From d39bb42f9aa74aca49278aac972a5e58a4f56e4a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 12 Sep 2018 21:26:50 -0400 Subject: [PATCH 0001/2212] Initial commit --- LICENSE | 201 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. From ed96c2b8e0f8d9fe4520db96d43ebffb42e33bba Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 12 Sep 2018 21:28:55 -0400 Subject: [PATCH 0002/2212] Transpiler skeleton and first bits of MSL support --- .gitignore | 4 +++ Cargo.toml | 11 ++++++++ examples/convert.rs | 19 +++++++++++++ src/lib.rs | 69 +++++++++++++++++++++++++++++++++++++++++++++ src/msl.rs | 30 ++++++++++++++++++++ 5 files changed, 133 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 examples/convert.rs create mode 100644 src/lib.rs create mode 100644 src/msl.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..fe42cc56d --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target +**/*.rs.bk +Cargo.lock +.DS_Store diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 000000000..f4f551467 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "javelin" +version = "0.1.0" +authors = ["Dzmitry Malyshau "] + +[dependencies] +rspirv = "0.5" +spirv_headers = "1" + +[dev-dependencies] +env_logger = "0.5" diff --git a/examples/convert.rs b/examples/convert.rs new file mode 100644 index 000000000..e0a4823c8 --- /dev/null +++ b/examples/convert.rs @@ -0,0 +1,19 @@ +extern crate env_logger; +extern crate javelin; + +use std::{env, fs}; + +fn main() { + env_logger::init(); + + let args = env::args().collect::>(); + let input = fs::read(&args[1]).unwrap(); + + let mut transpiler = javelin::Transpiler::new(); + let module = transpiler.load(&input).unwrap(); + + let options = javelin::msl::Options {}; + let msl = module.to_msl(&options).unwrap(); + println!("{}", msl); +} + diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 000000000..3ab2132be --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,69 @@ +extern crate rspirv; +extern crate spirv_headers; + +pub mod msl; + +use std::collections::HashMap; + + +pub struct Transpiler { +} + +pub struct Module { + raw: rspirv::mr::Module, + entry_points: HashMap, +} + +pub struct EntryPoint { + pub cleansed_name: String, + pub exec_model: spirv_headers::ExecutionModel, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum LoadError { + Parsing, +} + +impl Transpiler { + pub fn new() -> Self { + Transpiler { + } + } + + pub fn load(&mut self, spv: &[u8]) -> Result { + let mut loader = rspirv::mr::Loader::new(); + rspirv::binary::Parser::new(spv, &mut loader) + .parse() + .map_err(|_| LoadError::Parsing)?; + let raw = loader.module(); + + let entry_points = raw.entry_points + .iter() + .map(|ep| { + let name = match ep.operands[2] { + rspirv::mr::Operand::LiteralString(ref name) => name.to_string(), + ref other => panic!("Unexpected entry point operand {:?}", other), + }; + let ep = EntryPoint { + cleansed_name: name.clone(), //TODO + exec_model: match ep.operands[0] { + rspirv::mr::Operand::ExecutionModel(model) => model, + ref other => panic!("Unexpected execution model operand {:?}", other), + }, + }; + (name, ep) + }) + .collect(); + + Ok(Module { + raw, + entry_points, + }) + } +} + +impl Module { + pub fn entry_points(&self) -> &HashMap { + &self.entry_points + } +} diff --git a/src/msl.rs b/src/msl.rs new file mode 100644 index 000000000..b9e86a17c --- /dev/null +++ b/src/msl.rs @@ -0,0 +1,30 @@ +use std::fmt::{Error as FmtError, Write}; + +use Module; + + +pub struct Options { +} + +#[derive(Debug)] +pub enum Error { + Format(FmtError) +} + +impl From for Error { + fn from(e: FmtError) -> Self { + Error::Format(e) + } +} + +impl Module { + pub fn to_msl(&self, _options: &Options) -> Result { + let mut out = String::new(); + + writeln!(out, "#include ")?; + writeln!(out, "#include ")?; + writeln!(out, "using namespace metal;")?; + + Ok(out) + } +} From 99f160ebcec4a38e1aa9f0fa063e332c14b591d8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 18 Feb 2020 15:34:16 -0500 Subject: [PATCH 0003/2212] First bits of hand-written high-level representation --- Cargo.toml | 6 +- examples/convert.rs | 4 +- src/lib.rs | 145 ++++++++++++++++++++++++++---------------- src/msl.rs | 5 +- src/parse.rs | 60 ++++++++++++++++++ src/storage.rs | 149 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 306 insertions(+), 63 deletions(-) create mode 100644 src/parse.rs create mode 100644 src/storage.rs diff --git a/Cargo.toml b/Cargo.toml index f4f551467..9cbe44f15 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,10 +2,12 @@ name = "javelin" version = "0.1.0" authors = ["Dzmitry Malyshau "] +edition = "2018" [dependencies] -rspirv = "0.5" +log = "0.4" +smallvec = "1" spirv_headers = "1" [dev-dependencies] -env_logger = "0.5" +env_logger = "0.6" diff --git a/examples/convert.rs b/examples/convert.rs index e0a4823c8..195d47576 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -9,8 +9,8 @@ fn main() { let args = env::args().collect::>(); let input = fs::read(&args[1]).unwrap(); - let mut transpiler = javelin::Transpiler::new(); - let module = transpiler.load(&input).unwrap(); + let module = javelin::parse_u8_slice(&input).unwrap(); + //println!("{:?}", module); let options = javelin::msl::Options {}; let msl = module.to_msl(&options).unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 3ab2132be..9165bec25 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,69 +1,104 @@ -extern crate rspirv; -extern crate spirv_headers; +extern crate spirv_headers as spirv; pub mod msl; +mod parse; +mod storage; + +pub use parse::{parse, parse_u8_slice, ParseError}; + +use crate::storage::{Storage, Token}; use std::collections::HashMap; +use smallvec::SmallVec; -pub struct Transpiler { + + +#[derive(Debug)] +pub struct Header { + pub version: (u8, u8, u8), + pub generator: u32, } -pub struct Module { - raw: rspirv::mr::Module, - entry_points: HashMap, +pub type Bytes = u8; + +#[derive(Debug)] +pub struct StructDeclaration { + } +#[derive(Debug)] +pub enum Type { + Void, + Int { width: Bytes }, + Uint { width: Bytes }, + Float { width: Bytes }, + Struct(Token), +} + +#[derive(Debug)] +pub struct Jump { + pub target: Token, + pub arguments: SmallVec<[Token; 1]>, +} + +#[derive(Debug)] +pub enum Branch { + Jump(Jump), + JumpIf { + condition: Token, //bool + accept: Jump, + reject: Jump, + }, + Switch { + selector: Token, //int + cases: HashMap, + default: Jump, + }, + Return { + value: Option>, + }, +} + +#[derive(Debug)] +pub enum Operation { + Arithmetic, +} + +#[derive(Debug)] +pub enum Terminator { + Branch(Branch), + Kill, + Unreachable, +} + +#[derive(Debug)] +pub struct Block { + pub label: Option, + pub argument_types: Vec, + pub operations: Storage, + pub terminator: Terminator, +} + +#[derive(Debug)] +pub struct Function { + pub name: Option, + pub parameter_types: Vec, + pub return_type: Type, + pub blocks: Storage, +} + +#[derive(Debug)] pub struct EntryPoint { - pub cleansed_name: String, - pub exec_model: spirv_headers::ExecutionModel, + pub exec_model: spirv::ExecutionModel, + pub name: String, + pub function: Token, } -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum LoadError { - Parsing, -} - -impl Transpiler { - pub fn new() -> Self { - Transpiler { - } - } - - pub fn load(&mut self, spv: &[u8]) -> Result { - let mut loader = rspirv::mr::Loader::new(); - rspirv::binary::Parser::new(spv, &mut loader) - .parse() - .map_err(|_| LoadError::Parsing)?; - let raw = loader.module(); - - let entry_points = raw.entry_points - .iter() - .map(|ep| { - let name = match ep.operands[2] { - rspirv::mr::Operand::LiteralString(ref name) => name.to_string(), - ref other => panic!("Unexpected entry point operand {:?}", other), - }; - let ep = EntryPoint { - cleansed_name: name.clone(), //TODO - exec_model: match ep.operands[0] { - rspirv::mr::Operand::ExecutionModel(model) => model, - ref other => panic!("Unexpected execution model operand {:?}", other), - }, - }; - (name, ep) - }) - .collect(); - - Ok(Module { - raw, - entry_points, - }) - } -} - -impl Module { - pub fn entry_points(&self) -> &HashMap { - &self.entry_points - } +#[derive(Debug)] +pub struct Module { + pub header: Header, + pub struct_declarations: Storage, + pub functions: Storage, + pub entry_points: Vec, } diff --git a/src/msl.rs b/src/msl.rs index b9e86a17c..3da8c6ce5 100644 --- a/src/msl.rs +++ b/src/msl.rs @@ -1,8 +1,5 @@ use std::fmt::{Error as FmtError, Write}; -use Module; - - pub struct Options { } @@ -17,7 +14,7 @@ impl From for Error { } } -impl Module { +impl super::Module { pub fn to_msl(&self, _options: &Options) -> Result { let mut out = String::new(); diff --git a/src/parse.rs b/src/parse.rs new file mode 100644 index 000000000..08e482c18 --- /dev/null +++ b/src/parse.rs @@ -0,0 +1,60 @@ +use crate::storage::Storage; + +#[derive(Debug)] +pub enum ParseError { + InvalidHeader, + UnknownInstruction, + IncompleteData, +} + +pub fn parse(mut data: impl Iterator) -> Result { + let header = { + if data.next().ok_or(ParseError::IncompleteData)? != spirv::MAGIC_NUMBER { + return Err(ParseError::InvalidHeader); + } + let version_raw = data.next().ok_or(ParseError::IncompleteData)?.to_le_bytes(); + super::Header { + version: (version_raw[2], version_raw[1], version_raw[0]), + generator: 0, + } + }; + Ok(super::Module { + header, + struct_declarations: Storage::new(), + functions: Storage::new(), + entry_points: Vec::new(), + }) +} + +pub fn parse_u8_slice(data: &[u8]) -> Result { + use std::convert::TryInto; + + if data.len() % 4 != 0 { + return Err(ParseError::IncompleteData); + } + + parse(data + .chunks(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap())) + ) +} + +#[cfg(test)] +mod test { + #[test] + fn parse() { + let bin = vec![ + // Magic number. Version number: 1.0. + 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, + // Generator number: 0. Bound: 0. + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Reserved word: 0. + 0x00, 0x00, 0x00, 0x00, + // OpMemoryModel. Logical. + 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, + // GLSL450. + 0x01, 0x00, 0x00, 0x00, + ]; + let _ = super::parse_u8_slice(&bin).unwrap(); + } +} diff --git a/src/storage.rs b/src/storage.rs new file mode 100644 index 000000000..8142b75cf --- /dev/null +++ b/src/storage.rs @@ -0,0 +1,149 @@ +use std::{ + fmt, + marker::PhantomData, +}; + +/// An unique index in the storage array that a token points to. +/// +/// This type is independent of `spirv::Word`. `spirv::Word` is used in data +/// representation. It holds a SPIR-V and refers to that instruction. In +/// structured representation, we use Token to refer to an SPIR-V instruction. +/// Index is an implementation detail to Token. +type Index = u32; + +/// A strongly typed reference to a SPIR-V element. +pub struct Token { + index: Index, + marker: PhantomData, +} + +impl Clone for Token { + fn clone(&self) -> Self { + Token { + index: self.index, + marker: self.marker, + } + } +} +impl Copy for Token {} +impl PartialEq for Token { + fn eq(&self, other: &Self) -> bool { + self.index == other.index + } +} +impl Eq for Token {} +impl fmt::Debug for Token { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "Token({})", self.index) + } +} + +impl Token { + #[cfg(test)] + pub const DUMMY: Self = Token { + index: !0, + marker: PhantomData, + }; + + pub(crate) fn new(index: Index) -> Self { + Token { + index, + marker: PhantomData, + } + } + + pub fn index(&self) -> usize { + self.index as usize + } +} + +/// A structure holding some kind of SPIR-V entity (e.g., type, constant, +/// instruction, etc.) that can be referenced. +#[derive(Debug)] +pub struct Storage { + /// Values of this storage. + data: Vec, +} + +impl Storage { + pub fn new() -> Self { + Storage { + data: Vec::new(), + } + } + + pub fn iter<'a>(&'a self) -> impl Iterator, &'a T)> { + self.data + .iter() + .enumerate() + .map(|(i, v)| (Token::new(i as Index), v)) + } + + /// Adds a new value to the storage, returning a typed token. + /// + /// The value is not linked to any SPIR-V module. + pub fn append(&mut self, value: T) -> Token { + let index = self.data.len() as Index; + self.data.push(value); + Token::new(index) + } + + /// Adds a value with a check for uniqueness: returns a token pointing to + /// an existing element if its value matches the given one, or adds a new + /// element otherwise. + pub fn fetch_or_append(&mut self, value: T) -> Token where T: PartialEq { + if let Some(index) = self.data.iter().position(|d| d == &value) { + Token::new(index as Index) + } else { + self.append(value) + } + } +} + +impl std::ops::Index> for Storage { + type Output = T; + fn index(&self, token: Token) -> &T { + &self.data[token.index as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn append_non_unique() { + let mut storage: Storage = Storage::new(); + let t1 = storage.append(0.0); + let t2 = storage.append(0.0); + assert!(t1 != t2); + assert!(storage[t1] == storage[t2]); + } + + #[test] + fn append_unique() { + let mut storage: Storage = Storage::new(); + let t1 = storage.append(std::f64::NAN); + let t2 = storage.append(std::f64::NAN); + assert!(t1 != t2); + assert!(storage[t1] != storage[t2]); + } + + #[test] + fn fetch_or_append_non_unique() { + let mut storage: Storage = Storage::new(); + let t1 = storage.fetch_or_append(0.0); + let t2 = storage.fetch_or_append(0.0); + assert!(t1 == t2); + assert!(storage[t1] == storage[t2]) + } + + #[test] + fn fetch_or_append_unique() { + let mut storage: Storage = Storage::new(); + let t1 = storage.fetch_or_append(std::f64::NAN); + let t2 = storage.fetch_or_append(std::f64::NAN); + assert!(t1 != t2); + assert!(storage[t1] != storage[t2]); + } +} From f6912acdbd546c021412fb79f26da7f61ea2d9a8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 18 Feb 2020 17:27:12 -0500 Subject: [PATCH 0004/2212] Add parsing states --- src/lib.rs | 2 +- src/parse.rs | 140 ++++++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 123 insertions(+), 19 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9165bec25..ec39a4bf6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,7 +4,7 @@ pub mod msl; mod parse; mod storage; -pub use parse::{parse, parse_u8_slice, ParseError}; +pub use parse::{Parser, ParseError, parse_u8_slice}; use crate::storage::{Storage, Token}; diff --git a/src/parse.rs b/src/parse.rs index 08e482c18..77ed9d798 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -3,27 +3,131 @@ use crate::storage::Storage; #[derive(Debug)] pub enum ParseError { InvalidHeader, + InvalidWordCount, + UnexpectedInstruction(ModuleState, spirv::Op), UnknownInstruction, + InvalidOperandCount(spirv::Op, u16), IncompleteData, } -pub fn parse(mut data: impl Iterator) -> Result { - let header = { - if data.next().ok_or(ParseError::IncompleteData)? != spirv::MAGIC_NUMBER { - return Err(ParseError::InvalidHeader); +struct Instruction { + op: spirv::Op, + wc: u16, +} + +impl Instruction { + fn expect(&self, count: u16) -> Result<(), ParseError> { + if self.wc == count { + Ok(()) + } else { + Err(ParseError::InvalidOperandCount(self.op, self.wc)) } - let version_raw = data.next().ok_or(ParseError::IncompleteData)?.to_le_bytes(); - super::Header { - version: (version_raw[2], version_raw[1], version_raw[0]), - generator: 0, + } +} + +#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] +pub enum ModuleState { + Empty, + Capability, + Extension, + ExtInstImport, + MemoryModel, + EntryPoint, + ExecutionMode, + Source, + Name, + ModuleProcessed, + Annotation, + Type, + FunctionDecl, + FunctionDef, +} + +pub struct Parser { + data: I, + state: ModuleState, +} + +impl> Parser { + pub fn new(data: I) -> Self { + Parser { + data, + state: ModuleState::Empty, } - }; - Ok(super::Module { - header, - struct_declarations: Storage::new(), - functions: Storage::new(), - entry_points: Vec::new(), - }) + } + + fn next(&mut self) -> Result { + self.data.next().ok_or(ParseError::IncompleteData) + } + + fn next_inst(&mut self) -> Result { + const LAST_KNOWN_OPCODE: spirv::Op = spirv::Op::MemberDecorateStringGOOGLE; + + let word = self.next()?; + let (wc, opcode) = ((word >> 16) as u16, (word & 0xffff) as u16); + if wc == 0 { + return Err(ParseError::InvalidWordCount); + } + if opcode > LAST_KNOWN_OPCODE as u16 { + return Err(ParseError::UnknownInstruction); + } + + Ok(Instruction { + op: unsafe { + std::mem::transmute(opcode as u32) + }, + wc, + }) + } + + fn switch(&mut self, state: ModuleState, inst: &Instruction, word_count: u16) -> Result<(), ParseError> { + if state < self.state { + return Err(ParseError::UnexpectedInstruction(self.state, inst.op)) + } else { + self.state = state; + inst.expect(word_count) + } + } + + pub fn parse(&mut self) -> Result { + let header = { + if self.next()? != spirv::MAGIC_NUMBER { + return Err(ParseError::InvalidHeader); + } + let version_raw = self.next()?.to_le_bytes(); + let generator = self.next()?; + let _bound = self.next()?; + let _schema = self.next()?; + super::Header { + version: (version_raw[2], version_raw[1], version_raw[0]), + generator, + } + }; + + while let Ok(inst) = self.next_inst() { + use spirv::Op; + match inst.op { + Op::Capability => { + self.switch(ModuleState::Capability, &inst, 2)?; + let _capability = self.next()?; + } + Op::MemoryModel => { + self.switch(ModuleState::MemoryModel, &inst, 3)?; + let _addressing_model = self.next()?; + let _memory_model = self.next()?; + }, + _ => return Err(ParseError::UnexpectedInstruction(self.state, inst.op)) + //TODO + } + } + + Ok(super::Module { + header, + struct_declarations: Storage::new(), + functions: Storage::new(), + entry_points: Vec::new(), + }) + } } pub fn parse_u8_slice(data: &[u8]) -> Result { @@ -33,10 +137,10 @@ pub fn parse_u8_slice(data: &[u8]) -> Result { return Err(ParseError::IncompleteData); } - parse(data + let words = data .chunks(4) - .map(|c| u32::from_le_bytes(c.try_into().unwrap())) - ) + .map(|c| u32::from_le_bytes(c.try_into().unwrap())); + Parser::new(words).parse() } #[cfg(test)] From 8a945c79c802673e6ee94197dc170c1e066c8512 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 18 Feb 2020 23:20:03 -0500 Subject: [PATCH 0005/2212] Parsing names and entry points --- Cargo.toml | 1 + src/parse.rs | 190 +++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 176 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9cbe44f15..411e70f6f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ authors = ["Dzmitry Malyshau "] edition = "2018" [dependencies] +fxhash = "0.2" log = "0.4" smallvec = "1" spirv_headers = "1" diff --git a/src/parse.rs b/src/parse.rs index 77ed9d798..eb67b1cf5 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -1,12 +1,38 @@ -use crate::storage::Storage; +use crate::storage::{Storage, Token}; + +use std::{ + collections::HashMap, + hash::BuildHasherDefault, +}; + +const LAST_KNOWN_OPCODE: spirv::Op = spirv::Op::MemberDecorateStringGOOGLE; +const LAST_KNOWN_CAPABILITY: spirv::Capability = spirv::Capability::VulkanMemoryModelDeviceScopeKHR; +const LAST_KNOWN_EXEC_MODEL: spirv::ExecutionModel = spirv::ExecutionModel::Kernel; + +pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ + spirv::Capability::Shader, +]; +pub const SUPPORTED_EXTENSIONS: &[&str] = &[ +]; +pub const SUPPORTED_EXT_SETS: &[&str] = &[ + "GLSL.std.450", +]; #[derive(Debug)] pub enum ParseError { InvalidHeader, InvalidWordCount, - UnexpectedInstruction(ModuleState, spirv::Op), - UnknownInstruction, + UnknownInstruction(u16), + UnsupportedInstruction(ModuleState, spirv::Op), + UnknownCapability(u32), + UnsupportedCapability(spirv::Capability), + UnsupportedExtension(String), + UnsupportedExtSet(String), + UnsupportedExecModel(u32), InvalidOperandCount(spirv::Op, u16), + InvalidOperand, + InvalidId(spirv::Word), + BadString, IncompleteData, } @@ -43,9 +69,30 @@ pub enum ModuleState { FunctionDef, } +trait Lookup { + type Target; + fn lookup(&self, key: spirv::Word) -> Result<&Self::Target, ParseError>; +} + +type FastHashMap = HashMap>; + +impl Lookup for FastHashMap { + type Target = T; + fn lookup(&self, key: spirv::Word) -> Result<&T, ParseError> { + self.get(&key) + .ok_or(ParseError::InvalidId(key)) + } +} + +type MemberIndex = u32; + pub struct Parser { data: I, state: ModuleState, + temp_bytes: Vec, + future_names: FastHashMap, + future_member_names: FastHashMap<(spirv::Word, MemberIndex), String>, + lookup_function: FastHashMap>, } impl> Parser { @@ -53,6 +100,10 @@ impl> Parser { Parser { data, state: ModuleState::Empty, + temp_bytes: Vec::new(), + future_names: HashMap::default(), + future_member_names: HashMap::default(), + lookup_function: HashMap::default(), } } @@ -61,15 +112,13 @@ impl> Parser { } fn next_inst(&mut self) -> Result { - const LAST_KNOWN_OPCODE: spirv::Op = spirv::Op::MemberDecorateStringGOOGLE; - let word = self.next()?; let (wc, opcode) = ((word >> 16) as u16, (word & 0xffff) as u16); if wc == 0 { return Err(ParseError::InvalidWordCount); } if opcode > LAST_KNOWN_OPCODE as u16 { - return Err(ParseError::UnknownInstruction); + return Err(ParseError::UnknownInstruction(opcode)); } Ok(Instruction { @@ -80,12 +129,31 @@ impl> Parser { }) } - fn switch(&mut self, state: ModuleState, inst: &Instruction, word_count: u16) -> Result<(), ParseError> { + fn next_string(&mut self, mut count: u16) -> Result<(String, u16), ParseError>{ + self.temp_bytes.clear(); + loop { + if count == 0 { + return Err(ParseError::BadString); + } + count -= 1; + let chars = self.next()?.to_le_bytes(); + let pos = chars.iter().position(|&c| c == 0).unwrap_or(4); + self.temp_bytes.extend_from_slice(&chars[.. pos]); + if pos < 4 { + break + } + } + std::str::from_utf8(&self.temp_bytes) + .map(|s| (s.to_owned(), count)) + .map_err(|_| ParseError::BadString) + } + + fn switch(&mut self, state: ModuleState, op: spirv::Op) -> Result<(), ParseError> { if state < self.state { - return Err(ParseError::UnexpectedInstruction(self.state, inst.op)) + return Err(ParseError::UnsupportedInstruction(self.state, op)) } else { self.state = state; - inst.expect(word_count) + Ok(()) } } @@ -103,29 +171,121 @@ impl> Parser { generator, } }; + let mut raw_entry_points = Vec::new(); while let Ok(inst) = self.next_inst() { use spirv::Op; match inst.op { Op::Capability => { - self.switch(ModuleState::Capability, &inst, 2)?; - let _capability = self.next()?; + self.switch(ModuleState::Capability, inst.op)?; + inst.expect(2)?; + let capability = self.next()?; + if capability > LAST_KNOWN_CAPABILITY as u32 { + return Err(ParseError::UnknownCapability(capability)); + } + let cap = unsafe { + std::mem::transmute(capability) + }; + if !SUPPORTED_CAPABILITIES.contains(&cap) { + return Err(ParseError::UnsupportedCapability(cap)); + } + } + Op::Extension => { + self.switch(ModuleState::Extension, inst.op)?; + let (name, left) = self.next_string(inst.wc - 1)?; + if left != 0 { + return Err(ParseError::InvalidOperand); + } + if !SUPPORTED_EXTENSIONS.contains(&name.as_str()) { + return Err(ParseError::UnsupportedExtension(name.to_owned())); + } + } + Op::ExtInstImport => { + self.switch(ModuleState::Extension, inst.op)?; + let _result = self.next()?; + let (name, left) = self.next_string(inst.wc - 2)?; + if left != 0 { + return Err(ParseError::InvalidOperand) + } + if !SUPPORTED_EXT_SETS.contains(&name.as_str()) { + return Err(ParseError::UnsupportedExtSet(name.to_owned())); + } } Op::MemoryModel => { - self.switch(ModuleState::MemoryModel, &inst, 3)?; + self.switch(ModuleState::MemoryModel, inst.op)?; + inst.expect(3)?; let _addressing_model = self.next()?; let _memory_model = self.next()?; - }, - _ => return Err(ParseError::UnexpectedInstruction(self.state, inst.op)) + } + Op::EntryPoint => { + self.switch(ModuleState::EntryPoint, inst.op)?; + let exec_model = self.next()?; + if exec_model > LAST_KNOWN_EXEC_MODEL as u32 { + return Err(ParseError::UnsupportedExecModel(exec_model)); + } + let function_id = self.next()?; + let (name, left) = self.next_string(inst.wc - 3)?; + for _ in 0 .. left { + let _var = self.next()?; //TODO + } + raw_entry_points.push(( + unsafe { + std::mem::transmute(exec_model) + }, + name.to_owned(), + function_id, + )); + } + Op::Source => { + self.switch(ModuleState::Source, inst.op)?; + for _ in 1 .. inst.wc { + let _ = self.next()?; + } + } + Op::Name => { + self.switch(ModuleState::Name, inst.op)?; + if inst.wc < 3 { + return Err(ParseError::InvalidOperandCount(inst.op, inst.wc)); + } + let id = self.next()?; + let (name, left) = self.next_string(inst.wc - 2)?; + if left != 0 { + return Err(ParseError::InvalidOperand); + } + self.future_names.insert(id, name.to_owned()); + } + Op::MemberName => { + self.switch(ModuleState::Name, inst.op)?; + if inst.wc < 4 { + return Err(ParseError::InvalidOperandCount(inst.op, inst.wc)); + } + let id = self.next()?; + let member = self.next()?; + let (name, left) = self.next_string(inst.wc - 3)?; + if left != 0 { + return Err(ParseError::InvalidOperand); + } + self.future_member_names.insert((id, member), name.to_owned()); + } + _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)) //TODO } } + let mut entry_points = Vec::with_capacity(raw_entry_points.len()); + for (exec_model, name, fun_id) in raw_entry_points { + entry_points.push(super::EntryPoint { + exec_model, + name, + function: *self.lookup_function.lookup(fun_id)?, + }); + } + Ok(super::Module { header, struct_declarations: Storage::new(), functions: Storage::new(), - entry_points: Vec::new(), + entry_points, }) } } From 0e38eef82de7c7d8db4d2bf68637aba9bd6448b7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 21 Feb 2020 08:23:44 -0500 Subject: [PATCH 0006/2212] Restructure the project with frontends and backends --- examples/convert.rs | 4 +- src/back/mod.rs | 1 + src/{ => back}/msl.rs | 2 +- src/front/mod.rs | 1 + src/{parse.rs => front/spirv.rs} | 28 ++++++------- src/lib.rs | 69 +++++++++++++------------------- 6 files changed, 45 insertions(+), 60 deletions(-) create mode 100644 src/back/mod.rs rename src/{ => back}/msl.rs (96%) create mode 100644 src/front/mod.rs rename src/{parse.rs => front/spirv.rs} (94%) diff --git a/examples/convert.rs b/examples/convert.rs index 195d47576..ccf085393 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -9,10 +9,10 @@ fn main() { let args = env::args().collect::>(); let input = fs::read(&args[1]).unwrap(); - let module = javelin::parse_u8_slice(&input).unwrap(); + let module = javelin::front::spirv::parse_u8_slice(&input).unwrap(); //println!("{:?}", module); - let options = javelin::msl::Options {}; + let options = javelin::back::msl::Options {}; let msl = module.to_msl(&options).unwrap(); println!("{}", msl); } diff --git a/src/back/mod.rs b/src/back/mod.rs new file mode 100644 index 000000000..f4f1fce17 --- /dev/null +++ b/src/back/mod.rs @@ -0,0 +1 @@ +pub mod msl; \ No newline at end of file diff --git a/src/msl.rs b/src/back/msl.rs similarity index 96% rename from src/msl.rs rename to src/back/msl.rs index 3da8c6ce5..959f1558a 100644 --- a/src/msl.rs +++ b/src/back/msl.rs @@ -14,7 +14,7 @@ impl From for Error { } } -impl super::Module { +impl crate::Module { pub fn to_msl(&self, _options: &Options) -> Result { let mut out = String::new(); diff --git a/src/front/mod.rs b/src/front/mod.rs new file mode 100644 index 000000000..e4919e773 --- /dev/null +++ b/src/front/mod.rs @@ -0,0 +1 @@ +pub mod spirv; diff --git a/src/parse.rs b/src/front/spirv.rs similarity index 94% rename from src/parse.rs rename to src/front/spirv.rs index eb67b1cf5..cb95e2893 100644 --- a/src/parse.rs +++ b/src/front/spirv.rs @@ -1,8 +1,6 @@ -use crate::storage::{Storage, Token}; - -use std::{ - collections::HashMap, - hash::BuildHasherDefault, +use crate::{ + storage::{Storage, Token}, + FastHashMap, }; const LAST_KNOWN_OPCODE: spirv::Op = spirv::Op::MemberDecorateStringGOOGLE; @@ -74,8 +72,6 @@ trait Lookup { fn lookup(&self, key: spirv::Word) -> Result<&Self::Target, ParseError>; } -type FastHashMap = HashMap>; - impl Lookup for FastHashMap { type Target = T; fn lookup(&self, key: spirv::Word) -> Result<&T, ParseError> { @@ -92,7 +88,7 @@ pub struct Parser { temp_bytes: Vec, future_names: FastHashMap, future_member_names: FastHashMap<(spirv::Word, MemberIndex), String>, - lookup_function: FastHashMap>, + lookup_function: FastHashMap>, } impl> Parser { @@ -101,9 +97,9 @@ impl> Parser { data, state: ModuleState::Empty, temp_bytes: Vec::new(), - future_names: HashMap::default(), - future_member_names: HashMap::default(), - lookup_function: HashMap::default(), + future_names: FastHashMap::default(), + future_member_names: FastHashMap::default(), + lookup_function: FastHashMap::default(), } } @@ -157,7 +153,7 @@ impl> Parser { } } - pub fn parse(&mut self) -> Result { + pub fn parse(&mut self) -> Result { let header = { if self.next()? != spirv::MAGIC_NUMBER { return Err(ParseError::InvalidHeader); @@ -166,7 +162,7 @@ impl> Parser { let generator = self.next()?; let _bound = self.next()?; let _schema = self.next()?; - super::Header { + crate::Header { version: (version_raw[2], version_raw[1], version_raw[0]), generator, } @@ -274,14 +270,14 @@ impl> Parser { let mut entry_points = Vec::with_capacity(raw_entry_points.len()); for (exec_model, name, fun_id) in raw_entry_points { - entry_points.push(super::EntryPoint { + entry_points.push(crate::EntryPoint { exec_model, name, function: *self.lookup_function.lookup(fun_id)?, }); } - Ok(super::Module { + Ok(crate::Module { header, struct_declarations: Storage::new(), functions: Storage::new(), @@ -290,7 +286,7 @@ impl> Parser { } } -pub fn parse_u8_slice(data: &[u8]) -> Result { +pub fn parse_u8_slice(data: &[u8]) -> Result { use std::convert::TryInto; if data.len() % 4 != 0 { diff --git a/src/lib.rs b/src/lib.rs index ec39a4bf6..d6e6d674e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,16 +1,18 @@ extern crate spirv_headers as spirv; -pub mod msl; -mod parse; +pub mod back; +pub mod front; mod storage; -pub use parse::{Parser, ParseError, parse_u8_slice}; use crate::storage::{Storage, Token}; -use std::collections::HashMap; +use std::{ + collections::HashMap, + hash::BuildHasherDefault, +}; -use smallvec::SmallVec; +type FastHashMap = HashMap>; @@ -37,47 +39,32 @@ pub enum Type { } #[derive(Debug)] -pub struct Jump { - pub target: Token, - pub arguments: SmallVec<[Token; 1]>, -} - -#[derive(Debug)] -pub enum Branch { - Jump(Jump), - JumpIf { - condition: Token, //bool - accept: Jump, - reject: Jump, - }, - Switch { - selector: Token, //int - cases: HashMap, - default: Jump, - }, - Return { - value: Option>, - }, -} - -#[derive(Debug)] -pub enum Operation { +pub enum Expression { Arithmetic, } +pub type Block = Vec; #[derive(Debug)] -pub enum Terminator { - Branch(Branch), - Kill, - Unreachable, -} +pub struct FallThrough; #[derive(Debug)] -pub struct Block { - pub label: Option, - pub argument_types: Vec, - pub operations: Storage, - pub terminator: Terminator, +pub enum Statement { + Expression(Expression), + Block(Block), + If { + condition: Expression, //bool + accept: Block, + reject: Block, + }, + Switch { + selector: Expression, //int + cases: FastHashMap)>, + default: Block, + }, + Return { + value: Option, + }, + Kill, } #[derive(Debug)] @@ -85,7 +72,7 @@ pub struct Function { pub name: Option, pub parameter_types: Vec, pub return_type: Type, - pub blocks: Storage, + pub body: Block, } #[derive(Debug)] From 54924e5f6695498ac911514c1e2cb32f0ac00ec5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 21 Feb 2020 10:45:03 -0500 Subject: [PATCH 0007/2212] Parse basic types from SPIRV --- src/front/spirv.rs | 155 ++++++++++++++++++++++++++++++++++++++++----- src/lib.rs | 23 +++++-- 2 files changed, 159 insertions(+), 19 deletions(-) diff --git a/src/front/spirv.rs b/src/front/spirv.rs index cb95e2893..297280896 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -3,6 +3,8 @@ use crate::{ FastHashMap, }; +use std::convert::TryInto; + const LAST_KNOWN_OPCODE: spirv::Op = spirv::Op::MemberDecorateStringGOOGLE; const LAST_KNOWN_CAPABILITY: spirv::Capability = spirv::Capability::VulkanMemoryModelDeviceScopeKHR; const LAST_KNOWN_EXEC_MODEL: spirv::ExecutionModel = spirv::ExecutionModel::Kernel; @@ -30,6 +32,10 @@ pub enum ParseError { InvalidOperandCount(spirv::Op, u16), InvalidOperand, InvalidId(spirv::Word), + InvalidTypeWidth(spirv::Word), + InvalidSign(spirv::Word), + InvalidScalar(spirv::Word), + InvalidVectorSize(spirv::Word), BadString, IncompleteData, } @@ -47,6 +53,14 @@ impl Instruction { Err(ParseError::InvalidOperandCount(self.op, self.wc)) } } + + fn expect_at_least(&self, count: u16) -> Result<(), ParseError> { + if self.wc >= count { + Ok(()) + } else { + Err(ParseError::InvalidOperandCount(self.op, self.wc)) + } + } } #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] @@ -80,14 +94,34 @@ impl Lookup for FastHashMap { } } +fn map_vector_size(word: spirv::Word) -> Result { + match word { + 2 => Ok(crate::VectorSize::Bi), + 3 => Ok(crate::VectorSize::Tri), + 4 => Ok(crate::VectorSize::Quad), + _ => Err(ParseError::InvalidVectorSize(word)) + } +} + type MemberIndex = u32; +#[derive(Debug, Default)] +struct Decoration { + name: Option, +} + +#[derive(Debug, Default)] +struct MemberDecoration { + name: Option, +} + pub struct Parser { data: I, state: ModuleState, temp_bytes: Vec, - future_names: FastHashMap, - future_member_names: FastHashMap<(spirv::Word, MemberIndex), String>, + future_decor: FastHashMap, + future_member_decor: FastHashMap<(spirv::Word, MemberIndex), MemberDecoration>, + lookup_type: FastHashMap, lookup_function: FastHashMap>, } @@ -97,8 +131,9 @@ impl> Parser { data, state: ModuleState::Empty, temp_bytes: Vec::new(), - future_names: FastHashMap::default(), - future_member_names: FastHashMap::default(), + future_decor: FastHashMap::default(), + future_member_decor: FastHashMap::default(), + lookup_type: FastHashMap::default(), lookup_function: FastHashMap::default(), } } @@ -168,6 +203,7 @@ impl> Parser { } }; let mut raw_entry_points = Vec::new(); + let mut functions = Storage::new(); while let Ok(inst) = self.next_inst() { use spirv::Op; @@ -240,28 +276,119 @@ impl> Parser { } Op::Name => { self.switch(ModuleState::Name, inst.op)?; - if inst.wc < 3 { - return Err(ParseError::InvalidOperandCount(inst.op, inst.wc)); - } + inst.expect_at_least(3)?; let id = self.next()?; let (name, left) = self.next_string(inst.wc - 2)?; if left != 0 { return Err(ParseError::InvalidOperand); } - self.future_names.insert(id, name.to_owned()); + self.future_decor + .entry(id) + .or_default() + .name = Some(name.to_owned()); } Op::MemberName => { self.switch(ModuleState::Name, inst.op)?; - if inst.wc < 4 { - return Err(ParseError::InvalidOperandCount(inst.op, inst.wc)); - } + inst.expect_at_least(4)?; let id = self.next()?; let member = self.next()?; let (name, left) = self.next_string(inst.wc - 3)?; if left != 0 { return Err(ParseError::InvalidOperand); } - self.future_member_names.insert((id, member), name.to_owned()); + self.future_member_decor + .entry((id, member)) + .or_default() + .name = Some(name.to_owned()); + } + Op::Decorate => { + self.switch(ModuleState::Annotation, inst.op)?; + inst.expect_at_least(3)?; + let _id = self.next()?; + let _decoration = self.next()?; + for _ in 3 .. inst.wc { + let _var = self.next()?; //TODO + } + } + Op::MemberDecorate => { + self.switch(ModuleState::Annotation, inst.op)?; + inst.expect_at_least(4)?; + let _id = self.next()?; + let _member = self.next()?; + let _decoration = self.next()?; + for _ in 4 .. inst.wc { + let _var = self.next()?; //TODO + } + } + Op::TypeVoid => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(2)?; + let id = self.next()?; + self.lookup_type.insert(id, crate::Type::Void); + } + Op::TypeInt => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let width = self.next()?; + let sign = self.next()?; + self.lookup_type.insert(id, crate::Type::Scalar { + kind: match sign { + 0 => crate::ScalarKind::Uint, + 1 => crate::ScalarKind::Sint, + _ => return Err(ParseError::InvalidSign(sign)), + }, + width: width + .try_into() + .map_err(|_| ParseError::InvalidTypeWidth(width))?, + }); + } + Op::TypeFloat => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(3)?; + let id = self.next()?; + let width = self.next()?; + self.lookup_type.insert(id, crate::Type::Scalar { + kind: crate::ScalarKind::Float, + width: width + .try_into() + .map_err(|_| ParseError::InvalidTypeWidth(width))?, + }); + } + Op::TypeVector => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let type_id = self.next()?; + let (kind, width) = match self.lookup_type.lookup(type_id)? { + &crate::Type::Scalar { ref kind, width } => (kind.clone(), width), + _ => return Err(ParseError::InvalidScalar(type_id)), + }; + let component_count = self.next()?; + self.lookup_type.insert(id, crate::Type::Vector { + size: map_vector_size(component_count)?, + kind, + width, + }); + } + Op::TypeFunction => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(3)?; + let id = self.next()?; + let ret_type_id = self.next()?; + let mut parameter_types = Vec::new(); + for _ in 3 .. inst.wc { + let type_id = self.next()?; + let ty = self.lookup_type.lookup(type_id)?.clone(); + parameter_types.push(ty); + } + let token = functions.append(crate::Function { + name: None, + return_type: self.lookup_type.lookup(ret_type_id)?.clone(), + parameter_types, + body: Vec::new(), + }); + self.lookup_function.insert(id, token); } _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)) //TODO @@ -280,15 +407,13 @@ impl> Parser { Ok(crate::Module { header, struct_declarations: Storage::new(), - functions: Storage::new(), + functions, entry_points, }) } } pub fn parse_u8_slice(data: &[u8]) -> Result { - use std::convert::TryInto; - if data.len() % 4 != 0 { return Err(ParseError::IncompleteData); } diff --git a/src/lib.rs b/src/lib.rs index d6e6d674e..9d709f617 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,17 +24,32 @@ pub struct Header { pub type Bytes = u8; +#[repr(u8)] +#[derive(Clone, Debug)] +pub enum VectorSize { + Bi = 2, + Tri = 3, + Quad = 4, +} + +#[repr(u8)] +#[derive(Clone, Debug)] +pub enum ScalarKind { + Sint, + Uint, + Float, +} + #[derive(Debug)] pub struct StructDeclaration { } -#[derive(Debug)] +#[derive(Clone, Debug)] pub enum Type { Void, - Int { width: Bytes }, - Uint { width: Bytes }, - Float { width: Bytes }, + Scalar { kind: ScalarKind, width: Bytes }, + Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, Struct(Token), } From 2c16742d1bf53e118fe5f15af3fb71602cb06c6f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 21 Feb 2020 14:02:21 -0500 Subject: [PATCH 0008/2212] Parse SPIR-V arrays, structs, and constants --- src/front/spirv.rs | 145 ++++++++++++++++++++++++++++++++++++++------- src/lib.rs | 25 +++++++- 2 files changed, 146 insertions(+), 24 deletions(-) diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 297280896..16a84ca30 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -28,6 +28,7 @@ pub enum ParseError { UnsupportedCapability(spirv::Capability), UnsupportedExtension(String), UnsupportedExtSet(String), + UnsupportedType(crate::Type), UnsupportedExecModel(u32), InvalidOperandCount(spirv::Op, u16), InvalidOperand, @@ -122,6 +123,7 @@ pub struct Parser { future_decor: FastHashMap, future_member_decor: FastHashMap<(spirv::Word, MemberIndex), MemberDecoration>, lookup_type: FastHashMap, + lookup_constant: FastHashMap, lookup_function: FastHashMap>, } @@ -134,6 +136,7 @@ impl> Parser { future_decor: FastHashMap::default(), future_member_decor: FastHashMap::default(), lookup_type: FastHashMap::default(), + lookup_constant: FastHashMap::default(), lookup_function: FastHashMap::default(), } } @@ -189,21 +192,26 @@ impl> Parser { } pub fn parse(&mut self) -> Result { - let header = { - if self.next()? != spirv::MAGIC_NUMBER { - return Err(ParseError::InvalidHeader); - } - let version_raw = self.next()?.to_le_bytes(); - let generator = self.next()?; - let _bound = self.next()?; - let _schema = self.next()?; - crate::Header { - version: (version_raw[2], version_raw[1], version_raw[0]), - generator, - } + let mut module = crate::Module { + header: { + if self.next()? != spirv::MAGIC_NUMBER { + return Err(ParseError::InvalidHeader); + } + let version_raw = self.next()?.to_le_bytes(); + let generator = self.next()?; + let _bound = self.next()?; + let _schema = self.next()?; + crate::Header { + version: (version_raw[2], version_raw[1], version_raw[0]), + generator, + } + }, + array_declarations: Storage::new(), + struct_declarations: Storage::new(), + functions: Storage::new(), + entry_points: Vec::new(), }; let mut raw_entry_points = Vec::new(); - let mut functions = Storage::new(); while let Ok(inst) = self.next_inst() { use spirv::Op; @@ -258,7 +266,7 @@ impl> Parser { let function_id = self.next()?; let (name, left) = self.next_string(inst.wc - 3)?; for _ in 0 .. left { - let _var = self.next()?; //TODO + let _var = self.next()?; //TODO: in/out variables } raw_entry_points.push(( unsafe { @@ -382,7 +390,7 @@ impl> Parser { let ty = self.lookup_type.lookup(type_id)?.clone(); parameter_types.push(ty); } - let token = functions.append(crate::Function { + let token = module.functions.append(crate::Function { name: None, return_type: self.lookup_type.lookup(ret_type_id)?.clone(), parameter_types, @@ -390,26 +398,117 @@ impl> Parser { }); self.lookup_function.insert(id, token); } + Op::TypeArray => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let type_id = self.next()?; + let length = self.next()?; + let decl = crate::ArrayDeclaration { + base: self.lookup_type.lookup(type_id)?.clone(), + length, + }; + let ty = crate::Type::Array(module.array_declarations.append(decl)); + self.lookup_type.insert(id, ty); + } + Op::TypeStruct => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(2)?; + let id = self.next()?; + let mut decl = crate::StructDeclaration { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + members: Vec::with_capacity(inst.wc as usize - 2), + }; + for i in 0 .. inst.wc as u32 - 2 { + let type_id = self.next()?; + let ty = self.lookup_type.lookup(type_id)?.clone(); + decl.members.push(crate::StructMember { + name: self.future_member_decor + .remove(&(id, i)) + .and_then(|dec| dec.name), + ty, + }); + } + let ty = crate::Type::Struct(module.struct_declarations.append(decl)); + self.lookup_type.insert(id, ty); + } + Op::Constant => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(3)?; + let result_type_id = self.next()?; + let id = self.next()?; + let constant = match *self.lookup_type.lookup(result_type_id)? { + crate::Type::Scalar { kind: crate::ScalarKind::Uint, width } => { + let low = self.next()?; + let high = if width > 32 { + inst.expect(4)?; + self.next()? + } else { + 0 + }; + crate::Constant::Uint(((high as u64) << 32) | low as u64) + } + crate::Type::Scalar { kind: crate::ScalarKind::Sint, width } => { + let low = self.next()?; + let high = if width < 32 { + return Err(ParseError::InvalidTypeWidth(width as u32)); + } else if width > 32 { + inst.expect(4)?; + self.next()? + } else { + !0 + }; + crate::Constant::Sint(unsafe { + std::mem::transmute(((high as u64) << 32) | low as u64) + }) + } + crate::Type::Scalar { kind: crate::ScalarKind::Float, width } => { + let low = self.next()?; + let extended = if width < 32 { + return Err(ParseError::InvalidTypeWidth(width as u32)); + } else if width > 32 { + inst.expect(4)?; + let high = self.next()?; + unsafe { + std::mem::transmute(((high as u64) << 32) | low as u64) + } + } else { + unsafe { + std::mem::transmute::<_, f32>(low) as f64 + } + }; + crate::Constant::Float(extended) + } + ref other => return Err(ParseError::UnsupportedType(other.clone())) + }; + self.lookup_constant.insert(id, constant); + } _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)) //TODO } } - let mut entry_points = Vec::with_capacity(raw_entry_points.len()); + if !self.future_decor.is_empty() { + log::warn!("Unused item decorations: {:?}", self.future_decor); + self.future_decor.clear(); + } + if !self.future_member_decor.is_empty() { + log::warn!("Unused member decorations: {:?}", self.future_member_decor); + self.future_member_decor.clear(); + } + + module.entry_points.reserve(raw_entry_points.len()); for (exec_model, name, fun_id) in raw_entry_points { - entry_points.push(crate::EntryPoint { + module.entry_points.push(crate::EntryPoint { exec_model, name, function: *self.lookup_function.lookup(fun_id)?, }); } - Ok(crate::Module { - header, - struct_declarations: Storage::new(), - functions, - entry_points, - }) + Ok(module) } } diff --git a/src/lib.rs b/src/lib.rs index 9d709f617..916aa987e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,8 +41,21 @@ pub enum ScalarKind { } #[derive(Debug)] -pub struct StructDeclaration { +pub struct ArrayDeclaration { + pub base: Type, + pub length: u32, +} +#[derive(Debug)] +pub struct StructMember { + pub name: Option, + pub ty: Type, +} + +#[derive(Debug)] +pub struct StructDeclaration { + pub name: Option, + pub members: Vec, } #[derive(Clone, Debug)] @@ -50,11 +63,20 @@ pub enum Type { Void, Scalar { kind: ScalarKind, width: Bytes }, Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, + Array(Token), Struct(Token), } +#[derive(Clone, Debug)] +pub enum Constant { + Sint(i64), + Uint(u64), + Float(f64), +} + #[derive(Debug)] pub enum Expression { + Constant(Constant), Arithmetic, } @@ -100,6 +122,7 @@ pub struct EntryPoint { #[derive(Debug)] pub struct Module { pub header: Header, + pub array_declarations: Storage, pub struct_declarations: Storage, pub functions: Storage, pub entry_points: Vec, From 1fc6f89d7917791ea195943f341443045f720170 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 21 Feb 2020 16:27:11 -0500 Subject: [PATCH 0009/2212] Parse SPIR-V function declarations --- Cargo.toml | 1 - src/front/spirv.rs | 162 ++++++++++++++++++++++++++++++++++++++------- src/lib.rs | 16 ++++- 3 files changed, 151 insertions(+), 28 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 411e70f6f..30295aabe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,6 @@ edition = "2018" [dependencies] fxhash = "0.2" log = "0.4" -smallvec = "1" spirv_headers = "1" [dev-dependencies] diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 16a84ca30..0ca19e684 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -7,7 +7,8 @@ use std::convert::TryInto; const LAST_KNOWN_OPCODE: spirv::Op = spirv::Op::MemberDecorateStringGOOGLE; const LAST_KNOWN_CAPABILITY: spirv::Capability = spirv::Capability::VulkanMemoryModelDeviceScopeKHR; -const LAST_KNOWN_EXEC_MODEL: spirv::ExecutionModel = spirv::ExecutionModel::Kernel; +const LAST_KNOWN_EXECUTION_MODEL: spirv::ExecutionModel = spirv::ExecutionModel::Kernel; +const LAST_KNOWN_STORAGE_CLASS: spirv::StorageClass = spirv::StorageClass::StorageBuffer; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, @@ -23,20 +24,25 @@ pub enum ParseError { InvalidHeader, InvalidWordCount, UnknownInstruction(u16), - UnsupportedInstruction(ModuleState, spirv::Op), UnknownCapability(u32), + UnsupportedInstruction(ModuleState, spirv::Op), UnsupportedCapability(spirv::Capability), UnsupportedExtension(String), UnsupportedExtSet(String), UnsupportedType(crate::Type), - UnsupportedExecModel(u32), + UnsupportedExecutionModel(u32), + UnsupportedStorageClass(u32), + UnsupportedFunctionControl(u32), + InvalidParameter(spirv::Op), InvalidOperandCount(spirv::Op, u16), InvalidOperand, InvalidId(spirv::Word), InvalidTypeWidth(spirv::Word), InvalidSign(spirv::Word), - InvalidScalar(spirv::Word), + InvalidInnerType(spirv::Word), InvalidVectorSize(spirv::Word), + WrongFunctionResultType(spirv::Word), + WrongFunctionParameterType(spirv::Word), BadString, IncompleteData, } @@ -104,6 +110,14 @@ fn map_vector_size(word: spirv::Word) -> Result { } } +fn map_storage_class(word: spirv::Word) -> Result { + if word > LAST_KNOWN_STORAGE_CLASS as u32 { + Err(ParseError::UnsupportedStorageClass(word)) + } else { + Ok(unsafe { std::mem::transmute(word) }) + } +} + type MemberIndex = u32; #[derive(Debug, Default)] @@ -116,6 +130,13 @@ struct MemberDecoration { name: Option, } +//TODO: avoid cloning this +#[derive(Clone, Debug)] +struct FunctionType { + parameter_type_ids: Vec, + return_type_id: spirv::Word, +} + pub struct Parser { data: I, state: ModuleState, @@ -124,6 +145,8 @@ pub struct Parser { future_member_decor: FastHashMap<(spirv::Word, MemberIndex), MemberDecoration>, lookup_type: FastHashMap, lookup_constant: FastHashMap, + lookup_variable: FastHashMap>, + lookup_function_type: FastHashMap, lookup_function: FastHashMap>, } @@ -137,6 +160,8 @@ impl> Parser { future_member_decor: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_constant: FastHashMap::default(), + lookup_variable: FastHashMap::default(), + lookup_function_type: FastHashMap::default(), lookup_function: FastHashMap::default(), } } @@ -206,8 +231,8 @@ impl> Parser { generator, } }, - array_declarations: Storage::new(), struct_declarations: Storage::new(), + global_variables: Storage::new(), functions: Storage::new(), entry_points: Vec::new(), }; @@ -260,8 +285,8 @@ impl> Parser { Op::EntryPoint => { self.switch(ModuleState::EntryPoint, inst.op)?; let exec_model = self.next()?; - if exec_model > LAST_KNOWN_EXEC_MODEL as u32 { - return Err(ParseError::UnsupportedExecModel(exec_model)); + if exec_model > LAST_KNOWN_EXECUTION_MODEL as u32 { + return Err(ParseError::UnsupportedExecutionModel(exec_model)); } let function_id = self.next()?; let (name, left) = self.next_string(inst.wc - 3)?; @@ -370,7 +395,7 @@ impl> Parser { let type_id = self.next()?; let (kind, width) = match self.lookup_type.lookup(type_id)? { &crate::Type::Scalar { ref kind, width } => (kind.clone(), width), - _ => return Err(ParseError::InvalidScalar(type_id)), + _ => return Err(ParseError::InvalidInnerType(type_id)), }; let component_count = self.next()?; self.lookup_type.insert(id, crate::Type::Vector { @@ -379,24 +404,48 @@ impl> Parser { width, }); } + Op::TypeMatrix => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let vector_type_id = self.next()?; + let num_columns = self.next()?; + let (rows, kind, width) = match self.lookup_type.lookup(vector_type_id)? { + &crate::Type::Vector { ref size, ref kind, width } => (size.clone(), kind.clone(), width), + _ => return Err(ParseError::InvalidInnerType(vector_type_id)), + }; + self.lookup_type.insert(id, crate::Type::Matrix { + columns: map_vector_size(num_columns)?, + rows, + kind, + width, + }); + } Op::TypeFunction => { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(3)?; let id = self.next()?; - let ret_type_id = self.next()?; - let mut parameter_types = Vec::new(); - for _ in 3 .. inst.wc { - let type_id = self.next()?; - let ty = self.lookup_type.lookup(type_id)?.clone(); - parameter_types.push(ty); - } - let token = module.functions.append(crate::Function { - name: None, - return_type: self.lookup_type.lookup(ret_type_id)?.clone(), - parameter_types, - body: Vec::new(), + let return_type_id = self.next()?; + let parameter_type_ids = self.data + .by_ref() + .take(inst.wc as usize - 3) + .collect(); + self.lookup_function_type.insert(id, FunctionType { + parameter_type_ids, + return_type_id, }); - self.lookup_function.insert(id, token); + } + Op::TypePointer => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let storage = self.next()?; + let type_id = self.next()?; + let ty = crate::Type::Pointer { + base: Box::new(self.lookup_type.lookup(type_id)?.clone()), + class: map_storage_class(storage)?, + }; + self.lookup_type.insert(id, ty); } Op::TypeArray => { self.switch(ModuleState::Type, inst.op)?; @@ -404,11 +453,10 @@ impl> Parser { let id = self.next()?; let type_id = self.next()?; let length = self.next()?; - let decl = crate::ArrayDeclaration { - base: self.lookup_type.lookup(type_id)?.clone(), + let ty = crate::Type::Array { + base: Box::new(self.lookup_type.lookup(type_id)?.clone()), length, }; - let ty = crate::Type::Array(module.array_declarations.append(decl)); self.lookup_type.insert(id, ty); } Op::TypeStruct => { @@ -485,6 +533,72 @@ impl> Parser { }; self.lookup_constant.insert(id, constant); } + Op::Variable => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(4)?; + let result_type = self.next()?; + let id = self.next()?; + let storage = self.next()?; + if inst.wc != 4 { + inst.expect(5)?; + let _init = self.next()?; //TODO + } + let var = crate::GlobalVariable { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + class: map_storage_class(storage)?, + ty: self.lookup_type.lookup(result_type)?.clone(), + }; + let token = module.global_variables.append(var); + self.lookup_variable.insert(id, token); + } + Op::Function => { + self.switch(ModuleState::FunctionDecl, inst.op)?; + inst.expect(5)?; + let result_type = self.next()?; + let fun_id = self.next()?; + let fun_control = self.next()?; + let fun_type = self.next()?; + let ft = self.lookup_function_type.lookup(fun_type)?.clone(); + if ft.return_type_id != result_type { + return Err(ParseError::WrongFunctionResultType(result_type)) + } + let mut fun = crate::Function { + name: None, + control: spirv::FunctionControl::from_bits(fun_control) + .ok_or(ParseError::UnsupportedFunctionControl(fun_control))?, + parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), + return_type: self.lookup_type.lookup(result_type)?.clone(), + body: Vec::new(), + }; + for &par_type_id in ft.parameter_type_ids.iter() { + match self.next_inst()? { + Instruction { op: Op::FunctionParameter, wc: 3 } => { + let type_id = self.next()?; + let _id = self.next()?; + if type_id != par_type_id { + return Err(ParseError::WrongFunctionParameterType(type_id)) + } + let ty = self.lookup_type.lookup(type_id)?.clone(); + fun.parameter_types.push(ty); + } + Instruction { op, .. } => return Err(ParseError::InvalidParameter(op)), + } + } + loop { + let fun_inst = self.next_inst()?; + match fun_inst.op { + Op::FunctionEnd => { + fun_inst.expect(1)?; + break + } + _ => return Err(ParseError::UnsupportedInstruction(self.state, fun_inst.op)) + } + } + let token = module.functions.append(fun); + self.lookup_function.insert(fun_id, token); + } _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)) //TODO } diff --git a/src/lib.rs b/src/lib.rs index 916aa987e..6148fd9dc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,7 @@ pub enum ScalarKind { } #[derive(Debug)] -pub struct ArrayDeclaration { +pub struct PointerDeclaration { pub base: Type, pub length: u32, } @@ -63,7 +63,9 @@ pub enum Type { Void, Scalar { kind: ScalarKind, width: Bytes }, Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, - Array(Token), + Matrix { columns: VectorSize, rows: VectorSize, kind: ScalarKind, width: Bytes }, + Pointer { base: Box, class: spirv::StorageClass }, + Array { base: Box, length: u32 }, Struct(Token), } @@ -74,6 +76,13 @@ pub enum Constant { Float(f64), } +#[derive(Clone, Debug)] +pub struct GlobalVariable { + pub name: Option, + pub class: spirv::StorageClass, + pub ty: Type, +} + #[derive(Debug)] pub enum Expression { Constant(Constant), @@ -107,6 +116,7 @@ pub enum Statement { #[derive(Debug)] pub struct Function { pub name: Option, + pub control: spirv::FunctionControl, pub parameter_types: Vec, pub return_type: Type, pub body: Block, @@ -122,8 +132,8 @@ pub struct EntryPoint { #[derive(Debug)] pub struct Module { pub header: Header, - pub array_declarations: Storage, pub struct_declarations: Storage, + pub global_variables: Storage, pub functions: Storage, pub entry_points: Vec, } From e8a7a86c427f839d72a7c1dcd54d4a92a86fbac0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 21 Feb 2020 16:44:22 -0500 Subject: [PATCH 0010/2212] Parse SPIR-V inputs/outputs of entry points --- src/front/spirv.rs | 68 ++++++++++++++++++++++++++++++++++------------ src/lib.rs | 2 ++ 2 files changed, 52 insertions(+), 18 deletions(-) diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 0ca19e684..8efe8ef19 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -41,6 +41,7 @@ pub enum ParseError { InvalidSign(spirv::Word), InvalidInnerType(spirv::Word), InvalidVectorSize(spirv::Word), + InvalidVariableClass(spirv::StorageClass), WrongFunctionResultType(spirv::Word), WrongFunctionParameterType(spirv::Word), BadString, @@ -84,8 +85,7 @@ pub enum ModuleState { ModuleProcessed, Annotation, Type, - FunctionDecl, - FunctionDef, + Function, } trait Lookup { @@ -137,6 +137,14 @@ struct FunctionType { return_type_id: spirv::Word, } +#[derive(Debug)] +struct EntryPoint { + exec_model: spirv::ExecutionModel, + name: String, + function_id: spirv::Word, + variable_ids: Vec, +} + pub struct Parser { data: I, state: ModuleState, @@ -207,6 +215,11 @@ impl> Parser { .map_err(|_| ParseError::BadString) } + fn next_block(&mut self) -> Result<(), ParseError> { + //TODO + Ok(()) + } + fn switch(&mut self, state: ModuleState, op: spirv::Op) -> Result<(), ParseError> { if state < self.state { return Err(ParseError::UnsupportedInstruction(self.state, op)) @@ -236,7 +249,7 @@ impl> Parser { functions: Storage::new(), entry_points: Vec::new(), }; - let mut raw_entry_points = Vec::new(); + let mut entry_points = Vec::new(); while let Ok(inst) = self.next_inst() { use spirv::Op; @@ -290,16 +303,18 @@ impl> Parser { } let function_id = self.next()?; let (name, left) = self.next_string(inst.wc - 3)?; - for _ in 0 .. left { - let _var = self.next()?; //TODO: in/out variables - } - raw_entry_points.push(( - unsafe { + let ep = EntryPoint { + exec_model: unsafe { std::mem::transmute(exec_model) }, - name.to_owned(), + name: name.to_owned(), function_id, - )); + variable_ids: self.data + .by_ref() + .take(left as usize) + .collect(), + }; + entry_points.push(ep); } Op::Source => { self.switch(ModuleState::Source, inst.op)?; @@ -554,7 +569,7 @@ impl> Parser { self.lookup_variable.insert(id, token); } Op::Function => { - self.switch(ModuleState::FunctionDecl, inst.op)?; + self.switch(ModuleState::Function, inst.op)?; inst.expect(5)?; let result_type = self.next()?; let fun_id = self.next()?; @@ -589,6 +604,12 @@ impl> Parser { loop { let fun_inst = self.next_inst()?; match fun_inst.op { + Op::Label => { + fun_inst.expect(2)?; + let _id = self.next()?; + self.next_block()?; + break + } Op::FunctionEnd => { fun_inst.expect(1)?; break @@ -613,13 +634,24 @@ impl> Parser { self.future_member_decor.clear(); } - module.entry_points.reserve(raw_entry_points.len()); - for (exec_model, name, fun_id) in raw_entry_points { - module.entry_points.push(crate::EntryPoint { - exec_model, - name, - function: *self.lookup_function.lookup(fun_id)?, - }); + module.entry_points.reserve(entry_points.len()); + for raw in entry_points { + let mut ep = crate::EntryPoint { + exec_model: raw.exec_model, + name: raw.name, + function: *self.lookup_function.lookup(raw.function_id)?, + inputs: Vec::new(), + outputs: Vec::new(), + }; + for var_id in raw.variable_ids { + let token = *self.lookup_variable.lookup(var_id)?; + match module.global_variables[token].class { + spirv::StorageClass::Input => ep.inputs.push(token), + spirv::StorageClass::Output => ep.outputs.push(token), + other => return Err(ParseError::InvalidVariableClass(other)) + } + } + module.entry_points.push(ep); } Ok(module) diff --git a/src/lib.rs b/src/lib.rs index 6148fd9dc..f58ca4b57 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -126,6 +126,8 @@ pub struct Function { pub struct EntryPoint { pub exec_model: spirv::ExecutionModel, pub name: String, + pub inputs: Vec>, + pub outputs: Vec>, pub function: Token, } From fe654ee8c50037b0feba2f5a71b9466dcfb3cb4c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 24 Feb 2020 09:04:09 -0500 Subject: [PATCH 0011/2212] Implement spir-v access chain parsing --- src/front/spirv.rs | 305 +++++++++++++++++++++++++++++++++++---------- src/lib.rs | 26 ++-- 2 files changed, 254 insertions(+), 77 deletions(-) diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 8efe8ef19..df387bac5 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -42,6 +42,8 @@ pub enum ParseError { InvalidInnerType(spirv::Word), InvalidVectorSize(spirv::Word), InvalidVariableClass(spirv::StorageClass), + InvalidAccessType(spirv::Word), + InvalidAccessIndex(crate::Expression), WrongFunctionResultType(spirv::Word), WrongFunctionParameterType(spirv::Word), BadString, @@ -130,9 +132,8 @@ struct MemberDecoration { name: Option, } -//TODO: avoid cloning this -#[derive(Clone, Debug)] -struct FunctionType { +#[derive(Debug)] +struct LookupFunctionType { parameter_type_ids: Vec, return_type_id: spirv::Word, } @@ -145,16 +146,42 @@ struct EntryPoint { variable_ids: Vec, } +#[derive(Debug)] +struct LookupType { + value: crate::Type, + base_id: Option, +} + +#[derive(Debug)] +struct LookupConstant { + value: crate::Constant, + type_id: spirv::Word, +} + +#[derive(Debug)] +struct LookupVariable { + token: Token, + type_id: spirv::Word, +} + +#[derive(Clone, Debug)] +struct LookupExpression { + token: Token, + type_id: spirv::Word, +} + pub struct Parser { data: I, state: ModuleState, temp_bytes: Vec, future_decor: FastHashMap, future_member_decor: FastHashMap<(spirv::Word, MemberIndex), MemberDecoration>, - lookup_type: FastHashMap, - lookup_constant: FastHashMap, - lookup_variable: FastHashMap>, - lookup_function_type: FastHashMap, + lookup_member_type_id: FastHashMap<(spirv::Word, MemberIndex), spirv::Word>, + lookup_type: FastHashMap, + lookup_constant: FastHashMap, + lookup_variable: FastHashMap, + lookup_expression: FastHashMap, + lookup_function_type: FastHashMap, lookup_function: FastHashMap>, } @@ -166,9 +193,11 @@ impl> Parser { temp_bytes: Vec::new(), future_decor: FastHashMap::default(), future_member_decor: FastHashMap::default(), + lookup_member_type_id: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_constant: FastHashMap::default(), lookup_variable: FastHashMap::default(), + lookup_expression: FastHashMap::default(), lookup_function_type: FastHashMap::default(), lookup_function: FastHashMap::default(), } @@ -215,9 +244,103 @@ impl> Parser { .map_err(|_| ParseError::BadString) } - fn next_block(&mut self) -> Result<(), ParseError> { - //TODO - Ok(()) + fn next_block(&mut self, fun: &mut crate::Function) -> Result<(), ParseError> { + loop { + use spirv::Op; + let inst = self.next_inst()?; + log::debug!("\t\t{:?} [{}]", inst.op, inst.wc); + match inst.op { + Op::AccessChain => { + struct AccessExpression { + base_token: Token, + type_id: spirv::Word, + } + inst.expect_at_least(4)?; + let result_type_id = self.next()?; + let id = self.next()?; + let base_id = self.next()?; + log::trace!("\t\t\tlooking up expr {:?}", base_id); + let mut acex = { + let expr = self.lookup_expression.lookup(base_id)?; + let ptr_type = self.lookup_type.lookup(expr.type_id)?; + AccessExpression { + base_token: expr.token, + type_id: ptr_type.base_id.unwrap(), + } + }; + for _ in 4 .. inst.wc { + let access_id = self.next()?; + log::trace!("\t\t\tlooking up expr {:?}", access_id); + let index_expr = self.lookup_expression.lookup(access_id)?.clone(); + match self.lookup_type.lookup(index_expr.type_id)?.value { + crate::Type::Scalar { kind: crate::ScalarKind::Uint, .. } | + crate::Type::Scalar { kind: crate::ScalarKind::Sint, .. } => (), + ref other => return Err(ParseError::UnsupportedType(other.clone())), + } + log::trace!("\t\t\tlooking up type {:?}", acex.type_id); + let ty = self.lookup_type.lookup(acex.type_id)?; + acex = match ty.value { + crate::Type::Struct(_) => { + let index = match fun.expressions[index_expr.token] { + crate::Expression::Constant(crate::Constant::Sint(v)) => v as u32, + crate::Expression::Constant(crate::Constant::Uint(v)) => v as u32, + ref other => return Err(ParseError::InvalidAccessIndex(other.clone())) + }; + AccessExpression { + base_token: fun.expressions.append(crate::Expression::AccessMember { + base: acex.base_token, + index, + }), + type_id: *self.lookup_member_type_id + .get(&(acex.type_id, index)) + .ok_or(ParseError::InvalidAccessType(acex.type_id))?, + } + } + crate::Type::Array { .. } | + crate::Type::Vector { .. } | + crate::Type::Matrix { .. } => { + AccessExpression { + base_token: fun.expressions.append(crate::Expression::Access { + base: acex.base_token, + index: index_expr.token, + }), + type_id: ty.base_id + .ok_or(ParseError::InvalidAccessType(acex.type_id))?, + } + } + ref other => return Err(ParseError::UnsupportedType(other.clone())), + }; + } + + self.lookup_expression.insert(id, LookupExpression { + token: acex.base_token, + type_id: result_type_id, + }); + } + _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)), + } + } + } + + fn make_expression_storage(&mut self) -> Storage { + let mut expressions = Storage::new(); + assert!(self.lookup_expression.is_empty()); + // register global variables + for (&id, var) in self.lookup_variable.iter() { + self.lookup_expression.insert(id, LookupExpression { + type_id: var.type_id, + token: expressions.append(crate::Expression::GlobalVariable(var.token)), + }); + } + // register constants + for (&id, con) in self.lookup_constant.iter() { + self.lookup_expression.insert(id, LookupExpression { + type_id: con.type_id, + token: expressions.append(crate::Expression::Constant(con.value.clone())), + }); + } + // done + expressions } fn switch(&mut self, state: ModuleState, op: spirv::Op) -> Result<(), ParseError> { @@ -253,6 +376,7 @@ impl> Parser { while let Ok(inst) = self.next_inst() { use spirv::Op; + log::debug!("\t{:?} [{}]", inst.op, inst.wc); match inst.op { Op::Capability => { self.switch(ModuleState::Capability, inst.op)?; @@ -372,7 +496,10 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect(2)?; let id = self.next()?; - self.lookup_type.insert(id, crate::Type::Void); + self.lookup_type.insert(id, LookupType { + value: crate::Type::Void, + base_id: None, + }); } Op::TypeInt => { self.switch(ModuleState::Type, inst.op)?; @@ -380,15 +507,18 @@ impl> Parser { let id = self.next()?; let width = self.next()?; let sign = self.next()?; - self.lookup_type.insert(id, crate::Type::Scalar { - kind: match sign { - 0 => crate::ScalarKind::Uint, - 1 => crate::ScalarKind::Sint, - _ => return Err(ParseError::InvalidSign(sign)), + self.lookup_type.insert(id, LookupType { + value: crate::Type::Scalar { + kind: match sign { + 0 => crate::ScalarKind::Uint, + 1 => crate::ScalarKind::Sint, + _ => return Err(ParseError::InvalidSign(sign)), + }, + width: width + .try_into() + .map_err(|_| ParseError::InvalidTypeWidth(width))?, }, - width: width - .try_into() - .map_err(|_| ParseError::InvalidTypeWidth(width))?, + base_id: None, }); } Op::TypeFloat => { @@ -396,11 +526,14 @@ impl> Parser { inst.expect(3)?; let id = self.next()?; let width = self.next()?; - self.lookup_type.insert(id, crate::Type::Scalar { - kind: crate::ScalarKind::Float, - width: width - .try_into() - .map_err(|_| ParseError::InvalidTypeWidth(width))?, + self.lookup_type.insert(id, LookupType { + value: crate::Type::Scalar { + kind: crate::ScalarKind::Float, + width: width + .try_into() + .map_err(|_| ParseError::InvalidTypeWidth(width))?, + }, + base_id: None, }); } Op::TypeVector => { @@ -408,15 +541,18 @@ impl> Parser { inst.expect(4)?; let id = self.next()?; let type_id = self.next()?; - let (kind, width) = match self.lookup_type.lookup(type_id)? { - &crate::Type::Scalar { ref kind, width } => (kind.clone(), width), + let (kind, width) = match self.lookup_type.lookup(type_id)?.value { + crate::Type::Scalar { kind, width } => (kind, width), _ => return Err(ParseError::InvalidInnerType(type_id)), }; let component_count = self.next()?; - self.lookup_type.insert(id, crate::Type::Vector { - size: map_vector_size(component_count)?, - kind, - width, + self.lookup_type.insert(id, LookupType { + value: crate::Type::Vector { + size: map_vector_size(component_count)?, + kind, + width, + }, + base_id: Some(type_id), }); } Op::TypeMatrix => { @@ -425,15 +561,18 @@ impl> Parser { let id = self.next()?; let vector_type_id = self.next()?; let num_columns = self.next()?; - let (rows, kind, width) = match self.lookup_type.lookup(vector_type_id)? { - &crate::Type::Vector { ref size, ref kind, width } => (size.clone(), kind.clone(), width), + let (rows, kind, width) = match self.lookup_type.lookup(vector_type_id)?.value { + crate::Type::Vector { size, kind, width } => (size, kind, width), _ => return Err(ParseError::InvalidInnerType(vector_type_id)), }; - self.lookup_type.insert(id, crate::Type::Matrix { - columns: map_vector_size(num_columns)?, - rows, - kind, - width, + self.lookup_type.insert(id, LookupType { + value: crate::Type::Matrix { + columns: map_vector_size(num_columns)?, + rows, + kind, + width, + }, + base_id: Some(vector_type_id), }); } Op::TypeFunction => { @@ -445,7 +584,7 @@ impl> Parser { .by_ref() .take(inst.wc as usize - 3) .collect(); - self.lookup_function_type.insert(id, FunctionType { + self.lookup_function_type.insert(id, LookupFunctionType { parameter_type_ids, return_type_id, }); @@ -456,11 +595,14 @@ impl> Parser { let id = self.next()?; let storage = self.next()?; let type_id = self.next()?; - let ty = crate::Type::Pointer { - base: Box::new(self.lookup_type.lookup(type_id)?.clone()), + let value = crate::Type::Pointer { + base: Box::new(self.lookup_type.lookup(type_id)?.value.clone()), class: map_storage_class(storage)?, }; - self.lookup_type.insert(id, ty); + self.lookup_type.insert(id, LookupType { + value, + base_id: Some(type_id), + }); } Op::TypeArray => { self.switch(ModuleState::Type, inst.op)?; @@ -468,11 +610,14 @@ impl> Parser { let id = self.next()?; let type_id = self.next()?; let length = self.next()?; - let ty = crate::Type::Array { - base: Box::new(self.lookup_type.lookup(type_id)?.clone()), + let value = crate::Type::Array { + base: Box::new(self.lookup_type.lookup(type_id)?.value.clone()), length, }; - self.lookup_type.insert(id, ty); + self.lookup_type.insert(id, LookupType { + value, + base_id: Some(type_id), + }); } Op::TypeStruct => { self.switch(ModuleState::Type, inst.op)?; @@ -486,7 +631,8 @@ impl> Parser { }; for i in 0 .. inst.wc as u32 - 2 { let type_id = self.next()?; - let ty = self.lookup_type.lookup(type_id)?.clone(); + let ty = self.lookup_type.lookup(type_id)?.value.clone(); + self.lookup_member_type_id.insert((id, i), type_id); decl.members.push(crate::StructMember { name: self.future_member_decor .remove(&(id, i)) @@ -494,15 +640,18 @@ impl> Parser { ty, }); } - let ty = crate::Type::Struct(module.struct_declarations.append(decl)); - self.lookup_type.insert(id, ty); + let value = crate::Type::Struct(module.struct_declarations.append(decl)); + self.lookup_type.insert(id, LookupType { + value, + base_id: None, + }); } Op::Constant => { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(3)?; - let result_type_id = self.next()?; + let type_id = self.next()?; let id = self.next()?; - let constant = match *self.lookup_type.lookup(result_type_id)? { + let value = match self.lookup_type.lookup(type_id)?.value { crate::Type::Scalar { kind: crate::ScalarKind::Uint, width } => { let low = self.next()?; let high = if width > 32 { @@ -546,12 +695,15 @@ impl> Parser { } ref other => return Err(ParseError::UnsupportedType(other.clone())) }; - self.lookup_constant.insert(id, constant); + self.lookup_constant.insert(id, LookupConstant { + value, + type_id, + }); } Op::Variable => { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(4)?; - let result_type = self.next()?; + let type_id = self.next()?; let id = self.next()?; let storage = self.next()?; if inst.wc != 4 { @@ -563,10 +715,13 @@ impl> Parser { .remove(&id) .and_then(|dec| dec.name), class: map_storage_class(storage)?, - ty: self.lookup_type.lookup(result_type)?.clone(), + ty: self.lookup_type.lookup(type_id)?.value.clone(), }; let token = module.global_variables.append(var); - self.lookup_variable.insert(id, token); + self.lookup_variable.insert(id, LookupVariable { + token, + type_id, + }); } Op::Function => { self.switch(ModuleState::Function, inst.op)?; @@ -575,39 +730,49 @@ impl> Parser { let fun_id = self.next()?; let fun_control = self.next()?; let fun_type = self.next()?; - let ft = self.lookup_function_type.lookup(fun_type)?.clone(); - if ft.return_type_id != result_type { - return Err(ParseError::WrongFunctionResultType(result_type)) - } - let mut fun = crate::Function { - name: None, - control: spirv::FunctionControl::from_bits(fun_control) - .ok_or(ParseError::UnsupportedFunctionControl(fun_control))?, - parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), - return_type: self.lookup_type.lookup(result_type)?.clone(), - body: Vec::new(), + let mut fun = { + let ft = self.lookup_function_type.lookup(fun_type)?.clone(); + if ft.return_type_id != result_type { + return Err(ParseError::WrongFunctionResultType(result_type)) + } + crate::Function { + name: None, + control: spirv::FunctionControl::from_bits(fun_control) + .ok_or(ParseError::UnsupportedFunctionControl(fun_control))?, + parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), + return_type: self.lookup_type.lookup(result_type)?.value.clone(), + expressions: self.make_expression_storage(), + body: Vec::new(), + } }; - for &par_type_id in ft.parameter_type_ids.iter() { + // read parameters + for i in 0 .. fun.parameter_types.capacity() { match self.next_inst()? { Instruction { op: Op::FunctionParameter, wc: 3 } => { let type_id = self.next()?; let _id = self.next()?; - if type_id != par_type_id { + //Note: we redo the lookup in order to work around `self` borrowing + if type_id != self.lookup_function_type + .lookup(fun_type)? + .parameter_type_ids[i] + { return Err(ParseError::WrongFunctionParameterType(type_id)) } - let ty = self.lookup_type.lookup(type_id)?.clone(); + let ty = self.lookup_type.lookup(type_id)?.value.clone(); fun.parameter_types.push(ty); } Instruction { op, .. } => return Err(ParseError::InvalidParameter(op)), } } + // read body loop { let fun_inst = self.next_inst()?; + log::debug!("\t\t{:?}", fun_inst.op); match fun_inst.op { Op::Label => { fun_inst.expect(2)?; let _id = self.next()?; - self.next_block()?; + self.next_block(&mut fun)?; break } Op::FunctionEnd => { @@ -617,8 +782,10 @@ impl> Parser { _ => return Err(ParseError::UnsupportedInstruction(self.state, fun_inst.op)) } } + // done let token = module.functions.append(fun); self.lookup_function.insert(fun_id, token); + self.lookup_expression.clear(); } _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)) //TODO @@ -644,7 +811,7 @@ impl> Parser { outputs: Vec::new(), }; for var_id in raw.variable_ids { - let token = *self.lookup_variable.lookup(var_id)?; + let token = self.lookup_variable.lookup(var_id)?.token; match module.global_variables[token].class { spirv::StorageClass::Input => ep.inputs.push(token), spirv::StorageClass::Output => ep.outputs.push(token), diff --git a/src/lib.rs b/src/lib.rs index f58ca4b57..80dac62dc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,7 +25,7 @@ pub struct Header { pub type Bytes = u8; #[repr(u8)] -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] pub enum VectorSize { Bi = 2, Tri = 3, @@ -33,7 +33,7 @@ pub enum VectorSize { } #[repr(u8)] -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] pub enum ScalarKind { Sint, Uint, @@ -83,10 +83,20 @@ pub struct GlobalVariable { pub ty: Type, } -#[derive(Debug)] +#[derive(Clone, Debug)] pub enum Expression { - Constant(Constant), + Access { + base: Token, + index: Token, //int + }, + AccessMember { + base: Token, + index: u32, + }, Arithmetic, + Constant(Constant), + FunctionParameter(u32), + GlobalVariable(Token), } pub type Block = Vec; @@ -95,20 +105,19 @@ pub struct FallThrough; #[derive(Debug)] pub enum Statement { - Expression(Expression), Block(Block), If { - condition: Expression, //bool + condition: Token, //bool accept: Block, reject: Block, }, Switch { - selector: Expression, //int + selector: Token, //int cases: FastHashMap)>, default: Block, }, Return { - value: Option, + value: Option>, }, Kill, } @@ -119,6 +128,7 @@ pub struct Function { pub control: spirv::FunctionControl, pub parameter_types: Vec, pub return_type: Type, + pub expressions: Storage, pub body: Block, } From e1a6b5aa554d97b1edef4028933405770e55a02c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 24 Feb 2020 09:56:51 -0500 Subject: [PATCH 0012/2212] Add README --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..ec0b6a7d8 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# Naga + +[![Matrix](https://img.shields.io/badge/Matrix-%23gfx%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#gfx:matrix.org) +[![Build Status](https://travis-ci.org/gfx-rs/naga.svg?branch=master)](https://travis-ci.org/gfx-rs/naga) + +This is an experimental shader translation library for the needs of gfx-rs project and WebGPU. It's meant to provide a safe and performant way of converting to and from SPIR-V. + +## Supported end-points + +Front-end | Status | Notes | +--------------- | ------------------ | ----- | +SPIR-V (binary) | :construction: | | +Tint | | | +GLSL (Vulkan) | | | +Rust | | | + +Back-end | Status | Notes | +--------------- | ------------------ | ----- | +SPIR-V (binary) | | | +Tint | | | +MSL | | | +HLSL | | | +GLSL | | | +AIR | | | +DXBC | | | +DXIL | | | From 62c07782caffe32a71627adf2c716b5543836916 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 24 Feb 2020 09:58:30 -0500 Subject: [PATCH 0013/2212] Add travis integration --- .travis.yml | 1 + 1 file changed, 1 insertion(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..22761ba7e --- /dev/null +++ b/.travis.yml @@ -0,0 +1 @@ +language: rust From 17f31ca8462609b2d8378a64dbb1b1c1ab14ecc7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 24 Feb 2020 11:34:45 -0500 Subject: [PATCH 0014/2212] Parse SPIR-V load instruction --- src/front/spirv.rs | 27 +++++++++++++++++++++++++++ src/lib.rs | 3 +++ 2 files changed, 30 insertions(+) diff --git a/src/front/spirv.rs b/src/front/spirv.rs index df387bac5..5b6b7ccee 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -44,6 +44,7 @@ pub enum ParseError { InvalidVariableClass(spirv::StorageClass), InvalidAccessType(spirv::Word), InvalidAccessIndex(crate::Expression), + InvalidLoadType(spirv::Word), WrongFunctionResultType(spirv::Word), WrongFunctionParameterType(spirv::Word), BadString, @@ -317,6 +318,32 @@ impl> Parser { type_id: result_type_id, }); } + Op::Load => { + inst.expect_at_least(4)?; + let result_type_id = self.next()?; + let id = self.next()?; + let pointer_id = self.next()?; + if inst.wc != 4 { + inst.expect(5)?; + let _memory_access = self.next()?; + } + let base_expr = self.lookup_expression.lookup(pointer_id)?; + let base_type = self.lookup_type.lookup(base_expr.type_id)?; + if base_type.base_id != Some(result_type_id) { + return Err(ParseError::InvalidLoadType(result_type_id)); + } + match base_type.value { + crate::Type::Pointer { .. } => (), + ref other => return Err(ParseError::UnsupportedType(other.clone())), + } + let expr = crate::Expression::Load { + pointer: base_expr.token, + }; + self.lookup_expression.insert(id, LookupExpression { + token: fun.expressions.append(expr), + type_id: result_type_id, + }); + } _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)), } } diff --git a/src/lib.rs b/src/lib.rs index 80dac62dc..625564c6a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -97,6 +97,9 @@ pub enum Expression { Constant(Constant), FunctionParameter(u32), GlobalVariable(Token), + Load { + pointer: Token, + }, } pub type Block = Vec; From 84bc55e3d46a2da33f7797dcdb3750f280405144 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 24 Feb 2020 13:38:34 -0500 Subject: [PATCH 0015/2212] Parse Store, Composite extraction and composing from SPIR-V --- src/front/spirv.rs | 138 ++++++++++++++++++++++++++++++++++++++++++--- src/lib.rs | 18 ++++-- 2 files changed, 145 insertions(+), 11 deletions(-) diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 5b6b7ccee..47a874969 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -45,6 +45,7 @@ pub enum ParseError { InvalidAccessType(spirv::Word), InvalidAccessIndex(crate::Expression), InvalidLoadType(spirv::Word), + InvalidStoreType(spirv::Word), WrongFunctionResultType(spirv::Word), WrongFunctionParameterType(spirv::Word), BadString, @@ -258,7 +259,7 @@ impl> Parser { } inst.expect_at_least(4)?; let result_type_id = self.next()?; - let id = self.next()?; + let result_id = self.next()?; let base_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", base_id); let mut acex = { @@ -288,7 +289,7 @@ impl> Parser { ref other => return Err(ParseError::InvalidAccessIndex(other.clone())) }; AccessExpression { - base_token: fun.expressions.append(crate::Expression::AccessMember { + base_token: fun.expressions.append(crate::Expression::AccessIndex { base: acex.base_token, index, }), @@ -313,15 +314,79 @@ impl> Parser { }; } - self.lookup_expression.insert(id, LookupExpression { + self.lookup_expression.insert(result_id, LookupExpression { token: acex.base_token, type_id: result_type_id, }); } + Op::CompositeExtract => { + inst.expect_at_least(4)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let base_id = self.next()?; + log::trace!("\t\t\tlooking up expr {:?}", base_id); + let mut lexp = { + let expr = self.lookup_expression.lookup(base_id)?; + LookupExpression { + token: expr.token, + type_id: expr.type_id, + } + }; + for _ in 4 .. inst.wc { + let index = self.next()?; + log::trace!("\t\t\tlooking up type {:?}", lexp.type_id); + let ty = self.lookup_type.lookup(lexp.type_id)?; + let type_id = match ty.value { + crate::Type::Struct(_) => { + *self.lookup_member_type_id + .get(&(lexp.type_id, index)) + .ok_or(ParseError::InvalidAccessType(lexp.type_id))? + } + crate::Type::Array { .. } | + crate::Type::Vector { .. } | + crate::Type::Matrix { .. } => { + ty.base_id + .ok_or(ParseError::InvalidAccessType(lexp.type_id))? + } + ref other => return Err(ParseError::UnsupportedType(other.clone())), + }; + lexp = LookupExpression { + token: fun.expressions.append(crate::Expression::AccessIndex { + base: lexp.token, + index, + }), + type_id, + }; + } + + self.lookup_expression.insert(result_id, LookupExpression { + token: lexp.token, + type_id: result_type_id, + }); + } + Op::CompositeConstruct => { + inst.expect_at_least(3)?; + let result_type_id = self.next()?; + let id = self.next()?; + let mut components = Vec::with_capacity(inst.wc as usize - 2); + for _ in 3 .. inst.wc { + let comp_id = self.next()?; + log::trace!("\t\t\tlooking up expr {:?}", comp_id); + let lexp = self.lookup_expression.lookup(comp_id)?; + components.push(lexp.token); + } + let expr = crate::Expression::Compose { + components, + }; + self.lookup_expression.insert(id, LookupExpression { + token: fun.expressions.append(expr), + type_id: result_type_id, + }); + } Op::Load => { inst.expect_at_least(4)?; let result_type_id = self.next()?; - let id = self.next()?; + let result_id = self.next()?; let pointer_id = self.next()?; if inst.wc != 4 { inst.expect(5)?; @@ -339,7 +404,64 @@ impl> Parser { let expr = crate::Expression::Load { pointer: base_expr.token, }; - self.lookup_expression.insert(id, LookupExpression { + self.lookup_expression.insert(result_id, LookupExpression { + token: fun.expressions.append(expr), + type_id: result_type_id, + }); + } + Op::Store => { + inst.expect_at_least(3)?; + let pointer_id = self.next()?; + let value_id = self.next()?; + if inst.wc != 3 { + inst.expect(4)?; + let _memory_access = self.next()?; + } + let base_expr = self.lookup_expression.lookup(pointer_id)?; + let base_type = self.lookup_type.lookup(base_expr.type_id)?; + match base_type.value { + crate::Type::Pointer { .. } => (), + ref other => return Err(ParseError::UnsupportedType(other.clone())), + }; + let value_expr = self.lookup_expression.lookup(value_id)?; + if base_type.base_id != Some(value_expr.type_id) { + return Err(ParseError::InvalidStoreType(value_expr.type_id)); + } + fun.body.push(crate::Statement::Store { + pointer: base_expr.token, + value: value_expr.token, + }) + } + Op::Return => { + inst.expect(1)?; + fun.body.push(crate::Statement::Return { value: None }); + break + } + Op::MatrixTimesVector => { + inst.expect(5)?; + let result_type_id = self.next()?; + let (res_size, res_width) = match self.lookup_type.lookup(result_type_id)?.value { + crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), + ref other => return Err(ParseError::UnsupportedType(other.clone())), + }; + let result_id = self.next()?; + let matrix_id = self.next()?; + let vector_id = self.next()?; + let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; + let columns = match self.lookup_type.lookup(matrix_lexp.type_id)?.value { + crate::Type::Matrix { columns, rows, kind: crate::ScalarKind::Float, width } if rows == res_size && width == res_width => columns, + ref other => return Err(ParseError::UnsupportedType(other.clone())), + }; + let vector_lexp = self.lookup_expression.lookup(vector_id)?.clone(); + match self.lookup_type.lookup(vector_lexp.type_id)?.value { + crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } if size == columns && width == res_width => (), + ref other => return Err(ParseError::UnsupportedType(other.clone())), + }; + let expr = crate::Expression::MatrixTimesVector { + matrix: matrix_lexp.token, + vector: vector_lexp.token, + }; + self.lookup_expression.insert(result_id, LookupExpression { token: fun.expressions.append(expr), type_id: result_type_id, }); @@ -347,6 +469,7 @@ impl> Parser { _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)), } } + Ok(()) } fn make_expression_storage(&mut self) -> Storage { @@ -763,7 +886,9 @@ impl> Parser { return Err(ParseError::WrongFunctionResultType(result_type)) } crate::Function { - name: None, + name: self.future_decor + .remove(&fun_id) + .and_then(|dec| dec.name), control: spirv::FunctionControl::from_bits(fun_control) .ok_or(ParseError::UnsupportedFunctionControl(fun_control))?, parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), @@ -800,7 +925,6 @@ impl> Parser { fun_inst.expect(2)?; let _id = self.next()?; self.next_block(&mut fun)?; - break } Op::FunctionEnd => { fun_inst.expect(1)?; diff --git a/src/lib.rs b/src/lib.rs index 625564c6a..49b18f8a3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,7 +25,7 @@ pub struct Header { pub type Bytes = u8; #[repr(u8)] -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum VectorSize { Bi = 2, Tri = 3, @@ -33,7 +33,7 @@ pub enum VectorSize { } #[repr(u8)] -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum ScalarKind { Sint, Uint, @@ -89,17 +89,23 @@ pub enum Expression { base: Token, index: Token, //int }, - AccessMember { + AccessIndex { base: Token, index: u32, }, - Arithmetic, Constant(Constant), + Compose { + components: Vec>, + }, FunctionParameter(u32), GlobalVariable(Token), Load { pointer: Token, }, + MatrixTimesVector { + matrix: Token, + vector: Token, + }, } pub type Block = Vec; @@ -123,6 +129,10 @@ pub enum Statement { value: Option>, }, Kill, + Store { + pointer: Token, + value: Token, + }, } #[derive(Debug)] From 763014cb439c92bd08ae63ac8f5681fbe21f9ca0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 24 Feb 2020 18:49:19 -0500 Subject: [PATCH 0016/2212] [msl] write struct definitions --- examples/convert.rs | 2 +- src/back/msl.rs | 110 ++++++++++++++++++++++++++++++++++++++++---- src/storage.rs | 6 +++ 3 files changed, 109 insertions(+), 9 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index ccf085393..32a1f46c9 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -13,7 +13,7 @@ fn main() { //println!("{:?}", module); let options = javelin::back::msl::Options {}; - let msl = module.to_msl(&options).unwrap(); + let msl = javelin::back::msl::write_string(&module, &options).unwrap(); println!("{}", msl); } diff --git a/src/back/msl.rs b/src/back/msl.rs index 959f1558a..74fa85376 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -1,5 +1,6 @@ use std::fmt::{Error as FmtError, Write}; + pub struct Options { } @@ -14,14 +15,107 @@ impl From for Error { } } -impl crate::Module { - pub fn to_msl(&self, _options: &Options) -> Result { - let mut out = String::new(); +pub struct Writer { + out: W, +} - writeln!(out, "#include ")?; - writeln!(out, "#include ")?; - writeln!(out, "using namespace metal;")?; - - Ok(out) +fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { + match kind { + crate::ScalarKind::Float => "float", + crate::ScalarKind::Sint => "signed int", + crate::ScalarKind::Uint => "unsigned int", } } + +fn vector_size_string(size: crate::VectorSize) -> &'static str { + match size { + crate::VectorSize::Bi => "2", + crate::VectorSize::Tri => "3", + crate::VectorSize::Quad => "4", + } +} + +impl Writer { + fn put_type_pre(&mut self, ty: &crate::Type) -> Result<(), FmtError> { + match *ty { + crate::Type::Void => { + write!(self.out, "void") + }, + crate::Type::Scalar { kind, .. } => { + write!(self.out, "{}", scalar_kind_string(kind)) + }, + crate::Type::Vector { size, kind, .. } => { + write!(self.out, "{}{}", scalar_kind_string(kind), vector_size_string(size)) + }, + crate::Type::Matrix { columns, rows, kind, .. } => { + write!(self.out, "{}{}x{}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows)) + } + crate::Type::Array { ref base, .. } => { + self.put_type_pre(base) + } + _ => panic!("Unknown type {:?}", ty), + } + } + + fn put_type_post(&mut self, ty: &crate::Type) -> Result<(), FmtError> { + match *ty { + crate::Type::Array { length, .. } => { + write!(self.out, "[{}]", length) + } + _ => Ok(()) + } + } + + fn put_struct_name( + &mut self, + token: crate::Token, + module: &crate::Module, + ) -> Result<(), FmtError> { + match module.struct_declarations[token].name { + Some(ref name) => write!(self.out, "{}", name), + None => write!(self.out, "_Struct{}", token.index()), + } + } + + fn put_struct_member_name( + &mut self, + token: crate::Token, + index: usize, + module: &crate::Module, + ) -> Result<(), FmtError> { + match module.struct_declarations[token].members[index].name { + Some(ref name) => write!(self.out, "{}", name), + None => write!(self.out, "_field{}", index), + } + } + + pub fn write(&mut self, module: &crate::Module) -> Result<(), Error> { + writeln!(self.out, "#include ")?; + writeln!(self.out, "#include ")?; + writeln!(self.out, "using namespace metal;")?; + + writeln!(self.out, "")?; + for (token, decl) in module.struct_declarations.iter() { + write!(self.out, "struct ")?; + self.put_struct_name(token, module)?; + writeln!(self.out, " {{")?; + for (index, member) in decl.members.iter().enumerate() { + write!(self.out, "\t")?; + self.put_type_pre(&member.ty)?; + write!(self.out, " ")?; + self.put_struct_member_name(token, index, module)?; + self.put_type_post(&member.ty)?; + writeln!(self.out, ";")?; + } + writeln!(self.out, "}};")?; + } + + Ok(()) + } +} + +pub fn write_string(module: &crate::Module, _options: &Options) -> Result { + let mut w = Writer { out: String::new() }; + w.write(module)?; + Ok(w.out) +} diff --git a/src/storage.rs b/src/storage.rs index 8142b75cf..b56c426ca 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -1,5 +1,6 @@ use std::{ fmt, + hash, marker::PhantomData, }; @@ -37,6 +38,11 @@ impl fmt::Debug for Token { write!(formatter, "Token({})", self.index) } } +impl hash::Hash for Token { + fn hash(&self, hasher: &mut H) { + self.index.hash(hasher) + } +} impl Token { #[cfg(test)] From b3c75ec1cd9343d3ba40f3c2aca991a8fc203320 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 24 Feb 2020 22:27:29 -0500 Subject: [PATCH 0017/2212] [msl] collect function parameters --- src/back/msl.rs | 182 +++++++++++++++++++++++++++++++----------------- src/lib.rs | 6 -- 2 files changed, 119 insertions(+), 69 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 74fa85376..75b4a3841 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -1,4 +1,4 @@ -use std::fmt::{Error as FmtError, Write}; +use std::fmt::{Display, Error as FmtError, Formatter, Write}; pub struct Options { @@ -15,6 +15,94 @@ impl From for Error { } } +trait Indexed { + const CLASS: &'static str; + fn id(&self) -> usize; +} + +impl Indexed for crate::Token { + const CLASS: &'static str = "Struct"; + fn id(&self) -> usize { self.index() } +} +impl Indexed for crate::Token { + const CLASS: &'static str = "global"; + fn id(&self) -> usize { self.index() } +} +impl Indexed for crate::Token { + const CLASS: &'static str = "function"; + fn id(&self) -> usize { self.index() } +} + +struct MemberIndex(usize); +impl Indexed for MemberIndex { + const CLASS: &'static str = "field"; + fn id(&self) -> usize { self.0 } +} + +struct ParameterIndex(usize); +impl Indexed for ParameterIndex { + const CLASS: &'static str = "param"; + fn id(&self) -> usize { self.0 } +} + + +enum Name<'a, I> { + Custom(&'a str), + Index(I), +} + +impl Display for Name<'_, I> { + fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { + match *self { + Name::Custom(name) => formatter.write_str(name), + Name::Index(ref index) => write!(formatter, "{}{}", I::CLASS, index.id()), + } + } +} + +trait AsName { + fn or_index(&self, index: I) -> Name; +} + +impl AsName for Option { + fn or_index(&self, index: I) -> Name { + match *self { + Some(ref name) => Name::Custom(name), + None => Name::Index(index), + } + } +} + +struct TypedVar<'a, T>(&'a crate::Type, &'a T, &'a crate::Storage); + +impl Display for TypedVar<'_, T> { + fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { + match *self.0 { + crate::Type::Void => { + write!(formatter, "void {}", self.1) + }, + crate::Type::Scalar { kind, .. } => { + write!(formatter, "{} {}", scalar_kind_string(kind), self.1) + }, + crate::Type::Vector { size, kind, .. } => { + write!(formatter, "{}{} {}", scalar_kind_string(kind), vector_size_string(size), self.1) + }, + crate::Type::Matrix { columns, rows, kind, .. } => { + write!(formatter, "{}{}x{} {}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows), self.1) + } + crate::Type::Array { ref base, length } => { + write!(formatter, "{}[{}]", TypedVar(base, self.1, self.2), length) + } + crate::Type::Pointer { ref base, .. } => { + write!(formatter, "{}*{}", TypedVar(base, &"", self.2), self.1) + } + crate::Type::Struct(token) => { + write!(formatter, "{} {}", self.2[token].name.or_index(token), self.1) + } + } + } +} + pub struct Writer { out: W, } @@ -36,59 +124,6 @@ fn vector_size_string(size: crate::VectorSize) -> &'static str { } impl Writer { - fn put_type_pre(&mut self, ty: &crate::Type) -> Result<(), FmtError> { - match *ty { - crate::Type::Void => { - write!(self.out, "void") - }, - crate::Type::Scalar { kind, .. } => { - write!(self.out, "{}", scalar_kind_string(kind)) - }, - crate::Type::Vector { size, kind, .. } => { - write!(self.out, "{}{}", scalar_kind_string(kind), vector_size_string(size)) - }, - crate::Type::Matrix { columns, rows, kind, .. } => { - write!(self.out, "{}{}x{}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows)) - } - crate::Type::Array { ref base, .. } => { - self.put_type_pre(base) - } - _ => panic!("Unknown type {:?}", ty), - } - } - - fn put_type_post(&mut self, ty: &crate::Type) -> Result<(), FmtError> { - match *ty { - crate::Type::Array { length, .. } => { - write!(self.out, "[{}]", length) - } - _ => Ok(()) - } - } - - fn put_struct_name( - &mut self, - token: crate::Token, - module: &crate::Module, - ) -> Result<(), FmtError> { - match module.struct_declarations[token].name { - Some(ref name) => write!(self.out, "{}", name), - None => write!(self.out, "_Struct{}", token.index()), - } - } - - fn put_struct_member_name( - &mut self, - token: crate::Token, - index: usize, - module: &crate::Module, - ) -> Result<(), FmtError> { - match module.struct_declarations[token].members[index].name { - Some(ref name) => write!(self.out, "{}", name), - None => write!(self.out, "_field{}", index), - } - } - pub fn write(&mut self, module: &crate::Module) -> Result<(), Error> { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; @@ -96,20 +131,41 @@ impl Writer { writeln!(self.out, "")?; for (token, decl) in module.struct_declarations.iter() { - write!(self.out, "struct ")?; - self.put_struct_name(token, module)?; - writeln!(self.out, " {{")?; + writeln!(self.out, "struct {} {{", decl.name.or_index(token))?; for (index, member) in decl.members.iter().enumerate() { - write!(self.out, "\t")?; - self.put_type_pre(&member.ty)?; - write!(self.out, " ")?; - self.put_struct_member_name(token, index, module)?; - self.put_type_post(&member.ty)?; - writeln!(self.out, ";")?; + let name = member.name.or_index(MemberIndex(index)); + let tv = TypedVar(&member.ty, &name, &module.struct_declarations); + writeln!(self.out, "\t{};", tv)?; } writeln!(self.out, "}};")?; } + let mut globals_used = Vec::new(); + writeln!(self.out, "")?; + for (fun_token, fun) in module.functions.iter() { + let fun_name = fun.name.or_index(fun_token); + let fun_tv = TypedVar(&fun.return_type, &fun_name, &module.struct_declarations); + writeln!(self.out, "{}(", fun_tv)?; + for (index, ty) in fun.parameter_types.iter().enumerate() { + let name = Name::Index(ParameterIndex(index)); + let tv = TypedVar(ty, &name, &module.struct_declarations); + writeln!(self.out, "\t{},", tv)?; + } + for (_, expr) in fun.expressions.iter() { + if let crate::Expression::GlobalVariable(token) = *expr { + if !globals_used.contains(&token) { + globals_used.push(token); + let var = &module.global_variables[token]; + let name = var.name.or_index(token); + let tv = TypedVar(&var.ty, &name, &module.struct_declarations); + writeln!(self.out, "\t{},", tv)?; + } + } + } + writeln!(self.out, ") {{")?; + writeln!(self.out, "}}")?; + } + Ok(()) } } diff --git a/src/lib.rs b/src/lib.rs index 49b18f8a3..bfb0e63a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -40,12 +40,6 @@ pub enum ScalarKind { Float, } -#[derive(Debug)] -pub struct PointerDeclaration { - pub base: Type, - pub length: u32, -} - #[derive(Debug)] pub struct StructMember { pub name: Option, From 96a12a0c9ad51e1b708e4ebd294f806be887df7f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 25 Feb 2020 14:00:51 -0500 Subject: [PATCH 0018/2212] Complete the crate rename to Naga --- Cargo.toml | 2 +- README.md | 2 +- examples/convert.rs | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 30295aabe..2a6695e5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "javelin" +name = "naga" version = "0.1.0" authors = ["Dzmitry Malyshau "] edition = "2018" diff --git a/README.md b/README.md index ec0b6a7d8..d298c2447 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Back-end | Status | Notes | --------------- | ------------------ | ----- | SPIR-V (binary) | | | Tint | | | -MSL | | | +MSL | :construction: | | HLSL | | | GLSL | | | AIR | | | diff --git a/examples/convert.rs b/examples/convert.rs index 32a1f46c9..28ab978a3 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -1,5 +1,5 @@ extern crate env_logger; -extern crate javelin; +extern crate naga; use std::{env, fs}; @@ -9,11 +9,11 @@ fn main() { let args = env::args().collect::>(); let input = fs::read(&args[1]).unwrap(); - let module = javelin::front::spirv::parse_u8_slice(&input).unwrap(); + let module = naga::front::spirv::parse_u8_slice(&input).unwrap(); //println!("{:?}", module); - let options = javelin::back::msl::Options {}; - let msl = javelin::back::msl::write_string(&module, &options).unwrap(); + let options = naga::back::msl::Options {}; + let msl = naga::back::msl::write_string(&module, &options).unwrap(); println!("{}", msl); } From 34c59d0371b2dce465ce51dd40c24ca14807fd6f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 25 Feb 2020 14:26:23 -0500 Subject: [PATCH 0019/2212] [msl] improve function I/O declarations --- src/back/msl.rs | 200 ++++++++++++++++++++++++++++++++++++++++-------- src/lib.rs | 7 +- 2 files changed, 169 insertions(+), 38 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 75b4a3841..6a9bff10a 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -1,4 +1,10 @@ -use std::fmt::{Display, Error as FmtError, Formatter, Write}; +use std::{ + fmt::{ + Display, Error as FmtError, Formatter, Write, + }, +}; + +use crate::FastHashSet; pub struct Options { @@ -6,7 +12,10 @@ pub struct Options { #[derive(Debug)] pub enum Error { - Format(FmtError) + Format(FmtError), + UnsupportedExecutionModel(spirv::ExecutionModel), + MixedExecutionModels(crate::Token), + BadName(String), } impl From for Error { @@ -17,6 +26,7 @@ impl From for Error { trait Indexed { const CLASS: &'static str; + const PREFIX: bool = false; fn id(&self) -> usize; } @@ -38,37 +48,75 @@ impl Indexed for MemberIndex { const CLASS: &'static str = "field"; fn id(&self) -> usize { self.0 } } - struct ParameterIndex(usize); impl Indexed for ParameterIndex { const CLASS: &'static str = "param"; fn id(&self) -> usize { self.0 } } - - -enum Name<'a, I> { - Custom(&'a str), - Index(I), +struct InputStructIndex(crate::Token); +impl Indexed for InputStructIndex { + const CLASS: &'static str = "Input"; + const PREFIX: bool = true; + fn id(&self) -> usize { self.0.index() } +} +struct OutputStructIndex(crate::Token); +impl Indexed for OutputStructIndex { + const CLASS: &'static str = "Output"; + const PREFIX: bool = true; + fn id(&self) -> usize { self.0.index() } } -impl Display for Name<'_, I> { +enum NameSource<'a> { + Custom { name: &'a str, prefix: bool }, + Index(usize), +} + +struct Name<'a> { + class: &'static str, + source: NameSource<'a>, +} + +const RESERVED_NAMES: &[&str] = &[ + "main", +]; + +impl Display for Name<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - match *self { - Name::Custom(name) => formatter.write_str(name), - Name::Index(ref index) => write!(formatter, "{}{}", I::CLASS, index.id()), + match self.source { + NameSource::Custom { name, prefix: false } if RESERVED_NAMES.contains(&name) => { + write!(formatter, "{}_", name) + } + NameSource::Custom { name, prefix: false } => formatter.write_str(name), + NameSource::Custom { name, prefix: true } => { + let (head, tail) = name.split_at(1); + write!(formatter, "{}{}{}", self.class, head.to_uppercase(), tail) + } + NameSource::Index(index) => write!(formatter, "{}{}", self.class, index), + } + } +} + +impl From for Name<'_> { + fn from(index: I) -> Self { + Name { + class: I::CLASS, + source: NameSource::Index(index.id()), } } } trait AsName { - fn or_index(&self, index: I) -> Name; + fn or_index(&self, index: I) -> Name; } impl AsName for Option { - fn or_index(&self, index: I) -> Name { - match *self { - Some(ref name) => Name::Custom(name), - None => Name::Index(index), + fn or_index(&self, index: I) -> Name { + Name { + class: I::CLASS, + source: match *self { + Some(ref name) if !name.is_empty() => NameSource::Custom { name, prefix: I::PREFIX }, + _ => NameSource::Index(index.id()), + }, } } } @@ -103,6 +151,26 @@ impl Display for TypedVar<'_, T> { } } +struct TypedGlobalVariable<'a> { + module: &'a crate::Module, + token: crate::Token, +} + +impl Display for TypedGlobalVariable<'_> { + fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { + let var = &self.module.global_variables[self.token]; + let name = var.name.or_index(self.token); + let tv = match var.ty { + crate::Type::Pointer { ref base, .. } => { + TypedVar(base, &name, &self.module.struct_declarations) + } + _ => panic!("Unexpected global type {:?}", var.ty), + }; + write!(formatter, "{}", tv) + } +} + + pub struct Writer { out: W, } @@ -123,6 +191,9 @@ fn vector_size_string(size: crate::VectorSize) -> &'static str { } } +const NAME_INPUT: &'static str = "input"; +const NAME_OUTPUT: &'static str = "output"; + impl Writer { pub fn write(&mut self, module: &crate::Module) -> Result<(), Error> { writeln!(self.out, "#include ")?; @@ -140,29 +211,90 @@ impl Writer { writeln!(self.out, "}};")?; } - let mut globals_used = Vec::new(); + let mut uniforms_used = FastHashSet::default(); writeln!(self.out, "")?; for (fun_token, fun) in module.functions.iter() { - let fun_name = fun.name.or_index(fun_token); - let fun_tv = TypedVar(&fun.return_type, &fun_name, &module.struct_declarations); - writeln!(self.out, "{}(", fun_tv)?; - for (index, ty) in fun.parameter_types.iter().enumerate() { - let name = Name::Index(ParameterIndex(index)); - let tv = TypedVar(ty, &name, &module.struct_declarations); - writeln!(self.out, "\t{},", tv)?; - } - for (_, expr) in fun.expressions.iter() { - if let crate::Expression::GlobalVariable(token) = *expr { - if !globals_used.contains(&token) { - globals_used.push(token); - let var = &module.global_variables[token]; - let name = var.name.or_index(token); - let tv = TypedVar(&var.ty, &name, &module.struct_declarations); - writeln!(self.out, "\t{},", tv)?; + let mut exec_model = None; + let mut var_inputs = FastHashSet::default(); + let mut var_outputs = FastHashSet::default(); + for ep in module.entry_points.iter() { + if ep.function == fun_token { + var_inputs.extend(ep.inputs.iter().cloned()); + var_outputs.extend(ep.outputs.iter().cloned()); + if exec_model.is_some() { + if exec_model != Some(ep.exec_model) { + return Err(Error::MixedExecutionModels(fun_token)); + } + } else { + exec_model = Some(ep.exec_model); } } } + let input_name = fun.name.or_index(InputStructIndex(fun_token)); + let output_name = fun.name.or_index(OutputStructIndex(fun_token)); + if let Some(em) = exec_model { + writeln!(self.out, "struct {} {{", input_name)?; + for &token in var_inputs.iter() { + let var = TypedGlobalVariable { module, token }; + writeln!(self.out, "\t{};", var)?; + } + writeln!(self.out, "}};")?; + writeln!(self.out, "struct {} {{", output_name)?; + for &token in var_outputs.iter() { + let var = TypedGlobalVariable { module, token }; + writeln!(self.out, "\t{};", var)?; + } + writeln!(self.out, "}};")?; + let em_str = match em { + spirv::ExecutionModel::Vertex => "vertex", + spirv::ExecutionModel::Fragment => "fragment", + spirv::ExecutionModel::GLCompute => "compute", + _ => return Err(Error::UnsupportedExecutionModel(em)), + }; + write!(self.out, "{} ", em_str)?; + } + + let fun_name = fun.name.or_index(fun_token); + if exec_model.is_some() { + writeln!(self.out, "{} {}(", output_name, fun_name)?; + writeln!(self.out, "\t{} {} [[stage_in]],", input_name, NAME_INPUT)?; + } else { + let fun_tv = TypedVar(&fun.return_type, &fun_name, &module.struct_declarations); + writeln!(self.out, "{}(", fun_tv)?; + for (index, ty) in fun.parameter_types.iter().enumerate() { + let name = Name::from(ParameterIndex(index)); + let tv = TypedVar(ty, &name, &module.struct_declarations); + writeln!(self.out, "\t{},", tv)?; + } + } + for (_, expr) in fun.expressions.iter() { + if let crate::Expression::GlobalVariable(token) = *expr { + let var = &module.global_variables[token]; + if var.class == spirv::StorageClass::Uniform && !uniforms_used.contains(&token) { + uniforms_used.insert(token); + let var = TypedGlobalVariable { module, token }; + writeln!(self.out, "\t{},", var)?; + } + } + } + // add an extra parameter to make Metal happy about the comma + match exec_model { + Some(spirv::ExecutionModel::Vertex) => { + writeln!(self.out, "\tunsigned _dummy [[vertex_id]]")?; + } + Some(spirv::ExecutionModel::Fragment) => { + writeln!(self.out, "\tbool _dummy [[front_facing]]")?; + } + Some(spirv::ExecutionModel::GLCompute) => { + writeln!(self.out, "\tunsigned _dummy [[threads_per_grid]]")?; + } + _ => { + writeln!(self.out, "\tint _dummy")?; + } + } writeln!(self.out, ") {{")?; + writeln!(self.out, "\t{} {};", output_name, NAME_OUTPUT)?; + writeln!(self.out, "\treturn {};", NAME_OUTPUT)?; writeln!(self.out, "}}")?; } diff --git a/src/lib.rs b/src/lib.rs index bfb0e63a1..8858dbdb2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,17 +4,16 @@ pub mod back; pub mod front; mod storage; - use crate::storage::{Storage, Token}; use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, hash::BuildHasherDefault, }; + type FastHashMap = HashMap>; - - +type FastHashSet = HashSet>; #[derive(Debug)] pub struct Header { From 72ecd7b07217fe5fd6a626e772569189d8e93c77 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 25 Feb 2020 17:10:42 -0500 Subject: [PATCH 0020/2212] Parse decorations --- examples/convert.rs | 15 ++-- src/back/msl.rs | 105 +++++++++++++++++++++++---- src/front/spirv.rs | 170 +++++++++++++++++++++++++++++++++++++------- src/lib.rs | 9 +++ 4 files changed, 253 insertions(+), 46 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 28ab978a3..a4d017c21 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -1,6 +1,3 @@ -extern crate env_logger; -extern crate naga; - use std::{env, fs}; fn main() { @@ -12,8 +9,14 @@ fn main() { let module = naga::front::spirv::parse_u8_slice(&input).unwrap(); //println!("{:?}", module); - let options = naga::back::msl::Options {}; - let msl = naga::back::msl::write_string(&module, &options).unwrap(); + let mut binding_map = naga::back::msl::BindingMap::default(); + binding_map.insert( + naga::back::msl::BindSource { set: 0, binding: 0 }, + naga::back::msl::BindTarget { buffer: None, texture: None, sampler: None }, + ); + let options = naga::back::msl::Options { + binding_map: &binding_map, + }; + let msl = naga::back::msl::write_string(&module, options).unwrap(); println!("{}", msl); } - diff --git a/src/back/msl.rs b/src/back/msl.rs index 6a9bff10a..f04988364 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -4,10 +4,27 @@ use std::{ }, }; -use crate::FastHashSet; +use crate::{FastHashMap, FastHashSet}; +#[derive(Clone, Debug, PartialEq)] +pub struct BindTarget { + pub buffer: Option, + pub texture: Option, + pub sampler: Option, +} -pub struct Options { +#[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub struct BindSource { + pub set: spirv::Word, + pub binding: spirv::Word, +} + +pub type BindingMap = FastHashMap; + +enum ResolvedBinding { + BuiltIn(spirv::BuiltIn), + User { prefix: &'static str, index: spirv::Word }, + Resource(BindTarget), } #[derive(Debug)] @@ -15,6 +32,8 @@ pub enum Error { Format(FmtError), UnsupportedExecutionModel(spirv::ExecutionModel), MixedExecutionModels(crate::Token), + MissingBinding(crate::Token), + MissingBindTarget(BindSource), BadName(String), } @@ -24,6 +43,32 @@ impl From for Error { } } +pub struct Options<'a> { + pub binding_map: &'a BindingMap, +} + +impl Options<'_> { + fn resolve_binding(&self, binding: &crate::Binding) -> Result { + match *binding { + crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), + crate::Binding::Location(index) => Ok(ResolvedBinding::User { + prefix: "loc", + index, + }), + crate::Binding::Descriptor { set, binding } => { + let source = BindSource { set, binding }; + self.binding_map + .get(&source) + .cloned() + .map(ResolvedBinding::Resource) + .ok_or(Error::MissingBindTarget(source)) + + } + } + } +} + + trait Indexed { const CLASS: &'static str; const PREFIX: bool = false; @@ -71,15 +116,14 @@ enum NameSource<'a> { Index(usize), } -struct Name<'a> { - class: &'static str, - source: NameSource<'a>, -} - const RESERVED_NAMES: &[&str] = &[ "main", ]; +struct Name<'a> { + class: &'static str, + source: NameSource<'a>, +} impl Display for Name<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { match self.source { @@ -95,7 +139,6 @@ impl Display for Name<'_> { } } } - impl From for Name<'_> { fn from(index: I) -> Self { Name { @@ -108,7 +151,6 @@ impl From for Name<'_> { trait AsName { fn or_index(&self, index: I) -> Name; } - impl AsName for Option { fn or_index(&self, index: I) -> Name { Name { @@ -122,7 +164,6 @@ impl AsName for Option { } struct TypedVar<'a, T>(&'a crate::Type, &'a T, &'a crate::Storage); - impl Display for TypedVar<'_, T> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { match *self.0 { @@ -155,7 +196,6 @@ struct TypedGlobalVariable<'a> { module: &'a crate::Module, token: crate::Token, } - impl Display for TypedGlobalVariable<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { let var = &self.module.global_variables[self.token]; @@ -170,6 +210,36 @@ impl Display for TypedGlobalVariable<'_> { } } +impl Display for ResolvedBinding { + fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { + match *self { + ResolvedBinding::BuiltIn(built_in) => { + let name = match built_in { + spirv::BuiltIn::ClipDistance => "clip_distance", + spirv::BuiltIn::CullDistance => "cull_distance", + spirv::BuiltIn::PointSize => "point_size", + spirv::BuiltIn::Position => "position", + _ => panic!("Built in {:?} is not implemented", built_in), + }; + formatter.write_str(name) + } + ResolvedBinding::User { prefix, index } => { + write!(formatter, "user({}{})", prefix, index) + } + ResolvedBinding::Resource(ref target) => { + if let Some(id) = target.buffer { + write!(formatter, "buffer({})", id) + } else if let Some(id) = target.texture { + write!(formatter, "buffer({})", id) + } else if let Some(id) = target.sampler { + write!(formatter, "sampler({})", id) + } else { + unimplemented!() + } + } + } + } +} pub struct Writer { out: W, @@ -195,7 +265,7 @@ const NAME_INPUT: &'static str = "input"; const NAME_OUTPUT: &'static str = "output"; impl Writer { - pub fn write(&mut self, module: &crate::Module) -> Result<(), Error> { + pub fn write(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; writeln!(self.out, "using namespace metal;")?; @@ -206,7 +276,12 @@ impl Writer { for (index, member) in decl.members.iter().enumerate() { let name = member.name.or_index(MemberIndex(index)); let tv = TypedVar(&member.ty, &name, &module.struct_declarations); - writeln!(self.out, "\t{};", tv)?; + write!(self.out, "\t{}", tv)?; + if let Some(ref binding) = member.binding { + let resolved = options.resolve_binding(binding)?; + write!(self.out, " [[{}]]", resolved)?; + } + writeln!(self.out, ";")?; } writeln!(self.out, "}};")?; } @@ -302,8 +377,8 @@ impl Writer { } } -pub fn write_string(module: &crate::Module, _options: &Options) -> Result { +pub fn write_string(module: &crate::Module, options: Options) -> Result { let mut w = Writer { out: String::new() }; - w.write(module)?; + w.write(module, options)?; Ok(w.out) } diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 47a874969..3371cf5a4 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -9,6 +9,8 @@ const LAST_KNOWN_OPCODE: spirv::Op = spirv::Op::MemberDecorateStringGOOGLE; const LAST_KNOWN_CAPABILITY: spirv::Capability = spirv::Capability::VulkanMemoryModelDeviceScopeKHR; const LAST_KNOWN_EXECUTION_MODEL: spirv::ExecutionModel = spirv::ExecutionModel::Kernel; const LAST_KNOWN_STORAGE_CLASS: spirv::StorageClass = spirv::StorageClass::StorageBuffer; +const LAST_KNOWN_DECORATION: spirv::Decoration = spirv::Decoration::NonUniformEXT; +const LAST_KNOWN_BUILT_IN: spirv::BuiltIn = spirv::BuiltIn::FullyCoveredEXT; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, @@ -36,6 +38,7 @@ pub enum ParseError { InvalidParameter(spirv::Op), InvalidOperandCount(spirv::Op, u16), InvalidOperand, + InvalidDecoration(spirv::Word), InvalidId(spirv::Word), InvalidTypeWidth(spirv::Word), InvalidSign(spirv::Word), @@ -46,6 +49,7 @@ pub enum ParseError { InvalidAccessIndex(crate::Expression), InvalidLoadType(spirv::Word), InvalidStoreType(spirv::Word), + InvalidBinding(spirv::Word), WrongFunctionResultType(spirv::Word), WrongFunctionParameterType(spirv::Word), BadString, @@ -127,11 +131,40 @@ type MemberIndex = u32; #[derive(Debug, Default)] struct Decoration { name: Option, + built_in: Option, + location: Option, + desc_set: Option, + desc_index: Option, } -#[derive(Debug, Default)] -struct MemberDecoration { - name: Option, +impl Decoration { + fn get_binding(&self) -> Option { + //TODO: validate this better + match *self { + Decoration { + built_in: Some(built_in), + location: None, + desc_set: None, + desc_index: None, + .. + } => Some(crate::Binding::BuiltIn(built_in)), + Decoration { + built_in: None, + location: Some(loc), + desc_set: None, + desc_index: None, + .. + } => Some(crate::Binding::Location(loc)), + Decoration { + built_in: None, + location: None, + desc_set: Some(set), + desc_index: Some(binding), + .. + } => Some(crate::Binding::Descriptor { set, binding }), + _ => None, + } + } } #[derive(Debug)] @@ -177,7 +210,7 @@ pub struct Parser { state: ModuleState, temp_bytes: Vec, future_decor: FastHashMap, - future_member_decor: FastHashMap<(spirv::Word, MemberIndex), MemberDecoration>, + future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>, lookup_member_type_id: FastHashMap<(spirv::Word, MemberIndex), spirv::Word>, lookup_type: FastHashMap, lookup_constant: FastHashMap, @@ -246,6 +279,54 @@ impl> Parser { .map_err(|_| ParseError::BadString) } + fn next_decoration( + &mut self, + inst: Instruction, + base_words: u16, + dec: &mut Decoration, + ) -> Result<(), ParseError> { + let raw = self.next()?; + if raw > LAST_KNOWN_DECORATION as spirv::Word { + return Err(ParseError::InvalidDecoration(raw)); + } + let dec_typed = unsafe { + std::mem::transmute::<_, spirv::Decoration>(raw) + }; + log::trace!("\t\t{:?}", dec_typed); + match dec_typed { + spirv::Decoration::BuiltIn => { + inst.expect(base_words + 2)?; + let raw = self.next()?; + if raw > LAST_KNOWN_BUILT_IN as spirv::Word { + log::warn!("Unknown built in {:?}", raw); + } else { + dec.built_in = Some(unsafe { + std::mem::transmute(raw) + }); + } + } + spirv::Decoration::Location => { + inst.expect(base_words + 2)?; + dec.location = Some(self.next()?); + } + spirv::Decoration::DescriptorSet => { + inst.expect(base_words + 2)?; + dec.desc_set = Some(self.next()?); + } + spirv::Decoration::Binding => { + inst.expect(base_words + 2)?; + dec.desc_index = Some(self.next()?); + } + other => { + log::warn!("Unknown decoration {:?}", other); + for _ in base_words + 1 .. inst.wc { + let _var = self.next()?; + } + } + } + Ok(()) + } + fn next_block(&mut self, fun: &mut crate::Function) -> Result<(), ParseError> { loop { use spirv::Op; @@ -626,21 +707,23 @@ impl> Parser { Op::Decorate => { self.switch(ModuleState::Annotation, inst.op)?; inst.expect_at_least(3)?; - let _id = self.next()?; - let _decoration = self.next()?; - for _ in 3 .. inst.wc { - let _var = self.next()?; //TODO - } + let id = self.next()?; + let mut dec = self.future_decor + .remove(&id) + .unwrap_or_default(); + self.next_decoration(inst, 2, &mut dec)?; + self.future_decor.insert(id, dec); } Op::MemberDecorate => { self.switch(ModuleState::Annotation, inst.op)?; inst.expect_at_least(4)?; - let _id = self.next()?; - let _member = self.next()?; - let _decoration = self.next()?; - for _ in 4 .. inst.wc { - let _var = self.next()?; //TODO - } + let id = self.next()?; + let member = self.next()?; + let mut dec = self.future_member_decor + .remove(&(id, member)) + .unwrap_or_default(); + self.next_decoration(inst, 3, &mut dec)?; + self.future_member_decor.insert((id, member), dec); } Op::TypeVoid => { self.switch(ModuleState::Type, inst.op)?; @@ -773,7 +856,7 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(2)?; let id = self.next()?; - let mut decl = crate::StructDeclaration { + let mut sd = crate::StructDeclaration { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -783,14 +866,17 @@ impl> Parser { let type_id = self.next()?; let ty = self.lookup_type.lookup(type_id)?.value.clone(); self.lookup_member_type_id.insert((id, i), type_id); - decl.members.push(crate::StructMember { - name: self.future_member_decor - .remove(&(id, i)) - .and_then(|dec| dec.name), + let dec = self.future_member_decor + .remove(&(id, i)) + .unwrap_or_default(); + let binding = dec.get_binding(); + sd.members.push(crate::StructMember { + name: dec.name, + binding, ty, }); } - let value = crate::Type::Struct(module.struct_declarations.append(decl)); + let value = crate::Type::Struct(module.struct_declarations.append(sd)); self.lookup_type.insert(id, LookupType { value, base_id: None, @@ -860,12 +946,46 @@ impl> Parser { inst.expect(5)?; let _init = self.next()?; //TODO } + let ty = self.lookup_type.lookup(type_id)?.value.clone(); + let dec = self.future_decor + .remove(&id) + .ok_or(ParseError::InvalidBinding(id))?; + let binding = match ty { + crate::Type::Pointer { ref base, class: spirv::StorageClass::Input } | + crate::Type::Pointer { ref base, class: spirv::StorageClass::Output } => { + match **base { + crate::Type::Struct(token) => { + // we don't expect binding decoration on I/O structs, + // but we do expect them on all of the members + let sd = &module.struct_declarations[token]; + for member in sd.members.iter() { + if member.binding.is_none() { + log::warn!("Struct {:?} member {:?} doesn't have a binding", token, member); + return Err(ParseError::InvalidBinding(id)); + } + } + None + } + _ => { + Some(dec + .get_binding() + .ok_or(ParseError::InvalidBinding(id))? + ) + } + } + } + _ => { + Some(dec + .get_binding() + .ok_or(ParseError::InvalidBinding(id))? + ) + } + }; let var = crate::GlobalVariable { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), + name: dec.name, class: map_storage_class(storage)?, - ty: self.lookup_type.lookup(type_id)?.value.clone(), + binding, + ty, }; let token = module.global_variables.append(var); self.lookup_variable.insert(id, LookupVariable { diff --git a/src/lib.rs b/src/lib.rs index 8858dbdb2..3cd990ce6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,6 +42,7 @@ pub enum ScalarKind { #[derive(Debug)] pub struct StructMember { pub name: Option, + pub binding: Option, pub ty: Type, } @@ -69,10 +70,18 @@ pub enum Constant { Float(f64), } +#[derive(Clone, Debug)] +pub enum Binding { + BuiltIn(spirv::BuiltIn), + Location(spirv::Word), + Descriptor { set: spirv::Word, binding: spirv::Word }, +} + #[derive(Clone, Debug)] pub struct GlobalVariable { pub name: Option, pub class: spirv::StorageClass, + pub binding: Option, pub ty: Type, } From 61e0a980c28f494ece6a73a680c48e9ae265aa46 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Feb 2020 10:14:10 -0500 Subject: [PATCH 0021/2212] Move complex types out into a separate struct --- src/back/msl.rs | 176 +++++++++++++++++++++++++++++++++++++-------- src/front/spirv.rs | 99 ++++++++++++++++++++----- src/lib.rs | 32 +++++++-- 3 files changed, 250 insertions(+), 57 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index f04988364..2d0a55bcc 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -1,3 +1,19 @@ +/*! Metal Shading Language (MSL) backend + +## Binding model + +Metal's bindings are flat per resource. Since there isn't an obvious mapping +from SPIR-V's descriptor sets, we require a separate mapping provided in the options. +This mapping may have one or more resource end points for each descriptor set + index +pair. + +## Outputs + +In Metal, built-in shader outputs can not be nested into structures within +the output struct. If there is a structure in the outputs, and it contains any built-ins, +we move them up to the root output structure that we define ourselves. +!*/ + use std::{ fmt::{ Display, Error as FmtError, Formatter, Write, @@ -23,6 +39,8 @@ pub type BindingMap = FastHashMap; enum ResolvedBinding { BuiltIn(spirv::BuiltIn), + Attribute(spirv::Word), + Color(spirv::Word), User { prefix: &'static str, index: spirv::Word }, Resource(BindTarget), } @@ -43,17 +61,28 @@ impl From for Error { } } +#[derive(Clone, Copy, Debug)] +enum LocationMode { + VertexInput, + FragmentOutput, + Intermediate, +} + pub struct Options<'a> { pub binding_map: &'a BindingMap, } impl Options<'_> { - fn resolve_binding(&self, binding: &crate::Binding) -> Result { + fn resolve_binding(&self, binding: &crate::Binding, mode: LocationMode) -> Result { match *binding { crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), - crate::Binding::Location(index) => Ok(ResolvedBinding::User { - prefix: "loc", - index, + crate::Binding::Location(index) => Ok(match mode { + LocationMode::VertexInput => ResolvedBinding::Attribute(index), + LocationMode::FragmentOutput => ResolvedBinding::Color(index), + LocationMode::Intermediate => ResolvedBinding::User { + prefix: "loc", + index, + }, }), crate::Binding::Descriptor { set, binding } => { let source = BindSource { set, binding }; @@ -75,6 +104,14 @@ trait Indexed { fn id(&self) -> usize; } +impl Indexed for crate::Token { + const CLASS: &'static str = "Pointer"; + fn id(&self) -> usize { self.index() } +} +impl Indexed for crate::Token { + const CLASS: &'static str = "Array"; + fn id(&self) -> usize { self.index() } +} impl Indexed for crate::Token { const CLASS: &'static str = "Struct"; fn id(&self) -> usize { self.index() } @@ -163,7 +200,14 @@ impl AsName for Option { } } -struct TypedVar<'a, T>(&'a crate::Type, &'a T, &'a crate::Storage); +struct Starred(T); +impl Display for Starred { + fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { + write!(formatter, "*{}", self.0) + } +} + +struct TypedVar<'a, T>(&'a crate::Type, &'a T, &'a crate::ComplexTypes); impl Display for TypedVar<'_, T> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { match *self.0 { @@ -179,14 +223,17 @@ impl Display for TypedVar<'_, T> { crate::Type::Matrix { columns, rows, kind, .. } => { write!(formatter, "{}{}x{} {}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows), self.1) } - crate::Type::Array { ref base, length } => { - write!(formatter, "{}[{}]", TypedVar(base, self.1, self.2), length) + crate::Type::Pointer(token) => { + let decl = &self.2.pointers[token]; + write!(formatter, "{} {}", decl.name.or_index(token), self.1) } - crate::Type::Pointer { ref base, .. } => { - write!(formatter, "{}*{}", TypedVar(base, &"", self.2), self.1) + crate::Type::Array(token) => { + let decl = &self.2.arrays[token]; + write!(formatter, "{} {}", decl.name.or_index(token), self.1) } crate::Type::Struct(token) => { - write!(formatter, "{} {}", self.2[token].name.or_index(token), self.1) + let decl = &self.2.structs[token]; + write!(formatter, "{} {}", decl.name.or_index(token), self.1) } } } @@ -200,13 +247,19 @@ impl Display for TypedGlobalVariable<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { let var = &self.module.global_variables[self.token]; let name = var.name.or_index(self.token); - let tv = match var.ty { - crate::Type::Pointer { ref base, .. } => { - TypedVar(base, &name, &self.module.struct_declarations) + match var.ty { + crate::Type::Pointer(token) => { + let decl = &self.module.complex_types.pointers[token]; + let ty = match decl.class { + spirv::StorageClass::Input | + spirv::StorageClass::Output => &decl.base, + _ => &var.ty + }; + let tv = TypedVar(ty, &name, &self.module.complex_types); + write!(formatter, "{}", tv) } _ => panic!("Unexpected global type {:?}", var.ty), - }; - write!(formatter, "{}", tv) + } } } @@ -216,13 +269,18 @@ impl Display for ResolvedBinding { ResolvedBinding::BuiltIn(built_in) => { let name = match built_in { spirv::BuiltIn::ClipDistance => "clip_distance", - spirv::BuiltIn::CullDistance => "cull_distance", spirv::BuiltIn::PointSize => "point_size", spirv::BuiltIn::Position => "position", _ => panic!("Built in {:?} is not implemented", built_in), }; formatter.write_str(name) } + ResolvedBinding::Attribute(index) => { + write!(formatter, "attribute({})", index) + } + ResolvedBinding::Color(index) => { + write!(formatter, "color({})", index) + } ResolvedBinding::User { prefix, index } => { write!(formatter, "user({}{})", prefix, index) } @@ -270,15 +328,42 @@ impl Writer { writeln!(self.out, "#include ")?; writeln!(self.out, "using namespace metal;")?; + // write down complex types writeln!(self.out, "")?; - for (token, decl) in module.struct_declarations.iter() { + for (token, decl) in module.complex_types.pointers.iter() { + let name = Starred(decl.name.or_index(token)); + // Input and output are always provided as pointers, + // but we are only interested in the contents. + //TODO: consider resolving this at the root + let class = match decl.class { + spirv::StorageClass::Input | + spirv::StorageClass::Output => continue, + spirv::StorageClass::Uniform => "constant", + other => { + log::warn!("Unexpected pointer class {:?}", other); + "" + } + }; + if let crate::Type::Struct(st) = decl.base { + let var = module.complex_types.structs[st].name.or_index(st); + writeln!(self.out, "struct {}; //forward decl", var)?; + } + let tv = TypedVar(&decl.base, &name, &module.complex_types); + writeln!(self.out, "typedef {} {};", class, tv)?; + } + for (token, decl) in module.complex_types.arrays.iter() { + let name = decl.name.or_index(token); + let tv = TypedVar(&decl.base, &name, &module.complex_types); + writeln!(self.out, "typedef {}[{}];", tv, decl.length)?; + } + for (token, decl) in module.complex_types.structs.iter() { writeln!(self.out, "struct {} {{", decl.name.or_index(token))?; for (index, member) in decl.members.iter().enumerate() { let name = member.name.or_index(MemberIndex(index)); - let tv = TypedVar(&member.ty, &name, &module.struct_declarations); + let tv = TypedVar(&member.ty, &name, &module.complex_types); write!(self.out, "\t{}", tv)?; if let Some(ref binding) = member.binding { - let resolved = options.resolve_binding(binding)?; + let resolved = options.resolve_binding(binding, LocationMode::Intermediate)?; write!(self.out, " [[{}]]", resolved)?; } writeln!(self.out, ";")?; @@ -286,6 +371,7 @@ impl Writer { writeln!(self.out, "}};")?; } + // write down functions let mut uniforms_used = FastHashSet::default(); writeln!(self.out, "")?; for (fun_token, fun) in module.functions.iter() { @@ -309,23 +395,51 @@ impl Writer { let output_name = fun.name.or_index(OutputStructIndex(fun_token)); if let Some(em) = exec_model { writeln!(self.out, "struct {} {{", input_name)?; + let (em_str, in_mode, out_mode) = match em { + spirv::ExecutionModel::Vertex => ("vertex", LocationMode::VertexInput, LocationMode::Intermediate), + spirv::ExecutionModel::Fragment => ("fragment", LocationMode::Intermediate, LocationMode::FragmentOutput), + spirv::ExecutionModel::GLCompute => ("compute", LocationMode::Intermediate, LocationMode::Intermediate), + _ => return Err(Error::UnsupportedExecutionModel(em)), + }; for &token in var_inputs.iter() { - let var = TypedGlobalVariable { module, token }; - writeln!(self.out, "\t{};", var)?; + let var = &module.global_variables[token]; + let tyvar = TypedGlobalVariable { module, token }; + write!(self.out, "\t{}", tyvar)?; + if let Some(ref binding) = var.binding { + let resolved = options.resolve_binding(binding, in_mode)?; + write!(self.out, " [[{}]]", resolved)?; + } + writeln!(self.out, ";")?; } writeln!(self.out, "}};")?; writeln!(self.out, "struct {} {{", output_name)?; for &token in var_outputs.iter() { - let var = TypedGlobalVariable { module, token }; - writeln!(self.out, "\t{};", var)?; + let var = &module.global_variables[token]; + // if it's a struct, lift all the built-in contents up to the root + if let crate::Type::Pointer(pt) = var.ty { + if let crate::Type::Struct(st) = module.complex_types.pointers[pt].base { + let sd = &module.complex_types.structs[st]; + for (index, member) in sd.members.iter().enumerate() { + let name = member.name.or_index(MemberIndex(index)); + let tv = TypedVar(&member.ty, &name, &module.complex_types); + let binding = member.binding + .as_ref() + .ok_or(Error::MissingBinding(token))?; + let resolved = options.resolve_binding(binding, out_mode)?; + writeln!(self.out, "\t{} [[{}]];", tv, resolved)?; + } + continue + } + } + let tyvar = TypedGlobalVariable { module, token }; + write!(self.out, "\t{}", tyvar)?; + if let Some(ref binding) = var.binding { + let resolved = options.resolve_binding(binding, out_mode)?; + write!(self.out, " [[{}]]", resolved)?; + } + writeln!(self.out, ";")?; } writeln!(self.out, "}};")?; - let em_str = match em { - spirv::ExecutionModel::Vertex => "vertex", - spirv::ExecutionModel::Fragment => "fragment", - spirv::ExecutionModel::GLCompute => "compute", - _ => return Err(Error::UnsupportedExecutionModel(em)), - }; write!(self.out, "{} ", em_str)?; } @@ -334,11 +448,11 @@ impl Writer { writeln!(self.out, "{} {}(", output_name, fun_name)?; writeln!(self.out, "\t{} {} [[stage_in]],", input_name, NAME_INPUT)?; } else { - let fun_tv = TypedVar(&fun.return_type, &fun_name, &module.struct_declarations); + let fun_tv = TypedVar(&fun.return_type, &fun_name, &module.complex_types); writeln!(self.out, "{}(", fun_tv)?; for (index, ty) in fun.parameter_types.iter().enumerate() { let name = Name::from(ParameterIndex(index)); - let tv = TypedVar(ty, &name, &module.struct_declarations); + let tv = TypedVar(ty, &name, &module.complex_types); writeln!(self.out, "\t{},", tv)?; } } diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 3371cf5a4..22b28c8bd 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -518,6 +518,32 @@ impl> Parser { fun.body.push(crate::Statement::Return { value: None }); break } + Op::VectorTimesScalar => { + inst.expect(5)?; + let result_type_id = self.next()?; + let (res_size, res_width) = match self.lookup_type.lookup(result_type_id)?.value { + crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), + ref other => return Err(ParseError::UnsupportedType(other.clone())), + }; + let result_id = self.next()?; + let vector_id = self.next()?; + let scalar_id = self.next()?; + let vector_lexp = self.lookup_expression.lookup(vector_id)?; + match self.lookup_type.lookup(vector_lexp.type_id)?.value { + crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } if size == res_size && width == res_width => (), + ref other => return Err(ParseError::UnsupportedType(other.clone())), + }; + let scalar_lexp = self.lookup_expression.lookup(scalar_id)?.clone(); + match self.lookup_type.lookup(scalar_lexp.type_id)?.value { + crate::Type::Scalar { kind: crate::ScalarKind::Float, width } if width == res_width => (), + ref other => return Err(ParseError::UnsupportedType(other.clone())), + }; + let expr = crate::Expression::Mul(vector_lexp.token, scalar_lexp.token); + self.lookup_expression.insert(result_id, LookupExpression { + token: fun.expressions.append(expr), + type_id: result_type_id, + }); + } Op::MatrixTimesVector => { inst.expect(5)?; let result_type_id = self.next()?; @@ -538,10 +564,7 @@ impl> Parser { crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } if size == columns && width == res_width => (), ref other => return Err(ParseError::UnsupportedType(other.clone())), }; - let expr = crate::Expression::MatrixTimesVector { - matrix: matrix_lexp.token, - vector: vector_lexp.token, - }; + let expr = crate::Expression::Mul(matrix_lexp.token, vector_lexp.token); self.lookup_expression.insert(result_id, LookupExpression { token: fun.expressions.append(expr), type_id: result_type_id, @@ -598,7 +621,11 @@ impl> Parser { generator, } }, - struct_declarations: Storage::new(), + complex_types: crate::ComplexTypes { + pointers: Storage::new(), + arrays: Storage::new(), + structs: Storage::new(), + }, global_variables: Storage::new(), functions: Storage::new(), entry_points: Vec::new(), @@ -625,6 +652,7 @@ impl> Parser { } Op::Extension => { self.switch(ModuleState::Extension, inst.op)?; + inst.expect_at_least(2)?; let (name, left) = self.next_string(inst.wc - 1)?; if left != 0 { return Err(ParseError::InvalidOperand); @@ -635,6 +663,7 @@ impl> Parser { } Op::ExtInstImport => { self.switch(ModuleState::Extension, inst.op)?; + inst.expect_at_least(3)?; let _result = self.next()?; let (name, left) = self.next_string(inst.wc - 2)?; if left != 0 { @@ -652,6 +681,7 @@ impl> Parser { } Op::EntryPoint => { self.switch(ModuleState::EntryPoint, inst.op)?; + inst.expect_at_least(4)?; let exec_model = self.next()?; if exec_model > LAST_KNOWN_EXECUTION_MODEL as u32 { return Err(ParseError::UnsupportedExecutionModel(exec_model)); @@ -671,12 +701,26 @@ impl> Parser { }; entry_points.push(ep); } + Op::ExecutionMode => { + self.switch(ModuleState::ExecutionMode, inst.op)?; + inst.expect_at_least(3)?; + let _ep_id = self.next()?; + let _mode = self.next()?; + for _ in 3 .. inst.wc { + let _ = self.next()?; //TODO + } + } Op::Source => { self.switch(ModuleState::Source, inst.op)?; for _ in 1 .. inst.wc { let _ = self.next()?; } } + Op::SourceExtension => { + self.switch(ModuleState::Source, inst.op)?; + inst.expect_at_least(2)?; + let (_name, _) = self.next_string(inst.wc - 1)?; + } Op::Name => { self.switch(ModuleState::Name, inst.op)?; inst.expect_at_least(3)?; @@ -828,12 +872,16 @@ impl> Parser { let id = self.next()?; let storage = self.next()?; let type_id = self.next()?; - let value = crate::Type::Pointer { - base: Box::new(self.lookup_type.lookup(type_id)?.value.clone()), + let pd = crate::PointerDeclaration { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + base: self.lookup_type.lookup(type_id)?.value.clone(), class: map_storage_class(storage)?, }; + let token = module.complex_types.pointers.append(pd); self.lookup_type.insert(id, LookupType { - value, + value: crate::Type::Pointer(token), base_id: Some(type_id), }); } @@ -843,12 +891,16 @@ impl> Parser { let id = self.next()?; let type_id = self.next()?; let length = self.next()?; - let value = crate::Type::Array { - base: Box::new(self.lookup_type.lookup(type_id)?.value.clone()), + let ad = crate::ArrayDeclaration { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + base: self.lookup_type.lookup(type_id)?.value.clone(), length, }; + let token = module.complex_types.arrays.append(ad); self.lookup_type.insert(id, LookupType { - value, + value: crate::Type::Array(token), base_id: Some(type_id), }); } @@ -876,13 +928,14 @@ impl> Parser { ty, }); } - let value = crate::Type::Struct(module.struct_declarations.append(sd)); + let token = module.complex_types.structs.append(sd); self.lookup_type.insert(id, LookupType { - value, + value: crate::Type::Struct(token), base_id: None, }); } - Op::Constant => { + Op::Constant | + Op::SpecConstant => { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(3)?; let type_id = self.next()?; @@ -951,13 +1004,21 @@ impl> Parser { .remove(&id) .ok_or(ParseError::InvalidBinding(id))?; let binding = match ty { - crate::Type::Pointer { ref base, class: spirv::StorageClass::Input } | - crate::Type::Pointer { ref base, class: spirv::StorageClass::Output } => { - match **base { - crate::Type::Struct(token) => { + crate::Type::Pointer(pd) => { + match module.complex_types.pointers[pd] { + crate::PointerDeclaration { + base: crate::Type::Struct(token), + class: spirv::StorageClass::Input, + .. + } | + crate::PointerDeclaration { + base: crate::Type::Struct(token), + class: spirv::StorageClass::Output, + .. + } => { // we don't expect binding decoration on I/O structs, // but we do expect them on all of the members - let sd = &module.struct_declarations[token]; + let sd = &module.complex_types.structs[token]; for member in sd.members.iter() { if member.binding.is_none() { log::warn!("Struct {:?} member {:?} doesn't have a binding", token, member); diff --git a/src/lib.rs b/src/lib.rs index 3cd990ce6..3da37bb36 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -39,6 +39,20 @@ pub enum ScalarKind { Float, } +#[derive(Debug)] +pub struct PointerDeclaration { + pub name: Option, + pub base: Type, + pub class: spirv::StorageClass, +} + +#[derive(Debug)] +pub struct ArrayDeclaration { + pub name: Option, + pub base: Type, + pub length: u32, +} + #[derive(Debug)] pub struct StructMember { pub name: Option, @@ -58,8 +72,8 @@ pub enum Type { Scalar { kind: ScalarKind, width: Bytes }, Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, Matrix { columns: VectorSize, rows: VectorSize, kind: ScalarKind, width: Bytes }, - Pointer { base: Box, class: spirv::StorageClass }, - Array { base: Box, length: u32 }, + Pointer(Token), + Array(Token), Struct(Token), } @@ -104,10 +118,7 @@ pub enum Expression { Load { pointer: Token, }, - MatrixTimesVector { - matrix: Token, - vector: Token, - }, + Mul(Token, Token), } pub type Block = Vec; @@ -156,10 +167,17 @@ pub struct EntryPoint { pub function: Token, } +#[derive(Debug)] +pub struct ComplexTypes { + pub pointers: Storage, + pub arrays: Storage, + pub structs: Storage, +} + #[derive(Debug)] pub struct Module { pub header: Header, - pub struct_declarations: Storage, + pub complex_types: ComplexTypes, pub global_variables: Storage, pub functions: Storage, pub entry_points: Vec, From 20be6876d7449dcdee3687a4d0be3caacb98d876 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Feb 2020 15:20:01 -0500 Subject: [PATCH 0022/2212] [msl] write down expressions --- src/back/msl.rs | 145 ++++++++++++++++++++++++++++++++++++++++++--- src/front/spirv.rs | 1 + src/lib.rs | 1 + 3 files changed, 138 insertions(+), 9 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 2d0a55bcc..4b308d722 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -319,10 +319,122 @@ fn vector_size_string(size: crate::VectorSize) -> &'static str { } } -const NAME_INPUT: &'static str = "input"; -const NAME_OUTPUT: &'static str = "output"; +const NAME_INPUT: &str = "input"; +const NAME_OUTPUT: &str = "output"; +const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; impl Writer { + fn put_expression<'a>( + &mut self, + expr_token: crate::Token, + expressions: &crate::Storage, + module: &crate::Module, + ) -> Result { + let expression = &expressions[expr_token]; + log::trace!("expression {:?}", expression); + match *expression { + crate::Expression::AccessIndex { base, index } => { + match self.put_expression(base, expressions, module)? { + crate::Type::Struct(token) => { + let member = &module.complex_types.structs[token].members[index as usize]; + let name = member.name.or_index(MemberIndex(index as usize)); + write!(self.out, ".{}", name)?; + Ok(member.ty.clone()) + } + crate::Type::Matrix { rows, kind, width, .. } => { + write!(self.out, ".{}", COMPONENTS[index as usize])?; + Ok(crate::Type::Vector { size: rows, kind, width }) + } + crate::Type::Vector { kind, width, .. } => { + write!(self.out, ".{}", COMPONENTS[index as usize])?; + Ok(crate::Type::Scalar { kind, width }) + } + _ => { + write!(self.out, "[{}]", index)?; + Ok(crate::Type::Void) //TODO + } + } + } + crate::Expression::Constant(ref constant) => { + let kind = match *constant { + crate::Constant::Sint(value) => { + write!(self.out, "{}", value)?; + crate::ScalarKind::Sint + } + crate::Constant::Uint(value) => { + write!(self.out, "{}", value)?; + crate::ScalarKind::Uint + } + crate::Constant::Float(value) => { + write!(self.out, "{}", value)?; + crate::ScalarKind::Float + } + }; + let width = 32; //TODO: not sure how to get that... + Ok(crate::Type::Scalar { kind, width }) + } + crate::Expression::Compose { ref ty, ref components } => { + match *ty { + crate::Type::Vector { size, kind, .. } => { + write!(self.out, "{}{}(", scalar_kind_string(kind), vector_size_string(size))?; + for (i, &token) in components.iter().enumerate() { + if i != 0 { + write!(self.out, ",")?; + } + self.put_expression(token, expressions, module)?; + } + write!(self.out, ")")?; + } + _ => panic!("Unsupported compose {:?}", ty), + } + Ok(ty.clone()) + } + crate::Expression::GlobalVariable(token) => { + let var = &module.global_variables[token]; + match var.class { + spirv::StorageClass::Output => { + self.out.write_str(NAME_OUTPUT)?; + if let crate::Type::Pointer(pt) = var.ty { + if let crate::Type::Struct(_) = module.complex_types.pointers[pt].base { + return Ok(module.complex_types.pointers[pt].base.clone()); + } + } + self.out.write_str(".")?; + } + spirv::StorageClass::Input => { + write!(self.out, "{}.", NAME_INPUT)?; + } + _ => () + } + let name = var.name.or_index(token); + write!(self.out, "{}", name)?; + Ok(var.ty.clone()) + } + crate::Expression::Load { pointer } => { + //write!(self.out, "*")?; + match self.put_expression(pointer, expressions, module)? { + crate::Type::Pointer(token) => { + Ok(module.complex_types.pointers[token].base.clone()) + } + other => panic!("Unexpected load pointer {:?}", other), + } + } + crate::Expression::Mul(left, right) => { + write!(self.out, "(")?; + let ty_left = self.put_expression(left, expressions, module)?; + write!(self.out, " * ")?; + let ty_right = self.put_expression(right, expressions, module)?; + write!(self.out, ")")?; + Ok(match (ty_left, ty_right) { + (crate::Type::Vector { size, kind, width }, crate::Type::Scalar { .. }) => + crate::Type::Vector { size, kind, width }, + other => panic!("Unable to infer Mul for {:?}", other), + }) + } + ref other => panic!("Unsupported {:?}", other), + } + } + pub fn write(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; @@ -375,6 +487,8 @@ impl Writer { let mut uniforms_used = FastHashSet::default(); writeln!(self.out, "")?; for (fun_token, fun) in module.functions.iter() { + let fun_name = fun.name.or_index(fun_token); + // find the entry point(s) and inputs/outputs let mut exec_model = None; let mut var_inputs = FastHashSet::default(); let mut var_outputs = FastHashSet::default(); @@ -393,6 +507,7 @@ impl Writer { } let input_name = fun.name.or_index(InputStructIndex(fun_token)); let output_name = fun.name.or_index(OutputStructIndex(fun_token)); + // make dedicated input/output structs if let Some(em) = exec_model { writeln!(self.out, "struct {} {{", input_name)?; let (em_str, in_mode, out_mode) = match em { @@ -440,12 +555,7 @@ impl Writer { writeln!(self.out, ";")?; } writeln!(self.out, "}};")?; - write!(self.out, "{} ", em_str)?; - } - - let fun_name = fun.name.or_index(fun_token); - if exec_model.is_some() { - writeln!(self.out, "{} {}(", output_name, fun_name)?; + writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; writeln!(self.out, "\t{} {} [[stage_in]],", input_name, NAME_INPUT)?; } else { let fun_tv = TypedVar(&fun.return_type, &fun_name, &module.complex_types); @@ -482,8 +592,25 @@ impl Writer { } } writeln!(self.out, ") {{")?; + // write down function body writeln!(self.out, "\t{} {};", output_name, NAME_OUTPUT)?; - writeln!(self.out, "\treturn {};", NAME_OUTPUT)?; + for statement in fun.body.iter() { + log::trace!("statement {:?}", statement); + match *statement { + crate::Statement::Store { pointer, value } => { + //write!(self.out, "\t*")?; + write!(self.out, "\t")?; + self.put_expression(pointer, &fun.expressions, module)?; + write!(self.out, " = ")?; + self.put_expression(value, &fun.expressions, module)?; + writeln!(self.out, ";")?; + } + crate::Statement::Return { value: None } => { + writeln!(self.out, "\treturn {};", NAME_OUTPUT)?; + } + _ => panic!("Unsupported {:?}", statement), + } + } writeln!(self.out, "}}")?; } diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 22b28c8bd..65114474f 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -457,6 +457,7 @@ impl> Parser { components.push(lexp.token); } let expr = crate::Expression::Compose { + ty: self.lookup_type.lookup(result_type_id)?.value.clone(), components, }; self.lookup_expression.insert(id, LookupExpression { diff --git a/src/lib.rs b/src/lib.rs index 3da37bb36..31a9c353c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -111,6 +111,7 @@ pub enum Expression { }, Constant(Constant), Compose { + ty: Type, components: Vec>, }, FunctionParameter(u32), From 515f878fa27b3576f0b0635edfe6f8c07a7ce4ea Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Feb 2020 17:10:42 -0500 Subject: [PATCH 0023/2212] Basic image sampling support --- Cargo.toml | 1 + examples/convert.rs | 6 +- src/back/msl.rs | 80 +++++++++++++++++++---- src/front/spirv.rs | 153 +++++++++++++++++++++++++++++++++++++++++--- src/lib.rs | 33 ++++++++++ 5 files changed, 250 insertions(+), 23 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2a6695e5e..9d98ecec9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ authors = ["Dzmitry Malyshau "] edition = "2018" [dependencies] +bitflags = "1" fxhash = "0.2" log = "0.4" spirv_headers = "1" diff --git a/examples/convert.rs b/examples/convert.rs index a4d017c21..e5ce528aa 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -12,7 +12,11 @@ fn main() { let mut binding_map = naga::back::msl::BindingMap::default(); binding_map.insert( naga::back::msl::BindSource { set: 0, binding: 0 }, - naga::back::msl::BindTarget { buffer: None, texture: None, sampler: None }, + naga::back::msl::BindTarget { buffer: None, texture: Some(1), sampler: None }, + ); + binding_map.insert( + naga::back::msl::BindSource { set: 0, binding: 1 }, + naga::back::msl::BindTarget { buffer: None, texture: None, sampler: Some(1) }, ); let options = naga::back::msl::Options { binding_map: &binding_map, diff --git a/src/back/msl.rs b/src/back/msl.rs index 4b308d722..f5cb016dd 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -49,6 +49,7 @@ enum ResolvedBinding { pub enum Error { Format(FmtError), UnsupportedExecutionModel(spirv::ExecutionModel), + UnexpectedLocation, MixedExecutionModels(crate::Token), MissingBinding(crate::Token), MissingBindTarget(BindSource), @@ -66,6 +67,7 @@ enum LocationMode { VertexInput, FragmentOutput, Intermediate, + Uniform, } pub struct Options<'a> { @@ -76,14 +78,15 @@ impl Options<'_> { fn resolve_binding(&self, binding: &crate::Binding, mode: LocationMode) -> Result { match *binding { crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), - crate::Binding::Location(index) => Ok(match mode { - LocationMode::VertexInput => ResolvedBinding::Attribute(index), - LocationMode::FragmentOutput => ResolvedBinding::Color(index), - LocationMode::Intermediate => ResolvedBinding::User { + crate::Binding::Location(index) => match mode { + LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(index)), + LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(index)), + LocationMode::Intermediate => Ok(ResolvedBinding::User { prefix: "loc", index, - }, - }), + }), + LocationMode::Uniform => Err(Error::UnexpectedLocation), + }, crate::Binding::Descriptor { set, binding } => { let source = BindSource { set, binding }; self.binding_map @@ -116,6 +119,14 @@ impl Indexed for crate::Token { const CLASS: &'static str = "Struct"; fn id(&self) -> usize { self.index() } } +impl Indexed for crate::Token { + const CLASS: &'static str = "Image"; + fn id(&self) -> usize { self.index() } +} +impl Indexed for crate::Token { + const CLASS: &'static str = "Sampler"; + fn id(&self) -> usize { self.index() } +} impl Indexed for crate::Token { const CLASS: &'static str = "global"; fn id(&self) -> usize { self.index() } @@ -235,6 +246,14 @@ impl Display for TypedVar<'_, T> { let decl = &self.2.structs[token]; write!(formatter, "{} {}", decl.name.or_index(token), self.1) } + crate::Type::Image(token) => { + let decl = &self.2.images[token]; + write!(formatter, "{} {}", decl.name.or_index(token), self.1) + } + crate::Type::Sampler(token) => { + let decl = &self.2.samplers[token]; + write!(formatter, "{} {}", decl.name.or_index(token), self.1) + } } } } @@ -252,7 +271,8 @@ impl Display for TypedGlobalVariable<'_> { let decl = &self.module.complex_types.pointers[token]; let ty = match decl.class { spirv::StorageClass::Input | - spirv::StorageClass::Output => &decl.base, + spirv::StorageClass::Output | + spirv::StorageClass::UniformConstant => &decl.base, _ => &var.ty }; let tv = TypedVar(ty, &name, &self.module.complex_types); @@ -288,7 +308,7 @@ impl Display for ResolvedBinding { if let Some(id) = target.buffer { write!(formatter, "buffer({})", id) } else if let Some(id) = target.texture { - write!(formatter, "buffer({})", id) + write!(formatter, "texture({})", id) } else if let Some(id) = target.sampler { write!(formatter, "sampler({})", id) } else { @@ -431,6 +451,18 @@ impl Writer { other => panic!("Unable to infer Mul for {:?}", other), }) } + crate::Expression::ImageSample { image, sampler, coordinate } => { + let ty_image = self.put_expression(image, expressions, module)?; + write!(self.out, ".sample(")?; + self.put_expression(sampler, expressions, module)?; + write!(self.out, ", ")?; + self.put_expression(coordinate, expressions, module)?; + write!(self.out, ")")?; + match ty_image { + crate::Type::Image(token) => Ok(module.complex_types.images[token].ty.clone()), + other => panic!("Unexpected image type {:?}", other), + } + } ref other => panic!("Unsupported {:?}", other), } } @@ -442,6 +474,26 @@ impl Writer { // write down complex types writeln!(self.out, "")?; + for (token, decl) in module.complex_types.images.iter() { + let name = decl.name.or_index(token); + let dim = match decl.dim { + spirv::Dim::Dim1D => "1d", + spirv::Dim::Dim2D => "2d", + spirv::Dim::Dim3D => "3d", + spirv::Dim::DimCube => "Cube", + _ => panic!("Unsupported dim {:?}", decl.dim), + }; + let base = match decl.ty { + crate::Type::Scalar { kind, .. } | + crate::Type::Vector { kind, .. } => scalar_kind_string(kind), + _ => panic!("Unsupported image type {:?}", decl.ty), + }; + writeln!(self.out, "typedef texture{}<{}> {};", dim, base, name)?; + } + for (token, decl) in module.complex_types.samplers.iter() { + let name = decl.name.or_index(token); + writeln!(self.out, "typedef sampler {};", name)?; + } for (token, decl) in module.complex_types.pointers.iter() { let name = Starred(decl.name.or_index(token)); // Input and output are always provided as pointers, @@ -450,7 +502,7 @@ impl Writer { let class = match decl.class { spirv::StorageClass::Input | spirv::StorageClass::Output => continue, - spirv::StorageClass::Uniform => "constant", + spirv::StorageClass::UniformConstant => "constant", other => { log::warn!("Unexpected pointer class {:?}", other); "" @@ -513,7 +565,7 @@ impl Writer { let (em_str, in_mode, out_mode) = match em { spirv::ExecutionModel::Vertex => ("vertex", LocationMode::VertexInput, LocationMode::Intermediate), spirv::ExecutionModel::Fragment => ("fragment", LocationMode::Intermediate, LocationMode::FragmentOutput), - spirv::ExecutionModel::GLCompute => ("compute", LocationMode::Intermediate, LocationMode::Intermediate), + spirv::ExecutionModel::GLCompute => ("compute", LocationMode::Uniform, LocationMode::Uniform), _ => return Err(Error::UnsupportedExecutionModel(em)), }; for &token in var_inputs.iter() { @@ -569,10 +621,14 @@ impl Writer { for (_, expr) in fun.expressions.iter() { if let crate::Expression::GlobalVariable(token) = *expr { let var = &module.global_variables[token]; - if var.class == spirv::StorageClass::Uniform && !uniforms_used.contains(&token) { + if var.class == spirv::StorageClass::UniformConstant && !uniforms_used.contains(&token) { uniforms_used.insert(token); + let binding = var.binding + .as_ref() + .ok_or(Error::MissingBinding(token))?; + let resolved = options.resolve_binding(binding, LocationMode::Uniform)?; let var = TypedGlobalVariable { module, token }; - writeln!(self.out, "\t{},", var)?; + writeln!(self.out, "\t{} [[{}]],", var, resolved)?; } } } diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 65114474f..63ec7e288 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -11,6 +11,7 @@ const LAST_KNOWN_EXECUTION_MODEL: spirv::ExecutionModel = spirv::ExecutionModel: const LAST_KNOWN_STORAGE_CLASS: spirv::StorageClass = spirv::StorageClass::StorageBuffer; const LAST_KNOWN_DECORATION: spirv::Decoration = spirv::Decoration::NonUniformEXT; const LAST_KNOWN_BUILT_IN: spirv::BuiltIn = spirv::BuiltIn::FullyCoveredEXT; +const LAST_KNOWN_DIM: spirv::Dim = spirv::Dim::DimSubpassData; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, @@ -35,6 +36,7 @@ pub enum ParseError { UnsupportedExecutionModel(u32), UnsupportedStorageClass(u32), UnsupportedFunctionControl(u32), + UnsupportedDim(u32), InvalidParameter(spirv::Op), InvalidOperandCount(spirv::Op, u16), InvalidOperand, @@ -205,6 +207,12 @@ struct LookupExpression { type_id: spirv::Word, } +#[derive(Clone, Debug)] +struct LookupSampledImage { + image: Token, + sampler: Token, +} + pub struct Parser { data: I, state: ModuleState, @@ -216,6 +224,7 @@ pub struct Parser { lookup_constant: FastHashMap, lookup_variable: FastHashMap, lookup_expression: FastHashMap, + lookup_sampled_image: FastHashMap, lookup_function_type: FastHashMap, lookup_function: FastHashMap>, } @@ -233,6 +242,7 @@ impl> Parser { lookup_constant: FastHashMap::default(), lookup_variable: FastHashMap::default(), lookup_expression: FastHashMap::default(), + lookup_sampled_image: FastHashMap::default(), lookup_function_type: FastHashMap::default(), lookup_function: FastHashMap::default(), } @@ -571,6 +581,44 @@ impl> Parser { type_id: result_type_id, }); } + Op::SampledImage => { + inst.expect(5)?; + let _result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + let sampler_id = self.next()?; + let image_lexp = self.lookup_expression.lookup(image_id)?; + let sampler_lexp = self.lookup_expression.lookup(sampler_id)?; + //TODO: compare the result type + self.lookup_sampled_image.insert(result_id, LookupSampledImage { + image: image_lexp.token, + sampler: sampler_lexp.token, + }); + } + Op::ImageSampleImplicitLod => { + inst.expect_at_least(5)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let sampled_image_id = self.next()?; + let coordinate_id = self.next()?; + let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + match self.lookup_type.lookup(coord_lexp.type_id)?.value { + crate::Type::Scalar { kind: crate::ScalarKind::Float, .. } | + crate::Type::Vector { kind: crate::ScalarKind::Float, .. } => (), + ref other => return Err(ParseError::UnsupportedType(other.clone())), + } + //TODO: compare the result type + let expr = crate::Expression::ImageSample { + image: si_lexp.image, + sampler: si_lexp.sampler, + coordinate: coord_lexp.token, + }; + self.lookup_expression.insert(result_id, LookupExpression { + token: fun.expressions.append(expr), + type_id: result_type_id, + }); + } _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)), } } @@ -626,6 +674,8 @@ impl> Parser { pointers: Storage::new(), arrays: Storage::new(), structs: Storage::new(), + images: Storage::new(), + samplers: Storage::new(), }, global_variables: Storage::new(), functions: Storage::new(), @@ -873,14 +923,14 @@ impl> Parser { let id = self.next()?; let storage = self.next()?; let type_id = self.next()?; - let pd = crate::PointerDeclaration { + let decl = crate::PointerDeclaration { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), base: self.lookup_type.lookup(type_id)?.value.clone(), class: map_storage_class(storage)?, }; - let token = module.complex_types.pointers.append(pd); + let token = module.complex_types.pointers.append(decl); self.lookup_type.insert(id, LookupType { value: crate::Type::Pointer(token), base_id: Some(type_id), @@ -892,14 +942,14 @@ impl> Parser { let id = self.next()?; let type_id = self.next()?; let length = self.next()?; - let ad = crate::ArrayDeclaration { + let decl = crate::ArrayDeclaration { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), base: self.lookup_type.lookup(type_id)?.value.clone(), length, }; - let token = module.complex_types.arrays.append(ad); + let token = module.complex_types.arrays.append(decl); self.lookup_type.insert(id, LookupType { value: crate::Type::Array(token), base_id: Some(type_id), @@ -909,7 +959,7 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(2)?; let id = self.next()?; - let mut sd = crate::StructDeclaration { + let mut decl = crate::StructDeclaration { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -919,22 +969,104 @@ impl> Parser { let type_id = self.next()?; let ty = self.lookup_type.lookup(type_id)?.value.clone(); self.lookup_member_type_id.insert((id, i), type_id); - let dec = self.future_member_decor + let decor = self.future_member_decor .remove(&(id, i)) .unwrap_or_default(); - let binding = dec.get_binding(); - sd.members.push(crate::StructMember { - name: dec.name, + let binding = decor.get_binding(); + decl.members.push(crate::StructMember { + name: decor.name, binding, ty, }); } - let token = module.complex_types.structs.append(sd); + let token = module.complex_types.structs.append(decl); self.lookup_type.insert(id, LookupType { value: crate::Type::Struct(token), base_id: None, }); } + Op::TypeImage => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(9)?; + + let id = self.next()?; + let sample_type_id = self.next()?; + let dim = self.next()?; + let mut flags = crate::ImageFlags::empty(); + let _is_depth = self.next()?; + if self.next()? != 0 { + flags |= crate::ImageFlags::ARRAYED; + } + if self.next()? != 0 { + flags |= crate::ImageFlags::MULTISAMPLED; + } + let is_sampled = self.next()?; + let _format = self.next()?; + let access = if inst.wc > 9 { + inst.expect(10)?; + self.next()? + } else if is_sampled == 1 { + 0 // read-only + } else { + 2 // read-write + }; + if access == 0 || access == 2 { + flags |= crate::ImageFlags::READABLE; + } + if access == 1 || access == 2 { + flags |= crate::ImageFlags::WRITABLE; + } + let decor = self.future_decor + .remove(&id) + .unwrap_or_default(); + let binding = decor.get_binding(); + + let decl = crate::ImageDeclaration { + name: decor.name, + binding, + ty: self.lookup_type.lookup(sample_type_id)?.value.clone(), + dim: if dim > LAST_KNOWN_DIM as u32 { + return Err(ParseError::UnsupportedDim(dim)); + } else { + unsafe { std::mem::transmute(dim) } + }, + flags, + }; + let token = module.complex_types.images.append(decl); + self.lookup_type.insert(id, LookupType { + value: crate::Type::Image(token), + base_id: Some(sample_type_id), + }); + } + Op::TypeSampledImage => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(3)?; + let id = self.next()?; + let image_id = self.next()?; + self.lookup_type.insert(id, LookupType { + value: self.lookup_type.lookup(image_id)?.value.clone(), + base_id: Some(image_id), + }); + } + Op::TypeSampler => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(2)?; + let id = self.next()?; + let decor = self.future_decor + .remove(&id) + .unwrap_or_default(); + let binding = decor.get_binding(); + + let decl = crate::SamplerDeclaration { + name: decor.name, + binding, + }; + let token = module.complex_types.samplers.append(decl); + self.lookup_type.insert(id, LookupType { + value: crate::Type::Sampler(token), + base_id: None, + }); + } Op::Constant | Op::SpecConstant => { self.switch(ModuleState::Type, inst.op)?; @@ -1119,6 +1251,7 @@ impl> Parser { let token = module.functions.append(fun); self.lookup_function.insert(fun_id, token); self.lookup_expression.clear(); + self.lookup_sampled_image.clear(); } _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)) //TODO diff --git a/src/lib.rs b/src/lib.rs index 31a9c353c..4bda73b8d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -66,6 +66,30 @@ pub struct StructDeclaration { pub members: Vec, } +bitflags::bitflags! { + pub struct ImageFlags: u32 { + const ARRAYED = 0x1; + const MULTISAMPLED = 0x2; + const READABLE = 0x4; + const WRITABLE = 0x8; + } +} + +#[derive(Debug)] +pub struct ImageDeclaration { + pub name: Option, + pub binding: Option, + pub ty: Type, + pub dim: spirv::Dim, + pub flags: ImageFlags, +} + +#[derive(Debug)] +pub struct SamplerDeclaration { + pub name: Option, + pub binding: Option, +} + #[derive(Clone, Debug)] pub enum Type { Void, @@ -75,6 +99,8 @@ pub enum Type { Pointer(Token), Array(Token), Struct(Token), + Image(Token), + Sampler(Token), } #[derive(Clone, Debug)] @@ -120,6 +146,11 @@ pub enum Expression { pointer: Token, }, Mul(Token, Token), + ImageSample { + image: Token, + sampler: Token, + coordinate: Token, + }, } pub type Block = Vec; @@ -173,6 +204,8 @@ pub struct ComplexTypes { pub pointers: Storage, pub arrays: Storage, pub structs: Storage, + pub images: Storage, + pub samplers: Storage, } #[derive(Debug)] From 9ca1312617e171574dbaacf5fb5f9e687e608276 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Feb 2020 17:25:08 -0500 Subject: [PATCH 0024/2212] [spv] rename ParseError to just Error --- src/front/spirv.rs | 168 ++++++++++++++++++++++++--------------------- 1 file changed, 90 insertions(+), 78 deletions(-) diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 63ec7e288..67d606cde 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -1,3 +1,15 @@ +/*! SPIR-V frontend + +## ID lookups + +Our IR links to everything with `Token`, while SPIR-V uses IDs. +In order to keep track of the associations, the parser has many lookup tables. +There map `spirv::Word` into a specific IR token, plus potentially a bit of +extra info, such as the related SPIR-V type ID. +TODO: would be nice to find ways that avoid looking up as much + +!*/ + use crate::{ storage::{Storage, Token}, FastHashMap, @@ -23,7 +35,7 @@ pub const SUPPORTED_EXT_SETS: &[&str] = &[ ]; #[derive(Debug)] -pub enum ParseError { +pub enum Error { InvalidHeader, InvalidWordCount, UnknownInstruction(u16), @@ -64,19 +76,19 @@ struct Instruction { } impl Instruction { - fn expect(&self, count: u16) -> Result<(), ParseError> { + fn expect(&self, count: u16) -> Result<(), Error> { if self.wc == count { Ok(()) } else { - Err(ParseError::InvalidOperandCount(self.op, self.wc)) + Err(Error::InvalidOperandCount(self.op, self.wc)) } } - fn expect_at_least(&self, count: u16) -> Result<(), ParseError> { + fn expect_at_least(&self, count: u16) -> Result<(), Error> { if self.wc >= count { Ok(()) } else { - Err(ParseError::InvalidOperandCount(self.op, self.wc)) + Err(Error::InvalidOperandCount(self.op, self.wc)) } } } @@ -100,29 +112,29 @@ pub enum ModuleState { trait Lookup { type Target; - fn lookup(&self, key: spirv::Word) -> Result<&Self::Target, ParseError>; + fn lookup(&self, key: spirv::Word) -> Result<&Self::Target, Error>; } impl Lookup for FastHashMap { type Target = T; - fn lookup(&self, key: spirv::Word) -> Result<&T, ParseError> { + fn lookup(&self, key: spirv::Word) -> Result<&T, Error> { self.get(&key) - .ok_or(ParseError::InvalidId(key)) + .ok_or(Error::InvalidId(key)) } } -fn map_vector_size(word: spirv::Word) -> Result { +fn map_vector_size(word: spirv::Word) -> Result { match word { 2 => Ok(crate::VectorSize::Bi), 3 => Ok(crate::VectorSize::Tri), 4 => Ok(crate::VectorSize::Quad), - _ => Err(ParseError::InvalidVectorSize(word)) + _ => Err(Error::InvalidVectorSize(word)) } } -fn map_storage_class(word: spirv::Word) -> Result { +fn map_storage_class(word: spirv::Word) -> Result { if word > LAST_KNOWN_STORAGE_CLASS as u32 { - Err(ParseError::UnsupportedStorageClass(word)) + Err(Error::UnsupportedStorageClass(word)) } else { Ok(unsafe { std::mem::transmute(word) }) } @@ -248,18 +260,18 @@ impl> Parser { } } - fn next(&mut self) -> Result { - self.data.next().ok_or(ParseError::IncompleteData) + fn next(&mut self) -> Result { + self.data.next().ok_or(Error::IncompleteData) } - fn next_inst(&mut self) -> Result { + fn next_inst(&mut self) -> Result { let word = self.next()?; let (wc, opcode) = ((word >> 16) as u16, (word & 0xffff) as u16); if wc == 0 { - return Err(ParseError::InvalidWordCount); + return Err(Error::InvalidWordCount); } if opcode > LAST_KNOWN_OPCODE as u16 { - return Err(ParseError::UnknownInstruction(opcode)); + return Err(Error::UnknownInstruction(opcode)); } Ok(Instruction { @@ -270,11 +282,11 @@ impl> Parser { }) } - fn next_string(&mut self, mut count: u16) -> Result<(String, u16), ParseError>{ + fn next_string(&mut self, mut count: u16) -> Result<(String, u16), Error>{ self.temp_bytes.clear(); loop { if count == 0 { - return Err(ParseError::BadString); + return Err(Error::BadString); } count -= 1; let chars = self.next()?.to_le_bytes(); @@ -286,7 +298,7 @@ impl> Parser { } std::str::from_utf8(&self.temp_bytes) .map(|s| (s.to_owned(), count)) - .map_err(|_| ParseError::BadString) + .map_err(|_| Error::BadString) } fn next_decoration( @@ -294,10 +306,10 @@ impl> Parser { inst: Instruction, base_words: u16, dec: &mut Decoration, - ) -> Result<(), ParseError> { + ) -> Result<(), Error> { let raw = self.next()?; if raw > LAST_KNOWN_DECORATION as spirv::Word { - return Err(ParseError::InvalidDecoration(raw)); + return Err(Error::InvalidDecoration(raw)); } let dec_typed = unsafe { std::mem::transmute::<_, spirv::Decoration>(raw) @@ -337,7 +349,7 @@ impl> Parser { Ok(()) } - fn next_block(&mut self, fun: &mut crate::Function) -> Result<(), ParseError> { + fn next_block(&mut self, fun: &mut crate::Function) -> Result<(), Error> { loop { use spirv::Op; let inst = self.next_inst()?; @@ -368,7 +380,7 @@ impl> Parser { match self.lookup_type.lookup(index_expr.type_id)?.value { crate::Type::Scalar { kind: crate::ScalarKind::Uint, .. } | crate::Type::Scalar { kind: crate::ScalarKind::Sint, .. } => (), - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), } log::trace!("\t\t\tlooking up type {:?}", acex.type_id); let ty = self.lookup_type.lookup(acex.type_id)?; @@ -377,7 +389,7 @@ impl> Parser { let index = match fun.expressions[index_expr.token] { crate::Expression::Constant(crate::Constant::Sint(v)) => v as u32, crate::Expression::Constant(crate::Constant::Uint(v)) => v as u32, - ref other => return Err(ParseError::InvalidAccessIndex(other.clone())) + ref other => return Err(Error::InvalidAccessIndex(other.clone())) }; AccessExpression { base_token: fun.expressions.append(crate::Expression::AccessIndex { @@ -386,7 +398,7 @@ impl> Parser { }), type_id: *self.lookup_member_type_id .get(&(acex.type_id, index)) - .ok_or(ParseError::InvalidAccessType(acex.type_id))?, + .ok_or(Error::InvalidAccessType(acex.type_id))?, } } crate::Type::Array { .. } | @@ -398,10 +410,10 @@ impl> Parser { index: index_expr.token, }), type_id: ty.base_id - .ok_or(ParseError::InvalidAccessType(acex.type_id))?, + .ok_or(Error::InvalidAccessType(acex.type_id))?, } } - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), }; } @@ -431,15 +443,15 @@ impl> Parser { crate::Type::Struct(_) => { *self.lookup_member_type_id .get(&(lexp.type_id, index)) - .ok_or(ParseError::InvalidAccessType(lexp.type_id))? + .ok_or(Error::InvalidAccessType(lexp.type_id))? } crate::Type::Array { .. } | crate::Type::Vector { .. } | crate::Type::Matrix { .. } => { ty.base_id - .ok_or(ParseError::InvalidAccessType(lexp.type_id))? + .ok_or(Error::InvalidAccessType(lexp.type_id))? } - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), }; lexp = LookupExpression { token: fun.expressions.append(crate::Expression::AccessIndex { @@ -487,11 +499,11 @@ impl> Parser { let base_expr = self.lookup_expression.lookup(pointer_id)?; let base_type = self.lookup_type.lookup(base_expr.type_id)?; if base_type.base_id != Some(result_type_id) { - return Err(ParseError::InvalidLoadType(result_type_id)); + return Err(Error::InvalidLoadType(result_type_id)); } match base_type.value { crate::Type::Pointer { .. } => (), - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), } let expr = crate::Expression::Load { pointer: base_expr.token, @@ -513,11 +525,11 @@ impl> Parser { let base_type = self.lookup_type.lookup(base_expr.type_id)?; match base_type.value { crate::Type::Pointer { .. } => (), - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), }; let value_expr = self.lookup_expression.lookup(value_id)?; if base_type.base_id != Some(value_expr.type_id) { - return Err(ParseError::InvalidStoreType(value_expr.type_id)); + return Err(Error::InvalidStoreType(value_expr.type_id)); } fun.body.push(crate::Statement::Store { pointer: base_expr.token, @@ -534,7 +546,7 @@ impl> Parser { let result_type_id = self.next()?; let (res_size, res_width) = match self.lookup_type.lookup(result_type_id)?.value { crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), }; let result_id = self.next()?; let vector_id = self.next()?; @@ -542,12 +554,12 @@ impl> Parser { let vector_lexp = self.lookup_expression.lookup(vector_id)?; match self.lookup_type.lookup(vector_lexp.type_id)?.value { crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } if size == res_size && width == res_width => (), - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), }; let scalar_lexp = self.lookup_expression.lookup(scalar_id)?.clone(); match self.lookup_type.lookup(scalar_lexp.type_id)?.value { crate::Type::Scalar { kind: crate::ScalarKind::Float, width } if width == res_width => (), - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), }; let expr = crate::Expression::Mul(vector_lexp.token, scalar_lexp.token); self.lookup_expression.insert(result_id, LookupExpression { @@ -560,7 +572,7 @@ impl> Parser { let result_type_id = self.next()?; let (res_size, res_width) = match self.lookup_type.lookup(result_type_id)?.value { crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), }; let result_id = self.next()?; let matrix_id = self.next()?; @@ -568,12 +580,12 @@ impl> Parser { let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; let columns = match self.lookup_type.lookup(matrix_lexp.type_id)?.value { crate::Type::Matrix { columns, rows, kind: crate::ScalarKind::Float, width } if rows == res_size && width == res_width => columns, - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), }; let vector_lexp = self.lookup_expression.lookup(vector_id)?.clone(); match self.lookup_type.lookup(vector_lexp.type_id)?.value { crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } if size == columns && width == res_width => (), - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), }; let expr = crate::Expression::Mul(matrix_lexp.token, vector_lexp.token); self.lookup_expression.insert(result_id, LookupExpression { @@ -606,7 +618,7 @@ impl> Parser { match self.lookup_type.lookup(coord_lexp.type_id)?.value { crate::Type::Scalar { kind: crate::ScalarKind::Float, .. } | crate::Type::Vector { kind: crate::ScalarKind::Float, .. } => (), - ref other => return Err(ParseError::UnsupportedType(other.clone())), + ref other => return Err(Error::UnsupportedType(other.clone())), } //TODO: compare the result type let expr = crate::Expression::ImageSample { @@ -619,7 +631,7 @@ impl> Parser { type_id: result_type_id, }); } - _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)), + _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } } Ok(()) @@ -646,20 +658,20 @@ impl> Parser { expressions } - fn switch(&mut self, state: ModuleState, op: spirv::Op) -> Result<(), ParseError> { + fn switch(&mut self, state: ModuleState, op: spirv::Op) -> Result<(), Error> { if state < self.state { - return Err(ParseError::UnsupportedInstruction(self.state, op)) + return Err(Error::UnsupportedInstruction(self.state, op)) } else { self.state = state; Ok(()) } } - pub fn parse(&mut self) -> Result { + pub fn parse(&mut self) -> Result { let mut module = crate::Module { header: { if self.next()? != spirv::MAGIC_NUMBER { - return Err(ParseError::InvalidHeader); + return Err(Error::InvalidHeader); } let version_raw = self.next()?.to_le_bytes(); let generator = self.next()?; @@ -692,13 +704,13 @@ impl> Parser { inst.expect(2)?; let capability = self.next()?; if capability > LAST_KNOWN_CAPABILITY as u32 { - return Err(ParseError::UnknownCapability(capability)); + return Err(Error::UnknownCapability(capability)); } let cap = unsafe { std::mem::transmute(capability) }; if !SUPPORTED_CAPABILITIES.contains(&cap) { - return Err(ParseError::UnsupportedCapability(cap)); + return Err(Error::UnsupportedCapability(cap)); } } Op::Extension => { @@ -706,10 +718,10 @@ impl> Parser { inst.expect_at_least(2)?; let (name, left) = self.next_string(inst.wc - 1)?; if left != 0 { - return Err(ParseError::InvalidOperand); + return Err(Error::InvalidOperand); } if !SUPPORTED_EXTENSIONS.contains(&name.as_str()) { - return Err(ParseError::UnsupportedExtension(name.to_owned())); + return Err(Error::UnsupportedExtension(name.to_owned())); } } Op::ExtInstImport => { @@ -718,10 +730,10 @@ impl> Parser { let _result = self.next()?; let (name, left) = self.next_string(inst.wc - 2)?; if left != 0 { - return Err(ParseError::InvalidOperand) + return Err(Error::InvalidOperand) } if !SUPPORTED_EXT_SETS.contains(&name.as_str()) { - return Err(ParseError::UnsupportedExtSet(name.to_owned())); + return Err(Error::UnsupportedExtSet(name.to_owned())); } } Op::MemoryModel => { @@ -735,7 +747,7 @@ impl> Parser { inst.expect_at_least(4)?; let exec_model = self.next()?; if exec_model > LAST_KNOWN_EXECUTION_MODEL as u32 { - return Err(ParseError::UnsupportedExecutionModel(exec_model)); + return Err(Error::UnsupportedExecutionModel(exec_model)); } let function_id = self.next()?; let (name, left) = self.next_string(inst.wc - 3)?; @@ -778,7 +790,7 @@ impl> Parser { let id = self.next()?; let (name, left) = self.next_string(inst.wc - 2)?; if left != 0 { - return Err(ParseError::InvalidOperand); + return Err(Error::InvalidOperand); } self.future_decor .entry(id) @@ -792,7 +804,7 @@ impl> Parser { let member = self.next()?; let (name, left) = self.next_string(inst.wc - 3)?; if left != 0 { - return Err(ParseError::InvalidOperand); + return Err(Error::InvalidOperand); } self.future_member_decor .entry((id, member)) @@ -840,11 +852,11 @@ impl> Parser { kind: match sign { 0 => crate::ScalarKind::Uint, 1 => crate::ScalarKind::Sint, - _ => return Err(ParseError::InvalidSign(sign)), + _ => return Err(Error::InvalidSign(sign)), }, width: width .try_into() - .map_err(|_| ParseError::InvalidTypeWidth(width))?, + .map_err(|_| Error::InvalidTypeWidth(width))?, }, base_id: None, }); @@ -859,7 +871,7 @@ impl> Parser { kind: crate::ScalarKind::Float, width: width .try_into() - .map_err(|_| ParseError::InvalidTypeWidth(width))?, + .map_err(|_| Error::InvalidTypeWidth(width))?, }, base_id: None, }); @@ -871,7 +883,7 @@ impl> Parser { let type_id = self.next()?; let (kind, width) = match self.lookup_type.lookup(type_id)?.value { crate::Type::Scalar { kind, width } => (kind, width), - _ => return Err(ParseError::InvalidInnerType(type_id)), + _ => return Err(Error::InvalidInnerType(type_id)), }; let component_count = self.next()?; self.lookup_type.insert(id, LookupType { @@ -891,7 +903,7 @@ impl> Parser { let num_columns = self.next()?; let (rows, kind, width) = match self.lookup_type.lookup(vector_type_id)?.value { crate::Type::Vector { size, kind, width } => (size, kind, width), - _ => return Err(ParseError::InvalidInnerType(vector_type_id)), + _ => return Err(Error::InvalidInnerType(vector_type_id)), }; self.lookup_type.insert(id, LookupType { value: crate::Type::Matrix { @@ -1026,7 +1038,7 @@ impl> Parser { binding, ty: self.lookup_type.lookup(sample_type_id)?.value.clone(), dim: if dim > LAST_KNOWN_DIM as u32 { - return Err(ParseError::UnsupportedDim(dim)); + return Err(Error::UnsupportedDim(dim)); } else { unsafe { std::mem::transmute(dim) } }, @@ -1087,7 +1099,7 @@ impl> Parser { crate::Type::Scalar { kind: crate::ScalarKind::Sint, width } => { let low = self.next()?; let high = if width < 32 { - return Err(ParseError::InvalidTypeWidth(width as u32)); + return Err(Error::InvalidTypeWidth(width as u32)); } else if width > 32 { inst.expect(4)?; self.next()? @@ -1101,7 +1113,7 @@ impl> Parser { crate::Type::Scalar { kind: crate::ScalarKind::Float, width } => { let low = self.next()?; let extended = if width < 32 { - return Err(ParseError::InvalidTypeWidth(width as u32)); + return Err(Error::InvalidTypeWidth(width as u32)); } else if width > 32 { inst.expect(4)?; let high = self.next()?; @@ -1115,7 +1127,7 @@ impl> Parser { }; crate::Constant::Float(extended) } - ref other => return Err(ParseError::UnsupportedType(other.clone())) + ref other => return Err(Error::UnsupportedType(other.clone())) }; self.lookup_constant.insert(id, LookupConstant { value, @@ -1135,7 +1147,7 @@ impl> Parser { let ty = self.lookup_type.lookup(type_id)?.value.clone(); let dec = self.future_decor .remove(&id) - .ok_or(ParseError::InvalidBinding(id))?; + .ok_or(Error::InvalidBinding(id))?; let binding = match ty { crate::Type::Pointer(pd) => { match module.complex_types.pointers[pd] { @@ -1155,7 +1167,7 @@ impl> Parser { for member in sd.members.iter() { if member.binding.is_none() { log::warn!("Struct {:?} member {:?} doesn't have a binding", token, member); - return Err(ParseError::InvalidBinding(id)); + return Err(Error::InvalidBinding(id)); } } None @@ -1163,7 +1175,7 @@ impl> Parser { _ => { Some(dec .get_binding() - .ok_or(ParseError::InvalidBinding(id))? + .ok_or(Error::InvalidBinding(id))? ) } } @@ -1171,7 +1183,7 @@ impl> Parser { _ => { Some(dec .get_binding() - .ok_or(ParseError::InvalidBinding(id))? + .ok_or(Error::InvalidBinding(id))? ) } }; @@ -1197,14 +1209,14 @@ impl> Parser { let mut fun = { let ft = self.lookup_function_type.lookup(fun_type)?.clone(); if ft.return_type_id != result_type { - return Err(ParseError::WrongFunctionResultType(result_type)) + return Err(Error::WrongFunctionResultType(result_type)) } crate::Function { name: self.future_decor .remove(&fun_id) .and_then(|dec| dec.name), control: spirv::FunctionControl::from_bits(fun_control) - .ok_or(ParseError::UnsupportedFunctionControl(fun_control))?, + .ok_or(Error::UnsupportedFunctionControl(fun_control))?, parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), return_type: self.lookup_type.lookup(result_type)?.value.clone(), expressions: self.make_expression_storage(), @@ -1222,12 +1234,12 @@ impl> Parser { .lookup(fun_type)? .parameter_type_ids[i] { - return Err(ParseError::WrongFunctionParameterType(type_id)) + return Err(Error::WrongFunctionParameterType(type_id)) } let ty = self.lookup_type.lookup(type_id)?.value.clone(); fun.parameter_types.push(ty); } - Instruction { op, .. } => return Err(ParseError::InvalidParameter(op)), + Instruction { op, .. } => return Err(Error::InvalidParameter(op)), } } // read body @@ -1244,7 +1256,7 @@ impl> Parser { fun_inst.expect(1)?; break } - _ => return Err(ParseError::UnsupportedInstruction(self.state, fun_inst.op)) + _ => return Err(Error::UnsupportedInstruction(self.state, fun_inst.op)) } } // done @@ -1253,7 +1265,7 @@ impl> Parser { self.lookup_expression.clear(); self.lookup_sampled_image.clear(); } - _ => return Err(ParseError::UnsupportedInstruction(self.state, inst.op)) + _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)) //TODO } } @@ -1281,7 +1293,7 @@ impl> Parser { match module.global_variables[token].class { spirv::StorageClass::Input => ep.inputs.push(token), spirv::StorageClass::Output => ep.outputs.push(token), - other => return Err(ParseError::InvalidVariableClass(other)) + other => return Err(Error::InvalidVariableClass(other)) } } module.entry_points.push(ep); @@ -1291,9 +1303,9 @@ impl> Parser { } } -pub fn parse_u8_slice(data: &[u8]) -> Result { +pub fn parse_u8_slice(data: &[u8]) -> Result { if data.len() % 4 != 0 { - return Err(ParseError::IncompleteData); + return Err(Error::IncompleteData); } let words = data From 8c4e60eb815446f8f40f6e5941f68abadbe90e91 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Feb 2020 23:28:18 -0500 Subject: [PATCH 0025/2212] Add DXIR to readme, more badges --- Cargo.toml | 5 +++++ README.md | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 9d98ecec9..125014f06 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,11 @@ name = "naga" version = "0.1.0" authors = ["Dzmitry Malyshau "] edition = "2018" +description = "Shader translation infrastructure" +homepage = "https://github.com/gfx-rs/naga" +repository = "https://github.com/gfx-rs/naga" +keywords = ["shader", "SPIR-V"] +license = "MPL-2.0" [dependencies] bitflags = "1" diff --git a/README.md b/README.md index d298c2447..cdb0b3164 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # Naga [![Matrix](https://img.shields.io/badge/Matrix-%23gfx%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#gfx:matrix.org) +[![Crates.io](https://img.shields.io/crates/v/naga.svg?label=naga)](https://crates.io/crates/naga) +[![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga) [![Build Status](https://travis-ci.org/gfx-rs/naga.svg?branch=master)](https://travis-ci.org/gfx-rs/naga) This is an experimental shader translation library for the needs of gfx-rs project and WebGPU. It's meant to provide a safe and performant way of converting to and from SPIR-V. @@ -22,5 +24,6 @@ MSL | :construction: | | HLSL | | | GLSL | | | AIR | | | -DXBC | | | +DXIR | | | DXIL | | | +DXBC | | | From 246ca018efa844b88e1cb4b4c5fc6d92455e659e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 28 Feb 2020 13:05:24 -0500 Subject: [PATCH 0026/2212] [tint] beginning of the front-end based on Pest (#9) --- Cargo.toml | 2 + README.md | 4 +- examples/convert.rs | 51 +++++++++++------ grammars/wgsl.pest | 90 ++++++++++++++++++++++++++++++ src/front/mod.rs | 30 ++++++++++ src/front/spirv.rs | 38 +++++-------- src/front/wgsl.rs | 132 ++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 4 +- 8 files changed, 306 insertions(+), 45 deletions(-) create mode 100644 grammars/wgsl.pest create mode 100644 src/front/wgsl.rs diff --git a/Cargo.toml b/Cargo.toml index 125014f06..8db524e08 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,8 @@ license = "MPL-2.0" bitflags = "1" fxhash = "0.2" log = "0.4" +pest = "2" +pest_derive = "2" spirv_headers = "1" [dev-dependencies] diff --git a/README.md b/README.md index cdb0b3164..a18d882e1 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,14 @@ This is an experimental shader translation library for the needs of gfx-rs proje Front-end | Status | Notes | --------------- | ------------------ | ----- | SPIR-V (binary) | :construction: | | -Tint | | | +WGSL (Tint) | :construction: | | GLSL (Vulkan) | | | Rust | | | Back-end | Status | Notes | --------------- | ------------------ | ----- | SPIR-V (binary) | | | -Tint | | | +WGSL | | | MSL | :construction: | | HLSL | | | GLSL | | | diff --git a/examples/convert.rs b/examples/convert.rs index e5ce528aa..f10909462 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -4,23 +4,40 @@ fn main() { env_logger::init(); let args = env::args().collect::>(); - let input = fs::read(&args[1]).unwrap(); - let module = naga::front::spirv::parse_u8_slice(&input).unwrap(); - //println!("{:?}", module); - - let mut binding_map = naga::back::msl::BindingMap::default(); - binding_map.insert( - naga::back::msl::BindSource { set: 0, binding: 0 }, - naga::back::msl::BindTarget { buffer: None, texture: Some(1), sampler: None }, - ); - binding_map.insert( - naga::back::msl::BindSource { set: 0, binding: 1 }, - naga::back::msl::BindTarget { buffer: None, texture: None, sampler: Some(1) }, - ); - let options = naga::back::msl::Options { - binding_map: &binding_map, + let module = if args.len() <= 1 { + println!("Call with "); + return + } else if args[1].ends_with(".spv") { + let input = fs::read(&args[1]).unwrap(); + naga::front::spirv::parse_u8_slice(&input).unwrap() + } else if args[1].ends_with(".wgsl") { + let input = fs::read_to_string(&args[1]).unwrap(); + naga::front::wgsl::parse_str(&input).unwrap() + } else { + panic!("Unknown input: {:?}", args[1]); }; - let msl = naga::back::msl::write_string(&module, options).unwrap(); - println!("{}", msl); + + if args.len() <= 2 { + println!("{:?}", module); + return + } else if args[2].ends_with(".msl") { + use naga::back::msl; + let mut binding_map = msl::BindingMap::default(); + binding_map.insert( + msl::BindSource { set: 0, binding: 0 }, + msl::BindTarget { buffer: None, texture: Some(1), sampler: None }, + ); + binding_map.insert( + msl::BindSource { set: 0, binding: 1 }, + msl::BindTarget { buffer: None, texture: None, sampler: Some(1) }, + ); + let options = msl::Options { + binding_map: &binding_map, + }; + let msl = msl::write_string(&module, options).unwrap(); + fs::write(&args[2], msl).unwrap(); + } else { + panic!("Unknown output: {:?}", args[2]); + } } diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest new file mode 100644 index 000000000..831dd9910 --- /dev/null +++ b/grammars/wgsl.pest @@ -0,0 +1,90 @@ +translation_unit = _{ SOI ~ global_decl* ~ EOI } + +global_decl = { + ";" + | import_decl ~ ";" + | global_variable_decl ~ ";" +// | global_constant_decl SEMICOLON +// | entry_point_decl SEMICOLON +// | type_alias SEMICOLON +// | function_decl +} + +import_decl = { "import" ~ string ~ "as" ~ (ident ~ "::")* ~ ident} + +global_variable_decl = { + variable_decoration_list ~ variable_decl + | variable_decoration_list ~ variable_decl ~ "=" ~ const_expr +} + +variable_decoration_list = { "[[" ~ (variable_decoration ~ ",")* ~ variable_decoration ~ "]]" } + +variable_decoration = { + "location" ~ int_literal +// | BUILTIN builtin_decoration +// | BINDING INT_LITERAL +// | SET INT_LITERAL +} + +variable_decl = { "var" ~ variable_storage_decoration? ~ variable_ident_decl } +variable_storage_decoration = _{ "<" ~ storage_class ~ ">" } +variable_ident_decl = { ident ~ ":" ~ type_decl } + +storage_class = { + "in" + | "out" + | "uniform" +// | WORKGROUP +// | UNIFORM_CONSTANT +// | STORAGE_BUFFER +// | IMAGE +// | PUSH_CONSTANT + | "private" + | "function" +} + +const_literal = { + int_literal +// | UINT_LITERAL +// | FLOAT_LITERAL + | "true" + | "false" +} + +const_expr = { + type_decl ~ "(" ~ (const_expr ~ ",")? ~ const_expr ~ ")" + | const_literal +} + +type_decl = { + scalar_type +// | VEC2 LESS_THAN type_decl GREATER_THAN +// | VEC3 LESS_THAN type_decl GREATER_THAN +// | VEC3 LESS_THAN type_decl GREATER_THAN +// | PTR LESS_THAN storage_class, type_decl GREATER_THAN +// | ARRAY LESS_THAN type_decl COMMA INT_LITERAL GREATER_THAN +// | ARRAY LESS_THAN type_decl GREATER_THAN +// | MAT2x2 LESS_THAN type_decl GREATER_THAN +// | MAT2x3 LESS_THAN type_decl GREATER_THAN +// | MAT2x4 LESS_THAN type_decl GREATER_THAN +// | MAT3x2 LESS_THAN type_decl GREATER_THAN +// | MAT3x3 LESS_THAN type_decl GREATER_THAN +// | MAT3x4 LESS_THAN type_decl GREATER_THAN +// | MAT4x2 LESS_THAN type_decl GREATER_THAN +// | MAT4x3 LESS_THAN type_decl GREATER_THAN +// | MAT4x4 LESS_THAN type_decl GREATER_THAN + | ident +} + +scalar_type = { + "bool" + | "f32" + | "i32" + | "u32" +} + +ident = @{ ASCII_ALPHA ~ (ASCII_ALPHANUMERIC | "_")* } +int_literal = @{ ("-"? ~ "0x"? ~ (ASCII_DIGIT | 'a'..'f' | 'A'..'F')+) | "0" | ("-"? ~ '1'..'9' ~ ASCII_DIGIT*) } +string = @{ "\"" ~ ( "\"\"" | (!"\"" ~ ANY) )* ~ "\"" } + +WHITESPACE = _{ " " | "\t" | "\n" } diff --git a/src/front/mod.rs b/src/front/mod.rs index e4919e773..9c549d16c 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1 +1,31 @@ pub mod spirv; +pub mod wgsl; + +use crate::storage::Storage; + +pub const GENERATOR: u32 = 0; + +impl crate::Module { + fn from_header(header: crate::Header) -> Self { + crate::Module { + header, + complex_types: crate::ComplexTypes { + pointers: Storage::new(), + arrays: Storage::new(), + structs: Storage::new(), + images: Storage::new(), + samplers: Storage::new(), + }, + global_variables: Storage::new(), + functions: Storage::new(), + entry_points: Vec::new(), + } + } + + fn generate_empty() -> Self { + Self::from_header(crate::Header { + version: (1, 0, 0), + generator: GENERATOR, + }) + } +} diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 67d606cde..77daeec19 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -668,31 +668,19 @@ impl> Parser { } pub fn parse(&mut self) -> Result { - let mut module = crate::Module { - header: { - if self.next()? != spirv::MAGIC_NUMBER { - return Err(Error::InvalidHeader); - } - let version_raw = self.next()?.to_le_bytes(); - let generator = self.next()?; - let _bound = self.next()?; - let _schema = self.next()?; - crate::Header { - version: (version_raw[2], version_raw[1], version_raw[0]), - generator, - } - }, - complex_types: crate::ComplexTypes { - pointers: Storage::new(), - arrays: Storage::new(), - structs: Storage::new(), - images: Storage::new(), - samplers: Storage::new(), - }, - global_variables: Storage::new(), - functions: Storage::new(), - entry_points: Vec::new(), - }; + let mut module = crate::Module::from_header({ + if self.next()? != spirv::MAGIC_NUMBER { + return Err(Error::InvalidHeader); + } + let version_raw = self.next()?.to_le_bytes(); + let generator = self.next()?; + let _bound = self.next()?; + let _schema = self.next()?; + crate::Header { + version: (version_raw[2], version_raw[1], version_raw[0]), + generator, + } + }); let mut entry_points = Vec::new(); while let Ok(inst) = self.next_inst() { diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs new file mode 100644 index 000000000..12f3c1559 --- /dev/null +++ b/src/front/wgsl.rs @@ -0,0 +1,132 @@ +#[derive(Parser)] +#[grammar = "../grammars/wgsl.pest"] +struct Tokenizer; + +#[derive(Debug)] +pub enum Error { + Pest(pest::error::Error), + BadInt(std::num::ParseIntError), + BadStorageClass(String), +} +impl From> for Error { + fn from(error: pest::error::Error) -> Self { + Error::Pest(error) + } +} +impl From for Error { + fn from(error: std::num::ParseIntError) -> Self { + Error::BadInt(error) + } +} + +pub struct Parser { +} + +impl Parser { + fn parse_uint_literal(pair: pest::iterators::Pair) -> Result { + Ok(pair.as_str().parse()?) + } + + fn _parse_int_literal(pair: pest::iterators::Pair) -> Result { + let istr = pair.as_str(); + let (sign, istr) = match &istr[..1] { + "_" => (-1, &istr[1..]), + _ => (1, &istr[..]), + }; + let integer: i32 = istr.parse()?; + Ok(sign * integer) + } + + fn parse_decoration_list(variable_decoration_list: pest::iterators::Pair) -> Result, Error> { + assert_eq!(variable_decoration_list.as_rule(), Rule::variable_decoration_list); + for variable_decoration in variable_decoration_list.into_inner() { + assert_eq!(variable_decoration.as_rule(), Rule::variable_decoration); + let mut inner = variable_decoration.into_inner(); + let first = inner.next().unwrap(); + match first.as_rule() { + Rule::int_literal => { + let location = Self::parse_uint_literal(first)?; + return Ok(Some(crate::Binding::Location(location))); + } + unknown => panic!("Unexpected decoration: {:?}", unknown), + } + } + unimplemented!() + } + + fn parse_storage_class(storage_class: pest::iterators::Pair) -> Result { + match storage_class.as_str() { + "in" => Ok(spirv::StorageClass::Input), + "out" => Ok(spirv::StorageClass::Output), + other => Err(Error::BadStorageClass(other.to_owned())), + } + } + + fn parse_type_decl(type_decl: pest::iterators::Pair) -> Result { + assert_eq!(type_decl.as_rule(), Rule::type_decl); + let inner = type_decl.into_inner().next().unwrap(); + match inner.as_rule() { + Rule::scalar_type => match inner.as_str() { + "f32" => Ok(crate::Type::Scalar { kind: crate::ScalarKind::Float, width: 32 }), + "i32" => Ok(crate::Type::Scalar { kind: crate::ScalarKind::Sint, width: 32 }), + "u32" => Ok(crate::Type::Scalar { kind: crate::ScalarKind::Uint, width: 32 }), + other => panic!("Unexpected scalar {:?}", other), + }, + Rule::ident => unimplemented!(), + other => panic!("Unexpected type {:?}", other), + } + } + + pub fn parse(&mut self, source: &str) -> Result { + use pest::Parser as _; + let pairs = Tokenizer::parse(Rule::translation_unit, source)?; + let mut module = crate::Module::generate_empty(); + for global_decl_maybe in pairs { + match global_decl_maybe.as_rule() { + Rule::global_decl => { + let global_decl = global_decl_maybe.into_inner().next().unwrap(); + match global_decl.as_rule() { + Rule::import_decl => { + let mut import_decl = global_decl.into_inner(); + let path = import_decl.next().unwrap().as_str(); + log::warn!("Ignoring import {:?}", path); + } + Rule::global_variable_decl => { + let mut global_decl_pairs = global_decl.into_inner(); + let binding = Self::parse_decoration_list(global_decl_pairs.next().unwrap())?; + let var_decl = global_decl_pairs.next().unwrap(); + assert_eq!(var_decl.as_rule(), Rule::variable_decl); + let mut var_decl_pairs = var_decl.into_inner(); + let mut body = var_decl_pairs.next().unwrap(); + let class = if body.as_rule() == Rule::storage_class { + let class = Self::parse_storage_class(body)?; + body = var_decl_pairs.next().unwrap(); + class + } else { + spirv::StorageClass::Private + }; + assert_eq!(body.as_rule(), Rule::variable_ident_decl); + let mut var_ident_decl_pairs = body.into_inner(); + let name = var_ident_decl_pairs.next().unwrap().as_str().to_owned(); + let ty = Self::parse_type_decl(var_ident_decl_pairs.next().unwrap())?; + module.global_variables.append(crate::GlobalVariable { + name: Some(name), + class, + binding, + ty, + }); + } + unknown => panic!("Unexpected global decl: {:?}", unknown), + } + } + Rule::EOI => break, + unknown => panic!("Unexpected: {:?}", unknown), + } + } + Ok(module) + } +} + +pub fn parse_str(source: &str) -> Result { + Parser{}.parse(source) +} diff --git a/src/lib.rs b/src/lib.rs index 4bda73b8d..5ab2f8676 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +#[macro_use] +extern crate pest_derive; extern crate spirv_headers as spirv; pub mod back; @@ -15,7 +17,7 @@ use std::{ type FastHashMap = HashMap>; type FastHashSet = HashSet>; -#[derive(Debug)] +#[derive(Clone, Debug)] pub struct Header { pub version: (u8, u8, u8), pub generator: u32, From 2f0540c6ab4526007a5f5479ad543be9a9c6df4e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 2 Mar 2020 16:37:56 -0500 Subject: [PATCH 0027/2212] Flat type structure (#10) --- src/back/msl.rs | 324 +++++++++++++++++++-------------------- src/front/mod.rs | 9 +- src/front/spirv.rs | 369 +++++++++++++++++++++++++-------------------- src/front/wgsl.rs | 28 ++-- src/lib.rs | 80 +++------- 5 files changed, 408 insertions(+), 402 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index f5cb016dd..0111bf631 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -20,7 +20,10 @@ use std::{ }, }; -use crate::{FastHashMap, FastHashSet}; +use crate::{ + storage::Token, + FastHashMap, FastHashSet +}; #[derive(Clone, Debug, PartialEq)] pub struct BindTarget { @@ -107,24 +110,8 @@ trait Indexed { fn id(&self) -> usize; } -impl Indexed for crate::Token { - const CLASS: &'static str = "Pointer"; - fn id(&self) -> usize { self.index() } -} -impl Indexed for crate::Token { - const CLASS: &'static str = "Array"; - fn id(&self) -> usize { self.index() } -} -impl Indexed for crate::Token { - const CLASS: &'static str = "Struct"; - fn id(&self) -> usize { self.index() } -} -impl Indexed for crate::Token { - const CLASS: &'static str = "Image"; - fn id(&self) -> usize { self.index() } -} -impl Indexed for crate::Token { - const CLASS: &'static str = "Sampler"; +impl Indexed for crate::Token { + const CLASS: &'static str = "Type"; fn id(&self) -> usize { self.index() } } impl Indexed for crate::Token { @@ -218,46 +205,6 @@ impl Display for Starred { } } -struct TypedVar<'a, T>(&'a crate::Type, &'a T, &'a crate::ComplexTypes); -impl Display for TypedVar<'_, T> { - fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - match *self.0 { - crate::Type::Void => { - write!(formatter, "void {}", self.1) - }, - crate::Type::Scalar { kind, .. } => { - write!(formatter, "{} {}", scalar_kind_string(kind), self.1) - }, - crate::Type::Vector { size, kind, .. } => { - write!(formatter, "{}{} {}", scalar_kind_string(kind), vector_size_string(size), self.1) - }, - crate::Type::Matrix { columns, rows, kind, .. } => { - write!(formatter, "{}{}x{} {}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows), self.1) - } - crate::Type::Pointer(token) => { - let decl = &self.2.pointers[token]; - write!(formatter, "{} {}", decl.name.or_index(token), self.1) - } - crate::Type::Array(token) => { - let decl = &self.2.arrays[token]; - write!(formatter, "{} {}", decl.name.or_index(token), self.1) - } - crate::Type::Struct(token) => { - let decl = &self.2.structs[token]; - write!(formatter, "{} {}", decl.name.or_index(token), self.1) - } - crate::Type::Image(token) => { - let decl = &self.2.images[token]; - write!(formatter, "{} {}", decl.name.or_index(token), self.1) - } - crate::Type::Sampler(token) => { - let decl = &self.2.samplers[token]; - write!(formatter, "{} {}", decl.name.or_index(token), self.1) - } - } - } -} - struct TypedGlobalVariable<'a> { module: &'a crate::Module, token: crate::Token, @@ -266,17 +213,17 @@ impl Display for TypedGlobalVariable<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { let var = &self.module.global_variables[self.token]; let name = var.name.or_index(self.token); - match var.ty { - crate::Type::Pointer(token) => { - let decl = &self.module.complex_types.pointers[token]; - let ty = match decl.class { + let ty = &self.module.types[var.ty]; + match ty.inner { + crate::TypeInner::Pointer { base, class } => { + let ty_token = match class { spirv::StorageClass::Input | spirv::StorageClass::Output | - spirv::StorageClass::UniformConstant => &decl.base, - _ => &var.ty + spirv::StorageClass::UniformConstant => base, + _ => var.ty }; - let tv = TypedVar(ty, &name, &self.module.complex_types); - write!(formatter, "{}", tv) + let ty_name = self.module.types[ty_token].name.or_index(ty_token); + write!(formatter, "{} {}", ty_name, name) } _ => panic!("Unexpected global type {:?}", var.ty), } @@ -343,59 +290,83 @@ const NAME_INPUT: &str = "input"; const NAME_OUTPUT: &str = "output"; const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; +#[derive(Debug)] +enum MaybeOwned<'a, T: 'a> { + Borrowed(&'a T), + Owned(T), +} + +impl MaybeOwned<'_, T> { + fn borrow(&self) -> &T { + match *self { + MaybeOwned::Borrowed(inner) => inner, + MaybeOwned::Owned(ref inner) => inner, + } + } +} + +impl crate::Module { + fn borrow_type(&self, token: Token) -> MaybeOwned { + MaybeOwned::Borrowed(&self.types[token].inner) + } +} + impl Writer { fn put_expression<'a>( &mut self, expr_token: crate::Token, expressions: &crate::Storage, - module: &crate::Module, - ) -> Result { + module: &'a crate::Module, + ) -> Result, Error> { let expression = &expressions[expr_token]; log::trace!("expression {:?}", expression); match *expression { crate::Expression::AccessIndex { base, index } => { - match self.put_expression(base, expressions, module)? { - crate::Type::Struct(token) => { - let member = &module.complex_types.structs[token].members[index as usize]; + match *self.put_expression(base, expressions, module)?.borrow() { + crate::TypeInner::Struct { ref members } => { + let member = &members[index as usize]; let name = member.name.or_index(MemberIndex(index as usize)); write!(self.out, ".{}", name)?; - Ok(member.ty.clone()) + Ok(module.borrow_type(member.ty)) } - crate::Type::Matrix { rows, kind, width, .. } => { + crate::TypeInner::Matrix { rows, kind, width, .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; - Ok(crate::Type::Vector { size: rows, kind, width }) + Ok(MaybeOwned::Owned(crate::TypeInner::Vector { size: rows, kind, width })) } - crate::Type::Vector { kind, width, .. } => { + crate::TypeInner::Vector { kind, width, .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; - Ok(crate::Type::Scalar { kind, width }) + Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width })) } - _ => { + crate::TypeInner::Array { base, size } => { + assert!(index < size); write!(self.out, "[{}]", index)?; - Ok(crate::Type::Void) //TODO + Ok(module.borrow_type(base)) } + ref other => panic!("Unexpected indexing of {:?}", other), } } - crate::Expression::Constant(ref constant) => { - let kind = match *constant { - crate::Constant::Sint(value) => { + crate::Expression::Constant(token) => { + let kind = match module.constants[token].inner { + crate::ConstantInner::Sint(value) => { write!(self.out, "{}", value)?; crate::ScalarKind::Sint } - crate::Constant::Uint(value) => { + crate::ConstantInner::Uint(value) => { write!(self.out, "{}", value)?; crate::ScalarKind::Uint } - crate::Constant::Float(value) => { + crate::ConstantInner::Float(value) => { write!(self.out, "{}", value)?; crate::ScalarKind::Float } }; let width = 32; //TODO: not sure how to get that... - Ok(crate::Type::Scalar { kind, width }) + Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width })) } - crate::Expression::Compose { ref ty, ref components } => { - match *ty { - crate::Type::Vector { size, kind, .. } => { + crate::Expression::Compose { ty, ref components } => { + let inner = &module.types[ty].inner; + match *inner { + crate::TypeInner::Vector { size, kind, .. } => { write!(self.out, "{}{}(", scalar_kind_string(kind), vector_size_string(size))?; for (i, &token) in components.iter().enumerate() { if i != 0 { @@ -407,16 +378,18 @@ impl Writer { } _ => panic!("Unsupported compose {:?}", ty), } - Ok(ty.clone()) + Ok(MaybeOwned::Borrowed(inner)) } crate::Expression::GlobalVariable(token) => { let var = &module.global_variables[token]; + let inner = &module.types[var.ty].inner; match var.class { spirv::StorageClass::Output => { self.out.write_str(NAME_OUTPUT)?; - if let crate::Type::Pointer(pt) = var.ty { - if let crate::Type::Struct(_) = module.complex_types.pointers[pt].base { - return Ok(module.complex_types.pointers[pt].base.clone()); + if let crate::TypeInner::Pointer { base, .. } = *inner { + let base_inner = &module.types[base].inner; + if let crate::TypeInner::Struct { .. } = *base_inner { + return Ok(MaybeOwned::Borrowed(base_inner)); } } self.out.write_str(".")?; @@ -428,15 +401,15 @@ impl Writer { } let name = var.name.or_index(token); write!(self.out, "{}", name)?; - Ok(var.ty.clone()) + Ok(MaybeOwned::Borrowed(inner)) } crate::Expression::Load { pointer } => { //write!(self.out, "*")?; - match self.put_expression(pointer, expressions, module)? { - crate::Type::Pointer(token) => { - Ok(module.complex_types.pointers[token].base.clone()) + match *self.put_expression(pointer, expressions, module)?.borrow() { + crate::TypeInner::Pointer { base, .. } => { + Ok(module.borrow_type(base)) } - other => panic!("Unexpected load pointer {:?}", other), + ref other => panic!("Unexpected load pointer {:?}", other), } } crate::Expression::Mul(left, right) => { @@ -445,9 +418,9 @@ impl Writer { write!(self.out, " * ")?; let ty_right = self.put_expression(right, expressions, module)?; write!(self.out, ")")?; - Ok(match (ty_left, ty_right) { - (crate::Type::Vector { size, kind, width }, crate::Type::Scalar { .. }) => - crate::Type::Vector { size, kind, width }, + Ok(match (ty_left.borrow(), ty_right.borrow()) { + (&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Scalar { .. }) => + MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), other => panic!("Unable to infer Mul for {:?}", other), }) } @@ -458,9 +431,9 @@ impl Writer { write!(self.out, ", ")?; self.put_expression(coordinate, expressions, module)?; write!(self.out, ")")?; - match ty_image { - crate::Type::Image(token) => Ok(module.complex_types.images[token].ty.clone()), - other => panic!("Unexpected image type {:?}", other), + match *ty_image.borrow() { + crate::TypeInner::Image { base, .. } => Ok(module.borrow_type(base)), + ref other => panic!("Unexpected image type {:?}", other), } } ref other => panic!("Unsupported {:?}", other), @@ -474,65 +447,77 @@ impl Writer { // write down complex types writeln!(self.out, "")?; - for (token, decl) in module.complex_types.images.iter() { - let name = decl.name.or_index(token); - let dim = match decl.dim { - spirv::Dim::Dim1D => "1d", - spirv::Dim::Dim2D => "2d", - spirv::Dim::Dim3D => "3d", - spirv::Dim::DimCube => "Cube", - _ => panic!("Unsupported dim {:?}", decl.dim), - }; - let base = match decl.ty { - crate::Type::Scalar { kind, .. } | - crate::Type::Vector { kind, .. } => scalar_kind_string(kind), - _ => panic!("Unsupported image type {:?}", decl.ty), - }; - writeln!(self.out, "typedef texture{}<{}> {};", dim, base, name)?; - } - for (token, decl) in module.complex_types.samplers.iter() { - let name = decl.name.or_index(token); - writeln!(self.out, "typedef sampler {};", name)?; - } - for (token, decl) in module.complex_types.pointers.iter() { - let name = Starred(decl.name.or_index(token)); - // Input and output are always provided as pointers, - // but we are only interested in the contents. - //TODO: consider resolving this at the root - let class = match decl.class { - spirv::StorageClass::Input | - spirv::StorageClass::Output => continue, - spirv::StorageClass::UniformConstant => "constant", - other => { - log::warn!("Unexpected pointer class {:?}", other); - "" + for (token, ty) in module.types.iter() { + write!(self.out, "typedef ")?; + let name = ty.name.or_index(token); + match ty.inner { + crate::TypeInner::Void => { + write!(self.out, "void {}", name)?; + }, + crate::TypeInner::Scalar { kind, .. } => { + write!(self.out, "{} {}", scalar_kind_string(kind), name)?; + }, + crate::TypeInner::Vector { size, kind, .. } => { + write!(self.out, "{}{} {}", scalar_kind_string(kind), vector_size_string(size), name)?; + }, + crate::TypeInner::Matrix { columns, rows, kind, .. } => { + write!(self.out, "{}{}x{} {}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows), name)?; } - }; - if let crate::Type::Struct(st) = decl.base { - let var = module.complex_types.structs[st].name.or_index(st); - writeln!(self.out, "struct {}; //forward decl", var)?; - } - let tv = TypedVar(&decl.base, &name, &module.complex_types); - writeln!(self.out, "typedef {} {};", class, tv)?; - } - for (token, decl) in module.complex_types.arrays.iter() { - let name = decl.name.or_index(token); - let tv = TypedVar(&decl.base, &name, &module.complex_types); - writeln!(self.out, "typedef {}[{}];", tv, decl.length)?; - } - for (token, decl) in module.complex_types.structs.iter() { - writeln!(self.out, "struct {} {{", decl.name.or_index(token))?; - for (index, member) in decl.members.iter().enumerate() { - let name = member.name.or_index(MemberIndex(index)); - let tv = TypedVar(&member.ty, &name, &module.complex_types); - write!(self.out, "\t{}", tv)?; - if let Some(ref binding) = member.binding { - let resolved = options.resolve_binding(binding, LocationMode::Intermediate)?; - write!(self.out, " [[{}]]", resolved)?; + crate::TypeInner::Pointer { base, class } => { + let base_name = module.types[base].name.or_index(base); + let class_name = match class { + spirv::StorageClass::Input | + spirv::StorageClass::Output => continue, + spirv::StorageClass::UniformConstant => "constant", + other => { + log::warn!("Unexpected pointer class {:?}", other); + "" + } + }; + write!(self.out, "{} {} *{}", class_name, base_name, name)?; + } + crate::TypeInner::Array { base, size } => { + let base_name = module.types[base].name.or_index(base); + write!(self.out, "{} {}[{}]", base_name, name, size)?; + } + crate::TypeInner::Struct { ref members } => { + writeln!(self.out, "struct {} {{", name)?; + for (index, member) in members.iter().enumerate() { + let name = member.name.or_index(MemberIndex(index)); + let base_name = module.types[member.ty].name.or_index(member.ty); + write!(self.out, "\t{} {}", base_name, name)?; + if let Some(ref binding) = member.binding { + let resolved = options.resolve_binding(binding, LocationMode::Intermediate)?; + write!(self.out, " [[{}]]", resolved)?; + } + writeln!(self.out, ";")?; + } + writeln!(self.out, "}};")?; + } + crate::TypeInner::Image { base, dim, flags } => { + let base_name = module.types[base].name.or_index(base); + let dim = match dim { + spirv::Dim::Dim1D => "1d", + spirv::Dim::Dim2D => "2d", + spirv::Dim::Dim3D => "3d", + spirv::Dim::DimCube => "Cube", + _ => panic!("Unsupported dim {:?}", dim), + }; + let access = if flags.contains(crate::ImageFlags::READABLE | crate::ImageFlags::WRITABLE) { + "read_write" + } else if flags.contains(crate::ImageFlags::WRITABLE) { + "write" + } else { + assert!(flags.contains(crate::ImageFlags::READABLE)); + "read" + }; + write!(self.out, "texture{}<{}, access::{}> {}", dim, base_name, access, name)?; + } + crate::TypeInner::Sampler => { + write!(self.out, "sampler {}", name)?; } - writeln!(self.out, ";")?; } - writeln!(self.out, "}};")?; + writeln!(self.out, ";")?; } // write down functions @@ -583,17 +568,16 @@ impl Writer { for &token in var_outputs.iter() { let var = &module.global_variables[token]; // if it's a struct, lift all the built-in contents up to the root - if let crate::Type::Pointer(pt) = var.ty { - if let crate::Type::Struct(st) = module.complex_types.pointers[pt].base { - let sd = &module.complex_types.structs[st]; - for (index, member) in sd.members.iter().enumerate() { + if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner { + if let crate::TypeInner::Struct { ref members } = module.types[base].inner { + for (index, member) in members.iter().enumerate() { let name = member.name.or_index(MemberIndex(index)); - let tv = TypedVar(&member.ty, &name, &module.complex_types); + let ty_name = module.types[member.ty].name.or_index(member.ty); let binding = member.binding .as_ref() .ok_or(Error::MissingBinding(token))?; let resolved = options.resolve_binding(binding, out_mode)?; - writeln!(self.out, "\t{} [[{}]];", tv, resolved)?; + writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; } continue } @@ -610,12 +594,12 @@ impl Writer { writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; writeln!(self.out, "\t{} {} [[stage_in]],", input_name, NAME_INPUT)?; } else { - let fun_tv = TypedVar(&fun.return_type, &fun_name, &module.complex_types); - writeln!(self.out, "{}(", fun_tv)?; - for (index, ty) in fun.parameter_types.iter().enumerate() { + let result_type_name = module.types[fun.return_type].name.or_index(fun.return_type); + writeln!(self.out, "{} {}(", result_type_name, fun_name)?; + for (index, &ty) in fun.parameter_types.iter().enumerate() { let name = Name::from(ParameterIndex(index)); - let tv = TypedVar(ty, &name, &module.complex_types); - writeln!(self.out, "\t{},", tv)?; + let member_type_name = module.types[ty].name.or_index(ty); + writeln!(self.out, "\t{} {},", member_type_name, name)?; } } for (_, expr) in fun.expressions.iter() { diff --git a/src/front/mod.rs b/src/front/mod.rs index 9c549d16c..484df8f3c 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -9,13 +9,8 @@ impl crate::Module { fn from_header(header: crate::Header) -> Self { crate::Module { header, - complex_types: crate::ComplexTypes { - pointers: Storage::new(), - arrays: Storage::new(), - structs: Storage::new(), - images: Storage::new(), - samplers: Storage::new(), - }, + types: Storage::new(), + constants: Storage::new(), global_variables: Storage::new(), functions: Storage::new(), entry_points: Vec::new(), diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 77daeec19..987ea6214 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -44,7 +44,7 @@ pub enum Error { UnsupportedCapability(spirv::Capability), UnsupportedExtension(String), UnsupportedExtSet(String), - UnsupportedType(crate::Type), + UnsupportedType(Token), UnsupportedExecutionModel(u32), UnsupportedStorageClass(u32), UnsupportedFunctionControl(u32), @@ -110,12 +110,12 @@ pub enum ModuleState { Function, } -trait Lookup { +trait LookupHelper { type Target; fn lookup(&self, key: spirv::Word) -> Result<&Self::Target, Error>; } -impl Lookup for FastHashMap { +impl LookupHelper for FastHashMap { type Target = T; fn lookup(&self, key: spirv::Word) -> Result<&T, Error> { self.get(&key) @@ -197,13 +197,13 @@ struct EntryPoint { #[derive(Debug)] struct LookupType { - value: crate::Type, + token: Token, base_id: Option, } #[derive(Debug)] struct LookupConstant { - value: crate::Constant, + token: Token, type_id: spirv::Word, } @@ -349,7 +349,12 @@ impl> Parser { Ok(()) } - fn next_block(&mut self, fun: &mut crate::Function) -> Result<(), Error> { + fn next_block( + &mut self, + fun: &mut crate::Function, + type_store: &Storage, + const_store: &Storage, + ) -> Result<(), Error> { loop { use spirv::Op; let inst = self.next_inst()?; @@ -377,18 +382,24 @@ impl> Parser { let access_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", access_id); let index_expr = self.lookup_expression.lookup(access_id)?.clone(); - match self.lookup_type.lookup(index_expr.type_id)?.value { - crate::Type::Scalar { kind: crate::ScalarKind::Uint, .. } | - crate::Type::Scalar { kind: crate::ScalarKind::Sint, .. } => (), - ref other => return Err(Error::UnsupportedType(other.clone())), + let index_type_token = self.lookup_type.lookup(index_expr.type_id)?.token; + match type_store[index_type_token].inner { + crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, .. } | + crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, .. } => (), + _ => return Err(Error::UnsupportedType(index_type_token)), } log::trace!("\t\t\tlooking up type {:?}", acex.type_id); - let ty = self.lookup_type.lookup(acex.type_id)?; - acex = match ty.value { - crate::Type::Struct(_) => { + let type_lookup = self.lookup_type.lookup(acex.type_id)?; + acex = match type_store[type_lookup.token].inner { + crate::TypeInner::Struct { .. } => { let index = match fun.expressions[index_expr.token] { - crate::Expression::Constant(crate::Constant::Sint(v)) => v as u32, - crate::Expression::Constant(crate::Constant::Uint(v)) => v as u32, + crate::Expression::Constant(const_token) => { + match const_store[const_token].inner { + crate::ConstantInner::Uint(v) => v as u32, + crate::ConstantInner::Sint(v) => v as u32, + _ => return Err(Error::InvalidAccessIndex(crate::Expression::Constant(const_token))), + } + } ref other => return Err(Error::InvalidAccessIndex(other.clone())) }; AccessExpression { @@ -401,19 +412,19 @@ impl> Parser { .ok_or(Error::InvalidAccessType(acex.type_id))?, } } - crate::Type::Array { .. } | - crate::Type::Vector { .. } | - crate::Type::Matrix { .. } => { + crate::TypeInner::Array { .. } | + crate::TypeInner::Vector { .. } | + crate::TypeInner::Matrix { .. } => { AccessExpression { base_token: fun.expressions.append(crate::Expression::Access { base: acex.base_token, index: index_expr.token, }), - type_id: ty.base_id + type_id: type_lookup.base_id .ok_or(Error::InvalidAccessType(acex.type_id))?, } } - ref other => return Err(Error::UnsupportedType(other.clone())), + _ => return Err(Error::UnsupportedType(type_lookup.token)), }; } @@ -438,20 +449,20 @@ impl> Parser { for _ in 4 .. inst.wc { let index = self.next()?; log::trace!("\t\t\tlooking up type {:?}", lexp.type_id); - let ty = self.lookup_type.lookup(lexp.type_id)?; - let type_id = match ty.value { - crate::Type::Struct(_) => { + let type_lookup = self.lookup_type.lookup(lexp.type_id)?; + let type_id = match type_store[type_lookup.token].inner { + crate::TypeInner::Struct { .. } => { *self.lookup_member_type_id .get(&(lexp.type_id, index)) .ok_or(Error::InvalidAccessType(lexp.type_id))? } - crate::Type::Array { .. } | - crate::Type::Vector { .. } | - crate::Type::Matrix { .. } => { - ty.base_id + crate::TypeInner::Array { .. } | + crate::TypeInner::Vector { .. } | + crate::TypeInner::Matrix { .. } => { + type_lookup.base_id .ok_or(Error::InvalidAccessType(lexp.type_id))? } - ref other => return Err(Error::UnsupportedType(other.clone())), + _ => return Err(Error::UnsupportedType(type_lookup.token)), }; lexp = LookupExpression { token: fun.expressions.append(crate::Expression::AccessIndex { @@ -479,7 +490,7 @@ impl> Parser { components.push(lexp.token); } let expr = crate::Expression::Compose { - ty: self.lookup_type.lookup(result_type_id)?.value.clone(), + ty: self.lookup_type.lookup(result_type_id)?.token, components, }; self.lookup_expression.insert(id, LookupExpression { @@ -501,9 +512,9 @@ impl> Parser { if base_type.base_id != Some(result_type_id) { return Err(Error::InvalidLoadType(result_type_id)); } - match base_type.value { - crate::Type::Pointer { .. } => (), - ref other => return Err(Error::UnsupportedType(other.clone())), + match type_store[base_type.token].inner { + crate::TypeInner::Pointer { .. } => (), + _ => return Err(Error::UnsupportedType(base_type.token)), } let expr = crate::Expression::Load { pointer: base_expr.token, @@ -523,9 +534,9 @@ impl> Parser { } let base_expr = self.lookup_expression.lookup(pointer_id)?; let base_type = self.lookup_type.lookup(base_expr.type_id)?; - match base_type.value { - crate::Type::Pointer { .. } => (), - ref other => return Err(Error::UnsupportedType(other.clone())), + match type_store[base_type.token].inner { + crate::TypeInner::Pointer { .. } => (), + _ => return Err(Error::UnsupportedType(base_type.token)), }; let value_expr = self.lookup_expression.lookup(value_id)?; if base_type.base_id != Some(value_expr.type_id) { @@ -544,22 +555,25 @@ impl> Parser { Op::VectorTimesScalar => { inst.expect(5)?; let result_type_id = self.next()?; - let (res_size, res_width) = match self.lookup_type.lookup(result_type_id)?.value { - crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), - ref other => return Err(Error::UnsupportedType(other.clone())), + let result_type_loookup = self.lookup_type.lookup(result_type_id)?; + let (res_size, res_width) = match type_store[result_type_loookup.token].inner { + crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), + _ => return Err(Error::UnsupportedType(result_type_loookup.token)), }; let result_id = self.next()?; let vector_id = self.next()?; let scalar_id = self.next()?; let vector_lexp = self.lookup_expression.lookup(vector_id)?; - match self.lookup_type.lookup(vector_lexp.type_id)?.value { - crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } if size == res_size && width == res_width => (), - ref other => return Err(Error::UnsupportedType(other.clone())), + let vector_type_lookup = self.lookup_type.lookup(vector_lexp.type_id)?; + match type_store[vector_type_lookup.token].inner { + crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } if size == res_size && width == res_width => (), + _ => return Err(Error::UnsupportedType(vector_type_lookup.token)), }; let scalar_lexp = self.lookup_expression.lookup(scalar_id)?.clone(); - match self.lookup_type.lookup(scalar_lexp.type_id)?.value { - crate::Type::Scalar { kind: crate::ScalarKind::Float, width } if width == res_width => (), - ref other => return Err(Error::UnsupportedType(other.clone())), + let scalar_type_lookup = self.lookup_type.lookup(scalar_lexp.type_id)?; + match type_store[scalar_type_lookup.token].inner { + crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width } if width == res_width => (), + _ => return Err(Error::UnsupportedType(scalar_type_lookup.token)), }; let expr = crate::Expression::Mul(vector_lexp.token, scalar_lexp.token); self.lookup_expression.insert(result_id, LookupExpression { @@ -570,22 +584,25 @@ impl> Parser { Op::MatrixTimesVector => { inst.expect(5)?; let result_type_id = self.next()?; - let (res_size, res_width) = match self.lookup_type.lookup(result_type_id)?.value { - crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), - ref other => return Err(Error::UnsupportedType(other.clone())), + let result_type_loookup = self.lookup_type.lookup(result_type_id)?; + let (res_size, res_width) = match type_store[result_type_loookup.token].inner { + crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), + _ => return Err(Error::UnsupportedType(result_type_loookup.token)), }; let result_id = self.next()?; let matrix_id = self.next()?; let vector_id = self.next()?; let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; - let columns = match self.lookup_type.lookup(matrix_lexp.type_id)?.value { - crate::Type::Matrix { columns, rows, kind: crate::ScalarKind::Float, width } if rows == res_size && width == res_width => columns, - ref other => return Err(Error::UnsupportedType(other.clone())), + let matrix_type_lookup = self.lookup_type.lookup(matrix_lexp.type_id)?; + let columns = match type_store[matrix_type_lookup.token].inner { + crate::TypeInner::Matrix { columns, rows, kind: crate::ScalarKind::Float, width } if rows == res_size && width == res_width => columns, + _ => return Err(Error::UnsupportedType(matrix_type_lookup.token)), }; let vector_lexp = self.lookup_expression.lookup(vector_id)?.clone(); - match self.lookup_type.lookup(vector_lexp.type_id)?.value { - crate::Type::Vector { size, kind: crate::ScalarKind::Float, width } if size == columns && width == res_width => (), - ref other => return Err(Error::UnsupportedType(other.clone())), + let vector_type_lookup = self.lookup_type.lookup(vector_lexp.type_id)?; + match type_store[vector_type_lookup.token].inner { + crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } if size == columns && width == res_width => (), + _ => return Err(Error::UnsupportedType(vector_type_lookup.token)), }; let expr = crate::Expression::Mul(matrix_lexp.token, vector_lexp.token); self.lookup_expression.insert(result_id, LookupExpression { @@ -615,10 +632,11 @@ impl> Parser { let coordinate_id = self.next()?; let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - match self.lookup_type.lookup(coord_lexp.type_id)?.value { - crate::Type::Scalar { kind: crate::ScalarKind::Float, .. } | - crate::Type::Vector { kind: crate::ScalarKind::Float, .. } => (), - ref other => return Err(Error::UnsupportedType(other.clone())), + let coord_type_lookup = self.lookup_type.lookup(coord_lexp.type_id)?; + match type_store[coord_type_lookup.token].inner { + crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, .. } | + crate::TypeInner::Vector { kind: crate::ScalarKind::Float, .. } => (), + _ => return Err(Error::UnsupportedType(coord_type_lookup.token)), } //TODO: compare the result type let expr = crate::Expression::ImageSample { @@ -651,7 +669,7 @@ impl> Parser { for (&id, con) in self.lookup_constant.iter() { self.lookup_expression.insert(id, LookupExpression { type_id: con.type_id, - token: expressions.append(crate::Expression::Constant(con.value.clone())), + token: expressions.append(crate::Expression::Constant(con.token)), }); } // done @@ -824,8 +842,14 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect(2)?; let id = self.next()?; + let inner = crate::TypeInner::Void; self.lookup_type.insert(id, LookupType { - value: crate::Type::Void, + token: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), base_id: None, }); } @@ -835,17 +859,23 @@ impl> Parser { let id = self.next()?; let width = self.next()?; let sign = self.next()?; - self.lookup_type.insert(id, LookupType { - value: crate::Type::Scalar { - kind: match sign { - 0 => crate::ScalarKind::Uint, - 1 => crate::ScalarKind::Sint, - _ => return Err(Error::InvalidSign(sign)), - }, - width: width - .try_into() - .map_err(|_| Error::InvalidTypeWidth(width))?, + let inner = crate::TypeInner::Scalar { + kind: match sign { + 0 => crate::ScalarKind::Uint, + 1 => crate::ScalarKind::Sint, + _ => return Err(Error::InvalidSign(sign)), }, + width: width + .try_into() + .map_err(|_| Error::InvalidTypeWidth(width))?, + }; + self.lookup_type.insert(id, LookupType { + token: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), base_id: None, }); } @@ -854,13 +884,19 @@ impl> Parser { inst.expect(3)?; let id = self.next()?; let width = self.next()?; + let inner = crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: width + .try_into() + .map_err(|_| Error::InvalidTypeWidth(width))?, + }; self.lookup_type.insert(id, LookupType { - value: crate::Type::Scalar { - kind: crate::ScalarKind::Float, - width: width - .try_into() - .map_err(|_| Error::InvalidTypeWidth(width))?, - }, + token: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), base_id: None, }); } @@ -869,17 +905,24 @@ impl> Parser { inst.expect(4)?; let id = self.next()?; let type_id = self.next()?; - let (kind, width) = match self.lookup_type.lookup(type_id)?.value { - crate::Type::Scalar { kind, width } => (kind, width), + let type_lookup = self.lookup_type.lookup(type_id)?; + let (kind, width) = match module.types[type_lookup.token].inner { + crate::TypeInner::Scalar { kind, width } => (kind, width), _ => return Err(Error::InvalidInnerType(type_id)), }; let component_count = self.next()?; + let inner = crate::TypeInner::Vector { + size: map_vector_size(component_count)?, + kind, + width, + }; self.lookup_type.insert(id, LookupType { - value: crate::Type::Vector { - size: map_vector_size(component_count)?, - kind, - width, - }, + token: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), base_id: Some(type_id), }); } @@ -889,17 +932,23 @@ impl> Parser { let id = self.next()?; let vector_type_id = self.next()?; let num_columns = self.next()?; - let (rows, kind, width) = match self.lookup_type.lookup(vector_type_id)?.value { - crate::Type::Vector { size, kind, width } => (size, kind, width), - _ => return Err(Error::InvalidInnerType(vector_type_id)), - }; - self.lookup_type.insert(id, LookupType { - value: crate::Type::Matrix { + let vector_type_lookup = self.lookup_type.lookup(vector_type_id)?; + let inner = match module.types[vector_type_lookup.token].inner { + crate::TypeInner::Vector { size, kind, width } => crate::TypeInner::Matrix { columns: map_vector_size(num_columns)?, - rows, + rows: size, kind, width, }, + _ => return Err(Error::InvalidInnerType(vector_type_id)), + }; + self.lookup_type.insert(id, LookupType { + token: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), base_id: Some(vector_type_id), }); } @@ -923,16 +972,17 @@ impl> Parser { let id = self.next()?; let storage = self.next()?; let type_id = self.next()?; - let decl = crate::PointerDeclaration { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - base: self.lookup_type.lookup(type_id)?.value.clone(), + let inner = crate::TypeInner::Pointer { + base: self.lookup_type.lookup(type_id)?.token, class: map_storage_class(storage)?, }; - let token = module.complex_types.pointers.append(decl); self.lookup_type.insert(id, LookupType { - value: crate::Type::Pointer(token), + token: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), base_id: Some(type_id), }); } @@ -941,17 +991,18 @@ impl> Parser { inst.expect(4)?; let id = self.next()?; let type_id = self.next()?; - let length = self.next()?; - let decl = crate::ArrayDeclaration { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - base: self.lookup_type.lookup(type_id)?.value.clone(), - length, + let size = self.next()?; + let inner = crate::TypeInner::Array { + base: self.lookup_type.lookup(type_id)?.token, + size, }; - let token = module.complex_types.arrays.append(decl); self.lookup_type.insert(id, LookupType { - value: crate::Type::Array(token), + token: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), base_id: Some(type_id), }); } @@ -959,29 +1010,31 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(2)?; let id = self.next()?; - let mut decl = crate::StructDeclaration { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - members: Vec::with_capacity(inst.wc as usize - 2), - }; + let mut members = Vec::with_capacity(inst.wc as usize - 2); for i in 0 .. inst.wc as u32 - 2 { let type_id = self.next()?; - let ty = self.lookup_type.lookup(type_id)?.value.clone(); + let ty = self.lookup_type.lookup(type_id)?.token; self.lookup_member_type_id.insert((id, i), type_id); let decor = self.future_member_decor .remove(&(id, i)) .unwrap_or_default(); let binding = decor.get_binding(); - decl.members.push(crate::StructMember { + members.push(crate::StructMember { name: decor.name, binding, ty, }); } - let token = module.complex_types.structs.append(decl); + let inner = crate::TypeInner::Struct { + members + }; self.lookup_type.insert(id, LookupType { - value: crate::Type::Struct(token), + token: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), base_id: None, }); } @@ -1019,12 +1072,9 @@ impl> Parser { let decor = self.future_decor .remove(&id) .unwrap_or_default(); - let binding = decor.get_binding(); - let decl = crate::ImageDeclaration { - name: decor.name, - binding, - ty: self.lookup_type.lookup(sample_type_id)?.value.clone(), + let inner = crate::TypeInner::Image { + base: self.lookup_type.lookup(sample_type_id)?.token, dim: if dim > LAST_KNOWN_DIM as u32 { return Err(Error::UnsupportedDim(dim)); } else { @@ -1032,9 +1082,11 @@ impl> Parser { }, flags, }; - let token = module.complex_types.images.append(decl); self.lookup_type.insert(id, LookupType { - value: crate::Type::Image(token), + token: module.types.append(crate::Type { + name: decor.name, + inner, + }), base_id: Some(sample_type_id), }); } @@ -1044,7 +1096,7 @@ impl> Parser { let id = self.next()?; let image_id = self.next()?; self.lookup_type.insert(id, LookupType { - value: self.lookup_type.lookup(image_id)?.value.clone(), + token: self.lookup_type.lookup(image_id)?.token, base_id: Some(image_id), }); } @@ -1055,15 +1107,12 @@ impl> Parser { let decor = self.future_decor .remove(&id) .unwrap_or_default(); - let binding = decor.get_binding(); - - let decl = crate::SamplerDeclaration { - name: decor.name, - binding, - }; - let token = module.complex_types.samplers.append(decl); + let inner = crate::TypeInner::Sampler; self.lookup_type.insert(id, LookupType { - value: crate::Type::Sampler(token), + token: module.types.append(crate::Type { + name: decor.name, + inner, + }), base_id: None, }); } @@ -1073,8 +1122,9 @@ impl> Parser { inst.expect_at_least(3)?; let type_id = self.next()?; let id = self.next()?; - let value = match self.lookup_type.lookup(type_id)?.value { - crate::Type::Scalar { kind: crate::ScalarKind::Uint, width } => { + let type_lookup = self.lookup_type.lookup(type_id)?; + let inner = match module.types[type_lookup.token].inner { + crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width } => { let low = self.next()?; let high = if width > 32 { inst.expect(4)?; @@ -1082,9 +1132,9 @@ impl> Parser { } else { 0 }; - crate::Constant::Uint(((high as u64) << 32) | low as u64) + crate::ConstantInner::Uint(((high as u64) << 32) | low as u64) } - crate::Type::Scalar { kind: crate::ScalarKind::Sint, width } => { + crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width } => { let low = self.next()?; let high = if width < 32 { return Err(Error::InvalidTypeWidth(width as u32)); @@ -1094,11 +1144,11 @@ impl> Parser { } else { !0 }; - crate::Constant::Sint(unsafe { + crate::ConstantInner::Sint(unsafe { std::mem::transmute(((high as u64) << 32) | low as u64) }) } - crate::Type::Scalar { kind: crate::ScalarKind::Float, width } => { + crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width } => { let low = self.next()?; let extended = if width < 32 { return Err(Error::InvalidTypeWidth(width as u32)); @@ -1113,12 +1163,18 @@ impl> Parser { std::mem::transmute::<_, f32>(low) as f64 } }; - crate::Constant::Float(extended) + crate::ConstantInner::Float(extended) } - ref other => return Err(Error::UnsupportedType(other.clone())) + _ => return Err(Error::UnsupportedType(type_lookup.token)) }; self.lookup_constant.insert(id, LookupConstant { - value, + token: module.constants.append(crate::Constant { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + specialization: None, //TODO + inner, + }), type_id, }); } @@ -1132,29 +1188,20 @@ impl> Parser { inst.expect(5)?; let _init = self.next()?; //TODO } - let ty = self.lookup_type.lookup(type_id)?.value.clone(); + let lookup_type = self.lookup_type.lookup(type_id)?; let dec = self.future_decor .remove(&id) .ok_or(Error::InvalidBinding(id))?; - let binding = match ty { - crate::Type::Pointer(pd) => { - match module.complex_types.pointers[pd] { - crate::PointerDeclaration { - base: crate::Type::Struct(token), - class: spirv::StorageClass::Input, - .. - } | - crate::PointerDeclaration { - base: crate::Type::Struct(token), - class: spirv::StorageClass::Output, - .. - } => { + let binding = match module.types[lookup_type.token].inner { + crate::TypeInner::Pointer { base, class: spirv::StorageClass::Input } | + crate::TypeInner::Pointer { base, class: spirv::StorageClass::Output } => { + match module.types[base].inner { + crate::TypeInner::Struct { ref members } => { // we don't expect binding decoration on I/O structs, // but we do expect them on all of the members - let sd = &module.complex_types.structs[token]; - for member in sd.members.iter() { + for member in members { if member.binding.is_none() { - log::warn!("Struct {:?} member {:?} doesn't have a binding", token, member); + log::warn!("Struct {:?} member {:?} doesn't have a binding", base, member); return Err(Error::InvalidBinding(id)); } } @@ -1179,7 +1226,7 @@ impl> Parser { name: dec.name, class: map_storage_class(storage)?, binding, - ty, + ty: lookup_type.token, }; let token = module.global_variables.append(var); self.lookup_variable.insert(id, LookupVariable { @@ -1206,7 +1253,7 @@ impl> Parser { control: spirv::FunctionControl::from_bits(fun_control) .ok_or(Error::UnsupportedFunctionControl(fun_control))?, parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), - return_type: self.lookup_type.lookup(result_type)?.value.clone(), + return_type: self.lookup_type.lookup(result_type)?.token, expressions: self.make_expression_storage(), body: Vec::new(), } @@ -1224,7 +1271,7 @@ impl> Parser { { return Err(Error::WrongFunctionParameterType(type_id)) } - let ty = self.lookup_type.lookup(type_id)?.value.clone(); + let ty = self.lookup_type.lookup(type_id)?.token; fun.parameter_types.push(ty); } Instruction { op, .. } => return Err(Error::InvalidParameter(op)), @@ -1238,7 +1285,7 @@ impl> Parser { Op::Label => { fun_inst.expect(2)?; let _id = self.next()?; - self.next_block(&mut fun)?; + self.next_block(&mut fun, &module.types, &module.constants)?; } Op::FunctionEnd => { fun_inst.expect(1)?; diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 12f3c1559..99b01bf77 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,3 +1,6 @@ +use crate::storage::{Storage, Token}; + + #[derive(Parser)] #[grammar = "../grammars/wgsl.pest"] struct Tokenizer; @@ -62,19 +65,26 @@ impl Parser { } } - fn parse_type_decl(type_decl: pest::iterators::Pair) -> Result { + fn parse_type_decl( + type_decl: pest::iterators::Pair, + type_store: &mut Storage, + ) -> Result, Error> { assert_eq!(type_decl.as_rule(), Rule::type_decl); - let inner = type_decl.into_inner().next().unwrap(); - match inner.as_rule() { - Rule::scalar_type => match inner.as_str() { - "f32" => Ok(crate::Type::Scalar { kind: crate::ScalarKind::Float, width: 32 }), - "i32" => Ok(crate::Type::Scalar { kind: crate::ScalarKind::Sint, width: 32 }), - "u32" => Ok(crate::Type::Scalar { kind: crate::ScalarKind::Uint, width: 32 }), + let temp = type_decl.into_inner().next().unwrap(); + let inner = match temp.as_rule() { + Rule::scalar_type => match temp.as_str() { + "f32" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: 32 }, + "i32" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width: 32 }, + "u32" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width: 32 }, other => panic!("Unexpected scalar {:?}", other), }, Rule::ident => unimplemented!(), other => panic!("Unexpected type {:?}", other), - } + }; + Ok(type_store.append(crate::Type { + name: None, //TODO + inner, + })) } pub fn parse(&mut self, source: &str) -> Result { @@ -108,7 +118,7 @@ impl Parser { assert_eq!(body.as_rule(), Rule::variable_ident_decl); let mut var_ident_decl_pairs = body.into_inner(); let name = var_ident_decl_pairs.next().unwrap().as_str().to_owned(); - let ty = Self::parse_type_decl(var_ident_decl_pairs.next().unwrap())?; + let ty = Self::parse_type_decl(var_ident_decl_pairs.next().unwrap(), &mut module.types)?; module.global_variables.append(crate::GlobalVariable { name: Some(name), class, diff --git a/src/lib.rs b/src/lib.rs index 5ab2f8676..2fa24d0a4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,31 +41,11 @@ pub enum ScalarKind { Float, } -#[derive(Debug)] -pub struct PointerDeclaration { - pub name: Option, - pub base: Type, - pub class: spirv::StorageClass, -} - -#[derive(Debug)] -pub struct ArrayDeclaration { - pub name: Option, - pub base: Type, - pub length: u32, -} - #[derive(Debug)] pub struct StructMember { pub name: Option, pub binding: Option, - pub ty: Type, -} - -#[derive(Debug)] -pub struct StructDeclaration { - pub name: Option, - pub members: Vec, + pub ty: Token, } bitflags::bitflags! { @@ -78,35 +58,33 @@ bitflags::bitflags! { } #[derive(Debug)] -pub struct ImageDeclaration { +pub struct Type { pub name: Option, - pub binding: Option, - pub ty: Type, - pub dim: spirv::Dim, - pub flags: ImageFlags, + pub inner: TypeInner, } #[derive(Debug)] -pub struct SamplerDeclaration { - pub name: Option, - pub binding: Option, -} - -#[derive(Clone, Debug)] -pub enum Type { +pub enum TypeInner { Void, Scalar { kind: ScalarKind, width: Bytes }, Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, Matrix { columns: VectorSize, rows: VectorSize, kind: ScalarKind, width: Bytes }, - Pointer(Token), - Array(Token), - Struct(Token), - Image(Token), - Sampler(Token), + Pointer { base: Token, class: spirv::StorageClass }, + Array { base: Token, size: u32 }, + Struct { members: Vec }, + Image { base: Token, dim: spirv::Dim, flags: ImageFlags }, + Sampler, } -#[derive(Clone, Debug)] -pub enum Constant { +#[derive(Debug)] +pub struct Constant { + pub name: Option, + pub specialization: Option, + pub inner: ConstantInner, +} + +#[derive(Debug)] +pub enum ConstantInner { Sint(i64), Uint(u64), Float(f64), @@ -124,7 +102,7 @@ pub struct GlobalVariable { pub name: Option, pub class: spirv::StorageClass, pub binding: Option, - pub ty: Type, + pub ty: Token, } #[derive(Clone, Debug)] @@ -137,9 +115,9 @@ pub enum Expression { base: Token, index: u32, }, - Constant(Constant), + Constant(Token), Compose { - ty: Type, + ty: Token, components: Vec>, }, FunctionParameter(u32), @@ -186,8 +164,8 @@ pub enum Statement { pub struct Function { pub name: Option, pub control: spirv::FunctionControl, - pub parameter_types: Vec, - pub return_type: Type, + pub parameter_types: Vec>, + pub return_type: Token, pub expressions: Storage, pub body: Block, } @@ -201,19 +179,11 @@ pub struct EntryPoint { pub function: Token, } -#[derive(Debug)] -pub struct ComplexTypes { - pub pointers: Storage, - pub arrays: Storage, - pub structs: Storage, - pub images: Storage, - pub samplers: Storage, -} - #[derive(Debug)] pub struct Module { pub header: Header, - pub complex_types: ComplexTypes, + pub types: Storage, + pub constants: Storage, pub global_variables: Storage, pub functions: Storage, pub entry_points: Vec, From aba9e8a0f2dc9f2a3ddd655ccf5b2c8b925b8427 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 2 Mar 2020 16:56:10 -0500 Subject: [PATCH 0028/2212] Fixup metal type exports --- README.md | 2 +- examples/convert.rs | 2 +- src/back/msl.rs | 22 +++++++++++----------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index a18d882e1..3c374c4e8 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Back-end | Status | Notes | --------------- | ------------------ | ----- | SPIR-V (binary) | | | WGSL | | | -MSL | :construction: | | +Metal | :construction: | | HLSL | | | GLSL | | | AIR | | | diff --git a/examples/convert.rs b/examples/convert.rs index f10909462..11eadc9ac 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -21,7 +21,7 @@ fn main() { if args.len() <= 2 { println!("{:?}", module); return - } else if args[2].ends_with(".msl") { + } else if args[2].ends_with(".metal") { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); binding_map.insert( diff --git a/src/back/msl.rs b/src/back/msl.rs index 0111bf631..1adcae1a0 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -448,20 +448,19 @@ impl Writer { // write down complex types writeln!(self.out, "")?; for (token, ty) in module.types.iter() { - write!(self.out, "typedef ")?; let name = ty.name.or_index(token); match ty.inner { crate::TypeInner::Void => { - write!(self.out, "void {}", name)?; + write!(self.out, "typedef void {}", name)?; }, crate::TypeInner::Scalar { kind, .. } => { - write!(self.out, "{} {}", scalar_kind_string(kind), name)?; + write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?; }, crate::TypeInner::Vector { size, kind, .. } => { - write!(self.out, "{}{} {}", scalar_kind_string(kind), vector_size_string(size), name)?; + write!(self.out, "typedef {}{} {}", scalar_kind_string(kind), vector_size_string(size), name)?; }, crate::TypeInner::Matrix { columns, rows, kind, .. } => { - write!(self.out, "{}{}x{} {}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows), name)?; + write!(self.out, "typedef {}{}x{} {}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows), name)?; } crate::TypeInner::Pointer { base, class } => { let base_name = module.types[base].name.or_index(base); @@ -474,11 +473,11 @@ impl Writer { "" } }; - write!(self.out, "{} {} *{}", class_name, base_name, name)?; + write!(self.out, "typedef {} {} *{}", class_name, base_name, name)?; } crate::TypeInner::Array { base, size } => { let base_name = module.types[base].name.or_index(base); - write!(self.out, "{} {}[{}]", base_name, name, size)?; + write!(self.out, "typedef {} {}[{}]", base_name, name, size)?; } crate::TypeInner::Struct { ref members } => { writeln!(self.out, "struct {} {{", name)?; @@ -492,7 +491,7 @@ impl Writer { } writeln!(self.out, ";")?; } - writeln!(self.out, "}};")?; + write!(self.out, "}}")?; } crate::TypeInner::Image { base, dim, flags } => { let base_name = module.types[base].name.or_index(base); @@ -509,12 +508,13 @@ impl Writer { "write" } else { assert!(flags.contains(crate::ImageFlags::READABLE)); - "read" + //TODO: figure out when to use `read` + "sample" }; - write!(self.out, "texture{}<{}, access::{}> {}", dim, base_name, access, name)?; + write!(self.out, "typedef texture{}<{}, access::{}> {}", dim, base_name, access, name)?; } crate::TypeInner::Sampler => { - write!(self.out, "sampler {}", name)?; + write!(self.out, "typedef sampler {}", name)?; } } writeln!(self.out, ";")?; From c2265ca4c8f888310e391725b674ef9b95c050e9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 3 Mar 2020 11:14:15 -0500 Subject: [PATCH 0029/2212] [wgsl] structure declarations, better array types --- grammars/wgsl.pest | 58 ++++++++++++++------- src/back/msl.rs | 10 +++- src/front/spirv.rs | 23 ++++++++- src/front/wgsl.rs | 122 ++++++++++++++++++++++++++++++++++++++++----- src/lib.rs | 15 ++++-- 5 files changed, 188 insertions(+), 40 deletions(-) diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest index 831dd9910..5314c8f2a 100644 --- a/grammars/wgsl.pest +++ b/grammars/wgsl.pest @@ -4,9 +4,9 @@ global_decl = { ";" | import_decl ~ ";" | global_variable_decl ~ ";" -// | global_constant_decl SEMICOLON -// | entry_point_decl SEMICOLON -// | type_alias SEMICOLON + | global_constant_decl ~ ";" +// | entry_point_decl ~ ";" + | type_alias ~ ";" // | function_decl } @@ -17,6 +17,8 @@ global_variable_decl = { | variable_decoration_list ~ variable_decl ~ "=" ~ const_expr } +global_constant_decl = { "const" ~ variable_ident_decl ~ "=" ~ const_expr } + variable_decoration_list = { "[[" ~ (variable_decoration ~ ",")* ~ variable_decoration ~ "]]" } variable_decoration = { @@ -30,13 +32,36 @@ variable_decl = { "var" ~ variable_storage_decoration? ~ variable_ident_decl } variable_storage_decoration = _{ "<" ~ storage_class ~ ">" } variable_ident_decl = { ident ~ ":" ~ type_decl } +type_alias = { + "type" ~ ident ~ "=" ~ type_decl + | "type" ~ ident ~ "=" ~ struct_decl +} + +struct_decl = { struct_decoration_decl? ~ "struct" ~ struct_body_decl } + +struct_decoration_decl = { "[[" ~ struct_decoration ~ "]]" } + +struct_decoration = { + "block" +} + +struct_body_decl = { "{" ~ struct_member* ~ "}" } + +struct_member = { struct_member_decoration_decl? ~ variable_ident_decl ~ ";" } + +struct_member_decoration_decl = { "[[" ~ (struct_member_decoration ~ ",")* ~ struct_member_decoration ~ "]]" } + +struct_member_decoration = { + "offset" ~ int_literal +} + storage_class = { "in" | "out" | "uniform" // | WORKGROUP // | UNIFORM_CONSTANT -// | STORAGE_BUFFER + | "storage_buffer" // | IMAGE // | PUSH_CONSTANT | "private" @@ -56,23 +81,18 @@ const_expr = { | const_literal } +type_pointer_kind = { "ptr" } +type_array_kind = { "array" } +type_vec_kind = { "vec2" | "vec3" | "vec4" } +type_mat_kind = { "mat2x2" | "mat3x3" | "mat4x4" } + type_decl = { scalar_type -// | VEC2 LESS_THAN type_decl GREATER_THAN -// | VEC3 LESS_THAN type_decl GREATER_THAN -// | VEC3 LESS_THAN type_decl GREATER_THAN -// | PTR LESS_THAN storage_class, type_decl GREATER_THAN -// | ARRAY LESS_THAN type_decl COMMA INT_LITERAL GREATER_THAN -// | ARRAY LESS_THAN type_decl GREATER_THAN -// | MAT2x2 LESS_THAN type_decl GREATER_THAN -// | MAT2x3 LESS_THAN type_decl GREATER_THAN -// | MAT2x4 LESS_THAN type_decl GREATER_THAN -// | MAT3x2 LESS_THAN type_decl GREATER_THAN -// | MAT3x3 LESS_THAN type_decl GREATER_THAN -// | MAT3x4 LESS_THAN type_decl GREATER_THAN -// | MAT4x2 LESS_THAN type_decl GREATER_THAN -// | MAT4x3 LESS_THAN type_decl GREATER_THAN -// | MAT4x4 LESS_THAN type_decl GREATER_THAN + | type_vec_kind ~ "<" ~ type_decl ~ ">" + | type_pointer_kind ~ "<" ~ storage_class ~ "," ~ type_decl ~ ">" + | type_array_kind ~ "<" ~ type_decl ~ "," ~ int_literal ~ ">" + | type_array_kind ~ "<" ~ type_decl ~ ">" + | type_mat_kind ~ "<" ~ type_decl ~ ">" | ident } diff --git a/src/back/msl.rs b/src/back/msl.rs index 1adcae1a0..f1246456c 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -338,7 +338,9 @@ impl Writer { Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width })) } crate::TypeInner::Array { base, size } => { - assert!(index < size); + if let crate::ArraySize::Static(length) = size { + assert!(index < length); + } write!(self.out, "[{}]", index)?; Ok(module.borrow_type(base)) } @@ -477,7 +479,11 @@ impl Writer { } crate::TypeInner::Array { base, size } => { let base_name = module.types[base].name.or_index(base); - write!(self.out, "typedef {} {}[{}]", base_name, name, size)?; + write!(self.out, "typedef {} {}[", base_name, name)?; + if let crate::ArraySize::Static(length) = size { + write!(self.out, "{}", length)?; + } + write!(self.out, "]")?; } crate::TypeInner::Struct { ref members } => { writeln!(self.out, "struct {} {{", name)?; diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 987ea6214..65a13feec 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -991,10 +991,29 @@ impl> Parser { inst.expect(4)?; let id = self.next()?; let type_id = self.next()?; - let size = self.next()?; + let length = self.next()?; let inner = crate::TypeInner::Array { base: self.lookup_type.lookup(type_id)?.token, - size, + size: crate::ArraySize::Static(length), + }; + self.lookup_type.insert(id, LookupType { + token: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), + base_id: Some(type_id), + }); + } + Op::TypeRuntimeArray => { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let type_id = self.next()?; + let inner = crate::TypeInner::Array { + base: self.lookup_type.lookup(type_id)?.token, + size: crate::ArraySize::Dynamic, }; self.lookup_type.insert(id, LookupType { token: module.types.append(crate::Type { diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 99b01bf77..b2a5fa089 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,4 +1,7 @@ -use crate::storage::{Storage, Token}; +use crate::{ + storage::{Storage, Token}, + FastHashMap, +}; #[derive(Parser)] @@ -10,6 +13,7 @@ pub enum Error { Pest(pest::error::Error), BadInt(std::num::ParseIntError), BadStorageClass(String), + UnknownType(String), } impl From> for Error { fn from(error: pest::error::Error) -> Self { @@ -23,9 +27,16 @@ impl From for Error { } pub struct Parser { + lookup_type: FastHashMap>, } impl Parser { + pub fn new() -> Self { + Parser { + lookup_type: FastHashMap::default(), + } + } + fn parse_uint_literal(pair: pest::iterators::Pair) -> Result { Ok(pair.as_str().parse()?) } @@ -66,27 +77,88 @@ impl Parser { } fn parse_type_decl( + &self, type_decl: pest::iterators::Pair, type_store: &mut Storage, ) -> Result, Error> { assert_eq!(type_decl.as_rule(), Rule::type_decl); - let temp = type_decl.into_inner().next().unwrap(); - let inner = match temp.as_rule() { - Rule::scalar_type => match temp.as_str() { - "f32" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: 32 }, - "i32" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width: 32 }, - "u32" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width: 32 }, - other => panic!("Unexpected scalar {:?}", other), - }, - Rule::ident => unimplemented!(), + let mut type_decl_pairs = type_decl.into_inner(); + let type_kind = type_decl_pairs.next().unwrap(); + let inner = match type_kind.as_rule() { + Rule::scalar_type => { + let kind = match type_kind.as_str() { + "f32" => crate::ScalarKind::Float, + "i32" => crate::ScalarKind::Sint, + "u32" => crate::ScalarKind::Uint, + other => panic!("Unexpected scalar kind {:?}", other), + }; + crate::TypeInner::Scalar { kind, width: 32 } + } + Rule::type_array_kind => { + let base = self.parse_type_decl(type_decl_pairs.next().unwrap(), type_store)?; + let size = match type_decl_pairs.next() { + Some(pair) => crate::ArraySize::Static(Self::parse_uint_literal(pair)?), + None => crate::ArraySize::Dynamic, + }; + crate::TypeInner::Array { base, size } + } + Rule::type_vec_kind => { + let size = match type_kind.as_str() { + "vec2" => crate::VectorSize::Bi, + "vec3" => crate::VectorSize::Tri, + "vec4" => crate::VectorSize::Quad, + other => panic!("Unexpected vec kind {:?}", other), + }; + crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width: 32 } + } + Rule::ident => { + return self.lookup_type + .get(type_kind.as_str()) + .cloned() + .ok_or(Error::UnknownType(type_kind.as_str().to_owned())); + } other => panic!("Unexpected type {:?}", other), }; + if let Some((token, _)) = type_store + .iter() + .find(|(_, ty)| ty.inner == inner) + { + return Ok(token); + } Ok(type_store.append(crate::Type { - name: None, //TODO + name: None, inner, })) } + fn parse_struct_decl( + &self, + struct_body_decl: pest::iterators::Pair, + type_store: &mut Storage, + ) -> Result { + assert_eq!(struct_body_decl.as_rule(), Rule::struct_body_decl); + let mut members = Vec::new(); + for member_decl in struct_body_decl.into_inner() { + assert_eq!(member_decl.as_rule(), Rule::struct_member); + let mut member_decl_pairs = member_decl.into_inner(); + let mut body = member_decl_pairs.next().unwrap(); + let binding = None; + if body.as_rule() == Rule::struct_member_decoration_decl { + body = member_decl_pairs.next().unwrap(); //TODO: parse properly + } + assert_eq!(body.as_rule(), Rule::variable_ident_decl); + let mut variable_ident_decl_pairs = body.into_inner(); + let member_name = variable_ident_decl_pairs.next().unwrap().as_str().to_owned(); + let ty = self.parse_type_decl(variable_ident_decl_pairs.next().unwrap(), type_store)?; + members.push(crate::StructMember { + name: Some(member_name), + binding, + ty, + }); + } + Ok(crate::TypeInner::Struct { members }) + } + pub fn parse(&mut self, source: &str) -> Result { use pest::Parser as _; let pairs = Tokenizer::parse(Rule::translation_unit, source)?; @@ -118,7 +190,7 @@ impl Parser { assert_eq!(body.as_rule(), Rule::variable_ident_decl); let mut var_ident_decl_pairs = body.into_inner(); let name = var_ident_decl_pairs.next().unwrap().as_str().to_owned(); - let ty = Self::parse_type_decl(var_ident_decl_pairs.next().unwrap(), &mut module.types)?; + let ty = self.parse_type_decl(var_ident_decl_pairs.next().unwrap(), &mut module.types)?; module.global_variables.append(crate::GlobalVariable { name: Some(name), class, @@ -126,6 +198,30 @@ impl Parser { ty, }); } + Rule::type_alias => { + let mut type_alias_pairs = global_decl.into_inner(); + let name = type_alias_pairs.next().unwrap().as_str().to_owned(); + let something_decl = type_alias_pairs.next().unwrap(); + match something_decl.as_rule() { + Rule::type_decl => { + let token = self.parse_type_decl(something_decl, &mut module.types)?; + self.lookup_type.insert(name, token); + } + Rule::struct_decl => { + let mut struct_decl_pairs = something_decl.into_inner(); + let mut body = struct_decl_pairs.next().unwrap(); + while body.as_rule() == Rule::struct_decoration_decl { + body = struct_decl_pairs.next().unwrap(); //skip + } + let inner = self.parse_struct_decl(body, &mut module.types)?; + module.types.append(crate::Type { + name: Some(name), + inner, + }); + } + other => panic!("Unexpected type alias rule {:?}", other), + }; + } unknown => panic!("Unexpected global decl: {:?}", unknown), } } @@ -138,5 +234,5 @@ impl Parser { } pub fn parse_str(source: &str) -> Result { - Parser{}.parse(source) + Parser::new().parse(source) } diff --git a/src/lib.rs b/src/lib.rs index 2fa24d0a4..902a0b311 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,14 @@ pub enum ScalarKind { Float, } -#[derive(Debug)] +#[repr(u8)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ArraySize { + Static(spirv::Word), + Dynamic, +} + +#[derive(Debug, PartialEq)] pub struct StructMember { pub name: Option, pub binding: Option, @@ -63,14 +70,14 @@ pub struct Type { pub inner: TypeInner, } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum TypeInner { Void, Scalar { kind: ScalarKind, width: Bytes }, Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, Matrix { columns: VectorSize, rows: VectorSize, kind: ScalarKind, width: Bytes }, Pointer { base: Token, class: spirv::StorageClass }, - Array { base: Token, size: u32 }, + Array { base: Token, size: ArraySize }, Struct { members: Vec }, Image { base: Token, dim: spirv::Dim, flags: ImageFlags }, Sampler, @@ -90,7 +97,7 @@ pub enum ConstantInner { Float(f64), } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub enum Binding { BuiltIn(spirv::BuiltIn), Location(spirv::Word), From 4a9f8382080cf5d2f247df83ca685722c780f6d8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 3 Mar 2020 13:52:47 -0500 Subject: [PATCH 0030/2212] [wgsl] first bits of function parsing --- grammars/wgsl.pest | 31 +++++++++++++++++++++++++++---- src/front/wgsl.rs | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest index 5314c8f2a..045248c58 100644 --- a/grammars/wgsl.pest +++ b/grammars/wgsl.pest @@ -7,7 +7,7 @@ global_decl = { | global_constant_decl ~ ";" // | entry_point_decl ~ ";" | type_alias ~ ";" -// | function_decl + | function_decl } import_decl = { "import" ~ string ~ "as" ~ (ident ~ "::")* ~ ident} @@ -46,15 +46,18 @@ struct_decoration = { } struct_body_decl = { "{" ~ struct_member* ~ "}" } - struct_member = { struct_member_decoration_decl? ~ variable_ident_decl ~ ";" } - struct_member_decoration_decl = { "[[" ~ (struct_member_decoration ~ ",")* ~ struct_member_decoration ~ "]]" } - struct_member_decoration = { "offset" ~ int_literal } +function_decl = { function_header ~ body_stmt } +function_header = { "fn" ~ ident ~ "(" ~ param_list ~ ")" ~ "->" ~ function_type_decl } +function_type_decl = _{ type_decl | "void" } +param_list = { (variable_ident_decl ~ ",")* ~ variable_ident_decl } +body_stmt = { "{" ~ statement* ~ "}" } + storage_class = { "in" | "out" @@ -103,6 +106,26 @@ scalar_type = { | "u32" } +statement = { + ";" + | "return" ~ primary_expression ~ ";" +// | if_stmt +// | unless_stmt +// | regardless_stmt +// | switch_stmt +// | loop_stmt +// | variable_stmt SEMICOLON +// | break_stmt SEMICOLON +// | continue_stmt SEMICOLON +// | KILL SEMICOLON +// | NOP SEMICOLON +// | assignment_stmt SEMICOLON +} + +primary_expression = { + const_literal +} + ident = @{ ASCII_ALPHA ~ (ASCII_ALPHANUMERIC | "_")* } int_literal = @{ ("-"? ~ "0x"? ~ (ASCII_DIGIT | 'a'..'f' | 'A'..'F')+) | "0" | ("-"? ~ '1'..'9' ~ ASCII_DIGIT*) } string = @{ "\"" ~ ( "\"\"" | (!"\"" ~ ANY) )* ~ "\"" } diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index b2a5fa089..0f2e2c5f8 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -159,6 +159,42 @@ impl Parser { Ok(crate::TypeInner::Struct { members }) } + fn parse_function_decl( + &self, + function_decl: pest::iterators::Pair, + module: &mut crate::Module, + ) -> Result, Error> { + assert_eq!(function_decl.as_rule(), Rule::function_decl); + let mut function_decl_pairs = function_decl.into_inner(); + + let function_header = function_decl_pairs.next().unwrap(); + assert_eq!(function_header.as_rule(), Rule::function_header); + let mut function_header_pairs = function_header.into_inner(); + let fun_name = function_header_pairs.next().unwrap().as_str().to_owned(); + let param_list = function_header_pairs.next().unwrap(); + assert_eq!(param_list.as_rule(), Rule::param_list); + let function_type_decl = function_header_pairs.next().unwrap(); + let fun = crate::Function { + name: Some(fun_name), + control: spirv::FunctionControl::empty(), + parameter_types: Vec::new(), + return_type: if function_type_decl.as_rule() == Rule::type_decl { + self.parse_type_decl(function_type_decl, &mut module.types)? + } else { + module.types.append(crate::Type { + name: None, + inner: crate::TypeInner::Void, + }) + }, + expressions: Storage::new(), + body: Vec::new(), + }; + + let function_body = function_decl_pairs.next().unwrap(); + assert_eq!(function_body.as_rule(), Rule::body_stmt); + Ok(module.functions.append(fun)) + } + pub fn parse(&mut self, source: &str) -> Result { use pest::Parser as _; let pairs = Tokenizer::parse(Rule::translation_unit, source)?; @@ -222,6 +258,9 @@ impl Parser { other => panic!("Unexpected type alias rule {:?}", other), }; } + Rule::function_decl => { + self.parse_function_decl(global_decl, &mut module)?; + } unknown => panic!("Unexpected global decl: {:?}", unknown), } } From a9c476d58d7d3bb896569f6d0b143d3034fe2949 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 3 Mar 2020 14:09:41 -0500 Subject: [PATCH 0031/2212] Move out Void from the type enum --- src/back/msl.rs | 11 +++++++---- src/front/spirv.rs | 21 +++++++++------------ src/front/wgsl.rs | 7 ++----- src/lib.rs | 3 +-- 4 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index f1246456c..956dfddaf 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -452,9 +452,6 @@ impl Writer { for (token, ty) in module.types.iter() { let name = ty.name.or_index(token); match ty.inner { - crate::TypeInner::Void => { - write!(self.out, "typedef void {}", name)?; - }, crate::TypeInner::Scalar { kind, .. } => { write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?; }, @@ -600,7 +597,13 @@ impl Writer { writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; writeln!(self.out, "\t{} {} [[stage_in]],", input_name, NAME_INPUT)?; } else { - let result_type_name = module.types[fun.return_type].name.or_index(fun.return_type); + let result_type_name = match fun.return_type { + Some(type_id) => module.types[type_id].name.or_index(type_id), + None => Name { + class: "", + source: NameSource::Custom { name: "void", prefix: false }, + }, + }; writeln!(self.out, "{} {}(", result_type_name, fun_name)?; for (index, &ty) in fun.parameter_types.iter().enumerate() { let name = Name::from(ParameterIndex(index)); diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 65a13feec..020b63188 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -12,7 +12,7 @@ TODO: would be nice to find ways that avoid looking up as much use crate::{ storage::{Storage, Token}, - FastHashMap, + FastHashMap, FastHashSet, }; use std::convert::TryInto; @@ -233,6 +233,7 @@ pub struct Parser { future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>, lookup_member_type_id: FastHashMap<(spirv::Word, MemberIndex), spirv::Word>, lookup_type: FastHashMap, + lookup_void_type: FastHashSet, lookup_constant: FastHashMap, lookup_variable: FastHashMap, lookup_expression: FastHashMap, @@ -251,6 +252,7 @@ impl> Parser { future_member_decor: FastHashMap::default(), lookup_member_type_id: FastHashMap::default(), lookup_type: FastHashMap::default(), + lookup_void_type: FastHashSet::default(), lookup_constant: FastHashMap::default(), lookup_variable: FastHashMap::default(), lookup_expression: FastHashMap::default(), @@ -842,16 +844,7 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect(2)?; let id = self.next()?; - let inner = crate::TypeInner::Void; - self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: None, - }); + self.lookup_void_type.insert(id); } Op::TypeInt => { self.switch(ModuleState::Type, inst.op)?; @@ -1272,7 +1265,11 @@ impl> Parser { control: spirv::FunctionControl::from_bits(fun_control) .ok_or(Error::UnsupportedFunctionControl(fun_control))?, parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), - return_type: self.lookup_type.lookup(result_type)?.token, + return_type: if self.lookup_void_type.contains(&result_type) { + None + } else { + Some(self.lookup_type.lookup(result_type)?.token) + }, expressions: self.make_expression_storage(), body: Vec::new(), } diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 0f2e2c5f8..d08a59dd8 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -179,12 +179,9 @@ impl Parser { control: spirv::FunctionControl::empty(), parameter_types: Vec::new(), return_type: if function_type_decl.as_rule() == Rule::type_decl { - self.parse_type_decl(function_type_decl, &mut module.types)? + Some(self.parse_type_decl(function_type_decl, &mut module.types)?) } else { - module.types.append(crate::Type { - name: None, - inner: crate::TypeInner::Void, - }) + None }, expressions: Storage::new(), body: Vec::new(), diff --git a/src/lib.rs b/src/lib.rs index 902a0b311..579e29dbd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -72,7 +72,6 @@ pub struct Type { #[derive(Debug, PartialEq)] pub enum TypeInner { - Void, Scalar { kind: ScalarKind, width: Bytes }, Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, Matrix { columns: VectorSize, rows: VectorSize, kind: ScalarKind, width: Bytes }, @@ -172,7 +171,7 @@ pub struct Function { pub name: Option, pub control: spirv::FunctionControl, pub parameter_types: Vec>, - pub return_type: Token, + pub return_type: Option>, pub expressions: Storage, pub body: Block, } From ee987325a533fd6ea88d9a785882ddf1b6c0dfd1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 3 Mar 2020 16:08:20 -0500 Subject: [PATCH 0032/2212] [wgsl] basic parsing of function body --- grammars/wgsl.pest | 10 +++-- src/back/msl.rs | 5 +++ src/front/wgsl.rs | 97 +++++++++++++++++++++++++++++++++++++++++----- src/lib.rs | 2 + 4 files changed, 100 insertions(+), 14 deletions(-) diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest index 045248c58..3978c9f13 100644 --- a/grammars/wgsl.pest +++ b/grammars/wgsl.pest @@ -75,8 +75,7 @@ const_literal = { int_literal // | UINT_LITERAL // | FLOAT_LITERAL - | "true" - | "false" + | bool_literal } const_expr = { @@ -106,9 +105,11 @@ scalar_type = { | "u32" } +return_statement = { "return" ~ primary_expression? } + statement = { ";" - | "return" ~ primary_expression ~ ";" + | return_statement ~ ";" // | if_stmt // | unless_stmt // | regardless_stmt @@ -122,12 +123,13 @@ statement = { // | assignment_stmt SEMICOLON } -primary_expression = { +primary_expression = _{ const_literal } ident = @{ ASCII_ALPHA ~ (ASCII_ALPHANUMERIC | "_")* } int_literal = @{ ("-"? ~ "0x"? ~ (ASCII_DIGIT | 'a'..'f' | 'A'..'F')+) | "0" | ("-"? ~ '1'..'9' ~ ASCII_DIGIT*) } +bool_literal = @{ "true" | "false" } string = @{ "\"" ~ ( "\"\"" | (!"\"" ~ ANY) )* ~ "\"" } WHITESPACE = _{ " " | "\t" | "\n" } diff --git a/src/back/msl.rs b/src/back/msl.rs index 956dfddaf..9a5813e9f 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -275,6 +275,7 @@ fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { crate::ScalarKind::Float => "float", crate::ScalarKind::Sint => "signed int", crate::ScalarKind::Uint => "unsigned int", + crate::ScalarKind::Bool => "bool", } } @@ -361,6 +362,10 @@ impl Writer { write!(self.out, "{}", value)?; crate::ScalarKind::Float } + crate::ConstantInner::Bool(value) => { + write!(self.out, "{}", value)?; + crate::ScalarKind::Bool + } }; let width = 32; //TODO: not sure how to get that... Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width })) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index d08a59dd8..9106f66e9 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -13,6 +13,7 @@ pub enum Error { Pest(pest::error::Error), BadInt(std::num::ParseIntError), BadStorageClass(String), + BadBool(String), UnknownType(String), } impl From> for Error { @@ -41,7 +42,7 @@ impl Parser { Ok(pair.as_str().parse()?) } - fn _parse_int_literal(pair: pest::iterators::Pair) -> Result { + fn parse_int_literal(pair: pest::iterators::Pair) -> Result { let istr = pair.as_str(); let (sign, istr) = match &istr[..1] { "_" => (-1, &istr[1..]), @@ -159,11 +160,58 @@ impl Parser { Ok(crate::TypeInner::Struct { members }) } + fn parse_const_literal( + const_literal: pest::iterators::Pair, + const_store: &mut Storage, + ) -> Result, Error> { + let inner = match const_literal.as_rule() { + Rule::int_literal => { + let value = Self::parse_int_literal(const_literal)?; + crate::ConstantInner::Sint(value as i64) + } + Rule::bool_literal => { + let value = match const_literal.as_str() { + "true" => true, + "false" => false, + other => return Err(Error::BadBool(other.to_owned())), + }; + crate::ConstantInner::Bool(value) + } + ref other => panic!("Unknown const literal {:?}", other), + }; + Ok(const_store.append(crate::Constant { + name: None, + specialization: None, + inner, + })) + } + + fn parse_primary_expression( + &self, + primary_expression: pest::iterators::Pair, + function: &mut crate::Function, + const_store: &mut Storage, + ) -> Result, Error> { + let expression = match primary_expression.as_rule() { + Rule::const_literal => { + let const_literal = primary_expression.into_inner().next().unwrap(); + let token = Self::parse_const_literal(const_literal, const_store)?; + crate::Expression::Constant(token) + } + ref other => panic!("Unknown expression {:?}", other), + }; + Ok(function.expressions.append(expression)) + } + fn parse_function_decl( &self, function_decl: pest::iterators::Pair, module: &mut crate::Module, ) -> Result, Error> { + enum Ident { + Parameter(u8), + } + let mut lookup_symbols = FastHashMap::default(); assert_eq!(function_decl.as_rule(), Rule::function_decl); let mut function_decl_pairs = function_decl.into_inner(); @@ -171,24 +219,53 @@ impl Parser { assert_eq!(function_header.as_rule(), Rule::function_header); let mut function_header_pairs = function_header.into_inner(); let fun_name = function_header_pairs.next().unwrap().as_str().to_owned(); - let param_list = function_header_pairs.next().unwrap(); - assert_eq!(param_list.as_rule(), Rule::param_list); - let function_type_decl = function_header_pairs.next().unwrap(); - let fun = crate::Function { + let mut fun = crate::Function { name: Some(fun_name), control: spirv::FunctionControl::empty(), parameter_types: Vec::new(), - return_type: if function_type_decl.as_rule() == Rule::type_decl { - Some(self.parse_type_decl(function_type_decl, &mut module.types)?) - } else { - None - }, + return_type: None, expressions: Storage::new(), body: Vec::new(), }; + let param_list = function_header_pairs.next().unwrap(); + assert_eq!(param_list.as_rule(), Rule::param_list); + for (i, variable_ident_decl) in param_list.into_inner().enumerate() { + assert_eq!(variable_ident_decl.as_rule(), Rule::variable_ident_decl); + let mut variable_ident_decl_pairs = variable_ident_decl.into_inner(); + let param_name = variable_ident_decl_pairs.next().unwrap().as_str().to_owned(); + lookup_symbols.insert(param_name, Ident::Parameter(i as u8)); + let param_type_decl = variable_ident_decl_pairs.next().unwrap(); + let ty = self.parse_type_decl(param_type_decl, &mut module.types)?; + fun.parameter_types.push(ty); + } + let function_type_decl = function_header_pairs.next().unwrap(); + if function_type_decl.as_rule() == Rule::type_decl { + let ty = self.parse_type_decl(function_type_decl, &mut module.types)?; + fun.return_type = Some(ty); + } let function_body = function_decl_pairs.next().unwrap(); assert_eq!(function_body.as_rule(), Rule::body_stmt); + for statement in function_body.into_inner() { + assert_eq!(statement.as_rule(), Rule::statement); + let mut statement_pairs = statement.into_inner(); + let first_statement = match statement_pairs.next() { + Some(st) => st, + None => continue, + }; + let stmt = match first_statement.as_rule() { + Rule::return_statement => { + let mut return_pairs = first_statement.into_inner(); + let value = match return_pairs.next() { + Some(st) => Some(self.parse_primary_expression(st, &mut fun, &mut module.constants)?), + None => None, + }; + crate::Statement::Return { value } + } + ref other => panic!("Unknown statement {:?}", other), + }; + fun.body.push(stmt); + } Ok(module.functions.append(fun)) } diff --git a/src/lib.rs b/src/lib.rs index 579e29dbd..70e28471c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -39,6 +39,7 @@ pub enum ScalarKind { Sint, Uint, Float, + Bool, } #[repr(u8)] @@ -94,6 +95,7 @@ pub enum ConstantInner { Sint(i64), Uint(u64), Float(f64), + Bool(bool), } #[derive(Clone, Debug, PartialEq)] From 78d5a73a2f15570edb4dc03dbdf72060f1c66a0a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 3 Mar 2020 16:25:56 -0500 Subject: [PATCH 0033/2212] [msl] support returning values --- src/back/msl.rs | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 9a5813e9f..20b752bc9 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -481,11 +481,11 @@ impl Writer { } crate::TypeInner::Array { base, size } => { let base_name = module.types[base].name.or_index(base); - write!(self.out, "typedef {} {}[", base_name, name)?; - if let crate::ArraySize::Static(length) = size { - write!(self.out, "{}", length)?; - } - write!(self.out, "]")?; + let resolved_size = match size { + crate::ArraySize::Static(length) => length, + crate::ArraySize::Dynamic => 1, + }; + write!(self.out, "typedef {} {}[{}]", base_name, name, resolved_size)?; } crate::TypeInner::Struct { ref members } => { writeln!(self.out, "struct {} {{", name)?; @@ -647,7 +647,9 @@ impl Writer { } writeln!(self.out, ") {{")?; // write down function body - writeln!(self.out, "\t{} {};", output_name, NAME_OUTPUT)?; + if exec_model.is_some() { + writeln!(self.out, "\t{} {};", output_name, NAME_OUTPUT)?; + } for statement in fun.body.iter() { log::trace!("statement {:?}", statement); match *statement { @@ -659,8 +661,19 @@ impl Writer { self.put_expression(value, &fun.expressions, module)?; writeln!(self.out, ";")?; } - crate::Statement::Return { value: None } => { - writeln!(self.out, "\treturn {};", NAME_OUTPUT)?; + crate::Statement::Return { value } => { + write!(self.out, "\treturn ")?; + match (value, exec_model) { + (None, None) => (), + (None, Some(_)) => self.out.write_str(NAME_OUTPUT)?, + (Some(expr_token), None) => { + self.put_expression(expr_token, &fun.expressions, module)?; + } + (Some(expr_token), Some(_)) => { + panic!("Unable to return value {:?} from an entry point!", expr_token) + } + } + writeln!(self.out, ";")?; } _ => panic!("Unsupported {:?}", statement), } From b9ba223b6e062d8fc9ba65d7b11c97723895f9da Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 3 Mar 2020 22:33:53 -0500 Subject: [PATCH 0034/2212] [wgsl] basic parsing of entry points and global constants --- grammars/wgsl.pest | 74 ++++++++++++------ src/front/wgsl.rs | 181 +++++++++++++++++++++++++++++++++++---------- 2 files changed, 192 insertions(+), 63 deletions(-) diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest index 3978c9f13..beb993a9c 100644 --- a/grammars/wgsl.pest +++ b/grammars/wgsl.pest @@ -5,12 +5,12 @@ global_decl = { | import_decl ~ ";" | global_variable_decl ~ ";" | global_constant_decl ~ ";" -// | entry_point_decl ~ ";" + | entry_point_decl ~ ";" | type_alias ~ ";" | function_decl } -import_decl = { "import" ~ string ~ "as" ~ (ident ~ "::")* ~ ident} +import_decl = { "import" ~ string_literal ~ "as" ~ (ident ~ "::")* ~ ident} global_variable_decl = { variable_decoration_list ~ variable_decl @@ -21,13 +21,20 @@ global_constant_decl = { "const" ~ variable_ident_decl ~ "=" ~ const_expr } variable_decoration_list = { "[[" ~ (variable_decoration ~ ",")* ~ variable_decoration ~ "]]" } -variable_decoration = { - "location" ~ int_literal +variable_decoration = _{ + "location" ~ location_decoration + | "builtin" ~ builtin_decoration // | BUILTIN builtin_decoration // | BINDING INT_LITERAL // | SET INT_LITERAL } +location_decoration = { int_literal } +builtin_decoration = { + "position" + | "vertex_idx" +} + variable_decl = { "var" ~ variable_storage_decoration? ~ variable_ident_decl } variable_storage_decoration = _{ "<" ~ storage_class ~ ">" } variable_ident_decl = { ident ~ ":" ~ type_decl } @@ -49,15 +56,25 @@ struct_body_decl = { "{" ~ struct_member* ~ "}" } struct_member = { struct_member_decoration_decl? ~ variable_ident_decl ~ ";" } struct_member_decoration_decl = { "[[" ~ (struct_member_decoration ~ ",")* ~ struct_member_decoration ~ "]]" } struct_member_decoration = { - "offset" ~ int_literal + "offset" ~ uint_literal } function_decl = { function_header ~ body_stmt } function_header = { "fn" ~ ident ~ "(" ~ param_list ~ ")" ~ "->" ~ function_type_decl } -function_type_decl = _{ type_decl | "void" } -param_list = { (variable_ident_decl ~ ",")* ~ variable_ident_decl } +function_type_decl = _{ "void" | type_decl } +param_list = { (variable_ident_decl ~ ",")* ~ variable_ident_decl | "" } body_stmt = { "{" ~ statement* ~ "}" } +entry_point_decl = { + "entry_point" ~ pipeline_stage ~ ("as" ~ string_literal)? ~ "=" ~ ident +} + +pipeline_stage = { + "vertex" + | "fragment" + | "compute" +} + storage_class = { "in" | "out" @@ -66,21 +83,20 @@ storage_class = { // | UNIFORM_CONSTANT | "storage_buffer" // | IMAGE -// | PUSH_CONSTANT | "private" | "function" } const_literal = { - int_literal -// | UINT_LITERAL -// | FLOAT_LITERAL - | bool_literal + bool_literal + | float_literal + | int_literal + | uint_literal } const_expr = { - type_decl ~ "(" ~ (const_expr ~ ",")? ~ const_expr ~ ")" - | const_literal + const_literal + | type_decl ~ "(" ~ (const_expr ~ ",")? ~ const_expr ~ ")" } type_pointer_kind = { "ptr" } @@ -92,7 +108,7 @@ type_decl = { scalar_type | type_vec_kind ~ "<" ~ type_decl ~ ">" | type_pointer_kind ~ "<" ~ storage_class ~ "," ~ type_decl ~ ">" - | type_array_kind ~ "<" ~ type_decl ~ "," ~ int_literal ~ ">" + | type_array_kind ~ "<" ~ type_decl ~ "," ~ uint_literal ~ ">" | type_array_kind ~ "<" ~ type_decl ~ ">" | type_mat_kind ~ "<" ~ type_decl ~ ">" | ident @@ -106,6 +122,7 @@ scalar_type = { } return_statement = { "return" ~ primary_expression? } +assignment_statement = { ident ~ "=" ~ primary_expression } statement = { ";" @@ -115,21 +132,30 @@ statement = { // | regardless_stmt // | switch_stmt // | loop_stmt -// | variable_stmt SEMICOLON -// | break_stmt SEMICOLON -// | continue_stmt SEMICOLON -// | KILL SEMICOLON -// | NOP SEMICOLON -// | assignment_stmt SEMICOLON +// | variable_stmt ~ ";" +// | break_stmt ~ ";" +// | continue_stmt ~ ";" +// | KILL ~ ";" +// | NOP ~ ";" + | assignment_statement ~ ";" } primary_expression = _{ - const_literal + type_decl ~ "(" ~ argument_expression_list ~ ")" + | const_expr + | multiplicative_expression } +//multiplicative_expression = { primary_expression ~ "*" ~ primary_expression } //TODO +multiplicative_expression = { ident ~ "*" ~ primary_expression } +argument_expression_list = { (primary_expression ~ ",")* ~ primary_expression } + ident = @{ ASCII_ALPHA ~ (ASCII_ALPHANUMERIC | "_")* } -int_literal = @{ ("-"? ~ "0x"? ~ (ASCII_DIGIT | 'a'..'f' | 'A'..'F')+) | "0" | ("-"? ~ '1'..'9' ~ ASCII_DIGIT*) } +int_literal = @{ ("-"? ~ "0x"? ~ ASCII_HEX_DIGIT+) | "0" | ("-"? ~ ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } +uint_literal = @{ ("0x"? ~ ASCII_HEX_DIGIT+) | "0" | (ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } +float_literal = @{ "-"? ~ ASCII_DIGIT+ ~ ("." ~ ASCII_DIGIT*)? } bool_literal = @{ "true" | "false" } -string = @{ "\"" ~ ( "\"\"" | (!"\"" ~ ANY) )* ~ "\"" } +string_literal = @{ "\"" ~ ( "\"\"" | (!"\"" ~ ANY) )* ~ "\"" } WHITESPACE = _{ " " | "\t" | "\n" } +COMMENT = _{ "#" ~ (!"\n" ~ ANY)* } diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 9106f66e9..4410f7528 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -12,9 +12,13 @@ struct Tokenizer; pub enum Error { Pest(pest::error::Error), BadInt(std::num::ParseIntError), + BadFloat(std::num::ParseFloatError), BadStorageClass(String), BadBool(String), + BadDecoration(String), + UnknownIdent(String), UnknownType(String), + UnknownFunction(String), } impl From> for Error { fn from(error: pest::error::Error) -> Self { @@ -26,6 +30,24 @@ impl From for Error { Error::BadInt(error) } } +impl From for Error { + fn from(error: std::num::ParseFloatError) -> Self { + Error::BadFloat(error) + } +} + +trait StringValueLookup { + type Value; + fn lookup(&self, key: &str) -> Result; +} +impl StringValueLookup for FastHashMap> { + type Value = Token; + fn lookup(&self, key: &str) -> Result { + self.get(key) + .cloned() + .ok_or(Error::UnknownIdent(key.to_owned())) + } +} pub struct Parser { lookup_type: FastHashMap>, @@ -43,26 +65,30 @@ impl Parser { } fn parse_int_literal(pair: pest::iterators::Pair) -> Result { - let istr = pair.as_str(); - let (sign, istr) = match &istr[..1] { - "_" => (-1, &istr[1..]), - _ => (1, &istr[..]), - }; - let integer: i32 = istr.parse()?; - Ok(sign * integer) + Ok(pair.as_str().parse()?) + } + + fn parse_float_literal(pair: pest::iterators::Pair) -> Result { + Ok(pair.as_str().parse()?) } fn parse_decoration_list(variable_decoration_list: pest::iterators::Pair) -> Result, Error> { assert_eq!(variable_decoration_list.as_rule(), Rule::variable_decoration_list); for variable_decoration in variable_decoration_list.into_inner() { - assert_eq!(variable_decoration.as_rule(), Rule::variable_decoration); - let mut inner = variable_decoration.into_inner(); - let first = inner.next().unwrap(); - match first.as_rule() { - Rule::int_literal => { - let location = Self::parse_uint_literal(first)?; + match variable_decoration.as_rule() { + Rule::location_decoration => { + let location_pair = variable_decoration.into_inner().next().unwrap(); + let location = Self::parse_uint_literal(location_pair)?; return Ok(Some(crate::Binding::Location(location))); } + Rule::builtin_decoration => { + let builtin = match variable_decoration.as_str() { + "position" => spirv::BuiltIn::Position, + "vertex_idx" => spirv::BuiltIn::VertexIndex, + other => return Err(Error::BadDecoration(other.to_owned())), + }; + return Ok(Some(crate::Binding::BuiltIn(builtin))); + } unknown => panic!("Unexpected decoration: {:?}", unknown), } } @@ -132,6 +158,18 @@ impl Parser { })) } + fn parse_variable_ident_decl( + &self, + variable_ident_decl: pest::iterators::Pair, + type_store: &mut Storage, + ) -> Result<(String, Token), Error> { + assert_eq!(variable_ident_decl.as_rule(), Rule::variable_ident_decl); + let mut pairs = variable_ident_decl.into_inner(); + let name = pairs.next().unwrap().as_str().to_owned(); + let ty = self.parse_type_decl(pairs.next().unwrap(), type_store)?; + Ok((name, ty)) + } + fn parse_struct_decl( &self, struct_body_decl: pest::iterators::Pair, @@ -147,10 +185,7 @@ impl Parser { if body.as_rule() == Rule::struct_member_decoration_decl { body = member_decl_pairs.next().unwrap(); //TODO: parse properly } - assert_eq!(body.as_rule(), Rule::variable_ident_decl); - let mut variable_ident_decl_pairs = body.into_inner(); - let member_name = variable_ident_decl_pairs.next().unwrap().as_str().to_owned(); - let ty = self.parse_type_decl(variable_ident_decl_pairs.next().unwrap(), type_store)?; + let (member_name, ty) = self.parse_variable_ident_decl(body, type_store)?; members.push(crate::StructMember { name: Some(member_name), binding, @@ -162,13 +197,16 @@ impl Parser { fn parse_const_literal( const_literal: pest::iterators::Pair, - const_store: &mut Storage, - ) -> Result, Error> { + ) -> Result { let inner = match const_literal.as_rule() { Rule::int_literal => { let value = Self::parse_int_literal(const_literal)?; crate::ConstantInner::Sint(value as i64) } + Rule::uint_literal => { + let value = Self::parse_uint_literal(const_literal)?; + crate::ConstantInner::Uint(value as u64) + } Rule::bool_literal => { let value = match const_literal.as_str() { "true" => true, @@ -177,13 +215,30 @@ impl Parser { }; crate::ConstantInner::Bool(value) } + Rule::float_literal => { + let value = Self::parse_float_literal(const_literal)?; + crate::ConstantInner::Float(value as f64) + } ref other => panic!("Unknown const literal {:?}", other), }; - Ok(const_store.append(crate::Constant { - name: None, - specialization: None, - inner, - })) + Ok(inner) + } + + fn parse_const_expression( + const_expression: pest::iterators::Pair, + _const_store: &mut Storage, + ) -> Result { + let mut const_expr_pairs = const_expression.into_inner(); + let first_pair = const_expr_pairs.next().unwrap(); + let inner = match first_pair.as_rule() { + Rule::const_literal => { + let const_literal = first_pair.into_inner().next().unwrap(); + Self::parse_const_literal(const_literal)? + } + Rule::type_decl => unimplemented!(), + _ => panic!("Unknown const expr {:?}", first_pair), + }; + Ok(inner) } fn parse_primary_expression( @@ -193,9 +248,13 @@ impl Parser { const_store: &mut Storage, ) -> Result, Error> { let expression = match primary_expression.as_rule() { - Rule::const_literal => { - let const_literal = primary_expression.into_inner().next().unwrap(); - let token = Self::parse_const_literal(const_literal, const_store)?; + Rule::const_expr => { + let inner = Self::parse_const_expression(primary_expression, const_store)?; + let token = const_store.append(crate::Constant { + name: None, + specialization: None, + inner, + }); crate::Expression::Constant(token) } ref other => panic!("Unknown expression {:?}", other), @@ -208,10 +267,7 @@ impl Parser { function_decl: pest::iterators::Pair, module: &mut crate::Module, ) -> Result, Error> { - enum Ident { - Parameter(u8), - } - let mut lookup_symbols = FastHashMap::default(); + let mut lookup_ident = FastHashMap::default(); assert_eq!(function_decl.as_rule(), Rule::function_decl); let mut function_decl_pairs = function_decl.into_inner(); @@ -233,13 +289,13 @@ impl Parser { assert_eq!(variable_ident_decl.as_rule(), Rule::variable_ident_decl); let mut variable_ident_decl_pairs = variable_ident_decl.into_inner(); let param_name = variable_ident_decl_pairs.next().unwrap().as_str().to_owned(); - lookup_symbols.insert(param_name, Ident::Parameter(i as u8)); + let expression_token = fun.expressions.append(crate::Expression::FunctionParameter(i as u32)); + lookup_ident.insert(param_name, expression_token); let param_type_decl = variable_ident_decl_pairs.next().unwrap(); let ty = self.parse_type_decl(param_type_decl, &mut module.types)?; fun.parameter_types.push(ty); } - let function_type_decl = function_header_pairs.next().unwrap(); - if function_type_decl.as_rule() == Rule::type_decl { + if let Some(function_type_decl) = function_header_pairs.next() { let ty = self.parse_type_decl(function_type_decl, &mut module.types)?; fun.return_type = Some(ty); } @@ -257,11 +313,21 @@ impl Parser { Rule::return_statement => { let mut return_pairs = first_statement.into_inner(); let value = match return_pairs.next() { - Some(st) => Some(self.parse_primary_expression(st, &mut fun, &mut module.constants)?), + Some(exp) => Some(self.parse_primary_expression(exp, &mut fun, &mut module.constants)?), None => None, }; crate::Statement::Return { value } } + Rule::assignment_statement => { + let mut assignment_pairs = first_statement.into_inner(); + let left_token = lookup_ident.lookup(assignment_pairs.next().unwrap().as_str())?; + let right_pair = assignment_pairs.next().unwrap(); + let right_token = self.parse_primary_expression(right_pair, &mut fun, &mut module.constants)?; + crate::Statement::Store { + pointer: left_token, + value: right_token, + } + } ref other => panic!("Unknown statement {:?}", other), }; fun.body.push(stmt); @@ -297,10 +363,7 @@ impl Parser { } else { spirv::StorageClass::Private }; - assert_eq!(body.as_rule(), Rule::variable_ident_decl); - let mut var_ident_decl_pairs = body.into_inner(); - let name = var_ident_decl_pairs.next().unwrap().as_str().to_owned(); - let ty = self.parse_type_decl(var_ident_decl_pairs.next().unwrap(), &mut module.types)?; + let (name, ty) = self.parse_variable_ident_decl(body, &mut module.types)?; module.global_variables.append(crate::GlobalVariable { name: Some(name), class, @@ -308,6 +371,18 @@ impl Parser { ty, }); } + Rule::global_constant_decl => { + let mut global_constant_pairs = global_decl.into_inner(); + let variable_ident_decl = global_constant_pairs.next().unwrap(); + let (name, _ty) = self.parse_variable_ident_decl(variable_ident_decl, &mut module.types)?; + let const_expr_decl = global_constant_pairs.next().unwrap(); + let inner = Self::parse_const_expression(const_expr_decl, &mut module.constants)?; + module.constants.append(crate::Constant { + name: Some(name), + specialization: None, + inner, + }); + } Rule::type_alias => { let mut type_alias_pairs = global_decl.into_inner(); let name = type_alias_pairs.next().unwrap().as_str().to_owned(); @@ -335,6 +410,34 @@ impl Parser { Rule::function_decl => { self.parse_function_decl(global_decl, &mut module)?; } + Rule::entry_point_decl => { + let mut ep_decl_pairs = global_decl.into_inner(); + let pipeline_stage_pair = ep_decl_pairs.next().unwrap(); + assert_eq!(pipeline_stage_pair.as_rule(), Rule::pipeline_stage); + let mut fun_name_pair = ep_decl_pairs.next().unwrap(); + let name = fun_name_pair.as_str().to_owned(); + if fun_name_pair.as_rule() == Rule::string_literal { + fun_name_pair = ep_decl_pairs.next().unwrap(); + } + let fun_ident = fun_name_pair.as_str(); + let function = module.functions + .iter() + .find(|(_, fun)| fun.name.as_ref().map(|s| s.as_str()) == Some(fun_ident)) + .map(|(token, _)| token) + .ok_or(Error::UnknownFunction(fun_ident.to_owned()))?; + module.entry_points.push(crate::EntryPoint { + exec_model: match pipeline_stage_pair.as_str() { + "vertex" => spirv::ExecutionModel::Vertex, + "fragment" => spirv::ExecutionModel::Fragment, + "compute" => spirv::ExecutionModel::GLCompute, + other => panic!("Unknown execution model {:?}", other), + }, + name, + inputs: Vec::new(), //TODO + outputs: Vec::new(), //TODO + function, + }); + } unknown => panic!("Unexpected global decl: {:?}", unknown), } } From d4fb81a00525e468464c141d0d6bac11f9eea1c5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 3 Mar 2020 22:56:02 -0500 Subject: [PATCH 0035/2212] [wgsl] basic typed constructors --- examples/convert.rs | 2 +- grammars/wgsl.pest | 6 ++++-- src/front/wgsl.rs | 30 +++++++++++++++++++++++++++--- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 11eadc9ac..35cc954e5 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -19,7 +19,7 @@ fn main() { }; if args.len() <= 2 { - println!("{:?}", module); + println!("{:#?}", module); return } else if args[2].ends_with(".metal") { use naga::back::msl; diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest index beb993a9c..54b0bf622 100644 --- a/grammars/wgsl.pest +++ b/grammars/wgsl.pest @@ -141,14 +141,16 @@ statement = { } primary_expression = _{ - type_decl ~ "(" ~ argument_expression_list ~ ")" + typed_expression | const_expr | multiplicative_expression } //multiplicative_expression = { primary_expression ~ "*" ~ primary_expression } //TODO multiplicative_expression = { ident ~ "*" ~ primary_expression } -argument_expression_list = { (primary_expression ~ ",")* ~ primary_expression } +typed_expression = { type_decl ~ "(" ~ argument_expression_list ~ ")" } +argument_expression_list = _{ (primary_expression ~ ",")* ~ primary_expression } + ident = @{ ASCII_ALPHA ~ (ASCII_ALPHANUMERIC | "_")* } int_literal = @{ ("-"? ~ "0x"? ~ ASCII_HEX_DIGIT+) | "0" | ("-"? ~ ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 4410f7528..f53c9f87a 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -245,9 +245,20 @@ impl Parser { &self, primary_expression: pest::iterators::Pair, function: &mut crate::Function, + type_store: &mut Storage, const_store: &mut Storage, ) -> Result, Error> { let expression = match primary_expression.as_rule() { + Rule::typed_expression => { + let mut expr_pairs = primary_expression.into_inner(); + let ty = self.parse_type_decl(expr_pairs.next().unwrap(), type_store)?; + let mut components = Vec::new(); + for argument_pair in expr_pairs { + let expr_token = self.parse_primary_expression(argument_pair, function, type_store, const_store)?; + components.push(expr_token); + } + crate::Expression::Compose { ty, components } + } Rule::const_expr => { let inner = Self::parse_const_expression(primary_expression, const_store)?; let token = const_store.append(crate::Constant { @@ -257,7 +268,7 @@ impl Parser { }); crate::Expression::Constant(token) } - ref other => panic!("Unknown expression {:?}", other), + _ => panic!("Unknown expression {:?}", primary_expression), }; Ok(function.expressions.append(expression)) } @@ -283,6 +294,19 @@ impl Parser { expressions: Storage::new(), body: Vec::new(), }; + for (const_token, constant) in module.constants.iter() { + if let Some(ref name) = constant.name { + let expr_token = fun.expressions.append(crate::Expression::Constant(const_token)); + lookup_ident.insert(name.clone(), expr_token); + } + } + for (var_token, variable) in module.global_variables.iter() { + if let Some(ref name) = variable.name { + let expr_token = fun.expressions.append(crate::Expression::GlobalVariable(var_token)); + lookup_ident.insert(name.clone(), expr_token); + } + } + let param_list = function_header_pairs.next().unwrap(); assert_eq!(param_list.as_rule(), Rule::param_list); for (i, variable_ident_decl) in param_list.into_inner().enumerate() { @@ -313,7 +337,7 @@ impl Parser { Rule::return_statement => { let mut return_pairs = first_statement.into_inner(); let value = match return_pairs.next() { - Some(exp) => Some(self.parse_primary_expression(exp, &mut fun, &mut module.constants)?), + Some(exp) => Some(self.parse_primary_expression(exp, &mut fun, &mut module.types, &mut module.constants)?), None => None, }; crate::Statement::Return { value } @@ -322,7 +346,7 @@ impl Parser { let mut assignment_pairs = first_statement.into_inner(); let left_token = lookup_ident.lookup(assignment_pairs.next().unwrap().as_str())?; let right_pair = assignment_pairs.next().unwrap(); - let right_token = self.parse_primary_expression(right_pair, &mut fun, &mut module.constants)?; + let right_token = self.parse_primary_expression(right_pair, &mut fun, &mut module.types, &mut module.constants)?; crate::Statement::Store { pointer: left_token, value: right_token, From 13a4c4112177b44da98bc6315e365fd877b796fb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 3 Mar 2020 22:57:20 -0500 Subject: [PATCH 0036/2212] Include test WGSL shaders --- test-data/boids.wgsl | 152 +++++++++++++++++++++++++++++++++++++++++++ test-data/quad.wgsl | 25 +++++++ 2 files changed, 177 insertions(+) create mode 100644 test-data/boids.wgsl create mode 100644 test-data/quad.wgsl diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl new file mode 100644 index 000000000..6df8a30b3 --- /dev/null +++ b/test-data/boids.wgsl @@ -0,0 +1,152 @@ +# Copyright 2020 The Tint Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import "GLSL.std.450" as std; + +# vertex shader + +[[location 0]] var a_particlePos : vec2; +[[location 1]] var a_particleVel : vec2; +[[location 2]] var a_pos : vec2; +[[builtin position]] var gl_Position : vec4; + +fn vtx_main() -> void { + var angle : f32 = -std::atan2(a_particleVel.x, a_particleVel.y); + var pos : vec2 = vec2( + (a_pos.x * std::cos(angle)) - (a_pos.y * std::sin(angle)), + (a_pos.x * std::sin(angle)) + (a_pos.y * std::cos(angle))); + gl_Position = vec4(pos + a_particlePos, 0, 1); + return; +} +entry_point vertex as "main" = vtx_main; + +# fragment shader +[[location 0]] var fragColor : vec4; + +fn frag_main() -> void { + fragColor = vec4(1.0, 1.0, 1.0, 1.0); + return; +} +entry_point fragment as "main" = frag_main; + +# compute shader +type Particle = struct { + [[offset 0]] pos : vec2; + [[offset 8]] vel : vec2; +}; + +type SimParams = struct { + [[offset 0]] deltaT : f32; + [[offset 4]] rule1Distance : f32; + [[offset 8]] rule2Distance : f32; + [[offset 12]] rule3Distance : f32; + [[offset 16]] rule1Scale : f32; + [[offset 20]] rule2Scale : f32; + [[offset 24]] rule3Scale : f32; +}; + +type Particles = struct { + [[offset 0]] particles : array; +}; + +[[binding 0, set 0]] var params : SimParams; +[[binding 1, set 0]] var particlesA : Particles; +[[binding 2, set 0]] var particlesB : Particles; + +[[builtin global_invocation_id]] var gl_GlobalInvocationID : vec3; + +# https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp +fn compute_main() -> void { + var index : u32 = gl_GlobalInvocationID.x; + if (index >= 5) { + return; + } + + var vPos : vec2 = particlesA.particles[index].pos; + var vVel : vec2 = particlesA.particles[index].vel; + + var cMass : vec2 = vec2(0, 0); + var cVel : vec2 = vec2(0, 0); + var colVel : vec2 = vec2(0, 0); + var cMassCount : i32 = 0; + var cVelCount : i32 = 0; + + var pos : vec2; + var vel : vec2; + var i : i32 = 0; + loop { + if (i >= 5) { + break; + } + if (i == index) { + continue; + } + + pos = particlesA.particles[i].pos.xy; + vel = particlesA.particles[i].vel.xy; + + if (std::distance(pos, vPos) < params.rule1Distance) { + cMass = cMass + pos; + cMassCount = cMassCount + 1; + } + if (std::distance(pos, vPos) < params.rule2Distance) { + colVel = colVel - (pos - vPos); + } + if (std::distance(pos, vPos) < params.rule3Distance) { + cVel = cVel + vel; + cVelCount = cVelCount + 1; + } + + continuing { + i = i + 1; + } + } + if (cMassCount > 0) { + cMass = (cMass / vec2(cMassCount, cMassCount)) + vPos; + } + if (cVelCount > 0) { + cVel = cVel / vec2(cVelCount, cVelCount); + } + + vVel = vVel + (cMass * params.rule1Scale) + (colVel * params.rule2Scale) + + (cVel * params.rule3Scale); + + # clamp velocity for a more pleasing simulation + vVel = std::normalize(vVel) * std::fclamp(std::length(vVel), 0.0, 0.1); + + # kinematic update + vPos = vPos + (vVel * params.deltaT); + + # Wrap around boundary + if (vPos.x < -1.0) { + vPos.x = 1.0; + } + if (vPos.x > 1.0) { + vPos.x = -1.0; + } + if (vPos.y < -1.0) { + vPos.y = 1.0; + } + if (vPos.y > 1.0) { + vPos.y = -1.0; + } + + # Write back + particlesB.particles[index].pos = vPos; + particlesB.particles[index].vel = vVel; + + return; +} +entry_point compute as "main" = compute_main; + diff --git a/test-data/quad.wgsl b/test-data/quad.wgsl new file mode 100644 index 000000000..738e01dcb --- /dev/null +++ b/test-data/quad.wgsl @@ -0,0 +1,25 @@ +# vertex +const c_scale: f32 = 1.2; +[[location 0]] var a_pos : vec2; +[[location 1]] var a_uv : vec2; +[[location 0]] var v_uv : vec2; +[[builtin position]] var o_position : vec4; + +fn main_vert() -> void { +# scale * a_pos + o_position = vec4(0.0, 0.0, 0.0, 1.0); + return; +} +entry_point vertex as "main" = main_vert; + +# fragment +[[location 0]] var a_uv : vec2; +#layout(set = 0, binding = 0) uniform texture2D u_texture; +#layout(set = 0, binding = 1) uniform sampler u_sampler; +[[location 0]] var o_color : vec4; + +fn main_frag() -> void { + o_color = vec4(1, 0, 0, 1); #TODO: sample + return; +} +entry_point fragment as "main" = main_frag; From 3bf1760d5b20f325229162ecda86140f8097479c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 5 Mar 2020 11:21:36 -0500 Subject: [PATCH 0037/2212] [ir] add SAMPLED image flag --- src/back/msl.rs | 20 +++++++++++++------- src/front/spirv.rs | 24 ++++++++++++------------ src/lib.rs | 5 +++-- 3 files changed, 28 insertions(+), 21 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 20b752bc9..10336b782 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -56,6 +56,7 @@ pub enum Error { MixedExecutionModels(crate::Token), MissingBinding(crate::Token), MissingBindTarget(BindSource), + InvalidImageFlags(crate::ImageFlags), BadName(String), } @@ -510,14 +511,19 @@ impl Writer { spirv::Dim::DimCube => "Cube", _ => panic!("Unsupported dim {:?}", dim), }; - let access = if flags.contains(crate::ImageFlags::READABLE | crate::ImageFlags::WRITABLE) { - "read_write" - } else if flags.contains(crate::ImageFlags::WRITABLE) { - "write" - } else { - assert!(flags.contains(crate::ImageFlags::READABLE)); - //TODO: figure out when to use `read` + let access = if flags.contains(crate::ImageFlags::SAMPLED) { + if flags.intersects(crate::ImageFlags::CAN_STORE) { + return Err(Error::InvalidImageFlags(flags)); + } "sample" + } else if flags.contains(crate::ImageFlags::CAN_LOAD | crate::ImageFlags::CAN_STORE) { + "read_write" + } else if flags.contains(crate::ImageFlags::CAN_STORE) { + "write" + } else if flags.contains(crate::ImageFlags::CAN_LOAD) { + "read" + } else { + return Err(Error::InvalidImageFlags(flags)); }; write!(self.out, "typedef texture{}<{}, access::{}> {}", dim, base_name, access, name)?; } diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 020b63188..45b768db8 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -1066,21 +1066,21 @@ impl> Parser { flags |= crate::ImageFlags::MULTISAMPLED; } let is_sampled = self.next()?; + if is_sampled != 0 { + flags |= crate::ImageFlags::SAMPLED; + } let _format = self.next()?; - let access = if inst.wc > 9 { + if inst.wc > 9 { inst.expect(10)?; - self.next()? - } else if is_sampled == 1 { - 0 // read-only - } else { - 2 // read-write + let access = self.next()?; + if access == 0 || access == 2 { + flags |= crate::ImageFlags::CAN_LOAD; + } + if access == 1 || access == 2 { + flags |= crate::ImageFlags::CAN_STORE; + } }; - if access == 0 || access == 2 { - flags |= crate::ImageFlags::READABLE; - } - if access == 1 || access == 2 { - flags |= crate::ImageFlags::WRITABLE; - } + let decor = self.future_decor .remove(&id) .unwrap_or_default(); diff --git a/src/lib.rs b/src/lib.rs index 70e28471c..ad61a8359 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -60,8 +60,9 @@ bitflags::bitflags! { pub struct ImageFlags: u32 { const ARRAYED = 0x1; const MULTISAMPLED = 0x2; - const READABLE = 0x4; - const WRITABLE = 0x8; + const SAMPLED = 0x4; + const CAN_LOAD = 0x10; + const CAN_STORE = 0x20; } } From 279af921bccaa8140d48295a052bd51885a94c23 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Thu, 5 Mar 2020 01:39:52 -0330 Subject: [PATCH 0038/2212] [wgsl] richer expression grammar --- grammars/wgsl.pest | 68 +++++++++++++++++++++++++++++++++++++++++---- test-data/quad.wgsl | 2 +- 2 files changed, 64 insertions(+), 6 deletions(-) diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest index 54b0bf622..a478e4f17 100644 --- a/grammars/wgsl.pest +++ b/grammars/wgsl.pest @@ -132,7 +132,7 @@ statement = { // | regardless_stmt // | switch_stmt // | loop_stmt -// | variable_stmt ~ ";" + | variable_stmt ~ ";" // | break_stmt ~ ";" // | continue_stmt ~ ";" // | KILL ~ ";" @@ -140,17 +140,75 @@ statement = { | assignment_statement ~ ";" } +variable_stmt = _{ + variable_decl ~ "=" ~ logical_or_expression + | "const" ~ variable_ident_decl ~ "=" ~ logical_or_expression + | variable_decl +} + primary_expression = _{ typed_expression | const_expr + | paren_rhs_stmt + | ident +} + +unary_expression = { + primary_expression +} + +multiplicative_expression = { + unary_expression ~ "*" ~ multiplicative_expression + | unary_expression +} + +additive_expression = { + multiplicative_expression ~ "+" ~ additive_expression | multiplicative_expression } -//multiplicative_expression = { primary_expression ~ "*" ~ primary_expression } //TODO -multiplicative_expression = { ident ~ "*" ~ primary_expression } -typed_expression = { type_decl ~ "(" ~ argument_expression_list ~ ")" } -argument_expression_list = _{ (primary_expression ~ ",")* ~ primary_expression } +shift_expression = { + additive_expression +} +relational_expression = { + shift_expression +} + +equality_expression = { + relational_expression ~ "==" ~ relational_expression + | relational_expression +} + +and_expression = { + equality_expression ~ "=" ~ and_expression + | equality_expression +} + +exclusive_or_expression = { + and_expression ~ "^" ~ exclusive_or_expression + | and_expression +} + +inclusive_or_expression = { + exclusive_or_expression ~ "|" ~ inclusive_or_expression + | exclusive_or_expression +} + +logical_and_expression = { + inclusive_or_expression ~ "&&" ~ logical_and_expression + | inclusive_or_expression +} + +logical_or_expression = { + logical_and_expression ~ "||" ~ logical_or_expression + | logical_and_expression +} + +paren_rhs_stmt = { "(" ~ logical_or_expression ~ ")" } + +typed_expression = { type_decl ~ "(" ~ argument_expression_list ~ ")" } +argument_expression_list = _{ (logical_or_expression ~ ",")* ~ logical_or_expression } ident = @{ ASCII_ALPHA ~ (ASCII_ALPHANUMERIC | "_")* } int_literal = @{ ("-"? ~ "0x"? ~ ASCII_HEX_DIGIT+) | "0" | ("-"? ~ ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } diff --git a/test-data/quad.wgsl b/test-data/quad.wgsl index 738e01dcb..909b63865 100644 --- a/test-data/quad.wgsl +++ b/test-data/quad.wgsl @@ -7,7 +7,7 @@ const c_scale: f32 = 1.2; fn main_vert() -> void { # scale * a_pos - o_position = vec4(0.0, 0.0, 0.0, 1.0); + o_position = vec4(2.0 * 3.0, 0.0, 0.0, 1.0); return; } entry_point vertex as "main" = main_vert; From 330ce644d8579517b53c9d0249902d2e0d2961cd Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 5 Mar 2020 13:14:06 -0500 Subject: [PATCH 0039/2212] [wgsl] parse most binary expressions --- grammars/wgsl.pest | 60 +++---------- src/front/spirv.rs | 6 +- src/front/wgsl.rs | 211 ++++++++++++++++++++++++++++++++++++++------ src/lib.rs | 24 ++++- test-data/quad.wgsl | 3 +- 5 files changed, 224 insertions(+), 80 deletions(-) diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest index a478e4f17..c24d10b02 100644 --- a/grammars/wgsl.pest +++ b/grammars/wgsl.pest @@ -132,7 +132,7 @@ statement = { // | regardless_stmt // | switch_stmt // | loop_stmt - | variable_stmt ~ ";" + | variable_statement ~ ";" // | break_stmt ~ ";" // | continue_stmt ~ ";" // | KILL ~ ";" @@ -140,7 +140,7 @@ statement = { | assignment_statement ~ ";" } -variable_stmt = _{ +variable_statement = _{ variable_decl ~ "=" ~ logical_or_expression | "const" ~ variable_ident_decl ~ "=" ~ logical_or_expression | variable_decl @@ -153,59 +153,27 @@ primary_expression = _{ | ident } -unary_expression = { +unary_expression = _{ primary_expression } -multiplicative_expression = { - unary_expression ~ "*" ~ multiplicative_expression - | unary_expression -} - -additive_expression = { - multiplicative_expression ~ "+" ~ additive_expression - | multiplicative_expression -} - -shift_expression = { +multiplicative_expression = { unary_expression ~ ("*" ~ unary_expression)* } +additive_expression = { multiplicative_expression ~ ("+" ~ multiplicative_expression)* } +shift_expression = _{ additive_expression } - -relational_expression = { +relational_expression = _{ shift_expression } -equality_expression = { - relational_expression ~ "==" ~ relational_expression - | relational_expression -} +equality_expression = { relational_expression ~ ("==" ~ relational_expression)* } +and_expression = { equality_expression ~ ("&" ~ equality_expression)* } +exclusive_or_expression = { and_expression ~ ("^" ~ and_expression)* } +inclusive_or_expression = { exclusive_or_expression ~ ("|" ~ exclusive_or_expression)* } +logical_and_expression = { inclusive_or_expression ~ ("&&" ~ inclusive_or_expression)* } +logical_or_expression = { logical_and_expression ~ ("||" ~ logical_and_expression)* } -and_expression = { - equality_expression ~ "=" ~ and_expression - | equality_expression -} - -exclusive_or_expression = { - and_expression ~ "^" ~ exclusive_or_expression - | and_expression -} - -inclusive_or_expression = { - exclusive_or_expression ~ "|" ~ inclusive_or_expression - | exclusive_or_expression -} - -logical_and_expression = { - inclusive_or_expression ~ "&&" ~ logical_and_expression - | inclusive_or_expression -} - -logical_or_expression = { - logical_and_expression ~ "||" ~ logical_or_expression - | logical_and_expression -} - -paren_rhs_stmt = { "(" ~ logical_or_expression ~ ")" } +paren_rhs_stmt = _{ "(" ~ logical_or_expression ~ ")" } typed_expression = { type_decl ~ "(" ~ argument_expression_list ~ ")" } argument_expression_list = _{ (logical_or_expression ~ ",")* ~ logical_or_expression } diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 45b768db8..0c7e4db63 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -60,7 +60,7 @@ pub enum Error { InvalidVectorSize(spirv::Word), InvalidVariableClass(spirv::StorageClass), InvalidAccessType(spirv::Word), - InvalidAccessIndex(crate::Expression), + InvalidAccessIndex(Token), InvalidLoadType(spirv::Word), InvalidStoreType(spirv::Word), InvalidBinding(spirv::Word), @@ -399,10 +399,10 @@ impl> Parser { match const_store[const_token].inner { crate::ConstantInner::Uint(v) => v as u32, crate::ConstantInner::Sint(v) => v as u32, - _ => return Err(Error::InvalidAccessIndex(crate::Expression::Constant(const_token))), + _ => return Err(Error::InvalidAccessIndex(index_expr.token)), } } - ref other => return Err(Error::InvalidAccessIndex(other.clone())) + _ => return Err(Error::InvalidAccessIndex(index_expr.token)) }; AccessExpression { base_token: fun.expressions.append(crate::Expression::AccessIndex { diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index f53c9f87a..9f17730b6 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -19,6 +19,7 @@ pub enum Error { UnknownIdent(String), UnknownType(String), UnknownFunction(String), + InvalidVariableClass(spirv::StorageClass), } impl From> for Error { fn from(error: pest::error::Error) -> Self { @@ -49,6 +50,48 @@ impl StringValueLookup for FastHashMap> { } } +type ExpressionResult = Result, Error>; + +struct ExpressionContext<'a> { + function: &'a mut crate::Function, + lookup_ident: &'a FastHashMap>, + types: &'a mut Storage, + constants: &'a mut Storage, +} + +impl<'a> ExpressionContext<'a> { + fn reborrow(&mut self) -> ExpressionContext { + ExpressionContext { + function: self.function, + lookup_ident: self.lookup_ident, + types: self.types, + constants: self.constants, + } + } + + fn parse_binary( + &mut self, + expression_pair: pest::iterators::Pair, + rule: Rule, + op: crate::BinaryOperator, + mut parser: impl FnMut(pest::iterators::Pair, ExpressionContext<'_>) -> ExpressionResult, + ) -> ExpressionResult { + assert_eq!(expression_pair.as_rule(), rule); + let mut expression_pairs = expression_pair.into_inner(); + let base_pair = expression_pairs.next().unwrap(); + let mut left = parser(base_pair, self.reborrow())?; + for next_pair in expression_pairs { + let expression = crate::Expression::Binary { + op, + left, + right: parser(next_pair, self.reborrow())?, + }; + left = self.function.expressions.append(expression); + } + Ok(left) + } +} + pub struct Parser { lookup_type: FastHashMap>, } @@ -170,6 +213,25 @@ impl Parser { Ok((name, ty)) } + fn parse_variable_decl( + &self, + variable_decl: pest::iterators::Pair, + type_store: &mut Storage, + ) -> Result<(String, Option, Token), Error> { + assert_eq!(variable_decl.as_rule(), Rule::variable_decl); + let mut var_decl_pairs = variable_decl.into_inner(); + let mut body = var_decl_pairs.next().unwrap(); + let class = if body.as_rule() == Rule::storage_class { + let class = Self::parse_storage_class(body)?; + body = var_decl_pairs.next().unwrap(); + Some(class) + } else { + None + }; + let (name, ty) = self.parse_variable_ident_decl(body, type_store)?; + Ok((name, class, ty)) + } + fn parse_struct_decl( &self, struct_body_decl: pest::iterators::Pair, @@ -244,33 +306,94 @@ impl Parser { fn parse_primary_expression( &self, primary_expression: pest::iterators::Pair, - function: &mut crate::Function, - type_store: &mut Storage, - const_store: &mut Storage, - ) -> Result, Error> { - let expression = match primary_expression.as_rule() { + mut ctx: ExpressionContext, + ) -> ExpressionResult { + match primary_expression.as_rule() { Rule::typed_expression => { let mut expr_pairs = primary_expression.into_inner(); - let ty = self.parse_type_decl(expr_pairs.next().unwrap(), type_store)?; + let ty = self.parse_type_decl(expr_pairs.next().unwrap(), ctx.types)?; let mut components = Vec::new(); for argument_pair in expr_pairs { - let expr_token = self.parse_primary_expression(argument_pair, function, type_store, const_store)?; + let expr_token = self.parse_primary_expression(argument_pair, ctx.reborrow())?; components.push(expr_token); } - crate::Expression::Compose { ty, components } + let expression = crate::Expression::Compose { ty, components }; + Ok(ctx.function.expressions.append(expression)) } Rule::const_expr => { - let inner = Self::parse_const_expression(primary_expression, const_store)?; - let token = const_store.append(crate::Constant { + let inner = Self::parse_const_expression(primary_expression, ctx.constants)?; + let token = ctx.constants.append(crate::Constant { name: None, specialization: None, inner, }); - crate::Expression::Constant(token) + let expression = crate::Expression::Constant(token); + Ok(ctx.function.expressions.append(expression)) + } + Rule::logical_or_expression => { + self.parse_logical_or_expression(primary_expression, ctx) + } + Rule::ident => { + ctx.lookup_ident.lookup(primary_expression.as_str()) } _ => panic!("Unknown expression {:?}", primary_expression), - }; - Ok(function.expressions.append(expression)) + } + } + + fn parse_relational_expression( + &self, + pair: pest::iterators::Pair, + mut context: ExpressionContext, + ) -> ExpressionResult { + context.parse_binary( + pair, + Rule::additive_expression, + crate::BinaryOperator::Add, + |pair, mut context| context.parse_binary( + pair, + Rule::multiplicative_expression, + crate::BinaryOperator::Multiply, + |pair, context| self.parse_primary_expression(pair, context), + ), + ) + } + + fn parse_logical_or_expression( + &self, + pair: pest::iterators::Pair, + mut context: ExpressionContext, + ) -> ExpressionResult { + context.parse_binary( + pair, + Rule::logical_or_expression, + crate::BinaryOperator::LogicalOr, + |pair, mut context| context.parse_binary( + pair, + Rule::logical_and_expression, + crate::BinaryOperator::LogicalAnd, + |pair, mut context| context.parse_binary( + pair, + Rule::inclusive_or_expression, + crate::BinaryOperator::InclusiveOr, + |pair, mut context| context.parse_binary( + pair, + Rule::exclusive_or_expression, + crate::BinaryOperator::ExclusiveOr, + |pair, mut context| context.parse_binary( + pair, + Rule::and_expression, + crate::BinaryOperator::And, + |pair, mut context| context.parse_binary( + pair, + Rule::equality_expression, + crate::BinaryOperator::Equals, + |pair, context| self.parse_relational_expression(pair, context), + ), + ), + ), + ), + ), + ) } fn parse_function_decl( @@ -333,26 +456,68 @@ impl Parser { Some(st) => st, None => continue, }; + let context = ExpressionContext { + function: &mut fun, + lookup_ident: &lookup_ident, + types: &mut module.types, + constants: &mut module.constants, + }; let stmt = match first_statement.as_rule() { Rule::return_statement => { let mut return_pairs = first_statement.into_inner(); let value = match return_pairs.next() { - Some(exp) => Some(self.parse_primary_expression(exp, &mut fun, &mut module.types, &mut module.constants)?), + Some(exp) => Some(self.parse_primary_expression(exp, context)?), None => None, }; crate::Statement::Return { value } } + Rule::variable_statement => { + let mut variable_pairs = first_statement.into_inner(); + let variable_decl = variable_pairs.next().unwrap(); + match variable_decl.as_rule() { + Rule::variable_decl => { + let (name, class, ty) = self.parse_variable_decl(variable_decl, context.types)?; + if let Some(class) = class { + return Err(Error::InvalidVariableClass(class)); + } + let value = if let Some(value_pair) = variable_pairs.next() { + let value_token = self.parse_primary_expression(value_pair, context)?; + lookup_ident.insert(name.clone(), value_token); + Some(value_token) + } else { + None + }; + crate::Statement::VariableDeclaration { + name, + ty, + value, + } + } + Rule::variable_ident_decl => { + let (name, ty) = self.parse_variable_ident_decl(variable_decl, context.types)?; + let value_pair = variable_pairs.next().unwrap(); + let value_token = self.parse_primary_expression(value_pair, context)?; + lookup_ident.insert(name.clone(), value_token); + crate::Statement::VariableDeclaration { + name, + ty, + value: Some(value_token), + } + } + _ => panic!("Unexpected variable decl {:?}", variable_decl) + } + } Rule::assignment_statement => { let mut assignment_pairs = first_statement.into_inner(); let left_token = lookup_ident.lookup(assignment_pairs.next().unwrap().as_str())?; let right_pair = assignment_pairs.next().unwrap(); - let right_token = self.parse_primary_expression(right_pair, &mut fun, &mut module.types, &mut module.constants)?; + let right_token = self.parse_primary_expression(right_pair, context)?; crate::Statement::Store { pointer: left_token, value: right_token, } } - ref other => panic!("Unknown statement {:?}", other), + _ => panic!("Unknown statement {:?}", first_statement), }; fun.body.push(stmt); } @@ -377,20 +542,10 @@ impl Parser { let mut global_decl_pairs = global_decl.into_inner(); let binding = Self::parse_decoration_list(global_decl_pairs.next().unwrap())?; let var_decl = global_decl_pairs.next().unwrap(); - assert_eq!(var_decl.as_rule(), Rule::variable_decl); - let mut var_decl_pairs = var_decl.into_inner(); - let mut body = var_decl_pairs.next().unwrap(); - let class = if body.as_rule() == Rule::storage_class { - let class = Self::parse_storage_class(body)?; - body = var_decl_pairs.next().unwrap(); - class - } else { - spirv::StorageClass::Private - }; - let (name, ty) = self.parse_variable_ident_decl(body, &mut module.types)?; + let (name, class, ty) = self.parse_variable_decl(var_decl, &mut module.types)?; module.global_variables.append(crate::GlobalVariable { name: Some(name), - class, + class: class.unwrap_or(spirv::StorageClass::Private), binding, ty, }); diff --git a/src/lib.rs b/src/lib.rs index ad61a8359..6279d2c27 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -114,7 +114,19 @@ pub struct GlobalVariable { pub ty: Token, } -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] +pub enum BinaryOperator { + Multiply, + Add, + Equals, + And, + ExclusiveOr, + InclusiveOr, + LogicalAnd, + LogicalOr, +} + +#[derive(Debug)] pub enum Expression { Access { base: Token, @@ -140,6 +152,11 @@ pub enum Expression { sampler: Token, coordinate: Token, }, + Binary { + op: BinaryOperator, + left: Token, + right: Token, + }, } pub type Block = Vec; @@ -149,6 +166,11 @@ pub struct FallThrough; #[derive(Debug)] pub enum Statement { Block(Block), + VariableDeclaration { + name: String, + ty: Token, + value: Option>, + }, If { condition: Token, //bool accept: Block, diff --git a/test-data/quad.wgsl b/test-data/quad.wgsl index 909b63865..3f5bd5391 100644 --- a/test-data/quad.wgsl +++ b/test-data/quad.wgsl @@ -6,8 +6,7 @@ const c_scale: f32 = 1.2; [[builtin position]] var o_position : vec4; fn main_vert() -> void { -# scale * a_pos - o_position = vec4(2.0 * 3.0, 0.0, 0.0, 1.0); + o_position = vec4(scale * a_pos, 0.0, 1.0); return; } entry_point vertex as "main" = main_vert; From ee7882723a8b499e615bbb03387ad07d08b15d00 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 5 Mar 2020 21:14:58 -0500 Subject: [PATCH 0040/2212] [wgsl] expect logical expressions, fix hex literals --- README.md | 2 +- grammars/wgsl.pest | 8 ++++---- test-data/quad.wgsl | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 3c374c4e8..cd547c5d8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Naga -[![Matrix](https://img.shields.io/badge/Matrix-%23gfx%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#gfx:matrix.org) +[![Matrix](https://img.shields.io/badge/Matrix-%23naga%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#naga:matrix.org) [![Crates.io](https://img.shields.io/crates/v/naga.svg?label=naga)](https://crates.io/crates/naga) [![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga) [![Build Status](https://travis-ci.org/gfx-rs/naga.svg?branch=master)](https://travis-ci.org/gfx-rs/naga) diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest index c24d10b02..56de1fc21 100644 --- a/grammars/wgsl.pest +++ b/grammars/wgsl.pest @@ -121,8 +121,8 @@ scalar_type = { | "u32" } -return_statement = { "return" ~ primary_expression? } -assignment_statement = { ident ~ "=" ~ primary_expression } +return_statement = { "return" ~ logical_or_expression? } +assignment_statement = { ident ~ "=" ~ logical_or_expression } statement = { ";" @@ -179,8 +179,8 @@ typed_expression = { type_decl ~ "(" ~ argument_expression_list ~ ")" } argument_expression_list = _{ (logical_or_expression ~ ",")* ~ logical_or_expression } ident = @{ ASCII_ALPHA ~ (ASCII_ALPHANUMERIC | "_")* } -int_literal = @{ ("-"? ~ "0x"? ~ ASCII_HEX_DIGIT+) | "0" | ("-"? ~ ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } -uint_literal = @{ ("0x"? ~ ASCII_HEX_DIGIT+) | "0" | (ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } +int_literal = @{ ("-"? ~ "0x" ~ ASCII_HEX_DIGIT+) | "0" | ("-"? ~ ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } +uint_literal = @{ ("0x" ~ ASCII_HEX_DIGIT+) | "0" | (ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } float_literal = @{ "-"? ~ ASCII_DIGIT+ ~ ("." ~ ASCII_DIGIT*)? } bool_literal = @{ "true" | "false" } string_literal = @{ "\"" ~ ( "\"\"" | (!"\"" ~ ANY) )* ~ "\"" } diff --git a/test-data/quad.wgsl b/test-data/quad.wgsl index 3f5bd5391..2666ea1e7 100644 --- a/test-data/quad.wgsl +++ b/test-data/quad.wgsl @@ -6,7 +6,7 @@ const c_scale: f32 = 1.2; [[builtin position]] var o_position : vec4; fn main_vert() -> void { - o_position = vec4(scale * a_pos, 0.0, 1.0); + o_position = vec4(c_scale * a_pos, 0.0, 1.0); return; } entry_point vertex as "main" = main_vert; From 3066c3b558f1186e1330d941ea825bc1977e3268 Mon Sep 17 00:00:00 2001 From: msiglreith Date: Fri, 6 Mar 2020 04:52:24 +0100 Subject: [PATCH 0041/2212] Fix newline handling (#11) Support also non-LF variants --- grammars/wgsl.pest | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest index 56de1fc21..62fe8daae 100644 --- a/grammars/wgsl.pest +++ b/grammars/wgsl.pest @@ -185,5 +185,5 @@ float_literal = @{ "-"? ~ ASCII_DIGIT+ ~ ("." ~ ASCII_DIGIT*)? } bool_literal = @{ "true" | "false" } string_literal = @{ "\"" ~ ( "\"\"" | (!"\"" ~ ANY) )* ~ "\"" } -WHITESPACE = _{ " " | "\t" | "\n" } -COMMENT = _{ "#" ~ (!"\n" ~ ANY)* } +WHITESPACE = _{ " " | "\t" | NEWLINE } +COMMENT = _{ "#" ~ (!NEWLINE ~ ANY)* } From e6fe97f410f55d4856d84c30b6da8f4427d799fa Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 9 Mar 2020 23:17:35 -0400 Subject: [PATCH 0042/2212] [wgsl] rewrite with our own parser --- Cargo.toml | 4 +- src/front/wgsl.rs | 1085 ++++++++++++++++++++++----------------------- src/lib.rs | 4 - 3 files changed, 526 insertions(+), 567 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8db524e08..ff430bd3e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,9 +13,7 @@ license = "MPL-2.0" bitflags = "1" fxhash = "0.2" log = "0.4" -pest = "2" -pest_derive = "2" -spirv_headers = "1" +spirv = { package = "spirv_headers", version = "1" } [dev-dependencies] env_logger = "0.6" diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 9f17730b6..47baea070 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,194 +1,460 @@ use crate::{ - storage::{Storage, Token}, + storage::{Storage, Token as Id}, FastHashMap, }; +#[derive(Clone)] +struct Lexer<'a> { + input: &'a str, +} -#[derive(Parser)] -#[grammar = "../grammars/wgsl.pest"] -struct Tokenizer; +impl<'a> Lexer<'a> { + fn new(input: &'a str) -> Self { + Lexer { + input, + } + } +} + +#[derive(Debug, PartialEq)] +pub enum Token<'a> { + Separator(char), + Paren(char), + Number(&'a str), + Word(&'a str), + Operation { op: char, boolean: bool }, + End, +} + +impl<'a> Lexer<'a> { + fn consume_str(&mut self, what: &str) -> bool { + if self.input.starts_with(what) { + self.input = &self.input[what.len() ..]; + true + } else { + false + } + } + + fn consume_any(&mut self, what: impl Fn(char) -> bool) -> &'a str { + let pos = self.input.find(|c| !what(c)).unwrap_or(self.input.len()); + let (left, right) = self.input.split_at(pos); + debug_assert!(!left.is_empty(), "Leftover: '{}'...", &right[..10]); + self.input = right; + left + } + + fn skip_whitespace(&mut self) { + self.input = self.input.trim_start(); + } + + fn next(&mut self) -> Token<'a> { + self.skip_whitespace(); + let mut chars = self.input.chars(); + let cur = match chars.next() { + Some(c) => c, + None => return Token::End, + }; + match cur { + ':' | ';' | ',' | '.' => { + self.input = chars.as_str(); + Token::Separator(cur) + } + '(' | ')' | '[' | ']' | '<' | '>' => { + self.input = chars.as_str(); + Token::Paren(cur) + } + '0' ..= '9' => { + let number = self.consume_any(|c| (c>='0' && c<='9' || c=='.')); + Token::Number(number) + } + 'a'..='z' | 'A'..='Z' | '_' => { + let word = self.consume_any(|c| c.is_alphanumeric() || c=='_'); + Token::Word(word) + } + '=' | '+'| '-' | '*' | '/' | '&' | '|' | '^' => { + let next = chars.next(); + let boolean = (cur == '=' || cur == '&' || cur == '|') && next == Some(cur); + self.input = &self.input[if boolean { 2 } else { 1 } ..]; + Token::Operation { op: cur, boolean } + } + '#' => { + match chars.position(|c| c == '\n' || c == '\r') { + Some(_) => { + self.input = chars.as_str(); + self.next() + } + None => return Token::End, + } + } + _ => unimplemented!(), + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Scope { + Decoration, + ImportDecl, + VariableDecl, + TypeDecl, + ConstantExpr, +} #[derive(Debug)] -pub enum Error { - Pest(pest::error::Error), - BadInt(std::num::ParseIntError), - BadFloat(std::num::ParseFloatError), - BadStorageClass(String), - BadBool(String), - BadDecoration(String), - UnknownIdent(String), - UnknownType(String), - UnknownFunction(String), - InvalidVariableClass(spirv::StorageClass), -} -impl From> for Error { - fn from(error: pest::error::Error) -> Self { - Error::Pest(error) - } -} -impl From for Error { - fn from(error: std::num::ParseIntError) -> Self { - Error::BadInt(error) - } -} -impl From for Error { - fn from(error: std::num::ParseFloatError) -> Self { - Error::BadFloat(error) - } +pub enum Error<'a> { + Unexpected(Token<'a>), + BadInteger(&'a str, std::num::ParseIntError), + BadFloat(&'a str, std::num::ParseFloatError), + UnknownStorageClass(&'a str), + UnknownBuiltin(&'a str), + Other, } -trait StringValueLookup { - type Value; - fn lookup(&self, key: &str) -> Result; -} -impl StringValueLookup for FastHashMap> { - type Value = Token; - fn lookup(&self, key: &str) -> Result { - self.get(key) - .cloned() - .ok_or(Error::UnknownIdent(key.to_owned())) - } -} - -type ExpressionResult = Result, Error>; - -struct ExpressionContext<'a> { - function: &'a mut crate::Function, - lookup_ident: &'a FastHashMap>, - types: &'a mut Storage, - constants: &'a mut Storage, -} - -impl<'a> ExpressionContext<'a> { - fn reborrow(&mut self) -> ExpressionContext { - ExpressionContext { - function: self.function, - lookup_ident: self.lookup_ident, - types: self.types, - constants: self.constants, - } - } - - fn parse_binary( - &mut self, - expression_pair: pest::iterators::Pair, - rule: Rule, - op: crate::BinaryOperator, - mut parser: impl FnMut(pest::iterators::Pair, ExpressionContext<'_>) -> ExpressionResult, - ) -> ExpressionResult { - assert_eq!(expression_pair.as_rule(), rule); - let mut expression_pairs = expression_pair.into_inner(); - let base_pair = expression_pairs.next().unwrap(); - let mut left = parser(base_pair, self.reborrow())?; - for next_pair in expression_pairs { - let expression = crate::Expression::Binary { - op, - left, - right: parser(next_pair, self.reborrow())?, - }; - left = self.function.expressions.append(expression); - } - Ok(left) - } +#[derive(Debug)] +pub struct ParseError<'a> { + pub error: Error<'a>, + pub scopes: Vec, + pub pos: (usize, usize), } pub struct Parser { - lookup_type: FastHashMap>, + scopes: Vec, + lookup_type: FastHashMap>, } impl Parser { pub fn new() -> Self { Parser { + scopes: Vec::new(), lookup_type: FastHashMap::default(), } } - fn parse_uint_literal(pair: pest::iterators::Pair) -> Result { - Ok(pair.as_str().parse()?) - } - - fn parse_int_literal(pair: pest::iterators::Pair) -> Result { - Ok(pair.as_str().parse()?) - } - - fn parse_float_literal(pair: pest::iterators::Pair) -> Result { - Ok(pair.as_str().parse()?) - } - - fn parse_decoration_list(variable_decoration_list: pest::iterators::Pair) -> Result, Error> { - assert_eq!(variable_decoration_list.as_rule(), Rule::variable_decoration_list); - for variable_decoration in variable_decoration_list.into_inner() { - match variable_decoration.as_rule() { - Rule::location_decoration => { - let location_pair = variable_decoration.into_inner().next().unwrap(); - let location = Self::parse_uint_literal(location_pair)?; - return Ok(Some(crate::Binding::Location(location))); - } - Rule::builtin_decoration => { - let builtin = match variable_decoration.as_str() { - "position" => spirv::BuiltIn::Position, - "vertex_idx" => spirv::BuiltIn::VertexIndex, - other => return Err(Error::BadDecoration(other.to_owned())), - }; - return Ok(Some(crate::Binding::BuiltIn(builtin))); - } - unknown => panic!("Unexpected decoration: {:?}", unknown), - } + fn expect<'a>( + lexer: &mut Lexer<'a>, + expected: Token<'a>, + ) -> Result<(), Error<'a>> { + let token = lexer.next(); + if token == expected { + Ok(()) + } else { + Err(Error::Unexpected(token)) } - unimplemented!() } - fn parse_storage_class(storage_class: pest::iterators::Pair) -> Result { - match storage_class.as_str() { + fn parse_ident<'a>(&mut self, lexer: &mut Lexer<'a>) -> Result<&'a str, Error<'a>> { + match lexer.next() { + Token::Word(word) => Ok(word), + other => Err(Error::Unexpected(other)), + } + } + + fn _parse_float_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + match lexer.next() { + Token::Number(word) => word.parse().map_err(|err| Error::BadFloat(word, err)), + other => Err(Error::Unexpected(other)), + } + } + + fn parse_uint_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + match lexer.next() { + Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), + other => Err(Error::Unexpected(other)), + } + } + + fn _parse_sint_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + match lexer.next() { + Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), + other => Err(Error::Unexpected(other)), + } + } + + fn parse_scalar_generic<'a>(lexer: &mut Lexer<'a>) -> Result<(crate::ScalarKind, u8), Error<'a>> { + Self::expect(lexer, Token::Paren('<'))?; + let pair = match lexer.next() { + Token::Word("f32") => (crate::ScalarKind::Float, 32), + Token::Word("i32") => (crate::ScalarKind::Sint, 32), + Token::Word("u32") => (crate::ScalarKind::Uint, 32), + other => return Err(Error::Unexpected(other)), + }; + Self::expect(lexer, Token::Paren('>'))?; + Ok(pair) + } + + fn get_storage_class<'a>(word: &'a str) -> Result> { + match word { "in" => Ok(spirv::StorageClass::Input), "out" => Ok(spirv::StorageClass::Output), - other => Err(Error::BadStorageClass(other.to_owned())), + _ => Err(Error::UnknownStorageClass(word)), } } - fn parse_type_decl( - &self, - type_decl: pest::iterators::Pair, + fn get_built_in<'a>(word: &'a str) -> Result> { + match word { + "position" => Ok(spirv::BuiltIn::Position), + "vertex_idx" => Ok(spirv::BuiltIn::VertexId), + _ => Err(Error::UnknownBuiltin(word)), + } + } + + fn parse_const_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, type_store: &mut Storage, - ) -> Result, Error> { - assert_eq!(type_decl.as_rule(), Rule::type_decl); - let mut type_decl_pairs = type_decl.into_inner(); - let type_kind = type_decl_pairs.next().unwrap(); - let inner = match type_kind.as_rule() { - Rule::scalar_type => { - let kind = match type_kind.as_str() { - "f32" => crate::ScalarKind::Float, - "i32" => crate::ScalarKind::Sint, - "u32" => crate::ScalarKind::Uint, - other => panic!("Unexpected scalar kind {:?}", other), - }; - crate::TypeInner::Scalar { kind, width: 32 } + const_store: &mut Storage, + ) -> Result> { + self.scopes.push(Scope::ConstantExpr); + let backup = lexer.clone(); + let inner = match lexer.next() { + Token::Word("true") => crate::ConstantInner::Bool(true), + Token::Word("false") => crate::ConstantInner::Bool(false), + Token::Number(word) => { + if word.contains('.') { + let value = word + .parse() + .map_err(|err| Error::BadFloat(word, err))?; + crate::ConstantInner::Float(value) + } else { + let value = word + .parse() + .map_err(|err| Error::BadInteger(word, err))?; + crate::ConstantInner::Sint(value) + } } - Rule::type_array_kind => { - let base = self.parse_type_decl(type_decl_pairs.next().unwrap(), type_store)?; - let size = match type_decl_pairs.next() { - Some(pair) => crate::ArraySize::Static(Self::parse_uint_literal(pair)?), - None => crate::ArraySize::Dynamic, + _ => { + *lexer = backup; + let _ty = self.parse_type_decl(lexer, type_store); + Self::expect(lexer, Token::Paren('('))?; + loop { + let backup = lexer.clone(); + match lexer.next() { + Token::Paren(')') => break, + _ => { + *lexer = backup; + let _ = self.parse_const_expression(lexer, type_store, const_store)?; + } + } + } + unimplemented!() + } + }; + self.scopes.pop(); + Ok(inner) + } + + fn parse_variable_ident_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + type_store: &mut Storage, + ) -> Result<(&'a str, Id), Error<'a>> { + let name = match lexer.next() { + Token::Word(word) => word, + other => return Err(Error::Unexpected(other)), + }; + Self::expect(lexer, Token::Separator(':'))?; + let ty = self.parse_type_decl(lexer, type_store)?; + Ok((name, ty)) + } + + fn parse_variable_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + type_store: &mut Storage, + const_store: &mut Storage, + ) -> Result<(&'a str, Option, Id), Error<'a>> { + self.scopes.push(Scope::VariableDecl); + let mut class = None; + let mut token = lexer.next(); + if let Token::Paren('<') = token { + class = Some(match lexer.next() { + Token::Word(word) => Self::get_storage_class(word)?, + other => return Err(Error::Unexpected(other)), + }); + Self::expect(lexer, Token::Paren('>'))?; + token = lexer.next(); + } + let name = match token { + Token::Word(word) => word, + other => return Err(Error::Unexpected(other)), + }; + Self::expect(lexer, Token::Separator(':'))?; + let ty = self.parse_type_decl(lexer, type_store)?; + match lexer.next() { + Token::Separator(';') => {} + Token::Operation{ op: '=', boolean: false } => { + let _inner = self.parse_const_expression(lexer, type_store, const_store)?; + //TODO + Self::expect(lexer, Token::Separator(';'))?; + } + other => return Err(Error::Unexpected(other)), + } + self.scopes.pop(); + Ok((name, class, ty)) + } + + fn parse_struct_body<'a>( + &mut self, + lexer: &mut Lexer<'a>, + type_store: &mut Storage, + ) -> Result, Error<'a>> { + let mut members = Vec::new(); + Self::expect(lexer, Token::Paren('{'))?; + loop { + let mut token = lexer.next(); + if let Token::Paren('[') = token { + self.scopes.push(Scope::Decoration); + if !lexer.consume_str("[") { + return Err(Error::Other); + } + let mut ready = true; + loop { + match lexer.next() { + Token::Paren(']') => { + if !lexer.consume_str("]") { + return Err(Error::Other); + } + break; + } + Token::Separator(',') if !ready => { + ready = true; + } + Token::Word("offset") if ready => { + let _offset = Self::parse_uint_literal(lexer)?; //TODO + ready = false; + } + other => return Err(Error::Unexpected(other)), + } + } + token = lexer.next(); + self.scopes.pop(); + } + let name = match token { + Token::Word(word) => word, + Token::Paren('}') => return Ok(members), + other => return Err(Error::Unexpected(other)), + }; + Self::expect(lexer, Token::Separator(':'))?; + let ty = self.parse_type_decl(lexer, type_store)?; + Self::expect(lexer, Token::Separator(';'))?; + members.push(crate::StructMember { + name: Some(name.to_owned()), + binding: None, + ty, + }); + } + } + + fn parse_type_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + type_store: &mut Storage, + ) -> Result, Error<'a>> { + self.scopes.push(Scope::TypeDecl); + let inner = match lexer.next() { + Token::Word("f32") => { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: 32, + } + } + Token::Word("i32") => { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: 32, + } + } + Token::Word("u32") => { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: 32, + } + } + Token::Word("vec2") => { + let (kind, width) = Self::parse_scalar_generic(lexer)?; + crate::TypeInner::Vector { + size: crate::VectorSize::Bi, + kind, + width, + } + } + Token::Word("vec3") => { + let (kind, width) = Self::parse_scalar_generic(lexer)?; + crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + kind, + width, + } + } + Token::Word("vec4") => { + let (kind, width) = Self::parse_scalar_generic(lexer)?; + crate::TypeInner::Vector { + size: crate::VectorSize::Quad, + kind, + width, + } + } + Token::Word("mat2x2") => { + let (kind, width) = Self::parse_scalar_generic(lexer)?; + crate::TypeInner::Matrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Bi, + kind, + width, + } + } + Token::Word("mat3x3") => { + let (kind, width) = Self::parse_scalar_generic(lexer)?; + crate::TypeInner::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Tri, + kind, + width, + } + } + Token::Word("mat4x4") => { + let (kind, width) = Self::parse_scalar_generic(lexer)?; + crate::TypeInner::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Quad, + kind, + width, + } + } + Token::Word("ptr") => { + Self::expect(lexer, Token::Paren('<'))?; + let class = match lexer.next() { + Token::Word(word) => Self::get_storage_class(word)?, + other => return Err(Error::Unexpected(other)), + }; + Self::expect(lexer, Token::Separator(','))?; + let base = self.parse_type_decl(lexer, type_store)?; + Self::expect(lexer, Token::Paren('>'))?; + crate::TypeInner::Pointer { base, class } + } + Token::Word("array") => { + Self::expect(lexer, Token::Paren('<'))?; + let base = self.parse_type_decl(lexer, type_store)?; + let size = match lexer.next() { + Token::Separator(',') => { + let value = Self::parse_uint_literal(lexer)?; + Self::expect(lexer, Token::Paren('>'))?; + crate::ArraySize::Static(value) + } + Token::Separator('>') => crate::ArraySize::Dynamic, + other => return Err(Error::Unexpected(other)), }; crate::TypeInner::Array { base, size } } - Rule::type_vec_kind => { - let size = match type_kind.as_str() { - "vec2" => crate::VectorSize::Bi, - "vec3" => crate::VectorSize::Tri, - "vec4" => crate::VectorSize::Quad, - other => panic!("Unexpected vec kind {:?}", other), - }; - crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width: 32 } + Token::Word("struct") => { + let members = self.parse_struct_body(lexer, type_store)?; + crate::TypeInner::Struct { members } } - Rule::ident => { - return self.lookup_type - .get(type_kind.as_str()) - .cloned() - .ok_or(Error::UnknownType(type_kind.as_str().to_owned())); - } - other => panic!("Unexpected type {:?}", other), + other => return Err(Error::Unexpected(other)), }; + self.scopes.pop(); + if let Some((token, _)) = type_store .iter() .find(|(_, ty)| ty.inner == inner) @@ -201,433 +467,132 @@ impl Parser { })) } - fn parse_variable_ident_decl( - &self, - variable_ident_decl: pest::iterators::Pair, - type_store: &mut Storage, - ) -> Result<(String, Token), Error> { - assert_eq!(variable_ident_decl.as_rule(), Rule::variable_ident_decl); - let mut pairs = variable_ident_decl.into_inner(); - let name = pairs.next().unwrap().as_str().to_owned(); - let ty = self.parse_type_decl(pairs.next().unwrap(), type_store)?; - Ok((name, ty)) - } - - fn parse_variable_decl( - &self, - variable_decl: pest::iterators::Pair, - type_store: &mut Storage, - ) -> Result<(String, Option, Token), Error> { - assert_eq!(variable_decl.as_rule(), Rule::variable_decl); - let mut var_decl_pairs = variable_decl.into_inner(); - let mut body = var_decl_pairs.next().unwrap(); - let class = if body.as_rule() == Rule::storage_class { - let class = Self::parse_storage_class(body)?; - body = var_decl_pairs.next().unwrap(); - Some(class) - } else { - None - }; - let (name, ty) = self.parse_variable_ident_decl(body, type_store)?; - Ok((name, class, ty)) - } - - fn parse_struct_decl( - &self, - struct_body_decl: pest::iterators::Pair, - type_store: &mut Storage, - ) -> Result { - assert_eq!(struct_body_decl.as_rule(), Rule::struct_body_decl); - let mut members = Vec::new(); - for member_decl in struct_body_decl.into_inner() { - assert_eq!(member_decl.as_rule(), Rule::struct_member); - let mut member_decl_pairs = member_decl.into_inner(); - let mut body = member_decl_pairs.next().unwrap(); - let binding = None; - if body.as_rule() == Rule::struct_member_decoration_decl { - body = member_decl_pairs.next().unwrap(); //TODO: parse properly + fn parse_global_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + module: &mut crate::Module, + ) -> Result> { + match lexer.next() { + Token::Separator(';') => {}, + Token::Word("import") => { + self.scopes.push(Scope::ImportDecl); + let _path = lexer.next(); + //consume(words, "as", Scope::ImportDecl)?; + let _namespace = lexer.next(); + Self::expect(lexer, Token::Separator(';'))?; + self.scopes.pop(); } - let (member_name, ty) = self.parse_variable_ident_decl(body, type_store)?; - members.push(crate::StructMember { - name: Some(member_name), - binding, - ty, - }); - } - Ok(crate::TypeInner::Struct { members }) - } - - fn parse_const_literal( - const_literal: pest::iterators::Pair, - ) -> Result { - let inner = match const_literal.as_rule() { - Rule::int_literal => { - let value = Self::parse_int_literal(const_literal)?; - crate::ConstantInner::Sint(value as i64) + Token::Word("type") => { + let name = self.parse_ident(lexer)?; + Self::expect(lexer, Token::Operation { op: '=', boolean: false })?; + let ty = self.parse_type_decl(lexer, &mut module.types)?; + self.lookup_type.insert(name.to_owned(), ty); + Self::expect(lexer, Token::Separator(';'))?; } - Rule::uint_literal => { - let value = Self::parse_uint_literal(const_literal)?; - crate::ConstantInner::Uint(value as u64) - } - Rule::bool_literal => { - let value = match const_literal.as_str() { - "true" => true, - "false" => false, - other => return Err(Error::BadBool(other.to_owned())), - }; - crate::ConstantInner::Bool(value) - } - Rule::float_literal => { - let value = Self::parse_float_literal(const_literal)?; - crate::ConstantInner::Float(value as f64) - } - ref other => panic!("Unknown const literal {:?}", other), - }; - Ok(inner) - } - - fn parse_const_expression( - const_expression: pest::iterators::Pair, - _const_store: &mut Storage, - ) -> Result { - let mut const_expr_pairs = const_expression.into_inner(); - let first_pair = const_expr_pairs.next().unwrap(); - let inner = match first_pair.as_rule() { - Rule::const_literal => { - let const_literal = first_pair.into_inner().next().unwrap(); - Self::parse_const_literal(const_literal)? - } - Rule::type_decl => unimplemented!(), - _ => panic!("Unknown const expr {:?}", first_pair), - }; - Ok(inner) - } - - fn parse_primary_expression( - &self, - primary_expression: pest::iterators::Pair, - mut ctx: ExpressionContext, - ) -> ExpressionResult { - match primary_expression.as_rule() { - Rule::typed_expression => { - let mut expr_pairs = primary_expression.into_inner(); - let ty = self.parse_type_decl(expr_pairs.next().unwrap(), ctx.types)?; - let mut components = Vec::new(); - for argument_pair in expr_pairs { - let expr_token = self.parse_primary_expression(argument_pair, ctx.reborrow())?; - components.push(expr_token); - } - let expression = crate::Expression::Compose { ty, components }; - Ok(ctx.function.expressions.append(expression)) - } - Rule::const_expr => { - let inner = Self::parse_const_expression(primary_expression, ctx.constants)?; - let token = ctx.constants.append(crate::Constant { - name: None, + Token::Word("const") => { + let (name, _ty) = self.parse_variable_ident_decl(lexer, &mut module.types)?; + Self::expect(lexer, Token::Operation { op: '=', boolean: false })?; + let inner = self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; + module.constants.append(crate::Constant { + name: Some(name.to_owned()), specialization: None, inner, }); - let expression = crate::Expression::Constant(token); - Ok(ctx.function.expressions.append(expression)) + Self::expect(lexer, Token::Separator(';'))?; } - Rule::logical_or_expression => { - self.parse_logical_or_expression(primary_expression, ctx) - } - Rule::ident => { - ctx.lookup_ident.lookup(primary_expression.as_str()) - } - _ => panic!("Unknown expression {:?}", primary_expression), - } - } - - fn parse_relational_expression( - &self, - pair: pest::iterators::Pair, - mut context: ExpressionContext, - ) -> ExpressionResult { - context.parse_binary( - pair, - Rule::additive_expression, - crate::BinaryOperator::Add, - |pair, mut context| context.parse_binary( - pair, - Rule::multiplicative_expression, - crate::BinaryOperator::Multiply, - |pair, context| self.parse_primary_expression(pair, context), - ), - ) - } - - fn parse_logical_or_expression( - &self, - pair: pest::iterators::Pair, - mut context: ExpressionContext, - ) -> ExpressionResult { - context.parse_binary( - pair, - Rule::logical_or_expression, - crate::BinaryOperator::LogicalOr, - |pair, mut context| context.parse_binary( - pair, - Rule::logical_and_expression, - crate::BinaryOperator::LogicalAnd, - |pair, mut context| context.parse_binary( - pair, - Rule::inclusive_or_expression, - crate::BinaryOperator::InclusiveOr, - |pair, mut context| context.parse_binary( - pair, - Rule::exclusive_or_expression, - crate::BinaryOperator::ExclusiveOr, - |pair, mut context| context.parse_binary( - pair, - Rule::and_expression, - crate::BinaryOperator::And, - |pair, mut context| context.parse_binary( - pair, - Rule::equality_expression, - crate::BinaryOperator::Equals, - |pair, context| self.parse_relational_expression(pair, context), - ), - ), - ), - ), - ), - ) - } - - fn parse_function_decl( - &self, - function_decl: pest::iterators::Pair, - module: &mut crate::Module, - ) -> Result, Error> { - let mut lookup_ident = FastHashMap::default(); - assert_eq!(function_decl.as_rule(), Rule::function_decl); - let mut function_decl_pairs = function_decl.into_inner(); - - let function_header = function_decl_pairs.next().unwrap(); - assert_eq!(function_header.as_rule(), Rule::function_header); - let mut function_header_pairs = function_header.into_inner(); - let fun_name = function_header_pairs.next().unwrap().as_str().to_owned(); - let mut fun = crate::Function { - name: Some(fun_name), - control: spirv::FunctionControl::empty(), - parameter_types: Vec::new(), - return_type: None, - expressions: Storage::new(), - body: Vec::new(), - }; - for (const_token, constant) in module.constants.iter() { - if let Some(ref name) = constant.name { - let expr_token = fun.expressions.append(crate::Expression::Constant(const_token)); - lookup_ident.insert(name.clone(), expr_token); - } - } - for (var_token, variable) in module.global_variables.iter() { - if let Some(ref name) = variable.name { - let expr_token = fun.expressions.append(crate::Expression::GlobalVariable(var_token)); - lookup_ident.insert(name.clone(), expr_token); - } - } - - let param_list = function_header_pairs.next().unwrap(); - assert_eq!(param_list.as_rule(), Rule::param_list); - for (i, variable_ident_decl) in param_list.into_inner().enumerate() { - assert_eq!(variable_ident_decl.as_rule(), Rule::variable_ident_decl); - let mut variable_ident_decl_pairs = variable_ident_decl.into_inner(); - let param_name = variable_ident_decl_pairs.next().unwrap().as_str().to_owned(); - let expression_token = fun.expressions.append(crate::Expression::FunctionParameter(i as u32)); - lookup_ident.insert(param_name, expression_token); - let param_type_decl = variable_ident_decl_pairs.next().unwrap(); - let ty = self.parse_type_decl(param_type_decl, &mut module.types)?; - fun.parameter_types.push(ty); - } - if let Some(function_type_decl) = function_header_pairs.next() { - let ty = self.parse_type_decl(function_type_decl, &mut module.types)?; - fun.return_type = Some(ty); - } - - let function_body = function_decl_pairs.next().unwrap(); - assert_eq!(function_body.as_rule(), Rule::body_stmt); - for statement in function_body.into_inner() { - assert_eq!(statement.as_rule(), Rule::statement); - let mut statement_pairs = statement.into_inner(); - let first_statement = match statement_pairs.next() { - Some(st) => st, - None => continue, - }; - let context = ExpressionContext { - function: &mut fun, - lookup_ident: &lookup_ident, - types: &mut module.types, - constants: &mut module.constants, - }; - let stmt = match first_statement.as_rule() { - Rule::return_statement => { - let mut return_pairs = first_statement.into_inner(); - let value = match return_pairs.next() { - Some(exp) => Some(self.parse_primary_expression(exp, context)?), - None => None, - }; - crate::Statement::Return { value } + Token::Paren('[') => { + self.scopes.push(Scope::Decoration); + if !lexer.consume_str("[") { + return Err(Error::Other); } - Rule::variable_statement => { - let mut variable_pairs = first_statement.into_inner(); - let variable_decl = variable_pairs.next().unwrap(); - match variable_decl.as_rule() { - Rule::variable_decl => { - let (name, class, ty) = self.parse_variable_decl(variable_decl, context.types)?; - if let Some(class) = class { - return Err(Error::InvalidVariableClass(class)); + let mut ready = true; + let mut binding = None; + loop { + match lexer.next() { + Token::Paren(']') => { + if !lexer.consume_str("]") { + return Err(Error::Other); } - let value = if let Some(value_pair) = variable_pairs.next() { - let value_token = self.parse_primary_expression(value_pair, context)?; - lookup_ident.insert(name.clone(), value_token); - Some(value_token) - } else { - None + break; + } + Token::Separator(',') if !ready => { + ready = true; + } + Token::Word("location") if ready => { + let location = Self::parse_uint_literal(lexer)?; + binding = Some(crate::Binding::Location(location)); + ready = false; + } + Token::Word("builtin") if ready => { + let builtin = match lexer.next() { + Token::Word(word) => Self::get_built_in(word)?, + other => return Err(Error::Unexpected(other)), }; - crate::Statement::VariableDeclaration { - name, - ty, - value, - } + binding = Some(crate::Binding::BuiltIn(builtin)); + ready = false; } - Rule::variable_ident_decl => { - let (name, ty) = self.parse_variable_ident_decl(variable_decl, context.types)?; - let value_pair = variable_pairs.next().unwrap(); - let value_token = self.parse_primary_expression(value_pair, context)?; - lookup_ident.insert(name.clone(), value_token); - crate::Statement::VariableDeclaration { - name, - ty, - value: Some(value_token), - } - } - _ => panic!("Unexpected variable decl {:?}", variable_decl) + other => return Err(Error::Unexpected(other)), } } - Rule::assignment_statement => { - let mut assignment_pairs = first_statement.into_inner(); - let left_token = lookup_ident.lookup(assignment_pairs.next().unwrap().as_str())?; - let right_pair = assignment_pairs.next().unwrap(); - let right_token = self.parse_primary_expression(right_pair, context)?; - crate::Statement::Store { - pointer: left_token, - value: right_token, - } - } - _ => panic!("Unknown statement {:?}", first_statement), - }; - fun.body.push(stmt); + self.scopes.pop(); + Self::expect(lexer, Token::Word("var"))?; + let (name, class, ty) = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; + module.global_variables.append(crate::GlobalVariable { + name: Some(name.to_owned()), + class: class.unwrap_or(spirv::StorageClass::Private), + binding, + ty, + }); + } + Token::Word("var") => { + let (name, class, ty) = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; + module.global_variables.append(crate::GlobalVariable { + name: Some(name.to_owned()), + class: class.unwrap_or(spirv::StorageClass::Private), + binding: None, + ty, + }); + } + Token::Word("fn") => { + unimplemented!() + } + Token::Word("entry_point") => { + unimplemented!() + } + Token::End => return Ok(false), + token => return Err(Error::Unexpected(token)), } - Ok(module.functions.append(fun)) + Ok(true) } - pub fn parse(&mut self, source: &str) -> Result { - use pest::Parser as _; - let pairs = Tokenizer::parse(Rule::translation_unit, source)?; + pub fn parse<'a>(&mut self, source: &'a str) -> Result> { let mut module = crate::Module::generate_empty(); - for global_decl_maybe in pairs { - match global_decl_maybe.as_rule() { - Rule::global_decl => { - let global_decl = global_decl_maybe.into_inner().next().unwrap(); - match global_decl.as_rule() { - Rule::import_decl => { - let mut import_decl = global_decl.into_inner(); - let path = import_decl.next().unwrap().as_str(); - log::warn!("Ignoring import {:?}", path); - } - Rule::global_variable_decl => { - let mut global_decl_pairs = global_decl.into_inner(); - let binding = Self::parse_decoration_list(global_decl_pairs.next().unwrap())?; - let var_decl = global_decl_pairs.next().unwrap(); - let (name, class, ty) = self.parse_variable_decl(var_decl, &mut module.types)?; - module.global_variables.append(crate::GlobalVariable { - name: Some(name), - class: class.unwrap_or(spirv::StorageClass::Private), - binding, - ty, - }); - } - Rule::global_constant_decl => { - let mut global_constant_pairs = global_decl.into_inner(); - let variable_ident_decl = global_constant_pairs.next().unwrap(); - let (name, _ty) = self.parse_variable_ident_decl(variable_ident_decl, &mut module.types)?; - let const_expr_decl = global_constant_pairs.next().unwrap(); - let inner = Self::parse_const_expression(const_expr_decl, &mut module.constants)?; - module.constants.append(crate::Constant { - name: Some(name), - specialization: None, - inner, - }); - } - Rule::type_alias => { - let mut type_alias_pairs = global_decl.into_inner(); - let name = type_alias_pairs.next().unwrap().as_str().to_owned(); - let something_decl = type_alias_pairs.next().unwrap(); - match something_decl.as_rule() { - Rule::type_decl => { - let token = self.parse_type_decl(something_decl, &mut module.types)?; - self.lookup_type.insert(name, token); - } - Rule::struct_decl => { - let mut struct_decl_pairs = something_decl.into_inner(); - let mut body = struct_decl_pairs.next().unwrap(); - while body.as_rule() == Rule::struct_decoration_decl { - body = struct_decl_pairs.next().unwrap(); //skip - } - let inner = self.parse_struct_decl(body, &mut module.types)?; - module.types.append(crate::Type { - name: Some(name), - inner, - }); - } - other => panic!("Unexpected type alias rule {:?}", other), - }; - } - Rule::function_decl => { - self.parse_function_decl(global_decl, &mut module)?; - } - Rule::entry_point_decl => { - let mut ep_decl_pairs = global_decl.into_inner(); - let pipeline_stage_pair = ep_decl_pairs.next().unwrap(); - assert_eq!(pipeline_stage_pair.as_rule(), Rule::pipeline_stage); - let mut fun_name_pair = ep_decl_pairs.next().unwrap(); - let name = fun_name_pair.as_str().to_owned(); - if fun_name_pair.as_rule() == Rule::string_literal { - fun_name_pair = ep_decl_pairs.next().unwrap(); - } - let fun_ident = fun_name_pair.as_str(); - let function = module.functions - .iter() - .find(|(_, fun)| fun.name.as_ref().map(|s| s.as_str()) == Some(fun_ident)) - .map(|(token, _)| token) - .ok_or(Error::UnknownFunction(fun_ident.to_owned()))?; - module.entry_points.push(crate::EntryPoint { - exec_model: match pipeline_stage_pair.as_str() { - "vertex" => spirv::ExecutionModel::Vertex, - "fragment" => spirv::ExecutionModel::Fragment, - "compute" => spirv::ExecutionModel::GLCompute, - other => panic!("Unknown execution model {:?}", other), - }, - name, - inputs: Vec::new(), //TODO - outputs: Vec::new(), //TODO - function, - }); - } - unknown => panic!("Unexpected global decl: {:?}", unknown), + let mut lexer = Lexer::new(source); + loop { + match self.parse_global_decl(&mut lexer, &mut module) { + Err(error) => { + let pos = source.rfind(lexer.input).unwrap(); + let (mut rows, mut cols) = (0, 0); + for line in source[..pos].lines() { + rows += 1; + cols = line.len(); } + return Err(ParseError { + error, + scopes: std::mem::replace(&mut self.scopes, Vec::new()), + pos: (rows, cols), + }); + } + Ok(true) => {} + Ok(false) => { + assert_eq!(self.scopes, Vec::new()); + return Ok(module); } - Rule::EOI => break, - unknown => panic!("Unexpected: {:?}", unknown), } } - Ok(module) } } -pub fn parse_str(source: &str) -> Result { +pub fn parse_str(source: &str) -> Result { Parser::new().parse(source) } diff --git a/src/lib.rs b/src/lib.rs index 6279d2c27..cea653722 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,3 @@ -#[macro_use] -extern crate pest_derive; -extern crate spirv_headers as spirv; - pub mod back; pub mod front; mod storage; From 93d60ce8bf1939b9a33df53e77a221e4ee4592c5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 10 Mar 2020 22:08:25 -0400 Subject: [PATCH 0043/2212] [wgsl] hand-written function parsing --- src/front/wgsl.rs | 597 ++++++++++++++++++++++++++++++++++++---------- src/lib.rs | 2 +- 2 files changed, 472 insertions(+), 127 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 47baea070..1788b504a 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -20,14 +20,19 @@ impl<'a> Lexer<'a> { pub enum Token<'a> { Separator(char), Paren(char), + DoubleParen(char), Number(&'a str), + String(&'a str), Word(&'a str), Operation { op: char, boolean: bool }, + Arrow, + Unknown(char), + UnterminatedString, End, } impl<'a> Lexer<'a> { - fn consume_str(&mut self, what: &str) -> bool { + fn _consume_str(&mut self, what: &str) -> bool { if self.input.starts_with(what) { self.input = &self.input[what.len() ..]; true @@ -48,6 +53,7 @@ impl<'a> Lexer<'a> { self.input = self.input.trim_start(); } + #[must_use] fn next(&mut self) -> Token<'a> { self.skip_whitespace(); let mut chars = self.input.chars(); @@ -55,15 +61,24 @@ impl<'a> Lexer<'a> { Some(c) => c, None => return Token::End, }; - match cur { + let token = match cur { ':' | ';' | ',' | '.' => { self.input = chars.as_str(); Token::Separator(cur) } - '(' | ')' | '[' | ']' | '<' | '>' => { + '(' | ')' | '<' | '>' | '{' | '}' => { self.input = chars.as_str(); Token::Paren(cur) } + '[' | ']' => { + self.input = chars.as_str(); + if chars.next() == Some(cur) { + self.input = chars.as_str(); + Token::DoubleParen(cur) + } else { + Token::Paren(cur) + } + } '0' ..= '9' => { let number = self.consume_any(|c| (c>='0' && c<='9' || c=='.')); Token::Number(number) @@ -72,9 +87,39 @@ impl<'a> Lexer<'a> { let word = self.consume_any(|c| c.is_alphanumeric() || c=='_'); Token::Word(word) } - '=' | '+'| '-' | '*' | '/' | '&' | '|' | '^' => { + '"' => { + let base = chars.as_str(); + let len = match chars.position(|c| c == '"') { + Some(pos) => pos, + None => return Token::UnterminatedString, + }; + self.input = chars.as_str(); + Token::String(&base[..len]) + } + '-' => { + self.input = chars.as_str(); + if chars.next() == Some('>') { + self.input = chars.as_str(); + Token::Arrow + } else { + Token::Operation { op: cur, boolean: false } + } + } + '+' | '*' | '/' | '^' => { + self.input = chars.as_str(); + Token::Operation { op: cur, boolean: false } + } + '!' => { + if chars.next() == Some('=') { + self.input = chars.as_str(); + Token::Operation { op: cur, boolean: true } + } else { + Token::Unknown(cur) + } + } + '=' | '&' | '|' => { let next = chars.next(); - let boolean = (cur == '=' || cur == '&' || cur == '|') && next == Some(cur); + let boolean = next == Some(cur); self.input = &self.input[if boolean { 2 } else { 1 } ..]; Token::Operation { op: cur, boolean } } @@ -84,11 +129,17 @@ impl<'a> Lexer<'a> { self.input = chars.as_str(); self.next() } - None => return Token::End, + None => Token::End, } } - _ => unimplemented!(), - } + _ => Token::Unknown(cur), + }; + token + } + + #[must_use] + fn peek(&self) -> Token<'a> { + self.clone().next() } } @@ -98,7 +149,11 @@ pub enum Scope { ImportDecl, VariableDecl, TypeDecl, + FunctionDecl, + Statement, ConstantExpr, + PrimaryExpr, + GeneralExpr, } #[derive(Debug)] @@ -108,9 +163,63 @@ pub enum Error<'a> { BadFloat(&'a str, std::num::ParseFloatError), UnknownStorageClass(&'a str), UnknownBuiltin(&'a str), + UnknownPipelineStage(&'a str), + UnknownIdent(&'a str), + UnknownFunction(&'a str), Other, } +trait StringValueLookup<'a> { + type Value; + fn lookup(&self, key: &'a str) -> Result>; +} +impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Id> { + type Value = Id; + fn lookup(&self, key: &'a str) -> Result> { + self.get(key) + .cloned() + .ok_or(Error::UnknownIdent(key)) + } +} + +struct ExpressionContext<'input,'temp, 'out> { + function: &'out mut crate::Function, + lookup_ident: &'temp FastHashMap<&'input str, Id>, + types: &'out mut Storage, + constants: &'out mut Storage, +} + +impl<'a> ExpressionContext<'a, '_, '_> { + fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { + ExpressionContext { + function: self.function, + lookup_ident: self.lookup_ident, + types: self.types, + constants: self.constants, + } + } + + fn parse_binary_op( + &mut self, + lexer: &mut Lexer<'a>, + middle: Token<'a>, + op: crate::BinaryOperator, + mut parser: impl FnMut(&mut Lexer<'a>, ExpressionContext<'a, '_, '_>) -> Result, Error<'a>>, + ) -> Result, Error<'a>> { + let mut left = parser(lexer, self.reborrow())?; + while lexer.peek() == middle { + let _ = lexer.next(); + let expression = crate::Expression::Binary { + op, + left, + right: parser(lexer, self.reborrow())?, + }; + left = self.function.expressions.append(expression); + } + Ok(left) + } +} + #[derive(Debug)] pub struct ParseError<'a> { pub error: Error<'a>, @@ -143,7 +252,7 @@ impl Parser { } } - fn parse_ident<'a>(&mut self, lexer: &mut Lexer<'a>) -> Result<&'a str, Error<'a>> { + fn parse_ident<'a>(lexer: &mut Lexer<'a>) -> Result<&'a str, Error<'a>> { match lexer.next() { Token::Word(word) => Ok(word), other => Err(Error::Unexpected(other)), @@ -199,6 +308,29 @@ impl Parser { } } + fn get_execution_model<'a>(word: &'a str) -> Result> { + match word { + "vertex" => Ok(spirv::ExecutionModel::Vertex), + "fragment" => Ok(spirv::ExecutionModel::Fragment), + "compute" => Ok(spirv::ExecutionModel::GLCompute), + _ => Err(Error::UnknownPipelineStage(word)), + } + } + + fn get_constant_inner<'a>(word: &'a str) -> Result> { + if word.contains('.') { + word + .parse() + .map(crate::ConstantInner::Float) + .map_err(|err| Error::BadFloat(word, err)) + } else { + word + .parse() + .map(crate::ConstantInner::Sint) + .map_err(|err| Error::BadInteger(word, err)) + } + } + fn parse_const_expression<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -206,37 +338,26 @@ impl Parser { const_store: &mut Storage, ) -> Result> { self.scopes.push(Scope::ConstantExpr); - let backup = lexer.clone(); - let inner = match lexer.next() { - Token::Word("true") => crate::ConstantInner::Bool(true), - Token::Word("false") => crate::ConstantInner::Bool(false), + let inner = match lexer.peek() { + Token::Word("true") => { + let _ = lexer.next(); + crate::ConstantInner::Bool(true) + } + Token::Word("false") => { + let _ = lexer.next(); + crate::ConstantInner::Bool(false) + } Token::Number(word) => { - if word.contains('.') { - let value = word - .parse() - .map_err(|err| Error::BadFloat(word, err))?; - crate::ConstantInner::Float(value) - } else { - let value = word - .parse() - .map_err(|err| Error::BadInteger(word, err))?; - crate::ConstantInner::Sint(value) - } + let _ = lexer.next(); + Self::get_constant_inner(word)? } _ => { - *lexer = backup; let _ty = self.parse_type_decl(lexer, type_store); Self::expect(lexer, Token::Paren('('))?; - loop { - let backup = lexer.clone(); - match lexer.next() { - Token::Paren(')') => break, - _ => { - *lexer = backup; - let _ = self.parse_const_expression(lexer, type_store, const_store)?; - } - } + while lexer.peek() != Token::Paren(')') { + let _ = self.parse_const_expression(lexer, type_store, const_store)?; } + let _ = lexer.next(); unimplemented!() } }; @@ -244,15 +365,134 @@ impl Parser { Ok(inner) } + fn parse_primary_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + self.scopes.push(Scope::PrimaryExpr); + let backup = lexer.clone(); + let expression = match lexer.next() { + Token::Paren('(') => { + let expr = self.parse_general_expression(lexer, ctx)?; + Self::expect(lexer, Token::Paren(')'))?; + self.scopes.pop(); + return Ok(expr); + } + Token::Word("true") => { + let id = ctx.constants.append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Bool(true), + }); + crate::Expression::Constant(id) + } + Token::Word("false") => { + let id = ctx.constants.append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Bool(false), + }); + crate::Expression::Constant(id) + } + Token::Number(word) => { + let id = ctx.constants.append(crate::Constant { + name: None, + specialization: None, + inner: Self::get_constant_inner(word)?, + }); + crate::Expression::Constant(id) + } + Token::Word(word) => { + if let Some(id) = ctx.lookup_ident.get(word) { + self.scopes.pop(); + return Ok(*id); + } + *lexer = backup; + let ty = self.parse_type_decl(lexer, ctx.types)?; + Self::expect(lexer, Token::Paren('('))?; + let mut components = Vec::new(); + while lexer.peek() != Token::Paren(')') { + if !components.is_empty() { + Self::expect(lexer, Token::Separator(','))?; + } + let sub_expr = self.parse_general_expression(lexer, ctx.reborrow())?; + components.push(sub_expr); + } + let _ = lexer.next(); + crate::Expression::Compose { ty, components } + } + other => return Err(Error::Unexpected(other)), + }; + self.scopes.pop(); + Ok(ctx.function.expressions.append(expression)) + } + + fn parse_relational_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + context.parse_binary_op( + lexer, + Token::Operation { op: '+', boolean: false }, + crate::BinaryOperator::Add, + |lexer, mut context| context.parse_binary_op( + lexer, + Token::Operation { op: '*', boolean: false }, + crate::BinaryOperator::Multiply, + |lexer, context| self.parse_primary_expression(lexer, context), + ), + ) + } + + fn parse_general_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + self.scopes.push(Scope::GeneralExpr); + let id = context.parse_binary_op( + lexer, + Token::Operation { op: '|', boolean: true }, + crate::BinaryOperator::LogicalOr, + |lexer, mut context| context.parse_binary_op( + lexer, + Token::Operation { op: '&', boolean: true }, + crate::BinaryOperator::LogicalAnd, + |lexer, mut context| context.parse_binary_op( + lexer, + Token::Operation { op: '|', boolean: false }, + crate::BinaryOperator::InclusiveOr, + |lexer, mut context| context.parse_binary_op( + lexer, + Token::Operation { op: '^', boolean: false }, + crate::BinaryOperator::ExclusiveOr, + |lexer, mut context| context.parse_binary_op( + lexer, + Token::Operation { op: '&', boolean: false }, + crate::BinaryOperator::And, + |lexer, mut context| context.parse_binary_op( + lexer, + Token::Operation { op: '=', boolean: true }, + crate::BinaryOperator::Equals, + |lexer, context| self.parse_relational_expression(lexer, context), + ), + ), + ), + ), + ), + )?; + self.scopes.pop(); + Ok(id) + } + fn parse_variable_ident_decl<'a>( &mut self, lexer: &mut Lexer<'a>, type_store: &mut Storage, ) -> Result<(&'a str, Id), Error<'a>> { - let name = match lexer.next() { - Token::Word(word) => word, - other => return Err(Error::Unexpected(other)), - }; + let name = Self::parse_ident(lexer)?; Self::expect(lexer, Token::Separator(':'))?; let ty = self.parse_type_decl(lexer, type_store)?; Ok((name, ty)) @@ -266,30 +506,21 @@ impl Parser { ) -> Result<(&'a str, Option, Id), Error<'a>> { self.scopes.push(Scope::VariableDecl); let mut class = None; - let mut token = lexer.next(); - if let Token::Paren('<') = token { - class = Some(match lexer.next() { - Token::Word(word) => Self::get_storage_class(word)?, - other => return Err(Error::Unexpected(other)), - }); + if let Token::Paren('<') = lexer.peek() { + let _ = lexer.next(); + let class_str = Self::parse_ident(lexer)?; + class = Some(Self::get_storage_class(class_str)?); Self::expect(lexer, Token::Paren('>'))?; - token = lexer.next(); } - let name = match token { - Token::Word(word) => word, - other => return Err(Error::Unexpected(other)), - }; + let name = Self::parse_ident(lexer)?; Self::expect(lexer, Token::Separator(':'))?; let ty = self.parse_type_decl(lexer, type_store)?; - match lexer.next() { - Token::Separator(';') => {} - Token::Operation{ op: '=', boolean: false } => { - let _inner = self.parse_const_expression(lexer, type_store, const_store)?; - //TODO - Self::expect(lexer, Token::Separator(';'))?; - } - other => return Err(Error::Unexpected(other)), + if let Token::Operation{ op: '=', boolean: false } = lexer.peek() { + let _ = lexer.next(); + let _inner = self.parse_const_expression(lexer, type_store, const_store)?; + //TODO } + Self::expect(lexer, Token::Separator(';'))?; self.scopes.pop(); Ok((name, class, ty)) } @@ -302,19 +533,12 @@ impl Parser { let mut members = Vec::new(); Self::expect(lexer, Token::Paren('{'))?; loop { - let mut token = lexer.next(); - if let Token::Paren('[') = token { + if let Token::DoubleParen('[') = lexer.peek() { self.scopes.push(Scope::Decoration); - if !lexer.consume_str("[") { - return Err(Error::Other); - } let mut ready = true; loop { match lexer.next() { - Token::Paren(']') => { - if !lexer.consume_str("]") { - return Err(Error::Other); - } + Token::DoubleParen(']') => { break; } Token::Separator(',') if !ready => { @@ -327,10 +551,9 @@ impl Parser { other => return Err(Error::Unexpected(other)), } } - token = lexer.next(); self.scopes.pop(); } - let name = match token { + let name = match lexer.next() { Token::Word(word) => word, Token::Paren('}') => return Ok(members), other => return Err(Error::Unexpected(other)), @@ -424,10 +647,7 @@ impl Parser { } Token::Word("ptr") => { Self::expect(lexer, Token::Paren('<'))?; - let class = match lexer.next() { - Token::Word(word) => Self::get_storage_class(word)?, - other => return Err(Error::Unexpected(other)), - }; + let class = Self::get_storage_class(Self::parse_ident(lexer)?)?; Self::expect(lexer, Token::Separator(','))?; let base = self.parse_type_decl(lexer, type_store)?; Self::expect(lexer, Token::Paren('>'))?; @@ -467,11 +687,149 @@ impl Parser { })) } + fn parse_function_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + module: &mut crate::Module, + lookup_global_expression: &FastHashMap<&'a str, crate::Expression>, + ) -> Result, Error<'a>> { + self.scopes.push(Scope::FunctionDecl); + // read function name + let mut lookup_ident = FastHashMap::default(); + let fun_name = Self::parse_ident(lexer)?; + let mut fun = crate::Function { + name: Some(fun_name.to_owned()), + control: spirv::FunctionControl::empty(), + parameter_types: Vec::new(), + return_type: None, + expressions: Storage::new(), + body: Vec::new(), + }; + // populare initial expressions + for (&name, expression) in lookup_global_expression.iter() { + let expr_id = fun.expressions.append(expression.clone()); + lookup_ident.insert(name, expr_id); + } + // read parameter list + Self::expect(lexer, Token::Paren('('))?; + while lexer.peek() != Token::Paren(')') { + if !fun.parameter_types.is_empty() { + Self::expect(lexer, Token::Separator(','))?; + } + let (param_name, param_type) = self.parse_variable_ident_decl(lexer, &mut module.types)?; + let param_id = fun.parameter_types.len() as u32; + let expression_token = fun.expressions.append(crate::Expression::FunctionParameter(param_id)); + lookup_ident.insert(param_name, expression_token); + fun.parameter_types.push(param_type); + } + let _ = lexer.next(); + // read return type + Self::expect(lexer, Token::Arrow)?; + if let Token::Word("void") = lexer.peek() { + let _ = lexer.next(); + } else { + fun.return_type = Some(self.parse_type_decl(lexer, &mut module.types)?); + }; + // read body + Self::expect(lexer, Token::Paren('{'))?; + loop { + let context = ExpressionContext { + function: &mut fun, + lookup_ident: &lookup_ident, + types: &mut module.types, + constants: &mut module.constants, + }; + match lexer.next() { + Token::Separator(';') => {}, + Token::Paren('}') => break, + Token::Word(word) => { + self.scopes.push(Scope::Statement); + let statement = match word { + "var" => { + let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; + let value = if let Token::Operation { op: '=', boolean: false } = lexer.peek() { + let _ = lexer.next(); + Some(self.parse_general_expression(lexer, context)?) + } else { + None + }; + Self::expect(lexer, Token::Separator(';'))?; + crate::Statement::VariableDeclaration { + name: name.to_owned(), + ty, + value, + } + } + "return" => { + let value = if context.function.return_type.is_some() { + Some(self.parse_general_expression(lexer, context)?) + } else { + None + }; + Self::expect(lexer, Token::Separator(';'))?; + crate::Statement::Return { + value + } + } + ident => { + // assignment + let left = lookup_ident.lookup(ident)?; + Self::expect(lexer, Token::Operation { op: '=', boolean: false })?; + let value = self.parse_general_expression(lexer, context)?; + Self::expect(lexer, Token::Separator(';'))?; + crate::Statement::Store { + pointer: left, + value, + } + } + }; + self.scopes.pop(); + fun.body.push(statement); + } + other => return Err(Error::Unexpected(other)), + } + }; + // done + self.scopes.pop(); + Ok(module.functions.append(fun)) + } + fn parse_global_decl<'a>( &mut self, lexer: &mut Lexer<'a>, module: &mut crate::Module, + lookup_global_expression: &mut FastHashMap<&'a str, crate::Expression>, ) -> Result> { + // read decorations + let mut binding = None; + if let Token::DoubleParen('[') = lexer.peek() { + self.scopes.push(Scope::Decoration); + let _ = lexer.next(); + let mut ready = true; + loop { + match lexer.next() { + Token::DoubleParen(']') => { + break; + } + Token::Separator(',') if !ready => { + ready = true; + } + Token::Word("location") if ready => { + let location = Self::parse_uint_literal(lexer)?; + binding = Some(crate::Binding::Location(location)); + ready = false; + } + Token::Word("builtin") if ready => { + let builtin = Self::get_built_in(Self::parse_ident(lexer)?)?; + binding = Some(crate::Binding::BuiltIn(builtin)); + ready = false; + } + other => return Err(Error::Unexpected(other)), + } + } + self.scopes.pop(); + } + // read items match lexer.next() { Token::Separator(';') => {}, Token::Word("import") => { @@ -483,7 +841,7 @@ impl Parser { self.scopes.pop(); } Token::Word("type") => { - let name = self.parse_ident(lexer)?; + let name = Self::parse_ident(lexer)?; Self::expect(lexer, Token::Operation { op: '=', boolean: false })?; let ty = self.parse_type_decl(lexer, &mut module.types)?; self.lookup_type.insert(name.to_owned(), ty); @@ -493,85 +851,72 @@ impl Parser { let (name, _ty) = self.parse_variable_ident_decl(lexer, &mut module.types)?; Self::expect(lexer, Token::Operation { op: '=', boolean: false })?; let inner = self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; - module.constants.append(crate::Constant { + Self::expect(lexer, Token::Separator(';'))?; + let const_id = module.constants.append(crate::Constant { name: Some(name.to_owned()), specialization: None, inner, }); - Self::expect(lexer, Token::Separator(';'))?; - } - Token::Paren('[') => { - self.scopes.push(Scope::Decoration); - if !lexer.consume_str("[") { - return Err(Error::Other); - } - let mut ready = true; - let mut binding = None; - loop { - match lexer.next() { - Token::Paren(']') => { - if !lexer.consume_str("]") { - return Err(Error::Other); - } - break; - } - Token::Separator(',') if !ready => { - ready = true; - } - Token::Word("location") if ready => { - let location = Self::parse_uint_literal(lexer)?; - binding = Some(crate::Binding::Location(location)); - ready = false; - } - Token::Word("builtin") if ready => { - let builtin = match lexer.next() { - Token::Word(word) => Self::get_built_in(word)?, - other => return Err(Error::Unexpected(other)), - }; - binding = Some(crate::Binding::BuiltIn(builtin)); - ready = false; - } - other => return Err(Error::Unexpected(other)), - } - } - self.scopes.pop(); - Self::expect(lexer, Token::Word("var"))?; - let (name, class, ty) = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; - module.global_variables.append(crate::GlobalVariable { - name: Some(name.to_owned()), - class: class.unwrap_or(spirv::StorageClass::Private), - binding, - ty, - }); + lookup_global_expression.insert(name, crate::Expression::Constant(const_id)); } Token::Word("var") => { let (name, class, ty) = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; - module.global_variables.append(crate::GlobalVariable { + let var_id = module.global_variables.append(crate::GlobalVariable { name: Some(name.to_owned()), class: class.unwrap_or(spirv::StorageClass::Private), - binding: None, + binding: binding.take(), ty, }); + lookup_global_expression.insert(name, crate::Expression::GlobalVariable(var_id)); } Token::Word("fn") => { - unimplemented!() + self.parse_function_decl(lexer, module, &lookup_global_expression)?; } Token::Word("entry_point") => { - unimplemented!() + let exec_model = Self::get_execution_model(Self::parse_ident(lexer)?)?; + let export_name = if let Token::Word("as") = lexer.peek() { + let _ = lexer.next(); + match lexer.next() { + Token::String(name) => Some(name), + other => return Err(Error::Unexpected(other)) + } + } else { + None + }; + Self::expect(lexer, Token::Operation{ op: '=', boolean: false })?; + let fun_ident = Self::parse_ident(lexer)?; + Self::expect(lexer, Token::Separator(';'))?; + let function = module.functions + .iter() + .find(|(_, fun)| fun.name.as_ref().map(|s| s.as_str()) == Some(fun_ident)) + .map(|(id, _)| id) + .ok_or(Error::UnknownFunction(fun_ident))?; + module.entry_points.push(crate::EntryPoint { + exec_model, + name: export_name.unwrap_or(fun_ident).to_owned(), + inputs: Vec::new(), //TODO + outputs: Vec::new(), //TODO + function, + }); } Token::End => return Ok(false), token => return Err(Error::Unexpected(token)), } - Ok(true) + match binding { + None => Ok(true), + // we had the decoration but no var? + Some(_) => Err(Error::Other), + } } pub fn parse<'a>(&mut self, source: &'a str) -> Result> { let mut module = crate::Module::generate_empty(); let mut lexer = Lexer::new(source); + let mut lookup_global_expression = FastHashMap::default(); loop { - match self.parse_global_decl(&mut lexer, &mut module) { + match self.parse_global_decl(&mut lexer, &mut module, &mut lookup_global_expression) { Err(error) => { - let pos = source.rfind(lexer.input).unwrap(); + let pos = source.len() - lexer.input.len(); let (mut rows, mut cols) = (0, 0); for line in source[..pos].lines() { rows += 1; diff --git a/src/lib.rs b/src/lib.rs index cea653722..71957a1f9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -122,7 +122,7 @@ pub enum BinaryOperator { LogicalOr, } -#[derive(Debug)] +#[derive(Clone, Debug)] pub enum Expression { Access { base: Token, From ee8e0699be17918ffc66abb04440df4de68f5c49 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 10 Mar 2020 22:08:56 -0400 Subject: [PATCH 0044/2212] [wgsl] remove Pest grammar --- grammars/wgsl.pest | 189 --------------------------------------------- 1 file changed, 189 deletions(-) delete mode 100644 grammars/wgsl.pest diff --git a/grammars/wgsl.pest b/grammars/wgsl.pest deleted file mode 100644 index 62fe8daae..000000000 --- a/grammars/wgsl.pest +++ /dev/null @@ -1,189 +0,0 @@ -translation_unit = _{ SOI ~ global_decl* ~ EOI } - -global_decl = { - ";" - | import_decl ~ ";" - | global_variable_decl ~ ";" - | global_constant_decl ~ ";" - | entry_point_decl ~ ";" - | type_alias ~ ";" - | function_decl -} - -import_decl = { "import" ~ string_literal ~ "as" ~ (ident ~ "::")* ~ ident} - -global_variable_decl = { - variable_decoration_list ~ variable_decl - | variable_decoration_list ~ variable_decl ~ "=" ~ const_expr -} - -global_constant_decl = { "const" ~ variable_ident_decl ~ "=" ~ const_expr } - -variable_decoration_list = { "[[" ~ (variable_decoration ~ ",")* ~ variable_decoration ~ "]]" } - -variable_decoration = _{ - "location" ~ location_decoration - | "builtin" ~ builtin_decoration -// | BUILTIN builtin_decoration -// | BINDING INT_LITERAL -// | SET INT_LITERAL -} - -location_decoration = { int_literal } -builtin_decoration = { - "position" - | "vertex_idx" -} - -variable_decl = { "var" ~ variable_storage_decoration? ~ variable_ident_decl } -variable_storage_decoration = _{ "<" ~ storage_class ~ ">" } -variable_ident_decl = { ident ~ ":" ~ type_decl } - -type_alias = { - "type" ~ ident ~ "=" ~ type_decl - | "type" ~ ident ~ "=" ~ struct_decl -} - -struct_decl = { struct_decoration_decl? ~ "struct" ~ struct_body_decl } - -struct_decoration_decl = { "[[" ~ struct_decoration ~ "]]" } - -struct_decoration = { - "block" -} - -struct_body_decl = { "{" ~ struct_member* ~ "}" } -struct_member = { struct_member_decoration_decl? ~ variable_ident_decl ~ ";" } -struct_member_decoration_decl = { "[[" ~ (struct_member_decoration ~ ",")* ~ struct_member_decoration ~ "]]" } -struct_member_decoration = { - "offset" ~ uint_literal -} - -function_decl = { function_header ~ body_stmt } -function_header = { "fn" ~ ident ~ "(" ~ param_list ~ ")" ~ "->" ~ function_type_decl } -function_type_decl = _{ "void" | type_decl } -param_list = { (variable_ident_decl ~ ",")* ~ variable_ident_decl | "" } -body_stmt = { "{" ~ statement* ~ "}" } - -entry_point_decl = { - "entry_point" ~ pipeline_stage ~ ("as" ~ string_literal)? ~ "=" ~ ident -} - -pipeline_stage = { - "vertex" - | "fragment" - | "compute" -} - -storage_class = { - "in" - | "out" - | "uniform" -// | WORKGROUP -// | UNIFORM_CONSTANT - | "storage_buffer" -// | IMAGE - | "private" - | "function" -} - -const_literal = { - bool_literal - | float_literal - | int_literal - | uint_literal -} - -const_expr = { - const_literal - | type_decl ~ "(" ~ (const_expr ~ ",")? ~ const_expr ~ ")" -} - -type_pointer_kind = { "ptr" } -type_array_kind = { "array" } -type_vec_kind = { "vec2" | "vec3" | "vec4" } -type_mat_kind = { "mat2x2" | "mat3x3" | "mat4x4" } - -type_decl = { - scalar_type - | type_vec_kind ~ "<" ~ type_decl ~ ">" - | type_pointer_kind ~ "<" ~ storage_class ~ "," ~ type_decl ~ ">" - | type_array_kind ~ "<" ~ type_decl ~ "," ~ uint_literal ~ ">" - | type_array_kind ~ "<" ~ type_decl ~ ">" - | type_mat_kind ~ "<" ~ type_decl ~ ">" - | ident -} - -scalar_type = { - "bool" - | "f32" - | "i32" - | "u32" -} - -return_statement = { "return" ~ logical_or_expression? } -assignment_statement = { ident ~ "=" ~ logical_or_expression } - -statement = { - ";" - | return_statement ~ ";" -// | if_stmt -// | unless_stmt -// | regardless_stmt -// | switch_stmt -// | loop_stmt - | variable_statement ~ ";" -// | break_stmt ~ ";" -// | continue_stmt ~ ";" -// | KILL ~ ";" -// | NOP ~ ";" - | assignment_statement ~ ";" -} - -variable_statement = _{ - variable_decl ~ "=" ~ logical_or_expression - | "const" ~ variable_ident_decl ~ "=" ~ logical_or_expression - | variable_decl -} - -primary_expression = _{ - typed_expression - | const_expr - | paren_rhs_stmt - | ident -} - -unary_expression = _{ - primary_expression -} - -multiplicative_expression = { unary_expression ~ ("*" ~ unary_expression)* } -additive_expression = { multiplicative_expression ~ ("+" ~ multiplicative_expression)* } -shift_expression = _{ - additive_expression -} -relational_expression = _{ - shift_expression -} - -equality_expression = { relational_expression ~ ("==" ~ relational_expression)* } -and_expression = { equality_expression ~ ("&" ~ equality_expression)* } -exclusive_or_expression = { and_expression ~ ("^" ~ and_expression)* } -inclusive_or_expression = { exclusive_or_expression ~ ("|" ~ exclusive_or_expression)* } -logical_and_expression = { inclusive_or_expression ~ ("&&" ~ inclusive_or_expression)* } -logical_or_expression = { logical_and_expression ~ ("||" ~ logical_and_expression)* } - -paren_rhs_stmt = _{ "(" ~ logical_or_expression ~ ")" } - -typed_expression = { type_decl ~ "(" ~ argument_expression_list ~ ")" } -argument_expression_list = _{ (logical_or_expression ~ ",")* ~ logical_or_expression } - -ident = @{ ASCII_ALPHA ~ (ASCII_ALPHANUMERIC | "_")* } -int_literal = @{ ("-"? ~ "0x" ~ ASCII_HEX_DIGIT+) | "0" | ("-"? ~ ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } -uint_literal = @{ ("0x" ~ ASCII_HEX_DIGIT+) | "0" | (ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } -float_literal = @{ "-"? ~ ASCII_DIGIT+ ~ ("." ~ ASCII_DIGIT*)? } -bool_literal = @{ "true" | "false" } -string_literal = @{ "\"" ~ ( "\"\"" | (!"\"" ~ ANY) )* ~ "\"" } - -WHITESPACE = _{ " " | "\t" | NEWLINE } -COMMENT = _{ "#" ~ (!NEWLINE ~ ANY)* } From 7e0b004c16202cf81bd14d13f31cdd56fd5a40f7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 10 Mar 2020 22:38:10 -0400 Subject: [PATCH 0045/2212] [wgsl] refactor Token --- src/front/wgsl.rs | 48 +++++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 1788b504a..1ed8d18aa 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -24,7 +24,8 @@ pub enum Token<'a> { Number(&'a str), String(&'a str), Word(&'a str), - Operation { op: char, boolean: bool }, + Operation(char), + LogicalOperation(char), Arrow, Unknown(char), UnterminatedString, @@ -102,26 +103,29 @@ impl<'a> Lexer<'a> { self.input = chars.as_str(); Token::Arrow } else { - Token::Operation { op: cur, boolean: false } + Token::Operation(cur) } } '+' | '*' | '/' | '^' => { self.input = chars.as_str(); - Token::Operation { op: cur, boolean: false } + Token::Operation(cur) } '!' => { if chars.next() == Some('=') { self.input = chars.as_str(); - Token::Operation { op: cur, boolean: true } + Token::LogicalOperation(cur) } else { Token::Unknown(cur) } } '=' | '&' | '|' => { - let next = chars.next(); - let boolean = next == Some(cur); - self.input = &self.input[if boolean { 2 } else { 1 } ..]; - Token::Operation { op: cur, boolean } + if chars.next() == Some(cur) { + self.input = &self.input[2..]; + Token::LogicalOperation(cur) + } else { + self.input = &self.input[1..]; + Token::Operation(cur) + } } '#' => { match chars.position(|c| c == '\n' || c == '\r') { @@ -435,11 +439,11 @@ impl Parser { ) -> Result, Error<'a>> { context.parse_binary_op( lexer, - Token::Operation { op: '+', boolean: false }, + Token::Operation('+'), crate::BinaryOperator::Add, |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation { op: '*', boolean: false }, + Token::Operation('*'), crate::BinaryOperator::Multiply, |lexer, context| self.parse_primary_expression(lexer, context), ), @@ -454,27 +458,27 @@ impl Parser { self.scopes.push(Scope::GeneralExpr); let id = context.parse_binary_op( lexer, - Token::Operation { op: '|', boolean: true }, + Token::LogicalOperation('|'), crate::BinaryOperator::LogicalOr, |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation { op: '&', boolean: true }, + Token::LogicalOperation('&'), crate::BinaryOperator::LogicalAnd, |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation { op: '|', boolean: false }, + Token::Operation('|'), crate::BinaryOperator::InclusiveOr, |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation { op: '^', boolean: false }, + Token::Operation('^'), crate::BinaryOperator::ExclusiveOr, |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation { op: '&', boolean: false }, + Token::Operation('&'), crate::BinaryOperator::And, |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation { op: '=', boolean: true }, + Token::LogicalOperation('='), crate::BinaryOperator::Equals, |lexer, context| self.parse_relational_expression(lexer, context), ), @@ -515,7 +519,7 @@ impl Parser { let name = Self::parse_ident(lexer)?; Self::expect(lexer, Token::Separator(':'))?; let ty = self.parse_type_decl(lexer, type_store)?; - if let Token::Operation{ op: '=', boolean: false } = lexer.peek() { + if let Token::Operation('=') = lexer.peek() { let _ = lexer.next(); let _inner = self.parse_const_expression(lexer, type_store, const_store)?; //TODO @@ -747,7 +751,7 @@ impl Parser { let statement = match word { "var" => { let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; - let value = if let Token::Operation { op: '=', boolean: false } = lexer.peek() { + let value = if let Token::Operation('=') = lexer.peek() { let _ = lexer.next(); Some(self.parse_general_expression(lexer, context)?) } else { @@ -774,7 +778,7 @@ impl Parser { ident => { // assignment let left = lookup_ident.lookup(ident)?; - Self::expect(lexer, Token::Operation { op: '=', boolean: false })?; + Self::expect(lexer, Token::Operation('='))?; let value = self.parse_general_expression(lexer, context)?; Self::expect(lexer, Token::Separator(';'))?; crate::Statement::Store { @@ -842,14 +846,14 @@ impl Parser { } Token::Word("type") => { let name = Self::parse_ident(lexer)?; - Self::expect(lexer, Token::Operation { op: '=', boolean: false })?; + Self::expect(lexer, Token::Operation('='))?; let ty = self.parse_type_decl(lexer, &mut module.types)?; self.lookup_type.insert(name.to_owned(), ty); Self::expect(lexer, Token::Separator(';'))?; } Token::Word("const") => { let (name, _ty) = self.parse_variable_ident_decl(lexer, &mut module.types)?; - Self::expect(lexer, Token::Operation { op: '=', boolean: false })?; + Self::expect(lexer, Token::Operation('='))?; let inner = self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; Self::expect(lexer, Token::Separator(';'))?; let const_id = module.constants.append(crate::Constant { @@ -883,7 +887,7 @@ impl Parser { } else { None }; - Self::expect(lexer, Token::Operation{ op: '=', boolean: false })?; + Self::expect(lexer, Token::Operation('='))?; let fun_ident = Self::parse_ident(lexer)?; Self::expect(lexer, Token::Separator(';'))?; let function = module.functions From 5e78c71a4443b09e29d2832bdf84d932508db0e7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 11 Mar 2020 13:50:02 -0400 Subject: [PATCH 0046/2212] Rename Token/Id to Handle and Storage to Arena consistently --- src/arena.rs | 155 ++++++++++++++++++++++++++++++++ src/back/msl.rs | 100 ++++++++++----------- src/front/mod.rs | 10 +-- src/front/spirv.rs | 215 ++++++++++++++++++++++----------------------- src/front/wgsl.rs | 108 +++++++++++------------ src/lib.rs | 76 ++++++++-------- src/storage.rs | 155 -------------------------------- 7 files changed, 409 insertions(+), 410 deletions(-) create mode 100644 src/arena.rs delete mode 100644 src/storage.rs diff --git a/src/arena.rs b/src/arena.rs new file mode 100644 index 000000000..0ccf0fae6 --- /dev/null +++ b/src/arena.rs @@ -0,0 +1,155 @@ +use std::{ + fmt, + hash, + marker::PhantomData, +}; + +/// An unique index in the arena array that a handle points to. +/// +/// This type is independent of `spirv::Word`. `spirv::Word` is used in data +/// representation. It holds a SPIR-V and refers to that instruction. In +/// structured representation, we use Handle to refer to an SPIR-V instruction. +/// Index is an implementation detail to Handle. +type Index = u32; + +/// A strongly typed reference to a SPIR-V element. +pub struct Handle { + index: Index, + marker: PhantomData, +} + +impl Clone for Handle { + fn clone(&self) -> Self { + Handle { + index: self.index, + marker: self.marker, + } + } +} +impl Copy for Handle {} +impl PartialEq for Handle { + fn eq(&self, other: &Self) -> bool { + self.index == other.index + } +} +impl Eq for Handle {} +impl fmt::Debug for Handle { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "Handle({})", self.index) + } +} +impl hash::Hash for Handle { + fn hash(&self, hasher: &mut H) { + self.index.hash(hasher) + } +} + +impl Handle { + #[cfg(test)] + pub const DUMMY: Self = Handle { + index: !0, + marker: PhantomData, + }; + + pub(crate) fn new(index: Index) -> Self { + Handle { + index, + marker: PhantomData, + } + } + + pub fn index(&self) -> usize { + self.index as usize + } +} + +/// An arena holding some kind of component (e.g., type, constant, +/// instruction, etc.) that can be referenced. +#[derive(Debug)] +pub struct Arena { + /// Values of this arena. + data: Vec, +} + +impl Arena { + pub fn new() -> Self { + Arena { + data: Vec::new(), + } + } + + pub fn iter<'a>(&'a self) -> impl Iterator, &'a T)> { + self.data + .iter() + .enumerate() + .map(|(i, v)| (Handle::new(i as Index), v)) + } + + /// Adds a new value to the arena, returning a typed handle. + /// + /// The value is not linked to any SPIR-V module. + pub fn append(&mut self, value: T) -> Handle { + let index = self.data.len() as Index; + self.data.push(value); + Handle::new(index) + } + + /// Adds a value with a check for uniqueness: returns a handle pointing to + /// an existing element if its value matches the given one, or adds a new + /// element otherwise. + pub fn fetch_or_append(&mut self, value: T) -> Handle where T: PartialEq { + if let Some(index) = self.data.iter().position(|d| d == &value) { + Handle::new(index as Index) + } else { + self.append(value) + } + } +} + +impl std::ops::Index> for Arena { + type Output = T; + fn index(&self, handle: Handle) -> &T { + &self.data[handle.index as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn append_non_unique() { + let mut arena: Arena = Arena::new(); + let t1 = arena.append(0.0); + let t2 = arena.append(0.0); + assert!(t1 != t2); + assert!(arena[t1] == arena[t2]); + } + + #[test] + fn append_unique() { + let mut arena: Arena = Arena::new(); + let t1 = arena.append(std::f64::NAN); + let t2 = arena.append(std::f64::NAN); + assert!(t1 != t2); + assert!(arena[t1] != arena[t2]); + } + + #[test] + fn fetch_or_append_non_unique() { + let mut arena: Arena = Arena::new(); + let t1 = arena.fetch_or_append(0.0); + let t2 = arena.fetch_or_append(0.0); + assert!(t1 == t2); + assert!(arena[t1] == arena[t2]) + } + + #[test] + fn fetch_or_append_unique() { + let mut arena: Arena = Arena::new(); + let t1 = arena.fetch_or_append(std::f64::NAN); + let t2 = arena.fetch_or_append(std::f64::NAN); + assert!(t1 != t2); + assert!(arena[t1] != arena[t2]); + } +} diff --git a/src/back/msl.rs b/src/back/msl.rs index 10336b782..4152245b6 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -21,7 +21,7 @@ use std::{ }; use crate::{ - storage::Token, + arena::Handle, FastHashMap, FastHashSet }; @@ -53,8 +53,8 @@ pub enum Error { Format(FmtError), UnsupportedExecutionModel(spirv::ExecutionModel), UnexpectedLocation, - MixedExecutionModels(crate::Token), - MissingBinding(crate::Token), + MixedExecutionModels(crate::Handle), + MissingBinding(crate::Handle), MissingBindTarget(BindSource), InvalidImageFlags(crate::ImageFlags), BadName(String), @@ -111,15 +111,15 @@ trait Indexed { fn id(&self) -> usize; } -impl Indexed for crate::Token { +impl Indexed for crate::Handle { const CLASS: &'static str = "Type"; fn id(&self) -> usize { self.index() } } -impl Indexed for crate::Token { +impl Indexed for crate::Handle { const CLASS: &'static str = "global"; fn id(&self) -> usize { self.index() } } -impl Indexed for crate::Token { +impl Indexed for crate::Handle { const CLASS: &'static str = "function"; fn id(&self) -> usize { self.index() } } @@ -134,13 +134,13 @@ impl Indexed for ParameterIndex { const CLASS: &'static str = "param"; fn id(&self) -> usize { self.0 } } -struct InputStructIndex(crate::Token); +struct InputStructIndex(crate::Handle); impl Indexed for InputStructIndex { const CLASS: &'static str = "Input"; const PREFIX: bool = true; fn id(&self) -> usize { self.0.index() } } -struct OutputStructIndex(crate::Token); +struct OutputStructIndex(crate::Handle); impl Indexed for OutputStructIndex { const CLASS: &'static str = "Output"; const PREFIX: bool = true; @@ -208,22 +208,22 @@ impl Display for Starred { struct TypedGlobalVariable<'a> { module: &'a crate::Module, - token: crate::Token, + handle: crate::Handle, } impl Display for TypedGlobalVariable<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - let var = &self.module.global_variables[self.token]; - let name = var.name.or_index(self.token); + let var = &self.module.global_variables[self.handle]; + let name = var.name.or_index(self.handle); let ty = &self.module.types[var.ty]; match ty.inner { crate::TypeInner::Pointer { base, class } => { - let ty_token = match class { + let ty_handle= match class { spirv::StorageClass::Input | spirv::StorageClass::Output | spirv::StorageClass::UniformConstant => base, _ => var.ty }; - let ty_name = self.module.types[ty_token].name.or_index(ty_token); + let ty_name = self.module.types[ty_handle].name.or_index(ty_handle); write!(formatter, "{} {}", ty_name, name) } _ => panic!("Unexpected global type {:?}", var.ty), @@ -308,19 +308,19 @@ impl MaybeOwned<'_, T> { } impl crate::Module { - fn borrow_type(&self, token: Token) -> MaybeOwned { - MaybeOwned::Borrowed(&self.types[token].inner) + fn borrow_type(&self, handle: Handle) -> MaybeOwned { + MaybeOwned::Borrowed(&self.types[handle].inner) } } impl Writer { fn put_expression<'a>( &mut self, - expr_token: crate::Token, - expressions: &crate::Storage, + expr_handle: crate::Handle, + expressions: &crate::Arena, module: &'a crate::Module, ) -> Result, Error> { - let expression = &expressions[expr_token]; + let expression = &expressions[expr_handle]; log::trace!("expression {:?}", expression); match *expression { crate::Expression::AccessIndex { base, index } => { @@ -349,8 +349,8 @@ impl Writer { ref other => panic!("Unexpected indexing of {:?}", other), } } - crate::Expression::Constant(token) => { - let kind = match module.constants[token].inner { + crate::Expression::Constant(handle) => { + let kind = match module.constants[handle].inner { crate::ConstantInner::Sint(value) => { write!(self.out, "{}", value)?; crate::ScalarKind::Sint @@ -376,11 +376,11 @@ impl Writer { match *inner { crate::TypeInner::Vector { size, kind, .. } => { write!(self.out, "{}{}(", scalar_kind_string(kind), vector_size_string(size))?; - for (i, &token) in components.iter().enumerate() { + for (i, &handle) in components.iter().enumerate() { if i != 0 { write!(self.out, ",")?; } - self.put_expression(token, expressions, module)?; + self.put_expression(handle, expressions, module)?; } write!(self.out, ")")?; } @@ -388,8 +388,8 @@ impl Writer { } Ok(MaybeOwned::Borrowed(inner)) } - crate::Expression::GlobalVariable(token) => { - let var = &module.global_variables[token]; + crate::Expression::GlobalVariable(handle) => { + let var = &module.global_variables[handle]; let inner = &module.types[var.ty].inner; match var.class { spirv::StorageClass::Output => { @@ -407,7 +407,7 @@ impl Writer { } _ => () } - let name = var.name.or_index(token); + let name = var.name.or_index(handle); write!(self.out, "{}", name)?; Ok(MaybeOwned::Borrowed(inner)) } @@ -455,8 +455,8 @@ impl Writer { // write down complex types writeln!(self.out, "")?; - for (token, ty) in module.types.iter() { - let name = ty.name.or_index(token); + for (handle, ty) in module.types.iter() { + let name = ty.name.or_index(handle); match ty.inner { crate::TypeInner::Scalar { kind, .. } => { write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?; @@ -537,27 +537,27 @@ impl Writer { // write down functions let mut uniforms_used = FastHashSet::default(); writeln!(self.out, "")?; - for (fun_token, fun) in module.functions.iter() { - let fun_name = fun.name.or_index(fun_token); + for (fun_handle, fun) in module.functions.iter() { + let fun_name = fun.name.or_index(fun_handle); // find the entry point(s) and inputs/outputs let mut exec_model = None; let mut var_inputs = FastHashSet::default(); let mut var_outputs = FastHashSet::default(); for ep in module.entry_points.iter() { - if ep.function == fun_token { + if ep.function == fun_handle{ var_inputs.extend(ep.inputs.iter().cloned()); var_outputs.extend(ep.outputs.iter().cloned()); if exec_model.is_some() { if exec_model != Some(ep.exec_model) { - return Err(Error::MixedExecutionModels(fun_token)); + return Err(Error::MixedExecutionModels(fun_handle)); } } else { exec_model = Some(ep.exec_model); } } } - let input_name = fun.name.or_index(InputStructIndex(fun_token)); - let output_name = fun.name.or_index(OutputStructIndex(fun_token)); + let input_name = fun.name.or_index(InputStructIndex(fun_handle)); + let output_name = fun.name.or_index(OutputStructIndex(fun_handle)); // make dedicated input/output structs if let Some(em) = exec_model { writeln!(self.out, "struct {} {{", input_name)?; @@ -567,9 +567,9 @@ impl Writer { spirv::ExecutionModel::GLCompute => ("compute", LocationMode::Uniform, LocationMode::Uniform), _ => return Err(Error::UnsupportedExecutionModel(em)), }; - for &token in var_inputs.iter() { - let var = &module.global_variables[token]; - let tyvar = TypedGlobalVariable { module, token }; + for &handle in var_inputs.iter() { + let var = &module.global_variables[handle]; + let tyvar = TypedGlobalVariable { module, handle }; write!(self.out, "\t{}", tyvar)?; if let Some(ref binding) = var.binding { let resolved = options.resolve_binding(binding, in_mode)?; @@ -579,8 +579,8 @@ impl Writer { } writeln!(self.out, "}};")?; writeln!(self.out, "struct {} {{", output_name)?; - for &token in var_outputs.iter() { - let var = &module.global_variables[token]; + for &handle in var_outputs.iter() { + let var = &module.global_variables[handle]; // if it's a struct, lift all the built-in contents up to the root if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner { if let crate::TypeInner::Struct { ref members } = module.types[base].inner { @@ -589,14 +589,14 @@ impl Writer { let ty_name = module.types[member.ty].name.or_index(member.ty); let binding = member.binding .as_ref() - .ok_or(Error::MissingBinding(token))?; + .ok_or(Error::MissingBinding(handle))?; let resolved = options.resolve_binding(binding, out_mode)?; writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; } continue } } - let tyvar = TypedGlobalVariable { module, token }; + let tyvar = TypedGlobalVariable { module, handle }; write!(self.out, "\t{}", tyvar)?; if let Some(ref binding) = var.binding { let resolved = options.resolve_binding(binding, out_mode)?; @@ -623,15 +623,15 @@ impl Writer { } } for (_, expr) in fun.expressions.iter() { - if let crate::Expression::GlobalVariable(token) = *expr { - let var = &module.global_variables[token]; - if var.class == spirv::StorageClass::UniformConstant && !uniforms_used.contains(&token) { - uniforms_used.insert(token); + if let crate::Expression::GlobalVariable(handle) = *expr { + let var = &module.global_variables[handle]; + if var.class == spirv::StorageClass::UniformConstant && !uniforms_used.contains(&handle) { + uniforms_used.insert(handle); let binding = var.binding .as_ref() - .ok_or(Error::MissingBinding(token))?; + .ok_or(Error::MissingBinding(handle))?; let resolved = options.resolve_binding(binding, LocationMode::Uniform)?; - let var = TypedGlobalVariable { module, token }; + let var = TypedGlobalVariable { module, handle }; writeln!(self.out, "\t{} [[{}]],", var, resolved)?; } } @@ -672,11 +672,11 @@ impl Writer { match (value, exec_model) { (None, None) => (), (None, Some(_)) => self.out.write_str(NAME_OUTPUT)?, - (Some(expr_token), None) => { - self.put_expression(expr_token, &fun.expressions, module)?; + (Some(expr_handle), None) => { + self.put_expression(expr_handle, &fun.expressions, module)?; } - (Some(expr_token), Some(_)) => { - panic!("Unable to return value {:?} from an entry point!", expr_token) + (Some(expr_handle), Some(_)) => { + panic!("Unable to return value {:?} from an entry point!", expr_handle) } } writeln!(self.out, ";")?; diff --git a/src/front/mod.rs b/src/front/mod.rs index 484df8f3c..36c1b701e 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,7 +1,7 @@ pub mod spirv; pub mod wgsl; -use crate::storage::Storage; +use crate::arena::Arena; pub const GENERATOR: u32 = 0; @@ -9,10 +9,10 @@ impl crate::Module { fn from_header(header: crate::Header) -> Self { crate::Module { header, - types: Storage::new(), - constants: Storage::new(), - global_variables: Storage::new(), - functions: Storage::new(), + types: Arena::new(), + constants: Arena::new(), + global_variables: Arena::new(), + functions: Arena::new(), entry_points: Vec::new(), } } diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 0c7e4db63..4c922257a 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -2,16 +2,16 @@ ## ID lookups -Our IR links to everything with `Token`, while SPIR-V uses IDs. +Our IR links to everything with `Handle`, while SPIR-V uses IDs. In order to keep track of the associations, the parser has many lookup tables. -There map `spirv::Word` into a specific IR token, plus potentially a bit of +There map `spirv::Word` into a specific IR handle, plus potentially a bit of extra info, such as the related SPIR-V type ID. TODO: would be nice to find ways that avoid looking up as much !*/ use crate::{ - storage::{Storage, Token}, + arena::{Arena, Handle}, FastHashMap, FastHashSet, }; @@ -44,7 +44,7 @@ pub enum Error { UnsupportedCapability(spirv::Capability), UnsupportedExtension(String), UnsupportedExtSet(String), - UnsupportedType(Token), + UnsupportedType(Handle), UnsupportedExecutionModel(u32), UnsupportedStorageClass(u32), UnsupportedFunctionControl(u32), @@ -60,7 +60,7 @@ pub enum Error { InvalidVectorSize(spirv::Word), InvalidVariableClass(spirv::StorageClass), InvalidAccessType(spirv::Word), - InvalidAccessIndex(Token), + InvalidAccessIndex(Handle), InvalidLoadType(spirv::Word), InvalidStoreType(spirv::Word), InvalidBinding(spirv::Word), @@ -197,32 +197,32 @@ struct EntryPoint { #[derive(Debug)] struct LookupType { - token: Token, + handle: Handle, base_id: Option, } #[derive(Debug)] struct LookupConstant { - token: Token, + handle: Handle, type_id: spirv::Word, } #[derive(Debug)] struct LookupVariable { - token: Token, + handle: Handle, type_id: spirv::Word, } #[derive(Clone, Debug)] struct LookupExpression { - token: Token, + handle: Handle, type_id: spirv::Word, } #[derive(Clone, Debug)] struct LookupSampledImage { - image: Token, - sampler: Token, + image: Handle, + sampler: Handle, } pub struct Parser { @@ -239,7 +239,7 @@ pub struct Parser { lookup_expression: FastHashMap, lookup_sampled_image: FastHashMap, lookup_function_type: FastHashMap, - lookup_function: FastHashMap>, + lookup_function: FastHashMap>, } impl> Parser { @@ -354,8 +354,8 @@ impl> Parser { fn next_block( &mut self, fun: &mut crate::Function, - type_store: &Storage, - const_store: &Storage, + type_arena: &Arena, + const_arena: &Arena, ) -> Result<(), Error> { loop { use spirv::Op; @@ -364,7 +364,7 @@ impl> Parser { match inst.op { Op::AccessChain => { struct AccessExpression { - base_token: Token, + base_handle: Handle, type_id: spirv::Word, } inst.expect_at_least(4)?; @@ -376,7 +376,7 @@ impl> Parser { let expr = self.lookup_expression.lookup(base_id)?; let ptr_type = self.lookup_type.lookup(expr.type_id)?; AccessExpression { - base_token: expr.token, + base_handle: expr.handle, type_id: ptr_type.base_id.unwrap(), } }; @@ -384,29 +384,29 @@ impl> Parser { let access_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", access_id); let index_expr = self.lookup_expression.lookup(access_id)?.clone(); - let index_type_token = self.lookup_type.lookup(index_expr.type_id)?.token; - match type_store[index_type_token].inner { + let index_type_handle = self.lookup_type.lookup(index_expr.type_id)?.handle; + match type_arena[index_type_handle].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, .. } | crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, .. } => (), - _ => return Err(Error::UnsupportedType(index_type_token)), + _ => return Err(Error::UnsupportedType(index_type_handle)), } log::trace!("\t\t\tlooking up type {:?}", acex.type_id); let type_lookup = self.lookup_type.lookup(acex.type_id)?; - acex = match type_store[type_lookup.token].inner { + acex = match type_arena[type_lookup.handle].inner { crate::TypeInner::Struct { .. } => { - let index = match fun.expressions[index_expr.token] { - crate::Expression::Constant(const_token) => { - match const_store[const_token].inner { + let index = match fun.expressions[index_expr.handle] { + crate::Expression::Constant(const_handle) => { + match const_arena[const_handle].inner { crate::ConstantInner::Uint(v) => v as u32, crate::ConstantInner::Sint(v) => v as u32, - _ => return Err(Error::InvalidAccessIndex(index_expr.token)), + _ => return Err(Error::InvalidAccessIndex(index_expr.handle)), } } - _ => return Err(Error::InvalidAccessIndex(index_expr.token)) + _ => return Err(Error::InvalidAccessIndex(index_expr.handle)) }; AccessExpression { - base_token: fun.expressions.append(crate::Expression::AccessIndex { - base: acex.base_token, + base_handle: fun.expressions.append(crate::Expression::AccessIndex { + base: acex.base_handle, index, }), type_id: *self.lookup_member_type_id @@ -418,20 +418,20 @@ impl> Parser { crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { AccessExpression { - base_token: fun.expressions.append(crate::Expression::Access { - base: acex.base_token, - index: index_expr.token, + base_handle: fun.expressions.append(crate::Expression::Access { + base: acex.base_handle, + index: index_expr.handle, }), type_id: type_lookup.base_id .ok_or(Error::InvalidAccessType(acex.type_id))?, } } - _ => return Err(Error::UnsupportedType(type_lookup.token)), + _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; } self.lookup_expression.insert(result_id, LookupExpression { - token: acex.base_token, + handle: acex.base_handle, type_id: result_type_id, }); } @@ -444,7 +444,7 @@ impl> Parser { let mut lexp = { let expr = self.lookup_expression.lookup(base_id)?; LookupExpression { - token: expr.token, + handle: expr.handle, type_id: expr.type_id, } }; @@ -452,7 +452,7 @@ impl> Parser { let index = self.next()?; log::trace!("\t\t\tlooking up type {:?}", lexp.type_id); let type_lookup = self.lookup_type.lookup(lexp.type_id)?; - let type_id = match type_store[type_lookup.token].inner { + let type_id = match type_arena[type_lookup.handle].inner { crate::TypeInner::Struct { .. } => { *self.lookup_member_type_id .get(&(lexp.type_id, index)) @@ -464,11 +464,11 @@ impl> Parser { type_lookup.base_id .ok_or(Error::InvalidAccessType(lexp.type_id))? } - _ => return Err(Error::UnsupportedType(type_lookup.token)), + _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; lexp = LookupExpression { - token: fun.expressions.append(crate::Expression::AccessIndex { - base: lexp.token, + handle: fun.expressions.append(crate::Expression::AccessIndex { + base: lexp.handle, index, }), type_id, @@ -476,7 +476,7 @@ impl> Parser { } self.lookup_expression.insert(result_id, LookupExpression { - token: lexp.token, + handle: lexp.handle, type_id: result_type_id, }); } @@ -489,14 +489,14 @@ impl> Parser { let comp_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", comp_id); let lexp = self.lookup_expression.lookup(comp_id)?; - components.push(lexp.token); + components.push(lexp.handle); } let expr = crate::Expression::Compose { - ty: self.lookup_type.lookup(result_type_id)?.token, + ty: self.lookup_type.lookup(result_type_id)?.handle, components, }; self.lookup_expression.insert(id, LookupExpression { - token: fun.expressions.append(expr), + handle: fun.expressions.append(expr), type_id: result_type_id, }); } @@ -514,15 +514,15 @@ impl> Parser { if base_type.base_id != Some(result_type_id) { return Err(Error::InvalidLoadType(result_type_id)); } - match type_store[base_type.token].inner { + match type_arena[base_type.handle].inner { crate::TypeInner::Pointer { .. } => (), - _ => return Err(Error::UnsupportedType(base_type.token)), + _ => return Err(Error::UnsupportedType(base_type.handle)), } let expr = crate::Expression::Load { - pointer: base_expr.token, + pointer: base_expr.handle, }; self.lookup_expression.insert(result_id, LookupExpression { - token: fun.expressions.append(expr), + handle: fun.expressions.append(expr), type_id: result_type_id, }); } @@ -536,17 +536,17 @@ impl> Parser { } let base_expr = self.lookup_expression.lookup(pointer_id)?; let base_type = self.lookup_type.lookup(base_expr.type_id)?; - match type_store[base_type.token].inner { + match type_arena[base_type.handle].inner { crate::TypeInner::Pointer { .. } => (), - _ => return Err(Error::UnsupportedType(base_type.token)), + _ => return Err(Error::UnsupportedType(base_type.handle)), }; let value_expr = self.lookup_expression.lookup(value_id)?; if base_type.base_id != Some(value_expr.type_id) { return Err(Error::InvalidStoreType(value_expr.type_id)); } fun.body.push(crate::Statement::Store { - pointer: base_expr.token, - value: value_expr.token, + pointer: base_expr.handle, + value: value_expr.handle, }) } Op::Return => { @@ -558,28 +558,28 @@ impl> Parser { inst.expect(5)?; let result_type_id = self.next()?; let result_type_loookup = self.lookup_type.lookup(result_type_id)?; - let (res_size, res_width) = match type_store[result_type_loookup.token].inner { + let (res_size, res_width) = match type_arena[result_type_loookup.handle].inner { crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), - _ => return Err(Error::UnsupportedType(result_type_loookup.token)), + _ => return Err(Error::UnsupportedType(result_type_loookup.handle)), }; let result_id = self.next()?; let vector_id = self.next()?; let scalar_id = self.next()?; let vector_lexp = self.lookup_expression.lookup(vector_id)?; let vector_type_lookup = self.lookup_type.lookup(vector_lexp.type_id)?; - match type_store[vector_type_lookup.token].inner { + match type_arena[vector_type_lookup.handle].inner { crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } if size == res_size && width == res_width => (), - _ => return Err(Error::UnsupportedType(vector_type_lookup.token)), + _ => return Err(Error::UnsupportedType(vector_type_lookup.handle)), }; let scalar_lexp = self.lookup_expression.lookup(scalar_id)?.clone(); let scalar_type_lookup = self.lookup_type.lookup(scalar_lexp.type_id)?; - match type_store[scalar_type_lookup.token].inner { + match type_arena[scalar_type_lookup.handle].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width } if width == res_width => (), - _ => return Err(Error::UnsupportedType(scalar_type_lookup.token)), + _ => return Err(Error::UnsupportedType(scalar_type_lookup.handle)), }; - let expr = crate::Expression::Mul(vector_lexp.token, scalar_lexp.token); + let expr = crate::Expression::Mul(vector_lexp.handle, scalar_lexp.handle); self.lookup_expression.insert(result_id, LookupExpression { - token: fun.expressions.append(expr), + handle: fun.expressions.append(expr), type_id: result_type_id, }); } @@ -587,28 +587,28 @@ impl> Parser { inst.expect(5)?; let result_type_id = self.next()?; let result_type_loookup = self.lookup_type.lookup(result_type_id)?; - let (res_size, res_width) = match type_store[result_type_loookup.token].inner { + let (res_size, res_width) = match type_arena[result_type_loookup.handle].inner { crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), - _ => return Err(Error::UnsupportedType(result_type_loookup.token)), + _ => return Err(Error::UnsupportedType(result_type_loookup.handle)), }; let result_id = self.next()?; let matrix_id = self.next()?; let vector_id = self.next()?; let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; let matrix_type_lookup = self.lookup_type.lookup(matrix_lexp.type_id)?; - let columns = match type_store[matrix_type_lookup.token].inner { + let columns = match type_arena[matrix_type_lookup.handle].inner { crate::TypeInner::Matrix { columns, rows, kind: crate::ScalarKind::Float, width } if rows == res_size && width == res_width => columns, - _ => return Err(Error::UnsupportedType(matrix_type_lookup.token)), + _ => return Err(Error::UnsupportedType(matrix_type_lookup.handle)), }; let vector_lexp = self.lookup_expression.lookup(vector_id)?.clone(); let vector_type_lookup = self.lookup_type.lookup(vector_lexp.type_id)?; - match type_store[vector_type_lookup.token].inner { + match type_arena[vector_type_lookup.handle].inner { crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } if size == columns && width == res_width => (), - _ => return Err(Error::UnsupportedType(vector_type_lookup.token)), + _ => return Err(Error::UnsupportedType(vector_type_lookup.handle)), }; - let expr = crate::Expression::Mul(matrix_lexp.token, vector_lexp.token); + let expr = crate::Expression::Mul(matrix_lexp.handle, vector_lexp.handle); self.lookup_expression.insert(result_id, LookupExpression { - token: fun.expressions.append(expr), + handle: fun.expressions.append(expr), type_id: result_type_id, }); } @@ -622,8 +622,8 @@ impl> Parser { let sampler_lexp = self.lookup_expression.lookup(sampler_id)?; //TODO: compare the result type self.lookup_sampled_image.insert(result_id, LookupSampledImage { - image: image_lexp.token, - sampler: sampler_lexp.token, + image: image_lexp.handle, + sampler: sampler_lexp.handle, }); } Op::ImageSampleImplicitLod => { @@ -635,19 +635,19 @@ impl> Parser { let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_lookup = self.lookup_type.lookup(coord_lexp.type_id)?; - match type_store[coord_type_lookup.token].inner { + match type_arena[coord_type_lookup.handle].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, .. } | crate::TypeInner::Vector { kind: crate::ScalarKind::Float, .. } => (), - _ => return Err(Error::UnsupportedType(coord_type_lookup.token)), + _ => return Err(Error::UnsupportedType(coord_type_lookup.handle)), } //TODO: compare the result type let expr = crate::Expression::ImageSample { image: si_lexp.image, sampler: si_lexp.sampler, - coordinate: coord_lexp.token, + coordinate: coord_lexp.handle, }; self.lookup_expression.insert(result_id, LookupExpression { - token: fun.expressions.append(expr), + handle: fun.expressions.append(expr), type_id: result_type_id, }); } @@ -657,21 +657,21 @@ impl> Parser { Ok(()) } - fn make_expression_storage(&mut self) -> Storage { - let mut expressions = Storage::new(); + fn make_expression_storage(&mut self) -> Arena { + let mut expressions = Arena::new(); assert!(self.lookup_expression.is_empty()); // register global variables for (&id, var) in self.lookup_variable.iter() { self.lookup_expression.insert(id, LookupExpression { type_id: var.type_id, - token: expressions.append(crate::Expression::GlobalVariable(var.token)), + handle: expressions.append(crate::Expression::GlobalVariable(var.handle)), }); } // register constants for (&id, con) in self.lookup_constant.iter() { self.lookup_expression.insert(id, LookupExpression { type_id: con.type_id, - token: expressions.append(crate::Expression::Constant(con.token)), + handle: expressions.append(crate::Expression::Constant(con.handle)), }); } // done @@ -863,7 +863,7 @@ impl> Parser { .map_err(|_| Error::InvalidTypeWidth(width))?, }; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -884,7 +884,7 @@ impl> Parser { .map_err(|_| Error::InvalidTypeWidth(width))?, }; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -899,7 +899,7 @@ impl> Parser { let id = self.next()?; let type_id = self.next()?; let type_lookup = self.lookup_type.lookup(type_id)?; - let (kind, width) = match module.types[type_lookup.token].inner { + let (kind, width) = match module.types[type_lookup.handle].inner { crate::TypeInner::Scalar { kind, width } => (kind, width), _ => return Err(Error::InvalidInnerType(type_id)), }; @@ -910,7 +910,7 @@ impl> Parser { width, }; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -926,7 +926,7 @@ impl> Parser { let vector_type_id = self.next()?; let num_columns = self.next()?; let vector_type_lookup = self.lookup_type.lookup(vector_type_id)?; - let inner = match module.types[vector_type_lookup.token].inner { + let inner = match module.types[vector_type_lookup.handle].inner { crate::TypeInner::Vector { size, kind, width } => crate::TypeInner::Matrix { columns: map_vector_size(num_columns)?, rows: size, @@ -936,7 +936,7 @@ impl> Parser { _ => return Err(Error::InvalidInnerType(vector_type_id)), }; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -966,11 +966,11 @@ impl> Parser { let storage = self.next()?; let type_id = self.next()?; let inner = crate::TypeInner::Pointer { - base: self.lookup_type.lookup(type_id)?.token, + base: self.lookup_type.lookup(type_id)?.handle, class: map_storage_class(storage)?, }; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -986,11 +986,11 @@ impl> Parser { let type_id = self.next()?; let length = self.next()?; let inner = crate::TypeInner::Array { - base: self.lookup_type.lookup(type_id)?.token, + base: self.lookup_type.lookup(type_id)?.handle, size: crate::ArraySize::Static(length), }; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -1005,11 +1005,11 @@ impl> Parser { let id = self.next()?; let type_id = self.next()?; let inner = crate::TypeInner::Array { - base: self.lookup_type.lookup(type_id)?.token, + base: self.lookup_type.lookup(type_id)?.handle, size: crate::ArraySize::Dynamic, }; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -1025,7 +1025,7 @@ impl> Parser { let mut members = Vec::with_capacity(inst.wc as usize - 2); for i in 0 .. inst.wc as u32 - 2 { let type_id = self.next()?; - let ty = self.lookup_type.lookup(type_id)?.token; + let ty = self.lookup_type.lookup(type_id)?.handle; self.lookup_member_type_id.insert((id, i), type_id); let decor = self.future_member_decor .remove(&(id, i)) @@ -1041,7 +1041,7 @@ impl> Parser { members }; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -1086,7 +1086,7 @@ impl> Parser { .unwrap_or_default(); let inner = crate::TypeInner::Image { - base: self.lookup_type.lookup(sample_type_id)?.token, + base: self.lookup_type.lookup(sample_type_id)?.handle, dim: if dim > LAST_KNOWN_DIM as u32 { return Err(Error::UnsupportedDim(dim)); } else { @@ -1095,7 +1095,7 @@ impl> Parser { flags, }; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: decor.name, inner, }), @@ -1108,7 +1108,7 @@ impl> Parser { let id = self.next()?; let image_id = self.next()?; self.lookup_type.insert(id, LookupType { - token: self.lookup_type.lookup(image_id)?.token, + handle: self.lookup_type.lookup(image_id)?.handle, base_id: Some(image_id), }); } @@ -1121,7 +1121,7 @@ impl> Parser { .unwrap_or_default(); let inner = crate::TypeInner::Sampler; self.lookup_type.insert(id, LookupType { - token: module.types.append(crate::Type { + handle: module.types.append(crate::Type { name: decor.name, inner, }), @@ -1135,7 +1135,7 @@ impl> Parser { let type_id = self.next()?; let id = self.next()?; let type_lookup = self.lookup_type.lookup(type_id)?; - let inner = match module.types[type_lookup.token].inner { + let inner = match module.types[type_lookup.handle].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width } => { let low = self.next()?; let high = if width > 32 { @@ -1177,10 +1177,10 @@ impl> Parser { }; crate::ConstantInner::Float(extended) } - _ => return Err(Error::UnsupportedType(type_lookup.token)) + _ => return Err(Error::UnsupportedType(type_lookup.handle)) }; self.lookup_constant.insert(id, LookupConstant { - token: module.constants.append(crate::Constant { + handle: module.constants.append(crate::Constant { name: self.future_decor .remove(&id) .and_then(|dec| dec.name), @@ -1204,7 +1204,7 @@ impl> Parser { let dec = self.future_decor .remove(&id) .ok_or(Error::InvalidBinding(id))?; - let binding = match module.types[lookup_type.token].inner { + let binding = match module.types[lookup_type.handle].inner { crate::TypeInner::Pointer { base, class: spirv::StorageClass::Input } | crate::TypeInner::Pointer { base, class: spirv::StorageClass::Output } => { match module.types[base].inner { @@ -1238,11 +1238,10 @@ impl> Parser { name: dec.name, class: map_storage_class(storage)?, binding, - ty: lookup_type.token, + ty: lookup_type.handle, }; - let token = module.global_variables.append(var); self.lookup_variable.insert(id, LookupVariable { - token, + handle: module.global_variables.append(var), type_id, }); } @@ -1268,7 +1267,7 @@ impl> Parser { return_type: if self.lookup_void_type.contains(&result_type) { None } else { - Some(self.lookup_type.lookup(result_type)?.token) + Some(self.lookup_type.lookup(result_type)?.handle) }, expressions: self.make_expression_storage(), body: Vec::new(), @@ -1287,7 +1286,7 @@ impl> Parser { { return Err(Error::WrongFunctionParameterType(type_id)) } - let ty = self.lookup_type.lookup(type_id)?.token; + let ty = self.lookup_type.lookup(type_id)?.handle; fun.parameter_types.push(ty); } Instruction { op, .. } => return Err(Error::InvalidParameter(op)), @@ -1311,8 +1310,8 @@ impl> Parser { } } // done - let token = module.functions.append(fun); - self.lookup_function.insert(fun_id, token); + let handle = module.functions.append(fun); + self.lookup_function.insert(fun_id, handle); self.lookup_expression.clear(); self.lookup_sampled_image.clear(); } @@ -1340,10 +1339,10 @@ impl> Parser { outputs: Vec::new(), }; for var_id in raw.variable_ids { - let token = self.lookup_variable.lookup(var_id)?.token; - match module.global_variables[token].class { - spirv::StorageClass::Input => ep.inputs.push(token), - spirv::StorageClass::Output => ep.outputs.push(token), + let handle = self.lookup_variable.lookup(var_id)?.handle; + match module.global_variables[handle].class { + spirv::StorageClass::Input => ep.inputs.push(handle), + spirv::StorageClass::Output => ep.outputs.push(handle), other => return Err(Error::InvalidVariableClass(other)) } } diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 1ed8d18aa..a2d4ebc3d 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,5 +1,5 @@ use crate::{ - storage::{Storage, Token as Id}, + arena::{Arena, Handle}, FastHashMap, }; @@ -177,8 +177,8 @@ trait StringValueLookup<'a> { type Value; fn lookup(&self, key: &'a str) -> Result>; } -impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Id> { - type Value = Id; +impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle> { + type Value = Handle; fn lookup(&self, key: &'a str) -> Result> { self.get(key) .cloned() @@ -188,9 +188,9 @@ impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Id> { struct ExpressionContext<'input,'temp, 'out> { function: &'out mut crate::Function, - lookup_ident: &'temp FastHashMap<&'input str, Id>, - types: &'out mut Storage, - constants: &'out mut Storage, + lookup_ident: &'temp FastHashMap<&'input str, Handle>, + types: &'out mut Arena, + constants: &'out mut Arena, } impl<'a> ExpressionContext<'a, '_, '_> { @@ -208,8 +208,8 @@ impl<'a> ExpressionContext<'a, '_, '_> { lexer: &mut Lexer<'a>, middle: Token<'a>, op: crate::BinaryOperator, - mut parser: impl FnMut(&mut Lexer<'a>, ExpressionContext<'a, '_, '_>) -> Result, Error<'a>>, - ) -> Result, Error<'a>> { + mut parser: impl FnMut(&mut Lexer<'a>, ExpressionContext<'a, '_, '_>) -> Result, Error<'a>>, + ) -> Result, Error<'a>> { let mut left = parser(lexer, self.reborrow())?; while lexer.peek() == middle { let _ = lexer.next(); @@ -233,7 +233,7 @@ pub struct ParseError<'a> { pub struct Parser { scopes: Vec, - lookup_type: FastHashMap>, + lookup_type: FastHashMap>, } impl Parser { @@ -338,8 +338,8 @@ impl Parser { fn parse_const_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - type_store: &mut Storage, - const_store: &mut Storage, + type_arena: &mut Arena, + const_arena: &mut Arena, ) -> Result> { self.scopes.push(Scope::ConstantExpr); let inner = match lexer.peek() { @@ -356,10 +356,10 @@ impl Parser { Self::get_constant_inner(word)? } _ => { - let _ty = self.parse_type_decl(lexer, type_store); + let _ty = self.parse_type_decl(lexer, type_arena); Self::expect(lexer, Token::Paren('('))?; while lexer.peek() != Token::Paren(')') { - let _ = self.parse_const_expression(lexer, type_store, const_store)?; + let _ = self.parse_const_expression(lexer, type_arena, const_arena)?; } let _ = lexer.next(); unimplemented!() @@ -373,7 +373,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { + ) -> Result, Error<'a>> { self.scopes.push(Scope::PrimaryExpr); let backup = lexer.clone(); let expression = match lexer.next() { @@ -384,33 +384,33 @@ impl Parser { return Ok(expr); } Token::Word("true") => { - let id = ctx.constants.append(crate::Constant { + let handle = ctx.constants.append(crate::Constant { name: None, specialization: None, inner: crate::ConstantInner::Bool(true), }); - crate::Expression::Constant(id) + crate::Expression::Constant(handle) } Token::Word("false") => { - let id = ctx.constants.append(crate::Constant { + let handle = ctx.constants.append(crate::Constant { name: None, specialization: None, inner: crate::ConstantInner::Bool(false), }); - crate::Expression::Constant(id) + crate::Expression::Constant(handle) } Token::Number(word) => { - let id = ctx.constants.append(crate::Constant { + let handle = ctx.constants.append(crate::Constant { name: None, specialization: None, inner: Self::get_constant_inner(word)?, }); - crate::Expression::Constant(id) + crate::Expression::Constant(handle) } Token::Word(word) => { - if let Some(id) = ctx.lookup_ident.get(word) { + if let Some(handle) = ctx.lookup_ident.get(word) { self.scopes.pop(); - return Ok(*id); + return Ok(*handle); } *lexer = backup; let ty = self.parse_type_decl(lexer, ctx.types)?; @@ -436,7 +436,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { + ) -> Result, Error<'a>> { context.parse_binary_op( lexer, Token::Operation('+'), @@ -454,9 +454,9 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { + ) -> Result, Error<'a>> { self.scopes.push(Scope::GeneralExpr); - let id = context.parse_binary_op( + let handle = context.parse_binary_op( lexer, Token::LogicalOperation('|'), crate::BinaryOperator::LogicalOr, @@ -488,26 +488,26 @@ impl Parser { ), )?; self.scopes.pop(); - Ok(id) + Ok(handle) } fn parse_variable_ident_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - type_store: &mut Storage, - ) -> Result<(&'a str, Id), Error<'a>> { + type_arena: &mut Arena, + ) -> Result<(&'a str, Handle), Error<'a>> { let name = Self::parse_ident(lexer)?; Self::expect(lexer, Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, type_store)?; + let ty = self.parse_type_decl(lexer, type_arena)?; Ok((name, ty)) } fn parse_variable_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - type_store: &mut Storage, - const_store: &mut Storage, - ) -> Result<(&'a str, Option, Id), Error<'a>> { + type_arena: &mut Arena, + const_arena: &mut Arena, + ) -> Result<(&'a str, Option, Handle), Error<'a>> { self.scopes.push(Scope::VariableDecl); let mut class = None; if let Token::Paren('<') = lexer.peek() { @@ -518,10 +518,10 @@ impl Parser { } let name = Self::parse_ident(lexer)?; Self::expect(lexer, Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, type_store)?; + let ty = self.parse_type_decl(lexer, type_arena)?; if let Token::Operation('=') = lexer.peek() { let _ = lexer.next(); - let _inner = self.parse_const_expression(lexer, type_store, const_store)?; + let _inner = self.parse_const_expression(lexer, type_arena, const_arena)?; //TODO } Self::expect(lexer, Token::Separator(';'))?; @@ -532,7 +532,7 @@ impl Parser { fn parse_struct_body<'a>( &mut self, lexer: &mut Lexer<'a>, - type_store: &mut Storage, + type_arena: &mut Arena, ) -> Result, Error<'a>> { let mut members = Vec::new(); Self::expect(lexer, Token::Paren('{'))?; @@ -563,7 +563,7 @@ impl Parser { other => return Err(Error::Unexpected(other)), }; Self::expect(lexer, Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, type_store)?; + let ty = self.parse_type_decl(lexer, type_arena)?; Self::expect(lexer, Token::Separator(';'))?; members.push(crate::StructMember { name: Some(name.to_owned()), @@ -576,8 +576,8 @@ impl Parser { fn parse_type_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - type_store: &mut Storage, - ) -> Result, Error<'a>> { + type_arena: &mut Arena, + ) -> Result, Error<'a>> { self.scopes.push(Scope::TypeDecl); let inner = match lexer.next() { Token::Word("f32") => { @@ -653,13 +653,13 @@ impl Parser { Self::expect(lexer, Token::Paren('<'))?; let class = Self::get_storage_class(Self::parse_ident(lexer)?)?; Self::expect(lexer, Token::Separator(','))?; - let base = self.parse_type_decl(lexer, type_store)?; + let base = self.parse_type_decl(lexer, type_arena)?; Self::expect(lexer, Token::Paren('>'))?; crate::TypeInner::Pointer { base, class } } Token::Word("array") => { Self::expect(lexer, Token::Paren('<'))?; - let base = self.parse_type_decl(lexer, type_store)?; + let base = self.parse_type_decl(lexer, type_arena)?; let size = match lexer.next() { Token::Separator(',') => { let value = Self::parse_uint_literal(lexer)?; @@ -672,20 +672,20 @@ impl Parser { crate::TypeInner::Array { base, size } } Token::Word("struct") => { - let members = self.parse_struct_body(lexer, type_store)?; + let members = self.parse_struct_body(lexer, type_arena)?; crate::TypeInner::Struct { members } } other => return Err(Error::Unexpected(other)), }; self.scopes.pop(); - if let Some((token, _)) = type_store + if let Some((token, _)) = type_arena .iter() .find(|(_, ty)| ty.inner == inner) { return Ok(token); } - Ok(type_store.append(crate::Type { + Ok(type_arena.append(crate::Type { name: None, inner, })) @@ -696,7 +696,7 @@ impl Parser { lexer: &mut Lexer<'a>, module: &mut crate::Module, lookup_global_expression: &FastHashMap<&'a str, crate::Expression>, - ) -> Result, Error<'a>> { + ) -> Result, Error<'a>> { self.scopes.push(Scope::FunctionDecl); // read function name let mut lookup_ident = FastHashMap::default(); @@ -706,13 +706,13 @@ impl Parser { control: spirv::FunctionControl::empty(), parameter_types: Vec::new(), return_type: None, - expressions: Storage::new(), + expressions: Arena::new(), body: Vec::new(), }; // populare initial expressions for (&name, expression) in lookup_global_expression.iter() { - let expr_id = fun.expressions.append(expression.clone()); - lookup_ident.insert(name, expr_id); + let expr_handle = fun.expressions.append(expression.clone()); + lookup_ident.insert(name, expr_handle); } // read parameter list Self::expect(lexer, Token::Paren('('))?; @@ -721,8 +721,8 @@ impl Parser { Self::expect(lexer, Token::Separator(','))?; } let (param_name, param_type) = self.parse_variable_ident_decl(lexer, &mut module.types)?; - let param_id = fun.parameter_types.len() as u32; - let expression_token = fun.expressions.append(crate::Expression::FunctionParameter(param_id)); + let param_index = fun.parameter_types.len() as u32; + let expression_token = fun.expressions.append(crate::Expression::FunctionParameter(param_index)); lookup_ident.insert(param_name, expression_token); fun.parameter_types.push(param_type); } @@ -856,22 +856,22 @@ impl Parser { Self::expect(lexer, Token::Operation('='))?; let inner = self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; Self::expect(lexer, Token::Separator(';'))?; - let const_id = module.constants.append(crate::Constant { + let const_handle = module.constants.append(crate::Constant { name: Some(name.to_owned()), specialization: None, inner, }); - lookup_global_expression.insert(name, crate::Expression::Constant(const_id)); + lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); } Token::Word("var") => { let (name, class, ty) = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; - let var_id = module.global_variables.append(crate::GlobalVariable { + let var_handle = module.global_variables.append(crate::GlobalVariable { name: Some(name.to_owned()), class: class.unwrap_or(spirv::StorageClass::Private), binding: binding.take(), ty, }); - lookup_global_expression.insert(name, crate::Expression::GlobalVariable(var_id)); + lookup_global_expression.insert(name, crate::Expression::GlobalVariable(var_handle)); } Token::Word("fn") => { self.parse_function_decl(lexer, module, &lookup_global_expression)?; @@ -893,7 +893,7 @@ impl Parser { let function = module.functions .iter() .find(|(_, fun)| fun.name.as_ref().map(|s| s.as_str()) == Some(fun_ident)) - .map(|(id, _)| id) + .map(|(handle, _)| handle) .ok_or(Error::UnknownFunction(fun_ident))?; module.entry_points.push(crate::EntryPoint { exec_model, diff --git a/src/lib.rs b/src/lib.rs index 71957a1f9..dfaf89626 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,8 +1,8 @@ +mod arena; pub mod back; pub mod front; -mod storage; -use crate::storage::{Storage, Token}; +use crate::arena::{Arena, Handle}; use std::{ collections::{HashMap, HashSet}, @@ -49,7 +49,7 @@ pub enum ArraySize { pub struct StructMember { pub name: Option, pub binding: Option, - pub ty: Token, + pub ty: Handle, } bitflags::bitflags! { @@ -73,10 +73,10 @@ pub enum TypeInner { Scalar { kind: ScalarKind, width: Bytes }, Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, Matrix { columns: VectorSize, rows: VectorSize, kind: ScalarKind, width: Bytes }, - Pointer { base: Token, class: spirv::StorageClass }, - Array { base: Token, size: ArraySize }, + Pointer { base: Handle, class: spirv::StorageClass }, + Array { base: Handle, size: ArraySize }, Struct { members: Vec }, - Image { base: Token, dim: spirv::Dim, flags: ImageFlags }, + Image { base: Handle, dim: spirv::Dim, flags: ImageFlags }, Sampler, } @@ -107,7 +107,7 @@ pub struct GlobalVariable { pub name: Option, pub class: spirv::StorageClass, pub binding: Option, - pub ty: Token, + pub ty: Handle, } #[derive(Clone, Copy, Debug)] @@ -125,33 +125,33 @@ pub enum BinaryOperator { #[derive(Clone, Debug)] pub enum Expression { Access { - base: Token, - index: Token, //int + base: Handle, + index: Handle, //int }, AccessIndex { - base: Token, + base: Handle, index: u32, }, - Constant(Token), + Constant(Handle), Compose { - ty: Token, - components: Vec>, + ty: Handle, + components: Vec>, }, FunctionParameter(u32), - GlobalVariable(Token), + GlobalVariable(Handle), Load { - pointer: Token, + pointer: Handle, }, - Mul(Token, Token), + Mul(Handle, Handle), ImageSample { - image: Token, - sampler: Token, - coordinate: Token, + image: Handle, + sampler: Handle, + coordinate: Handle, }, Binary { op: BinaryOperator, - left: Token, - right: Token, + left: Handle, + right: Handle, }, } @@ -164,26 +164,26 @@ pub enum Statement { Block(Block), VariableDeclaration { name: String, - ty: Token, - value: Option>, + ty: Handle, + value: Option>, }, If { - condition: Token, //bool + condition: Handle, //bool accept: Block, reject: Block, }, Switch { - selector: Token, //int + selector: Handle, //int cases: FastHashMap)>, default: Block, }, Return { - value: Option>, + value: Option>, }, Kill, Store { - pointer: Token, - value: Token, + pointer: Handle, + value: Handle, }, } @@ -191,9 +191,9 @@ pub enum Statement { pub struct Function { pub name: Option, pub control: spirv::FunctionControl, - pub parameter_types: Vec>, - pub return_type: Option>, - pub expressions: Storage, + pub parameter_types: Vec>, + pub return_type: Option>, + pub expressions: Arena, pub body: Block, } @@ -201,17 +201,17 @@ pub struct Function { pub struct EntryPoint { pub exec_model: spirv::ExecutionModel, pub name: String, - pub inputs: Vec>, - pub outputs: Vec>, - pub function: Token, + pub inputs: Vec>, + pub outputs: Vec>, + pub function: Handle, } #[derive(Debug)] pub struct Module { pub header: Header, - pub types: Storage, - pub constants: Storage, - pub global_variables: Storage, - pub functions: Storage, + pub types: Arena, + pub constants: Arena, + pub global_variables: Arena, + pub functions: Arena, pub entry_points: Vec, } diff --git a/src/storage.rs b/src/storage.rs deleted file mode 100644 index b56c426ca..000000000 --- a/src/storage.rs +++ /dev/null @@ -1,155 +0,0 @@ -use std::{ - fmt, - hash, - marker::PhantomData, -}; - -/// An unique index in the storage array that a token points to. -/// -/// This type is independent of `spirv::Word`. `spirv::Word` is used in data -/// representation. It holds a SPIR-V and refers to that instruction. In -/// structured representation, we use Token to refer to an SPIR-V instruction. -/// Index is an implementation detail to Token. -type Index = u32; - -/// A strongly typed reference to a SPIR-V element. -pub struct Token { - index: Index, - marker: PhantomData, -} - -impl Clone for Token { - fn clone(&self) -> Self { - Token { - index: self.index, - marker: self.marker, - } - } -} -impl Copy for Token {} -impl PartialEq for Token { - fn eq(&self, other: &Self) -> bool { - self.index == other.index - } -} -impl Eq for Token {} -impl fmt::Debug for Token { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "Token({})", self.index) - } -} -impl hash::Hash for Token { - fn hash(&self, hasher: &mut H) { - self.index.hash(hasher) - } -} - -impl Token { - #[cfg(test)] - pub const DUMMY: Self = Token { - index: !0, - marker: PhantomData, - }; - - pub(crate) fn new(index: Index) -> Self { - Token { - index, - marker: PhantomData, - } - } - - pub fn index(&self) -> usize { - self.index as usize - } -} - -/// A structure holding some kind of SPIR-V entity (e.g., type, constant, -/// instruction, etc.) that can be referenced. -#[derive(Debug)] -pub struct Storage { - /// Values of this storage. - data: Vec, -} - -impl Storage { - pub fn new() -> Self { - Storage { - data: Vec::new(), - } - } - - pub fn iter<'a>(&'a self) -> impl Iterator, &'a T)> { - self.data - .iter() - .enumerate() - .map(|(i, v)| (Token::new(i as Index), v)) - } - - /// Adds a new value to the storage, returning a typed token. - /// - /// The value is not linked to any SPIR-V module. - pub fn append(&mut self, value: T) -> Token { - let index = self.data.len() as Index; - self.data.push(value); - Token::new(index) - } - - /// Adds a value with a check for uniqueness: returns a token pointing to - /// an existing element if its value matches the given one, or adds a new - /// element otherwise. - pub fn fetch_or_append(&mut self, value: T) -> Token where T: PartialEq { - if let Some(index) = self.data.iter().position(|d| d == &value) { - Token::new(index as Index) - } else { - self.append(value) - } - } -} - -impl std::ops::Index> for Storage { - type Output = T; - fn index(&self, token: Token) -> &T { - &self.data[token.index as usize] - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn append_non_unique() { - let mut storage: Storage = Storage::new(); - let t1 = storage.append(0.0); - let t2 = storage.append(0.0); - assert!(t1 != t2); - assert!(storage[t1] == storage[t2]); - } - - #[test] - fn append_unique() { - let mut storage: Storage = Storage::new(); - let t1 = storage.append(std::f64::NAN); - let t2 = storage.append(std::f64::NAN); - assert!(t1 != t2); - assert!(storage[t1] != storage[t2]); - } - - #[test] - fn fetch_or_append_non_unique() { - let mut storage: Storage = Storage::new(); - let t1 = storage.fetch_or_append(0.0); - let t2 = storage.fetch_or_append(0.0); - assert!(t1 == t2); - assert!(storage[t1] == storage[t2]) - } - - #[test] - fn fetch_or_append_unique() { - let mut storage: Storage = Storage::new(); - let t1 = storage.fetch_or_append(std::f64::NAN); - let t2 = storage.fetch_or_append(std::f64::NAN); - assert!(t1 != t2); - assert!(storage[t1] != storage[t2]); - } -} From 0f8e3e4b9b41a70132117d12887d507b11e87317 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 12 Mar 2020 11:39:16 -0400 Subject: [PATCH 0047/2212] Singular, intrinsic, and derivative expressions --- src/front/wgsl.rs | 239 +++++++++++++++++++++++++++++++++++++++------- src/lib.rs | 55 ++++++++++- 2 files changed, 257 insertions(+), 37 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index a2d4ebc3d..158810d9b 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -26,6 +26,8 @@ pub enum Token<'a> { Word(&'a str), Operation(char), LogicalOperation(char), + ShiftOperation(char), + ArithmeticShiftOperation(char), Arrow, Unknown(char), UnterminatedString, @@ -67,10 +69,27 @@ impl<'a> Lexer<'a> { self.input = chars.as_str(); Token::Separator(cur) } - '(' | ')' | '<' | '>' | '{' | '}' => { + '(' | ')' | '{' | '}' => { self.input = chars.as_str(); Token::Paren(cur) } + '<' | '>' => { + self.input = chars.as_str(); + if chars.next() == Some('=') { + self.input = chars.as_str(); + Token::LogicalOperation(cur) + } else if chars.next() == Some(cur) { + self.input = chars.as_str(); + if chars.next() == Some(cur) { + self.input = chars.as_str(); + Token::ArithmeticShiftOperation(cur) + } else { + Token::ShiftOperation(cur) + } + } else { + Token::Paren(cur) + } + } '[' | ']' => { self.input = chars.as_str(); if chars.next() == Some(cur) { @@ -106,7 +125,7 @@ impl<'a> Lexer<'a> { Token::Operation(cur) } } - '+' | '*' | '/' | '^' => { + '+' | '*' | '/' | '%' | '^' => { self.input = chars.as_str(); Token::Operation(cur) } @@ -115,15 +134,15 @@ impl<'a> Lexer<'a> { self.input = chars.as_str(); Token::LogicalOperation(cur) } else { - Token::Unknown(cur) + Token::Operation(cur) } } '=' | '&' | '|' => { + self.input = chars.as_str(); if chars.next() == Some(cur) { - self.input = &self.input[2..]; + self.input = chars.as_str(); Token::LogicalOperation(cur) } else { - self.input = &self.input[1..]; Token::Operation(cur) } } @@ -157,6 +176,7 @@ pub enum Scope { Statement, ConstantExpr, PrimaryExpr, + SingularExpr, GeneralExpr, } @@ -165,6 +185,7 @@ pub enum Error<'a> { Unexpected(Token<'a>), BadInteger(&'a str, std::num::ParseIntError), BadFloat(&'a str, std::num::ParseFloatError), + UnknownImport(&'a str), UnknownStorageClass(&'a str), UnknownBuiltin(&'a str), UnknownPipelineStage(&'a str), @@ -206,12 +227,11 @@ impl<'a> ExpressionContext<'a, '_, '_> { fn parse_binary_op( &mut self, lexer: &mut Lexer<'a>, - middle: Token<'a>, - op: crate::BinaryOperator, + classifier: impl Fn(Token<'a>) -> Option, mut parser: impl FnMut(&mut Lexer<'a>, ExpressionContext<'a, '_, '_>) -> Result, Error<'a>>, ) -> Result, Error<'a>> { let mut left = parser(lexer, self.reborrow())?; - while lexer.peek() == middle { + while let Some(op) = classifier(lexer.peek()) { let _ = lexer.next(); let expression = crate::Expression::Binary { op, @@ -234,6 +254,7 @@ pub struct ParseError<'a> { pub struct Parser { scopes: Vec, lookup_type: FastHashMap>, + std_namespace: Option, } impl Parser { @@ -241,6 +262,7 @@ impl Parser { Parser { scopes: Vec::new(), lookup_type: FastHashMap::default(), + std_namespace: None, } } @@ -432,20 +454,146 @@ impl Parser { Ok(ctx.function.expressions.append(expression)) } - fn parse_relational_expression<'a>( + fn parse_singular_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + fn get_intrinsic(word: &str) -> Option { + match word { + "any" => Some(crate::IntrinsicFunction::Any), + "all" => Some(crate::IntrinsicFunction::All), + "is_nan" => Some(crate::IntrinsicFunction::IsNan), + "is_inf" => Some(crate::IntrinsicFunction::IsInf), + "is_normal" => Some(crate::IntrinsicFunction::IsNormal), + _ => None, + } + } + fn get_derivative(word: &str) -> Option { + match word { + "dpdx" => Some(crate::DerivativeAxis::X), + "dpdy" => Some(crate::DerivativeAxis::Y), + "dwidth" => Some(crate::DerivativeAxis::Width), + _ => None, + } + } + + self.scopes.push(Scope::SingularExpr); + let backup = lexer.clone(); + let expression = match lexer.next() { + Token::Operation('-') => { + Some(crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr: self.parse_singular_expression(lexer, ctx.reborrow())?, + }) + } + Token::Operation('!') => { + Some(crate::Expression::Unary { + op: crate::UnaryOperator::Not, + expr: self.parse_singular_expression(lexer, ctx.reborrow())?, + }) + } + Token::Word(word) => { + if let Some(fun) = get_intrinsic(word) { + Self::expect(lexer, Token::Paren('('))?; + let argument = self.parse_primary_expression(lexer, ctx.reborrow())?; + Self::expect(lexer, Token::Paren(')'))?; + Some(crate::Expression::Intrinsic { + fun, + argument, + }) + } else if let Some(axis) = get_derivative(word) { + Self::expect(lexer, Token::Paren('('))?; + let expr = self.parse_primary_expression(lexer, ctx.reborrow())?; + Self::expect(lexer, Token::Paren(')'))?; + Some(crate::Expression::Derivative { + axis, + expr, + }) + } else if word == "dot" { + Self::expect(lexer, Token::Paren('('))?; + let a = self.parse_primary_expression(lexer, ctx.reborrow())?; + Self::expect(lexer, Token::Separator(','))?; + let b = self.parse_primary_expression(lexer, ctx.reborrow())?; + Self::expect(lexer, Token::Paren(')'))?; + Some(crate::Expression::DotProduct(a, b)) + } else if word == "outer_product" { + Self::expect(lexer, Token::Paren('('))?; + let a = self.parse_primary_expression(lexer, ctx.reborrow())?; + Self::expect(lexer, Token::Separator(','))?; + let b = self.parse_primary_expression(lexer, ctx.reborrow())?; + Self::expect(lexer, Token::Paren(')'))?; + Some(crate::Expression::CrossProduct(a, b)) + } else { + None + } + } + _ => None, + }; + + self.scopes.pop(); + match expression { + Some(expr) => Ok(ctx.function.expressions.append(expr)), + None => { + *lexer = backup; + self.parse_primary_expression(lexer, ctx) + } + } + } + + fn parse_equality_expression<'a>( &mut self, lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { + // equality_expression context.parse_binary_op( lexer, - Token::Operation('+'), - crate::BinaryOperator::Add, + |token| match token { + Token::LogicalOperation('=') => Some(crate::BinaryOperator::Equal), + Token::LogicalOperation('!') => Some(crate::BinaryOperator::NotEqual), + _ => None + }, + // relational_expression |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation('*'), - crate::BinaryOperator::Multiply, - |lexer, context| self.parse_primary_expression(lexer, context), + |token| match token { + Token::Paren('<') => Some(crate::BinaryOperator::Less), + Token::Paren('>') => Some(crate::BinaryOperator::Greater), + Token::LogicalOperation('<') => Some(crate::BinaryOperator::LessEqual), + Token::LogicalOperation('>') => Some(crate::BinaryOperator::GreaterEqual), + _ => None, + }, + // shift_expression + |lexer, mut context| context.parse_binary_op( + lexer, + |token| match token { + Token::ShiftOperation('<') => Some(crate::BinaryOperator::ShiftLeftLogical), + Token::ShiftOperation('>') => Some(crate::BinaryOperator::ShiftRightLogical), + Token::ArithmeticShiftOperation('>') => Some(crate::BinaryOperator::ShiftRightArithmetic), + _ => None, + }, + // additive_expression + |lexer, mut context| context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('+') => Some(crate::BinaryOperator::Add), + Token::Operation('-') => Some(crate::BinaryOperator::Subtract), + _ => None, + }, + // multiplicative_expression + |lexer, mut context| context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('*') => Some(crate::BinaryOperator::Multiply), + Token::Operation('/') => Some(crate::BinaryOperator::Divide), + Token::Operation('%') => Some(crate::BinaryOperator::Modulo), + _ => None, + }, + |lexer, context| self.parse_singular_expression(lexer, context), + ), + ), + ), ), ) } @@ -456,32 +604,42 @@ impl Parser { mut context: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { self.scopes.push(Scope::GeneralExpr); + // logical_or_expression let handle = context.parse_binary_op( lexer, - Token::LogicalOperation('|'), - crate::BinaryOperator::LogicalOr, + |token| match token { + Token::LogicalOperation('|') => Some(crate::BinaryOperator::LogicalOr), + _ => None, + }, + // logical_and_expression |lexer, mut context| context.parse_binary_op( lexer, - Token::LogicalOperation('&'), - crate::BinaryOperator::LogicalAnd, + |token| match token { + Token::LogicalOperation('&') => Some(crate::BinaryOperator::LogicalAnd), + _ => None, + }, + // inclusive_or_expression |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation('|'), - crate::BinaryOperator::InclusiveOr, + |token| match token { + Token::Operation('|') => Some(crate::BinaryOperator::InclusiveOr), + _ => None, + }, + // exclusive_or_expression |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation('^'), - crate::BinaryOperator::ExclusiveOr, + |token| match token { + Token::Operation('^') => Some(crate::BinaryOperator::ExclusiveOr), + _ => None, + }, + // and_expression |lexer, mut context| context.parse_binary_op( lexer, - Token::Operation('&'), - crate::BinaryOperator::And, - |lexer, mut context| context.parse_binary_op( - lexer, - Token::LogicalOperation('='), - crate::BinaryOperator::Equals, - |lexer, context| self.parse_relational_expression(lexer, context), - ), + |token| match token { + Token::Operation('&') => Some(crate::BinaryOperator::And), + _ => None, + }, + |lexer, context| self.parse_equality_expression(lexer, context), ), ), ), @@ -838,10 +996,19 @@ impl Parser { Token::Separator(';') => {}, Token::Word("import") => { self.scopes.push(Scope::ImportDecl); - let _path = lexer.next(); - //consume(words, "as", Scope::ImportDecl)?; - let _namespace = lexer.next(); + let path = match lexer.next() { + Token::String(path) => path, + other => return Err(Error::Unexpected(other)), + }; + Self::expect(lexer, Token::Word("as"))?; + let namespace = Self::parse_ident(lexer)?; Self::expect(lexer, Token::Separator(';'))?; + match path { + "GLSL.std.450" => { + self.std_namespace = Some(namespace.to_owned()) + } + _ => return Err(Error::UnknownImport(path)), + } self.scopes.pop(); } Token::Word("type") => { @@ -914,6 +1081,10 @@ impl Parser { } pub fn parse<'a>(&mut self, source: &'a str) -> Result> { + self.scopes.clear(); + self.lookup_type.clear(); + self.std_namespace = None; + let mut module = crate::Module::generate_empty(); let mut lexer = Lexer::new(source); let mut lookup_global_expression = FastHashMap::default(); @@ -921,7 +1092,7 @@ impl Parser { match self.parse_global_decl(&mut lexer, &mut module, &mut lookup_global_expression) { Err(error) => { let pos = source.len() - lexer.input.len(); - let (mut rows, mut cols) = (0, 0); + let (mut rows, mut cols) = (0, 1); for line in source[..pos].lines() { rows += 1; cols = line.len(); diff --git a/src/lib.rs b/src/lib.rs index dfaf89626..e63c92f07 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -110,16 +110,50 @@ pub struct GlobalVariable { pub ty: Handle, } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum UnaryOperator { + Negate, + Not, +} + +#[derive(Clone, Copy, Debug, PartialEq)] pub enum BinaryOperator { - Multiply, Add, - Equals, + Subtract, + Multiply, + Divide, + Modulo, + Equal, + NotEqual, + Less, + LessEqual, + Greater, + GreaterEqual, And, ExclusiveOr, InclusiveOr, LogicalAnd, LogicalOr, + ShiftLeftLogical, + ShiftRightLogical, + ShiftRightArithmetic, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum IntrinsicFunction { + Any, + All, + IsNan, + IsInf, + IsFinite, + IsNormal, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum DerivativeAxis { + X, + Y, + Width, } #[derive(Clone, Debug)] @@ -148,11 +182,26 @@ pub enum Expression { sampler: Handle, coordinate: Handle, }, + Unary { + op: UnaryOperator, + expr: Handle, + }, Binary { op: BinaryOperator, left: Handle, right: Handle, }, + Intrinsic { + fun: IntrinsicFunction, + argument: Handle, + }, + DotProduct(Handle, Handle), + CrossProduct(Handle, Handle), + Derivative { + axis: DerivativeAxis, + //modifier, + expr: Handle, + }, } pub type Block = Vec; From ee325a6a67438a2c49c711ec49c2f8afdf9d93d1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 12 Mar 2020 12:47:16 -0400 Subject: [PATCH 0048/2212] Add imported function calls --- src/front/wgsl.rs | 50 +++++++++++++++++++++++++++++++++++------------ src/lib.rs | 4 ++++ 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 158810d9b..a345d0772 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -19,6 +19,7 @@ impl<'a> Lexer<'a> { #[derive(Debug, PartialEq)] pub enum Token<'a> { Separator(char), + DoubleColon, Paren(char), DoubleParen(char), Number(&'a str), @@ -65,7 +66,16 @@ impl<'a> Lexer<'a> { None => return Token::End, }; let token = match cur { - ':' | ';' | ',' | '.' => { + ':' => { + self.input = chars.as_str(); + if chars.next() == Some(':') { + self.input = chars.as_str(); + Token::DoubleColon + } else { + Token::Separator(cur) + } + } + ';' | ',' | '.' => { self.input = chars.as_str(); Token::Separator(cur) } @@ -434,19 +444,35 @@ impl Parser { self.scopes.pop(); return Ok(*handle); } - *lexer = backup; - let ty = self.parse_type_decl(lexer, ctx.types)?; - Self::expect(lexer, Token::Paren('('))?; - let mut components = Vec::new(); - while lexer.peek() != Token::Paren(')') { - if !components.is_empty() { - Self::expect(lexer, Token::Separator(','))?; + if self.std_namespace.as_ref().map(|s| s.as_str()) == Some(word) { + Self::expect(lexer, Token::DoubleColon)?; + let name = Self::parse_ident(lexer)?; + let mut arguments = Vec::new(); + Self::expect(lexer, Token::Paren('('))?; + while lexer.peek() != Token::Paren(')') { + let arg = self.parse_general_expression(lexer, ctx.reborrow())?; + arguments.push(arg); } - let sub_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - components.push(sub_expr); + let _ = lexer.next(); + crate::Expression::Call { + name: name.to_owned(), + arguments, + } + } else { + *lexer = backup; + let ty = self.parse_type_decl(lexer, ctx.types)?; + Self::expect(lexer, Token::Paren('('))?; + let mut components = Vec::new(); + while lexer.peek() != Token::Paren(')') { + if !components.is_empty() { + Self::expect(lexer, Token::Separator(','))?; + } + let sub_expr = self.parse_general_expression(lexer, ctx.reborrow())?; + components.push(sub_expr); + } + let _ = lexer.next(); + crate::Expression::Compose { ty, components } } - let _ = lexer.next(); - crate::Expression::Compose { ty, components } } other => return Err(Error::Unexpected(other)), }; diff --git a/src/lib.rs b/src/lib.rs index e63c92f07..ee7a69787 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -202,6 +202,10 @@ pub enum Expression { //modifier, expr: Handle, }, + Call { + name: String, + arguments: Vec>, + }, } pub type Block = Vec; From cb72a92bce0b08449519f5c10d8e3c1519dc806f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 12 Mar 2020 14:08:22 -0400 Subject: [PATCH 0049/2212] [wgsl] improved decoration parsing --- src/front/wgsl.rs | 80 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 61 insertions(+), 19 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index a345d0772..fd61f73d1 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -197,9 +197,11 @@ pub enum Error<'a> { BadFloat(&'a str, std::num::ParseFloatError), UnknownImport(&'a str), UnknownStorageClass(&'a str), + UnknownDecoration(&'a str), UnknownBuiltin(&'a str), UnknownPipelineStage(&'a str), UnknownIdent(&'a str), + UnknownType(&'a str), UnknownFunction(&'a str), Other, } @@ -332,6 +334,8 @@ impl Parser { match word { "in" => Ok(spirv::StorageClass::Input), "out" => Ok(spirv::StorageClass::Output), + "uniform" => Ok(spirv::StorageClass::Uniform), + "storage_buffer" => Ok(spirv::StorageClass::StorageBuffer), _ => Err(Error::UnknownStorageClass(word)), } } @@ -340,6 +344,7 @@ impl Parser { match word { "position" => Ok(spirv::BuiltIn::Position), "vertex_idx" => Ok(spirv::BuiltIn::VertexId), + "global_invocation_id" => Ok(spirv::BuiltIn::GlobalInvocationId), _ => Err(Error::UnknownBuiltin(word)), } } @@ -450,6 +455,9 @@ impl Parser { let mut arguments = Vec::new(); Self::expect(lexer, Token::Paren('('))?; while lexer.peek() != Token::Paren(')') { + if !arguments.is_empty() { + Self::expect(lexer, Token::Separator(','))?; + } let arg = self.parse_general_expression(lexer, ctx.reborrow())?; arguments.push(arg); } @@ -557,14 +565,25 @@ impl Parser { _ => None, }; - self.scopes.pop(); - match expression { - Some(expr) => Ok(ctx.function.expressions.append(expr)), + let handle = match expression { + Some(expr) => ctx.function.expressions.append(expr), None => { *lexer = backup; - self.parse_primary_expression(lexer, ctx) + let mut handle = self.parse_primary_expression(lexer, ctx.reborrow())?; + while let Token::Separator('.') = lexer.peek() { + let _ = lexer.next(); + let _name = Self::parse_ident(lexer)?; + let expr = crate::Expression::AccessIndex { + base: handle, + index: 0, //TODO: compute from `name` + }; + handle = ctx.function.expressions.append(expr); + } + handle } - } + }; + self.scopes.pop(); + Ok(handle) } fn parse_equality_expression<'a>( @@ -722,6 +741,7 @@ impl Parser { Self::expect(lexer, Token::Paren('{'))?; loop { if let Token::DoubleParen('[') = lexer.peek() { + let _ = lexer.next(); self.scopes.push(Scope::Decoration); let mut ready = true; loop { @@ -859,6 +879,13 @@ impl Parser { let members = self.parse_struct_body(lexer, type_arena)?; crate::TypeInner::Struct { members } } + Token::Word(name) => { + self.scopes.pop(); + return self.lookup_type + .get(name) + .cloned() + .ok_or(Error::UnknownType(name)); + } other => return Err(Error::Unexpected(other)), }; self.scopes.pop(); @@ -937,7 +964,9 @@ impl Parser { let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; let value = if let Token::Operation('=') = lexer.peek() { let _ = lexer.next(); - Some(self.parse_general_expression(lexer, context)?) + let value = self.parse_general_expression(lexer, context)?; + lookup_ident.insert(name, value); + Some(value) } else { None }; @@ -991,30 +1020,43 @@ impl Parser { // read decorations let mut binding = None; if let Token::DoubleParen('[') = lexer.peek() { + let (mut bind_index, mut bind_set) = (None, None); self.scopes.push(Scope::Decoration); let _ = lexer.next(); - let mut ready = true; loop { + match Self::parse_ident(lexer)? { + "location" => { + let loc = Self::parse_uint_literal(lexer)?; + binding = Some(crate::Binding::Location(loc)); + } + "builtin" => { + let builtin = Self::get_built_in(Self::parse_ident(lexer)?)?; + binding = Some(crate::Binding::BuiltIn(builtin)); + } + "binding" => { + bind_index = Some(Self::parse_uint_literal(lexer)?); + } + "set" => { + bind_set = Some(Self::parse_uint_literal(lexer)?); + } + other => return Err(Error::UnknownDecoration(other)), + } match lexer.next() { Token::DoubleParen(']') => { break; } - Token::Separator(',') if !ready => { - ready = true; - } - Token::Word("location") if ready => { - let location = Self::parse_uint_literal(lexer)?; - binding = Some(crate::Binding::Location(location)); - ready = false; - } - Token::Word("builtin") if ready => { - let builtin = Self::get_built_in(Self::parse_ident(lexer)?)?; - binding = Some(crate::Binding::BuiltIn(builtin)); - ready = false; + Token::Separator(',') => { } other => return Err(Error::Unexpected(other)), } } + match (bind_set, bind_index) { + (Some(set), Some(index)) if binding.is_none() => { + binding = Some(crate::Binding::Descriptor { set, binding: index }); + } + _ if binding.is_none() => return Err(Error::Other), + _ => {} + } self.scopes.pop(); } // read items From 16f018046a159ae435ec8bacbe5c126615247480 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 13 Mar 2020 17:05:20 -0400 Subject: [PATCH 0050/2212] [wgsl] make lexer Error-aware --- src/front/wgsl.rs | 433 ++++++++++++++++++++++------------------------ 1 file changed, 209 insertions(+), 224 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index fd61f73d1..0b43a99d2 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -3,18 +3,6 @@ use crate::{ FastHashMap, }; -#[derive(Clone)] -struct Lexer<'a> { - input: &'a str, -} - -impl<'a> Lexer<'a> { - fn new(input: &'a str) -> Self { - Lexer { - input, - } - } -} #[derive(Debug, PartialEq)] pub enum Token<'a> { @@ -35,159 +23,119 @@ pub enum Token<'a> { End, } -impl<'a> Lexer<'a> { - fn _consume_str(&mut self, what: &str) -> bool { - if self.input.starts_with(what) { - self.input = &self.input[what.len() ..]; - true +mod lex { + use super::Token; + + fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { + if input.starts_with(what) { + Some(&input[what.len() ..]) } else { - false + None } } - fn consume_any(&mut self, what: impl Fn(char) -> bool) -> &'a str { - let pos = self.input.find(|c| !what(c)).unwrap_or(self.input.len()); - let (left, right) = self.input.split_at(pos); - debug_assert!(!left.is_empty(), "Leftover: '{}'...", &right[..10]); - self.input = right; - left + fn consume_any<'a>(input: &'a str, what: impl Fn(char) -> bool) -> (&'a str, &'a str) { + let pos = input.find(|c| !what(c)).unwrap_or(input.len()); + input.split_at(pos) } - fn skip_whitespace(&mut self) { - self.input = self.input.trim_start(); - } - - #[must_use] - fn next(&mut self) -> Token<'a> { - self.skip_whitespace(); - let mut chars = self.input.chars(); + pub fn consume_token<'a>(mut input: &'a str) -> (Token<'a>, &'a str) { + input = input.trim_start(); + let mut chars = input.chars(); let cur = match chars.next() { Some(c) => c, - None => return Token::End, + None => return (Token::End, input), }; - let token = match cur { + match cur { ':' => { - self.input = chars.as_str(); + input = chars.as_str(); if chars.next() == Some(':') { - self.input = chars.as_str(); - Token::DoubleColon + (Token::DoubleColon, chars.as_str()) } else { - Token::Separator(cur) + (Token::Separator(cur), input) } } ';' | ',' | '.' => { - self.input = chars.as_str(); - Token::Separator(cur) + (Token::Separator(cur), chars.as_str()) } '(' | ')' | '{' | '}' => { - self.input = chars.as_str(); - Token::Paren(cur) + (Token::Paren(cur), chars.as_str()) } '<' | '>' => { - self.input = chars.as_str(); - if chars.next() == Some('=') { - self.input = chars.as_str(); - Token::LogicalOperation(cur) - } else if chars.next() == Some(cur) { - self.input = chars.as_str(); + input = chars.as_str(); + let next = chars.next(); + if next == Some('=') { + (Token::LogicalOperation(cur), chars.as_str()) + } else if next == Some(cur) { + input = chars.as_str(); if chars.next() == Some(cur) { - self.input = chars.as_str(); - Token::ArithmeticShiftOperation(cur) + (Token::ArithmeticShiftOperation(cur), chars.as_str()) } else { - Token::ShiftOperation(cur) + (Token::ShiftOperation(cur), input) } } else { - Token::Paren(cur) + (Token::Paren(cur), input) } } '[' | ']' => { - self.input = chars.as_str(); + input = chars.as_str(); if chars.next() == Some(cur) { - self.input = chars.as_str(); - Token::DoubleParen(cur) + (Token::DoubleParen(cur), chars.as_str()) } else { - Token::Paren(cur) + (Token::Paren(cur), input) } } '0' ..= '9' => { - let number = self.consume_any(|c| (c>='0' && c<='9' || c=='.')); - Token::Number(number) + let (number, rest) = consume_any(input, |c| (c>='0' && c<='9' || c=='.')); + (Token::Number(number), rest) } 'a'..='z' | 'A'..='Z' | '_' => { - let word = self.consume_any(|c| c.is_alphanumeric() || c=='_'); - Token::Word(word) + let (word, rest) = consume_any(input, |c| c.is_alphanumeric() || c=='_'); + (Token::Word(word), rest) } '"' => { let base = chars.as_str(); let len = match chars.position(|c| c == '"') { Some(pos) => pos, - None => return Token::UnterminatedString, + None => return (Token::UnterminatedString, chars.as_str()) }; - self.input = chars.as_str(); - Token::String(&base[..len]) + (Token::String(&base[..len]), chars.as_str()) } '-' => { - self.input = chars.as_str(); + input = chars.as_str(); if chars.next() == Some('>') { - self.input = chars.as_str(); - Token::Arrow + (Token::Arrow, chars.as_str()) } else { - Token::Operation(cur) + (Token::Operation(cur), input) } } '+' | '*' | '/' | '%' | '^' => { - self.input = chars.as_str(); - Token::Operation(cur) + (Token::Operation(cur), chars.as_str()) } '!' => { if chars.next() == Some('=') { - self.input = chars.as_str(); - Token::LogicalOperation(cur) + (Token::LogicalOperation(cur), chars.as_str()) } else { - Token::Operation(cur) + (Token::Operation(cur), input) } } '=' | '&' | '|' => { - self.input = chars.as_str(); + input = chars.as_str(); if chars.next() == Some(cur) { - self.input = chars.as_str(); - Token::LogicalOperation(cur) + (Token::LogicalOperation(cur), chars.as_str()) } else { - Token::Operation(cur) + (Token::Operation(cur), input) } } '#' => { match chars.position(|c| c == '\n' || c == '\r') { - Some(_) => { - self.input = chars.as_str(); - self.next() - } - None => Token::End, + Some(_) => consume_token(chars.as_str()), + None => (Token::End, chars.as_str()) } } - _ => Token::Unknown(cur), - }; - token + _ => (Token::Unknown(cur), chars.as_str()) + } } - - #[must_use] - fn peek(&self) -> Token<'a> { - self.clone().next() - } -} - -#[derive(Clone, Debug, PartialEq)] -pub enum Scope { - Decoration, - ImportDecl, - VariableDecl, - TypeDecl, - FunctionDecl, - Statement, - ConstantExpr, - PrimaryExpr, - SingularExpr, - GeneralExpr, } #[derive(Debug)] @@ -206,6 +154,80 @@ pub enum Error<'a> { Other, } +#[derive(Clone)] +struct Lexer<'a> { + input: &'a str, +} + +impl<'a> Lexer<'a> { + fn new(input: &'a str) -> Self { + Lexer { + input, + } + } + + #[must_use] + fn next(&mut self) -> Token<'a> { + let (token, rest) = lex::consume_token(self.input); + self.input = rest; + token + } + + #[must_use] + fn peek(&mut self) -> Token<'a> { + self.clone().next() + } + + fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { + let token = self.next(); + if token == expected { + Ok(()) + } else { + Err(Error::Unexpected(token)) + } + } + + fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { + match self.next() { + Token::Word(word) => Ok(word), + other => Err(Error::Unexpected(other)), + } + } + + fn _next_float_literal(&mut self) -> Result> { + match self.next() { + Token::Number(word) => word.parse().map_err(|err| Error::BadFloat(word, err)), + other => Err(Error::Unexpected(other)), + } + } + + fn next_uint_literal(&mut self) -> Result> { + match self.next() { + Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), + other => Err(Error::Unexpected(other)), + } + } + + fn _next_sint_literal(&mut self) -> Result> { + match self.next() { + Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), + other => Err(Error::Unexpected(other)), + } + } + + fn next_scalar_generic(&mut self) -> Result<(crate::ScalarKind, u8), Error<'a>> { + self.expect(Token::Paren('<'))?; + let pair = match self.next() { + Token::Word("f32") => (crate::ScalarKind::Float, 32), + Token::Word("i32") => (crate::ScalarKind::Sint, 32), + Token::Word("u32") => (crate::ScalarKind::Uint, 32), + other => return Err(Error::Unexpected(other)), + }; + self.expect(Token::Paren('>'))?; + Ok(pair) + } +} + trait StringValueLookup<'a> { type Value; fn lookup(&self, key: &'a str) -> Result>; @@ -256,6 +278,21 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } + +#[derive(Clone, Debug, PartialEq)] +pub enum Scope { + Decoration, + ImportDecl, + VariableDecl, + TypeDecl, + FunctionDecl, + Statement, + ConstantExpr, + PrimaryExpr, + SingularExpr, + GeneralExpr, +} + #[derive(Debug)] pub struct ParseError<'a> { pub error: Error<'a>, @@ -278,58 +315,6 @@ impl Parser { } } - fn expect<'a>( - lexer: &mut Lexer<'a>, - expected: Token<'a>, - ) -> Result<(), Error<'a>> { - let token = lexer.next(); - if token == expected { - Ok(()) - } else { - Err(Error::Unexpected(token)) - } - } - - fn parse_ident<'a>(lexer: &mut Lexer<'a>) -> Result<&'a str, Error<'a>> { - match lexer.next() { - Token::Word(word) => Ok(word), - other => Err(Error::Unexpected(other)), - } - } - - fn _parse_float_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { - match lexer.next() { - Token::Number(word) => word.parse().map_err(|err| Error::BadFloat(word, err)), - other => Err(Error::Unexpected(other)), - } - } - - fn parse_uint_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { - match lexer.next() { - Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), - other => Err(Error::Unexpected(other)), - } - } - - fn _parse_sint_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { - match lexer.next() { - Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), - other => Err(Error::Unexpected(other)), - } - } - - fn parse_scalar_generic<'a>(lexer: &mut Lexer<'a>) -> Result<(crate::ScalarKind, u8), Error<'a>> { - Self::expect(lexer, Token::Paren('<'))?; - let pair = match lexer.next() { - Token::Word("f32") => (crate::ScalarKind::Float, 32), - Token::Word("i32") => (crate::ScalarKind::Sint, 32), - Token::Word("u32") => (crate::ScalarKind::Uint, 32), - other => return Err(Error::Unexpected(other)), - }; - Self::expect(lexer, Token::Paren('>'))?; - Ok(pair) - } - fn get_storage_class<'a>(word: &'a str) -> Result> { match word { "in" => Ok(spirv::StorageClass::Input), @@ -394,7 +379,7 @@ impl Parser { } _ => { let _ty = self.parse_type_decl(lexer, type_arena); - Self::expect(lexer, Token::Paren('('))?; + lexer.expect(Token::Paren('('))?; while lexer.peek() != Token::Paren(')') { let _ = self.parse_const_expression(lexer, type_arena, const_arena)?; } @@ -416,7 +401,7 @@ impl Parser { let expression = match lexer.next() { Token::Paren('(') => { let expr = self.parse_general_expression(lexer, ctx)?; - Self::expect(lexer, Token::Paren(')'))?; + lexer.expect(Token::Paren(')'))?; self.scopes.pop(); return Ok(expr); } @@ -450,13 +435,13 @@ impl Parser { return Ok(*handle); } if self.std_namespace.as_ref().map(|s| s.as_str()) == Some(word) { - Self::expect(lexer, Token::DoubleColon)?; - let name = Self::parse_ident(lexer)?; + lexer.expect(Token::DoubleColon)?; + let name = lexer.next_ident()?; let mut arguments = Vec::new(); - Self::expect(lexer, Token::Paren('('))?; + lexer.expect(Token::Paren('('))?; while lexer.peek() != Token::Paren(')') { if !arguments.is_empty() { - Self::expect(lexer, Token::Separator(','))?; + lexer.expect(Token::Separator(','))?; } let arg = self.parse_general_expression(lexer, ctx.reborrow())?; arguments.push(arg); @@ -469,11 +454,11 @@ impl Parser { } else { *lexer = backup; let ty = self.parse_type_decl(lexer, ctx.types)?; - Self::expect(lexer, Token::Paren('('))?; + lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while lexer.peek() != Token::Paren(')') { if !components.is_empty() { - Self::expect(lexer, Token::Separator(','))?; + lexer.expect(Token::Separator(','))?; } let sub_expr = self.parse_general_expression(lexer, ctx.reborrow())?; components.push(sub_expr); @@ -529,34 +514,34 @@ impl Parser { } Token::Word(word) => { if let Some(fun) = get_intrinsic(word) { - Self::expect(lexer, Token::Paren('('))?; + lexer.expect(Token::Paren('('))?; let argument = self.parse_primary_expression(lexer, ctx.reborrow())?; - Self::expect(lexer, Token::Paren(')'))?; + lexer.expect(Token::Paren(')'))?; Some(crate::Expression::Intrinsic { fun, argument, }) } else if let Some(axis) = get_derivative(word) { - Self::expect(lexer, Token::Paren('('))?; + lexer.expect(Token::Paren('('))?; let expr = self.parse_primary_expression(lexer, ctx.reborrow())?; - Self::expect(lexer, Token::Paren(')'))?; + lexer.expect(Token::Paren(')'))?; Some(crate::Expression::Derivative { axis, expr, }) } else if word == "dot" { - Self::expect(lexer, Token::Paren('('))?; + lexer.expect(Token::Paren('('))?; let a = self.parse_primary_expression(lexer, ctx.reborrow())?; - Self::expect(lexer, Token::Separator(','))?; + lexer.expect(Token::Separator(','))?; let b = self.parse_primary_expression(lexer, ctx.reborrow())?; - Self::expect(lexer, Token::Paren(')'))?; + lexer.expect(Token::Paren(')'))?; Some(crate::Expression::DotProduct(a, b)) } else if word == "outer_product" { - Self::expect(lexer, Token::Paren('('))?; + lexer.expect(Token::Paren('('))?; let a = self.parse_primary_expression(lexer, ctx.reborrow())?; - Self::expect(lexer, Token::Separator(','))?; + lexer.expect(Token::Separator(','))?; let b = self.parse_primary_expression(lexer, ctx.reborrow())?; - Self::expect(lexer, Token::Paren(')'))?; + lexer.expect(Token::Paren(')'))?; Some(crate::Expression::CrossProduct(a, b)) } else { None @@ -572,7 +557,7 @@ impl Parser { let mut handle = self.parse_primary_expression(lexer, ctx.reborrow())?; while let Token::Separator('.') = lexer.peek() { let _ = lexer.next(); - let _name = Self::parse_ident(lexer)?; + let _name = lexer.next_ident()?; let expr = crate::Expression::AccessIndex { base: handle, index: 0, //TODO: compute from `name` @@ -699,8 +684,8 @@ impl Parser { lexer: &mut Lexer<'a>, type_arena: &mut Arena, ) -> Result<(&'a str, Handle), Error<'a>> { - let name = Self::parse_ident(lexer)?; - Self::expect(lexer, Token::Separator(':'))?; + let name = lexer.next_ident()?; + lexer.expect(Token::Separator(':'))?; let ty = self.parse_type_decl(lexer, type_arena)?; Ok((name, ty)) } @@ -715,19 +700,19 @@ impl Parser { let mut class = None; if let Token::Paren('<') = lexer.peek() { let _ = lexer.next(); - let class_str = Self::parse_ident(lexer)?; + let class_str = lexer.next_ident()?; class = Some(Self::get_storage_class(class_str)?); - Self::expect(lexer, Token::Paren('>'))?; + lexer.expect(Token::Paren('>'))?; } - let name = Self::parse_ident(lexer)?; - Self::expect(lexer, Token::Separator(':'))?; + let name = lexer.next_ident()?; + lexer.expect(Token::Separator(':'))?; let ty = self.parse_type_decl(lexer, type_arena)?; if let Token::Operation('=') = lexer.peek() { let _ = lexer.next(); let _inner = self.parse_const_expression(lexer, type_arena, const_arena)?; //TODO } - Self::expect(lexer, Token::Separator(';'))?; + lexer.expect(Token::Separator(';'))?; self.scopes.pop(); Ok((name, class, ty)) } @@ -738,7 +723,7 @@ impl Parser { type_arena: &mut Arena, ) -> Result, Error<'a>> { let mut members = Vec::new(); - Self::expect(lexer, Token::Paren('{'))?; + lexer.expect(Token::Paren('{'))?; loop { if let Token::DoubleParen('[') = lexer.peek() { let _ = lexer.next(); @@ -753,7 +738,7 @@ impl Parser { ready = true; } Token::Word("offset") if ready => { - let _offset = Self::parse_uint_literal(lexer)?; //TODO + let _offset = lexer.next_uint_literal()?; //TODO ready = false; } other => return Err(Error::Unexpected(other)), @@ -766,9 +751,9 @@ impl Parser { Token::Paren('}') => return Ok(members), other => return Err(Error::Unexpected(other)), }; - Self::expect(lexer, Token::Separator(':'))?; + lexer.expect(Token::Separator(':'))?; let ty = self.parse_type_decl(lexer, type_arena)?; - Self::expect(lexer, Token::Separator(';'))?; + lexer.expect(Token::Separator(';'))?; members.push(crate::StructMember { name: Some(name.to_owned()), binding: None, @@ -803,7 +788,7 @@ impl Parser { } } Token::Word("vec2") => { - let (kind, width) = Self::parse_scalar_generic(lexer)?; + let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { size: crate::VectorSize::Bi, kind, @@ -811,7 +796,7 @@ impl Parser { } } Token::Word("vec3") => { - let (kind, width) = Self::parse_scalar_generic(lexer)?; + let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { size: crate::VectorSize::Tri, kind, @@ -819,7 +804,7 @@ impl Parser { } } Token::Word("vec4") => { - let (kind, width) = Self::parse_scalar_generic(lexer)?; + let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { size: crate::VectorSize::Quad, kind, @@ -827,7 +812,7 @@ impl Parser { } } Token::Word("mat2x2") => { - let (kind, width) = Self::parse_scalar_generic(lexer)?; + let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Bi, rows: crate::VectorSize::Bi, @@ -836,7 +821,7 @@ impl Parser { } } Token::Word("mat3x3") => { - let (kind, width) = Self::parse_scalar_generic(lexer)?; + let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Tri, rows: crate::VectorSize::Tri, @@ -845,7 +830,7 @@ impl Parser { } } Token::Word("mat4x4") => { - let (kind, width) = Self::parse_scalar_generic(lexer)?; + let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Quad, rows: crate::VectorSize::Quad, @@ -854,20 +839,20 @@ impl Parser { } } Token::Word("ptr") => { - Self::expect(lexer, Token::Paren('<'))?; - let class = Self::get_storage_class(Self::parse_ident(lexer)?)?; - Self::expect(lexer, Token::Separator(','))?; + lexer.expect(Token::Paren('<'))?; + let class = Self::get_storage_class(lexer.next_ident()?)?; + lexer.expect(Token::Separator(','))?; let base = self.parse_type_decl(lexer, type_arena)?; - Self::expect(lexer, Token::Paren('>'))?; + lexer.expect(Token::Paren('>'))?; crate::TypeInner::Pointer { base, class } } Token::Word("array") => { - Self::expect(lexer, Token::Paren('<'))?; + lexer.expect(Token::Paren('<'))?; let base = self.parse_type_decl(lexer, type_arena)?; let size = match lexer.next() { Token::Separator(',') => { - let value = Self::parse_uint_literal(lexer)?; - Self::expect(lexer, Token::Paren('>'))?; + let value = lexer.next_uint_literal()?; + lexer.expect(Token::Paren('>'))?; crate::ArraySize::Static(value) } Token::Separator('>') => crate::ArraySize::Dynamic, @@ -911,7 +896,7 @@ impl Parser { self.scopes.push(Scope::FunctionDecl); // read function name let mut lookup_ident = FastHashMap::default(); - let fun_name = Self::parse_ident(lexer)?; + let fun_name = lexer.next_ident()?; let mut fun = crate::Function { name: Some(fun_name.to_owned()), control: spirv::FunctionControl::empty(), @@ -926,10 +911,10 @@ impl Parser { lookup_ident.insert(name, expr_handle); } // read parameter list - Self::expect(lexer, Token::Paren('('))?; + lexer.expect(Token::Paren('('))?; while lexer.peek() != Token::Paren(')') { if !fun.parameter_types.is_empty() { - Self::expect(lexer, Token::Separator(','))?; + lexer.expect(Token::Separator(','))?; } let (param_name, param_type) = self.parse_variable_ident_decl(lexer, &mut module.types)?; let param_index = fun.parameter_types.len() as u32; @@ -939,14 +924,14 @@ impl Parser { } let _ = lexer.next(); // read return type - Self::expect(lexer, Token::Arrow)?; + lexer.expect(Token::Arrow)?; if let Token::Word("void") = lexer.peek() { let _ = lexer.next(); } else { fun.return_type = Some(self.parse_type_decl(lexer, &mut module.types)?); }; // read body - Self::expect(lexer, Token::Paren('{'))?; + lexer.expect(Token::Paren('{'))?; loop { let context = ExpressionContext { function: &mut fun, @@ -970,7 +955,7 @@ impl Parser { } else { None }; - Self::expect(lexer, Token::Separator(';'))?; + lexer.expect(Token::Separator(';'))?; crate::Statement::VariableDeclaration { name: name.to_owned(), ty, @@ -983,7 +968,7 @@ impl Parser { } else { None }; - Self::expect(lexer, Token::Separator(';'))?; + lexer.expect(Token::Separator(';'))?; crate::Statement::Return { value } @@ -991,9 +976,9 @@ impl Parser { ident => { // assignment let left = lookup_ident.lookup(ident)?; - Self::expect(lexer, Token::Operation('='))?; + lexer.expect(Token::Operation('='))?; let value = self.parse_general_expression(lexer, context)?; - Self::expect(lexer, Token::Separator(';'))?; + lexer.expect(Token::Separator(';'))?; crate::Statement::Store { pointer: left, value, @@ -1024,20 +1009,20 @@ impl Parser { self.scopes.push(Scope::Decoration); let _ = lexer.next(); loop { - match Self::parse_ident(lexer)? { + match lexer.next_ident()? { "location" => { - let loc = Self::parse_uint_literal(lexer)?; + let loc = lexer.next_uint_literal()?; binding = Some(crate::Binding::Location(loc)); } "builtin" => { - let builtin = Self::get_built_in(Self::parse_ident(lexer)?)?; + let builtin = Self::get_built_in(lexer.next_ident()?)?; binding = Some(crate::Binding::BuiltIn(builtin)); } "binding" => { - bind_index = Some(Self::parse_uint_literal(lexer)?); + bind_index = Some(lexer.next_uint_literal()?); } "set" => { - bind_set = Some(Self::parse_uint_literal(lexer)?); + bind_set = Some(lexer.next_uint_literal()?); } other => return Err(Error::UnknownDecoration(other)), } @@ -1068,9 +1053,9 @@ impl Parser { Token::String(path) => path, other => return Err(Error::Unexpected(other)), }; - Self::expect(lexer, Token::Word("as"))?; - let namespace = Self::parse_ident(lexer)?; - Self::expect(lexer, Token::Separator(';'))?; + lexer.expect(Token::Word("as"))?; + let namespace = lexer.next_ident()?; + lexer.expect(Token::Separator(';'))?; match path { "GLSL.std.450" => { self.std_namespace = Some(namespace.to_owned()) @@ -1080,17 +1065,17 @@ impl Parser { self.scopes.pop(); } Token::Word("type") => { - let name = Self::parse_ident(lexer)?; - Self::expect(lexer, Token::Operation('='))?; + let name = lexer.next_ident()?; + lexer.expect(Token::Operation('='))?; let ty = self.parse_type_decl(lexer, &mut module.types)?; self.lookup_type.insert(name.to_owned(), ty); - Self::expect(lexer, Token::Separator(';'))?; + lexer.expect(Token::Separator(';'))?; } Token::Word("const") => { let (name, _ty) = self.parse_variable_ident_decl(lexer, &mut module.types)?; - Self::expect(lexer, Token::Operation('='))?; + lexer.expect(Token::Operation('='))?; let inner = self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; - Self::expect(lexer, Token::Separator(';'))?; + lexer.expect(Token::Separator(';'))?; let const_handle = module.constants.append(crate::Constant { name: Some(name.to_owned()), specialization: None, @@ -1112,7 +1097,7 @@ impl Parser { self.parse_function_decl(lexer, module, &lookup_global_expression)?; } Token::Word("entry_point") => { - let exec_model = Self::get_execution_model(Self::parse_ident(lexer)?)?; + let exec_model = Self::get_execution_model(lexer.next_ident()?)?; let export_name = if let Token::Word("as") = lexer.peek() { let _ = lexer.next(); match lexer.next() { @@ -1122,9 +1107,9 @@ impl Parser { } else { None }; - Self::expect(lexer, Token::Operation('='))?; - let fun_ident = Self::parse_ident(lexer)?; - Self::expect(lexer, Token::Separator(';'))?; + lexer.expect(Token::Operation('='))?; + let fun_ident = lexer.next_ident()?; + lexer.expect(Token::Separator(';'))?; let function = module.functions .iter() .find(|(_, fun)| fun.name.as_ref().map(|s| s.as_str()) == Some(fun_ident)) From d6a4e05e053a7a8b3b24126aba8fd582b11d1788 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 13 Mar 2020 18:09:34 -0400 Subject: [PATCH 0051/2212] [wgsl] add parse_block, use for if statements --- src/front/wgsl.rs | 213 ++++++++++++++++++++++++++++------------------ src/lib.rs | 1 + 2 files changed, 130 insertions(+), 84 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 0b43a99d2..fe20f1fa3 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -242,8 +242,8 @@ impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle { - function: &'out mut crate::Function, - lookup_ident: &'temp FastHashMap<&'input str, Handle>, + lookup_ident: &'temp mut FastHashMap<&'input str, Handle>, + expressions: &'out mut Arena, types: &'out mut Arena, constants: &'out mut Arena, } @@ -251,8 +251,8 @@ struct ExpressionContext<'input,'temp, 'out> { impl<'a> ExpressionContext<'a, '_, '_> { fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { ExpressionContext { - function: self.function, lookup_ident: self.lookup_ident, + expressions: self.expressions, types: self.types, constants: self.constants, } @@ -272,7 +272,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { left, right: parser(lexer, self.reborrow())?, }; - left = self.function.expressions.append(expression); + left = self.expressions.append(expression); } Ok(left) } @@ -286,6 +286,7 @@ pub enum Scope { VariableDecl, TypeDecl, FunctionDecl, + Block, Statement, ConstantExpr, PrimaryExpr, @@ -470,7 +471,7 @@ impl Parser { other => return Err(Error::Unexpected(other)), }; self.scopes.pop(); - Ok(ctx.function.expressions.append(expression)) + Ok(ctx.expressions.append(expression)) } fn parse_singular_expression<'a>( @@ -551,7 +552,7 @@ impl Parser { }; let handle = match expression { - Some(expr) => ctx.function.expressions.append(expr), + Some(expr) => ctx.expressions.append(expr), None => { *lexer = backup; let mut handle = self.parse_primary_expression(lexer, ctx.reborrow())?; @@ -562,7 +563,7 @@ impl Parser { base: handle, index: 0, //TODO: compute from `name` }; - handle = ctx.function.expressions.append(expr); + handle = ctx.expressions.append(expr); } handle } @@ -887,6 +888,98 @@ impl Parser { })) } + fn parse_statement<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + match lexer.next() { + Token::Separator(';') => Ok(Some(crate::Statement::Empty)), + Token::Paren('}') => Ok(None), + Token::Word(word) => { + self.scopes.push(Scope::Statement); + let statement = match word { + "var" => { + let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; + let value = if let Token::Operation('=') = lexer.peek() { + let _ = lexer.next(); + let value = self.parse_general_expression(lexer, context.reborrow())?; + context.lookup_ident.insert(name, value); + Some(value) + } else { + None + }; + lexer.expect(Token::Separator(';'))?; + crate::Statement::VariableDeclaration { + name: name.to_owned(), + ty, + value, + } + } + "return" => { + let value = if lexer.peek() != Token::Separator(';') { + Some(self.parse_general_expression(lexer, context)?) + } else { + None + }; + lexer.expect(Token::Separator(';'))?; + crate::Statement::Return { + value + } + } + "if" => { + lexer.expect(Token::Paren('('))?; + let condition = self.parse_general_expression(lexer, context.reborrow())?; + lexer.expect(Token::Paren(')'))?; + let accept = self.parse_block(lexer, context.reborrow())?; + let reject = match lexer.peek() { + Token::Word("else") => { + let _ = lexer.next(); + self.parse_block(lexer, context.reborrow())? + } + _ => Vec::new(), + }; + let statement = crate::Statement::If { + condition, + accept, + reject, + }; + statement + } + ident => { + // assignment + let left = context.lookup_ident.lookup(ident)?; + lexer.expect(Token::Operation('='))?; + let value = self.parse_general_expression(lexer, context)?; + lexer.expect(Token::Separator(';'))?; + crate::Statement::Store { + pointer: left, + value, + } + } + }; + self.scopes.pop(); + Ok(Some(statement)) + } + other => Err(Error::Unexpected(other)), + } + } + + fn parse_block<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + self.scopes.push(Scope::Block); + lexer.expect(Token::Paren('{'))?; + let mut statements = Vec::new(); + while let Some(s) = self.parse_statement(lexer, context.reborrow())? { + statements.push(s); + } + self.scopes.pop(); + Ok(statements) + } + fn parse_function_decl<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -897,102 +990,54 @@ impl Parser { // read function name let mut lookup_ident = FastHashMap::default(); let fun_name = lexer.next_ident()?; - let mut fun = crate::Function { - name: Some(fun_name.to_owned()), - control: spirv::FunctionControl::empty(), - parameter_types: Vec::new(), - return_type: None, - expressions: Arena::new(), - body: Vec::new(), - }; // populare initial expressions + let mut expressions = Arena::new(); for (&name, expression) in lookup_global_expression.iter() { - let expr_handle = fun.expressions.append(expression.clone()); + let expr_handle = expressions.append(expression.clone()); lookup_ident.insert(name, expr_handle); } // read parameter list + let mut parameter_types = Vec::new(); lexer.expect(Token::Paren('('))?; while lexer.peek() != Token::Paren(')') { - if !fun.parameter_types.is_empty() { + if !parameter_types.is_empty() { lexer.expect(Token::Separator(','))?; } let (param_name, param_type) = self.parse_variable_ident_decl(lexer, &mut module.types)?; - let param_index = fun.parameter_types.len() as u32; - let expression_token = fun.expressions.append(crate::Expression::FunctionParameter(param_index)); + let param_index = parameter_types.len() as u32; + let expression_token = expressions.append(crate::Expression::FunctionParameter(param_index)); lookup_ident.insert(param_name, expression_token); - fun.parameter_types.push(param_type); + parameter_types.push(param_type); } let _ = lexer.next(); // read return type lexer.expect(Token::Arrow)?; - if let Token::Word("void") = lexer.peek() { - let _ = lexer.next(); - } else { - fun.return_type = Some(self.parse_type_decl(lexer, &mut module.types)?); - }; - // read body - lexer.expect(Token::Paren('{'))?; - loop { - let context = ExpressionContext { - function: &mut fun, - lookup_ident: &lookup_ident, - types: &mut module.types, - constants: &mut module.constants, - }; - match lexer.next() { - Token::Separator(';') => {}, - Token::Paren('}') => break, - Token::Word(word) => { - self.scopes.push(Scope::Statement); - let statement = match word { - "var" => { - let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; - let value = if let Token::Operation('=') = lexer.peek() { - let _ = lexer.next(); - let value = self.parse_general_expression(lexer, context)?; - lookup_ident.insert(name, value); - Some(value) - } else { - None - }; - lexer.expect(Token::Separator(';'))?; - crate::Statement::VariableDeclaration { - name: name.to_owned(), - ty, - value, - } - } - "return" => { - let value = if context.function.return_type.is_some() { - Some(self.parse_general_expression(lexer, context)?) - } else { - None - }; - lexer.expect(Token::Separator(';'))?; - crate::Statement::Return { - value - } - } - ident => { - // assignment - let left = lookup_ident.lookup(ident)?; - lexer.expect(Token::Operation('='))?; - let value = self.parse_general_expression(lexer, context)?; - lexer.expect(Token::Separator(';'))?; - crate::Statement::Store { - pointer: left, - value, - } - } - }; - self.scopes.pop(); - fun.body.push(statement); - } - other => return Err(Error::Unexpected(other)), + let return_type = match lexer.peek() { + Token::Word("void") => { + let _ = lexer.next(); + None + } + _ => { + Some(self.parse_type_decl(lexer, &mut module.types)?) } }; + // read body + let body = self.parse_block(lexer, ExpressionContext { + lookup_ident: &mut lookup_ident, + expressions: &mut expressions, + types: &mut module.types, + constants: &mut module.constants, + })?; // done self.scopes.pop(); + let fun = crate::Function { + name: Some(fun_name.to_owned()), + control: spirv::FunctionControl::empty(), + parameter_types, + return_type, + expressions, + body, + }; Ok(module.functions.append(fun)) } diff --git a/src/lib.rs b/src/lib.rs index ee7a69787..f8b237f91 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -214,6 +214,7 @@ pub struct FallThrough; #[derive(Debug)] pub enum Statement { + Empty, Block(Block), VariableDeclaration { name: String, From 607b77899bb51ce7c6235df43d69bd3c4978f8e9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 13 Mar 2020 18:18:58 -0400 Subject: [PATCH 0052/2212] [wgsl] add Lexer::skip() helper --- src/front/wgsl.rs | 65 +++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 36 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index fe20f1fa3..a809cc684 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -187,6 +187,16 @@ impl<'a> Lexer<'a> { } } + fn skip(&mut self, what: Token<'a>) -> bool { + let (token, rest) = lex::consume_token(self.input); + if token == what { + self.input = rest; + true + } else { + false + } + } + fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { match self.next() { Token::Word(word) => Ok(word), @@ -381,10 +391,9 @@ impl Parser { _ => { let _ty = self.parse_type_decl(lexer, type_arena); lexer.expect(Token::Paren('('))?; - while lexer.peek() != Token::Paren(')') { + while !lexer.skip(Token::Paren(')')) { let _ = self.parse_const_expression(lexer, type_arena, const_arena)?; } - let _ = lexer.next(); unimplemented!() } }; @@ -440,14 +449,13 @@ impl Parser { let name = lexer.next_ident()?; let mut arguments = Vec::new(); lexer.expect(Token::Paren('('))?; - while lexer.peek() != Token::Paren(')') { + while !lexer.skip(Token::Paren(')')) { if !arguments.is_empty() { lexer.expect(Token::Separator(','))?; } let arg = self.parse_general_expression(lexer, ctx.reborrow())?; arguments.push(arg); } - let _ = lexer.next(); crate::Expression::Call { name: name.to_owned(), arguments, @@ -457,14 +465,13 @@ impl Parser { let ty = self.parse_type_decl(lexer, ctx.types)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); - while lexer.peek() != Token::Paren(')') { + while !lexer.skip(Token::Paren(')')) { if !components.is_empty() { lexer.expect(Token::Separator(','))?; } let sub_expr = self.parse_general_expression(lexer, ctx.reborrow())?; components.push(sub_expr); } - let _ = lexer.next(); crate::Expression::Compose { ty, components } } } @@ -556,8 +563,7 @@ impl Parser { None => { *lexer = backup; let mut handle = self.parse_primary_expression(lexer, ctx.reborrow())?; - while let Token::Separator('.') = lexer.peek() { - let _ = lexer.next(); + while lexer.skip(Token::Separator('.')) { let _name = lexer.next_ident()?; let expr = crate::Expression::AccessIndex { base: handle, @@ -699,8 +705,7 @@ impl Parser { ) -> Result<(&'a str, Option, Handle), Error<'a>> { self.scopes.push(Scope::VariableDecl); let mut class = None; - if let Token::Paren('<') = lexer.peek() { - let _ = lexer.next(); + if lexer.skip(Token::Paren('<')) { let class_str = lexer.next_ident()?; class = Some(Self::get_storage_class(class_str)?); lexer.expect(Token::Paren('>'))?; @@ -708,8 +713,7 @@ impl Parser { let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; let ty = self.parse_type_decl(lexer, type_arena)?; - if let Token::Operation('=') = lexer.peek() { - let _ = lexer.next(); + if lexer.skip(Token::Operation('=')) { let _inner = self.parse_const_expression(lexer, type_arena, const_arena)?; //TODO } @@ -726,8 +730,7 @@ impl Parser { let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; loop { - if let Token::DoubleParen('[') = lexer.peek() { - let _ = lexer.next(); + if lexer.skip(Token::DoubleParen('[')) { self.scopes.push(Scope::Decoration); let mut ready = true; loop { @@ -901,8 +904,7 @@ impl Parser { let statement = match word { "var" => { let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; - let value = if let Token::Operation('=') = lexer.peek() { - let _ = lexer.next(); + let value = if lexer.skip(Token::Operation('=')) { let value = self.parse_general_expression(lexer, context.reborrow())?; context.lookup_ident.insert(name, value); Some(value) @@ -932,12 +934,10 @@ impl Parser { let condition = self.parse_general_expression(lexer, context.reborrow())?; lexer.expect(Token::Paren(')'))?; let accept = self.parse_block(lexer, context.reborrow())?; - let reject = match lexer.peek() { - Token::Word("else") => { - let _ = lexer.next(); - self.parse_block(lexer, context.reborrow())? - } - _ => Vec::new(), + let reject = if lexer.skip(Token::Word("else")) { + self.parse_block(lexer, context.reborrow())? + } else { + Vec::new() }; let statement = crate::Statement::If { condition, @@ -999,7 +999,7 @@ impl Parser { // read parameter list let mut parameter_types = Vec::new(); lexer.expect(Token::Paren('('))?; - while lexer.peek() != Token::Paren(')') { + while !lexer.skip(Token::Paren(')')) { if !parameter_types.is_empty() { lexer.expect(Token::Separator(','))?; } @@ -1009,17 +1009,12 @@ impl Parser { lookup_ident.insert(param_name, expression_token); parameter_types.push(param_type); } - let _ = lexer.next(); // read return type lexer.expect(Token::Arrow)?; - let return_type = match lexer.peek() { - Token::Word("void") => { - let _ = lexer.next(); - None - } - _ => { - Some(self.parse_type_decl(lexer, &mut module.types)?) - } + let return_type = if lexer.skip(Token::Word("void")) { + None + } else { + Some(self.parse_type_decl(lexer, &mut module.types)?) }; // read body let body = self.parse_block(lexer, ExpressionContext { @@ -1049,10 +1044,9 @@ impl Parser { ) -> Result> { // read decorations let mut binding = None; - if let Token::DoubleParen('[') = lexer.peek() { + if lexer.skip(Token::DoubleParen('[')) { let (mut bind_index, mut bind_set) = (None, None); self.scopes.push(Scope::Decoration); - let _ = lexer.next(); loop { match lexer.next_ident()? { "location" => { @@ -1143,8 +1137,7 @@ impl Parser { } Token::Word("entry_point") => { let exec_model = Self::get_execution_model(lexer.next_ident()?)?; - let export_name = if let Token::Word("as") = lexer.peek() { - let _ = lexer.next(); + let export_name = if lexer.skip(Token::Word("as")) { match lexer.next() { Token::String(name) => Some(name), other => return Err(Error::Unexpected(other)) From 76eb307d350e63073bd378e0d2d4fc7d2e5676f9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 14 Mar 2020 00:15:37 -0400 Subject: [PATCH 0053/2212] Local variables, [wgsl] statement context --- src/front/spirv.rs | 1 + src/front/wgsl.rs | 137 +++++++++++++++++++++++++++++++++++---------- src/lib.rs | 21 +++++-- 3 files changed, 125 insertions(+), 34 deletions(-) diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 4c922257a..8777f6f60 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -1269,6 +1269,7 @@ impl> Parser { } else { Some(self.lookup_type.lookup(result_type)?.handle) }, + local_variables: Arena::new(), expressions: self.make_expression_storage(), body: Vec::new(), } diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index a809cc684..e6113c076 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -251,8 +251,37 @@ impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle { +struct StatementContext<'input, 'temp, 'out> { lookup_ident: &'temp mut FastHashMap<&'input str, Handle>, + variables: &'out mut Arena, + expressions: &'out mut Arena, + types: &'out mut Arena, + constants: &'out mut Arena, +} + +impl<'a> StatementContext<'a, '_, '_> { + fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { + StatementContext { + lookup_ident: self.lookup_ident, + variables: self.variables, + expressions: self.expressions, + types: self.types, + constants: self.constants, + } + } + + fn as_expression(&mut self) -> ExpressionContext<'a, '_, '_> { + ExpressionContext { + lookup_ident: self.lookup_ident, + expressions: self.expressions, + types: self.types, + constants: self.constants, + } + } +} + +struct ExpressionContext<'input, 'temp, 'out> { + lookup_ident: &'temp FastHashMap<&'input str, Handle>, expressions: &'out mut Arena, types: &'out mut Arena, constants: &'out mut Arena, @@ -481,6 +510,38 @@ impl Parser { Ok(ctx.expressions.append(expression)) } + fn parse_postfix<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + mut handle: Handle, + ) -> Result, Error<'a>> { + loop { + match lexer.peek() { + Token::Separator('.') => { + let _ = lexer.next(); + let _name = lexer.next_ident()?; + let expr = crate::Expression::AccessIndex { + base: handle, + index: 0, //TODO: compute from `name` + }; + handle = ctx.expressions.append(expr); + } + Token::Paren('[') => { + let _ = lexer.next(); + let index = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(']'))?; + let expr = crate::Expression::Access { + base: handle, + index, + }; + handle = ctx.expressions.append(expr); + } + _ => return Ok(handle), + } + } + } + fn parse_singular_expression<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -562,16 +623,8 @@ impl Parser { Some(expr) => ctx.expressions.append(expr), None => { *lexer = backup; - let mut handle = self.parse_primary_expression(lexer, ctx.reborrow())?; - while lexer.skip(Token::Separator('.')) { - let _name = lexer.next_ident()?; - let expr = crate::Expression::AccessIndex { - base: handle, - index: 0, //TODO: compute from `name` - }; - handle = ctx.expressions.append(expr); - } - handle + let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; + self.parse_postfix(lexer, ctx, handle)? } }; self.scopes.pop(); @@ -894,7 +947,7 @@ impl Parser { fn parse_statement<'a>( &mut self, lexer: &mut Lexer<'a>, - mut context: ExpressionContext<'a, '_, '_>, + mut context: StatementContext<'a, '_, '_>, ) -> Result, Error<'a>> { match lexer.next() { Token::Separator(';') => Ok(Some(crate::Statement::Empty)), @@ -904,23 +957,24 @@ impl Parser { let statement = match word { "var" => { let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; - let value = if lexer.skip(Token::Operation('=')) { - let value = self.parse_general_expression(lexer, context.reborrow())?; - context.lookup_ident.insert(name, value); - Some(value) + let init = if lexer.skip(Token::Operation('=')) { + Some(self.parse_general_expression(lexer, context.as_expression())?) } else { None }; lexer.expect(Token::Separator(';'))?; - crate::Statement::VariableDeclaration { - name: name.to_owned(), + let var_id = context.variables.append(crate::LocalVariable { + name: Some(name.to_owned()), ty, - value, - } + init, + }); + let expr_id = context.expressions.append(crate::Expression::LocalVariable(var_id)); + context.lookup_ident.insert(name, expr_id); + crate::Statement::Empty } "return" => { let value = if lexer.peek() != Token::Separator(';') { - Some(self.parse_general_expression(lexer, context)?) + Some(self.parse_general_expression(lexer, context.as_expression())?) } else { None }; @@ -931,7 +985,7 @@ impl Parser { } "if" => { lexer.expect(Token::Paren('('))?; - let condition = self.parse_general_expression(lexer, context.reborrow())?; + let condition = self.parse_general_expression(lexer, context.as_expression())?; lexer.expect(Token::Paren(')'))?; let accept = self.parse_block(lexer, context.reborrow())?; let reject = if lexer.skip(Token::Word("else")) { @@ -939,18 +993,40 @@ impl Parser { } else { Vec::new() }; - let statement = crate::Statement::If { + crate::Statement::If { condition, accept, reject, - }; - statement + } } + "loop" => { + let mut body = Vec::new(); + let mut continuing = Vec::new(); + lexer.expect(Token::Paren('{'))?; + loop { + if lexer.skip(Token::Word("continuing")) { + continuing = self.parse_block(lexer, context.reborrow())?; + lexer.expect(Token::Paren('}'))?; + break; + } + match self.parse_statement(lexer, context.reborrow())? { + Some(s) => body.push(s), + None => break, + } + } + crate::Statement::Loop { + body, + continuing + } + } + "break" => crate::Statement::Break, + "continue" => crate::Statement::Continue, ident => { // assignment - let left = context.lookup_ident.lookup(ident)?; + let var_expr = context.lookup_ident.lookup(ident)?; + let left = self.parse_postfix(lexer, context.as_expression(), var_expr)?; lexer.expect(Token::Operation('='))?; - let value = self.parse_general_expression(lexer, context)?; + let value = self.parse_general_expression(lexer, context.as_expression())?; lexer.expect(Token::Separator(';'))?; crate::Statement::Store { pointer: left, @@ -968,7 +1044,7 @@ impl Parser { fn parse_block<'a>( &mut self, lexer: &mut Lexer<'a>, - mut context: ExpressionContext<'a, '_, '_>, + mut context: StatementContext<'a, '_, '_>, ) -> Result, Error<'a>> { self.scopes.push(Scope::Block); lexer.expect(Token::Paren('{'))?; @@ -1017,8 +1093,10 @@ impl Parser { Some(self.parse_type_decl(lexer, &mut module.types)?) }; // read body - let body = self.parse_block(lexer, ExpressionContext { + let mut local_variables = Arena::new(); + let body = self.parse_block(lexer, StatementContext { lookup_ident: &mut lookup_ident, + variables: &mut local_variables, expressions: &mut expressions, types: &mut module.types, constants: &mut module.constants, @@ -1030,6 +1108,7 @@ impl Parser { control: spirv::FunctionControl::empty(), parameter_types, return_type, + local_variables, expressions, body, }; diff --git a/src/lib.rs b/src/lib.rs index f8b237f91..59fc5e9e6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -110,6 +110,13 @@ pub struct GlobalVariable { pub ty: Handle, } +#[derive(Clone, Debug)] +pub struct LocalVariable { + pub name: Option, + pub ty: Handle, + pub init: Option>, +} + #[derive(Clone, Copy, Debug, PartialEq)] pub enum UnaryOperator { Negate, @@ -173,6 +180,7 @@ pub enum Expression { }, FunctionParameter(u32), GlobalVariable(Handle), + LocalVariable(Handle), Load { pointer: Handle, }, @@ -216,11 +224,6 @@ pub struct FallThrough; pub enum Statement { Empty, Block(Block), - VariableDeclaration { - name: String, - ty: Handle, - value: Option>, - }, If { condition: Handle, //bool accept: Block, @@ -231,6 +234,13 @@ pub enum Statement { cases: FastHashMap)>, default: Block, }, + Loop { + body: Block, + continuing: Block, + }, + //TODO: move terminator variations into a separate enum? + Break, + Continue, Return { value: Option>, }, @@ -247,6 +257,7 @@ pub struct Function { pub control: spirv::FunctionControl, pub parameter_types: Vec>, pub return_type: Option>, + pub local_variables: Arena, pub expressions: Arena, pub body: Block, } From 6ba942330abfa777daa92a8d83b56687a59c0898 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 14 Mar 2020 13:21:57 -0400 Subject: [PATCH 0054/2212] Typifier skeleton --- src/front/wgsl.rs | 31 +++++++++++++++++++++++++++-- src/lib.rs | 1 + src/proc/mod.rs | 3 +++ src/proc/typifier.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 src/proc/mod.rs create mode 100644 src/proc/typifier.rs diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index e6113c076..2e4e8dc0a 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,5 +1,6 @@ use crate::{ arena::{Arena, Handle}, + proc::Typifier, FastHashMap, }; @@ -143,6 +144,7 @@ pub enum Error<'a> { Unexpected(Token<'a>), BadInteger(&'a str, std::num::ParseIntError), BadFloat(&'a str, std::num::ParseFloatError), + BadAccessor(&'a str), UnknownImport(&'a str), UnknownStorageClass(&'a str), UnknownDecoration(&'a str), @@ -253,6 +255,7 @@ impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle { lookup_ident: &'temp mut FastHashMap<&'input str, Handle>, + typifier: &'temp mut Typifier, variables: &'out mut Arena, expressions: &'out mut Arena, types: &'out mut Arena, @@ -263,6 +266,7 @@ impl<'a> StatementContext<'a, '_, '_> { fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { StatementContext { lookup_ident: self.lookup_ident, + typifier: self.typifier, variables: self.variables, expressions: self.expressions, types: self.types, @@ -273,6 +277,7 @@ impl<'a> StatementContext<'a, '_, '_> { fn as_expression(&mut self) -> ExpressionContext<'a, '_, '_> { ExpressionContext { lookup_ident: self.lookup_ident, + typifier: self.typifier, expressions: self.expressions, types: self.types, constants: self.constants, @@ -282,6 +287,7 @@ impl<'a> StatementContext<'a, '_, '_> { struct ExpressionContext<'input, 'temp, 'out> { lookup_ident: &'temp FastHashMap<&'input str, Handle>, + typifier: &'temp mut Typifier, expressions: &'out mut Arena, types: &'out mut Arena, constants: &'out mut Arena, @@ -291,6 +297,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { ExpressionContext { lookup_ident: self.lookup_ident, + typifier: self.typifier, expressions: self.expressions, types: self.types, constants: self.constants, @@ -520,10 +527,28 @@ impl Parser { match lexer.peek() { Token::Separator('.') => { let _ = lexer.next(); - let _name = lexer.next_ident()?; + let name = lexer.next_ident()?; + let type_handle = ctx.typifier.resolve(handle, ctx.expressions); + let index = match ctx.types[type_handle].inner { + crate::TypeInner::Struct { ref members } => { + members + .iter() + .position(|m| m.name.as_ref().map(|s| s.as_str()) == Some(name)) + .ok_or(Error::BadAccessor(name))? as u32 + } + crate::TypeInner::Vector { size, .. } | + crate::TypeInner::Matrix { columns: size, .. } => { + const MEMBERS: [&'static str; 4] = ["x", "y", "z", "w"]; + MEMBERS[.. size as usize] + .iter() + .position(|&m| m == name) + .ok_or(Error::BadAccessor(name))? as u32 + } + _ => return Err(Error::BadAccessor(name)), + }; let expr = crate::Expression::AccessIndex { base: handle, - index: 0, //TODO: compute from `name` + index, }; handle = ctx.expressions.append(expr); } @@ -1094,8 +1119,10 @@ impl Parser { }; // read body let mut local_variables = Arena::new(); + let mut typifier = Typifier::new(); let body = self.parse_block(lexer, StatementContext { lookup_ident: &mut lookup_ident, + typifier: &mut typifier, variables: &mut local_variables, expressions: &mut expressions, types: &mut module.types, diff --git a/src/lib.rs b/src/lib.rs index 59fc5e9e6..c8c91926f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ mod arena; pub mod back; pub mod front; +pub mod proc; use crate::arena::{Arena, Handle}; diff --git a/src/proc/mod.rs b/src/proc/mod.rs new file mode 100644 index 000000000..396f41163 --- /dev/null +++ b/src/proc/mod.rs @@ -0,0 +1,3 @@ +mod typifier; + +pub use typifier::Typifier; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs new file mode 100644 index 000000000..9d0c09cdb --- /dev/null +++ b/src/proc/typifier.rs @@ -0,0 +1,47 @@ +use crate::arena::{Arena, Handle}; + +pub struct Typifier { + types: Vec>, +} + +impl Typifier { + pub fn new() -> Self { + Typifier { + types: Vec::new(), + } + } + + pub fn resolve( + &mut self, + expr_handle: Handle, + expressions: &Arena, + ) -> Handle { + if self.types.len() <= expr_handle.index() { + for (_, expr) in expressions.iter().skip(self.types.len()) { + self.types.push(match *expr { + crate::Expression::Access { base, .. } | + crate::Expression::AccessIndex { base, .. } => { + let _ = base; + unimplemented!() + } + crate::Expression::Constant(_) => unimplemented!(), + crate::Expression::Compose { ty, .. } => ty, + crate::Expression::FunctionParameter(_) => unimplemented!(), + crate::Expression::GlobalVariable(_) => unimplemented!(), + crate::Expression::LocalVariable(_) => unimplemented!(), + crate::Expression::Load { .. } => unimplemented!(), + crate::Expression::Mul(_, _) => unimplemented!(), + crate::Expression::ImageSample { .. } => unimplemented!(), + crate::Expression::Unary { .. } => unimplemented!(), + crate::Expression::Binary { .. } => unimplemented!(), + crate::Expression::Intrinsic { .. } => unimplemented!(), + crate::Expression::DotProduct(_, _) => unimplemented!(), + crate::Expression::CrossProduct(_, _) => unimplemented!(), + crate::Expression::Derivative { .. } => unimplemented!(), + crate::Expression::Call { .. } => unimplemented!(), + }); + }; + } + self.types[expr_handle.index()] + } +} From 3c5a12412ce3997d55e89d89a7aac24ebbfe3536 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 14 Mar 2020 16:23:16 -0400 Subject: [PATCH 0055/2212] Typifier lookups into constants, variables, and structs --- src/front/spirv.rs | 2 ++ src/front/wgsl.rs | 65 ++++++++++++++++++++++++++++++++++---------- src/lib.rs | 12 ++++++++ src/proc/typifier.rs | 26 +++++++++++++----- 4 files changed, 84 insertions(+), 21 deletions(-) diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 8777f6f60..4c6904ea6 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -1135,6 +1135,7 @@ impl> Parser { let type_id = self.next()?; let id = self.next()?; let type_lookup = self.lookup_type.lookup(type_id)?; + let ty = type_lookup.handle; let inner = match module.types[type_lookup.handle].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width } => { let low = self.next()?; @@ -1186,6 +1187,7 @@ impl> Parser { .and_then(|dec| dec.name), specialization: None, //TODO inner, + ty, }), type_id, }); diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 2e4e8dc0a..f394c5f89 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -260,6 +260,7 @@ struct StatementContext<'input, 'temp, 'out> { expressions: &'out mut Arena, types: &'out mut Arena, constants: &'out mut Arena, + global_vars: &'out Arena, } impl<'a> StatementContext<'a, '_, '_> { @@ -271,6 +272,7 @@ impl<'a> StatementContext<'a, '_, '_> { expressions: self.expressions, types: self.types, constants: self.constants, + global_vars: self.global_vars, } } @@ -281,6 +283,8 @@ impl<'a> StatementContext<'a, '_, '_> { expressions: self.expressions, types: self.types, constants: self.constants, + global_vars: self.global_vars, + local_vars: self.variables, } } } @@ -291,6 +295,8 @@ struct ExpressionContext<'input, 'temp, 'out> { expressions: &'out mut Arena, types: &'out mut Arena, constants: &'out mut Arena, + global_vars: &'out Arena, + local_vars: &'out Arena, } impl<'a> ExpressionContext<'a, '_, '_> { @@ -301,9 +307,15 @@ impl<'a> ExpressionContext<'a, '_, '_> { expressions: self.expressions, types: self.types, constants: self.constants, + global_vars: self.global_vars, + local_vars: self.local_vars, } } + fn resolve_type(&mut self, handle: Handle) -> Handle { + self.typifier.resolve(handle, self.expressions, self.types, self.constants, self.global_vars, self.local_vars) + } + fn parse_binary_op( &mut self, lexer: &mut Lexer<'a>, @@ -456,6 +468,13 @@ impl Parser { name: None, specialization: None, inner: crate::ConstantInner::Bool(true), + ty: Self::deduce_type_handle( + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: 1, + }, + ctx.types, + ) }); crate::Expression::Constant(handle) } @@ -464,14 +483,27 @@ impl Parser { name: None, specialization: None, inner: crate::ConstantInner::Bool(false), + ty: Self::deduce_type_handle( + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: 1, + }, + ctx.types, + ) }); crate::Expression::Constant(handle) } Token::Number(word) => { + let inner = Self::get_constant_inner(word)?; + let kind = inner.scalar_kind(); let handle = ctx.constants.append(crate::Constant { name: None, specialization: None, - inner: Self::get_constant_inner(word)?, + inner, + ty: Self::deduce_type_handle( + crate::TypeInner::Scalar { kind, width: 32 }, + ctx.types, + ) }); crate::Expression::Constant(handle) } @@ -528,7 +560,7 @@ impl Parser { Token::Separator('.') => { let _ = lexer.next(); let name = lexer.next_ident()?; - let type_handle = ctx.typifier.resolve(handle, ctx.expressions); + let type_handle = ctx.resolve_type(handle); let index = match ctx.types[type_handle].inner { crate::TypeInner::Struct { ref members } => { members @@ -844,6 +876,19 @@ impl Parser { } } + fn deduce_type_handle<'a>(inner: crate::TypeInner, arena: &mut Arena) -> Handle { + if let Some((token, _)) = arena + .iter() + .find(|(_, ty)| ty.inner == inner) + { + return token; + } + arena.append(crate::Type { + name: None, + inner, + }) + } + fn parse_type_decl<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -956,17 +1001,7 @@ impl Parser { other => return Err(Error::Unexpected(other)), }; self.scopes.pop(); - - if let Some((token, _)) = type_arena - .iter() - .find(|(_, ty)| ty.inner == inner) - { - return Ok(token); - } - Ok(type_arena.append(crate::Type { - name: None, - inner, - })) + Ok(Self::deduce_type_handle(inner, type_arena)) } fn parse_statement<'a>( @@ -1127,6 +1162,7 @@ impl Parser { expressions: &mut expressions, types: &mut module.types, constants: &mut module.constants, + global_vars: &module.global_variables, })?; // done self.scopes.pop(); @@ -1217,7 +1253,7 @@ impl Parser { lexer.expect(Token::Separator(';'))?; } Token::Word("const") => { - let (name, _ty) = self.parse_variable_ident_decl(lexer, &mut module.types)?; + let (name, ty) = self.parse_variable_ident_decl(lexer, &mut module.types)?; lexer.expect(Token::Operation('='))?; let inner = self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; lexer.expect(Token::Separator(';'))?; @@ -1225,6 +1261,7 @@ impl Parser { name: Some(name.to_owned()), specialization: None, inner, + ty, }); lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); } diff --git a/src/lib.rs b/src/lib.rs index c8c91926f..82b78745f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -86,6 +86,7 @@ pub struct Constant { pub name: Option, pub specialization: Option, pub inner: ConstantInner, + pub ty: Handle, } #[derive(Debug)] @@ -96,6 +97,17 @@ pub enum ConstantInner { Bool(bool), } +impl ConstantInner { + pub fn scalar_kind(&self) -> ScalarKind { + match *self { + ConstantInner::Sint(_) => ScalarKind::Sint, + ConstantInner::Uint(_) => ScalarKind::Uint, + ConstantInner::Float(_) => ScalarKind::Float, + ConstantInner::Bool(_) => ScalarKind::Bool, + } + } +} + #[derive(Clone, Debug, PartialEq)] pub enum Binding { BuiltIn(spirv::BuiltIn), diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 9d0c09cdb..0c0c2ccc2 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -15,20 +15,32 @@ impl Typifier { &mut self, expr_handle: Handle, expressions: &Arena, + types: &Arena, + constants: &Arena, + global_vars: &Arena, + local_vars: &Arena, ) -> Handle { if self.types.len() <= expr_handle.index() { for (_, expr) in expressions.iter().skip(self.types.len()) { self.types.push(match *expr { - crate::Expression::Access { base, .. } | - crate::Expression::AccessIndex { base, .. } => { - let _ = base; - unimplemented!() + crate::Expression::Access { base, .. } => { + match types[self.types[base.index()]].inner { + crate::TypeInner::Array { base, .. } => self.types[base.index()], + ref other => panic!("Can't access into {:?}", other), + } } - crate::Expression::Constant(_) => unimplemented!(), + crate::Expression::AccessIndex { base, index } => { + match types[self.types[base.index()]].inner { + crate::TypeInner::Array { base, .. } => self.types[base.index()], + crate::TypeInner::Struct { ref members } => members[index as usize].ty, + ref other => panic!("Can't access into {:?}", other), + } + } + crate::Expression::Constant(h) => constants[h].ty, crate::Expression::Compose { ty, .. } => ty, crate::Expression::FunctionParameter(_) => unimplemented!(), - crate::Expression::GlobalVariable(_) => unimplemented!(), - crate::Expression::LocalVariable(_) => unimplemented!(), + crate::Expression::GlobalVariable(h) => global_vars[h].ty, + crate::Expression::LocalVariable(h) => local_vars[h].ty, crate::Expression::Load { .. } => unimplemented!(), crate::Expression::Mul(_, _) => unimplemented!(), crate::Expression::ImageSample { .. } => unimplemented!(), From a768af6011d61312e9bac94c9f63d7271678a0b7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 14 Mar 2020 18:23:31 -0400 Subject: [PATCH 0056/2212] Implement a fair bit of typifier logic, resolve access ids in WGSL --- src/front/wgsl.rs | 97 +++++++++++++++++++++------------- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 121 ++++++++++++++++++++++++++++++++++++++----- 3 files changed, 171 insertions(+), 49 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index f394c5f89..77b58e3f5 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,6 +1,6 @@ use crate::{ arena::{Arena, Handle}, - proc::Typifier, + proc::{Typifier, ResolveError}, FastHashMap, }; @@ -145,6 +145,7 @@ pub enum Error<'a> { BadInteger(&'a str, std::num::ParseIntError), BadFloat(&'a str, std::num::ParseFloatError), BadAccessor(&'a str), + InvalidResolve(ResolveError), UnknownImport(&'a str), UnknownStorageClass(&'a str), UnknownDecoration(&'a str), @@ -312,8 +313,10 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } - fn resolve_type(&mut self, handle: Handle) -> Handle { - self.typifier.resolve(handle, self.expressions, self.types, self.constants, self.global_vars, self.local_vars) + fn resolve_type(&mut self, handle: Handle) -> Result, Error<'a>> { + self.typifier + .resolve(handle, self.expressions, self.types, self.constants, self.global_vars, self.local_vars) + .map_err(Error::InvalidResolve) } fn parse_binary_op( @@ -468,7 +471,7 @@ impl Parser { name: None, specialization: None, inner: crate::ConstantInner::Bool(true), - ty: Self::deduce_type_handle( + ty: Typifier::deduce_type_handle( crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1, @@ -483,7 +486,7 @@ impl Parser { name: None, specialization: None, inner: crate::ConstantInner::Bool(false), - ty: Self::deduce_type_handle( + ty: Typifier::deduce_type_handle( crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1, @@ -500,7 +503,7 @@ impl Parser { name: None, specialization: None, inner, - ty: Self::deduce_type_handle( + ty: Typifier::deduce_type_handle( crate::TypeInner::Scalar { kind, width: 32 }, ctx.types, ) @@ -560,29 +563,64 @@ impl Parser { Token::Separator('.') => { let _ = lexer.next(); let name = lexer.next_ident()?; - let type_handle = ctx.resolve_type(handle); - let index = match ctx.types[type_handle].inner { + let type_handle = ctx.resolve_type(handle)?; + let base_type = &ctx.types[type_handle]; + let expression = match base_type.inner { crate::TypeInner::Struct { ref members } => { - members + let index = members .iter() .position(|m| m.name.as_ref().map(|s| s.as_str()) == Some(name)) - .ok_or(Error::BadAccessor(name))? as u32 + .ok_or(Error::BadAccessor(name))? as u32; + crate::Expression::AccessIndex { + base: handle, + index, + } } - crate::TypeInner::Vector { size, .. } | - crate::TypeInner::Matrix { columns: size, .. } => { - const MEMBERS: [&'static str; 4] = ["x", "y", "z", "w"]; - MEMBERS[.. size as usize] - .iter() - .position(|&m| m == name) - .ok_or(Error::BadAccessor(name))? as u32 + crate::TypeInner::Vector { size, kind, width } | + crate::TypeInner::Matrix { columns: size, kind, width, .. } => { + const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; + if name.len() > 1 { + let mut components = Vec::with_capacity(name.len()); + for ch in name.chars() { + let expr = crate::Expression::AccessIndex { + base: handle, + index: MEMBERS[.. size as usize] + .iter() + .position(|&m| m == ch) + .ok_or(Error::BadAccessor(name))? as u32, + }; + components.push(ctx.expressions.append(expr)); + } + let size = match name.len() { + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + 4 => crate::VectorSize::Quad, + _ => return Err(Error::BadAccessor(name)), + }; + let inner = if let crate::TypeInner::Matrix { rows, .. } = base_type.inner { + crate::TypeInner::Matrix { columns: size, rows, kind, width } + } else { + crate::TypeInner::Vector { size, kind, width } + }; + crate::Expression::Compose { + ty: Typifier::deduce_type_handle(inner, ctx.types), + components, + } + } else { + let ch = name.chars().next().unwrap(); + let index = MEMBERS[.. size as usize] + .iter() + .position(|&m| m == ch) + .ok_or(Error::BadAccessor(name))? as u32; + crate::Expression::AccessIndex { + base: handle, + index, + } + } } _ => return Err(Error::BadAccessor(name)), }; - let expr = crate::Expression::AccessIndex { - base: handle, - index, - }; - handle = ctx.expressions.append(expr); + handle = ctx.expressions.append(expression); } Token::Paren('[') => { let _ = lexer.next(); @@ -876,19 +914,6 @@ impl Parser { } } - fn deduce_type_handle<'a>(inner: crate::TypeInner, arena: &mut Arena) -> Handle { - if let Some((token, _)) = arena - .iter() - .find(|(_, ty)| ty.inner == inner) - { - return token; - } - arena.append(crate::Type { - name: None, - inner, - }) - } - fn parse_type_decl<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -1001,7 +1026,7 @@ impl Parser { other => return Err(Error::Unexpected(other)), }; self.scopes.pop(); - Ok(Self::deduce_type_handle(inner, type_arena)) + Ok(Typifier::deduce_type_handle(inner, type_arena)) } fn parse_statement<'a>( diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 396f41163..38ac9304b 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,3 +1,3 @@ mod typifier; -pub use typifier::Typifier; +pub use typifier::{ResolveError, Typifier}; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 0c0c2ccc2..a1f08e79c 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -4,6 +4,11 @@ pub struct Typifier { types: Vec>, } +#[derive(Debug)] +pub enum ResolveError { + InvalidAccessIndex, +} + impl Typifier { pub fn new() -> Self { Typifier { @@ -15,24 +20,42 @@ impl Typifier { &mut self, expr_handle: Handle, expressions: &Arena, - types: &Arena, + types: &mut Arena, constants: &Arena, global_vars: &Arena, local_vars: &Arena, - ) -> Handle { + ) -> Result, ResolveError> { if self.types.len() <= expr_handle.index() { - for (_, expr) in expressions.iter().skip(self.types.len()) { - self.types.push(match *expr { + for (eh, expr) in expressions.iter().skip(self.types.len()) { + let ty = match *expr { crate::Expression::Access { base, .. } => { match types[self.types[base.index()]].inner { - crate::TypeInner::Array { base, .. } => self.types[base.index()], + crate::TypeInner::Array { base, .. } => base, ref other => panic!("Can't access into {:?}", other), } } crate::Expression::AccessIndex { base, index } => { match types[self.types[base.index()]].inner { - crate::TypeInner::Array { base, .. } => self.types[base.index()], - crate::TypeInner::Struct { ref members } => members[index as usize].ty, + crate::TypeInner::Vector { size, kind, width } => { + if index >= size as u32 { + return Err(ResolveError::InvalidAccessIndex) + } + let inner = crate::TypeInner::Scalar { kind, width }; + Self::deduce_type_handle(inner, types) + } + crate::TypeInner::Matrix { columns, rows, kind, width } => { + if index >= columns as u32 { + return Err(ResolveError::InvalidAccessIndex) + } + let inner = crate::TypeInner::Vector { size: rows, kind, width }; + Self::deduce_type_handle(inner, types) + } + crate::TypeInner::Array { base, .. } => base, + crate::TypeInner::Struct { ref members } => { + members.get(index as usize) + .ok_or(ResolveError::InvalidAccessIndex)? + .ty + } ref other => panic!("Can't access into {:?}", other), } } @@ -44,16 +67,90 @@ impl Typifier { crate::Expression::Load { .. } => unimplemented!(), crate::Expression::Mul(_, _) => unimplemented!(), crate::Expression::ImageSample { .. } => unimplemented!(), - crate::Expression::Unary { .. } => unimplemented!(), - crate::Expression::Binary { .. } => unimplemented!(), + crate::Expression::Unary { expr, .. } => self.types[expr.index()], + crate::Expression::Binary { op, left, right } => { + match op { + crate::BinaryOperator::Add | + crate::BinaryOperator::Subtract | + crate::BinaryOperator::Divide | + crate::BinaryOperator::Modulo => { + self.types[left.index()] + } + crate::BinaryOperator::Multiply => { + let ty_left = self.types[left.index()]; + let ty_right = self.types[right.index()]; + if ty_left == ty_right { + ty_left + } else if let crate::TypeInner::Scalar { .. } = types[ty_right].inner { + ty_left + } else if let crate::TypeInner::Matrix { columns, kind, width, .. } = types[ty_left].inner { + let inner = crate::TypeInner::Vector { size: columns, kind, width}; + Self::deduce_type_handle(inner, types) + } else { + panic!("Incompatible arguments {:?} x {:?}", types[ty_left], types[ty_right]); + } + } + crate::BinaryOperator::Equal | + crate::BinaryOperator::NotEqual | + crate::BinaryOperator::Less | + crate::BinaryOperator::LessEqual | + crate::BinaryOperator::Greater | + crate::BinaryOperator::GreaterEqual | + crate::BinaryOperator::LogicalAnd | + crate::BinaryOperator::LogicalOr => { + self.types[left.index()] + } + crate::BinaryOperator::And | + crate::BinaryOperator::ExclusiveOr | + crate::BinaryOperator::InclusiveOr | + crate::BinaryOperator::ShiftLeftLogical | + crate::BinaryOperator::ShiftRightLogical | + crate::BinaryOperator::ShiftRightArithmetic => { + self.types[left.index()] + } + } + } crate::Expression::Intrinsic { .. } => unimplemented!(), crate::Expression::DotProduct(_, _) => unimplemented!(), crate::Expression::CrossProduct(_, _) => unimplemented!(), crate::Expression::Derivative { .. } => unimplemented!(), - crate::Expression::Call { .. } => unimplemented!(), - }); + crate::Expression::Call { ref name, ref arguments } => { + match name.as_str() { + "distance" | "length" => { + let ty_handle = self.types[arguments[0].index()]; + let inner = match types[ty_handle].inner { + crate::TypeInner::Vector { kind, width, .. } => { + crate::TypeInner::Scalar { kind, width } + } + ref other => panic!("Unexpected argument {:?}", other), + }; + Self::deduce_type_handle(inner, types) + } + "normalize" | "fclamp" => self.types[arguments[0].index()], + _ => panic!("Unknown '{}' call", name), + } + } + }; + log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, ty); + self.types.push(ty); }; } - self.types[expr_handle.index()] + Ok(self.types[expr_handle.index()]) + } + + pub fn deduce_type_handle( + inner: crate::TypeInner, + arena: &mut Arena, + ) -> Handle { + if let Some((token, _)) = arena + .iter() + .find(|(_, ty)| ty.inner == inner) + { + return token; + } + arena.append(crate::Type { + name: None, + inner, + }) } } From 1957b09c4dcd3f04766b57e0afec7425a4aee411 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 15 Mar 2020 11:39:45 -0400 Subject: [PATCH 0057/2212] Add WGSL parsing tests --- tests/convert.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 tests/convert.rs diff --git a/tests/convert.rs b/tests/convert.rs new file mode 100644 index 000000000..6e18ae764 --- /dev/null +++ b/tests/convert.rs @@ -0,0 +1,15 @@ +fn convert_wgsl(name: &str) { + let path = format!("{}/test-data/{}.wgsl", env!("CARGO_MANIFEST_DIR"), name); + let input = std::fs::read_to_string(path).unwrap(); + let _module = naga::front::wgsl::parse_str(&input).unwrap(); +} + +#[test] +fn convert_quad() { + convert_wgsl("quad"); +} + +#[test] +fn convert_boids() { + convert_wgsl("boids"); +} From 4a72abb14276cc5003e4dff7fc4a823abfa60e06 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 15 Mar 2020 11:55:01 -0400 Subject: [PATCH 0058/2212] Remove Mul expression type --- src/back/msl.rs | 11 +++++++++-- src/front/spirv.rs | 12 ++++++++++-- src/lib.rs | 1 - src/proc/typifier.rs | 1 - 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 4152245b6..a5460c7b3 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -420,10 +420,17 @@ impl Writer { ref other => panic!("Unexpected load pointer {:?}", other), } } - crate::Expression::Mul(left, right) => { + crate::Expression::Binary { op, left, right } => { + let op_ch = match op { + crate::BinaryOperator::Add => '+', + crate::BinaryOperator::Multiply => '*', + crate::BinaryOperator::Divide => '/', + crate::BinaryOperator::Modulo => '%', + _ => panic!("Unsupported binary op {:?}", op), + }; write!(self.out, "(")?; let ty_left = self.put_expression(left, expressions, module)?; - write!(self.out, " * ")?; + write!(self.out, " {} ", op_ch)?; let ty_right = self.put_expression(right, expressions, module)?; write!(self.out, ")")?; Ok(match (ty_left.borrow(), ty_right.borrow()) { diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 4c6904ea6..a0b9d4d4b 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -577,7 +577,11 @@ impl> Parser { crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width } if width == res_width => (), _ => return Err(Error::UnsupportedType(scalar_type_lookup.handle)), }; - let expr = crate::Expression::Mul(vector_lexp.handle, scalar_lexp.handle); + let expr = crate::Expression::Binary { + op: crate::BinaryOperator::Multiply, + left: vector_lexp.handle, + right: scalar_lexp.handle, + }; self.lookup_expression.insert(result_id, LookupExpression { handle: fun.expressions.append(expr), type_id: result_type_id, @@ -606,7 +610,11 @@ impl> Parser { crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } if size == columns && width == res_width => (), _ => return Err(Error::UnsupportedType(vector_type_lookup.handle)), }; - let expr = crate::Expression::Mul(matrix_lexp.handle, vector_lexp.handle); + let expr = crate::Expression::Binary { + op: crate::BinaryOperator::Multiply, + left: matrix_lexp.handle, + right: vector_lexp.handle, + }; self.lookup_expression.insert(result_id, LookupExpression { handle: fun.expressions.append(expr), type_id: result_type_id, diff --git a/src/lib.rs b/src/lib.rs index 82b78745f..ada612473 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -197,7 +197,6 @@ pub enum Expression { Load { pointer: Handle, }, - Mul(Handle, Handle), ImageSample { image: Handle, sampler: Handle, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index a1f08e79c..700a6b32f 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -65,7 +65,6 @@ impl Typifier { crate::Expression::GlobalVariable(h) => global_vars[h].ty, crate::Expression::LocalVariable(h) => local_vars[h].ty, crate::Expression::Load { .. } => unimplemented!(), - crate::Expression::Mul(_, _) => unimplemented!(), crate::Expression::ImageSample { .. } => unimplemented!(), crate::Expression::Unary { expr, .. } => self.types[expr.index()], crate::Expression::Binary { op, left, right } => { From c467693253d12a7c4fc4d638e56ebbac4ce4829b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 15 Mar 2020 12:00:50 -0400 Subject: [PATCH 0059/2212] Add quad -> MSL testing --- src/back/msl.rs | 3 ++- tests/convert.rs | 24 ++++++++++++++++++++---- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index a5460c7b3..58b927861 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -321,7 +321,7 @@ impl Writer { module: &'a crate::Module, ) -> Result, Error> { let expression = &expressions[expr_handle]; - log::trace!("expression {:?}", expression); + log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { crate::Expression::AccessIndex { base, index } => { match *self.put_expression(base, expressions, module)?.borrow() { @@ -434,6 +434,7 @@ impl Writer { let ty_right = self.put_expression(right, expressions, module)?; write!(self.out, ")")?; Ok(match (ty_left.borrow(), ty_right.borrow()) { + (&crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, kind, width }) | (&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Scalar { .. }) => MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), other => panic!("Unable to infer Mul for {:?}", other), diff --git a/tests/convert.rs b/tests/convert.rs index 6e18ae764..d8c7feba7 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -1,15 +1,31 @@ -fn convert_wgsl(name: &str) { +fn load_wgsl(name: &str) -> naga::Module { let path = format!("{}/test-data/{}.wgsl", env!("CARGO_MANIFEST_DIR"), name); let input = std::fs::read_to_string(path).unwrap(); - let _module = naga::front::wgsl::parse_str(&input).unwrap(); + naga::front::wgsl::parse_str(&input).unwrap() } #[test] fn convert_quad() { - convert_wgsl("quad"); + let module = load_wgsl("quad"); + { + use naga::back::msl; + let mut binding_map = msl::BindingMap::default(); + binding_map.insert( + msl::BindSource { set: 0, binding: 0 }, + msl::BindTarget { buffer: None, texture: Some(1), sampler: None }, + ); + binding_map.insert( + msl::BindSource { set: 0, binding: 1 }, + msl::BindTarget { buffer: None, texture: None, sampler: Some(1) }, + ); + let options = msl::Options { + binding_map: &binding_map, + }; + msl::write_string(&module, options).unwrap(); + } } #[test] fn convert_boids() { - convert_wgsl("boids"); + let _module = load_wgsl("boids"); } From 1ac92cd942edd1ef2f7604008b735f51dc5d5b1f Mon Sep 17 00:00:00 2001 From: AIOOB Date: Sun, 15 Mar 2020 00:30:09 +0000 Subject: [PATCH 0060/2212] Fixup clippy lints and remove unsafe --- Cargo.toml | 1 + examples/convert.rs | 1 - src/arena.rs | 34 +- src/back/msl.rs | 25 +- src/front/spirv.rs | 1395 +++++++++++++++++++++++-------------------- src/front/wgsl.rs | 18 +- src/lib.rs | 2 + 7 files changed, 788 insertions(+), 688 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ff430bd3e..382075918 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ license = "MPL-2.0" bitflags = "1" fxhash = "0.2" log = "0.4" +num-traits = "0.2" spirv = { package = "spirv_headers", version = "1" } [dev-dependencies] diff --git a/examples/convert.rs b/examples/convert.rs index 35cc954e5..aa266e889 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -20,7 +20,6 @@ fn main() { if args.len() <= 2 { println!("{:#?}", module); - return } else if args[2].ends_with(".metal") { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); diff --git a/src/arena.rs b/src/arena.rs index 0ccf0fae6..a6e436425 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -58,7 +58,7 @@ impl Handle { } } - pub fn index(&self) -> usize { + pub fn index(self) -> usize { self.index as usize } } @@ -71,6 +71,12 @@ pub struct Arena { data: Vec, } +impl Default for Arena { + fn default() -> Self { + Self::new() + } +} + impl Arena { pub fn new() -> Self { Arena { @@ -78,7 +84,7 @@ impl Arena { } } - pub fn iter<'a>(&'a self) -> impl Iterator, &'a T)> { + pub fn iter(&self) -> impl Iterator, &T)> { self.data .iter() .enumerate() @@ -119,36 +125,36 @@ mod tests { #[test] fn append_non_unique() { - let mut arena: Arena = Arena::new(); - let t1 = arena.append(0.0); - let t2 = arena.append(0.0); + let mut arena: Arena = Arena::new(); + let t1 = arena.append(0); + let t2 = arena.append(0); assert!(t1 != t2); assert!(arena[t1] == arena[t2]); } #[test] fn append_unique() { - let mut arena: Arena = Arena::new(); - let t1 = arena.append(std::f64::NAN); - let t2 = arena.append(std::f64::NAN); + let mut arena: Arena = Arena::new(); + let t1 = arena.append(0); + let t2 = arena.append(1); assert!(t1 != t2); assert!(arena[t1] != arena[t2]); } #[test] fn fetch_or_append_non_unique() { - let mut arena: Arena = Arena::new(); - let t1 = arena.fetch_or_append(0.0); - let t2 = arena.fetch_or_append(0.0); + let mut arena: Arena = Arena::new(); + let t1 = arena.fetch_or_append(0); + let t2 = arena.fetch_or_append(0); assert!(t1 == t2); assert!(arena[t1] == arena[t2]) } #[test] fn fetch_or_append_unique() { - let mut arena: Arena = Arena::new(); - let t1 = arena.fetch_or_append(std::f64::NAN); - let t2 = arena.fetch_or_append(std::f64::NAN); + let mut arena: Arena = Arena::new(); + let t1 = arena.fetch_or_append(0); + let t2 = arena.fetch_or_append(1); assert!(t1 != t2); assert!(arena[t1] != arena[t2]); } diff --git a/src/back/msl.rs b/src/back/msl.rs index 58b927861..b9968bfc2 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -74,6 +74,7 @@ enum LocationMode { Uniform, } +#[derive(Debug, Clone, Copy)] pub struct Options<'a> { pub binding_map: &'a BindingMap, } @@ -199,13 +200,6 @@ impl AsName for Option { } } -struct Starred(T); -impl Display for Starred { - fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - write!(formatter, "*{}", self.0) - } -} - struct TypedGlobalVariable<'a> { module: &'a crate::Module, handle: crate::Handle, @@ -461,8 +455,16 @@ impl Writer { writeln!(self.out, "#include ")?; writeln!(self.out, "using namespace metal;")?; - // write down complex types - writeln!(self.out, "")?; + writeln!(self.out)?; + self.write_type_defs(module, options)?; + + writeln!(self.out)?; + self.write_functions(module, options)?; + + Ok(()) + } + + fn write_type_defs(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { for (handle, ty) in module.types.iter() { let name = ty.name.or_index(handle); match ty.inner { @@ -541,10 +543,11 @@ impl Writer { } writeln!(self.out, ";")?; } + Ok(()) + } - // write down functions + fn write_functions(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { let mut uniforms_used = FastHashSet::default(); - writeln!(self.out, "")?; for (fun_handle, fun) in module.functions.iter() { let fun_name = fun.name.or_index(fun_handle); // find the entry point(s) and inputs/outputs diff --git a/src/front/spirv.rs b/src/front/spirv.rs index a0b9d4d4b..ab2fd5497 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -15,16 +15,9 @@ use crate::{ FastHashMap, FastHashSet, }; +use num_traits::cast::FromPrimitive; use std::convert::TryInto; -const LAST_KNOWN_OPCODE: spirv::Op = spirv::Op::MemberDecorateStringGOOGLE; -const LAST_KNOWN_CAPABILITY: spirv::Capability = spirv::Capability::VulkanMemoryModelDeviceScopeKHR; -const LAST_KNOWN_EXECUTION_MODEL: spirv::ExecutionModel = spirv::ExecutionModel::Kernel; -const LAST_KNOWN_STORAGE_CLASS: spirv::StorageClass = spirv::StorageClass::StorageBuffer; -const LAST_KNOWN_DECORATION: spirv::Decoration = spirv::Decoration::NonUniformEXT; -const LAST_KNOWN_BUILT_IN: spirv::BuiltIn = spirv::BuiltIn::FullyCoveredEXT; -const LAST_KNOWN_DIM: spirv::Dim = spirv::Dim::DimSubpassData; - pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, ]; @@ -118,8 +111,7 @@ trait LookupHelper { impl LookupHelper for FastHashMap { type Target = T; fn lookup(&self, key: spirv::Word) -> Result<&T, Error> { - self.get(&key) - .ok_or(Error::InvalidId(key)) + self.get(&key).ok_or(Error::InvalidId(key)) } } @@ -128,16 +120,12 @@ fn map_vector_size(word: spirv::Word) -> Result { 2 => Ok(crate::VectorSize::Bi), 3 => Ok(crate::VectorSize::Tri), 4 => Ok(crate::VectorSize::Quad), - _ => Err(Error::InvalidVectorSize(word)) + _ => Err(Error::InvalidVectorSize(word)), } } fn map_storage_class(word: spirv::Word) -> Result { - if word > LAST_KNOWN_STORAGE_CLASS as u32 { - Err(Error::UnsupportedStorageClass(word)) - } else { - Ok(unsafe { std::mem::transmute(word) }) - } + spirv::StorageClass::from_u32(word).ok_or(Error::UnsupportedStorageClass(word)) } type MemberIndex = u32; @@ -272,16 +260,9 @@ impl> Parser { if wc == 0 { return Err(Error::InvalidWordCount); } - if opcode > LAST_KNOWN_OPCODE as u16 { - return Err(Error::UnknownInstruction(opcode)); - } + let op = spirv::Op::from_u16(opcode).ok_or(Error::UnknownInstruction(opcode))?; - Ok(Instruction { - op: unsafe { - std::mem::transmute(opcode as u32) - }, - wc, - }) + Ok(Instruction { op, wc }) } fn next_string(&mut self, mut count: u16) -> Result<(String, u16), Error>{ @@ -310,24 +291,17 @@ impl> Parser { dec: &mut Decoration, ) -> Result<(), Error> { let raw = self.next()?; - if raw > LAST_KNOWN_DECORATION as spirv::Word { - return Err(Error::InvalidDecoration(raw)); - } - let dec_typed = unsafe { - std::mem::transmute::<_, spirv::Decoration>(raw) - }; + let dec_typed = spirv::Decoration::from_u32(raw).ok_or(Error::InvalidDecoration(raw))?; log::trace!("\t\t{:?}", dec_typed); match dec_typed { spirv::Decoration::BuiltIn => { inst.expect(base_words + 2)?; let raw = self.next()?; - if raw > LAST_KNOWN_BUILT_IN as spirv::Word { + let built_in = spirv::BuiltIn::from_u32(raw); + if built_in.is_none() { log::warn!("Unknown built in {:?}", raw); - } else { - dec.built_in = Some(unsafe { - std::mem::transmute(raw) - }); } + dec.built_in = built_in; } spirv::Decoration::Location => { inst.expect(base_words + 2)?; @@ -688,7 +662,7 @@ impl> Parser { fn switch(&mut self, state: ModuleState, op: spirv::Op) -> Result<(), Error> { if state < self.state { - return Err(Error::UnsupportedInstruction(self.state, op)) + Err(Error::UnsupportedInstruction(self.state, op)) } else { self.state = state; Ok(()) @@ -715,620 +689,36 @@ impl> Parser { use spirv::Op; log::debug!("\t{:?} [{}]", inst.op, inst.wc); match inst.op { - Op::Capability => { - self.switch(ModuleState::Capability, inst.op)?; - inst.expect(2)?; - let capability = self.next()?; - if capability > LAST_KNOWN_CAPABILITY as u32 { - return Err(Error::UnknownCapability(capability)); - } - let cap = unsafe { - std::mem::transmute(capability) - }; - if !SUPPORTED_CAPABILITIES.contains(&cap) { - return Err(Error::UnsupportedCapability(cap)); - } - } - Op::Extension => { - self.switch(ModuleState::Extension, inst.op)?; - inst.expect_at_least(2)?; - let (name, left) = self.next_string(inst.wc - 1)?; - if left != 0 { - return Err(Error::InvalidOperand); - } - if !SUPPORTED_EXTENSIONS.contains(&name.as_str()) { - return Err(Error::UnsupportedExtension(name.to_owned())); - } - } - Op::ExtInstImport => { - self.switch(ModuleState::Extension, inst.op)?; - inst.expect_at_least(3)?; - let _result = self.next()?; - let (name, left) = self.next_string(inst.wc - 2)?; - if left != 0 { - return Err(Error::InvalidOperand) - } - if !SUPPORTED_EXT_SETS.contains(&name.as_str()) { - return Err(Error::UnsupportedExtSet(name.to_owned())); - } - } - Op::MemoryModel => { - self.switch(ModuleState::MemoryModel, inst.op)?; - inst.expect(3)?; - let _addressing_model = self.next()?; - let _memory_model = self.next()?; - } - Op::EntryPoint => { - self.switch(ModuleState::EntryPoint, inst.op)?; - inst.expect_at_least(4)?; - let exec_model = self.next()?; - if exec_model > LAST_KNOWN_EXECUTION_MODEL as u32 { - return Err(Error::UnsupportedExecutionModel(exec_model)); - } - let function_id = self.next()?; - let (name, left) = self.next_string(inst.wc - 3)?; - let ep = EntryPoint { - exec_model: unsafe { - std::mem::transmute(exec_model) - }, - name: name.to_owned(), - function_id, - variable_ids: self.data - .by_ref() - .take(left as usize) - .collect(), - }; - entry_points.push(ep); - } - Op::ExecutionMode => { - self.switch(ModuleState::ExecutionMode, inst.op)?; - inst.expect_at_least(3)?; - let _ep_id = self.next()?; - let _mode = self.next()?; - for _ in 3 .. inst.wc { - let _ = self.next()?; //TODO - } - } - Op::Source => { - self.switch(ModuleState::Source, inst.op)?; - for _ in 1 .. inst.wc { - let _ = self.next()?; - } - } - Op::SourceExtension => { - self.switch(ModuleState::Source, inst.op)?; - inst.expect_at_least(2)?; - let (_name, _) = self.next_string(inst.wc - 1)?; - } - Op::Name => { - self.switch(ModuleState::Name, inst.op)?; - inst.expect_at_least(3)?; - let id = self.next()?; - let (name, left) = self.next_string(inst.wc - 2)?; - if left != 0 { - return Err(Error::InvalidOperand); - } - self.future_decor - .entry(id) - .or_default() - .name = Some(name.to_owned()); - } - Op::MemberName => { - self.switch(ModuleState::Name, inst.op)?; - inst.expect_at_least(4)?; - let id = self.next()?; - let member = self.next()?; - let (name, left) = self.next_string(inst.wc - 3)?; - if left != 0 { - return Err(Error::InvalidOperand); - } - self.future_member_decor - .entry((id, member)) - .or_default() - .name = Some(name.to_owned()); - } - Op::Decorate => { - self.switch(ModuleState::Annotation, inst.op)?; - inst.expect_at_least(3)?; - let id = self.next()?; - let mut dec = self.future_decor - .remove(&id) - .unwrap_or_default(); - self.next_decoration(inst, 2, &mut dec)?; - self.future_decor.insert(id, dec); - } - Op::MemberDecorate => { - self.switch(ModuleState::Annotation, inst.op)?; - inst.expect_at_least(4)?; - let id = self.next()?; - let member = self.next()?; - let mut dec = self.future_member_decor - .remove(&(id, member)) - .unwrap_or_default(); - self.next_decoration(inst, 3, &mut dec)?; - self.future_member_decor.insert((id, member), dec); - } - Op::TypeVoid => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(2)?; - let id = self.next()?; - self.lookup_void_type.insert(id); - } - Op::TypeInt => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(4)?; - let id = self.next()?; - let width = self.next()?; - let sign = self.next()?; - let inner = crate::TypeInner::Scalar { - kind: match sign { - 0 => crate::ScalarKind::Uint, - 1 => crate::ScalarKind::Sint, - _ => return Err(Error::InvalidSign(sign)), - }, - width: width - .try_into() - .map_err(|_| Error::InvalidTypeWidth(width))?, - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: None, - }); - } - Op::TypeFloat => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(3)?; - let id = self.next()?; - let width = self.next()?; - let inner = crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: width - .try_into() - .map_err(|_| Error::InvalidTypeWidth(width))?, - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: None, - }); - } - Op::TypeVector => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(4)?; - let id = self.next()?; - let type_id = self.next()?; - let type_lookup = self.lookup_type.lookup(type_id)?; - let (kind, width) = match module.types[type_lookup.handle].inner { - crate::TypeInner::Scalar { kind, width } => (kind, width), - _ => return Err(Error::InvalidInnerType(type_id)), - }; - let component_count = self.next()?; - let inner = crate::TypeInner::Vector { - size: map_vector_size(component_count)?, - kind, - width, - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: Some(type_id), - }); - } - Op::TypeMatrix => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(4)?; - let id = self.next()?; - let vector_type_id = self.next()?; - let num_columns = self.next()?; - let vector_type_lookup = self.lookup_type.lookup(vector_type_id)?; - let inner = match module.types[vector_type_lookup.handle].inner { - crate::TypeInner::Vector { size, kind, width } => crate::TypeInner::Matrix { - columns: map_vector_size(num_columns)?, - rows: size, - kind, - width, - }, - _ => return Err(Error::InvalidInnerType(vector_type_id)), - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: Some(vector_type_id), - }); - } - Op::TypeFunction => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect_at_least(3)?; - let id = self.next()?; - let return_type_id = self.next()?; - let parameter_type_ids = self.data - .by_ref() - .take(inst.wc as usize - 3) - .collect(); - self.lookup_function_type.insert(id, LookupFunctionType { - parameter_type_ids, - return_type_id, - }); - } - Op::TypePointer => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(4)?; - let id = self.next()?; - let storage = self.next()?; - let type_id = self.next()?; - let inner = crate::TypeInner::Pointer { - base: self.lookup_type.lookup(type_id)?.handle, - class: map_storage_class(storage)?, - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: Some(type_id), - }); - } - Op::TypeArray => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(4)?; - let id = self.next()?; - let type_id = self.next()?; - let length = self.next()?; - let inner = crate::TypeInner::Array { - base: self.lookup_type.lookup(type_id)?.handle, - size: crate::ArraySize::Static(length), - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: Some(type_id), - }); - } - Op::TypeRuntimeArray => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(4)?; - let id = self.next()?; - let type_id = self.next()?; - let inner = crate::TypeInner::Array { - base: self.lookup_type.lookup(type_id)?.handle, - size: crate::ArraySize::Dynamic, - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: Some(type_id), - }); - } - Op::TypeStruct => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect_at_least(2)?; - let id = self.next()?; - let mut members = Vec::with_capacity(inst.wc as usize - 2); - for i in 0 .. inst.wc as u32 - 2 { - let type_id = self.next()?; - let ty = self.lookup_type.lookup(type_id)?.handle; - self.lookup_member_type_id.insert((id, i), type_id); - let decor = self.future_member_decor - .remove(&(id, i)) - .unwrap_or_default(); - let binding = decor.get_binding(); - members.push(crate::StructMember { - name: decor.name, - binding, - ty, - }); - } - let inner = crate::TypeInner::Struct { - members - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: None, - }); - } - Op::TypeImage => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect_at_least(9)?; - - let id = self.next()?; - let sample_type_id = self.next()?; - let dim = self.next()?; - let mut flags = crate::ImageFlags::empty(); - let _is_depth = self.next()?; - if self.next()? != 0 { - flags |= crate::ImageFlags::ARRAYED; - } - if self.next()? != 0 { - flags |= crate::ImageFlags::MULTISAMPLED; - } - let is_sampled = self.next()?; - if is_sampled != 0 { - flags |= crate::ImageFlags::SAMPLED; - } - let _format = self.next()?; - if inst.wc > 9 { - inst.expect(10)?; - let access = self.next()?; - if access == 0 || access == 2 { - flags |= crate::ImageFlags::CAN_LOAD; - } - if access == 1 || access == 2 { - flags |= crate::ImageFlags::CAN_STORE; - } - }; - - let decor = self.future_decor - .remove(&id) - .unwrap_or_default(); - - let inner = crate::TypeInner::Image { - base: self.lookup_type.lookup(sample_type_id)?.handle, - dim: if dim > LAST_KNOWN_DIM as u32 { - return Err(Error::UnsupportedDim(dim)); - } else { - unsafe { std::mem::transmute(dim) } - }, - flags, - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: decor.name, - inner, - }), - base_id: Some(sample_type_id), - }); - } - Op::TypeSampledImage => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(3)?; - let id = self.next()?; - let image_id = self.next()?; - self.lookup_type.insert(id, LookupType { - handle: self.lookup_type.lookup(image_id)?.handle, - base_id: Some(image_id), - }); - } - Op::TypeSampler => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(2)?; - let id = self.next()?; - let decor = self.future_decor - .remove(&id) - .unwrap_or_default(); - let inner = crate::TypeInner::Sampler; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: decor.name, - inner, - }), - base_id: None, - }); - } - Op::Constant | - Op::SpecConstant => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect_at_least(3)?; - let type_id = self.next()?; - let id = self.next()?; - let type_lookup = self.lookup_type.lookup(type_id)?; - let ty = type_lookup.handle; - let inner = match module.types[type_lookup.handle].inner { - crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width } => { - let low = self.next()?; - let high = if width > 32 { - inst.expect(4)?; - self.next()? - } else { - 0 - }; - crate::ConstantInner::Uint(((high as u64) << 32) | low as u64) - } - crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width } => { - let low = self.next()?; - let high = if width < 32 { - return Err(Error::InvalidTypeWidth(width as u32)); - } else if width > 32 { - inst.expect(4)?; - self.next()? - } else { - !0 - }; - crate::ConstantInner::Sint(unsafe { - std::mem::transmute(((high as u64) << 32) | low as u64) - }) - } - crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width } => { - let low = self.next()?; - let extended = if width < 32 { - return Err(Error::InvalidTypeWidth(width as u32)); - } else if width > 32 { - inst.expect(4)?; - let high = self.next()?; - unsafe { - std::mem::transmute(((high as u64) << 32) | low as u64) - } - } else { - unsafe { - std::mem::transmute::<_, f32>(low) as f64 - } - }; - crate::ConstantInner::Float(extended) - } - _ => return Err(Error::UnsupportedType(type_lookup.handle)) - }; - self.lookup_constant.insert(id, LookupConstant { - handle: module.constants.append(crate::Constant { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - specialization: None, //TODO - inner, - ty, - }), - type_id, - }); - } - Op::Variable => { - self.switch(ModuleState::Type, inst.op)?; - inst.expect_at_least(4)?; - let type_id = self.next()?; - let id = self.next()?; - let storage = self.next()?; - if inst.wc != 4 { - inst.expect(5)?; - let _init = self.next()?; //TODO - } - let lookup_type = self.lookup_type.lookup(type_id)?; - let dec = self.future_decor - .remove(&id) - .ok_or(Error::InvalidBinding(id))?; - let binding = match module.types[lookup_type.handle].inner { - crate::TypeInner::Pointer { base, class: spirv::StorageClass::Input } | - crate::TypeInner::Pointer { base, class: spirv::StorageClass::Output } => { - match module.types[base].inner { - crate::TypeInner::Struct { ref members } => { - // we don't expect binding decoration on I/O structs, - // but we do expect them on all of the members - for member in members { - if member.binding.is_none() { - log::warn!("Struct {:?} member {:?} doesn't have a binding", base, member); - return Err(Error::InvalidBinding(id)); - } - } - None - } - _ => { - Some(dec - .get_binding() - .ok_or(Error::InvalidBinding(id))? - ) - } - } - } - _ => { - Some(dec - .get_binding() - .ok_or(Error::InvalidBinding(id))? - ) - } - }; - let var = crate::GlobalVariable { - name: dec.name, - class: map_storage_class(storage)?, - binding, - ty: lookup_type.handle, - }; - self.lookup_variable.insert(id, LookupVariable { - handle: module.global_variables.append(var), - type_id, - }); - } - Op::Function => { - self.switch(ModuleState::Function, inst.op)?; - inst.expect(5)?; - let result_type = self.next()?; - let fun_id = self.next()?; - let fun_control = self.next()?; - let fun_type = self.next()?; - let mut fun = { - let ft = self.lookup_function_type.lookup(fun_type)?.clone(); - if ft.return_type_id != result_type { - return Err(Error::WrongFunctionResultType(result_type)) - } - crate::Function { - name: self.future_decor - .remove(&fun_id) - .and_then(|dec| dec.name), - control: spirv::FunctionControl::from_bits(fun_control) - .ok_or(Error::UnsupportedFunctionControl(fun_control))?, - parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), - return_type: if self.lookup_void_type.contains(&result_type) { - None - } else { - Some(self.lookup_type.lookup(result_type)?.handle) - }, - local_variables: Arena::new(), - expressions: self.make_expression_storage(), - body: Vec::new(), - } - }; - // read parameters - for i in 0 .. fun.parameter_types.capacity() { - match self.next_inst()? { - Instruction { op: Op::FunctionParameter, wc: 3 } => { - let type_id = self.next()?; - let _id = self.next()?; - //Note: we redo the lookup in order to work around `self` borrowing - if type_id != self.lookup_function_type - .lookup(fun_type)? - .parameter_type_ids[i] - { - return Err(Error::WrongFunctionParameterType(type_id)) - } - let ty = self.lookup_type.lookup(type_id)?.handle; - fun.parameter_types.push(ty); - } - Instruction { op, .. } => return Err(Error::InvalidParameter(op)), - } - } - // read body - loop { - let fun_inst = self.next_inst()?; - log::debug!("\t\t{:?}", fun_inst.op); - match fun_inst.op { - Op::Label => { - fun_inst.expect(2)?; - let _id = self.next()?; - self.next_block(&mut fun, &module.types, &module.constants)?; - } - Op::FunctionEnd => { - fun_inst.expect(1)?; - break - } - _ => return Err(Error::UnsupportedInstruction(self.state, fun_inst.op)) - } - } - // done - let handle = module.functions.append(fun); - self.lookup_function.insert(fun_id, handle); - self.lookup_expression.clear(); - self.lookup_sampled_image.clear(); - } - _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)) - //TODO - } + Op::Capability => self.parse_capability(inst), + Op::Extension => self.parse_extension(inst), + Op::ExtInstImport => self.parse_ext_inst_import(inst), + Op::MemoryModel => self.parse_memory_model(inst), + Op::EntryPoint => self.parse_entry_point(inst, &mut entry_points), + Op::ExecutionMode => self.parse_execution_mode(inst), + Op::Source => self.parse_source(inst), + Op::SourceExtension => self.parse_source_extension(inst), + Op::Name => self.parse_name(inst), + Op::MemberName => self.parse_member_name(inst), + Op::Decorate => self.parse_decorate(inst), + Op::MemberDecorate => self.parse_member_decorate(inst), + Op::TypeVoid => self.parse_type_void(inst), + Op::TypeInt => self.parse_type_int(inst, &mut module), + Op::TypeFloat => self.parse_type_float(inst, &mut module), + Op::TypeVector => self.parse_type_vector(inst, &mut module), + Op::TypeMatrix => self.parse_type_matrix(inst, &mut module), + Op::TypeFunction => self.parse_type_function(inst), + Op::TypePointer => self.parse_type_pointer(inst, &mut module), + Op::TypeArray => self.parse_type_array(inst, &mut module), + Op::TypeRuntimeArray => self.parse_type_runtime_array(inst, &mut module), + Op::TypeStruct => self.parse_type_struct(inst, &mut module), + Op::TypeImage => self.parse_type_image(inst, &mut module), + Op::TypeSampledImage => self.parse_type_sampled_image(inst), + Op::TypeSampler => self.parse_type_sampler(inst, &mut module), + Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), + Op::Variable => self.parse_variable(inst, &mut module), + Op::Function => self.parse_function(inst, &mut module), + _ => Err(Error::UnsupportedInstruction(self.state, inst.op)), //TODO + }?; } if !self.future_decor.is_empty() { @@ -1354,7 +744,7 @@ impl> Parser { match module.global_variables[handle].class { spirv::StorageClass::Input => ep.inputs.push(handle), spirv::StorageClass::Output => ep.outputs.push(handle), - other => return Err(Error::InvalidVariableClass(other)) + other => return Err(Error::InvalidVariableClass(other)), } } module.entry_points.push(ep); @@ -1362,6 +752,707 @@ impl> Parser { Ok(module) } + + fn parse_capability(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Capability, inst.op)?; + inst.expect(2)?; + let capability = self.next()?; + let cap = + spirv::Capability::from_u32(capability).ok_or(Error::UnknownCapability(capability))?; + if !SUPPORTED_CAPABILITIES.contains(&cap) { + return Err(Error::UnsupportedCapability(cap)); + } + Ok(()) + } + + fn parse_extension(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Extension, inst.op)?; + inst.expect_at_least(2)?; + let (name, left) = self.next_string(inst.wc - 1)?; + if left != 0 { + return Err(Error::InvalidOperand); + } + if !SUPPORTED_EXTENSIONS.contains(&name.as_str()) { + return Err(Error::UnsupportedExtension(name.to_owned())); + } + Ok(()) + } + + fn parse_ext_inst_import(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Extension, inst.op)?; + inst.expect_at_least(3)?; + let _result = self.next()?; + let (name, left) = self.next_string(inst.wc - 2)?; + if left != 0 { + return Err(Error::InvalidOperand); + } + if !SUPPORTED_EXT_SETS.contains(&name.as_str()) { + return Err(Error::UnsupportedExtSet(name.to_owned())); + } + Ok(()) + } + + fn parse_memory_model(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::MemoryModel, inst.op)?; + inst.expect(3)?; + let _addressing_model = self.next()?; + let _memory_model = self.next()?; + Ok(()) + } + + fn parse_entry_point( + &mut self, + inst: Instruction, + entry_points: &mut Vec, + ) -> Result<(), Error> { + self.switch(ModuleState::EntryPoint, inst.op)?; + inst.expect_at_least(4)?; + let exec_model = self.next()?; + let exec_model = spirv::ExecutionModel::from_u32(exec_model) + .ok_or(Error::UnsupportedExecutionModel(exec_model))?; + let function_id = self.next()?; + let (name, left) = self.next_string(inst.wc - 3)?; + let ep = EntryPoint { + exec_model, + name: name.to_owned(), + function_id, + variable_ids: self.data + .by_ref() + .take(left as usize) + .collect(), + }; + entry_points.push(ep); + Ok(()) + } + + fn parse_execution_mode(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::ExecutionMode, inst.op)?; + inst.expect_at_least(3)?; + let _ep_id = self.next()?; + let _mode = self.next()?; + for _ in 3..inst.wc { + let _ = self.next()?; //TODO + } + Ok(()) + } + + fn parse_source(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Source, inst.op)?; + for _ in 1 .. inst.wc { + let _ = self.next()?; + } + Ok(()) + } + + fn parse_source_extension(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Source, inst.op)?; + inst.expect_at_least(2)?; + let (_name, _) = self.next_string(inst.wc - 1)?; + Ok(()) + } + + fn parse_name(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Name, inst.op)?; + inst.expect_at_least(3)?; + let id = self.next()?; + let (name, left) = self.next_string(inst.wc - 2)?; + if left != 0 { + return Err(Error::InvalidOperand); + } + self.future_decor + .entry(id) + .or_default() + .name = Some(name.to_owned()); + Ok(()) + } + + fn parse_member_name(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Name, inst.op)?; + inst.expect_at_least(4)?; + let id = self.next()?; + let member = self.next()?; + let (name, left) = self.next_string(inst.wc - 3)?; + if left != 0 { + return Err(Error::InvalidOperand); + } + self.future_member_decor + .entry((id, member)) + .or_default() + .name = Some(name.to_owned()); + Ok(()) + } + + fn parse_decorate(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Annotation, inst.op)?; + inst.expect_at_least(3)?; + let id = self.next()?; + let mut dec = self.future_decor + .remove(&id) + .unwrap_or_default(); + self.next_decoration(inst, 2, &mut dec)?; + self.future_decor.insert(id, dec); + Ok(()) + } + + fn parse_member_decorate(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Annotation, inst.op)?; + inst.expect_at_least(4)?; + let id = self.next()?; + let member = self.next()?; + let mut dec = self.future_member_decor + .remove(&(id, member)) + .unwrap_or_default(); + self.next_decoration(inst, 3, &mut dec)?; + self.future_member_decor.insert((id, member), dec); + Ok(()) + } + + fn parse_type_void(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(2)?; + let id = self.next()?; + self.lookup_void_type.insert(id); + Ok(()) + } + + fn parse_type_int( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let width = self.next()?; + let sign = self.next()?; + let inner = crate::TypeInner::Scalar { + kind: match sign { + 0 => crate::ScalarKind::Uint, + 1 => crate::ScalarKind::Sint, + _ => return Err(Error::InvalidSign(sign)), + }, + width: width + .try_into() + .map_err(|_| Error::InvalidTypeWidth(width))?, + }; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), + base_id: None, + }); + Ok(()) + } + + fn parse_type_float( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(3)?; + let id = self.next()?; + let width = self.next()?; + let inner = crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: width + .try_into() + .map_err(|_| Error::InvalidTypeWidth(width))?, + }; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), + base_id: None, + }); + Ok(()) + } + + fn parse_type_vector( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let type_id = self.next()?; + let type_lookup = self.lookup_type.lookup(type_id)?; + let (kind, width) = match module.types[type_lookup.handle].inner { + crate::TypeInner::Scalar { kind, width } => (kind, width), + _ => return Err(Error::InvalidInnerType(type_id)), + }; + let component_count = self.next()?; + let inner = crate::TypeInner::Vector { + size: map_vector_size(component_count)?, + kind, + width, + }; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), + base_id: Some(type_id), + }); + Ok(()) + } + + fn parse_type_matrix( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let vector_type_id = self.next()?; + let num_columns = self.next()?; + let vector_type_lookup = self.lookup_type.lookup(vector_type_id)?; + let inner = match module.types[vector_type_lookup.handle].inner { + crate::TypeInner::Vector { size, kind, width } => crate::TypeInner::Matrix { + columns: map_vector_size(num_columns)?, + rows: size, + kind, + width, + }, + _ => return Err(Error::InvalidInnerType(vector_type_id)), + }; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), + base_id: Some(vector_type_id), + }); + Ok(()) + } + + fn parse_type_function(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(3)?; + let id = self.next()?; + let return_type_id = self.next()?; + let parameter_type_ids = self.data + .by_ref() + .take(inst.wc as usize - 3) + .collect(); + self.lookup_function_type.insert(id, LookupFunctionType { + parameter_type_ids, + return_type_id, + }); + Ok(()) + } + + fn parse_type_pointer( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let storage = self.next()?; + let type_id = self.next()?; + let inner = crate::TypeInner::Pointer { + base: self.lookup_type.lookup(type_id)?.handle, + class: map_storage_class(storage)?, + }; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), + base_id: Some(type_id), + }); + Ok(()) + } + + fn parse_type_array( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let type_id = self.next()?; + let length = self.next()?; + let inner = crate::TypeInner::Array { + base: self.lookup_type.lookup(type_id)?.handle, + size: crate::ArraySize::Static(length), + }; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + inner, + }), + base_id: Some(type_id), + }); + Ok(()) + } + + fn parse_type_runtime_array( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(4)?; + let id = self.next()?; + let type_id = self.next()?; + let inner = crate::TypeInner::Array { + base: self.lookup_type.lookup(type_id)?.handle, + size: crate::ArraySize::Dynamic, + }; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: Some(type_id), + }); + Ok(()) + } + + fn parse_type_struct( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(2)?; + let id = self.next()?; + let mut members = Vec::with_capacity(inst.wc as usize - 2); + for i in 0 .. u32::from(inst.wc) - 2 { + let type_id = self.next()?; + let ty = self.lookup_type.lookup(type_id)?.handle; + self.lookup_member_type_id.insert((id, i), type_id); + let decor = self.future_member_decor + .remove(&(id, i)) + .unwrap_or_default(); + let binding = decor.get_binding(); + members.push(crate::StructMember { + name: decor.name, + binding, + ty, + }); + } + let inner = crate::TypeInner::Struct { + members + }; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: None, + }); + Ok(()) + } + + fn parse_type_image( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(9)?; + + let id = self.next()?; + let sample_type_id = self.next()?; + let dim = self.next()?; + let mut flags = crate::ImageFlags::empty(); + let _is_depth = self.next()?; + if self.next()? != 0 { + flags |= crate::ImageFlags::ARRAYED; + } + if self.next()? != 0 { + flags |= crate::ImageFlags::MULTISAMPLED; + } + let is_sampled = self.next()?; + if is_sampled != 0 { + flags |= crate::ImageFlags::SAMPLED; + } + let _format = self.next()?; + if inst.wc > 9 { + inst.expect(10)?; + let access = self.next()?; + if access == 0 || access == 2 { + flags |= crate::ImageFlags::CAN_LOAD; + } + if access == 1 || access == 2 { + flags |= crate::ImageFlags::CAN_STORE; + } + }; + + let decor = self.future_decor + .remove(&id) + .unwrap_or_default(); + + let inner = crate::TypeInner::Image { + base: self.lookup_type.lookup(sample_type_id)?.handle, + dim: spirv::Dim::from_u32(dim).ok_or(Error::UnsupportedDim(dim))?, + flags, + }; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: decor.name, + inner, + }), + base_id: Some(sample_type_id), + }); + Ok(()) + } + + fn parse_type_sampled_image(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(3)?; + let id = self.next()?; + let image_id = self.next()?; + self.lookup_type.insert(id, LookupType { + handle: self.lookup_type.lookup(image_id)?.handle, + base_id: Some(image_id), + }); + Ok(()) + } + + fn parse_type_sampler( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(2)?; + let id = self.next()?; + let decor = self.future_decor + .remove(&id) + .unwrap_or_default(); + let inner = crate::TypeInner::Sampler; + self.lookup_type.insert(id, LookupType { + handle: module.types.append(crate::Type { + name: decor.name, + inner, + }), + base_id: None, + }); + Ok(()) + } + + fn parse_constant( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(3)?; + let type_id = self.next()?; + let id = self.next()?; + let type_lookup = self.lookup_type.lookup(type_id)?; + let ty = type_lookup.handle; + let inner = match module.types[type_lookup.handle].inner { + crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width } => { + let low = self.next()?; + let high = if width > 32 { + inst.expect(4)?; + self.next()? + } else { + 0 + }; + crate::ConstantInner::Uint((u64::from(high) << 32) | u64::from(low)) + } + crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width } => { + let low = self.next()?; + let high = if width < 32 { + return Err(Error::InvalidTypeWidth(u32::from(width))); + } else if width > 32 { + inst.expect(4)?; + self.next()? + } else { + !0 + }; + crate::ConstantInner::Sint(((u64::from(high) << 32) | u64::from(low)) as i64) + } + crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width } => { + let low = self.next()?; + let extended = match width { + 32 => f64::from(f32::from_bits(low)), + 64 => { + inst.expect(4)?; + let high = self.next()?; + f64::from_bits((u64::from(high) << 32) | u64::from(low)) + } + _ => return Err(Error::InvalidTypeWidth(u32::from(width))), + }; + crate::ConstantInner::Float(extended) + } + _ => return Err(Error::UnsupportedType(type_lookup.handle)) + }; + self.lookup_constant.insert(id, LookupConstant { + handle: module.constants.append(crate::Constant { + name: self.future_decor + .remove(&id) + .and_then(|dec| dec.name), + specialization: None, //TODO + inner, + ty, + }), + type_id, + }); + Ok(()) + } + + fn parse_variable( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(4)?; + let type_id = self.next()?; + let id = self.next()?; + let storage = self.next()?; + if inst.wc != 4 { + inst.expect(5)?; + let _init = self.next()?; //TODO + } + let lookup_type = self.lookup_type.lookup(type_id)?; + let dec = self.future_decor + .remove(&id) + .ok_or(Error::InvalidBinding(id))?; + let binding = match module.types[lookup_type.handle].inner { + crate::TypeInner::Pointer { base, class: spirv::StorageClass::Input } | + crate::TypeInner::Pointer { base, class: spirv::StorageClass::Output } => { + match module.types[base].inner { + crate::TypeInner::Struct { ref members } => { + // we don't expect binding decoration on I/O structs, + // but we do expect them on all of the members + for member in members { + if member.binding.is_none() { + log::warn!("Struct {:?} member {:?} doesn't have a binding", base, member); + return Err(Error::InvalidBinding(id)); + } + } + None + } + _ => { + Some(dec + .get_binding() + .ok_or(Error::InvalidBinding(id))? + ) + } + } + } + _ => { + Some(dec + .get_binding() + .ok_or(Error::InvalidBinding(id))? + ) + } + }; + let var = crate::GlobalVariable { + name: dec.name, + class: map_storage_class(storage)?, + binding, + ty: lookup_type.handle, + }; + self.lookup_variable.insert(id, LookupVariable { + handle: module.global_variables.append(var), + type_id, + }); + Ok(()) + } + + fn parse_function( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Function, inst.op)?; + inst.expect(5)?; + let result_type = self.next()?; + let fun_id = self.next()?; + let fun_control = self.next()?; + let fun_type = self.next()?; + let mut fun = { + let ft = self.lookup_function_type.lookup(fun_type)?; + if ft.return_type_id != result_type { + return Err(Error::WrongFunctionResultType(result_type)) + } + crate::Function { + name: self.future_decor + .remove(&fun_id) + .and_then(|dec| dec.name), + control: spirv::FunctionControl::from_bits(fun_control) + .ok_or(Error::UnsupportedFunctionControl(fun_control))?, + parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), + return_type: if self.lookup_void_type.contains(&result_type) { + None + } else { + Some(self.lookup_type.lookup(result_type)?.handle) + }, + local_variables: Arena::new(), + expressions: self.make_expression_storage(), + body: Vec::new(), + } + }; + // read parameters + for i in 0..fun.parameter_types.capacity() { + match self.next_inst()? { + Instruction { op: spirv::Op::FunctionParameter, wc: 3 } => { + let type_id = self.next()?; + let _id = self.next()?; + //Note: we redo the lookup in order to work around `self` borrowing + if type_id != self.lookup_function_type + .lookup(fun_type)? + .parameter_type_ids[i] + { + return Err(Error::WrongFunctionParameterType(type_id)) + } + let ty = self.lookup_type.lookup(type_id)?.handle; + fun.parameter_types.push(ty); + } + Instruction { op, .. } => return Err(Error::InvalidParameter(op)), + } + } + // read body + loop { + let fun_inst = self.next_inst()?; + log::debug!("\t\t{:?}", fun_inst.op); + match fun_inst.op { + spirv::Op::Label => { + fun_inst.expect(2)?; + let _id = self.next()?; + self.next_block(&mut fun, &module.types, &module.constants)?; + } + spirv::Op::FunctionEnd => { + fun_inst.expect(1)?; + break + } + _ => return Err(Error::UnsupportedInstruction(self.state, fun_inst.op)) + } + } + // done + let handle = module.functions.append(fun); + self.lookup_function.insert(fun_id, handle); + self.lookup_expression.clear(); + self.lookup_sampled_image.clear(); + Ok(()) + } } pub fn parse_u8_slice(data: &[u8]) -> Result { diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 77b58e3f5..303ff1bdf 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -35,12 +35,12 @@ mod lex { } } - fn consume_any<'a>(input: &'a str, what: impl Fn(char) -> bool) -> (&'a str, &'a str) { - let pos = input.find(|c| !what(c)).unwrap_or(input.len()); + fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { + let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); input.split_at(pos) } - pub fn consume_token<'a>(mut input: &'a str) -> (Token<'a>, &'a str) { + pub fn consume_token(mut input: &str) -> (Token<'_>, &str) { input = input.trim_start(); let mut chars = input.chars(); let cur = match chars.next() { @@ -164,9 +164,7 @@ struct Lexer<'a> { impl<'a> Lexer<'a> { fn new(input: &'a str) -> Self { - Lexer { - input, - } + Lexer { input } } #[must_use] @@ -377,7 +375,7 @@ impl Parser { } } - fn get_storage_class<'a>(word: &'a str) -> Result> { + fn get_storage_class(word: &str) -> Result> { match word { "in" => Ok(spirv::StorageClass::Input), "out" => Ok(spirv::StorageClass::Output), @@ -387,7 +385,7 @@ impl Parser { } } - fn get_built_in<'a>(word: &'a str) -> Result> { + fn get_built_in(word: &str) -> Result> { match word { "position" => Ok(spirv::BuiltIn::Position), "vertex_idx" => Ok(spirv::BuiltIn::VertexId), @@ -396,7 +394,7 @@ impl Parser { } } - fn get_execution_model<'a>(word: &'a str) -> Result> { + fn get_execution_model(word: &str) -> Result> { match word { "vertex" => Ok(spirv::ExecutionModel::Vertex), "fragment" => Ok(spirv::ExecutionModel::Fragment), @@ -405,7 +403,7 @@ impl Parser { } } - fn get_constant_inner<'a>(word: &'a str) -> Result> { + fn get_constant_inner(word: &str) -> Result> { if word.contains('.') { word .parse() diff --git a/src/lib.rs b/src/lib.rs index ada612473..85f4fb787 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::new_without_default)] + mod arena; pub mod back; pub mod front; From 0de28d1656e341f89920225d70fe748836a941b0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 15 Mar 2020 23:01:20 -0400 Subject: [PATCH 0061/2212] [msl] operators, array access, and built-in calls --- src/back/msl.rs | 235 +++++++++++++++++++++++++++++++++++++---------- tests/convert.rs | 10 +- 2 files changed, 196 insertions(+), 49 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index b9968bfc2..a2a5df726 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -48,6 +48,18 @@ enum ResolvedBinding { Resource(BindTarget), } +struct Level(usize); +impl Level { + fn next(&self) -> Self { + Level(self.0 + 1) + } +} +impl Display for Level { + fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { + (0 .. self.0).map(|_| formatter.write_str("\t")).collect() + } +} + #[derive(Debug)] pub enum Error { Format(FmtError), @@ -120,6 +132,10 @@ impl Indexed for crate::Handle { const CLASS: &'static str = "global"; fn id(&self) -> usize { self.index() } } +impl Indexed for crate::Handle { + const CLASS: &'static str = "local"; + fn id(&self) -> usize { self.index() } +} impl Indexed for crate::Handle { const CLASS: &'static str = "function"; fn id(&self) -> usize { self.index() } @@ -310,15 +326,27 @@ impl crate::Module { impl Writer { fn put_expression<'a>( &mut self, - expr_handle: crate::Handle, - expressions: &crate::Arena, + expr_handle: Handle, + function: &crate::Function, module: &'a crate::Module, ) -> Result, Error> { - let expression = &expressions[expr_handle]; + let expression = &function.expressions[expr_handle]; log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { + crate::Expression::Access { base, index } => { + match *self.put_expression(base, function, module)?.borrow() { + crate::TypeInner::Array { base, .. } => { + //TODO: add size check + self.out.write_str("[")?; + self.put_expression(index, function, module)?; + self.out.write_str("]")?; + Ok(module.borrow_type(base)) + } + ref other => panic!("Unexpected indexing of {:?}", other), + } + } crate::Expression::AccessIndex { base, index } => { - match *self.put_expression(base, expressions, module)?.borrow() { + match *self.put_expression(base, function, module)?.borrow() { crate::TypeInner::Struct { ref members } => { let member = &members[index as usize]; let name = member.name.or_index(MemberIndex(index as usize)); @@ -374,7 +402,7 @@ impl Writer { if i != 0 { write!(self.out, ",")?; } - self.put_expression(handle, expressions, module)?; + self.put_expression(handle, function, module)?; } write!(self.out, ")")?; } @@ -405,51 +433,187 @@ impl Writer { write!(self.out, "{}", name)?; Ok(MaybeOwned::Borrowed(inner)) } + crate::Expression::LocalVariable(handle) => { + let var = &function.local_variables[handle]; + let inner = &module.types[var.ty].inner; + let name = var.name.or_index(handle); + write!(self.out, "{}", name)?; + Ok(MaybeOwned::Borrowed(inner)) + } crate::Expression::Load { pointer } => { //write!(self.out, "*")?; - match *self.put_expression(pointer, expressions, module)?.borrow() { + match *self.put_expression(pointer, function, module)?.borrow() { crate::TypeInner::Pointer { base, .. } => { Ok(module.borrow_type(base)) } ref other => panic!("Unexpected load pointer {:?}", other), } } + crate::Expression::Unary { op, expr } => { + let op_str = match op { + crate::UnaryOperator::Negate => "-", + crate::UnaryOperator::Not => "!", + }; + write!(self.out, "{}", op_str)?; + self.put_expression(expr, function, module) + } crate::Expression::Binary { op, left, right } => { - let op_ch = match op { - crate::BinaryOperator::Add => '+', - crate::BinaryOperator::Multiply => '*', - crate::BinaryOperator::Divide => '/', - crate::BinaryOperator::Modulo => '%', + let op_str = match op { + crate::BinaryOperator::Add => "+", + crate::BinaryOperator::Subtract => "-", + crate::BinaryOperator::Multiply => "*", + crate::BinaryOperator::Divide => "/", + crate::BinaryOperator::Modulo => "%", + crate::BinaryOperator::Equal => "==", + crate::BinaryOperator::NotEqual => "!=", + crate::BinaryOperator::Less => "<", + crate::BinaryOperator::LessEqual => "<=", + crate::BinaryOperator::Greater => "==", + crate::BinaryOperator::GreaterEqual => ">=", _ => panic!("Unsupported binary op {:?}", op), }; write!(self.out, "(")?; - let ty_left = self.put_expression(left, expressions, module)?; - write!(self.out, " {} ", op_ch)?; - let ty_right = self.put_expression(right, expressions, module)?; + let ty_left = self.put_expression(left, function, module)?; + write!(self.out, " {} ", op_str)?; + let ty_right = self.put_expression(right, function, module)?; write!(self.out, ")")?; - Ok(match (ty_left.borrow(), ty_right.borrow()) { - (&crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, kind, width }) | - (&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Scalar { .. }) => - MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), - other => panic!("Unable to infer Mul for {:?}", other), + + Ok(if op_str.len() == 1 { + match (ty_left.borrow(), ty_right.borrow()) { + (&crate::TypeInner::Scalar { kind, width }, &crate::TypeInner::Scalar { .. }) => + MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width }), + (&crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, kind, width }) | + (&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Scalar { .. }) | + (&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Vector { .. }) => + MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), + other => panic!("Unable to infer {:?} for {:?}", op, other), + } + } else { + MaybeOwned::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1 }) }) } crate::Expression::ImageSample { image, sampler, coordinate } => { - let ty_image = self.put_expression(image, expressions, module)?; + let ty_image = self.put_expression(image, function, module)?; write!(self.out, ".sample(")?; - self.put_expression(sampler, expressions, module)?; + self.put_expression(sampler, function, module)?; write!(self.out, ", ")?; - self.put_expression(coordinate, expressions, module)?; + self.put_expression(coordinate, function, module)?; write!(self.out, ")")?; match *ty_image.borrow() { crate::TypeInner::Image { base, .. } => Ok(module.borrow_type(base)), ref other => panic!("Unexpected image type {:?}", other), } } + crate::Expression::Call { ref name, ref arguments } => { + match name.as_str() { + "distance" => { + write!(self.out, "distance(")?; + let result = match *self.put_expression(arguments[0], function, module)?.borrow() { + crate::TypeInner::Vector { kind, width, .. } => crate::TypeInner::Scalar { kind, width }, + ref other => panic!("Unexpected distance argument {:?}", other), + }; + write!(self.out, ", ")?; + self.put_expression(arguments[1], function, module)?; + write!(self.out, ")")?; + Ok(MaybeOwned::Owned(result)) + } + "length" => { + write!(self.out, "length(")?; + let result = match *self.put_expression(arguments[0], function, module)?.borrow() { + crate::TypeInner::Vector { kind, width, .. } => crate::TypeInner::Scalar { kind, width }, + ref other => panic!("Unexpected distance argument {:?}", other), + }; + write!(self.out, ")")?; + Ok(MaybeOwned::Owned(result)) + } + "normalize" => { + write!(self.out, "normalize(")?; + let result = self.put_expression(arguments[0], function, module)?; + write!(self.out, ")")?; + Ok(result) + } + "fclamp" => { + write!(self.out, "fclamp(")?; + let result = self.put_expression(arguments[0], function, module)?; + write!(self.out, ")")?; + Ok(result) + } + _ => panic!("Unsupported call to '{}'", name), + } + } ref other => panic!("Unsupported {:?}", other), } } + fn put_statement<'a>( + &mut self, + level: Level, + statement: &crate::Statement, + function: &crate::Function, + is_entry_point: bool, + module: &'a crate::Module, + ) -> Result<(), Error> { + log::trace!("statement[{}] {:?}", level.0, statement); + match *statement { + crate::Statement::Empty => {} + crate::Statement::If { condition, ref accept, ref reject } => { + write!(self.out, "{}if (", level)?; + self.put_expression(condition, function, module)?; + writeln!(self.out, ") {{")?; + for s in accept { + self.put_statement(level.next(), s, function, is_entry_point, module)?; + } + if !reject.is_empty() { + writeln!(self.out, "{}}} else {{", level)?; + for s in reject { + self.put_statement(level.next(), s, function, is_entry_point, module)?; + } + } + writeln!(self.out, "{}}}", level)?; + } + crate::Statement::Loop { ref body, ref continuing } => { + writeln!(self.out, "{}while(true) {{", level)?; + for s in body { + self.put_statement(level.next(), s, function, is_entry_point, module)?; + } + if !continuing.is_empty() { + //TODO + } + writeln!(self.out, "{}}}", level)?; + } + crate::Statement::Store { pointer, value } => { + //write!(self.out, "\t*")?; + write!(self.out, "{}", level)?; + self.put_expression(pointer, function, module)?; + write!(self.out, " = ")?; + self.put_expression(value, function, module)?; + writeln!(self.out, ";")?; + } + crate::Statement::Break => { + writeln!(self.out, "{}break;", level)?; + } + crate::Statement::Continue => { + writeln!(self.out, "{}continue;", level)?; + } + crate::Statement::Return { value } => { + write!(self.out, "{}return ", level)?; + match value { + None if is_entry_point => self.out.write_str(NAME_OUTPUT)?, + None => {} + Some(expr_handle) if is_entry_point => { + panic!("Unable to return value {:?} from an entry point!", expr_handle) + } + Some(expr_handle) => { + self.put_expression(expr_handle, function, module)?; + } + } + writeln!(self.out, ";")?; + } + _ => panic!("Unsupported {:?}", statement), + }; + Ok(()) + } + pub fn write(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; @@ -668,32 +832,7 @@ impl Writer { writeln!(self.out, "\t{} {};", output_name, NAME_OUTPUT)?; } for statement in fun.body.iter() { - log::trace!("statement {:?}", statement); - match *statement { - crate::Statement::Store { pointer, value } => { - //write!(self.out, "\t*")?; - write!(self.out, "\t")?; - self.put_expression(pointer, &fun.expressions, module)?; - write!(self.out, " = ")?; - self.put_expression(value, &fun.expressions, module)?; - writeln!(self.out, ";")?; - } - crate::Statement::Return { value } => { - write!(self.out, "\treturn ")?; - match (value, exec_model) { - (None, None) => (), - (None, Some(_)) => self.out.write_str(NAME_OUTPUT)?, - (Some(expr_handle), None) => { - self.put_expression(expr_handle, &fun.expressions, module)?; - } - (Some(expr_handle), Some(_)) => { - panic!("Unable to return value {:?} from an entry point!", expr_handle) - } - } - writeln!(self.out, ";")?; - } - _ => panic!("Unsupported {:?}", statement), - } + self.put_statement(Level(1), statement, fun, exec_model.is_some(), module)?; } writeln!(self.out, "}}")?; } diff --git a/tests/convert.rs b/tests/convert.rs index d8c7feba7..9740e4154 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -27,5 +27,13 @@ fn convert_quad() { #[test] fn convert_boids() { - let _module = load_wgsl("boids"); + let module = load_wgsl("boids"); + { + use naga::back::msl; + let binding_map = msl::BindingMap::default(); + let options = msl::Options { + binding_map: &binding_map, + }; + msl::write_string(&module, options).unwrap(); + } } From df855bc2ffe8c7e6c44f85a2aaf7176db64ff27c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Mar 2020 09:35:10 -0400 Subject: [PATCH 0062/2212] Makefile and RON converter parameters --- Cargo.toml | 2 ++ Makefile | 15 +++++++++++++ examples/convert.rs | 52 +++++++++++++++++++++++++++++++++++++-------- src/lib.rs | 4 ++-- test-data/boids.ron | 7 ++++++ tests/convert.rs | 14 +++++++++++- 6 files changed, 82 insertions(+), 12 deletions(-) create mode 100644 Makefile create mode 100644 test-data/boids.ron diff --git a/Cargo.toml b/Cargo.toml index 382075918..fb5a16443 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,3 +18,5 @@ spirv = { package = "spirv_headers", version = "1" } [dev-dependencies] env_logger = "0.6" +ron = "0.5" +serde = { version = "1", features = ["serde_derive"] } diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..d1240c235 --- /dev/null +++ b/Makefile @@ -0,0 +1,15 @@ +.PHONY: all clean + +all: boids.metallib + +clean: + rm *.metal *.air *.metallib + +%.metal: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) + cargo run --example convert -- $< $@ + +%.air: %.metal + xcrun -sdk macosx metal -c $< -mmacosx-version-min=10.11 + +%.metallib: %.air + xcrun -sdk macosx metallib $< -o $@ diff --git a/examples/convert.rs b/examples/convert.rs index aa266e889..f9aacd29b 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -1,5 +1,24 @@ +use serde::{Serialize, Deserialize}; use std::{env, fs}; +#[derive(Hash, PartialEq, Eq, Serialize, Deserialize)] +struct BindSource { + set: u32, + binding: u32, +} + +#[derive(Serialize, Deserialize)] +struct BindTarget { + buffer: Option, + texture: Option, + sampler: Option, +} + +#[derive(Default, Serialize, Deserialize)] +struct Parameters { + metal_bindings: naga::FastHashMap, +} + fn main() { env_logger::init(); @@ -20,17 +39,32 @@ fn main() { if args.len() <= 2 { println!("{:#?}", module); - } else if args[2].ends_with(".metal") { + return; + } + + let param_path = std::path::PathBuf::from(&args[1]) + .with_extension("ron"); + let params = match fs::read_to_string(param_path) { + Ok(string) => ron::de::from_str(&string).unwrap(), + Err(_) => Parameters::default(), + }; + + if args[2].ends_with(".metal") { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); - binding_map.insert( - msl::BindSource { set: 0, binding: 0 }, - msl::BindTarget { buffer: None, texture: Some(1), sampler: None }, - ); - binding_map.insert( - msl::BindSource { set: 0, binding: 1 }, - msl::BindTarget { buffer: None, texture: None, sampler: Some(1) }, - ); + for (key, value) in params.metal_bindings { + binding_map.insert( + msl::BindSource { + set: key.set, + binding: key.binding, + }, + msl::BindTarget { + buffer: value.buffer, + texture: value.texture, + sampler: value.sampler, + }, + ); + } let options = msl::Options { binding_map: &binding_map, }; diff --git a/src/lib.rs b/src/lib.rs index 85f4fb787..c1cf027b5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,8 +13,8 @@ use std::{ }; -type FastHashMap = HashMap>; -type FastHashSet = HashSet>; +pub type FastHashMap = HashMap>; +pub type FastHashSet = HashSet>; #[derive(Clone, Debug)] pub struct Header { diff --git a/test-data/boids.ron b/test-data/boids.ron new file mode 100644 index 000000000..1bf180ed2 --- /dev/null +++ b/test-data/boids.ron @@ -0,0 +1,7 @@ +( + metal_bindings: { + (set: 0, binding: 0): (buffer: Some(0), texture: None, sampler: None), + (set: 0, binding: 1): (buffer: Some(1), texture: None, sampler: None), + (set: 0, binding: 2): (buffer: Some(2), texture: None, sampler: None), + } +) \ No newline at end of file diff --git a/tests/convert.rs b/tests/convert.rs index 9740e4154..fe86a7034 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -30,7 +30,19 @@ fn convert_boids() { let module = load_wgsl("boids"); { use naga::back::msl; - let binding_map = msl::BindingMap::default(); + let mut binding_map = msl::BindingMap::default(); + binding_map.insert( + msl::BindSource { set: 0, binding: 0 }, + msl::BindTarget { buffer: Some(0), texture: None, sampler: None }, + ); + binding_map.insert( + msl::BindSource { set: 0, binding: 1 }, + msl::BindTarget { buffer: Some(1), texture: None, sampler: Some(1) }, + ); + binding_map.insert( + msl::BindSource { set: 0, binding: 2 }, + msl::BindTarget { buffer: Some(2), texture: None, sampler: Some(1) }, + ); let options = msl::Options { binding_map: &binding_map, }; From 80a9254dbedb32934dc92665efce379c6d57b59a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Mar 2020 09:40:34 -0400 Subject: [PATCH 0063/2212] Interface processor --- src/back/msl.rs | 115 +++++++++++++++++++++------------ src/front/spirv.rs | 10 +-- src/front/wgsl.rs | 49 ++++++++++---- src/lib.rs | 4 +- src/proc/interface.rs | 145 ++++++++++++++++++++++++++++++++++++++++++ src/proc/mod.rs | 2 + 6 files changed, 267 insertions(+), 58 deletions(-) create mode 100644 src/proc/interface.rs diff --git a/src/back/msl.rs b/src/back/msl.rs index a2a5df726..ea08a4149 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -25,6 +25,10 @@ use crate::{ FastHashMap, FastHashSet }; +/// Expect all the global variables to have a pointer type, +/// like in SPIR-V. +const GLOBAL_POINTERS: bool = false; + #[derive(Clone, Debug, PartialEq)] pub struct BindTarget { pub buffer: Option, @@ -224,19 +228,24 @@ impl Display for TypedGlobalVariable<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { let var = &self.module.global_variables[self.handle]; let name = var.name.or_index(self.handle); - let ty = &self.module.types[var.ty]; - match ty.inner { - crate::TypeInner::Pointer { base, class } => { - let ty_handle= match class { - spirv::StorageClass::Input | - spirv::StorageClass::Output | - spirv::StorageClass::UniformConstant => base, - _ => var.ty - }; - let ty_name = self.module.types[ty_handle].name.or_index(ty_handle); - write!(formatter, "{} {}", ty_name, name) + if GLOBAL_POINTERS { + let ty = &self.module.types[var.ty]; + match ty.inner { + crate::TypeInner::Pointer { base, class } => { + let ty_handle = match class { + spirv::StorageClass::Input | + spirv::StorageClass::Output | + spirv::StorageClass::UniformConstant => base, + _ => var.ty + }; + let ty_name = self.module.types[ty_handle].name.or_index(ty_handle); + write!(formatter, "{} {}", ty_name, name) + } + _ => panic!("Unexpected global type {:?} = {:?}", var.ty, ty), } - _ => panic!("Unexpected global type {:?}", var.ty), + } else { + let ty_name = self.module.types[var.ty].name.or_index(var.ty); + write!(formatter, "{} {}", ty_name, name) } } } @@ -247,6 +256,7 @@ impl Display for ResolvedBinding { ResolvedBinding::BuiltIn(built_in) => { let name = match built_in { spirv::BuiltIn::ClipDistance => "clip_distance", + spirv::BuiltIn::GlobalInvocationId => "thread_position_in_grid", spirv::BuiltIn::PointSize => "point_size", spirv::BuiltIn::Position => "position", _ => panic!("Built in {:?} is not implemented", built_in), @@ -416,10 +426,16 @@ impl Writer { match var.class { spirv::StorageClass::Output => { self.out.write_str(NAME_OUTPUT)?; - if let crate::TypeInner::Pointer { base, .. } = *inner { - let base_inner = &module.types[base].inner; - if let crate::TypeInner::Struct { .. } = *base_inner { - return Ok(MaybeOwned::Borrowed(base_inner)); + if GLOBAL_POINTERS { + if let crate::TypeInner::Pointer { base, .. } = *inner { + let base_inner = &module.types[base].inner; + if let crate::TypeInner::Struct { .. } = *base_inner { + return Ok(MaybeOwned::Borrowed(base_inner)); + } + } + } else { + if let crate::TypeInner::Struct { .. } = *inner { + return Ok(MaybeOwned::Borrowed(inner)); } } self.out.write_str(".")?; @@ -506,6 +522,23 @@ impl Writer { } crate::Expression::Call { ref name, ref arguments } => { match name.as_str() { + "cos" | + "fclamp" | + "normalize" | + "sin" => { + write!(self.out, "{}(", name)?; + let result = self.put_expression(arguments[0], function, module)?; + write!(self.out, ")")?; + Ok(result) + } + "atan2" => { + write!(self.out, "{}(", name)?; + let result = self.put_expression(arguments[0], function, module)?; + write!(self.out, ", ")?; + self.put_expression(arguments[1], function, module)?; + write!(self.out, ")")?; + Ok(result) + } "distance" => { write!(self.out, "distance(")?; let result = match *self.put_expression(arguments[0], function, module)?.borrow() { @@ -526,18 +559,7 @@ impl Writer { write!(self.out, ")")?; Ok(MaybeOwned::Owned(result)) } - "normalize" => { - write!(self.out, "normalize(")?; - let result = self.put_expression(arguments[0], function, module)?; - write!(self.out, ")")?; - Ok(result) - } - "fclamp" => { - write!(self.out, "fclamp(")?; - let result = self.put_expression(arguments[0], function, module)?; - write!(self.out, ")")?; - Ok(result) - } + _ => panic!("Unsupported call to '{}'", name), } } @@ -757,20 +779,24 @@ impl Writer { for &handle in var_outputs.iter() { let var = &module.global_variables[handle]; // if it's a struct, lift all the built-in contents up to the root - if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner { - if let crate::TypeInner::Struct { ref members } = module.types[base].inner { - for (index, member) in members.iter().enumerate() { - let name = member.name.or_index(MemberIndex(index)); - let ty_name = module.types[member.ty].name.or_index(member.ty); - let binding = member.binding - .as_ref() - .ok_or(Error::MissingBinding(handle))?; - let resolved = options.resolve_binding(binding, out_mode)?; - writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; - } - continue + let mut ty_handle = var.ty; + if GLOBAL_POINTERS { + if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner { + ty_handle = base; } } + if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner { + for (index, member) in members.iter().enumerate() { + let name = member.name.or_index(MemberIndex(index)); + let ty_name = module.types[member.ty].name.or_index(member.ty); + let binding = member.binding + .as_ref() + .ok_or(Error::MissingBinding(handle))?; + let resolved = options.resolve_binding(binding, out_mode)?; + writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; + } + continue + } let tyvar = TypedGlobalVariable { module, handle }; write!(self.out, "\t{}", tyvar)?; if let Some(ref binding) = var.binding { @@ -831,6 +857,15 @@ impl Writer { if exec_model.is_some() { writeln!(self.out, "\t{} {};", output_name, NAME_OUTPUT)?; } + for (local_handle, local) in fun.local_variables.iter() { + let ty_name = module.types[local.ty].name.or_index(local.ty); + write!(self.out, "\t{} {}", ty_name, local.name.or_index(local_handle))?; + if let Some(value) = local.init { + write!(self.out, " = ")?; + self.put_expression(value, fun, module)?; + } + writeln!(self.out, ";")?; + } for statement in fun.body.iter() { self.put_statement(Level(1), statement, fun, exec_model.is_some(), module)?; } diff --git a/src/front/spirv.rs b/src/front/spirv.rs index ab2fd5497..7ee620bf8 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -736,16 +736,16 @@ impl> Parser { exec_model: raw.exec_model, name: raw.name, function: *self.lookup_function.lookup(raw.function_id)?, - inputs: Vec::new(), - outputs: Vec::new(), + inputs: FastHashSet::default(), + outputs: FastHashSet::default(), }; for var_id in raw.variable_ids { let handle = self.lookup_variable.lookup(var_id)?.handle; match module.global_variables[handle].class { - spirv::StorageClass::Input => ep.inputs.push(handle), - spirv::StorageClass::Output => ep.outputs.push(handle), + spirv::StorageClass::Input => ep.inputs.insert(handle), + spirv::StorageClass::Output => ep.outputs.insert(handle), other => return Err(Error::InvalidVariableClass(other)), - } + }; } module.entry_points.push(ep); } diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 303ff1bdf..9c1bf02bf 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,6 +1,6 @@ use crate::{ arena::{Arena, Handle}, - proc::{Typifier, ResolveError}, + proc::{Interface, Typifier, ResolveError}, FastHashMap, }; @@ -1039,21 +1039,37 @@ impl Parser { self.scopes.push(Scope::Statement); let statement = match word { "var" => { + enum Init { + Empty, + Uniform(Handle), + Variable(Handle), + } let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; let init = if lexer.skip(Token::Operation('=')) { - Some(self.parse_general_expression(lexer, context.as_expression())?) + let value = self.parse_general_expression(lexer, context.as_expression())?; + if let crate::Expression::Constant(_) = context.expressions[value] { + Init::Uniform(value) + } else { + Init::Variable(value) + } } else { - None + Init::Empty }; lexer.expect(Token::Separator(';'))?; let var_id = context.variables.append(crate::LocalVariable { name: Some(name.to_owned()), ty, - init, + init: match init { + Init::Uniform(value) => Some(value), + _ => None, + } }); let expr_id = context.expressions.append(crate::Expression::LocalVariable(var_id)); context.lookup_ident.insert(name, expr_id); - crate::Statement::Empty + match init { + Init::Variable(value) => crate::Statement::Store { pointer: expr_id, value }, + _ => crate::Statement::Empty, + } } "return" => { let value = if lexer.peek() != Token::Separator(';') { @@ -1292,7 +1308,17 @@ impl Parser { let (name, class, ty) = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; let var_handle = module.global_variables.append(crate::GlobalVariable { name: Some(name.to_owned()), - class: class.unwrap_or(spirv::StorageClass::Private), + class: match class { + Some(c) => c, + None => match binding { + Some(crate::Binding::BuiltIn(builtin)) => match builtin { + spirv::BuiltIn::GlobalInvocationId => spirv::StorageClass::Input, + spirv::BuiltIn::Position => spirv::StorageClass::Output, + _ => unimplemented!(), + }, + _ => spirv::StorageClass::Private, + }, + }, binding: binding.take(), ty, }); @@ -1314,17 +1340,18 @@ impl Parser { lexer.expect(Token::Operation('='))?; let fun_ident = lexer.next_ident()?; lexer.expect(Token::Separator(';'))?; - let function = module.functions + let (fun_handle, function) = module.functions .iter() .find(|(_, fun)| fun.name.as_ref().map(|s| s.as_str()) == Some(fun_ident)) - .map(|(handle, _)| handle) .ok_or(Error::UnknownFunction(fun_ident))?; + + let io = Interface::new(function, &module.global_variables); module.entry_points.push(crate::EntryPoint { exec_model, name: export_name.unwrap_or(fun_ident).to_owned(), - inputs: Vec::new(), //TODO - outputs: Vec::new(), //TODO - function, + inputs: io.inputs, + outputs: io.outputs, + function: fun_handle, }); } Token::End => return Ok(false), diff --git a/src/lib.rs b/src/lib.rs index c1cf027b5..f7b091958 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -280,8 +280,8 @@ pub struct Function { pub struct EntryPoint { pub exec_model: spirv::ExecutionModel, pub name: String, - pub inputs: Vec>, - pub outputs: Vec>, + pub inputs: FastHashSet>, + pub outputs: FastHashSet>, pub function: Handle, } diff --git a/src/proc/interface.rs b/src/proc/interface.rs new file mode 100644 index 000000000..a68baee8c --- /dev/null +++ b/src/proc/interface.rs @@ -0,0 +1,145 @@ +use crate::{ + arena::{Arena, Handle}, + FastHashSet, +}; + +pub struct Interface<'a> { + expressions: &'a Arena, + globals: &'a Arena, + pub inputs: FastHashSet>, + pub outputs: FastHashSet>, +} + +impl<'a> Interface<'a> { + fn add_inputs(&mut self, handle: Handle) { + use crate::Expression as E; + match self.expressions[handle] { + E::Access { base, index } => { + self.add_inputs(base); + self.add_inputs(index); + } + E::AccessIndex { base, .. } => { + self.add_inputs(base); + } + E::Constant(_) => {} + E::Compose { ref components, .. } => { + for &comp in components { + self.add_inputs(comp); + } + } + E::FunctionParameter(_) => {}, + E::GlobalVariable(handle) => { + if self.globals[handle].class == spirv::StorageClass::Input { + self.inputs.insert(handle); + } + } + E::LocalVariable(_) => {} + E::Load { pointer } => { + self.add_inputs(pointer); + } + E::ImageSample { image, sampler, coordinate } => { + self.add_inputs(image); + self.add_inputs(sampler); + self.add_inputs(coordinate); + } + E::Unary { expr, .. } => { + self.add_inputs(expr); + } + E::Binary { left, right, .. } => { + self.add_inputs(left); + self.add_inputs(right); + } + E::Intrinsic { argument, .. } => { + self.add_inputs(argument); + } + E::DotProduct(left, right) => { + self.add_inputs(left); + self.add_inputs(right); + } + E::CrossProduct(left, right) => { + self.add_inputs(left); + self.add_inputs(right); + } + E::Derivative { expr, .. } => { + self.add_inputs(expr); + } + E::Call { ref arguments, .. } => { + for &argument in arguments { + self.add_inputs(argument); + } + } + } + } + + fn collect(&mut self, block: &[crate::Statement]) { + for statement in block { + use crate::Statement as S; + match *statement { + S::Empty | + S::Break | + S::Continue | + S::Kill => (), + S::Block(ref b) => { + self.collect(b); + } + S::If { condition, ref accept, ref reject } => { + self.add_inputs(condition); + self.collect(accept); + self.collect(reject); + } + S::Switch { selector, ref cases, ref default } => { + self.add_inputs(selector); + for &(ref case, _) in cases.values() { + self.collect(case); + } + self.collect(default); + } + S::Loop { ref body, ref continuing } => { + self.collect(body); + self.collect(continuing); + } + S::Return { value } => { + if let Some(expr) = value { + self.add_inputs(expr); + } + } + S::Store { pointer, value } => { + let mut left = pointer; + loop { + match self.expressions[left] { + crate::Expression::Access { base, index } => { + self.add_inputs(index); + left = base; + } + crate::Expression::AccessIndex { base, .. } => { + left = base; + } + crate::Expression::GlobalVariable(handle) => { + if self.globals[handle].class == spirv::StorageClass::Output { + self.outputs.insert(handle); + } + break; + } + _ => break, + } + } + self.add_inputs(value); + } + } + } + } + + pub fn new( + fun: &'a crate::Function, + globals: &'a Arena, + ) -> Self { + let mut io = Interface { + expressions: &fun.expressions, + globals, + inputs: FastHashSet::default(), + outputs: FastHashSet::default(), + }; + io.collect(&fun.body); + io + } +} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 38ac9304b..1237df94d 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,3 +1,5 @@ +mod interface; mod typifier; +pub use interface::Interface; pub use typifier::{ResolveError, Typifier}; From 55fab04353773916af56bbfa9b140c1e204c1a53 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Mar 2020 22:14:40 -0400 Subject: [PATCH 0064/2212] Refactor the interface processor, many improvements in global variables handling in MSL --- Makefile | 3 +- examples/convert.rs | 2 + src/arena.rs | 4 + src/back/msl.rs | 267 +++++++++++++++++++++++++++--------------- src/front/wgsl.rs | 37 +++++- src/proc/interface.rs | 38 +++--- src/proc/mod.rs | 2 +- test-data/boids.ron | 8 +- test-data/boids.wgsl | 4 +- tests/convert.rs | 10 +- 10 files changed, 243 insertions(+), 132 deletions(-) diff --git a/Makefile b/Makefile index d1240c235..89a899515 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,7 @@ .PHONY: all clean +.SECONDARY: boids.metal quad.metal -all: boids.metallib +all: clean: rm *.metal *.air *.metallib diff --git a/examples/convert.rs b/examples/convert.rs index f9aacd29b..c03e1d8fd 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -12,6 +12,7 @@ struct BindTarget { buffer: Option, texture: Option, sampler: Option, + mutable: bool, } #[derive(Default, Serialize, Deserialize)] @@ -62,6 +63,7 @@ fn main() { buffer: value.buffer, texture: value.texture, sampler: value.sampler, + mutable: value.mutable, }, ); } diff --git a/src/arena.rs b/src/arena.rs index a6e436425..349887754 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -84,6 +84,10 @@ impl Arena { } } + pub fn len(&self) -> usize { + self.data.len() + } + pub fn iter(&self) -> impl Iterator, &T)> { self.data .iter() diff --git a/src/back/msl.rs b/src/back/msl.rs index ea08a4149..e4896380d 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -22,6 +22,7 @@ use std::{ use crate::{ arena::Handle, + proc::GlobalUse, FastHashMap, FastHashSet }; @@ -29,11 +30,12 @@ use crate::{ /// like in SPIR-V. const GLOBAL_POINTERS: bool = false; -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct BindTarget { pub buffer: Option, pub texture: Option, pub sampler: Option, + pub mutable: bool, } #[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] @@ -73,6 +75,7 @@ pub enum Error { MissingBinding(crate::Handle), MissingBindTarget(BindSource), InvalidImageFlags(crate::ImageFlags), + MutabilityViolation(crate::Handle), BadName(String), } @@ -223,11 +226,25 @@ impl AsName for Option { struct TypedGlobalVariable<'a> { module: &'a crate::Module, handle: crate::Handle, + usage: GlobalUse, } impl Display for TypedGlobalVariable<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { let var = &self.module.global_variables[self.handle]; let name = var.name.or_index(self.handle); + let (space_qualifier, reference) = match var.class { + spirv::StorageClass::Uniform | + spirv::StorageClass::UniformConstant | + spirv::StorageClass::StorageBuffer => { + let space = if self.usage.contains(GlobalUse::STORE) { + "device " + } else { + "constant " + }; + (space, "&") + } + _ => ("", "") + }; if GLOBAL_POINTERS { let ty = &self.module.types[var.ty]; match ty.inner { @@ -235,6 +252,7 @@ impl Display for TypedGlobalVariable<'_> { let ty_handle = match class { spirv::StorageClass::Input | spirv::StorageClass::Output | + spirv::StorageClass::Uniform | spirv::StorageClass::UniformConstant => base, _ => var.ty }; @@ -245,7 +263,7 @@ impl Display for TypedGlobalVariable<'_> { } } else { let ty_name = self.module.types[var.ty].name.or_index(var.ty); - write!(formatter, "{} {}", ty_name, name) + write!(formatter, "{}{}{} {}", space_qualifier, ty_name, reference, name) } } } @@ -294,8 +312,8 @@ pub struct Writer { fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { match kind { crate::ScalarKind::Float => "float", - crate::ScalarKind::Sint => "signed int", - crate::ScalarKind::Uint => "unsigned int", + crate::ScalarKind::Sint => "int", + crate::ScalarKind::Uint => "uint", crate::ScalarKind::Bool => "bool", } } @@ -308,10 +326,14 @@ fn vector_size_string(size: crate::VectorSize) -> &'static str { } } -const NAME_INPUT: &str = "input"; -const NAME_OUTPUT: &str = "output"; +const OUTPUT_STRUCT_NAME: &str = "output"; +const LOCATION_INPUT_STRUCT_NAME: &str = "input"; const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; +fn separate(is_last: bool) -> &'static str { + if is_last { "" } else { "," } +} + #[derive(Debug)] enum MaybeOwned<'a, T: 'a> { Borrowed(&'a T), @@ -393,6 +415,9 @@ impl Writer { } crate::ConstantInner::Float(value) => { write!(self.out, "{}", value)?; + if value.fract() == 0.0 { + self.out.write_str(".0")?; + } crate::ScalarKind::Float } crate::ConstantInner::Bool(value) => { @@ -425,7 +450,6 @@ impl Writer { let inner = &module.types[var.ty].inner; match var.class { spirv::StorageClass::Output => { - self.out.write_str(NAME_OUTPUT)?; if GLOBAL_POINTERS { if let crate::TypeInner::Pointer { base, .. } = *inner { let base_inner = &module.types[base].inner; @@ -438,12 +462,14 @@ impl Writer { return Ok(MaybeOwned::Borrowed(inner)); } } - self.out.write_str(".")?; + write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; } spirv::StorageClass::Input => { - write!(self.out, "{}.", NAME_INPUT)?; + if let Some(crate::Binding::Location(_)) = var.binding { + write!(self.out, "{}.", LOCATION_INPUT_STRUCT_NAME)?; + } } - _ => () + _ => {} } let name = var.name.or_index(handle); write!(self.out, "{}", name)?; @@ -488,11 +514,11 @@ impl Writer { crate::BinaryOperator::GreaterEqual => ">=", _ => panic!("Unsupported binary op {:?}", op), }; - write!(self.out, "(")?; + //write!(self.out, "(")?; let ty_left = self.put_expression(left, function, module)?; write!(self.out, " {} ", op_str)?; let ty_right = self.put_expression(right, function, module)?; - write!(self.out, ")")?; + //write!(self.out, ")")?; Ok(if op_str.len() == 1 { match (ty_left.borrow(), ty_right.borrow()) { @@ -523,7 +549,6 @@ impl Writer { crate::Expression::Call { ref name, ref arguments } => { match name.as_str() { "cos" | - "fclamp" | "normalize" | "sin" => { write!(self.out, "{}(", name)?; @@ -531,6 +556,16 @@ impl Writer { write!(self.out, ")")?; Ok(result) } + "fclamp" => { + write!(self.out, "clamp(")?; + let result = self.put_expression(arguments[0], function, module)?; + write!(self.out, ", ")?; + self.put_expression(arguments[1], function, module)?; + write!(self.out, ", ")?; + self.put_expression(arguments[2], function, module)?; + write!(self.out, ")")?; + Ok(result) + } "atan2" => { write!(self.out, "{}(", name)?; let result = self.put_expression(arguments[0], function, module)?; @@ -572,7 +607,7 @@ impl Writer { level: Level, statement: &crate::Statement, function: &crate::Function, - is_entry_point: bool, + has_output: bool, module: &'a crate::Module, ) -> Result<(), Error> { log::trace!("statement[{}] {:?}", level.0, statement); @@ -583,12 +618,12 @@ impl Writer { self.put_expression(condition, function, module)?; writeln!(self.out, ") {{")?; for s in accept { - self.put_statement(level.next(), s, function, is_entry_point, module)?; + self.put_statement(level.next(), s, function, has_output, module)?; } if !reject.is_empty() { writeln!(self.out, "{}}} else {{", level)?; for s in reject { - self.put_statement(level.next(), s, function, is_entry_point, module)?; + self.put_statement(level.next(), s, function, has_output, module)?; } } writeln!(self.out, "{}}}", level)?; @@ -596,7 +631,7 @@ impl Writer { crate::Statement::Loop { ref body, ref continuing } => { writeln!(self.out, "{}while(true) {{", level)?; for s in body { - self.put_statement(level.next(), s, function, is_entry_point, module)?; + self.put_statement(level.next(), s, function, has_output, module)?; } if !continuing.is_empty() { //TODO @@ -620,9 +655,9 @@ impl Writer { crate::Statement::Return { value } => { write!(self.out, "{}return ", level)?; match value { - None if is_entry_point => self.out.write_str(NAME_OUTPUT)?, + None if has_output => self.out.write_str(OUTPUT_STRUCT_NAME)?, None => {} - Some(expr_handle) if is_entry_point => { + Some(expr_handle) if has_output => { panic!("Unable to return value {:?} from an entry point!", expr_handle) } Some(expr_handle) => { @@ -668,6 +703,7 @@ impl Writer { let class_name = match class { spirv::StorageClass::Input | spirv::StorageClass::Output => continue, + spirv::StorageClass::Uniform | spirv::StorageClass::UniformConstant => "constant", other => { log::warn!("Unexpected pointer class {:?}", other); @@ -733,11 +769,26 @@ impl Writer { } fn write_functions(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { - let mut uniforms_used = FastHashSet::default(); for (fun_handle, fun) in module.functions.iter() { let fun_name = fun.name.or_index(fun_handle); // find the entry point(s) and inputs/outputs let mut exec_model = None; + let global_use = GlobalUse::scan(fun, &module.global_variables); + let mut last_used_global = None; + for ((handle, var), &usage) in module.global_variables.iter().zip(global_use.iter()) { + match var.class { + spirv::StorageClass::Input => { + if let Some(crate::Binding::Location(_)) = var.binding { + continue + } + } + spirv::StorageClass::Output => continue, + _ => {} + } + if !usage.is_empty() { + last_used_global = Some(handle); + } + } let mut var_inputs = FastHashSet::default(); let mut var_outputs = FastHashSet::default(); for ep in module.entry_points.iter() { @@ -753,61 +804,109 @@ impl Writer { } } } - let input_name = fun.name.or_index(InputStructIndex(fun_handle)); let output_name = fun.name.or_index(OutputStructIndex(fun_handle)); + // make dedicated input/output structs if let Some(em) = exec_model { - writeln!(self.out, "struct {} {{", input_name)?; + assert_eq!(fun.return_type, None); let (em_str, in_mode, out_mode) = match em { spirv::ExecutionModel::Vertex => ("vertex", LocationMode::VertexInput, LocationMode::Intermediate), spirv::ExecutionModel::Fragment => ("fragment", LocationMode::Intermediate, LocationMode::FragmentOutput), - spirv::ExecutionModel::GLCompute => ("compute", LocationMode::Uniform, LocationMode::Uniform), + spirv::ExecutionModel::GLCompute => ("kernel", LocationMode::Uniform, LocationMode::Uniform), _ => return Err(Error::UnsupportedExecutionModel(em)), }; - for &handle in var_inputs.iter() { - let var = &module.global_variables[handle]; - let tyvar = TypedGlobalVariable { module, handle }; - write!(self.out, "\t{}", tyvar)?; - if let Some(ref binding) = var.binding { - let resolved = options.resolve_binding(binding, in_mode)?; - write!(self.out, " [[{}]]", resolved)?; + let location_input_name = fun.name.or_index(InputStructIndex(fun_handle)); + + if em != spirv::ExecutionModel::GLCompute { + writeln!(self.out, "struct {} {{", location_input_name)?; + for &handle in var_inputs.iter() { + let var = &module.global_variables[handle]; + // if it's a struct, lift all the built-in contents up to the root + let mut ty_handle = var.ty; + if GLOBAL_POINTERS { + if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner { + ty_handle = base; + } + } + if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner { + for (index, member) in members.iter().enumerate() { + if let Some(ref binding@crate::Binding::Location(_)) = member.binding { + let name = member.name.or_index(MemberIndex(index)); + let ty_name = module.types[member.ty].name.or_index(member.ty); + let resolved = options.resolve_binding(binding, in_mode)?; + writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; + } + } + } else { + if let Some(ref binding@crate::Binding::Location(_)) = var.binding { + let tyvar = TypedGlobalVariable { module, handle, usage: GlobalUse::empty() }; + let resolved = options.resolve_binding(binding, in_mode)?; + writeln!(self.out, "\t{} [[{}]];", tyvar, resolved)?; + } + } } - writeln!(self.out, ";")?; + writeln!(self.out, "}};")?; + writeln!(self.out, "struct {} {{", output_name)?; + for &handle in var_outputs.iter() { + let var = &module.global_variables[handle]; + // if it's a struct, lift all the built-in contents up to the root + let mut ty_handle = var.ty; + if GLOBAL_POINTERS { + if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner { + ty_handle = base; + } + } + if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner { + for (index, member) in members.iter().enumerate() { + let name = member.name.or_index(MemberIndex(index)); + let ty_name = module.types[member.ty].name.or_index(member.ty); + let binding = member.binding + .as_ref() + .ok_or(Error::MissingBinding(handle))?; + let resolved = options.resolve_binding(binding, out_mode)?; + writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; + } + } else { + let tyvar = TypedGlobalVariable { module, handle, usage: GlobalUse::empty() }; + write!(self.out, "\t{}", tyvar)?; + if let Some(ref binding) = var.binding { + let resolved = options.resolve_binding(binding, out_mode)?; + write!(self.out, " [[{}]]", resolved)?; + } + writeln!(self.out, ";")?; + } + } + writeln!(self.out, "}};")?; + writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; + let separator = separate(last_used_global.is_none()); + writeln!(self.out, "\t{} {} [[stage_in]]{}", + location_input_name, LOCATION_INPUT_STRUCT_NAME, separator)?; + } else { + writeln!(self.out, "{} void {}(", em_str, fun_name)?; } - writeln!(self.out, "}};")?; - writeln!(self.out, "struct {} {{", output_name)?; - for &handle in var_outputs.iter() { - let var = &module.global_variables[handle]; - // if it's a struct, lift all the built-in contents up to the root - let mut ty_handle = var.ty; - if GLOBAL_POINTERS { - if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner { - ty_handle = base; - } - } - if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner { - for (index, member) in members.iter().enumerate() { - let name = member.name.or_index(MemberIndex(index)); - let ty_name = module.types[member.ty].name.or_index(member.ty); - let binding = member.binding - .as_ref() - .ok_or(Error::MissingBinding(handle))?; - let resolved = options.resolve_binding(binding, out_mode)?; - writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; - } + + for ((handle, var), &usage) in module.global_variables.iter().zip(global_use.iter()) { + if usage.is_empty() || var.class == spirv::StorageClass::Output { continue } - let tyvar = TypedGlobalVariable { module, handle }; - write!(self.out, "\t{}", tyvar)?; - if let Some(ref binding) = var.binding { - let resolved = options.resolve_binding(binding, out_mode)?; - write!(self.out, " [[{}]]", resolved)?; + if var.class == spirv::StorageClass::Input { + if let Some(crate::Binding::Location(_)) = var.binding { + // location inputs are put into a separate struct + continue + } } - writeln!(self.out, ";")?; + let loc_mode = match (em, var.class) { + (spirv::ExecutionModel::Vertex, spirv::StorageClass::Input) => LocationMode::VertexInput, + (spirv::ExecutionModel::Vertex, spirv::StorageClass::Output) | + (spirv::ExecutionModel::Fragment, spirv::StorageClass::Input) => LocationMode::Intermediate, + (spirv::ExecutionModel::Fragment, spirv::StorageClass::Output) => LocationMode::FragmentOutput, + _ => LocationMode::Uniform, + }; + let resolved = options.resolve_binding(var.binding.as_ref().unwrap(), loc_mode)?; + let tyvar = TypedGlobalVariable { module, handle, usage }; + let separator = separate(last_used_global == Some(handle)); + writeln!(self.out, "\t{} [[{}]]{}", tyvar, resolved, separator)?; } - writeln!(self.out, "}};")?; - writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; - writeln!(self.out, "\t{} {} [[stage_in]],", input_name, NAME_INPUT)?; } else { let result_type_name = match fun.return_type { Some(type_id) => module.types[type_id].name.or_index(type_id), @@ -820,43 +919,21 @@ impl Writer { for (index, &ty) in fun.parameter_types.iter().enumerate() { let name = Name::from(ParameterIndex(index)); let member_type_name = module.types[ty].name.or_index(ty); - writeln!(self.out, "\t{} {},", member_type_name, name)?; - } - } - for (_, expr) in fun.expressions.iter() { - if let crate::Expression::GlobalVariable(handle) = *expr { - let var = &module.global_variables[handle]; - if var.class == spirv::StorageClass::UniformConstant && !uniforms_used.contains(&handle) { - uniforms_used.insert(handle); - let binding = var.binding - .as_ref() - .ok_or(Error::MissingBinding(handle))?; - let resolved = options.resolve_binding(binding, LocationMode::Uniform)?; - let var = TypedGlobalVariable { module, handle }; - writeln!(self.out, "\t{} [[{}]],", var, resolved)?; - } - } - } - // add an extra parameter to make Metal happy about the comma - match exec_model { - Some(spirv::ExecutionModel::Vertex) => { - writeln!(self.out, "\tunsigned _dummy [[vertex_id]]")?; - } - Some(spirv::ExecutionModel::Fragment) => { - writeln!(self.out, "\tbool _dummy [[front_facing]]")?; - } - Some(spirv::ExecutionModel::GLCompute) => { - writeln!(self.out, "\tunsigned _dummy [[threads_per_grid]]")?; - } - _ => { - writeln!(self.out, "\tint _dummy")?; + let separator = separate(index + 1 == fun.parameter_types.len() && last_used_global.is_none()); + writeln!(self.out, "\t{} {}{}", member_type_name, name, separator)?; } } writeln!(self.out, ") {{")?; + // write down function body - if exec_model.is_some() { - writeln!(self.out, "\t{} {};", output_name, NAME_OUTPUT)?; - } + let has_output = match exec_model { + Some(spirv::ExecutionModel::Vertex) | + Some(spirv::ExecutionModel::Fragment) => { + writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?; + true + } + _ => false + }; for (local_handle, local) in fun.local_variables.iter() { let ty_name = module.types[local.ty].name.or_index(local.ty); write!(self.out, "\t{} {}", ty_name, local.name.or_index(local_handle))?; @@ -867,7 +944,7 @@ impl Writer { writeln!(self.out, ";")?; } for statement in fun.body.iter() { - self.put_statement(Level(1), statement, fun, exec_model.is_some(), module)?; + self.put_statement(Level(1), statement, fun, has_output, module)?; } writeln!(self.out, "}}")?; } diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 9c1bf02bf..b05bf8275 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,7 +1,7 @@ use crate::{ arena::{Arena, Handle}, - proc::{Interface, Typifier, ResolveError}, - FastHashMap, + proc::{GlobalUse, Typifier, ResolveError}, + FastHashMap, FastHashSet, }; @@ -154,6 +154,7 @@ pub enum Error<'a> { UnknownIdent(&'a str), UnknownType(&'a str), UnknownFunction(&'a str), + MutabilityViolation(&'a str), Other, } @@ -1345,12 +1346,38 @@ impl Parser { .find(|(_, fun)| fun.name.as_ref().map(|s| s.as_str()) == Some(fun_ident)) .ok_or(Error::UnknownFunction(fun_ident))?; - let io = Interface::new(function, &module.global_variables); + let uses = GlobalUse::scan(function, &module.global_variables); + let mut inputs = FastHashSet::default(); + let mut outputs = FastHashSet::default(); + for ((handle, var), &usage) in module.global_variables.iter().zip(uses.iter()) { + match var.class { + _ if usage.is_empty() => {} + spirv::StorageClass::Input if usage.contains(GlobalUse::LOAD) => { + inputs.insert(handle); + } + spirv::StorageClass::Output if usage.contains(GlobalUse::STORE) => { + outputs.insert(handle); + } + spirv::StorageClass::Input | + spirv::StorageClass::Output => { + let name = lookup_global_expression + .iter() + .find(|&(_, h)| match *h { + crate::Expression::GlobalVariable(h) => h == handle, + _ => false, + }) + .map(|(name, _)| name) + .unwrap(); + return Err(Error::MutabilityViolation(name)); + } + _ => {} + } + } module.entry_points.push(crate::EntryPoint { exec_model, name: export_name.unwrap_or(fun_ident).to_owned(), - inputs: io.inputs, - outputs: io.outputs, + inputs, + outputs, function: fun_handle, }); } diff --git a/src/proc/interface.rs b/src/proc/interface.rs index a68baee8c..2bea51f41 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -1,13 +1,17 @@ use crate::{ arena::{Arena, Handle}, - FastHashSet, }; -pub struct Interface<'a> { +bitflags::bitflags! { + pub struct GlobalUse: u8 { + const LOAD = 0x1; + const STORE = 0x2; + } +} + +struct Interface<'a> { expressions: &'a Arena, - globals: &'a Arena, - pub inputs: FastHashSet>, - pub outputs: FastHashSet>, + uses: Vec, } impl<'a> Interface<'a> { @@ -29,9 +33,7 @@ impl<'a> Interface<'a> { } E::FunctionParameter(_) => {}, E::GlobalVariable(handle) => { - if self.globals[handle].class == spirv::StorageClass::Input { - self.inputs.insert(handle); - } + self.uses[handle.index()] |= GlobalUse::LOAD; } E::LocalVariable(_) => {} E::Load { pointer } => { @@ -115,9 +117,7 @@ impl<'a> Interface<'a> { left = base; } crate::Expression::GlobalVariable(handle) => { - if self.globals[handle].class == spirv::StorageClass::Output { - self.outputs.insert(handle); - } + self.uses[handle.index()] |= GlobalUse::STORE; break; } _ => break, @@ -128,18 +128,18 @@ impl<'a> Interface<'a> { } } } +} - pub fn new( - fun: &'a crate::Function, - globals: &'a Arena, - ) -> Self { +impl GlobalUse { + pub fn scan( + fun: &crate::Function, + globals: &Arena, + ) -> Box<[Self]> { let mut io = Interface { expressions: &fun.expressions, - globals, - inputs: FastHashSet::default(), - outputs: FastHashSet::default(), + uses: vec![GlobalUse::empty(); globals.len()], }; io.collect(&fun.body); - io + io.uses.into_boxed_slice() } } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 1237df94d..9aba4f1cf 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,5 +1,5 @@ mod interface; mod typifier; -pub use interface::Interface; +pub use interface::GlobalUse; pub use typifier::{ResolveError, Typifier}; diff --git a/test-data/boids.ron b/test-data/boids.ron index 1bf180ed2..db17ca341 100644 --- a/test-data/boids.ron +++ b/test-data/boids.ron @@ -1,7 +1,7 @@ ( metal_bindings: { - (set: 0, binding: 0): (buffer: Some(0), texture: None, sampler: None), - (set: 0, binding: 1): (buffer: Some(1), texture: None, sampler: None), - (set: 0, binding: 2): (buffer: Some(2), texture: None, sampler: None), + (set: 0, binding: 0): (buffer: Some(0), texture: None, sampler: None, mutable: false), + (set: 0, binding: 1): (buffer: Some(1), texture: None, sampler: None, mutable: true), + (set: 0, binding: 2): (buffer: Some(2), texture: None, sampler: None, mutable: true), } -) \ No newline at end of file +) diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl index 6df8a30b3..c7dc9a29a 100644 --- a/test-data/boids.wgsl +++ b/test-data/boids.wgsl @@ -64,7 +64,7 @@ type Particles = struct { [[binding 1, set 0]] var particlesA : Particles; [[binding 2, set 0]] var particlesB : Particles; -[[builtin global_invocation_id]] var gl_GlobalInvocationID : vec3; +[[builtin global_invocation_id]] var gl_GlobalInvocationID : vec3; # https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp fn compute_main() -> void { @@ -84,7 +84,7 @@ fn compute_main() -> void { var pos : vec2; var vel : vec2; - var i : i32 = 0; + var i : u32 = 0; loop { if (i >= 5) { break; diff --git a/tests/convert.rs b/tests/convert.rs index fe86a7034..4150ed824 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -12,11 +12,11 @@ fn convert_quad() { let mut binding_map = msl::BindingMap::default(); binding_map.insert( msl::BindSource { set: 0, binding: 0 }, - msl::BindTarget { buffer: None, texture: Some(1), sampler: None }, + msl::BindTarget { buffer: None, texture: Some(1), sampler: None, mutable: false }, ); binding_map.insert( msl::BindSource { set: 0, binding: 1 }, - msl::BindTarget { buffer: None, texture: None, sampler: Some(1) }, + msl::BindTarget { buffer: None, texture: None, sampler: Some(1), mutable: false }, ); let options = msl::Options { binding_map: &binding_map, @@ -33,15 +33,15 @@ fn convert_boids() { let mut binding_map = msl::BindingMap::default(); binding_map.insert( msl::BindSource { set: 0, binding: 0 }, - msl::BindTarget { buffer: Some(0), texture: None, sampler: None }, + msl::BindTarget { buffer: Some(0), texture: None, sampler: None, mutable: false }, ); binding_map.insert( msl::BindSource { set: 0, binding: 1 }, - msl::BindTarget { buffer: Some(1), texture: None, sampler: Some(1) }, + msl::BindTarget { buffer: Some(1), texture: None, sampler: Some(1), mutable: false }, ); binding_map.insert( msl::BindSource { set: 0, binding: 2 }, - msl::BindTarget { buffer: Some(2), texture: None, sampler: Some(1) }, + msl::BindTarget { buffer: Some(2), texture: None, sampler: Some(1), mutable: false }, ); let options = msl::Options { binding_map: &binding_map, From 3ea6ca428f5ba91ae0b5ecb60a96976ff4c10988 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 20 Mar 2020 12:54:51 -0400 Subject: [PATCH 0065/2212] Move the global usage into the IR function --- src/back/msl.rs | 34 ++++++++++++++++------------------ src/front/spirv.rs | 17 ++++------------- src/front/wgsl.rs | 39 ++++++--------------------------------- src/lib.rs | 10 ++++++++-- src/proc/interface.rs | 28 +++++++++++----------------- src/proc/mod.rs | 1 - 6 files changed, 45 insertions(+), 84 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index e4896380d..7b1d806a9 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -22,8 +22,7 @@ use std::{ use crate::{ arena::Handle, - proc::GlobalUse, - FastHashMap, FastHashSet + FastHashMap, }; /// Expect all the global variables to have a pointer type, @@ -226,7 +225,7 @@ impl AsName for Option { struct TypedGlobalVariable<'a> { module: &'a crate::Module, handle: crate::Handle, - usage: GlobalUse, + usage: crate::GlobalUse, } impl Display for TypedGlobalVariable<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { @@ -236,7 +235,7 @@ impl Display for TypedGlobalVariable<'_> { spirv::StorageClass::Uniform | spirv::StorageClass::UniformConstant | spirv::StorageClass::StorageBuffer => { - let space = if self.usage.contains(GlobalUse::STORE) { + let space = if self.usage.contains(crate::GlobalUse::STORE) { "device " } else { "constant " @@ -773,9 +772,8 @@ impl Writer { let fun_name = fun.name.or_index(fun_handle); // find the entry point(s) and inputs/outputs let mut exec_model = None; - let global_use = GlobalUse::scan(fun, &module.global_variables); let mut last_used_global = None; - for ((handle, var), &usage) in module.global_variables.iter().zip(global_use.iter()) { + for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { match var.class { spirv::StorageClass::Input => { if let Some(crate::Binding::Location(_)) = var.binding { @@ -789,12 +787,8 @@ impl Writer { last_used_global = Some(handle); } } - let mut var_inputs = FastHashSet::default(); - let mut var_outputs = FastHashSet::default(); for ep in module.entry_points.iter() { - if ep.function == fun_handle{ - var_inputs.extend(ep.inputs.iter().cloned()); - var_outputs.extend(ep.outputs.iter().cloned()); + if ep.function == fun_handle { if exec_model.is_some() { if exec_model != Some(ep.exec_model) { return Err(Error::MixedExecutionModels(fun_handle)); @@ -819,8 +813,10 @@ impl Writer { if em != spirv::ExecutionModel::GLCompute { writeln!(self.out, "struct {} {{", location_input_name)?; - for &handle in var_inputs.iter() { - let var = &module.global_variables[handle]; + for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { + if var.class != spirv::StorageClass::Input || !usage.contains(crate::GlobalUse::LOAD) { + continue + } // if it's a struct, lift all the built-in contents up to the root let mut ty_handle = var.ty; if GLOBAL_POINTERS { @@ -839,7 +835,7 @@ impl Writer { } } else { if let Some(ref binding@crate::Binding::Location(_)) = var.binding { - let tyvar = TypedGlobalVariable { module, handle, usage: GlobalUse::empty() }; + let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() }; let resolved = options.resolve_binding(binding, in_mode)?; writeln!(self.out, "\t{} [[{}]];", tyvar, resolved)?; } @@ -847,8 +843,10 @@ impl Writer { } writeln!(self.out, "}};")?; writeln!(self.out, "struct {} {{", output_name)?; - for &handle in var_outputs.iter() { - let var = &module.global_variables[handle]; + for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { + if var.class != spirv::StorageClass::Output || !usage.contains(crate::GlobalUse::STORE) { + continue + } // if it's a struct, lift all the built-in contents up to the root let mut ty_handle = var.ty; if GLOBAL_POINTERS { @@ -867,7 +865,7 @@ impl Writer { writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; } } else { - let tyvar = TypedGlobalVariable { module, handle, usage: GlobalUse::empty() }; + let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() }; write!(self.out, "\t{}", tyvar)?; if let Some(ref binding) = var.binding { let resolved = options.resolve_binding(binding, out_mode)?; @@ -885,7 +883,7 @@ impl Writer { writeln!(self.out, "{} void {}(", em_str, fun_name)?; } - for ((handle, var), &usage) in module.global_variables.iter().zip(global_use.iter()) { + for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { if usage.is_empty() || var.class == spirv::StorageClass::Output { continue } diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 7ee620bf8..6e3d54e9f 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -732,22 +732,11 @@ impl> Parser { module.entry_points.reserve(entry_points.len()); for raw in entry_points { - let mut ep = crate::EntryPoint { + module.entry_points.push(crate::EntryPoint { exec_model: raw.exec_model, name: raw.name, function: *self.lookup_function.lookup(raw.function_id)?, - inputs: FastHashSet::default(), - outputs: FastHashSet::default(), - }; - for var_id in raw.variable_ids { - let handle = self.lookup_variable.lookup(var_id)?.handle; - match module.global_variables[handle].class { - spirv::StorageClass::Input => ep.inputs.insert(handle), - spirv::StorageClass::Output => ep.outputs.insert(handle), - other => return Err(Error::InvalidVariableClass(other)), - }; - } - module.entry_points.push(ep); + }); } Ok(module) @@ -1405,6 +1394,7 @@ impl> Parser { } else { Some(self.lookup_type.lookup(result_type)?.handle) }, + global_usage: Vec::new(), local_variables: Arena::new(), expressions: self.make_expression_storage(), body: Vec::new(), @@ -1447,6 +1437,7 @@ impl> Parser { } } // done + fun.global_usage = crate::GlobalUse::scan(&fun.expressions, &fun.body, &module.global_variables); let handle = module.functions.append(fun); self.lookup_function.insert(fun_id, handle); self.lookup_expression.clear(); diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index b05bf8275..7a963b68b 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,7 +1,7 @@ use crate::{ arena::{Arena, Handle}, - proc::{GlobalUse, Typifier, ResolveError}, - FastHashMap, FastHashSet, + proc::{Typifier, ResolveError}, + FastHashMap, }; @@ -1205,12 +1205,15 @@ impl Parser { global_vars: &module.global_variables, })?; // done + let global_usage = crate::GlobalUse::scan(&expressions, &body, &module.global_variables); self.scopes.pop(); + let fun = crate::Function { name: Some(fun_name.to_owned()), control: spirv::FunctionControl::empty(), parameter_types, return_type, + global_usage, local_variables, expressions, body, @@ -1341,43 +1344,13 @@ impl Parser { lexer.expect(Token::Operation('='))?; let fun_ident = lexer.next_ident()?; lexer.expect(Token::Separator(';'))?; - let (fun_handle, function) = module.functions + let (fun_handle, _) = module.functions .iter() .find(|(_, fun)| fun.name.as_ref().map(|s| s.as_str()) == Some(fun_ident)) .ok_or(Error::UnknownFunction(fun_ident))?; - - let uses = GlobalUse::scan(function, &module.global_variables); - let mut inputs = FastHashSet::default(); - let mut outputs = FastHashSet::default(); - for ((handle, var), &usage) in module.global_variables.iter().zip(uses.iter()) { - match var.class { - _ if usage.is_empty() => {} - spirv::StorageClass::Input if usage.contains(GlobalUse::LOAD) => { - inputs.insert(handle); - } - spirv::StorageClass::Output if usage.contains(GlobalUse::STORE) => { - outputs.insert(handle); - } - spirv::StorageClass::Input | - spirv::StorageClass::Output => { - let name = lookup_global_expression - .iter() - .find(|&(_, h)| match *h { - crate::Expression::GlobalVariable(h) => h == handle, - _ => false, - }) - .map(|(name, _)| name) - .unwrap(); - return Err(Error::MutabilityViolation(name)); - } - _ => {} - } - } module.entry_points.push(crate::EntryPoint { exec_model, name: export_name.unwrap_or(fun_ident).to_owned(), - inputs, - outputs, function: fun_handle, }); } diff --git a/src/lib.rs b/src/lib.rs index f7b091958..9260a91e7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -117,6 +117,13 @@ pub enum Binding { Descriptor { set: spirv::Word, binding: spirv::Word }, } +bitflags::bitflags! { + pub struct GlobalUse: u8 { + const LOAD = 0x1; + const STORE = 0x2; + } +} + #[derive(Clone, Debug)] pub struct GlobalVariable { pub name: Option, @@ -271,6 +278,7 @@ pub struct Function { pub control: spirv::FunctionControl, pub parameter_types: Vec>, pub return_type: Option>, + pub global_usage: Vec, pub local_variables: Arena, pub expressions: Arena, pub body: Block, @@ -280,8 +288,6 @@ pub struct Function { pub struct EntryPoint { pub exec_model: spirv::ExecutionModel, pub name: String, - pub inputs: FastHashSet>, - pub outputs: FastHashSet>, pub function: Handle, } diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 2bea51f41..9522ac981 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -2,16 +2,9 @@ use crate::{ arena::{Arena, Handle}, }; -bitflags::bitflags! { - pub struct GlobalUse: u8 { - const LOAD = 0x1; - const STORE = 0x2; - } -} - struct Interface<'a> { expressions: &'a Arena, - uses: Vec, + uses: Vec, } impl<'a> Interface<'a> { @@ -33,7 +26,7 @@ impl<'a> Interface<'a> { } E::FunctionParameter(_) => {}, E::GlobalVariable(handle) => { - self.uses[handle.index()] |= GlobalUse::LOAD; + self.uses[handle.index()] |= crate::GlobalUse::LOAD; } E::LocalVariable(_) => {} E::Load { pointer } => { @@ -117,7 +110,7 @@ impl<'a> Interface<'a> { left = base; } crate::Expression::GlobalVariable(handle) => { - self.uses[handle.index()] |= GlobalUse::STORE; + self.uses[handle.index()] |= crate::GlobalUse::STORE; break; } _ => break, @@ -130,16 +123,17 @@ impl<'a> Interface<'a> { } } -impl GlobalUse { +impl crate::GlobalUse { pub fn scan( - fun: &crate::Function, + expressions: &Arena, + body: &[crate::Statement], globals: &Arena, - ) -> Box<[Self]> { + ) -> Vec { let mut io = Interface { - expressions: &fun.expressions, - uses: vec![GlobalUse::empty(); globals.len()], + expressions, + uses: vec![crate::GlobalUse::empty(); globals.len()], }; - io.collect(&fun.body); - io.uses.into_boxed_slice() + io.collect(body); + io.uses } } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 9aba4f1cf..cb78f765f 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,5 +1,4 @@ mod interface; mod typifier; -pub use interface::GlobalUse; pub use typifier::{ResolveError, Typifier}; From 47d7536f3584691aa8d6a6613c8483e2b2a25ed2 Mon Sep 17 00:00:00 2001 From: Gabriel Majeri Date: Sat, 21 Mar 2020 11:02:34 +0200 Subject: [PATCH 0066/2212] Format `src/arena.rs` --- src/arena.rs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 349887754..0ccf33314 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -1,8 +1,4 @@ -use std::{ - fmt, - hash, - marker::PhantomData, -}; +use std::{fmt, hash, marker::PhantomData}; /// An unique index in the arena array that a handle points to. /// @@ -79,9 +75,7 @@ impl Default for Arena { impl Arena { pub fn new() -> Self { - Arena { - data: Vec::new(), - } + Arena { data: Vec::new() } } pub fn len(&self) -> usize { @@ -107,7 +101,10 @@ impl Arena { /// Adds a value with a check for uniqueness: returns a handle pointing to /// an existing element if its value matches the given one, or adds a new /// element otherwise. - pub fn fetch_or_append(&mut self, value: T) -> Handle where T: PartialEq { + pub fn fetch_or_append(&mut self, value: T) -> Handle + where + T: PartialEq, + { if let Some(index) = self.data.iter().position(|d| d == &value) { Handle::new(index as Index) } else { From f09f87bb253fb94576aca7a5058ab771d89e67f6 Mon Sep 17 00:00:00 2001 From: Gabriel Majeri Date: Sat, 21 Mar 2020 11:03:42 +0200 Subject: [PATCH 0067/2212] Use `NonZeroU32` for handle index --- src/arena.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 0ccf33314..c790ec553 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -1,12 +1,12 @@ -use std::{fmt, hash, marker::PhantomData}; +use std::{fmt, hash, marker::PhantomData, num::NonZeroU32}; /// An unique index in the arena array that a handle points to. /// /// This type is independent of `spirv::Word`. `spirv::Word` is used in data /// representation. It holds a SPIR-V and refers to that instruction. In /// structured representation, we use Handle to refer to an SPIR-V instruction. -/// Index is an implementation detail to Handle. -type Index = u32; +/// `Index` is an implementation detail to `Handle`. +type Index = NonZeroU32; /// A strongly typed reference to a SPIR-V element. pub struct Handle { @@ -43,7 +43,7 @@ impl hash::Hash for Handle { impl Handle { #[cfg(test)] pub const DUMMY: Self = Handle { - index: !0, + index: unsafe { NonZeroU32::new_unchecked(!0) }, marker: PhantomData, }; @@ -54,8 +54,10 @@ impl Handle { } } + /// Returns the zero-based index of this handle. pub fn index(self) -> usize { - self.index as usize + let index = self.index.get() - 1; + index as usize } } @@ -83,17 +85,19 @@ impl Arena { } pub fn iter(&self) -> impl Iterator, &T)> { - self.data - .iter() - .enumerate() - .map(|(i, v)| (Handle::new(i as Index), v)) + self.data.iter().enumerate().map(|(i, v)| { + let position = i + 1; + let index = unsafe { Index::new_unchecked(position as u32) }; + (Handle::new(index), v) + }) } /// Adds a new value to the arena, returning a typed handle. /// /// The value is not linked to any SPIR-V module. pub fn append(&mut self, value: T) -> Handle { - let index = self.data.len() as Index; + let position = self.data.len() + 1; + let index = unsafe { Index::new_unchecked(position as u32) }; self.data.push(value); Handle::new(index) } @@ -106,7 +110,8 @@ impl Arena { T: PartialEq, { if let Some(index) = self.data.iter().position(|d| d == &value) { - Handle::new(index as Index) + let index = unsafe { Index::new_unchecked((index + 1) as u32) }; + Handle::new(index) } else { self.append(value) } @@ -116,7 +121,8 @@ impl Arena { impl std::ops::Index> for Arena { type Output = T; fn index(&self, handle: Handle) -> &T { - &self.data[handle.index as usize] + let index = handle.index.get() - 1; + &self.data[index as usize] } } From 1a1f6a47b06c89abb1dff70326c076f1088964a3 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Fri, 27 Mar 2020 00:58:09 +0100 Subject: [PATCH 0068/2212] add support for ConstantComposite --- src/back/msl.rs | 64 +++++++++++++++++++++++++++++----------------- src/front/spirv.rs | 37 +++++++++++++++++++++++++++ src/front/wgsl.rs | 12 ++++----- src/lib.rs | 12 +-------- 4 files changed, 85 insertions(+), 40 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 7b1d806a9..89beb6e68 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -403,29 +403,7 @@ impl Writer { } } crate::Expression::Constant(handle) => { - let kind = match module.constants[handle].inner { - crate::ConstantInner::Sint(value) => { - write!(self.out, "{}", value)?; - crate::ScalarKind::Sint - } - crate::ConstantInner::Uint(value) => { - write!(self.out, "{}", value)?; - crate::ScalarKind::Uint - } - crate::ConstantInner::Float(value) => { - write!(self.out, "{}", value)?; - if value.fract() == 0.0 { - self.out.write_str(".0")?; - } - crate::ScalarKind::Float - } - crate::ConstantInner::Bool(value) => { - write!(self.out, "{}", value)?; - crate::ScalarKind::Bool - } - }; - let width = 32; //TODO: not sure how to get that... - Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width })) + self.put_constant(handle, module) } crate::Expression::Compose { ty, ref components } => { let inner = &module.types[ty].inner; @@ -601,6 +579,46 @@ impl Writer { } } + fn put_constant<'a>( + &mut self, + handle: Handle, + module: &'a crate::Module, + ) -> Result, Error> { + let constant = &module.constants[handle]; + let ty = &module.types[constant.ty]; + + match constant.inner { + crate::ConstantInner::Sint(value) => { + write!(self.out, "{}", value)?; + } + crate::ConstantInner::Uint(value) => { + write!(self.out, "{}", value)?; + } + crate::ConstantInner::Float(value) => { + write!(self.out, "{}", value)?; + if value.fract() == 0.0 { + self.out.write_str(".0")?; + } + } + crate::ConstantInner::Bool(value) => { + write!(self.out, "{}", value)?; + } + crate::ConstantInner::Composite(ref constituents) => { + let ty_name = ty.name.or_index(constant.ty); + write!(self.out, "{}(", ty_name)?; + for (i, handle) in constituents.iter().enumerate() { + if i != 0 { + write!(self.out, ", ")?; + } + self.put_constant(*handle, module)?; + } + write!(self.out, ")")?; + } + } + + Ok(MaybeOwned::Borrowed(&ty.inner)) + } + fn put_statement<'a>( &mut self, level: Level, diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 6e3d54e9f..3afcb39bf 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -715,6 +715,7 @@ impl> Parser { Op::TypeSampledImage => self.parse_type_sampled_image(inst), Op::TypeSampler => self.parse_type_sampler(inst, &mut module), Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), + Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), Op::Variable => self.parse_variable(inst, &mut module), Op::Function => self.parse_function(inst, &mut module), _ => Err(Error::UnsupportedInstruction(self.state, inst.op)), //TODO @@ -1305,6 +1306,42 @@ impl> Parser { Ok(()) } + fn parse_composite_constant( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect_at_least(3)?; + let type_id = self.next()?; + let type_lookup = self.lookup_type.lookup(type_id)?; + let ty = type_lookup.handle; + + let id = self.next()?; + + let constituents_count = inst.wc - 3; + let mut constituents = Vec::with_capacity(constituents_count as usize); + for _ in 0..constituents_count { + let constituent_id = self.next()?; + let constant = self.lookup_constant.lookup(constituent_id)?; + constituents.push(constant.handle); + } + + self.lookup_constant.insert(id, LookupConstant { + handle: module.constants.append(crate::Constant { + name: self.future_decor + .remove(&id) + .and_then(|dec|dec.name), + specialization: None, + inner: crate::ConstantInner::Composite(constituents), + ty + }), + type_id + }); + + Ok(()) + } + fn parse_variable( &mut self, inst: Instruction, diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 7a963b68b..4cbce2c3e 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -404,16 +404,16 @@ impl Parser { } } - fn get_constant_inner(word: &str) -> Result> { + fn get_constant_inner(word: &str) -> Result<(crate::ConstantInner, crate::ScalarKind), Error<'_>> { if word.contains('.') { word .parse() - .map(crate::ConstantInner::Float) + .map(|f|(crate::ConstantInner::Float(f), crate::ScalarKind::Float)) .map_err(|err| Error::BadFloat(word, err)) } else { word .parse() - .map(crate::ConstantInner::Sint) + .map(|i|(crate::ConstantInner::Sint(i), crate::ScalarKind::Sint)) .map_err(|err| Error::BadInteger(word, err)) } } @@ -436,7 +436,8 @@ impl Parser { } Token::Number(word) => { let _ = lexer.next(); - Self::get_constant_inner(word)? + let (inner, _) = Self::get_constant_inner(word)?; + inner } _ => { let _ty = self.parse_type_decl(lexer, type_arena); @@ -496,8 +497,7 @@ impl Parser { crate::Expression::Constant(handle) } Token::Number(word) => { - let inner = Self::get_constant_inner(word)?; - let kind = inner.scalar_kind(); + let (inner, kind) = Self::get_constant_inner(word)?; let handle = ctx.constants.append(crate::Constant { name: None, specialization: None, diff --git a/src/lib.rs b/src/lib.rs index 9260a91e7..bdaeaca2d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -97,17 +97,7 @@ pub enum ConstantInner { Uint(u64), Float(f64), Bool(bool), -} - -impl ConstantInner { - pub fn scalar_kind(&self) -> ScalarKind { - match *self { - ConstantInner::Sint(_) => ScalarKind::Sint, - ConstantInner::Uint(_) => ScalarKind::Uint, - ConstantInner::Float(_) => ScalarKind::Float, - ConstantInner::Bool(_) => ScalarKind::Bool, - } - } + Composite(Vec>), } #[derive(Clone, Debug, PartialEq)] From 4b686165c290c4fd8c8e96365725750de418d9ce Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Fri, 17 Apr 2020 17:20:15 +0200 Subject: [PATCH 0069/2212] Remove duplicate constants in IR module --- src/front/wgsl.rs | 6 +++--- src/lib.rs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 4cbce2c3e..2ae50f9be 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -467,7 +467,7 @@ impl Parser { return Ok(expr); } Token::Word("true") => { - let handle = ctx.constants.append(crate::Constant { + let handle = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, inner: crate::ConstantInner::Bool(true), @@ -482,7 +482,7 @@ impl Parser { crate::Expression::Constant(handle) } Token::Word("false") => { - let handle = ctx.constants.append(crate::Constant { + let handle = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, inner: crate::ConstantInner::Bool(false), @@ -498,7 +498,7 @@ impl Parser { } Token::Number(word) => { let (inner, kind) = Self::get_constant_inner(word)?; - let handle = ctx.constants.append(crate::Constant { + let handle = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, inner, diff --git a/src/lib.rs b/src/lib.rs index bdaeaca2d..8f97346e2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -83,7 +83,7 @@ pub enum TypeInner { Sampler, } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub struct Constant { pub name: Option, pub specialization: Option, @@ -91,7 +91,7 @@ pub struct Constant { pub ty: Handle, } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum ConstantInner { Sint(i64), Uint(u64), From bce6358eb1026c13d2f1c6d365af37afe8869a86 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 1 May 2020 09:59:37 -0400 Subject: [PATCH 0070/2212] Create .monocodus --- .monocodus | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .monocodus diff --git a/.monocodus b/.monocodus new file mode 100644 index 000000000..59d8a4711 --- /dev/null +++ b/.monocodus @@ -0,0 +1,7 @@ +version: 1.0.0 + +rust: + formatter: + name: rustfmt + ignore_paths: + - ".*" From e2bd93aa21702c7574022b3541167e0fc367b57d Mon Sep 17 00:00:00 2001 From: Paul Kernfeld Date: Mon, 18 May 2020 12:39:03 -0400 Subject: [PATCH 0071/2212] Replace write! with TypedGlobalVariable::try_fmt A step towards #31 --- src/back/msl.rs | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 89beb6e68..70b3e7ed7 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -76,6 +76,7 @@ pub enum Error { InvalidImageFlags(crate::ImageFlags), MutabilityViolation(crate::Handle), BadName(String), + UnexpectedGlobalType(crate::Handle), } impl From for Error { @@ -227,8 +228,9 @@ struct TypedGlobalVariable<'a> { handle: crate::Handle, usage: crate::GlobalUse, } -impl Display for TypedGlobalVariable<'_> { - fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { + +impl<'a> TypedGlobalVariable<'a> { + fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { let var = &self.module.global_variables[self.handle]; let name = var.name.or_index(self.handle); let (space_qualifier, reference) = match var.class { @@ -256,13 +258,13 @@ impl Display for TypedGlobalVariable<'_> { _ => var.ty }; let ty_name = self.module.types[ty_handle].name.or_index(ty_handle); - write!(formatter, "{} {}", ty_name, name) + Ok(write!(formatter, "{} {}", ty_name, name)?) } - _ => panic!("Unexpected global type {:?} = {:?}", var.ty, ty), + _ => Err(Error::UnexpectedGlobalType(var.ty)), } } else { let ty_name = self.module.types[var.ty].name.or_index(var.ty); - write!(formatter, "{}{}{} {}", space_qualifier, ty_name, reference, name) + Ok(write!(formatter, "{}{}{} {}", space_qualifier, ty_name, reference, name)?) } } } @@ -855,7 +857,10 @@ impl Writer { if let Some(ref binding@crate::Binding::Location(_)) = var.binding { let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() }; let resolved = options.resolve_binding(binding, in_mode)?; - writeln!(self.out, "\t{} [[{}]];", tyvar, resolved)?; + + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + writeln!(self.out, " [[{}]];", resolved)?; } } } @@ -884,7 +889,8 @@ impl Writer { } } else { let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() }; - write!(self.out, "\t{}", tyvar)?; + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; if let Some(ref binding) = var.binding { let resolved = options.resolve_binding(binding, out_mode)?; write!(self.out, " [[{}]]", resolved)?; @@ -921,7 +927,9 @@ impl Writer { let resolved = options.resolve_binding(var.binding.as_ref().unwrap(), loc_mode)?; let tyvar = TypedGlobalVariable { module, handle, usage }; let separator = separate(last_used_global == Some(handle)); - writeln!(self.out, "\t{} [[{}]]{}", tyvar, resolved, separator)?; + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + writeln!(self.out, " [[{}]]{}", resolved, separator)?; } } else { let result_type_name = match fun.return_type { From 2a3fc6dc54851f4b8d4026e5df666c43f9723876 Mon Sep 17 00:00:00 2001 From: Paul Kernfeld Date: Tue, 19 May 2020 14:15:41 -0400 Subject: [PATCH 0072/2212] Replace panics with errors in Metal backend Fixes #31 --- src/back/msl.rs | 96 ++++++++++++++++++++++++++++++++----------------- src/lib.rs | 13 ++++--- 2 files changed, 72 insertions(+), 37 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 70b3e7ed7..20eb6a370 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -77,6 +77,22 @@ pub enum Error { MutabilityViolation(crate::Handle), BadName(String), UnexpectedGlobalType(crate::Handle), + UnimplementedBuiltIn(spirv::BuiltIn), + UnimplementedBindTarget(BindTarget), + UnexpectedIndexing(crate::TypeInner), + UnsupportedCompose(crate::Handle), + UnexpectedLoadPointer(crate::TypeInner), + UnsupportedBinaryOp(crate::BinaryOperator), + UnableToInferBinaryOpOutput(crate::TypeInner, crate::BinaryOperator, crate::TypeInner), + UnexpectedImageType(crate::TypeInner), + UnexpectedDistanceArgument(crate::TypeInner), + UnsupportedCall(String), + UnsupportedExpression(crate::Expression), + UnableToReturnValue(crate::Handle), + UnsupportedStatement(crate::Statement), + UnsupportedDim(spirv::Dim), + ExecutionModelReturnType(spirv::ExecutionModel, crate::Handle), + AccessIndexExceedsStaticLength(u32, u32), } impl From for Error { @@ -269,8 +285,8 @@ impl<'a> TypedGlobalVariable<'a> { } } -impl Display for ResolvedBinding { - fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { +impl ResolvedBinding { + fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { match *self { ResolvedBinding::BuiltIn(built_in) => { let name = match built_in { @@ -278,32 +294,40 @@ impl Display for ResolvedBinding { spirv::BuiltIn::GlobalInvocationId => "thread_position_in_grid", spirv::BuiltIn::PointSize => "point_size", spirv::BuiltIn::Position => "position", - _ => panic!("Built in {:?} is not implemented", built_in), + _ => return Err(Error::UnimplementedBuiltIn(built_in)), }; - formatter.write_str(name) + Ok(formatter.write_str(name)?) } ResolvedBinding::Attribute(index) => { - write!(formatter, "attribute({})", index) + Ok(write!(formatter, "attribute({})", index)?) } ResolvedBinding::Color(index) => { - write!(formatter, "color({})", index) + Ok(write!(formatter, "color({})", index)?) } ResolvedBinding::User { prefix, index } => { - write!(formatter, "user({}{})", prefix, index) + Ok(write!(formatter, "user({}{})", prefix, index)?) } ResolvedBinding::Resource(ref target) => { if let Some(id) = target.buffer { - write!(formatter, "buffer({})", id) + Ok(write!(formatter, "buffer({})", id)?) } else if let Some(id) = target.texture { - write!(formatter, "texture({})", id) + Ok(write!(formatter, "texture({})", id)?) } else if let Some(id) = target.sampler { - write!(formatter, "sampler({})", id) + Ok(write!(formatter, "sampler({})", id)?) } else { - unimplemented!() + Err(Error::UnimplementedBindTarget(target.clone())) } } } } + + fn try_fmt_decorated(&self, formatter: &mut W, terminator: &str) -> Result<(), Error> { + formatter.write_str(" [[")?; + self.try_fmt(formatter)?; + formatter.write_str("]]")?; + formatter.write_str(terminator)?; + Ok(()) + } } pub struct Writer { @@ -375,7 +399,7 @@ impl Writer { self.out.write_str("]")?; Ok(module.borrow_type(base)) } - ref other => panic!("Unexpected indexing of {:?}", other), + ref other => Err(Error::UnexpectedIndexing(other.clone())), } } crate::Expression::AccessIndex { base, index } => { @@ -396,12 +420,12 @@ impl Writer { } crate::TypeInner::Array { base, size } => { if let crate::ArraySize::Static(length) = size { - assert!(index < length); + return Err(Error::AccessIndexExceedsStaticLength(index, length)); } write!(self.out, "[{}]", index)?; Ok(module.borrow_type(base)) } - ref other => panic!("Unexpected indexing of {:?}", other), + ref other => Err(Error::UnexpectedIndexing(other.clone())), } } crate::Expression::Constant(handle) => { @@ -420,7 +444,7 @@ impl Writer { } write!(self.out, ")")?; } - _ => panic!("Unsupported compose {:?}", ty), + _ => return Err(Error::UnsupportedCompose(ty)), } Ok(MaybeOwned::Borrowed(inner)) } @@ -467,7 +491,7 @@ impl Writer { crate::TypeInner::Pointer { base, .. } => { Ok(module.borrow_type(base)) } - ref other => panic!("Unexpected load pointer {:?}", other), + ref other => Err(Error::UnexpectedLoadPointer(other.clone())), } } crate::Expression::Unary { op, expr } => { @@ -491,7 +515,7 @@ impl Writer { crate::BinaryOperator::LessEqual => "<=", crate::BinaryOperator::Greater => "==", crate::BinaryOperator::GreaterEqual => ">=", - _ => panic!("Unsupported binary op {:?}", op), + other => return Err(Error::UnsupportedBinaryOp(other)), }; //write!(self.out, "(")?; let ty_left = self.put_expression(left, function, module)?; @@ -507,7 +531,8 @@ impl Writer { (&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Scalar { .. }) | (&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Vector { .. }) => MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), - other => panic!("Unable to infer {:?} for {:?}", op, other), + (other_left, other_right) => + return Err(Error::UnableToInferBinaryOpOutput(other_left.clone(), op, other_right.clone())), } } else { MaybeOwned::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1 }) @@ -522,7 +547,7 @@ impl Writer { write!(self.out, ")")?; match *ty_image.borrow() { crate::TypeInner::Image { base, .. } => Ok(module.borrow_type(base)), - ref other => panic!("Unexpected image type {:?}", other), + ref other => Err(Error::UnexpectedImageType(other.clone())), } } crate::Expression::Call { ref name, ref arguments } => { @@ -557,7 +582,7 @@ impl Writer { write!(self.out, "distance(")?; let result = match *self.put_expression(arguments[0], function, module)?.borrow() { crate::TypeInner::Vector { kind, width, .. } => crate::TypeInner::Scalar { kind, width }, - ref other => panic!("Unexpected distance argument {:?}", other), + ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())), }; write!(self.out, ", ")?; self.put_expression(arguments[1], function, module)?; @@ -568,16 +593,16 @@ impl Writer { write!(self.out, "length(")?; let result = match *self.put_expression(arguments[0], function, module)?.borrow() { crate::TypeInner::Vector { kind, width, .. } => crate::TypeInner::Scalar { kind, width }, - ref other => panic!("Unexpected distance argument {:?}", other), + ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())), }; write!(self.out, ")")?; Ok(MaybeOwned::Owned(result)) } - _ => panic!("Unsupported call to '{}'", name), + other => Err(Error::UnsupportedCall(other.to_owned())), } } - ref other => panic!("Unsupported {:?}", other), + ref other => Err(Error::UnsupportedExpression(other.clone())), } } @@ -677,7 +702,7 @@ impl Writer { None if has_output => self.out.write_str(OUTPUT_STRUCT_NAME)?, None => {} Some(expr_handle) if has_output => { - panic!("Unable to return value {:?} from an entry point!", expr_handle) + return Err(Error::UnableToReturnValue(expr_handle)); } Some(expr_handle) => { self.put_expression(expr_handle, function, module)?; @@ -685,7 +710,7 @@ impl Writer { } writeln!(self.out, ";")?; } - _ => panic!("Unsupported {:?}", statement), + ref other => return Err(Error::UnsupportedStatement(other.clone())), }; Ok(()) } @@ -747,7 +772,7 @@ impl Writer { write!(self.out, "\t{} {}", base_name, name)?; if let Some(ref binding) = member.binding { let resolved = options.resolve_binding(binding, LocationMode::Intermediate)?; - write!(self.out, " [[{}]]", resolved)?; + resolved.try_fmt_decorated(&mut self.out, "")?; } writeln!(self.out, ";")?; } @@ -760,7 +785,7 @@ impl Writer { spirv::Dim::Dim2D => "2d", spirv::Dim::Dim3D => "3d", spirv::Dim::DimCube => "Cube", - _ => panic!("Unsupported dim {:?}", dim), + other => return Err(Error::UnsupportedDim(other)), }; let access = if flags.contains(crate::ImageFlags::SAMPLED) { if flags.intersects(crate::ImageFlags::CAN_STORE) { @@ -822,7 +847,9 @@ impl Writer { // make dedicated input/output structs if let Some(em) = exec_model { - assert_eq!(fun.return_type, None); + if let Some(return_type) = fun.return_type { + return Err(Error::ExecutionModelReturnType(em, return_type)) + } let (em_str, in_mode, out_mode) = match em { spirv::ExecutionModel::Vertex => ("vertex", LocationMode::VertexInput, LocationMode::Intermediate), spirv::ExecutionModel::Fragment => ("fragment", LocationMode::Intermediate, LocationMode::FragmentOutput), @@ -850,7 +877,8 @@ impl Writer { let name = member.name.or_index(MemberIndex(index)); let ty_name = module.types[member.ty].name.or_index(member.ty); let resolved = options.resolve_binding(binding, in_mode)?; - writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; + write!(self.out, "\t{} {}", ty_name, name)?; + resolved.try_fmt_decorated(&mut self.out, ";\n")?; } } } else { @@ -860,7 +888,7 @@ impl Writer { write!(self.out, "\t")?; tyvar.try_fmt(&mut self.out)?; - writeln!(self.out, " [[{}]];", resolved)?; + resolved.try_fmt_decorated(&mut self.out, ";\n")?; } } } @@ -885,7 +913,8 @@ impl Writer { .as_ref() .ok_or(Error::MissingBinding(handle))?; let resolved = options.resolve_binding(binding, out_mode)?; - writeln!(self.out, "\t{} {} [[{}]];", ty_name, name, resolved)?; + write!(self.out, "\t{} {}", ty_name, name)?; + resolved.try_fmt_decorated(&mut self.out, ";\n")?; } } else { let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() }; @@ -893,7 +922,7 @@ impl Writer { tyvar.try_fmt(&mut self.out)?; if let Some(ref binding) = var.binding { let resolved = options.resolve_binding(binding, out_mode)?; - write!(self.out, " [[{}]]", resolved)?; + resolved.try_fmt_decorated(&mut self.out, "")?; } writeln!(self.out, ";")?; } @@ -929,7 +958,8 @@ impl Writer { let separator = separate(last_used_global == Some(handle)); write!(self.out, "\t")?; tyvar.try_fmt(&mut self.out)?; - writeln!(self.out, " [[{}]]{}", resolved, separator)?; + resolved.try_fmt_decorated(&mut self.out, separator)?; + writeln!(self.out)?; } } else { let result_type_name = match fun.return_type { diff --git a/src/lib.rs b/src/lib.rs index 8f97346e2..985f84343 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -48,7 +48,8 @@ pub enum ArraySize { Dynamic, } -#[derive(Debug, PartialEq)] +// Clone is used only for error reporting and is not intended for end users +#[derive(Clone, Debug, PartialEq)] pub struct StructMember { pub name: Option, pub binding: Option, @@ -71,7 +72,8 @@ pub struct Type { pub inner: TypeInner, } -#[derive(Debug, PartialEq)] +// Clone is used only for error reporting and is not intended for end users +#[derive(Clone, Debug, PartialEq)] pub enum TypeInner { Scalar { kind: ScalarKind, width: Bytes }, Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, @@ -228,10 +230,13 @@ pub enum Expression { } pub type Block = Vec; -#[derive(Debug)] + +// Clone is used only for error reporting and is not intended for end users +#[derive(Clone, Debug)] pub struct FallThrough; -#[derive(Debug)] +// Clone is used only for error reporting and is not intended for end users +#[derive(Clone, Debug)] pub enum Statement { Empty, Block(Block), From b108a50089d1f66e9f788298be9f83e05c163721 Mon Sep 17 00:00:00 2001 From: Paul Kernfeld Date: Fri, 22 May 2020 12:30:30 -0400 Subject: [PATCH 0073/2212] Check constant types (#54) * Check constant types A baby step towards #43 * Move tp src/proc/typifier, remove unneeded return * Don't do pub(crate) * Don't use crate::proc::UnexpectedConstantTypeError Co-authored-by: Paul Kernfeld --- src/front/wgsl.rs | 23 +++++++++++++++++++++++ src/lib.rs | 3 ++- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 2ae50f9be..5e7ac351d 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -142,6 +142,7 @@ mod lex { #[derive(Debug)] pub enum Error<'a> { Unexpected(Token<'a>), + UnexpectedConstantType(crate::proc::UnexpectedConstantTypeError), BadInteger(&'a str, std::num::ParseIntError), BadFloat(&'a str, std::num::ParseFloatError), BadAccessor(&'a str), @@ -158,6 +159,12 @@ pub enum Error<'a> { Other, } +impl<'a> From for Error<'a> { + fn from(error: crate::proc::UnexpectedConstantTypeError) -> Self { + Error::UnexpectedConstantType(error) + } +} + #[derive(Clone)] struct Lexer<'a> { input: &'a str, @@ -1300,6 +1307,7 @@ impl Parser { lexer.expect(Token::Operation('='))?; let inner = self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; lexer.expect(Token::Separator(';'))?; + crate::proc::check_constant_types(&inner, &module.types[ty].inner)?; let const_handle = module.constants.append(crate::Constant { name: Some(name.to_owned()), specialization: None, @@ -1400,3 +1408,18 @@ impl Parser { pub fn parse_str(source: &str) -> Result { Parser::new().parse(source) } + +#[cfg(test)] +mod tests { + #[test] + fn check_constant_type_scalar_ok() { + let wgsl = "const a : i32 = 2;"; + assert!(super::parse_str(wgsl).is_ok()); + } + + #[test] + fn check_constant_type_scalar_err() { + let wgsl = "const a : i32 = 2.0;"; + assert!(super::parse_str(wgsl).is_err()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 985f84343..794c4212c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -93,7 +93,8 @@ pub struct Constant { pub ty: Handle, } -#[derive(Debug, PartialEq)] +// Clone is used only for error reporting and is not intended for end users +#[derive(Clone, Debug, PartialEq)] pub enum ConstantInner { Sint(i64), Uint(u64), diff --git a/src/proc/mod.rs b/src/proc/mod.rs index cb78f765f..dc2dd64b4 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,4 +1,4 @@ mod interface; mod typifier; -pub use typifier::{ResolveError, Typifier}; +pub use typifier::{ResolveError, Typifier, UnexpectedConstantTypeError, check_constant_types}; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 700a6b32f..e5965312c 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -153,3 +153,38 @@ impl Typifier { }) } } + +#[derive(Debug)] +pub struct UnexpectedConstantTypeError(crate::ConstantInner, crate::TypeInner); + +pub fn check_constant_types( + inner: &crate::ConstantInner, + type_inner: &crate::TypeInner +) -> Result<(), UnexpectedConstantTypeError> { + match (inner, type_inner) { + ( + crate::ConstantInner::Sint(_), + crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width: _ }, + ) => Ok(()), + ( + crate::ConstantInner::Uint(_), + crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width: _ }, + ) => Ok(()), + ( + crate::ConstantInner::Float(_), + crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: _ }, + ) => Ok(()), + ( + crate::ConstantInner::Bool(_), + crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: _ }, + ) => Ok(()), + ( + crate::ConstantInner::Composite(_inner), + _ + ) => Ok(()), // TODO recursively check composite types + (other_inner, other_type_inner) => Err(UnexpectedConstantTypeError( + other_inner.clone(), + other_type_inner.clone(), + )), + } +} From 706a88e21c9de00d4e3ef5bd591d5169bc94f982 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 8 Jun 2020 21:00:46 +0100 Subject: [PATCH 0074/2212] Fix clippy errors (#62) * Move from travis to github actions (#58) * Added github actions * Remove travis * Fixed clippy warnings * Add the clippy check to ci * Move workflows to .github * Fix missing clippy --- .github/workflows/pipeline.yml | 32 ++++++++++++++++++++++++++++++++ .travis.yml | 1 - src/back/msl.rs | 18 +++++++----------- src/front/spirv.rs | 25 +++++++++++++------------ src/front/wgsl.rs | 6 +++--- 5 files changed, 55 insertions(+), 27 deletions(-) create mode 100644 .github/workflows/pipeline.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml new file mode 100644 index 000000000..d455eeeb1 --- /dev/null +++ b/.github/workflows/pipeline.yml @@ -0,0 +1,32 @@ +name: pipeline +on: [push, pull_request] + +jobs: + test: + name: Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + - uses: actions-rs/cargo@v1 + with: + command: test + clippy: + name: Clippy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + - run: rustup component add clippy + - uses: actions-rs/cargo@v1 + with: + command: clippy + args: -- -D warnings diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 22761ba7e..000000000 --- a/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: rust diff --git a/src/back/msl.rs b/src/back/msl.rs index 20eb6a370..a2086ef7f 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -460,10 +460,8 @@ impl Writer { return Ok(MaybeOwned::Borrowed(base_inner)); } } - } else { - if let crate::TypeInner::Struct { .. } = *inner { + } else if let crate::TypeInner::Struct { .. } = *inner { return Ok(MaybeOwned::Borrowed(inner)); - } } write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; } @@ -881,15 +879,13 @@ impl Writer { resolved.try_fmt_decorated(&mut self.out, ";\n")?; } } - } else { - if let Some(ref binding@crate::Binding::Location(_)) = var.binding { - let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() }; - let resolved = options.resolve_binding(binding, in_mode)?; + } else if let Some(ref binding@crate::Binding::Location(_)) = var.binding { + let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() }; + let resolved = options.resolve_binding(binding, in_mode)?; - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - resolved.try_fmt_decorated(&mut self.out, ";\n")?; - } + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + resolved.try_fmt_decorated(&mut self.out, ";\n")?; } } writeln!(self.out, "}};")?; diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 3afcb39bf..142d00576 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -763,7 +763,7 @@ impl> Parser { return Err(Error::InvalidOperand); } if !SUPPORTED_EXTENSIONS.contains(&name.as_str()) { - return Err(Error::UnsupportedExtension(name.to_owned())); + return Err(Error::UnsupportedExtension(name)); } Ok(()) } @@ -777,7 +777,7 @@ impl> Parser { return Err(Error::InvalidOperand); } if !SUPPORTED_EXT_SETS.contains(&name.as_str()) { - return Err(Error::UnsupportedExtSet(name.to_owned())); + return Err(Error::UnsupportedExtSet(name)); } Ok(()) } @@ -804,7 +804,7 @@ impl> Parser { let (name, left) = self.next_string(inst.wc - 3)?; let ep = EntryPoint { exec_model, - name: name.to_owned(), + name, function_id, variable_ids: self.data .by_ref() @@ -852,7 +852,7 @@ impl> Parser { self.future_decor .entry(id) .or_default() - .name = Some(name.to_owned()); + .name = Some(name); Ok(()) } @@ -868,7 +868,7 @@ impl> Parser { self.future_member_decor .entry((id, member)) .or_default() - .name = Some(name.to_owned()); + .name = Some(name); Ok(()) } @@ -1266,14 +1266,15 @@ impl> Parser { crate::ConstantInner::Uint((u64::from(high) << 32) | u64::from(low)) } crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width } => { + use std::cmp::Ordering; let low = self.next()?; - let high = if width < 32 { - return Err(Error::InvalidTypeWidth(u32::from(width))); - } else if width > 32 { - inst.expect(4)?; - self.next()? - } else { - !0 + let high = match width.cmp(&32) { + Ordering::Less => return Err(Error::InvalidTypeWidth(u32::from(width))), + Ordering::Greater => { + inst.expect(4)?; + self.next()? + }, + Ordering::Equal => !0 }; crate::ConstantInner::Sint(((u64::from(high) << 32) | u64::from(low)) as i64) } diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 5e7ac351d..22cbc4eea 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -521,7 +521,7 @@ impl Parser { self.scopes.pop(); return Ok(*handle); } - if self.std_namespace.as_ref().map(|s| s.as_str()) == Some(word) { + if self.std_namespace.as_deref() == Some(word) { lexer.expect(Token::DoubleColon)?; let name = lexer.next_ident()?; let mut arguments = Vec::new(); @@ -575,7 +575,7 @@ impl Parser { crate::TypeInner::Struct { ref members } => { let index = members .iter() - .position(|m| m.name.as_ref().map(|s| s.as_str()) == Some(name)) + .position(|m| m.name.as_deref() == Some(name)) .ok_or(Error::BadAccessor(name))? as u32; crate::Expression::AccessIndex { base: handle, @@ -1354,7 +1354,7 @@ impl Parser { lexer.expect(Token::Separator(';'))?; let (fun_handle, _) = module.functions .iter() - .find(|(_, fun)| fun.name.as_ref().map(|s| s.as_str()) == Some(fun_ident)) + .find(|(_, fun)| fun.name.as_deref() == Some(fun_ident)) .ok_or(Error::UnknownFunction(fun_ident))?; module.entry_points.push(crate::EntryPoint { exec_model, From b91b9ca987993f2e0f7fc62a860f851c6574485b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 9 Jun 2020 18:43:16 +0100 Subject: [PATCH 0075/2212] Glsl frontend (#50) * Basic glsl support * Miscellaneous fixes and vertex shader works * Added rudimentary texture and sampler support * Basic preprocessor * Added preprocessor if macros * Pass tests and handle floats correctly * Fix preprocessor if wrong precedence ordering when using macros Refractor for the glsl parser Partial primary expression parser * Fix all clippy errors * Cleanup * Rollback formatting changes in lib.rs --- .github/workflows/pipeline.yml | 3 +- Cargo.toml | 4 + src/front/glsl.rs | 1262 ++++++++++++++++++ src/front/glsl/helpers.rs | 284 +++++ src/front/glsl/parser.rs | 246 ++++ src/front/glsl/parser/lex.rs | 254 ++++ src/front/glsl/preprocessor.rs | 1618 ++++++++++++++++++++++++ src/front/mod.rs | 2 + src/front/wgsl.rs | 2 +- src/lib.rs | 5 +- src/proc/typifier.rs | 196 +-- test-data/glsl_if_preprocessor.vert | 14 + test-data/glsl_phong_lighting.frag | 56 + test-data/glsl_preprocessor_abuse.vert | 11 + test-data/glsl_vertex_test_shader.vert | 29 + 15 files changed, 3907 insertions(+), 79 deletions(-) create mode 100644 src/front/glsl.rs create mode 100644 src/front/glsl/helpers.rs create mode 100644 src/front/glsl/parser.rs create mode 100644 src/front/glsl/parser/lex.rs create mode 100644 src/front/glsl/preprocessor.rs create mode 100644 test-data/glsl_if_preprocessor.vert create mode 100644 test-data/glsl_phong_lighting.frag create mode 100644 test-data/glsl_preprocessor_abuse.vert create mode 100644 test-data/glsl_vertex_test_shader.vert diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index d455eeeb1..d896407c6 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -15,6 +15,7 @@ jobs: - uses: actions-rs/cargo@v1 with: command: test + args: --all-features clippy: name: Clippy runs-on: ubuntu-latest @@ -29,4 +30,4 @@ jobs: - uses: actions-rs/cargo@v1 with: command: clippy - args: -- -D warnings + args: --all-features -- -D warnings diff --git a/Cargo.toml b/Cargo.toml index fb5a16443..48dc52968 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,10 @@ fxhash = "0.2" log = "0.4" num-traits = "0.2" spirv = { package = "spirv_headers", version = "1" } +glsl = { version = "4", optional = true } + +[features] +glsl_preprocessor = ["glsl"] [dev-dependencies] env_logger = "0.6" diff --git a/src/front/glsl.rs b/src/front/glsl.rs new file mode 100644 index 000000000..1fe3b215f --- /dev/null +++ b/src/front/glsl.rs @@ -0,0 +1,1262 @@ +use crate::{ + Arena, ArraySize, BinaryOperator, Binding, Constant, ConstantInner, EntryPoint, Expression, + FastHashMap, Function, GlobalVariable, Handle, Header, LocalVariable, Module, ScalarKind, + StructMember, Type, TypeInner, VectorSize, +}; +use glsl::{ + parser::{Parse, ParseError}, + syntax::*, +}; +use parser::{Token, TokenMetadata}; +use spirv::{BuiltIn, ExecutionModel, StorageClass}; +use std::fmt; + +mod helpers; +mod parser; + +#[derive(Debug)] +pub enum ErrorKind { + UnexpectedToken { + expected: Vec, + got: TokenMetadata, + }, + UnexpectedWord { + expected: Vec<&'static str>, + got: String, + }, + ExpectedEOL { + got: TokenMetadata, + }, + UnknownPragma { + pragma: String, + }, + ExtensionNotSupported { + extension: String, + }, + AllExtensionsEnabled, + ExtensionUnknownBehavior { + behavior: String, + }, + UnsupportedVersion { + version: usize, + }, + UnsupportedProfile { + profile: String, + }, + UnknownProfile { + profile: String, + }, + UnknownPreprocessorDirective { + directive: String, + }, + UnboundedIfCloserOrVariant { + token: TokenMetadata, + }, + NonIntegralType { + token: TokenMetadata, + }, + ReservedMacro, + EOL, + EOF, +} + +impl fmt::Display for ErrorKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ErrorKind::UnexpectedToken { expected, got } => write!( + f, + "Unexpected token:\nexpected: {}\ngot: {}", + expected + .iter() + .map(|token| { + let mut type_string = token.type_to_string(); + type_string.push_str(" |"); + type_string + }) + .collect::(), + got.token + ), + ErrorKind::UnexpectedWord { expected, got } => write!( + f, + "Unexpected word:\nexpected: {}\ngot: {}", + expected.iter().fold(String::new(), |mut acc, word| { + acc.push_str(*word); + + acc.push_str("|"); + + acc + }), + got + ), + ErrorKind::ExpectedEOL { got } => { + write!(f, "Expected end of line:\ngot: {}", got.token) + } + ErrorKind::UnknownPragma { pragma } => write!(f, "Unknown pragma: {}", pragma), + ErrorKind::ExtensionNotSupported { extension } => { + write!(f, "The extension \"{}\" is not supported", extension) + } + ErrorKind::AllExtensionsEnabled => { + write!(f, "All extensions can't be require or enable") + } + ErrorKind::ExtensionUnknownBehavior { behavior } => write!( + f, + "The extension behavior must be one of require|enable|warn|disable got: {}", + behavior + ), + ErrorKind::UnsupportedVersion { version } => write!( + f, + "The version {} isn't supported use either 450 or 460", + version + ), + ErrorKind::UnsupportedProfile { profile } => { + write!(f, "The profile {} isn't supported use core", profile) + } + ErrorKind::UnknownProfile { profile } => { + write!(f, "The profile {} isn't defined use core", profile) + } + ErrorKind::UnknownPreprocessorDirective { directive } => { + write!(f, "The preprocessor directive {} isn't defined", directive) + } + ErrorKind::UnboundedIfCloserOrVariant { token } => { + write!(f, "The preprocessor directives \"else\", \"elif\" or \"endif\" must be preceded by an \"if\", token: {}", token.token) + } + ErrorKind::NonIntegralType { token } => { + write!(f, "The preprocessor \"if\" directive can only contain integrals found: {}", token.token) + } + ErrorKind::ReservedMacro => write!(f, "Macro can't begin with GL_"), + ErrorKind::EOL => write!(f, "End of line"), + ErrorKind::EOF => write!(f, "End of file"), + } + } +} + +#[derive(Debug)] +pub struct Error { + pub kind: ErrorKind, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self) + } +} + +impl std::error::Error for Error {} + +#[derive(Debug, Copy, Clone)] +enum Global { + Variable(Handle), + StructShorthand(Handle, u32), +} + +struct Parser<'a> { + source: &'a str, + types: Arena, + globals: Arena, + globals_lookup: FastHashMap, + constants: Arena, + functions: Arena, + function_lookup: FastHashMap>, + exec_model: ExecutionModel, +} + +impl<'a> Parser<'a> { + pub fn new(source: &'a str, exec_model: ExecutionModel) -> Result { + Ok(Self { + source, + types: Arena::new(), + globals: Arena::new(), + globals_lookup: FastHashMap::default(), + constants: Arena::new(), + functions: Arena::new(), + function_lookup: FastHashMap::default(), + exec_model, + }) + } + + pub fn parse(mut self, entry: String) -> Result { + let ast = TranslationUnit::parse(self.source)?; + + //println!("{:#?}", ast); + + let mut entry_point = None; + + for declaration in ast { + match declaration { + ExternalDeclaration::Preprocessor(_) => + { + #[cfg(feature = "glsl_preprocessor")] + unreachable!() + } + ExternalDeclaration::FunctionDefinition(function) => { + let function = self.parse_function_definition(function); + + if *self.functions[function].name.as_ref().unwrap() == entry { + assert!(entry_point.is_none()); + + entry_point = Some(function); + } + } + ExternalDeclaration::Declaration(decl) => match decl { + Declaration::InitDeclaratorList(init) => { + let handle = self.parse_global(init); + let name = self.globals[handle].name.clone().unwrap(); + self.globals_lookup.insert(name, Global::Variable(handle)); + } + Declaration::Block(block) => { + let (class, binding) = Self::parse_type_qualifier(block.qualifier); + let ty_name = block.name.0; + + let name = block.identifier.clone().map(|ident| ident.ident.0); + + let mut fields = Vec::new(); + let mut reexports = Vec::new(); + let mut index = 0; + + for field in block.fields { + let binding = field + .qualifier + .and_then(|qualifier| Self::parse_type_qualifier(qualifier).1); + + let ty = self.parse_type(field.ty).unwrap(); + + for ident in field.identifiers { + let field_name = ident.ident.0; + + fields.push(StructMember { + name: Some(field_name.clone()), + binding: binding.clone(), + ty: if let Some(array_spec) = ident.array_spec { + self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size: match array_spec { + ArraySpecifier::Unsized => ArraySize::Dynamic, + ArraySpecifier::ExplicitlySized(_expr) => { + unimplemented!() + } + }, + }, + }) + } else { + ty + }, + }); + + if name.is_none() { + reexports.push((field_name, index)); + index += 1; + } + } + } + + let ty = if let Some(array_spec) = + block.identifier.and_then(|ident| ident.array_spec) + { + let base = self.types.fetch_or_append(Type { + name: Some(ty_name), + inner: TypeInner::Struct { members: fields }, + }); + + self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base, + size: match array_spec { + ArraySpecifier::Unsized => ArraySize::Dynamic, + ArraySpecifier::ExplicitlySized(_expr) => unimplemented!(), + }, + }, + }) + } else { + self.types.fetch_or_append(Type { + name: Some(ty_name), + inner: TypeInner::Struct { members: fields }, + }) + }; + + let handle = self.globals.append(GlobalVariable { + binding, + class, + name, + ty, + }); + + for (name, index) in reexports { + self.globals_lookup + .insert(name, Global::StructShorthand(handle, index)); + } + } + _ => unimplemented!(), + }, + } + } + + Ok(Module { + header: Header { + version: (1, 0, 0), + generator: 0, + }, + types: self.types, + constants: self.constants, + global_variables: self.globals, + functions: self.functions, + entry_points: vec![EntryPoint { + exec_model: self.exec_model, + function: entry_point.unwrap(), + name: entry, + }], + }) + } + + fn parse_function_definition(&mut self, function: FunctionDefinition) -> Handle { + let name = function.prototype.name.0; + + // Parse return type + let ty = self.parse_type(function.prototype.ty.ty); + + let mut parameter_types = Vec::with_capacity(function.prototype.parameters.len()); + let mut parameter_lookup = FastHashMap::default(); + + let mut local_variables = Arena::::new(); + let mut locals_map = FastHashMap::default(); + let mut expressions = Arena::::new(); + let mut body = Vec::new(); + + // TODO: Parse Qualifiers + for (index, parameter) in function.prototype.parameters.into_iter().enumerate() { + match parameter { + FunctionParameterDeclaration::Named(_ /* TODO */, decl) => { + let ty = self.parse_type(decl.ty).unwrap(); + + let ty = if let Some(specifier) = decl.ident.array_spec { + match specifier { + ArraySpecifier::Unsized => self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size: ArraySize::Dynamic, + }, + }), + ArraySpecifier::ExplicitlySized(_) => unimplemented!(), + } + } else { + ty + }; + + parameter_types.push(ty); + parameter_lookup.insert( + decl.ident.ident.0, + Expression::FunctionParameter(index as u32), + ); + } + FunctionParameterDeclaration::Unnamed(_, ty) => { + parameter_types.push(self.parse_type(ty).unwrap()); + } + } + } + + for statement in function.statement.statement_list { + match statement { + Statement::Compound(_) => unimplemented!(), + Statement::Simple(statement) => match *statement { + SimpleStatement::Declaration(declaration) => match declaration { + Declaration::InitDeclaratorList(init) => { + self.parse_local_variable( + init, + &mut expressions, + &mut local_variables, + &mut locals_map, + ¶meter_lookup, + ); + } + _ => unimplemented!(), + }, + SimpleStatement::Expression(expr) => { + let expr = match expr { + Some(expr) => expr, + None => continue, + }; + + body.push(self.parse_statement( + expr, + &mut expressions, + &mut local_variables, + &mut locals_map, + ¶meter_lookup, + )); + } + SimpleStatement::Selection(_) => unimplemented!(), + SimpleStatement::Switch(_) => unimplemented!(), + SimpleStatement::CaseLabel(_) => unimplemented!(), + SimpleStatement::Iteration(_) => unimplemented!(), + SimpleStatement::Jump(op) => body.push(match op { + JumpStatement::Continue => crate::Statement::Continue, + JumpStatement::Break => crate::Statement::Break, + JumpStatement::Return(expr) => crate::Statement::Return { + value: expr.map(|expr| { + let expr = self.parse_expression( + *expr, + &mut expressions, + &mut local_variables, + &mut locals_map, + ¶meter_lookup, + ); + expressions.append(expr) + }), + }, + JumpStatement::Discard => crate::Statement::Kill, + }), + }, + } + } + + let handle = self.functions.append(Function { + name: Some(name.clone()), + control: spirv::FunctionControl::NONE, + parameter_types, + return_type: ty, + global_usage: vec![], + local_variables, + expressions, + body, + }); + + self.function_lookup.insert(name, handle); + + handle + } + + fn parse_local_variable( + &mut self, + init: InitDeclaratorList, + expressions: &mut Arena, + locals: &mut Arena, + locals_map: &mut FastHashMap>, + parameter_lookup: &FastHashMap, + ) -> Handle { + let name = init.head.name.map(|d| d.0); + let ty = { + let ty = self.parse_type(init.head.ty.ty).unwrap(); + + if let Some(specifier) = init.head.array_specifier { + match specifier { + ArraySpecifier::Unsized => self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size: ArraySize::Dynamic, + }, + }), + ArraySpecifier::ExplicitlySized(_) => unimplemented!(), + } + } else { + ty + } + }; + + let initializer = init.head.initializer.map(|initializer| { + self.parse_initializer( + initializer, + expressions, + locals, + locals_map, + parameter_lookup, + ) + }); + + let handle = locals.append(LocalVariable { + name: name.clone(), + ty, + init: initializer, + }); + + locals_map.insert(name.unwrap(), handle); + + handle + } + + fn parse_initializer( + &mut self, + initializer: Initializer, + expressions: &mut Arena, + locals: &mut Arena, + locals_map: &mut FastHashMap>, + parameter_lookup: &FastHashMap, + ) -> Handle { + match initializer { + Initializer::Simple(expr) => { + let handle = + self.parse_expression(*expr, expressions, locals, locals_map, parameter_lookup); + + expressions.append(handle) + } + Initializer::List(_exprs) => unimplemented!(), + } + } + + fn parse_statement( + &mut self, + expr: Expr, + expressions: &mut Arena, + locals: &mut Arena, + locals_map: &mut FastHashMap>, + parameter_lookup: &FastHashMap, + ) -> crate::Statement { + match expr { + Expr::Assignment(reg, op, value) => { + let pointer = { + let pointer = self.parse_expression( + *reg, + expressions, + locals, + locals_map, + parameter_lookup, + ); + expressions.append(pointer) + }; + + let right = self.parse_expression( + *value, + expressions, + locals, + locals_map, + parameter_lookup, + ); + let value = match op { + AssignmentOp::Equal => right, + AssignmentOp::Mult => Expression::Binary { + op: BinaryOperator::Multiply, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Div => Expression::Binary { + op: BinaryOperator::Divide, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Mod => Expression::Binary { + op: BinaryOperator::Modulo, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Add => Expression::Binary { + op: BinaryOperator::Add, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Sub => Expression::Binary { + op: BinaryOperator::Subtract, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::LShift => Expression::Binary { + op: BinaryOperator::ShiftLeftLogical, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::RShift => { + Expression::Binary { + op: BinaryOperator::ShiftRightArithmetic, /* ??? */ + left: pointer, + right: expressions.append(right), + } + } + AssignmentOp::And => Expression::Binary { + op: BinaryOperator::And, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Xor => Expression::Binary { + op: BinaryOperator::ExclusiveOr, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Or => Expression::Binary { + op: BinaryOperator::InclusiveOr, + left: pointer, + right: expressions.append(right), + }, + }; + + crate::Statement::Store { + pointer, + value: expressions.append(value), + } + } + Expr::FunCall(_, _) => unimplemented!(), + Expr::PostInc(_) => unimplemented!(), + Expr::PostDec(_) => unimplemented!(), + _ => panic!(), + } + } + + fn parse_expression( + &mut self, + expr: Expr, + expressions: &mut Arena, + locals: &mut Arena, + locals_map: &mut FastHashMap>, + parameter_lookup: &FastHashMap, + ) -> Expression { + match expr { + Expr::Variable(ident) => { + let name = ident.0; + + match name.as_str() { + "gl_VertexIndex" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_InstanceIndex" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::InstanceIndex)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_DrawID" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::DrawIndex)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_BaseVertex" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::BaseVertex)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_BaseInstance" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::BaseInstance)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_Position" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: match self.exec_model { + ExecutionModel::Vertex => StorageClass::Output, + ExecutionModel::Fragment => StorageClass::Input, + _ => panic!(), + }, + binding: Some(Binding::BuiltIn(BuiltIn::Position)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + "gl_PointSize" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Output, + binding: Some(Binding::BuiltIn(BuiltIn::PointSize)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + "gl_ClipDistance" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Output, + binding: Some(Binding::BuiltIn(BuiltIn::ClipDistance)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + "gl_CullDistance" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Output, + binding: Some(Binding::BuiltIn(BuiltIn::CullDistance)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + other => { + if let Some(global) = self.globals_lookup.get(other) { + match *global { + Global::Variable(handle) => Expression::GlobalVariable(handle), + Global::StructShorthand(struct_handle, index) => { + Expression::AccessIndex { + base: expressions + .append(Expression::GlobalVariable(struct_handle)), + index, + } + } + } + } else if let Some(expr) = parameter_lookup.get(other) { + expr.clone() + } else if let Some(local) = locals_map.get(other) { + Expression::LocalVariable(*local) + } else { + println!("{}", other); + panic!() + } + } + } + } + Expr::IntConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Sint(value as i64), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + Expr::UIntConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Uint(value as u64), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 32, + }, + }), + })) + } + Expr::BoolConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Bool(value), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Bool, + width: 1, + }, + }), + })) + } + Expr::FloatConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Float(value as f64), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + Expr::DoubleConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Float(value), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 64, + }, + }), + })) + } + Expr::Unary(_op, _reg) => unimplemented!(), + Expr::Binary(op, left, right) => { + let left = + self.parse_expression(*left, expressions, locals, locals_map, parameter_lookup); + let right = self.parse_expression( + *right, + expressions, + locals, + locals_map, + parameter_lookup, + ); + + Expression::Binary { + op: helpers::glsl_to_spirv_binary_op(op), + left: expressions.append(left), + right: expressions.append(right), + } + } + Expr::Ternary(_condition, _accept, _reject) => unimplemented!(), + Expr::Assignment(_, _, _) => panic!(), + Expr::Bracket(_reg, _index) => unimplemented!(), + Expr::FunCall(ident, mut args) => { + let name = match ident { + FunIdentifier::Identifier(ident) => ident.0, + FunIdentifier::Expr(_expr) => todo!(), + }; + + match name.as_str() { + "vec2" | "vec3" | "vec4" => Expression::Compose { + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: match name.chars().last().unwrap() { + '2' => VectorSize::Bi, + '3' => VectorSize::Tri, + '4' => VectorSize::Quad, + _ => panic!(), + }, + kind: ScalarKind::Float, + width: 32, + }, + }), + components: args + .into_iter() + .map(|arg| { + let expr = self.parse_expression( + arg, + expressions, + locals, + locals_map, + parameter_lookup, + ); + expressions.append(expr) + }) + .collect(), + }, + "texture" => { + let (image, sampler) = + if let Expr::FunCall(ident, mut sample_args) = args.remove(0) { + let name = match ident { + FunIdentifier::Expr(_) => unimplemented!(), + FunIdentifier::Identifier(ident) => ident.0, + }; + + match name.as_str() { + "sampler2D" => ( + self.parse_expression( + sample_args.remove(0), + expressions, + locals, + locals_map, + parameter_lookup, + ), + self.parse_expression( + sample_args.remove(0), + expressions, + locals, + locals_map, + parameter_lookup, + ), + ), + _ => unimplemented!(), + } + } else { + panic!() + }; + + let coordinate = self.parse_expression( + args.remove(0), + expressions, + locals, + locals_map, + parameter_lookup, + ); + + Expression::ImageSample { + image: expressions.append(image), + sampler: expressions.append(sampler), + coordinate: expressions.append(coordinate), + } + } + _ => Expression::Call { + name, + arguments: args + .into_iter() + .map(|arg| { + let expr = self.parse_expression( + arg, + expressions, + locals, + locals_map, + parameter_lookup, + ); + expressions.append(expr) + }) + .collect(), + }, + } + } + Expr::Dot(reg, ident) => { + let handle = { + let expr = self.parse_expression( + *reg, + expressions, + locals, + locals_map, + parameter_lookup, + ); + expressions.append(expr) + }; + + let mut typefier = crate::proc::Typifier::new(); + let name = ident.0.as_str(); + let type_handle = typefier + .resolve( + handle, + expressions, + &mut self.types, + &self.constants, + &self.globals, + locals, + &self.functions, + &self.function_lookup, + ) + .unwrap(); + let base_type = &self.types[type_handle]; + match base_type.inner { + crate::TypeInner::Struct { ref members } => { + let index = members + .iter() + .position(|m| m.name.as_deref() == Some(name)) + .unwrap() as u32; + crate::Expression::AccessIndex { + base: handle, + index, + } + } + crate::TypeInner::Vector { size, kind, width } + | crate::TypeInner::Matrix { + columns: size, + kind, + width, + .. + } => { + const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; + if name.len() > 1 { + let mut components = Vec::with_capacity(name.len()); + + for ch in name.chars() { + let expr = crate::Expression::AccessIndex { + base: handle, + index: MEMBERS[..size as usize] + .iter() + .position(|&m| m == ch) + .unwrap() as u32, + }; + components.push(expressions.append(expr)); + } + let size = match name.len() { + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + 4 => crate::VectorSize::Quad, + _ => panic!(), + }; + let inner = + if let crate::TypeInner::Matrix { rows, .. } = base_type.inner { + crate::TypeInner::Matrix { + columns: size, + rows, + kind, + width, + } + } else { + crate::TypeInner::Vector { size, kind, width } + }; + crate::Expression::Compose { + ty: crate::proc::Typifier::deduce_type_handle( + inner, + &mut self.types, + ), + components, + } + } else { + let ch = name.chars().next().unwrap(); + let index = MEMBERS[..size as usize] + .iter() + .position(|&m| m == ch) + .unwrap() as u32; + crate::Expression::AccessIndex { + base: handle, + index, + } + } + } + _ => panic!(), + } + } + Expr::PostInc(_reg) => unimplemented!(), + Expr::PostDec(_reg) => unimplemented!(), + Expr::Comma(_, _) => unimplemented!(), + } + } + + // None = void + fn parse_type(&mut self, ty: TypeSpecifier) -> Option> { + let base_ty = helpers::glsl_to_spirv_type(ty.ty, &mut self.types)?; + + let ty = if let Some(specifier) = ty.array_specifier { + let handle = self.types.fetch_or_append(Type { + name: None, + inner: base_ty, + }); + + match specifier { + ArraySpecifier::Unsized => TypeInner::Array { + base: handle, + size: ArraySize::Dynamic, + }, + ArraySpecifier::ExplicitlySized(_) => unimplemented!(), + } + } else { + base_ty + }; + + Some(self.types.fetch_or_append(Type { + name: None, + inner: ty, + })) + } + + fn parse_global(&mut self, init: InitDeclaratorList) -> Handle { + let name = init.head.name.map(|d| d.0); + let ty = { + let ty = self.parse_type(init.head.ty.ty).unwrap(); + + if let Some(specifier) = init.head.array_specifier { + match specifier { + ArraySpecifier::Unsized => self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size: ArraySize::Dynamic, + }, + }), + ArraySpecifier::ExplicitlySized(_) => unimplemented!(), + } + } else { + ty + } + }; + + let (class, binding) = init + .head + .ty + .qualifier + .map(Self::parse_type_qualifier) + .unwrap_or((StorageClass::Private, None)); + + self.globals.append(GlobalVariable { + name, + class, + binding, + ty, + }) + } + + fn parse_type_qualifier(qualifier: TypeQualifier) -> (StorageClass, Option) { + let mut storage = None; + let mut binding = None; + + for qualifier in qualifier.qualifiers { + match qualifier { + TypeQualifierSpec::Storage(storage_qualifier) => { + assert!(storage.is_none()); + + match storage_qualifier { + StorageQualifier::Const => storage = Some(StorageClass::UniformConstant), + StorageQualifier::In => storage = Some(StorageClass::Input), + StorageQualifier::Out => storage = Some(StorageClass::Output), + StorageQualifier::Uniform => storage = Some(StorageClass::Uniform), + StorageQualifier::Buffer => storage = Some(StorageClass::StorageBuffer), + StorageQualifier::Shared => storage = Some(StorageClass::Workgroup), + StorageQualifier::Coherent => storage = Some(StorageClass::Workgroup), + _ => panic!(), + } + } + TypeQualifierSpec::Layout(layout_qualifier) => { + assert!(binding.is_none()); + + let mut set = None; + let mut bind = None; + let mut location = None; + + for identifier in layout_qualifier.ids { + match identifier { + LayoutQualifierSpec::Identifier(identifier, Some(expr)) => { + if let Expr::IntConst(word) = *expr { + match identifier.as_str() { + "location" => { + assert!(set.is_none(),); + assert!(bind.is_none(),); + assert!(location.is_none()); + + location = Some(word); + } + "binding" => { + assert!(bind.is_none(),); + assert!(location.is_none()); + + bind = Some(word); + } + "set" => { + assert!(set.is_none(),); + assert!(location.is_none()); + + set = Some(word); + } + _ => {} + } + } + } + _ => unimplemented!(), + } + } + + if let (Some(set), Some(bind)) = (set, bind) { + binding = Some(Binding::Descriptor { + set: set as u32, + binding: bind as u32, + }) + } else if let Some(location) = location { + binding = Some(Binding::Location(location as u32)) + } else { + panic!() + } + } + _ => unimplemented!(), + } + } + + (storage.unwrap_or(StorageClass::Private), binding) + } +} + +pub fn parse_str( + source: &str, + entry: String, + exec: ExecutionModel, +) -> Result { + let input = parser::parse(source).unwrap(); + + log::debug!("------GLSL PREPROCESSOR------"); + log::debug!("\n{}", input); + log::debug!("-----------------------------"); + + Parser::new(&input, exec)?.parse(entry) +} + +#[cfg(test)] +mod tests { + use super::parse_str; + + #[test] + fn test_vertex() { + let data = include_str!("../../test-data/glsl_vertex_test_shader.vert"); + + println!( + "{:#?}", + parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) + ); + } + + #[test] + fn test_frag() { + let _ = env_logger::try_init(); + + let data = include_str!("../../test-data/glsl_phong_lighting.frag"); + + println!( + "{:#?}", + parse_str(data, String::from("main"), spirv::ExecutionModel::Fragment) + ); + } + + #[cfg(feature = "glsl_preprocessor")] + #[test] + fn test_preprocess() { + let _ = env_logger::try_init(); + + let data = include_str!("../../test-data/glsl_preprocessor_abuse.vert"); + + println!( + "{:#?}", + parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) + ); + } + + #[cfg(feature = "glsl_preprocessor")] + #[test] + #[should_panic] + fn test_preprocess_ifs() { + let _ = env_logger::try_init(); + + let data = include_str!("../../test-data/glsl_if_preprocessor.vert"); + + println!( + "{:#?}", + parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) + ); + } +} diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs new file mode 100644 index 000000000..7c88746e3 --- /dev/null +++ b/src/front/glsl/helpers.rs @@ -0,0 +1,284 @@ +use crate::{Arena, ImageFlags, ScalarKind, Type, TypeInner, VectorSize}; +use glsl::syntax::{BinaryOp, TypeSpecifierNonArray}; +use spirv::Dim; + +pub fn glsl_to_spirv_binary_op(op: BinaryOp) -> crate::BinaryOperator { + match op { + BinaryOp::Or => crate::BinaryOperator::LogicalOr, + BinaryOp::Xor => todo!(), + BinaryOp::And => crate::BinaryOperator::LogicalAnd, + BinaryOp::BitOr => crate::BinaryOperator::InclusiveOr, + BinaryOp::BitXor => crate::BinaryOperator::ExclusiveOr, + BinaryOp::BitAnd => crate::BinaryOperator::And, + BinaryOp::Equal => crate::BinaryOperator::Equal, + BinaryOp::NonEqual => crate::BinaryOperator::NotEqual, + BinaryOp::LT => crate::BinaryOperator::Less, + BinaryOp::GT => crate::BinaryOperator::Greater, + BinaryOp::LTE => crate::BinaryOperator::LessEqual, + BinaryOp::GTE => crate::BinaryOperator::GreaterEqual, + BinaryOp::LShift => crate::BinaryOperator::ShiftLeftLogical, + BinaryOp::RShift => crate::BinaryOperator::ShiftRightArithmetic, + BinaryOp::Add => crate::BinaryOperator::Add, + BinaryOp::Sub => crate::BinaryOperator::Subtract, + BinaryOp::Mult => crate::BinaryOperator::Multiply, + BinaryOp::Div => crate::BinaryOperator::Divide, + BinaryOp::Mod => crate::BinaryOperator::Modulo, + } +} + +pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> Option { + use TypeSpecifierNonArray::*; + + Some(match ty { + Void => return None, + Bool => TypeInner::Scalar { + kind: ScalarKind::Bool, + width: 1, + }, + Int => TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + UInt => TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 32, + }, + Float => TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + Double => TypeInner::Scalar { + kind: ScalarKind::Float, + width: 64, + }, + Vec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Float, + width: 32, + }, + Vec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Float, + width: 32, + }, + Vec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + DVec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Float, + width: 64, + }, + DVec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Float, + width: 64, + }, + DVec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 64, + }, + BVec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Bool, + width: 1, + }, + BVec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Bool, + width: 1, + }, + BVec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Bool, + width: 1, + }, + IVec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Sint, + width: 32, + }, + IVec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Sint, + width: 32, + }, + IVec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Sint, + width: 32, + }, + UVec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Uint, + width: 32, + }, + UVec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Uint, + width: 32, + }, + UVec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Uint, + width: 32, + }, + // Float Matrices + Mat2 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 32, + }, + Mat3 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 32, + }, + Mat4 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + Mat23 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 32, + }, + Mat24 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + Mat32 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 32, + }, + Mat34 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + Mat42 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 32, + }, + Mat43 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 32, + }, + // Double Matrices + DMat2 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 64, + }, + DMat3 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 64, + }, + DMat4 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 64, + }, + DMat23 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 64, + }, + DMat24 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 64, + }, + DMat32 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 64, + }, + DMat34 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 64, + }, + DMat42 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 64, + }, + DMat43 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 64, + }, + TypeName(ty_name) => { + if let Some(t_pos) = ty_name.0.find("texture") { + let scalar_kind = match &ty_name.0[..t_pos] { + "" => ScalarKind::Float, + "i" => ScalarKind::Sint, + "u" => ScalarKind::Uint, + _ => panic!(), + }; + let base = types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: scalar_kind, + width: 32, + }, + }); + + let (dim, flags) = match &ty_name.0[(t_pos + 7)..] { + "1D" => (Dim::Dim1D, ImageFlags::SAMPLED), + "2D" => (Dim::Dim2D, ImageFlags::SAMPLED), + "3D" => (Dim::Dim3D, ImageFlags::SAMPLED), + "1DArray" => (Dim::Dim1D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), + "2DArray" => (Dim::Dim2D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), + "3DArray" => (Dim::Dim3D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), + "2DMS" => (Dim::Dim2D, ImageFlags::SAMPLED | ImageFlags::MULTISAMPLED), + "2DMSArray" => ( + Dim::Dim2D, + ImageFlags::SAMPLED | ImageFlags::ARRAYED | ImageFlags::MULTISAMPLED, + ), + "2DRect" => (Dim::DimRect, ImageFlags::SAMPLED), + "Cube" => (Dim::DimCube, ImageFlags::SAMPLED), + "CubeArray" => (Dim::DimCube, ImageFlags::SAMPLED | ImageFlags::ARRAYED), + "Buffer" => (Dim::DimBuffer, ImageFlags::SAMPLED), + _ => panic!(), + }; + + return Some(TypeInner::Image { base, dim, flags }); + } + + if ty_name.0 == "sampler" { + return Some(TypeInner::Sampler); + } + unimplemented!() + } + _ => unimplemented!(), + }) +} diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs new file mode 100644 index 000000000..0b0332313 --- /dev/null +++ b/src/front/glsl/parser.rs @@ -0,0 +1,246 @@ +#![allow(clippy::all)] +#![allow(dead_code)] + +use super::{Error, ErrorKind}; +use crate::FastHashMap; +use std::{ + fmt, + iter::Peekable, + ops::{Deref, Range}, + vec::IntoIter, +}; + +pub mod lex; + +#[cfg(feature = "glsl_preprocessor")] +#[path = "./preprocessor.rs"] +pub mod preprocessor; + +type Tokens = Peekable>; + +#[derive(Debug, Clone)] +pub struct TokenMetadata { + pub token: Token, + pub line: usize, + pub chars: Range, +} + +impl Deref for TokenMetadata { + type Target = Token; + + fn deref(&self) -> &Token { + &self.token + } +} + +#[derive(Debug, PartialEq, Clone)] +pub enum Token { + Separator(char), + DoubleColon, + Paren(char), + Integral(usize), + Float(f32), + Double(f64), + Word(String), + Operation(char), + OpAssign(char), + LogicalOperation(char), + ShiftOperation(char), + Unknown(char), + LineComment, + MultiLineCommentOpen, + MultiLineCommentClose, + Preprocessor, + End, + Selection, + Sufix(char), + TokenPasting, +} + +impl Token { + pub fn type_to_string(&self) -> String { + match self { + Token::Separator(separator) => separator.to_string(), + Token::DoubleColon => ":".to_string(), + Token::Paren(paren) => paren.to_string(), + Token::Integral(_) => "integer".to_string(), + Token::Float(_) => "float".to_string(), + Token::Double(_) => "double".to_string(), + Token::Word(_) => "word".to_string(), + Token::Operation(op) => op.to_string(), + Token::OpAssign(op) => format!("{}=", op), + Token::LogicalOperation(op) => format!("{}=", op), + Token::ShiftOperation(op) => format!("{0}{0}", op), + Token::Unknown(_) => "unknown".to_string(), + Token::LineComment => "//".to_string(), + Token::MultiLineCommentOpen => "/*".to_string(), + Token::MultiLineCommentClose => "*/".to_string(), + Token::Preprocessor => "#".to_string(), + Token::End => "EOF".to_string(), + Token::Selection => "?".to_string(), + Token::Sufix(op) => format!("{0}{0}", op), + Token::TokenPasting => "##".to_string(), + } + } +} + +impl fmt::Display for Token { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Token::Separator(sep) => write!(f, "{}", sep), + Token::DoubleColon => write!(f, ":"), + Token::Paren(paren) => write!(f, "{}", paren), + Token::Integral(int) => write!(f, "{}", int), + Token::Float(float) => write!(f, "{}", float), + Token::Double(double) => write!(f, "{}", double), + Token::Word(word) => write!(f, "{}", word), + Token::Operation(op) => write!(f, "{}", op), + Token::OpAssign(op) => write!(f, "{}=", op), + Token::LogicalOperation(op) => write!(f, "{0}=", op), + Token::ShiftOperation(op) => write!(f, "{0}{0}", op), + Token::Unknown(unknown) => write!(f, "{}", unknown), + Token::LineComment => write!(f, "//"), + Token::MultiLineCommentOpen => write!(f, "/*"), + Token::MultiLineCommentClose => write!(f, "*/"), + Token::Preprocessor => write!(f, "#"), + Token::End => write!(f, ""), + Token::Selection => write!(f, "?"), + Token::Sufix(op) => write!(f, "{0}{0}", op), + Token::TokenPasting => write!(f, "##"), + } + } +} + +#[derive(Debug)] +pub enum Node { + Ident(String), + Const(Literal), +} + +#[derive(Debug, Copy, Clone)] +pub enum Literal { + Double(f64), + Float(f32), + Uint(usize), + Sint(isize), + Bool(bool), +} + +fn parse_primary_expression(tokens: &mut Tokens) -> Result { + let token = tokens.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + match token.token { + Token::Word(ident) => Ok(match ident.as_str() { + "true" => Node::Const(Literal::Bool(true)), + "false" => Node::Const(Literal::Bool(false)), + _ => Node::Ident(ident), + }), + Token::Integral(uint) => Ok(Node::Const(Literal::Uint(uint))), + Token::Float(float) => Ok(Node::Const(Literal::Float(float))), + Token::Double(double) => Ok(Node::Const(Literal::Double(double))), + Token::Paren('(') => todo!(), /* parse_expression */ + _ => Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![ + Token::Word(String::new()), + Token::Integral(0), + Token::Double(0.0), + Token::Float(0.0), + Token::Paren('('), + ], + got: token, + }, + }), + } +} + +pub(self) fn parse_comments(mut lexer: lex::Lexer) -> Result, Error> { + let mut tokens = Vec::new(); + + loop { + let token = lexer.next(); + + match token.token { + Token::MultiLineCommentOpen => { + let mut token = lexer.next(); + while Token::MultiLineCommentClose != token.token { + match token.token { + Token::End => { + return Err(Error { + kind: ErrorKind::EOF, + }) + } + _ => {} + } + + token = lexer.next(); + } + } + Token::LineComment => { + while token.line == lexer.peek().line && Token::End != lexer.peek().token { + let _ = lexer.next(); + } + } + Token::End => { + tokens.push(token); + break; + } + _ => tokens.push(token), + } + } + + Ok(tokens) +} + +pub fn parse(input: &str) -> Result { + let lexer = lex::Lexer::new(input); + + let tokens = parse_comments(lexer)?; + + let mut macros = FastHashMap::default(); + + macros.insert( + String::from("GL_SPIRV"), + vec![TokenMetadata { + token: Token::Integral(100), + line: 0, + chars: 0..1, + }], + ); + macros.insert( + String::from("VULKAN"), + vec![TokenMetadata { + token: Token::Integral(100), + line: 0, + chars: 0..1, + }], + ); + + log::trace!("------GLSL COMMENT STRIPPED------"); + log::trace!("\n{:#?}", tokens); + log::trace!("---------------------------------"); + + #[cfg(feature = "glsl_preprocessor")] + let tokens = preprocessor::preprocess(&mut tokens.into_iter().peekable(), &mut macros)?; + + let mut line = 0; + let mut start = 0; + + Ok(tokens.into_iter().fold(String::new(), |mut acc, token| { + if token.line - line != 0 { + acc.push_str(&"\n".repeat(token.line - line)); + start = 0; + line = token.line; + } + + acc.push_str(&" ".repeat(token.chars.start - start)); + + acc.push_str(&token.token.to_string()); + + start = token.chars.end; + + acc + })) +} diff --git a/src/front/glsl/parser/lex.rs b/src/front/glsl/parser/lex.rs new file mode 100644 index 000000000..7cf27dd13 --- /dev/null +++ b/src/front/glsl/parser/lex.rs @@ -0,0 +1,254 @@ +use super::{Token, TokenMetadata}; +use std::{iter::Enumerate, str::Lines}; + +fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { + if input.starts_with(what) { + Some(&input[what.len()..]) + } else { + None + } +} + +fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str, usize) { + let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); + let (o, i) = input.split_at(pos); + (o, i, pos) +} + +pub fn consume_token(input: &String) -> (Token, &str, usize, usize) { + let mut input = input.as_str(); + + let start = input + .find(|c: char| !c.is_whitespace()) + .unwrap_or(input.chars().count()); + input = &input[start..]; + + let mut chars = input.chars(); + let cur = match chars.next() { + Some(c) => c, + None => return (Token::End, input, start, start + 1), + }; + match cur { + ':' => { + input = chars.as_str(); + if chars.next() == Some(':') { + (Token::DoubleColon, chars.as_str(), start, start + 2) + } else { + (Token::Separator(cur), input, start, start + 1) + } + } + ';' | ',' | '.' => (Token::Separator(cur), chars.as_str(), start, start + 1), + '(' | ')' | '{' | '}' | '[' | ']' => (Token::Paren(cur), chars.as_str(), start, start + 1), + '<' | '>' => { + input = chars.as_str(); + let next = chars.next(); + if next == Some('=') { + ( + Token::LogicalOperation(cur), + chars.as_str(), + start, + start + 1, + ) + } else if next == Some(cur) { + (Token::ShiftOperation(cur), chars.as_str(), start, start + 2) + } else { + (Token::Operation(cur), input, start, start + 1) + } + } + '0'..='9' => { + let (number, rest, pos) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); + if let Some(_) = number.find('.') { + if ( + chars.next().map(|c| c.to_lowercase().next().unwrap()), + chars.next().map(|c| c.to_lowercase().next().unwrap()), + ) == (Some('l'), Some('f')) + { + ( + Token::Double(number.parse().unwrap()), + chars.as_str(), + start, + start + pos + 2, + ) + } else { + ( + Token::Float(number.parse().unwrap()), + chars.as_str(), + start, + start + pos, + ) + } + } else { + ( + Token::Integral(number.parse().unwrap()), + rest, + start, + start + pos, + ) + } + } + 'a'..='z' | 'A'..='Z' | '_' => { + let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); + (Token::Word(String::from(word)), rest, start, start + pos) + } + '+' | '-' => { + input = chars.as_str(); + match chars.next() { + Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), + Some(next) if cur == next => (Token::Sufix(cur), chars.as_str(), start, start + 2), + _ => (Token::Operation(cur), input, start, start + 1), + } + } + '%' | '^' => { + input = chars.as_str(); + + if chars.next() == Some('=') { + (Token::OpAssign(cur), chars.as_str(), start, start + 2) + } else { + (Token::Operation(cur), input, start, start + 1) + } + } + '!' => { + input = chars.as_str(); + + if chars.next() == Some('=') { + ( + Token::LogicalOperation(cur), + chars.as_str(), + start, + start + 2, + ) + } else { + (Token::Operation(cur), input, start, start + 1) + } + } + '*' => { + input = chars.as_str(); + match chars.next() { + Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), + Some('/') => ( + Token::MultiLineCommentClose, + chars.as_str(), + start, + start + 2, + ), + _ => (Token::Operation(cur), input, start, start + 1), + } + } + '/' => { + input = chars.as_str(); + match chars.next() { + Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), + Some('/') => (Token::LineComment, chars.as_str(), start, start + 2), + Some('*') => ( + Token::MultiLineCommentOpen, + chars.as_str(), + start, + start + 2, + ), + _ => (Token::Operation(cur), input, start, start + 1), + } + } + '=' | '&' | '|' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + ( + Token::LogicalOperation(cur), + chars.as_str(), + start, + start + 2, + ) + } else { + (Token::Operation(cur), input, start, start + 1) + } + } + '#' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + (Token::TokenPasting, chars.as_str(), start, start + 2) + } else { + (Token::Preprocessor, input, start, start + 1) + } + } + '~' => (Token::Operation(cur), chars.as_str(), start, start + 1), + '?' => (Token::Selection, chars.as_str(), start, start + 1), + _ => (Token::Unknown(cur), chars.as_str(), start, start + 1), + } +} + +#[derive(Clone, Debug)] +pub struct Lexer<'a> { + lines: Enumerate>, + input: String, + line: usize, + offset: usize, +} + +impl<'a> Lexer<'a> { + pub fn new(input: &'a str) -> Self { + let mut lines = input.lines().enumerate(); + let (line, input) = lines.next().unwrap_or((0, "")); + let mut input = String::from(input); + + while input.chars().last() == Some('\\') { + if let Some((_, next)) = lines.next() { + input.pop(); + input.push_str(next); + } else { + break; + } + } + + Lexer { + lines, + input, + line, + offset: 0, + } + } + + #[must_use] + pub fn next(&mut self) -> TokenMetadata { + let (token, rest, start, end) = consume_token(&self.input); + + if token == Token::End { + match self.lines.next() { + Some((line, input)) => { + let mut input = String::from(input); + + while input.chars().last() == Some('\\') { + if let Some((_, next)) = self.lines.next() { + input.pop(); + input.push_str(next); + } else { + break; + } + } + + self.input = input; + self.line = line; + self.offset = 0; + self.next() + } + None => TokenMetadata { + token: Token::End, + line: self.line, + chars: self.offset + start..end + self.offset, + }, + } + } else { + self.input = String::from(rest); + let metadata = TokenMetadata { + token, + line: self.line, + chars: self.offset + start..end + self.offset, + }; + self.offset += end; + metadata + } + } + + #[must_use] + pub fn peek(&mut self) -> TokenMetadata { + self.clone().next() + } +} diff --git a/src/front/glsl/preprocessor.rs b/src/front/glsl/preprocessor.rs new file mode 100644 index 000000000..0121455ac --- /dev/null +++ b/src/front/glsl/preprocessor.rs @@ -0,0 +1,1618 @@ +use super::{ + super::{Error, ErrorKind}, + Literal, Token, TokenMetadata, +}; +use crate::{BinaryOperator, FastHashMap}; +use std::{iter::Peekable, vec::IntoIter}; + +#[derive(Debug)] +pub enum PreprocessorIfNode { + Literal(Literal), + Unary { + op: UnaryOp, + tgt: Box, + }, + Binary { + left: Box, + op: BinaryOperator, + right: Box, + }, +} + +impl Literal { + pub fn as_isize(&self) -> isize { + match self { + Literal::Double(double) => *double as isize, + Literal::Float(float) => *float as isize, + Literal::Uint(uint) => *uint as isize, + Literal::Sint(sint) => *sint, + Literal::Bool(val) => *val as isize, + } + } + + pub fn as_bool(&self) -> Result { + Ok(match self { + Literal::Double(_) | Literal::Float(_) => panic!(), + Literal::Uint(uint) => { + if *uint == 0 { + false + } else { + true + } + } + Literal::Sint(sint) => { + if *sint == 0 { + false + } else { + true + } + } + Literal::Bool(val) => *val, + }) + } +} + +#[derive(Debug, Copy, Clone)] +pub enum UnaryOp { + Positive, + Negative, + BitWiseNot, + LogicalNot, +} + +macro_rules! get_macro { + ($name:expr, $token:expr, $line_offset:expr,$macros:expr) => { + match $name.as_str() { + "__LINE__" => Some(vec![TokenMetadata { + token: Token::Integral(($token.line as i32 + $line_offset + 1) as usize), + line: 0, + chars: 0..1, + }]), + "__FILE__" => Some(vec![TokenMetadata { + token: Token::Integral(0), + line: 0, + chars: 0..1, + }]), + "__VERSION__" => Some(vec![TokenMetadata { + token: Token::Integral(460), + line: 0, + chars: 0..1, + }]), /* TODO */ + other => $macros.get(other).cloned().map(|mut tokens| { + let mut start = tokens[0].chars.start; + let mut offset = 0; + + for token in tokens.iter_mut() { + token.line = $token.line; + + let length = token.chars.end - token.chars.start; + + offset += token.chars.start - start; + start = token.chars.start; + + token.chars.start = $token.chars.start + offset; + + token.chars.end = length + $token.chars.start + offset; + } + tokens + }), + } + }; +} + +pub fn preprocess( + lexer: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result, Error> { + let mut tokens = Vec::new(); + let mut line_offset = 0i32; + + let mut offset = (0, 0); + + loop { + let token = match lexer.next() { + Some(t) => t, + None => break, + }; + + match token.token { + Token::Preprocessor => { + let preprocessor_op_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + continue; + }; + + let preprocessor_op = if let Token::Word(name) = preprocessor_op_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: preprocessor_op_token, + }, + }); + }; + + match preprocessor_op.as_str() { + "define" => { + let macro_name_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let macro_name = if let Token::Word(name) = macro_name_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + if macro_name.starts_with("GL_") { + return Err(Error { + kind: ErrorKind::ReservedMacro, + }); + } + + let mut macro_tokens = Vec::new(); + + while Some(token.line) == lexer.peek().map(|t| t.line) { + let macro_token = lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + match macro_token.token { + Token::Word(ref word) => { + match get_macro!(word, &token, line_offset, macros) { + Some(stream) => macro_tokens.append(&mut stream.clone()), + None => macro_tokens.push(macro_token), + } + } + _ => macro_tokens.push(macro_token), + } + } + + macros.insert(macro_name, macro_tokens); + } + "undef" => { + let macro_name_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let macro_name = if let Token::Word(name) = macro_name_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + macros.remove(¯o_name); + } + "if" => { + let mut expr = Vec::new(); + + while lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + == token.line + { + let expr_token = lexer.next().unwrap(); + + match expr_token.token { + Token::Word(ref macro_name) => expr.append( + &mut get_macro!(macro_name, expr_token, line_offset, macros) + .unwrap(), + ), + _ => expr.push(expr_token), + } + } + + let condition = evaluate_preprocessor_if(expr, macros)?; + + let mut body_tokens = + parse_preprocessor_if(lexer, macros, condition, line_offset, offset)?; + + tokens.append(&mut body_tokens); + } + "ifdef" | "ifndef" => { + let macro_name_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().unwrap() + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let macro_name = if let Token::Word(name) = macro_name_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + // There shouldn't be any more tokens on this line so we throw a error + if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } + + let mut body_tokens = parse_preprocessor_if( + lexer, + macros, + match preprocessor_op.as_str() { + "ifdef" => macros.get(¯o_name).is_some(), + "ifndef" => macros.get(¯o_name).is_none(), + _ => unreachable!(), + }, + line_offset, + offset, + )?; + + tokens.append(&mut body_tokens); + } + "else" | "elif" | "endif" => { + return Err(Error { + kind: ErrorKind::UnboundedIfCloserOrVariant { token }, + }) + } + "error" => { + let mut error_token = lexer.next(); + + let first_byte = error_token + .as_ref() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .chars + .start; + + let mut error_message = String::new(); + + while error_token.as_ref().map(|t| t.line) == Some(token.line) { + let error_msg_token = error_token.as_ref().unwrap(); + + let spacing = error_msg_token.chars.start + - first_byte + - error_message.chars().count(); + + error_message.push_str(&" ".repeat(spacing)); + error_message.push_str(error_msg_token.token.to_string().as_str()); + + error_token = lexer.next() + } + + panic!(error_message) + } + "pragma" => { + let pragma_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let pragma = if let Token::Word(name) = pragma_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: pragma_token, + }, + }); + }; + + match pragma.as_str() { + "optimize" => { + let open_paren_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if Token::Paren('(') != open_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren('(')], + got: open_paren_token, + }, + }); + }; + + let status_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let _ = if let Token::Word(name) = status_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: status_token, + }, + }); + }; + + let close_paren_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if Token::Paren(')') != close_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren(')')], + got: close_paren_token, + }, + }); + }; + } + "debug" => { + let open_paren_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if Token::Paren('(') != open_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren('(')], + got: open_paren_token, + }, + }); + }; + + let status_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let _ = if let Token::Word(name) = status_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: status_token, + }, + }); + }; + + let close_paren_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if Token::Paren(')') != close_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren(')')], + got: close_paren_token, + }, + }); + }; + } + _ => { + return Err(Error { + kind: ErrorKind::UnknownPragma { pragma }, + }) + } + } + } + "extension" => { + let extension_name_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let extension_name = if let Token::Word(word) = extension_name_token.token { + word + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: extension_name_token, + }, + }); + }; + + let separator_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if separator_token.token != Token::DoubleColon { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::DoubleColon], + got: separator_token, + }, + }); + } + + let behavior_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let behavior = if let Token::Word(word) = behavior_token.token { + word + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: behavior_token, + }, + }); + }; + + match extension_name.as_str() { + "all" => match behavior.as_str() { + "require" | "enable" => { + return Err(Error { + kind: ErrorKind::AllExtensionsEnabled, + }) + } + "warn" | "disable" => {} + _ => { + return Err(Error { + kind: ErrorKind::ExtensionUnknownBehavior { behavior }, + }) + } + }, + _ => match behavior.as_str() { + "require" => { + return Err(Error { + kind: ErrorKind::ExtensionNotSupported { + extension: extension_name, + }, + }) + } + "enable" | "warn" | "disable" => log::warn!( + "Unsupported extensions was enabled: {}", + extension_name + ), + _ => { + return Err(Error { + kind: ErrorKind::ExtensionUnknownBehavior { behavior }, + }) + } + }, + } + } + "version" => { + let version_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let version = if let Token::Integral(int) = version_token.token { + int + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Integral(0)], + got: version_token, + }, + }); + }; + + match version { + 450 | 460 => {} + _ => { + return Err(Error { + kind: ErrorKind::UnsupportedVersion { version }, + }) + } + }; + + let profile_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let profile = if let Token::Word(word) = profile_token.token { + word + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: profile_token, + }, + }); + }; + + match profile.as_str() { + "core" => macros.insert( + String::from("GL_core_profile"), + vec![TokenMetadata { + token: Token::Integral(1), + line: 0, + chars: 0..1, + }], + ), + "compatibility" | "es" => { + return Err(Error { + kind: ErrorKind::UnsupportedProfile { profile }, + }) + } + _ => { + return Err(Error { + kind: ErrorKind::UnknownProfile { profile }, + }) + } + }; + } + "line" => { + let line_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let line = if let Token::Integral(int) = line_token.token { + int + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Integral(0)], + got: line_token, + }, + }); + }; + + let source_string_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if let Token::Word(_) = source_string_token.token { + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: source_string_token, + }, + }); + } + + line_offset = line as i32 - token.line as i32; + } + _ => { + return Err(Error { + kind: ErrorKind::UnknownPreprocessorDirective { + directive: preprocessor_op, + }, + }) + } + } + + if lexer.peek().map(|t| t.line) == Some(token.line) { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } + } + Token::End => { + let mut token = token; + + if offset.0 == token.line { + token.chars.start = (token.chars.start as isize + offset.1) as usize; + token.chars.end = (token.chars.end as isize + offset.1) as usize; + } + + tokens.push(token); + break; + } + Token::Word(ref word) => match get_macro!(word, &token, line_offset, macros) { + Some(mut stream) => { + for macro_token in stream.iter_mut() { + if offset.0 == token.line { + macro_token.chars.start = + (macro_token.chars.start as isize + offset.1) as usize; + macro_token.chars.end = + (macro_token.chars.end as isize + offset.1) as usize; + } + } + + offset.0 = stream.last().unwrap().line; + offset.1 = stream.last().unwrap().chars.end as isize - token.chars.end as isize; + + tokens.append(&mut stream) + } + None => { + let mut token = token; + + if offset.0 == token.line { + token.chars.start = (token.chars.start as isize + offset.1) as usize; + token.chars.end = (token.chars.end as isize + offset.1) as usize; + } + + tokens.push(token) + } + }, + _ => { + let mut token = token; + + if offset.0 == token.line { + token.chars.start = (token.chars.start as isize + offset.1) as usize; + token.chars.end = (token.chars.end as isize + offset.1) as usize; + } + + tokens.push(token) + } + } + } + + Ok(tokens) +} + +fn parse_preprocessor_if( + lexer: &mut Peekable>, + macros: &mut FastHashMap>, + mut condition: bool, + line_offset: i32, + offset: (usize, isize), +) -> Result, Error> { + let mut body = Vec::new(); + let mut else_block = false; + + loop { + let macro_token = lexer.peek().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + if let Token::Preprocessor = macro_token.token { + let macro_token = lexer.next().unwrap(); + + let directive_token = if macro_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().unwrap() + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let directive = if let Token::Word(name) = directive_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_token, + }, + }); + }; + + match directive.as_str() { + "if" => { + let mut expr = Vec::new(); + + while lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + == macro_token.line + { + let expr_token = lexer.next().unwrap(); + + match expr_token.token { + Token::Word(ref macro_name) => expr.append( + &mut get_macro!(macro_name, expr_token, line_offset, macros) + .unwrap(), + ), + _ => expr.push(expr_token), + } + } + + let condition = evaluate_preprocessor_if(expr, macros)?; + + let mut body_tokens = + parse_preprocessor_if(lexer, macros, condition, line_offset, offset)?; + + body.append(&mut body_tokens); + } + "elif" => { + let mut expr = Vec::new(); + + while lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + == macro_token.line + { + let expr_token = lexer.next().unwrap(); + + match expr_token.token { + Token::Word(ref macro_name) => expr.append( + &mut get_macro!(macro_name, expr_token, line_offset, macros) + .unwrap(), + ), + _ => expr.push(expr_token), + } + } + + if !condition { + condition = evaluate_preprocessor_if(expr, macros)?; + } + } + "ifdef" | "ifndef" => { + let macro_name_token = if macro_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().unwrap() + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let macro_name = if let Token::Word(name) = macro_name_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + // There shouldn't be any more tokens on this line so we throw a error + if macro_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } + + let mut body_tokens = parse_preprocessor_if( + lexer, + macros, + match directive.as_str() { + "ifdef" => macros.get(¯o_name).is_some(), + "ifndef" => macros.get(¯o_name).is_none(), + _ => unreachable!(), + }, + line_offset, + offset, + )?; + + body.append(&mut body_tokens); + } + "else" => { + // There shouldn't be any more tokens on this line so we throw a error + if directive_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } + + if else_block { + return Err(Error { + kind: ErrorKind::UnexpectedWord { + expected: vec!["endif"], + got: directive, + }, + }); + } + + else_block = true; + condition = !condition; + } + "endif" => { + // There shouldn't be any more tokens on this line so we throw a error + if directive_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + if lexer.peek().unwrap().token != Token::End { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } else { + body.push(lexer.next().unwrap()); + } + } + + break; + } + _ => {} + } + } + + if condition { + body.push(lexer.next().unwrap()); + } else { + lexer.next().unwrap(); + } + } + + let body_tokens = preprocess(&mut body.into_iter().peekable(), macros)?; + + Ok(body_tokens) +} + +fn evaluate_preprocessor_if( + expr: Vec, + macros: &mut FastHashMap>, +) -> Result { + let tree = logical_or_parser(&mut expr.into_iter().peekable(), macros)?; + log::trace!("{:#?}", tree); + evaluate_node(tree)?.as_bool() +} + +fn evaluate_node(node: PreprocessorIfNode) -> Result { + Ok(match node { + PreprocessorIfNode::Literal(literal) => literal, + PreprocessorIfNode::Unary { op, tgt } => { + let literal = evaluate_node(*tgt)?; + + match op { + UnaryOp::Positive => literal, + UnaryOp::Negative => Literal::Sint(-literal.as_isize()), + UnaryOp::BitWiseNot => Literal::Sint(!literal.as_isize()), + UnaryOp::LogicalNot => Literal::Sint((!literal.as_bool()?) as isize), + } + } + PreprocessorIfNode::Binary { left, op, right } => { + let left = evaluate_node(*left)?; + let right = evaluate_node(*right)?; + + match op { + BinaryOperator::Multiply => Literal::Sint(left.as_isize() * right.as_isize()), + BinaryOperator::Divide => Literal::Sint(left.as_isize() / right.as_isize()), + BinaryOperator::Modulo => Literal::Sint(left.as_isize() % right.as_isize()), + BinaryOperator::Add => Literal::Sint(left.as_isize() + right.as_isize()), + BinaryOperator::Subtract => Literal::Sint(left.as_isize() - right.as_isize()), + + BinaryOperator::ShiftLeftLogical => { + Literal::Sint(left.as_isize() << right.as_isize()) + } + BinaryOperator::ShiftRightArithmetic => { + Literal::Sint(left.as_isize() << right.as_isize()) + } + + BinaryOperator::Greater => { + Literal::Sint((left.as_isize() > right.as_isize()) as isize) + } + BinaryOperator::Less => { + Literal::Sint((left.as_isize() < right.as_isize()) as isize) + } + BinaryOperator::GreaterEqual => { + Literal::Sint((left.as_isize() >= right.as_isize()) as isize) + } + BinaryOperator::LessEqual => { + Literal::Sint((left.as_isize() <= right.as_isize()) as isize) + } + + BinaryOperator::Equal => { + Literal::Sint((left.as_isize() == right.as_isize()) as isize) + } + BinaryOperator::NotEqual => { + Literal::Sint((left.as_isize() != right.as_isize()) as isize) + } + + BinaryOperator::And => Literal::Sint(left.as_isize() & right.as_isize()), + BinaryOperator::ExclusiveOr => Literal::Sint(left.as_isize() ^ right.as_isize()), + BinaryOperator::InclusiveOr => Literal::Sint(left.as_isize() | right.as_isize()), + + BinaryOperator::LogicalOr => { + Literal::Sint((left.as_bool()? || right.as_bool()?) as isize) + } + BinaryOperator::LogicalAnd => { + Literal::Sint((left.as_bool()? && right.as_bool()?) as isize) + } + _ => unreachable!(), + } + } + }) +} + +pub(self) fn logical_or_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = logical_and_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::LogicalOperation('|')) { + let _ = expr.next().unwrap(); + + let right = logical_and_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::LogicalOr, + right: Box::new(right), + } + } + + Ok(node) +} + +fn logical_and_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = bitwise_or_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::LogicalOperation('&')) { + let _ = expr.next().unwrap(); + + let right = bitwise_or_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::LogicalAnd, + right: Box::new(right), + } + } + + Ok(node) +} + +fn bitwise_or_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = bitwise_xor_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::Operation('|')) { + let _ = expr.next().unwrap(); + + let right = bitwise_xor_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::InclusiveOr, + right: Box::new(right), + } + } + + Ok(node) +} + +fn bitwise_xor_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = bitwise_and_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::Operation('^')) { + let _ = expr.next().unwrap(); + + let right = bitwise_and_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::ExclusiveOr, + right: Box::new(right), + } + } + + Ok(node) +} + +fn bitwise_and_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = equality_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::Operation('&')) { + let _ = expr.next().unwrap(); + + let right = equality_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::And, + right: Box::new(right), + } + } + + Ok(node) +} + +fn equality_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = relational_parser(expr, macros)?; + + let mut node = left; + + loop { + let equality_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match equality_token.token { + Token::LogicalOperation('=') => BinaryOperator::Equal, + Token::LogicalOperation('!') => BinaryOperator::NotEqual, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = relational_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn relational_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = shift_parser(expr, macros)?; + + let mut node = left; + + loop { + let relational_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match relational_token.token { + Token::LogicalOperation('<') => BinaryOperator::LessEqual, + Token::LogicalOperation('>') => BinaryOperator::GreaterEqual, + Token::Operation('<') => BinaryOperator::Less, + Token::Operation('>') => BinaryOperator::Greater, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = shift_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn shift_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = additive_parser(expr, macros)?; + + let mut node = left; + + loop { + let shift_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match shift_token.token { + Token::ShiftOperation('<') => BinaryOperator::ShiftLeftLogical, + Token::ShiftOperation('>') => BinaryOperator::ShiftRightArithmetic, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = additive_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn additive_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = multiplicative_parser(expr, macros)?; + + let mut node = left; + + loop { + let additive_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match additive_token.token { + Token::Operation('+') => BinaryOperator::Add, + Token::Operation('-') => BinaryOperator::Subtract, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = multiplicative_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn multiplicative_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = unary_parser(expr, macros)?; + + let mut node = left; + + loop { + let multiplicative_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match multiplicative_token.token { + Token::Operation('*') => BinaryOperator::Multiply, + Token::Operation('/') => BinaryOperator::Divide, + Token::Operation('%') => BinaryOperator::Modulo, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = unary_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn unary_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let unary_or_atom_token = expr.peek().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + Ok(match unary_or_atom_token.token { + Token::Operation(op) => { + let unary_token = expr.next().unwrap(); + + PreprocessorIfNode::Unary { + op: match op { + '+' => UnaryOp::Positive, + '-' => UnaryOp::Negative, + '!' => UnaryOp::BitWiseNot, + '~' => UnaryOp::LogicalNot, + _ => { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![ + Token::Operation('+'), + Token::Operation('-'), + Token::Operation('!'), + Token::Operation('~'), + ], + got: unary_token, + }, + }) + } + }, + tgt: Box::new(atom_parser(expr, macros)?), + } + } + _ => atom_parser(expr, macros)?, + }) +} + +fn atom_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let atom = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + Ok(match atom.token { + Token::Double(_) | Token::Float(_) => { + return Err(Error { + kind: ErrorKind::NonIntegralType { token: atom }, + }) + } + Token::Integral(int) => PreprocessorIfNode::Literal(Literal::Uint(int)), + Token::Word(word) => PreprocessorIfNode::Literal(match word.as_str() { + "defined" => { + let macro_name_or_paren_token = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + match macro_name_or_paren_token.token { + Token::Paren('(') => { + let macro_name_token = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + let node = if let Token::Word(macro_name) = macro_name_token.token { + Literal::Sint(macros.get(¯o_name).is_some() as isize) + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + let close_paren_token = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + if Token::Paren(')') != close_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren(')')], + got: close_paren_token, + }, + }); + } + + node + } + _ => { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_or_paren_token, + }, + }) + } + } + } + _ => { + return logical_or_parser( + &mut macros + .get_mut(&word) + .cloned() + .unwrap() + .into_iter() + .peekable(), + macros, + ) + } + }), + Token::Paren('(') => { + let node = logical_or_parser(expr, macros)?; + + let close_paren = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + if close_paren.token != Token::Paren(')') { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren(')')], + got: close_paren, + }, + }); + } + + node + } + _ => { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![ + Token::Word(String::new()), + Token::Paren('('), + Token::Integral(0), + ], + got: atom, + }, + }) + } + }) +} diff --git a/src/front/mod.rs b/src/front/mod.rs index 36c1b701e..0ca2c87c3 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,3 +1,5 @@ +#[cfg(feature = "glsl")] +pub mod glsl; pub mod spirv; pub mod wgsl; diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 22cbc4eea..2059a79af 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -321,7 +321,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { fn resolve_type(&mut self, handle: Handle) -> Result, Error<'a>> { self.typifier - .resolve(handle, self.expressions, self.types, self.constants, self.global_vars, self.local_vars) + .resolve(handle, self.expressions, self.types, self.constants, self.global_vars, self.local_vars,&Arena::new(),&FastHashMap::default()) .map_err(Error::InvalidResolve) } diff --git a/src/lib.rs b/src/lib.rs index 794c4212c..c9359c001 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,7 +12,6 @@ use std::{ hash::BuildHasherDefault, }; - pub type FastHashMap = HashMap>; pub type FastHashSet = HashSet>; @@ -66,7 +65,7 @@ bitflags::bitflags! { } } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub struct Type { pub name: Option, pub inner: TypeInner, @@ -117,7 +116,7 @@ bitflags::bitflags! { } } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub struct GlobalVariable { pub name: Option, pub class: spirv::StorageClass, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index e5965312c..ed87c964a 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -1,4 +1,7 @@ -use crate::arena::{Arena, Handle}; +use crate::{ + arena::{Arena, Handle}, + FastHashMap, Type, TypeInner, VectorSize, +}; pub struct Typifier { types: Vec>, @@ -7,15 +10,16 @@ pub struct Typifier { #[derive(Debug)] pub enum ResolveError { InvalidAccessIndex, + FunctionNotDefined, + FunctionReturnsVoid, } impl Typifier { pub fn new() -> Self { - Typifier { - types: Vec::new(), - } + Typifier { types: Vec::new() } } + #[allow(clippy::too_many_arguments)] pub fn resolve( &mut self, expr_handle: Handle, @@ -24,6 +28,8 @@ impl Typifier { constants: &Arena, global_vars: &Arena, local_vars: &Arena, + functions: &Arena, + function_lookup: &FastHashMap>, ) -> Result, ResolveError> { if self.types.len() <= expr_handle.index() { for (eh, expr) in expressions.iter().skip(self.types.len()) { @@ -38,21 +44,31 @@ impl Typifier { match types[self.types[base.index()]].inner { crate::TypeInner::Vector { size, kind, width } => { if index >= size as u32 { - return Err(ResolveError::InvalidAccessIndex) + return Err(ResolveError::InvalidAccessIndex); } let inner = crate::TypeInner::Scalar { kind, width }; Self::deduce_type_handle(inner, types) } - crate::TypeInner::Matrix { columns, rows, kind, width } => { + crate::TypeInner::Matrix { + columns, + rows, + kind, + width, + } => { if index >= columns as u32 { - return Err(ResolveError::InvalidAccessIndex) + return Err(ResolveError::InvalidAccessIndex); } - let inner = crate::TypeInner::Vector { size: rows, kind, width }; + let inner = crate::TypeInner::Vector { + size: rows, + kind, + width, + }; Self::deduce_type_handle(inner, types) } crate::TypeInner::Array { base, .. } => base, crate::TypeInner::Struct { ref members } => { - members.get(index as usize) + members + .get(index as usize) .ok_or(ResolveError::InvalidAccessIndex)? .ty } @@ -65,74 +81,112 @@ impl Typifier { crate::Expression::GlobalVariable(h) => global_vars[h].ty, crate::Expression::LocalVariable(h) => local_vars[h].ty, crate::Expression::Load { .. } => unimplemented!(), - crate::Expression::ImageSample { .. } => unimplemented!(), + crate::Expression::ImageSample { image, .. } => { + let image = self.resolve( + image, + expressions, + types, + constants, + global_vars, + local_vars, + functions, + function_lookup, + )?; + + let (kind, width) = match types[image].inner { + TypeInner::Image { base, .. } => match types[base].inner { + TypeInner::Scalar { kind, width } => (kind, width), + _ => unimplemented!(), + }, + _ => unreachable!(), + }; + + types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + kind, + width, + size: VectorSize::Quad, + }, + }) + } crate::Expression::Unary { expr, .. } => self.types[expr.index()], - crate::Expression::Binary { op, left, right } => { - match op { - crate::BinaryOperator::Add | - crate::BinaryOperator::Subtract | - crate::BinaryOperator::Divide | - crate::BinaryOperator::Modulo => { - self.types[left.index()] - } - crate::BinaryOperator::Multiply => { - let ty_left = self.types[left.index()]; - let ty_right = self.types[right.index()]; - if ty_left == ty_right { - ty_left - } else if let crate::TypeInner::Scalar { .. } = types[ty_right].inner { - ty_left - } else if let crate::TypeInner::Matrix { columns, kind, width, .. } = types[ty_left].inner { - let inner = crate::TypeInner::Vector { size: columns, kind, width}; - Self::deduce_type_handle(inner, types) - } else { - panic!("Incompatible arguments {:?} x {:?}", types[ty_left], types[ty_right]); - } - } - crate::BinaryOperator::Equal | - crate::BinaryOperator::NotEqual | - crate::BinaryOperator::Less | - crate::BinaryOperator::LessEqual | - crate::BinaryOperator::Greater | - crate::BinaryOperator::GreaterEqual | - crate::BinaryOperator::LogicalAnd | - crate::BinaryOperator::LogicalOr => { - self.types[left.index()] - } - crate::BinaryOperator::And | - crate::BinaryOperator::ExclusiveOr | - crate::BinaryOperator::InclusiveOr | - crate::BinaryOperator::ShiftLeftLogical | - crate::BinaryOperator::ShiftRightLogical | - crate::BinaryOperator::ShiftRightArithmetic => { - self.types[left.index()] + crate::Expression::Binary { op, left, right } => match op { + crate::BinaryOperator::Add + | crate::BinaryOperator::Subtract + | crate::BinaryOperator::Divide + | crate::BinaryOperator::Modulo => self.types[left.index()], + crate::BinaryOperator::Multiply => { + let ty_left = self.types[left.index()]; + let ty_right = self.types[right.index()]; + if ty_left == ty_right { + ty_left + } else if let crate::TypeInner::Scalar { .. } = types[ty_right].inner { + ty_left + } else if let crate::TypeInner::Matrix { + columns, + kind, + width, + .. + } = types[ty_left].inner + { + let inner = crate::TypeInner::Vector { + size: columns, + kind, + width, + }; + Self::deduce_type_handle(inner, types) + } else { + panic!( + "Incompatible arguments {:?} x {:?}", + types[ty_left], types[ty_right] + ); } } - } + crate::BinaryOperator::Equal + | crate::BinaryOperator::NotEqual + | crate::BinaryOperator::Less + | crate::BinaryOperator::LessEqual + | crate::BinaryOperator::Greater + | crate::BinaryOperator::GreaterEqual + | crate::BinaryOperator::LogicalAnd + | crate::BinaryOperator::LogicalOr => self.types[left.index()], + crate::BinaryOperator::And + | crate::BinaryOperator::ExclusiveOr + | crate::BinaryOperator::InclusiveOr + | crate::BinaryOperator::ShiftLeftLogical + | crate::BinaryOperator::ShiftRightLogical + | crate::BinaryOperator::ShiftRightArithmetic => self.types[left.index()], + }, crate::Expression::Intrinsic { .. } => unimplemented!(), crate::Expression::DotProduct(_, _) => unimplemented!(), crate::Expression::CrossProduct(_, _) => unimplemented!(), crate::Expression::Derivative { .. } => unimplemented!(), - crate::Expression::Call { ref name, ref arguments } => { - match name.as_str() { - "distance" | "length" => { - let ty_handle = self.types[arguments[0].index()]; - let inner = match types[ty_handle].inner { - crate::TypeInner::Vector { kind, width, .. } => { - crate::TypeInner::Scalar { kind, width } - } - ref other => panic!("Unexpected argument {:?}", other), - }; - Self::deduce_type_handle(inner, types) - } - "normalize" | "fclamp" => self.types[arguments[0].index()], - _ => panic!("Unknown '{}' call", name), + crate::Expression::Call { + ref name, + ref arguments, + } => match name.as_str() { + "distance" | "length" => { + let ty_handle = self.types[arguments[0].index()]; + let inner = match types[ty_handle].inner { + crate::TypeInner::Vector { kind, width, .. } => { + crate::TypeInner::Scalar { kind, width } + } + ref other => panic!("Unexpected argument {:?}", other), + }; + Self::deduce_type_handle(inner, types) } - } + "normalize" | "fclamp" => self.types[arguments[0].index()], + other => functions[*function_lookup + .get(other) + .ok_or(ResolveError::FunctionNotDefined)?] + .return_type + .ok_or(ResolveError::FunctionReturnsVoid)?, + }, }; log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, ty); self.types.push(ty); - }; + } } Ok(self.types[expr_handle.index()]) } @@ -141,16 +195,10 @@ impl Typifier { inner: crate::TypeInner, arena: &mut Arena, ) -> Handle { - if let Some((token, _)) = arena - .iter() - .find(|(_, ty)| ty.inner == inner) - { + if let Some((token, _)) = arena.iter().find(|(_, ty)| ty.inner == inner) { return token; } - arena.append(crate::Type { - name: None, - inner, - }) + arena.append(crate::Type { name: None, inner }) } } diff --git a/test-data/glsl_if_preprocessor.vert b/test-data/glsl_if_preprocessor.vert new file mode 100644 index 000000000..64917a2c4 --- /dev/null +++ b/test-data/glsl_if_preprocessor.vert @@ -0,0 +1,14 @@ +#version 460 core + +#define TEST 3 +#define TEST_EXPR 2 && 2 + +#if TEST_EXPR - 2 == 0 +#error 0 +#elif TEST_EXPR - 2 == 1 +#error 1 +#elif TEST_EXPR - 2 == 2 +#error 2 +#else +#error You shouldn't do that +#endif diff --git a/test-data/glsl_phong_lighting.frag b/test-data/glsl_phong_lighting.frag new file mode 100644 index 000000000..6153f2caf --- /dev/null +++ b/test-data/glsl_phong_lighting.frag @@ -0,0 +1,56 @@ +#version 450 core + +layout(location=0) in vec3 v_position; +layout(location=1) in vec3 v_color; +layout(location=2) in vec3 v_normal; + +layout(location=0) out vec4 f_color; + +layout(set=0, binding=0) +uniform Globals { + mat4 u_view_proj; + vec3 u_view_position; +}; + +layout(set = 1, binding = 0) uniform Light { + vec3 u_position; + vec3 u_color; +}; + +layout(set=2, binding=0) +uniform Locals { + mat4 u_transform; + vec2 u_min_max; +}; + +layout (set = 2, binding = 1) uniform texture2D t_color; +layout (set = 2, binding = 2) uniform sampler s_color; + +float invLerp(float from, float to, float value){ + return (value - from) / (to - from); +} + +void main() { + vec3 object_color = + texture(sampler2D(t_color,s_color), vec2(invLerp(u_min_max.x,u_min_max.y,length(v_position)),0.0)).xyz; + + float ambient_strength = 0.1; + vec3 ambient_color = u_color * ambient_strength; + + vec3 normal = normalize(v_normal); + vec3 light_dir = normalize(u_position - v_position); + + float diffuse_strength = max(dot(normal, light_dir), 0.0); + vec3 diffuse_color = u_color * diffuse_strength; + + vec3 view_dir = normalize(u_view_position - v_position); + vec3 half_dir = normalize(view_dir + light_dir); + + float specular_strength = pow(max(dot(normal, half_dir), 0.0), 32); + + vec3 specular_color = specular_strength * u_color; + + vec3 result = (ambient_color + diffuse_color + specular_color) * object_color; + + f_color = vec4(result, 1.0); +} diff --git a/test-data/glsl_preprocessor_abuse.vert b/test-data/glsl_preprocessor_abuse.vert new file mode 100644 index 000000000..9f27c77da --- /dev/null +++ b/test-data/glsl_preprocessor_abuse.vert @@ -0,0 +1,11 @@ +#version 450 core + +#define MAIN void main() { +#define V_POSITION layout(location=0) in vec4 a_position; +#define ASSIGN_POSITION gl_Position = a_position; + +V_POSITION + +MAIN + ASSIGN_POSITION +} \ No newline at end of file diff --git a/test-data/glsl_vertex_test_shader.vert b/test-data/glsl_vertex_test_shader.vert new file mode 100644 index 000000000..b82d34f81 --- /dev/null +++ b/test-data/glsl_vertex_test_shader.vert @@ -0,0 +1,29 @@ +#version 450 core + +layout(location=0) in vec3 a_position; +layout(location=1) in vec3 a_color; +layout(location=2) in vec3 a_normal; + +layout(location=0) out vec3 v_position; +layout(location=1) out vec3 v_color; +layout(location=2) out vec3 v_normal; + +layout(set=0, binding=0) +uniform Globals { + mat4 u_view_proj; + vec3 u_view_position; +}; + +layout(set=2, binding=0) +uniform Locals { + mat4 u_transform; + vec2 U_min_max; +}; + +void main() { + v_color = a_color; + v_normal = a_normal; + + v_position = (u_transform * vec4(a_position, 1.0)).xyz; + gl_Position = u_view_proj * u_transform * vec4(a_position, 1.0); +} From f94b486d8b74eaa783bbe342449dc628aae533ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 9 Jun 2020 19:49:12 +0100 Subject: [PATCH 0076/2212] Run cargo fmt and enable monocodus (#63) --- .monocodus | 2 - examples/convert.rs | 7 +- src/back/mod.rs | 2 +- src/back/msl.rs | 507 +++++++++++++++++++++----------- src/front/spirv.rs | 656 ++++++++++++++++++++++++------------------ src/front/wgsl.rs | 417 +++++++++++++++------------ src/lib.rs | 43 ++- src/proc/interface.rs | 34 ++- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 27 +- tests/convert.rs | 35 ++- 11 files changed, 1053 insertions(+), 679 deletions(-) diff --git a/.monocodus b/.monocodus index 59d8a4711..b429007b9 100644 --- a/.monocodus +++ b/.monocodus @@ -3,5 +3,3 @@ version: 1.0.0 rust: formatter: name: rustfmt - ignore_paths: - - ".*" diff --git a/examples/convert.rs b/examples/convert.rs index c03e1d8fd..ba6e6a4a1 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -1,4 +1,4 @@ -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; use std::{env, fs}; #[derive(Hash, PartialEq, Eq, Serialize, Deserialize)] @@ -27,7 +27,7 @@ fn main() { let module = if args.len() <= 1 { println!("Call with "); - return + return; } else if args[1].ends_with(".spv") { let input = fs::read(&args[1]).unwrap(); naga::front::spirv::parse_u8_slice(&input).unwrap() @@ -43,8 +43,7 @@ fn main() { return; } - let param_path = std::path::PathBuf::from(&args[1]) - .with_extension("ron"); + let param_path = std::path::PathBuf::from(&args[1]).with_extension("ron"); let params = match fs::read_to_string(param_path) { Ok(string) => ron::de::from_str(&string).unwrap(), Err(_) => Parameters::default(), diff --git a/src/back/mod.rs b/src/back/mod.rs index f4f1fce17..4a194befe 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -1 +1 @@ -pub mod msl; \ No newline at end of file +pub mod msl; diff --git a/src/back/msl.rs b/src/back/msl.rs index a2086ef7f..20fe75cb0 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -14,16 +14,9 @@ the output struct. If there is a structure in the outputs, and it contains any b we move them up to the root output structure that we define ourselves. !*/ -use std::{ - fmt::{ - Display, Error as FmtError, Formatter, Write, - }, -}; +use std::fmt::{Display, Error as FmtError, Formatter, Write}; -use crate::{ - arena::Handle, - FastHashMap, -}; +use crate::{arena::Handle, FastHashMap}; /// Expect all the global variables to have a pointer type, /// like in SPIR-V. @@ -49,7 +42,10 @@ enum ResolvedBinding { BuiltIn(spirv::BuiltIn), Attribute(spirv::Word), Color(spirv::Word), - User { prefix: &'static str, index: spirv::Word }, + User { + prefix: &'static str, + index: spirv::Word, + }, Resource(BindTarget), } @@ -61,7 +57,7 @@ impl Level { } impl Display for Level { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - (0 .. self.0).map(|_| formatter.write_str("\t")).collect() + (0..self.0).map(|_| formatter.write_str("\t")).collect() } } @@ -115,7 +111,11 @@ pub struct Options<'a> { } impl Options<'_> { - fn resolve_binding(&self, binding: &crate::Binding, mode: LocationMode) -> Result { + fn resolve_binding( + &self, + binding: &crate::Binding, + mode: LocationMode, + ) -> Result { match *binding { crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), crate::Binding::Location(index) => match mode { @@ -134,13 +134,11 @@ impl Options<'_> { .cloned() .map(ResolvedBinding::Resource) .ok_or(Error::MissingBindTarget(source)) - } } } } - trait Indexed { const CLASS: &'static str; const PREFIX: bool = false; @@ -149,42 +147,58 @@ trait Indexed { impl Indexed for crate::Handle { const CLASS: &'static str = "Type"; - fn id(&self) -> usize { self.index() } + fn id(&self) -> usize { + self.index() + } } impl Indexed for crate::Handle { const CLASS: &'static str = "global"; - fn id(&self) -> usize { self.index() } + fn id(&self) -> usize { + self.index() + } } impl Indexed for crate::Handle { const CLASS: &'static str = "local"; - fn id(&self) -> usize { self.index() } + fn id(&self) -> usize { + self.index() + } } impl Indexed for crate::Handle { const CLASS: &'static str = "function"; - fn id(&self) -> usize { self.index() } + fn id(&self) -> usize { + self.index() + } } struct MemberIndex(usize); impl Indexed for MemberIndex { const CLASS: &'static str = "field"; - fn id(&self) -> usize { self.0 } + fn id(&self) -> usize { + self.0 + } } struct ParameterIndex(usize); impl Indexed for ParameterIndex { const CLASS: &'static str = "param"; - fn id(&self) -> usize { self.0 } + fn id(&self) -> usize { + self.0 + } } struct InputStructIndex(crate::Handle); impl Indexed for InputStructIndex { const CLASS: &'static str = "Input"; const PREFIX: bool = true; - fn id(&self) -> usize { self.0.index() } + fn id(&self) -> usize { + self.0.index() + } } struct OutputStructIndex(crate::Handle); impl Indexed for OutputStructIndex { const CLASS: &'static str = "Output"; const PREFIX: bool = true; - fn id(&self) -> usize { self.0.index() } + fn id(&self) -> usize { + self.0.index() + } } enum NameSource<'a> { @@ -192,9 +206,7 @@ enum NameSource<'a> { Index(usize), } -const RESERVED_NAMES: &[&str] = &[ - "main", -]; +const RESERVED_NAMES: &[&str] = &["main"]; struct Name<'a> { class: &'static str, @@ -203,10 +215,14 @@ struct Name<'a> { impl Display for Name<'_> { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { match self.source { - NameSource::Custom { name, prefix: false } if RESERVED_NAMES.contains(&name) => { - write!(formatter, "{}_", name) - } - NameSource::Custom { name, prefix: false } => formatter.write_str(name), + NameSource::Custom { + name, + prefix: false, + } if RESERVED_NAMES.contains(&name) => write!(formatter, "{}_", name), + NameSource::Custom { + name, + prefix: false, + } => formatter.write_str(name), NameSource::Custom { name, prefix: true } => { let (head, tail) = name.split_at(1); write!(formatter, "{}{}{}", self.class, head.to_uppercase(), tail) @@ -232,7 +248,10 @@ impl AsName for Option { Name { class: I::CLASS, source: match *self { - Some(ref name) if !name.is_empty() => NameSource::Custom { name, prefix: I::PREFIX }, + Some(ref name) if !name.is_empty() => NameSource::Custom { + name, + prefix: I::PREFIX, + }, _ => NameSource::Index(index.id()), }, } @@ -250,9 +269,9 @@ impl<'a> TypedGlobalVariable<'a> { let var = &self.module.global_variables[self.handle]; let name = var.name.or_index(self.handle); let (space_qualifier, reference) = match var.class { - spirv::StorageClass::Uniform | - spirv::StorageClass::UniformConstant | - spirv::StorageClass::StorageBuffer => { + spirv::StorageClass::Uniform + | spirv::StorageClass::UniformConstant + | spirv::StorageClass::StorageBuffer => { let space = if self.usage.contains(crate::GlobalUse::STORE) { "device " } else { @@ -260,18 +279,18 @@ impl<'a> TypedGlobalVariable<'a> { }; (space, "&") } - _ => ("", "") + _ => ("", ""), }; if GLOBAL_POINTERS { let ty = &self.module.types[var.ty]; match ty.inner { - crate::TypeInner::Pointer { base, class } => { + crate::TypeInner::Pointer { base, class } => { let ty_handle = match class { - spirv::StorageClass::Input | - spirv::StorageClass::Output | - spirv::StorageClass::Uniform | - spirv::StorageClass::UniformConstant => base, - _ => var.ty + spirv::StorageClass::Input + | spirv::StorageClass::Output + | spirv::StorageClass::Uniform + | spirv::StorageClass::UniformConstant => base, + _ => var.ty, }; let ty_name = self.module.types[ty_handle].name.or_index(ty_handle); Ok(write!(formatter, "{} {}", ty_name, name)?) @@ -280,7 +299,11 @@ impl<'a> TypedGlobalVariable<'a> { } } else { let ty_name = self.module.types[var.ty].name.or_index(var.ty); - Ok(write!(formatter, "{}{}{} {}", space_qualifier, ty_name, reference, name)?) + Ok(write!( + formatter, + "{}{}{} {}", + space_qualifier, ty_name, reference, name + )?) } } } @@ -298,12 +321,8 @@ impl ResolvedBinding { }; Ok(formatter.write_str(name)?) } - ResolvedBinding::Attribute(index) => { - Ok(write!(formatter, "attribute({})", index)?) - } - ResolvedBinding::Color(index) => { - Ok(write!(formatter, "color({})", index)?) - } + ResolvedBinding::Attribute(index) => Ok(write!(formatter, "attribute({})", index)?), + ResolvedBinding::Color(index) => Ok(write!(formatter, "color({})", index)?), ResolvedBinding::User { prefix, index } => { Ok(write!(formatter, "user({}{})", prefix, index)?) } @@ -321,7 +340,11 @@ impl ResolvedBinding { } } - fn try_fmt_decorated(&self, formatter: &mut W, terminator: &str) -> Result<(), Error> { + fn try_fmt_decorated( + &self, + formatter: &mut W, + terminator: &str, + ) -> Result<(), Error> { formatter.write_str(" [[")?; self.try_fmt(formatter)?; formatter.write_str("]]")?; @@ -356,7 +379,11 @@ const LOCATION_INPUT_STRUCT_NAME: &str = "input"; const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; fn separate(is_last: bool) -> &'static str { - if is_last { "" } else { "," } + if is_last { + "" + } else { + "," + } } #[derive(Debug)] @@ -410,9 +437,15 @@ impl Writer { write!(self.out, ".{}", name)?; Ok(module.borrow_type(member.ty)) } - crate::TypeInner::Matrix { rows, kind, width, .. } => { + crate::TypeInner::Matrix { + rows, kind, width, .. + } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; - Ok(MaybeOwned::Owned(crate::TypeInner::Vector { size: rows, kind, width })) + Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + size: rows, + kind, + width, + })) } crate::TypeInner::Vector { kind, width, .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; @@ -428,14 +461,17 @@ impl Writer { ref other => Err(Error::UnexpectedIndexing(other.clone())), } } - crate::Expression::Constant(handle) => { - self.put_constant(handle, module) - } + crate::Expression::Constant(handle) => self.put_constant(handle, module), crate::Expression::Compose { ty, ref components } => { let inner = &module.types[ty].inner; match *inner { crate::TypeInner::Vector { size, kind, .. } => { - write!(self.out, "{}{}(", scalar_kind_string(kind), vector_size_string(size))?; + write!( + self.out, + "{}{}(", + scalar_kind_string(kind), + vector_size_string(size) + )?; for (i, &handle) in components.iter().enumerate() { if i != 0 { write!(self.out, ",")?; @@ -461,7 +497,7 @@ impl Writer { } } } else if let crate::TypeInner::Struct { .. } = *inner { - return Ok(MaybeOwned::Borrowed(inner)); + return Ok(MaybeOwned::Borrowed(inner)); } write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; } @@ -486,9 +522,7 @@ impl Writer { crate::Expression::Load { pointer } => { //write!(self.out, "*")?; match *self.put_expression(pointer, function, module)?.borrow() { - crate::TypeInner::Pointer { base, .. } => { - Ok(module.borrow_type(base)) - } + crate::TypeInner::Pointer { base, .. } => Ok(module.borrow_type(base)), ref other => Err(Error::UnexpectedLoadPointer(other.clone())), } } @@ -523,20 +557,42 @@ impl Writer { Ok(if op_str.len() == 1 { match (ty_left.borrow(), ty_right.borrow()) { - (&crate::TypeInner::Scalar { kind, width }, &crate::TypeInner::Scalar { .. }) => - MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width }), - (&crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, kind, width }) | - (&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Scalar { .. }) | - (&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Vector { .. }) => - MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), - (other_left, other_right) => - return Err(Error::UnableToInferBinaryOpOutput(other_left.clone(), op, other_right.clone())), + ( + &crate::TypeInner::Scalar { kind, width }, + &crate::TypeInner::Scalar { .. }, + ) => MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width }), + ( + &crate::TypeInner::Scalar { .. }, + &crate::TypeInner::Vector { size, kind, width }, + ) + | ( + &crate::TypeInner::Vector { size, kind, width }, + &crate::TypeInner::Scalar { .. }, + ) + | ( + &crate::TypeInner::Vector { size, kind, width }, + &crate::TypeInner::Vector { .. }, + ) => MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), + (other_left, other_right) => { + return Err(Error::UnableToInferBinaryOpOutput( + other_left.clone(), + op, + other_right.clone(), + )) + } } } else { - MaybeOwned::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1 }) + MaybeOwned::Owned(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: 1, + }) }) } - crate::Expression::ImageSample { image, sampler, coordinate } => { + crate::Expression::ImageSample { + image, + sampler, + coordinate, + } => { let ty_image = self.put_expression(image, function, module)?; write!(self.out, ".sample(")?; self.put_expression(sampler, function, module)?; @@ -548,58 +604,67 @@ impl Writer { ref other => Err(Error::UnexpectedImageType(other.clone())), } } - crate::Expression::Call { ref name, ref arguments } => { - match name.as_str() { - "cos" | - "normalize" | - "sin" => { - write!(self.out, "{}(", name)?; - let result = self.put_expression(arguments[0], function, module)?; - write!(self.out, ")")?; - Ok(result) - } - "fclamp" => { - write!(self.out, "clamp(")?; - let result = self.put_expression(arguments[0], function, module)?; - write!(self.out, ", ")?; - self.put_expression(arguments[1], function, module)?; - write!(self.out, ", ")?; - self.put_expression(arguments[2], function, module)?; - write!(self.out, ")")?; - Ok(result) - } - "atan2" => { - write!(self.out, "{}(", name)?; - let result = self.put_expression(arguments[0], function, module)?; - write!(self.out, ", ")?; - self.put_expression(arguments[1], function, module)?; - write!(self.out, ")")?; - Ok(result) - } - "distance" => { - write!(self.out, "distance(")?; - let result = match *self.put_expression(arguments[0], function, module)?.borrow() { - crate::TypeInner::Vector { kind, width, .. } => crate::TypeInner::Scalar { kind, width }, - ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())), - }; - write!(self.out, ", ")?; - self.put_expression(arguments[1], function, module)?; - write!(self.out, ")")?; - Ok(MaybeOwned::Owned(result)) - } - "length" => { - write!(self.out, "length(")?; - let result = match *self.put_expression(arguments[0], function, module)?.borrow() { - crate::TypeInner::Vector { kind, width, .. } => crate::TypeInner::Scalar { kind, width }, - ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())), - }; - write!(self.out, ")")?; - Ok(MaybeOwned::Owned(result)) - } - - other => Err(Error::UnsupportedCall(other.to_owned())), + crate::Expression::Call { + ref name, + ref arguments, + } => match name.as_str() { + "cos" | "normalize" | "sin" => { + write!(self.out, "{}(", name)?; + let result = self.put_expression(arguments[0], function, module)?; + write!(self.out, ")")?; + Ok(result) } - } + "fclamp" => { + write!(self.out, "clamp(")?; + let result = self.put_expression(arguments[0], function, module)?; + write!(self.out, ", ")?; + self.put_expression(arguments[1], function, module)?; + write!(self.out, ", ")?; + self.put_expression(arguments[2], function, module)?; + write!(self.out, ")")?; + Ok(result) + } + "atan2" => { + write!(self.out, "{}(", name)?; + let result = self.put_expression(arguments[0], function, module)?; + write!(self.out, ", ")?; + self.put_expression(arguments[1], function, module)?; + write!(self.out, ")")?; + Ok(result) + } + "distance" => { + write!(self.out, "distance(")?; + let result = match *self + .put_expression(arguments[0], function, module)? + .borrow() + { + crate::TypeInner::Vector { kind, width, .. } => { + crate::TypeInner::Scalar { kind, width } + } + ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())), + }; + write!(self.out, ", ")?; + self.put_expression(arguments[1], function, module)?; + write!(self.out, ")")?; + Ok(MaybeOwned::Owned(result)) + } + "length" => { + write!(self.out, "length(")?; + let result = match *self + .put_expression(arguments[0], function, module)? + .borrow() + { + crate::TypeInner::Vector { kind, width, .. } => { + crate::TypeInner::Scalar { kind, width } + } + ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())), + }; + write!(self.out, ")")?; + Ok(MaybeOwned::Owned(result)) + } + + other => Err(Error::UnsupportedCall(other.to_owned())), + }, ref other => Err(Error::UnsupportedExpression(other.clone())), } } @@ -655,7 +720,11 @@ impl Writer { log::trace!("statement[{}] {:?}", level.0, statement); match *statement { crate::Statement::Empty => {} - crate::Statement::If { condition, ref accept, ref reject } => { + crate::Statement::If { + condition, + ref accept, + ref reject, + } => { write!(self.out, "{}if (", level)?; self.put_expression(condition, function, module)?; writeln!(self.out, ") {{")?; @@ -670,7 +739,10 @@ impl Writer { } writeln!(self.out, "{}}}", level)?; } - crate::Statement::Loop { ref body, ref continuing } => { + crate::Statement::Loop { + ref body, + ref continuing, + } => { writeln!(self.out, "{}while(true) {{", level)?; for s in body { self.put_statement(level.next(), s, function, has_output, module)?; @@ -733,20 +805,38 @@ impl Writer { match ty.inner { crate::TypeInner::Scalar { kind, .. } => { write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?; - }, + } crate::TypeInner::Vector { size, kind, .. } => { - write!(self.out, "typedef {}{} {}", scalar_kind_string(kind), vector_size_string(size), name)?; - }, - crate::TypeInner::Matrix { columns, rows, kind, .. } => { - write!(self.out, "typedef {}{}x{} {}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows), name)?; + write!( + self.out, + "typedef {}{} {}", + scalar_kind_string(kind), + vector_size_string(size), + name + )?; + } + crate::TypeInner::Matrix { + columns, + rows, + kind, + .. + } => { + write!( + self.out, + "typedef {}{}x{} {}", + scalar_kind_string(kind), + vector_size_string(columns), + vector_size_string(rows), + name + )?; } crate::TypeInner::Pointer { base, class } => { let base_name = module.types[base].name.or_index(base); let class_name = match class { - spirv::StorageClass::Input | - spirv::StorageClass::Output => continue, - spirv::StorageClass::Uniform | - spirv::StorageClass::UniformConstant => "constant", + spirv::StorageClass::Input | spirv::StorageClass::Output => continue, + spirv::StorageClass::Uniform | spirv::StorageClass::UniformConstant => { + "constant" + } other => { log::warn!("Unexpected pointer class {:?}", other); "" @@ -760,7 +850,11 @@ impl Writer { crate::ArraySize::Static(length) => length, crate::ArraySize::Dynamic => 1, }; - write!(self.out, "typedef {} {}[{}]", base_name, name, resolved_size)?; + write!( + self.out, + "typedef {} {}[{}]", + base_name, name, resolved_size + )?; } crate::TypeInner::Struct { ref members } => { writeln!(self.out, "struct {} {{", name)?; @@ -769,7 +863,8 @@ impl Writer { let base_name = module.types[member.ty].name.or_index(member.ty); write!(self.out, "\t{} {}", base_name, name)?; if let Some(ref binding) = member.binding { - let resolved = options.resolve_binding(binding, LocationMode::Intermediate)?; + let resolved = + options.resolve_binding(binding, LocationMode::Intermediate)?; resolved.try_fmt_decorated(&mut self.out, "")?; } writeln!(self.out, ";")?; @@ -790,7 +885,9 @@ impl Writer { return Err(Error::InvalidImageFlags(flags)); } "sample" - } else if flags.contains(crate::ImageFlags::CAN_LOAD | crate::ImageFlags::CAN_STORE) { + } else if flags + .contains(crate::ImageFlags::CAN_LOAD | crate::ImageFlags::CAN_STORE) + { "read_write" } else if flags.contains(crate::ImageFlags::CAN_STORE) { "write" @@ -799,7 +896,11 @@ impl Writer { } else { return Err(Error::InvalidImageFlags(flags)); }; - write!(self.out, "typedef texture{}<{}, access::{}> {}", dim, base_name, access, name)?; + write!( + self.out, + "typedef texture{}<{}, access::{}> {}", + dim, base_name, access, name + )?; } crate::TypeInner::Sampler => { write!(self.out, "typedef sampler {}", name)?; @@ -820,7 +921,7 @@ impl Writer { match var.class { spirv::StorageClass::Input => { if let Some(crate::Binding::Location(_)) = var.binding { - continue + continue; } } spirv::StorageClass::Output => continue, @@ -846,32 +947,52 @@ impl Writer { // make dedicated input/output structs if let Some(em) = exec_model { if let Some(return_type) = fun.return_type { - return Err(Error::ExecutionModelReturnType(em, return_type)) + return Err(Error::ExecutionModelReturnType(em, return_type)); } let (em_str, in_mode, out_mode) = match em { - spirv::ExecutionModel::Vertex => ("vertex", LocationMode::VertexInput, LocationMode::Intermediate), - spirv::ExecutionModel::Fragment => ("fragment", LocationMode::Intermediate, LocationMode::FragmentOutput), - spirv::ExecutionModel::GLCompute => ("kernel", LocationMode::Uniform, LocationMode::Uniform), + spirv::ExecutionModel::Vertex => ( + "vertex", + LocationMode::VertexInput, + LocationMode::Intermediate, + ), + spirv::ExecutionModel::Fragment => ( + "fragment", + LocationMode::Intermediate, + LocationMode::FragmentOutput, + ), + spirv::ExecutionModel::GLCompute => { + ("kernel", LocationMode::Uniform, LocationMode::Uniform) + } _ => return Err(Error::UnsupportedExecutionModel(em)), }; let location_input_name = fun.name.or_index(InputStructIndex(fun_handle)); if em != spirv::ExecutionModel::GLCompute { writeln!(self.out, "struct {} {{", location_input_name)?; - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { - if var.class != spirv::StorageClass::Input || !usage.contains(crate::GlobalUse::LOAD) { - continue + for ((handle, var), &usage) in + module.global_variables.iter().zip(&fun.global_usage) + { + if var.class != spirv::StorageClass::Input + || !usage.contains(crate::GlobalUse::LOAD) + { + continue; } // if it's a struct, lift all the built-in contents up to the root let mut ty_handle = var.ty; if GLOBAL_POINTERS { - if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner { + if let crate::TypeInner::Pointer { base, .. } = + module.types[var.ty].inner + { ty_handle = base; } } - if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner { + if let crate::TypeInner::Struct { ref members } = + module.types[ty_handle].inner + { for (index, member) in members.iter().enumerate() { - if let Some(ref binding@crate::Binding::Location(_)) = member.binding { + if let Some(ref binding @ crate::Binding::Location(_)) = + member.binding + { let name = member.name.or_index(MemberIndex(index)); let ty_name = module.types[member.ty].name.or_index(member.ty); let resolved = options.resolve_binding(binding, in_mode)?; @@ -879,8 +1000,13 @@ impl Writer { resolved.try_fmt_decorated(&mut self.out, ";\n")?; } } - } else if let Some(ref binding@crate::Binding::Location(_)) = var.binding { - let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() }; + } else if let Some(ref binding @ crate::Binding::Location(_)) = var.binding + { + let tyvar = TypedGlobalVariable { + module, + handle, + usage: crate::GlobalUse::empty(), + }; let resolved = options.resolve_binding(binding, in_mode)?; write!(self.out, "\t")?; @@ -890,22 +1016,31 @@ impl Writer { } writeln!(self.out, "}};")?; writeln!(self.out, "struct {} {{", output_name)?; - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { - if var.class != spirv::StorageClass::Output || !usage.contains(crate::GlobalUse::STORE) { - continue + for ((handle, var), &usage) in + module.global_variables.iter().zip(&fun.global_usage) + { + if var.class != spirv::StorageClass::Output + || !usage.contains(crate::GlobalUse::STORE) + { + continue; } // if it's a struct, lift all the built-in contents up to the root let mut ty_handle = var.ty; if GLOBAL_POINTERS { - if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner { + if let crate::TypeInner::Pointer { base, .. } = + module.types[var.ty].inner + { ty_handle = base; } } - if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner { + if let crate::TypeInner::Struct { ref members } = + module.types[ty_handle].inner + { for (index, member) in members.iter().enumerate() { let name = member.name.or_index(MemberIndex(index)); let ty_name = module.types[member.ty].name.or_index(member.ty); - let binding = member.binding + let binding = member + .binding .as_ref() .ok_or(Error::MissingBinding(handle))?; let resolved = options.resolve_binding(binding, out_mode)?; @@ -913,7 +1048,11 @@ impl Writer { resolved.try_fmt_decorated(&mut self.out, ";\n")?; } } else { - let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() }; + let tyvar = TypedGlobalVariable { + module, + handle, + usage: crate::GlobalUse::empty(), + }; write!(self.out, "\t")?; tyvar.try_fmt(&mut self.out)?; if let Some(ref binding) = var.binding { @@ -926,31 +1065,46 @@ impl Writer { writeln!(self.out, "}};")?; writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; let separator = separate(last_used_global.is_none()); - writeln!(self.out, "\t{} {} [[stage_in]]{}", - location_input_name, LOCATION_INPUT_STRUCT_NAME, separator)?; + writeln!( + self.out, + "\t{} {} [[stage_in]]{}", + location_input_name, LOCATION_INPUT_STRUCT_NAME, separator + )?; } else { writeln!(self.out, "{} void {}(", em_str, fun_name)?; } - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { + for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) + { if usage.is_empty() || var.class == spirv::StorageClass::Output { - continue + continue; } if var.class == spirv::StorageClass::Input { if let Some(crate::Binding::Location(_)) = var.binding { // location inputs are put into a separate struct - continue + continue; } } let loc_mode = match (em, var.class) { - (spirv::ExecutionModel::Vertex, spirv::StorageClass::Input) => LocationMode::VertexInput, - (spirv::ExecutionModel::Vertex, spirv::StorageClass::Output) | - (spirv::ExecutionModel::Fragment, spirv::StorageClass::Input) => LocationMode::Intermediate, - (spirv::ExecutionModel::Fragment, spirv::StorageClass::Output) => LocationMode::FragmentOutput, + (spirv::ExecutionModel::Vertex, spirv::StorageClass::Input) => { + LocationMode::VertexInput + } + (spirv::ExecutionModel::Vertex, spirv::StorageClass::Output) + | (spirv::ExecutionModel::Fragment, spirv::StorageClass::Input) => { + LocationMode::Intermediate + } + (spirv::ExecutionModel::Fragment, spirv::StorageClass::Output) => { + LocationMode::FragmentOutput + } _ => LocationMode::Uniform, }; - let resolved = options.resolve_binding(var.binding.as_ref().unwrap(), loc_mode)?; - let tyvar = TypedGlobalVariable { module, handle, usage }; + let resolved = + options.resolve_binding(var.binding.as_ref().unwrap(), loc_mode)?; + let tyvar = TypedGlobalVariable { + module, + handle, + usage, + }; let separator = separate(last_used_global == Some(handle)); write!(self.out, "\t")?; tyvar.try_fmt(&mut self.out)?; @@ -962,14 +1116,19 @@ impl Writer { Some(type_id) => module.types[type_id].name.or_index(type_id), None => Name { class: "", - source: NameSource::Custom { name: "void", prefix: false }, + source: NameSource::Custom { + name: "void", + prefix: false, + }, }, }; writeln!(self.out, "{} {}(", result_type_name, fun_name)?; for (index, &ty) in fun.parameter_types.iter().enumerate() { let name = Name::from(ParameterIndex(index)); let member_type_name = module.types[ty].name.or_index(ty); - let separator = separate(index + 1 == fun.parameter_types.len() && last_used_global.is_none()); + let separator = separate( + index + 1 == fun.parameter_types.len() && last_used_global.is_none(), + ); writeln!(self.out, "\t{} {}{}", member_type_name, name, separator)?; } } @@ -977,16 +1136,20 @@ impl Writer { // write down function body let has_output = match exec_model { - Some(spirv::ExecutionModel::Vertex) | - Some(spirv::ExecutionModel::Fragment) => { + Some(spirv::ExecutionModel::Vertex) | Some(spirv::ExecutionModel::Fragment) => { writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?; true } - _ => false + _ => false, }; for (local_handle, local) in fun.local_variables.iter() { let ty_name = module.types[local.ty].name.or_index(local.ty); - write!(self.out, "\t{} {}", ty_name, local.name.or_index(local_handle))?; + write!( + self.out, + "\t{} {}", + ty_name, + local.name.or_index(local_handle) + )?; if let Some(value) = local.init { write!(self.out, " = ")?; self.put_expression(value, fun, module)?; diff --git a/src/front/spirv.rs b/src/front/spirv.rs index 142d00576..1ebd1b1f0 100644 --- a/src/front/spirv.rs +++ b/src/front/spirv.rs @@ -18,14 +18,9 @@ use crate::{ use num_traits::cast::FromPrimitive; use std::convert::TryInto; -pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ - spirv::Capability::Shader, -]; -pub const SUPPORTED_EXTENSIONS: &[&str] = &[ -]; -pub const SUPPORTED_EXT_SETS: &[&str] = &[ - "GLSL.std.450", -]; +pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[spirv::Capability::Shader]; +pub const SUPPORTED_EXTENSIONS: &[&str] = &[]; +pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"]; #[derive(Debug)] pub enum Error { @@ -265,7 +260,7 @@ impl> Parser { Ok(Instruction { op, wc }) } - fn next_string(&mut self, mut count: u16) -> Result<(String, u16), Error>{ + fn next_string(&mut self, mut count: u16) -> Result<(String, u16), Error> { self.temp_bytes.clear(); loop { if count == 0 { @@ -273,10 +268,10 @@ impl> Parser { } count -= 1; let chars = self.next()?.to_le_bytes(); - let pos = chars.iter().position(|&c| c == 0).unwrap_or(4); - self.temp_bytes.extend_from_slice(&chars[.. pos]); + let pos = chars.iter().position(|&c| c == 0).unwrap_or(4); + self.temp_bytes.extend_from_slice(&chars[..pos]); if pos < 4 { - break + break; } } std::str::from_utf8(&self.temp_bytes) @@ -317,7 +312,7 @@ impl> Parser { } other => { log::warn!("Unknown decoration {:?}", other); - for _ in base_words + 1 .. inst.wc { + for _ in base_words + 1..inst.wc { let _var = self.next()?; } } @@ -354,14 +349,20 @@ impl> Parser { type_id: ptr_type.base_id.unwrap(), } }; - for _ in 4 .. inst.wc { + for _ in 4..inst.wc { let access_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", access_id); let index_expr = self.lookup_expression.lookup(access_id)?.clone(); let index_type_handle = self.lookup_type.lookup(index_expr.type_id)?.handle; match type_arena[index_type_handle].inner { - crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, .. } | - crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, .. } => (), + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } + | crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + .. + } => (), _ => return Err(Error::UnsupportedType(index_type_handle)), } log::trace!("\t\t\tlooking up type {:?}", acex.type_id); @@ -373,41 +374,50 @@ impl> Parser { match const_arena[const_handle].inner { crate::ConstantInner::Uint(v) => v as u32, crate::ConstantInner::Sint(v) => v as u32, - _ => return Err(Error::InvalidAccessIndex(index_expr.handle)), + _ => { + return Err(Error::InvalidAccessIndex( + index_expr.handle, + )) + } } } - _ => return Err(Error::InvalidAccessIndex(index_expr.handle)) + _ => return Err(Error::InvalidAccessIndex(index_expr.handle)), }; AccessExpression { - base_handle: fun.expressions.append(crate::Expression::AccessIndex { - base: acex.base_handle, - index, - }), - type_id: *self.lookup_member_type_id + base_handle: fun.expressions.append( + crate::Expression::AccessIndex { + base: acex.base_handle, + index, + }, + ), + type_id: *self + .lookup_member_type_id .get(&(acex.type_id, index)) .ok_or(Error::InvalidAccessType(acex.type_id))?, } } - crate::TypeInner::Array { .. } | - crate::TypeInner::Vector { .. } | - crate::TypeInner::Matrix { .. } => { - AccessExpression { - base_handle: fun.expressions.append(crate::Expression::Access { - base: acex.base_handle, - index: index_expr.handle, - }), - type_id: type_lookup.base_id - .ok_or(Error::InvalidAccessType(acex.type_id))?, - } - } + crate::TypeInner::Array { .. } + | crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } => AccessExpression { + base_handle: fun.expressions.append(crate::Expression::Access { + base: acex.base_handle, + index: index_expr.handle, + }), + type_id: type_lookup + .base_id + .ok_or(Error::InvalidAccessType(acex.type_id))?, + }, _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; } - self.lookup_expression.insert(result_id, LookupExpression { - handle: acex.base_handle, - type_id: result_type_id, - }); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: acex.base_handle, + type_id: result_type_id, + }, + ); } Op::CompositeExtract => { inst.expect_at_least(4)?; @@ -422,22 +432,20 @@ impl> Parser { type_id: expr.type_id, } }; - for _ in 4 .. inst.wc { + for _ in 4..inst.wc { let index = self.next()?; log::trace!("\t\t\tlooking up type {:?}", lexp.type_id); let type_lookup = self.lookup_type.lookup(lexp.type_id)?; let type_id = match type_arena[type_lookup.handle].inner { - crate::TypeInner::Struct { .. } => { - *self.lookup_member_type_id - .get(&(lexp.type_id, index)) - .ok_or(Error::InvalidAccessType(lexp.type_id))? - } - crate::TypeInner::Array { .. } | - crate::TypeInner::Vector { .. } | - crate::TypeInner::Matrix { .. } => { - type_lookup.base_id - .ok_or(Error::InvalidAccessType(lexp.type_id))? - } + crate::TypeInner::Struct { .. } => *self + .lookup_member_type_id + .get(&(lexp.type_id, index)) + .ok_or(Error::InvalidAccessType(lexp.type_id))?, + crate::TypeInner::Array { .. } + | crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } => type_lookup + .base_id + .ok_or(Error::InvalidAccessType(lexp.type_id))?, _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; lexp = LookupExpression { @@ -449,17 +457,20 @@ impl> Parser { }; } - self.lookup_expression.insert(result_id, LookupExpression { - handle: lexp.handle, - type_id: result_type_id, - }); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: lexp.handle, + type_id: result_type_id, + }, + ); } Op::CompositeConstruct => { inst.expect_at_least(3)?; let result_type_id = self.next()?; let id = self.next()?; - let mut components = Vec::with_capacity(inst.wc as usize - 2); - for _ in 3 .. inst.wc { + let mut components = Vec::with_capacity(inst.wc as usize - 2); + for _ in 3..inst.wc { let comp_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", comp_id); let lexp = self.lookup_expression.lookup(comp_id)?; @@ -469,10 +480,13 @@ impl> Parser { ty: self.lookup_type.lookup(result_type_id)?.handle, components, }; - self.lookup_expression.insert(id, LookupExpression { - handle: fun.expressions.append(expr), - type_id: result_type_id, - }); + self.lookup_expression.insert( + id, + LookupExpression { + handle: fun.expressions.append(expr), + type_id: result_type_id, + }, + ); } Op::Load => { inst.expect_at_least(4)?; @@ -495,10 +509,13 @@ impl> Parser { let expr = crate::Expression::Load { pointer: base_expr.handle, }; - self.lookup_expression.insert(result_id, LookupExpression { - handle: fun.expressions.append(expr), - type_id: result_type_id, - }); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: fun.expressions.append(expr), + type_id: result_type_id, + }, + ); } Op::Store => { inst.expect_at_least(3)?; @@ -526,14 +543,18 @@ impl> Parser { Op::Return => { inst.expect(1)?; fun.body.push(crate::Statement::Return { value: None }); - break + break; } Op::VectorTimesScalar => { inst.expect(5)?; let result_type_id = self.next()?; let result_type_loookup = self.lookup_type.lookup(result_type_id)?; let (res_size, res_width) = match type_arena[result_type_loookup.handle].inner { - crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), + crate::TypeInner::Vector { + size, + kind: crate::ScalarKind::Float, + width, + } => (size, width), _ => return Err(Error::UnsupportedType(result_type_loookup.handle)), }; let result_id = self.next()?; @@ -542,13 +563,20 @@ impl> Parser { let vector_lexp = self.lookup_expression.lookup(vector_id)?; let vector_type_lookup = self.lookup_type.lookup(vector_lexp.type_id)?; match type_arena[vector_type_lookup.handle].inner { - crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } if size == res_size && width == res_width => (), + crate::TypeInner::Vector { + size, + kind: crate::ScalarKind::Float, + width, + } if size == res_size && width == res_width => (), _ => return Err(Error::UnsupportedType(vector_type_lookup.handle)), }; let scalar_lexp = self.lookup_expression.lookup(scalar_id)?.clone(); let scalar_type_lookup = self.lookup_type.lookup(scalar_lexp.type_id)?; match type_arena[scalar_type_lookup.handle].inner { - crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width } if width == res_width => (), + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width, + } if width == res_width => (), _ => return Err(Error::UnsupportedType(scalar_type_lookup.handle)), }; let expr = crate::Expression::Binary { @@ -556,17 +584,24 @@ impl> Parser { left: vector_lexp.handle, right: scalar_lexp.handle, }; - self.lookup_expression.insert(result_id, LookupExpression { - handle: fun.expressions.append(expr), - type_id: result_type_id, - }); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: fun.expressions.append(expr), + type_id: result_type_id, + }, + ); } Op::MatrixTimesVector => { inst.expect(5)?; let result_type_id = self.next()?; let result_type_loookup = self.lookup_type.lookup(result_type_id)?; let (res_size, res_width) = match type_arena[result_type_loookup.handle].inner { - crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } => (size, width), + crate::TypeInner::Vector { + size, + kind: crate::ScalarKind::Float, + width, + } => (size, width), _ => return Err(Error::UnsupportedType(result_type_loookup.handle)), }; let result_id = self.next()?; @@ -575,13 +610,22 @@ impl> Parser { let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; let matrix_type_lookup = self.lookup_type.lookup(matrix_lexp.type_id)?; let columns = match type_arena[matrix_type_lookup.handle].inner { - crate::TypeInner::Matrix { columns, rows, kind: crate::ScalarKind::Float, width } if rows == res_size && width == res_width => columns, + crate::TypeInner::Matrix { + columns, + rows, + kind: crate::ScalarKind::Float, + width, + } if rows == res_size && width == res_width => columns, _ => return Err(Error::UnsupportedType(matrix_type_lookup.handle)), }; let vector_lexp = self.lookup_expression.lookup(vector_id)?.clone(); let vector_type_lookup = self.lookup_type.lookup(vector_lexp.type_id)?; match type_arena[vector_type_lookup.handle].inner { - crate::TypeInner::Vector { size, kind: crate::ScalarKind::Float, width } if size == columns && width == res_width => (), + crate::TypeInner::Vector { + size, + kind: crate::ScalarKind::Float, + width, + } if size == columns && width == res_width => (), _ => return Err(Error::UnsupportedType(vector_type_lookup.handle)), }; let expr = crate::Expression::Binary { @@ -589,10 +633,13 @@ impl> Parser { left: matrix_lexp.handle, right: vector_lexp.handle, }; - self.lookup_expression.insert(result_id, LookupExpression { - handle: fun.expressions.append(expr), - type_id: result_type_id, - }); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: fun.expressions.append(expr), + type_id: result_type_id, + }, + ); } Op::SampledImage => { inst.expect(5)?; @@ -603,10 +650,13 @@ impl> Parser { let image_lexp = self.lookup_expression.lookup(image_id)?; let sampler_lexp = self.lookup_expression.lookup(sampler_id)?; //TODO: compare the result type - self.lookup_sampled_image.insert(result_id, LookupSampledImage { - image: image_lexp.handle, - sampler: sampler_lexp.handle, - }); + self.lookup_sampled_image.insert( + result_id, + LookupSampledImage { + image: image_lexp.handle, + sampler: sampler_lexp.handle, + }, + ); } Op::ImageSampleImplicitLod => { inst.expect_at_least(5)?; @@ -618,8 +668,14 @@ impl> Parser { let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_lookup = self.lookup_type.lookup(coord_lexp.type_id)?; match type_arena[coord_type_lookup.handle].inner { - crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, .. } | - crate::TypeInner::Vector { kind: crate::ScalarKind::Float, .. } => (), + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + .. + } + | crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + .. + } => (), _ => return Err(Error::UnsupportedType(coord_type_lookup.handle)), } //TODO: compare the result type @@ -628,10 +684,13 @@ impl> Parser { sampler: si_lexp.sampler, coordinate: coord_lexp.handle, }; - self.lookup_expression.insert(result_id, LookupExpression { - handle: fun.expressions.append(expr), - type_id: result_type_id, - }); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: fun.expressions.append(expr), + type_id: result_type_id, + }, + ); } _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } @@ -644,17 +703,23 @@ impl> Parser { assert!(self.lookup_expression.is_empty()); // register global variables for (&id, var) in self.lookup_variable.iter() { - self.lookup_expression.insert(id, LookupExpression { - type_id: var.type_id, - handle: expressions.append(crate::Expression::GlobalVariable(var.handle)), - }); + self.lookup_expression.insert( + id, + LookupExpression { + type_id: var.type_id, + handle: expressions.append(crate::Expression::GlobalVariable(var.handle)), + }, + ); } // register constants for (&id, con) in self.lookup_constant.iter() { - self.lookup_expression.insert(id, LookupExpression { - type_id: con.type_id, - handle: expressions.append(crate::Expression::Constant(con.handle)), - }); + self.lookup_expression.insert( + id, + LookupExpression { + type_id: con.type_id, + handle: expressions.append(crate::Expression::Constant(con.handle)), + }, + ); } // done expressions @@ -806,10 +871,7 @@ impl> Parser { exec_model, name, function_id, - variable_ids: self.data - .by_ref() - .take(left as usize) - .collect(), + variable_ids: self.data.by_ref().take(left as usize).collect(), }; entry_points.push(ep); Ok(()) @@ -828,7 +890,7 @@ impl> Parser { fn parse_source(&mut self, inst: Instruction) -> Result<(), Error> { self.switch(ModuleState::Source, inst.op)?; - for _ in 1 .. inst.wc { + for _ in 1..inst.wc { let _ = self.next()?; } Ok(()) @@ -849,10 +911,7 @@ impl> Parser { if left != 0 { return Err(Error::InvalidOperand); } - self.future_decor - .entry(id) - .or_default() - .name = Some(name); + self.future_decor.entry(id).or_default().name = Some(name); Ok(()) } @@ -876,9 +935,7 @@ impl> Parser { self.switch(ModuleState::Annotation, inst.op)?; inst.expect_at_least(3)?; let id = self.next()?; - let mut dec = self.future_decor - .remove(&id) - .unwrap_or_default(); + let mut dec = self.future_decor.remove(&id).unwrap_or_default(); self.next_decoration(inst, 2, &mut dec)?; self.future_decor.insert(id, dec); Ok(()) @@ -889,7 +946,8 @@ impl> Parser { inst.expect_at_least(4)?; let id = self.next()?; let member = self.next()?; - let mut dec = self.future_member_decor + let mut dec = self + .future_member_decor .remove(&(id, member)) .unwrap_or_default(); self.next_decoration(inst, 3, &mut dec)?; @@ -925,15 +983,16 @@ impl> Parser { .try_into() .map_err(|_| Error::InvalidTypeWidth(width))?, }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: None, - }); + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: None, + }, + ); Ok(()) } @@ -952,15 +1011,16 @@ impl> Parser { .try_into() .map_err(|_| Error::InvalidTypeWidth(width))?, }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: None, - }); + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: None, + }, + ); Ok(()) } @@ -984,15 +1044,16 @@ impl> Parser { kind, width, }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: Some(type_id), - }); + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: Some(type_id), + }, + ); Ok(()) } @@ -1016,15 +1077,16 @@ impl> Parser { }, _ => return Err(Error::InvalidInnerType(vector_type_id)), }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: Some(vector_type_id), - }); + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: Some(vector_type_id), + }, + ); Ok(()) } @@ -1033,14 +1095,14 @@ impl> Parser { inst.expect_at_least(3)?; let id = self.next()?; let return_type_id = self.next()?; - let parameter_type_ids = self.data - .by_ref() - .take(inst.wc as usize - 3) - .collect(); - self.lookup_function_type.insert(id, LookupFunctionType { - parameter_type_ids, - return_type_id, - }); + let parameter_type_ids = self.data.by_ref().take(inst.wc as usize - 3).collect(); + self.lookup_function_type.insert( + id, + LookupFunctionType { + parameter_type_ids, + return_type_id, + }, + ); Ok(()) } @@ -1058,15 +1120,16 @@ impl> Parser { base: self.lookup_type.lookup(type_id)?.handle, class: map_storage_class(storage)?, }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: Some(type_id), - }); + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: Some(type_id), + }, + ); Ok(()) } @@ -1084,15 +1147,16 @@ impl> Parser { base: self.lookup_type.lookup(type_id)?.handle, size: crate::ArraySize::Static(length), }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - inner, - }), - base_id: Some(type_id), - }); + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: Some(type_id), + }, + ); Ok(()) } @@ -1109,13 +1173,16 @@ impl> Parser { base: self.lookup_type.lookup(type_id)?.handle, size: crate::ArraySize::Dynamic, }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - inner, - }), - base_id: Some(type_id), - }); + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: Some(type_id), + }, + ); Ok(()) } @@ -1128,11 +1195,12 @@ impl> Parser { inst.expect_at_least(2)?; let id = self.next()?; let mut members = Vec::with_capacity(inst.wc as usize - 2); - for i in 0 .. u32::from(inst.wc) - 2 { + for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; let ty = self.lookup_type.lookup(type_id)?.handle; self.lookup_member_type_id.insert((id, i), type_id); - let decor = self.future_member_decor + let decor = self + .future_member_decor .remove(&(id, i)) .unwrap_or_default(); let binding = decor.get_binding(); @@ -1142,16 +1210,17 @@ impl> Parser { ty, }); } - let inner = crate::TypeInner::Struct { - members - }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - inner, - }), - base_id: None, - }); + let inner = crate::TypeInner::Struct { members }; + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: None, + }, + ); Ok(()) } @@ -1190,22 +1259,23 @@ impl> Parser { } }; - let decor = self.future_decor - .remove(&id) - .unwrap_or_default(); + let decor = self.future_decor.remove(&id).unwrap_or_default(); let inner = crate::TypeInner::Image { base: self.lookup_type.lookup(sample_type_id)?.handle, dim: spirv::Dim::from_u32(dim).ok_or(Error::UnsupportedDim(dim))?, flags, }; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: decor.name, - inner, - }), - base_id: Some(sample_type_id), - }); + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: decor.name, + inner, + }), + base_id: Some(sample_type_id), + }, + ); Ok(()) } @@ -1214,10 +1284,13 @@ impl> Parser { inst.expect(3)?; let id = self.next()?; let image_id = self.next()?; - self.lookup_type.insert(id, LookupType { - handle: self.lookup_type.lookup(image_id)?.handle, - base_id: Some(image_id), - }); + self.lookup_type.insert( + id, + LookupType { + handle: self.lookup_type.lookup(image_id)?.handle, + base_id: Some(image_id), + }, + ); Ok(()) } @@ -1229,17 +1302,18 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect(2)?; let id = self.next()?; - let decor = self.future_decor - .remove(&id) - .unwrap_or_default(); + let decor = self.future_decor.remove(&id).unwrap_or_default(); let inner = crate::TypeInner::Sampler; - self.lookup_type.insert(id, LookupType { - handle: module.types.append(crate::Type { - name: decor.name, - inner, - }), - base_id: None, - }); + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: decor.name, + inner, + }), + base_id: None, + }, + ); Ok(()) } @@ -1255,7 +1329,10 @@ impl> Parser { let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; let inner = match module.types[type_lookup.handle].inner { - crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width } => { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width, + } => { let low = self.next()?; let high = if width > 32 { inst.expect(4)?; @@ -1265,7 +1342,10 @@ impl> Parser { }; crate::ConstantInner::Uint((u64::from(high) << 32) | u64::from(low)) } - crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width } => { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width, + } => { use std::cmp::Ordering; let low = self.next()?; let high = match width.cmp(&32) { @@ -1273,12 +1353,15 @@ impl> Parser { Ordering::Greater => { inst.expect(4)?; self.next()? - }, - Ordering::Equal => !0 + } + Ordering::Equal => !0, }; crate::ConstantInner::Sint(((u64::from(high) << 32) | u64::from(low)) as i64) } - crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width } => { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width, + } => { let low = self.next()?; let extended = match width { 32 => f64::from(f32::from_bits(low)), @@ -1291,19 +1374,20 @@ impl> Parser { }; crate::ConstantInner::Float(extended) } - _ => return Err(Error::UnsupportedType(type_lookup.handle)) + _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; - self.lookup_constant.insert(id, LookupConstant { - handle: module.constants.append(crate::Constant { - name: self.future_decor - .remove(&id) - .and_then(|dec| dec.name), - specialization: None, //TODO - inner, - ty, - }), - type_id, - }); + self.lookup_constant.insert( + id, + LookupConstant { + handle: module.constants.append(crate::Constant { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + specialization: None, //TODO + inner, + ty, + }), + type_id, + }, + ); Ok(()) } @@ -1328,17 +1412,18 @@ impl> Parser { constituents.push(constant.handle); } - self.lookup_constant.insert(id, LookupConstant { - handle: module.constants.append(crate::Constant { - name: self.future_decor - .remove(&id) - .and_then(|dec|dec.name), - specialization: None, - inner: crate::ConstantInner::Composite(constituents), - ty - }), - type_id - }); + self.lookup_constant.insert( + id, + LookupConstant { + handle: module.constants.append(crate::Constant { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + specialization: None, + inner: crate::ConstantInner::Composite(constituents), + ty, + }), + type_id, + }, + ); Ok(()) } @@ -1358,38 +1443,39 @@ impl> Parser { let _init = self.next()?; //TODO } let lookup_type = self.lookup_type.lookup(type_id)?; - let dec = self.future_decor + let dec = self + .future_decor .remove(&id) .ok_or(Error::InvalidBinding(id))?; let binding = match module.types[lookup_type.handle].inner { - crate::TypeInner::Pointer { base, class: spirv::StorageClass::Input } | - crate::TypeInner::Pointer { base, class: spirv::StorageClass::Output } => { + crate::TypeInner::Pointer { + base, + class: spirv::StorageClass::Input, + } + | crate::TypeInner::Pointer { + base, + class: spirv::StorageClass::Output, + } => { match module.types[base].inner { crate::TypeInner::Struct { ref members } => { // we don't expect binding decoration on I/O structs, // but we do expect them on all of the members for member in members { if member.binding.is_none() { - log::warn!("Struct {:?} member {:?} doesn't have a binding", base, member); + log::warn!( + "Struct {:?} member {:?} doesn't have a binding", + base, + member + ); return Err(Error::InvalidBinding(id)); } } None } - _ => { - Some(dec - .get_binding() - .ok_or(Error::InvalidBinding(id))? - ) - } + _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), } } - _ => { - Some(dec - .get_binding() - .ok_or(Error::InvalidBinding(id))? - ) - } + _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), }; let var = crate::GlobalVariable { name: dec.name, @@ -1397,10 +1483,13 @@ impl> Parser { binding, ty: lookup_type.handle, }; - self.lookup_variable.insert(id, LookupVariable { - handle: module.global_variables.append(var), - type_id, - }); + self.lookup_variable.insert( + id, + LookupVariable { + handle: module.global_variables.append(var), + type_id, + }, + ); Ok(()) } @@ -1418,12 +1507,10 @@ impl> Parser { let mut fun = { let ft = self.lookup_function_type.lookup(fun_type)?; if ft.return_type_id != result_type { - return Err(Error::WrongFunctionResultType(result_type)) + return Err(Error::WrongFunctionResultType(result_type)); } crate::Function { - name: self.future_decor - .remove(&fun_id) - .and_then(|dec| dec.name), + name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name), control: spirv::FunctionControl::from_bits(fun_control) .ok_or(Error::UnsupportedFunctionControl(fun_control))?, parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), @@ -1441,15 +1528,20 @@ impl> Parser { // read parameters for i in 0..fun.parameter_types.capacity() { match self.next_inst()? { - Instruction { op: spirv::Op::FunctionParameter, wc: 3 } => { + Instruction { + op: spirv::Op::FunctionParameter, + wc: 3, + } => { let type_id = self.next()?; let _id = self.next()?; //Note: we redo the lookup in order to work around `self` borrowing - if type_id != self.lookup_function_type - .lookup(fun_type)? - .parameter_type_ids[i] + if type_id + != self + .lookup_function_type + .lookup(fun_type)? + .parameter_type_ids[i] { - return Err(Error::WrongFunctionParameterType(type_id)) + return Err(Error::WrongFunctionParameterType(type_id)); } let ty = self.lookup_type.lookup(type_id)?.handle; fun.parameter_types.push(ty); @@ -1469,13 +1561,14 @@ impl> Parser { } spirv::Op::FunctionEnd => { fun_inst.expect(1)?; - break + break; } - _ => return Err(Error::UnsupportedInstruction(self.state, fun_inst.op)) + _ => return Err(Error::UnsupportedInstruction(self.state, fun_inst.op)), } } // done - fun.global_usage = crate::GlobalUse::scan(&fun.expressions, &fun.body, &module.global_variables); + fun.global_usage = + crate::GlobalUse::scan(&fun.expressions, &fun.body, &module.global_variables); let handle = module.functions.append(fun); self.lookup_function.insert(fun_id, handle); self.lookup_expression.clear(); @@ -1501,14 +1594,11 @@ mod test { fn parse() { let bin = vec![ // Magic number. Version number: 1.0. - 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, + 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, // Generator number: 0. Bound: 0. - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Reserved word: 0. - 0x00, 0x00, 0x00, 0x00, - // OpMemoryModel. Logical. - 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, - // GLSL450. + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved word: 0. + 0x00, 0x00, 0x00, 0x00, // OpMemoryModel. Logical. + 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, // GLSL450. 0x01, 0x00, 0x00, 0x00, ]; let _ = super::parse_u8_slice(&bin).unwrap(); diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 2059a79af..5e34032ff 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,10 +1,9 @@ use crate::{ arena::{Arena, Handle}, - proc::{Typifier, ResolveError}, + proc::{ResolveError, Typifier}, FastHashMap, }; - #[derive(Debug, PartialEq)] pub enum Token<'a> { Separator(char), @@ -29,7 +28,7 @@ mod lex { fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { if input.starts_with(what) { - Some(&input[what.len() ..]) + Some(&input[what.len()..]) } else { None } @@ -56,12 +55,8 @@ mod lex { (Token::Separator(cur), input) } } - ';' | ',' | '.' => { - (Token::Separator(cur), chars.as_str()) - } - '(' | ')' | '{' | '}' => { - (Token::Paren(cur), chars.as_str()) - } + ';' | ',' | '.' => (Token::Separator(cur), chars.as_str()), + '(' | ')' | '{' | '}' => (Token::Paren(cur), chars.as_str()), '<' | '>' => { input = chars.as_str(); let next = chars.next(); @@ -86,19 +81,19 @@ mod lex { (Token::Paren(cur), input) } } - '0' ..= '9' => { - let (number, rest) = consume_any(input, |c| (c>='0' && c<='9' || c=='.')); + '0'..='9' => { + let (number, rest) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); (Token::Number(number), rest) } 'a'..='z' | 'A'..='Z' | '_' => { - let (word, rest) = consume_any(input, |c| c.is_alphanumeric() || c=='_'); + let (word, rest) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); (Token::Word(word), rest) } '"' => { let base = chars.as_str(); let len = match chars.position(|c| c == '"') { Some(pos) => pos, - None => return (Token::UnterminatedString, chars.as_str()) + None => return (Token::UnterminatedString, chars.as_str()), }; (Token::String(&base[..len]), chars.as_str()) } @@ -110,9 +105,7 @@ mod lex { (Token::Operation(cur), input) } } - '+' | '*' | '/' | '%' | '^' => { - (Token::Operation(cur), chars.as_str()) - } + '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), '!' => { if chars.next() == Some('=') { (Token::LogicalOperation(cur), chars.as_str()) @@ -120,7 +113,7 @@ mod lex { (Token::Operation(cur), input) } } - '=' | '&' | '|' => { + '=' | '&' | '|' => { input = chars.as_str(); if chars.next() == Some(cur) { (Token::LogicalOperation(cur), chars.as_str()) @@ -128,13 +121,11 @@ mod lex { (Token::Operation(cur), input) } } - '#' => { - match chars.position(|c| c == '\n' || c == '\r') { - Some(_) => consume_token(chars.as_str()), - None => (Token::End, chars.as_str()) - } - } - _ => (Token::Unknown(cur), chars.as_str()) + '#' => match chars.position(|c| c == '\n' || c == '\r') { + Some(_) => consume_token(chars.as_str()), + None => (Token::End, chars.as_str()), + }, + _ => (Token::Unknown(cur), chars.as_str()), } } } @@ -254,9 +245,7 @@ trait StringValueLookup<'a> { impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle> { type Value = Handle; fn lookup(&self, key: &'a str) -> Result> { - self.get(key) - .cloned() - .ok_or(Error::UnknownIdent(key)) + self.get(key).cloned().ok_or(Error::UnknownIdent(key)) } } @@ -319,9 +308,21 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } - fn resolve_type(&mut self, handle: Handle) -> Result, Error<'a>> { + fn resolve_type( + &mut self, + handle: Handle, + ) -> Result, Error<'a>> { self.typifier - .resolve(handle, self.expressions, self.types, self.constants, self.global_vars, self.local_vars,&Arena::new(),&FastHashMap::default()) + .resolve( + handle, + self.expressions, + self.types, + self.constants, + self.global_vars, + self.local_vars, + &Arena::new(), + &FastHashMap::default(), + ) .map_err(Error::InvalidResolve) } @@ -329,7 +330,10 @@ impl<'a> ExpressionContext<'a, '_, '_> { &mut self, lexer: &mut Lexer<'a>, classifier: impl Fn(Token<'a>) -> Option, - mut parser: impl FnMut(&mut Lexer<'a>, ExpressionContext<'a, '_, '_>) -> Result, Error<'a>>, + mut parser: impl FnMut( + &mut Lexer<'a>, + ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>>, ) -> Result, Error<'a>> { let mut left = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek()) { @@ -345,7 +349,6 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } - #[derive(Clone, Debug, PartialEq)] pub enum Scope { Decoration, @@ -411,16 +414,16 @@ impl Parser { } } - fn get_constant_inner(word: &str) -> Result<(crate::ConstantInner, crate::ScalarKind), Error<'_>> { + fn get_constant_inner( + word: &str, + ) -> Result<(crate::ConstantInner, crate::ScalarKind), Error<'_>> { if word.contains('.') { - word - .parse() - .map(|f|(crate::ConstantInner::Float(f), crate::ScalarKind::Float)) + word.parse() + .map(|f| (crate::ConstantInner::Float(f), crate::ScalarKind::Float)) .map_err(|err| Error::BadFloat(word, err)) } else { - word - .parse() - .map(|i|(crate::ConstantInner::Sint(i), crate::ScalarKind::Sint)) + word.parse() + .map(|i| (crate::ConstantInner::Sint(i), crate::ScalarKind::Sint)) .map_err(|err| Error::BadInteger(word, err)) } } @@ -484,7 +487,7 @@ impl Parser { width: 1, }, ctx.types, - ) + ), }); crate::Expression::Constant(handle) } @@ -499,7 +502,7 @@ impl Parser { width: 1, }, ctx.types, - ) + ), }); crate::Expression::Constant(handle) } @@ -512,7 +515,7 @@ impl Parser { ty: Typifier::deduce_type_handle( crate::TypeInner::Scalar { kind, width: 32 }, ctx.types, - ) + ), }); crate::Expression::Constant(handle) } @@ -576,24 +579,31 @@ impl Parser { let index = members .iter() .position(|m| m.name.as_deref() == Some(name)) - .ok_or(Error::BadAccessor(name))? as u32; + .ok_or(Error::BadAccessor(name))? + as u32; crate::Expression::AccessIndex { base: handle, index, } } - crate::TypeInner::Vector { size, kind, width } | - crate::TypeInner::Matrix { columns: size, kind, width, .. } => { + crate::TypeInner::Vector { size, kind, width } + | crate::TypeInner::Matrix { + columns: size, + kind, + width, + .. + } => { const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; if name.len() > 1 { let mut components = Vec::with_capacity(name.len()); for ch in name.chars() { let expr = crate::Expression::AccessIndex { base: handle, - index: MEMBERS[.. size as usize] + index: MEMBERS[..size as usize] .iter() .position(|&m| m == ch) - .ok_or(Error::BadAccessor(name))? as u32, + .ok_or(Error::BadAccessor(name))? + as u32, }; components.push(ctx.expressions.append(expr)); } @@ -603,8 +613,15 @@ impl Parser { 4 => crate::VectorSize::Quad, _ => return Err(Error::BadAccessor(name)), }; - let inner = if let crate::TypeInner::Matrix { rows, .. } = base_type.inner { - crate::TypeInner::Matrix { columns: size, rows, kind, width } + let inner = if let crate::TypeInner::Matrix { rows, .. } = + base_type.inner + { + crate::TypeInner::Matrix { + columns: size, + rows, + kind, + width, + } } else { crate::TypeInner::Vector { size, kind, width } }; @@ -614,10 +631,11 @@ impl Parser { } } else { let ch = name.chars().next().unwrap(); - let index = MEMBERS[.. size as usize] + let index = MEMBERS[..size as usize] .iter() .position(|&m| m == ch) - .ok_or(Error::BadAccessor(name))? as u32; + .ok_or(Error::BadAccessor(name))? + as u32; crate::Expression::AccessIndex { base: handle, index, @@ -670,35 +688,25 @@ impl Parser { self.scopes.push(Scope::SingularExpr); let backup = lexer.clone(); let expression = match lexer.next() { - Token::Operation('-') => { - Some(crate::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr: self.parse_singular_expression(lexer, ctx.reborrow())?, - }) - } - Token::Operation('!') => { - Some(crate::Expression::Unary { - op: crate::UnaryOperator::Not, - expr: self.parse_singular_expression(lexer, ctx.reborrow())?, - }) - } + Token::Operation('-') => Some(crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr: self.parse_singular_expression(lexer, ctx.reborrow())?, + }), + Token::Operation('!') => Some(crate::Expression::Unary { + op: crate::UnaryOperator::Not, + expr: self.parse_singular_expression(lexer, ctx.reborrow())?, + }), Token::Word(word) => { if let Some(fun) = get_intrinsic(word) { lexer.expect(Token::Paren('('))?; let argument = self.parse_primary_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Intrinsic { - fun, - argument, - }) + Some(crate::Expression::Intrinsic { fun, argument }) } else if let Some(axis) = get_derivative(word) { lexer.expect(Token::Paren('('))?; let expr = self.parse_primary_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Derivative { - axis, - expr, - }) + Some(crate::Expression::Derivative { axis, expr }) } else if word == "dot" { lexer.expect(Token::Paren('('))?; let a = self.parse_primary_expression(lexer, ctx.reborrow())?; @@ -743,49 +751,73 @@ impl Parser { |token| match token { Token::LogicalOperation('=') => Some(crate::BinaryOperator::Equal), Token::LogicalOperation('!') => Some(crate::BinaryOperator::NotEqual), - _ => None + _ => None, }, // relational_expression - |lexer, mut context| context.parse_binary_op( - lexer, - |token| match token { - Token::Paren('<') => Some(crate::BinaryOperator::Less), - Token::Paren('>') => Some(crate::BinaryOperator::Greater), - Token::LogicalOperation('<') => Some(crate::BinaryOperator::LessEqual), - Token::LogicalOperation('>') => Some(crate::BinaryOperator::GreaterEqual), - _ => None, - }, - // shift_expression - |lexer, mut context| context.parse_binary_op( + |lexer, mut context| { + context.parse_binary_op( lexer, |token| match token { - Token::ShiftOperation('<') => Some(crate::BinaryOperator::ShiftLeftLogical), - Token::ShiftOperation('>') => Some(crate::BinaryOperator::ShiftRightLogical), - Token::ArithmeticShiftOperation('>') => Some(crate::BinaryOperator::ShiftRightArithmetic), + Token::Paren('<') => Some(crate::BinaryOperator::Less), + Token::Paren('>') => Some(crate::BinaryOperator::Greater), + Token::LogicalOperation('<') => Some(crate::BinaryOperator::LessEqual), + Token::LogicalOperation('>') => Some(crate::BinaryOperator::GreaterEqual), _ => None, }, - // additive_expression - |lexer, mut context| context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('+') => Some(crate::BinaryOperator::Add), - Token::Operation('-') => Some(crate::BinaryOperator::Subtract), - _ => None, - }, - // multiplicative_expression - |lexer, mut context| context.parse_binary_op( + // shift_expression + |lexer, mut context| { + context.parse_binary_op( lexer, |token| match token { - Token::Operation('*') => Some(crate::BinaryOperator::Multiply), - Token::Operation('/') => Some(crate::BinaryOperator::Divide), - Token::Operation('%') => Some(crate::BinaryOperator::Modulo), + Token::ShiftOperation('<') => { + Some(crate::BinaryOperator::ShiftLeftLogical) + } + Token::ShiftOperation('>') => { + Some(crate::BinaryOperator::ShiftRightLogical) + } + Token::ArithmeticShiftOperation('>') => { + Some(crate::BinaryOperator::ShiftRightArithmetic) + } _ => None, }, - |lexer, context| self.parse_singular_expression(lexer, context), - ), - ), - ), - ), + // additive_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('+') => Some(crate::BinaryOperator::Add), + Token::Operation('-') => { + Some(crate::BinaryOperator::Subtract) + } + _ => None, + }, + // multiplicative_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('*') => { + Some(crate::BinaryOperator::Multiply) + } + Token::Operation('/') => { + Some(crate::BinaryOperator::Divide) + } + Token::Operation('%') => { + Some(crate::BinaryOperator::Modulo) + } + _ => None, + }, + |lexer, context| { + self.parse_singular_expression(lexer, context) + }, + ) + }, + ) + }, + ) + }, + ) + }, ) } @@ -803,38 +835,52 @@ impl Parser { _ => None, }, // logical_and_expression - |lexer, mut context| context.parse_binary_op( - lexer, - |token| match token { - Token::LogicalOperation('&') => Some(crate::BinaryOperator::LogicalAnd), - _ => None, - }, - // inclusive_or_expression - |lexer, mut context| context.parse_binary_op( + |lexer, mut context| { + context.parse_binary_op( lexer, |token| match token { - Token::Operation('|') => Some(crate::BinaryOperator::InclusiveOr), + Token::LogicalOperation('&') => Some(crate::BinaryOperator::LogicalAnd), _ => None, }, - // exclusive_or_expression - |lexer, mut context| context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('^') => Some(crate::BinaryOperator::ExclusiveOr), - _ => None, - }, - // and_expression - |lexer, mut context| context.parse_binary_op( + // inclusive_or_expression + |lexer, mut context| { + context.parse_binary_op( lexer, |token| match token { - Token::Operation('&') => Some(crate::BinaryOperator::And), + Token::Operation('|') => Some(crate::BinaryOperator::InclusiveOr), _ => None, }, - |lexer, context| self.parse_equality_expression(lexer, context), - ), - ), - ), - ), + // exclusive_or_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('^') => { + Some(crate::BinaryOperator::ExclusiveOr) + } + _ => None, + }, + // and_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('&') => { + Some(crate::BinaryOperator::And) + } + _ => None, + }, + |lexer, context| { + self.parse_equality_expression(lexer, context) + }, + ) + }, + ) + }, + ) + }, + ) + }, )?; self.scopes.pop(); Ok(handle) @@ -927,24 +973,18 @@ impl Parser { ) -> Result, Error<'a>> { self.scopes.push(Scope::TypeDecl); let inner = match lexer.next() { - Token::Word("f32") => { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: 32, - } - } - Token::Word("i32") => { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Sint, - width: 32, - } - } - Token::Word("u32") => { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: 32, - } - } + Token::Word("f32") => crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: 32, + }, + Token::Word("i32") => crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: 32, + }, + Token::Word("u32") => crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: 32, + }, Token::Word("vec2") => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { @@ -1024,7 +1064,8 @@ impl Parser { } Token::Word(name) => { self.scopes.pop(); - return self.lookup_type + return self + .lookup_type .get(name) .cloned() .ok_or(Error::UnknownType(name)); @@ -1054,7 +1095,8 @@ impl Parser { } let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; let init = if lexer.skip(Token::Operation('=')) { - let value = self.parse_general_expression(lexer, context.as_expression())?; + let value = + self.parse_general_expression(lexer, context.as_expression())?; if let crate::Expression::Constant(_) = context.expressions[value] { Init::Uniform(value) } else { @@ -1070,12 +1112,17 @@ impl Parser { init: match init { Init::Uniform(value) => Some(value), _ => None, - } + }, }); - let expr_id = context.expressions.append(crate::Expression::LocalVariable(var_id)); + let expr_id = context + .expressions + .append(crate::Expression::LocalVariable(var_id)); context.lookup_ident.insert(name, expr_id); match init { - Init::Variable(value) => crate::Statement::Store { pointer: expr_id, value }, + Init::Variable(value) => crate::Statement::Store { + pointer: expr_id, + value, + }, _ => crate::Statement::Empty, } } @@ -1086,13 +1133,12 @@ impl Parser { None }; lexer.expect(Token::Separator(';'))?; - crate::Statement::Return { - value - } + crate::Statement::Return { value } } "if" => { lexer.expect(Token::Paren('('))?; - let condition = self.parse_general_expression(lexer, context.as_expression())?; + let condition = + self.parse_general_expression(lexer, context.as_expression())?; lexer.expect(Token::Paren(')'))?; let accept = self.parse_block(lexer, context.reborrow())?; let reject = if lexer.skip(Token::Word("else")) { @@ -1121,10 +1167,7 @@ impl Parser { None => break, } } - crate::Statement::Loop { - body, - continuing - } + crate::Statement::Loop { body, continuing } } "break" => crate::Statement::Break, "continue" => crate::Statement::Continue, @@ -1133,7 +1176,8 @@ impl Parser { let var_expr = context.lookup_ident.lookup(ident)?; let left = self.parse_postfix(lexer, context.as_expression(), var_expr)?; lexer.expect(Token::Operation('='))?; - let value = self.parse_general_expression(lexer, context.as_expression())?; + let value = + self.parse_general_expression(lexer, context.as_expression())?; lexer.expect(Token::Separator(';'))?; crate::Statement::Store { pointer: left, @@ -1186,9 +1230,11 @@ impl Parser { if !parameter_types.is_empty() { lexer.expect(Token::Separator(','))?; } - let (param_name, param_type) = self.parse_variable_ident_decl(lexer, &mut module.types)?; + let (param_name, param_type) = + self.parse_variable_ident_decl(lexer, &mut module.types)?; let param_index = parameter_types.len() as u32; - let expression_token = expressions.append(crate::Expression::FunctionParameter(param_index)); + let expression_token = + expressions.append(crate::Expression::FunctionParameter(param_index)); lookup_ident.insert(param_name, expression_token); parameter_types.push(param_type); } @@ -1202,15 +1248,18 @@ impl Parser { // read body let mut local_variables = Arena::new(); let mut typifier = Typifier::new(); - let body = self.parse_block(lexer, StatementContext { - lookup_ident: &mut lookup_ident, - typifier: &mut typifier, - variables: &mut local_variables, - expressions: &mut expressions, - types: &mut module.types, - constants: &mut module.constants, - global_vars: &module.global_variables, - })?; + let body = self.parse_block( + lexer, + StatementContext { + lookup_ident: &mut lookup_ident, + typifier: &mut typifier, + variables: &mut local_variables, + expressions: &mut expressions, + types: &mut module.types, + constants: &mut module.constants, + global_vars: &module.global_variables, + }, + )?; // done let global_usage = crate::GlobalUse::scan(&expressions, &body, &module.global_variables); self.scopes.pop(); @@ -1261,14 +1310,16 @@ impl Parser { Token::DoubleParen(']') => { break; } - Token::Separator(',') => { - } + Token::Separator(',') => {} other => return Err(Error::Unexpected(other)), } } match (bind_set, bind_index) { (Some(set), Some(index)) if binding.is_none() => { - binding = Some(crate::Binding::Descriptor { set, binding: index }); + binding = Some(crate::Binding::Descriptor { + set, + binding: index, + }); } _ if binding.is_none() => return Err(Error::Other), _ => {} @@ -1277,7 +1328,7 @@ impl Parser { } // read items match lexer.next() { - Token::Separator(';') => {}, + Token::Separator(';') => {} Token::Word("import") => { self.scopes.push(Scope::ImportDecl); let path = match lexer.next() { @@ -1288,9 +1339,7 @@ impl Parser { let namespace = lexer.next_ident()?; lexer.expect(Token::Separator(';'))?; match path { - "GLSL.std.450" => { - self.std_namespace = Some(namespace.to_owned()) - } + "GLSL.std.450" => self.std_namespace = Some(namespace.to_owned()), _ => return Err(Error::UnknownImport(path)), } self.scopes.pop(); @@ -1305,7 +1354,8 @@ impl Parser { Token::Word("const") => { let (name, ty) = self.parse_variable_ident_decl(lexer, &mut module.types)?; lexer.expect(Token::Operation('='))?; - let inner = self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; + let inner = + self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; lexer.expect(Token::Separator(';'))?; crate::proc::check_constant_types(&inner, &module.types[ty].inner)?; let const_handle = module.constants.append(crate::Constant { @@ -1317,7 +1367,8 @@ impl Parser { lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); } Token::Word("var") => { - let (name, class, ty) = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; + let (name, class, ty) = + self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; let var_handle = module.global_variables.append(crate::GlobalVariable { name: Some(name.to_owned()), class: match class { @@ -1334,7 +1385,8 @@ impl Parser { binding: binding.take(), ty, }); - lookup_global_expression.insert(name, crate::Expression::GlobalVariable(var_handle)); + lookup_global_expression + .insert(name, crate::Expression::GlobalVariable(var_handle)); } Token::Word("fn") => { self.parse_function_decl(lexer, module, &lookup_global_expression)?; @@ -1344,7 +1396,7 @@ impl Parser { let export_name = if lexer.skip(Token::Word("as")) { match lexer.next() { Token::String(name) => Some(name), - other => return Err(Error::Unexpected(other)) + other => return Err(Error::Unexpected(other)), } } else { None @@ -1352,7 +1404,8 @@ impl Parser { lexer.expect(Token::Operation('='))?; let fun_ident = lexer.next_ident()?; lexer.expect(Token::Separator(';'))?; - let (fun_handle, _) = module.functions + let (fun_handle, _) = module + .functions .iter() .find(|(_, fun)| fun.name.as_deref() == Some(fun_ident)) .ok_or(Error::UnknownFunction(fun_ident))?; diff --git a/src/lib.rs b/src/lib.rs index c9359c001..67660c33e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -74,13 +74,37 @@ pub struct Type { // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug, PartialEq)] pub enum TypeInner { - Scalar { kind: ScalarKind, width: Bytes }, - Vector { size: VectorSize, kind: ScalarKind, width: Bytes }, - Matrix { columns: VectorSize, rows: VectorSize, kind: ScalarKind, width: Bytes }, - Pointer { base: Handle, class: spirv::StorageClass }, - Array { base: Handle, size: ArraySize }, - Struct { members: Vec }, - Image { base: Handle, dim: spirv::Dim, flags: ImageFlags }, + Scalar { + kind: ScalarKind, + width: Bytes, + }, + Vector { + size: VectorSize, + kind: ScalarKind, + width: Bytes, + }, + Matrix { + columns: VectorSize, + rows: VectorSize, + kind: ScalarKind, + width: Bytes, + }, + Pointer { + base: Handle, + class: spirv::StorageClass, + }, + Array { + base: Handle, + size: ArraySize, + }, + Struct { + members: Vec, + }, + Image { + base: Handle, + dim: spirv::Dim, + flags: ImageFlags, + }, Sampler, } @@ -106,7 +130,10 @@ pub enum ConstantInner { pub enum Binding { BuiltIn(spirv::BuiltIn), Location(spirv::Word), - Descriptor { set: spirv::Word, binding: spirv::Word }, + Descriptor { + set: spirv::Word, + binding: spirv::Word, + }, } bitflags::bitflags! { diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 9522ac981..e44106409 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -1,6 +1,4 @@ -use crate::{ - arena::{Arena, Handle}, -}; +use crate::arena::{Arena, Handle}; struct Interface<'a> { expressions: &'a Arena, @@ -24,7 +22,7 @@ impl<'a> Interface<'a> { self.add_inputs(comp); } } - E::FunctionParameter(_) => {}, + E::FunctionParameter(_) => {} E::GlobalVariable(handle) => { self.uses[handle.index()] |= crate::GlobalUse::LOAD; } @@ -32,7 +30,11 @@ impl<'a> Interface<'a> { E::Load { pointer } => { self.add_inputs(pointer); } - E::ImageSample { image, sampler, coordinate } => { + E::ImageSample { + image, + sampler, + coordinate, + } => { self.add_inputs(image); self.add_inputs(sampler); self.add_inputs(coordinate); @@ -70,26 +72,34 @@ impl<'a> Interface<'a> { for statement in block { use crate::Statement as S; match *statement { - S::Empty | - S::Break | - S::Continue | - S::Kill => (), + S::Empty | S::Break | S::Continue | S::Kill => (), S::Block(ref b) => { self.collect(b); } - S::If { condition, ref accept, ref reject } => { + S::If { + condition, + ref accept, + ref reject, + } => { self.add_inputs(condition); self.collect(accept); self.collect(reject); } - S::Switch { selector, ref cases, ref default } => { + S::Switch { + selector, + ref cases, + ref default, + } => { self.add_inputs(selector); for &(ref case, _) in cases.values() { self.collect(case); } self.collect(default); } - S::Loop { ref body, ref continuing } => { + S::Loop { + ref body, + ref continuing, + } => { self.collect(body); self.collect(continuing); } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index dc2dd64b4..e4b181a69 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,4 +1,4 @@ mod interface; mod typifier; -pub use typifier::{ResolveError, Typifier, UnexpectedConstantTypeError, check_constant_types}; +pub use typifier::{check_constant_types, ResolveError, Typifier, UnexpectedConstantTypeError}; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index ed87c964a..314404674 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -207,29 +207,38 @@ pub struct UnexpectedConstantTypeError(crate::ConstantInner, crate::TypeInner); pub fn check_constant_types( inner: &crate::ConstantInner, - type_inner: &crate::TypeInner + type_inner: &crate::TypeInner, ) -> Result<(), UnexpectedConstantTypeError> { match (inner, type_inner) { ( crate::ConstantInner::Sint(_), - crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width: _ }, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + }, ) => Ok(()), ( crate::ConstantInner::Uint(_), - crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width: _ }, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + }, ) => Ok(()), ( crate::ConstantInner::Float(_), - crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: _ }, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: _, + }, ) => Ok(()), ( crate::ConstantInner::Bool(_), - crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: _ }, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: _, + }, ) => Ok(()), - ( - crate::ConstantInner::Composite(_inner), - _ - ) => Ok(()), // TODO recursively check composite types + (crate::ConstantInner::Composite(_inner), _) => Ok(()), // TODO recursively check composite types (other_inner, other_type_inner) => Err(UnexpectedConstantTypeError( other_inner.clone(), other_type_inner.clone(), diff --git a/tests/convert.rs b/tests/convert.rs index 4150ed824..85bb15d7a 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -12,11 +12,21 @@ fn convert_quad() { let mut binding_map = msl::BindingMap::default(); binding_map.insert( msl::BindSource { set: 0, binding: 0 }, - msl::BindTarget { buffer: None, texture: Some(1), sampler: None, mutable: false }, + msl::BindTarget { + buffer: None, + texture: Some(1), + sampler: None, + mutable: false, + }, ); binding_map.insert( msl::BindSource { set: 0, binding: 1 }, - msl::BindTarget { buffer: None, texture: None, sampler: Some(1), mutable: false }, + msl::BindTarget { + buffer: None, + texture: None, + sampler: Some(1), + mutable: false, + }, ); let options = msl::Options { binding_map: &binding_map, @@ -33,15 +43,30 @@ fn convert_boids() { let mut binding_map = msl::BindingMap::default(); binding_map.insert( msl::BindSource { set: 0, binding: 0 }, - msl::BindTarget { buffer: Some(0), texture: None, sampler: None, mutable: false }, + msl::BindTarget { + buffer: Some(0), + texture: None, + sampler: None, + mutable: false, + }, ); binding_map.insert( msl::BindSource { set: 0, binding: 1 }, - msl::BindTarget { buffer: Some(1), texture: None, sampler: Some(1), mutable: false }, + msl::BindTarget { + buffer: Some(1), + texture: None, + sampler: Some(1), + mutable: false, + }, ); binding_map.insert( msl::BindSource { set: 0, binding: 2 }, - msl::BindTarget { buffer: Some(2), texture: None, sampler: Some(1), mutable: false }, + msl::BindTarget { + buffer: Some(2), + texture: None, + sampler: Some(1), + mutable: false, + }, ); let options = msl::Options { binding_map: &binding_map, From f9fa281da5ebb030cdf891b10fc006471187a082 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sat, 13 Jun 2020 19:05:30 +0200 Subject: [PATCH 0077/2212] Update integers to float32 (#64) --- test-data/boids.wgsl | 8 ++++---- test-data/quad.wgsl | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl index c7dc9a29a..a7c13dd63 100644 --- a/test-data/boids.wgsl +++ b/test-data/boids.wgsl @@ -26,7 +26,7 @@ fn vtx_main() -> void { var pos : vec2 = vec2( (a_pos.x * std::cos(angle)) - (a_pos.y * std::sin(angle)), (a_pos.x * std::sin(angle)) + (a_pos.y * std::cos(angle))); - gl_Position = vec4(pos + a_particlePos, 0, 1); + gl_Position = vec4(pos + a_particlePos, 0.0, 1.0); return; } entry_point vertex as "main" = vtx_main; @@ -76,9 +76,9 @@ fn compute_main() -> void { var vPos : vec2 = particlesA.particles[index].pos; var vVel : vec2 = particlesA.particles[index].vel; - var cMass : vec2 = vec2(0, 0); - var cVel : vec2 = vec2(0, 0); - var colVel : vec2 = vec2(0, 0); + var cMass : vec2 = vec2(0.0, 0.0); + var cVel : vec2 = vec2(0.0, 0.0); + var colVel : vec2 = vec2(0.0, 0.0); var cMassCount : i32 = 0; var cVelCount : i32 = 0; diff --git a/test-data/quad.wgsl b/test-data/quad.wgsl index 2666ea1e7..0e2dc08da 100644 --- a/test-data/quad.wgsl +++ b/test-data/quad.wgsl @@ -18,7 +18,7 @@ entry_point vertex as "main" = main_vert; [[location 0]] var o_color : vec4; fn main_frag() -> void { - o_color = vec4(1, 0, 0, 1); #TODO: sample + o_color = vec4(1.0, 0.0, 0.0, 1.0); #TODO: sample return; } entry_point fragment as "main" = main_frag; From 82573b288bd17430042d8f701b94bf56d1969f2a Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Mon, 15 Jun 2020 22:01:00 +0200 Subject: [PATCH 0078/2212] Implement basic SPIR-V back-end (#46) --- .gitignore | 1 + README.md | 2 +- examples/convert.rs | 23 +- src/arena.rs | 2 +- src/back/mod.rs | 1 + src/back/spv/layout.rs | 85 +++ src/back/spv/mod.rs | 42 ++ src/back/spv/writer.rs | 1013 ++++++++++++++++++++++++++++++++ src/front/mod.rs | 2 +- src/front/{spirv.rs => spv.rs} | 2 +- 10 files changed, 1168 insertions(+), 5 deletions(-) create mode 100644 src/back/spv/layout.rs create mode 100644 src/back/spv/mod.rs create mode 100644 src/back/spv/writer.rs rename src/front/{spirv.rs => spv.rs} (99%) diff --git a/.gitignore b/.gitignore index fe42cc56d..743f7ed7c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ **/*.rs.bk Cargo.lock .DS_Store +.idea diff --git a/README.md b/README.md index cd547c5d8..a2a88688d 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Rust | | | Back-end | Status | Notes | --------------- | ------------------ | ----- | -SPIR-V (binary) | | | +SPIR-V (binary) | :construction: | | WGSL | | | Metal | :construction: | | HLSL | | | diff --git a/examples/convert.rs b/examples/convert.rs index ba6e6a4a1..b41e0127b 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -30,7 +30,7 @@ fn main() { return; } else if args[1].ends_with(".spv") { let input = fs::read(&args[1]).unwrap(); - naga::front::spirv::parse_u8_slice(&input).unwrap() + naga::front::spv::parse_u8_slice(&input).unwrap() } else if args[1].ends_with(".wgsl") { let input = fs::read_to_string(&args[1]).unwrap(); naga::front::wgsl::parse_str(&input).unwrap() @@ -71,6 +71,27 @@ fn main() { }; let msl = msl::write_string(&module, options).unwrap(); fs::write(&args[2], msl).unwrap(); + } else if args[2].ends_with(".spv") { + use naga::back::spv; + + let debug_flag = args.get(3).map_or(spv::WriterFlags::DEBUG, |arg| { + if arg.parse().unwrap() { + spv::WriterFlags::DEBUG + } else { + spv::WriterFlags::NONE + } + }); + + let spv = spv::writer::Writer::new(&module.header, debug_flag).write(&module); + + let bytes = spv + .iter() + .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { + v.extend_from_slice(&w.to_le_bytes()); + v + }); + + fs::write(&args[2], bytes.as_slice()).unwrap(); } else { panic!("Unknown output: {:?}", args[2]); } diff --git a/src/arena.rs b/src/arena.rs index c790ec553..d6d8dc511 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -2,7 +2,7 @@ use std::{fmt, hash, marker::PhantomData, num::NonZeroU32}; /// An unique index in the arena array that a handle points to. /// -/// This type is independent of `spirv::Word`. `spirv::Word` is used in data +/// This type is independent of `spv::Word`. `spv::Word` is used in data /// representation. It holds a SPIR-V and refers to that instruction. In /// structured representation, we use Handle to refer to an SPIR-V instruction. /// `Index` is an implementation detail to `Handle`. diff --git a/src/back/mod.rs b/src/back/mod.rs index 4a194befe..e2b4919f6 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -1 +1,2 @@ pub mod msl; +pub mod spv; diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs new file mode 100644 index 000000000..40e3e47e9 --- /dev/null +++ b/src/back/spv/layout.rs @@ -0,0 +1,85 @@ +use crate::back::spv::{Instruction, LogicalLayout, PhysicalLayout}; +use spirv::*; +use std::iter; + +impl PhysicalLayout { + pub(crate) fn new(header: &crate::Header) -> Self { + let version: Word = ((header.version.0 as u32) << 16) + | ((header.version.1 as u32) << 8) + | header.version.2 as u32; + + PhysicalLayout { + magic_number: MAGIC_NUMBER, + version, + generator: header.generator, + bound: 0, + instruction_schema: 0x0u32, + } + } + + pub(crate) fn in_words(&self, sink: &mut impl Extend) { + sink.extend(iter::once(self.magic_number)); + sink.extend(iter::once(self.version)); + sink.extend(iter::once(self.generator)); + sink.extend(iter::once(self.bound)); + sink.extend(iter::once(self.instruction_schema)); + } +} + +impl LogicalLayout { + pub(crate) fn in_words(&self, sink: &mut impl Extend) { + sink.extend(self.capabilities.iter().cloned()); + sink.extend(self.extensions.iter().cloned()); + sink.extend(self.ext_inst_imports.iter().cloned()); + sink.extend(self.memory_model.iter().cloned()); + sink.extend(self.entry_points.iter().cloned()); + sink.extend(self.execution_modes.iter().cloned()); + sink.extend(self.debugs.iter().cloned()); + sink.extend(self.annotations.iter().cloned()); + sink.extend(self.declarations.iter().cloned()); + sink.extend(self.function_declarations.iter().cloned()); + sink.extend(self.function_definitions.iter().cloned()); + } +} + +impl Instruction { + pub(crate) fn new(op: Op) -> Self { + Instruction { + op, + wc: 1, // Always start at 1 for the first word (OP + WC), + type_id: None, + result_id: None, + operands: vec![], + } + } + + pub(crate) fn set_type(&mut self, id: Word) { + assert!(self.type_id.is_none(), "Type can only be set once"); + self.type_id = Some(id); + self.wc += 1; + } + + pub(crate) fn set_result(&mut self, id: Word) { + assert!(self.result_id.is_none(), "Result can only be set once"); + self.result_id = Some(id); + self.wc += 1; + } + + pub(crate) fn add_operand(&mut self, operand: Word) { + self.operands.push(operand); + self.wc += 1; + } + + pub(crate) fn add_operands(&mut self, operands: Vec) { + for operand in operands.into_iter() { + self.add_operand(operand) + } + } + + pub(crate) fn to_words(&self, sink: &mut impl Extend) { + sink.extend(Some((self.wc << 16 | self.op as u32) as u32)); + sink.extend(self.type_id); + sink.extend(self.result_id); + sink.extend(self.operands.iter().cloned()); + } +} diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs new file mode 100644 index 000000000..183f7c008 --- /dev/null +++ b/src/back/spv/mod.rs @@ -0,0 +1,42 @@ +mod layout; +pub mod writer; + +use spirv::*; + +bitflags::bitflags! { + pub struct WriterFlags: u32 { + const NONE = 0x0; + const DEBUG = 0x1; + } +} + +struct PhysicalLayout { + magic_number: Word, + version: Word, + generator: Word, + bound: Word, + instruction_schema: Word, +} + +#[derive(Default)] +pub(crate) struct LogicalLayout { + capabilities: Vec, + extensions: Vec, + ext_inst_imports: Vec, + memory_model: Vec, + entry_points: Vec, + execution_modes: Vec, + debugs: Vec, + annotations: Vec, + declarations: Vec, + function_declarations: Vec, + function_definitions: Vec, +} + +struct Instruction { + op: Op, + wc: u32, + type_id: Option, + result_id: Option, + operands: Vec, +} diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs new file mode 100644 index 000000000..d5a3b70ed --- /dev/null +++ b/src/back/spv/writer.rs @@ -0,0 +1,1013 @@ +/*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ +use crate::back::spv::{Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; +use crate::{FastHashMap, FastHashSet}; +use spirv::*; + +trait LookupHelper { + type Target; + fn lookup_id(&self, handle: crate::Handle) -> Option; + fn lookup_handle(&self, word: Word) -> Option>; +} + +impl LookupHelper for FastHashMap> { + type Target = T; + + fn lookup_id(&self, handle: crate::Handle) -> Option { + let mut word = None; + for (k, v) in self.iter() { + if *v == handle { + word = Some(*k); + break; + } + } + word + } + + fn lookup_handle(&self, word: u32) -> Option> { + let mut handle = None; + for (k, v) in self.iter() { + if *k == word { + handle = Some(*v); + break; + } + } + handle + } +} + +#[derive(Debug, PartialEq)] +struct LookupFunctionType { + parameter_type_ids: Vec, + return_type_id: Word, +} + +pub struct Writer { + physical_layout: PhysicalLayout, + logical_layout: LogicalLayout, + id_count: u32, + capabilities: FastHashSet, + debugs: Vec, + annotations: Vec, + writer_flags: WriterFlags, + void_type: Option, + lookup_type: FastHashMap>, + lookup_function: FastHashMap>, + lookup_function_type: FastHashMap, + lookup_constant: FastHashMap>, + lookup_global_variable: FastHashMap>, +} + +impl Writer { + pub fn new(header: &crate::Header, writer_flags: WriterFlags) -> Self { + Writer { + physical_layout: PhysicalLayout::new(header), + logical_layout: LogicalLayout::default(), + id_count: 0, + capabilities: FastHashSet::default(), + debugs: vec![], + annotations: vec![], + writer_flags, + void_type: None, + lookup_type: FastHashMap::default(), + lookup_function: FastHashMap::default(), + lookup_function_type: FastHashMap::default(), + lookup_constant: FastHashMap::default(), + lookup_global_variable: FastHashMap::default(), + } + } + + fn generate_id(&mut self) -> Word { + self.id_count += 1; + self.id_count + } + + fn bytes_to_words(&self, bytes: &[u8]) -> Vec { + bytes + .chunks(4) + .map(|chars| chars.iter().rev().fold(0u32, |u, c| (u << 8) | *c as u32)) + .collect() + } + + fn string_to_words(&self, input: &str) -> Vec { + let bytes = input.as_bytes(); + let mut words = self.bytes_to_words(bytes); + + if bytes.len() % 4 == 0 { + // nul-termination + words.push(0x0u32); + } + + words + } + + fn try_add_capabilities(&mut self, capabilities: &[Capability]) { + for capability in capabilities.iter() { + self.capabilities.insert(*capability); + } + } + + fn instruction_capability(&self, capability: Capability) -> Instruction { + let mut instruction = Instruction::new(Op::Capability); + instruction.add_operand(capability as u32); + instruction + } + + fn instruction_ext_inst_import(&mut self, name: &str) -> Instruction { + let mut instruction = Instruction::new(Op::ExtInstImport); + let id = self.generate_id(); + instruction.set_result(id); + instruction.add_operands(self.string_to_words(name)); + instruction + } + + fn instruction_memory_model(&mut self) -> Instruction { + let mut instruction = Instruction::new(Op::MemoryModel); + let addressing_model = AddressingModel::Logical; + let memory_model = MemoryModel::GLSL450; + self.try_add_capabilities(addressing_model.required_capabilities()); + self.try_add_capabilities(memory_model.required_capabilities()); + + instruction.add_operand(addressing_model as u32); + instruction.add_operand(memory_model as u32); + instruction + } + + fn instruction_entry_point( + &mut self, + entry_point: &crate::EntryPoint, + ir_module: &crate::Module, + ) -> Instruction { + let mut instruction = Instruction::new(Op::EntryPoint); + let function_id = self + .lookup_function + .lookup_id(entry_point.function) + .unwrap(); + + instruction.add_operand(entry_point.exec_model as u32); + instruction.add_operand(function_id); + + if self.writer_flags.contains(WriterFlags::DEBUG) { + let mut debug_instruction = Instruction::new(Op::Name); + debug_instruction.set_result(function_id); + debug_instruction.add_operands(self.string_to_words(entry_point.name.as_str())); + self.debugs.push(debug_instruction); + } + + instruction.add_operands(self.string_to_words(entry_point.name.as_str())); + + let function = &ir_module.functions[entry_point.function]; + for ((handle, _), &usage) in ir_module + .global_variables + .iter() + .zip(&function.global_usage) + { + if usage.contains(crate::GlobalUse::STORE) || usage.contains(crate::GlobalUse::LOAD) { + let id = self.get_global_variable_id( + &ir_module.types, + &ir_module.global_variables, + handle, + ); + instruction.add_operand(id); + } + } + + self.try_add_capabilities(entry_point.exec_model.required_capabilities()); + match entry_point.exec_model { + ExecutionModel::Vertex => {} + ExecutionModel::Fragment => { + let execution_mode = ExecutionMode::OriginUpperLeft; + self.try_add_capabilities(execution_mode.required_capabilities()); + + let mut execution_mode_instruction = Instruction::new(Op::ExecutionMode); + execution_mode_instruction.add_operand(function_id); + execution_mode_instruction.add_operand(execution_mode as u32); + execution_mode_instruction.to_words(&mut self.logical_layout.execution_modes); + } + _ => unimplemented!(), + } + + instruction + } + + fn get_type_id( + &mut self, + arena: &crate::Arena, + handle: crate::Handle, + ) -> Word { + match self.lookup_type.lookup_id(handle) { + Some(word) => word, + None => { + let (instruction, id) = self.instruction_type_declaration(arena, handle); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + } + } + + fn get_constant_id( + &mut self, + handle: crate::Handle, + ir_module: &crate::Module, + ) -> Word { + match self.lookup_constant.lookup_id(handle) { + Some(word) => word, + None => { + let (instruction, id) = self.instruction_constant_type(handle, ir_module); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + } + } + + fn get_global_variable_id( + &mut self, + arena: &crate::Arena, + global_arena: &crate::Arena, + handle: crate::Handle, + ) -> Word { + match self.lookup_global_variable.lookup_id(handle) { + Some(word) => word, + None => { + let global_variable = &global_arena[handle]; + let (instruction, id) = + self.instruction_global_variable(arena, global_variable, handle); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + } + } + + fn get_function_type( + &mut self, + ty: Option>, + arena: &crate::Arena, + ) -> Word { + match ty { + Some(handle) => self.get_type_id(arena, handle), + None => match self.void_type { + Some(id) => id, + None => { + let id = self.generate_id(); + + let mut instruction = Instruction::new(Op::TypeVoid); + instruction.set_result(id); + + self.void_type = Some(id); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + }, + } + } + + fn find_scalar_handle( + &self, + arena: &crate::Arena, + kind: crate::ScalarKind, + width: u8, + ) -> crate::Handle { + let mut scalar_handle = None; + for (handle, ty) in arena.iter() { + match ty.inner { + crate::TypeInner::Scalar { + kind: _kind, + width: _width, + } => { + if kind == _kind && width == _width { + scalar_handle = Some(handle); + break; + } + } + _ => continue, + } + } + scalar_handle.unwrap() + } + + fn instruction_type_declaration( + &mut self, + arena: &crate::Arena, + handle: crate::Handle, + ) -> (Instruction, Word) { + let ty = &arena[handle]; + let id = self.generate_id(); + let mut instruction; + + match ty.inner { + crate::TypeInner::Scalar { kind, width } => { + match kind { + crate::ScalarKind::Sint => { + instruction = Instruction::new(Op::TypeInt); + instruction.set_result(id); + instruction.add_operand(width as u32); + instruction.add_operand(0x1u32); + } + crate::ScalarKind::Uint => { + instruction = Instruction::new(Op::TypeInt); + instruction.set_result(id); + instruction.add_operand(width as u32); + instruction.add_operand(0x0u32); + } + crate::ScalarKind::Float => { + instruction = Instruction::new(Op::TypeFloat); + instruction.set_result(id); + instruction.add_operand(width as u32); + } + crate::ScalarKind::Bool => { + instruction = Instruction::new(Op::TypeBool); + instruction.set_result(id); + } + } + self.lookup_type.insert(id, handle); + } + crate::TypeInner::Vector { size, kind, width } => { + let scalar_handle = self.find_scalar_handle(arena, kind, width); + let scalar_id = self.get_type_id(arena, scalar_handle); + + instruction = Instruction::new(Op::TypeVector); + instruction.set_result(id); + instruction.add_operand(scalar_id); + instruction.add_operand(size as u32); + + self.lookup_type.insert(id, handle); + } + crate::TypeInner::Matrix { + columns, + rows: _, + kind, + width, + } => { + let scalar_handle = self.find_scalar_handle(arena, kind, width); + let scalar_id = self.get_type_id(arena, scalar_handle); + + instruction = Instruction::new(Op::TypeMatrix); + instruction.set_result(id); + instruction.add_operand(scalar_id); + instruction.add_operand(columns as u32); + } + crate::TypeInner::Pointer { base, class } => { + let type_id = self.get_type_id(arena, base); + instruction = Instruction::new(Op::TypePointer); + instruction.set_result(id); + instruction.add_operand(class as u32); + instruction.add_operand(type_id); + + self.lookup_type.insert(id, handle); + } + crate::TypeInner::Array { base, size } => { + let type_id = self.get_type_id(arena, handle); + + instruction = Instruction::new(Op::TypeArray); + instruction.set_result(id); + instruction.add_operand(type_id); + + match size { + crate::ArraySize::Static(word) => { + instruction.add_operand(word); + } + _ => panic!("Array size {:?} unsupported", size), + } + + self.lookup_type.insert(id, base); + } + crate::TypeInner::Struct { ref members } => { + instruction = Instruction::new(Op::TypeStruct); + instruction.set_result(id); + + for member in members { + let type_id = self.get_type_id(arena, member.ty); + instruction.add_operand(type_id); + } + + self.lookup_type.insert(id, handle); + } + crate::TypeInner::Image { base, dim, flags } => { + let type_id = self.get_type_id(arena, base); + self.try_add_capabilities(dim.required_capabilities()); + + instruction = Instruction::new(Op::TypeImage); + instruction.set_result(id); + instruction.add_operand(type_id); + instruction.add_operand(dim as u32); + + // TODO Add Depth, but how to determine? Not yet in the WGSL spec + instruction.add_operand(1); + + instruction.add_operand(if flags.contains(crate::ImageFlags::ARRAYED) { + 1 + } else { + 0 + }); + + instruction.add_operand(if flags.contains(crate::ImageFlags::MULTISAMPLED) { + 1 + } else { + 0 + }); + + if let Dim::DimSubpassData = dim { + instruction.add_operand(2); + instruction.add_operand(ImageFormat::Unknown as u32); + } else { + instruction.add_operand(if flags.contains(crate::ImageFlags::SAMPLED) { + 1 + } else { + 0 + }); + + // TODO Defaults to Unknown, not yet in IR + instruction.add_operand(ImageFormat::Unknown as u32); + }; + + instruction.add_operand( + if flags.contains(crate::ImageFlags::CAN_STORE) + && flags.contains(crate::ImageFlags::CAN_LOAD) + { + 2 + } else if flags.contains(crate::ImageFlags::CAN_STORE) { + 1 + } else { + 0 + }, + ); + + self.lookup_type.insert(id, base); + } + crate::TypeInner::Sampler => { + instruction = Instruction::new(Op::TypeSampler); + instruction.set_result(id); + self.lookup_type.insert(id, handle); + } + } + + (instruction, id) + } + + fn instruction_constant_type( + &mut self, + handle: crate::Handle, + ir_module: &crate::Module, + ) -> (Instruction, Word) { + let id = self.generate_id(); + self.lookup_constant.insert(id, handle); + let constant = &ir_module.constants[handle]; + let arena = &ir_module.types; + + match constant.inner { + crate::ConstantInner::Sint(val) => { + let type_id = self.get_type_id(arena, constant.ty); + + let mut instruction = Instruction::new(Op::Constant); + instruction.set_type(type_id); + instruction.set_result(id); + + let ty = &ir_module.types[constant.ty]; + match ty.inner { + crate::TypeInner::Scalar { kind: _, width } => match width { + 32 => { + instruction.add_operand(val as u32); + } + 64 => { + let (low, high) = ((val >> 32) as u32, val as u32); + instruction.add_operand(low); + instruction.add_operand(high); + } + _ => unreachable!(), + }, + _ => unreachable!(), + } + + (instruction, id) + } + crate::ConstantInner::Uint(val) => { + let type_id = self.get_type_id(arena, constant.ty); + + let mut instruction = Instruction::new(Op::Constant); + instruction.set_type(type_id); + instruction.set_result(id); + + let ty = &ir_module.types[constant.ty]; + match ty.inner { + crate::TypeInner::Scalar { kind: _, width } => match width { + 32 => { + instruction.add_operand(val as u32); + } + 64 => { + let (low, high) = ((val >> 32) as u32, val as u32); + instruction.add_operand(low); + instruction.add_operand(high); + } + _ => unreachable!(), + }, + _ => unreachable!(), + } + + (instruction, id) + } + crate::ConstantInner::Float(val) => { + let type_id = self.get_type_id(arena, constant.ty); + + let mut instruction = Instruction::new(Op::Constant); + instruction.set_type(type_id); + instruction.set_result(id); + + let ty = &ir_module.types[constant.ty]; + match ty.inner { + crate::TypeInner::Scalar { kind: _, width } => match width { + 32 => { + instruction.add_operand((val as f32).to_bits()); + } + 64 => { + let bits = f64::to_bits(val); + let (low, high) = ((bits >> 32) as u32, bits as u32); + instruction.add_operand(low); + instruction.add_operand(high); + } + _ => unreachable!(), + }, + _ => unreachable!(), + } + + (instruction, id) + } + crate::ConstantInner::Bool(val) => { + let type_id = self.get_type_id(arena, constant.ty); + + let mut instruction = Instruction::new(if val { + Op::ConstantTrue + } else { + Op::ConstantFalse + }); + + instruction.set_type(type_id); + instruction.set_result(id); + (instruction, id) + } + crate::ConstantInner::Composite(ref constituents) => { + let type_id = self.get_type_id(arena, constant.ty); + + let mut instruction = Instruction::new(Op::ConstantComposite); + instruction.set_type(type_id); + instruction.set_result(id); + + for constituent in constituents.iter() { + let id = self.get_constant_id(*constituent, &ir_module); + instruction.add_operand(id); + } + + (instruction, id) + } + } + } + + fn get_pointer_id( + &mut self, + arena: &crate::Arena, + handle: crate::Handle, + class: StorageClass, + ) -> Word { + let ty = &arena[handle]; + let type_id = self.get_type_id(arena, handle); + match ty.inner { + crate::TypeInner::Pointer { .. } => type_id, + _ => { + let pointer_id = self.generate_id(); + let mut instruction = Instruction::new(Op::TypePointer); + instruction.set_result(pointer_id); + instruction.add_operand((class) as u32); + instruction.add_operand(type_id); + instruction.to_words(&mut self.logical_layout.declarations); + + /* TODO + Not able to lookup Pointer, because there is no Handle in the IR for it. + Idea would be to not have any handles at all in the lookups, so we aren't bound + to the IR. We can then insert, like here runtime values to the lookups + */ + // self.lookup_type.insert(pointer_id, global_variable.ty); + pointer_id + } + } + } + + fn instruction_global_variable( + &mut self, + arena: &crate::Arena, + global_variable: &crate::GlobalVariable, + handle: crate::Handle, + ) -> (Instruction, Word) { + let mut instruction = Instruction::new(Op::Variable); + let id = self.generate_id(); + + self.try_add_capabilities(global_variable.class.required_capabilities()); + + let pointer_id = self.get_pointer_id(arena, global_variable.ty, global_variable.class); + + instruction.set_type(pointer_id); + instruction.set_result(id); + instruction.add_operand(global_variable.class as u32); + + if self.writer_flags.contains(WriterFlags::DEBUG) { + let mut debug_instruction = Instruction::new(Op::Name); + debug_instruction.set_result(id); + debug_instruction.add_operands( + self.string_to_words(global_variable.name.as_ref().unwrap().as_str()), + ); + self.debugs.push(debug_instruction); + } + + match global_variable.binding.as_ref().unwrap() { + crate::Binding::Location(location) => { + let mut instruction = Instruction::new(Op::Decorate); + instruction.add_operand(id); + instruction.add_operand(Decoration::Location as u32); + instruction.add_operand(*location); + self.annotations.push(instruction); + } + crate::Binding::Descriptor { set, binding } => { + let mut set_instruction = Instruction::new(Op::Decorate); + set_instruction.add_operand(id); + set_instruction.add_operand(Decoration::DescriptorSet as u32); + set_instruction.add_operand(*set); + self.annotations.push(set_instruction); + + let mut binding_instruction = Instruction::new(Op::Decorate); + binding_instruction.add_operand(id); + binding_instruction.add_operand(Decoration::Binding as u32); + binding_instruction.add_operand(*binding); + self.annotations.push(binding_instruction); + } + crate::Binding::BuiltIn(built_in) => { + let built_in_u32: u32 = unsafe { std::mem::transmute(*built_in) }; + + let mut instruction = Instruction::new(Op::Decorate); + instruction.add_operand(id); + instruction.add_operand(Decoration::BuiltIn as u32); + instruction.add_operand(built_in_u32); + self.annotations.push(instruction); + } + } + + // TODO Initializer is optional and not (yet) included in the IR + + self.lookup_global_variable.insert(id, handle); + (instruction, id) + } + + fn write_physical_layout(&mut self) { + self.physical_layout.bound = self.id_count + 1; + } + + fn instruction_source(&self) -> Instruction { + let version = 450u32; + + let mut instruction = Instruction::new(Op::Source); + instruction.add_operand(SourceLanguage::GLSL as u32); + instruction.add_operands(self.bytes_to_words(&version.to_le_bytes())); + instruction + } + + fn instruction_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { + let mut id = None; + + for (k, v) in self.lookup_function_type.iter() { + if v.eq(&lookup_function_type) { + id = Some(*k); + break; + } + } + + if id.is_none() { + let _id = self.generate_id(); + id = Some(_id); + + let mut instruction = Instruction::new(Op::TypeFunction); + instruction.set_result(_id); + instruction.add_operand(lookup_function_type.return_type_id); + + for parameter_type_id in lookup_function_type.parameter_type_ids.iter() { + instruction.add_operand(*parameter_type_id); + } + + self.lookup_function_type.insert(_id, lookup_function_type); + instruction.to_words(&mut self.logical_layout.declarations); + } + + id.unwrap() + } + + fn instruction_function( + &mut self, + handle: crate::Handle, + function: &crate::Function, + arena: &crate::Arena, + ) -> Instruction { + let id = self.generate_id(); + + let return_type_id = self.get_function_type(function.return_type, arena); + + let mut instruction = Instruction::new(Op::Function); + instruction.set_type(return_type_id); + instruction.set_result(id); + + let control_u32: Word = unsafe { std::mem::transmute(function.control) }; + + instruction.add_operand(control_u32); + + let mut parameter_type_ids = Vec::with_capacity(function.parameter_types.len()); + for parameter_type in function.parameter_types.iter() { + parameter_type_ids.push(self.get_type_id(arena, *parameter_type)) + } + + let lookup_function_type = LookupFunctionType { + return_type_id, + parameter_type_ids, + }; + + let type_function_id = self.instruction_function_type(lookup_function_type); + + instruction.add_operand(type_function_id); + + self.lookup_function.insert(id, handle); + + instruction + } + + fn parse_expression<'a>( + &mut self, + ir_module: &'a crate::Module, + function: &crate::Function, + expression: &crate::Expression, + output: &mut Vec, + ) -> (Word, &'a crate::TypeInner) { + match expression { + crate::Expression::GlobalVariable(handle) => { + let var = &ir_module.global_variables[*handle]; + let inner = &ir_module.types[var.ty].inner; + let id = self.get_global_variable_id( + &ir_module.types, + &ir_module.global_variables, + *handle, + ); + (id, inner) + } + crate::Expression::Constant(handle) => { + let var = &ir_module.constants[*handle]; + let inner = &ir_module.types[var.ty].inner; + let id = self.get_constant_id(*handle, ir_module); + (id, inner) + } + crate::Expression::Compose { ty, components } => { + let var = &ir_module.types[*ty]; + let inner = &var.inner; + let id = self.generate_id(); + let type_id = self.get_type_id(&ir_module.types, *ty); + + let mut instruction = Instruction::new(Op::CompositeConstruct); + instruction.set_type(type_id); + instruction.set_result(id); + + for component in components { + let expression = &function.expressions[*component]; + let (component_id, _) = + self.parse_expression(ir_module, &function, expression, output); + instruction.add_operand(component_id); + } + + output.push(instruction); + + (id, inner) + } + crate::Expression::Binary { op, left, right } => { + match op { + crate::BinaryOperator::Multiply => { + // TODO OpVectorTimesScalar is only supported + let id = self.generate_id(); + let left_expression = &function.expressions[*left]; + let right_expression = &function.expressions[*right]; + let (left_id, left_inner) = + self.parse_expression(ir_module, function, left_expression, output); + let (right_id, right_inner) = + self.parse_expression(ir_module, function, right_expression, output); + + let mut result_type_id = None; + let mut vector_id = None; + let mut scalar_id = None; + + match left_inner { + crate::TypeInner::Vector { size, kind, width } => { + vector_id = Some(left_id); + for (k, v) in self.lookup_type.iter() { + let ty = &ir_module.types[*v]; + match ty.inner { + crate::TypeInner::Vector { + size: _size, + kind: _kind, + width: _width, + } => { + if size == &_size && kind == &_kind && width == &_width + { + result_type_id = Some(*k); + break; + } + } + _ => continue, + } + } + } + _ => scalar_id = Some(left_id), + } + + match right_inner { + crate::TypeInner::Vector { size, kind, width } => { + vector_id = Some(right_id); + for (k, v) in self.lookup_type.iter() { + let ty = &ir_module.types[*v]; + match ty.inner { + crate::TypeInner::Vector { + size: _size, + kind: _kind, + width: _width, + } => { + if size == &_size && kind == &_kind && width == &_width + { + result_type_id = Some(*k); + break; + } + } + _ => continue, + } + } + } + _ => scalar_id = Some(right_id), + } + + // TODO Quick fix + let load_id = self.generate_id(); + let mut instruction = Instruction::new(Op::Load); + instruction.set_type(result_type_id.unwrap()); + instruction.set_result(load_id); + instruction.add_operand(vector_id.unwrap()); + + output.push(instruction); + + let mut instruction = Instruction::new(Op::VectorTimesScalar); + instruction.set_type(result_type_id.unwrap()); + instruction.set_result(id); + instruction.add_operand(load_id); + instruction.add_operand(scalar_id.unwrap()); + output.push(instruction); + + // TODO Not sure how or what to return + ( + id, + &crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: 10, + }, + ) + } + _ => unimplemented!("{:?}", op), + } + } + crate::Expression::LocalVariable(variable) => { + let id = self.generate_id(); + let var = &function.local_variables[*variable]; + + let ty = &ir_module.types[var.ty]; + + let pointer_id = + self.get_pointer_id(&ir_module.types, var.ty, StorageClass::Function); + + let mut instruction = Instruction::new(Op::Variable); + instruction.set_type(pointer_id); + instruction.set_result(id); + instruction.add_operand(StorageClass::Function as u32); + (id, &ty.inner) + } + _ => unimplemented!("{:?}", expression), + } + } + + fn instruction_function_block( + &mut self, + ir_module: &crate::Module, + function: &crate::Function, + statement: &crate::Statement, + output: &mut Vec, + ) -> Instruction { + match statement { + crate::Statement::Return { value: _ } => match function.return_type { + Some(_) => unimplemented!(), + None => Instruction::new(Op::Return), + }, + crate::Statement::Store { pointer, value } => { + let mut instruction = Instruction::new(Op::Store); + + let pointer_expression = &function.expressions[*pointer]; + let value_expression = &function.expressions[*value]; + let (pointer_id, _) = + self.parse_expression(ir_module, function, pointer_expression, output); + let (value_id, _) = + self.parse_expression(ir_module, function, value_expression, output); + + instruction.add_operand(pointer_id); + instruction.add_operand(value_id); + + instruction + } + _ => unimplemented!(), + } + } + + fn instruction_label(&mut self) -> Instruction { + let mut instruction = Instruction::new(Op::Label); + instruction.set_result(self.generate_id()); + instruction + } + + fn instruction_function_end(&self) -> Instruction { + Instruction::new(Op::FunctionEnd) + } + + fn write_logical_layout(&mut self, ir_module: &crate::Module) { + self.instruction_ext_inst_import("GLSL.std.450") + .to_words(&mut self.logical_layout.ext_inst_imports); + + if self.writer_flags.contains(WriterFlags::DEBUG) { + self.debugs.push(self.instruction_source()); + } + + for (handle, function) in ir_module.functions.iter() { + let mut function_instructions: Vec = vec![]; + function_instructions.push(self.instruction_function( + handle, + function, + &ir_module.types, + )); + + function_instructions.push(self.instruction_label()); + + for block in function.body.iter() { + let mut output: Vec = vec![]; + let instruction = + self.instruction_function_block(ir_module, function, &block, &mut output); + function_instructions.append(&mut output); + function_instructions.push(instruction); + } + + function_instructions.push(self.instruction_function_end()); + for instruction in function_instructions.iter() { + instruction.to_words(&mut self.logical_layout.function_definitions); + } + } + + for entry_point in ir_module.entry_points.iter() { + let entry_point_instruction = self.instruction_entry_point(entry_point, ir_module); + entry_point_instruction.to_words(&mut self.logical_layout.entry_points); + } + + // Looking through all global variable, types, constants. + // Doing this because we also want to include not used parts of the module + // to be included in the output + for (handle, _) in ir_module.global_variables.iter() { + self.get_global_variable_id(&ir_module.types, &ir_module.global_variables, handle); + } + + for (handle, _) in ir_module.types.iter() { + self.get_type_id(&ir_module.types, handle); + } + + for (handle, _) in ir_module.constants.iter() { + self.get_constant_id(handle, &ir_module); + } + + for annotation in self.annotations.iter() { + annotation.to_words(&mut self.logical_layout.annotations); + } + + for capability in self.capabilities.iter() { + self.instruction_capability(*capability) + .to_words(&mut self.logical_layout.capabilities); + } + + self.instruction_memory_model() + .to_words(&mut self.logical_layout.memory_model); + + if self.writer_flags.contains(WriterFlags::DEBUG) { + for debug in self.debugs.iter() { + debug.to_words(&mut self.logical_layout.debugs); + } + } + } + + pub fn write(&mut self, ir_module: &crate::Module) -> Vec { + let mut words: Vec = vec![]; + + self.write_logical_layout(ir_module); + self.write_physical_layout(); + + self.physical_layout.in_words(&mut words); + self.logical_layout.in_words(&mut words); + words + } +} diff --git a/src/front/mod.rs b/src/front/mod.rs index 0ca2c87c3..36bdd65e9 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,6 +1,6 @@ #[cfg(feature = "glsl")] pub mod glsl; -pub mod spirv; +pub mod spv; pub mod wgsl; use crate::arena::Arena; diff --git a/src/front/spirv.rs b/src/front/spv.rs similarity index 99% rename from src/front/spirv.rs rename to src/front/spv.rs index 1ebd1b1f0..ac4a12071 100644 --- a/src/front/spirv.rs +++ b/src/front/spv.rs @@ -4,7 +4,7 @@ Our IR links to everything with `Handle`, while SPIR-V uses IDs. In order to keep track of the associations, the parser has many lookup tables. -There map `spirv::Word` into a specific IR handle, plus potentially a bit of +There map `spv::Word` into a specific IR handle, plus potentially a bit of extra info, such as the related SPIR-V type ID. TODO: would be nice to find ways that avoid looking up as much From 89d2afa11bf8eac4b429267cc70ba9a1769f3a10 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Jun 2020 14:55:40 -0400 Subject: [PATCH 0079/2212] Comparison sampler API (#66) --- Cargo.toml | 2 +- src/back/msl.rs | 2 +- src/back/spv/writer.rs | 2 +- src/front/glsl/helpers.rs | 2 +- src/front/spv.rs | 2 +- src/lib.rs | 4 +++- 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 48dc52968..fab5e3df5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ bitflags = "1" fxhash = "0.2" log = "0.4" num-traits = "0.2" -spirv = { package = "spirv_headers", version = "1" } +spirv = { package = "spirv_headers", version = "1.4.2" } glsl = { version = "4", optional = true } [features] diff --git a/src/back/msl.rs b/src/back/msl.rs index 20fe75cb0..bb74984a7 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -902,7 +902,7 @@ impl Writer { dim, base_name, access, name )?; } - crate::TypeInner::Sampler => { + crate::TypeInner::Sampler { comparison: _ } => { write!(self.out, "typedef sampler {}", name)?; } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d5a3b70ed..a81ad7a5e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -433,7 +433,7 @@ impl Writer { self.lookup_type.insert(id, base); } - crate::TypeInner::Sampler => { + crate::TypeInner::Sampler { comparison: _ } => { instruction = Instruction::new(Op::TypeSampler); instruction.set_result(id); self.lookup_type.insert(id, handle); diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs index 7c88746e3..a2a9c7a73 100644 --- a/src/front/glsl/helpers.rs +++ b/src/front/glsl/helpers.rs @@ -275,7 +275,7 @@ pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> } if ty_name.0 == "sampler" { - return Some(TypeInner::Sampler); + return Some(TypeInner::Sampler { comparison: false }); //TODO } unimplemented!() } diff --git a/src/front/spv.rs b/src/front/spv.rs index ac4a12071..79fdf8330 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -1303,7 +1303,7 @@ impl> Parser { inst.expect(2)?; let id = self.next()?; let decor = self.future_decor.remove(&id).unwrap_or_default(); - let inner = crate::TypeInner::Sampler; + let inner = crate::TypeInner::Sampler { comparison: false }; //TODO! self.lookup_type.insert( id, LookupType { diff --git a/src/lib.rs b/src/lib.rs index 67660c33e..6dfdee9d0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -105,7 +105,9 @@ pub enum TypeInner { dim: spirv::Dim, flags: ImageFlags, }, - Sampler, + Sampler { + comparison: bool, + }, } #[derive(Debug, PartialEq)] From d55cd79a216a62520052c27724078c60a94e8943 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Jun 2020 22:38:23 -0400 Subject: [PATCH 0080/2212] Minor improvements, expose Handle, move glsl module inside the dir. --- examples/convert.rs | 26 ++++++++++++++++---------- src/arena.rs | 4 ++++ src/back/spv/mod.rs | 4 +++- src/front/glsl/helpers.rs | 7 ++++--- src/front/{glsl.rs => glsl/mod.rs} | 8 ++++---- src/lib.rs | 2 +- 6 files changed, 32 insertions(+), 19 deletions(-) rename src/front/{glsl.rs => glsl/mod.rs} (96%) diff --git a/examples/convert.rs b/examples/convert.rs index b41e0127b..bd066a9f7 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -25,17 +25,23 @@ fn main() { let args = env::args().collect::>(); - let module = if args.len() <= 1 { + if args.len() <= 1 { println!("Call with "); return; - } else if args[1].ends_with(".spv") { - let input = fs::read(&args[1]).unwrap(); - naga::front::spv::parse_u8_slice(&input).unwrap() - } else if args[1].ends_with(".wgsl") { - let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::wgsl::parse_str(&input).unwrap() - } else { - panic!("Unknown input: {:?}", args[1]); + } + let in_ext_pos = args[1].rfind(".").expect("Input has no extension?"); + let module = match &args[1][in_ext_pos..] { + "spv" => { + let input = fs::read(&args[1]).unwrap(); + naga::front::spv::parse_u8_slice(&input).unwrap() + } + "wgsl" => { + let input = fs::read_to_string(&args[1]).unwrap(); + naga::front::wgsl::parse_str(&input).unwrap() + } + //#[cfg(feature = "glsl")] //TODO + //"glsl" | "vert" | "frag" | "comp" => {} + other => panic!("Unknown input extension: {}", other), }; if args.len() <= 2 { @@ -82,7 +88,7 @@ fn main() { } }); - let spv = spv::writer::Writer::new(&module.header, debug_flag).write(&module); + let spv = spv::Writer::new(&module.header, debug_flag).write(&module); let bytes = spv .iter() diff --git a/src/arena.rs b/src/arena.rs index d6d8dc511..d84da7790 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -84,6 +84,10 @@ impl Arena { self.data.len() } + pub fn is_empty(&self) -> bool { + self.data.is_empty() + } + pub fn iter(&self) -> impl Iterator, &T)> { self.data.iter().enumerate().map(|(i, v)| { let position = i + 1; diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 183f7c008..444bc2301 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -1,5 +1,7 @@ mod layout; -pub mod writer; +mod writer; + +pub use writer::Writer; use spirv::*; diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs index a2a9c7a73..5b575cbf4 100644 --- a/src/front/glsl/helpers.rs +++ b/src/front/glsl/helpers.rs @@ -274,10 +274,11 @@ pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> return Some(TypeInner::Image { base, dim, flags }); } - if ty_name.0 == "sampler" { - return Some(TypeInner::Sampler { comparison: false }); //TODO + match ty_name.0.as_str() { + "sampler" => TypeInner::Sampler { comparison: false }, + "samplerShadow" => TypeInner::Sampler { comparison: true }, + _ => unimplemented!(), } - unimplemented!() } _ => unimplemented!(), }) diff --git a/src/front/glsl.rs b/src/front/glsl/mod.rs similarity index 96% rename from src/front/glsl.rs rename to src/front/glsl/mod.rs index 1fe3b215f..9b52e8967 100644 --- a/src/front/glsl.rs +++ b/src/front/glsl/mod.rs @@ -1213,7 +1213,7 @@ mod tests { #[test] fn test_vertex() { - let data = include_str!("../../test-data/glsl_vertex_test_shader.vert"); + let data = include_str!("../../../test-data/glsl_vertex_test_shader.vert"); println!( "{:#?}", @@ -1225,7 +1225,7 @@ mod tests { fn test_frag() { let _ = env_logger::try_init(); - let data = include_str!("../../test-data/glsl_phong_lighting.frag"); + let data = include_str!("../../../test-data/glsl_phong_lighting.frag"); println!( "{:#?}", @@ -1238,7 +1238,7 @@ mod tests { fn test_preprocess() { let _ = env_logger::try_init(); - let data = include_str!("../../test-data/glsl_preprocessor_abuse.vert"); + let data = include_str!("../../../test-data/glsl_preprocessor_abuse.vert"); println!( "{:#?}", @@ -1252,7 +1252,7 @@ mod tests { fn test_preprocess_ifs() { let _ = env_logger::try_init(); - let data = include_str!("../../test-data/glsl_if_preprocessor.vert"); + let data = include_str!("../../../test-data/glsl_if_preprocessor.vert"); println!( "{:#?}", diff --git a/src/lib.rs b/src/lib.rs index 6dfdee9d0..c75562988 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,7 +5,7 @@ pub mod back; pub mod front; pub mod proc; -use crate::arena::{Arena, Handle}; +pub use crate::arena::{Arena, Handle}; use std::{ collections::{HashMap, HashSet}, From 8e0ae1cf0695a6a8dd169ab7afa767b707ed8476 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Jun 2020 22:41:20 -0400 Subject: [PATCH 0081/2212] Convert glsl module line endings to Unix --- src/front/glsl/helpers.rs | 570 ++--- src/front/glsl/mod.rs | 2524 +++++++++--------- src/front/glsl/parser.rs | 492 ++-- src/front/glsl/parser/lex.rs | 508 ++-- src/front/glsl/preprocessor.rs | 3236 ++++++++++++------------ test-data/glsl_if_preprocessor.vert | 28 +- test-data/glsl_preprocessor_abuse.vert | 20 +- 7 files changed, 3689 insertions(+), 3689 deletions(-) diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs index 5b575cbf4..1bd8dc889 100644 --- a/src/front/glsl/helpers.rs +++ b/src/front/glsl/helpers.rs @@ -1,285 +1,285 @@ -use crate::{Arena, ImageFlags, ScalarKind, Type, TypeInner, VectorSize}; -use glsl::syntax::{BinaryOp, TypeSpecifierNonArray}; -use spirv::Dim; - -pub fn glsl_to_spirv_binary_op(op: BinaryOp) -> crate::BinaryOperator { - match op { - BinaryOp::Or => crate::BinaryOperator::LogicalOr, - BinaryOp::Xor => todo!(), - BinaryOp::And => crate::BinaryOperator::LogicalAnd, - BinaryOp::BitOr => crate::BinaryOperator::InclusiveOr, - BinaryOp::BitXor => crate::BinaryOperator::ExclusiveOr, - BinaryOp::BitAnd => crate::BinaryOperator::And, - BinaryOp::Equal => crate::BinaryOperator::Equal, - BinaryOp::NonEqual => crate::BinaryOperator::NotEqual, - BinaryOp::LT => crate::BinaryOperator::Less, - BinaryOp::GT => crate::BinaryOperator::Greater, - BinaryOp::LTE => crate::BinaryOperator::LessEqual, - BinaryOp::GTE => crate::BinaryOperator::GreaterEqual, - BinaryOp::LShift => crate::BinaryOperator::ShiftLeftLogical, - BinaryOp::RShift => crate::BinaryOperator::ShiftRightArithmetic, - BinaryOp::Add => crate::BinaryOperator::Add, - BinaryOp::Sub => crate::BinaryOperator::Subtract, - BinaryOp::Mult => crate::BinaryOperator::Multiply, - BinaryOp::Div => crate::BinaryOperator::Divide, - BinaryOp::Mod => crate::BinaryOperator::Modulo, - } -} - -pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> Option { - use TypeSpecifierNonArray::*; - - Some(match ty { - Void => return None, - Bool => TypeInner::Scalar { - kind: ScalarKind::Bool, - width: 1, - }, - Int => TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 32, - }, - UInt => TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 32, - }, - Float => TypeInner::Scalar { - kind: ScalarKind::Float, - width: 32, - }, - Double => TypeInner::Scalar { - kind: ScalarKind::Float, - width: 64, - }, - Vec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 32, - }, - Vec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Float, - width: 32, - }, - Vec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 32, - }, - DVec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 64, - }, - DVec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Float, - width: 64, - }, - DVec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 64, - }, - BVec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Bool, - width: 1, - }, - BVec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Bool, - width: 1, - }, - BVec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Bool, - width: 1, - }, - IVec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Sint, - width: 32, - }, - IVec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Sint, - width: 32, - }, - IVec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Sint, - width: 32, - }, - UVec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Uint, - width: 32, - }, - UVec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Uint, - width: 32, - }, - UVec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Uint, - width: 32, - }, - // Float Matrices - Mat2 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 32, - }, - Mat3 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 32, - }, - Mat4 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 32, - }, - Mat23 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 32, - }, - Mat24 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 32, - }, - Mat32 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 32, - }, - Mat34 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 32, - }, - Mat42 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 32, - }, - Mat43 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 32, - }, - // Double Matrices - DMat2 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 64, - }, - DMat3 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 64, - }, - DMat4 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 64, - }, - DMat23 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 64, - }, - DMat24 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 64, - }, - DMat32 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 64, - }, - DMat34 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 64, - }, - DMat42 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 64, - }, - DMat43 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 64, - }, - TypeName(ty_name) => { - if let Some(t_pos) = ty_name.0.find("texture") { - let scalar_kind = match &ty_name.0[..t_pos] { - "" => ScalarKind::Float, - "i" => ScalarKind::Sint, - "u" => ScalarKind::Uint, - _ => panic!(), - }; - let base = types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: scalar_kind, - width: 32, - }, - }); - - let (dim, flags) = match &ty_name.0[(t_pos + 7)..] { - "1D" => (Dim::Dim1D, ImageFlags::SAMPLED), - "2D" => (Dim::Dim2D, ImageFlags::SAMPLED), - "3D" => (Dim::Dim3D, ImageFlags::SAMPLED), - "1DArray" => (Dim::Dim1D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), - "2DArray" => (Dim::Dim2D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), - "3DArray" => (Dim::Dim3D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), - "2DMS" => (Dim::Dim2D, ImageFlags::SAMPLED | ImageFlags::MULTISAMPLED), - "2DMSArray" => ( - Dim::Dim2D, - ImageFlags::SAMPLED | ImageFlags::ARRAYED | ImageFlags::MULTISAMPLED, - ), - "2DRect" => (Dim::DimRect, ImageFlags::SAMPLED), - "Cube" => (Dim::DimCube, ImageFlags::SAMPLED), - "CubeArray" => (Dim::DimCube, ImageFlags::SAMPLED | ImageFlags::ARRAYED), - "Buffer" => (Dim::DimBuffer, ImageFlags::SAMPLED), - _ => panic!(), - }; - - return Some(TypeInner::Image { base, dim, flags }); - } - - match ty_name.0.as_str() { - "sampler" => TypeInner::Sampler { comparison: false }, - "samplerShadow" => TypeInner::Sampler { comparison: true }, - _ => unimplemented!(), - } - } - _ => unimplemented!(), - }) -} +use crate::{Arena, ImageFlags, ScalarKind, Type, TypeInner, VectorSize}; +use glsl::syntax::{BinaryOp, TypeSpecifierNonArray}; +use spirv::Dim; + +pub fn glsl_to_spirv_binary_op(op: BinaryOp) -> crate::BinaryOperator { + match op { + BinaryOp::Or => crate::BinaryOperator::LogicalOr, + BinaryOp::Xor => todo!(), + BinaryOp::And => crate::BinaryOperator::LogicalAnd, + BinaryOp::BitOr => crate::BinaryOperator::InclusiveOr, + BinaryOp::BitXor => crate::BinaryOperator::ExclusiveOr, + BinaryOp::BitAnd => crate::BinaryOperator::And, + BinaryOp::Equal => crate::BinaryOperator::Equal, + BinaryOp::NonEqual => crate::BinaryOperator::NotEqual, + BinaryOp::LT => crate::BinaryOperator::Less, + BinaryOp::GT => crate::BinaryOperator::Greater, + BinaryOp::LTE => crate::BinaryOperator::LessEqual, + BinaryOp::GTE => crate::BinaryOperator::GreaterEqual, + BinaryOp::LShift => crate::BinaryOperator::ShiftLeftLogical, + BinaryOp::RShift => crate::BinaryOperator::ShiftRightArithmetic, + BinaryOp::Add => crate::BinaryOperator::Add, + BinaryOp::Sub => crate::BinaryOperator::Subtract, + BinaryOp::Mult => crate::BinaryOperator::Multiply, + BinaryOp::Div => crate::BinaryOperator::Divide, + BinaryOp::Mod => crate::BinaryOperator::Modulo, + } +} + +pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> Option { + use TypeSpecifierNonArray::*; + + Some(match ty { + Void => return None, + Bool => TypeInner::Scalar { + kind: ScalarKind::Bool, + width: 1, + }, + Int => TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + UInt => TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 32, + }, + Float => TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + Double => TypeInner::Scalar { + kind: ScalarKind::Float, + width: 64, + }, + Vec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Float, + width: 32, + }, + Vec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Float, + width: 32, + }, + Vec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + DVec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Float, + width: 64, + }, + DVec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Float, + width: 64, + }, + DVec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 64, + }, + BVec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Bool, + width: 1, + }, + BVec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Bool, + width: 1, + }, + BVec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Bool, + width: 1, + }, + IVec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Sint, + width: 32, + }, + IVec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Sint, + width: 32, + }, + IVec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Sint, + width: 32, + }, + UVec2 => TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Uint, + width: 32, + }, + UVec3 => TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Uint, + width: 32, + }, + UVec4 => TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Uint, + width: 32, + }, + // Float Matrices + Mat2 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 32, + }, + Mat3 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 32, + }, + Mat4 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + Mat23 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 32, + }, + Mat24 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + Mat32 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 32, + }, + Mat34 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + Mat42 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 32, + }, + Mat43 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 32, + }, + // Double Matrices + DMat2 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 64, + }, + DMat3 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 64, + }, + DMat4 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 64, + }, + DMat23 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 64, + }, + DMat24 => TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 64, + }, + DMat32 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 64, + }, + DMat34 => TypeInner::Matrix { + columns: VectorSize::Tri, + rows: VectorSize::Quad, + kind: ScalarKind::Float, + width: 64, + }, + DMat42 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Bi, + kind: ScalarKind::Float, + width: 64, + }, + DMat43 => TypeInner::Matrix { + columns: VectorSize::Quad, + rows: VectorSize::Tri, + kind: ScalarKind::Float, + width: 64, + }, + TypeName(ty_name) => { + if let Some(t_pos) = ty_name.0.find("texture") { + let scalar_kind = match &ty_name.0[..t_pos] { + "" => ScalarKind::Float, + "i" => ScalarKind::Sint, + "u" => ScalarKind::Uint, + _ => panic!(), + }; + let base = types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: scalar_kind, + width: 32, + }, + }); + + let (dim, flags) = match &ty_name.0[(t_pos + 7)..] { + "1D" => (Dim::Dim1D, ImageFlags::SAMPLED), + "2D" => (Dim::Dim2D, ImageFlags::SAMPLED), + "3D" => (Dim::Dim3D, ImageFlags::SAMPLED), + "1DArray" => (Dim::Dim1D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), + "2DArray" => (Dim::Dim2D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), + "3DArray" => (Dim::Dim3D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), + "2DMS" => (Dim::Dim2D, ImageFlags::SAMPLED | ImageFlags::MULTISAMPLED), + "2DMSArray" => ( + Dim::Dim2D, + ImageFlags::SAMPLED | ImageFlags::ARRAYED | ImageFlags::MULTISAMPLED, + ), + "2DRect" => (Dim::DimRect, ImageFlags::SAMPLED), + "Cube" => (Dim::DimCube, ImageFlags::SAMPLED), + "CubeArray" => (Dim::DimCube, ImageFlags::SAMPLED | ImageFlags::ARRAYED), + "Buffer" => (Dim::DimBuffer, ImageFlags::SAMPLED), + _ => panic!(), + }; + + return Some(TypeInner::Image { base, dim, flags }); + } + + match ty_name.0.as_str() { + "sampler" => TypeInner::Sampler { comparison: false }, + "samplerShadow" => TypeInner::Sampler { comparison: true }, + _ => unimplemented!(), + } + } + _ => unimplemented!(), + }) +} diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 9b52e8967..603e75c36 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,1262 +1,1262 @@ -use crate::{ - Arena, ArraySize, BinaryOperator, Binding, Constant, ConstantInner, EntryPoint, Expression, - FastHashMap, Function, GlobalVariable, Handle, Header, LocalVariable, Module, ScalarKind, - StructMember, Type, TypeInner, VectorSize, -}; -use glsl::{ - parser::{Parse, ParseError}, - syntax::*, -}; -use parser::{Token, TokenMetadata}; -use spirv::{BuiltIn, ExecutionModel, StorageClass}; -use std::fmt; - -mod helpers; -mod parser; - -#[derive(Debug)] -pub enum ErrorKind { - UnexpectedToken { - expected: Vec, - got: TokenMetadata, - }, - UnexpectedWord { - expected: Vec<&'static str>, - got: String, - }, - ExpectedEOL { - got: TokenMetadata, - }, - UnknownPragma { - pragma: String, - }, - ExtensionNotSupported { - extension: String, - }, - AllExtensionsEnabled, - ExtensionUnknownBehavior { - behavior: String, - }, - UnsupportedVersion { - version: usize, - }, - UnsupportedProfile { - profile: String, - }, - UnknownProfile { - profile: String, - }, - UnknownPreprocessorDirective { - directive: String, - }, - UnboundedIfCloserOrVariant { - token: TokenMetadata, - }, - NonIntegralType { - token: TokenMetadata, - }, - ReservedMacro, - EOL, - EOF, -} - -impl fmt::Display for ErrorKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ErrorKind::UnexpectedToken { expected, got } => write!( - f, - "Unexpected token:\nexpected: {}\ngot: {}", - expected - .iter() - .map(|token| { - let mut type_string = token.type_to_string(); - type_string.push_str(" |"); - type_string - }) - .collect::(), - got.token - ), - ErrorKind::UnexpectedWord { expected, got } => write!( - f, - "Unexpected word:\nexpected: {}\ngot: {}", - expected.iter().fold(String::new(), |mut acc, word| { - acc.push_str(*word); - - acc.push_str("|"); - - acc - }), - got - ), - ErrorKind::ExpectedEOL { got } => { - write!(f, "Expected end of line:\ngot: {}", got.token) - } - ErrorKind::UnknownPragma { pragma } => write!(f, "Unknown pragma: {}", pragma), - ErrorKind::ExtensionNotSupported { extension } => { - write!(f, "The extension \"{}\" is not supported", extension) - } - ErrorKind::AllExtensionsEnabled => { - write!(f, "All extensions can't be require or enable") - } - ErrorKind::ExtensionUnknownBehavior { behavior } => write!( - f, - "The extension behavior must be one of require|enable|warn|disable got: {}", - behavior - ), - ErrorKind::UnsupportedVersion { version } => write!( - f, - "The version {} isn't supported use either 450 or 460", - version - ), - ErrorKind::UnsupportedProfile { profile } => { - write!(f, "The profile {} isn't supported use core", profile) - } - ErrorKind::UnknownProfile { profile } => { - write!(f, "The profile {} isn't defined use core", profile) - } - ErrorKind::UnknownPreprocessorDirective { directive } => { - write!(f, "The preprocessor directive {} isn't defined", directive) - } - ErrorKind::UnboundedIfCloserOrVariant { token } => { - write!(f, "The preprocessor directives \"else\", \"elif\" or \"endif\" must be preceded by an \"if\", token: {}", token.token) - } - ErrorKind::NonIntegralType { token } => { - write!(f, "The preprocessor \"if\" directive can only contain integrals found: {}", token.token) - } - ErrorKind::ReservedMacro => write!(f, "Macro can't begin with GL_"), - ErrorKind::EOL => write!(f, "End of line"), - ErrorKind::EOF => write!(f, "End of file"), - } - } -} - -#[derive(Debug)] -pub struct Error { - pub kind: ErrorKind, -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self) - } -} - -impl std::error::Error for Error {} - -#[derive(Debug, Copy, Clone)] -enum Global { - Variable(Handle), - StructShorthand(Handle, u32), -} - -struct Parser<'a> { - source: &'a str, - types: Arena, - globals: Arena, - globals_lookup: FastHashMap, - constants: Arena, - functions: Arena, - function_lookup: FastHashMap>, - exec_model: ExecutionModel, -} - -impl<'a> Parser<'a> { - pub fn new(source: &'a str, exec_model: ExecutionModel) -> Result { - Ok(Self { - source, - types: Arena::new(), - globals: Arena::new(), - globals_lookup: FastHashMap::default(), - constants: Arena::new(), - functions: Arena::new(), - function_lookup: FastHashMap::default(), - exec_model, - }) - } - - pub fn parse(mut self, entry: String) -> Result { - let ast = TranslationUnit::parse(self.source)?; - - //println!("{:#?}", ast); - - let mut entry_point = None; - - for declaration in ast { - match declaration { - ExternalDeclaration::Preprocessor(_) => - { - #[cfg(feature = "glsl_preprocessor")] - unreachable!() - } - ExternalDeclaration::FunctionDefinition(function) => { - let function = self.parse_function_definition(function); - - if *self.functions[function].name.as_ref().unwrap() == entry { - assert!(entry_point.is_none()); - - entry_point = Some(function); - } - } - ExternalDeclaration::Declaration(decl) => match decl { - Declaration::InitDeclaratorList(init) => { - let handle = self.parse_global(init); - let name = self.globals[handle].name.clone().unwrap(); - self.globals_lookup.insert(name, Global::Variable(handle)); - } - Declaration::Block(block) => { - let (class, binding) = Self::parse_type_qualifier(block.qualifier); - let ty_name = block.name.0; - - let name = block.identifier.clone().map(|ident| ident.ident.0); - - let mut fields = Vec::new(); - let mut reexports = Vec::new(); - let mut index = 0; - - for field in block.fields { - let binding = field - .qualifier - .and_then(|qualifier| Self::parse_type_qualifier(qualifier).1); - - let ty = self.parse_type(field.ty).unwrap(); - - for ident in field.identifiers { - let field_name = ident.ident.0; - - fields.push(StructMember { - name: Some(field_name.clone()), - binding: binding.clone(), - ty: if let Some(array_spec) = ident.array_spec { - self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size: match array_spec { - ArraySpecifier::Unsized => ArraySize::Dynamic, - ArraySpecifier::ExplicitlySized(_expr) => { - unimplemented!() - } - }, - }, - }) - } else { - ty - }, - }); - - if name.is_none() { - reexports.push((field_name, index)); - index += 1; - } - } - } - - let ty = if let Some(array_spec) = - block.identifier.and_then(|ident| ident.array_spec) - { - let base = self.types.fetch_or_append(Type { - name: Some(ty_name), - inner: TypeInner::Struct { members: fields }, - }); - - self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base, - size: match array_spec { - ArraySpecifier::Unsized => ArraySize::Dynamic, - ArraySpecifier::ExplicitlySized(_expr) => unimplemented!(), - }, - }, - }) - } else { - self.types.fetch_or_append(Type { - name: Some(ty_name), - inner: TypeInner::Struct { members: fields }, - }) - }; - - let handle = self.globals.append(GlobalVariable { - binding, - class, - name, - ty, - }); - - for (name, index) in reexports { - self.globals_lookup - .insert(name, Global::StructShorthand(handle, index)); - } - } - _ => unimplemented!(), - }, - } - } - - Ok(Module { - header: Header { - version: (1, 0, 0), - generator: 0, - }, - types: self.types, - constants: self.constants, - global_variables: self.globals, - functions: self.functions, - entry_points: vec![EntryPoint { - exec_model: self.exec_model, - function: entry_point.unwrap(), - name: entry, - }], - }) - } - - fn parse_function_definition(&mut self, function: FunctionDefinition) -> Handle { - let name = function.prototype.name.0; - - // Parse return type - let ty = self.parse_type(function.prototype.ty.ty); - - let mut parameter_types = Vec::with_capacity(function.prototype.parameters.len()); - let mut parameter_lookup = FastHashMap::default(); - - let mut local_variables = Arena::::new(); - let mut locals_map = FastHashMap::default(); - let mut expressions = Arena::::new(); - let mut body = Vec::new(); - - // TODO: Parse Qualifiers - for (index, parameter) in function.prototype.parameters.into_iter().enumerate() { - match parameter { - FunctionParameterDeclaration::Named(_ /* TODO */, decl) => { - let ty = self.parse_type(decl.ty).unwrap(); - - let ty = if let Some(specifier) = decl.ident.array_spec { - match specifier { - ArraySpecifier::Unsized => self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size: ArraySize::Dynamic, - }, - }), - ArraySpecifier::ExplicitlySized(_) => unimplemented!(), - } - } else { - ty - }; - - parameter_types.push(ty); - parameter_lookup.insert( - decl.ident.ident.0, - Expression::FunctionParameter(index as u32), - ); - } - FunctionParameterDeclaration::Unnamed(_, ty) => { - parameter_types.push(self.parse_type(ty).unwrap()); - } - } - } - - for statement in function.statement.statement_list { - match statement { - Statement::Compound(_) => unimplemented!(), - Statement::Simple(statement) => match *statement { - SimpleStatement::Declaration(declaration) => match declaration { - Declaration::InitDeclaratorList(init) => { - self.parse_local_variable( - init, - &mut expressions, - &mut local_variables, - &mut locals_map, - ¶meter_lookup, - ); - } - _ => unimplemented!(), - }, - SimpleStatement::Expression(expr) => { - let expr = match expr { - Some(expr) => expr, - None => continue, - }; - - body.push(self.parse_statement( - expr, - &mut expressions, - &mut local_variables, - &mut locals_map, - ¶meter_lookup, - )); - } - SimpleStatement::Selection(_) => unimplemented!(), - SimpleStatement::Switch(_) => unimplemented!(), - SimpleStatement::CaseLabel(_) => unimplemented!(), - SimpleStatement::Iteration(_) => unimplemented!(), - SimpleStatement::Jump(op) => body.push(match op { - JumpStatement::Continue => crate::Statement::Continue, - JumpStatement::Break => crate::Statement::Break, - JumpStatement::Return(expr) => crate::Statement::Return { - value: expr.map(|expr| { - let expr = self.parse_expression( - *expr, - &mut expressions, - &mut local_variables, - &mut locals_map, - ¶meter_lookup, - ); - expressions.append(expr) - }), - }, - JumpStatement::Discard => crate::Statement::Kill, - }), - }, - } - } - - let handle = self.functions.append(Function { - name: Some(name.clone()), - control: spirv::FunctionControl::NONE, - parameter_types, - return_type: ty, - global_usage: vec![], - local_variables, - expressions, - body, - }); - - self.function_lookup.insert(name, handle); - - handle - } - - fn parse_local_variable( - &mut self, - init: InitDeclaratorList, - expressions: &mut Arena, - locals: &mut Arena, - locals_map: &mut FastHashMap>, - parameter_lookup: &FastHashMap, - ) -> Handle { - let name = init.head.name.map(|d| d.0); - let ty = { - let ty = self.parse_type(init.head.ty.ty).unwrap(); - - if let Some(specifier) = init.head.array_specifier { - match specifier { - ArraySpecifier::Unsized => self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size: ArraySize::Dynamic, - }, - }), - ArraySpecifier::ExplicitlySized(_) => unimplemented!(), - } - } else { - ty - } - }; - - let initializer = init.head.initializer.map(|initializer| { - self.parse_initializer( - initializer, - expressions, - locals, - locals_map, - parameter_lookup, - ) - }); - - let handle = locals.append(LocalVariable { - name: name.clone(), - ty, - init: initializer, - }); - - locals_map.insert(name.unwrap(), handle); - - handle - } - - fn parse_initializer( - &mut self, - initializer: Initializer, - expressions: &mut Arena, - locals: &mut Arena, - locals_map: &mut FastHashMap>, - parameter_lookup: &FastHashMap, - ) -> Handle { - match initializer { - Initializer::Simple(expr) => { - let handle = - self.parse_expression(*expr, expressions, locals, locals_map, parameter_lookup); - - expressions.append(handle) - } - Initializer::List(_exprs) => unimplemented!(), - } - } - - fn parse_statement( - &mut self, - expr: Expr, - expressions: &mut Arena, - locals: &mut Arena, - locals_map: &mut FastHashMap>, - parameter_lookup: &FastHashMap, - ) -> crate::Statement { - match expr { - Expr::Assignment(reg, op, value) => { - let pointer = { - let pointer = self.parse_expression( - *reg, - expressions, - locals, - locals_map, - parameter_lookup, - ); - expressions.append(pointer) - }; - - let right = self.parse_expression( - *value, - expressions, - locals, - locals_map, - parameter_lookup, - ); - let value = match op { - AssignmentOp::Equal => right, - AssignmentOp::Mult => Expression::Binary { - op: BinaryOperator::Multiply, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Div => Expression::Binary { - op: BinaryOperator::Divide, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Mod => Expression::Binary { - op: BinaryOperator::Modulo, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Add => Expression::Binary { - op: BinaryOperator::Add, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Sub => Expression::Binary { - op: BinaryOperator::Subtract, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::LShift => Expression::Binary { - op: BinaryOperator::ShiftLeftLogical, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::RShift => { - Expression::Binary { - op: BinaryOperator::ShiftRightArithmetic, /* ??? */ - left: pointer, - right: expressions.append(right), - } - } - AssignmentOp::And => Expression::Binary { - op: BinaryOperator::And, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Xor => Expression::Binary { - op: BinaryOperator::ExclusiveOr, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Or => Expression::Binary { - op: BinaryOperator::InclusiveOr, - left: pointer, - right: expressions.append(right), - }, - }; - - crate::Statement::Store { - pointer, - value: expressions.append(value), - } - } - Expr::FunCall(_, _) => unimplemented!(), - Expr::PostInc(_) => unimplemented!(), - Expr::PostDec(_) => unimplemented!(), - _ => panic!(), - } - } - - fn parse_expression( - &mut self, - expr: Expr, - expressions: &mut Arena, - locals: &mut Arena, - locals_map: &mut FastHashMap>, - parameter_lookup: &FastHashMap, - ) -> Expression { - match expr { - Expr::Variable(ident) => { - let name = ident.0; - - match name.as_str() { - "gl_VertexIndex" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 32, - }, - }), - })) - } - "gl_InstanceIndex" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::InstanceIndex)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 32, - }, - }), - })) - } - "gl_DrawID" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::DrawIndex)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 32, - }, - }), - })) - } - "gl_BaseVertex" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::BaseVertex)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 32, - }, - }), - })) - } - "gl_BaseInstance" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::BaseInstance)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 32, - }, - }), - })) - } - "gl_Position" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: match self.exec_model { - ExecutionModel::Vertex => StorageClass::Output, - ExecutionModel::Fragment => StorageClass::Input, - _ => panic!(), - }, - binding: Some(Binding::BuiltIn(BuiltIn::Position)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 32, - }, - }), - })) - } - "gl_PointSize" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Output, - binding: Some(Binding::BuiltIn(BuiltIn::PointSize)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 32, - }, - }), - })) - } - "gl_ClipDistance" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Output, - binding: Some(Binding::BuiltIn(BuiltIn::ClipDistance)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 32, - }, - }), - })) - } - "gl_CullDistance" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Output, - binding: Some(Binding::BuiltIn(BuiltIn::CullDistance)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 32, - }, - }), - })) - } - other => { - if let Some(global) = self.globals_lookup.get(other) { - match *global { - Global::Variable(handle) => Expression::GlobalVariable(handle), - Global::StructShorthand(struct_handle, index) => { - Expression::AccessIndex { - base: expressions - .append(Expression::GlobalVariable(struct_handle)), - index, - } - } - } - } else if let Some(expr) = parameter_lookup.get(other) { - expr.clone() - } else if let Some(local) = locals_map.get(other) { - Expression::LocalVariable(*local) - } else { - println!("{}", other); - panic!() - } - } - } - } - Expr::IntConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Sint(value as i64), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 32, - }, - }), - })) - } - Expr::UIntConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Uint(value as u64), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 32, - }, - }), - })) - } - Expr::BoolConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Bool(value), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Bool, - width: 1, - }, - }), - })) - } - Expr::FloatConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Float(value as f64), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 32, - }, - }), - })) - } - Expr::DoubleConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Float(value), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 64, - }, - }), - })) - } - Expr::Unary(_op, _reg) => unimplemented!(), - Expr::Binary(op, left, right) => { - let left = - self.parse_expression(*left, expressions, locals, locals_map, parameter_lookup); - let right = self.parse_expression( - *right, - expressions, - locals, - locals_map, - parameter_lookup, - ); - - Expression::Binary { - op: helpers::glsl_to_spirv_binary_op(op), - left: expressions.append(left), - right: expressions.append(right), - } - } - Expr::Ternary(_condition, _accept, _reject) => unimplemented!(), - Expr::Assignment(_, _, _) => panic!(), - Expr::Bracket(_reg, _index) => unimplemented!(), - Expr::FunCall(ident, mut args) => { - let name = match ident { - FunIdentifier::Identifier(ident) => ident.0, - FunIdentifier::Expr(_expr) => todo!(), - }; - - match name.as_str() { - "vec2" | "vec3" | "vec4" => Expression::Compose { - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: match name.chars().last().unwrap() { - '2' => VectorSize::Bi, - '3' => VectorSize::Tri, - '4' => VectorSize::Quad, - _ => panic!(), - }, - kind: ScalarKind::Float, - width: 32, - }, - }), - components: args - .into_iter() - .map(|arg| { - let expr = self.parse_expression( - arg, - expressions, - locals, - locals_map, - parameter_lookup, - ); - expressions.append(expr) - }) - .collect(), - }, - "texture" => { - let (image, sampler) = - if let Expr::FunCall(ident, mut sample_args) = args.remove(0) { - let name = match ident { - FunIdentifier::Expr(_) => unimplemented!(), - FunIdentifier::Identifier(ident) => ident.0, - }; - - match name.as_str() { - "sampler2D" => ( - self.parse_expression( - sample_args.remove(0), - expressions, - locals, - locals_map, - parameter_lookup, - ), - self.parse_expression( - sample_args.remove(0), - expressions, - locals, - locals_map, - parameter_lookup, - ), - ), - _ => unimplemented!(), - } - } else { - panic!() - }; - - let coordinate = self.parse_expression( - args.remove(0), - expressions, - locals, - locals_map, - parameter_lookup, - ); - - Expression::ImageSample { - image: expressions.append(image), - sampler: expressions.append(sampler), - coordinate: expressions.append(coordinate), - } - } - _ => Expression::Call { - name, - arguments: args - .into_iter() - .map(|arg| { - let expr = self.parse_expression( - arg, - expressions, - locals, - locals_map, - parameter_lookup, - ); - expressions.append(expr) - }) - .collect(), - }, - } - } - Expr::Dot(reg, ident) => { - let handle = { - let expr = self.parse_expression( - *reg, - expressions, - locals, - locals_map, - parameter_lookup, - ); - expressions.append(expr) - }; - - let mut typefier = crate::proc::Typifier::new(); - let name = ident.0.as_str(); - let type_handle = typefier - .resolve( - handle, - expressions, - &mut self.types, - &self.constants, - &self.globals, - locals, - &self.functions, - &self.function_lookup, - ) - .unwrap(); - let base_type = &self.types[type_handle]; - match base_type.inner { - crate::TypeInner::Struct { ref members } => { - let index = members - .iter() - .position(|m| m.name.as_deref() == Some(name)) - .unwrap() as u32; - crate::Expression::AccessIndex { - base: handle, - index, - } - } - crate::TypeInner::Vector { size, kind, width } - | crate::TypeInner::Matrix { - columns: size, - kind, - width, - .. - } => { - const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; - if name.len() > 1 { - let mut components = Vec::with_capacity(name.len()); - - for ch in name.chars() { - let expr = crate::Expression::AccessIndex { - base: handle, - index: MEMBERS[..size as usize] - .iter() - .position(|&m| m == ch) - .unwrap() as u32, - }; - components.push(expressions.append(expr)); - } - let size = match name.len() { - 2 => crate::VectorSize::Bi, - 3 => crate::VectorSize::Tri, - 4 => crate::VectorSize::Quad, - _ => panic!(), - }; - let inner = - if let crate::TypeInner::Matrix { rows, .. } = base_type.inner { - crate::TypeInner::Matrix { - columns: size, - rows, - kind, - width, - } - } else { - crate::TypeInner::Vector { size, kind, width } - }; - crate::Expression::Compose { - ty: crate::proc::Typifier::deduce_type_handle( - inner, - &mut self.types, - ), - components, - } - } else { - let ch = name.chars().next().unwrap(); - let index = MEMBERS[..size as usize] - .iter() - .position(|&m| m == ch) - .unwrap() as u32; - crate::Expression::AccessIndex { - base: handle, - index, - } - } - } - _ => panic!(), - } - } - Expr::PostInc(_reg) => unimplemented!(), - Expr::PostDec(_reg) => unimplemented!(), - Expr::Comma(_, _) => unimplemented!(), - } - } - - // None = void - fn parse_type(&mut self, ty: TypeSpecifier) -> Option> { - let base_ty = helpers::glsl_to_spirv_type(ty.ty, &mut self.types)?; - - let ty = if let Some(specifier) = ty.array_specifier { - let handle = self.types.fetch_or_append(Type { - name: None, - inner: base_ty, - }); - - match specifier { - ArraySpecifier::Unsized => TypeInner::Array { - base: handle, - size: ArraySize::Dynamic, - }, - ArraySpecifier::ExplicitlySized(_) => unimplemented!(), - } - } else { - base_ty - }; - - Some(self.types.fetch_or_append(Type { - name: None, - inner: ty, - })) - } - - fn parse_global(&mut self, init: InitDeclaratorList) -> Handle { - let name = init.head.name.map(|d| d.0); - let ty = { - let ty = self.parse_type(init.head.ty.ty).unwrap(); - - if let Some(specifier) = init.head.array_specifier { - match specifier { - ArraySpecifier::Unsized => self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size: ArraySize::Dynamic, - }, - }), - ArraySpecifier::ExplicitlySized(_) => unimplemented!(), - } - } else { - ty - } - }; - - let (class, binding) = init - .head - .ty - .qualifier - .map(Self::parse_type_qualifier) - .unwrap_or((StorageClass::Private, None)); - - self.globals.append(GlobalVariable { - name, - class, - binding, - ty, - }) - } - - fn parse_type_qualifier(qualifier: TypeQualifier) -> (StorageClass, Option) { - let mut storage = None; - let mut binding = None; - - for qualifier in qualifier.qualifiers { - match qualifier { - TypeQualifierSpec::Storage(storage_qualifier) => { - assert!(storage.is_none()); - - match storage_qualifier { - StorageQualifier::Const => storage = Some(StorageClass::UniformConstant), - StorageQualifier::In => storage = Some(StorageClass::Input), - StorageQualifier::Out => storage = Some(StorageClass::Output), - StorageQualifier::Uniform => storage = Some(StorageClass::Uniform), - StorageQualifier::Buffer => storage = Some(StorageClass::StorageBuffer), - StorageQualifier::Shared => storage = Some(StorageClass::Workgroup), - StorageQualifier::Coherent => storage = Some(StorageClass::Workgroup), - _ => panic!(), - } - } - TypeQualifierSpec::Layout(layout_qualifier) => { - assert!(binding.is_none()); - - let mut set = None; - let mut bind = None; - let mut location = None; - - for identifier in layout_qualifier.ids { - match identifier { - LayoutQualifierSpec::Identifier(identifier, Some(expr)) => { - if let Expr::IntConst(word) = *expr { - match identifier.as_str() { - "location" => { - assert!(set.is_none(),); - assert!(bind.is_none(),); - assert!(location.is_none()); - - location = Some(word); - } - "binding" => { - assert!(bind.is_none(),); - assert!(location.is_none()); - - bind = Some(word); - } - "set" => { - assert!(set.is_none(),); - assert!(location.is_none()); - - set = Some(word); - } - _ => {} - } - } - } - _ => unimplemented!(), - } - } - - if let (Some(set), Some(bind)) = (set, bind) { - binding = Some(Binding::Descriptor { - set: set as u32, - binding: bind as u32, - }) - } else if let Some(location) = location { - binding = Some(Binding::Location(location as u32)) - } else { - panic!() - } - } - _ => unimplemented!(), - } - } - - (storage.unwrap_or(StorageClass::Private), binding) - } -} - -pub fn parse_str( - source: &str, - entry: String, - exec: ExecutionModel, -) -> Result { - let input = parser::parse(source).unwrap(); - - log::debug!("------GLSL PREPROCESSOR------"); - log::debug!("\n{}", input); - log::debug!("-----------------------------"); - - Parser::new(&input, exec)?.parse(entry) -} - -#[cfg(test)] -mod tests { - use super::parse_str; - - #[test] - fn test_vertex() { - let data = include_str!("../../../test-data/glsl_vertex_test_shader.vert"); - - println!( - "{:#?}", - parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) - ); - } - - #[test] - fn test_frag() { - let _ = env_logger::try_init(); - - let data = include_str!("../../../test-data/glsl_phong_lighting.frag"); - - println!( - "{:#?}", - parse_str(data, String::from("main"), spirv::ExecutionModel::Fragment) - ); - } - - #[cfg(feature = "glsl_preprocessor")] - #[test] - fn test_preprocess() { - let _ = env_logger::try_init(); - - let data = include_str!("../../../test-data/glsl_preprocessor_abuse.vert"); - - println!( - "{:#?}", - parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) - ); - } - - #[cfg(feature = "glsl_preprocessor")] - #[test] - #[should_panic] - fn test_preprocess_ifs() { - let _ = env_logger::try_init(); - - let data = include_str!("../../../test-data/glsl_if_preprocessor.vert"); - - println!( - "{:#?}", - parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) - ); - } -} +use crate::{ + Arena, ArraySize, BinaryOperator, Binding, Constant, ConstantInner, EntryPoint, Expression, + FastHashMap, Function, GlobalVariable, Handle, Header, LocalVariable, Module, ScalarKind, + StructMember, Type, TypeInner, VectorSize, +}; +use glsl::{ + parser::{Parse, ParseError}, + syntax::*, +}; +use parser::{Token, TokenMetadata}; +use spirv::{BuiltIn, ExecutionModel, StorageClass}; +use std::fmt; + +mod helpers; +mod parser; + +#[derive(Debug)] +pub enum ErrorKind { + UnexpectedToken { + expected: Vec, + got: TokenMetadata, + }, + UnexpectedWord { + expected: Vec<&'static str>, + got: String, + }, + ExpectedEOL { + got: TokenMetadata, + }, + UnknownPragma { + pragma: String, + }, + ExtensionNotSupported { + extension: String, + }, + AllExtensionsEnabled, + ExtensionUnknownBehavior { + behavior: String, + }, + UnsupportedVersion { + version: usize, + }, + UnsupportedProfile { + profile: String, + }, + UnknownProfile { + profile: String, + }, + UnknownPreprocessorDirective { + directive: String, + }, + UnboundedIfCloserOrVariant { + token: TokenMetadata, + }, + NonIntegralType { + token: TokenMetadata, + }, + ReservedMacro, + EOL, + EOF, +} + +impl fmt::Display for ErrorKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ErrorKind::UnexpectedToken { expected, got } => write!( + f, + "Unexpected token:\nexpected: {}\ngot: {}", + expected + .iter() + .map(|token| { + let mut type_string = token.type_to_string(); + type_string.push_str(" |"); + type_string + }) + .collect::(), + got.token + ), + ErrorKind::UnexpectedWord { expected, got } => write!( + f, + "Unexpected word:\nexpected: {}\ngot: {}", + expected.iter().fold(String::new(), |mut acc, word| { + acc.push_str(*word); + + acc.push_str("|"); + + acc + }), + got + ), + ErrorKind::ExpectedEOL { got } => { + write!(f, "Expected end of line:\ngot: {}", got.token) + } + ErrorKind::UnknownPragma { pragma } => write!(f, "Unknown pragma: {}", pragma), + ErrorKind::ExtensionNotSupported { extension } => { + write!(f, "The extension \"{}\" is not supported", extension) + } + ErrorKind::AllExtensionsEnabled => { + write!(f, "All extensions can't be require or enable") + } + ErrorKind::ExtensionUnknownBehavior { behavior } => write!( + f, + "The extension behavior must be one of require|enable|warn|disable got: {}", + behavior + ), + ErrorKind::UnsupportedVersion { version } => write!( + f, + "The version {} isn't supported use either 450 or 460", + version + ), + ErrorKind::UnsupportedProfile { profile } => { + write!(f, "The profile {} isn't supported use core", profile) + } + ErrorKind::UnknownProfile { profile } => { + write!(f, "The profile {} isn't defined use core", profile) + } + ErrorKind::UnknownPreprocessorDirective { directive } => { + write!(f, "The preprocessor directive {} isn't defined", directive) + } + ErrorKind::UnboundedIfCloserOrVariant { token } => { + write!(f, "The preprocessor directives \"else\", \"elif\" or \"endif\" must be preceded by an \"if\", token: {}", token.token) + } + ErrorKind::NonIntegralType { token } => { + write!(f, "The preprocessor \"if\" directive can only contain integrals found: {}", token.token) + } + ErrorKind::ReservedMacro => write!(f, "Macro can't begin with GL_"), + ErrorKind::EOL => write!(f, "End of line"), + ErrorKind::EOF => write!(f, "End of file"), + } + } +} + +#[derive(Debug)] +pub struct Error { + pub kind: ErrorKind, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self) + } +} + +impl std::error::Error for Error {} + +#[derive(Debug, Copy, Clone)] +enum Global { + Variable(Handle), + StructShorthand(Handle, u32), +} + +struct Parser<'a> { + source: &'a str, + types: Arena, + globals: Arena, + globals_lookup: FastHashMap, + constants: Arena, + functions: Arena, + function_lookup: FastHashMap>, + exec_model: ExecutionModel, +} + +impl<'a> Parser<'a> { + pub fn new(source: &'a str, exec_model: ExecutionModel) -> Result { + Ok(Self { + source, + types: Arena::new(), + globals: Arena::new(), + globals_lookup: FastHashMap::default(), + constants: Arena::new(), + functions: Arena::new(), + function_lookup: FastHashMap::default(), + exec_model, + }) + } + + pub fn parse(mut self, entry: String) -> Result { + let ast = TranslationUnit::parse(self.source)?; + + //println!("{:#?}", ast); + + let mut entry_point = None; + + for declaration in ast { + match declaration { + ExternalDeclaration::Preprocessor(_) => + { + #[cfg(feature = "glsl_preprocessor")] + unreachable!() + } + ExternalDeclaration::FunctionDefinition(function) => { + let function = self.parse_function_definition(function); + + if *self.functions[function].name.as_ref().unwrap() == entry { + assert!(entry_point.is_none()); + + entry_point = Some(function); + } + } + ExternalDeclaration::Declaration(decl) => match decl { + Declaration::InitDeclaratorList(init) => { + let handle = self.parse_global(init); + let name = self.globals[handle].name.clone().unwrap(); + self.globals_lookup.insert(name, Global::Variable(handle)); + } + Declaration::Block(block) => { + let (class, binding) = Self::parse_type_qualifier(block.qualifier); + let ty_name = block.name.0; + + let name = block.identifier.clone().map(|ident| ident.ident.0); + + let mut fields = Vec::new(); + let mut reexports = Vec::new(); + let mut index = 0; + + for field in block.fields { + let binding = field + .qualifier + .and_then(|qualifier| Self::parse_type_qualifier(qualifier).1); + + let ty = self.parse_type(field.ty).unwrap(); + + for ident in field.identifiers { + let field_name = ident.ident.0; + + fields.push(StructMember { + name: Some(field_name.clone()), + binding: binding.clone(), + ty: if let Some(array_spec) = ident.array_spec { + self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size: match array_spec { + ArraySpecifier::Unsized => ArraySize::Dynamic, + ArraySpecifier::ExplicitlySized(_expr) => { + unimplemented!() + } + }, + }, + }) + } else { + ty + }, + }); + + if name.is_none() { + reexports.push((field_name, index)); + index += 1; + } + } + } + + let ty = if let Some(array_spec) = + block.identifier.and_then(|ident| ident.array_spec) + { + let base = self.types.fetch_or_append(Type { + name: Some(ty_name), + inner: TypeInner::Struct { members: fields }, + }); + + self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base, + size: match array_spec { + ArraySpecifier::Unsized => ArraySize::Dynamic, + ArraySpecifier::ExplicitlySized(_expr) => unimplemented!(), + }, + }, + }) + } else { + self.types.fetch_or_append(Type { + name: Some(ty_name), + inner: TypeInner::Struct { members: fields }, + }) + }; + + let handle = self.globals.append(GlobalVariable { + binding, + class, + name, + ty, + }); + + for (name, index) in reexports { + self.globals_lookup + .insert(name, Global::StructShorthand(handle, index)); + } + } + _ => unimplemented!(), + }, + } + } + + Ok(Module { + header: Header { + version: (1, 0, 0), + generator: 0, + }, + types: self.types, + constants: self.constants, + global_variables: self.globals, + functions: self.functions, + entry_points: vec![EntryPoint { + exec_model: self.exec_model, + function: entry_point.unwrap(), + name: entry, + }], + }) + } + + fn parse_function_definition(&mut self, function: FunctionDefinition) -> Handle { + let name = function.prototype.name.0; + + // Parse return type + let ty = self.parse_type(function.prototype.ty.ty); + + let mut parameter_types = Vec::with_capacity(function.prototype.parameters.len()); + let mut parameter_lookup = FastHashMap::default(); + + let mut local_variables = Arena::::new(); + let mut locals_map = FastHashMap::default(); + let mut expressions = Arena::::new(); + let mut body = Vec::new(); + + // TODO: Parse Qualifiers + for (index, parameter) in function.prototype.parameters.into_iter().enumerate() { + match parameter { + FunctionParameterDeclaration::Named(_ /* TODO */, decl) => { + let ty = self.parse_type(decl.ty).unwrap(); + + let ty = if let Some(specifier) = decl.ident.array_spec { + match specifier { + ArraySpecifier::Unsized => self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size: ArraySize::Dynamic, + }, + }), + ArraySpecifier::ExplicitlySized(_) => unimplemented!(), + } + } else { + ty + }; + + parameter_types.push(ty); + parameter_lookup.insert( + decl.ident.ident.0, + Expression::FunctionParameter(index as u32), + ); + } + FunctionParameterDeclaration::Unnamed(_, ty) => { + parameter_types.push(self.parse_type(ty).unwrap()); + } + } + } + + for statement in function.statement.statement_list { + match statement { + Statement::Compound(_) => unimplemented!(), + Statement::Simple(statement) => match *statement { + SimpleStatement::Declaration(declaration) => match declaration { + Declaration::InitDeclaratorList(init) => { + self.parse_local_variable( + init, + &mut expressions, + &mut local_variables, + &mut locals_map, + ¶meter_lookup, + ); + } + _ => unimplemented!(), + }, + SimpleStatement::Expression(expr) => { + let expr = match expr { + Some(expr) => expr, + None => continue, + }; + + body.push(self.parse_statement( + expr, + &mut expressions, + &mut local_variables, + &mut locals_map, + ¶meter_lookup, + )); + } + SimpleStatement::Selection(_) => unimplemented!(), + SimpleStatement::Switch(_) => unimplemented!(), + SimpleStatement::CaseLabel(_) => unimplemented!(), + SimpleStatement::Iteration(_) => unimplemented!(), + SimpleStatement::Jump(op) => body.push(match op { + JumpStatement::Continue => crate::Statement::Continue, + JumpStatement::Break => crate::Statement::Break, + JumpStatement::Return(expr) => crate::Statement::Return { + value: expr.map(|expr| { + let expr = self.parse_expression( + *expr, + &mut expressions, + &mut local_variables, + &mut locals_map, + ¶meter_lookup, + ); + expressions.append(expr) + }), + }, + JumpStatement::Discard => crate::Statement::Kill, + }), + }, + } + } + + let handle = self.functions.append(Function { + name: Some(name.clone()), + control: spirv::FunctionControl::NONE, + parameter_types, + return_type: ty, + global_usage: vec![], + local_variables, + expressions, + body, + }); + + self.function_lookup.insert(name, handle); + + handle + } + + fn parse_local_variable( + &mut self, + init: InitDeclaratorList, + expressions: &mut Arena, + locals: &mut Arena, + locals_map: &mut FastHashMap>, + parameter_lookup: &FastHashMap, + ) -> Handle { + let name = init.head.name.map(|d| d.0); + let ty = { + let ty = self.parse_type(init.head.ty.ty).unwrap(); + + if let Some(specifier) = init.head.array_specifier { + match specifier { + ArraySpecifier::Unsized => self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size: ArraySize::Dynamic, + }, + }), + ArraySpecifier::ExplicitlySized(_) => unimplemented!(), + } + } else { + ty + } + }; + + let initializer = init.head.initializer.map(|initializer| { + self.parse_initializer( + initializer, + expressions, + locals, + locals_map, + parameter_lookup, + ) + }); + + let handle = locals.append(LocalVariable { + name: name.clone(), + ty, + init: initializer, + }); + + locals_map.insert(name.unwrap(), handle); + + handle + } + + fn parse_initializer( + &mut self, + initializer: Initializer, + expressions: &mut Arena, + locals: &mut Arena, + locals_map: &mut FastHashMap>, + parameter_lookup: &FastHashMap, + ) -> Handle { + match initializer { + Initializer::Simple(expr) => { + let handle = + self.parse_expression(*expr, expressions, locals, locals_map, parameter_lookup); + + expressions.append(handle) + } + Initializer::List(_exprs) => unimplemented!(), + } + } + + fn parse_statement( + &mut self, + expr: Expr, + expressions: &mut Arena, + locals: &mut Arena, + locals_map: &mut FastHashMap>, + parameter_lookup: &FastHashMap, + ) -> crate::Statement { + match expr { + Expr::Assignment(reg, op, value) => { + let pointer = { + let pointer = self.parse_expression( + *reg, + expressions, + locals, + locals_map, + parameter_lookup, + ); + expressions.append(pointer) + }; + + let right = self.parse_expression( + *value, + expressions, + locals, + locals_map, + parameter_lookup, + ); + let value = match op { + AssignmentOp::Equal => right, + AssignmentOp::Mult => Expression::Binary { + op: BinaryOperator::Multiply, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Div => Expression::Binary { + op: BinaryOperator::Divide, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Mod => Expression::Binary { + op: BinaryOperator::Modulo, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Add => Expression::Binary { + op: BinaryOperator::Add, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Sub => Expression::Binary { + op: BinaryOperator::Subtract, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::LShift => Expression::Binary { + op: BinaryOperator::ShiftLeftLogical, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::RShift => { + Expression::Binary { + op: BinaryOperator::ShiftRightArithmetic, /* ??? */ + left: pointer, + right: expressions.append(right), + } + } + AssignmentOp::And => Expression::Binary { + op: BinaryOperator::And, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Xor => Expression::Binary { + op: BinaryOperator::ExclusiveOr, + left: pointer, + right: expressions.append(right), + }, + AssignmentOp::Or => Expression::Binary { + op: BinaryOperator::InclusiveOr, + left: pointer, + right: expressions.append(right), + }, + }; + + crate::Statement::Store { + pointer, + value: expressions.append(value), + } + } + Expr::FunCall(_, _) => unimplemented!(), + Expr::PostInc(_) => unimplemented!(), + Expr::PostDec(_) => unimplemented!(), + _ => panic!(), + } + } + + fn parse_expression( + &mut self, + expr: Expr, + expressions: &mut Arena, + locals: &mut Arena, + locals_map: &mut FastHashMap>, + parameter_lookup: &FastHashMap, + ) -> Expression { + match expr { + Expr::Variable(ident) => { + let name = ident.0; + + match name.as_str() { + "gl_VertexIndex" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_InstanceIndex" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::InstanceIndex)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_DrawID" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::DrawIndex)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_BaseVertex" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::BaseVertex)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_BaseInstance" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::BaseInstance)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + "gl_Position" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: match self.exec_model { + ExecutionModel::Vertex => StorageClass::Output, + ExecutionModel::Fragment => StorageClass::Input, + _ => panic!(), + }, + binding: Some(Binding::BuiltIn(BuiltIn::Position)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + "gl_PointSize" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Output, + binding: Some(Binding::BuiltIn(BuiltIn::PointSize)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + "gl_ClipDistance" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Output, + binding: Some(Binding::BuiltIn(BuiltIn::ClipDistance)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + "gl_CullDistance" => { + Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + name: Some(name), + class: StorageClass::Output, + binding: Some(Binding::BuiltIn(BuiltIn::CullDistance)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + other => { + if let Some(global) = self.globals_lookup.get(other) { + match *global { + Global::Variable(handle) => Expression::GlobalVariable(handle), + Global::StructShorthand(struct_handle, index) => { + Expression::AccessIndex { + base: expressions + .append(Expression::GlobalVariable(struct_handle)), + index, + } + } + } + } else if let Some(expr) = parameter_lookup.get(other) { + expr.clone() + } else if let Some(local) = locals_map.get(other) { + Expression::LocalVariable(*local) + } else { + println!("{}", other); + panic!() + } + } + } + } + Expr::IntConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Sint(value as i64), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 32, + }, + }), + })) + } + Expr::UIntConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Uint(value as u64), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 32, + }, + }), + })) + } + Expr::BoolConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Bool(value), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Bool, + width: 1, + }, + }), + })) + } + Expr::FloatConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Float(value as f64), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 32, + }, + }), + })) + } + Expr::DoubleConst(value) => { + Expression::Constant(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Float(value), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 64, + }, + }), + })) + } + Expr::Unary(_op, _reg) => unimplemented!(), + Expr::Binary(op, left, right) => { + let left = + self.parse_expression(*left, expressions, locals, locals_map, parameter_lookup); + let right = self.parse_expression( + *right, + expressions, + locals, + locals_map, + parameter_lookup, + ); + + Expression::Binary { + op: helpers::glsl_to_spirv_binary_op(op), + left: expressions.append(left), + right: expressions.append(right), + } + } + Expr::Ternary(_condition, _accept, _reject) => unimplemented!(), + Expr::Assignment(_, _, _) => panic!(), + Expr::Bracket(_reg, _index) => unimplemented!(), + Expr::FunCall(ident, mut args) => { + let name = match ident { + FunIdentifier::Identifier(ident) => ident.0, + FunIdentifier::Expr(_expr) => todo!(), + }; + + match name.as_str() { + "vec2" | "vec3" | "vec4" => Expression::Compose { + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: match name.chars().last().unwrap() { + '2' => VectorSize::Bi, + '3' => VectorSize::Tri, + '4' => VectorSize::Quad, + _ => panic!(), + }, + kind: ScalarKind::Float, + width: 32, + }, + }), + components: args + .into_iter() + .map(|arg| { + let expr = self.parse_expression( + arg, + expressions, + locals, + locals_map, + parameter_lookup, + ); + expressions.append(expr) + }) + .collect(), + }, + "texture" => { + let (image, sampler) = + if let Expr::FunCall(ident, mut sample_args) = args.remove(0) { + let name = match ident { + FunIdentifier::Expr(_) => unimplemented!(), + FunIdentifier::Identifier(ident) => ident.0, + }; + + match name.as_str() { + "sampler2D" => ( + self.parse_expression( + sample_args.remove(0), + expressions, + locals, + locals_map, + parameter_lookup, + ), + self.parse_expression( + sample_args.remove(0), + expressions, + locals, + locals_map, + parameter_lookup, + ), + ), + _ => unimplemented!(), + } + } else { + panic!() + }; + + let coordinate = self.parse_expression( + args.remove(0), + expressions, + locals, + locals_map, + parameter_lookup, + ); + + Expression::ImageSample { + image: expressions.append(image), + sampler: expressions.append(sampler), + coordinate: expressions.append(coordinate), + } + } + _ => Expression::Call { + name, + arguments: args + .into_iter() + .map(|arg| { + let expr = self.parse_expression( + arg, + expressions, + locals, + locals_map, + parameter_lookup, + ); + expressions.append(expr) + }) + .collect(), + }, + } + } + Expr::Dot(reg, ident) => { + let handle = { + let expr = self.parse_expression( + *reg, + expressions, + locals, + locals_map, + parameter_lookup, + ); + expressions.append(expr) + }; + + let mut typefier = crate::proc::Typifier::new(); + let name = ident.0.as_str(); + let type_handle = typefier + .resolve( + handle, + expressions, + &mut self.types, + &self.constants, + &self.globals, + locals, + &self.functions, + &self.function_lookup, + ) + .unwrap(); + let base_type = &self.types[type_handle]; + match base_type.inner { + crate::TypeInner::Struct { ref members } => { + let index = members + .iter() + .position(|m| m.name.as_deref() == Some(name)) + .unwrap() as u32; + crate::Expression::AccessIndex { + base: handle, + index, + } + } + crate::TypeInner::Vector { size, kind, width } + | crate::TypeInner::Matrix { + columns: size, + kind, + width, + .. + } => { + const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; + if name.len() > 1 { + let mut components = Vec::with_capacity(name.len()); + + for ch in name.chars() { + let expr = crate::Expression::AccessIndex { + base: handle, + index: MEMBERS[..size as usize] + .iter() + .position(|&m| m == ch) + .unwrap() as u32, + }; + components.push(expressions.append(expr)); + } + let size = match name.len() { + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + 4 => crate::VectorSize::Quad, + _ => panic!(), + }; + let inner = + if let crate::TypeInner::Matrix { rows, .. } = base_type.inner { + crate::TypeInner::Matrix { + columns: size, + rows, + kind, + width, + } + } else { + crate::TypeInner::Vector { size, kind, width } + }; + crate::Expression::Compose { + ty: crate::proc::Typifier::deduce_type_handle( + inner, + &mut self.types, + ), + components, + } + } else { + let ch = name.chars().next().unwrap(); + let index = MEMBERS[..size as usize] + .iter() + .position(|&m| m == ch) + .unwrap() as u32; + crate::Expression::AccessIndex { + base: handle, + index, + } + } + } + _ => panic!(), + } + } + Expr::PostInc(_reg) => unimplemented!(), + Expr::PostDec(_reg) => unimplemented!(), + Expr::Comma(_, _) => unimplemented!(), + } + } + + // None = void + fn parse_type(&mut self, ty: TypeSpecifier) -> Option> { + let base_ty = helpers::glsl_to_spirv_type(ty.ty, &mut self.types)?; + + let ty = if let Some(specifier) = ty.array_specifier { + let handle = self.types.fetch_or_append(Type { + name: None, + inner: base_ty, + }); + + match specifier { + ArraySpecifier::Unsized => TypeInner::Array { + base: handle, + size: ArraySize::Dynamic, + }, + ArraySpecifier::ExplicitlySized(_) => unimplemented!(), + } + } else { + base_ty + }; + + Some(self.types.fetch_or_append(Type { + name: None, + inner: ty, + })) + } + + fn parse_global(&mut self, init: InitDeclaratorList) -> Handle { + let name = init.head.name.map(|d| d.0); + let ty = { + let ty = self.parse_type(init.head.ty.ty).unwrap(); + + if let Some(specifier) = init.head.array_specifier { + match specifier { + ArraySpecifier::Unsized => self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size: ArraySize::Dynamic, + }, + }), + ArraySpecifier::ExplicitlySized(_) => unimplemented!(), + } + } else { + ty + } + }; + + let (class, binding) = init + .head + .ty + .qualifier + .map(Self::parse_type_qualifier) + .unwrap_or((StorageClass::Private, None)); + + self.globals.append(GlobalVariable { + name, + class, + binding, + ty, + }) + } + + fn parse_type_qualifier(qualifier: TypeQualifier) -> (StorageClass, Option) { + let mut storage = None; + let mut binding = None; + + for qualifier in qualifier.qualifiers { + match qualifier { + TypeQualifierSpec::Storage(storage_qualifier) => { + assert!(storage.is_none()); + + match storage_qualifier { + StorageQualifier::Const => storage = Some(StorageClass::UniformConstant), + StorageQualifier::In => storage = Some(StorageClass::Input), + StorageQualifier::Out => storage = Some(StorageClass::Output), + StorageQualifier::Uniform => storage = Some(StorageClass::Uniform), + StorageQualifier::Buffer => storage = Some(StorageClass::StorageBuffer), + StorageQualifier::Shared => storage = Some(StorageClass::Workgroup), + StorageQualifier::Coherent => storage = Some(StorageClass::Workgroup), + _ => panic!(), + } + } + TypeQualifierSpec::Layout(layout_qualifier) => { + assert!(binding.is_none()); + + let mut set = None; + let mut bind = None; + let mut location = None; + + for identifier in layout_qualifier.ids { + match identifier { + LayoutQualifierSpec::Identifier(identifier, Some(expr)) => { + if let Expr::IntConst(word) = *expr { + match identifier.as_str() { + "location" => { + assert!(set.is_none(),); + assert!(bind.is_none(),); + assert!(location.is_none()); + + location = Some(word); + } + "binding" => { + assert!(bind.is_none(),); + assert!(location.is_none()); + + bind = Some(word); + } + "set" => { + assert!(set.is_none(),); + assert!(location.is_none()); + + set = Some(word); + } + _ => {} + } + } + } + _ => unimplemented!(), + } + } + + if let (Some(set), Some(bind)) = (set, bind) { + binding = Some(Binding::Descriptor { + set: set as u32, + binding: bind as u32, + }) + } else if let Some(location) = location { + binding = Some(Binding::Location(location as u32)) + } else { + panic!() + } + } + _ => unimplemented!(), + } + } + + (storage.unwrap_or(StorageClass::Private), binding) + } +} + +pub fn parse_str( + source: &str, + entry: String, + exec: ExecutionModel, +) -> Result { + let input = parser::parse(source).unwrap(); + + log::debug!("------GLSL PREPROCESSOR------"); + log::debug!("\n{}", input); + log::debug!("-----------------------------"); + + Parser::new(&input, exec)?.parse(entry) +} + +#[cfg(test)] +mod tests { + use super::parse_str; + + #[test] + fn test_vertex() { + let data = include_str!("../../../test-data/glsl_vertex_test_shader.vert"); + + println!( + "{:#?}", + parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) + ); + } + + #[test] + fn test_frag() { + let _ = env_logger::try_init(); + + let data = include_str!("../../../test-data/glsl_phong_lighting.frag"); + + println!( + "{:#?}", + parse_str(data, String::from("main"), spirv::ExecutionModel::Fragment) + ); + } + + #[cfg(feature = "glsl_preprocessor")] + #[test] + fn test_preprocess() { + let _ = env_logger::try_init(); + + let data = include_str!("../../../test-data/glsl_preprocessor_abuse.vert"); + + println!( + "{:#?}", + parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) + ); + } + + #[cfg(feature = "glsl_preprocessor")] + #[test] + #[should_panic] + fn test_preprocess_ifs() { + let _ = env_logger::try_init(); + + let data = include_str!("../../../test-data/glsl_if_preprocessor.vert"); + + println!( + "{:#?}", + parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) + ); + } +} diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0b0332313..f0a9503b4 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,246 +1,246 @@ -#![allow(clippy::all)] -#![allow(dead_code)] - -use super::{Error, ErrorKind}; -use crate::FastHashMap; -use std::{ - fmt, - iter::Peekable, - ops::{Deref, Range}, - vec::IntoIter, -}; - -pub mod lex; - -#[cfg(feature = "glsl_preprocessor")] -#[path = "./preprocessor.rs"] -pub mod preprocessor; - -type Tokens = Peekable>; - -#[derive(Debug, Clone)] -pub struct TokenMetadata { - pub token: Token, - pub line: usize, - pub chars: Range, -} - -impl Deref for TokenMetadata { - type Target = Token; - - fn deref(&self) -> &Token { - &self.token - } -} - -#[derive(Debug, PartialEq, Clone)] -pub enum Token { - Separator(char), - DoubleColon, - Paren(char), - Integral(usize), - Float(f32), - Double(f64), - Word(String), - Operation(char), - OpAssign(char), - LogicalOperation(char), - ShiftOperation(char), - Unknown(char), - LineComment, - MultiLineCommentOpen, - MultiLineCommentClose, - Preprocessor, - End, - Selection, - Sufix(char), - TokenPasting, -} - -impl Token { - pub fn type_to_string(&self) -> String { - match self { - Token::Separator(separator) => separator.to_string(), - Token::DoubleColon => ":".to_string(), - Token::Paren(paren) => paren.to_string(), - Token::Integral(_) => "integer".to_string(), - Token::Float(_) => "float".to_string(), - Token::Double(_) => "double".to_string(), - Token::Word(_) => "word".to_string(), - Token::Operation(op) => op.to_string(), - Token::OpAssign(op) => format!("{}=", op), - Token::LogicalOperation(op) => format!("{}=", op), - Token::ShiftOperation(op) => format!("{0}{0}", op), - Token::Unknown(_) => "unknown".to_string(), - Token::LineComment => "//".to_string(), - Token::MultiLineCommentOpen => "/*".to_string(), - Token::MultiLineCommentClose => "*/".to_string(), - Token::Preprocessor => "#".to_string(), - Token::End => "EOF".to_string(), - Token::Selection => "?".to_string(), - Token::Sufix(op) => format!("{0}{0}", op), - Token::TokenPasting => "##".to_string(), - } - } -} - -impl fmt::Display for Token { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Token::Separator(sep) => write!(f, "{}", sep), - Token::DoubleColon => write!(f, ":"), - Token::Paren(paren) => write!(f, "{}", paren), - Token::Integral(int) => write!(f, "{}", int), - Token::Float(float) => write!(f, "{}", float), - Token::Double(double) => write!(f, "{}", double), - Token::Word(word) => write!(f, "{}", word), - Token::Operation(op) => write!(f, "{}", op), - Token::OpAssign(op) => write!(f, "{}=", op), - Token::LogicalOperation(op) => write!(f, "{0}=", op), - Token::ShiftOperation(op) => write!(f, "{0}{0}", op), - Token::Unknown(unknown) => write!(f, "{}", unknown), - Token::LineComment => write!(f, "//"), - Token::MultiLineCommentOpen => write!(f, "/*"), - Token::MultiLineCommentClose => write!(f, "*/"), - Token::Preprocessor => write!(f, "#"), - Token::End => write!(f, ""), - Token::Selection => write!(f, "?"), - Token::Sufix(op) => write!(f, "{0}{0}", op), - Token::TokenPasting => write!(f, "##"), - } - } -} - -#[derive(Debug)] -pub enum Node { - Ident(String), - Const(Literal), -} - -#[derive(Debug, Copy, Clone)] -pub enum Literal { - Double(f64), - Float(f32), - Uint(usize), - Sint(isize), - Bool(bool), -} - -fn parse_primary_expression(tokens: &mut Tokens) -> Result { - let token = tokens.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - match token.token { - Token::Word(ident) => Ok(match ident.as_str() { - "true" => Node::Const(Literal::Bool(true)), - "false" => Node::Const(Literal::Bool(false)), - _ => Node::Ident(ident), - }), - Token::Integral(uint) => Ok(Node::Const(Literal::Uint(uint))), - Token::Float(float) => Ok(Node::Const(Literal::Float(float))), - Token::Double(double) => Ok(Node::Const(Literal::Double(double))), - Token::Paren('(') => todo!(), /* parse_expression */ - _ => Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![ - Token::Word(String::new()), - Token::Integral(0), - Token::Double(0.0), - Token::Float(0.0), - Token::Paren('('), - ], - got: token, - }, - }), - } -} - -pub(self) fn parse_comments(mut lexer: lex::Lexer) -> Result, Error> { - let mut tokens = Vec::new(); - - loop { - let token = lexer.next(); - - match token.token { - Token::MultiLineCommentOpen => { - let mut token = lexer.next(); - while Token::MultiLineCommentClose != token.token { - match token.token { - Token::End => { - return Err(Error { - kind: ErrorKind::EOF, - }) - } - _ => {} - } - - token = lexer.next(); - } - } - Token::LineComment => { - while token.line == lexer.peek().line && Token::End != lexer.peek().token { - let _ = lexer.next(); - } - } - Token::End => { - tokens.push(token); - break; - } - _ => tokens.push(token), - } - } - - Ok(tokens) -} - -pub fn parse(input: &str) -> Result { - let lexer = lex::Lexer::new(input); - - let tokens = parse_comments(lexer)?; - - let mut macros = FastHashMap::default(); - - macros.insert( - String::from("GL_SPIRV"), - vec![TokenMetadata { - token: Token::Integral(100), - line: 0, - chars: 0..1, - }], - ); - macros.insert( - String::from("VULKAN"), - vec![TokenMetadata { - token: Token::Integral(100), - line: 0, - chars: 0..1, - }], - ); - - log::trace!("------GLSL COMMENT STRIPPED------"); - log::trace!("\n{:#?}", tokens); - log::trace!("---------------------------------"); - - #[cfg(feature = "glsl_preprocessor")] - let tokens = preprocessor::preprocess(&mut tokens.into_iter().peekable(), &mut macros)?; - - let mut line = 0; - let mut start = 0; - - Ok(tokens.into_iter().fold(String::new(), |mut acc, token| { - if token.line - line != 0 { - acc.push_str(&"\n".repeat(token.line - line)); - start = 0; - line = token.line; - } - - acc.push_str(&" ".repeat(token.chars.start - start)); - - acc.push_str(&token.token.to_string()); - - start = token.chars.end; - - acc - })) -} +#![allow(clippy::all)] +#![allow(dead_code)] + +use super::{Error, ErrorKind}; +use crate::FastHashMap; +use std::{ + fmt, + iter::Peekable, + ops::{Deref, Range}, + vec::IntoIter, +}; + +pub mod lex; + +#[cfg(feature = "glsl_preprocessor")] +#[path = "./preprocessor.rs"] +pub mod preprocessor; + +type Tokens = Peekable>; + +#[derive(Debug, Clone)] +pub struct TokenMetadata { + pub token: Token, + pub line: usize, + pub chars: Range, +} + +impl Deref for TokenMetadata { + type Target = Token; + + fn deref(&self) -> &Token { + &self.token + } +} + +#[derive(Debug, PartialEq, Clone)] +pub enum Token { + Separator(char), + DoubleColon, + Paren(char), + Integral(usize), + Float(f32), + Double(f64), + Word(String), + Operation(char), + OpAssign(char), + LogicalOperation(char), + ShiftOperation(char), + Unknown(char), + LineComment, + MultiLineCommentOpen, + MultiLineCommentClose, + Preprocessor, + End, + Selection, + Sufix(char), + TokenPasting, +} + +impl Token { + pub fn type_to_string(&self) -> String { + match self { + Token::Separator(separator) => separator.to_string(), + Token::DoubleColon => ":".to_string(), + Token::Paren(paren) => paren.to_string(), + Token::Integral(_) => "integer".to_string(), + Token::Float(_) => "float".to_string(), + Token::Double(_) => "double".to_string(), + Token::Word(_) => "word".to_string(), + Token::Operation(op) => op.to_string(), + Token::OpAssign(op) => format!("{}=", op), + Token::LogicalOperation(op) => format!("{}=", op), + Token::ShiftOperation(op) => format!("{0}{0}", op), + Token::Unknown(_) => "unknown".to_string(), + Token::LineComment => "//".to_string(), + Token::MultiLineCommentOpen => "/*".to_string(), + Token::MultiLineCommentClose => "*/".to_string(), + Token::Preprocessor => "#".to_string(), + Token::End => "EOF".to_string(), + Token::Selection => "?".to_string(), + Token::Sufix(op) => format!("{0}{0}", op), + Token::TokenPasting => "##".to_string(), + } + } +} + +impl fmt::Display for Token { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Token::Separator(sep) => write!(f, "{}", sep), + Token::DoubleColon => write!(f, ":"), + Token::Paren(paren) => write!(f, "{}", paren), + Token::Integral(int) => write!(f, "{}", int), + Token::Float(float) => write!(f, "{}", float), + Token::Double(double) => write!(f, "{}", double), + Token::Word(word) => write!(f, "{}", word), + Token::Operation(op) => write!(f, "{}", op), + Token::OpAssign(op) => write!(f, "{}=", op), + Token::LogicalOperation(op) => write!(f, "{0}=", op), + Token::ShiftOperation(op) => write!(f, "{0}{0}", op), + Token::Unknown(unknown) => write!(f, "{}", unknown), + Token::LineComment => write!(f, "//"), + Token::MultiLineCommentOpen => write!(f, "/*"), + Token::MultiLineCommentClose => write!(f, "*/"), + Token::Preprocessor => write!(f, "#"), + Token::End => write!(f, ""), + Token::Selection => write!(f, "?"), + Token::Sufix(op) => write!(f, "{0}{0}", op), + Token::TokenPasting => write!(f, "##"), + } + } +} + +#[derive(Debug)] +pub enum Node { + Ident(String), + Const(Literal), +} + +#[derive(Debug, Copy, Clone)] +pub enum Literal { + Double(f64), + Float(f32), + Uint(usize), + Sint(isize), + Bool(bool), +} + +fn parse_primary_expression(tokens: &mut Tokens) -> Result { + let token = tokens.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + match token.token { + Token::Word(ident) => Ok(match ident.as_str() { + "true" => Node::Const(Literal::Bool(true)), + "false" => Node::Const(Literal::Bool(false)), + _ => Node::Ident(ident), + }), + Token::Integral(uint) => Ok(Node::Const(Literal::Uint(uint))), + Token::Float(float) => Ok(Node::Const(Literal::Float(float))), + Token::Double(double) => Ok(Node::Const(Literal::Double(double))), + Token::Paren('(') => todo!(), /* parse_expression */ + _ => Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![ + Token::Word(String::new()), + Token::Integral(0), + Token::Double(0.0), + Token::Float(0.0), + Token::Paren('('), + ], + got: token, + }, + }), + } +} + +pub(self) fn parse_comments(mut lexer: lex::Lexer) -> Result, Error> { + let mut tokens = Vec::new(); + + loop { + let token = lexer.next(); + + match token.token { + Token::MultiLineCommentOpen => { + let mut token = lexer.next(); + while Token::MultiLineCommentClose != token.token { + match token.token { + Token::End => { + return Err(Error { + kind: ErrorKind::EOF, + }) + } + _ => {} + } + + token = lexer.next(); + } + } + Token::LineComment => { + while token.line == lexer.peek().line && Token::End != lexer.peek().token { + let _ = lexer.next(); + } + } + Token::End => { + tokens.push(token); + break; + } + _ => tokens.push(token), + } + } + + Ok(tokens) +} + +pub fn parse(input: &str) -> Result { + let lexer = lex::Lexer::new(input); + + let tokens = parse_comments(lexer)?; + + let mut macros = FastHashMap::default(); + + macros.insert( + String::from("GL_SPIRV"), + vec![TokenMetadata { + token: Token::Integral(100), + line: 0, + chars: 0..1, + }], + ); + macros.insert( + String::from("VULKAN"), + vec![TokenMetadata { + token: Token::Integral(100), + line: 0, + chars: 0..1, + }], + ); + + log::trace!("------GLSL COMMENT STRIPPED------"); + log::trace!("\n{:#?}", tokens); + log::trace!("---------------------------------"); + + #[cfg(feature = "glsl_preprocessor")] + let tokens = preprocessor::preprocess(&mut tokens.into_iter().peekable(), &mut macros)?; + + let mut line = 0; + let mut start = 0; + + Ok(tokens.into_iter().fold(String::new(), |mut acc, token| { + if token.line - line != 0 { + acc.push_str(&"\n".repeat(token.line - line)); + start = 0; + line = token.line; + } + + acc.push_str(&" ".repeat(token.chars.start - start)); + + acc.push_str(&token.token.to_string()); + + start = token.chars.end; + + acc + })) +} diff --git a/src/front/glsl/parser/lex.rs b/src/front/glsl/parser/lex.rs index 7cf27dd13..09c2f43e7 100644 --- a/src/front/glsl/parser/lex.rs +++ b/src/front/glsl/parser/lex.rs @@ -1,254 +1,254 @@ -use super::{Token, TokenMetadata}; -use std::{iter::Enumerate, str::Lines}; - -fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { - if input.starts_with(what) { - Some(&input[what.len()..]) - } else { - None - } -} - -fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str, usize) { - let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); - let (o, i) = input.split_at(pos); - (o, i, pos) -} - -pub fn consume_token(input: &String) -> (Token, &str, usize, usize) { - let mut input = input.as_str(); - - let start = input - .find(|c: char| !c.is_whitespace()) - .unwrap_or(input.chars().count()); - input = &input[start..]; - - let mut chars = input.chars(); - let cur = match chars.next() { - Some(c) => c, - None => return (Token::End, input, start, start + 1), - }; - match cur { - ':' => { - input = chars.as_str(); - if chars.next() == Some(':') { - (Token::DoubleColon, chars.as_str(), start, start + 2) - } else { - (Token::Separator(cur), input, start, start + 1) - } - } - ';' | ',' | '.' => (Token::Separator(cur), chars.as_str(), start, start + 1), - '(' | ')' | '{' | '}' | '[' | ']' => (Token::Paren(cur), chars.as_str(), start, start + 1), - '<' | '>' => { - input = chars.as_str(); - let next = chars.next(); - if next == Some('=') { - ( - Token::LogicalOperation(cur), - chars.as_str(), - start, - start + 1, - ) - } else if next == Some(cur) { - (Token::ShiftOperation(cur), chars.as_str(), start, start + 2) - } else { - (Token::Operation(cur), input, start, start + 1) - } - } - '0'..='9' => { - let (number, rest, pos) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); - if let Some(_) = number.find('.') { - if ( - chars.next().map(|c| c.to_lowercase().next().unwrap()), - chars.next().map(|c| c.to_lowercase().next().unwrap()), - ) == (Some('l'), Some('f')) - { - ( - Token::Double(number.parse().unwrap()), - chars.as_str(), - start, - start + pos + 2, - ) - } else { - ( - Token::Float(number.parse().unwrap()), - chars.as_str(), - start, - start + pos, - ) - } - } else { - ( - Token::Integral(number.parse().unwrap()), - rest, - start, - start + pos, - ) - } - } - 'a'..='z' | 'A'..='Z' | '_' => { - let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); - (Token::Word(String::from(word)), rest, start, start + pos) - } - '+' | '-' => { - input = chars.as_str(); - match chars.next() { - Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), - Some(next) if cur == next => (Token::Sufix(cur), chars.as_str(), start, start + 2), - _ => (Token::Operation(cur), input, start, start + 1), - } - } - '%' | '^' => { - input = chars.as_str(); - - if chars.next() == Some('=') { - (Token::OpAssign(cur), chars.as_str(), start, start + 2) - } else { - (Token::Operation(cur), input, start, start + 1) - } - } - '!' => { - input = chars.as_str(); - - if chars.next() == Some('=') { - ( - Token::LogicalOperation(cur), - chars.as_str(), - start, - start + 2, - ) - } else { - (Token::Operation(cur), input, start, start + 1) - } - } - '*' => { - input = chars.as_str(); - match chars.next() { - Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), - Some('/') => ( - Token::MultiLineCommentClose, - chars.as_str(), - start, - start + 2, - ), - _ => (Token::Operation(cur), input, start, start + 1), - } - } - '/' => { - input = chars.as_str(); - match chars.next() { - Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), - Some('/') => (Token::LineComment, chars.as_str(), start, start + 2), - Some('*') => ( - Token::MultiLineCommentOpen, - chars.as_str(), - start, - start + 2, - ), - _ => (Token::Operation(cur), input, start, start + 1), - } - } - '=' | '&' | '|' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - ( - Token::LogicalOperation(cur), - chars.as_str(), - start, - start + 2, - ) - } else { - (Token::Operation(cur), input, start, start + 1) - } - } - '#' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::TokenPasting, chars.as_str(), start, start + 2) - } else { - (Token::Preprocessor, input, start, start + 1) - } - } - '~' => (Token::Operation(cur), chars.as_str(), start, start + 1), - '?' => (Token::Selection, chars.as_str(), start, start + 1), - _ => (Token::Unknown(cur), chars.as_str(), start, start + 1), - } -} - -#[derive(Clone, Debug)] -pub struct Lexer<'a> { - lines: Enumerate>, - input: String, - line: usize, - offset: usize, -} - -impl<'a> Lexer<'a> { - pub fn new(input: &'a str) -> Self { - let mut lines = input.lines().enumerate(); - let (line, input) = lines.next().unwrap_or((0, "")); - let mut input = String::from(input); - - while input.chars().last() == Some('\\') { - if let Some((_, next)) = lines.next() { - input.pop(); - input.push_str(next); - } else { - break; - } - } - - Lexer { - lines, - input, - line, - offset: 0, - } - } - - #[must_use] - pub fn next(&mut self) -> TokenMetadata { - let (token, rest, start, end) = consume_token(&self.input); - - if token == Token::End { - match self.lines.next() { - Some((line, input)) => { - let mut input = String::from(input); - - while input.chars().last() == Some('\\') { - if let Some((_, next)) = self.lines.next() { - input.pop(); - input.push_str(next); - } else { - break; - } - } - - self.input = input; - self.line = line; - self.offset = 0; - self.next() - } - None => TokenMetadata { - token: Token::End, - line: self.line, - chars: self.offset + start..end + self.offset, - }, - } - } else { - self.input = String::from(rest); - let metadata = TokenMetadata { - token, - line: self.line, - chars: self.offset + start..end + self.offset, - }; - self.offset += end; - metadata - } - } - - #[must_use] - pub fn peek(&mut self) -> TokenMetadata { - self.clone().next() - } -} +use super::{Token, TokenMetadata}; +use std::{iter::Enumerate, str::Lines}; + +fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { + if input.starts_with(what) { + Some(&input[what.len()..]) + } else { + None + } +} + +fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str, usize) { + let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); + let (o, i) = input.split_at(pos); + (o, i, pos) +} + +pub fn consume_token(input: &String) -> (Token, &str, usize, usize) { + let mut input = input.as_str(); + + let start = input + .find(|c: char| !c.is_whitespace()) + .unwrap_or(input.chars().count()); + input = &input[start..]; + + let mut chars = input.chars(); + let cur = match chars.next() { + Some(c) => c, + None => return (Token::End, input, start, start + 1), + }; + match cur { + ':' => { + input = chars.as_str(); + if chars.next() == Some(':') { + (Token::DoubleColon, chars.as_str(), start, start + 2) + } else { + (Token::Separator(cur), input, start, start + 1) + } + } + ';' | ',' | '.' => (Token::Separator(cur), chars.as_str(), start, start + 1), + '(' | ')' | '{' | '}' | '[' | ']' => (Token::Paren(cur), chars.as_str(), start, start + 1), + '<' | '>' => { + input = chars.as_str(); + let next = chars.next(); + if next == Some('=') { + ( + Token::LogicalOperation(cur), + chars.as_str(), + start, + start + 1, + ) + } else if next == Some(cur) { + (Token::ShiftOperation(cur), chars.as_str(), start, start + 2) + } else { + (Token::Operation(cur), input, start, start + 1) + } + } + '0'..='9' => { + let (number, rest, pos) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); + if let Some(_) = number.find('.') { + if ( + chars.next().map(|c| c.to_lowercase().next().unwrap()), + chars.next().map(|c| c.to_lowercase().next().unwrap()), + ) == (Some('l'), Some('f')) + { + ( + Token::Double(number.parse().unwrap()), + chars.as_str(), + start, + start + pos + 2, + ) + } else { + ( + Token::Float(number.parse().unwrap()), + chars.as_str(), + start, + start + pos, + ) + } + } else { + ( + Token::Integral(number.parse().unwrap()), + rest, + start, + start + pos, + ) + } + } + 'a'..='z' | 'A'..='Z' | '_' => { + let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); + (Token::Word(String::from(word)), rest, start, start + pos) + } + '+' | '-' => { + input = chars.as_str(); + match chars.next() { + Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), + Some(next) if cur == next => (Token::Sufix(cur), chars.as_str(), start, start + 2), + _ => (Token::Operation(cur), input, start, start + 1), + } + } + '%' | '^' => { + input = chars.as_str(); + + if chars.next() == Some('=') { + (Token::OpAssign(cur), chars.as_str(), start, start + 2) + } else { + (Token::Operation(cur), input, start, start + 1) + } + } + '!' => { + input = chars.as_str(); + + if chars.next() == Some('=') { + ( + Token::LogicalOperation(cur), + chars.as_str(), + start, + start + 2, + ) + } else { + (Token::Operation(cur), input, start, start + 1) + } + } + '*' => { + input = chars.as_str(); + match chars.next() { + Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), + Some('/') => ( + Token::MultiLineCommentClose, + chars.as_str(), + start, + start + 2, + ), + _ => (Token::Operation(cur), input, start, start + 1), + } + } + '/' => { + input = chars.as_str(); + match chars.next() { + Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), + Some('/') => (Token::LineComment, chars.as_str(), start, start + 2), + Some('*') => ( + Token::MultiLineCommentOpen, + chars.as_str(), + start, + start + 2, + ), + _ => (Token::Operation(cur), input, start, start + 1), + } + } + '=' | '&' | '|' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + ( + Token::LogicalOperation(cur), + chars.as_str(), + start, + start + 2, + ) + } else { + (Token::Operation(cur), input, start, start + 1) + } + } + '#' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + (Token::TokenPasting, chars.as_str(), start, start + 2) + } else { + (Token::Preprocessor, input, start, start + 1) + } + } + '~' => (Token::Operation(cur), chars.as_str(), start, start + 1), + '?' => (Token::Selection, chars.as_str(), start, start + 1), + _ => (Token::Unknown(cur), chars.as_str(), start, start + 1), + } +} + +#[derive(Clone, Debug)] +pub struct Lexer<'a> { + lines: Enumerate>, + input: String, + line: usize, + offset: usize, +} + +impl<'a> Lexer<'a> { + pub fn new(input: &'a str) -> Self { + let mut lines = input.lines().enumerate(); + let (line, input) = lines.next().unwrap_or((0, "")); + let mut input = String::from(input); + + while input.chars().last() == Some('\\') { + if let Some((_, next)) = lines.next() { + input.pop(); + input.push_str(next); + } else { + break; + } + } + + Lexer { + lines, + input, + line, + offset: 0, + } + } + + #[must_use] + pub fn next(&mut self) -> TokenMetadata { + let (token, rest, start, end) = consume_token(&self.input); + + if token == Token::End { + match self.lines.next() { + Some((line, input)) => { + let mut input = String::from(input); + + while input.chars().last() == Some('\\') { + if let Some((_, next)) = self.lines.next() { + input.pop(); + input.push_str(next); + } else { + break; + } + } + + self.input = input; + self.line = line; + self.offset = 0; + self.next() + } + None => TokenMetadata { + token: Token::End, + line: self.line, + chars: self.offset + start..end + self.offset, + }, + } + } else { + self.input = String::from(rest); + let metadata = TokenMetadata { + token, + line: self.line, + chars: self.offset + start..end + self.offset, + }; + self.offset += end; + metadata + } + } + + #[must_use] + pub fn peek(&mut self) -> TokenMetadata { + self.clone().next() + } +} diff --git a/src/front/glsl/preprocessor.rs b/src/front/glsl/preprocessor.rs index 0121455ac..37d27efaa 100644 --- a/src/front/glsl/preprocessor.rs +++ b/src/front/glsl/preprocessor.rs @@ -1,1618 +1,1618 @@ -use super::{ - super::{Error, ErrorKind}, - Literal, Token, TokenMetadata, -}; -use crate::{BinaryOperator, FastHashMap}; -use std::{iter::Peekable, vec::IntoIter}; - -#[derive(Debug)] -pub enum PreprocessorIfNode { - Literal(Literal), - Unary { - op: UnaryOp, - tgt: Box, - }, - Binary { - left: Box, - op: BinaryOperator, - right: Box, - }, -} - -impl Literal { - pub fn as_isize(&self) -> isize { - match self { - Literal::Double(double) => *double as isize, - Literal::Float(float) => *float as isize, - Literal::Uint(uint) => *uint as isize, - Literal::Sint(sint) => *sint, - Literal::Bool(val) => *val as isize, - } - } - - pub fn as_bool(&self) -> Result { - Ok(match self { - Literal::Double(_) | Literal::Float(_) => panic!(), - Literal::Uint(uint) => { - if *uint == 0 { - false - } else { - true - } - } - Literal::Sint(sint) => { - if *sint == 0 { - false - } else { - true - } - } - Literal::Bool(val) => *val, - }) - } -} - -#[derive(Debug, Copy, Clone)] -pub enum UnaryOp { - Positive, - Negative, - BitWiseNot, - LogicalNot, -} - -macro_rules! get_macro { - ($name:expr, $token:expr, $line_offset:expr,$macros:expr) => { - match $name.as_str() { - "__LINE__" => Some(vec![TokenMetadata { - token: Token::Integral(($token.line as i32 + $line_offset + 1) as usize), - line: 0, - chars: 0..1, - }]), - "__FILE__" => Some(vec![TokenMetadata { - token: Token::Integral(0), - line: 0, - chars: 0..1, - }]), - "__VERSION__" => Some(vec![TokenMetadata { - token: Token::Integral(460), - line: 0, - chars: 0..1, - }]), /* TODO */ - other => $macros.get(other).cloned().map(|mut tokens| { - let mut start = tokens[0].chars.start; - let mut offset = 0; - - for token in tokens.iter_mut() { - token.line = $token.line; - - let length = token.chars.end - token.chars.start; - - offset += token.chars.start - start; - start = token.chars.start; - - token.chars.start = $token.chars.start + offset; - - token.chars.end = length + $token.chars.start + offset; - } - tokens - }), - } - }; -} - -pub fn preprocess( - lexer: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result, Error> { - let mut tokens = Vec::new(); - let mut line_offset = 0i32; - - let mut offset = (0, 0); - - loop { - let token = match lexer.next() { - Some(t) => t, - None => break, - }; - - match token.token { - Token::Preprocessor => { - let preprocessor_op_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - continue; - }; - - let preprocessor_op = if let Token::Word(name) = preprocessor_op_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: preprocessor_op_token, - }, - }); - }; - - match preprocessor_op.as_str() { - "define" => { - let macro_name_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let macro_name = if let Token::Word(name) = macro_name_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - if macro_name.starts_with("GL_") { - return Err(Error { - kind: ErrorKind::ReservedMacro, - }); - } - - let mut macro_tokens = Vec::new(); - - while Some(token.line) == lexer.peek().map(|t| t.line) { - let macro_token = lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - match macro_token.token { - Token::Word(ref word) => { - match get_macro!(word, &token, line_offset, macros) { - Some(stream) => macro_tokens.append(&mut stream.clone()), - None => macro_tokens.push(macro_token), - } - } - _ => macro_tokens.push(macro_token), - } - } - - macros.insert(macro_name, macro_tokens); - } - "undef" => { - let macro_name_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let macro_name = if let Token::Word(name) = macro_name_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - macros.remove(¯o_name); - } - "if" => { - let mut expr = Vec::new(); - - while lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - == token.line - { - let expr_token = lexer.next().unwrap(); - - match expr_token.token { - Token::Word(ref macro_name) => expr.append( - &mut get_macro!(macro_name, expr_token, line_offset, macros) - .unwrap(), - ), - _ => expr.push(expr_token), - } - } - - let condition = evaluate_preprocessor_if(expr, macros)?; - - let mut body_tokens = - parse_preprocessor_if(lexer, macros, condition, line_offset, offset)?; - - tokens.append(&mut body_tokens); - } - "ifdef" | "ifndef" => { - let macro_name_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().unwrap() - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let macro_name = if let Token::Word(name) = macro_name_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - // There shouldn't be any more tokens on this line so we throw a error - if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } - - let mut body_tokens = parse_preprocessor_if( - lexer, - macros, - match preprocessor_op.as_str() { - "ifdef" => macros.get(¯o_name).is_some(), - "ifndef" => macros.get(¯o_name).is_none(), - _ => unreachable!(), - }, - line_offset, - offset, - )?; - - tokens.append(&mut body_tokens); - } - "else" | "elif" | "endif" => { - return Err(Error { - kind: ErrorKind::UnboundedIfCloserOrVariant { token }, - }) - } - "error" => { - let mut error_token = lexer.next(); - - let first_byte = error_token - .as_ref() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .chars - .start; - - let mut error_message = String::new(); - - while error_token.as_ref().map(|t| t.line) == Some(token.line) { - let error_msg_token = error_token.as_ref().unwrap(); - - let spacing = error_msg_token.chars.start - - first_byte - - error_message.chars().count(); - - error_message.push_str(&" ".repeat(spacing)); - error_message.push_str(error_msg_token.token.to_string().as_str()); - - error_token = lexer.next() - } - - panic!(error_message) - } - "pragma" => { - let pragma_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let pragma = if let Token::Word(name) = pragma_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: pragma_token, - }, - }); - }; - - match pragma.as_str() { - "optimize" => { - let open_paren_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if Token::Paren('(') != open_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren('(')], - got: open_paren_token, - }, - }); - }; - - let status_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let _ = if let Token::Word(name) = status_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: status_token, - }, - }); - }; - - let close_paren_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if Token::Paren(')') != close_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren(')')], - got: close_paren_token, - }, - }); - }; - } - "debug" => { - let open_paren_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if Token::Paren('(') != open_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren('(')], - got: open_paren_token, - }, - }); - }; - - let status_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let _ = if let Token::Word(name) = status_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: status_token, - }, - }); - }; - - let close_paren_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if Token::Paren(')') != close_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren(')')], - got: close_paren_token, - }, - }); - }; - } - _ => { - return Err(Error { - kind: ErrorKind::UnknownPragma { pragma }, - }) - } - } - } - "extension" => { - let extension_name_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let extension_name = if let Token::Word(word) = extension_name_token.token { - word - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: extension_name_token, - }, - }); - }; - - let separator_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if separator_token.token != Token::DoubleColon { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::DoubleColon], - got: separator_token, - }, - }); - } - - let behavior_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let behavior = if let Token::Word(word) = behavior_token.token { - word - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: behavior_token, - }, - }); - }; - - match extension_name.as_str() { - "all" => match behavior.as_str() { - "require" | "enable" => { - return Err(Error { - kind: ErrorKind::AllExtensionsEnabled, - }) - } - "warn" | "disable" => {} - _ => { - return Err(Error { - kind: ErrorKind::ExtensionUnknownBehavior { behavior }, - }) - } - }, - _ => match behavior.as_str() { - "require" => { - return Err(Error { - kind: ErrorKind::ExtensionNotSupported { - extension: extension_name, - }, - }) - } - "enable" | "warn" | "disable" => log::warn!( - "Unsupported extensions was enabled: {}", - extension_name - ), - _ => { - return Err(Error { - kind: ErrorKind::ExtensionUnknownBehavior { behavior }, - }) - } - }, - } - } - "version" => { - let version_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let version = if let Token::Integral(int) = version_token.token { - int - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Integral(0)], - got: version_token, - }, - }); - }; - - match version { - 450 | 460 => {} - _ => { - return Err(Error { - kind: ErrorKind::UnsupportedVersion { version }, - }) - } - }; - - let profile_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let profile = if let Token::Word(word) = profile_token.token { - word - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: profile_token, - }, - }); - }; - - match profile.as_str() { - "core" => macros.insert( - String::from("GL_core_profile"), - vec![TokenMetadata { - token: Token::Integral(1), - line: 0, - chars: 0..1, - }], - ), - "compatibility" | "es" => { - return Err(Error { - kind: ErrorKind::UnsupportedProfile { profile }, - }) - } - _ => { - return Err(Error { - kind: ErrorKind::UnknownProfile { profile }, - }) - } - }; - } - "line" => { - let line_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let line = if let Token::Integral(int) = line_token.token { - int - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Integral(0)], - got: line_token, - }, - }); - }; - - let source_string_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if let Token::Word(_) = source_string_token.token { - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: source_string_token, - }, - }); - } - - line_offset = line as i32 - token.line as i32; - } - _ => { - return Err(Error { - kind: ErrorKind::UnknownPreprocessorDirective { - directive: preprocessor_op, - }, - }) - } - } - - if lexer.peek().map(|t| t.line) == Some(token.line) { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } - } - Token::End => { - let mut token = token; - - if offset.0 == token.line { - token.chars.start = (token.chars.start as isize + offset.1) as usize; - token.chars.end = (token.chars.end as isize + offset.1) as usize; - } - - tokens.push(token); - break; - } - Token::Word(ref word) => match get_macro!(word, &token, line_offset, macros) { - Some(mut stream) => { - for macro_token in stream.iter_mut() { - if offset.0 == token.line { - macro_token.chars.start = - (macro_token.chars.start as isize + offset.1) as usize; - macro_token.chars.end = - (macro_token.chars.end as isize + offset.1) as usize; - } - } - - offset.0 = stream.last().unwrap().line; - offset.1 = stream.last().unwrap().chars.end as isize - token.chars.end as isize; - - tokens.append(&mut stream) - } - None => { - let mut token = token; - - if offset.0 == token.line { - token.chars.start = (token.chars.start as isize + offset.1) as usize; - token.chars.end = (token.chars.end as isize + offset.1) as usize; - } - - tokens.push(token) - } - }, - _ => { - let mut token = token; - - if offset.0 == token.line { - token.chars.start = (token.chars.start as isize + offset.1) as usize; - token.chars.end = (token.chars.end as isize + offset.1) as usize; - } - - tokens.push(token) - } - } - } - - Ok(tokens) -} - -fn parse_preprocessor_if( - lexer: &mut Peekable>, - macros: &mut FastHashMap>, - mut condition: bool, - line_offset: i32, - offset: (usize, isize), -) -> Result, Error> { - let mut body = Vec::new(); - let mut else_block = false; - - loop { - let macro_token = lexer.peek().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - if let Token::Preprocessor = macro_token.token { - let macro_token = lexer.next().unwrap(); - - let directive_token = if macro_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().unwrap() - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let directive = if let Token::Word(name) = directive_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_token, - }, - }); - }; - - match directive.as_str() { - "if" => { - let mut expr = Vec::new(); - - while lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - == macro_token.line - { - let expr_token = lexer.next().unwrap(); - - match expr_token.token { - Token::Word(ref macro_name) => expr.append( - &mut get_macro!(macro_name, expr_token, line_offset, macros) - .unwrap(), - ), - _ => expr.push(expr_token), - } - } - - let condition = evaluate_preprocessor_if(expr, macros)?; - - let mut body_tokens = - parse_preprocessor_if(lexer, macros, condition, line_offset, offset)?; - - body.append(&mut body_tokens); - } - "elif" => { - let mut expr = Vec::new(); - - while lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - == macro_token.line - { - let expr_token = lexer.next().unwrap(); - - match expr_token.token { - Token::Word(ref macro_name) => expr.append( - &mut get_macro!(macro_name, expr_token, line_offset, macros) - .unwrap(), - ), - _ => expr.push(expr_token), - } - } - - if !condition { - condition = evaluate_preprocessor_if(expr, macros)?; - } - } - "ifdef" | "ifndef" => { - let macro_name_token = if macro_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().unwrap() - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let macro_name = if let Token::Word(name) = macro_name_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - // There shouldn't be any more tokens on this line so we throw a error - if macro_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } - - let mut body_tokens = parse_preprocessor_if( - lexer, - macros, - match directive.as_str() { - "ifdef" => macros.get(¯o_name).is_some(), - "ifndef" => macros.get(¯o_name).is_none(), - _ => unreachable!(), - }, - line_offset, - offset, - )?; - - body.append(&mut body_tokens); - } - "else" => { - // There shouldn't be any more tokens on this line so we throw a error - if directive_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } - - if else_block { - return Err(Error { - kind: ErrorKind::UnexpectedWord { - expected: vec!["endif"], - got: directive, - }, - }); - } - - else_block = true; - condition = !condition; - } - "endif" => { - // There shouldn't be any more tokens on this line so we throw a error - if directive_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - if lexer.peek().unwrap().token != Token::End { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } else { - body.push(lexer.next().unwrap()); - } - } - - break; - } - _ => {} - } - } - - if condition { - body.push(lexer.next().unwrap()); - } else { - lexer.next().unwrap(); - } - } - - let body_tokens = preprocess(&mut body.into_iter().peekable(), macros)?; - - Ok(body_tokens) -} - -fn evaluate_preprocessor_if( - expr: Vec, - macros: &mut FastHashMap>, -) -> Result { - let tree = logical_or_parser(&mut expr.into_iter().peekable(), macros)?; - log::trace!("{:#?}", tree); - evaluate_node(tree)?.as_bool() -} - -fn evaluate_node(node: PreprocessorIfNode) -> Result { - Ok(match node { - PreprocessorIfNode::Literal(literal) => literal, - PreprocessorIfNode::Unary { op, tgt } => { - let literal = evaluate_node(*tgt)?; - - match op { - UnaryOp::Positive => literal, - UnaryOp::Negative => Literal::Sint(-literal.as_isize()), - UnaryOp::BitWiseNot => Literal::Sint(!literal.as_isize()), - UnaryOp::LogicalNot => Literal::Sint((!literal.as_bool()?) as isize), - } - } - PreprocessorIfNode::Binary { left, op, right } => { - let left = evaluate_node(*left)?; - let right = evaluate_node(*right)?; - - match op { - BinaryOperator::Multiply => Literal::Sint(left.as_isize() * right.as_isize()), - BinaryOperator::Divide => Literal::Sint(left.as_isize() / right.as_isize()), - BinaryOperator::Modulo => Literal::Sint(left.as_isize() % right.as_isize()), - BinaryOperator::Add => Literal::Sint(left.as_isize() + right.as_isize()), - BinaryOperator::Subtract => Literal::Sint(left.as_isize() - right.as_isize()), - - BinaryOperator::ShiftLeftLogical => { - Literal::Sint(left.as_isize() << right.as_isize()) - } - BinaryOperator::ShiftRightArithmetic => { - Literal::Sint(left.as_isize() << right.as_isize()) - } - - BinaryOperator::Greater => { - Literal::Sint((left.as_isize() > right.as_isize()) as isize) - } - BinaryOperator::Less => { - Literal::Sint((left.as_isize() < right.as_isize()) as isize) - } - BinaryOperator::GreaterEqual => { - Literal::Sint((left.as_isize() >= right.as_isize()) as isize) - } - BinaryOperator::LessEqual => { - Literal::Sint((left.as_isize() <= right.as_isize()) as isize) - } - - BinaryOperator::Equal => { - Literal::Sint((left.as_isize() == right.as_isize()) as isize) - } - BinaryOperator::NotEqual => { - Literal::Sint((left.as_isize() != right.as_isize()) as isize) - } - - BinaryOperator::And => Literal::Sint(left.as_isize() & right.as_isize()), - BinaryOperator::ExclusiveOr => Literal::Sint(left.as_isize() ^ right.as_isize()), - BinaryOperator::InclusiveOr => Literal::Sint(left.as_isize() | right.as_isize()), - - BinaryOperator::LogicalOr => { - Literal::Sint((left.as_bool()? || right.as_bool()?) as isize) - } - BinaryOperator::LogicalAnd => { - Literal::Sint((left.as_bool()? && right.as_bool()?) as isize) - } - _ => unreachable!(), - } - } - }) -} - -pub(self) fn logical_or_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = logical_and_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::LogicalOperation('|')) { - let _ = expr.next().unwrap(); - - let right = logical_and_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::LogicalOr, - right: Box::new(right), - } - } - - Ok(node) -} - -fn logical_and_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = bitwise_or_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::LogicalOperation('&')) { - let _ = expr.next().unwrap(); - - let right = bitwise_or_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::LogicalAnd, - right: Box::new(right), - } - } - - Ok(node) -} - -fn bitwise_or_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = bitwise_xor_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::Operation('|')) { - let _ = expr.next().unwrap(); - - let right = bitwise_xor_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::InclusiveOr, - right: Box::new(right), - } - } - - Ok(node) -} - -fn bitwise_xor_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = bitwise_and_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::Operation('^')) { - let _ = expr.next().unwrap(); - - let right = bitwise_and_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::ExclusiveOr, - right: Box::new(right), - } - } - - Ok(node) -} - -fn bitwise_and_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = equality_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::Operation('&')) { - let _ = expr.next().unwrap(); - - let right = equality_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::And, - right: Box::new(right), - } - } - - Ok(node) -} - -fn equality_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = relational_parser(expr, macros)?; - - let mut node = left; - - loop { - let equality_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match equality_token.token { - Token::LogicalOperation('=') => BinaryOperator::Equal, - Token::LogicalOperation('!') => BinaryOperator::NotEqual, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = relational_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn relational_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = shift_parser(expr, macros)?; - - let mut node = left; - - loop { - let relational_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match relational_token.token { - Token::LogicalOperation('<') => BinaryOperator::LessEqual, - Token::LogicalOperation('>') => BinaryOperator::GreaterEqual, - Token::Operation('<') => BinaryOperator::Less, - Token::Operation('>') => BinaryOperator::Greater, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = shift_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn shift_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = additive_parser(expr, macros)?; - - let mut node = left; - - loop { - let shift_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match shift_token.token { - Token::ShiftOperation('<') => BinaryOperator::ShiftLeftLogical, - Token::ShiftOperation('>') => BinaryOperator::ShiftRightArithmetic, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = additive_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn additive_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = multiplicative_parser(expr, macros)?; - - let mut node = left; - - loop { - let additive_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match additive_token.token { - Token::Operation('+') => BinaryOperator::Add, - Token::Operation('-') => BinaryOperator::Subtract, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = multiplicative_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn multiplicative_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = unary_parser(expr, macros)?; - - let mut node = left; - - loop { - let multiplicative_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match multiplicative_token.token { - Token::Operation('*') => BinaryOperator::Multiply, - Token::Operation('/') => BinaryOperator::Divide, - Token::Operation('%') => BinaryOperator::Modulo, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = unary_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn unary_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let unary_or_atom_token = expr.peek().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - Ok(match unary_or_atom_token.token { - Token::Operation(op) => { - let unary_token = expr.next().unwrap(); - - PreprocessorIfNode::Unary { - op: match op { - '+' => UnaryOp::Positive, - '-' => UnaryOp::Negative, - '!' => UnaryOp::BitWiseNot, - '~' => UnaryOp::LogicalNot, - _ => { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![ - Token::Operation('+'), - Token::Operation('-'), - Token::Operation('!'), - Token::Operation('~'), - ], - got: unary_token, - }, - }) - } - }, - tgt: Box::new(atom_parser(expr, macros)?), - } - } - _ => atom_parser(expr, macros)?, - }) -} - -fn atom_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let atom = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - Ok(match atom.token { - Token::Double(_) | Token::Float(_) => { - return Err(Error { - kind: ErrorKind::NonIntegralType { token: atom }, - }) - } - Token::Integral(int) => PreprocessorIfNode::Literal(Literal::Uint(int)), - Token::Word(word) => PreprocessorIfNode::Literal(match word.as_str() { - "defined" => { - let macro_name_or_paren_token = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - match macro_name_or_paren_token.token { - Token::Paren('(') => { - let macro_name_token = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - let node = if let Token::Word(macro_name) = macro_name_token.token { - Literal::Sint(macros.get(¯o_name).is_some() as isize) - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - let close_paren_token = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - if Token::Paren(')') != close_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren(')')], - got: close_paren_token, - }, - }); - } - - node - } - _ => { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_or_paren_token, - }, - }) - } - } - } - _ => { - return logical_or_parser( - &mut macros - .get_mut(&word) - .cloned() - .unwrap() - .into_iter() - .peekable(), - macros, - ) - } - }), - Token::Paren('(') => { - let node = logical_or_parser(expr, macros)?; - - let close_paren = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - if close_paren.token != Token::Paren(')') { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren(')')], - got: close_paren, - }, - }); - } - - node - } - _ => { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![ - Token::Word(String::new()), - Token::Paren('('), - Token::Integral(0), - ], - got: atom, - }, - }) - } - }) -} +use super::{ + super::{Error, ErrorKind}, + Literal, Token, TokenMetadata, +}; +use crate::{BinaryOperator, FastHashMap}; +use std::{iter::Peekable, vec::IntoIter}; + +#[derive(Debug)] +pub enum PreprocessorIfNode { + Literal(Literal), + Unary { + op: UnaryOp, + tgt: Box, + }, + Binary { + left: Box, + op: BinaryOperator, + right: Box, + }, +} + +impl Literal { + pub fn as_isize(&self) -> isize { + match self { + Literal::Double(double) => *double as isize, + Literal::Float(float) => *float as isize, + Literal::Uint(uint) => *uint as isize, + Literal::Sint(sint) => *sint, + Literal::Bool(val) => *val as isize, + } + } + + pub fn as_bool(&self) -> Result { + Ok(match self { + Literal::Double(_) | Literal::Float(_) => panic!(), + Literal::Uint(uint) => { + if *uint == 0 { + false + } else { + true + } + } + Literal::Sint(sint) => { + if *sint == 0 { + false + } else { + true + } + } + Literal::Bool(val) => *val, + }) + } +} + +#[derive(Debug, Copy, Clone)] +pub enum UnaryOp { + Positive, + Negative, + BitWiseNot, + LogicalNot, +} + +macro_rules! get_macro { + ($name:expr, $token:expr, $line_offset:expr,$macros:expr) => { + match $name.as_str() { + "__LINE__" => Some(vec![TokenMetadata { + token: Token::Integral(($token.line as i32 + $line_offset + 1) as usize), + line: 0, + chars: 0..1, + }]), + "__FILE__" => Some(vec![TokenMetadata { + token: Token::Integral(0), + line: 0, + chars: 0..1, + }]), + "__VERSION__" => Some(vec![TokenMetadata { + token: Token::Integral(460), + line: 0, + chars: 0..1, + }]), /* TODO */ + other => $macros.get(other).cloned().map(|mut tokens| { + let mut start = tokens[0].chars.start; + let mut offset = 0; + + for token in tokens.iter_mut() { + token.line = $token.line; + + let length = token.chars.end - token.chars.start; + + offset += token.chars.start - start; + start = token.chars.start; + + token.chars.start = $token.chars.start + offset; + + token.chars.end = length + $token.chars.start + offset; + } + tokens + }), + } + }; +} + +pub fn preprocess( + lexer: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result, Error> { + let mut tokens = Vec::new(); + let mut line_offset = 0i32; + + let mut offset = (0, 0); + + loop { + let token = match lexer.next() { + Some(t) => t, + None => break, + }; + + match token.token { + Token::Preprocessor => { + let preprocessor_op_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + continue; + }; + + let preprocessor_op = if let Token::Word(name) = preprocessor_op_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: preprocessor_op_token, + }, + }); + }; + + match preprocessor_op.as_str() { + "define" => { + let macro_name_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let macro_name = if let Token::Word(name) = macro_name_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + if macro_name.starts_with("GL_") { + return Err(Error { + kind: ErrorKind::ReservedMacro, + }); + } + + let mut macro_tokens = Vec::new(); + + while Some(token.line) == lexer.peek().map(|t| t.line) { + let macro_token = lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + match macro_token.token { + Token::Word(ref word) => { + match get_macro!(word, &token, line_offset, macros) { + Some(stream) => macro_tokens.append(&mut stream.clone()), + None => macro_tokens.push(macro_token), + } + } + _ => macro_tokens.push(macro_token), + } + } + + macros.insert(macro_name, macro_tokens); + } + "undef" => { + let macro_name_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let macro_name = if let Token::Word(name) = macro_name_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + macros.remove(¯o_name); + } + "if" => { + let mut expr = Vec::new(); + + while lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + == token.line + { + let expr_token = lexer.next().unwrap(); + + match expr_token.token { + Token::Word(ref macro_name) => expr.append( + &mut get_macro!(macro_name, expr_token, line_offset, macros) + .unwrap(), + ), + _ => expr.push(expr_token), + } + } + + let condition = evaluate_preprocessor_if(expr, macros)?; + + let mut body_tokens = + parse_preprocessor_if(lexer, macros, condition, line_offset, offset)?; + + tokens.append(&mut body_tokens); + } + "ifdef" | "ifndef" => { + let macro_name_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().unwrap() + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let macro_name = if let Token::Word(name) = macro_name_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + // There shouldn't be any more tokens on this line so we throw a error + if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } + + let mut body_tokens = parse_preprocessor_if( + lexer, + macros, + match preprocessor_op.as_str() { + "ifdef" => macros.get(¯o_name).is_some(), + "ifndef" => macros.get(¯o_name).is_none(), + _ => unreachable!(), + }, + line_offset, + offset, + )?; + + tokens.append(&mut body_tokens); + } + "else" | "elif" | "endif" => { + return Err(Error { + kind: ErrorKind::UnboundedIfCloserOrVariant { token }, + }) + } + "error" => { + let mut error_token = lexer.next(); + + let first_byte = error_token + .as_ref() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .chars + .start; + + let mut error_message = String::new(); + + while error_token.as_ref().map(|t| t.line) == Some(token.line) { + let error_msg_token = error_token.as_ref().unwrap(); + + let spacing = error_msg_token.chars.start + - first_byte + - error_message.chars().count(); + + error_message.push_str(&" ".repeat(spacing)); + error_message.push_str(error_msg_token.token.to_string().as_str()); + + error_token = lexer.next() + } + + panic!(error_message) + } + "pragma" => { + let pragma_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let pragma = if let Token::Word(name) = pragma_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: pragma_token, + }, + }); + }; + + match pragma.as_str() { + "optimize" => { + let open_paren_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if Token::Paren('(') != open_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren('(')], + got: open_paren_token, + }, + }); + }; + + let status_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let _ = if let Token::Word(name) = status_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: status_token, + }, + }); + }; + + let close_paren_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if Token::Paren(')') != close_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren(')')], + got: close_paren_token, + }, + }); + }; + } + "debug" => { + let open_paren_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if Token::Paren('(') != open_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren('(')], + got: open_paren_token, + }, + }); + }; + + let status_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let _ = if let Token::Word(name) = status_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: status_token, + }, + }); + }; + + let close_paren_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if Token::Paren(')') != close_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren(')')], + got: close_paren_token, + }, + }); + }; + } + _ => { + return Err(Error { + kind: ErrorKind::UnknownPragma { pragma }, + }) + } + } + } + "extension" => { + let extension_name_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let extension_name = if let Token::Word(word) = extension_name_token.token { + word + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: extension_name_token, + }, + }); + }; + + let separator_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if separator_token.token != Token::DoubleColon { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::DoubleColon], + got: separator_token, + }, + }); + } + + let behavior_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let behavior = if let Token::Word(word) = behavior_token.token { + word + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: behavior_token, + }, + }); + }; + + match extension_name.as_str() { + "all" => match behavior.as_str() { + "require" | "enable" => { + return Err(Error { + kind: ErrorKind::AllExtensionsEnabled, + }) + } + "warn" | "disable" => {} + _ => { + return Err(Error { + kind: ErrorKind::ExtensionUnknownBehavior { behavior }, + }) + } + }, + _ => match behavior.as_str() { + "require" => { + return Err(Error { + kind: ErrorKind::ExtensionNotSupported { + extension: extension_name, + }, + }) + } + "enable" | "warn" | "disable" => log::warn!( + "Unsupported extensions was enabled: {}", + extension_name + ), + _ => { + return Err(Error { + kind: ErrorKind::ExtensionUnknownBehavior { behavior }, + }) + } + }, + } + } + "version" => { + let version_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let version = if let Token::Integral(int) = version_token.token { + int + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Integral(0)], + got: version_token, + }, + }); + }; + + match version { + 450 | 460 => {} + _ => { + return Err(Error { + kind: ErrorKind::UnsupportedVersion { version }, + }) + } + }; + + let profile_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let profile = if let Token::Word(word) = profile_token.token { + word + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: profile_token, + }, + }); + }; + + match profile.as_str() { + "core" => macros.insert( + String::from("GL_core_profile"), + vec![TokenMetadata { + token: Token::Integral(1), + line: 0, + chars: 0..1, + }], + ), + "compatibility" | "es" => { + return Err(Error { + kind: ErrorKind::UnsupportedProfile { profile }, + }) + } + _ => { + return Err(Error { + kind: ErrorKind::UnknownProfile { profile }, + }) + } + }; + } + "line" => { + let line_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let line = if let Token::Integral(int) = line_token.token { + int + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Integral(0)], + got: line_token, + }, + }); + }; + + let source_string_token = if token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().ok_or(Error { + kind: ErrorKind::EOF, + })? + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + if let Token::Word(_) = source_string_token.token { + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: source_string_token, + }, + }); + } + + line_offset = line as i32 - token.line as i32; + } + _ => { + return Err(Error { + kind: ErrorKind::UnknownPreprocessorDirective { + directive: preprocessor_op, + }, + }) + } + } + + if lexer.peek().map(|t| t.line) == Some(token.line) { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } + } + Token::End => { + let mut token = token; + + if offset.0 == token.line { + token.chars.start = (token.chars.start as isize + offset.1) as usize; + token.chars.end = (token.chars.end as isize + offset.1) as usize; + } + + tokens.push(token); + break; + } + Token::Word(ref word) => match get_macro!(word, &token, line_offset, macros) { + Some(mut stream) => { + for macro_token in stream.iter_mut() { + if offset.0 == token.line { + macro_token.chars.start = + (macro_token.chars.start as isize + offset.1) as usize; + macro_token.chars.end = + (macro_token.chars.end as isize + offset.1) as usize; + } + } + + offset.0 = stream.last().unwrap().line; + offset.1 = stream.last().unwrap().chars.end as isize - token.chars.end as isize; + + tokens.append(&mut stream) + } + None => { + let mut token = token; + + if offset.0 == token.line { + token.chars.start = (token.chars.start as isize + offset.1) as usize; + token.chars.end = (token.chars.end as isize + offset.1) as usize; + } + + tokens.push(token) + } + }, + _ => { + let mut token = token; + + if offset.0 == token.line { + token.chars.start = (token.chars.start as isize + offset.1) as usize; + token.chars.end = (token.chars.end as isize + offset.1) as usize; + } + + tokens.push(token) + } + } + } + + Ok(tokens) +} + +fn parse_preprocessor_if( + lexer: &mut Peekable>, + macros: &mut FastHashMap>, + mut condition: bool, + line_offset: i32, + offset: (usize, isize), +) -> Result, Error> { + let mut body = Vec::new(); + let mut else_block = false; + + loop { + let macro_token = lexer.peek().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + if let Token::Preprocessor = macro_token.token { + let macro_token = lexer.next().unwrap(); + + let directive_token = if macro_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().unwrap() + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let directive = if let Token::Word(name) = directive_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_token, + }, + }); + }; + + match directive.as_str() { + "if" => { + let mut expr = Vec::new(); + + while lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + == macro_token.line + { + let expr_token = lexer.next().unwrap(); + + match expr_token.token { + Token::Word(ref macro_name) => expr.append( + &mut get_macro!(macro_name, expr_token, line_offset, macros) + .unwrap(), + ), + _ => expr.push(expr_token), + } + } + + let condition = evaluate_preprocessor_if(expr, macros)?; + + let mut body_tokens = + parse_preprocessor_if(lexer, macros, condition, line_offset, offset)?; + + body.append(&mut body_tokens); + } + "elif" => { + let mut expr = Vec::new(); + + while lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + == macro_token.line + { + let expr_token = lexer.next().unwrap(); + + match expr_token.token { + Token::Word(ref macro_name) => expr.append( + &mut get_macro!(macro_name, expr_token, line_offset, macros) + .unwrap(), + ), + _ => expr.push(expr_token), + } + } + + if !condition { + condition = evaluate_preprocessor_if(expr, macros)?; + } + } + "ifdef" | "ifndef" => { + let macro_name_token = if macro_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + lexer.next().unwrap() + } else { + return Err(Error { + kind: ErrorKind::EOL, + }); + }; + + let macro_name = if let Token::Word(name) = macro_name_token.token { + name + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + // There shouldn't be any more tokens on this line so we throw a error + if macro_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } + + let mut body_tokens = parse_preprocessor_if( + lexer, + macros, + match directive.as_str() { + "ifdef" => macros.get(¯o_name).is_some(), + "ifndef" => macros.get(¯o_name).is_none(), + _ => unreachable!(), + }, + line_offset, + offset, + )?; + + body.append(&mut body_tokens); + } + "else" => { + // There shouldn't be any more tokens on this line so we throw a error + if directive_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } + + if else_block { + return Err(Error { + kind: ErrorKind::UnexpectedWord { + expected: vec!["endif"], + got: directive, + }, + }); + } + + else_block = true; + condition = !condition; + } + "endif" => { + // There shouldn't be any more tokens on this line so we throw a error + if directive_token.line + == lexer + .peek() + .ok_or(Error { + kind: ErrorKind::EOF, + })? + .line + { + if lexer.peek().unwrap().token != Token::End { + return Err(Error { + kind: ErrorKind::ExpectedEOL { + got: lexer.next().unwrap(), + }, + }); + } else { + body.push(lexer.next().unwrap()); + } + } + + break; + } + _ => {} + } + } + + if condition { + body.push(lexer.next().unwrap()); + } else { + lexer.next().unwrap(); + } + } + + let body_tokens = preprocess(&mut body.into_iter().peekable(), macros)?; + + Ok(body_tokens) +} + +fn evaluate_preprocessor_if( + expr: Vec, + macros: &mut FastHashMap>, +) -> Result { + let tree = logical_or_parser(&mut expr.into_iter().peekable(), macros)?; + log::trace!("{:#?}", tree); + evaluate_node(tree)?.as_bool() +} + +fn evaluate_node(node: PreprocessorIfNode) -> Result { + Ok(match node { + PreprocessorIfNode::Literal(literal) => literal, + PreprocessorIfNode::Unary { op, tgt } => { + let literal = evaluate_node(*tgt)?; + + match op { + UnaryOp::Positive => literal, + UnaryOp::Negative => Literal::Sint(-literal.as_isize()), + UnaryOp::BitWiseNot => Literal::Sint(!literal.as_isize()), + UnaryOp::LogicalNot => Literal::Sint((!literal.as_bool()?) as isize), + } + } + PreprocessorIfNode::Binary { left, op, right } => { + let left = evaluate_node(*left)?; + let right = evaluate_node(*right)?; + + match op { + BinaryOperator::Multiply => Literal::Sint(left.as_isize() * right.as_isize()), + BinaryOperator::Divide => Literal::Sint(left.as_isize() / right.as_isize()), + BinaryOperator::Modulo => Literal::Sint(left.as_isize() % right.as_isize()), + BinaryOperator::Add => Literal::Sint(left.as_isize() + right.as_isize()), + BinaryOperator::Subtract => Literal::Sint(left.as_isize() - right.as_isize()), + + BinaryOperator::ShiftLeftLogical => { + Literal::Sint(left.as_isize() << right.as_isize()) + } + BinaryOperator::ShiftRightArithmetic => { + Literal::Sint(left.as_isize() << right.as_isize()) + } + + BinaryOperator::Greater => { + Literal::Sint((left.as_isize() > right.as_isize()) as isize) + } + BinaryOperator::Less => { + Literal::Sint((left.as_isize() < right.as_isize()) as isize) + } + BinaryOperator::GreaterEqual => { + Literal::Sint((left.as_isize() >= right.as_isize()) as isize) + } + BinaryOperator::LessEqual => { + Literal::Sint((left.as_isize() <= right.as_isize()) as isize) + } + + BinaryOperator::Equal => { + Literal::Sint((left.as_isize() == right.as_isize()) as isize) + } + BinaryOperator::NotEqual => { + Literal::Sint((left.as_isize() != right.as_isize()) as isize) + } + + BinaryOperator::And => Literal::Sint(left.as_isize() & right.as_isize()), + BinaryOperator::ExclusiveOr => Literal::Sint(left.as_isize() ^ right.as_isize()), + BinaryOperator::InclusiveOr => Literal::Sint(left.as_isize() | right.as_isize()), + + BinaryOperator::LogicalOr => { + Literal::Sint((left.as_bool()? || right.as_bool()?) as isize) + } + BinaryOperator::LogicalAnd => { + Literal::Sint((left.as_bool()? && right.as_bool()?) as isize) + } + _ => unreachable!(), + } + } + }) +} + +pub(self) fn logical_or_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = logical_and_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::LogicalOperation('|')) { + let _ = expr.next().unwrap(); + + let right = logical_and_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::LogicalOr, + right: Box::new(right), + } + } + + Ok(node) +} + +fn logical_and_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = bitwise_or_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::LogicalOperation('&')) { + let _ = expr.next().unwrap(); + + let right = bitwise_or_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::LogicalAnd, + right: Box::new(right), + } + } + + Ok(node) +} + +fn bitwise_or_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = bitwise_xor_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::Operation('|')) { + let _ = expr.next().unwrap(); + + let right = bitwise_xor_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::InclusiveOr, + right: Box::new(right), + } + } + + Ok(node) +} + +fn bitwise_xor_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = bitwise_and_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::Operation('^')) { + let _ = expr.next().unwrap(); + + let right = bitwise_and_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::ExclusiveOr, + right: Box::new(right), + } + } + + Ok(node) +} + +fn bitwise_and_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = equality_parser(expr, macros)?; + + let mut node = left; + + while expr.peek().map(|t| &t.token) == Some(&Token::Operation('&')) { + let _ = expr.next().unwrap(); + + let right = equality_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op: BinaryOperator::And, + right: Box::new(right), + } + } + + Ok(node) +} + +fn equality_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = relational_parser(expr, macros)?; + + let mut node = left; + + loop { + let equality_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match equality_token.token { + Token::LogicalOperation('=') => BinaryOperator::Equal, + Token::LogicalOperation('!') => BinaryOperator::NotEqual, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = relational_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn relational_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = shift_parser(expr, macros)?; + + let mut node = left; + + loop { + let relational_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match relational_token.token { + Token::LogicalOperation('<') => BinaryOperator::LessEqual, + Token::LogicalOperation('>') => BinaryOperator::GreaterEqual, + Token::Operation('<') => BinaryOperator::Less, + Token::Operation('>') => BinaryOperator::Greater, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = shift_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn shift_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = additive_parser(expr, macros)?; + + let mut node = left; + + loop { + let shift_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match shift_token.token { + Token::ShiftOperation('<') => BinaryOperator::ShiftLeftLogical, + Token::ShiftOperation('>') => BinaryOperator::ShiftRightArithmetic, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = additive_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn additive_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = multiplicative_parser(expr, macros)?; + + let mut node = left; + + loop { + let additive_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match additive_token.token { + Token::Operation('+') => BinaryOperator::Add, + Token::Operation('-') => BinaryOperator::Subtract, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = multiplicative_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn multiplicative_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let left = unary_parser(expr, macros)?; + + let mut node = left; + + loop { + let multiplicative_token = match expr.peek() { + Some(t) => t, + None => break, + }; + + let op = match multiplicative_token.token { + Token::Operation('*') => BinaryOperator::Multiply, + Token::Operation('/') => BinaryOperator::Divide, + Token::Operation('%') => BinaryOperator::Modulo, + _ => break, + }; + + let _ = expr.next().unwrap(); + + let right = unary_parser(expr, macros)?; + + node = PreprocessorIfNode::Binary { + left: Box::new(node), + op, + right: Box::new(right), + } + } + + Ok(node) +} + +fn unary_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let unary_or_atom_token = expr.peek().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + Ok(match unary_or_atom_token.token { + Token::Operation(op) => { + let unary_token = expr.next().unwrap(); + + PreprocessorIfNode::Unary { + op: match op { + '+' => UnaryOp::Positive, + '-' => UnaryOp::Negative, + '!' => UnaryOp::BitWiseNot, + '~' => UnaryOp::LogicalNot, + _ => { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![ + Token::Operation('+'), + Token::Operation('-'), + Token::Operation('!'), + Token::Operation('~'), + ], + got: unary_token, + }, + }) + } + }, + tgt: Box::new(atom_parser(expr, macros)?), + } + } + _ => atom_parser(expr, macros)?, + }) +} + +fn atom_parser( + expr: &mut Peekable>, + macros: &mut FastHashMap>, +) -> Result { + let atom = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + Ok(match atom.token { + Token::Double(_) | Token::Float(_) => { + return Err(Error { + kind: ErrorKind::NonIntegralType { token: atom }, + }) + } + Token::Integral(int) => PreprocessorIfNode::Literal(Literal::Uint(int)), + Token::Word(word) => PreprocessorIfNode::Literal(match word.as_str() { + "defined" => { + let macro_name_or_paren_token = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + match macro_name_or_paren_token.token { + Token::Paren('(') => { + let macro_name_token = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + let node = if let Token::Word(macro_name) = macro_name_token.token { + Literal::Sint(macros.get(¯o_name).is_some() as isize) + } else { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_token, + }, + }); + }; + + let close_paren_token = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + if Token::Paren(')') != close_paren_token.token { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren(')')], + got: close_paren_token, + }, + }); + } + + node + } + _ => { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Word(String::new())], + got: macro_name_or_paren_token, + }, + }) + } + } + } + _ => { + return logical_or_parser( + &mut macros + .get_mut(&word) + .cloned() + .unwrap() + .into_iter() + .peekable(), + macros, + ) + } + }), + Token::Paren('(') => { + let node = logical_or_parser(expr, macros)?; + + let close_paren = expr.next().ok_or(Error { + kind: ErrorKind::EOF, + })?; + + if close_paren.token != Token::Paren(')') { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![Token::Paren(')')], + got: close_paren, + }, + }); + } + + node + } + _ => { + return Err(Error { + kind: ErrorKind::UnexpectedToken { + expected: vec![ + Token::Word(String::new()), + Token::Paren('('), + Token::Integral(0), + ], + got: atom, + }, + }) + } + }) +} diff --git a/test-data/glsl_if_preprocessor.vert b/test-data/glsl_if_preprocessor.vert index 64917a2c4..752dde308 100644 --- a/test-data/glsl_if_preprocessor.vert +++ b/test-data/glsl_if_preprocessor.vert @@ -1,14 +1,14 @@ -#version 460 core - -#define TEST 3 -#define TEST_EXPR 2 && 2 - -#if TEST_EXPR - 2 == 0 -#error 0 -#elif TEST_EXPR - 2 == 1 -#error 1 -#elif TEST_EXPR - 2 == 2 -#error 2 -#else -#error You shouldn't do that -#endif +#version 460 core + +#define TEST 3 +#define TEST_EXPR 2 && 2 + +#if TEST_EXPR - 2 == 0 +#error 0 +#elif TEST_EXPR - 2 == 1 +#error 1 +#elif TEST_EXPR - 2 == 2 +#error 2 +#else +#error You shouldn't do that +#endif diff --git a/test-data/glsl_preprocessor_abuse.vert b/test-data/glsl_preprocessor_abuse.vert index 9f27c77da..f83cc74c4 100644 --- a/test-data/glsl_preprocessor_abuse.vert +++ b/test-data/glsl_preprocessor_abuse.vert @@ -1,11 +1,11 @@ -#version 450 core - -#define MAIN void main() { -#define V_POSITION layout(location=0) in vec4 a_position; -#define ASSIGN_POSITION gl_Position = a_position; - -V_POSITION - -MAIN - ASSIGN_POSITION +#version 450 core + +#define MAIN void main() { +#define V_POSITION layout(location=0) in vec4 a_position; +#define ASSIGN_POSITION gl_Position = a_position; + +V_POSITION + +MAIN + ASSIGN_POSITION } \ No newline at end of file From ba0798e5d17acd53b4da3751e87b160be1bd1b16 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 17 Jun 2020 15:34:35 +0200 Subject: [PATCH 0082/2212] Add glsl handling to convert sample (#69) * Add glsl handling to convert sample - Also fis extension check for spv and wgsl (missing .) * Use std::path::Path for ext handling * Also fix ext for .comp Missing from last commit --- examples/convert.rs | 38 +++++++++++++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index bd066a9f7..722e811c6 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -1,5 +1,5 @@ use serde::{Deserialize, Serialize}; -use std::{env, fs}; +use std::{env, fs, path::Path}; #[derive(Hash, PartialEq, Eq, Serialize, Deserialize)] struct BindSource { @@ -29,8 +29,12 @@ fn main() { println!("Call with "); return; } - let in_ext_pos = args[1].rfind(".").expect("Input has no extension?"); - let module = match &args[1][in_ext_pos..] { + let ext = Path::new(&args[1]) + .extension() + .expect("Input has no extension?") + .to_str() + .unwrap(); + let module = match ext { "spv" => { let input = fs::read(&args[1]).unwrap(); naga::front::spv::parse_u8_slice(&input).unwrap() @@ -39,8 +43,32 @@ fn main() { let input = fs::read_to_string(&args[1]).unwrap(); naga::front::wgsl::parse_str(&input).unwrap() } - //#[cfg(feature = "glsl")] //TODO - //"glsl" | "vert" | "frag" | "comp" => {} + #[cfg(feature = "glsl")] + "vert" => { + let input = fs::read_to_string(&args[1]).unwrap(); + naga::front::glsl::parse_str(&input, "main".to_string(), spirv::ExecutionModel::Vertex) + .unwrap() + } + #[cfg(feature = "glsl")] + "frag" => { + let input = fs::read_to_string(&args[1]).unwrap(); + naga::front::glsl::parse_str( + &input, + "main".to_string(), + spirv::ExecutionModel::Fragment, + ) + .unwrap() + } + #[cfg(feature = "glsl")] + "comp" => { + let input = fs::read_to_string(&args[1]).unwrap(); + naga::front::glsl::parse_str( + &input, + "main".to_string(), + spirv::ExecutionModel::GLCompute, + ) + .unwrap() + } other => panic!("Unknown input extension: {}", other), }; From e3aea9619865b16a24164d46ab29cca36ad7daf2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 17 Jun 2020 09:43:31 -0400 Subject: [PATCH 0083/2212] Refactor GLSL parser modules --- src/front/glsl/{parser.rs => parser/mod.rs} | 1 - src/front/glsl/{ => parser}/preprocessor.rs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) rename src/front/glsl/{parser.rs => parser/mod.rs} (99%) rename src/front/glsl/{ => parser}/preprocessor.rs (99%) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser/mod.rs similarity index 99% rename from src/front/glsl/parser.rs rename to src/front/glsl/parser/mod.rs index f0a9503b4..8a1634da7 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser/mod.rs @@ -13,7 +13,6 @@ use std::{ pub mod lex; #[cfg(feature = "glsl_preprocessor")] -#[path = "./preprocessor.rs"] pub mod preprocessor; type Tokens = Peekable>; diff --git a/src/front/glsl/preprocessor.rs b/src/front/glsl/parser/preprocessor.rs similarity index 99% rename from src/front/glsl/preprocessor.rs rename to src/front/glsl/parser/preprocessor.rs index 37d27efaa..a093c5d2d 100644 --- a/src/front/glsl/preprocessor.rs +++ b/src/front/glsl/parser/preprocessor.rs @@ -6,7 +6,7 @@ use crate::{BinaryOperator, FastHashMap}; use std::{iter::Peekable, vec::IntoIter}; #[derive(Debug)] -pub enum PreprocessorIfNode { +enum PreprocessorIfNode { Literal(Literal), Unary { op: UnaryOp, From 0a781f4ce750296b8b6b29a8c4a7dadeda937fad Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Thu, 18 Jun 2020 18:14:19 +0200 Subject: [PATCH 0084/2212] Add Layout Tests Add Physical Layout test Add Instruction tests Add Logical Layout test --- src/back/spv/helpers.rs | 20 ++++ src/back/spv/layout_tests.rs | 190 +++++++++++++++++++++++++++++++++++ src/back/spv/mod.rs | 4 + src/back/spv/writer.rs | 35 ++----- 4 files changed, 222 insertions(+), 27 deletions(-) create mode 100644 src/back/spv/helpers.rs create mode 100644 src/back/spv/layout_tests.rs diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs new file mode 100644 index 000000000..5facbe8b6 --- /dev/null +++ b/src/back/spv/helpers.rs @@ -0,0 +1,20 @@ +use spirv::Word; + +pub(crate) fn bytes_to_words(bytes: &[u8]) -> Vec { + bytes + .chunks(4) + .map(|chars| chars.iter().rev().fold(0u32, |u, c| (u << 8) | *c as u32)) + .collect() +} + +pub(crate) fn string_to_words(input: &str) -> Vec { + let bytes = input.as_bytes(); + let mut words = bytes_to_words(bytes); + + if bytes.len() % 4 == 0 { + // nul-termination + words.push(0x0u32); + } + + words +} diff --git a/src/back/spv/layout_tests.rs b/src/back/spv/layout_tests.rs new file mode 100644 index 000000000..697b609fa --- /dev/null +++ b/src/back/spv/layout_tests.rs @@ -0,0 +1,190 @@ +use crate::back::spv::{helpers, Instruction, LogicalLayout, PhysicalLayout}; +use crate::Header; +use spirv::*; + +#[test] +fn test_physical_layout_in_words() { + let header = Header { + generator: 0, + version: (1, 2, 3), + }; + let bound = 5; + + let mut output = vec![]; + let mut layout = PhysicalLayout::new(&header); + layout.bound = bound; + + layout.in_words(&mut output); + + assert_eq!(output[0], spirv::MAGIC_NUMBER); + assert_eq!( + output[1], + to_word(&[header.version.0, header.version.1, header.version.2, 1]) + ); + assert_eq!(output[2], 0); + assert_eq!(output[3], bound); + assert_eq!(output[4], 0); +} + +#[test] +fn test_logical_layout_in_words() { + let mut output = vec![]; + let mut layout = LogicalLayout::default(); + let layout_vectors = 11; + let mut instructions = Vec::with_capacity(layout_vectors); + + let vector_names = &[ + "Capabilities", + "Extensions", + "External Instruction Imports", + "Memory Model", + "Entry Points", + "Execution Modes", + "Debugs", + "Annotations", + "Declarations", + "Function Declarations", + "Function Definitions", + ]; + + for i in 0..layout_vectors { + let mut dummy_instruction = Instruction::new(Op::Constant); + dummy_instruction.set_type((i + 1) as u32); + dummy_instruction.set_result((i + 2) as u32); + dummy_instruction.add_operand((i + 3) as u32); + dummy_instruction.add_operands(helpers::string_to_words( + format!("This is the vector: {}", vector_names[i]).as_str(), + )); + instructions.push(dummy_instruction); + } + + instructions[0].to_words(&mut layout.capabilities); + instructions[1].to_words(&mut layout.extensions); + instructions[2].to_words(&mut layout.ext_inst_imports); + instructions[3].to_words(&mut layout.memory_model); + instructions[4].to_words(&mut layout.entry_points); + instructions[5].to_words(&mut layout.execution_modes); + instructions[6].to_words(&mut layout.debugs); + instructions[7].to_words(&mut layout.annotations); + instructions[8].to_words(&mut layout.declarations); + instructions[9].to_words(&mut layout.function_declarations); + instructions[10].to_words(&mut layout.function_definitions); + + layout.in_words(&mut output); + + let mut index: usize = 0; + for instruction in instructions { + let wc = instruction.wc as usize; + let instruction_output = &output[index..index + wc]; + validate_instruction(instruction_output, instruction); + index += wc; + } +} + +#[test] +fn test_instruction_set_type() { + let ty = 1; + let mut instruction = Instruction::new(Op::Constant); + assert_eq!(instruction.wc, 1); + + instruction.set_type(ty); + assert_eq!(instruction.type_id.unwrap(), ty); + assert_eq!(instruction.wc, 2); +} + +#[test] +#[should_panic] +fn test_instruction_set_type_twice() { + let ty = 1; + let mut instruction = Instruction::new(Op::Constant); + instruction.set_type(ty); + instruction.set_type(ty); +} + +#[test] +fn test_instruction_set_result() { + let result = 1; + let mut instruction = Instruction::new(Op::Constant); + assert_eq!(instruction.wc, 1); + + instruction.set_result(result); + assert_eq!(instruction.result_id.unwrap(), result); + assert_eq!(instruction.wc, 2); +} + +#[test] +#[should_panic] +fn test_instruction_set_result_twice() { + let result = 1; + let mut instruction = Instruction::new(Op::Constant); + instruction.set_result(result); + instruction.set_result(result); +} + +#[test] +fn test_instruction_add_operand() { + let operand = 1; + let mut instruction = Instruction::new(Op::Constant); + assert_eq!(instruction.operands.len(), 0); + assert_eq!(instruction.wc, 1); + + instruction.add_operand(operand); + assert_eq!(instruction.operands.len(), 1); + assert_eq!(instruction.wc, 2); +} + +#[test] +fn test_instruction_add_operands() { + let operands = vec![1, 2, 3]; + let mut instruction = Instruction::new(Op::Constant); + assert_eq!(instruction.operands.len(), 0); + assert_eq!(instruction.wc, 1); + + instruction.add_operands(operands); + assert_eq!(instruction.operands.len(), 3); + assert_eq!(instruction.wc, 4); +} + +#[test] +fn test_instruction_to_words() { + let ty = 1; + let result = 2; + let operand = 3; + let mut instruction = Instruction::new(Op::Constant); + instruction.set_type(ty); + instruction.set_result(result); + instruction.add_operand(operand); + + let mut output = vec![]; + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), instruction); +} + +fn validate_instruction(words: &[Word], instruction: Instruction) { + let mut inst_index = 0; + let (wc, op) = ((words[inst_index] >> 16) as u16, words[inst_index] as u16); + inst_index += 1; + + assert_eq!(wc, words.len() as u16); + assert_eq!(op, instruction.op as u16); + + if instruction.type_id.is_some() { + assert_eq!(words[inst_index], instruction.type_id.unwrap()); + inst_index += 1; + } + + if instruction.result_id.is_some() { + assert_eq!(words[inst_index], instruction.result_id.unwrap()); + inst_index += 1; + } + + let mut op_index = 0; + for i in inst_index..wc as usize { + assert_eq!(words[i as usize], instruction.operands[op_index]); + op_index += 1; + } +} + +fn to_word(bytes: &[u8]) -> Word { + ((bytes[0] as u32) << 16) | ((bytes[1] as u32) << 8) | bytes[2] as u32 +} diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 444bc2301..468307f55 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -1,6 +1,10 @@ +mod helpers; mod layout; mod writer; +#[cfg(test)] +mod layout_tests; + pub use writer::Writer; use spirv::*; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a81ad7a5e..5ed31c344 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,5 +1,5 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ -use crate::back::spv::{Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; +use crate::back::spv::{helpers, Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; use crate::{FastHashMap, FastHashSet}; use spirv::*; @@ -81,25 +81,6 @@ impl Writer { self.id_count } - fn bytes_to_words(&self, bytes: &[u8]) -> Vec { - bytes - .chunks(4) - .map(|chars| chars.iter().rev().fold(0u32, |u, c| (u << 8) | *c as u32)) - .collect() - } - - fn string_to_words(&self, input: &str) -> Vec { - let bytes = input.as_bytes(); - let mut words = self.bytes_to_words(bytes); - - if bytes.len() % 4 == 0 { - // nul-termination - words.push(0x0u32); - } - - words - } - fn try_add_capabilities(&mut self, capabilities: &[Capability]) { for capability in capabilities.iter() { self.capabilities.insert(*capability); @@ -116,7 +97,7 @@ impl Writer { let mut instruction = Instruction::new(Op::ExtInstImport); let id = self.generate_id(); instruction.set_result(id); - instruction.add_operands(self.string_to_words(name)); + instruction.add_operands(helpers::string_to_words(name)); instruction } @@ -149,11 +130,11 @@ impl Writer { if self.writer_flags.contains(WriterFlags::DEBUG) { let mut debug_instruction = Instruction::new(Op::Name); debug_instruction.set_result(function_id); - debug_instruction.add_operands(self.string_to_words(entry_point.name.as_str())); + debug_instruction.add_operands(helpers::string_to_words(entry_point.name.as_str())); self.debugs.push(debug_instruction); } - instruction.add_operands(self.string_to_words(entry_point.name.as_str())); + instruction.add_operands(helpers::string_to_words(entry_point.name.as_str())); let function = &ir_module.functions[entry_point.function]; for ((handle, _), &usage) in ir_module @@ -609,9 +590,9 @@ impl Writer { if self.writer_flags.contains(WriterFlags::DEBUG) { let mut debug_instruction = Instruction::new(Op::Name); debug_instruction.set_result(id); - debug_instruction.add_operands( - self.string_to_words(global_variable.name.as_ref().unwrap().as_str()), - ); + debug_instruction.add_operands(helpers::string_to_words( + global_variable.name.as_ref().unwrap().as_str(), + )); self.debugs.push(debug_instruction); } @@ -662,7 +643,7 @@ impl Writer { let mut instruction = Instruction::new(Op::Source); instruction.add_operand(SourceLanguage::GLSL as u32); - instruction.add_operands(self.bytes_to_words(&version.to_le_bytes())); + instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); instruction } From eb559c5b3228337c9ea5285906f3106fbf25bb54 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Thu, 18 Jun 2020 23:34:15 +0200 Subject: [PATCH 0085/2212] Add GLSL construction status --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a2a88688d..ee1a9261c 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Front-end | Status | Notes | --------------- | ------------------ | ----- | SPIR-V (binary) | :construction: | | WGSL (Tint) | :construction: | | -GLSL (Vulkan) | | | +GLSL (Vulkan) | :construction: | | Rust | | | Back-end | Status | Notes | From a9228d2aed38c71388489a95817238ff98198fa3 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 18 Jun 2020 23:53:44 -0400 Subject: [PATCH 0086/2212] Add member offsets and array strides --- src/back/msl.rs | 12 +++++++++-- src/back/spv/writer.rs | 10 ++++++++- src/front/glsl/mod.rs | 7 +++++++ src/front/spv.rs | 46 ++++++++++++++++++++++++++++++++++++++---- src/front/wgsl.rs | 14 +++++++++++-- src/lib.rs | 3 +++ 6 files changed, 83 insertions(+), 9 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index bb74984a7..ed4a47d7c 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -451,7 +451,11 @@ impl Writer { write!(self.out, ".{}", COMPONENTS[index as usize])?; Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width })) } - crate::TypeInner::Array { base, size } => { + crate::TypeInner::Array { + base, + size, + stride: _, + } => { if let crate::ArraySize::Static(length) = size { return Err(Error::AccessIndexExceedsStaticLength(index, length)); } @@ -844,7 +848,11 @@ impl Writer { }; write!(self.out, "typedef {} {} *{}", class_name, base_name, name)?; } - crate::TypeInner::Array { base, size } => { + crate::TypeInner::Array { + base, + size, + stride: _, + } => { let base_name = module.types[base].name.or_index(base); let resolved_size = match size { crate::ArraySize::Static(length) => length, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 5ed31c344..4124280d2 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -335,7 +335,15 @@ impl Writer { self.lookup_type.insert(id, handle); } - crate::TypeInner::Array { base, size } => { + crate::TypeInner::Array { base, size, stride } => { + if let Some(array_stride) = stride { + let mut instruction = Instruction::new(Op::Decorate); + instruction.add_operand(id); + instruction.add_operand(Decoration::ArrayStride as u32); + instruction.add_operand(array_stride.get()); + self.annotations.push(instruction); + } + let type_id = self.get_type_id(arena, handle); instruction = Instruction::new(Op::TypeArray); diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 603e75c36..1cd44b0c3 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -237,11 +237,13 @@ impl<'a> Parser<'a> { unimplemented!() } }, + stride: None, }, }) } else { ty }, + offset: 0, //TODO }); if name.is_none() { @@ -267,6 +269,7 @@ impl<'a> Parser<'a> { ArraySpecifier::Unsized => ArraySize::Dynamic, ArraySpecifier::ExplicitlySized(_expr) => unimplemented!(), }, + stride: None, }, }) } else { @@ -337,6 +340,7 @@ impl<'a> Parser<'a> { inner: TypeInner::Array { base: ty, size: ArraySize::Dynamic, + stride: None, }, }), ArraySpecifier::ExplicitlySized(_) => unimplemented!(), @@ -447,6 +451,7 @@ impl<'a> Parser<'a> { inner: TypeInner::Array { base: ty, size: ArraySize::Dynamic, + stride: None, }, }), ArraySpecifier::ExplicitlySized(_) => unimplemented!(), @@ -1066,6 +1071,7 @@ impl<'a> Parser<'a> { ArraySpecifier::Unsized => TypeInner::Array { base: handle, size: ArraySize::Dynamic, + stride: None, }, ArraySpecifier::ExplicitlySized(_) => unimplemented!(), } @@ -1091,6 +1097,7 @@ impl<'a> Parser<'a> { inner: TypeInner::Array { base: ty, size: ArraySize::Dynamic, + stride: None, }, }), ArraySpecifier::ExplicitlySized(_) => unimplemented!(), diff --git a/src/front/spv.rs b/src/front/spv.rs index 79fdf8330..cdee75660 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -16,7 +16,7 @@ use crate::{ }; use num_traits::cast::FromPrimitive; -use std::convert::TryInto; +use std::{convert::TryInto, num::NonZeroU32}; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[spirv::Capability::Shader]; pub const SUPPORTED_EXTENSIONS: &[&str] = &[]; @@ -54,6 +54,7 @@ pub enum Error { InvalidBinding(spirv::Word), WrongFunctionResultType(spirv::Word), WrongFunctionParameterType(spirv::Word), + MissingDecoration(spirv::Decoration), BadString, IncompleteData, } @@ -125,6 +126,11 @@ fn map_storage_class(word: spirv::Word) -> Result { type MemberIndex = u32; +#[derive(Debug, Default)] +struct Block { + buffer: bool, +} + #[derive(Debug, Default)] struct Decoration { name: Option, @@ -132,6 +138,9 @@ struct Decoration { location: Option, desc_set: Option, desc_index: Option, + block: Option, + offset: Option, + array_stride: Option, } impl Decoration { @@ -310,6 +319,20 @@ impl> Parser { inst.expect(base_words + 2)?; dec.desc_index = Some(self.next()?); } + spirv::Decoration::Block => { + dec.block = Some(Block { buffer: false }); + } + spirv::Decoration::BufferBlock => { + dec.block = Some(Block { buffer: true }); + } + spirv::Decoration::Offset => { + inst.expect(base_words + 2)?; + dec.offset = Some(self.next()?); + } + spirv::Decoration::ArrayStride => { + inst.expect(base_words + 2)?; + dec.array_stride = NonZeroU32::new(self.next()?); + } other => { log::warn!("Unknown decoration {:?}", other); for _ in base_words + 1..inst.wc { @@ -1143,15 +1166,18 @@ impl> Parser { let id = self.next()?; let type_id = self.next()?; let length = self.next()?; + + let decor = self.future_decor.remove(&id); let inner = crate::TypeInner::Array { base: self.lookup_type.lookup(type_id)?.handle, size: crate::ArraySize::Static(length), + stride: decor.as_ref().and_then(|dec| dec.array_stride), }; self.lookup_type.insert( id, LookupType { handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), + name: decor.and_then(|dec| dec.name), inner, }), base_id: Some(type_id), @@ -1169,15 +1195,18 @@ impl> Parser { inst.expect(4)?; let id = self.next()?; let type_id = self.next()?; + + let decor = self.future_decor.remove(&id); let inner = crate::TypeInner::Array { base: self.lookup_type.lookup(type_id)?.handle, size: crate::ArraySize::Dynamic, + stride: decor.as_ref().and_then(|dec| dec.array_stride), }; self.lookup_type.insert( id, LookupType { handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), + name: decor.and_then(|dec| dec.name), inner, }), base_id: Some(type_id), @@ -1208,14 +1237,23 @@ impl> Parser { name: decor.name, binding, ty, + offset: decor + .offset + .ok_or(Error::MissingDecoration(spirv::Decoration::Offset))?, }); } let inner = crate::TypeInner::Struct { members }; + let decor = self.future_decor.remove(&id); + if let Some(ref decor) = decor { + if decor.block.is_some() { + // do nothing + } + } self.lookup_type.insert( id, LookupType { handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), + name: decor.and_then(|dec| dec.name), inner, }), base_id: None, diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 5e34032ff..d1d266d31 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -146,6 +146,7 @@ pub enum Error<'a> { UnknownIdent(&'a str), UnknownType(&'a str), UnknownFunction(&'a str), + MissingMemberOffset(&'a str), MutabilityViolation(&'a str), Other, } @@ -930,6 +931,7 @@ impl Parser { let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; loop { + let mut offset = !0; if lexer.skip(Token::DoubleParen('[')) { self.scopes.push(Scope::Decoration); let mut ready = true; @@ -942,7 +944,7 @@ impl Parser { ready = true; } Token::Word("offset") if ready => { - let _offset = lexer.next_uint_literal()?; //TODO + offset = lexer.next_uint_literal()?; ready = false; } other => return Err(Error::Unexpected(other)), @@ -955,6 +957,9 @@ impl Parser { Token::Paren('}') => return Ok(members), other => return Err(Error::Unexpected(other)), }; + if offset == !0 { + return Err(Error::MissingMemberOffset(name)); + } lexer.expect(Token::Separator(':'))?; let ty = self.parse_type_decl(lexer, type_arena)?; lexer.expect(Token::Separator(';'))?; @@ -962,6 +967,7 @@ impl Parser { name: Some(name.to_owned()), binding: None, ty, + offset, }); } } @@ -1056,7 +1062,11 @@ impl Parser { Token::Separator('>') => crate::ArraySize::Dynamic, other => return Err(Error::Unexpected(other)), }; - crate::TypeInner::Array { base, size } + crate::TypeInner::Array { + base, + size, + stride: None, + } } Token::Word("struct") => { let members = self.parse_struct_body(lexer, type_arena)?; diff --git a/src/lib.rs b/src/lib.rs index c75562988..c163e89a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ pub use crate::arena::{Arena, Handle}; use std::{ collections::{HashMap, HashSet}, hash::BuildHasherDefault, + num::NonZeroU32, }; pub type FastHashMap = HashMap>; @@ -53,6 +54,7 @@ pub struct StructMember { pub name: Option, pub binding: Option, pub ty: Handle, + pub offset: spirv::Word, } bitflags::bitflags! { @@ -96,6 +98,7 @@ pub enum TypeInner { Array { base: Handle, size: ArraySize, + stride: Option, }, Struct { members: Vec, From 9940460fe615fb0c695f82b96d69cef180bc7811 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Fri, 19 Jun 2020 00:08:24 +0200 Subject: [PATCH 0087/2212] Add basic tests for SPIR-V back-end writer --- src/back/spv/layout.rs | 18 ++-- src/back/spv/layout_tests.rs | 30 +----- src/back/spv/mod.rs | 7 +- src/back/spv/test_framework.rs | 58 +++++++++++ src/back/spv/writer.rs | 172 ++++++++++++++++++++++++++++++++- 5 files changed, 242 insertions(+), 43 deletions(-) create mode 100644 src/back/spv/test_framework.rs diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index 40e3e47e9..5db9a05ca 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -3,7 +3,7 @@ use spirv::*; use std::iter; impl PhysicalLayout { - pub(crate) fn new(header: &crate::Header) -> Self { + pub(super) fn new(header: &crate::Header) -> Self { let version: Word = ((header.version.0 as u32) << 16) | ((header.version.1 as u32) << 8) | header.version.2 as u32; @@ -17,7 +17,7 @@ impl PhysicalLayout { } } - pub(crate) fn in_words(&self, sink: &mut impl Extend) { + pub(super) fn in_words(&self, sink: &mut impl Extend) { sink.extend(iter::once(self.magic_number)); sink.extend(iter::once(self.version)); sink.extend(iter::once(self.generator)); @@ -27,7 +27,7 @@ impl PhysicalLayout { } impl LogicalLayout { - pub(crate) fn in_words(&self, sink: &mut impl Extend) { + pub(super) fn in_words(&self, sink: &mut impl Extend) { sink.extend(self.capabilities.iter().cloned()); sink.extend(self.extensions.iter().cloned()); sink.extend(self.ext_inst_imports.iter().cloned()); @@ -43,7 +43,7 @@ impl LogicalLayout { } impl Instruction { - pub(crate) fn new(op: Op) -> Self { + pub(super) fn new(op: Op) -> Self { Instruction { op, wc: 1, // Always start at 1 for the first word (OP + WC), @@ -53,30 +53,30 @@ impl Instruction { } } - pub(crate) fn set_type(&mut self, id: Word) { + pub(super) fn set_type(&mut self, id: Word) { assert!(self.type_id.is_none(), "Type can only be set once"); self.type_id = Some(id); self.wc += 1; } - pub(crate) fn set_result(&mut self, id: Word) { + pub(super) fn set_result(&mut self, id: Word) { assert!(self.result_id.is_none(), "Result can only be set once"); self.result_id = Some(id); self.wc += 1; } - pub(crate) fn add_operand(&mut self, operand: Word) { + pub(super) fn add_operand(&mut self, operand: Word) { self.operands.push(operand); self.wc += 1; } - pub(crate) fn add_operands(&mut self, operands: Vec) { + pub(super) fn add_operands(&mut self, operands: Vec) { for operand in operands.into_iter() { self.add_operand(operand) } } - pub(crate) fn to_words(&self, sink: &mut impl Extend) { + pub(super) fn to_words(&self, sink: &mut impl Extend) { sink.extend(Some((self.wc << 16 | self.op as u32) as u32)); sink.extend(self.type_id); sink.extend(self.result_id); diff --git a/src/back/spv/layout_tests.rs b/src/back/spv/layout_tests.rs index 697b609fa..37024b238 100644 --- a/src/back/spv/layout_tests.rs +++ b/src/back/spv/layout_tests.rs @@ -1,3 +1,4 @@ +use crate::back::spv::test_framework::*; use crate::back::spv::{helpers, Instruction, LogicalLayout, PhysicalLayout}; use crate::Header; use spirv::*; @@ -76,7 +77,7 @@ fn test_logical_layout_in_words() { for instruction in instructions { let wc = instruction.wc as usize; let instruction_output = &output[index..index + wc]; - validate_instruction(instruction_output, instruction); + validate_instruction(instruction_output, &instruction); index += wc; } } @@ -157,32 +158,7 @@ fn test_instruction_to_words() { let mut output = vec![]; instruction.to_words(&mut output); - validate_instruction(output.as_slice(), instruction); -} - -fn validate_instruction(words: &[Word], instruction: Instruction) { - let mut inst_index = 0; - let (wc, op) = ((words[inst_index] >> 16) as u16, words[inst_index] as u16); - inst_index += 1; - - assert_eq!(wc, words.len() as u16); - assert_eq!(op, instruction.op as u16); - - if instruction.type_id.is_some() { - assert_eq!(words[inst_index], instruction.type_id.unwrap()); - inst_index += 1; - } - - if instruction.result_id.is_some() { - assert_eq!(words[inst_index], instruction.result_id.unwrap()); - inst_index += 1; - } - - let mut op_index = 0; - for i in inst_index..wc as usize { - assert_eq!(words[i as usize], instruction.operands[op_index]); - op_index += 1; - } + validate_instruction(output.as_slice(), &instruction); } fn to_word(bytes: &[u8]) -> Word { diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 468307f55..4c3ca3362 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -2,6 +2,9 @@ mod helpers; mod layout; mod writer; +#[cfg(test)] +mod test_framework; + #[cfg(test)] mod layout_tests; @@ -25,7 +28,7 @@ struct PhysicalLayout { } #[derive(Default)] -pub(crate) struct LogicalLayout { +struct LogicalLayout { capabilities: Vec, extensions: Vec, ext_inst_imports: Vec, @@ -39,7 +42,7 @@ pub(crate) struct LogicalLayout { function_definitions: Vec, } -struct Instruction { +pub(self) struct Instruction { op: Op, wc: u32, type_id: Option, diff --git a/src/back/spv/test_framework.rs b/src/back/spv/test_framework.rs new file mode 100644 index 000000000..332d300a4 --- /dev/null +++ b/src/back/spv/test_framework.rs @@ -0,0 +1,58 @@ +use crate::back::spv::Instruction; +use spirv::{Op, Word}; + +pub(super) struct SpecRequirements { + pub(super) op: Op, + pub(super) wc: u32, + pub(super) type_id: bool, + pub(super) result_id: bool, + pub(super) operands: bool, +} + +/// Basic validation for checking if the instruction complies to the spec requirements +pub(super) fn validate_spec_requirements( + requirements: SpecRequirements, + instruction: &Instruction, +) { + assert_eq!(requirements.op, instruction.op); + + // Pass the assert if the minimum referred wc in the spec is met + assert!(instruction.wc >= requirements.wc); + + if requirements.type_id { + assert!(instruction.type_id.is_some()); + } + + if requirements.result_id { + assert!(instruction.result_id.is_some()); + } + + if requirements.operands { + assert!(!instruction.operands.is_empty()); + } +} + +pub(super) fn validate_instruction(words: &[Word], instruction: &Instruction) { + let mut inst_index = 0; + let (wc, op) = ((words[inst_index] >> 16) as u16, words[inst_index] as u16); + inst_index += 1; + + assert_eq!(wc, words.len() as u16); + assert_eq!(op, instruction.op as u16); + + if instruction.type_id.is_some() { + assert_eq!(words[inst_index], instruction.type_id.unwrap()); + inst_index += 1; + } + + if instruction.result_id.is_some() { + assert_eq!(words[inst_index], instruction.result_id.unwrap()); + inst_index += 1; + } + + let mut op_index = 0; + for i in inst_index..wc as usize { + assert_eq!(words[i as usize], instruction.operands[op_index]); + op_index += 1; + } +} diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4124280d2..3757f8fdd 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -646,11 +646,9 @@ impl Writer { self.physical_layout.bound = self.id_count + 1; } - fn instruction_source(&self) -> Instruction { - let version = 450u32; - + fn instruction_source(&self, source_language: SourceLanguage, version: u32) -> Instruction { let mut instruction = Instruction::new(Op::Source); - instruction.add_operand(SourceLanguage::GLSL as u32); + instruction.add_operand(source_language as u32); instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); instruction } @@ -923,7 +921,8 @@ impl Writer { .to_words(&mut self.logical_layout.ext_inst_imports); if self.writer_flags.contains(WriterFlags::DEBUG) { - self.debugs.push(self.instruction_source()); + self.debugs + .push(self.instruction_source(SourceLanguage::GLSL, 450)); } for (handle, function) in ir_module.functions.iter() { @@ -1000,3 +999,166 @@ impl Writer { words } } + +#[cfg(test)] +mod tests { + use crate::back::spv::test_framework::*; + use crate::back::spv::{Writer, WriterFlags}; + use crate::Header; + use spirv::*; + + #[test] + fn test_writer_generate_id() { + let mut writer = create_writer(); + + assert_eq!(writer.id_count, 0); + writer.generate_id(); + assert_eq!(writer.id_count, 1); + } + + #[test] + fn test_try_add_capabilities() { + let mut writer = create_writer(); + + assert_eq!(writer.capabilities.len(), 0); + writer.try_add_capabilities(&[Capability::Shader]); + assert_eq!(writer.capabilities.len(), 1); + + writer.try_add_capabilities(&[Capability::Shader]); + assert_eq!(writer.capabilities.len(), 1); + } + + #[test] + fn test_instruction_capability() { + let writer = create_writer(); + let instruction = writer.instruction_capability(Capability::Shader); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Capability, + wc: 2, + type_id: false, + result_id: false, + operands: true, + }; + + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_ext_inst_import() { + let mut writer = create_writer(); + let import_name = "GLSL.std.450"; + let instruction = writer.instruction_ext_inst_import(import_name); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ExtInstImport, + wc: 2, + type_id: false, + result_id: true, + operands: true, + }; + + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_memory_model() { + let mut writer = create_writer(); + let instruction = writer.instruction_memory_model(); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::MemoryModel, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_source() { + let writer = create_writer(); + let version = 450; + let instruction = writer.instruction_source(SourceLanguage::GLSL, version); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Source, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_label() { + let mut writer = create_writer(); + let instruction = writer.instruction_label(); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Label, + wc: 2, + type_id: false, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_function_end() { + let writer = create_writer(); + let instruction = writer.instruction_function_end(); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::FunctionEnd, + wc: 1, + type_id: false, + result_id: false, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_write_physical_layout() { + let mut writer = create_writer(); + assert_eq!(writer.physical_layout.bound, 0); + writer.write_physical_layout(); + assert_eq!(writer.physical_layout.bound, 1); + } + + fn create_writer() -> Writer { + let header = Header { + generator: 0, + version: (1, 0, 0), + }; + Writer::new(&header, WriterFlags::NONE) + } +} From 70054b7693f67e1cb110f8bd041b5599f6f02072 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 18 Jun 2020 16:51:51 -0400 Subject: [PATCH 0088/2212] Relicense under MIT+Apache2 --- Cargo.toml | 2 +- LICENSE => LICENSE-APACHE | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename LICENSE => LICENSE-APACHE (100%) diff --git a/Cargo.toml b/Cargo.toml index fab5e3df5..6a654a211 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ description = "Shader translation infrastructure" homepage = "https://github.com/gfx-rs/naga" repository = "https://github.com/gfx-rs/naga" keywords = ["shader", "SPIR-V"] -license = "MPL-2.0" +license = "MIT OR Apache-2.0" [dependencies] bitflags = "1" diff --git a/LICENSE b/LICENSE-APACHE similarity index 100% rename from LICENSE rename to LICENSE-APACHE From 84615eead3bab8a370dc85553fb9f391a6775b4e Mon Sep 17 00:00:00 2001 From: Gabriel Majeri Date: Mon, 22 Jun 2020 17:11:40 +0300 Subject: [PATCH 0089/2212] Add support for return value to SPIR-V backend (#79) * Add test for `glsl_phong_lighting` * Implement `ReturnValue` op for SPIR-V backend --- src/back/spv/writer.rs | 22 ++++++++++++++++++---- tests/convert.rs | 36 ++++++++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 3757f8fdd..ccbcffda5 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -883,10 +883,24 @@ impl Writer { output: &mut Vec, ) -> Instruction { match statement { - crate::Statement::Return { value: _ } => match function.return_type { - Some(_) => unimplemented!(), - None => Instruction::new(Op::Return), - }, + crate::Statement::Return { value } => { + match function.return_type { + Some(_) => { + let value = value.unwrap(); + + // Parse the expression + let value_expression = &function.expressions[value]; + let (value_id, _) = + self.parse_expression(ir_module, function, value_expression, output); + + // Construct the return value instruction + let mut instruction = Instruction::new(Op::ReturnValue); + instruction.add_operand(value_id); + instruction + } + None => Instruction::new(Op::Return), + } + } crate::Statement::Store { pointer, value } => { let mut instruction = Instruction::new(Op::Store); diff --git a/tests/convert.rs b/tests/convert.rs index 85bb15d7a..1048b6a61 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -1,12 +1,25 @@ +#[cfg(feature = "glsl")] +use spirv::ExecutionModel; + +fn load_test_data(name: &str) -> String { + let path = format!("{}/test-data/{}", env!("CARGO_MANIFEST_DIR"), name); + std::fs::read_to_string(path).unwrap() +} + fn load_wgsl(name: &str) -> naga::Module { - let path = format!("{}/test-data/{}.wgsl", env!("CARGO_MANIFEST_DIR"), name); - let input = std::fs::read_to_string(path).unwrap(); + let input = load_test_data(name); naga::front::wgsl::parse_str(&input).unwrap() } +#[cfg(feature = "glsl")] +fn load_glsl(name: &str, entry: &str, exec: ExecutionModel) -> naga::Module { + let input = load_test_data(name); + naga::front::glsl::parse_str(&input, entry.to_owned(), exec).unwrap() +} + #[test] fn convert_quad() { - let module = load_wgsl("quad"); + let module = load_wgsl("quad.wgsl"); { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); @@ -37,7 +50,7 @@ fn convert_quad() { #[test] fn convert_boids() { - let module = load_wgsl("boids"); + let module = load_wgsl("boids.wgsl"); { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); @@ -74,3 +87,18 @@ fn convert_boids() { msl::write_string(&module, options).unwrap(); } } + +#[cfg(feature = "glsl")] +#[test] +#[ignore] +fn convert_phong_lighting() { + let module = load_glsl("glsl_phong_lighting.frag", "main", ExecutionModel::Fragment); + + let header = naga::Header { + version: (1, 0, 0), + generator: 1234, + }; + let writer_flags = naga::back::spv::WriterFlags::empty(); + let mut w = naga::back::spv::Writer::new(&header, writer_flags); + w.write(&module); +} From 6eecea5dad8537524cbfff18fcea4611b77b08a5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 24 Jun 2020 22:55:46 -0400 Subject: [PATCH 0090/2212] First bits of IR validation --- src/arena.rs | 12 +++++++++- src/proc/mod.rs | 2 ++ src/proc/validator.rs | 56 +++++++++++++++++++++++++++++++++++++++++++ tests/convert.rs | 3 +++ 4 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 src/proc/validator.rs diff --git a/src/arena.rs b/src/arena.rs index d84da7790..d9c760f90 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -1,4 +1,4 @@ -use std::{fmt, hash, marker::PhantomData, num::NonZeroU32}; +use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32}; /// An unique index in the arena array that a handle points to. /// @@ -29,6 +29,16 @@ impl PartialEq for Handle { } } impl Eq for Handle {} +impl PartialOrd for Handle { + fn partial_cmp(&self, other: &Self) -> Option { + self.index.partial_cmp(&other.index) + } +} +impl Ord for Handle { + fn cmp(&self, other: &Self) -> Ordering { + self.index.cmp(&other.index) + } +} impl fmt::Debug for Handle { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "Handle({})", self.index) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index e4b181a69..18362d183 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,4 +1,6 @@ mod interface; mod typifier; +mod validator; pub use typifier::{check_constant_types, ResolveError, Typifier, UnexpectedConstantTypeError}; +pub use validator::{ValidationError, Validator}; diff --git a/src/proc/validator.rs b/src/proc/validator.rs new file mode 100644 index 000000000..613357e55 --- /dev/null +++ b/src/proc/validator.rs @@ -0,0 +1,56 @@ +use crate::arena::Handle; + +pub struct Validator {} + +#[derive(Clone, Debug)] +pub enum ValidationError { + /// The type width is not supported. + InvalidTypeWidth(crate::ScalarKind, crate::Bytes), + /// A type handle can not be resolved. + UnresolvedType(Handle), + /// There are instructions after `return`/`break`/`continue`. + InvalidControlFlowExitTail, +} + +impl Validator { + pub fn new() -> Self { + Validator {} + } + + pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { + for (handle, ty) in module.types.iter() { + use crate::TypeInner as Ti; + match ty.inner { + Ti::Scalar { kind, width } + | Ti::Vector { kind, width, .. } + | Ti::Matrix { kind, width, .. } => { + if width != 32 { + return Err(ValidationError::InvalidTypeWidth(kind, width)); + } + } + Ti::Pointer { base, class: _ } => { + if base >= handle { + return Err(ValidationError::UnresolvedType(base)); + } + } + Ti::Array { base, .. } => { + if base >= handle { + return Err(ValidationError::UnresolvedType(base)); + } + } + Ti::Struct { ref members } => { + //TODO: check that offsets are not intersecting? + for member in members { + if member.ty >= handle { + return Err(ValidationError::UnresolvedType(member.ty)); + } + } + } + Ti::Image { .. } => {} + Ti::Sampler { comparison: _ } => {} + } + } + + Ok(()) + } +} diff --git a/tests/convert.rs b/tests/convert.rs index 1048b6a61..5a1ed8bd0 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -20,6 +20,7 @@ fn load_glsl(name: &str, entry: &str, exec: ExecutionModel) -> naga::Module { #[test] fn convert_quad() { let module = load_wgsl("quad.wgsl"); + naga::proc::Validator::new().validate(&module).unwrap(); { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); @@ -51,6 +52,7 @@ fn convert_quad() { #[test] fn convert_boids() { let module = load_wgsl("boids.wgsl"); + naga::proc::Validator::new().validate(&module).unwrap(); { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); @@ -93,6 +95,7 @@ fn convert_boids() { #[ignore] fn convert_phong_lighting() { let module = load_glsl("glsl_phong_lighting.frag", "main", ExecutionModel::Fragment); + naga::proc::Validator::new().validate(&module).unwrap(); let header = naga::Header { version: (1, 0, 0), From e0a1e80fb54912548e5ca444b0a48eaae30ad791 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Jun 2020 00:34:02 -0400 Subject: [PATCH 0091/2212] Remove spirv-headers use from IR, make it optional --- Cargo.toml | 2 +- README.md | 6 +- examples/convert.rs | 117 ++++++++++++++++---------------- src/back/mod.rs | 1 + src/back/msl.rs | 138 +++++++++++++++++++------------------- src/back/spv/writer.rs | 129 ++++++++++++++++++++++------------- src/front/glsl/helpers.rs | 40 +++++++---- src/front/glsl/mod.rs | 80 +++++++--------------- src/front/mod.rs | 1 + src/front/spv.rs | 74 +++++++++++++++----- src/front/wgsl.rs | 47 +++++++------ src/lib.rs | 74 ++++++++++++++++---- tests/convert.rs | 13 ++-- 13 files changed, 418 insertions(+), 304 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6a654a211..10c8f94ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ bitflags = "1" fxhash = "0.2" log = "0.4" num-traits = "0.2" -spirv = { package = "spirv_headers", version = "1.4.2" } +spirv = { package = "spirv_headers", version = "1.4.2", optional = true } glsl = { version = "4", optional = true } [features] diff --git a/README.md b/README.md index ee1a9261c..0643c94a5 100644 --- a/README.md +++ b/README.md @@ -3,16 +3,16 @@ [![Matrix](https://img.shields.io/badge/Matrix-%23naga%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#naga:matrix.org) [![Crates.io](https://img.shields.io/crates/v/naga.svg?label=naga)](https://crates.io/crates/naga) [![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga) -[![Build Status](https://travis-ci.org/gfx-rs/naga.svg?branch=master)](https://travis-ci.org/gfx-rs/naga) +[![Build Status](https://github.com/gfx-rs/naga/workflows/pipeline/badge.svg)](https://github.com/gfx-rs/naga/actions) -This is an experimental shader translation library for the needs of gfx-rs project and WebGPU. It's meant to provide a safe and performant way of converting to and from SPIR-V. +This is an experimental shader translation library for the needs of gfx-rs project and WebGPU. ## Supported end-points Front-end | Status | Notes | --------------- | ------------------ | ----- | SPIR-V (binary) | :construction: | | -WGSL (Tint) | :construction: | | +WGSL | :construction: | | GLSL (Vulkan) | :construction: | | Rust | | | diff --git a/examples/convert.rs b/examples/convert.rs index 722e811c6..7a2b7cfa0 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -29,12 +29,13 @@ fn main() { println!("Call with "); return; } - let ext = Path::new(&args[1]) + let module = match Path::new(&args[1]) .extension() .expect("Input has no extension?") .to_str() - .unwrap(); - let module = match ext { + .unwrap() + { + #[cfg(feature = "spirv")] "spv" => { let input = fs::read(&args[1]).unwrap(); naga::front::spv::parse_u8_slice(&input).unwrap() @@ -46,28 +47,20 @@ fn main() { #[cfg(feature = "glsl")] "vert" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main".to_string(), spirv::ExecutionModel::Vertex) + naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Vertex) .unwrap() } #[cfg(feature = "glsl")] "frag" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str( - &input, - "main".to_string(), - spirv::ExecutionModel::Fragment, - ) - .unwrap() + naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Fragment) + .unwrap() } #[cfg(feature = "glsl")] "comp" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str( - &input, - "main".to_string(), - spirv::ExecutionModel::GLCompute, - ) - .unwrap() + naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Compute) + .unwrap() } other => panic!("Unknown input extension: {}", other), }; @@ -83,50 +76,60 @@ fn main() { Err(_) => Parameters::default(), }; - if args[2].ends_with(".metal") { - use naga::back::msl; - let mut binding_map = msl::BindingMap::default(); - for (key, value) in params.metal_bindings { - binding_map.insert( - msl::BindSource { - set: key.set, - binding: key.binding, - }, - msl::BindTarget { - buffer: value.buffer, - texture: value.texture, - sampler: value.sampler, - mutable: value.mutable, - }, - ); - } - let options = msl::Options { - binding_map: &binding_map, - }; - let msl = msl::write_string(&module, options).unwrap(); - fs::write(&args[2], msl).unwrap(); - } else if args[2].ends_with(".spv") { - use naga::back::spv; - - let debug_flag = args.get(3).map_or(spv::WriterFlags::DEBUG, |arg| { - if arg.parse().unwrap() { - spv::WriterFlags::DEBUG - } else { - spv::WriterFlags::NONE + match Path::new(&args[2]) + .extension() + .expect("Output has no extension?") + .to_str() + .unwrap() + { + "metal" => { + use naga::back::msl; + let mut binding_map = msl::BindingMap::default(); + for (key, value) in params.metal_bindings { + binding_map.insert( + msl::BindSource { + set: key.set, + binding: key.binding, + }, + msl::BindTarget { + buffer: value.buffer, + texture: value.texture, + sampler: value.sampler, + mutable: value.mutable, + }, + ); } - }); + let options = msl::Options { + binding_map: &binding_map, + }; + let msl = msl::write_string(&module, options).unwrap(); + fs::write(&args[2], msl).unwrap(); + } + #[cfg(feature = "spirv")] + "spv" => { + use naga::back::spv; - let spv = spv::Writer::new(&module.header, debug_flag).write(&module); - - let bytes = spv - .iter() - .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { - v.extend_from_slice(&w.to_le_bytes()); - v + let debug_flag = args.get(3).map_or(spv::WriterFlags::DEBUG, |arg| { + if arg.parse().unwrap() { + spv::WriterFlags::DEBUG + } else { + spv::WriterFlags::NONE + } }); - fs::write(&args[2], bytes.as_slice()).unwrap(); - } else { - panic!("Unknown output: {:?}", args[2]); + let spv = spv::Writer::new(&module.header, debug_flag).write(&module); + + let bytes = spv + .iter() + .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { + v.extend_from_slice(&w.to_le_bytes()); + v + }); + + fs::write(&args[2], bytes.as_slice()).unwrap(); + } + other => { + panic!("Unknown output extension: {}", other); + } } } diff --git a/src/back/mod.rs b/src/back/mod.rs index e2b4919f6..8e310f7a8 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -1,2 +1,3 @@ pub mod msl; +#[cfg(feature = "spirv")] pub mod spv; diff --git a/src/back/msl.rs b/src/back/msl.rs index ed4a47d7c..acd2a1323 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -32,20 +32,17 @@ pub struct BindTarget { #[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub struct BindSource { - pub set: spirv::Word, - pub binding: spirv::Word, + pub set: u32, + pub binding: u32, } pub type BindingMap = FastHashMap; enum ResolvedBinding { - BuiltIn(spirv::BuiltIn), - Attribute(spirv::Word), - Color(spirv::Word), - User { - prefix: &'static str, - index: spirv::Word, - }, + BuiltIn(crate::BuiltIn), + Attribute(u32), + Color(u32), + User { prefix: &'static str, index: u32 }, Resource(BindTarget), } @@ -61,10 +58,11 @@ impl Display for Level { } } +// Note: some of these should be removed in favor of proper IR validation. + #[derive(Debug)] pub enum Error { Format(FmtError), - UnsupportedExecutionModel(spirv::ExecutionModel), UnexpectedLocation, MixedExecutionModels(crate::Handle), MissingBinding(crate::Handle), @@ -73,7 +71,6 @@ pub enum Error { MutabilityViolation(crate::Handle), BadName(String), UnexpectedGlobalType(crate::Handle), - UnimplementedBuiltIn(spirv::BuiltIn), UnimplementedBindTarget(BindTarget), UnexpectedIndexing(crate::TypeInner), UnsupportedCompose(crate::Handle), @@ -86,8 +83,6 @@ pub enum Error { UnsupportedExpression(crate::Expression), UnableToReturnValue(crate::Handle), UnsupportedStatement(crate::Statement), - UnsupportedDim(spirv::Dim), - ExecutionModelReturnType(spirv::ExecutionModel, crate::Handle), AccessIndexExceedsStaticLength(u32, u32), } @@ -269,9 +264,9 @@ impl<'a> TypedGlobalVariable<'a> { let var = &self.module.global_variables[self.handle]; let name = var.name.or_index(self.handle); let (space_qualifier, reference) = match var.class { - spirv::StorageClass::Uniform - | spirv::StorageClass::UniformConstant - | spirv::StorageClass::StorageBuffer => { + crate::StorageClass::Constant + | crate::StorageClass::Uniform + | crate::StorageClass::StorageBuffer => { let space = if self.usage.contains(crate::GlobalUse::STORE) { "device " } else { @@ -286,10 +281,10 @@ impl<'a> TypedGlobalVariable<'a> { match ty.inner { crate::TypeInner::Pointer { base, class } => { let ty_handle = match class { - spirv::StorageClass::Input - | spirv::StorageClass::Output - | spirv::StorageClass::Uniform - | spirv::StorageClass::UniformConstant => base, + crate::StorageClass::Constant + | crate::StorageClass::Input + | crate::StorageClass::Output + | crate::StorageClass::Uniform => base, _ => var.ty, }; let ty_name = self.module.types[ty_handle].name.or_index(ty_handle); @@ -312,12 +307,26 @@ impl ResolvedBinding { fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { match *self { ResolvedBinding::BuiltIn(built_in) => { + use crate::BuiltIn as Bi; let name = match built_in { - spirv::BuiltIn::ClipDistance => "clip_distance", - spirv::BuiltIn::GlobalInvocationId => "thread_position_in_grid", - spirv::BuiltIn::PointSize => "point_size", - spirv::BuiltIn::Position => "position", - _ => return Err(Error::UnimplementedBuiltIn(built_in)), + // vertex + Bi::BaseInstance => "base_instance", + Bi::BaseVertex => "base_vertex", + Bi::ClipDistance => "clip_distance", + Bi::InstanceIndex => "instance_id", + Bi::PointSize => "point_size", + Bi::Position => "position", + Bi::VertexIndex => "vertex_id", + // fragment + Bi::FragCoord => "position", + Bi::FragDepth => "depth(any)", + Bi::FrontFacing => "front_facing", + Bi::SampleIndex => "sample_id", + // compute + Bi::GlobalInvocationId => "thread_position_in_grid", + Bi::LocalInvocationId => "thread_position_in_threadgroup", + Bi::LocalInvocationIndex => "thread_index_in_threadgroup", + Bi::WorkGroupId => "threadgroup_position_in_grid", }; Ok(formatter.write_str(name)?) } @@ -492,7 +501,7 @@ impl Writer { let var = &module.global_variables[handle]; let inner = &module.types[var.ty].inner; match var.class { - spirv::StorageClass::Output => { + crate::StorageClass::Output => { if GLOBAL_POINTERS { if let crate::TypeInner::Pointer { base, .. } = *inner { let base_inner = &module.types[base].inner; @@ -505,7 +514,7 @@ impl Writer { } write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; } - spirv::StorageClass::Input => { + crate::StorageClass::Input => { if let Some(crate::Binding::Location(_)) = var.binding { write!(self.out, "{}.", LOCATION_INPUT_STRUCT_NAME)?; } @@ -835,16 +844,13 @@ impl Writer { )?; } crate::TypeInner::Pointer { base, class } => { + use crate::StorageClass as Sc; let base_name = module.types[base].name.or_index(base); let class_name = match class { - spirv::StorageClass::Input | spirv::StorageClass::Output => continue, - spirv::StorageClass::Uniform | spirv::StorageClass::UniformConstant => { - "constant" - } - other => { - log::warn!("Unexpected pointer class {:?}", other); - "" - } + Sc::Input | Sc::Output => continue, + Sc::Constant | Sc::Uniform => "constant", + Sc::StorageBuffer => "device", + Sc::Private | Sc::Function | Sc::WorkGroup => "", }; write!(self.out, "typedef {} {} *{}", class_name, base_name, name)?; } @@ -882,11 +888,10 @@ impl Writer { crate::TypeInner::Image { base, dim, flags } => { let base_name = module.types[base].name.or_index(base); let dim = match dim { - spirv::Dim::Dim1D => "1d", - spirv::Dim::Dim2D => "2d", - spirv::Dim::Dim3D => "3d", - spirv::Dim::DimCube => "Cube", - other => return Err(Error::UnsupportedDim(other)), + crate::ImageDimension::D1 => "1d", + crate::ImageDimension::D2 => "2d", + crate::ImageDimension::D3 => "3d", + crate::ImageDimension::Cube => "Cube", }; let access = if flags.contains(crate::ImageFlags::SAMPLED) { if flags.intersects(crate::ImageFlags::CAN_STORE) { @@ -923,16 +928,16 @@ impl Writer { for (fun_handle, fun) in module.functions.iter() { let fun_name = fun.name.or_index(fun_handle); // find the entry point(s) and inputs/outputs - let mut exec_model = None; + let mut shader_stage = None; let mut last_used_global = None; for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { match var.class { - spirv::StorageClass::Input => { + crate::StorageClass::Input => { if let Some(crate::Binding::Location(_)) = var.binding { continue; } } - spirv::StorageClass::Output => continue, + crate::StorageClass::Output => continue, _ => {} } if !usage.is_empty() { @@ -941,46 +946,43 @@ impl Writer { } for ep in module.entry_points.iter() { if ep.function == fun_handle { - if exec_model.is_some() { - if exec_model != Some(ep.exec_model) { + if shader_stage.is_some() { + if shader_stage != Some(ep.stage) { return Err(Error::MixedExecutionModels(fun_handle)); } } else { - exec_model = Some(ep.exec_model); + shader_stage = Some(ep.stage); } } } let output_name = fun.name.or_index(OutputStructIndex(fun_handle)); // make dedicated input/output structs - if let Some(em) = exec_model { - if let Some(return_type) = fun.return_type { - return Err(Error::ExecutionModelReturnType(em, return_type)); - } - let (em_str, in_mode, out_mode) = match em { - spirv::ExecutionModel::Vertex => ( + if let Some(stage) = shader_stage { + assert_eq!(fun.return_type, None); + let (em_str, in_mode, out_mode) = match stage { + crate::ShaderStage::Vertex => ( "vertex", LocationMode::VertexInput, LocationMode::Intermediate, ), - spirv::ExecutionModel::Fragment => ( + crate::ShaderStage::Fragment => ( "fragment", LocationMode::Intermediate, LocationMode::FragmentOutput, ), - spirv::ExecutionModel::GLCompute => { + crate::ShaderStage::Compute => { ("kernel", LocationMode::Uniform, LocationMode::Uniform) } - _ => return Err(Error::UnsupportedExecutionModel(em)), }; let location_input_name = fun.name.or_index(InputStructIndex(fun_handle)); - if em != spirv::ExecutionModel::GLCompute { + if stage != crate::ShaderStage::Compute { writeln!(self.out, "struct {} {{", location_input_name)?; for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { - if var.class != spirv::StorageClass::Input + if var.class != crate::StorageClass::Input || !usage.contains(crate::GlobalUse::LOAD) { continue; @@ -1027,7 +1029,7 @@ impl Writer { for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { - if var.class != spirv::StorageClass::Output + if var.class != crate::StorageClass::Output || !usage.contains(crate::GlobalUse::STORE) { continue; @@ -1084,24 +1086,24 @@ impl Writer { for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { - if usage.is_empty() || var.class == spirv::StorageClass::Output { + if usage.is_empty() || var.class == crate::StorageClass::Output { continue; } - if var.class == spirv::StorageClass::Input { + if var.class == crate::StorageClass::Input { if let Some(crate::Binding::Location(_)) = var.binding { // location inputs are put into a separate struct continue; } } - let loc_mode = match (em, var.class) { - (spirv::ExecutionModel::Vertex, spirv::StorageClass::Input) => { + let loc_mode = match (stage, var.class) { + (crate::ShaderStage::Vertex, crate::StorageClass::Input) => { LocationMode::VertexInput } - (spirv::ExecutionModel::Vertex, spirv::StorageClass::Output) - | (spirv::ExecutionModel::Fragment, spirv::StorageClass::Input) => { + (crate::ShaderStage::Vertex, crate::StorageClass::Output) + | (crate::ShaderStage::Fragment, crate::StorageClass::Input) => { LocationMode::Intermediate } - (spirv::ExecutionModel::Fragment, spirv::StorageClass::Output) => { + (crate::ShaderStage::Fragment, crate::StorageClass::Output) => { LocationMode::FragmentOutput } _ => LocationMode::Uniform, @@ -1143,12 +1145,12 @@ impl Writer { writeln!(self.out, ") {{")?; // write down function body - let has_output = match exec_model { - Some(spirv::ExecutionModel::Vertex) | Some(spirv::ExecutionModel::Fragment) => { + let has_output = match shader_stage { + Some(crate::ShaderStage::Vertex) | Some(crate::ShaderStage::Fragment) => { writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?; true } - _ => false, + Some(crate::ShaderStage::Compute) | None => false, }; for (local_handle, local) in fun.local_variables.iter() { let ty_name = module.types[local.ty].name.or_index(local.ty); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index ccbcffda5..95ce6ba5f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,7 +1,7 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ -use crate::back::spv::{helpers, Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; +use super::{helpers, Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; use crate::{FastHashMap, FastHashSet}; -use spirv::*; +use spirv::{Op, Word}; trait LookupHelper { type Target; @@ -45,7 +45,7 @@ pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, id_count: u32, - capabilities: FastHashSet, + capabilities: FastHashSet, debugs: Vec, annotations: Vec, writer_flags: WriterFlags, @@ -81,13 +81,13 @@ impl Writer { self.id_count } - fn try_add_capabilities(&mut self, capabilities: &[Capability]) { + fn try_add_capabilities(&mut self, capabilities: &[spirv::Capability]) { for capability in capabilities.iter() { self.capabilities.insert(*capability); } } - fn instruction_capability(&self, capability: Capability) -> Instruction { + fn instruction_capability(&self, capability: spirv::Capability) -> Instruction { let mut instruction = Instruction::new(Op::Capability); instruction.add_operand(capability as u32); instruction @@ -103,8 +103,8 @@ impl Writer { fn instruction_memory_model(&mut self) -> Instruction { let mut instruction = Instruction::new(Op::MemoryModel); - let addressing_model = AddressingModel::Logical; - let memory_model = MemoryModel::GLSL450; + let addressing_model = spirv::AddressingModel::Logical; + let memory_model = spirv::MemoryModel::GLSL450; self.try_add_capabilities(addressing_model.required_capabilities()); self.try_add_capabilities(memory_model.required_capabilities()); @@ -124,7 +124,13 @@ impl Writer { .lookup_id(entry_point.function) .unwrap(); - instruction.add_operand(entry_point.exec_model as u32); + let exec_model = match entry_point.stage { + crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, + crate::ShaderStage::Fragment => spirv::ExecutionModel::Fragment, + crate::ShaderStage::Compute => spirv::ExecutionModel::GLCompute, + }; + + instruction.add_operand(exec_model as u32); instruction.add_operand(function_id); if self.writer_flags.contains(WriterFlags::DEBUG) { @@ -152,11 +158,11 @@ impl Writer { } } - self.try_add_capabilities(entry_point.exec_model.required_capabilities()); - match entry_point.exec_model { - ExecutionModel::Vertex => {} - ExecutionModel::Fragment => { - let execution_mode = ExecutionMode::OriginUpperLeft; + self.try_add_capabilities(exec_model.required_capabilities()); + match entry_point.stage { + crate::ShaderStage::Vertex => {} + crate::ShaderStage::Fragment => { + let execution_mode = spirv::ExecutionMode::OriginUpperLeft; self.try_add_capabilities(execution_mode.required_capabilities()); let mut execution_mode_instruction = Instruction::new(Op::ExecutionMode); @@ -164,7 +170,7 @@ impl Writer { execution_mode_instruction.add_operand(execution_mode as u32); execution_mode_instruction.to_words(&mut self.logical_layout.execution_modes); } - _ => unimplemented!(), + crate::ShaderStage::Compute => {} } instruction @@ -339,7 +345,7 @@ impl Writer { if let Some(array_stride) = stride { let mut instruction = Instruction::new(Op::Decorate); instruction.add_operand(id); - instruction.add_operand(Decoration::ArrayStride as u32); + instruction.add_operand(spirv::Decoration::ArrayStride as u32); instruction.add_operand(array_stride.get()); self.annotations.push(instruction); } @@ -372,6 +378,12 @@ impl Writer { } crate::TypeInner::Image { base, dim, flags } => { let type_id = self.get_type_id(arena, base); + let dim = match dim { + crate::ImageDimension::D1 => spirv::Dim::Dim1D, + crate::ImageDimension::D2 => spirv::Dim::Dim2D, + crate::ImageDimension::D3 => spirv::Dim::Dim2D, + crate::ImageDimension::Cube => spirv::Dim::DimCube, + }; self.try_add_capabilities(dim.required_capabilities()); instruction = Instruction::new(Op::TypeImage); @@ -394,19 +406,13 @@ impl Writer { 0 }); - if let Dim::DimSubpassData = dim { - instruction.add_operand(2); - instruction.add_operand(ImageFormat::Unknown as u32); + instruction.add_operand(if flags.contains(crate::ImageFlags::SAMPLED) { + 1 } else { - instruction.add_operand(if flags.contains(crate::ImageFlags::SAMPLED) { - 1 - } else { - 0 - }); - - // TODO Defaults to Unknown, not yet in IR - instruction.add_operand(ImageFormat::Unknown as u32); - }; + 0 + }); + // TODO Defaults to Unknown, not yet in IR + instruction.add_operand(spirv::ImageFormat::Unknown as u32); instruction.add_operand( if flags.contains(crate::ImageFlags::CAN_STORE) @@ -553,7 +559,7 @@ impl Writer { &mut self, arena: &crate::Arena, handle: crate::Handle, - class: StorageClass, + class: spirv::StorageClass, ) -> Word { let ty = &arena[handle]; let type_id = self.get_type_id(arena, handle); @@ -587,13 +593,23 @@ impl Writer { let mut instruction = Instruction::new(Op::Variable); let id = self.generate_id(); - self.try_add_capabilities(global_variable.class.required_capabilities()); + let class = match global_variable.class { + crate::StorageClass::Constant => spirv::StorageClass::UniformConstant, + crate::StorageClass::Function => spirv::StorageClass::Function, + crate::StorageClass::Input => spirv::StorageClass::Input, + crate::StorageClass::Output => spirv::StorageClass::Output, + crate::StorageClass::Private => spirv::StorageClass::Private, + crate::StorageClass::StorageBuffer => spirv::StorageClass::StorageBuffer, + crate::StorageClass::Uniform => spirv::StorageClass::Uniform, + crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, + }; + self.try_add_capabilities(class.required_capabilities()); - let pointer_id = self.get_pointer_id(arena, global_variable.ty, global_variable.class); + let pointer_id = self.get_pointer_id(arena, global_variable.ty, class); instruction.set_type(pointer_id); instruction.set_result(id); - instruction.add_operand(global_variable.class as u32); + instruction.add_operand(class as u32); if self.writer_flags.contains(WriterFlags::DEBUG) { let mut debug_instruction = Instruction::new(Op::Name); @@ -608,30 +624,46 @@ impl Writer { crate::Binding::Location(location) => { let mut instruction = Instruction::new(Op::Decorate); instruction.add_operand(id); - instruction.add_operand(Decoration::Location as u32); + instruction.add_operand(spirv::Decoration::Location as u32); instruction.add_operand(*location); self.annotations.push(instruction); } crate::Binding::Descriptor { set, binding } => { let mut set_instruction = Instruction::new(Op::Decorate); set_instruction.add_operand(id); - set_instruction.add_operand(Decoration::DescriptorSet as u32); + set_instruction.add_operand(spirv::Decoration::DescriptorSet as u32); set_instruction.add_operand(*set); self.annotations.push(set_instruction); let mut binding_instruction = Instruction::new(Op::Decorate); binding_instruction.add_operand(id); - binding_instruction.add_operand(Decoration::Binding as u32); + binding_instruction.add_operand(spirv::Decoration::Binding as u32); binding_instruction.add_operand(*binding); self.annotations.push(binding_instruction); } crate::Binding::BuiltIn(built_in) => { - let built_in_u32: u32 = unsafe { std::mem::transmute(*built_in) }; + let built_in = match built_in { + crate::BuiltIn::BaseInstance => spirv::BuiltIn::BaseInstance, + crate::BuiltIn::BaseVertex => spirv::BuiltIn::BaseVertex, + crate::BuiltIn::ClipDistance => spirv::BuiltIn::ClipDistance, + crate::BuiltIn::InstanceIndex => spirv::BuiltIn::InstanceIndex, + crate::BuiltIn::Position => spirv::BuiltIn::Position, + crate::BuiltIn::VertexIndex => spirv::BuiltIn::VertexIndex, + crate::BuiltIn::PointSize => spirv::BuiltIn::PointSize, + crate::BuiltIn::FragCoord => spirv::BuiltIn::FragCoord, + crate::BuiltIn::FrontFacing => spirv::BuiltIn::FrontFacing, + crate::BuiltIn::SampleIndex => spirv::BuiltIn::SampleId, + crate::BuiltIn::FragDepth => spirv::BuiltIn::FragDepth, + crate::BuiltIn::GlobalInvocationId => spirv::BuiltIn::GlobalInvocationId, + crate::BuiltIn::LocalInvocationId => spirv::BuiltIn::LocalInvocationId, + crate::BuiltIn::LocalInvocationIndex => spirv::BuiltIn::LocalInvocationIndex, + crate::BuiltIn::WorkGroupId => spirv::BuiltIn::WorkgroupId, + }; let mut instruction = Instruction::new(Op::Decorate); instruction.add_operand(id); - instruction.add_operand(Decoration::BuiltIn as u32); - instruction.add_operand(built_in_u32); + instruction.add_operand(spirv::Decoration::BuiltIn as u32); + instruction.add_operand(built_in as u32); self.annotations.push(instruction); } } @@ -646,7 +678,11 @@ impl Writer { self.physical_layout.bound = self.id_count + 1; } - fn instruction_source(&self, source_language: SourceLanguage, version: u32) -> Instruction { + fn instruction_source( + &self, + source_language: spirv::SourceLanguage, + version: u32, + ) -> Instruction { let mut instruction = Instruction::new(Op::Source); instruction.add_operand(source_language as u32); instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); @@ -696,9 +732,8 @@ impl Writer { instruction.set_type(return_type_id); instruction.set_result(id); - let control_u32: Word = unsafe { std::mem::transmute(function.control) }; - - instruction.add_operand(control_u32); + let control = spirv::FunctionControl::empty(); + instruction.add_operand(control.bits()); let mut parameter_type_ids = Vec::with_capacity(function.parameter_types.len()); for parameter_type in function.parameter_types.iter() { @@ -863,12 +898,12 @@ impl Writer { let ty = &ir_module.types[var.ty]; let pointer_id = - self.get_pointer_id(&ir_module.types, var.ty, StorageClass::Function); + self.get_pointer_id(&ir_module.types, var.ty, spirv::StorageClass::Function); let mut instruction = Instruction::new(Op::Variable); instruction.set_type(pointer_id); instruction.set_result(id); - instruction.add_operand(StorageClass::Function as u32); + instruction.add_operand(spirv::StorageClass::Function as u32); (id, &ty.inner) } _ => unimplemented!("{:?}", expression), @@ -936,7 +971,7 @@ impl Writer { if self.writer_flags.contains(WriterFlags::DEBUG) { self.debugs - .push(self.instruction_source(SourceLanguage::GLSL, 450)); + .push(self.instruction_source(spirv::SourceLanguage::GLSL, 450)); } for (handle, function) in ir_module.functions.iter() { @@ -1035,17 +1070,17 @@ mod tests { let mut writer = create_writer(); assert_eq!(writer.capabilities.len(), 0); - writer.try_add_capabilities(&[Capability::Shader]); + writer.try_add_capabilities(&[spirv::Capability::Shader]); assert_eq!(writer.capabilities.len(), 1); - writer.try_add_capabilities(&[Capability::Shader]); + writer.try_add_capabilities(&[spirv::Capability::Shader]); assert_eq!(writer.capabilities.len(), 1); } #[test] fn test_instruction_capability() { let writer = create_writer(); - let instruction = writer.instruction_capability(Capability::Shader); + let instruction = writer.instruction_capability(spirv::Capability::Shader); let mut output = vec![]; let requirements = SpecRequirements { diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs index 1bd8dc889..8377c057a 100644 --- a/src/front/glsl/helpers.rs +++ b/src/front/glsl/helpers.rs @@ -1,6 +1,5 @@ -use crate::{Arena, ImageFlags, ScalarKind, Type, TypeInner, VectorSize}; +use crate::{Arena, ImageDimension, ImageFlags, ScalarKind, Type, TypeInner, VectorSize}; use glsl::syntax::{BinaryOp, TypeSpecifierNonArray}; -use spirv::Dim; pub fn glsl_to_spirv_binary_op(op: BinaryOp) -> crate::BinaryOperator { match op { @@ -253,21 +252,34 @@ pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> }); let (dim, flags) = match &ty_name.0[(t_pos + 7)..] { - "1D" => (Dim::Dim1D, ImageFlags::SAMPLED), - "2D" => (Dim::Dim2D, ImageFlags::SAMPLED), - "3D" => (Dim::Dim3D, ImageFlags::SAMPLED), - "1DArray" => (Dim::Dim1D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), - "2DArray" => (Dim::Dim2D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), - "3DArray" => (Dim::Dim3D, ImageFlags::SAMPLED | ImageFlags::ARRAYED), - "2DMS" => (Dim::Dim2D, ImageFlags::SAMPLED | ImageFlags::MULTISAMPLED), + "1D" => (ImageDimension::D1, ImageFlags::SAMPLED), + "2D" => (ImageDimension::D2, ImageFlags::SAMPLED), + "3D" => (ImageDimension::D3, ImageFlags::SAMPLED), + "1DArray" => ( + ImageDimension::D1, + ImageFlags::SAMPLED | ImageFlags::ARRAYED, + ), + "2DArray" => ( + ImageDimension::D2, + ImageFlags::SAMPLED | ImageFlags::ARRAYED, + ), + "3DArray" => ( + ImageDimension::D3, + ImageFlags::SAMPLED | ImageFlags::ARRAYED, + ), + "2DMS" => ( + ImageDimension::D2, + ImageFlags::SAMPLED | ImageFlags::MULTISAMPLED, + ), "2DMSArray" => ( - Dim::Dim2D, + ImageDimension::D2, ImageFlags::SAMPLED | ImageFlags::ARRAYED | ImageFlags::MULTISAMPLED, ), - "2DRect" => (Dim::DimRect, ImageFlags::SAMPLED), - "Cube" => (Dim::DimCube, ImageFlags::SAMPLED), - "CubeArray" => (Dim::DimCube, ImageFlags::SAMPLED | ImageFlags::ARRAYED), - "Buffer" => (Dim::DimBuffer, ImageFlags::SAMPLED), + "Cube" => (ImageDimension::Cube, ImageFlags::SAMPLED), + "CubeArray" => ( + ImageDimension::Cube, + ImageFlags::SAMPLED | ImageFlags::ARRAYED, + ), _ => panic!(), }; diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 1cd44b0c3..0414a6731 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,14 +1,13 @@ use crate::{ - Arena, ArraySize, BinaryOperator, Binding, Constant, ConstantInner, EntryPoint, Expression, - FastHashMap, Function, GlobalVariable, Handle, Header, LocalVariable, Module, ScalarKind, - StructMember, Type, TypeInner, VectorSize, + Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Constant, ConstantInner, EntryPoint, + Expression, FastHashMap, Function, GlobalVariable, Handle, Header, LocalVariable, Module, + ScalarKind, ShaderStage, StorageClass, StructMember, Type, TypeInner, VectorSize, }; use glsl::{ parser::{Parse, ParseError}, syntax::*, }; use parser::{Token, TokenMetadata}; -use spirv::{BuiltIn, ExecutionModel, StorageClass}; use std::fmt; mod helpers; @@ -157,11 +156,11 @@ struct Parser<'a> { constants: Arena, functions: Arena, function_lookup: FastHashMap>, - exec_model: ExecutionModel, + shader_stage: ShaderStage, } impl<'a> Parser<'a> { - pub fn new(source: &'a str, exec_model: ExecutionModel) -> Result { + pub fn new(source: &'a str, shader_stage: ShaderStage) -> Result { Ok(Self { source, types: Arena::new(), @@ -170,7 +169,7 @@ impl<'a> Parser<'a> { constants: Arena::new(), functions: Arena::new(), function_lookup: FastHashMap::default(), - exec_model, + shader_stage, }) } @@ -306,7 +305,7 @@ impl<'a> Parser<'a> { global_variables: self.globals, functions: self.functions, entry_points: vec![EntryPoint { - exec_model: self.exec_model, + stage: self.shader_stage, function: entry_point.unwrap(), name: entry, }], @@ -418,7 +417,6 @@ impl<'a> Parser<'a> { let handle = self.functions.append(Function { name: Some(name.clone()), - control: spirv::FunctionControl::NONE, parameter_types, return_type: ty, global_usage: vec![], @@ -638,20 +636,6 @@ impl<'a> Parser<'a> { }), })) } - "gl_DrawID" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::DrawIndex)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 32, - }, - }), - })) - } "gl_BaseVertex" => { Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { name: Some(name), @@ -683,9 +667,9 @@ impl<'a> Parser<'a> { "gl_Position" => { Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { name: Some(name), - class: match self.exec_model { - ExecutionModel::Vertex => StorageClass::Output, - ExecutionModel::Fragment => StorageClass::Input, + class: match self.shader_stage { + ShaderStage::Vertex => StorageClass::Output, + ShaderStage::Fragment => StorageClass::Input, _ => panic!(), }, binding: Some(Binding::BuiltIn(BuiltIn::Position)), @@ -727,20 +711,6 @@ impl<'a> Parser<'a> { }), })) } - "gl_CullDistance" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Output, - binding: Some(Binding::BuiltIn(BuiltIn::CullDistance)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 32, - }, - }), - })) - } other => { if let Some(global) = self.globals_lookup.get(other) { match *global { @@ -1131,16 +1101,16 @@ impl<'a> Parser<'a> { TypeQualifierSpec::Storage(storage_qualifier) => { assert!(storage.is_none()); - match storage_qualifier { - StorageQualifier::Const => storage = Some(StorageClass::UniformConstant), - StorageQualifier::In => storage = Some(StorageClass::Input), - StorageQualifier::Out => storage = Some(StorageClass::Output), - StorageQualifier::Uniform => storage = Some(StorageClass::Uniform), - StorageQualifier::Buffer => storage = Some(StorageClass::StorageBuffer), - StorageQualifier::Shared => storage = Some(StorageClass::Workgroup), - StorageQualifier::Coherent => storage = Some(StorageClass::Workgroup), + storage = Some(match storage_qualifier { + StorageQualifier::Const => StorageClass::Constant, + StorageQualifier::In => StorageClass::Input, + StorageQualifier::Out => StorageClass::Output, + StorageQualifier::Uniform => StorageClass::Uniform, + StorageQualifier::Buffer => StorageClass::StorageBuffer, + StorageQualifier::Shared => StorageClass::WorkGroup, + StorageQualifier::Coherent => StorageClass::WorkGroup, _ => panic!(), - } + }); } TypeQualifierSpec::Layout(layout_qualifier) => { assert!(binding.is_none()); @@ -1203,7 +1173,7 @@ impl<'a> Parser<'a> { pub fn parse_str( source: &str, entry: String, - exec: ExecutionModel, + stage: ShaderStage, ) -> Result { let input = parser::parse(source).unwrap(); @@ -1211,7 +1181,7 @@ pub fn parse_str( log::debug!("\n{}", input); log::debug!("-----------------------------"); - Parser::new(&input, exec)?.parse(entry) + Parser::new(&input, stage)?.parse(entry) } #[cfg(test)] @@ -1224,7 +1194,7 @@ mod tests { println!( "{:#?}", - parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) + parse_str(data, String::from("main"), crate::ShaderStage::Vertex) ); } @@ -1236,7 +1206,7 @@ mod tests { println!( "{:#?}", - parse_str(data, String::from("main"), spirv::ExecutionModel::Fragment) + parse_str(data, String::from("main"), crate::ShaderStage::Fragment) ); } @@ -1249,7 +1219,7 @@ mod tests { println!( "{:#?}", - parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) + parse_str(data, String::from("main"), crate::ShaderStage::Vertex) ); } @@ -1263,7 +1233,7 @@ mod tests { println!( "{:#?}", - parse_str(data, String::from("main"), spirv::ExecutionModel::Vertex) + parse_str(data, String::from("main"), crate::ShaderStage::Vertex) ); } } diff --git a/src/front/mod.rs b/src/front/mod.rs index 36bdd65e9..bb10fbdc7 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,5 +1,6 @@ #[cfg(feature = "glsl")] pub mod glsl; +#[cfg(feature = "spirv")] pub mod spv; pub mod wgsl; diff --git a/src/front/spv.rs b/src/front/spv.rs index cdee75660..2d7e738c9 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -35,8 +35,8 @@ pub enum Error { UnsupportedType(Handle), UnsupportedExecutionModel(u32), UnsupportedStorageClass(u32), - UnsupportedFunctionControl(u32), - UnsupportedDim(u32), + UnsupportedImageDim(u32), + UnsupportedBuiltIn(u32), InvalidParameter(spirv::Op), InvalidOperandCount(spirv::Op, u16), InvalidOperand, @@ -120,8 +120,29 @@ fn map_vector_size(word: spirv::Word) -> Result { } } -fn map_storage_class(word: spirv::Word) -> Result { - spirv::StorageClass::from_u32(word).ok_or(Error::UnsupportedStorageClass(word)) +fn map_storage_class(word: spirv::Word) -> Result { + use spirv::StorageClass as Sc; + match Sc::from_u32(word) { + Some(Sc::UniformConstant) => Ok(crate::StorageClass::Constant), + Some(Sc::Function) => Ok(crate::StorageClass::Function), + Some(Sc::Input) => Ok(crate::StorageClass::Input), + Some(Sc::Output) => Ok(crate::StorageClass::Output), + Some(Sc::Private) => Ok(crate::StorageClass::Private), + Some(Sc::StorageBuffer) => Ok(crate::StorageClass::StorageBuffer), + Some(Sc::Uniform) => Ok(crate::StorageClass::Uniform), + Some(Sc::Workgroup) => Ok(crate::StorageClass::WorkGroup), + _ => Err(Error::UnsupportedStorageClass(word)), + } +} + +fn map_image_dim(word: spirv::Word) -> Result { + match spirv::Dim::from_u32(word) { + Some(spirv::Dim::Dim1D) => Ok(crate::ImageDimension::D1), + Some(spirv::Dim::Dim2D) => Ok(crate::ImageDimension::D2), + Some(spirv::Dim::Dim3D) => Ok(crate::ImageDimension::D3), + Some(spirv::Dim::DimCube) => Ok(crate::ImageDimension::Cube), + _ => Err(Error::UnsupportedImageDim(word)), + } } type MemberIndex = u32; @@ -134,7 +155,7 @@ struct Block { #[derive(Debug, Default)] struct Decoration { name: Option, - built_in: Option, + built_in: Option, location: Option, desc_set: Option, desc_index: Option, @@ -299,13 +320,29 @@ impl> Parser { log::trace!("\t\t{:?}", dec_typed); match dec_typed { spirv::Decoration::BuiltIn => { + use spirv::BuiltIn as Bi; inst.expect(base_words + 2)?; let raw = self.next()?; - let built_in = spirv::BuiltIn::from_u32(raw); - if built_in.is_none() { - log::warn!("Unknown built in {:?}", raw); - } - dec.built_in = built_in; + dec.built_in = Some(match spirv::BuiltIn::from_u32(raw) { + Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, + Some(Bi::BaseVertex) => crate::BuiltIn::BaseVertex, + Some(Bi::ClipDistance) => crate::BuiltIn::ClipDistance, + Some(Bi::InstanceIndex) => crate::BuiltIn::InstanceIndex, + Some(Bi::Position) => crate::BuiltIn::Position, + Some(Bi::VertexIndex) => crate::BuiltIn::VertexIndex, + // fragment + Some(Bi::PointSize) => crate::BuiltIn::PointSize, + Some(Bi::FragCoord) => crate::BuiltIn::FragCoord, + Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing, + Some(Bi::SampleId) => crate::BuiltIn::SampleIndex, + Some(Bi::FragDepth) => crate::BuiltIn::FragDepth, + // compute + Some(Bi::GlobalInvocationId) => crate::BuiltIn::GlobalInvocationId, + Some(Bi::LocalInvocationId) => crate::BuiltIn::LocalInvocationId, + Some(Bi::LocalInvocationIndex) => crate::BuiltIn::LocalInvocationIndex, + Some(Bi::WorkgroupId) => crate::BuiltIn::WorkGroupId, + _ => return Err(Error::UnsupportedBuiltIn(raw)), + }); } spirv::Decoration::Location => { inst.expect(base_words + 2)?; @@ -822,7 +859,12 @@ impl> Parser { module.entry_points.reserve(entry_points.len()); for raw in entry_points { module.entry_points.push(crate::EntryPoint { - exec_model: raw.exec_model, + stage: match raw.exec_model { + spirv::ExecutionModel::Vertex => crate::ShaderStage::Vertex, + spirv::ExecutionModel::Fragment => crate::ShaderStage::Fragment, + spirv::ExecutionModel::GLCompute => crate::ShaderStage::Compute, + other => return Err(Error::UnsupportedExecutionModel(other as u32)), + }, name: raw.name, function: *self.lookup_function.lookup(raw.function_id)?, }); @@ -1301,7 +1343,7 @@ impl> Parser { let inner = crate::TypeInner::Image { base: self.lookup_type.lookup(sample_type_id)?.handle, - dim: spirv::Dim::from_u32(dim).ok_or(Error::UnsupportedDim(dim))?, + dim: map_image_dim(dim)?, flags, }; self.lookup_type.insert( @@ -1488,11 +1530,11 @@ impl> Parser { let binding = match module.types[lookup_type.handle].inner { crate::TypeInner::Pointer { base, - class: spirv::StorageClass::Input, + class: crate::StorageClass::Input, } | crate::TypeInner::Pointer { base, - class: spirv::StorageClass::Output, + class: crate::StorageClass::Output, } => { match module.types[base].inner { crate::TypeInner::Struct { ref members } => { @@ -1540,7 +1582,7 @@ impl> Parser { inst.expect(5)?; let result_type = self.next()?; let fun_id = self.next()?; - let fun_control = self.next()?; + let _fun_control = self.next()?; let fun_type = self.next()?; let mut fun = { let ft = self.lookup_function_type.lookup(fun_type)?; @@ -1549,8 +1591,6 @@ impl> Parser { } crate::Function { name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name), - control: spirv::FunctionControl::from_bits(fun_control) - .ok_or(Error::UnsupportedFunctionControl(fun_control))?, parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), return_type: if self.lookup_void_type.contains(&result_type) { None diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index d1d266d31..485e207f0 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -142,7 +142,7 @@ pub enum Error<'a> { UnknownStorageClass(&'a str), UnknownDecoration(&'a str), UnknownBuiltin(&'a str), - UnknownPipelineStage(&'a str), + UnknownShaderStage(&'a str), UnknownIdent(&'a str), UnknownType(&'a str), UnknownFunction(&'a str), @@ -387,31 +387,35 @@ impl Parser { } } - fn get_storage_class(word: &str) -> Result> { + fn get_storage_class(word: &str) -> Result> { match word { - "in" => Ok(spirv::StorageClass::Input), - "out" => Ok(spirv::StorageClass::Output), - "uniform" => Ok(spirv::StorageClass::Uniform), - "storage_buffer" => Ok(spirv::StorageClass::StorageBuffer), + "in" => Ok(crate::StorageClass::Input), + "out" => Ok(crate::StorageClass::Output), + "uniform" => Ok(crate::StorageClass::Uniform), + "storage_buffer" => Ok(crate::StorageClass::StorageBuffer), _ => Err(Error::UnknownStorageClass(word)), } } - fn get_built_in(word: &str) -> Result> { + fn get_built_in(word: &str) -> Result> { match word { - "position" => Ok(spirv::BuiltIn::Position), - "vertex_idx" => Ok(spirv::BuiltIn::VertexId), - "global_invocation_id" => Ok(spirv::BuiltIn::GlobalInvocationId), + // vertex + "position" => Ok(crate::BuiltIn::Position), + "vertex_idx" => Ok(crate::BuiltIn::VertexIndex), + "instance_idx" => Ok(crate::BuiltIn::InstanceIndex), + // compute + "global_invocation_id" => Ok(crate::BuiltIn::GlobalInvocationId), + "local_invocation_id" => Ok(crate::BuiltIn::LocalInvocationId), _ => Err(Error::UnknownBuiltin(word)), } } - fn get_execution_model(word: &str) -> Result> { + fn get_shader_stage(word: &str) -> Result> { match word { - "vertex" => Ok(spirv::ExecutionModel::Vertex), - "fragment" => Ok(spirv::ExecutionModel::Fragment), - "compute" => Ok(spirv::ExecutionModel::GLCompute), - _ => Err(Error::UnknownPipelineStage(word)), + "vertex" => Ok(crate::ShaderStage::Vertex), + "fragment" => Ok(crate::ShaderStage::Fragment), + "compute" => Ok(crate::ShaderStage::Compute), + _ => Err(Error::UnknownShaderStage(word)), } } @@ -903,7 +907,7 @@ impl Parser { lexer: &mut Lexer<'a>, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result<(&'a str, Option, Handle), Error<'a>> { + ) -> Result<(&'a str, Option, Handle), Error<'a>> { self.scopes.push(Scope::VariableDecl); let mut class = None; if lexer.skip(Token::Paren('<')) { @@ -1276,7 +1280,6 @@ impl Parser { let fun = crate::Function { name: Some(fun_name.to_owned()), - control: spirv::FunctionControl::empty(), parameter_types, return_type, global_usage, @@ -1385,11 +1388,11 @@ impl Parser { Some(c) => c, None => match binding { Some(crate::Binding::BuiltIn(builtin)) => match builtin { - spirv::BuiltIn::GlobalInvocationId => spirv::StorageClass::Input, - spirv::BuiltIn::Position => spirv::StorageClass::Output, + crate::BuiltIn::GlobalInvocationId => crate::StorageClass::Input, + crate::BuiltIn::Position => crate::StorageClass::Output, _ => unimplemented!(), }, - _ => spirv::StorageClass::Private, + _ => crate::StorageClass::Private, }, }, binding: binding.take(), @@ -1402,7 +1405,7 @@ impl Parser { self.parse_function_decl(lexer, module, &lookup_global_expression)?; } Token::Word("entry_point") => { - let exec_model = Self::get_execution_model(lexer.next_ident()?)?; + let stage = Self::get_shader_stage(lexer.next_ident()?)?; let export_name = if lexer.skip(Token::Word("as")) { match lexer.next() { Token::String(name) => Some(name), @@ -1420,7 +1423,7 @@ impl Parser { .find(|(_, fun)| fun.name.as_deref() == Some(fun_ident)) .ok_or(Error::UnknownFunction(fun_ident))?; module.entry_points.push(crate::EntryPoint { - exec_model, + stage, name: export_name.unwrap_or(fun_ident).to_owned(), function: fun_handle, }); diff --git a/src/lib.rs b/src/lib.rs index c163e89a1..b35a75968 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,6 +22,47 @@ pub struct Header { pub generator: u32, } +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ShaderStage { + Vertex, + Fragment, + Compute, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum StorageClass { + Constant, + Function, + Input, + Output, + Private, + StorageBuffer, + Uniform, + WorkGroup, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum BuiltIn { + // vertex + BaseInstance, + BaseVertex, + ClipDistance, + InstanceIndex, + Position, + VertexIndex, + // fragment + PointSize, + FragCoord, + FrontFacing, + SampleIndex, + FragDepth, + // compute + GlobalInvocationId, + LocalInvocationId, + LocalInvocationIndex, + WorkGroupId, +} + pub type Bytes = u8; #[repr(u8)] @@ -44,7 +85,7 @@ pub enum ScalarKind { #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ArraySize { - Static(spirv::Word), + Static(u32), Dynamic, } @@ -54,7 +95,15 @@ pub struct StructMember { pub name: Option, pub binding: Option, pub ty: Handle, - pub offset: spirv::Word, + pub offset: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ImageDimension { + D1, + D2, + D3, + Cube, } bitflags::bitflags! { @@ -93,7 +142,7 @@ pub enum TypeInner { }, Pointer { base: Handle, - class: spirv::StorageClass, + class: StorageClass, }, Array { base: Handle, @@ -105,7 +154,7 @@ pub enum TypeInner { }, Image { base: Handle, - dim: spirv::Dim, + dim: ImageDimension, flags: ImageFlags, }, Sampler { @@ -116,7 +165,7 @@ pub enum TypeInner { #[derive(Debug, PartialEq)] pub struct Constant { pub name: Option, - pub specialization: Option, + pub specialization: Option, pub inner: ConstantInner, pub ty: Handle, } @@ -133,12 +182,9 @@ pub enum ConstantInner { #[derive(Clone, Debug, PartialEq)] pub enum Binding { - BuiltIn(spirv::BuiltIn), - Location(spirv::Word), - Descriptor { - set: spirv::Word, - binding: spirv::Word, - }, + BuiltIn(BuiltIn), + Location(u32), + Descriptor { set: u32, binding: u32 }, } bitflags::bitflags! { @@ -151,7 +197,7 @@ bitflags::bitflags! { #[derive(Clone, Debug, PartialEq)] pub struct GlobalVariable { pub name: Option, - pub class: spirv::StorageClass, + pub class: StorageClass, pub binding: Option, pub ty: Handle, } @@ -302,7 +348,7 @@ pub enum Statement { #[derive(Debug)] pub struct Function { pub name: Option, - pub control: spirv::FunctionControl, + //pub control: spirv::FunctionControl, pub parameter_types: Vec>, pub return_type: Option>, pub global_usage: Vec, @@ -313,7 +359,7 @@ pub struct Function { #[derive(Debug)] pub struct EntryPoint { - pub exec_model: spirv::ExecutionModel, + pub stage: ShaderStage, pub name: String, pub function: Handle, } diff --git a/tests/convert.rs b/tests/convert.rs index 5a1ed8bd0..5a6828efc 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -1,6 +1,3 @@ -#[cfg(feature = "glsl")] -use spirv::ExecutionModel; - fn load_test_data(name: &str) -> String { let path = format!("{}/test-data/{}", env!("CARGO_MANIFEST_DIR"), name); std::fs::read_to_string(path).unwrap() @@ -12,9 +9,9 @@ fn load_wgsl(name: &str) -> naga::Module { } #[cfg(feature = "glsl")] -fn load_glsl(name: &str, entry: &str, exec: ExecutionModel) -> naga::Module { +fn load_glsl(name: &str, entry: &str, stage: naga::ShaderStage) -> naga::Module { let input = load_test_data(name); - naga::front::glsl::parse_str(&input, entry.to_owned(), exec).unwrap() + naga::front::glsl::parse_str(&input, entry.to_owned(), stage).unwrap() } #[test] @@ -94,7 +91,11 @@ fn convert_boids() { #[test] #[ignore] fn convert_phong_lighting() { - let module = load_glsl("glsl_phong_lighting.frag", "main", ExecutionModel::Fragment); + let module = load_glsl( + "glsl_phong_lighting.frag", + "main", + naga::ShaderStage::Fragment, + ); naga::proc::Validator::new().validate(&module).unwrap(); let header = naga::Header { From 713fcaaa119d2e538c539e9ccf06698e03f067a6 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Tue, 23 Jun 2020 23:33:59 +0200 Subject: [PATCH 0092/2212] Spirv backend - Extract instructions to own functions --- src/back/spv/writer.rs | 1212 +++++++++++++++++++++++++--------------- 1 file changed, 773 insertions(+), 439 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 95ce6ba5f..e8e76e1e2 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,8 +1,13 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ use super::{helpers, Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; -use crate::{FastHashMap, FastHashSet}; +use crate::{FastHashMap, FastHashSet, ImageFlags, VectorSize}; use spirv::{Op, Word}; +enum Signedness { + Unsigned = 0, + Signed = 1, +} + trait LookupHelper { type Target; fn lookup_id(&self, handle: crate::Handle) -> Option; @@ -87,12 +92,166 @@ impl Writer { } } - fn instruction_capability(&self, capability: spirv::Capability) -> Instruction { - let mut instruction = Instruction::new(Op::Capability); - instruction.add_operand(capability as u32); + fn get_type_id( + &mut self, + arena: &crate::Arena, + handle: crate::Handle, + ) -> Word { + match self.lookup_type.lookup_id(handle) { + Some(word) => word, + None => { + let (instruction, id) = self.parse_type_declaration(arena, handle); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + } + } + + fn get_constant_id( + &mut self, + handle: crate::Handle, + ir_module: &crate::Module, + ) -> Word { + match self.lookup_constant.lookup_id(handle) { + Some(word) => word, + None => { + let (instruction, id) = self.parse_constant_type(handle, ir_module); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + } + } + + fn get_global_variable_id( + &mut self, + arena: &crate::Arena, + global_arena: &crate::Arena, + handle: crate::Handle, + ) -> Word { + match self.lookup_global_variable.lookup_id(handle) { + Some(word) => word, + None => { + let global_variable = &global_arena[handle]; + let (instruction, id) = self.parse_global_variable(arena, global_variable, handle); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + } + } + + fn get_function_type( + &mut self, + ty: Option>, + arena: &crate::Arena, + ) -> Word { + match ty { + Some(handle) => self.get_type_id(arena, handle), + None => match self.void_type { + Some(id) => id, + None => { + let id = self.generate_id(); + self.void_type = Some(id); + self.instruction_type_void(id) + .to_words(&mut self.logical_layout.declarations); + id + } + }, + } + } + + fn get_pointer_id( + &mut self, + arena: &crate::Arena, + handle: crate::Handle, + class: spirv::StorageClass, + ) -> Word { + let ty = &arena[handle]; + let type_id = self.get_type_id(arena, handle); + match ty.inner { + crate::TypeInner::Pointer { .. } => type_id, + _ => { + let pointer_id = self.generate_id(); + let instruction = self.instruction_type_pointer(pointer_id, class, type_id); + instruction.to_words(&mut self.logical_layout.declarations); + + /* TODO + Not able to lookup Pointer, because there is no Handle in the IR for it. + Idea would be to not have any handles at all in the lookups, so we aren't bound + to the IR. We can then insert, like here runtime values to the lookups + */ + // self.lookup_type.insert(pointer_id, global_variable.ty); + pointer_id + } + } + } + + fn find_scalar_handle( + &self, + arena: &crate::Arena, + kind: crate::ScalarKind, + width: u8, + ) -> crate::Handle { + let mut scalar_handle = None; + for (handle, ty) in arena.iter() { + match ty.inner { + crate::TypeInner::Scalar { + kind: lookup_kind, + width: lookup_width, + } => { + if kind == lookup_kind && width == lookup_width { + scalar_handle = Some(handle); + break; + } + } + _ => continue, + } + } + scalar_handle.unwrap() + } + + /// + /// Debug Instructions + /// + + fn instruction_source( + &self, + source_language: spirv::SourceLanguage, + version: u32, + ) -> Instruction { + let mut instruction = Instruction::new(Op::Source); + instruction.add_operand(source_language as u32); + instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); instruction } + fn instruction_name(&self, target_id: Word, name: &str) -> Instruction { + let mut instruction = Instruction::new(Op::Name); + instruction.set_result(target_id); + instruction.add_operands(helpers::string_to_words(name)); + instruction + } + + /// + /// Annotation Instructions + /// + + fn instruction_decorate( + &self, + target_id: Word, + decoration: spirv::Decoration, + operands: &[Word], + ) -> Instruction { + let mut instruction = Instruction::new(Op::Decorate); + instruction.add_operand(target_id); + instruction.add_operand(decoration as u32); + instruction.add_operands(Vec::from(operands)); + instruction + } + + /// + /// Extension Instructions + /// + fn instruction_ext_inst_import(&mut self, name: &str) -> Instruction { let mut instruction = Instruction::new(Op::ExtInstImport); let id = self.generate_id(); @@ -101,6 +260,10 @@ impl Writer { instruction } + /// + /// Mode-Setting Instructions + /// + fn instruction_memory_model(&mut self) -> Instruction { let mut instruction = Instruction::new(Op::MemoryModel); let addressing_model = spirv::AddressingModel::Logical; @@ -132,14 +295,6 @@ impl Writer { instruction.add_operand(exec_model as u32); instruction.add_operand(function_id); - - if self.writer_flags.contains(WriterFlags::DEBUG) { - let mut debug_instruction = Instruction::new(Op::Name); - debug_instruction.set_result(function_id); - debug_instruction.add_operands(helpers::string_to_words(entry_point.name.as_str())); - self.debugs.push(debug_instruction); - } - instruction.add_operands(helpers::string_to_words(entry_point.name.as_str())); let function = &ir_module.functions[entry_point.function]; @@ -164,158 +319,436 @@ impl Writer { crate::ShaderStage::Fragment => { let execution_mode = spirv::ExecutionMode::OriginUpperLeft; self.try_add_capabilities(execution_mode.required_capabilities()); - - let mut execution_mode_instruction = Instruction::new(Op::ExecutionMode); - execution_mode_instruction.add_operand(function_id); - execution_mode_instruction.add_operand(execution_mode as u32); - execution_mode_instruction.to_words(&mut self.logical_layout.execution_modes); + self.instruction_execution_mode(function_id, execution_mode) + .to_words(&mut self.logical_layout.execution_modes); } crate::ShaderStage::Compute => {} } + if self.writer_flags.contains(WriterFlags::DEBUG) { + self.debugs + .push(self.instruction_name(function_id, entry_point.name.as_str())); + } + instruction } - fn get_type_id( - &mut self, - arena: &crate::Arena, - handle: crate::Handle, - ) -> Word { - match self.lookup_type.lookup_id(handle) { - Some(word) => word, - None => { - let (instruction, id) = self.instruction_type_declaration(arena, handle); - instruction.to_words(&mut self.logical_layout.declarations); - id - } - } - } - - fn get_constant_id( - &mut self, - handle: crate::Handle, - ir_module: &crate::Module, - ) -> Word { - match self.lookup_constant.lookup_id(handle) { - Some(word) => word, - None => { - let (instruction, id) = self.instruction_constant_type(handle, ir_module); - instruction.to_words(&mut self.logical_layout.declarations); - id - } - } - } - - fn get_global_variable_id( - &mut self, - arena: &crate::Arena, - global_arena: &crate::Arena, - handle: crate::Handle, - ) -> Word { - match self.lookup_global_variable.lookup_id(handle) { - Some(word) => word, - None => { - let global_variable = &global_arena[handle]; - let (instruction, id) = - self.instruction_global_variable(arena, global_variable, handle); - instruction.to_words(&mut self.logical_layout.declarations); - id - } - } - } - - fn get_function_type( - &mut self, - ty: Option>, - arena: &crate::Arena, - ) -> Word { - match ty { - Some(handle) => self.get_type_id(arena, handle), - None => match self.void_type { - Some(id) => id, - None => { - let id = self.generate_id(); - - let mut instruction = Instruction::new(Op::TypeVoid); - instruction.set_result(id); - - self.void_type = Some(id); - instruction.to_words(&mut self.logical_layout.declarations); - id - } - }, - } - } - - fn find_scalar_handle( + fn instruction_execution_mode( &self, - arena: &crate::Arena, - kind: crate::ScalarKind, - width: u8, - ) -> crate::Handle { - let mut scalar_handle = None; - for (handle, ty) in arena.iter() { - match ty.inner { - crate::TypeInner::Scalar { - kind: _kind, - width: _width, - } => { - if kind == _kind && width == _width { - scalar_handle = Some(handle); - break; - } - } - _ => continue, - } - } - scalar_handle.unwrap() + function_id: Word, + execution_mode: spirv::ExecutionMode, + ) -> Instruction { + let mut instruction = Instruction::new(Op::ExecutionMode); + instruction.add_operand(function_id); + instruction.add_operand(execution_mode as u32); + instruction } - fn instruction_type_declaration( + fn instruction_capability(&self, capability: spirv::Capability) -> Instruction { + let mut instruction = Instruction::new(Op::Capability); + instruction.add_operand(capability as u32); + instruction + } + + /// + /// Type-Declaration Instructions + /// + + fn instruction_type_void(&self, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeVoid); + instruction.set_result(id); + instruction + } + + fn instruction_type_bool(&self, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeBool); + instruction.set_result(id); + instruction + } + + fn instruction_type_int(&self, id: Word, width: u8, signedness: Signedness) -> Instruction { + let mut instruction = Instruction::new(Op::TypeInt); + instruction.set_result(id); + instruction.add_operand(width as u32); + instruction.add_operand(signedness as u32); + instruction + } + + fn instruction_type_float(&self, id: Word, width: u8) -> Instruction { + let mut instruction = Instruction::new(Op::TypeFloat); + instruction.set_result(id); + instruction.add_operand(width as u32); + instruction + } + + fn instruction_type_vector( + &self, + id: Word, + component_type_id: Word, + component_count: VectorSize, + ) -> Instruction { + let mut instruction = Instruction::new(Op::TypeVector); + instruction.set_result(id); + instruction.add_operand(component_type_id); + instruction.add_operand(component_count as u32); + instruction + } + + fn instruction_type_matrix( + &self, + id: Word, + column_type_id: Word, + column_count: VectorSize, + ) -> Instruction { + let mut instruction = Instruction::new(Op::TypeMatrix); + instruction.set_result(id); + instruction.add_operand(column_type_id); + instruction.add_operand(column_count as u32); + instruction + } + + fn instruction_type_image( + &self, + id: Word, + sampled_type_id: Word, + dim: spirv::Dim, + flags: ImageFlags, + ) -> Instruction { + let mut instruction = Instruction::new(Op::TypeImage); + instruction.set_result(id); + instruction.add_operand(sampled_type_id); + instruction.add_operand(dim as u32); + + // TODO Add Depth, but how to determine? Not yet in the WGSL spec + instruction.add_operand(1); + + instruction.add_operand(if flags.contains(crate::ImageFlags::ARRAYED) { + 1 + } else { + 0 + }); + + instruction.add_operand(if flags.contains(crate::ImageFlags::MULTISAMPLED) { + 1 + } else { + 0 + }); + + instruction.add_operand(if flags.contains(crate::ImageFlags::SAMPLED) { + 1 + } else { + 0 + }); + + // TODO Image Format defaults to Unknown, not yet in IR + instruction.add_operand(spirv::ImageFormat::Unknown as u32); + + // Access Qualifier + instruction.add_operand( + if flags.contains(crate::ImageFlags::CAN_STORE) + && flags.contains(crate::ImageFlags::CAN_LOAD) + { + 2 + } else if flags.contains(crate::ImageFlags::CAN_STORE) { + 1 + } else { + 0 + }, + ); + instruction + } + + fn instruction_type_sampler(&self, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeSampler); + instruction.set_result(id); + instruction + } + + fn instruction_type_array( + &self, + id: Word, + element_type_id: Word, + length_id: Word, + ) -> Instruction { + let mut instruction = Instruction::new(Op::TypeArray); + instruction.set_result(id); + instruction.add_operand(element_type_id); + instruction.add_operand(length_id); + instruction + } + + fn instruction_type_runtime_array(&self, id: Word, element_type_id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeRuntimeArray); + instruction.set_result(id); + instruction.add_operand(element_type_id); + instruction + } + + fn instruction_type_struct(&self, id: Word, member_ids: Vec) -> Instruction { + let mut instruction = Instruction::new(Op::TypeStruct); + instruction.set_result(id); + instruction.add_operands(member_ids); + instruction + } + + fn instruction_type_pointer( + &self, + id: Word, + storage_class: spirv::StorageClass, + type_id: Word, + ) -> Instruction { + let mut instruction = Instruction::new(Op::TypePointer); + instruction.set_result(id); + instruction.add_operand(storage_class as u32); + instruction.add_operand(type_id); + instruction + } + + fn instruction_type_function( + &self, + id: Word, + return_type_id: Word, + parameter_ids: Vec, + ) -> Instruction { + let mut instruction = Instruction::new(Op::TypeFunction); + instruction.set_result(id); + instruction.add_operand(return_type_id); + instruction.add_operands(parameter_ids); + instruction + } + + /// + /// Constant-Creation Instructions + /// + + fn instruction_constant_true(&self, scalar_constant_id: Word, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::ConstantTrue); + instruction.set_type(scalar_constant_id); + instruction.set_result(id); + instruction + } + + fn instruction_constant_false(&self, scalar_constant_id: Word, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::ConstantFalse); + instruction.set_type(scalar_constant_id); + instruction.set_result(id); + instruction + } + + fn instruction_constant( + &self, + scalar_constant_id: Word, + id: Word, + values: &[Word], + ) -> Instruction { + let mut instruction = Instruction::new(Op::Constant); + instruction.set_type(scalar_constant_id); + instruction.set_result(id); + for value in values { + instruction.add_operand(*value); + } + instruction + } + + fn instruction_constant_composite( + &self, + composite_type_id: Word, + id: Word, + constituent_ids: Vec, + ) -> Instruction { + let mut instruction = Instruction::new(Op::ConstantComposite); + instruction.set_type(composite_type_id); + instruction.set_result(id); + instruction.add_operands(constituent_ids); + instruction + } + + /// + /// Memory Instructions + /// + + fn instruction_variable( + &self, + pointer_type_id: Word, + id: Word, + storage_class: spirv::StorageClass, + initializer_id: Option, + ) -> Instruction { + let mut instruction = Instruction::new(Op::Variable); + instruction.set_type(pointer_type_id); + instruction.set_result(id); + instruction.add_operand(storage_class as u32); + + if let Some(initializer_id) = initializer_id { + instruction.add_operand(initializer_id); + } + + instruction + } + + fn instruction_load( + &self, + type_id: Word, + id: Word, + pointer_type_id: Word, + memory_access: Option, + ) -> Instruction { + let mut instruction = Instruction::new(Op::Load); + instruction.set_type(type_id); + instruction.set_result(id); + instruction.add_operand(pointer_type_id); + + instruction.add_operand(if let Some(memory_access) = memory_access { + memory_access.bits() + } else { + spirv::MemoryAccess::NONE.bits() + }); + + instruction + } + + fn instruction_store(&self, pointer_type_id: Word, object_id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::Store); + instruction.set_type(pointer_type_id); + instruction.add_operand(object_id); + instruction + } + + /// + /// Function Instructions + /// + + fn instruction_function( + &self, + return_type_id: Word, + id: Word, + function_control: spirv::FunctionControl, + function_type_id: Word, + ) -> Instruction { + let mut instruction = Instruction::new(Op::Function); + instruction.set_type(return_type_id); + instruction.set_result(id); + instruction.add_operand(function_control.bits()); + instruction.add_operand(function_type_id); + instruction + } + + fn instruction_function_end(&self) -> Instruction { + Instruction::new(Op::FunctionEnd) + } + + /// + /// Image Instructions + /// + + /// + /// Conversion Instructions + /// + + /// + /// Composite Instructions + /// + + fn instruction_composite_construct( + &self, + composite_type_id: Word, + id: Word, + constituent_ids: Vec, + ) -> Instruction { + let mut instruction = Instruction::new(Op::CompositeConstruct); + instruction.set_type(composite_type_id); + instruction.set_result(id); + instruction.add_operands(constituent_ids); + instruction + } + + /// + /// Arithmetic Instructions + /// + + fn instruction_vector_times_scalar( + &self, + float_type_id: Word, + id: Word, + vector_type_id: Word, + scalar_type_id: Word, + ) -> Instruction { + let mut instruction = Instruction::new(Op::VectorTimesScalar); + instruction.set_type(float_type_id); + instruction.set_result(id); + instruction.add_operand(vector_type_id); + instruction.add_operand(scalar_type_id); + instruction + } + + /// + /// Bit Instructions + /// + + /// + /// Relational and Logical Instructions + /// + + /// + /// Derivative Instructions + /// + + /// + /// Control-Flow Instructions + /// + + fn instruction_label(&self, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::Label); + instruction.set_result(id); + instruction + } + + fn instruction_return(&self) -> Instruction { + Instruction::new(Op::Return) + } + + fn instruction_return_value(&self, value_id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::ReturnValue); + instruction.add_operand(value_id); + instruction + } + + /// + /// Atomic Instructions + /// + + /// + /// Primitive Instructions + /// + + fn parse_type_declaration( &mut self, arena: &crate::Arena, handle: crate::Handle, ) -> (Instruction, Word) { let ty = &arena[handle]; let id = self.generate_id(); - let mut instruction; + + let instruction; match ty.inner { crate::TypeInner::Scalar { kind, width } => { - match kind { + instruction = match kind { crate::ScalarKind::Sint => { - instruction = Instruction::new(Op::TypeInt); - instruction.set_result(id); - instruction.add_operand(width as u32); - instruction.add_operand(0x1u32); + self.instruction_type_int(id, width, Signedness::Signed) } crate::ScalarKind::Uint => { - instruction = Instruction::new(Op::TypeInt); - instruction.set_result(id); - instruction.add_operand(width as u32); - instruction.add_operand(0x0u32); + self.instruction_type_int(id, width, Signedness::Unsigned) } - crate::ScalarKind::Float => { - instruction = Instruction::new(Op::TypeFloat); - instruction.set_result(id); - instruction.add_operand(width as u32); - } - crate::ScalarKind::Bool => { - instruction = Instruction::new(Op::TypeBool); - instruction.set_result(id); - } - } + crate::ScalarKind::Float => self.instruction_type_float(id, width), + crate::ScalarKind::Bool => self.instruction_type_bool(id), + }; self.lookup_type.insert(id, handle); } crate::TypeInner::Vector { size, kind, width } => { let scalar_handle = self.find_scalar_handle(arena, kind, width); let scalar_id = self.get_type_id(arena, scalar_handle); - - instruction = Instruction::new(Op::TypeVector); - instruction.set_result(id); - instruction.add_operand(scalar_id); - instruction.add_operand(size as u32); - + instruction = self.instruction_type_vector(id, scalar_id, size); self.lookup_type.insert(id, handle); } crate::TypeInner::Matrix { @@ -327,53 +760,7 @@ impl Writer { let scalar_handle = self.find_scalar_handle(arena, kind, width); let scalar_id = self.get_type_id(arena, scalar_handle); - instruction = Instruction::new(Op::TypeMatrix); - instruction.set_result(id); - instruction.add_operand(scalar_id); - instruction.add_operand(columns as u32); - } - crate::TypeInner::Pointer { base, class } => { - let type_id = self.get_type_id(arena, base); - instruction = Instruction::new(Op::TypePointer); - instruction.set_result(id); - instruction.add_operand(class as u32); - instruction.add_operand(type_id); - - self.lookup_type.insert(id, handle); - } - crate::TypeInner::Array { base, size, stride } => { - if let Some(array_stride) = stride { - let mut instruction = Instruction::new(Op::Decorate); - instruction.add_operand(id); - instruction.add_operand(spirv::Decoration::ArrayStride as u32); - instruction.add_operand(array_stride.get()); - self.annotations.push(instruction); - } - - let type_id = self.get_type_id(arena, handle); - - instruction = Instruction::new(Op::TypeArray); - instruction.set_result(id); - instruction.add_operand(type_id); - - match size { - crate::ArraySize::Static(word) => { - instruction.add_operand(word); - } - _ => panic!("Array size {:?} unsupported", size), - } - - self.lookup_type.insert(id, base); - } - crate::TypeInner::Struct { ref members } => { - instruction = Instruction::new(Op::TypeStruct); - instruction.set_result(id); - - for member in members { - let type_id = self.get_type_id(arena, member.ty); - instruction.add_operand(type_id); - } - + instruction = self.instruction_type_matrix(id, scalar_id, columns); self.lookup_type.insert(id, handle); } crate::TypeInner::Image { base, dim, flags } => { @@ -386,59 +773,62 @@ impl Writer { }; self.try_add_capabilities(dim.required_capabilities()); - instruction = Instruction::new(Op::TypeImage); - instruction.set_result(id); - instruction.add_operand(type_id); - instruction.add_operand(dim as u32); - - // TODO Add Depth, but how to determine? Not yet in the WGSL spec - instruction.add_operand(1); - - instruction.add_operand(if flags.contains(crate::ImageFlags::ARRAYED) { - 1 - } else { - 0 - }); - - instruction.add_operand(if flags.contains(crate::ImageFlags::MULTISAMPLED) { - 1 - } else { - 0 - }); - - instruction.add_operand(if flags.contains(crate::ImageFlags::SAMPLED) { - 1 - } else { - 0 - }); - // TODO Defaults to Unknown, not yet in IR - instruction.add_operand(spirv::ImageFormat::Unknown as u32); - - instruction.add_operand( - if flags.contains(crate::ImageFlags::CAN_STORE) - && flags.contains(crate::ImageFlags::CAN_LOAD) - { - 2 - } else if flags.contains(crate::ImageFlags::CAN_STORE) { - 1 - } else { - 0 - }, - ); - + instruction = self.instruction_type_image(id, type_id, dim, flags); self.lookup_type.insert(id, base); } crate::TypeInner::Sampler { comparison: _ } => { - instruction = Instruction::new(Op::TypeSampler); - instruction.set_result(id); + instruction = self.instruction_type_sampler(id); self.lookup_type.insert(id, handle); } - } + crate::TypeInner::Array { base, size, stride } => { + if let Some(array_stride) = stride { + self.annotations.push(self.instruction_decorate( + id, + spirv::Decoration::ArrayStride, + &[array_stride.get()], + )); + } + + let type_id = self.get_type_id(arena, handle); + instruction = match size { + crate::ArraySize::Static(length) => { + self.instruction_type_array(id, type_id, length) + } + crate::ArraySize::Dynamic => self.instruction_type_runtime_array(id, type_id), + }; + + self.lookup_type.insert(id, base); + } + crate::TypeInner::Struct { ref members } => { + let mut member_ids = Vec::with_capacity(members.len()); + for member in members { + let member_id = self.get_type_id(arena, member.ty); + member_ids.push(member_id); + } + instruction = self.instruction_type_struct(id, member_ids); + self.lookup_type.insert(id, handle); + } + crate::TypeInner::Pointer { base, class } => { + let type_id = self.get_type_id(arena, base); + let storage_class = match class { + crate::StorageClass::Constant => spirv::StorageClass::UniformConstant, + crate::StorageClass::Function => spirv::StorageClass::Function, + crate::StorageClass::Input => spirv::StorageClass::Input, + crate::StorageClass::Output => spirv::StorageClass::Output, + crate::StorageClass::Private => spirv::StorageClass::Private, + crate::StorageClass::StorageBuffer => spirv::StorageClass::StorageBuffer, + crate::StorageClass::Uniform => spirv::StorageClass::Uniform, + crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, + }; + instruction = self.instruction_type_pointer(id, storage_class, type_id); + self.lookup_type.insert(id, handle); + } + }; (instruction, id) } - fn instruction_constant_type( + fn parse_constant_type( &mut self, handle: crate::Handle, ir_module: &crate::Module, @@ -450,147 +840,89 @@ impl Writer { match constant.inner { crate::ConstantInner::Sint(val) => { + let ty = &ir_module.types[constant.ty]; let type_id = self.get_type_id(arena, constant.ty); - let mut instruction = Instruction::new(Op::Constant); - instruction.set_type(type_id); - instruction.set_result(id); - - let ty = &ir_module.types[constant.ty]; - match ty.inner { + let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { - 32 => { - instruction.add_operand(val as u32); - } + 32 => self.instruction_constant(type_id, id, &[val as u32]), 64 => { let (low, high) = ((val >> 32) as u32, val as u32); - instruction.add_operand(low); - instruction.add_operand(high); + self.instruction_constant(type_id, id, &[low, high]) } _ => unreachable!(), }, _ => unreachable!(), - } - + }; (instruction, id) } crate::ConstantInner::Uint(val) => { + let ty = &ir_module.types[constant.ty]; let type_id = self.get_type_id(arena, constant.ty); - let mut instruction = Instruction::new(Op::Constant); - instruction.set_type(type_id); - instruction.set_result(id); - - let ty = &ir_module.types[constant.ty]; - match ty.inner { + let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { - 32 => { - instruction.add_operand(val as u32); - } + 32 => self.instruction_constant(type_id, id, &[val as u32]), 64 => { let (low, high) = ((val >> 32) as u32, val as u32); - instruction.add_operand(low); - instruction.add_operand(high); + self.instruction_constant(type_id, id, &[low, high]) } _ => unreachable!(), }, _ => unreachable!(), - } + }; (instruction, id) } crate::ConstantInner::Float(val) => { + let ty = &ir_module.types[constant.ty]; let type_id = self.get_type_id(arena, constant.ty); - let mut instruction = Instruction::new(Op::Constant); - instruction.set_type(type_id); - instruction.set_result(id); - - let ty = &ir_module.types[constant.ty]; - match ty.inner { + let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { - 32 => { - instruction.add_operand((val as f32).to_bits()); - } + 32 => self.instruction_constant(type_id, id, &[(val as f32).to_bits()]), 64 => { let bits = f64::to_bits(val); let (low, high) = ((bits >> 32) as u32, bits as u32); - instruction.add_operand(low); - instruction.add_operand(high); + self.instruction_constant(type_id, id, &[low, high]) } _ => unreachable!(), }, _ => unreachable!(), - } - + }; (instruction, id) } crate::ConstantInner::Bool(val) => { let type_id = self.get_type_id(arena, constant.ty); - let mut instruction = Instruction::new(if val { - Op::ConstantTrue + let instruction = if val { + self.instruction_constant_true(type_id, id) } else { - Op::ConstantFalse - }); + self.instruction_constant_false(type_id, id) + }; - instruction.set_type(type_id); - instruction.set_result(id); (instruction, id) } crate::ConstantInner::Composite(ref constituents) => { - let type_id = self.get_type_id(arena, constant.ty); - - let mut instruction = Instruction::new(Op::ConstantComposite); - instruction.set_type(type_id); - instruction.set_result(id); - + let mut constituent_ids = Vec::with_capacity(constituents.len()); for constituent in constituents.iter() { - let id = self.get_constant_id(*constituent, &ir_module); - instruction.add_operand(id); + let constituent_id = self.get_constant_id(*constituent, &ir_module); + constituent_ids.push(constituent_id); } + let type_id = self.get_type_id(arena, constant.ty); + let instruction = self.instruction_constant_composite(type_id, id, constituent_ids); (instruction, id) } } } - fn get_pointer_id( - &mut self, - arena: &crate::Arena, - handle: crate::Handle, - class: spirv::StorageClass, - ) -> Word { - let ty = &arena[handle]; - let type_id = self.get_type_id(arena, handle); - match ty.inner { - crate::TypeInner::Pointer { .. } => type_id, - _ => { - let pointer_id = self.generate_id(); - let mut instruction = Instruction::new(Op::TypePointer); - instruction.set_result(pointer_id); - instruction.add_operand((class) as u32); - instruction.add_operand(type_id); - instruction.to_words(&mut self.logical_layout.declarations); - - /* TODO - Not able to lookup Pointer, because there is no Handle in the IR for it. - Idea would be to not have any handles at all in the lookups, so we aren't bound - to the IR. We can then insert, like here runtime values to the lookups - */ - // self.lookup_type.insert(pointer_id, global_variable.ty); - pointer_id - } - } - } - - fn instruction_global_variable( + fn parse_global_variable( &mut self, arena: &crate::Arena, global_variable: &crate::GlobalVariable, handle: crate::Handle, ) -> (Instruction, Word) { - let mut instruction = Instruction::new(Op::Variable); let id = self.generate_id(); let class = match global_variable.class { @@ -606,40 +938,32 @@ impl Writer { self.try_add_capabilities(class.required_capabilities()); let pointer_id = self.get_pointer_id(arena, global_variable.ty, class); - - instruction.set_type(pointer_id); - instruction.set_result(id); - instruction.add_operand(class as u32); + let instruction = self.instruction_variable(pointer_id, id, class, None); if self.writer_flags.contains(WriterFlags::DEBUG) { - let mut debug_instruction = Instruction::new(Op::Name); - debug_instruction.set_result(id); - debug_instruction.add_operands(helpers::string_to_words( - global_variable.name.as_ref().unwrap().as_str(), - )); - self.debugs.push(debug_instruction); + self.debugs + .push(self.instruction_name(id, global_variable.name.as_ref().unwrap().as_str())); } match global_variable.binding.as_ref().unwrap() { crate::Binding::Location(location) => { - let mut instruction = Instruction::new(Op::Decorate); - instruction.add_operand(id); - instruction.add_operand(spirv::Decoration::Location as u32); - instruction.add_operand(*location); - self.annotations.push(instruction); + self.annotations.push(self.instruction_decorate( + id, + spirv::Decoration::Location, + &[*location], + )); } crate::Binding::Descriptor { set, binding } => { - let mut set_instruction = Instruction::new(Op::Decorate); - set_instruction.add_operand(id); - set_instruction.add_operand(spirv::Decoration::DescriptorSet as u32); - set_instruction.add_operand(*set); - self.annotations.push(set_instruction); - - let mut binding_instruction = Instruction::new(Op::Decorate); - binding_instruction.add_operand(id); - binding_instruction.add_operand(spirv::Decoration::Binding as u32); - binding_instruction.add_operand(*binding); - self.annotations.push(binding_instruction); + self.annotations.push(self.instruction_decorate( + id, + spirv::Decoration::DescriptorSet, + &[*set], + )); + self.annotations.push(self.instruction_decorate( + id, + spirv::Decoration::Binding, + &[*binding], + )); } crate::Binding::BuiltIn(built_in) => { let built_in = match built_in { @@ -660,11 +984,11 @@ impl Writer { crate::BuiltIn::WorkGroupId => spirv::BuiltIn::WorkgroupId, }; - let mut instruction = Instruction::new(Op::Decorate); - instruction.add_operand(id); - instruction.add_operand(spirv::Decoration::BuiltIn as u32); - instruction.add_operand(built_in as u32); - self.annotations.push(instruction); + self.annotations.push(self.instruction_decorate( + id, + spirv::Decoration::BuiltIn, + &[built_in as u32], + )); } } @@ -674,22 +998,7 @@ impl Writer { (instruction, id) } - fn write_physical_layout(&mut self) { - self.physical_layout.bound = self.id_count + 1; - } - - fn instruction_source( - &self, - source_language: spirv::SourceLanguage, - version: u32, - ) -> Instruction { - let mut instruction = Instruction::new(Op::Source); - instruction.add_operand(source_language as u32); - instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); - instruction - } - - fn instruction_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { + fn parse_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { let mut id = None; for (k, v) in self.lookup_function_type.iter() { @@ -702,23 +1011,19 @@ impl Writer { if id.is_none() { let _id = self.generate_id(); id = Some(_id); - - let mut instruction = Instruction::new(Op::TypeFunction); - instruction.set_result(_id); - instruction.add_operand(lookup_function_type.return_type_id); - - for parameter_type_id in lookup_function_type.parameter_type_ids.iter() { - instruction.add_operand(*parameter_type_id); - } - - self.lookup_function_type.insert(_id, lookup_function_type); + let instruction = self.instruction_type_function( + _id, + lookup_function_type.return_type_id, + lookup_function_type.parameter_type_ids.clone(), + ); instruction.to_words(&mut self.logical_layout.declarations); + self.lookup_function_type.insert(_id, lookup_function_type); } id.unwrap() } - fn instruction_function( + fn parse_function( &mut self, handle: crate::Handle, function: &crate::Function, @@ -728,13 +1033,6 @@ impl Writer { let return_type_id = self.get_function_type(function.return_type, arena); - let mut instruction = Instruction::new(Op::Function); - instruction.set_type(return_type_id); - instruction.set_result(id); - - let control = spirv::FunctionControl::empty(); - instruction.add_operand(control.bits()); - let mut parameter_type_ids = Vec::with_capacity(function.parameter_types.len()); for parameter_type in function.parameter_types.iter() { parameter_type_ids.push(self.get_type_id(arena, *parameter_type)) @@ -745,12 +1043,16 @@ impl Writer { parameter_type_ids, }; - let type_function_id = self.instruction_function_type(lookup_function_type); + let type_function_id = self.parse_function_type(lookup_function_type); - instruction.add_operand(type_function_id); + let instruction = self.instruction_function( + return_type_id, + id, + spirv::FunctionControl::empty(), + type_function_id, + ); self.lookup_function.insert(id, handle); - instruction } @@ -784,17 +1086,16 @@ impl Writer { let id = self.generate_id(); let type_id = self.get_type_id(&ir_module.types, *ty); - let mut instruction = Instruction::new(Op::CompositeConstruct); - instruction.set_type(type_id); - instruction.set_result(id); - + let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { let expression = &function.expressions[*component]; let (component_id, _) = self.parse_expression(ir_module, &function, expression, output); - instruction.add_operand(component_id); + constituent_ids.push(component_id); } + let instruction = + self.instruction_composite_construct(type_id, id, constituent_ids); output.push(instruction); (id, inner) @@ -865,18 +1166,21 @@ impl Writer { // TODO Quick fix let load_id = self.generate_id(); - let mut instruction = Instruction::new(Op::Load); - instruction.set_type(result_type_id.unwrap()); - instruction.set_result(load_id); - instruction.add_operand(vector_id.unwrap()); - output.push(instruction); + let load_instruction = self.instruction_load( + result_type_id.unwrap(), + load_id, + vector_id.unwrap(), + None, + ); + output.push(load_instruction); - let mut instruction = Instruction::new(Op::VectorTimesScalar); - instruction.set_type(result_type_id.unwrap()); - instruction.set_result(id); - instruction.add_operand(load_id); - instruction.add_operand(scalar_id.unwrap()); + let instruction = self.instruction_vector_times_scalar( + result_type_id.unwrap(), + id, + load_id, + scalar_id.unwrap(), + ); output.push(instruction); // TODO Not sure how or what to return @@ -894,23 +1198,21 @@ impl Writer { crate::Expression::LocalVariable(variable) => { let id = self.generate_id(); let var = &function.local_variables[*variable]; - let ty = &ir_module.types[var.ty]; let pointer_id = self.get_pointer_id(&ir_module.types, var.ty, spirv::StorageClass::Function); - let mut instruction = Instruction::new(Op::Variable); - instruction.set_type(pointer_id); - instruction.set_result(id); - instruction.add_operand(spirv::StorageClass::Function as u32); + let instruction = + self.instruction_variable(pointer_id, id, spirv::StorageClass::Function, None); + output.push(instruction); (id, &ty.inner) } _ => unimplemented!("{:?}", expression), } } - fn instruction_function_block( + fn parse_function_block( &mut self, ir_module: &crate::Module, function: &crate::Function, @@ -918,27 +1220,14 @@ impl Writer { output: &mut Vec, ) -> Instruction { match statement { - crate::Statement::Return { value } => { - match function.return_type { - Some(_) => { - let value = value.unwrap(); - - // Parse the expression - let value_expression = &function.expressions[value]; - let (value_id, _) = - self.parse_expression(ir_module, function, value_expression, output); - - // Construct the return value instruction - let mut instruction = Instruction::new(Op::ReturnValue); - instruction.add_operand(value_id); - instruction - } - None => Instruction::new(Op::Return), + crate::Statement::Return { .. } => match function.return_type { + Some(ty) => { + let value_id = self.get_type_id(&ir_module.types, ty); + self.instruction_return_value(value_id) } - } + None => self.instruction_return(), + }, crate::Statement::Store { pointer, value } => { - let mut instruction = Instruction::new(Op::Store); - let pointer_expression = &function.expressions[*pointer]; let value_expression = &function.expressions[*value]; let (pointer_id, _) = @@ -946,23 +1235,14 @@ impl Writer { let (value_id, _) = self.parse_expression(ir_module, function, value_expression, output); - instruction.add_operand(pointer_id); - instruction.add_operand(value_id); - - instruction + self.instruction_store(pointer_id, value_id) } _ => unimplemented!(), } } - fn instruction_label(&mut self) -> Instruction { - let mut instruction = Instruction::new(Op::Label); - instruction.set_result(self.generate_id()); - instruction - } - - fn instruction_function_end(&self) -> Instruction { - Instruction::new(Op::FunctionEnd) + fn write_physical_layout(&mut self) { + self.physical_layout.bound = self.id_count + 1; } fn write_logical_layout(&mut self, ir_module: &crate::Module) { @@ -976,18 +1256,15 @@ impl Writer { for (handle, function) in ir_module.functions.iter() { let mut function_instructions: Vec = vec![]; - function_instructions.push(self.instruction_function( - handle, - function, - &ir_module.types, - )); + function_instructions.push(self.parse_function(handle, function, &ir_module.types)); - function_instructions.push(self.instruction_label()); + let id = self.generate_id(); + function_instructions.push(self.instruction_label(id)); for block in function.body.iter() { let mut output: Vec = vec![]; let instruction = - self.instruction_function_block(ir_module, function, &block, &mut output); + self.parse_function_block(ir_module, function, &block, &mut output); function_instructions.append(&mut output); function_instructions.push(instruction); } @@ -1137,6 +1414,44 @@ mod tests { validate_instruction(output.as_slice(), &instruction); } + #[test] + fn test_instruction_name() { + let writer = create_writer(); + let instruction = writer.instruction_name(1, "Test"); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Name, + wc: 3, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_execution_mode() { + let writer = create_writer(); + let instruction = writer.instruction_execution_mode(1, ExecutionMode::OriginUpperLeft); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ExecutionMode, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + #[test] fn test_instruction_source() { let writer = create_writer(); @@ -1159,8 +1474,8 @@ mod tests { #[test] fn test_instruction_label() { - let mut writer = create_writer(); - let instruction = writer.instruction_label(); + let writer = create_writer(); + let instruction = writer.instruction_label(1); let mut output = vec![]; let requirements = SpecRequirements { @@ -1195,6 +1510,25 @@ mod tests { validate_instruction(output.as_slice(), &instruction); } + #[test] + fn test_instruction_decorate() { + let writer = create_writer(); + let instruction = writer.instruction_decorate(1, Decoration::Location, &[1]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Decorate, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + #[test] fn test_write_physical_layout() { let mut writer = create_writer(); From c2a220840f449687f8861879fb0f7d10c416adb9 Mon Sep 17 00:00:00 2001 From: Gabriel Majeri Date: Mon, 29 Jun 2020 17:47:07 +0300 Subject: [PATCH 0093/2212] Document almost everything --- src/arena.rs | 9 +++ src/back/mod.rs | 2 + src/front/mod.rs | 2 + src/front/wgsl.rs | 3 + src/lib.rs | 140 ++++++++++++++++++++++++++++++++++++++++++ src/proc/mod.rs | 2 + src/proc/validator.rs | 2 + 7 files changed, 160 insertions(+) diff --git a/src/arena.rs b/src/arena.rs index d9c760f90..0a5706ac3 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -73,6 +73,10 @@ impl Handle { /// An arena holding some kind of component (e.g., type, constant, /// instruction, etc.) that can be referenced. +/// +/// Adding new items to the arena produces a strongly-typed [`Handle`]. +/// The arena can be indexed using the given handle to obtain +/// a reference to the stored item. #[derive(Debug)] pub struct Arena { /// Values of this arena. @@ -86,18 +90,23 @@ impl Default for Arena { } impl Arena { + /// Create a new arena with no initial capacity allocated. pub fn new() -> Self { Arena { data: Vec::new() } } + /// Returns the current number of items stored in this arena. pub fn len(&self) -> usize { self.data.len() } + /// Returns `true` if the arena contains no elements. pub fn is_empty(&self) -> bool { self.data.is_empty() } + /// Returns an iterator over the items stored in this arena, returning both + /// the item's handle and a reference to it. pub fn iter(&self) -> impl Iterator, &T)> { self.data.iter().enumerate().map(|(i, v)| { let position = i + 1; diff --git a/src/back/mod.rs b/src/back/mod.rs index 8e310f7a8..ce751b11e 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -1,3 +1,5 @@ +//! Functions which export shader modules into binary and text formats. + pub mod msl; #[cfg(feature = "spirv")] pub mod spv; diff --git a/src/front/mod.rs b/src/front/mod.rs index bb10fbdc7..cae930128 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,3 +1,5 @@ +//! Parsers which load shaders into memory. + #[cfg(feature = "glsl")] pub mod glsl; #[cfg(feature = "spirv")] diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 485e207f0..b5b1c5e2c 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1,3 +1,6 @@ +//! Front end for consuming [WebGPU Shading Language][wgsl]. +//! +//! [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html use crate::{ arena::{Arena, Handle}, proc::{ResolveError, Typifier}, diff --git a/src/lib.rs b/src/lib.rs index b35a75968..49e4703e4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,9 @@ +//! Universal shader translator. +//! +//! The central structure of the crate is [`Module`]. +//! +//! To improve performance and reduce memory usage, most structures are stored +//! in an [`Arena`], and can be retrieved using the corresponding [`Handle`]. #![allow(clippy::new_without_default)] mod arena; @@ -13,23 +19,36 @@ use std::{ num::NonZeroU32, }; +/// Hash map that is faster but not resilient to DoS attacks. pub type FastHashMap = HashMap>; +/// Hash set that is faster but not resilient to DoS attacks. pub type FastHashSet = HashSet>; +/// Metadata for a given module. #[derive(Clone, Debug)] pub struct Header { + /// Major, minor and patch version. + /// + /// Currently used only for the SPIR-V back end. pub version: (u8, u8, u8), + /// Magic number identifying the tool that generated the shader code. + /// + /// Can safely be set to 0. pub generator: u32, } +/// Stage of the programmable pipeline. #[derive(Clone, Copy, Debug, PartialEq)] +#[allow(missing_docs)] // The names are self evident pub enum ShaderStage { Vertex, Fragment, Compute, } +/// Class of storage for variables. #[derive(Clone, Copy, Debug, PartialEq)] +#[allow(missing_docs)] // The names are self evident pub enum StorageClass { Constant, Function, @@ -41,6 +60,7 @@ pub enum StorageClass { WorkGroup, } +/// Built-in inputs and outputs. #[derive(Clone, Copy, Debug, PartialEq)] pub enum BuiltIn { // vertex @@ -63,32 +83,46 @@ pub enum BuiltIn { WorkGroupId, } +/// Number of bytes. pub type Bytes = u8; +/// Number of components in a vector. #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VectorSize { + /// 2D vector Bi = 2, + /// 3D vector Tri = 3, + /// 4D vector Quad = 4, } +/// Primitive type for a scalar. #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ScalarKind { + /// Signed integer type. Sint, + /// Unsigned integer type. Uint, + /// Floating point type. Float, + /// Boolean type. Bool, } +/// Size of an array. #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ArraySize { + /// The array size is known at compilation. Static(u32), + /// The array size can change at runtime. Dynamic, } +/// Member of a user-defined structure. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug, PartialEq)] pub struct StructMember { @@ -98,70 +132,94 @@ pub struct StructMember { pub offset: u32, } +/// The number of dimensions an image has. #[derive(Clone, Copy, Debug, PartialEq)] pub enum ImageDimension { + /// 1D image D1, + /// 2D image D2, + /// 3D image D3, + /// Cube map Cube, } bitflags::bitflags! { + /// Flags describing an image. pub struct ImageFlags: u32 { + /// Image is an array. const ARRAYED = 0x1; + /// Image is multisampled. const MULTISAMPLED = 0x2; + /// Image is to be accessed with a sampler. const SAMPLED = 0x4; + /// Image can be used as a source for load ops. const CAN_LOAD = 0x10; + /// Image can be used as a target for store ops. const CAN_STORE = 0x20; } } +/// A data type declared in the module. #[derive(Debug, PartialEq)] pub struct Type { + /// The name of the type, if any. pub name: Option, + /// Inner structure that depends on the kind of the type. pub inner: TypeInner, } +/// Enum with additional information, depending on the kind of type. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug, PartialEq)] pub enum TypeInner { + /// Number of integral or floating-point kind. Scalar { kind: ScalarKind, width: Bytes, }, + /// Vector of numbers. Vector { size: VectorSize, kind: ScalarKind, width: Bytes, }, + /// Matrix of numbers. Matrix { columns: VectorSize, rows: VectorSize, kind: ScalarKind, width: Bytes, }, + /// Pointer to a value. Pointer { base: Handle, class: StorageClass, }, + /// Homogenous list of elements. Array { base: Handle, size: ArraySize, stride: Option, }, + /// User-defined structure. Struct { members: Vec, }, + /// Possibly multidimensional array of pixels. Image { base: Handle, dim: ImageDimension, flags: ImageFlags, }, + /// Can be used to sample values from images. Sampler { comparison: bool, }, } +/// Constant value. #[derive(Debug, PartialEq)] pub struct Constant { pub name: Option, @@ -170,6 +228,7 @@ pub struct Constant { pub ty: Handle, } +/// Additional information, dependendent on the kind of constant. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug, PartialEq)] pub enum ConstantInner { @@ -180,41 +239,59 @@ pub enum ConstantInner { Composite(Vec>), } +/// Describes how an input/output variable is to be bound. #[derive(Clone, Debug, PartialEq)] pub enum Binding { + /// Built-in shader variable. BuiltIn(BuiltIn), + /// Indexed location. Location(u32), + /// Binding within a descriptor set. Descriptor { set: u32, binding: u32 }, } bitflags::bitflags! { + /// Indicates how a global variable is used. pub struct GlobalUse: u8 { + /// Data will be read from the variable. const LOAD = 0x1; + /// Data will be written to the variable. const STORE = 0x2; } } +/// Variable defined at module level. #[derive(Clone, Debug, PartialEq)] pub struct GlobalVariable { + /// Name of the variable, if any. pub name: Option, + /// How this variable is to be stored. pub class: StorageClass, + /// How this variable is to be bound. pub binding: Option, + /// The type of this variable. pub ty: Handle, } +/// Variable defined at function level. #[derive(Clone, Debug)] pub struct LocalVariable { + /// Name of the variable, if any. pub name: Option, + /// The type of this variable. pub ty: Handle, + /// Initial value for this variable. pub init: Option>, } +/// Operation that can be applied on a single value. #[derive(Clone, Copy, Debug, PartialEq)] pub enum UnaryOperator { Negate, Not, } +/// Operation that can be applied on two values. #[derive(Clone, Copy, Debug, PartialEq)] pub enum BinaryOperator { Add, @@ -238,6 +315,7 @@ pub enum BinaryOperator { ShiftRightArithmetic, } +/// Built-in shader function. #[derive(Clone, Copy, Debug, PartialEq)] pub enum IntrinsicFunction { Any, @@ -248,6 +326,7 @@ pub enum IntrinsicFunction { IsNormal, } +/// Axis on which to compute a derivative. #[derive(Clone, Copy, Debug, PartialEq)] pub enum DerivativeAxis { X, @@ -255,121 +334,182 @@ pub enum DerivativeAxis { Width, } +/// An expression that can be evaluated to obtain a value. #[derive(Clone, Debug)] pub enum Expression { + /// Array access with a computed index. Access { base: Handle, index: Handle, //int }, + /// Array access with a known index. AccessIndex { base: Handle, index: u32, }, + /// Constant value. Constant(Handle), + /// Composite expression. Compose { ty: Handle, components: Vec>, }, + /// Reference a function parameter, by its index. FunctionParameter(u32), + /// Reference a global variable. GlobalVariable(Handle), + /// Reference a local variable. LocalVariable(Handle), + /// Load a value indirectly. Load { pointer: Handle, }, + /// Sample a point from an image. ImageSample { image: Handle, sampler: Handle, coordinate: Handle, }, + /// Apply an unary operator. Unary { op: UnaryOperator, expr: Handle, }, + /// Apply a binary operator. Binary { op: BinaryOperator, left: Handle, right: Handle, }, + /// Call an intrinsic function. Intrinsic { fun: IntrinsicFunction, argument: Handle, }, + /// Dot product between two vectors. DotProduct(Handle, Handle), + /// Cross product between two vectors. CrossProduct(Handle, Handle), + /// Compute the derivative on an axis. Derivative { axis: DerivativeAxis, //modifier, expr: Handle, }, + /// Call a function defined in this module. Call { name: String, arguments: Vec>, }, } +/// A code block is just a vector of statements. pub type Block = Vec; +/// Marker type, used for falling through in a switch statement. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug)] pub struct FallThrough; +/// Instructions which make up an executable block. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug)] pub enum Statement { + /// Empty statement, does nothing. Empty, + /// A block containing more statements, to be executed sequentially. Block(Block), + /// Conditionally executes one of two blocks, based on the value of the condition. If { condition: Handle, //bool accept: Block, reject: Block, }, + /// Conditionally executes one of multiple blocks, based on the value of the selector. Switch { selector: Handle, //int cases: FastHashMap)>, default: Block, }, + /// Executes a block repeatedly. Loop { body: Block, continuing: Block, }, //TODO: move terminator variations into a separate enum? + /// Exits the loop. Break, + /// Skips execution to the next iteration of the loop. Continue, + /// Returns from the function (possibly with a value). Return { value: Option>, }, + /// Aborts the current shader execution. Kill, + /// Stores a value at an address. Store { pointer: Handle, value: Handle, }, } +/// A function defined in the module. #[derive(Debug)] pub struct Function { + /// Name of the function, if any. pub name: Option, //pub control: spirv::FunctionControl, + /// The types of the parameters of this function. pub parameter_types: Vec>, + /// The return type of this function, if any. pub return_type: Option>, + /// Vector of global variable usages. + /// + /// Each item corresponds to a global variable in the module. pub global_usage: Vec, + /// Local variables defined and used in the function. pub local_variables: Arena, + /// Expressions used inside this function. pub expressions: Arena, + /// Block of instructions comprising the body of the function. pub body: Block, } +/// Exported function, to be run at a certain stage in the pipeline. #[derive(Debug)] pub struct EntryPoint { + /// The stage in the programmable pipeline this entry point is for. pub stage: ShaderStage, + /// Name identifying this entry point. pub name: String, + /// The function to be used. pub function: Handle, } +/// Shader module. +/// +/// A module is a set of constants, global variables and functions, as well as +/// the types required to define them. +/// +/// Some functions are marked as entry points, to be used in a certain shader stage. +/// +/// To create a new module, use [`Module::from_header`] or [`Module::generate_empty`]. +/// Alternatively, you can load an existing shader using one of the [available front ends][front]. +/// +/// When finished, you can export modules using one of the [available back ends][back]. #[derive(Debug)] pub struct Module { + /// Header containing module metadata. pub header: Header, + /// Storage for the types defined in this module. pub types: Arena, + /// Storage for the constants defined in this module. pub constants: Arena, + /// Storage for the global variables defined in this module. pub global_variables: Arena, + /// Storage for the functions defined in this module. pub functions: Arena, + /// Vector of exported entry points. pub entry_points: Vec, } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 18362d183..6269e0183 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,3 +1,5 @@ +//! Module processing functionality. + mod interface; mod typifier; mod validator; diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 613357e55..7976386fe 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -13,10 +13,12 @@ pub enum ValidationError { } impl Validator { + /// Construct a new validator instance. pub fn new() -> Self { Validator {} } + /// Check the given module to be valid. pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { for (handle, ty) in module.types.iter() { use crate::TypeInner as Ti; From 6f0f551bac9cf920d7bbc8c91f70e79776eb4e1b Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 30 Jun 2020 16:42:50 +0200 Subject: [PATCH 0094/2212] New GLSL frontend using pomelo (#87) * Add initial pomelo glsl work * Fix ref to glsl_old * Fix idents with numbers in lexer * Use glsl_new for .vert in convert example Controlled by PREFER_GLSL_NEW=1 env var Also add simple test files * Start making parser look like spec * Port 'old' lex.rs to glsl_new * Apply fixes after rebasing * Fix clippy issue * Fix PR comments - Make into optional feature glsl-new - Minor code style improvements --- Cargo.toml | 2 + examples/convert.rs | 35 +++- src/front/glsl_new/error.rs | 43 +++++ src/front/glsl_new/lex.rs | 311 +++++++++++++++++++++++++++++++++++ src/front/glsl_new/mod.rs | 48 ++++++ src/front/glsl_new/parser.rs | 185 +++++++++++++++++++++ src/front/glsl_new/token.rs | 7 + src/front/mod.rs | 2 + test-data/simple.frag | 5 + test-data/simple.vert | 5 + test-data/simple.wgsl | 8 + 11 files changed, 648 insertions(+), 3 deletions(-) create mode 100644 src/front/glsl_new/error.rs create mode 100644 src/front/glsl_new/lex.rs create mode 100644 src/front/glsl_new/mod.rs create mode 100644 src/front/glsl_new/parser.rs create mode 100644 src/front/glsl_new/token.rs create mode 100644 test-data/simple.frag create mode 100644 test-data/simple.vert create mode 100644 test-data/simple.wgsl diff --git a/Cargo.toml b/Cargo.toml index 10c8f94ed..f4cdd1f9b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,9 +16,11 @@ log = "0.4" num-traits = "0.2" spirv = { package = "spirv_headers", version = "1.4.2", optional = true } glsl = { version = "4", optional = true } +pomelo = { version = "0.1.4", optional = true } [features] glsl_preprocessor = ["glsl"] +glsl-new = ["pomelo"] [dev-dependencies] env_logger = "0.6" diff --git a/examples/convert.rs b/examples/convert.rs index 7a2b7cfa0..5658f5a31 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -29,6 +29,9 @@ fn main() { println!("Call with "); return; } + #[cfg(any(feature = "glsl", feature = "glsl-new"))] + let prefer_glsl_new = + !cfg!(feature = "glsl") || env::var("PREFER_GLSL_NEW").unwrap_or_default() == "1"; let module = match Path::new(&args[1]) .extension() .expect("Input has no extension?") @@ -44,11 +47,37 @@ fn main() { let input = fs::read_to_string(&args[1]).unwrap(); naga::front::wgsl::parse_str(&input).unwrap() } - #[cfg(feature = "glsl")] + #[cfg(any(feature = "glsl", feature = "glsl-new"))] "vert" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Vertex) - .unwrap() + let mut module: Option = None; + if prefer_glsl_new { + #[cfg(feature = "glsl-new")] + { + module = Some( + naga::front::glsl_new::parse_str( + &input, + "main".to_string(), + naga::ShaderStage::Vertex, + ) + .unwrap(), + ) + } + } + if module.is_none() { + #[cfg(feature = "glsl")] + { + module = Some( + naga::front::glsl::parse_str( + &input, + "main".to_string(), + naga::ShaderStage::Vertex, + ) + .unwrap(), + ) + } + } + module.unwrap() } #[cfg(feature = "glsl")] "frag" => { diff --git a/src/front/glsl_new/error.rs b/src/front/glsl_new/error.rs new file mode 100644 index 000000000..991e6050a --- /dev/null +++ b/src/front/glsl_new/error.rs @@ -0,0 +1,43 @@ +use std::{fmt, io}; + +#[derive(Debug)] +pub enum ErrorKind { + InvalidInput, + IoError(io::Error), +} + +impl fmt::Display for ErrorKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ErrorKind::IoError(error) => write!(f, "IO Error {}", error), + ErrorKind::InvalidInput => write!(f, "InvalidInput"), + } + } +} + +#[derive(Debug)] +pub struct ParseError { + pub kind: ErrorKind, +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self) + } +} + +impl From for ParseError { + fn from(error: io::Error) -> Self { + ParseError { + kind: ErrorKind::IoError(error), + } + } +} + +impl From for ParseError { + fn from(kind: ErrorKind) -> Self { + ParseError { kind } + } +} + +impl std::error::Error for ParseError {} diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs new file mode 100644 index 000000000..8097518a6 --- /dev/null +++ b/src/front/glsl_new/lex.rs @@ -0,0 +1,311 @@ +use super::parser::Token; +use super::token::TokenMetadata; +use std::{iter::Enumerate, str::Lines}; + +fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { + if input.starts_with(what) { + Some(&input[what.len()..]) + } else { + None + } +} + +fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str, usize) { + let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); + let (o, i) = input.split_at(pos); + (o, i, pos) +} + +pub fn consume_token(mut input: &str) -> (Option, &str) { + let start = input + .find(|c: char| !c.is_whitespace()) + .unwrap_or_else(|| input.chars().count()); + input = &input[start..]; + + let mut chars = input.chars(); + let cur = match chars.next() { + Some(c) => c, + None => return (None, input), + }; + let mut meta = TokenMetadata { + line: 0, + chars: start..start + 1, + }; + match cur { + ':' => (Some(Token::Colon(meta)), chars.as_str()), + ';' => (Some(Token::Semicolon(meta)), chars.as_str()), + ',' => (Some(Token::Comma(meta)), chars.as_str()), + '.' => (Some(Token::Dot(meta)), chars.as_str()), + + '(' => (Some(Token::LeftParen(meta)), chars.as_str()), + ')' => (Some(Token::RightParen(meta)), chars.as_str()), + '{' => (Some(Token::LeftBrace(meta)), chars.as_str()), + '}' => (Some(Token::RightBrace(meta)), chars.as_str()), + '[' => (Some(Token::LeftBracket(meta)), chars.as_str()), + ']' => (Some(Token::RightBracket(meta)), chars.as_str()), + '<' | '>' => { + input = chars.as_str(); + let n1 = chars.next(); + let input1 = chars.as_str(); + let n2 = chars.next(); + match (cur, n1, n2) { + ('<', Some('<'), Some('=')) => { + meta.chars.end = start + 3; + (Some(Token::LeftAssign(meta)), chars.as_str()) + } + ('>', Some('>'), Some('=')) => { + meta.chars.end = start + 3; + (Some(Token::RightAssign(meta)), chars.as_str()) + } + ('<', Some('<'), _) => { + meta.chars.end = start + 2; + (Some(Token::LeftOp(meta)), input1) + } + ('>', Some('>'), _) => { + meta.chars.end = start + 2; + (Some(Token::RightOp(meta)), input1) + } + ('<', Some('='), _) => { + meta.chars.end = start + 2; + (Some(Token::LeOp(meta)), input1) + } + ('>', Some('='), _) => { + meta.chars.end = start + 2; + (Some(Token::GeOp(meta)), input1) + } + ('<', _, _) => (Some(Token::LeftAngle(meta)), input), + ('>', _, _) => (Some(Token::RightAngle(meta)), input), + _ => (None, input), + } + } + '0'..='9' => { + let (number, rest, pos) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); + if number.find('.').is_some() { + if ( + chars.next().map(|c| c.to_lowercase().next().unwrap()), + chars.next().map(|c| c.to_lowercase().next().unwrap()), + ) == (Some('l'), Some('f')) + { + meta.chars.end = start + pos + 2; + ( + Some(Token::DoubleConstant((meta, number.parse().unwrap()))), + chars.as_str(), + ) + } else { + meta.chars.end = start + pos; + ( + Some(Token::FloatConstant((meta, number.parse().unwrap()))), + chars.as_str(), + ) + } + } else { + meta.chars.end = start + pos; + ( + Some(Token::IntConstant((meta, number.parse().unwrap()))), + rest, + ) + } + } + 'a'..='z' | 'A'..='Z' | '_' => { + let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); + meta.chars.end = start + pos; + match word { + "void" => (Some(Token::Void(meta)), rest), + "vec4" => (Some(Token::Vec4(meta)), rest), + //TODO: remaining types + _ => (Some(Token::Identifier((meta, String::from(word)))), rest), + } + } + + '+' | '-' | '&' | '|' => { + input = chars.as_str(); + match chars.next() { + Some('=') => { + meta.chars.end = start + 2; + match cur { + '+' => (Some(Token::AddAssign(meta)), chars.as_str()), + '-' => (Some(Token::SubAssign(meta)), chars.as_str()), + '&' => (Some(Token::AndAssign(meta)), chars.as_str()), + '|' => (Some(Token::OrAssign(meta)), chars.as_str()), + '^' => (Some(Token::XorAssign(meta)), chars.as_str()), + _ => (None, input), + } + } + Some(cur) => { + meta.chars.end = start + 2; + match cur { + '+' => (Some(Token::IncOp(meta)), chars.as_str()), + '-' => (Some(Token::DecOp(meta)), chars.as_str()), + '&' => (Some(Token::AndOp(meta)), chars.as_str()), + '|' => (Some(Token::OrOp(meta)), chars.as_str()), + '^' => (Some(Token::XorOp(meta)), chars.as_str()), + _ => (None, input), + } + } + _ => match cur { + '+' => (Some(Token::Plus(meta)), input), + '-' => (Some(Token::Dash(meta)), input), + '&' => (Some(Token::Ampersand(meta)), input), + '|' => (Some(Token::VerticalBar(meta)), input), + '^' => (Some(Token::Caret(meta)), input), + _ => (None, input), + }, + } + } + + '%' | '!' | '=' => { + input = chars.as_str(); + match chars.next() { + Some('=') => { + meta.chars.end = start + 2; + match cur { + '%' => (Some(Token::ModAssign(meta)), chars.as_str()), + '!' => (Some(Token::NeOp(meta)), chars.as_str()), + '=' => (Some(Token::EqOp(meta)), chars.as_str()), + _ => (None, input), + } + } + _ => match cur { + '%' => (Some(Token::Percent(meta)), input), + '!' => (Some(Token::Bang(meta)), input), + '=' => (Some(Token::Equal(meta)), input), + _ => (None, input), + }, + } + } + + '*' => { + input = chars.as_str(); + match chars.next() { + Some('=') => { + meta.chars.end = start + 2; + (Some(Token::MulAssign(meta)), chars.as_str()) + } + //TODO: multi-line comments + // Some('/') => ( + // Token::MultiLineCommentClose, + // chars.as_str(), + // start, + // start + 2, + // ), + _ => (Some(Token::MulAssign(meta)), input), + } + } + '/' => { + input = chars.as_str(); + match chars.next() { + Some('=') => { + meta.chars.end = start + 2; + (Some(Token::DivAssign(meta)), chars.as_str()) + } + //TODO: line comments + // Some('/') => (Token::LineComment, chars.as_str(), start, start + 2), + //TODO: multi-line comments + // Some('*') => ( + // Token::MultiLineCommentOpen, + // chars.as_str(), + // start, + // start + 2, + // ), + _ => (Some(Token::Slash(meta)), input), + } + } + '#' => { + input = chars.as_str(); + let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); + meta.chars.end = start + pos; + match word { + "version" => (Some(Token::Version(meta)), rest), + _ => (None, input), + } + + //TODO: preprocessor + // if chars.next() == Some(cur) { + // (Token::TokenPasting, chars.as_str(), start, start + 2) + // } else { + // (Token::Preprocessor, input, start, start + 1) + // } + } + '~' => (Some(Token::Tilde(meta)), chars.as_str()), + '?' => (Some(Token::Question(meta)), chars.as_str()), + _ => (None, chars.as_str()), + } +} + +#[derive(Clone, Debug)] +pub struct Lexer<'a> { + lines: Enumerate>, + input: String, + line: usize, + offset: usize, +} + +impl<'a> Lexer<'a> { + pub fn new(input: &'a str) -> Self { + let mut lines = input.lines().enumerate(); + let (line, input) = lines.next().unwrap_or((0, "")); + let mut input = String::from(input); + + while input.ends_with('\\') { + if let Some((_, next)) = lines.next() { + input.pop(); + input.push_str(next); + } else { + break; + } + } + + Lexer { + lines, + input, + line, + offset: 0, + } + } + + #[must_use] + pub fn next(&mut self) -> Option { + let (token, rest) = consume_token(&self.input); + + if let Some(mut token) = token { + self.input = String::from(rest); + let meta = token.extra_mut(); + let end = meta.chars.end; + meta.line = self.line; + meta.chars.start += self.offset; + meta.chars.end += self.offset; + self.offset += end; + Some(token) + } else { + let (line, input) = self.lines.next()?; + + let mut input = String::from(input); + + while input.ends_with('\\') { + if let Some((_, next)) = self.lines.next() { + input.pop(); + input.push_str(next); + } else { + break; + } + } + + self.input = input; + self.line = line; + self.offset = 0; + self.next() + } + } + + // #[must_use] + // pub fn peek(&mut self) -> Option { + // self.clone().next() + // } +} + +impl<'a> Iterator for Lexer<'a> { + type Item = Token; + fn next(&mut self) -> Option { + self.next() + } +} diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs new file mode 100644 index 000000000..4b3c70daf --- /dev/null +++ b/src/front/glsl_new/mod.rs @@ -0,0 +1,48 @@ +use crate::{Arena, Constant, EntryPoint, Function, GlobalVariable, Header, Module, ShaderStage, Type}; + +mod lex; +use lex::Lexer; +mod error; +use error::{ErrorKind, ParseError}; +mod parser; +mod token; + +pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { + log::debug!("------ GLSL-pomelo ------"); + + let module = Module { + header: Header { + version: (1, 0, 0), + generator: 0, + }, + types: Arena::::new(), + constants: Arena::::new(), + global_variables: Arena::::new(), + functions: Arena::::new(), + entry_points: vec![], + }; + + let lex = Lexer::new(source); + let mut parser = parser::Parser::new(module); + + for token in lex { + log::debug!("token: {:#?}", token); + parser.parse(token).map_err(|_| ErrorKind::InvalidInput)?; + } + let (_, mut parsed_module) = parser.end_of_input().map_err(|_| ErrorKind::InvalidInput)?; + + // find entry point + let entry_func = parsed_module + .functions + .iter() + .find(|(_, f)| f.name.as_ref().filter(|n| **n == entry).is_some()); + if let Some((h, _)) = entry_func { + parsed_module.entry_points.push(EntryPoint { + stage, + name: entry, + function: h, + }); + } + + Ok(parsed_module) +} diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs new file mode 100644 index 000000000..67fe65737 --- /dev/null +++ b/src/front/glsl_new/parser.rs @@ -0,0 +1,185 @@ +#![allow(unused_braces)] +use pomelo::pomelo; + +pomelo! { + //%verbose; + %include { + use super::super::token::*; + use crate::{Arena, Expression, Function, LocalVariable, Module}; + } + %token #[derive(Debug)] pub enum Token {}; + %extra_argument Module; + %extra_token TokenMetadata; + %type Identifier String; + %type IntConstant i64; + %type UintConstant u64; + %type FloatConstant f32; + %type BoolConstant bool; + %type DoubleConstant f64; + %type String String; + %type arg_list Vec; + %type function_definition Function; + + %left Else; + %right Assign; + %left Or; + %left And; + %nonassoc Equal NotEqual; + %nonassoc Less LessEq Greater GreaterEq; + %left Plus Minus; + %left Mult Div; + %nonassoc Not; + + root ::= version_pragma translation_unit; + version_pragma ::= Version IntConstant Identifier?; + + // expression + variable_identifier ::= Identifier; + + primary_expression ::= variable_identifier; + primary_expression ::= IntConstant; + primary_expression ::= UintConstant; + primary_expression ::= FloatConstant; + primary_expression ::= BoolConstant; + primary_expression ::= DoubleConstant; + primary_expression ::= LeftParen expression RightParen; + + postfix_expression ::= primary_expression; + postfix_expression ::= postfix_expression LeftBracket integer_expression RightBracket; + postfix_expression ::= function_call; + postfix_expression ::= postfix_expression Dot FieldSelection; + postfix_expression ::= postfix_expression IncOp; + postfix_expression ::= postfix_expression DecOp; + + integer_expression ::= expression; + + function_call ::= function_call_generic; + function_call_generic ::= function_call_header_with_parameters RightParen; + function_call_generic ::= function_call_header_no_parameters RightParen; + function_call_header_no_parameters ::= function_call_header Void; + function_call_header_no_parameters ::= function_call_header; + function_call_header_with_parameters ::= function_call_header assignment_expression; + function_call_header_with_parameters ::= function_call_header_with_parameters Comma assignment_expression; + function_call_header ::= function_identifier LeftParen; + + // Grammar Note: Constructors look like functions, but lexical analysis recognized most of them as + // keywords. They are now recognized through “type_specifier”. + // Methods (.length), subroutine array calls, and identifiers are recognized through postfix_expression. + function_identifier ::= type_specifier; + function_identifier ::= postfix_expression; + + unary_expression ::= postfix_expression; + unary_expression ::= IncOp unary_expression; + unary_expression ::= DecOp unary_expression; + unary_expression ::= unary_operator unary_expression; + unary_operator ::= Plus; + unary_operator ::= Dash; + unary_operator ::= Bang; + unary_operator ::= Tilde; + multiplicative_expression ::= unary_expression; + multiplicative_expression ::= multiplicative_expression Star unary_expression; + multiplicative_expression ::= multiplicative_expression Slash unary_expression; + multiplicative_expression ::= multiplicative_expression Percent unary_expression; + additive_expression ::= multiplicative_expression; + additive_expression ::= additive_expression Plus multiplicative_expression; + additive_expression ::= additive_expression Dash multiplicative_expression; + shift_expression ::= additive_expression; + shift_expression ::= shift_expression LeftOp additive_expression; + shift_expression ::= shift_expression RightOp additive_expression; + relational_expression ::= shift_expression; + relational_expression ::= relational_expression LeftAngle shift_expression; + relational_expression ::= relational_expression RightAngle shift_expression; + relational_expression ::= relational_expression LeOp shift_expression; + relational_expression ::= relational_expression GeOp shift_expression; + equality_expression ::= relational_expression; + equality_expression ::= equality_expression EqOp relational_expression; + equality_expression ::= equality_expression NeOp relational_expression; + and_expression ::= equality_expression; + and_expression ::= and_expression Ampersand equality_expression; + exclusive_or_expression ::= and_expression; + exclusive_or_expression ::= exclusive_or_expression Caret and_expression; + inclusive_or_expression ::= exclusive_or_expression; + inclusive_or_expression ::= inclusive_or_expression VerticalBar exclusive_or_expression; + logical_and_expression ::= inclusive_or_expression; + logical_and_expression ::= logical_and_expression AndOp inclusive_or_expression; + logical_xor_expression ::= logical_and_expression; + logical_xor_expression ::= logical_xor_expression XorOp logical_and_expression; + logical_or_expression ::= logical_xor_expression; + logical_or_expression ::= logical_or_expression OrOp logical_xor_expression; + + conditional_expression ::= logical_or_expression; + conditional_expression ::= logical_or_expression Question expression Colon assignment_expression; + + assignment_expression ::= conditional_expression; + assignment_expression ::= unary_expression assignment_operator assignment_expression; + + assignment_operator ::= Equal; + assignment_operator ::= MulAssign; + assignment_operator ::= DivAssign; + assignment_operator ::= ModAssign; + assignment_operator ::= AddAssign; + assignment_operator ::= SubAssign; + assignment_operator ::= LeftAssign; + assignment_operator ::= RightAssign; + assignment_operator ::= AndAssign; + assignment_operator ::= XorAssign; + assignment_operator ::= OrAssign; + + expression ::= assignment_expression; + expression ::= expression Comma assignment_expression; + + // statement + statement ::= compound_statement; + statement ::= simple_statement; + + // Grammar Note: labeled statements for SWITCH only; 'goto' is not supported. + //simple_statement ::= declaration_statement; + simple_statement ::= expression_statement; + + compound_statement ::= LeftBrace RightBrace; + compound_statement ::= LeftBrace statement_list RightBrace; + + compound_statement_no_new_scope ::= LeftBrace RightBrace; + compound_statement_no_new_scope ::= LeftBrace statement_list RightBrace; + + statement_list ::= statement(s) { /*vec![s]*/ } + statement_list ::= statement_list/*(mut ss)*/ statement(s) { /*ss.push(s); ss*/ } + + expression_statement ::= Semicolon; + expression_statement ::= expression Semicolon; + + + + // function + function_prototype ::= function_declarator RightParen; + function_declarator ::= function_header; + function_header ::= fully_specified_type Identifier LeftParen; + + // type + fully_specified_type ::= type_specifier; + type_specifier ::= type_specifier_nonarray; + + type_specifier_nonarray ::= Void; + type_specifier_nonarray ::= Vec4; + //TODO: remaining types + + // misc + translation_unit ::= external_declaration; + translation_unit ::= translation_unit external_declaration; + + external_declaration ::= function_definition(f) { extra.functions.append(f); } + + function_definition ::= function_prototype compound_statement_no_new_scope { + Function { + name: Some(String::from("main")), + parameter_types: vec![], + return_type: None, + global_usage: vec![], + local_variables: Arena::::new(), + expressions: Arena::::new(), + body: vec![], + } + }; +} + +pub use parser::*; diff --git a/src/front/glsl_new/token.rs b/src/front/glsl_new/token.rs new file mode 100644 index 000000000..31daf24cb --- /dev/null +++ b/src/front/glsl_new/token.rs @@ -0,0 +1,7 @@ +use std::ops::Range; + +#[derive(Debug, Clone)] +pub struct TokenMetadata { + pub line: usize, + pub chars: Range, +} diff --git a/src/front/mod.rs b/src/front/mod.rs index cae930128..7e169017a 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -2,6 +2,8 @@ #[cfg(feature = "glsl")] pub mod glsl; +#[cfg(feature = "glsl-new")] +pub mod glsl_new; #[cfg(feature = "spirv")] pub mod spv; pub mod wgsl; diff --git a/test-data/simple.frag b/test-data/simple.frag new file mode 100644 index 000000000..2aea31896 --- /dev/null +++ b/test-data/simple.frag @@ -0,0 +1,5 @@ +#version 450 core + +void main() { + gl_FragDepth = 0; +} diff --git a/test-data/simple.vert b/test-data/simple.vert new file mode 100644 index 000000000..2a0aaea1c --- /dev/null +++ b/test-data/simple.vert @@ -0,0 +1,5 @@ +#version 450 core + +void main() { + gl_Position = vec4(1); +} diff --git a/test-data/simple.wgsl b/test-data/simple.wgsl new file mode 100644 index 000000000..35afac087 --- /dev/null +++ b/test-data/simple.wgsl @@ -0,0 +1,8 @@ +# vertex +[[builtin position]] var o_position : vec4; + +fn main() -> void { + o_position = vec4(1); + return; +} +entry_point vertex as "main" = main; From 1f5008f67388bc5bf9a3dac94a13d99414f5d6c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristoffer=20S=C3=B8holm?= Date: Fri, 26 Jun 2020 00:25:26 +0200 Subject: [PATCH 0095/2212] Refactor error handling in GLSL frontend --- Cargo.toml | 1 + src/front/glsl/helpers.rs | 13 +- src/front/glsl/mod.rs | 431 +++++++++++++++++--------------------- src/proc/typifier.rs | 23 +- 4 files changed, 221 insertions(+), 247 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f4cdd1f9b..66e3d3381 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ num-traits = "0.2" spirv = { package = "spirv_headers", version = "1.4.2", optional = true } glsl = { version = "4", optional = true } pomelo = { version = "0.1.4", optional = true } +thiserror = "1.0" [features] glsl_preprocessor = ["glsl"] diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs index 8377c057a..ea1b1e5b5 100644 --- a/src/front/glsl/helpers.rs +++ b/src/front/glsl/helpers.rs @@ -1,5 +1,16 @@ use crate::{Arena, ImageDimension, ImageFlags, ScalarKind, Type, TypeInner, VectorSize}; -use glsl::syntax::{BinaryOp, TypeSpecifierNonArray}; +use glsl::syntax::{BinaryOp, TypeSpecifierNonArray, UnaryOp}; + +pub fn glsl_to_spirv_unary_op(op: UnaryOp) -> crate::UnaryOperator { + match op { + UnaryOp::Inc => todo!(), + UnaryOp::Dec => todo!(), + UnaryOp::Add => todo!(), + UnaryOp::Minus => crate::UnaryOperator::Negate, + UnaryOp::Not => crate::UnaryOperator::Not, + UnaryOp::Complement => todo!(), + } +} pub fn glsl_to_spirv_binary_op(op: BinaryOp) -> crate::BinaryOperator { match op { diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 0414a6731..c5fa04950 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -8,140 +8,69 @@ use glsl::{ syntax::*, }; use parser::{Token, TokenMetadata}; -use std::fmt; mod helpers; mod parser; -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] pub enum ErrorKind { + #[error("Unexpected token:\nexpected: {}\ngot: {}", expected.iter().map(|t| t.type_to_string()).collect::>().join(" |"), got.token)] UnexpectedToken { expected: Vec, got: TokenMetadata, }, + #[error("Unexpected word:\nexpected: {}\ngot: {got}", expected.join("|"))] UnexpectedWord { expected: Vec<&'static str>, got: String, }, - ExpectedEOL { - got: TokenMetadata, - }, - UnknownPragma { - pragma: String, - }, - ExtensionNotSupported { - extension: String, - }, + #[error("Expected end of line:\ngot: {}", got.token)] + ExpectedEOL { got: TokenMetadata }, + #[error("Unknown pragma: {pragma}")] + UnknownPragma { pragma: String }, + #[error("The extension \"{extension}\" is not supported")] + ExtensionNotSupported { extension: String }, + #[error("All extensions can't be require or enable")] AllExtensionsEnabled, - ExtensionUnknownBehavior { - behavior: String, + #[error("The extension behavior must be one of require|enable|warn|disable got: {behavior}")] + ExtensionUnknownBehavior { behavior: String }, + #[error("The version {version} isn't supported; use either 450 or 460")] + UnsupportedVersion { version: usize }, + #[error("The profile {profile} isn't supported; use core")] + UnsupportedProfile { profile: String }, + #[error("The profile {profile} isn't defined; use core")] + UnknownProfile { profile: String }, + #[error("The preprocessor directive {directive} isn't defined")] + UnknownPreprocessorDirective { directive: String }, + #[error("The preprocessor directives \"else\", \"elif\" or \"endif\" must be preceded by an \"if\", token: {}", token.token)] + UnboundedIfCloserOrVariant { token: TokenMetadata }, + #[error("The preprocessor \"if\" directive can only contain integrals found: {}", token.token)] + NonIntegralType { token: TokenMetadata }, + #[error("Type resolver error: {kind}")] + TypeResolverError { + #[from] + kind: crate::proc::ResolveError, }, - UnsupportedVersion { - version: usize, - }, - UnsupportedProfile { - profile: String, - }, - UnknownProfile { - profile: String, - }, - UnknownPreprocessorDirective { - directive: String, - }, - UnboundedIfCloserOrVariant { - token: TokenMetadata, - }, - NonIntegralType { - token: TokenMetadata, + #[error("Parser error: {error}")] + ParseError { + #[from] + error: ParseError, }, + #[error("Macro can't begin with GL_")] ReservedMacro, + #[error("End of line")] EOL, + #[error("End of file")] EOF, } -impl fmt::Display for ErrorKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ErrorKind::UnexpectedToken { expected, got } => write!( - f, - "Unexpected token:\nexpected: {}\ngot: {}", - expected - .iter() - .map(|token| { - let mut type_string = token.type_to_string(); - type_string.push_str(" |"); - type_string - }) - .collect::(), - got.token - ), - ErrorKind::UnexpectedWord { expected, got } => write!( - f, - "Unexpected word:\nexpected: {}\ngot: {}", - expected.iter().fold(String::new(), |mut acc, word| { - acc.push_str(*word); - - acc.push_str("|"); - - acc - }), - got - ), - ErrorKind::ExpectedEOL { got } => { - write!(f, "Expected end of line:\ngot: {}", got.token) - } - ErrorKind::UnknownPragma { pragma } => write!(f, "Unknown pragma: {}", pragma), - ErrorKind::ExtensionNotSupported { extension } => { - write!(f, "The extension \"{}\" is not supported", extension) - } - ErrorKind::AllExtensionsEnabled => { - write!(f, "All extensions can't be require or enable") - } - ErrorKind::ExtensionUnknownBehavior { behavior } => write!( - f, - "The extension behavior must be one of require|enable|warn|disable got: {}", - behavior - ), - ErrorKind::UnsupportedVersion { version } => write!( - f, - "The version {} isn't supported use either 450 or 460", - version - ), - ErrorKind::UnsupportedProfile { profile } => { - write!(f, "The profile {} isn't supported use core", profile) - } - ErrorKind::UnknownProfile { profile } => { - write!(f, "The profile {} isn't defined use core", profile) - } - ErrorKind::UnknownPreprocessorDirective { directive } => { - write!(f, "The preprocessor directive {} isn't defined", directive) - } - ErrorKind::UnboundedIfCloserOrVariant { token } => { - write!(f, "The preprocessor directives \"else\", \"elif\" or \"endif\" must be preceded by an \"if\", token: {}", token.token) - } - ErrorKind::NonIntegralType { token } => { - write!(f, "The preprocessor \"if\" directive can only contain integrals found: {}", token.token) - } - ErrorKind::ReservedMacro => write!(f, "Macro can't begin with GL_"), - ErrorKind::EOL => write!(f, "End of line"), - ErrorKind::EOF => write!(f, "End of file"), - } - } -} - -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] +#[error("{kind}")] pub struct Error { - pub kind: ErrorKind, + #[from] + kind: ErrorKind, } -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self) - } -} - -impl std::error::Error for Error {} - #[derive(Debug, Copy, Clone)] enum Global { Variable(Handle), @@ -160,8 +89,8 @@ struct Parser<'a> { } impl<'a> Parser<'a> { - pub fn new(source: &'a str, shader_stage: ShaderStage) -> Result { - Ok(Self { + pub fn new(source: &'a str, shader_stage: ShaderStage) -> Self { + Self { source, types: Arena::new(), globals: Arena::new(), @@ -170,11 +99,11 @@ impl<'a> Parser<'a> { functions: Arena::new(), function_lookup: FastHashMap::default(), shader_stage, - }) + } } - pub fn parse(mut self, entry: String) -> Result { - let ast = TranslationUnit::parse(self.source)?; + pub fn parse(mut self, entry: String) -> Result { + let ast = TranslationUnit::parse(self.source).map_err(|e| Error { kind: e.into() })?; //println!("{:#?}", ast); @@ -188,7 +117,7 @@ impl<'a> Parser<'a> { unreachable!() } ExternalDeclaration::FunctionDefinition(function) => { - let function = self.parse_function_definition(function); + let function = self.parse_function_definition(function)?; if *self.functions[function].name.as_ref().unwrap() == entry { assert!(entry_point.is_none()); @@ -312,7 +241,10 @@ impl<'a> Parser<'a> { }) } - fn parse_function_definition(&mut self, function: FunctionDefinition) -> Handle { + fn parse_function_definition( + &mut self, + function: FunctionDefinition, + ) -> Result, Error> { let name = function.prototype.name.0; // Parse return type @@ -372,7 +304,7 @@ impl<'a> Parser<'a> { &mut local_variables, &mut locals_map, ¶meter_lookup, - ); + )?; } _ => unimplemented!(), }, @@ -388,7 +320,7 @@ impl<'a> Parser<'a> { &mut local_variables, &mut locals_map, ¶meter_lookup, - )); + )?); } SimpleStatement::Selection(_) => unimplemented!(), SimpleStatement::Switch(_) => unimplemented!(), @@ -399,13 +331,15 @@ impl<'a> Parser<'a> { JumpStatement::Break => crate::Statement::Break, JumpStatement::Return(expr) => crate::Statement::Return { value: expr.map(|expr| { - let expr = self.parse_expression( - *expr, - &mut expressions, - &mut local_variables, - &mut locals_map, - ¶meter_lookup, - ); + let expr = self + .parse_expression( + *expr, + &mut expressions, + &mut local_variables, + &mut locals_map, + ¶meter_lookup, + ) + .unwrap(); expressions.append(expr) }), }, @@ -427,7 +361,7 @@ impl<'a> Parser<'a> { self.function_lookup.insert(name, handle); - handle + Ok(handle) } fn parse_local_variable( @@ -437,7 +371,7 @@ impl<'a> Parser<'a> { locals: &mut Arena, locals_map: &mut FastHashMap>, parameter_lookup: &FastHashMap, - ) -> Handle { + ) -> Result, Error> { let name = init.head.name.map(|d| d.0); let ty = { let ty = self.parse_type(init.head.ty.ty).unwrap(); @@ -459,15 +393,17 @@ impl<'a> Parser<'a> { } }; - let initializer = init.head.initializer.map(|initializer| { - self.parse_initializer( + let initializer = if let Some(initializer) = init.head.initializer { + Some(self.parse_initializer( initializer, expressions, locals, locals_map, parameter_lookup, - ) - }); + )?) + } else { + None + }; let handle = locals.append(LocalVariable { name: name.clone(), @@ -477,7 +413,7 @@ impl<'a> Parser<'a> { locals_map.insert(name.unwrap(), handle); - handle + Ok(handle) } fn parse_initializer( @@ -487,13 +423,18 @@ impl<'a> Parser<'a> { locals: &mut Arena, locals_map: &mut FastHashMap>, parameter_lookup: &FastHashMap, - ) -> Handle { + ) -> Result, Error> { match initializer { Initializer::Simple(expr) => { - let handle = - self.parse_expression(*expr, expressions, locals, locals_map, parameter_lookup); + let handle = self.parse_expression( + *expr, + expressions, + locals, + locals_map, + parameter_lookup, + )?; - expressions.append(handle) + Ok(expressions.append(handle)) } Initializer::List(_exprs) => unimplemented!(), } @@ -506,7 +447,7 @@ impl<'a> Parser<'a> { locals: &mut Arena, locals_map: &mut FastHashMap>, parameter_lookup: &FastHashMap, - ) -> crate::Statement { + ) -> Result { match expr { Expr::Assignment(reg, op, value) => { let pointer = { @@ -516,7 +457,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, - ); + )?; expressions.append(pointer) }; @@ -526,7 +467,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, - ); + )?; let value = match op { AssignmentOp::Equal => right, AssignmentOp::Mult => Expression::Binary { @@ -583,10 +524,10 @@ impl<'a> Parser<'a> { }, }; - crate::Statement::Store { + Ok(crate::Statement::Store { pointer, value: expressions.append(value), - } + }) } Expr::FunCall(_, _) => unimplemented!(), Expr::PostInc(_) => unimplemented!(), @@ -602,14 +543,14 @@ impl<'a> Parser<'a> { locals: &mut Arena, locals_map: &mut FastHashMap>, parameter_lookup: &FastHashMap, - ) -> Expression { + ) -> Result { match expr { Expr::Variable(ident) => { let name = ident.0; match name.as_str() { - "gl_VertexIndex" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + "gl_VertexIndex" => Ok(Expression::GlobalVariable( + self.globals.fetch_or_append(GlobalVariable { name: Some(name), class: StorageClass::Input, binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), @@ -620,10 +561,10 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } - "gl_InstanceIndex" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + }), + )), + "gl_InstanceIndex" => Ok(Expression::GlobalVariable( + self.globals.fetch_or_append(GlobalVariable { name: Some(name), class: StorageClass::Input, binding: Some(Binding::BuiltIn(BuiltIn::InstanceIndex)), @@ -634,10 +575,10 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } - "gl_BaseVertex" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + }), + )), + "gl_BaseVertex" => Ok(Expression::GlobalVariable( + self.globals.fetch_or_append(GlobalVariable { name: Some(name), class: StorageClass::Input, binding: Some(Binding::BuiltIn(BuiltIn::BaseVertex)), @@ -648,10 +589,10 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } - "gl_BaseInstance" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + }), + )), + "gl_BaseInstance" => Ok(Expression::GlobalVariable( + self.globals.fetch_or_append(GlobalVariable { name: Some(name), class: StorageClass::Input, binding: Some(Binding::BuiltIn(BuiltIn::BaseInstance)), @@ -662,10 +603,10 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } - "gl_Position" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + }), + )), + "gl_Position" => Ok(Expression::GlobalVariable(self.globals.fetch_or_append( + GlobalVariable { name: Some(name), class: match self.shader_stage { ShaderStage::Vertex => StorageClass::Output, @@ -681,10 +622,10 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } - "gl_PointSize" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + }, + ))), + "gl_PointSize" => Ok(Expression::GlobalVariable(self.globals.fetch_or_append( + GlobalVariable { name: Some(name), class: StorageClass::Output, binding: Some(Binding::BuiltIn(BuiltIn::PointSize)), @@ -695,10 +636,10 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } - "gl_ClipDistance" => { - Expression::GlobalVariable(self.globals.fetch_or_append(GlobalVariable { + }, + ))), + "gl_ClipDistance" => Ok(Expression::GlobalVariable( + self.globals.fetch_or_append(GlobalVariable { name: Some(name), class: StorageClass::Output, binding: Some(Binding::BuiltIn(BuiltIn::ClipDistance)), @@ -709,24 +650,24 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } + }), + )), other => { if let Some(global) = self.globals_lookup.get(other) { match *global { - Global::Variable(handle) => Expression::GlobalVariable(handle), + Global::Variable(handle) => Ok(Expression::GlobalVariable(handle)), Global::StructShorthand(struct_handle, index) => { - Expression::AccessIndex { + Ok(Expression::AccessIndex { base: expressions .append(Expression::GlobalVariable(struct_handle)), index, - } + }) } } } else if let Some(expr) = parameter_lookup.get(other) { - expr.clone() + Ok(expr.clone()) } else if let Some(local) = locals_map.get(other) { - Expression::LocalVariable(*local) + Ok(Expression::LocalVariable(*local)) } else { println!("{}", other); panic!() @@ -734,8 +675,8 @@ impl<'a> Parser<'a> { } } } - Expr::IntConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { + Expr::IntConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( + Constant { name: None, specialization: None, inner: ConstantInner::Sint(value as i64), @@ -746,10 +687,10 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } - Expr::UIntConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { + }, + ))), + Expr::UIntConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( + Constant { name: None, specialization: None, inner: ConstantInner::Uint(value as u64), @@ -760,10 +701,10 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } - Expr::BoolConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { + }, + ))), + Expr::BoolConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( + Constant { name: None, specialization: None, inner: ConstantInner::Bool(value), @@ -774,10 +715,10 @@ impl<'a> Parser<'a> { width: 1, }, }), - })) - } - Expr::FloatConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { + }, + ))), + Expr::FloatConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( + Constant { name: None, specialization: None, inner: ConstantInner::Float(value as f64), @@ -788,10 +729,10 @@ impl<'a> Parser<'a> { width: 32, }, }), - })) - } - Expr::DoubleConst(value) => { - Expression::Constant(self.constants.fetch_or_append(Constant { + }, + ))), + Expr::DoubleConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( + Constant { name: None, specialization: None, inner: ConstantInner::Float(value), @@ -802,25 +743,37 @@ impl<'a> Parser<'a> { width: 64, }, }), - })) + }, + ))), + Expr::Unary(op, reg) => { + let expr = + self.parse_expression(*reg, expressions, locals, locals_map, parameter_lookup)?; + Ok(Expression::Unary { + op: helpers::glsl_to_spirv_unary_op(op), + expr: expressions.append(expr), + }) } - Expr::Unary(_op, _reg) => unimplemented!(), Expr::Binary(op, left, right) => { - let left = - self.parse_expression(*left, expressions, locals, locals_map, parameter_lookup); + let left = self.parse_expression( + *left, + expressions, + locals, + locals_map, + parameter_lookup, + )?; let right = self.parse_expression( *right, expressions, locals, locals_map, parameter_lookup, - ); + )?; - Expression::Binary { + Ok(Expression::Binary { op: helpers::glsl_to_spirv_binary_op(op), left: expressions.append(left), right: expressions.append(right), - } + }) } Expr::Ternary(_condition, _accept, _reject) => unimplemented!(), Expr::Assignment(_, _, _) => panic!(), @@ -832,7 +785,7 @@ impl<'a> Parser<'a> { }; match name.as_str() { - "vec2" | "vec3" | "vec4" => Expression::Compose { + "vec2" | "vec3" | "vec4" => Ok(Expression::Compose { ty: self.types.fetch_or_append(Type { name: None, inner: TypeInner::Vector { @@ -849,17 +802,19 @@ impl<'a> Parser<'a> { components: args .into_iter() .map(|arg| { - let expr = self.parse_expression( - arg, - expressions, - locals, - locals_map, - parameter_lookup, - ); + let expr = self + .parse_expression( + arg, + expressions, + locals, + locals_map, + parameter_lookup, + ) + .unwrap(); expressions.append(expr) }) .collect(), - }, + }), "texture" => { let (image, sampler) = if let Expr::FunCall(ident, mut sample_args) = args.remove(0) { @@ -876,14 +831,14 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, - ), + )?, self.parse_expression( sample_args.remove(0), expressions, locals, locals_map, parameter_lookup, - ), + )?, ), _ => unimplemented!(), } @@ -897,30 +852,32 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, - ); + )?; - Expression::ImageSample { + Ok(Expression::ImageSample { image: expressions.append(image), sampler: expressions.append(sampler), coordinate: expressions.append(coordinate), - } + }) } - _ => Expression::Call { + _ => Ok(Expression::Call { name, arguments: args .into_iter() .map(|arg| { - let expr = self.parse_expression( - arg, - expressions, - locals, - locals_map, - parameter_lookup, - ); + let expr = self + .parse_expression( + arg, + expressions, + locals, + locals_map, + parameter_lookup, + ) + .unwrap(); expressions.append(expr) }) .collect(), - }, + }), } } Expr::Dot(reg, ident) => { @@ -931,7 +888,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, - ); + )?; expressions.append(expr) }; @@ -948,7 +905,7 @@ impl<'a> Parser<'a> { &self.functions, &self.function_lookup, ) - .unwrap(); + .map_err(|e| Error { kind: e.into() })?; let base_type = &self.types[type_handle]; match base_type.inner { crate::TypeInner::Struct { ref members } => { @@ -956,10 +913,10 @@ impl<'a> Parser<'a> { .iter() .position(|m| m.name.as_deref() == Some(name)) .unwrap() as u32; - crate::Expression::AccessIndex { + Ok(crate::Expression::AccessIndex { base: handle, index, - } + }) } crate::TypeInner::Vector { size, kind, width } | crate::TypeInner::Matrix { @@ -999,23 +956,23 @@ impl<'a> Parser<'a> { } else { crate::TypeInner::Vector { size, kind, width } }; - crate::Expression::Compose { + Ok(crate::Expression::Compose { ty: crate::proc::Typifier::deduce_type_handle( inner, &mut self.types, ), components, - } + }) } else { let ch = name.chars().next().unwrap(); let index = MEMBERS[..size as usize] .iter() .position(|&m| m == ch) .unwrap() as u32; - crate::Expression::AccessIndex { + Ok(crate::Expression::AccessIndex { base: handle, index, - } + }) } } _ => panic!(), @@ -1170,18 +1127,14 @@ impl<'a> Parser<'a> { } } -pub fn parse_str( - source: &str, - entry: String, - stage: ShaderStage, -) -> Result { - let input = parser::parse(source).unwrap(); +pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { + let input = parser::parse(source)?; log::debug!("------GLSL PREPROCESSOR------"); log::debug!("\n{}", input); log::debug!("-----------------------------"); - Parser::new(&input, stage)?.parse(entry) + Parser::new(&input, stage).parse(entry) } #[cfg(test)] diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 314404674..c3de558d1 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -7,10 +7,13 @@ pub struct Typifier { types: Vec>, } -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] pub enum ResolveError { + #[error("Invalid index into array")] InvalidAccessIndex, - FunctionNotDefined, + #[error("Function {name} not defined")] + FunctionNotDefined { name: String }, + #[error("Function without return type")] FunctionReturnsVoid, } @@ -123,6 +126,8 @@ impl Typifier { ty_left } else if let crate::TypeInner::Scalar { .. } = types[ty_right].inner { ty_left + } else if let crate::TypeInner::Scalar { .. } = types[ty_left].inner { + ty_right } else if let crate::TypeInner::Matrix { columns, kind, @@ -166,7 +171,7 @@ impl Typifier { ref name, ref arguments, } => match name.as_str() { - "distance" | "length" => { + "distance" | "length" | "dot" => { let ty_handle = self.types[arguments[0].index()]; let inner = match types[ty_handle].inner { crate::TypeInner::Vector { kind, width, .. } => { @@ -176,10 +181,14 @@ impl Typifier { }; Self::deduce_type_handle(inner, types) } - "normalize" | "fclamp" => self.types[arguments[0].index()], - other => functions[*function_lookup - .get(other) - .ok_or(ResolveError::FunctionNotDefined)?] + "normalize" | "fclamp" | "max" | "reflect" | "pow" | "clamp" | "mix" => { + self.types[arguments[0].index()] + } + other => functions[*function_lookup.get(other).ok_or( + ResolveError::FunctionNotDefined { + name: other.to_string(), + }, + )?] .return_type .ok_or(ResolveError::FunctionReturnsVoid)?, }, From de3024f6b28e3371b3cf4cf784ed1a6c98d05c1b Mon Sep 17 00:00:00 2001 From: Gabriel Majeri Date: Wed, 1 Jul 2020 09:53:49 +0300 Subject: [PATCH 0096/2212] Add fuzzing support --- fuzz/.gitignore | 3 +++ fuzz/Cargo.toml | 32 ++++++++++++++++++++++++++++++++ fuzz/fuzz_targets/spv_parser.rs | 8 ++++++++ fuzz/fuzz_targets/wgsl_parser.rs | 8 ++++++++ 4 files changed, 51 insertions(+) create mode 100644 fuzz/.gitignore create mode 100644 fuzz/Cargo.toml create mode 100644 fuzz/fuzz_targets/spv_parser.rs create mode 100644 fuzz/fuzz_targets/wgsl_parser.rs diff --git a/fuzz/.gitignore b/fuzz/.gitignore new file mode 100644 index 000000000..a0925114d --- /dev/null +++ b/fuzz/.gitignore @@ -0,0 +1,3 @@ +target +corpus +artifacts diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml new file mode 100644 index 000000000..a2b18642e --- /dev/null +++ b/fuzz/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "naga-fuzz" +version = "0.0.0" +authors = ["Automatically generated"] +publish = false +edition = "2018" + +[package.metadata] +cargo-fuzz = true + +[dependencies] +libfuzzer-sys = "0.3" + +[dependencies.naga] +path = ".." +features = ["spirv"] + +# Prevent this from interfering with workspaces +[workspace] +members = ["."] + +[[bin]] +name = "spv_parser" +path = "fuzz_targets/spv_parser.rs" +test = false +doc = false + +[[bin]] +name = "wgsl_parser" +path = "fuzz_targets/wgsl_parser.rs" +test = false +doc = false diff --git a/fuzz/fuzz_targets/spv_parser.rs b/fuzz/fuzz_targets/spv_parser.rs new file mode 100644 index 000000000..dca86b8fa --- /dev/null +++ b/fuzz/fuzz_targets/spv_parser.rs @@ -0,0 +1,8 @@ +#![no_main] +use libfuzzer_sys::fuzz_target; +use naga::front::spv::Parser; + +fuzz_target!(|data: Vec| { + // Ensure the parser can handle potentially malformed data without crashing. + let _result = Parser::new(data.into_iter()).parse(); +}); diff --git a/fuzz/fuzz_targets/wgsl_parser.rs b/fuzz/fuzz_targets/wgsl_parser.rs new file mode 100644 index 000000000..3ff9b15bf --- /dev/null +++ b/fuzz/fuzz_targets/wgsl_parser.rs @@ -0,0 +1,8 @@ +#![no_main] +use libfuzzer_sys::fuzz_target; +use naga::front::wgsl::Parser; + +fuzz_target!(|data: String| { + // Ensure the parser can handle potentially malformed strings without crashing. + let _result = Parser::new().parse(&data); +}); From 1a9f34ecf2b9dd8da1b5c13529d86838851d66cf Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 1 Jul 2020 13:15:14 +0000 Subject: [PATCH 0097/2212] Handle glsl_new parser errors --- src/front/glsl_new/error.rs | 11 ++++++++++- src/front/glsl_new/mod.rs | 11 ++++++----- src/front/glsl_new/parser.rs | 26 +++++++++++++++----------- 3 files changed, 31 insertions(+), 17 deletions(-) diff --git a/src/front/glsl_new/error.rs b/src/front/glsl_new/error.rs index 991e6050a..c860960ba 100644 --- a/src/front/glsl_new/error.rs +++ b/src/front/glsl_new/error.rs @@ -1,16 +1,25 @@ +use super::parser::Token; use std::{fmt, io}; #[derive(Debug)] pub enum ErrorKind { InvalidInput, IoError(io::Error), + InvalidToken(Token), + EndOfFile, + ParserFail, + ParserStackOverflow, } impl fmt::Display for ErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ErrorKind::IoError(error) => write!(f, "IO Error {}", error), ErrorKind::InvalidInput => write!(f, "InvalidInput"), + ErrorKind::IoError(error) => write!(f, "IO Error {}", error), + ErrorKind::InvalidToken(token) => write!(f, "Invalid Token {:?}", token), + ErrorKind::EndOfFile => write!(f, "Unexpected end of file"), + ErrorKind::ParserFail => write!(f, "Parser failed"), + ErrorKind::ParserStackOverflow => write!(f, "Parser stack overflow"), } } } diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index 4b3c70daf..3f1d65fa4 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -1,9 +1,11 @@ -use crate::{Arena, Constant, EntryPoint, Function, GlobalVariable, Header, Module, ShaderStage, Type}; +use crate::{ + Arena, Constant, EntryPoint, Function, GlobalVariable, Header, Module, ShaderStage, Type, +}; mod lex; use lex::Lexer; mod error; -use error::{ErrorKind, ParseError}; +use error::ParseError; mod parser; mod token; @@ -26,10 +28,9 @@ pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result Err(ErrorKind::InvalidToken(token)), + None => Err(ErrorKind::EndOfFile), + } + } + %parse_fail { + ErrorKind::ParserFail + } + %stack_overflow { + ErrorKind::ParserStackOverflow + } + %type Identifier String; %type IntConstant i64; %type UintConstant u64; @@ -20,16 +34,6 @@ pomelo! { %type arg_list Vec; %type function_definition Function; - %left Else; - %right Assign; - %left Or; - %left And; - %nonassoc Equal NotEqual; - %nonassoc Less LessEq Greater GreaterEq; - %left Plus Minus; - %left Mult Div; - %nonassoc Not; - root ::= version_pragma translation_unit; version_pragma ::= Version IntConstant Identifier?; From 7d5bc0b2e2ebf28dd1a1620adf60a029507f6bf9 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 2 Jul 2020 04:17:16 +0000 Subject: [PATCH 0098/2212] Make glsl dep more specific - Require 4.1 as 4.0 now gives compile errors --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 66e3d3381..8b18a4a01 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ fxhash = "0.2" log = "0.4" num-traits = "0.2" spirv = { package = "spirv_headers", version = "1.4.2", optional = true } -glsl = { version = "4", optional = true } +glsl = { version = "4.1", optional = true } pomelo = { version = "0.1.4", optional = true } thiserror = "1.0" From aa70703fee4672078f70359d677646b700ef189d Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 2 Jul 2020 05:54:28 +0000 Subject: [PATCH 0099/2212] Add simple test for glsl-new lexer --- src/front/glsl_new/lex_tests.rs | 36 +++++++++++++++++++++++++++++++++ src/front/glsl_new/mod.rs | 3 +++ 2 files changed, 39 insertions(+) create mode 100644 src/front/glsl_new/lex_tests.rs diff --git a/src/front/glsl_new/lex_tests.rs b/src/front/glsl_new/lex_tests.rs new file mode 100644 index 000000000..fe17f260e --- /dev/null +++ b/src/front/glsl_new/lex_tests.rs @@ -0,0 +1,36 @@ +use super::lex::Lexer; +use super::parser::Token; + +#[test] +fn glsl_lex_simple() { + let source = "void main() {\n}"; + let lex = Lexer::new(source); + let tokens: Vec = lex.collect(); + assert_eq!(tokens.len(), 6); + + let mut iter = tokens.iter(); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Void(TokenMetadata { line: 0, chars: 0..4 })" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Identifier((TokenMetadata { line: 0, chars: 5..9 }, \"main\"))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "LeftParen(TokenMetadata { line: 0, chars: 9..10 })" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "RightParen(TokenMetadata { line: 0, chars: 10..11 })" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "LeftBrace(TokenMetadata { line: 0, chars: 12..13 })" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "RightBrace(TokenMetadata { line: 1, chars: 0..1 })" + ); +} diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index 3f1d65fa4..202a7e6fa 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -3,6 +3,9 @@ use crate::{ }; mod lex; +#[cfg(test)] +mod lex_tests; + use lex::Lexer; mod error; use error::ParseError; From dff31114855382638129a7d846140afd5e18b2a5 Mon Sep 17 00:00:00 2001 From: LaughingMan Date: Fri, 3 Jul 2020 06:05:02 +0200 Subject: [PATCH 0100/2212] WGSL front end: Fix panic on invalid input MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Until now the WGSL parser would interpret a character index as a byte index. This could lead to a panic on invalid input strings like "\"\u{2}ПЀ\u{0}\"", because it would use that index to slice a string without ensuring the slicing happens on a character boundary. One possible fix would have been to call `str::find` instead of `position`, however by relying on `splitn` instead of slicing a str manually it is easier to convince ourselves that this code can no longer panic. Fixes https://github.com/gfx-rs/naga/issues/90 --- src/front/wgsl.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index b5b1c5e2c..15632b10b 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -93,12 +93,15 @@ mod lex { (Token::Word(word), rest) } '"' => { - let base = chars.as_str(); - let len = match chars.position(|c| c == '"') { - Some(pos) => pos, - None => return (Token::UnterminatedString, chars.as_str()), - }; - (Token::String(&base[..len]), chars.as_str()) + let mut iter = chars.as_str().splitn(2, '"'); + + // splitn returns an iterator with at least one element, so unwrapping is fine + let quote_content = iter.next().unwrap(); + if let Some(rest) = iter.next() { + (Token::String(quote_content), rest) + } else { + (Token::UnterminatedString, quote_content) + } } '-' => { input = chars.as_str(); From 87595725302192658f1870065a0071c8a9631d6b Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Fri, 3 Jul 2020 06:07:00 +0000 Subject: [PATCH 0101/2212] Add glsl-new lexer line comment support - Includes test --- src/front/glsl_new/lex.rs | 3 +-- src/front/glsl_new/lex_tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 8097518a6..6583d5e3f 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -198,8 +198,7 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { meta.chars.end = start + 2; (Some(Token::DivAssign(meta)), chars.as_str()) } - //TODO: line comments - // Some('/') => (Token::LineComment, chars.as_str(), start, start + 2), + Some('/') => (None, ""), //TODO: multi-line comments // Some('*') => ( // Token::MultiLineCommentOpen, diff --git a/src/front/glsl_new/lex_tests.rs b/src/front/glsl_new/lex_tests.rs index fe17f260e..02c426ffa 100644 --- a/src/front/glsl_new/lex_tests.rs +++ b/src/front/glsl_new/lex_tests.rs @@ -34,3 +34,29 @@ fn glsl_lex_simple() { "RightBrace(TokenMetadata { line: 1, chars: 0..1 })" ); } + +#[test] +fn glsl_lex_line_comment() { + let source = "void main // myfunction\n//()\n{}"; + let lex = Lexer::new(source); + let tokens: Vec = lex.collect(); + assert_eq!(tokens.len(), 4); + + let mut iter = tokens.iter(); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Void(TokenMetadata { line: 0, chars: 0..4 })" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Identifier((TokenMetadata { line: 0, chars: 5..9 }, \"main\"))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "LeftBrace(TokenMetadata { line: 2, chars: 0..1 })" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "RightBrace(TokenMetadata { line: 2, chars: 1..2 })" + ); +} From 2ffbeba8c69f44eff646be27c070f19ca843a83f Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Sat, 4 Jul 2020 06:59:45 +0000 Subject: [PATCH 0102/2212] Fix illegal chars in identifier for glsl-new --- src/front/glsl_new/lex.rs | 4 +-- src/front/glsl_new/lex_tests.rs | 50 +++++++++++++++++++++++++++++++++ src/front/glsl_new/parser.rs | 1 + 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 6583d5e3f..0b6d67502 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -107,7 +107,7 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { } } 'a'..='z' | 'A'..='Z' | '_' => { - let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); + let (word, rest, pos) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); meta.chars.end = start + pos; match word { "void" => (Some(Token::Void(meta)), rest), @@ -227,7 +227,7 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { } '~' => (Some(Token::Tilde(meta)), chars.as_str()), '?' => (Some(Token::Question(meta)), chars.as_str()), - _ => (None, chars.as_str()), + ch => (Some(Token::Unknown((meta, ch))), chars.as_str()), } } diff --git a/src/front/glsl_new/lex_tests.rs b/src/front/glsl_new/lex_tests.rs index 02c426ffa..377f17f5f 100644 --- a/src/front/glsl_new/lex_tests.rs +++ b/src/front/glsl_new/lex_tests.rs @@ -60,3 +60,53 @@ fn glsl_lex_line_comment() { "RightBrace(TokenMetadata { line: 2, chars: 1..2 })" ); } + +#[test] +fn glsl_lex_identifier() { + let source = "id123_OK 92No æNoø No¾ No好"; + let lex = Lexer::new(source); + let tokens: Vec = lex.collect(); + assert_eq!(tokens.len(), 10); + + let mut iter = tokens.iter(); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Identifier((TokenMetadata { line: 0, chars: 0..8 }, \"id123_OK\"))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "IntConstant((TokenMetadata { line: 0, chars: 9..11 }, 92))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Identifier((TokenMetadata { line: 0, chars: 11..13 }, \"No\"))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Unknown((TokenMetadata { line: 0, chars: 14..15 }, \'æ\'))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Identifier((TokenMetadata { line: 0, chars: 15..17 }, \"No\"))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Unknown((TokenMetadata { line: 0, chars: 17..18 }, \'ø\'))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Identifier((TokenMetadata { line: 0, chars: 19..21 }, \"No\"))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Unknown((TokenMetadata { line: 0, chars: 21..22 }, \'¾\'))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Identifier((TokenMetadata { line: 0, chars: 23..25 }, \"No\"))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Unknown((TokenMetadata { line: 0, chars: 25..26 }, \'好\'))" + ); +} diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 3e80bcd7d..10ac3af5c 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -24,6 +24,7 @@ pomelo! { ErrorKind::ParserStackOverflow } + %type Unknown char; %type Identifier String; %type IntConstant i64; %type UintConstant u64; From 5d6406b0184c62cbae605ccbb5b8536cbc7e661b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 3 Jul 2020 18:27:16 -0400 Subject: [PATCH 0103/2212] Add DepthImage IR type. Fix all the usage of Bytes type to really mean bytes. Have logic in the SPIR-V front-end to detect the comparison properties of samplers and images. --- src/arena.rs | 5 + src/back/msl.rs | 57 +++++++-- src/back/spv/writer.rs | 47 ++++--- src/front/glsl/helpers.rs | 70 +++++------ src/front/glsl/mod.rs | 25 ++-- src/front/spv.rs | 253 +++++++++++++++++++++++++++++++++----- src/front/wgsl.rs | 16 +-- src/lib.rs | 31 ++--- src/proc/interface.rs | 4 + src/proc/validator.rs | 4 +- 10 files changed, 380 insertions(+), 132 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 0a5706ac3..66cf171ef 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -139,6 +139,11 @@ impl Arena { self.append(value) } } + + /// Get a mutable reference to an element in the arena. + pub fn mutate(&mut self, handle: Handle) -> &mut T { + self.data.get_mut(handle.index.get() as usize - 1).unwrap() + } } impl std::ops::Index> for Arena { diff --git a/src/back/msl.rs b/src/back/msl.rs index acd2a1323..f3d909b0c 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -100,6 +100,15 @@ enum LocationMode { Uniform, } +fn dim_str(dim: crate::ImageDimension) -> &'static str { + match dim { + crate::ImageDimension::D1 => "1d", + crate::ImageDimension::D2 => "2d", + crate::ImageDimension::D3 => "3d", + crate::ImageDimension::Cube => "Cube", + } +} + #[derive(Debug, Clone, Copy)] pub struct Options<'a> { pub binding_map: &'a BindingMap, @@ -605,6 +614,7 @@ impl Writer { image, sampler, coordinate, + depth_ref: None, } => { let ty_image = self.put_expression(image, function, module)?; write!(self.out, ".sample(")?; @@ -617,6 +627,25 @@ impl Writer { ref other => Err(Error::UnexpectedImageType(other.clone())), } } + crate::Expression::ImageSample { + image, + sampler, + coordinate, + depth_ref: Some(dref), + } => { + self.put_expression(image, function, module)?; + write!(self.out, ".sample_compare(")?; + self.put_expression(sampler, function, module)?; + write!(self.out, ", ")?; + self.put_expression(coordinate, function, module)?; + write!(self.out, ", ")?; + self.put_expression(dref, function, module)?; + write!(self.out, ")")?; + Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: 4, + })) + } crate::Expression::Call { ref name, ref arguments, @@ -887,11 +916,16 @@ impl Writer { } crate::TypeInner::Image { base, dim, flags } => { let base_name = module.types[base].name.or_index(base); - let dim = match dim { - crate::ImageDimension::D1 => "1d", - crate::ImageDimension::D2 => "2d", - crate::ImageDimension::D3 => "3d", - crate::ImageDimension::Cube => "Cube", + let dim_str = dim_str(dim); + let msaa_str = if flags.contains(crate::ImageFlags::MULTISAMPLED) { + "_ms" + } else { + "" + }; + let array_str = if flags.contains(crate::ImageFlags::ARRAYED) { + "_array" + } else { + "" }; let access = if flags.contains(crate::ImageFlags::SAMPLED) { if flags.intersects(crate::ImageFlags::CAN_STORE) { @@ -911,8 +945,17 @@ impl Writer { }; write!( self.out, - "typedef texture{}<{}, access::{}> {}", - dim, base_name, access, name + "typedef texture{}{}{}<{}, access::{}> {}", + dim_str, msaa_str, array_str, base_name, access, name + )?; + } + crate::TypeInner::DepthImage { dim, arrayed } => { + let dim_str = dim_str(dim); + let array_str = if arrayed { "_array" } else { "" }; + write!( + self.out, + "typedef depth{}{} {}", + dim_str, array_str, name )?; } crate::TypeInner::Sampler { comparison: _ } => { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e8e76e1e2..a456d3cd5 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -40,6 +40,15 @@ impl LookupHelper for FastHashMap> { } } +fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { + match dim { + crate::ImageDimension::D1 => spirv::Dim::Dim1D, + crate::ImageDimension::D2 => spirv::Dim::Dim2D, + crate::ImageDimension::D3 => spirv::Dim::Dim2D, + crate::ImageDimension::Cube => spirv::Dim::DimCube, + } +} + #[derive(Debug, PartialEq)] struct LookupFunctionType { parameter_type_ids: Vec, @@ -413,14 +422,14 @@ impl Writer { sampled_type_id: Word, dim: spirv::Dim, flags: ImageFlags, + comparison: bool, ) -> Instruction { let mut instruction = Instruction::new(Op::TypeImage); instruction.set_result(id); instruction.add_operand(sampled_type_id); instruction.add_operand(dim as u32); - // TODO Add Depth, but how to determine? Not yet in the WGSL spec - instruction.add_operand(1); + instruction.add_operand(if comparison { 1 } else { 0 }); instruction.add_operand(if flags.contains(crate::ImageFlags::ARRAYED) { 1 @@ -765,17 +774,25 @@ impl Writer { } crate::TypeInner::Image { base, dim, flags } => { let type_id = self.get_type_id(arena, base); - let dim = match dim { - crate::ImageDimension::D1 => spirv::Dim::Dim1D, - crate::ImageDimension::D2 => spirv::Dim::Dim2D, - crate::ImageDimension::D3 => spirv::Dim::Dim2D, - crate::ImageDimension::Cube => spirv::Dim::DimCube, - }; + let dim = map_dim(dim); self.try_add_capabilities(dim.required_capabilities()); - instruction = self.instruction_type_image(id, type_id, dim, flags); + instruction = self.instruction_type_image(id, type_id, dim, flags, false); self.lookup_type.insert(id, base); } + crate::TypeInner::DepthImage { dim, arrayed } => { + let type_id = 0; //TODO! + let dim = map_dim(dim); + self.try_add_capabilities(dim.required_capabilities()); + + let flags = if arrayed { + crate::ImageFlags::ARRAYED + } else { + crate::ImageFlags::empty() + }; + instruction = self.instruction_type_image(id, type_id, dim, flags, true); + //self.lookup_type.insert(id, base); + } crate::TypeInner::Sampler { comparison: _ } => { instruction = self.instruction_type_sampler(id); self.lookup_type.insert(id, handle); @@ -845,8 +862,8 @@ impl Writer { let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { - 32 => self.instruction_constant(type_id, id, &[val as u32]), - 64 => { + 4 => self.instruction_constant(type_id, id, &[val as u32]), + 8 => { let (low, high) = ((val >> 32) as u32, val as u32); self.instruction_constant(type_id, id, &[low, high]) } @@ -862,8 +879,8 @@ impl Writer { let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { - 32 => self.instruction_constant(type_id, id, &[val as u32]), - 64 => { + 4 => self.instruction_constant(type_id, id, &[val as u32]), + 8 => { let (low, high) = ((val >> 32) as u32, val as u32); self.instruction_constant(type_id, id, &[low, high]) } @@ -880,8 +897,8 @@ impl Writer { let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { - 32 => self.instruction_constant(type_id, id, &[(val as f32).to_bits()]), - 64 => { + 4 => self.instruction_constant(type_id, id, &[(val as f32).to_bits()]), + 8 => { let bits = f64::to_bits(val); let (low, high) = ((bits >> 32) as u32, bits as u32); self.instruction_constant(type_id, id, &[low, high]) diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs index ea1b1e5b5..1a43ed973 100644 --- a/src/front/glsl/helpers.rs +++ b/src/front/glsl/helpers.rs @@ -47,49 +47,49 @@ pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> }, Int => TypeInner::Scalar { kind: ScalarKind::Sint, - width: 32, + width: 4, }, UInt => TypeInner::Scalar { kind: ScalarKind::Uint, - width: 32, + width: 4, }, Float => TypeInner::Scalar { kind: ScalarKind::Float, - width: 32, + width: 4, }, Double => TypeInner::Scalar { kind: ScalarKind::Float, - width: 64, + width: 8, }, Vec2 => TypeInner::Vector { size: VectorSize::Bi, kind: ScalarKind::Float, - width: 32, + width: 4, }, Vec3 => TypeInner::Vector { size: VectorSize::Tri, kind: ScalarKind::Float, - width: 32, + width: 4, }, Vec4 => TypeInner::Vector { size: VectorSize::Quad, kind: ScalarKind::Float, - width: 32, + width: 4, }, DVec2 => TypeInner::Vector { size: VectorSize::Bi, kind: ScalarKind::Float, - width: 64, + width: 8, }, DVec3 => TypeInner::Vector { size: VectorSize::Tri, kind: ScalarKind::Float, - width: 64, + width: 8, }, DVec4 => TypeInner::Vector { size: VectorSize::Quad, kind: ScalarKind::Float, - width: 64, + width: 8, }, BVec2 => TypeInner::Vector { size: VectorSize::Bi, @@ -109,142 +109,142 @@ pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> IVec2 => TypeInner::Vector { size: VectorSize::Bi, kind: ScalarKind::Sint, - width: 32, + width: 4, }, IVec3 => TypeInner::Vector { size: VectorSize::Tri, kind: ScalarKind::Sint, - width: 32, + width: 4, }, IVec4 => TypeInner::Vector { size: VectorSize::Quad, kind: ScalarKind::Sint, - width: 32, + width: 4, }, UVec2 => TypeInner::Vector { size: VectorSize::Bi, kind: ScalarKind::Uint, - width: 32, + width: 4, }, UVec3 => TypeInner::Vector { size: VectorSize::Tri, kind: ScalarKind::Uint, - width: 32, + width: 4, }, UVec4 => TypeInner::Vector { size: VectorSize::Quad, kind: ScalarKind::Uint, - width: 32, + width: 4, }, // Float Matrices Mat2 => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Bi, kind: ScalarKind::Float, - width: 32, + width: 4, }, Mat3 => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Tri, kind: ScalarKind::Float, - width: 32, + width: 4, }, Mat4 => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Quad, kind: ScalarKind::Float, - width: 32, + width: 4, }, Mat23 => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Tri, kind: ScalarKind::Float, - width: 32, + width: 4, }, Mat24 => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Quad, kind: ScalarKind::Float, - width: 32, + width: 4, }, Mat32 => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Bi, kind: ScalarKind::Float, - width: 32, + width: 4, }, Mat34 => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Quad, kind: ScalarKind::Float, - width: 32, + width: 4, }, Mat42 => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Bi, kind: ScalarKind::Float, - width: 32, + width: 4, }, Mat43 => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Tri, kind: ScalarKind::Float, - width: 32, + width: 4, }, // Double Matrices DMat2 => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Bi, kind: ScalarKind::Float, - width: 64, + width: 8, }, DMat3 => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Tri, kind: ScalarKind::Float, - width: 64, + width: 8, }, DMat4 => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Quad, kind: ScalarKind::Float, - width: 64, + width: 8, }, DMat23 => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Tri, kind: ScalarKind::Float, - width: 64, + width: 8, }, DMat24 => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Quad, kind: ScalarKind::Float, - width: 64, + width: 8, }, DMat32 => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Bi, kind: ScalarKind::Float, - width: 64, + width: 8, }, DMat34 => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Quad, kind: ScalarKind::Float, - width: 64, + width: 8, }, DMat42 => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Bi, kind: ScalarKind::Float, - width: 64, + width: 8, }, DMat43 => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Tri, kind: ScalarKind::Float, - width: 64, + width: 8, }, TypeName(ty_name) => { if let Some(t_pos) = ty_name.0.find("texture") { @@ -258,7 +258,7 @@ pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> name: None, inner: TypeInner::Scalar { kind: scalar_kind, - width: 32, + width: 4, }, }); diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index c5fa04950..0b2d661b5 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -558,7 +558,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Sint, - width: 32, + width: 4, }, }), }), @@ -572,7 +572,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Sint, - width: 32, + width: 4, }, }), }), @@ -586,7 +586,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Sint, - width: 32, + width: 4, }, }), }), @@ -600,7 +600,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Sint, - width: 32, + width: 4, }, }), }), @@ -619,7 +619,7 @@ impl<'a> Parser<'a> { inner: TypeInner::Vector { size: VectorSize::Quad, kind: ScalarKind::Float, - width: 32, + width: 4, }, }), }, @@ -633,7 +633,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Float, - width: 32, + width: 4, }, }), }, @@ -647,7 +647,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Float, - width: 32, + width: 4, }, }), }), @@ -684,7 +684,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Sint, - width: 32, + width: 4, }, }), }, @@ -698,7 +698,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Uint, - width: 32, + width: 4, }, }), }, @@ -726,7 +726,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Float, - width: 32, + width: 4, }, }), }, @@ -740,7 +740,7 @@ impl<'a> Parser<'a> { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Float, - width: 64, + width: 8, }, }), }, @@ -796,7 +796,7 @@ impl<'a> Parser<'a> { _ => panic!(), }, kind: ScalarKind::Float, - width: 32, + width: 4, }, }), components: args @@ -858,6 +858,7 @@ impl<'a> Parser<'a> { image: expressions.append(image), sampler: expressions.append(sampler), coordinate: expressions.append(coordinate), + depth_ref: None, //TODO }) } _ => Ok(Expression::Call { diff --git a/src/front/spv.rs b/src/front/spv.rs index 2d7e738c9..ae435eb69 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -52,6 +52,13 @@ pub enum Error { InvalidLoadType(spirv::Word), InvalidStoreType(spirv::Word), InvalidBinding(spirv::Word), + InvalidImageExpression(Handle), + InvalidSamplerExpression(Handle), + InvalidSampleImage(Handle), + InvalidSampleSampler(Handle), + InvalidSampleCoordinates(Handle), + InvalidDepthReference(Handle), + InconsistentComparisonSampling(Handle), WrongFunctionResultType(spirv::Word), WrongFunctionParameterType(spirv::Word), MissingDecoration(spirv::Decoration), @@ -145,6 +152,49 @@ fn map_image_dim(word: spirv::Word) -> Result { } } +fn map_width(word: spirv::Word) -> Result { + (word >> 3) // bits to bytes + .try_into() + .map_err(|_| Error::InvalidTypeWidth(word)) +} + +//TODO: this method may need to be gone, depending on whether +// WGSL allows treating images and samplers as expressions and pass them around. +fn reach_global_type( + expr_handle: Handle, + expressions: &Arena, + globals: &Arena, +) -> Option> { + match expressions[expr_handle] { + crate::Expression::GlobalVariable(var) => Some(globals[var].ty), + _ => None, + } +} + +fn check_sample_coordinates( + ty: &crate::Type, + expect_kind: crate::ScalarKind, + dim: crate::ImageDimension, + is_array: bool, +) -> bool { + let base_count = match dim { + crate::ImageDimension::D1 => 1, + crate::ImageDimension::D2 => 2, + crate::ImageDimension::D3 | crate::ImageDimension::Cube => 3, + }; + let extra_count = if is_array { 1 } else { 0 }; + let count = base_count + extra_count; + match ty.inner { + crate::TypeInner::Scalar { kind, width: _ } => count == 1 && kind == expect_kind, + crate::TypeInner::Vector { + size, + kind, + width: _, + } => size as u8 == count && kind == expect_kind, + _ => false, + } +} + type MemberIndex = u32; #[derive(Debug, Default)] @@ -194,6 +244,16 @@ impl Decoration { } } +bitflags::bitflags! { + /// Flags describing sampling method. + pub struct SamplingFlags: u32 { + /// Regular sampling. + const REGULAR = 0x1; + /// Comparison sampling. + const COMPARISON = 0x2; + } +} + #[derive(Debug)] struct LookupFunctionType { parameter_type_ids: Vec, @@ -245,8 +305,10 @@ pub struct Parser { future_decor: FastHashMap, future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>, lookup_member_type_id: FastHashMap<(spirv::Word, MemberIndex), spirv::Word>, + handle_sampling: FastHashMap, SamplingFlags>, lookup_type: FastHashMap, lookup_void_type: FastHashSet, + // Lookup for samplers and sampled images, storing flags on how they are used. lookup_constant: FastHashMap, lookup_variable: FastHashMap, lookup_expression: FastHashMap, @@ -263,6 +325,7 @@ impl> Parser { temp_bytes: Vec::new(), future_decor: FastHashMap::default(), future_member_decor: FastHashMap::default(), + handle_sampling: FastHashMap::default(), lookup_member_type_id: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_void_type: FastHashSet::default(), @@ -385,6 +448,7 @@ impl> Parser { fun: &mut crate::Function, type_arena: &Arena, const_arena: &Arena, + global_arena: &Arena, ) -> Result<(), Error> { loop { use spirv::Op; @@ -726,23 +790,113 @@ impl> Parser { let coordinate_id = self.next()?; let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - let coord_type_lookup = self.lookup_type.lookup(coord_lexp.type_id)?; - match type_arena[coord_type_lookup.handle].inner { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - .. + let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + + let sampler_type_handle = + reach_global_type(si_lexp.sampler, &fun.expressions, global_arena) + .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; + let image_type_handle = + reach_global_type(si_lexp.image, &fun.expressions, global_arena) + .ok_or(Error::InvalidImageExpression(si_lexp.image))?; + *self.handle_sampling.get_mut(&sampler_type_handle).unwrap() |= + SamplingFlags::REGULAR; + *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= + SamplingFlags::REGULAR; + match type_arena[sampler_type_handle].inner { + crate::TypeInner::Sampler { comparison: false } => (), + _ => return Err(Error::InvalidSampleSampler(sampler_type_handle)), + }; + match type_arena[image_type_handle].inner { + //TODO: compare the result type + crate::TypeInner::Image { + base: _, + dim, + flags, + } if flags + & (crate::ImageFlags::MULTISAMPLED | crate::ImageFlags::SAMPLED) + == crate::ImageFlags::SAMPLED => + { + if !check_sample_coordinates( + &type_arena[coord_type_handle], + crate::ScalarKind::Float, + dim, + flags.contains(crate::ImageFlags::ARRAYED), + ) { + return Err(Error::InvalidSampleCoordinates(coord_type_handle)); + } } - | crate::TypeInner::Vector { - kind: crate::ScalarKind::Float, - .. - } => (), - _ => return Err(Error::UnsupportedType(coord_type_lookup.handle)), - } - //TODO: compare the result type + _ => return Err(Error::InvalidSampleImage(image_type_handle)), + }; + let expr = crate::Expression::ImageSample { image: si_lexp.image, sampler: si_lexp.sampler, coordinate: coord_lexp.handle, + depth_ref: None, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: fun.expressions.append(expr), + type_id: result_type_id, + }, + ); + } + Op::ImageSampleDrefImplicitLod => { + inst.expect_at_least(6)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let sampled_image_id = self.next()?; + let coordinate_id = self.next()?; + let dref_id = self.next()?; + + let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + let sampler_type_handle = + reach_global_type(si_lexp.sampler, &fun.expressions, global_arena) + .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; + let image_type_handle = + reach_global_type(si_lexp.image, &fun.expressions, global_arena) + .ok_or(Error::InvalidImageExpression(si_lexp.image))?; + *self.handle_sampling.get_mut(&sampler_type_handle).unwrap() |= + SamplingFlags::COMPARISON; + *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= + SamplingFlags::COMPARISON; + match type_arena[sampler_type_handle].inner { + crate::TypeInner::Sampler { comparison: true } => (), + _ => return Err(Error::InvalidSampleSampler(sampler_type_handle)), + }; + match type_arena[image_type_handle].inner { + //TODO: compare the result type + crate::TypeInner::DepthImage { dim, arrayed } => { + if !check_sample_coordinates( + &type_arena[coord_type_handle], + crate::ScalarKind::Float, + dim, + arrayed, + ) { + return Err(Error::InvalidSampleCoordinates(coord_type_handle)); + } + } + _ => return Err(Error::InvalidSampleImage(image_type_handle)), + }; + + let dref_lexp = self.lookup_expression.lookup(dref_id)?; + let dref_type_handle = self.lookup_type.lookup(dref_lexp.type_id)?.handle; + match type_arena[dref_type_handle].inner { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: _, + } => (), + _ => return Err(Error::InvalidDepthReference(dref_type_handle)), + } + + let expr = crate::Expression::ImageSample { + image: si_lexp.image, + sampler: si_lexp.sampler, + coordinate: coord_lexp.handle, + depth_ref: Some(dref_lexp.handle), }; self.lookup_expression.insert( result_id, @@ -847,6 +1001,34 @@ impl> Parser { }?; } + // Check all the images and samplers to have consistent comparison property. + for (handle, flags) in self.handle_sampling.drain() { + if !flags.contains(SamplingFlags::COMPARISON) { + continue; + } + if flags == SamplingFlags::all() { + return Err(Error::InconsistentComparisonSampling(handle)); + } + let ty = module.types.mutate(handle); + match ty.inner { + crate::TypeInner::Sampler { ref mut comparison } => { + assert!(!*comparison); + *comparison = true; + } + crate::TypeInner::Image { + base: _, + dim, + flags, + } => { + ty.inner = crate::TypeInner::DepthImage { + dim, + arrayed: flags.contains(crate::ImageFlags::ARRAYED), + }; + } + _ => panic!("Unexpected comparison type {:?}", ty), + } + } + if !self.future_decor.is_empty() { log::warn!("Unused item decorations: {:?}", self.future_decor); self.future_decor.clear(); @@ -1044,9 +1226,7 @@ impl> Parser { 1 => crate::ScalarKind::Sint, _ => return Err(Error::InvalidSign(sign)), }, - width: width - .try_into() - .map_err(|_| Error::InvalidTypeWidth(width))?, + width: map_width(width)?, }; self.lookup_type.insert( id, @@ -1072,9 +1252,7 @@ impl> Parser { let width = self.next()?; let inner = crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, - width: width - .try_into() - .map_err(|_| Error::InvalidTypeWidth(width))?, + width: map_width(width)?, }; self.lookup_type.insert( id, @@ -1346,13 +1524,15 @@ impl> Parser { dim: map_image_dim(dim)?, flags, }; + let handle = module.types.append(crate::Type { + name: decor.name, + inner, + }); + self.handle_sampling.insert(handle, SamplingFlags::empty()); self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: decor.name, - inner, - }), + handle, base_id: Some(sample_type_id), }, ); @@ -1383,14 +1563,18 @@ impl> Parser { inst.expect(2)?; let id = self.next()?; let decor = self.future_decor.remove(&id).unwrap_or_default(); - let inner = crate::TypeInner::Sampler { comparison: false }; //TODO! + // The comparison bit is temporary, will be overwritten based on the + // accumulated sampling flags at the end. + let inner = crate::TypeInner::Sampler { comparison: false }; + let handle = module.types.append(crate::Type { + name: decor.name, + inner, + }); + self.handle_sampling.insert(handle, SamplingFlags::empty()); self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: decor.name, - inner, - }), + handle, base_id: None, }, ); @@ -1414,7 +1598,7 @@ impl> Parser { width, } => { let low = self.next()?; - let high = if width > 32 { + let high = if width > 4 { inst.expect(4)?; self.next()? } else { @@ -1428,7 +1612,7 @@ impl> Parser { } => { use std::cmp::Ordering; let low = self.next()?; - let high = match width.cmp(&32) { + let high = match width.cmp(&4) { Ordering::Less => return Err(Error::InvalidTypeWidth(u32::from(width))), Ordering::Greater => { inst.expect(4)?; @@ -1444,8 +1628,8 @@ impl> Parser { } => { let low = self.next()?; let extended = match width { - 32 => f64::from(f32::from_bits(low)), - 64 => { + 4 => f64::from(f32::from_bits(low)), + 8 => { inst.expect(4)?; let high = self.next()?; f64::from_bits((u64::from(high) << 32) | u64::from(low)) @@ -1635,7 +1819,12 @@ impl> Parser { spirv::Op::Label => { fun_inst.expect(2)?; let _id = self.next()?; - self.next_block(&mut fun, &module.types, &module.constants)?; + self.next_block( + &mut fun, + &module.types, + &module.constants, + &module.global_variables, + )?; } spirv::Op::FunctionEnd => { fun_inst.expect(1)?; diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 15632b10b..c12a10b2e 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -232,12 +232,12 @@ impl<'a> Lexer<'a> { } } - fn next_scalar_generic(&mut self) -> Result<(crate::ScalarKind, u8), Error<'a>> { + fn next_scalar_generic(&mut self) -> Result<(crate::ScalarKind, crate::Bytes), Error<'a>> { self.expect(Token::Paren('<'))?; let pair = match self.next() { - Token::Word("f32") => (crate::ScalarKind::Float, 32), - Token::Word("i32") => (crate::ScalarKind::Sint, 32), - Token::Word("u32") => (crate::ScalarKind::Uint, 32), + Token::Word("f32") => (crate::ScalarKind::Float, 4), + Token::Word("i32") => (crate::ScalarKind::Sint, 4), + Token::Word("u32") => (crate::ScalarKind::Uint, 4), other => return Err(Error::Unexpected(other)), }; self.expect(Token::Paren('>'))?; @@ -524,7 +524,7 @@ impl Parser { specialization: None, inner, ty: Typifier::deduce_type_handle( - crate::TypeInner::Scalar { kind, width: 32 }, + crate::TypeInner::Scalar { kind, width: 4 }, ctx.types, ), }); @@ -991,15 +991,15 @@ impl Parser { let inner = match lexer.next() { Token::Word("f32") => crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, - width: 32, + width: 4, }, Token::Word("i32") => crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, - width: 32, + width: 4, }, Token::Word("u32") => crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, - width: 32, + width: 4, }, Token::Word("vec2") => { let (kind, width) = lexer.next_scalar_generic()?; diff --git a/src/lib.rs b/src/lib.rs index 49e4703e4..7463e1bc4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -175,10 +175,7 @@ pub struct Type { #[derive(Clone, Debug, PartialEq)] pub enum TypeInner { /// Number of integral or floating-point kind. - Scalar { - kind: ScalarKind, - width: Bytes, - }, + Scalar { kind: ScalarKind, width: Bytes }, /// Vector of numbers. Vector { size: VectorSize, @@ -204,19 +201,17 @@ pub enum TypeInner { stride: Option, }, /// User-defined structure. - Struct { - members: Vec, - }, - /// Possibly multidimensional array of pixels. + Struct { members: Vec }, + /// Possibly multidimensional array of texels. Image { base: Handle, dim: ImageDimension, flags: ImageFlags, }, + /// Depth-comparison image. + DepthImage { dim: ImageDimension, arrayed: bool }, /// Can be used to sample values from images. - Sampler { - comparison: bool, - }, + Sampler { comparison: bool }, } /// Constant value. @@ -361,14 +356,13 @@ pub enum Expression { /// Reference a local variable. LocalVariable(Handle), /// Load a value indirectly. - Load { - pointer: Handle, - }, + Load { pointer: Handle }, /// Sample a point from an image. ImageSample { image: Handle, sampler: Handle, coordinate: Handle, + depth_ref: Option>, }, /// Apply an unary operator. Unary { @@ -432,19 +426,14 @@ pub enum Statement { default: Block, }, /// Executes a block repeatedly. - Loop { - body: Block, - continuing: Block, - }, + Loop { body: Block, continuing: Block }, //TODO: move terminator variations into a separate enum? /// Exits the loop. Break, /// Skips execution to the next iteration of the loop. Continue, /// Returns from the function (possibly with a value). - Return { - value: Option>, - }, + Return { value: Option> }, /// Aborts the current shader execution. Kill, /// Stores a value at an address. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index e44106409..7459248ea 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -34,10 +34,14 @@ impl<'a> Interface<'a> { image, sampler, coordinate, + depth_ref, } => { self.add_inputs(image); self.add_inputs(sampler); self.add_inputs(coordinate); + if let Some(dref) = depth_ref { + self.add_inputs(dref); + } } E::Unary { expr, .. } => { self.add_inputs(expr); diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 7976386fe..576baea68 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -26,7 +26,7 @@ impl Validator { Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } | Ti::Matrix { kind, width, .. } => { - if width != 32 { + if width != 4 { return Err(ValidationError::InvalidTypeWidth(kind, width)); } } @@ -48,7 +48,7 @@ impl Validator { } } } - Ti::Image { .. } => {} + Ti::Image { .. } | Ti::DepthImage { .. } => {} Ti::Sampler { comparison: _ } => {} } } From 33fe3a3dbad09288126100d805b44e1657099a11 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 3 Jul 2020 23:29:05 -0400 Subject: [PATCH 0104/2212] Struct member origin enum --- src/arena.rs | 2 +- src/back/msl.rs | 41 +++++++++-------- src/front/glsl/mod.rs | 8 +--- src/front/spv.rs | 101 ++++++++++++++++++++++++++++-------------- src/front/wgsl.rs | 3 +- src/lib.rs | 12 ++++- src/proc/validator.rs | 6 ++- 7 files changed, 109 insertions(+), 64 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 66cf171ef..9751beff5 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -141,7 +141,7 @@ impl Arena { } /// Get a mutable reference to an element in the arena. - pub fn mutate(&mut self, handle: Handle) -> &mut T { + pub fn get_mut(&mut self, handle: Handle) -> &mut T { self.data.get_mut(handle.index.get() as usize - 1).unwrap() } } diff --git a/src/back/msl.rs b/src/back/msl.rs index f3d909b0c..34ca94ce9 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -833,7 +833,7 @@ impl Writer { writeln!(self.out, "using namespace metal;")?; writeln!(self.out)?; - self.write_type_defs(module, options)?; + self.write_type_defs(module)?; writeln!(self.out)?; self.write_functions(module, options)?; @@ -841,7 +841,7 @@ impl Writer { Ok(()) } - fn write_type_defs(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { + fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { for (handle, ty) in module.types.iter() { let name = ty.name.or_index(handle); match ty.inner { @@ -905,10 +905,14 @@ impl Writer { let name = member.name.or_index(MemberIndex(index)); let base_name = module.types[member.ty].name.or_index(member.ty); write!(self.out, "\t{} {}", base_name, name)?; - if let Some(ref binding) = member.binding { - let resolved = - options.resolve_binding(binding, LocationMode::Intermediate)?; - resolved.try_fmt_decorated(&mut self.out, "")?; + match member.origin { + crate::MemberOrigin::BuiltIn(built_in) => { + ResolvedBinding::BuiltIn(built_in) + .try_fmt_decorated(&mut self.out, "")?; + } + crate::MemberOrigin::Offset(_) => { + //TODO + } } writeln!(self.out, ";")?; } @@ -1043,14 +1047,12 @@ impl Writer { module.types[ty_handle].inner { for (index, member) in members.iter().enumerate() { - if let Some(ref binding @ crate::Binding::Location(_)) = - member.binding - { + if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { let name = member.name.or_index(MemberIndex(index)); let ty_name = module.types[member.ty].name.or_index(member.ty); - let resolved = options.resolve_binding(binding, in_mode)?; write!(self.out, "\t{} {}", ty_name, name)?; - resolved.try_fmt_decorated(&mut self.out, ";\n")?; + ResolvedBinding::BuiltIn(built_in) + .try_fmt_decorated(&mut self.out, ";\n")?; } } } else if let Some(ref binding @ crate::Binding::Location(_)) = var.binding @@ -1092,13 +1094,16 @@ impl Writer { for (index, member) in members.iter().enumerate() { let name = member.name.or_index(MemberIndex(index)); let ty_name = module.types[member.ty].name.or_index(member.ty); - let binding = member - .binding - .as_ref() - .ok_or(Error::MissingBinding(handle))?; - let resolved = options.resolve_binding(binding, out_mode)?; - write!(self.out, "\t{} {}", ty_name, name)?; - resolved.try_fmt_decorated(&mut self.out, ";\n")?; + match member.origin { + crate::MemberOrigin::BuiltIn(built_in) => { + write!(self.out, "\t{} {}", ty_name, name)?; + ResolvedBinding::BuiltIn(built_in) + .try_fmt_decorated(&mut self.out, ";\n")?; + } + crate::MemberOrigin::Offset(_) => { + //TODO + } + } } } else { let tyvar = TypedGlobalVariable { diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 0b2d661b5..40d372911 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -142,18 +142,15 @@ impl<'a> Parser<'a> { let mut index = 0; for field in block.fields { - let binding = field - .qualifier - .and_then(|qualifier| Self::parse_type_qualifier(qualifier).1); - let ty = self.parse_type(field.ty).unwrap(); for ident in field.identifiers { let field_name = ident.ident.0; + let origin = crate::MemberOrigin::Offset(0); //TODO fields.push(StructMember { name: Some(field_name.clone()), - binding: binding.clone(), + origin, ty: if let Some(array_spec) = ident.array_spec { self.types.fetch_or_append(Type { name: None, @@ -171,7 +168,6 @@ impl<'a> Parser<'a> { } else { ty }, - offset: 0, //TODO }); if name.is_none() { diff --git a/src/front/spv.rs b/src/front/spv.rs index ae435eb69..fb9873b06 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -40,8 +40,8 @@ pub enum Error { InvalidParameter(spirv::Op), InvalidOperandCount(spirv::Op, u16), InvalidOperand, - InvalidDecoration(spirv::Word), InvalidId(spirv::Word), + InvalidDecoration(spirv::Word), InvalidTypeWidth(spirv::Word), InvalidSign(spirv::Word), InvalidInnerType(spirv::Word), @@ -242,6 +242,32 @@ impl Decoration { _ => None, } } + + fn get_origin(&self) -> Result { + match *self { + Decoration { + location: Some(_), .. + } + | Decoration { + desc_set: Some(_), .. + } + | Decoration { + desc_index: Some(_), + .. + } => Err(Error::MissingDecoration(spirv::Decoration::Offset)), + Decoration { + built_in: Some(built_in), + offset: None, + .. + } => Ok(crate::MemberOrigin::BuiltIn(built_in)), + Decoration { + built_in: None, + offset: Some(offset), + .. + } => Ok(crate::MemberOrigin::Offset(offset)), + _ => Err(Error::MissingDecoration(spirv::Decoration::Offset)), + } + } } bitflags::bitflags! { @@ -981,6 +1007,7 @@ impl> Parser { Op::Decorate => self.parse_decorate(inst), Op::MemberDecorate => self.parse_member_decorate(inst), Op::TypeVoid => self.parse_type_void(inst), + Op::TypeBool => self.parse_type_bool(inst, &mut module), Op::TypeInt => self.parse_type_int(inst, &mut module), Op::TypeFloat => self.parse_type_float(inst, &mut module), Op::TypeVector => self.parse_type_vector(inst, &mut module), @@ -1009,7 +1036,7 @@ impl> Parser { if flags == SamplingFlags::all() { return Err(Error::InconsistentComparisonSampling(handle)); } - let ty = module.types.mutate(handle); + let ty = module.types.get_mut(handle); match ty.inner { crate::TypeInner::Sampler { ref mut comparison } => { assert!(!*comparison); @@ -1210,6 +1237,31 @@ impl> Parser { Ok(()) } + fn parse_type_bool( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(2)?; + let id = self.next()?; + let inner = crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: 1, + }; + self.lookup_type.insert( + id, + LookupType { + handle: module.types.append(crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }), + base_id: None, + }, + ); + Ok(()) + } + fn parse_type_int( &mut self, inst: Instruction, @@ -1412,7 +1464,7 @@ impl> Parser { module: &mut crate::Module, ) -> Result<(), Error> { self.switch(ModuleState::Type, inst.op)?; - inst.expect(4)?; + inst.expect(3)?; let id = self.next()?; let type_id = self.next()?; @@ -1443,6 +1495,12 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(2)?; let id = self.next()?; + let decor = self.future_decor.remove(&id); + if let Some(ref decor) = decor { + if decor.block.is_some() { + // do nothing + } + } let mut members = Vec::with_capacity(inst.wc as usize - 2); for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; @@ -1452,23 +1510,14 @@ impl> Parser { .future_member_decor .remove(&(id, i)) .unwrap_or_default(); - let binding = decor.get_binding(); + let origin = decor.get_origin()?; members.push(crate::StructMember { name: decor.name, - binding, + origin, ty, - offset: decor - .offset - .ok_or(Error::MissingDecoration(spirv::Decoration::Offset))?, }); } let inner = crate::TypeInner::Struct { members }; - let decor = self.future_decor.remove(&id); - if let Some(ref decor) = decor { - if decor.block.is_some() { - // do nothing - } - } self.lookup_type.insert( id, LookupType { @@ -1719,26 +1768,10 @@ impl> Parser { | crate::TypeInner::Pointer { base, class: crate::StorageClass::Output, - } => { - match module.types[base].inner { - crate::TypeInner::Struct { ref members } => { - // we don't expect binding decoration on I/O structs, - // but we do expect them on all of the members - for member in members { - if member.binding.is_none() { - log::warn!( - "Struct {:?} member {:?} doesn't have a binding", - base, - member - ); - return Err(Error::InvalidBinding(id)); - } - } - None - } - _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), - } - } + } => match module.types[base].inner { + crate::TypeInner::Struct { members: _ } => None, + _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), + }, _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), }; let var = crate::GlobalVariable { diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index c12a10b2e..9ee23376a 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -975,9 +975,8 @@ impl Parser { lexer.expect(Token::Separator(';'))?; members.push(crate::StructMember { name: Some(name.to_owned()), - binding: None, + origin: crate::MemberOrigin::Offset(offset), ty, - offset, }); } } diff --git a/src/lib.rs b/src/lib.rs index 7463e1bc4..2bfe6ceb6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -122,14 +122,22 @@ pub enum ArraySize { Dynamic, } +/// Describes where a struct member is placed. +#[derive(Clone, Debug, PartialEq)] +pub enum MemberOrigin { + /// Built-in shader variable. + BuiltIn(BuiltIn), + /// Offset within the struct. + Offset(u32), +} + /// Member of a user-defined structure. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug, PartialEq)] pub struct StructMember { pub name: Option, - pub binding: Option, + pub origin: MemberOrigin, pub ty: Handle, - pub offset: u32, } /// The number of dimensions an image has. diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 576baea68..985ea5054 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -26,7 +26,11 @@ impl Validator { Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } | Ti::Matrix { kind, width, .. } => { - if width != 4 { + let expected = match kind { + crate::ScalarKind::Bool => 1, + _ => 4, + }; + if width != expected { return Err(ValidationError::InvalidTypeWidth(kind, width)); } } From 4a769c10b50e0c9d48d190b510eecc33ba66fa43 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 5 Jul 2020 01:35:28 -0400 Subject: [PATCH 0105/2212] [spv] remove the pointer indirection to variables --- Cargo.toml | 1 + src/back/msl.rs | 61 ++------ src/front/spv.rs | 296 +++++++++++++++++++++++++----------- test-data/spv/cube.frag.spv | Bin 0 -> 1208 bytes test-data/spv/cube.vert.spv | Bin 0 -> 1124 bytes tests/convert.rs | 17 +++ 6 files changed, 236 insertions(+), 139 deletions(-) create mode 100644 test-data/spv/cube.frag.spv create mode 100644 test-data/spv/cube.vert.spv diff --git a/Cargo.toml b/Cargo.toml index 8b18a4a01..3884ba309 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ pomelo = { version = "0.1.4", optional = true } thiserror = "1.0" [features] +default = [] glsl_preprocessor = ["glsl"] glsl-new = ["pomelo"] diff --git a/src/back/msl.rs b/src/back/msl.rs index 34ca94ce9..b9aafc48d 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -18,10 +18,6 @@ use std::fmt::{Display, Error as FmtError, Formatter, Write}; use crate::{arena::Handle, FastHashMap}; -/// Expect all the global variables to have a pointer type, -/// like in SPIR-V. -const GLOBAL_POINTERS: bool = false; - #[derive(Clone, Debug, Default, PartialEq)] pub struct BindTarget { pub buffer: Option, @@ -285,30 +281,12 @@ impl<'a> TypedGlobalVariable<'a> { } _ => ("", ""), }; - if GLOBAL_POINTERS { - let ty = &self.module.types[var.ty]; - match ty.inner { - crate::TypeInner::Pointer { base, class } => { - let ty_handle = match class { - crate::StorageClass::Constant - | crate::StorageClass::Input - | crate::StorageClass::Output - | crate::StorageClass::Uniform => base, - _ => var.ty, - }; - let ty_name = self.module.types[ty_handle].name.or_index(ty_handle); - Ok(write!(formatter, "{} {}", ty_name, name)?) - } - _ => Err(Error::UnexpectedGlobalType(var.ty)), - } - } else { - let ty_name = self.module.types[var.ty].name.or_index(var.ty); - Ok(write!( - formatter, - "{}{}{} {}", - space_qualifier, ty_name, reference, name - )?) - } + let ty_name = self.module.types[var.ty].name.or_index(var.ty); + Ok(write!( + formatter, + "{}{}{} {}", + space_qualifier, ty_name, reference, name + )?) } } @@ -511,14 +489,7 @@ impl Writer { let inner = &module.types[var.ty].inner; match var.class { crate::StorageClass::Output => { - if GLOBAL_POINTERS { - if let crate::TypeInner::Pointer { base, .. } = *inner { - let base_inner = &module.types[base].inner; - if let crate::TypeInner::Struct { .. } = *base_inner { - return Ok(MaybeOwned::Borrowed(base_inner)); - } - } - } else if let crate::TypeInner::Struct { .. } = *inner { + if let crate::TypeInner::Struct { .. } = *inner { return Ok(MaybeOwned::Borrowed(inner)); } write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; @@ -1035,14 +1006,7 @@ impl Writer { continue; } // if it's a struct, lift all the built-in contents up to the root - let mut ty_handle = var.ty; - if GLOBAL_POINTERS { - if let crate::TypeInner::Pointer { base, .. } = - module.types[var.ty].inner - { - ty_handle = base; - } - } + let ty_handle = var.ty; if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner { @@ -1080,14 +1044,7 @@ impl Writer { continue; } // if it's a struct, lift all the built-in contents up to the root - let mut ty_handle = var.ty; - if GLOBAL_POINTERS { - if let crate::TypeInner::Pointer { base, .. } = - module.types[var.ty].inner - { - ty_handle = base; - } - } + let ty_handle = var.ty; if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner { diff --git a/src/front/spv.rs b/src/front/spv.rs index fb9873b06..91708f411 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -27,16 +27,18 @@ pub enum Error { InvalidHeader, InvalidWordCount, UnknownInstruction(u16), - UnknownCapability(u32), + UnknownCapability(spirv::Word), UnsupportedInstruction(ModuleState, spirv::Op), UnsupportedCapability(spirv::Capability), UnsupportedExtension(String), UnsupportedExtSet(String), + UnsupportedExtInstSet(spirv::Word), + UnsupportedExtInst(spirv::Word), UnsupportedType(Handle), - UnsupportedExecutionModel(u32), - UnsupportedStorageClass(u32), - UnsupportedImageDim(u32), - UnsupportedBuiltIn(u32), + UnsupportedExecutionModel(spirv::Word), + UnsupportedStorageClass(spirv::Word), + UnsupportedImageDim(spirv::Word), + UnsupportedBuiltIn(spirv::Word), InvalidParameter(spirv::Op), InvalidOperandCount(spirv::Op, u16), InvalidOperand, @@ -48,7 +50,8 @@ pub enum Error { InvalidVectorSize(spirv::Word), InvalidVariableClass(spirv::StorageClass), InvalidAccessType(spirv::Word), - InvalidAccessIndex(Handle), + InvalidAccess(Handle), + InvalidAccessIndex(spirv::Word), InvalidLoadType(spirv::Word), InvalidStoreType(spirv::Word), InvalidBinding(spirv::Word), @@ -161,13 +164,16 @@ fn map_width(word: spirv::Word) -> Result { //TODO: this method may need to be gone, depending on whether // WGSL allows treating images and samplers as expressions and pass them around. fn reach_global_type( - expr_handle: Handle, + mut expr_handle: Handle, expressions: &Arena, globals: &Arena, ) -> Option> { - match expressions[expr_handle] { - crate::Expression::GlobalVariable(var) => Some(globals[var].ty), - _ => None, + loop { + expr_handle = match expressions[expr_handle] { + crate::Expression::Load { pointer } => pointer, + crate::Expression::GlobalVariable(var) => return Some(globals[var].ty), + _ => return None, + }; } } @@ -328,6 +334,7 @@ pub struct Parser { data: I, state: ModuleState, temp_bytes: Vec, + ext_glsl_id: Option, future_decor: FastHashMap, future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>, lookup_member_type_id: FastHashMap<(spirv::Word, MemberIndex), spirv::Word>, @@ -349,6 +356,7 @@ impl> Parser { data, state: ModuleState::Empty, temp_bytes: Vec::new(), + ext_glsl_id: None, future_decor: FastHashMap::default(), future_member_decor: FastHashMap::default(), handle_sampling: FastHashMap::default(), @@ -469,6 +477,34 @@ impl> Parser { Ok(()) } + fn parse_expr_binary_op( + &mut self, + fun: &mut crate::Function, + op: crate::BinaryOperator, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let p1_id = self.next()?; + let p2_id = self.next()?; + + let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let p2_lexp = self.lookup_expression.lookup(p2_id)?; + + let expr = crate::Expression::Binary { + op, + left: p1_lexp.handle, + right: p2_lexp.handle, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: fun.expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } + fn next_block( &mut self, fun: &mut crate::Function, @@ -481,6 +517,43 @@ impl> Parser { let inst = self.next_inst()?; log::debug!("\t\t{:?} [{}]", inst.op, inst.wc); match inst.op { + Op::Variable => { + inst.expect_at_least(4)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let storage = self.next()?; + match spirv::StorageClass::from_u32(storage) { + Some(spirv::StorageClass::Function) => (), + Some(class) => return Err(Error::InvalidVariableClass(class)), + None => return Err(Error::UnsupportedStorageClass(storage)), + } + let init = if inst.wc > 4 { + inst.expect(5)?; + let init_id = self.next()?; + let lexp = self.lookup_expression.lookup(init_id)?; + Some(lexp.handle) + } else { + None + }; + let name = self + .future_decor + .remove(&result_id) + .and_then(|decor| decor.name); + let var_handle = fun.local_variables.append(crate::LocalVariable { + name, + ty: self.lookup_type.lookup(result_type_id)?.handle, + init, + }); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: fun + .expressions + .append(crate::Expression::LocalVariable(var_handle)), + type_id: result_type_id, + }, + ); + } Op::AccessChain => { struct AccessExpression { base_handle: Handle, @@ -525,13 +598,11 @@ impl> Parser { crate::ConstantInner::Uint(v) => v as u32, crate::ConstantInner::Sint(v) => v as u32, _ => { - return Err(Error::InvalidAccessIndex( - index_expr.handle, - )) + return Err(Error::InvalidAccess(index_expr.handle)) } } } - _ => return Err(Error::InvalidAccessIndex(index_expr.handle)), + _ => return Err(Error::InvalidAccess(index_expr.handle)), }; AccessExpression { base_handle: fun.expressions.append( @@ -695,40 +766,24 @@ impl> Parser { fun.body.push(crate::Statement::Return { value: None }); break; } + Op::FSub => { + inst.expect(5)?; + self.parse_expr_binary_op(fun, crate::BinaryOperator::Subtract)?; + } + Op::FMul => { + inst.expect(5)?; + self.parse_expr_binary_op(fun, crate::BinaryOperator::Multiply)?; + } Op::VectorTimesScalar => { inst.expect(5)?; let result_type_id = self.next()?; - let result_type_loookup = self.lookup_type.lookup(result_type_id)?; - let (res_size, res_width) = match type_arena[result_type_loookup.handle].inner { - crate::TypeInner::Vector { - size, - kind: crate::ScalarKind::Float, - width, - } => (size, width), - _ => return Err(Error::UnsupportedType(result_type_loookup.handle)), - }; let result_id = self.next()?; let vector_id = self.next()?; let scalar_id = self.next()?; + let vector_lexp = self.lookup_expression.lookup(vector_id)?; - let vector_type_lookup = self.lookup_type.lookup(vector_lexp.type_id)?; - match type_arena[vector_type_lookup.handle].inner { - crate::TypeInner::Vector { - size, - kind: crate::ScalarKind::Float, - width, - } if size == res_size && width == res_width => (), - _ => return Err(Error::UnsupportedType(vector_type_lookup.handle)), - }; - let scalar_lexp = self.lookup_expression.lookup(scalar_id)?.clone(); - let scalar_type_lookup = self.lookup_type.lookup(scalar_lexp.type_id)?; - match type_arena[scalar_type_lookup.handle].inner { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width, - } if width == res_width => (), - _ => return Err(Error::UnsupportedType(scalar_type_lookup.handle)), - }; + let scalar_lexp = self.lookup_expression.lookup(scalar_id)?; + let expr = crate::Expression::Binary { op: crate::BinaryOperator::Multiply, left: vector_lexp.handle, @@ -745,39 +800,11 @@ impl> Parser { Op::MatrixTimesVector => { inst.expect(5)?; let result_type_id = self.next()?; - let result_type_loookup = self.lookup_type.lookup(result_type_id)?; - let (res_size, res_width) = match type_arena[result_type_loookup.handle].inner { - crate::TypeInner::Vector { - size, - kind: crate::ScalarKind::Float, - width, - } => (size, width), - _ => return Err(Error::UnsupportedType(result_type_loookup.handle)), - }; let result_id = self.next()?; let matrix_id = self.next()?; let vector_id = self.next()?; let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; - let matrix_type_lookup = self.lookup_type.lookup(matrix_lexp.type_id)?; - let columns = match type_arena[matrix_type_lookup.handle].inner { - crate::TypeInner::Matrix { - columns, - rows, - kind: crate::ScalarKind::Float, - width, - } if rows == res_size && width == res_width => columns, - _ => return Err(Error::UnsupportedType(matrix_type_lookup.handle)), - }; - let vector_lexp = self.lookup_expression.lookup(vector_id)?.clone(); - let vector_type_lookup = self.lookup_type.lookup(vector_lexp.type_id)?; - match type_arena[vector_type_lookup.handle].inner { - crate::TypeInner::Vector { - size, - kind: crate::ScalarKind::Float, - width, - } if size == columns && width == res_width => (), - _ => return Err(Error::UnsupportedType(vector_type_lookup.handle)), - }; + let vector_lexp = self.lookup_expression.lookup(vector_id)?; let expr = crate::Expression::Binary { op: crate::BinaryOperator::Multiply, left: matrix_lexp.handle, @@ -824,6 +851,11 @@ impl> Parser { let image_type_handle = reach_global_type(si_lexp.image, &fun.expressions, global_arena) .ok_or(Error::InvalidImageExpression(si_lexp.image))?; + log::debug!( + "\t\t\tImage {:?} with sampler {:?}", + image_type_handle, + sampler_type_handle + ); *self.handle_sampling.get_mut(&sampler_type_handle).unwrap() |= SamplingFlags::REGULAR; *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= @@ -932,6 +964,96 @@ impl> Parser { }, ); } + Op::VectorShuffle => { + inst.expect_at_least(5)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let v1_id = self.next()?; + let v2_id = self.next()?; + + let v1_lexp = self.lookup_expression.lookup(v1_id)?; + let v1_lty = self.lookup_type.lookup(v1_lexp.type_id)?; + let n1 = match type_arena[v1_lty.handle].inner { + crate::TypeInner::Vector { size, .. } => size as u8, + _ => return Err(Error::InvalidInnerType(v1_lexp.type_id)), + }; + let v1_handle = v1_lexp.handle; + let v2_lexp = self.lookup_expression.lookup(v2_id)?; + let v2_lty = self.lookup_type.lookup(v2_lexp.type_id)?; + let n2 = match type_arena[v2_lty.handle].inner { + crate::TypeInner::Vector { size, .. } => size as u8, + _ => return Err(Error::InvalidInnerType(v2_lexp.type_id)), + }; + let v2_handle = v2_lexp.handle; + + let mut components = Vec::with_capacity(inst.wc as usize - 5); + for _ in 0..components.capacity() { + let index = self.next()?; + let expr = if index < n1 as u32 { + crate::Expression::AccessIndex { + base: v1_handle, + index, + } + } else if index < n1 as u32 + n2 as u32 { + crate::Expression::AccessIndex { + base: v2_handle, + index: index - n1 as u32, + } + } else { + return Err(Error::InvalidAccessIndex(index)); + }; + components.push(fun.expressions.append(expr)); + } + let expr = crate::Expression::Compose { + ty: self.lookup_type.lookup(result_type_id)?.handle, + components, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: fun.expressions.append(expr), + type_id: result_type_id, + }, + ); + } + Op::ExtInst => { + inst.expect_at_least(5)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let set_id = self.next()?; + if Some(set_id) != self.ext_glsl_id { + return Err(Error::UnsupportedExtInstSet(set_id)); + } + let inst_id = self.next()?; + let name = match spirv::GLOp::from_u32(inst_id) { + Some(spirv::GLOp::Length) => { + inst.expect(5 + 1)?; + "length" + } + Some(spirv::GLOp::FMix) => { + inst.expect(5 + 3)?; + "mix" + } + _ => return Err(Error::UnsupportedExtInst(inst_id)), + }; + + let mut arguments = Vec::with_capacity(inst.wc as usize - 5); + for _ in 0..arguments.capacity() { + let arg_id = self.next()?; + arguments.push(self.lookup_expression.lookup(arg_id)?.handle); + } + let expr = crate::Expression::Call { + name: name.to_string(), + arguments, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: fun.expressions.append(expr), + type_id: result_type_id, + }, + ); + } _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } } @@ -974,7 +1096,7 @@ impl> Parser { } } - pub fn parse(&mut self) -> Result { + pub fn parse(mut self) -> Result { let mut module = crate::Module::from_header({ if self.next()? != spirv::MAGIC_NUMBER { return Err(Error::InvalidHeader); @@ -1022,7 +1144,7 @@ impl> Parser { Op::TypeSampler => self.parse_type_sampler(inst, &mut module), Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), - Op::Variable => self.parse_variable(inst, &mut module), + Op::Variable => self.parse_global_variable(inst, &mut module), Op::Function => self.parse_function(inst, &mut module), _ => Err(Error::UnsupportedInstruction(self.state, inst.op)), //TODO }?; @@ -1110,7 +1232,7 @@ impl> Parser { fn parse_ext_inst_import(&mut self, inst: Instruction) -> Result<(), Error> { self.switch(ModuleState::Extension, inst.op)?; inst.expect_at_least(3)?; - let _result = self.next()?; + let result_id = self.next()?; let (name, left) = self.next_string(inst.wc - 2)?; if left != 0 { return Err(Error::InvalidOperand); @@ -1118,6 +1240,7 @@ impl> Parser { if !SUPPORTED_EXT_SETS.contains(&name.as_str()) { return Err(Error::UnsupportedExtSet(name)); } + self.ext_glsl_id = Some(result_id); Ok(()) } @@ -1577,6 +1700,7 @@ impl> Parser { name: decor.name, inner, }); + log::debug!("\t\ttracking {:?} for sampling properties", handle); self.handle_sampling.insert(handle, SamplingFlags::empty()); self.lookup_type.insert( id, @@ -1619,6 +1743,7 @@ impl> Parser { name: decor.name, inner, }); + log::debug!("\t\ttracking {:?} for sampling properties", handle); self.handle_sampling.insert(handle, SamplingFlags::empty()); self.lookup_type.insert( id, @@ -1741,7 +1866,7 @@ impl> Parser { Ok(()) } - fn parse_variable( + fn parse_global_variable( &mut self, inst: Instruction, module: &mut crate::Module, @@ -1760,25 +1885,22 @@ impl> Parser { .future_decor .remove(&id) .ok_or(Error::InvalidBinding(id))?; - let binding = match module.types[lookup_type.handle].inner { - crate::TypeInner::Pointer { - base, - class: crate::StorageClass::Input, + let (ty, binding) = match module.types[lookup_type.handle].inner { + crate::TypeInner::Pointer { base, class } => { + let binding = match (class, &module.types[base].inner) { + (crate::StorageClass::Input, &crate::TypeInner::Struct { .. }) + | (crate::StorageClass::Output, &crate::TypeInner::Struct { .. }) => None, + _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), + }; + (base, binding) } - | crate::TypeInner::Pointer { - base, - class: crate::StorageClass::Output, - } => match module.types[base].inner { - crate::TypeInner::Struct { members: _ } => None, - _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), - }, - _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), + _ => return Err(Error::UnsupportedType(lookup_type.handle)), }; let var = crate::GlobalVariable { name: dec.name, class: map_storage_class(storage)?, binding, - ty: lookup_type.handle, + ty, }; self.lookup_variable.insert( id, diff --git a/test-data/spv/cube.frag.spv b/test-data/spv/cube.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..41358746fd14ea891129cce085219a17fdedc963 GIT binary patch literal 1208 zcmYk4T}xC^6o%J09krbN$kf!z8STrQCWDF~O2`XugcPMN2f;yv>cBXJmqPTP`f1(> zKF^-B!wv83z25b%&pGvxwXuj=+=}sd6T>qTBQOyYF`Dk3-GklE+2FYI_T8q6$*3ox znyDBgHWGdwo&M4>4_aUvojwZis*^S1A3+7IeAXBEZetI6=gHUb-Q6yKl>KB+W1s!E ziWit2kq~hc~#=8&o=6nv!k?j|i z{g*!UuLCvmdobpF3FI>xRjmy;^LK!C{cqInSGivCR^!Q>+8md;*A-`#e5kqaZ%02%;bg?L!}g7GF!yD1n+t5~cVr{5SqIUj)y$ z$%1Z}%$_r|XJ#iUmpU`XOqppjYdR)hbyE^!%z~*}-|Y|jM``wWbaHx3#nv^~R}eOi(4N`w2svB1m*Om97%;9e|vmg9)S z{mr9iIKDtvZ_dK?ie9yqVy@wOb>9_T$LXV+6&V_EXwVz?Xv naga::Module { naga::front::wgsl::parse_str(&input).unwrap() } +#[cfg(feature = "spirv")] +fn load_spv(name: &str) -> naga::Module { + let path = format!("{}/test-data/spv/{}", env!("CARGO_MANIFEST_DIR"), name); + let input = std::fs::read(path).unwrap(); + naga::front::spv::parse_u8_slice(&input).unwrap() +} + #[cfg(feature = "glsl")] fn load_glsl(name: &str, entry: &str, stage: naga::ShaderStage) -> naga::Module { let input = load_test_data(name); @@ -87,6 +94,16 @@ fn convert_boids() { } } +#[cfg(feature = "spirv")] +#[test] +fn convert_cube() { + let mut validator = naga::proc::Validator::new(); + let vs = load_spv("cube.vert.spv"); + validator.validate(&vs).unwrap(); + let fs = load_spv("cube.frag.spv"); + validator.validate(&fs).unwrap(); +} + #[cfg(feature = "glsl")] #[test] #[ignore] From cf62dc3d8c9694f9fdf4105c8590ba7cdebed9b1 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Sun, 5 Jul 2020 15:35:20 +0200 Subject: [PATCH 0106/2212] Glsl new multi line comments (#103) * Add multi line comment support to glsl-new * Fix glsl-new TokenMetadata for multi line comments --- src/front/glsl_new/lex.rs | 39 ++++++++++++++++++++------------- src/front/glsl_new/lex_tests.rs | 26 ++++++++++++++++++++++ src/front/glsl_new/parser.rs | 3 +++ 3 files changed, 53 insertions(+), 15 deletions(-) diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 0b6d67502..eb05603e2 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -181,13 +181,10 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { meta.chars.end = start + 2; (Some(Token::MulAssign(meta)), chars.as_str()) } - //TODO: multi-line comments - // Some('/') => ( - // Token::MultiLineCommentClose, - // chars.as_str(), - // start, - // start + 2, - // ), + Some('/') => { + meta.chars.end = start + 2; + (Some(Token::CommentEnd((meta, ()))), chars.as_str()) + } _ => (Some(Token::MulAssign(meta)), input), } } @@ -199,13 +196,10 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { (Some(Token::DivAssign(meta)), chars.as_str()) } Some('/') => (None, ""), - //TODO: multi-line comments - // Some('*') => ( - // Token::MultiLineCommentOpen, - // chars.as_str(), - // start, - // start + 2, - // ), + Some('*') => { + meta.chars.end = start + 2; + (Some(Token::CommentStart((meta, ()))), chars.as_str()) + } _ => (Some(Token::Slash(meta)), input), } } @@ -237,6 +231,7 @@ pub struct Lexer<'a> { input: String, line: usize, offset: usize, + inside_comment: bool, } impl<'a> Lexer<'a> { @@ -259,6 +254,7 @@ impl<'a> Lexer<'a> { input, line, offset: 0, + inside_comment: false, } } @@ -274,7 +270,20 @@ impl<'a> Lexer<'a> { meta.chars.start += self.offset; meta.chars.end += self.offset; self.offset += end; - Some(token) + if !self.inside_comment { + match token { + Token::CommentStart(_) => { + self.inside_comment = true; + self.next() + } + _ => Some(token), + } + } else { + if let Token::CommentEnd(_) = token { + self.inside_comment = false; + } + self.next() + } } else { let (line, input) = self.lines.next()?; diff --git a/src/front/glsl_new/lex_tests.rs b/src/front/glsl_new/lex_tests.rs index 377f17f5f..1da89d80f 100644 --- a/src/front/glsl_new/lex_tests.rs +++ b/src/front/glsl_new/lex_tests.rs @@ -61,6 +61,32 @@ fn glsl_lex_line_comment() { ); } +#[test] +fn glsl_lex_multi_line_comment() { + let source = "void main /* comment [] {}\n/**\n{}*/{}"; + let lex = Lexer::new(source); + let tokens: Vec = lex.collect(); + assert_eq!(tokens.len(), 4); + + let mut iter = tokens.iter(); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Void(TokenMetadata { line: 0, chars: 0..4 })" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Identifier((TokenMetadata { line: 0, chars: 5..9 }, \"main\"))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "LeftBrace(TokenMetadata { line: 2, chars: 4..5 })" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "RightBrace(TokenMetadata { line: 2, chars: 5..6 })" + ); +} + #[test] fn glsl_lex_identifier() { let source = "id123_OK 92No æNoø No¾ No好"; diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 10ac3af5c..194dca93d 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -25,6 +25,9 @@ pomelo! { } %type Unknown char; + %type CommentStart (); + %type CommentEnd (); + %type Identifier String; %type IntConstant i64; %type UintConstant u64; From 1acd12334aa588f30501c74dd0615e98df55a864 Mon Sep 17 00:00:00 2001 From: LaughingMan Date: Sun, 5 Jul 2020 08:23:56 +0200 Subject: [PATCH 0107/2212] WGSL front end: Only accept ASCII chars in identifiers Previously the lexer would accept any alphanumeric character as part of an identifier. The spec only allowes identifiers to consist of ASCII alphanumeric characters though. --- src/front/wgsl.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 9ee23376a..3b5b1a500 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -89,7 +89,7 @@ mod lex { (Token::Number(number), rest) } 'a'..='z' | 'A'..='Z' | '_' => { - let (word, rest) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); + let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); (Token::Word(word), rest) } '"' => { From 106cd6d188d3a35eca8aba1e70a038e937341c00 Mon Sep 17 00:00:00 2001 From: LaughingMan Date: Sun, 5 Jul 2020 08:35:50 +0200 Subject: [PATCH 0108/2212] WGSL front end: Add basic lexer tests --- src/front/wgsl.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 3b5b1a500..eeaffc331 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -7,7 +7,7 @@ use crate::{ FastHashMap, }; -#[derive(Debug, PartialEq)] +#[derive(Copy, Clone, Debug, PartialEq)] pub enum Token<'a> { Separator(char), DoubleColon, @@ -1482,6 +1482,8 @@ pub fn parse_str(source: &str) -> Result { #[cfg(test)] mod tests { + use crate::front::wgsl::{Lexer, Token}; + #[test] fn check_constant_type_scalar_ok() { let wgsl = "const a : i32 = 2;"; @@ -1493,4 +1495,29 @@ mod tests { let wgsl = "const a : i32 = 2.0;"; assert!(super::parse_str(wgsl).is_err()); } + + #[test] + fn check_lexer() { + use Token::{End, Number, String, Unknown, Word}; + let data = vec![ + ("id123_OK", vec![Word("id123_OK"), End]), + ("92No", vec![Number("92"), Word("No"), End]), + ("æNoø", vec![Unknown('æ'), Word("No"), Unknown('ø'), End]), + ("No¾", vec![Word("No"), Unknown('¾'), End]), + ("No好", vec![Word("No"), Unknown('好'), End]), + ("\"\u{2}ПЀ\u{0}\"", vec![String("\u{2}ПЀ\u{0}"), End]), // https://github.com/gfx-rs/naga/issues/90 + ]; + for (x, expected) in data { + let mut lex = Lexer::new(x); + let mut results = vec![]; + loop { + let result = lex.next(); + results.push(result); + if result == Token::End { + break; + } + } + assert_eq!(expected, results); + } + } } From ec52598d619733c96044e387d9ecead3cba6e0c4 Mon Sep 17 00:00:00 2001 From: Paul Kernfeld Date: Sun, 5 Jul 2020 13:36:57 -0400 Subject: [PATCH 0109/2212] Deny on panics with clippy --- src/back/spv/layout.rs | 2 ++ src/front/glsl/mod.rs | 1 + src/front/glsl_new/parser.rs | 1 + src/front/spv.rs | 10 ++++++++-- src/lib.rs | 1 + 5 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index 5db9a05ca..e4c3d1cc0 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -53,12 +53,14 @@ impl Instruction { } } + #[allow(clippy::panic)] pub(super) fn set_type(&mut self, id: Word) { assert!(self.type_id.is_none(), "Type can only be set once"); self.type_id = Some(id); self.wc += 1; } + #[allow(clippy::panic)] pub(super) fn set_result(&mut self, id: Word) { assert!(self.result_id.is_none(), "Result can only be set once"); self.result_id = Some(id); diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 40d372911..2d2baeb12 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,3 +1,4 @@ +#![allow(clippy::panic)] use crate::{ Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Constant, ConstantInner, EntryPoint, Expression, FastHashMap, Function, GlobalVariable, Handle, Header, LocalVariable, Module, diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 194dca93d..ee1c89b90 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -1,4 +1,5 @@ #![allow(unused_braces)] +#![allow(clippy::panic)] use pomelo::pomelo; pomelo! { diff --git a/src/front/spv.rs b/src/front/spv.rs index 91708f411..a28d0cf5a 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -1062,7 +1062,10 @@ impl> Parser { fn make_expression_storage(&mut self) -> Arena { let mut expressions = Arena::new(); - assert!(self.lookup_expression.is_empty()); + #[allow(clippy::panic)] + { + assert!(self.lookup_expression.is_empty()); + } // register global variables for (&id, var) in self.lookup_variable.iter() { self.lookup_expression.insert( @@ -1161,7 +1164,10 @@ impl> Parser { let ty = module.types.get_mut(handle); match ty.inner { crate::TypeInner::Sampler { ref mut comparison } => { - assert!(!*comparison); + #[allow(clippy::panic)] + { + assert!(!*comparison) + }; *comparison = true; } crate::TypeInner::Image { diff --git a/src/lib.rs b/src/lib.rs index 2bfe6ceb6..51f8984b5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ //! To improve performance and reduce memory usage, most structures are stored //! in an [`Arena`], and can be retrieved using the corresponding [`Handle`]. #![allow(clippy::new_without_default)] +#![deny(clippy::panic)] mod arena; pub mod back; From 39998a4c383660eaa851ac04ef6d8d677f92b368 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 5 Jul 2020 23:58:12 -0400 Subject: [PATCH 0110/2212] Differenciate between local and external function calls at IR level --- src/back/msl.rs | 2 +- src/front/glsl/mod.rs | 10 ++----- src/front/spv.rs | 63 ++++++++++++++++++++++++++++++++++++++++++- src/front/wgsl.rs | 3 +-- src/lib.rs | 11 ++++++-- src/proc/typifier.rs | 18 ++++++------- 6 files changed, 83 insertions(+), 24 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index b9aafc48d..586d72dc3 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -618,7 +618,7 @@ impl Writer { })) } crate::Expression::Call { - ref name, + origin: crate::FunctionOrigin::External(ref name), ref arguments, } => match name.as_str() { "cos" | "normalize" | "sin" => { diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 2d2baeb12..e8fc4d00d 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -85,7 +85,6 @@ struct Parser<'a> { globals_lookup: FastHashMap, constants: Arena, functions: Arena, - function_lookup: FastHashMap>, shader_stage: ShaderStage, } @@ -98,7 +97,6 @@ impl<'a> Parser<'a> { globals_lookup: FastHashMap::default(), constants: Arena::new(), functions: Arena::new(), - function_lookup: FastHashMap::default(), shader_stage, } } @@ -347,7 +345,7 @@ impl<'a> Parser<'a> { } let handle = self.functions.append(Function { - name: Some(name.clone()), + name: Some(name), parameter_types, return_type: ty, global_usage: vec![], @@ -355,9 +353,6 @@ impl<'a> Parser<'a> { expressions, body, }); - - self.function_lookup.insert(name, handle); - Ok(handle) } @@ -859,7 +854,7 @@ impl<'a> Parser<'a> { }) } _ => Ok(Expression::Call { - name, + origin: crate::FunctionOrigin::External(name), arguments: args .into_iter() .map(|arg| { @@ -901,7 +896,6 @@ impl<'a> Parser<'a> { &self.globals, locals, &self.functions, - &self.function_lookup, ) .map_err(|e| Error { kind: e.into() })?; let base_type = &self.types[type_handle]; diff --git a/src/front/spv.rs b/src/front/spv.rs index a28d0cf5a..50f57b194 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -330,6 +330,12 @@ struct LookupSampledImage { sampler: Handle, } +struct DeferredFunctionCall { + source_handle: Handle, + expr_handle: Handle, + dst_id: spirv::Word, +} + pub struct Parser { data: I, state: ModuleState, @@ -348,6 +354,7 @@ pub struct Parser { lookup_sampled_image: FastHashMap, lookup_function_type: FastHashMap, lookup_function: FastHashMap>, + deferred_function_calls: Vec, } impl> Parser { @@ -369,6 +376,7 @@ impl> Parser { lookup_sampled_image: FastHashMap::default(), lookup_function_type: FastHashMap::default(), lookup_function: FastHashMap::default(), + deferred_function_calls: Vec::new(), } } @@ -511,6 +519,7 @@ impl> Parser { type_arena: &Arena, const_arena: &Arena, global_arena: &Arena, + local_function_calls: &mut FastHashMap, spirv::Word>, ) -> Result<(), Error> { loop { use spirv::Op; @@ -1016,6 +1025,32 @@ impl> Parser { }, ); } + Op::FunctionCall => { + inst.expect_at_least(4)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let func_id = self.next()?; + + let mut arguments = Vec::with_capacity(inst.wc as usize - 4); + for _ in 0..arguments.capacity() { + let arg_id = self.next()?; + arguments.push(self.lookup_expression.lookup(arg_id)?.handle); + } + let expr = crate::Expression::Call { + // will be replaced by `Local()` after all the functions are parsed + origin: crate::FunctionOrigin::External(String::new()), + arguments, + }; + let expr_handle = fun.expressions.append(expr); + local_function_calls.insert(expr_handle, func_id); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expr_handle, + type_id: result_type_id, + }, + ); + } Op::ExtInst => { inst.expect_at_least(5)?; let result_type_id = self.next()?; @@ -1043,7 +1078,7 @@ impl> Parser { arguments.push(self.lookup_expression.lookup(arg_id)?.handle); } let expr = crate::Expression::Call { - name: name.to_string(), + origin: crate::FunctionOrigin::External(name.to_string()), arguments, }; self.lookup_expression.insert( @@ -1184,6 +1219,22 @@ impl> Parser { } } + for dfc in self.deferred_function_calls.drain(..) { + let dst_handle = *self.lookup_function.lookup(dfc.dst_id)?; + match *module + .functions + .get_mut(dfc.source_handle) + .expressions + .get_mut(dfc.expr_handle) + { + crate::Expression::Call { + ref mut origin, + arguments: _, + } => *origin = crate::FunctionOrigin::Local(dst_handle), + _ => unreachable!(), + } + } + if !self.future_decor.is_empty() { log::warn!("Unused item decorations: {:?}", self.future_decor); self.future_decor.clear(); @@ -1973,6 +2024,7 @@ impl> Parser { } } // read body + let mut local_function_calls = FastHashMap::default(); loop { let fun_inst = self.next_inst()?; log::debug!("\t\t{:?}", fun_inst.op); @@ -1985,6 +2037,7 @@ impl> Parser { &module.types, &module.constants, &module.global_variables, + &mut local_function_calls, )?; } spirv::Op::FunctionEnd => { @@ -1998,6 +2051,14 @@ impl> Parser { fun.global_usage = crate::GlobalUse::scan(&fun.expressions, &fun.body, &module.global_variables); let handle = module.functions.append(fun); + for (expr_handle, dst_id) in local_function_calls { + self.deferred_function_calls.push(DeferredFunctionCall { + source_handle: handle, + expr_handle, + dst_id, + }); + } + self.lookup_function.insert(fun_id, handle); self.lookup_expression.clear(); self.lookup_sampled_image.clear(); diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index eeaffc331..0614bf172 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -328,7 +328,6 @@ impl<'a> ExpressionContext<'a, '_, '_> { self.global_vars, self.local_vars, &Arena::new(), - &FastHashMap::default(), ) .map_err(Error::InvalidResolve) } @@ -548,7 +547,7 @@ impl Parser { arguments.push(arg); } crate::Expression::Call { - name: name.to_owned(), + origin: crate::FunctionOrigin::External(name.to_owned()), arguments, } } else { diff --git a/src/lib.rs b/src/lib.rs index 51f8984b5..be0873ffc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -338,6 +338,13 @@ pub enum DerivativeAxis { Width, } +/// Origin of a function to call. +#[derive(Clone, Debug, PartialEq)] +pub enum FunctionOrigin { + Local(Handle), + External(String), +} + /// An expression that can be evaluated to obtain a value. #[derive(Clone, Debug)] pub enum Expression { @@ -399,9 +406,9 @@ pub enum Expression { //modifier, expr: Handle, }, - /// Call a function defined in this module. + /// Call another function. Call { - name: String, + origin: FunctionOrigin, arguments: Vec>, }, } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index c3de558d1..044b5ea52 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -1,6 +1,6 @@ use crate::{ arena::{Arena, Handle}, - FastHashMap, Type, TypeInner, VectorSize, + Type, TypeInner, VectorSize, }; pub struct Typifier { @@ -32,7 +32,6 @@ impl Typifier { global_vars: &Arena, local_vars: &Arena, functions: &Arena, - function_lookup: &FastHashMap>, ) -> Result, ResolveError> { if self.types.len() <= expr_handle.index() { for (eh, expr) in expressions.iter().skip(self.types.len()) { @@ -93,7 +92,6 @@ impl Typifier { global_vars, local_vars, functions, - function_lookup, )?; let (kind, width) = match types[image].inner { @@ -168,7 +166,7 @@ impl Typifier { crate::Expression::CrossProduct(_, _) => unimplemented!(), crate::Expression::Derivative { .. } => unimplemented!(), crate::Expression::Call { - ref name, + origin: crate::FunctionOrigin::External(ref name), ref arguments, } => match name.as_str() { "distance" | "length" | "dot" => { @@ -184,14 +182,14 @@ impl Typifier { "normalize" | "fclamp" | "max" | "reflect" | "pow" | "clamp" | "mix" => { self.types[arguments[0].index()] } - other => functions[*function_lookup.get(other).ok_or( - ResolveError::FunctionNotDefined { - name: other.to_string(), - }, - )?] + _ => return Err(ResolveError::FunctionNotDefined { name: name.clone() }), + }, + crate::Expression::Call { + origin: crate::FunctionOrigin::Local(handle), + arguments: _, + } => functions[handle] .return_type .ok_or(ResolveError::FunctionReturnsVoid)?, - }, }; log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, ty); self.types.push(ty); From 28f22810a00fa747d8215cedfaaf34fd87ddcef0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 6 Jul 2020 00:32:55 -0400 Subject: [PATCH 0111/2212] [spv] first steps in control flow graph --- src/front/spv.rs | 129 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 91 insertions(+), 38 deletions(-) diff --git a/src/front/spv.rs b/src/front/spv.rs index 50f57b194..0b6929f9f 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -39,6 +39,7 @@ pub enum Error { UnsupportedStorageClass(spirv::Word), UnsupportedImageDim(spirv::Word), UnsupportedBuiltIn(spirv::Word), + UnsupportedControlFlow(spirv::Word), InvalidParameter(spirv::Op), InvalidOperandCount(spirv::Op, u16), InvalidOperand, @@ -336,6 +337,26 @@ struct DeferredFunctionCall { dst_id: spirv::Word, } +enum Terminator { + Return { + value: Option>, + }, + Branch { + label_id: spirv::Word, + condition: Option>, + }, +} + +struct Assignment { + to: Handle, + value: Handle, +} + +struct ControlFlowNode { + assignments: Vec, + terminator: Terminator, +} + pub struct Parser { data: I, state: ModuleState, @@ -487,7 +508,7 @@ impl> Parser { fn parse_expr_binary_op( &mut self, - fun: &mut crate::Function, + expressions: &mut Arena, op: crate::BinaryOperator, ) -> Result<(), Error> { let result_type_id = self.next()?; @@ -506,7 +527,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: fun.expressions.append(expr), + handle: expressions.append(expr), type_id: result_type_id, }, ); @@ -515,13 +536,15 @@ impl> Parser { fn next_block( &mut self, - fun: &mut crate::Function, + expressions: &mut Arena, + local_arena: &mut Arena, type_arena: &Arena, const_arena: &Arena, global_arena: &Arena, local_function_calls: &mut FastHashMap, spirv::Word>, - ) -> Result<(), Error> { - loop { + ) -> Result { + let mut assignments = Vec::new(); + let terminator = loop { use spirv::Op; let inst = self.next_inst()?; log::debug!("\t\t{:?} [{}]", inst.op, inst.wc); @@ -548,7 +571,7 @@ impl> Parser { .future_decor .remove(&result_id) .and_then(|decor| decor.name); - let var_handle = fun.local_variables.append(crate::LocalVariable { + let var_handle = local_arena.append(crate::LocalVariable { name, ty: self.lookup_type.lookup(result_type_id)?.handle, init, @@ -556,8 +579,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: fun - .expressions + handle: expressions .append(crate::Expression::LocalVariable(var_handle)), type_id: result_type_id, }, @@ -601,7 +623,7 @@ impl> Parser { let type_lookup = self.lookup_type.lookup(acex.type_id)?; acex = match type_arena[type_lookup.handle].inner { crate::TypeInner::Struct { .. } => { - let index = match fun.expressions[index_expr.handle] { + let index = match expressions[index_expr.handle] { crate::Expression::Constant(const_handle) => { match const_arena[const_handle].inner { crate::ConstantInner::Uint(v) => v as u32, @@ -614,7 +636,7 @@ impl> Parser { _ => return Err(Error::InvalidAccess(index_expr.handle)), }; AccessExpression { - base_handle: fun.expressions.append( + base_handle: expressions.append( crate::Expression::AccessIndex { base: acex.base_handle, index, @@ -629,7 +651,7 @@ impl> Parser { crate::TypeInner::Array { .. } | crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => AccessExpression { - base_handle: fun.expressions.append(crate::Expression::Access { + base_handle: expressions.append(crate::Expression::Access { base: acex.base_handle, index: index_expr.handle, }), @@ -679,7 +701,7 @@ impl> Parser { _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; lexp = LookupExpression { - handle: fun.expressions.append(crate::Expression::AccessIndex { + handle: expressions.append(crate::Expression::AccessIndex { base: lexp.handle, index, }), @@ -713,7 +735,7 @@ impl> Parser { self.lookup_expression.insert( id, LookupExpression { - handle: fun.expressions.append(expr), + handle: expressions.append(expr), type_id: result_type_id, }, ); @@ -742,7 +764,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: fun.expressions.append(expr), + handle: expressions.append(expr), type_id: result_type_id, }, ); @@ -765,23 +787,30 @@ impl> Parser { if base_type.base_id != Some(value_expr.type_id) { return Err(Error::InvalidStoreType(value_expr.type_id)); } - fun.body.push(crate::Statement::Store { - pointer: base_expr.handle, + assignments.push(Assignment { + to: base_expr.handle, value: value_expr.handle, - }) + }); } Op::Return => { inst.expect(1)?; - fun.body.push(crate::Statement::Return { value: None }); - break; + break Terminator::Return { value: None }; + } + Op::Branch => { + inst.expect(2)?; + let label_id = self.next()?; + break Terminator::Branch { + label_id, + condition: None, + }; } Op::FSub => { inst.expect(5)?; - self.parse_expr_binary_op(fun, crate::BinaryOperator::Subtract)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::Subtract)?; } Op::FMul => { inst.expect(5)?; - self.parse_expr_binary_op(fun, crate::BinaryOperator::Multiply)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::Multiply)?; } Op::VectorTimesScalar => { inst.expect(5)?; @@ -801,7 +830,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: fun.expressions.append(expr), + handle: expressions.append(expr), type_id: result_type_id, }, ); @@ -822,7 +851,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: fun.expressions.append(expr), + handle: expressions.append(expr), type_id: result_type_id, }, ); @@ -855,10 +884,10 @@ impl> Parser { let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; let sampler_type_handle = - reach_global_type(si_lexp.sampler, &fun.expressions, global_arena) + reach_global_type(si_lexp.sampler, &expressions, global_arena) .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; let image_type_handle = - reach_global_type(si_lexp.image, &fun.expressions, global_arena) + reach_global_type(si_lexp.image, &expressions, global_arena) .ok_or(Error::InvalidImageExpression(si_lexp.image))?; log::debug!( "\t\t\tImage {:?} with sampler {:?}", @@ -904,7 +933,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: fun.expressions.append(expr), + handle: expressions.append(expr), type_id: result_type_id, }, ); @@ -921,10 +950,10 @@ impl> Parser { let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; let sampler_type_handle = - reach_global_type(si_lexp.sampler, &fun.expressions, global_arena) + reach_global_type(si_lexp.sampler, &expressions, global_arena) .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; let image_type_handle = - reach_global_type(si_lexp.image, &fun.expressions, global_arena) + reach_global_type(si_lexp.image, &expressions, global_arena) .ok_or(Error::InvalidImageExpression(si_lexp.image))?; *self.handle_sampling.get_mut(&sampler_type_handle).unwrap() |= SamplingFlags::COMPARISON; @@ -968,7 +997,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: fun.expressions.append(expr), + handle: expressions.append(expr), type_id: result_type_id, }, ); @@ -1011,7 +1040,7 @@ impl> Parser { } else { return Err(Error::InvalidAccessIndex(index)); }; - components.push(fun.expressions.append(expr)); + components.push(expressions.append(expr)); } let expr = crate::Expression::Compose { ty: self.lookup_type.lookup(result_type_id)?.handle, @@ -1020,7 +1049,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: fun.expressions.append(expr), + handle: expressions.append(expr), type_id: result_type_id, }, ); @@ -1041,7 +1070,7 @@ impl> Parser { origin: crate::FunctionOrigin::External(String::new()), arguments, }; - let expr_handle = fun.expressions.append(expr); + let expr_handle = expressions.append(expr); local_function_calls.insert(expr_handle, func_id); self.lookup_expression.insert( result_id, @@ -1084,15 +1113,18 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: fun.expressions.append(expr), + handle: expressions.append(expr), type_id: result_type_id, }, ); } _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } - } - Ok(()) + }; + Ok(ControlFlowNode { + assignments, + terminator, + }) } fn make_expression_storage(&mut self) -> Arena { @@ -2025,20 +2057,41 @@ impl> Parser { } // read body let mut local_function_calls = FastHashMap::default(); + let mut control_flow_graph = FastHashMap::default(); loop { let fun_inst = self.next_inst()?; log::debug!("\t\t{:?}", fun_inst.op); match fun_inst.op { spirv::Op::Label => { fun_inst.expect(2)?; - let _id = self.next()?; - self.next_block( - &mut fun, + let label_id = self.next()?; + let node = self.next_block( + &mut fun.expressions, + &mut fun.local_variables, &module.types, &module.constants, &module.global_variables, &mut local_function_calls, )?; + // temp until the CFG is fully processed + for assign in node.assignments.iter() { + fun.body.push(crate::Statement::Store { + pointer: assign.to, + value: assign.value, + }); + } + match node.terminator { + Terminator::Return { value } => { + fun.body.push(crate::Statement::Return { value }); + } + Terminator::Branch { + label_id, + condition, + } => { + let _ = (label_id, condition); //TODO + } + } + control_flow_graph.insert(label_id, node); } spirv::Op::FunctionEnd => { fun_inst.expect(1)?; From c9fea374302cb51c69957a9552fcc306404923ee Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 8 Jul 2020 14:46:31 +0200 Subject: [PATCH 0112/2212] Add inital ast for glsl-new (#107) * Add inital ast for glsl-new * Fix clippy for glsl-new Deref instead of cloning --- src/front/glsl_new/ast.rs | 34 +++++++++++++++++++++++++++++++ src/front/glsl_new/mod.rs | 39 +++++++++++++----------------------- src/front/glsl_new/parser.rs | 15 ++++++++++---- 3 files changed, 59 insertions(+), 29 deletions(-) create mode 100644 src/front/glsl_new/ast.rs diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs new file mode 100644 index 000000000..1f0643912 --- /dev/null +++ b/src/front/glsl_new/ast.rs @@ -0,0 +1,34 @@ +use crate::{Arena, FastHashMap, Function, Handle}; + +#[derive(Debug)] +pub struct Program { + pub version: u16, + pub profile: Profile, + pub ext_decls: Vec, + pub lookup_function: FastHashMap>, + pub functions: Arena, +} + +impl Program { + pub fn new() -> Program { + Program { + version: 0, + profile: Profile::Core, + ext_decls: vec![], + lookup_function: FastHashMap::default(), + functions: Arena::::new(), + } + } +} + +#[derive(Debug)] +pub enum Profile { + // Compatibility, + Core, + // Es, +} + +#[derive(Debug)] +pub enum ExtDecl { + // FunctionDecl, +} diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index 202a7e6fa..6c1fb568f 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -1,11 +1,12 @@ -use crate::{ - Arena, Constant, EntryPoint, Function, GlobalVariable, Header, Module, ShaderStage, Type, -}; +use crate::{EntryPoint, Module, ShaderStage}; mod lex; #[cfg(test)] mod lex_tests; +mod ast; +use ast::Program; + use lex::Lexer; mod error; use error::ParseError; @@ -15,38 +16,26 @@ mod token; pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { log::debug!("------ GLSL-pomelo ------"); - let module = Module { - header: Header { - version: (1, 0, 0), - generator: 0, - }, - types: Arena::::new(), - constants: Arena::::new(), - global_variables: Arena::::new(), - functions: Arena::::new(), - entry_points: vec![], - }; - + let mut program = Program::new(); let lex = Lexer::new(source); - let mut parser = parser::Parser::new(module); + let mut parser = parser::Parser::new(&mut program); for token in lex { parser.parse(token)?; } - let (_, mut parsed_module) = parser.end_of_input()?; + parser.end_of_input()?; + + let mut module = Module::generate_empty(); + module.functions = program.functions; // find entry point - let entry_func = parsed_module - .functions - .iter() - .find(|(_, f)| f.name.as_ref().filter(|n| **n == entry).is_some()); - if let Some((h, _)) = entry_func { - parsed_module.entry_points.push(EntryPoint { + if let Some(entry_handle) = program.lookup_function.get(&entry) { + module.entry_points.push(EntryPoint { stage, name: entry, - function: h, + function: *entry_handle, }); } - Ok(parsed_module) + Ok(module) } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index ee1c89b90..9cba9a6b6 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -5,11 +5,12 @@ use pomelo::pomelo; pomelo! { //%verbose; %include { - use super::super::{error::ErrorKind, token::*}; - use crate::{Arena, Expression, Function, LocalVariable, Module}; + use super::super::{error::ErrorKind, token::*, ast::*}; + use crate::{Arena, Expression, Function, LocalVariable}; } %token #[derive(Debug)] pub enum Token {}; - %extra_argument Module; + %parser pub struct Parser<'a> {}; + %extra_argument &'a mut Program; %extra_token TokenMetadata; %error ErrorKind; %syntax_error { @@ -176,7 +177,13 @@ pomelo! { translation_unit ::= external_declaration; translation_unit ::= translation_unit external_declaration; - external_declaration ::= function_definition(f) { extra.functions.append(f); } + external_declaration ::= function_definition(f) { + let name = f.name.clone(); + let handle = extra.functions.append(f); + if let Some(name) = name { + extra.lookup_function.insert(name, handle); + } + } function_definition ::= function_prototype compound_statement_no_new_scope { Function { From 6c062087fa649654047764bc6ac8cea10a7de474 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristoffer=20S=C3=B8holm?= Date: Fri, 10 Jul 2020 02:52:13 +0200 Subject: [PATCH 0113/2212] Initial GLSL constant evaluation implementation (#94) Adds constant evaluation for addition, and uses it for globals and array specifiers. --- src/front/glsl/mod.rs | 255 +++++++++++++++++------- test-data/glsl_constant_expression.vert | 9 + tests/convert.rs | 11 + 3 files changed, 206 insertions(+), 69 deletions(-) create mode 100644 test-data/glsl_constant_expression.vert diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index e8fc4d00d..993e0214b 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -63,6 +63,8 @@ pub enum ErrorKind { EOL, #[error("End of file")] EOF, + #[error("Non constant expression encountered where a constant expression was expected")] + NonConstantExpr, } #[derive(Debug, thiserror::Error)] @@ -83,6 +85,7 @@ struct Parser<'a> { types: Arena, globals: Arena, globals_lookup: FastHashMap, + globals_constants: FastHashMap>, constants: Arena, functions: Arena, shader_stage: ShaderStage, @@ -95,6 +98,7 @@ impl<'a> Parser<'a> { types: Arena::new(), globals: Arena::new(), globals_lookup: FastHashMap::default(), + globals_constants: FastHashMap::default(), constants: Arena::new(), functions: Arena::new(), shader_stage, @@ -107,6 +111,10 @@ impl<'a> Parser<'a> { //println!("{:#?}", ast); let mut entry_point = None; + let parameter_lookup = FastHashMap::default(); + let mut locals = Arena::::new(); + let mut locals_map = FastHashMap::default(); + let mut expressions = Arena::::new(); for declaration in ast { match declaration { @@ -125,9 +133,32 @@ impl<'a> Parser<'a> { } } ExternalDeclaration::Declaration(decl) => match decl { - Declaration::InitDeclaratorList(init) => { - let handle = self.parse_global(init); + Declaration::InitDeclaratorList(mut init) => { + // Get initializer out for lifetime reasons. Maybe self.parse_global needs + // to take a reference and clone what it needs? + let mut initializer = None; + std::mem::swap(&mut initializer, &mut init.head.initializer); + + let handle = self.parse_global(init.head)?; let name = self.globals[handle].name.clone().unwrap(); + if let Some(initializer) = initializer { + match initializer { + Initializer::Simple(expr) => { + let expr = self.parse_expression( + *expr, + &mut expressions, + &mut locals, + &mut locals_map, + ¶meter_lookup, + )?; + let handle = expressions.append(expr); + let val = self.eval_const_expr(handle, &expressions)?; + self.globals_constants.insert(name.clone(), val); + } + _ => todo!(), + } + } + self.globals_lookup.insert(name, Global::Variable(handle)); } Declaration::Block(block) => { @@ -151,16 +182,12 @@ impl<'a> Parser<'a> { name: Some(field_name.clone()), origin, ty: if let Some(array_spec) = ident.array_spec { + let size = self.parse_array_size(array_spec)?; self.types.fetch_or_append(Type { name: None, inner: TypeInner::Array { base: ty, - size: match array_spec { - ArraySpecifier::Unsized => ArraySize::Dynamic, - ArraySpecifier::ExplicitlySized(_expr) => { - unimplemented!() - } - }, + size, stride: None, }, }) @@ -184,14 +211,12 @@ impl<'a> Parser<'a> { inner: TypeInner::Struct { members: fields }, }); + let size = self.parse_array_size(array_spec)?; self.types.fetch_or_append(Type { name: None, inner: TypeInner::Array { base, - size: match array_spec { - ArraySpecifier::Unsized => ArraySize::Dynamic, - ArraySpecifier::ExplicitlySized(_expr) => unimplemented!(), - }, + size, stride: None, }, }) @@ -259,18 +284,16 @@ impl<'a> Parser<'a> { FunctionParameterDeclaration::Named(_ /* TODO */, decl) => { let ty = self.parse_type(decl.ty).unwrap(); - let ty = if let Some(specifier) = decl.ident.array_spec { - match specifier { - ArraySpecifier::Unsized => self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size: ArraySize::Dynamic, - stride: None, - }, - }), - ArraySpecifier::ExplicitlySized(_) => unimplemented!(), - } + let ty = if let Some(array_spec) = decl.ident.array_spec { + let size = self.parse_array_size(array_spec)?; + self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size, + stride: None, + }, + }) } else { ty }; @@ -303,12 +326,7 @@ impl<'a> Parser<'a> { } _ => unimplemented!(), }, - SimpleStatement::Expression(expr) => { - let expr = match expr { - Some(expr) => expr, - None => continue, - }; - + SimpleStatement::Expression(Some(expr)) => { body.push(self.parse_statement( expr, &mut expressions, @@ -317,6 +335,7 @@ impl<'a> Parser<'a> { ¶meter_lookup, )?); } + SimpleStatement::Expression(None) => (), SimpleStatement::Selection(_) => unimplemented!(), SimpleStatement::Switch(_) => unimplemented!(), SimpleStatement::CaseLabel(_) => unimplemented!(), @@ -368,18 +387,16 @@ impl<'a> Parser<'a> { let ty = { let ty = self.parse_type(init.head.ty.ty).unwrap(); - if let Some(specifier) = init.head.array_specifier { - match specifier { - ArraySpecifier::Unsized => self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size: ArraySize::Dynamic, - stride: None, - }, - }), - ArraySpecifier::ExplicitlySized(_) => unimplemented!(), - } + if let Some(array_spec) = init.head.array_specifier { + let size = self.parse_array_size(array_spec)?; + self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size, + stride: None, + }, + }) } else { ty } @@ -980,19 +997,17 @@ impl<'a> Parser<'a> { fn parse_type(&mut self, ty: TypeSpecifier) -> Option> { let base_ty = helpers::glsl_to_spirv_type(ty.ty, &mut self.types)?; - let ty = if let Some(specifier) = ty.array_specifier { + let ty = if let Some(array_spec) = ty.array_specifier { let handle = self.types.fetch_or_append(Type { name: None, inner: base_ty, }); + let size = self.parse_array_size(array_spec).unwrap(); - match specifier { - ArraySpecifier::Unsized => TypeInner::Array { - base: handle, - size: ArraySize::Dynamic, - stride: None, - }, - ArraySpecifier::ExplicitlySized(_) => unimplemented!(), + TypeInner::Array { + base: handle, + size, + stride: None, } } else { base_ty @@ -1004,41 +1019,143 @@ impl<'a> Parser<'a> { })) } - fn parse_global(&mut self, init: InitDeclaratorList) -> Handle { - let name = init.head.name.map(|d| d.0); + fn parse_global(&mut self, head: SingleDeclaration) -> Result, Error> { + let name = head.name.map(|d| d.0); let ty = { - let ty = self.parse_type(init.head.ty.ty).unwrap(); + let ty = self.parse_type(head.ty.ty).unwrap(); - if let Some(specifier) = init.head.array_specifier { - match specifier { - ArraySpecifier::Unsized => self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size: ArraySize::Dynamic, - stride: None, - }, - }), - ArraySpecifier::ExplicitlySized(_) => unimplemented!(), - } + if let Some(array_spec) = head.array_specifier { + let size = self.parse_array_size(array_spec)?; + self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size, + stride: None, + }, + }) } else { ty } }; - let (class, binding) = init - .head + let (class, binding) = head .ty .qualifier .map(Self::parse_type_qualifier) .unwrap_or((StorageClass::Private, None)); - self.globals.append(GlobalVariable { + Ok(self.globals.append(GlobalVariable { name, class, binding, ty, - }) + })) + } + + /// https://www.khronos.org/opengl/wiki/Core_Language_(GLSL)#Constant_expression + pub fn eval_const_expr( + &mut self, + expr: Handle, + expressions: &Arena, + ) -> Result, Error> { + match &expressions[expr] { + Expression::Constant(handle) => Ok(*handle), + Expression::Call { .. } => todo!(), + Expression::GlobalVariable(handle) => { + let name = self.globals[*handle].name.as_ref().unwrap(); + if let Some(handle) = self.globals_constants.get(name) { + Ok(*handle) + } else { + todo!("Global const error") + } + } + Expression::Binary { left, right, op } => { + let left = self.eval_const_expr(*left, expressions)?; + let right = self.eval_const_expr(*right, expressions)?; + let inner: ConstantInner; + let ty; + match op { + BinaryOperator::Add => { + match (&self.constants[left].inner, &self.constants[right].inner) { + (ConstantInner::Sint(left), ConstantInner::Sint(right)) => { + inner = ConstantInner::Sint(left + right); + ty = self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + }) + } + (ConstantInner::Uint(left), ConstantInner::Uint(right)) => { + inner = ConstantInner::Uint(left + right); + ty = self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + }, + }) + } + (ConstantInner::Float(left), ConstantInner::Float(right)) => { + inner = ConstantInner::Float(left + right); + ty = self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 4, + }, + }) + } + _ => todo!(), + } + } + + _ => todo!(), + } + Ok(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner, + ty, + })) + } + expr => todo!("Const eval for {:?}", expr), + } + } + + pub fn parse_array_size(&mut self, array_spec: ArraySpecifier) -> Result { + let parameter_lookup = FastHashMap::default(); + let mut locals = Arena::::new(); + let mut locals_map = FastHashMap::default(); + let mut expressions = Arena::::new(); + let size = match array_spec { + ArraySpecifier::Unsized => ArraySize::Dynamic, + ArraySpecifier::ExplicitlySized(expr) => { + let expr = self.parse_expression( + *expr, + &mut expressions, + &mut locals, + &mut locals_map, + ¶meter_lookup, + )?; + let handle = expressions.append(expr); + + let const_handle = self.eval_const_expr(handle, &expressions)?; + + match &self.constants[const_handle].inner { + ConstantInner::Sint(val) => ArraySize::Static(*val as u32), + ConstantInner::Uint(val) => ArraySize::Static(*val as u32), + val => panic!( + "Array size must be an integral constant expression, got: {:?}", + val + ), + } + } + }; + + Ok(size) } fn parse_type_qualifier(qualifier: TypeQualifier) -> (StorageClass, Option) { diff --git a/test-data/glsl_constant_expression.vert b/test-data/glsl_constant_expression.vert new file mode 100644 index 000000000..3edd419c1 --- /dev/null +++ b/test-data/glsl_constant_expression.vert @@ -0,0 +1,9 @@ +#version 450 core + +const int N = 5; + +float foo[2+N]; + +void main() { + gl_Position = vec4(1); +} \ No newline at end of file diff --git a/tests/convert.rs b/tests/convert.rs index 6c8062353..c75b04515 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -123,3 +123,14 @@ fn convert_phong_lighting() { let mut w = naga::back::spv::Writer::new(&header, writer_flags); w.write(&module); } + +#[cfg(feature = "glsl")] +#[test] +fn constant_expressions() { + let module = load_glsl( + "glsl_constant_expression.vert", + "main", + naga::ShaderStage::Fragment, + ); + naga::proc::Validator::new().validate(&module).unwrap(); +} From e55c6b56e2752fafd10e749579b37ac515e0b5a4 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sun, 12 Jul 2020 20:22:47 +0200 Subject: [PATCH 0114/2212] Fix SPIR-V back-end, width will now be multiplied by 8 (#108) --- src/back/spv/writer.rs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a456d3cd5..107bfbda3 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -3,6 +3,8 @@ use super::{helpers, Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; use crate::{FastHashMap, FastHashSet, ImageFlags, VectorSize}; use spirv::{Op, Word}; +const BITS_PER_BYTE: u8 = 8; + enum Signedness { Unsigned = 0, Signed = 1, @@ -375,18 +377,18 @@ impl Writer { instruction } - fn instruction_type_int(&self, id: Word, width: u8, signedness: Signedness) -> Instruction { + fn instruction_type_int(&self, id: Word, width: Word, signedness: Signedness) -> Instruction { let mut instruction = Instruction::new(Op::TypeInt); instruction.set_result(id); - instruction.add_operand(width as u32); + instruction.add_operand(width); instruction.add_operand(signedness as u32); instruction } - fn instruction_type_float(&self, id: Word, width: u8) -> Instruction { + fn instruction_type_float(&self, id: Word, width: Word) -> Instruction { let mut instruction = Instruction::new(Op::TypeFloat); instruction.set_result(id); - instruction.add_operand(width as u32); + instruction.add_operand(width); instruction } @@ -743,13 +745,19 @@ impl Writer { match ty.inner { crate::TypeInner::Scalar { kind, width } => { instruction = match kind { - crate::ScalarKind::Sint => { - self.instruction_type_int(id, width, Signedness::Signed) + crate::ScalarKind::Sint => self.instruction_type_int( + id, + (width * BITS_PER_BYTE) as u32, + Signedness::Signed, + ), + crate::ScalarKind::Uint => self.instruction_type_int( + id, + (width * BITS_PER_BYTE) as u32, + Signedness::Unsigned, + ), + crate::ScalarKind::Float => { + self.instruction_type_float(id, (width * BITS_PER_BYTE) as u32) } - crate::ScalarKind::Uint => { - self.instruction_type_int(id, width, Signedness::Unsigned) - } - crate::ScalarKind::Float => self.instruction_type_float(id, width), crate::ScalarKind::Bool => self.instruction_type_bool(id), }; self.lookup_type.insert(id, handle); From 244c587457546a124cbf96ed9ee7c82f16ce3cce Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 13 Jul 2020 19:40:12 +0200 Subject: [PATCH 0115/2212] Glsl new handle version (#109) * Fix TokenMetadata for #version * Add glsl-new #version parsing * Fix clippy issues * glsl-new only core profile, allow 440-460 * Cleanup glsl-new profile matching --- src/front/glsl_new/ast.rs | 2 -- src/front/glsl_new/error.rs | 21 +++++++++---- src/front/glsl_new/lex.rs | 2 +- src/front/glsl_new/lex_tests.rs | 22 ++++++++++++++ src/front/glsl_new/mod.rs | 2 ++ src/front/glsl_new/parser.rs | 19 +++++++++++- src/front/glsl_new/parser_tests.rs | 49 ++++++++++++++++++++++++++++++ 7 files changed, 107 insertions(+), 10 deletions(-) create mode 100644 src/front/glsl_new/parser_tests.rs diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 1f0643912..61c1d18a1 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -23,9 +23,7 @@ impl Program { #[derive(Debug)] pub enum Profile { - // Compatibility, Core, - // Es, } #[derive(Debug)] diff --git a/src/front/glsl_new/error.rs b/src/front/glsl_new/error.rs index c860960ba..bfb7d7c93 100644 --- a/src/front/glsl_new/error.rs +++ b/src/front/glsl_new/error.rs @@ -1,12 +1,15 @@ use super::parser::Token; +use super::token::TokenMetadata; use std::{fmt, io}; #[derive(Debug)] pub enum ErrorKind { - InvalidInput, - IoError(io::Error), - InvalidToken(Token), EndOfFile, + InvalidInput, + InvalidProfile(TokenMetadata, String), + InvalidToken(Token), + InvalidVersion(TokenMetadata, i64), + IoError(io::Error), ParserFail, ParserStackOverflow, } @@ -14,10 +17,16 @@ pub enum ErrorKind { impl fmt::Display for ErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ErrorKind::InvalidInput => write!(f, "InvalidInput"), - ErrorKind::IoError(error) => write!(f, "IO Error {}", error), - ErrorKind::InvalidToken(token) => write!(f, "Invalid Token {:?}", token), ErrorKind::EndOfFile => write!(f, "Unexpected end of file"), + ErrorKind::InvalidInput => write!(f, "InvalidInput"), + ErrorKind::InvalidProfile(meta, val) => { + write!(f, "Invalid profile {} at {:?}", val, meta) + } + ErrorKind::InvalidToken(token) => write!(f, "Invalid Token {:?}", token), + ErrorKind::InvalidVersion(meta, val) => { + write!(f, "Invalid version {} at {:?}", val, meta) + } + ErrorKind::IoError(error) => write!(f, "IO Error {}", error), ErrorKind::ParserFail => write!(f, "Parser failed"), ErrorKind::ParserStackOverflow => write!(f, "Parser stack overflow"), } diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index eb05603e2..1f46f23c7 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -206,7 +206,7 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { '#' => { input = chars.as_str(); let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); - meta.chars.end = start + pos; + meta.chars.end = start + 1 + pos; match word { "version" => (Some(Token::Version(meta)), rest), _ => (None, input), diff --git a/src/front/glsl_new/lex_tests.rs b/src/front/glsl_new/lex_tests.rs index 1da89d80f..5d260cae5 100644 --- a/src/front/glsl_new/lex_tests.rs +++ b/src/front/glsl_new/lex_tests.rs @@ -136,3 +136,25 @@ fn glsl_lex_identifier() { "Unknown((TokenMetadata { line: 0, chars: 25..26 }, \'好\'))" ); } + +#[test] +fn glsl_lex_version() { + let source = "#version 890 core"; + let lex = Lexer::new(source); + let tokens: Vec = lex.collect(); + assert_eq!(tokens.len(), 3); + + let mut iter = tokens.iter(); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Version(TokenMetadata { line: 0, chars: 0..8 })" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "IntConstant((TokenMetadata { line: 0, chars: 9..12 }, 890))" + ); + assert_eq!( + format!("{:?}", iter.next().unwrap()), + "Identifier((TokenMetadata { line: 0, chars: 13..17 }, \"core\"))" + ); +} diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index 6c1fb568f..4836f5efb 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -11,6 +11,8 @@ use lex::Lexer; mod error; use error::ParseError; mod parser; +#[cfg(test)] +mod parser_tests; mod token; pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 9cba9a6b6..b0cca17ac 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -41,7 +41,24 @@ pomelo! { %type function_definition Function; root ::= version_pragma translation_unit; - version_pragma ::= Version IntConstant Identifier?; + version_pragma ::= Version IntConstant(V) Identifier?(P) { + match V.1 { + 440 => (), + 450 => (), + 460 => (), + _ => return Err(ErrorKind::InvalidVersion(V.0, V.1)) + } + extra.version = V.1 as u16; + extra.profile = match P { + Some((meta, profile)) => { + match profile.as_str() { + "core" => Profile::Core, + _ => return Err(ErrorKind::InvalidProfile(meta, profile)) + } + }, + None => Profile::Core, + } + }; // expression variable_identifier ::= Identifier; diff --git a/src/front/glsl_new/parser_tests.rs b/src/front/glsl_new/parser_tests.rs new file mode 100644 index 000000000..9da4677c6 --- /dev/null +++ b/src/front/glsl_new/parser_tests.rs @@ -0,0 +1,49 @@ +use super::ast::Program; +use super::error::ErrorKind; +use super::lex::Lexer; +use super::parser; + +fn parse_program(source: &str) -> Result { + let mut program = Program::new(); + let lex = Lexer::new(source); + let mut parser = parser::Parser::new(&mut program); + + for token in lex { + parser.parse(token)?; + } + parser.end_of_input()?; + Ok(program) +} + +#[test] +fn glsl_parser_version_invalid() { + assert_eq!( + format!("{:?}", parse_program("#version 99000").err().unwrap()), + "InvalidVersion(TokenMetadata { line: 0, chars: 9..14 }, 99000)" + ); + + assert_eq!( + format!("{:?}", parse_program("#version 449").err().unwrap()), + "InvalidVersion(TokenMetadata { line: 0, chars: 9..12 }, 449)" + ); + + assert_eq!( + format!("{:?}", parse_program("#version 450 smart").err().unwrap()), + "InvalidProfile(TokenMetadata { line: 0, chars: 13..18 }, \"smart\")" + ); +} + +#[test] +fn glsl_parser_version_valid() { + let program = parse_program("#version 450\nvoid main() {}").unwrap(); + assert_eq!( + format!("{:?}", (program.version, program.profile)), + "(450, Core)" + ); + + let program = parse_program("#version 450 core\nvoid main() {}").unwrap(); + assert_eq!( + format!("{:?}", (program.version, program.profile)), + "(450, Core)" + ); +} From d26f75485304a574b4500a116794ee451e0c072c Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 14 Jul 2020 14:56:18 +0200 Subject: [PATCH 0116/2212] Add more glsl-new handling of funcs and types (#110) --- src/front/glsl_new/ast.rs | 6 +++- src/front/glsl_new/mod.rs | 1 + src/front/glsl_new/parser.rs | 63 +++++++++++++++++++++++++++--------- 3 files changed, 53 insertions(+), 17 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 61c1d18a1..2ac0dd0bf 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -1,4 +1,4 @@ -use crate::{Arena, FastHashMap, Function, Handle}; +use crate::{Arena, FastHashMap, Function, Handle, Type}; #[derive(Debug)] pub struct Program { @@ -7,6 +7,8 @@ pub struct Program { pub ext_decls: Vec, pub lookup_function: FastHashMap>, pub functions: Arena, + pub lookup_type: FastHashMap>, + pub types: Arena, } impl Program { @@ -17,6 +19,8 @@ impl Program { ext_decls: vec![], lookup_function: FastHashMap::default(), functions: Arena::::new(), + lookup_type: FastHashMap::default(), + types: Arena::::new(), } } } diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index 4836f5efb..ca5c530f2 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -29,6 +29,7 @@ pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result {}; @@ -38,8 +39,18 @@ pomelo! { %type DoubleConstant f64; %type String String; %type arg_list Vec; + + %type function_prototype Function; + %type function_declarator Function; + %type function_header Function; + %type function_definition Function; + %type fully_specified_type Option>; + %type type_specifier Option>; + %type type_specifier_nonarray Option; + + root ::= version_pragma translation_unit; version_pragma ::= Version IntConstant(V) Identifier?(P) { match V.1 { @@ -178,16 +189,44 @@ pomelo! { // function - function_prototype ::= function_declarator RightParen; + function_prototype ::= function_declarator(f) RightParen {f} function_declarator ::= function_header; - function_header ::= fully_specified_type Identifier LeftParen; + function_header ::= fully_specified_type(t) Identifier(n) LeftParen { + Function { + name: Some(n.1), + parameter_types: vec![], + return_type: t, + global_usage: vec![], + local_variables: Arena::::new(), + expressions: Arena::::new(), + body: vec![], + } + } // type fully_specified_type ::= type_specifier; - type_specifier ::= type_specifier_nonarray; + type_specifier ::= type_specifier_nonarray(t) { + t.map(|t| { + let name = t.name.clone(); + let handle = extra.types.fetch_or_append(t); + if let Some(name) = name { + extra.lookup_type.insert(name, handle); + } + handle + }) + } - type_specifier_nonarray ::= Void; - type_specifier_nonarray ::= Vec4; + type_specifier_nonarray ::= Void { None } + type_specifier_nonarray ::= Vec4 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 16, + } + }) + } //TODO: remaining types // misc @@ -202,16 +241,8 @@ pomelo! { } } - function_definition ::= function_prototype compound_statement_no_new_scope { - Function { - name: Some(String::from("main")), - parameter_types: vec![], - return_type: None, - global_usage: vec![], - local_variables: Arena::::new(), - expressions: Arena::::new(), - body: vec![], - } + function_definition ::= function_prototype(f) compound_statement_no_new_scope { + f }; } From 56e78e47acbd71df8a5c4f34f8e1a793352734ff Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 16 Jul 2020 09:54:52 -0400 Subject: [PATCH 0117/2212] Enable clippy on monocodus --- .monocodus | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.monocodus b/.monocodus index b429007b9..7900103af 100644 --- a/.monocodus +++ b/.monocodus @@ -1,5 +1,7 @@ -version: 1.0.0 +version: 1.1.0 rust: formatter: name: rustfmt + repo_checkers: + - name: rust-clippy From 41ca3834f5bfecc513a96bd295b93eb7cc61e7c6 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 20 Jul 2020 16:56:10 +0200 Subject: [PATCH 0118/2212] [glsl-new] store int constants in module (#111) --- src/front/glsl_new/ast.rs | 4 +++- src/front/glsl_new/mod.rs | 1 + src/front/glsl_new/parser.rs | 20 +++++++++++++++++--- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 2ac0dd0bf..39b28e919 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -1,4 +1,4 @@ -use crate::{Arena, FastHashMap, Function, Handle, Type}; +use crate::{Arena, Constant, FastHashMap, Function, Handle, Type}; #[derive(Debug)] pub struct Program { @@ -9,6 +9,7 @@ pub struct Program { pub functions: Arena, pub lookup_type: FastHashMap>, pub types: Arena, + pub constants: Arena, } impl Program { @@ -21,6 +22,7 @@ impl Program { functions: Arena::::new(), lookup_type: FastHashMap::default(), types: Arena::::new(), + constants: Arena::::new(), } } } diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index ca5c530f2..44ad43b4b 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -30,6 +30,7 @@ pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result {}; @@ -75,7 +75,21 @@ pomelo! { variable_identifier ::= Identifier; primary_expression ::= variable_identifier; - primary_expression ::= IntConstant; + primary_expression ::= IntConstant(i) { + let ty = extra.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + } + }); + let ch = extra.constants.fetch_or_append(Constant { + name: None, + specialization: None, + ty, + inner: ConstantInner::Sint(i.1) + }); + } primary_expression ::= UintConstant; primary_expression ::= FloatConstant; primary_expression ::= BoolConstant; From 94802078c3bc5d138f497419ea3e7a869f10916d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 21 Jul 2020 11:36:05 -0400 Subject: [PATCH 0119/2212] Derive Error for validation errors (#112) --- src/proc/validator.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 985ea5054..b528fc069 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -1,14 +1,15 @@ use crate::arena::Handle; +#[derive(Debug)] pub struct Validator {} -#[derive(Clone, Debug)] +#[derive(Clone, Debug, thiserror::Error)] pub enum ValidationError { - /// The type width is not supported. + #[error("The type width is not supported")] InvalidTypeWidth(crate::ScalarKind, crate::Bytes), - /// A type handle can not be resolved. + #[error("The type handle can not be resolved")] UnresolvedType(Handle), - /// There are instructions after `return`/`break`/`continue`. + #[error("There are instructions after `return`/`break`/`continue`")] InvalidControlFlowExitTail, } From ccab9f7c3881882b77477fcf8c0bec4bea9ab9dd Mon Sep 17 00:00:00 2001 From: Gabriel Majeri Date: Tue, 21 Jul 2020 21:52:18 +0300 Subject: [PATCH 0120/2212] Implement `Error` for `wgsl::ParseError` (#113) --- src/front/wgsl.rs | 34 ++++++++++++++++++++++++---------- src/proc/typifier.rs | 7 +++++-- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 0614bf172..a8004b26e 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -7,6 +7,8 @@ use crate::{ FastHashMap, }; +use thiserror::Error; + #[derive(Copy, Clone, Debug, PartialEq)] pub enum Token<'a> { Separator(char), @@ -136,33 +138,44 @@ mod lex { } } -#[derive(Debug)] +#[derive(Clone, Debug, Error)] pub enum Error<'a> { + #[error("unexpected token: {0:?}")] Unexpected(Token<'a>), - UnexpectedConstantType(crate::proc::UnexpectedConstantTypeError), + #[error(transparent)] + UnexpectedConstantType(#[from] crate::proc::UnexpectedConstantTypeError), + #[error("unable to parse `{0}` as integer: {1}")] BadInteger(&'a str, std::num::ParseIntError), + #[error("unable to parse `{1}` as float: {1}")] BadFloat(&'a str, std::num::ParseFloatError), + #[error("bad field accessor `{0}`")] BadAccessor(&'a str), + #[error(transparent)] InvalidResolve(ResolveError), + #[error("unknown import: `{0}`")] UnknownImport(&'a str), + #[error("unknown storage class: `{0}`")] UnknownStorageClass(&'a str), + #[error("unknown decoration: `{0}`")] UnknownDecoration(&'a str), + #[error("unknown builtin: `{0}`")] UnknownBuiltin(&'a str), + #[error("unknown shader stage: `{0}`")] UnknownShaderStage(&'a str), + #[error("unknown identifier: `{0}`")] UnknownIdent(&'a str), + #[error("unknown type: `{0}`")] UnknownType(&'a str), + #[error("unknown function: `{0}`")] UnknownFunction(&'a str), + #[error("missing offset for structure member `{0}`")] MissingMemberOffset(&'a str), - MutabilityViolation(&'a str), + //MutabilityViolation(&'a str), + // TODO: these could be replaced with more detailed errors + #[error("other error")] Other, } -impl<'a> From for Error<'a> { - fn from(error: crate::proc::UnexpectedConstantTypeError) -> Self { - Error::UnexpectedConstantType(error) - } -} - #[derive(Clone)] struct Lexer<'a> { input: &'a str, @@ -370,7 +383,8 @@ pub enum Scope { GeneralExpr, } -#[derive(Debug)] +#[derive(Clone, Debug, Error)] +#[error("error while parsing WGSL in scopes {scopes:?} at position {pos:?}: {error}")] pub struct ParseError<'a> { pub error: Error<'a>, pub scopes: Vec, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 044b5ea52..c967bd80c 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -3,11 +3,13 @@ use crate::{ Type, TypeInner, VectorSize, }; +use thiserror::Error; + pub struct Typifier { types: Vec>, } -#[derive(Debug, thiserror::Error)] +#[derive(Clone, Debug, Error)] pub enum ResolveError { #[error("Invalid index into array")] InvalidAccessIndex, @@ -209,7 +211,8 @@ impl Typifier { } } -#[derive(Debug)] +#[derive(Clone, Debug, Error)] +#[error("mismatched constant type {0:?} expected {1:?}")] pub struct UnexpectedConstantTypeError(crate::ConstantInner, crate::TypeInner); pub fn check_constant_types( From 3884921f4ece24a0660afd6fd49bbf4a4aba6a14 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 23 Jul 2020 17:52:10 +0200 Subject: [PATCH 0121/2212] [glsl-new] handle gl_Position builtin (#114) * [glsl-new] handle gl_Position builtin - Also fix width of vec4 type * [glsl-new] add shader stage as arg to program ctor --- src/front/glsl_new/ast.rs | 15 ++++++-------- src/front/glsl_new/mod.rs | 3 ++- src/front/glsl_new/parser.rs | 33 ++++++++++++++++++++++++++---- src/front/glsl_new/parser_tests.rs | 30 ++++++++++++++++++++------- 4 files changed, 60 insertions(+), 21 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 39b28e919..fb6ab27d4 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -1,28 +1,30 @@ -use crate::{Arena, Constant, FastHashMap, Function, Handle, Type}; +use crate::{Arena, Constant, FastHashMap, Function, GlobalVariable, Handle, ShaderStage, Type}; #[derive(Debug)] pub struct Program { pub version: u16, pub profile: Profile, - pub ext_decls: Vec, + pub shader_stage: ShaderStage, pub lookup_function: FastHashMap>, pub functions: Arena, pub lookup_type: FastHashMap>, pub types: Arena, pub constants: Arena, + pub global_variables: Arena, } impl Program { - pub fn new() -> Program { + pub fn new(shader_stage: ShaderStage) -> Program { Program { version: 0, profile: Profile::Core, - ext_decls: vec![], + shader_stage, lookup_function: FastHashMap::default(), functions: Arena::::new(), lookup_type: FastHashMap::default(), types: Arena::::new(), constants: Arena::::new(), + global_variables: Arena::::new(), } } } @@ -31,8 +33,3 @@ impl Program { pub enum Profile { Core, } - -#[derive(Debug)] -pub enum ExtDecl { - // FunctionDecl, -} diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index 44ad43b4b..81e27bb3d 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -18,7 +18,7 @@ mod token; pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { log::debug!("------ GLSL-pomelo ------"); - let mut program = Program::new(); + let mut program = Program::new(stage); let lex = Lexer::new(source); let mut parser = parser::Parser::new(&mut program); @@ -31,6 +31,7 @@ pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result {}; @@ -72,7 +73,31 @@ pomelo! { }; // expression - variable_identifier ::= Identifier; + variable_identifier ::= Identifier(v) { + if v.1.as_str() == "gl_Position" && + (extra.shader_stage == ShaderStage::Vertex || + extra.shader_stage == ShaderStage::Fragment) { + extra.global_variables.fetch_or_append( + GlobalVariable { + name: Some(v.1), + class: match extra.shader_stage { + ShaderStage::Vertex => StorageClass::Output, + ShaderStage::Fragment => StorageClass::Input, + _ => StorageClass::Input, + }, + binding: Some(Binding::BuiltIn(BuiltIn::Position)), + ty: extra.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 4, + }, + }), + }, + ); + } + } primary_expression ::= variable_identifier; primary_expression ::= IntConstant(i) { @@ -237,7 +262,7 @@ pomelo! { inner: TypeInner::Vector { size: VectorSize::Quad, kind: ScalarKind::Float, - width: 16, + width: 4, } }) } diff --git a/src/front/glsl_new/parser_tests.rs b/src/front/glsl_new/parser_tests.rs index 9da4677c6..017df8780 100644 --- a/src/front/glsl_new/parser_tests.rs +++ b/src/front/glsl_new/parser_tests.rs @@ -2,9 +2,10 @@ use super::ast::Program; use super::error::ErrorKind; use super::lex::Lexer; use super::parser; +use crate::ShaderStage; -fn parse_program(source: &str) -> Result { - let mut program = Program::new(); +fn parse_program(source: &str, stage: ShaderStage) -> Result { + let mut program = Program::new(stage); let lex = Lexer::new(source); let mut parser = parser::Parser::new(&mut program); @@ -18,30 +19,45 @@ fn parse_program(source: &str) -> Result { #[test] fn glsl_parser_version_invalid() { assert_eq!( - format!("{:?}", parse_program("#version 99000").err().unwrap()), + format!( + "{:?}", + parse_program("#version 99000", ShaderStage::Vertex) + .err() + .unwrap() + ), "InvalidVersion(TokenMetadata { line: 0, chars: 9..14 }, 99000)" ); assert_eq!( - format!("{:?}", parse_program("#version 449").err().unwrap()), + format!( + "{:?}", + parse_program("#version 449", ShaderStage::Vertex) + .err() + .unwrap() + ), "InvalidVersion(TokenMetadata { line: 0, chars: 9..12 }, 449)" ); assert_eq!( - format!("{:?}", parse_program("#version 450 smart").err().unwrap()), + format!( + "{:?}", + parse_program("#version 450 smart", ShaderStage::Vertex) + .err() + .unwrap() + ), "InvalidProfile(TokenMetadata { line: 0, chars: 13..18 }, \"smart\")" ); } #[test] fn glsl_parser_version_valid() { - let program = parse_program("#version 450\nvoid main() {}").unwrap(); + let program = parse_program("#version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); assert_eq!( format!("{:?}", (program.version, program.profile)), "(450, Core)" ); - let program = parse_program("#version 450 core\nvoid main() {}").unwrap(); + let program = parse_program("#version 450 core\nvoid main() {}", ShaderStage::Vertex).unwrap(); assert_eq!( format!("{:?}", (program.version, program.profile)), "(450, Core)" From 115c29c0223eee9c98498fb91d5e7660d89389d8 Mon Sep 17 00:00:00 2001 From: Josh Groves Date: Sat, 25 Jul 2020 00:18:14 -0230 Subject: [PATCH 0122/2212] [msl] Cast single-component scalars (#115) * [msl] Cast single-component scalars * [msl] Allow `BinaryOperator::And` --- src/back/msl.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 586d72dc3..627bd1751 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -474,12 +474,17 @@ impl Writer { )?; for (i, &handle) in components.iter().enumerate() { if i != 0 { - write!(self.out, ",")?; + write!(self.out, ", ")?; } self.put_expression(handle, function, module)?; } write!(self.out, ")")?; } + crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { + write!(self.out, "{}(", scalar_kind_string(kind))?; + self.put_expression(components[0], function, module)?; + write!(self.out, ")")?; + } _ => return Err(Error::UnsupportedCompose(ty)), } Ok(MaybeOwned::Borrowed(inner)) @@ -540,6 +545,7 @@ impl Writer { crate::BinaryOperator::LessEqual => "<=", crate::BinaryOperator::Greater => "==", crate::BinaryOperator::GreaterEqual => ">=", + crate::BinaryOperator::And => "&", other => return Err(Error::UnsupportedBinaryOp(other)), }; //write!(self.out, "(")?; From 1eb637038dd15fc1dad770eca8e6943424dbc122 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 29 Jul 2020 04:48:05 +0200 Subject: [PATCH 0123/2212] [glsl-new] Add initial handling of stmts and exprs (#116) * [glsl-new] Add initial handling of stmts and exprs * [glsl-new] use &'static str for NotImplemented msg * [glsl-new] Don't lazy create function context --- src/front/glsl_new/ast.rs | 16 +- src/front/glsl_new/error.rs | 2 + src/front/glsl_new/parser.rs | 289 ++++++++++++++++++++++++++--------- 3 files changed, 236 insertions(+), 71 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index fb6ab27d4..36938356f 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -1,4 +1,7 @@ -use crate::{Arena, Constant, FastHashMap, Function, GlobalVariable, Handle, ShaderStage, Type}; +use crate::{ + Arena, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, LocalVariable, + ShaderStage, Type, +}; #[derive(Debug)] pub struct Program { @@ -11,6 +14,7 @@ pub struct Program { pub types: Arena, pub constants: Arena, pub global_variables: Arena, + pub context: Context, } impl Program { @@ -25,6 +29,10 @@ impl Program { types: Arena::::new(), constants: Arena::::new(), global_variables: Arena::::new(), + context: Context { + expressions: Arena::::new(), + local_variables: Arena::::new(), + }, } } } @@ -33,3 +41,9 @@ impl Program { pub enum Profile { Core, } + +#[derive(Debug)] +pub struct Context { + pub expressions: Arena, + pub local_variables: Arena, +} diff --git a/src/front/glsl_new/error.rs b/src/front/glsl_new/error.rs index bfb7d7c93..61e0ae7e6 100644 --- a/src/front/glsl_new/error.rs +++ b/src/front/glsl_new/error.rs @@ -12,6 +12,7 @@ pub enum ErrorKind { IoError(io::Error), ParserFail, ParserStackOverflow, + NotImplemented(&'static str), } impl fmt::Display for ErrorKind { @@ -29,6 +30,7 @@ impl fmt::Display for ErrorKind { ErrorKind::IoError(error) => write!(f, "IO Error {}", error), ErrorKind::ParserFail => write!(f, "Parser failed"), ErrorKind::ParserStackOverflow => write!(f, "Parser stack overflow"), + ErrorKind::NotImplemented(msg) => write!(f, "Not implemented: {}", msg), } } } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 55a3636a3..8760d0651 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -6,9 +6,9 @@ pomelo! { //%verbose; %include { use super::super::{error::ErrorKind, token::*, ast::*}; - use crate::{Arena, Binding, BuiltIn, Constant, ConstantInner, Expression, + use crate::{Arena, BinaryOperator, Binding, Block, BuiltIn, Constant, ConstantInner, Expression, Function, GlobalVariable, Handle, LocalVariable, ScalarKind, - ShaderStage, StorageClass, Type, TypeInner, VectorSize}; + ShaderStage, Statement, StorageClass, Type, TypeInner, VectorSize}; } %token #[derive(Debug)] pub enum Token {}; %parser pub struct Parser<'a> {}; @@ -33,20 +33,57 @@ pomelo! { %type CommentEnd (); %type Identifier String; + // constants %type IntConstant i64; %type UintConstant u64; %type FloatConstant f32; %type BoolConstant bool; %type DoubleConstant f64; %type String String; - %type arg_list Vec; - + // function %type function_prototype Function; %type function_declarator Function; %type function_header Function; - %type function_definition Function; + // statements + %type compound_statement Block; + %type compound_statement_no_new_scope Block; + %type statement_list Block; + %type statement Statement; + %type simple_statement Statement; + %type expression_statement Statement; + // expressions + %type unary_expression Handle; + %type postfix_expression Handle; + %type primary_expression Handle; + %type variable_identifier Handle; + + %type function_call Handle; + %type function_call_generic Handle; + %type function_call_header_no_parameters Handle; + %type function_call_header_with_parameters Handle; + %type function_call_header Handle; + %type function_identifier Handle; + + %type multiplicative_expression Handle; + %type additive_expression Handle; + %type shift_expression Handle; + %type relational_expression Handle; + %type equality_expression Handle; + %type and_expression Handle; + %type exclusive_or_expression Handle; + %type inclusive_or_expression Handle; + %type logical_and_expression Handle; + %type logical_xor_expression Handle; + %type logical_or_expression Handle; + %type conditional_expression Handle; + + %type assignment_expression (Statement, Handle); + %type assignment_operator BinaryOperator; + %type expression Statement; + + // types %type fully_specified_type Option>; %type type_specifier Option>; %type type_specifier_nonarray Option; @@ -77,7 +114,7 @@ pomelo! { if v.1.as_str() == "gl_Position" && (extra.shader_stage == ShaderStage::Vertex || extra.shader_stage == ShaderStage::Fragment) { - extra.global_variables.fetch_or_append( + let h = extra.global_variables.fetch_or_append( GlobalVariable { name: Some(v.1), class: match extra.shader_stage { @@ -96,6 +133,9 @@ pomelo! { }), }, ); + extra.context.expressions.append(Expression::GlobalVariable(h)) + } else { + return Err(ErrorKind::NotImplemented("var")) } } @@ -114,116 +154,222 @@ pomelo! { ty, inner: ConstantInner::Sint(i.1) }); + extra.context.expressions.append(Expression::Constant(ch)) } - primary_expression ::= UintConstant; - primary_expression ::= FloatConstant; - primary_expression ::= BoolConstant; - primary_expression ::= DoubleConstant; - primary_expression ::= LeftParen expression RightParen; + // primary_expression ::= UintConstant; + // primary_expression ::= FloatConstant; + // primary_expression ::= BoolConstant; + // primary_expression ::= DoubleConstant; + // primary_expression ::= LeftParen expression RightParen; postfix_expression ::= primary_expression; - postfix_expression ::= postfix_expression LeftBracket integer_expression RightBracket; + postfix_expression ::= postfix_expression LeftBracket integer_expression RightBracket { + // TODO + return Err(ErrorKind::NotImplemented("[]")) + } postfix_expression ::= function_call; - postfix_expression ::= postfix_expression Dot FieldSelection; - postfix_expression ::= postfix_expression IncOp; - postfix_expression ::= postfix_expression DecOp; + postfix_expression ::= postfix_expression Dot FieldSelection { + // TODO + return Err(ErrorKind::NotImplemented(".field")) + } + postfix_expression ::= postfix_expression(pe) IncOp { + // TODO + return Err(ErrorKind::NotImplemented("post++")) + } + postfix_expression ::= postfix_expression(pe) DecOp { + // TODO + return Err(ErrorKind::NotImplemented("post--")) + } integer_expression ::= expression; function_call ::= function_call_generic; - function_call_generic ::= function_call_header_with_parameters RightParen; - function_call_generic ::= function_call_header_no_parameters RightParen; - function_call_header_no_parameters ::= function_call_header Void; + function_call_generic ::= function_call_header_with_parameters(h) RightParen {h} + function_call_generic ::= function_call_header_no_parameters(h) RightParen {h} + function_call_header_no_parameters ::= function_call_header(h) Void {h} function_call_header_no_parameters ::= function_call_header; - function_call_header_with_parameters ::= function_call_header assignment_expression; - function_call_header_with_parameters ::= function_call_header_with_parameters Comma assignment_expression; - function_call_header ::= function_identifier LeftParen; + function_call_header_with_parameters ::= function_call_header(h) assignment_expression(ae) { + if let Expression::Compose{ty, components} = extra.context.expressions.get_mut(h) { + components.push(ae.1); + } + //TODO: Call + h + } + function_call_header_with_parameters ::= function_call_header_with_parameters(h) Comma assignment_expression(ae) { + if let Expression::Compose{ty, components} = extra.context.expressions.get_mut(h) { + components.push(ae.1); + } + //TODO: Call + h + } + function_call_header ::= function_identifier(i) LeftParen {i} // Grammar Note: Constructors look like functions, but lexical analysis recognized most of them as // keywords. They are now recognized through “type_specifier”. // Methods (.length), subroutine array calls, and identifiers are recognized through postfix_expression. - function_identifier ::= type_specifier; + function_identifier ::= type_specifier(t) { + if let Some(ty) = t { + extra.context.expressions.append(Expression::Compose{ + ty, + components: vec![], + }) + } else { + return Err(ErrorKind::NotImplemented("bad type ctor")) + } + } function_identifier ::= postfix_expression; unary_expression ::= postfix_expression; - unary_expression ::= IncOp unary_expression; - unary_expression ::= DecOp unary_expression; - unary_expression ::= unary_operator unary_expression; + unary_expression ::= IncOp unary_expression { + // TODO + return Err(ErrorKind::NotImplemented("++pre")) + } + unary_expression ::= DecOp unary_expression { + // TODO + return Err(ErrorKind::NotImplemented("--pre")) + } + unary_expression ::= unary_operator unary_expression { + // TODO + return Err(ErrorKind::NotImplemented("unary_op")) + } + unary_operator ::= Plus; unary_operator ::= Dash; unary_operator ::= Bang; unary_operator ::= Tilde; multiplicative_expression ::= unary_expression; - multiplicative_expression ::= multiplicative_expression Star unary_expression; - multiplicative_expression ::= multiplicative_expression Slash unary_expression; - multiplicative_expression ::= multiplicative_expression Percent unary_expression; + multiplicative_expression ::= multiplicative_expression(left) Star unary_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Multiply, left, right}) + } + multiplicative_expression ::= multiplicative_expression(left) Slash unary_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Divide, left, right}) + } + multiplicative_expression ::= multiplicative_expression(left) Percent unary_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Modulo, left, right}) + } additive_expression ::= multiplicative_expression; - additive_expression ::= additive_expression Plus multiplicative_expression; - additive_expression ::= additive_expression Dash multiplicative_expression; + additive_expression ::= additive_expression(left) Plus multiplicative_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Add, left, right}) + } + additive_expression ::= additive_expression(left) Dash multiplicative_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Subtract, left, right}) + } shift_expression ::= additive_expression; - shift_expression ::= shift_expression LeftOp additive_expression; - shift_expression ::= shift_expression RightOp additive_expression; + shift_expression ::= shift_expression(left) LeftOp additive_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::ShiftLeftLogical, left, right}) + } + shift_expression ::= shift_expression(left) RightOp additive_expression(right) { + //TODO: when to use ShiftRightArithmetic + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::ShiftRightLogical, left, right}) + } relational_expression ::= shift_expression; - relational_expression ::= relational_expression LeftAngle shift_expression; - relational_expression ::= relational_expression RightAngle shift_expression; - relational_expression ::= relational_expression LeOp shift_expression; - relational_expression ::= relational_expression GeOp shift_expression; + relational_expression ::= relational_expression(left) LeftAngle shift_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Less, left, right}) + } + relational_expression ::= relational_expression(left) RightAngle shift_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Greater, left, right}) + } + relational_expression ::= relational_expression(left) LeOp shift_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::LessEqual, left, right}) + } + relational_expression ::= relational_expression(left) GeOp shift_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::GreaterEqual, left, right}) + } equality_expression ::= relational_expression; - equality_expression ::= equality_expression EqOp relational_expression; - equality_expression ::= equality_expression NeOp relational_expression; + equality_expression ::= equality_expression(left) EqOp relational_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Equal, left, right}) + } + equality_expression ::= equality_expression(left) NeOp relational_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::NotEqual, left, right}) + } and_expression ::= equality_expression; - and_expression ::= and_expression Ampersand equality_expression; + and_expression ::= and_expression(left) Ampersand equality_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::And, left, right}) + } exclusive_or_expression ::= and_expression; - exclusive_or_expression ::= exclusive_or_expression Caret and_expression; + exclusive_or_expression ::= exclusive_or_expression(left) Caret and_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::ExclusiveOr, left, right}) + } inclusive_or_expression ::= exclusive_or_expression; - inclusive_or_expression ::= inclusive_or_expression VerticalBar exclusive_or_expression; + inclusive_or_expression ::= inclusive_or_expression(left) VerticalBar exclusive_or_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::InclusiveOr, left, right}) + } logical_and_expression ::= inclusive_or_expression; - logical_and_expression ::= logical_and_expression AndOp inclusive_or_expression; + logical_and_expression ::= logical_and_expression(left) AndOp inclusive_or_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::LogicalAnd, left, right}) + } logical_xor_expression ::= logical_and_expression; - logical_xor_expression ::= logical_xor_expression XorOp logical_and_expression; + logical_xor_expression ::= logical_xor_expression(left) XorOp logical_and_expression(right) { + return Err(ErrorKind::NotImplemented("logical xor")) + //TODO: naga doesn't have BinaryOperator::LogicalXor + // extra.context.expressions.append(Expression::Binary{op: BinaryOperator::LogicalXor, left, right}) + } logical_or_expression ::= logical_xor_expression; - logical_or_expression ::= logical_or_expression OrOp logical_xor_expression; + logical_or_expression ::= logical_or_expression(left) OrOp logical_xor_expression(right) { + extra.context.expressions.append(Expression::Binary{op: BinaryOperator::LogicalOr, left, right}) + } conditional_expression ::= logical_or_expression; - conditional_expression ::= logical_or_expression Question expression Colon assignment_expression; + conditional_expression ::= logical_or_expression Question expression Colon assignment_expression(ae) { + //TODO: how to do ternary here in naga? + return Err(ErrorKind::NotImplemented("ternary exp")) + } - assignment_expression ::= conditional_expression; - assignment_expression ::= unary_expression assignment_operator assignment_expression; + assignment_expression ::= conditional_expression(ce) { + (Statement::Empty, ce) + } + assignment_expression ::= unary_expression(pointer) assignment_operator(op) assignment_expression(value) { + match op { + BinaryOperator::Equal => (Statement::Store{pointer, value: value.1}, pointer), + //TODO: op != Equal + _ => {return Err(ErrorKind::NotImplemented("assign op"))} + } + } - assignment_operator ::= Equal; - assignment_operator ::= MulAssign; - assignment_operator ::= DivAssign; - assignment_operator ::= ModAssign; - assignment_operator ::= AddAssign; - assignment_operator ::= SubAssign; - assignment_operator ::= LeftAssign; - assignment_operator ::= RightAssign; - assignment_operator ::= AndAssign; - assignment_operator ::= XorAssign; - assignment_operator ::= OrAssign; + assignment_operator ::= Equal {BinaryOperator::Equal} + assignment_operator ::= MulAssign {BinaryOperator::Multiply} + assignment_operator ::= DivAssign {BinaryOperator::Divide} + assignment_operator ::= ModAssign {BinaryOperator::Modulo} + assignment_operator ::= AddAssign {BinaryOperator::Add} + assignment_operator ::= SubAssign {BinaryOperator::Subtract} + assignment_operator ::= LeftAssign {BinaryOperator::ShiftLeftLogical} + assignment_operator ::= RightAssign {BinaryOperator::ShiftRightLogical} + assignment_operator ::= AndAssign {BinaryOperator::And} + assignment_operator ::= XorAssign {BinaryOperator::ExclusiveOr} + assignment_operator ::= OrAssign {BinaryOperator::InclusiveOr} - expression ::= assignment_expression; - expression ::= expression Comma assignment_expression; + expression ::= assignment_expression(ae) {ae.0} + expression ::= expression(e) Comma assignment_expression(ae) { + match e { + Statement::Block(mut b) => { b.push(ae.0); Statement::Block(b) }, + e => Statement::Block(vec![e, ae.0]), + } + } // statement - statement ::= compound_statement; + statement ::= compound_statement(cs) {Statement::Block(cs)} statement ::= simple_statement; // Grammar Note: labeled statements for SWITCH only; 'goto' is not supported. //simple_statement ::= declaration_statement; simple_statement ::= expression_statement; + //simple_statement ::= selection_statement; + //simple_statement ::= switch_statement; + //simple_statement ::= case_label; + //simple_statement ::= iteration_statement; + //simple_statement ::= jump_statement; - compound_statement ::= LeftBrace RightBrace; - compound_statement ::= LeftBrace statement_list RightBrace; + compound_statement ::= LeftBrace RightBrace {vec![]} + compound_statement ::= LeftBrace statement_list(sl) RightBrace {sl} - compound_statement_no_new_scope ::= LeftBrace RightBrace; - compound_statement_no_new_scope ::= LeftBrace statement_list RightBrace; + compound_statement_no_new_scope ::= LeftBrace RightBrace {vec![]} + compound_statement_no_new_scope ::= LeftBrace statement_list(sl) RightBrace {sl} - statement_list ::= statement(s) { /*vec![s]*/ } - statement_list ::= statement_list/*(mut ss)*/ statement(s) { /*ss.push(s); ss*/ } + statement_list ::= statement(s) { vec![s] } + statement_list ::= statement_list(mut ss) statement(s) { ss.push(s); ss } - expression_statement ::= Semicolon; - expression_statement ::= expression Semicolon; + expression_statement ::= Semicolon {Statement::Empty} + expression_statement ::= expression(e) Semicolon {e} @@ -280,7 +426,10 @@ pomelo! { } } - function_definition ::= function_prototype(f) compound_statement_no_new_scope { + function_definition ::= function_prototype(mut f) compound_statement_no_new_scope(cs) { + std::mem::swap(&mut f.expressions, &mut extra.context.expressions); + std::mem::swap(&mut f.local_variables, &mut extra.context.local_variables); + f.body = cs; f }; } From 747535906f5ea58db6e6c6dc200fa329ad461d94 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 4 Aug 2020 21:45:55 +0200 Subject: [PATCH 0124/2212] [glsl-new] Add ExpressionRule for expr/stmts (#118) - Initial work for handling expressions that also generates statements --- src/front/glsl_new/ast.rs | 8 ++- src/front/glsl_new/parser.rs | 94 ++++++++++++++++++++++++++---------- 2 files changed, 75 insertions(+), 27 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 36938356f..f3a581381 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -1,6 +1,6 @@ use crate::{ Arena, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, LocalVariable, - ShaderStage, Type, + ShaderStage, Statement, Type, }; #[derive(Debug)] @@ -47,3 +47,9 @@ pub struct Context { pub expressions: Arena, pub local_variables: Arena, } + +#[derive(Debug)] +pub struct ExpressionRule { + pub expression: Handle, + pub statements: Vec, +} diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 8760d0651..f1c108007 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -54,10 +54,10 @@ pomelo! { %type expression_statement Statement; // expressions - %type unary_expression Handle; - %type postfix_expression Handle; - %type primary_expression Handle; - %type variable_identifier Handle; + %type unary_expression ExpressionRule; + %type postfix_expression ExpressionRule; + %type primary_expression ExpressionRule; + %type variable_identifier ExpressionRule; %type function_call Handle; %type function_call_generic Handle; @@ -79,9 +79,9 @@ pomelo! { %type logical_or_expression Handle; %type conditional_expression Handle; - %type assignment_expression (Statement, Handle); + %type assignment_expression ExpressionRule; %type assignment_operator BinaryOperator; - %type expression Statement; + %type expression ExpressionRule; // types %type fully_specified_type Option>; @@ -133,7 +133,10 @@ pomelo! { }), }, ); - extra.context.expressions.append(Expression::GlobalVariable(h)) + ExpressionRule{ + expression: extra.context.expressions.append(Expression::GlobalVariable(h)), + statements: vec![], + } } else { return Err(ErrorKind::NotImplemented("var")) } @@ -154,7 +157,10 @@ pomelo! { ty, inner: ConstantInner::Sint(i.1) }); - extra.context.expressions.append(Expression::Constant(ch)) + ExpressionRule { + expression: extra.context.expressions.append(Expression::Constant(ch)), + statements: vec![], + } } // primary_expression ::= UintConstant; // primary_expression ::= FloatConstant; @@ -167,7 +173,12 @@ pomelo! { // TODO return Err(ErrorKind::NotImplemented("[]")) } - postfix_expression ::= function_call; + postfix_expression ::= function_call(f) { + ExpressionRule{ + expression: f, + statements: vec![], + } + } postfix_expression ::= postfix_expression Dot FieldSelection { // TODO return Err(ErrorKind::NotImplemented(".field")) @@ -190,14 +201,16 @@ pomelo! { function_call_header_no_parameters ::= function_call_header; function_call_header_with_parameters ::= function_call_header(h) assignment_expression(ae) { if let Expression::Compose{ty, components} = extra.context.expressions.get_mut(h) { - components.push(ae.1); + components.push(ae.expression); + //TODO: ae.statements } //TODO: Call h } function_call_header_with_parameters ::= function_call_header_with_parameters(h) Comma assignment_expression(ae) { if let Expression::Compose{ty, components} = extra.context.expressions.get_mut(h) { - components.push(ae.1); + components.push(ae.expression); + //TODO: ae.statements } //TODO: Call h @@ -217,9 +230,10 @@ pomelo! { return Err(ErrorKind::NotImplemented("bad type ctor")) } } - function_identifier ::= postfix_expression; + function_identifier ::= postfix_expression(e) {e.expression} unary_expression ::= postfix_expression; + unary_expression ::= IncOp unary_expression { // TODO return Err(ErrorKind::NotImplemented("++pre")) @@ -237,15 +251,27 @@ pomelo! { unary_operator ::= Dash; unary_operator ::= Bang; unary_operator ::= Tilde; - multiplicative_expression ::= unary_expression; + multiplicative_expression ::= unary_expression(e) {e.expression} multiplicative_expression ::= multiplicative_expression(left) Star unary_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Multiply, left, right}) + extra.context.expressions.append(Expression::Binary{ + op: BinaryOperator::Multiply, + left, + right: right.expression, + }) } multiplicative_expression ::= multiplicative_expression(left) Slash unary_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Divide, left, right}) + extra.context.expressions.append(Expression::Binary{ + op: BinaryOperator::Divide, + left, + right: right.expression + }) } multiplicative_expression ::= multiplicative_expression(left) Percent unary_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Modulo, left, right}) + extra.context.expressions.append(Expression::Binary{ + op: BinaryOperator::Modulo, + left, + right: right.expression, + }) } additive_expression ::= multiplicative_expression; additive_expression ::= additive_expression(left) Plus multiplicative_expression(right) { @@ -316,13 +342,23 @@ pomelo! { } assignment_expression ::= conditional_expression(ce) { - (Statement::Empty, ce) + ExpressionRule{ + expression: ce, + statements: vec![], + } } - assignment_expression ::= unary_expression(pointer) assignment_operator(op) assignment_expression(value) { + assignment_expression ::= unary_expression(mut pointer) assignment_operator(op) assignment_expression(value) { match op { - BinaryOperator::Equal => (Statement::Store{pointer, value: value.1}, pointer), + BinaryOperator::Equal => { + pointer.statements.extend(value.statements); + pointer.statements.push(Statement::Store{ + pointer: pointer.expression, + value: value.expression + }); + pointer + }, //TODO: op != Equal - _ => {return Err(ErrorKind::NotImplemented("assign op"))} + _ => {return Err(ErrorKind::NotImplemented("assign op"))} } } @@ -338,11 +374,12 @@ pomelo! { assignment_operator ::= XorAssign {BinaryOperator::ExclusiveOr} assignment_operator ::= OrAssign {BinaryOperator::InclusiveOr} - expression ::= assignment_expression(ae) {ae.0} - expression ::= expression(e) Comma assignment_expression(ae) { - match e { - Statement::Block(mut b) => { b.push(ae.0); Statement::Block(b) }, - e => Statement::Block(vec![e, ae.0]), + expression ::= assignment_expression; + expression ::= expression(e) Comma assignment_expression(mut ae) { + ae.statements.extend(e.statements); + ExpressionRule{ + expression: e.expression, + statements: ae.statements, } } @@ -369,7 +406,12 @@ pomelo! { statement_list ::= statement_list(mut ss) statement(s) { ss.push(s); ss } expression_statement ::= Semicolon {Statement::Empty} - expression_statement ::= expression(e) Semicolon {e} + expression_statement ::= expression(mut e) Semicolon { + match e.statements.len() { + 1 => e.statements.remove(0), + _ => Statement::Block(e.statements), + } + } From 745ef6a6d609a6690d6051a16dec82e058884792 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 5 Aug 2020 15:45:42 +0200 Subject: [PATCH 0125/2212] [glsl-new] Add float consts (#119) --- src/front/glsl_new/parser.rs | 22 ++++++++++++++++++++-- test-data/simple.vert | 2 +- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index f1c108007..02a6b03e0 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -163,10 +163,28 @@ pomelo! { } } // primary_expression ::= UintConstant; - // primary_expression ::= FloatConstant; + primary_expression ::= FloatConstant(f) { + let ty = extra.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 4, + } + }); + let ch = extra.constants.fetch_or_append(Constant { + name: None, + specialization: None, + ty, + inner: ConstantInner::Float(f.1 as f64) + }); + ExpressionRule { + expression: extra.context.expressions.append(Expression::Constant(ch)), + statements: vec![], + } + } // primary_expression ::= BoolConstant; // primary_expression ::= DoubleConstant; - // primary_expression ::= LeftParen expression RightParen; + primary_expression ::= LeftParen expression(e) RightParen {e} postfix_expression ::= primary_expression; postfix_expression ::= postfix_expression LeftBracket integer_expression RightBracket { diff --git a/test-data/simple.vert b/test-data/simple.vert index 2a0aaea1c..515cc82a5 100644 --- a/test-data/simple.vert +++ b/test-data/simple.vert @@ -1,5 +1,5 @@ #version 450 core void main() { - gl_Position = vec4(1); + gl_Position = vec4(1.0); } From 6db5b373f87658daa36fe0aff3dec5387e910725 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sun, 9 Aug 2020 15:32:22 +0200 Subject: [PATCH 0126/2212] Add support for other matrices keywords (#121) Add mat2x3, mat2x4, mat3x2, mat3x4, mat4x2, and mat4x3 keywords --- src/front/wgsl.rs | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index a8004b26e..6ebf0aea0 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -1046,6 +1046,33 @@ impl Parser { width, } } + Token::Word("mat2x3") => { + let (kind, width) = lexer.next_scalar_generic()?; + crate::TypeInner::Matrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Tri, + kind, + width, + } + } + Token::Word("mat2x4") => { + let (kind, width) = lexer.next_scalar_generic()?; + crate::TypeInner::Matrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Quad, + kind, + width, + } + } + Token::Word("mat3x2") => { + let (kind, width) = lexer.next_scalar_generic()?; + crate::TypeInner::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Bi, + kind, + width, + } + } Token::Word("mat3x3") => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { @@ -1055,6 +1082,33 @@ impl Parser { width, } } + Token::Word("mat3x4") => { + let (kind, width) = lexer.next_scalar_generic()?; + crate::TypeInner::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Quad, + kind, + width, + } + } + Token::Word("mat4x2") => { + let (kind, width) = lexer.next_scalar_generic()?; + crate::TypeInner::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Bi, + kind, + width, + } + } + Token::Word("mat4x3") => { + let (kind, width) = lexer.next_scalar_generic()?; + crate::TypeInner::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Tri, + kind, + width, + } + } Token::Word("mat4x4") => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { From f98054afdd7503e2ee27f9952f98f07fd72ebe59 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Fri, 7 Aug 2020 04:49:43 +0000 Subject: [PATCH 0127/2212] [glsl-new] add vec2 and vec3 --- src/front/glsl_new/lex.rs | 2 ++ src/front/glsl_new/parser.rs | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 1f46f23c7..4eec42bc1 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -111,6 +111,8 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { meta.chars.end = start + pos; match word { "void" => (Some(Token::Void(meta)), rest), + "vec2" => (Some(Token::Vec2(meta)), rest), + "vec3" => (Some(Token::Vec3(meta)), rest), "vec4" => (Some(Token::Vec4(meta)), rest), //TODO: remaining types _ => (Some(Token::Identifier((meta, String::from(word)))), rest), diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 02a6b03e0..755b9d8e2 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -462,6 +462,26 @@ pomelo! { } type_specifier_nonarray ::= Void { None } + type_specifier_nonarray ::= Vec2 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Float, + width: 4, + } + }) + } + type_specifier_nonarray ::= Vec3 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Float, + width: 4, + } + }) + } type_specifier_nonarray ::= Vec4 { Some(Type { name: None, From 482c6d042d43c2ca9d5753ec7045709d5660ba1b Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Fri, 7 Aug 2020 15:25:34 +0000 Subject: [PATCH 0128/2212] [glsl.new] Add initial declaration support Focus on handling global in/out vars --- src/front/glsl_new/ast.rs | 12 +++- src/front/glsl_new/error.rs | 8 +++ src/front/glsl_new/lex.rs | 4 ++ src/front/glsl_new/parser.rs | 128 +++++++++++++++++++++++++++++++++-- test-data/simple.vert | 4 +- 5 files changed, 147 insertions(+), 9 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index f3a581381..baee50c6a 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -1,6 +1,6 @@ use crate::{ - Arena, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, LocalVariable, - ShaderStage, Statement, Type, + Arena, Binding, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, + LocalVariable, ShaderStage, Statement, StorageClass, Type, }; #[derive(Debug)] @@ -14,6 +14,7 @@ pub struct Program { pub types: Arena, pub constants: Arena, pub global_variables: Arena, + pub lookup_global_variables: FastHashMap>, pub context: Context, } @@ -29,6 +30,7 @@ impl Program { types: Arena::::new(), constants: Arena::::new(), global_variables: Arena::::new(), + lookup_global_variables: FastHashMap::default(), context: Context { expressions: Arena::::new(), local_variables: Arena::::new(), @@ -53,3 +55,9 @@ pub struct ExpressionRule { pub expression: Handle, pub statements: Vec, } + +#[derive(Debug)] +pub enum TypeQualifier { + StorageClass(StorageClass), + Binding(Binding), +} diff --git a/src/front/glsl_new/error.rs b/src/front/glsl_new/error.rs index 61e0ae7e6..726eee1c8 100644 --- a/src/front/glsl_new/error.rs +++ b/src/front/glsl_new/error.rs @@ -13,6 +13,9 @@ pub enum ErrorKind { ParserFail, ParserStackOverflow, NotImplemented(&'static str), + UnknownVariable(TokenMetadata, String), + ExpectedConstant, + SemanticError(&'static str), } impl fmt::Display for ErrorKind { @@ -31,6 +34,11 @@ impl fmt::Display for ErrorKind { ErrorKind::ParserFail => write!(f, "Parser failed"), ErrorKind::ParserStackOverflow => write!(f, "Parser stack overflow"), ErrorKind::NotImplemented(msg) => write!(f, "Not implemented: {}", msg), + ErrorKind::UnknownVariable(meta, val) => { + write!(f, "Unknown variable {} at {:?}", val, meta) + } + ErrorKind::ExpectedConstant => write!(f, "Expected constant"), + ErrorKind::SemanticError(msg) => write!(f, "Semantic error: {}", msg), } } } diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 4eec42bc1..898236723 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -110,6 +110,10 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { let (word, rest, pos) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); meta.chars.end = start + pos; match word { + "layout" => (Some(Token::Layout(meta)), rest), + "in" => (Some(Token::In(meta)), rest), + "out" => (Some(Token::Out(meta)), rest), + // types "void" => (Some(Token::Void(meta)), rest), "vec2" => (Some(Token::Vec2(meta)), rest), "vec3" => (Some(Token::Vec3(meta)), rest), diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 755b9d8e2..ecf2e058c 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -45,6 +45,7 @@ pomelo! { %type function_declarator Function; %type function_header Function; %type function_definition Function; + // statements %type compound_statement Block; %type compound_statement_no_new_scope Block; @@ -52,6 +53,7 @@ pomelo! { %type statement Statement; %type simple_statement Statement; %type expression_statement Statement; + %type declaration_statement Statement; // expressions %type unary_expression ExpressionRule; @@ -82,9 +84,18 @@ pomelo! { %type assignment_expression ExpressionRule; %type assignment_operator BinaryOperator; %type expression ExpressionRule; + %type constant_expression Handle; + + // decalartions + %type layout_qualifier Binding; + %type layout_qualifier_id_list Binding; + %type layout_qualifier_id Binding; + %type type_qualifier Vec; + %type single_type_qualifier TypeQualifier; + %type storage_qualifier StorageClass; // types - %type fully_specified_type Option>; + %type fully_specified_type (Vec, Option>); %type type_specifier Option>; %type type_specifier_nonarray Option; @@ -116,7 +127,7 @@ pomelo! { extra.shader_stage == ShaderStage::Fragment) { let h = extra.global_variables.fetch_or_append( GlobalVariable { - name: Some(v.1), + name: Some(v.1.clone()), class: match extra.shader_stage { ShaderStage::Vertex => StorageClass::Output, ShaderStage::Fragment => StorageClass::Input, @@ -133,12 +144,21 @@ pomelo! { }), }, ); + extra.lookup_global_variables.insert(v.1, h); ExpressionRule{ expression: extra.context.expressions.append(Expression::GlobalVariable(h)), statements: vec![], } } else { - return Err(ErrorKind::NotImplemented("var")) + // try global vars + if let Some(global_var) = extra.lookup_global_variables.get(&v.1) { + ExpressionRule{ + expression: extra.context.expressions.append(Expression::GlobalVariable(global_var.clone())), + statements: vec![], + } + } else { + return Err(ErrorKind::UnknownVariable(v.0, v.1)) + } } } @@ -401,12 +421,108 @@ pomelo! { } } + constant_expression ::= conditional_expression(e) { + if let Expression::Constant(h) = extra.context.expressions[e] { + h + } else { + return Err(ErrorKind::ExpectedConstant) + } + } + + // declaration + declaration ::= init_declarator_list Semicolon; + init_declarator_list ::= single_declaration; + single_declaration ::= fully_specified_type; + single_declaration ::= fully_specified_type(t) Identifier(i) { + //TODO: global or local? For now always global + if let Some(ty) = t.1 { + if let Some(TypeQualifier::StorageClass(sc)) = t.0.iter().find(|tq| { + if let TypeQualifier::StorageClass(_) = tq { true } else { false } + }) { + let binding = t.0.iter().find_map(|tq| { + if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } + }); + + let h = extra.global_variables.fetch_or_append( + GlobalVariable { + name: Some(i.1.clone()), + class: *sc, + binding: binding, + ty: ty, + }, + ); + extra.lookup_global_variables.insert(i.1, h); + + } else { + return Err(ErrorKind::SemanticError("Missing storage class for declaration")) + } + } else { + return Err(ErrorKind::SemanticError("Empty type for declaration")) + } + } + + fully_specified_type ::= type_specifier(t) {(vec![], t)} + fully_specified_type ::= type_qualifier(q) type_specifier(t) {(q,t)} + + layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen {l} + layout_qualifier_id_list ::= layout_qualifier_id; + layout_qualifier_id_list ::= layout_qualifier_id_list Comma layout_qualifier_id(l) { + //TODO: for now always pick last + l + } + // layout_qualifier_id ::= Identifier; + layout_qualifier_id ::= Identifier(i) Equal constant_expression(c) { + if i.1.as_str() == "location" { + if let ConstantInner::Sint(loc) = extra.constants[c].inner { + Binding::Location(loc as u32) + } else { + return Err(ErrorKind::NotImplemented("location not Sint")); + } + } else { + return Err(ErrorKind::NotImplemented("non location layout qualifier")); + } + } + // layout_qualifier_id ::= Shared; + + // precise_qualifier ::= Precise; + + type_qualifier ::= single_type_qualifier(t) { + vec![t] + } + type_qualifier ::= type_qualifier(mut l) single_type_qualifier(t) { + l.push(t); + l + } + + single_type_qualifier ::= storage_qualifier(s) { + TypeQualifier::StorageClass(s) + } + single_type_qualifier ::= layout_qualifier(l) { + TypeQualifier::Binding(l) + } + // single_type_qualifier ::= precision_qualifier; + // single_type_qualifier ::= interpolation_qualifier; + // single_type_qualifier ::= invariant_qualifier; + // single_type_qualifier ::= precise_qualifier; + + storage_qualifier ::= Const {StorageClass::Constant} + // storage_qualifier ::= InOut; + storage_qualifier ::= In {StorageClass::Input} + storage_qualifier ::= Out {StorageClass::Output} + //TODO: other storage qualifiers + + + declaration_statement ::= declaration { + //TODO: Should declarations be able to genereate expression/statements? + Statement::Empty + } + // statement statement ::= compound_statement(cs) {Statement::Block(cs)} statement ::= simple_statement; // Grammar Note: labeled statements for SWITCH only; 'goto' is not supported. - //simple_statement ::= declaration_statement; + simple_statement ::= declaration_statement; simple_statement ::= expression_statement; //simple_statement ::= selection_statement; //simple_statement ::= switch_statement; @@ -440,7 +556,7 @@ pomelo! { Function { name: Some(n.1), parameter_types: vec![], - return_type: t, + return_type: t.1, global_usage: vec![], local_variables: Arena::::new(), expressions: Arena::::new(), @@ -449,7 +565,6 @@ pomelo! { } // type - fully_specified_type ::= type_specifier; type_specifier ::= type_specifier_nonarray(t) { t.map(|t| { let name = t.name.clone(); @@ -505,6 +620,7 @@ pomelo! { extra.lookup_function.insert(name, handle); } } + external_declaration ::= declaration; function_definition ::= function_prototype(mut f) compound_statement_no_new_scope(cs) { std::mem::swap(&mut f.expressions, &mut extra.context.expressions); diff --git a/test-data/simple.vert b/test-data/simple.vert index 515cc82a5..761b17ed0 100644 --- a/test-data/simple.vert +++ b/test-data/simple.vert @@ -1,5 +1,7 @@ #version 450 core +layout(location = 0) in vec2 position; + void main() { - gl_Position = vec4(1.0); + gl_Position = vec4(position, 0.0, 1.0); } From ede04ba4dc4037904fa22f7051279a5aef14589f Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Fri, 7 Aug 2020 16:42:58 +0000 Subject: [PATCH 0129/2212] [glsl-new] Simplify declaration code - Fix clippy issues --- src/front/glsl_new/parser.rs | 43 ++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index ecf2e058c..3608eba77 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -153,7 +153,7 @@ pomelo! { // try global vars if let Some(global_var) = extra.lookup_global_variables.get(&v.1) { ExpressionRule{ - expression: extra.context.expressions.append(Expression::GlobalVariable(global_var.clone())), + expression: extra.context.expressions.append(Expression::GlobalVariable(*global_var)), statements: vec![], } } else { @@ -435,30 +435,25 @@ pomelo! { single_declaration ::= fully_specified_type; single_declaration ::= fully_specified_type(t) Identifier(i) { //TODO: global or local? For now always global - if let Some(ty) = t.1 { - if let Some(TypeQualifier::StorageClass(sc)) = t.0.iter().find(|tq| { - if let TypeQualifier::StorageClass(_) = tq { true } else { false } - }) { - let binding = t.0.iter().find_map(|tq| { - if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } - }); + let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; - let h = extra.global_variables.fetch_or_append( - GlobalVariable { - name: Some(i.1.clone()), - class: *sc, - binding: binding, - ty: ty, - }, - ); - extra.lookup_global_variables.insert(i.1, h); - - } else { - return Err(ErrorKind::SemanticError("Missing storage class for declaration")) - } - } else { - return Err(ErrorKind::SemanticError("Empty type for declaration")) - } + let class = t.0.iter().find_map(|tq| { + if let TypeQualifier::StorageClass(sc) = tq { Some(*sc) } else { None } + }).ok_or(ErrorKind::SemanticError("Missing storage class for declaration"))?; + + let binding = t.0.iter().find_map(|tq| { + if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } + }); + + let h = extra.global_variables.fetch_or_append( + GlobalVariable { + name: Some(i.1.clone()), + class, + binding, + ty, + }, + ); + extra.lookup_global_variables.insert(i.1, h); } fully_specified_type ::= type_specifier(t) {(vec![], t)} From 41c1c713dc32ae8d32d6fb67655bc1c7c5355d6e Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 10 Aug 2020 13:16:31 +0000 Subject: [PATCH 0130/2212] [glsl-new] handle global vars in external_decl --- src/front/glsl_new/ast.rs | 7 ++++ src/front/glsl_new/parser.rs | 70 +++++++++++++++++++++++++----------- 2 files changed, 56 insertions(+), 21 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index baee50c6a..7980b0ae7 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -61,3 +61,10 @@ pub enum TypeQualifier { StorageClass(StorageClass), Binding(Binding), } + +#[derive(Debug)] +pub struct VarDeclaration { + pub type_qualifiers: Vec, + pub ids_initializers: Vec<(String, Option)>, + pub ty: Handle, +} diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 3608eba77..79b489bc3 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -87,6 +87,9 @@ pomelo! { %type constant_expression Handle; // decalartions + %type declaration VarDeclaration; + %type init_declarator_list VarDeclaration; + %type single_declaration VarDeclaration; %type layout_qualifier Binding; %type layout_qualifier_id_list Binding; %type layout_qualifier_id Binding; @@ -430,30 +433,34 @@ pomelo! { } // declaration - declaration ::= init_declarator_list Semicolon; + declaration ::= init_declarator_list(idl) Semicolon {idl} + init_declarator_list ::= single_declaration; - single_declaration ::= fully_specified_type; - single_declaration ::= fully_specified_type(t) Identifier(i) { - //TODO: global or local? For now always global + init_declarator_list ::= init_declarator_list(mut idl) Comma Identifier(i) { + idl.ids_initializers.push((i.1, None)); + idl + } + // init_declarator_list ::= init_declarator_list Comma Identifier array_specifier; + // init_declarator_list ::= init_declarator_list Comma Identifier array_specifier Equal initializer; + // init_declarator_list ::= init_declarator_list Comma Identifier Equal initializer; + + single_declaration ::= fully_specified_type(t) { let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; - let class = t.0.iter().find_map(|tq| { - if let TypeQualifier::StorageClass(sc) = tq { Some(*sc) } else { None } - }).ok_or(ErrorKind::SemanticError("Missing storage class for declaration"))?; + VarDeclaration{ + type_qualifiers: t.0, + ids_initializers: vec![], + ty, + } + } + single_declaration ::= fully_specified_type(t) Identifier(i) { + let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; - let binding = t.0.iter().find_map(|tq| { - if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } - }); - - let h = extra.global_variables.fetch_or_append( - GlobalVariable { - name: Some(i.1.clone()), - class, - binding, - ty, - }, - ); - extra.lookup_global_variables.insert(i.1, h); + VarDeclaration{ + type_qualifiers: t.0, + ids_initializers: vec![(i.1, None)], + ty, + } } fully_specified_type ::= type_specifier(t) {(vec![], t)} @@ -509,6 +516,7 @@ pomelo! { declaration_statement ::= declaration { //TODO: Should declarations be able to genereate expression/statements? + //TODO: local vars Statement::Empty } @@ -615,7 +623,27 @@ pomelo! { extra.lookup_function.insert(name, handle); } } - external_declaration ::= declaration; + external_declaration ::= declaration(d) { + let class = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::StorageClass(sc) = tq { Some(*sc) } else { None } + }).ok_or(ErrorKind::SemanticError("Missing storage class for global var"))?; + + let binding = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } + }); + + for (id, initializer) in d.ids_initializers { + let h = extra.global_variables.fetch_or_append( + GlobalVariable { + name: Some(id.clone()), + class, + binding: binding.clone(), + ty: d.ty, + }, + ); + extra.lookup_global_variables.insert(id, h); + } + } function_definition ::= function_prototype(mut f) compound_statement_no_new_scope(cs) { std::mem::swap(&mut f.expressions, &mut extra.context.expressions); From b96b7449dbac1aa987952cb8b4256208c32ac648 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 10 Aug 2020 14:44:57 +0000 Subject: [PATCH 0131/2212] [gls-new] handle local vars --- src/front/glsl_new/ast.rs | 2 ++ src/front/glsl_new/lex.rs | 1 + src/front/glsl_new/parser.rs | 64 ++++++++++++++++++++++++++++++++---- test-data/simple.vert | 3 +- 4 files changed, 63 insertions(+), 7 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 7980b0ae7..3819ceb4f 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -34,6 +34,7 @@ impl Program { context: Context { expressions: Arena::::new(), local_variables: Arena::::new(), + lookup_local_variables: FastHashMap::default(), }, } } @@ -48,6 +49,7 @@ pub enum Profile { pub struct Context { pub expressions: Arena, pub local_variables: Arena, + pub lookup_local_variables: FastHashMap>, } #[derive(Debug)] diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 898236723..27c6e1ca8 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -115,6 +115,7 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { "out" => (Some(Token::Out(meta)), rest), // types "void" => (Some(Token::Void(meta)), rest), + "float" => (Some(Token::Float(meta)), rest), "vec2" => (Some(Token::Vec2(meta)), rest), "vec3" => (Some(Token::Vec3(meta)), rest), "vec4" => (Some(Token::Vec4(meta)), rest), diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 79b489bc3..6e4e592c8 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -86,6 +86,8 @@ pomelo! { %type expression ExpressionRule; %type constant_expression Handle; + %type initializer ExpressionRule; + // decalartions %type declaration VarDeclaration; %type init_declarator_list VarDeclaration; @@ -153,12 +155,17 @@ pomelo! { statements: vec![], } } else { - // try global vars + // try global and local vars if let Some(global_var) = extra.lookup_global_variables.get(&v.1) { ExpressionRule{ expression: extra.context.expressions.append(Expression::GlobalVariable(*global_var)), statements: vec![], } + } else if let Some(local_var) = extra.context.lookup_local_variables.get(&v.1) { + ExpressionRule{ + expression: extra.context.expressions.append(Expression::LocalVariable(*local_var)), + statements: vec![], + } } else { return Err(ErrorKind::UnknownVariable(v.0, v.1)) } @@ -442,7 +449,10 @@ pomelo! { } // init_declarator_list ::= init_declarator_list Comma Identifier array_specifier; // init_declarator_list ::= init_declarator_list Comma Identifier array_specifier Equal initializer; - // init_declarator_list ::= init_declarator_list Comma Identifier Equal initializer; + init_declarator_list ::= init_declarator_list(mut idl) Comma Identifier(i) Equal initializer(init) { + idl.ids_initializers.push((i.1, Some(init))); + idl + } single_declaration ::= fully_specified_type(t) { let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; @@ -462,6 +472,17 @@ pomelo! { ty, } } + // single_declaration ::= fully_specified_type Identifier array_specifier; + // single_declaration ::= fully_specified_type Identifier array_specifier Equal initializer; + single_declaration ::= fully_specified_type(t) Identifier(i) Equal initializer(init) { + let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; + + VarDeclaration{ + type_qualifiers: t.0, + ids_initializers: vec![(i.1, Some(init))], + ty, + } + } fully_specified_type ::= type_specifier(t) {(vec![], t)} fully_specified_type ::= type_qualifier(q) type_specifier(t) {(q,t)} @@ -513,11 +534,33 @@ pomelo! { storage_qualifier ::= Out {StorageClass::Output} //TODO: other storage qualifiers + initializer ::= assignment_expression; + // initializer ::= LeftBrace initializer_list RightBrace; + // initializer ::= LeftBrace initializer_list Comma RightBrace; - declaration_statement ::= declaration { - //TODO: Should declarations be able to genereate expression/statements? - //TODO: local vars - Statement::Empty + // initializer_list ::= initializer; + // initializer_list ::= initializer_list Comma initializer; + + declaration_statement ::= declaration(d) { + let mut statements = Vec::::new(); + // local variables + for (id, initializer) in d.ids_initializers { + let h = extra.context.local_variables.append( + LocalVariable { + name: Some(id.clone()), + ty: d.ty, + init: initializer.map(|i| { + statements.extend(i.statements); + i.expression + }), + } + ); + extra.context.lookup_local_variables.insert(id, h); + } + match statements.len() { + 1 => statements.remove(0), + _ => Statement::Block(statements), + } } // statement @@ -580,6 +623,15 @@ pomelo! { } type_specifier_nonarray ::= Void { None } + type_specifier_nonarray ::= Float { + Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 4, + } + }) + } type_specifier_nonarray ::= Vec2 { Some(Type { name: None, diff --git a/test-data/simple.vert b/test-data/simple.vert index 761b17ed0..3aa56b2e9 100644 --- a/test-data/simple.vert +++ b/test-data/simple.vert @@ -3,5 +3,6 @@ layout(location = 0) in vec2 position; void main() { - gl_Position = vec4(position, 0.0, 1.0); + float w = 1.0; + gl_Position = vec4(position, 0.0, w); } From a16204456e6195e35ef577d95bafa0824315904c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 11 Aug 2020 21:20:23 +0100 Subject: [PATCH 0132/2212] WIP: glsl 450 backend and common glsl module (#123) * Initial backend implementation * Refractored glsl450 backend to have a common module between further glsl backends Implemented more missing functionality * Error handling * Implemented most of the suggestions * Addresed all comments Fixed some bugs * Made code style consistent --- Cargo.toml | 1 + examples/convert.rs | 13 + src/back/glsl.rs | 923 ++++++++++++++++++++++++++++++++++++++++++++ src/back/mod.rs | 2 + 4 files changed, 939 insertions(+) create mode 100644 src/back/glsl.rs diff --git a/Cargo.toml b/Cargo.toml index 3884ba309..144d7c5b2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ thiserror = "1.0" default = [] glsl_preprocessor = ["glsl"] glsl-new = ["pomelo"] +glsl-out = [] [dev-dependencies] env_logger = "0.6" diff --git a/examples/convert.rs b/examples/convert.rs index 5658f5a31..4de017759 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -157,6 +157,19 @@ fn main() { fs::write(&args[2], bytes.as_slice()).unwrap(); } + #[cfg(feature = "glsl-out")] + "vert" | "frag" => { + use naga::back::glsl; + + let mut file = fs::OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(&args[2]) + .unwrap(); + + glsl::write(&module, &mut file).unwrap(); + } other => { panic!("Unknown output extension: {}", other); } diff --git a/src/back/glsl.rs b/src/back/glsl.rs new file mode 100644 index 000000000..25f2cc86c --- /dev/null +++ b/src/back/glsl.rs @@ -0,0 +1,923 @@ +use crate::{ + Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, + FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageFlags, IntrinsicFunction, + LocalVariable, Module, ScalarKind, Statement, StorageClass, Type, TypeInner, UnaryOperator, +}; +use std::{ + borrow::Cow, + fmt::{self, Error as FmtError, Write as FmtWrite}, + io::{Error as IoError, Write}, +}; + +#[derive(Debug)] +pub enum Error { + FormatError(FmtError), + IoError(IoError), + Custom(String), +} + +impl From for Error { + fn from(err: FmtError) -> Self { + Error::FormatError(err) + } +} + +impl From for Error { + fn from(err: IoError) -> Self { + Error::IoError(err) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::FormatError(err) => write!(f, "Formatting error {}", err), + Error::IoError(err) => write!(f, "Io error: {}", err), + Error::Custom(err) => write!(f, "{}", err), + } + } +} + +pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { + writeln!(out, "#version 450 core")?; + + let mut counter = 0; + let mut names = FastHashMap::default(); + + let mut namer = |name: Option<&String>| { + if let Some(name) = name { + names.insert(name.clone(), ()); + name.clone() + } else { + counter += 1; + while names.get(&format!("_{}", counter)).is_some() { + counter += 1; + } + format!("_{}", counter) + } + }; + + let mut structs = FastHashMap::default(); + + // Do a first pass to collect names + for (handle, ty) in module.types.iter() { + match ty.inner { + TypeInner::Struct { .. } => { + let name = namer(ty.name.as_ref()); + + structs.insert(handle, name); + } + _ => continue, + } + } + + // Do a second pass to build the structs + // TODO: glsl is order dependent so we need to build structs in order + for (handle, ty) in module.types.iter() { + match ty.inner { + TypeInner::Struct { ref members } => { + let name = structs.get(&handle).unwrap(); + + writeln!(out, "struct {} {{", name)?; + for (idx, member) in members.iter().enumerate() { + writeln!( + out, + " {} {};", + write_type(member.ty, &module.types, &structs)?, + member.name.clone().unwrap_or_else(|| idx.to_string()) + )?; + } + writeln!(out, "}};")?; + } + _ => continue, + } + } + + let mut globals_lookup = FastHashMap::default(); + + for (handle, global) in module.global_variables.iter() { + if let Some(crate::Binding::BuiltIn(built_in)) = global.binding { + let semantic = match built_in { + BuiltIn::Position => "gl_position", + BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", + BuiltIn::BaseInstance => "gl_BaseInstance", + BuiltIn::BaseVertex => "gl_BaseVertex", + BuiltIn::ClipDistance => "gl_ClipDistance", + BuiltIn::InstanceIndex => "gl_InstanceIndex", + BuiltIn::VertexIndex => "gl_VertexIndex", + BuiltIn::PointSize => "gl_PointSize", + BuiltIn::FragCoord => "gl_FragCoord", + BuiltIn::FrontFacing => "gl_FrontFacing", + BuiltIn::SampleIndex => "gl_SampleID", + BuiltIn::FragDepth => "gl_FragDepth", + BuiltIn::LocalInvocationId => "gl_LocalInvocationID", + BuiltIn::LocalInvocationIndex => "gl_LocalInvocationIndex", + BuiltIn::WorkGroupId => "gl_WorkGroupID", + }; + + globals_lookup.insert(handle, String::from(semantic)); + continue; + } + + if let Some(ref binding) = global.binding { + write!(out, "layout({}) ", Binding(binding.clone()))?; + } + + let name = namer(global.name.as_ref()); + + writeln!( + out, + "{}{} {};", + write_storage_class(global.class)?, + write_type(global.ty, &module.types, &structs)?, + name + )?; + + globals_lookup.insert(handle, name); + } + + let mut functions = FastHashMap::default(); + + // Do a first pass to collect names + for (handle, func) in module.functions.iter() { + functions.insert(handle, namer(func.name.as_ref())); + } + + // TODO: glsl is order dependent so we need to build functions in order + for (handle, func) in module.functions.iter() { + let name = functions.get(&handle).unwrap(); + + writeln!( + out, + "{} {}({}) {{", + func.return_type + .map_or(Ok(String::from("void")), |ty| write_type( + ty, + &module.types, + &structs + ))?, + name, + func.parameter_types + .iter() + .map(|ty| write_type(*ty, &module.types, &structs)) + .collect::, _>>()? + .join(","), + )?; + + let locals: FastHashMap<_, _> = func + .local_variables + .iter() + .map(|(handle, local)| (handle, namer(local.name.as_ref()))) + .collect(); + + for (handle, name) in locals.iter() { + writeln!( + out, + "{} {};", + write_type(func.local_variables[*handle].ty, &module.types, &structs)?, + name + )?; + } + + let mut builder = StatementBuilder { + functions: &functions, + globals: &globals_lookup, + locals_lookup: &locals, + structs: &structs, + args: &func + .parameter_types + .iter() + .enumerate() + .map(|(pos, ty)| (pos as u32, (namer(None), *ty))) + .collect(), + expressions: &func.expressions, + locals: &func.local_variables, + }; + + for sta in func.body.iter() { + writeln!(out, "{}", write_statement(sta, module, &mut builder)?)?; + } + + writeln!(out, "}}")?; + } + + Ok(()) +} + +struct Binding(crate::Binding); +impl fmt::Display for Binding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + crate::Binding::BuiltIn(_) => write!(f, ""), // Ignore because they are variables with a predefined name + crate::Binding::Location(location) => write!(f, "location={}", location), + crate::Binding::Descriptor { set, binding } => { + write!(f, "set={},binding={}", set, binding) + } + } + } +} + +struct StatementBuilder<'a> { + pub functions: &'a FastHashMap, String>, + pub globals: &'a FastHashMap, String>, + pub locals_lookup: &'a FastHashMap, String>, + pub structs: &'a FastHashMap, String>, + pub args: &'a FastHashMap)>, + pub expressions: &'a Arena, + pub locals: &'a Arena, +} + +fn write_statement( + sta: &Statement, + module: &Module, + builder: &mut StatementBuilder<'_>, +) -> Result { + Ok(match sta { + Statement::Empty => String::new(), + Statement::Block(block) => block + .iter() + .map(|sta| write_statement(sta, module, builder)) + .collect::, _>>()? + .join("\n"), + Statement::If { + condition, + accept, + reject, + } => { + let mut out = String::new(); + + writeln!( + &mut out, + "if({}) {{", + write_expression(&builder.expressions[*condition], module, builder)?.0 + )?; + for sta in accept { + writeln!(&mut out, "{}", write_statement(sta, module, builder)?)?; + } + writeln!(&mut out, "}} else {{")?; + for sta in reject { + writeln!(&mut out, "{}", write_statement(sta, module, builder)?)?; + } + write!(&mut out, "}}")?; + + out + } + Statement::Switch { + selector, + cases, + default, + } => { + let mut out = String::new(); + + writeln!( + &mut out, + "switch({}) {{", + write_expression(&builder.expressions[*selector], module, builder)?.0 + )?; + + for (label, (block, fallthrough)) in cases { + writeln!(&mut out, " case {}:", label)?; + + for sta in block { + writeln!(&mut out, " {}", write_statement(sta, module, builder)?)?; + } + + if fallthrough.is_some() { + writeln!(&mut out, " break;")?; + } + } + + writeln!(&mut out, " default:")?; + + for sta in default { + writeln!(&mut out, " {}", write_statement(sta, module, builder)?)?; + } + + write!(&mut out, "}}")?; + + out + } + Statement::Loop { body, continuing } => { + let mut out = String::new(); + + writeln!(&mut out, "while(true) {{",)?; + + for sta in body.iter().chain(continuing.iter()) { + writeln!(&mut out, " {}", write_statement(sta, module, builder)?)?; + } + + write!(&mut out, "}}")?; + + out + } + Statement::Break => String::from("break;"), + Statement::Continue => String::from("continue;"), + Statement::Return { value } => format!( + "return {};", + value.map_or::, _>(Ok(String::from("")), |expr| Ok( + write_expression(&builder.expressions[expr], module, builder)?.0 + ))? + ), + Statement::Kill => String::from("discard;"), + Statement::Store { pointer, value } => format!( + "{} = {};", + write_expression(&builder.expressions[*pointer], module, builder)?.0, + write_expression(&builder.expressions[*value], module, builder)?.0 + ), + }) +} + +fn write_expression<'a>( + expr: &Expression, + module: &'a Module, + builder: &mut StatementBuilder<'_>, +) -> Result<(String, Cow<'a, TypeInner>), Error> { + Ok(match expr { + Expression::Access { base, index } => { + let (base_expr, ty) = write_expression(&builder.expressions[*base], module, builder)?; + + let inner = match ty.as_ref() { + TypeInner::Vector { kind, width, .. } | TypeInner::Matrix { kind, width, .. } => { + Cow::Owned(TypeInner::Scalar { + kind: *kind, + width: *width, + }) + } + TypeInner::Array { base, .. } => Cow::Borrowed(&module.types[*base].inner), + _ => return Err(Error::Custom(format!("Cannot dynamically index {:?}", ty))), + }; + + ( + format!( + "{}[{}]", + base_expr, + write_expression(&builder.expressions[*index], module, builder)?.0 + ), + inner, + ) + } + Expression::AccessIndex { base, index } => { + let (base_expr, ty) = write_expression(&builder.expressions[*base], module, builder)?; + + match ty.as_ref() { + TypeInner::Vector { kind, width, .. } | TypeInner::Matrix { kind, width, .. } => ( + format!("{}[{}]", base_expr, index), + Cow::Owned(TypeInner::Scalar { + kind: *kind, + width: *width, + }), + ), + TypeInner::Array { base, .. } => ( + format!("{}[{}]", base_expr, index), + Cow::Borrowed(&module.types[*base].inner), + ), + TypeInner::Struct { members } => ( + format!( + "{}.{}", + base_expr, + members[*index as usize] + .name + .as_ref() + .unwrap_or(&index.to_string()) + ), + Cow::Borrowed(&module.types[members[*index as usize].ty].inner), + ), + _ => return Err(Error::Custom(format!("Cannot index {:?}", ty))), + } + } + Expression::Constant(constant) => ( + write_constant(&module.constants[*constant], module, builder)?, + Cow::Borrowed(&module.types[module.constants[*constant].ty].inner), + ), + Expression::Compose { ty, components } => { + let constructor = match module.types[*ty].inner { + TypeInner::Vector { size, kind, width } => format!( + "{}vec{}", + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => match width { + 4 => "", + 8 => "d", + _ => + return Err(Error::Custom(format!( + "Cannot build float of width {}", + width + ))), + }, + ScalarKind::Bool => "b", + }, + size as u8, + ), + TypeInner::Matrix { + columns, + rows, + kind, + width, + } => format!( + "{}mat{}x{}", + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => match width { + 4 => "", + 8 => "d", + _ => + return Err(Error::Custom(format!( + "Cannot build float of width {}", + width + ))), + }, + ScalarKind::Bool => "b", + }, + columns as u8, + rows as u8, + ), + TypeInner::Array { .. } => write_type(*ty, &module.types, builder.structs)?, + TypeInner::Struct { .. } => builder.structs.get(ty).unwrap().clone(), + _ => { + return Err(Error::Custom(format!( + "Cannot compose type {}", + write_type(*ty, &module.types, builder.structs)? + ))) + } + }; + + ( + format!( + "{}({})", + constructor, + components + .iter() + .map::, _>(|arg| Ok(write_expression( + &builder.expressions[*arg], + module, + builder + )? + .0)) + .collect::, _>>()? + .join(","), + ), + Cow::Borrowed(&module.types[*ty].inner), + ) + } + Expression::FunctionParameter(pos) => { + let (arg, ty) = builder.args.get(&pos).unwrap().clone(); + + (arg, Cow::Borrowed(&module.types[ty].inner)) + } + Expression::GlobalVariable(handle) => ( + builder.globals.get(&handle).unwrap().clone(), + Cow::Borrowed(&module.types[module.global_variables[*handle].ty].inner), + ), + Expression::LocalVariable(handle) => ( + builder.locals_lookup.get(&handle).unwrap().clone(), + Cow::Borrowed(&module.types[builder.locals[*handle].ty].inner), + ), + Expression::Load { pointer } => { + write_expression(&builder.expressions[*pointer], module, builder)? + } + Expression::ImageSample { + image, + sampler, + coordinate, + depth_ref, + } => { + let (image_expr, image_ty) = + write_expression(&builder.expressions[*image], module, builder)?; + let (sampler_expr, sampler_ty) = + write_expression(&builder.expressions[*sampler], module, builder)?; + let (coordinate_expr, coordinate_ty) = + write_expression(&builder.expressions[*coordinate], module, builder)?; + + let (kind, dim, arrayed, ms, width) = match image_ty.as_ref() { + TypeInner::Image { base, dim, flags } => match module.types[*base].inner { + TypeInner::Scalar { kind, width } => ( + kind, + *dim, + flags.contains(ImageFlags::ARRAYED), + flags.contains(ImageFlags::MULTISAMPLED), + width, + ), + _ => { + return Err(Error::Custom(format!( + "Cannot build image of {}", + write_type(*base, &module.types, builder.structs)? + ))) + } + }, + TypeInner::DepthImage { dim, arrayed } => { + (ScalarKind::Float, *dim, *arrayed, false, 4) + } + _ => return Err(Error::Custom(format!("Cannot sample {:?}", image_ty))), + }; + + let shadow = match sampler_ty.as_ref() { + TypeInner::Sampler { comparison } => *comparison, + _ => { + return Err(Error::Custom(format!( + "Cannot have a sampler of {:?}", + sampler_ty + ))) + } + }; + + let size = match coordinate_ty.as_ref() { + TypeInner::Vector { size, .. } => *size, + _ => { + return Err(Error::Custom(format!( + "Cannot sample with coordinates of type {:?}", + coordinate_ty + ))) + } + }; + + let sampler_constructor = format!( + "{}sampler{}{}{}{}({},{})", + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => "", + _ => return Err(Error::Custom(String::from("Cannot build image of bools",))), + }, + ImageDimension(dim), + if ms { "MS" } else { "" }, + if arrayed { "Array" } else { "" }, + if shadow { "Shadow" } else { "" }, + image_expr, + sampler_expr + ); + + let coordinate = if let Some(depth_ref) = depth_ref { + format!( + "vec{}({},{})", + size as u8 + 1, + coordinate_expr, + write_expression(&builder.expressions[*depth_ref], module, builder)?.0 + ) + } else { + coordinate_expr + }; + + let expr = if !ms { + format!("texture({},{})", sampler_constructor, coordinate) + } else { + todo!() + }; + + let ty = if shadow { + Cow::Owned(TypeInner::Scalar { kind, width }) + } else { + Cow::Owned(TypeInner::Vector { kind, width, size }) + }; + + (expr, ty) + } + Expression::Unary { op, expr } => { + let (expr, ty) = write_expression(&builder.expressions[*expr], module, builder)?; + + ( + format!( + "({} {})", + match op { + UnaryOperator::Negate => "-", + UnaryOperator::Not => "~", + }, + expr + ), + ty, + ) + } + Expression::Binary { op, left, right } => { + let (left_expr, left_ty) = + write_expression(&builder.expressions[*left], module, builder)?; + let (right_expr, right_ty) = + write_expression(&builder.expressions[*right], module, builder)?; + + let op = match op { + BinaryOperator::Add => "+", + BinaryOperator::Subtract => "-", + BinaryOperator::Multiply => "*", + BinaryOperator::Divide => "/", + BinaryOperator::Modulo => "%", + BinaryOperator::Equal => "==", + BinaryOperator::NotEqual => "!=", + BinaryOperator::Less => "<", + BinaryOperator::LessEqual => "<=", + BinaryOperator::Greater => ">", + BinaryOperator::GreaterEqual => ">=", + BinaryOperator::And => "&", + BinaryOperator::ExclusiveOr => "^", + BinaryOperator::InclusiveOr => "|", + BinaryOperator::LogicalAnd => "&&", + BinaryOperator::LogicalOr => "||", + BinaryOperator::ShiftLeftLogical => "<<", + BinaryOperator::ShiftRightLogical => todo!(), + BinaryOperator::ShiftRightArithmetic => ">>", + }; + + let ty = match (left_ty.as_ref(), right_ty.as_ref()) { + (TypeInner::Scalar { .. }, TypeInner::Scalar { .. }) => left_ty, + (TypeInner::Scalar { .. }, TypeInner::Vector { .. }) => right_ty, + (TypeInner::Scalar { .. }, TypeInner::Matrix { .. }) => right_ty, + (TypeInner::Vector { .. }, TypeInner::Scalar { .. }) => left_ty, + (TypeInner::Vector { .. }, TypeInner::Vector { .. }) => left_ty, + (TypeInner::Vector { .. }, TypeInner::Matrix { .. }) => left_ty, + (TypeInner::Matrix { .. }, TypeInner::Scalar { .. }) => left_ty, + (TypeInner::Matrix { .. }, TypeInner::Vector { .. }) => right_ty, + (TypeInner::Matrix { .. }, TypeInner::Matrix { .. }) => left_ty, + _ => { + return Err(Error::Custom(format!( + "Cannot apply {} to {} and {}", + op, left_expr, right_expr + ))) + } + }; + + (format!("({} {} {})", left_expr, op, right_expr), ty) + } + Expression::Intrinsic { fun, argument } => { + let (expr, ty) = write_expression(&builder.expressions[*argument], module, builder)?; + + ( + format!( + "{:?}({})", + match fun { + IntrinsicFunction::IsFinite => "!isinf", + IntrinsicFunction::IsInf => "isinf", + IntrinsicFunction::IsNan => "isnan", + IntrinsicFunction::IsNormal => "!isnan", + IntrinsicFunction::All => "all", + IntrinsicFunction::Any => "any", + }, + expr + ), + ty, + ) + } + Expression::DotProduct(left, right) => { + let (left_expr, left_ty) = + write_expression(&builder.expressions[*left], module, builder)?; + let (right_expr, _) = write_expression(&builder.expressions[*right], module, builder)?; + + let ty = match left_ty.as_ref() { + TypeInner::Vector { kind, width, .. } => Cow::Owned(TypeInner::Scalar { + kind: *kind, + width: *width, + }), + _ => { + return Err(Error::Custom(format!( + "Cannot apply dot product to {}", + left_expr + ))) + } + }; + + (format!("dot({},{})", left_expr, right_expr), ty) + } + Expression::CrossProduct(left, right) => { + let (left_expr, left_ty) = + write_expression(&builder.expressions[*left], module, builder)?; + let (right_expr, _) = write_expression(&builder.expressions[*right], module, builder)?; + + (format!("cross({},{})", left_expr, right_expr), left_ty) + } + Expression::Derivative { axis, expr } => { + let (expr, ty) = write_expression(&builder.expressions[*expr], module, builder)?; + + ( + format!( + "{}({})", + match axis { + DerivativeAxis::X => "dFdx", + DerivativeAxis::Y => "dFdy", + DerivativeAxis::Width => "fwidth", + }, + expr + ), + ty, + ) + } + Expression::Call { origin, arguments } => { + let ty = match origin { + FunctionOrigin::Local(function) => module.functions[*function] + .return_type + .map(|ty| Cow::Borrowed(&module.types[ty].inner)) + .unwrap_or(Cow::Owned( + TypeInner::Sampler { comparison: false }, /*Dummy type*/ + )), + FunctionOrigin::External(_) => { + write_expression(&builder.expressions[arguments[0]], module, builder)?.1 + } + }; + + ( + format!( + "{}({})", + match origin { + FunctionOrigin::External(name) => name, + FunctionOrigin::Local(handle) => builder.functions.get(&handle).unwrap(), + }, + arguments + .iter() + .map::, _>(|arg| Ok(write_expression( + &builder.expressions[*arg], + module, + builder + )? + .0)) + .collect::, _>>()? + .join(","), + ), + ty, + ) + } + }) +} + +fn write_constant( + constant: &Constant, + module: &Module, + builder: &StatementBuilder<'_>, +) -> Result { + Ok(match constant.inner { + ConstantInner::Sint(int) => int.to_string(), + ConstantInner::Uint(int) => int.to_string(), + ConstantInner::Float(float) => format!("{:?}", float), + ConstantInner::Bool(boolean) => boolean.to_string(), + ConstantInner::Composite(ref components) => format!( + "{}({})", + match module.types[constant.ty].inner { + TypeInner::Vector { size, .. } => format!("vec{}", size as u8,), + TypeInner::Matrix { columns, rows, .. } => + format!("mat{}x{}", columns as u8, rows as u8,), + TypeInner::Struct { .. } => builder.structs.get(&constant.ty).unwrap().clone(), + TypeInner::Array { .. } => write_type(constant.ty, &module.types, builder.structs)?, + _ => + return Err(Error::Custom(format!( + "Cannot build constant of type {}", + write_type(constant.ty, &module.types, builder.structs)? + ))), + }, + components + .iter() + .map(|component| write_constant(&module.constants[*component], module, builder)) + .collect::, _>>()? + .join(","), + ), + }) +} + +fn write_type<'a>( + ty: Handle, + types: &'a Arena, + structs: &'a FastHashMap, String>, +) -> Result { + Ok(match types[ty].inner { + TypeInner::Scalar { kind, width } => match kind { + ScalarKind::Sint => String::from("int"), + ScalarKind::Uint => String::from("uint"), + ScalarKind::Float => match width { + 4 => String::from("float"), + 8 => String::from("double"), + _ => { + return Err(Error::Custom(format!( + "Cannot build float of width {}", + width + ))) + } + }, + ScalarKind::Bool => String::from("bool"), + }, + TypeInner::Vector { size, kind, width } => format!( + "{}vec{}", + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => match width { + 4 => "", + 8 => "d", + _ => + return Err(Error::Custom(format!( + "Cannot build float of width {}", + width + ))), + }, + ScalarKind::Bool => "b", + }, + size as u8 + ), + TypeInner::Matrix { + columns, + rows, + kind, + width, + } => format!( + "{}mat{}x{}", + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => match width { + 4 => "", + 8 => "d", + _ => + return Err(Error::Custom(format!( + "Cannot build float of width {}", + width + ))), + }, + ScalarKind::Bool => "b", + }, + columns as u8, + rows as u8 + ), + TypeInner::Pointer { base, .. } => write_type(base, types, structs)?, + TypeInner::Array { base, size, .. } => format!( + "{}[{}]", + write_type(base, types, structs)?, + write_array_size(size)? + ), + TypeInner::Struct { .. } => structs.get(&ty).unwrap().clone(), + TypeInner::Image { base, dim, flags } => format!( + "{}texture{}{}", + match types[base].inner { + TypeInner::Scalar { kind, .. } => match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => "", + _ => + return Err(Error::Custom(String::from( + "Cannot build image of booleans", + ))), + }, + _ => + return Err(Error::Custom(format!( + "Cannot build image of type {}", + write_type(base, types, structs)? + ))), + }, + ImageDimension(dim), + write_image_flags(flags)? + ), + TypeInner::DepthImage { dim, arrayed } => format!( + "texture{}{}", + ImageDimension(dim), + if arrayed { "Array" } else { "" } + ), + TypeInner::Sampler { comparison } => String::from(if comparison { + "sampler" + } else { + "samplerShadow" + }), + }) +} + +fn write_storage_class(class: StorageClass) -> Result { + Ok(String::from(match class { + StorageClass::Constant => "const ", + StorageClass::Function => "", + StorageClass::Input => "in ", + StorageClass::Output => "out ", + StorageClass::Private => "", + StorageClass::StorageBuffer => "buffer ", + StorageClass::Uniform => "uniform ", + StorageClass::WorkGroup => "shared ", + })) +} + +fn write_array_size(size: ArraySize) -> Result { + Ok(match size { + ArraySize::Static(size) => size.to_string(), + ArraySize::Dynamic => String::from(""), + }) +} + +fn write_image_flags(flags: ImageFlags) -> Result { + let mut out = String::new(); + + if flags.contains(ImageFlags::MULTISAMPLED) { + write!(out, "MS")?; + } + + if flags.contains(ImageFlags::ARRAYED) { + write!(out, "Array")?; + } + + Ok(out) +} + +struct ImageDimension(crate::ImageDimension); +impl fmt::Display for ImageDimension { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + match self.0 { + crate::ImageDimension::D1 => "1D", + crate::ImageDimension::D2 => "2D", + crate::ImageDimension::D3 => "3D", + crate::ImageDimension::Cube => "Cube", + } + ) + } +} diff --git a/src/back/mod.rs b/src/back/mod.rs index ce751b11e..11439f934 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -1,5 +1,7 @@ //! Functions which export shader modules into binary and text formats. +#[cfg(feature = "glsl-out")] +pub mod glsl; pub mod msl; #[cfg(feature = "spirv")] pub mod spv; From 466cd1b7283dc9734400e933799e74bd896a4d74 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Thu, 13 Aug 2020 12:27:10 -0400 Subject: [PATCH 0133/2212] Serialize and Deserialize Module (#125) * Add serialize and deserialize features with examples * Fix formatting * Make some types (de)serialize transparently * Fix more formatting * Remove new examples and add (de)serialization support to the convert example * Remove extraneous file * Rename param file --- Cargo.toml | 5 +- examples/convert.rs | 12 ++++- src/arena.rs | 13 +++++ src/lib.rs | 65 ++++++++++++++++++++++++ test-data/{boids.ron => boids.param.ron} | 0 5 files changed, 93 insertions(+), 2 deletions(-) rename test-data/{boids.ron => boids.param.ron} (100%) diff --git a/Cargo.toml b/Cargo.toml index 144d7c5b2..509d3cf37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,14 +18,17 @@ spirv = { package = "spirv_headers", version = "1.4.2", optional = true } glsl = { version = "4.1", optional = true } pomelo = { version = "0.1.4", optional = true } thiserror = "1.0" +serde = { version = "1.0", features = ["derive"], optional = true } [features] default = [] glsl_preprocessor = ["glsl"] glsl-new = ["pomelo"] glsl-out = [] +serialize = ["serde"] +deserialize = ["serde"] [dev-dependencies] env_logger = "0.6" ron = "0.5" -serde = { version = "1", features = ["serde_derive"] } +serde = { version = "1.0", features = ["derive"] } \ No newline at end of file diff --git a/examples/convert.rs b/examples/convert.rs index 4de017759..d36bef330 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -91,6 +91,11 @@ fn main() { naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Compute) .unwrap() } + #[cfg(feature = "deserialize")] + "ron" => { + let mut input = fs::File::open(&args[1]).unwrap(); + ron::de::from_reader(&mut input).unwrap() + } other => panic!("Unknown input extension: {}", other), }; @@ -99,7 +104,7 @@ fn main() { return; } - let param_path = std::path::PathBuf::from(&args[1]).with_extension("ron"); + let param_path = std::path::PathBuf::from(&args[1]).with_extension("param.ron"); let params = match fs::read_to_string(param_path) { Ok(string) => ron::de::from_str(&string).unwrap(), Err(_) => Parameters::default(), @@ -170,6 +175,11 @@ fn main() { glsl::write(&module, &mut file).unwrap(); } + #[cfg(feature = "serialize")] + "ron" => { + let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); + fs::write(&args[2], output).unwrap(); + } other => { panic!("Unknown output extension: {}", other); } diff --git a/src/arena.rs b/src/arena.rs index 9751beff5..3d7304644 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -9,8 +9,15 @@ use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32}; type Index = NonZeroU32; /// A strongly typed reference to a SPIR-V element. +#[cfg_attr(feature = "serialize", derive(crate::Serialize))] +#[cfg_attr(feature = "deserialize", derive(crate::Deserialize))] +#[cfg_attr( + any(feature = "serialize", feature = "deserialize"), + serde(transparent) +)] pub struct Handle { index: Index, + #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))] marker: PhantomData, } @@ -78,6 +85,12 @@ impl Handle { /// The arena can be indexed using the given handle to obtain /// a reference to the stored item. #[derive(Debug)] +#[cfg_attr(feature = "serialize", derive(crate::Serialize))] +#[cfg_attr(feature = "deserialize", derive(crate::Deserialize))] +#[cfg_attr( + any(feature = "serialize", feature = "deserialize"), + serde(transparent) +)] pub struct Arena { /// Values of this arena. data: Vec, diff --git a/src/lib.rs b/src/lib.rs index be0873ffc..1f58819ec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,6 +20,11 @@ use std::{ num::NonZeroU32, }; +#[cfg(feature = "deserialize")] +use serde::Deserialize; +#[cfg(feature = "serialize")] +use serde::Serialize; + /// Hash map that is faster but not resilient to DoS attacks. pub type FastHashMap = HashMap>; /// Hash set that is faster but not resilient to DoS attacks. @@ -27,6 +32,8 @@ pub type FastHashSet = HashSet>; /// Metadata for a given module. #[derive(Clone, Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct Header { /// Major, minor and patch version. /// @@ -40,6 +47,8 @@ pub struct Header { /// Stage of the programmable pipeline. #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] #[allow(missing_docs)] // The names are self evident pub enum ShaderStage { Vertex, @@ -49,6 +58,8 @@ pub enum ShaderStage { /// Class of storage for variables. #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] #[allow(missing_docs)] // The names are self evident pub enum StorageClass { Constant, @@ -63,6 +74,8 @@ pub enum StorageClass { /// Built-in inputs and outputs. #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum BuiltIn { // vertex BaseInstance, @@ -90,6 +103,8 @@ pub type Bytes = u8; /// Number of components in a vector. #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum VectorSize { /// 2D vector Bi = 2, @@ -102,6 +117,8 @@ pub enum VectorSize { /// Primitive type for a scalar. #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ScalarKind { /// Signed integer type. Sint, @@ -116,6 +133,8 @@ pub enum ScalarKind { /// Size of an array. #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ArraySize { /// The array size is known at compilation. Static(u32), @@ -125,6 +144,8 @@ pub enum ArraySize { /// Describes where a struct member is placed. #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum MemberOrigin { /// Built-in shader variable. BuiltIn(BuiltIn), @@ -135,6 +156,8 @@ pub enum MemberOrigin { /// Member of a user-defined structure. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct StructMember { pub name: Option, pub origin: MemberOrigin, @@ -143,6 +166,8 @@ pub struct StructMember { /// The number of dimensions an image has. #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ImageDimension { /// 1D image D1, @@ -156,6 +181,8 @@ pub enum ImageDimension { bitflags::bitflags! { /// Flags describing an image. + #[cfg_attr(feature = "serialize", derive(Serialize))] + #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct ImageFlags: u32 { /// Image is an array. const ARRAYED = 0x1; @@ -172,6 +199,8 @@ bitflags::bitflags! { /// A data type declared in the module. #[derive(Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct Type { /// The name of the type, if any. pub name: Option, @@ -182,6 +211,8 @@ pub struct Type { /// Enum with additional information, depending on the kind of type. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum TypeInner { /// Number of integral or floating-point kind. Scalar { kind: ScalarKind, width: Bytes }, @@ -225,6 +256,8 @@ pub enum TypeInner { /// Constant value. #[derive(Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct Constant { pub name: Option, pub specialization: Option, @@ -235,6 +268,8 @@ pub struct Constant { /// Additional information, dependendent on the kind of constant. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ConstantInner { Sint(i64), Uint(u64), @@ -245,6 +280,8 @@ pub enum ConstantInner { /// Describes how an input/output variable is to be bound. #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Binding { /// Built-in shader variable. BuiltIn(BuiltIn), @@ -256,6 +293,8 @@ pub enum Binding { bitflags::bitflags! { /// Indicates how a global variable is used. + #[cfg_attr(feature = "serialize", derive(Serialize))] + #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct GlobalUse: u8 { /// Data will be read from the variable. const LOAD = 0x1; @@ -266,6 +305,8 @@ bitflags::bitflags! { /// Variable defined at module level. #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct GlobalVariable { /// Name of the variable, if any. pub name: Option, @@ -279,6 +320,8 @@ pub struct GlobalVariable { /// Variable defined at function level. #[derive(Clone, Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct LocalVariable { /// Name of the variable, if any. pub name: Option, @@ -290,6 +333,8 @@ pub struct LocalVariable { /// Operation that can be applied on a single value. #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum UnaryOperator { Negate, Not, @@ -297,6 +342,8 @@ pub enum UnaryOperator { /// Operation that can be applied on two values. #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum BinaryOperator { Add, Subtract, @@ -321,6 +368,8 @@ pub enum BinaryOperator { /// Built-in shader function. #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum IntrinsicFunction { Any, All, @@ -332,6 +381,8 @@ pub enum IntrinsicFunction { /// Axis on which to compute a derivative. #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum DerivativeAxis { X, Y, @@ -340,6 +391,8 @@ pub enum DerivativeAxis { /// Origin of a function to call. #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum FunctionOrigin { Local(Handle), External(String), @@ -347,6 +400,8 @@ pub enum FunctionOrigin { /// An expression that can be evaluated to obtain a value. #[derive(Clone, Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Expression { /// Array access with a computed index. Access { @@ -419,11 +474,15 @@ pub type Block = Vec; /// Marker type, used for falling through in a switch statement. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct FallThrough; /// Instructions which make up an executable block. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Statement { /// Empty statement, does nothing. Empty, @@ -461,6 +520,8 @@ pub enum Statement { /// A function defined in the module. #[derive(Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct Function { /// Name of the function, if any. pub name: Option, @@ -483,6 +544,8 @@ pub struct Function { /// Exported function, to be run at a certain stage in the pipeline. #[derive(Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct EntryPoint { /// The stage in the programmable pipeline this entry point is for. pub stage: ShaderStage, @@ -504,6 +567,8 @@ pub struct EntryPoint { /// /// When finished, you can export modules using one of the [available back ends][back]. #[derive(Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct Module { /// Header containing module metadata. pub header: Header, diff --git a/test-data/boids.ron b/test-data/boids.param.ron similarity index 100% rename from test-data/boids.ron rename to test-data/boids.param.ron From b4e1775b9e3551ae95d9bb9f6d01312bd1347390 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 13 Aug 2020 21:36:51 +0200 Subject: [PATCH 0134/2212] [glsl-new] Handle local vars scopes (#126) * [glsl-new] Handle local vars scopes * [glsl-new] scope fixes - Check loacl vars before globals - Rename add_scope > push_scope - Remove unnecessary ref in lookup functions --- src/front/glsl_new/ast.rs | 45 ++++++++++++++++++++++++++++++++++-- src/front/glsl_new/error.rs | 4 ++++ src/front/glsl_new/parser.rs | 41 +++++++++++++++++++++----------- 3 files changed, 74 insertions(+), 16 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 3819ceb4f..594df535c 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -34,7 +34,7 @@ impl Program { context: Context { expressions: Arena::::new(), local_variables: Arena::::new(), - lookup_local_variables: FastHashMap::default(), + scopes: vec![FastHashMap::default()], }, } } @@ -49,7 +49,48 @@ pub enum Profile { pub struct Context { pub expressions: Arena, pub local_variables: Arena, - pub lookup_local_variables: FastHashMap>, + //TODO: Find less allocation heavy representation + pub scopes: Vec>>, +} + +impl Context { + pub fn lookup_local_var(&self, name: &str) -> Option> { + for scope in self.scopes.iter().rev() { + if let Some(var) = scope.get(name) { + return Some(*var); + } + } + None + } + + pub fn lookup_local_var_current_scope(&self, name: &str) -> Option> { + if let Some(current) = self.scopes.last() { + current.get(name).cloned() + } else { + None + } + } + + pub fn clear_scopes(&mut self) { + self.scopes.clear(); + self.scopes.push(FastHashMap::default()); + } + + /// Add variable to current scope + pub fn add_local_var(&mut self, name: String, handle: Handle) { + if let Some(current) = self.scopes.last_mut() { + (*current).insert(name, handle); + } + } + + /// Add new empty scope + pub fn push_scope(&mut self) { + self.scopes.push(FastHashMap::default()); + } + + pub fn remove_current_scope(&mut self) { + self.scopes.pop(); + } } #[derive(Debug)] diff --git a/src/front/glsl_new/error.rs b/src/front/glsl_new/error.rs index 726eee1c8..75a76a249 100644 --- a/src/front/glsl_new/error.rs +++ b/src/front/glsl_new/error.rs @@ -14,6 +14,7 @@ pub enum ErrorKind { ParserStackOverflow, NotImplemented(&'static str), UnknownVariable(TokenMetadata, String), + VariableAlreadyDeclared(String), ExpectedConstant, SemanticError(&'static str), } @@ -37,6 +38,9 @@ impl fmt::Display for ErrorKind { ErrorKind::UnknownVariable(meta, val) => { write!(f, "Unknown variable {} at {:?}", val, meta) } + ErrorKind::VariableAlreadyDeclared(val) => { + write!(f, "Variable {} already decalred in current scope", val) + } ErrorKind::ExpectedConstant => write!(f, "Expected constant"), ErrorKind::SemanticError(msg) => write!(f, "Semantic error: {}", msg), } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 6e4e592c8..ec8edcd3e 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -156,18 +156,17 @@ pomelo! { } } else { // try global and local vars - if let Some(global_var) = extra.lookup_global_variables.get(&v.1) { - ExpressionRule{ - expression: extra.context.expressions.append(Expression::GlobalVariable(*global_var)), - statements: vec![], - } - } else if let Some(local_var) = extra.context.lookup_local_variables.get(&v.1) { - ExpressionRule{ - expression: extra.context.expressions.append(Expression::LocalVariable(*local_var)), - statements: vec![], - } - } else { - return Err(ErrorKind::UnknownVariable(v.0, v.1)) + let expr = + if let Some(local_var) = extra.context.lookup_local_var(&v.1) { + Expression::LocalVariable(local_var) + } else if let Some(global_var) = extra.lookup_global_variables.get(&v.1) { + Expression::GlobalVariable(*global_var) + } else { + return Err(ErrorKind::UnknownVariable(v.0, v.1)) + }; + ExpressionRule{ + expression: extra.context.expressions.append(expr), + statements: vec![], } } } @@ -545,6 +544,10 @@ pomelo! { let mut statements = Vec::::new(); // local variables for (id, initializer) in d.ids_initializers { + // check if already declared in current scope + if extra.context.lookup_local_var_current_scope(&id).is_some() { + return Err(ErrorKind::VariableAlreadyDeclared(id)) + } let h = extra.context.local_variables.append( LocalVariable { name: Some(id.clone()), @@ -555,7 +558,7 @@ pomelo! { }), } ); - extra.context.lookup_local_variables.insert(id, h); + extra.context.add_local_var(id, h); } match statements.len() { 1 => statements.remove(0), @@ -577,7 +580,16 @@ pomelo! { //simple_statement ::= jump_statement; compound_statement ::= LeftBrace RightBrace {vec![]} - compound_statement ::= LeftBrace statement_list(sl) RightBrace {sl} + compound_statement ::= left_brace_scope statement_list(sl) RightBrace { + extra.context.remove_current_scope(); + sl + } + + // extra rule to add scope before statement_list + left_brace_scope ::= LeftBrace { + extra.context.push_scope(); + } + compound_statement_no_new_scope ::= LeftBrace RightBrace {vec![]} compound_statement_no_new_scope ::= LeftBrace statement_list(sl) RightBrace {sl} @@ -700,6 +712,7 @@ pomelo! { function_definition ::= function_prototype(mut f) compound_statement_no_new_scope(cs) { std::mem::swap(&mut f.expressions, &mut extra.context.expressions); std::mem::swap(&mut f.local_variables, &mut extra.context.local_variables); + extra.context.clear_scopes(); f.body = cs; f }; From 7f780e8efcdfe475d8bd57d9d77edeedab8ecc39 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 13 Aug 2020 22:27:12 +0200 Subject: [PATCH 0135/2212] [glsl-new] put validation errors behind featureUsing glsl-validate feature (#127) --- Cargo.toml | 1 + src/front/glsl_new/ast.rs | 1 + src/front/glsl_new/error.rs | 2 ++ src/front/glsl_new/parser.rs | 1 + 4 files changed, 5 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 509d3cf37..49fbe26b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ serde = { version = "1.0", features = ["derive"], optional = true } default = [] glsl_preprocessor = ["glsl"] glsl-new = ["pomelo"] +glsl-validate = [] glsl-out = [] serialize = ["serde"] deserialize = ["serde"] diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 594df535c..d36b427b0 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -63,6 +63,7 @@ impl Context { None } + #[cfg(feature = "glsl-validate")] pub fn lookup_local_var_current_scope(&self, name: &str) -> Option> { if let Some(current) = self.scopes.last() { current.get(name).cloned() diff --git a/src/front/glsl_new/error.rs b/src/front/glsl_new/error.rs index 75a76a249..859fb06e2 100644 --- a/src/front/glsl_new/error.rs +++ b/src/front/glsl_new/error.rs @@ -14,6 +14,7 @@ pub enum ErrorKind { ParserStackOverflow, NotImplemented(&'static str), UnknownVariable(TokenMetadata, String), + #[cfg(feature = "glsl-validate")] VariableAlreadyDeclared(String), ExpectedConstant, SemanticError(&'static str), @@ -38,6 +39,7 @@ impl fmt::Display for ErrorKind { ErrorKind::UnknownVariable(meta, val) => { write!(f, "Unknown variable {} at {:?}", val, meta) } + #[cfg(feature = "glsl-validate")] ErrorKind::VariableAlreadyDeclared(val) => { write!(f, "Variable {} already decalred in current scope", val) } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index ec8edcd3e..af99a6803 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -545,6 +545,7 @@ pomelo! { // local variables for (id, initializer) in d.ids_initializers { // check if already declared in current scope + #[cfg(feature = "glsl-validate")] if extra.context.lookup_local_var_current_scope(&id).is_some() { return Err(ErrorKind::VariableAlreadyDeclared(id)) } From fccefaccde249cd7c7e7df96c225b52ad1fa9f29 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Sat, 15 Aug 2020 01:46:10 -0400 Subject: [PATCH 0136/2212] Add support for initialization of local variables to glsl backend (#129) * Add support for initialization of local variables to glsl backend * Cleanup --- src/back/glsl.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 25f2cc86c..042a0991e 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -170,15 +170,6 @@ pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { .map(|(handle, local)| (handle, namer(local.name.as_ref()))) .collect(); - for (handle, name) in locals.iter() { - writeln!( - out, - "{} {};", - write_type(func.local_variables[*handle].ty, &module.types, &structs)?, - name - )?; - } - let mut builder = StatementBuilder { functions: &functions, globals: &globals_lookup, @@ -194,6 +185,22 @@ pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { locals: &func.local_variables, }; + for (handle, name) in locals.iter() { + let ty = write_type(func.local_variables[*handle].ty, &module.types, &structs)?; + let init = func.local_variables[*handle].init; + if let Some(init) = init { + writeln!( + out, + "{} {} = {init};", + ty, + name, + init = write_expression(&func.expressions[init], &module, &mut builder)?.0, + )?; + } else { + writeln!(out, "{} {};", ty, name,)?; + } + } + for sta in func.body.iter() { writeln!(out, "{}", write_statement(sta, module, &mut builder)?)?; } From 7902bd54a854ce498cd57518994386cbb6152190 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Sun, 16 Aug 2020 15:38:07 +0200 Subject: [PATCH 0137/2212] [glsl-new] Fix expression ordering for compose (#130) --- src/front/glsl_new/ast.rs | 13 +++++++ src/front/glsl_new/parser.rs | 71 ++++++++++++++++++++---------------- 2 files changed, 53 insertions(+), 31 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index d36b427b0..8f082c520 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -112,3 +112,16 @@ pub struct VarDeclaration { pub ids_initializers: Vec<(String, Option)>, pub ty: Handle, } + +#[derive(Debug)] +pub enum FunctionCallKind { + TypeConstructor(Handle), + Function(Handle), +} + +#[derive(Debug)] +pub struct FunctionCall { + pub kind: FunctionCallKind, + pub args: Vec>, + pub statements: Vec, +} diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index af99a6803..1de9d4e1a 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -61,12 +61,13 @@ pomelo! { %type primary_expression ExpressionRule; %type variable_identifier ExpressionRule; - %type function_call Handle; - %type function_call_generic Handle; - %type function_call_header_no_parameters Handle; - %type function_call_header_with_parameters Handle; - %type function_call_header Handle; - %type function_identifier Handle; + %type function_call ExpressionRule; + %type function_call_or_method FunctionCall; + %type function_call_generic FunctionCall; + %type function_call_header_no_parameters FunctionCall; + %type function_call_header_with_parameters FunctionCall; + %type function_call_header FunctionCall; + %type function_identifier FunctionCallKind; %type multiplicative_expression Handle; %type additive_expression Handle; @@ -220,12 +221,7 @@ pomelo! { // TODO return Err(ErrorKind::NotImplemented("[]")) } - postfix_expression ::= function_call(f) { - ExpressionRule{ - expression: f, - statements: vec![], - } - } + postfix_expression ::= function_call; postfix_expression ::= postfix_expression Dot FieldSelection { // TODO return Err(ErrorKind::NotImplemented(".field")) @@ -241,43 +237,56 @@ pomelo! { integer_expression ::= expression; - function_call ::= function_call_generic; + function_call ::= function_call_or_method(fc) { + if let FunctionCallKind::TypeConstructor(ty) = fc.kind { + let h = extra.context.expressions.append(Expression::Compose{ + ty, + components: fc.args, + }); + ExpressionRule{ + expression: h, + statements: fc.statements, + } + } else { + return Err(ErrorKind::NotImplemented("Function call")); + } + } + function_call_or_method ::= function_call_generic; function_call_generic ::= function_call_header_with_parameters(h) RightParen {h} function_call_generic ::= function_call_header_no_parameters(h) RightParen {h} function_call_header_no_parameters ::= function_call_header(h) Void {h} function_call_header_no_parameters ::= function_call_header; - function_call_header_with_parameters ::= function_call_header(h) assignment_expression(ae) { - if let Expression::Compose{ty, components} = extra.context.expressions.get_mut(h) { - components.push(ae.expression); - //TODO: ae.statements - } - //TODO: Call + function_call_header_with_parameters ::= function_call_header(mut h) assignment_expression(ae) { + h.args.push(ae.expression); + h.statements.extend(ae.statements); h } - function_call_header_with_parameters ::= function_call_header_with_parameters(h) Comma assignment_expression(ae) { - if let Expression::Compose{ty, components} = extra.context.expressions.get_mut(h) { - components.push(ae.expression); - //TODO: ae.statements - } - //TODO: Call + function_call_header_with_parameters ::= function_call_header_with_parameters(mut h) Comma assignment_expression(ae) { + h.args.push(ae.expression); + h.statements.extend(ae.statements); h } - function_call_header ::= function_identifier(i) LeftParen {i} + function_call_header ::= function_identifier(i) LeftParen { + FunctionCall { + kind: i, + args: vec![], + statements: vec![], + } + } // Grammar Note: Constructors look like functions, but lexical analysis recognized most of them as // keywords. They are now recognized through “type_specifier”. // Methods (.length), subroutine array calls, and identifiers are recognized through postfix_expression. function_identifier ::= type_specifier(t) { if let Some(ty) = t { - extra.context.expressions.append(Expression::Compose{ - ty, - components: vec![], - }) + FunctionCallKind::TypeConstructor(ty) } else { return Err(ErrorKind::NotImplemented("bad type ctor")) } } - function_identifier ::= postfix_expression(e) {e.expression} + function_identifier ::= postfix_expression(e) { + FunctionCallKind::Function(e.expression) + } unary_expression ::= postfix_expression; From 50cd2b1bc212ae6650c3b7474c3fac646d1b79ab Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 16 Aug 2020 23:49:48 -0400 Subject: [PATCH 0138/2212] Bump version to 0.2, add changelog --- CHANGELOG.md | 7 +++++++ Cargo.toml | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..614c76834 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Change Log + +## v0.2 (2020-08-17) + - development release for wgpu-0.6 + +## v0.1 (2020-02-26) + - initial release diff --git a/Cargo.toml b/Cargo.toml index 49fbe26b5..ee33f41c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.1.0" +version = "0.2.0" authors = ["Dzmitry Malyshau "] edition = "2018" description = "Shader translation infrastructure" @@ -32,4 +32,4 @@ deserialize = ["serde"] [dev-dependencies] env_logger = "0.6" ron = "0.5" -serde = { version = "1.0", features = ["derive"] } \ No newline at end of file +serde = { version = "1.0", features = ["derive"] } From 34cf97cb9177eb248693d024d54790601e7f071b Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 17 Aug 2020 15:37:11 +0200 Subject: [PATCH 0139/2212] [glsl-new] disable constant expression (#131) --- src/front/glsl_new/parser.rs | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 1de9d4e1a..015301cf2 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -439,13 +439,14 @@ pomelo! { } } - constant_expression ::= conditional_expression(e) { - if let Expression::Constant(h) = extra.context.expressions[e] { - h - } else { - return Err(ErrorKind::ExpectedConstant) - } - } + //TODO: properly handle constant expressions + // constant_expression ::= conditional_expression(e) { + // if let Expression::Constant(h) = extra.context.expressions[e] { + // h + // } else { + // return Err(ErrorKind::ExpectedConstant) + // } + // } // declaration declaration ::= init_declarator_list(idl) Semicolon {idl} @@ -502,13 +503,10 @@ pomelo! { l } // layout_qualifier_id ::= Identifier; - layout_qualifier_id ::= Identifier(i) Equal constant_expression(c) { + //TODO: handle full constant_expression instead of IntConstant + layout_qualifier_id ::= Identifier(i) Equal IntConstant(ic) { if i.1.as_str() == "location" { - if let ConstantInner::Sint(loc) = extra.constants[c].inner { - Binding::Location(loc as u32) - } else { - return Err(ErrorKind::NotImplemented("location not Sint")); - } + Binding::Location(ic.1 as u32) } else { return Err(ErrorKind::NotImplemented("non location layout qualifier")); } From 4677b74928ba8b85ce31074983f1a45612031948 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Mon, 17 Aug 2020 13:35:18 -0400 Subject: [PATCH 0140/2212] Add more scalar and vector types to glsl-new (#133) * Add more scalar and vector types to glsl-new * Formatting --- src/front/glsl_new/lex.rs | 15 ++++ src/front/glsl_new/parser.rs | 165 ++++++++++++++++++++++++++++++++++- 2 files changed, 178 insertions(+), 2 deletions(-) diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 27c6e1ca8..1b1410995 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -116,9 +116,24 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { // types "void" => (Some(Token::Void(meta)), rest), "float" => (Some(Token::Float(meta)), rest), + "double" => (Some(Token::Double(meta)), rest), + "int" => (Some(Token::Int(meta)), rest), + "uint" => (Some(Token::Uint(meta)), rest), "vec2" => (Some(Token::Vec2(meta)), rest), + "bvec2" => (Some(Token::Bvec2(meta)), rest), + "ivec2" => (Some(Token::Ivec2(meta)), rest), + "uvec2" => (Some(Token::Uvec2(meta)), rest), + "dvec2" => (Some(Token::Dvec2(meta)), rest), "vec3" => (Some(Token::Vec3(meta)), rest), + "bvec3" => (Some(Token::Bvec3(meta)), rest), + "ivec3" => (Some(Token::Ivec3(meta)), rest), + "uvec3" => (Some(Token::Uvec3(meta)), rest), + "dvec3" => (Some(Token::Dvec3(meta)), rest), "vec4" => (Some(Token::Vec4(meta)), rest), + "bvec4" => (Some(Token::Bvec4(meta)), rest), + "ivec4" => (Some(Token::Ivec4(meta)), rest), + "uvec4" => (Some(Token::Uvec4(meta)), rest), + "dvec4" => (Some(Token::Dvec4(meta)), rest), //TODO: remaining types _ => (Some(Token::Identifier((meta, String::from(word)))), rest), } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 015301cf2..dc1164657 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -643,6 +643,16 @@ pomelo! { } type_specifier_nonarray ::= Void { None } + // Scalars + type_specifier_nonarray ::= Bool { + Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Bool, + width: 4, // https://stackoverflow.com/questions/9419781/what-is-the-size-of-glsl-boolean + } + }) + } type_specifier_nonarray ::= Float { Some(Type { name: None, @@ -652,6 +662,34 @@ pomelo! { } }) } + type_specifier_nonarray ::= Double { + Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 8, + } + }) + } + type_specifier_nonarray ::= Int { + Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + } + }) + } + type_specifier_nonarray ::= Uint { + Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + } + }) + } + // Vectors (2) type_specifier_nonarray ::= Vec2 { Some(Type { name: None, @@ -662,26 +700,149 @@ pomelo! { } }) } + type_specifier_nonarray ::= Bvec2 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Bool, + width: 4, + } + }) + } + type_specifier_nonarray ::= Ivec2 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Sint, + width: 4, + } + }) + } + type_specifier_nonarray ::= Uvec2 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Uint, + width: 4, + } + }) + } + type_specifier_nonarray ::= Dvec2 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Float, + width: 8, + } + }) + } + // Vectors (3) type_specifier_nonarray ::= Vec3 { Some(Type { name: None, inner: TypeInner::Vector { - size: VectorSize::Tri, + size: VectorSize::Bi, kind: ScalarKind::Float, width: 4, } }) } + type_specifier_nonarray ::= Bvec3 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Bool, + width: 4, + } + }) + } + type_specifier_nonarray ::= Ivec3 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Sint, + width: 4, + } + }) + } + type_specifier_nonarray ::= Uvec3 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Uint, + width: 4, + } + }) + } + type_specifier_nonarray ::= Dvec3 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Float, + width: 8, + } + }) + } + // Vectors (4) type_specifier_nonarray ::= Vec4 { Some(Type { name: None, inner: TypeInner::Vector { - size: VectorSize::Quad, + size: VectorSize::Bi, kind: ScalarKind::Float, width: 4, } }) } + type_specifier_nonarray ::= Bvec4 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Bool, + width: 4, + } + }) + } + type_specifier_nonarray ::= Ivec4 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Sint, + width: 4, + } + }) + } + type_specifier_nonarray ::= Uvec4 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Uint, + width: 4, + } + }) + } + type_specifier_nonarray ::= Dvec4 { + Some(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Float, + width: 8, + } + }) + } + //TODO: remaining types // misc From b03e874646431d67a3afd64b3a4b880de152ca9d Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Mon, 17 Aug 2020 15:35:05 -0400 Subject: [PATCH 0141/2212] Make type handling more generic in glsl-new (#134) * Make type handling more generic in glsl-new * Remove commented-out code --- src/front/glsl_new/lex.rs | 77 +++++++++++++---- src/front/glsl_new/parser.rs | 159 +++-------------------------------- 2 files changed, 74 insertions(+), 162 deletions(-) diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 1b1410995..e26252b68 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -119,23 +119,66 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { "double" => (Some(Token::Double(meta)), rest), "int" => (Some(Token::Int(meta)), rest), "uint" => (Some(Token::Uint(meta)), rest), - "vec2" => (Some(Token::Vec2(meta)), rest), - "bvec2" => (Some(Token::Bvec2(meta)), rest), - "ivec2" => (Some(Token::Ivec2(meta)), rest), - "uvec2" => (Some(Token::Uvec2(meta)), rest), - "dvec2" => (Some(Token::Dvec2(meta)), rest), - "vec3" => (Some(Token::Vec3(meta)), rest), - "bvec3" => (Some(Token::Bvec3(meta)), rest), - "ivec3" => (Some(Token::Ivec3(meta)), rest), - "uvec3" => (Some(Token::Uvec3(meta)), rest), - "dvec3" => (Some(Token::Dvec3(meta)), rest), - "vec4" => (Some(Token::Vec4(meta)), rest), - "bvec4" => (Some(Token::Bvec4(meta)), rest), - "ivec4" => (Some(Token::Ivec4(meta)), rest), - "uvec4" => (Some(Token::Uvec4(meta)), rest), - "dvec4" => (Some(Token::Dvec4(meta)), rest), - //TODO: remaining types - _ => (Some(Token::Identifier((meta, String::from(word)))), rest), + word => { + use crate::{ScalarKind, VectorSize}; + + fn kind_width_parse(ty: &str) -> Option<(ScalarKind, u8)> { + Some(match ty { + "" => (ScalarKind::Float, 4), + "b" => (ScalarKind::Bool, 4), + "i" => (ScalarKind::Sint, 4), + "u" => (ScalarKind::Uint, 4), + "d" => (ScalarKind::Float, 8), + _ => return None, + }) + } + + fn size_parse(n: &str) -> Option { + Some(match n { + "2" => VectorSize::Bi, + "3" => VectorSize::Tri, + "4" => VectorSize::Quad, + _ => return None, + }) + } + + let vec_parse = |word: &str| { + let mut iter = word.split("vec"); + + let kind = iter.next()?; + let size = iter.next()?; + let (kind, width) = kind_width_parse(kind)?; + let size = size_parse(size)?; + + Some(Token::Vec((meta.clone(), (size, kind, width)))) + }; + + let mat_parse = |word: &str| { + let mut iter = word.split("mat"); + + let kind = iter.next()?; + let size = iter.next()?; + let (kind, width) = kind_width_parse(kind)?; + + let (col, row) = if let Some(size) = size_parse(size) { + (size, size) + } else { + let mut iter = size.split('x'); + match (iter.next()?, iter.next()?, iter.next()) { + (col, row, None) => (size_parse(col)?, size_parse(row)?), + _ => return None, + } + }; + + Some(Token::Mat((meta.clone(), (col, row, kind, width)))) + }; + + let token = vec_parse(word) + .or_else(|| mat_parse(word)) + .unwrap_or_else(|| Token::Identifier((meta, String::from(word)))); + + (Some(token), rest) + } } } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index dc1164657..91db0cd3b 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -8,7 +8,7 @@ pomelo! { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{Arena, BinaryOperator, Binding, Block, BuiltIn, Constant, ConstantInner, Expression, Function, GlobalVariable, Handle, LocalVariable, ScalarKind, - ShaderStage, Statement, StorageClass, Type, TypeInner, VectorSize}; + ShaderStage, Statement, StorageClass, Type, TypeInner, VectorSize, Bytes}; } %token #[derive(Debug)] pub enum Token {}; %parser pub struct Parser<'a> {}; @@ -105,6 +105,9 @@ pomelo! { %type type_specifier Option>; %type type_specifier_nonarray Option; + %type Vec (VectorSize, ScalarKind, Bytes); + %type Mat (VectorSize, VectorSize, ScalarKind, Bytes); + root ::= version_pragma translation_unit; version_pragma ::= Version IntConstant(V) Identifier?(P) { @@ -689,161 +692,27 @@ pomelo! { } }) } - // Vectors (2) - type_specifier_nonarray ::= Vec2 { + type_specifier_nonarray ::= Vec((_, (size, kind, width))) { Some(Type { name: None, inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 4, + size, + kind, + width, } }) } - type_specifier_nonarray ::= Bvec2 { + type_specifier_nonarray ::= Mat((_, (columns, rows, kind, width))) { Some(Type { name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Bool, - width: 4, + inner: TypeInner::Matrix { + columns, + rows, + kind, + width, } }) } - type_specifier_nonarray ::= Ivec2 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Sint, - width: 4, - } - }) - } - type_specifier_nonarray ::= Uvec2 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Uint, - width: 4, - } - }) - } - type_specifier_nonarray ::= Dvec2 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 8, - } - }) - } - // Vectors (3) - type_specifier_nonarray ::= Vec3 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 4, - } - }) - } - type_specifier_nonarray ::= Bvec3 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Bool, - width: 4, - } - }) - } - type_specifier_nonarray ::= Ivec3 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Sint, - width: 4, - } - }) - } - type_specifier_nonarray ::= Uvec3 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Uint, - width: 4, - } - }) - } - type_specifier_nonarray ::= Dvec3 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 8, - } - }) - } - // Vectors (4) - type_specifier_nonarray ::= Vec4 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 4, - } - }) - } - type_specifier_nonarray ::= Bvec4 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Bool, - width: 4, - } - }) - } - type_specifier_nonarray ::= Ivec4 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Sint, - width: 4, - } - }) - } - type_specifier_nonarray ::= Uvec4 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Uint, - width: 4, - } - }) - } - type_specifier_nonarray ::= Dvec4 { - Some(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 8, - } - }) - } - - //TODO: remaining types // misc translation_unit ::= external_declaration; From 58dd54f938f66a22a96a792c070a3dcadc84bfef Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Tue, 18 Aug 2020 00:16:31 +0200 Subject: [PATCH 0142/2212] [spirv-out] Refactor lookup (#88) --- src/back/spv/writer.rs | 555 +++++++++++++++++++---------------------- src/lib.rs | 4 +- 2 files changed, 259 insertions(+), 300 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 107bfbda3..cb194919f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,45 +1,37 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ use super::{helpers, Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; -use crate::{FastHashMap, FastHashSet, ImageFlags, VectorSize}; +use crate::{Bytes, FastHashMap, FastHashSet, ImageFlags, VectorSize}; use spirv::{Op, Word}; +use std::collections::hash_map::Entry; -const BITS_PER_BYTE: u8 = 8; +const BITS_PER_BYTE: Bytes = 8; enum Signedness { Unsigned = 0, Signed = 1, } -trait LookupHelper { - type Target; - fn lookup_id(&self, handle: crate::Handle) -> Option; - fn lookup_handle(&self, word: Word) -> Option>; +#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] +enum LocalType { + Scalar { + kind: crate::ScalarKind, + width: Bytes, + }, + Vector { + size: crate::VectorSize, + kind: crate::ScalarKind, + width: Bytes, + }, + Pointer { + base: crate::Handle, + class: spirv::StorageClass, + }, } -impl LookupHelper for FastHashMap> { - type Target = T; - - fn lookup_id(&self, handle: crate::Handle) -> Option { - let mut word = None; - for (k, v) in self.iter() { - if *v == handle { - word = Some(*k); - break; - } - } - word - } - - fn lookup_handle(&self, word: u32) -> Option> { - let mut handle = None; - for (k, v) in self.iter() { - if *k == word { - handle = Some(*v); - break; - } - } - handle - } +#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] +enum LookupType { + Handle(crate::Handle), + Local(LocalType), } fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { @@ -51,7 +43,7 @@ fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { } } -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Clone, Hash, Eq)] struct LookupFunctionType { parameter_type_ids: Vec, return_type_id: Word, @@ -66,11 +58,11 @@ pub struct Writer { annotations: Vec, writer_flags: WriterFlags, void_type: Option, - lookup_type: FastHashMap>, - lookup_function: FastHashMap>, - lookup_function_type: FastHashMap, - lookup_constant: FastHashMap>, - lookup_global_variable: FastHashMap>, + lookup_type: FastHashMap, + lookup_function: FastHashMap, Word>, + lookup_function_type: FastHashMap, + lookup_constant: FastHashMap, Word>, + lookup_global_variable: FastHashMap, Word>, } impl Writer { @@ -103,17 +95,13 @@ impl Writer { } } - fn get_type_id( - &mut self, - arena: &crate::Arena, - handle: crate::Handle, - ) -> Word { - match self.lookup_type.lookup_id(handle) { - Some(word) => word, - None => { - let (instruction, id) = self.parse_type_declaration(arena, handle); - instruction.to_words(&mut self.logical_layout.declarations); - id + fn get_type_id(&mut self, arena: &crate::Arena, lookup_ty: LookupType) -> Word { + if let Entry::Occupied(e) = self.lookup_type.entry(lookup_ty) { + *e.get() + } else { + match lookup_ty { + LookupType::Handle(handle) => self.write_type_declaration_arena(arena, handle), + LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty), } } } @@ -123,10 +111,10 @@ impl Writer { handle: crate::Handle, ir_module: &crate::Module, ) -> Word { - match self.lookup_constant.lookup_id(handle) { - Some(word) => word, - None => { - let (instruction, id) = self.parse_constant_type(handle, ir_module); + match self.lookup_constant.entry(handle) { + Entry::Occupied(e) => *e.get(), + _ => { + let (instruction, id) = self.write_constant_type(handle, ir_module); instruction.to_words(&mut self.logical_layout.declarations); id } @@ -139,11 +127,11 @@ impl Writer { global_arena: &crate::Arena, handle: crate::Handle, ) -> Word { - match self.lookup_global_variable.lookup_id(handle) { - Some(word) => word, - None => { + match self.lookup_global_variable.entry(handle) { + Entry::Occupied(e) => *e.get(), + _ => { let global_variable = &global_arena[handle]; - let (instruction, id) = self.parse_global_variable(arena, global_variable, handle); + let (instruction, id) = self.write_global_variable(arena, global_variable, handle); instruction.to_words(&mut self.logical_layout.declarations); id } @@ -156,7 +144,7 @@ impl Writer { arena: &crate::Arena, ) -> Word { match ty { - Some(handle) => self.get_type_id(arena, handle), + Some(handle) => self.get_type_id(arena, LookupType::Handle(handle)), None => match self.void_type { Some(id) => id, None => { @@ -177,47 +165,33 @@ impl Writer { class: spirv::StorageClass, ) -> Word { let ty = &arena[handle]; - let type_id = self.get_type_id(arena, handle); + let ty_id = self.get_type_id(arena, LookupType::Handle(handle)); match ty.inner { - crate::TypeInner::Pointer { .. } => type_id, + crate::TypeInner::Pointer { .. } => ty_id, _ => { - let pointer_id = self.generate_id(); - let instruction = self.instruction_type_pointer(pointer_id, class, type_id); - instruction.to_words(&mut self.logical_layout.declarations); - - /* TODO - Not able to lookup Pointer, because there is no Handle in the IR for it. - Idea would be to not have any handles at all in the lookups, so we aren't bound - to the IR. We can then insert, like here runtime values to the lookups - */ - // self.lookup_type.insert(pointer_id, global_variable.ty); - pointer_id - } - } - } - - fn find_scalar_handle( - &self, - arena: &crate::Arena, - kind: crate::ScalarKind, - width: u8, - ) -> crate::Handle { - let mut scalar_handle = None; - for (handle, ty) in arena.iter() { - match ty.inner { - crate::TypeInner::Scalar { - kind: lookup_kind, - width: lookup_width, - } => { - if kind == lookup_kind && width == lookup_width { - scalar_handle = Some(handle); - break; + match self + .lookup_type + .entry(LookupType::Local(LocalType::Pointer { + base: handle, + class, + })) { + Entry::Occupied(e) => *e.get(), + _ => { + let pointer_id = self.generate_id(); + let instruction = self.instruction_type_pointer(pointer_id, class, ty_id); + instruction.to_words(&mut self.logical_layout.declarations); + self.lookup_type.insert( + LookupType::Local(LocalType::Pointer { + base: handle, + class, + }), + pointer_id, + ); + pointer_id } } - _ => continue, } } - scalar_handle.unwrap() } /// @@ -293,10 +267,8 @@ impl Writer { ir_module: &crate::Module, ) -> Instruction { let mut instruction = Instruction::new(Op::EntryPoint); - let function_id = self - .lookup_function - .lookup_id(entry_point.function) - .unwrap(); + + let function_id = *self.lookup_function.get(&entry_point.function).unwrap(); let exec_model = match entry_point.stage { crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, @@ -732,41 +704,71 @@ impl Writer { /// Primitive Instructions /// - fn parse_type_declaration( + fn write_scalar(&self, id: Word, kind: crate::ScalarKind, width: Bytes) -> Instruction { + let bits = (width * BITS_PER_BYTE) as u32; + match kind { + crate::ScalarKind::Sint => self.instruction_type_int(id, bits, Signedness::Signed), + crate::ScalarKind::Uint => self.instruction_type_int(id, bits, Signedness::Unsigned), + crate::ScalarKind::Float => self.instruction_type_float(id, bits), + crate::ScalarKind::Bool => self.instruction_type_bool(id), + } + } + + fn parse_to_spirv_storage_class(&self, class: crate::StorageClass) -> spirv::StorageClass { + match class { + crate::StorageClass::Constant => spirv::StorageClass::UniformConstant, + crate::StorageClass::Function => spirv::StorageClass::Function, + crate::StorageClass::Input => spirv::StorageClass::Input, + crate::StorageClass::Output => spirv::StorageClass::Output, + crate::StorageClass::Private => spirv::StorageClass::Private, + crate::StorageClass::StorageBuffer => spirv::StorageClass::StorageBuffer, + crate::StorageClass::Uniform => spirv::StorageClass::Uniform, + crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, + } + } + + fn write_type_declaration_local( + &mut self, + arena: &crate::Arena, + local_ty: LocalType, + ) -> Word { + let id = self.generate_id(); + let instruction = match local_ty { + LocalType::Scalar { kind, width } => self.write_scalar(id, kind, width), + LocalType::Vector { size, .. } => { + let scalar_id = self.get_type_id(arena, LookupType::Local(local_ty)); + self.instruction_type_vector(id, scalar_id, size) + } + LocalType::Pointer { .. } => unimplemented!(), + }; + + self.lookup_type.insert(LookupType::Local(local_ty), id); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + + fn write_type_declaration_arena( &mut self, arena: &crate::Arena, handle: crate::Handle, - ) -> (Instruction, Word) { + ) -> Word { let ty = &arena[handle]; let id = self.generate_id(); - let instruction; - - match ty.inner { + let instruction = match ty.inner { crate::TypeInner::Scalar { kind, width } => { - instruction = match kind { - crate::ScalarKind::Sint => self.instruction_type_int( - id, - (width * BITS_PER_BYTE) as u32, - Signedness::Signed, - ), - crate::ScalarKind::Uint => self.instruction_type_int( - id, - (width * BITS_PER_BYTE) as u32, - Signedness::Unsigned, - ), - crate::ScalarKind::Float => { - self.instruction_type_float(id, (width * BITS_PER_BYTE) as u32) - } - crate::ScalarKind::Bool => self.instruction_type_bool(id), - }; - self.lookup_type.insert(id, handle); + self.lookup_type + .insert(LookupType::Local(LocalType::Scalar { kind, width }), id); + self.write_scalar(id, kind, width) } crate::TypeInner::Vector { size, kind, width } => { - let scalar_handle = self.find_scalar_handle(arena, kind, width); - let scalar_id = self.get_type_id(arena, scalar_handle); - instruction = self.instruction_type_vector(id, scalar_id, size); - self.lookup_type.insert(id, handle); + let scalar_id = + self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width })); + self.lookup_type.insert( + LookupType::Local(LocalType::Vector { size, kind, width }), + id, + ); + self.instruction_type_vector(id, scalar_id, size) } crate::TypeInner::Matrix { columns, @@ -774,19 +776,21 @@ impl Writer { kind, width, } => { - let scalar_handle = self.find_scalar_handle(arena, kind, width); - let scalar_id = self.get_type_id(arena, scalar_handle); - - instruction = self.instruction_type_matrix(id, scalar_id, columns); - self.lookup_type.insert(id, handle); + let vector_id = self.get_type_id( + arena, + LookupType::Local(LocalType::Vector { + size: columns, + kind, + width, + }), + ); + self.instruction_type_matrix(id, vector_id, columns) } crate::TypeInner::Image { base, dim, flags } => { - let type_id = self.get_type_id(arena, base); + let type_id = self.get_type_id(arena, LookupType::Handle(base)); let dim = map_dim(dim); self.try_add_capabilities(dim.required_capabilities()); - - instruction = self.instruction_type_image(id, type_id, dim, flags, false); - self.lookup_type.insert(id, base); + self.instruction_type_image(id, type_id, dim, flags, false) } crate::TypeInner::DepthImage { dim, arrayed } => { let type_id = 0; //TODO! @@ -798,14 +802,10 @@ impl Writer { } else { crate::ImageFlags::empty() }; - instruction = self.instruction_type_image(id, type_id, dim, flags, true); - //self.lookup_type.insert(id, base); + self.instruction_type_image(id, type_id, dim, flags, true) } - crate::TypeInner::Sampler { comparison: _ } => { - instruction = self.instruction_type_sampler(id); - self.lookup_type.insert(id, handle); - } - crate::TypeInner::Array { base, size, stride } => { + crate::TypeInner::Sampler { comparison: _ } => self.instruction_type_sampler(id), + crate::TypeInner::Array { size, stride, .. } => { if let Some(array_stride) = stride { self.annotations.push(self.instruction_decorate( id, @@ -814,59 +814,54 @@ impl Writer { )); } - let type_id = self.get_type_id(arena, handle); - instruction = match size { + let type_id = self.get_type_id(arena, LookupType::Handle(handle)); + match size { crate::ArraySize::Static(length) => { self.instruction_type_array(id, type_id, length) } crate::ArraySize::Dynamic => self.instruction_type_runtime_array(id, type_id), - }; - - self.lookup_type.insert(id, base); + } } crate::TypeInner::Struct { ref members } => { let mut member_ids = Vec::with_capacity(members.len()); for member in members { - let member_id = self.get_type_id(arena, member.ty); + let member_id = self.get_type_id(arena, LookupType::Handle(member.ty)); member_ids.push(member_id); } - instruction = self.instruction_type_struct(id, member_ids); - self.lookup_type.insert(id, handle); + self.instruction_type_struct(id, member_ids) } crate::TypeInner::Pointer { base, class } => { - let type_id = self.get_type_id(arena, base); - let storage_class = match class { - crate::StorageClass::Constant => spirv::StorageClass::UniformConstant, - crate::StorageClass::Function => spirv::StorageClass::Function, - crate::StorageClass::Input => spirv::StorageClass::Input, - crate::StorageClass::Output => spirv::StorageClass::Output, - crate::StorageClass::Private => spirv::StorageClass::Private, - crate::StorageClass::StorageBuffer => spirv::StorageClass::StorageBuffer, - crate::StorageClass::Uniform => spirv::StorageClass::Uniform, - crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, - }; - instruction = self.instruction_type_pointer(id, storage_class, type_id); - self.lookup_type.insert(id, handle); + let type_id = self.get_type_id(arena, LookupType::Handle(base)); + self.lookup_type.insert( + LookupType::Local(LocalType::Pointer { + base, + class: self.parse_to_spirv_storage_class(class), + }), + id, + ); + self.instruction_type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) } }; - (instruction, id) + self.lookup_type.insert(LookupType::Handle(handle), id); + instruction.to_words(&mut self.logical_layout.declarations); + id } - fn parse_constant_type( + fn write_constant_type( &mut self, handle: crate::Handle, ir_module: &crate::Module, ) -> (Instruction, Word) { let id = self.generate_id(); - self.lookup_constant.insert(id, handle); + self.lookup_constant.insert(handle, id); let constant = &ir_module.constants[handle]; let arena = &ir_module.types; match constant.inner { crate::ConstantInner::Sint(val) => { let ty = &ir_module.types[constant.ty]; - let type_id = self.get_type_id(arena, constant.ty); + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { @@ -883,7 +878,7 @@ impl Writer { } crate::ConstantInner::Uint(val) => { let ty = &ir_module.types[constant.ty]; - let type_id = self.get_type_id(arena, constant.ty); + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { @@ -901,7 +896,7 @@ impl Writer { } crate::ConstantInner::Float(val) => { let ty = &ir_module.types[constant.ty]; - let type_id = self.get_type_id(arena, constant.ty); + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { @@ -918,7 +913,7 @@ impl Writer { (instruction, id) } crate::ConstantInner::Bool(val) => { - let type_id = self.get_type_id(arena, constant.ty); + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); let instruction = if val { self.instruction_constant_true(type_id, id) @@ -935,14 +930,14 @@ impl Writer { constituent_ids.push(constituent_id); } - let type_id = self.get_type_id(arena, constant.ty); + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); let instruction = self.instruction_constant_composite(type_id, id, constituent_ids); (instruction, id) } } } - fn parse_global_variable( + fn write_global_variable( &mut self, arena: &crate::Arena, global_variable: &crate::GlobalVariable, @@ -950,16 +945,7 @@ impl Writer { ) -> (Instruction, Word) { let id = self.generate_id(); - let class = match global_variable.class { - crate::StorageClass::Constant => spirv::StorageClass::UniformConstant, - crate::StorageClass::Function => spirv::StorageClass::Function, - crate::StorageClass::Input => spirv::StorageClass::Input, - crate::StorageClass::Output => spirv::StorageClass::Output, - crate::StorageClass::Private => spirv::StorageClass::Private, - crate::StorageClass::StorageBuffer => spirv::StorageClass::StorageBuffer, - crate::StorageClass::Uniform => spirv::StorageClass::Uniform, - crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, - }; + let class = self.parse_to_spirv_storage_class(global_variable.class); self.try_add_capabilities(class.required_capabilities()); let pointer_id = self.get_pointer_id(arena, global_variable.ty, class); @@ -1019,36 +1005,31 @@ impl Writer { // TODO Initializer is optional and not (yet) included in the IR - self.lookup_global_variable.insert(id, handle); + self.lookup_global_variable.insert(handle, id); (instruction, id) } - fn parse_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { - let mut id = None; - - for (k, v) in self.lookup_function_type.iter() { - if v.eq(&lookup_function_type) { - id = Some(*k); - break; + fn write_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { + match self + .lookup_function_type + .entry(lookup_function_type.clone()) + { + Entry::Occupied(e) => *e.get(), + _ => { + let id = self.generate_id(); + let instruction = self.instruction_type_function( + id, + lookup_function_type.return_type_id, + lookup_function_type.parameter_type_ids.clone(), + ); + instruction.to_words(&mut self.logical_layout.declarations); + self.lookup_function_type.insert(lookup_function_type, id); + id } } - - if id.is_none() { - let _id = self.generate_id(); - id = Some(_id); - let instruction = self.instruction_type_function( - _id, - lookup_function_type.return_type_id, - lookup_function_type.parameter_type_ids.clone(), - ); - instruction.to_words(&mut self.logical_layout.declarations); - self.lookup_function_type.insert(_id, lookup_function_type); - } - - id.unwrap() } - fn parse_function( + fn write_function( &mut self, handle: crate::Handle, function: &crate::Function, @@ -1060,7 +1041,7 @@ impl Writer { let mut parameter_type_ids = Vec::with_capacity(function.parameter_types.len()); for parameter_type in function.parameter_types.iter() { - parameter_type_ids.push(self.get_type_id(arena, *parameter_type)) + parameter_type_ids.push(self.get_type_id(arena, LookupType::Handle(*parameter_type))) } let lookup_function_type = LookupFunctionType { @@ -1068,7 +1049,7 @@ impl Writer { parameter_type_ids, }; - let type_function_id = self.parse_function_type(lookup_function_type); + let type_function_id = self.write_function_type(lookup_function_type); let instruction = self.instruction_function( return_type_id, @@ -1077,11 +1058,11 @@ impl Writer { type_function_id, ); - self.lookup_function.insert(id, handle); + self.lookup_function.insert(handle, id); instruction } - fn parse_expression<'a>( + fn write_expression<'a>( &mut self, ir_module: &'a crate::Module, function: &crate::Function, @@ -1109,13 +1090,13 @@ impl Writer { let var = &ir_module.types[*ty]; let inner = &var.inner; let id = self.generate_id(); - let type_id = self.get_type_id(&ir_module.types, *ty); + let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*ty)); let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { let expression = &function.expressions[*component]; let (component_id, _) = - self.parse_expression(ir_module, &function, expression, output); + self.write_expression(ir_module, &function, expression, output); constituent_ids.push(component_id); } @@ -1133,78 +1114,56 @@ impl Writer { let left_expression = &function.expressions[*left]; let right_expression = &function.expressions[*right]; let (left_id, left_inner) = - self.parse_expression(ir_module, function, left_expression, output); + self.write_expression(ir_module, function, left_expression, output); let (right_id, right_inner) = - self.parse_expression(ir_module, function, right_expression, output); + self.write_expression(ir_module, function, right_expression, output); - let mut result_type_id = None; - let mut vector_id = None; - let mut scalar_id = None; + let (result_type_id, vector_id, scalar_id) = match (left_inner, right_inner) + { + ( + crate::TypeInner::Vector { size, kind, width }, + crate::TypeInner::Scalar { .. }, + ) => { + let result_type_id = *self + .lookup_type + .get(&LookupType::Local(LocalType::Vector { + size: *size, + kind: *kind, + width: *width, + })) + .unwrap(); - match left_inner { - crate::TypeInner::Vector { size, kind, width } => { - vector_id = Some(left_id); - for (k, v) in self.lookup_type.iter() { - let ty = &ir_module.types[*v]; - match ty.inner { - crate::TypeInner::Vector { - size: _size, - kind: _kind, - width: _width, - } => { - if size == &_size && kind == &_kind && width == &_width - { - result_type_id = Some(*k); - break; - } - } - _ => continue, - } - } + (result_type_id, left_id, right_id) } - _ => scalar_id = Some(left_id), - } - - match right_inner { - crate::TypeInner::Vector { size, kind, width } => { - vector_id = Some(right_id); - for (k, v) in self.lookup_type.iter() { - let ty = &ir_module.types[*v]; - match ty.inner { - crate::TypeInner::Vector { - size: _size, - kind: _kind, - width: _width, - } => { - if size == &_size && kind == &_kind && width == &_width - { - result_type_id = Some(*k); - break; - } - } - _ => continue, - } - } + ( + crate::TypeInner::Scalar { .. }, + crate::TypeInner::Vector { size, kind, width }, + ) => { + let result_type_id = *self + .lookup_type + .get(&LookupType::Local(LocalType::Vector { + size: *size, + kind: *kind, + width: *width, + })) + .unwrap(); + (result_type_id, right_id, left_id) } - _ => scalar_id = Some(right_id), - } + _ => unreachable!("Expression requires both a scalar and vector"), + }; // TODO Quick fix let load_id = self.generate_id(); - let load_instruction = self.instruction_load( - result_type_id.unwrap(), - load_id, - vector_id.unwrap(), - None, - ); + let load_instruction = + self.instruction_load(result_type_id, load_id, vector_id, None); output.push(load_instruction); let instruction = self.instruction_vector_times_scalar( - result_type_id.unwrap(), + result_type_id, id, load_id, - scalar_id.unwrap(), + scalar_id, ); output.push(instruction); @@ -1237,7 +1196,7 @@ impl Writer { } } - fn parse_function_block( + fn write_function_block( &mut self, ir_module: &crate::Module, function: &crate::Function, @@ -1247,7 +1206,7 @@ impl Writer { match statement { crate::Statement::Return { .. } => match function.return_type { Some(ty) => { - let value_id = self.get_type_id(&ir_module.types, ty); + let value_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty)); self.instruction_return_value(value_id) } None => self.instruction_return(), @@ -1256,9 +1215,9 @@ impl Writer { let pointer_expression = &function.expressions[*pointer]; let value_expression = &function.expressions[*value]; let (pointer_id, _) = - self.parse_expression(ir_module, function, pointer_expression, output); + self.write_expression(ir_module, function, pointer_expression, output); let (value_id, _) = - self.parse_expression(ir_module, function, value_expression, output); + self.write_expression(ir_module, function, value_expression, output); self.instruction_store(pointer_id, value_id) } @@ -1279,41 +1238,15 @@ impl Writer { .push(self.instruction_source(spirv::SourceLanguage::GLSL, 450)); } - for (handle, function) in ir_module.functions.iter() { - let mut function_instructions: Vec = vec![]; - function_instructions.push(self.parse_function(handle, function, &ir_module.types)); - - let id = self.generate_id(); - function_instructions.push(self.instruction_label(id)); - - for block in function.body.iter() { - let mut output: Vec = vec![]; - let instruction = - self.parse_function_block(ir_module, function, &block, &mut output); - function_instructions.append(&mut output); - function_instructions.push(instruction); - } - - function_instructions.push(self.instruction_function_end()); - for instruction in function_instructions.iter() { - instruction.to_words(&mut self.logical_layout.function_definitions); - } - } - - for entry_point in ir_module.entry_points.iter() { - let entry_point_instruction = self.instruction_entry_point(entry_point, ir_module); - entry_point_instruction.to_words(&mut self.logical_layout.entry_points); - } - // Looking through all global variable, types, constants. // Doing this because we also want to include not used parts of the module // to be included in the output - for (handle, _) in ir_module.global_variables.iter() { - self.get_global_variable_id(&ir_module.types, &ir_module.global_variables, handle); + for (handle, _) in ir_module.types.iter() { + self.get_type_id(&ir_module.types, LookupType::Handle(handle)); } - for (handle, _) in ir_module.types.iter() { - self.get_type_id(&ir_module.types, handle); + for (handle, _) in ir_module.global_variables.iter() { + self.get_global_variable_id(&ir_module.types, &ir_module.global_variables, handle); } for (handle, _) in ir_module.constants.iter() { @@ -1329,6 +1262,32 @@ impl Writer { .to_words(&mut self.logical_layout.capabilities); } + for (handle, function) in ir_module.functions.iter() { + let mut function_instructions: Vec = vec![]; + function_instructions.push(self.write_function(handle, function, &ir_module.types)); + + let id = self.generate_id(); + function_instructions.push(self.instruction_label(id)); + + for block in function.body.iter() { + let mut output: Vec = vec![]; + let instruction = + self.write_function_block(ir_module, function, &block, &mut output); + function_instructions.append(&mut output); + function_instructions.push(instruction); + } + + function_instructions.push(self.instruction_function_end()); + for instruction in function_instructions.iter() { + instruction.to_words(&mut self.logical_layout.function_definitions); + } + } + + for entry_point in ir_module.entry_points.iter() { + let entry_point_instruction = self.instruction_entry_point(entry_point, ir_module); + entry_point_instruction.to_words(&mut self.logical_layout.entry_points); + } + self.instruction_memory_model() .to_words(&mut self.logical_layout.memory_model); diff --git a/src/lib.rs b/src/lib.rs index 1f58819ec..9578b73be 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -102,7 +102,7 @@ pub type Bytes = u8; /// Number of components in a vector. #[repr(u8)] -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum VectorSize { @@ -116,7 +116,7 @@ pub enum VectorSize { /// Primitive type for a scalar. #[repr(u8)] -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ScalarKind { From c5a302b76946e0ce0da0b8f62df866bbe334927d Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 19 Aug 2020 20:05:24 +0200 Subject: [PATCH 0143/2212] [glsl-new] Use Empty statement (#139) --- src/front/glsl_new/parser.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 91db0cd3b..d7c8541a6 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -572,6 +572,7 @@ pomelo! { extra.context.add_local_var(id, h); } match statements.len() { + 0 => Statement::Empty, 1 => statements.remove(0), _ => Statement::Block(statements), } From b0f1f6285accce779f9ea518efe952b6174a690a Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 19 Aug 2020 20:06:24 +0200 Subject: [PATCH 0144/2212] [glsl-new] set global_usgae on functions (#138) --- src/front/glsl_new/parser.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index d7c8541a6..823194b9d 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -753,6 +753,7 @@ pomelo! { std::mem::swap(&mut f.local_variables, &mut extra.context.local_variables); extra.context.clear_scopes(); f.body = cs; + f.global_usage = crate::GlobalUse::scan(&f.expressions, &f.body, &extra.global_variables); f }; } From d6b172ddcb363402a526e50f0c79448e9f231eaa Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Wed, 19 Aug 2020 14:09:28 -0400 Subject: [PATCH 0145/2212] Add support for array stride to wgsl frontend (#137) * Add support for array stride to wgsl frontend * rename --- src/front/wgsl.rs | 48 ++++++++++++++++++++++++++++++++++++++++---- test-data/boids.wgsl | 2 +- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 6ebf0aea0..6ae1eee23 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -170,6 +170,8 @@ pub enum Error<'a> { UnknownFunction(&'a str), #[error("missing offset for structure member `{0}`")] MissingMemberOffset(&'a str), + #[error("array stride must not be 0")] + ZeroStride, //MutabilityViolation(&'a str), // TODO: these could be replaced with more detailed errors #[error("other error")] @@ -256,6 +258,22 @@ impl<'a> Lexer<'a> { self.expect(Token::Paren('>'))?; Ok(pair) } + + fn take_until(&mut self, what: Token<'a>) -> Result, Error<'a>> { + let original_input = self.input; + let initial_len = self.input.len(); + let mut used_len = 0; + loop { + if self.next() == what { + break; + } + used_len = initial_len - self.input.len(); + } + + Ok(Lexer { + input: &original_input[..used_len], + }) + } } trait StringValueLookup<'a> { @@ -1000,6 +1018,12 @@ impl Parser { type_arena: &mut Arena, ) -> Result, Error<'a>> { self.scopes.push(Scope::TypeDecl); + let decoration_lexer = if lexer.skip(Token::DoubleParen('[')) { + Some(lexer.take_until(Token::DoubleParen(']'))?) + } else { + None + }; + let inner = match lexer.next() { Token::Word("f32") => crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, @@ -1138,11 +1162,27 @@ impl Parser { Token::Separator('>') => crate::ArraySize::Dynamic, other => return Err(Error::Unexpected(other)), }; - crate::TypeInner::Array { - base, - size, - stride: None, + + let mut stride = None; + if let Some(mut lexer) = decoration_lexer { + self.scopes.push(Scope::Decoration); + loop { + match lexer.next() { + Token::Word("stride") => { + use std::num::NonZeroU32; + stride = Some( + NonZeroU32::new(lexer.next_uint_literal()?) + .ok_or(Error::ZeroStride)?, + ); + } + Token::End => break, + other => return Err(Error::Unexpected(other)), + } + } + self.scopes.pop(); } + + crate::TypeInner::Array { base, size, stride } } Token::Word("struct") => { let members = self.parse_struct_body(lexer, type_arena)?; diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl index a7c13dd63..b3aeca6e0 100644 --- a/test-data/boids.wgsl +++ b/test-data/boids.wgsl @@ -57,7 +57,7 @@ type SimParams = struct { }; type Particles = struct { - [[offset 0]] particles : array; + [[offset 0]] particles : [[stride 16]] array; }; [[binding 0, set 0]] var params : SimParams; From 8c0b1636eae835b64a4a827c26879a17c85a38ba Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Wed, 19 Aug 2020 20:22:21 -0400 Subject: [PATCH 0146/2212] Interpolation support for wgsl, glsl, glsl-new, spirv (front and back), and glsl-out (#140) * Add interpolation support to naga core and wgsl * Add glsl-new fragment shader support to examples/convert.rs * Add interpolation support to glsl_new * Add interpolation support to spirv frontend * Add interpolation support to spirv backend * Add interpolation support to glsl backend * Add interpolation support to old glsl backend * Fix interpolation field syntax in glsl backend * Formatting fix * thanks clippy * Add wgsl struct interpolation decoration * Change wgsl interpolation syntax * Modify interpolation enum * Changes responding to review * Remove interpolation struct member qualifier * code changes after review --- examples/convert.rs | 32 +++++++++++++++++++++--- src/back/glsl.rs | 24 ++++++++++++++++-- src/back/spv/writer.rs | 15 +++++++++++ src/front/glsl/mod.rs | 44 +++++++++++++++++++++++++++------ src/front/glsl_new/ast.rs | 3 ++- src/front/glsl_new/lex.rs | 23 +++++++++++++++++ src/front/glsl_new/parser.rs | 20 +++++++++++++-- src/front/spv.rs | 26 ++++++++++++++++++- src/front/wgsl.rs | 48 ++++++++++++++++++++++++++---------- src/lib.rs | 28 +++++++++++++++++++++ 10 files changed, 234 insertions(+), 29 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index d36bef330..ab47a0375 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -79,11 +79,37 @@ fn main() { } module.unwrap() } - #[cfg(feature = "glsl")] + #[cfg(any(feature = "glsl", feature = "glsl-new"))] "frag" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Fragment) - .unwrap() + let mut module = None; + if prefer_glsl_new { + #[cfg(feature = "glsl-new")] + { + module = Some( + naga::front::glsl_new::parse_str( + &input, + "main".to_string(), + naga::ShaderStage::Fragment, + ) + .unwrap(), + ) + } + } + if module.is_none() { + #[cfg(feature = "glsl")] + { + module = Some( + naga::front::glsl::parse_str( + &input, + "main".to_string(), + naga::ShaderStage::Fragment, + ) + .unwrap(), + ) + } + } + module.unwrap() } #[cfg(feature = "glsl")] "comp" => { diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 042a0991e..fdd0a32bb 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,7 +1,8 @@ use crate::{ Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, - FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageFlags, IntrinsicFunction, - LocalVariable, Module, ScalarKind, Statement, StorageClass, Type, TypeInner, UnaryOperator, + FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageFlags, Interpolation, + IntrinsicFunction, LocalVariable, Module, ScalarKind, Statement, StorageClass, Type, TypeInner, + UnaryOperator, }; use std::{ borrow::Cow, @@ -123,6 +124,10 @@ pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { write!(out, "layout({}) ", Binding(binding.clone()))?; } + if let Some(interpolation) = global.interpolation { + write!(out, "{} ", write_interpolation(interpolation)?)?; + } + let name = namer(global.name.as_ref()); writeln!( @@ -892,6 +897,21 @@ fn write_storage_class(class: StorageClass) -> Result { })) } +fn write_interpolation(interpolation: Interpolation) -> Result<&'static str, Error> { + Ok(match interpolation { + Interpolation::Perspective => "smooth", + Interpolation::Linear => "noperspective", + Interpolation::Flat => "flat", + Interpolation::Centroid => "centroid", + Interpolation::Sample => "sample", + Interpolation::Patch => { + return Err(Error::Custom( + "patch interpolation qualifier not supported".to_string(), + )) + } + }) +} + fn write_array_size(size: ArraySize) -> Result { Ok(match size { ArraySize::Static(size) => size.to_string(), diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index cb194919f..f4448bd11 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -956,6 +956,21 @@ impl Writer { .push(self.instruction_name(id, global_variable.name.as_ref().unwrap().as_str())); } + if let Some(interpolation) = global_variable.interpolation { + let decoration = match interpolation { + crate::Interpolation::Linear => Some(spirv::Decoration::NoPerspective), + crate::Interpolation::Flat => Some(spirv::Decoration::Flat), + crate::Interpolation::Patch => Some(spirv::Decoration::Patch), + crate::Interpolation::Centroid => Some(spirv::Decoration::Centroid), + crate::Interpolation::Sample => Some(spirv::Decoration::Sample), + crate::Interpolation::Perspective => None, + }; + if let Some(decoration) = decoration { + self.annotations + .push(self.instruction_decorate(id, decoration, &[])); + } + } + match global_variable.binding.as_ref().unwrap() { crate::Binding::Location(location) => { self.annotations.push(self.instruction_decorate( diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 993e0214b..43986531d 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,8 +1,9 @@ #![allow(clippy::panic)] use crate::{ Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Constant, ConstantInner, EntryPoint, - Expression, FastHashMap, Function, GlobalVariable, Handle, Header, LocalVariable, Module, - ScalarKind, ShaderStage, StorageClass, StructMember, Type, TypeInner, VectorSize, + Expression, FastHashMap, Function, GlobalVariable, Handle, Header, Interpolation, + LocalVariable, Module, ScalarKind, ShaderStage, StorageClass, StructMember, Type, TypeInner, + VectorSize, }; use glsl::{ parser::{Parse, ParseError}, @@ -162,7 +163,8 @@ impl<'a> Parser<'a> { self.globals_lookup.insert(name, Global::Variable(handle)); } Declaration::Block(block) => { - let (class, binding) = Self::parse_type_qualifier(block.qualifier); + let (class, binding, interpolation) = + Self::parse_type_qualifier(block.qualifier); let ty_name = block.name.0; let name = block.identifier.clone().map(|ident| ident.ident.0); @@ -232,6 +234,7 @@ impl<'a> Parser<'a> { class, name, ty, + interpolation, }); for (name, index) in reexports { @@ -570,6 +573,7 @@ impl<'a> Parser<'a> { width: 4, }, }), + interpolation: None, }), )), "gl_InstanceIndex" => Ok(Expression::GlobalVariable( @@ -584,6 +588,7 @@ impl<'a> Parser<'a> { width: 4, }, }), + interpolation: None, }), )), "gl_BaseVertex" => Ok(Expression::GlobalVariable( @@ -598,6 +603,7 @@ impl<'a> Parser<'a> { width: 4, }, }), + interpolation: None, }), )), "gl_BaseInstance" => Ok(Expression::GlobalVariable( @@ -612,6 +618,7 @@ impl<'a> Parser<'a> { width: 4, }, }), + interpolation: None, }), )), "gl_Position" => Ok(Expression::GlobalVariable(self.globals.fetch_or_append( @@ -631,6 +638,7 @@ impl<'a> Parser<'a> { width: 4, }, }), + interpolation: None, }, ))), "gl_PointSize" => Ok(Expression::GlobalVariable(self.globals.fetch_or_append( @@ -645,6 +653,7 @@ impl<'a> Parser<'a> { width: 4, }, }), + interpolation: None, }, ))), "gl_ClipDistance" => Ok(Expression::GlobalVariable( @@ -659,6 +668,7 @@ impl<'a> Parser<'a> { width: 4, }, }), + interpolation: None, }), )), other => { @@ -1039,17 +1049,18 @@ impl<'a> Parser<'a> { } }; - let (class, binding) = head + let (class, binding, interpolation) = head .ty .qualifier .map(Self::parse_type_qualifier) - .unwrap_or((StorageClass::Private, None)); + .unwrap_or((StorageClass::Private, None, None)); Ok(self.globals.append(GlobalVariable { name, class, binding, ty, + interpolation, })) } @@ -1158,9 +1169,12 @@ impl<'a> Parser<'a> { Ok(size) } - fn parse_type_qualifier(qualifier: TypeQualifier) -> (StorageClass, Option) { + fn parse_type_qualifier( + qualifier: TypeQualifier, + ) -> (StorageClass, Option, Option) { let mut storage = None; let mut binding = None; + let mut interpolation = Interpolation::Perspective; for qualifier in qualifier.qualifiers { match qualifier { @@ -1228,11 +1242,27 @@ impl<'a> Parser<'a> { panic!() } } + TypeQualifierSpec::Interpolation(interpolation_qualifier) => { + interpolation = match interpolation_qualifier { + InterpolationQualifier::NoPerspective => Interpolation::Linear, + InterpolationQualifier::Flat => Interpolation::Flat, + InterpolationQualifier::Smooth => Interpolation::Perspective, + } + } _ => unimplemented!(), } } - (storage.unwrap_or(StorageClass::Private), binding) + let class = storage.unwrap_or(StorageClass::Private); + + ( + class, + binding, + match class { + StorageClass::Input | StorageClass::Output => Some(interpolation), + _ => None, + }, + ) } } diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 8f082c520..26b49534f 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -1,6 +1,6 @@ use crate::{ Arena, Binding, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, - LocalVariable, ShaderStage, Statement, StorageClass, Type, + Interpolation, LocalVariable, ShaderStage, Statement, StorageClass, Type, }; #[derive(Debug)] @@ -104,6 +104,7 @@ pub struct ExpressionRule { pub enum TypeQualifier { StorageClass(StorageClass), Binding(Binding), + Interpolation(Interpolation), } #[derive(Debug)] diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index e26252b68..17be2d30f 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -113,6 +113,29 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { "layout" => (Some(Token::Layout(meta)), rest), "in" => (Some(Token::In(meta)), rest), "out" => (Some(Token::Out(meta)), rest), + "flat" => ( + Some(Token::Interpolation((meta, crate::Interpolation::Flat))), + rest, + ), + "noperspective" => ( + Some(Token::Interpolation((meta, crate::Interpolation::Linear))), + rest, + ), + "smooth" => ( + Some(Token::Interpolation(( + meta, + crate::Interpolation::Perspective, + ))), + rest, + ), + "centroid" => ( + Some(Token::Interpolation((meta, crate::Interpolation::Centroid))), + rest, + ), + "sample" => ( + Some(Token::Interpolation((meta, crate::Interpolation::Sample))), + rest, + ), // types "void" => (Some(Token::Void(meta)), rest), "float" => (Some(Token::Float(meta)), rest), diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 823194b9d..7ecd92301 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -8,7 +8,7 @@ pomelo! { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{Arena, BinaryOperator, Binding, Block, BuiltIn, Constant, ConstantInner, Expression, Function, GlobalVariable, Handle, LocalVariable, ScalarKind, - ShaderStage, Statement, StorageClass, Type, TypeInner, VectorSize, Bytes}; + ShaderStage, Statement, StorageClass, Type, TypeInner, VectorSize, Bytes, Interpolation}; } %token #[derive(Debug)] pub enum Token {}; %parser pub struct Parser<'a> {}; @@ -99,6 +99,8 @@ pomelo! { %type type_qualifier Vec; %type single_type_qualifier TypeQualifier; %type storage_qualifier StorageClass; + %type interpolation_qualifier Interpolation; + %type Interpolation Interpolation; // types %type fully_specified_type (Vec, Option>); @@ -151,6 +153,7 @@ pomelo! { width: 4, }, }), + interpolation: None, }, ); extra.lookup_global_variables.insert(v.1, h); @@ -533,7 +536,9 @@ pomelo! { TypeQualifier::Binding(l) } // single_type_qualifier ::= precision_qualifier; - // single_type_qualifier ::= interpolation_qualifier; + single_type_qualifier ::= interpolation_qualifier(i) { + TypeQualifier::Interpolation(i) + } // single_type_qualifier ::= invariant_qualifier; // single_type_qualifier ::= precise_qualifier; @@ -542,6 +547,7 @@ pomelo! { storage_qualifier ::= In {StorageClass::Input} storage_qualifier ::= Out {StorageClass::Output} //TODO: other storage qualifiers + interpolation_qualifier ::= Interpolation((_, i)) { i } initializer ::= assignment_expression; // initializer ::= LeftBrace initializer_list RightBrace; @@ -735,6 +741,15 @@ pomelo! { if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } }); + let interpolation = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Interpolation(i) = tq { Some(*i) } else { None } + }).or_else(|| match class { + StorageClass::Input | StorageClass::Output => { + Some(Interpolation::Perspective) + } + _ => None, + }); + for (id, initializer) in d.ids_initializers { let h = extra.global_variables.fetch_or_append( GlobalVariable { @@ -742,6 +757,7 @@ pomelo! { class, binding: binding.clone(), ty: d.ty, + interpolation, }, ); extra.lookup_global_variables.insert(id, h); diff --git a/src/front/spv.rs b/src/front/spv.rs index 0b6929f9f..1b880a92b 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -219,6 +219,7 @@ struct Decoration { block: Option, offset: Option, array_stride: Option, + interpolation: Option, } impl Decoration { @@ -496,6 +497,21 @@ impl> Parser { inst.expect(base_words + 2)?; dec.array_stride = NonZeroU32::new(self.next()?); } + spirv::Decoration::NoPerspective => { + dec.interpolation = Some(crate::Interpolation::Linear); + } + spirv::Decoration::Flat => { + dec.interpolation = Some(crate::Interpolation::Flat); + } + spirv::Decoration::Patch => { + dec.interpolation = Some(crate::Interpolation::Patch); + } + spirv::Decoration::Centroid => { + dec.interpolation = Some(crate::Interpolation::Centroid); + } + spirv::Decoration::Sample => { + dec.interpolation = Some(crate::Interpolation::Sample); + } other => { log::warn!("Unknown decoration {:?}", other); for _ in base_words + 1..inst.wc { @@ -1985,11 +2001,19 @@ impl> Parser { } _ => return Err(Error::UnsupportedType(lookup_type.handle)), }; + let class = map_storage_class(storage)?; + let var = crate::GlobalVariable { name: dec.name, - class: map_storage_class(storage)?, + class, binding, ty, + interpolation: dec.interpolation.or_else(|| match class { + crate::StorageClass::Input | crate::StorageClass::Output => { + Some(crate::Interpolation::Perspective) + } + _ => None, + }), }; self.lookup_variable.insert( id, diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 6ae1eee23..58a9b3cc2 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -456,6 +456,16 @@ impl Parser { } } + fn get_interpolation(word: &str) -> Result> { + match word { + "linear" => Ok(crate::Interpolation::Linear), + "flat" => Ok(crate::Interpolation::Flat), + "centroid" => Ok(crate::Interpolation::Centroid), + "sample" => Ok(crate::Interpolation::Sample), + _ => Err(Error::UnknownDecoration(word)), + } + } + fn get_constant_inner( word: &str, ) -> Result<(crate::ConstantInner, crate::ScalarKind), Error<'_>> { @@ -1159,7 +1169,7 @@ impl Parser { lexer.expect(Token::Paren('>'))?; crate::ArraySize::Static(value) } - Token::Separator('>') => crate::ArraySize::Dynamic, + Token::Paren('>') => crate::ArraySize::Dynamic, other => return Err(Error::Unexpected(other)), }; @@ -1410,6 +1420,8 @@ impl Parser { ) -> Result> { // read decorations let mut binding = None; + // Perspective is the default qualifier. + let mut interpolation = crate::Interpolation::Perspective; if lexer.skip(Token::DoubleParen('[')) { let (mut bind_index, mut bind_set) = (None, None); self.scopes.push(Scope::Decoration); @@ -1429,7 +1441,10 @@ impl Parser { "set" => { bind_set = Some(lexer.next_uint_literal()?); } - other => return Err(Error::UnknownDecoration(other)), + "interpolate" => { + interpolation = Self::get_interpolation(lexer.next_ident()?)?; + } + word => return Err(Error::UnknownDecoration(word)), } match lexer.next() { Token::DoubleParen(']') => { @@ -1494,21 +1509,28 @@ impl Parser { Token::Word("var") => { let (name, class, ty) = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; + let class = match class { + Some(c) => c, + None => match binding { + Some(crate::Binding::BuiltIn(builtin)) => match builtin { + crate::BuiltIn::GlobalInvocationId => crate::StorageClass::Input, + crate::BuiltIn::Position => crate::StorageClass::Output, + _ => unimplemented!(), + }, + _ => crate::StorageClass::Private, + }, + }; let var_handle = module.global_variables.append(crate::GlobalVariable { name: Some(name.to_owned()), - class: match class { - Some(c) => c, - None => match binding { - Some(crate::Binding::BuiltIn(builtin)) => match builtin { - crate::BuiltIn::GlobalInvocationId => crate::StorageClass::Input, - crate::BuiltIn::Position => crate::StorageClass::Output, - _ => unimplemented!(), - }, - _ => crate::StorageClass::Private, - }, - }, + class, binding: binding.take(), ty, + interpolation: match class { + crate::StorageClass::Input | crate::StorageClass::Output => { + Some(interpolation) + } + _ => None, + }, }); lookup_global_expression .insert(name, crate::Expression::GlobalVariable(var_handle)); diff --git a/src/lib.rs b/src/lib.rs index 9578b73be..867cacb9d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -153,6 +153,30 @@ pub enum MemberOrigin { Offset(u32), } +/// The interpolation qualifier of a binding or struct field. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum Interpolation { + /// The value will be interpolated in a perspective-correct fashion. + /// Also known as "smooth" in glsl. + Perspective, + /// Indicates that linear, non-perspective, correct + /// interpolation must be used. + /// Also known as "no_perspective" in glsl. + Linear, + /// Indicates that no interpolation will be performed. + Flat, + /// Indicates a tessellation patch. + Patch, + /// When used with multi-sampling rasterization, allow + /// a single interpolation location for an entire pixel. + Centroid, + /// When used with multi-sampling rasterization, require + /// per-sample interpolation. + Sample, +} + /// Member of a user-defined structure. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug, PartialEq)] @@ -316,6 +340,10 @@ pub struct GlobalVariable { pub binding: Option, /// The type of this variable. pub ty: Handle, + /// The interpolation qualifier, if any. + /// Required for global outputs in vertex shaders + /// and global inputs in fragment shaders. + pub interpolation: Option, } /// Variable defined at function level. From 88fb1bb22a359980d65dc69c55efb368dd7eb0f4 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Wed, 19 Aug 2020 20:48:09 -0400 Subject: [PATCH 0147/2212] [wgsl] Support for composite constant expressions. (#141) * Add composite constant expression support to wgsl * remove matching on reference * Re-fix reference matching --- src/front/wgsl.rs | 44 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 58a9b3cc2..0929ec322 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -172,6 +172,8 @@ pub enum Error<'a> { MissingMemberOffset(&'a str), #[error("array stride must not be 0")] ZeroStride, + #[error("not a composite type: {0:?}")] + NotCompositeType(crate::TypeInner), //MutabilityViolation(&'a str), // TODO: these could be replaced with more detailed errors #[error("other error")] @@ -466,6 +468,27 @@ impl Parser { } } + fn deconstruct_composite_type( + type_arena: &mut Arena, + ty: Handle, + index: usize, + ) -> Result, Error<'static>> { + let ty = match type_arena[ty].inner { + crate::TypeInner::Vector { kind, width, .. } + | crate::TypeInner::Matrix { kind, width, .. } => { + type_arena.fetch_or_append(crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind, width }, + }) + } + crate::TypeInner::Array { base, .. } => base, + crate::TypeInner::Struct { ref members } => members[index].ty, + ref inner => return Err(Error::NotCompositeType(inner.clone())), + }; + + Ok(ty) + } + fn get_constant_inner( word: &str, ) -> Result<(crate::ConstantInner, crate::ScalarKind), Error<'_>> { @@ -502,12 +525,27 @@ impl Parser { inner } _ => { - let _ty = self.parse_type_decl(lexer, type_arena); + let composite_ty = self.parse_type_decl(lexer, type_arena)?; lexer.expect(Token::Paren('('))?; + let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { - let _ = self.parse_const_expression(lexer, type_arena, const_arena)?; + if !components.is_empty() { + lexer.expect(Token::Separator(','))?; + } + let inner = self.parse_const_expression(lexer, type_arena, const_arena)?; + let ty = Self::deconstruct_composite_type( + type_arena, + composite_ty, + components.len(), + )?; + components.push(const_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner, + ty, + })); } - unimplemented!() + crate::ConstantInner::Composite(components) } }; self.scopes.pop(); From bd276bf4a4736c7c481c33ff19a0a33fc2852ba5 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Thu, 20 Aug 2020 01:39:27 -0400 Subject: [PATCH 0148/2212] Add more builtins to wgsl frontend (#143) --- src/front/wgsl.rs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 0929ec322..3c5295266 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -437,16 +437,21 @@ impl Parser { } fn get_built_in(word: &str) -> Result> { - match word { + Ok(match word { // vertex - "position" => Ok(crate::BuiltIn::Position), - "vertex_idx" => Ok(crate::BuiltIn::VertexIndex), - "instance_idx" => Ok(crate::BuiltIn::InstanceIndex), + "position" => crate::BuiltIn::Position, + "vertex_idx" => crate::BuiltIn::VertexIndex, + "instance_idx" => crate::BuiltIn::InstanceIndex, + // fragment + "front_facing" => crate::BuiltIn::FrontFacing, + "frag_coord" => crate::BuiltIn::FragCoord, + "frag_depth" => crate::BuiltIn::FragDepth, // compute - "global_invocation_id" => Ok(crate::BuiltIn::GlobalInvocationId), - "local_invocation_id" => Ok(crate::BuiltIn::LocalInvocationId), - _ => Err(Error::UnknownBuiltin(word)), - } + "global_invocation_id" => crate::BuiltIn::GlobalInvocationId, + "local_invocation_id" => crate::BuiltIn::LocalInvocationId, + "local_invocation_idx" => crate::BuiltIn::LocalInvocationIndex, + _ => return Err(Error::UnknownBuiltin(word)), + }) } fn get_shader_stage(word: &str) -> Result> { From 5035362ee6d9cc311dfc907d09ae92de14560d0b Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Thu, 20 Aug 2020 01:41:24 -0400 Subject: [PATCH 0149/2212] Better floating point support for wgsl (#142) * Add custom consume_number function for consuming numbers into tokens to wgsl frontend * clippy --- src/front/wgsl.rs | 49 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 3c5295266..8ccdd41ad 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -44,6 +44,28 @@ mod lex { input.split_at(pos) } + fn consume_number(input: &str) -> (&str, &str) { + let mut is_first_char = true; + let mut right_after_exponent = false; + + let mut what = |c| { + if is_first_char { + is_first_char = false; + c == '-' || c >= '0' && c <= '9' || c == '.' + } else if c == 'e' || c == 'E' { + right_after_exponent = true; + true + } else if right_after_exponent { + right_after_exponent = false; + c >= '0' && c <= '9' || c == '-' + } else { + c >= '0' && c <= '9' || c == '.' + } + }; + let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); + input.split_at(pos) + } + pub fn consume_token(mut input: &str) -> (Token<'_>, &str) { input = input.trim_start(); let mut chars = input.chars(); @@ -60,7 +82,17 @@ mod lex { (Token::Separator(cur), input) } } - ';' | ',' | '.' => (Token::Separator(cur), chars.as_str()), + ';' | ',' => (Token::Separator(cur), chars.as_str()), + '.' => { + let og_chars = chars.as_str(); + match chars.next() { + Some('0'..='9') => { + let (number, rest) = consume_number(input); + (Token::Number(number), rest) + } + _ => (Token::Separator(cur), og_chars), + } + } '(' | ')' | '{' | '}' => (Token::Paren(cur), chars.as_str()), '<' | '>' => { input = chars.as_str(); @@ -87,7 +119,7 @@ mod lex { } } '0'..='9' => { - let (number, rest) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); + let (number, rest) = consume_number(input); (Token::Number(number), rest) } 'a'..='z' | 'A'..='Z' | '_' => { @@ -106,11 +138,14 @@ mod lex { } } '-' => { - input = chars.as_str(); - if chars.next() == Some('>') { - (Token::Arrow, chars.as_str()) - } else { - (Token::Operation(cur), input) + let og_chars = chars.as_str(); + match chars.next() { + Some('>') => (Token::Arrow, chars.as_str()), + Some('0'..='9') | Some('.') => { + let (number, rest) = consume_number(input); + (Token::Number(number), rest) + } + _ => (Token::Operation(cur), og_chars), } } '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), From 6026e57404bf32ae7a2cb74c3acdf8852ebea301 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Fri, 21 Aug 2020 00:13:25 -0400 Subject: [PATCH 0150/2212] [wgsl] Add more complete function calling support (#144) * Add function calling support to wgsl frontend * Fix external namespace with multiple namespaces * changes after code review * Don't re-tokenize std_namespace every time --- src/front/wgsl.rs | 158 ++++++++++++++++++++++++++++------------ src/lib.rs | 4 + test-data/function.wgsl | 12 +++ 3 files changed, 127 insertions(+), 47 deletions(-) create mode 100644 test-data/function.wgsl diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 8ccdd41ad..4c3fa5453 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -209,6 +209,8 @@ pub enum Error<'a> { ZeroStride, #[error("not a composite type: {0:?}")] NotCompositeType(crate::TypeInner), + #[error("function redefinition: `{0}`")] + FunctionRedefinition(&'a str), //MutabilityViolation(&'a str), // TODO: these could be replaced with more detailed errors #[error("other error")] @@ -237,7 +239,7 @@ impl<'a> Lexer<'a> { self.clone().next() } - fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { + fn expect(&mut self, expected: Token<'_>) -> Result<(), Error<'a>> { let token = self.next(); if token == expected { Ok(()) @@ -246,7 +248,7 @@ impl<'a> Lexer<'a> { } } - fn skip(&mut self, what: Token<'a>) -> bool { + fn skip(&mut self, what: Token<'_>) -> bool { let (token, rest) = lex::consume_token(self.input); if token == what { self.input = rest; @@ -296,7 +298,7 @@ impl<'a> Lexer<'a> { Ok(pair) } - fn take_until(&mut self, what: Token<'a>) -> Result, Error<'a>> { + fn take_until(&mut self, what: Token<'_>) -> Result, Error<'a>> { let original_input = self.input; let initial_len = self.input.len(); let mut used_len = 0; @@ -449,7 +451,8 @@ pub struct ParseError<'a> { pub struct Parser { scopes: Vec, lookup_type: FastHashMap>, - std_namespace: Option, + function_lookup: FastHashMap>, + std_namespace: Option>, } impl Parser { @@ -457,6 +460,7 @@ impl Parser { Parser { scopes: Vec::new(), lookup_type: FastHashMap::default(), + function_lookup: FastHashMap::default(), std_namespace: None, } } @@ -543,6 +547,49 @@ impl Parser { } } + fn parse_function_call<'a>( + &mut self, + lexer: &Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result)>, Error<'a>> { + let mut lexer = lexer.clone(); + + let external_function = if let Some(std_namespaces) = self.std_namespace.as_deref() { + std_namespaces.iter().all(|namespace| { + lexer.skip(Token::Word(namespace)) && lexer.skip(Token::DoubleColon) + }) + } else { + false + }; + + let origin = if external_function { + let function = lexer.next_ident()?; + crate::FunctionOrigin::External(function.to_string()) + } else if let Ok(function) = lexer.next_ident() { + if let Some(&function) = self.function_lookup.get(function) { + crate::FunctionOrigin::Local(function) + } else { + return Ok(None); + } + } else { + return Ok(None); + }; + + if !lexer.skip(Token::Paren('(')) { + return Ok(None); + } + + let mut arguments = Vec::new(); + while !lexer.skip(Token::Paren(')')) { + if !arguments.is_empty() { + lexer.expect(Token::Separator(','))?; + } + let arg = self.parse_general_expression(&mut lexer, ctx.reborrow())?; + arguments.push(arg); + } + Ok(Some((crate::Expression::Call { origin, arguments }, lexer))) + } + fn parse_const_expression<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -654,22 +701,11 @@ impl Parser { self.scopes.pop(); return Ok(*handle); } - if self.std_namespace.as_deref() == Some(word) { - lexer.expect(Token::DoubleColon)?; - let name = lexer.next_ident()?; - let mut arguments = Vec::new(); - lexer.expect(Token::Paren('('))?; - while !lexer.skip(Token::Paren(')')) { - if !arguments.is_empty() { - lexer.expect(Token::Separator(','))?; - } - let arg = self.parse_general_expression(lexer, ctx.reborrow())?; - arguments.push(arg); - } - crate::Expression::Call { - origin: crate::FunctionOrigin::External(name.to_owned()), - arguments, - } + if let Some((expr, new_lexer)) = + self.parse_function_call(&backup, ctx.reborrow())? + { + *lexer = new_lexer; + expr } else { *lexer = backup; let ty = self.parse_type_decl(lexer, ctx.types)?; @@ -1295,6 +1331,7 @@ impl Parser { lexer: &mut Lexer<'a>, mut context: StatementContext<'a, '_, '_>, ) -> Result, Error<'a>> { + let backup = lexer.clone(); match lexer.next() { Token::Separator(';') => Ok(Some(crate::Statement::Empty)), Token::Paren('}') => Ok(None), @@ -1387,15 +1424,26 @@ impl Parser { "continue" => crate::Statement::Continue, ident => { // assignment - let var_expr = context.lookup_ident.lookup(ident)?; - let left = self.parse_postfix(lexer, context.as_expression(), var_expr)?; - lexer.expect(Token::Operation('='))?; - let value = - self.parse_general_expression(lexer, context.as_expression())?; - lexer.expect(Token::Separator(';'))?; - crate::Statement::Store { - pointer: left, - value, + if let Some(&var_expr) = context.lookup_ident.get(ident) { + let left = + self.parse_postfix(lexer, context.as_expression(), var_expr)?; + lexer.expect(Token::Operation('='))?; + let value = + self.parse_general_expression(lexer, context.as_expression())?; + lexer.expect(Token::Separator(';'))?; + crate::Statement::Store { + pointer: left, + value, + } + } else if let Some((expr, new_lexer)) = + self.parse_function_call(&backup, context.as_expression())? + { + *lexer = new_lexer; + context.expressions.append(expr); + lexer.expect(Token::Separator(';'))?; + crate::Statement::Empty + } else { + return Err(Error::UnknownIdent(ident)); } } }; @@ -1459,35 +1507,45 @@ impl Parser { } else { Some(self.parse_type_decl(lexer, &mut module.types)?) }; + + let fun_handle = module.functions.append(crate::Function { + name: Some(fun_name.to_string()), + parameter_types, + return_type, + global_usage: Vec::new(), + local_variables: Arena::new(), + expressions, + body: Vec::new(), + }); + if self + .function_lookup + .insert(fun_name.to_string(), fun_handle) + .is_some() + { + return Err(Error::FunctionRedefinition(fun_name)); + } + let fun = module.functions.get_mut(fun_handle); + // read body - let mut local_variables = Arena::new(); let mut typifier = Typifier::new(); - let body = self.parse_block( + fun.body = self.parse_block( lexer, StatementContext { lookup_ident: &mut lookup_ident, typifier: &mut typifier, - variables: &mut local_variables, - expressions: &mut expressions, + variables: &mut fun.local_variables, + expressions: &mut fun.expressions, types: &mut module.types, constants: &mut module.constants, global_vars: &module.global_variables, }, )?; // done - let global_usage = crate::GlobalUse::scan(&expressions, &body, &module.global_variables); + fun.global_usage = + crate::GlobalUse::scan(&fun.expressions, &fun.body, &module.global_variables); self.scopes.pop(); - let fun = crate::Function { - name: Some(fun_name.to_owned()), - parameter_types, - return_type, - global_usage, - local_variables, - expressions, - body, - }; - Ok(module.functions.append(fun)) + Ok(fun_handle) } fn parse_global_decl<'a>( @@ -1554,10 +1612,16 @@ impl Parser { other => return Err(Error::Unexpected(other)), }; lexer.expect(Token::Word("as"))?; - let namespace = lexer.next_ident()?; - lexer.expect(Token::Separator(';'))?; + let mut namespaces = Vec::new(); + loop { + namespaces.push(lexer.next_ident()?.to_owned()); + if lexer.skip(Token::Separator(';')) { + break; + } + lexer.expect(Token::DoubleColon)?; + } match path { - "GLSL.std.450" => self.std_namespace = Some(namespace.to_owned()), + "GLSL.std.450" => self.std_namespace = Some(namespaces), _ => return Err(Error::UnknownImport(path)), } self.scopes.pop(); diff --git a/src/lib.rs b/src/lib.rs index 867cacb9d..753ebf7fb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -423,6 +423,10 @@ pub enum DerivativeAxis { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum FunctionOrigin { Local(Handle), + // External { + // namespace: String, // Maybe this should be a handle to a namespace Arena? + // function: String, + // }, External(String), } diff --git a/test-data/function.wgsl b/test-data/function.wgsl new file mode 100644 index 000000000..7252e1cd1 --- /dev/null +++ b/test-data/function.wgsl @@ -0,0 +1,12 @@ +import "GLSL.std.450" as std::glsl; + +fn test_function(test: f32) -> f32 { + return test; +} + +fn main_vert() -> void { + var foo: f32 = std::glsl::distance(0.0, 1.0); + var test: f32 = test_function(1.0); +} + +entry_point vertex as "main" = main_vert; \ No newline at end of file From e9d00d38a4efb72a52ccf980c18a8127694a308d Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Fri, 21 Aug 2020 00:41:14 -0400 Subject: [PATCH 0151/2212] Make "None" interpolation mean default or nothing, depending on context (#146) * Make no interpolation mean default or nothing, depending on context * Re-add Interpolation::Perspective --- src/front/glsl/mod.rs | 15 +++++---------- src/front/glsl_new/parser.rs | 5 ----- src/front/spv.rs | 7 +------ src/front/wgsl.rs | 15 +++++++-------- src/lib.rs | 5 +++-- 5 files changed, 16 insertions(+), 31 deletions(-) diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 43986531d..888e9b63c 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1174,7 +1174,7 @@ impl<'a> Parser<'a> { ) -> (StorageClass, Option, Option) { let mut storage = None; let mut binding = None; - let mut interpolation = Interpolation::Perspective; + let mut interpolation = None; for qualifier in qualifier.qualifiers { match qualifier { @@ -1243,25 +1243,20 @@ impl<'a> Parser<'a> { } } TypeQualifierSpec::Interpolation(interpolation_qualifier) => { - interpolation = match interpolation_qualifier { + interpolation = Some(match interpolation_qualifier { InterpolationQualifier::NoPerspective => Interpolation::Linear, InterpolationQualifier::Flat => Interpolation::Flat, InterpolationQualifier::Smooth => Interpolation::Perspective, - } + }); } _ => unimplemented!(), } } - let class = storage.unwrap_or(StorageClass::Private); - ( - class, + storage.unwrap_or(StorageClass::Private), binding, - match class { - StorageClass::Input | StorageClass::Output => Some(interpolation), - _ => None, - }, + interpolation, ) } } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 7ecd92301..6b7d99c4f 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -743,11 +743,6 @@ pomelo! { let interpolation = d.type_qualifiers.iter().find_map(|tq| { if let TypeQualifier::Interpolation(i) = tq { Some(*i) } else { None } - }).or_else(|| match class { - StorageClass::Input | StorageClass::Output => { - Some(Interpolation::Perspective) - } - _ => None, }); for (id, initializer) in d.ids_initializers { diff --git a/src/front/spv.rs b/src/front/spv.rs index 1b880a92b..e98c14ef3 100644 --- a/src/front/spv.rs +++ b/src/front/spv.rs @@ -2008,12 +2008,7 @@ impl> Parser { class, binding, ty, - interpolation: dec.interpolation.or_else(|| match class { - crate::StorageClass::Input | crate::StorageClass::Output => { - Some(crate::Interpolation::Perspective) - } - _ => None, - }), + interpolation: dec.interpolation, }; self.lookup_variable.insert( id, diff --git a/src/front/wgsl.rs b/src/front/wgsl.rs index 4c3fa5453..a2cd5b3d8 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl.rs @@ -508,6 +508,7 @@ impl Parser { "flat" => Ok(crate::Interpolation::Flat), "centroid" => Ok(crate::Interpolation::Centroid), "sample" => Ok(crate::Interpolation::Sample), + "perspective" => Ok(crate::Interpolation::Perspective), _ => Err(Error::UnknownDecoration(word)), } } @@ -1557,7 +1558,7 @@ impl Parser { // read decorations let mut binding = None; // Perspective is the default qualifier. - let mut interpolation = crate::Interpolation::Perspective; + let mut interpolation = None; if lexer.skip(Token::DoubleParen('[')) { let (mut bind_index, mut bind_set) = (None, None); self.scopes.push(Scope::Decoration); @@ -1578,7 +1579,10 @@ impl Parser { bind_set = Some(lexer.next_uint_literal()?); } "interpolate" => { - interpolation = Self::get_interpolation(lexer.next_ident()?)?; + if interpolation.is_some() { + return Err(Error::UnknownDecoration(lexer.next_ident()?)); + } + interpolation = Some(Self::get_interpolation(lexer.next_ident()?)?); } word => return Err(Error::UnknownDecoration(word)), } @@ -1667,12 +1671,7 @@ impl Parser { class, binding: binding.take(), ty, - interpolation: match class { - crate::StorageClass::Input | crate::StorageClass::Output => { - Some(interpolation) - } - _ => None, - }, + interpolation, }); lookup_global_expression .insert(name, crate::Expression::GlobalVariable(var_handle)); diff --git a/src/lib.rs b/src/lib.rs index 753ebf7fb..e45ca820f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -341,8 +341,9 @@ pub struct GlobalVariable { /// The type of this variable. pub ty: Handle, /// The interpolation qualifier, if any. - /// Required for global outputs in vertex shaders - /// and global inputs in fragment shaders. + /// If the this `GlobalVariable` is a vertex output + /// or fragment input, `None` corresponds to the + /// `smooth`/`perspective` interpolation qualifier. pub interpolation: Option, } From cf39a88f215e57589c5235be3bad3f42fdfa2093 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Fri, 21 Aug 2020 16:13:36 +0200 Subject: [PATCH 0152/2212] [glsl-new] match wgsl expression order (#147) --- src/front/glsl_new/ast.rs | 10 ++++++---- src/front/glsl_new/parser.rs | 37 ++++++++++++++++++++++++++---------- 2 files changed, 33 insertions(+), 14 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 26b49534f..32d5e8df9 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -35,6 +35,7 @@ impl Program { expressions: Arena::::new(), local_variables: Arena::::new(), scopes: vec![FastHashMap::default()], + lookup_global_var_exps: FastHashMap::default(), }, } } @@ -50,11 +51,12 @@ pub struct Context { pub expressions: Arena, pub local_variables: Arena, //TODO: Find less allocation heavy representation - pub scopes: Vec>>, + pub scopes: Vec>>, + pub lookup_global_var_exps: FastHashMap>, } impl Context { - pub fn lookup_local_var(&self, name: &str) -> Option> { + pub fn lookup_local_var(&self, name: &str) -> Option> { for scope in self.scopes.iter().rev() { if let Some(var) = scope.get(name) { return Some(*var); @@ -64,7 +66,7 @@ impl Context { } #[cfg(feature = "glsl-validate")] - pub fn lookup_local_var_current_scope(&self, name: &str) -> Option> { + pub fn lookup_local_var_current_scope(&self, name: &str) -> Option> { if let Some(current) = self.scopes.last() { current.get(name).cloned() } else { @@ -78,7 +80,7 @@ impl Context { } /// Add variable to current scope - pub fn add_local_var(&mut self, name: String, handle: Handle) { + pub fn add_local_var(&mut self, name: String, handle: Handle) { if let Some(current) = self.scopes.last_mut() { (*current).insert(name, handle); } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 6b7d99c4f..ae4443bb1 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -156,23 +156,27 @@ pomelo! { interpolation: None, }, ); - extra.lookup_global_variables.insert(v.1, h); + extra.lookup_global_variables.insert(v.1.clone(), h); + let expression = extra.context.expressions.append( + Expression::GlobalVariable(h) + ); + extra.context.lookup_global_var_exps.insert(v.1, expression); ExpressionRule{ - expression: extra.context.expressions.append(Expression::GlobalVariable(h)), + expression, statements: vec![], } } else { // try global and local vars - let expr = + let expression = if let Some(local_var) = extra.context.lookup_local_var(&v.1) { - Expression::LocalVariable(local_var) - } else if let Some(global_var) = extra.lookup_global_variables.get(&v.1) { - Expression::GlobalVariable(*global_var) + local_var + } else if let Some(global_var) = extra.context.lookup_global_var_exps.get(&v.1) { + *global_var } else { return Err(ErrorKind::UnknownVariable(v.0, v.1)) }; ExpressionRule{ - expression: extra.context.expressions.append(expr), + expression, statements: vec![], } } @@ -565,7 +569,7 @@ pomelo! { if extra.context.lookup_local_var_current_scope(&id).is_some() { return Err(ErrorKind::VariableAlreadyDeclared(id)) } - let h = extra.context.local_variables.append( + let localVar = extra.context.local_variables.append( LocalVariable { name: Some(id.clone()), ty: d.ty, @@ -575,7 +579,8 @@ pomelo! { }), } ); - extra.context.add_local_var(id, h); + let exp = extra.context.expressions.append(Expression::LocalVariable(localVar)); + extra.context.add_local_var(id, exp); } match statements.len() { 0 => Statement::Empty, @@ -626,7 +631,18 @@ pomelo! { // function - function_prototype ::= function_declarator(f) RightParen {f} + function_prototype ::= function_declarator(f) RightParen { + // prelude, add global var expressions + for (var_handle, var) in extra.global_variables.iter() { + if let Some(name) = var.name.as_ref() { + let exp = extra.context.expressions.append( + Expression::GlobalVariable(var_handle) + ); + extra.context.lookup_global_var_exps.insert(name.clone(), exp); + } + } + f + } function_declarator ::= function_header; function_header ::= fully_specified_type(t) Identifier(n) LeftParen { Function { @@ -763,6 +779,7 @@ pomelo! { std::mem::swap(&mut f.expressions, &mut extra.context.expressions); std::mem::swap(&mut f.local_variables, &mut extra.context.local_variables); extra.context.clear_scopes(); + extra.context.lookup_global_var_exps.clear(); f.body = cs; f.global_usage = crate::GlobalUse::scan(&f.expressions, &f.body, &extra.global_variables); f From 5d9489871d95610029243ef1ef18fe0764877540 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 22 Aug 2020 15:50:54 +0100 Subject: [PATCH 0153/2212] Add support for glsl es in the glsl backend (#128) * Initial glsl es 300 support * Set float default precision * Generate interface blocks and check storage class in es * Added more checks on es and fixed uniform blocks with same name type * Added image checks * Added the test to the makefile * applied comments --- Makefile | 14 +- examples/convert.rs | 22 +- src/back/glsl.rs | 559 ++++++++++++++++++++++++++++++++++---------- 3 files changed, 470 insertions(+), 125 deletions(-) diff --git a/Makefile b/Makefile index 89a899515..f4ecbca40 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ all: clean: - rm *.metal *.air *.metallib + rm *.metal *.air *.metallib *.vert *.frag *.comp %.metal: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) cargo run --example convert -- $< $@ @@ -14,3 +14,15 @@ clean: %.metallib: %.air xcrun -sdk macosx metallib $< -o $@ + +%.vert: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) + cargo run --example convert --features glsl-out -- $< $@ + +%.frag: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) + cargo run --example convert --features glsl-out -- $< $@ + +%.comp: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) + cargo run --example convert --features glsl-out -- $< $@ + +%.glsl_validate: %.vert %.frag %.comp + glslangValidator $< diff --git a/examples/convert.rs b/examples/convert.rs index ab47a0375..1fb5f428d 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -189,8 +189,11 @@ fn main() { fs::write(&args[2], bytes.as_slice()).unwrap(); } #[cfg(feature = "glsl-out")] - "vert" | "frag" => { - use naga::back::glsl; + stage @ "vert" | stage @ "frag" | stage @ "comp" => { + use naga::{ + back::glsl::{self, Options, Version}, + ShaderStage, + }; let mut file = fs::OpenOptions::new() .write(true) @@ -199,7 +202,20 @@ fn main() { .open(&args[2]) .unwrap(); - glsl::write(&module, &mut file).unwrap(); + let options = Options { + version: Version::Embedded(310), + entry_point: ( + String::from("main"), + match stage { + "vert" => ShaderStage::Vertex, + "frag" => ShaderStage::Fragment, + "comp" => ShaderStage::Compute, + _ => unreachable!(), + }, + ), + }; + + glsl::write(&module, &mut file, options).unwrap(); } #[cfg(feature = "serialize")] "ron" => { diff --git a/src/back/glsl.rs b/src/back/glsl.rs index fdd0a32bb..d41c0952a 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,8 +1,8 @@ use crate::{ Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageFlags, Interpolation, - IntrinsicFunction, LocalVariable, Module, ScalarKind, Statement, StorageClass, Type, TypeInner, - UnaryOperator, + IntrinsicFunction, LocalVariable, Module, ScalarKind, ShaderStage, Statement, StorageClass, + StructMember, Type, TypeInner, UnaryOperator, }; use std::{ borrow::Cow, @@ -39,26 +39,126 @@ impl fmt::Display for Error { } } -pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { - writeln!(out, "#version 450 core")?; +#[derive(Debug, Copy, Clone, PartialEq)] +pub enum Version { + Desktop(u16), + Embedded(u16), +} + +impl fmt::Display for Version { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Version::Desktop(v) => write!(f, "{} core", v), + Version::Embedded(v) => write!(f, "{} es", v), + } + } +} + +#[derive(Debug, Clone)] +pub struct Options { + pub version: Version, + pub entry_point: (String, ShaderStage), +} + +const SUPPORTED_CORE_VERSIONS: &[u16] = &[450, 460]; +const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310]; + +bitflags::bitflags! { + struct SupportedFeatures: u32 { + const BUFFER_STORAGE = 1; + const SHARED_STORAGE = 1 << 1; + const SEPARATE_IMAGE_SAMPLER = 1 << 2; + const DOUBLE_TYPE = 1 << 3; + const NON_FLOAT_MATRICES = 1 << 4; + const MULTISAMPLED_TEXTURES = 1 << 5; + const MULTISAMPLED_TEXTURE_ARRAYS = 1 << 6; + const NON_2D_TEXTURE_ARRAYS = 1 << 7; + } +} + +pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> Result<(), Error> { + let (version, es) = match options.version { + Version::Desktop(v) => (v, false), + Version::Embedded(v) => (v, true), + }; + + if (!es && !SUPPORTED_CORE_VERSIONS.contains(&version)) + || (es && !SUPPORTED_ES_VERSIONS.contains(&version)) + { + return Err(Error::Custom(format!( + "Version not supported {}", + options.version + ))); + } + + writeln!(out, "#version {}", options.version)?; + + if es { + writeln!(out, "precision highp float;")?; + } let mut counter = 0; let mut names = FastHashMap::default(); - let mut namer = |name: Option<&String>| { + let mut namer = |name: Option<&'a String>| { if let Some(name) = name { - names.insert(name.clone(), ()); - name.clone() + if name.starts_with("gl_") || name == "main" || names.get(name.as_str()).is_some() { + counter += 1; + while names.get(format!("_{}", counter).as_str()).is_some() { + counter += 1; + } + format!("_{}", counter) + } else { + names.insert(name.as_str(), ()); + name.clone() + } } else { counter += 1; - while names.get(&format!("_{}", counter)).is_some() { + while names.get(format!("_{}", counter).as_str()).is_some() { counter += 1; } format!("_{}", counter) } }; + let entry_point = module + .entry_points + .iter() + .find(|entry| entry.name == options.entry_point.0 && entry.stage == options.entry_point.1) + .ok_or_else(|| Error::Custom(String::from("Entry point not found")))?; + let func = &module.functions[entry_point.function]; + + if entry_point.stage == ShaderStage::Compute { + if (es && version < 310) || (!es && version < 430) { + return Err(Error::Custom(format!( + "Version {} doesn't support compute shaders", + options.version + ))); + } + + if !es && version < 460 { + writeln!(out, "#extension ARB_compute_shader : require")?; + } + } + + let mut features = SupportedFeatures::empty(); + + if !es && version > 440 { + features |= SupportedFeatures::SEPARATE_IMAGE_SAMPLER; + features |= SupportedFeatures::DOUBLE_TYPE; + features |= SupportedFeatures::NON_FLOAT_MATRICES; + features |= SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS; + features |= SupportedFeatures::NON_2D_TEXTURE_ARRAYS; + } + + if !es || version > 300 { + features |= SupportedFeatures::BUFFER_STORAGE; + features |= SupportedFeatures::SHARED_STORAGE; + features |= SupportedFeatures::MULTISAMPLED_TEXTURES; + } + let mut structs = FastHashMap::default(); + let mut built_structs = FastHashMap::default(); // Do a first pass to collect names for (handle, ty) in module.types.iter() { @@ -72,23 +172,40 @@ pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { } } + for ((_, global), usage) in module.global_variables.iter().zip(func.global_usage.iter()) { + if usage.is_empty() { + continue; + } + + let block = matches!( + global.class, + StorageClass::Input + | StorageClass::Output + | StorageClass::StorageBuffer + | StorageClass::Uniform + ); + + match module.types[global.ty].inner { + TypeInner::Struct { .. } if block => { + built_structs.insert(global.ty, ()); + } + _ => {} + } + } + // Do a second pass to build the structs - // TODO: glsl is order dependent so we need to build structs in order for (handle, ty) in module.types.iter() { match ty.inner { TypeInner::Struct { ref members } => { - let name = structs.get(&handle).unwrap(); - - writeln!(out, "struct {} {{", name)?; - for (idx, member) in members.iter().enumerate() { - writeln!( - out, - " {} {};", - write_type(member.ty, &module.types, &structs)?, - member.name.clone().unwrap_or_else(|| idx.to_string()) - )?; - } - writeln!(out, "}};")?; + write_struct( + handle, + members, + module, + &structs, + out, + &mut built_structs, + features, + )?; } _ => continue, } @@ -96,10 +213,14 @@ pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { let mut globals_lookup = FastHashMap::default(); - for (handle, global) in module.global_variables.iter() { + for ((handle, global), usage) in module.global_variables.iter().zip(func.global_usage.iter()) { + if usage.is_empty() { + continue; + } + if let Some(crate::Binding::BuiltIn(built_in)) = global.binding { let semantic = match built_in { - BuiltIn::Position => "gl_position", + BuiltIn::Position => "gl_Position", BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", BuiltIn::BaseInstance => "gl_BaseInstance", BuiltIn::BaseVertex => "gl_BaseVertex", @@ -120,21 +241,42 @@ pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { continue; } + let name = if !es { + namer(global.name.as_ref()) + } else { + global.name.clone().ok_or_else(|| { + Error::Custom(String::from("Global names must be specified in es")) + })? + }; + if let Some(ref binding) = global.binding { - write!(out, "layout({}) ", Binding(binding.clone()))?; + if !es { + write!(out, "layout({}) ", Binding(binding.clone()))?; + } } if let Some(interpolation) = global.interpolation { - write!(out, "{} ", write_interpolation(interpolation)?)?; + if (entry_point.stage == ShaderStage::Fragment && global.class == StorageClass::Input) + || (entry_point.stage == ShaderStage::Vertex + && global.class == StorageClass::Output) + { + write!(out, "{} ", write_interpolation(interpolation)?)?; + } } - let name = namer(global.name.as_ref()); + let block = match global.class { + StorageClass::Input + | StorageClass::Output + | StorageClass::StorageBuffer + | StorageClass::Uniform => Some(namer(None)), + _ => None, + }; writeln!( out, "{}{} {};", - write_storage_class(global.class)?, - write_type(global.ty, &module.types, &structs)?, + write_storage_class(global.class, features)?, + write_type(global.ty, &module.types, &structs, block, features)?, name )?; @@ -143,28 +285,57 @@ pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { let mut functions = FastHashMap::default(); - // Do a first pass to collect names for (handle, func) in module.functions.iter() { - functions.insert(handle, namer(func.name.as_ref())); + // Discard all entry points + if entry_point.function != handle + && module + .entry_points + .iter() + .any(|entry| entry.function == handle) + { + continue; + } + + let name = if entry_point.function != handle { + namer(func.name.as_ref()) + } else { + String::from("main") + }; + + writeln!( + out, + "{} {}({});", + func.return_type + .map(|ty| write_type(ty, &module.types, &structs, None, features)) + .transpose()? + .as_deref() + .unwrap_or("void"), + name, + func.parameter_types + .iter() + .map(|ty| write_type(*ty, &module.types, &structs, None, features)) + .collect::, _>>()? + .join(","), + )?; + + functions.insert(handle, name); } - // TODO: glsl is order dependent so we need to build functions in order - for (handle, func) in module.functions.iter() { - let name = functions.get(&handle).unwrap(); + for (handle, name) in functions.iter() { + let func = &module.functions[*handle]; writeln!( out, "{} {}({}) {{", func.return_type - .map_or(Ok(String::from("void")), |ty| write_type( - ty, - &module.types, - &structs - ))?, + .map(|ty| write_type(ty, &module.types, &structs, None, features)) + .transpose()? + .as_deref() + .unwrap_or("void"), name, func.parameter_types .iter() - .map(|ty| write_type(*ty, &module.types, &structs)) + .map(|ty| write_type(*ty, &module.types, &structs, None, features)) .collect::, _>>()? .join(","), )?; @@ -175,6 +346,21 @@ pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { .map(|(handle, local)| (handle, namer(local.name.as_ref()))) .collect(); + for (handle, name) in locals.iter() { + writeln!( + out, + "{} {};", + write_type( + func.local_variables[*handle].ty, + &module.types, + &structs, + None, + features + )?, + name + )?; + } + let mut builder = StatementBuilder { functions: &functions, globals: &globals_lookup, @@ -188,24 +374,9 @@ pub fn write(module: &Module, out: &mut impl Write) -> Result<(), Error> { .collect(), expressions: &func.expressions, locals: &func.local_variables, + features, }; - for (handle, name) in locals.iter() { - let ty = write_type(func.local_variables[*handle].ty, &module.types, &structs)?; - let init = func.local_variables[*handle].init; - if let Some(init) = init { - writeln!( - out, - "{} {} = {init};", - ty, - name, - init = write_expression(&func.expressions[init], &module, &mut builder)?.0, - )?; - } else { - writeln!(out, "{} {};", ty, name,)?; - } - } - for sta in func.body.iter() { writeln!(out, "{}", write_statement(sta, module, &mut builder)?)?; } @@ -237,6 +408,7 @@ struct StatementBuilder<'a> { pub args: &'a FastHashMap)>, pub expressions: &'a Arena, pub locals: &'a Arena, + pub features: SupportedFeatures, } fn write_statement( @@ -398,7 +570,12 @@ fn write_expression<'a>( } } Expression::Constant(constant) => ( - write_constant(&module.constants[*constant], module, builder)?, + write_constant( + &module.constants[*constant], + module, + builder, + builder.features, + )?, Cow::Borrowed(&module.types[module.constants[*constant].ty].inner), ), Expression::Compose { ty, components } => { @@ -445,12 +622,15 @@ fn write_expression<'a>( columns as u8, rows as u8, ), - TypeInner::Array { .. } => write_type(*ty, &module.types, builder.structs)?, + TypeInner::Array { .. } => { + write_type(*ty, &module.types, builder.structs, None, builder.features)? + .into_owned() + } TypeInner::Struct { .. } => builder.structs.get(ty).unwrap().clone(), _ => { return Err(Error::Custom(format!( "Cannot compose type {}", - write_type(*ty, &module.types, builder.structs)? + write_type(*ty, &module.types, builder.structs, None, builder.features)? ))) } }; @@ -514,7 +694,13 @@ fn write_expression<'a>( _ => { return Err(Error::Custom(format!( "Cannot build image of {}", - write_type(*base, &module.types, builder.structs)? + write_type( + *base, + &module.types, + builder.structs, + None, + builder.features + )? ))) } }, @@ -751,10 +937,11 @@ fn write_constant( constant: &Constant, module: &Module, builder: &StatementBuilder<'_>, + features: SupportedFeatures, ) -> Result { Ok(match constant.inner { ConstantInner::Sint(int) => int.to_string(), - ConstantInner::Uint(int) => int.to_string(), + ConstantInner::Uint(int) => format!("{}u", int), ConstantInner::Float(float) => format!("{:?}", float), ConstantInner::Bool(boolean) => boolean.to_string(), ConstantInner::Composite(ref components) => format!( @@ -764,34 +951,43 @@ fn write_constant( TypeInner::Matrix { columns, rows, .. } => format!("mat{}x{}", columns as u8, rows as u8,), TypeInner::Struct { .. } => builder.structs.get(&constant.ty).unwrap().clone(), - TypeInner::Array { .. } => write_type(constant.ty, &module.types, builder.structs)?, + TypeInner::Array { .. } => + write_type(constant.ty, &module.types, builder.structs, None, features)? + .into_owned(), _ => return Err(Error::Custom(format!( "Cannot build constant of type {}", - write_type(constant.ty, &module.types, builder.structs)? + write_type(constant.ty, &module.types, builder.structs, None, features)? ))), }, components .iter() - .map(|component| write_constant(&module.constants[*component], module, builder)) + .map(|component| write_constant( + &module.constants[*component], + module, + builder, + features + )) .collect::, _>>()? .join(","), ), }) } -fn write_type<'a>( +fn write_type( ty: Handle, - types: &'a Arena, - structs: &'a FastHashMap, String>, -) -> Result { + types: &Arena, + structs: &FastHashMap, String>, + block: Option, + features: SupportedFeatures, +) -> Result, Error> { Ok(match types[ty].inner { TypeInner::Scalar { kind, width } => match kind { - ScalarKind::Sint => String::from("int"), - ScalarKind::Uint => String::from("uint"), + ScalarKind::Sint => Cow::Borrowed("int"), + ScalarKind::Uint => Cow::Borrowed("uint"), ScalarKind::Float => match width { - 4 => String::from("float"), - 8 => String::from("double"), + 4 => Cow::Borrowed("float"), + 8 if features.contains(SupportedFeatures::DOUBLE_TYPE) => Cow::Borrowed("double"), _ => { return Err(Error::Custom(format!( "Cannot build float of width {}", @@ -799,16 +995,16 @@ fn write_type<'a>( ))) } }, - ScalarKind::Bool => String::from("bool"), + ScalarKind::Bool => Cow::Borrowed("bool"), }, - TypeInner::Vector { size, kind, width } => format!( + TypeInner::Vector { size, kind, width } => Cow::Owned(format!( "{}vec{}", match kind { ScalarKind::Sint => "i", ScalarKind::Uint => "u", ScalarKind::Float => match width { 4 => "", - 8 => "d", + 8 if features.contains(SupportedFeatures::DOUBLE_TYPE) => "d", _ => return Err(Error::Custom(format!( "Cannot build float of width {}", @@ -818,65 +1014,104 @@ fn write_type<'a>( ScalarKind::Bool => "b", }, size as u8 - ), + )), TypeInner::Matrix { columns, rows, kind, width, - } => format!( + } => Cow::Owned(format!( "{}mat{}x{}", match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", + ScalarKind::Sint if features.contains(SupportedFeatures::NON_FLOAT_MATRICES) => "i", + ScalarKind::Uint if features.contains(SupportedFeatures::NON_FLOAT_MATRICES) => "u", ScalarKind::Float => match width { 4 => "", - 8 => "d", + 8 if features.contains( + SupportedFeatures::DOUBLE_TYPE & SupportedFeatures::NON_FLOAT_MATRICES + ) => + "d", _ => return Err(Error::Custom(format!( "Cannot build float of width {}", width ))), }, - ScalarKind::Bool => "b", + ScalarKind::Bool if features.contains(SupportedFeatures::NON_FLOAT_MATRICES) => "b", + _ => + return Err(Error::Custom(format!( + "Cannot build matrix of base type {:?}", + kind + ))), }, columns as u8, rows as u8 - ), - TypeInner::Pointer { base, .. } => write_type(base, types, structs)?, - TypeInner::Array { base, size, .. } => format!( + )), + TypeInner::Pointer { base, .. } => write_type(base, types, structs, None, features)?, + TypeInner::Array { base, size, .. } => Cow::Owned(format!( "{}[{}]", - write_type(base, types, structs)?, + write_type(base, types, structs, None, features)?, write_array_size(size)? - ), - TypeInner::Struct { .. } => structs.get(&ty).unwrap().clone(), - TypeInner::Image { base, dim, flags } => format!( - "{}texture{}{}", - match types[base].inner { - TypeInner::Scalar { kind, .. } => match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => "", + )), + TypeInner::Struct { ref members } => { + if let Some(name) = block { + let mut out = String::new(); + writeln!(&mut out, "{} {{", name)?; + + for (idx, member) in members.iter().enumerate() { + writeln!( + &mut out, + "{} {};", + write_type(member.ty, types, structs, None, features)?, + member.name.clone().unwrap_or_else(|| idx.to_string()) + )?; + } + + write!(&mut out, "}}")?; + + Cow::Owned(out) + } else { + Cow::Owned(structs.get(&ty).unwrap().clone()) + } + } + TypeInner::Image { base, dim, flags } => { + if flags.contains(ImageFlags::ARRAYED) + && dim != crate::ImageDimension::D2 + && !features.contains(SupportedFeatures::NON_2D_TEXTURE_ARRAYS) + { + return Err(Error::Custom(String::from( + "Arrayed non 2d images aren't supported", + ))); + } + + Cow::Owned(format!( + "{}texture{}{}", + match types[base].inner { + TypeInner::Scalar { kind, .. } => match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => "", + ScalarKind::Bool => + return Err(Error::Custom(String::from( + "Cannot build image of booleans", + ))), + }, _ => - return Err(Error::Custom(String::from( - "Cannot build image of booleans", + return Err(Error::Custom(format!( + "Cannot build image of type {}", + write_type(base, types, structs, block, features)? ))), }, - _ => - return Err(Error::Custom(format!( - "Cannot build image of type {}", - write_type(base, types, structs)? - ))), - }, - ImageDimension(dim), - write_image_flags(flags)? - ), - TypeInner::DepthImage { dim, arrayed } => format!( + ImageDimension(dim), + write_image_flags(flags, features)? + )) + } + TypeInner::DepthImage { dim, arrayed } => Cow::Owned(format!( "texture{}{}", ImageDimension(dim), if arrayed { "Array" } else { "" } - ), - TypeInner::Sampler { comparison } => String::from(if comparison { + )), + TypeInner::Sampler { comparison } => Cow::Borrowed(if comparison { "sampler" } else { "samplerShadow" @@ -884,17 +1119,36 @@ fn write_type<'a>( }) } -fn write_storage_class(class: StorageClass) -> Result { - Ok(String::from(match class { +fn write_storage_class( + class: StorageClass, + features: SupportedFeatures, +) -> Result<&'static str, Error> { + Ok(match class { StorageClass::Constant => "const ", StorageClass::Function => "", StorageClass::Input => "in ", StorageClass::Output => "out ", StorageClass::Private => "", - StorageClass::StorageBuffer => "buffer ", + StorageClass::StorageBuffer => { + if features.contains(SupportedFeatures::BUFFER_STORAGE) { + "buffer " + } else { + return Err(Error::Custom(String::from( + "buffer storage class isn't supported in glsl es", + ))); + } + } StorageClass::Uniform => "uniform ", - StorageClass::WorkGroup => "shared ", - })) + StorageClass::WorkGroup => { + if features.contains(SupportedFeatures::SHARED_STORAGE) { + "shared " + } else { + return Err(Error::Custom(String::from( + "workgroup storage class isn't supported in glsl es", + ))); + } + } + }) } fn write_interpolation(interpolation: Interpolation) -> Result<&'static str, Error> { @@ -919,18 +1173,34 @@ fn write_array_size(size: ArraySize) -> Result { }) } -fn write_image_flags(flags: ImageFlags) -> Result { - let mut out = String::new(); +fn write_image_flags(flags: ImageFlags, features: SupportedFeatures) -> Result { + let ms = if flags.contains(ImageFlags::MULTISAMPLED) { + if features.contains(SupportedFeatures::MULTISAMPLED_TEXTURES) { + "MS" + } else { + return Err(Error::Custom(String::from( + "Multi sampled textures aren't supported", + ))); + } + } else { + "" + }; - if flags.contains(ImageFlags::MULTISAMPLED) { - write!(out, "MS")?; + let array = if flags.contains(ImageFlags::ARRAYED) { + "Array" + } else { + "" + }; + + if flags.contains(ImageFlags::ARRAYED & ImageFlags::MULTISAMPLED) + && !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS) + { + return Err(Error::Custom(String::from( + "Multi sampled texture arrays aren't supported", + ))); } - if flags.contains(ImageFlags::ARRAYED) { - write!(out, "Array")?; - } - - Ok(out) + Ok(format!("{}{}", ms, array)) } struct ImageDimension(crate::ImageDimension); @@ -948,3 +1218,50 @@ impl fmt::Display for ImageDimension { ) } } + +fn write_struct( + handle: Handle, + members: &[StructMember], + module: &Module, + structs: &FastHashMap, String>, + out: &mut impl Write, + built_structs: &mut FastHashMap, ()>, + features: SupportedFeatures, +) -> Result<(), Error> { + if built_structs.get(&handle).is_some() { + return Ok(()); + } + + let mut tmp = String::new(); + + let name = structs.get(&handle).unwrap(); + + writeln!(&mut tmp, "struct {} {{", name)?; + for (idx, member) in members.iter().enumerate() { + if let TypeInner::Struct { ref members } = module.types[member.ty].inner { + write_struct( + member.ty, + members, + module, + structs, + out, + built_structs, + features, + )?; + } + + writeln!( + &mut tmp, + " {} {};", + write_type(member.ty, &module.types, &structs, None, features)?, + member.name.clone().unwrap_or_else(|| idx.to_string()) + )?; + } + writeln!(&mut tmp, "}};")?; + + built_structs.insert(handle, ()); + + writeln!(out, "{}", tmp)?; + + Ok(()) +} From c12c9a9faceda2fe46ade27f11accf0e6b229c13 Mon Sep 17 00:00:00 2001 From: Matus Talcik Date: Mon, 24 Aug 2020 05:14:51 +0200 Subject: [PATCH 0154/2212] init control flow graph (#122) format major refactor Change spirv to spirv_headers Remove files First translation to naga + format Fix Int Constant error Don't add unnecessary blocks. Some cleanups format remove constructs docs fix debug leftovers format, clippy satisfy clippy --- Cargo.toml | 2 + src/front/mod.rs | 2 +- src/front/spv/convert.rs | 75 ++++++ src/front/spv/error.rs | 52 ++++ src/front/spv/flow.rs | 404 +++++++++++++++++++++++++++++++ src/front/spv/function.rs | 163 +++++++++++++ src/front/{spv.rs => spv/mod.rs} | 368 +++++++++------------------- 7 files changed, 814 insertions(+), 252 deletions(-) create mode 100644 src/front/spv/convert.rs create mode 100644 src/front/spv/error.rs create mode 100644 src/front/spv/flow.rs create mode 100644 src/front/spv/function.rs rename src/front/{spv.rs => spv/mod.rs} (89%) diff --git a/Cargo.toml b/Cargo.toml index ee33f41c7..3939aa9a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ glsl = { version = "4.1", optional = true } pomelo = { version = "0.1.4", optional = true } thiserror = "1.0" serde = { version = "1.0", features = ["derive"], optional = true } +petgraph = { version ="0.5", optional = true } [features] default = [] @@ -28,6 +29,7 @@ glsl-validate = [] glsl-out = [] serialize = ["serde"] deserialize = ["serde"] +spirv-in = ["petgraph", "spirv"] [dev-dependencies] env_logger = "0.6" diff --git a/src/front/mod.rs b/src/front/mod.rs index 7e169017a..ec4c36cf0 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -4,7 +4,7 @@ pub mod glsl; #[cfg(feature = "glsl-new")] pub mod glsl_new; -#[cfg(feature = "spirv")] +#[cfg(feature = "spirv-in")] pub mod spv; pub mod wgsl; diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs new file mode 100644 index 000000000..6329975e4 --- /dev/null +++ b/src/front/spv/convert.rs @@ -0,0 +1,75 @@ +use super::error::Error; +use num_traits::cast::FromPrimitive; +use std::convert::TryInto; + +pub fn map_binary_operator(word: spirv::Op) -> Result { + use crate::BinaryOperator; + use spirv::Op; + + match word { + // Arithmetic Instructions +, -, *, /, % + Op::IAdd | Op::FAdd => Ok(BinaryOperator::Add), + Op::ISub | Op::FSub => Ok(BinaryOperator::Subtract), + Op::IMul | Op::FMul => Ok(BinaryOperator::Multiply), + Op::UDiv | Op::SDiv | Op::FDiv => Ok(BinaryOperator::Divide), + Op::UMod | Op::SMod | Op::FMod => Ok(BinaryOperator::Modulo), + // Relational and Logical Instructions + Op::IEqual | Op::FOrdEqual | Op::FUnordEqual => Ok(BinaryOperator::Equal), + Op::INotEqual | Op::FOrdNotEqual | Op::FUnordNotEqual => Ok(BinaryOperator::NotEqual), + Op::ULessThan | Op::SLessThan | Op::FOrdLessThan | Op::FUnordLessThan => { + Ok(BinaryOperator::Less) + } + Op::ULessThanEqual + | Op::SLessThanEqual + | Op::FOrdLessThanEqual + | Op::FUnordLessThanEqual => Ok(BinaryOperator::LessEqual), + Op::UGreaterThan | Op::SGreaterThan | Op::FOrdGreaterThan | Op::FUnordGreaterThan => { + Ok(BinaryOperator::Greater) + } + Op::UGreaterThanEqual + | Op::SGreaterThanEqual + | Op::FOrdGreaterThanEqual + | Op::FUnordGreaterThanEqual => Ok(BinaryOperator::GreaterEqual), + _ => Err(Error::UnknownInstruction(word as u16)), + } +} + +pub fn map_vector_size(word: spirv::Word) -> Result { + match word { + 2 => Ok(crate::VectorSize::Bi), + 3 => Ok(crate::VectorSize::Tri), + 4 => Ok(crate::VectorSize::Quad), + _ => Err(Error::InvalidVectorSize(word)), + } +} + +pub fn map_storage_class(word: spirv::Word) -> Result { + use spirv::StorageClass as Sc; + match Sc::from_u32(word) { + Some(Sc::UniformConstant) => Ok(crate::StorageClass::Constant), + Some(Sc::Function) => Ok(crate::StorageClass::Function), + Some(Sc::Input) => Ok(crate::StorageClass::Input), + Some(Sc::Output) => Ok(crate::StorageClass::Output), + Some(Sc::Private) => Ok(crate::StorageClass::Private), + Some(Sc::StorageBuffer) => Ok(crate::StorageClass::StorageBuffer), + Some(Sc::Uniform) => Ok(crate::StorageClass::Uniform), + Some(Sc::Workgroup) => Ok(crate::StorageClass::WorkGroup), + _ => Err(Error::UnsupportedStorageClass(word)), + } +} + +pub fn map_image_dim(word: spirv::Word) -> Result { + match spirv::Dim::from_u32(word) { + Some(spirv::Dim::Dim1D) => Ok(crate::ImageDimension::D1), + Some(spirv::Dim::Dim2D) => Ok(crate::ImageDimension::D2), + Some(spirv::Dim::Dim3D) => Ok(crate::ImageDimension::D3), + Some(spirv::Dim::DimCube) => Ok(crate::ImageDimension::Cube), + _ => Err(Error::UnsupportedImageDim(word)), + } +} + +pub fn map_width(word: spirv::Word) -> Result { + (word >> 3) // bits to bytes + .try_into() + .map_err(|_| Error::InvalidTypeWidth(word)) +} diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs new file mode 100644 index 000000000..f4384cd89 --- /dev/null +++ b/src/front/spv/error.rs @@ -0,0 +1,52 @@ +use super::ModuleState; +use crate::arena::Handle; + +#[derive(Debug)] +pub enum Error { + InvalidHeader, + InvalidWordCount, + UnknownInstruction(u16), + UnknownCapability(spirv::Word), + UnsupportedInstruction(ModuleState, spirv::Op), + UnsupportedCapability(spirv::Capability), + UnsupportedExtension(String), + UnsupportedExtSet(String), + UnsupportedExtInstSet(spirv::Word), + UnsupportedExtInst(spirv::Word), + UnsupportedType(Handle), + UnsupportedExecutionModel(spirv::Word), + UnsupportedStorageClass(spirv::Word), + UnsupportedImageDim(spirv::Word), + UnsupportedBuiltIn(spirv::Word), + UnsupportedControlFlow(spirv::Word), + UnsupportedBinaryOperator(spirv::Word), + InvalidParameter(spirv::Op), + InvalidOperandCount(spirv::Op, u16), + InvalidOperand, + InvalidId(spirv::Word), + InvalidDecoration(spirv::Word), + InvalidTypeWidth(spirv::Word), + InvalidSign(spirv::Word), + InvalidInnerType(spirv::Word), + InvalidVectorSize(spirv::Word), + InvalidVariableClass(spirv::StorageClass), + InvalidAccessType(spirv::Word), + InvalidAccess(Handle), + InvalidAccessIndex(spirv::Word), + InvalidLoadType(spirv::Word), + InvalidStoreType(spirv::Word), + InvalidBinding(spirv::Word), + InvalidImageExpression(Handle), + InvalidSamplerExpression(Handle), + InvalidSampleImage(Handle), + InvalidSampleSampler(Handle), + InvalidSampleCoordinates(Handle), + InvalidDepthReference(Handle), + InconsistentComparisonSampling(Handle), + WrongFunctionResultType(spirv::Word), + WrongFunctionParameterType(spirv::Word), + MissingDecoration(spirv::Decoration), + BadString, + IncompleteData, + InvalidTerminator, +} diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs new file mode 100644 index 000000000..a2f35b846 --- /dev/null +++ b/src/front/spv/flow.rs @@ -0,0 +1,404 @@ +#![allow(dead_code)] + +use super::error::Error; +///! see https://en.wikipedia.org/wiki/Control-flow_graph +///! see https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#_a_id_structuredcontrolflow_a_structured_control_flow +use super::function::{BlockId, MergeInstruction, Terminator}; + +use crate::FastHashMap; + +use petgraph::{ + graph::{node_index, NodeIndex}, + visit::EdgeRef, + Directed, Direction, +}; + +use std::fmt::Write; + +/// Index of a block node in the `ControlFlowGraph`. +type BlockNodeIndex = NodeIndex; + +/// Internal representation of a CFG constisting of function's basic blocks. +type ControlFlowGraph = petgraph::Graph; + +/// Control flow graph (CFG) containing relationships between blocks. +pub struct FlowGraph { + /// + flow: ControlFlowGraph, + + /// Block ID to Node index mapping. Internal helper to speed up the classification. + block_to_node: FastHashMap, +} + +impl FlowGraph { + /// Creates empty flow graph. + pub fn new() -> Self { + Self { + flow: ControlFlowGraph::default(), + block_to_node: FastHashMap::default(), + } + } + + /// Add a control flow node. + pub fn add_node(&mut self, node: ControlFlowNode) { + let block_id = node.id; + let node_index = self.flow.add_node(node); + self.block_to_node.insert(block_id, node_index); + } + + /// + /// 1. Creates edges in the CFG. + /// 2. Classifies types of blocks and edges in the CFG. + pub fn classify(&mut self) { + let block_to_node = &mut self.block_to_node; + + // 1. + // Add all edges + // Classify Nodes as one of [Header, Loop, Kill, Return] + for source_node_index in self.flow.node_indices() { + // Merge edges + if let Some(merge) = self.flow[source_node_index].merge { + let merge_block_index = block_to_node[&merge.merge_block_id]; + + self.flow[source_node_index].ty = Some(ControlFlowNodeType::Header); + self.flow[merge_block_index].ty = Some(ControlFlowNodeType::Merge); + self.flow.add_edge( + source_node_index, + merge_block_index, + ControlFlowEdgeType::ForwardMerge, + ); + + if let Some(continue_block_id) = merge.continue_block_id { + let continue_block_index = block_to_node[&continue_block_id]; + + self.flow[source_node_index].ty = Some(ControlFlowNodeType::Loop); + self.flow.add_edge( + source_node_index, + continue_block_index, + ControlFlowEdgeType::ForwardContinue, + ); + } + } + + // Branch Edges + match self.flow[source_node_index].terminator { + Terminator::Branch { target_id } => { + let target_node_index = block_to_node[&target_id]; + self.flow.add_edge( + source_node_index, + target_node_index, + ControlFlowEdgeType::Forward, + ); + } + Terminator::BranchConditional { + true_id, false_id, .. + } => { + let true_node_index = block_to_node[&true_id]; + let false_node_index = block_to_node[&false_id]; + + self.flow.add_edge( + source_node_index, + true_node_index, + ControlFlowEdgeType::IfTrue, + ); + self.flow.add_edge( + source_node_index, + false_node_index, + ControlFlowEdgeType::IfFalse, + ); + } + Terminator::Switch { .. } => { + // TODO + } + Terminator::Return { .. } => { + self.flow[source_node_index].ty = Some(ControlFlowNodeType::Return) + } + Terminator::Kill => { + self.flow[source_node_index].ty = Some(ControlFlowNodeType::Kill) + } + _ => {} + }; + } + + // Classify Nodes/Edges as one of [Break, Continue, Back] + for edge_index in self.flow.edge_indices() { + let (node_source_index, node_target_index) = + self.flow.edge_endpoints(edge_index).unwrap(); + + // Back + if self.flow[node_target_index].ty == Some(ControlFlowNodeType::Loop) + && self.flow[node_source_index].id > self.flow[node_target_index].id + { + self.flow[node_source_index].ty = Some(ControlFlowNodeType::Back); + self.flow[edge_index] = ControlFlowEdgeType::Back; + } + + let mut target_incoming_edges = self + .flow + .neighbors_directed(node_target_index, Direction::Incoming) + .detach(); + while let Some((incoming_edge, incoming_source)) = + target_incoming_edges.next(&self.flow) + { + // Loop continue + if self.flow[incoming_edge] == ControlFlowEdgeType::ForwardContinue { + self.flow[node_source_index].ty = Some(ControlFlowNodeType::Continue); + self.flow[edge_index] = ControlFlowEdgeType::LoopContinue; + } + // Loop break + if self.flow[incoming_source].ty == Some(ControlFlowNodeType::Loop) + && self.flow[incoming_edge] == ControlFlowEdgeType::ForwardMerge + { + self.flow[node_source_index].ty = Some(ControlFlowNodeType::Break); + self.flow[edge_index] = ControlFlowEdgeType::LoopBreak; + } + } + } + } + + /// TODO + /// Removes OpPhi instructions from the control flow graph and turns them into ordinary variables. + /// + /// Phi instructions are not supported inside Naga nor do they exist as instructions on CPUs. It is neccessary + /// to remove them and turn into ordinary variables before converting to Naga's IR and shader code. + pub fn remove_phi_instructions() { + unimplemented!(); + } + + /// Traverses the flow graph and returns a list of Naga's statements. + pub fn to_naga(&self) -> Result { + self.naga_traverse(node_index(0)) + } + + fn naga_traverse(&self, node_index: BlockNodeIndex) -> Result { + let node = &self.flow[node_index]; + + match node.ty { + Some(ControlFlowNodeType::Header) => { + match node.terminator { + Terminator::BranchConditional { + condition, + true_id, + false_id, + } => { + let mut result = node.block.clone(); + result.push(crate::Statement::If { + condition, + accept: self.naga_traverse(self.block_to_node[&true_id])?, + reject: self.naga_traverse(self.block_to_node[&false_id])?, + }); + Ok(result) + } + Terminator::Switch { .. } => { + // TODO + Ok(node.block.clone()) + } + _ => Err(Error::InvalidTerminator), + } + } + Some(ControlFlowNodeType::Loop) => { + let continuing: crate::Block = { + let continue_edge = self + .flow + .edges_directed(node_index, Direction::Outgoing) + .find(|&ty| *ty.weight() == ControlFlowEdgeType::ForwardContinue) + .unwrap(); + + self.flow[continue_edge.target()].block.clone() + }; + + let mut body: crate::Block = node.block.clone(); + match node.terminator { + Terminator::BranchConditional { + condition, + true_id, + false_id, + } => body.push(crate::Statement::If { + condition, + accept: self.naga_traverse(self.block_to_node[&true_id])?, + reject: self.naga_traverse(self.block_to_node[&false_id])?, + }), + Terminator::Branch { target_id } => { + body.extend(self.naga_traverse(self.block_to_node[&target_id])?) + } + _ => return Err(Error::InvalidTerminator), + }; + + Ok(vec![crate::Statement::Loop { body, continuing }]) + } + Some(ControlFlowNodeType::Break) => { + let mut result = node.block.clone(); + match node.terminator { + Terminator::BranchConditional { + condition, + true_id, + false_id, + } => result.push(crate::Statement::If { + condition, + accept: self.naga_traverse(self.block_to_node[&true_id])?, + reject: self.naga_traverse(self.block_to_node[&false_id])?, + }), + _ => return Err(Error::InvalidTerminator), + }; + Ok(result) + } + Some(ControlFlowNodeType::Continue) => { + let mut result = node.block.clone(); + result.push(crate::Statement::Continue); + Ok(result) + } + Some(ControlFlowNodeType::Back) | Some(ControlFlowNodeType::Merge) => { + Ok(node.block.clone()) + } + Some(ControlFlowNodeType::Kill) => { + let mut result = node.block.clone(); + result.push(crate::Statement::Kill); + Ok(result) + } + Some(ControlFlowNodeType::Return) => { + let value = match node.terminator { + Terminator::Return { value } => value, + _ => return Err(Error::InvalidTerminator), + }; + let mut result = node.block.clone(); + result.push(crate::Statement::Return { value }); + Ok(result) + } + None => match node.terminator { + Terminator::Branch { target_id } => { + let mut result = node.block.clone(); + result.extend(self.naga_traverse(self.block_to_node[&target_id])?); + Ok(result) + } + _ => Ok(node.block.clone()), + }, + } + } + + /// Get the entire graph in a graphviz dot format for visualization. Useful for debugging purposes. + pub fn to_graphviz(&self) -> Result { + let mut output = String::new(); + + output += "digraph ControlFlowGraph {"; + + for node_index in self.flow.node_indices() { + let node = &self.flow[node_index]; + writeln!( + output, + "{} [ label = \"%{} {:?}\" ]", + node_index.index(), + node.id, + node.ty + )?; + } + + for edge in self.flow.raw_edges() { + let source = edge.source(); + let target = edge.target(); + + let style = match edge.weight { + ControlFlowEdgeType::IfTrue => "color=blue", + ControlFlowEdgeType::IfFalse => "color=red", + ControlFlowEdgeType::ForwardMerge => "style=dotted", + _ => "", + }; + + writeln!( + &mut output, + "{} -> {} [ {} ]", + source.index(), + target.index(), + style + )?; + } + + output += "}\n"; + + Ok(output) + } +} + +/// Type of an edge(flow) in the `ControlFlowGraph`. +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +pub enum ControlFlowEdgeType { + /// Default + Forward, + + /// Forward edge to a merge block. + ForwardMerge, + + /// Forward edge to a OpLoopMerge continue's instruction. + ForwardContinue, + + /// A back-edge: An edge from a node to one of its ancestors in a depth-first + /// search from the entry block. + /// Can only be to a ControlFlowNodeType::Loop. + Back, + + /// An edge from a node to the merge block of the nearest enclosing loop, where + /// there is no intervening switch. + /// The source block is a "break block" as defined by SPIR-V. + LoopBreak, + + /// An edge from a node in a loop body to the associated continue target, where + /// there are no other intervening loops or switches. + /// The source block is a "continue block" as defined by SPIR-V. + LoopContinue, + + /// An edge from a node with OpBranchConditional to the block of true operand. + IfTrue, + + /// An edge from a node with OpBranchConditional to the block of false operand. + IfFalse, + + /// An edge from a node to the merge block of the nearest enclosing switch, + /// where there is no intervening loop. + SwitchBreak, + + /// An edge from one switch case to the next sibling switch case. + CaseFallThrough, +} +/// Type of a node(block) in the `ControlFlowGraph`. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum ControlFlowNodeType { + /// A block whose merge instruction is an OpSelectionMerge. + Header, + + /// A header block whose merge instruction is an OpLoopMerge. + Loop, + + /// A block declared by the Merge Block operand of a merge instruction. + Merge, + + /// A block containing a branch to the Merge Block of a loop header’s merge instruction. + Break, + + /// A block containing a branch to an OpLoopMerge instruction’s Continue Target. + Continue, + + /// A block containing an OpBranch to a Loop block. + Back, + + /// A block containing an OpKill instruction. + Kill, + + /// A block containing an OpReturn or OpReturnValue branch. + Return, +} +/// ControlFlowGraph's node representing a block in the control flow. +pub struct ControlFlowNode { + /// SPIR-V ID. + pub id: BlockId, + + /// Type of the node. See *ControlFlowNodeType*. + pub ty: Option, + + /// Naga's statements inside this block. + pub block: crate::Block, + + /// Termination instruction of the block. + pub terminator: Terminator, + + /// Merge Instruction + pub merge: Option, +} diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs new file mode 100644 index 000000000..4012242ed --- /dev/null +++ b/src/front/spv/function.rs @@ -0,0 +1,163 @@ +use crate::arena::Handle; + +use super::flow::*; +use super::*; + +pub type BlockId = u32; + +#[derive(Copy, Clone, Debug)] +pub struct MergeInstruction { + pub merge_block_id: BlockId, + pub continue_block_id: Option, +} +/// Terminator instruction of a SPIR-V's block. +#[derive(Clone, Debug)] +#[allow(dead_code)] +pub enum Terminator { + /// + Return { + value: Option>, + }, + /// + Branch { target_id: BlockId }, + /// + BranchConditional { + condition: Handle, + true_id: BlockId, + false_id: BlockId, + }, + /// + /// switch(SELECTOR) { + /// case TARGET_LITERAL#: { + /// TARGET_BLOCK# + /// } + /// default: { + /// DEFAULT + /// } + /// } + Switch { + /// + selector: Handle, + /// Default block of the switch case. + default: BlockId, + /// Tuples of (literal, target block) + targets: Vec<(i32, BlockId)>, + }, + /// Fragment shader discard + Kill, + /// + Unreachable, +} + +pub fn parse_function>( + parser: &mut super::Parser, + inst: Instruction, + module: &mut crate::Module, +) -> Result<(), Error> { + parser.switch(ModuleState::Function, inst.op)?; + inst.expect(5)?; + let result_type = parser.next()?; + let fun_id = parser.next()?; + let _fun_control = parser.next()?; + let fun_type = parser.next()?; + let mut fun = { + let ft = parser.lookup_function_type.lookup(fun_type)?; + if ft.return_type_id != result_type { + return Err(Error::WrongFunctionResultType(result_type)); + } + crate::Function { + name: parser.future_decor.remove(&fun_id).and_then(|dec| dec.name), + parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), + return_type: if parser.lookup_void_type.contains(&result_type) { + None + } else { + Some(parser.lookup_type.lookup(result_type)?.handle) + }, + global_usage: Vec::new(), + local_variables: Arena::new(), + expressions: parser.make_expression_storage(), + body: Vec::new(), + } + }; + + // read parameters + for i in 0..fun.parameter_types.capacity() { + match parser.next_inst()? { + Instruction { + op: spirv::Op::FunctionParameter, + wc: 3, + } => { + let type_id = parser.next()?; + let _id = parser.next()?; + //Note: we redo the lookup in order to work around `parser` borrowing + if type_id + != parser + .lookup_function_type + .lookup(fun_type)? + .parameter_type_ids[i] + { + return Err(Error::WrongFunctionParameterType(type_id)); + } + let ty = parser.lookup_type.lookup(type_id)?.handle; + fun.parameter_types.push(ty); + } + Instruction { op, .. } => return Err(Error::InvalidParameter(op)), + } + } + + // Read body + let mut local_function_calls = FastHashMap::default(); + let mut flow_graph = FlowGraph::new(); + + // Scan the blocks and add them as nodes + loop { + let fun_inst = parser.next_inst()?; + log::debug!("\t\t{:?}", fun_inst.op); + match fun_inst.op { + spirv::Op::Label => { + // Read the label ID + fun_inst.expect(2)?; + let block_id = parser.next()?; + + let node = parser.next_block( + block_id, + &mut fun.expressions, + &mut fun.local_variables, + &module.types, + &module.constants, + &module.global_variables, + &mut local_function_calls, + )?; + + flow_graph.add_node(node); + } + spirv::Op::FunctionEnd => { + fun_inst.expect(1)?; + break; + } + _ => { + return Err(Error::UnsupportedInstruction(parser.state, fun_inst.op)); + } + } + } + + flow_graph.classify(); + fun.body = flow_graph.to_naga()?; + + // done + fun.global_usage = + crate::GlobalUse::scan(&fun.expressions, &fun.body, &module.global_variables); + let handle = module.functions.append(fun); + for (expr_handle, dst_id) in local_function_calls { + parser.deferred_function_calls.push(DeferredFunctionCall { + source_handle: handle, + expr_handle, + dst_id, + }); + } + + parser.lookup_function.insert(fun_id, handle); + parser.lookup_expression.clear(); + parser.lookup_sampled_image.clear(); + Ok(()) +} diff --git a/src/front/spv.rs b/src/front/spv/mod.rs similarity index 89% rename from src/front/spv.rs rename to src/front/spv/mod.rs index e98c14ef3..701c150db 100644 --- a/src/front/spv.rs +++ b/src/front/spv/mod.rs @@ -9,6 +9,17 @@ extra info, such as the related SPIR-V type ID. TODO: would be nice to find ways that avoid looking up as much !*/ +#![allow(dead_code)] + +mod convert; +mod error; +mod flow; +mod function; + +use convert::*; +use error::Error; +use flow::*; +use function::*; use crate::{ arena::{Arena, Handle}, @@ -22,55 +33,8 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[spirv::Capability::Sh pub const SUPPORTED_EXTENSIONS: &[&str] = &[]; pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"]; -#[derive(Debug)] -pub enum Error { - InvalidHeader, - InvalidWordCount, - UnknownInstruction(u16), - UnknownCapability(spirv::Word), - UnsupportedInstruction(ModuleState, spirv::Op), - UnsupportedCapability(spirv::Capability), - UnsupportedExtension(String), - UnsupportedExtSet(String), - UnsupportedExtInstSet(spirv::Word), - UnsupportedExtInst(spirv::Word), - UnsupportedType(Handle), - UnsupportedExecutionModel(spirv::Word), - UnsupportedStorageClass(spirv::Word), - UnsupportedImageDim(spirv::Word), - UnsupportedBuiltIn(spirv::Word), - UnsupportedControlFlow(spirv::Word), - InvalidParameter(spirv::Op), - InvalidOperandCount(spirv::Op, u16), - InvalidOperand, - InvalidId(spirv::Word), - InvalidDecoration(spirv::Word), - InvalidTypeWidth(spirv::Word), - InvalidSign(spirv::Word), - InvalidInnerType(spirv::Word), - InvalidVectorSize(spirv::Word), - InvalidVariableClass(spirv::StorageClass), - InvalidAccessType(spirv::Word), - InvalidAccess(Handle), - InvalidAccessIndex(spirv::Word), - InvalidLoadType(spirv::Word), - InvalidStoreType(spirv::Word), - InvalidBinding(spirv::Word), - InvalidImageExpression(Handle), - InvalidSamplerExpression(Handle), - InvalidSampleImage(Handle), - InvalidSampleSampler(Handle), - InvalidSampleCoordinates(Handle), - InvalidDepthReference(Handle), - InconsistentComparisonSampling(Handle), - WrongFunctionResultType(spirv::Word), - WrongFunctionParameterType(spirv::Word), - MissingDecoration(spirv::Decoration), - BadString, - IncompleteData, -} - -struct Instruction { +#[derive(Copy, Clone)] +pub struct Instruction { op: spirv::Op, wc: u16, } @@ -122,46 +86,6 @@ impl LookupHelper for FastHashMap { } } -fn map_vector_size(word: spirv::Word) -> Result { - match word { - 2 => Ok(crate::VectorSize::Bi), - 3 => Ok(crate::VectorSize::Tri), - 4 => Ok(crate::VectorSize::Quad), - _ => Err(Error::InvalidVectorSize(word)), - } -} - -fn map_storage_class(word: spirv::Word) -> Result { - use spirv::StorageClass as Sc; - match Sc::from_u32(word) { - Some(Sc::UniformConstant) => Ok(crate::StorageClass::Constant), - Some(Sc::Function) => Ok(crate::StorageClass::Function), - Some(Sc::Input) => Ok(crate::StorageClass::Input), - Some(Sc::Output) => Ok(crate::StorageClass::Output), - Some(Sc::Private) => Ok(crate::StorageClass::Private), - Some(Sc::StorageBuffer) => Ok(crate::StorageClass::StorageBuffer), - Some(Sc::Uniform) => Ok(crate::StorageClass::Uniform), - Some(Sc::Workgroup) => Ok(crate::StorageClass::WorkGroup), - _ => Err(Error::UnsupportedStorageClass(word)), - } -} - -fn map_image_dim(word: spirv::Word) -> Result { - match spirv::Dim::from_u32(word) { - Some(spirv::Dim::Dim1D) => Ok(crate::ImageDimension::D1), - Some(spirv::Dim::Dim2D) => Ok(crate::ImageDimension::D2), - Some(spirv::Dim::Dim3D) => Ok(crate::ImageDimension::D3), - Some(spirv::Dim::DimCube) => Ok(crate::ImageDimension::Cube), - _ => Err(Error::UnsupportedImageDim(word)), - } -} - -fn map_width(word: spirv::Word) -> Result { - (word >> 3) // bits to bytes - .try_into() - .map_err(|_| Error::InvalidTypeWidth(word)) -} - //TODO: this method may need to be gone, depending on whether // WGSL allows treating images and samplers as expressions and pass them around. fn reach_global_type( @@ -331,33 +255,18 @@ struct LookupSampledImage { image: Handle, sampler: Handle, } - struct DeferredFunctionCall { source_handle: Handle, expr_handle: Handle, dst_id: spirv::Word, } -enum Terminator { - Return { - value: Option>, - }, - Branch { - label_id: spirv::Word, - condition: Option>, - }, -} - -struct Assignment { +#[derive(Clone, Debug)] +pub struct Assignment { to: Handle, value: Handle, } -struct ControlFlowNode { - assignments: Vec, - terminator: Terminator, -} - pub struct Parser { data: I, state: ModuleState, @@ -550,8 +459,10 @@ impl> Parser { Ok(()) } + #[allow(clippy::too_many_arguments)] fn next_block( &mut self, + block_id: spirv::Word, expressions: &mut Arena, local_arena: &mut Arena, type_arena: &Arena, @@ -560,10 +471,12 @@ impl> Parser { local_function_calls: &mut FastHashMap, spirv::Word>, ) -> Result { let mut assignments = Vec::new(); + let mut merge = None; let terminator = loop { use spirv::Op; let inst = self.next_inst()?; log::debug!("\t\t{:?} [{}]", inst.op, inst.wc); + match inst.op { Op::Variable => { inst.expect_at_least(4)?; @@ -679,13 +592,11 @@ impl> Parser { }; } - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: acex.base_handle, - type_id: result_type_id, - }, - ); + let lookup_expression = LookupExpression { + handle: acex.base_handle, + type_id: result_type_id, + }; + self.lookup_expression.insert(result_id, lookup_expression); } Op::CompositeExtract => { inst.expect_at_least(4)?; @@ -808,26 +719,11 @@ impl> Parser { value: value_expr.handle, }); } - Op::Return => { - inst.expect(1)?; - break Terminator::Return { value: None }; - } - Op::Branch => { - inst.expect(2)?; - let label_id = self.next()?; - break Terminator::Branch { - label_id, - condition: None, - }; - } - Op::FSub => { + // Arithmetic Instructions +, -, *, /, % + _ if inst.op >= Op::IAdd && inst.op <= Op::FMod => { inst.expect(5)?; self.parse_expr_binary_op(expressions, crate::BinaryOperator::Subtract)?; } - Op::FMul => { - inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::Multiply)?; - } Op::VectorTimesScalar => { inst.expect(5)?; let result_type_id = self.next()?; @@ -1134,12 +1030,99 @@ impl> Parser { }, ); } + // Relational and Logical Instructions + op if inst.op >= Op::IEqual && inst.op <= Op::FUnordGreaterThanEqual => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, map_binary_operator(op)?)?; + } + Op::Return => { + inst.expect(1)?; + break Terminator::Return { value: None }; + } + Op::Branch => { + inst.expect(2)?; + let target_id = self.next()?; + break Terminator::Branch { target_id }; + } + Op::BranchConditional => { + inst.expect_at_least(4)?; + + let condition_id = self.next()?; + let condition = self.lookup_expression.lookup(condition_id)?.handle; + + let true_id = self.next()?; + let false_id = self.next()?; + + break Terminator::BranchConditional { + condition, + true_id, + false_id, + }; + } + Op::Switch => { + inst.expect_at_least(3)?; + + let selector = self.next()?; + let selector = self.lookup_expression[&selector].handle; + let default = self.next()?; + + let mut targets = Vec::new(); + for _ in 0..inst.wc - 3 { + let literal = self.next()?; + let target = self.next()?; + targets.push((literal as i32, target)); + } + + break Terminator::Switch { + selector, + default, + targets, + }; + } + Op::SelectionMerge => { + inst.expect(3)?; + let merge_block_id = self.next()?; + // TODO: Selection Control Mask + let _selection_control = self.next()?; + let continue_block_id = None; + merge = Some(MergeInstruction { + merge_block_id, + continue_block_id, + }); + } + Op::LoopMerge => { + inst.expect_at_least(4)?; + let merge_block_id = self.next()?; + let continue_block_id = Some(self.next()?); + + // TODO: Loop Control Parameters + for _ in 0..inst.wc - 3 { + self.next()?; + } + + merge = Some(MergeInstruction { + merge_block_id, + continue_block_id, + }); + } _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } }; + + let mut block = Vec::new(); + for assignment in assignments.iter() { + block.push(crate::Statement::Store { + pointer: assignment.to, + value: assignment.value, + }); + } + Ok(ControlFlowNode { - assignments, + id: block_id, + ty: None, + block, terminator, + merge, }) } @@ -1231,7 +1214,7 @@ impl> Parser { Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), Op::Variable => self.parse_global_variable(inst, &mut module), - Op::Function => self.parse_function(inst, &mut module), + Op::Function => parse_function(&mut self, inst, &mut module), _ => Err(Error::UnsupportedInstruction(self.state, inst.op)), //TODO }?; } @@ -1871,7 +1854,7 @@ impl> Parser { let id = self.next()?; let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; - let inner = match module.types[type_lookup.handle].inner { + let inner = match module.types[ty].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width, @@ -1897,7 +1880,7 @@ impl> Parser { inst.expect(4)?; self.next()? } - Ordering::Equal => !0, + Ordering::Equal => 0, }; crate::ConstantInner::Sint(((u64::from(high) << 32) | u64::from(low)) as i64) } @@ -2019,123 +2002,6 @@ impl> Parser { ); Ok(()) } - - fn parse_function( - &mut self, - inst: Instruction, - module: &mut crate::Module, - ) -> Result<(), Error> { - self.switch(ModuleState::Function, inst.op)?; - inst.expect(5)?; - let result_type = self.next()?; - let fun_id = self.next()?; - let _fun_control = self.next()?; - let fun_type = self.next()?; - let mut fun = { - let ft = self.lookup_function_type.lookup(fun_type)?; - if ft.return_type_id != result_type { - return Err(Error::WrongFunctionResultType(result_type)); - } - crate::Function { - name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name), - parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), - return_type: if self.lookup_void_type.contains(&result_type) { - None - } else { - Some(self.lookup_type.lookup(result_type)?.handle) - }, - global_usage: Vec::new(), - local_variables: Arena::new(), - expressions: self.make_expression_storage(), - body: Vec::new(), - } - }; - // read parameters - for i in 0..fun.parameter_types.capacity() { - match self.next_inst()? { - Instruction { - op: spirv::Op::FunctionParameter, - wc: 3, - } => { - let type_id = self.next()?; - let _id = self.next()?; - //Note: we redo the lookup in order to work around `self` borrowing - if type_id - != self - .lookup_function_type - .lookup(fun_type)? - .parameter_type_ids[i] - { - return Err(Error::WrongFunctionParameterType(type_id)); - } - let ty = self.lookup_type.lookup(type_id)?.handle; - fun.parameter_types.push(ty); - } - Instruction { op, .. } => return Err(Error::InvalidParameter(op)), - } - } - // read body - let mut local_function_calls = FastHashMap::default(); - let mut control_flow_graph = FastHashMap::default(); - loop { - let fun_inst = self.next_inst()?; - log::debug!("\t\t{:?}", fun_inst.op); - match fun_inst.op { - spirv::Op::Label => { - fun_inst.expect(2)?; - let label_id = self.next()?; - let node = self.next_block( - &mut fun.expressions, - &mut fun.local_variables, - &module.types, - &module.constants, - &module.global_variables, - &mut local_function_calls, - )?; - // temp until the CFG is fully processed - for assign in node.assignments.iter() { - fun.body.push(crate::Statement::Store { - pointer: assign.to, - value: assign.value, - }); - } - match node.terminator { - Terminator::Return { value } => { - fun.body.push(crate::Statement::Return { value }); - } - Terminator::Branch { - label_id, - condition, - } => { - let _ = (label_id, condition); //TODO - } - } - control_flow_graph.insert(label_id, node); - } - spirv::Op::FunctionEnd => { - fun_inst.expect(1)?; - break; - } - _ => return Err(Error::UnsupportedInstruction(self.state, fun_inst.op)), - } - } - // done - fun.global_usage = - crate::GlobalUse::scan(&fun.expressions, &fun.body, &module.global_variables); - let handle = module.functions.append(fun); - for (expr_handle, dst_id) in local_function_calls { - self.deferred_function_calls.push(DeferredFunctionCall { - source_handle: handle, - expr_handle, - dst_id, - }); - } - - self.lookup_function.insert(fun_id, handle); - self.lookup_expression.clear(); - self.lookup_sampled_image.clear(); - Ok(()) - } } pub fn parse_u8_slice(data: &[u8]) -> Result { From 92c1ffb588fea859305b59b790dd08b3c943593d Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 24 Aug 2020 06:09:37 +0200 Subject: [PATCH 0155/2212] Add initial Rosetta testing (#148) * Add initial Rosetta testing * Make rosetta tests run as part of cargo test * Fix rosetta test failure --- Cargo.toml | 1 + src/front/glsl_new/mod.rs | 3 + src/front/glsl_new/rosetta_tests.rs | 21 +++++ src/front/mod.rs | 2 + src/front/wgsl_rosetta_tests.rs | 21 +++++ test-data/simple/simple.expected.ron | 112 +++++++++++++++++++++++++++ test-data/simple/simple.vert | 9 +++ test-data/simple/simple.wgsl | 9 +++ 8 files changed, 178 insertions(+) create mode 100644 src/front/glsl_new/rosetta_tests.rs create mode 100644 src/front/wgsl_rosetta_tests.rs create mode 100644 test-data/simple/simple.expected.ron create mode 100644 test-data/simple/simple.vert create mode 100644 test-data/simple/simple.wgsl diff --git a/Cargo.toml b/Cargo.toml index 3939aa9a4..010482e13 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ deserialize = ["serde"] spirv-in = ["petgraph", "spirv"] [dev-dependencies] +difference = "2.0" env_logger = "0.6" ron = "0.5" serde = { version = "1.0", features = ["derive"] } diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index 81e27bb3d..541c3261c 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -15,6 +15,9 @@ mod parser; mod parser_tests; mod token; +#[cfg(test)] +mod rosetta_tests; + pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { log::debug!("------ GLSL-pomelo ------"); diff --git a/src/front/glsl_new/rosetta_tests.rs b/src/front/glsl_new/rosetta_tests.rs new file mode 100644 index 000000000..efb921375 --- /dev/null +++ b/src/front/glsl_new/rosetta_tests.rs @@ -0,0 +1,21 @@ +use difference::assert_diff; +use std::{fs, path::Path}; + +const TEST_PATH: &str = "test-data"; + +fn rosetta_test(file_name: &str, stage: crate::ShaderStage) { + let test_dir = Path::new(TEST_PATH); + let input = fs::read_to_string(test_dir.join(file_name)).unwrap(); + let expected = + fs::read_to_string(test_dir.join(file_name).with_extension("expected.ron")).unwrap(); + + let module = crate::front::glsl_new::parse_str(&input, "main".to_string(), stage).unwrap(); + let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); + + assert_diff!(output.as_str(), expected.as_str(), "", 0); +} + +#[test] +fn simple() { + rosetta_test("simple/simple.vert", crate::ShaderStage::Vertex) +} diff --git a/src/front/mod.rs b/src/front/mod.rs index ec4c36cf0..757101cf6 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -7,6 +7,8 @@ pub mod glsl_new; #[cfg(feature = "spirv-in")] pub mod spv; pub mod wgsl; +#[cfg(test)] +mod wgsl_rosetta_tests; use crate::arena::Arena; diff --git a/src/front/wgsl_rosetta_tests.rs b/src/front/wgsl_rosetta_tests.rs new file mode 100644 index 000000000..a4e7179a3 --- /dev/null +++ b/src/front/wgsl_rosetta_tests.rs @@ -0,0 +1,21 @@ +use difference::assert_diff; +use std::{fs, path::Path}; + +const TEST_PATH: &str = "test-data"; + +fn rosetta_test(file_name: &str) { + let test_dir = Path::new(TEST_PATH); + let input = fs::read_to_string(test_dir.join(file_name)).unwrap(); + let expected = + fs::read_to_string(test_dir.join(file_name).with_extension("expected.ron")).unwrap(); + + let module = crate::front::wgsl::parse_str(&input).unwrap(); + let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); + + assert_diff!(output.as_str(), expected.as_str(), "", 0); +} + +#[test] +fn simple() { + rosetta_test("simple/simple.wgsl") +} diff --git a/test-data/simple/simple.expected.ron b/test-data/simple/simple.expected.ron new file mode 100644 index 000000000..baad5a38d --- /dev/null +++ b/test-data/simple/simple.expected.ron @@ -0,0 +1,112 @@ +( + header: ( + version: (1, 0, 0), + generator: 0, + ), + types: [ + ( + name: None, + inner: Vector( + size: Bi, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Quad, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Scalar( + kind: Float, + width: 4, + ), + ), + ], + constants: [ + ( + name: None, + specialization: None, + inner: Float(1), + ty: 3, + ), + ( + name: None, + specialization: None, + inner: Float(0), + ty: 3, + ), + ], + global_variables: [ + ( + name: Some("a_pos"), + class: Input, + binding: Some(Location(0)), + ty: 1, + interpolation: None, + ), + ( + name: Some("o_pos"), + class: Output, + binding: Some(Location(0)), + ty: 2, + interpolation: None, + ), + ], + functions: [ + ( + name: Some("main"), + parameter_types: [], + return_type: None, + global_usage: [ + ( + bits: 1, + ), + ( + bits: 2, + ), + ], + local_variables: [ + ( + name: Some("w"), + ty: 3, + init: Some(3), + ), + ], + expressions: [ + GlobalVariable(1), + GlobalVariable(2), + Constant(1), + LocalVariable(1), + Constant(2), + Compose( + ty: 2, + components: [ + 1, + 5, + 4, + ], + ), + ], + body: [ + Empty, + Store( + pointer: 2, + value: 6, + ), + ], + ), + ], + entry_points: [ + ( + stage: Vertex, + name: "main", + function: 1, + ), + ], +) \ No newline at end of file diff --git a/test-data/simple/simple.vert b/test-data/simple/simple.vert new file mode 100644 index 000000000..507039ffd --- /dev/null +++ b/test-data/simple/simple.vert @@ -0,0 +1,9 @@ +#version 450 core + +layout(location = 0) in vec2 a_pos; +layout(location = 0) out vec4 o_pos; + +void main() { + float w = 1.0; + o_pos = vec4(a_pos, 0.0, w); +} diff --git a/test-data/simple/simple.wgsl b/test-data/simple/simple.wgsl new file mode 100644 index 000000000..bac4c31f0 --- /dev/null +++ b/test-data/simple/simple.wgsl @@ -0,0 +1,9 @@ +# vertex +[[location 0]] var a_pos : vec2; +[[location 0]] var o_pos : vec4; + +fn main() -> void { + var w: f32 = 1.0; + o_pos = vec4(a_pos, 0.0, w); +} +entry_point vertex as "main" = main; From 6a3af2fe87479335fb609ed4a2fe2237df6c0ae2 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 25 Aug 2020 19:51:27 +0200 Subject: [PATCH 0156/2212] Add dependency on serialize for Rosetta tests (#150) * Add dependency on serialize for Rosetta tests Fixes #149 * Also run default cargo test on CI --- .github/workflows/pipeline.yml | 5 +++++ src/front/glsl_new/mod.rs | 2 +- src/front/mod.rs | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index d896407c6..0d9ead518 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -13,6 +13,11 @@ jobs: toolchain: stable override: true - uses: actions-rs/cargo@v1 + name: Default test + with: + command: test + - uses: actions-rs/cargo@v1 + name: Test all features with: command: test args: --all-features diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index 541c3261c..d937beda1 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -15,7 +15,7 @@ mod parser; mod parser_tests; mod token; -#[cfg(test)] +#[cfg(all(test, feature = "serialize"))] mod rosetta_tests; pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { diff --git a/src/front/mod.rs b/src/front/mod.rs index 757101cf6..62117c3fd 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -7,7 +7,7 @@ pub mod glsl_new; #[cfg(feature = "spirv-in")] pub mod spv; pub mod wgsl; -#[cfg(test)] +#[cfg(all(test, feature = "serialize"))] mod wgsl_rosetta_tests; use crate::arena::Arena; From ac66d149a47a5c261e30719e867f58d105f26ef8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 25 Aug 2020 20:54:13 +0100 Subject: [PATCH 0157/2212] Fixed names beginning with digits and arguments without names (#151) --- src/back/glsl.rs | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index d41c0952a..201aaba6e 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -102,7 +102,11 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> let mut namer = |name: Option<&'a String>| { if let Some(name) = name { - if name.starts_with("gl_") || name == "main" || names.get(name.as_str()).is_some() { + if name.chars().next().map(char::is_numeric).unwrap_or(true) + || name.starts_with("gl_") + || name == "main" + || names.get(name.as_str()).is_some() + { counter += 1; while names.get(format!("_{}", counter).as_str()).is_some() { counter += 1; @@ -324,6 +328,13 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> for (handle, name) in functions.iter() { let func = &module.functions[*handle]; + let args: FastHashMap<_, _> = func + .parameter_types + .iter() + .enumerate() + .map(|(pos, ty)| (pos as u32, (namer(None), *ty))) + .collect(); + writeln!( out, "{} {}({}) {{", @@ -333,9 +344,12 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> .as_deref() .unwrap_or("void"), name, - func.parameter_types - .iter() - .map(|ty| write_type(*ty, &module.types, &structs, None, features)) + args.values() + .map::, _>(|(name, ty)| { + let ty = write_type(*ty, &module.types, &structs, None, features)?; + + Ok(format!("{} {}", ty, name)) + }) .collect::, _>>()? .join(","), )?; @@ -366,19 +380,14 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> globals: &globals_lookup, locals_lookup: &locals, structs: &structs, - args: &func - .parameter_types - .iter() - .enumerate() - .map(|(pos, ty)| (pos as u32, (namer(None), *ty))) - .collect(), + args: &args, expressions: &func.expressions, locals: &func.local_variables, features, }; for sta in func.body.iter() { - writeln!(out, "{}", write_statement(sta, module, &mut builder)?)?; + writeln!(out, "\t{}", write_statement(sta, module, &mut builder)?)?; } writeln!(out, "}}")?; @@ -497,7 +506,7 @@ fn write_statement( Statement::Break => String::from("break;"), Statement::Continue => String::from("continue;"), Statement::Return { value } => format!( - "return {};", + "return {};", value.map_or::, _>(Ok(String::from("")), |expr| Ok( write_expression(&builder.expressions[expr], module, builder)?.0 ))? From f7c5e4873e39f958a87d317e2c6a87a5f61e9d02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 26 Aug 2020 17:29:33 +0100 Subject: [PATCH 0158/2212] Made the output of glsl-out more human readable (#154) --- src/back/glsl.rs | 128 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 93 insertions(+), 35 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 201aaba6e..03b9697d9 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -91,10 +91,10 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> ))); } - writeln!(out, "#version {}", options.version)?; + writeln!(out, "#version {}\n", options.version)?; if es { - writeln!(out, "precision highp float;")?; + writeln!(out, "precision highp float;\n")?; } let mut counter = 0; @@ -102,7 +102,8 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> let mut namer = |name: Option<&'a String>| { if let Some(name) = name { - if name.chars().next().map(char::is_numeric).unwrap_or(true) + if name.starts_with(|c: char| !(c.is_ascii_alphabetic() || c == '_')) + || name.contains(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) || name.starts_with("gl_") || name == "main" || names.get(name.as_str()).is_some() @@ -215,6 +216,8 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> } } + writeln!(out)?; + let mut globals_lookup = FastHashMap::default(); for ((handle, global), usage) in module.global_variables.iter().zip(func.global_usage.iter()) { @@ -287,6 +290,8 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> globals_lookup.insert(handle, name); } + writeln!(out)?; + let mut functions = FastHashMap::default(); for (handle, func) in module.functions.iter() { @@ -325,6 +330,8 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> functions.insert(handle, name); } + writeln!(out)?; + for (handle, name) in functions.iter() { let func = &module.functions[*handle]; @@ -363,7 +370,7 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> for (handle, name) in locals.iter() { writeln!( out, - "{} {};", + "\t{} {};", write_type( func.local_variables[*handle].ty, &module.types, @@ -375,6 +382,8 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> )?; } + writeln!(out)?; + let mut builder = StatementBuilder { functions: &functions, globals: &globals_lookup, @@ -387,7 +396,9 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> }; for sta in func.body.iter() { - writeln!(out, "\t{}", write_statement(sta, module, &mut builder)?)?; + if !matches!(sta, Statement::Empty) { + writeln!(out, "{}", write_statement(sta, module, &mut builder, 1)?)?; + } } writeln!(out, "}}")?; @@ -424,12 +435,13 @@ fn write_statement( sta: &Statement, module: &Module, builder: &mut StatementBuilder<'_>, + indent: usize, ) -> Result { Ok(match sta { Statement::Empty => String::new(), Statement::Block(block) => block .iter() - .map(|sta| write_statement(sta, module, builder)) + .map(|sta| write_statement(sta, module, builder, indent)) .collect::, _>>()? .join("\n"), Statement::If { @@ -441,17 +453,35 @@ fn write_statement( writeln!( &mut out, - "if({}) {{", + "{}if({}) {{", + "\t".repeat(indent), write_expression(&builder.expressions[*condition], module, builder)?.0 )?; + for sta in accept { - writeln!(&mut out, "{}", write_statement(sta, module, builder)?)?; + if !matches!(sta, Statement::Empty) { + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 1)? + )?; + } } - writeln!(&mut out, "}} else {{")?; - for sta in reject { - writeln!(&mut out, "{}", write_statement(sta, module, builder)?)?; + + if !reject.is_empty() { + writeln!(&mut out, "{}}} else {{", "\t".repeat(indent),)?; + for sta in reject { + if !matches!(sta, Statement::Empty) { + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 1)? + )?; + } + } } - write!(&mut out, "}}")?; + + write!(&mut out, "{}}}", "\t".repeat(indent),)?; out } @@ -464,56 +494,84 @@ fn write_statement( writeln!( &mut out, - "switch({}) {{", + "{}switch({}) {{", + "\t".repeat(indent), write_expression(&builder.expressions[*selector], module, builder)?.0 )?; for (label, (block, fallthrough)) in cases { - writeln!(&mut out, " case {}:", label)?; + writeln!(&mut out, "{}case {}:", "\t".repeat(indent + 1), label)?; for sta in block { - writeln!(&mut out, " {}", write_statement(sta, module, builder)?)?; + if !matches!(sta, Statement::Empty) { + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 2)? + )?; + } } if fallthrough.is_some() { - writeln!(&mut out, " break;")?; + writeln!(&mut out, "{}break;", "\t".repeat(indent + 2),)?; } } - writeln!(&mut out, " default:")?; + if !default.is_empty() { + writeln!(&mut out, "{}default:", "\t".repeat(indent + 1),)?; - for sta in default { - writeln!(&mut out, " {}", write_statement(sta, module, builder)?)?; + for sta in default { + if !matches!(sta, Statement::Empty) { + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 2)? + )?; + } + } } - write!(&mut out, "}}")?; + write!(&mut out, "{}}}", "\t".repeat(indent),)?; out } Statement::Loop { body, continuing } => { let mut out = String::new(); - writeln!(&mut out, "while(true) {{",)?; + writeln!(&mut out, "{}while(true) {{", "\t".repeat(indent),)?; for sta in body.iter().chain(continuing.iter()) { - writeln!(&mut out, " {}", write_statement(sta, module, builder)?)?; + if !matches!(sta, Statement::Empty) { + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 1)? + )?; + } } - write!(&mut out, "}}")?; + write!(&mut out, "{}}}", "\t".repeat(indent),)?; out } - Statement::Break => String::from("break;"), - Statement::Continue => String::from("continue;"), + Statement::Break => format!("{}break;", "\t".repeat(indent),), + Statement::Continue => format!("{}continue;", "\t".repeat(indent),), Statement::Return { value } => format!( - "return {};", - value.map_or::, _>(Ok(String::from("")), |expr| Ok( - write_expression(&builder.expressions[expr], module, builder)?.0 - ))? + "{}{}", + "\t".repeat(indent), + if let Some(expr) = value { + format!( + "return {};", + write_expression(&builder.expressions[*expr], module, builder)?.0 + ) + } else { + String::from("return;") + } ), - Statement::Kill => String::from("discard;"), + Statement::Kill => format!("{}discard;", "\t".repeat(indent)), Statement::Store { pointer, value } => format!( - "{} = {};", + "{}{} = {};", + "\t".repeat(indent), write_expression(&builder.expressions[*pointer], module, builder)?.0, write_expression(&builder.expressions[*value], module, builder)?.0 ), @@ -571,7 +629,7 @@ fn write_expression<'a>( members[*index as usize] .name .as_ref() - .unwrap_or(&index.to_string()) + .unwrap_or(&format!("_{}", index)) ), Cow::Borrowed(&module.types[members[*index as usize].ty].inner), ), @@ -1070,7 +1128,7 @@ fn write_type( for (idx, member) in members.iter().enumerate() { writeln!( &mut out, - "{} {};", + "\t{} {};", write_type(member.ty, types, structs, None, features)?, member.name.clone().unwrap_or_else(|| idx.to_string()) )?; @@ -1261,9 +1319,9 @@ fn write_struct( writeln!( &mut tmp, - " {} {};", + "\t{} {};", write_type(member.ty, &module.types, &structs, None, features)?, - member.name.clone().unwrap_or_else(|| idx.to_string()) + member.name.clone().unwrap_or_else(|| format!("_{}", idx)) )?; } writeln!(&mut tmp, "}};")?; From 479777315211f23f640dc53977eecd46ced6aaf6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Aug 2020 13:26:51 -0400 Subject: [PATCH 0159/2212] Image IR refactor (#153) --- .github/workflows/pipeline.yml | 2 +- Cargo.toml | 1 + examples/convert.rs | 4 +- src/back/glsl.rs | 364 ++++++++++++++++++--------------- src/back/mod.rs | 2 +- src/back/msl.rs | 143 ++++++++----- src/back/spv/writer.rs | 126 ++++++------ src/front/glsl/helpers.rs | 57 ++---- src/front/glsl/mod.rs | 3 +- src/front/glsl_new/parser.rs | 9 +- src/front/spv/convert.rs | 19 +- src/front/spv/error.rs | 2 + src/front/spv/mod.rs | 78 +++---- src/lib.rs | 70 +++++-- src/proc/interface.rs | 16 ++ src/proc/typifier.rs | 26 +-- src/proc/validator.rs | 2 +- 17 files changed, 524 insertions(+), 400 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 0d9ead518..50be221f7 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -10,7 +10,7 @@ jobs: - uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: stable + toolchain: 1.41.0 override: true - uses: actions-rs/cargo@v1 name: Default test diff --git a/Cargo.toml b/Cargo.toml index 010482e13..19157929a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ glsl-out = [] serialize = ["serde"] deserialize = ["serde"] spirv-in = ["petgraph", "spirv"] +spirv-out = ["spirv"] [dev-dependencies] difference = "2.0" diff --git a/examples/convert.rs b/examples/convert.rs index 1fb5f428d..4cb4d1297 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -38,7 +38,7 @@ fn main() { .to_str() .unwrap() { - #[cfg(feature = "spirv")] + #[cfg(feature = "spirv-in")] "spv" => { let input = fs::read(&args[1]).unwrap(); naga::front::spv::parse_u8_slice(&input).unwrap() @@ -165,7 +165,7 @@ fn main() { let msl = msl::write_string(&module, options).unwrap(); fs::write(&args[2], msl).unwrap(); } - #[cfg(feature = "spirv")] + #[cfg(feature = "spirv-out")] "spv" => { use naga::back::spv; diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 03b9697d9..8e1a5cbb0 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,6 +1,6 @@ use crate::{ Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, - FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageFlags, Interpolation, + FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageClass, Interpolation, IntrinsicFunction, LocalVariable, Module, ScalarKind, ShaderStage, Statement, StorageClass, StructMember, Type, TypeInner, UnaryOperator, }; @@ -182,13 +182,13 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> continue; } - let block = matches!( - global.class, + let block = match global.class { StorageClass::Input - | StorageClass::Output - | StorageClass::StorageBuffer - | StorageClass::Uniform - ); + | StorageClass::Output + | StorageClass::StorageBuffer + | StorageClass::Uniform => true, + _ => false, + }; match module.types[global.ty].inner { TypeInner::Struct { .. } if block => { @@ -396,9 +396,7 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> }; for sta in func.body.iter() { - if !matches!(sta, Statement::Empty) { - writeln!(out, "{}", write_statement(sta, module, &mut builder, 1)?)?; - } + writeln!(out, "{}", write_statement(sta, module, &mut builder, 1)?)?; } writeln!(out, "}}")?; @@ -459,25 +457,21 @@ fn write_statement( )?; for sta in accept { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 1)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 1)? + )?; } if !reject.is_empty() { writeln!(&mut out, "{}}} else {{", "\t".repeat(indent),)?; for sta in reject { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 1)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 1)? + )?; } } @@ -503,13 +497,11 @@ fn write_statement( writeln!(&mut out, "{}case {}:", "\t".repeat(indent + 1), label)?; for sta in block { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 2)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 2)? + )?; } if fallthrough.is_some() { @@ -521,13 +513,11 @@ fn write_statement( writeln!(&mut out, "{}default:", "\t".repeat(indent + 1),)?; for sta in default { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 2)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 2)? + )?; } } @@ -541,13 +531,11 @@ fn write_statement( writeln!(&mut out, "{}while(true) {{", "\t".repeat(indent),)?; for sta in body.iter().chain(continuing.iter()) { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 1)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 1)? + )?; } write!(&mut out, "{}}}", "\t".repeat(indent),)?; @@ -583,18 +571,15 @@ fn write_expression<'a>( module: &'a Module, builder: &mut StatementBuilder<'_>, ) -> Result<(String, Cow<'a, TypeInner>), Error> { - Ok(match expr { + Ok(match *expr { Expression::Access { base, index } => { - let (base_expr, ty) = write_expression(&builder.expressions[*base], module, builder)?; + let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; - let inner = match ty.as_ref() { + let inner = match *ty.as_ref() { TypeInner::Vector { kind, width, .. } | TypeInner::Matrix { kind, width, .. } => { - Cow::Owned(TypeInner::Scalar { - kind: *kind, - width: *width, - }) + Cow::Owned(TypeInner::Scalar { kind, width }) } - TypeInner::Array { base, .. } => Cow::Borrowed(&module.types[*base].inner), + TypeInner::Array { base, .. } => Cow::Borrowed(&module.types[base].inner), _ => return Err(Error::Custom(format!("Cannot dynamically index {:?}", ty))), }; @@ -602,51 +587,48 @@ fn write_expression<'a>( format!( "{}[{}]", base_expr, - write_expression(&builder.expressions[*index], module, builder)?.0 + write_expression(&builder.expressions[index], module, builder)?.0 ), inner, ) } Expression::AccessIndex { base, index } => { - let (base_expr, ty) = write_expression(&builder.expressions[*base], module, builder)?; + let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; - match ty.as_ref() { + match *ty.as_ref() { TypeInner::Vector { kind, width, .. } | TypeInner::Matrix { kind, width, .. } => ( format!("{}[{}]", base_expr, index), - Cow::Owned(TypeInner::Scalar { - kind: *kind, - width: *width, - }), + Cow::Owned(TypeInner::Scalar { kind, width }), ), TypeInner::Array { base, .. } => ( format!("{}[{}]", base_expr, index), - Cow::Borrowed(&module.types[*base].inner), + Cow::Borrowed(&module.types[base].inner), ), - TypeInner::Struct { members } => ( + TypeInner::Struct { ref members } => ( format!( "{}.{}", base_expr, - members[*index as usize] + members[index as usize] .name .as_ref() .unwrap_or(&format!("_{}", index)) ), - Cow::Borrowed(&module.types[members[*index as usize].ty].inner), + Cow::Borrowed(&module.types[members[index as usize].ty].inner), ), _ => return Err(Error::Custom(format!("Cannot index {:?}", ty))), } } Expression::Constant(constant) => ( write_constant( - &module.constants[*constant], + &module.constants[constant], module, builder, builder.features, )?, - Cow::Borrowed(&module.types[module.constants[*constant].ty].inner), + Cow::Borrowed(&module.types[module.constants[constant].ty].inner), ), - Expression::Compose { ty, components } => { - let constructor = match module.types[*ty].inner { + Expression::Compose { ty, ref components } => { + let constructor = match module.types[ty].inner { TypeInner::Vector { size, kind, width } => format!( "{}vec{}", match kind { @@ -690,14 +672,14 @@ fn write_expression<'a>( rows as u8, ), TypeInner::Array { .. } => { - write_type(*ty, &module.types, builder.structs, None, builder.features)? + write_type(ty, &module.types, builder.structs, None, builder.features)? .into_owned() } - TypeInner::Struct { .. } => builder.structs.get(ty).unwrap().clone(), + TypeInner::Struct { .. } => builder.structs.get(&ty).unwrap().clone(), _ => { return Err(Error::Custom(format!( "Cannot compose type {}", - write_type(*ty, &module.types, builder.structs, None, builder.features)? + write_type(ty, &module.types, builder.structs, None, builder.features)? ))) } }; @@ -717,7 +699,7 @@ fn write_expression<'a>( .collect::, _>>()? .join(","), ), - Cow::Borrowed(&module.types[*ty].inner), + Cow::Borrowed(&module.types[ty].inner), ) } Expression::FunctionParameter(pos) => { @@ -727,56 +709,43 @@ fn write_expression<'a>( } Expression::GlobalVariable(handle) => ( builder.globals.get(&handle).unwrap().clone(), - Cow::Borrowed(&module.types[module.global_variables[*handle].ty].inner), + Cow::Borrowed(&module.types[module.global_variables[handle].ty].inner), ), Expression::LocalVariable(handle) => ( builder.locals_lookup.get(&handle).unwrap().clone(), - Cow::Borrowed(&module.types[builder.locals[*handle].ty].inner), + Cow::Borrowed(&module.types[builder.locals[handle].ty].inner), ), Expression::Load { pointer } => { - write_expression(&builder.expressions[*pointer], module, builder)? + write_expression(&builder.expressions[pointer], module, builder)? } Expression::ImageSample { image, sampler, coordinate, + level, depth_ref, } => { let (image_expr, image_ty) = - write_expression(&builder.expressions[*image], module, builder)?; + write_expression(&builder.expressions[image], module, builder)?; let (sampler_expr, sampler_ty) = - write_expression(&builder.expressions[*sampler], module, builder)?; + write_expression(&builder.expressions[sampler], module, builder)?; let (coordinate_expr, coordinate_ty) = - write_expression(&builder.expressions[*coordinate], module, builder)?; + write_expression(&builder.expressions[coordinate], module, builder)?; - let (kind, dim, arrayed, ms, width) = match image_ty.as_ref() { - TypeInner::Image { base, dim, flags } => match module.types[*base].inner { - TypeInner::Scalar { kind, width } => ( - kind, - *dim, - flags.contains(ImageFlags::ARRAYED), - flags.contains(ImageFlags::MULTISAMPLED), - width, - ), - _ => { - return Err(Error::Custom(format!( - "Cannot build image of {}", - write_type( - *base, - &module.types, - builder.structs, - None, - builder.features - )? - ))) - } - }, - TypeInner::DepthImage { dim, arrayed } => { - (ScalarKind::Float, *dim, *arrayed, false, 4) - } + let (kind, dim, arrayed, class) = match *image_ty.as_ref() { + TypeInner::Image { + kind, + dim, + arrayed, + class, + } => (kind, dim, arrayed, class), _ => return Err(Error::Custom(format!("Cannot sample {:?}", image_ty))), }; + let ms = match class { + crate::ImageClass::Multisampled => true, + _ => false, + }; let shadow = match sampler_ty.as_ref() { TypeInner::Sampler { comparison } => *comparison, _ => { @@ -786,7 +755,6 @@ fn write_expression<'a>( ))) } }; - let size = match coordinate_ty.as_ref() { TypeInner::Vector { size, .. } => *size, _ => { @@ -818,18 +786,29 @@ fn write_expression<'a>( "vec{}({},{})", size as u8 + 1, coordinate_expr, - write_expression(&builder.expressions[*depth_ref], module, builder)?.0 + write_expression(&builder.expressions[depth_ref], module, builder)?.0 ) } else { coordinate_expr }; - let expr = if !ms { - format!("texture({},{})", sampler_constructor, coordinate) - } else { - todo!() + //TODO: handle MS + let expr = match level { + crate::SampleLevel::Auto => { + format!("texture({},{})", sampler_constructor, coordinate) + } + crate::SampleLevel::Exact(expr) => { + let (level_expr, _) = + write_expression(&builder.expressions[expr], module, builder)?; + format!( + "textureLod({}, {}, {})", + sampler_constructor, coordinate, level_expr + ) + } + crate::SampleLevel::Bias(_) => todo!(), }; + let width = 4; let ty = if shadow { Cow::Owned(TypeInner::Scalar { kind, width }) } else { @@ -838,8 +817,66 @@ fn write_expression<'a>( (expr, ty) } + Expression::ImageLoad { + image, + coordinate, + index: _, + } => { + let (image_expr, image_ty) = + write_expression(&builder.expressions[image], module, builder)?; + let (coordinate_expr, coordinate_ty) = + write_expression(&builder.expressions[coordinate], module, builder)?; + + let (kind, dim, arrayed, class) = match *image_ty.as_ref() { + TypeInner::Image { + kind, + dim, + arrayed, + class, + } => (kind, dim, arrayed, class), + _ => return Err(Error::Custom(format!("Cannot load {:?}", image_ty))), + }; + + let ms = match class { + crate::ImageClass::Multisampled => true, + _ => false, + }; + let size = match coordinate_ty.as_ref() { + TypeInner::Vector { size, .. } => *size, + _ => { + return Err(Error::Custom(format!( + "Cannot sample with coordinates of type {:?}", + coordinate_ty + ))) + } + }; + + //TODO: fix this + let sampler_constructor = format!( + "{}sampler{}{}{}({})", + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => "", + _ => return Err(Error::Custom(String::from("Cannot build image of bools",))), + }, + ImageDimension(dim), + if ms { "MS" } else { "" }, + if arrayed { "Array" } else { "" }, + image_expr, + ); + + let expr = if !ms { + format!("texture({},{})", sampler_constructor, coordinate_expr) + } else { + todo!() + }; + + let width = 4; + (expr, Cow::Owned(TypeInner::Vector { kind, width, size })) + } Expression::Unary { op, expr } => { - let (expr, ty) = write_expression(&builder.expressions[*expr], module, builder)?; + let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; ( format!( @@ -855,9 +892,9 @@ fn write_expression<'a>( } Expression::Binary { op, left, right } => { let (left_expr, left_ty) = - write_expression(&builder.expressions[*left], module, builder)?; + write_expression(&builder.expressions[left], module, builder)?; let (right_expr, right_ty) = - write_expression(&builder.expressions[*right], module, builder)?; + write_expression(&builder.expressions[right], module, builder)?; let op = match op { BinaryOperator::Add => "+", @@ -902,7 +939,7 @@ fn write_expression<'a>( (format!("({} {} {})", left_expr, op, right_expr), ty) } Expression::Intrinsic { fun, argument } => { - let (expr, ty) = write_expression(&builder.expressions[*argument], module, builder)?; + let (expr, ty) = write_expression(&builder.expressions[argument], module, builder)?; ( format!( @@ -922,8 +959,8 @@ fn write_expression<'a>( } Expression::DotProduct(left, right) => { let (left_expr, left_ty) = - write_expression(&builder.expressions[*left], module, builder)?; - let (right_expr, _) = write_expression(&builder.expressions[*right], module, builder)?; + write_expression(&builder.expressions[left], module, builder)?; + let (right_expr, _) = write_expression(&builder.expressions[right], module, builder)?; let ty = match left_ty.as_ref() { TypeInner::Vector { kind, width, .. } => Cow::Owned(TypeInner::Scalar { @@ -942,13 +979,13 @@ fn write_expression<'a>( } Expression::CrossProduct(left, right) => { let (left_expr, left_ty) = - write_expression(&builder.expressions[*left], module, builder)?; - let (right_expr, _) = write_expression(&builder.expressions[*right], module, builder)?; + write_expression(&builder.expressions[left], module, builder)?; + let (right_expr, _) = write_expression(&builder.expressions[right], module, builder)?; (format!("cross({},{})", left_expr, right_expr), left_ty) } Expression::Derivative { axis, expr } => { - let (expr, ty) = write_expression(&builder.expressions[*expr], module, builder)?; + let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; ( format!( @@ -963,9 +1000,12 @@ fn write_expression<'a>( ty, ) } - Expression::Call { origin, arguments } => { - let ty = match origin { - FunctionOrigin::Local(function) => module.functions[*function] + Expression::Call { + ref origin, + ref arguments, + } => { + let ty = match *origin { + FunctionOrigin::Local(function) => module.functions[function] .return_type .map(|ty| Cow::Borrowed(&module.types[ty].inner)) .unwrap_or(Cow::Owned( @@ -979,8 +1019,8 @@ fn write_expression<'a>( ( format!( "{}({})", - match origin { - FunctionOrigin::External(name) => name, + match *origin { + FunctionOrigin::External(ref name) => name, FunctionOrigin::Local(handle) => builder.functions.get(&handle).unwrap(), }, arguments @@ -1141,8 +1181,13 @@ fn write_type( Cow::Owned(structs.get(&ty).unwrap().clone()) } } - TypeInner::Image { base, dim, flags } => { - if flags.contains(ImageFlags::ARRAYED) + TypeInner::Image { + kind, + dim, + arrayed, + class, + } => { + if arrayed && dim != crate::ImageDimension::D2 && !features.contains(SupportedFeatures::NON_2D_TEXTURE_ARRAYS) { @@ -1153,31 +1198,19 @@ fn write_type( Cow::Owned(format!( "{}texture{}{}", - match types[base].inner { - TypeInner::Scalar { kind, .. } => match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => "", - ScalarKind::Bool => - return Err(Error::Custom(String::from( - "Cannot build image of booleans", - ))), - }, - _ => - return Err(Error::Custom(format!( - "Cannot build image of type {}", - write_type(base, types, structs, block, features)? + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => "", + ScalarKind::Bool => + return Err(Error::Custom(String::from( + "Cannot build image of booleans", ))), }, ImageDimension(dim), - write_image_flags(flags, features)? + write_image_flags(arrayed, class, features)? )) } - TypeInner::DepthImage { dim, arrayed } => Cow::Owned(format!( - "texture{}{}", - ImageDimension(dim), - if arrayed { "Array" } else { "" } - )), TypeInner::Sampler { comparison } => Cow::Borrowed(if comparison { "sampler" } else { @@ -1240,32 +1273,29 @@ fn write_array_size(size: ArraySize) -> Result { }) } -fn write_image_flags(flags: ImageFlags, features: SupportedFeatures) -> Result { - let ms = if flags.contains(ImageFlags::MULTISAMPLED) { - if features.contains(SupportedFeatures::MULTISAMPLED_TEXTURES) { +fn write_image_flags( + arrayed: bool, + class: ImageClass, + features: SupportedFeatures, +) -> Result { + let ms = match class { + ImageClass::Multisampled => { + if !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURES) { + return Err(Error::Custom(String::from( + "Multi sampled textures aren't supported", + ))); + } + if arrayed && !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS) { + return Err(Error::Custom(String::from( + "Multi sampled texture arrays aren't supported", + ))); + } "MS" - } else { - return Err(Error::Custom(String::from( - "Multi sampled textures aren't supported", - ))); } - } else { - "" + _ => "", }; - let array = if flags.contains(ImageFlags::ARRAYED) { - "Array" - } else { - "" - }; - - if flags.contains(ImageFlags::ARRAYED & ImageFlags::MULTISAMPLED) - && !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS) - { - return Err(Error::Custom(String::from( - "Multi sampled texture arrays aren't supported", - ))); - } + let array = if arrayed { "Array" } else { "" }; Ok(format!("{}{}", ms, array)) } diff --git a/src/back/mod.rs b/src/back/mod.rs index 11439f934..fc601cd9f 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -3,5 +3,5 @@ #[cfg(feature = "glsl-out")] pub mod glsl; pub mod msl; -#[cfg(feature = "spirv")] +#[cfg(feature = "spirv-out")] pub mod spv; diff --git a/src/back/msl.rs b/src/back/msl.rs index 627bd1751..4bf57ba0b 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -63,7 +63,7 @@ pub enum Error { MixedExecutionModels(crate::Handle), MissingBinding(crate::Handle), MissingBindTarget(BindSource), - InvalidImageFlags(crate::ImageFlags), + InvalidImageAccess(crate::StorageAccess), MutabilityViolation(crate::Handle), BadName(String), UnexpectedGlobalType(crate::Handle), @@ -74,6 +74,7 @@ pub enum Error { UnsupportedBinaryOp(crate::BinaryOperator), UnableToInferBinaryOpOutput(crate::TypeInner, crate::BinaryOperator, crate::TypeInner), UnexpectedImageType(crate::TypeInner), + UnexpectedSampleLevel(crate::SampleLevel), UnexpectedDistanceArgument(crate::TypeInner), UnsupportedCall(String), UnsupportedExpression(crate::Expression), @@ -96,15 +97,6 @@ enum LocationMode { Uniform, } -fn dim_str(dim: crate::ImageDimension) -> &'static str { - match dim { - crate::ImageDimension::D1 => "1d", - crate::ImageDimension::D2 => "2d", - crate::ImageDimension::D3 => "3d", - crate::ImageDimension::Cube => "Cube", - } -} - #[derive(Debug, Clone, Copy)] pub struct Options<'a> { pub binding_map: &'a BindingMap, @@ -112,7 +104,7 @@ pub struct Options<'a> { impl Options<'_> { fn resolve_binding( - &self, + self, binding: &crate::Binding, mode: LocationMode, ) -> Result { @@ -591,16 +583,37 @@ impl Writer { image, sampler, coordinate, + level, depth_ref: None, } => { + //TODO: handle arrayed images let ty_image = self.put_expression(image, function, module)?; write!(self.out, ".sample(")?; self.put_expression(sampler, function, module)?; write!(self.out, ", ")?; self.put_expression(coordinate, function, module)?; + match level { + crate::SampleLevel::Auto => {} + crate::SampleLevel::Exact(h) => { + write!(self.out, ", level(")?; + self.put_expression(h, function, module)?; + write!(self.out, ")")?; + } + crate::SampleLevel::Bias(h) => { + write!(self.out, ", bias(")?; + self.put_expression(h, function, module)?; + write!(self.out, ")")?; + } + } write!(self.out, ")")?; match *ty_image.borrow() { - crate::TypeInner::Image { base, .. } => Ok(module.borrow_type(base)), + crate::TypeInner::Image { kind, .. } => { + Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + size: crate::VectorSize::Quad, + kind, + width: 4, + })) + } ref other => Err(Error::UnexpectedImageType(other.clone())), } } @@ -608,8 +621,10 @@ impl Writer { image, sampler, coordinate, + level, depth_ref: Some(dref), } => { + //TODO: handle arrayed images self.put_expression(image, function, module)?; write!(self.out, ".sample_compare(")?; self.put_expression(sampler, function, module)?; @@ -617,12 +632,44 @@ impl Writer { self.put_expression(coordinate, function, module)?; write!(self.out, ", ")?; self.put_expression(dref, function, module)?; + match level { + crate::SampleLevel::Auto => {} + crate::SampleLevel::Exact(h) => { + write!(self.out, ", level(")?; + self.put_expression(h, function, module)?; + write!(self.out, ")")?; + } + crate::SampleLevel::Bias(_) => return Err(Error::UnexpectedSampleLevel(level)), + } write!(self.out, ")")?; Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: 4, })) } + crate::Expression::ImageLoad { + image, + coordinate, + index, + } => { + //TODO: handle arrayed images + let ty_image = self.put_expression(image, function, module)?; + write!(self.out, ".read(")?; + self.put_expression(coordinate, function, module)?; + write!(self.out, ", ")?; + self.put_expression(index, function, module)?; + write!(self.out, ")")?; + match *ty_image.borrow() { + crate::TypeInner::Image { kind, .. } => { + Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + size: crate::VectorSize::Quad, + kind, + width: 4, + })) + } + ref other => Err(Error::UnexpectedImageType(other.clone())), + } + } crate::Expression::Call { origin: crate::FunctionOrigin::External(ref name), ref arguments, @@ -895,48 +942,48 @@ impl Writer { } write!(self.out, "}}")?; } - crate::TypeInner::Image { base, dim, flags } => { - let base_name = module.types[base].name.or_index(base); - let dim_str = dim_str(dim); - let msaa_str = if flags.contains(crate::ImageFlags::MULTISAMPLED) { - "_ms" - } else { - "" + crate::TypeInner::Image { + kind, + dim, + arrayed, + class, + } => { + let base_name = scalar_kind_string(kind); + let dim_str = match dim { + crate::ImageDimension::D1 => "1d", + crate::ImageDimension::D2 => "2d", + crate::ImageDimension::D3 => "3d", + crate::ImageDimension::Cube => "Cube", }; - let array_str = if flags.contains(crate::ImageFlags::ARRAYED) { - "_array" - } else { - "" + let texture_str = match class { + crate::ImageClass::Depth => "depth", + _ => "texture", }; - let access = if flags.contains(crate::ImageFlags::SAMPLED) { - if flags.intersects(crate::ImageFlags::CAN_STORE) { - return Err(Error::InvalidImageFlags(flags)); - } - "sample" - } else if flags - .contains(crate::ImageFlags::CAN_LOAD | crate::ImageFlags::CAN_STORE) - { - "read_write" - } else if flags.contains(crate::ImageFlags::CAN_STORE) { - "write" - } else if flags.contains(crate::ImageFlags::CAN_LOAD) { - "read" - } else { - return Err(Error::InvalidImageFlags(flags)); + let msaa_str = match class { + crate::ImageClass::Multisampled => "_ms", + _ => "", }; - write!( - self.out, - "typedef texture{}{}{}<{}, access::{}> {}", - dim_str, msaa_str, array_str, base_name, access, name - )?; - } - crate::TypeInner::DepthImage { dim, arrayed } => { - let dim_str = dim_str(dim); let array_str = if arrayed { "_array" } else { "" }; + let access = match class { + crate::ImageClass::Storage(_, access) => { + if access + .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) + { + "read_write" + } else if access.contains(crate::StorageAccess::STORE) { + "write" + } else if access.contains(crate::StorageAccess::LOAD) { + "read" + } else { + return Err(Error::InvalidImageAccess(access)); + } + } + _ => "sample", + }; write!( self.out, - "typedef depth{}{} {}", - dim_str, array_str, name + "typedef {}{}{}{}<{}, access::{}> {}", + texture_str, dim_str, msaa_str, array_str, base_name, access, name )?; } crate::TypeInner::Sampler { comparison: _ } => { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f4448bd11..07c98b96d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,10 +1,9 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ use super::{helpers, Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; -use crate::{Bytes, FastHashMap, FastHashSet, ImageFlags, VectorSize}; use spirv::{Op, Word}; use std::collections::hash_map::Entry; -const BITS_PER_BYTE: Bytes = 8; +const BITS_PER_BYTE: crate::Bytes = 8; enum Signedness { Unsigned = 0, @@ -15,12 +14,12 @@ enum Signedness { enum LocalType { Scalar { kind: crate::ScalarKind, - width: Bytes, + width: crate::Bytes, }, Vector { size: crate::VectorSize, kind: crate::ScalarKind, - width: Bytes, + width: crate::Bytes, }, Pointer { base: crate::Handle, @@ -53,16 +52,16 @@ pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, id_count: u32, - capabilities: FastHashSet, + capabilities: crate::FastHashSet, debugs: Vec, annotations: Vec, writer_flags: WriterFlags, void_type: Option, - lookup_type: FastHashMap, - lookup_function: FastHashMap, Word>, - lookup_function_type: FastHashMap, - lookup_constant: FastHashMap, Word>, - lookup_global_variable: FastHashMap, Word>, + lookup_type: crate::FastHashMap, + lookup_function: crate::FastHashMap, Word>, + lookup_function_type: crate::FastHashMap, + lookup_constant: crate::FastHashMap, Word>, + lookup_global_variable: crate::FastHashMap, Word>, } impl Writer { @@ -71,16 +70,16 @@ impl Writer { physical_layout: PhysicalLayout::new(header), logical_layout: LogicalLayout::default(), id_count: 0, - capabilities: FastHashSet::default(), + capabilities: crate::FastHashSet::default(), debugs: vec![], annotations: vec![], writer_flags, void_type: None, - lookup_type: FastHashMap::default(), - lookup_function: FastHashMap::default(), - lookup_function_type: FastHashMap::default(), - lookup_constant: FastHashMap::default(), - lookup_global_variable: FastHashMap::default(), + lookup_type: crate::FastHashMap::default(), + lookup_function: crate::FastHashMap::default(), + lookup_function_type: crate::FastHashMap::default(), + lookup_constant: crate::FastHashMap::default(), + lookup_global_variable: crate::FastHashMap::default(), } } @@ -368,7 +367,7 @@ impl Writer { &self, id: Word, component_type_id: Word, - component_count: VectorSize, + component_count: crate::VectorSize, ) -> Instruction { let mut instruction = Instruction::new(Op::TypeVector); instruction.set_result(id); @@ -381,7 +380,7 @@ impl Writer { &self, id: Word, column_type_id: Word, - column_count: VectorSize, + column_count: crate::VectorSize, ) -> Instruction { let mut instruction = Instruction::new(Op::TypeMatrix); instruction.set_result(id); @@ -395,49 +394,50 @@ impl Writer { id: Word, sampled_type_id: Word, dim: spirv::Dim, - flags: ImageFlags, - comparison: bool, + arrayed: bool, + class: crate::ImageClass, ) -> Instruction { let mut instruction = Instruction::new(Op::TypeImage); instruction.set_result(id); instruction.add_operand(sampled_type_id); instruction.add_operand(dim as u32); - instruction.add_operand(if comparison { 1 } else { 0 }); - - instruction.add_operand(if flags.contains(crate::ImageFlags::ARRAYED) { - 1 - } else { - 0 + instruction.add_operand(match class { + crate::ImageClass::Depth => 1, + _ => 0, + }); + instruction.add_operand(if arrayed { 1 } else { 0 }); + instruction.add_operand(match class { + crate::ImageClass::Multisampled => 1, + _ => 0, + }); + instruction.add_operand(match class { + crate::ImageClass::Sampled => 1, + _ => 0, }); - instruction.add_operand(if flags.contains(crate::ImageFlags::MULTISAMPLED) { - 1 - } else { - 0 - }); - - instruction.add_operand(if flags.contains(crate::ImageFlags::SAMPLED) { - 1 - } else { - 0 - }); - - // TODO Image Format defaults to Unknown, not yet in IR - instruction.add_operand(spirv::ImageFormat::Unknown as u32); + let (format, access) = match class { + crate::ImageClass::Storage(format, access) => { + let spv_format = match format { + crate::StorageFormat::Rgba32f => spirv::ImageFormat::Rgba32f, + }; + (spv_format, access) + } + _ => (spirv::ImageFormat::Unknown, crate::StorageAccess::empty()), + }; + instruction.add_operand(format as u32); // Access Qualifier - instruction.add_operand( - if flags.contains(crate::ImageFlags::CAN_STORE) - && flags.contains(crate::ImageFlags::CAN_LOAD) - { + if !access.is_empty() { + instruction.add_operand(if access == crate::StorageAccess::all() { 2 - } else if flags.contains(crate::ImageFlags::CAN_STORE) { + } else if access.contains(crate::StorageAccess::STORE) { 1 } else { 0 - }, - ); + }); + } + instruction } @@ -704,7 +704,7 @@ impl Writer { /// Primitive Instructions /// - fn write_scalar(&self, id: Word, kind: crate::ScalarKind, width: Bytes) -> Instruction { + fn write_scalar(&self, id: Word, kind: crate::ScalarKind, width: crate::Bytes) -> Instruction { let bits = (width * BITS_PER_BYTE) as u32; match kind { crate::ScalarKind::Sint => self.instruction_type_int(id, bits, Signedness::Signed), @@ -786,23 +786,23 @@ impl Writer { ); self.instruction_type_matrix(id, vector_id, columns) } - crate::TypeInner::Image { base, dim, flags } => { - let type_id = self.get_type_id(arena, LookupType::Handle(base)); + crate::TypeInner::Image { + kind, + dim, + arrayed, + class, + } => { + let type_id = self.get_type_id( + arena, + LookupType::Local(LocalType::Vector { + size: crate::VectorSize::Quad, + kind, + width: 4, + }), + ); let dim = map_dim(dim); self.try_add_capabilities(dim.required_capabilities()); - self.instruction_type_image(id, type_id, dim, flags, false) - } - crate::TypeInner::DepthImage { dim, arrayed } => { - let type_id = 0; //TODO! - let dim = map_dim(dim); - self.try_add_capabilities(dim.required_capabilities()); - - let flags = if arrayed { - crate::ImageFlags::ARRAYED - } else { - crate::ImageFlags::empty() - }; - self.instruction_type_image(id, type_id, dim, flags, true) + self.instruction_type_image(id, type_id, dim, arrayed, class) } crate::TypeInner::Sampler { comparison: _ } => self.instruction_type_sampler(id), crate::TypeInner::Array { size, stride, .. } => { diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs index 1a43ed973..101448c1d 100644 --- a/src/front/glsl/helpers.rs +++ b/src/front/glsl/helpers.rs @@ -1,4 +1,4 @@ -use crate::{Arena, ImageDimension, ImageFlags, ScalarKind, Type, TypeInner, VectorSize}; +use crate::{ImageClass, ImageDimension, ScalarKind, TypeInner, VectorSize}; use glsl::syntax::{BinaryOp, TypeSpecifierNonArray, UnaryOp}; pub fn glsl_to_spirv_unary_op(op: UnaryOp) -> crate::UnaryOperator { @@ -36,7 +36,7 @@ pub fn glsl_to_spirv_binary_op(op: BinaryOp) -> crate::BinaryOperator { } } -pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> Option { +pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray) -> Option { use TypeSpecifierNonArray::*; Some(match ty { @@ -248,53 +248,28 @@ pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> }, TypeName(ty_name) => { if let Some(t_pos) = ty_name.0.find("texture") { - let scalar_kind = match &ty_name.0[..t_pos] { + let kind = match &ty_name.0[..t_pos] { "" => ScalarKind::Float, "i" => ScalarKind::Sint, "u" => ScalarKind::Uint, _ => panic!(), }; - let base = types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: scalar_kind, - width: 4, - }, - }); - - let (dim, flags) = match &ty_name.0[(t_pos + 7)..] { - "1D" => (ImageDimension::D1, ImageFlags::SAMPLED), - "2D" => (ImageDimension::D2, ImageFlags::SAMPLED), - "3D" => (ImageDimension::D3, ImageFlags::SAMPLED), - "1DArray" => ( - ImageDimension::D1, - ImageFlags::SAMPLED | ImageFlags::ARRAYED, - ), - "2DArray" => ( - ImageDimension::D2, - ImageFlags::SAMPLED | ImageFlags::ARRAYED, - ), - "3DArray" => ( - ImageDimension::D3, - ImageFlags::SAMPLED | ImageFlags::ARRAYED, - ), - "2DMS" => ( - ImageDimension::D2, - ImageFlags::SAMPLED | ImageFlags::MULTISAMPLED, - ), - "2DMSArray" => ( - ImageDimension::D2, - ImageFlags::SAMPLED | ImageFlags::ARRAYED | ImageFlags::MULTISAMPLED, - ), - "Cube" => (ImageDimension::Cube, ImageFlags::SAMPLED), - "CubeArray" => ( - ImageDimension::Cube, - ImageFlags::SAMPLED | ImageFlags::ARRAYED, - ), + let arrayed = ty_name.0.ends_with("Array"); + let (dim, class) = match &ty_name.0[(t_pos + 7)..] { + "1D" | "1DArray" => (ImageDimension::D1, ImageClass::Sampled), + "2D" | "2DArray" => (ImageDimension::D2, ImageClass::Sampled), + "3D" | "3DArray" => (ImageDimension::D3, ImageClass::Sampled), + "2DMS" | "2DMSArray" => (ImageDimension::D2, ImageClass::Multisampled), + "Cube" | "CubeArray" => (ImageDimension::Cube, ImageClass::Sampled), _ => panic!(), }; - return Some(TypeInner::Image { base, dim, flags }); + return Some(TypeInner::Image { + kind, + dim, + arrayed, + class, + }); } match ty_name.0.as_str() { diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 888e9b63c..b4061233b 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -877,6 +877,7 @@ impl<'a> Parser<'a> { image: expressions.append(image), sampler: expressions.append(sampler), coordinate: expressions.append(coordinate), + level: crate::SampleLevel::Auto, depth_ref: None, //TODO }) } @@ -1005,7 +1006,7 @@ impl<'a> Parser<'a> { // None = void fn parse_type(&mut self, ty: TypeSpecifier) -> Option> { - let base_ty = helpers::glsl_to_spirv_type(ty.ty, &mut self.types)?; + let base_ty = helpers::glsl_to_spirv_type(ty.ty)?; let ty = if let Some(array_spec) = ty.array_specifier { let handle = self.types.fetch_or_append(Type { diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index ae4443bb1..953a0034d 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -1,5 +1,4 @@ -#![allow(unused_braces)] -#![allow(clippy::panic)] +#![allow(clippy::panic, unused_braces)] use pomelo::pomelo; pomelo! { @@ -566,8 +565,10 @@ pomelo! { for (id, initializer) in d.ids_initializers { // check if already declared in current scope #[cfg(feature = "glsl-validate")] - if extra.context.lookup_local_var_current_scope(&id).is_some() { - return Err(ErrorKind::VariableAlreadyDeclared(id)) + { + if extra.context.lookup_local_var_current_scope(&id).is_some() { + return Err(ErrorKind::VariableAlreadyDeclared(id)) + } } let localVar = extra.context.local_variables.append( LocalVariable { diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 6329975e4..0c4d23da5 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -59,15 +59,24 @@ pub fn map_storage_class(word: spirv::Word) -> Result Result { - match spirv::Dim::from_u32(word) { - Some(spirv::Dim::Dim1D) => Ok(crate::ImageDimension::D1), - Some(spirv::Dim::Dim2D) => Ok(crate::ImageDimension::D2), - Some(spirv::Dim::Dim3D) => Ok(crate::ImageDimension::D3), - Some(spirv::Dim::DimCube) => Ok(crate::ImageDimension::Cube), + use spirv::Dim as D; + match D::from_u32(word) { + Some(D::Dim1D) => Ok(crate::ImageDimension::D1), + Some(D::Dim2D) => Ok(crate::ImageDimension::D2), + Some(D::Dim3D) => Ok(crate::ImageDimension::D3), + Some(D::DimCube) => Ok(crate::ImageDimension::Cube), _ => Err(Error::UnsupportedImageDim(word)), } } +pub fn map_image_format(word: spirv::Word) -> Result { + use spirv::ImageFormat as If; + match If::from_u32(word) { + Some(If::Rgba32f) => Ok(crate::StorageFormat::Rgba32f), + _ => Err(Error::UnsupportedImageFormat(word)), + } +} + pub fn map_width(word: spirv::Word) -> Result { (word >> 3) // bits to bytes .try_into() diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index f4384cd89..b467020b5 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -17,6 +17,7 @@ pub enum Error { UnsupportedExecutionModel(spirv::Word), UnsupportedStorageClass(spirv::Word), UnsupportedImageDim(spirv::Word), + UnsupportedImageFormat(spirv::Word), UnsupportedBuiltIn(spirv::Word), UnsupportedControlFlow(spirv::Word), UnsupportedBinaryOperator(spirv::Word), @@ -37,6 +38,7 @@ pub enum Error { InvalidStoreType(spirv::Word), InvalidBinding(spirv::Word), InvalidImageExpression(Handle), + InvalidImageBaseType(Handle), InvalidSamplerExpression(Handle), InvalidSampleImage(Handle), InvalidSampleSampler(Handle), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 701c150db..0f3d8dcb4 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -40,7 +40,7 @@ pub struct Instruction { } impl Instruction { - fn expect(&self, count: u16) -> Result<(), Error> { + fn expect(self, count: u16) -> Result<(), Error> { if self.wc == count { Ok(()) } else { @@ -48,7 +48,7 @@ impl Instruction { } } - fn expect_at_least(&self, count: u16) -> Result<(), Error> { + fn expect_at_least(self, count: u16) -> Result<(), Error> { if self.wc >= count { Ok(()) } else { @@ -817,18 +817,16 @@ impl> Parser { match type_arena[image_type_handle].inner { //TODO: compare the result type crate::TypeInner::Image { - base: _, + kind: _, dim, - flags, - } if flags - & (crate::ImageFlags::MULTISAMPLED | crate::ImageFlags::SAMPLED) - == crate::ImageFlags::SAMPLED => - { + arrayed, + class: crate::ImageClass::Sampled, + } => { if !check_sample_coordinates( &type_arena[coord_type_handle], crate::ScalarKind::Float, dim, - flags.contains(crate::ImageFlags::ARRAYED), + arrayed, ) { return Err(Error::InvalidSampleCoordinates(coord_type_handle)); } @@ -840,6 +838,7 @@ impl> Parser { image: si_lexp.image, sampler: si_lexp.sampler, coordinate: coord_lexp.handle, + level: crate::SampleLevel::Auto, depth_ref: None, }; self.lookup_expression.insert( @@ -877,7 +876,12 @@ impl> Parser { }; match type_arena[image_type_handle].inner { //TODO: compare the result type - crate::TypeInner::DepthImage { dim, arrayed } => { + crate::TypeInner::Image { + kind: _, + dim, + arrayed, + class: crate::ImageClass::Depth, + } => { if !check_sample_coordinates( &type_arena[coord_type_handle], crate::ScalarKind::Float, @@ -904,6 +908,7 @@ impl> Parser { image: si_lexp.image, sampler: si_lexp.sampler, coordinate: coord_lexp.handle, + level: crate::SampleLevel::Auto, depth_ref: Some(dref_lexp.handle), }; self.lookup_expression.insert( @@ -1236,15 +1241,9 @@ impl> Parser { }; *comparison = true; } - crate::TypeInner::Image { - base: _, - dim, - flags, - } => { - ty.inner = crate::TypeInner::DepthImage { - dim, - arrayed: flags.contains(crate::ImageFlags::ARRAYED), - }; + crate::TypeInner::Image { ref mut class, .. } => { + assert_eq!(*class, crate::ImageClass::Sampled); + *class = crate::ImageClass::Multisampled; } _ => panic!("Unexpected comparison type {:?}", ty), } @@ -1753,36 +1752,43 @@ impl> Parser { let id = self.next()?; let sample_type_id = self.next()?; let dim = self.next()?; - let mut flags = crate::ImageFlags::empty(); let _is_depth = self.next()?; - if self.next()? != 0 { - flags |= crate::ImageFlags::ARRAYED; - } - if self.next()? != 0 { - flags |= crate::ImageFlags::MULTISAMPLED; - } - let is_sampled = self.next()?; - if is_sampled != 0 { - flags |= crate::ImageFlags::SAMPLED; - } - let _format = self.next()?; - if inst.wc > 9 { + let is_array = self.next()? != 0; + let is_msaa = self.next()? != 0; + let _is_sampled = self.next()?; + let format = self.next()?; + + let base_handle = self.lookup_type.lookup(sample_type_id)?.handle; + let kind = match module.types[base_handle].inner { + crate::TypeInner::Scalar { kind, .. } | crate::TypeInner::Vector { kind, .. } => kind, + _ => return Err(Error::InvalidImageBaseType(base_handle)), + }; + + let class = if inst.wc > 9 { + let storage_format = map_image_format(format)?; + let mut flags = crate::StorageAccess::empty(); inst.expect(10)?; let access = self.next()?; if access == 0 || access == 2 { - flags |= crate::ImageFlags::CAN_LOAD; + flags |= crate::StorageAccess::LOAD; } if access == 1 || access == 2 { - flags |= crate::ImageFlags::CAN_STORE; + flags |= crate::StorageAccess::STORE; } + crate::ImageClass::Storage(storage_format, flags) + } else if is_msaa { + crate::ImageClass::Multisampled + } else { + crate::ImageClass::Sampled }; let decor = self.future_decor.remove(&id).unwrap_or_default(); let inner = crate::TypeInner::Image { - base: self.lookup_type.lookup(sample_type_id)?.handle, + class, + kind, dim: map_image_dim(dim)?, - flags, + arrayed: is_array, }; let handle = module.types.append(crate::Type { name: decor.name, diff --git a/src/lib.rs b/src/lib.rs index e45ca820f..6d6a6aa09 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,7 +4,7 @@ //! //! To improve performance and reduce memory usage, most structures are stored //! in an [`Arena`], and can be retrieved using the corresponding [`Handle`]. -#![allow(clippy::new_without_default)] +#![allow(clippy::new_without_default, clippy::unneeded_field_pattern)] #![deny(clippy::panic)] mod arena; @@ -207,20 +207,39 @@ bitflags::bitflags! { /// Flags describing an image. #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] - pub struct ImageFlags: u32 { - /// Image is an array. - const ARRAYED = 0x1; - /// Image is multisampled. - const MULTISAMPLED = 0x2; - /// Image is to be accessed with a sampler. - const SAMPLED = 0x4; - /// Image can be used as a source for load ops. - const CAN_LOAD = 0x10; - /// Image can be used as a target for store ops. - const CAN_STORE = 0x20; + pub struct StorageAccess: u32 { + /// Storage can be used as a source for load ops. + const LOAD = 0x1; + /// Storage can be used as a target for store ops. + const STORE = 0x2; } } +// Storage image format. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum StorageFormat { + /// + Rgba32f, + //TODO +} + +/// Sub-class of the image type. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum ImageClass { + /// Regular sampled image. + Sampled, + /// Multi-sampled image. + Multisampled, + /// Depth comparison image. + Depth, + /// Storage image. + Storage(StorageFormat, StorageAccess), +} + /// A data type declared in the module. #[derive(Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -268,12 +287,11 @@ pub enum TypeInner { Struct { members: Vec }, /// Possibly multidimensional array of texels. Image { - base: Handle, + kind: ScalarKind, dim: ImageDimension, - flags: ImageFlags, + arrayed: bool, + class: ImageClass, }, - /// Depth-comparison image. - DepthImage { dim: ImageDimension, arrayed: bool }, /// Can be used to sample values from images. Sampler { comparison: bool }, } @@ -431,6 +449,16 @@ pub enum FunctionOrigin { External(String), } +/// Sampling modifier to control the level of detail. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum SampleLevel { + Auto, + Exact(Handle), + Bias(Handle), +} + /// An expression that can be evaluated to obtain a value. #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -461,13 +489,21 @@ pub enum Expression { LocalVariable(Handle), /// Load a value indirectly. Load { pointer: Handle }, - /// Sample a point from an image. + /// Sample a point from a sampled or a depth image. ImageSample { image: Handle, sampler: Handle, coordinate: Handle, + level: SampleLevel, depth_ref: Option>, }, + /// Load a texel from an image. + ImageLoad { + image: Handle, + coordinate: Handle, + /// This is either LOD index, or sample index, based on the image class. + index: Handle, + }, /// Apply an unary operator. Unary { op: UnaryOperator, diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 7459248ea..814285e23 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -34,15 +34,31 @@ impl<'a> Interface<'a> { image, sampler, coordinate, + level, depth_ref, } => { self.add_inputs(image); self.add_inputs(sampler); self.add_inputs(coordinate); + match level { + crate::SampleLevel::Auto => (), + crate::SampleLevel::Exact(h) | crate::SampleLevel::Bias(h) => { + self.add_inputs(h) + } + } if let Some(dref) = depth_ref { self.add_inputs(dref); } } + E::ImageLoad { + image, + coordinate, + index, + } => { + self.add_inputs(image); + self.add_inputs(coordinate); + self.add_inputs(index); + } E::Unary { expr, .. } => { self.add_inputs(expr); } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index c967bd80c..9a4d5e4a1 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -85,7 +85,8 @@ impl Typifier { crate::Expression::GlobalVariable(h) => global_vars[h].ty, crate::Expression::LocalVariable(h) => local_vars[h].ty, crate::Expression::Load { .. } => unimplemented!(), - crate::Expression::ImageSample { image, .. } => { + crate::Expression::ImageSample { image, .. } + | crate::Expression::ImageLoad { image, .. } => { let image = self.resolve( image, expressions, @@ -96,22 +97,21 @@ impl Typifier { functions, )?; - let (kind, width) = match types[image].inner { - TypeInner::Image { base, .. } => match types[base].inner { - TypeInner::Scalar { kind, width } => (kind, width), - _ => unimplemented!(), + let inner = match types[image].inner { + TypeInner::Image { + kind, + class: crate::ImageClass::Depth, + .. + } => TypeInner::Scalar { kind, width: 4 }, + TypeInner::Image { kind, .. } => TypeInner::Vector { + kind, + width: 4, + size: VectorSize::Quad, }, _ => unreachable!(), }; - types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - kind, - width, - size: VectorSize::Quad, - }, - }) + types.fetch_or_append(Type { name: None, inner }) } crate::Expression::Unary { expr, .. } => self.types[expr.index()], crate::Expression::Binary { op, left, right } => match op { diff --git a/src/proc/validator.rs b/src/proc/validator.rs index b528fc069..364d7fd10 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -53,7 +53,7 @@ impl Validator { } } } - Ti::Image { .. } | Ti::DepthImage { .. } => {} + Ti::Image { .. } => {} Ti::Sampler { comparison: _ } => {} } } From df8364f92c7214361941b8a3ab15752c59327512 Mon Sep 17 00:00:00 2001 From: Matus Talcik Date: Thu, 27 Aug 2020 02:29:18 +0200 Subject: [PATCH 0160/2212] Add kill, unreachable + switch (#156) --- src/front/spv/flow.rs | 141 +++++++++++++++++++++++++++++++++++------- src/front/spv/mod.rs | 10 ++- 2 files changed, 128 insertions(+), 23 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index a2f35b846..2fa1036db 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -8,6 +8,7 @@ use super::function::{BlockId, MergeInstruction, Terminator}; use crate::FastHashMap; use petgraph::{ + algo::has_path_connecting, graph::{node_index, NodeIndex}, visit::EdgeRef, Directed, Direction, @@ -81,9 +82,11 @@ impl FlowGraph { } // Branch Edges - match self.flow[source_node_index].terminator { + let terminator = self.flow[source_node_index].terminator.clone(); + match terminator { Terminator::Branch { target_id } => { let target_node_index = block_to_node[&target_id]; + self.flow.add_edge( source_node_index, target_node_index, @@ -107,8 +110,28 @@ impl FlowGraph { ControlFlowEdgeType::IfFalse, ); } - Terminator::Switch { .. } => { - // TODO + Terminator::Switch { + selector: _, + default, + ref targets, + } => { + let default_node_index = block_to_node[&default]; + + self.flow.add_edge( + source_node_index, + default_node_index, + ControlFlowEdgeType::Forward, + ); + + for (_, target_block_id) in targets.iter() { + let target_node_index = block_to_node[&target_block_id]; + + self.flow.add_edge( + source_node_index, + target_node_index, + ControlFlowEdgeType::Forward, + ); + } } Terminator::Return { .. } => { self.flow[source_node_index].ty = Some(ControlFlowNodeType::Return) @@ -120,6 +143,7 @@ impl FlowGraph { }; } + // 2. // Classify Nodes/Edges as one of [Break, Continue, Back] for edge_index in self.flow.edge_indices() { let (node_source_index, node_target_index) = @@ -167,36 +191,103 @@ impl FlowGraph { /// Traverses the flow graph and returns a list of Naga's statements. pub fn to_naga(&self) -> Result { - self.naga_traverse(node_index(0)) + self.naga_traverse(node_index(0), None) } - fn naga_traverse(&self, node_index: BlockNodeIndex) -> Result { + fn naga_traverse( + &self, + node_index: BlockNodeIndex, + stop_node_index: Option, + ) -> Result { + if let Some(stop_node_index) = stop_node_index { + if stop_node_index == node_index { + return Ok(vec![]); + } + } + let node = &self.flow[node_index]; match node.ty { Some(ControlFlowNodeType::Header) => { + let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; + let mut result = node.block.clone(); + match node.terminator { Terminator::BranchConditional { condition, true_id, false_id, } => { - let mut result = node.block.clone(); result.push(crate::Statement::If { condition, - accept: self.naga_traverse(self.block_to_node[&true_id])?, - reject: self.naga_traverse(self.block_to_node[&false_id])?, + accept: self.naga_traverse( + self.block_to_node[&true_id], + Some(merge_node_index), + )?, + reject: self.naga_traverse( + self.block_to_node[&false_id], + Some(merge_node_index), + )?, }); - Ok(result) } - Terminator::Switch { .. } => { - // TODO - Ok(node.block.clone()) + Terminator::Switch { + selector, + default, + ref targets, + } => { + let mut cases = FastHashMap::default(); + + for i in 0..targets.len() { + let left_target_node_index = self.block_to_node[&targets[i].1]; + + let fallthrough: Option = if i < targets.len() - 1 { + let right_target_node_index = self.block_to_node[&targets[i + 1].1]; + if has_path_connecting( + &self.flow, + left_target_node_index, + right_target_node_index, + None, + ) { + Some(crate::FallThrough {}) + } else { + None + } + } else { + None + }; + + cases.insert( + targets[i].0, + ( + self.naga_traverse( + left_target_node_index, + Some(merge_node_index), + )?, + fallthrough, + ), + ); + } + + result.push(crate::Statement::Switch { + selector, + cases, + default: self.naga_traverse( + self.block_to_node[&default], + Some(merge_node_index), + )?, + }); } - _ => Err(Error::InvalidTerminator), - } + _ => { + return Err(Error::InvalidTerminator); + } + }; + + result.extend(self.naga_traverse(merge_node_index, None)?); + + Ok(result) } Some(ControlFlowNodeType::Loop) => { + let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; let continuing: crate::Block = { let continue_edge = self .flow @@ -215,12 +306,14 @@ impl FlowGraph { false_id, } => body.push(crate::Statement::If { condition, - accept: self.naga_traverse(self.block_to_node[&true_id])?, - reject: self.naga_traverse(self.block_to_node[&false_id])?, + accept: self + .naga_traverse(self.block_to_node[&true_id], Some(merge_node_index))?, + reject: self + .naga_traverse(self.block_to_node[&false_id], Some(merge_node_index))?, }), - Terminator::Branch { target_id } => { - body.extend(self.naga_traverse(self.block_to_node[&target_id])?) - } + Terminator::Branch { target_id } => body.extend( + self.naga_traverse(self.block_to_node[&target_id], Some(merge_node_index))?, + ), _ => return Err(Error::InvalidTerminator), }; @@ -235,8 +328,10 @@ impl FlowGraph { false_id, } => result.push(crate::Statement::If { condition, - accept: self.naga_traverse(self.block_to_node[&true_id])?, - reject: self.naga_traverse(self.block_to_node[&false_id])?, + accept: self + .naga_traverse(self.block_to_node[&true_id], stop_node_index)?, + reject: self + .naga_traverse(self.block_to_node[&false_id], stop_node_index)?, }), _ => return Err(Error::InvalidTerminator), }; @@ -267,7 +362,9 @@ impl FlowGraph { None => match node.terminator { Terminator::Branch { target_id } => { let mut result = node.block.clone(); - result.extend(self.naga_traverse(self.block_to_node[&target_id])?); + result.extend( + self.naga_traverse(self.block_to_node[&target_id], stop_node_index)?, + ); Ok(result) } _ => Ok(node.block.clone()), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 0f3d8dcb4..3d165aa86 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1040,6 +1040,14 @@ impl> Parser { inst.expect(5)?; self.parse_expr_binary_op(expressions, map_binary_operator(op)?)?; } + Op::Kill => { + inst.expect(1)?; + break Terminator::Kill; + } + Op::Unreachable => { + inst.expect(1)?; + break Terminator::Unreachable; + } Op::Return => { inst.expect(1)?; break Terminator::Return { value: None }; @@ -1072,7 +1080,7 @@ impl> Parser { let default = self.next()?; let mut targets = Vec::new(); - for _ in 0..inst.wc - 3 { + for _ in 0..(inst.wc - 3) / 2 { let literal = self.next()?; let target = self.next()?; targets.push((literal as i32, target)); From 64bb2104cf14c84c4f39c61df2da379f0ff0427d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 27 Aug 2020 15:26:55 +0100 Subject: [PATCH 0161/2212] glsl-out: Less allocations, handle struct member origin and correctly handle empty names (#160) * Removed half of the clones Fixed struct field names with invalid ident * Fix struct member origin not being respected * is_valid_ident handles empty names --- src/back/glsl.rs | 201 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 136 insertions(+), 65 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 8e1a5cbb0..4a9eaec42 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,8 +1,8 @@ use crate::{ Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageClass, Interpolation, - IntrinsicFunction, LocalVariable, Module, ScalarKind, ShaderStage, Statement, StorageClass, - StructMember, Type, TypeInner, UnaryOperator, + IntrinsicFunction, LocalVariable, MemberOrigin, Module, ScalarKind, ShaderStage, Statement, + StorageClass, StructMember, Type, TypeInner, UnaryOperator, }; use std::{ borrow::Cow, @@ -102,12 +102,7 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> let mut namer = |name: Option<&'a String>| { if let Some(name) = name { - if name.starts_with(|c: char| !(c.is_ascii_alphabetic() || c == '_')) - || name.contains(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) - || name.starts_with("gl_") - || name == "main" - || names.get(name.as_str()).is_some() - { + if !is_valid_ident(name) || names.get(name.as_str()).is_some() { counter += 1; while names.get(format!("_{}", counter).as_str()).is_some() { counter += 1; @@ -258,7 +253,7 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> if let Some(ref binding) = global.binding { if !es { - write!(out, "layout({}) ", Binding(binding.clone()))?; + write!(out, "layout({}) ", Binding(binding))?; } } @@ -405,8 +400,8 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> Ok(()) } -struct Binding(crate::Binding); -impl fmt::Display for Binding { +struct Binding<'a>(&'a crate::Binding); +impl<'a> fmt::Display for Binding<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.0 { crate::Binding::BuiltIn(_) => write!(f, ""), // Ignore because they are variables with a predefined name @@ -429,10 +424,10 @@ struct StatementBuilder<'a> { pub features: SupportedFeatures, } -fn write_statement( +fn write_statement<'a, 'b>( sta: &Statement, - module: &Module, - builder: &mut StatementBuilder<'_>, + module: &'a Module, + builder: &'b mut StatementBuilder<'a>, indent: usize, ) -> Result { Ok(match sta { @@ -566,29 +561,39 @@ fn write_statement( }) } -fn write_expression<'a>( +fn write_expression<'a, 'b>( expr: &Expression, module: &'a Module, - builder: &mut StatementBuilder<'_>, -) -> Result<(String, Cow<'a, TypeInner>), Error> { + builder: &'b mut StatementBuilder<'a>, +) -> Result<(Cow<'a, str>, Cow<'a, TypeInner>), Error> { Ok(match *expr { Expression::Access { base, index } => { let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; let inner = match *ty.as_ref() { - TypeInner::Vector { kind, width, .. } | TypeInner::Matrix { kind, width, .. } => { + TypeInner::Vector { kind, width, .. } => { Cow::Owned(TypeInner::Scalar { kind, width }) } + TypeInner::Matrix { + kind, + width, + columns, + .. + } => Cow::Owned(TypeInner::Vector { + kind, + width, + size: columns, + }), TypeInner::Array { base, .. } => Cow::Borrowed(&module.types[base].inner), _ => return Err(Error::Custom(format!("Cannot dynamically index {:?}", ty))), }; ( - format!( + Cow::Owned(format!( "{}[{}]", base_expr, write_expression(&builder.expressions[index], module, builder)?.0 - ), + )), inner, ) } @@ -596,35 +601,53 @@ fn write_expression<'a>( let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; match *ty.as_ref() { - TypeInner::Vector { kind, width, .. } | TypeInner::Matrix { kind, width, .. } => ( - format!("{}[{}]", base_expr, index), + TypeInner::Vector { kind, width, .. } => ( + Cow::Owned(format!("{}[{}]", base_expr, index)), Cow::Owned(TypeInner::Scalar { kind, width }), ), + TypeInner::Matrix { + kind, + width, + columns, + .. + } => ( + Cow::Owned(format!("{}[{}]", base_expr, index)), + Cow::Owned(TypeInner::Vector { + kind, + width, + size: columns, + }), + ), TypeInner::Array { base, .. } => ( - format!("{}[{}]", base_expr, index), + Cow::Owned(format!("{}[{}]", base_expr, index)), Cow::Borrowed(&module.types[base].inner), ), TypeInner::Struct { ref members } => ( - format!( - "{}.{}", - base_expr, - members[index as usize] - .name - .as_ref() - .unwrap_or(&format!("_{}", index)) - ), + if let MemberOrigin::BuiltIn(builtin) = members[index as usize].origin { + Cow::Borrowed(builtin_to_glsl(builtin)) + } else { + Cow::Owned(format!( + "{}.{}", + base_expr, + members[index as usize] + .name + .as_ref() + .filter(|s| is_valid_ident(s)) + .unwrap_or(&format!("_{}", index)) + )) + }, Cow::Borrowed(&module.types[members[index as usize].ty].inner), ), _ => return Err(Error::Custom(format!("Cannot index {:?}", ty))), } } Expression::Constant(constant) => ( - write_constant( + Cow::Owned(write_constant( &module.constants[constant], module, builder, builder.features, - )?, + )?), Cow::Borrowed(&module.types[module.constants[constant].ty].inner), ), Expression::Compose { ty, ref components } => { @@ -685,7 +708,7 @@ fn write_expression<'a>( }; ( - format!( + Cow::Owned(format!( "{}({})", constructor, components @@ -698,21 +721,21 @@ fn write_expression<'a>( .0)) .collect::, _>>()? .join(","), - ), + )), Cow::Borrowed(&module.types[ty].inner), ) } Expression::FunctionParameter(pos) => { - let (arg, ty) = builder.args.get(&pos).unwrap().clone(); + let (arg, ty) = builder.args.get(&pos).unwrap(); - (arg, Cow::Borrowed(&module.types[ty].inner)) + (Cow::Borrowed(arg), Cow::Borrowed(&module.types[*ty].inner)) } Expression::GlobalVariable(handle) => ( - builder.globals.get(&handle).unwrap().clone(), + Cow::Borrowed(builder.globals.get(&handle).unwrap()), Cow::Borrowed(&module.types[module.global_variables[handle].ty].inner), ), Expression::LocalVariable(handle) => ( - builder.locals_lookup.get(&handle).unwrap().clone(), + Cow::Borrowed(builder.locals_lookup.get(&handle).unwrap()), Cow::Borrowed(&module.types[builder.locals[handle].ty].inner), ), Expression::Load { pointer } => { @@ -782,12 +805,12 @@ fn write_expression<'a>( ); let coordinate = if let Some(depth_ref) = depth_ref { - format!( + Cow::Owned(format!( "vec{}({},{})", size as u8 + 1, coordinate_expr, write_expression(&builder.expressions[depth_ref], module, builder)?.0 - ) + )) } else { coordinate_expr }; @@ -815,7 +838,7 @@ fn write_expression<'a>( Cow::Owned(TypeInner::Vector { kind, width, size }) }; - (expr, ty) + (Cow::Owned(expr), ty) } Expression::ImageLoad { image, @@ -873,20 +896,23 @@ fn write_expression<'a>( }; let width = 4; - (expr, Cow::Owned(TypeInner::Vector { kind, width, size })) + ( + Cow::Owned(expr), + Cow::Owned(TypeInner::Vector { kind, width, size }), + ) } Expression::Unary { op, expr } => { let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; ( - format!( + Cow::Owned(format!( "({} {})", match op { UnaryOperator::Negate => "-", UnaryOperator::Not => "~", }, expr - ), + )), ty, ) } @@ -936,13 +962,16 @@ fn write_expression<'a>( } }; - (format!("({} {} {})", left_expr, op, right_expr), ty) + ( + Cow::Owned(format!("({} {} {})", left_expr, op, right_expr)), + ty, + ) } Expression::Intrinsic { fun, argument } => { let (expr, ty) = write_expression(&builder.expressions[argument], module, builder)?; ( - format!( + Cow::Owned(format!( "{:?}({})", match fun { IntrinsicFunction::IsFinite => "!isinf", @@ -953,7 +982,7 @@ fn write_expression<'a>( IntrinsicFunction::Any => "any", }, expr - ), + )), ty, ) } @@ -975,20 +1004,23 @@ fn write_expression<'a>( } }; - (format!("dot({},{})", left_expr, right_expr), ty) + (Cow::Owned(format!("dot({},{})", left_expr, right_expr)), ty) } Expression::CrossProduct(left, right) => { let (left_expr, left_ty) = write_expression(&builder.expressions[left], module, builder)?; let (right_expr, _) = write_expression(&builder.expressions[right], module, builder)?; - (format!("cross({},{})", left_expr, right_expr), left_ty) + ( + Cow::Owned(format!("cross({},{})", left_expr, right_expr)), + left_ty, + ) } Expression::Derivative { axis, expr } => { let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; ( - format!( + Cow::Owned(format!( "{}({})", match axis { DerivativeAxis::X => "dFdx", @@ -996,7 +1028,7 @@ fn write_expression<'a>( DerivativeAxis::Width => "fwidth", }, expr - ), + )), ty, ) } @@ -1017,7 +1049,7 @@ fn write_expression<'a>( }; ( - format!( + Cow::Owned(format!( "{}({})", match *origin { FunctionOrigin::External(ref name) => name, @@ -1033,7 +1065,7 @@ fn write_expression<'a>( .0)) .collect::, _>>()? .join(","), - ), + )), ty, ) } @@ -1054,13 +1086,13 @@ fn write_constant( ConstantInner::Composite(ref components) => format!( "{}({})", match module.types[constant.ty].inner { - TypeInner::Vector { size, .. } => format!("vec{}", size as u8,), + TypeInner::Vector { size, .. } => Cow::Owned(format!("vec{}", size as u8,)), TypeInner::Matrix { columns, rows, .. } => - format!("mat{}x{}", columns as u8, rows as u8,), - TypeInner::Struct { .. } => builder.structs.get(&constant.ty).unwrap().clone(), + Cow::Owned(format!("mat{}x{}", columns as u8, rows as u8,)), + TypeInner::Struct { .. } => + Cow::::Borrowed(builder.structs.get(&constant.ty).unwrap()), TypeInner::Array { .. } => - write_type(constant.ty, &module.types, builder.structs, None, features)? - .into_owned(), + write_type(constant.ty, &module.types, builder.structs, None, features)?, _ => return Err(Error::Custom(format!( "Cannot build constant of type {}", @@ -1081,13 +1113,13 @@ fn write_constant( }) } -fn write_type( +fn write_type<'a>( ty: Handle, types: &Arena, - structs: &FastHashMap, String>, + structs: &'a FastHashMap, String>, block: Option, features: SupportedFeatures, -) -> Result, Error> { +) -> Result, Error> { Ok(match types[ty].inner { TypeInner::Scalar { kind, width } => match kind { ScalarKind::Sint => Cow::Borrowed("int"), @@ -1170,7 +1202,11 @@ fn write_type( &mut out, "\t{} {};", write_type(member.ty, types, structs, None, features)?, - member.name.clone().unwrap_or_else(|| idx.to_string()) + member + .name + .clone() + .filter(|s| is_valid_ident(s)) + .unwrap_or_else(|| format!("_{}", idx)) )?; } @@ -1178,7 +1214,7 @@ fn write_type( Cow::Owned(out) } else { - Cow::Owned(structs.get(&ty).unwrap().clone()) + Cow::Borrowed(structs.get(&ty).unwrap()) } } TypeInner::Image { @@ -1335,6 +1371,10 @@ fn write_struct( writeln!(&mut tmp, "struct {} {{", name)?; for (idx, member) in members.iter().enumerate() { + if let MemberOrigin::BuiltIn(_) = member.origin { + continue; + } + if let TypeInner::Struct { ref members } = module.types[member.ty].inner { write_struct( member.ty, @@ -1351,7 +1391,11 @@ fn write_struct( &mut tmp, "\t{} {};", write_type(member.ty, &module.types, &structs, None, features)?, - member.name.clone().unwrap_or_else(|| format!("_{}", idx)) + member + .name + .clone() + .filter(|s| is_valid_ident(s)) + .unwrap_or_else(|| format!("_{}", idx)) )?; } writeln!(&mut tmp, "}};")?; @@ -1362,3 +1406,30 @@ fn write_struct( Ok(()) } + +fn is_valid_ident(ident: &str) -> bool { + ident.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') + || ident.contains(|c: char| c.is_ascii_alphanumeric() || c == '_') + || !ident.starts_with("gl_") + || ident != "main" +} + +fn builtin_to_glsl(builtin: BuiltIn) -> &'static str { + match builtin { + BuiltIn::Position => "gl_Position", + BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", + BuiltIn::BaseInstance => "gl_BaseInstance", + BuiltIn::BaseVertex => "gl_BaseVertex", + BuiltIn::ClipDistance => "gl_ClipDistance", + BuiltIn::InstanceIndex => "gl_InstanceIndex", + BuiltIn::VertexIndex => "gl_VertexIndex", + BuiltIn::PointSize => "gl_PointSize", + BuiltIn::FragCoord => "gl_FragCoord", + BuiltIn::FrontFacing => "gl_FrontFacing", + BuiltIn::SampleIndex => "gl_SampleID", + BuiltIn::FragDepth => "gl_FragDepth", + BuiltIn::LocalInvocationId => "gl_LocalInvocationID", + BuiltIn::LocalInvocationIndex => "gl_LocalInvocationIndex", + BuiltIn::WorkGroupId => "gl_WorkGroupID", + } +} From e41dc6958c57d0b8c803ddc5862d66f58a6c144b Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 27 Aug 2020 16:30:04 +0200 Subject: [PATCH 0162/2212] Make CI test on multiple rust versions (#159) Use 1.41.0 and nightly --- .github/workflows/pipeline.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 50be221f7..927afb7be 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -5,12 +5,15 @@ jobs: test: name: Test runs-on: ubuntu-latest + strategy: + matrix: + rust: [1.41.0, nightly] steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: 1.41.0 + toolchain: ${{ matrix.rust }} override: true - uses: actions-rs/cargo@v1 name: Default test From 58b35f13ba63ba3baaf4677b1d7f6ef9e8ee43f6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Aug 2020 20:51:43 -0400 Subject: [PATCH 0163/2212] [spirv] refactor builtin handling --- src/front/spv/convert.rs | 28 ++++++++++++++++++++++++++++ src/front/spv/mod.rs | 22 +--------------------- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 0c4d23da5..cc20ff5d4 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -82,3 +82,31 @@ pub fn map_width(word: spirv::Word) -> Result { .try_into() .map_err(|_| Error::InvalidTypeWidth(word)) } + +pub fn map_builtin(word: spirv::Word) -> Result, Error> { + use spirv::BuiltIn as Bi; + Ok(Some(match spirv::BuiltIn::from_u32(word) { + Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, + Some(Bi::BaseVertex) => crate::BuiltIn::BaseVertex, + Some(Bi::ClipDistance) => crate::BuiltIn::ClipDistance, + Some(Bi::InstanceIndex) => crate::BuiltIn::InstanceIndex, + Some(Bi::Position) => crate::BuiltIn::Position, + Some(Bi::VertexIndex) => crate::BuiltIn::VertexIndex, + // fragment + Some(Bi::PointSize) => crate::BuiltIn::PointSize, + Some(Bi::FragCoord) => crate::BuiltIn::FragCoord, + Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing, + Some(Bi::SampleId) => crate::BuiltIn::SampleIndex, + Some(Bi::FragDepth) => crate::BuiltIn::FragDepth, + // compute + Some(Bi::GlobalInvocationId) => crate::BuiltIn::GlobalInvocationId, + Some(Bi::LocalInvocationId) => crate::BuiltIn::LocalInvocationId, + Some(Bi::LocalInvocationIndex) => crate::BuiltIn::LocalInvocationIndex, + Some(Bi::WorkgroupId) => crate::BuiltIn::WorkGroupId, + Some(Bi::WorkgroupSize) => { + log::warn!("gl_WorkgroupSize builtin is not supported"); + return Ok(None); + } + _ => return Err(Error::UnsupportedBuiltIn(word)), + })) +} diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3d165aa86..a3b2d2102 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -356,29 +356,9 @@ impl> Parser { log::trace!("\t\t{:?}", dec_typed); match dec_typed { spirv::Decoration::BuiltIn => { - use spirv::BuiltIn as Bi; inst.expect(base_words + 2)?; let raw = self.next()?; - dec.built_in = Some(match spirv::BuiltIn::from_u32(raw) { - Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, - Some(Bi::BaseVertex) => crate::BuiltIn::BaseVertex, - Some(Bi::ClipDistance) => crate::BuiltIn::ClipDistance, - Some(Bi::InstanceIndex) => crate::BuiltIn::InstanceIndex, - Some(Bi::Position) => crate::BuiltIn::Position, - Some(Bi::VertexIndex) => crate::BuiltIn::VertexIndex, - // fragment - Some(Bi::PointSize) => crate::BuiltIn::PointSize, - Some(Bi::FragCoord) => crate::BuiltIn::FragCoord, - Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing, - Some(Bi::SampleId) => crate::BuiltIn::SampleIndex, - Some(Bi::FragDepth) => crate::BuiltIn::FragDepth, - // compute - Some(Bi::GlobalInvocationId) => crate::BuiltIn::GlobalInvocationId, - Some(Bi::LocalInvocationId) => crate::BuiltIn::LocalInvocationId, - Some(Bi::LocalInvocationIndex) => crate::BuiltIn::LocalInvocationIndex, - Some(Bi::WorkgroupId) => crate::BuiltIn::WorkGroupId, - _ => return Err(Error::UnsupportedBuiltIn(raw)), - }); + dec.built_in = map_builtin(raw)?; } spirv::Decoration::Location => { inst.expect(base_words + 2)?; From 91a7bdf7e7a36855b611d06ae60dac1d35cedd2f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Aug 2020 22:40:16 -0400 Subject: [PATCH 0164/2212] [spirv] handle LOD and BIAS image operands --- src/front/spv/mod.rs | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a3b2d2102..51df92147 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -765,14 +765,14 @@ impl> Parser { }, ); } - Op::ImageSampleImplicitLod => { + Op::ImageSampleImplicitLod | Op::ImageSampleExplicitLod => { inst.expect_at_least(5)?; let result_type_id = self.next()?; let result_id = self.next()?; let sampled_image_id = self.next()?; let coordinate_id = self.next()?; - let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; - let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?.clone(); + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?.clone(); let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; let sampler_type_handle = @@ -814,11 +814,34 @@ impl> Parser { _ => return Err(Error::InvalidSampleImage(image_type_handle)), }; + let mut level = crate::SampleLevel::Auto; + let mut base_wc = 5; + if base_wc < inst.wc { + let image_ops = self.next()?; + base_wc += 1; + let mask = spirv::ImageOperands::from_bits_truncate(image_ops); + if mask.contains(spirv::ImageOperands::BIAS) { + let bias_expr = self.next()?; + let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; + level = crate::SampleLevel::Bias(bias_handle); + base_wc += 1; + } + if mask.contains(spirv::ImageOperands::LOD) { + let lod_expr = self.next()?; + let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; + level = crate::SampleLevel::Exact(lod_handle); + base_wc += 1; + } + for _ in base_wc..inst.wc { + self.next()?; + } + } + let expr = crate::Expression::ImageSample { image: si_lexp.image, sampler: si_lexp.sampler, coordinate: coord_lexp.handle, - level: crate::SampleLevel::Auto, + level, depth_ref: None, }; self.lookup_expression.insert( From 4a61705201a2d1a66757819b5dcdc16b284199b9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Aug 2020 23:03:58 -0400 Subject: [PATCH 0165/2212] Add matrix transposition expression --- src/back/glsl.rs | 35 +++++++++++++++++++++++++++++----- src/front/spv/mod.rs | 44 +++++++++++++++++++++++++++++++++++++------ src/lib.rs | 2 ++ src/proc/interface.rs | 3 +++ src/proc/typifier.rs | 18 ++++++++++++++++++ 5 files changed, 91 insertions(+), 11 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 4a9eaec42..628fd8f1f 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -986,16 +986,41 @@ fn write_expression<'a, 'b>( ty, ) } + Expression::Transpose(matrix) => { + let (matrix_expr, matrix_ty) = + write_expression(&builder.expressions[matrix], module, builder)?; + + let ty = match *matrix_ty.as_ref() { + TypeInner::Matrix { + columns, + rows, + kind, + width, + } => Cow::Owned(TypeInner::Matrix { + columns: rows, + rows: columns, + kind, + width, + }), + _ => { + return Err(Error::Custom(format!( + "Cannot apply transpose to {}", + matrix_expr + ))) + } + }; + + (Cow::Owned(format!("transpose({})", matrix_expr)), ty) + } Expression::DotProduct(left, right) => { let (left_expr, left_ty) = write_expression(&builder.expressions[left], module, builder)?; let (right_expr, _) = write_expression(&builder.expressions[right], module, builder)?; - let ty = match left_ty.as_ref() { - TypeInner::Vector { kind, width, .. } => Cow::Owned(TypeInner::Scalar { - kind: *kind, - width: *width, - }), + let ty = match *left_ty.as_ref() { + TypeInner::Vector { kind, width, .. } => { + Cow::Owned(TypeInner::Scalar { kind, width }) + } _ => { return Err(Error::Custom(format!( "Cannot apply dot product to {}", diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 51df92147..36f3405ce 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -748,6 +748,21 @@ impl> Parser { }, ); } + Op::Transpose => { + inst.expect(4)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let matrix_id = self.next()?; + let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; + let expr = crate::Expression::Transpose(matrix_lexp.handle); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } Op::SampledImage => { inst.expect(5)?; let _result_type_id = self.next()?; @@ -1001,7 +1016,8 @@ impl> Parser { ); } Op::ExtInst => { - inst.expect_at_least(5)?; + let base_wc = 5; + inst.expect_at_least(base_wc)?; let result_type_id = self.next()?; let result_id = self.next()?; let set_id = self.next()?; @@ -1010,18 +1026,34 @@ impl> Parser { } let inst_id = self.next()?; let name = match spirv::GLOp::from_u32(inst_id) { - Some(spirv::GLOp::Length) => { - inst.expect(5 + 1)?; - "length" + Some(spirv::GLOp::Atan2) => { + inst.expect(base_wc + 1)?; + "atan2" + } + Some(spirv::GLOp::MatrixInverse) => { + inst.expect(base_wc + 1)?; + "inverse" } Some(spirv::GLOp::FMix) => { - inst.expect(5 + 3)?; + inst.expect(base_wc + 3)?; "mix" } + Some(spirv::GLOp::SmoothStep) => { + inst.expect(base_wc + 3)?; + "smoothstep" + } + Some(spirv::GLOp::Length) => { + inst.expect(base_wc + 1)?; + "length" + } + Some(spirv::GLOp::Normalize) => { + inst.expect(base_wc + 1)?; + "normalize" + } _ => return Err(Error::UnsupportedExtInst(inst_id)), }; - let mut arguments = Vec::with_capacity(inst.wc as usize - 5); + let mut arguments = Vec::with_capacity((inst.wc - base_wc) as usize); for _ in 0..arguments.capacity() { let arg_id = self.next()?; arguments.push(self.lookup_expression.lookup(arg_id)?.handle); diff --git a/src/lib.rs b/src/lib.rs index 6d6a6aa09..2edbd316e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -520,6 +520,8 @@ pub enum Expression { fun: IntrinsicFunction, argument: Handle, }, + /// Transpose of a matrix. + Transpose(Handle), /// Dot product between two vectors. DotProduct(Handle, Handle), /// Cross product between two vectors. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 814285e23..3eae87126 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -69,6 +69,9 @@ impl<'a> Interface<'a> { E::Intrinsic { argument, .. } => { self.add_inputs(argument); } + E::Transpose(matrix) => { + self.add_inputs(matrix); + } E::DotProduct(left, right) => { self.add_inputs(left); self.add_inputs(right); diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 9a4d5e4a1..3fc2e3e4f 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -164,6 +164,24 @@ impl Typifier { | crate::BinaryOperator::ShiftRightArithmetic => self.types[left.index()], }, crate::Expression::Intrinsic { .. } => unimplemented!(), + crate::Expression::Transpose(expr) => { + let ty_handle = self.types[expr.index()]; + let inner = match types[ty_handle].inner { + crate::TypeInner::Matrix { + columns, + rows, + kind, + width, + } => crate::TypeInner::Matrix { + columns: rows, + rows: columns, + kind, + width, + }, + ref other => panic!("incompatible transpose of {:?}", other), + }; + types.fetch_or_append(Type { name: None, inner }) + } crate::Expression::DotProduct(_, _) => unimplemented!(), crate::Expression::CrossProduct(_, _) => unimplemented!(), crate::Expression::Derivative { .. } => unimplemented!(), From cf6002be01e467585992be9d481b53dd23703417 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Aug 2020 23:14:52 -0400 Subject: [PATCH 0166/2212] [spirv] dot product and a few more GLSL ops --- src/front/spv/mod.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 36f3405ce..e3fc1a6f2 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -763,6 +763,23 @@ impl> Parser { }, ); } + Op::Dot => { + inst.expect(5)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let left_id = self.next()?; + let right_id = self.next()?; + let left_expr = self.lookup_expression.lookup(left_id)?; + let right_expr = self.lookup_expression.lookup(right_id)?; + let expr = crate::Expression::DotProduct(left_expr.handle, right_expr.handle); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } Op::SampledImage => { inst.expect(5)?; let _result_type_id = self.next()?; @@ -1030,6 +1047,10 @@ impl> Parser { inst.expect(base_wc + 1)?; "atan2" } + Some(spirv::GLOp::Pow) => { + inst.expect(base_wc + 2)?; + "pow" + } Some(spirv::GLOp::MatrixInverse) => { inst.expect(base_wc + 1)?; "inverse" @@ -1042,6 +1063,18 @@ impl> Parser { inst.expect(base_wc + 3)?; "smoothstep" } + Some(spirv::GLOp::FMin) => { + inst.expect(base_wc + 2)?; + "min" + } + Some(spirv::GLOp::FMax) => { + inst.expect(base_wc + 2)?; + "max" + } + Some(spirv::GLOp::FClamp) => { + inst.expect(base_wc + 3)?; + "clamp" + } Some(spirv::GLOp::Length) => { inst.expect(base_wc + 1)?; "length" From 35e14378b31971d9036e866ea72c994ed50e8253 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 Aug 2020 23:58:15 -0400 Subject: [PATCH 0167/2212] [spirv] register function parameters, handle return values --- src/front/spv/function.rs | 9 ++++++++- src/front/spv/mod.rs | 17 +++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 4012242ed..5b7edac1c 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -88,8 +88,15 @@ pub fn parse_function>( wc: 3, } => { let type_id = parser.next()?; - let _id = parser.next()?; + let id = parser.next()?; + let handle = fun + .expressions + .append(crate::Expression::FunctionParameter(i as u32)); + parser + .lookup_expression + .insert(id, LookupExpression { type_id, handle }); //Note: we redo the lookup in order to work around `parser` borrowing + if type_id != parser .lookup_function_type diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e3fc1a6f2..b4ab8c905 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -480,6 +480,9 @@ impl> Parser { .future_decor .remove(&result_id) .and_then(|decor| decor.name); + if let Some(ref name) = name { + log::debug!("\t\t\tid={} name={}", result_id, name); + } let var_handle = local_arena.append(crate::LocalVariable { name, ty: self.lookup_type.lookup(result_type_id)?.handle, @@ -1120,6 +1123,14 @@ impl> Parser { inst.expect(1)?; break Terminator::Return { value: None }; } + Op::ReturnValue => { + inst.expect(2)?; + let value_id = self.next()?; + let value_expr = self.lookup_expression.lookup(value_id)?; + break Terminator::Return { + value: Some(value_expr.handle), + }; + } Op::Branch => { inst.expect(2)?; let target_id = self.next()?; @@ -1215,21 +1226,23 @@ impl> Parser { } // register global variables for (&id, var) in self.lookup_variable.iter() { + let handle = expressions.append(crate::Expression::GlobalVariable(var.handle)); self.lookup_expression.insert( id, LookupExpression { type_id: var.type_id, - handle: expressions.append(crate::Expression::GlobalVariable(var.handle)), + handle, }, ); } // register constants for (&id, con) in self.lookup_constant.iter() { + let handle = expressions.append(crate::Expression::Constant(con.handle)); self.lookup_expression.insert( id, LookupExpression { type_id: con.type_id, - handle: expressions.append(crate::Expression::Constant(con.handle)), + handle, }, ); } From 462c82fb71d12489cbad7478d687bb9242e617bf Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 27 Aug 2020 00:19:39 -0400 Subject: [PATCH 0168/2212] As expressions --- src/back/glsl.rs | 56 +++++++++++++++++++++++++++++++----------- src/front/spv/error.rs | 1 + src/front/spv/mod.rs | 23 +++++++++++++++++ src/lib.rs | 2 ++ src/proc/interface.rs | 3 +++ src/proc/typifier.rs | 28 ++++++++++++++++++++- 6 files changed, 97 insertions(+), 16 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 628fd8f1f..132f4d79e 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1041,6 +1041,24 @@ fn write_expression<'a, 'b>( left_ty, ) } + Expression::As(value, kind) => { + let (value_expr, value_ty) = + write_expression(&builder.expressions[value], module, builder)?; + let (width, out_ty) = match *value_ty.as_ref() { + TypeInner::Scalar { width, kind: _ } => { + (width, Cow::Owned(TypeInner::Scalar { kind, width })) + } + TypeInner::Vector { + width, + kind: _, + size, + } => (width, Cow::Owned(TypeInner::Vector { kind, width, size })), + _ => return Err(Error::Custom(format!("Cannot cast {}", value_expr))), + }; + let ty_expr = map_scalar(kind, width, builder.features)?; + + (Cow::Owned(format!("{}({})", ty_expr, value_expr)), out_ty) + } Expression::Derivative { axis, expr } => { let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; @@ -1138,6 +1156,28 @@ fn write_constant( }) } +fn map_scalar( + kind: ScalarKind, + width: crate::Bytes, + features: SupportedFeatures, +) -> Result<&'static str, Error> { + Ok(match kind { + ScalarKind::Sint => "int", + ScalarKind::Uint => "uint", + ScalarKind::Float => match width { + 4 => "float", + 8 if features.contains(SupportedFeatures::DOUBLE_TYPE) => "double", + _ => { + return Err(Error::Custom(format!( + "Cannot build float of width {}", + width + ))) + } + }, + ScalarKind::Bool => "bool", + }) +} + fn write_type<'a>( ty: Handle, types: &Arena, @@ -1146,21 +1186,7 @@ fn write_type<'a>( features: SupportedFeatures, ) -> Result, Error> { Ok(match types[ty].inner { - TypeInner::Scalar { kind, width } => match kind { - ScalarKind::Sint => Cow::Borrowed("int"), - ScalarKind::Uint => Cow::Borrowed("uint"), - ScalarKind::Float => match width { - 4 => Cow::Borrowed("float"), - 8 if features.contains(SupportedFeatures::DOUBLE_TYPE) => Cow::Borrowed("double"), - _ => { - return Err(Error::Custom(format!( - "Cannot build float of width {}", - width - ))) - } - }, - ScalarKind::Bool => Cow::Borrowed("bool"), - }, + TypeInner::Scalar { kind, width } => Cow::Borrowed(map_scalar(kind, width, features)?), TypeInner::Vector { size, kind, width } => Cow::Owned(format!( "{}vec{}", match kind { diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index b467020b5..0488a83ef 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -44,6 +44,7 @@ pub enum Error { InvalidSampleSampler(Handle), InvalidSampleCoordinates(Handle), InvalidDepthReference(Handle), + InvalidAsType(Handle), InconsistentComparisonSampling(Handle), WrongFunctionResultType(spirv::Word), WrongFunctionParameterType(spirv::Word), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index b4ab8c905..47e4f6249 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1009,6 +1009,29 @@ impl> Parser { }, ); } + Op::ConvertSToF | Op::ConvertUToF | Op::ConvertFToU | Op::ConvertFToS => { + inst.expect_at_least(4)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let value_id = self.next()?; + + let value_expr = self.lookup_expression.lookup(value_id)?; + let ty_lookup = self.lookup_type.lookup(result_type_id)?; + let kind = match type_arena[ty_lookup.handle].inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } => kind, + _ => return Err(Error::InvalidAsType(ty_lookup.handle)), + }; + + let expr = crate::Expression::As(value_expr.handle, kind); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } Op::FunctionCall => { inst.expect_at_least(4)?; let result_type_id = self.next()?; diff --git a/src/lib.rs b/src/lib.rs index 2edbd316e..8dec8ff0d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -526,6 +526,8 @@ pub enum Expression { DotProduct(Handle, Handle), /// Cross product between two vectors. CrossProduct(Handle, Handle), + /// Cast a scalar or a vector to another kind. + As(Handle, ScalarKind), /// Compute the derivative on an axis. Derivative { axis: DerivativeAxis, diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 3eae87126..015dd51ce 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -80,6 +80,9 @@ impl<'a> Interface<'a> { self.add_inputs(left); self.add_inputs(right); } + E::As(expr, _) => { + self.add_inputs(expr); + } E::Derivative { expr, .. } => { self.add_inputs(expr); } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 3fc2e3e4f..e5c5a4006 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -182,8 +182,34 @@ impl Typifier { }; types.fetch_or_append(Type { name: None, inner }) } - crate::Expression::DotProduct(_, _) => unimplemented!(), + crate::Expression::DotProduct(left_expr, _) => { + let left_ty = self.types[left_expr.index()]; + let inner = match types[left_ty].inner { + crate::TypeInner::Vector { + kind, + size: _, + width, + } => crate::TypeInner::Scalar { kind, width }, + ref other => panic!("incompatible dot of {:?}", other), + }; + types.fetch_or_append(Type { name: None, inner }) + } crate::Expression::CrossProduct(_, _) => unimplemented!(), + crate::Expression::As(expr, kind) => { + let ty_handle = self.types[expr.index()]; + let inner = match types[ty_handle].inner { + crate::TypeInner::Scalar { kind: _, width } => { + crate::TypeInner::Scalar { kind, width } + } + crate::TypeInner::Vector { + kind: _, + size, + width, + } => crate::TypeInner::Vector { kind, size, width }, + ref other => panic!("incompatible as of {:?}", other), + }; + types.fetch_or_append(Type { name: None, inner }) + } crate::Expression::Derivative { .. } => unimplemented!(), crate::Expression::Call { origin: crate::FunctionOrigin::External(ref name), From b5d99e133b309af59cd7996db2a4bfdc1fae460a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 27 Aug 2020 00:47:31 -0400 Subject: [PATCH 0169/2212] [spirv] fix binary operators, support more extensions --- src/front/spv/mod.rs | 151 +++++++++++++++++++++++++++++-------------- 1 file changed, 102 insertions(+), 49 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 47e4f6249..307d9309f 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -411,6 +411,31 @@ impl> Parser { Ok(()) } + fn parse_expr_unary_op( + &mut self, + expressions: &mut Arena, + op: crate::UnaryOperator, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let p_id = self.next()?; + + let p_lexp = self.lookup_expression.lookup(p_id)?; + + let expr = crate::Expression::Unary { + op, + expr: p_lexp.handle, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } + fn parse_expr_binary_op( &mut self, expressions: &mut Arena, @@ -703,53 +728,37 @@ impl> Parser { }); } // Arithmetic Instructions +, -, *, /, % - _ if inst.op >= Op::IAdd && inst.op <= Op::FMod => { + Op::SNegate | Op::FNegate => { + inst.expect(4)?; + self.parse_expr_unary_op(expressions, crate::UnaryOperator::Negate)?; + } + Op::IAdd | Op::FAdd => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::Add)?; + } + Op::ISub | Op::FSub => { inst.expect(5)?; self.parse_expr_binary_op(expressions, crate::BinaryOperator::Subtract)?; } - Op::VectorTimesScalar => { + Op::IMul | Op::FMul => { inst.expect(5)?; - let result_type_id = self.next()?; - let result_id = self.next()?; - let vector_id = self.next()?; - let scalar_id = self.next()?; - - let vector_lexp = self.lookup_expression.lookup(vector_id)?; - let scalar_lexp = self.lookup_expression.lookup(scalar_id)?; - - let expr = crate::Expression::Binary { - op: crate::BinaryOperator::Multiply, - left: vector_lexp.handle, - right: scalar_lexp.handle, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + self.parse_expr_binary_op(expressions, crate::BinaryOperator::Multiply)?; } - Op::MatrixTimesVector => { + Op::SDiv | Op::UDiv | Op::FDiv => { inst.expect(5)?; - let result_type_id = self.next()?; - let result_id = self.next()?; - let matrix_id = self.next()?; - let vector_id = self.next()?; - let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; - let vector_lexp = self.lookup_expression.lookup(vector_id)?; - let expr = crate::Expression::Binary { - op: crate::BinaryOperator::Multiply, - left: matrix_lexp.handle, - right: vector_lexp.handle, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + self.parse_expr_binary_op(expressions, crate::BinaryOperator::Divide)?; + } + Op::UMod | Op::FMod | Op::SRem | Op::FRem => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::Modulo)?; + } + Op::VectorTimesScalar + | Op::VectorTimesMatrix + | Op::MatrixTimesScalar + | Op::MatrixTimesVector + | Op::MatrixTimesMatrix => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::Multiply)?; } Op::Transpose => { inst.expect(4)?; @@ -772,9 +781,9 @@ impl> Parser { let result_id = self.next()?; let left_id = self.next()?; let right_id = self.next()?; - let left_expr = self.lookup_expression.lookup(left_id)?; - let right_expr = self.lookup_expression.lookup(right_id)?; - let expr = crate::Expression::DotProduct(left_expr.handle, right_expr.handle); + let left_lexp = self.lookup_expression.lookup(left_id)?; + let right_lexp = self.lookup_expression.lookup(right_id)?; + let expr = crate::Expression::DotProduct(left_lexp.handle, right_lexp.handle); self.lookup_expression.insert( result_id, LookupExpression { @@ -1015,7 +1024,7 @@ impl> Parser { let result_id = self.next()?; let value_id = self.next()?; - let value_expr = self.lookup_expression.lookup(value_id)?; + let value_lexp = self.lookup_expression.lookup(value_id)?; let ty_lookup = self.lookup_type.lookup(result_type_id)?; let kind = match type_arena[ty_lookup.handle].inner { crate::TypeInner::Scalar { kind, .. } @@ -1023,7 +1032,7 @@ impl> Parser { _ => return Err(Error::InvalidAsType(ty_lookup.handle)), }; - let expr = crate::Expression::As(value_expr.handle, kind); + let expr = crate::Expression::As(value_lexp.handle, kind); self.lookup_expression.insert( result_id, LookupExpression { @@ -1069,8 +1078,40 @@ impl> Parser { } let inst_id = self.next()?; let name = match spirv::GLOp::from_u32(inst_id) { - Some(spirv::GLOp::Atan2) => { + Some(spirv::GLOp::FAbs) | Some(spirv::GLOp::SAbs) => { inst.expect(base_wc + 1)?; + "abs" + } + Some(spirv::GLOp::FSign) | Some(spirv::GLOp::SSign) => { + inst.expect(base_wc + 1)?; + "sign" + } + Some(spirv::GLOp::Floor) => { + inst.expect(base_wc + 1)?; + "floor" + } + Some(spirv::GLOp::Ceil) => { + inst.expect(base_wc + 1)?; + "ceil" + } + Some(spirv::GLOp::Fract) => { + inst.expect(base_wc + 1)?; + "fract" + } + Some(spirv::GLOp::Sin) => { + inst.expect(base_wc + 1)?; + "sin" + } + Some(spirv::GLOp::Cos) => { + inst.expect(base_wc + 1)?; + "cos" + } + Some(spirv::GLOp::Tan) => { + inst.expect(base_wc + 1)?; + "tan" + } + Some(spirv::GLOp::Atan2) => { + inst.expect(base_wc + 2)?; "atan2" } Some(spirv::GLOp::Pow) => { @@ -1085,6 +1126,10 @@ impl> Parser { inst.expect(base_wc + 3)?; "mix" } + Some(spirv::GLOp::Step) => { + inst.expect(base_wc + 2)?; + "step" + } Some(spirv::GLOp::SmoothStep) => { inst.expect(base_wc + 3)?; "smoothstep" @@ -1105,10 +1150,18 @@ impl> Parser { inst.expect(base_wc + 1)?; "length" } + Some(spirv::GLOp::Cross) => { + inst.expect(base_wc + 2)?; + "cross" + } Some(spirv::GLOp::Normalize) => { inst.expect(base_wc + 1)?; "normalize" } + Some(spirv::GLOp::Reflect) => { + inst.expect(base_wc + 2)?; + "reflect" + } _ => return Err(Error::UnsupportedExtInst(inst_id)), }; @@ -1149,9 +1202,9 @@ impl> Parser { Op::ReturnValue => { inst.expect(2)?; let value_id = self.next()?; - let value_expr = self.lookup_expression.lookup(value_id)?; + let value_lexp = self.lookup_expression.lookup(value_id)?; break Terminator::Return { - value: Some(value_expr.handle), + value: Some(value_lexp.handle), }; } Op::Branch => { From bd9efe5915e548b9a2ec1f3d3e9296c90b31e69a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 27 Aug 2020 01:31:32 -0400 Subject: [PATCH 0170/2212] Allow struct members without an origin --- src/back/msl.rs | 2 ++ src/front/spv/convert.rs | 10 +++------- src/front/spv/mod.rs | 24 ++++++++++++++++++------ src/lib.rs | 2 ++ 4 files changed, 25 insertions(+), 13 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 4bf57ba0b..3950b6960 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -930,6 +930,7 @@ impl Writer { let base_name = module.types[member.ty].name.or_index(member.ty); write!(self.out, "\t{} {}", base_name, name)?; match member.origin { + crate::MemberOrigin::Empty => {} crate::MemberOrigin::BuiltIn(built_in) => { ResolvedBinding::BuiltIn(built_in) .try_fmt_decorated(&mut self.out, "")?; @@ -1105,6 +1106,7 @@ impl Writer { let name = member.name.or_index(MemberIndex(index)); let ty_name = module.types[member.ty].name.or_index(member.ty); match member.origin { + crate::MemberOrigin::Empty => {} crate::MemberOrigin::BuiltIn(built_in) => { write!(self.out, "\t{} {}", ty_name, name)?; ResolvedBinding::BuiltIn(built_in) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index cc20ff5d4..fe3845a14 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -83,9 +83,9 @@ pub fn map_width(word: spirv::Word) -> Result { .map_err(|_| Error::InvalidTypeWidth(word)) } -pub fn map_builtin(word: spirv::Word) -> Result, Error> { +pub fn map_builtin(word: spirv::Word) -> Result { use spirv::BuiltIn as Bi; - Ok(Some(match spirv::BuiltIn::from_u32(word) { + Ok(match spirv::BuiltIn::from_u32(word) { Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, Some(Bi::BaseVertex) => crate::BuiltIn::BaseVertex, Some(Bi::ClipDistance) => crate::BuiltIn::ClipDistance, @@ -103,10 +103,6 @@ pub fn map_builtin(word: spirv::Word) -> Result, Error> { Some(Bi::LocalInvocationId) => crate::BuiltIn::LocalInvocationId, Some(Bi::LocalInvocationIndex) => crate::BuiltIn::LocalInvocationIndex, Some(Bi::WorkgroupId) => crate::BuiltIn::WorkGroupId, - Some(Bi::WorkgroupSize) => { - log::warn!("gl_WorkgroupSize builtin is not supported"); - return Ok(None); - } _ => return Err(Error::UnsupportedBuiltIn(word)), - })) + }) } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 307d9309f..44cfedbd0 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -147,6 +147,13 @@ struct Decoration { } impl Decoration { + fn debug_name(&self) -> &str { + match self.name { + Some(ref name) => name.as_str(), + None => "?", + } + } + fn get_binding(&self) -> Option { //TODO: validate this better match *self { @@ -197,7 +204,7 @@ impl Decoration { offset: Some(offset), .. } => Ok(crate::MemberOrigin::Offset(offset)), - _ => Err(Error::MissingDecoration(spirv::Decoration::Offset)), + _ => Ok(crate::MemberOrigin::Empty), } } } @@ -353,12 +360,15 @@ impl> Parser { ) -> Result<(), Error> { let raw = self.next()?; let dec_typed = spirv::Decoration::from_u32(raw).ok_or(Error::InvalidDecoration(raw))?; - log::trace!("\t\t{:?}", dec_typed); + log::trace!("\t\t{}: {:?}", dec.debug_name(), dec_typed); match dec_typed { spirv::Decoration::BuiltIn => { inst.expect(base_words + 2)?; let raw = self.next()?; - dec.built_in = map_builtin(raw)?; + match map_builtin(raw) { + Ok(built_in) => dec.built_in = Some(built_in), + Err(_e) => log::warn!("Unsupported builtin {}", raw), + }; } spirv::Decoration::Location => { inst.expect(base_words + 2)?; @@ -1573,6 +1583,7 @@ impl> Parser { if left != 0 { return Err(Error::InvalidOperand); } + self.future_member_decor .entry((id, member)) .or_default() @@ -1595,6 +1606,7 @@ impl> Parser { inst.expect_at_least(4)?; let id = self.next()?; let member = self.next()?; + let mut dec = self .future_member_decor .remove(&(id, member)) @@ -1870,8 +1882,8 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(2)?; let id = self.next()?; - let decor = self.future_decor.remove(&id); - if let Some(ref decor) = decor { + let parent_decor = self.future_decor.remove(&id); + if let Some(ref decor) = parent_decor { if decor.block.is_some() { // do nothing } @@ -1897,7 +1909,7 @@ impl> Parser { id, LookupType { handle: module.types.append(crate::Type { - name: decor.and_then(|dec| dec.name), + name: parent_decor.and_then(|dec| dec.name), inner, }), base_id: None, diff --git a/src/lib.rs b/src/lib.rs index 8dec8ff0d..3315108e7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -147,6 +147,8 @@ pub enum ArraySize { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum MemberOrigin { + /// Member is local to the shader. + Empty, /// Built-in shader variable. BuiltIn(BuiltIn), /// Offset within the struct. From 447e2483f92c742c1f78d46e1dc337b76de085b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Tal=C4=8D=C3=ADk?= Date: Thu, 27 Aug 2020 23:01:05 +0200 Subject: [PATCH 0171/2212] Format, clippy pub(super) --- src/front/spv/flow.rs | 176 ++++++++++++++++++++++---------------- src/front/spv/function.rs | 1 + src/front/spv/mod.rs | 43 ++++++++++ 3 files changed, 146 insertions(+), 74 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 2fa1036db..526ec1ac7 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -3,7 +3,10 @@ use super::error::Error; ///! see https://en.wikipedia.org/wiki/Control-flow_graph ///! see https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#_a_id_structuredcontrolflow_a_structured_control_flow -use super::function::{BlockId, MergeInstruction, Terminator}; +use super::{ + function::{BlockId, MergeInstruction, Terminator}, + LookupExpression, PhiInstruction, +}; use crate::FastHashMap; @@ -23,7 +26,7 @@ type BlockNodeIndex = NodeIndex; type ControlFlowGraph = petgraph::Graph; /// Control flow graph (CFG) containing relationships between blocks. -pub struct FlowGraph { +pub(super) struct FlowGraph { /// flow: ControlFlowGraph, @@ -33,7 +36,7 @@ pub struct FlowGraph { impl FlowGraph { /// Creates empty flow graph. - pub fn new() -> Self { + pub(super) fn new() -> Self { Self { flow: ControlFlowGraph::default(), block_to_node: FastHashMap::default(), @@ -41,7 +44,7 @@ impl FlowGraph { } /// Add a control flow node. - pub fn add_node(&mut self, node: ControlFlowNode) { + pub(super) fn add_node(&mut self, node: ControlFlowNode) { let block_id = node.id; let node_index = self.flow.add_node(node); self.block_to_node.insert(block_id, node_index); @@ -50,7 +53,7 @@ impl FlowGraph { /// /// 1. Creates edges in the CFG. /// 2. Classifies types of blocks and edges in the CFG. - pub fn classify(&mut self) { + pub(super) fn classify(&mut self) { let block_to_node = &mut self.block_to_node; // 1. @@ -180,17 +183,34 @@ impl FlowGraph { } } - /// TODO /// Removes OpPhi instructions from the control flow graph and turns them into ordinary variables. /// /// Phi instructions are not supported inside Naga nor do they exist as instructions on CPUs. It is neccessary /// to remove them and turn into ordinary variables before converting to Naga's IR and shader code. - pub fn remove_phi_instructions() { - unimplemented!(); + pub(super) fn remove_phi_instructions( + &mut self, + lookup_expression: &FastHashMap, + ) { + for node_index in self.flow.node_indices() { + let phis = std::mem::replace(&mut self.flow[node_index].phis, Vec::new()); + for phi in phis.iter() { + let phi_var = &lookup_expression[&phi.id]; + for (variable_id, parent_id) in phi.variables.iter() { + let variable = &lookup_expression[&variable_id]; + let parent_node = &mut self.flow[self.block_to_node[&parent_id]]; + + parent_node.block.push(crate::Statement::Store { + pointer: phi_var.handle, + value: variable.handle, + }); + } + } + self.flow[node_index].phis = phis; + } } /// Traverses the flow graph and returns a list of Naga's statements. - pub fn to_naga(&self) -> Result { + pub(super) fn to_naga(&self) -> Result { self.naga_traverse(node_index(0), None) } @@ -208,84 +228,89 @@ impl FlowGraph { let node = &self.flow[node_index]; match node.ty { - Some(ControlFlowNodeType::Header) => { - let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; - let mut result = node.block.clone(); + Some(ControlFlowNodeType::Header) => match node.terminator { + Terminator::BranchConditional { + condition, + true_id, + false_id, + } => { + let true_node_index = self.block_to_node[&true_id]; + let false_node_index = self.block_to_node[&false_id]; + let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; - match node.terminator { - Terminator::BranchConditional { - condition, - true_id, - false_id, - } => { + let mut result = node.block.clone(); + + if false_node_index != merge_node_index { + result.push(crate::Statement::If { + condition, + accept: self.naga_traverse(true_node_index, Some(merge_node_index))?, + reject: self.naga_traverse(false_node_index, Some(merge_node_index))?, + }); + result.extend(self.naga_traverse(merge_node_index, None)?); + } else { result.push(crate::Statement::If { condition, accept: self.naga_traverse( self.block_to_node[&true_id], Some(merge_node_index), )?, - reject: self.naga_traverse( - self.block_to_node[&false_id], - Some(merge_node_index), - )?, + reject: self.naga_traverse(merge_node_index, None)?, }); } - Terminator::Switch { - selector, - default, - ref targets, - } => { - let mut cases = FastHashMap::default(); - for i in 0..targets.len() { - let left_target_node_index = self.block_to_node[&targets[i].1]; + Ok(result) + } + Terminator::Switch { + selector, + default, + ref targets, + } => { + let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; + let mut result = node.block.clone(); - let fallthrough: Option = if i < targets.len() - 1 { - let right_target_node_index = self.block_to_node[&targets[i + 1].1]; - if has_path_connecting( - &self.flow, - left_target_node_index, - right_target_node_index, - None, - ) { - Some(crate::FallThrough {}) - } else { - None - } + let mut cases = FastHashMap::default(); + + for i in 0..targets.len() { + let left_target_node_index = self.block_to_node[&targets[i].1]; + + let fallthrough: Option = if i < targets.len() - 1 { + let right_target_node_index = self.block_to_node[&targets[i + 1].1]; + if has_path_connecting( + &self.flow, + left_target_node_index, + right_target_node_index, + None, + ) { + Some(crate::FallThrough {}) } else { None - }; + } + } else { + None + }; - cases.insert( - targets[i].0, - ( - self.naga_traverse( - left_target_node_index, - Some(merge_node_index), - )?, - fallthrough, - ), - ); - } - - result.push(crate::Statement::Switch { - selector, - cases, - default: self.naga_traverse( - self.block_to_node[&default], - Some(merge_node_index), - )?, - }); + cases.insert( + targets[i].0, + ( + self.naga_traverse(left_target_node_index, Some(merge_node_index))?, + fallthrough, + ), + ); } - _ => { - return Err(Error::InvalidTerminator); - } - }; - result.extend(self.naga_traverse(merge_node_index, None)?); + result.push(crate::Statement::Switch { + selector, + cases, + default: self + .naga_traverse(self.block_to_node[&default], Some(merge_node_index))?, + }); - Ok(result) - } + result.extend(self.naga_traverse(merge_node_index, None)?); + + Ok(result) + } + _ => Err(Error::InvalidTerminator), + }, Some(ControlFlowNodeType::Loop) => { let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; let continuing: crate::Block = { @@ -373,7 +398,7 @@ impl FlowGraph { } /// Get the entire graph in a graphviz dot format for visualization. Useful for debugging purposes. - pub fn to_graphviz(&self) -> Result { + pub(super) fn to_graphviz(&self) -> Result { let mut output = String::new(); output += "digraph ControlFlowGraph {"; @@ -417,7 +442,7 @@ impl FlowGraph { /// Type of an edge(flow) in the `ControlFlowGraph`. #[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub enum ControlFlowEdgeType { +pub(super) enum ControlFlowEdgeType { /// Default Forward, @@ -457,7 +482,7 @@ pub enum ControlFlowEdgeType { } /// Type of a node(block) in the `ControlFlowGraph`. #[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum ControlFlowNodeType { +pub(super) enum ControlFlowNodeType { /// A block whose merge instruction is an OpSelectionMerge. Header, @@ -483,13 +508,16 @@ pub enum ControlFlowNodeType { Return, } /// ControlFlowGraph's node representing a block in the control flow. -pub struct ControlFlowNode { +pub(super) struct ControlFlowNode { /// SPIR-V ID. pub id: BlockId, /// Type of the node. See *ControlFlowNodeType*. pub ty: Option, + /// Phi instructions. + pub phis: Vec, + /// Naga's statements inside this block. pub block: crate::Block, diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 5b7edac1c..f133c50ce 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -149,6 +149,7 @@ pub fn parse_function>( } flow_graph.classify(); + flow_graph.remove_phi_instructions(&parser.lookup_expression); fun.body = flow_graph.to_naga()?; // done diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 44cfedbd0..0f7786006 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -56,7 +56,15 @@ impl Instruction { } } } +/// OpPhi instruction. +#[derive(Clone, Default, Debug)] +struct PhiInstruction { + /// SPIR-V's ID. + id: u32, + /// Tuples of (variable, parent). + variables: Vec<(u32, u32)>, +} #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] pub enum ModuleState { Empty, @@ -486,6 +494,7 @@ impl> Parser { local_function_calls: &mut FastHashMap, spirv::Word>, ) -> Result { let mut assignments = Vec::new(); + let mut phis = Vec::new(); let mut merge = None; let terminator = loop { use spirv::Op; @@ -532,6 +541,35 @@ impl> Parser { }, ); } + Op::Phi => { + inst.expect_at_least(3)?; + + let result_type_id = self.next()?; + let result_id = self.next()?; + + let name = format!("phi_{}", result_id); + let var_handle = local_arena.append(crate::LocalVariable { + name: Some(name), + ty: self.lookup_type.lookup(result_type_id)?.handle, + init: None, + }); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions + .append(crate::Expression::LocalVariable(var_handle)), + type_id: result_type_id, + }, + ); + + let mut phi = PhiInstruction::default(); + phi.id = result_id; + for _ in 0..(inst.wc - 3) / 2 { + phi.variables.push((self.next()?, self.next()?)); + } + + phis.push(phi); + } Op::AccessChain => { struct AccessExpression { base_handle: Handle, @@ -1193,6 +1231,10 @@ impl> Parser { ); } // Relational and Logical Instructions + Op::LogicalNot => { + inst.expect(4)?; + self.parse_expr_unary_op(expressions, crate::UnaryOperator::Not)?; + } op if inst.op >= Op::IEqual && inst.op <= Op::FUnordGreaterThanEqual => { inst.expect(5)?; self.parse_expr_binary_op(expressions, map_binary_operator(op)?)?; @@ -1298,6 +1340,7 @@ impl> Parser { Ok(ControlFlowNode { id: block_id, ty: None, + phis, block, terminator, merge, From 73204d094c043830bb23cf5d9b15d534aa2a3dba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 27 Aug 2020 23:01:19 +0100 Subject: [PATCH 0172/2212] glsl-out: fixes (#164) * Fixed not generating wrong op on booleans Correctly handle storage images and sampled images * Fixed comments --- src/back/glsl.rs | 214 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 163 insertions(+), 51 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 132f4d79e..4e98f0eba 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -2,7 +2,7 @@ use crate::{ Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageClass, Interpolation, IntrinsicFunction, LocalVariable, MemberOrigin, Module, ScalarKind, ShaderStage, Statement, - StorageClass, StructMember, Type, TypeInner, UnaryOperator, + StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, UnaryOperator, }; use std::{ borrow::Cow, @@ -251,9 +251,43 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> })? }; - if let Some(ref binding) = global.binding { - if !es { - write!(out, "layout({}) ", Binding(binding))?; + let storage_format = match module.types[global.ty].inner { + TypeInner::Image { + class: ImageClass::Storage(format, _), + .. + } => Some(format), + _ => None, + }; + + if global.binding.is_some() { + write!(out, "layout(")?; + + if let Some(ref binding) = global.binding { + if !es { + write!(out, "{}", Binding(binding))?; + } + } + + if storage_format.is_some() && global.binding.is_some() { + write!(out, ",")?; + } + + if let Some(format) = storage_format { + write!(out, "{}", write_format_glsl(format))?; + } + + write!(out, ") ")?; + } + + if let TypeInner::Image { + class: ImageClass::Storage(_, access), + .. + } = module.types[global.ty].inner + { + if access == StorageAccess::LOAD { + write!(out, "readonly ")?; + } else if access == StorageAccess::STORE { + write!(out, "writeonly ")?; } } @@ -499,7 +533,7 @@ fn write_statement<'a, 'b>( )?; } - if fallthrough.is_some() { + if fallthrough.is_none() { writeln!(&mut out, "{}break;", "\t".repeat(indent + 2),)?; } } @@ -828,7 +862,14 @@ fn write_expression<'a, 'b>( sampler_constructor, coordinate, level_expr ) } - crate::SampleLevel::Bias(_) => todo!(), + crate::SampleLevel::Bias(bias) => { + let (bias_expr, _) = + write_expression(&builder.expressions[bias], module, builder)?; + format!( + "texture({},{},{})", + sampler_constructor, coordinate, bias_expr + ) + } }; let width = 4; @@ -843,7 +884,7 @@ fn write_expression<'a, 'b>( Expression::ImageLoad { image, coordinate, - index: _, + index, } => { let (image_expr, image_ty) = write_expression(&builder.expressions[image], module, builder)?; @@ -860,10 +901,6 @@ fn write_expression<'a, 'b>( _ => return Err(Error::Custom(format!("Cannot load {:?}", image_ty))), }; - let ms = match class { - crate::ImageClass::Multisampled => true, - _ => false, - }; let size = match coordinate_ty.as_ref() { TypeInner::Vector { size, .. } => *size, _ => { @@ -874,25 +911,47 @@ fn write_expression<'a, 'b>( } }; - //TODO: fix this - let sampler_constructor = format!( - "{}sampler{}{}{}({})", - match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => "", - _ => return Err(Error::Custom(String::from("Cannot build image of bools",))), - }, - ImageDimension(dim), - if ms { "MS" } else { "" }, - if arrayed { "Array" } else { "" }, - image_expr, - ); + let expr = match class { + ImageClass::Sampled | ImageClass::Multisampled => { + let ms = match class { + crate::ImageClass::Multisampled => true, + _ => false, + }; - let expr = if !ms { - format!("texture({},{})", sampler_constructor, coordinate_expr) - } else { - todo!() + //TODO: fix this + let sampler_constructor = format!( + "{}sampler{}{}{}({})", + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => "", + _ => + return Err(Error::Custom(String::from( + "Cannot build image of bools" + ))), + }, + ImageDimension(dim), + if ms { "MS" } else { "" }, + if arrayed { "Array" } else { "" }, + image_expr, + ); + + if !ms { + format!("texelFetch({},{})", sampler_constructor, coordinate_expr) + } else { + let (index_expr, _) = + write_expression(&builder.expressions[index], module, builder)?; + + format!( + "texelFetch({},{},{})", + sampler_constructor, coordinate_expr, index_expr + ) + } + } + ImageClass::Storage(_, _) => { + format!("imageLoad({},{})", image_expr, coordinate_expr) + } + ImageClass::Depth => todo!(), }; let width = 4; @@ -909,7 +968,25 @@ fn write_expression<'a, 'b>( "({} {})", match op { UnaryOperator::Negate => "-", - UnaryOperator::Not => "~", + UnaryOperator::Not => match ty.as_ref() { + TypeInner::Scalar { + kind: ScalarKind::Sint, + .. + } => "~", + TypeInner::Scalar { + kind: ScalarKind::Uint, + .. + } => "~", + TypeInner::Scalar { + kind: ScalarKind::Bool, + .. + } => "!", + _ => + return Err(Error::Custom(format!( + "Cannot apply not to type {:?}", + ty + ))), + }, }, expr )), @@ -922,7 +999,7 @@ fn write_expression<'a, 'b>( let (right_expr, right_ty) = write_expression(&builder.expressions[right], module, builder)?; - let op = match op { + let op_str = match op { BinaryOperator::Add => "+", BinaryOperator::Subtract => "-", BinaryOperator::Multiply => "*", @@ -944,26 +1021,51 @@ fn write_expression<'a, 'b>( BinaryOperator::ShiftRightArithmetic => ">>", }; - let ty = match (left_ty.as_ref(), right_ty.as_ref()) { - (TypeInner::Scalar { .. }, TypeInner::Scalar { .. }) => left_ty, - (TypeInner::Scalar { .. }, TypeInner::Vector { .. }) => right_ty, - (TypeInner::Scalar { .. }, TypeInner::Matrix { .. }) => right_ty, - (TypeInner::Vector { .. }, TypeInner::Scalar { .. }) => left_ty, - (TypeInner::Vector { .. }, TypeInner::Vector { .. }) => left_ty, - (TypeInner::Vector { .. }, TypeInner::Matrix { .. }) => left_ty, - (TypeInner::Matrix { .. }, TypeInner::Scalar { .. }) => left_ty, - (TypeInner::Matrix { .. }, TypeInner::Vector { .. }) => right_ty, - (TypeInner::Matrix { .. }, TypeInner::Matrix { .. }) => left_ty, - _ => { - return Err(Error::Custom(format!( - "Cannot apply {} to {} and {}", - op, left_expr, right_expr - ))) + let ty = match op { + BinaryOperator::Add + | BinaryOperator::Subtract + | BinaryOperator::Multiply + | BinaryOperator::Divide + | BinaryOperator::Modulo + | BinaryOperator::And + | BinaryOperator::ExclusiveOr + | BinaryOperator::InclusiveOr + | BinaryOperator::LogicalAnd + | BinaryOperator::LogicalOr + | BinaryOperator::ShiftLeftLogical + | BinaryOperator::ShiftRightLogical + | BinaryOperator::ShiftRightArithmetic => { + match (left_ty.as_ref(), right_ty.as_ref()) { + (TypeInner::Scalar { .. }, TypeInner::Scalar { .. }) => left_ty, + (TypeInner::Scalar { .. }, TypeInner::Vector { .. }) => right_ty, + (TypeInner::Scalar { .. }, TypeInner::Matrix { .. }) => right_ty, + (TypeInner::Vector { .. }, TypeInner::Scalar { .. }) => left_ty, + (TypeInner::Vector { .. }, TypeInner::Vector { .. }) => left_ty, + (TypeInner::Vector { .. }, TypeInner::Matrix { .. }) => left_ty, + (TypeInner::Matrix { .. }, TypeInner::Scalar { .. }) => left_ty, + (TypeInner::Matrix { .. }, TypeInner::Vector { .. }) => right_ty, + (TypeInner::Matrix { .. }, TypeInner::Matrix { .. }) => left_ty, + _ => { + return Err(Error::Custom(format!( + "Cannot apply '{}' to {} and {}", + op_str, left_expr, right_expr + ))) + } + } } + BinaryOperator::Equal + | BinaryOperator::NotEqual + | BinaryOperator::Less + | BinaryOperator::LessEqual + | BinaryOperator::Greater + | BinaryOperator::GreaterEqual => Cow::Owned(TypeInner::Scalar { + kind: ScalarKind::Bool, + width: 1, + }), }; ( - Cow::Owned(format!("({} {} {})", left_expr, op, right_expr)), + Cow::Owned(format!("({} {} {})", left_expr, op_str, right_expr)), ty, ) } @@ -1284,7 +1386,7 @@ fn write_type<'a>( } Cow::Owned(format!( - "{}texture{}{}", + "{}{}{}{}", match kind { ScalarKind::Sint => "i", ScalarKind::Uint => "u", @@ -1294,6 +1396,10 @@ fn write_type<'a>( "Cannot build image of booleans", ))), }, + match class { + ImageClass::Storage(_, _) => "image", + _ => "texture", + }, ImageDimension(dim), write_image_flags(arrayed, class, features)? )) @@ -1460,9 +1566,9 @@ fn write_struct( fn is_valid_ident(ident: &str) -> bool { ident.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') - || ident.contains(|c: char| c.is_ascii_alphanumeric() || c == '_') - || !ident.starts_with("gl_") - || ident != "main" + && ident.contains(|c: char| c.is_ascii_alphanumeric() || c == '_') + && !ident.starts_with("gl_") + && ident != "main" } fn builtin_to_glsl(builtin: BuiltIn) -> &'static str { @@ -1484,3 +1590,9 @@ fn builtin_to_glsl(builtin: BuiltIn) -> &'static str { BuiltIn::WorkGroupId => "gl_WorkGroupID", } } + +fn write_format_glsl(format: StorageFormat) -> &'static str { + match format { + StorageFormat::Rgba32f => "rgba32f", + } +} From 1b17030d052a5624b3575fd3d774f0db66b52c70 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 27 Aug 2020 23:30:53 -0400 Subject: [PATCH 0173/2212] Split wgsl into sub-modules, and gate by a feature (#165) --- Cargo.toml | 1 + examples/convert.rs | 1 + src/front/mod.rs | 3 +- src/front/wgsl/lexer.rs | 246 +++++++++++++++++ src/front/{wgsl.rs => wgsl/mod.rs} | 251 +----------------- .../rosetta_tests.rs} | 0 tests/convert.rs | 7 +- 7 files changed, 261 insertions(+), 248 deletions(-) create mode 100644 src/front/wgsl/lexer.rs rename src/front/{wgsl.rs => wgsl/mod.rs} (88%) rename src/front/{wgsl_rosetta_tests.rs => wgsl/rosetta_tests.rs} (100%) diff --git a/Cargo.toml b/Cargo.toml index 19157929a..c80416608 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ serialize = ["serde"] deserialize = ["serde"] spirv-in = ["petgraph", "spirv"] spirv-out = ["spirv"] +wgsl-in = [] [dev-dependencies] difference = "2.0" diff --git a/examples/convert.rs b/examples/convert.rs index 4cb4d1297..3e54b8ffb 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -43,6 +43,7 @@ fn main() { let input = fs::read(&args[1]).unwrap(); naga::front::spv::parse_u8_slice(&input).unwrap() } + #[cfg(feature = "wgsl-in")] "wgsl" => { let input = fs::read_to_string(&args[1]).unwrap(); naga::front::wgsl::parse_str(&input).unwrap() diff --git a/src/front/mod.rs b/src/front/mod.rs index 62117c3fd..cb531bb92 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -6,9 +6,8 @@ pub mod glsl; pub mod glsl_new; #[cfg(feature = "spirv-in")] pub mod spv; +#[cfg(feature = "wgsl-in")] pub mod wgsl; -#[cfg(all(test, feature = "serialize"))] -mod wgsl_rosetta_tests; use crate::arena::Arena; diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs new file mode 100644 index 000000000..5468bedb8 --- /dev/null +++ b/src/front/wgsl/lexer.rs @@ -0,0 +1,246 @@ +use super::{Error, Token}; + +fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { + if input.starts_with(what) { + Some(&input[what.len()..]) + } else { + None + } +} + +fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { + let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); + input.split_at(pos) +} + +fn consume_number(input: &str) -> (&str, &str) { + let mut is_first_char = true; + let mut right_after_exponent = false; + + let mut what = |c| { + if is_first_char { + is_first_char = false; + c == '-' || c >= '0' && c <= '9' || c == '.' + } else if c == 'e' || c == 'E' { + right_after_exponent = true; + true + } else if right_after_exponent { + right_after_exponent = false; + c >= '0' && c <= '9' || c == '-' + } else { + c >= '0' && c <= '9' || c == '.' + } + }; + let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); + input.split_at(pos) +} + +fn consume_token(mut input: &str) -> (Token<'_>, &str) { + input = input.trim_start(); + let mut chars = input.chars(); + let cur = match chars.next() { + Some(c) => c, + None => return (Token::End, input), + }; + match cur { + ':' => { + input = chars.as_str(); + if chars.next() == Some(':') { + (Token::DoubleColon, chars.as_str()) + } else { + (Token::Separator(cur), input) + } + } + ';' | ',' => (Token::Separator(cur), chars.as_str()), + '.' => { + let og_chars = chars.as_str(); + match chars.next() { + Some('0'..='9') => { + let (number, rest) = consume_number(input); + (Token::Number(number), rest) + } + _ => (Token::Separator(cur), og_chars), + } + } + '(' | ')' | '{' | '}' => (Token::Paren(cur), chars.as_str()), + '<' | '>' => { + input = chars.as_str(); + let next = chars.next(); + if next == Some('=') { + (Token::LogicalOperation(cur), chars.as_str()) + } else if next == Some(cur) { + input = chars.as_str(); + if chars.next() == Some(cur) { + (Token::ArithmeticShiftOperation(cur), chars.as_str()) + } else { + (Token::ShiftOperation(cur), input) + } + } else { + (Token::Paren(cur), input) + } + } + '[' | ']' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + (Token::DoubleParen(cur), chars.as_str()) + } else { + (Token::Paren(cur), input) + } + } + '0'..='9' => { + let (number, rest) = consume_number(input); + (Token::Number(number), rest) + } + 'a'..='z' | 'A'..='Z' | '_' => { + let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); + (Token::Word(word), rest) + } + '"' => { + let mut iter = chars.as_str().splitn(2, '"'); + + // splitn returns an iterator with at least one element, so unwrapping is fine + let quote_content = iter.next().unwrap(); + if let Some(rest) = iter.next() { + (Token::String(quote_content), rest) + } else { + (Token::UnterminatedString, quote_content) + } + } + '-' => { + let og_chars = chars.as_str(); + match chars.next() { + Some('>') => (Token::Arrow, chars.as_str()), + Some('0'..='9') | Some('.') => { + let (number, rest) = consume_number(input); + (Token::Number(number), rest) + } + _ => (Token::Operation(cur), og_chars), + } + } + '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), + '!' => { + if chars.next() == Some('=') { + (Token::LogicalOperation(cur), chars.as_str()) + } else { + (Token::Operation(cur), input) + } + } + '=' | '&' | '|' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + (Token::LogicalOperation(cur), chars.as_str()) + } else { + (Token::Operation(cur), input) + } + } + '#' => match chars.position(|c| c == '\n' || c == '\r') { + Some(_) => consume_token(chars.as_str()), + None => (Token::End, chars.as_str()), + }, + _ => (Token::Unknown(cur), chars.as_str()), + } +} + +#[derive(Clone)] +pub(super) struct Lexer<'a> { + input: &'a str, +} + +impl<'a> Lexer<'a> { + pub(super) fn new(input: &'a str) -> Self { + Lexer { input } + } + + #[must_use] + pub(super) fn next(&mut self) -> Token<'a> { + let (token, rest) = consume_token(self.input); + self.input = rest; + token + } + + #[must_use] + pub(super) fn peek(&mut self) -> Token<'a> { + self.clone().next() + } + + pub(super) fn expect(&mut self, expected: Token<'_>) -> Result<(), Error<'a>> { + let token = self.next(); + if token == expected { + Ok(()) + } else { + Err(Error::Unexpected(token)) + } + } + + pub(super) fn skip(&mut self, what: Token<'_>) -> bool { + let (token, rest) = consume_token(self.input); + if token == what { + self.input = rest; + true + } else { + false + } + } + + pub(super) fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { + match self.next() { + Token::Word(word) => Ok(word), + other => Err(Error::Unexpected(other)), + } + } + + fn _next_float_literal(&mut self) -> Result> { + match self.next() { + Token::Number(word) => word.parse().map_err(|err| Error::BadFloat(word, err)), + other => Err(Error::Unexpected(other)), + } + } + + pub(super) fn next_uint_literal(&mut self) -> Result> { + match self.next() { + Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), + other => Err(Error::Unexpected(other)), + } + } + + fn _next_sint_literal(&mut self) -> Result> { + match self.next() { + Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), + other => Err(Error::Unexpected(other)), + } + } + + pub(super) fn next_scalar_generic( + &mut self, + ) -> Result<(crate::ScalarKind, crate::Bytes), Error<'a>> { + self.expect(Token::Paren('<'))?; + let pair = match self.next() { + Token::Word("f32") => (crate::ScalarKind::Float, 4), + Token::Word("i32") => (crate::ScalarKind::Sint, 4), + Token::Word("u32") => (crate::ScalarKind::Uint, 4), + other => return Err(Error::Unexpected(other)), + }; + self.expect(Token::Paren('>'))?; + Ok(pair) + } + + pub(super) fn take_until(&mut self, what: Token<'_>) -> Result, Error<'a>> { + let original_input = self.input; + let initial_len = self.input.len(); + let mut used_len = 0; + loop { + if self.next() == what { + break; + } + used_len = initial_len - self.input.len(); + } + + Ok(Lexer { + input: &original_input[..used_len], + }) + } + + pub(super) fn offset_from(&self, source: &'a str) -> usize { + source.len() - self.input.len() + } +} diff --git a/src/front/wgsl.rs b/src/front/wgsl/mod.rs similarity index 88% rename from src/front/wgsl.rs rename to src/front/wgsl/mod.rs index a2cd5b3d8..cd57c5767 100644 --- a/src/front/wgsl.rs +++ b/src/front/wgsl/mod.rs @@ -1,12 +1,18 @@ //! Front end for consuming [WebGPU Shading Language][wgsl]. //! //! [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html + +mod lexer; +#[cfg(all(test, feature = "serialize"))] +mod rosetta_tests; + use crate::{ arena::{Arena, Handle}, proc::{ResolveError, Typifier}, FastHashMap, }; +use self::lexer::Lexer; use thiserror::Error; #[derive(Copy, Clone, Debug, PartialEq)] @@ -28,151 +34,6 @@ pub enum Token<'a> { End, } -mod lex { - use super::Token; - - fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { - if input.starts_with(what) { - Some(&input[what.len()..]) - } else { - None - } - } - - fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { - let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); - input.split_at(pos) - } - - fn consume_number(input: &str) -> (&str, &str) { - let mut is_first_char = true; - let mut right_after_exponent = false; - - let mut what = |c| { - if is_first_char { - is_first_char = false; - c == '-' || c >= '0' && c <= '9' || c == '.' - } else if c == 'e' || c == 'E' { - right_after_exponent = true; - true - } else if right_after_exponent { - right_after_exponent = false; - c >= '0' && c <= '9' || c == '-' - } else { - c >= '0' && c <= '9' || c == '.' - } - }; - let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); - input.split_at(pos) - } - - pub fn consume_token(mut input: &str) -> (Token<'_>, &str) { - input = input.trim_start(); - let mut chars = input.chars(); - let cur = match chars.next() { - Some(c) => c, - None => return (Token::End, input), - }; - match cur { - ':' => { - input = chars.as_str(); - if chars.next() == Some(':') { - (Token::DoubleColon, chars.as_str()) - } else { - (Token::Separator(cur), input) - } - } - ';' | ',' => (Token::Separator(cur), chars.as_str()), - '.' => { - let og_chars = chars.as_str(); - match chars.next() { - Some('0'..='9') => { - let (number, rest) = consume_number(input); - (Token::Number(number), rest) - } - _ => (Token::Separator(cur), og_chars), - } - } - '(' | ')' | '{' | '}' => (Token::Paren(cur), chars.as_str()), - '<' | '>' => { - input = chars.as_str(); - let next = chars.next(); - if next == Some('=') { - (Token::LogicalOperation(cur), chars.as_str()) - } else if next == Some(cur) { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::ArithmeticShiftOperation(cur), chars.as_str()) - } else { - (Token::ShiftOperation(cur), input) - } - } else { - (Token::Paren(cur), input) - } - } - '[' | ']' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::DoubleParen(cur), chars.as_str()) - } else { - (Token::Paren(cur), input) - } - } - '0'..='9' => { - let (number, rest) = consume_number(input); - (Token::Number(number), rest) - } - 'a'..='z' | 'A'..='Z' | '_' => { - let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); - (Token::Word(word), rest) - } - '"' => { - let mut iter = chars.as_str().splitn(2, '"'); - - // splitn returns an iterator with at least one element, so unwrapping is fine - let quote_content = iter.next().unwrap(); - if let Some(rest) = iter.next() { - (Token::String(quote_content), rest) - } else { - (Token::UnterminatedString, quote_content) - } - } - '-' => { - let og_chars = chars.as_str(); - match chars.next() { - Some('>') => (Token::Arrow, chars.as_str()), - Some('0'..='9') | Some('.') => { - let (number, rest) = consume_number(input); - (Token::Number(number), rest) - } - _ => (Token::Operation(cur), og_chars), - } - } - '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), - '!' => { - if chars.next() == Some('=') { - (Token::LogicalOperation(cur), chars.as_str()) - } else { - (Token::Operation(cur), input) - } - } - '=' | '&' | '|' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::LogicalOperation(cur), chars.as_str()) - } else { - (Token::Operation(cur), input) - } - } - '#' => match chars.position(|c| c == '\n' || c == '\r') { - Some(_) => consume_token(chars.as_str()), - None => (Token::End, chars.as_str()), - }, - _ => (Token::Unknown(cur), chars.as_str()), - } - } -} - #[derive(Clone, Debug, Error)] pub enum Error<'a> { #[error("unexpected token: {0:?}")] @@ -217,104 +78,6 @@ pub enum Error<'a> { Other, } -#[derive(Clone)] -struct Lexer<'a> { - input: &'a str, -} - -impl<'a> Lexer<'a> { - fn new(input: &'a str) -> Self { - Lexer { input } - } - - #[must_use] - fn next(&mut self) -> Token<'a> { - let (token, rest) = lex::consume_token(self.input); - self.input = rest; - token - } - - #[must_use] - fn peek(&mut self) -> Token<'a> { - self.clone().next() - } - - fn expect(&mut self, expected: Token<'_>) -> Result<(), Error<'a>> { - let token = self.next(); - if token == expected { - Ok(()) - } else { - Err(Error::Unexpected(token)) - } - } - - fn skip(&mut self, what: Token<'_>) -> bool { - let (token, rest) = lex::consume_token(self.input); - if token == what { - self.input = rest; - true - } else { - false - } - } - - fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { - match self.next() { - Token::Word(word) => Ok(word), - other => Err(Error::Unexpected(other)), - } - } - - fn _next_float_literal(&mut self) -> Result> { - match self.next() { - Token::Number(word) => word.parse().map_err(|err| Error::BadFloat(word, err)), - other => Err(Error::Unexpected(other)), - } - } - - fn next_uint_literal(&mut self) -> Result> { - match self.next() { - Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), - other => Err(Error::Unexpected(other)), - } - } - - fn _next_sint_literal(&mut self) -> Result> { - match self.next() { - Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), - other => Err(Error::Unexpected(other)), - } - } - - fn next_scalar_generic(&mut self) -> Result<(crate::ScalarKind, crate::Bytes), Error<'a>> { - self.expect(Token::Paren('<'))?; - let pair = match self.next() { - Token::Word("f32") => (crate::ScalarKind::Float, 4), - Token::Word("i32") => (crate::ScalarKind::Sint, 4), - Token::Word("u32") => (crate::ScalarKind::Uint, 4), - other => return Err(Error::Unexpected(other)), - }; - self.expect(Token::Paren('>'))?; - Ok(pair) - } - - fn take_until(&mut self, what: Token<'_>) -> Result, Error<'a>> { - let original_input = self.input; - let initial_len = self.input.len(); - let mut used_len = 0; - loop { - if self.next() == what { - break; - } - used_len = initial_len - self.input.len(); - } - - Ok(Lexer { - input: &original_input[..used_len], - }) - } -} - trait StringValueLookup<'a> { type Value; fn lookup(&self, key: &'a str) -> Result>; @@ -1724,7 +1487,7 @@ impl Parser { loop { match self.parse_global_decl(&mut lexer, &mut module, &mut lookup_global_expression) { Err(error) => { - let pos = source.len() - lexer.input.len(); + let pos = lexer.offset_from(source); let (mut rows, mut cols) = (0, 1); for line in source[..pos].lines() { rows += 1; diff --git a/src/front/wgsl_rosetta_tests.rs b/src/front/wgsl/rosetta_tests.rs similarity index 100% rename from src/front/wgsl_rosetta_tests.rs rename to src/front/wgsl/rosetta_tests.rs diff --git a/tests/convert.rs b/tests/convert.rs index c75b04515..ef3431f56 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -3,12 +3,13 @@ fn load_test_data(name: &str) -> String { std::fs::read_to_string(path).unwrap() } +#[cfg(feature = "wgsl-in")] fn load_wgsl(name: &str) -> naga::Module { let input = load_test_data(name); naga::front::wgsl::parse_str(&input).unwrap() } -#[cfg(feature = "spirv")] +#[cfg(feature = "spirv-in")] fn load_spv(name: &str) -> naga::Module { let path = format!("{}/test-data/spv/{}", env!("CARGO_MANIFEST_DIR"), name); let input = std::fs::read(path).unwrap(); @@ -21,6 +22,7 @@ fn load_glsl(name: &str, entry: &str, stage: naga::ShaderStage) -> naga::Module naga::front::glsl::parse_str(&input, entry.to_owned(), stage).unwrap() } +#[cfg(feature = "spirv-in")] #[test] fn convert_quad() { let module = load_wgsl("quad.wgsl"); @@ -53,6 +55,7 @@ fn convert_quad() { } } +#[cfg(feature = "wgsl-in")] #[test] fn convert_boids() { let module = load_wgsl("boids.wgsl"); @@ -94,7 +97,7 @@ fn convert_boids() { } } -#[cfg(feature = "spirv")] +#[cfg(feature = "spirv-in")] #[test] fn convert_cube() { let mut validator = naga::proc::Validator::new(); From c824287fd57a9709704acf16258b0119950647b5 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Fri, 28 Aug 2020 18:09:57 +0200 Subject: [PATCH 0174/2212] [glsl-new] Refactor type handling (#166) * [glsl-new] Refactor type handling * [glsl-new] Fix clippy error --- src/front/glsl_new/lex.rs | 65 ++------------------- src/front/glsl_new/mod.rs | 1 + src/front/glsl_new/parser.rs | 74 +----------------------- src/front/glsl_new/types.rs | 106 +++++++++++++++++++++++++++++++++++ 4 files changed, 114 insertions(+), 132 deletions(-) create mode 100644 src/front/glsl_new/types.rs diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 17be2d30f..d7ae86008 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -1,5 +1,5 @@ use super::parser::Token; -use super::token::TokenMetadata; +use super::{token::TokenMetadata, types::parse_type}; use std::{iter::Enumerate, str::Lines}; fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { @@ -138,68 +138,11 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { ), // types "void" => (Some(Token::Void(meta)), rest), - "float" => (Some(Token::Float(meta)), rest), - "double" => (Some(Token::Double(meta)), rest), - "int" => (Some(Token::Int(meta)), rest), - "uint" => (Some(Token::Uint(meta)), rest), word => { - use crate::{ScalarKind, VectorSize}; - - fn kind_width_parse(ty: &str) -> Option<(ScalarKind, u8)> { - Some(match ty { - "" => (ScalarKind::Float, 4), - "b" => (ScalarKind::Bool, 4), - "i" => (ScalarKind::Sint, 4), - "u" => (ScalarKind::Uint, 4), - "d" => (ScalarKind::Float, 8), - _ => return None, - }) - } - - fn size_parse(n: &str) -> Option { - Some(match n { - "2" => VectorSize::Bi, - "3" => VectorSize::Tri, - "4" => VectorSize::Quad, - _ => return None, - }) - } - - let vec_parse = |word: &str| { - let mut iter = word.split("vec"); - - let kind = iter.next()?; - let size = iter.next()?; - let (kind, width) = kind_width_parse(kind)?; - let size = size_parse(size)?; - - Some(Token::Vec((meta.clone(), (size, kind, width)))) + let token = match parse_type(word) { + Some(t) => Token::TypeName((meta, t)), + None => Token::Identifier((meta, String::from(word))), }; - - let mat_parse = |word: &str| { - let mut iter = word.split("mat"); - - let kind = iter.next()?; - let size = iter.next()?; - let (kind, width) = kind_width_parse(kind)?; - - let (col, row) = if let Some(size) = size_parse(size) { - (size, size) - } else { - let mut iter = size.split('x'); - match (iter.next()?, iter.next()?, iter.next()) { - (col, row, None) => (size_parse(col)?, size_parse(row)?), - _ => return None, - } - }; - - Some(Token::Mat((meta.clone(), (col, row, kind, width)))) - }; - - let token = vec_parse(word) - .or_else(|| mat_parse(word)) - .unwrap_or_else(|| Token::Identifier((meta, String::from(word)))); - (Some(token), rest) } } diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs index d937beda1..2af60fe94 100644 --- a/src/front/glsl_new/mod.rs +++ b/src/front/glsl_new/mod.rs @@ -14,6 +14,7 @@ mod parser; #[cfg(test)] mod parser_tests; mod token; +mod types; #[cfg(all(test, feature = "serialize"))] mod rosetta_tests; diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 953a0034d..c1c986d8e 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -7,7 +7,7 @@ pomelo! { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{Arena, BinaryOperator, Binding, Block, BuiltIn, Constant, ConstantInner, Expression, Function, GlobalVariable, Handle, LocalVariable, ScalarKind, - ShaderStage, Statement, StorageClass, Type, TypeInner, VectorSize, Bytes, Interpolation}; + ShaderStage, Statement, StorageClass, Type, TypeInner, VectorSize, Interpolation}; } %token #[derive(Debug)] pub enum Token {}; %parser pub struct Parser<'a> {}; @@ -106,9 +106,7 @@ pomelo! { %type type_specifier Option>; %type type_specifier_nonarray Option; - %type Vec (VectorSize, ScalarKind, Bytes); - %type Mat (VectorSize, VectorSize, ScalarKind, Bytes); - + %type TypeName Type; root ::= version_pragma translation_unit; version_pragma ::= Version IntConstant(V) Identifier?(P) { @@ -670,73 +668,7 @@ pomelo! { } type_specifier_nonarray ::= Void { None } - // Scalars - type_specifier_nonarray ::= Bool { - Some(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Bool, - width: 4, // https://stackoverflow.com/questions/9419781/what-is-the-size-of-glsl-boolean - } - }) - } - type_specifier_nonarray ::= Float { - Some(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 4, - } - }) - } - type_specifier_nonarray ::= Double { - Some(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 8, - } - }) - } - type_specifier_nonarray ::= Int { - Some(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - } - }) - } - type_specifier_nonarray ::= Uint { - Some(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - } - }) - } - type_specifier_nonarray ::= Vec((_, (size, kind, width))) { - Some(Type { - name: None, - inner: TypeInner::Vector { - size, - kind, - width, - } - }) - } - type_specifier_nonarray ::= Mat((_, (columns, rows, kind, width))) { - Some(Type { - name: None, - inner: TypeInner::Matrix { - columns, - rows, - kind, - width, - } - }) - } + type_specifier_nonarray ::= TypeName(t) {Some(t.1)}; // misc translation_unit ::= external_declaration; diff --git a/src/front/glsl_new/types.rs b/src/front/glsl_new/types.rs new file mode 100644 index 000000000..25845ef46 --- /dev/null +++ b/src/front/glsl_new/types.rs @@ -0,0 +1,106 @@ +use crate::{ScalarKind, Type, TypeInner, VectorSize}; + +pub fn parse_type(type_name: &str) -> Option { + match type_name { + "bool" => Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Bool, + width: 4, // https://stackoverflow.com/questions/9419781/what-is-the-size-of-glsl-boolean + }, + }), + "float" => Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 4, + }, + }), + "double" => Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 8, + }, + }), + "int" => Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + }), + "uint" => Some(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + }, + }), + word => { + fn kind_width_parse(ty: &str) -> Option<(ScalarKind, u8)> { + Some(match ty { + "" => (ScalarKind::Float, 4), + "b" => (ScalarKind::Bool, 4), + "i" => (ScalarKind::Sint, 4), + "u" => (ScalarKind::Uint, 4), + "d" => (ScalarKind::Float, 8), + _ => return None, + }) + } + + fn size_parse(n: &str) -> Option { + Some(match n { + "2" => VectorSize::Bi, + "3" => VectorSize::Tri, + "4" => VectorSize::Quad, + _ => return None, + }) + } + + let vec_parse = |word: &str| { + let mut iter = word.split("vec"); + + let kind = iter.next()?; + let size = iter.next()?; + let (kind, width) = kind_width_parse(kind)?; + let size = size_parse(size)?; + + Some(Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }) + }; + + let mat_parse = |word: &str| { + let mut iter = word.split("mat"); + + let kind = iter.next()?; + let size = iter.next()?; + let (kind, width) = kind_width_parse(kind)?; + + let (columns, rows) = if let Some(size) = size_parse(size) { + (size, size) + } else { + let mut iter = size.split('x'); + match (iter.next()?, iter.next()?, iter.next()) { + (col, row, None) => (size_parse(col)?, size_parse(row)?), + _ => return None, + } + }; + + Some(Type { + name: None, + inner: TypeInner::Matrix { + columns, + rows, + kind, + width, + }, + }) + }; + + vec_parse(word).or_else(|| mat_parse(word)) + } + } +} From 7a43c78e29f9dd8389d4db186123e05d3c8d7d98 Mon Sep 17 00:00:00 2001 From: Matus Talcik Date: Fri, 28 Aug 2020 20:55:30 +0200 Subject: [PATCH 0175/2212] Add storage formats (#167) Add GLSL backend Add SPIR-V back + front --- src/back/glsl.rs | 33 +++++++++++++++++++++++++++- src/back/spv/writer.rs | 33 +++++++++++++++++++++++++++- src/front/spv/convert.rs | 36 ++++++++++++++++++++++++++++--- src/lib.rs | 46 +++++++++++++++++++++++++++++++++++++--- 4 files changed, 140 insertions(+), 8 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 4e98f0eba..caf75ae82 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1593,6 +1593,37 @@ fn builtin_to_glsl(builtin: BuiltIn) -> &'static str { fn write_format_glsl(format: StorageFormat) -> &'static str { match format { - StorageFormat::Rgba32f => "rgba32f", + StorageFormat::R8Unorm => "r8", + StorageFormat::R8Snorm => "r8_snorm", + StorageFormat::R8Uint => "r8ui", + StorageFormat::R8Sint => "r8i", + StorageFormat::R16Uint => "r16ui", + StorageFormat::R16Sint => "r16i", + StorageFormat::R16Float => "r16f", + StorageFormat::Rg8Unorm => "rg8", + StorageFormat::Rg8Snorm => "rg8_snorm", + StorageFormat::Rg8Uint => "rg8ui", + StorageFormat::Rg8Sint => "rg8i", + StorageFormat::R32Uint => "r32ui", + StorageFormat::R32Sint => "r32i", + StorageFormat::R32Float => "r32f", + StorageFormat::Rg16Uint => "rg16ui", + StorageFormat::Rg16Sint => "rg16i", + StorageFormat::Rg16Float => "rg16f", + StorageFormat::Rgba8Unorm => "rgba8ui", + StorageFormat::Rgba8Snorm => "rgba8_snorm", + StorageFormat::Rgba8Uint => "rgba8ui", + StorageFormat::Rgba8Sint => "rgba8i", + StorageFormat::Rgb10a2Unorm => "rgb10_a2ui", + StorageFormat::Rg11b10Float => "r11f_g11f_b10f", + StorageFormat::Rg32Uint => "rg32ui", + StorageFormat::Rg32Sint => "rg32i", + StorageFormat::Rg32Float => "rg32f", + StorageFormat::Rgba16Uint => "rgba16ui", + StorageFormat::Rgba16Sint => "rgba16i", + StorageFormat::Rgba16Float => "rgba16f", + StorageFormat::Rgba32Uint => "rgba32ui", + StorageFormat::Rgba32Sint => "rgba32i", + StorageFormat::Rgba32Float => "rgba32f", } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 07c98b96d..1c6c6957b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -419,7 +419,38 @@ impl Writer { let (format, access) = match class { crate::ImageClass::Storage(format, access) => { let spv_format = match format { - crate::StorageFormat::Rgba32f => spirv::ImageFormat::Rgba32f, + crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8, + crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm, + crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui, + crate::StorageFormat::R8Sint => spirv::ImageFormat::R8i, + crate::StorageFormat::R16Uint => spirv::ImageFormat::R16ui, + crate::StorageFormat::R16Sint => spirv::ImageFormat::R16i, + crate::StorageFormat::R16Float => spirv::ImageFormat::R16f, + crate::StorageFormat::Rg8Unorm => spirv::ImageFormat::Rg8, + crate::StorageFormat::Rg8Snorm => spirv::ImageFormat::Rg8Snorm, + crate::StorageFormat::Rg8Uint => spirv::ImageFormat::Rg8ui, + crate::StorageFormat::Rg8Sint => spirv::ImageFormat::Rg8i, + crate::StorageFormat::R32Uint => spirv::ImageFormat::R32ui, + crate::StorageFormat::R32Sint => spirv::ImageFormat::R32i, + crate::StorageFormat::R32Float => spirv::ImageFormat::R32f, + crate::StorageFormat::Rg16Uint => spirv::ImageFormat::Rg16ui, + crate::StorageFormat::Rg16Sint => spirv::ImageFormat::Rg16i, + crate::StorageFormat::Rg16Float => spirv::ImageFormat::Rg16f, + crate::StorageFormat::Rgba8Unorm => spirv::ImageFormat::Rgba8, + crate::StorageFormat::Rgba8Snorm => spirv::ImageFormat::Rgba8Snorm, + crate::StorageFormat::Rgba8Uint => spirv::ImageFormat::Rgba8ui, + crate::StorageFormat::Rgba8Sint => spirv::ImageFormat::Rgba8i, + crate::StorageFormat::Rgb10a2Unorm => spirv::ImageFormat::Rgb10a2ui, + crate::StorageFormat::Rg11b10Float => spirv::ImageFormat::R11fG11fB10f, + crate::StorageFormat::Rg32Uint => spirv::ImageFormat::Rg32ui, + crate::StorageFormat::Rg32Sint => spirv::ImageFormat::Rg32i, + crate::StorageFormat::Rg32Float => spirv::ImageFormat::Rg32f, + crate::StorageFormat::Rgba16Uint => spirv::ImageFormat::Rgba16ui, + crate::StorageFormat::Rgba16Sint => spirv::ImageFormat::Rgba16i, + crate::StorageFormat::Rgba16Float => spirv::ImageFormat::Rgba16f, + crate::StorageFormat::Rgba32Uint => spirv::ImageFormat::Rgba32ui, + crate::StorageFormat::Rgba32Sint => spirv::ImageFormat::Rgba32i, + crate::StorageFormat::Rgba32Float => spirv::ImageFormat::Rgba32f, }; (spv_format, access) } diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index fe3845a14..c7b5cfa48 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -70,9 +70,39 @@ pub fn map_image_dim(word: spirv::Word) -> Result } pub fn map_image_format(word: spirv::Word) -> Result { - use spirv::ImageFormat as If; - match If::from_u32(word) { - Some(If::Rgba32f) => Ok(crate::StorageFormat::Rgba32f), + match spirv::ImageFormat::from_u32(word) { + Some(spirv::ImageFormat::R8) => Ok(crate::StorageFormat::R8Unorm), + Some(spirv::ImageFormat::R8Snorm) => Ok(crate::StorageFormat::R8Snorm), + Some(spirv::ImageFormat::R8ui) => Ok(crate::StorageFormat::R8Uint), + Some(spirv::ImageFormat::R8i) => Ok(crate::StorageFormat::R8Sint), + Some(spirv::ImageFormat::R16ui) => Ok(crate::StorageFormat::R16Uint), + Some(spirv::ImageFormat::R16i) => Ok(crate::StorageFormat::R16Sint), + Some(spirv::ImageFormat::R16f) => Ok(crate::StorageFormat::R16Float), + Some(spirv::ImageFormat::Rg8) => Ok(crate::StorageFormat::Rg8Unorm), + Some(spirv::ImageFormat::Rg8Snorm) => Ok(crate::StorageFormat::Rg8Snorm), + Some(spirv::ImageFormat::Rg8ui) => Ok(crate::StorageFormat::Rg8Uint), + Some(spirv::ImageFormat::Rg8i) => Ok(crate::StorageFormat::Rg8Sint), + Some(spirv::ImageFormat::R32ui) => Ok(crate::StorageFormat::R32Uint), + Some(spirv::ImageFormat::R32i) => Ok(crate::StorageFormat::R32Sint), + Some(spirv::ImageFormat::R32f) => Ok(crate::StorageFormat::R32Float), + Some(spirv::ImageFormat::Rg16ui) => Ok(crate::StorageFormat::Rg16Uint), + Some(spirv::ImageFormat::Rg16i) => Ok(crate::StorageFormat::Rg16Sint), + Some(spirv::ImageFormat::Rg16f) => Ok(crate::StorageFormat::Rg16Float), + Some(spirv::ImageFormat::Rgba8) => Ok(crate::StorageFormat::Rgba8Unorm), + Some(spirv::ImageFormat::Rgba8Snorm) => Ok(crate::StorageFormat::Rgba8Snorm), + Some(spirv::ImageFormat::Rgba8ui) => Ok(crate::StorageFormat::Rgba8Uint), + Some(spirv::ImageFormat::Rgba8i) => Ok(crate::StorageFormat::Rgba8Sint), + Some(spirv::ImageFormat::Rgb10a2ui) => Ok(crate::StorageFormat::Rgb10a2Unorm), + Some(spirv::ImageFormat::R11fG11fB10f) => Ok(crate::StorageFormat::Rg11b10Float), + Some(spirv::ImageFormat::Rg32ui) => Ok(crate::StorageFormat::Rg32Uint), + Some(spirv::ImageFormat::Rg32i) => Ok(crate::StorageFormat::Rg32Sint), + Some(spirv::ImageFormat::Rg32f) => Ok(crate::StorageFormat::Rg32Float), + Some(spirv::ImageFormat::Rgba16ui) => Ok(crate::StorageFormat::Rgba16Uint), + Some(spirv::ImageFormat::Rgba16i) => Ok(crate::StorageFormat::Rgba16Sint), + Some(spirv::ImageFormat::Rgba16f) => Ok(crate::StorageFormat::Rgba16Float), + Some(spirv::ImageFormat::Rgba32ui) => Ok(crate::StorageFormat::Rgba32Uint), + Some(spirv::ImageFormat::Rgba32i) => Ok(crate::StorageFormat::Rgba32Sint), + Some(spirv::ImageFormat::Rgba32f) => Ok(crate::StorageFormat::Rgba32Float), _ => Err(Error::UnsupportedImageFormat(word)), } } diff --git a/src/lib.rs b/src/lib.rs index 3315108e7..a7c68a417 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -222,9 +222,49 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum StorageFormat { - /// - Rgba32f, - //TODO + // 8-bit formats + R8Unorm, + R8Snorm, + R8Uint, + R8Sint, + + // 16-bit formats + R16Uint, + R16Sint, + R16Float, + Rg8Unorm, + Rg8Snorm, + Rg8Uint, + Rg8Sint, + + // 32-bit formats + R32Uint, + R32Sint, + R32Float, + Rg16Uint, + Rg16Sint, + Rg16Float, + Rgba8Unorm, + Rgba8Snorm, + Rgba8Uint, + Rgba8Sint, + + // Packed 32-bit formats + Rgb10a2Unorm, + Rg11b10Float, + + // 64-bit formats + Rg32Uint, + Rg32Sint, + Rg32Float, + Rgba16Uint, + Rgba16Sint, + Rgba16Float, + + // 128-bit formats + Rgba32Uint, + Rgba32Sint, + Rgba32Float, } /// Sub-class of the image type. From d370686351444f871bf2d4f886b32a19820cec8c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 28 Aug 2020 00:44:52 -0400 Subject: [PATCH 0176/2212] proc: support parameter types in Typifier --- src/arena.rs | 28 ++++--- src/front/glsl/mod.rs | 73 ++++++++++++++----- src/front/wgsl/mod.rs | 61 ++++++++++------ src/proc/typifier.rs | 165 ++++++++++++++++++++++-------------------- 4 files changed, 192 insertions(+), 135 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 3d7304644..210133e1b 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -9,8 +9,8 @@ use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32}; type Index = NonZeroU32; /// A strongly typed reference to a SPIR-V element. -#[cfg_attr(feature = "serialize", derive(crate::Serialize))] -#[cfg_attr(feature = "deserialize", derive(crate::Deserialize))] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[cfg_attr( any(feature = "serialize", feature = "deserialize"), serde(transparent) @@ -85,8 +85,8 @@ impl Handle { /// The arena can be indexed using the given handle to obtain /// a reference to the stored item. #[derive(Debug)] -#[cfg_attr(feature = "serialize", derive(crate::Serialize))] -#[cfg_attr(feature = "deserialize", derive(crate::Deserialize))] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[cfg_attr( any(feature = "serialize", feature = "deserialize"), serde(transparent) @@ -138,14 +138,12 @@ impl Arena { Handle::new(index) } - /// Adds a value with a check for uniqueness: returns a handle pointing to - /// an existing element if its value matches the given one, or adds a new + /// Adds a value with a custom check for uniqueness: + /// returns a handle pointing to + /// an existing element if the check succeeds, or adds a new /// element otherwise. - pub fn fetch_or_append(&mut self, value: T) -> Handle - where - T: PartialEq, - { - if let Some(index) = self.data.iter().position(|d| d == &value) { + pub fn fetch_if_or_append bool>(&mut self, value: T, fun: F) -> Handle { + if let Some(index) = self.data.iter().position(|d| fun(d, &value)) { let index = unsafe { Index::new_unchecked((index + 1) as u32) }; Handle::new(index) } else { @@ -153,6 +151,14 @@ impl Arena { } } + /// Adds a value with a check for uniqueness, where the check is plain comparison. + pub fn fetch_or_append(&mut self, value: T) -> Handle + where + T: PartialEq, + { + self.fetch_if_or_append(value, T::eq) + } + /// Get a mutable reference to an element in the arena. pub fn get_mut(&mut self, handle: Handle) -> &mut T { self.data.get_mut(handle.index.get() as usize - 1).unwrap() diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index b4061233b..6bc39d63c 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -151,6 +151,7 @@ impl<'a> Parser<'a> { &mut locals, &mut locals_map, ¶meter_lookup, + &[], )?; let handle = expressions.append(expr); let val = self.eval_const_expr(handle, &expressions)?; @@ -174,7 +175,7 @@ impl<'a> Parser<'a> { let mut index = 0; for field in block.fields { - let ty = self.parse_type(field.ty).unwrap(); + let ty = self.parse_type(field.ty, &[]).unwrap(); for ident in field.identifiers { let field_name = ident.ident.0; @@ -184,7 +185,7 @@ impl<'a> Parser<'a> { name: Some(field_name.clone()), origin, ty: if let Some(array_spec) = ident.array_spec { - let size = self.parse_array_size(array_spec)?; + let size = self.parse_array_size(array_spec, &[])?; self.types.fetch_or_append(Type { name: None, inner: TypeInner::Array { @@ -213,7 +214,7 @@ impl<'a> Parser<'a> { inner: TypeInner::Struct { members: fields }, }); - let size = self.parse_array_size(array_spec)?; + let size = self.parse_array_size(array_spec, &[])?; self.types.fetch_or_append(Type { name: None, inner: TypeInner::Array { @@ -271,7 +272,7 @@ impl<'a> Parser<'a> { let name = function.prototype.name.0; // Parse return type - let ty = self.parse_type(function.prototype.ty.ty); + let ty = self.parse_type(function.prototype.ty.ty, &[]); let mut parameter_types = Vec::with_capacity(function.prototype.parameters.len()); let mut parameter_lookup = FastHashMap::default(); @@ -285,10 +286,10 @@ impl<'a> Parser<'a> { for (index, parameter) in function.prototype.parameters.into_iter().enumerate() { match parameter { FunctionParameterDeclaration::Named(_ /* TODO */, decl) => { - let ty = self.parse_type(decl.ty).unwrap(); + let ty = self.parse_type(decl.ty, &[]).unwrap(); let ty = if let Some(array_spec) = decl.ident.array_spec { - let size = self.parse_array_size(array_spec)?; + let size = self.parse_array_size(array_spec, &[])?; self.types.fetch_or_append(Type { name: None, inner: TypeInner::Array { @@ -308,7 +309,7 @@ impl<'a> Parser<'a> { ); } FunctionParameterDeclaration::Unnamed(_, ty) => { - parameter_types.push(self.parse_type(ty).unwrap()); + parameter_types.push(self.parse_type(ty, &[]).unwrap()); } } } @@ -325,6 +326,7 @@ impl<'a> Parser<'a> { &mut local_variables, &mut locals_map, ¶meter_lookup, + ¶meter_types, )?; } _ => unimplemented!(), @@ -336,6 +338,7 @@ impl<'a> Parser<'a> { &mut local_variables, &mut locals_map, ¶meter_lookup, + ¶meter_types, )?); } SimpleStatement::Expression(None) => (), @@ -355,6 +358,7 @@ impl<'a> Parser<'a> { &mut local_variables, &mut locals_map, ¶meter_lookup, + ¶meter_types, ) .unwrap(); expressions.append(expr) @@ -385,13 +389,14 @@ impl<'a> Parser<'a> { locals: &mut Arena, locals_map: &mut FastHashMap>, parameter_lookup: &FastHashMap, + parameter_types: &[Handle], ) -> Result, Error> { let name = init.head.name.map(|d| d.0); let ty = { - let ty = self.parse_type(init.head.ty.ty).unwrap(); + let ty = self.parse_type(init.head.ty.ty, parameter_types).unwrap(); if let Some(array_spec) = init.head.array_specifier { - let size = self.parse_array_size(array_spec)?; + let size = self.parse_array_size(array_spec, parameter_types)?; self.types.fetch_or_append(Type { name: None, inner: TypeInner::Array { @@ -412,6 +417,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?) } else { None @@ -435,6 +441,7 @@ impl<'a> Parser<'a> { locals: &mut Arena, locals_map: &mut FastHashMap>, parameter_lookup: &FastHashMap, + parameter_types: &[Handle], ) -> Result, Error> { match initializer { Initializer::Simple(expr) => { @@ -444,6 +451,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?; Ok(expressions.append(handle)) @@ -459,6 +467,7 @@ impl<'a> Parser<'a> { locals: &mut Arena, locals_map: &mut FastHashMap>, parameter_lookup: &FastHashMap, + parameter_types: &[Handle], ) -> Result { match expr { Expr::Assignment(reg, op, value) => { @@ -469,6 +478,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?; expressions.append(pointer) }; @@ -479,6 +489,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?; let value = match op { AssignmentOp::Equal => right, @@ -555,6 +566,7 @@ impl<'a> Parser<'a> { locals: &mut Arena, locals_map: &mut FastHashMap>, parameter_lookup: &FastHashMap, + parameter_types: &[Handle], ) -> Result { match expr { Expr::Variable(ident) => { @@ -765,8 +777,14 @@ impl<'a> Parser<'a> { }, ))), Expr::Unary(op, reg) => { - let expr = - self.parse_expression(*reg, expressions, locals, locals_map, parameter_lookup)?; + let expr = self.parse_expression( + *reg, + expressions, + locals, + locals_map, + parameter_lookup, + parameter_types, + )?; Ok(Expression::Unary { op: helpers::glsl_to_spirv_unary_op(op), expr: expressions.append(expr), @@ -779,6 +797,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?; let right = self.parse_expression( *right, @@ -786,6 +805,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?; Ok(Expression::Binary { @@ -828,6 +848,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, ) .unwrap(); expressions.append(expr) @@ -850,6 +871,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?, self.parse_expression( sample_args.remove(0), @@ -857,6 +879,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?, ), _ => unimplemented!(), @@ -871,6 +894,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?; Ok(Expression::ImageSample { @@ -893,6 +917,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, ) .unwrap(); expressions.append(expr) @@ -909,6 +934,7 @@ impl<'a> Parser<'a> { locals, locals_map, parameter_lookup, + parameter_types, )?; expressions.append(expr) }; @@ -924,6 +950,7 @@ impl<'a> Parser<'a> { &self.globals, locals, &self.functions, + parameter_types, ) .map_err(|e| Error { kind: e.into() })?; let base_type = &self.types[type_handle]; @@ -977,10 +1004,7 @@ impl<'a> Parser<'a> { crate::TypeInner::Vector { size, kind, width } }; Ok(crate::Expression::Compose { - ty: crate::proc::Typifier::deduce_type_handle( - inner, - &mut self.types, - ), + ty: self.types.fetch_or_append(Type { name: None, inner }), components, }) } else { @@ -1005,7 +1029,11 @@ impl<'a> Parser<'a> { } // None = void - fn parse_type(&mut self, ty: TypeSpecifier) -> Option> { + fn parse_type( + &mut self, + ty: TypeSpecifier, + parameter_types: &[Handle], + ) -> Option> { let base_ty = helpers::glsl_to_spirv_type(ty.ty)?; let ty = if let Some(array_spec) = ty.array_specifier { @@ -1013,7 +1041,7 @@ impl<'a> Parser<'a> { name: None, inner: base_ty, }); - let size = self.parse_array_size(array_spec).unwrap(); + let size = self.parse_array_size(array_spec, parameter_types).unwrap(); TypeInner::Array { base: handle, @@ -1033,10 +1061,10 @@ impl<'a> Parser<'a> { fn parse_global(&mut self, head: SingleDeclaration) -> Result, Error> { let name = head.name.map(|d| d.0); let ty = { - let ty = self.parse_type(head.ty.ty).unwrap(); + let ty = self.parse_type(head.ty.ty, &[]).unwrap(); if let Some(array_spec) = head.array_specifier { - let size = self.parse_array_size(array_spec)?; + let size = self.parse_array_size(array_spec, &[])?; self.types.fetch_or_append(Type { name: None, inner: TypeInner::Array { @@ -1137,7 +1165,11 @@ impl<'a> Parser<'a> { } } - pub fn parse_array_size(&mut self, array_spec: ArraySpecifier) -> Result { + pub fn parse_array_size( + &mut self, + array_spec: ArraySpecifier, + parameter_types: &[Handle], + ) -> Result { let parameter_lookup = FastHashMap::default(); let mut locals = Arena::::new(); let mut locals_map = FastHashMap::default(); @@ -1151,6 +1183,7 @@ impl<'a> Parser<'a> { &mut locals, &mut locals_map, ¶meter_lookup, + parameter_types, )?; let handle = expressions.append(expr); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index cd57c5767..4e34671b1 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -97,6 +97,7 @@ struct StatementContext<'input, 'temp, 'out> { types: &'out mut Arena, constants: &'out mut Arena, global_vars: &'out Arena, + parameter_types: &'out [Handle], } impl<'a> StatementContext<'a, '_, '_> { @@ -109,6 +110,7 @@ impl<'a> StatementContext<'a, '_, '_> { types: self.types, constants: self.constants, global_vars: self.global_vars, + parameter_types: self.parameter_types, } } @@ -121,6 +123,7 @@ impl<'a> StatementContext<'a, '_, '_> { constants: self.constants, global_vars: self.global_vars, local_vars: self.variables, + parameter_types: self.parameter_types, } } } @@ -133,6 +136,7 @@ struct ExpressionContext<'input, 'temp, 'out> { constants: &'out mut Arena, global_vars: &'out Arena, local_vars: &'out Arena, + parameter_types: &'out [Handle], } impl<'a> ExpressionContext<'a, '_, '_> { @@ -145,6 +149,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { constants: self.constants, global_vars: self.global_vars, local_vars: self.local_vars, + parameter_types: self.parameter_types, } } @@ -160,7 +165,8 @@ impl<'a> ExpressionContext<'a, '_, '_> { self.constants, self.global_vars, self.local_vars, - &Arena::new(), + &Arena::new(), //TODO + self.parameter_types, ) .map_err(Error::InvalidResolve) } @@ -376,7 +382,7 @@ impl Parser { inner } _ => { - let composite_ty = self.parse_type_decl(lexer, type_arena)?; + let composite_ty = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -422,13 +428,13 @@ impl Parser { name: None, specialization: None, inner: crate::ConstantInner::Bool(true), - ty: Typifier::deduce_type_handle( - crate::TypeInner::Scalar { + ty: ctx.types.fetch_or_append(crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1, }, - ctx.types, - ), + }), }); crate::Expression::Constant(handle) } @@ -437,13 +443,13 @@ impl Parser { name: None, specialization: None, inner: crate::ConstantInner::Bool(false), - ty: Typifier::deduce_type_handle( - crate::TypeInner::Scalar { + ty: ctx.types.fetch_or_append(crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1, }, - ctx.types, - ), + }), }); crate::Expression::Constant(handle) } @@ -453,10 +459,10 @@ impl Parser { name: None, specialization: None, inner, - ty: Typifier::deduce_type_handle( - crate::TypeInner::Scalar { kind, width: 4 }, - ctx.types, - ), + ty: ctx.types.fetch_or_append(crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind, width: 4 }, + }), }); crate::Expression::Constant(handle) } @@ -472,7 +478,7 @@ impl Parser { expr } else { *lexer = backup; - let ty = self.parse_type_decl(lexer, ctx.types)?; + let ty = self.parse_type_decl(lexer, None, ctx.types)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -556,7 +562,9 @@ impl Parser { crate::TypeInner::Vector { size, kind, width } }; crate::Expression::Compose { - ty: Typifier::deduce_type_handle(inner, ctx.types), + ty: ctx + .types + .fetch_or_append(crate::Type { name: None, inner }), components, } } else { @@ -823,7 +831,7 @@ impl Parser { ) -> Result<(&'a str, Handle), Error<'a>> { let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, type_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena)?; Ok((name, ty)) } @@ -842,7 +850,7 @@ impl Parser { } let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, type_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena)?; if lexer.skip(Token::Operation('=')) { let _inner = self.parse_const_expression(lexer, type_arena, const_arena)?; //TODO @@ -890,7 +898,7 @@ impl Parser { return Err(Error::MissingMemberOffset(name)); } lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, type_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Separator(';'))?; members.push(crate::StructMember { name: Some(name.to_owned()), @@ -903,6 +911,7 @@ impl Parser { fn parse_type_decl<'a>( &mut self, lexer: &mut Lexer<'a>, + self_name: Option<&'a str>, type_arena: &mut Arena, ) -> Result, Error<'a>> { self.scopes.push(Scope::TypeDecl); @@ -1034,13 +1043,13 @@ impl Parser { lexer.expect(Token::Paren('<'))?; let class = Self::get_storage_class(lexer.next_ident()?)?; lexer.expect(Token::Separator(','))?; - let base = self.parse_type_decl(lexer, type_arena)?; + let base = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Paren('>'))?; crate::TypeInner::Pointer { base, class } } Token::Word("array") => { lexer.expect(Token::Paren('<'))?; - let base = self.parse_type_decl(lexer, type_arena)?; + let base = self.parse_type_decl(lexer, None, type_arena)?; let size = match lexer.next() { Token::Separator(',') => { let value = lexer.next_uint_literal()?; @@ -1087,7 +1096,10 @@ impl Parser { other => return Err(Error::Unexpected(other)), }; self.scopes.pop(); - Ok(Typifier::deduce_type_handle(inner, type_arena)) + Ok(type_arena.fetch_or_append(crate::Type { + name: self_name.map(|s| s.to_string()), + inner, + })) } fn parse_statement<'a>( @@ -1269,7 +1281,7 @@ impl Parser { let return_type = if lexer.skip(Token::Word("void")) { None } else { - Some(self.parse_type_decl(lexer, &mut module.types)?) + Some(self.parse_type_decl(lexer, None, &mut module.types)?) }; let fun_handle = module.functions.append(crate::Function { @@ -1302,6 +1314,7 @@ impl Parser { types: &mut module.types, constants: &mut module.constants, global_vars: &module.global_variables, + parameter_types: &fun.parameter_types, }, )?; // done @@ -1396,7 +1409,7 @@ impl Parser { Token::Word("type") => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; - let ty = self.parse_type_decl(lexer, &mut module.types)?; + let ty = self.parse_type_decl(lexer, Some(name), &mut module.types)?; self.lookup_type.insert(name.to_owned(), ty); lexer.expect(Token::Separator(';'))?; } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index e5c5a4006..7109751be 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -1,7 +1,4 @@ -use crate::{ - arena::{Arena, Handle}, - Type, TypeInner, VectorSize, -}; +use crate::arena::{Arena, Handle}; use thiserror::Error; @@ -29,29 +26,35 @@ impl Typifier { &mut self, expr_handle: Handle, expressions: &Arena, - types: &mut Arena, + arena: &mut Arena, constants: &Arena, global_vars: &Arena, local_vars: &Arena, functions: &Arena, + parameter_types: &[Handle], ) -> Result, ResolveError> { + #[derive(Debug)] + enum Resolution { + Handle(crate::Handle), + Value(crate::TypeInner), + } + if self.types.len() <= expr_handle.index() { for (eh, expr) in expressions.iter().skip(self.types.len()) { - let ty = match *expr { + let resolution = match *expr { crate::Expression::Access { base, .. } => { - match types[self.types[base.index()]].inner { - crate::TypeInner::Array { base, .. } => base, + match arena[self.types[base.index()]].inner { + crate::TypeInner::Array { base, .. } => Resolution::Handle(base), ref other => panic!("Can't access into {:?}", other), } } crate::Expression::AccessIndex { base, index } => { - match types[self.types[base.index()]].inner { + match arena[self.types[base.index()]].inner { crate::TypeInner::Vector { size, kind, width } => { if index >= size as u32 { return Err(ResolveError::InvalidAccessIndex); } - let inner = crate::TypeInner::Scalar { kind, width }; - Self::deduce_type_handle(inner, types) + Resolution::Value(crate::TypeInner::Scalar { kind, width }) } crate::TypeInner::Matrix { columns, @@ -62,89 +65,92 @@ impl Typifier { if index >= columns as u32 { return Err(ResolveError::InvalidAccessIndex); } - let inner = crate::TypeInner::Vector { + Resolution::Value(crate::TypeInner::Vector { size: rows, kind, width, - }; - Self::deduce_type_handle(inner, types) + }) } - crate::TypeInner::Array { base, .. } => base, + crate::TypeInner::Array { base, .. } => Resolution::Handle(base), crate::TypeInner::Struct { ref members } => { - members + let member = members .get(index as usize) - .ok_or(ResolveError::InvalidAccessIndex)? - .ty + .ok_or(ResolveError::InvalidAccessIndex)?; + Resolution::Handle(member.ty) } ref other => panic!("Can't access into {:?}", other), } } - crate::Expression::Constant(h) => constants[h].ty, - crate::Expression::Compose { ty, .. } => ty, - crate::Expression::FunctionParameter(_) => unimplemented!(), - crate::Expression::GlobalVariable(h) => global_vars[h].ty, - crate::Expression::LocalVariable(h) => local_vars[h].ty, + crate::Expression::Constant(h) => Resolution::Handle(constants[h].ty), + crate::Expression::Compose { ty, .. } => Resolution::Handle(ty), + crate::Expression::FunctionParameter(index) => { + Resolution::Handle(parameter_types[index as usize]) + } + crate::Expression::GlobalVariable(h) => Resolution::Handle(global_vars[h].ty), + crate::Expression::LocalVariable(h) => Resolution::Handle(local_vars[h].ty), crate::Expression::Load { .. } => unimplemented!(), crate::Expression::ImageSample { image, .. } | crate::Expression::ImageLoad { image, .. } => { let image = self.resolve( image, expressions, - types, + arena, constants, global_vars, local_vars, functions, + parameter_types, )?; - let inner = match types[image].inner { - TypeInner::Image { + Resolution::Value(match arena[image].inner { + crate::TypeInner::Image { kind, class: crate::ImageClass::Depth, .. - } => TypeInner::Scalar { kind, width: 4 }, - TypeInner::Image { kind, .. } => TypeInner::Vector { + } => crate::TypeInner::Scalar { kind, width: 4 }, + crate::TypeInner::Image { kind, .. } => crate::TypeInner::Vector { kind, width: 4, - size: VectorSize::Quad, + size: crate::VectorSize::Quad, }, _ => unreachable!(), - }; - - types.fetch_or_append(Type { name: None, inner }) + }) + } + crate::Expression::Unary { expr, .. } => { + Resolution::Handle(self.types[expr.index()]) } - crate::Expression::Unary { expr, .. } => self.types[expr.index()], crate::Expression::Binary { op, left, right } => match op { crate::BinaryOperator::Add | crate::BinaryOperator::Subtract | crate::BinaryOperator::Divide - | crate::BinaryOperator::Modulo => self.types[left.index()], + | crate::BinaryOperator::Modulo => { + Resolution::Handle(self.types[left.index()]) + } crate::BinaryOperator::Multiply => { let ty_left = self.types[left.index()]; let ty_right = self.types[right.index()]; if ty_left == ty_right { - ty_left - } else if let crate::TypeInner::Scalar { .. } = types[ty_right].inner { - ty_left - } else if let crate::TypeInner::Scalar { .. } = types[ty_left].inner { - ty_right + Resolution::Handle(ty_left) + } else if let crate::TypeInner::Scalar { .. } = arena[ty_right].inner { + Resolution::Handle(ty_left) + } else if let crate::TypeInner::Scalar { .. } = arena[ty_left].inner { + Resolution::Handle(ty_right) } else if let crate::TypeInner::Matrix { columns, kind, width, .. - } = types[ty_left].inner + } = arena[ty_left].inner { - let inner = crate::TypeInner::Vector { + Resolution::Value(crate::TypeInner::Vector { size: columns, kind, width, - }; - Self::deduce_type_handle(inner, types) + }) } else { panic!( "Incompatible arguments {:?} x {:?}", - types[ty_left], types[ty_right] + arena[ty_left], arena[ty_right] ); } } @@ -155,60 +161,61 @@ impl Typifier { | crate::BinaryOperator::Greater | crate::BinaryOperator::GreaterEqual | crate::BinaryOperator::LogicalAnd - | crate::BinaryOperator::LogicalOr => self.types[left.index()], + | crate::BinaryOperator::LogicalOr => { + Resolution::Handle(self.types[left.index()]) + } crate::BinaryOperator::And | crate::BinaryOperator::ExclusiveOr | crate::BinaryOperator::InclusiveOr | crate::BinaryOperator::ShiftLeftLogical | crate::BinaryOperator::ShiftRightLogical - | crate::BinaryOperator::ShiftRightArithmetic => self.types[left.index()], + | crate::BinaryOperator::ShiftRightArithmetic => { + Resolution::Handle(self.types[left.index()]) + } }, crate::Expression::Intrinsic { .. } => unimplemented!(), crate::Expression::Transpose(expr) => { let ty_handle = self.types[expr.index()]; - let inner = match types[ty_handle].inner { + match arena[ty_handle].inner { crate::TypeInner::Matrix { columns, rows, kind, width, - } => crate::TypeInner::Matrix { + } => Resolution::Value(crate::TypeInner::Matrix { columns: rows, rows: columns, kind, width, - }, + }), ref other => panic!("incompatible transpose of {:?}", other), - }; - types.fetch_or_append(Type { name: None, inner }) + } } crate::Expression::DotProduct(left_expr, _) => { let left_ty = self.types[left_expr.index()]; - let inner = match types[left_ty].inner { + match arena[left_ty].inner { crate::TypeInner::Vector { kind, size: _, width, - } => crate::TypeInner::Scalar { kind, width }, + } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), ref other => panic!("incompatible dot of {:?}", other), - }; - types.fetch_or_append(Type { name: None, inner }) + } } crate::Expression::CrossProduct(_, _) => unimplemented!(), crate::Expression::As(expr, kind) => { let ty_handle = self.types[expr.index()]; - let inner = match types[ty_handle].inner { + match arena[ty_handle].inner { crate::TypeInner::Scalar { kind: _, width } => { - crate::TypeInner::Scalar { kind, width } + Resolution::Value(crate::TypeInner::Scalar { kind, width }) } crate::TypeInner::Vector { kind: _, size, width, - } => crate::TypeInner::Vector { kind, size, width }, + } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }), ref other => panic!("incompatible as of {:?}", other), - }; - types.fetch_or_append(Type { name: None, inner }) + } } crate::Expression::Derivative { .. } => unimplemented!(), crate::Expression::Call { @@ -217,42 +224,40 @@ impl Typifier { } => match name.as_str() { "distance" | "length" | "dot" => { let ty_handle = self.types[arguments[0].index()]; - let inner = match types[ty_handle].inner { + match arena[ty_handle].inner { crate::TypeInner::Vector { kind, width, .. } => { - crate::TypeInner::Scalar { kind, width } + Resolution::Value(crate::TypeInner::Scalar { kind, width }) } ref other => panic!("Unexpected argument {:?}", other), - }; - Self::deduce_type_handle(inner, types) + } } "normalize" | "fclamp" | "max" | "reflect" | "pow" | "clamp" | "mix" => { - self.types[arguments[0].index()] + Resolution::Handle(self.types[arguments[0].index()]) } _ => return Err(ResolveError::FunctionNotDefined { name: name.clone() }), }, crate::Expression::Call { origin: crate::FunctionOrigin::Local(handle), arguments: _, - } => functions[handle] - .return_type - .ok_or(ResolveError::FunctionReturnsVoid)?, + } => { + let ty = functions[handle] + .return_type + .ok_or(ResolveError::FunctionReturnsVoid)?; + Resolution::Handle(ty) + } }; - log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, ty); - self.types.push(ty); + log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); + self.types.push(match resolution { + Resolution::Handle(h) => h, + Resolution::Value(inner) => arena + .fetch_if_or_append(crate::Type { name: None, inner }, |a, b| { + a.inner == b.inner + }), + }); } } Ok(self.types[expr_handle.index()]) } - - pub fn deduce_type_handle( - inner: crate::TypeInner, - arena: &mut Arena, - ) -> Handle { - if let Some((token, _)) = arena.iter().find(|(_, ty)| ty.inner == inner) { - return token; - } - arena.append(crate::Type { name: None, inner }) - } } #[derive(Clone, Debug, Error)] From dc442343d6d94af00bb13f39419614fdba63f6e3 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 28 Aug 2020 09:56:20 -0400 Subject: [PATCH 0177/2212] Make TypeInner to be non-clonable --- src/arena.rs | 8 + src/back/glsl.rs | 80 ++++---- src/back/mod.rs | 23 +++ src/back/msl.rs | 148 ++++++-------- src/front/wgsl/mod.rs | 30 ++- src/lib.rs | 3 +- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 454 +++++++++++++++++++++--------------------- 8 files changed, 380 insertions(+), 368 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 210133e1b..ea2adcdda 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -138,6 +138,14 @@ impl Arena { Handle::new(index) } + /// Fetch a handle to an existing type. + pub fn fetch_if bool>(&self, fun: F) -> Option> { + self.data + .iter() + .position(fun) + .map(|index| Handle::new(unsafe { Index::new_unchecked((index + 1) as u32) })) + } + /// Adds a value with a custom check for uniqueness: /// returns a handle pointing to /// an existing element if the check succeeds, or adds a new diff --git a/src/back/glsl.rs b/src/back/glsl.rs index caf75ae82..d0652adc7 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,3 +1,4 @@ +use super::{BorrowType, MaybeOwned}; use crate::{ Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageClass, Interpolation, @@ -599,26 +600,26 @@ fn write_expression<'a, 'b>( expr: &Expression, module: &'a Module, builder: &'b mut StatementBuilder<'a>, -) -> Result<(Cow<'a, str>, Cow<'a, TypeInner>), Error> { +) -> Result<(Cow<'a, str>, BorrowType<'a>), Error> { Ok(match *expr { Expression::Access { base, index } => { let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; - let inner = match *ty.as_ref() { + let inner = match *ty.borrow() { TypeInner::Vector { kind, width, .. } => { - Cow::Owned(TypeInner::Scalar { kind, width }) + MaybeOwned::Owned(TypeInner::Scalar { kind, width }) } TypeInner::Matrix { kind, width, columns, .. - } => Cow::Owned(TypeInner::Vector { + } => MaybeOwned::Owned(TypeInner::Vector { kind, width, size: columns, }), - TypeInner::Array { base, .. } => Cow::Borrowed(&module.types[base].inner), + TypeInner::Array { base, .. } => module.borrow_type(base), _ => return Err(Error::Custom(format!("Cannot dynamically index {:?}", ty))), }; @@ -634,10 +635,10 @@ fn write_expression<'a, 'b>( Expression::AccessIndex { base, index } => { let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; - match *ty.as_ref() { + match *ty.borrow() { TypeInner::Vector { kind, width, .. } => ( Cow::Owned(format!("{}[{}]", base_expr, index)), - Cow::Owned(TypeInner::Scalar { kind, width }), + MaybeOwned::Owned(TypeInner::Scalar { kind, width }), ), TypeInner::Matrix { kind, @@ -646,7 +647,7 @@ fn write_expression<'a, 'b>( .. } => ( Cow::Owned(format!("{}[{}]", base_expr, index)), - Cow::Owned(TypeInner::Vector { + MaybeOwned::Owned(TypeInner::Vector { kind, width, size: columns, @@ -654,7 +655,7 @@ fn write_expression<'a, 'b>( ), TypeInner::Array { base, .. } => ( Cow::Owned(format!("{}[{}]", base_expr, index)), - Cow::Borrowed(&module.types[base].inner), + module.borrow_type(base), ), TypeInner::Struct { ref members } => ( if let MemberOrigin::BuiltIn(builtin) = members[index as usize].origin { @@ -670,7 +671,7 @@ fn write_expression<'a, 'b>( .unwrap_or(&format!("_{}", index)) )) }, - Cow::Borrowed(&module.types[members[index as usize].ty].inner), + module.borrow_type(members[index as usize].ty), ), _ => return Err(Error::Custom(format!("Cannot index {:?}", ty))), } @@ -682,7 +683,7 @@ fn write_expression<'a, 'b>( builder, builder.features, )?), - Cow::Borrowed(&module.types[module.constants[constant].ty].inner), + module.borrow_type(module.constants[constant].ty), ), Expression::Compose { ty, ref components } => { let constructor = match module.types[ty].inner { @@ -756,21 +757,21 @@ fn write_expression<'a, 'b>( .collect::, _>>()? .join(","), )), - Cow::Borrowed(&module.types[ty].inner), + module.borrow_type(ty), ) } Expression::FunctionParameter(pos) => { let (arg, ty) = builder.args.get(&pos).unwrap(); - (Cow::Borrowed(arg), Cow::Borrowed(&module.types[*ty].inner)) + (Cow::Borrowed(arg), module.borrow_type(*ty)) } Expression::GlobalVariable(handle) => ( Cow::Borrowed(builder.globals.get(&handle).unwrap()), - Cow::Borrowed(&module.types[module.global_variables[handle].ty].inner), + module.borrow_type(module.global_variables[handle].ty), ), Expression::LocalVariable(handle) => ( Cow::Borrowed(builder.locals_lookup.get(&handle).unwrap()), - Cow::Borrowed(&module.types[builder.locals[handle].ty].inner), + module.borrow_type(builder.locals[handle].ty), ), Expression::Load { pointer } => { write_expression(&builder.expressions[pointer], module, builder)? @@ -789,7 +790,7 @@ fn write_expression<'a, 'b>( let (coordinate_expr, coordinate_ty) = write_expression(&builder.expressions[coordinate], module, builder)?; - let (kind, dim, arrayed, class) = match *image_ty.as_ref() { + let (kind, dim, arrayed, class) = match *image_ty.borrow() { TypeInner::Image { kind, dim, @@ -803,8 +804,8 @@ fn write_expression<'a, 'b>( crate::ImageClass::Multisampled => true, _ => false, }; - let shadow = match sampler_ty.as_ref() { - TypeInner::Sampler { comparison } => *comparison, + let shadow = match *sampler_ty.borrow() { + TypeInner::Sampler { comparison } => comparison, _ => { return Err(Error::Custom(format!( "Cannot have a sampler of {:?}", @@ -812,8 +813,8 @@ fn write_expression<'a, 'b>( ))) } }; - let size = match coordinate_ty.as_ref() { - TypeInner::Vector { size, .. } => *size, + let size = match *coordinate_ty.borrow() { + TypeInner::Vector { size, .. } => size, _ => { return Err(Error::Custom(format!( "Cannot sample with coordinates of type {:?}", @@ -874,9 +875,9 @@ fn write_expression<'a, 'b>( let width = 4; let ty = if shadow { - Cow::Owned(TypeInner::Scalar { kind, width }) + MaybeOwned::Owned(TypeInner::Scalar { kind, width }) } else { - Cow::Owned(TypeInner::Vector { kind, width, size }) + MaybeOwned::Owned(TypeInner::Vector { kind, width, size }) }; (Cow::Owned(expr), ty) @@ -891,7 +892,7 @@ fn write_expression<'a, 'b>( let (coordinate_expr, coordinate_ty) = write_expression(&builder.expressions[coordinate], module, builder)?; - let (kind, dim, arrayed, class) = match *image_ty.as_ref() { + let (kind, dim, arrayed, class) = match *image_ty.borrow() { TypeInner::Image { kind, dim, @@ -901,8 +902,8 @@ fn write_expression<'a, 'b>( _ => return Err(Error::Custom(format!("Cannot load {:?}", image_ty))), }; - let size = match coordinate_ty.as_ref() { - TypeInner::Vector { size, .. } => *size, + let size = match *coordinate_ty.borrow() { + TypeInner::Vector { size, .. } => size, _ => { return Err(Error::Custom(format!( "Cannot sample with coordinates of type {:?}", @@ -957,7 +958,7 @@ fn write_expression<'a, 'b>( let width = 4; ( Cow::Owned(expr), - Cow::Owned(TypeInner::Vector { kind, width, size }), + MaybeOwned::Owned(TypeInner::Vector { kind, width, size }), ) } Expression::Unary { op, expr } => { @@ -968,7 +969,7 @@ fn write_expression<'a, 'b>( "({} {})", match op { UnaryOperator::Negate => "-", - UnaryOperator::Not => match ty.as_ref() { + UnaryOperator::Not => match ty.borrow() { TypeInner::Scalar { kind: ScalarKind::Sint, .. @@ -1035,7 +1036,7 @@ fn write_expression<'a, 'b>( | BinaryOperator::ShiftLeftLogical | BinaryOperator::ShiftRightLogical | BinaryOperator::ShiftRightArithmetic => { - match (left_ty.as_ref(), right_ty.as_ref()) { + match (left_ty.borrow(), right_ty.borrow()) { (TypeInner::Scalar { .. }, TypeInner::Scalar { .. }) => left_ty, (TypeInner::Scalar { .. }, TypeInner::Vector { .. }) => right_ty, (TypeInner::Scalar { .. }, TypeInner::Matrix { .. }) => right_ty, @@ -1058,7 +1059,7 @@ fn write_expression<'a, 'b>( | BinaryOperator::Less | BinaryOperator::LessEqual | BinaryOperator::Greater - | BinaryOperator::GreaterEqual => Cow::Owned(TypeInner::Scalar { + | BinaryOperator::GreaterEqual => MaybeOwned::Owned(TypeInner::Scalar { kind: ScalarKind::Bool, width: 1, }), @@ -1092,13 +1093,13 @@ fn write_expression<'a, 'b>( let (matrix_expr, matrix_ty) = write_expression(&builder.expressions[matrix], module, builder)?; - let ty = match *matrix_ty.as_ref() { + let ty = match *matrix_ty.borrow() { TypeInner::Matrix { columns, rows, kind, width, - } => Cow::Owned(TypeInner::Matrix { + } => MaybeOwned::Owned(TypeInner::Matrix { columns: rows, rows: columns, kind, @@ -1119,9 +1120,9 @@ fn write_expression<'a, 'b>( write_expression(&builder.expressions[left], module, builder)?; let (right_expr, _) = write_expression(&builder.expressions[right], module, builder)?; - let ty = match *left_ty.as_ref() { + let ty = match *left_ty.borrow() { TypeInner::Vector { kind, width, .. } => { - Cow::Owned(TypeInner::Scalar { kind, width }) + MaybeOwned::Owned(TypeInner::Scalar { kind, width }) } _ => { return Err(Error::Custom(format!( @@ -1146,15 +1147,18 @@ fn write_expression<'a, 'b>( Expression::As(value, kind) => { let (value_expr, value_ty) = write_expression(&builder.expressions[value], module, builder)?; - let (width, out_ty) = match *value_ty.as_ref() { + let (width, out_ty) = match *value_ty.borrow() { TypeInner::Scalar { width, kind: _ } => { - (width, Cow::Owned(TypeInner::Scalar { kind, width })) + (width, MaybeOwned::Owned(TypeInner::Scalar { kind, width })) } TypeInner::Vector { width, kind: _, size, - } => (width, Cow::Owned(TypeInner::Vector { kind, width, size })), + } => ( + width, + MaybeOwned::Owned(TypeInner::Vector { kind, width, size }), + ), _ => return Err(Error::Custom(format!("Cannot cast {}", value_expr))), }; let ty_expr = map_scalar(kind, width, builder.features)?; @@ -1184,8 +1188,8 @@ fn write_expression<'a, 'b>( let ty = match *origin { FunctionOrigin::Local(function) => module.functions[function] .return_type - .map(|ty| Cow::Borrowed(&module.types[ty].inner)) - .unwrap_or(Cow::Owned( + .map(|ty| module.borrow_type(ty)) + .unwrap_or(MaybeOwned::Owned( TypeInner::Sampler { comparison: false }, /*Dummy type*/ )), FunctionOrigin::External(_) => { diff --git a/src/back/mod.rs b/src/back/mod.rs index fc601cd9f..7aceda745 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -5,3 +5,26 @@ pub mod glsl; pub mod msl; #[cfg(feature = "spirv-out")] pub mod spv; + +#[derive(Debug)] +pub enum MaybeOwned<'a, T: 'a> { + Borrowed(&'a T), + Owned(T), +} + +impl MaybeOwned<'_, T> { + fn borrow(&self) -> &T { + match *self { + MaybeOwned::Borrowed(inner) => inner, + MaybeOwned::Owned(ref inner) => inner, + } + } +} + +pub type BorrowType<'a> = MaybeOwned<'a, crate::TypeInner>; + +impl crate::Module { + fn borrow_type(&self, handle: crate::Handle) -> BorrowType { + MaybeOwned::Borrowed(&self.types[handle].inner) + } +} diff --git a/src/back/msl.rs b/src/back/msl.rs index 3950b6960..eb3464f96 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -14,9 +14,9 @@ the output struct. If there is a structure in the outputs, and it contains any b we move them up to the root output structure that we define ourselves. !*/ -use std::fmt::{Display, Error as FmtError, Formatter, Write}; - +use super::{BorrowType, MaybeOwned}; use crate::{arena::Handle, FastHashMap}; +use std::fmt::{Display, Error as FmtError, Formatter, Write}; #[derive(Clone, Debug, Default, PartialEq)] pub struct BindTarget { @@ -57,33 +57,33 @@ impl Display for Level { // Note: some of these should be removed in favor of proper IR validation. #[derive(Debug)] -pub enum Error { +pub enum Error<'a> { Format(FmtError), UnexpectedLocation, - MixedExecutionModels(crate::Handle), - MissingBinding(crate::Handle), + MixedExecutionModels(Handle), + MissingBinding(Handle), MissingBindTarget(BindSource), InvalidImageAccess(crate::StorageAccess), - MutabilityViolation(crate::Handle), + MutabilityViolation(Handle), BadName(String), - UnexpectedGlobalType(crate::Handle), + UnexpectedGlobalType(Handle), UnimplementedBindTarget(BindTarget), - UnexpectedIndexing(crate::TypeInner), - UnsupportedCompose(crate::Handle), - UnexpectedLoadPointer(crate::TypeInner), + UnexpectedIndexing(BorrowType<'a>), + UnsupportedCompose(Handle), + UnexpectedLoadPointer(BorrowType<'a>), UnsupportedBinaryOp(crate::BinaryOperator), - UnableToInferBinaryOpOutput(crate::TypeInner, crate::BinaryOperator, crate::TypeInner), - UnexpectedImageType(crate::TypeInner), + UnableToInferBinaryOpOutput(BorrowType<'a>, crate::BinaryOperator, BorrowType<'a>), + UnexpectedImageType(BorrowType<'a>), UnexpectedSampleLevel(crate::SampleLevel), - UnexpectedDistanceArgument(crate::TypeInner), + UnexpectedDistanceArgument(BorrowType<'a>), UnsupportedCall(String), UnsupportedExpression(crate::Expression), - UnableToReturnValue(crate::Handle), + UnableToReturnValue(Handle), UnsupportedStatement(crate::Statement), AccessIndexExceedsStaticLength(u32, u32), } -impl From for Error { +impl From for Error<'_> { fn from(e: FmtError) -> Self { Error::Format(e) } @@ -137,25 +137,25 @@ trait Indexed { fn id(&self) -> usize; } -impl Indexed for crate::Handle { +impl Indexed for Handle { const CLASS: &'static str = "Type"; fn id(&self) -> usize { self.index() } } -impl Indexed for crate::Handle { +impl Indexed for Handle { const CLASS: &'static str = "global"; fn id(&self) -> usize { self.index() } } -impl Indexed for crate::Handle { +impl Indexed for Handle { const CLASS: &'static str = "local"; fn id(&self) -> usize { self.index() } } -impl Indexed for crate::Handle { +impl Indexed for Handle { const CLASS: &'static str = "function"; fn id(&self) -> usize { self.index() @@ -176,7 +176,7 @@ impl Indexed for ParameterIndex { self.0 } } -struct InputStructIndex(crate::Handle); +struct InputStructIndex(Handle); impl Indexed for InputStructIndex { const CLASS: &'static str = "Input"; const PREFIX: bool = true; @@ -184,7 +184,7 @@ impl Indexed for InputStructIndex { self.0.index() } } -struct OutputStructIndex(crate::Handle); +struct OutputStructIndex(Handle); impl Indexed for OutputStructIndex { const CLASS: &'static str = "Output"; const PREFIX: bool = true; @@ -252,12 +252,12 @@ impl AsName for Option { struct TypedGlobalVariable<'a> { module: &'a crate::Module, - handle: crate::Handle, + handle: Handle, usage: crate::GlobalUse, } impl<'a> TypedGlobalVariable<'a> { - fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { + fn try_fmt(&self, formatter: &mut W) -> Result<(), Error<'a>> { let var = &self.module.global_variables[self.handle]; let name = var.name.or_index(self.handle); let (space_qualifier, reference) = match var.class { @@ -283,7 +283,7 @@ impl<'a> TypedGlobalVariable<'a> { } impl ResolvedBinding { - fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { + fn try_fmt(&self, formatter: &mut W) -> Result<(), Error<'static>> { match *self { ResolvedBinding::BuiltIn(built_in) => { use crate::BuiltIn as Bi; @@ -332,7 +332,7 @@ impl ResolvedBinding { &self, formatter: &mut W, terminator: &str, - ) -> Result<(), Error> { + ) -> Result<(), Error<'static>> { formatter.write_str(" [[")?; self.try_fmt(formatter)?; formatter.write_str("]]")?; @@ -374,39 +374,19 @@ fn separate(is_last: bool) -> &'static str { } } -#[derive(Debug)] -enum MaybeOwned<'a, T: 'a> { - Borrowed(&'a T), - Owned(T), -} - -impl MaybeOwned<'_, T> { - fn borrow(&self) -> &T { - match *self { - MaybeOwned::Borrowed(inner) => inner, - MaybeOwned::Owned(ref inner) => inner, - } - } -} - -impl crate::Module { - fn borrow_type(&self, handle: Handle) -> MaybeOwned { - MaybeOwned::Borrowed(&self.types[handle].inner) - } -} - impl Writer { - fn put_expression<'a>( - &mut self, + fn put_expression<'w, 'a: 'w>( + &'w mut self, expr_handle: Handle, function: &crate::Function, module: &'a crate::Module, - ) -> Result, Error> { + ) -> Result, Error<'a>> { let expression = &function.expressions[expr_handle]; log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { crate::Expression::Access { base, index } => { - match *self.put_expression(base, function, module)?.borrow() { + let ty_base = self.put_expression(base, function, module)?; + match *ty_base.borrow() { crate::TypeInner::Array { base, .. } => { //TODO: add size check self.out.write_str("[")?; @@ -414,11 +394,12 @@ impl Writer { self.out.write_str("]")?; Ok(module.borrow_type(base)) } - ref other => Err(Error::UnexpectedIndexing(other.clone())), + _ => Err(Error::UnexpectedIndexing(ty_base)), } } crate::Expression::AccessIndex { base, index } => { - match *self.put_expression(base, function, module)?.borrow() { + let ty_base = self.put_expression(base, function, module)?; + match *ty_base.borrow() { crate::TypeInner::Struct { ref members } => { let member = &members[index as usize]; let name = member.name.or_index(MemberIndex(index as usize)); @@ -450,7 +431,7 @@ impl Writer { write!(self.out, "[{}]", index)?; Ok(module.borrow_type(base)) } - ref other => Err(Error::UnexpectedIndexing(other.clone())), + _ => Err(Error::UnexpectedIndexing(ty_base)), } } crate::Expression::Constant(handle) => self.put_constant(handle, module), @@ -511,9 +492,10 @@ impl Writer { } crate::Expression::Load { pointer } => { //write!(self.out, "*")?; - match *self.put_expression(pointer, function, module)?.borrow() { + let ty_ptr = self.put_expression(pointer, function, module)?; + match *ty_ptr.borrow() { crate::TypeInner::Pointer { base, .. } => Ok(module.borrow_type(base)), - ref other => Err(Error::UnexpectedLoadPointer(other.clone())), + _ => Err(Error::UnexpectedLoadPointer(ty_ptr)), } } crate::Expression::Unary { op, expr } => { @@ -564,12 +546,8 @@ impl Writer { &crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Vector { .. }, ) => MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), - (other_left, other_right) => { - return Err(Error::UnableToInferBinaryOpOutput( - other_left.clone(), - op, - other_right.clone(), - )) + (_, _) => { + return Err(Error::UnableToInferBinaryOpOutput(ty_left, op, ty_right)) } } } else { @@ -614,7 +592,7 @@ impl Writer { width: 4, })) } - ref other => Err(Error::UnexpectedImageType(other.clone())), + _ => Err(Error::UnexpectedImageType(ty_image)), } } crate::Expression::ImageSample { @@ -667,7 +645,7 @@ impl Writer { width: 4, })) } - ref other => Err(Error::UnexpectedImageType(other.clone())), + _ => Err(Error::UnexpectedImageType(ty_image)), } } crate::Expression::Call { @@ -700,14 +678,12 @@ impl Writer { } "distance" => { write!(self.out, "distance(")?; - let result = match *self - .put_expression(arguments[0], function, module)? - .borrow() - { + let ty_arg = self.put_expression(arguments[0], function, module)?; + let result = match *ty_arg.borrow() { crate::TypeInner::Vector { kind, width, .. } => { crate::TypeInner::Scalar { kind, width } } - ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())), + _ => return Err(Error::UnexpectedDistanceArgument(ty_arg)), }; write!(self.out, ", ")?; self.put_expression(arguments[1], function, module)?; @@ -716,14 +692,12 @@ impl Writer { } "length" => { write!(self.out, "length(")?; - let result = match *self - .put_expression(arguments[0], function, module)? - .borrow() - { + let ty_arg = self.put_expression(arguments[0], function, module)?; + let result = match *ty_arg.borrow() { crate::TypeInner::Vector { kind, width, .. } => { crate::TypeInner::Scalar { kind, width } } - ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())), + _ => return Err(Error::UnexpectedDistanceArgument(ty_arg)), }; write!(self.out, ")")?; Ok(MaybeOwned::Owned(result)) @@ -735,11 +709,11 @@ impl Writer { } } - fn put_constant<'a>( - &mut self, + fn put_constant<'w, 'a: 'w>( + &'w mut self, handle: Handle, module: &'a crate::Module, - ) -> Result, Error> { + ) -> Result, Error<'a>> { let constant = &module.constants[handle]; let ty = &module.types[constant.ty]; @@ -775,14 +749,14 @@ impl Writer { Ok(MaybeOwned::Borrowed(&ty.inner)) } - fn put_statement<'a>( - &mut self, + fn put_statement<'w, 'a: 'w>( + &'w mut self, level: Level, statement: &crate::Statement, function: &crate::Function, has_output: bool, module: &'a crate::Module, - ) -> Result<(), Error> { + ) -> Result<(), Error<'a>> { log::trace!("statement[{}] {:?}", level.0, statement); match *statement { crate::Statement::Empty => {} @@ -851,7 +825,11 @@ impl Writer { Ok(()) } - pub fn write(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { + pub fn write<'w, 'a: 'w>( + &'w mut self, + module: &'a crate::Module, + options: Options, + ) -> Result<(), Error<'a>> { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; writeln!(self.out, "using namespace metal;")?; @@ -865,7 +843,7 @@ impl Writer { Ok(()) } - fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { + fn write_type_defs<'a>(&mut self, module: &'a crate::Module) -> Result<(), Error<'a>> { for (handle, ty) in module.types.iter() { let name = ty.name.or_index(handle); match ty.inner { @@ -996,7 +974,11 @@ impl Writer { Ok(()) } - fn write_functions(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { + fn write_functions<'w, 'a: 'w>( + &'w mut self, + module: &'a crate::Module, + options: Options, + ) -> Result<(), Error<'a>> { for (fun_handle, fun) in module.functions.iter() { let fun_name = fun.name.or_index(fun_handle); // find the entry point(s) and inputs/outputs @@ -1236,7 +1218,7 @@ impl Writer { } } -pub fn write_string(module: &crate::Module, options: Options) -> Result { +pub fn write_string<'a>(module: &'a crate::Module, options: Options) -> Result> { let mut w = Writer { out: String::new() }; w.write(module, options)?; Ok(w.out) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 4e34671b1..ec89afe88 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -38,8 +38,8 @@ pub enum Token<'a> { pub enum Error<'a> { #[error("unexpected token: {0:?}")] Unexpected(Token<'a>), - #[error(transparent)] - UnexpectedConstantType(#[from] crate::proc::UnexpectedConstantTypeError), + #[error("constant {0:?} doesn't match its type {1:?}")] + UnexpectedConstantType(crate::ConstantInner, Handle), #[error("unable to parse `{0}` as integer: {1}")] BadInteger(&'a str, std::num::ParseIntError), #[error("unable to parse `{1}` as float: {1}")] @@ -69,7 +69,7 @@ pub enum Error<'a> { #[error("array stride must not be 0")] ZeroStride, #[error("not a composite type: {0:?}")] - NotCompositeType(crate::TypeInner), + NotCompositeType(Handle), #[error("function redefinition: `{0}`")] FunctionRedefinition(&'a str), //MutabilityViolation(&'a str), @@ -287,20 +287,16 @@ impl Parser { ty: Handle, index: usize, ) -> Result, Error<'static>> { - let ty = match type_arena[ty].inner { + match type_arena[ty].inner { crate::TypeInner::Vector { kind, width, .. } | crate::TypeInner::Matrix { kind, width, .. } => { - type_arena.fetch_or_append(crate::Type { - name: None, - inner: crate::TypeInner::Scalar { kind, width }, - }) + let inner = crate::TypeInner::Scalar { kind, width }; + Ok(type_arena.fetch_or_append(crate::Type { name: None, inner })) } - crate::TypeInner::Array { base, .. } => base, - crate::TypeInner::Struct { ref members } => members[index].ty, - ref inner => return Err(Error::NotCompositeType(inner.clone())), - }; - - Ok(ty) + crate::TypeInner::Array { base, .. } => Ok(base), + crate::TypeInner::Struct { ref members } => Ok(members[index].ty), + _ => Err(Error::NotCompositeType(ty)), + } } fn get_constant_inner( @@ -389,12 +385,12 @@ impl Parser { if !components.is_empty() { lexer.expect(Token::Separator(','))?; } - let inner = self.parse_const_expression(lexer, type_arena, const_arena)?; let ty = Self::deconstruct_composite_type( type_arena, composite_ty, components.len(), )?; + let inner = self.parse_const_expression(lexer, type_arena, const_arena)?; components.push(const_arena.fetch_or_append(crate::Constant { name: None, specialization: None, @@ -1419,7 +1415,9 @@ impl Parser { let inner = self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; lexer.expect(Token::Separator(';'))?; - crate::proc::check_constant_types(&inner, &module.types[ty].inner)?; + if !crate::proc::check_constant_type(&inner, &module.types[ty].inner) { + return Err(Error::UnexpectedConstantType(inner, ty)); + } let const_handle = module.constants.append(crate::Constant { name: Some(name.to_owned()), specialization: None, diff --git a/src/lib.rs b/src/lib.rs index a7c68a417..3e25f8885 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -294,8 +294,7 @@ pub struct Type { } /// Enum with additional information, depending on the kind of type. -// Clone is used only for error reporting and is not intended for end users -#[derive(Clone, Debug, PartialEq)] +#[derive(Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum TypeInner { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 6269e0183..93178ba15 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -4,5 +4,5 @@ mod interface; mod typifier; mod validator; -pub use typifier::{check_constant_types, ResolveError, Typifier, UnexpectedConstantTypeError}; +pub use typifier::{check_constant_type, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 7109751be..7ae2de663 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -14,6 +14,14 @@ pub enum ResolveError { FunctionNotDefined { name: String }, #[error("Function without return type")] FunctionReturnsVoid, + #[error("Type is not found in the given immutable arena")] + TypeNotFound, +} + +#[derive(Debug)] +enum Resolution { + Handle(crate::Handle), + Value(crate::TypeInner), } impl Typifier { @@ -21,6 +29,208 @@ impl Typifier { Typifier { types: Vec::new() } } + #[allow(clippy::too_many_arguments)] + fn resolve_impl( + &self, + expr: &crate::Expression, + arena: &Arena, + constants: &Arena, + global_vars: &Arena, + local_vars: &Arena, + functions: &Arena, + parameter_types: &[Handle], + ) -> Result { + Ok(match *expr { + crate::Expression::Access { base, .. } => match arena[self.types[base.index()]].inner { + crate::TypeInner::Array { base, .. } => Resolution::Handle(base), + ref other => panic!("Can't access into {:?}", other), + }, + crate::Expression::AccessIndex { base, index } => { + match arena[self.types[base.index()]].inner { + crate::TypeInner::Vector { size, kind, width } => { + if index >= size as u32 { + return Err(ResolveError::InvalidAccessIndex); + } + Resolution::Value(crate::TypeInner::Scalar { kind, width }) + } + crate::TypeInner::Matrix { + columns, + rows, + kind, + width, + } => { + if index >= columns as u32 { + return Err(ResolveError::InvalidAccessIndex); + } + Resolution::Value(crate::TypeInner::Vector { + size: rows, + kind, + width, + }) + } + crate::TypeInner::Array { base, .. } => Resolution::Handle(base), + crate::TypeInner::Struct { ref members } => { + let member = members + .get(index as usize) + .ok_or(ResolveError::InvalidAccessIndex)?; + Resolution::Handle(member.ty) + } + ref other => panic!("Can't access into {:?}", other), + } + } + crate::Expression::Constant(h) => Resolution::Handle(constants[h].ty), + crate::Expression::Compose { ty, .. } => Resolution::Handle(ty), + crate::Expression::FunctionParameter(index) => { + Resolution::Handle(parameter_types[index as usize]) + } + crate::Expression::GlobalVariable(h) => Resolution::Handle(global_vars[h].ty), + crate::Expression::LocalVariable(h) => Resolution::Handle(local_vars[h].ty), + crate::Expression::Load { .. } => unimplemented!(), + crate::Expression::ImageSample { image, .. } + | crate::Expression::ImageLoad { image, .. } => { + let image_ty = self.types[image.index()]; + match arena[image_ty].inner { + crate::TypeInner::Image { + kind, + class: crate::ImageClass::Depth, + .. + } => Resolution::Value(crate::TypeInner::Scalar { kind, width: 4 }), + crate::TypeInner::Image { kind, .. } => { + Resolution::Value(crate::TypeInner::Vector { + kind, + width: 4, + size: crate::VectorSize::Quad, + }) + } + _ => unreachable!(), + } + } + crate::Expression::Unary { expr, .. } => Resolution::Handle(self.types[expr.index()]), + crate::Expression::Binary { op, left, right } => match op { + crate::BinaryOperator::Add + | crate::BinaryOperator::Subtract + | crate::BinaryOperator::Divide + | crate::BinaryOperator::Modulo => Resolution::Handle(self.types[left.index()]), + crate::BinaryOperator::Multiply => { + let ty_left = self.types[left.index()]; + let ty_right = self.types[right.index()]; + if ty_left == ty_right { + Resolution::Handle(ty_left) + } else if let crate::TypeInner::Scalar { .. } = arena[ty_right].inner { + Resolution::Handle(ty_left) + } else if let crate::TypeInner::Scalar { .. } = arena[ty_left].inner { + Resolution::Handle(ty_right) + } else if let crate::TypeInner::Matrix { + columns, + kind, + width, + .. + } = arena[ty_left].inner + { + Resolution::Value(crate::TypeInner::Vector { + size: columns, + kind, + width, + }) + } else { + panic!( + "Incompatible arguments {:?} x {:?}", + arena[ty_left], arena[ty_right] + ); + } + } + crate::BinaryOperator::Equal + | crate::BinaryOperator::NotEqual + | crate::BinaryOperator::Less + | crate::BinaryOperator::LessEqual + | crate::BinaryOperator::Greater + | crate::BinaryOperator::GreaterEqual + | crate::BinaryOperator::LogicalAnd + | crate::BinaryOperator::LogicalOr => Resolution::Handle(self.types[left.index()]), + crate::BinaryOperator::And + | crate::BinaryOperator::ExclusiveOr + | crate::BinaryOperator::InclusiveOr + | crate::BinaryOperator::ShiftLeftLogical + | crate::BinaryOperator::ShiftRightLogical + | crate::BinaryOperator::ShiftRightArithmetic => { + Resolution::Handle(self.types[left.index()]) + } + }, + crate::Expression::Intrinsic { .. } => unimplemented!(), + crate::Expression::Transpose(expr) => { + let ty_handle = self.types[expr.index()]; + match arena[ty_handle].inner { + crate::TypeInner::Matrix { + columns, + rows, + kind, + width, + } => Resolution::Value(crate::TypeInner::Matrix { + columns: rows, + rows: columns, + kind, + width, + }), + ref other => panic!("incompatible transpose of {:?}", other), + } + } + crate::Expression::DotProduct(left_expr, _) => { + let left_ty = self.types[left_expr.index()]; + match arena[left_ty].inner { + crate::TypeInner::Vector { + kind, + size: _, + width, + } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), + ref other => panic!("incompatible dot of {:?}", other), + } + } + crate::Expression::CrossProduct(_, _) => unimplemented!(), + crate::Expression::As(expr, kind) => { + let ty_handle = self.types[expr.index()]; + match arena[ty_handle].inner { + crate::TypeInner::Scalar { kind: _, width } => { + Resolution::Value(crate::TypeInner::Scalar { kind, width }) + } + crate::TypeInner::Vector { + kind: _, + size, + width, + } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }), + ref other => panic!("incompatible as of {:?}", other), + } + } + crate::Expression::Derivative { .. } => unimplemented!(), + crate::Expression::Call { + origin: crate::FunctionOrigin::External(ref name), + ref arguments, + } => match name.as_str() { + "distance" | "length" | "dot" => { + let ty_handle = self.types[arguments[0].index()]; + match arena[ty_handle].inner { + crate::TypeInner::Vector { kind, width, .. } => { + Resolution::Value(crate::TypeInner::Scalar { kind, width }) + } + ref other => panic!("Unexpected argument {:?}", other), + } + } + "normalize" | "fclamp" | "max" | "reflect" | "pow" | "clamp" | "mix" => { + Resolution::Handle(self.types[arguments[0].index()]) + } + _ => return Err(ResolveError::FunctionNotDefined { name: name.clone() }), + }, + crate::Expression::Call { + origin: crate::FunctionOrigin::Local(handle), + arguments: _, + } => { + let ty = functions[handle] + .return_type + .ok_or(ResolveError::FunctionReturnsVoid)?; + Resolution::Handle(ty) + } + }) + } + #[allow(clippy::too_many_arguments)] pub fn resolve( &mut self, @@ -33,219 +243,17 @@ impl Typifier { functions: &Arena, parameter_types: &[Handle], ) -> Result, ResolveError> { - #[derive(Debug)] - enum Resolution { - Handle(crate::Handle), - Value(crate::TypeInner), - } - if self.types.len() <= expr_handle.index() { for (eh, expr) in expressions.iter().skip(self.types.len()) { - let resolution = match *expr { - crate::Expression::Access { base, .. } => { - match arena[self.types[base.index()]].inner { - crate::TypeInner::Array { base, .. } => Resolution::Handle(base), - ref other => panic!("Can't access into {:?}", other), - } - } - crate::Expression::AccessIndex { base, index } => { - match arena[self.types[base.index()]].inner { - crate::TypeInner::Vector { size, kind, width } => { - if index >= size as u32 { - return Err(ResolveError::InvalidAccessIndex); - } - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - crate::TypeInner::Matrix { - columns, - rows, - kind, - width, - } => { - if index >= columns as u32 { - return Err(ResolveError::InvalidAccessIndex); - } - Resolution::Value(crate::TypeInner::Vector { - size: rows, - kind, - width, - }) - } - crate::TypeInner::Array { base, .. } => Resolution::Handle(base), - crate::TypeInner::Struct { ref members } => { - let member = members - .get(index as usize) - .ok_or(ResolveError::InvalidAccessIndex)?; - Resolution::Handle(member.ty) - } - ref other => panic!("Can't access into {:?}", other), - } - } - crate::Expression::Constant(h) => Resolution::Handle(constants[h].ty), - crate::Expression::Compose { ty, .. } => Resolution::Handle(ty), - crate::Expression::FunctionParameter(index) => { - Resolution::Handle(parameter_types[index as usize]) - } - crate::Expression::GlobalVariable(h) => Resolution::Handle(global_vars[h].ty), - crate::Expression::LocalVariable(h) => Resolution::Handle(local_vars[h].ty), - crate::Expression::Load { .. } => unimplemented!(), - crate::Expression::ImageSample { image, .. } - | crate::Expression::ImageLoad { image, .. } => { - let image = self.resolve( - image, - expressions, - arena, - constants, - global_vars, - local_vars, - functions, - parameter_types, - )?; - - Resolution::Value(match arena[image].inner { - crate::TypeInner::Image { - kind, - class: crate::ImageClass::Depth, - .. - } => crate::TypeInner::Scalar { kind, width: 4 }, - crate::TypeInner::Image { kind, .. } => crate::TypeInner::Vector { - kind, - width: 4, - size: crate::VectorSize::Quad, - }, - _ => unreachable!(), - }) - } - crate::Expression::Unary { expr, .. } => { - Resolution::Handle(self.types[expr.index()]) - } - crate::Expression::Binary { op, left, right } => match op { - crate::BinaryOperator::Add - | crate::BinaryOperator::Subtract - | crate::BinaryOperator::Divide - | crate::BinaryOperator::Modulo => { - Resolution::Handle(self.types[left.index()]) - } - crate::BinaryOperator::Multiply => { - let ty_left = self.types[left.index()]; - let ty_right = self.types[right.index()]; - if ty_left == ty_right { - Resolution::Handle(ty_left) - } else if let crate::TypeInner::Scalar { .. } = arena[ty_right].inner { - Resolution::Handle(ty_left) - } else if let crate::TypeInner::Scalar { .. } = arena[ty_left].inner { - Resolution::Handle(ty_right) - } else if let crate::TypeInner::Matrix { - columns, - kind, - width, - .. - } = arena[ty_left].inner - { - Resolution::Value(crate::TypeInner::Vector { - size: columns, - kind, - width, - }) - } else { - panic!( - "Incompatible arguments {:?} x {:?}", - arena[ty_left], arena[ty_right] - ); - } - } - crate::BinaryOperator::Equal - | crate::BinaryOperator::NotEqual - | crate::BinaryOperator::Less - | crate::BinaryOperator::LessEqual - | crate::BinaryOperator::Greater - | crate::BinaryOperator::GreaterEqual - | crate::BinaryOperator::LogicalAnd - | crate::BinaryOperator::LogicalOr => { - Resolution::Handle(self.types[left.index()]) - } - crate::BinaryOperator::And - | crate::BinaryOperator::ExclusiveOr - | crate::BinaryOperator::InclusiveOr - | crate::BinaryOperator::ShiftLeftLogical - | crate::BinaryOperator::ShiftRightLogical - | crate::BinaryOperator::ShiftRightArithmetic => { - Resolution::Handle(self.types[left.index()]) - } - }, - crate::Expression::Intrinsic { .. } => unimplemented!(), - crate::Expression::Transpose(expr) => { - let ty_handle = self.types[expr.index()]; - match arena[ty_handle].inner { - crate::TypeInner::Matrix { - columns, - rows, - kind, - width, - } => Resolution::Value(crate::TypeInner::Matrix { - columns: rows, - rows: columns, - kind, - width, - }), - ref other => panic!("incompatible transpose of {:?}", other), - } - } - crate::Expression::DotProduct(left_expr, _) => { - let left_ty = self.types[left_expr.index()]; - match arena[left_ty].inner { - crate::TypeInner::Vector { - kind, - size: _, - width, - } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), - ref other => panic!("incompatible dot of {:?}", other), - } - } - crate::Expression::CrossProduct(_, _) => unimplemented!(), - crate::Expression::As(expr, kind) => { - let ty_handle = self.types[expr.index()]; - match arena[ty_handle].inner { - crate::TypeInner::Scalar { kind: _, width } => { - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - crate::TypeInner::Vector { - kind: _, - size, - width, - } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }), - ref other => panic!("incompatible as of {:?}", other), - } - } - crate::Expression::Derivative { .. } => unimplemented!(), - crate::Expression::Call { - origin: crate::FunctionOrigin::External(ref name), - ref arguments, - } => match name.as_str() { - "distance" | "length" | "dot" => { - let ty_handle = self.types[arguments[0].index()]; - match arena[ty_handle].inner { - crate::TypeInner::Vector { kind, width, .. } => { - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - ref other => panic!("Unexpected argument {:?}", other), - } - } - "normalize" | "fclamp" | "max" | "reflect" | "pow" | "clamp" | "mix" => { - Resolution::Handle(self.types[arguments[0].index()]) - } - _ => return Err(ResolveError::FunctionNotDefined { name: name.clone() }), - }, - crate::Expression::Call { - origin: crate::FunctionOrigin::Local(handle), - arguments: _, - } => { - let ty = functions[handle] - .return_type - .ok_or(ResolveError::FunctionReturnsVoid)?; - Resolution::Handle(ty) - } - }; + let resolution = self.resolve_impl( + expr, + arena, + constants, + global_vars, + local_vars, + functions, + parameter_types, + )?; log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); self.types.push(match resolution { Resolution::Handle(h) => h, @@ -260,14 +268,7 @@ impl Typifier { } } -#[derive(Clone, Debug, Error)] -#[error("mismatched constant type {0:?} expected {1:?}")] -pub struct UnexpectedConstantTypeError(crate::ConstantInner, crate::TypeInner); - -pub fn check_constant_types( - inner: &crate::ConstantInner, - type_inner: &crate::TypeInner, -) -> Result<(), UnexpectedConstantTypeError> { +pub fn check_constant_type(inner: &crate::ConstantInner, type_inner: &crate::TypeInner) -> bool { match (inner, type_inner) { ( crate::ConstantInner::Sint(_), @@ -275,32 +276,29 @@ pub fn check_constant_types( kind: crate::ScalarKind::Sint, width: _, }, - ) => Ok(()), + ) => true, ( crate::ConstantInner::Uint(_), crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width: _, }, - ) => Ok(()), + ) => true, ( crate::ConstantInner::Float(_), crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: _, }, - ) => Ok(()), + ) => true, ( crate::ConstantInner::Bool(_), crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: _, }, - ) => Ok(()), - (crate::ConstantInner::Composite(_inner), _) => Ok(()), // TODO recursively check composite types - (other_inner, other_type_inner) => Err(UnexpectedConstantTypeError( - other_inner.clone(), - other_type_inner.clone(), - )), + ) => true, + (crate::ConstantInner::Composite(_inner), _) => true, // TODO recursively check composite types + (_, _) => false, } } From b67739034ebe48dc8f21dfd75a428c907ac46e6b Mon Sep 17 00:00:00 2001 From: Matus Talcik Date: Mon, 31 Aug 2020 20:34:38 +0200 Subject: [PATCH 0178/2212] Implement Execution Modes (#169) Add documentation, make clippy happy Compilation errors Add some more docs Few more compilation errors Changes based on the review glsl-new parser fix Set default local size to (0, 0, 0) final cleanup Last design New design --- examples/convert.rs | 26 +++-- src/back/glsl.rs | 15 +-- src/back/msl.rs | 183 ++++++++++++++++++----------------- src/back/spv/writer.rs | 8 +- src/front/glsl/mod.rs | 10 +- src/front/glsl_new/parser.rs | 90 +++++++++-------- src/front/spv/error.rs | 1 + src/front/spv/mod.rs | 116 +++++++++++++++++----- src/front/wgsl/mod.rs | 8 +- src/lib.rs | 50 +++++++++- tests/convert.rs | 8 +- 11 files changed, 333 insertions(+), 182 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 3e54b8ffb..9707b6cb7 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -91,7 +91,9 @@ fn main() { naga::front::glsl_new::parse_str( &input, "main".to_string(), - naga::ShaderStage::Fragment, + naga::ShaderStage::Fragment { + early_depth_test: None, + }, ) .unwrap(), ) @@ -104,7 +106,9 @@ fn main() { naga::front::glsl::parse_str( &input, "main".to_string(), - naga::ShaderStage::Fragment, + naga::ShaderStage::Fragment { + early_depth_test: None, + }, ) .unwrap(), ) @@ -115,8 +119,14 @@ fn main() { #[cfg(feature = "glsl")] "comp" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Compute) - .unwrap() + naga::front::glsl::parse_str( + &input, + "main".to_string(), + naga::ShaderStage::Compute { + local_size: (0, 0, 0), + }, + ) + .unwrap() } #[cfg(feature = "deserialize")] "ron" => { @@ -209,8 +219,12 @@ fn main() { String::from("main"), match stage { "vert" => ShaderStage::Vertex, - "frag" => ShaderStage::Fragment, - "comp" => ShaderStage::Compute, + "frag" => ShaderStage::Fragment { + early_depth_test: None, + }, + "comp" => ShaderStage::Compute { + local_size: (0, 0, 0), + }, _ => unreachable!(), }, ), diff --git a/src/back/glsl.rs b/src/back/glsl.rs index d0652adc7..e5224c0b8 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -129,7 +129,7 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> .ok_or_else(|| Error::Custom(String::from("Entry point not found")))?; let func = &module.functions[entry_point.function]; - if entry_point.stage == ShaderStage::Compute { + if let ShaderStage::Compute { .. } = entry_point.stage { if (es && version < 310) || (!es && version < 430) { return Err(Error::Custom(format!( "Version {} doesn't support compute shaders", @@ -293,12 +293,13 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> } if let Some(interpolation) = global.interpolation { - if (entry_point.stage == ShaderStage::Fragment && global.class == StorageClass::Input) - || (entry_point.stage == ShaderStage::Vertex - && global.class == StorageClass::Output) - { - write!(out, "{} ", write_interpolation(interpolation)?)?; - } + match (entry_point.stage, global.class) { + (ShaderStage::Fragment { .. }, StorageClass::Input) + | (ShaderStage::Vertex, StorageClass::Output) => { + write!(out, "{} ", write_interpolation(interpolation)?)?; + } + _ => {} + }; } let block = match global.class { diff --git a/src/back/msl.rs b/src/back/msl.rs index eb3464f96..da7045942 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -1020,111 +1020,116 @@ impl Writer { LocationMode::VertexInput, LocationMode::Intermediate, ), - crate::ShaderStage::Fragment => ( + crate::ShaderStage::Fragment { .. } => ( "fragment", LocationMode::Intermediate, LocationMode::FragmentOutput, ), - crate::ShaderStage::Compute => { + crate::ShaderStage::Compute { .. } => { ("kernel", LocationMode::Uniform, LocationMode::Uniform) } }; let location_input_name = fun.name.or_index(InputStructIndex(fun_handle)); - if stage != crate::ShaderStage::Compute { - writeln!(self.out, "struct {} {{", location_input_name)?; - for ((handle, var), &usage) in - module.global_variables.iter().zip(&fun.global_usage) - { - if var.class != crate::StorageClass::Input - || !usage.contains(crate::GlobalUse::LOAD) + match stage { + crate::ShaderStage::Compute { .. } => { + writeln!(self.out, "struct {} {{", location_input_name)?; + for ((handle, var), &usage) in + module.global_variables.iter().zip(&fun.global_usage) { - continue; - } - // if it's a struct, lift all the built-in contents up to the root - let ty_handle = var.ty; - if let crate::TypeInner::Struct { ref members } = - module.types[ty_handle].inner - { - for (index, member) in members.iter().enumerate() { - if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { - let name = member.name.or_index(MemberIndex(index)); - let ty_name = module.types[member.ty].name.or_index(member.ty); - write!(self.out, "\t{} {}", ty_name, name)?; - ResolvedBinding::BuiltIn(built_in) - .try_fmt_decorated(&mut self.out, ";\n")?; - } + if var.class != crate::StorageClass::Input + || !usage.contains(crate::GlobalUse::LOAD) + { + continue; } - } else if let Some(ref binding @ crate::Binding::Location(_)) = var.binding - { - let tyvar = TypedGlobalVariable { - module, - handle, - usage: crate::GlobalUse::empty(), - }; - let resolved = options.resolve_binding(binding, in_mode)?; - - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - resolved.try_fmt_decorated(&mut self.out, ";\n")?; - } - } - writeln!(self.out, "}};")?; - writeln!(self.out, "struct {} {{", output_name)?; - for ((handle, var), &usage) in - module.global_variables.iter().zip(&fun.global_usage) - { - if var.class != crate::StorageClass::Output - || !usage.contains(crate::GlobalUse::STORE) - { - continue; - } - // if it's a struct, lift all the built-in contents up to the root - let ty_handle = var.ty; - if let crate::TypeInner::Struct { ref members } = - module.types[ty_handle].inner - { - for (index, member) in members.iter().enumerate() { - let name = member.name.or_index(MemberIndex(index)); - let ty_name = module.types[member.ty].name.or_index(member.ty); - match member.origin { - crate::MemberOrigin::Empty => {} - crate::MemberOrigin::BuiltIn(built_in) => { + // if it's a struct, lift all the built-in contents up to the root + let ty_handle = var.ty; + if let crate::TypeInner::Struct { ref members } = + module.types[ty_handle].inner + { + for (index, member) in members.iter().enumerate() { + if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { + let name = member.name.or_index(MemberIndex(index)); + let ty_name = + module.types[member.ty].name.or_index(member.ty); write!(self.out, "\t{} {}", ty_name, name)?; ResolvedBinding::BuiltIn(built_in) .try_fmt_decorated(&mut self.out, ";\n")?; } - crate::MemberOrigin::Offset(_) => { - //TODO + } + } else if let Some(ref binding @ crate::Binding::Location(_)) = + var.binding + { + let tyvar = TypedGlobalVariable { + module, + handle, + usage: crate::GlobalUse::empty(), + }; + let resolved = options.resolve_binding(binding, in_mode)?; + + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + resolved.try_fmt_decorated(&mut self.out, ";\n")?; + } + } + writeln!(self.out, "}};")?; + writeln!(self.out, "struct {} {{", output_name)?; + for ((handle, var), &usage) in + module.global_variables.iter().zip(&fun.global_usage) + { + if var.class != crate::StorageClass::Output + || !usage.contains(crate::GlobalUse::STORE) + { + continue; + } + // if it's a struct, lift all the built-in contents up to the root + let ty_handle = var.ty; + if let crate::TypeInner::Struct { ref members } = + module.types[ty_handle].inner + { + for (index, member) in members.iter().enumerate() { + let name = member.name.or_index(MemberIndex(index)); + let ty_name = module.types[member.ty].name.or_index(member.ty); + match member.origin { + crate::MemberOrigin::Empty => {} + crate::MemberOrigin::BuiltIn(built_in) => { + write!(self.out, "\t{} {}", ty_name, name)?; + ResolvedBinding::BuiltIn(built_in) + .try_fmt_decorated(&mut self.out, ";\n")?; + } + crate::MemberOrigin::Offset(_) => { + //TODO + } } } + } else { + let tyvar = TypedGlobalVariable { + module, + handle, + usage: crate::GlobalUse::empty(), + }; + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + if let Some(ref binding) = var.binding { + let resolved = options.resolve_binding(binding, out_mode)?; + resolved.try_fmt_decorated(&mut self.out, "")?; + } + writeln!(self.out, ";")?; } - } else { - let tyvar = TypedGlobalVariable { - module, - handle, - usage: crate::GlobalUse::empty(), - }; - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - if let Some(ref binding) = var.binding { - let resolved = options.resolve_binding(binding, out_mode)?; - resolved.try_fmt_decorated(&mut self.out, "")?; - } - writeln!(self.out, ";")?; } + writeln!(self.out, "}};")?; + writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; + let separator = separate(last_used_global.is_none()); + writeln!( + self.out, + "\t{} {} [[stage_in]]{}", + location_input_name, LOCATION_INPUT_STRUCT_NAME, separator + )?; } - writeln!(self.out, "}};")?; - writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; - let separator = separate(last_used_global.is_none()); - writeln!( - self.out, - "\t{} {} [[stage_in]]{}", - location_input_name, LOCATION_INPUT_STRUCT_NAME, separator - )?; - } else { - writeln!(self.out, "{} void {}(", em_str, fun_name)?; - } + _ => { + writeln!(self.out, "{} void {}(", em_str, fun_name)?; + } + }; for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { @@ -1142,10 +1147,10 @@ impl Writer { LocationMode::VertexInput } (crate::ShaderStage::Vertex, crate::StorageClass::Output) - | (crate::ShaderStage::Fragment, crate::StorageClass::Input) => { + | (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Input) => { LocationMode::Intermediate } - (crate::ShaderStage::Fragment, crate::StorageClass::Output) => { + (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Output) => { LocationMode::FragmentOutput } _ => LocationMode::Uniform, @@ -1188,11 +1193,11 @@ impl Writer { // write down function body let has_output = match shader_stage { - Some(crate::ShaderStage::Vertex) | Some(crate::ShaderStage::Fragment) => { + Some(crate::ShaderStage::Vertex) | Some(crate::ShaderStage::Fragment { .. }) => { writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?; true } - Some(crate::ShaderStage::Compute) | None => false, + Some(crate::ShaderStage::Compute { .. }) | None => false, }; for (local_handle, local) in fun.local_variables.iter() { let ty_name = module.types[local.ty].name.or_index(local.ty); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 1c6c6957b..1e5d44a22 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -271,8 +271,8 @@ impl Writer { let exec_model = match entry_point.stage { crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, - crate::ShaderStage::Fragment => spirv::ExecutionModel::Fragment, - crate::ShaderStage::Compute => spirv::ExecutionModel::GLCompute, + crate::ShaderStage::Fragment { .. } => spirv::ExecutionModel::Fragment, + crate::ShaderStage::Compute { .. } => spirv::ExecutionModel::GLCompute, }; instruction.add_operand(exec_model as u32); @@ -298,13 +298,13 @@ impl Writer { self.try_add_capabilities(exec_model.required_capabilities()); match entry_point.stage { crate::ShaderStage::Vertex => {} - crate::ShaderStage::Fragment => { + crate::ShaderStage::Fragment { .. } => { let execution_mode = spirv::ExecutionMode::OriginUpperLeft; self.try_add_capabilities(execution_mode.required_capabilities()); self.instruction_execution_mode(function_id, execution_mode) .to_words(&mut self.logical_layout.execution_modes); } - crate::ShaderStage::Compute => {} + crate::ShaderStage::Compute { .. } => {} } if self.writer_flags.contains(WriterFlags::DEBUG) { diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 6bc39d63c..f8fad62b5 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -638,7 +638,7 @@ impl<'a> Parser<'a> { name: Some(name), class: match self.shader_stage { ShaderStage::Vertex => StorageClass::Output, - ShaderStage::Fragment => StorageClass::Input, + ShaderStage::Fragment { .. } => StorageClass::Input, _ => panic!(), }, binding: Some(Binding::BuiltIn(BuiltIn::Position)), @@ -1327,7 +1327,13 @@ mod tests { println!( "{:#?}", - parse_str(data, String::from("main"), crate::ShaderStage::Fragment) + parse_str( + data, + String::from("main"), + crate::ShaderStage::Fragment { + early_depth_test: None + } + ) ); } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index c1c986d8e..b74dc64a9 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -130,52 +130,56 @@ pomelo! { // expression variable_identifier ::= Identifier(v) { - if v.1.as_str() == "gl_Position" && - (extra.shader_stage == ShaderStage::Vertex || - extra.shader_stage == ShaderStage::Fragment) { - let h = extra.global_variables.fetch_or_append( - GlobalVariable { - name: Some(v.1.clone()), - class: match extra.shader_stage { - ShaderStage::Vertex => StorageClass::Output, - ShaderStage::Fragment => StorageClass::Input, - _ => StorageClass::Input, - }, - binding: Some(Binding::BuiltIn(BuiltIn::Position)), - ty: extra.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, + let gl_position = if let ShaderStage::Vertex | ShaderStage::Fragment { .. } = extra.shader_stage { + if v.1.as_str() == "gl_Position" { + let h = extra.global_variables.fetch_or_append( + GlobalVariable { + name: Some(v.1.clone()), + class: match extra.shader_stage { + ShaderStage::Vertex => StorageClass::Output, + ShaderStage::Fragment { .. } => StorageClass::Input, + _ => StorageClass::Input, }, - }), - interpolation: None, - }, - ); - extra.lookup_global_variables.insert(v.1.clone(), h); - let expression = extra.context.expressions.append( - Expression::GlobalVariable(h) - ); - extra.context.lookup_global_var_exps.insert(v.1, expression); - ExpressionRule{ - expression, - statements: vec![], + binding: Some(Binding::BuiltIn(BuiltIn::Position)), + ty: extra.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 4, + }, + }), + interpolation: None, + }, + ); + extra.lookup_global_variables.insert(v.1.clone(), h); + let expression = extra.context.expressions.append( + Expression::GlobalVariable(h) + ); + extra.context.lookup_global_var_exps.insert(v.1.clone(), expression); + + Some(expression) + } else { + None } } else { - // try global and local vars - let expression = - if let Some(local_var) = extra.context.lookup_local_var(&v.1) { - local_var - } else if let Some(global_var) = extra.context.lookup_global_var_exps.get(&v.1) { - *global_var - } else { - return Err(ErrorKind::UnknownVariable(v.0, v.1)) - }; - ExpressionRule{ - expression, - statements: vec![], - } + None + }; + + let expression = + if let Some(gl_position) = gl_position { + gl_position + } else if let Some(local_var) = extra.context.lookup_local_var(&v.1) { + local_var + } else if let Some(global_var) = extra.context.lookup_global_var_exps.get(&v.1) { + *global_var + } else { + return Err(ErrorKind::UnknownVariable(v.0, v.1)); + }; + + ExpressionRule { + expression, + statements: vec![], } } diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 0488a83ef..f9ab8fca3 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -15,6 +15,7 @@ pub enum Error { UnsupportedExtInst(spirv::Word), UnsupportedType(Handle), UnsupportedExecutionModel(spirv::Word), + UnsupportedExecutionMode(spirv::Word), UnsupportedStorageClass(spirv::Word), UnsupportedImageDim(spirv::Word), UnsupportedImageFormat(spirv::Word), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 0f7786006..5ef5be200 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -29,7 +29,11 @@ use crate::{ use num_traits::cast::FromPrimitive; use std::{convert::TryInto, num::NonZeroU32}; -pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[spirv::Capability::Shader]; +pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ + spirv::Capability::Shader, + spirv::Capability::CullDistance, + spirv::Capability::StorageImageExtendedFormats, +]; pub const SUPPORTED_EXTENSIONS: &[&str] = &[]; pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"]; @@ -235,7 +239,7 @@ struct LookupFunctionType { #[derive(Debug)] struct EntryPoint { - exec_model: spirv::ExecutionModel, + stage: crate::ShaderStage, name: String, function_id: spirv::Word, variable_ids: Vec, @@ -300,6 +304,7 @@ pub struct Parser { lookup_sampled_image: FastHashMap, lookup_function_type: FastHashMap, lookup_function: FastHashMap>, + lookup_entry_point: FastHashMap, deferred_function_calls: Vec, } @@ -322,6 +327,7 @@ impl> Parser { lookup_sampled_image: FastHashMap::default(), lookup_function_type: FastHashMap::default(), lookup_function: FastHashMap::default(), + lookup_entry_point: FastHashMap::default(), deferred_function_calls: Vec::new(), } } @@ -1402,7 +1408,6 @@ impl> Parser { generator, } }); - let mut entry_points = Vec::new(); while let Ok(inst) = self.next_inst() { use spirv::Op; @@ -1412,7 +1417,7 @@ impl> Parser { Op::Extension => self.parse_extension(inst), Op::ExtInstImport => self.parse_ext_inst_import(inst), Op::MemoryModel => self.parse_memory_model(inst), - Op::EntryPoint => self.parse_entry_point(inst, &mut entry_points), + Op::EntryPoint => self.parse_entry_point(inst), Op::ExecutionMode => self.parse_execution_mode(inst), Op::Source => self.parse_source(inst), Op::SourceExtension => self.parse_source_extension(inst), @@ -1492,16 +1497,11 @@ impl> Parser { self.future_member_decor.clear(); } - module.entry_points.reserve(entry_points.len()); - for raw in entry_points { + module.entry_points.reserve(self.lookup_entry_point.len()); + for raw in self.lookup_entry_point.values() { module.entry_points.push(crate::EntryPoint { - stage: match raw.exec_model { - spirv::ExecutionModel::Vertex => crate::ShaderStage::Vertex, - spirv::ExecutionModel::Fragment => crate::ShaderStage::Fragment, - spirv::ExecutionModel::GLCompute => crate::ShaderStage::Compute, - other => return Err(Error::UnsupportedExecutionModel(other as u32)), - }, - name: raw.name, + stage: raw.stage, + name: raw.name.clone(), function: *self.lookup_function.lookup(raw.function_id)?, }); } @@ -1557,11 +1557,7 @@ impl> Parser { Ok(()) } - fn parse_entry_point( - &mut self, - inst: Instruction, - entry_points: &mut Vec, - ) -> Result<(), Error> { + fn parse_entry_point(&mut self, inst: Instruction) -> Result<(), Error> { self.switch(ModuleState::EntryPoint, inst.op)?; inst.expect_at_least(4)?; let exec_model = self.next()?; @@ -1570,23 +1566,93 @@ impl> Parser { let function_id = self.next()?; let (name, left) = self.next_string(inst.wc - 3)?; let ep = EntryPoint { - exec_model, + stage: match exec_model { + spirv::ExecutionModel::Vertex => crate::ShaderStage::Vertex, + spirv::ExecutionModel::Fragment => crate::ShaderStage::Fragment { + early_depth_test: None, + }, + spirv::ExecutionModel::GLCompute => crate::ShaderStage::Compute { + local_size: (0, 0, 0), + }, + _ => return Err(Error::UnsupportedExecutionModel(exec_model as u32)), + }, name, function_id, variable_ids: self.data.by_ref().take(left as usize).collect(), }; - entry_points.push(ep); + self.lookup_entry_point.insert(function_id, ep); Ok(()) } fn parse_execution_mode(&mut self, inst: Instruction) -> Result<(), Error> { + use crate::ShaderStage; + use spirv::ExecutionMode; + self.switch(ModuleState::ExecutionMode, inst.op)?; inst.expect_at_least(3)?; - let _ep_id = self.next()?; - let _mode = self.next()?; - for _ in 3..inst.wc { - let _ = self.next()?; //TODO - } + + let ep_id = self.next()?; + let mode_id = self.next()?; + let args: Vec = self.data.by_ref().take(inst.wc as usize - 3).collect(); + + let ep: &mut EntryPoint = self + .lookup_entry_point + .get_mut(&ep_id) + .ok_or(Error::InvalidId(ep_id))?; + let mode = spirv::ExecutionMode::from_u32(mode_id) + .ok_or(Error::UnsupportedExecutionMode(mode_id))?; + + match ep.stage { + ShaderStage::Fragment { + ref mut early_depth_test, + } => { + match mode { + ExecutionMode::EarlyFragmentTests => { + if early_depth_test.is_none() { + *early_depth_test = Some(crate::EarlyDepthTest { conservative: None }); + } + } + ExecutionMode::DepthUnchanged => { + *early_depth_test = Some(crate::EarlyDepthTest { + conservative: Some(crate::ConservativeDepth::Unchanged), + }); + } + ExecutionMode::DepthGreater => { + *early_depth_test = Some(crate::EarlyDepthTest { + conservative: Some(crate::ConservativeDepth::GreaterEqual), + }); + } + ExecutionMode::DepthLess => { + *early_depth_test = Some(crate::EarlyDepthTest { + conservative: Some(crate::ConservativeDepth::LessEqual), + }); + } + ExecutionMode::DepthReplacing => { + // Ignored because it can be deduced from the IR. + } + ExecutionMode::OriginUpperLeft => { + // Ignored because the other option (OriginLowerLeft) is not valid in Vulkan mode. + } + _ => { + return Err(Error::UnsupportedExecutionMode(mode_id)); + } + }; + } + ShaderStage::Compute { ref mut local_size } => { + match mode { + ExecutionMode::LocalSize => { + *local_size = (args[0], args[1], args[2]); + } + _ => { + return Err(Error::UnsupportedExecutionMode(mode_id)); + } + }; + } + _ => { + return Err(Error::UnsupportedExecutionMode(mode_id)); + } + }; + Ok(()) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index ec89afe88..efced204f 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -265,8 +265,12 @@ impl Parser { fn get_shader_stage(word: &str) -> Result> { match word { "vertex" => Ok(crate::ShaderStage::Vertex), - "fragment" => Ok(crate::ShaderStage::Fragment), - "compute" => Ok(crate::ShaderStage::Compute), + "fragment" => Ok(crate::ShaderStage::Fragment { + early_depth_test: None, + }), + "compute" => Ok(crate::ShaderStage::Compute { + local_size: (0, 0, 0), + }), _ => Err(Error::UnknownShaderStage(word)), } } diff --git a/src/lib.rs b/src/lib.rs index 3e25f8885..b662046c2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -45,6 +45,48 @@ pub struct Header { pub generator: u32, } +/// Early fragment tests. In a standard situation if a driver determines that it is possible to +/// switch on early depth test it will. Typical situations when early depth test is switched off: +/// - Calling ```discard``` in a shader. +/// - Writing to the depth buffer, unless ConservativeDepth is enabled. +/// +/// SPIR-V: ExecutionMode EarlyFragmentTests +/// In GLSL: layout(early_fragment_tests) in; +/// HLSL: Attribute earlydepthstencil +/// +/// For more, see: +/// - https://www.khronos.org/opengl/wiki/Early_Fragment_Test#Explicit_specification +/// - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-earlydepthstencil +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub struct EarlyDepthTest { + conservative: Option, +} +/// Enables adjusting depth without disabling early Z. +/// +/// SPIR-V: ExecutionMode DepthGreater/DepthLess/DepthUnchanged +/// GLSL: layout (depth_) out float gl_FragDepth; +/// - ```depth_any``` option behaves as if the layout qualifier was not present. +/// HLSL: SV_Depth/SV_DepthGreaterEqual/SV_DepthLessEqual +/// +/// For more, see: +/// - https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_conservative_depth.txt +/// - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics#system-value-semantics +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum ConservativeDepth { + /// Shader may rewrite depth only with a value greater than calculated; + GreaterEqual, + + /// Shader may rewrite depth smaller than one that would have been written without the modification. + LessEqual, + + /// Shader may not rewrite depth value. + Unchanged, +} + /// Stage of the programmable pipeline. #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -52,8 +94,12 @@ pub struct Header { #[allow(missing_docs)] // The names are self evident pub enum ShaderStage { Vertex, - Fragment, - Compute, + Fragment { + early_depth_test: Option, + }, + Compute { + local_size: (u32, u32, u32), + }, } /// Class of storage for variables. diff --git a/tests/convert.rs b/tests/convert.rs index ef3431f56..0e1f6b869 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -114,7 +114,9 @@ fn convert_phong_lighting() { let module = load_glsl( "glsl_phong_lighting.frag", "main", - naga::ShaderStage::Fragment, + naga::ShaderStage::Fragment { + early_depth_test: None, + }, ); naga::proc::Validator::new().validate(&module).unwrap(); @@ -133,7 +135,9 @@ fn constant_expressions() { let module = load_glsl( "glsl_constant_expression.vert", "main", - naga::ShaderStage::Fragment, + naga::ShaderStage::Fragment { + early_depth_test: None, + }, ); naga::proc::Validator::new().validate(&module).unwrap(); } From f97c62b0e6a083bd2aee1f3b689b8859a8e449e7 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 1 Sep 2020 06:52:07 +0200 Subject: [PATCH 0179/2212] [glsl-new] Add bool consts, update logical exprs (#171) --- src/front/glsl_new/ast.rs | 9 +++++ src/front/glsl_new/lex.rs | 3 ++ src/front/glsl_new/parser.rs | 75 +++++++++++++++++++++++------------- 3 files changed, 61 insertions(+), 26 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 32d5e8df9..47feacac6 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -102,6 +102,15 @@ pub struct ExpressionRule { pub statements: Vec, } +impl ExpressionRule { + pub fn from_expression(expression: Handle) -> ExpressionRule { + ExpressionRule { + expression, + statements: vec![], + } + } +} + #[derive(Debug)] pub enum TypeQualifier { StorageClass(StorageClass), diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index d7ae86008..6fda4bb6c 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -136,6 +136,9 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { Some(Token::Interpolation((meta, crate::Interpolation::Sample))), rest, ), + // values + "true" => (Some(Token::BoolConstant((meta, true))), rest), + "false" => (Some(Token::BoolConstant((meta, false))), rest), // types "void" => (Some(Token::Void(meta)), rest), word => { diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index b74dc64a9..0fdec7770 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -76,10 +76,10 @@ pomelo! { %type and_expression Handle; %type exclusive_or_expression Handle; %type inclusive_or_expression Handle; - %type logical_and_expression Handle; - %type logical_xor_expression Handle; - %type logical_or_expression Handle; - %type conditional_expression Handle; + %type logical_and_expression ExpressionRule; + %type logical_xor_expression ExpressionRule; + %type logical_or_expression ExpressionRule; + %type conditional_expression ExpressionRule; %type assignment_expression ExpressionRule; %type assignment_operator BinaryOperator; @@ -177,10 +177,9 @@ pomelo! { return Err(ErrorKind::UnknownVariable(v.0, v.1)); }; - ExpressionRule { - expression, - statements: vec![], - } + ExpressionRule::from_expression( + expression + ) } primary_expression ::= variable_identifier; @@ -198,10 +197,9 @@ pomelo! { ty, inner: ConstantInner::Sint(i.1) }); - ExpressionRule { - expression: extra.context.expressions.append(Expression::Constant(ch)), - statements: vec![], - } + ExpressionRule::from_expression( + extra.context.expressions.append(Expression::Constant(ch)) + ) } // primary_expression ::= UintConstant; primary_expression ::= FloatConstant(f) { @@ -218,12 +216,28 @@ pomelo! { ty, inner: ConstantInner::Float(f.1 as f64) }); - ExpressionRule { - expression: extra.context.expressions.append(Expression::Constant(ch)), - statements: vec![], - } + ExpressionRule::from_expression( + extra.context.expressions.append(Expression::Constant(ch)) + ) + } + primary_expression ::= BoolConstant(b) { + let ty = extra.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Bool, + width: 4, + } + }); + let ch = extra.constants.fetch_or_append(Constant { + name: None, + specialization: None, + ty, + inner: ConstantInner::Bool(b.1) + }); + ExpressionRule::from_expression( + extra.context.expressions.append(Expression::Constant(ch)) + ) } - // primary_expression ::= BoolConstant; // primary_expression ::= DoubleConstant; primary_expression ::= LeftParen expression(e) RightParen {e} @@ -387,9 +401,17 @@ pomelo! { inclusive_or_expression ::= inclusive_or_expression(left) VerticalBar exclusive_or_expression(right) { extra.context.expressions.append(Expression::Binary{op: BinaryOperator::InclusiveOr, left, right}) } - logical_and_expression ::= inclusive_or_expression; + logical_and_expression ::= inclusive_or_expression(e) { + ExpressionRule::from_expression(e) + } logical_and_expression ::= logical_and_expression(left) AndOp inclusive_or_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::LogicalAnd, left, right}) + ExpressionRule::from_expression( + extra.context.expressions.append(Expression::Binary{ + op: BinaryOperator::LogicalAnd, + left: left.expression, + right + }) + ) } logical_xor_expression ::= logical_and_expression; logical_xor_expression ::= logical_xor_expression(left) XorOp logical_and_expression(right) { @@ -399,7 +421,13 @@ pomelo! { } logical_or_expression ::= logical_xor_expression; logical_or_expression ::= logical_or_expression(left) OrOp logical_xor_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::LogicalOr, left, right}) + ExpressionRule::from_expression( + extra.context.expressions.append(Expression::Binary{ + op: BinaryOperator::LogicalOr, + left: left.expression, + right: right.expression, + }) + ) } conditional_expression ::= logical_or_expression; @@ -408,12 +436,7 @@ pomelo! { return Err(ErrorKind::NotImplemented("ternary exp")) } - assignment_expression ::= conditional_expression(ce) { - ExpressionRule{ - expression: ce, - statements: vec![], - } - } + assignment_expression ::= conditional_expression; assignment_expression ::= unary_expression(mut pointer) assignment_operator(op) assignment_expression(value) { match op { BinaryOperator::Equal => { From dc38fc115bbf3ba5d7efadee066725b353c57188 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Tue, 18 Aug 2020 20:18:55 +0200 Subject: [PATCH 0180/2212] [spirv-out] Add OpFunctionParameter --- src/back/spv/writer.rs | 72 ++++++++++++++++++++++-------------------- 1 file changed, 38 insertions(+), 34 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 1e5d44a22..6c6da3162 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -647,6 +647,13 @@ impl Writer { instruction } + fn instruction_function_parameter(&self, result_type_id: Word, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::FunctionParameter); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction + } + fn instruction_function_end(&self) -> Instruction { Instruction::new(Op::FunctionEnd) } @@ -1075,39 +1082,6 @@ impl Writer { } } - fn write_function( - &mut self, - handle: crate::Handle, - function: &crate::Function, - arena: &crate::Arena, - ) -> Instruction { - let id = self.generate_id(); - - let return_type_id = self.get_function_type(function.return_type, arena); - - let mut parameter_type_ids = Vec::with_capacity(function.parameter_types.len()); - for parameter_type in function.parameter_types.iter() { - parameter_type_ids.push(self.get_type_id(arena, LookupType::Handle(*parameter_type))) - } - - let lookup_function_type = LookupFunctionType { - return_type_id, - parameter_type_ids, - }; - - let type_function_id = self.write_function_type(lookup_function_type); - - let instruction = self.instruction_function( - return_type_id, - id, - spirv::FunctionControl::empty(), - type_function_id, - ); - - self.lookup_function.insert(handle, id); - instruction - } - fn write_expression<'a>( &mut self, ir_module: &'a crate::Module, @@ -1310,7 +1284,37 @@ impl Writer { for (handle, function) in ir_module.functions.iter() { let mut function_instructions: Vec = vec![]; - function_instructions.push(self.write_function(handle, function, &ir_module.types)); + let id = self.generate_id(); + + let return_type_id = self.get_function_type(function.return_type, &ir_module.types); + let mut parameter_type_ids = Vec::with_capacity(function.parameter_types.len()); + + let mut function_parameter_instructions = vec![]; + for parameter_type in function.parameter_types.iter() { + let parameter_id = + self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type)); + parameter_type_ids.push(parameter_id); + let id = self.generate_id(); + function_parameter_instructions + .push(self.instruction_function_parameter(parameter_id, id)); + } + + let lookup_function_type = LookupFunctionType { + return_type_id, + parameter_type_ids, + }; + + let type_function_id = self.write_function_type(lookup_function_type); + + function_instructions.push(self.instruction_function( + return_type_id, + id, + spirv::FunctionControl::empty(), + type_function_id, + )); + function_instructions.append(&mut function_parameter_instructions); + + self.lookup_function.insert(handle, id); let id = self.generate_id(); function_instructions.push(self.instruction_label(id)); From b7d834ed33fa0a261791087cfa6e11aa70677a48 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sat, 22 Aug 2020 15:42:12 +0200 Subject: [PATCH 0181/2212] [spirv-out] Implement return value for functions --- src/back/spv/writer.rs | 81 +++++++++++++++++++++--------------------- 1 file changed, 40 insertions(+), 41 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 6c6da3162..685bf8be7 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -137,7 +137,7 @@ impl Writer { } } - fn get_function_type( + fn get_function_return_type( &mut self, ty: Option>, arena: &crate::Arena, @@ -1062,7 +1062,7 @@ impl Writer { (instruction, id) } - fn write_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { + fn get_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { match self .lookup_function_type .entry(lookup_function_type.clone()) @@ -1088,7 +1088,7 @@ impl Writer { function: &crate::Function, expression: &crate::Expression, output: &mut Vec, - ) -> (Word, &'a crate::TypeInner) { + ) -> Option<(Word, &'a crate::TypeInner)> { match expression { crate::Expression::GlobalVariable(handle) => { let var = &ir_module.global_variables[*handle]; @@ -1098,13 +1098,13 @@ impl Writer { &ir_module.global_variables, *handle, ); - (id, inner) + Some((id, inner)) } crate::Expression::Constant(handle) => { let var = &ir_module.constants[*handle]; let inner = &ir_module.types[var.ty].inner; let id = self.get_constant_id(*handle, ir_module); - (id, inner) + Some((id, inner)) } crate::Expression::Compose { ty, components } => { let var = &ir_module.types[*ty]; @@ -1116,7 +1116,7 @@ impl Writer { for component in components { let expression = &function.expressions[*component]; let (component_id, _) = - self.write_expression(ir_module, &function, expression, output); + self.write_expression(ir_module, &function, expression, output).unwrap(); constituent_ids.push(component_id); } @@ -1124,7 +1124,7 @@ impl Writer { self.instruction_composite_construct(type_id, id, constituent_ids); output.push(instruction); - (id, inner) + Some((id, inner)) } crate::Expression::Binary { op, left, right } => { match op { @@ -1134,9 +1134,9 @@ impl Writer { let left_expression = &function.expressions[*left]; let right_expression = &function.expressions[*right]; let (left_id, left_inner) = - self.write_expression(ir_module, function, left_expression, output); + self.write_expression(ir_module, function, left_expression, output).unwrap(); let (right_id, right_inner) = - self.write_expression(ir_module, function, right_expression, output); + self.write_expression(ir_module, function, right_expression, output).unwrap(); let (result_type_id, vector_id, scalar_id) = match (left_inner, right_inner) { @@ -1187,14 +1187,7 @@ impl Writer { ); output.push(instruction); - // TODO Not sure how or what to return - ( - id, - &crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: 10, - }, - ) + None } _ => unimplemented!("{:?}", op), } @@ -1210,7 +1203,7 @@ impl Writer { let instruction = self.instruction_variable(pointer_id, id, spirv::StorageClass::Function, None); output.push(instruction); - (id, &ty.inner) + Some((id, &ty.inner)) } _ => unimplemented!("{:?}", expression), } @@ -1222,24 +1215,32 @@ impl Writer { function: &crate::Function, statement: &crate::Statement, output: &mut Vec, - ) -> Instruction { + ) { match statement { - crate::Statement::Return { .. } => match function.return_type { - Some(ty) => { - let value_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty)); - self.instruction_return_value(value_id) + crate::Statement::Return { value } => { + match function.return_type { + Some(ty) => { + // let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty)); + let pointer_id = self.generate_id(); + + let expression = &function.expressions[value.unwrap()]; + let (id, _) = self.write_expression(ir_module, function, expression, output).unwrap(); + + + output.push(self.instruction_return_value(id)) + } + None => output.push(self.instruction_return()), } - None => self.instruction_return(), }, crate::Statement::Store { pointer, value } => { let pointer_expression = &function.expressions[*pointer]; let value_expression = &function.expressions[*value]; let (pointer_id, _) = - self.write_expression(ir_module, function, pointer_expression, output); + self.write_expression(ir_module, function, pointer_expression, output).unwrap(); let (value_id, _) = - self.write_expression(ir_module, function, value_expression, output); + self.write_expression(ir_module, function, value_expression, output).unwrap(); - self.instruction_store(pointer_id, value_id) + output.push(self.instruction_store(pointer_id, value_id)); } _ => unimplemented!(), } @@ -1277,26 +1278,21 @@ impl Writer { annotation.to_words(&mut self.logical_layout.annotations); } - for capability in self.capabilities.iter() { - self.instruction_capability(*capability) - .to_words(&mut self.logical_layout.capabilities); - } - for (handle, function) in ir_module.functions.iter() { let mut function_instructions: Vec = vec![]; let id = self.generate_id(); - let return_type_id = self.get_function_type(function.return_type, &ir_module.types); + let return_type_id = self.get_function_return_type(function.return_type, &ir_module.types); let mut parameter_type_ids = Vec::with_capacity(function.parameter_types.len()); let mut function_parameter_instructions = vec![]; for parameter_type in function.parameter_types.iter() { - let parameter_id = - self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type)); - parameter_type_ids.push(parameter_id); + parameter_type_ids.push(self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type))); let id = self.generate_id(); + + let pointer_id = self.get_pointer_id(&ir_module.types, *parameter_type, spirv::StorageClass::Function); function_parameter_instructions - .push(self.instruction_function_parameter(parameter_id, id)); + .push(self.instruction_function_parameter(pointer_id, id)); } let lookup_function_type = LookupFunctionType { @@ -1304,7 +1300,7 @@ impl Writer { parameter_type_ids, }; - let type_function_id = self.write_function_type(lookup_function_type); + let type_function_id = self.get_function_type(lookup_function_type); function_instructions.push(self.instruction_function( return_type_id, @@ -1321,10 +1317,8 @@ impl Writer { for block in function.body.iter() { let mut output: Vec = vec![]; - let instruction = - self.write_function_block(ir_module, function, &block, &mut output); + self.write_function_block(ir_module, function, &block, &mut output); function_instructions.append(&mut output); - function_instructions.push(instruction); } function_instructions.push(self.instruction_function_end()); @@ -1338,6 +1332,11 @@ impl Writer { entry_point_instruction.to_words(&mut self.logical_layout.entry_points); } + for capability in self.capabilities.iter() { + self.instruction_capability(*capability) + .to_words(&mut self.logical_layout.capabilities); + } + self.instruction_memory_model() .to_words(&mut self.logical_layout.memory_model); From c56013b46e010c266a75eda988eae3d3eb53da07 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sat, 22 Aug 2020 18:49:04 +0200 Subject: [PATCH 0182/2212] [spirv-out] Implement FunctionParameter --- src/back/spv/writer.rs | 150 +++++++++++++++++++++++++++++++---------- 1 file changed, 116 insertions(+), 34 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 685bf8be7..f0041251a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1062,7 +1062,11 @@ impl Writer { (instruction, id) } - fn get_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { + fn get_function_type( + &mut self, + lookup_function_type: LookupFunctionType, + parameter_pointer_ids: Vec, + ) -> Word { match self .lookup_function_type .entry(lookup_function_type.clone()) @@ -1073,7 +1077,7 @@ impl Writer { let instruction = self.instruction_type_function( id, lookup_function_type.return_type_id, - lookup_function_type.parameter_type_ids.clone(), + parameter_pointer_ids, ); instruction.to_words(&mut self.logical_layout.declarations); self.lookup_function_type.insert(lookup_function_type, id); @@ -1088,6 +1092,7 @@ impl Writer { function: &crate::Function, expression: &crate::Expression, output: &mut Vec, + parameter_type_ids: &Vec, ) -> Option<(Word, &'a crate::TypeInner)> { match expression { crate::Expression::GlobalVariable(handle) => { @@ -1115,8 +1120,15 @@ impl Writer { let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { let expression = &function.expressions[*component]; - let (component_id, _) = - self.write_expression(ir_module, &function, expression, output).unwrap(); + let (component_id, _) = self + .write_expression( + ir_module, + &function, + expression, + output, + parameter_type_ids, + ) + .unwrap(); constituent_ids.push(component_id); } @@ -1133,10 +1145,24 @@ impl Writer { let id = self.generate_id(); let left_expression = &function.expressions[*left]; let right_expression = &function.expressions[*right]; - let (left_id, left_inner) = - self.write_expression(ir_module, function, left_expression, output).unwrap(); - let (right_id, right_inner) = - self.write_expression(ir_module, function, right_expression, output).unwrap(); + let (left_id, left_inner) = self + .write_expression( + ir_module, + function, + left_expression, + output, + parameter_type_ids, + ) + .unwrap(); + let (right_id, right_inner) = self + .write_expression( + ir_module, + function, + right_expression, + output, + parameter_type_ids, + ) + .unwrap(); let (result_type_id, vector_id, scalar_id) = match (left_inner, right_inner) { @@ -1186,9 +1212,12 @@ impl Writer { scalar_id, ); output.push(instruction); - - None + Some((id, &crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: 10, + })) } + _ => unimplemented!("{:?}", op), } } @@ -1205,6 +1234,25 @@ impl Writer { output.push(instruction); Some((id, &ty.inner)) } + crate::Expression::FunctionParameter(index) => { + let handle = function.parameter_types.get(*index as usize).unwrap(); + let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*handle)); + let load_id = self.generate_id(); + + output.push(self.instruction_load( + type_id, + load_id, + parameter_type_ids[*index as usize], + None, + )); + Some(( + load_id, + &crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: 10, + }, + )) + } _ => unimplemented!("{:?}", expression), } } @@ -1215,30 +1263,46 @@ impl Writer { function: &crate::Function, statement: &crate::Statement, output: &mut Vec, + parameter_type_ids: &Vec, ) { match statement { - crate::Statement::Return { value } => { - match function.return_type { - Some(ty) => { - // let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty)); - let pointer_id = self.generate_id(); - - let expression = &function.expressions[value.unwrap()]; - let (id, _) = self.write_expression(ir_module, function, expression, output).unwrap(); - - - output.push(self.instruction_return_value(id)) - } - None => output.push(self.instruction_return()), + crate::Statement::Return { value } => match function.return_type { + Some(ty) => { + let expression = &function.expressions[value.unwrap()]; + let (id, _) = self + .write_expression( + ir_module, + function, + expression, + output, + parameter_type_ids, + ) + .unwrap(); + output.push(self.instruction_return_value(id)) } + None => output.push(self.instruction_return()), }, crate::Statement::Store { pointer, value } => { let pointer_expression = &function.expressions[*pointer]; let value_expression = &function.expressions[*value]; - let (pointer_id, _) = - self.write_expression(ir_module, function, pointer_expression, output).unwrap(); - let (value_id, _) = - self.write_expression(ir_module, function, value_expression, output).unwrap(); + let (pointer_id, _) = self + .write_expression( + ir_module, + function, + pointer_expression, + output, + parameter_type_ids, + ) + .unwrap(); + let (value_id, _) = self + .write_expression( + ir_module, + function, + value_expression, + output, + parameter_type_ids, + ) + .unwrap(); output.push(self.instruction_store(pointer_id, value_id)); } @@ -1282,17 +1346,28 @@ impl Writer { let mut function_instructions: Vec = vec![]; let id = self.generate_id(); - let return_type_id = self.get_function_return_type(function.return_type, &ir_module.types); + let return_type_id = + self.get_function_return_type(function.return_type, &ir_module.types); let mut parameter_type_ids = Vec::with_capacity(function.parameter_types.len()); + let mut function_parameter_ids = vec![]; + let mut function_parameter_pointer_ids = vec![]; let mut function_parameter_instructions = vec![]; - for parameter_type in function.parameter_types.iter() { - parameter_type_ids.push(self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type))); - let id = self.generate_id(); - let pointer_id = self.get_pointer_id(&ir_module.types, *parameter_type, spirv::StorageClass::Function); + for parameter_type in function.parameter_types.iter() { + let id = self.generate_id(); + let pointer_id = self.get_pointer_id( + &ir_module.types, + *parameter_type, + spirv::StorageClass::Function, + ); + + function_parameter_ids.push(id); + function_parameter_pointer_ids.push(pointer_id); function_parameter_instructions .push(self.instruction_function_parameter(pointer_id, id)); + parameter_type_ids + .push(self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type))); } let lookup_function_type = LookupFunctionType { @@ -1300,7 +1375,8 @@ impl Writer { parameter_type_ids, }; - let type_function_id = self.get_function_type(lookup_function_type); + let type_function_id = + self.get_function_type(lookup_function_type, function_parameter_pointer_ids); function_instructions.push(self.instruction_function( return_type_id, @@ -1317,7 +1393,13 @@ impl Writer { for block in function.body.iter() { let mut output: Vec = vec![]; - self.write_function_block(ir_module, function, &block, &mut output); + self.write_function_block( + ir_module, + function, + &block, + &mut output, + &function_parameter_ids, + ); function_instructions.append(&mut output); } From 9ba075c9903fb2f56c83eab09ffe38ca518c2649 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sat, 22 Aug 2020 19:14:14 +0200 Subject: [PATCH 0183/2212] [spirv-out] Implement FunctionCall --- src/back/spv/writer.rs | 462 +++++++++++++++++++++++++++-------------- 1 file changed, 301 insertions(+), 161 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f0041251a..9f704dba4 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -5,6 +5,65 @@ use std::collections::hash_map::Entry; const BITS_PER_BYTE: crate::Bytes = 8; +struct Block { + label: Option, + body: Vec, + termination: Option, +} + +impl Block { + pub fn new() -> Self { + Block { + label: None, + body: vec![], + termination: None, + } + } +} + +struct LocalVariable { + id: Word, + name: Option, + instruction: Instruction, +} + +struct Function { + signature: Option, + parameters: Vec, + variables: Vec, + blocks: Vec, +} + +impl Function { + pub fn new() -> Self { + Function { + signature: None, + parameters: vec![], + variables: vec![], + blocks: vec![], + } + } + + fn to_words(&self, sink: &mut impl Extend) { + self.signature.as_ref().unwrap().to_words(sink); + for instruction in self.parameters.iter() { + instruction.to_words(sink); + } + for (index, block) in self.blocks.iter().enumerate() { + block.label.as_ref().unwrap().to_words(sink); + if index == 0 { + for local_var in self.variables.iter() { + local_var.instruction.to_words(sink); + } + } + for instruction in block.body.iter() { + instruction.to_words(sink); + } + block.termination.as_ref().unwrap().to_words(sink); + } + } +} + enum Signedness { Unsigned = 0, Signed = 1, @@ -583,14 +642,14 @@ impl Writer { fn instruction_variable( &self, - pointer_type_id: Word, - id: Word, + result_type_id: Word, + result_id: Word, storage_class: spirv::StorageClass, initializer_id: Option, ) -> Instruction { let mut instruction = Instruction::new(Op::Variable); - instruction.set_type(pointer_type_id); - instruction.set_result(id); + instruction.set_type(result_type_id); + instruction.set_result(result_id); instruction.add_operand(storage_class as u32); if let Some(initializer_id) = initializer_id { @@ -658,6 +717,21 @@ impl Writer { Instruction::new(Op::FunctionEnd) } + fn instruction_function_call( + &self, + result_type_id: Word, + id: Word, + function_id: Word, + argument_ids: Vec, + ) -> Instruction { + let mut instruction = Instruction::new(Op::FunctionCall); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(function_id); + instruction.add_operands(argument_ids); + instruction + } + /// /// Image Instructions /// @@ -1089,121 +1163,104 @@ impl Writer { fn write_expression<'a>( &mut self, ir_module: &'a crate::Module, - function: &crate::Function, + ir_function: &crate::Function, expression: &crate::Expression, - output: &mut Vec, - parameter_type_ids: &Vec, - ) -> Option<(Word, &'a crate::TypeInner)> { + block: &mut Block, + function: &mut Function, + ) -> Option<(Word, Option>)> { match expression { crate::Expression::GlobalVariable(handle) => { let var = &ir_module.global_variables[*handle]; - let inner = &ir_module.types[var.ty].inner; let id = self.get_global_variable_id( &ir_module.types, &ir_module.global_variables, *handle, ); - Some((id, inner)) + Some((id, Some(var.ty))) } crate::Expression::Constant(handle) => { let var = &ir_module.constants[*handle]; - let inner = &ir_module.types[var.ty].inner; let id = self.get_constant_id(*handle, ir_module); - Some((id, inner)) + Some((id, Some(var.ty))) } crate::Expression::Compose { ty, components } => { - let var = &ir_module.types[*ty]; - let inner = &var.inner; let id = self.generate_id(); let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*ty)); let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { - let expression = &function.expressions[*component]; + let expression = &ir_function.expressions[*component]; let (component_id, _) = self - .write_expression( - ir_module, - &function, - expression, - output, - parameter_type_ids, - ) + .write_expression(ir_module, &ir_function, expression, block, function) .unwrap(); constituent_ids.push(component_id); } let instruction = self.instruction_composite_construct(type_id, id, constituent_ids); - output.push(instruction); - - Some((id, inner)) + block.body.push(instruction); + Some((id, Some(*ty))) } crate::Expression::Binary { op, left, right } => { match op { crate::BinaryOperator::Multiply => { // TODO OpVectorTimesScalar is only supported let id = self.generate_id(); - let left_expression = &function.expressions[*left]; - let right_expression = &function.expressions[*right]; - let (left_id, left_inner) = self + let left_expression = &ir_function.expressions[*left]; + let right_expression = &ir_function.expressions[*right]; + let (left_id, left_ty) = self .write_expression( ir_module, - function, + ir_function, left_expression, - output, - parameter_type_ids, + block, + function, ) .unwrap(); - let (right_id, right_inner) = self + let (right_id, right_ty) = self .write_expression( ir_module, - function, + ir_function, right_expression, - output, - parameter_type_ids, + block, + function, ) .unwrap(); - let (result_type_id, vector_id, scalar_id) = match (left_inner, right_inner) - { - ( - crate::TypeInner::Vector { size, kind, width }, - crate::TypeInner::Scalar { .. }, - ) => { - let result_type_id = *self - .lookup_type - .get(&LookupType::Local(LocalType::Vector { - size: *size, - kind: *kind, - width: *width, - })) - .unwrap(); + let left_ty_inner = &ir_module.types[left_ty.unwrap()].inner; + let right_ty_inner = &ir_module.types[right_ty.unwrap()].inner; - (result_type_id, left_id, right_id) - } - ( - crate::TypeInner::Scalar { .. }, - crate::TypeInner::Vector { size, kind, width }, - ) => { - let result_type_id = *self - .lookup_type - .get(&LookupType::Local(LocalType::Vector { - size: *size, - kind: *kind, - width: *width, - })) - .unwrap(); - (result_type_id, right_id, left_id) - } - _ => unreachable!("Expression requires both a scalar and vector"), - }; + let (result_type_id, vector_id, scalar_id) = + match (left_ty_inner, right_ty_inner) { + ( + crate::TypeInner::Vector { .. }, + crate::TypeInner::Scalar { .. }, + ) => ( + self.get_type_id( + &ir_module.types, + LookupType::Handle(left_ty.unwrap()), + ), + left_id, + right_id, + ), + ( + crate::TypeInner::Scalar { .. }, + crate::TypeInner::Vector { .. }, + ) => ( + self.get_type_id( + &ir_module.types, + LookupType::Handle(right_ty.unwrap()), + ), + right_id, + left_id, + ), + _ => unreachable!("Expression requires both a scalar and vector"), + }; - // TODO Quick fix let load_id = self.generate_id(); - let load_instruction = self.instruction_load(result_type_id, load_id, vector_id, None); - output.push(load_instruction); + block.body.push(load_instruction); let instruction = self.instruction_vector_times_scalar( result_type_id, @@ -1211,102 +1268,161 @@ impl Writer { load_id, scalar_id, ); - output.push(instruction); - Some((id, &crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: 10, - })) + block.body.push(instruction); + Some((id, None)) } _ => unimplemented!("{:?}", op), } } crate::Expression::LocalVariable(variable) => { - let id = self.generate_id(); - let var = &function.local_variables[*variable]; - let ty = &ir_module.types[var.ty]; + let var = &ir_function.local_variables[*variable]; + let id = if let Some(local_var) = function + .variables + .iter() + .find(|&v| v.name.as_ref().unwrap() == var.name.as_ref().unwrap()) + { + local_var.id + } else { + panic!("Could not find: {:?}", var) + }; - let pointer_id = - self.get_pointer_id(&ir_module.types, var.ty, spirv::StorageClass::Function); - - let instruction = - self.instruction_variable(pointer_id, id, spirv::StorageClass::Function, None); - output.push(instruction); - Some((id, &ty.inner)) + Some((id, Some(var.ty))) } crate::Expression::FunctionParameter(index) => { - let handle = function.parameter_types.get(*index as usize).unwrap(); + let handle = ir_function.parameter_types.get(*index as usize).unwrap(); let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*handle)); let load_id = self.generate_id(); - output.push(self.instruction_load( + block.body.push(self.instruction_load( type_id, load_id, - parameter_type_ids[*index as usize], + function.parameters[*index as usize].result_id.unwrap(), None, )); - Some(( - load_id, - &crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: 10, - }, - )) + Some((load_id, Some(*handle))) } + crate::Expression::Call { origin, arguments } => match origin { + crate::FunctionOrigin::Local(local_function) => { + let origin_function = &ir_module.functions[*local_function]; + let id = self.generate_id(); + let mut argument_ids = vec![]; + + for argument in arguments { + let expression = &ir_function.expressions[*argument]; + let (id, ty) = self + .write_expression(ir_module, ir_function, expression, block, function) + .unwrap(); + + // Create variable - OpVariable + // Store value to variable - OpStore + // Use id of variable + + let pointer_id = self.get_pointer_id( + &ir_module.types, + ty.unwrap(), + spirv::StorageClass::Function, + ); + + let variable_id = self.generate_id(); + function.variables.push(LocalVariable { + id: variable_id, + name: None, + instruction: self.instruction_variable( + pointer_id, + variable_id, + spirv::StorageClass::Function, + None, + ), + }); + block.body.push(self.instruction_store(variable_id, id)); + argument_ids.push(variable_id); + } + + let return_type_id = self + .get_function_return_type(origin_function.return_type, &ir_module.types); + + block.body.push(self.instruction_function_call( + return_type_id, + id, + *self.lookup_function.get(local_function).unwrap(), + argument_ids, + )); + Some((id, None)) + } + _ => unimplemented!("{:?}", origin), + }, _ => unimplemented!("{:?}", expression), } } - fn write_function_block( + fn write_function_statement( &mut self, ir_module: &crate::Module, - function: &crate::Function, + ir_function: &crate::Function, statement: &crate::Statement, - output: &mut Vec, - parameter_type_ids: &Vec, + block: &mut Block, + function: &mut Function, ) { match statement { - crate::Statement::Return { value } => match function.return_type { - Some(ty) => { - let expression = &function.expressions[value.unwrap()]; - let (id, _) = self - .write_expression( - ir_module, - function, - expression, - output, - parameter_type_ids, - ) + crate::Statement::Return { value } => match ir_function.return_type { + Some(_) => { + let expression = &ir_function.expressions[value.unwrap()]; + let (id, ty) = self + .write_expression(ir_module, ir_function, expression, block, function) .unwrap(); - output.push(self.instruction_return_value(id)) + + let id = match expression { + crate::Expression::LocalVariable(_) => { + let load_id = self.generate_id(); + let value_ty_id = self + .get_type_id(&ir_module.types, LookupType::Handle(ty.unwrap())); + block.body.push(self.instruction_load( + value_ty_id, + load_id, + id, + None, + )); + load_id + } + _ => id + }; + block.termination = Some(self.instruction_return_value(id)); } - None => output.push(self.instruction_return()), + None => block.termination = Some(self.instruction_return()), }, crate::Statement::Store { pointer, value } => { - let pointer_expression = &function.expressions[*pointer]; - let value_expression = &function.expressions[*value]; + let pointer_expression = &ir_function.expressions[*pointer]; + let value_expression = &ir_function.expressions[*value]; let (pointer_id, _) = self - .write_expression( - ir_module, - function, - pointer_expression, - output, - parameter_type_ids, - ) + .write_expression(ir_module, ir_function, pointer_expression, block, function) .unwrap(); - let (value_id, _) = self - .write_expression( - ir_module, - function, - value_expression, - output, - parameter_type_ids, - ) + let (value_id, value_ty) = self + .write_expression(ir_module, ir_function, value_expression, block, function) .unwrap(); - output.push(self.instruction_store(pointer_id, value_id)); + let value_id = match value_expression { + crate::Expression::LocalVariable(_) => { + let load_id = self.generate_id(); + let value_ty_id = self + .get_type_id(&ir_module.types, LookupType::Handle(value_ty.unwrap())); + block.body.push(self.instruction_load( + value_ty_id, + load_id, + value_id, + None, + )); + load_id + } + _ => value_id, + }; + + block + .body + .push(self.instruction_store(pointer_id, value_id)); } - _ => unimplemented!(), + crate::Statement::Empty => {} + _ => unimplemented!("{:?}", statement), } } @@ -1342,19 +1458,46 @@ impl Writer { annotation.to_words(&mut self.logical_layout.annotations); } - for (handle, function) in ir_module.functions.iter() { - let mut function_instructions: Vec = vec![]; - let id = self.generate_id(); + for (handle, ir_function) in ir_module.functions.iter() { + let mut function = Function::new(); + + for (_, variable) in ir_function.local_variables.iter() { + let id = self.generate_id(); + + let init_word = match variable.init { + Some(exp) => match &ir_function.expressions[exp] { + crate::Expression::Constant(handle) => { + Some(self.get_constant_id(*handle, ir_module)) + } + _ => unreachable!(), + }, + None => None, + }; + + let pointer_id = self.get_pointer_id( + &ir_module.types, + variable.ty, + spirv::StorageClass::Function, + ); + function.variables.push(LocalVariable { + id, + name: variable.name.clone(), + instruction: self.instruction_variable( + pointer_id, + id, + spirv::StorageClass::Function, + init_word, + ), + }); + } let return_type_id = - self.get_function_return_type(function.return_type, &ir_module.types); - let mut parameter_type_ids = Vec::with_capacity(function.parameter_types.len()); + self.get_function_return_type(ir_function.return_type, &ir_module.types); + let mut parameter_type_ids = Vec::with_capacity(ir_function.parameter_types.len()); - let mut function_parameter_ids = vec![]; let mut function_parameter_pointer_ids = vec![]; - let mut function_parameter_instructions = vec![]; - for parameter_type in function.parameter_types.iter() { + for parameter_type in ir_function.parameter_types.iter() { let id = self.generate_id(); let pointer_id = self.get_pointer_id( &ir_module.types, @@ -1362,12 +1505,12 @@ impl Writer { spirv::StorageClass::Function, ); - function_parameter_ids.push(id); function_parameter_pointer_ids.push(pointer_id); - function_parameter_instructions - .push(self.instruction_function_parameter(pointer_id, id)); parameter_type_ids .push(self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type))); + function + .parameters + .push(self.instruction_function_parameter(pointer_id, id)); } let lookup_function_type = LookupFunctionType { @@ -1375,38 +1518,35 @@ impl Writer { parameter_type_ids, }; - let type_function_id = + let id = self.generate_id(); + let function_type = self.get_function_type(lookup_function_type, function_parameter_pointer_ids); - - function_instructions.push(self.instruction_function( + function.signature = Some(self.instruction_function( return_type_id, id, spirv::FunctionControl::empty(), - type_function_id, + function_type, )); - function_instructions.append(&mut function_parameter_instructions); self.lookup_function.insert(handle, id); + let mut block = Block::new(); let id = self.generate_id(); - function_instructions.push(self.instruction_label(id)); - - for block in function.body.iter() { - let mut output: Vec = vec![]; - self.write_function_block( + block.label = Some(self.instruction_label(id)); + for statement in ir_function.body.iter() { + self.write_function_statement( ir_module, - function, - &block, - &mut output, - &function_parameter_ids, + ir_function, + &statement, + &mut block, + &mut function, ); - function_instructions.append(&mut output); } + function.blocks.push(block); - function_instructions.push(self.instruction_function_end()); - for instruction in function_instructions.iter() { - instruction.to_words(&mut self.logical_layout.function_definitions); - } + function.to_words(&mut self.logical_layout.function_definitions); + self.instruction_function_end() + .to_words(&mut self.logical_layout.function_definitions); } for entry_point in ir_module.entry_points.iter() { From 2cdb54e266527b67209d1280c654be6428a86b9c Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 2 Sep 2020 07:34:39 +0200 Subject: [PATCH 0184/2212] [glsl-new] Update last exprs to ExpressionRule (#173) * [glsl-new] Update last exprs to ExpressionRule Refactor out binary_expr to keep parser.rs 'small' and readable * [glsl-new] Change binary_expr to method on Program * [glsl-new] Make binary_expr a proper method --- src/front/glsl_new/ast.rs | 17 +++++++- src/front/glsl_new/parser.rs | 82 ++++++++++++------------------------ 2 files changed, 43 insertions(+), 56 deletions(-) diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl_new/ast.rs index 47feacac6..2919ef503 100644 --- a/src/front/glsl_new/ast.rs +++ b/src/front/glsl_new/ast.rs @@ -1,6 +1,6 @@ use crate::{ - Arena, Binding, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, - Interpolation, LocalVariable, ShaderStage, Statement, StorageClass, Type, + Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, GlobalVariable, + Handle, Interpolation, LocalVariable, ShaderStage, Statement, StorageClass, Type, }; #[derive(Debug)] @@ -39,6 +39,19 @@ impl Program { }, } } + + pub fn binary_expr( + &mut self, + op: BinaryOperator, + left: ExpressionRule, + right: ExpressionRule, + ) -> ExpressionRule { + ExpressionRule::from_expression(self.context.expressions.append(Expression::Binary { + op, + left: left.expression, + right: right.expression, + })) + } } #[derive(Debug)] diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 0fdec7770..43bed09b6 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -68,14 +68,14 @@ pomelo! { %type function_call_header FunctionCall; %type function_identifier FunctionCallKind; - %type multiplicative_expression Handle; - %type additive_expression Handle; - %type shift_expression Handle; - %type relational_expression Handle; - %type equality_expression Handle; - %type and_expression Handle; - %type exclusive_or_expression Handle; - %type inclusive_or_expression Handle; + %type multiplicative_expression ExpressionRule; + %type additive_expression ExpressionRule; + %type shift_expression ExpressionRule; + %type relational_expression ExpressionRule; + %type equality_expression ExpressionRule; + %type and_expression ExpressionRule; + %type exclusive_or_expression ExpressionRule; + %type inclusive_or_expression ExpressionRule; %type logical_and_expression ExpressionRule; %type logical_xor_expression ExpressionRule; %type logical_or_expression ExpressionRule; @@ -332,86 +332,66 @@ pomelo! { unary_operator ::= Dash; unary_operator ::= Bang; unary_operator ::= Tilde; - multiplicative_expression ::= unary_expression(e) {e.expression} + multiplicative_expression ::= unary_expression; multiplicative_expression ::= multiplicative_expression(left) Star unary_expression(right) { - extra.context.expressions.append(Expression::Binary{ - op: BinaryOperator::Multiply, - left, - right: right.expression, - }) + extra.binary_expr(BinaryOperator::Multiply, left, right) } multiplicative_expression ::= multiplicative_expression(left) Slash unary_expression(right) { - extra.context.expressions.append(Expression::Binary{ - op: BinaryOperator::Divide, - left, - right: right.expression - }) + extra.binary_expr(BinaryOperator::Divide, left, right) } multiplicative_expression ::= multiplicative_expression(left) Percent unary_expression(right) { - extra.context.expressions.append(Expression::Binary{ - op: BinaryOperator::Modulo, - left, - right: right.expression, - }) + extra.binary_expr(BinaryOperator::Modulo, left, right) } additive_expression ::= multiplicative_expression; additive_expression ::= additive_expression(left) Plus multiplicative_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Add, left, right}) + extra.binary_expr(BinaryOperator::Add, left, right) } additive_expression ::= additive_expression(left) Dash multiplicative_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Subtract, left, right}) + extra.binary_expr(BinaryOperator::Subtract, left, right) } shift_expression ::= additive_expression; shift_expression ::= shift_expression(left) LeftOp additive_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::ShiftLeftLogical, left, right}) + extra.binary_expr(BinaryOperator::ShiftLeftLogical, left, right) } shift_expression ::= shift_expression(left) RightOp additive_expression(right) { //TODO: when to use ShiftRightArithmetic - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::ShiftRightLogical, left, right}) + extra.binary_expr(BinaryOperator::ShiftRightLogical, left, right) } relational_expression ::= shift_expression; relational_expression ::= relational_expression(left) LeftAngle shift_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Less, left, right}) + extra.binary_expr(BinaryOperator::Less, left, right) } relational_expression ::= relational_expression(left) RightAngle shift_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Greater, left, right}) + extra.binary_expr(BinaryOperator::Greater, left, right) } relational_expression ::= relational_expression(left) LeOp shift_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::LessEqual, left, right}) + extra.binary_expr(BinaryOperator::LessEqual, left, right) } relational_expression ::= relational_expression(left) GeOp shift_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::GreaterEqual, left, right}) + extra.binary_expr(BinaryOperator::GreaterEqual, left, right) } equality_expression ::= relational_expression; equality_expression ::= equality_expression(left) EqOp relational_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::Equal, left, right}) + extra.binary_expr(BinaryOperator::Equal, left, right) } equality_expression ::= equality_expression(left) NeOp relational_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::NotEqual, left, right}) + extra.binary_expr(BinaryOperator::NotEqual, left, right) } and_expression ::= equality_expression; and_expression ::= and_expression(left) Ampersand equality_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::And, left, right}) + extra.binary_expr(BinaryOperator::And, left, right) } exclusive_or_expression ::= and_expression; exclusive_or_expression ::= exclusive_or_expression(left) Caret and_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::ExclusiveOr, left, right}) + extra.binary_expr(BinaryOperator::ExclusiveOr, left, right) } inclusive_or_expression ::= exclusive_or_expression; inclusive_or_expression ::= inclusive_or_expression(left) VerticalBar exclusive_or_expression(right) { - extra.context.expressions.append(Expression::Binary{op: BinaryOperator::InclusiveOr, left, right}) - } - logical_and_expression ::= inclusive_or_expression(e) { - ExpressionRule::from_expression(e) + extra.binary_expr(BinaryOperator::InclusiveOr, left, right) } + logical_and_expression ::= inclusive_or_expression; logical_and_expression ::= logical_and_expression(left) AndOp inclusive_or_expression(right) { - ExpressionRule::from_expression( - extra.context.expressions.append(Expression::Binary{ - op: BinaryOperator::LogicalAnd, - left: left.expression, - right - }) - ) + extra.binary_expr(BinaryOperator::LogicalAnd, left, right) } logical_xor_expression ::= logical_and_expression; logical_xor_expression ::= logical_xor_expression(left) XorOp logical_and_expression(right) { @@ -421,13 +401,7 @@ pomelo! { } logical_or_expression ::= logical_xor_expression; logical_or_expression ::= logical_or_expression(left) OrOp logical_xor_expression(right) { - ExpressionRule::from_expression( - extra.context.expressions.append(Expression::Binary{ - op: BinaryOperator::LogicalOr, - left: left.expression, - right: right.expression, - }) - ) + extra.binary_expr(BinaryOperator::LogicalOr, left, right) } conditional_expression ::= logical_or_expression; From a3bac5ee0f9ba68235c1ea9e1166f06e5a7e9065 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sun, 6 Sep 2020 06:35:59 +0200 Subject: [PATCH 0185/2212] [Spirv-out] Move instructions to own module (#174) * [spirv-out] Move instructions to own module * [spirv-out] Fix wrong function use of some instructions * [spirv-out] Update instruction parameters * [spirv-out] Update current instruction tests * [spirv-out] Order current instruction tests * [spirv-out] Add missing instruction tests --- src/back/spv/instructions.rs | 1229 ++++++++++++++++++++++++++++++++++ src/back/spv/mod.rs | 1 + src/back/spv/writer.rs | 961 +++++--------------------- 3 files changed, 1396 insertions(+), 795 deletions(-) create mode 100644 src/back/spv/instructions.rs diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs new file mode 100644 index 000000000..70aed08da --- /dev/null +++ b/src/back/spv/instructions.rs @@ -0,0 +1,1229 @@ +use crate::back::spv::{helpers, Instruction}; +use spirv::{Op, Word}; + +pub(super) enum Signedness { + Unsigned = 0, + Signed = 1, +} + +// +// Debug Instructions +// + +pub(super) fn instruction_source( + source_language: spirv::SourceLanguage, + version: u32, +) -> Instruction { + let mut instruction = Instruction::new(Op::Source); + instruction.add_operand(source_language as u32); + instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); + instruction +} + +pub(super) fn instruction_name(target_id: Word, name: &str) -> Instruction { + let mut instruction = Instruction::new(Op::Name); + instruction.add_operand(target_id); + instruction.add_operands(helpers::string_to_words(name)); + instruction +} + +// +// Annotation Instructions +// + +pub(super) fn instruction_decorate( + target_id: Word, + decoration: spirv::Decoration, + operands: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::Decorate); + instruction.add_operand(target_id); + instruction.add_operand(decoration as u32); + + for operand in operands { + instruction.add_operand(*operand) + } + + instruction +} + +// +// Extension Instructions +// + +pub(super) fn instruction_ext_inst_import(id: Word, name: &str) -> Instruction { + let mut instruction = Instruction::new(Op::ExtInstImport); + instruction.set_result(id); + instruction.add_operands(helpers::string_to_words(name)); + instruction +} + +// +// Mode-Setting Instructions +// + +pub(super) fn instruction_memory_model( + addressing_model: spirv::AddressingModel, + memory_model: spirv::MemoryModel, +) -> Instruction { + let mut instruction = Instruction::new(Op::MemoryModel); + instruction.add_operand(addressing_model as u32); + instruction.add_operand(memory_model as u32); + instruction +} + +pub(super) fn instruction_entry_point( + execution_model: spirv::ExecutionModel, + entry_point_id: Word, + name: &str, + interface_ids: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::EntryPoint); + instruction.add_operand(execution_model as u32); + instruction.add_operand(entry_point_id); + instruction.add_operands(helpers::string_to_words(name)); + + for interface_id in interface_ids { + instruction.add_operand(*interface_id); + } + + instruction +} + +pub(super) fn instruction_execution_mode( + entry_point_id: Word, + execution_mode: spirv::ExecutionMode, +) -> Instruction { + let mut instruction = Instruction::new(Op::ExecutionMode); + instruction.add_operand(entry_point_id); + instruction.add_operand(execution_mode as u32); + instruction +} + +pub(super) fn instruction_capability(capability: spirv::Capability) -> Instruction { + let mut instruction = Instruction::new(Op::Capability); + instruction.add_operand(capability as u32); + instruction +} + +// +// Type-Declaration Instructions +// + +pub(super) fn instruction_type_void(id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeVoid); + instruction.set_result(id); + instruction +} + +pub(super) fn instruction_type_bool(id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeBool); + instruction.set_result(id); + instruction +} + +pub(super) fn instruction_type_int(id: Word, width: Word, signedness: Signedness) -> Instruction { + let mut instruction = Instruction::new(Op::TypeInt); + instruction.set_result(id); + instruction.add_operand(width); + instruction.add_operand(signedness as u32); + instruction +} + +pub(super) fn instruction_type_float(id: Word, width: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeFloat); + instruction.set_result(id); + instruction.add_operand(width); + instruction +} + +pub(super) fn instruction_type_vector( + id: Word, + component_type_id: Word, + component_count: crate::VectorSize, +) -> Instruction { + let mut instruction = Instruction::new(Op::TypeVector); + instruction.set_result(id); + instruction.add_operand(component_type_id); + instruction.add_operand(component_count as u32); + instruction +} + +pub(super) fn instruction_type_matrix( + id: Word, + column_type_id: Word, + column_count: crate::VectorSize, +) -> Instruction { + let mut instruction = Instruction::new(Op::TypeMatrix); + instruction.set_result(id); + instruction.add_operand(column_type_id); + instruction.add_operand(column_count as u32); + instruction +} + +pub(super) fn instruction_type_image( + id: Word, + sampled_type_id: Word, + dim: spirv::Dim, + arrayed: bool, + image_class: crate::ImageClass, +) -> Instruction { + let mut instruction = Instruction::new(Op::TypeImage); + instruction.set_result(id); + instruction.add_operand(sampled_type_id); + instruction.add_operand(dim as u32); + + instruction.add_operand(match image_class { + crate::ImageClass::Depth => 1, + _ => 0, + }); + instruction.add_operand(arrayed as u32); + instruction.add_operand(match image_class { + crate::ImageClass::Multisampled => 1, + _ => 0, + }); + instruction.add_operand(match image_class { + crate::ImageClass::Sampled => 1, + _ => 0, + }); + + let (format, access) = match image_class { + crate::ImageClass::Storage(format, access) => { + let spv_format = match format { + crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8, + crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm, + crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui, + crate::StorageFormat::R8Sint => spirv::ImageFormat::R8i, + crate::StorageFormat::R16Uint => spirv::ImageFormat::R16ui, + crate::StorageFormat::R16Sint => spirv::ImageFormat::R16i, + crate::StorageFormat::R16Float => spirv::ImageFormat::R16f, + crate::StorageFormat::Rg8Unorm => spirv::ImageFormat::Rg8, + crate::StorageFormat::Rg8Snorm => spirv::ImageFormat::Rg8Snorm, + crate::StorageFormat::Rg8Uint => spirv::ImageFormat::Rg8ui, + crate::StorageFormat::Rg8Sint => spirv::ImageFormat::Rg8i, + crate::StorageFormat::R32Uint => spirv::ImageFormat::R32ui, + crate::StorageFormat::R32Sint => spirv::ImageFormat::R32i, + crate::StorageFormat::R32Float => spirv::ImageFormat::R32f, + crate::StorageFormat::Rg16Uint => spirv::ImageFormat::Rg16ui, + crate::StorageFormat::Rg16Sint => spirv::ImageFormat::Rg16i, + crate::StorageFormat::Rg16Float => spirv::ImageFormat::Rg16f, + crate::StorageFormat::Rgba8Unorm => spirv::ImageFormat::Rgba8, + crate::StorageFormat::Rgba8Snorm => spirv::ImageFormat::Rgba8Snorm, + crate::StorageFormat::Rgba8Uint => spirv::ImageFormat::Rgba8ui, + crate::StorageFormat::Rgba8Sint => spirv::ImageFormat::Rgba8i, + crate::StorageFormat::Rgb10a2Unorm => spirv::ImageFormat::Rgb10a2ui, + crate::StorageFormat::Rg11b10Float => spirv::ImageFormat::R11fG11fB10f, + crate::StorageFormat::Rg32Uint => spirv::ImageFormat::Rg32ui, + crate::StorageFormat::Rg32Sint => spirv::ImageFormat::Rg32i, + crate::StorageFormat::Rg32Float => spirv::ImageFormat::Rg32f, + crate::StorageFormat::Rgba16Uint => spirv::ImageFormat::Rgba16ui, + crate::StorageFormat::Rgba16Sint => spirv::ImageFormat::Rgba16i, + crate::StorageFormat::Rgba16Float => spirv::ImageFormat::Rgba16f, + crate::StorageFormat::Rgba32Uint => spirv::ImageFormat::Rgba32ui, + crate::StorageFormat::Rgba32Sint => spirv::ImageFormat::Rgba32i, + crate::StorageFormat::Rgba32Float => spirv::ImageFormat::Rgba32f, + }; + (spv_format, access) + } + _ => (spirv::ImageFormat::Unknown, crate::StorageAccess::empty()), + }; + + instruction.add_operand(format as u32); + // Access Qualifier + if !access.is_empty() { + instruction.add_operand(if access == crate::StorageAccess::all() { + 2 + } else if access.contains(crate::StorageAccess::STORE) { + 1 + } else { + 0 + }); + } + + instruction +} + +pub(super) fn instruction_type_sampler(id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeSampler); + instruction.set_result(id); + instruction +} + +pub(super) fn instruction_type_array( + id: Word, + element_type_id: Word, + length_id: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::TypeArray); + instruction.set_result(id); + instruction.add_operand(element_type_id); + instruction.add_operand(length_id); + instruction +} + +pub(super) fn instruction_type_runtime_array(id: Word, element_type_id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeRuntimeArray); + instruction.set_result(id); + instruction.add_operand(element_type_id); + instruction +} + +pub(super) fn instruction_type_struct(id: Word, member_ids: &[Word]) -> Instruction { + let mut instruction = Instruction::new(Op::TypeStruct); + instruction.set_result(id); + + for member_id in member_ids { + instruction.add_operand(*member_id) + } + + instruction +} + +pub(super) fn instruction_type_pointer( + id: Word, + storage_class: spirv::StorageClass, + type_id: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::TypePointer); + instruction.set_result(id); + instruction.add_operand(storage_class as u32); + instruction.add_operand(type_id); + instruction +} + +pub(super) fn instruction_type_function( + id: Word, + return_type_id: Word, + parameter_ids: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::TypeFunction); + instruction.set_result(id); + instruction.add_operand(return_type_id); + + for parameter_id in parameter_ids { + instruction.add_operand(*parameter_id); + } + + instruction +} + +// +// Constant-Creation Instructions +// + +pub(super) fn instruction_constant_true(result_type_id: Word, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::ConstantTrue); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction +} + +pub(super) fn instruction_constant_false(result_type_id: Word, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::ConstantFalse); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction +} + +pub(super) fn instruction_constant(result_type_id: Word, id: Word, values: &[Word]) -> Instruction { + let mut instruction = Instruction::new(Op::Constant); + instruction.set_type(result_type_id); + instruction.set_result(id); + + for value in values { + instruction.add_operand(*value); + } + + instruction +} + +pub(super) fn instruction_constant_composite( + result_type_id: Word, + id: Word, + constituent_ids: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::ConstantComposite); + instruction.set_type(result_type_id); + instruction.set_result(id); + + for constituent_id in constituent_ids { + instruction.add_operand(*constituent_id); + } + + instruction +} + +// +// Memory Instructions +// + +pub(super) fn instruction_variable( + result_type_id: Word, + id: Word, + storage_class: spirv::StorageClass, + initializer_id: Option, +) -> Instruction { + let mut instruction = Instruction::new(Op::Variable); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(storage_class as u32); + + if let Some(initializer_id) = initializer_id { + instruction.add_operand(initializer_id); + } + + instruction +} + +pub(super) fn instruction_load( + result_type_id: Word, + id: Word, + pointer_type_id: Word, + memory_access: Option, +) -> Instruction { + let mut instruction = Instruction::new(Op::Load); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(pointer_type_id); + + instruction.add_operand(if let Some(memory_access) = memory_access { + memory_access.bits() + } else { + spirv::MemoryAccess::NONE.bits() + }); + + instruction +} + +pub(super) fn instruction_store( + pointer_type_id: Word, + object_id: Word, + memory_access: Option, +) -> Instruction { + let mut instruction = Instruction::new(Op::Store); + instruction.add_operand(pointer_type_id); + instruction.add_operand(object_id); + + instruction.add_operand(if let Some(memory_access) = memory_access { + memory_access.bits() + } else { + spirv::MemoryAccess::NONE.bits() + }); + + instruction +} + +// +// Function Instructions +// + +pub(super) fn instruction_function( + return_type_id: Word, + id: Word, + function_control: spirv::FunctionControl, + function_type_id: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::Function); + instruction.set_type(return_type_id); + instruction.set_result(id); + instruction.add_operand(function_control.bits()); + instruction.add_operand(function_type_id); + instruction +} + +pub(super) fn instruction_function_parameter(result_type_id: Word, id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::FunctionParameter); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction +} + +pub(super) fn instruction_function_end() -> Instruction { + Instruction::new(Op::FunctionEnd) +} + +pub(super) fn instruction_function_call( + result_type_id: Word, + id: Word, + function_id: Word, + argument_ids: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::FunctionCall); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(function_id); + + for argument_id in argument_ids { + instruction.add_operand(*argument_id); + } + + instruction +} + +// +// Image Instructions +// + +// +// Conversion Instructions +// + +// +// Composite Instructions +// + +pub(super) fn instruction_composite_construct( + result_type_id: Word, + id: Word, + constituent_ids: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::CompositeConstruct); + instruction.set_type(result_type_id); + instruction.set_result(id); + + for constituent_id in constituent_ids { + instruction.add_operand(*constituent_id); + } + + instruction +} + +// +// Arithmetic Instructions +// + +pub(super) fn instruction_vector_times_scalar( + result_type_id: Word, + id: Word, + vector_type_id: Word, + scalar_type_id: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::VectorTimesScalar); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(vector_type_id); + instruction.add_operand(scalar_type_id); + instruction +} + +// +// Bit Instructions +// + +// +// Relational and Logical Instructions +// + +// +// Derivative Instructions +// + +// +// Control-Flow Instructions +// + +pub(super) fn instruction_label(id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::Label); + instruction.set_result(id); + instruction +} + +pub(super) fn instruction_return() -> Instruction { + Instruction::new(Op::Return) +} + +pub(super) fn instruction_return_value(value_id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::ReturnValue); + instruction.add_operand(value_id); + instruction +} + +// +// Atomic Instructions +// + +// +// Primitive Instructions +// + +#[cfg(test)] +mod tests { + use crate::back::spv::test_framework::*; + use spirv::*; + + #[test] + fn test_instruction_source() { + let version = 450; + let instruction = super::instruction_source(SourceLanguage::GLSL, version); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Source, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_name() { + let instruction = super::instruction_name(1, "Test"); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Name, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_decorate() { + let instruction = super::instruction_decorate(1, Decoration::Location, &[1]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Decorate, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_ext_inst_import() { + let import_name = "GLSL.std.450"; + let instruction = super::instruction_ext_inst_import(1, import_name); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ExtInstImport, + wc: 3, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_memory_model() { + let instruction = + super::instruction_memory_model(AddressingModel::Logical, MemoryModel::GLSL450); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::MemoryModel, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_entry_point() { + let instruction = + super::instruction_entry_point(spirv::ExecutionModel::Fragment, 1, "main", &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::EntryPoint, + wc: 4, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_execution_mode() { + let instruction = super::instruction_execution_mode(1, ExecutionMode::OriginUpperLeft); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ExecutionMode, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_capability() { + let instruction = super::instruction_capability(Capability::Shader); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Capability, + wc: 2, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_void() { + let instruction = super::instruction_type_void(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeVoid, + wc: 2, + type_id: false, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_bool() { + let instruction = super::instruction_type_bool(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeBool, + wc: 2, + type_id: false, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_int() { + let instruction = super::instruction_type_int(1, 32, super::Signedness::Signed); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeInt, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_float() { + let instruction = super::instruction_type_float(1, 32); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeFloat, + wc: 3, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_vector() { + let instruction = super::instruction_type_vector(1, 1, crate::VectorSize::Bi); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeVector, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_matrix() { + let instruction = super::instruction_type_matrix(1, 1, crate::VectorSize::Bi); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeMatrix, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_image() { + let instruction = super::instruction_type_image( + 1, + 1, + spirv::Dim::Dim3D, + true, + crate::ImageClass::Multisampled, + ); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeImage, + wc: 9, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_sampler() { + let instruction = super::instruction_type_sampler(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeSampler, + wc: 2, + type_id: false, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_array() { + let instruction = super::instruction_type_array(1, 1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeArray, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_runtime_array() { + let instruction = super::instruction_type_runtime_array(1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeRuntimeArray, + wc: 3, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_struct() { + let instruction = super::instruction_type_struct(1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeStruct, + wc: 2, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_pointer() { + let instruction = super::instruction_type_pointer(1, spirv::StorageClass::Function, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypePointer, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_type_function() { + let instruction = super::instruction_type_function(1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeFunction, + wc: 3, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_constant_true() { + let instruction = super::instruction_constant_true(1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ConstantTrue, + wc: 3, + type_id: true, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_constant_false() { + let instruction = super::instruction_constant_false(1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ConstantFalse, + wc: 3, + type_id: true, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_constant() { + let instruction = super::instruction_constant(1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Constant, + wc: 3, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_constant_composite() { + let instruction = super::instruction_constant_composite(1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ConstantComposite, + wc: 3, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_variable() { + let instruction = super::instruction_variable(1, 1, spirv::StorageClass::Function, Some(1)); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Variable, + wc: 4, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_load() { + let instruction = super::instruction_load(1, 1, 1, None); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Load, + wc: 4, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_store() { + let instruction = super::instruction_store(1, 1, None); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Store, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_function() { + let instruction = super::instruction_function(1, 1, spirv::FunctionControl::NONE, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Function, + wc: 5, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_function_parameter() { + let instruction = super::instruction_function_parameter(1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::FunctionParameter, + wc: 3, + type_id: true, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_function_end() { + let instruction = super::instruction_function_end(); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::FunctionEnd, + wc: 1, + type_id: false, + result_id: false, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_function_call() { + let instruction = super::instruction_function_call(1, 1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::FunctionCall, + wc: 4, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_composite_construct() { + let instruction = super::instruction_composite_construct(1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::CompositeConstruct, + wc: 3, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_vector_times_scalar() { + let instruction = super::instruction_vector_times_scalar(1, 1, 1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::VectorTimesScalar, + wc: 5, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_label() { + let instruction = super::instruction_label(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Label, + wc: 2, + type_id: false, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_return() { + let instruction = super::instruction_return(); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Return, + wc: 1, + type_id: false, + result_id: false, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + #[test] + fn test_instruction_return_value() { + let instruction = super::instruction_return_value(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ReturnValue, + wc: 2, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } +} diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 4c3ca3362..15f159835 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -1,4 +1,5 @@ mod helpers; +mod instructions; mod layout; mod writer; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 9f704dba4..91cbc9f87 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,6 +1,6 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ -use super::{helpers, Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; -use spirv::{Op, Word}; +use super::{Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; +use spirv::Word; use std::collections::hash_map::Entry; const BITS_PER_BYTE: crate::Bytes = 8; @@ -64,11 +64,6 @@ impl Function { } } -enum Signedness { - Unsigned = 0, - Signed = 1, -} - #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LocalType { Scalar { @@ -208,7 +203,7 @@ impl Writer { None => { let id = self.generate_id(); self.void_type = Some(id); - self.instruction_type_void(id) + super::instructions::instruction_type_void(id) .to_words(&mut self.logical_layout.declarations); id } @@ -236,7 +231,8 @@ impl Writer { Entry::Occupied(e) => *e.get(), _ => { let pointer_id = self.generate_id(); - let instruction = self.instruction_type_pointer(pointer_id, class, ty_id); + let instruction = + super::instructions::instruction_type_pointer(pointer_id, class, ty_id); instruction.to_words(&mut self.logical_layout.declarations); self.lookup_type.insert( LookupType::Local(LocalType::Pointer { @@ -252,80 +248,12 @@ impl Writer { } } - /// - /// Debug Instructions - /// - - fn instruction_source( - &self, - source_language: spirv::SourceLanguage, - version: u32, - ) -> Instruction { - let mut instruction = Instruction::new(Op::Source); - instruction.add_operand(source_language as u32); - instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); - instruction - } - - fn instruction_name(&self, target_id: Word, name: &str) -> Instruction { - let mut instruction = Instruction::new(Op::Name); - instruction.set_result(target_id); - instruction.add_operands(helpers::string_to_words(name)); - instruction - } - - /// - /// Annotation Instructions - /// - - fn instruction_decorate( - &self, - target_id: Word, - decoration: spirv::Decoration, - operands: &[Word], - ) -> Instruction { - let mut instruction = Instruction::new(Op::Decorate); - instruction.add_operand(target_id); - instruction.add_operand(decoration as u32); - instruction.add_operands(Vec::from(operands)); - instruction - } - - /// - /// Extension Instructions - /// - - fn instruction_ext_inst_import(&mut self, name: &str) -> Instruction { - let mut instruction = Instruction::new(Op::ExtInstImport); - let id = self.generate_id(); - instruction.set_result(id); - instruction.add_operands(helpers::string_to_words(name)); - instruction - } - - /// - /// Mode-Setting Instructions - /// - - fn instruction_memory_model(&mut self) -> Instruction { - let mut instruction = Instruction::new(Op::MemoryModel); - let addressing_model = spirv::AddressingModel::Logical; - let memory_model = spirv::MemoryModel::GLSL450; - self.try_add_capabilities(addressing_model.required_capabilities()); - self.try_add_capabilities(memory_model.required_capabilities()); - - instruction.add_operand(addressing_model as u32); - instruction.add_operand(memory_model as u32); - instruction - } - - fn instruction_entry_point( + // TODO Move to instructions module + fn write_entry_point( &mut self, entry_point: &crate::EntryPoint, ir_module: &crate::Module, ) -> Instruction { - let mut instruction = Instruction::new(Op::EntryPoint); - let function_id = *self.lookup_function.get(&entry_point.function).unwrap(); let exec_model = match entry_point.stage { @@ -334,10 +262,7 @@ impl Writer { crate::ShaderStage::Compute { .. } => spirv::ExecutionModel::GLCompute, }; - instruction.add_operand(exec_model as u32); - instruction.add_operand(function_id); - instruction.add_operands(helpers::string_to_words(entry_point.name.as_str())); - + let mut interface_ids = vec![]; let function = &ir_module.functions[entry_point.function]; for ((handle, _), &usage) in ir_module .global_variables @@ -350,7 +275,7 @@ impl Writer { &ir_module.global_variables, handle, ); - instruction.add_operand(id); + interface_ids.push(id); } } @@ -360,469 +285,42 @@ impl Writer { crate::ShaderStage::Fragment { .. } => { let execution_mode = spirv::ExecutionMode::OriginUpperLeft; self.try_add_capabilities(execution_mode.required_capabilities()); - self.instruction_execution_mode(function_id, execution_mode) + super::instructions::instruction_execution_mode(function_id, execution_mode) .to_words(&mut self.logical_layout.execution_modes); } crate::ShaderStage::Compute { .. } => {} } if self.writer_flags.contains(WriterFlags::DEBUG) { - self.debugs - .push(self.instruction_name(function_id, entry_point.name.as_str())); + self.debugs.push(super::instructions::instruction_name( + function_id, + entry_point.name.as_str(), + )); } - instruction + super::instructions::instruction_entry_point( + exec_model, + function_id, + entry_point.name.as_str(), + interface_ids.as_slice(), + ) } - fn instruction_execution_mode( - &self, - function_id: Word, - execution_mode: spirv::ExecutionMode, - ) -> Instruction { - let mut instruction = Instruction::new(Op::ExecutionMode); - instruction.add_operand(function_id); - instruction.add_operand(execution_mode as u32); - instruction - } - - fn instruction_capability(&self, capability: spirv::Capability) -> Instruction { - let mut instruction = Instruction::new(Op::Capability); - instruction.add_operand(capability as u32); - instruction - } - - /// - /// Type-Declaration Instructions - /// - - fn instruction_type_void(&self, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeVoid); - instruction.set_result(id); - instruction - } - - fn instruction_type_bool(&self, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeBool); - instruction.set_result(id); - instruction - } - - fn instruction_type_int(&self, id: Word, width: Word, signedness: Signedness) -> Instruction { - let mut instruction = Instruction::new(Op::TypeInt); - instruction.set_result(id); - instruction.add_operand(width); - instruction.add_operand(signedness as u32); - instruction - } - - fn instruction_type_float(&self, id: Word, width: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeFloat); - instruction.set_result(id); - instruction.add_operand(width); - instruction - } - - fn instruction_type_vector( - &self, - id: Word, - component_type_id: Word, - component_count: crate::VectorSize, - ) -> Instruction { - let mut instruction = Instruction::new(Op::TypeVector); - instruction.set_result(id); - instruction.add_operand(component_type_id); - instruction.add_operand(component_count as u32); - instruction - } - - fn instruction_type_matrix( - &self, - id: Word, - column_type_id: Word, - column_count: crate::VectorSize, - ) -> Instruction { - let mut instruction = Instruction::new(Op::TypeMatrix); - instruction.set_result(id); - instruction.add_operand(column_type_id); - instruction.add_operand(column_count as u32); - instruction - } - - fn instruction_type_image( - &self, - id: Word, - sampled_type_id: Word, - dim: spirv::Dim, - arrayed: bool, - class: crate::ImageClass, - ) -> Instruction { - let mut instruction = Instruction::new(Op::TypeImage); - instruction.set_result(id); - instruction.add_operand(sampled_type_id); - instruction.add_operand(dim as u32); - - instruction.add_operand(match class { - crate::ImageClass::Depth => 1, - _ => 0, - }); - instruction.add_operand(if arrayed { 1 } else { 0 }); - instruction.add_operand(match class { - crate::ImageClass::Multisampled => 1, - _ => 0, - }); - instruction.add_operand(match class { - crate::ImageClass::Sampled => 1, - _ => 0, - }); - - let (format, access) = match class { - crate::ImageClass::Storage(format, access) => { - let spv_format = match format { - crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8, - crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm, - crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui, - crate::StorageFormat::R8Sint => spirv::ImageFormat::R8i, - crate::StorageFormat::R16Uint => spirv::ImageFormat::R16ui, - crate::StorageFormat::R16Sint => spirv::ImageFormat::R16i, - crate::StorageFormat::R16Float => spirv::ImageFormat::R16f, - crate::StorageFormat::Rg8Unorm => spirv::ImageFormat::Rg8, - crate::StorageFormat::Rg8Snorm => spirv::ImageFormat::Rg8Snorm, - crate::StorageFormat::Rg8Uint => spirv::ImageFormat::Rg8ui, - crate::StorageFormat::Rg8Sint => spirv::ImageFormat::Rg8i, - crate::StorageFormat::R32Uint => spirv::ImageFormat::R32ui, - crate::StorageFormat::R32Sint => spirv::ImageFormat::R32i, - crate::StorageFormat::R32Float => spirv::ImageFormat::R32f, - crate::StorageFormat::Rg16Uint => spirv::ImageFormat::Rg16ui, - crate::StorageFormat::Rg16Sint => spirv::ImageFormat::Rg16i, - crate::StorageFormat::Rg16Float => spirv::ImageFormat::Rg16f, - crate::StorageFormat::Rgba8Unorm => spirv::ImageFormat::Rgba8, - crate::StorageFormat::Rgba8Snorm => spirv::ImageFormat::Rgba8Snorm, - crate::StorageFormat::Rgba8Uint => spirv::ImageFormat::Rgba8ui, - crate::StorageFormat::Rgba8Sint => spirv::ImageFormat::Rgba8i, - crate::StorageFormat::Rgb10a2Unorm => spirv::ImageFormat::Rgb10a2ui, - crate::StorageFormat::Rg11b10Float => spirv::ImageFormat::R11fG11fB10f, - crate::StorageFormat::Rg32Uint => spirv::ImageFormat::Rg32ui, - crate::StorageFormat::Rg32Sint => spirv::ImageFormat::Rg32i, - crate::StorageFormat::Rg32Float => spirv::ImageFormat::Rg32f, - crate::StorageFormat::Rgba16Uint => spirv::ImageFormat::Rgba16ui, - crate::StorageFormat::Rgba16Sint => spirv::ImageFormat::Rgba16i, - crate::StorageFormat::Rgba16Float => spirv::ImageFormat::Rgba16f, - crate::StorageFormat::Rgba32Uint => spirv::ImageFormat::Rgba32ui, - crate::StorageFormat::Rgba32Sint => spirv::ImageFormat::Rgba32i, - crate::StorageFormat::Rgba32Float => spirv::ImageFormat::Rgba32f, - }; - (spv_format, access) - } - _ => (spirv::ImageFormat::Unknown, crate::StorageAccess::empty()), - }; - - instruction.add_operand(format as u32); - // Access Qualifier - if !access.is_empty() { - instruction.add_operand(if access == crate::StorageAccess::all() { - 2 - } else if access.contains(crate::StorageAccess::STORE) { - 1 - } else { - 0 - }); - } - - instruction - } - - fn instruction_type_sampler(&self, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeSampler); - instruction.set_result(id); - instruction - } - - fn instruction_type_array( - &self, - id: Word, - element_type_id: Word, - length_id: Word, - ) -> Instruction { - let mut instruction = Instruction::new(Op::TypeArray); - instruction.set_result(id); - instruction.add_operand(element_type_id); - instruction.add_operand(length_id); - instruction - } - - fn instruction_type_runtime_array(&self, id: Word, element_type_id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeRuntimeArray); - instruction.set_result(id); - instruction.add_operand(element_type_id); - instruction - } - - fn instruction_type_struct(&self, id: Word, member_ids: Vec) -> Instruction { - let mut instruction = Instruction::new(Op::TypeStruct); - instruction.set_result(id); - instruction.add_operands(member_ids); - instruction - } - - fn instruction_type_pointer( - &self, - id: Word, - storage_class: spirv::StorageClass, - type_id: Word, - ) -> Instruction { - let mut instruction = Instruction::new(Op::TypePointer); - instruction.set_result(id); - instruction.add_operand(storage_class as u32); - instruction.add_operand(type_id); - instruction - } - - fn instruction_type_function( - &self, - id: Word, - return_type_id: Word, - parameter_ids: Vec, - ) -> Instruction { - let mut instruction = Instruction::new(Op::TypeFunction); - instruction.set_result(id); - instruction.add_operand(return_type_id); - instruction.add_operands(parameter_ids); - instruction - } - - /// - /// Constant-Creation Instructions - /// - - fn instruction_constant_true(&self, scalar_constant_id: Word, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::ConstantTrue); - instruction.set_type(scalar_constant_id); - instruction.set_result(id); - instruction - } - - fn instruction_constant_false(&self, scalar_constant_id: Word, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::ConstantFalse); - instruction.set_type(scalar_constant_id); - instruction.set_result(id); - instruction - } - - fn instruction_constant( - &self, - scalar_constant_id: Word, - id: Word, - values: &[Word], - ) -> Instruction { - let mut instruction = Instruction::new(Op::Constant); - instruction.set_type(scalar_constant_id); - instruction.set_result(id); - for value in values { - instruction.add_operand(*value); - } - instruction - } - - fn instruction_constant_composite( - &self, - composite_type_id: Word, - id: Word, - constituent_ids: Vec, - ) -> Instruction { - let mut instruction = Instruction::new(Op::ConstantComposite); - instruction.set_type(composite_type_id); - instruction.set_result(id); - instruction.add_operands(constituent_ids); - instruction - } - - /// - /// Memory Instructions - /// - - fn instruction_variable( - &self, - result_type_id: Word, - result_id: Word, - storage_class: spirv::StorageClass, - initializer_id: Option, - ) -> Instruction { - let mut instruction = Instruction::new(Op::Variable); - instruction.set_type(result_type_id); - instruction.set_result(result_id); - instruction.add_operand(storage_class as u32); - - if let Some(initializer_id) = initializer_id { - instruction.add_operand(initializer_id); - } - - instruction - } - - fn instruction_load( - &self, - type_id: Word, - id: Word, - pointer_type_id: Word, - memory_access: Option, - ) -> Instruction { - let mut instruction = Instruction::new(Op::Load); - instruction.set_type(type_id); - instruction.set_result(id); - instruction.add_operand(pointer_type_id); - - instruction.add_operand(if let Some(memory_access) = memory_access { - memory_access.bits() - } else { - spirv::MemoryAccess::NONE.bits() - }); - - instruction - } - - fn instruction_store(&self, pointer_type_id: Word, object_id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::Store); - instruction.set_type(pointer_type_id); - instruction.add_operand(object_id); - instruction - } - - /// - /// Function Instructions - /// - - fn instruction_function( - &self, - return_type_id: Word, - id: Word, - function_control: spirv::FunctionControl, - function_type_id: Word, - ) -> Instruction { - let mut instruction = Instruction::new(Op::Function); - instruction.set_type(return_type_id); - instruction.set_result(id); - instruction.add_operand(function_control.bits()); - instruction.add_operand(function_type_id); - instruction - } - - fn instruction_function_parameter(&self, result_type_id: Word, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::FunctionParameter); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction - } - - fn instruction_function_end(&self) -> Instruction { - Instruction::new(Op::FunctionEnd) - } - - fn instruction_function_call( - &self, - result_type_id: Word, - id: Word, - function_id: Word, - argument_ids: Vec, - ) -> Instruction { - let mut instruction = Instruction::new(Op::FunctionCall); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(function_id); - instruction.add_operands(argument_ids); - instruction - } - - /// - /// Image Instructions - /// - - /// - /// Conversion Instructions - /// - - /// - /// Composite Instructions - /// - - fn instruction_composite_construct( - &self, - composite_type_id: Word, - id: Word, - constituent_ids: Vec, - ) -> Instruction { - let mut instruction = Instruction::new(Op::CompositeConstruct); - instruction.set_type(composite_type_id); - instruction.set_result(id); - instruction.add_operands(constituent_ids); - instruction - } - - /// - /// Arithmetic Instructions - /// - - fn instruction_vector_times_scalar( - &self, - float_type_id: Word, - id: Word, - vector_type_id: Word, - scalar_type_id: Word, - ) -> Instruction { - let mut instruction = Instruction::new(Op::VectorTimesScalar); - instruction.set_type(float_type_id); - instruction.set_result(id); - instruction.add_operand(vector_type_id); - instruction.add_operand(scalar_type_id); - instruction - } - - /// - /// Bit Instructions - /// - - /// - /// Relational and Logical Instructions - /// - - /// - /// Derivative Instructions - /// - - /// - /// Control-Flow Instructions - /// - - fn instruction_label(&self, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::Label); - instruction.set_result(id); - instruction - } - - fn instruction_return(&self) -> Instruction { - Instruction::new(Op::Return) - } - - fn instruction_return_value(&self, value_id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::ReturnValue); - instruction.add_operand(value_id); - instruction - } - - /// - /// Atomic Instructions - /// - - /// - /// Primitive Instructions - /// - fn write_scalar(&self, id: Word, kind: crate::ScalarKind, width: crate::Bytes) -> Instruction { let bits = (width * BITS_PER_BYTE) as u32; match kind { - crate::ScalarKind::Sint => self.instruction_type_int(id, bits, Signedness::Signed), - crate::ScalarKind::Uint => self.instruction_type_int(id, bits, Signedness::Unsigned), - crate::ScalarKind::Float => self.instruction_type_float(id, bits), - crate::ScalarKind::Bool => self.instruction_type_bool(id), + crate::ScalarKind::Sint => super::instructions::instruction_type_int( + id, + bits, + super::instructions::Signedness::Signed, + ), + crate::ScalarKind::Uint => super::instructions::instruction_type_int( + id, + bits, + super::instructions::Signedness::Unsigned, + ), + crate::ScalarKind::Float => super::instructions::instruction_type_float(id, bits), + crate::ScalarKind::Bool => super::instructions::instruction_type_bool(id), } } @@ -849,7 +347,7 @@ impl Writer { LocalType::Scalar { kind, width } => self.write_scalar(id, kind, width), LocalType::Vector { size, .. } => { let scalar_id = self.get_type_id(arena, LookupType::Local(local_ty)); - self.instruction_type_vector(id, scalar_id, size) + super::instructions::instruction_type_vector(id, scalar_id, size) } LocalType::Pointer { .. } => unimplemented!(), }; @@ -880,7 +378,7 @@ impl Writer { LookupType::Local(LocalType::Vector { size, kind, width }), id, ); - self.instruction_type_vector(id, scalar_id, size) + super::instructions::instruction_type_vector(id, scalar_id, size) } crate::TypeInner::Matrix { columns, @@ -896,7 +394,7 @@ impl Writer { width, }), ); - self.instruction_type_matrix(id, vector_id, columns) + super::instructions::instruction_type_matrix(id, vector_id, columns) } crate::TypeInner::Image { kind, @@ -914,24 +412,29 @@ impl Writer { ); let dim = map_dim(dim); self.try_add_capabilities(dim.required_capabilities()); - self.instruction_type_image(id, type_id, dim, arrayed, class) + super::instructions::instruction_type_image(id, type_id, dim, arrayed, class) + } + crate::TypeInner::Sampler { comparison: _ } => { + super::instructions::instruction_type_sampler(id) } - crate::TypeInner::Sampler { comparison: _ } => self.instruction_type_sampler(id), crate::TypeInner::Array { size, stride, .. } => { if let Some(array_stride) = stride { - self.annotations.push(self.instruction_decorate( - id, - spirv::Decoration::ArrayStride, - &[array_stride.get()], - )); + self.annotations + .push(super::instructions::instruction_decorate( + id, + spirv::Decoration::ArrayStride, + &[array_stride.get()], + )); } let type_id = self.get_type_id(arena, LookupType::Handle(handle)); match size { crate::ArraySize::Static(length) => { - self.instruction_type_array(id, type_id, length) + super::instructions::instruction_type_array(id, type_id, length) + } + crate::ArraySize::Dynamic => { + super::instructions::instruction_type_runtime_array(id, type_id) } - crate::ArraySize::Dynamic => self.instruction_type_runtime_array(id, type_id), } } crate::TypeInner::Struct { ref members } => { @@ -940,7 +443,7 @@ impl Writer { let member_id = self.get_type_id(arena, LookupType::Handle(member.ty)); member_ids.push(member_id); } - self.instruction_type_struct(id, member_ids) + super::instructions::instruction_type_struct(id, member_ids.as_slice()) } crate::TypeInner::Pointer { base, class } => { let type_id = self.get_type_id(arena, LookupType::Handle(base)); @@ -951,7 +454,11 @@ impl Writer { }), id, ); - self.instruction_type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) + super::instructions::instruction_type_pointer( + id, + self.parse_to_spirv_storage_class(class), + type_id, + ) } }; @@ -977,10 +484,10 @@ impl Writer { let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { - 4 => self.instruction_constant(type_id, id, &[val as u32]), + 4 => super::instructions::instruction_constant(type_id, id, &[val as u32]), 8 => { let (low, high) = ((val >> 32) as u32, val as u32); - self.instruction_constant(type_id, id, &[low, high]) + super::instructions::instruction_constant(type_id, id, &[low, high]) } _ => unreachable!(), }, @@ -994,10 +501,10 @@ impl Writer { let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { - 4 => self.instruction_constant(type_id, id, &[val as u32]), + 4 => super::instructions::instruction_constant(type_id, id, &[val as u32]), 8 => { let (low, high) = ((val >> 32) as u32, val as u32); - self.instruction_constant(type_id, id, &[low, high]) + super::instructions::instruction_constant(type_id, id, &[low, high]) } _ => unreachable!(), }, @@ -1012,11 +519,15 @@ impl Writer { let instruction = match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { - 4 => self.instruction_constant(type_id, id, &[(val as f32).to_bits()]), + 4 => super::instructions::instruction_constant( + type_id, + id, + &[(val as f32).to_bits()], + ), 8 => { let bits = f64::to_bits(val); let (low, high) = ((bits >> 32) as u32, bits as u32); - self.instruction_constant(type_id, id, &[low, high]) + super::instructions::instruction_constant(type_id, id, &[low, high]) } _ => unreachable!(), }, @@ -1028,9 +539,9 @@ impl Writer { let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); let instruction = if val { - self.instruction_constant_true(type_id, id) + super::instructions::instruction_constant_true(type_id, id) } else { - self.instruction_constant_false(type_id, id) + super::instructions::instruction_constant_false(type_id, id) }; (instruction, id) @@ -1043,7 +554,11 @@ impl Writer { } let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); - let instruction = self.instruction_constant_composite(type_id, id, constituent_ids); + let instruction = super::instructions::instruction_constant_composite( + type_id, + id, + constituent_ids.as_slice(), + ); (instruction, id) } } @@ -1061,11 +576,13 @@ impl Writer { self.try_add_capabilities(class.required_capabilities()); let pointer_id = self.get_pointer_id(arena, global_variable.ty, class); - let instruction = self.instruction_variable(pointer_id, id, class, None); + let instruction = super::instructions::instruction_variable(pointer_id, id, class, None); if self.writer_flags.contains(WriterFlags::DEBUG) { - self.debugs - .push(self.instruction_name(id, global_variable.name.as_ref().unwrap().as_str())); + self.debugs.push(super::instructions::instruction_name( + id, + global_variable.name.as_ref().unwrap().as_str(), + )); } if let Some(interpolation) = global_variable.interpolation { @@ -1079,29 +596,36 @@ impl Writer { }; if let Some(decoration) = decoration { self.annotations - .push(self.instruction_decorate(id, decoration, &[])); + .push(super::instructions::instruction_decorate( + id, + decoration, + &[], + )); } } match global_variable.binding.as_ref().unwrap() { crate::Binding::Location(location) => { - self.annotations.push(self.instruction_decorate( - id, - spirv::Decoration::Location, - &[*location], - )); + self.annotations + .push(super::instructions::instruction_decorate( + id, + spirv::Decoration::Location, + &[*location], + )); } crate::Binding::Descriptor { set, binding } => { - self.annotations.push(self.instruction_decorate( - id, - spirv::Decoration::DescriptorSet, - &[*set], - )); - self.annotations.push(self.instruction_decorate( - id, - spirv::Decoration::Binding, - &[*binding], - )); + self.annotations + .push(super::instructions::instruction_decorate( + id, + spirv::Decoration::DescriptorSet, + &[*set], + )); + self.annotations + .push(super::instructions::instruction_decorate( + id, + spirv::Decoration::Binding, + &[*binding], + )); } crate::Binding::BuiltIn(built_in) => { let built_in = match built_in { @@ -1122,11 +646,12 @@ impl Writer { crate::BuiltIn::WorkGroupId => spirv::BuiltIn::WorkgroupId, }; - self.annotations.push(self.instruction_decorate( - id, - spirv::Decoration::BuiltIn, - &[built_in as u32], - )); + self.annotations + .push(super::instructions::instruction_decorate( + id, + spirv::Decoration::BuiltIn, + &[built_in as u32], + )); } } @@ -1148,10 +673,10 @@ impl Writer { Entry::Occupied(e) => *e.get(), _ => { let id = self.generate_id(); - let instruction = self.instruction_type_function( + let instruction = super::instructions::instruction_type_function( id, lookup_function_type.return_type_id, - parameter_pointer_ids, + parameter_pointer_ids.as_slice(), ); instruction.to_words(&mut self.logical_layout.declarations); self.lookup_function_type.insert(lookup_function_type, id); @@ -1196,8 +721,11 @@ impl Writer { constituent_ids.push(component_id); } - let instruction = - self.instruction_composite_construct(type_id, id, constituent_ids); + let instruction = super::instructions::instruction_composite_construct( + type_id, + id, + constituent_ids.as_slice(), + ); block.body.push(instruction); Some((id, Some(*ty))) } @@ -1258,11 +786,15 @@ impl Writer { }; let load_id = self.generate_id(); - let load_instruction = - self.instruction_load(result_type_id, load_id, vector_id, None); + let load_instruction = super::instructions::instruction_load( + result_type_id, + load_id, + vector_id, + None, + ); block.body.push(load_instruction); - let instruction = self.instruction_vector_times_scalar( + let instruction = super::instructions::instruction_vector_times_scalar( result_type_id, id, load_id, @@ -1294,7 +826,7 @@ impl Writer { let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*handle)); let load_id = self.generate_id(); - block.body.push(self.instruction_load( + block.body.push(super::instructions::instruction_load( type_id, load_id, function.parameters[*index as usize].result_id.unwrap(), @@ -1328,26 +860,32 @@ impl Writer { function.variables.push(LocalVariable { id: variable_id, name: None, - instruction: self.instruction_variable( + instruction: super::instructions::instruction_variable( pointer_id, variable_id, spirv::StorageClass::Function, None, ), }); - block.body.push(self.instruction_store(variable_id, id)); + block.body.push(super::instructions::instruction_store( + variable_id, + id, + None, + )); argument_ids.push(variable_id); } let return_type_id = self .get_function_return_type(origin_function.return_type, &ir_module.types); - block.body.push(self.instruction_function_call( - return_type_id, - id, - *self.lookup_function.get(local_function).unwrap(), - argument_ids, - )); + block + .body + .push(super::instructions::instruction_function_call( + return_type_id, + id, + *self.lookup_function.get(local_function).unwrap(), + argument_ids.as_slice(), + )); Some((id, None)) } _ => unimplemented!("{:?}", origin), @@ -1375,9 +913,9 @@ impl Writer { let id = match expression { crate::Expression::LocalVariable(_) => { let load_id = self.generate_id(); - let value_ty_id = self - .get_type_id(&ir_module.types, LookupType::Handle(ty.unwrap())); - block.body.push(self.instruction_load( + let value_ty_id = + self.get_type_id(&ir_module.types, LookupType::Handle(ty.unwrap())); + block.body.push(super::instructions::instruction_load( value_ty_id, load_id, id, @@ -1385,11 +923,11 @@ impl Writer { )); load_id } - _ => id + _ => id, }; - block.termination = Some(self.instruction_return_value(id)); + block.termination = Some(super::instructions::instruction_return_value(id)); } - None => block.termination = Some(self.instruction_return()), + None => block.termination = Some(super::instructions::instruction_return()), }, crate::Statement::Store { pointer, value } => { let pointer_expression = &ir_function.expressions[*pointer]; @@ -1406,7 +944,7 @@ impl Writer { let load_id = self.generate_id(); let value_ty_id = self .get_type_id(&ir_module.types, LookupType::Handle(value_ty.unwrap())); - block.body.push(self.instruction_load( + block.body.push(super::instructions::instruction_load( value_ty_id, load_id, value_id, @@ -1417,9 +955,9 @@ impl Writer { _ => value_id, }; - block - .body - .push(self.instruction_store(pointer_id, value_id)); + block.body.push(super::instructions::instruction_store( + pointer_id, value_id, None, + )); } crate::Statement::Empty => {} _ => unimplemented!("{:?}", statement), @@ -1431,12 +969,15 @@ impl Writer { } fn write_logical_layout(&mut self, ir_module: &crate::Module) { - self.instruction_ext_inst_import("GLSL.std.450") + let id = self.generate_id(); + super::instructions::instruction_ext_inst_import(id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); if self.writer_flags.contains(WriterFlags::DEBUG) { - self.debugs - .push(self.instruction_source(spirv::SourceLanguage::GLSL, 450)); + self.debugs.push(super::instructions::instruction_source( + spirv::SourceLanguage::GLSL, + 450, + )); } // Looking through all global variable, types, constants. @@ -1482,7 +1023,7 @@ impl Writer { function.variables.push(LocalVariable { id, name: variable.name.clone(), - instruction: self.instruction_variable( + instruction: super::instructions::instruction_variable( pointer_id, id, spirv::StorageClass::Function, @@ -1510,7 +1051,9 @@ impl Writer { .push(self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type))); function .parameters - .push(self.instruction_function_parameter(pointer_id, id)); + .push(super::instructions::instruction_function_parameter( + pointer_id, id, + )); } let lookup_function_type = LookupFunctionType { @@ -1521,7 +1064,7 @@ impl Writer { let id = self.generate_id(); let function_type = self.get_function_type(lookup_function_type, function_parameter_pointer_ids); - function.signature = Some(self.instruction_function( + function.signature = Some(super::instructions::instruction_function( return_type_id, id, spirv::FunctionControl::empty(), @@ -1532,7 +1075,7 @@ impl Writer { let mut block = Block::new(); let id = self.generate_id(); - block.label = Some(self.instruction_label(id)); + block.label = Some(super::instructions::instruction_label(id)); for statement in ir_function.body.iter() { self.write_function_statement( ir_module, @@ -1545,21 +1088,26 @@ impl Writer { function.blocks.push(block); function.to_words(&mut self.logical_layout.function_definitions); - self.instruction_function_end() + super::instructions::instruction_function_end() .to_words(&mut self.logical_layout.function_definitions); } for entry_point in ir_module.entry_points.iter() { - let entry_point_instruction = self.instruction_entry_point(entry_point, ir_module); + let entry_point_instruction = self.write_entry_point(entry_point, ir_module); entry_point_instruction.to_words(&mut self.logical_layout.entry_points); } for capability in self.capabilities.iter() { - self.instruction_capability(*capability) + super::instructions::instruction_capability(*capability) .to_words(&mut self.logical_layout.capabilities); } - self.instruction_memory_model() + let addressing_model = spirv::AddressingModel::Logical; + let memory_model = spirv::MemoryModel::GLSL450; + self.try_add_capabilities(addressing_model.required_capabilities()); + self.try_add_capabilities(memory_model.required_capabilities()); + + super::instructions::instruction_memory_model(addressing_model, memory_model) .to_words(&mut self.logical_layout.memory_model); if self.writer_flags.contains(WriterFlags::DEBUG) { @@ -1583,10 +1131,8 @@ impl Writer { #[cfg(test)] mod tests { - use crate::back::spv::test_framework::*; use crate::back::spv::{Writer, WriterFlags}; use crate::Header; - use spirv::*; #[test] fn test_writer_generate_id() { @@ -1609,181 +1155,6 @@ mod tests { assert_eq!(writer.capabilities.len(), 1); } - #[test] - fn test_instruction_capability() { - let writer = create_writer(); - let instruction = writer.instruction_capability(spirv::Capability::Shader); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Capability, - wc: 2, - type_id: false, - result_id: false, - operands: true, - }; - - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_ext_inst_import() { - let mut writer = create_writer(); - let import_name = "GLSL.std.450"; - let instruction = writer.instruction_ext_inst_import(import_name); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ExtInstImport, - wc: 2, - type_id: false, - result_id: true, - operands: true, - }; - - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_memory_model() { - let mut writer = create_writer(); - let instruction = writer.instruction_memory_model(); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::MemoryModel, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_name() { - let writer = create_writer(); - let instruction = writer.instruction_name(1, "Test"); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Name, - wc: 3, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_execution_mode() { - let writer = create_writer(); - let instruction = writer.instruction_execution_mode(1, ExecutionMode::OriginUpperLeft); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ExecutionMode, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_source() { - let writer = create_writer(); - let version = 450; - let instruction = writer.instruction_source(SourceLanguage::GLSL, version); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Source, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_label() { - let writer = create_writer(); - let instruction = writer.instruction_label(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Label, - wc: 2, - type_id: false, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_function_end() { - let writer = create_writer(); - let instruction = writer.instruction_function_end(); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::FunctionEnd, - wc: 1, - type_id: false, - result_id: false, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_decorate() { - let writer = create_writer(); - let instruction = writer.instruction_decorate(1, Decoration::Location, &[1]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Decorate, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - #[test] fn test_write_physical_layout() { let mut writer = create_writer(); From 43bad8ee5086424ebbe86458a4b36ef0416eaae9 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 7 Sep 2020 07:28:13 +0200 Subject: [PATCH 0186/2212] [glsl-new] Add jump statements (#179) * [glsl-new] Add jump statements - continue - break - return - discard * [glsl-new] Fix clippy error for return statement --- src/front/glsl_new/lex.rs | 5 +++++ src/front/glsl_new/parser.rs | 18 +++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl_new/lex.rs index 6fda4bb6c..060b16c2e 100644 --- a/src/front/glsl_new/lex.rs +++ b/src/front/glsl_new/lex.rs @@ -139,6 +139,11 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { // values "true" => (Some(Token::BoolConstant((meta, true))), rest), "false" => (Some(Token::BoolConstant((meta, false))), rest), + // jump statements + "continue" => (Some(Token::Continue(meta)), rest), + "break" => (Some(Token::Break(meta)), rest), + "return" => (Some(Token::Return(meta)), rest), + "discard" => (Some(Token::Discard(meta)), rest), // types "void" => (Some(Token::Void(meta)), rest), word => { diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 43bed09b6..57878be07 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -53,6 +53,7 @@ pomelo! { %type simple_statement Statement; %type expression_statement Statement; %type declaration_statement Statement; + %type jump_statement Statement; // expressions %type unary_expression ExpressionRule; @@ -600,7 +601,7 @@ pomelo! { //simple_statement ::= switch_statement; //simple_statement ::= case_label; //simple_statement ::= iteration_statement; - //simple_statement ::= jump_statement; + simple_statement ::= jump_statement; compound_statement ::= LeftBrace RightBrace {vec![]} compound_statement ::= left_brace_scope statement_list(sl) RightBrace { @@ -671,6 +672,21 @@ pomelo! { type_specifier_nonarray ::= Void { None } type_specifier_nonarray ::= TypeName(t) {Some(t.1)}; + jump_statement ::= Continue Semicolon { Statement::Continue } + jump_statement ::= Break Semicolon { Statement::Break } + jump_statement ::= Return Semicolon { Statement::Return{ value: None } } + jump_statement ::= Return expression(mut e) Semicolon { + let ret = Statement::Return{ value: Some(e.expression) }; + if !e.statements.is_empty() { + e.statements.push(ret); + Statement::Block(e.statements) + } else { + ret + } + } + jump_statement ::= Discard Semicolon { Statement::Kill } // Fragment shader only + // Grammar Note: No 'goto'. Gotos are not supported. + // misc translation_unit ::= external_declaration; translation_unit ::= translation_unit external_declaration; From 789d624710889fbbd41bb73e2337698283edb903 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 8 Sep 2020 07:18:07 +0200 Subject: [PATCH 0187/2212] [rosetta] Add explicit return (#180) --- test-data/simple/simple.expected.ron | 3 +++ test-data/simple/simple.vert | 1 + test-data/simple/simple.wgsl | 1 + 3 files changed, 5 insertions(+) diff --git a/test-data/simple/simple.expected.ron b/test-data/simple/simple.expected.ron index baad5a38d..33281f1bb 100644 --- a/test-data/simple/simple.expected.ron +++ b/test-data/simple/simple.expected.ron @@ -99,6 +99,9 @@ pointer: 2, value: 6, ), + Return( + value: None, + ), ], ), ], diff --git a/test-data/simple/simple.vert b/test-data/simple/simple.vert index 507039ffd..27c9f0406 100644 --- a/test-data/simple/simple.vert +++ b/test-data/simple/simple.vert @@ -6,4 +6,5 @@ layout(location = 0) out vec4 o_pos; void main() { float w = 1.0; o_pos = vec4(a_pos, 0.0, w); + return; } diff --git a/test-data/simple/simple.wgsl b/test-data/simple/simple.wgsl index bac4c31f0..85eef7614 100644 --- a/test-data/simple/simple.wgsl +++ b/test-data/simple/simple.wgsl @@ -5,5 +5,6 @@ fn main() -> void { var w: f32 = 1.0; o_pos = vec4(a_pos, 0.0, w); + return; } entry_point vertex as "main" = main; From c122e064a7b56c2ee0175585f637c5324026d830 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 9 Sep 2020 13:59:29 -0400 Subject: [PATCH 0188/2212] Move storage class from image type into the global declaration (#182) --- src/back/glsl.rs | 22 +++---- src/back/msl.rs | 16 ++++-- src/back/spv/instructions.rs | 86 ++++++++++++---------------- src/front/glsl/mod.rs | 13 ++++- src/front/glsl_new/parser.rs | 5 +- src/front/spv/mod.rs | 53 ++++++++++++----- src/front/wgsl/mod.rs | 62 ++++++++++++-------- src/lib.rs | 4 +- test-data/simple/simple.expected.ron | 6 ++ 9 files changed, 156 insertions(+), 111 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index e5224c0b8..708374e5b 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -254,7 +254,7 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> let storage_format = match module.types[global.ty].inner { TypeInner::Image { - class: ImageClass::Storage(format, _), + class: ImageClass::Storage(format), .. } => Some(format), _ => None, @@ -280,16 +280,10 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> write!(out, ") ")?; } - if let TypeInner::Image { - class: ImageClass::Storage(_, access), - .. - } = module.types[global.ty].inner - { - if access == StorageAccess::LOAD { - write!(out, "readonly ")?; - } else if access == StorageAccess::STORE { - write!(out, "writeonly ")?; - } + if global.storage_access == StorageAccess::LOAD { + write!(out, "readonly ")?; + } else if global.storage_access == StorageAccess::STORE { + write!(out, "writeonly ")?; } if let Some(interpolation) = global.interpolation { @@ -950,9 +944,7 @@ fn write_expression<'a, 'b>( ) } } - ImageClass::Storage(_, _) => { - format!("imageLoad({},{})", image_expr, coordinate_expr) - } + ImageClass::Storage(_) => format!("imageLoad({},{})", image_expr, coordinate_expr), ImageClass::Depth => todo!(), }; @@ -1402,7 +1394,7 @@ fn write_type<'a>( ))), }, match class { - ImageClass::Storage(_, _) => "image", + ImageClass::Storage(_) => "image", _ => "texture", }, ImageDimension(dim), diff --git a/src/back/msl.rs b/src/back/msl.rs index da7045942..ee9fd2490 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -944,17 +944,23 @@ impl Writer { }; let array_str = if arrayed { "_array" } else { "" }; let access = match class { - crate::ImageClass::Storage(_, access) => { - if access + crate::ImageClass::Storage(_) => { + let (_, global) = module + .global_variables + .iter() + .find(|(_, var)| var.ty == handle) + .expect("Unable to find a global variable using the image type"); + if global + .storage_access .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) { "read_write" - } else if access.contains(crate::StorageAccess::STORE) { + } else if global.storage_access.contains(crate::StorageAccess::STORE) { "write" - } else if access.contains(crate::StorageAccess::LOAD) { + } else if global.storage_access.contains(crate::StorageAccess::LOAD) { "read" } else { - return Err(Error::InvalidImageAccess(access)); + return Err(Error::InvalidImageAccess(global.storage_access)); } } _ => "sample", diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 70aed08da..35914c33c 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -187,59 +187,45 @@ pub(super) fn instruction_type_image( _ => 0, }); - let (format, access) = match image_class { - crate::ImageClass::Storage(format, access) => { - let spv_format = match format { - crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8, - crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm, - crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui, - crate::StorageFormat::R8Sint => spirv::ImageFormat::R8i, - crate::StorageFormat::R16Uint => spirv::ImageFormat::R16ui, - crate::StorageFormat::R16Sint => spirv::ImageFormat::R16i, - crate::StorageFormat::R16Float => spirv::ImageFormat::R16f, - crate::StorageFormat::Rg8Unorm => spirv::ImageFormat::Rg8, - crate::StorageFormat::Rg8Snorm => spirv::ImageFormat::Rg8Snorm, - crate::StorageFormat::Rg8Uint => spirv::ImageFormat::Rg8ui, - crate::StorageFormat::Rg8Sint => spirv::ImageFormat::Rg8i, - crate::StorageFormat::R32Uint => spirv::ImageFormat::R32ui, - crate::StorageFormat::R32Sint => spirv::ImageFormat::R32i, - crate::StorageFormat::R32Float => spirv::ImageFormat::R32f, - crate::StorageFormat::Rg16Uint => spirv::ImageFormat::Rg16ui, - crate::StorageFormat::Rg16Sint => spirv::ImageFormat::Rg16i, - crate::StorageFormat::Rg16Float => spirv::ImageFormat::Rg16f, - crate::StorageFormat::Rgba8Unorm => spirv::ImageFormat::Rgba8, - crate::StorageFormat::Rgba8Snorm => spirv::ImageFormat::Rgba8Snorm, - crate::StorageFormat::Rgba8Uint => spirv::ImageFormat::Rgba8ui, - crate::StorageFormat::Rgba8Sint => spirv::ImageFormat::Rgba8i, - crate::StorageFormat::Rgb10a2Unorm => spirv::ImageFormat::Rgb10a2ui, - crate::StorageFormat::Rg11b10Float => spirv::ImageFormat::R11fG11fB10f, - crate::StorageFormat::Rg32Uint => spirv::ImageFormat::Rg32ui, - crate::StorageFormat::Rg32Sint => spirv::ImageFormat::Rg32i, - crate::StorageFormat::Rg32Float => spirv::ImageFormat::Rg32f, - crate::StorageFormat::Rgba16Uint => spirv::ImageFormat::Rgba16ui, - crate::StorageFormat::Rgba16Sint => spirv::ImageFormat::Rgba16i, - crate::StorageFormat::Rgba16Float => spirv::ImageFormat::Rgba16f, - crate::StorageFormat::Rgba32Uint => spirv::ImageFormat::Rgba32ui, - crate::StorageFormat::Rgba32Sint => spirv::ImageFormat::Rgba32i, - crate::StorageFormat::Rgba32Float => spirv::ImageFormat::Rgba32f, - }; - (spv_format, access) - } - _ => (spirv::ImageFormat::Unknown, crate::StorageAccess::empty()), + let format = match image_class { + crate::ImageClass::Storage(format) => match format { + crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8, + crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm, + crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui, + crate::StorageFormat::R8Sint => spirv::ImageFormat::R8i, + crate::StorageFormat::R16Uint => spirv::ImageFormat::R16ui, + crate::StorageFormat::R16Sint => spirv::ImageFormat::R16i, + crate::StorageFormat::R16Float => spirv::ImageFormat::R16f, + crate::StorageFormat::Rg8Unorm => spirv::ImageFormat::Rg8, + crate::StorageFormat::Rg8Snorm => spirv::ImageFormat::Rg8Snorm, + crate::StorageFormat::Rg8Uint => spirv::ImageFormat::Rg8ui, + crate::StorageFormat::Rg8Sint => spirv::ImageFormat::Rg8i, + crate::StorageFormat::R32Uint => spirv::ImageFormat::R32ui, + crate::StorageFormat::R32Sint => spirv::ImageFormat::R32i, + crate::StorageFormat::R32Float => spirv::ImageFormat::R32f, + crate::StorageFormat::Rg16Uint => spirv::ImageFormat::Rg16ui, + crate::StorageFormat::Rg16Sint => spirv::ImageFormat::Rg16i, + crate::StorageFormat::Rg16Float => spirv::ImageFormat::Rg16f, + crate::StorageFormat::Rgba8Unorm => spirv::ImageFormat::Rgba8, + crate::StorageFormat::Rgba8Snorm => spirv::ImageFormat::Rgba8Snorm, + crate::StorageFormat::Rgba8Uint => spirv::ImageFormat::Rgba8ui, + crate::StorageFormat::Rgba8Sint => spirv::ImageFormat::Rgba8i, + crate::StorageFormat::Rgb10a2Unorm => spirv::ImageFormat::Rgb10a2ui, + crate::StorageFormat::Rg11b10Float => spirv::ImageFormat::R11fG11fB10f, + crate::StorageFormat::Rg32Uint => spirv::ImageFormat::Rg32ui, + crate::StorageFormat::Rg32Sint => spirv::ImageFormat::Rg32i, + crate::StorageFormat::Rg32Float => spirv::ImageFormat::Rg32f, + crate::StorageFormat::Rgba16Uint => spirv::ImageFormat::Rgba16ui, + crate::StorageFormat::Rgba16Sint => spirv::ImageFormat::Rgba16i, + crate::StorageFormat::Rgba16Float => spirv::ImageFormat::Rgba16f, + crate::StorageFormat::Rgba32Uint => spirv::ImageFormat::Rgba32ui, + crate::StorageFormat::Rgba32Sint => spirv::ImageFormat::Rgba32i, + crate::StorageFormat::Rgba32Float => spirv::ImageFormat::Rgba32f, + }, + _ => spirv::ImageFormat::Unknown, }; instruction.add_operand(format as u32); - // Access Qualifier - if !access.is_empty() { - instruction.add_operand(if access == crate::StorageAccess::all() { - 2 - } else if access.contains(crate::StorageAccess::STORE) { - 1 - } else { - 0 - }); - } - instruction } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index f8fad62b5..be2ee62ad 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -2,8 +2,8 @@ use crate::{ Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Constant, ConstantInner, EntryPoint, Expression, FastHashMap, Function, GlobalVariable, Handle, Header, Interpolation, - LocalVariable, Module, ScalarKind, ShaderStage, StorageClass, StructMember, Type, TypeInner, - VectorSize, + LocalVariable, Module, ScalarKind, ShaderStage, StorageAccess, StorageClass, StructMember, + Type, TypeInner, VectorSize, }; use glsl::{ parser::{Parse, ParseError}, @@ -236,6 +236,7 @@ impl<'a> Parser<'a> { name, ty, interpolation, + storage_access: StorageAccess::empty(), //TODO }); for (name, index) in reexports { @@ -586,6 +587,7 @@ impl<'a> Parser<'a> { }, }), interpolation: None, + storage_access: StorageAccess::empty(), }), )), "gl_InstanceIndex" => Ok(Expression::GlobalVariable( @@ -601,6 +603,7 @@ impl<'a> Parser<'a> { }, }), interpolation: None, + storage_access: StorageAccess::empty(), }), )), "gl_BaseVertex" => Ok(Expression::GlobalVariable( @@ -616,6 +619,7 @@ impl<'a> Parser<'a> { }, }), interpolation: None, + storage_access: StorageAccess::empty(), }), )), "gl_BaseInstance" => Ok(Expression::GlobalVariable( @@ -631,6 +635,7 @@ impl<'a> Parser<'a> { }, }), interpolation: None, + storage_access: StorageAccess::empty(), }), )), "gl_Position" => Ok(Expression::GlobalVariable(self.globals.fetch_or_append( @@ -651,6 +656,7 @@ impl<'a> Parser<'a> { }, }), interpolation: None, + storage_access: StorageAccess::empty(), }, ))), "gl_PointSize" => Ok(Expression::GlobalVariable(self.globals.fetch_or_append( @@ -666,6 +672,7 @@ impl<'a> Parser<'a> { }, }), interpolation: None, + storage_access: StorageAccess::empty(), }, ))), "gl_ClipDistance" => Ok(Expression::GlobalVariable( @@ -681,6 +688,7 @@ impl<'a> Parser<'a> { }, }), interpolation: None, + storage_access: StorageAccess::empty(), }), )), other => { @@ -1090,6 +1098,7 @@ impl<'a> Parser<'a> { binding, ty, interpolation, + storage_access: StorageAccess::empty(), //TODO })) } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index 57878be07..2c0c2e7ea 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -7,7 +7,8 @@ pomelo! { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{Arena, BinaryOperator, Binding, Block, BuiltIn, Constant, ConstantInner, Expression, Function, GlobalVariable, Handle, LocalVariable, ScalarKind, - ShaderStage, Statement, StorageClass, Type, TypeInner, VectorSize, Interpolation}; + ShaderStage, Statement, StorageAccess, StorageClass, Type, TypeInner, + VectorSize, Interpolation}; } %token #[derive(Debug)] pub enum Token {}; %parser pub struct Parser<'a> {}; @@ -151,6 +152,7 @@ pomelo! { }, }), interpolation: None, + storage_access: StorageAccess::empty(), }, ); extra.lookup_global_variables.insert(v.1.clone(), h); @@ -719,6 +721,7 @@ pomelo! { binding: binding.clone(), ty: d.ty, interpolation, + storage_access: StorageAccess::empty(), //TODO }, ); extra.lookup_global_variables.insert(id, h); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 5ef5be200..e467dec02 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -145,6 +145,14 @@ struct Block { buffer: bool, } +bitflags::bitflags! { + #[derive(Default)] + struct DecorationFlags: u32 { + const NON_READABLE = 0x1; + const NON_WRITABLE = 0x2; + } +} + #[derive(Debug, Default)] struct Decoration { name: Option, @@ -156,6 +164,7 @@ struct Decoration { offset: Option, array_stride: Option, interpolation: Option, + flags: DecorationFlags, } impl Decoration { @@ -425,6 +434,12 @@ impl> Parser { spirv::Decoration::Sample => { dec.interpolation = Some(crate::Interpolation::Sample); } + spirv::Decoration::NonReadable => { + dec.flags |= DecorationFlags::NON_READABLE; + } + spirv::Decoration::NonWritable => { + dec.flags |= DecorationFlags::NON_WRITABLE; + } other => { log::warn!("Unknown decoration {:?}", other); for _ in base_words + 1..inst.wc { @@ -2033,7 +2048,7 @@ impl> Parser { module: &mut crate::Module, ) -> Result<(), Error> { self.switch(ModuleState::Type, inst.op)?; - inst.expect_at_least(9)?; + inst.expect(9)?; let id = self.next()?; let sample_type_id = self.next()?; @@ -2050,18 +2065,8 @@ impl> Parser { _ => return Err(Error::InvalidImageBaseType(base_handle)), }; - let class = if inst.wc > 9 { - let storage_format = map_image_format(format)?; - let mut flags = crate::StorageAccess::empty(); - inst.expect(10)?; - let access = self.next()?; - if access == 0 || access == 2 { - flags |= crate::StorageAccess::LOAD; - } - if access == 1 || access == 2 { - flags |= crate::StorageAccess::STORE; - } - crate::ImageClass::Storage(storage_format, flags) + let class = if format != 0 { + crate::ImageClass::Storage(map_image_format(format)?) } else if is_msaa { crate::ImageClass::Multisampled } else { @@ -2277,6 +2282,27 @@ impl> Parser { _ => return Err(Error::UnsupportedType(lookup_type.handle)), }; let class = map_storage_class(storage)?; + let is_storage = match module.types[ty].inner { + crate::TypeInner::Struct { .. } => class == crate::StorageClass::StorageBuffer, + crate::TypeInner::Image { + class: crate::ImageClass::Storage(_), + .. + } => true, + _ => false, + }; + + let storage_access = if is_storage { + let mut access = crate::StorageAccess::all(); + if dec.flags.contains(DecorationFlags::NON_READABLE) { + access ^= crate::StorageAccess::LOAD; + } + if dec.flags.contains(DecorationFlags::NON_WRITABLE) { + access ^= crate::StorageAccess::STORE; + } + access + } else { + crate::StorageAccess::empty() + }; let var = crate::GlobalVariable { name: dec.name, @@ -2284,6 +2310,7 @@ impl> Parser { binding, ty, interpolation: dec.interpolation, + storage_access, }; self.lookup_variable.insert( id, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index efced204f..f291057b1 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -209,6 +209,13 @@ pub enum Scope { GeneralExpr, } +struct ParsedVariable<'a> { + name: &'a str, + class: Option, + ty: Handle, + access: crate::StorageAccess, +} + #[derive(Clone, Debug, Error)] #[error("error while parsing WGSL in scopes {scopes:?} at position {pos:?}: {error}")] pub struct ParseError<'a> { @@ -382,7 +389,7 @@ impl Parser { inner } _ => { - let composite_ty = self.parse_type_decl(lexer, None, type_arena)?; + let (composite_ty, _) = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -478,7 +485,7 @@ impl Parser { expr } else { *lexer = backup; - let ty = self.parse_type_decl(lexer, None, ctx.types)?; + let (ty, _) = self.parse_type_decl(lexer, None, ctx.types)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -831,7 +838,7 @@ impl Parser { ) -> Result<(&'a str, Handle), Error<'a>> { let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena)?; + let (ty, _) = self.parse_type_decl(lexer, None, type_arena)?; Ok((name, ty)) } @@ -840,7 +847,7 @@ impl Parser { lexer: &mut Lexer<'a>, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result<(&'a str, Option, Handle), Error<'a>> { + ) -> Result, Error<'a>> { self.scopes.push(Scope::VariableDecl); let mut class = None; if lexer.skip(Token::Paren('<')) { @@ -850,14 +857,19 @@ impl Parser { } let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena)?; + let (ty, access) = self.parse_type_decl(lexer, None, type_arena)?; if lexer.skip(Token::Operation('=')) { let _inner = self.parse_const_expression(lexer, type_arena, const_arena)?; //TODO } lexer.expect(Token::Separator(';'))?; self.scopes.pop(); - Ok((name, class, ty)) + Ok(ParsedVariable { + name, + class, + ty, + access, + }) } fn parse_struct_body<'a>( @@ -898,7 +910,7 @@ impl Parser { return Err(Error::MissingMemberOffset(name)); } lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena)?; + let (ty, _) = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Separator(';'))?; members.push(crate::StructMember { name: Some(name.to_owned()), @@ -913,7 +925,7 @@ impl Parser { lexer: &mut Lexer<'a>, self_name: Option<&'a str>, type_arena: &mut Arena, - ) -> Result, Error<'a>> { + ) -> Result<(Handle, crate::StorageAccess), Error<'a>> { self.scopes.push(Scope::TypeDecl); let decoration_lexer = if lexer.skip(Token::DoubleParen('[')) { Some(lexer.take_until(Token::DoubleParen(']'))?) @@ -1043,13 +1055,13 @@ impl Parser { lexer.expect(Token::Paren('<'))?; let class = Self::get_storage_class(lexer.next_ident()?)?; lexer.expect(Token::Separator(','))?; - let base = self.parse_type_decl(lexer, None, type_arena)?; + let (base, _) = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Paren('>'))?; crate::TypeInner::Pointer { base, class } } Token::Word("array") => { lexer.expect(Token::Paren('<'))?; - let base = self.parse_type_decl(lexer, None, type_arena)?; + let (base, _) = self.parse_type_decl(lexer, None, type_arena)?; let size = match lexer.next() { Token::Separator(',') => { let value = lexer.next_uint_literal()?; @@ -1087,19 +1099,20 @@ impl Parser { } Token::Word(name) => { self.scopes.pop(); - return self - .lookup_type - .get(name) - .cloned() - .ok_or(Error::UnknownType(name)); + return match self.lookup_type.get(name) { + Some(&handle) => Ok((handle, crate::StorageAccess::empty())), + None => Err(Error::UnknownType(name)), + }; } other => return Err(Error::Unexpected(other)), }; self.scopes.pop(); - Ok(type_arena.fetch_or_append(crate::Type { + + let handle = type_arena.fetch_or_append(crate::Type { name: self_name.map(|s| s.to_string()), inner, - })) + }); + Ok((handle, crate::StorageAccess::empty())) } fn parse_statement<'a>( @@ -1281,7 +1294,7 @@ impl Parser { let return_type = if lexer.skip(Token::Word("void")) { None } else { - Some(self.parse_type_decl(lexer, None, &mut module.types)?) + Some(self.parse_type_decl(lexer, None, &mut module.types)?.0) }; let fun_handle = module.functions.append(crate::Function { @@ -1409,7 +1422,7 @@ impl Parser { Token::Word("type") => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; - let ty = self.parse_type_decl(lexer, Some(name), &mut module.types)?; + let (ty, _) = self.parse_type_decl(lexer, Some(name), &mut module.types)?; self.lookup_type.insert(name.to_owned(), ty); lexer.expect(Token::Separator(';'))?; } @@ -1431,9 +1444,9 @@ impl Parser { lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); } Token::Word("var") => { - let (name, class, ty) = + let pvar = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; - let class = match class { + let class = match pvar.class { Some(c) => c, None => match binding { Some(crate::Binding::BuiltIn(builtin)) => match builtin { @@ -1445,14 +1458,15 @@ impl Parser { }, }; let var_handle = module.global_variables.append(crate::GlobalVariable { - name: Some(name.to_owned()), + name: Some(pvar.name.to_owned()), class, binding: binding.take(), - ty, + ty: pvar.ty, interpolation, + storage_access: pvar.access, }); lookup_global_expression - .insert(name, crate::Expression::GlobalVariable(var_handle)); + .insert(pvar.name, crate::Expression::GlobalVariable(var_handle)); } Token::Word("fn") => { self.parse_function_decl(lexer, module, &lookup_global_expression)?; diff --git a/src/lib.rs b/src/lib.rs index b662046c2..c4c9f1596 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -325,7 +325,7 @@ pub enum ImageClass { /// Depth comparison image. Depth, /// Storage image. - Storage(StorageFormat, StorageAccess), + Storage(StorageFormat), } /// A data type declared in the module. @@ -450,6 +450,8 @@ pub struct GlobalVariable { /// or fragment input, `None` corresponds to the /// `smooth`/`perspective` interpolation qualifier. pub interpolation: Option, + /// Access bit for storage types of images and buffers. + pub storage_access: StorageAccess, } /// Variable defined at function level. diff --git a/test-data/simple/simple.expected.ron b/test-data/simple/simple.expected.ron index 33281f1bb..5d6863579 100644 --- a/test-data/simple/simple.expected.ron +++ b/test-data/simple/simple.expected.ron @@ -49,6 +49,9 @@ binding: Some(Location(0)), ty: 1, interpolation: None, + storage_access: ( + bits: 0, + ), ), ( name: Some("o_pos"), @@ -56,6 +59,9 @@ binding: Some(Location(0)), ty: 2, interpolation: None, + storage_access: ( + bits: 0, + ), ), ], functions: [ From e1e116537e83b27a3a63ef17d5bdaeb5f8e8b434 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 9 Sep 2020 22:22:13 +0100 Subject: [PATCH 0189/2212] Extended Interface to be used in more places (#183) * Extended Interface to be used in more places * Applied comments and added tests * Removed the statement visitor * Fixed remaining comments --- src/proc/interface.rs | 193 ++++++++++++++++++++++++++++++------------ src/proc/mod.rs | 1 + 2 files changed, 139 insertions(+), 55 deletions(-) diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 015dd51ce..4e2ec5f8b 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -1,34 +1,43 @@ use crate::arena::{Arena, Handle}; -struct Interface<'a> { +pub struct Interface<'a, T> { expressions: &'a Arena, - uses: Vec, + visitor: &'a mut T, } -impl<'a> Interface<'a> { - fn add_inputs(&mut self, handle: Handle) { +pub trait Visitor { + fn visit_expr(&mut self, _: &crate::Expression) {} + fn visit_lhs_expr(&mut self, _: &crate::Expression) {} +} + +impl<'a, T> Interface<'a, T> +where + T: Visitor, +{ + fn traverse_expr(&mut self, handle: Handle) { use crate::Expression as E; - match self.expressions[handle] { + + let expr = &self.expressions[handle]; + + self.visitor.visit_expr(expr); + + match *expr { E::Access { base, index } => { - self.add_inputs(base); - self.add_inputs(index); + self.traverse_expr(base); + self.traverse_expr(index); } E::AccessIndex { base, .. } => { - self.add_inputs(base); + self.traverse_expr(base); } E::Constant(_) => {} E::Compose { ref components, .. } => { for &comp in components { - self.add_inputs(comp); + self.traverse_expr(comp); } } - E::FunctionParameter(_) => {} - E::GlobalVariable(handle) => { - self.uses[handle.index()] |= crate::GlobalUse::LOAD; - } - E::LocalVariable(_) => {} + E::FunctionParameter(_) | E::GlobalVariable(_) | E::LocalVariable(_) => {} E::Load { pointer } => { - self.add_inputs(pointer); + self.traverse_expr(pointer); } E::ImageSample { image, @@ -37,17 +46,17 @@ impl<'a> Interface<'a> { level, depth_ref, } => { - self.add_inputs(image); - self.add_inputs(sampler); - self.add_inputs(coordinate); + self.traverse_expr(image); + self.traverse_expr(sampler); + self.traverse_expr(coordinate); match level { crate::SampleLevel::Auto => (), crate::SampleLevel::Exact(h) | crate::SampleLevel::Bias(h) => { - self.add_inputs(h) + self.traverse_expr(h) } } if let Some(dref) = depth_ref { - self.add_inputs(dref); + self.traverse_expr(dref); } } E::ImageLoad { @@ -55,83 +64,83 @@ impl<'a> Interface<'a> { coordinate, index, } => { - self.add_inputs(image); - self.add_inputs(coordinate); - self.add_inputs(index); + self.traverse_expr(image); + self.traverse_expr(coordinate); + self.traverse_expr(index); } E::Unary { expr, .. } => { - self.add_inputs(expr); + self.traverse_expr(expr); } E::Binary { left, right, .. } => { - self.add_inputs(left); - self.add_inputs(right); + self.traverse_expr(left); + self.traverse_expr(right); } E::Intrinsic { argument, .. } => { - self.add_inputs(argument); + self.traverse_expr(argument); } E::Transpose(matrix) => { - self.add_inputs(matrix); + self.traverse_expr(matrix); } E::DotProduct(left, right) => { - self.add_inputs(left); - self.add_inputs(right); + self.traverse_expr(left); + self.traverse_expr(right); } E::CrossProduct(left, right) => { - self.add_inputs(left); - self.add_inputs(right); + self.traverse_expr(left); + self.traverse_expr(right); } E::As(expr, _) => { - self.add_inputs(expr); + self.traverse_expr(expr); } E::Derivative { expr, .. } => { - self.add_inputs(expr); + self.traverse_expr(expr); } E::Call { ref arguments, .. } => { for &argument in arguments { - self.add_inputs(argument); + self.traverse_expr(argument); } } } } - fn collect(&mut self, block: &[crate::Statement]) { + pub fn traverse(&mut self, block: &[crate::Statement]) { for statement in block { use crate::Statement as S; match *statement { S::Empty | S::Break | S::Continue | S::Kill => (), S::Block(ref b) => { - self.collect(b); + self.traverse(b); } S::If { condition, ref accept, ref reject, } => { - self.add_inputs(condition); - self.collect(accept); - self.collect(reject); + self.traverse_expr(condition); + self.traverse(accept); + self.traverse(reject); } S::Switch { selector, ref cases, ref default, } => { - self.add_inputs(selector); + self.traverse_expr(selector); for &(ref case, _) in cases.values() { - self.collect(case); + self.traverse(case); } - self.collect(default); + self.traverse(default); } S::Loop { ref body, ref continuing, } => { - self.collect(body); - self.collect(continuing); + self.traverse(body); + self.traverse(continuing); } S::Return { value } => { if let Some(expr) = value { - self.add_inputs(expr); + self.traverse_expr(expr); } } S::Store { pointer, value } => { @@ -139,37 +148,111 @@ impl<'a> Interface<'a> { loop { match self.expressions[left] { crate::Expression::Access { base, index } => { - self.add_inputs(index); + self.traverse_expr(index); left = base; } crate::Expression::AccessIndex { base, .. } => { left = base; } - crate::Expression::GlobalVariable(handle) => { - self.uses[handle.index()] |= crate::GlobalUse::STORE; - break; - } _ => break, } } - self.add_inputs(value); + self.visitor.visit_lhs_expr(&self.expressions[left]); + self.traverse_expr(value); } } } } } +struct GlobalUseVisitor(Vec); + +impl Visitor for GlobalUseVisitor { + fn visit_expr(&mut self, expr: &crate::Expression) { + if let crate::Expression::GlobalVariable(handle) = expr { + self.0[handle.index()] |= crate::GlobalUse::LOAD; + } + } + + fn visit_lhs_expr(&mut self, expr: &crate::Expression) { + if let crate::Expression::GlobalVariable(handle) = expr { + self.0[handle.index()] |= crate::GlobalUse::STORE; + } + } +} + impl crate::GlobalUse { pub fn scan( expressions: &Arena, body: &[crate::Statement], globals: &Arena, ) -> Vec { + let mut visitor = GlobalUseVisitor(vec![crate::GlobalUse::empty(); globals.len()]); + let mut io = Interface { expressions, - uses: vec![crate::GlobalUse::empty(); globals.len()], + visitor: &mut visitor, }; - io.collect(body); - io.uses + io.traverse(body); + visitor.0 + } +} + +#[cfg(test)] +mod tests { + use crate::{ + Arena, Expression, GlobalUse, GlobalVariable, Handle, Statement, StorageAccess, + StorageClass, + }; + + #[test] + fn global_use_scan() { + let test_global = GlobalVariable { + name: None, + class: StorageClass::Constant, + binding: None, + ty: Handle::new(std::num::NonZeroU32::new(1).unwrap()), + interpolation: None, + storage_access: StorageAccess::empty(), + }; + let mut test_globals = Arena::new(); + + let global_1 = test_globals.append(test_global.clone()); + let global_2 = test_globals.append(test_global.clone()); + let global_3 = test_globals.append(test_global.clone()); + let global_4 = test_globals.append(test_global); + + let mut expressions = Arena::new(); + let global_1_expr = expressions.append(Expression::GlobalVariable(global_1)); + let global_2_expr = expressions.append(Expression::GlobalVariable(global_2)); + let global_3_expr = expressions.append(Expression::GlobalVariable(global_3)); + let global_4_expr = expressions.append(Expression::GlobalVariable(global_4)); + + let test_body = vec![ + Statement::Return { + value: Some(global_1_expr), + }, + Statement::Store { + pointer: global_2_expr, + value: global_1_expr, + }, + Statement::Store { + pointer: expressions.append(Expression::Access { + base: global_3_expr, + index: global_4_expr, + }), + value: global_1_expr, + }, + ]; + + assert_eq!( + GlobalUse::scan(&expressions, &test_body, &test_globals), + vec![ + GlobalUse::LOAD, + GlobalUse::STORE, + GlobalUse::STORE, + GlobalUse::LOAD, + ] + ) } } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 93178ba15..a37d5bf22 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -4,5 +4,6 @@ mod interface; mod typifier; mod validator; +pub use interface::{Interface, Visitor}; pub use typifier::{check_constant_type, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; From 2fa8eb596d97017a98119a6d4a2a517ea2d2e7a5 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 10 Sep 2020 06:32:02 +0200 Subject: [PATCH 0190/2212] [spv-out] Add initial Rosetta test (#181) * [spv-out] Add initial Rosetta test For now just check that spv-out succeeds * [spv-out] Check spv output has len > 0 --- src/back/spv/mod.rs | 3 +++ src/back/spv/rosetta_tests.rs | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 src/back/spv/rosetta_tests.rs diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 15f159835..6709e59ee 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -9,6 +9,9 @@ mod test_framework; #[cfg(test)] mod layout_tests; +#[cfg(all(test, feature = "deserialize"))] +mod rosetta_tests; + pub use writer::Writer; use spirv::*; diff --git a/src/back/spv/rosetta_tests.rs b/src/back/spv/rosetta_tests.rs new file mode 100644 index 000000000..4552ca13b --- /dev/null +++ b/src/back/spv/rosetta_tests.rs @@ -0,0 +1,17 @@ +use std::{fs, path::Path}; + +const TEST_PATH: &str = "test-data"; + +fn rosetta_test(file_name: &str) { + let test_dir = Path::new(TEST_PATH); + let input = fs::read_to_string(test_dir.join(file_name)).unwrap(); + let module: crate::Module = ron::de::from_str(&input).unwrap(); + + let spv = super::Writer::new(&module.header, super::WriterFlags::NONE).write(&module); + assert!(spv.len() > 0, "spv.len() > 0"); +} + +#[test] +fn simple() { + rosetta_test("simple/simple.expected.ron") +} From 2ea0310b6309e21de8edc80d637fa46c05190756 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 10 Sep 2020 07:11:52 +0200 Subject: [PATCH 0191/2212] [glsl] Promote glsl-new to glsl (#184) * [glsl] Promote glsl-new to glsl * [glsl-in] rename feature glsl > glsl-in --- Cargo.toml | 4 +- examples/convert.rs | 79 +- src/front/{glsl_new => glsl}/ast.rs | 0 src/front/{glsl_new => glsl}/error.rs | 0 src/front/glsl/helpers.rs | 283 --- src/front/{glsl_new => glsl}/lex.rs | 0 src/front/{glsl_new => glsl}/lex_tests.rs | 0 src/front/glsl/mod.rs | 1411 +------------- src/front/{glsl_new => glsl}/parser.rs | 0 src/front/glsl/parser/lex.rs | 254 --- src/front/glsl/parser/mod.rs | 245 --- src/front/glsl/parser/preprocessor.rs | 1618 ----------------- src/front/{glsl_new => glsl}/parser_tests.rs | 0 src/front/{glsl_new => glsl}/rosetta_tests.rs | 2 +- src/front/{glsl_new => glsl}/token.rs | 0 src/front/{glsl_new => glsl}/types.rs | 0 src/front/glsl_new/mod.rs | 50 - src/front/mod.rs | 4 +- tests/convert.rs | 29 +- 19 files changed, 74 insertions(+), 3905 deletions(-) rename src/front/{glsl_new => glsl}/ast.rs (100%) rename src/front/{glsl_new => glsl}/error.rs (100%) delete mode 100644 src/front/glsl/helpers.rs rename src/front/{glsl_new => glsl}/lex.rs (100%) rename src/front/{glsl_new => glsl}/lex_tests.rs (100%) rename src/front/{glsl_new => glsl}/parser.rs (100%) delete mode 100644 src/front/glsl/parser/lex.rs delete mode 100644 src/front/glsl/parser/mod.rs delete mode 100644 src/front/glsl/parser/preprocessor.rs rename src/front/{glsl_new => glsl}/parser_tests.rs (100%) rename src/front/{glsl_new => glsl}/rosetta_tests.rs (86%) rename src/front/{glsl_new => glsl}/token.rs (100%) rename src/front/{glsl_new => glsl}/types.rs (100%) delete mode 100644 src/front/glsl_new/mod.rs diff --git a/Cargo.toml b/Cargo.toml index c80416608..669015720 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,6 @@ fxhash = "0.2" log = "0.4" num-traits = "0.2" spirv = { package = "spirv_headers", version = "1.4.2", optional = true } -glsl = { version = "4.1", optional = true } pomelo = { version = "0.1.4", optional = true } thiserror = "1.0" serde = { version = "1.0", features = ["derive"], optional = true } @@ -23,8 +22,7 @@ petgraph = { version ="0.5", optional = true } [features] default = [] -glsl_preprocessor = ["glsl"] -glsl-new = ["pomelo"] +glsl-in = ["pomelo"] glsl-validate = [] glsl-out = [] serialize = ["serde"] diff --git a/examples/convert.rs b/examples/convert.rs index 9707b6cb7..8b42e5b3a 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -29,9 +29,6 @@ fn main() { println!("Call with "); return; } - #[cfg(any(feature = "glsl", feature = "glsl-new"))] - let prefer_glsl_new = - !cfg!(feature = "glsl") || env::var("PREFER_GLSL_NEW").unwrap_or_default() == "1"; let module = match Path::new(&args[1]) .extension() .expect("Input has no extension?") @@ -48,75 +45,25 @@ fn main() { let input = fs::read_to_string(&args[1]).unwrap(); naga::front::wgsl::parse_str(&input).unwrap() } - #[cfg(any(feature = "glsl", feature = "glsl-new"))] + #[cfg(feature = "glsl-in")] "vert" => { let input = fs::read_to_string(&args[1]).unwrap(); - let mut module: Option = None; - if prefer_glsl_new { - #[cfg(feature = "glsl-new")] - { - module = Some( - naga::front::glsl_new::parse_str( - &input, - "main".to_string(), - naga::ShaderStage::Vertex, - ) - .unwrap(), - ) - } - } - if module.is_none() { - #[cfg(feature = "glsl")] - { - module = Some( - naga::front::glsl::parse_str( - &input, - "main".to_string(), - naga::ShaderStage::Vertex, - ) - .unwrap(), - ) - } - } - module.unwrap() + naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Vertex) + .unwrap() } - #[cfg(any(feature = "glsl", feature = "glsl-new"))] + #[cfg(feature = "glsl-in")] "frag" => { let input = fs::read_to_string(&args[1]).unwrap(); - let mut module = None; - if prefer_glsl_new { - #[cfg(feature = "glsl-new")] - { - module = Some( - naga::front::glsl_new::parse_str( - &input, - "main".to_string(), - naga::ShaderStage::Fragment { - early_depth_test: None, - }, - ) - .unwrap(), - ) - } - } - if module.is_none() { - #[cfg(feature = "glsl")] - { - module = Some( - naga::front::glsl::parse_str( - &input, - "main".to_string(), - naga::ShaderStage::Fragment { - early_depth_test: None, - }, - ) - .unwrap(), - ) - } - } - module.unwrap() + naga::front::glsl::parse_str( + &input, + "main".to_string(), + naga::ShaderStage::Fragment { + early_depth_test: None, + }, + ) + .unwrap() } - #[cfg(feature = "glsl")] + #[cfg(feature = "glsl-in")] "comp" => { let input = fs::read_to_string(&args[1]).unwrap(); naga::front::glsl::parse_str( diff --git a/src/front/glsl_new/ast.rs b/src/front/glsl/ast.rs similarity index 100% rename from src/front/glsl_new/ast.rs rename to src/front/glsl/ast.rs diff --git a/src/front/glsl_new/error.rs b/src/front/glsl/error.rs similarity index 100% rename from src/front/glsl_new/error.rs rename to src/front/glsl/error.rs diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs deleted file mode 100644 index 101448c1d..000000000 --- a/src/front/glsl/helpers.rs +++ /dev/null @@ -1,283 +0,0 @@ -use crate::{ImageClass, ImageDimension, ScalarKind, TypeInner, VectorSize}; -use glsl::syntax::{BinaryOp, TypeSpecifierNonArray, UnaryOp}; - -pub fn glsl_to_spirv_unary_op(op: UnaryOp) -> crate::UnaryOperator { - match op { - UnaryOp::Inc => todo!(), - UnaryOp::Dec => todo!(), - UnaryOp::Add => todo!(), - UnaryOp::Minus => crate::UnaryOperator::Negate, - UnaryOp::Not => crate::UnaryOperator::Not, - UnaryOp::Complement => todo!(), - } -} - -pub fn glsl_to_spirv_binary_op(op: BinaryOp) -> crate::BinaryOperator { - match op { - BinaryOp::Or => crate::BinaryOperator::LogicalOr, - BinaryOp::Xor => todo!(), - BinaryOp::And => crate::BinaryOperator::LogicalAnd, - BinaryOp::BitOr => crate::BinaryOperator::InclusiveOr, - BinaryOp::BitXor => crate::BinaryOperator::ExclusiveOr, - BinaryOp::BitAnd => crate::BinaryOperator::And, - BinaryOp::Equal => crate::BinaryOperator::Equal, - BinaryOp::NonEqual => crate::BinaryOperator::NotEqual, - BinaryOp::LT => crate::BinaryOperator::Less, - BinaryOp::GT => crate::BinaryOperator::Greater, - BinaryOp::LTE => crate::BinaryOperator::LessEqual, - BinaryOp::GTE => crate::BinaryOperator::GreaterEqual, - BinaryOp::LShift => crate::BinaryOperator::ShiftLeftLogical, - BinaryOp::RShift => crate::BinaryOperator::ShiftRightArithmetic, - BinaryOp::Add => crate::BinaryOperator::Add, - BinaryOp::Sub => crate::BinaryOperator::Subtract, - BinaryOp::Mult => crate::BinaryOperator::Multiply, - BinaryOp::Div => crate::BinaryOperator::Divide, - BinaryOp::Mod => crate::BinaryOperator::Modulo, - } -} - -pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray) -> Option { - use TypeSpecifierNonArray::*; - - Some(match ty { - Void => return None, - Bool => TypeInner::Scalar { - kind: ScalarKind::Bool, - width: 1, - }, - Int => TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - }, - UInt => TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - Float => TypeInner::Scalar { - kind: ScalarKind::Float, - width: 4, - }, - Double => TypeInner::Scalar { - kind: ScalarKind::Float, - width: 8, - }, - Vec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 4, - }, - Vec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Float, - width: 4, - }, - Vec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, - }, - DVec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Float, - width: 8, - }, - DVec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Float, - width: 8, - }, - DVec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 8, - }, - BVec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Bool, - width: 1, - }, - BVec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Bool, - width: 1, - }, - BVec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Bool, - width: 1, - }, - IVec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Sint, - width: 4, - }, - IVec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Sint, - width: 4, - }, - IVec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Sint, - width: 4, - }, - UVec2 => TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Uint, - width: 4, - }, - UVec3 => TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Uint, - width: 4, - }, - UVec4 => TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Uint, - width: 4, - }, - // Float Matrices - Mat2 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 4, - }, - Mat3 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 4, - }, - Mat4 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, - }, - Mat23 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 4, - }, - Mat24 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, - }, - Mat32 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 4, - }, - Mat34 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, - }, - Mat42 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 4, - }, - Mat43 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 4, - }, - // Double Matrices - DMat2 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 8, - }, - DMat3 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 8, - }, - DMat4 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 8, - }, - DMat23 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 8, - }, - DMat24 => TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 8, - }, - DMat32 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 8, - }, - DMat34 => TypeInner::Matrix { - columns: VectorSize::Tri, - rows: VectorSize::Quad, - kind: ScalarKind::Float, - width: 8, - }, - DMat42 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Bi, - kind: ScalarKind::Float, - width: 8, - }, - DMat43 => TypeInner::Matrix { - columns: VectorSize::Quad, - rows: VectorSize::Tri, - kind: ScalarKind::Float, - width: 8, - }, - TypeName(ty_name) => { - if let Some(t_pos) = ty_name.0.find("texture") { - let kind = match &ty_name.0[..t_pos] { - "" => ScalarKind::Float, - "i" => ScalarKind::Sint, - "u" => ScalarKind::Uint, - _ => panic!(), - }; - let arrayed = ty_name.0.ends_with("Array"); - let (dim, class) = match &ty_name.0[(t_pos + 7)..] { - "1D" | "1DArray" => (ImageDimension::D1, ImageClass::Sampled), - "2D" | "2DArray" => (ImageDimension::D2, ImageClass::Sampled), - "3D" | "3DArray" => (ImageDimension::D3, ImageClass::Sampled), - "2DMS" | "2DMSArray" => (ImageDimension::D2, ImageClass::Multisampled), - "Cube" | "CubeArray" => (ImageDimension::Cube, ImageClass::Sampled), - _ => panic!(), - }; - - return Some(TypeInner::Image { - kind, - dim, - arrayed, - class, - }); - } - - match ty_name.0.as_str() { - "sampler" => TypeInner::Sampler { comparison: false }, - "samplerShadow" => TypeInner::Sampler { comparison: true }, - _ => unimplemented!(), - } - } - _ => unimplemented!(), - }) -} diff --git a/src/front/glsl_new/lex.rs b/src/front/glsl/lex.rs similarity index 100% rename from src/front/glsl_new/lex.rs rename to src/front/glsl/lex.rs diff --git a/src/front/glsl_new/lex_tests.rs b/src/front/glsl/lex_tests.rs similarity index 100% rename from src/front/glsl_new/lex_tests.rs rename to src/front/glsl/lex_tests.rs diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index be2ee62ad..2af60fe94 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,1375 +1,50 @@ -#![allow(clippy::panic)] -use crate::{ - Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Constant, ConstantInner, EntryPoint, - Expression, FastHashMap, Function, GlobalVariable, Handle, Header, Interpolation, - LocalVariable, Module, ScalarKind, ShaderStage, StorageAccess, StorageClass, StructMember, - Type, TypeInner, VectorSize, -}; -use glsl::{ - parser::{Parse, ParseError}, - syntax::*, -}; -use parser::{Token, TokenMetadata}; - -mod helpers; -mod parser; - -#[derive(Debug, thiserror::Error)] -pub enum ErrorKind { - #[error("Unexpected token:\nexpected: {}\ngot: {}", expected.iter().map(|t| t.type_to_string()).collect::>().join(" |"), got.token)] - UnexpectedToken { - expected: Vec, - got: TokenMetadata, - }, - #[error("Unexpected word:\nexpected: {}\ngot: {got}", expected.join("|"))] - UnexpectedWord { - expected: Vec<&'static str>, - got: String, - }, - #[error("Expected end of line:\ngot: {}", got.token)] - ExpectedEOL { got: TokenMetadata }, - #[error("Unknown pragma: {pragma}")] - UnknownPragma { pragma: String }, - #[error("The extension \"{extension}\" is not supported")] - ExtensionNotSupported { extension: String }, - #[error("All extensions can't be require or enable")] - AllExtensionsEnabled, - #[error("The extension behavior must be one of require|enable|warn|disable got: {behavior}")] - ExtensionUnknownBehavior { behavior: String }, - #[error("The version {version} isn't supported; use either 450 or 460")] - UnsupportedVersion { version: usize }, - #[error("The profile {profile} isn't supported; use core")] - UnsupportedProfile { profile: String }, - #[error("The profile {profile} isn't defined; use core")] - UnknownProfile { profile: String }, - #[error("The preprocessor directive {directive} isn't defined")] - UnknownPreprocessorDirective { directive: String }, - #[error("The preprocessor directives \"else\", \"elif\" or \"endif\" must be preceded by an \"if\", token: {}", token.token)] - UnboundedIfCloserOrVariant { token: TokenMetadata }, - #[error("The preprocessor \"if\" directive can only contain integrals found: {}", token.token)] - NonIntegralType { token: TokenMetadata }, - #[error("Type resolver error: {kind}")] - TypeResolverError { - #[from] - kind: crate::proc::ResolveError, - }, - #[error("Parser error: {error}")] - ParseError { - #[from] - error: ParseError, - }, - #[error("Macro can't begin with GL_")] - ReservedMacro, - #[error("End of line")] - EOL, - #[error("End of file")] - EOF, - #[error("Non constant expression encountered where a constant expression was expected")] - NonConstantExpr, -} - -#[derive(Debug, thiserror::Error)] -#[error("{kind}")] -pub struct Error { - #[from] - kind: ErrorKind, -} - -#[derive(Debug, Copy, Clone)] -enum Global { - Variable(Handle), - StructShorthand(Handle, u32), -} - -struct Parser<'a> { - source: &'a str, - types: Arena, - globals: Arena, - globals_lookup: FastHashMap, - globals_constants: FastHashMap>, - constants: Arena, - functions: Arena, - shader_stage: ShaderStage, -} - -impl<'a> Parser<'a> { - pub fn new(source: &'a str, shader_stage: ShaderStage) -> Self { - Self { - source, - types: Arena::new(), - globals: Arena::new(), - globals_lookup: FastHashMap::default(), - globals_constants: FastHashMap::default(), - constants: Arena::new(), - functions: Arena::new(), - shader_stage, - } - } - - pub fn parse(mut self, entry: String) -> Result { - let ast = TranslationUnit::parse(self.source).map_err(|e| Error { kind: e.into() })?; - - //println!("{:#?}", ast); - - let mut entry_point = None; - let parameter_lookup = FastHashMap::default(); - let mut locals = Arena::::new(); - let mut locals_map = FastHashMap::default(); - let mut expressions = Arena::::new(); - - for declaration in ast { - match declaration { - ExternalDeclaration::Preprocessor(_) => - { - #[cfg(feature = "glsl_preprocessor")] - unreachable!() - } - ExternalDeclaration::FunctionDefinition(function) => { - let function = self.parse_function_definition(function)?; - - if *self.functions[function].name.as_ref().unwrap() == entry { - assert!(entry_point.is_none()); - - entry_point = Some(function); - } - } - ExternalDeclaration::Declaration(decl) => match decl { - Declaration::InitDeclaratorList(mut init) => { - // Get initializer out for lifetime reasons. Maybe self.parse_global needs - // to take a reference and clone what it needs? - let mut initializer = None; - std::mem::swap(&mut initializer, &mut init.head.initializer); - - let handle = self.parse_global(init.head)?; - let name = self.globals[handle].name.clone().unwrap(); - if let Some(initializer) = initializer { - match initializer { - Initializer::Simple(expr) => { - let expr = self.parse_expression( - *expr, - &mut expressions, - &mut locals, - &mut locals_map, - ¶meter_lookup, - &[], - )?; - let handle = expressions.append(expr); - let val = self.eval_const_expr(handle, &expressions)?; - self.globals_constants.insert(name.clone(), val); - } - _ => todo!(), - } - } - - self.globals_lookup.insert(name, Global::Variable(handle)); - } - Declaration::Block(block) => { - let (class, binding, interpolation) = - Self::parse_type_qualifier(block.qualifier); - let ty_name = block.name.0; - - let name = block.identifier.clone().map(|ident| ident.ident.0); - - let mut fields = Vec::new(); - let mut reexports = Vec::new(); - let mut index = 0; - - for field in block.fields { - let ty = self.parse_type(field.ty, &[]).unwrap(); - - for ident in field.identifiers { - let field_name = ident.ident.0; - let origin = crate::MemberOrigin::Offset(0); //TODO - - fields.push(StructMember { - name: Some(field_name.clone()), - origin, - ty: if let Some(array_spec) = ident.array_spec { - let size = self.parse_array_size(array_spec, &[])?; - self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size, - stride: None, - }, - }) - } else { - ty - }, - }); - - if name.is_none() { - reexports.push((field_name, index)); - index += 1; - } - } - } - - let ty = if let Some(array_spec) = - block.identifier.and_then(|ident| ident.array_spec) - { - let base = self.types.fetch_or_append(Type { - name: Some(ty_name), - inner: TypeInner::Struct { members: fields }, - }); - - let size = self.parse_array_size(array_spec, &[])?; - self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base, - size, - stride: None, - }, - }) - } else { - self.types.fetch_or_append(Type { - name: Some(ty_name), - inner: TypeInner::Struct { members: fields }, - }) - }; - - let handle = self.globals.append(GlobalVariable { - binding, - class, - name, - ty, - interpolation, - storage_access: StorageAccess::empty(), //TODO - }); - - for (name, index) in reexports { - self.globals_lookup - .insert(name, Global::StructShorthand(handle, index)); - } - } - _ => unimplemented!(), - }, - } - } - - Ok(Module { - header: Header { - version: (1, 0, 0), - generator: 0, - }, - types: self.types, - constants: self.constants, - global_variables: self.globals, - functions: self.functions, - entry_points: vec![EntryPoint { - stage: self.shader_stage, - function: entry_point.unwrap(), - name: entry, - }], - }) - } - - fn parse_function_definition( - &mut self, - function: FunctionDefinition, - ) -> Result, Error> { - let name = function.prototype.name.0; - - // Parse return type - let ty = self.parse_type(function.prototype.ty.ty, &[]); - - let mut parameter_types = Vec::with_capacity(function.prototype.parameters.len()); - let mut parameter_lookup = FastHashMap::default(); - - let mut local_variables = Arena::::new(); - let mut locals_map = FastHashMap::default(); - let mut expressions = Arena::::new(); - let mut body = Vec::new(); - - // TODO: Parse Qualifiers - for (index, parameter) in function.prototype.parameters.into_iter().enumerate() { - match parameter { - FunctionParameterDeclaration::Named(_ /* TODO */, decl) => { - let ty = self.parse_type(decl.ty, &[]).unwrap(); - - let ty = if let Some(array_spec) = decl.ident.array_spec { - let size = self.parse_array_size(array_spec, &[])?; - self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size, - stride: None, - }, - }) - } else { - ty - }; - - parameter_types.push(ty); - parameter_lookup.insert( - decl.ident.ident.0, - Expression::FunctionParameter(index as u32), - ); - } - FunctionParameterDeclaration::Unnamed(_, ty) => { - parameter_types.push(self.parse_type(ty, &[]).unwrap()); - } - } - } - - for statement in function.statement.statement_list { - match statement { - Statement::Compound(_) => unimplemented!(), - Statement::Simple(statement) => match *statement { - SimpleStatement::Declaration(declaration) => match declaration { - Declaration::InitDeclaratorList(init) => { - self.parse_local_variable( - init, - &mut expressions, - &mut local_variables, - &mut locals_map, - ¶meter_lookup, - ¶meter_types, - )?; - } - _ => unimplemented!(), - }, - SimpleStatement::Expression(Some(expr)) => { - body.push(self.parse_statement( - expr, - &mut expressions, - &mut local_variables, - &mut locals_map, - ¶meter_lookup, - ¶meter_types, - )?); - } - SimpleStatement::Expression(None) => (), - SimpleStatement::Selection(_) => unimplemented!(), - SimpleStatement::Switch(_) => unimplemented!(), - SimpleStatement::CaseLabel(_) => unimplemented!(), - SimpleStatement::Iteration(_) => unimplemented!(), - SimpleStatement::Jump(op) => body.push(match op { - JumpStatement::Continue => crate::Statement::Continue, - JumpStatement::Break => crate::Statement::Break, - JumpStatement::Return(expr) => crate::Statement::Return { - value: expr.map(|expr| { - let expr = self - .parse_expression( - *expr, - &mut expressions, - &mut local_variables, - &mut locals_map, - ¶meter_lookup, - ¶meter_types, - ) - .unwrap(); - expressions.append(expr) - }), - }, - JumpStatement::Discard => crate::Statement::Kill, - }), - }, - } - } - - let handle = self.functions.append(Function { - name: Some(name), - parameter_types, - return_type: ty, - global_usage: vec![], - local_variables, - expressions, - body, - }); - Ok(handle) - } - - fn parse_local_variable( - &mut self, - init: InitDeclaratorList, - expressions: &mut Arena, - locals: &mut Arena, - locals_map: &mut FastHashMap>, - parameter_lookup: &FastHashMap, - parameter_types: &[Handle], - ) -> Result, Error> { - let name = init.head.name.map(|d| d.0); - let ty = { - let ty = self.parse_type(init.head.ty.ty, parameter_types).unwrap(); - - if let Some(array_spec) = init.head.array_specifier { - let size = self.parse_array_size(array_spec, parameter_types)?; - self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size, - stride: None, - }, - }) - } else { - ty - } - }; - - let initializer = if let Some(initializer) = init.head.initializer { - Some(self.parse_initializer( - initializer, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?) - } else { - None - }; - - let handle = locals.append(LocalVariable { - name: name.clone(), - ty, - init: initializer, - }); - - locals_map.insert(name.unwrap(), handle); - - Ok(handle) - } - - fn parse_initializer( - &mut self, - initializer: Initializer, - expressions: &mut Arena, - locals: &mut Arena, - locals_map: &mut FastHashMap>, - parameter_lookup: &FastHashMap, - parameter_types: &[Handle], - ) -> Result, Error> { - match initializer { - Initializer::Simple(expr) => { - let handle = self.parse_expression( - *expr, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?; - - Ok(expressions.append(handle)) - } - Initializer::List(_exprs) => unimplemented!(), - } - } - - fn parse_statement( - &mut self, - expr: Expr, - expressions: &mut Arena, - locals: &mut Arena, - locals_map: &mut FastHashMap>, - parameter_lookup: &FastHashMap, - parameter_types: &[Handle], - ) -> Result { - match expr { - Expr::Assignment(reg, op, value) => { - let pointer = { - let pointer = self.parse_expression( - *reg, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?; - expressions.append(pointer) - }; - - let right = self.parse_expression( - *value, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?; - let value = match op { - AssignmentOp::Equal => right, - AssignmentOp::Mult => Expression::Binary { - op: BinaryOperator::Multiply, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Div => Expression::Binary { - op: BinaryOperator::Divide, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Mod => Expression::Binary { - op: BinaryOperator::Modulo, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Add => Expression::Binary { - op: BinaryOperator::Add, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Sub => Expression::Binary { - op: BinaryOperator::Subtract, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::LShift => Expression::Binary { - op: BinaryOperator::ShiftLeftLogical, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::RShift => { - Expression::Binary { - op: BinaryOperator::ShiftRightArithmetic, /* ??? */ - left: pointer, - right: expressions.append(right), - } - } - AssignmentOp::And => Expression::Binary { - op: BinaryOperator::And, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Xor => Expression::Binary { - op: BinaryOperator::ExclusiveOr, - left: pointer, - right: expressions.append(right), - }, - AssignmentOp::Or => Expression::Binary { - op: BinaryOperator::InclusiveOr, - left: pointer, - right: expressions.append(right), - }, - }; - - Ok(crate::Statement::Store { - pointer, - value: expressions.append(value), - }) - } - Expr::FunCall(_, _) => unimplemented!(), - Expr::PostInc(_) => unimplemented!(), - Expr::PostDec(_) => unimplemented!(), - _ => panic!(), - } - } - - fn parse_expression( - &mut self, - expr: Expr, - expressions: &mut Arena, - locals: &mut Arena, - locals_map: &mut FastHashMap>, - parameter_lookup: &FastHashMap, - parameter_types: &[Handle], - ) -> Result { - match expr { - Expr::Variable(ident) => { - let name = ident.0; - - match name.as_str() { - "gl_VertexIndex" => Ok(Expression::GlobalVariable( - self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }), - )), - "gl_InstanceIndex" => Ok(Expression::GlobalVariable( - self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::InstanceIndex)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }), - )), - "gl_BaseVertex" => Ok(Expression::GlobalVariable( - self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::BaseVertex)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }), - )), - "gl_BaseInstance" => Ok(Expression::GlobalVariable( - self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::BaseInstance)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }), - )), - "gl_Position" => Ok(Expression::GlobalVariable(self.globals.fetch_or_append( - GlobalVariable { - name: Some(name), - class: match self.shader_stage { - ShaderStage::Vertex => StorageClass::Output, - ShaderStage::Fragment { .. } => StorageClass::Input, - _ => panic!(), - }, - binding: Some(Binding::BuiltIn(BuiltIn::Position)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, - }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }, - ))), - "gl_PointSize" => Ok(Expression::GlobalVariable(self.globals.fetch_or_append( - GlobalVariable { - name: Some(name), - class: StorageClass::Output, - binding: Some(Binding::BuiltIn(BuiltIn::PointSize)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 4, - }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }, - ))), - "gl_ClipDistance" => Ok(Expression::GlobalVariable( - self.globals.fetch_or_append(GlobalVariable { - name: Some(name), - class: StorageClass::Output, - binding: Some(Binding::BuiltIn(BuiltIn::ClipDistance)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 4, - }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }), - )), - other => { - if let Some(global) = self.globals_lookup.get(other) { - match *global { - Global::Variable(handle) => Ok(Expression::GlobalVariable(handle)), - Global::StructShorthand(struct_handle, index) => { - Ok(Expression::AccessIndex { - base: expressions - .append(Expression::GlobalVariable(struct_handle)), - index, - }) - } - } - } else if let Some(expr) = parameter_lookup.get(other) { - Ok(expr.clone()) - } else if let Some(local) = locals_map.get(other) { - Ok(Expression::LocalVariable(*local)) - } else { - println!("{}", other); - panic!() - } - } - } - } - Expr::IntConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Sint(value as i64), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - }, - }), - }, - ))), - Expr::UIntConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Uint(value as u64), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - }), - }, - ))), - Expr::BoolConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Bool(value), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Bool, - width: 1, - }, - }), - }, - ))), - Expr::FloatConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Float(value as f64), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 4, - }, - }), - }, - ))), - Expr::DoubleConst(value) => Ok(Expression::Constant(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Float(value), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 8, - }, - }), - }, - ))), - Expr::Unary(op, reg) => { - let expr = self.parse_expression( - *reg, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?; - Ok(Expression::Unary { - op: helpers::glsl_to_spirv_unary_op(op), - expr: expressions.append(expr), - }) - } - Expr::Binary(op, left, right) => { - let left = self.parse_expression( - *left, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?; - let right = self.parse_expression( - *right, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?; - - Ok(Expression::Binary { - op: helpers::glsl_to_spirv_binary_op(op), - left: expressions.append(left), - right: expressions.append(right), - }) - } - Expr::Ternary(_condition, _accept, _reject) => unimplemented!(), - Expr::Assignment(_, _, _) => panic!(), - Expr::Bracket(_reg, _index) => unimplemented!(), - Expr::FunCall(ident, mut args) => { - let name = match ident { - FunIdentifier::Identifier(ident) => ident.0, - FunIdentifier::Expr(_expr) => todo!(), - }; - - match name.as_str() { - "vec2" | "vec3" | "vec4" => Ok(Expression::Compose { - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: match name.chars().last().unwrap() { - '2' => VectorSize::Bi, - '3' => VectorSize::Tri, - '4' => VectorSize::Quad, - _ => panic!(), - }, - kind: ScalarKind::Float, - width: 4, - }, - }), - components: args - .into_iter() - .map(|arg| { - let expr = self - .parse_expression( - arg, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - ) - .unwrap(); - expressions.append(expr) - }) - .collect(), - }), - "texture" => { - let (image, sampler) = - if let Expr::FunCall(ident, mut sample_args) = args.remove(0) { - let name = match ident { - FunIdentifier::Expr(_) => unimplemented!(), - FunIdentifier::Identifier(ident) => ident.0, - }; - - match name.as_str() { - "sampler2D" => ( - self.parse_expression( - sample_args.remove(0), - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?, - self.parse_expression( - sample_args.remove(0), - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?, - ), - _ => unimplemented!(), - } - } else { - panic!() - }; - - let coordinate = self.parse_expression( - args.remove(0), - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?; - - Ok(Expression::ImageSample { - image: expressions.append(image), - sampler: expressions.append(sampler), - coordinate: expressions.append(coordinate), - level: crate::SampleLevel::Auto, - depth_ref: None, //TODO - }) - } - _ => Ok(Expression::Call { - origin: crate::FunctionOrigin::External(name), - arguments: args - .into_iter() - .map(|arg| { - let expr = self - .parse_expression( - arg, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - ) - .unwrap(); - expressions.append(expr) - }) - .collect(), - }), - } - } - Expr::Dot(reg, ident) => { - let handle = { - let expr = self.parse_expression( - *reg, - expressions, - locals, - locals_map, - parameter_lookup, - parameter_types, - )?; - expressions.append(expr) - }; - - let mut typefier = crate::proc::Typifier::new(); - let name = ident.0.as_str(); - let type_handle = typefier - .resolve( - handle, - expressions, - &mut self.types, - &self.constants, - &self.globals, - locals, - &self.functions, - parameter_types, - ) - .map_err(|e| Error { kind: e.into() })?; - let base_type = &self.types[type_handle]; - match base_type.inner { - crate::TypeInner::Struct { ref members } => { - let index = members - .iter() - .position(|m| m.name.as_deref() == Some(name)) - .unwrap() as u32; - Ok(crate::Expression::AccessIndex { - base: handle, - index, - }) - } - crate::TypeInner::Vector { size, kind, width } - | crate::TypeInner::Matrix { - columns: size, - kind, - width, - .. - } => { - const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; - if name.len() > 1 { - let mut components = Vec::with_capacity(name.len()); - - for ch in name.chars() { - let expr = crate::Expression::AccessIndex { - base: handle, - index: MEMBERS[..size as usize] - .iter() - .position(|&m| m == ch) - .unwrap() as u32, - }; - components.push(expressions.append(expr)); - } - let size = match name.len() { - 2 => crate::VectorSize::Bi, - 3 => crate::VectorSize::Tri, - 4 => crate::VectorSize::Quad, - _ => panic!(), - }; - let inner = - if let crate::TypeInner::Matrix { rows, .. } = base_type.inner { - crate::TypeInner::Matrix { - columns: size, - rows, - kind, - width, - } - } else { - crate::TypeInner::Vector { size, kind, width } - }; - Ok(crate::Expression::Compose { - ty: self.types.fetch_or_append(Type { name: None, inner }), - components, - }) - } else { - let ch = name.chars().next().unwrap(); - let index = MEMBERS[..size as usize] - .iter() - .position(|&m| m == ch) - .unwrap() as u32; - Ok(crate::Expression::AccessIndex { - base: handle, - index, - }) - } - } - _ => panic!(), - } - } - Expr::PostInc(_reg) => unimplemented!(), - Expr::PostDec(_reg) => unimplemented!(), - Expr::Comma(_, _) => unimplemented!(), - } - } - - // None = void - fn parse_type( - &mut self, - ty: TypeSpecifier, - parameter_types: &[Handle], - ) -> Option> { - let base_ty = helpers::glsl_to_spirv_type(ty.ty)?; - - let ty = if let Some(array_spec) = ty.array_specifier { - let handle = self.types.fetch_or_append(Type { - name: None, - inner: base_ty, - }); - let size = self.parse_array_size(array_spec, parameter_types).unwrap(); - - TypeInner::Array { - base: handle, - size, - stride: None, - } - } else { - base_ty - }; - - Some(self.types.fetch_or_append(Type { - name: None, - inner: ty, - })) - } - - fn parse_global(&mut self, head: SingleDeclaration) -> Result, Error> { - let name = head.name.map(|d| d.0); - let ty = { - let ty = self.parse_type(head.ty.ty, &[]).unwrap(); - - if let Some(array_spec) = head.array_specifier { - let size = self.parse_array_size(array_spec, &[])?; - self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size, - stride: None, - }, - }) - } else { - ty - } - }; - - let (class, binding, interpolation) = head - .ty - .qualifier - .map(Self::parse_type_qualifier) - .unwrap_or((StorageClass::Private, None, None)); - - Ok(self.globals.append(GlobalVariable { - name, - class, - binding, - ty, - interpolation, - storage_access: StorageAccess::empty(), //TODO - })) - } - - /// https://www.khronos.org/opengl/wiki/Core_Language_(GLSL)#Constant_expression - pub fn eval_const_expr( - &mut self, - expr: Handle, - expressions: &Arena, - ) -> Result, Error> { - match &expressions[expr] { - Expression::Constant(handle) => Ok(*handle), - Expression::Call { .. } => todo!(), - Expression::GlobalVariable(handle) => { - let name = self.globals[*handle].name.as_ref().unwrap(); - if let Some(handle) = self.globals_constants.get(name) { - Ok(*handle) - } else { - todo!("Global const error") - } - } - Expression::Binary { left, right, op } => { - let left = self.eval_const_expr(*left, expressions)?; - let right = self.eval_const_expr(*right, expressions)?; - let inner: ConstantInner; - let ty; - match op { - BinaryOperator::Add => { - match (&self.constants[left].inner, &self.constants[right].inner) { - (ConstantInner::Sint(left), ConstantInner::Sint(right)) => { - inner = ConstantInner::Sint(left + right); - ty = self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - }, - }) - } - (ConstantInner::Uint(left), ConstantInner::Uint(right)) => { - inner = ConstantInner::Uint(left + right); - ty = self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - }) - } - (ConstantInner::Float(left), ConstantInner::Float(right)) => { - inner = ConstantInner::Float(left + right); - ty = self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 4, - }, - }) - } - _ => todo!(), - } - } - - _ => todo!(), - } - Ok(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner, - ty, - })) - } - expr => todo!("Const eval for {:?}", expr), - } - } - - pub fn parse_array_size( - &mut self, - array_spec: ArraySpecifier, - parameter_types: &[Handle], - ) -> Result { - let parameter_lookup = FastHashMap::default(); - let mut locals = Arena::::new(); - let mut locals_map = FastHashMap::default(); - let mut expressions = Arena::::new(); - let size = match array_spec { - ArraySpecifier::Unsized => ArraySize::Dynamic, - ArraySpecifier::ExplicitlySized(expr) => { - let expr = self.parse_expression( - *expr, - &mut expressions, - &mut locals, - &mut locals_map, - ¶meter_lookup, - parameter_types, - )?; - let handle = expressions.append(expr); - - let const_handle = self.eval_const_expr(handle, &expressions)?; - - match &self.constants[const_handle].inner { - ConstantInner::Sint(val) => ArraySize::Static(*val as u32), - ConstantInner::Uint(val) => ArraySize::Static(*val as u32), - val => panic!( - "Array size must be an integral constant expression, got: {:?}", - val - ), - } - } - }; - - Ok(size) - } - - fn parse_type_qualifier( - qualifier: TypeQualifier, - ) -> (StorageClass, Option, Option) { - let mut storage = None; - let mut binding = None; - let mut interpolation = None; - - for qualifier in qualifier.qualifiers { - match qualifier { - TypeQualifierSpec::Storage(storage_qualifier) => { - assert!(storage.is_none()); - - storage = Some(match storage_qualifier { - StorageQualifier::Const => StorageClass::Constant, - StorageQualifier::In => StorageClass::Input, - StorageQualifier::Out => StorageClass::Output, - StorageQualifier::Uniform => StorageClass::Uniform, - StorageQualifier::Buffer => StorageClass::StorageBuffer, - StorageQualifier::Shared => StorageClass::WorkGroup, - StorageQualifier::Coherent => StorageClass::WorkGroup, - _ => panic!(), - }); - } - TypeQualifierSpec::Layout(layout_qualifier) => { - assert!(binding.is_none()); - - let mut set = None; - let mut bind = None; - let mut location = None; - - for identifier in layout_qualifier.ids { - match identifier { - LayoutQualifierSpec::Identifier(identifier, Some(expr)) => { - if let Expr::IntConst(word) = *expr { - match identifier.as_str() { - "location" => { - assert!(set.is_none(),); - assert!(bind.is_none(),); - assert!(location.is_none()); - - location = Some(word); - } - "binding" => { - assert!(bind.is_none(),); - assert!(location.is_none()); - - bind = Some(word); - } - "set" => { - assert!(set.is_none(),); - assert!(location.is_none()); - - set = Some(word); - } - _ => {} - } - } - } - _ => unimplemented!(), - } - } - - if let (Some(set), Some(bind)) = (set, bind) { - binding = Some(Binding::Descriptor { - set: set as u32, - binding: bind as u32, - }) - } else if let Some(location) = location { - binding = Some(Binding::Location(location as u32)) - } else { - panic!() - } - } - TypeQualifierSpec::Interpolation(interpolation_qualifier) => { - interpolation = Some(match interpolation_qualifier { - InterpolationQualifier::NoPerspective => Interpolation::Linear, - InterpolationQualifier::Flat => Interpolation::Flat, - InterpolationQualifier::Smooth => Interpolation::Perspective, - }); - } - _ => unimplemented!(), - } - } - - ( - storage.unwrap_or(StorageClass::Private), - binding, - interpolation, - ) - } -} - -pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { - let input = parser::parse(source)?; - - log::debug!("------GLSL PREPROCESSOR------"); - log::debug!("\n{}", input); - log::debug!("-----------------------------"); - - Parser::new(&input, stage).parse(entry) -} +use crate::{EntryPoint, Module, ShaderStage}; +mod lex; #[cfg(test)] -mod tests { - use super::parse_str; +mod lex_tests; - #[test] - fn test_vertex() { - let data = include_str!("../../../test-data/glsl_vertex_test_shader.vert"); +mod ast; +use ast::Program; - println!( - "{:#?}", - parse_str(data, String::from("main"), crate::ShaderStage::Vertex) - ); +use lex::Lexer; +mod error; +use error::ParseError; +mod parser; +#[cfg(test)] +mod parser_tests; +mod token; +mod types; + +#[cfg(all(test, feature = "serialize"))] +mod rosetta_tests; + +pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { + log::debug!("------ GLSL-pomelo ------"); + + let mut program = Program::new(stage); + let lex = Lexer::new(source); + let mut parser = parser::Parser::new(&mut program); + + for token in lex { + parser.parse(token)?; + } + parser.end_of_input()?; + + let mut module = Module::generate_empty(); + module.functions = program.functions; + module.types = program.types; + module.constants = program.constants; + module.global_variables = program.global_variables; + + // find entry point + if let Some(entry_handle) = program.lookup_function.get(&entry) { + module.entry_points.push(EntryPoint { + stage, + name: entry, + function: *entry_handle, + }); } - #[test] - fn test_frag() { - let _ = env_logger::try_init(); - - let data = include_str!("../../../test-data/glsl_phong_lighting.frag"); - - println!( - "{:#?}", - parse_str( - data, - String::from("main"), - crate::ShaderStage::Fragment { - early_depth_test: None - } - ) - ); - } - - #[cfg(feature = "glsl_preprocessor")] - #[test] - fn test_preprocess() { - let _ = env_logger::try_init(); - - let data = include_str!("../../../test-data/glsl_preprocessor_abuse.vert"); - - println!( - "{:#?}", - parse_str(data, String::from("main"), crate::ShaderStage::Vertex) - ); - } - - #[cfg(feature = "glsl_preprocessor")] - #[test] - #[should_panic] - fn test_preprocess_ifs() { - let _ = env_logger::try_init(); - - let data = include_str!("../../../test-data/glsl_if_preprocessor.vert"); - - println!( - "{:#?}", - parse_str(data, String::from("main"), crate::ShaderStage::Vertex) - ); - } + Ok(module) } diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl/parser.rs similarity index 100% rename from src/front/glsl_new/parser.rs rename to src/front/glsl/parser.rs diff --git a/src/front/glsl/parser/lex.rs b/src/front/glsl/parser/lex.rs deleted file mode 100644 index 09c2f43e7..000000000 --- a/src/front/glsl/parser/lex.rs +++ /dev/null @@ -1,254 +0,0 @@ -use super::{Token, TokenMetadata}; -use std::{iter::Enumerate, str::Lines}; - -fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { - if input.starts_with(what) { - Some(&input[what.len()..]) - } else { - None - } -} - -fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str, usize) { - let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); - let (o, i) = input.split_at(pos); - (o, i, pos) -} - -pub fn consume_token(input: &String) -> (Token, &str, usize, usize) { - let mut input = input.as_str(); - - let start = input - .find(|c: char| !c.is_whitespace()) - .unwrap_or(input.chars().count()); - input = &input[start..]; - - let mut chars = input.chars(); - let cur = match chars.next() { - Some(c) => c, - None => return (Token::End, input, start, start + 1), - }; - match cur { - ':' => { - input = chars.as_str(); - if chars.next() == Some(':') { - (Token::DoubleColon, chars.as_str(), start, start + 2) - } else { - (Token::Separator(cur), input, start, start + 1) - } - } - ';' | ',' | '.' => (Token::Separator(cur), chars.as_str(), start, start + 1), - '(' | ')' | '{' | '}' | '[' | ']' => (Token::Paren(cur), chars.as_str(), start, start + 1), - '<' | '>' => { - input = chars.as_str(); - let next = chars.next(); - if next == Some('=') { - ( - Token::LogicalOperation(cur), - chars.as_str(), - start, - start + 1, - ) - } else if next == Some(cur) { - (Token::ShiftOperation(cur), chars.as_str(), start, start + 2) - } else { - (Token::Operation(cur), input, start, start + 1) - } - } - '0'..='9' => { - let (number, rest, pos) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); - if let Some(_) = number.find('.') { - if ( - chars.next().map(|c| c.to_lowercase().next().unwrap()), - chars.next().map(|c| c.to_lowercase().next().unwrap()), - ) == (Some('l'), Some('f')) - { - ( - Token::Double(number.parse().unwrap()), - chars.as_str(), - start, - start + pos + 2, - ) - } else { - ( - Token::Float(number.parse().unwrap()), - chars.as_str(), - start, - start + pos, - ) - } - } else { - ( - Token::Integral(number.parse().unwrap()), - rest, - start, - start + pos, - ) - } - } - 'a'..='z' | 'A'..='Z' | '_' => { - let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); - (Token::Word(String::from(word)), rest, start, start + pos) - } - '+' | '-' => { - input = chars.as_str(); - match chars.next() { - Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), - Some(next) if cur == next => (Token::Sufix(cur), chars.as_str(), start, start + 2), - _ => (Token::Operation(cur), input, start, start + 1), - } - } - '%' | '^' => { - input = chars.as_str(); - - if chars.next() == Some('=') { - (Token::OpAssign(cur), chars.as_str(), start, start + 2) - } else { - (Token::Operation(cur), input, start, start + 1) - } - } - '!' => { - input = chars.as_str(); - - if chars.next() == Some('=') { - ( - Token::LogicalOperation(cur), - chars.as_str(), - start, - start + 2, - ) - } else { - (Token::Operation(cur), input, start, start + 1) - } - } - '*' => { - input = chars.as_str(); - match chars.next() { - Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), - Some('/') => ( - Token::MultiLineCommentClose, - chars.as_str(), - start, - start + 2, - ), - _ => (Token::Operation(cur), input, start, start + 1), - } - } - '/' => { - input = chars.as_str(); - match chars.next() { - Some('=') => (Token::OpAssign(cur), chars.as_str(), start, start + 2), - Some('/') => (Token::LineComment, chars.as_str(), start, start + 2), - Some('*') => ( - Token::MultiLineCommentOpen, - chars.as_str(), - start, - start + 2, - ), - _ => (Token::Operation(cur), input, start, start + 1), - } - } - '=' | '&' | '|' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - ( - Token::LogicalOperation(cur), - chars.as_str(), - start, - start + 2, - ) - } else { - (Token::Operation(cur), input, start, start + 1) - } - } - '#' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::TokenPasting, chars.as_str(), start, start + 2) - } else { - (Token::Preprocessor, input, start, start + 1) - } - } - '~' => (Token::Operation(cur), chars.as_str(), start, start + 1), - '?' => (Token::Selection, chars.as_str(), start, start + 1), - _ => (Token::Unknown(cur), chars.as_str(), start, start + 1), - } -} - -#[derive(Clone, Debug)] -pub struct Lexer<'a> { - lines: Enumerate>, - input: String, - line: usize, - offset: usize, -} - -impl<'a> Lexer<'a> { - pub fn new(input: &'a str) -> Self { - let mut lines = input.lines().enumerate(); - let (line, input) = lines.next().unwrap_or((0, "")); - let mut input = String::from(input); - - while input.chars().last() == Some('\\') { - if let Some((_, next)) = lines.next() { - input.pop(); - input.push_str(next); - } else { - break; - } - } - - Lexer { - lines, - input, - line, - offset: 0, - } - } - - #[must_use] - pub fn next(&mut self) -> TokenMetadata { - let (token, rest, start, end) = consume_token(&self.input); - - if token == Token::End { - match self.lines.next() { - Some((line, input)) => { - let mut input = String::from(input); - - while input.chars().last() == Some('\\') { - if let Some((_, next)) = self.lines.next() { - input.pop(); - input.push_str(next); - } else { - break; - } - } - - self.input = input; - self.line = line; - self.offset = 0; - self.next() - } - None => TokenMetadata { - token: Token::End, - line: self.line, - chars: self.offset + start..end + self.offset, - }, - } - } else { - self.input = String::from(rest); - let metadata = TokenMetadata { - token, - line: self.line, - chars: self.offset + start..end + self.offset, - }; - self.offset += end; - metadata - } - } - - #[must_use] - pub fn peek(&mut self) -> TokenMetadata { - self.clone().next() - } -} diff --git a/src/front/glsl/parser/mod.rs b/src/front/glsl/parser/mod.rs deleted file mode 100644 index 8a1634da7..000000000 --- a/src/front/glsl/parser/mod.rs +++ /dev/null @@ -1,245 +0,0 @@ -#![allow(clippy::all)] -#![allow(dead_code)] - -use super::{Error, ErrorKind}; -use crate::FastHashMap; -use std::{ - fmt, - iter::Peekable, - ops::{Deref, Range}, - vec::IntoIter, -}; - -pub mod lex; - -#[cfg(feature = "glsl_preprocessor")] -pub mod preprocessor; - -type Tokens = Peekable>; - -#[derive(Debug, Clone)] -pub struct TokenMetadata { - pub token: Token, - pub line: usize, - pub chars: Range, -} - -impl Deref for TokenMetadata { - type Target = Token; - - fn deref(&self) -> &Token { - &self.token - } -} - -#[derive(Debug, PartialEq, Clone)] -pub enum Token { - Separator(char), - DoubleColon, - Paren(char), - Integral(usize), - Float(f32), - Double(f64), - Word(String), - Operation(char), - OpAssign(char), - LogicalOperation(char), - ShiftOperation(char), - Unknown(char), - LineComment, - MultiLineCommentOpen, - MultiLineCommentClose, - Preprocessor, - End, - Selection, - Sufix(char), - TokenPasting, -} - -impl Token { - pub fn type_to_string(&self) -> String { - match self { - Token::Separator(separator) => separator.to_string(), - Token::DoubleColon => ":".to_string(), - Token::Paren(paren) => paren.to_string(), - Token::Integral(_) => "integer".to_string(), - Token::Float(_) => "float".to_string(), - Token::Double(_) => "double".to_string(), - Token::Word(_) => "word".to_string(), - Token::Operation(op) => op.to_string(), - Token::OpAssign(op) => format!("{}=", op), - Token::LogicalOperation(op) => format!("{}=", op), - Token::ShiftOperation(op) => format!("{0}{0}", op), - Token::Unknown(_) => "unknown".to_string(), - Token::LineComment => "//".to_string(), - Token::MultiLineCommentOpen => "/*".to_string(), - Token::MultiLineCommentClose => "*/".to_string(), - Token::Preprocessor => "#".to_string(), - Token::End => "EOF".to_string(), - Token::Selection => "?".to_string(), - Token::Sufix(op) => format!("{0}{0}", op), - Token::TokenPasting => "##".to_string(), - } - } -} - -impl fmt::Display for Token { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Token::Separator(sep) => write!(f, "{}", sep), - Token::DoubleColon => write!(f, ":"), - Token::Paren(paren) => write!(f, "{}", paren), - Token::Integral(int) => write!(f, "{}", int), - Token::Float(float) => write!(f, "{}", float), - Token::Double(double) => write!(f, "{}", double), - Token::Word(word) => write!(f, "{}", word), - Token::Operation(op) => write!(f, "{}", op), - Token::OpAssign(op) => write!(f, "{}=", op), - Token::LogicalOperation(op) => write!(f, "{0}=", op), - Token::ShiftOperation(op) => write!(f, "{0}{0}", op), - Token::Unknown(unknown) => write!(f, "{}", unknown), - Token::LineComment => write!(f, "//"), - Token::MultiLineCommentOpen => write!(f, "/*"), - Token::MultiLineCommentClose => write!(f, "*/"), - Token::Preprocessor => write!(f, "#"), - Token::End => write!(f, ""), - Token::Selection => write!(f, "?"), - Token::Sufix(op) => write!(f, "{0}{0}", op), - Token::TokenPasting => write!(f, "##"), - } - } -} - -#[derive(Debug)] -pub enum Node { - Ident(String), - Const(Literal), -} - -#[derive(Debug, Copy, Clone)] -pub enum Literal { - Double(f64), - Float(f32), - Uint(usize), - Sint(isize), - Bool(bool), -} - -fn parse_primary_expression(tokens: &mut Tokens) -> Result { - let token = tokens.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - match token.token { - Token::Word(ident) => Ok(match ident.as_str() { - "true" => Node::Const(Literal::Bool(true)), - "false" => Node::Const(Literal::Bool(false)), - _ => Node::Ident(ident), - }), - Token::Integral(uint) => Ok(Node::Const(Literal::Uint(uint))), - Token::Float(float) => Ok(Node::Const(Literal::Float(float))), - Token::Double(double) => Ok(Node::Const(Literal::Double(double))), - Token::Paren('(') => todo!(), /* parse_expression */ - _ => Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![ - Token::Word(String::new()), - Token::Integral(0), - Token::Double(0.0), - Token::Float(0.0), - Token::Paren('('), - ], - got: token, - }, - }), - } -} - -pub(self) fn parse_comments(mut lexer: lex::Lexer) -> Result, Error> { - let mut tokens = Vec::new(); - - loop { - let token = lexer.next(); - - match token.token { - Token::MultiLineCommentOpen => { - let mut token = lexer.next(); - while Token::MultiLineCommentClose != token.token { - match token.token { - Token::End => { - return Err(Error { - kind: ErrorKind::EOF, - }) - } - _ => {} - } - - token = lexer.next(); - } - } - Token::LineComment => { - while token.line == lexer.peek().line && Token::End != lexer.peek().token { - let _ = lexer.next(); - } - } - Token::End => { - tokens.push(token); - break; - } - _ => tokens.push(token), - } - } - - Ok(tokens) -} - -pub fn parse(input: &str) -> Result { - let lexer = lex::Lexer::new(input); - - let tokens = parse_comments(lexer)?; - - let mut macros = FastHashMap::default(); - - macros.insert( - String::from("GL_SPIRV"), - vec![TokenMetadata { - token: Token::Integral(100), - line: 0, - chars: 0..1, - }], - ); - macros.insert( - String::from("VULKAN"), - vec![TokenMetadata { - token: Token::Integral(100), - line: 0, - chars: 0..1, - }], - ); - - log::trace!("------GLSL COMMENT STRIPPED------"); - log::trace!("\n{:#?}", tokens); - log::trace!("---------------------------------"); - - #[cfg(feature = "glsl_preprocessor")] - let tokens = preprocessor::preprocess(&mut tokens.into_iter().peekable(), &mut macros)?; - - let mut line = 0; - let mut start = 0; - - Ok(tokens.into_iter().fold(String::new(), |mut acc, token| { - if token.line - line != 0 { - acc.push_str(&"\n".repeat(token.line - line)); - start = 0; - line = token.line; - } - - acc.push_str(&" ".repeat(token.chars.start - start)); - - acc.push_str(&token.token.to_string()); - - start = token.chars.end; - - acc - })) -} diff --git a/src/front/glsl/parser/preprocessor.rs b/src/front/glsl/parser/preprocessor.rs deleted file mode 100644 index a093c5d2d..000000000 --- a/src/front/glsl/parser/preprocessor.rs +++ /dev/null @@ -1,1618 +0,0 @@ -use super::{ - super::{Error, ErrorKind}, - Literal, Token, TokenMetadata, -}; -use crate::{BinaryOperator, FastHashMap}; -use std::{iter::Peekable, vec::IntoIter}; - -#[derive(Debug)] -enum PreprocessorIfNode { - Literal(Literal), - Unary { - op: UnaryOp, - tgt: Box, - }, - Binary { - left: Box, - op: BinaryOperator, - right: Box, - }, -} - -impl Literal { - pub fn as_isize(&self) -> isize { - match self { - Literal::Double(double) => *double as isize, - Literal::Float(float) => *float as isize, - Literal::Uint(uint) => *uint as isize, - Literal::Sint(sint) => *sint, - Literal::Bool(val) => *val as isize, - } - } - - pub fn as_bool(&self) -> Result { - Ok(match self { - Literal::Double(_) | Literal::Float(_) => panic!(), - Literal::Uint(uint) => { - if *uint == 0 { - false - } else { - true - } - } - Literal::Sint(sint) => { - if *sint == 0 { - false - } else { - true - } - } - Literal::Bool(val) => *val, - }) - } -} - -#[derive(Debug, Copy, Clone)] -pub enum UnaryOp { - Positive, - Negative, - BitWiseNot, - LogicalNot, -} - -macro_rules! get_macro { - ($name:expr, $token:expr, $line_offset:expr,$macros:expr) => { - match $name.as_str() { - "__LINE__" => Some(vec![TokenMetadata { - token: Token::Integral(($token.line as i32 + $line_offset + 1) as usize), - line: 0, - chars: 0..1, - }]), - "__FILE__" => Some(vec![TokenMetadata { - token: Token::Integral(0), - line: 0, - chars: 0..1, - }]), - "__VERSION__" => Some(vec![TokenMetadata { - token: Token::Integral(460), - line: 0, - chars: 0..1, - }]), /* TODO */ - other => $macros.get(other).cloned().map(|mut tokens| { - let mut start = tokens[0].chars.start; - let mut offset = 0; - - for token in tokens.iter_mut() { - token.line = $token.line; - - let length = token.chars.end - token.chars.start; - - offset += token.chars.start - start; - start = token.chars.start; - - token.chars.start = $token.chars.start + offset; - - token.chars.end = length + $token.chars.start + offset; - } - tokens - }), - } - }; -} - -pub fn preprocess( - lexer: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result, Error> { - let mut tokens = Vec::new(); - let mut line_offset = 0i32; - - let mut offset = (0, 0); - - loop { - let token = match lexer.next() { - Some(t) => t, - None => break, - }; - - match token.token { - Token::Preprocessor => { - let preprocessor_op_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - continue; - }; - - let preprocessor_op = if let Token::Word(name) = preprocessor_op_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: preprocessor_op_token, - }, - }); - }; - - match preprocessor_op.as_str() { - "define" => { - let macro_name_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let macro_name = if let Token::Word(name) = macro_name_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - if macro_name.starts_with("GL_") { - return Err(Error { - kind: ErrorKind::ReservedMacro, - }); - } - - let mut macro_tokens = Vec::new(); - - while Some(token.line) == lexer.peek().map(|t| t.line) { - let macro_token = lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - match macro_token.token { - Token::Word(ref word) => { - match get_macro!(word, &token, line_offset, macros) { - Some(stream) => macro_tokens.append(&mut stream.clone()), - None => macro_tokens.push(macro_token), - } - } - _ => macro_tokens.push(macro_token), - } - } - - macros.insert(macro_name, macro_tokens); - } - "undef" => { - let macro_name_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let macro_name = if let Token::Word(name) = macro_name_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - macros.remove(¯o_name); - } - "if" => { - let mut expr = Vec::new(); - - while lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - == token.line - { - let expr_token = lexer.next().unwrap(); - - match expr_token.token { - Token::Word(ref macro_name) => expr.append( - &mut get_macro!(macro_name, expr_token, line_offset, macros) - .unwrap(), - ), - _ => expr.push(expr_token), - } - } - - let condition = evaluate_preprocessor_if(expr, macros)?; - - let mut body_tokens = - parse_preprocessor_if(lexer, macros, condition, line_offset, offset)?; - - tokens.append(&mut body_tokens); - } - "ifdef" | "ifndef" => { - let macro_name_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().unwrap() - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let macro_name = if let Token::Word(name) = macro_name_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - // There shouldn't be any more tokens on this line so we throw a error - if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } - - let mut body_tokens = parse_preprocessor_if( - lexer, - macros, - match preprocessor_op.as_str() { - "ifdef" => macros.get(¯o_name).is_some(), - "ifndef" => macros.get(¯o_name).is_none(), - _ => unreachable!(), - }, - line_offset, - offset, - )?; - - tokens.append(&mut body_tokens); - } - "else" | "elif" | "endif" => { - return Err(Error { - kind: ErrorKind::UnboundedIfCloserOrVariant { token }, - }) - } - "error" => { - let mut error_token = lexer.next(); - - let first_byte = error_token - .as_ref() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .chars - .start; - - let mut error_message = String::new(); - - while error_token.as_ref().map(|t| t.line) == Some(token.line) { - let error_msg_token = error_token.as_ref().unwrap(); - - let spacing = error_msg_token.chars.start - - first_byte - - error_message.chars().count(); - - error_message.push_str(&" ".repeat(spacing)); - error_message.push_str(error_msg_token.token.to_string().as_str()); - - error_token = lexer.next() - } - - panic!(error_message) - } - "pragma" => { - let pragma_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let pragma = if let Token::Word(name) = pragma_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: pragma_token, - }, - }); - }; - - match pragma.as_str() { - "optimize" => { - let open_paren_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if Token::Paren('(') != open_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren('(')], - got: open_paren_token, - }, - }); - }; - - let status_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let _ = if let Token::Word(name) = status_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: status_token, - }, - }); - }; - - let close_paren_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if Token::Paren(')') != close_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren(')')], - got: close_paren_token, - }, - }); - }; - } - "debug" => { - let open_paren_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if Token::Paren('(') != open_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren('(')], - got: open_paren_token, - }, - }); - }; - - let status_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let _ = if let Token::Word(name) = status_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: status_token, - }, - }); - }; - - let close_paren_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if Token::Paren(')') != close_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren(')')], - got: close_paren_token, - }, - }); - }; - } - _ => { - return Err(Error { - kind: ErrorKind::UnknownPragma { pragma }, - }) - } - } - } - "extension" => { - let extension_name_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let extension_name = if let Token::Word(word) = extension_name_token.token { - word - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: extension_name_token, - }, - }); - }; - - let separator_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if separator_token.token != Token::DoubleColon { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::DoubleColon], - got: separator_token, - }, - }); - } - - let behavior_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let behavior = if let Token::Word(word) = behavior_token.token { - word - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: behavior_token, - }, - }); - }; - - match extension_name.as_str() { - "all" => match behavior.as_str() { - "require" | "enable" => { - return Err(Error { - kind: ErrorKind::AllExtensionsEnabled, - }) - } - "warn" | "disable" => {} - _ => { - return Err(Error { - kind: ErrorKind::ExtensionUnknownBehavior { behavior }, - }) - } - }, - _ => match behavior.as_str() { - "require" => { - return Err(Error { - kind: ErrorKind::ExtensionNotSupported { - extension: extension_name, - }, - }) - } - "enable" | "warn" | "disable" => log::warn!( - "Unsupported extensions was enabled: {}", - extension_name - ), - _ => { - return Err(Error { - kind: ErrorKind::ExtensionUnknownBehavior { behavior }, - }) - } - }, - } - } - "version" => { - let version_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let version = if let Token::Integral(int) = version_token.token { - int - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Integral(0)], - got: version_token, - }, - }); - }; - - match version { - 450 | 460 => {} - _ => { - return Err(Error { - kind: ErrorKind::UnsupportedVersion { version }, - }) - } - }; - - let profile_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let profile = if let Token::Word(word) = profile_token.token { - word - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: profile_token, - }, - }); - }; - - match profile.as_str() { - "core" => macros.insert( - String::from("GL_core_profile"), - vec![TokenMetadata { - token: Token::Integral(1), - line: 0, - chars: 0..1, - }], - ), - "compatibility" | "es" => { - return Err(Error { - kind: ErrorKind::UnsupportedProfile { profile }, - }) - } - _ => { - return Err(Error { - kind: ErrorKind::UnknownProfile { profile }, - }) - } - }; - } - "line" => { - let line_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let line = if let Token::Integral(int) = line_token.token { - int - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Integral(0)], - got: line_token, - }, - }); - }; - - let source_string_token = if token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().ok_or(Error { - kind: ErrorKind::EOF, - })? - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - if let Token::Word(_) = source_string_token.token { - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: source_string_token, - }, - }); - } - - line_offset = line as i32 - token.line as i32; - } - _ => { - return Err(Error { - kind: ErrorKind::UnknownPreprocessorDirective { - directive: preprocessor_op, - }, - }) - } - } - - if lexer.peek().map(|t| t.line) == Some(token.line) { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } - } - Token::End => { - let mut token = token; - - if offset.0 == token.line { - token.chars.start = (token.chars.start as isize + offset.1) as usize; - token.chars.end = (token.chars.end as isize + offset.1) as usize; - } - - tokens.push(token); - break; - } - Token::Word(ref word) => match get_macro!(word, &token, line_offset, macros) { - Some(mut stream) => { - for macro_token in stream.iter_mut() { - if offset.0 == token.line { - macro_token.chars.start = - (macro_token.chars.start as isize + offset.1) as usize; - macro_token.chars.end = - (macro_token.chars.end as isize + offset.1) as usize; - } - } - - offset.0 = stream.last().unwrap().line; - offset.1 = stream.last().unwrap().chars.end as isize - token.chars.end as isize; - - tokens.append(&mut stream) - } - None => { - let mut token = token; - - if offset.0 == token.line { - token.chars.start = (token.chars.start as isize + offset.1) as usize; - token.chars.end = (token.chars.end as isize + offset.1) as usize; - } - - tokens.push(token) - } - }, - _ => { - let mut token = token; - - if offset.0 == token.line { - token.chars.start = (token.chars.start as isize + offset.1) as usize; - token.chars.end = (token.chars.end as isize + offset.1) as usize; - } - - tokens.push(token) - } - } - } - - Ok(tokens) -} - -fn parse_preprocessor_if( - lexer: &mut Peekable>, - macros: &mut FastHashMap>, - mut condition: bool, - line_offset: i32, - offset: (usize, isize), -) -> Result, Error> { - let mut body = Vec::new(); - let mut else_block = false; - - loop { - let macro_token = lexer.peek().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - if let Token::Preprocessor = macro_token.token { - let macro_token = lexer.next().unwrap(); - - let directive_token = if macro_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().unwrap() - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let directive = if let Token::Word(name) = directive_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_token, - }, - }); - }; - - match directive.as_str() { - "if" => { - let mut expr = Vec::new(); - - while lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - == macro_token.line - { - let expr_token = lexer.next().unwrap(); - - match expr_token.token { - Token::Word(ref macro_name) => expr.append( - &mut get_macro!(macro_name, expr_token, line_offset, macros) - .unwrap(), - ), - _ => expr.push(expr_token), - } - } - - let condition = evaluate_preprocessor_if(expr, macros)?; - - let mut body_tokens = - parse_preprocessor_if(lexer, macros, condition, line_offset, offset)?; - - body.append(&mut body_tokens); - } - "elif" => { - let mut expr = Vec::new(); - - while lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - == macro_token.line - { - let expr_token = lexer.next().unwrap(); - - match expr_token.token { - Token::Word(ref macro_name) => expr.append( - &mut get_macro!(macro_name, expr_token, line_offset, macros) - .unwrap(), - ), - _ => expr.push(expr_token), - } - } - - if !condition { - condition = evaluate_preprocessor_if(expr, macros)?; - } - } - "ifdef" | "ifndef" => { - let macro_name_token = if macro_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - lexer.next().unwrap() - } else { - return Err(Error { - kind: ErrorKind::EOL, - }); - }; - - let macro_name = if let Token::Word(name) = macro_name_token.token { - name - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - // There shouldn't be any more tokens on this line so we throw a error - if macro_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } - - let mut body_tokens = parse_preprocessor_if( - lexer, - macros, - match directive.as_str() { - "ifdef" => macros.get(¯o_name).is_some(), - "ifndef" => macros.get(¯o_name).is_none(), - _ => unreachable!(), - }, - line_offset, - offset, - )?; - - body.append(&mut body_tokens); - } - "else" => { - // There shouldn't be any more tokens on this line so we throw a error - if directive_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } - - if else_block { - return Err(Error { - kind: ErrorKind::UnexpectedWord { - expected: vec!["endif"], - got: directive, - }, - }); - } - - else_block = true; - condition = !condition; - } - "endif" => { - // There shouldn't be any more tokens on this line so we throw a error - if directive_token.line - == lexer - .peek() - .ok_or(Error { - kind: ErrorKind::EOF, - })? - .line - { - if lexer.peek().unwrap().token != Token::End { - return Err(Error { - kind: ErrorKind::ExpectedEOL { - got: lexer.next().unwrap(), - }, - }); - } else { - body.push(lexer.next().unwrap()); - } - } - - break; - } - _ => {} - } - } - - if condition { - body.push(lexer.next().unwrap()); - } else { - lexer.next().unwrap(); - } - } - - let body_tokens = preprocess(&mut body.into_iter().peekable(), macros)?; - - Ok(body_tokens) -} - -fn evaluate_preprocessor_if( - expr: Vec, - macros: &mut FastHashMap>, -) -> Result { - let tree = logical_or_parser(&mut expr.into_iter().peekable(), macros)?; - log::trace!("{:#?}", tree); - evaluate_node(tree)?.as_bool() -} - -fn evaluate_node(node: PreprocessorIfNode) -> Result { - Ok(match node { - PreprocessorIfNode::Literal(literal) => literal, - PreprocessorIfNode::Unary { op, tgt } => { - let literal = evaluate_node(*tgt)?; - - match op { - UnaryOp::Positive => literal, - UnaryOp::Negative => Literal::Sint(-literal.as_isize()), - UnaryOp::BitWiseNot => Literal::Sint(!literal.as_isize()), - UnaryOp::LogicalNot => Literal::Sint((!literal.as_bool()?) as isize), - } - } - PreprocessorIfNode::Binary { left, op, right } => { - let left = evaluate_node(*left)?; - let right = evaluate_node(*right)?; - - match op { - BinaryOperator::Multiply => Literal::Sint(left.as_isize() * right.as_isize()), - BinaryOperator::Divide => Literal::Sint(left.as_isize() / right.as_isize()), - BinaryOperator::Modulo => Literal::Sint(left.as_isize() % right.as_isize()), - BinaryOperator::Add => Literal::Sint(left.as_isize() + right.as_isize()), - BinaryOperator::Subtract => Literal::Sint(left.as_isize() - right.as_isize()), - - BinaryOperator::ShiftLeftLogical => { - Literal::Sint(left.as_isize() << right.as_isize()) - } - BinaryOperator::ShiftRightArithmetic => { - Literal::Sint(left.as_isize() << right.as_isize()) - } - - BinaryOperator::Greater => { - Literal::Sint((left.as_isize() > right.as_isize()) as isize) - } - BinaryOperator::Less => { - Literal::Sint((left.as_isize() < right.as_isize()) as isize) - } - BinaryOperator::GreaterEqual => { - Literal::Sint((left.as_isize() >= right.as_isize()) as isize) - } - BinaryOperator::LessEqual => { - Literal::Sint((left.as_isize() <= right.as_isize()) as isize) - } - - BinaryOperator::Equal => { - Literal::Sint((left.as_isize() == right.as_isize()) as isize) - } - BinaryOperator::NotEqual => { - Literal::Sint((left.as_isize() != right.as_isize()) as isize) - } - - BinaryOperator::And => Literal::Sint(left.as_isize() & right.as_isize()), - BinaryOperator::ExclusiveOr => Literal::Sint(left.as_isize() ^ right.as_isize()), - BinaryOperator::InclusiveOr => Literal::Sint(left.as_isize() | right.as_isize()), - - BinaryOperator::LogicalOr => { - Literal::Sint((left.as_bool()? || right.as_bool()?) as isize) - } - BinaryOperator::LogicalAnd => { - Literal::Sint((left.as_bool()? && right.as_bool()?) as isize) - } - _ => unreachable!(), - } - } - }) -} - -pub(self) fn logical_or_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = logical_and_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::LogicalOperation('|')) { - let _ = expr.next().unwrap(); - - let right = logical_and_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::LogicalOr, - right: Box::new(right), - } - } - - Ok(node) -} - -fn logical_and_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = bitwise_or_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::LogicalOperation('&')) { - let _ = expr.next().unwrap(); - - let right = bitwise_or_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::LogicalAnd, - right: Box::new(right), - } - } - - Ok(node) -} - -fn bitwise_or_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = bitwise_xor_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::Operation('|')) { - let _ = expr.next().unwrap(); - - let right = bitwise_xor_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::InclusiveOr, - right: Box::new(right), - } - } - - Ok(node) -} - -fn bitwise_xor_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = bitwise_and_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::Operation('^')) { - let _ = expr.next().unwrap(); - - let right = bitwise_and_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::ExclusiveOr, - right: Box::new(right), - } - } - - Ok(node) -} - -fn bitwise_and_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = equality_parser(expr, macros)?; - - let mut node = left; - - while expr.peek().map(|t| &t.token) == Some(&Token::Operation('&')) { - let _ = expr.next().unwrap(); - - let right = equality_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op: BinaryOperator::And, - right: Box::new(right), - } - } - - Ok(node) -} - -fn equality_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = relational_parser(expr, macros)?; - - let mut node = left; - - loop { - let equality_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match equality_token.token { - Token::LogicalOperation('=') => BinaryOperator::Equal, - Token::LogicalOperation('!') => BinaryOperator::NotEqual, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = relational_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn relational_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = shift_parser(expr, macros)?; - - let mut node = left; - - loop { - let relational_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match relational_token.token { - Token::LogicalOperation('<') => BinaryOperator::LessEqual, - Token::LogicalOperation('>') => BinaryOperator::GreaterEqual, - Token::Operation('<') => BinaryOperator::Less, - Token::Operation('>') => BinaryOperator::Greater, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = shift_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn shift_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = additive_parser(expr, macros)?; - - let mut node = left; - - loop { - let shift_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match shift_token.token { - Token::ShiftOperation('<') => BinaryOperator::ShiftLeftLogical, - Token::ShiftOperation('>') => BinaryOperator::ShiftRightArithmetic, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = additive_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn additive_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = multiplicative_parser(expr, macros)?; - - let mut node = left; - - loop { - let additive_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match additive_token.token { - Token::Operation('+') => BinaryOperator::Add, - Token::Operation('-') => BinaryOperator::Subtract, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = multiplicative_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn multiplicative_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let left = unary_parser(expr, macros)?; - - let mut node = left; - - loop { - let multiplicative_token = match expr.peek() { - Some(t) => t, - None => break, - }; - - let op = match multiplicative_token.token { - Token::Operation('*') => BinaryOperator::Multiply, - Token::Operation('/') => BinaryOperator::Divide, - Token::Operation('%') => BinaryOperator::Modulo, - _ => break, - }; - - let _ = expr.next().unwrap(); - - let right = unary_parser(expr, macros)?; - - node = PreprocessorIfNode::Binary { - left: Box::new(node), - op, - right: Box::new(right), - } - } - - Ok(node) -} - -fn unary_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let unary_or_atom_token = expr.peek().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - Ok(match unary_or_atom_token.token { - Token::Operation(op) => { - let unary_token = expr.next().unwrap(); - - PreprocessorIfNode::Unary { - op: match op { - '+' => UnaryOp::Positive, - '-' => UnaryOp::Negative, - '!' => UnaryOp::BitWiseNot, - '~' => UnaryOp::LogicalNot, - _ => { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![ - Token::Operation('+'), - Token::Operation('-'), - Token::Operation('!'), - Token::Operation('~'), - ], - got: unary_token, - }, - }) - } - }, - tgt: Box::new(atom_parser(expr, macros)?), - } - } - _ => atom_parser(expr, macros)?, - }) -} - -fn atom_parser( - expr: &mut Peekable>, - macros: &mut FastHashMap>, -) -> Result { - let atom = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - Ok(match atom.token { - Token::Double(_) | Token::Float(_) => { - return Err(Error { - kind: ErrorKind::NonIntegralType { token: atom }, - }) - } - Token::Integral(int) => PreprocessorIfNode::Literal(Literal::Uint(int)), - Token::Word(word) => PreprocessorIfNode::Literal(match word.as_str() { - "defined" => { - let macro_name_or_paren_token = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - match macro_name_or_paren_token.token { - Token::Paren('(') => { - let macro_name_token = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - let node = if let Token::Word(macro_name) = macro_name_token.token { - Literal::Sint(macros.get(¯o_name).is_some() as isize) - } else { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_token, - }, - }); - }; - - let close_paren_token = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - if Token::Paren(')') != close_paren_token.token { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren(')')], - got: close_paren_token, - }, - }); - } - - node - } - _ => { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Word(String::new())], - got: macro_name_or_paren_token, - }, - }) - } - } - } - _ => { - return logical_or_parser( - &mut macros - .get_mut(&word) - .cloned() - .unwrap() - .into_iter() - .peekable(), - macros, - ) - } - }), - Token::Paren('(') => { - let node = logical_or_parser(expr, macros)?; - - let close_paren = expr.next().ok_or(Error { - kind: ErrorKind::EOF, - })?; - - if close_paren.token != Token::Paren(')') { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![Token::Paren(')')], - got: close_paren, - }, - }); - } - - node - } - _ => { - return Err(Error { - kind: ErrorKind::UnexpectedToken { - expected: vec![ - Token::Word(String::new()), - Token::Paren('('), - Token::Integral(0), - ], - got: atom, - }, - }) - } - }) -} diff --git a/src/front/glsl_new/parser_tests.rs b/src/front/glsl/parser_tests.rs similarity index 100% rename from src/front/glsl_new/parser_tests.rs rename to src/front/glsl/parser_tests.rs diff --git a/src/front/glsl_new/rosetta_tests.rs b/src/front/glsl/rosetta_tests.rs similarity index 86% rename from src/front/glsl_new/rosetta_tests.rs rename to src/front/glsl/rosetta_tests.rs index efb921375..eb7a01696 100644 --- a/src/front/glsl_new/rosetta_tests.rs +++ b/src/front/glsl/rosetta_tests.rs @@ -9,7 +9,7 @@ fn rosetta_test(file_name: &str, stage: crate::ShaderStage) { let expected = fs::read_to_string(test_dir.join(file_name).with_extension("expected.ron")).unwrap(); - let module = crate::front::glsl_new::parse_str(&input, "main".to_string(), stage).unwrap(); + let module = super::parse_str(&input, "main".to_string(), stage).unwrap(); let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); assert_diff!(output.as_str(), expected.as_str(), "", 0); diff --git a/src/front/glsl_new/token.rs b/src/front/glsl/token.rs similarity index 100% rename from src/front/glsl_new/token.rs rename to src/front/glsl/token.rs diff --git a/src/front/glsl_new/types.rs b/src/front/glsl/types.rs similarity index 100% rename from src/front/glsl_new/types.rs rename to src/front/glsl/types.rs diff --git a/src/front/glsl_new/mod.rs b/src/front/glsl_new/mod.rs deleted file mode 100644 index 2af60fe94..000000000 --- a/src/front/glsl_new/mod.rs +++ /dev/null @@ -1,50 +0,0 @@ -use crate::{EntryPoint, Module, ShaderStage}; - -mod lex; -#[cfg(test)] -mod lex_tests; - -mod ast; -use ast::Program; - -use lex::Lexer; -mod error; -use error::ParseError; -mod parser; -#[cfg(test)] -mod parser_tests; -mod token; -mod types; - -#[cfg(all(test, feature = "serialize"))] -mod rosetta_tests; - -pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { - log::debug!("------ GLSL-pomelo ------"); - - let mut program = Program::new(stage); - let lex = Lexer::new(source); - let mut parser = parser::Parser::new(&mut program); - - for token in lex { - parser.parse(token)?; - } - parser.end_of_input()?; - - let mut module = Module::generate_empty(); - module.functions = program.functions; - module.types = program.types; - module.constants = program.constants; - module.global_variables = program.global_variables; - - // find entry point - if let Some(entry_handle) = program.lookup_function.get(&entry) { - module.entry_points.push(EntryPoint { - stage, - name: entry, - function: *entry_handle, - }); - } - - Ok(module) -} diff --git a/src/front/mod.rs b/src/front/mod.rs index cb531bb92..dc9915064 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,9 +1,7 @@ //! Parsers which load shaders into memory. -#[cfg(feature = "glsl")] +#[cfg(feature = "glsl-in")] pub mod glsl; -#[cfg(feature = "glsl-new")] -pub mod glsl_new; #[cfg(feature = "spirv-in")] pub mod spv; #[cfg(feature = "wgsl-in")] diff --git a/tests/convert.rs b/tests/convert.rs index 0e1f6b869..089c1e352 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -16,7 +16,7 @@ fn load_spv(name: &str) -> naga::Module { naga::front::spv::parse_u8_slice(&input).unwrap() } -#[cfg(feature = "glsl")] +#[cfg(feature = "glsl-in")] fn load_glsl(name: &str, entry: &str, stage: naga::ShaderStage) -> naga::Module { let input = load_test_data(name); naga::front::glsl::parse_str(&input, entry.to_owned(), stage).unwrap() @@ -107,7 +107,7 @@ fn convert_cube() { validator.validate(&fs).unwrap(); } -#[cfg(feature = "glsl")] +#[cfg(feature = "glsl-in")] #[test] #[ignore] fn convert_phong_lighting() { @@ -129,15 +129,16 @@ fn convert_phong_lighting() { w.write(&module); } -#[cfg(feature = "glsl")] -#[test] -fn constant_expressions() { - let module = load_glsl( - "glsl_constant_expression.vert", - "main", - naga::ShaderStage::Fragment { - early_depth_test: None, - }, - ); - naga::proc::Validator::new().validate(&module).unwrap(); -} +//TODO: get this working again (glsl-new) +// #[cfg(feature = "glsl-in")] +// #[test] +// fn constant_expressions() { +// let module = load_glsl( +// "glsl_constant_expression.vert", +// "main", +// naga::ShaderStage::Fragment { +// early_depth_test: None, +// }, +// ); +// naga::proc::Validator::new().validate(&module).unwrap(); +// } From e64f28375e8e813e81ef70bb2699ddd1871eee7e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 10 Sep 2020 01:43:27 -0400 Subject: [PATCH 0192/2212] ir: bitcast expression --- src/back/glsl.rs | 187 ++++++++++++++++++------------------------ src/front/spv/mod.rs | 12 ++- src/lib.rs | 11 ++- src/proc/interface.rs | 2 +- src/proc/typifier.rs | 6 +- 5 files changed, 103 insertions(+), 115 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 708374e5b..589a05412 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -684,20 +684,7 @@ fn write_expression<'a, 'b>( let constructor = match module.types[ty].inner { TypeInner::Vector { size, kind, width } => format!( "{}vec{}", - match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => match width { - 4 => "", - 8 => "d", - _ => - return Err(Error::Custom(format!( - "Cannot build float of width {}", - width - ))), - }, - ScalarKind::Bool => "b", - }, + map_scalar(kind, width, builder.features)?.prefix, size as u8, ), TypeInner::Matrix { @@ -707,20 +694,7 @@ fn write_expression<'a, 'b>( width, } => format!( "{}mat{}x{}", - match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => match width { - 4 => "", - 8 => "d", - _ => - return Err(Error::Custom(format!( - "Cannot build float of width {}", - width - ))), - }, - ScalarKind::Bool => "b", - }, + map_scalar(kind, width, builder.features)?.prefix, columns as u8, rows as u8, ), @@ -820,12 +794,7 @@ fn write_expression<'a, 'b>( let sampler_constructor = format!( "{}sampler{}{}{}{}({},{})", - match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => "", - _ => return Err(Error::Custom(String::from("Cannot build image of bools",))), - }, + map_scalar(kind, 4, builder.features)?.prefix, ImageDimension(dim), if ms { "MS" } else { "" }, if arrayed { "Array" } else { "" }, @@ -917,15 +886,7 @@ fn write_expression<'a, 'b>( //TODO: fix this let sampler_constructor = format!( "{}sampler{}{}{}({})", - match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => "", - _ => - return Err(Error::Custom(String::from( - "Cannot build image of bools" - ))), - }, + map_scalar(kind, 4, builder.features)?.prefix, ImageDimension(dim), if ms { "MS" } else { "" }, if arrayed { "Array" } else { "" }, @@ -1137,26 +1098,47 @@ fn write_expression<'a, 'b>( left_ty, ) } - Expression::As(value, kind) => { + Expression::As { + expr, + kind, + convert, + } => { let (value_expr, value_ty) = - write_expression(&builder.expressions[value], module, builder)?; - let (width, out_ty) = match *value_ty.borrow() { - TypeInner::Scalar { width, kind: _ } => { - (width, MaybeOwned::Owned(TypeInner::Scalar { kind, width })) - } - TypeInner::Vector { - width, - kind: _, - size, - } => ( - width, + write_expression(&builder.expressions[expr], module, builder)?; + let (source_kind, ty_expr, out_ty) = match *value_ty.borrow() { + TypeInner::Scalar { width, kind } => ( + kind, + Cow::Borrowed(map_scalar(kind, width, builder.features)?.full), + MaybeOwned::Owned(TypeInner::Scalar { kind, width }), + ), + TypeInner::Vector { width, kind, size } => ( + kind, + Cow::Owned(format!( + "{}vec", + map_scalar(kind, width, builder.features)?.prefix + )), MaybeOwned::Owned(TypeInner::Vector { kind, width, size }), ), - _ => return Err(Error::Custom(format!("Cannot cast {}", value_expr))), + _ => return Err(Error::Custom(format!("Cannot convert {}", value_expr))), + }; + let op = if convert { + ty_expr + } else { + Cow::Borrowed(match (source_kind, kind) { + (ScalarKind::Float, ScalarKind::Sint) => "floatBitsToInt", + (ScalarKind::Float, ScalarKind::Uint) => "floatBitsToUInt", + (ScalarKind::Sint, ScalarKind::Float) => "intBitsToFloat", + (ScalarKind::Uint, ScalarKind::Float) => "uintBitsToFloat", + _ => { + return Err(Error::Custom(format!( + "Cannot bitcast {:?} to {:?}", + source_kind, kind + ))) + } + }) }; - let ty_expr = map_scalar(kind, width, builder.features)?; - (Cow::Owned(format!("{}({})", ty_expr, value_expr)), out_ty) + (Cow::Owned(format!("{}({})", op, value_expr)), out_ty) } Expression::Derivative { axis, expr } => { let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; @@ -1255,17 +1237,34 @@ fn write_constant( }) } +struct ScalarString<'a> { + prefix: &'a str, + full: &'a str, +} + fn map_scalar( kind: ScalarKind, width: crate::Bytes, features: SupportedFeatures, -) -> Result<&'static str, Error> { +) -> Result, Error> { Ok(match kind { - ScalarKind::Sint => "int", - ScalarKind::Uint => "uint", + ScalarKind::Sint => ScalarString { + prefix: "i", + full: "int", + }, + ScalarKind::Uint => ScalarString { + prefix: "u", + full: "uint", + }, ScalarKind::Float => match width { - 4 => "float", - 8 if features.contains(SupportedFeatures::DOUBLE_TYPE) => "double", + 4 => ScalarString { + prefix: "", + full: "float", + }, + 8 if features.contains(SupportedFeatures::DOUBLE_TYPE) => ScalarString { + prefix: "d", + full: "double", + }, _ => { return Err(Error::Custom(format!( "Cannot build float of width {}", @@ -1273,7 +1272,10 @@ fn map_scalar( ))) } }, - ScalarKind::Bool => "bool", + ScalarKind::Bool => ScalarString { + prefix: "b", + full: "bool", + }, }) } @@ -1285,23 +1287,10 @@ fn write_type<'a>( features: SupportedFeatures, ) -> Result, Error> { Ok(match types[ty].inner { - TypeInner::Scalar { kind, width } => Cow::Borrowed(map_scalar(kind, width, features)?), + TypeInner::Scalar { kind, width } => Cow::Borrowed(map_scalar(kind, width, features)?.full), TypeInner::Vector { size, kind, width } => Cow::Owned(format!( "{}vec{}", - match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => match width { - 4 => "", - 8 if features.contains(SupportedFeatures::DOUBLE_TYPE) => "d", - _ => - return Err(Error::Custom(format!( - "Cannot build float of width {}", - width - ))), - }, - ScalarKind::Bool => "b", - }, + map_scalar(kind, width, features)?.prefix, size as u8 )), TypeInner::Matrix { @@ -1311,27 +1300,15 @@ fn write_type<'a>( width, } => Cow::Owned(format!( "{}mat{}x{}", - match kind { - ScalarKind::Sint if features.contains(SupportedFeatures::NON_FLOAT_MATRICES) => "i", - ScalarKind::Uint if features.contains(SupportedFeatures::NON_FLOAT_MATRICES) => "u", - ScalarKind::Float => match width { - 4 => "", - 8 if features.contains( - SupportedFeatures::DOUBLE_TYPE & SupportedFeatures::NON_FLOAT_MATRICES - ) => - "d", - _ => - return Err(Error::Custom(format!( - "Cannot build float of width {}", - width - ))), - }, - ScalarKind::Bool if features.contains(SupportedFeatures::NON_FLOAT_MATRICES) => "b", - _ => - return Err(Error::Custom(format!( - "Cannot build matrix of base type {:?}", - kind - ))), + if (width == 4 && kind == ScalarKind::Float) + || features.contains(SupportedFeatures::NON_FLOAT_MATRICES) + { + map_scalar(kind, width, features)?.prefix + } else { + return Err(Error::Custom(format!( + "Cannot build matrix of base type {:?}", + kind + ))); }, columns as u8, rows as u8 @@ -1384,15 +1361,7 @@ fn write_type<'a>( Cow::Owned(format!( "{}{}{}{}", - match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => "", - ScalarKind::Bool => - return Err(Error::Custom(String::from( - "Cannot build image of booleans", - ))), - }, + map_scalar(kind, 4, features)?.prefix, match class { ImageClass::Storage(_) => "image", _ => "texture", diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e467dec02..559d1a30a 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1087,7 +1087,11 @@ impl> Parser { }, ); } - Op::ConvertSToF | Op::ConvertUToF | Op::ConvertFToU | Op::ConvertFToS => { + Op::Bitcast + | Op::ConvertSToF + | Op::ConvertUToF + | Op::ConvertFToU + | Op::ConvertFToS => { inst.expect_at_least(4)?; let result_type_id = self.next()?; let result_id = self.next()?; @@ -1101,7 +1105,11 @@ impl> Parser { _ => return Err(Error::InvalidAsType(ty_lookup.handle)), }; - let expr = crate::Expression::As(value_lexp.handle, kind); + let expr = crate::Expression::As { + expr: value_lexp.handle, + kind, + convert: inst.op != Op::Bitcast, + }; self.lookup_expression.insert( result_id, LookupExpression { diff --git a/src/lib.rs b/src/lib.rs index c4c9f1596..2b65d8ac8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -615,8 +615,15 @@ pub enum Expression { DotProduct(Handle, Handle), /// Cross product between two vectors. CrossProduct(Handle, Handle), - /// Cast a scalar or a vector to another kind. - As(Handle, ScalarKind), + /// Cast a simply type to another kind. + As { + /// Source expression, which can only be a scalar or a vector. + expr: Handle, + /// Target scalar kind. + kind: ScalarKind, + /// True = conversion needs to take place; False = bitcast. + convert: bool, + }, /// Compute the derivative on an axis. Derivative { axis: DerivativeAxis, diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 4e2ec5f8b..394033874 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -89,7 +89,7 @@ where self.traverse_expr(left); self.traverse_expr(right); } - E::As(expr, _) => { + E::As { expr, .. } => { self.traverse_expr(expr); } E::Derivative { expr, .. } => { diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 7ae2de663..58e0edc3e 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -186,7 +186,11 @@ impl Typifier { } } crate::Expression::CrossProduct(_, _) => unimplemented!(), - crate::Expression::As(expr, kind) => { + crate::Expression::As { + expr, + kind, + convert: _, + } => { let ty_handle = self.types[expr.index()]; match arena[ty_handle].inner { crate::TypeInner::Scalar { kind: _, width } => { From 0129aa2ca699070497e7d0c6c749fc872e395623 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 10 Sep 2020 19:14:03 +0100 Subject: [PATCH 0193/2212] [glsl-out]: combined image sampler (#177) * Added generation of the texture mappings to the glsl backend * Added a temporary workaround for the spirv shaders Fixed some parts that were using vulkan glsl * Made texture mapping not require a sampler * Used interface to build the texture map * Made global names mandatory except for sampler ones * Addressed more comments * Removed the temp fix for the spirv frontend * Addressed the comments --- src/back/glsl.rs | 432 ++++++++++++++++++++++++++---------------- src/proc/interface.rs | 4 +- 2 files changed, 271 insertions(+), 165 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 589a05412..dd472e32e 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,5 +1,6 @@ use super::{BorrowType, MaybeOwned}; use crate::{ + proc::{Interface, Visitor}, Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageClass, Interpolation, IntrinsicFunction, LocalVariable, MemberOrigin, Module, ScalarKind, ShaderStage, Statement, @@ -61,6 +62,12 @@ pub struct Options { pub entry_point: (String, ShaderStage), } +#[derive(Debug, Clone)] +pub struct TextureMapping { + pub texture: Handle, + pub sampler: Option>, +} + const SUPPORTED_CORE_VERSIONS: &[u16] = &[450, 460]; const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310]; @@ -68,16 +75,19 @@ bitflags::bitflags! { struct SupportedFeatures: u32 { const BUFFER_STORAGE = 1; const SHARED_STORAGE = 1 << 1; - const SEPARATE_IMAGE_SAMPLER = 1 << 2; - const DOUBLE_TYPE = 1 << 3; - const NON_FLOAT_MATRICES = 1 << 4; - const MULTISAMPLED_TEXTURES = 1 << 5; - const MULTISAMPLED_TEXTURE_ARRAYS = 1 << 6; - const NON_2D_TEXTURE_ARRAYS = 1 << 7; + const DOUBLE_TYPE = 1 << 2; + const NON_FLOAT_MATRICES = 1 << 3; + const MULTISAMPLED_TEXTURES = 1 << 4; + const MULTISAMPLED_TEXTURE_ARRAYS = 1 << 5; + const NON_2D_TEXTURE_ARRAYS = 1 << 6; } } -pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> Result<(), Error> { +pub fn write<'a>( + module: &'a Module, + out: &mut impl Write, + options: Options, +) -> Result, Error> { let (version, es) = match options.version { Version::Desktop(v) => (v, false), Version::Embedded(v) => (v, true), @@ -145,7 +155,6 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> let mut features = SupportedFeatures::empty(); if !es && version > 440 { - features |= SupportedFeatures::SEPARATE_IMAGE_SAMPLER; features |= SupportedFeatures::DOUBLE_TYPE; features |= SupportedFeatures::NON_FLOAT_MATRICES; features |= SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS; @@ -214,11 +223,136 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> writeln!(out)?; + let mut functions = FastHashMap::default(); + + for (handle, func) in module.functions.iter() { + // Discard all entry points + if entry_point.function != handle + && module + .entry_points + .iter() + .any(|entry| entry.function == handle) + { + continue; + } + + let name = if entry_point.function != handle { + namer(func.name.as_ref()) + } else { + String::from("main") + }; + + writeln!( + out, + "{} {}({});", + func.return_type + .map(|ty| write_type(ty, &module.types, &structs, None, features)) + .transpose()? + .as_deref() + .unwrap_or("void"), + name, + func.parameter_types + .iter() + .map(|ty| write_type(*ty, &module.types, &structs, None, features)) + .collect::, _>>()? + .join(","), + )?; + + functions.insert(handle, name); + } + + writeln!(out)?; + + let texture_mappings = collect_texture_mapping(module, &functions)?; + let mut mappings_map = FastHashMap::default(); let mut globals_lookup = FastHashMap::default(); - for ((handle, global), usage) in module.global_variables.iter().zip(func.global_usage.iter()) { - if usage.is_empty() { - continue; + for ((handle, global), _) in module + .global_variables + .iter() + .zip(func.global_usage.iter()) + .filter(|(_, usage)| !usage.is_empty()) + { + match module.types[global.ty].inner { + TypeInner::Image { + kind, + dim, + arrayed, + class, + } => { + let mapping = if let Some(map) = texture_mappings.get_key_value(&handle) { + map + } else { + log::warn!( + "Couldn't find a mapping for {:?}, handle {:?}", + global, + handle + ); + continue; + }; + + if let TypeInner::Image { + class: ImageClass::Storage(storage_format), + .. + } = module.types[global.ty].inner + { + write!(out, "layout({}) ", write_format_glsl(storage_format))?; + } + + if global.storage_access == StorageAccess::LOAD { + write!(out, "readonly ")?; + } else if global.storage_access == StorageAccess::STORE { + write!(out, "writeonly ")?; + } + + let name = namer(global.name.as_ref()); + + let comparison = if let Some(sampler) = mapping.1 { + if let TypeInner::Sampler { comparison } = + module.types[module.global_variables[*sampler].ty].inner + { + comparison + } else { + false + } + } else { + unreachable!() + }; + + writeln!( + out, + "uniform {} {};", + write_image_type(kind, dim, arrayed, class, comparison, features)?, + name + )?; + + mappings_map.insert( + name.clone(), + TextureMapping { + texture: *mapping.0, + sampler: *mapping.1, + }, + ); + globals_lookup.insert(handle, name); + } + TypeInner::Sampler { .. } => { + let name = namer(global.name.as_ref()); + + globals_lookup.insert(handle, name); + } + _ => continue, + } + } + + for ((handle, global), _) in module + .global_variables + .iter() + .zip(func.global_usage.iter()) + .filter(|(_, usage)| !usage.is_empty()) + { + match module.types[global.ty].inner { + TypeInner::Image { .. } | TypeInner::Sampler { .. } => continue, + _ => {} } if let Some(crate::Binding::BuiltIn(built_in)) = global.binding { @@ -244,37 +378,15 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> continue; } - let name = if !es { - namer(global.name.as_ref()) - } else { - global.name.clone().ok_or_else(|| { - Error::Custom(String::from("Global names must be specified in es")) - })? - }; + let name = global + .name + .clone() + .ok_or_else(|| Error::Custom(String::from("Global names must be specified in es")))?; - let storage_format = match module.types[global.ty].inner { - TypeInner::Image { - class: ImageClass::Storage(format), - .. - } => Some(format), - _ => None, - }; - - if global.binding.is_some() { - write!(out, "layout(")?; - - if let Some(ref binding) = global.binding { - if !es { - write!(out, "{}", Binding(binding))?; - } - } - - if storage_format.is_some() && global.binding.is_some() { - write!(out, ",")?; - } - - if let Some(format) = storage_format { - write!(out, "{}", write_format_glsl(format))?; + if let Some(ref binding) = global.binding { + // Only vulkan glsl supports set/binding on the layout + if let crate::Binding::Location(location) = binding { + write!(out, "layout(location = {}) ", location)?; } write!(out, ") ")?; @@ -317,46 +429,6 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> writeln!(out)?; - let mut functions = FastHashMap::default(); - - for (handle, func) in module.functions.iter() { - // Discard all entry points - if entry_point.function != handle - && module - .entry_points - .iter() - .any(|entry| entry.function == handle) - { - continue; - } - - let name = if entry_point.function != handle { - namer(func.name.as_ref()) - } else { - String::from("main") - }; - - writeln!( - out, - "{} {}({});", - func.return_type - .map(|ty| write_type(ty, &module.types, &structs, None, features)) - .transpose()? - .as_deref() - .unwrap_or("void"), - name, - func.parameter_types - .iter() - .map(|ty| write_type(*ty, &module.types, &structs, None, features)) - .collect::, _>>()? - .join(","), - )?; - - functions.insert(handle, name); - } - - writeln!(out)?; - for (handle, name) in functions.iter() { let func = &module.functions[*handle]; @@ -427,20 +499,7 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> writeln!(out, "}}")?; } - Ok(()) -} - -struct Binding<'a>(&'a crate::Binding); -impl<'a> fmt::Display for Binding<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self.0 { - crate::Binding::BuiltIn(_) => write!(f, ""), // Ignore because they are variables with a predefined name - crate::Binding::Location(location) => write!(f, "location={}", location), - crate::Binding::Descriptor { set, binding } => { - write!(f, "set={},binding={}", set, binding) - } - } - } + Ok(mappings_map) } struct StatementBuilder<'a> { @@ -754,25 +813,15 @@ fn write_expression<'a, 'b>( } => { let (image_expr, image_ty) = write_expression(&builder.expressions[image], module, builder)?; - let (sampler_expr, sampler_ty) = - write_expression(&builder.expressions[sampler], module, builder)?; + let (_, sampler_ty) = write_expression(&builder.expressions[sampler], module, builder)?; let (coordinate_expr, coordinate_ty) = write_expression(&builder.expressions[coordinate], module, builder)?; - let (kind, dim, arrayed, class) = match *image_ty.borrow() { - TypeInner::Image { - kind, - dim, - arrayed, - class, - } => (kind, dim, arrayed, class), + let kind = match *image_ty.borrow() { + TypeInner::Image { kind, .. } => kind, _ => return Err(Error::Custom(format!("Cannot sample {:?}", image_ty))), }; - let ms = match class { - crate::ImageClass::Multisampled => true, - _ => false, - }; let shadow = match *sampler_ty.borrow() { TypeInner::Sampler { comparison } => comparison, _ => { @@ -792,17 +841,6 @@ fn write_expression<'a, 'b>( } }; - let sampler_constructor = format!( - "{}sampler{}{}{}{}({},{})", - map_scalar(kind, 4, builder.features)?.prefix, - ImageDimension(dim), - if ms { "MS" } else { "" }, - if arrayed { "Array" } else { "" }, - if shadow { "Shadow" } else { "" }, - image_expr, - sampler_expr - ); - let coordinate = if let Some(depth_ref) = depth_ref { Cow::Owned(format!( "vec{}({},{})", @@ -816,24 +854,16 @@ fn write_expression<'a, 'b>( //TODO: handle MS let expr = match level { - crate::SampleLevel::Auto => { - format!("texture({},{})", sampler_constructor, coordinate) - } + crate::SampleLevel::Auto => format!("texture({},{})", image_expr, coordinate), crate::SampleLevel::Exact(expr) => { let (level_expr, _) = write_expression(&builder.expressions[expr], module, builder)?; - format!( - "textureLod({}, {}, {})", - sampler_constructor, coordinate, level_expr - ) + format!("textureLod({}, {}, {})", image_expr, coordinate, level_expr) } crate::SampleLevel::Bias(bias) => { let (bias_expr, _) = write_expression(&builder.expressions[bias], module, builder)?; - format!( - "texture({},{},{})", - sampler_constructor, coordinate, bias_expr - ) + format!("texture({},{},{})", image_expr, coordinate, bias_expr) } }; @@ -923,7 +953,7 @@ fn write_expression<'a, 'b>( "({} {})", match op { UnaryOperator::Negate => "-", - UnaryOperator::Not => match ty.borrow() { + UnaryOperator::Not => match *ty.borrow() { TypeInner::Scalar { kind: ScalarKind::Sint, .. @@ -1105,6 +1135,7 @@ fn write_expression<'a, 'b>( } => { let (value_expr, value_ty) = write_expression(&builder.expressions[expr], module, builder)?; + let (source_kind, ty_expr, out_ty) = match *value_ty.borrow() { TypeInner::Scalar { width, kind } => ( kind, @@ -1121,6 +1152,7 @@ fn write_expression<'a, 'b>( ), _ => return Err(Error::Custom(format!("Cannot convert {}", value_expr))), }; + let op = if convert { ty_expr } else { @@ -1344,46 +1376,46 @@ fn write_type<'a>( Cow::Borrowed(structs.get(&ty).unwrap()) } } - TypeInner::Image { - kind, - dim, - arrayed, - class, - } => { - if arrayed - && dim != crate::ImageDimension::D2 - && !features.contains(SupportedFeatures::NON_2D_TEXTURE_ARRAYS) - { - return Err(Error::Custom(String::from( - "Arrayed non 2d images aren't supported", - ))); - } - - Cow::Owned(format!( - "{}{}{}{}", - map_scalar(kind, 4, features)?.prefix, - match class { - ImageClass::Storage(_) => "image", - _ => "texture", - }, - ImageDimension(dim), - write_image_flags(arrayed, class, features)? - )) - } - TypeInner::Sampler { comparison } => Cow::Borrowed(if comparison { - "sampler" - } else { - "samplerShadow" - }), + _ => unreachable!(), }) } +fn write_image_type( + kind: ScalarKind, + dim: crate::ImageDimension, + arrayed: bool, + class: ImageClass, + comparison: bool, + features: SupportedFeatures, +) -> Result { + if arrayed + && dim != crate::ImageDimension::D2 + && !features.contains(SupportedFeatures::NON_2D_TEXTURE_ARRAYS) + { + return Err(Error::Custom(String::from( + "Arrayed non 2d images aren't supported", + ))); + } + + Ok(format!( + "{}{}{}{}{}", + map_scalar(kind, 4, features)?.prefix, + match class { + ImageClass::Storage(_) => "image", + _ => "sampler", + }, + ImageDimension(dim), + write_image_flags(arrayed, class, features)?, + if comparison { "Shadow" } else { "" } + )) +} + fn write_storage_class( class: StorageClass, features: SupportedFeatures, ) -> Result<&'static str, Error> { Ok(match class { - StorageClass::Constant => "const ", + StorageClass::Constant => "", StorageClass::Function => "", StorageClass::Input => "in ", StorageClass::Output => "out ", @@ -1593,3 +1625,77 @@ fn write_format_glsl(format: StorageFormat) -> &'static str { StorageFormat::Rgba32Float => "rgba32f", } } + +struct TextureMappingVisitor<'a> { + expressions: &'a Arena, + map: FastHashMap, Option>>, + error: Option, +} + +impl<'a> Visitor for TextureMappingVisitor<'a> { + fn visit_expr(&mut self, expr: &crate::Expression) { + match expr { + Expression::ImageSample { image, sampler, .. } => { + let tex_handle = match self.expressions[*image] { + Expression::GlobalVariable(global) => global, + _ => unreachable!(), + }; + + let sampler_handle = match self.expressions[*sampler] { + Expression::GlobalVariable(global) => global, + _ => unreachable!(), + }; + + let sampler = self.map.entry(tex_handle).or_insert(Some(sampler_handle)); + + if *sampler != Some(sampler_handle) { + self.error = Some(Error::Custom(String::from( + "Cannot use texture with two different samplers", + ))); + } + } + Expression::ImageLoad { image, .. } => { + let tex_handle = match self.expressions[*image] { + Expression::GlobalVariable(global) => global, + _ => unreachable!(), + }; + + let sampler = self.map.entry(tex_handle).or_insert(None); + + if *sampler != None { + self.error = Some(Error::Custom(String::from( + "Cannot use texture with two different samplers", + ))); + } + } + _ => {} + } + } +} + +fn collect_texture_mapping( + module: &Module, + functions: &FastHashMap, String>, +) -> Result, Option>>, Error> { + let mut mappings = FastHashMap::default(); + + for function in functions.keys() { + let func = &module.functions[*function]; + + let mut visitor = TextureMappingVisitor { + expressions: &func.expressions, + map: FastHashMap::default(), + error: None, + }; + + let mut interface = Interface { + expressions: &func.expressions, + visitor: &mut visitor, + }; + interface.traverse(&func.body); + + mappings.extend(visitor.map); + } + + Ok(mappings) +} diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 394033874..ff4290c19 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -1,8 +1,8 @@ use crate::arena::{Arena, Handle}; pub struct Interface<'a, T> { - expressions: &'a Arena, - visitor: &'a mut T, + pub expressions: &'a Arena, + pub visitor: &'a mut T, } pub trait Visitor { From b278e10ea7c144b2387585c4e81c1d86db8e2def Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Sep 2020 12:19:55 -0400 Subject: [PATCH 0194/2212] [spirv-in] make pointers totally transparent (#187) --- Cargo.toml | 2 +- examples/convert.rs | 6 ++- src/back/msl.rs | 24 ++++++++- src/front/mod.rs | 1 + src/front/spv/error.rs | 2 - src/front/spv/function.rs | 2 +- src/front/spv/mod.rs | 101 ++++++++++++++------------------------ src/front/spv/rosetta.rs | 24 +++++++++ tests/convert.rs | 37 ++++++++++++++ 9 files changed, 130 insertions(+), 69 deletions(-) create mode 100644 src/front/spv/rosetta.rs diff --git a/Cargo.toml b/Cargo.toml index 669015720..3c60739c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,5 +34,5 @@ wgsl-in = [] [dev-dependencies] difference = "2.0" env_logger = "0.6" -ron = "0.5" +ron = "0.6" serde = { version = "1.0", features = ["derive"] } diff --git a/examples/convert.rs b/examples/convert.rs index 8b42e5b3a..76f5a156e 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -181,7 +181,11 @@ fn main() { } #[cfg(feature = "serialize")] "ron" => { - let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); + let config = ron::ser::PrettyConfig::new() + .with_enumerate_arrays(true) + .with_decimal_floats(true); + + let output = ron::ser::to_string_pretty(&module, config).unwrap(); fs::write(&args[2], output).unwrap(); } other => { diff --git a/src/back/msl.rs b/src/back/msl.rs index ee9fd2490..251dfd503 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -546,6 +546,19 @@ impl Writer { &crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Vector { .. }, ) => MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), + ( + &crate::TypeInner::Matrix { + rows, + columns: _, + kind, + width, + }, + &crate::TypeInner::Vector { .. }, + ) => MaybeOwned::Owned(crate::TypeInner::Vector { + size: rows, + kind, + width, + }), (_, _) => { return Err(Error::UnableToInferBinaryOpOutput(ty_left, op, ty_right)) } @@ -702,7 +715,16 @@ impl Writer { write!(self.out, ")")?; Ok(MaybeOwned::Owned(result)) } - + "mix" => { + write!(self.out, "mix(")?; + let result = self.put_expression(arguments[0], function, module)?; + write!(self.out, ", ")?; + self.put_expression(arguments[1], function, module)?; + write!(self.out, ", ")?; + self.put_expression(arguments[2], function, module)?; + write!(self.out, ")")?; + Ok(result) + } other => Err(Error::UnsupportedCall(other.to_owned())), }, ref other => Err(Error::UnsupportedExpression(other.clone())), diff --git a/src/front/mod.rs b/src/front/mod.rs index dc9915064..ec7738963 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -11,6 +11,7 @@ use crate::arena::Arena; pub const GENERATOR: u32 = 0; +#[allow(dead_code)] impl crate::Module { fn from_header(header: crate::Header) -> Self { crate::Module { diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index f9ab8fca3..e80cd39f0 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -35,8 +35,6 @@ pub enum Error { InvalidAccessType(spirv::Word), InvalidAccess(Handle), InvalidAccessIndex(spirv::Word), - InvalidLoadType(spirv::Word), - InvalidStoreType(spirv::Word), InvalidBinding(spirv::Word), InvalidImageExpression(Handle), InvalidImageBaseType(Handle), diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index f133c50ce..06de75e41 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -119,7 +119,7 @@ pub fn parse_function>( // Scan the blocks and add them as nodes loop { let fun_inst = parser.next_inst()?; - log::debug!("\t\t{:?}", fun_inst.op); + log::debug!("{:?}", fun_inst.op); match fun_inst.op { spirv::Op::Label => { // Read the label ID diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 559d1a30a..275ba7930 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -15,6 +15,8 @@ mod convert; mod error; mod flow; mod function; +#[cfg(test)] +mod rosetta; use convert::*; use error::Error; @@ -254,7 +256,7 @@ struct EntryPoint { variable_ids: Vec, } -#[derive(Debug)] +#[derive(Clone, Debug)] struct LookupType { handle: Handle, base_id: Option, @@ -302,7 +304,7 @@ pub struct Parser { ext_glsl_id: Option, future_decor: FastHashMap, future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>, - lookup_member_type_id: FastHashMap<(spirv::Word, MemberIndex), spirv::Word>, + lookup_member_type_id: FastHashMap<(Handle, MemberIndex), spirv::Word>, handle_sampling: FastHashMap, SamplingFlags>, lookup_type: FastHashMap, lookup_void_type: FastHashSet, @@ -603,15 +605,14 @@ impl> Parser { log::trace!("\t\t\tlooking up expr {:?}", base_id); let mut acex = { let expr = self.lookup_expression.lookup(base_id)?; - let ptr_type = self.lookup_type.lookup(expr.type_id)?; AccessExpression { base_handle: expr.handle, - type_id: ptr_type.base_id.unwrap(), + type_id: expr.type_id, } }; for _ in 4..inst.wc { let access_id = self.next()?; - log::trace!("\t\t\tlooking up expr {:?}", access_id); + log::trace!("\t\t\tlooking up index expr {:?}", access_id); let index_expr = self.lookup_expression.lookup(access_id)?.clone(); let index_type_handle = self.lookup_type.lookup(index_expr.type_id)?.handle; match type_arena[index_type_handle].inner { @@ -650,7 +651,7 @@ impl> Parser { ), type_id: *self .lookup_member_type_id - .get(&(acex.type_id, index)) + .get(&(type_lookup.handle, index)) .ok_or(Error::InvalidAccessType(acex.type_id))?, } } @@ -695,7 +696,7 @@ impl> Parser { let type_id = match type_arena[type_lookup.handle].inner { crate::TypeInner::Struct { .. } => *self .lookup_member_type_id - .get(&(lexp.type_id, index)) + .get(&(type_lookup.handle, index)) .ok_or(Error::InvalidAccessType(lexp.type_id))?, crate::TypeInner::Array { .. } | crate::TypeInner::Vector { .. } @@ -753,22 +754,11 @@ impl> Parser { inst.expect(5)?; let _memory_access = self.next()?; } - let base_expr = self.lookup_expression.lookup(pointer_id)?; - let base_type = self.lookup_type.lookup(base_expr.type_id)?; - if base_type.base_id != Some(result_type_id) { - return Err(Error::InvalidLoadType(result_type_id)); - } - match type_arena[base_type.handle].inner { - crate::TypeInner::Pointer { .. } => (), - _ => return Err(Error::UnsupportedType(base_type.handle)), - } - let expr = crate::Expression::Load { - pointer: base_expr.handle, - }; + let base_expr = self.lookup_expression.lookup(pointer_id)?.clone(); self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: base_expr.handle, // pass-through pointers type_id: result_type_id, }, ); @@ -782,15 +772,7 @@ impl> Parser { let _memory_access = self.next()?; } let base_expr = self.lookup_expression.lookup(pointer_id)?; - let base_type = self.lookup_type.lookup(base_expr.type_id)?; - match type_arena[base_type.handle].inner { - crate::TypeInner::Pointer { .. } => (), - _ => return Err(Error::UnsupportedType(base_type.handle)), - }; let value_expr = self.lookup_expression.lookup(value_id)?; - if base_type.base_id != Some(value_expr.type_id) { - return Err(Error::InvalidStoreType(value_expr.type_id)); - } assignments.push(Assignment { to: base_expr.handle, value: value_expr.handle, @@ -1923,27 +1905,15 @@ impl> Parser { fn parse_type_pointer( &mut self, inst: Instruction, - module: &mut crate::Module, + _module: &mut crate::Module, ) -> Result<(), Error> { self.switch(ModuleState::Type, inst.op)?; inst.expect(4)?; let id = self.next()?; - let storage = self.next()?; + let _storage = self.next()?; let type_id = self.next()?; - let inner = crate::TypeInner::Pointer { - base: self.lookup_type.lookup(type_id)?.handle, - class: map_storage_class(storage)?, - }; - self.lookup_type.insert( - id, - LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - inner, - }), - base_id: Some(type_id), - }, - ); + let type_lookup = self.lookup_type.lookup(type_id)?.clone(); + self.lookup_type.insert(id, type_lookup); // don't register pointers in the IR Ok(()) } @@ -2020,11 +1990,13 @@ impl> Parser { // do nothing } } + let mut members = Vec::with_capacity(inst.wc as usize - 2); + let mut member_type_ids = Vec::with_capacity(members.capacity()); for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; + member_type_ids.push(type_id); let ty = self.lookup_type.lookup(type_id)?.handle; - self.lookup_member_type_id.insert((id, i), type_id); let decor = self .future_member_decor .remove(&(id, i)) @@ -2037,13 +2009,19 @@ impl> Parser { }); } let inner = crate::TypeInner::Struct { members }; + let ty_handle = module.types.append(crate::Type { + name: parent_decor.and_then(|dec| dec.name), + inner, + }); + + for (i, type_id) in member_type_ids.into_iter().enumerate() { + self.lookup_member_type_id + .insert((ty_handle, i as u32), type_id); + } self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: parent_decor.and_then(|dec| dec.name), - inner, - }), + handle: ty_handle, base_id: None, }, ); @@ -2278,20 +2256,17 @@ impl> Parser { .future_decor .remove(&id) .ok_or(Error::InvalidBinding(id))?; - let (ty, binding) = match module.types[lookup_type.handle].inner { - crate::TypeInner::Pointer { base, class } => { - let binding = match (class, &module.types[base].inner) { - (crate::StorageClass::Input, &crate::TypeInner::Struct { .. }) - | (crate::StorageClass::Output, &crate::TypeInner::Struct { .. }) => None, - _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), - }; - (base, binding) - } - _ => return Err(Error::UnsupportedType(lookup_type.handle)), - }; let class = map_storage_class(storage)?; - let is_storage = match module.types[ty].inner { - crate::TypeInner::Struct { .. } => class == crate::StorageClass::StorageBuffer, + let binding = match (class, &module.types[lookup_type.handle].inner) { + (crate::StorageClass::Input, &crate::TypeInner::Struct { .. }) + | (crate::StorageClass::Output, &crate::TypeInner::Struct { .. }) => None, + _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), + }; + let is_storage = match module.types[lookup_type.handle].inner { + crate::TypeInner::Struct { .. } => match class { + crate::StorageClass::StorageBuffer | crate::StorageClass::Constant => true, // careful with `Constant` here! + _ => false, + }, crate::TypeInner::Image { class: crate::ImageClass::Storage(_), .. @@ -2316,7 +2291,7 @@ impl> Parser { name: dec.name, class, binding, - ty, + ty: lookup_type.handle, interpolation: dec.interpolation, storage_access, }; diff --git a/src/front/spv/rosetta.rs b/src/front/spv/rosetta.rs new file mode 100644 index 000000000..7bd18bf19 --- /dev/null +++ b/src/front/spv/rosetta.rs @@ -0,0 +1,24 @@ +use std::{fs, path::Path}; + +const TEST_PATH: &str = "test-data"; + +fn rosetta_test(file_name: &str) { + if true { + return; //TODO: fix this test + } + let test_dir = Path::new(TEST_PATH); + let input = fs::read(test_dir.join(file_name)).unwrap(); + + let module = super::parse_u8_slice(&input).unwrap(); + let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); + + let expected = + fs::read_to_string(test_dir.join(file_name).with_extension("expected.ron")).unwrap(); + + difference::assert_diff!(output.as_str(), expected.as_str(), "", 0); +} + +#[test] +fn simple() { + rosetta_test("simple/simple.spv") +} diff --git a/tests/convert.rs b/tests/convert.rs index 089c1e352..9598fbf39 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -105,6 +105,43 @@ fn convert_cube() { validator.validate(&vs).unwrap(); let fs = load_spv("cube.frag.spv"); validator.validate(&fs).unwrap(); + + { + use naga::back::msl; + let mut binding_map = msl::BindingMap::default(); + binding_map.insert( + msl::BindSource { set: 0, binding: 0 }, + msl::BindTarget { + buffer: Some(0), + texture: None, + sampler: None, + mutable: false, + }, + ); + binding_map.insert( + msl::BindSource { set: 0, binding: 1 }, + msl::BindTarget { + buffer: None, + texture: Some(1), + sampler: None, + mutable: false, + }, + ); + binding_map.insert( + msl::BindSource { set: 0, binding: 2 }, + msl::BindTarget { + buffer: None, + texture: None, + sampler: Some(1), + mutable: false, + }, + ); + let options = msl::Options { + binding_map: &binding_map, + }; + msl::write_string(&vs, options).unwrap(); + msl::write_string(&fs, options).unwrap(); + } } #[cfg(feature = "glsl-in")] From 0235c4a86cc32df69001bcc74276f468596e1f60 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Sun, 13 Sep 2020 06:22:06 +0200 Subject: [PATCH 0195/2212] [glsl-in] Fix unused braces in parser.rs (#190) --- src/front/glsl/parser.rs | 143 +++++++++++++++++++++++++++++---------- 1 file changed, 107 insertions(+), 36 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2c0c2e7ea..840b36666 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,4 +1,4 @@ -#![allow(clippy::panic, unused_braces)] +#![allow(clippy::panic)] use pomelo::pomelo; pomelo! { @@ -242,7 +242,9 @@ pomelo! { ) } // primary_expression ::= DoubleConstant; - primary_expression ::= LeftParen expression(e) RightParen {e} + primary_expression ::= LeftParen expression(e) RightParen { + e + } postfix_expression ::= primary_expression; postfix_expression ::= postfix_expression LeftBracket integer_expression RightBracket { @@ -280,9 +282,15 @@ pomelo! { } } function_call_or_method ::= function_call_generic; - function_call_generic ::= function_call_header_with_parameters(h) RightParen {h} - function_call_generic ::= function_call_header_no_parameters(h) RightParen {h} - function_call_header_no_parameters ::= function_call_header(h) Void {h} + function_call_generic ::= function_call_header_with_parameters(h) RightParen { + h + } + function_call_generic ::= function_call_header_no_parameters(h) RightParen { + h + } + function_call_header_no_parameters ::= function_call_header(h) Void { + h + } function_call_header_no_parameters ::= function_call_header; function_call_header_with_parameters ::= function_call_header(mut h) assignment_expression(ae) { h.args.push(ae.expression); @@ -429,17 +437,39 @@ pomelo! { } } - assignment_operator ::= Equal {BinaryOperator::Equal} - assignment_operator ::= MulAssign {BinaryOperator::Multiply} - assignment_operator ::= DivAssign {BinaryOperator::Divide} - assignment_operator ::= ModAssign {BinaryOperator::Modulo} - assignment_operator ::= AddAssign {BinaryOperator::Add} - assignment_operator ::= SubAssign {BinaryOperator::Subtract} - assignment_operator ::= LeftAssign {BinaryOperator::ShiftLeftLogical} - assignment_operator ::= RightAssign {BinaryOperator::ShiftRightLogical} - assignment_operator ::= AndAssign {BinaryOperator::And} - assignment_operator ::= XorAssign {BinaryOperator::ExclusiveOr} - assignment_operator ::= OrAssign {BinaryOperator::InclusiveOr} + assignment_operator ::= Equal { + BinaryOperator::Equal + } + assignment_operator ::= MulAssign { + BinaryOperator::Multiply + } + assignment_operator ::= DivAssign { + BinaryOperator::Divide + } + assignment_operator ::= ModAssign { + BinaryOperator::Modulo + } + assignment_operator ::= AddAssign { + BinaryOperator::Add + } + assignment_operator ::= SubAssign { + BinaryOperator::Subtract + } + assignment_operator ::= LeftAssign { + BinaryOperator::ShiftLeftLogical + } + assignment_operator ::= RightAssign { + BinaryOperator::ShiftRightLogical + } + assignment_operator ::= AndAssign { + BinaryOperator::And + } + assignment_operator ::= XorAssign { + BinaryOperator::ExclusiveOr + } + assignment_operator ::= OrAssign { + BinaryOperator::InclusiveOr + } expression ::= assignment_expression; expression ::= expression(e) Comma assignment_expression(mut ae) { @@ -460,7 +490,9 @@ pomelo! { // } // declaration - declaration ::= init_declarator_list(idl) Semicolon {idl} + declaration ::= init_declarator_list(idl) Semicolon { + idl + } init_declarator_list ::= single_declaration; init_declarator_list ::= init_declarator_list(mut idl) Comma Identifier(i) { @@ -504,10 +536,16 @@ pomelo! { } } - fully_specified_type ::= type_specifier(t) {(vec![], t)} - fully_specified_type ::= type_qualifier(q) type_specifier(t) {(q,t)} + fully_specified_type ::= type_specifier(t) { + (vec![], t) + } + fully_specified_type ::= type_qualifier(q) type_specifier(t) { + (q,t) + } - layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen {l} + layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen { + l + } layout_qualifier_id_list ::= layout_qualifier_id; layout_qualifier_id_list ::= layout_qualifier_id_list Comma layout_qualifier_id(l) { //TODO: for now always pick last @@ -547,12 +585,20 @@ pomelo! { // single_type_qualifier ::= invariant_qualifier; // single_type_qualifier ::= precise_qualifier; - storage_qualifier ::= Const {StorageClass::Constant} + storage_qualifier ::= Const { + StorageClass::Constant + } // storage_qualifier ::= InOut; - storage_qualifier ::= In {StorageClass::Input} - storage_qualifier ::= Out {StorageClass::Output} + storage_qualifier ::= In { + StorageClass::Input + } + storage_qualifier ::= Out { + StorageClass::Output + } //TODO: other storage qualifiers - interpolation_qualifier ::= Interpolation((_, i)) { i } + interpolation_qualifier ::= Interpolation((_, i)) { + i + } initializer ::= assignment_expression; // initializer ::= LeftBrace initializer_list RightBrace; @@ -593,7 +639,9 @@ pomelo! { } // statement - statement ::= compound_statement(cs) {Statement::Block(cs)} + statement ::= compound_statement(cs) { + Statement::Block(cs) + } statement ::= simple_statement; // Grammar Note: labeled statements for SWITCH only; 'goto' is not supported. @@ -605,7 +653,9 @@ pomelo! { //simple_statement ::= iteration_statement; simple_statement ::= jump_statement; - compound_statement ::= LeftBrace RightBrace {vec![]} + compound_statement ::= LeftBrace RightBrace { + vec![] + } compound_statement ::= left_brace_scope statement_list(sl) RightBrace { extra.context.remove_current_scope(); sl @@ -617,13 +667,21 @@ pomelo! { } - compound_statement_no_new_scope ::= LeftBrace RightBrace {vec![]} - compound_statement_no_new_scope ::= LeftBrace statement_list(sl) RightBrace {sl} + compound_statement_no_new_scope ::= LeftBrace RightBrace { + vec![] + } + compound_statement_no_new_scope ::= LeftBrace statement_list(sl) RightBrace { + sl + } - statement_list ::= statement(s) { vec![s] } + statement_list ::= statement(s) { + vec![s] + } statement_list ::= statement_list(mut ss) statement(s) { ss.push(s); ss } - expression_statement ::= Semicolon {Statement::Empty} + expression_statement ::= Semicolon { + Statement::Empty + } expression_statement ::= expression(mut e) Semicolon { match e.statements.len() { 1 => e.statements.remove(0), @@ -671,12 +729,22 @@ pomelo! { }) } - type_specifier_nonarray ::= Void { None } - type_specifier_nonarray ::= TypeName(t) {Some(t.1)}; + type_specifier_nonarray ::= Void { + None + } + type_specifier_nonarray ::= TypeName(t) { + Some(t.1) + }; - jump_statement ::= Continue Semicolon { Statement::Continue } - jump_statement ::= Break Semicolon { Statement::Break } - jump_statement ::= Return Semicolon { Statement::Return{ value: None } } + jump_statement ::= Continue Semicolon { + Statement::Continue + } + jump_statement ::= Break Semicolon { + Statement::Break + } + jump_statement ::= Return Semicolon { + Statement::Return{ value: None } + } jump_statement ::= Return expression(mut e) Semicolon { let ret = Statement::Return{ value: Some(e.expression) }; if !e.statements.is_empty() { @@ -686,7 +754,10 @@ pomelo! { ret } } - jump_statement ::= Discard Semicolon { Statement::Kill } // Fragment shader only + jump_statement ::= Discard Semicolon { + Statement::Kill + } // Fragment shader only + // Grammar Note: No 'goto'. Gotos are not supported. // misc From 089d0dd4f8d9e878a967c327cd30523188ccbeb6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 13 Sep 2020 21:03:00 -0400 Subject: [PATCH 0196/2212] Minor fixes in feature checks (#194) --- src/front/spv/mod.rs | 15 ++++++--------- src/front/spv/rosetta.rs | 6 +++--- test-data/simple/simple.spv | Bin 0 -> 500 bytes tests/convert.rs | 2 +- 4 files changed, 10 insertions(+), 13 deletions(-) create mode 100644 test-data/simple/simple.spv diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 275ba7930..a9115f9c5 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -15,7 +15,7 @@ mod convert; mod error; mod flow; mod function; -#[cfg(test)] +#[cfg(all(test, feature = "serialize"))] mod rosetta; use convert::*; @@ -1400,19 +1400,16 @@ impl> Parser { } pub fn parse(mut self) -> Result { - let mut module = crate::Module::from_header({ + let mut module = { if self.next()? != spirv::MAGIC_NUMBER { return Err(Error::InvalidHeader); } - let version_raw = self.next()?.to_le_bytes(); - let generator = self.next()?; + let _version_raw = self.next()?.to_le_bytes(); + let _generator = self.next()?; let _bound = self.next()?; let _schema = self.next()?; - crate::Header { - version: (version_raw[2], version_raw[1], version_raw[0]), - generator, - } - }); + crate::Module::generate_empty() + }; while let Ok(inst) = self.next_inst() { use spirv::Op; diff --git a/src/front/spv/rosetta.rs b/src/front/spv/rosetta.rs index 7bd18bf19..0dffc79de 100644 --- a/src/front/spv/rosetta.rs +++ b/src/front/spv/rosetta.rs @@ -6,14 +6,14 @@ fn rosetta_test(file_name: &str) { if true { return; //TODO: fix this test } - let test_dir = Path::new(TEST_PATH); - let input = fs::read(test_dir.join(file_name)).unwrap(); + let file_path = Path::new(TEST_PATH).join(file_name); + let input = fs::read(&file_path).unwrap(); let module = super::parse_u8_slice(&input).unwrap(); let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); let expected = - fs::read_to_string(test_dir.join(file_name).with_extension("expected.ron")).unwrap(); + fs::read_to_string(file_path.with_extension("expected.ron")).unwrap(); difference::assert_diff!(output.as_str(), expected.as_str(), "", 0); } diff --git a/test-data/simple/simple.spv b/test-data/simple/simple.spv new file mode 100644 index 0000000000000000000000000000000000000000..924ff447e06a0ed4945161b4e1229042388b8c39 GIT binary patch literal 500 zcmYk2PfJ2k5XHy$e41MRNy%LpEdyy`AxO1!<09|_h|s1*8W^USd-lGo#&CnMgruRC+y zdcr*E-!v;wj%y043Ti$HJ@4!{@B2f^y}vE_vh**}JaYYt59!>1U(v;F%rD4Kz)6aF zv_L(z8*YnjBI4_54DXPsx#I+W3jY6th(*brsb>8dXuX>CUC=kETVHXtYF>}rbI*(2 z(ODk%`hoSq1)jV5Z`9rKfqw2cAe<+6_BmnQGu@m!B&>0cp4&dMl{@JD!so;v(JmGt literal 0 HcmV?d00001 diff --git a/tests/convert.rs b/tests/convert.rs index 9598fbf39..a95d4affd 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -22,7 +22,7 @@ fn load_glsl(name: &str, entry: &str, stage: naga::ShaderStage) -> naga::Module naga::front::glsl::parse_str(&input, entry.to_owned(), stage).unwrap() } -#[cfg(feature = "spirv-in")] +#[cfg(feature = "wgsl-in")] #[test] fn convert_quad() { let module = load_wgsl("quad.wgsl"); From a9355f928fcb88f1581ed586a444535b0c6a8e17 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 14 Sep 2020 03:20:46 +0200 Subject: [PATCH 0197/2212] [glsl-in] Add gl_VertexIndex (#189) * [glsl-in] Add gl_VertexIndex Refactor variable handling out of parser.rs * [glsl-in] Fixes for gl_VertexIndex - Make lookup_variable a method of Program - Try to cleanup conditional logic * [glsl-in] Error on gl_ builtin in wrong stage Wrapped in glsl-validate feature --- src/front/glsl/error.rs | 6 +++ src/front/glsl/mod.rs | 1 + src/front/glsl/parser.rs | 66 ++++++-------------------- src/front/glsl/variables.rs | 93 +++++++++++++++++++++++++++++++++++++ 4 files changed, 113 insertions(+), 53 deletions(-) create mode 100644 src/front/glsl/variables.rs diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 859fb06e2..61bd7759f 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -16,6 +16,8 @@ pub enum ErrorKind { UnknownVariable(TokenMetadata, String), #[cfg(feature = "glsl-validate")] VariableAlreadyDeclared(String), + #[cfg(feature = "glsl-validate")] + VariableNotAvailable(String), ExpectedConstant, SemanticError(&'static str), } @@ -43,6 +45,10 @@ impl fmt::Display for ErrorKind { ErrorKind::VariableAlreadyDeclared(val) => { write!(f, "Variable {} already decalred in current scope", val) } + #[cfg(feature = "glsl-validate")] + ErrorKind::VariableNotAvailable(val) => { + write!(f, "Variable {} not available in this stage", val) + } ErrorKind::ExpectedConstant => write!(f, "Expected constant"), ErrorKind::SemanticError(msg) => write!(f, "Semantic error: {}", msg), } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 2af60fe94..338a21f68 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -15,6 +15,7 @@ mod parser; mod parser_tests; mod token; mod types; +mod variables; #[cfg(all(test, feature = "serialize"))] mod rosetta_tests; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 840b36666..57bb843c7 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -5,10 +5,10 @@ pomelo! { //%verbose; %include { use super::super::{error::ErrorKind, token::*, ast::*}; - use crate::{Arena, BinaryOperator, Binding, Block, BuiltIn, Constant, ConstantInner, Expression, + use crate::{Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, Expression, Function, GlobalVariable, Handle, LocalVariable, ScalarKind, - ShaderStage, Statement, StorageAccess, StorageClass, Type, TypeInner, - VectorSize, Interpolation}; + Statement, StorageAccess, StorageClass, Type, TypeInner, + Interpolation}; } %token #[derive(Debug)] pub enum Token {}; %parser pub struct Parser<'a> {}; @@ -132,57 +132,17 @@ pomelo! { // expression variable_identifier ::= Identifier(v) { - let gl_position = if let ShaderStage::Vertex | ShaderStage::Fragment { .. } = extra.shader_stage { - if v.1.as_str() == "gl_Position" { - let h = extra.global_variables.fetch_or_append( - GlobalVariable { - name: Some(v.1.clone()), - class: match extra.shader_stage { - ShaderStage::Vertex => StorageClass::Output, - ShaderStage::Fragment { .. } => StorageClass::Input, - _ => StorageClass::Input, - }, - binding: Some(Binding::BuiltIn(BuiltIn::Position)), - ty: extra.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, - }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }, - ); - extra.lookup_global_variables.insert(v.1.clone(), h); - let expression = extra.context.expressions.append( - Expression::GlobalVariable(h) - ); - extra.context.lookup_global_var_exps.insert(v.1.clone(), expression); - - Some(expression) - } else { - None + let var = extra.lookup_variable(&v.1)?; + match var { + Some(expression) => { + ExpressionRule::from_expression( + expression + ) + }, + None => { + return Err(ErrorKind::UnknownVariable(v.0, v.1)); } - } else { - None - }; - - let expression = - if let Some(gl_position) = gl_position { - gl_position - } else if let Some(local_var) = extra.context.lookup_local_var(&v.1) { - local_var - } else if let Some(global_var) = extra.context.lookup_global_var_exps.get(&v.1) { - *global_var - } else { - return Err(ErrorKind::UnknownVariable(v.0, v.1)); - }; - - ExpressionRule::from_expression( - expression - ) + } } primary_expression ::= variable_identifier; diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs new file mode 100644 index 000000000..263bca52e --- /dev/null +++ b/src/front/glsl/variables.rs @@ -0,0 +1,93 @@ +use crate::{ + Binding, BuiltIn, Expression, GlobalVariable, Handle, ScalarKind, ShaderStage, StorageAccess, + StorageClass, Type, TypeInner, VectorSize, +}; + +use super::ast::*; +use super::error::ErrorKind; + +impl Program { + pub fn lookup_variable(&mut self, name: &str) -> Result>, ErrorKind> { + let mut expression: Option> = None; + match name { + "gl_Position" => { + #[cfg(feature = "glsl-validate")] + match self.shader_stage { + ShaderStage::Vertex | ShaderStage::Fragment { .. } => {} + _ => { + return Err(ErrorKind::VariableNotAvailable(name.into())); + } + }; + let h = self.global_variables.fetch_or_append(GlobalVariable { + name: Some(name.into()), + class: if self.shader_stage == ShaderStage::Vertex { + StorageClass::Output + } else { + StorageClass::Input + }, + binding: Some(Binding::BuiltIn(BuiltIn::Position)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 4, + }, + }), + interpolation: None, + storage_access: StorageAccess::empty(), + }); + self.lookup_global_variables.insert(name.into(), h); + let exp = self + .context + .expressions + .append(Expression::GlobalVariable(h)); + self.context.lookup_global_var_exps.insert(name.into(), exp); + + expression = Some(exp); + } + "gl_VertexIndex" => { + #[cfg(feature = "glsl-validate")] + match self.shader_stage { + ShaderStage::Vertex => {} + _ => { + return Err(ErrorKind::VariableNotAvailable(name.into())); + } + }; + let h = self.global_variables.fetch_or_append(GlobalVariable { + name: Some(name.into()), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), + ty: self.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + }, + }), + interpolation: None, + storage_access: StorageAccess::empty(), + }); + self.lookup_global_variables.insert(name.into(), h); + let exp = self + .context + .expressions + .append(Expression::GlobalVariable(h)); + self.context.lookup_global_var_exps.insert(name.into(), exp); + + expression = Some(exp); + } + _ => {} + } + + if let Some(expression) = expression { + Ok(Some(expression)) + } else if let Some(local_var) = self.context.lookup_local_var(name) { + Ok(Some(local_var)) + } else if let Some(global_var) = self.context.lookup_global_var_exps.get(name) { + Ok(Some(*global_var)) + } else { + Ok(None) + } + } +} From 094e4fdd175ebbd3268e020c30c68550e2b7ebfc Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 14 Sep 2020 07:16:12 +0200 Subject: [PATCH 0198/2212] Fix lexer operator issues (with tests) (#188) * Fix lexer operator issues (with tests) * [glsl-in] Don't convet to string in lexer tests * [glsl-in] cleanup lexer tests further - Consolidate use statements - Iterate lex directly, check for None at end --- src/front/glsl/lex.rs | 66 +++--- src/front/glsl/lex_tests.rs | 409 +++++++++++++++++++++++++++++------- src/front/glsl/parser.rs | 2 +- src/front/glsl/token.rs | 1 + 4 files changed, 368 insertions(+), 110 deletions(-) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 060b16c2e..7e44a7901 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -156,39 +156,41 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { } } - '+' | '-' | '&' | '|' => { + '+' | '-' | '&' | '|' | '^' => { input = chars.as_str(); - match chars.next() { - Some('=') => { - meta.chars.end = start + 2; - match cur { - '+' => (Some(Token::AddAssign(meta)), chars.as_str()), - '-' => (Some(Token::SubAssign(meta)), chars.as_str()), - '&' => (Some(Token::AndAssign(meta)), chars.as_str()), - '|' => (Some(Token::OrAssign(meta)), chars.as_str()), - '^' => (Some(Token::XorAssign(meta)), chars.as_str()), - _ => (None, input), - } - } - Some(cur) => { - meta.chars.end = start + 2; - match cur { - '+' => (Some(Token::IncOp(meta)), chars.as_str()), - '-' => (Some(Token::DecOp(meta)), chars.as_str()), - '&' => (Some(Token::AndOp(meta)), chars.as_str()), - '|' => (Some(Token::OrOp(meta)), chars.as_str()), - '^' => (Some(Token::XorOp(meta)), chars.as_str()), - _ => (None, input), - } - } - _ => match cur { - '+' => (Some(Token::Plus(meta)), input), - '-' => (Some(Token::Dash(meta)), input), - '&' => (Some(Token::Ampersand(meta)), input), - '|' => (Some(Token::VerticalBar(meta)), input), - '^' => (Some(Token::Caret(meta)), input), + let next = chars.next(); + if next == Some(cur) { + meta.chars.end = start + 2; + match cur { + '+' => (Some(Token::IncOp(meta)), chars.as_str()), + '-' => (Some(Token::DecOp(meta)), chars.as_str()), + '&' => (Some(Token::AndOp(meta)), chars.as_str()), + '|' => (Some(Token::OrOp(meta)), chars.as_str()), + '^' => (Some(Token::XorOp(meta)), chars.as_str()), _ => (None, input), - }, + } + } else { + match next { + Some('=') => { + meta.chars.end = start + 2; + match cur { + '+' => (Some(Token::AddAssign(meta)), chars.as_str()), + '-' => (Some(Token::SubAssign(meta)), chars.as_str()), + '&' => (Some(Token::AndAssign(meta)), chars.as_str()), + '|' => (Some(Token::OrAssign(meta)), chars.as_str()), + '^' => (Some(Token::XorAssign(meta)), chars.as_str()), + _ => (None, input), + } + } + _ => match cur { + '+' => (Some(Token::Plus(meta)), input), + '-' => (Some(Token::Dash(meta)), input), + '&' => (Some(Token::Ampersand(meta)), input), + '|' => (Some(Token::VerticalBar(meta)), input), + '^' => (Some(Token::Caret(meta)), input), + _ => (None, input), + }, + } } } @@ -224,7 +226,7 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { meta.chars.end = start + 2; (Some(Token::CommentEnd((meta, ()))), chars.as_str()) } - _ => (Some(Token::MulAssign(meta)), input), + _ => (Some(Token::Star(meta)), input), } } '/' => { diff --git a/src/front/glsl/lex_tests.rs b/src/front/glsl/lex_tests.rs index 5d260cae5..7710b4eb9 100644 --- a/src/front/glsl/lex_tests.rs +++ b/src/front/glsl/lex_tests.rs @@ -1,160 +1,415 @@ -use super::lex::Lexer; -use super::parser::Token; +use super::{lex::Lexer, parser::Token::*, token::TokenMetadata}; #[test] fn glsl_lex_simple() { let source = "void main() {\n}"; - let lex = Lexer::new(source); - let tokens: Vec = lex.collect(); - assert_eq!(tokens.len(), 6); + let mut lex = Lexer::new(source); - let mut iter = tokens.iter(); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Void(TokenMetadata { line: 0, chars: 0..4 })" + lex.next().unwrap(), + Void(TokenMetadata { + line: 0, + chars: 0..4 + }) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Identifier((TokenMetadata { line: 0, chars: 5..9 }, \"main\"))" + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 0, + chars: 5..9 + }, + "main".into() + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "LeftParen(TokenMetadata { line: 0, chars: 9..10 })" + lex.next().unwrap(), + LeftParen(TokenMetadata { + line: 0, + chars: 9..10 + }) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "RightParen(TokenMetadata { line: 0, chars: 10..11 })" + lex.next().unwrap(), + RightParen(TokenMetadata { + line: 0, + chars: 10..11 + }) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "LeftBrace(TokenMetadata { line: 0, chars: 12..13 })" + lex.next().unwrap(), + LeftBrace(TokenMetadata { + line: 0, + chars: 12..13 + }) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "RightBrace(TokenMetadata { line: 1, chars: 0..1 })" + lex.next().unwrap(), + RightBrace(TokenMetadata { + line: 1, + chars: 0..1 + }) ); + assert_eq!(lex.next(), None); } #[test] fn glsl_lex_line_comment() { let source = "void main // myfunction\n//()\n{}"; - let lex = Lexer::new(source); - let tokens: Vec = lex.collect(); - assert_eq!(tokens.len(), 4); - - let mut iter = tokens.iter(); + let mut lex = Lexer::new(source); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Void(TokenMetadata { line: 0, chars: 0..4 })" + lex.next().unwrap(), + Void(TokenMetadata { + line: 0, + chars: 0..4 + }) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Identifier((TokenMetadata { line: 0, chars: 5..9 }, \"main\"))" + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 0, + chars: 5..9 + }, + "main".into() + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "LeftBrace(TokenMetadata { line: 2, chars: 0..1 })" + lex.next().unwrap(), + LeftBrace(TokenMetadata { + line: 2, + chars: 0..1 + }) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "RightBrace(TokenMetadata { line: 2, chars: 1..2 })" + lex.next().unwrap(), + RightBrace(TokenMetadata { + line: 2, + chars: 1..2 + }) ); + assert_eq!(lex.next(), None); } #[test] fn glsl_lex_multi_line_comment() { let source = "void main /* comment [] {}\n/**\n{}*/{}"; - let lex = Lexer::new(source); - let tokens: Vec = lex.collect(); - assert_eq!(tokens.len(), 4); + let mut lex = Lexer::new(source); - let mut iter = tokens.iter(); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Void(TokenMetadata { line: 0, chars: 0..4 })" + lex.next().unwrap(), + Void(TokenMetadata { + line: 0, + chars: 0..4 + }) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Identifier((TokenMetadata { line: 0, chars: 5..9 }, \"main\"))" + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 0, + chars: 5..9 + }, + "main".into() + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "LeftBrace(TokenMetadata { line: 2, chars: 4..5 })" + lex.next().unwrap(), + LeftBrace(TokenMetadata { + line: 2, + chars: 4..5 + }) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "RightBrace(TokenMetadata { line: 2, chars: 5..6 })" + lex.next().unwrap(), + RightBrace(TokenMetadata { + line: 2, + chars: 5..6 + }) ); + assert_eq!(lex.next(), None); } #[test] fn glsl_lex_identifier() { let source = "id123_OK 92No æNoø No¾ No好"; - let lex = Lexer::new(source); - let tokens: Vec = lex.collect(); - assert_eq!(tokens.len(), 10); + let mut lex = Lexer::new(source); - let mut iter = tokens.iter(); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Identifier((TokenMetadata { line: 0, chars: 0..8 }, \"id123_OK\"))" + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 0, + chars: 0..8 + }, + "id123_OK".into() + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "IntConstant((TokenMetadata { line: 0, chars: 9..11 }, 92))" + lex.next().unwrap(), + IntConstant(( + TokenMetadata { + line: 0, + chars: 9..11 + }, + 92 + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Identifier((TokenMetadata { line: 0, chars: 11..13 }, \"No\"))" + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 0, + chars: 11..13 + }, + "No".into() + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Unknown((TokenMetadata { line: 0, chars: 14..15 }, \'æ\'))" + lex.next().unwrap(), + Unknown(( + TokenMetadata { + line: 0, + chars: 14..15 + }, + 'æ' + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Identifier((TokenMetadata { line: 0, chars: 15..17 }, \"No\"))" + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 0, + chars: 15..17 + }, + "No".into() + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Unknown((TokenMetadata { line: 0, chars: 17..18 }, \'ø\'))" + lex.next().unwrap(), + Unknown(( + TokenMetadata { + line: 0, + chars: 17..18 + }, + 'ø' + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Identifier((TokenMetadata { line: 0, chars: 19..21 }, \"No\"))" + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 0, + chars: 19..21 + }, + "No".into() + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Unknown((TokenMetadata { line: 0, chars: 21..22 }, \'¾\'))" + lex.next().unwrap(), + Unknown(( + TokenMetadata { + line: 0, + chars: 21..22 + }, + '¾' + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Identifier((TokenMetadata { line: 0, chars: 23..25 }, \"No\"))" + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 0, + chars: 23..25 + }, + "No".into() + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Unknown((TokenMetadata { line: 0, chars: 25..26 }, \'好\'))" + lex.next().unwrap(), + Unknown(( + TokenMetadata { + line: 0, + chars: 25..26 + }, + '好' + )) ); + assert_eq!(lex.next(), None); } #[test] fn glsl_lex_version() { let source = "#version 890 core"; - let lex = Lexer::new(source); - let tokens: Vec = lex.collect(); - assert_eq!(tokens.len(), 3); + let mut lex = Lexer::new(source); - let mut iter = tokens.iter(); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Version(TokenMetadata { line: 0, chars: 0..8 })" + lex.next().unwrap(), + Version(TokenMetadata { + line: 0, + chars: 0..8 + }) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "IntConstant((TokenMetadata { line: 0, chars: 9..12 }, 890))" + lex.next().unwrap(), + IntConstant(( + TokenMetadata { + line: 0, + chars: 9..12 + }, + 890 + )) ); assert_eq!( - format!("{:?}", iter.next().unwrap()), - "Identifier((TokenMetadata { line: 0, chars: 13..17 }, \"core\"))" + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 0, + chars: 13..17 + }, + "core".into() + )) ); + assert_eq!(lex.next(), None); +} + +#[test] +fn glsl_lex_operators() { + let source = "+ - * | & % / += -= *= |= &= %= /= ++ -- || && ^^"; + let mut lex = Lexer::new(source); + + assert_eq!( + lex.next().unwrap(), + Plus(TokenMetadata { + line: 0, + chars: 0..1 + }) + ); + assert_eq!( + lex.next().unwrap(), + Dash(TokenMetadata { + line: 0, + chars: 2..3 + }) + ); + assert_eq!( + lex.next().unwrap(), + Star(TokenMetadata { + line: 0, + chars: 4..5 + }) + ); + assert_eq!( + lex.next().unwrap(), + VerticalBar(TokenMetadata { + line: 0, + chars: 6..7 + }) + ); + assert_eq!( + lex.next().unwrap(), + Ampersand(TokenMetadata { + line: 0, + chars: 8..9 + }) + ); + assert_eq!( + lex.next().unwrap(), + Percent(TokenMetadata { + line: 0, + chars: 10..11 + }) + ); + assert_eq!( + lex.next().unwrap(), + Slash(TokenMetadata { + line: 0, + chars: 12..13 + }) + ); + assert_eq!( + lex.next().unwrap(), + AddAssign(TokenMetadata { + line: 0, + chars: 14..16 + }) + ); + assert_eq!( + lex.next().unwrap(), + SubAssign(TokenMetadata { + line: 0, + chars: 17..19 + }) + ); + assert_eq!( + lex.next().unwrap(), + MulAssign(TokenMetadata { + line: 0, + chars: 20..22 + }) + ); + assert_eq!( + lex.next().unwrap(), + OrAssign(TokenMetadata { + line: 0, + chars: 23..25 + }) + ); + assert_eq!( + lex.next().unwrap(), + AndAssign(TokenMetadata { + line: 0, + chars: 26..28 + }) + ); + assert_eq!( + lex.next().unwrap(), + ModAssign(TokenMetadata { + line: 0, + chars: 29..31 + }) + ); + assert_eq!( + lex.next().unwrap(), + DivAssign(TokenMetadata { + line: 0, + chars: 32..34 + }) + ); + assert_eq!( + lex.next().unwrap(), + IncOp(TokenMetadata { + line: 0, + chars: 35..37 + }) + ); + assert_eq!( + lex.next().unwrap(), + DecOp(TokenMetadata { + line: 0, + chars: 38..40 + }) + ); + assert_eq!( + lex.next().unwrap(), + OrOp(TokenMetadata { + line: 0, + chars: 41..43 + }) + ); + assert_eq!( + lex.next().unwrap(), + AndOp(TokenMetadata { + line: 0, + chars: 44..46 + }) + ); + assert_eq!( + lex.next().unwrap(), + XorOp(TokenMetadata { + line: 0, + chars: 47..49 + }) + ); + assert_eq!(lex.next(), None); } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 57bb843c7..c9e1743ba 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -10,7 +10,7 @@ pomelo! { Statement, StorageAccess, StorageClass, Type, TypeInner, Interpolation}; } - %token #[derive(Debug)] pub enum Token {}; + %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; %parser pub struct Parser<'a> {}; %extra_argument &'a mut Program; %extra_token TokenMetadata; diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 31daf24cb..7b849d361 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -1,6 +1,7 @@ use std::ops::Range; #[derive(Debug, Clone)] +#[cfg_attr(test, derive(PartialEq))] pub struct TokenMetadata { pub line: usize, pub chars: Range, From f04a07c86c0ee6ac4184acb74f0a6e82efecf13f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 14 Sep 2020 01:14:51 -0400 Subject: [PATCH 0199/2212] proc: make typifier work with gaps in the type graph --- src/back/glsl.rs | 28 +-- src/back/msl.rs | 36 ++-- src/front/spv/rosetta.rs | 3 +- src/front/wgsl/mod.rs | 155 ++++++++++------- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 363 +++++++++++++++++++++------------------ 6 files changed, 322 insertions(+), 265 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index dd472e32e..ed8f3feb0 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,4 +1,4 @@ -use super::{BorrowType, MaybeOwned}; +use super::BorrowType; use crate::{ proc::{Interface, Visitor}, Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, @@ -661,14 +661,14 @@ fn write_expression<'a, 'b>( let inner = match *ty.borrow() { TypeInner::Vector { kind, width, .. } => { - MaybeOwned::Owned(TypeInner::Scalar { kind, width }) + BorrowType::Owned(TypeInner::Scalar { kind, width }) } TypeInner::Matrix { kind, width, columns, .. - } => MaybeOwned::Owned(TypeInner::Vector { + } => BorrowType::Owned(TypeInner::Vector { kind, width, size: columns, @@ -692,7 +692,7 @@ fn write_expression<'a, 'b>( match *ty.borrow() { TypeInner::Vector { kind, width, .. } => ( Cow::Owned(format!("{}[{}]", base_expr, index)), - MaybeOwned::Owned(TypeInner::Scalar { kind, width }), + BorrowType::Owned(TypeInner::Scalar { kind, width }), ), TypeInner::Matrix { kind, @@ -701,7 +701,7 @@ fn write_expression<'a, 'b>( .. } => ( Cow::Owned(format!("{}[{}]", base_expr, index)), - MaybeOwned::Owned(TypeInner::Vector { + BorrowType::Owned(TypeInner::Vector { kind, width, size: columns, @@ -869,9 +869,9 @@ fn write_expression<'a, 'b>( let width = 4; let ty = if shadow { - MaybeOwned::Owned(TypeInner::Scalar { kind, width }) + BorrowType::Owned(TypeInner::Scalar { kind, width }) } else { - MaybeOwned::Owned(TypeInner::Vector { kind, width, size }) + BorrowType::Owned(TypeInner::Vector { kind, width, size }) }; (Cow::Owned(expr), ty) @@ -942,7 +942,7 @@ fn write_expression<'a, 'b>( let width = 4; ( Cow::Owned(expr), - MaybeOwned::Owned(TypeInner::Vector { kind, width, size }), + BorrowType::Owned(TypeInner::Vector { kind, width, size }), ) } Expression::Unary { op, expr } => { @@ -1043,7 +1043,7 @@ fn write_expression<'a, 'b>( | BinaryOperator::Less | BinaryOperator::LessEqual | BinaryOperator::Greater - | BinaryOperator::GreaterEqual => MaybeOwned::Owned(TypeInner::Scalar { + | BinaryOperator::GreaterEqual => BorrowType::Owned(TypeInner::Scalar { kind: ScalarKind::Bool, width: 1, }), @@ -1083,7 +1083,7 @@ fn write_expression<'a, 'b>( rows, kind, width, - } => MaybeOwned::Owned(TypeInner::Matrix { + } => BorrowType::Owned(TypeInner::Matrix { columns: rows, rows: columns, kind, @@ -1106,7 +1106,7 @@ fn write_expression<'a, 'b>( let ty = match *left_ty.borrow() { TypeInner::Vector { kind, width, .. } => { - MaybeOwned::Owned(TypeInner::Scalar { kind, width }) + BorrowType::Owned(TypeInner::Scalar { kind, width }) } _ => { return Err(Error::Custom(format!( @@ -1140,7 +1140,7 @@ fn write_expression<'a, 'b>( TypeInner::Scalar { width, kind } => ( kind, Cow::Borrowed(map_scalar(kind, width, builder.features)?.full), - MaybeOwned::Owned(TypeInner::Scalar { kind, width }), + BorrowType::Owned(TypeInner::Scalar { kind, width }), ), TypeInner::Vector { width, kind, size } => ( kind, @@ -1148,7 +1148,7 @@ fn write_expression<'a, 'b>( "{}vec", map_scalar(kind, width, builder.features)?.prefix )), - MaybeOwned::Owned(TypeInner::Vector { kind, width, size }), + BorrowType::Owned(TypeInner::Vector { kind, width, size }), ), _ => return Err(Error::Custom(format!("Cannot convert {}", value_expr))), }; @@ -1196,7 +1196,7 @@ fn write_expression<'a, 'b>( FunctionOrigin::Local(function) => module.functions[function] .return_type .map(|ty| module.borrow_type(ty)) - .unwrap_or(MaybeOwned::Owned( + .unwrap_or(BorrowType::Owned( TypeInner::Sampler { comparison: false }, /*Dummy type*/ )), FunctionOrigin::External(_) => { diff --git a/src/back/msl.rs b/src/back/msl.rs index 251dfd503..e35a6bfc8 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -14,7 +14,7 @@ the output struct. If there is a structure in the outputs, and it contains any b we move them up to the root output structure that we define ourselves. !*/ -use super::{BorrowType, MaybeOwned}; +use super::BorrowType; use crate::{arena::Handle, FastHashMap}; use std::fmt::{Display, Error as FmtError, Formatter, Write}; @@ -410,7 +410,7 @@ impl Writer { rows, kind, width, .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; - Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + Ok(BorrowType::Owned(crate::TypeInner::Vector { size: rows, kind, width, @@ -418,7 +418,7 @@ impl Writer { } crate::TypeInner::Vector { kind, width, .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; - Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width })) + Ok(BorrowType::Owned(crate::TypeInner::Scalar { kind, width })) } crate::TypeInner::Array { base, @@ -460,7 +460,7 @@ impl Writer { } _ => return Err(Error::UnsupportedCompose(ty)), } - Ok(MaybeOwned::Borrowed(inner)) + Ok(BorrowType::Borrowed(inner)) } crate::Expression::GlobalVariable(handle) => { let var = &module.global_variables[handle]; @@ -468,7 +468,7 @@ impl Writer { match var.class { crate::StorageClass::Output => { if let crate::TypeInner::Struct { .. } = *inner { - return Ok(MaybeOwned::Borrowed(inner)); + return Ok(BorrowType::Borrowed(inner)); } write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; } @@ -481,14 +481,14 @@ impl Writer { } let name = var.name.or_index(handle); write!(self.out, "{}", name)?; - Ok(MaybeOwned::Borrowed(inner)) + Ok(BorrowType::Borrowed(inner)) } crate::Expression::LocalVariable(handle) => { let var = &function.local_variables[handle]; let inner = &module.types[var.ty].inner; let name = var.name.or_index(handle); write!(self.out, "{}", name)?; - Ok(MaybeOwned::Borrowed(inner)) + Ok(BorrowType::Borrowed(inner)) } crate::Expression::Load { pointer } => { //write!(self.out, "*")?; @@ -533,7 +533,7 @@ impl Writer { ( &crate::TypeInner::Scalar { kind, width }, &crate::TypeInner::Scalar { .. }, - ) => MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width }), + ) => BorrowType::Owned(crate::TypeInner::Scalar { kind, width }), ( &crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, kind, width }, @@ -545,7 +545,7 @@ impl Writer { | ( &crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Vector { .. }, - ) => MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), + ) => BorrowType::Owned(crate::TypeInner::Vector { size, kind, width }), ( &crate::TypeInner::Matrix { rows, @@ -554,7 +554,7 @@ impl Writer { width, }, &crate::TypeInner::Vector { .. }, - ) => MaybeOwned::Owned(crate::TypeInner::Vector { + ) => BorrowType::Owned(crate::TypeInner::Vector { size: rows, kind, width, @@ -564,7 +564,7 @@ impl Writer { } } } else { - MaybeOwned::Owned(crate::TypeInner::Scalar { + BorrowType::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1, }) @@ -599,7 +599,7 @@ impl Writer { write!(self.out, ")")?; match *ty_image.borrow() { crate::TypeInner::Image { kind, .. } => { - Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + Ok(BorrowType::Owned(crate::TypeInner::Vector { size: crate::VectorSize::Quad, kind, width: 4, @@ -633,7 +633,7 @@ impl Writer { crate::SampleLevel::Bias(_) => return Err(Error::UnexpectedSampleLevel(level)), } write!(self.out, ")")?; - Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { + Ok(BorrowType::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: 4, })) @@ -652,7 +652,7 @@ impl Writer { write!(self.out, ")")?; match *ty_image.borrow() { crate::TypeInner::Image { kind, .. } => { - Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + Ok(BorrowType::Owned(crate::TypeInner::Vector { size: crate::VectorSize::Quad, kind, width: 4, @@ -701,7 +701,7 @@ impl Writer { write!(self.out, ", ")?; self.put_expression(arguments[1], function, module)?; write!(self.out, ")")?; - Ok(MaybeOwned::Owned(result)) + Ok(BorrowType::Owned(result)) } "length" => { write!(self.out, "length(")?; @@ -713,7 +713,7 @@ impl Writer { _ => return Err(Error::UnexpectedDistanceArgument(ty_arg)), }; write!(self.out, ")")?; - Ok(MaybeOwned::Owned(result)) + Ok(BorrowType::Owned(result)) } "mix" => { write!(self.out, "mix(")?; @@ -735,7 +735,7 @@ impl Writer { &'w mut self, handle: Handle, module: &'a crate::Module, - ) -> Result, Error<'a>> { + ) -> Result, Error<'a>> { let constant = &module.constants[handle]; let ty = &module.types[constant.ty]; @@ -768,7 +768,7 @@ impl Writer { } } - Ok(MaybeOwned::Borrowed(&ty.inner)) + Ok(BorrowType::Borrowed(&ty.inner)) } fn put_statement<'w, 'a: 'w>( diff --git a/src/front/spv/rosetta.rs b/src/front/spv/rosetta.rs index 0dffc79de..c787e7646 100644 --- a/src/front/spv/rosetta.rs +++ b/src/front/spv/rosetta.rs @@ -12,8 +12,7 @@ fn rosetta_test(file_name: &str) { let module = super::parse_u8_slice(&input).unwrap(); let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); - let expected = - fs::read_to_string(file_path.with_extension("expected.ron")).unwrap(); + let expected = fs::read_to_string(file_path.with_extension("expected.ron")).unwrap(); difference::assert_diff!(output.as_str(), expected.as_str(), "", 0); } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f291057b1..f3f980e9b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -8,7 +8,7 @@ mod rosetta_tests; use crate::{ arena::{Arena, Handle}, - proc::{ResolveError, Typifier}, + proc::{ResolveContext, ResolveError, Typifier}, FastHashMap, }; @@ -156,19 +156,22 @@ impl<'a> ExpressionContext<'a, '_, '_> { fn resolve_type( &mut self, handle: Handle, - ) -> Result, Error<'a>> { - self.typifier - .resolve( - handle, - self.expressions, - self.types, - self.constants, - self.global_vars, - self.local_vars, - &Arena::new(), //TODO - self.parameter_types, - ) - .map_err(Error::InvalidResolve) + ) -> Result<&crate::TypeInner, Error<'a>> { + let functions = Arena::new(); //TODO + let resolve_ctx = ResolveContext { + constants: self.constants, + global_vars: self.global_vars, + local_vars: self.local_vars, + functions: &functions, + parameter_types: self.parameter_types, + }; + match self + .typifier + .grow(handle, self.expressions, self.types, &resolve_ctx) + { + Err(e) => Err(Error::InvalidResolve(e)), + Ok(()) => Ok(self.typifier.get(handle, self.types)), + } } fn parse_binary_op( @@ -194,6 +197,51 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } +enum Composition { + Single(crate::Expression), + Multi(crate::VectorSize, Vec>), +} + +impl Composition { + fn make<'a>( + base: Handle, + base_size: crate::VectorSize, + name: &'a str, + expressions: &mut Arena, + ) -> Result> { + const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; + + Ok(if name.len() > 1 { + let mut components = Vec::with_capacity(name.len()); + for ch in name.chars() { + let expr = crate::Expression::AccessIndex { + base, + index: MEMBERS[..base_size as usize] + .iter() + .position(|&m| m == ch) + .ok_or(Error::BadAccessor(name))? as u32, + }; + components.push(expressions.append(expr)); + } + + let size = match name.len() { + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + 4 => crate::VectorSize::Quad, + _ => return Err(Error::BadAccessor(name)), + }; + Composition::Multi(size, components) + } else { + let ch = name.chars().next().ok_or(Error::BadAccessor(name))?; + let index = MEMBERS[..base_size as usize] + .iter() + .position(|&m| m == ch) + .ok_or(Error::BadAccessor(name))? as u32; + Composition::Single(crate::Expression::AccessIndex { base, index }) + }) + } +} + #[derive(Clone, Debug, PartialEq)] pub enum Scope { Decoration, @@ -515,9 +563,8 @@ impl Parser { Token::Separator('.') => { let _ = lexer.next(); let name = lexer.next_ident()?; - let type_handle = ctx.resolve_type(handle)?; - let base_type = &ctx.types[type_handle]; - let expression = match base_type.inner { + println!("Resolving '{}' for {:?}", name, ctx.resolve_type(handle)); //TEMP + let expression = match *ctx.resolve_type(handle)? { crate::TypeInner::Struct { ref members } => { let index = members .iter() @@ -529,44 +576,32 @@ impl Parser { index, } } - crate::TypeInner::Vector { size, kind, width } - | crate::TypeInner::Matrix { - columns: size, + crate::TypeInner::Vector { size, kind, width } => { + match Composition::make(handle, size, name, ctx.expressions)? { + Composition::Multi(size, components) => { + let inner = crate::TypeInner::Vector { size, kind, width }; + crate::Expression::Compose { + ty: ctx + .types + .fetch_or_append(crate::Type { name: None, inner }), + components, + } + } + Composition::Single(expr) => expr, + } + } + crate::TypeInner::Matrix { + rows, + columns, kind, width, - .. - } => { - const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; - if name.len() > 1 { - let mut components = Vec::with_capacity(name.len()); - for ch in name.chars() { - let expr = crate::Expression::AccessIndex { - base: handle, - index: MEMBERS[..size as usize] - .iter() - .position(|&m| m == ch) - .ok_or(Error::BadAccessor(name))? - as u32, - }; - components.push(ctx.expressions.append(expr)); - } - let size = match name.len() { - 2 => crate::VectorSize::Bi, - 3 => crate::VectorSize::Tri, - 4 => crate::VectorSize::Quad, - _ => return Err(Error::BadAccessor(name)), - }; - let inner = if let crate::TypeInner::Matrix { rows, .. } = - base_type.inner - { - crate::TypeInner::Matrix { - columns: size, - rows, - kind, - width, - } - } else { - crate::TypeInner::Vector { size, kind, width } + } => match Composition::make(handle, columns, name, ctx.expressions)? { + Composition::Multi(columns, components) => { + let inner = crate::TypeInner::Matrix { + columns, + rows, + kind, + width, }; crate::Expression::Compose { ty: ctx @@ -574,19 +609,9 @@ impl Parser { .fetch_or_append(crate::Type { name: None, inner }), components, } - } else { - let ch = name.chars().next().unwrap(); - let index = MEMBERS[..size as usize] - .iter() - .position(|&m| m == ch) - .ok_or(Error::BadAccessor(name))? - as u32; - crate::Expression::AccessIndex { - base: handle, - index, - } } - } + Composition::Single(expr) => expr, + }, _ => return Err(Error::BadAccessor(name)), }; handle = ctx.expressions.append(expression); diff --git a/src/proc/mod.rs b/src/proc/mod.rs index a37d5bf22..827d40358 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -5,5 +5,5 @@ mod typifier; mod validator; pub use interface::{Interface, Visitor}; -pub use typifier::{check_constant_type, ResolveError, Typifier}; +pub use typifier::{check_constant_type, ResolveContext, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 58e0edc3e..793d50043 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -2,8 +2,43 @@ use crate::arena::{Arena, Handle}; use thiserror::Error; +#[derive(Debug, PartialEq)] +enum Resolution { + Handle(Handle), + Value(crate::TypeInner), +} + +// Clone is only implemented for numeric variants of `TypeInner`. +impl Clone for Resolution { + fn clone(&self) -> Self { + match *self { + Resolution::Handle(handle) => Resolution::Handle(handle), + Resolution::Value(ref v) => Resolution::Value(match *v { + crate::TypeInner::Scalar { kind, width } => { + crate::TypeInner::Scalar { kind, width } + } + crate::TypeInner::Vector { size, kind, width } => { + crate::TypeInner::Vector { size, kind, width } + } + crate::TypeInner::Matrix { + rows, + columns, + kind, + width, + } => crate::TypeInner::Matrix { + rows, + columns, + kind, + width, + }, + _ => panic!("Unepxected clone type: {:?}", v), + }), + } + } +} + pub struct Typifier { - types: Vec>, + resolutions: Vec, } #[derive(Clone, Debug, Error)] @@ -18,125 +53,132 @@ pub enum ResolveError { TypeNotFound, } -#[derive(Debug)] -enum Resolution { - Handle(crate::Handle), - Value(crate::TypeInner), +pub struct ResolveContext<'a> { + pub constants: &'a Arena, + pub global_vars: &'a Arena, + pub local_vars: &'a Arena, + pub functions: &'a Arena, + pub parameter_types: &'a [Handle], } impl Typifier { pub fn new() -> Self { - Typifier { types: Vec::new() } + Typifier { + resolutions: Vec::new(), + } + } + + pub fn clear(&mut self) { + self.resolutions.clear() + } + + pub fn get<'a>( + &'a self, + expr_handle: Handle, + types: &'a Arena, + ) -> &'a crate::TypeInner { + match self.resolutions[expr_handle.index()] { + Resolution::Handle(ty_handle) => &types[ty_handle].inner, + Resolution::Value(ref inner) => inner, + } } - #[allow(clippy::too_many_arguments)] fn resolve_impl( &self, expr: &crate::Expression, - arena: &Arena, - constants: &Arena, - global_vars: &Arena, - local_vars: &Arena, - functions: &Arena, - parameter_types: &[Handle], + types: &Arena, + ctx: &ResolveContext, ) -> Result { Ok(match *expr { - crate::Expression::Access { base, .. } => match arena[self.types[base.index()]].inner { + crate::Expression::Access { base, .. } => match *self.get(base, types) { crate::TypeInner::Array { base, .. } => Resolution::Handle(base), ref other => panic!("Can't access into {:?}", other), }, - crate::Expression::AccessIndex { base, index } => { - match arena[self.types[base.index()]].inner { - crate::TypeInner::Vector { size, kind, width } => { - if index >= size as u32 { - return Err(ResolveError::InvalidAccessIndex); - } - Resolution::Value(crate::TypeInner::Scalar { kind, width }) + crate::Expression::AccessIndex { base, index } => match *self.get(base, types) { + crate::TypeInner::Vector { size, kind, width } => { + if index >= size as u32 { + return Err(ResolveError::InvalidAccessIndex); } - crate::TypeInner::Matrix { - columns, - rows, + Resolution::Value(crate::TypeInner::Scalar { kind, width }) + } + crate::TypeInner::Matrix { + columns, + rows, + kind, + width, + } => { + if index >= columns as u32 { + return Err(ResolveError::InvalidAccessIndex); + } + Resolution::Value(crate::TypeInner::Vector { + size: rows, kind, width, - } => { - if index >= columns as u32 { - return Err(ResolveError::InvalidAccessIndex); - } - Resolution::Value(crate::TypeInner::Vector { - size: rows, - kind, - width, - }) - } - crate::TypeInner::Array { base, .. } => Resolution::Handle(base), - crate::TypeInner::Struct { ref members } => { - let member = members - .get(index as usize) - .ok_or(ResolveError::InvalidAccessIndex)?; - Resolution::Handle(member.ty) - } - ref other => panic!("Can't access into {:?}", other), + }) } - } - crate::Expression::Constant(h) => Resolution::Handle(constants[h].ty), + crate::TypeInner::Array { base, .. } => Resolution::Handle(base), + crate::TypeInner::Struct { ref members } => { + let member = members + .get(index as usize) + .ok_or(ResolveError::InvalidAccessIndex)?; + Resolution::Handle(member.ty) + } + ref other => panic!("Can't access into {:?}", other), + }, + crate::Expression::Constant(h) => Resolution::Handle(ctx.constants[h].ty), crate::Expression::Compose { ty, .. } => Resolution::Handle(ty), crate::Expression::FunctionParameter(index) => { - Resolution::Handle(parameter_types[index as usize]) + Resolution::Handle(ctx.parameter_types[index as usize]) } - crate::Expression::GlobalVariable(h) => Resolution::Handle(global_vars[h].ty), - crate::Expression::LocalVariable(h) => Resolution::Handle(local_vars[h].ty), + crate::Expression::GlobalVariable(h) => Resolution::Handle(ctx.global_vars[h].ty), + crate::Expression::LocalVariable(h) => Resolution::Handle(ctx.local_vars[h].ty), crate::Expression::Load { .. } => unimplemented!(), crate::Expression::ImageSample { image, .. } - | crate::Expression::ImageLoad { image, .. } => { - let image_ty = self.types[image.index()]; - match arena[image_ty].inner { - crate::TypeInner::Image { + | crate::Expression::ImageLoad { image, .. } => match *self.get(image, types) { + crate::TypeInner::Image { + kind, + class: crate::ImageClass::Depth, + .. + } => Resolution::Value(crate::TypeInner::Scalar { kind, width: 4 }), + crate::TypeInner::Image { kind, .. } => { + Resolution::Value(crate::TypeInner::Vector { kind, - class: crate::ImageClass::Depth, - .. - } => Resolution::Value(crate::TypeInner::Scalar { kind, width: 4 }), - crate::TypeInner::Image { kind, .. } => { - Resolution::Value(crate::TypeInner::Vector { - kind, - width: 4, - size: crate::VectorSize::Quad, - }) - } - _ => unreachable!(), + width: 4, + size: crate::VectorSize::Quad, + }) } - } - crate::Expression::Unary { expr, .. } => Resolution::Handle(self.types[expr.index()]), + _ => unreachable!(), + }, + crate::Expression::Unary { expr, .. } => self.resolutions[expr.index()].clone(), crate::Expression::Binary { op, left, right } => match op { crate::BinaryOperator::Add | crate::BinaryOperator::Subtract | crate::BinaryOperator::Divide - | crate::BinaryOperator::Modulo => Resolution::Handle(self.types[left.index()]), + | crate::BinaryOperator::Modulo => self.resolutions[left.index()].clone(), crate::BinaryOperator::Multiply => { - let ty_left = self.types[left.index()]; - let ty_right = self.types[right.index()]; + let ty_left = self.get(left, types); + let ty_right = self.get(right, types); if ty_left == ty_right { - Resolution::Handle(ty_left) - } else if let crate::TypeInner::Scalar { .. } = arena[ty_right].inner { - Resolution::Handle(ty_left) - } else if let crate::TypeInner::Scalar { .. } = arena[ty_left].inner { - Resolution::Handle(ty_right) - } else if let crate::TypeInner::Matrix { - columns, - kind, - width, - .. - } = arena[ty_left].inner - { - Resolution::Value(crate::TypeInner::Vector { - size: columns, - kind, - width, - }) + self.resolutions[left.index()].clone() + } else if let crate::TypeInner::Scalar { .. } = *ty_right { + self.resolutions[left.index()].clone() } else { - panic!( - "Incompatible arguments {:?} x {:?}", - arena[ty_left], arena[ty_right] - ); + match *ty_left { + crate::TypeInner::Scalar { .. } => { + self.resolutions[right.index()].clone() + } + crate::TypeInner::Matrix { + columns, + rows: _, + kind, + width, + } => Resolution::Value(crate::TypeInner::Vector { + size: columns, + kind, + width, + }), + _ => panic!("Incompatible arguments {:?} x {:?}", ty_left, ty_right), + } } } crate::BinaryOperator::Equal @@ -146,80 +188,68 @@ impl Typifier { | crate::BinaryOperator::Greater | crate::BinaryOperator::GreaterEqual | crate::BinaryOperator::LogicalAnd - | crate::BinaryOperator::LogicalOr => Resolution::Handle(self.types[left.index()]), + | crate::BinaryOperator::LogicalOr => self.resolutions[left.index()].clone(), crate::BinaryOperator::And | crate::BinaryOperator::ExclusiveOr | crate::BinaryOperator::InclusiveOr | crate::BinaryOperator::ShiftLeftLogical | crate::BinaryOperator::ShiftRightLogical | crate::BinaryOperator::ShiftRightArithmetic => { - Resolution::Handle(self.types[left.index()]) + self.resolutions[left.index()].clone() } }, crate::Expression::Intrinsic { .. } => unimplemented!(), - crate::Expression::Transpose(expr) => { - let ty_handle = self.types[expr.index()]; - match arena[ty_handle].inner { - crate::TypeInner::Matrix { - columns, - rows, - kind, - width, - } => Resolution::Value(crate::TypeInner::Matrix { - columns: rows, - rows: columns, - kind, - width, - }), - ref other => panic!("incompatible transpose of {:?}", other), - } - } - crate::Expression::DotProduct(left_expr, _) => { - let left_ty = self.types[left_expr.index()]; - match arena[left_ty].inner { - crate::TypeInner::Vector { - kind, - size: _, - width, - } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), - ref other => panic!("incompatible dot of {:?}", other), - } - } + crate::Expression::Transpose(expr) => match *self.get(expr, types) { + crate::TypeInner::Matrix { + columns, + rows, + kind, + width, + } => Resolution::Value(crate::TypeInner::Matrix { + columns: rows, + rows: columns, + kind, + width, + }), + ref other => panic!("incompatible transpose of {:?}", other), + }, + crate::Expression::DotProduct(left_expr, _) => match *self.get(left_expr, types) { + crate::TypeInner::Vector { + kind, + size: _, + width, + } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), + ref other => panic!("incompatible dot of {:?}", other), + }, crate::Expression::CrossProduct(_, _) => unimplemented!(), crate::Expression::As { expr, kind, convert: _, - } => { - let ty_handle = self.types[expr.index()]; - match arena[ty_handle].inner { - crate::TypeInner::Scalar { kind: _, width } => { - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - crate::TypeInner::Vector { - kind: _, - size, - width, - } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }), - ref other => panic!("incompatible as of {:?}", other), + } => match *self.get(expr, types) { + crate::TypeInner::Scalar { kind: _, width } => { + Resolution::Value(crate::TypeInner::Scalar { kind, width }) } - } + crate::TypeInner::Vector { + kind: _, + size, + width, + } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }), + ref other => panic!("incompatible as of {:?}", other), + }, crate::Expression::Derivative { .. } => unimplemented!(), crate::Expression::Call { origin: crate::FunctionOrigin::External(ref name), ref arguments, } => match name.as_str() { - "distance" | "length" | "dot" => { - let ty_handle = self.types[arguments[0].index()]; - match arena[ty_handle].inner { - crate::TypeInner::Vector { kind, width, .. } => { - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - ref other => panic!("Unexpected argument {:?}", other), + "distance" | "length" | "dot" => match *self.get(arguments[0], types) { + crate::TypeInner::Vector { kind, width, .. } => { + Resolution::Value(crate::TypeInner::Scalar { kind, width }) } - } + ref other => panic!("Unexpected argument {:?}", other), + }, "normalize" | "fclamp" | "max" | "reflect" | "pow" | "clamp" | "mix" => { - Resolution::Handle(self.types[arguments[0].index()]) + self.resolutions[arguments[0].index()].clone() } _ => return Err(ResolveError::FunctionNotDefined { name: name.clone() }), }, @@ -227,7 +257,7 @@ impl Typifier { origin: crate::FunctionOrigin::Local(handle), arguments: _, } => { - let ty = functions[handle] + let ty = ctx.functions[handle] .return_type .ok_or(ResolveError::FunctionReturnsVoid)?; Resolution::Handle(ty) @@ -235,40 +265,43 @@ impl Typifier { }) } - #[allow(clippy::too_many_arguments)] - pub fn resolve( + pub fn grow( &mut self, expr_handle: Handle, expressions: &Arena, - arena: &mut Arena, - constants: &Arena, - global_vars: &Arena, - local_vars: &Arena, - functions: &Arena, - parameter_types: &[Handle], - ) -> Result, ResolveError> { - if self.types.len() <= expr_handle.index() { - for (eh, expr) in expressions.iter().skip(self.types.len()) { - let resolution = self.resolve_impl( - expr, - arena, - constants, - global_vars, - local_vars, - functions, - parameter_types, - )?; + types: &mut Arena, + ctx: &ResolveContext, + ) -> Result<(), ResolveError> { + if self.resolutions.len() <= expr_handle.index() { + for (eh, expr) in expressions.iter().skip(self.resolutions.len()) { + let resolution = self.resolve_impl(expr, types, ctx)?; log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); - self.types.push(match resolution { + + let ty_handle = match resolution { Resolution::Handle(h) => h, - Resolution::Value(inner) => arena + Resolution::Value(inner) => types .fetch_if_or_append(crate::Type { name: None, inner }, |a, b| { a.inner == b.inner }), - }); + }; + self.resolutions.push(Resolution::Handle(ty_handle)); } } - Ok(self.types[expr_handle.index()]) + Ok(()) + } + + pub fn resolve_all( + &mut self, + expressions: &Arena, + types: &Arena, + ctx: &ResolveContext, + ) -> Result<(), ResolveError> { + self.clear(); + for (_, expr) in expressions.iter() { + let resolution = self.resolve_impl(expr, types, ctx)?; + self.resolutions.push(resolution); + } + Ok(()) } } From fb2c60b31c813c1a618e7374a8352e8ab3752552 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 14 Sep 2020 10:13:38 -0400 Subject: [PATCH 0200/2212] msl: use typifier in the backend --- src/back/msl.rs | 270 +++++++++++++++---------------------------- src/proc/typifier.rs | 5 +- 2 files changed, 96 insertions(+), 179 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index e35a6bfc8..ed7e16027 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -14,8 +14,11 @@ the output struct. If there is a structure in the outputs, and it contains any b we move them up to the root output structure that we define ourselves. !*/ -use super::BorrowType; -use crate::{arena::Handle, FastHashMap}; +use crate::{ + arena::Handle, + proc::{ResolveContext, ResolveError, Typifier}, + FastHashMap, +}; use std::fmt::{Display, Error as FmtError, Formatter, Write}; #[derive(Clone, Debug, Default, PartialEq)] @@ -57,8 +60,9 @@ impl Display for Level { // Note: some of these should be removed in favor of proper IR validation. #[derive(Debug)] -pub enum Error<'a> { +pub enum Error { Format(FmtError), + Type(ResolveError), UnexpectedLocation, MixedExecutionModels(Handle), MissingBinding(Handle), @@ -68,14 +72,10 @@ pub enum Error<'a> { BadName(String), UnexpectedGlobalType(Handle), UnimplementedBindTarget(BindTarget), - UnexpectedIndexing(BorrowType<'a>), + UnexpectedIndexing(crate::Expression), UnsupportedCompose(Handle), - UnexpectedLoadPointer(BorrowType<'a>), UnsupportedBinaryOp(crate::BinaryOperator), - UnableToInferBinaryOpOutput(BorrowType<'a>, crate::BinaryOperator, BorrowType<'a>), - UnexpectedImageType(BorrowType<'a>), UnexpectedSampleLevel(crate::SampleLevel), - UnexpectedDistanceArgument(BorrowType<'a>), UnsupportedCall(String), UnsupportedExpression(crate::Expression), UnableToReturnValue(Handle), @@ -83,12 +83,18 @@ pub enum Error<'a> { AccessIndexExceedsStaticLength(u32, u32), } -impl From for Error<'_> { +impl From for Error { fn from(e: FmtError) -> Self { Error::Format(e) } } +impl From for Error { + fn from(e: ResolveError) -> Self { + Error::Type(e) + } +} + #[derive(Clone, Copy, Debug)] enum LocationMode { VertexInput, @@ -257,7 +263,7 @@ struct TypedGlobalVariable<'a> { } impl<'a> TypedGlobalVariable<'a> { - fn try_fmt(&self, formatter: &mut W) -> Result<(), Error<'a>> { + fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { let var = &self.module.global_variables[self.handle]; let name = var.name.or_index(self.handle); let (space_qualifier, reference) = match var.class { @@ -283,7 +289,7 @@ impl<'a> TypedGlobalVariable<'a> { } impl ResolvedBinding { - fn try_fmt(&self, formatter: &mut W) -> Result<(), Error<'static>> { + fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { match *self { ResolvedBinding::BuiltIn(built_in) => { use crate::BuiltIn as Bi; @@ -332,7 +338,7 @@ impl ResolvedBinding { &self, formatter: &mut W, terminator: &str, - ) -> Result<(), Error<'static>> { + ) -> Result<(), Error> { formatter.write_str(" [[")?; self.try_fmt(formatter)?; formatter.write_str("]]")?; @@ -343,6 +349,7 @@ impl ResolvedBinding { pub struct Writer { out: W, + typifier: Typifier, } fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { @@ -375,66 +382,62 @@ fn separate(is_last: bool) -> &'static str { } impl Writer { - fn put_expression<'w, 'a: 'w>( - &'w mut self, + fn put_expression( + &mut self, expr_handle: Handle, function: &crate::Function, - module: &'a crate::Module, - ) -> Result, Error<'a>> { + module: &crate::Module, + ) -> Result<(), Error> { let expression = &function.expressions[expr_handle]; log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { crate::Expression::Access { base, index } => { - let ty_base = self.put_expression(base, function, module)?; - match *ty_base.borrow() { - crate::TypeInner::Array { base, .. } => { + self.put_expression(base, function, module)?; + match *self.typifier.get(base, &module.types) { + crate::TypeInner::Array { .. } => { //TODO: add size check self.out.write_str("[")?; self.put_expression(index, function, module)?; self.out.write_str("]")?; - Ok(module.borrow_type(base)) } - _ => Err(Error::UnexpectedIndexing(ty_base)), + _ => { + return Err(Error::UnexpectedIndexing( + function.expressions[base].clone(), + )) + } } } crate::Expression::AccessIndex { base, index } => { - let ty_base = self.put_expression(base, function, module)?; - match *ty_base.borrow() { + self.put_expression(base, function, module)?; + match *self.typifier.get(base, &module.types) { crate::TypeInner::Struct { ref members } => { let member = &members[index as usize]; let name = member.name.or_index(MemberIndex(index as usize)); write!(self.out, ".{}", name)?; - Ok(module.borrow_type(member.ty)) } - crate::TypeInner::Matrix { - rows, kind, width, .. - } => { + crate::TypeInner::Matrix { rows: size, .. } + | crate::TypeInner::Vector { size, .. } => { + if index >= size as u32 { + return Err(Error::AccessIndexExceedsStaticLength(index, size as u32)); + } write!(self.out, ".{}", COMPONENTS[index as usize])?; - Ok(BorrowType::Owned(crate::TypeInner::Vector { - size: rows, - kind, - width, - })) } - crate::TypeInner::Vector { kind, width, .. } => { - write!(self.out, ".{}", COMPONENTS[index as usize])?; - Ok(BorrowType::Owned(crate::TypeInner::Scalar { kind, width })) - } - crate::TypeInner::Array { - base, - size, - stride: _, - } => { + crate::TypeInner::Array { size, .. } => { if let crate::ArraySize::Static(length) = size { - return Err(Error::AccessIndexExceedsStaticLength(index, length)); + if index >= length { + return Err(Error::AccessIndexExceedsStaticLength(index, length)); + } } write!(self.out, "[{}]", index)?; - Ok(module.borrow_type(base)) } - _ => Err(Error::UnexpectedIndexing(ty_base)), + _ => { + return Err(Error::UnexpectedIndexing( + function.expressions[base].clone(), + )) + } } } - crate::Expression::Constant(handle) => self.put_constant(handle, module), + crate::Expression::Constant(handle) => self.put_constant(handle, module)?, crate::Expression::Compose { ty, ref components } => { let inner = &module.types[ty].inner; match *inner { @@ -460,15 +463,13 @@ impl Writer { } _ => return Err(Error::UnsupportedCompose(ty)), } - Ok(BorrowType::Borrowed(inner)) } crate::Expression::GlobalVariable(handle) => { let var = &module.global_variables[handle]; - let inner = &module.types[var.ty].inner; match var.class { crate::StorageClass::Output => { - if let crate::TypeInner::Struct { .. } = *inner { - return Ok(BorrowType::Borrowed(inner)); + if let crate::TypeInner::Struct { .. } = module.types[var.ty].inner { + return Ok(()); } write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; } @@ -481,22 +482,15 @@ impl Writer { } let name = var.name.or_index(handle); write!(self.out, "{}", name)?; - Ok(BorrowType::Borrowed(inner)) } crate::Expression::LocalVariable(handle) => { let var = &function.local_variables[handle]; - let inner = &module.types[var.ty].inner; let name = var.name.or_index(handle); write!(self.out, "{}", name)?; - Ok(BorrowType::Borrowed(inner)) } crate::Expression::Load { pointer } => { //write!(self.out, "*")?; - let ty_ptr = self.put_expression(pointer, function, module)?; - match *ty_ptr.borrow() { - crate::TypeInner::Pointer { base, .. } => Ok(module.borrow_type(base)), - _ => Err(Error::UnexpectedLoadPointer(ty_ptr)), - } + self.put_expression(pointer, function, module)?; } crate::Expression::Unary { op, expr } => { let op_str = match op { @@ -504,7 +498,7 @@ impl Writer { crate::UnaryOperator::Not => "!", }; write!(self.out, "{}", op_str)?; - self.put_expression(expr, function, module) + self.put_expression(expr, function, module)?; } crate::Expression::Binary { op, left, right } => { let op_str = match op { @@ -523,52 +517,10 @@ impl Writer { other => return Err(Error::UnsupportedBinaryOp(other)), }; //write!(self.out, "(")?; - let ty_left = self.put_expression(left, function, module)?; + self.put_expression(left, function, module)?; write!(self.out, " {} ", op_str)?; - let ty_right = self.put_expression(right, function, module)?; + self.put_expression(right, function, module)?; //write!(self.out, ")")?; - - Ok(if op_str.len() == 1 { - match (ty_left.borrow(), ty_right.borrow()) { - ( - &crate::TypeInner::Scalar { kind, width }, - &crate::TypeInner::Scalar { .. }, - ) => BorrowType::Owned(crate::TypeInner::Scalar { kind, width }), - ( - &crate::TypeInner::Scalar { .. }, - &crate::TypeInner::Vector { size, kind, width }, - ) - | ( - &crate::TypeInner::Vector { size, kind, width }, - &crate::TypeInner::Scalar { .. }, - ) - | ( - &crate::TypeInner::Vector { size, kind, width }, - &crate::TypeInner::Vector { .. }, - ) => BorrowType::Owned(crate::TypeInner::Vector { size, kind, width }), - ( - &crate::TypeInner::Matrix { - rows, - columns: _, - kind, - width, - }, - &crate::TypeInner::Vector { .. }, - ) => BorrowType::Owned(crate::TypeInner::Vector { - size: rows, - kind, - width, - }), - (_, _) => { - return Err(Error::UnableToInferBinaryOpOutput(ty_left, op, ty_right)) - } - } - } else { - BorrowType::Owned(crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: 1, - }) - }) } crate::Expression::ImageSample { image, @@ -578,7 +530,7 @@ impl Writer { depth_ref: None, } => { //TODO: handle arrayed images - let ty_image = self.put_expression(image, function, module)?; + self.put_expression(image, function, module)?; write!(self.out, ".sample(")?; self.put_expression(sampler, function, module)?; write!(self.out, ", ")?; @@ -597,16 +549,6 @@ impl Writer { } } write!(self.out, ")")?; - match *ty_image.borrow() { - crate::TypeInner::Image { kind, .. } => { - Ok(BorrowType::Owned(crate::TypeInner::Vector { - size: crate::VectorSize::Quad, - kind, - width: 4, - })) - } - _ => Err(Error::UnexpectedImageType(ty_image)), - } } crate::Expression::ImageSample { image, @@ -633,10 +575,6 @@ impl Writer { crate::SampleLevel::Bias(_) => return Err(Error::UnexpectedSampleLevel(level)), } write!(self.out, ")")?; - Ok(BorrowType::Owned(crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: 4, - })) } crate::Expression::ImageLoad { image, @@ -644,22 +582,12 @@ impl Writer { index, } => { //TODO: handle arrayed images - let ty_image = self.put_expression(image, function, module)?; + self.put_expression(image, function, module)?; write!(self.out, ".read(")?; self.put_expression(coordinate, function, module)?; write!(self.out, ", ")?; self.put_expression(index, function, module)?; write!(self.out, ")")?; - match *ty_image.borrow() { - crate::TypeInner::Image { kind, .. } => { - Ok(BorrowType::Owned(crate::TypeInner::Vector { - size: crate::VectorSize::Quad, - kind, - width: 4, - })) - } - _ => Err(Error::UnexpectedImageType(ty_image)), - } } crate::Expression::Call { origin: crate::FunctionOrigin::External(ref name), @@ -667,75 +595,58 @@ impl Writer { } => match name.as_str() { "cos" | "normalize" | "sin" => { write!(self.out, "{}(", name)?; - let result = self.put_expression(arguments[0], function, module)?; + self.put_expression(arguments[0], function, module)?; write!(self.out, ")")?; - Ok(result) } "fclamp" => { write!(self.out, "clamp(")?; - let result = self.put_expression(arguments[0], function, module)?; + self.put_expression(arguments[0], function, module)?; write!(self.out, ", ")?; self.put_expression(arguments[1], function, module)?; write!(self.out, ", ")?; self.put_expression(arguments[2], function, module)?; write!(self.out, ")")?; - Ok(result) } "atan2" => { write!(self.out, "{}(", name)?; - let result = self.put_expression(arguments[0], function, module)?; + self.put_expression(arguments[0], function, module)?; write!(self.out, ", ")?; self.put_expression(arguments[1], function, module)?; write!(self.out, ")")?; - Ok(result) } "distance" => { write!(self.out, "distance(")?; - let ty_arg = self.put_expression(arguments[0], function, module)?; - let result = match *ty_arg.borrow() { - crate::TypeInner::Vector { kind, width, .. } => { - crate::TypeInner::Scalar { kind, width } - } - _ => return Err(Error::UnexpectedDistanceArgument(ty_arg)), - }; + self.put_expression(arguments[0], function, module)?; write!(self.out, ", ")?; self.put_expression(arguments[1], function, module)?; write!(self.out, ")")?; - Ok(BorrowType::Owned(result)) } "length" => { write!(self.out, "length(")?; - let ty_arg = self.put_expression(arguments[0], function, module)?; - let result = match *ty_arg.borrow() { - crate::TypeInner::Vector { kind, width, .. } => { - crate::TypeInner::Scalar { kind, width } - } - _ => return Err(Error::UnexpectedDistanceArgument(ty_arg)), - }; + self.put_expression(arguments[0], function, module)?; write!(self.out, ")")?; - Ok(BorrowType::Owned(result)) } "mix" => { write!(self.out, "mix(")?; - let result = self.put_expression(arguments[0], function, module)?; + self.put_expression(arguments[0], function, module)?; write!(self.out, ", ")?; self.put_expression(arguments[1], function, module)?; write!(self.out, ", ")?; self.put_expression(arguments[2], function, module)?; write!(self.out, ")")?; - Ok(result) } - other => Err(Error::UnsupportedCall(other.to_owned())), + other => return Err(Error::UnsupportedCall(other.to_owned())), }, - ref other => Err(Error::UnsupportedExpression(other.clone())), + ref other => return Err(Error::UnsupportedExpression(other.clone())), } + Ok(()) } - fn put_constant<'w, 'a: 'w>( - &'w mut self, + fn put_constant( + &mut self, handle: Handle, - module: &'a crate::Module, - ) -> Result, Error<'a>> { + module: &crate::Module, + ) -> Result<(), Error> { let constant = &module.constants[handle]; let ty = &module.types[constant.ty]; @@ -768,17 +679,17 @@ impl Writer { } } - Ok(BorrowType::Borrowed(&ty.inner)) + Ok(()) } - fn put_statement<'w, 'a: 'w>( - &'w mut self, + fn put_statement( + &mut self, level: Level, statement: &crate::Statement, function: &crate::Function, has_output: bool, - module: &'a crate::Module, - ) -> Result<(), Error<'a>> { + module: &crate::Module, + ) -> Result<(), Error> { log::trace!("statement[{}] {:?}", level.0, statement); match *statement { crate::Statement::Empty => {} @@ -847,11 +758,7 @@ impl Writer { Ok(()) } - pub fn write<'w, 'a: 'w>( - &'w mut self, - module: &'a crate::Module, - options: Options, - ) -> Result<(), Error<'a>> { + pub fn write(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; writeln!(self.out, "using namespace metal;")?; @@ -865,7 +772,7 @@ impl Writer { Ok(()) } - fn write_type_defs<'a>(&mut self, module: &'a crate::Module) -> Result<(), Error<'a>> { + fn write_type_defs<'a>(&mut self, module: &'a crate::Module) -> Result<(), Error> { for (handle, ty) in module.types.iter() { let name = ty.name.or_index(handle); match ty.inner { @@ -1002,12 +909,20 @@ impl Writer { Ok(()) } - fn write_functions<'w, 'a: 'w>( - &'w mut self, - module: &'a crate::Module, - options: Options, - ) -> Result<(), Error<'a>> { + fn write_functions(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { for (fun_handle, fun) in module.functions.iter() { + self.typifier.resolve_all( + &fun.expressions, + &module.types, + &ResolveContext { + constants: &module.constants, + global_vars: &module.global_variables, + local_vars: &fun.local_variables, + functions: &module.functions, + parameter_types: &fun.parameter_types, + }, + )?; + let fun_name = fun.name.or_index(fun_handle); // find the entry point(s) and inputs/outputs let mut shader_stage = None; @@ -1251,8 +1166,11 @@ impl Writer { } } -pub fn write_string<'a>(module: &'a crate::Module, options: Options) -> Result> { - let mut w = Writer { out: String::new() }; +pub fn write_string(module: &crate::Module, options: Options) -> Result { + let mut w = Writer { + out: String::new(), + typifier: Typifier::new(), + }; w.write(module, options)?; Ok(w.out) } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 793d50043..c3f10ee77 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -248,9 +248,8 @@ impl Typifier { } ref other => panic!("Unexpected argument {:?}", other), }, - "normalize" | "fclamp" | "max" | "reflect" | "pow" | "clamp" | "mix" => { - self.resolutions[arguments[0].index()].clone() - } + "atan2" | "cos" | "sin" | "normalize" | "max" | "reflect" | "pow" | "clamp" + | "fclamp" | "mix" => self.resolutions[arguments[0].index()].clone(), _ => return Err(ResolveError::FunctionNotDefined { name: name.clone() }), }, crate::Expression::Call { From e99c71516094bd7f9c76a9bae62adc43535e6163 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 14 Sep 2020 14:09:35 -0400 Subject: [PATCH 0201/2212] glsl: use typifier in the backend --- src/back/glsl.rs | 571 ++++++++++++++++------------------------------- src/back/mod.rs | 23 -- 2 files changed, 194 insertions(+), 400 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index ed8f3feb0..c3003dcca 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,6 +1,5 @@ -use super::BorrowType; use crate::{ - proc::{Interface, Visitor}, + proc::{Interface, ResolveContext, ResolveError, Typifier, Visitor}, Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageClass, Interpolation, IntrinsicFunction, LocalVariable, MemberOrigin, Module, ScalarKind, ShaderStage, Statement, @@ -16,6 +15,7 @@ use std::{ pub enum Error { FormatError(FmtError), IoError(IoError), + Type(ResolveError), Custom(String), } @@ -31,11 +31,18 @@ impl From for Error { } } +impl From for Error { + fn from(err: ResolveError) -> Self { + Error::Type(err) + } +} + impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::FormatError(err) => write!(f, "Formatting error {}", err), Error::IoError(err) => write!(f, "Io error: {}", err), + Error::Type(err) => write!(f, "Type error: {:?}", err), Error::Custom(err) => write!(f, "{}", err), } } @@ -428,15 +435,27 @@ pub fn write<'a>( } writeln!(out)?; + let mut typifier = Typifier::new(); for (handle, name) in functions.iter() { let func = &module.functions[*handle]; + typifier.resolve_all( + &func.expressions, + &module.types, + &ResolveContext { + constants: &module.constants, + global_vars: &module.global_variables, + local_vars: &func.local_variables, + functions: &module.functions, + parameter_types: &func.parameter_types, + }, + )?; let args: FastHashMap<_, _> = func .parameter_types .iter() .enumerate() - .map(|(pos, ty)| (pos as u32, (namer(None), *ty))) + .map(|(pos, _ty)| (pos as u32, namer(None))) .collect(); writeln!( @@ -448,8 +467,10 @@ pub fn write<'a>( .as_deref() .unwrap_or("void"), name, - args.values() - .map::, _>(|(name, ty)| { + func.parameter_types + .iter() + .zip(args.values()) + .map::, _>(|(ty, name)| { let ty = write_type(*ty, &module.types, &structs, None, features)?; Ok(format!("{} {}", ty, name)) @@ -481,19 +502,19 @@ pub fn write<'a>( writeln!(out)?; - let mut builder = StatementBuilder { + let builder = StatementBuilder { functions: &functions, globals: &globals_lookup, locals_lookup: &locals, structs: &structs, args: &args, expressions: &func.expressions, - locals: &func.local_variables, features, + typifier: &typifier, }; for sta in func.body.iter() { - writeln!(out, "{}", write_statement(sta, module, &mut builder, 1)?)?; + writeln!(out, "{}", write_statement(sta, module, &builder, 1)?)?; } writeln!(out, "}}")?; @@ -503,20 +524,20 @@ pub fn write<'a>( } struct StatementBuilder<'a> { - pub functions: &'a FastHashMap, String>, - pub globals: &'a FastHashMap, String>, - pub locals_lookup: &'a FastHashMap, String>, - pub structs: &'a FastHashMap, String>, - pub args: &'a FastHashMap)>, - pub expressions: &'a Arena, - pub locals: &'a Arena, - pub features: SupportedFeatures, + functions: &'a FastHashMap, String>, + globals: &'a FastHashMap, String>, + locals_lookup: &'a FastHashMap, String>, + structs: &'a FastHashMap, String>, + args: &'a FastHashMap, + expressions: &'a Arena, + features: SupportedFeatures, + typifier: &'a Typifier, } fn write_statement<'a, 'b>( sta: &Statement, module: &'a Module, - builder: &'b mut StatementBuilder<'a>, + builder: &'b StatementBuilder<'a>, indent: usize, ) -> Result { Ok(match sta { @@ -537,7 +558,7 @@ fn write_statement<'a, 'b>( &mut out, "{}if({}) {{", "\t".repeat(indent), - write_expression(&builder.expressions[*condition], module, builder)?.0 + write_expression(&builder.expressions[*condition], module, builder)? )?; for sta in accept { @@ -574,7 +595,7 @@ fn write_statement<'a, 'b>( &mut out, "{}switch({}) {{", "\t".repeat(indent), - write_expression(&builder.expressions[*selector], module, builder)?.0 + write_expression(&builder.expressions[*selector], module, builder)? )?; for (label, (block, fallthrough)) in cases { @@ -634,7 +655,7 @@ fn write_statement<'a, 'b>( if let Some(expr) = value { format!( "return {};", - write_expression(&builder.expressions[*expr], module, builder)?.0 + write_expression(&builder.expressions[*expr], module, builder)? ) } else { String::from("return;") @@ -644,8 +665,8 @@ fn write_statement<'a, 'b>( Statement::Store { pointer, value } => format!( "{}{} = {};", "\t".repeat(indent), - write_expression(&builder.expressions[*pointer], module, builder)?.0, - write_expression(&builder.expressions[*value], module, builder)?.0 + write_expression(&builder.expressions[*pointer], module, builder)?, + write_expression(&builder.expressions[*value], module, builder)? ), }) } @@ -653,65 +674,26 @@ fn write_statement<'a, 'b>( fn write_expression<'a, 'b>( expr: &Expression, module: &'a Module, - builder: &'b mut StatementBuilder<'a>, -) -> Result<(Cow<'a, str>, BorrowType<'a>), Error> { + builder: &'b StatementBuilder<'a>, +) -> Result, Error> { Ok(match *expr { Expression::Access { base, index } => { - let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; - - let inner = match *ty.borrow() { - TypeInner::Vector { kind, width, .. } => { - BorrowType::Owned(TypeInner::Scalar { kind, width }) - } - TypeInner::Matrix { - kind, - width, - columns, - .. - } => BorrowType::Owned(TypeInner::Vector { - kind, - width, - size: columns, - }), - TypeInner::Array { base, .. } => module.borrow_type(base), - _ => return Err(Error::Custom(format!("Cannot dynamically index {:?}", ty))), - }; - - ( - Cow::Owned(format!( - "{}[{}]", - base_expr, - write_expression(&builder.expressions[index], module, builder)?.0 - )), - inner, - ) + let base_expr = write_expression(&builder.expressions[base], module, builder)?; + Cow::Owned(format!( + "{}[{}]", + base_expr, + write_expression(&builder.expressions[index], module, builder)? + )) } Expression::AccessIndex { base, index } => { - let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; + let base_expr = write_expression(&builder.expressions[base], module, builder)?; - match *ty.borrow() { - TypeInner::Vector { kind, width, .. } => ( - Cow::Owned(format!("{}[{}]", base_expr, index)), - BorrowType::Owned(TypeInner::Scalar { kind, width }), - ), - TypeInner::Matrix { - kind, - width, - columns, - .. - } => ( - Cow::Owned(format!("{}[{}]", base_expr, index)), - BorrowType::Owned(TypeInner::Vector { - kind, - width, - size: columns, - }), - ), - TypeInner::Array { base, .. } => ( - Cow::Owned(format!("{}[{}]", base_expr, index)), - module.borrow_type(base), - ), - TypeInner::Struct { ref members } => ( + match *builder.typifier.get(base, &module.types) { + TypeInner::Vector { .. } => Cow::Owned(format!("{}[{}]", base_expr, index)), + TypeInner::Matrix { .. } | TypeInner::Array { .. } => { + Cow::Owned(format!("{}[{}]", base_expr, index)) + } + TypeInner::Struct { ref members } => { if let MemberOrigin::BuiltIn(builtin) = members[index as usize].origin { Cow::Borrowed(builtin_to_glsl(builtin)) } else { @@ -724,21 +706,17 @@ fn write_expression<'a, 'b>( .filter(|s| is_valid_ident(s)) .unwrap_or(&format!("_{}", index)) )) - }, - module.borrow_type(members[index as usize].ty), - ), - _ => return Err(Error::Custom(format!("Cannot index {:?}", ty))), + } + } + ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), } } - Expression::Constant(constant) => ( - Cow::Owned(write_constant( - &module.constants[constant], - module, - builder, - builder.features, - )?), - module.borrow_type(module.constants[constant].ty), - ), + Expression::Constant(constant) => Cow::Owned(write_constant( + &module.constants[constant], + module, + builder, + builder.features, + )?), Expression::Compose { ty, ref components } => { let constructor = match module.types[ty].inner { TypeInner::Vector { size, kind, width } => format!( @@ -770,37 +748,25 @@ fn write_expression<'a, 'b>( } }; - ( - Cow::Owned(format!( - "{}({})", - constructor, - components - .iter() - .map::, _>(|arg| Ok(write_expression( - &builder.expressions[*arg], - module, - builder - )? - .0)) - .collect::, _>>()? - .join(","), - )), - module.borrow_type(ty), - ) + Cow::Owned(format!( + "{}({})", + constructor, + components + .iter() + .map::, _>(|arg| Ok(write_expression( + &builder.expressions[*arg], + module, + builder + )?)) + .collect::, _>>()? + .join(","), + )) } - Expression::FunctionParameter(pos) => { - let (arg, ty) = builder.args.get(&pos).unwrap(); - - (Cow::Borrowed(arg), module.borrow_type(*ty)) + Expression::FunctionParameter(pos) => Cow::Borrowed(builder.args.get(&pos).unwrap()), + Expression::GlobalVariable(handle) => Cow::Borrowed(builder.globals.get(&handle).unwrap()), + Expression::LocalVariable(handle) => { + Cow::Borrowed(builder.locals_lookup.get(&handle).unwrap()) } - Expression::GlobalVariable(handle) => ( - Cow::Borrowed(builder.globals.get(&handle).unwrap()), - module.borrow_type(module.global_variables[handle].ty), - ), - Expression::LocalVariable(handle) => ( - Cow::Borrowed(builder.locals_lookup.get(&handle).unwrap()), - module.borrow_type(builder.locals[handle].ty), - ), Expression::Load { pointer } => { write_expression(&builder.expressions[pointer], module, builder)? } @@ -811,102 +777,68 @@ fn write_expression<'a, 'b>( level, depth_ref, } => { - let (image_expr, image_ty) = - write_expression(&builder.expressions[image], module, builder)?; - let (_, sampler_ty) = write_expression(&builder.expressions[sampler], module, builder)?; - let (coordinate_expr, coordinate_ty) = + let image_expr = write_expression(&builder.expressions[image], module, builder)?; + write_expression(&builder.expressions[sampler], module, builder)?; + let coordinate_expr = write_expression(&builder.expressions[coordinate], module, builder)?; - let kind = match *image_ty.borrow() { - TypeInner::Image { kind, .. } => kind, - _ => return Err(Error::Custom(format!("Cannot sample {:?}", image_ty))), - }; - - let shadow = match *sampler_ty.borrow() { - TypeInner::Sampler { comparison } => comparison, - _ => { - return Err(Error::Custom(format!( - "Cannot have a sampler of {:?}", - sampler_ty - ))) - } - }; - let size = match *coordinate_ty.borrow() { + let size = match *builder.typifier.get(coordinate, &module.types) { TypeInner::Vector { size, .. } => size, - _ => { + ref other => { return Err(Error::Custom(format!( "Cannot sample with coordinates of type {:?}", - coordinate_ty + other ))) } }; - let coordinate = if let Some(depth_ref) = depth_ref { + let coordinate_expr = if let Some(depth_ref) = depth_ref { Cow::Owned(format!( "vec{}({},{})", size as u8 + 1, coordinate_expr, - write_expression(&builder.expressions[depth_ref], module, builder)?.0 + write_expression(&builder.expressions[depth_ref], module, builder)? )) } else { coordinate_expr }; //TODO: handle MS - let expr = match level { - crate::SampleLevel::Auto => format!("texture({},{})", image_expr, coordinate), + Cow::Owned(match level { + crate::SampleLevel::Auto => format!("texture({},{})", image_expr, coordinate_expr), crate::SampleLevel::Exact(expr) => { - let (level_expr, _) = - write_expression(&builder.expressions[expr], module, builder)?; - format!("textureLod({}, {}, {})", image_expr, coordinate, level_expr) + let level_expr = write_expression(&builder.expressions[expr], module, builder)?; + format!( + "textureLod({}, {}, {})", + image_expr, coordinate_expr, level_expr + ) } crate::SampleLevel::Bias(bias) => { - let (bias_expr, _) = - write_expression(&builder.expressions[bias], module, builder)?; - format!("texture({},{},{})", image_expr, coordinate, bias_expr) + let bias_expr = write_expression(&builder.expressions[bias], module, builder)?; + format!("texture({},{},{})", image_expr, coordinate_expr, bias_expr) } - }; - - let width = 4; - let ty = if shadow { - BorrowType::Owned(TypeInner::Scalar { kind, width }) - } else { - BorrowType::Owned(TypeInner::Vector { kind, width, size }) - }; - - (Cow::Owned(expr), ty) + }) } Expression::ImageLoad { image, coordinate, index, } => { - let (image_expr, image_ty) = - write_expression(&builder.expressions[image], module, builder)?; - let (coordinate_expr, coordinate_ty) = + let image_expr = write_expression(&builder.expressions[image], module, builder)?; + let coordinate_expr = write_expression(&builder.expressions[coordinate], module, builder)?; - let (kind, dim, arrayed, class) = match *image_ty.borrow() { + let (kind, dim, arrayed, class) = match *builder.typifier.get(image, &module.types) { TypeInner::Image { kind, dim, arrayed, class, } => (kind, dim, arrayed, class), - _ => return Err(Error::Custom(format!("Cannot load {:?}", image_ty))), + ref other => return Err(Error::Custom(format!("Cannot load {:?}", other))), }; - let size = match *coordinate_ty.borrow() { - TypeInner::Vector { size, .. } => size, - _ => { - return Err(Error::Custom(format!( - "Cannot sample with coordinates of type {:?}", - coordinate_ty - ))) - } - }; - - let expr = match class { + Cow::Owned(match class { ImageClass::Sampled | ImageClass::Multisampled => { let ms = match class { crate::ImageClass::Multisampled => true, @@ -926,7 +858,7 @@ fn write_expression<'a, 'b>( if !ms { format!("texelFetch({},{})", sampler_constructor, coordinate_expr) } else { - let (index_expr, _) = + let index_expr = write_expression(&builder.expressions[index], module, builder)?; format!( @@ -937,52 +869,41 @@ fn write_expression<'a, 'b>( } ImageClass::Storage(_) => format!("imageLoad({},{})", image_expr, coordinate_expr), ImageClass::Depth => todo!(), - }; - - let width = 4; - ( - Cow::Owned(expr), - BorrowType::Owned(TypeInner::Vector { kind, width, size }), - ) + }) } Expression::Unary { op, expr } => { - let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; + let base_expr = write_expression(&builder.expressions[expr], module, builder)?; - ( - Cow::Owned(format!( - "({} {})", - match op { - UnaryOperator::Negate => "-", - UnaryOperator::Not => match *ty.borrow() { - TypeInner::Scalar { - kind: ScalarKind::Sint, - .. - } => "~", - TypeInner::Scalar { - kind: ScalarKind::Uint, - .. - } => "~", - TypeInner::Scalar { - kind: ScalarKind::Bool, - .. - } => "!", - _ => - return Err(Error::Custom(format!( - "Cannot apply not to type {:?}", - ty - ))), - }, + Cow::Owned(format!( + "({} {})", + match op { + UnaryOperator::Negate => "-", + UnaryOperator::Not => match *builder.typifier.get(expr, &module.types) { + TypeInner::Scalar { + kind: ScalarKind::Sint, + .. + } => "~", + TypeInner::Scalar { + kind: ScalarKind::Uint, + .. + } => "~", + TypeInner::Scalar { + kind: ScalarKind::Bool, + .. + } => "!", + ref other => + return Err(Error::Custom(format!( + "Cannot apply not to type {:?}", + other + ))), }, - expr - )), - ty, - ) + }, + base_expr + )) } Expression::Binary { op, left, right } => { - let (left_expr, left_ty) = - write_expression(&builder.expressions[left], module, builder)?; - let (right_expr, right_ty) = - write_expression(&builder.expressions[right], module, builder)?; + let left_expr = write_expression(&builder.expressions[left], module, builder)?; + let right_expr = write_expression(&builder.expressions[right], module, builder)?; let op_str = match op { BinaryOperator::Add => "+", @@ -1006,149 +927,57 @@ fn write_expression<'a, 'b>( BinaryOperator::ShiftRightArithmetic => ">>", }; - let ty = match op { - BinaryOperator::Add - | BinaryOperator::Subtract - | BinaryOperator::Multiply - | BinaryOperator::Divide - | BinaryOperator::Modulo - | BinaryOperator::And - | BinaryOperator::ExclusiveOr - | BinaryOperator::InclusiveOr - | BinaryOperator::LogicalAnd - | BinaryOperator::LogicalOr - | BinaryOperator::ShiftLeftLogical - | BinaryOperator::ShiftRightLogical - | BinaryOperator::ShiftRightArithmetic => { - match (left_ty.borrow(), right_ty.borrow()) { - (TypeInner::Scalar { .. }, TypeInner::Scalar { .. }) => left_ty, - (TypeInner::Scalar { .. }, TypeInner::Vector { .. }) => right_ty, - (TypeInner::Scalar { .. }, TypeInner::Matrix { .. }) => right_ty, - (TypeInner::Vector { .. }, TypeInner::Scalar { .. }) => left_ty, - (TypeInner::Vector { .. }, TypeInner::Vector { .. }) => left_ty, - (TypeInner::Vector { .. }, TypeInner::Matrix { .. }) => left_ty, - (TypeInner::Matrix { .. }, TypeInner::Scalar { .. }) => left_ty, - (TypeInner::Matrix { .. }, TypeInner::Vector { .. }) => right_ty, - (TypeInner::Matrix { .. }, TypeInner::Matrix { .. }) => left_ty, - _ => { - return Err(Error::Custom(format!( - "Cannot apply '{}' to {} and {}", - op_str, left_expr, right_expr - ))) - } - } - } - BinaryOperator::Equal - | BinaryOperator::NotEqual - | BinaryOperator::Less - | BinaryOperator::LessEqual - | BinaryOperator::Greater - | BinaryOperator::GreaterEqual => BorrowType::Owned(TypeInner::Scalar { - kind: ScalarKind::Bool, - width: 1, - }), - }; - - ( - Cow::Owned(format!("({} {} {})", left_expr, op_str, right_expr)), - ty, - ) + Cow::Owned(format!("({} {} {})", left_expr, op_str, right_expr)) } Expression::Intrinsic { fun, argument } => { - let (expr, ty) = write_expression(&builder.expressions[argument], module, builder)?; + let expr = write_expression(&builder.expressions[argument], module, builder)?; - ( - Cow::Owned(format!( - "{:?}({})", - match fun { - IntrinsicFunction::IsFinite => "!isinf", - IntrinsicFunction::IsInf => "isinf", - IntrinsicFunction::IsNan => "isnan", - IntrinsicFunction::IsNormal => "!isnan", - IntrinsicFunction::All => "all", - IntrinsicFunction::Any => "any", - }, - expr - )), - ty, - ) + Cow::Owned(format!( + "{:?}({})", + match fun { + IntrinsicFunction::IsFinite => "!isinf", + IntrinsicFunction::IsInf => "isinf", + IntrinsicFunction::IsNan => "isnan", + IntrinsicFunction::IsNormal => "!isnan", + IntrinsicFunction::All => "all", + IntrinsicFunction::Any => "any", + }, + expr + )) } Expression::Transpose(matrix) => { - let (matrix_expr, matrix_ty) = - write_expression(&builder.expressions[matrix], module, builder)?; - - let ty = match *matrix_ty.borrow() { - TypeInner::Matrix { - columns, - rows, - kind, - width, - } => BorrowType::Owned(TypeInner::Matrix { - columns: rows, - rows: columns, - kind, - width, - }), - _ => { - return Err(Error::Custom(format!( - "Cannot apply transpose to {}", - matrix_expr - ))) - } - }; - - (Cow::Owned(format!("transpose({})", matrix_expr)), ty) + let matrix_expr = write_expression(&builder.expressions[matrix], module, builder)?; + Cow::Owned(format!("transpose({})", matrix_expr)) } Expression::DotProduct(left, right) => { - let (left_expr, left_ty) = - write_expression(&builder.expressions[left], module, builder)?; - let (right_expr, _) = write_expression(&builder.expressions[right], module, builder)?; - - let ty = match *left_ty.borrow() { - TypeInner::Vector { kind, width, .. } => { - BorrowType::Owned(TypeInner::Scalar { kind, width }) - } - _ => { - return Err(Error::Custom(format!( - "Cannot apply dot product to {}", - left_expr - ))) - } - }; - - (Cow::Owned(format!("dot({},{})", left_expr, right_expr)), ty) + let left_expr = write_expression(&builder.expressions[left], module, builder)?; + let right_expr = write_expression(&builder.expressions[right], module, builder)?; + Cow::Owned(format!("dot({},{})", left_expr, right_expr)) } Expression::CrossProduct(left, right) => { - let (left_expr, left_ty) = - write_expression(&builder.expressions[left], module, builder)?; - let (right_expr, _) = write_expression(&builder.expressions[right], module, builder)?; - - ( - Cow::Owned(format!("cross({},{})", left_expr, right_expr)), - left_ty, - ) + let left_expr = write_expression(&builder.expressions[left], module, builder)?; + let right_expr = write_expression(&builder.expressions[right], module, builder)?; + Cow::Owned(format!("cross({},{})", left_expr, right_expr)) } Expression::As { expr, kind, convert, } => { - let (value_expr, value_ty) = - write_expression(&builder.expressions[expr], module, builder)?; + let value_expr = write_expression(&builder.expressions[expr], module, builder)?; - let (source_kind, ty_expr, out_ty) = match *value_ty.borrow() { + let (source_kind, ty_expr) = match *builder.typifier.get(expr, &module.types) { TypeInner::Scalar { width, kind } => ( kind, Cow::Borrowed(map_scalar(kind, width, builder.features)?.full), - BorrowType::Owned(TypeInner::Scalar { kind, width }), ), TypeInner::Vector { width, kind, size } => ( kind, Cow::Owned(format!( - "{}vec", - map_scalar(kind, width, builder.features)?.prefix + "{}vec{}", + map_scalar(kind, width, builder.features)?.prefix, + size as u32, )), - BorrowType::Owned(TypeInner::Vector { kind, width, size }), ), _ => return Err(Error::Custom(format!("Cannot convert {}", value_expr))), }; @@ -1170,60 +999,48 @@ fn write_expression<'a, 'b>( }) }; - (Cow::Owned(format!("{}({})", op, value_expr)), out_ty) + Cow::Owned(format!("{}({})", op, value_expr)) } Expression::Derivative { axis, expr } => { - let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; + let expr = write_expression(&builder.expressions[expr], module, builder)?; - ( - Cow::Owned(format!( - "{}({})", - match axis { - DerivativeAxis::X => "dFdx", - DerivativeAxis::Y => "dFdy", - DerivativeAxis::Width => "fwidth", - }, - expr - )), - ty, - ) + Cow::Owned(format!( + "{}({})", + match axis { + DerivativeAxis::X => "dFdx", + DerivativeAxis::Y => "dFdy", + DerivativeAxis::Width => "fwidth", + }, + expr + )) } Expression::Call { ref origin, ref arguments, } => { - let ty = match *origin { - FunctionOrigin::Local(function) => module.functions[function] - .return_type - .map(|ty| module.borrow_type(ty)) - .unwrap_or(BorrowType::Owned( - TypeInner::Sampler { comparison: false }, /*Dummy type*/ - )), + match *origin { + FunctionOrigin::Local(_) => {} FunctionOrigin::External(_) => { - write_expression(&builder.expressions[arguments[0]], module, builder)?.1 + write_expression(&builder.expressions[arguments[0]], module, builder)?; } }; - ( - Cow::Owned(format!( - "{}({})", - match *origin { - FunctionOrigin::External(ref name) => name, - FunctionOrigin::Local(handle) => builder.functions.get(&handle).unwrap(), - }, - arguments - .iter() - .map::, _>(|arg| Ok(write_expression( - &builder.expressions[*arg], - module, - builder - )? - .0)) - .collect::, _>>()? - .join(","), - )), - ty, - ) + Cow::Owned(format!( + "{}({})", + match *origin { + FunctionOrigin::External(ref name) => name, + FunctionOrigin::Local(handle) => builder.functions.get(&handle).unwrap(), + }, + arguments + .iter() + .map(|arg| Ok(write_expression( + &builder.expressions[*arg], + module, + builder + )?)) + .collect::, Error>>()? + .join(","), + )) } }) } diff --git a/src/back/mod.rs b/src/back/mod.rs index 7aceda745..fc601cd9f 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -5,26 +5,3 @@ pub mod glsl; pub mod msl; #[cfg(feature = "spirv-out")] pub mod spv; - -#[derive(Debug)] -pub enum MaybeOwned<'a, T: 'a> { - Borrowed(&'a T), - Owned(T), -} - -impl MaybeOwned<'_, T> { - fn borrow(&self) -> &T { - match *self { - MaybeOwned::Borrowed(inner) => inner, - MaybeOwned::Owned(ref inner) => inner, - } - } -} - -pub type BorrowType<'a> = MaybeOwned<'a, crate::TypeInner>; - -impl crate::Module { - fn borrow_type(&self, handle: crate::Handle) -> BorrowType { - MaybeOwned::Borrowed(&self.types[handle].inner) - } -} From d6cc17f0519d4b3e09f46f8428927c81690440ed Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 14 Sep 2020 10:27:05 -0400 Subject: [PATCH 0202/2212] Refactor feature names --- Cargo.toml | 5 +++-- examples/convert.rs | 14 +++++++++++--- src/back/mod.rs | 3 ++- src/front/mod.rs | 7 +++---- tests/convert.rs | 9 ++++++--- 5 files changed, 25 insertions(+), 13 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3c60739c3..803c506f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,10 +25,11 @@ default = [] glsl-in = ["pomelo"] glsl-validate = [] glsl-out = [] +msl-out = [] serialize = ["serde"] deserialize = ["serde"] -spirv-in = ["petgraph", "spirv"] -spirv-out = ["spirv"] +spv-in = ["petgraph", "spirv"] +spv-out = ["spirv"] wgsl-in = [] [dev-dependencies] diff --git a/examples/convert.rs b/examples/convert.rs index 76f5a156e..3b219540c 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -35,7 +35,7 @@ fn main() { .to_str() .unwrap() { - #[cfg(feature = "spirv-in")] + #[cfg(feature = "spv-in")] "spv" => { let input = fs::read(&args[1]).unwrap(); naga::front::spv::parse_u8_slice(&input).unwrap() @@ -80,7 +80,13 @@ fn main() { let mut input = fs::File::open(&args[1]).unwrap(); ron::de::from_reader(&mut input).unwrap() } - other => panic!("Unknown input extension: {}", other), + other => { + if true { + // prevent "unreachable_code" warnings + panic!("Unknown input extension: {}", other); + } + naga::Module::generate_empty() + } }; if args.len() <= 2 { @@ -100,6 +106,7 @@ fn main() { .to_str() .unwrap() { + #[cfg(feature = "msl-out")] "metal" => { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); @@ -123,7 +130,7 @@ fn main() { let msl = msl::write_string(&module, options).unwrap(); fs::write(&args[2], msl).unwrap(); } - #[cfg(feature = "spirv-out")] + #[cfg(feature = "spv-out")] "spv" => { use naga::back::spv; @@ -189,6 +196,7 @@ fn main() { fs::write(&args[2], output).unwrap(); } other => { + let _ = params; panic!("Unknown output extension: {}", other); } } diff --git a/src/back/mod.rs b/src/back/mod.rs index fc601cd9f..bc96dd349 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -2,6 +2,7 @@ #[cfg(feature = "glsl-out")] pub mod glsl; +#[cfg(feature = "msl-out")] pub mod msl; -#[cfg(feature = "spirv-out")] +#[cfg(feature = "spv-out")] pub mod spv; diff --git a/src/front/mod.rs b/src/front/mod.rs index ec7738963..3e7464577 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -2,7 +2,7 @@ #[cfg(feature = "glsl-in")] pub mod glsl; -#[cfg(feature = "spirv-in")] +#[cfg(feature = "spv-in")] pub mod spv; #[cfg(feature = "wgsl-in")] pub mod wgsl; @@ -11,9 +11,8 @@ use crate::arena::Arena; pub const GENERATOR: u32 = 0; -#[allow(dead_code)] impl crate::Module { - fn from_header(header: crate::Header) -> Self { + pub fn from_header(header: crate::Header) -> Self { crate::Module { header, types: Arena::new(), @@ -24,7 +23,7 @@ impl crate::Module { } } - fn generate_empty() -> Self { + pub fn generate_empty() -> Self { Self::from_header(crate::Header { version: (1, 0, 0), generator: GENERATOR, diff --git a/tests/convert.rs b/tests/convert.rs index a95d4affd..d6a1243c3 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -1,3 +1,4 @@ +#[allow(dead_code)] fn load_test_data(name: &str) -> String { let path = format!("{}/test-data/{}", env!("CARGO_MANIFEST_DIR"), name); std::fs::read_to_string(path).unwrap() @@ -9,7 +10,7 @@ fn load_wgsl(name: &str) -> naga::Module { naga::front::wgsl::parse_str(&input).unwrap() } -#[cfg(feature = "spirv-in")] +#[cfg(feature = "spv-in")] fn load_spv(name: &str) -> naga::Module { let path = format!("{}/test-data/spv/{}", env!("CARGO_MANIFEST_DIR"), name); let input = std::fs::read(path).unwrap(); @@ -27,6 +28,7 @@ fn load_glsl(name: &str, entry: &str, stage: naga::ShaderStage) -> naga::Module fn convert_quad() { let module = load_wgsl("quad.wgsl"); naga::proc::Validator::new().validate(&module).unwrap(); + #[cfg(feature = "msl-out")] { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); @@ -60,6 +62,7 @@ fn convert_quad() { fn convert_boids() { let module = load_wgsl("boids.wgsl"); naga::proc::Validator::new().validate(&module).unwrap(); + #[cfg(feature = "msl-out")] { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); @@ -97,7 +100,7 @@ fn convert_boids() { } } -#[cfg(feature = "spirv-in")] +#[cfg(feature = "spv-in")] #[test] fn convert_cube() { let mut validator = naga::proc::Validator::new(); @@ -105,7 +108,7 @@ fn convert_cube() { validator.validate(&vs).unwrap(); let fs = load_spv("cube.frag.spv"); validator.validate(&fs).unwrap(); - + #[cfg(feature = "msl-out")] { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); From a561c7cacbb178f3a3fc6c985ef0dbb85298ee94 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 14 Sep 2020 14:25:03 -0400 Subject: [PATCH 0203/2212] validator: try resolving the types --- src/proc/typifier.rs | 1 + src/proc/validator.rs | 31 +++++++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index c3f10ee77..787c8adac 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -37,6 +37,7 @@ impl Clone for Resolution { } } +#[derive(Debug)] pub struct Typifier { resolutions: Vec, } diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 364d7fd10..7d26f1441 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -1,7 +1,12 @@ +use super::typifier::{ResolveContext, ResolveError, Typifier}; use crate::arena::Handle; #[derive(Debug)] -pub struct Validator {} +pub struct Validator { + //Note: this is a bit tricky: some of the front-ends as well as backends + // already have to use the typifier, so the work here is redundant in a way. + typifier: Typifier, +} #[derive(Clone, Debug, thiserror::Error)] pub enum ValidationError { @@ -9,6 +14,8 @@ pub enum ValidationError { InvalidTypeWidth(crate::ScalarKind, crate::Bytes), #[error("The type handle can not be resolved")] UnresolvedType(Handle), + #[error("Expression type can't be resolved")] + Resolve(Handle, ResolveError), #[error("There are instructions after `return`/`break`/`continue`")] InvalidControlFlowExitTail, } @@ -16,11 +23,14 @@ pub enum ValidationError { impl Validator { /// Construct a new validator instance. pub fn new() -> Self { - Validator {} + Validator { + typifier: Typifier::new(), + } } /// Check the given module to be valid. pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { + // check the types for (handle, ty) in module.types.iter() { use crate::TypeInner as Ti; match ty.inner { @@ -58,6 +68,23 @@ impl Validator { } } + // check the type resolution of expressions + for (fun_handle, fun) in module.functions.iter() { + let resolve_ctx = ResolveContext { + constants: &module.constants, + global_vars: &module.global_variables, + local_vars: &fun.local_variables, + functions: &module.functions, + parameter_types: &fun.parameter_types, + }; + if let Err(e) = self + .typifier + .resolve_all(&fun.expressions, &module.types, &resolve_ctx) + { + return Err(ValidationError::Resolve(fun_handle, e)); + } + } + Ok(()) } } From bcd3db2dad100ada25b331ac010f2aab99cd89e3 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 15 Sep 2020 16:05:56 +0000 Subject: [PATCH 0204/2212] [glsl-in] Add unifroms and structs --- src/front/glsl/lex.rs | 1 + src/front/glsl/parser.rs | 175 +++++++++++++++++++++++++++++++-------- 2 files changed, 140 insertions(+), 36 deletions(-) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 7e44a7901..6502bbb5a 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -113,6 +113,7 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { "layout" => (Some(Token::Layout(meta)), rest), "in" => (Some(Token::In(meta)), rest), "out" => (Some(Token::Out(meta)), rest), + "uniform" => (Some(Token::Uniform(meta)), rest), "flat" => ( Some(Token::Interpolation((meta, crate::Interpolation::Flat))), rest, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index c9e1743ba..cf51514f0 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -6,8 +6,8 @@ pomelo! { %include { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, Expression, - Function, GlobalVariable, Handle, LocalVariable, ScalarKind, - Statement, StorageAccess, StorageClass, Type, TypeInner, + Function, GlobalVariable, Handle, LocalVariable, MemberOrigin, ScalarKind, + Statement, StorageAccess, StorageClass, StructMember, Type, TypeInner, Interpolation}; } %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; @@ -95,8 +95,8 @@ pomelo! { %type init_declarator_list VarDeclaration; %type single_declaration VarDeclaration; %type layout_qualifier Binding; - %type layout_qualifier_id_list Binding; - %type layout_qualifier_id Binding; + %type layout_qualifier_id_list Vec<(String, u32)>; + %type layout_qualifier_id (String, u32); %type type_qualifier Vec; %type single_type_qualifier TypeQualifier; %type storage_qualifier StorageClass; @@ -107,6 +107,11 @@ pomelo! { %type fully_specified_type (Vec, Option>); %type type_specifier Option>; %type type_specifier_nonarray Option; + %type struct_specifier Type; + %type struct_declaration_list Vec; + %type struct_declaration Vec; + %type struct_declarator_list Vec; + %type struct_declarator String; %type TypeName Type; @@ -454,6 +459,37 @@ pomelo! { idl } + declaration ::= type_qualifier(t) Identifier(i) LeftBrace + struct_declaration_list(sdl) RightBrace Semicolon { + VarDeclaration{ + type_qualifiers: t, + ids_initializers: vec![], + ty: extra.types.fetch_or_append(Type{ + name: Some(i.1), + inner: TypeInner::Struct { + members: sdl + } + }), + } + } + + declaration ::= type_qualifier(t) Identifier(i1) LeftBrace + struct_declaration_list(sdl) RightBrace Identifier(i2) Semicolon { + VarDeclaration{ + type_qualifiers: t, + ids_initializers: vec![(i2.1, None)], + ty: extra.types.fetch_or_append(Type{ + name: Some(i1.1), + inner: TypeInner::Struct { + members: sdl + } + }), + } + } + + // declaration ::= type_qualifier(t) Identifier(i1) LeftBrace + // struct_declaration_list RightBrace Identifier(i2) array_specifier Semicolon; + init_declarator_list ::= single_declaration; init_declarator_list ::= init_declarator_list(mut idl) Comma Identifier(i) { idl.ids_initializers.push((i.1, None)); @@ -503,22 +539,37 @@ pomelo! { (q,t) } + interpolation_qualifier ::= Interpolation((_, i)) { + i + } + layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen { + if let Some((_, loc)) = l.iter().find(|&q| q.0.as_str() == "location") { + Binding::Location(*loc) + } else if let Some((_, binding)) = l.iter().find(|&q| q.0.as_str() == "binding") { + let set = if let Some((_, set)) = l.iter().find(|&q| q.0.as_str() == "set") { + *set + } else { + 0 + }; + Binding::Descriptor{set, binding: *binding} + } else { + return Err(ErrorKind::NotImplemented("unsupported layout qualifier(s)")); + } + } + layout_qualifier_id_list ::= layout_qualifier_id(lqi) { + vec![lqi] + } + layout_qualifier_id_list ::= layout_qualifier_id_list(mut l) Comma layout_qualifier_id(lqi) { + l.push(lqi); l } - layout_qualifier_id_list ::= layout_qualifier_id; - layout_qualifier_id_list ::= layout_qualifier_id_list Comma layout_qualifier_id(l) { - //TODO: for now always pick last - l + layout_qualifier_id ::= Identifier(i) { + (i.1, 0) } - // layout_qualifier_id ::= Identifier; //TODO: handle full constant_expression instead of IntConstant layout_qualifier_id ::= Identifier(i) Equal IntConstant(ic) { - if i.1.as_str() == "location" { - Binding::Location(ic.1 as u32) - } else { - return Err(ErrorKind::NotImplemented("non location layout qualifier")); - } + (i.1, ic.1 as u32) } // layout_qualifier_id ::= Shared; @@ -555,10 +606,81 @@ pomelo! { storage_qualifier ::= Out { StorageClass::Output } - //TODO: other storage qualifiers - interpolation_qualifier ::= Interpolation((_, i)) { - i + // storage_qualifier ::= Centroid; + // storage_qualifier ::= Patch; + // storage_qualifier ::= Sample; + storage_qualifier ::= Uniform { + StorageClass::Uniform } + //TODO: other storage qualifiers + + type_specifier ::= type_specifier_nonarray(t) { + t.map(|t| { + let name = t.name.clone(); + let handle = extra.types.fetch_or_append(t); + if let Some(name) = name { + extra.lookup_type.insert(name, handle); + } + handle + }) + } + //TODO: array + + type_specifier_nonarray ::= Void { + None + } + type_specifier_nonarray ::= TypeName(t) { + Some(t.1) + }; + type_specifier_nonarray ::= struct_specifier(s) { + Some(s) + } + + // struct + struct_specifier ::= Struct Identifier(i) LeftBrace struct_declaration_list RightBrace { + Type{ + name: Some(i.1), + inner: TypeInner::Struct { + members: vec![] + } + } + } + //struct_specifier ::= Struct LeftBrace struct_declaration_list RightBrace; + + struct_declaration_list ::= struct_declaration(sd) { + sd + } + struct_declaration_list ::= struct_declaration_list(mut sdl) struct_declaration(sd) { + sdl.extend(sd); + sdl + } + + struct_declaration ::= type_specifier(t) struct_declarator_list(sdl) Semicolon { + if let Some(ty) = t { + sdl.iter().map(|name| StructMember{ + name: Some(name.clone()), + origin: MemberOrigin::Empty, + ty, + }).collect() + } else { + return Err(ErrorKind::SemanticError("Struct member can't be void")) + } + } + //struct_declaration ::= type_qualifier type_specifier struct_declarator_list Semicolon; + + struct_declarator_list ::= struct_declarator(sd) { + vec![sd] + } + struct_declarator_list ::= struct_declarator_list(mut sdl) Comma struct_declarator(sd) { + sdl.push(sd); + sdl + } + + struct_declarator ::= Identifier(i) { + i.1 + } + //struct_declarator ::= Identifier array_specifier; + initializer ::= assignment_expression; // initializer ::= LeftBrace initializer_list RightBrace; @@ -677,25 +799,6 @@ pomelo! { } } - // type - type_specifier ::= type_specifier_nonarray(t) { - t.map(|t| { - let name = t.name.clone(); - let handle = extra.types.fetch_or_append(t); - if let Some(name) = name { - extra.lookup_type.insert(name, handle); - } - handle - }) - } - - type_specifier_nonarray ::= Void { - None - } - type_specifier_nonarray ::= TypeName(t) { - Some(t.1) - }; - jump_statement ::= Continue Semicolon { Statement::Continue } From 74c4a3ce184d9bc378a03b48affc8c3fa074105a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 16 Sep 2020 00:48:37 -0400 Subject: [PATCH 0205/2212] Add ArrayLength expression --- src/back/glsl.rs | 4 ++++ src/lib.rs | 2 ++ src/proc/interface.rs | 3 +++ src/proc/typifier.rs | 4 ++++ 4 files changed, 13 insertions(+) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index c3003dcca..cbb8fd26a 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1042,6 +1042,10 @@ fn write_expression<'a, 'b>( .join(","), )) } + Expression::ArrayLength(expr) => { + let base = write_expression(&builder.expressions[expr], module, builder)?; + Cow::Owned(format!("uint({}.length())", base)) + } }) } diff --git a/src/lib.rs b/src/lib.rs index 2b65d8ac8..4cded46ca 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -635,6 +635,8 @@ pub enum Expression { origin: FunctionOrigin, arguments: Vec>, }, + /// Get dynamic array length. + ArrayLength(Handle), } /// A code block is just a vector of statements. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index ff4290c19..8e1f5666c 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -100,6 +100,9 @@ where self.traverse_expr(argument); } } + E::ArrayLength(expr) => { + self.traverse_expr(expr); + } } } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 787c8adac..461bfa1bb 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -262,6 +262,10 @@ impl Typifier { .ok_or(ResolveError::FunctionReturnsVoid)?; Resolution::Handle(ty) } + crate::Expression::ArrayLength(_) => Resolution::Value(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: 4, + }), }) } From 2ebaadaf0ca62e558ac027606f6f18c807308ee7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 17 Sep 2020 00:35:32 -0400 Subject: [PATCH 0206/2212] Refactor entry point IR --- examples/convert.rs | 34 +-- src/back/glsl.rs | 46 +--- src/back/msl.rs | 393 ++++++++++++++------------- src/back/spv/writer.rs | 221 +++++++-------- src/front/glsl/ast.rs | 18 +- src/front/glsl/mod.rs | 21 +- src/front/glsl/parser.rs | 54 ++-- src/front/glsl/parser_tests.rs | 2 +- src/front/glsl/variables.rs | 70 ++--- src/front/mod.rs | 2 +- src/front/spv/function.rs | 245 +++++++++-------- src/front/spv/mod.rs | 128 ++++----- src/front/wgsl/mod.rs | 127 +++++---- src/lib.rs | 32 +-- src/proc/interface.rs | 51 ++-- test-data/boids.param.ron | 6 +- test-data/boids.wgsl | 51 ++-- test-data/function.wgsl | 5 +- test-data/quad.wgsl | 20 +- test-data/simple/simple.expected.ron | 104 ++++--- test-data/simple/simple.wgsl | 6 +- tests/convert.rs | 48 +++- 22 files changed, 846 insertions(+), 838 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 3b219540c..dda2eb400 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -3,7 +3,7 @@ use std::{env, fs, path::Path}; #[derive(Hash, PartialEq, Eq, Serialize, Deserialize)] struct BindSource { - set: u32, + group: u32, binding: u32, } @@ -54,26 +54,14 @@ fn main() { #[cfg(feature = "glsl-in")] "frag" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str( - &input, - "main".to_string(), - naga::ShaderStage::Fragment { - early_depth_test: None, - }, - ) - .unwrap() + naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Fragment) + .unwrap() } #[cfg(feature = "glsl-in")] "comp" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str( - &input, - "main".to_string(), - naga::ShaderStage::Compute { - local_size: (0, 0, 0), - }, - ) - .unwrap() + naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Compute) + .unwrap() } #[cfg(feature = "deserialize")] "ron" => { @@ -113,7 +101,7 @@ fn main() { for (key, value) in params.metal_bindings { binding_map.insert( msl::BindSource { - set: key.set, + group: key.group, binding: key.binding, }, msl::BindTarget { @@ -170,17 +158,13 @@ fn main() { let options = Options { version: Version::Embedded(310), entry_point: ( - String::from("main"), match stage { "vert" => ShaderStage::Vertex, - "frag" => ShaderStage::Fragment { - early_depth_test: None, - }, - "comp" => ShaderStage::Compute { - local_size: (0, 0, 0), - }, + "frag" => ShaderStage::Fragment, + "comp" => ShaderStage::Compute, _ => unreachable!(), }, + String::from("main"), ), }; diff --git a/src/back/glsl.rs b/src/back/glsl.rs index cbb8fd26a..c54282cc5 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -66,7 +66,7 @@ impl fmt::Display for Version { #[derive(Debug, Clone)] pub struct Options { pub version: Version, - pub entry_point: (String, ShaderStage), + pub entry_point: (ShaderStage, String), } #[derive(Debug, Clone)] @@ -141,12 +141,12 @@ pub fn write<'a>( let entry_point = module .entry_points - .iter() - .find(|entry| entry.name == options.entry_point.0 && entry.stage == options.entry_point.1) + .get(&options.entry_point) .ok_or_else(|| Error::Custom(String::from("Entry point not found")))?; - let func = &module.functions[entry_point.function]; + let func = &entry_point.function; + let stage = options.entry_point.0; - if let ShaderStage::Compute { .. } = entry_point.stage { + if let ShaderStage::Compute = stage { if (es && version < 310) || (!es && version < 430) { return Err(Error::Custom(format!( "Version {} doesn't support compute shaders", @@ -233,21 +233,7 @@ pub fn write<'a>( let mut functions = FastHashMap::default(); for (handle, func) in module.functions.iter() { - // Discard all entry points - if entry_point.function != handle - && module - .entry_points - .iter() - .any(|entry| entry.function == handle) - { - continue; - } - - let name = if entry_point.function != handle { - namer(func.name.as_ref()) - } else { - String::from("main") - }; + let name = namer(func.name.as_ref()); writeln!( out, @@ -406,8 +392,8 @@ pub fn write<'a>( } if let Some(interpolation) = global.interpolation { - match (entry_point.stage, global.class) { - (ShaderStage::Fragment { .. }, StorageClass::Input) + match (stage, global.class) { + (ShaderStage::Fragment, StorageClass::Input) | (ShaderStage::Vertex, StorageClass::Output) => { write!(out, "{} ", write_interpolation(interpolation)?)?; } @@ -1449,7 +1435,7 @@ fn write_format_glsl(format: StorageFormat) -> &'static str { struct TextureMappingVisitor<'a> { expressions: &'a Arena, - map: FastHashMap, Option>>, + map: &'a mut FastHashMap, Option>>, error: Option, } @@ -1503,19 +1489,15 @@ fn collect_texture_mapping( for function in functions.keys() { let func = &module.functions[*function]; - let mut visitor = TextureMappingVisitor { - expressions: &func.expressions, - map: FastHashMap::default(), - error: None, - }; - let mut interface = Interface { expressions: &func.expressions, - visitor: &mut visitor, + visitor: TextureMappingVisitor { + expressions: &func.expressions, + map: &mut mappings, + error: None, + }, }; interface.traverse(&func.body); - - mappings.extend(visitor.map); } Ok(mappings) diff --git a/src/back/msl.rs b/src/back/msl.rs index ed7e16027..607b11ace 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -31,7 +31,7 @@ pub struct BindTarget { #[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub struct BindSource { - pub set: u32, + pub group: u32, pub binding: u32, } @@ -64,7 +64,6 @@ pub enum Error { Format(FmtError), Type(ResolveError), UnexpectedLocation, - MixedExecutionModels(Handle), MissingBinding(Handle), MissingBindTarget(BindSource), InvalidImageAccess(crate::StorageAccess), @@ -125,8 +124,8 @@ impl Options<'_> { }), LocationMode::Uniform => Err(Error::UnexpectedLocation), }, - crate::Binding::Descriptor { set, binding } => { - let source = BindSource { set, binding }; + crate::Binding::Resource { group, binding } => { + let source = BindSource { group, binding }; self.binding_map .get(&source) .cloned() @@ -182,22 +181,6 @@ impl Indexed for ParameterIndex { self.0 } } -struct InputStructIndex(Handle); -impl Indexed for InputStructIndex { - const CLASS: &'static str = "Input"; - const PREFIX: bool = true; - fn id(&self) -> usize { - self.0.index() - } -} -struct OutputStructIndex(Handle); -impl Indexed for OutputStructIndex { - const CLASS: &'static str = "Output"; - const PREFIX: bool = true; - fn id(&self) -> usize { - self.0.index() - } -} enum NameSource<'a> { Custom { name: &'a str, prefix: bool }, @@ -924,8 +907,55 @@ impl Writer { )?; let fun_name = fun.name.or_index(fun_handle); + let result_type_handle = fun.return_type.unwrap(); + let result_type_name = module.types[result_type_handle] + .name + .or_index(result_type_handle); + writeln!(self.out, "{} {}(", result_type_name, fun_name)?; + + for (index, &ty) in fun.parameter_types.iter().enumerate() { + let name = Name::from(ParameterIndex(index)); + let member_type_name = module.types[ty].name.or_index(ty); + let separator = separate(index + 1 == fun.parameter_types.len()); + writeln!(self.out, "\t{} {}{}", member_type_name, name, separator)?; + } + writeln!(self.out, ") {{")?; + + for (local_handle, local) in fun.local_variables.iter() { + let ty_name = module.types[local.ty].name.or_index(local.ty); + write!( + self.out, + "\t{} {}", + ty_name, + local.name.or_index(local_handle) + )?; + if let Some(value) = local.init { + write!(self.out, " = ")?; + self.put_expression(value, fun, module)?; + } + writeln!(self.out, ";")?; + } + for statement in fun.body.iter() { + self.put_statement(Level(1), statement, fun, false, module)?; + } + writeln!(self.out, "}}")?; + } + + for (&(stage, ref name), ep) in module.entry_points.iter() { + let fun = &ep.function; + self.typifier.resolve_all( + &fun.expressions, + &module.types, + &ResolveContext { + constants: &module.constants, + global_vars: &module.global_variables, + local_vars: &fun.local_variables, + functions: &module.functions, + parameter_types: &fun.parameter_types, + }, + )?; + // find the entry point(s) and inputs/outputs - let mut shader_stage = None; let mut last_used_global = None; for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { match var.class { @@ -941,206 +971,177 @@ impl Writer { last_used_global = Some(handle); } } - for ep in module.entry_points.iter() { - if ep.function == fun_handle { - if shader_stage.is_some() { - if shader_stage != Some(ep.stage) { - return Err(Error::MixedExecutionModels(fun_handle)); - } - } else { - shader_stage = Some(ep.stage); - } + + let output_name = Name { + class: "Output", + source: NameSource::Custom { name, prefix: true }, + }; + + let (em_str, in_mode, out_mode) = match stage { + crate::ShaderStage::Vertex => ( + "vertex", + LocationMode::VertexInput, + LocationMode::Intermediate, + ), + crate::ShaderStage::Fragment { .. } => ( + "fragment", + LocationMode::Intermediate, + LocationMode::FragmentOutput, + ), + crate::ShaderStage::Compute { .. } => { + ("kernel", LocationMode::Uniform, LocationMode::Uniform) } - } - let output_name = fun.name.or_index(OutputStructIndex(fun_handle)); + }; + let location_input_name = Name { + class: "Input", + source: NameSource::Custom { name, prefix: true }, + }; - // make dedicated input/output structs - if let Some(stage) = shader_stage { - assert_eq!(fun.return_type, None); - let (em_str, in_mode, out_mode) = match stage { - crate::ShaderStage::Vertex => ( - "vertex", - LocationMode::VertexInput, - LocationMode::Intermediate, - ), - crate::ShaderStage::Fragment { .. } => ( - "fragment", - LocationMode::Intermediate, - LocationMode::FragmentOutput, - ), - crate::ShaderStage::Compute { .. } => { - ("kernel", LocationMode::Uniform, LocationMode::Uniform) - } - }; - let location_input_name = fun.name.or_index(InputStructIndex(fun_handle)); + match stage { + crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { + // make dedicated input/output structs + writeln!(self.out, "struct {} {{", location_input_name)?; - match stage { - crate::ShaderStage::Compute { .. } => { - writeln!(self.out, "struct {} {{", location_input_name)?; - for ((handle, var), &usage) in - module.global_variables.iter().zip(&fun.global_usage) + for ((handle, var), &usage) in + module.global_variables.iter().zip(&fun.global_usage) + { + if var.class != crate::StorageClass::Input + || !usage.contains(crate::GlobalUse::LOAD) { - if var.class != crate::StorageClass::Input - || !usage.contains(crate::GlobalUse::LOAD) - { - continue; + continue; + } + // if it's a struct, lift all the built-in contents up to the root + let ty_handle = var.ty; + if let crate::TypeInner::Struct { ref members } = + module.types[ty_handle].inner + { + for (index, member) in members.iter().enumerate() { + if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { + let name = member.name.or_index(MemberIndex(index)); + let ty_name = module.types[member.ty].name.or_index(member.ty); + write!(self.out, "\t{} {}", ty_name, name)?; + ResolvedBinding::BuiltIn(built_in) + .try_fmt_decorated(&mut self.out, ";\n")?; + } } - // if it's a struct, lift all the built-in contents up to the root - let ty_handle = var.ty; - if let crate::TypeInner::Struct { ref members } = - module.types[ty_handle].inner - { - for (index, member) in members.iter().enumerate() { - if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { - let name = member.name.or_index(MemberIndex(index)); - let ty_name = - module.types[member.ty].name.or_index(member.ty); + } else if let Some(ref binding @ crate::Binding::Location(_)) = var.binding + { + let tyvar = TypedGlobalVariable { + module, + handle, + usage: crate::GlobalUse::empty(), + }; + let resolved = options.resolve_binding(binding, in_mode)?; + + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + resolved.try_fmt_decorated(&mut self.out, ";\n")?; + } + } + writeln!(self.out, "}};")?; + + writeln!(self.out, "struct {} {{", output_name)?; + for ((handle, var), &usage) in + module.global_variables.iter().zip(&fun.global_usage) + { + if var.class != crate::StorageClass::Output + || !usage.contains(crate::GlobalUse::STORE) + { + continue; + } + // if it's a struct, lift all the built-in contents up to the root + let ty_handle = var.ty; + if let crate::TypeInner::Struct { ref members } = + module.types[ty_handle].inner + { + for (index, member) in members.iter().enumerate() { + let name = member.name.or_index(MemberIndex(index)); + let ty_name = module.types[member.ty].name.or_index(member.ty); + match member.origin { + crate::MemberOrigin::Empty => {} + crate::MemberOrigin::BuiltIn(built_in) => { write!(self.out, "\t{} {}", ty_name, name)?; ResolvedBinding::BuiltIn(built_in) .try_fmt_decorated(&mut self.out, ";\n")?; } - } - } else if let Some(ref binding @ crate::Binding::Location(_)) = - var.binding - { - let tyvar = TypedGlobalVariable { - module, - handle, - usage: crate::GlobalUse::empty(), - }; - let resolved = options.resolve_binding(binding, in_mode)?; - - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - resolved.try_fmt_decorated(&mut self.out, ";\n")?; - } - } - writeln!(self.out, "}};")?; - writeln!(self.out, "struct {} {{", output_name)?; - for ((handle, var), &usage) in - module.global_variables.iter().zip(&fun.global_usage) - { - if var.class != crate::StorageClass::Output - || !usage.contains(crate::GlobalUse::STORE) - { - continue; - } - // if it's a struct, lift all the built-in contents up to the root - let ty_handle = var.ty; - if let crate::TypeInner::Struct { ref members } = - module.types[ty_handle].inner - { - for (index, member) in members.iter().enumerate() { - let name = member.name.or_index(MemberIndex(index)); - let ty_name = module.types[member.ty].name.or_index(member.ty); - match member.origin { - crate::MemberOrigin::Empty => {} - crate::MemberOrigin::BuiltIn(built_in) => { - write!(self.out, "\t{} {}", ty_name, name)?; - ResolvedBinding::BuiltIn(built_in) - .try_fmt_decorated(&mut self.out, ";\n")?; - } - crate::MemberOrigin::Offset(_) => { - //TODO - } + crate::MemberOrigin::Offset(_) => { + //TODO } } - } else { - let tyvar = TypedGlobalVariable { - module, - handle, - usage: crate::GlobalUse::empty(), - }; - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - if let Some(ref binding) = var.binding { - let resolved = options.resolve_binding(binding, out_mode)?; - resolved.try_fmt_decorated(&mut self.out, "")?; - } - writeln!(self.out, ";")?; } + } else { + let tyvar = TypedGlobalVariable { + module, + handle, + usage: crate::GlobalUse::empty(), + }; + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + if let Some(ref binding) = var.binding { + let resolved = options.resolve_binding(binding, out_mode)?; + resolved.try_fmt_decorated(&mut self.out, "")?; + } + writeln!(self.out, ";")?; } - writeln!(self.out, "}};")?; - writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; - let separator = separate(last_used_global.is_none()); - writeln!( - self.out, - "\t{} {} [[stage_in]]{}", - location_input_name, LOCATION_INPUT_STRUCT_NAME, separator - )?; } - _ => { - writeln!(self.out, "{} void {}(", em_str, fun_name)?; - } - }; + writeln!(self.out, "}};")?; - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) - { - if usage.is_empty() || var.class == crate::StorageClass::Output { + writeln!(self.out, "{} {} {}(", em_str, output_name, name)?; + let separator = separate(last_used_global.is_none()); + writeln!( + self.out, + "\t{} {} [[stage_in]]{}", + location_input_name, LOCATION_INPUT_STRUCT_NAME, separator + )?; + } + crate::ShaderStage::Compute => { + writeln!(self.out, "{} void {}(", em_str, name)?; + } + }; + + for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { + if usage.is_empty() || var.class == crate::StorageClass::Output { + continue; + } + if var.class == crate::StorageClass::Input { + if let Some(crate::Binding::Location(_)) = var.binding { + // location inputs are put into a separate struct continue; } - if var.class == crate::StorageClass::Input { - if let Some(crate::Binding::Location(_)) = var.binding { - // location inputs are put into a separate struct - continue; - } + } + let loc_mode = match (stage, var.class) { + (crate::ShaderStage::Vertex, crate::StorageClass::Input) => { + LocationMode::VertexInput } - let loc_mode = match (stage, var.class) { - (crate::ShaderStage::Vertex, crate::StorageClass::Input) => { - LocationMode::VertexInput - } - (crate::ShaderStage::Vertex, crate::StorageClass::Output) - | (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Input) => { - LocationMode::Intermediate - } - (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Output) => { - LocationMode::FragmentOutput - } - _ => LocationMode::Uniform, - }; - let resolved = - options.resolve_binding(var.binding.as_ref().unwrap(), loc_mode)?; - let tyvar = TypedGlobalVariable { - module, - handle, - usage, - }; - let separator = separate(last_used_global == Some(handle)); - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - resolved.try_fmt_decorated(&mut self.out, separator)?; - writeln!(self.out)?; - } - } else { - let result_type_name = match fun.return_type { - Some(type_id) => module.types[type_id].name.or_index(type_id), - None => Name { - class: "", - source: NameSource::Custom { - name: "void", - prefix: false, - }, - }, + (crate::ShaderStage::Vertex, crate::StorageClass::Output) + | (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Input) => { + LocationMode::Intermediate + } + (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Output) => { + LocationMode::FragmentOutput + } + _ => LocationMode::Uniform, }; - writeln!(self.out, "{} {}(", result_type_name, fun_name)?; - for (index, &ty) in fun.parameter_types.iter().enumerate() { - let name = Name::from(ParameterIndex(index)); - let member_type_name = module.types[ty].name.or_index(ty); - let separator = separate( - index + 1 == fun.parameter_types.len() && last_used_global.is_none(), - ); - writeln!(self.out, "\t{} {}{}", member_type_name, name, separator)?; - } + let resolved = options.resolve_binding(var.binding.as_ref().unwrap(), loc_mode)?; + let tyvar = TypedGlobalVariable { + module, + handle, + usage, + }; + let separator = separate(last_used_global == Some(handle)); + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + resolved.try_fmt_decorated(&mut self.out, separator)?; + writeln!(self.out)?; } writeln!(self.out, ") {{")?; - // write down function body - let has_output = match shader_stage { - Some(crate::ShaderStage::Vertex) | Some(crate::ShaderStage::Fragment { .. }) => { + let has_output = match stage { + crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?; true } - Some(crate::ShaderStage::Compute { .. }) | None => false, + crate::ShaderStage::Compute => false, }; for (local_handle, local) in fun.local_variables.iter() { let ty_name = module.types[local.ty].name.or_index(local.ty); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 91cbc9f87..b757aab8d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -248,26 +248,121 @@ impl Writer { } } + fn write_function( + &mut self, + ir_function: &crate::Function, + ir_module: &crate::Module, + ) -> spirv::Word { + let mut function = Function::new(); + + for (_, variable) in ir_function.local_variables.iter() { + let id = self.generate_id(); + + let init_word = match variable.init { + Some(exp) => match &ir_function.expressions[exp] { + crate::Expression::Constant(handle) => { + Some(self.get_constant_id(*handle, ir_module)) + } + _ => unreachable!(), + }, + None => None, + }; + + let pointer_id = + self.get_pointer_id(&ir_module.types, variable.ty, spirv::StorageClass::Function); + function.variables.push(LocalVariable { + id, + name: variable.name.clone(), + instruction: super::instructions::instruction_variable( + pointer_id, + id, + spirv::StorageClass::Function, + init_word, + ), + }); + } + + let return_type_id = + self.get_function_return_type(ir_function.return_type, &ir_module.types); + let mut parameter_type_ids = Vec::with_capacity(ir_function.parameter_types.len()); + + let mut function_parameter_pointer_ids = vec![]; + + for parameter_type in ir_function.parameter_types.iter() { + let id = self.generate_id(); + let pointer_id = self.get_pointer_id( + &ir_module.types, + *parameter_type, + spirv::StorageClass::Function, + ); + + function_parameter_pointer_ids.push(pointer_id); + parameter_type_ids + .push(self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type))); + function + .parameters + .push(super::instructions::instruction_function_parameter( + pointer_id, id, + )); + } + + let lookup_function_type = LookupFunctionType { + return_type_id, + parameter_type_ids, + }; + + let id = self.generate_id(); + let function_type = + self.get_function_type(lookup_function_type, function_parameter_pointer_ids); + function.signature = Some(super::instructions::instruction_function( + return_type_id, + id, + spirv::FunctionControl::empty(), + function_type, + )); + + let mut block = Block::new(); + let id = self.generate_id(); + block.label = Some(super::instructions::instruction_label(id)); + for statement in ir_function.body.iter() { + self.write_function_statement( + ir_module, + ir_function, + &statement, + &mut block, + &mut function, + ); + } + function.blocks.push(block); + + function.to_words(&mut self.logical_layout.function_definitions); + super::instructions::instruction_function_end() + .to_words(&mut self.logical_layout.function_definitions); + + id + } + // TODO Move to instructions module fn write_entry_point( &mut self, entry_point: &crate::EntryPoint, + stage: crate::ShaderStage, + name: &str, ir_module: &crate::Module, ) -> Instruction { - let function_id = *self.lookup_function.get(&entry_point.function).unwrap(); + let function_id = self.write_function(&entry_point.function, ir_module); - let exec_model = match entry_point.stage { + let exec_model = match stage { crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, crate::ShaderStage::Fragment { .. } => spirv::ExecutionModel::Fragment, crate::ShaderStage::Compute { .. } => spirv::ExecutionModel::GLCompute, }; let mut interface_ids = vec![]; - let function = &ir_module.functions[entry_point.function]; for ((handle, _), &usage) in ir_module .global_variables .iter() - .zip(&function.global_usage) + .zip(&entry_point.function.global_usage) { if usage.contains(crate::GlobalUse::STORE) || usage.contains(crate::GlobalUse::LOAD) { let id = self.get_global_variable_id( @@ -280,28 +375,26 @@ impl Writer { } self.try_add_capabilities(exec_model.required_capabilities()); - match entry_point.stage { + match stage { crate::ShaderStage::Vertex => {} - crate::ShaderStage::Fragment { .. } => { + crate::ShaderStage::Fragment => { let execution_mode = spirv::ExecutionMode::OriginUpperLeft; self.try_add_capabilities(execution_mode.required_capabilities()); super::instructions::instruction_execution_mode(function_id, execution_mode) .to_words(&mut self.logical_layout.execution_modes); } - crate::ShaderStage::Compute { .. } => {} + crate::ShaderStage::Compute => {} } if self.writer_flags.contains(WriterFlags::DEBUG) { - self.debugs.push(super::instructions::instruction_name( - function_id, - entry_point.name.as_str(), - )); + self.debugs + .push(super::instructions::instruction_name(function_id, name)); } super::instructions::instruction_entry_point( exec_model, function_id, - entry_point.name.as_str(), + name, interface_ids.as_slice(), ) } @@ -604,27 +697,27 @@ impl Writer { } } - match global_variable.binding.as_ref().unwrap() { + match *global_variable.binding.as_ref().unwrap() { crate::Binding::Location(location) => { self.annotations .push(super::instructions::instruction_decorate( id, spirv::Decoration::Location, - &[*location], + &[location], )); } - crate::Binding::Descriptor { set, binding } => { + crate::Binding::Resource { group, binding } => { self.annotations .push(super::instructions::instruction_decorate( id, spirv::Decoration::DescriptorSet, - &[*set], + &[group], )); self.annotations .push(super::instructions::instruction_decorate( id, spirv::Decoration::Binding, - &[*binding], + &[binding], )); } crate::Binding::BuiltIn(built_in) => { @@ -1000,100 +1093,12 @@ impl Writer { } for (handle, ir_function) in ir_module.functions.iter() { - let mut function = Function::new(); - - for (_, variable) in ir_function.local_variables.iter() { - let id = self.generate_id(); - - let init_word = match variable.init { - Some(exp) => match &ir_function.expressions[exp] { - crate::Expression::Constant(handle) => { - Some(self.get_constant_id(*handle, ir_module)) - } - _ => unreachable!(), - }, - None => None, - }; - - let pointer_id = self.get_pointer_id( - &ir_module.types, - variable.ty, - spirv::StorageClass::Function, - ); - function.variables.push(LocalVariable { - id, - name: variable.name.clone(), - instruction: super::instructions::instruction_variable( - pointer_id, - id, - spirv::StorageClass::Function, - init_word, - ), - }); - } - - let return_type_id = - self.get_function_return_type(ir_function.return_type, &ir_module.types); - let mut parameter_type_ids = Vec::with_capacity(ir_function.parameter_types.len()); - - let mut function_parameter_pointer_ids = vec![]; - - for parameter_type in ir_function.parameter_types.iter() { - let id = self.generate_id(); - let pointer_id = self.get_pointer_id( - &ir_module.types, - *parameter_type, - spirv::StorageClass::Function, - ); - - function_parameter_pointer_ids.push(pointer_id); - parameter_type_ids - .push(self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type))); - function - .parameters - .push(super::instructions::instruction_function_parameter( - pointer_id, id, - )); - } - - let lookup_function_type = LookupFunctionType { - return_type_id, - parameter_type_ids, - }; - - let id = self.generate_id(); - let function_type = - self.get_function_type(lookup_function_type, function_parameter_pointer_ids); - function.signature = Some(super::instructions::instruction_function( - return_type_id, - id, - spirv::FunctionControl::empty(), - function_type, - )); - + let id = self.write_function(ir_function, ir_module); self.lookup_function.insert(handle, id); - - let mut block = Block::new(); - let id = self.generate_id(); - block.label = Some(super::instructions::instruction_label(id)); - for statement in ir_function.body.iter() { - self.write_function_statement( - ir_module, - ir_function, - &statement, - &mut block, - &mut function, - ); - } - function.blocks.push(block); - - function.to_words(&mut self.logical_layout.function_definitions); - super::instructions::instruction_function_end() - .to_words(&mut self.logical_layout.function_definitions); } - for entry_point in ir_module.entry_points.iter() { - let entry_point_instruction = self.write_entry_point(entry_point, ir_module); + for (&(stage, ref name), ir_ep) in ir_module.entry_points.iter() { + let entry_point_instruction = self.write_entry_point(ir_ep, stage, name, ir_module); entry_point_instruction.to_words(&mut self.logical_layout.entry_points); } diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 2919ef503..2a32234e4 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,6 +1,6 @@ use crate::{ - Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, GlobalVariable, - Handle, Interpolation, LocalVariable, ShaderStage, Statement, StorageClass, Type, + Arena, BinaryOperator, Binding, Expression, FastHashMap, Function, GlobalVariable, Handle, + Interpolation, LocalVariable, Module, ShaderStage, Statement, StorageClass, Type, }; #[derive(Debug)] @@ -8,28 +8,23 @@ pub struct Program { pub version: u16, pub profile: Profile, pub shader_stage: ShaderStage, + pub entry: Option, pub lookup_function: FastHashMap>, - pub functions: Arena, pub lookup_type: FastHashMap>, - pub types: Arena, - pub constants: Arena, - pub global_variables: Arena, pub lookup_global_variables: FastHashMap>, pub context: Context, + pub module: Module, } impl Program { - pub fn new(shader_stage: ShaderStage) -> Program { + pub fn new(shader_stage: ShaderStage, entry: String) -> Program { Program { version: 0, profile: Profile::Core, shader_stage, + entry: Some(entry), lookup_function: FastHashMap::default(), - functions: Arena::::new(), lookup_type: FastHashMap::default(), - types: Arena::::new(), - constants: Arena::::new(), - global_variables: Arena::::new(), lookup_global_variables: FastHashMap::default(), context: Context { expressions: Arena::::new(), @@ -37,6 +32,7 @@ impl Program { scopes: vec![FastHashMap::default()], lookup_global_var_exps: FastHashMap::default(), }, + module: Module::generate_empty(), } } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 338a21f68..ca0ddaad8 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,4 +1,4 @@ -use crate::{EntryPoint, Module, ShaderStage}; +use crate::{Module, ShaderStage}; mod lex; #[cfg(test)] @@ -23,7 +23,7 @@ mod rosetta_tests; pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { log::debug!("------ GLSL-pomelo ------"); - let mut program = Program::new(stage); + let mut program = Program::new(stage, entry); let lex = Lexer::new(source); let mut parser = parser::Parser::new(&mut program); @@ -32,20 +32,5 @@ pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result Result { - let mut program = Program::new(stage); + let mut program = Program::new(stage, "".to_string()); let lex = Lexer::new(source); let mut parser = parser::Parser::new(&mut program); diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 263bca52e..834f78765 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -18,25 +18,28 @@ impl Program { return Err(ErrorKind::VariableNotAvailable(name.into())); } }; - let h = self.global_variables.fetch_or_append(GlobalVariable { - name: Some(name.into()), - class: if self.shader_stage == ShaderStage::Vertex { - StorageClass::Output - } else { - StorageClass::Input - }, - binding: Some(Binding::BuiltIn(BuiltIn::Position)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, + let h = self + .module + .global_variables + .fetch_or_append(GlobalVariable { + name: Some(name.into()), + class: if self.shader_stage == ShaderStage::Vertex { + StorageClass::Output + } else { + StorageClass::Input }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }); + binding: Some(Binding::BuiltIn(BuiltIn::Position)), + ty: self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 4, + }, + }), + interpolation: None, + storage_access: StorageAccess::empty(), + }); self.lookup_global_variables.insert(name.into(), h); let exp = self .context @@ -54,20 +57,23 @@ impl Program { return Err(ErrorKind::VariableNotAvailable(name.into())); } }; - let h = self.global_variables.fetch_or_append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), - ty: self.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - }), - interpolation: None, - storage_access: StorageAccess::empty(), - }); + let h = self + .module + .global_variables + .fetch_or_append(GlobalVariable { + name: Some(name.into()), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), + ty: self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + }, + }), + interpolation: None, + storage_access: StorageAccess::empty(), + }); self.lookup_global_variables.insert(name.into(), h); let exp = self .context diff --git a/src/front/mod.rs b/src/front/mod.rs index 3e7464577..cb543c72a 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -19,7 +19,7 @@ impl crate::Module { constants: Arena::new(), global_variables: Arena::new(), functions: Arena::new(), - entry_points: Vec::new(), + entry_points: crate::FastHashMap::default(), } } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 06de75e41..335e1a33e 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -49,123 +49,142 @@ pub enum Terminator { Unreachable, } -pub fn parse_function>( - parser: &mut super::Parser, - inst: Instruction, - module: &mut crate::Module, -) -> Result<(), Error> { - parser.switch(ModuleState::Function, inst.op)?; - inst.expect(5)?; - let result_type = parser.next()?; - let fun_id = parser.next()?; - let _fun_control = parser.next()?; - let fun_type = parser.next()?; - let mut fun = { - let ft = parser.lookup_function_type.lookup(fun_type)?; - if ft.return_type_id != result_type { - return Err(Error::WrongFunctionResultType(result_type)); - } - crate::Function { - name: parser.future_decor.remove(&fun_id).and_then(|dec| dec.name), - parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), - return_type: if parser.lookup_void_type.contains(&result_type) { - None - } else { - Some(parser.lookup_type.lookup(result_type)?.handle) - }, - global_usage: Vec::new(), - local_variables: Arena::new(), - expressions: parser.make_expression_storage(), - body: Vec::new(), - } - }; +impl> super::Parser { + pub fn parse_function( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Function, inst.op)?; + inst.expect(5)?; + let result_type = self.next()?; + let fun_id = self.next()?; + let _fun_control = self.next()?; + let fun_type = self.next()?; - // read parameters - for i in 0..fun.parameter_types.capacity() { - match parser.next_inst()? { - Instruction { - op: spirv::Op::FunctionParameter, - wc: 3, - } => { - let type_id = parser.next()?; - let id = parser.next()?; - let handle = fun - .expressions - .append(crate::Expression::FunctionParameter(i as u32)); - parser - .lookup_expression - .insert(id, LookupExpression { type_id, handle }); - //Note: we redo the lookup in order to work around `parser` borrowing + let mut fun = { + let ft = self.lookup_function_type.lookup(fun_type)?; + if ft.return_type_id != result_type { + return Err(Error::WrongFunctionResultType(result_type)); + } + crate::Function { + name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name), + parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), + return_type: if self.lookup_void_type.contains(&result_type) { + None + } else { + Some(self.lookup_type.lookup(result_type)?.handle) + }, + global_usage: Vec::new(), + local_variables: Arena::new(), + expressions: self.make_expression_storage(), + body: Vec::new(), + } + }; - if type_id - != parser - .lookup_function_type - .lookup(fun_type)? - .parameter_type_ids[i] - { - return Err(Error::WrongFunctionParameterType(type_id)); + // read parameters + for i in 0..fun.parameter_types.capacity() { + match self.next_inst()? { + Instruction { + op: spirv::Op::FunctionParameter, + wc: 3, + } => { + let type_id = self.next()?; + let id = self.next()?; + let handle = fun + .expressions + .append(crate::Expression::FunctionParameter(i as u32)); + self.lookup_expression + .insert(id, LookupExpression { type_id, handle }); + //Note: we redo the lookup in order to work around `self` borrowing + + if type_id + != self + .lookup_function_type + .lookup(fun_type)? + .parameter_type_ids[i] + { + return Err(Error::WrongFunctionParameterType(type_id)); + } + let ty = self.lookup_type.lookup(type_id)?.handle; + fun.parameter_types.push(ty); } - let ty = parser.lookup_type.lookup(type_id)?.handle; - fun.parameter_types.push(ty); - } - Instruction { op, .. } => return Err(Error::InvalidParameter(op)), - } - } - - // Read body - let mut local_function_calls = FastHashMap::default(); - let mut flow_graph = FlowGraph::new(); - - // Scan the blocks and add them as nodes - loop { - let fun_inst = parser.next_inst()?; - log::debug!("{:?}", fun_inst.op); - match fun_inst.op { - spirv::Op::Label => { - // Read the label ID - fun_inst.expect(2)?; - let block_id = parser.next()?; - - let node = parser.next_block( - block_id, - &mut fun.expressions, - &mut fun.local_variables, - &module.types, - &module.constants, - &module.global_variables, - &mut local_function_calls, - )?; - - flow_graph.add_node(node); - } - spirv::Op::FunctionEnd => { - fun_inst.expect(1)?; - break; - } - _ => { - return Err(Error::UnsupportedInstruction(parser.state, fun_inst.op)); + Instruction { op, .. } => return Err(Error::InvalidParameter(op)), } } + + // Read body + let mut local_function_calls = FastHashMap::default(); + let mut flow_graph = FlowGraph::new(); + + // Scan the blocks and add them as nodes + loop { + let fun_inst = self.next_inst()?; + log::debug!("{:?}", fun_inst.op); + match fun_inst.op { + spirv::Op::Label => { + // Read the label ID + fun_inst.expect(2)?; + let block_id = self.next()?; + + let node = self.next_block( + block_id, + &mut fun.expressions, + &mut fun.local_variables, + &module.types, + &module.constants, + &module.global_variables, + &mut local_function_calls, + )?; + + flow_graph.add_node(node); + } + spirv::Op::FunctionEnd => { + fun_inst.expect(1)?; + break; + } + _ => { + return Err(Error::UnsupportedInstruction(self.state, fun_inst.op)); + } + } + } + + flow_graph.classify(); + flow_graph.remove_phi_instructions(&self.lookup_expression); + fun.body = flow_graph.to_naga()?; + + // done + fun.fill_global_use(&module.global_variables); + + let source = match self.lookup_entry_point.remove(&fun_id) { + Some(ep) => { + module.entry_points.insert( + (ep.stage, ep.name.clone()), + crate::EntryPoint { + early_depth_test: ep.early_depth_test, + workgroup_size: ep.workgroup_size, + function: fun, + }, + ); + DeferredSource::EntryPoint(ep.stage, ep.name) + } + None => { + let handle = module.functions.append(fun); + self.lookup_function.insert(fun_id, handle); + DeferredSource::Function(handle) + } + }; + + for (expr_handle, dst_id) in local_function_calls { + self.deferred_function_calls.push(DeferredFunctionCall { + source: source.clone(), + expr_handle, + dst_id, + }); + } + + self.lookup_expression.clear(); + self.lookup_sampled_image.clear(); + Ok(()) } - - flow_graph.classify(); - flow_graph.remove_phi_instructions(&parser.lookup_expression); - fun.body = flow_graph.to_naga()?; - - // done - fun.global_usage = - crate::GlobalUse::scan(&fun.expressions, &fun.body, &module.global_variables); - let handle = module.functions.append(fun); - for (expr_handle, dst_id) in local_function_calls { - parser.deferred_function_calls.push(DeferredFunctionCall { - source_handle: handle, - expr_handle, - dst_id, - }); - } - - parser.lookup_function.insert(fun_id, handle); - parser.lookup_expression.clear(); - parser.lookup_sampled_image.clear(); - Ok(()) } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a9115f9c5..c4c75f69e 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -197,10 +197,10 @@ impl Decoration { Decoration { built_in: None, location: None, - desc_set: Some(set), + desc_set: Some(group), desc_index: Some(binding), .. - } => Some(crate::Binding::Descriptor { set, binding }), + } => Some(crate::Binding::Resource { group, binding }), _ => None, } } @@ -252,6 +252,8 @@ struct LookupFunctionType { struct EntryPoint { stage: crate::ShaderStage, name: String, + early_depth_test: Option, + workgroup_size: [u32; 3], function_id: spirv::Word, variable_ids: Vec, } @@ -285,8 +287,13 @@ struct LookupSampledImage { image: Handle, sampler: Handle, } +#[derive(Clone, Debug)] +enum DeferredSource { + EntryPoint(crate::ShaderStage, String), + Function(Handle), +} struct DeferredFunctionCall { - source_handle: Handle, + source: DeferredSource, expr_handle: Handle, dst_id: spirv::Word, } @@ -1444,7 +1451,7 @@ impl> Parser { Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), Op::Variable => self.parse_global_variable(inst, &mut module), - Op::Function => parse_function(&mut self, inst, &mut module), + Op::Function => self.parse_function(inst, &mut module), _ => Err(Error::UnsupportedInstruction(self.state, inst.op)), //TODO }?; } @@ -1476,12 +1483,17 @@ impl> Parser { for dfc in self.deferred_function_calls.drain(..) { let dst_handle = *self.lookup_function.lookup(dfc.dst_id)?; - match *module - .functions - .get_mut(dfc.source_handle) - .expressions - .get_mut(dfc.expr_handle) - { + let fun = match dfc.source { + DeferredSource::Function(fun_handle) => module.functions.get_mut(fun_handle), + DeferredSource::EntryPoint(stage, name) => { + &mut module + .entry_points + .get_mut(&(stage, name)) + .unwrap() + .function + } + }; + match *fun.expressions.get_mut(dfc.expr_handle) { crate::Expression::Call { ref mut origin, arguments: _, @@ -1499,15 +1511,6 @@ impl> Parser { self.future_member_decor.clear(); } - module.entry_points.reserve(self.lookup_entry_point.len()); - for raw in self.lookup_entry_point.values() { - module.entry_points.push(crate::EntryPoint { - stage: raw.stage, - name: raw.name.clone(), - function: *self.lookup_function.lookup(raw.function_id)?, - }); - } - Ok(module) } @@ -1570,15 +1573,13 @@ impl> Parser { let ep = EntryPoint { stage: match exec_model { spirv::ExecutionModel::Vertex => crate::ShaderStage::Vertex, - spirv::ExecutionModel::Fragment => crate::ShaderStage::Fragment { - early_depth_test: None, - }, - spirv::ExecutionModel::GLCompute => crate::ShaderStage::Compute { - local_size: (0, 0, 0), - }, + spirv::ExecutionModel::Fragment => crate::ShaderStage::Fragment, + spirv::ExecutionModel::GLCompute => crate::ShaderStage::Compute, _ => return Err(Error::UnsupportedExecutionModel(exec_model as u32)), }, name, + early_depth_test: None, + workgroup_size: [0; 3], function_id, variable_ids: self.data.by_ref().take(left as usize).collect(), }; @@ -1587,7 +1588,6 @@ impl> Parser { } fn parse_execution_mode(&mut self, inst: Instruction) -> Result<(), Error> { - use crate::ShaderStage; use spirv::ExecutionMode; self.switch(ModuleState::ExecutionMode, inst.op)?; @@ -1597,63 +1597,47 @@ impl> Parser { let mode_id = self.next()?; let args: Vec = self.data.by_ref().take(inst.wc as usize - 3).collect(); - let ep: &mut EntryPoint = self + let ep = self .lookup_entry_point .get_mut(&ep_id) .ok_or(Error::InvalidId(ep_id))?; let mode = spirv::ExecutionMode::from_u32(mode_id) .ok_or(Error::UnsupportedExecutionMode(mode_id))?; - match ep.stage { - ShaderStage::Fragment { - ref mut early_depth_test, - } => { - match mode { - ExecutionMode::EarlyFragmentTests => { - if early_depth_test.is_none() { - *early_depth_test = Some(crate::EarlyDepthTest { conservative: None }); - } - } - ExecutionMode::DepthUnchanged => { - *early_depth_test = Some(crate::EarlyDepthTest { - conservative: Some(crate::ConservativeDepth::Unchanged), - }); - } - ExecutionMode::DepthGreater => { - *early_depth_test = Some(crate::EarlyDepthTest { - conservative: Some(crate::ConservativeDepth::GreaterEqual), - }); - } - ExecutionMode::DepthLess => { - *early_depth_test = Some(crate::EarlyDepthTest { - conservative: Some(crate::ConservativeDepth::LessEqual), - }); - } - ExecutionMode::DepthReplacing => { - // Ignored because it can be deduced from the IR. - } - ExecutionMode::OriginUpperLeft => { - // Ignored because the other option (OriginLowerLeft) is not valid in Vulkan mode. - } - _ => { - return Err(Error::UnsupportedExecutionMode(mode_id)); - } - }; + match mode { + ExecutionMode::EarlyFragmentTests => { + if ep.early_depth_test.is_none() { + ep.early_depth_test = Some(crate::EarlyDepthTest { conservative: None }); + } } - ShaderStage::Compute { ref mut local_size } => { - match mode { - ExecutionMode::LocalSize => { - *local_size = (args[0], args[1], args[2]); - } - _ => { - return Err(Error::UnsupportedExecutionMode(mode_id)); - } - }; + ExecutionMode::DepthUnchanged => { + ep.early_depth_test = Some(crate::EarlyDepthTest { + conservative: Some(crate::ConservativeDepth::Unchanged), + }); + } + ExecutionMode::DepthGreater => { + ep.early_depth_test = Some(crate::EarlyDepthTest { + conservative: Some(crate::ConservativeDepth::GreaterEqual), + }); + } + ExecutionMode::DepthLess => { + ep.early_depth_test = Some(crate::EarlyDepthTest { + conservative: Some(crate::ConservativeDepth::LessEqual), + }); + } + ExecutionMode::DepthReplacing => { + // Ignored because it can be deduced from the IR. + } + ExecutionMode::OriginUpperLeft => { + // Ignored because the other option (OriginLowerLeft) is not valid in Vulkan mode. + } + ExecutionMode::LocalSize => { + ep.workgroup_size = [args[0], args[1], args[2]]; } _ => { return Err(Error::UnsupportedExecutionMode(mode_id)); } - }; + } Ok(()) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f3f980e9b..ed0feb831 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -320,12 +320,8 @@ impl Parser { fn get_shader_stage(word: &str) -> Result> { match word { "vertex" => Ok(crate::ShaderStage::Vertex), - "fragment" => Ok(crate::ShaderStage::Fragment { - early_depth_test: None, - }), - "compute" => Ok(crate::ShaderStage::Compute { - local_size: (0, 0, 0), - }), + "fragment" => Ok(crate::ShaderStage::Fragment), + "compute" => Ok(crate::ShaderStage::Compute), _ => Err(Error::UnknownShaderStage(word)), } } @@ -563,7 +559,6 @@ impl Parser { Token::Separator('.') => { let _ = lexer.next(); let name = lexer.next_ident()?; - println!("Resolving '{}' for {:?}", name, ctx.resolve_type(handle)); //TEMP let expression = match *ctx.resolve_type(handle)? { crate::TypeInner::Struct { ref members } => { let index = members @@ -918,7 +913,9 @@ impl Parser { ready = true; } Token::Word("offset") if ready => { + lexer.expect(Token::Paren('('))?; offset = lexer.next_uint_literal()?; + lexer.expect(Token::Paren(')'))?; ready = false; } other => return Err(Error::Unexpected(other)), @@ -1288,7 +1285,7 @@ impl Parser { lexer: &mut Lexer<'a>, module: &mut crate::Module, lookup_global_expression: &FastHashMap<&'a str, crate::Expression>, - ) -> Result, Error<'a>> { + ) -> Result<(crate::Function, &'a str), Error<'a>> { self.scopes.push(Scope::FunctionDecl); // read function name let mut lookup_ident = FastHashMap::default(); @@ -1322,7 +1319,7 @@ impl Parser { Some(self.parse_type_decl(lexer, None, &mut module.types)?.0) }; - let fun_handle = module.functions.append(crate::Function { + let mut fun = crate::Function { name: Some(fun_name.to_string()), parameter_types, return_type, @@ -1330,15 +1327,7 @@ impl Parser { local_variables: Arena::new(), expressions, body: Vec::new(), - }); - if self - .function_lookup - .insert(fun_name.to_string(), fun_handle) - .is_some() - { - return Err(Error::FunctionRedefinition(fun_name)); - } - let fun = module.functions.get_mut(fun_handle); + }; // read body let mut typifier = Typifier::new(); @@ -1356,11 +1345,10 @@ impl Parser { }, )?; // done - fun.global_usage = - crate::GlobalUse::scan(&fun.expressions, &fun.body, &module.global_variables); + fun.fill_global_use(&module.global_variables); self.scopes.pop(); - Ok(fun_handle) + Ok((fun, fun_name)) } fn parse_global_decl<'a>( @@ -1373,30 +1361,56 @@ impl Parser { let mut binding = None; // Perspective is the default qualifier. let mut interpolation = None; + let mut stage = None; + let mut workgroup_size = [1u32; 3]; + if lexer.skip(Token::DoubleParen('[')) { - let (mut bind_index, mut bind_set) = (None, None); + let (mut bind_index, mut bind_group) = (None, None); self.scopes.push(Scope::Decoration); loop { match lexer.next_ident()? { "location" => { + lexer.expect(Token::Paren('('))?; let loc = lexer.next_uint_literal()?; + lexer.expect(Token::Paren(')'))?; binding = Some(crate::Binding::Location(loc)); } "builtin" => { + lexer.expect(Token::Paren('('))?; let builtin = Self::get_built_in(lexer.next_ident()?)?; + lexer.expect(Token::Paren(')'))?; binding = Some(crate::Binding::BuiltIn(builtin)); } "binding" => { + lexer.expect(Token::Paren('('))?; bind_index = Some(lexer.next_uint_literal()?); + lexer.expect(Token::Paren(')'))?; } - "set" => { - bind_set = Some(lexer.next_uint_literal()?); + "group" => { + lexer.expect(Token::Paren('('))?; + bind_group = Some(lexer.next_uint_literal()?); + lexer.expect(Token::Paren(')'))?; } "interpolate" => { - if interpolation.is_some() { - return Err(Error::UnknownDecoration(lexer.next_ident()?)); - } + lexer.expect(Token::Paren('('))?; interpolation = Some(Self::get_interpolation(lexer.next_ident()?)?); + lexer.expect(Token::Paren(')'))?; + } + "stage" => { + lexer.expect(Token::Paren('('))?; + stage = Some(Self::get_shader_stage(lexer.next_ident()?)?); + lexer.expect(Token::Paren(')'))?; + } + "workgroup_size" => { + lexer.expect(Token::Paren('('))?; + for (i, size) in workgroup_size.iter_mut().enumerate() { + *size = lexer.next_uint_literal()?; + match lexer.next() { + Token::Paren(')') => break, + Token::Separator(',') if i != 2 => (), + other => return Err(Error::Unexpected(other)), + } + } } word => return Err(Error::UnknownDecoration(word)), } @@ -1408,15 +1422,11 @@ impl Parser { other => return Err(Error::Unexpected(other)), } } - match (bind_set, bind_index) { - (Some(set), Some(index)) if binding.is_none() => { - binding = Some(crate::Binding::Descriptor { - set, - binding: index, - }); - } - _ if binding.is_none() => return Err(Error::Other), - _ => {} + if let (Some(group), Some(index)) = (bind_group, bind_index) { + binding = Some(crate::Binding::Resource { + group, + binding: index, + }); } self.scopes.pop(); } @@ -1494,31 +1504,30 @@ impl Parser { .insert(pvar.name, crate::Expression::GlobalVariable(var_handle)); } Token::Word("fn") => { - self.parse_function_decl(lexer, module, &lookup_global_expression)?; - } - Token::Word("entry_point") => { - let stage = Self::get_shader_stage(lexer.next_ident()?)?; - let export_name = if lexer.skip(Token::Word("as")) { - match lexer.next() { - Token::String(name) => Some(name), - other => return Err(Error::Unexpected(other)), + let (function, name) = + self.parse_function_decl(lexer, module, &lookup_global_expression)?; + let already_declared = match stage { + Some(stage) => module + .entry_points + .insert( + (stage, name.to_string()), + crate::EntryPoint { + early_depth_test: None, + workgroup_size, + function, + }, + ) + .is_some(), + None => { + let fun_handle = module.functions.append(function); + self.function_lookup + .insert(name.to_string(), fun_handle) + .is_some() } - } else { - None }; - lexer.expect(Token::Operation('='))?; - let fun_ident = lexer.next_ident()?; - lexer.expect(Token::Separator(';'))?; - let (fun_handle, _) = module - .functions - .iter() - .find(|(_, fun)| fun.name.as_deref() == Some(fun_ident)) - .ok_or(Error::UnknownFunction(fun_ident))?; - module.entry_points.push(crate::EntryPoint { - stage, - name: export_name.unwrap_or(fun_ident).to_owned(), - function: fun_handle, - }); + if already_declared { + return Err(Error::FunctionRedefinition(name)); + } } Token::End => return Ok(false), token => return Err(Error::Unexpected(token)), diff --git a/src/lib.rs b/src/lib.rs index 4cded46ca..7086834c2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -88,18 +88,14 @@ pub enum ConservativeDepth { } /// Stage of the programmable pipeline. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[allow(missing_docs)] // The names are self evident pub enum ShaderStage { Vertex, - Fragment { - early_depth_test: Option, - }, - Compute { - local_size: (u32, u32, u32), - }, + Fragment, + Compute, } /// Class of storage for variables. @@ -416,8 +412,8 @@ pub enum Binding { BuiltIn(BuiltIn), /// Indexed location. Location(u32), - /// Binding within a descriptor set. - Descriptor { set: u32, binding: u32 }, + /// Binding within a resource group. + Resource { group: u32, binding: u32 }, } bitflags::bitflags! { @@ -635,7 +631,7 @@ pub enum Expression { origin: FunctionOrigin, arguments: Vec>, }, - /// Get dynamic array length. + /// Get the length of an array. ArrayLength(Handle), } @@ -718,12 +714,12 @@ pub struct Function { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct EntryPoint { - /// The stage in the programmable pipeline this entry point is for. - pub stage: ShaderStage, - /// Name identifying this entry point. - pub name: String, - /// The function to be used. - pub function: Handle, + /// Early depth test for fragment stages. + pub early_depth_test: Option, + /// Workgroup size for compute stages + pub workgroup_size: [u32; 3], + /// The entrance function. + pub function: Function, } /// Shader module. @@ -751,6 +747,6 @@ pub struct Module { pub global_variables: Arena, /// Storage for the functions defined in this module. pub functions: Arena, - /// Vector of exported entry points. - pub entry_points: Vec, + /// Exported entry points. + pub entry_points: FastHashMap<(ShaderStage, String), EntryPoint>, } diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 8e1f5666c..102da6e6a 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -2,12 +2,13 @@ use crate::arena::{Arena, Handle}; pub struct Interface<'a, T> { pub expressions: &'a Arena, - pub visitor: &'a mut T, + pub visitor: T, } pub trait Visitor { fn visit_expr(&mut self, _: &crate::Expression) {} fn visit_lhs_expr(&mut self, _: &crate::Expression) {} + fn visit_fun(&mut self, _: Handle) {} } impl<'a, T> Interface<'a, T> @@ -95,10 +96,16 @@ where E::Derivative { expr, .. } => { self.traverse_expr(expr); } - E::Call { ref arguments, .. } => { + E::Call { + ref origin, + ref arguments, + } => { for &argument in arguments { self.traverse_expr(argument); } + if let crate::FunctionOrigin::Local(fun) = *origin { + self.visitor.visit_fun(fun); + } } E::ArrayLength(expr) => { self.traverse_expr(expr); @@ -168,9 +175,9 @@ where } } -struct GlobalUseVisitor(Vec); +struct GlobalUseVisitor<'a>(&'a mut [crate::GlobalUse]); -impl Visitor for GlobalUseVisitor { +impl Visitor for GlobalUseVisitor<'_> { fn visit_expr(&mut self, expr: &crate::Expression) { if let crate::Expression::GlobalVariable(handle) = expr { self.0[handle.index()] |= crate::GlobalUse::LOAD; @@ -184,20 +191,17 @@ impl Visitor for GlobalUseVisitor { } } -impl crate::GlobalUse { - pub fn scan( - expressions: &Arena, - body: &[crate::Statement], - globals: &Arena, - ) -> Vec { - let mut visitor = GlobalUseVisitor(vec![crate::GlobalUse::empty(); globals.len()]); +impl crate::Function { + pub fn fill_global_use(&mut self, globals: &Arena) { + self.global_usage.clear(); + self.global_usage + .resize(globals.len(), crate::GlobalUse::empty()); let mut io = Interface { - expressions, - visitor: &mut visitor, + expressions: &self.expressions, + visitor: GlobalUseVisitor(&mut self.global_usage), }; - io.traverse(body); - visitor.0 + io.traverse(&self.body); } } @@ -248,14 +252,25 @@ mod tests { }, ]; + let mut function = crate::Function { + name: None, + parameter_types: Vec::new(), + return_type: None, + local_variables: Arena::new(), + expressions, + global_usage: Vec::new(), + body: test_body, + }; + function.fill_global_use(&test_globals); + assert_eq!( - GlobalUse::scan(&expressions, &test_body, &test_globals), - vec![ + &function.global_usage, + &[ GlobalUse::LOAD, GlobalUse::STORE, GlobalUse::STORE, GlobalUse::LOAD, - ] + ], ) } } diff --git a/test-data/boids.param.ron b/test-data/boids.param.ron index db17ca341..bfd748777 100644 --- a/test-data/boids.param.ron +++ b/test-data/boids.param.ron @@ -1,7 +1,7 @@ ( metal_bindings: { - (set: 0, binding: 0): (buffer: Some(0), texture: None, sampler: None, mutable: false), - (set: 0, binding: 1): (buffer: Some(1), texture: None, sampler: None, mutable: true), - (set: 0, binding: 2): (buffer: Some(2), texture: None, sampler: None, mutable: true), + (group: 0, binding: 0): (buffer: Some(0), texture: None, sampler: None, mutable: false), + (group: 0, binding: 1): (buffer: Some(1), texture: None, sampler: None, mutable: true), + (group: 0, binding: 2): (buffer: Some(2), texture: None, sampler: None, mutable: true), } ) diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl index b3aeca6e0..efb4a6968 100644 --- a/test-data/boids.wgsl +++ b/test-data/boids.wgsl @@ -16,12 +16,13 @@ import "GLSL.std.450" as std; # vertex shader -[[location 0]] var a_particlePos : vec2; -[[location 1]] var a_particleVel : vec2; -[[location 2]] var a_pos : vec2; -[[builtin position]] var gl_Position : vec4; +[[location(0)]] var a_particlePos : vec2; +[[location(1)]] var a_particleVel : vec2; +[[location(2)]] var a_pos : vec2; +[[builtin(position)]] var gl_Position : vec4; -fn vtx_main() -> void { +[[stage(vertex)]] +fn main() -> void { var angle : f32 = -std::atan2(a_particleVel.x, a_particleVel.y); var pos : vec2 = vec2( (a_pos.x * std::cos(angle)) - (a_pos.y * std::sin(angle)), @@ -29,45 +30,45 @@ fn vtx_main() -> void { gl_Position = vec4(pos + a_particlePos, 0.0, 1.0); return; } -entry_point vertex as "main" = vtx_main; # fragment shader -[[location 0]] var fragColor : vec4; +[[location(0)]] var fragColor : vec4; -fn frag_main() -> void { +[[stage(fragment)]] +fn main() -> void { fragColor = vec4(1.0, 1.0, 1.0, 1.0); return; } -entry_point fragment as "main" = frag_main; # compute shader type Particle = struct { - [[offset 0]] pos : vec2; - [[offset 8]] vel : vec2; + [[offset(0)]] pos : vec2; + [[offset(8)]] vel : vec2; }; type SimParams = struct { - [[offset 0]] deltaT : f32; - [[offset 4]] rule1Distance : f32; - [[offset 8]] rule2Distance : f32; - [[offset 12]] rule3Distance : f32; - [[offset 16]] rule1Scale : f32; - [[offset 20]] rule2Scale : f32; - [[offset 24]] rule3Scale : f32; + [[offset(0)]] deltaT : f32; + [[offset(4)]] rule1Distance : f32; + [[offset(8)]] rule2Distance : f32; + [[offset(12)]] rule3Distance : f32; + [[offset(16)]] rule1Scale : f32; + [[offset(20)]] rule2Scale : f32; + [[offset(24)]] rule3Scale : f32; }; type Particles = struct { - [[offset 0]] particles : [[stride 16]] array; + [[offset(0)]] particles : [[stride 16]] array; }; -[[binding 0, set 0]] var params : SimParams; -[[binding 1, set 0]] var particlesA : Particles; -[[binding 2, set 0]] var particlesB : Particles; +[[group(0), binding(0)]] var params : SimParams; +[[group(0), binding(1)]] var particlesA : Particles; +[[group(0), binding(2)]] var particlesB : Particles; -[[builtin global_invocation_id]] var gl_GlobalInvocationID : vec3; +[[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3; # https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp -fn compute_main() -> void { +[[stage(compute)]] +fn main() -> void { var index : u32 = gl_GlobalInvocationID.x; if (index >= 5) { return; @@ -148,5 +149,3 @@ fn compute_main() -> void { return; } -entry_point compute as "main" = compute_main; - diff --git a/test-data/function.wgsl b/test-data/function.wgsl index 7252e1cd1..5a968cadd 100644 --- a/test-data/function.wgsl +++ b/test-data/function.wgsl @@ -4,9 +4,8 @@ fn test_function(test: f32) -> f32 { return test; } -fn main_vert() -> void { +[[stage(vertex)]] +fn main() -> void { var foo: f32 = std::glsl::distance(0.0, 1.0); var test: f32 = test_function(1.0); } - -entry_point vertex as "main" = main_vert; \ No newline at end of file diff --git a/test-data/quad.wgsl b/test-data/quad.wgsl index 0e2dc08da..1e83ccd72 100644 --- a/test-data/quad.wgsl +++ b/test-data/quad.wgsl @@ -1,24 +1,24 @@ # vertex const c_scale: f32 = 1.2; -[[location 0]] var a_pos : vec2; -[[location 1]] var a_uv : vec2; -[[location 0]] var v_uv : vec2; -[[builtin position]] var o_position : vec4; +[[location(0)]] var a_pos : vec2; +[[location(1)]] var a_uv : vec2; +[[location(0)]] var v_uv : vec2; +[[builtin(position)]] var o_position : vec4; -fn main_vert() -> void { +[[stage(vertex)]] +fn main() -> void { o_position = vec4(c_scale * a_pos, 0.0, 1.0); return; } -entry_point vertex as "main" = main_vert; # fragment -[[location 0]] var a_uv : vec2; +[[location(0)]] var a_uv : vec2; #layout(set = 0, binding = 0) uniform texture2D u_texture; #layout(set = 0, binding = 1) uniform sampler u_sampler; -[[location 0]] var o_color : vec4; +[[location(0)]] var o_color : vec4; -fn main_frag() -> void { +[[stage(fragment)]] +fn main() -> void { o_color = vec4(1.0, 0.0, 0.0, 1.0); #TODO: sample return; } -entry_point fragment as "main" = main_frag; diff --git a/test-data/simple/simple.expected.ron b/test-data/simple/simple.expected.ron index 5d6863579..a4b55e443 100644 --- a/test-data/simple/simple.expected.ron +++ b/test-data/simple/simple.expected.ron @@ -64,58 +64,56 @@ ), ), ], - functions: [ - ( - name: Some("main"), - parameter_types: [], - return_type: None, - global_usage: [ - ( - bits: 1, - ), - ( - bits: 2, - ), - ], - local_variables: [ - ( - name: Some("w"), - ty: 3, - init: Some(3), - ), - ], - expressions: [ - GlobalVariable(1), - GlobalVariable(2), - Constant(1), - LocalVariable(1), - Constant(2), - Compose( - ty: 2, - components: [ - 1, - 5, - 4, - ], - ), - ], - body: [ - Empty, - Store( - pointer: 2, - value: 6, - ), - Return( - value: None, - ), - ], + functions: [], + entry_points: { + (Vertex, "main"): ( + early_depth_test: None, + workgroup_size: (1, 1, 1), + function: ( + name: Some("main"), + parameter_types: [], + return_type: None, + global_usage: [ + ( + bits: 1, + ), + ( + bits: 2, + ), + ], + local_variables: [ + ( + name: Some("w"), + ty: 3, + init: Some(3), + ), + ], + expressions: [ + GlobalVariable(1), + GlobalVariable(2), + Constant(1), + LocalVariable(1), + Constant(2), + Compose( + ty: 2, + components: [ + 1, + 5, + 4, + ], + ), + ], + body: [ + Empty, + Store( + pointer: 2, + value: 6, + ), + Return( + value: None, + ), + ], + ), ), - ], - entry_points: [ - ( - stage: Vertex, - name: "main", - function: 1, - ), - ], + }, ) \ No newline at end of file diff --git a/test-data/simple/simple.wgsl b/test-data/simple/simple.wgsl index 85eef7614..b35b83b42 100644 --- a/test-data/simple/simple.wgsl +++ b/test-data/simple/simple.wgsl @@ -1,10 +1,10 @@ # vertex -[[location 0]] var a_pos : vec2; -[[location 0]] var o_pos : vec4; +[[location(0)]] var a_pos : vec2; +[[location(0)]] var o_pos : vec4; +[[stage(vertex)]] fn main() -> void { var w: f32 = 1.0; o_pos = vec4(a_pos, 0.0, w); return; } -entry_point vertex as "main" = main; diff --git a/tests/convert.rs b/tests/convert.rs index d6a1243c3..97dbe8409 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -33,7 +33,10 @@ fn convert_quad() { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); binding_map.insert( - msl::BindSource { set: 0, binding: 0 }, + msl::BindSource { + group: 0, + binding: 0, + }, msl::BindTarget { buffer: None, texture: Some(1), @@ -42,7 +45,10 @@ fn convert_quad() { }, ); binding_map.insert( - msl::BindSource { set: 0, binding: 1 }, + msl::BindSource { + group: 0, + binding: 1, + }, msl::BindTarget { buffer: None, texture: None, @@ -67,7 +73,10 @@ fn convert_boids() { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); binding_map.insert( - msl::BindSource { set: 0, binding: 0 }, + msl::BindSource { + group: 0, + binding: 0, + }, msl::BindTarget { buffer: Some(0), texture: None, @@ -76,7 +85,10 @@ fn convert_boids() { }, ); binding_map.insert( - msl::BindSource { set: 0, binding: 1 }, + msl::BindSource { + group: 0, + binding: 1, + }, msl::BindTarget { buffer: Some(1), texture: None, @@ -85,7 +97,10 @@ fn convert_boids() { }, ); binding_map.insert( - msl::BindSource { set: 0, binding: 2 }, + msl::BindSource { + group: 0, + binding: 2, + }, msl::BindTarget { buffer: Some(2), texture: None, @@ -113,7 +128,10 @@ fn convert_cube() { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); binding_map.insert( - msl::BindSource { set: 0, binding: 0 }, + msl::BindSource { + group: 0, + binding: 0, + }, msl::BindTarget { buffer: Some(0), texture: None, @@ -122,7 +140,10 @@ fn convert_cube() { }, ); binding_map.insert( - msl::BindSource { set: 0, binding: 1 }, + msl::BindSource { + group: 0, + binding: 1, + }, msl::BindTarget { buffer: None, texture: Some(1), @@ -131,7 +152,10 @@ fn convert_cube() { }, ); binding_map.insert( - msl::BindSource { set: 0, binding: 2 }, + msl::BindSource { + group: 0, + binding: 2, + }, msl::BindTarget { buffer: None, texture: None, @@ -154,9 +178,7 @@ fn convert_phong_lighting() { let module = load_glsl( "glsl_phong_lighting.frag", "main", - naga::ShaderStage::Fragment { - early_depth_test: None, - }, + naga::ShaderStage::Fragment, ); naga::proc::Validator::new().validate(&module).unwrap(); @@ -176,9 +198,7 @@ fn convert_phong_lighting() { // let module = load_glsl( // "glsl_constant_expression.vert", // "main", -// naga::ShaderStage::Fragment { -// early_depth_test: None, -// }, +// naga::ShaderStage::Fragment, // ); // naga::proc::Validator::new().validate(&module).unwrap(); // } From 081b90f11765c8afaf9f26cbe7030781bb4155c9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 17 Sep 2020 01:17:25 -0400 Subject: [PATCH 0207/2212] Consolidate rosetta tests --- examples/convert.rs | 9 +-- src/arena.rs | 1 + src/back/spv/mod.rs | 3 - src/back/spv/rosetta_tests.rs | 17 ----- src/front/glsl/ast.rs | 4 +- src/front/glsl/mod.rs | 5 +- src/front/glsl/parser_tests.rs | 2 +- src/front/glsl/rosetta_tests.rs | 21 ------ src/front/wgsl/mod.rs | 2 - src/front/wgsl/rosetta_tests.rs | 21 ------ .../{simple.expected.ron => module.ron} | 0 test-data/simple/{simple.spv => x.spv} | Bin test-data/simple/{simple.vert => x.vert} | 0 test-data/simple/{simple.wgsl => x.wgsl} | 0 tests/convert.rs | 2 +- tests/rosetta.rs | 60 ++++++++++++++++++ 16 files changed, 69 insertions(+), 78 deletions(-) delete mode 100644 src/back/spv/rosetta_tests.rs delete mode 100644 src/front/glsl/rosetta_tests.rs delete mode 100644 src/front/wgsl/rosetta_tests.rs rename test-data/simple/{simple.expected.ron => module.ron} (100%) rename test-data/simple/{simple.spv => x.spv} (100%) rename test-data/simple/{simple.vert => x.vert} (100%) rename test-data/simple/{simple.wgsl => x.wgsl} (100%) create mode 100644 tests/rosetta.rs diff --git a/examples/convert.rs b/examples/convert.rs index dda2eb400..d1834b6b5 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -48,20 +48,17 @@ fn main() { #[cfg(feature = "glsl-in")] "vert" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Vertex) - .unwrap() + naga::front::glsl::parse_str(&input, "main", naga::ShaderStage::Vertex).unwrap() } #[cfg(feature = "glsl-in")] "frag" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Fragment) - .unwrap() + naga::front::glsl::parse_str(&input, "main", naga::ShaderStage::Fragment).unwrap() } #[cfg(feature = "glsl-in")] "comp" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main".to_string(), naga::ShaderStage::Compute) - .unwrap() + naga::front::glsl::parse_str(&input, "main", naga::ShaderStage::Compute).unwrap() } #[cfg(feature = "deserialize")] "ron" => { diff --git a/src/arena.rs b/src/arena.rs index ea2adcdda..1727da30d 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -91,6 +91,7 @@ impl Handle { any(feature = "serialize", feature = "deserialize"), serde(transparent) )] +#[cfg_attr(test, derive(PartialEq))] pub struct Arena { /// Values of this arena. data: Vec, diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 6709e59ee..15f159835 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -9,9 +9,6 @@ mod test_framework; #[cfg(test)] mod layout_tests; -#[cfg(all(test, feature = "deserialize"))] -mod rosetta_tests; - pub use writer::Writer; use spirv::*; diff --git a/src/back/spv/rosetta_tests.rs b/src/back/spv/rosetta_tests.rs deleted file mode 100644 index 4552ca13b..000000000 --- a/src/back/spv/rosetta_tests.rs +++ /dev/null @@ -1,17 +0,0 @@ -use std::{fs, path::Path}; - -const TEST_PATH: &str = "test-data"; - -fn rosetta_test(file_name: &str) { - let test_dir = Path::new(TEST_PATH); - let input = fs::read_to_string(test_dir.join(file_name)).unwrap(); - let module: crate::Module = ron::de::from_str(&input).unwrap(); - - let spv = super::Writer::new(&module.header, super::WriterFlags::NONE).write(&module); - assert!(spv.len() > 0, "spv.len() > 0"); -} - -#[test] -fn simple() { - rosetta_test("simple/simple.expected.ron") -} diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 2a32234e4..a0233ec04 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -17,12 +17,12 @@ pub struct Program { } impl Program { - pub fn new(shader_stage: ShaderStage, entry: String) -> Program { + pub fn new(shader_stage: ShaderStage, entry: &str) -> Program { Program { version: 0, profile: Profile::Core, shader_stage, - entry: Some(entry), + entry: Some(entry.to_string()), lookup_function: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_global_variables: FastHashMap::default(), diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index ca0ddaad8..c711b3119 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -17,10 +17,7 @@ mod token; mod types; mod variables; -#[cfg(all(test, feature = "serialize"))] -mod rosetta_tests; - -pub fn parse_str(source: &str, entry: String, stage: ShaderStage) -> Result { +pub fn parse_str(source: &str, entry: &str, stage: ShaderStage) -> Result { log::debug!("------ GLSL-pomelo ------"); let mut program = Program::new(stage, entry); diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 4a7cae899..285df911d 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -5,7 +5,7 @@ use super::parser; use crate::ShaderStage; fn parse_program(source: &str, stage: ShaderStage) -> Result { - let mut program = Program::new(stage, "".to_string()); + let mut program = Program::new(stage, ""); let lex = Lexer::new(source); let mut parser = parser::Parser::new(&mut program); diff --git a/src/front/glsl/rosetta_tests.rs b/src/front/glsl/rosetta_tests.rs deleted file mode 100644 index eb7a01696..000000000 --- a/src/front/glsl/rosetta_tests.rs +++ /dev/null @@ -1,21 +0,0 @@ -use difference::assert_diff; -use std::{fs, path::Path}; - -const TEST_PATH: &str = "test-data"; - -fn rosetta_test(file_name: &str, stage: crate::ShaderStage) { - let test_dir = Path::new(TEST_PATH); - let input = fs::read_to_string(test_dir.join(file_name)).unwrap(); - let expected = - fs::read_to_string(test_dir.join(file_name).with_extension("expected.ron")).unwrap(); - - let module = super::parse_str(&input, "main".to_string(), stage).unwrap(); - let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); - - assert_diff!(output.as_str(), expected.as_str(), "", 0); -} - -#[test] -fn simple() { - rosetta_test("simple/simple.vert", crate::ShaderStage::Vertex) -} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index ed0feb831..15b70f835 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3,8 +3,6 @@ //! [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html mod lexer; -#[cfg(all(test, feature = "serialize"))] -mod rosetta_tests; use crate::{ arena::{Arena, Handle}, diff --git a/src/front/wgsl/rosetta_tests.rs b/src/front/wgsl/rosetta_tests.rs deleted file mode 100644 index a4e7179a3..000000000 --- a/src/front/wgsl/rosetta_tests.rs +++ /dev/null @@ -1,21 +0,0 @@ -use difference::assert_diff; -use std::{fs, path::Path}; - -const TEST_PATH: &str = "test-data"; - -fn rosetta_test(file_name: &str) { - let test_dir = Path::new(TEST_PATH); - let input = fs::read_to_string(test_dir.join(file_name)).unwrap(); - let expected = - fs::read_to_string(test_dir.join(file_name).with_extension("expected.ron")).unwrap(); - - let module = crate::front::wgsl::parse_str(&input).unwrap(); - let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); - - assert_diff!(output.as_str(), expected.as_str(), "", 0); -} - -#[test] -fn simple() { - rosetta_test("simple/simple.wgsl") -} diff --git a/test-data/simple/simple.expected.ron b/test-data/simple/module.ron similarity index 100% rename from test-data/simple/simple.expected.ron rename to test-data/simple/module.ron diff --git a/test-data/simple/simple.spv b/test-data/simple/x.spv similarity index 100% rename from test-data/simple/simple.spv rename to test-data/simple/x.spv diff --git a/test-data/simple/simple.vert b/test-data/simple/x.vert similarity index 100% rename from test-data/simple/simple.vert rename to test-data/simple/x.vert diff --git a/test-data/simple/simple.wgsl b/test-data/simple/x.wgsl similarity index 100% rename from test-data/simple/simple.wgsl rename to test-data/simple/x.wgsl diff --git a/tests/convert.rs b/tests/convert.rs index 97dbe8409..b0ec3cc49 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -20,7 +20,7 @@ fn load_spv(name: &str) -> naga::Module { #[cfg(feature = "glsl-in")] fn load_glsl(name: &str, entry: &str, stage: naga::ShaderStage) -> naga::Module { let input = load_test_data(name); - naga::front::glsl::parse_str(&input, entry.to_owned(), stage).unwrap() + naga::front::glsl::parse_str(&input, entry, stage).unwrap() } #[cfg(feature = "wgsl-in")] diff --git a/tests/rosetta.rs b/tests/rosetta.rs new file mode 100644 index 000000000..9ca096c80 --- /dev/null +++ b/tests/rosetta.rs @@ -0,0 +1,60 @@ +use std::{fs, path::Path}; + +fn test_rosetta(dir_name: &str) { + let dir_path = Path::new("test-data").join(dir_name); + #[cfg_attr(not(feature = "serde"), allow(unused))] + let expected = fs::read_to_string(dir_path.join("module.ron")).unwrap(); + + #[cfg(feature = "deserialize")] + { + use naga::back::*; + let module = ron::de::from_str::(&expected).unwrap(); + + #[cfg(feature = "spv-out")] + { + let spv = spv::Writer::new(&module.header, spv::WriterFlags::NONE).write(&module); + assert!(spv.len() > 0); + } + } + + #[cfg(feature = "serialize")] + { + use naga::front::*; + + fn check(name: &str, module: &naga::Module, expected: &str) { + let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); + if output != expected { + let changeset = difference::Changeset::new(expected, &output, ""); + panic!("'{}' failed with diff:\n{}", name, changeset); + } + } + + #[cfg(feature = "wgsl-in")] + { + let input = fs::read_to_string(dir_path.join("x.wgsl")).unwrap(); + let module = wgsl::parse_str(&input).unwrap(); + check("wgsl", &module, &expected); + } + + #[cfg(feature = "glsl-in")] + { + if let Ok(input) = fs::read_to_string(dir_path.join("x.vert")) { + let module = glsl::parse_str(&input, "main", naga::ShaderStage::Vertex).unwrap(); + check("vert", &module, &expected); + } + if let Ok(input) = fs::read_to_string(dir_path.join("x.frag")) { + let module = glsl::parse_str(&input, "main", naga::ShaderStage::Fragment).unwrap(); + check("frag", &module, &expected); + } + if let Ok(input) = fs::read_to_string(dir_path.join("x.comp")) { + let module = glsl::parse_str(&input, "main", naga::ShaderStage::Compute).unwrap(); + check("comp", &module, &expected); + } + } + } +} + +#[test] +fn simple() { + test_rosetta("simple"); +} From 1c3f4513dea6e1e27a8c44867102fec18817fdf5 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 17 Sep 2020 06:06:26 +0000 Subject: [PATCH 0208/2212] [glsl.in] Implement field lookup --- src/front/glsl/ast.rs | 29 +++++++++++++++++++++++++++++ src/front/glsl/error.rs | 2 ++ src/front/glsl/parser.rs | 39 ++++++++++++++++++++++++++------------- 3 files changed, 57 insertions(+), 13 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index a0233ec04..bd8f12595 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,4 +1,6 @@ +use super::error::ErrorKind; use crate::{ + proc::{ResolveContext, Typifier}, Arena, BinaryOperator, Binding, Expression, FastHashMap, Function, GlobalVariable, Handle, Interpolation, LocalVariable, Module, ShaderStage, Statement, StorageClass, Type, }; @@ -31,6 +33,7 @@ impl Program { local_variables: Arena::::new(), scopes: vec![FastHashMap::default()], lookup_global_var_exps: FastHashMap::default(), + typifier: Typifier::new(), }, module: Module::generate_empty(), } @@ -48,6 +51,31 @@ impl Program { right: right.expression, })) } + + pub fn resolve_type( + &mut self, + handle: Handle, + ) -> Result<&crate::TypeInner, ErrorKind> { + let functions = Arena::new(); //TODO + let parameter_types: Vec> = vec![]; //TODO + let resolve_ctx = ResolveContext { + constants: &self.module.constants, + global_vars: &self.module.global_variables, + local_vars: &self.context.local_variables, + functions: &functions, + parameter_types: ¶meter_types, + }; + match self.context.typifier.grow( + handle, + &self.context.expressions, + &mut self.module.types, + &resolve_ctx, + ) { + //TODO: better error report + Err(_) => Err(ErrorKind::SemanticError("Can't resolve type")), + Ok(()) => Ok(self.context.typifier.get(handle, &self.module.types)), + } + } } #[derive(Debug)] @@ -62,6 +90,7 @@ pub struct Context { //TODO: Find less allocation heavy representation pub scopes: Vec>>, pub lookup_global_var_exps: FastHashMap>, + pub typifier: Typifier, } impl Context { diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 61bd7759f..0194544a6 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -14,6 +14,7 @@ pub enum ErrorKind { ParserStackOverflow, NotImplemented(&'static str), UnknownVariable(TokenMetadata, String), + UnknownField(TokenMetadata, String), #[cfg(feature = "glsl-validate")] VariableAlreadyDeclared(String), #[cfg(feature = "glsl-validate")] @@ -41,6 +42,7 @@ impl fmt::Display for ErrorKind { ErrorKind::UnknownVariable(meta, val) => { write!(f, "Unknown variable {} at {:?}", val, meta) } + ErrorKind::UnknownField(meta, val) => write!(f, "Unknown field {} at {:?}", val, meta), #[cfg(feature = "glsl-validate")] ErrorKind::VariableAlreadyDeclared(val) => { write!(f, "Variable {} already decalred in current scope", val) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 4b6385509..e2c112bc7 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -5,10 +5,10 @@ pomelo! { //%verbose; %include { use super::super::{error::ErrorKind, token::*, ast::*}; - use crate::{Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, EntryPoint, Expression, - Function, GlobalVariable, Handle, LocalVariable, MemberOrigin, ScalarKind, - Statement, StorageAccess, StorageClass, StructMember, Type, TypeInner, - Interpolation}; + use crate::{proc::Typifier, Arena, BinaryOperator, Binding, Block, Constant, + ConstantInner, EntryPoint, Expression, Function, GlobalVariable, Handle, Interpolation, + LocalVariable, MemberOrigin, ScalarKind, Statement, StorageAccess, + StorageClass, StructMember, Type, TypeInner}; } %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; %parser pub struct Parser<'a> {}; @@ -213,20 +213,32 @@ pomelo! { postfix_expression ::= primary_expression; postfix_expression ::= postfix_expression LeftBracket integer_expression RightBracket { - // TODO + //TODO return Err(ErrorKind::NotImplemented("[]")) } postfix_expression ::= function_call; - postfix_expression ::= postfix_expression Dot FieldSelection { - // TODO - return Err(ErrorKind::NotImplemented(".field")) + postfix_expression ::= postfix_expression(e) Dot Identifier(i) /* FieldSelection in spec */ { + let type_inner = extra.resolve_type(e.expression)?; + if let TypeInner::Struct{members} = type_inner { + let index = members.iter().position(|m| m.name == Some(i.1.clone())) + .ok_or(ErrorKind::UnknownField(i.0, i.1))?; + ExpressionRule::from_expression( + extra.context.expressions.append(Expression::AccessIndex { + base: e.expression, + index: index as u32, + }) + ) + } else { + //TODO: swizzle + return Err(ErrorKind::SemanticError("Can't lookup field on this type")) + } } postfix_expression ::= postfix_expression(pe) IncOp { - // TODO + //TODO return Err(ErrorKind::NotImplemented("post++")) } postfix_expression ::= postfix_expression(pe) DecOp { - // TODO + //TODO return Err(ErrorKind::NotImplemented("post--")) } @@ -292,15 +304,15 @@ pomelo! { unary_expression ::= postfix_expression; unary_expression ::= IncOp unary_expression { - // TODO + //TODO return Err(ErrorKind::NotImplemented("++pre")) } unary_expression ::= DecOp unary_expression { - // TODO + //TODO return Err(ErrorKind::NotImplemented("--pre")) } unary_expression ::= unary_operator unary_expression { - // TODO + //TODO return Err(ErrorKind::NotImplemented("unary_op")) } @@ -877,6 +889,7 @@ pomelo! { std::mem::swap(&mut f.local_variables, &mut extra.context.local_variables); extra.context.clear_scopes(); extra.context.lookup_global_var_exps.clear(); + extra.context.typifier = Typifier::new(); f.body = cs; f.fill_global_use(&extra.module.global_variables); f From 14feb9ac017a4880389b7b3a29f2c0fac8561819 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 17 Sep 2020 14:00:50 -0400 Subject: [PATCH 0209/2212] Validation of global variables and entry points --- src/front/glsl/parser.rs | 2 +- src/front/wgsl/mod.rs | 36 ++-- src/proc/validator.rs | 329 +++++++++++++++++++++++++++++++++--- test-data/boids.wgsl | 2 +- test-data/simple/module.ron | 2 +- tests/rosetta.rs | 1 + 6 files changed, 333 insertions(+), 39 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index e2c112bc7..e6ee55635 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -846,7 +846,7 @@ pomelo! { (extra.shader_stage, name), EntryPoint { early_depth_test: None, - workgroup_size: [1; 3], //TODO + workgroup_size: [0; 3], //TODO function: f, }, ); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 15b70f835..da5457be6 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -431,7 +431,7 @@ impl Parser { inner } _ => { - let (composite_ty, _) = self.parse_type_decl(lexer, None, type_arena)?; + let composite_ty = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -527,7 +527,7 @@ impl Parser { expr } else { *lexer = backup; - let (ty, _) = self.parse_type_decl(lexer, None, ctx.types)?; + let ty = self.parse_type_decl(lexer, None, ctx.types)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -856,7 +856,7 @@ impl Parser { ) -> Result<(&'a str, Handle), Error<'a>> { let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let (ty, _) = self.parse_type_decl(lexer, None, type_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena)?; Ok((name, ty)) } @@ -875,7 +875,12 @@ impl Parser { } let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let (ty, access) = self.parse_type_decl(lexer, None, type_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena)?; + let access = match class { + Some(crate::StorageClass::StorageBuffer) => crate::StorageAccess::all(), + Some(crate::StorageClass::Constant) => crate::StorageAccess::LOAD, + _ => crate::StorageAccess::empty(), + }; if lexer.skip(Token::Operation('=')) { let _inner = self.parse_const_expression(lexer, type_arena, const_arena)?; //TODO @@ -930,7 +935,7 @@ impl Parser { return Err(Error::MissingMemberOffset(name)); } lexer.expect(Token::Separator(':'))?; - let (ty, _) = self.parse_type_decl(lexer, None, type_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Separator(';'))?; members.push(crate::StructMember { name: Some(name.to_owned()), @@ -945,7 +950,7 @@ impl Parser { lexer: &mut Lexer<'a>, self_name: Option<&'a str>, type_arena: &mut Arena, - ) -> Result<(Handle, crate::StorageAccess), Error<'a>> { + ) -> Result, Error<'a>> { self.scopes.push(Scope::TypeDecl); let decoration_lexer = if lexer.skip(Token::DoubleParen('[')) { Some(lexer.take_until(Token::DoubleParen(']'))?) @@ -1075,13 +1080,13 @@ impl Parser { lexer.expect(Token::Paren('<'))?; let class = Self::get_storage_class(lexer.next_ident()?)?; lexer.expect(Token::Separator(','))?; - let (base, _) = self.parse_type_decl(lexer, None, type_arena)?; + let base = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Paren('>'))?; crate::TypeInner::Pointer { base, class } } Token::Word("array") => { lexer.expect(Token::Paren('<'))?; - let (base, _) = self.parse_type_decl(lexer, None, type_arena)?; + let base = self.parse_type_decl(lexer, None, type_arena)?; let size = match lexer.next() { Token::Separator(',') => { let value = lexer.next_uint_literal()?; @@ -1120,7 +1125,7 @@ impl Parser { Token::Word(name) => { self.scopes.pop(); return match self.lookup_type.get(name) { - Some(&handle) => Ok((handle, crate::StorageAccess::empty())), + Some(&handle) => Ok(handle), None => Err(Error::UnknownType(name)), }; } @@ -1132,7 +1137,7 @@ impl Parser { name: self_name.map(|s| s.to_string()), inner, }); - Ok((handle, crate::StorageAccess::empty())) + Ok(handle) } fn parse_statement<'a>( @@ -1314,7 +1319,7 @@ impl Parser { let return_type = if lexer.skip(Token::Word("void")) { None } else { - Some(self.parse_type_decl(lexer, None, &mut module.types)?.0) + Some(self.parse_type_decl(lexer, None, &mut module.types)?) }; let mut fun = crate::Function { @@ -1360,7 +1365,7 @@ impl Parser { // Perspective is the default qualifier. let mut interpolation = None; let mut stage = None; - let mut workgroup_size = [1u32; 3]; + let mut workgroup_size = [0u32; 3]; if lexer.skip(Token::DoubleParen('[')) { let (mut bind_index, mut bind_group) = (None, None); @@ -1409,6 +1414,11 @@ impl Parser { other => return Err(Error::Unexpected(other)), } } + for size in workgroup_size.iter_mut() { + if *size == 0 { + *size = 1; + } + } } word => return Err(Error::UnknownDecoration(word)), } @@ -1455,7 +1465,7 @@ impl Parser { Token::Word("type") => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; - let (ty, _) = self.parse_type_decl(lexer, Some(name), &mut module.types)?; + let ty = self.parse_type_decl(lexer, Some(name), &mut module.types)?; self.lookup_type.insert(name.to_owned(), ty); lexer.expect(Token::Separator(';'))?; } diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 7d26f1441..1c6fcc59c 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -1,5 +1,10 @@ use super::typifier::{ResolveContext, ResolveError, Typifier}; -use crate::arena::Handle; +use crate::arena::{Arena, Handle}; + +const MAX_BIND_GROUPS: u32 = 8; +const MAX_LOCATIONS: u32 = 64; // using u64 mask +const MAX_BIND_INDICES: u32 = 64; // using u64 mask +const MAX_WORKGROUP_SIZE: u32 = 0x4000; #[derive(Debug)] pub struct Validator { @@ -9,17 +14,65 @@ pub struct Validator { } #[derive(Clone, Debug, thiserror::Error)] -pub enum ValidationError { - #[error("The type width is not supported")] - InvalidTypeWidth(crate::ScalarKind, crate::Bytes), - #[error("The type handle can not be resolved")] - UnresolvedType(Handle), - #[error("Expression type can't be resolved")] - Resolve(Handle, ResolveError), +pub enum GlobalVariableError { + #[error("Usage isn't compatible with the storage class")] + InvalidUsage, + #[error("Type isn't compatible with the storage class")] + InvalidType, + #[error("Interpolation is not valid")] + InvalidInterpolation, + #[error("Storage access flags are invalid")] + InvalidStorageAccess, + #[error("Binding decoration is missing or not applicable")] + InvalidBinding, + #[error("Binding is out of range")] + OutOfRangeBinding, +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum FunctionError { + #[error(transparent)] + Resolve(#[from] ResolveError), #[error("There are instructions after `return`/`break`/`continue`")] InvalidControlFlowExitTail, } +#[derive(Clone, Debug, thiserror::Error)] +pub enum EntryPointError { + #[error("Early depth test is not applicable")] + UnexpectedEarlyDepthTest, + #[error("Workgroup size is not applicable")] + UnexpectedWorkgroupSize, + #[error("Workgroup size is out of range")] + OutOfRangeWorkgroupSize, + #[error("Global variable {0:?} is used incorrectly as {1:?}")] + InvalidGlobalUsage(Handle, crate::GlobalUse), + #[error("Bindings for {0:?} conflict with other global variables")] + BindingCollision(Handle), + #[error("Built-in {0:?} is not applicable to this entry point")] + InvalidBuiltIn(crate::BuiltIn), + #[error(transparent)] + Function(#[from] FunctionError), +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum ValidationError<'a> { + #[error("The type {0:?} width {1} is not supported")] + InvalidTypeWidth(crate::ScalarKind, crate::Bytes), + #[error("The type handle {0:?} can not be resolved")] + UnresolvedType(Handle), + #[error("Global variable {0:?} is invalid: {1:?}")] + GlobalVariable(Handle, GlobalVariableError), + #[error("Function {0:?} is invalid: {1:?}")] + Function(Handle, FunctionError), + #[error("Entry point {name} at {stage:?} is invalid: {error:?}")] + EntryPoint { + stage: crate::ShaderStage, + name: &'a str, + error: EntryPointError, + }, +} + impl Validator { /// Construct a new validator instance. pub fn new() -> Self { @@ -28,8 +81,240 @@ impl Validator { } } + fn validate_global_var( + &self, + var: &crate::GlobalVariable, + types: &Arena, + ) -> Result<(), GlobalVariableError> { + log::debug!("var {:?}", var); + let is_storage = match var.class { + crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), + crate::StorageClass::Input | crate::StorageClass::Output => { + match var.binding { + Some(crate::Binding::BuiltIn(_)) => { + // validated per entry point + if var.interpolation.is_some() { + return Err(GlobalVariableError::InvalidInterpolation); + } + } + Some(crate::Binding::Location(loc)) => { + if loc > MAX_LOCATIONS { + return Err(GlobalVariableError::OutOfRangeBinding); + } + match types[var.ty].inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } + | crate::TypeInner::Matrix { kind, .. } => { + if kind != crate::ScalarKind::Float + && var.interpolation != Some(crate::Interpolation::Flat) + { + return Err(GlobalVariableError::InvalidInterpolation); + } + } + _ => return Err(GlobalVariableError::InvalidType), + } + } + Some(crate::Binding::Resource { .. }) => { + return Err(GlobalVariableError::InvalidBinding) + } + None => { + match types[var.ty].inner { + //TODO: check the member types + crate::TypeInner::Struct { members: _ } => { + if var.interpolation.is_some() { + return Err(GlobalVariableError::InvalidInterpolation); + } + } + _ => return Err(GlobalVariableError::InvalidType), + } + } + } + false + } + crate::StorageClass::Constant + | crate::StorageClass::StorageBuffer + | crate::StorageClass::Uniform => { + match var.binding { + Some(crate::Binding::BuiltIn(_)) => {} // validated per entry point + Some(crate::Binding::Resource { group, binding }) => { + if group > MAX_BIND_GROUPS || binding > MAX_BIND_INDICES { + return Err(GlobalVariableError::OutOfRangeBinding); + } + } + Some(crate::Binding::Location(_)) | None => { + return Err(GlobalVariableError::InvalidBinding) + } + } + if var.interpolation.is_some() { + return Err(GlobalVariableError::InvalidInterpolation); + } + //TODO: prevent `Uniform` storage class with `STORE` access + match types[var.ty].inner { + crate::TypeInner::Struct { .. } + | crate::TypeInner::Image { + class: crate::ImageClass::Storage(_), + .. + } => true, + _ => false, + } + } + crate::StorageClass::Private | crate::StorageClass::WorkGroup => { + if var.binding.is_some() { + return Err(GlobalVariableError::InvalidBinding); + } + if var.interpolation.is_some() { + return Err(GlobalVariableError::InvalidInterpolation); + } + false + } + }; + + if !is_storage && !var.storage_access.is_empty() { + return Err(GlobalVariableError::InvalidStorageAccess); + } + + Ok(()) + } + + fn validate_function( + &mut self, + fun: &crate::Function, + module: &crate::Module, + ) -> Result<(), FunctionError> { + let resolve_ctx = ResolveContext { + constants: &module.constants, + global_vars: &module.global_variables, + local_vars: &fun.local_variables, + functions: &module.functions, + parameter_types: &fun.parameter_types, + }; + self.typifier + .resolve_all(&fun.expressions, &module.types, &resolve_ctx)?; + Ok(()) + } + + fn validate_entry_point( + &mut self, + ep: &crate::EntryPoint, + stage: crate::ShaderStage, + module: &crate::Module, + ) -> Result<(), EntryPointError> { + if ep.early_depth_test.is_some() && stage != crate::ShaderStage::Fragment { + return Err(EntryPointError::UnexpectedEarlyDepthTest); + } + if stage == crate::ShaderStage::Compute { + if ep + .workgroup_size + .iter() + .any(|&s| s == 0 || s > MAX_WORKGROUP_SIZE) + { + return Err(EntryPointError::OutOfRangeWorkgroupSize); + } + } else if ep.workgroup_size != [0; 3] { + return Err(EntryPointError::UnexpectedWorkgroupSize); + } + + let mut bind_group_masks = [0u64; MAX_BIND_GROUPS as usize]; + let mut location_in_mask = 0u64; + let mut location_out_mask = 0u64; + for ((var_handle, var), &usage) in module + .global_variables + .iter() + .zip(&ep.function.global_usage) + { + if usage.is_empty() { + continue; + } + + let allowed_usage = match var.class { + crate::StorageClass::Function => unreachable!(), + crate::StorageClass::Input => { + let mask = match var.binding { + Some(crate::Binding::BuiltIn(built_in)) => match (stage, built_in) { + (crate::ShaderStage::Vertex, crate::BuiltIn::BaseInstance) + | (crate::ShaderStage::Vertex, crate::BuiltIn::BaseVertex) + | (crate::ShaderStage::Vertex, crate::BuiltIn::InstanceIndex) + | (crate::ShaderStage::Vertex, crate::BuiltIn::VertexIndex) + | (crate::ShaderStage::Fragment, crate::BuiltIn::PointSize) + | (crate::ShaderStage::Fragment, crate::BuiltIn::FragCoord) + | (crate::ShaderStage::Fragment, crate::BuiltIn::FrontFacing) + | (crate::ShaderStage::Fragment, crate::BuiltIn::SampleIndex) + | (crate::ShaderStage::Compute, crate::BuiltIn::GlobalInvocationId) + | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationId) + | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationIndex) + | (crate::ShaderStage::Compute, crate::BuiltIn::WorkGroupId) => 0, + _ => return Err(EntryPointError::InvalidBuiltIn(built_in)), + }, + Some(crate::Binding::Location(loc)) => 1 << loc, + Some(crate::Binding::Resource { .. }) => unreachable!(), + None => 0, + }; + if location_in_mask & mask != 0 { + return Err(EntryPointError::BindingCollision(var_handle)); + } + location_in_mask |= mask; + crate::GlobalUse::LOAD + } + crate::StorageClass::Output => { + let mask = match var.binding { + Some(crate::Binding::BuiltIn(built_in)) => match (stage, built_in) { + (crate::ShaderStage::Vertex, crate::BuiltIn::Position) + | (crate::ShaderStage::Vertex, crate::BuiltIn::PointSize) + | (crate::ShaderStage::Vertex, crate::BuiltIn::ClipDistance) + | (crate::ShaderStage::Fragment, crate::BuiltIn::FragDepth) => 0, + _ => return Err(EntryPointError::InvalidBuiltIn(built_in)), + }, + Some(crate::Binding::Location(loc)) => 1 << loc, + Some(crate::Binding::Resource { .. }) => unreachable!(), + None => 0, + }; + if location_out_mask & mask != 0 { + return Err(EntryPointError::BindingCollision(var_handle)); + } + location_out_mask |= mask; + crate::GlobalUse::STORE + } + crate::StorageClass::Constant => crate::GlobalUse::LOAD, + crate::StorageClass::Uniform | crate::StorageClass::StorageBuffer => { + //TODO: built-in checks? + let mut storage_usage = crate::GlobalUse::empty(); + if var.storage_access.contains(crate::StorageAccess::LOAD) { + storage_usage |= crate::GlobalUse::LOAD; + } + if var.storage_access.contains(crate::StorageAccess::STORE) { + storage_usage |= crate::GlobalUse::STORE; + } + if storage_usage.is_empty() { + // its a uniform buffer + crate::GlobalUse::LOAD + } else { + storage_usage + } + } + crate::StorageClass::Private | crate::StorageClass::WorkGroup => { + crate::GlobalUse::all() + } + }; + if !allowed_usage.contains(usage) { + return Err(EntryPointError::InvalidGlobalUsage(var_handle, usage)); + } + + if let Some(crate::Binding::Resource { group, binding }) = var.binding { + let mask = 1 << binding; + let group_mask = &mut bind_group_masks[group as usize]; + if *group_mask & mask != 0 { + return Err(EntryPointError::BindingCollision(var_handle)); + } + *group_mask |= mask; + } + } + + self.validate_function(&ep.function, module)?; + Ok(()) + } + /// Check the given module to be valid. - pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { + pub fn validate<'a>(&mut self, module: &'a crate::Module) -> Result<(), ValidationError<'a>> { // check the types for (handle, ty) in module.types.iter() { use crate::TypeInner as Ti; @@ -68,21 +353,19 @@ impl Validator { } } - // check the type resolution of expressions + for (var_handle, var) in module.global_variables.iter() { + self.validate_global_var(var, &module.types) + .map_err(|e| ValidationError::GlobalVariable(var_handle, e))?; + } + for (fun_handle, fun) in module.functions.iter() { - let resolve_ctx = ResolveContext { - constants: &module.constants, - global_vars: &module.global_variables, - local_vars: &fun.local_variables, - functions: &module.functions, - parameter_types: &fun.parameter_types, - }; - if let Err(e) = self - .typifier - .resolve_all(&fun.expressions, &module.types, &resolve_ctx) - { - return Err(ValidationError::Resolve(fun_handle, e)); - } + self.validate_function(fun, module) + .map_err(|e| ValidationError::Function(fun_handle, e))?; + } + + for (&(stage, ref name), entry_point) in module.entry_points.iter() { + self.validate_entry_point(entry_point, stage, module) + .map_err(|error| ValidationError::EntryPoint { stage, name, error })?; } Ok(()) diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl index efb4a6968..6e4cf7c67 100644 --- a/test-data/boids.wgsl +++ b/test-data/boids.wgsl @@ -67,7 +67,7 @@ type Particles = struct { [[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3; # https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp -[[stage(compute)]] +[[stage(compute), workgroup_size(1)]] fn main() -> void { var index : u32 = gl_GlobalInvocationID.x; if (index >= 5) { diff --git a/test-data/simple/module.ron b/test-data/simple/module.ron index a4b55e443..b45c6b417 100644 --- a/test-data/simple/module.ron +++ b/test-data/simple/module.ron @@ -68,7 +68,7 @@ entry_points: { (Vertex, "main"): ( early_depth_test: None, - workgroup_size: (1, 1, 1), + workgroup_size: (0, 0, 0), function: ( name: Some("main"), parameter_types: [], diff --git a/tests/rosetta.rs b/tests/rosetta.rs index 9ca096c80..70da9922b 100644 --- a/tests/rosetta.rs +++ b/tests/rosetta.rs @@ -9,6 +9,7 @@ fn test_rosetta(dir_name: &str) { { use naga::back::*; let module = ron::de::from_str::(&expected).unwrap(); + naga::proc::Validator::new().validate(&module).unwrap(); #[cfg(feature = "spv-out")] { From 7aff39784bc4a06897ed213b81aa72f713f1658f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 17 Sep 2020 23:20:02 -0400 Subject: [PATCH 0210/2212] [wgsl] texture operations --- Makefile | 8 +- examples/convert.rs | 4 + src/back/msl.rs | 46 +++--- src/front/wgsl/lexer.rs | 42 ++++++ src/front/wgsl/mod.rs | 298 ++++++++++++++++++++++++++++++++++++-- src/proc/mod.rs | 40 +++++ test-data/boids.param.ron | 6 +- test-data/quad.param.ron | 6 + test-data/quad.wgsl | 9 +- 9 files changed, 416 insertions(+), 43 deletions(-) create mode 100644 test-data/quad.param.ron diff --git a/Makefile b/Makefile index f4ecbca40..2223335f2 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ clean: rm *.metal *.air *.metallib *.vert *.frag *.comp %.metal: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --example convert -- $< $@ + cargo run --example convert --features wgsl-in,msl-out -- $< $@ %.air: %.metal xcrun -sdk macosx metal -c $< -mmacosx-version-min=10.11 @@ -16,13 +16,13 @@ clean: xcrun -sdk macosx metallib $< -o $@ %.vert: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --example convert --features glsl-out -- $< $@ + cargo run --example convert --features wgsl-in,glsl-out -- $< $@ %.frag: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --example convert --features glsl-out -- $< $@ + cargo run --example convert --features wgsl-in,glsl-out -- $< $@ %.comp: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --example convert --features glsl-out -- $< $@ + cargo run --example convert --features wgsl-in,glsl-out -- $< $@ %.glsl_validate: %.vert %.frag %.comp glslangValidator $< diff --git a/examples/convert.rs b/examples/convert.rs index d1834b6b5..795c0a306 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -9,9 +9,13 @@ struct BindSource { #[derive(Serialize, Deserialize)] struct BindTarget { + #[serde(default)] buffer: Option, + #[serde(default)] texture: Option, + #[serde(default)] sampler: Option, + #[serde(default)] mutable: bool, } diff --git a/src/back/msl.rs b/src/back/msl.rs index 607b11ace..7bcf3dbdf 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -249,20 +249,25 @@ impl<'a> TypedGlobalVariable<'a> { fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { let var = &self.module.global_variables[self.handle]; let name = var.name.or_index(self.handle); - let (space_qualifier, reference) = match var.class { - crate::StorageClass::Constant - | crate::StorageClass::Uniform - | crate::StorageClass::StorageBuffer => { - let space = if self.usage.contains(crate::GlobalUse::STORE) { - "device " - } else { - "constant " - }; - (space, "&") - } + let ty = &self.module.types[var.ty]; + let ty_name = ty.name.or_index(var.ty); + + let (space_qualifier, reference) = match ty.inner { + crate::TypeInner::Struct { .. } => match var.class { + crate::StorageClass::Constant + | crate::StorageClass::Uniform + | crate::StorageClass::StorageBuffer => { + let space = if self.usage.contains(crate::GlobalUse::STORE) { + "device " + } else { + "constant " + }; + (space, "&") + } + _ => ("", ""), + }, _ => ("", ""), }; - let ty_name = self.module.types[var.ty].name.or_index(var.ty); Ok(write!( formatter, "{}{}{} {}", @@ -941,7 +946,7 @@ impl Writer { writeln!(self.out, "}}")?; } - for (&(stage, ref name), ep) in module.entry_points.iter() { + for (&(stage, ref ep_name), ep) in module.entry_points.iter() { let fun = &ep.function; self.typifier.resolve_all( &fun.expressions, @@ -972,9 +977,13 @@ impl Writer { } } + let fun_name = format!("{}{:?}", ep_name, stage); let output_name = Name { class: "Output", - source: NameSource::Custom { name, prefix: true }, + source: NameSource::Custom { + name: &fun_name, + prefix: true, + }, }; let (em_str, in_mode, out_mode) = match stage { @@ -994,7 +1003,10 @@ impl Writer { }; let location_input_name = Name { class: "Input", - source: NameSource::Custom { name, prefix: true }, + source: NameSource::Custom { + name: &fun_name, + prefix: true, + }, }; match stage { @@ -1086,7 +1098,7 @@ impl Writer { } writeln!(self.out, "}};")?; - writeln!(self.out, "{} {} {}(", em_str, output_name, name)?; + writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; let separator = separate(last_used_global.is_none()); writeln!( self.out, @@ -1095,7 +1107,7 @@ impl Writer { )?; } crate::ShaderStage::Compute => { - writeln!(self.out, "{} void {}(", em_str, name)?; + writeln!(self.out, "{} void {}(", em_str, fun_name)?; } }; diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 5468bedb8..efd3bca3c 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -224,6 +224,48 @@ impl<'a> Lexer<'a> { Ok(pair) } + pub(super) fn next_format_generic(&mut self) -> Result> { + use crate::StorageFormat as Sf; + self.expect(Token::Paren('<'))?; + let pair = match self.next() { + Token::Word("r8unorm") => Sf::R8Unorm, + Token::Word("r8snorm") => Sf::R8Snorm, + Token::Word("r8uint") => Sf::R8Uint, + Token::Word("r8sint") => Sf::R8Sint, + Token::Word("r16uint") => Sf::R16Uint, + Token::Word("r16sint") => Sf::R16Sint, + Token::Word("r16float") => Sf::R16Float, + Token::Word("rg8unorm") => Sf::Rg8Unorm, + Token::Word("rg8snorm") => Sf::Rg8Snorm, + Token::Word("rg8uint") => Sf::Rg8Uint, + Token::Word("rg8sint") => Sf::Rg8Sint, + Token::Word("r32uint") => Sf::R32Uint, + Token::Word("r32sint") => Sf::R32Sint, + Token::Word("r32float") => Sf::R32Float, + Token::Word("rg16uint") => Sf::Rg16Uint, + Token::Word("rg16sint") => Sf::Rg16Sint, + Token::Word("rg16float") => Sf::Rg16Float, + Token::Word("rgba8unorm") => Sf::Rgba8Unorm, + Token::Word("rgba8snorm") => Sf::Rgba8Snorm, + Token::Word("rgba8uint") => Sf::Rgba8Uint, + Token::Word("rgba8sint") => Sf::Rgba8Sint, + Token::Word("rgb10a2unorm") => Sf::Rgb10a2Unorm, + Token::Word("rg11b10float") => Sf::Rg11b10Float, + Token::Word("rg32uint") => Sf::Rg32Uint, + Token::Word("rg32sint") => Sf::Rg32Sint, + Token::Word("rg32float") => Sf::Rg32Float, + Token::Word("rgba16uint") => Sf::Rgba16Uint, + Token::Word("rgba16sint") => Sf::Rgba16Sint, + Token::Word("rgba16float") => Sf::Rgba16Float, + Token::Word("rgba32uint") => Sf::Rgba32Uint, + Token::Word("rgba32sint") => Sf::Rgba32Sint, + Token::Word("rgba32float") => Sf::Rgba32Float, + other => return Err(Error::Unexpected(other)), + }; + self.expect(Token::Paren('>'))?; + Ok(pair) + } + pub(super) fn take_until(&mut self, what: Token<'_>) -> Result, Error<'a>> { let original_input = self.input; let initial_len = self.input.len(); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index da5457be6..0dc6730da 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -52,6 +52,8 @@ pub enum Error<'a> { UnknownStorageClass(&'a str), #[error("unknown decoration: `{0}`")] UnknownDecoration(&'a str), + #[error("unknown scalar kind: `{0}`")] + UnknownScalarKind(&'a str), #[error("unknown builtin: `{0}`")] UnknownBuiltin(&'a str), #[error("unknown shader stage: `{0}`")] @@ -670,22 +672,100 @@ impl Parser { let expr = self.parse_primary_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::Derivative { axis, expr }) - } else if word == "dot" { - lexer.expect(Token::Paren('('))?; - let a = self.parse_primary_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let b = self.parse_primary_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::DotProduct(a, b)) - } else if word == "outer_product" { - lexer.expect(Token::Paren('('))?; - let a = self.parse_primary_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let b = self.parse_primary_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::CrossProduct(a, b)) } else { - None + match word { + "dot" => { + lexer.expect(Token::Paren('('))?; + let a = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let b = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::DotProduct(a, b)) + } + "cross" => { + lexer.expect(Token::Paren('('))?; + let a = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let b = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::CrossProduct(a, b)) + } + "textureSample" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let sampler_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let coordinate = + self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageSample { + image: ctx.lookup_ident.lookup(image_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name)?, + coordinate, + level: crate::SampleLevel::Auto, + depth_ref: None, + }) + } + "textureSampleLevel" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let sampler_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let coordinate = + self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let level = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageSample { + image: ctx.lookup_ident.lookup(image_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name)?, + coordinate, + level: crate::SampleLevel::Exact(level), + depth_ref: None, + }) + } + "textureSampleBias" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let sampler_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let coordinate = + self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let bias = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageSample { + image: ctx.lookup_ident.lookup(image_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name)?, + coordinate, + level: crate::SampleLevel::Bias(bias), + depth_ref: None, + }) + } + "textureSampleCompare" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let sampler_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let coordinate = + self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let reference = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageSample { + image: ctx.lookup_ident.lookup(image_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name)?, + coordinate, + level: crate::SampleLevel::Auto, //TODO: create a constant expression for 0? + depth_ref: Some(reference), + }) + } + _ => None, + } } } _ => None, @@ -1122,6 +1202,194 @@ impl Parser { let members = self.parse_struct_body(lexer, type_arena)?; crate::TypeInner::Struct { members } } + Token::Word("sampler") => crate::TypeInner::Sampler { comparison: false }, + Token::Word("sampler_comparison") => crate::TypeInner::Sampler { comparison: true }, + Token::Word("texture_sampled_1d") => { + let (kind, _) = lexer.next_scalar_generic()?; + crate::TypeInner::Image { + kind, + dim: crate::ImageDimension::D1, + arrayed: false, + class: crate::ImageClass::Sampled, + } + } + Token::Word("texture_sampled_1d_array") => { + let (kind, _) = lexer.next_scalar_generic()?; + crate::TypeInner::Image { + kind, + dim: crate::ImageDimension::D1, + arrayed: true, + class: crate::ImageClass::Sampled, + } + } + Token::Word("texture_sampled_2d") => { + let (kind, _) = lexer.next_scalar_generic()?; + crate::TypeInner::Image { + kind, + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Sampled, + } + } + Token::Word("texture_sampled_2d_array") => { + let (kind, _) = lexer.next_scalar_generic()?; + crate::TypeInner::Image { + kind, + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Sampled, + } + } + Token::Word("texture_sampled_3d") => { + let (kind, _) = lexer.next_scalar_generic()?; + crate::TypeInner::Image { + kind, + dim: crate::ImageDimension::D3, + arrayed: false, + class: crate::ImageClass::Sampled, + } + } + Token::Word("texture_sampled_cube") => { + let (kind, _) = lexer.next_scalar_generic()?; + crate::TypeInner::Image { + kind, + dim: crate::ImageDimension::Cube, + arrayed: false, + class: crate::ImageClass::Sampled, + } + } + Token::Word("texture_sampled_cube_array") => { + let (kind, _) = lexer.next_scalar_generic()?; + crate::TypeInner::Image { + kind, + dim: crate::ImageDimension::Cube, + arrayed: true, + class: crate::ImageClass::Sampled, + } + } + Token::Word("texture_multisampled_2d") => { + let (kind, _) = lexer.next_scalar_generic()?; + crate::TypeInner::Image { + kind, + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Multisampled, + } + } + Token::Word("texture_depth_2d") => crate::TypeInner::Image { + kind: crate::ScalarKind::Float, + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Depth, + }, + Token::Word("texture_depth_2d_array") => crate::TypeInner::Image { + kind: crate::ScalarKind::Float, + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Depth, + }, + Token::Word("texture_depth_cube") => crate::TypeInner::Image { + kind: crate::ScalarKind::Float, + dim: crate::ImageDimension::Cube, + arrayed: false, + class: crate::ImageClass::Depth, + }, + Token::Word("texture_depth_cube_array") => crate::TypeInner::Image { + kind: crate::ScalarKind::Float, + dim: crate::ImageDimension::Cube, + arrayed: true, + class: crate::ImageClass::Depth, + }, + Token::Word("texture_ro_1d") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D1, + arrayed: false, + class: crate::ImageClass::Storage(format), + } + } + Token::Word("texture_ro_1d_array") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D1, + arrayed: true, + class: crate::ImageClass::Storage(format), + } + } + Token::Word("texture_ro_2d") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Storage(format), + } + } + Token::Word("texture_ro_2d_array") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Storage(format), + } + } + Token::Word("texture_ro_3d") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D3, + arrayed: false, + class: crate::ImageClass::Storage(format), + } + } + Token::Word("texture_wo_1d") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D1, + arrayed: false, + class: crate::ImageClass::Storage(format), + } + } + Token::Word("texture_wo_1d_array") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D1, + arrayed: true, + class: crate::ImageClass::Storage(format), + } + } + Token::Word("texture_wo_2d") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Storage(format), + } + } + Token::Word("texture_wo_2d_array") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Storage(format), + } + } + Token::Word("texture_wo_3d") => { + let format = lexer.next_format_generic()?; + crate::TypeInner::Image { + kind: format.into(), + dim: crate::ImageDimension::D3, + arrayed: false, + class: crate::ImageClass::Storage(format), + } + } Token::Word(name) => { self.scopes.pop(); return match self.lookup_type.get(name) { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 827d40358..cb21c042c 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -7,3 +7,43 @@ mod validator; pub use interface::{Interface, Visitor}; pub use typifier::{check_constant_type, ResolveContext, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; + +impl From for super::ScalarKind { + fn from(format: super::StorageFormat) -> Self { + use super::{ScalarKind as Sk, StorageFormat as Sf}; + match format { + Sf::R8Unorm => Sk::Float, + Sf::R8Snorm => Sk::Float, + Sf::R8Uint => Sk::Uint, + Sf::R8Sint => Sk::Sint, + Sf::R16Uint => Sk::Uint, + Sf::R16Sint => Sk::Sint, + Sf::R16Float => Sk::Float, + Sf::Rg8Unorm => Sk::Float, + Sf::Rg8Snorm => Sk::Float, + Sf::Rg8Uint => Sk::Uint, + Sf::Rg8Sint => Sk::Sint, + Sf::R32Uint => Sk::Uint, + Sf::R32Sint => Sk::Sint, + Sf::R32Float => Sk::Float, + Sf::Rg16Uint => Sk::Uint, + Sf::Rg16Sint => Sk::Sint, + Sf::Rg16Float => Sk::Float, + Sf::Rgba8Unorm => Sk::Float, + Sf::Rgba8Snorm => Sk::Float, + Sf::Rgba8Uint => Sk::Uint, + Sf::Rgba8Sint => Sk::Sint, + Sf::Rgb10a2Unorm => Sk::Float, + Sf::Rg11b10Float => Sk::Float, + Sf::Rg32Uint => Sk::Uint, + Sf::Rg32Sint => Sk::Sint, + Sf::Rg32Float => Sk::Float, + Sf::Rgba16Uint => Sk::Uint, + Sf::Rgba16Sint => Sk::Sint, + Sf::Rgba16Float => Sk::Float, + Sf::Rgba32Uint => Sk::Uint, + Sf::Rgba32Sint => Sk::Sint, + Sf::Rgba32Float => Sk::Float, + } + } +} diff --git a/test-data/boids.param.ron b/test-data/boids.param.ron index bfd748777..4f5503c1c 100644 --- a/test-data/boids.param.ron +++ b/test-data/boids.param.ron @@ -1,7 +1,7 @@ ( metal_bindings: { - (group: 0, binding: 0): (buffer: Some(0), texture: None, sampler: None, mutable: false), - (group: 0, binding: 1): (buffer: Some(1), texture: None, sampler: None, mutable: true), - (group: 0, binding: 2): (buffer: Some(2), texture: None, sampler: None, mutable: true), + (group: 0, binding: 0): (buffer: Some(0), mutable: false), + (group: 0, binding: 1): (buffer: Some(1), mutable: true), + (group: 0, binding: 2): (buffer: Some(2), mutable: true), } ) diff --git a/test-data/quad.param.ron b/test-data/quad.param.ron new file mode 100644 index 000000000..cd26cc9e8 --- /dev/null +++ b/test-data/quad.param.ron @@ -0,0 +1,6 @@ +( + metal_bindings: { + (group: 0, binding: 0): (texture: Some(0)), + (group: 0, binding: 1): (sampler: Some(0)), + } +) diff --git a/test-data/quad.wgsl b/test-data/quad.wgsl index 1e83ccd72..3e56d317f 100644 --- a/test-data/quad.wgsl +++ b/test-data/quad.wgsl @@ -7,18 +7,19 @@ const c_scale: f32 = 1.2; [[stage(vertex)]] fn main() -> void { + v_uv = a_uv; o_position = vec4(c_scale * a_pos, 0.0, 1.0); return; } # fragment -[[location(0)]] var a_uv : vec2; -#layout(set = 0, binding = 0) uniform texture2D u_texture; -#layout(set = 0, binding = 1) uniform sampler u_sampler; +[[location(0)]] var v_uv : vec2; +[[group(0), binding(0)]] var u_texture : texture_sampled_2d; +[[group(0), binding(1)]] var u_sampler : sampler; [[location(0)]] var o_color : vec4; [[stage(fragment)]] fn main() -> void { - o_color = vec4(1.0, 0.0, 0.0, 1.0); #TODO: sample + o_color = textureSample(u_texture, u_sampler, v_uv); return; } From aa7005fdf3e60e043ce91d9781b312b00210b9d2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 17 Sep 2020 23:59:55 -0400 Subject: [PATCH 0211/2212] [ir] Move scalar kind into the Sampled image class variant --- src/back/glsl.rs | 91 ++++++++++++------------------------ src/back/msl.rs | 29 ++++++------ src/back/spv/instructions.rs | 9 ++-- src/back/spv/writer.rs | 23 ++++++--- src/front/spv/mod.rs | 20 ++++---- src/front/wgsl/mod.rs | 38 ++++----------- src/lib.rs | 10 ++-- src/proc/typifier.rs | 22 +++++---- 8 files changed, 101 insertions(+), 141 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index c54282cc5..135675129 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -268,7 +268,6 @@ pub fn write<'a>( { match module.types[global.ty].inner { TypeInner::Image { - kind, dim, arrayed, class, @@ -300,22 +299,10 @@ pub fn write<'a>( let name = namer(global.name.as_ref()); - let comparison = if let Some(sampler) = mapping.1 { - if let TypeInner::Sampler { comparison } = - module.types[module.global_variables[*sampler].ty].inner - { - comparison - } else { - false - } - } else { - unreachable!() - }; - writeln!( out, "uniform {} {};", - write_image_type(kind, dim, arrayed, class, comparison, features)?, + write_image_type(dim, arrayed, class, features)?, name )?; @@ -814,34 +801,28 @@ fn write_expression<'a, 'b>( let coordinate_expr = write_expression(&builder.expressions[coordinate], module, builder)?; - let (kind, dim, arrayed, class) = match *builder.typifier.get(image, &module.types) { + let (dim, arrayed, class) = match *builder.typifier.get(image, &module.types) { TypeInner::Image { - kind, dim, arrayed, class, - } => (kind, dim, arrayed, class), + } => (dim, arrayed, class), ref other => return Err(Error::Custom(format!("Cannot load {:?}", other))), }; Cow::Owned(match class { - ImageClass::Sampled | ImageClass::Multisampled => { - let ms = match class { - crate::ImageClass::Multisampled => true, - _ => false, - }; - + ImageClass::Sampled { kind, multi } => { //TODO: fix this let sampler_constructor = format!( "{}sampler{}{}{}({})", map_scalar(kind, 4, builder.features)?.prefix, ImageDimension(dim), - if ms { "MS" } else { "" }, + if multi { "MS" } else { "" }, if arrayed { "Array" } else { "" }, image_expr, ); - if !ms { + if !multi { format!("texelFetch({},{})", sampler_constructor, coordinate_expr) } else { let index_expr = @@ -1188,11 +1169,9 @@ fn write_type<'a>( } fn write_image_type( - kind: ScalarKind, dim: crate::ImageDimension, arrayed: bool, class: ImageClass, - comparison: bool, features: SupportedFeatures, ) -> Result { if arrayed @@ -1204,16 +1183,33 @@ fn write_image_type( ))); } + let (base, kind, ms, comparison) = match class { + ImageClass::Sampled { kind, multi: true } => { + if !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURES) { + return Err(Error::Custom(String::from( + "Multi sampled textures aren't supported", + ))); + } + if arrayed && !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS) { + return Err(Error::Custom(String::from( + "Multi sampled texture arrays aren't supported", + ))); + } + ("sampler", kind, "MS", "") + } + ImageClass::Sampled { kind, multi: false } => ("sampler", kind, "", ""), + ImageClass::Depth => ("sampler", crate::ScalarKind::Float, "", "Shadow"), + ImageClass::Storage(format) => ("image", format.into(), "", ""), + }; + Ok(format!( - "{}{}{}{}{}", + "{}{}{}{}{}{}", map_scalar(kind, 4, features)?.prefix, - match class { - ImageClass::Storage(_) => "image", - _ => "sampler", - }, + base, ImageDimension(dim), - write_image_flags(arrayed, class, features)?, - if comparison { "Shadow" } else { "" } + ms, + if arrayed { "Array" } else { "" }, + comparison )) } @@ -1271,33 +1267,6 @@ fn write_array_size(size: ArraySize) -> Result { }) } -fn write_image_flags( - arrayed: bool, - class: ImageClass, - features: SupportedFeatures, -) -> Result { - let ms = match class { - ImageClass::Multisampled => { - if !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURES) { - return Err(Error::Custom(String::from( - "Multi sampled textures aren't supported", - ))); - } - if arrayed && !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS) { - return Err(Error::Custom(String::from( - "Multi sampled texture arrays aren't supported", - ))); - } - "MS" - } - _ => "", - }; - - let array = if arrayed { "Array" } else { "" }; - - Ok(format!("{}{}", ms, array)) -} - struct ImageDimension(crate::ImageDimension); impl fmt::Display for ImageDimension { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/src/back/msl.rs b/src/back/msl.rs index 7bcf3dbdf..2910089ea 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -839,35 +839,30 @@ impl Writer { write!(self.out, "}}")?; } crate::TypeInner::Image { - kind, dim, arrayed, class, } => { - let base_name = scalar_kind_string(kind); let dim_str = match dim { crate::ImageDimension::D1 => "1d", crate::ImageDimension::D2 => "2d", crate::ImageDimension::D3 => "3d", crate::ImageDimension::Cube => "Cube", }; - let texture_str = match class { - crate::ImageClass::Depth => "depth", - _ => "texture", - }; - let msaa_str = match class { - crate::ImageClass::Multisampled => "_ms", - _ => "", - }; - let array_str = if arrayed { "_array" } else { "" }; - let access = match class { - crate::ImageClass::Storage(_) => { + let (texture_str, msaa_str, kind, access) = match class { + crate::ImageClass::Sampled { kind, multi } => { + ("texture", if multi { "_ms" } else { "" }, kind, "sample") + } + crate::ImageClass::Depth => { + ("depth", "", crate::ScalarKind::Float, "sample") + } + crate::ImageClass::Storage(format) => { let (_, global) = module .global_variables .iter() .find(|(_, var)| var.ty == handle) .expect("Unable to find a global variable using the image type"); - if global + let access = if global .storage_access .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) { @@ -878,10 +873,12 @@ impl Writer { "read" } else { return Err(Error::InvalidImageAccess(global.storage_access)); - } + }; + ("texture", "", format.into(), access) } - _ => "sample", }; + let base_name = scalar_kind_string(kind); + let array_str = if arrayed { "_array" } else { "" }; write!( self.out, "typedef {}{}{}{}<{}, access::{}> {}", diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 35914c33c..9a4f5bb4a 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -179,11 +179,11 @@ pub(super) fn instruction_type_image( }); instruction.add_operand(arrayed as u32); instruction.add_operand(match image_class { - crate::ImageClass::Multisampled => 1, + crate::ImageClass::Sampled { multi: true, .. } => 1, _ => 0, }); instruction.add_operand(match image_class { - crate::ImageClass::Sampled => 1, + crate::ImageClass::Sampled { .. } => 1, _ => 0, }); @@ -800,7 +800,10 @@ mod tests { 1, spirv::Dim::Dim3D, true, - crate::ImageClass::Multisampled, + crate::ImageClass::Sampled { + kind: crate::ScalarKind::Float, + multi: true, + }, ); let mut output = vec![]; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b757aab8d..a0939d73b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -490,19 +490,28 @@ impl Writer { super::instructions::instruction_type_matrix(id, vector_id, columns) } crate::TypeInner::Image { - kind, dim, arrayed, class, } => { - let type_id = self.get_type_id( - arena, - LookupType::Local(LocalType::Vector { + let width = 4; + let local_type = match class { + crate::ImageClass::Sampled { kind, multi: _ } => LocalType::Vector { size: crate::VectorSize::Quad, kind, - width: 4, - }), - ); + width, + }, + crate::ImageClass::Depth => LocalType::Scalar { + kind: crate::ScalarKind::Float, + width, + }, + crate::ImageClass::Storage(format) => LocalType::Vector { + size: crate::VectorSize::Quad, + kind: format.into(), + width, + }, + }; + let type_id = self.get_type_id(arena, LookupType::Local(local_type)); let dim = map_dim(dim); self.try_add_capabilities(dim.required_capabilities()); super::instructions::instruction_type_image(id, type_id, dim, arrayed, class) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index c4c75f69e..d88f6ec1d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -899,10 +899,13 @@ impl> Parser { match type_arena[image_type_handle].inner { //TODO: compare the result type crate::TypeInner::Image { - kind: _, dim, arrayed, - class: crate::ImageClass::Sampled, + class: + crate::ImageClass::Sampled { + kind: _, + multi: false, + }, } => { if !check_sample_coordinates( &type_arena[coord_type_handle], @@ -982,7 +985,6 @@ impl> Parser { match type_arena[image_type_handle].inner { //TODO: compare the result type crate::TypeInner::Image { - kind: _, dim, arrayed, class: crate::ImageClass::Depth, @@ -1473,10 +1475,6 @@ impl> Parser { }; *comparison = true; } - crate::TypeInner::Image { ref mut class, .. } => { - assert_eq!(*class, crate::ImageClass::Sampled); - *class = crate::ImageClass::Multisampled; - } _ => panic!("Unexpected comparison type {:?}", ty), } } @@ -2034,17 +2032,17 @@ impl> Parser { let class = if format != 0 { crate::ImageClass::Storage(map_image_format(format)?) - } else if is_msaa { - crate::ImageClass::Multisampled } else { - crate::ImageClass::Sampled + crate::ImageClass::Sampled { + kind, + multi: is_msaa, + } }; let decor = self.future_decor.remove(&id).unwrap_or_default(); let inner = crate::TypeInner::Image { class, - kind, dim: map_image_dim(dim)?, arrayed: is_array, }; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 0dc6730da..17f3fe1d2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1207,95 +1207,83 @@ impl Parser { Token::Word("texture_sampled_1d") => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { - kind, dim: crate::ImageDimension::D1, arrayed: false, - class: crate::ImageClass::Sampled, + class: crate::ImageClass::Sampled { kind, multi: false }, } } Token::Word("texture_sampled_1d_array") => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { - kind, dim: crate::ImageDimension::D1, arrayed: true, - class: crate::ImageClass::Sampled, + class: crate::ImageClass::Sampled { kind, multi: false }, } } Token::Word("texture_sampled_2d") => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { - kind, dim: crate::ImageDimension::D2, arrayed: false, - class: crate::ImageClass::Sampled, + class: crate::ImageClass::Sampled { kind, multi: false }, } } Token::Word("texture_sampled_2d_array") => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { - kind, dim: crate::ImageDimension::D2, arrayed: true, - class: crate::ImageClass::Sampled, + class: crate::ImageClass::Sampled { kind, multi: false }, } } Token::Word("texture_sampled_3d") => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { - kind, dim: crate::ImageDimension::D3, arrayed: false, - class: crate::ImageClass::Sampled, + class: crate::ImageClass::Sampled { kind, multi: false }, } } Token::Word("texture_sampled_cube") => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { - kind, dim: crate::ImageDimension::Cube, arrayed: false, - class: crate::ImageClass::Sampled, + class: crate::ImageClass::Sampled { kind, multi: false }, } } Token::Word("texture_sampled_cube_array") => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { - kind, dim: crate::ImageDimension::Cube, arrayed: true, - class: crate::ImageClass::Sampled, + class: crate::ImageClass::Sampled { kind, multi: false }, } } Token::Word("texture_multisampled_2d") => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { - kind, dim: crate::ImageDimension::D2, arrayed: false, - class: crate::ImageClass::Multisampled, + class: crate::ImageClass::Sampled { kind, multi: true }, } } Token::Word("texture_depth_2d") => crate::TypeInner::Image { - kind: crate::ScalarKind::Float, dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Depth, }, Token::Word("texture_depth_2d_array") => crate::TypeInner::Image { - kind: crate::ScalarKind::Float, dim: crate::ImageDimension::D2, arrayed: true, class: crate::ImageClass::Depth, }, Token::Word("texture_depth_cube") => crate::TypeInner::Image { - kind: crate::ScalarKind::Float, dim: crate::ImageDimension::Cube, arrayed: false, class: crate::ImageClass::Depth, }, Token::Word("texture_depth_cube_array") => crate::TypeInner::Image { - kind: crate::ScalarKind::Float, dim: crate::ImageDimension::Cube, arrayed: true, class: crate::ImageClass::Depth, @@ -1303,7 +1291,6 @@ impl Parser { Token::Word("texture_ro_1d") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D1, arrayed: false, class: crate::ImageClass::Storage(format), @@ -1312,7 +1299,6 @@ impl Parser { Token::Word("texture_ro_1d_array") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D1, arrayed: true, class: crate::ImageClass::Storage(format), @@ -1321,7 +1307,6 @@ impl Parser { Token::Word("texture_ro_2d") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Storage(format), @@ -1330,7 +1315,6 @@ impl Parser { Token::Word("texture_ro_2d_array") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D2, arrayed: true, class: crate::ImageClass::Storage(format), @@ -1339,7 +1323,6 @@ impl Parser { Token::Word("texture_ro_3d") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D3, arrayed: false, class: crate::ImageClass::Storage(format), @@ -1348,7 +1331,6 @@ impl Parser { Token::Word("texture_wo_1d") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D1, arrayed: false, class: crate::ImageClass::Storage(format), @@ -1357,7 +1339,6 @@ impl Parser { Token::Word("texture_wo_1d_array") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D1, arrayed: true, class: crate::ImageClass::Storage(format), @@ -1366,7 +1347,6 @@ impl Parser { Token::Word("texture_wo_2d") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Storage(format), @@ -1375,7 +1355,6 @@ impl Parser { Token::Word("texture_wo_2d_array") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D2, arrayed: true, class: crate::ImageClass::Storage(format), @@ -1384,7 +1363,6 @@ impl Parser { Token::Word("texture_wo_3d") => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { - kind: format.into(), dim: crate::ImageDimension::D3, arrayed: false, class: crate::ImageClass::Storage(format), diff --git a/src/lib.rs b/src/lib.rs index 7086834c2..e1e884edb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -315,9 +315,12 @@ pub enum StorageFormat { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ImageClass { /// Regular sampled image. - Sampled, - /// Multi-sampled image. - Multisampled, + Sampled { + /// Kind of values to sample. + kind: ScalarKind, + // Multi-sampled. + multi: bool, + }, /// Depth comparison image. Depth, /// Storage image. @@ -370,7 +373,6 @@ pub enum TypeInner { Struct { members: Vec }, /// Possibly multidimensional array of texels. Image { - kind: ScalarKind, dim: ImageDimension, arrayed: bool, class: ImageClass, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 461bfa1bb..0a0fc8695 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -136,18 +136,22 @@ impl Typifier { crate::Expression::Load { .. } => unimplemented!(), crate::Expression::ImageSample { image, .. } | crate::Expression::ImageLoad { image, .. } => match *self.get(image, types) { - crate::TypeInner::Image { - kind, - class: crate::ImageClass::Depth, - .. - } => Resolution::Value(crate::TypeInner::Scalar { kind, width: 4 }), - crate::TypeInner::Image { kind, .. } => { - Resolution::Value(crate::TypeInner::Vector { + crate::TypeInner::Image { class, .. } => Resolution::Value(match class { + crate::ImageClass::Depth => crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: 4, + }, + crate::ImageClass::Sampled { kind, multi: _ } => crate::TypeInner::Vector { kind, width: 4, size: crate::VectorSize::Quad, - }) - } + }, + crate::ImageClass::Storage(format) => crate::TypeInner::Vector { + kind: format.into(), + width: 4, + size: crate::VectorSize::Quad, + }, + }), _ => unreachable!(), }, crate::Expression::Unary { expr, .. } => self.resolutions[expr.index()].clone(), From 0aa91927b287abb2383000deccf45eebfe6e0fec Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Sep 2020 00:19:20 -0400 Subject: [PATCH 0212/2212] [wgsl] extend and refactor lexer tests --- src/front/wgsl/lexer.rs | 48 +++++++++++++++++++++++++++++++++++++++++ src/front/wgsl/mod.rs | 44 ++++--------------------------------- 2 files changed, 52 insertions(+), 40 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index efd3bca3c..af4104175 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -286,3 +286,51 @@ impl<'a> Lexer<'a> { source.len() - self.input.len() } } + +#[cfg(test)] +fn sub_test(source: &str, expected_tokens: &[Token]) { + let mut lex = Lexer::new(source); + for &token in expected_tokens { + assert_eq!(lex.next(), token); + } + assert_eq!(lex.next(), Token::End); +} + +#[test] +fn test_tokens() { + sub_test("id123_OK", &[Token::Word("id123_OK")]); + sub_test("92No", &[Token::Number("92"), Token::Word("No")]); + sub_test( + "æNoø", + &[Token::Unknown('æ'), Token::Word("No"), Token::Unknown('ø')], + ); + sub_test("No¾", &[Token::Word("No"), Token::Unknown('¾')]); + sub_test("No好", &[Token::Word("No"), Token::Unknown('好')]); + sub_test("\"\u{2}ПЀ\u{0}\"", &[Token::String("\u{2}ПЀ\u{0}")]); // https://github.com/gfx-rs/naga/issues/90 +} + +#[test] +fn test_variable_decl() { + sub_test( + "[[ group(0 )]] var< uniform> texture: texture_multisampled_2d ;", + &[ + Token::DoubleParen('['), + Token::Word("group"), + Token::Paren('('), + Token::Number("0"), + Token::Paren(')'), + Token::DoubleParen(']'), + Token::Word("var"), + Token::Paren('<'), + Token::Word("uniform"), + Token::Paren('>'), + Token::Word("texture"), + Token::Separator(':'), + Token::Word("texture_multisampled_2d"), + Token::Paren('<'), + Token::Word("f32"), + Token::Paren('>'), + Token::Separator(';'), + ], + ) +} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 17f3fe1d2..102ea0ca6 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1830,44 +1830,8 @@ pub fn parse_str(source: &str) -> Result { Parser::new().parse(source) } -#[cfg(test)] -mod tests { - use crate::front::wgsl::{Lexer, Token}; - - #[test] - fn check_constant_type_scalar_ok() { - let wgsl = "const a : i32 = 2;"; - assert!(super::parse_str(wgsl).is_ok()); - } - - #[test] - fn check_constant_type_scalar_err() { - let wgsl = "const a : i32 = 2.0;"; - assert!(super::parse_str(wgsl).is_err()); - } - - #[test] - fn check_lexer() { - use Token::{End, Number, String, Unknown, Word}; - let data = vec![ - ("id123_OK", vec![Word("id123_OK"), End]), - ("92No", vec![Number("92"), Word("No"), End]), - ("æNoø", vec![Unknown('æ'), Word("No"), Unknown('ø'), End]), - ("No¾", vec![Word("No"), Unknown('¾'), End]), - ("No好", vec![Word("No"), Unknown('好'), End]), - ("\"\u{2}ПЀ\u{0}\"", vec![String("\u{2}ПЀ\u{0}"), End]), // https://github.com/gfx-rs/naga/issues/90 - ]; - for (x, expected) in data { - let mut lex = Lexer::new(x); - let mut results = vec![]; - loop { - let result = lex.next(); - results.push(result); - if result == Token::End { - break; - } - } - assert_eq!(expected, results); - } - } +#[test] +fn parse_types() { + assert!(parse_str("const a : i32 = 2;").is_ok()); + assert!(parse_str("const a : i32 = 2.0;").is_err()); } From d25ab1b1e8cd649579aca2efb00a8a6141974758 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Sep 2020 09:57:12 -0400 Subject: [PATCH 0213/2212] Refactor image sampling arguments, add textureLoad support to WGSL --- src/back/glsl.rs | 20 +++++++++--------- src/back/msl.rs | 47 ++++++++++++++++--------------------------- src/front/wgsl/mod.rs | 30 ++++++++++++++++++++++++++- src/lib.rs | 7 +++++-- src/proc/interface.rs | 6 ++++-- 5 files changed, 64 insertions(+), 46 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 135675129..4443c3dbd 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -779,6 +779,9 @@ fn write_expression<'a, 'b>( //TODO: handle MS Cow::Owned(match level { crate::SampleLevel::Auto => format!("texture({},{})", image_expr, coordinate_expr), + crate::SampleLevel::Zero => { + format!("textureLod({},{},0)", image_expr, coordinate_expr) + } crate::SampleLevel::Exact(expr) => { let level_expr = write_expression(&builder.expressions[expr], module, builder)?; format!( @@ -822,17 +825,12 @@ fn write_expression<'a, 'b>( image_expr, ); - if !multi { - format!("texelFetch({},{})", sampler_constructor, coordinate_expr) - } else { - let index_expr = - write_expression(&builder.expressions[index], module, builder)?; - - format!( - "texelFetch({},{},{})", - sampler_constructor, coordinate_expr, index_expr - ) - } + let index_expr = + write_expression(&builder.expressions[index.unwrap()], module, builder)?; + format!( + "texelFetch({},{},{})", + sampler_constructor, coordinate_expr, index_expr + ) } ImageClass::Storage(_) => format!("imageLoad({},{})", image_expr, coordinate_expr), ImageClass::Depth => todo!(), diff --git a/src/back/msl.rs b/src/back/msl.rs index 2910089ea..618d258c6 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -515,16 +515,27 @@ impl Writer { sampler, coordinate, level, - depth_ref: None, + depth_ref, } => { + let op = match depth_ref { + Some(_) => "sample_compare", + None => "sample", + }; //TODO: handle arrayed images self.put_expression(image, function, module)?; - write!(self.out, ".sample(")?; + write!(self.out, ".{}(", op)?; self.put_expression(sampler, function, module)?; write!(self.out, ", ")?; self.put_expression(coordinate, function, module)?; + if let Some(dref) = depth_ref { + write!(self.out, ", ")?; + self.put_expression(dref, function, module)?; + } match level { crate::SampleLevel::Auto => {} + crate::SampleLevel::Zero => { + write!(self.out, ", level(0)")?; + } crate::SampleLevel::Exact(h) => { write!(self.out, ", level(")?; self.put_expression(h, function, module)?; @@ -538,32 +549,6 @@ impl Writer { } write!(self.out, ")")?; } - crate::Expression::ImageSample { - image, - sampler, - coordinate, - level, - depth_ref: Some(dref), - } => { - //TODO: handle arrayed images - self.put_expression(image, function, module)?; - write!(self.out, ".sample_compare(")?; - self.put_expression(sampler, function, module)?; - write!(self.out, ", ")?; - self.put_expression(coordinate, function, module)?; - write!(self.out, ", ")?; - self.put_expression(dref, function, module)?; - match level { - crate::SampleLevel::Auto => {} - crate::SampleLevel::Exact(h) => { - write!(self.out, ", level(")?; - self.put_expression(h, function, module)?; - write!(self.out, ")")?; - } - crate::SampleLevel::Bias(_) => return Err(Error::UnexpectedSampleLevel(level)), - } - write!(self.out, ")")?; - } crate::Expression::ImageLoad { image, coordinate, @@ -573,8 +558,10 @@ impl Writer { self.put_expression(image, function, module)?; write!(self.out, ".read(")?; self.put_expression(coordinate, function, module)?; - write!(self.out, ", ")?; - self.put_expression(index, function, module)?; + if let Some(index) = index { + write!(self.out, ", ")?; + self.put_expression(index, function, module)?; + } write!(self.out, ")")?; } crate::Expression::Call { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 102ea0ca6..61f2330e3 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -760,10 +760,38 @@ impl Parser { image: ctx.lookup_ident.lookup(image_name)?, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, - level: crate::SampleLevel::Auto, //TODO: create a constant expression for 0? + level: crate::SampleLevel::Zero, depth_ref: Some(reference), }) } + "textureLoad" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + let image = ctx.lookup_ident.lookup(image_name)?; + lexer.expect(Token::Separator(','))?; + let coordinate = + self.parse_primary_expression(lexer, ctx.reborrow())?; + let is_storage = match *ctx.resolve_type(image)? { + crate::TypeInner::Image { + class: crate::ImageClass::Storage(_), + .. + } => true, + _ => false, + }; + let index = if is_storage { + None + } else { + lexer.expect(Token::Separator(','))?; + let index_name = lexer.next_ident()?; + Some(ctx.lookup_ident.lookup(index_name)?) + }; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageLoad { + image, + coordinate, + index, + }) + } _ => None, } } diff --git a/src/lib.rs b/src/lib.rs index e1e884edb..c54d057e8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -542,6 +542,7 @@ pub enum FunctionOrigin { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum SampleLevel { Auto, + Zero, Exact(Handle), Bias(Handle), } @@ -588,8 +589,10 @@ pub enum Expression { ImageLoad { image: Handle, coordinate: Handle, - /// This is either LOD index, or sample index, based on the image class. - index: Handle, + /// For storage images, this is None. + /// For sampled images, this is the Some(Level). + /// For multisampled images, this is Some(Sample). + index: Option>, }, /// Apply an unary operator. Unary { diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 102da6e6a..ce117c56f 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -51,7 +51,7 @@ where self.traverse_expr(sampler); self.traverse_expr(coordinate); match level { - crate::SampleLevel::Auto => (), + crate::SampleLevel::Auto | crate::SampleLevel::Zero => (), crate::SampleLevel::Exact(h) | crate::SampleLevel::Bias(h) => { self.traverse_expr(h) } @@ -67,7 +67,9 @@ where } => { self.traverse_expr(image); self.traverse_expr(coordinate); - self.traverse_expr(index); + if let Some(index) = index { + self.traverse_expr(index); + } } E::Unary { expr, .. } => { self.traverse_expr(expr); From 0aae8ae6f8ad9417d3d7cd71e9706f8ad8659b20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 18 Sep 2020 22:01:05 +0100 Subject: [PATCH 0214/2212] glsl-out: More glsl versions (#191) * Added support for glsl core version up to 400 * Added 330 to the list supported versions * Added links to all extensions and fixed a extension being wrongfully activated * Cleanup and check for image formats * Removed useless extension and location on layout * Added support for external functions and fixed global names * Typefier allow Scalars in distance and length * Addressed comments * Fixed extension appearing after body * Fixed entry point not being generated --- examples/convert.rs | 32 +- src/back/glsl.rs | 858 ++++++++++++++++++++++++++++++------------- src/proc/typifier.rs | 11 +- 3 files changed, 632 insertions(+), 269 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 795c0a306..6cfb2caaa 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -149,15 +149,19 @@ fn main() { ShaderStage, }; - let mut file = fs::OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(&args[2]) - .unwrap(); + let version = match args.get(3).map(|p| p.as_str()) { + Some("core") => { + Version::Desktop(args.get(4).and_then(|v| v.parse().ok()).unwrap_or(330)) + } + Some("es") => { + Version::Embedded(args.get(4).and_then(|v| v.parse().ok()).unwrap_or(310)) + } + Some(_) => panic!("Unknown profile"), + _ => Version::Embedded(310), + }; let options = Options { - version: Version::Embedded(310), + version, entry_point: ( match stage { "vert" => ShaderStage::Vertex, @@ -169,7 +173,19 @@ fn main() { ), }; - glsl::write(&module, &mut file, options).unwrap(); + let mut file = fs::OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(&args[2]) + .unwrap(); + + glsl::write(&module, &mut file, options) + .map_err(|e| { + fs::remove_file(&args[2]).unwrap(); + e + }) + .unwrap(); } #[cfg(feature = "serialize")] "ron" => { diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 4443c3dbd..75780860e 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,12 +1,14 @@ use crate::{ proc::{Interface, ResolveContext, ResolveError, Typifier, Visitor}, - Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, - FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageClass, Interpolation, - IntrinsicFunction, LocalVariable, MemberOrigin, Module, ScalarKind, ShaderStage, Statement, - StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, UnaryOperator, + Arena, ArraySize, BinaryOperator, BuiltIn, ConservativeDepth, Constant, ConstantInner, + DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, + ImageClass, Interpolation, IntrinsicFunction, LocalVariable, MemberOrigin, Module, ScalarKind, + ShaderStage, Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, + TypeInner, UnaryOperator, }; use std::{ borrow::Cow, + cmp::Ordering, fmt::{self, Error as FmtError, Write as FmtWrite}, io::{Error as IoError, Write}, }; @@ -54,6 +56,25 @@ pub enum Version { Embedded(u16), } +impl Version { + fn is_es(&self) -> bool { + match self { + Version::Desktop(_) => false, + Version::Embedded(_) => true, + } + } +} + +impl PartialOrd for Version { + fn partial_cmp(&self, other: &Self) -> Option { + match (*self, *other) { + (Version::Desktop(x), Version::Desktop(y)) => Some(x.cmp(&y)), + (Version::Embedded(x), Version::Embedded(y)) => Some(x.cmp(&y)), + _ => None, + } + } +} + impl fmt::Display for Version { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -75,18 +96,188 @@ pub struct TextureMapping { pub sampler: Option>, } -const SUPPORTED_CORE_VERSIONS: &[u16] = &[450, 460]; +const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310]; bitflags::bitflags! { - struct SupportedFeatures: u32 { + struct Features: u32 { const BUFFER_STORAGE = 1; - const SHARED_STORAGE = 1 << 1; + const ARRAY_OF_ARRAYS = 1 << 1; const DOUBLE_TYPE = 1 << 2; - const NON_FLOAT_MATRICES = 1 << 3; + const FULL_IMAGE_FORMATS = 1 << 3; const MULTISAMPLED_TEXTURES = 1 << 4; const MULTISAMPLED_TEXTURE_ARRAYS = 1 << 5; - const NON_2D_TEXTURE_ARRAYS = 1 << 6; + const CUBE_TEXTURES_ARRAY = 1 << 6; + const COMPUTE_SHADER = 1 << 7; + const IMAGE_LOAD_STORE = 1 << 8; + const CONSERVATIVE_DEPTH = 1 << 9; + const TEXTURE_1D = 1 << 10; + } +} + +struct FeaturesManager(Features); + +impl FeaturesManager { + pub fn new() -> Self { + Self(Features::empty()) + } + + pub fn request(&mut self, features: Features) { + self.0 |= features + } + + #[allow(clippy::collapsible_if)] + pub fn write(&self, version: Version, out: &mut impl Write) -> Result<(), Error> { + if self.0.contains(Features::COMPUTE_SHADER) { + if version < Version::Embedded(310) || version < Version::Desktop(420) { + return Err(Error::Custom(format!( + "Version {} doesn't support compute shaders", + version + ))); + } + + if !version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_compute_shader.txt + writeln!(out, "#extension GL_ARB_compute_shader : require")?; + } + } + + if self.0.contains(Features::BUFFER_STORAGE) { + if version < Version::Embedded(310) || version < Version::Desktop(400) { + return Err(Error::Custom(format!( + "Version {} doesn't support buffer storage class", + version + ))); + } + + if let Version::Desktop(_) = version { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_storage_buffer_object.txt + writeln!( + out, + "#extension GL_ARB_shader_storage_buffer_object : require" + )?; + } + } + + if self.0.contains(Features::DOUBLE_TYPE) { + if version.is_es() || version < Version::Desktop(150) { + return Err(Error::Custom(format!( + "Version {} doesn't support doubles", + version + ))); + } + + if version < Version::Desktop(400) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_gpu_shader_fp64.txt + writeln!(out, "#extension GL_ARB_gpu_shader_fp64 : require")?; + } + } + + if self.0.contains(Features::CUBE_TEXTURES_ARRAY) { + if version < Version::Embedded(310) || version < Version::Desktop(130) { + return Err(Error::Custom(format!( + "Version {} doesn't support cube map array textures", + version + ))); + } + + if version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_cube_map_array.txt + writeln!(out, "#extension GL_EXT_texture_cube_map_array : require")?; + } else if version < Version::Desktop(400) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_cube_map_array.txt + writeln!(out, "#extension GL_ARB_texture_cube_map_array : require")?; + } + } + + if self.0.contains(Features::MULTISAMPLED_TEXTURES) { + if version < Version::Embedded(300) { + return Err(Error::Custom(format!( + "Version {} doesn't support multi sampled textures", + version + ))); + } + } + + if self.0.contains(Features::MULTISAMPLED_TEXTURE_ARRAYS) { + if version < Version::Embedded(310) { + return Err(Error::Custom(format!( + "Version {} doesn't support multi sampled texture arrays", + version + ))); + } + + if version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/OES/OES_texture_storage_multisample_2d_array.txt + writeln!( + out, + "#extension GL_OES_texture_storage_multisample_2d_array : require" + )?; + } + } + + if self.0.contains(Features::ARRAY_OF_ARRAYS) { + if version < Version::Embedded(310) || version < Version::Desktop(120) { + return Err(Error::Custom(format!( + "Version {} doesn't arrays of arrays", + version + ))); + } + + if version < Version::Desktop(430) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_arrays_of_arrays.txt + writeln!(out, "#extension ARB_arrays_of_arrays : require")?; + } + } + + if self.0.contains(Features::IMAGE_LOAD_STORE) { + if version < Version::Embedded(310) || version < Version::Desktop(130) { + return Err(Error::Custom(format!( + "Version {} doesn't support images load/stores", + version + ))); + } + + if self.0.contains(Features::FULL_IMAGE_FORMATS) && version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/NV/NV_image_formats.txt + writeln!(out, "#extension GL_NV_image_formats : require")?; + } + + if version < Version::Desktop(420) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_image_load_store.txt + writeln!(out, "#extension GL_ARB_shader_image_load_store : require")?; + } + } + + if self.0.contains(Features::CONSERVATIVE_DEPTH) { + if version < Version::Embedded(300) || version < Version::Desktop(130) { + return Err(Error::Custom(format!( + "Version {} doesn't support conservative depth", + version + ))); + } + + if version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_conservative_depth.txt + writeln!(out, "#extension GL_EXT_conservative_depth : require")?; + } + + if version < Version::Desktop(420) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_conservative_depth.txt + writeln!(out, "#extension GL_ARB_conservative_depth : require")?; + } + } + + if self.0.contains(Features::TEXTURE_1D) { + if version.is_es() { + return Err(Error::Custom(format!( + "Version {} doesn't support 1d textures", + version + ))); + } + } + + Ok(()) } } @@ -109,36 +300,15 @@ pub fn write<'a>( ))); } + let mut manager = FeaturesManager::new(); + let mut buf = Vec::new(); + writeln!(out, "#version {}\n", options.version)?; if es { writeln!(out, "precision highp float;\n")?; } - let mut counter = 0; - let mut names = FastHashMap::default(); - - let mut namer = |name: Option<&'a String>| { - if let Some(name) = name { - if !is_valid_ident(name) || names.get(name.as_str()).is_some() { - counter += 1; - while names.get(format!("_{}", counter).as_str()).is_some() { - counter += 1; - } - format!("_{}", counter) - } else { - names.insert(name.as_str(), ()); - name.clone() - } - } else { - counter += 1; - while names.get(format!("_{}", counter).as_str()).is_some() { - counter += 1; - } - format!("_{}", counter) - } - }; - let entry_point = module .entry_points .get(&options.entry_point) @@ -146,32 +316,27 @@ pub fn write<'a>( let func = &entry_point.function; let stage = options.entry_point.0; + if let Some(depth_test) = entry_point.early_depth_test { + manager.request(Features::IMAGE_LOAD_STORE); + writeln!(&mut buf, "layout(early_fragment_tests) in;\n")?; + + if let Some(conservative) = depth_test.conservative { + manager.request(Features::CONSERVATIVE_DEPTH); + + writeln!( + &mut buf, + "layout (depth_{}) out float gl_FragDepth;\n", + match conservative { + ConservativeDepth::GreaterEqual => "greater", + ConservativeDepth::LessEqual => "less", + ConservativeDepth::Unchanged => "unchanged", + } + )?; + } + } + if let ShaderStage::Compute = stage { - if (es && version < 310) || (!es && version < 430) { - return Err(Error::Custom(format!( - "Version {} doesn't support compute shaders", - options.version - ))); - } - - if !es && version < 460 { - writeln!(out, "#extension ARB_compute_shader : require")?; - } - } - - let mut features = SupportedFeatures::empty(); - - if !es && version > 440 { - features |= SupportedFeatures::DOUBLE_TYPE; - features |= SupportedFeatures::NON_FLOAT_MATRICES; - features |= SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS; - features |= SupportedFeatures::NON_2D_TEXTURE_ARRAYS; - } - - if !es || version > 300 { - features |= SupportedFeatures::BUFFER_STORAGE; - features |= SupportedFeatures::SHARED_STORAGE; - features |= SupportedFeatures::MULTISAMPLED_TEXTURES; + manager.request(Features::COMPUTE_SHADER) } let mut structs = FastHashMap::default(); @@ -181,7 +346,11 @@ pub fn write<'a>( for (handle, ty) in module.types.iter() { match ty.inner { TypeInner::Struct { .. } => { - let name = namer(ty.name.as_ref()); + let name = ty + .name + .clone() + .filter(|ident| is_valid_ident(ident)) + .unwrap_or_else(|| format!("struct_{}", handle.index())); structs.insert(handle, name); } @@ -195,10 +364,7 @@ pub fn write<'a>( } let block = match global.class { - StorageClass::Input - | StorageClass::Output - | StorageClass::StorageBuffer - | StorageClass::Uniform => true, + StorageClass::StorageBuffer | StorageClass::Uniform => true, _ => false, }; @@ -219,34 +385,38 @@ pub fn write<'a>( members, module, &structs, - out, + &mut buf, &mut built_structs, - features, + &mut manager, )?; } _ => continue, } } - writeln!(out)?; + writeln!(&mut buf)?; let mut functions = FastHashMap::default(); for (handle, func) in module.functions.iter() { - let name = namer(func.name.as_ref()); + let name = func + .name + .clone() + .filter(|ident| is_valid_ident(ident)) + .unwrap_or_else(|| format!("function_{}", handle.index())); writeln!( - out, + &mut buf, "{} {}({});", func.return_type - .map(|ty| write_type(ty, &module.types, &structs, None, features)) + .map(|ty| write_type(ty, &module.types, &structs, None, &mut manager)) .transpose()? .as_deref() .unwrap_or("void"), name, func.parameter_types .iter() - .map(|ty| write_type(*ty, &module.types, &structs, None, features)) + .map(|ty| write_type(*ty, &module.types, &structs, None, &mut manager)) .collect::, _>>()? .join(","), )?; @@ -254,9 +424,14 @@ pub fn write<'a>( functions.insert(handle, name); } - writeln!(out)?; + writeln!(&mut buf)?; - let texture_mappings = collect_texture_mapping(module, &functions)?; + let texture_mappings = collect_texture_mapping( + functions + .keys() + .map(|handle| &module.functions[*handle]) + .chain(std::iter::once(func)), + )?; let mut mappings_map = FastHashMap::default(); let mut globals_lookup = FastHashMap::default(); @@ -288,21 +463,39 @@ pub fn write<'a>( .. } = module.types[global.ty].inner { - write!(out, "layout({}) ", write_format_glsl(storage_format))?; + write!( + &mut buf, + "layout({}) ", + write_format_glsl(storage_format, &mut manager) + )?; } if global.storage_access == StorageAccess::LOAD { - write!(out, "readonly ")?; + write!(&mut buf, "readonly ")?; } else if global.storage_access == StorageAccess::STORE { - write!(out, "writeonly ")?; + write!(&mut buf, "writeonly ")?; } - let name = namer(global.name.as_ref()); + let name = if let Some(ref binding) = global.binding { + match binding { + crate::Binding::Location(location) => format!("location_{}", location), + crate::Binding::Resource { group, binding } => { + format!("set_{}_binding_{}", group, binding) + } + crate::Binding::BuiltIn(_) => unreachable!(), + } + } else { + global + .name + .clone() + .filter(|ident| is_valid_ident(ident)) + .unwrap_or_else(|| format!("global_{}", handle.index())) + }; writeln!( - out, + &mut buf, "uniform {} {};", - write_image_type(dim, arrayed, class, features)?, + write_image_type(dim, arrayed, class, &mut manager)?, name )?; @@ -316,7 +509,11 @@ pub fn write<'a>( globals_lookup.insert(handle, name); } TypeInner::Sampler { .. } => { - let name = namer(global.name.as_ref()); + let name = global + .name + .clone() + .filter(|ident| is_valid_ident(ident)) + .unwrap_or_else(|| format!("global_{}", handle.index())); globals_lookup.insert(handle, name); } @@ -358,60 +555,78 @@ pub fn write<'a>( continue; } - let name = global - .name - .clone() - .ok_or_else(|| Error::Custom(String::from("Global names must be specified in es")))?; + let name = if let Some(ref binding) = global.binding { + let prefix = match global.class { + StorageClass::Constant => "const", + StorageClass::Function => "fn", + StorageClass::Input => "in", + StorageClass::Output => "out", + StorageClass::Private => "priv", + StorageClass::StorageBuffer => "buffer", + StorageClass::Uniform => "uniform", + StorageClass::WorkGroup => "wg", + }; - if let Some(ref binding) = global.binding { - // Only vulkan glsl supports set/binding on the layout - if let crate::Binding::Location(location) = binding { - write!(out, "layout(location = {}) ", location)?; + match binding { + crate::Binding::Location(location) => format!("{}_location_{}", prefix, location), + crate::Binding::Resource { group, binding } => { + format!("{}_set_{}_binding_{}", prefix, group, binding) + } + crate::Binding::BuiltIn(_) => unreachable!(), } + } else { + global + .name + .clone() + .filter(|ident| is_valid_ident(ident)) + .unwrap_or_else(|| format!("global_{}", handle.index())) + }; - write!(out, ") ")?; + if let TypeInner::Struct { .. } = module.types[global.ty].inner { + if built_structs.get(&global.ty).is_none() { + globals_lookup.insert(handle, name); + continue; + } } if global.storage_access == StorageAccess::LOAD { - write!(out, "readonly ")?; + write!(&mut buf, "readonly ")?; } else if global.storage_access == StorageAccess::STORE { - write!(out, "writeonly ")?; + write!(&mut buf, "writeonly ")?; } if let Some(interpolation) = global.interpolation { match (stage, global.class) { (ShaderStage::Fragment, StorageClass::Input) | (ShaderStage::Vertex, StorageClass::Output) => { - write!(out, "{} ", write_interpolation(interpolation)?)?; + write!(&mut buf, "{} ", write_interpolation(interpolation)?)?; } _ => {} }; } let block = match global.class { - StorageClass::Input - | StorageClass::Output - | StorageClass::StorageBuffer - | StorageClass::Uniform => Some(namer(None)), + StorageClass::StorageBuffer | StorageClass::Uniform => { + Some(format!("global_block_{}", handle.index())) + } _ => None, }; writeln!( - out, + &mut buf, "{}{} {};", - write_storage_class(global.class, features)?, - write_type(global.ty, &module.types, &structs, block, features)?, + write_storage_class(global.class, &mut manager)?, + write_type(global.ty, &module.types, &structs, block, &mut manager)?, name )?; globals_lookup.insert(handle, name); } - writeln!(out)?; + writeln!(&mut buf)?; let mut typifier = Typifier::new(); - for (handle, name) in functions.iter() { - let func = &module.functions[*handle]; + let mut write_function = |func: &Function, name: &str| -> Result<(), Error> { typifier.resolve_all( &func.expressions, &module.types, @@ -428,14 +643,14 @@ pub fn write<'a>( .parameter_types .iter() .enumerate() - .map(|(pos, _ty)| (pos as u32, namer(None))) + .map(|(pos, _)| (pos as u32, format!("arg_{}", pos))) .collect(); writeln!( - out, + &mut buf, "{} {}({}) {{", func.return_type - .map(|ty| write_type(ty, &module.types, &structs, None, features)) + .map(|ty| write_type(ty, &module.types, &structs, None, &mut manager)) .transpose()? .as_deref() .unwrap_or("void"), @@ -444,7 +659,7 @@ pub fn write<'a>( .iter() .zip(args.values()) .map::, _>(|(ty, name)| { - let ty = write_type(*ty, &module.types, &structs, None, features)?; + let ty = write_type(*ty, &module.types, &structs, None, &mut manager)?; Ok(format!("{} {}", ty, name)) }) @@ -455,44 +670,71 @@ pub fn write<'a>( let locals: FastHashMap<_, _> = func .local_variables .iter() - .map(|(handle, local)| (handle, namer(local.name.as_ref()))) + .map(|(handle, local)| { + ( + handle, + local + .name + .clone() + .filter(|ident| is_valid_ident(ident)) + .unwrap_or_else(|| format!("local_{}", handle.index())), + ) + }) .collect(); for (handle, name) in locals.iter() { writeln!( - out, + &mut buf, "\t{} {};", write_type( func.local_variables[*handle].ty, &module.types, &structs, None, - features + &mut manager )?, name )?; } - writeln!(out)?; + writeln!(&mut buf)?; - let builder = StatementBuilder { + let mut builder = StatementBuilder { functions: &functions, globals: &globals_lookup, locals_lookup: &locals, structs: &structs, args: &args, expressions: &func.expressions, - features, typifier: &typifier, + manager: &mut manager, }; for sta in func.body.iter() { - writeln!(out, "{}", write_statement(sta, module, &builder, 1)?)?; + writeln!( + &mut buf, + "{}", + write_statement(sta, module, &mut builder, 1)? + )?; } - writeln!(out, "}}")?; + writeln!(&mut buf, "}}")?; + + Ok(()) + }; + + for (handle, name) in functions.iter() { + let func = &module.functions[*handle]; + write_function(func, name)?; } + write_function(func, "main")?; + + writeln!(out)?; + + manager.write(options.version, out)?; + out.write_all(&buf)?; + Ok(mappings_map) } @@ -503,14 +745,14 @@ struct StatementBuilder<'a> { structs: &'a FastHashMap, String>, args: &'a FastHashMap, expressions: &'a Arena, - features: SupportedFeatures, typifier: &'a Typifier, + pub manager: &'a mut FeaturesManager, } fn write_statement<'a, 'b>( sta: &Statement, module: &'a Module, - builder: &'b StatementBuilder<'a>, + builder: &'b mut StatementBuilder<'a>, indent: usize, ) -> Result { Ok(match sta { @@ -647,7 +889,7 @@ fn write_statement<'a, 'b>( fn write_expression<'a, 'b>( expr: &Expression, module: &'a Module, - builder: &'b StatementBuilder<'a>, + builder: &'b mut StatementBuilder<'a>, ) -> Result, Error> { Ok(match *expr { Expression::Access { base, index } => { @@ -688,13 +930,12 @@ fn write_expression<'a, 'b>( &module.constants[constant], module, builder, - builder.features, )?), Expression::Compose { ty, ref components } => { let constructor = match module.types[ty].inner { TypeInner::Vector { size, kind, width } => format!( "{}vec{}", - map_scalar(kind, width, builder.features)?.prefix, + map_scalar(kind, width, builder.manager)?.prefix, size as u8, ), TypeInner::Matrix { @@ -704,19 +945,19 @@ fn write_expression<'a, 'b>( width, } => format!( "{}mat{}x{}", - map_scalar(kind, width, builder.features)?.prefix, + map_scalar(kind, width, builder.manager)?.prefix, columns as u8, rows as u8, ), TypeInner::Array { .. } => { - write_type(ty, &module.types, builder.structs, None, builder.features)? + write_type(ty, &module.types, builder.structs, None, builder.manager)? .into_owned() } TypeInner::Struct { .. } => builder.structs.get(&ty).unwrap().clone(), _ => { return Err(Error::Custom(format!( "Cannot compose type {}", - write_type(ty, &module.types, builder.structs, None, builder.features)? + write_type(ty, &module.types, builder.structs, None, builder.manager)? ))) } }; @@ -818,7 +1059,7 @@ fn write_expression<'a, 'b>( //TODO: fix this let sampler_constructor = format!( "{}sampler{}{}{}({})", - map_scalar(kind, 4, builder.features)?.prefix, + map_scalar(kind, 4, builder.manager)?.prefix, ImageDimension(dim), if multi { "MS" } else { "" }, if arrayed { "Array" } else { "" }, @@ -934,13 +1175,13 @@ fn write_expression<'a, 'b>( let (source_kind, ty_expr) = match *builder.typifier.get(expr, &module.types) { TypeInner::Scalar { width, kind } => ( kind, - Cow::Borrowed(map_scalar(kind, width, builder.features)?.full), + Cow::Borrowed(map_scalar(kind, width, builder.manager)?.full), ), TypeInner::Vector { width, kind, size } => ( kind, Cow::Owned(format!( "{}vec{}", - map_scalar(kind, width, builder.features)?.prefix, + map_scalar(kind, width, builder.manager)?.prefix, size as u32, )), ), @@ -980,33 +1221,68 @@ fn write_expression<'a, 'b>( )) } Expression::Call { - ref origin, + origin: FunctionOrigin::Local(ref function), ref arguments, - } => { - match *origin { - FunctionOrigin::Local(_) => {} - FunctionOrigin::External(_) => { - write_expression(&builder.expressions[arguments[0]], module, builder)?; - } - }; + } => Cow::Owned(format!( + "{}({})", + builder.functions.get(function).unwrap(), + arguments + .iter() + .map::, _>(|arg| write_expression( + &builder.expressions[*arg], + module, + builder + )) + .collect::, _>>()? + .join(","), + )), + Expression::Call { + origin: crate::FunctionOrigin::External(ref name), + ref arguments, + } => match name.as_str() { + "cos" | "normalize" | "sin" => { + let expr = write_expression(&builder.expressions[arguments[0]], module, builder)?; - Cow::Owned(format!( - "{}({})", - match *origin { - FunctionOrigin::External(ref name) => name, - FunctionOrigin::Local(handle) => builder.functions.get(&handle).unwrap(), - }, - arguments - .iter() - .map(|arg| Ok(write_expression( - &builder.expressions[*arg], - module, - builder - )?)) - .collect::, Error>>()? - .join(","), - )) - } + Cow::Owned(format!("{}({})", name, expr)) + } + "fclamp" => { + let val = write_expression(&builder.expressions[arguments[0]], module, builder)?; + let min = write_expression(&builder.expressions[arguments[1]], module, builder)?; + let max = write_expression(&builder.expressions[arguments[2]], module, builder)?; + + Cow::Owned(format!("clamp({}, {}, {})", val, min, max)) + } + "atan2" => { + let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; + let y = write_expression(&builder.expressions[arguments[1]], module, builder)?; + + Cow::Owned(format!("atan({}, {})", y, x)) + } + "distance" => { + let p0 = write_expression(&builder.expressions[arguments[0]], module, builder)?; + let p1 = write_expression(&builder.expressions[arguments[1]], module, builder)?; + + Cow::Owned(format!("distance({}, {})", p0, p1)) + } + "length" => { + let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; + + Cow::Owned(format!("length({})", x)) + } + "mix" => { + let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; + let y = write_expression(&builder.expressions[arguments[0]], module, builder)?; + let a = write_expression(&builder.expressions[arguments[0]], module, builder)?; + + Cow::Owned(format!("mix({}, {}, {})", x, y, a)) + } + other => { + return Err(Error::Custom(format!( + "Unsupported function call {}", + other + ))) + } + }, Expression::ArrayLength(expr) => { let base = write_expression(&builder.expressions[expr], module, builder)?; Cow::Owned(format!("uint({}.length())", base)) @@ -1017,8 +1293,7 @@ fn write_expression<'a, 'b>( fn write_constant( constant: &Constant, module: &Module, - builder: &StatementBuilder<'_>, - features: SupportedFeatures, + builder: &mut StatementBuilder<'_>, ) -> Result { Ok(match constant.inner { ConstantInner::Sint(int) => int.to_string(), @@ -1033,22 +1308,28 @@ fn write_constant( Cow::Owned(format!("mat{}x{}", columns as u8, rows as u8,)), TypeInner::Struct { .. } => Cow::::Borrowed(builder.structs.get(&constant.ty).unwrap()), - TypeInner::Array { .. } => - write_type(constant.ty, &module.types, builder.structs, None, features)?, + TypeInner::Array { .. } => write_type( + constant.ty, + &module.types, + builder.structs, + None, + builder.manager + )?, _ => return Err(Error::Custom(format!( "Cannot build constant of type {}", - write_type(constant.ty, &module.types, builder.structs, None, features)? + write_type( + constant.ty, + &module.types, + builder.structs, + None, + builder.manager + )? ))), }, components .iter() - .map(|component| write_constant( - &module.constants[*component], - module, - builder, - features - )) + .map(|component| write_constant(&module.constants[*component], module, builder,)) .collect::, _>>()? .join(","), ), @@ -1063,7 +1344,7 @@ struct ScalarString<'a> { fn map_scalar( kind: ScalarKind, width: crate::Bytes, - features: SupportedFeatures, + manager: &mut FeaturesManager, ) -> Result, Error> { Ok(match kind { ScalarKind::Sint => ScalarString { @@ -1079,10 +1360,14 @@ fn map_scalar( prefix: "", full: "float", }, - 8 if features.contains(SupportedFeatures::DOUBLE_TYPE) => ScalarString { - prefix: "d", - full: "double", - }, + 8 => { + manager.request(Features::DOUBLE_TYPE); + + ScalarString { + prefix: "d", + full: "double", + } + } _ => { return Err(Error::Custom(format!( "Cannot build float of width {}", @@ -1102,13 +1387,13 @@ fn write_type<'a>( types: &Arena, structs: &'a FastHashMap, String>, block: Option, - features: SupportedFeatures, + manager: &mut FeaturesManager, ) -> Result, Error> { Ok(match types[ty].inner { - TypeInner::Scalar { kind, width } => Cow::Borrowed(map_scalar(kind, width, features)?.full), + TypeInner::Scalar { kind, width } => Cow::Borrowed(map_scalar(kind, width, manager)?.full), TypeInner::Vector { size, kind, width } => Cow::Owned(format!( "{}vec{}", - map_scalar(kind, width, features)?.prefix, + map_scalar(kind, width, manager)?.prefix, size as u8 )), TypeInner::Matrix { @@ -1116,27 +1401,34 @@ fn write_type<'a>( rows, kind, width, - } => Cow::Owned(format!( - "{}mat{}x{}", - if (width == 4 && kind == ScalarKind::Float) - || features.contains(SupportedFeatures::NON_FLOAT_MATRICES) - { - map_scalar(kind, width, features)?.prefix - } else { - return Err(Error::Custom(format!( - "Cannot build matrix of base type {:?}", - kind + } => { + if kind != ScalarKind::Float { + return Err(Error::Custom(String::from( + "Non float matrices aren't allowed", ))); - }, - columns as u8, - rows as u8 - )), - TypeInner::Pointer { base, .. } => write_type(base, types, structs, None, features)?, - TypeInner::Array { base, size, .. } => Cow::Owned(format!( - "{}[{}]", - write_type(base, types, structs, None, features)?, - write_array_size(size)? - )), + } else if width == 8 { + manager.request(Features::DOUBLE_TYPE); + } + + Cow::Owned(format!( + "{}mat{}x{}", + map_scalar(kind, width, manager)?.prefix, + columns as u8, + rows as u8 + )) + } + TypeInner::Pointer { base, .. } => write_type(base, types, structs, None, manager)?, + TypeInner::Array { base, size, .. } => { + if let TypeInner::Array { .. } = types[base].inner { + manager.request(Features::ARRAY_OF_ARRAYS) + } + + Cow::Owned(format!( + "{}[{}]", + write_type(base, types, structs, None, manager)?, + write_array_size(size)? + )) + } TypeInner::Struct { ref members } => { if let Some(name) = block { let mut out = String::new(); @@ -1146,7 +1438,7 @@ fn write_type<'a>( writeln!( &mut out, "\t{} {};", - write_type(member.ty, types, structs, None, features)?, + write_type(member.ty, types, structs, None, manager)?, member .name .clone() @@ -1170,29 +1462,21 @@ fn write_image_type( dim: crate::ImageDimension, arrayed: bool, class: ImageClass, - features: SupportedFeatures, + manager: &mut FeaturesManager, ) -> Result { - if arrayed - && dim != crate::ImageDimension::D2 - && !features.contains(SupportedFeatures::NON_2D_TEXTURE_ARRAYS) - { - return Err(Error::Custom(String::from( - "Arrayed non 2d images aren't supported", - ))); + if arrayed && dim == crate::ImageDimension::Cube { + manager.request(Features::CUBE_TEXTURES_ARRAY) + } else if dim == crate::ImageDimension::D1 { + manager.request(Features::TEXTURE_1D) } let (base, kind, ms, comparison) = match class { ImageClass::Sampled { kind, multi: true } => { - if !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURES) { - return Err(Error::Custom(String::from( - "Multi sampled textures aren't supported", - ))); - } - if arrayed && !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS) { - return Err(Error::Custom(String::from( - "Multi sampled texture arrays aren't supported", - ))); + manager.request(Features::MULTISAMPLED_TEXTURES); + if arrayed { + manager.request(Features::MULTISAMPLED_TEXTURE_ARRAYS); } + ("sampler", kind, "MS", "") } ImageClass::Sampled { kind, multi: false } => ("sampler", kind, "", ""), @@ -1202,7 +1486,7 @@ fn write_image_type( Ok(format!( "{}{}{}{}{}{}", - map_scalar(kind, 4, features)?.prefix, + map_scalar(kind, 4, manager)?.prefix, base, ImageDimension(dim), ms, @@ -1213,7 +1497,7 @@ fn write_image_type( fn write_storage_class( class: StorageClass, - features: SupportedFeatures, + manager: &mut FeaturesManager, ) -> Result<&'static str, Error> { Ok(match class { StorageClass::Constant => "", @@ -1222,23 +1506,15 @@ fn write_storage_class( StorageClass::Output => "out ", StorageClass::Private => "", StorageClass::StorageBuffer => { - if features.contains(SupportedFeatures::BUFFER_STORAGE) { - "buffer " - } else { - return Err(Error::Custom(String::from( - "buffer storage class isn't supported in glsl es", - ))); - } + manager.request(Features::BUFFER_STORAGE); + + "buffer " } StorageClass::Uniform => "uniform ", StorageClass::WorkGroup => { - if features.contains(SupportedFeatures::SHARED_STORAGE) { - "shared " - } else { - return Err(Error::Custom(String::from( - "workgroup storage class isn't supported in glsl es", - ))); - } + manager.request(Features::COMPUTE_SHADER); + + "shared " } }) } @@ -1288,15 +1564,16 @@ fn write_struct( structs: &FastHashMap, String>, out: &mut impl Write, built_structs: &mut FastHashMap, ()>, - features: SupportedFeatures, -) -> Result<(), Error> { + manager: &mut FeaturesManager, +) -> Result { if built_structs.get(&handle).is_some() { - return Ok(()); + return Ok(true); } let mut tmp = String::new(); let name = structs.get(&handle).unwrap(); + let mut fields = 0; writeln!(&mut tmp, "struct {} {{", name)?; for (idx, member) in members.iter().enumerate() { @@ -1305,35 +1582,40 @@ fn write_struct( } if let TypeInner::Struct { ref members } = module.types[member.ty].inner { - write_struct( + if !write_struct( member.ty, members, module, structs, out, built_structs, - features, - )?; + manager, + )? { + continue; + } } writeln!( &mut tmp, "\t{} {};", - write_type(member.ty, &module.types, &structs, None, features)?, + write_type(member.ty, &module.types, &structs, None, manager)?, member .name .clone() .filter(|s| is_valid_ident(s)) .unwrap_or_else(|| format!("_{}", idx)) )?; + + fields += 1; } writeln!(&mut tmp, "}};")?; - built_structs.insert(handle, ()); + if fields != 0 { + built_structs.insert(handle, ()); + writeln!(out, "{}", tmp)?; + } - writeln!(out, "{}", tmp)?; - - Ok(()) + Ok(fields != 0) } fn is_valid_ident(ident: &str) -> bool { @@ -1363,34 +1645,91 @@ fn builtin_to_glsl(builtin: BuiltIn) -> &'static str { } } -fn write_format_glsl(format: StorageFormat) -> &'static str { +fn write_format_glsl(format: StorageFormat, manager: &mut FeaturesManager) -> &'static str { match format { - StorageFormat::R8Unorm => "r8", - StorageFormat::R8Snorm => "r8_snorm", - StorageFormat::R8Uint => "r8ui", - StorageFormat::R8Sint => "r8i", - StorageFormat::R16Uint => "r16ui", - StorageFormat::R16Sint => "r16i", - StorageFormat::R16Float => "r16f", - StorageFormat::Rg8Unorm => "rg8", - StorageFormat::Rg8Snorm => "rg8_snorm", - StorageFormat::Rg8Uint => "rg8ui", - StorageFormat::Rg8Sint => "rg8i", + StorageFormat::R8Unorm => { + manager.request(Features::FULL_IMAGE_FORMATS); + "r8" + } + StorageFormat::R8Snorm => { + manager.request(Features::FULL_IMAGE_FORMATS); + "r8_snorm" + } + StorageFormat::R8Uint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "r8ui" + } + StorageFormat::R8Sint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "r8i" + } + StorageFormat::R16Uint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "r16ui" + } + StorageFormat::R16Sint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "r16i" + } + StorageFormat::R16Float => { + manager.request(Features::FULL_IMAGE_FORMATS); + "r16f" + } + StorageFormat::Rg8Unorm => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg8" + } + StorageFormat::Rg8Snorm => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg8_snorm" + } + StorageFormat::Rg8Uint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg8ui" + } + StorageFormat::Rg8Sint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg8i" + } StorageFormat::R32Uint => "r32ui", StorageFormat::R32Sint => "r32i", StorageFormat::R32Float => "r32f", - StorageFormat::Rg16Uint => "rg16ui", - StorageFormat::Rg16Sint => "rg16i", - StorageFormat::Rg16Float => "rg16f", + StorageFormat::Rg16Uint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg16ui" + } + StorageFormat::Rg16Sint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg16i" + } + StorageFormat::Rg16Float => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg16f" + } StorageFormat::Rgba8Unorm => "rgba8ui", StorageFormat::Rgba8Snorm => "rgba8_snorm", StorageFormat::Rgba8Uint => "rgba8ui", StorageFormat::Rgba8Sint => "rgba8i", - StorageFormat::Rgb10a2Unorm => "rgb10_a2ui", - StorageFormat::Rg11b10Float => "r11f_g11f_b10f", - StorageFormat::Rg32Uint => "rg32ui", - StorageFormat::Rg32Sint => "rg32i", - StorageFormat::Rg32Float => "rg32f", + StorageFormat::Rgb10a2Unorm => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rgb10_a2ui" + } + StorageFormat::Rg11b10Float => { + manager.request(Features::FULL_IMAGE_FORMATS); + "r11f_g11f_b10f" + } + StorageFormat::Rg32Uint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg32ui" + } + StorageFormat::Rg32Sint => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg32i" + } + StorageFormat::Rg32Float => { + manager.request(Features::FULL_IMAGE_FORMATS); + "rg32f" + } StorageFormat::Rgba16Uint => "rgba16ui", StorageFormat::Rgba16Sint => "rgba16i", StorageFormat::Rgba16Float => "rgba16f", @@ -1447,15 +1786,12 @@ impl<'a> Visitor for TextureMappingVisitor<'a> { } } -fn collect_texture_mapping( - module: &Module, - functions: &FastHashMap, String>, +fn collect_texture_mapping<'a>( + functions: impl Iterator, ) -> Result, Option>>, Error> { let mut mappings = FastHashMap::default(); - for function in functions.keys() { - let func = &module.functions[*function]; - + for func in functions { let mut interface = Interface { expressions: &func.expressions, visitor: TextureMappingVisitor { @@ -1465,6 +1801,10 @@ fn collect_texture_mapping( }, }; interface.traverse(&func.body); + + if let Some(error) = interface.visitor.error { + return Err(error); + } } Ok(mappings) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 0a0fc8695..9db625c41 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -247,11 +247,18 @@ impl Typifier { origin: crate::FunctionOrigin::External(ref name), ref arguments, } => match name.as_str() { - "distance" | "length" | "dot" => match *self.get(arguments[0], types) { + "distance" | "length" => match *self.get(arguments[0], types) { + crate::TypeInner::Vector { kind, width, .. } + | crate::TypeInner::Scalar { kind, width } => { + Resolution::Value(crate::TypeInner::Scalar { kind, width }) + } + ref other => panic!("Unexpected argument {:?} on {}", other, name), + }, + "dot" => match *self.get(arguments[0], types) { crate::TypeInner::Vector { kind, width, .. } => { Resolution::Value(crate::TypeInner::Scalar { kind, width }) } - ref other => panic!("Unexpected argument {:?}", other), + ref other => panic!("Unexpected argument {:?} on {}", other, name), }, "atan2" | "cos" | "sin" | "normalize" | "max" | "reflect" | "pow" | "clamp" | "fclamp" | "mix" => self.resolutions[arguments[0].index()].clone(), From 40f37c5c8c5782a35c3c4f2518e3afbcad96c5fe Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Fri, 18 Sep 2020 23:02:00 +0200 Subject: [PATCH 0215/2212] [spv-out] Combined all instruction spec tests to one test (#208) --- src/back/spv/instructions.rs | 1362 +++++++++++++++++----------------- 1 file changed, 688 insertions(+), 674 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 9a4f5bb4a..78a934d40 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -538,681 +538,695 @@ mod tests { use spirv::*; #[test] - fn test_instruction_source() { - let version = 450; - let instruction = super::instruction_source(SourceLanguage::GLSL, version); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Source, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); + fn test_spec_conformance() { + let suite = SpecConformanceSuite {}; + suite.test_all_instructions() } - #[test] - fn test_instruction_name() { - let instruction = super::instruction_name(1, "Test"); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Name, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_decorate() { - let instruction = super::instruction_decorate(1, Decoration::Location, &[1]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Decorate, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_ext_inst_import() { - let import_name = "GLSL.std.450"; - let instruction = super::instruction_ext_inst_import(1, import_name); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ExtInstImport, - wc: 3, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_memory_model() { - let instruction = - super::instruction_memory_model(AddressingModel::Logical, MemoryModel::GLSL450); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::MemoryModel, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_entry_point() { - let instruction = - super::instruction_entry_point(spirv::ExecutionModel::Fragment, 1, "main", &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::EntryPoint, - wc: 4, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_execution_mode() { - let instruction = super::instruction_execution_mode(1, ExecutionMode::OriginUpperLeft); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ExecutionMode, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_capability() { - let instruction = super::instruction_capability(Capability::Shader); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Capability, - wc: 2, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_void() { - let instruction = super::instruction_type_void(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeVoid, - wc: 2, - type_id: false, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_bool() { - let instruction = super::instruction_type_bool(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeBool, - wc: 2, - type_id: false, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_int() { - let instruction = super::instruction_type_int(1, 32, super::Signedness::Signed); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeInt, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_float() { - let instruction = super::instruction_type_float(1, 32); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeFloat, - wc: 3, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_vector() { - let instruction = super::instruction_type_vector(1, 1, crate::VectorSize::Bi); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeVector, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_matrix() { - let instruction = super::instruction_type_matrix(1, 1, crate::VectorSize::Bi); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeMatrix, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_image() { - let instruction = super::instruction_type_image( - 1, - 1, - spirv::Dim::Dim3D, - true, - crate::ImageClass::Sampled { - kind: crate::ScalarKind::Float, - multi: true, - }, - ); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeImage, - wc: 9, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_sampler() { - let instruction = super::instruction_type_sampler(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeSampler, - wc: 2, - type_id: false, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_array() { - let instruction = super::instruction_type_array(1, 1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeArray, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_runtime_array() { - let instruction = super::instruction_type_runtime_array(1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeRuntimeArray, - wc: 3, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_struct() { - let instruction = super::instruction_type_struct(1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeStruct, - wc: 2, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_pointer() { - let instruction = super::instruction_type_pointer(1, spirv::StorageClass::Function, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypePointer, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_type_function() { - let instruction = super::instruction_type_function(1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeFunction, - wc: 3, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_constant_true() { - let instruction = super::instruction_constant_true(1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ConstantTrue, - wc: 3, - type_id: true, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_constant_false() { - let instruction = super::instruction_constant_false(1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ConstantFalse, - wc: 3, - type_id: true, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_constant() { - let instruction = super::instruction_constant(1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Constant, - wc: 3, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_constant_composite() { - let instruction = super::instruction_constant_composite(1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ConstantComposite, - wc: 3, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_variable() { - let instruction = super::instruction_variable(1, 1, spirv::StorageClass::Function, Some(1)); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Variable, - wc: 4, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_load() { - let instruction = super::instruction_load(1, 1, 1, None); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Load, - wc: 4, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_store() { - let instruction = super::instruction_store(1, 1, None); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Store, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_function() { - let instruction = super::instruction_function(1, 1, spirv::FunctionControl::NONE, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Function, - wc: 5, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_function_parameter() { - let instruction = super::instruction_function_parameter(1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::FunctionParameter, - wc: 3, - type_id: true, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_function_end() { - let instruction = super::instruction_function_end(); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::FunctionEnd, - wc: 1, - type_id: false, - result_id: false, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_function_call() { - let instruction = super::instruction_function_call(1, 1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::FunctionCall, - wc: 4, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_composite_construct() { - let instruction = super::instruction_composite_construct(1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::CompositeConstruct, - wc: 3, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_vector_times_scalar() { - let instruction = super::instruction_vector_times_scalar(1, 1, 1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::VectorTimesScalar, - wc: 5, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_label() { - let instruction = super::instruction_label(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Label, - wc: 2, - type_id: false, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_return() { - let instruction = super::instruction_return(); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Return, - wc: 1, - type_id: false, - result_id: false, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - #[test] - fn test_instruction_return_value() { - let instruction = super::instruction_return_value(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ReturnValue, - wc: 2, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); + struct SpecConformanceSuite; + + impl SpecConformanceSuite { + fn test_all_instructions(&self) { + self.test_instruction_source(); + self.test_instruction_name(); + self.test_instruction_decorate(); + self.test_instruction_ext_inst_import(); + self.test_instruction_memory_model(); + self.test_instruction_entry_point(); + self.test_instruction_execution_mode(); + self.test_instruction_capability(); + self.test_instruction_type_void(); + self.test_instruction_type_bool(); + self.test_instruction_type_int(); + self.test_instruction_type_float(); + self.test_instruction_type_vector(); + self.test_instruction_type_matrix(); + self.test_instruction_type_image(); + self.test_instruction_type_sampler(); + self.test_instruction_type_array(); + self.test_instruction_type_runtime_array(); + self.test_instruction_type_struct(); + self.test_instruction_type_pointer(); + self.test_instruction_type_function(); + self.test_instruction_constant_true(); + self.test_instruction_constant_false(); + self.test_instruction_constant(); + self.test_instruction_constant_composite(); + self.test_instruction_variable(); + self.test_instruction_load(); + self.test_instruction_store(); + self.test_instruction_function(); + self.test_instruction_function_parameter(); + self.test_instruction_function_end(); + self.test_instruction_function_call(); + self.test_instruction_composite_construct(); + self.test_instruction_vector_times_scalar(); + self.test_instruction_label(); + self.test_instruction_return(); + self.test_instruction_return_value(); + } + + fn test_instruction_source(&self) { + let version = 450; + let instruction = super::instruction_source(SourceLanguage::GLSL, version); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Source, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_name(&self) { + let instruction = super::instruction_name(1, "Test"); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Name, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_decorate(&self) { + let instruction = super::instruction_decorate(1, Decoration::Location, &[1]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Decorate, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_ext_inst_import(&self) { + let import_name = "GLSL.std.450"; + let instruction = super::instruction_ext_inst_import(1, import_name); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ExtInstImport, + wc: 3, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_memory_model(&self) { + let instruction = + super::instruction_memory_model(AddressingModel::Logical, MemoryModel::GLSL450); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::MemoryModel, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_entry_point(&self) { + let instruction = + super::instruction_entry_point(spirv::ExecutionModel::Fragment, 1, "main", &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::EntryPoint, + wc: 4, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_execution_mode(&self) { + let instruction = super::instruction_execution_mode(1, ExecutionMode::OriginUpperLeft); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ExecutionMode, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_capability(&self) { + let instruction = super::instruction_capability(Capability::Shader); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Capability, + wc: 2, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_void(&self) { + let instruction = super::instruction_type_void(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeVoid, + wc: 2, + type_id: false, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_bool(&self) { + let instruction = super::instruction_type_bool(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeBool, + wc: 2, + type_id: false, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_int(&self) { + let instruction = super::instruction_type_int(1, 32, super::Signedness::Signed); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeInt, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_float(&self) { + let instruction = super::instruction_type_float(1, 32); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeFloat, + wc: 3, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_vector(&self) { + let instruction = super::instruction_type_vector(1, 1, crate::VectorSize::Bi); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeVector, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_matrix(&self) { + let instruction = super::instruction_type_matrix(1, 1, crate::VectorSize::Bi); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeMatrix, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_image(&self) { + let instruction = super::instruction_type_image( + 1, + 1, + spirv::Dim::Dim3D, + true, + crate::ImageClass::Sampled { + kind: crate::ScalarKind::Float, + multi: true, + }, + ); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeImage, + wc: 9, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_sampler(&self) { + let instruction = super::instruction_type_sampler(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeSampler, + wc: 2, + type_id: false, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_array(&self) { + let instruction = super::instruction_type_array(1, 1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeArray, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_runtime_array(&self) { + let instruction = super::instruction_type_runtime_array(1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeRuntimeArray, + wc: 3, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_struct(&self) { + let instruction = super::instruction_type_struct(1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeStruct, + wc: 2, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_pointer(&self) { + let instruction = super::instruction_type_pointer(1, spirv::StorageClass::Function, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypePointer, + wc: 4, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_type_function(&self) { + let instruction = super::instruction_type_function(1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::TypeFunction, + wc: 3, + type_id: false, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_constant_true(&self) { + let instruction = super::instruction_constant_true(1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ConstantTrue, + wc: 3, + type_id: true, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_constant_false(&self) { + let instruction = super::instruction_constant_false(1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ConstantFalse, + wc: 3, + type_id: true, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_constant(&self) { + let instruction = super::instruction_constant(1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Constant, + wc: 3, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_constant_composite(&self) { + let instruction = super::instruction_constant_composite(1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ConstantComposite, + wc: 3, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_variable(&self) { + let instruction = + super::instruction_variable(1, 1, spirv::StorageClass::Function, Some(1)); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Variable, + wc: 4, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_load(&self) { + let instruction = super::instruction_load(1, 1, 1, None); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Load, + wc: 4, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_store(&self) { + let instruction = super::instruction_store(1, 1, None); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Store, + wc: 3, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_function(&self) { + let instruction = super::instruction_function(1, 1, spirv::FunctionControl::NONE, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Function, + wc: 5, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_function_parameter(&self) { + let instruction = super::instruction_function_parameter(1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::FunctionParameter, + wc: 3, + type_id: true, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_function_end(&self) { + let instruction = super::instruction_function_end(); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::FunctionEnd, + wc: 1, + type_id: false, + result_id: false, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_function_call(&self) { + let instruction = super::instruction_function_call(1, 1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::FunctionCall, + wc: 4, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_composite_construct(&self) { + let instruction = super::instruction_composite_construct(1, 1, &[1, 2]); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::CompositeConstruct, + wc: 3, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_vector_times_scalar(&self) { + let instruction = super::instruction_vector_times_scalar(1, 1, 1, 1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::VectorTimesScalar, + wc: 5, + type_id: true, + result_id: true, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_label(&self) { + let instruction = super::instruction_label(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Label, + wc: 2, + type_id: false, + result_id: true, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_return(&self) { + let instruction = super::instruction_return(); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::Return, + wc: 1, + type_id: false, + result_id: false, + operands: false, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } + + fn test_instruction_return_value(&self) { + let instruction = super::instruction_return_value(1); + let mut output = vec![]; + + let requirements = SpecRequirements { + op: Op::ReturnValue, + wc: 2, + type_id: false, + result_id: false, + operands: true, + }; + validate_spec_requirements(requirements, &instruction); + + instruction.to_words(&mut output); + validate_instruction(output.as_slice(), &instruction); + } } } From ca492e43e6467c719dd2a161f995c90454daa0eb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Sep 2020 17:26:32 -0400 Subject: [PATCH 0216/2212] [glsl] write the entry point (#207) --- Makefile | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/Makefile b/Makefile index 2223335f2..7a74b50c5 100644 --- a/Makefile +++ b/Makefile @@ -15,14 +15,6 @@ clean: %.metallib: %.air xcrun -sdk macosx metallib $< -o $@ -%.vert: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) +%.vert %.frag %.comp: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) cargo run --example convert --features wgsl-in,glsl-out -- $< $@ - -%.frag: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --example convert --features wgsl-in,glsl-out -- $< $@ - -%.comp: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --example convert --features wgsl-in,glsl-out -- $< $@ - -%.glsl_validate: %.vert %.frag %.comp - glslangValidator $< + glslangValidator $@ From 0651eb8fabfe753169ef05ba131626e73c599f9e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 19 Sep 2020 00:11:35 -0400 Subject: [PATCH 0217/2212] Complete expression/statement support in MSL, refactor conversion methods in WGSL, and remove Statement::Empty --- src/back/glsl.rs | 16 +- src/back/msl.rs | 392 ++++++++++++++++++++---------------- src/back/spv/writer.rs | 149 ++++++++------ src/front/glsl/parser.rs | 3 +- src/front/wgsl/conv.rs | 116 +++++++++++ src/front/wgsl/lexer.rs | 49 +---- src/front/wgsl/mod.rs | 118 +++-------- src/lib.rs | 4 +- src/proc/interface.rs | 2 +- test-data/boids.wgsl | 6 +- test-data/simple/module.ron | 2 +- 11 files changed, 477 insertions(+), 380 deletions(-) create mode 100644 src/front/wgsl/conv.rs diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 75780860e..23187ffae 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -756,7 +756,6 @@ fn write_statement<'a, 'b>( indent: usize, ) -> Result { Ok(match sta { - Statement::Empty => String::new(), Statement::Block(block) => block .iter() .map(|sta| write_statement(sta, module, builder, indent)) @@ -1173,12 +1172,19 @@ fn write_expression<'a, 'b>( let value_expr = write_expression(&builder.expressions[expr], module, builder)?; let (source_kind, ty_expr) = match *builder.typifier.get(expr, &module.types) { - TypeInner::Scalar { width, kind } => ( - kind, + TypeInner::Scalar { + width, + kind: source_kind, + } => ( + source_kind, Cow::Borrowed(map_scalar(kind, width, builder.manager)?.full), ), - TypeInner::Vector { width, kind, size } => ( - kind, + TypeInner::Vector { + width, + kind: source_kind, + size, + } => ( + source_kind, Cow::Owned(format!( "{}vec{}", map_scalar(kind, width, builder.manager)?.prefix, diff --git a/src/back/msl.rs b/src/back/msl.rs index 618d258c6..78e091f87 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -71,15 +71,15 @@ pub enum Error { BadName(String), UnexpectedGlobalType(Handle), UnimplementedBindTarget(BindTarget), - UnexpectedIndexing(crate::Expression), UnsupportedCompose(Handle), UnsupportedBinaryOp(crate::BinaryOperator), UnexpectedSampleLevel(crate::SampleLevel), UnsupportedCall(String), - UnsupportedExpression(crate::Expression), + UnsupportedDynamicArrayLength, UnableToReturnValue(Handle), - UnsupportedStatement(crate::Statement), AccessIndexExceedsStaticLength(u32, u32), + /// The source IR is not valid. + Validation, } impl From for Error { @@ -370,6 +370,24 @@ fn separate(is_last: bool) -> &'static str { } impl Writer { + fn put_call( + &mut self, + name: &str, + parameters: &[Handle], + function: &crate::Function, + module: &crate::Module, + ) -> Result<(), Error> { + write!(self.out, "{}(", name)?; + for (i, &handle) in parameters.iter().enumerate() { + if i != 0 { + write!(self.out, ", ")?; + } + self.put_expression(handle, function, module)?; + } + write!(self.out, ")")?; + Ok(()) + } + fn put_expression( &mut self, expr_handle: Handle, @@ -381,19 +399,9 @@ impl Writer { match *expression { crate::Expression::Access { base, index } => { self.put_expression(base, function, module)?; - match *self.typifier.get(base, &module.types) { - crate::TypeInner::Array { .. } => { - //TODO: add size check - self.out.write_str("[")?; - self.put_expression(index, function, module)?; - self.out.write_str("]")?; - } - _ => { - return Err(Error::UnexpectedIndexing( - function.expressions[base].clone(), - )) - } - } + self.out.write_str("[")?; + self.put_expression(index, function, module)?; + self.out.write_str("]")?; } crate::Expression::AccessIndex { base, index } => { self.put_expression(base, function, module)?; @@ -419,9 +427,7 @@ impl Writer { write!(self.out, "[{}]", index)?; } _ => { - return Err(Error::UnexpectedIndexing( - function.expressions[base].clone(), - )) + // unexpected indexing, should fail validation } } } @@ -432,26 +438,22 @@ impl Writer { crate::TypeInner::Vector { size, kind, .. } => { write!( self.out, - "{}{}(", + "{}{}", scalar_kind_string(kind), vector_size_string(size) )?; - for (i, &handle) in components.iter().enumerate() { - if i != 0 { - write!(self.out, ", ")?; - } - self.put_expression(handle, function, module)?; - } - write!(self.out, ")")?; + self.put_call("", components, function, module)?; } crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { - write!(self.out, "{}(", scalar_kind_string(kind))?; - self.put_expression(components[0], function, module)?; - write!(self.out, ")")?; + self.put_call(scalar_kind_string(kind), components, function, module)?; } _ => return Err(Error::UnsupportedCompose(ty)), } } + crate::Expression::FunctionParameter(index) => { + let name = Name::from(ParameterIndex(index as usize)); + write!(self.out, "{}", name)?; + } crate::Expression::GlobalVariable(handle) => { let var = &module.global_variables[handle]; match var.class { @@ -480,36 +482,6 @@ impl Writer { //write!(self.out, "*")?; self.put_expression(pointer, function, module)?; } - crate::Expression::Unary { op, expr } => { - let op_str = match op { - crate::UnaryOperator::Negate => "-", - crate::UnaryOperator::Not => "!", - }; - write!(self.out, "{}", op_str)?; - self.put_expression(expr, function, module)?; - } - crate::Expression::Binary { op, left, right } => { - let op_str = match op { - crate::BinaryOperator::Add => "+", - crate::BinaryOperator::Subtract => "-", - crate::BinaryOperator::Multiply => "*", - crate::BinaryOperator::Divide => "/", - crate::BinaryOperator::Modulo => "%", - crate::BinaryOperator::Equal => "==", - crate::BinaryOperator::NotEqual => "!=", - crate::BinaryOperator::Less => "<", - crate::BinaryOperator::LessEqual => "<=", - crate::BinaryOperator::Greater => "==", - crate::BinaryOperator::GreaterEqual => ">=", - crate::BinaryOperator::And => "&", - other => return Err(Error::UnsupportedBinaryOp(other)), - }; - //write!(self.out, "(")?; - self.put_expression(left, function, module)?; - write!(self.out, " {} ", op_str)?; - self.put_expression(right, function, module)?; - //write!(self.out, ")")?; - } crate::Expression::ImageSample { image, sampler, @@ -564,55 +536,113 @@ impl Writer { } write!(self.out, ")")?; } + crate::Expression::Unary { op, expr } => { + let op_str = match op { + crate::UnaryOperator::Negate => "-", + crate::UnaryOperator::Not => "!", + }; + write!(self.out, "{}", op_str)?; + self.put_expression(expr, function, module)?; + } + crate::Expression::Binary { op, left, right } => { + let op_str = match op { + crate::BinaryOperator::Add => "+", + crate::BinaryOperator::Subtract => "-", + crate::BinaryOperator::Multiply => "*", + crate::BinaryOperator::Divide => "/", + crate::BinaryOperator::Modulo => "%", + crate::BinaryOperator::Equal => "==", + crate::BinaryOperator::NotEqual => "!=", + crate::BinaryOperator::Less => "<", + crate::BinaryOperator::LessEqual => "<=", + crate::BinaryOperator::Greater => "==", + crate::BinaryOperator::GreaterEqual => ">=", + crate::BinaryOperator::And => "&", + other => return Err(Error::UnsupportedBinaryOp(other)), + }; + //write!(self.out, "(")?; + self.put_expression(left, function, module)?; + write!(self.out, " {} ", op_str)?; + self.put_expression(right, function, module)?; + //write!(self.out, ")")?; + } + crate::Expression::Intrinsic { fun, argument } => { + let op = match fun { + crate::IntrinsicFunction::Any => "any", + crate::IntrinsicFunction::All => "all", + crate::IntrinsicFunction::IsNan => "", + crate::IntrinsicFunction::IsInf => "", + crate::IntrinsicFunction::IsFinite => "", + crate::IntrinsicFunction::IsNormal => "", + }; + self.put_call(op, &[argument], function, module)?; + } + crate::Expression::Transpose(expr) => { + self.put_call("transpose", &[expr], function, module)?; + } + crate::Expression::DotProduct(a, b) => { + self.put_call("dot", &[a, b], function, module)?; + } + crate::Expression::CrossProduct(a, b) => { + self.put_call("cross", &[a, b], function, module)?; + } + crate::Expression::As { + expr, + kind, + convert, + } => { + let scalar = scalar_kind_string(kind); + let size = match *self.typifier.get(expr, &module.types) { + crate::TypeInner::Scalar { .. } => "", + crate::TypeInner::Vector { size, .. } => vector_size_string(size), + _ => return Err(Error::Validation), + }; + let op = if convert { "static_cast" } else { "as_type" }; + write!(self.out, "{}<{}{}>(", op, scalar, size)?; + self.put_expression(expr, function, module)?; + write!(self.out, ")")?; + } + crate::Expression::Derivative { axis, expr } => { + let op = match axis { + crate::DerivativeAxis::X => "dfdx", + crate::DerivativeAxis::Y => "dfdy", + crate::DerivativeAxis::Width => "fwidth", + }; + self.put_call(op, &[expr], function, module)?; + } + crate::Expression::Call { + origin: crate::FunctionOrigin::Local(handle), + ref arguments, + } => { + let name = module.functions[handle].name.or_index(handle); + write!(self.out, "{}", name)?; + self.put_call("", arguments, function, module)?; + } crate::Expression::Call { origin: crate::FunctionOrigin::External(ref name), ref arguments, } => match name.as_str() { - "cos" | "normalize" | "sin" => { - write!(self.out, "{}(", name)?; - self.put_expression(arguments[0], function, module)?; - write!(self.out, ")")?; + "atan2" | "cos" | "distance" | "length" | "mix" | "normalize" | "sin" => { + self.put_call(name, arguments, function, module)?; } "fclamp" => { - write!(self.out, "clamp(")?; - self.put_expression(arguments[0], function, module)?; - write!(self.out, ", ")?; - self.put_expression(arguments[1], function, module)?; - write!(self.out, ", ")?; - self.put_expression(arguments[2], function, module)?; - write!(self.out, ")")?; - } - "atan2" => { - write!(self.out, "{}(", name)?; - self.put_expression(arguments[0], function, module)?; - write!(self.out, ", ")?; - self.put_expression(arguments[1], function, module)?; - write!(self.out, ")")?; - } - "distance" => { - write!(self.out, "distance(")?; - self.put_expression(arguments[0], function, module)?; - write!(self.out, ", ")?; - self.put_expression(arguments[1], function, module)?; - write!(self.out, ")")?; - } - "length" => { - write!(self.out, "length(")?; - self.put_expression(arguments[0], function, module)?; - write!(self.out, ")")?; - } - "mix" => { - write!(self.out, "mix(")?; - self.put_expression(arguments[0], function, module)?; - write!(self.out, ", ")?; - self.put_expression(arguments[1], function, module)?; - write!(self.out, ", ")?; - self.put_expression(arguments[2], function, module)?; - write!(self.out, ")")?; + self.put_call("clamp", arguments, function, module)?; } other => return Err(Error::UnsupportedCall(other.to_owned())), }, - ref other => return Err(Error::UnsupportedExpression(other.clone())), + crate::Expression::ArrayLength(expr) => { + let size = match *self.typifier.get(expr, &module.types) { + crate::TypeInner::Array { + size: crate::ArraySize::Static(size), + .. + } => size, + crate::TypeInner::Array { .. } => { + return Err(Error::UnsupportedDynamicArrayLength) + } + _ => return Err(Error::Validation), + }; + write!(self.out, "{}", size)?; + } } Ok(()) } @@ -657,79 +687,100 @@ impl Writer { Ok(()) } - fn put_statement( + fn put_block( &mut self, level: Level, - statement: &crate::Statement, + statements: &[crate::Statement], function: &crate::Function, - has_output: bool, module: &crate::Module, ) -> Result<(), Error> { - log::trace!("statement[{}] {:?}", level.0, statement); - match *statement { - crate::Statement::Empty => {} - crate::Statement::If { - condition, - ref accept, - ref reject, - } => { - write!(self.out, "{}if (", level)?; - self.put_expression(condition, function, module)?; - writeln!(self.out, ") {{")?; - for s in accept { - self.put_statement(level.next(), s, function, has_output, module)?; - } - if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", level)?; - for s in reject { - self.put_statement(level.next(), s, function, has_output, module)?; + for statement in statements { + log::trace!("statement[{}] {:?}", level.0, statement); + match *statement { + crate::Statement::Block(ref block) => { + if !block.is_empty() { + writeln!(self.out, "{}{{", level)?; + self.put_block(level.next(), block, function, module)?; + writeln!(self.out, "{}}}", level)?; } } - writeln!(self.out, "{}}}", level)?; - } - crate::Statement::Loop { - ref body, - ref continuing, - } => { - writeln!(self.out, "{}while(true) {{", level)?; - for s in body { - self.put_statement(level.next(), s, function, has_output, module)?; - } - if !continuing.is_empty() { - //TODO - } - writeln!(self.out, "{}}}", level)?; - } - crate::Statement::Store { pointer, value } => { - //write!(self.out, "\t*")?; - write!(self.out, "{}", level)?; - self.put_expression(pointer, function, module)?; - write!(self.out, " = ")?; - self.put_expression(value, function, module)?; - writeln!(self.out, ";")?; - } - crate::Statement::Break => { - writeln!(self.out, "{}break;", level)?; - } - crate::Statement::Continue => { - writeln!(self.out, "{}continue;", level)?; - } - crate::Statement::Return { value } => { - write!(self.out, "{}return ", level)?; - match value { - None if has_output => self.out.write_str(OUTPUT_STRUCT_NAME)?, - None => {} - Some(expr_handle) if has_output => { - return Err(Error::UnableToReturnValue(expr_handle)); - } - Some(expr_handle) => { - self.put_expression(expr_handle, function, module)?; + crate::Statement::If { + condition, + ref accept, + ref reject, + } => { + write!(self.out, "{}if (", level)?; + self.put_expression(condition, function, module)?; + writeln!(self.out, ") {{")?; + self.put_block(level.next(), accept, function, module)?; + if !reject.is_empty() { + writeln!(self.out, "{}}} else {{", level)?; + self.put_block(level.next(), reject, function, module)?; } + writeln!(self.out, "{}}}", level)?; + } + crate::Statement::Switch { + selector, + ref cases, + ref default, + } => { + write!(self.out, "{}switch(", level)?; + self.put_expression(selector, function, module)?; + writeln!(self.out, ") {{")?; + let lcase = level.next(); + for (&value, &(ref block, ref fall_through)) in cases.iter() { + writeln!(self.out, "{}case {}: {{", lcase, value)?; + self.put_block(lcase.next(), block, function, module)?; + if fall_through.is_none() { + writeln!(self.out, "{}break;", lcase.next())?; + } + writeln!(self.out, "{}}}", lcase)?; + } + writeln!(self.out, "{}default: {{", lcase)?; + self.put_block(lcase.next(), default, function, module)?; + writeln!(self.out, "{}}}", lcase)?; + writeln!(self.out, "{}}}", level)?; + } + crate::Statement::Loop { + ref body, + ref continuing, + } => { + writeln!(self.out, "{}while(true) {{", level)?; + self.put_block(level.next(), body, function, module)?; + if !continuing.is_empty() { + //TODO + } + writeln!(self.out, "{}}}", level)?; + } + crate::Statement::Break => { + writeln!(self.out, "{}break;", level)?; + } + crate::Statement::Continue => { + writeln!(self.out, "{}continue;", level)?; + } + crate::Statement::Return { value } => { + write!(self.out, "{}return ", level)?; + match value { + None => self.out.write_str(OUTPUT_STRUCT_NAME)?, + Some(expr_handle) => { + self.put_expression(expr_handle, function, module)?; + } + } + writeln!(self.out, ";")?; + } + crate::Statement::Kill => { + writeln!(self.out, "{}discard_fragment();", level)?; + } + crate::Statement::Store { pointer, value } => { + //write!(self.out, "\t*")?; + write!(self.out, "{}", level)?; + self.put_expression(pointer, function, module)?; + write!(self.out, " = ")?; + self.put_expression(value, function, module)?; + writeln!(self.out, ";")?; } - writeln!(self.out, ";")?; } - ref other => return Err(Error::UnsupportedStatement(other.clone())), - }; + } Ok(()) } @@ -924,9 +975,7 @@ impl Writer { } writeln!(self.out, ";")?; } - for statement in fun.body.iter() { - self.put_statement(Level(1), statement, fun, false, module)?; - } + self.put_block(Level(1), &fun.body, fun, module)?; writeln!(self.out, "}}")?; } @@ -1132,13 +1181,12 @@ impl Writer { } writeln!(self.out, ") {{")?; - let has_output = match stage { + match stage { crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?; - true } - crate::ShaderStage::Compute => false, - }; + crate::ShaderStage::Compute => {} + } for (local_handle, local) in fun.local_variables.iter() { let ty_name = module.types[local.ty].name.or_index(local.ty); write!( @@ -1153,9 +1201,7 @@ impl Writer { } writeln!(self.out, ";")?; } - for statement in fun.body.iter() { - self.put_statement(Level(1), statement, fun, has_output, module)?; - } + self.put_block(Level(1), &fun.body, fun, module)?; writeln!(self.out, "}}")?; } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a0939d73b..faca512f6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -321,19 +321,7 @@ impl Writer { function_type, )); - let mut block = Block::new(); - let id = self.generate_id(); - block.label = Some(super::instructions::instruction_label(id)); - for statement in ir_function.body.iter() { - self.write_function_statement( - ir_module, - ir_function, - &statement, - &mut block, - &mut function, - ); - } - function.blocks.push(block); + let id = self.write_block(&ir_function.body, ir_module, ir_function, &mut function); function.to_words(&mut self.logical_layout.function_definitions); super::instructions::instruction_function_end() @@ -996,74 +984,111 @@ impl Writer { } } - fn write_function_statement( + fn write_block( &mut self, + statements: &[crate::Statement], ir_module: &crate::Module, ir_function: &crate::Function, - statement: &crate::Statement, - block: &mut Block, function: &mut Function, - ) { - match statement { - crate::Statement::Return { value } => match ir_function.return_type { - Some(_) => { - let expression = &ir_function.expressions[value.unwrap()]; - let (id, ty) = self - .write_expression(ir_module, ir_function, expression, block, function) + ) -> spirv::Word { + let mut block = Block::new(); + let id = self.generate_id(); + block.label = Some(super::instructions::instruction_label(id)); + + for statement in statements { + match *statement { + crate::Statement::Block(ref ir_block) => { + if !ir_block.is_empty() { + //TODO: link the block with `OpBranch` + self.write_block(ir_block, ir_module, ir_function, function); + } + } + crate::Statement::Return { value } => { + block.termination = Some(match ir_function.return_type { + Some(_) => { + let expression = &ir_function.expressions[value.unwrap()]; + let (id, ty) = self + .write_expression( + ir_module, + ir_function, + expression, + &mut block, + function, + ) + .unwrap(); + + let id = match *expression { + crate::Expression::LocalVariable(_) => { + let load_id = self.generate_id(); + let value_ty_id = self.get_type_id( + &ir_module.types, + LookupType::Handle(ty.unwrap()), + ); + block.body.push(super::instructions::instruction_load( + value_ty_id, + load_id, + id, + None, + )); + load_id + } + _ => id, + }; + super::instructions::instruction_return_value(id) + } + None => super::instructions::instruction_return(), + }); + } + crate::Statement::Store { pointer, value } => { + let pointer_expression = &ir_function.expressions[pointer]; + let value_expression = &ir_function.expressions[value]; + let (pointer_id, _) = self + .write_expression( + ir_module, + ir_function, + pointer_expression, + &mut block, + function, + ) + .unwrap(); + let (value_id, value_ty) = self + .write_expression( + ir_module, + ir_function, + value_expression, + &mut block, + function, + ) .unwrap(); - let id = match expression { + let value_id = match value_expression { crate::Expression::LocalVariable(_) => { let load_id = self.generate_id(); - let value_ty_id = - self.get_type_id(&ir_module.types, LookupType::Handle(ty.unwrap())); + let value_ty_id = self.get_type_id( + &ir_module.types, + LookupType::Handle(value_ty.unwrap()), + ); block.body.push(super::instructions::instruction_load( value_ty_id, load_id, - id, + value_id, None, )); load_id } - _ => id, + _ => value_id, }; - block.termination = Some(super::instructions::instruction_return_value(id)); + + block.body.push(super::instructions::instruction_store( + pointer_id, value_id, None, + )); } - None => block.termination = Some(super::instructions::instruction_return()), - }, - crate::Statement::Store { pointer, value } => { - let pointer_expression = &ir_function.expressions[*pointer]; - let value_expression = &ir_function.expressions[*value]; - let (pointer_id, _) = self - .write_expression(ir_module, ir_function, pointer_expression, block, function) - .unwrap(); - let (value_id, value_ty) = self - .write_expression(ir_module, ir_function, value_expression, block, function) - .unwrap(); - - let value_id = match value_expression { - crate::Expression::LocalVariable(_) => { - let load_id = self.generate_id(); - let value_ty_id = self - .get_type_id(&ir_module.types, LookupType::Handle(value_ty.unwrap())); - block.body.push(super::instructions::instruction_load( - value_ty_id, - load_id, - value_id, - None, - )); - load_id - } - _ => value_id, - }; - - block.body.push(super::instructions::instruction_store( - pointer_id, value_id, None, - )); + _ => unimplemented!("{:?}", statement), } - crate::Statement::Empty => {} - _ => unimplemented!("{:?}", statement), } + + function.blocks.push(block); + id } fn write_physical_layout(&mut self) { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index e6ee55635..e0dff7325 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -726,7 +726,6 @@ pomelo! { extra.context.add_local_var(id, exp); } match statements.len() { - 0 => Statement::Empty, 1 => statements.remove(0), _ => Statement::Block(statements), } @@ -774,7 +773,7 @@ pomelo! { statement_list ::= statement_list(mut ss) statement(s) { ss.push(s); ss } expression_statement ::= Semicolon { - Statement::Empty + Statement::Block(Vec::new()) } expression_statement ::= expression(mut e) Semicolon { match e.statements.len() { diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs new file mode 100644 index 000000000..0b25ad943 --- /dev/null +++ b/src/front/wgsl/conv.rs @@ -0,0 +1,116 @@ +use super::Error; + +pub fn map_storage_class(word: &str) -> Result> { + match word { + "in" => Ok(crate::StorageClass::Input), + "out" => Ok(crate::StorageClass::Output), + "uniform" => Ok(crate::StorageClass::Uniform), + "storage_buffer" => Ok(crate::StorageClass::StorageBuffer), + _ => Err(Error::UnknownStorageClass(word)), + } +} + +pub fn map_built_in(word: &str) -> Result> { + Ok(match word { + // vertex + "position" => crate::BuiltIn::Position, + "vertex_idx" => crate::BuiltIn::VertexIndex, + "instance_idx" => crate::BuiltIn::InstanceIndex, + // fragment + "front_facing" => crate::BuiltIn::FrontFacing, + "frag_coord" => crate::BuiltIn::FragCoord, + "frag_depth" => crate::BuiltIn::FragDepth, + // compute + "global_invocation_id" => crate::BuiltIn::GlobalInvocationId, + "local_invocation_id" => crate::BuiltIn::LocalInvocationId, + "local_invocation_idx" => crate::BuiltIn::LocalInvocationIndex, + _ => return Err(Error::UnknownBuiltin(word)), + }) +} + +pub fn map_shader_stage(word: &str) -> Result> { + match word { + "vertex" => Ok(crate::ShaderStage::Vertex), + "fragment" => Ok(crate::ShaderStage::Fragment), + "compute" => Ok(crate::ShaderStage::Compute), + _ => Err(Error::UnknownShaderStage(word)), + } +} + +pub fn map_interpolation(word: &str) -> Result> { + match word { + "linear" => Ok(crate::Interpolation::Linear), + "flat" => Ok(crate::Interpolation::Flat), + "centroid" => Ok(crate::Interpolation::Centroid), + "sample" => Ok(crate::Interpolation::Sample), + "perspective" => Ok(crate::Interpolation::Perspective), + _ => Err(Error::UnknownDecoration(word)), + } +} + +pub fn map_storage_format(word: &str) -> Result> { + use crate::StorageFormat as Sf; + Ok(match word { + "r8unorm" => Sf::R8Unorm, + "r8snorm" => Sf::R8Snorm, + "r8uint" => Sf::R8Uint, + "r8sint" => Sf::R8Sint, + "r16uint" => Sf::R16Uint, + "r16sint" => Sf::R16Sint, + "r16float" => Sf::R16Float, + "rg8unorm" => Sf::Rg8Unorm, + "rg8snorm" => Sf::Rg8Snorm, + "rg8uint" => Sf::Rg8Uint, + "rg8sint" => Sf::Rg8Sint, + "r32uint" => Sf::R32Uint, + "r32sint" => Sf::R32Sint, + "r32float" => Sf::R32Float, + "rg16uint" => Sf::Rg16Uint, + "rg16sint" => Sf::Rg16Sint, + "rg16float" => Sf::Rg16Float, + "rgba8unorm" => Sf::Rgba8Unorm, + "rgba8snorm" => Sf::Rgba8Snorm, + "rgba8uint" => Sf::Rgba8Uint, + "rgba8sint" => Sf::Rgba8Sint, + "rgb10a2unorm" => Sf::Rgb10a2Unorm, + "rg11b10float" => Sf::Rg11b10Float, + "rg32uint" => Sf::Rg32Uint, + "rg32sint" => Sf::Rg32Sint, + "rg32float" => Sf::Rg32Float, + "rgba16uint" => Sf::Rgba16Uint, + "rgba16sint" => Sf::Rgba16Sint, + "rgba16float" => Sf::Rgba16Float, + "rgba32uint" => Sf::Rgba32Uint, + "rgba32sint" => Sf::Rgba32Sint, + "rgba32float" => Sf::Rgba32Float, + _ => return Err(Error::UnknownStorageFormat(word)), + }) +} + +pub fn get_scalar_type(word: &str) -> Option<(crate::ScalarKind, crate::Bytes)> { + match word { + "f32" => Some((crate::ScalarKind::Float, 4)), + "i32" => Some((crate::ScalarKind::Sint, 4)), + "u32" => Some((crate::ScalarKind::Uint, 4)), + _ => None, + } +} + +pub fn get_intrinsic(word: &str) -> Option { + match word { + "any" => Some(crate::IntrinsicFunction::Any), + "all" => Some(crate::IntrinsicFunction::All), + "is_nan" => Some(crate::IntrinsicFunction::IsNan), + "is_inf" => Some(crate::IntrinsicFunction::IsInf), + "is_normal" => Some(crate::IntrinsicFunction::IsNormal), + _ => None, + } +} +pub fn get_derivative(word: &str) -> Option { + match word { + "dpdx" => Some(crate::DerivativeAxis::X), + "dpdy" => Some(crate::DerivativeAxis::Y), + "dwidth" => Some(crate::DerivativeAxis::Width), + _ => None, + } +} diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index af4104175..65bea6384 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -1,4 +1,4 @@ -use super::{Error, Token}; +use super::{conv, Error, Token}; fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { if input.starts_with(what) { @@ -214,56 +214,17 @@ impl<'a> Lexer<'a> { &mut self, ) -> Result<(crate::ScalarKind, crate::Bytes), Error<'a>> { self.expect(Token::Paren('<'))?; - let pair = match self.next() { - Token::Word("f32") => (crate::ScalarKind::Float, 4), - Token::Word("i32") => (crate::ScalarKind::Sint, 4), - Token::Word("u32") => (crate::ScalarKind::Uint, 4), - other => return Err(Error::Unexpected(other)), - }; + let word = self.next_ident()?; + let pair = conv::get_scalar_type(word).ok_or(Error::UnknownScalarType(word))?; self.expect(Token::Paren('>'))?; Ok(pair) } pub(super) fn next_format_generic(&mut self) -> Result> { - use crate::StorageFormat as Sf; self.expect(Token::Paren('<'))?; - let pair = match self.next() { - Token::Word("r8unorm") => Sf::R8Unorm, - Token::Word("r8snorm") => Sf::R8Snorm, - Token::Word("r8uint") => Sf::R8Uint, - Token::Word("r8sint") => Sf::R8Sint, - Token::Word("r16uint") => Sf::R16Uint, - Token::Word("r16sint") => Sf::R16Sint, - Token::Word("r16float") => Sf::R16Float, - Token::Word("rg8unorm") => Sf::Rg8Unorm, - Token::Word("rg8snorm") => Sf::Rg8Snorm, - Token::Word("rg8uint") => Sf::Rg8Uint, - Token::Word("rg8sint") => Sf::Rg8Sint, - Token::Word("r32uint") => Sf::R32Uint, - Token::Word("r32sint") => Sf::R32Sint, - Token::Word("r32float") => Sf::R32Float, - Token::Word("rg16uint") => Sf::Rg16Uint, - Token::Word("rg16sint") => Sf::Rg16Sint, - Token::Word("rg16float") => Sf::Rg16Float, - Token::Word("rgba8unorm") => Sf::Rgba8Unorm, - Token::Word("rgba8snorm") => Sf::Rgba8Snorm, - Token::Word("rgba8uint") => Sf::Rgba8Uint, - Token::Word("rgba8sint") => Sf::Rgba8Sint, - Token::Word("rgb10a2unorm") => Sf::Rgb10a2Unorm, - Token::Word("rg11b10float") => Sf::Rg11b10Float, - Token::Word("rg32uint") => Sf::Rg32Uint, - Token::Word("rg32sint") => Sf::Rg32Sint, - Token::Word("rg32float") => Sf::Rg32Float, - Token::Word("rgba16uint") => Sf::Rgba16Uint, - Token::Word("rgba16sint") => Sf::Rgba16Sint, - Token::Word("rgba16float") => Sf::Rgba16Float, - Token::Word("rgba32uint") => Sf::Rgba32Uint, - Token::Word("rgba32sint") => Sf::Rgba32Sint, - Token::Word("rgba32float") => Sf::Rgba32Float, - other => return Err(Error::Unexpected(other)), - }; + let format = conv::map_storage_format(self.next_ident()?)?; self.expect(Token::Paren('>'))?; - Ok(pair) + Ok(format) } pub(super) fn take_until(&mut self, what: Token<'_>) -> Result, Error<'a>> { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 61f2330e3..7a4fc2b36 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2,6 +2,7 @@ //! //! [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html +mod conv; mod lexer; use crate::{ @@ -60,10 +61,14 @@ pub enum Error<'a> { UnknownShaderStage(&'a str), #[error("unknown identifier: `{0}`")] UnknownIdent(&'a str), + #[error("unknown scalar type: `{0}`")] + UnknownScalarType(&'a str), #[error("unknown type: `{0}`")] UnknownType(&'a str), #[error("unknown function: `{0}`")] UnknownFunction(&'a str), + #[error("unknown storage format: `{0}`")] + UnknownStorageFormat(&'a str), #[error("missing offset for structure member `{0}`")] MissingMemberOffset(&'a str), #[error("array stride must not be 0")] @@ -72,8 +77,6 @@ pub enum Error<'a> { NotCompositeType(Handle), #[error("function redefinition: `{0}`")] FunctionRedefinition(&'a str), - //MutabilityViolation(&'a str), - // TODO: these could be replaced with more detailed errors #[error("other error")] Other, } @@ -289,54 +292,6 @@ impl Parser { } } - fn get_storage_class(word: &str) -> Result> { - match word { - "in" => Ok(crate::StorageClass::Input), - "out" => Ok(crate::StorageClass::Output), - "uniform" => Ok(crate::StorageClass::Uniform), - "storage_buffer" => Ok(crate::StorageClass::StorageBuffer), - _ => Err(Error::UnknownStorageClass(word)), - } - } - - fn get_built_in(word: &str) -> Result> { - Ok(match word { - // vertex - "position" => crate::BuiltIn::Position, - "vertex_idx" => crate::BuiltIn::VertexIndex, - "instance_idx" => crate::BuiltIn::InstanceIndex, - // fragment - "front_facing" => crate::BuiltIn::FrontFacing, - "frag_coord" => crate::BuiltIn::FragCoord, - "frag_depth" => crate::BuiltIn::FragDepth, - // compute - "global_invocation_id" => crate::BuiltIn::GlobalInvocationId, - "local_invocation_id" => crate::BuiltIn::LocalInvocationId, - "local_invocation_idx" => crate::BuiltIn::LocalInvocationIndex, - _ => return Err(Error::UnknownBuiltin(word)), - }) - } - - fn get_shader_stage(word: &str) -> Result> { - match word { - "vertex" => Ok(crate::ShaderStage::Vertex), - "fragment" => Ok(crate::ShaderStage::Fragment), - "compute" => Ok(crate::ShaderStage::Compute), - _ => Err(Error::UnknownShaderStage(word)), - } - } - - fn get_interpolation(word: &str) -> Result> { - match word { - "linear" => Ok(crate::Interpolation::Linear), - "flat" => Ok(crate::Interpolation::Flat), - "centroid" => Ok(crate::Interpolation::Centroid), - "sample" => Ok(crate::Interpolation::Sample), - "perspective" => Ok(crate::Interpolation::Perspective), - _ => Err(Error::UnknownDecoration(word)), - } - } - fn deconstruct_composite_type( type_arena: &mut Arena, ty: Handle, @@ -631,25 +586,6 @@ impl Parser { lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { - fn get_intrinsic(word: &str) -> Option { - match word { - "any" => Some(crate::IntrinsicFunction::Any), - "all" => Some(crate::IntrinsicFunction::All), - "is_nan" => Some(crate::IntrinsicFunction::IsNan), - "is_inf" => Some(crate::IntrinsicFunction::IsInf), - "is_normal" => Some(crate::IntrinsicFunction::IsNormal), - _ => None, - } - } - fn get_derivative(word: &str) -> Option { - match word { - "dpdx" => Some(crate::DerivativeAxis::X), - "dpdy" => Some(crate::DerivativeAxis::Y), - "dwidth" => Some(crate::DerivativeAxis::Width), - _ => None, - } - } - self.scopes.push(Scope::SingularExpr); let backup = lexer.clone(); let expression = match lexer.next() { @@ -662,16 +598,25 @@ impl Parser { expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }), Token::Word(word) => { - if let Some(fun) = get_intrinsic(word) { + if let Some(fun) = conv::get_intrinsic(word) { lexer.expect(Token::Paren('('))?; let argument = self.parse_primary_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::Intrinsic { fun, argument }) - } else if let Some(axis) = get_derivative(word) { + } else if let Some(axis) = conv::get_derivative(word) { lexer.expect(Token::Paren('('))?; let expr = self.parse_primary_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::Derivative { axis, expr }) + } else if let Some((kind, _width)) = conv::get_scalar_type(word) { + lexer.expect(Token::Paren('('))?; + let expr = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::As { + expr, + kind, + convert: true, + }) } else { match word { "dot" => { @@ -978,7 +923,7 @@ impl Parser { let mut class = None; if lexer.skip(Token::Paren('<')) { let class_str = lexer.next_ident()?; - class = Some(Self::get_storage_class(class_str)?); + class = Some(conv::map_storage_class(class_str)?); lexer.expect(Token::Paren('>'))?; } let name = lexer.next_ident()?; @@ -1186,7 +1131,7 @@ impl Parser { } Token::Word("ptr") => { lexer.expect(Token::Paren('<'))?; - let class = Self::get_storage_class(lexer.next_ident()?)?; + let class = conv::map_storage_class(lexer.next_ident()?)?; lexer.expect(Token::Separator(','))?; let base = self.parse_type_decl(lexer, None, type_arena)?; lexer.expect(Token::Paren('>'))?; @@ -1418,11 +1363,10 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: StatementContext<'a, '_, '_>, - ) -> Result, Error<'a>> { + ) -> Result> { let backup = lexer.clone(); match lexer.next() { - Token::Separator(';') => Ok(Some(crate::Statement::Empty)), - Token::Paren('}') => Ok(None), + Token::Separator(';') => Ok(crate::Statement::Block(Vec::new())), Token::Word(word) => { self.scopes.push(Scope::Statement); let statement = match word { @@ -1462,7 +1406,7 @@ impl Parser { pointer: expr_id, value, }, - _ => crate::Statement::Empty, + _ => crate::Statement::Block(Vec::new()), } } "return" => { @@ -1501,10 +1445,11 @@ impl Parser { lexer.expect(Token::Paren('}'))?; break; } - match self.parse_statement(lexer, context.reborrow())? { - Some(s) => body.push(s), - None => break, + if lexer.skip(Token::Paren('}')) { + break; } + let s = self.parse_statement(lexer, context.reborrow())?; + body.push(s); } crate::Statement::Loop { body, continuing } } @@ -1529,14 +1474,14 @@ impl Parser { *lexer = new_lexer; context.expressions.append(expr); lexer.expect(Token::Separator(';'))?; - crate::Statement::Empty + crate::Statement::Block(Vec::new()) } else { return Err(Error::UnknownIdent(ident)); } } }; self.scopes.pop(); - Ok(Some(statement)) + Ok(statement) } other => Err(Error::Unexpected(other)), } @@ -1550,7 +1495,8 @@ impl Parser { self.scopes.push(Scope::Block); lexer.expect(Token::Paren('{'))?; let mut statements = Vec::new(); - while let Some(s) = self.parse_statement(lexer, context.reborrow())? { + while !lexer.skip(Token::Paren('}')) { + let s = self.parse_statement(lexer, context.reborrow())?; statements.push(s); } self.scopes.pop(); @@ -1654,7 +1600,7 @@ impl Parser { } "builtin" => { lexer.expect(Token::Paren('('))?; - let builtin = Self::get_built_in(lexer.next_ident()?)?; + let builtin = conv::map_built_in(lexer.next_ident()?)?; lexer.expect(Token::Paren(')'))?; binding = Some(crate::Binding::BuiltIn(builtin)); } @@ -1670,12 +1616,12 @@ impl Parser { } "interpolate" => { lexer.expect(Token::Paren('('))?; - interpolation = Some(Self::get_interpolation(lexer.next_ident()?)?); + interpolation = Some(conv::map_interpolation(lexer.next_ident()?)?); lexer.expect(Token::Paren(')'))?; } "stage" => { lexer.expect(Token::Paren('('))?; - stage = Some(Self::get_shader_stage(lexer.next_ident()?)?); + stage = Some(conv::map_shader_stage(lexer.next_ident()?)?); lexer.expect(Token::Paren(')'))?; } "workgroup_size" => { diff --git a/src/lib.rs b/src/lib.rs index c54d057e8..a05391cb3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -645,7 +645,7 @@ pub type Block = Vec; /// Marker type, used for falling through in a switch statement. // Clone is used only for error reporting and is not intended for end users -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct FallThrough; @@ -656,8 +656,6 @@ pub struct FallThrough; #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Statement { - /// Empty statement, does nothing. - Empty, /// A block containing more statements, to be executed sequentially. Block(Block), /// Conditionally executes one of two blocks, based on the value of the condition. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index ce117c56f..33767f597 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -119,7 +119,7 @@ where for statement in block { use crate::Statement as S; match *statement { - S::Empty | S::Break | S::Continue | S::Kill => (), + S::Break | S::Continue | S::Kill => (), S::Block(ref b) => { self.traverse(b); } diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl index 6e4cf7c67..5df5e6061 100644 --- a/test-data/boids.wgsl +++ b/test-data/boids.wgsl @@ -70,7 +70,7 @@ type Particles = struct { [[stage(compute), workgroup_size(1)]] fn main() -> void { var index : u32 = gl_GlobalInvocationID.x; - if (index >= 5) { + if (index >= u32(5)) { return; } @@ -87,7 +87,7 @@ fn main() -> void { var vel : vec2; var i : u32 = 0; loop { - if (i >= 5) { + if (i >= u32(5)) { break; } if (i == index) { @@ -110,7 +110,7 @@ fn main() -> void { } continuing { - i = i + 1; + i = i + u32(1); } } if (cMassCount > 0) { diff --git a/test-data/simple/module.ron b/test-data/simple/module.ron index b45c6b417..c3c34fc6b 100644 --- a/test-data/simple/module.ron +++ b/test-data/simple/module.ron @@ -104,7 +104,7 @@ ), ], body: [ - Empty, + Block([]), Store( pointer: 2, value: 6, From 8c48ae51ce61e4dfc7714a40b9ac4d771b2c5eec Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 22 Sep 2020 17:50:56 +0200 Subject: [PATCH 0218/2212] [glsl-in] consolidate tests (#206) * [glsl-in] consolidate tests - remove simple lex test as was covered by others - combine related tests to single function - remove redundant prefix in test names * [glsl-in] Consolidtae lex tests further --- src/front/glsl/lex_tests.rs | 91 ++++------------------------------ src/front/glsl/parser_tests.rs | 7 ++- 2 files changed, 14 insertions(+), 84 deletions(-) diff --git a/src/front/glsl/lex_tests.rs b/src/front/glsl/lex_tests.rs index 7710b4eb9..584baf302 100644 --- a/src/front/glsl/lex_tests.rs +++ b/src/front/glsl/lex_tests.rs @@ -1,62 +1,9 @@ use super::{lex::Lexer, parser::Token::*, token::TokenMetadata}; #[test] -fn glsl_lex_simple() { - let source = "void main() {\n}"; - let mut lex = Lexer::new(source); - - assert_eq!( - lex.next().unwrap(), - Void(TokenMetadata { - line: 0, - chars: 0..4 - }) - ); - assert_eq!( - lex.next().unwrap(), - Identifier(( - TokenMetadata { - line: 0, - chars: 5..9 - }, - "main".into() - )) - ); - assert_eq!( - lex.next().unwrap(), - LeftParen(TokenMetadata { - line: 0, - chars: 9..10 - }) - ); - assert_eq!( - lex.next().unwrap(), - RightParen(TokenMetadata { - line: 0, - chars: 10..11 - }) - ); - assert_eq!( - lex.next().unwrap(), - LeftBrace(TokenMetadata { - line: 0, - chars: 12..13 - }) - ); - assert_eq!( - lex.next().unwrap(), - RightBrace(TokenMetadata { - line: 1, - chars: 0..1 - }) - ); - assert_eq!(lex.next(), None); -} - -#[test] -fn glsl_lex_line_comment() { - let source = "void main // myfunction\n//()\n{}"; - let mut lex = Lexer::new(source); +fn tokens() { + // line comments + let mut lex = Lexer::new("void main // myfunction\n//()\n{}"); assert_eq!( lex.next().unwrap(), Void(TokenMetadata { @@ -89,13 +36,9 @@ fn glsl_lex_line_comment() { }) ); assert_eq!(lex.next(), None); -} - -#[test] -fn glsl_lex_multi_line_comment() { - let source = "void main /* comment [] {}\n/**\n{}*/{}"; - let mut lex = Lexer::new(source); + // multi line comment + let mut lex = Lexer::new("void main /* comment [] {}\n/**\n{}*/{}"); assert_eq!( lex.next().unwrap(), Void(TokenMetadata { @@ -128,13 +71,9 @@ fn glsl_lex_multi_line_comment() { }) ); assert_eq!(lex.next(), None); -} - -#[test] -fn glsl_lex_identifier() { - let source = "id123_OK 92No æNoø No¾ No好"; - let mut lex = Lexer::new(source); + // identifiers + let mut lex = Lexer::new("id123_OK 92No æNoø No¾ No好"); assert_eq!( lex.next().unwrap(), Identifier(( @@ -236,13 +175,9 @@ fn glsl_lex_identifier() { )) ); assert_eq!(lex.next(), None); -} - -#[test] -fn glsl_lex_version() { - let source = "#version 890 core"; - let mut lex = Lexer::new(source); + // version + let mut lex = Lexer::new("#version 890 core"); assert_eq!( lex.next().unwrap(), Version(TokenMetadata { @@ -271,13 +206,9 @@ fn glsl_lex_version() { )) ); assert_eq!(lex.next(), None); -} - -#[test] -fn glsl_lex_operators() { - let source = "+ - * | & % / += -= *= |= &= %= /= ++ -- || && ^^"; - let mut lex = Lexer::new(source); + // operators + let mut lex = Lexer::new("+ - * | & % / += -= *= |= &= %= /= ++ -- || && ^^"); assert_eq!( lex.next().unwrap(), Plus(TokenMetadata { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 285df911d..14db86fda 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -17,7 +17,8 @@ fn parse_program(source: &str, stage: ShaderStage) -> Result } #[test] -fn glsl_parser_version_invalid() { +fn version() { + // invalid versions assert_eq!( format!( "{:?}", @@ -47,10 +48,8 @@ fn glsl_parser_version_invalid() { ), "InvalidProfile(TokenMetadata { line: 0, chars: 13..18 }, \"smart\")" ); -} -#[test] -fn glsl_parser_version_valid() { + // valid versions let program = parse_program("#version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); assert_eq!( format!("{:?}", (program.version, program.profile)), From e5d17e878b7a823ef71e8c7da64d37a60f75f7aa Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 22 Sep 2020 17:52:51 +0200 Subject: [PATCH 0219/2212] [glsl-in] Support anonymous global uniforms (#211) * [glsl-in] Support anonymous global uniforms Partly fixes #210 * [glsl-in] Handle anon global structs in fn prelude --- src/front/glsl/ast.rs | 2 +- src/front/glsl/parser.rs | 38 ++++++++++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index bd8f12595..ce63dee0b 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -159,7 +159,7 @@ pub enum TypeQualifier { #[derive(Debug)] pub struct VarDeclaration { pub type_qualifiers: Vec, - pub ids_initializers: Vec<(String, Option)>, + pub ids_initializers: Vec<(Option, Option)>, pub ty: Handle, } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index e0dff7325..31aab6d7b 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -475,7 +475,7 @@ pomelo! { struct_declaration_list(sdl) RightBrace Semicolon { VarDeclaration{ type_qualifiers: t, - ids_initializers: vec![], + ids_initializers: vec![(None, None)], ty: extra.module.types.fetch_or_append(Type{ name: Some(i.1), inner: TypeInner::Struct { @@ -489,7 +489,7 @@ pomelo! { struct_declaration_list(sdl) RightBrace Identifier(i2) Semicolon { VarDeclaration{ type_qualifiers: t, - ids_initializers: vec![(i2.1, None)], + ids_initializers: vec![(Some(i2.1), None)], ty: extra.module.types.fetch_or_append(Type{ name: Some(i1.1), inner: TypeInner::Struct { @@ -504,13 +504,13 @@ pomelo! { init_declarator_list ::= single_declaration; init_declarator_list ::= init_declarator_list(mut idl) Comma Identifier(i) { - idl.ids_initializers.push((i.1, None)); + idl.ids_initializers.push((Some(i.1), None)); idl } // init_declarator_list ::= init_declarator_list Comma Identifier array_specifier; // init_declarator_list ::= init_declarator_list Comma Identifier array_specifier Equal initializer; init_declarator_list ::= init_declarator_list(mut idl) Comma Identifier(i) Equal initializer(init) { - idl.ids_initializers.push((i.1, Some(init))); + idl.ids_initializers.push((Some(i.1), Some(init))); idl } @@ -528,7 +528,7 @@ pomelo! { VarDeclaration{ type_qualifiers: t.0, - ids_initializers: vec![(i.1, None)], + ids_initializers: vec![(Some(i.1), None)], ty, } } @@ -539,7 +539,7 @@ pomelo! { VarDeclaration{ type_qualifiers: t.0, - ids_initializers: vec![(i.1, Some(init))], + ids_initializers: vec![(Some(i.1), Some(init))], ty, } } @@ -705,6 +705,7 @@ pomelo! { let mut statements = Vec::::new(); // local variables for (id, initializer) in d.ids_initializers { + let id = id.ok_or(ErrorKind::SemanticError("local var must be named"))?; // check if already declared in current scope #[cfg(feature = "glsl-validate")] { @@ -793,6 +794,25 @@ pomelo! { Expression::GlobalVariable(var_handle) ); extra.context.lookup_global_var_exps.insert(name.clone(), exp); + } else { + let ty = &extra.module.types[var.ty]; + // anonymous structs + if let TypeInner::Struct { members } = &ty.inner { + let base = extra.context.expressions.append( + Expression::GlobalVariable(var_handle) + ); + for (idx, member) in members.iter().enumerate() { + if let Some(name) = member.name.as_ref() { + let exp = extra.context.expressions.append( + Expression::AccessIndex{ + base, + index: idx as u32, + } + ); + extra.context.lookup_global_var_exps.insert(name.clone(), exp); + } + } + } } } f @@ -871,7 +891,7 @@ pomelo! { for (id, initializer) in d.ids_initializers { let h = extra.module.global_variables.fetch_or_append( GlobalVariable { - name: Some(id.clone()), + name: id.clone(), class, binding: binding.clone(), ty: d.ty, @@ -879,7 +899,9 @@ pomelo! { storage_access: StorageAccess::empty(), //TODO }, ); - extra.lookup_global_variables.insert(id, h); + if let Some(id) = id { + extra.lookup_global_variables.insert(id, h); + } } } From 7ce99774d57d83bd92a408fefbaa129db10c2e25 Mon Sep 17 00:00:00 2001 From: Nicholas Rishel Date: Tue, 22 Sep 2020 21:48:31 -0700 Subject: [PATCH 0220/2212] Add legend for supported end-points (#212) There's no legend explaining what symbols mean for supported end-points, but it seems to be following the same format at wgpu. This PR copies wgpu's legend. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 0643c94a5..d0672f636 100644 --- a/README.md +++ b/README.md @@ -27,3 +27,5 @@ AIR | | | DXIR | | | DXIL | | | DXBC | | | + +:heavy_check_mark: = Primary support — :white_check_mark: = Secondary support — :construction: = Unsupported, but support in progress From df9834258f819ca01154252ceba5eef63b629734 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Fri, 25 Sep 2020 16:32:50 +0200 Subject: [PATCH 0221/2212] [glsl-in] Implement swizzle for r-values (#213) * [glsl-in] Implement swizzle for r-values Related to #210 * [glsl-in] Just return Result from field_selection Removed unneccessary Otion in return type * [glsl-in] Always match on type in field_selection * [glsl.in] Borrow by value in field_selection --- src/front/glsl/parser.rs | 17 ++------ src/front/glsl/variables.rs | 84 +++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 14 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 31aab6d7b..d5da8f385 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -218,20 +218,9 @@ pomelo! { } postfix_expression ::= function_call; postfix_expression ::= postfix_expression(e) Dot Identifier(i) /* FieldSelection in spec */ { - let type_inner = extra.resolve_type(e.expression)?; - if let TypeInner::Struct{members} = type_inner { - let index = members.iter().position(|m| m.name == Some(i.1.clone())) - .ok_or(ErrorKind::UnknownField(i.0, i.1))?; - ExpressionRule::from_expression( - extra.context.expressions.append(Expression::AccessIndex { - base: e.expression, - index: index as u32, - }) - ) - } else { - //TODO: swizzle - return Err(ErrorKind::SemanticError("Can't lookup field on this type")) - } + //TODO: how will this work as l-value? + let expression = extra.field_selection(e.expression, &*i.1, i.0)?; + ExpressionRule { expression, statements: e.statements } } postfix_expression ::= postfix_expression(pe) IncOp { //TODO diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 834f78765..c4d37b7bb 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -5,6 +5,7 @@ use crate::{ use super::ast::*; use super::error::ErrorKind; +use super::token::TokenMetadata; impl Program { pub fn lookup_variable(&mut self, name: &str) -> Result>, ErrorKind> { @@ -96,4 +97,87 @@ impl Program { Ok(None) } } + + pub fn field_selection( + &mut self, + expression: Handle, + name: &str, + meta: TokenMetadata, + ) -> Result, ErrorKind> { + match *self.resolve_type(expression)? { + TypeInner::Struct { ref members } => { + let index = members + .iter() + .position(|m| m.name == Some(name.into())) + .ok_or_else(|| ErrorKind::UnknownField(meta, name.into()))?; + Ok(self.context.expressions.append(Expression::AccessIndex { + base: expression, + index: index as u32, + })) + } + // swizzles (xyzw, rgba, stpq) + TypeInner::Vector { size, kind, width } => { + let check_swizzle_components = |comps: &str| { + name.chars() + .map(|c| { + comps + .find(c) + .and_then(|i| if i < size as usize { Some(i) } else { None }) + }) + .fold(Some(Vec::::new()), |acc, cur| { + cur.and_then(|i| { + acc.map(|mut v| { + v.push(i); + v + }) + }) + }) + }; + + let indices = check_swizzle_components("xyzw") + .or_else(|| check_swizzle_components("rgba")) + .or_else(|| check_swizzle_components("stpq")); + + if let Some(v) = indices { + let components: Vec> = v + .iter() + .map(|idx| { + self.context.expressions.append(Expression::AccessIndex { + base: expression, + index: *idx as u32, + }) + }) + .collect(); + if components.len() == 1 { + // only single element swizzle, like pos.y, just return that component + Ok(components[0]) + } else { + Ok(self.context.expressions.append(Expression::Compose { + ty: self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + kind, + width, + size: match components.len() { + 2 => VectorSize::Bi, + 3 => VectorSize::Tri, + 4 => VectorSize::Quad, + _ => { + return Err(ErrorKind::SemanticError( + "Bad swizzle size", + )); + } + }, + }, + }), + components, + })) + } + } else { + Err(ErrorKind::SemanticError("Invalid swizzle for vector")) + } + } + _ => Err(ErrorKind::SemanticError("Can't lookup field on this type")), + } + } } From 7e809c605abd3f759ff1fbd3973cec31d13f8a02 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 28 Sep 2020 01:09:47 -0400 Subject: [PATCH 0222/2212] Remove validation error lifetime --- src/proc/validator.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 1c6fcc59c..694e23f84 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -56,7 +56,7 @@ pub enum EntryPointError { } #[derive(Clone, Debug, thiserror::Error)] -pub enum ValidationError<'a> { +pub enum ValidationError { #[error("The type {0:?} width {1} is not supported")] InvalidTypeWidth(crate::ScalarKind, crate::Bytes), #[error("The type handle {0:?} can not be resolved")] @@ -68,7 +68,7 @@ pub enum ValidationError<'a> { #[error("Entry point {name} at {stage:?} is invalid: {error:?}")] EntryPoint { stage: crate::ShaderStage, - name: &'a str, + name: String, error: EntryPointError, }, } @@ -314,7 +314,7 @@ impl Validator { } /// Check the given module to be valid. - pub fn validate<'a>(&mut self, module: &'a crate::Module) -> Result<(), ValidationError<'a>> { + pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { // check the types for (handle, ty) in module.types.iter() { use crate::TypeInner as Ti; @@ -365,7 +365,11 @@ impl Validator { for (&(stage, ref name), entry_point) in module.entry_points.iter() { self.validate_entry_point(entry_point, stage, module) - .map_err(|error| ValidationError::EntryPoint { stage, name, error })?; + .map_err(|error| ValidationError::EntryPoint { + stage, + name: name.to_string(), + error, + })?; } Ok(()) From 541d1dcb8b01d9e1389d9b3cf6a1f9c9db3dc120 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 28 Sep 2020 01:10:12 -0400 Subject: [PATCH 0223/2212] Fix convert_phong_lighting test feature checks --- tests/convert.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/tests/convert.rs b/tests/convert.rs index b0ec3cc49..6fc59e30c 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -182,13 +182,16 @@ fn convert_phong_lighting() { ); naga::proc::Validator::new().validate(&module).unwrap(); - let header = naga::Header { - version: (1, 0, 0), - generator: 1234, - }; - let writer_flags = naga::back::spv::WriterFlags::empty(); - let mut w = naga::back::spv::Writer::new(&header, writer_flags); - w.write(&module); + #[cfg(feaure = "spv-out")] + { + let header = naga::Header { + version: (1, 0, 0), + generator: 1234, + }; + let writer_flags = naga::back::spv::WriterFlags::empty(); + let mut w = naga::back::spv::Writer::new(&header, writer_flags); + w.write(&module); + } } //TODO: get this working again (glsl-new) From e57d877dbc83b0517d33c0550b9ee07d2ac7e3f7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 28 Sep 2020 01:40:35 -0400 Subject: [PATCH 0224/2212] [spv] fix storage buffer detection --- src/front/spv/mod.rs | 26 +++++++++++++++++--------- src/proc/validator.rs | 1 + 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d88f6ec1d..3b42f1092 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -315,6 +315,7 @@ pub struct Parser { handle_sampling: FastHashMap, SamplingFlags>, lookup_type: FastHashMap, lookup_void_type: FastHashSet, + lookup_storage_buffer_types: FastHashSet>, // Lookup for samplers and sampled images, storing flags on how they are used. lookup_constant: FastHashMap, lookup_variable: FastHashMap, @@ -339,6 +340,7 @@ impl> Parser { lookup_member_type_id: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_void_type: FastHashSet::default(), + lookup_storage_buffer_types: FastHashSet::default(), lookup_constant: FastHashMap::default(), lookup_variable: FastHashMap::default(), lookup_expression: FastHashMap::default(), @@ -1964,11 +1966,12 @@ impl> Parser { inst.expect_at_least(2)?; let id = self.next()?; let parent_decor = self.future_decor.remove(&id); - if let Some(ref decor) = parent_decor { - if decor.block.is_some() { - // do nothing - } - } + let is_buffer_block = parent_decor + .as_ref() + .map_or(false, |decor| match decor.block { + Some(Block { buffer }) => buffer, + _ => false, + }); let mut members = Vec::with_capacity(inst.wc as usize - 2); let mut member_type_ids = Vec::with_capacity(members.capacity()); @@ -1993,6 +1996,9 @@ impl> Parser { inner, }); + if is_buffer_block { + self.lookup_storage_buffer_types.insert(ty_handle); + } for (i, type_id) in member_type_ids.into_iter().enumerate() { self.lookup_member_type_id .insert((ty_handle, i as u32), type_id); @@ -2225,7 +2231,7 @@ impl> Parser { inst.expect_at_least(4)?; let type_id = self.next()?; let id = self.next()?; - let storage = self.next()?; + let storage_class = self.next()?; if inst.wc != 4 { inst.expect(5)?; let _init = self.next()?; //TODO @@ -2235,7 +2241,7 @@ impl> Parser { .future_decor .remove(&id) .ok_or(Error::InvalidBinding(id))?; - let class = map_storage_class(storage)?; + let class = map_storage_class(storage_class)?; let binding = match (class, &module.types[lookup_type.handle].inner) { (crate::StorageClass::Input, &crate::TypeInner::Struct { .. }) | (crate::StorageClass::Output, &crate::TypeInner::Struct { .. }) => None, @@ -2243,8 +2249,10 @@ impl> Parser { }; let is_storage = match module.types[lookup_type.handle].inner { crate::TypeInner::Struct { .. } => match class { - crate::StorageClass::StorageBuffer | crate::StorageClass::Constant => true, // careful with `Constant` here! - _ => false, + crate::StorageClass::StorageBuffer => true, + _ => self + .lookup_storage_buffer_types + .contains(&lookup_type.handle), }, crate::TypeInner::Image { class: crate::ImageClass::Storage(_), diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 694e23f84..cf6029d93 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -296,6 +296,7 @@ impl Validator { } }; if !allowed_usage.contains(usage) { + log::debug!("\tAllowed usage: {:?}", allowed_usage); return Err(EntryPointError::InvalidGlobalUsage(var_handle, usage)); } From 53627c5cd865a06afe3ca65f5318bf4549f1b34d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 28 Sep 2020 01:41:50 -0400 Subject: [PATCH 0225/2212] [valid] allow dynamic access into vectors --- src/proc/typifier.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 9db625c41..a02def71e 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -93,6 +93,11 @@ impl Typifier { Ok(match *expr { crate::Expression::Access { base, .. } => match *self.get(base, types) { crate::TypeInner::Array { base, .. } => Resolution::Handle(base), + crate::TypeInner::Vector { + size: _, + kind, + width, + } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), ref other => panic!("Can't access into {:?}", other), }, crate::Expression::AccessIndex { base, index } => match *self.get(base, types) { From d03c95a576fe5fdf37f58c418154f00b40a1dddd Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 28 Sep 2020 01:56:30 -0400 Subject: [PATCH 0226/2212] Add more methods recognized by the typifier --- src/proc/typifier.rs | 6 ++++-- src/proc/validator.rs | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index a02def71e..8c67df2c3 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -265,8 +265,10 @@ impl Typifier { } ref other => panic!("Unexpected argument {:?} on {}", other, name), }, - "atan2" | "cos" | "sin" | "normalize" | "max" | "reflect" | "pow" | "clamp" - | "fclamp" | "mix" => self.resolutions[arguments[0].index()].clone(), + //Note: `cross` is here too, we still need to figure out what to do with it + "abs" | "atan2" | "cos" | "sin" | "floor" | "inverse" | "normalize" | "min" + | "max" | "reflect" | "pow" | "clamp" | "fclamp" | "mix" | "step" + | "smoothstep" | "cross" => self.resolutions[arguments[0].index()].clone(), _ => return Err(ResolveError::FunctionNotDefined { name: name.clone() }), }, crate::Expression::Call { diff --git a/src/proc/validator.rs b/src/proc/validator.rs index cf6029d93..616b141d3 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -296,7 +296,12 @@ impl Validator { } }; if !allowed_usage.contains(usage) { - log::debug!("\tAllowed usage: {:?}", allowed_usage); + log::warn!("\tUsage error for: {:?}", var); + log::warn!( + "\tAllowed usage: {:?}, requested: {:?}", + allowed_usage, + usage + ); return Err(EntryPointError::InvalidGlobalUsage(var_handle, usage)); } From 8323521b838cf7a7cb4163c84f0f4ff237622f9a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 28 Sep 2020 01:56:47 -0400 Subject: [PATCH 0227/2212] [valid] move out the integer interpolation check to the entry point --- src/proc/validator.rs | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 616b141d3..a730db74b 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -51,6 +51,8 @@ pub enum EntryPointError { BindingCollision(Handle), #[error("Built-in {0:?} is not applicable to this entry point")] InvalidBuiltIn(crate::BuiltIn), + #[error("Interpolation of an integer has to be flat")] + InvalidIntegerInterpolation, #[error(transparent)] Function(#[from] FunctionError), } @@ -102,15 +104,9 @@ impl Validator { return Err(GlobalVariableError::OutOfRangeBinding); } match types[var.ty].inner { - crate::TypeInner::Scalar { kind, .. } - | crate::TypeInner::Vector { kind, .. } - | crate::TypeInner::Matrix { kind, .. } => { - if kind != crate::ScalarKind::Float - && var.interpolation != Some(crate::Interpolation::Flat) - { - return Err(GlobalVariableError::InvalidInterpolation); - } - } + crate::TypeInner::Scalar { .. } + | crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } => {} _ => return Err(GlobalVariableError::InvalidType), } } @@ -226,6 +222,27 @@ impl Validator { continue; } + if let Some(crate::Binding::Location(_)) = var.binding { + match (stage, var.class) { + (crate::ShaderStage::Vertex, crate::StorageClass::Output) + | (crate::ShaderStage::Fragment, crate::StorageClass::Input) => { + match module.types[var.ty].inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } + | crate::TypeInner::Matrix { kind, .. } => { + if kind != crate::ScalarKind::Float + && var.interpolation != Some(crate::Interpolation::Flat) + { + return Err(EntryPointError::InvalidIntegerInterpolation); + } + } + _ => unreachable!(), + } + } + _ => {} + } + } + let allowed_usage = match var.class { crate::StorageClass::Function => unreachable!(), crate::StorageClass::Input => { From 6de675313b16f89b9f93693a831b1b877df57043 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 28 Sep 2020 23:26:44 -0400 Subject: [PATCH 0228/2212] [spv] fix stack overflow in type writing --- src/back/spv/writer.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index faca512f6..b473dd808 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -426,8 +426,9 @@ impl Writer { let id = self.generate_id(); let instruction = match local_ty { LocalType::Scalar { kind, width } => self.write_scalar(id, kind, width), - LocalType::Vector { size, .. } => { - let scalar_id = self.get_type_id(arena, LookupType::Local(local_ty)); + LocalType::Vector { size, kind, width } => { + let scalar_id = + self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width })); super::instructions::instruction_type_vector(id, scalar_id, size) } LocalType::Pointer { .. } => unimplemented!(), From b56c2ddbdc448dc1e783a30343e8c648ce825a5c Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Wed, 30 Sep 2020 22:35:57 +0200 Subject: [PATCH 0229/2212] [spv-out] Fix write_function returning block id --- src/back/spv/writer.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b473dd808..90e906f1d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -311,23 +311,23 @@ impl Writer { parameter_type_ids, }; - let id = self.generate_id(); + let function_id = self.generate_id(); let function_type = self.get_function_type(lookup_function_type, function_parameter_pointer_ids); function.signature = Some(super::instructions::instruction_function( return_type_id, - id, + function_id, spirv::FunctionControl::empty(), function_type, )); - let id = self.write_block(&ir_function.body, ir_module, ir_function, &mut function); + self.write_block(&ir_function.body, ir_module, ir_function, &mut function); function.to_words(&mut self.logical_layout.function_definitions); super::instructions::instruction_function_end() .to_words(&mut self.logical_layout.function_definitions); - id + function_id } // TODO Move to instructions module From e0f593f35f34f3757cf9853c7517b8eedb763e6e Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Thu, 1 Oct 2020 20:46:48 +0200 Subject: [PATCH 0230/2212] [spv-out] Add matrix construct support --- src/back/spv/writer.rs | 68 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 8 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 90e906f1d..7821d2b4e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -776,6 +776,23 @@ impl Writer { } } + fn write_composite_construct( + &mut self, + base_type_id: Word, + constituent_ids: &[Word], + block: &mut Block, + ) -> Word { + let id = self.generate_id(); + block + .body + .push(super::instructions::instruction_composite_construct( + base_type_id, + id, + constituent_ids, + )); + id + } + fn write_expression<'a>( &mut self, ir_module: &'a crate::Module, @@ -800,8 +817,7 @@ impl Writer { Some((id, Some(var.ty))) } crate::Expression::Compose { ty, components } => { - let id = self.generate_id(); - let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*ty)); + let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*ty)); let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { @@ -811,13 +827,49 @@ impl Writer { .unwrap(); constituent_ids.push(component_id); } + let constituent_ids_slice = constituent_ids.as_slice(); + + let id = match ir_module.types[*ty].inner { + crate::TypeInner::Vector { .. } => { + self.write_composite_construct(base_type_id, constituent_ids_slice, block) + } + crate::TypeInner::Matrix { + rows, + columns, + kind, + width, + } => { + let vector_type_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Vector { + width, + kind, + size: columns, + }), + ); + + let capacity = match rows { + crate::VectorSize::Bi => 2, + crate::VectorSize::Tri => 3, + crate::VectorSize::Quad => 4, + }; + + let mut vector_ids = Vec::with_capacity(capacity); + + for _ in 0..capacity { + let vector_id = self.write_composite_construct( + vector_type_id, + constituent_ids_slice, + block, + ); + vector_ids.push(vector_id); + } + + self.write_composite_construct(base_type_id, vector_ids.as_slice(), block) + } + _ => unreachable!(), + }; - let instruction = super::instructions::instruction_composite_construct( - type_id, - id, - constituent_ids.as_slice(), - ); - block.body.push(instruction); Some((id, Some(*ty))) } crate::Expression::Binary { op, left, right } => { From 842079a3cd7528282d6ccc2a991f894bcaea4bf2 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 1 Oct 2020 12:31:16 +0000 Subject: [PATCH 0231/2212] [glsl-in] Handle spacing for preproces directives --- src/front/glsl/lex.rs | 29 ++++++++++++++++++++--------- src/front/glsl/parser_tests.rs | 16 ++++++++++++++++ 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 6502bbb5a..f0b9e6b95 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -16,7 +16,7 @@ fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str, usize) (o, i, pos) } -pub fn consume_token(mut input: &str) -> (Option, &str) { +pub fn consume_token(mut input: &str, start_of_line: bool) -> (Option, &str) { let start = input .find(|c: char| !c.is_whitespace()) .unwrap_or_else(|| input.chars().count()); @@ -246,13 +246,21 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { } } '#' => { - input = chars.as_str(); - let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); - meta.chars.end = start + 1 + pos; - match word { - "version" => (Some(Token::Version(meta)), rest), - _ => (None, input), - } + if start_of_line { + input = chars.as_str(); + + // skip whitespace + let word_start = input + .find(|c: char| !c.is_whitespace()) + .unwrap_or_else(|| input.chars().count()); + input = &input[word_start..]; + + let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); + meta.chars.end = start + word_start + 1 + pos; + match word { + "version" => (Some(Token::Version(meta)), rest), + _ => (None, input), + } //TODO: preprocessor // if chars.next() == Some(cur) { @@ -260,6 +268,9 @@ pub fn consume_token(mut input: &str) -> (Option, &str) { // } else { // (Token::Preprocessor, input, start, start + 1) // } + } else { + (Some(Token::Unknown((meta, '#'))), chars.as_str()) + } } '~' => (Some(Token::Tilde(meta)), chars.as_str()), '?' => (Some(Token::Question(meta)), chars.as_str()), @@ -302,7 +313,7 @@ impl<'a> Lexer<'a> { #[must_use] pub fn next(&mut self) -> Option { - let (token, rest) = consume_token(&self.input); + let (token, rest) = consume_token(&self.input, self.offset == 0); if let Some(mut token) = token { self.input = String::from(rest); diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 14db86fda..77cdac557 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -49,7 +49,23 @@ fn version() { "InvalidProfile(TokenMetadata { line: 0, chars: 13..18 }, \"smart\")" ); + assert_eq!( + format!( + "{:?}", + parse_program("#version 450\nvoid f(){} #version 450", ShaderStage::Vertex) + .err() + .unwrap() + ), + "InvalidToken(Unknown((TokenMetadata { line: 1, chars: 11..12 }, \'#\')))" + ); + // valid versions + let program = parse_program(" # version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); + assert_eq!( + format!("{:?}", (program.version, program.profile)), + "(450, Core)" + ); + let program = parse_program("#version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); assert_eq!( format!("{:?}", (program.version, program.profile)), From 98167103c2a5f019de7fab4ec547fbee1fbddb82 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sun, 4 Oct 2020 01:13:40 +0200 Subject: [PATCH 0232/2212] [spv-out] Remove instruction spec tests --- src/back/spv/instructions.rs | 699 --------------------------------- src/back/spv/test_framework.rs | 36 +- 2 files changed, 1 insertion(+), 734 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 78a934d40..bc5cc752d 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -531,702 +531,3 @@ pub(super) fn instruction_return_value(value_id: Word) -> Instruction { // // Primitive Instructions // - -#[cfg(test)] -mod tests { - use crate::back::spv::test_framework::*; - use spirv::*; - - #[test] - fn test_spec_conformance() { - let suite = SpecConformanceSuite {}; - suite.test_all_instructions() - } - - struct SpecConformanceSuite; - - impl SpecConformanceSuite { - fn test_all_instructions(&self) { - self.test_instruction_source(); - self.test_instruction_name(); - self.test_instruction_decorate(); - self.test_instruction_ext_inst_import(); - self.test_instruction_memory_model(); - self.test_instruction_entry_point(); - self.test_instruction_execution_mode(); - self.test_instruction_capability(); - self.test_instruction_type_void(); - self.test_instruction_type_bool(); - self.test_instruction_type_int(); - self.test_instruction_type_float(); - self.test_instruction_type_vector(); - self.test_instruction_type_matrix(); - self.test_instruction_type_image(); - self.test_instruction_type_sampler(); - self.test_instruction_type_array(); - self.test_instruction_type_runtime_array(); - self.test_instruction_type_struct(); - self.test_instruction_type_pointer(); - self.test_instruction_type_function(); - self.test_instruction_constant_true(); - self.test_instruction_constant_false(); - self.test_instruction_constant(); - self.test_instruction_constant_composite(); - self.test_instruction_variable(); - self.test_instruction_load(); - self.test_instruction_store(); - self.test_instruction_function(); - self.test_instruction_function_parameter(); - self.test_instruction_function_end(); - self.test_instruction_function_call(); - self.test_instruction_composite_construct(); - self.test_instruction_vector_times_scalar(); - self.test_instruction_label(); - self.test_instruction_return(); - self.test_instruction_return_value(); - } - - fn test_instruction_source(&self) { - let version = 450; - let instruction = super::instruction_source(SourceLanguage::GLSL, version); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Source, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_name(&self) { - let instruction = super::instruction_name(1, "Test"); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Name, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_decorate(&self) { - let instruction = super::instruction_decorate(1, Decoration::Location, &[1]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Decorate, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_ext_inst_import(&self) { - let import_name = "GLSL.std.450"; - let instruction = super::instruction_ext_inst_import(1, import_name); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ExtInstImport, - wc: 3, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_memory_model(&self) { - let instruction = - super::instruction_memory_model(AddressingModel::Logical, MemoryModel::GLSL450); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::MemoryModel, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_entry_point(&self) { - let instruction = - super::instruction_entry_point(spirv::ExecutionModel::Fragment, 1, "main", &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::EntryPoint, - wc: 4, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_execution_mode(&self) { - let instruction = super::instruction_execution_mode(1, ExecutionMode::OriginUpperLeft); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ExecutionMode, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_capability(&self) { - let instruction = super::instruction_capability(Capability::Shader); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Capability, - wc: 2, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_void(&self) { - let instruction = super::instruction_type_void(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeVoid, - wc: 2, - type_id: false, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_bool(&self) { - let instruction = super::instruction_type_bool(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeBool, - wc: 2, - type_id: false, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_int(&self) { - let instruction = super::instruction_type_int(1, 32, super::Signedness::Signed); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeInt, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_float(&self) { - let instruction = super::instruction_type_float(1, 32); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeFloat, - wc: 3, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_vector(&self) { - let instruction = super::instruction_type_vector(1, 1, crate::VectorSize::Bi); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeVector, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_matrix(&self) { - let instruction = super::instruction_type_matrix(1, 1, crate::VectorSize::Bi); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeMatrix, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_image(&self) { - let instruction = super::instruction_type_image( - 1, - 1, - spirv::Dim::Dim3D, - true, - crate::ImageClass::Sampled { - kind: crate::ScalarKind::Float, - multi: true, - }, - ); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeImage, - wc: 9, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_sampler(&self) { - let instruction = super::instruction_type_sampler(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeSampler, - wc: 2, - type_id: false, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_array(&self) { - let instruction = super::instruction_type_array(1, 1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeArray, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_runtime_array(&self) { - let instruction = super::instruction_type_runtime_array(1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeRuntimeArray, - wc: 3, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_struct(&self) { - let instruction = super::instruction_type_struct(1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeStruct, - wc: 2, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_pointer(&self) { - let instruction = super::instruction_type_pointer(1, spirv::StorageClass::Function, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypePointer, - wc: 4, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_type_function(&self) { - let instruction = super::instruction_type_function(1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::TypeFunction, - wc: 3, - type_id: false, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_constant_true(&self) { - let instruction = super::instruction_constant_true(1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ConstantTrue, - wc: 3, - type_id: true, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_constant_false(&self) { - let instruction = super::instruction_constant_false(1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ConstantFalse, - wc: 3, - type_id: true, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_constant(&self) { - let instruction = super::instruction_constant(1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Constant, - wc: 3, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_constant_composite(&self) { - let instruction = super::instruction_constant_composite(1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ConstantComposite, - wc: 3, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_variable(&self) { - let instruction = - super::instruction_variable(1, 1, spirv::StorageClass::Function, Some(1)); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Variable, - wc: 4, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_load(&self) { - let instruction = super::instruction_load(1, 1, 1, None); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Load, - wc: 4, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_store(&self) { - let instruction = super::instruction_store(1, 1, None); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Store, - wc: 3, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_function(&self) { - let instruction = super::instruction_function(1, 1, spirv::FunctionControl::NONE, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Function, - wc: 5, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_function_parameter(&self) { - let instruction = super::instruction_function_parameter(1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::FunctionParameter, - wc: 3, - type_id: true, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_function_end(&self) { - let instruction = super::instruction_function_end(); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::FunctionEnd, - wc: 1, - type_id: false, - result_id: false, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_function_call(&self) { - let instruction = super::instruction_function_call(1, 1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::FunctionCall, - wc: 4, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_composite_construct(&self) { - let instruction = super::instruction_composite_construct(1, 1, &[1, 2]); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::CompositeConstruct, - wc: 3, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_vector_times_scalar(&self) { - let instruction = super::instruction_vector_times_scalar(1, 1, 1, 1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::VectorTimesScalar, - wc: 5, - type_id: true, - result_id: true, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_label(&self) { - let instruction = super::instruction_label(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Label, - wc: 2, - type_id: false, - result_id: true, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_return(&self) { - let instruction = super::instruction_return(); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::Return, - wc: 1, - type_id: false, - result_id: false, - operands: false, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - - fn test_instruction_return_value(&self) { - let instruction = super::instruction_return_value(1); - let mut output = vec![]; - - let requirements = SpecRequirements { - op: Op::ReturnValue, - wc: 2, - type_id: false, - result_id: false, - operands: true, - }; - validate_spec_requirements(requirements, &instruction); - - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); - } - } -} diff --git a/src/back/spv/test_framework.rs b/src/back/spv/test_framework.rs index 332d300a4..a21aeb0f0 100644 --- a/src/back/spv/test_framework.rs +++ b/src/back/spv/test_framework.rs @@ -1,38 +1,4 @@ -use crate::back::spv::Instruction; -use spirv::{Op, Word}; - -pub(super) struct SpecRequirements { - pub(super) op: Op, - pub(super) wc: u32, - pub(super) type_id: bool, - pub(super) result_id: bool, - pub(super) operands: bool, -} - -/// Basic validation for checking if the instruction complies to the spec requirements -pub(super) fn validate_spec_requirements( - requirements: SpecRequirements, - instruction: &Instruction, -) { - assert_eq!(requirements.op, instruction.op); - - // Pass the assert if the minimum referred wc in the spec is met - assert!(instruction.wc >= requirements.wc); - - if requirements.type_id { - assert!(instruction.type_id.is_some()); - } - - if requirements.result_id { - assert!(instruction.result_id.is_some()); - } - - if requirements.operands { - assert!(!instruction.operands.is_empty()); - } -} - -pub(super) fn validate_instruction(words: &[Word], instruction: &Instruction) { +pub(super) fn validate_instruction(words: &[spirv::Word], instruction: &crate::back::spv::Instruction) { let mut inst_index = 0; let (wc, op) = ((words[inst_index] >> 16) as u16, words[inst_index] as u16); inst_index += 1; From 90c56aca2fcdd1ca0568d78aa4bde7ef5e4b3a4e Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sat, 3 Oct 2020 00:47:39 +0200 Subject: [PATCH 0233/2212] [spv-out] Add scalar conversion support --- src/back/spv/instructions.rs | 42 +++++++++++++++++++++ src/back/spv/writer.rs | 73 ++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index bc5cc752d..39a9c4e73 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -453,7 +453,49 @@ pub(super) fn instruction_function_call( // // Conversion Instructions // +fn instruction_unary(op: Op, result_type_id: Word, id: Word, value: Word) -> Instruction { + let mut instruction = Instruction::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(value); + instruction +} +pub(super) fn instruction_convert_f_to_u( + result_type_id: Word, + id: Word, + float_value: Word, +) -> Instruction { + instruction_unary(Op::ConvertFToU, result_type_id, id, float_value) +} + +pub(super) fn instruction_convert_f_to_s( + result_type_id: Word, + id: Word, + float_value: Word, +) -> Instruction { + instruction_unary(Op::ConvertFToS, result_type_id, id, float_value) +} + +pub(super) fn instruction_convert_s_to_f( + result_type_id: Word, + id: Word, + signed_value: Word, +) -> Instruction { + instruction_unary(Op::ConvertSToF, result_type_id, id, signed_value) +} + +pub(super) fn instruction_convert_u_to_f( + result_type_id: Word, + id: Word, + unsigned_value: Word, +) -> Instruction { + instruction_unary(Op::ConvertUToF, result_type_id, id, unsigned_value) +} + +pub(super) fn instruction_bit_cast(result_type_id: Word, id: Word, operand: Word) -> Instruction { + instruction_unary(Op::Bitcast, result_type_id, id, operand) +} // // Composite Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 7821d2b4e..92b600b68 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1033,6 +1033,79 @@ impl Writer { } _ => unimplemented!("{:?}", origin), }, + crate::Expression::As { + expr, + kind, + convert, + } => { + if !convert { + return None; + } + + let (expr_id, expr_type) = self + .write_expression( + ir_module, + ir_function, + &ir_function.expressions[*expr], + block, + function, + ) + .unwrap(); + + let id = self.generate_id(); + let instruction = match ir_module.types[expr_type.unwrap()].inner { + crate::TypeInner::Scalar { + kind: expr_kind, + width, + } => { + let kind_type_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Scalar { kind: *kind, width }), + ); + + if *convert { + super::instructions::instruction_bit_cast(kind_type_id, id, expr_id) + } else { + match (expr_kind, kind) { + (crate::ScalarKind::Float, crate::ScalarKind::Uint) => { + super::instructions::instruction_convert_f_to_u( + kind_type_id, + id, + expr_id, + ) + } + (crate::ScalarKind::Float, crate::ScalarKind::Sint) => { + super::instructions::instruction_convert_f_to_s( + kind_type_id, + id, + expr_id, + ) + } + (crate::ScalarKind::Sint, crate::ScalarKind::Float) => { + super::instructions::instruction_convert_s_to_f( + kind_type_id, + id, + expr_id, + ) + } + (crate::ScalarKind::Uint, crate::ScalarKind::Float) => { + super::instructions::instruction_convert_u_to_f( + kind_type_id, + id, + expr_id, + ) + } + _ => unreachable!(), + } + } + } + _ => unreachable!(), + }; + + block.body.push(instruction); + + Some((id, None)) + } _ => unimplemented!("{:?}", expression), } } From 99f829b3ccb82fe3d225338814042d8a54a1c8f0 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sun, 4 Oct 2020 15:03:11 +0200 Subject: [PATCH 0234/2212] [spv-out] Add check for global variables if name is set --- src/back/spv/writer.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 92b600b68..9404951d1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -670,10 +670,10 @@ impl Writer { let instruction = super::instructions::instruction_variable(pointer_id, id, class, None); if self.writer_flags.contains(WriterFlags::DEBUG) { - self.debugs.push(super::instructions::instruction_name( - id, - global_variable.name.as_ref().unwrap().as_str(), - )); + if let Some(ref name) = global_variable.name { + self.debugs + .push(super::instructions::instruction_name(id, name.as_str())); + } } if let Some(interpolation) = global_variable.interpolation { From 34e46d0a763433c86169de3e288cfdbfca986668 Mon Sep 17 00:00:00 2001 From: Capucho Date: Mon, 5 Oct 2020 21:02:00 +0100 Subject: [PATCH 0235/2212] Added support for matrix access on the typifier --- src/proc/typifier.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 8c67df2c3..721c92bef 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -98,6 +98,12 @@ impl Typifier { kind, width, } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), + crate::TypeInner::Matrix { + rows: size, + columns: _, + kind, + width, + } => Resolution::Value(crate::TypeInner::Vector { size, kind, width }), ref other => panic!("Can't access into {:?}", other), }, crate::Expression::AccessIndex { base, index } => match *self.get(base, types) { From 773408663b7c94431fdbd53f9021808ac8c7fc89 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 6 Oct 2020 16:31:41 +0200 Subject: [PATCH 0236/2212] [glsl-in] make consume_token a lexer method (#227) * [glsl-in] make consume_token a lexer method * [glsl-in] fix lex for 1.41 --- src/front/glsl/lex.rs | 521 ++++++++++++++++----------------- src/front/glsl/lex_tests.rs | 8 +- src/front/glsl/parser.rs | 2 +- src/front/glsl/parser_tests.rs | 2 +- 4 files changed, 263 insertions(+), 270 deletions(-) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index f0b9e6b95..57e2149f9 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -16,268 +16,6 @@ fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str, usize) (o, i, pos) } -pub fn consume_token(mut input: &str, start_of_line: bool) -> (Option, &str) { - let start = input - .find(|c: char| !c.is_whitespace()) - .unwrap_or_else(|| input.chars().count()); - input = &input[start..]; - - let mut chars = input.chars(); - let cur = match chars.next() { - Some(c) => c, - None => return (None, input), - }; - let mut meta = TokenMetadata { - line: 0, - chars: start..start + 1, - }; - match cur { - ':' => (Some(Token::Colon(meta)), chars.as_str()), - ';' => (Some(Token::Semicolon(meta)), chars.as_str()), - ',' => (Some(Token::Comma(meta)), chars.as_str()), - '.' => (Some(Token::Dot(meta)), chars.as_str()), - - '(' => (Some(Token::LeftParen(meta)), chars.as_str()), - ')' => (Some(Token::RightParen(meta)), chars.as_str()), - '{' => (Some(Token::LeftBrace(meta)), chars.as_str()), - '}' => (Some(Token::RightBrace(meta)), chars.as_str()), - '[' => (Some(Token::LeftBracket(meta)), chars.as_str()), - ']' => (Some(Token::RightBracket(meta)), chars.as_str()), - '<' | '>' => { - input = chars.as_str(); - let n1 = chars.next(); - let input1 = chars.as_str(); - let n2 = chars.next(); - match (cur, n1, n2) { - ('<', Some('<'), Some('=')) => { - meta.chars.end = start + 3; - (Some(Token::LeftAssign(meta)), chars.as_str()) - } - ('>', Some('>'), Some('=')) => { - meta.chars.end = start + 3; - (Some(Token::RightAssign(meta)), chars.as_str()) - } - ('<', Some('<'), _) => { - meta.chars.end = start + 2; - (Some(Token::LeftOp(meta)), input1) - } - ('>', Some('>'), _) => { - meta.chars.end = start + 2; - (Some(Token::RightOp(meta)), input1) - } - ('<', Some('='), _) => { - meta.chars.end = start + 2; - (Some(Token::LeOp(meta)), input1) - } - ('>', Some('='), _) => { - meta.chars.end = start + 2; - (Some(Token::GeOp(meta)), input1) - } - ('<', _, _) => (Some(Token::LeftAngle(meta)), input), - ('>', _, _) => (Some(Token::RightAngle(meta)), input), - _ => (None, input), - } - } - '0'..='9' => { - let (number, rest, pos) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); - if number.find('.').is_some() { - if ( - chars.next().map(|c| c.to_lowercase().next().unwrap()), - chars.next().map(|c| c.to_lowercase().next().unwrap()), - ) == (Some('l'), Some('f')) - { - meta.chars.end = start + pos + 2; - ( - Some(Token::DoubleConstant((meta, number.parse().unwrap()))), - chars.as_str(), - ) - } else { - meta.chars.end = start + pos; - ( - Some(Token::FloatConstant((meta, number.parse().unwrap()))), - chars.as_str(), - ) - } - } else { - meta.chars.end = start + pos; - ( - Some(Token::IntConstant((meta, number.parse().unwrap()))), - rest, - ) - } - } - 'a'..='z' | 'A'..='Z' | '_' => { - let (word, rest, pos) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); - meta.chars.end = start + pos; - match word { - "layout" => (Some(Token::Layout(meta)), rest), - "in" => (Some(Token::In(meta)), rest), - "out" => (Some(Token::Out(meta)), rest), - "uniform" => (Some(Token::Uniform(meta)), rest), - "flat" => ( - Some(Token::Interpolation((meta, crate::Interpolation::Flat))), - rest, - ), - "noperspective" => ( - Some(Token::Interpolation((meta, crate::Interpolation::Linear))), - rest, - ), - "smooth" => ( - Some(Token::Interpolation(( - meta, - crate::Interpolation::Perspective, - ))), - rest, - ), - "centroid" => ( - Some(Token::Interpolation((meta, crate::Interpolation::Centroid))), - rest, - ), - "sample" => ( - Some(Token::Interpolation((meta, crate::Interpolation::Sample))), - rest, - ), - // values - "true" => (Some(Token::BoolConstant((meta, true))), rest), - "false" => (Some(Token::BoolConstant((meta, false))), rest), - // jump statements - "continue" => (Some(Token::Continue(meta)), rest), - "break" => (Some(Token::Break(meta)), rest), - "return" => (Some(Token::Return(meta)), rest), - "discard" => (Some(Token::Discard(meta)), rest), - // types - "void" => (Some(Token::Void(meta)), rest), - word => { - let token = match parse_type(word) { - Some(t) => Token::TypeName((meta, t)), - None => Token::Identifier((meta, String::from(word))), - }; - (Some(token), rest) - } - } - } - - '+' | '-' | '&' | '|' | '^' => { - input = chars.as_str(); - let next = chars.next(); - if next == Some(cur) { - meta.chars.end = start + 2; - match cur { - '+' => (Some(Token::IncOp(meta)), chars.as_str()), - '-' => (Some(Token::DecOp(meta)), chars.as_str()), - '&' => (Some(Token::AndOp(meta)), chars.as_str()), - '|' => (Some(Token::OrOp(meta)), chars.as_str()), - '^' => (Some(Token::XorOp(meta)), chars.as_str()), - _ => (None, input), - } - } else { - match next { - Some('=') => { - meta.chars.end = start + 2; - match cur { - '+' => (Some(Token::AddAssign(meta)), chars.as_str()), - '-' => (Some(Token::SubAssign(meta)), chars.as_str()), - '&' => (Some(Token::AndAssign(meta)), chars.as_str()), - '|' => (Some(Token::OrAssign(meta)), chars.as_str()), - '^' => (Some(Token::XorAssign(meta)), chars.as_str()), - _ => (None, input), - } - } - _ => match cur { - '+' => (Some(Token::Plus(meta)), input), - '-' => (Some(Token::Dash(meta)), input), - '&' => (Some(Token::Ampersand(meta)), input), - '|' => (Some(Token::VerticalBar(meta)), input), - '^' => (Some(Token::Caret(meta)), input), - _ => (None, input), - }, - } - } - } - - '%' | '!' | '=' => { - input = chars.as_str(); - match chars.next() { - Some('=') => { - meta.chars.end = start + 2; - match cur { - '%' => (Some(Token::ModAssign(meta)), chars.as_str()), - '!' => (Some(Token::NeOp(meta)), chars.as_str()), - '=' => (Some(Token::EqOp(meta)), chars.as_str()), - _ => (None, input), - } - } - _ => match cur { - '%' => (Some(Token::Percent(meta)), input), - '!' => (Some(Token::Bang(meta)), input), - '=' => (Some(Token::Equal(meta)), input), - _ => (None, input), - }, - } - } - - '*' => { - input = chars.as_str(); - match chars.next() { - Some('=') => { - meta.chars.end = start + 2; - (Some(Token::MulAssign(meta)), chars.as_str()) - } - Some('/') => { - meta.chars.end = start + 2; - (Some(Token::CommentEnd((meta, ()))), chars.as_str()) - } - _ => (Some(Token::Star(meta)), input), - } - } - '/' => { - input = chars.as_str(); - match chars.next() { - Some('=') => { - meta.chars.end = start + 2; - (Some(Token::DivAssign(meta)), chars.as_str()) - } - Some('/') => (None, ""), - Some('*') => { - meta.chars.end = start + 2; - (Some(Token::CommentStart((meta, ()))), chars.as_str()) - } - _ => (Some(Token::Slash(meta)), input), - } - } - '#' => { - if start_of_line { - input = chars.as_str(); - - // skip whitespace - let word_start = input - .find(|c: char| !c.is_whitespace()) - .unwrap_or_else(|| input.chars().count()); - input = &input[word_start..]; - - let (word, rest, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); - meta.chars.end = start + word_start + 1 + pos; - match word { - "version" => (Some(Token::Version(meta)), rest), - _ => (None, input), - } - - //TODO: preprocessor - // if chars.next() == Some(cur) { - // (Token::TokenPasting, chars.as_str(), start, start + 2) - // } else { - // (Token::Preprocessor, input, start, start + 1) - // } - } else { - (Some(Token::Unknown((meta, '#'))), chars.as_str()) - } - } - '~' => (Some(Token::Tilde(meta)), chars.as_str()), - '?' => (Some(Token::Question(meta)), chars.as_str()), - ch => (Some(Token::Unknown((meta, ch))), chars.as_str()), - } -} - #[derive(Clone, Debug)] pub struct Lexer<'a> { lines: Enumerate>, @@ -288,6 +26,262 @@ pub struct Lexer<'a> { } impl<'a> Lexer<'a> { + pub fn consume_token(&mut self) -> Option { + let start = self + .input + .find(|c: char| !c.is_whitespace()) + .unwrap_or_else(|| self.input.chars().count()); + let input = &self.input[start..]; + + let mut chars = input.chars(); + let cur = match chars.next() { + Some(c) => c, + None => { + self.input = self.input[start..].into(); + return None; + } + }; + let mut meta = TokenMetadata { + line: 0, + chars: start..start + 1, + }; + let mut consume_all = false; + let token = match cur { + ':' => Some(Token::Colon(meta)), + ';' => Some(Token::Semicolon(meta)), + ',' => Some(Token::Comma(meta)), + '.' => Some(Token::Dot(meta)), + + '(' => Some(Token::LeftParen(meta)), + ')' => Some(Token::RightParen(meta)), + '{' => Some(Token::LeftBrace(meta)), + '}' => Some(Token::RightBrace(meta)), + '[' => Some(Token::LeftBracket(meta)), + ']' => Some(Token::RightBracket(meta)), + '<' | '>' => { + let n1 = chars.next(); + let n2 = chars.next(); + match (cur, n1, n2) { + ('<', Some('<'), Some('=')) => { + meta.chars.end = start + 3; + Some(Token::LeftAssign(meta)) + } + ('>', Some('>'), Some('=')) => { + meta.chars.end = start + 3; + Some(Token::RightAssign(meta)) + } + ('<', Some('<'), _) => { + meta.chars.end = start + 2; + Some(Token::LeftOp(meta)) + } + ('>', Some('>'), _) => { + meta.chars.end = start + 2; + Some(Token::RightOp(meta)) + } + ('<', Some('='), _) => { + meta.chars.end = start + 2; + Some(Token::LeOp(meta)) + } + ('>', Some('='), _) => { + meta.chars.end = start + 2; + Some(Token::GeOp(meta)) + } + ('<', _, _) => Some(Token::LeftAngle(meta)), + ('>', _, _) => Some(Token::RightAngle(meta)), + _ => None, + } + } + '0'..='9' => { + let (number, _, pos) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); + if number.find('.').is_some() { + if ( + chars.next().map(|c| c.to_lowercase().next().unwrap()), + chars.next().map(|c| c.to_lowercase().next().unwrap()), + ) == (Some('l'), Some('f')) + { + meta.chars.end = start + pos + 2; + Some(Token::DoubleConstant((meta, number.parse().unwrap()))) + } else { + meta.chars.end = start + pos; + + Some(Token::FloatConstant((meta, number.parse().unwrap()))) + } + } else { + meta.chars.end = start + pos; + Some(Token::IntConstant((meta, number.parse().unwrap()))) + } + } + 'a'..='z' | 'A'..='Z' | '_' => { + let (word, _, pos) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); + meta.chars.end = start + pos; + match word { + "layout" => Some(Token::Layout(meta)), + "in" => Some(Token::In(meta)), + "out" => Some(Token::Out(meta)), + "uniform" => Some(Token::Uniform(meta)), + "flat" => Some(Token::Interpolation((meta, crate::Interpolation::Flat))), + "noperspective" => { + Some(Token::Interpolation((meta, crate::Interpolation::Linear))) + } + "smooth" => Some(Token::Interpolation(( + meta, + crate::Interpolation::Perspective, + ))), + "centroid" => { + Some(Token::Interpolation((meta, crate::Interpolation::Centroid))) + } + "sample" => Some(Token::Interpolation((meta, crate::Interpolation::Sample))), + // values + "true" => Some(Token::BoolConstant((meta, true))), + "false" => Some(Token::BoolConstant((meta, false))), + // jump statements + "continue" => Some(Token::Continue(meta)), + "break" => Some(Token::Break(meta)), + "return" => Some(Token::Return(meta)), + "discard" => Some(Token::Discard(meta)), + // types + "void" => Some(Token::Void(meta)), + word => { + let token = match parse_type(word) { + Some(t) => Token::TypeName((meta, t)), + None => Token::Identifier((meta, String::from(word))), + }; + Some(token) + } + } + } + '+' | '-' | '&' | '|' | '^' => { + let next = chars.next(); + if next == Some(cur) { + meta.chars.end = start + 2; + match cur { + '+' => Some(Token::IncOp(meta)), + '-' => Some(Token::DecOp(meta)), + '&' => Some(Token::AndOp(meta)), + '|' => Some(Token::OrOp(meta)), + '^' => Some(Token::XorOp(meta)), + _ => None, + } + } else { + match next { + Some('=') => { + meta.chars.end = start + 2; + match cur { + '+' => Some(Token::AddAssign(meta)), + '-' => Some(Token::SubAssign(meta)), + '&' => Some(Token::AndAssign(meta)), + '|' => Some(Token::OrAssign(meta)), + '^' => Some(Token::XorAssign(meta)), + _ => None, + } + } + _ => match cur { + '+' => Some(Token::Plus(meta)), + '-' => Some(Token::Dash(meta)), + '&' => Some(Token::Ampersand(meta)), + '|' => Some(Token::VerticalBar(meta)), + '^' => Some(Token::Caret(meta)), + _ => None, + }, + } + } + } + + '%' | '!' | '=' => match chars.next() { + Some('=') => { + meta.chars.end = start + 2; + match cur { + '%' => Some(Token::ModAssign(meta)), + '!' => Some(Token::NeOp(meta)), + '=' => Some(Token::EqOp(meta)), + _ => None, + } + } + _ => match cur { + '%' => Some(Token::Percent(meta)), + '!' => Some(Token::Bang(meta)), + '=' => Some(Token::Equal(meta)), + _ => None, + }, + }, + + '*' => match chars.next() { + Some('=') => { + meta.chars.end = start + 2; + Some(Token::MulAssign(meta)) + } + Some('/') => { + meta.chars.end = start + 2; + Some(Token::CommentEnd((meta, ()))) + } + _ => Some(Token::Star(meta)), + }, + '/' => { + match chars.next() { + Some('=') => { + meta.chars.end = start + 2; + Some(Token::DivAssign(meta)) + } + Some('/') => { + // consume rest of line + consume_all = true; + None + } + Some('*') => { + meta.chars.end = start + 2; + Some(Token::CommentStart((meta, ()))) + } + _ => Some(Token::Slash(meta)), + } + } + '#' => { + if self.offset == 0 { + let mut input = chars.as_str(); + + // skip whitespace + let word_start = input + .find(|c: char| !c.is_whitespace()) + .unwrap_or_else(|| input.chars().count()); + input = &input[word_start..]; + + let (word, _, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); + meta.chars.end = start + word_start + 1 + pos; + match word { + "version" => Some(Token::Version(meta)), + w => Some(Token::Unknown((meta, w.into()))), + } + + //TODO: preprocessor + // if chars.next() == Some(cur) { + // (Token::TokenPasting, chars.as_str(), start, start + 2) + // } else { + // (Token::Preprocessor, input, start, start + 1) + // } + } else { + Some(Token::Unknown((meta, '#'.to_string()))) + } + } + '~' => Some(Token::Tilde(meta)), + '?' => Some(Token::Question(meta)), + ch => Some(Token::Unknown((meta, ch.to_string()))), + }; + if let Some(token) = token { + let skip_bytes = input + .chars() + .take(token.extra().chars.end - start) + .fold(0, |acc, c| acc + c.len_utf8()); + self.input = input[skip_bytes..].into(); + Some(token) + } else { + if consume_all { + self.input = "".into(); + } else { + self.input = self.input[start..].into(); + } + None + } + } + pub fn new(input: &'a str) -> Self { let mut lines = input.lines().enumerate(); let (line, input) = lines.next().unwrap_or((0, "")); @@ -313,10 +307,9 @@ impl<'a> Lexer<'a> { #[must_use] pub fn next(&mut self) -> Option { - let (token, rest) = consume_token(&self.input, self.offset == 0); + let token = self.consume_token(); if let Some(mut token) = token { - self.input = String::from(rest); let meta = token.extra_mut(); let end = meta.chars.end; meta.line = self.line; diff --git a/src/front/glsl/lex_tests.rs b/src/front/glsl/lex_tests.rs index 584baf302..fde7fc979 100644 --- a/src/front/glsl/lex_tests.rs +++ b/src/front/glsl/lex_tests.rs @@ -111,7 +111,7 @@ fn tokens() { line: 0, chars: 14..15 }, - 'æ' + 'æ'.to_string() )) ); assert_eq!( @@ -131,7 +131,7 @@ fn tokens() { line: 0, chars: 17..18 }, - 'ø' + 'ø'.to_string() )) ); assert_eq!( @@ -151,7 +151,7 @@ fn tokens() { line: 0, chars: 21..22 }, - '¾' + '¾'.to_string() )) ); assert_eq!( @@ -171,7 +171,7 @@ fn tokens() { line: 0, chars: 25..26 }, - '好' + '好'.to_string() )) ); assert_eq!(lex.next(), None); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index d5da8f385..3c8aaa180 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -28,7 +28,7 @@ pomelo! { ErrorKind::ParserStackOverflow } - %type Unknown char; + %type Unknown String; %type CommentStart (); %type CommentEnd (); diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 77cdac557..77b30eff0 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -56,7 +56,7 @@ fn version() { .err() .unwrap() ), - "InvalidToken(Unknown((TokenMetadata { line: 1, chars: 11..12 }, \'#\')))" + "InvalidToken(Unknown((TokenMetadata { line: 1, chars: 11..12 }, \"#\")))" ); // valid versions From f67dfd251a07f7b25ae591877542d04bbcad2fe9 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Tue, 6 Oct 2020 22:57:30 +0200 Subject: [PATCH 0237/2212] [spv-out] Add multiply instructions (#219) --- src/back/spv/instructions.rs | 84 ++++++++++++++++++ src/back/spv/writer.rs | 164 ++++++++++++++++++++++++++--------- 2 files changed, 205 insertions(+), 43 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 39a9c4e73..077522e91 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -520,6 +520,34 @@ pub(super) fn instruction_composite_construct( // Arithmetic Instructions // +pub(super) fn instruction_i_mul( + result_type_id: Word, + id: Word, + operand_1: Word, + operand_2: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::IMul); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(operand_1); + instruction.add_operand(operand_2); + instruction +} + +pub(super) fn instruction_f_mul( + result_type_id: Word, + id: Word, + operand_1: Word, + operand_2: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::FMul); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(operand_1); + instruction.add_operand(operand_2); + instruction +} + pub(super) fn instruction_vector_times_scalar( result_type_id: Word, id: Word, @@ -534,6 +562,62 @@ pub(super) fn instruction_vector_times_scalar( instruction } +pub(super) fn instruction_matrix_times_scalar( + result_type_id: Word, + id: Word, + matrix_id: Word, + scalar_id: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::MatrixTimesScalar); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(matrix_id); + instruction.add_operand(scalar_id); + instruction +} + +pub(super) fn instruction_vector_times_matrix( + result_type_id: Word, + id: Word, + vector_id: Word, + matrix_id: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::VectorTimesMatrix); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(vector_id); + instruction.add_operand(matrix_id); + instruction +} + +pub(super) fn instruction_matrix_times_vector( + result_type_id: Word, + id: Word, + matrix_id: Word, + vector_id: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::MatrixTimesVector); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(matrix_id); + instruction.add_operand(vector_id); + instruction +} + +pub(super) fn instruction_matrix_times_matrix( + result_type_id: Word, + id: Word, + left_matrix: Word, + right_matrix: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::MatrixTimesMatrix); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(left_matrix); + instruction.add_operand(right_matrix); + instruction +} + // // Bit Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 9404951d1..174b01764 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -875,7 +875,6 @@ impl Writer { crate::Expression::Binary { op, left, right } => { match op { crate::BinaryOperator::Multiply => { - // TODO OpVectorTimesScalar is only supported let id = self.generate_id(); let left_expression = &ir_function.expressions[*left]; let right_expression = &ir_function.expressions[*right]; @@ -898,53 +897,129 @@ impl Writer { ) .unwrap(); - let left_ty_inner = &ir_module.types[left_ty.unwrap()].inner; - let right_ty_inner = &ir_module.types[right_ty.unwrap()].inner; + let left_ty = left_ty.unwrap(); + let right_ty = right_ty.unwrap(); - let (result_type_id, vector_id, scalar_id) = - match (left_ty_inner, right_ty_inner) { - ( - crate::TypeInner::Vector { .. }, - crate::TypeInner::Scalar { .. }, - ) => ( - self.get_type_id( - &ir_module.types, - LookupType::Handle(left_ty.unwrap()), - ), + let left_ty_inner = &ir_module.types[left_ty].inner; + let right_ty_inner = &ir_module.types[right_ty].inner; + + let left_result_type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(left_ty)); + + let right_result_type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(right_ty)); + + let left_id = match *left_expression { + crate::Expression::LocalVariable(_) + | crate::Expression::GlobalVariable(_) => { + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + left_result_type_id, + load_id, left_id, + None, + )); + load_id + } + _ => left_id, + }; + + let right_id = match *right_expression { + crate::Expression::LocalVariable(..) + | crate::Expression::GlobalVariable(..) => { + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + right_result_type_id, + load_id, right_id, - ), - ( - crate::TypeInner::Scalar { .. }, - crate::TypeInner::Vector { .. }, - ) => ( - self.get_type_id( - &ir_module.types, - LookupType::Handle(right_ty.unwrap()), + None, + )); + load_id + } + _ => right_id, + }; + + let (instruction, ty) = match left_ty_inner { + crate::TypeInner::Vector { .. } => match right_ty_inner { + crate::TypeInner::Scalar { .. } => ( + super::instructions::instruction_vector_times_scalar( + left_result_type_id, + id, + left_id, + right_id, ), - right_id, - left_id, + left_ty, ), - _ => unreachable!("Expression requires both a scalar and vector"), - }; + crate::TypeInner::Matrix { .. } => ( + super::instructions::instruction_vector_times_matrix( + left_result_type_id, + id, + left_id, + right_id, + ), + left_ty, + ), + _ => unreachable!(), + }, + crate::TypeInner::Matrix { .. } => match right_ty_inner { + crate::TypeInner::Scalar { .. } => ( + super::instructions::instruction_matrix_times_scalar( + left_result_type_id, + id, + left_id, + right_id, + ), + left_ty, + ), + crate::TypeInner::Vector { .. } => ( + super::instructions::instruction_matrix_times_vector( + right_result_type_id, + id, + left_id, + right_id, + ), + right_ty, + ), + crate::TypeInner::Matrix { .. } => ( + super::instructions::instruction_matrix_times_matrix( + left_result_type_id, + id, + left_id, + right_id, + ), + left_ty, + ), + _ => unreachable!(), + }, + crate::TypeInner::Scalar { kind, .. } => { + // Always assuming left and hand side are equal scalar types. + match kind { + crate::ScalarKind::Float => ( + super::instructions::instruction_f_mul( + left_result_type_id, + id, + left_id, + right_id, + ), + left_ty, + ), + crate::ScalarKind::Sint | crate::ScalarKind::Uint => ( + super::instructions::instruction_i_mul( + left_result_type_id, + id, + left_id, + right_id, + ), + left_ty, + ), + _ => unreachable!(), + } + } + _ => unreachable!(), + }; - let load_id = self.generate_id(); - let load_instruction = super::instructions::instruction_load( - result_type_id, - load_id, - vector_id, - None, - ); - block.body.push(load_instruction); - - let instruction = super::instructions::instruction_vector_times_scalar( - result_type_id, - id, - load_id, - scalar_id, - ); block.body.push(instruction); - Some((id, None)) + Some((id, Some(ty))) } _ => unimplemented!("{:?}", op), @@ -1144,7 +1219,8 @@ impl Writer { .unwrap(); let id = match *expression { - crate::Expression::LocalVariable(_) => { + crate::Expression::LocalVariable(_) + | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); let value_ty_id = self.get_type_id( &ir_module.types, @@ -1158,6 +1234,7 @@ impl Writer { )); load_id } + _ => id, }; super::instructions::instruction_return_value(id) @@ -1188,7 +1265,8 @@ impl Writer { .unwrap(); let value_id = match value_expression { - crate::Expression::LocalVariable(_) => { + crate::Expression::LocalVariable(_) + | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); let value_ty_id = self.get_type_id( &ir_module.types, From 4420258001e5be7820c6eee7e0ee6394624aaa52 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Tue, 6 Oct 2020 23:19:29 +0200 Subject: [PATCH 0238/2212] [ir] Remove Matrix Kind from the IR (#230) --- src/back/glsl.rs | 12 +++-------- src/back/msl.rs | 9 ++------ src/back/spv/test_framework.rs | 5 ++++- src/back/spv/writer.rs | 6 ++---- src/front/glsl/types.rs | 3 +-- src/front/spv/mod.rs | 3 +-- src/front/wgsl/mod.rs | 39 +++++++++++++++------------------- src/lib.rs | 3 +-- src/proc/typifier.rs | 17 ++++++--------- src/proc/validator.rs | 16 +++++++++----- 10 files changed, 49 insertions(+), 64 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 23187ffae..3884282a5 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -940,11 +940,10 @@ fn write_expression<'a, 'b>( TypeInner::Matrix { columns, rows, - kind, width, } => format!( "{}mat{}x{}", - map_scalar(kind, width, builder.manager)?.prefix, + map_scalar(crate::ScalarKind::Float, width, builder.manager)?.prefix, columns as u8, rows as u8, ), @@ -1405,20 +1404,15 @@ fn write_type<'a>( TypeInner::Matrix { columns, rows, - kind, width, } => { - if kind != ScalarKind::Float { - return Err(Error::Custom(String::from( - "Non float matrices aren't allowed", - ))); - } else if width == 8 { + if width == 8 { manager.request(Features::DOUBLE_TYPE); } Cow::Owned(format!( "{}mat{}x{}", - map_scalar(kind, width, manager)?.prefix, + map_scalar(crate::ScalarKind::Float, width, manager)?.prefix, columns as u8, rows as u8 )) diff --git a/src/back/msl.rs b/src/back/msl.rs index 78e091f87..dd5bb0f44 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -814,16 +814,11 @@ impl Writer { name )?; } - crate::TypeInner::Matrix { - columns, - rows, - kind, - .. - } => { + crate::TypeInner::Matrix { columns, rows, .. } => { write!( self.out, "typedef {}{}x{} {}", - scalar_kind_string(kind), + scalar_kind_string(crate::ScalarKind::Float), vector_size_string(columns), vector_size_string(rows), name diff --git a/src/back/spv/test_framework.rs b/src/back/spv/test_framework.rs index a21aeb0f0..be2fa74fe 100644 --- a/src/back/spv/test_framework.rs +++ b/src/back/spv/test_framework.rs @@ -1,4 +1,7 @@ -pub(super) fn validate_instruction(words: &[spirv::Word], instruction: &crate::back::spv::Instruction) { +pub(super) fn validate_instruction( + words: &[spirv::Word], + instruction: &crate::back::spv::Instruction, +) { let mut inst_index = 0; let (wc, op) = ((words[inst_index] >> 16) as u16, words[inst_index] as u16); inst_index += 1; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 174b01764..c164a03ca 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -465,14 +465,13 @@ impl Writer { crate::TypeInner::Matrix { columns, rows: _, - kind, width, } => { let vector_id = self.get_type_id( arena, LookupType::Local(LocalType::Vector { size: columns, - kind, + kind: crate::ScalarKind::Float, width, }), ); @@ -836,14 +835,13 @@ impl Writer { crate::TypeInner::Matrix { rows, columns, - kind, width, } => { let vector_type_id = self.get_type_id( &ir_module.types, LookupType::Local(LocalType::Vector { width, - kind, + kind: crate::ScalarKind::Float, size: columns, }), ); diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 25845ef46..dceb230b8 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -77,7 +77,7 @@ pub fn parse_type(type_name: &str) -> Option { let kind = iter.next()?; let size = iter.next()?; - let (kind, width) = kind_width_parse(kind)?; + let (_, width) = kind_width_parse(kind)?; let (columns, rows) = if let Some(size) = size_parse(size) { (size, size) @@ -94,7 +94,6 @@ pub fn parse_type(type_name: &str) -> Option { inner: TypeInner::Matrix { columns, rows, - kind, width, }, }) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3b42f1092..c7458c1ec 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1846,10 +1846,9 @@ impl> Parser { let num_columns = self.next()?; let vector_type_lookup = self.lookup_type.lookup(vector_type_id)?; let inner = match module.types[vector_type_lookup.handle].inner { - crate::TypeInner::Vector { size, kind, width } => crate::TypeInner::Matrix { + crate::TypeInner::Vector { size, width, .. } => crate::TypeInner::Matrix { columns: map_vector_size(num_columns)?, rows: size, - kind, width, }, _ => return Err(Error::InvalidInnerType(vector_type_id)), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7a4fc2b36..3d7b4826b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -298,11 +298,17 @@ impl Parser { index: usize, ) -> Result, Error<'static>> { match type_arena[ty].inner { - crate::TypeInner::Vector { kind, width, .. } - | crate::TypeInner::Matrix { kind, width, .. } => { + crate::TypeInner::Vector { kind, width, .. } => { let inner = crate::TypeInner::Scalar { kind, width }; Ok(type_arena.fetch_or_append(crate::Type { name: None, inner })) } + crate::TypeInner::Matrix { width, .. } => { + let inner = crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width, + }; + Ok(type_arena.fetch_or_append(crate::Type { name: None, inner })) + } crate::TypeInner::Array { base, .. } => Ok(base), crate::TypeInner::Struct { ref members } => Ok(members[index].ty), _ => Err(Error::NotCompositeType(ty)), @@ -543,14 +549,12 @@ impl Parser { crate::TypeInner::Matrix { rows, columns, - kind, width, } => match Composition::make(handle, columns, name, ctx.expressions)? { Composition::Multi(columns, components) => { let inner = crate::TypeInner::Matrix { columns, rows, - kind, width, }; crate::Expression::Compose { @@ -1049,83 +1053,74 @@ impl Parser { } } Token::Word("mat2x2") => { - let (kind, width) = lexer.next_scalar_generic()?; + let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Bi, rows: crate::VectorSize::Bi, - kind, width, } } Token::Word("mat2x3") => { - let (kind, width) = lexer.next_scalar_generic()?; + let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Bi, rows: crate::VectorSize::Tri, - kind, width, } } Token::Word("mat2x4") => { - let (kind, width) = lexer.next_scalar_generic()?; + let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Bi, rows: crate::VectorSize::Quad, - kind, width, } } Token::Word("mat3x2") => { - let (kind, width) = lexer.next_scalar_generic()?; + let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Tri, rows: crate::VectorSize::Bi, - kind, width, } } Token::Word("mat3x3") => { - let (kind, width) = lexer.next_scalar_generic()?; + let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Tri, rows: crate::VectorSize::Tri, - kind, width, } } Token::Word("mat3x4") => { - let (kind, width) = lexer.next_scalar_generic()?; + let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Tri, rows: crate::VectorSize::Quad, - kind, width, } } Token::Word("mat4x2") => { - let (kind, width) = lexer.next_scalar_generic()?; + let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Quad, rows: crate::VectorSize::Bi, - kind, width, } } Token::Word("mat4x3") => { - let (kind, width) = lexer.next_scalar_generic()?; + let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Quad, rows: crate::VectorSize::Tri, - kind, width, } } Token::Word("mat4x4") => { - let (kind, width) = lexer.next_scalar_generic()?; + let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Quad, rows: crate::VectorSize::Quad, - kind, width, } } diff --git a/src/lib.rs b/src/lib.rs index a05391cb3..2354c8c5f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -351,11 +351,10 @@ pub enum TypeInner { kind: ScalarKind, width: Bytes, }, - /// Matrix of numbers. + /// Matrix of floats. Matrix { columns: VectorSize, rows: VectorSize, - kind: ScalarKind, width: Bytes, }, /// Pointer to a value. diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 721c92bef..64b59203b 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -23,12 +23,10 @@ impl Clone for Resolution { crate::TypeInner::Matrix { rows, columns, - kind, width, } => crate::TypeInner::Matrix { rows, columns, - kind, width, }, _ => panic!("Unepxected clone type: {:?}", v), @@ -101,9 +99,12 @@ impl Typifier { crate::TypeInner::Matrix { rows: size, columns: _, - kind, width, - } => Resolution::Value(crate::TypeInner::Vector { size, kind, width }), + } => Resolution::Value(crate::TypeInner::Vector { + size, + kind: crate::ScalarKind::Float, + width, + }), ref other => panic!("Can't access into {:?}", other), }, crate::Expression::AccessIndex { base, index } => match *self.get(base, types) { @@ -116,7 +117,6 @@ impl Typifier { crate::TypeInner::Matrix { columns, rows, - kind, width, } => { if index >= columns as u32 { @@ -124,7 +124,7 @@ impl Typifier { } Resolution::Value(crate::TypeInner::Vector { size: rows, - kind, + kind: crate::ScalarKind::Float, width, }) } @@ -186,11 +186,10 @@ impl Typifier { crate::TypeInner::Matrix { columns, rows: _, - kind, width, } => Resolution::Value(crate::TypeInner::Vector { size: columns, - kind, + kind: crate::ScalarKind::Float, width, }), _ => panic!("Incompatible arguments {:?} x {:?}", ty_left, ty_right), @@ -219,12 +218,10 @@ impl Typifier { crate::TypeInner::Matrix { columns, rows, - kind, width, } => Resolution::Value(crate::TypeInner::Matrix { columns: rows, rows: columns, - kind, width, }), ref other => panic!("incompatible transpose of {:?}", other), diff --git a/src/proc/validator.rs b/src/proc/validator.rs index a730db74b..450df01e2 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -228,14 +228,14 @@ impl Validator { | (crate::ShaderStage::Fragment, crate::StorageClass::Input) => { match module.types[var.ty].inner { crate::TypeInner::Scalar { kind, .. } - | crate::TypeInner::Vector { kind, .. } - | crate::TypeInner::Matrix { kind, .. } => { + | crate::TypeInner::Vector { kind, .. } => { if kind != crate::ScalarKind::Float && var.interpolation != Some(crate::Interpolation::Flat) { return Err(EntryPointError::InvalidIntegerInterpolation); } } + crate::TypeInner::Matrix { .. } => {} _ => unreachable!(), } } @@ -342,9 +342,7 @@ impl Validator { for (handle, ty) in module.types.iter() { use crate::TypeInner as Ti; match ty.inner { - Ti::Scalar { kind, width } - | Ti::Vector { kind, width, .. } - | Ti::Matrix { kind, width, .. } => { + Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { let expected = match kind { crate::ScalarKind::Bool => 1, _ => 4, @@ -353,6 +351,14 @@ impl Validator { return Err(ValidationError::InvalidTypeWidth(kind, width)); } } + Ti::Matrix { width, .. } => { + if width != 4 { + return Err(ValidationError::InvalidTypeWidth( + crate::ScalarKind::Float, + width, + )); + } + } Ti::Pointer { base, class: _ } => { if base >= handle { return Err(ValidationError::UnresolvedType(base)); From aa35110471ee7915e1f4e1de61ea41f2f32f92c4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 7 Oct 2020 16:08:00 -0400 Subject: [PATCH 0239/2212] Allow output variables to be read --- src/proc/validator.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 450df01e2..ffcf49492 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -289,7 +289,7 @@ impl Validator { return Err(EntryPointError::BindingCollision(var_handle)); } location_out_mask |= mask; - crate::GlobalUse::STORE + crate::GlobalUse::LOAD | crate::GlobalUse::STORE } crate::StorageClass::Constant => crate::GlobalUse::LOAD, crate::StorageClass::Uniform | crate::StorageClass::StorageBuffer => { From 2b268c926c6dff5e366226a9502c06725107489d Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 8 Oct 2020 19:14:05 +0200 Subject: [PATCH 0240/2212] [glsl-in] Extraxt lexer next_line method (#232) Have single place where advancing to next line --- src/front/glsl/lex.rs | 62 +++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 57e2149f9..a4f5e956f 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -283,25 +283,36 @@ impl<'a> Lexer<'a> { } pub fn new(input: &'a str) -> Self { - let mut lines = input.lines().enumerate(); - let (line, input) = lines.next().unwrap_or((0, "")); - let mut input = String::from(input); - - while input.ends_with('\\') { - if let Some((_, next)) = lines.next() { - input.pop(); - input.push_str(next); - } else { - break; - } - } - - Lexer { - lines, - input, - line, + let mut lexer = Lexer { + lines: input.lines().enumerate(), + input: "".to_string(), + line: 0, offset: 0, inside_comment: false, + }; + lexer.next_line(); + lexer + } + + fn next_line(&mut self) -> bool { + if let Some((line, input)) = self.lines.next() { + let mut input = String::from(input); + + while input.ends_with('\\') { + if let Some((_, next)) = self.lines.next() { + input.pop(); + input.push_str(next); + } else { + break; + } + } + + self.input = input; + self.line = line; + self.offset = 0; + true + } else { + false } } @@ -331,22 +342,9 @@ impl<'a> Lexer<'a> { self.next() } } else { - let (line, input) = self.lines.next()?; - - let mut input = String::from(input); - - while input.ends_with('\\') { - if let Some((_, next)) = self.lines.next() { - input.pop(); - input.push_str(next); - } else { - break; - } + if !self.next_line() { + return None; } - - self.input = input; - self.line = line; - self.offset = 0; self.next() } } From b76dff9d9ccb99b5e4f377f99d8b46017a181d26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 12 Oct 2020 16:49:53 +0100 Subject: [PATCH 0241/2212] Added the new method to the msl Writer (#236) --- src/back/msl.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/back/msl.rs b/src/back/msl.rs index dd5bb0f44..d7ff76069 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -370,6 +370,14 @@ fn separate(is_last: bool) -> &'static str { } impl Writer { + /// Creates a new `Writer` instance + pub fn new(out: W) -> Self { + Writer { + out, + typifier: Typifier::new(), + } + } + fn put_call( &mut self, name: &str, From 6fb195cdc85a13c45198b337c2b6b8ea2b67a9b6 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 13 Oct 2020 23:14:40 +0200 Subject: [PATCH 0242/2212] [clippy] Fix clippy issues after upgrading to 1.47 (#237) * [clippy] disable match_like_matches_macro for now * [wgsl-in] Return error instead of panic * [typifier] Convert panics to return error Still one panic in clone impl for Resolution, disabled clippy for that one * [spv-in] REturn error instead of panic'ing * [spv-out] Return error instead of panic'ing * [typifier] Use IncompatibleOperand(s) error Instead of just Other * [typifier] Use Expression for op in Error For IncompatibleOperands * [typifier] revert last commit --- src/back/spv/writer.rs | 52 +++++++++++++++++++-------------- src/front/spv/error.rs | 1 + src/front/spv/mod.rs | 4 ++- src/front/wgsl/mod.rs | 8 ++++- src/lib.rs | 6 +++- src/proc/typifier.rs | 66 +++++++++++++++++++++++++++++++++++++----- 6 files changed, 104 insertions(+), 33 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index c164a03ca..fa072a669 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2,9 +2,16 @@ use super::{Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; use spirv::Word; use std::collections::hash_map::Entry; +use thiserror::Error; const BITS_PER_BYTE: crate::Bytes = 8; +#[derive(Clone, Debug, Error)] +pub enum Error { + #[error("can't find local variable: {0:?}")] + UnknownLocalVariable(crate::LocalVariable), +} + struct Block { label: Option, body: Vec, @@ -118,6 +125,9 @@ pub struct Writer { lookup_global_variable: crate::FastHashMap, Word>, } +// type alias, for success return of write_expression +type WriteExpressionOutput = Option<(Word, Option>)>; + impl Writer { pub fn new(header: &crate::Header, writer_flags: WriterFlags) -> Self { Writer { @@ -799,7 +809,7 @@ impl Writer { expression: &crate::Expression, block: &mut Block, function: &mut Function, - ) -> Option<(Word, Option>)> { + ) -> Result { match expression { crate::Expression::GlobalVariable(handle) => { let var = &ir_module.global_variables[*handle]; @@ -808,12 +818,12 @@ impl Writer { &ir_module.global_variables, *handle, ); - Some((id, Some(var.ty))) + Ok(Some((id, Some(var.ty)))) } crate::Expression::Constant(handle) => { let var = &ir_module.constants[*handle]; let id = self.get_constant_id(*handle, ir_module); - Some((id, Some(var.ty))) + Ok(Some((id, Some(var.ty)))) } crate::Expression::Compose { ty, components } => { let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*ty)); @@ -822,7 +832,7 @@ impl Writer { for component in components { let expression = &ir_function.expressions[*component]; let (component_id, _) = self - .write_expression(ir_module, &ir_function, expression, block, function) + .write_expression(ir_module, &ir_function, expression, block, function)? .unwrap(); constituent_ids.push(component_id); } @@ -868,7 +878,7 @@ impl Writer { _ => unreachable!(), }; - Some((id, Some(*ty))) + Ok(Some((id, Some(*ty)))) } crate::Expression::Binary { op, left, right } => { match op { @@ -883,7 +893,7 @@ impl Writer { left_expression, block, function, - ) + )? .unwrap(); let (right_id, right_ty) = self .write_expression( @@ -892,7 +902,7 @@ impl Writer { right_expression, block, function, - ) + )? .unwrap(); let left_ty = left_ty.unwrap(); @@ -1017,7 +1027,7 @@ impl Writer { }; block.body.push(instruction); - Some((id, Some(ty))) + Ok(Some((id, Some(ty)))) } _ => unimplemented!("{:?}", op), @@ -1025,17 +1035,12 @@ impl Writer { } crate::Expression::LocalVariable(variable) => { let var = &ir_function.local_variables[*variable]; - let id = if let Some(local_var) = function + function .variables .iter() .find(|&v| v.name.as_ref().unwrap() == var.name.as_ref().unwrap()) - { - local_var.id - } else { - panic!("Could not find: {:?}", var) - }; - - Some((id, Some(var.ty))) + .map(|local_var| Some((local_var.id, Some(var.ty)))) + .ok_or_else(|| Error::UnknownLocalVariable(var.clone())) } crate::Expression::FunctionParameter(index) => { let handle = ir_function.parameter_types.get(*index as usize).unwrap(); @@ -1048,7 +1053,7 @@ impl Writer { function.parameters[*index as usize].result_id.unwrap(), None, )); - Some((load_id, Some(*handle))) + Ok(Some((load_id, Some(*handle)))) } crate::Expression::Call { origin, arguments } => match origin { crate::FunctionOrigin::Local(local_function) => { @@ -1059,7 +1064,7 @@ impl Writer { for argument in arguments { let expression = &ir_function.expressions[*argument]; let (id, ty) = self - .write_expression(ir_module, ir_function, expression, block, function) + .write_expression(ir_module, ir_function, expression, block, function)? .unwrap(); // Create variable - OpVariable @@ -1102,7 +1107,7 @@ impl Writer { *self.lookup_function.get(local_function).unwrap(), argument_ids.as_slice(), )); - Some((id, None)) + Ok(Some((id, None))) } _ => unimplemented!("{:?}", origin), }, @@ -1112,7 +1117,7 @@ impl Writer { convert, } => { if !convert { - return None; + return Ok(None); } let (expr_id, expr_type) = self @@ -1122,7 +1127,7 @@ impl Writer { &ir_function.expressions[*expr], block, function, - ) + )? .unwrap(); let id = self.generate_id(); @@ -1177,7 +1182,7 @@ impl Writer { block.body.push(instruction); - Some((id, None)) + Ok(Some((id, None))) } _ => unimplemented!("{:?}", expression), } @@ -1214,6 +1219,7 @@ impl Writer { &mut block, function, ) + .unwrap() .unwrap(); let id = match *expression { @@ -1251,6 +1257,7 @@ impl Writer { &mut block, function, ) + .unwrap() .unwrap(); let (value_id, value_ty) = self .write_expression( @@ -1260,6 +1267,7 @@ impl Writer { &mut block, function, ) + .unwrap() .unwrap(); let value_id = match value_expression { diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index e80cd39f0..cf9c59f2c 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -51,4 +51,5 @@ pub enum Error { BadString, IncompleteData, InvalidTerminator, + UnexpectedComparisonType(Handle), } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index c7458c1ec..a05694b1f 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1477,7 +1477,9 @@ impl> Parser { }; *comparison = true; } - _ => panic!("Unexpected comparison type {:?}", ty), + _ => { + return Err(Error::UnexpectedComparisonType(handle)); + } } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 3d7b4826b..782ad85e0 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1787,7 +1787,13 @@ impl Parser { } Ok(true) => {} Ok(false) => { - assert_eq!(self.scopes, Vec::new()); + if !self.scopes.is_empty() { + return Err(ParseError { + error: Error::Other, + scopes: std::mem::replace(&mut self.scopes, Vec::new()), + pos: (0, 0), + }); + }; return Ok(module); } } diff --git a/src/lib.rs b/src/lib.rs index 2354c8c5f..8a550e5d4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,7 +4,11 @@ //! //! To improve performance and reduce memory usage, most structures are stored //! in an [`Arena`], and can be retrieved using the corresponding [`Handle`]. -#![allow(clippy::new_without_default, clippy::unneeded_field_pattern)] +#![allow( + clippy::new_without_default, + clippy::unneeded_field_pattern, + clippy::match_like_matches_macro +)] #![deny(clippy::panic)] mod arena; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 64b59203b..ef698be57 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -29,6 +29,7 @@ impl Clone for Resolution { columns, width, }, + #[allow(clippy::panic)] _ => panic!("Unepxected clone type: {:?}", v), }), } @@ -50,6 +51,14 @@ pub enum ResolveError { FunctionReturnsVoid, #[error("Type is not found in the given immutable arena")] TypeNotFound, + #[error("Incompatible operand: {op} {operand}")] + IncompatibleOperand { op: String, operand: String }, + #[error("Incompatible operands: {left} {op} {right}")] + IncompatibleOperands { + op: String, + left: String, + right: String, + }, } pub struct ResolveContext<'a> { @@ -105,7 +114,12 @@ impl Typifier { kind: crate::ScalarKind::Float, width, }), - ref other => panic!("Can't access into {:?}", other), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "access".to_string(), + operand: format!("{:?}", other), + }) + } }, crate::Expression::AccessIndex { base, index } => match *self.get(base, types) { crate::TypeInner::Vector { size, kind, width } => { @@ -135,7 +149,12 @@ impl Typifier { .ok_or(ResolveError::InvalidAccessIndex)?; Resolution::Handle(member.ty) } - ref other => panic!("Can't access into {:?}", other), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "access index".to_string(), + operand: format!("{:?}", other), + }) + } }, crate::Expression::Constant(h) => Resolution::Handle(ctx.constants[h].ty), crate::Expression::Compose { ty, .. } => Resolution::Handle(ty), @@ -192,7 +211,13 @@ impl Typifier { kind: crate::ScalarKind::Float, width, }), - _ => panic!("Incompatible arguments {:?} x {:?}", ty_left, ty_right), + _ => { + return Err(ResolveError::IncompatibleOperands { + op: "x".to_string(), + left: format!("{:?}", ty_left), + right: format!("{:?}", ty_right), + }) + } } } } @@ -224,7 +249,12 @@ impl Typifier { rows: columns, width, }), - ref other => panic!("incompatible transpose of {:?}", other), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "transpose".to_string(), + operand: format!("{:?}", other), + }) + } }, crate::Expression::DotProduct(left_expr, _) => match *self.get(left_expr, types) { crate::TypeInner::Vector { @@ -232,7 +262,12 @@ impl Typifier { size: _, width, } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), - ref other => panic!("incompatible dot of {:?}", other), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "dot product".to_string(), + operand: format!("{:?}", other), + }) + } }, crate::Expression::CrossProduct(_, _) => unimplemented!(), crate::Expression::As { @@ -248,7 +283,12 @@ impl Typifier { size, width, } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }), - ref other => panic!("incompatible as of {:?}", other), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "as".to_string(), + operand: format!("{:?}", other), + }) + } }, crate::Expression::Derivative { .. } => unimplemented!(), crate::Expression::Call { @@ -260,13 +300,23 @@ impl Typifier { | crate::TypeInner::Scalar { kind, width } => { Resolution::Value(crate::TypeInner::Scalar { kind, width }) } - ref other => panic!("Unexpected argument {:?} on {}", other, name), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: name.clone(), + operand: format!("{:?}", other), + }) + } }, "dot" => match *self.get(arguments[0], types) { crate::TypeInner::Vector { kind, width, .. } => { Resolution::Value(crate::TypeInner::Scalar { kind, width }) } - ref other => panic!("Unexpected argument {:?} on {}", other, name), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: name.clone(), + operand: format!("{:?}", other), + }) + } }, //Note: `cross` is here too, we still need to figure out what to do with it "abs" | "atan2" | "cos" | "sin" | "floor" | "inverse" | "normalize" | "min" From 78c9e45182be5f28523d74f92b481f947d5819db Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 15 Oct 2020 19:38:02 +0200 Subject: [PATCH 0243/2212] [glsl-in] Add initial pre-processor (#238) * [glsl-in] Add initial pre-processor * [glsl-in] Tweak preprocessor after review - Add IfState struct - Use FastHashMap to pre-defines - Use ok-or() for some errors * [glsl-in] Remove Option in defines arg --- examples/convert.rs | 24 +++- src/front/glsl/error.rs | 2 + src/front/glsl/lex.rs | 17 ++- src/front/glsl/mod.rs | 20 ++- src/front/glsl/preprocess.rs | 152 ++++++++++++++++++++ src/front/glsl/preprocess_tests.rs | 218 +++++++++++++++++++++++++++++ tests/convert.rs | 2 +- tests/rosetta.rs | 24 +++- 8 files changed, 442 insertions(+), 17 deletions(-) create mode 100644 src/front/glsl/preprocess.rs create mode 100644 src/front/glsl/preprocess_tests.rs diff --git a/examples/convert.rs b/examples/convert.rs index 6cfb2caaa..a8160c14c 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -52,17 +52,35 @@ fn main() { #[cfg(feature = "glsl-in")] "vert" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main", naga::ShaderStage::Vertex).unwrap() + naga::front::glsl::parse_str( + &input, + "main", + naga::ShaderStage::Vertex, + Default::default(), + ) + .unwrap() } #[cfg(feature = "glsl-in")] "frag" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main", naga::ShaderStage::Fragment).unwrap() + naga::front::glsl::parse_str( + &input, + "main", + naga::ShaderStage::Fragment, + Default::default(), + ) + .unwrap() } #[cfg(feature = "glsl-in")] "comp" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::glsl::parse_str(&input, "main", naga::ShaderStage::Compute).unwrap() + naga::front::glsl::parse_str( + &input, + "main", + naga::ShaderStage::Compute, + Default::default(), + ) + .unwrap() } #[cfg(feature = "deserialize")] "ron" => { diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 0194544a6..db5ffbe9f 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -21,6 +21,7 @@ pub enum ErrorKind { VariableNotAvailable(String), ExpectedConstant, SemanticError(&'static str), + PreprocessorError(String), } impl fmt::Display for ErrorKind { @@ -53,6 +54,7 @@ impl fmt::Display for ErrorKind { } ErrorKind::ExpectedConstant => write!(f, "Expected constant"), ErrorKind::SemanticError(msg) => write!(f, "Semantic error: {}", msg), + ErrorKind::PreprocessorError(val) => write!(f, "Preprocessor error: {}", val), } } } diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index a4f5e956f..236faef42 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -1,5 +1,5 @@ use super::parser::Token; -use super::{token::TokenMetadata, types::parse_type}; +use super::{preprocess::LinePreProcessor, token::TokenMetadata, types::parse_type}; use std::{iter::Enumerate, str::Lines}; fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { @@ -23,6 +23,7 @@ pub struct Lexer<'a> { line: usize, offset: usize, inside_comment: bool, + pub pp: LinePreProcessor, } impl<'a> Lexer<'a> { @@ -289,6 +290,7 @@ impl<'a> Lexer<'a> { line: 0, offset: 0, inside_comment: false, + pp: LinePreProcessor::new(), }; lexer.next_line(); lexer @@ -307,10 +309,15 @@ impl<'a> Lexer<'a> { } } - self.input = input; - self.line = line; - self.offset = 0; - true + if let Ok(processed) = self.pp.process_line(&input) { + self.input = processed.unwrap_or_default(); + self.line = line; + self.offset = 0; + true + } else { + //TODO: handle preprocessor error + false + } } else { false } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index c711b3119..466101182 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,9 +1,13 @@ -use crate::{Module, ShaderStage}; +use crate::{FastHashMap, Module, ShaderStage}; mod lex; #[cfg(test)] mod lex_tests; +mod preprocess; +#[cfg(test)] +mod preprocess_tests; + mod ast; use ast::Program; @@ -17,11 +21,17 @@ mod token; mod types; mod variables; -pub fn parse_str(source: &str, entry: &str, stage: ShaderStage) -> Result { - log::debug!("------ GLSL-pomelo ------"); - +pub fn parse_str( + source: &str, + entry: &str, + stage: ShaderStage, + defines: FastHashMap, +) -> Result { let mut program = Program::new(stage, entry); - let lex = Lexer::new(source); + + let mut lex = Lexer::new(source); + lex.pp.defines = defines; + let mut parser = parser::Parser::new(&mut program); for token in lex { diff --git a/src/front/glsl/preprocess.rs b/src/front/glsl/preprocess.rs new file mode 100644 index 000000000..605059471 --- /dev/null +++ b/src/front/glsl/preprocess.rs @@ -0,0 +1,152 @@ +use crate::FastHashMap; +use thiserror::Error; + +#[derive(Clone, Debug, Error)] +#[cfg_attr(test, derive(PartialEq))] +pub enum Error { + #[error("unmatched else")] + UnmatchedElse, + #[error("unmatched endif")] + UnmatchedEndif, + #[error("missing macro name")] + MissingMacro, +} + +#[derive(Clone, Debug)] +pub struct IfState { + true_branch: bool, + else_seen: bool, +} + +#[derive(Clone, Debug)] +pub struct LinePreProcessor { + pub defines: FastHashMap, + if_stack: Vec, + inside_comment: bool, + in_preprocess: bool, +} + +impl LinePreProcessor { + pub fn new() -> Self { + LinePreProcessor { + defines: FastHashMap::default(), + if_stack: vec![], + inside_comment: false, + in_preprocess: false, + } + } + + fn subst_defines(&self, input: &str) -> String { + //TODO: don't subst in commments, strings literals? + self.defines + .iter() + .fold(input.to_string(), |acc, (k, v)| acc.replace(k, v)) + } + + pub fn process_line(&mut self, line: &str) -> Result, Error> { + let mut skip = !self.if_stack.last().map(|i| i.true_branch).unwrap_or(true); + let mut inside_comment = self.inside_comment; + let mut in_preprocess = inside_comment && self.in_preprocess; + // single-line comment + let mut processed = line; + if let Some(pos) = line.find("//") { + processed = line.split_at(pos).0; + } + // multi-line comment + let mut processed_string: String; + loop { + if inside_comment { + if let Some(pos) = processed.find("*/") { + processed = processed.split_at(pos + 2).1; + inside_comment = false; + self.inside_comment = false; + continue; + } + } else if let Some(pos) = processed.find("/*") { + if let Some(end_pos) = processed[pos + 2..].find("*/") { + // comment ends during this line + processed_string = processed.to_string(); + processed_string.replace_range(pos..pos + end_pos + 4, ""); + processed = &processed_string; + } else { + processed = processed.split_at(pos).0; + inside_comment = true; + } + continue; + } + break; + } + // strip leading whitespace + processed = processed.trim_start(); + if processed.starts_with('#') && !self.inside_comment { + let mut iter = processed[1..] + .trim_start() + .splitn(2, |c: char| c.is_whitespace()); + if let Some(directive) = iter.next() { + skip = true; + in_preprocess = true; + match directive { + "version" => { + skip = false; + } + "define" => { + let rest = iter.next().ok_or(Error::MissingMacro)?; + let pos = rest + .find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '(') + .unwrap_or_else(|| rest.len()); + let (key, mut value) = rest.split_at(pos); + value = value.trim(); + self.defines.insert(key.into(), self.subst_defines(value)); + } + "undef" => { + let rest = iter.next().ok_or(Error::MissingMacro)?; + let key = rest.trim(); + self.defines.remove(key); + } + "ifdef" => { + let rest = iter.next().ok_or(Error::MissingMacro)?; + let key = rest.trim(); + self.if_stack.push(IfState { + true_branch: self.defines.contains_key(key), + else_seen: false, + }); + } + "ifndef" => { + let rest = iter.next().ok_or(Error::MissingMacro)?; + let key = rest.trim(); + self.if_stack.push(IfState { + true_branch: !self.defines.contains_key(key), + else_seen: false, + }); + } + "else" => { + let if_state = self.if_stack.last_mut().ok_or(Error::UnmatchedElse)?; + if !if_state.else_seen { + // this is first else + if_state.true_branch = !if_state.true_branch; + if_state.else_seen = true; + } else { + return Err(Error::UnmatchedElse); + } + } + "endif" => { + self.if_stack.pop().ok_or(Error::UnmatchedEndif)?; + } + _ => {} + } + } + } + let res = if !skip && !self.inside_comment { + Ok(Some(self.subst_defines(&line))) + } else { + Ok(if in_preprocess && !self.in_preprocess { + Some("".to_string()) + } else { + None + }) + }; + self.in_preprocess = in_preprocess || skip; + self.inside_comment = inside_comment; + res + } +} diff --git a/src/front/glsl/preprocess_tests.rs b/src/front/glsl/preprocess_tests.rs new file mode 100644 index 000000000..253a99935 --- /dev/null +++ b/src/front/glsl/preprocess_tests.rs @@ -0,0 +1,218 @@ +use super::preprocess::{Error, LinePreProcessor}; +use std::{iter::Enumerate, str::Lines}; + +#[derive(Clone, Debug)] +pub struct PreProcessor<'a> { + lines: Enumerate>, + input: String, + line: usize, + offset: usize, + line_pp: LinePreProcessor, +} + +impl<'a> PreProcessor<'a> { + pub fn new(input: &'a str) -> Self { + let mut lexer = PreProcessor { + lines: input.lines().enumerate(), + input: "".to_string(), + line: 0, + offset: 0, + line_pp: LinePreProcessor::new(), + }; + lexer.next_line(); + lexer + } + + fn next_line(&mut self) -> bool { + if let Some((line, input)) = self.lines.next() { + let mut input = String::from(input); + + while input.ends_with('\\') { + if let Some((_, next)) = self.lines.next() { + input.pop(); + input.push_str(next); + } else { + break; + } + } + + self.input = input; + self.line = line; + self.offset = 0; + true + } else { + false + } + } + + pub fn process(&mut self) -> Result { + let mut res = String::new(); + loop { + let line = &self.line_pp.process_line(&self.input)?; + if let Some(line) = line { + res.push_str(line); + } + if !self.next_line() { + break; + } + if line.is_some() { + res.push_str("\n"); + } + } + Ok(res) + } +} + +#[test] +fn preprocess() { + // line continuation + let mut pp = PreProcessor::new( + "void main my_\ + func", + ); + assert_eq!(pp.process().unwrap(), "void main my_func"); + + // preserve #version + let mut pp = PreProcessor::new( + "#version 450 core\n\ + void main()", + ); + assert_eq!(pp.process().unwrap(), "#version 450 core\nvoid main()"); + + // simple define + let mut pp = PreProcessor::new( + "#define FOO 42 \n\ + fun=FOO", + ); + assert_eq!(pp.process().unwrap(), "\nfun=42"); + + // ifdef with else + let mut pp = PreProcessor::new( + "#define FOO\n\ + #ifdef FOO\n\ + foo=42\n\ + #endif\n\ + some=17\n\ + #ifdef BAR\n\ + bar=88\n\ + #else\n\ + mm=49\n\ + #endif\n\ + done=1", + ); + assert_eq!( + pp.process().unwrap(), + "\n\ + foo=42\n\ + \n\ + some=17\n\ + \n\ + mm=49\n\ + \n\ + done=1" + ); + + // nested ifdef/ifndef + let mut pp = PreProcessor::new( + "#define FOO\n\ + #define BOO\n\ + #ifdef FOO\n\ + foo=42\n\ + #ifdef BOO\n\ + boo=44\n\ + #endif\n\ + ifd=0\n\ + #ifndef XYZ\n\ + nxyz=8\n\ + #endif\n\ + #endif\n\ + some=17\n\ + #ifdef BAR\n\ + bar=88\n\ + #else\n\ + mm=49\n\ + #endif\n\ + done=1", + ); + assert_eq!( + pp.process().unwrap(), + "\n\ + foo=42\n\ + \n\ + boo=44\n\ + \n\ + ifd=0\n\ + \n\ + nxyz=8\n\ + \n\ + some=17\n\ + \n\ + mm=49\n\ + \n\ + done=1" + ); + + // undef + let mut pp = PreProcessor::new( + "#define FOO\n\ + #ifdef FOO\n\ + foo=42\n\ + #endif\n\ + some=17\n\ + #undef FOO\n\ + #ifdef FOO\n\ + foo=88\n\ + #else\n\ + nofoo=66\n\ + #endif\n\ + done=1", + ); + assert_eq!( + pp.process().unwrap(), + "\n\ + foo=42\n\ + \n\ + some=17\n\ + \n\ + nofoo=66\n\ + \n\ + done=1" + ); + + // single-line comment + let mut pp = PreProcessor::new( + "#define FOO 42//1234\n\ + fun=FOO", + ); + assert_eq!(pp.process().unwrap(), "\nfun=42"); + + // multi-line comments + let mut pp = PreProcessor::new( + "#define FOO 52/*/1234\n\ + #define FOO 88\n\ + end of comment*/ /* one more comment */ #define FOO 56\n\ + fun=FOO", + ); + assert_eq!(pp.process().unwrap(), "\nfun=56"); + + // unmatched endif + let mut pp = PreProcessor::new( + "#ifdef FOO\n\ + foo=42\n\ + #endif\n\ + #endif", + ); + assert_eq!(pp.process(), Err(Error::UnmatchedEndif)); + + // unmatched else + let mut pp = PreProcessor::new( + "#ifdef FOO\n\ + foo=42\n\ + #else\n\ + bar=88\n\ + #else\n\ + bad=true\n\ + #endif", + ); + assert_eq!(pp.process(), Err(Error::UnmatchedElse)); +} diff --git a/tests/convert.rs b/tests/convert.rs index 6fc59e30c..99c0e8b0d 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -20,7 +20,7 @@ fn load_spv(name: &str) -> naga::Module { #[cfg(feature = "glsl-in")] fn load_glsl(name: &str, entry: &str, stage: naga::ShaderStage) -> naga::Module { let input = load_test_data(name); - naga::front::glsl::parse_str(&input, entry, stage).unwrap() + naga::front::glsl::parse_str(&input, entry, stage, Default::default()).unwrap() } #[cfg(feature = "wgsl-in")] diff --git a/tests/rosetta.rs b/tests/rosetta.rs index 70da9922b..c97da529c 100644 --- a/tests/rosetta.rs +++ b/tests/rosetta.rs @@ -40,15 +40,33 @@ fn test_rosetta(dir_name: &str) { #[cfg(feature = "glsl-in")] { if let Ok(input) = fs::read_to_string(dir_path.join("x.vert")) { - let module = glsl::parse_str(&input, "main", naga::ShaderStage::Vertex).unwrap(); + let module = glsl::parse_str( + &input, + "main", + naga::ShaderStage::Vertex, + Default::default(), + ) + .unwrap(); check("vert", &module, &expected); } if let Ok(input) = fs::read_to_string(dir_path.join("x.frag")) { - let module = glsl::parse_str(&input, "main", naga::ShaderStage::Fragment).unwrap(); + let module = glsl::parse_str( + &input, + "main", + naga::ShaderStage::Fragment, + Default::default(), + ) + .unwrap(); check("frag", &module, &expected); } if let Ok(input) = fs::read_to_string(dir_path.join("x.comp")) { - let module = glsl::parse_str(&input, "main", naga::ShaderStage::Compute).unwrap(); + let module = glsl::parse_str( + &input, + "main", + naga::ShaderStage::Compute, + Default::default(), + ) + .unwrap(); check("comp", &module, &expected); } } From a718992acbcc344bcc4cd7d6722effc230535ddd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 19 Oct 2020 14:40:30 +0100 Subject: [PATCH 0244/2212] Added new external functions to the glsl backend to make it on par with the typifier (#240) --- README.md | 2 +- src/back/glsl.rs | 35 ++++++++++++++--------------------- 2 files changed, 15 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index d0672f636..e09db9182 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ SPIR-V (binary) | :construction: | | WGSL | | | Metal | :construction: | | HLSL | | | -GLSL | | | +GLSL | :construction: | | AIR | | | DXIR | | | DXIL | | | diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 3884282a5..c4cb2c340 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1245,17 +1245,22 @@ fn write_expression<'a, 'b>( origin: crate::FunctionOrigin::External(ref name), ref arguments, } => match name.as_str() { - "cos" | "normalize" | "sin" => { + "cos" | "normalize" | "sin" | "length" | "abs" | "floor" | "inverse" => { let expr = write_expression(&builder.expressions[arguments[0]], module, builder)?; Cow::Owned(format!("{}({})", name, expr)) } - "fclamp" => { - let val = write_expression(&builder.expressions[arguments[0]], module, builder)?; - let min = write_expression(&builder.expressions[arguments[1]], module, builder)?; - let max = write_expression(&builder.expressions[arguments[2]], module, builder)?; + "fclamp" | "clamp" | "mix" | "smoothstep" => { + let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; + let y = write_expression(&builder.expressions[arguments[1]], module, builder)?; + let a = write_expression(&builder.expressions[arguments[2]], module, builder)?; - Cow::Owned(format!("clamp({}, {}, {})", val, min, max)) + let name = match name.as_str() { + "fclamp" => "clamp", + name => name, + }; + + Cow::Owned(format!("{}({}, {}, {})", name, x, y, a)) } "atan2" => { let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; @@ -1263,23 +1268,11 @@ fn write_expression<'a, 'b>( Cow::Owned(format!("atan({}, {})", y, x)) } - "distance" => { - let p0 = write_expression(&builder.expressions[arguments[0]], module, builder)?; - let p1 = write_expression(&builder.expressions[arguments[1]], module, builder)?; - - Cow::Owned(format!("distance({}, {})", p0, p1)) - } - "length" => { + "distance" | "dot" | "min" | "max" | "reflect" | "pow" | "step" | "cross" => { let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; + let y = write_expression(&builder.expressions[arguments[1]], module, builder)?; - Cow::Owned(format!("length({})", x)) - } - "mix" => { - let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; - let y = write_expression(&builder.expressions[arguments[0]], module, builder)?; - let a = write_expression(&builder.expressions[arguments[0]], module, builder)?; - - Cow::Owned(format!("mix({}, {}, {})", x, y, a)) + Cow::Owned(format!("{}({}, {})", name, x, y)) } other => { return Err(Error::Custom(format!( From 621af3cbcbc1b8af83a72079423f2b0eef299564 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 20 Oct 2020 14:44:56 -0400 Subject: [PATCH 0245/2212] Bump thiserror to 1.0.21 (#241) --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 803c506f9..5cf912cc2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ log = "0.4" num-traits = "0.2" spirv = { package = "spirv_headers", version = "1.4.2", optional = true } pomelo = { version = "0.1.4", optional = true } -thiserror = "1.0" +thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } From c1830901c7fae4b8a4a4d86b204b83888edf6724 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 27 Oct 2020 09:05:14 -0400 Subject: [PATCH 0246/2212] Simplify bitshift IR (#244) --- src/back/glsl.rs | 5 ++--- src/front/glsl/parser.rs | 9 ++++----- src/front/spv/mod.rs | 32 ++++++++++++++++++++++++++++++++ src/front/wgsl/lexer.rs | 7 +------ src/front/wgsl/mod.rs | 8 ++------ src/lib.rs | 6 +++--- src/proc/typifier.rs | 7 ++----- 7 files changed, 46 insertions(+), 28 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index c4cb2c340..fee127199 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1126,9 +1126,8 @@ fn write_expression<'a, 'b>( BinaryOperator::InclusiveOr => "|", BinaryOperator::LogicalAnd => "&&", BinaryOperator::LogicalOr => "||", - BinaryOperator::ShiftLeftLogical => "<<", - BinaryOperator::ShiftRightLogical => todo!(), - BinaryOperator::ShiftRightArithmetic => ">>", + BinaryOperator::ShiftLeft => "<<", + BinaryOperator::ShiftRight => ">>", }; Cow::Owned(format!("({} {} {})", left_expr, op_str, right_expr)) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 3c8aaa180..4815adacd 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -328,11 +328,10 @@ pomelo! { } shift_expression ::= additive_expression; shift_expression ::= shift_expression(left) LeftOp additive_expression(right) { - extra.binary_expr(BinaryOperator::ShiftLeftLogical, left, right) + extra.binary_expr(BinaryOperator::ShiftLeft, left, right) } shift_expression ::= shift_expression(left) RightOp additive_expression(right) { - //TODO: when to use ShiftRightArithmetic - extra.binary_expr(BinaryOperator::ShiftRightLogical, left, right) + extra.binary_expr(BinaryOperator::ShiftRight, left, right) } relational_expression ::= shift_expression; relational_expression ::= relational_expression(left) LeftAngle shift_expression(right) { @@ -422,10 +421,10 @@ pomelo! { BinaryOperator::Subtract } assignment_operator ::= LeftAssign { - BinaryOperator::ShiftLeftLogical + BinaryOperator::ShiftLeft } assignment_operator ::= RightAssign { - BinaryOperator::ShiftRightLogical + BinaryOperator::ShiftRight } assignment_operator ::= AndAssign { BinaryOperator::And diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a05694b1f..38ca9aea0 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -852,6 +852,38 @@ impl> Parser { }, ); } + // Bitwise instructions + Op::Not => { + inst.expect(4)?; + self.parse_expr_unary_op(expressions, crate::UnaryOperator::Not)?; + } + Op::BitwiseOr => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::InclusiveOr)?; + } + Op::BitwiseXor => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::ExclusiveOr)?; + } + Op::BitwiseAnd => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::And)?; + } + Op::ShiftRightLogical => { + inst.expect(5)?; + //TODO: convert input and result to usigned + self.parse_expr_binary_op(expressions, crate::BinaryOperator::ShiftRight)?; + } + Op::ShiftRightArithmetic => { + inst.expect(5)?; + //TODO: convert input and result to signed + self.parse_expr_binary_op(expressions, crate::BinaryOperator::ShiftRight)?; + } + Op::ShiftLeftLogical => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::ShiftLeft)?; + } + // Sampling Op::SampledImage => { inst.expect(5)?; let _result_type_id = self.next()?; diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 65bea6384..b991ecf61 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -69,12 +69,7 @@ fn consume_token(mut input: &str) -> (Token<'_>, &str) { if next == Some('=') { (Token::LogicalOperation(cur), chars.as_str()) } else if next == Some(cur) { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::ArithmeticShiftOperation(cur), chars.as_str()) - } else { - (Token::ShiftOperation(cur), input) - } + (Token::ShiftOperation(cur), chars.as_str()) } else { (Token::Paren(cur), input) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 782ad85e0..5e8a3824e 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -26,7 +26,6 @@ pub enum Token<'a> { Operation(char), LogicalOperation(char), ShiftOperation(char), - ArithmeticShiftOperation(char), Arrow, Unknown(char), UnterminatedString, @@ -790,13 +789,10 @@ impl Parser { lexer, |token| match token { Token::ShiftOperation('<') => { - Some(crate::BinaryOperator::ShiftLeftLogical) + Some(crate::BinaryOperator::ShiftLeft) } Token::ShiftOperation('>') => { - Some(crate::BinaryOperator::ShiftRightLogical) - } - Token::ArithmeticShiftOperation('>') => { - Some(crate::BinaryOperator::ShiftRightArithmetic) + Some(crate::BinaryOperator::ShiftRight) } _ => None, }, diff --git a/src/lib.rs b/src/lib.rs index 8a550e5d4..e0a75e72e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -498,9 +498,9 @@ pub enum BinaryOperator { InclusiveOr, LogicalAnd, LogicalOr, - ShiftLeftLogical, - ShiftRightLogical, - ShiftRightArithmetic, + ShiftLeft, + /// Right shift carries the sign of signed integers only. + ShiftRight, } /// Built-in shader function. diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index ef698be57..99ed0a699 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -232,11 +232,8 @@ impl Typifier { crate::BinaryOperator::And | crate::BinaryOperator::ExclusiveOr | crate::BinaryOperator::InclusiveOr - | crate::BinaryOperator::ShiftLeftLogical - | crate::BinaryOperator::ShiftRightLogical - | crate::BinaryOperator::ShiftRightArithmetic => { - self.resolutions[left.index()].clone() - } + | crate::BinaryOperator::ShiftLeft + | crate::BinaryOperator::ShiftRight => self.resolutions[left.index()].clone(), }, crate::Expression::Intrinsic { .. } => unimplemented!(), crate::Expression::Transpose(expr) => match *self.get(expr, types) { From ce49afa3919ee1780fb6452d5ef82c05ef1e6f7e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 27 Oct 2020 09:10:55 -0400 Subject: [PATCH 0247/2212] Clean up the storage classes (#245) --- src/back/glsl.rs | 20 +++--- src/back/msl.rs | 14 ++-- src/back/spv/layout.rs | 4 ++ src/back/spv/writer.rs | 11 ++- src/front/glsl/parser.rs | 4 +- src/front/spv/convert.rs | 15 ---- src/front/spv/mod.rs | 34 +++++++-- src/front/wgsl/conv.rs | 3 +- src/front/wgsl/mod.rs | 15 +++- src/lib.rs | 16 ++++- src/proc/interface.rs | 2 +- src/proc/validator.rs | 150 ++++++++++++++++++++++++--------------- test-data/boids.wgsl | 4 +- test-data/quad.wgsl | 4 +- 14 files changed, 184 insertions(+), 112 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index fee127199..8463b1cff 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -112,6 +112,7 @@ bitflags::bitflags! { const IMAGE_LOAD_STORE = 1 << 8; const CONSERVATIVE_DEPTH = 1 << 9; const TEXTURE_1D = 1 << 10; + const PUSH_CONSTANT = 1 << 11; } } @@ -364,7 +365,7 @@ pub fn write<'a>( } let block = match global.class { - StorageClass::StorageBuffer | StorageClass::Uniform => true, + StorageClass::Storage | StorageClass::Uniform => true, _ => false, }; @@ -557,14 +558,15 @@ pub fn write<'a>( let name = if let Some(ref binding) = global.binding { let prefix = match global.class { - StorageClass::Constant => "const", StorageClass::Function => "fn", StorageClass::Input => "in", StorageClass::Output => "out", StorageClass::Private => "priv", - StorageClass::StorageBuffer => "buffer", + StorageClass::Storage => "buffer", StorageClass::Uniform => "uniform", + StorageClass::Handle => "handle", StorageClass::WorkGroup => "wg", + StorageClass::PushConstant => "pc", }; match binding { @@ -606,7 +608,7 @@ pub fn write<'a>( } let block = match global.class { - StorageClass::StorageBuffer | StorageClass::Uniform => { + StorageClass::Storage | StorageClass::Uniform => { Some(format!("global_block_{}", handle.index())) } _ => None, @@ -1492,22 +1494,24 @@ fn write_storage_class( manager: &mut FeaturesManager, ) -> Result<&'static str, Error> { Ok(match class { - StorageClass::Constant => "", StorageClass::Function => "", StorageClass::Input => "in ", StorageClass::Output => "out ", StorageClass::Private => "", - StorageClass::StorageBuffer => { + StorageClass::Storage => { manager.request(Features::BUFFER_STORAGE); - "buffer " } StorageClass::Uniform => "uniform ", + StorageClass::Handle => "uniform ", StorageClass::WorkGroup => { manager.request(Features::COMPUTE_SHADER); - "shared " } + StorageClass::PushConstant => { + manager.request(Features::PUSH_CONSTANT); + "" + } }) } diff --git a/src/back/msl.rs b/src/back/msl.rs index d7ff76069..007fa85ae 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -254,9 +254,7 @@ impl<'a> TypedGlobalVariable<'a> { let (space_qualifier, reference) = match ty.inner { crate::TypeInner::Struct { .. } => match var.class { - crate::StorageClass::Constant - | crate::StorageClass::Uniform - | crate::StorageClass::StorageBuffer => { + crate::StorageClass::Uniform | crate::StorageClass::Storage => { let space = if self.usage.contains(crate::GlobalUse::STORE) { "device " } else { @@ -837,9 +835,13 @@ impl Writer { let base_name = module.types[base].name.or_index(base); let class_name = match class { Sc::Input | Sc::Output => continue, - Sc::Constant | Sc::Uniform => "constant", - Sc::StorageBuffer => "device", - Sc::Private | Sc::Function | Sc::WorkGroup => "", + Sc::Uniform => "constant", + Sc::Storage => "device", + Sc::Handle + | Sc::Private + | Sc::Function + | Sc::WorkGroup + | Sc::PushConstant => "", }; write!(self.out, "typedef {} {} *{}", class_name, base_name, name)?; } diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index e4c3d1cc0..006e78531 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -24,6 +24,10 @@ impl PhysicalLayout { sink.extend(iter::once(self.bound)); sink.extend(iter::once(self.instruction_schema)); } + + pub(super) fn supports_storage_buffers(&self) -> bool { + self.version >= 0x10300 + } } impl LogicalLayout { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index fa072a669..b0e0a400c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -417,14 +417,19 @@ impl Writer { fn parse_to_spirv_storage_class(&self, class: crate::StorageClass) -> spirv::StorageClass { match class { - crate::StorageClass::Constant => spirv::StorageClass::UniformConstant, + crate::StorageClass::Handle => spirv::StorageClass::UniformConstant, crate::StorageClass::Function => spirv::StorageClass::Function, crate::StorageClass::Input => spirv::StorageClass::Input, crate::StorageClass::Output => spirv::StorageClass::Output, crate::StorageClass::Private => spirv::StorageClass::Private, - crate::StorageClass::StorageBuffer => spirv::StorageClass::StorageBuffer, - crate::StorageClass::Uniform => spirv::StorageClass::Uniform, + crate::StorageClass::Storage if self.physical_layout.supports_storage_buffers() => { + spirv::StorageClass::StorageBuffer + } + crate::StorageClass::Storage | crate::StorageClass::Uniform => { + spirv::StorageClass::Uniform + } crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, + crate::StorageClass::PushConstant => spirv::StorageClass::PushConstant, } } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 4815adacd..0ec67099e 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -596,9 +596,7 @@ pomelo! { // single_type_qualifier ::= invariant_qualifier; // single_type_qualifier ::= precise_qualifier; - storage_qualifier ::= Const { - StorageClass::Constant - } + // storage_qualifier ::= Const // storage_qualifier ::= InOut; storage_qualifier ::= In { StorageClass::Input diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index c7b5cfa48..6036d0894 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -43,21 +43,6 @@ pub fn map_vector_size(word: spirv::Word) -> Result { } } -pub fn map_storage_class(word: spirv::Word) -> Result { - use spirv::StorageClass as Sc; - match Sc::from_u32(word) { - Some(Sc::UniformConstant) => Ok(crate::StorageClass::Constant), - Some(Sc::Function) => Ok(crate::StorageClass::Function), - Some(Sc::Input) => Ok(crate::StorageClass::Input), - Some(Sc::Output) => Ok(crate::StorageClass::Output), - Some(Sc::Private) => Ok(crate::StorageClass::Private), - Some(Sc::StorageBuffer) => Ok(crate::StorageClass::StorageBuffer), - Some(Sc::Uniform) => Ok(crate::StorageClass::Uniform), - Some(Sc::Workgroup) => Ok(crate::StorageClass::WorkGroup), - _ => Err(Error::UnsupportedStorageClass(word)), - } -} - pub fn map_image_dim(word: spirv::Word) -> Result { use spirv::Dim as D; match D::from_u32(word) { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 38ca9aea0..61dc3d5fd 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2274,19 +2274,39 @@ impl> Parser { .future_decor .remove(&id) .ok_or(Error::InvalidBinding(id))?; - let class = map_storage_class(storage_class)?; + + let class = { + use spirv::StorageClass as Sc; + match Sc::from_u32(storage_class) { + Some(Sc::Function) => crate::StorageClass::Function, + Some(Sc::Input) => crate::StorageClass::Input, + Some(Sc::Output) => crate::StorageClass::Output, + Some(Sc::Private) => crate::StorageClass::Private, + Some(Sc::UniformConstant) => crate::StorageClass::Handle, + Some(Sc::StorageBuffer) => crate::StorageClass::Storage, + Some(Sc::Uniform) => { + if self + .lookup_storage_buffer_types + .contains(&lookup_type.handle) + { + crate::StorageClass::Storage + } else { + crate::StorageClass::Uniform + } + } + Some(Sc::Workgroup) => crate::StorageClass::WorkGroup, + Some(Sc::PushConstant) => crate::StorageClass::PushConstant, + _ => return Err(Error::UnsupportedStorageClass(storage_class)), + } + }; + let binding = match (class, &module.types[lookup_type.handle].inner) { (crate::StorageClass::Input, &crate::TypeInner::Struct { .. }) | (crate::StorageClass::Output, &crate::TypeInner::Struct { .. }) => None, _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), }; let is_storage = match module.types[lookup_type.handle].inner { - crate::TypeInner::Struct { .. } => match class { - crate::StorageClass::StorageBuffer => true, - _ => self - .lookup_storage_buffer_types - .contains(&lookup_type.handle), - }, + crate::TypeInner::Struct { .. } => class == crate::StorageClass::Storage, crate::TypeInner::Image { class: crate::ImageClass::Storage(_), .. diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 0b25ad943..6fdea89e7 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -4,8 +4,9 @@ pub fn map_storage_class(word: &str) -> Result> { match word { "in" => Ok(crate::StorageClass::Input), "out" => Ok(crate::StorageClass::Output), + "private" => Ok(crate::StorageClass::Private), "uniform" => Ok(crate::StorageClass::Uniform), - "storage_buffer" => Ok(crate::StorageClass::StorageBuffer), + "storage" => Ok(crate::StorageClass::Storage), _ => Err(Error::UnknownStorageClass(word)), } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5e8a3824e..05c274994 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -930,8 +930,17 @@ impl Parser { lexer.expect(Token::Separator(':'))?; let ty = self.parse_type_decl(lexer, None, type_arena)?; let access = match class { - Some(crate::StorageClass::StorageBuffer) => crate::StorageAccess::all(), - Some(crate::StorageClass::Constant) => crate::StorageAccess::LOAD, + Some(crate::StorageClass::Storage) => crate::StorageAccess::all(), + Some(crate::StorageClass::Handle) => { + match type_arena[ty].inner { + //TODO: RW textures + crate::TypeInner::Image { + class: crate::ImageClass::Storage(_), + .. + } => crate::StorageAccess::LOAD, + _ => crate::StorageAccess::empty(), + } + } _ => crate::StorageAccess::empty(), }; if lexer.skip(Token::Operation('=')) { @@ -1708,7 +1717,7 @@ impl Parser { crate::BuiltIn::Position => crate::StorageClass::Output, _ => unimplemented!(), }, - _ => crate::StorageClass::Private, + _ => crate::StorageClass::Handle, }, }; let var_handle = module.global_variables.append(crate::GlobalVariable { diff --git a/src/lib.rs b/src/lib.rs index e0a75e72e..63ca33f9a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -108,14 +108,24 @@ pub enum ShaderStage { #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[allow(missing_docs)] // The names are self evident pub enum StorageClass { - Constant, + /// Function locals. Function, + /// Pipeline input, per invocation. Input, + /// Pipeline output, per invocation, mutable. Output, + /// Private data, per invocation, mutable. Private, - StorageBuffer, - Uniform, + /// Workgroup shared data, mutable. WorkGroup, + /// Uniform buffer data. + Uniform, + /// Storage buffer data, potentially mutable. + Storage, + /// Opaque handles, such as samplers and images. + Handle, + /// Push constants. + PushConstant, } /// Built-in inputs and outputs. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 33767f597..670f2da50 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -218,7 +218,7 @@ mod tests { fn global_use_scan() { let test_global = GlobalVariable { name: None, - class: StorageClass::Constant, + class: StorageClass::Uniform, binding: None, ty: Handle::new(std::num::NonZeroU32::new(1).unwrap()), interpolation: None, diff --git a/src/proc/validator.rs b/src/proc/validator.rs index ffcf49492..bfb2858c6 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -21,8 +21,11 @@ pub enum GlobalVariableError { InvalidType, #[error("Interpolation is not valid")] InvalidInterpolation, - #[error("Storage access flags are invalid")] - InvalidStorageAccess, + #[error("Storage access {seen:?} exceed the allowed {allowed:?}")] + InvalidStorageAccess { + allowed: crate::StorageAccess, + seen: crate::StorageAccess, + }, #[error("Binding decoration is missing or not applicable")] InvalidBinding, #[error("Binding is out of range")] @@ -63,8 +66,12 @@ pub enum ValidationError { InvalidTypeWidth(crate::ScalarKind, crate::Bytes), #[error("The type handle {0:?} can not be resolved")] UnresolvedType(Handle), - #[error("Global variable {0:?} is invalid: {1:?}")] - GlobalVariable(Handle, GlobalVariableError), + #[error("Global variable {handle:?} '{name}' is invalid: {error:?}")] + GlobalVariable { + handle: Handle, + name: String, + error: GlobalVariableError, + }, #[error("Function {0:?} is invalid: {1:?}")] Function(Handle, FunctionError), #[error("Entry point {name} at {stage:?} is invalid: {error:?}")] @@ -75,6 +82,41 @@ pub enum ValidationError { }, } +impl crate::GlobalVariable { + fn forbid_interpolation(&self) -> Result<(), GlobalVariableError> { + match self.interpolation { + Some(_) => Err(GlobalVariableError::InvalidInterpolation), + None => Ok(()), + } + } + + fn check_resource(&self) -> Result<(), GlobalVariableError> { + match self.binding { + Some(crate::Binding::BuiltIn(_)) => {} // validated per entry point + Some(crate::Binding::Resource { group, binding }) => { + if group > MAX_BIND_GROUPS || binding > MAX_BIND_INDICES { + return Err(GlobalVariableError::OutOfRangeBinding); + } + } + Some(crate::Binding::Location(_)) | None => { + return Err(GlobalVariableError::InvalidBinding) + } + } + self.forbid_interpolation() + } +} + +fn storage_usage(access: crate::StorageAccess) -> crate::GlobalUse { + let mut storage_usage = crate::GlobalUse::empty(); + if access.contains(crate::StorageAccess::LOAD) { + storage_usage |= crate::GlobalUse::LOAD; + } + if access.contains(crate::StorageAccess::STORE) { + storage_usage |= crate::GlobalUse::STORE; + } + storage_usage +} + impl Validator { /// Construct a new validator instance. pub fn new() -> Self { @@ -89,15 +131,13 @@ impl Validator { types: &Arena, ) -> Result<(), GlobalVariableError> { log::debug!("var {:?}", var); - let is_storage = match var.class { + let allowed_storage_access = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), crate::StorageClass::Input | crate::StorageClass::Output => { match var.binding { Some(crate::Binding::BuiltIn(_)) => { // validated per entry point - if var.interpolation.is_some() { - return Err(GlobalVariableError::InvalidInterpolation); - } + var.forbid_interpolation()? } Some(crate::Binding::Location(loc)) => { if loc > MAX_LOCATIONS { @@ -117,56 +157,53 @@ impl Validator { match types[var.ty].inner { //TODO: check the member types crate::TypeInner::Struct { members: _ } => { - if var.interpolation.is_some() { - return Err(GlobalVariableError::InvalidInterpolation); - } + var.forbid_interpolation()? } _ => return Err(GlobalVariableError::InvalidType), } } } - false + crate::StorageAccess::empty() } - crate::StorageClass::Constant - | crate::StorageClass::StorageBuffer - | crate::StorageClass::Uniform => { - match var.binding { - Some(crate::Binding::BuiltIn(_)) => {} // validated per entry point - Some(crate::Binding::Resource { group, binding }) => { - if group > MAX_BIND_GROUPS || binding > MAX_BIND_INDICES { - return Err(GlobalVariableError::OutOfRangeBinding); - } - } - Some(crate::Binding::Location(_)) | None => { - return Err(GlobalVariableError::InvalidBinding) - } - } - if var.interpolation.is_some() { - return Err(GlobalVariableError::InvalidInterpolation); - } - //TODO: prevent `Uniform` storage class with `STORE` access + crate::StorageClass::Storage => { + var.check_resource()?; + crate::StorageAccess::all() + } + crate::StorageClass::Uniform => { + var.check_resource()?; + crate::StorageAccess::empty() + } + crate::StorageClass::Handle => { + var.check_resource()?; match types[var.ty].inner { - crate::TypeInner::Struct { .. } - | crate::TypeInner::Image { + crate::TypeInner::Image { class: crate::ImageClass::Storage(_), .. - } => true, - _ => false, + } => crate::StorageAccess::all(), + _ => crate::StorageAccess::empty(), } } crate::StorageClass::Private | crate::StorageClass::WorkGroup => { if var.binding.is_some() { return Err(GlobalVariableError::InvalidBinding); } - if var.interpolation.is_some() { - return Err(GlobalVariableError::InvalidInterpolation); - } - false + var.forbid_interpolation()?; + crate::StorageAccess::empty() + } + crate::StorageClass::PushConstant => { + //TODO + return Err(GlobalVariableError::InvalidStorageAccess { + allowed: crate::StorageAccess::empty(), + seen: crate::StorageAccess::empty(), + }); } }; - if !is_storage && !var.storage_access.is_empty() { - return Err(GlobalVariableError::InvalidStorageAccess); + if !allowed_storage_access.contains(var.storage_access) { + return Err(GlobalVariableError::InvalidStorageAccess { + allowed: allowed_storage_access, + seen: var.storage_access, + }); } Ok(()) @@ -291,26 +328,19 @@ impl Validator { location_out_mask |= mask; crate::GlobalUse::LOAD | crate::GlobalUse::STORE } - crate::StorageClass::Constant => crate::GlobalUse::LOAD, - crate::StorageClass::Uniform | crate::StorageClass::StorageBuffer => { - //TODO: built-in checks? - let mut storage_usage = crate::GlobalUse::empty(); - if var.storage_access.contains(crate::StorageAccess::LOAD) { - storage_usage |= crate::GlobalUse::LOAD; - } - if var.storage_access.contains(crate::StorageAccess::STORE) { - storage_usage |= crate::GlobalUse::STORE; - } - if storage_usage.is_empty() { - // its a uniform buffer - crate::GlobalUse::LOAD - } else { - storage_usage - } - } + crate::StorageClass::Uniform => crate::GlobalUse::LOAD, + crate::StorageClass::Storage => storage_usage(var.storage_access), + crate::StorageClass::Handle => match module.types[var.ty].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Storage(_), + .. + } => storage_usage(var.storage_access), + _ => crate::GlobalUse::LOAD, + }, crate::StorageClass::Private | crate::StorageClass::WorkGroup => { crate::GlobalUse::all() } + crate::StorageClass::PushConstant => crate::GlobalUse::LOAD, }; if !allowed_usage.contains(usage) { log::warn!("\tUsage error for: {:?}", var); @@ -384,7 +414,11 @@ impl Validator { for (var_handle, var) in module.global_variables.iter() { self.validate_global_var(var, &module.types) - .map_err(|e| ValidationError::GlobalVariable(var_handle, e))?; + .map_err(|error| ValidationError::GlobalVariable { + handle: var_handle, + name: var.name.clone().unwrap_or_default(), + error, + })?; } for (fun_handle, fun) in module.functions.iter() { diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl index 5df5e6061..9bc98052e 100644 --- a/test-data/boids.wgsl +++ b/test-data/boids.wgsl @@ -61,8 +61,8 @@ type Particles = struct { }; [[group(0), binding(0)]] var params : SimParams; -[[group(0), binding(1)]] var particlesA : Particles; -[[group(0), binding(2)]] var particlesB : Particles; +[[group(0), binding(1)]] var particlesA : Particles; +[[group(0), binding(2)]] var particlesB : Particles; [[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3; diff --git a/test-data/quad.wgsl b/test-data/quad.wgsl index 3e56d317f..16cbd2698 100644 --- a/test-data/quad.wgsl +++ b/test-data/quad.wgsl @@ -14,8 +14,8 @@ fn main() -> void { # fragment [[location(0)]] var v_uv : vec2; -[[group(0), binding(0)]] var u_texture : texture_sampled_2d; -[[group(0), binding(1)]] var u_sampler : sampler; +[[group(0), binding(0)]] var u_texture : texture_sampled_2d; +[[group(0), binding(1)]] var u_sampler : sampler; [[location(0)]] var o_color : vec4; [[stage(fragment)]] From 587dc01a2cc43fdf4637f1bf6d2b75b703e9f681 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 28 Oct 2020 00:30:22 -0400 Subject: [PATCH 0248/2212] [msl] refactor the options, add override stages --- examples/convert.rs | 19 ++++++++++++++++-- src/back/msl.rs | 42 +++++++++++++++++++++++++++------------ src/lib.rs | 34 +++++++++++++++---------------- test-data/boids.param.ron | 6 +++--- test-data/quad.param.ron | 4 ++-- tests/convert.rs | 28 +++++++++++++++++++------- 6 files changed, 89 insertions(+), 44 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index a8160c14c..7f72548a5 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -1,8 +1,16 @@ use serde::{Deserialize, Serialize}; use std::{env, fs, path::Path}; +#[derive(Hash, PartialEq, Eq, Serialize, Deserialize)] +enum Stage { + Vertex, + Fragment, + Compute, +} + #[derive(Hash, PartialEq, Eq, Serialize, Deserialize)] struct BindSource { + stage: Stage, group: u32, binding: u32, } @@ -120,6 +128,11 @@ fn main() { for (key, value) in params.metal_bindings { binding_map.insert( msl::BindSource { + stage: match key.stage { + Stage::Vertex => naga::ShaderStage::Vertex, + Stage::Fragment => naga::ShaderStage::Fragment, + Stage::Compute => naga::ShaderStage::Compute, + }, group: key.group, binding: key.binding, }, @@ -132,9 +145,11 @@ fn main() { ); } let options = msl::Options { - binding_map: &binding_map, + lang_version: (1, 0), + spirv_cross_compatibility: false, + binding_map, }; - let msl = msl::write_string(&module, options).unwrap(); + let msl = msl::write_string(&module, &options).unwrap(); fs::write(&args[2], msl).unwrap(); } #[cfg(feature = "spv-out")] diff --git a/src/back/msl.rs b/src/back/msl.rs index 007fa85ae..c14be2f8f 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -31,6 +31,7 @@ pub struct BindTarget { #[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub struct BindSource { + pub stage: crate::ShaderStage, pub group: u32, pub binding: u32, } @@ -102,14 +103,20 @@ enum LocationMode { Uniform, } -#[derive(Debug, Clone, Copy)] -pub struct Options<'a> { - pub binding_map: &'a BindingMap, +#[derive(Debug, Default, Clone)] +pub struct Options { + /// (Major, Minor) target version of the Metal Shading Language. + pub lang_version: (u8, u8), + /// Make it possible to link different stages via SPIRV-Cross. + pub spirv_cross_compatibility: bool, + /// Binding model mapping to Metal. + pub binding_map: BindingMap, } -impl Options<'_> { +impl Options { fn resolve_binding( - self, + &self, + stage: crate::ShaderStage, binding: &crate::Binding, mode: LocationMode, ) -> Result { @@ -119,13 +126,21 @@ impl Options<'_> { LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(index)), LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(index)), LocationMode::Intermediate => Ok(ResolvedBinding::User { - prefix: "loc", + prefix: if self.spirv_cross_compatibility { + "locn" + } else { + "loc" + }, index, }), LocationMode::Uniform => Err(Error::UnexpectedLocation), }, crate::Binding::Resource { group, binding } => { - let source = BindSource { group, binding }; + let source = BindSource { + stage, + group, + binding, + }; self.binding_map .get(&source) .cloned() @@ -790,7 +805,7 @@ impl Writer { Ok(()) } - pub fn write(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { + pub fn write(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; writeln!(self.out, "using namespace metal;")?; @@ -937,7 +952,7 @@ impl Writer { Ok(()) } - fn write_functions(&mut self, module: &crate::Module, options: Options) -> Result<(), Error> { + fn write_functions(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { for (fun_handle, fun) in module.functions.iter() { self.typifier.resolve_all( &fun.expressions, @@ -1081,7 +1096,7 @@ impl Writer { handle, usage: crate::GlobalUse::empty(), }; - let resolved = options.resolve_binding(binding, in_mode)?; + let resolved = options.resolve_binding(stage, binding, in_mode)?; write!(self.out, "\t")?; tyvar.try_fmt(&mut self.out)?; @@ -1128,7 +1143,7 @@ impl Writer { write!(self.out, "\t")?; tyvar.try_fmt(&mut self.out)?; if let Some(ref binding) = var.binding { - let resolved = options.resolve_binding(binding, out_mode)?; + let resolved = options.resolve_binding(stage, binding, out_mode)?; resolved.try_fmt_decorated(&mut self.out, "")?; } writeln!(self.out, ";")?; @@ -1172,7 +1187,8 @@ impl Writer { } _ => LocationMode::Uniform, }; - let resolved = options.resolve_binding(var.binding.as_ref().unwrap(), loc_mode)?; + let resolved = + options.resolve_binding(stage, var.binding.as_ref().unwrap(), loc_mode)?; let tyvar = TypedGlobalVariable { module, handle, @@ -1214,7 +1230,7 @@ impl Writer { } } -pub fn write_string(module: &crate::Module, options: Options) -> Result { +pub fn write_string(module: &crate::Module, options: &Options) -> Result { let mut w = Writer { out: String::new(), typifier: Typifier::new(), diff --git a/src/lib.rs b/src/lib.rs index 63ca33f9a..c8c1b0107 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -61,7 +61,7 @@ pub struct Header { /// For more, see: /// - https://www.khronos.org/opengl/wiki/Early_Fragment_Test#Explicit_specification /// - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-earlydepthstencil -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct EarlyDepthTest { @@ -77,7 +77,7 @@ pub struct EarlyDepthTest { /// For more, see: /// - https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_conservative_depth.txt /// - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics#system-value-semantics -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ConservativeDepth { @@ -92,7 +92,7 @@ pub enum ConservativeDepth { } /// Stage of the programmable pipeline. -#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[allow(missing_docs)] // The names are self evident @@ -103,7 +103,7 @@ pub enum ShaderStage { } /// Class of storage for variables. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[allow(missing_docs)] // The names are self evident @@ -129,7 +129,7 @@ pub enum StorageClass { } /// Built-in inputs and outputs. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum BuiltIn { @@ -158,7 +158,7 @@ pub type Bytes = u8; /// Number of components in a vector. #[repr(u8)] -#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum VectorSize { @@ -172,7 +172,7 @@ pub enum VectorSize { /// Primitive type for a scalar. #[repr(u8)] -#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ScalarKind { @@ -188,7 +188,7 @@ pub enum ScalarKind { /// Size of an array. #[repr(u8)] -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ArraySize { @@ -199,7 +199,7 @@ pub enum ArraySize { } /// Describes where a struct member is placed. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum MemberOrigin { @@ -212,7 +212,7 @@ pub enum MemberOrigin { } /// The interpolation qualifier of a binding or struct field. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Interpolation { @@ -247,7 +247,7 @@ pub struct StructMember { } /// The number of dimensions an image has. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ImageDimension { @@ -274,7 +274,7 @@ bitflags::bitflags! { } // Storage image format. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum StorageFormat { @@ -324,7 +324,7 @@ pub enum StorageFormat { } /// Sub-class of the image type. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ImageClass { @@ -479,7 +479,7 @@ pub struct LocalVariable { } /// Operation that can be applied on a single value. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum UnaryOperator { @@ -488,7 +488,7 @@ pub enum UnaryOperator { } /// Operation that can be applied on two values. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum BinaryOperator { @@ -514,7 +514,7 @@ pub enum BinaryOperator { } /// Built-in shader function. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum IntrinsicFunction { @@ -527,7 +527,7 @@ pub enum IntrinsicFunction { } /// Axis on which to compute a derivative. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum DerivativeAxis { diff --git a/test-data/boids.param.ron b/test-data/boids.param.ron index 4f5503c1c..32fe7e8e3 100644 --- a/test-data/boids.param.ron +++ b/test-data/boids.param.ron @@ -1,7 +1,7 @@ ( metal_bindings: { - (group: 0, binding: 0): (buffer: Some(0), mutable: false), - (group: 0, binding: 1): (buffer: Some(1), mutable: true), - (group: 0, binding: 2): (buffer: Some(2), mutable: true), + (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: false), + (stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true), + (stage: Compute, group: 0, binding: 2): (buffer: Some(2), mutable: true), } ) diff --git a/test-data/quad.param.ron b/test-data/quad.param.ron index cd26cc9e8..c4245bd18 100644 --- a/test-data/quad.param.ron +++ b/test-data/quad.param.ron @@ -1,6 +1,6 @@ ( metal_bindings: { - (group: 0, binding: 0): (texture: Some(0)), - (group: 0, binding: 1): (sampler: Some(0)), + (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), + (stage: Fragment, group: 0, binding: 1): (sampler: Some(0)), } ) diff --git a/tests/convert.rs b/tests/convert.rs index 99c0e8b0d..50ed7288d 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -34,6 +34,7 @@ fn convert_quad() { let mut binding_map = msl::BindingMap::default(); binding_map.insert( msl::BindSource { + stage: naga::ShaderStage::Fragment, group: 0, binding: 0, }, @@ -46,6 +47,7 @@ fn convert_quad() { ); binding_map.insert( msl::BindSource { + stage: naga::ShaderStage::Fragment, group: 0, binding: 1, }, @@ -57,9 +59,11 @@ fn convert_quad() { }, ); let options = msl::Options { - binding_map: &binding_map, + lang_version: (1, 0), + spirv_cross_compatibility: false, + binding_map, }; - msl::write_string(&module, options).unwrap(); + msl::write_string(&module, &options).unwrap(); } } @@ -74,6 +78,7 @@ fn convert_boids() { let mut binding_map = msl::BindingMap::default(); binding_map.insert( msl::BindSource { + stage: naga::ShaderStage::Compute, group: 0, binding: 0, }, @@ -86,6 +91,7 @@ fn convert_boids() { ); binding_map.insert( msl::BindSource { + stage: naga::ShaderStage::Compute, group: 0, binding: 1, }, @@ -98,6 +104,7 @@ fn convert_boids() { ); binding_map.insert( msl::BindSource { + stage: naga::ShaderStage::Compute, group: 0, binding: 2, }, @@ -109,9 +116,11 @@ fn convert_boids() { }, ); let options = msl::Options { - binding_map: &binding_map, + lang_version: (1, 0), + spirv_cross_compatibility: false, + binding_map, }; - msl::write_string(&module, options).unwrap(); + msl::write_string(&module, &options).unwrap(); } } @@ -129,6 +138,7 @@ fn convert_cube() { let mut binding_map = msl::BindingMap::default(); binding_map.insert( msl::BindSource { + stage: naga::ShaderStage::Vertex, group: 0, binding: 0, }, @@ -141,6 +151,7 @@ fn convert_cube() { ); binding_map.insert( msl::BindSource { + stage: naga::ShaderStage::Fragment, group: 0, binding: 1, }, @@ -153,6 +164,7 @@ fn convert_cube() { ); binding_map.insert( msl::BindSource { + stage: naga::ShaderStage::Fragment, group: 0, binding: 2, }, @@ -164,10 +176,12 @@ fn convert_cube() { }, ); let options = msl::Options { - binding_map: &binding_map, + lang_version: (1, 0), + spirv_cross_compatibility: false, + binding_map, }; - msl::write_string(&vs, options).unwrap(); - msl::write_string(&fs, options).unwrap(); + msl::write_string(&vs, &options).unwrap(); + msl::write_string(&fs, &options).unwrap(); } } From 4b43e282fcdbfe1420c77978a916b7bc86256dbd Mon Sep 17 00:00:00 2001 From: Matus Talcik Date: Thu, 29 Oct 2020 15:43:12 +0100 Subject: [PATCH 0249/2212] spv-in: fix flowgraph (#247) Header blocks were incorrectly overwritten. format --- src/front/spv/flow.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 526ec1ac7..a1c746701 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -152,6 +152,12 @@ impl FlowGraph { let (node_source_index, node_target_index) = self.flow.edge_endpoints(edge_index).unwrap(); + if self.flow[node_source_index].ty == Some(ControlFlowNodeType::Header) + || self.flow[node_source_index].ty == Some(ControlFlowNodeType::Loop) + { + continue; + } + // Back if self.flow[node_target_index].ty == Some(ControlFlowNodeType::Loop) && self.flow[node_source_index].id > self.flow[node_target_index].id From 529225ce4c353825e3cd1f684797b965f2100462 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 30 Oct 2020 16:44:59 -0400 Subject: [PATCH 0250/2212] Option to dump spirv flow graphs (#249) --- .gitignore | 4 ++++ examples/convert.rs | 29 +++++++++++++++++++++-------- src/front/spv/flow.rs | 20 ++++++++++++-------- src/front/spv/function.rs | 11 +++++++++++ src/front/spv/mod.rs | 17 ++++++++++++----- src/front/spv/rosetta.rs | 2 +- test-data/boids.param.ron | 1 + tests/convert.rs | 2 +- 8 files changed, 63 insertions(+), 23 deletions(-) diff --git a/.gitignore b/.gitignore index 743f7ed7c..798a1af6c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,7 @@ Cargo.lock .DS_Store .idea +/*.dot +/*.metal +/*.metallib +/*.ron diff --git a/examples/convert.rs b/examples/convert.rs index 7f72548a5..b75b48c82 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -29,6 +29,8 @@ struct BindTarget { #[derive(Default, Serialize, Deserialize)] struct Parameters { + #[serde(default)] + spv_flow_dump_prefix: String, metal_bindings: naga::FastHashMap, } @@ -41,6 +43,13 @@ fn main() { println!("Call with "); return; } + + let param_path = std::path::PathBuf::from(&args[1]).with_extension("param.ron"); + let params = match fs::read_to_string(param_path) { + Ok(string) => ron::de::from_str(&string).unwrap(), + Err(_) => Parameters::default(), + }; + let module = match Path::new(&args[1]) .extension() .expect("Input has no extension?") @@ -49,8 +58,15 @@ fn main() { { #[cfg(feature = "spv-in")] "spv" => { + let options = naga::front::spv::Options { + flow_graph_dump_prefix: if params.spv_flow_dump_prefix.is_empty() { + None + } else { + Some(params.spv_flow_dump_prefix.into()) + }, + }; let input = fs::read(&args[1]).unwrap(); - naga::front::spv::parse_u8_slice(&input).unwrap() + naga::front::spv::parse_u8_slice(&input, &options).unwrap() } #[cfg(feature = "wgsl-in")] "wgsl" => { @@ -109,12 +125,6 @@ fn main() { return; } - let param_path = std::path::PathBuf::from(&args[1]).with_extension("param.ron"); - let params = match fs::read_to_string(param_path) { - Ok(string) => ron::de::from_str(&string).unwrap(), - Err(_) => Parameters::default(), - }; - match Path::new(&args[2]) .extension() .expect("Output has no extension?") @@ -231,7 +241,10 @@ fn main() { } other => { let _ = params; - panic!("Unknown output extension: {}", other); + panic!( + "Unknown output extension: {}, forgot to enable a feature?", + other + ); } } } diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index a1c746701..8f3bb0dc3 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -225,10 +225,8 @@ impl FlowGraph { node_index: BlockNodeIndex, stop_node_index: Option, ) -> Result { - if let Some(stop_node_index) = stop_node_index { - if stop_node_index == node_index { - return Ok(vec![]); - } + if stop_node_index == Some(node_index) { + return Ok(vec![]); } let node = &self.flow[node_index]; @@ -329,7 +327,7 @@ impl FlowGraph { self.flow[continue_edge.target()].block.clone() }; - let mut body: crate::Block = node.block.clone(); + let mut body = node.block.clone(); match node.terminator { Terminator::BranchConditional { condition, @@ -407,7 +405,7 @@ impl FlowGraph { pub(super) fn to_graphviz(&self) -> Result { let mut output = String::new(); - output += "digraph ControlFlowGraph {"; + output += "digraph ControlFlowGraph {\n"; for node_index in self.flow.node_indices() { let node = &self.flow[node_index]; @@ -425,10 +423,16 @@ impl FlowGraph { let target = edge.target(); let style = match edge.weight { + ControlFlowEdgeType::Forward => "", + ControlFlowEdgeType::ForwardMerge => "style=dotted", + ControlFlowEdgeType::ForwardContinue => "color=green", + ControlFlowEdgeType::Back => "style=dashed", + ControlFlowEdgeType::LoopBreak => "color=yellow", + ControlFlowEdgeType::LoopContinue => "color=green", ControlFlowEdgeType::IfTrue => "color=blue", ControlFlowEdgeType::IfFalse => "color=red", - ControlFlowEdgeType::ForwardMerge => "style=dotted", - _ => "", + ControlFlowEdgeType::SwitchBreak => "color=yellow", + ControlFlowEdgeType::CaseFallThrough => "style=dotted", }; writeln!( diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 335e1a33e..eed33ddfe 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -175,6 +175,17 @@ impl> super::Parser { } }; + if let Some(ref prefix) = self.options.flow_graph_dump_prefix { + let dump = flow_graph.to_graphviz().unwrap_or_default(); + let suffix = match source { + DeferredSource::EntryPoint(stage, ref name) => { + format!("flow.{:?}-{}.dot", stage, name) + } + DeferredSource::Function(handle) => format!("flow.Fun-{}.dot", handle.index()), + }; + let _ = std::fs::write(prefix.join(suffix), dump); + } + for (expr_handle, dst_id) in local_function_calls { self.deferred_function_calls.push(DeferredFunctionCall { source: source.clone(), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 61dc3d5fd..3c99fc2af 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -29,7 +29,7 @@ use crate::{ }; use num_traits::cast::FromPrimitive; -use std::{convert::TryInto, num::NonZeroU32}; +use std::{convert::TryInto, num::NonZeroU32, path::PathBuf}; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, @@ -304,6 +304,11 @@ pub struct Assignment { value: Handle, } +#[derive(Clone, Debug, Default)] +pub struct Options { + pub flow_graph_dump_prefix: Option, +} + pub struct Parser { data: I, state: ModuleState, @@ -325,10 +330,11 @@ pub struct Parser { lookup_function: FastHashMap>, lookup_entry_point: FastHashMap, deferred_function_calls: Vec, + options: Options, } impl> Parser { - pub fn new(data: I) -> Self { + pub fn new(data: I, options: &Options) -> Self { Parser { data, state: ModuleState::Empty, @@ -349,6 +355,7 @@ impl> Parser { lookup_function: FastHashMap::default(), lookup_entry_point: FastHashMap::default(), deferred_function_calls: Vec::new(), + options: options.clone(), } } @@ -2346,7 +2353,7 @@ impl> Parser { } } -pub fn parse_u8_slice(data: &[u8]) -> Result { +pub fn parse_u8_slice(data: &[u8], options: &Options) -> Result { if data.len() % 4 != 0 { return Err(Error::IncompleteData); } @@ -2354,7 +2361,7 @@ pub fn parse_u8_slice(data: &[u8]) -> Result { let words = data .chunks(4) .map(|c| u32::from_le_bytes(c.try_into().unwrap())); - Parser::new(words).parse() + Parser::new(words, options).parse() } #[cfg(test)] @@ -2370,6 +2377,6 @@ mod test { 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, // GLSL450. 0x01, 0x00, 0x00, 0x00, ]; - let _ = super::parse_u8_slice(&bin).unwrap(); + let _ = super::parse_u8_slice(&bin, &Default::default()).unwrap(); } } diff --git a/src/front/spv/rosetta.rs b/src/front/spv/rosetta.rs index c787e7646..027c0d0ad 100644 --- a/src/front/spv/rosetta.rs +++ b/src/front/spv/rosetta.rs @@ -9,7 +9,7 @@ fn rosetta_test(file_name: &str) { let file_path = Path::new(TEST_PATH).join(file_name); let input = fs::read(&file_path).unwrap(); - let module = super::parse_u8_slice(&input).unwrap(); + let module = super::parse_u8_slice(&input, &Default::default()).unwrap(); let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); let expected = fs::read_to_string(file_path.with_extension("expected.ron")).unwrap(); diff --git a/test-data/boids.param.ron b/test-data/boids.param.ron index 32fe7e8e3..4de90960b 100644 --- a/test-data/boids.param.ron +++ b/test-data/boids.param.ron @@ -1,4 +1,5 @@ ( + spv_flow_dump_prefix: "", metal_bindings: { (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: false), (stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true), diff --git a/tests/convert.rs b/tests/convert.rs index 50ed7288d..238bb405f 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -14,7 +14,7 @@ fn load_wgsl(name: &str) -> naga::Module { fn load_spv(name: &str) -> naga::Module { let path = format!("{}/test-data/spv/{}", env!("CARGO_MANIFEST_DIR"), name); let input = std::fs::read(path).unwrap(); - naga::front::spv::parse_u8_slice(&input).unwrap() + naga::front::spv::parse_u8_slice(&input, &Default::default()).unwrap() } #[cfg(feature = "glsl-in")] From d45d11e4c5f1cbef191037e3d903a6c3f46668ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 30 Oct 2020 20:51:50 +0000 Subject: [PATCH 0251/2212] msl-out: Use io::Write instead of fmt::Write (#250) * msl-out: Use io::Write instead of fmt::Write * msl-out: merge std use --- src/back/msl.rs | 69 +++++++++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 31 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index c14be2f8f..45d2bd4d9 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -19,7 +19,11 @@ use crate::{ proc::{ResolveContext, ResolveError, Typifier}, FastHashMap, }; -use std::fmt::{Display, Error as FmtError, Formatter, Write}; +use std::{ + fmt::{Display, Error as FmtError, Formatter}, + io::{Error as IoError, Write}, + string::FromUtf8Error, +}; #[derive(Clone, Debug, Default, PartialEq)] pub struct BindTarget { @@ -62,7 +66,8 @@ impl Display for Level { #[derive(Debug)] pub enum Error { - Format(FmtError), + IO(IoError), + Utf8(FromUtf8Error), Type(ResolveError), UnexpectedLocation, MissingBinding(Handle), @@ -83,9 +88,15 @@ pub enum Error { Validation, } -impl From for Error { - fn from(e: FmtError) -> Self { - Error::Format(e) +impl From for Error { + fn from(e: IoError) -> Self { + Error::IO(e) + } +} + +impl From for Error { + fn from(e: FromUtf8Error) -> Self { + Error::Utf8(e) } } @@ -261,7 +272,7 @@ struct TypedGlobalVariable<'a> { } impl<'a> TypedGlobalVariable<'a> { - fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { + fn try_fmt(&self, out: &mut W) -> Result<(), Error> { let var = &self.module.global_variables[self.handle]; let name = var.name.or_index(self.handle); let ty = &self.module.types[var.ty]; @@ -282,7 +293,7 @@ impl<'a> TypedGlobalVariable<'a> { _ => ("", ""), }; Ok(write!( - formatter, + out, "{}{}{} {}", space_qualifier, ty_name, reference, name )?) @@ -290,7 +301,7 @@ impl<'a> TypedGlobalVariable<'a> { } impl ResolvedBinding { - fn try_fmt(&self, formatter: &mut W) -> Result<(), Error> { + fn try_fmt(&self, out: &mut W) -> Result<(), Error> { match *self { ResolvedBinding::BuiltIn(built_in) => { use crate::BuiltIn as Bi; @@ -314,20 +325,20 @@ impl ResolvedBinding { Bi::LocalInvocationIndex => "thread_index_in_threadgroup", Bi::WorkGroupId => "threadgroup_position_in_grid", }; - Ok(formatter.write_str(name)?) + Ok(write!(out, "{}", name)?) } - ResolvedBinding::Attribute(index) => Ok(write!(formatter, "attribute({})", index)?), - ResolvedBinding::Color(index) => Ok(write!(formatter, "color({})", index)?), + ResolvedBinding::Attribute(index) => Ok(write!(out, "attribute({})", index)?), + ResolvedBinding::Color(index) => Ok(write!(out, "color({})", index)?), ResolvedBinding::User { prefix, index } => { - Ok(write!(formatter, "user({}{})", prefix, index)?) + Ok(write!(out, "user({}{})", prefix, index)?) } ResolvedBinding::Resource(ref target) => { if let Some(id) = target.buffer { - Ok(write!(formatter, "buffer({})", id)?) + Ok(write!(out, "buffer({})", id)?) } else if let Some(id) = target.texture { - Ok(write!(formatter, "texture({})", id)?) + Ok(write!(out, "texture({})", id)?) } else if let Some(id) = target.sampler { - Ok(write!(formatter, "sampler({})", id)?) + Ok(write!(out, "sampler({})", id)?) } else { Err(Error::UnimplementedBindTarget(target.clone())) } @@ -335,15 +346,11 @@ impl ResolvedBinding { } } - fn try_fmt_decorated( - &self, - formatter: &mut W, - terminator: &str, - ) -> Result<(), Error> { - formatter.write_str(" [[")?; - self.try_fmt(formatter)?; - formatter.write_str("]]")?; - formatter.write_str(terminator)?; + fn try_fmt_decorated(&self, out: &mut W, terminator: &str) -> Result<(), Error> { + write!(out, " [[")?; + self.try_fmt(out)?; + write!(out, "]]")?; + write!(out, "{}", terminator)?; Ok(()) } } @@ -420,9 +427,9 @@ impl Writer { match *expression { crate::Expression::Access { base, index } => { self.put_expression(base, function, module)?; - self.out.write_str("[")?; + write!(self.out, "[")?; self.put_expression(index, function, module)?; - self.out.write_str("]")?; + write!(self.out, "]")?; } crate::Expression::AccessIndex { base, index } => { self.put_expression(base, function, module)?; @@ -686,7 +693,7 @@ impl Writer { crate::ConstantInner::Float(value) => { write!(self.out, "{}", value)?; if value.fract() == 0.0 { - self.out.write_str(".0")?; + write!(self.out, ".0")?; } } crate::ConstantInner::Bool(value) => { @@ -782,7 +789,7 @@ impl Writer { crate::Statement::Return { value } => { write!(self.out, "{}return ", level)?; match value { - None => self.out.write_str(OUTPUT_STRUCT_NAME)?, + None => write!(self.out, "{}", OUTPUT_STRUCT_NAME)?, Some(expr_handle) => { self.put_expression(expr_handle, function, module)?; } @@ -819,7 +826,7 @@ impl Writer { Ok(()) } - fn write_type_defs<'a>(&mut self, module: &'a crate::Module) -> Result<(), Error> { + fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { for (handle, ty) in module.types.iter() { let name = ty.name.or_index(handle); match ty.inner { @@ -1232,9 +1239,9 @@ impl Writer { pub fn write_string(module: &crate::Module, options: &Options) -> Result { let mut w = Writer { - out: String::new(), + out: Vec::new(), typifier: Typifier::new(), }; w.write(module, options)?; - Ok(w.out) + Ok(String::from_utf8(w.out)?) } From 871139431adec09fd23d3ae8fa067c63da76f7a5 Mon Sep 17 00:00:00 2001 From: Matus Talcik Date: Sat, 31 Oct 2020 01:58:29 +0100 Subject: [PATCH 0252/2212] spv-in: fix while loop traverse (#253) --- src/front/spv/error.rs | 1 + src/front/spv/flow.rs | 40 ++++++++++++++++++++++++++++++++-------- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index cf9c59f2c..5cc624970 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -51,5 +51,6 @@ pub enum Error { BadString, IncompleteData, InvalidTerminator, + InvalidEdgeClassification, UnexpectedComparisonType(Handle), } diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 8f3bb0dc3..62c3866c4 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -346,7 +346,10 @@ impl FlowGraph { _ => return Err(Error::InvalidTerminator), }; - Ok(vec![crate::Statement::Loop { body, continuing }]) + let mut result = vec![crate::Statement::Loop { body, continuing }]; + result.extend(self.naga_traverse(merge_node_index, None)?); + + Ok(result) } Some(ControlFlowNodeType::Break) => { let mut result = node.block.clone(); @@ -355,13 +358,34 @@ impl FlowGraph { condition, true_id, false_id, - } => result.push(crate::Statement::If { - condition, - accept: self - .naga_traverse(self.block_to_node[&true_id], stop_node_index)?, - reject: self - .naga_traverse(self.block_to_node[&false_id], stop_node_index)?, - }), + } => { + let true_node_id = self.block_to_node[&true_id]; + let false_node_id = self.block_to_node[&false_id]; + + let true_edge = + self.flow[self.flow.find_edge(node_index, true_node_id).unwrap()]; + let false_edge = + self.flow[self.flow.find_edge(node_index, false_node_id).unwrap()]; + + if true_edge == ControlFlowEdgeType::LoopBreak { + result.push(crate::Statement::If { + condition, + accept: vec![crate::Statement::Break], + reject: self.naga_traverse(false_node_id, stop_node_index)?, + }); + } else if false_edge == ControlFlowEdgeType::LoopBreak { + result.push(crate::Statement::If { + condition, + accept: self.naga_traverse(true_node_id, stop_node_index)?, + reject: vec![crate::Statement::Break], + }); + } else { + return Err(Error::InvalidEdgeClassification); + } + } + Terminator::Branch { .. } => { + result.push(crate::Statement::Break); + } _ => return Err(Error::InvalidTerminator), }; Ok(result) From 80bdd23fd4e781f5dc72fee09388a5489e171137 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 30 Oct 2020 21:25:55 -0400 Subject: [PATCH 0253/2212] Add scalar_kind() accessor to IR Type (#251) --- src/arena.rs | 7 ++----- src/front/spv/mod.rs | 17 ++++++++--------- src/proc/mod.rs | 12 ++++++++++++ src/proc/validator.rs | 15 +++++---------- 4 files changed, 27 insertions(+), 24 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 1727da30d..58c65997d 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -1,11 +1,8 @@ use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32}; /// An unique index in the arena array that a handle points to. -/// -/// This type is independent of `spv::Word`. `spv::Word` is used in data -/// representation. It holds a SPIR-V and refers to that instruction. In -/// structured representation, we use Handle to refer to an SPIR-V instruction. -/// `Index` is an implementation detail to `Handle`. +/// The "non-zero" part ensures that an `Option>` has +/// the same size and representation as `Handle`. type Index = NonZeroU32; /// A strongly typed reference to a SPIR-V element. diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3c99fc2af..b59fd239b 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1131,11 +1131,10 @@ impl> Parser { let value_lexp = self.lookup_expression.lookup(value_id)?; let ty_lookup = self.lookup_type.lookup(result_type_id)?; - let kind = match type_arena[ty_lookup.handle].inner { - crate::TypeInner::Scalar { kind, .. } - | crate::TypeInner::Vector { kind, .. } => kind, - _ => return Err(Error::InvalidAsType(ty_lookup.handle)), - }; + let kind = type_arena[ty_lookup.handle] + .inner + .scalar_kind() + .ok_or(Error::InvalidAsType(ty_lookup.handle))?; let expr = crate::Expression::As { expr: value_lexp.handle, @@ -2071,10 +2070,10 @@ impl> Parser { let format = self.next()?; let base_handle = self.lookup_type.lookup(sample_type_id)?.handle; - let kind = match module.types[base_handle].inner { - crate::TypeInner::Scalar { kind, .. } | crate::TypeInner::Vector { kind, .. } => kind, - _ => return Err(Error::InvalidImageBaseType(base_handle)), - }; + let kind = module.types[base_handle] + .inner + .scalar_kind() + .ok_or(Error::InvalidImageBaseType(base_handle))?; let class = if format != 0 { crate::ImageClass::Storage(map_image_format(format)?) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index cb21c042c..65ee3a6be 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -47,3 +47,15 @@ impl From for super::ScalarKind { } } } + +impl crate::TypeInner { + pub fn scalar_kind(&self) -> Option { + match *self { + super::TypeInner::Scalar { kind, .. } | super::TypeInner::Vector { kind, .. } => { + Some(kind) + } + super::TypeInner::Matrix { .. } => Some(super::ScalarKind::Float), + _ => None, + } + } +} diff --git a/src/proc/validator.rs b/src/proc/validator.rs index bfb2858c6..de37ec576 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -263,17 +263,12 @@ impl Validator { match (stage, var.class) { (crate::ShaderStage::Vertex, crate::StorageClass::Output) | (crate::ShaderStage::Fragment, crate::StorageClass::Input) => { - match module.types[var.ty].inner { - crate::TypeInner::Scalar { kind, .. } - | crate::TypeInner::Vector { kind, .. } => { - if kind != crate::ScalarKind::Float - && var.interpolation != Some(crate::Interpolation::Flat) - { - return Err(EntryPointError::InvalidIntegerInterpolation); - } + match module.types[var.ty].inner.scalar_kind() { + Some(crate::ScalarKind::Float) => {} + Some(_) if var.interpolation != Some(crate::Interpolation::Flat) => { + return Err(EntryPointError::InvalidIntegerInterpolation); } - crate::TypeInner::Matrix { .. } => {} - _ => unreachable!(), + _ => {} } } _ => {} From 3b8b7e28dd5a53723a5417dd00200c73dabd2e9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristoffer=20S=C3=B8holm?= Date: Fri, 30 Oct 2020 14:45:00 +0100 Subject: [PATCH 0254/2212] [glsl-in] Add selection statements i.e. if-else and switch-case --- src/front/glsl/lex.rs | 6 +++ src/front/glsl/parser.rs | 72 ++++++++++++++++++++++++++++++---- src/front/glsl/parser_tests.rs | 67 +++++++++++++++++++++++++++++++ 3 files changed, 138 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 236faef42..1055a6b0f 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -140,6 +140,12 @@ impl<'a> Lexer<'a> { "break" => Some(Token::Break(meta)), "return" => Some(Token::Return(meta)), "discard" => Some(Token::Discard(meta)), + // selection statements + "if" => Some(Token::If(meta)), + "else" => Some(Token::Else(meta)), + "switch" => Some(Token::Switch(meta)), + "case" => Some(Token::Case(meta)), + "default" => Some(Token::Default(meta)), // types "void" => Some(Token::Void(meta)), word => { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0ec67099e..a29a90138 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -6,7 +6,7 @@ pomelo! { %include { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{proc::Typifier, Arena, BinaryOperator, Binding, Block, Constant, - ConstantInner, EntryPoint, Expression, Function, GlobalVariable, Handle, Interpolation, + ConstantInner, EntryPoint, Expression, FallThrough, FastHashMap, Function, GlobalVariable, Handle, Interpolation, LocalVariable, MemberOrigin, ScalarKind, Statement, StorageAccess, StorageClass, StructMember, Type, TypeInner}; } @@ -55,6 +55,9 @@ pomelo! { %type expression_statement Statement; %type declaration_statement Statement; %type jump_statement Statement; + %type selection_statement Statement; + %type switch_statement_list Vec<(Option, Block, Option)>; + %type switch_statement (Option, Block, Option); // expressions %type unary_expression ExpressionRule; @@ -90,7 +93,7 @@ pomelo! { %type initializer ExpressionRule; - // decalartions + // declarations %type declaration VarDeclaration; %type init_declarator_list VarDeclaration; %type single_declaration VarDeclaration; @@ -115,6 +118,9 @@ pomelo! { %type TypeName Type; + // precedence + %right Else; + root ::= version_pragma translation_unit; version_pragma ::= Version IntConstant(V) Identifier?(P) { match V.1 { @@ -724,15 +730,67 @@ pomelo! { } statement ::= simple_statement; - // Grammar Note: labeled statements for SWITCH only; 'goto' is not supported. simple_statement ::= declaration_statement; simple_statement ::= expression_statement; - //simple_statement ::= selection_statement; - //simple_statement ::= switch_statement; - //simple_statement ::= case_label; - //simple_statement ::= iteration_statement; + simple_statement ::= selection_statement; simple_statement ::= jump_statement; + + selection_statement ::= If LeftParen expression(e) RightParen statement(s1) Else statement(s2) { + Statement::If { + condition: e.expression, + accept: vec![s1], + reject: vec![s2], + } + } + + selection_statement ::= If LeftParen expression(e) RightParen statement(s) [Else] { + Statement::If { + condition: e.expression, + accept: vec![s], + reject: vec![], + } + } + + selection_statement ::= Switch LeftParen expression(e) RightParen LeftBrace switch_statement_list(ls) RightBrace { + let mut default = Vec::new(); + let mut cases = FastHashMap::default(); + for (v, s, ft) in ls { + if let Some(v) = v { + cases.insert(v, (s, ft)); + } else { + default.extend_from_slice(&s); + } + } + Statement::Switch { + selector: e.expression, + cases, + default, + } + } + + switch_statement_list ::= { + vec![] + } + switch_statement_list ::= switch_statement_list(mut ssl) switch_statement((v, sl, ft)) { + ssl.push((v, sl, ft)); + ssl + } + switch_statement ::= Case IntConstant(v) Colon statement_list(sl) { + let fallthrough = match sl.last() { + Some(Statement::Break) => None, + _ => Some(FallThrough), + }; + (Some(v.1 as i32), sl, fallthrough) + } + switch_statement ::= Default Colon statement_list(sl) { + let fallthrough = match sl.last() { + Some(Statement::Break) => Some(FallThrough), + _ => None, + }; + (None, sl, fallthrough) + } + compound_statement ::= LeftBrace RightBrace { vec![] } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 77b30eff0..8e6e7838f 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -78,3 +78,70 @@ fn version() { "(450, Core)" ); } + +#[test] +fn control_flow() { + let program = parse_program( + r#" + # version 450 + void main() { + if (true) { + return 1; + } else { + return 2; + } + } + "#, + ShaderStage::Vertex, + ) + .unwrap(); + assert_eq!( + format!("{:?}", (program.version, program.profile)), + "(450, Core)" + ); + + let program = parse_program( + r#" + # version 450 + void main() { + if (true) { + return 1; + } + } + "#, + ShaderStage::Vertex, + ) + .unwrap(); + assert_eq!( + format!("{:?}", (program.version, program.profile)), + "(450, Core)" + ); + + let program = parse_program( + r#" + # version 450 + void main() { + int x; + int y = 3; + switch (5) { + case 2: + x = 2; + case 5: + x = 5; + y = 2; + break; + default: + x = 0; + } + } + "#, + ShaderStage::Vertex, + ) + .unwrap(); + // println!("{:#?}", program); + // assert!(false); + assert_eq!( + format!("{:?}", (program.version, program.profile)), + "(450, Core)" + ); +} From 4a10aab5f64cde2611dac67214a1d346a2c4673b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristoffer=20S=C3=B8holm?= Date: Sat, 31 Oct 2020 01:26:39 +0100 Subject: [PATCH 0255/2212] [glsl-in] Add iteration statements while, do-while and for loops --- src/front/glsl/lex.rs | 4 ++ src/front/glsl/parser.rs | 76 ++++++++++++++++++++++++++++++++++ src/front/glsl/parser_tests.rs | 51 +++++++++++++++-------- 3 files changed, 114 insertions(+), 17 deletions(-) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 1055a6b0f..57e86a4c2 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -146,6 +146,10 @@ impl<'a> Lexer<'a> { "switch" => Some(Token::Switch(meta)), "case" => Some(Token::Case(meta)), "default" => Some(Token::Default(meta)), + // iteration statements + "while" => Some(Token::While(meta)), + "do" => Some(Token::Do(meta)), + "for" => Some(Token::For(meta)), // types "void" => Some(Token::Void(meta)), word => { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index a29a90138..4cb212fdc 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -55,9 +55,13 @@ pomelo! { %type expression_statement Statement; %type declaration_statement Statement; %type jump_statement Statement; + %type iteration_statement Statement; %type selection_statement Statement; %type switch_statement_list Vec<(Option, Block, Option)>; %type switch_statement (Option, Block, Option); + %type for_init_statement Statement; + %type for_rest_statement (Option, Option); + %type condition_opt Option; // expressions %type unary_expression ExpressionRule; @@ -734,6 +738,7 @@ pomelo! { simple_statement ::= expression_statement; simple_statement ::= selection_statement; simple_statement ::= jump_statement; + simple_statement ::= iteration_statement; selection_statement ::= If LeftParen expression(e) RightParen statement(s1) Else statement(s2) { @@ -791,6 +796,77 @@ pomelo! { (None, sl, fallthrough) } + iteration_statement ::= While LeftParen expression(e) RightParen compound_statement_no_new_scope(sl) { + let mut body = Vec::with_capacity(sl.len() + 1); + body.push( + Statement::If { + condition: e.expression, + accept: vec![Statement::Break], + reject: vec![], + } + ); + body.extend_from_slice(&sl); + Statement::Loop { + body, + continuing: vec![], + } + } + + iteration_statement ::= Do compound_statement(sl) While LeftParen expression(e) RightParen { + let mut body = sl; + body.push( + Statement::If { + condition: e.expression, + accept: vec![Statement::Break], + reject: vec![], + } + ); + Statement::Loop { + body, + continuing: vec![], + } + } + + iteration_statement ::= For LeftParen for_init_statement(s_init) for_rest_statement((cond_e, loop_e)) RightParen compound_statement_no_new_scope(sl) { + let mut body = Vec::with_capacity(sl.len() + 2); + if let Some(cond_e) = cond_e { + body.push( + Statement::If { + condition: cond_e.expression, + accept: vec![Statement::Break], + reject: vec![], + } + ); + } + body.extend_from_slice(&sl); + if let Some(loop_e) = loop_e { + body.extend_from_slice(&loop_e.statements); + } + Statement::Block(vec![ + s_init, + Statement::Loop { + body, + continuing: vec![], + } + ]) + } + + for_init_statement ::= expression_statement; + for_init_statement ::= declaration_statement; + for_rest_statement ::= condition_opt(c) Semicolon { + (c, None) + } + for_rest_statement ::= condition_opt(c) Semicolon expression(e) { + (c, Some(e)) + } + + condition_opt ::= { + None + } + condition_opt ::= conditional_expression(c) { + Some(c) + } + compound_statement ::= LeftBrace RightBrace { vec![] } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 8e6e7838f..f564c679d 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -81,7 +81,7 @@ fn version() { #[test] fn control_flow() { - let program = parse_program( + let _program = parse_program( r#" # version 450 void main() { @@ -95,12 +95,8 @@ fn control_flow() { ShaderStage::Vertex, ) .unwrap(); - assert_eq!( - format!("{:?}", (program.version, program.profile)), - "(450, Core)" - ); - let program = parse_program( + let _program = parse_program( r#" # version 450 void main() { @@ -112,12 +108,8 @@ fn control_flow() { ShaderStage::Vertex, ) .unwrap(); - assert_eq!( - format!("{:?}", (program.version, program.profile)), - "(450, Core)" - ); - let program = parse_program( + let _program = parse_program( r#" # version 450 void main() { @@ -138,10 +130,35 @@ fn control_flow() { ShaderStage::Vertex, ) .unwrap(); - // println!("{:#?}", program); - // assert!(false); - assert_eq!( - format!("{:?}", (program.version, program.profile)), - "(450, Core)" - ); + let _program = parse_program( + r#" + # version 450 + void main() { + int x = 0; + while(x < 5) { + x = x + 1; + } + do { + x = x - 1; + } while(x >= 4) + } + "#, + ShaderStage::Vertex, + ) + .unwrap(); + + let _program = parse_program( + r#" + # version 450 + void main() { + int x = 0; + for(int i = 0; i < 10;) { + x = x + 2; + } + return x; + } + "#, + ShaderStage::Vertex, + ) + .unwrap(); } From f811b69aa81d659bb9c712700fe9234dce041615 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 29 Oct 2020 13:02:07 -0400 Subject: [PATCH 0256/2212] [msl] avoid bad identifiers --- src/back/msl.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index 45d2bd4d9..eb639c793 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -247,6 +247,15 @@ impl From for Name<'_> { } } +fn is_valid_identifier_name(s: &str) -> bool { + let mut chars = s.chars(); + match chars.next() { + Some(c) if c.is_ascii_alphabetic() || c == '_' => (), + _ => return false, + }; + chars.all(|c| c.is_ascii_alphanumeric() || c == '_') +} + trait AsName { fn or_index(&self, index: I) -> Name; } @@ -255,7 +264,9 @@ impl AsName for Option { Name { class: I::CLASS, source: match *self { - Some(ref name) if !name.is_empty() => NameSource::Custom { + //TODO: handle name collisions + //TODO: try to use parts of the name if it contains invalid characters + Some(ref name) if is_valid_identifier_name(name) => NameSource::Custom { name, prefix: I::PREFIX, }, From 0893d912be268298ae2ed784beb541a23b9d6b31 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 30 Oct 2020 16:23:04 -0400 Subject: [PATCH 0257/2212] [msl] fix floating point modulo, return value from compute entry point --- src/back/msl.rs | 63 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/src/back/msl.rs b/src/back/msl.rs index eb639c793..cade25218 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -597,13 +597,26 @@ impl Writer { crate::BinaryOperator::Greater => "==", crate::BinaryOperator::GreaterEqual => ">=", crate::BinaryOperator::And => "&", - other => return Err(Error::UnsupportedBinaryOp(other)), + _ => return Err(Error::UnsupportedBinaryOp(op)), }; - //write!(self.out, "(")?; - self.put_expression(left, function, module)?; - write!(self.out, " {} ", op_str)?; - self.put_expression(right, function, module)?; - //write!(self.out, ")")?; + let kind = self + .typifier + .get(left, &module.types) + .scalar_kind() + .ok_or(Error::UnsupportedBinaryOp(op))?; + if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float { + write!(self.out, "fmod(")?; + self.put_expression(left, function, module)?; + write!(self.out, ", ")?; + self.put_expression(right, function, module)?; + write!(self.out, ")")?; + } else { + //write!(self.out, "(")?; + self.put_expression(left, function, module)?; + write!(self.out, " {} ", op_str)?; + self.put_expression(right, function, module)?; + //write!(self.out, ")")?; + } } crate::Expression::Intrinsic { fun, argument } => { let op = match fun { @@ -732,6 +745,7 @@ impl Writer { statements: &[crate::Statement], function: &crate::Function, module: &crate::Module, + return_value: Option<&str>, ) -> Result<(), Error> { for statement in statements { log::trace!("statement[{}] {:?}", level.0, statement); @@ -739,7 +753,7 @@ impl Writer { crate::Statement::Block(ref block) => { if !block.is_empty() { writeln!(self.out, "{}{{", level)?; - self.put_block(level.next(), block, function, module)?; + self.put_block(level.next(), block, function, module, return_value)?; writeln!(self.out, "{}}}", level)?; } } @@ -751,10 +765,10 @@ impl Writer { write!(self.out, "{}if (", level)?; self.put_expression(condition, function, module)?; writeln!(self.out, ") {{")?; - self.put_block(level.next(), accept, function, module)?; + self.put_block(level.next(), accept, function, module, return_value)?; if !reject.is_empty() { writeln!(self.out, "{}}} else {{", level)?; - self.put_block(level.next(), reject, function, module)?; + self.put_block(level.next(), reject, function, module, return_value)?; } writeln!(self.out, "{}}}", level)?; } @@ -769,14 +783,14 @@ impl Writer { let lcase = level.next(); for (&value, &(ref block, ref fall_through)) in cases.iter() { writeln!(self.out, "{}case {}: {{", lcase, value)?; - self.put_block(lcase.next(), block, function, module)?; + self.put_block(lcase.next(), block, function, module, return_value)?; if fall_through.is_none() { writeln!(self.out, "{}break;", lcase.next())?; } writeln!(self.out, "{}}}", lcase)?; } writeln!(self.out, "{}default: {{", lcase)?; - self.put_block(lcase.next(), default, function, module)?; + self.put_block(lcase.next(), default, function, module, return_value)?; writeln!(self.out, "{}}}", lcase)?; writeln!(self.out, "{}}}", level)?; } @@ -785,7 +799,7 @@ impl Writer { ref continuing, } => { writeln!(self.out, "{}while(true) {{", level)?; - self.put_block(level.next(), body, function, module)?; + self.put_block(level.next(), body, function, module, return_value)?; if !continuing.is_empty() { //TODO } @@ -797,16 +811,18 @@ impl Writer { crate::Statement::Continue => { writeln!(self.out, "{}continue;", level)?; } - crate::Statement::Return { value } => { + crate::Statement::Return { + value: Some(expr_handle), + } => { write!(self.out, "{}return ", level)?; - match value { - None => write!(self.out, "{}", OUTPUT_STRUCT_NAME)?, - Some(expr_handle) => { - self.put_expression(expr_handle, function, module)?; - } - } + self.put_expression(expr_handle, function, module)?; writeln!(self.out, ";")?; } + crate::Statement::Return { value: None } => { + if let Some(string) = return_value { + writeln!(self.out, "{}return {};", level, string)?; + } + } crate::Statement::Kill => { writeln!(self.out, "{}discard_fragment();", level)?; } @@ -1013,7 +1029,7 @@ impl Writer { } writeln!(self.out, ";")?; } - self.put_block(Level(1), &fun.body, fun, module)?; + self.put_block(Level(1), &fun.body, fun, module, None)?; writeln!(self.out, "}}")?; } @@ -1080,7 +1096,7 @@ impl Writer { }, }; - match stage { + let return_value = match stage { crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { // make dedicated input/output structs writeln!(self.out, "struct {} {{", location_input_name)?; @@ -1176,9 +1192,12 @@ impl Writer { "\t{} {} [[stage_in]]{}", location_input_name, LOCATION_INPUT_STRUCT_NAME, separator )?; + + Some(OUTPUT_STRUCT_NAME) } crate::ShaderStage::Compute => { writeln!(self.out, "{} void {}(", em_str, fun_name)?; + None } }; @@ -1240,7 +1259,7 @@ impl Writer { } writeln!(self.out, ";")?; } - self.put_block(Level(1), &fun.body, fun, module)?; + self.put_block(Level(1), &fun.body, fun, module, return_value)?; writeln!(self.out, "}}")?; } From 173bb0de423bcd6e30c421c020f5119529abaaac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Tal=C4=8D=C3=ADk?= Date: Sat, 31 Oct 2020 14:42:46 +0100 Subject: [PATCH 0258/2212] spv-in: more loop fixes --- src/front/spv/flow.rs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 62c3866c4..32eac6694 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -250,7 +250,7 @@ impl FlowGraph { accept: self.naga_traverse(true_node_index, Some(merge_node_index))?, reject: self.naga_traverse(false_node_index, Some(merge_node_index))?, }); - result.extend(self.naga_traverse(merge_node_index, None)?); + result.extend(self.naga_traverse(merge_node_index, stop_node_index)?); } else { result.push(crate::Statement::If { condition, @@ -258,7 +258,7 @@ impl FlowGraph { self.block_to_node[&true_id], Some(merge_node_index), )?, - reject: self.naga_traverse(merge_node_index, None)?, + reject: self.naga_traverse(merge_node_index, stop_node_index)?, }); } @@ -309,7 +309,7 @@ impl FlowGraph { .naga_traverse(self.block_to_node[&default], Some(merge_node_index))?, }); - result.extend(self.naga_traverse(merge_node_index, None)?); + result.extend(self.naga_traverse(merge_node_index, stop_node_index)?); Ok(result) } @@ -347,7 +347,7 @@ impl FlowGraph { }; let mut result = vec![crate::Statement::Loop { body, continuing }]; - result.extend(self.naga_traverse(merge_node_index, None)?); + result.extend(self.naga_traverse(merge_node_index, stop_node_index)?); Ok(result) } @@ -391,13 +391,19 @@ impl FlowGraph { Ok(result) } Some(ControlFlowNodeType::Continue) => { + let back_block = match node.terminator { + Terminator::Branch { target_id } => { + self.naga_traverse(self.block_to_node[&target_id], None)? + } + _ => return Err(Error::InvalidTerminator), + }; + let mut result = node.block.clone(); + result.extend(back_block); result.push(crate::Statement::Continue); Ok(result) } - Some(ControlFlowNodeType::Back) | Some(ControlFlowNodeType::Merge) => { - Ok(node.block.clone()) - } + Some(ControlFlowNodeType::Back) => Ok(node.block.clone()), Some(ControlFlowNodeType::Kill) => { let mut result = node.block.clone(); result.push(crate::Statement::Kill); @@ -412,7 +418,7 @@ impl FlowGraph { result.push(crate::Statement::Return { value }); Ok(result) } - None => match node.terminator { + Some(ControlFlowNodeType::Merge) | None => match node.terminator { Terminator::Branch { target_id } => { let mut result = node.block.clone(); result.extend( From 602367c062e37819501168ca7063ab41dc6e4879 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Sun, 1 Nov 2020 13:46:21 +0000 Subject: [PATCH 0259/2212] [glsl-in] Add initial texture handling --- src/front/glsl/ast.rs | 7 +-- src/front/glsl/parser.rs | 78 +++++++++++++++++++++++++--------- src/front/glsl/parser_tests.rs | 18 ++++++++ src/front/glsl/types.rs | 15 +++++++ 4 files changed, 95 insertions(+), 23 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index ce63dee0b..cd7abfdea 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -138,6 +138,7 @@ impl Context { pub struct ExpressionRule { pub expression: Handle, pub statements: Vec, + pub sampler: Option>, } impl ExpressionRule { @@ -145,6 +146,7 @@ impl ExpressionRule { ExpressionRule { expression, statements: vec![], + sampler: None, } } } @@ -166,12 +168,11 @@ pub struct VarDeclaration { #[derive(Debug)] pub enum FunctionCallKind { TypeConstructor(Handle), - Function(Handle), + Function(String), } #[derive(Debug)] pub struct FunctionCall { pub kind: FunctionCallKind, - pub args: Vec>, - pub statements: Vec, + pub args: Vec, } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 4cb212fdc..2914c5de5 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -7,7 +7,7 @@ pomelo! { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{proc::Typifier, Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, EntryPoint, Expression, FallThrough, FastHashMap, Function, GlobalVariable, Handle, Interpolation, - LocalVariable, MemberOrigin, ScalarKind, Statement, StorageAccess, + LocalVariable, MemberOrigin, SampleLevel, ScalarKind, Statement, StorageAccess, StorageClass, StructMember, Type, TypeInner}; } %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; @@ -230,7 +230,7 @@ pomelo! { postfix_expression ::= postfix_expression(e) Dot Identifier(i) /* FieldSelection in spec */ { //TODO: how will this work as l-value? let expression = extra.field_selection(e.expression, &*i.1, i.0)?; - ExpressionRule { expression, statements: e.statements } + ExpressionRule { expression, statements: e.statements, sampler: None } } postfix_expression ::= postfix_expression(pe) IncOp { //TODO @@ -244,17 +244,49 @@ pomelo! { integer_expression ::= expression; function_call ::= function_call_or_method(fc) { - if let FunctionCallKind::TypeConstructor(ty) = fc.kind { - let h = extra.context.expressions.append(Expression::Compose{ - ty, - components: fc.args, - }); - ExpressionRule{ - expression: h, - statements: fc.statements, + match fc.kind { + FunctionCallKind::TypeConstructor(ty) => { + let h = extra.context.expressions.append(Expression::Compose{ + ty, + components: fc.args.iter().map(|a| a.expression).collect(), + }); + ExpressionRule{ + expression: h, + statements: fc.args.into_iter().map(|a| a.statements).flatten().collect(), + sampler: None + } + } + FunctionCallKind::Function(name) => { + match name.as_str() { + "sampler2D" => { + //TODO: check args len + ExpressionRule{ + expression: fc.args[0].expression, + sampler: Some(fc.args[1].expression), + statements: fc.args.into_iter().map(|a| a.statements).flatten().collect(), + } + } + "texture" => { + //TODO: check args len + if let Some(sampler) = fc.args[0].sampler { + ExpressionRule{ + expression: extra.context.expressions.append(Expression::ImageSample{ + image: fc.args[0].expression, + sampler, + coordinate: fc.args[1].expression, + level: SampleLevel::Auto, + depth_ref: None, + }), + sampler: None, + statements: fc.args.into_iter().map(|a| a.statements).flatten().collect(), + } + } else { + return Err(ErrorKind::SemanticError("Bad call to texture")); + } + } + _ => { return Err(ErrorKind::NotImplemented("Function call")); } + } } - } else { - return Err(ErrorKind::NotImplemented("Function call")); } } function_call_or_method ::= function_call_generic; @@ -269,26 +301,22 @@ pomelo! { } function_call_header_no_parameters ::= function_call_header; function_call_header_with_parameters ::= function_call_header(mut h) assignment_expression(ae) { - h.args.push(ae.expression); - h.statements.extend(ae.statements); + h.args.push(ae); h } function_call_header_with_parameters ::= function_call_header_with_parameters(mut h) Comma assignment_expression(ae) { - h.args.push(ae.expression); - h.statements.extend(ae.statements); + h.args.push(ae); h } function_call_header ::= function_identifier(i) LeftParen { FunctionCall { kind: i, args: vec![], - statements: vec![], } } // Grammar Note: Constructors look like functions, but lexical analysis recognized most of them as // keywords. They are now recognized through “type_specifier”. - // Methods (.length), subroutine array calls, and identifiers are recognized through postfix_expression. function_identifier ::= type_specifier(t) { if let Some(ty) = t { FunctionCallKind::TypeConstructor(ty) @@ -296,10 +324,19 @@ pomelo! { return Err(ErrorKind::NotImplemented("bad type ctor")) } } - function_identifier ::= postfix_expression(e) { - FunctionCallKind::Function(e.expression) + + //TODO + // Methods (.length), subroutine array calls, and identifiers are recognized through postfix_expression. + // function_identifier ::= postfix_expression(e) { + // FunctionCallKind::Function(e.expression) + // } + + // Simplification of above + function_identifier ::= Identifier(i) { + FunctionCallKind::Function(i.1) } + unary_expression ::= postfix_expression; unary_expression ::= IncOp unary_expression { @@ -452,6 +489,7 @@ pomelo! { ExpressionRule{ expression: e.expression, statements: ae.statements, + sampler: None, } } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index f564c679d..ccdc657a7 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -162,3 +162,21 @@ fn control_flow() { ) .unwrap(); } + +#[test] +fn textures() { + let _program = parse_program( + r#" + #version 450 + layout(location = 0) in vec2 v_uv; + layout(location = 0) out vec4 o_color; + layout(set = 1, binding = 1) uniform texture2D tex; + layout(set = 1, binding = 2) uniform sampler tex_sampler; + void main() { + o_color = texture(sampler2D(tex, tex_sampler), v_uv); + } + "#, + ShaderStage::Fragment, + ) + .unwrap(); +} diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index dceb230b8..715c0c743 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -37,6 +37,21 @@ pub fn parse_type(type_name: &str) -> Option { width: 4, }, }), + "texture2D" => Some(Type { + name: None, + inner: TypeInner::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Sampled { + kind: ScalarKind::Float, + multi: false, + }, + }, + }), + "sampler" => Some(Type { + name: None, + inner: TypeInner::Sampler { comparison: false }, + }), word => { fn kind_width_parse(ty: &str) -> Option<(ScalarKind, u8)> { Some(match ty { From 0101ea73199452d0dfdb2930fd49211e6eff28d4 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 2 Nov 2020 07:48:04 +0000 Subject: [PATCH 0260/2212] [glsl-in] Handle assign ops: +=, *=, etc --- src/front/glsl/parser.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2914c5de5..b32b711f0 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -435,17 +435,29 @@ pomelo! { assignment_expression ::= conditional_expression; assignment_expression ::= unary_expression(mut pointer) assignment_operator(op) assignment_expression(value) { + pointer.statements.extend(value.statements); match op { BinaryOperator::Equal => { - pointer.statements.extend(value.statements); pointer.statements.push(Statement::Store{ pointer: pointer.expression, value: value.expression }); pointer }, - //TODO: op != Equal - _ => {return Err(ErrorKind::NotImplemented("assign op"))} + _ => { + let h = extra.context.expressions.append( + Expression::Binary{ + op, + left: pointer.expression, + right: value.expression, + } + ); + pointer.statements.push(Statement::Store{ + pointer: pointer.expression, + value: h, + }); + pointer + } } } From a89191c234f0c99f13b4493888f41d15ca664da2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristoffer=20S=C3=B8holm?= Date: Mon, 2 Nov 2020 23:21:25 +0100 Subject: [PATCH 0261/2212] [glsl-out] Handle initializers for locals This pretty trivial change unfortunately required a loop to mutably borrow both builder and manager at the same time, so I had to separate them. Perhaps a cleaner solution would be to use an object with internal state instead of free functions. --- src/back/glsl.rs | 201 ++++++++++++++++++++++++++--------------------- 1 file changed, 111 insertions(+), 90 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 8463b1cff..52122cedb 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -684,23 +684,6 @@ pub fn write<'a>( }) .collect(); - for (handle, name) in locals.iter() { - writeln!( - &mut buf, - "\t{} {};", - write_type( - func.local_variables[*handle].ty, - &module.types, - &structs, - None, - &mut manager - )?, - name - )?; - } - - writeln!(&mut buf)?; - let mut builder = StatementBuilder { functions: &functions, globals: &globals_lookup, @@ -709,14 +692,33 @@ pub fn write<'a>( args: &args, expressions: &func.expressions, typifier: &typifier, - manager: &mut manager, }; + for (handle, name) in locals.iter() { + let var = &func.local_variables[*handle]; + write!( + &mut buf, + "\t{} {}", + write_type(var.ty, &module.types, &structs, None, &mut manager)?, + name + )?; + if let Some(init) = var.init { + write!( + &mut buf, + " = {}", + write_expression(&func.expressions[init], module, &mut builder, &mut manager)? + )?; + } + writeln!(&mut buf, ";")?; + } + + writeln!(&mut buf)?; + for sta in func.body.iter() { writeln!( &mut buf, "{}", - write_statement(sta, module, &mut builder, 1)? + write_statement(sta, module, &mut builder, &mut manager, 1)? )?; } @@ -748,19 +750,19 @@ struct StatementBuilder<'a> { args: &'a FastHashMap, expressions: &'a Arena, typifier: &'a Typifier, - pub manager: &'a mut FeaturesManager, } fn write_statement<'a, 'b>( sta: &Statement, module: &'a Module, builder: &'b mut StatementBuilder<'a>, + manager: &mut FeaturesManager, indent: usize, ) -> Result { Ok(match sta { Statement::Block(block) => block .iter() - .map(|sta| write_statement(sta, module, builder, indent)) + .map(|sta| write_statement(sta, module, builder, manager, indent)) .collect::, _>>()? .join("\n"), Statement::If { @@ -774,14 +776,14 @@ fn write_statement<'a, 'b>( &mut out, "{}if({}) {{", "\t".repeat(indent), - write_expression(&builder.expressions[*condition], module, builder)? + write_expression(&builder.expressions[*condition], module, builder, manager)? )?; for sta in accept { writeln!( &mut out, "{}", - write_statement(sta, module, builder, indent + 1)? + write_statement(sta, module, builder, manager, indent + 1)? )?; } @@ -791,7 +793,7 @@ fn write_statement<'a, 'b>( writeln!( &mut out, "{}", - write_statement(sta, module, builder, indent + 1)? + write_statement(sta, module, builder, manager, indent + 1)? )?; } } @@ -811,7 +813,7 @@ fn write_statement<'a, 'b>( &mut out, "{}switch({}) {{", "\t".repeat(indent), - write_expression(&builder.expressions[*selector], module, builder)? + write_expression(&builder.expressions[*selector], module, builder, manager)? )?; for (label, (block, fallthrough)) in cases { @@ -821,7 +823,7 @@ fn write_statement<'a, 'b>( writeln!( &mut out, "{}", - write_statement(sta, module, builder, indent + 2)? + write_statement(sta, module, builder, manager, indent + 2)? )?; } @@ -837,7 +839,7 @@ fn write_statement<'a, 'b>( writeln!( &mut out, "{}", - write_statement(sta, module, builder, indent + 2)? + write_statement(sta, module, builder, manager, indent + 2)? )?; } } @@ -855,7 +857,7 @@ fn write_statement<'a, 'b>( writeln!( &mut out, "{}", - write_statement(sta, module, builder, indent + 1)? + write_statement(sta, module, builder, manager, indent + 1)? )?; } @@ -871,7 +873,7 @@ fn write_statement<'a, 'b>( if let Some(expr) = value { format!( "return {};", - write_expression(&builder.expressions[*expr], module, builder)? + write_expression(&builder.expressions[*expr], module, builder, manager)? ) } else { String::from("return;") @@ -881,8 +883,8 @@ fn write_statement<'a, 'b>( Statement::Store { pointer, value } => format!( "{}{} = {};", "\t".repeat(indent), - write_expression(&builder.expressions[*pointer], module, builder)?, - write_expression(&builder.expressions[*value], module, builder)? + write_expression(&builder.expressions[*pointer], module, builder, manager)?, + write_expression(&builder.expressions[*value], module, builder, manager)? ), }) } @@ -891,18 +893,19 @@ fn write_expression<'a, 'b>( expr: &Expression, module: &'a Module, builder: &'b mut StatementBuilder<'a>, + manager: &mut FeaturesManager, ) -> Result, Error> { Ok(match *expr { Expression::Access { base, index } => { - let base_expr = write_expression(&builder.expressions[base], module, builder)?; + let base_expr = write_expression(&builder.expressions[base], module, builder, manager)?; Cow::Owned(format!( "{}[{}]", base_expr, - write_expression(&builder.expressions[index], module, builder)? + write_expression(&builder.expressions[index], module, builder, manager)? )) } Expression::AccessIndex { base, index } => { - let base_expr = write_expression(&builder.expressions[base], module, builder)?; + let base_expr = write_expression(&builder.expressions[base], module, builder, manager)?; match *builder.typifier.get(base, &module.types) { TypeInner::Vector { .. } => Cow::Owned(format!("{}[{}]", base_expr, index)), @@ -931,12 +934,13 @@ fn write_expression<'a, 'b>( &module.constants[constant], module, builder, + manager, )?), Expression::Compose { ty, ref components } => { let constructor = match module.types[ty].inner { TypeInner::Vector { size, kind, width } => format!( "{}vec{}", - map_scalar(kind, width, builder.manager)?.prefix, + map_scalar(kind, width, manager)?.prefix, size as u8, ), TypeInner::Matrix { @@ -945,19 +949,18 @@ fn write_expression<'a, 'b>( width, } => format!( "{}mat{}x{}", - map_scalar(crate::ScalarKind::Float, width, builder.manager)?.prefix, + map_scalar(crate::ScalarKind::Float, width, manager)?.prefix, columns as u8, rows as u8, ), TypeInner::Array { .. } => { - write_type(ty, &module.types, builder.structs, None, builder.manager)? - .into_owned() + write_type(ty, &module.types, builder.structs, None, manager)?.into_owned() } TypeInner::Struct { .. } => builder.structs.get(&ty).unwrap().clone(), _ => { return Err(Error::Custom(format!( "Cannot compose type {}", - write_type(ty, &module.types, builder.structs, None, builder.manager)? + write_type(ty, &module.types, builder.structs, None, manager)? ))) } }; @@ -970,7 +973,8 @@ fn write_expression<'a, 'b>( .map::, _>(|arg| Ok(write_expression( &builder.expressions[*arg], module, - builder + builder, + manager, )?)) .collect::, _>>()? .join(","), @@ -982,7 +986,7 @@ fn write_expression<'a, 'b>( Cow::Borrowed(builder.locals_lookup.get(&handle).unwrap()) } Expression::Load { pointer } => { - write_expression(&builder.expressions[pointer], module, builder)? + write_expression(&builder.expressions[pointer], module, builder, manager)? } Expression::ImageSample { image, @@ -991,10 +995,11 @@ fn write_expression<'a, 'b>( level, depth_ref, } => { - let image_expr = write_expression(&builder.expressions[image], module, builder)?; - write_expression(&builder.expressions[sampler], module, builder)?; + let image_expr = + write_expression(&builder.expressions[image], module, builder, manager)?; + write_expression(&builder.expressions[sampler], module, builder, manager)?; let coordinate_expr = - write_expression(&builder.expressions[coordinate], module, builder)?; + write_expression(&builder.expressions[coordinate], module, builder, manager)?; let size = match *builder.typifier.get(coordinate, &module.types) { TypeInner::Vector { size, .. } => size, @@ -1011,7 +1016,7 @@ fn write_expression<'a, 'b>( "vec{}({},{})", size as u8 + 1, coordinate_expr, - write_expression(&builder.expressions[depth_ref], module, builder)? + write_expression(&builder.expressions[depth_ref], module, builder, manager)? )) } else { coordinate_expr @@ -1024,14 +1029,16 @@ fn write_expression<'a, 'b>( format!("textureLod({},{},0)", image_expr, coordinate_expr) } crate::SampleLevel::Exact(expr) => { - let level_expr = write_expression(&builder.expressions[expr], module, builder)?; + let level_expr = + write_expression(&builder.expressions[expr], module, builder, manager)?; format!( "textureLod({}, {}, {})", image_expr, coordinate_expr, level_expr ) } crate::SampleLevel::Bias(bias) => { - let bias_expr = write_expression(&builder.expressions[bias], module, builder)?; + let bias_expr = + write_expression(&builder.expressions[bias], module, builder, manager)?; format!("texture({},{},{})", image_expr, coordinate_expr, bias_expr) } }) @@ -1041,9 +1048,10 @@ fn write_expression<'a, 'b>( coordinate, index, } => { - let image_expr = write_expression(&builder.expressions[image], module, builder)?; + let image_expr = + write_expression(&builder.expressions[image], module, builder, manager)?; let coordinate_expr = - write_expression(&builder.expressions[coordinate], module, builder)?; + write_expression(&builder.expressions[coordinate], module, builder, manager)?; let (dim, arrayed, class) = match *builder.typifier.get(image, &module.types) { TypeInner::Image { @@ -1059,15 +1067,19 @@ fn write_expression<'a, 'b>( //TODO: fix this let sampler_constructor = format!( "{}sampler{}{}{}({})", - map_scalar(kind, 4, builder.manager)?.prefix, + map_scalar(kind, 4, manager)?.prefix, ImageDimension(dim), if multi { "MS" } else { "" }, if arrayed { "Array" } else { "" }, image_expr, ); - let index_expr = - write_expression(&builder.expressions[index.unwrap()], module, builder)?; + let index_expr = write_expression( + &builder.expressions[index.unwrap()], + module, + builder, + manager, + )?; format!( "texelFetch({},{},{})", sampler_constructor, coordinate_expr, index_expr @@ -1078,7 +1090,7 @@ fn write_expression<'a, 'b>( }) } Expression::Unary { op, expr } => { - let base_expr = write_expression(&builder.expressions[expr], module, builder)?; + let base_expr = write_expression(&builder.expressions[expr], module, builder, manager)?; Cow::Owned(format!( "({} {})", @@ -1108,8 +1120,9 @@ fn write_expression<'a, 'b>( )) } Expression::Binary { op, left, right } => { - let left_expr = write_expression(&builder.expressions[left], module, builder)?; - let right_expr = write_expression(&builder.expressions[right], module, builder)?; + let left_expr = write_expression(&builder.expressions[left], module, builder, manager)?; + let right_expr = + write_expression(&builder.expressions[right], module, builder, manager)?; let op_str = match op { BinaryOperator::Add => "+", @@ -1135,7 +1148,7 @@ fn write_expression<'a, 'b>( Cow::Owned(format!("({} {} {})", left_expr, op_str, right_expr)) } Expression::Intrinsic { fun, argument } => { - let expr = write_expression(&builder.expressions[argument], module, builder)?; + let expr = write_expression(&builder.expressions[argument], module, builder, manager)?; Cow::Owned(format!( "{:?}({})", @@ -1151,17 +1164,20 @@ fn write_expression<'a, 'b>( )) } Expression::Transpose(matrix) => { - let matrix_expr = write_expression(&builder.expressions[matrix], module, builder)?; + let matrix_expr = + write_expression(&builder.expressions[matrix], module, builder, manager)?; Cow::Owned(format!("transpose({})", matrix_expr)) } Expression::DotProduct(left, right) => { - let left_expr = write_expression(&builder.expressions[left], module, builder)?; - let right_expr = write_expression(&builder.expressions[right], module, builder)?; + let left_expr = write_expression(&builder.expressions[left], module, builder, manager)?; + let right_expr = + write_expression(&builder.expressions[right], module, builder, manager)?; Cow::Owned(format!("dot({},{})", left_expr, right_expr)) } Expression::CrossProduct(left, right) => { - let left_expr = write_expression(&builder.expressions[left], module, builder)?; - let right_expr = write_expression(&builder.expressions[right], module, builder)?; + let left_expr = write_expression(&builder.expressions[left], module, builder, manager)?; + let right_expr = + write_expression(&builder.expressions[right], module, builder, manager)?; Cow::Owned(format!("cross({},{})", left_expr, right_expr)) } Expression::As { @@ -1169,7 +1185,8 @@ fn write_expression<'a, 'b>( kind, convert, } => { - let value_expr = write_expression(&builder.expressions[expr], module, builder)?; + let value_expr = + write_expression(&builder.expressions[expr], module, builder, manager)?; let (source_kind, ty_expr) = match *builder.typifier.get(expr, &module.types) { TypeInner::Scalar { @@ -1177,7 +1194,7 @@ fn write_expression<'a, 'b>( kind: source_kind, } => ( source_kind, - Cow::Borrowed(map_scalar(kind, width, builder.manager)?.full), + Cow::Borrowed(map_scalar(kind, width, manager)?.full), ), TypeInner::Vector { width, @@ -1187,7 +1204,7 @@ fn write_expression<'a, 'b>( source_kind, Cow::Owned(format!( "{}vec{}", - map_scalar(kind, width, builder.manager)?.prefix, + map_scalar(kind, width, manager)?.prefix, size as u32, )), ), @@ -1214,7 +1231,7 @@ fn write_expression<'a, 'b>( Cow::Owned(format!("{}({})", op, value_expr)) } Expression::Derivative { axis, expr } => { - let expr = write_expression(&builder.expressions[expr], module, builder)?; + let expr = write_expression(&builder.expressions[expr], module, builder, manager)?; Cow::Owned(format!( "{}({})", @@ -1237,7 +1254,8 @@ fn write_expression<'a, 'b>( .map::, _>(|arg| write_expression( &builder.expressions[*arg], module, - builder + builder, + manager, )) .collect::, _>>()? .join(","), @@ -1247,14 +1265,18 @@ fn write_expression<'a, 'b>( ref arguments, } => match name.as_str() { "cos" | "normalize" | "sin" | "length" | "abs" | "floor" | "inverse" => { - let expr = write_expression(&builder.expressions[arguments[0]], module, builder)?; + let expr = + write_expression(&builder.expressions[arguments[0]], module, builder, manager)?; Cow::Owned(format!("{}({})", name, expr)) } "fclamp" | "clamp" | "mix" | "smoothstep" => { - let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; - let y = write_expression(&builder.expressions[arguments[1]], module, builder)?; - let a = write_expression(&builder.expressions[arguments[2]], module, builder)?; + let x = + write_expression(&builder.expressions[arguments[0]], module, builder, manager)?; + let y = + write_expression(&builder.expressions[arguments[1]], module, builder, manager)?; + let a = + write_expression(&builder.expressions[arguments[2]], module, builder, manager)?; let name = match name.as_str() { "fclamp" => "clamp", @@ -1264,14 +1286,18 @@ fn write_expression<'a, 'b>( Cow::Owned(format!("{}({}, {}, {})", name, x, y, a)) } "atan2" => { - let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; - let y = write_expression(&builder.expressions[arguments[1]], module, builder)?; + let x = + write_expression(&builder.expressions[arguments[0]], module, builder, manager)?; + let y = + write_expression(&builder.expressions[arguments[1]], module, builder, manager)?; Cow::Owned(format!("atan({}, {})", y, x)) } "distance" | "dot" | "min" | "max" | "reflect" | "pow" | "step" | "cross" => { - let x = write_expression(&builder.expressions[arguments[0]], module, builder)?; - let y = write_expression(&builder.expressions[arguments[1]], module, builder)?; + let x = + write_expression(&builder.expressions[arguments[0]], module, builder, manager)?; + let y = + write_expression(&builder.expressions[arguments[1]], module, builder, manager)?; Cow::Owned(format!("{}({}, {})", name, x, y)) } @@ -1283,7 +1309,7 @@ fn write_expression<'a, 'b>( } }, Expression::ArrayLength(expr) => { - let base = write_expression(&builder.expressions[expr], module, builder)?; + let base = write_expression(&builder.expressions[expr], module, builder, manager)?; Cow::Owned(format!("uint({}.length())", base)) } }) @@ -1293,6 +1319,7 @@ fn write_constant( constant: &Constant, module: &Module, builder: &mut StatementBuilder<'_>, + manager: &mut FeaturesManager, ) -> Result { Ok(match constant.inner { ConstantInner::Sint(int) => int.to_string(), @@ -1307,28 +1334,22 @@ fn write_constant( Cow::Owned(format!("mat{}x{}", columns as u8, rows as u8,)), TypeInner::Struct { .. } => Cow::::Borrowed(builder.structs.get(&constant.ty).unwrap()), - TypeInner::Array { .. } => write_type( - constant.ty, - &module.types, - builder.structs, - None, - builder.manager - )?, + TypeInner::Array { .. } => + write_type(constant.ty, &module.types, builder.structs, None, manager)?, _ => return Err(Error::Custom(format!( "Cannot build constant of type {}", - write_type( - constant.ty, - &module.types, - builder.structs, - None, - builder.manager - )? + write_type(constant.ty, &module.types, builder.structs, None, manager)? ))), }, components .iter() - .map(|component| write_constant(&module.constants[*component], module, builder,)) + .map(|component| write_constant( + &module.constants[*component], + module, + builder, + manager + )) .collect::, _>>()? .join(","), ), From 8618a8a2078d00edcf126a40db7ed5219cfd0cc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristoffer=20S=C3=B8holm?= Date: Mon, 2 Nov 2020 23:08:02 +0100 Subject: [PATCH 0262/2212] [ir] Make the interface visitor traverse local variable initializers Otherwise the backends will panic on e.g. `vec4 local = Global;` if the global isn't used anywere else in the function. --- src/back/glsl.rs | 1 + src/proc/interface.rs | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 52122cedb..29e677eae 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1811,6 +1811,7 @@ fn collect_texture_mapping<'a>( for func in functions { let mut interface = Interface { expressions: &func.expressions, + local_variables: &func.local_variables, visitor: TextureMappingVisitor { expressions: &func.expressions, map: &mut mappings, diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 670f2da50..ca20d1958 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -2,6 +2,7 @@ use crate::arena::{Arena, Handle}; pub struct Interface<'a, T> { pub expressions: &'a Arena, + pub local_variables: &'a Arena, pub visitor: T, } @@ -36,7 +37,13 @@ where self.traverse_expr(comp); } } - E::FunctionParameter(_) | E::GlobalVariable(_) | E::LocalVariable(_) => {} + E::FunctionParameter(_) | E::GlobalVariable(_) => {} + E::LocalVariable(var) => { + let var = &self.local_variables[var]; + if let Some(init) = var.init { + self.traverse_expr(init); + } + } E::Load { pointer } => { self.traverse_expr(pointer); } @@ -201,6 +208,7 @@ impl crate::Function { let mut io = Interface { expressions: &self.expressions, + local_variables: &self.local_variables, visitor: GlobalUseVisitor(&mut self.global_usage), }; io.traverse(&self.body); From 973cfbc5d39b0a10c6863d20c30b8eb8a97cac12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristoffer=20S=C3=B8holm?= Date: Mon, 2 Nov 2020 21:40:04 +0100 Subject: [PATCH 0263/2212] [glsl-in] Add support for interface blocks --- src/front/glsl/parser.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b32b711f0..bf10899fc 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1071,7 +1071,29 @@ pomelo! { ); if let Some(id) = id { extra.lookup_global_variables.insert(id, h); + } else { + // variables in interface blocks without an instance name are in the global namespace + // https://www.khronos.org/opengl/wiki/Interface_Block_(GLSL) + if let TypeInner::Struct { members } = &extra.module.types[d.ty].inner { + for m in members { + if let Some(name) = &m.name { + let h = extra + .module + .global_variables + .fetch_or_append(GlobalVariable { + name: Some(name.into()), + class, + binding: binding.clone(), + ty: m.ty, + interpolation, + storage_access: StorageAccess::empty(), // TODO + }); + extra.lookup_global_variables.insert(name.into(), h); + } + } + } } + } } From bb5c9567b56b8dee196cd4a60fa724cefd703c55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristoffer=20S=C3=B8holm?= Date: Mon, 2 Nov 2020 22:57:18 +0100 Subject: [PATCH 0264/2212] [glsl-in] Add xor, small refactor --- src/front/glsl/ast.rs | 4 +-- src/front/glsl/parser.rs | 74 ++++++++++++++++++++-------------------- 2 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index cd7abfdea..a4acf3a91 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -42,8 +42,8 @@ impl Program { pub fn binary_expr( &mut self, op: BinaryOperator, - left: ExpressionRule, - right: ExpressionRule, + left: &ExpressionRule, + right: &ExpressionRule, ) -> ExpressionRule { ExpressionRule::from_expression(self.context.expressions.append(Expression::Binary { op, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index bf10899fc..5e6a16d34 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -8,7 +8,7 @@ pomelo! { use crate::{proc::Typifier, Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, EntryPoint, Expression, FallThrough, FastHashMap, Function, GlobalVariable, Handle, Interpolation, LocalVariable, MemberOrigin, SampleLevel, ScalarKind, Statement, StorageAccess, - StorageClass, StructMember, Type, TypeInner}; + StorageClass, StructMember, Type, TypeInner, UnaryOperator}; } %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; %parser pub struct Parser<'a> {}; @@ -150,9 +150,7 @@ pomelo! { let var = extra.lookup_variable(&v.1)?; match var { Some(expression) => { - ExpressionRule::from_expression( - expression - ) + ExpressionRule::from_expression(expression) }, None => { return Err(ErrorKind::UnknownVariable(v.0, v.1)); @@ -246,11 +244,11 @@ pomelo! { function_call ::= function_call_or_method(fc) { match fc.kind { FunctionCallKind::TypeConstructor(ty) => { - let h = extra.context.expressions.append(Expression::Compose{ + let h = extra.context.expressions.append(Expression::Compose { ty, components: fc.args.iter().map(|a| a.expression).collect(), }); - ExpressionRule{ + ExpressionRule { expression: h, statements: fc.args.into_iter().map(|a| a.statements).flatten().collect(), sampler: None @@ -270,7 +268,7 @@ pomelo! { //TODO: check args len if let Some(sampler) = fc.args[0].sampler { ExpressionRule{ - expression: extra.context.expressions.append(Expression::ImageSample{ + expression: extra.context.expressions.append(Expression::ImageSample { image: fc.args[0].expression, sampler, coordinate: fc.args[1].expression, @@ -358,73 +356,76 @@ pomelo! { unary_operator ::= Tilde; multiplicative_expression ::= unary_expression; multiplicative_expression ::= multiplicative_expression(left) Star unary_expression(right) { - extra.binary_expr(BinaryOperator::Multiply, left, right) + extra.binary_expr(BinaryOperator::Multiply, &left, &right) } multiplicative_expression ::= multiplicative_expression(left) Slash unary_expression(right) { - extra.binary_expr(BinaryOperator::Divide, left, right) + extra.binary_expr(BinaryOperator::Divide, &left, &right) } multiplicative_expression ::= multiplicative_expression(left) Percent unary_expression(right) { - extra.binary_expr(BinaryOperator::Modulo, left, right) + extra.binary_expr(BinaryOperator::Modulo, &left, &right) } additive_expression ::= multiplicative_expression; additive_expression ::= additive_expression(left) Plus multiplicative_expression(right) { - extra.binary_expr(BinaryOperator::Add, left, right) + extra.binary_expr(BinaryOperator::Add, &left, &right) } additive_expression ::= additive_expression(left) Dash multiplicative_expression(right) { - extra.binary_expr(BinaryOperator::Subtract, left, right) + extra.binary_expr(BinaryOperator::Subtract, &left, &right) } shift_expression ::= additive_expression; shift_expression ::= shift_expression(left) LeftOp additive_expression(right) { - extra.binary_expr(BinaryOperator::ShiftLeft, left, right) + extra.binary_expr(BinaryOperator::ShiftLeft, &left, &right) } shift_expression ::= shift_expression(left) RightOp additive_expression(right) { - extra.binary_expr(BinaryOperator::ShiftRight, left, right) + extra.binary_expr(BinaryOperator::ShiftRight, &left, &right) } relational_expression ::= shift_expression; relational_expression ::= relational_expression(left) LeftAngle shift_expression(right) { - extra.binary_expr(BinaryOperator::Less, left, right) + extra.binary_expr(BinaryOperator::Less, &left, &right) } relational_expression ::= relational_expression(left) RightAngle shift_expression(right) { - extra.binary_expr(BinaryOperator::Greater, left, right) + extra.binary_expr(BinaryOperator::Greater, &left, &right) } relational_expression ::= relational_expression(left) LeOp shift_expression(right) { - extra.binary_expr(BinaryOperator::LessEqual, left, right) + extra.binary_expr(BinaryOperator::LessEqual, &left, &right) } relational_expression ::= relational_expression(left) GeOp shift_expression(right) { - extra.binary_expr(BinaryOperator::GreaterEqual, left, right) + extra.binary_expr(BinaryOperator::GreaterEqual, &left, &right) } equality_expression ::= relational_expression; equality_expression ::= equality_expression(left) EqOp relational_expression(right) { - extra.binary_expr(BinaryOperator::Equal, left, right) + extra.binary_expr(BinaryOperator::Equal, &left, &right) } equality_expression ::= equality_expression(left) NeOp relational_expression(right) { - extra.binary_expr(BinaryOperator::NotEqual, left, right) + extra.binary_expr(BinaryOperator::NotEqual, &left, &right) } and_expression ::= equality_expression; and_expression ::= and_expression(left) Ampersand equality_expression(right) { - extra.binary_expr(BinaryOperator::And, left, right) + extra.binary_expr(BinaryOperator::And, &left, &right) } exclusive_or_expression ::= and_expression; exclusive_or_expression ::= exclusive_or_expression(left) Caret and_expression(right) { - extra.binary_expr(BinaryOperator::ExclusiveOr, left, right) + extra.binary_expr(BinaryOperator::ExclusiveOr, &left, &right) } inclusive_or_expression ::= exclusive_or_expression; inclusive_or_expression ::= inclusive_or_expression(left) VerticalBar exclusive_or_expression(right) { - extra.binary_expr(BinaryOperator::InclusiveOr, left, right) + extra.binary_expr(BinaryOperator::InclusiveOr, &left, &right) } logical_and_expression ::= inclusive_or_expression; logical_and_expression ::= logical_and_expression(left) AndOp inclusive_or_expression(right) { - extra.binary_expr(BinaryOperator::LogicalAnd, left, right) + extra.binary_expr(BinaryOperator::LogicalAnd, &left, &right) } logical_xor_expression ::= logical_and_expression; logical_xor_expression ::= logical_xor_expression(left) XorOp logical_and_expression(right) { - return Err(ErrorKind::NotImplemented("logical xor")) - //TODO: naga doesn't have BinaryOperator::LogicalXor - // extra.context.expressions.append(Expression::Binary{op: BinaryOperator::LogicalXor, left, right}) + let exp1 = extra.binary_expr(BinaryOperator::LogicalOr, &left, &right); + let exp2 = { + let tmp = extra.binary_expr(BinaryOperator::LogicalAnd, &left, &right).expression; + ExpressionRule::from_expression(extra.context.expressions.append(Expression::Unary { op: UnaryOperator::Not, expr: tmp })) + }; + extra.binary_expr(BinaryOperator::LogicalAnd, &exp1, &exp2) } logical_or_expression ::= logical_xor_expression; logical_or_expression ::= logical_or_expression(left) OrOp logical_xor_expression(right) { - extra.binary_expr(BinaryOperator::LogicalOr, left, right) + extra.binary_expr(BinaryOperator::LogicalOr, &left, &right) } conditional_expression ::= logical_or_expression; @@ -498,7 +499,7 @@ pomelo! { expression ::= assignment_expression; expression ::= expression(e) Comma assignment_expression(mut ae) { ae.statements.extend(e.statements); - ExpressionRule{ + ExpressionRule { expression: e.expression, statements: ae.statements, sampler: None, @@ -521,7 +522,7 @@ pomelo! { declaration ::= type_qualifier(t) Identifier(i) LeftBrace struct_declaration_list(sdl) RightBrace Semicolon { - VarDeclaration{ + VarDeclaration { type_qualifiers: t, ids_initializers: vec![(None, None)], ty: extra.module.types.fetch_or_append(Type{ @@ -535,7 +536,7 @@ pomelo! { declaration ::= type_qualifier(t) Identifier(i1) LeftBrace struct_declaration_list(sdl) RightBrace Identifier(i2) Semicolon { - VarDeclaration{ + VarDeclaration { type_qualifiers: t, ids_initializers: vec![(Some(i2.1), None)], ty: extra.module.types.fetch_or_append(Type{ @@ -565,7 +566,7 @@ pomelo! { single_declaration ::= fully_specified_type(t) { let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; - VarDeclaration{ + VarDeclaration { type_qualifiers: t.0, ids_initializers: vec![], ty, @@ -574,7 +575,7 @@ pomelo! { single_declaration ::= fully_specified_type(t) Identifier(i) { let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; - VarDeclaration{ + VarDeclaration { type_qualifiers: t.0, ids_initializers: vec![(Some(i.1), None)], ty, @@ -585,7 +586,7 @@ pomelo! { single_declaration ::= fully_specified_type(t) Identifier(i) Equal initializer(init) { let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; - VarDeclaration{ + VarDeclaration { type_qualifiers: t.0, ids_initializers: vec![(Some(i.1), Some(init))], ty, @@ -715,7 +716,7 @@ pomelo! { struct_declaration ::= type_specifier(t) struct_declarator_list(sdl) Semicolon { if let Some(ty) = t { - sdl.iter().map(|name| StructMember{ + sdl.iter().map(|name| StructMember { name: Some(name.clone()), origin: MemberOrigin::Empty, ty, @@ -1007,7 +1008,7 @@ pomelo! { Statement::Break } jump_statement ::= Return Semicolon { - Statement::Return{ value: None } + Statement::Return { value: None } } jump_statement ::= Return expression(mut e) Semicolon { let ret = Statement::Return{ value: Some(e.expression) }; @@ -1093,7 +1094,6 @@ pomelo! { } } } - } } From 6480370a19a0f32cf87323b83b97d65833b1590e Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 3 Nov 2020 21:18:30 +0100 Subject: [PATCH 0265/2212] [spv-out] Handle ImageSample (#261) --- src/back/spv/instructions.rs | 34 ++++++++ src/back/spv/writer.rs | 153 +++++++++++++++++++++++++++++++++-- 2 files changed, 180 insertions(+), 7 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 077522e91..a69c09b37 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -235,6 +235,13 @@ pub(super) fn instruction_type_sampler(id: Word) -> Instruction { instruction } +pub(super) fn instruction_type_sampled_image(id: Word, image_type_id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::TypeSampledImage); + instruction.set_result(id); + instruction.add_operand(image_type_id); + instruction +} + pub(super) fn instruction_type_array( id: Word, element_type_id: Word, @@ -449,6 +456,33 @@ pub(super) fn instruction_function_call( // // Image Instructions // +pub(super) fn instruction_sampled_image( + result_type_id: Word, + id: Word, + image: Word, + sampler: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::SampledImage); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(image); + instruction.add_operand(sampler); + instruction +} + +pub(super) fn instruction_image_sample_implicit_lod( + result_type_id: Word, + id: Word, + sampled_image: Word, + coordinates: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::ImageSampleImplicitLod); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(sampled_image); + instruction.add_operand(coordinates); + instruction +} // // Conversion Instructions diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b0e0a400c..159869bec 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -10,6 +10,12 @@ const BITS_PER_BYTE: crate::Bytes = 8; pub enum Error { #[error("can't find local variable: {0:?}")] UnknownLocalVariable(crate::LocalVariable), + #[error("bad image class for op: {0:?}")] + BadImageClass(crate::ImageClass), + #[error("not an image")] + NotImage, + #[error("empty value")] + EmptyValue, } struct Block { @@ -86,6 +92,9 @@ enum LocalType { base: crate::Handle, class: spirv::StorageClass, }, + SampledImage { + image_type: crate::Handle, + }, } #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] @@ -447,6 +456,10 @@ impl Writer { super::instructions::instruction_type_vector(id, scalar_id, size) } LocalType::Pointer { .. } => unimplemented!(), + LocalType::SampledImage { image_type } => { + let image_type_id = self.get_type_id(arena, LookupType::Handle(image_type)); + super::instructions::instruction_type_sampled_image(id, image_type_id) + } }; self.lookup_type.insert(LookupType::Local(local_ty), id); @@ -499,17 +512,14 @@ impl Writer { } => { let width = 4; let local_type = match class { - crate::ImageClass::Sampled { kind, multi: _ } => LocalType::Vector { - size: crate::VectorSize::Quad, - kind, - width, - }, + crate::ImageClass::Sampled { kind, multi: _ } => { + LocalType::Scalar { kind, width } + } crate::ImageClass::Depth => LocalType::Scalar { kind: crate::ScalarKind::Float, width, }, - crate::ImageClass::Storage(format) => LocalType::Vector { - size: crate::VectorSize::Quad, + crate::ImageClass::Storage(format) => LocalType::Scalar { kind: format.into(), width, }, @@ -1189,6 +1199,135 @@ impl Writer { Ok(Some((id, None))) } + crate::Expression::ImageSample { + image, + sampler, + coordinate, + level: _, + depth_ref: _, + } => { + // image + let image_expression = &ir_function.expressions[*image]; + let (image_id, image_ty) = self + .write_expression(ir_module, ir_function, image_expression, block, function)? + .ok_or(Error::EmptyValue)?; + let image_ty = image_ty.ok_or(Error::EmptyValue)?; + let image_result_type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(image_ty)); + let image_id = match *image_expression { + crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + image_result_type_id, + load_id, + image_id, + None, + )); + load_id + } + _ => image_id, + }; + + // OpTypeSampledImage + let sampled_image_type_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::SampledImage { + image_type: image_ty, + }), + ); + + // sampler + let sampler_expression = &ir_function.expressions[*sampler]; + let (sampler_id, sampler_ty) = self + .write_expression(ir_module, ir_function, sampler_expression, block, function)? + .ok_or(Error::EmptyValue)?; + let sampler_ty = sampler_ty.ok_or(Error::EmptyValue)?; + let sampler_result_type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(sampler_ty)); + let sampler_id = match *sampler_expression { + crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + sampler_result_type_id, + load_id, + sampler_id, + None, + )); + load_id + } + _ => sampler_id, + }; + + // coordinate + let coordinate_expression = &ir_function.expressions[*coordinate]; + let (coordinate_id, coordinate_ty) = self + .write_expression( + ir_module, + ir_function, + coordinate_expression, + block, + function, + )? + .ok_or(Error::EmptyValue)?; + let coordinate_ty = coordinate_ty.ok_or(Error::EmptyValue)?; + let coordinate_result_type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(coordinate_ty)); + let coordinate_id = match *coordinate_expression { + crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + coordinate_result_type_id, + load_id, + coordinate_id, + None, + )); + load_id + } + _ => coordinate_id, + }; + + // component kind + let image_type = &ir_module.types[image_ty]; + let image_sample_result_type = + if let crate::TypeInner::Image { class, .. } = image_type.inner { + let width = 4; + let local_type = match class { + crate::ImageClass::Sampled { kind, multi: _ } => LocalType::Vector { + kind, + width, + size: crate::VectorSize::Quad, + }, + crate::ImageClass::Depth => LocalType::Scalar { + kind: crate::ScalarKind::Float, + width, + }, + _ => return Err(Error::BadImageClass(class)), + }; + self.get_type_id(&ir_module.types, LookupType::Local(local_type)) + } else { + return Err(Error::NotImage); + }; + + let sampled_image_id = self.generate_id(); + block + .body + .push(super::instructions::instruction_sampled_image( + sampled_image_type_id, + sampled_image_id, + image_id, + sampler_id, + )); + let id = self.generate_id(); + block + .body + .push(super::instructions::instruction_image_sample_implicit_lod( + image_sample_result_type, + id, + sampled_image_id, + coordinate_id, + )); + Ok(Some((id, None))) + } _ => unimplemented!("{:?}", expression), } } From b61b100fa3791799d6664e1079ef66beb9c83df6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 2 Nov 2020 19:34:37 -0500 Subject: [PATCH 0266/2212] [ir] LocalVariableError --- src/proc/validator.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index de37ec576..27576433a 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -32,12 +32,26 @@ pub enum GlobalVariableError { OutOfRangeBinding, } +#[derive(Clone, Debug, thiserror::Error)] +pub enum LocalVariableError { + #[error("Initializer is not a constant expression")] + InitializerConst, + #[error("Initializer doesn't match the variable type")] + InitializerType, +} + #[derive(Clone, Debug, thiserror::Error)] pub enum FunctionError { #[error(transparent)] Resolve(#[from] ResolveError), #[error("There are instructions after `return`/`break`/`continue`")] InvalidControlFlowExitTail, + #[error("Local variable {handle:?} '{name}' is invalid: {error:?}")] + LocalVariable { + handle: Handle, + name: String, + error: LocalVariableError, + }, } #[derive(Clone, Debug, thiserror::Error)] @@ -209,6 +223,21 @@ impl Validator { Ok(()) } + fn validate_local_var( + &self, + var: &crate::LocalVariable, + _fun: &crate::Function, + _types: &Arena, + ) -> Result<(), LocalVariableError> { + log::debug!("var {:?}", var); + if let Some(_expr_handle) = var.init { + if false { + return Err(LocalVariableError::InitializerConst); + } + } + Ok(()) + } + fn validate_function( &mut self, fun: &crate::Function, @@ -223,6 +252,15 @@ impl Validator { }; self.typifier .resolve_all(&fun.expressions, &module.types, &resolve_ctx)?; + + for (var_handle, var) in fun.local_variables.iter() { + self.validate_local_var(var, fun, &module.types) + .map_err(|error| FunctionError::LocalVariable { + handle: var_handle, + name: var.name.clone().unwrap_or_default(), + error, + })?; + } Ok(()) } From 41b3865e5bb41b846e206de1a7bd57fbc1cc8f20 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 3 Nov 2020 23:26:25 -0500 Subject: [PATCH 0267/2212] Make variable initializers to be const --- src/back/glsl.rs | 2 +- src/back/msl.rs | 8 +++- src/back/spv/writer.rs | 89 +++++++++++++++++-------------------- src/front/glsl/parser.rs | 41 ++++++++--------- src/front/glsl/variables.rs | 2 + src/front/spv/mod.rs | 15 ++++--- src/front/wgsl/mod.rs | 64 +++++++++++++------------- src/lib.rs | 7 +-- src/proc/interface.rs | 9 +--- test-data/simple/module.ron | 4 +- 10 files changed, 119 insertions(+), 122 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 29e677eae..7c2d84c57 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -706,7 +706,7 @@ pub fn write<'a>( write!( &mut buf, " = {}", - write_expression(&func.expressions[init], module, &mut builder, &mut manager)? + write_constant(&module.constants[init], module, &mut builder, &mut manager)? )?; } writeln!(&mut buf, ";")?; diff --git a/src/back/msl.rs b/src/back/msl.rs index cade25218..6aa52d062 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -1025,7 +1025,7 @@ impl Writer { )?; if let Some(value) = local.init { write!(self.out, " = ")?; - self.put_expression(value, fun, module)?; + self.put_constant(value, module)?; } writeln!(self.out, ";")?; } @@ -1235,6 +1235,10 @@ impl Writer { write!(self.out, "\t")?; tyvar.try_fmt(&mut self.out)?; resolved.try_fmt_decorated(&mut self.out, separator)?; + if let Some(value) = var.init { + write!(self.out, " = ")?; + self.put_constant(value, module)?; + } writeln!(self.out)?; } writeln!(self.out, ") {{")?; @@ -1255,7 +1259,7 @@ impl Writer { )?; if let Some(value) = local.init { write!(self.out, " = ")?; - self.put_expression(value, fun, module)?; + self.put_constant(value, module)?; } writeln!(self.out, ";")?; } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 159869bec..32b5e53d9 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -195,15 +195,13 @@ impl Writer { fn get_global_variable_id( &mut self, - arena: &crate::Arena, - global_arena: &crate::Arena, + ir_module: &crate::Module, handle: crate::Handle, ) -> Word { match self.lookup_global_variable.entry(handle) { Entry::Occupied(e) => *e.get(), _ => { - let global_variable = &global_arena[handle]; - let (instruction, id) = self.write_global_variable(arena, global_variable, handle); + let (instruction, id) = self.write_global_variable(ir_module, handle); instruction.to_words(&mut self.logical_layout.declarations); id } @@ -277,15 +275,9 @@ impl Writer { for (_, variable) in ir_function.local_variables.iter() { let id = self.generate_id(); - let init_word = match variable.init { - Some(exp) => match &ir_function.expressions[exp] { - crate::Expression::Constant(handle) => { - Some(self.get_constant_id(*handle, ir_module)) - } - _ => unreachable!(), - }, - None => None, - }; + let init_word = variable + .init + .map(|constant| self.get_constant_id(constant, ir_module)); let pointer_id = self.get_pointer_id(&ir_module.types, variable.ty, spirv::StorageClass::Function); @@ -372,11 +364,7 @@ impl Writer { .zip(&entry_point.function.global_usage) { if usage.contains(crate::GlobalUse::STORE) || usage.contains(crate::GlobalUse::LOAD) { - let id = self.get_global_variable_id( - &ir_module.types, - &ir_module.global_variables, - handle, - ); + let id = self.get_global_variable_id(ir_module, handle); interface_ids.push(id); } } @@ -681,17 +669,21 @@ impl Writer { fn write_global_variable( &mut self, - arena: &crate::Arena, - global_variable: &crate::GlobalVariable, + ir_module: &crate::Module, handle: crate::Handle, ) -> (Instruction, Word) { + let global_variable = &ir_module.global_variables[handle]; let id = self.generate_id(); let class = self.parse_to_spirv_storage_class(global_variable.class); self.try_add_capabilities(class.required_capabilities()); - let pointer_id = self.get_pointer_id(arena, global_variable.ty, class); - let instruction = super::instructions::instruction_variable(pointer_id, id, class, None); + let init_word = global_variable + .init + .map(|constant| self.get_constant_id(constant, ir_module)); + let pointer_id = self.get_pointer_id(&ir_module.types, global_variable.ty, class); + let instruction = + super::instructions::instruction_variable(pointer_id, id, class, init_word); if self.writer_flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = global_variable.name { @@ -825,23 +817,19 @@ impl Writer { block: &mut Block, function: &mut Function, ) -> Result { - match expression { + match *expression { crate::Expression::GlobalVariable(handle) => { - let var = &ir_module.global_variables[*handle]; - let id = self.get_global_variable_id( - &ir_module.types, - &ir_module.global_variables, - *handle, - ); + let var = &ir_module.global_variables[handle]; + let id = self.get_global_variable_id(ir_module, handle); Ok(Some((id, Some(var.ty)))) } crate::Expression::Constant(handle) => { - let var = &ir_module.constants[*handle]; - let id = self.get_constant_id(*handle, ir_module); + let var = &ir_module.constants[handle]; + let id = self.get_constant_id(handle, ir_module); Ok(Some((id, Some(var.ty)))) } - crate::Expression::Compose { ty, components } => { - let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*ty)); + crate::Expression::Compose { ty, ref components } => { + let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty)); let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { @@ -853,7 +841,7 @@ impl Writer { } let constituent_ids_slice = constituent_ids.as_slice(); - let id = match ir_module.types[*ty].inner { + let id = match ir_module.types[ty].inner { crate::TypeInner::Vector { .. } => { self.write_composite_construct(base_type_id, constituent_ids_slice, block) } @@ -893,14 +881,14 @@ impl Writer { _ => unreachable!(), }; - Ok(Some((id, Some(*ty)))) + Ok(Some((id, Some(ty)))) } crate::Expression::Binary { op, left, right } => { match op { crate::BinaryOperator::Multiply => { let id = self.generate_id(); - let left_expression = &ir_function.expressions[*left]; - let right_expression = &ir_function.expressions[*right]; + let left_expression = &ir_function.expressions[left]; + let right_expression = &ir_function.expressions[right]; let (left_id, left_ty) = self .write_expression( ir_module, @@ -1049,7 +1037,7 @@ impl Writer { } } crate::Expression::LocalVariable(variable) => { - let var = &ir_function.local_variables[*variable]; + let var = &ir_function.local_variables[variable]; function .variables .iter() @@ -1058,19 +1046,22 @@ impl Writer { .ok_or_else(|| Error::UnknownLocalVariable(var.clone())) } crate::Expression::FunctionParameter(index) => { - let handle = ir_function.parameter_types.get(*index as usize).unwrap(); + let handle = ir_function.parameter_types.get(index as usize).unwrap(); let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*handle)); let load_id = self.generate_id(); block.body.push(super::instructions::instruction_load( type_id, load_id, - function.parameters[*index as usize].result_id.unwrap(), + function.parameters[index as usize].result_id.unwrap(), None, )); Ok(Some((load_id, Some(*handle)))) } - crate::Expression::Call { origin, arguments } => match origin { + crate::Expression::Call { + ref origin, + ref arguments, + } => match origin { crate::FunctionOrigin::Local(local_function) => { let origin_function = &ir_module.functions[*local_function]; let id = self.generate_id(); @@ -1119,7 +1110,7 @@ impl Writer { .push(super::instructions::instruction_function_call( return_type_id, id, - *self.lookup_function.get(local_function).unwrap(), + *self.lookup_function.get(&local_function).unwrap(), argument_ids.as_slice(), )); Ok(Some((id, None))) @@ -1139,7 +1130,7 @@ impl Writer { .write_expression( ir_module, ir_function, - &ir_function.expressions[*expr], + &ir_function.expressions[expr], block, function, )? @@ -1153,10 +1144,10 @@ impl Writer { } => { let kind_type_id = self.get_type_id( &ir_module.types, - LookupType::Local(LocalType::Scalar { kind: *kind, width }), + LookupType::Local(LocalType::Scalar { kind, width }), ); - if *convert { + if convert { super::instructions::instruction_bit_cast(kind_type_id, id, expr_id) } else { match (expr_kind, kind) { @@ -1207,7 +1198,7 @@ impl Writer { depth_ref: _, } => { // image - let image_expression = &ir_function.expressions[*image]; + let image_expression = &ir_function.expressions[image]; let (image_id, image_ty) = self .write_expression(ir_module, ir_function, image_expression, block, function)? .ok_or(Error::EmptyValue)?; @@ -1237,7 +1228,7 @@ impl Writer { ); // sampler - let sampler_expression = &ir_function.expressions[*sampler]; + let sampler_expression = &ir_function.expressions[sampler]; let (sampler_id, sampler_ty) = self .write_expression(ir_module, ir_function, sampler_expression, block, function)? .ok_or(Error::EmptyValue)?; @@ -1259,7 +1250,7 @@ impl Writer { }; // coordinate - let coordinate_expression = &ir_function.expressions[*coordinate]; + let coordinate_expression = &ir_function.expressions[coordinate]; let (coordinate_id, coordinate_ty) = self .write_expression( ir_module, @@ -1469,7 +1460,7 @@ impl Writer { } for (handle, _) in ir_module.global_variables.iter() { - self.get_global_variable_id(&ir_module.types, &ir_module.global_variables, handle); + self.get_global_variable_id(ir_module, handle); } for (handle, _) in ir_module.constants.iter() { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 5e6a16d34..69827f963 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -760,18 +760,33 @@ pomelo! { return Err(ErrorKind::VariableAlreadyDeclared(id)) } } + let mut init_exp: Option> = None; let localVar = extra.context.local_variables.append( LocalVariable { name: Some(id.clone()), ty: d.ty, init: initializer.map(|i| { statements.extend(i.statements); - i.expression - }), + if let Expression::Constant(constant) = extra.context.expressions[i.expression] { + Some(constant) + } else { + init_exp = Some(i.expression); + None + } + }).flatten(), } ); let exp = extra.context.expressions.append(Expression::LocalVariable(localVar)); extra.context.add_local_var(id, exp); + + if let Some(value) = init_exp { + statements.push( + Statement::Store { + pointer: exp, + value, + } + ); + } } match statements.len() { 1 => statements.remove(0), @@ -1066,33 +1081,13 @@ pomelo! { class, binding: binding.clone(), ty: d.ty, + init: None, interpolation, storage_access: StorageAccess::empty(), //TODO }, ); if let Some(id) = id { extra.lookup_global_variables.insert(id, h); - } else { - // variables in interface blocks without an instance name are in the global namespace - // https://www.khronos.org/opengl/wiki/Interface_Block_(GLSL) - if let TypeInner::Struct { members } = &extra.module.types[d.ty].inner { - for m in members { - if let Some(name) = &m.name { - let h = extra - .module - .global_variables - .fetch_or_append(GlobalVariable { - name: Some(name.into()), - class, - binding: binding.clone(), - ty: m.ty, - interpolation, - storage_access: StorageAccess::empty(), // TODO - }); - extra.lookup_global_variables.insert(name.into(), h); - } - } - } } } } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index c4d37b7bb..9f7633568 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -38,6 +38,7 @@ impl Program { width: 4, }, }), + init: None, interpolation: None, storage_access: StorageAccess::empty(), }); @@ -72,6 +73,7 @@ impl Program { width: 4, }, }), + init: None, interpolation: None, storage_access: StorageAccess::empty(), }); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index b59fd239b..f5aca1cf4 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -554,8 +554,8 @@ impl> Parser { let init = if inst.wc > 4 { inst.expect(5)?; let init_id = self.next()?; - let lexp = self.lookup_expression.lookup(init_id)?; - Some(lexp.handle) + let lconst = self.lookup_constant.lookup(init_id)?; + Some(lconst.handle) } else { None }; @@ -2271,10 +2271,14 @@ impl> Parser { let type_id = self.next()?; let id = self.next()?; let storage_class = self.next()?; - if inst.wc != 4 { + let init = if inst.wc > 4 { inst.expect(5)?; - let _init = self.next()?; //TODO - } + let init_id = self.next()?; + let lconst = self.lookup_constant.lookup(init_id)?; + Some(lconst.handle) + } else { + None + }; let lookup_type = self.lookup_type.lookup(type_id)?; let dec = self .future_decor @@ -2338,6 +2342,7 @@ impl> Parser { class, binding, ty: lookup_type.handle, + init, interpolation: dec.interpolation, storage_access, }; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 05c274994..ee84b040b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -36,8 +36,6 @@ pub enum Token<'a> { pub enum Error<'a> { #[error("unexpected token: {0:?}")] Unexpected(Token<'a>), - #[error("constant {0:?} doesn't match its type {1:?}")] - UnexpectedConstantType(crate::ConstantInner, Handle), #[error("unable to parse `{0}` as integer: {1}")] BadInteger(&'a str, std::num::ParseIntError), #[error("unable to parse `{1}` as float: {1}")] @@ -264,6 +262,7 @@ struct ParsedVariable<'a> { class: Option, ty: Handle, access: crate::StorageAccess, + init: Option>, } #[derive(Clone, Debug, Error)] @@ -374,9 +373,10 @@ impl Parser { fn parse_const_expression<'a>( &mut self, lexer: &mut Lexer<'a>, + self_ty: Handle, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result> { + ) -> Result, Error<'a>> { self.scopes.push(Scope::ConstantExpr); let inner = match lexer.peek() { Token::Word("true") => { @@ -405,19 +405,21 @@ impl Parser { composite_ty, components.len(), )?; - let inner = self.parse_const_expression(lexer, type_arena, const_arena)?; - components.push(const_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner, - ty, - })); + let component = + self.parse_const_expression(lexer, ty, type_arena, const_arena)?; + components.push(component); } crate::ConstantInner::Composite(components) } }; + let handle = const_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner, + ty: self_ty, + }); self.scopes.pop(); - Ok(inner) + Ok(handle) } fn parse_primary_expression<'a>( @@ -943,10 +945,12 @@ impl Parser { } _ => crate::StorageAccess::empty(), }; - if lexer.skip(Token::Operation('=')) { - let _inner = self.parse_const_expression(lexer, type_arena, const_arena)?; - //TODO - } + let init = if lexer.skip(Token::Operation('=')) { + let handle = self.parse_const_expression(lexer, ty, type_arena, const_arena)?; + Some(handle) + } else { + None + }; lexer.expect(Token::Separator(';'))?; self.scopes.pop(); Ok(ParsedVariable { @@ -954,6 +958,7 @@ impl Parser { class, ty, access, + init, }) } @@ -1373,15 +1378,16 @@ impl Parser { "var" => { enum Init { Empty, - Uniform(Handle), + Constant(Handle), Variable(Handle), } let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; let init = if lexer.skip(Token::Operation('=')) { let value = self.parse_general_expression(lexer, context.as_expression())?; - if let crate::Expression::Constant(_) = context.expressions[value] { - Init::Uniform(value) + if let crate::Expression::Constant(handle) = context.expressions[value] + { + Init::Constant(handle) } else { Init::Variable(value) } @@ -1393,7 +1399,7 @@ impl Parser { name: Some(name.to_owned()), ty, init: match init { - Init::Uniform(value) => Some(value), + Init::Constant(value) => Some(value), _ => None, }, }); @@ -1692,18 +1698,13 @@ impl Parser { Token::Word("const") => { let (name, ty) = self.parse_variable_ident_decl(lexer, &mut module.types)?; lexer.expect(Token::Operation('='))?; - let inner = - self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; - lexer.expect(Token::Separator(';'))?; - if !crate::proc::check_constant_type(&inner, &module.types[ty].inner) { - return Err(Error::UnexpectedConstantType(inner, ty)); - } - let const_handle = module.constants.append(crate::Constant { - name: Some(name.to_owned()), - specialization: None, - inner, + let const_handle = self.parse_const_expression( + lexer, ty, - }); + &mut module.types, + &mut module.constants, + )?; + lexer.expect(Token::Separator(';'))?; lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); } Token::Word("var") => { @@ -1725,6 +1726,7 @@ impl Parser { class, binding: binding.take(), ty: pvar.ty, + init: pvar.init, interpolation, storage_access: pvar.access, }); @@ -1813,5 +1815,5 @@ pub fn parse_str(source: &str) -> Result { #[test] fn parse_types() { assert!(parse_str("const a : i32 = 2;").is_ok()); - assert!(parse_str("const a : i32 = 2.0;").is_err()); + assert!(parse_str("const a : x32 = 2;").is_err()); } diff --git a/src/lib.rs b/src/lib.rs index c8c1b0107..ceec1f2b8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -406,8 +406,7 @@ pub struct Constant { } /// Additional information, dependendent on the kind of constant. -// Clone is used only for error reporting and is not intended for end users -#[derive(Clone, Debug, PartialEq)] +#[derive(Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ConstantInner { @@ -456,6 +455,8 @@ pub struct GlobalVariable { pub binding: Option, /// The type of this variable. pub ty: Handle, + /// Initial value for this variable. + pub init: Option>, /// The interpolation qualifier, if any. /// If the this `GlobalVariable` is a vertex output /// or fragment input, `None` corresponds to the @@ -475,7 +476,7 @@ pub struct LocalVariable { /// The type of this variable. pub ty: Handle, /// Initial value for this variable. - pub init: Option>, + pub init: Option>, } /// Operation that can be applied on a single value. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index ca20d1958..03cbf3e40 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -37,13 +37,7 @@ where self.traverse_expr(comp); } } - E::FunctionParameter(_) | E::GlobalVariable(_) => {} - E::LocalVariable(var) => { - let var = &self.local_variables[var]; - if let Some(init) = var.init { - self.traverse_expr(init); - } - } + E::FunctionParameter(_) | E::GlobalVariable(_) | E::LocalVariable(_) => {} E::Load { pointer } => { self.traverse_expr(pointer); } @@ -229,6 +223,7 @@ mod tests { class: StorageClass::Uniform, binding: None, ty: Handle::new(std::num::NonZeroU32::new(1).unwrap()), + init: None, interpolation: None, storage_access: StorageAccess::empty(), }; diff --git a/test-data/simple/module.ron b/test-data/simple/module.ron index c3c34fc6b..bcc93f020 100644 --- a/test-data/simple/module.ron +++ b/test-data/simple/module.ron @@ -48,6 +48,7 @@ class: Input, binding: Some(Location(0)), ty: 1, + init: None, interpolation: None, storage_access: ( bits: 0, @@ -58,6 +59,7 @@ class: Output, binding: Some(Location(0)), ty: 2, + init: None, interpolation: None, storage_access: ( bits: 0, @@ -85,7 +87,7 @@ ( name: Some("w"), ty: 3, - init: Some(3), + init: Some(1), ), ], expressions: [ From f8876dac733a5497527277571707b88cbee37ae8 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sat, 3 Oct 2020 22:48:35 +0200 Subject: [PATCH 0268/2212] [spv-out] Add AccessChain and AccessIndex instructions --- src/back/spv/instructions.rs | 18 ++ src/back/spv/writer.rs | 467 ++++++++++++++++++++++++----------- 2 files changed, 334 insertions(+), 151 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index a69c09b37..6741dbbf6 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -406,6 +406,24 @@ pub(super) fn instruction_store( instruction } +pub(super) fn instruction_access_chain( + result_type_id: Word, + id: Word, + base_id: Word, + index_ids: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::AccessChain); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(base_id); + + for index_id in index_ids { + instruction.add_operand(*index_id); + } + + instruction +} + // // Function Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 32b5e53d9..879dcd829 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,7 +1,7 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ use super::{Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; use spirv::Word; -use std::collections::hash_map::Entry; +use std::{collections::hash_map::Entry, ops}; use thiserror::Error; const BITS_PER_BYTE: crate::Bytes = 8; @@ -16,6 +16,8 @@ pub enum Error { NotImage, #[error("empty value")] EmptyValue, + #[error("feature is not yet implemented")] + FeatureNotImplemented(), } struct Block { @@ -90,7 +92,7 @@ enum LocalType { }, Pointer { base: crate::Handle, - class: spirv::StorageClass, + class: crate::StorageClass, }, SampledImage { image_type: crate::Handle, @@ -118,6 +120,21 @@ struct LookupFunctionType { return_type_id: Word, } +enum MaybeOwned<'a, T> { + Owned(T), + Borrowed(&'a T), +} + +impl<'a, T> ops::Deref for MaybeOwned<'a, T> { + type Target = T; + fn deref(&self) -> &T { + match *self { + MaybeOwned::Owned(ref value) => value, + MaybeOwned::Borrowed(reference) => reference, + } + } +} + pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, @@ -135,7 +152,7 @@ pub struct Writer { } // type alias, for success return of write_expression -type WriteExpressionOutput = Option<(Word, Option>)>; +type WriteExpressionOutput = (Word, Option); impl Writer { pub fn new(header: &crate::Header, writer_flags: WriterFlags) -> Self { @@ -232,7 +249,7 @@ impl Writer { &mut self, arena: &crate::Arena, handle: crate::Handle, - class: spirv::StorageClass, + class: crate::StorageClass, ) -> Word { let ty = &arena[handle]; let ty_id = self.get_type_id(arena, LookupType::Handle(handle)); @@ -247,24 +264,36 @@ impl Writer { })) { Entry::Occupied(e) => *e.get(), _ => { - let pointer_id = self.generate_id(); - let instruction = - super::instructions::instruction_type_pointer(pointer_id, class, ty_id); - instruction.to_words(&mut self.logical_layout.declarations); + let id = + self.create_pointer(ty_id, self.parse_to_spirv_storage_class(class)); self.lookup_type.insert( LookupType::Local(LocalType::Pointer { base: handle, class, }), - pointer_id, + id, ); - pointer_id + id } } } } } + fn create_pointer(&mut self, ty_id: Word, class: spirv::StorageClass) -> Word { + let id = self.generate_id(); + let instruction = super::instructions::instruction_type_pointer(id, class, ty_id); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + + fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word { + let id = self.generate_id(); + let instruction = super::instructions::instruction_constant(type_id, id, value); + instruction.to_words(&mut self.logical_layout.declarations); + id + } + fn write_function( &mut self, ir_function: &crate::Function, @@ -280,7 +309,7 @@ impl Writer { .map(|constant| self.get_constant_id(constant, ir_module)); let pointer_id = - self.get_pointer_id(&ir_module.types, variable.ty, spirv::StorageClass::Function); + self.get_pointer_id(&ir_module.types, variable.ty, crate::StorageClass::Function); function.variables.push(LocalVariable { id, name: variable.name.clone(), @@ -304,7 +333,7 @@ impl Writer { let pointer_id = self.get_pointer_id( &ir_module.types, *parameter_type, - spirv::StorageClass::Function, + crate::StorageClass::Function, ); function_parameter_pointer_ids.push(pointer_id); @@ -361,6 +390,9 @@ impl Writer { for ((handle, _), &usage) in ir_module .global_variables .iter() + .filter(|&(_, var)| { + var.class == crate::StorageClass::Input || var.class == crate::StorageClass::Output + }) .zip(&entry_point.function.global_usage) { if usage.contains(crate::GlobalUse::STORE) || usage.contains(crate::GlobalUse::LOAD) { @@ -520,7 +552,7 @@ impl Writer { crate::TypeInner::Sampler { comparison: _ } => { super::instructions::instruction_type_sampler(id) } - crate::TypeInner::Array { size, stride, .. } => { + crate::TypeInner::Array { base, size, stride } => { if let Some(array_stride) = stride { self.annotations .push(super::instructions::instruction_decorate( @@ -530,7 +562,7 @@ impl Writer { )); } - let type_id = self.get_type_id(arena, LookupType::Handle(handle)); + let type_id = self.get_type_id(arena, LookupType::Handle(base)); match size { crate::ArraySize::Static(length) => { super::instructions::instruction_type_array(id, type_id, length) @@ -550,13 +582,8 @@ impl Writer { } crate::TypeInner::Pointer { base, class } => { let type_id = self.get_type_id(arena, LookupType::Handle(base)); - self.lookup_type.insert( - LookupType::Local(LocalType::Pointer { - base, - class: self.parse_to_spirv_storage_class(class), - }), - id, - ); + self.lookup_type + .insert(LookupType::Local(LocalType::Pointer { base, class }), id); super::instructions::instruction_type_pointer( id, self.parse_to_spirv_storage_class(class), @@ -681,7 +708,8 @@ impl Writer { let init_word = global_variable .init .map(|constant| self.get_constant_id(constant, ir_module)); - let pointer_id = self.get_pointer_id(&ir_module.types, global_variable.ty, class); + let pointer_id = + self.get_pointer_id(&ir_module.types, global_variable.ty, global_variable.class); let instruction = super::instructions::instruction_variable(pointer_id, id, class, init_word); @@ -809,6 +837,28 @@ impl Writer { id } + fn get_type_inner<'a>( + &self, + ty_arena: &'a crate::Arena, + lookup_ty: LookupType, + ) -> MaybeOwned<'a, crate::TypeInner> { + match lookup_ty { + LookupType::Handle(handle) => MaybeOwned::Borrowed(&ty_arena[handle].inner), + LookupType::Local(local_ty) => match local_ty { + LocalType::Scalar { kind, width } => { + MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width }) + } + LocalType::Vector { size, kind, width } => { + MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }) + } + LocalType::Pointer { base, class } => { + MaybeOwned::Owned(crate::TypeInner::Pointer { base, class }) + } + _ => unreachable!(), + }, + } + } + fn write_expression<'a>( &mut self, ir_module: &'a crate::Module, @@ -817,31 +867,152 @@ impl Writer { block: &mut Block, function: &mut Function, ) -> Result { - match *expression { + match expression { + crate::Expression::Access { base, index } => { + let id = self.generate_id(); + + let (base_id, base_lookup_ty) = self.write_expression( + ir_module, + ir_function, + &ir_function.expressions[*base], + block, + function, + )?; + let (index_id, _) = self.write_expression( + ir_module, + ir_function, + &ir_function.expressions[*index], + block, + function, + )?; + + let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty.unwrap()); + + let (pointer_id, type_id, lookup_ty) = match *base_ty_inner { + crate::TypeInner::Vector { kind, width, .. } => { + let scalar_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Scalar { kind, width }), + ); + ( + self.create_pointer(scalar_id, spirv::StorageClass::Function), + scalar_id, + LookupType::Local(LocalType::Scalar { kind, width }), + ) + } + _ => unimplemented!(), + }; + + block + .body + .push(super::instructions::instruction_access_chain( + pointer_id, + id, + base_id, + &[index_id], + )); + + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + type_id, load_id, id, None, + )); + + Ok((load_id, Some(lookup_ty))) + } + crate::Expression::AccessIndex { base, index } => { + let id = self.generate_id(); + let (base_id, base_lookup_ty) = self + .write_expression( + ir_module, + ir_function, + &ir_function.expressions[*base], + block, + function, + ) + .unwrap(); + + let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty.unwrap()); + + let (pointer_id, type_id, lookup_ty) = match *base_ty_inner { + crate::TypeInner::Vector { kind, width, .. } => { + let scalar_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Scalar { kind, width }), + ); + ( + self.create_pointer(scalar_id, spirv::StorageClass::Function), + scalar_id, + LookupType::Local(LocalType::Scalar { kind, width }), + ) + } + crate::TypeInner::Struct { ref members } => { + let member = &members[*index as usize]; + let type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(member.ty)); + ( + self.create_pointer(type_id, spirv::StorageClass::Uniform), + type_id, + LookupType::Handle(member.ty), + ) + } + _ => unimplemented!(), + }; + + let const_ty_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Scalar { + kind: crate::ScalarKind::Sint, + width: 4, + }), + ); + let const_id = self.create_constant(const_ty_id, &[*index]); + + block + .body + .push(super::instructions::instruction_access_chain( + pointer_id, + id, + base_id, + &[const_id], + )); + + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + type_id, load_id, id, None, + )); + + Ok((load_id, Some(lookup_ty))) + } crate::Expression::GlobalVariable(handle) => { - let var = &ir_module.global_variables[handle]; - let id = self.get_global_variable_id(ir_module, handle); - Ok(Some((id, Some(var.ty)))) + let var = &ir_module.global_variables[*handle]; + let id = self.get_global_variable_id(&ir_module, *handle); + + Ok((id, Some(LookupType::Handle(var.ty)))) } crate::Expression::Constant(handle) => { - let var = &ir_module.constants[handle]; - let id = self.get_constant_id(handle, ir_module); - Ok(Some((id, Some(var.ty)))) + let var = &ir_module.constants[*handle]; + let id = self.get_constant_id(*handle, ir_module); + Ok((id, Some(LookupType::Handle(var.ty)))) } crate::Expression::Compose { ty, ref components } => { - let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty)); + let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*ty)); let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { let expression = &ir_function.expressions[*component]; - let (component_id, _) = self - .write_expression(ir_module, &ir_function, expression, block, function)? - .unwrap(); + let (component_id, _) = self.write_expression( + ir_module, + &ir_function, + expression, + block, + function, + )?; + constituent_ids.push(component_id); } let constituent_ids_slice = constituent_ids.as_slice(); - let id = match ir_module.types[ty].inner { + let id = match ir_module.types[*ty].inner { crate::TypeInner::Vector { .. } => { self.write_composite_construct(base_type_id, constituent_ids_slice, block) } @@ -881,44 +1052,40 @@ impl Writer { _ => unreachable!(), }; - Ok(Some((id, Some(ty)))) + Ok((id, Some(LookupType::Handle(*ty)))) } crate::Expression::Binary { op, left, right } => { match op { crate::BinaryOperator::Multiply => { let id = self.generate_id(); - let left_expression = &ir_function.expressions[left]; - let right_expression = &ir_function.expressions[right]; - let (left_id, left_ty) = self - .write_expression( - ir_module, - ir_function, - left_expression, - block, - function, - )? - .unwrap(); - let (right_id, right_ty) = self - .write_expression( - ir_module, - ir_function, - right_expression, - block, - function, - )? - .unwrap(); + let left_expression = &ir_function.expressions[*left]; + let right_expression = &ir_function.expressions[*right]; + let (left_id, left_lookup_ty) = self.write_expression( + ir_module, + ir_function, + left_expression, + block, + function, + )?; + let (right_id, right_lookup_ty) = self.write_expression( + ir_module, + ir_function, + right_expression, + block, + function, + )?; - let left_ty = left_ty.unwrap(); - let right_ty = right_ty.unwrap(); + let left_lookup_ty = left_lookup_ty.unwrap(); + let right_lookup_ty = right_lookup_ty.unwrap(); - let left_ty_inner = &ir_module.types[left_ty].inner; - let right_ty_inner = &ir_module.types[right_ty].inner; + let left_ty_inner = self.get_type_inner(&ir_module.types, left_lookup_ty); + let right_ty_inner = self.get_type_inner(&ir_module.types, right_lookup_ty); let left_result_type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(left_ty)); + self.get_type_id(&ir_module.types, left_lookup_ty); let right_result_type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(right_ty)); + self.get_type_id(&ir_module.types, right_lookup_ty); let left_id = match *left_expression { crate::Expression::LocalVariable(_) @@ -950,8 +1117,8 @@ impl Writer { _ => right_id, }; - let (instruction, ty) = match left_ty_inner { - crate::TypeInner::Vector { .. } => match right_ty_inner { + let (instruction, lookup_ty) = match *left_ty_inner { + crate::TypeInner::Vector { .. } => match *right_ty_inner { crate::TypeInner::Scalar { .. } => ( super::instructions::instruction_vector_times_scalar( left_result_type_id, @@ -959,7 +1126,7 @@ impl Writer { left_id, right_id, ), - left_ty, + left_lookup_ty, ), crate::TypeInner::Matrix { .. } => ( super::instructions::instruction_vector_times_matrix( @@ -968,11 +1135,11 @@ impl Writer { left_id, right_id, ), - left_ty, + left_lookup_ty, ), _ => unreachable!(), }, - crate::TypeInner::Matrix { .. } => match right_ty_inner { + crate::TypeInner::Matrix { .. } => match *right_ty_inner { crate::TypeInner::Scalar { .. } => ( super::instructions::instruction_matrix_times_scalar( left_result_type_id, @@ -980,7 +1147,7 @@ impl Writer { left_id, right_id, ), - left_ty, + left_lookup_ty, ), crate::TypeInner::Vector { .. } => ( super::instructions::instruction_matrix_times_vector( @@ -989,7 +1156,7 @@ impl Writer { left_id, right_id, ), - right_ty, + right_lookup_ty, ), crate::TypeInner::Matrix { .. } => ( super::instructions::instruction_matrix_times_matrix( @@ -998,7 +1165,7 @@ impl Writer { left_id, right_id, ), - left_ty, + left_lookup_ty, ), _ => unreachable!(), }, @@ -1012,7 +1179,7 @@ impl Writer { left_id, right_id, ), - left_ty, + left_lookup_ty, ), crate::ScalarKind::Sint | crate::ScalarKind::Uint => ( super::instructions::instruction_i_mul( @@ -1021,7 +1188,7 @@ impl Writer { left_id, right_id, ), - left_ty, + left_lookup_ty, ), _ => unreachable!(), } @@ -1030,33 +1197,33 @@ impl Writer { }; block.body.push(instruction); - Ok(Some((id, Some(ty)))) + Ok((id, Some(lookup_ty))) } _ => unimplemented!("{:?}", op), } } crate::Expression::LocalVariable(variable) => { - let var = &ir_function.local_variables[variable]; + let var = &ir_function.local_variables[*variable]; function .variables .iter() .find(|&v| v.name.as_ref().unwrap() == var.name.as_ref().unwrap()) - .map(|local_var| Some((local_var.id, Some(var.ty)))) + .map(|local_var| (local_var.id, Some(LookupType::Handle(var.ty)))) .ok_or_else(|| Error::UnknownLocalVariable(var.clone())) } crate::Expression::FunctionParameter(index) => { - let handle = ir_function.parameter_types.get(index as usize).unwrap(); + let handle = ir_function.parameter_types.get(*index as usize).unwrap(); let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*handle)); let load_id = self.generate_id(); block.body.push(super::instructions::instruction_load( type_id, load_id, - function.parameters[index as usize].result_id.unwrap(), + function.parameters[*index as usize].result_id.unwrap(), None, )); - Ok(Some((load_id, Some(*handle)))) + Ok((load_id, Some(LookupType::Handle(*handle)))) } crate::Expression::Call { ref origin, @@ -1069,18 +1236,27 @@ impl Writer { for argument in arguments { let expression = &ir_function.expressions[*argument]; - let (id, ty) = self - .write_expression(ir_module, ir_function, expression, block, function)? - .unwrap(); + let (id, lookup_ty) = self.write_expression( + ir_module, + ir_function, + expression, + block, + function, + )?; // Create variable - OpVariable // Store value to variable - OpStore // Use id of variable + let handle = match lookup_ty.unwrap() { + LookupType::Handle(handle) => handle, + LookupType::Local(_) => unreachable!(), + }; + let pointer_id = self.get_pointer_id( &ir_module.types, - ty.unwrap(), - spirv::StorageClass::Function, + handle, + crate::StorageClass::Function, ); let variable_id = self.generate_id(); @@ -1113,7 +1289,7 @@ impl Writer { *self.lookup_function.get(&local_function).unwrap(), argument_ids.as_slice(), )); - Ok(Some((id, None))) + Ok((id, None)) } _ => unimplemented!("{:?}", origin), }, @@ -1123,31 +1299,31 @@ impl Writer { convert, } => { if !convert { - return Ok(None); + return Err(Error::FeatureNotImplemented()); } - let (expr_id, expr_type) = self - .write_expression( - ir_module, - ir_function, - &ir_function.expressions[expr], - block, - function, - )? - .unwrap(); + let (expr_id, expr_type) = self.write_expression( + ir_module, + ir_function, + &ir_function.expressions[*expr], + block, + function, + )?; let id = self.generate_id(); - let instruction = match ir_module.types[expr_type.unwrap()].inner { + let expr_type_inner = self.get_type_inner(&ir_module.types, expr_type.unwrap()); + + let instruction = match *expr_type_inner { crate::TypeInner::Scalar { kind: expr_kind, width, } => { let kind_type_id = self.get_type_id( &ir_module.types, - LookupType::Local(LocalType::Scalar { kind, width }), + LookupType::Local(LocalType::Scalar { kind: *kind, width }), ); - if convert { + if *convert { super::instructions::instruction_bit_cast(kind_type_id, id, expr_id) } else { match (expr_kind, kind) { @@ -1188,7 +1364,7 @@ impl Writer { block.body.push(instruction); - Ok(Some((id, None))) + Ok((id, None)) } crate::Expression::ImageSample { image, @@ -1198,13 +1374,17 @@ impl Writer { depth_ref: _, } => { // image - let image_expression = &ir_function.expressions[image]; - let (image_id, image_ty) = self - .write_expression(ir_module, ir_function, image_expression, block, function)? - .ok_or(Error::EmptyValue)?; - let image_ty = image_ty.ok_or(Error::EmptyValue)?; - let image_result_type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(image_ty)); + let image_expression = &ir_function.expressions[*image]; + let (image_id, image_lookup_ty) = self.write_expression( + ir_module, + ir_function, + image_expression, + block, + function, + )?; + + let image_lookup_ty = image_lookup_ty.ok_or(Error::EmptyValue)?; + let image_result_type_id = self.get_type_id(&ir_module.types, image_lookup_ty); let image_id = match *image_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); @@ -1219,6 +1399,11 @@ impl Writer { _ => image_id, }; + let image_ty = match image_lookup_ty { + LookupType::Handle(handle) => handle, + LookupType::Local(_) => unreachable!(), + }; + // OpTypeSampledImage let sampled_image_type_id = self.get_type_id( &ir_module.types, @@ -1228,13 +1413,17 @@ impl Writer { ); // sampler - let sampler_expression = &ir_function.expressions[sampler]; - let (sampler_id, sampler_ty) = self - .write_expression(ir_module, ir_function, sampler_expression, block, function)? - .ok_or(Error::EmptyValue)?; - let sampler_ty = sampler_ty.ok_or(Error::EmptyValue)?; + let sampler_expression = &ir_function.expressions[*sampler]; + let (sampler_id, sampler_lookup_ty) = self.write_expression( + ir_module, + ir_function, + sampler_expression, + block, + function, + )?; + let sampler_result_type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(sampler_ty)); + self.get_type_id(&ir_module.types, sampler_lookup_ty.unwrap()); let sampler_id = match *sampler_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); @@ -1250,19 +1439,17 @@ impl Writer { }; // coordinate - let coordinate_expression = &ir_function.expressions[coordinate]; - let (coordinate_id, coordinate_ty) = self - .write_expression( - ir_module, - ir_function, - coordinate_expression, - block, - function, - )? - .ok_or(Error::EmptyValue)?; - let coordinate_ty = coordinate_ty.ok_or(Error::EmptyValue)?; + let coordinate_expression = &ir_function.expressions[*coordinate]; + let (coordinate_id, coordinate_lookup_ty) = self.write_expression( + ir_module, + ir_function, + coordinate_expression, + block, + function, + )?; + let coordinate_result_type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(coordinate_ty)); + self.get_type_id(&ir_module.types, coordinate_lookup_ty.unwrap()); let coordinate_id = match *coordinate_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); @@ -1317,7 +1504,7 @@ impl Writer { sampled_image_id, coordinate_id, )); - Ok(Some((id, None))) + Ok((id, None)) } _ => unimplemented!("{:?}", expression), } @@ -1346,7 +1533,7 @@ impl Writer { block.termination = Some(match ir_function.return_type { Some(_) => { let expression = &ir_function.expressions[value.unwrap()]; - let (id, ty) = self + let (id, lookup_ty) = self .write_expression( ir_module, ir_function, @@ -1354,17 +1541,14 @@ impl Writer { &mut block, function, ) - .unwrap() .unwrap(); let id = match *expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); - let value_ty_id = self.get_type_id( - &ir_module.types, - LookupType::Handle(ty.unwrap()), - ); + let value_ty_id = + self.get_type_id(&ir_module.types, lookup_ty.unwrap()); block.body.push(super::instructions::instruction_load( value_ty_id, load_id, @@ -1392,9 +1576,8 @@ impl Writer { &mut block, function, ) - .unwrap() .unwrap(); - let (value_id, value_ty) = self + let (value_id, value_lookup_ty) = self .write_expression( ir_module, ir_function, @@ -1402,17 +1585,14 @@ impl Writer { &mut block, function, ) - .unwrap() .unwrap(); let value_id = match value_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); - let value_ty_id = self.get_type_id( - &ir_module.types, - LookupType::Handle(value_ty.unwrap()), - ); + let value_ty_id = + self.get_type_id(&ir_module.types, value_lookup_ty.unwrap()); block.body.push(super::instructions::instruction_load( value_ty_id, load_id, @@ -1452,21 +1632,6 @@ impl Writer { )); } - // Looking through all global variable, types, constants. - // Doing this because we also want to include not used parts of the module - // to be included in the output - for (handle, _) in ir_module.types.iter() { - self.get_type_id(&ir_module.types, LookupType::Handle(handle)); - } - - for (handle, _) in ir_module.global_variables.iter() { - self.get_global_variable_id(ir_module, handle); - } - - for (handle, _) in ir_module.constants.iter() { - self.get_constant_id(handle, &ir_module); - } - for annotation in self.annotations.iter() { annotation.to_words(&mut self.logical_layout.annotations); } From 249e0bd4ac5d4c5cab98aef311b85be3c31cff87 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 11 Nov 2020 07:58:53 +0000 Subject: [PATCH 0269/2212] [glsl-in] Make sure functions ends with return --- src/front/glsl/parser.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 69827f963..341ef58bc 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1092,12 +1092,17 @@ pomelo! { } } - function_definition ::= function_prototype(mut f) compound_statement_no_new_scope(cs) { + function_definition ::= function_prototype(mut f) compound_statement_no_new_scope(mut cs) { std::mem::swap(&mut f.expressions, &mut extra.context.expressions); std::mem::swap(&mut f.local_variables, &mut extra.context.local_variables); extra.context.clear_scopes(); extra.context.lookup_global_var_exps.clear(); extra.context.typifier = Typifier::new(); + // make sure function ends with return + match cs.last() { + Some(Statement::Return {..}) => {} + _ => {cs.push(Statement::Return { value:None });} + } f.body = cs; f.fill_global_use(&extra.module.global_variables); f From ac5e91b31a4161388c422f068e99cc5c66adb78d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 10 Nov 2020 19:12:45 -0500 Subject: [PATCH 0270/2212] Fix and refactor the constant array sizes --- src/arena.rs | 4 ++ src/back/glsl.rs | 121 ++++++++++++++++++++++++++++++++++------- src/back/msl.rs | 54 +++++++----------- src/back/spv/writer.rs | 5 +- src/front/spv/mod.rs | 5 +- src/front/wgsl/mod.rs | 56 ++++++++++++++----- src/lib.rs | 4 +- src/proc/validator.rs | 18 +++++- 8 files changed, 192 insertions(+), 75 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 58c65997d..460d909c2 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -165,6 +165,10 @@ impl Arena { self.fetch_if_or_append(value, T::eq) } + pub fn try_get(&self, handle: Handle) -> Option<&T> { + self.data.get(handle.index.get() as usize - 1) + } + /// Get a mutable reference to an element in the arena. pub fn get_mut(&mut self, handle: Handle) -> &mut T { self.data.get_mut(handle.index.get() as usize - 1).unwrap() diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 7c2d84c57..79079eb1b 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -410,14 +410,28 @@ pub fn write<'a>( &mut buf, "{} {}({});", func.return_type - .map(|ty| write_type(ty, &module.types, &structs, None, &mut manager)) + .map(|ty| write_type( + ty, + &module.types, + &module.constants, + &structs, + None, + &mut manager + )) .transpose()? .as_deref() .unwrap_or("void"), name, func.parameter_types .iter() - .map(|ty| write_type(*ty, &module.types, &structs, None, &mut manager)) + .map(|ty| write_type( + *ty, + &module.types, + &module.constants, + &structs, + None, + &mut manager + )) .collect::, _>>()? .join(","), )?; @@ -618,7 +632,14 @@ pub fn write<'a>( &mut buf, "{}{} {};", write_storage_class(global.class, &mut manager)?, - write_type(global.ty, &module.types, &structs, block, &mut manager)?, + write_type( + global.ty, + &module.types, + &module.constants, + &structs, + block, + &mut manager + )?, name )?; @@ -652,7 +673,14 @@ pub fn write<'a>( &mut buf, "{} {}({}) {{", func.return_type - .map(|ty| write_type(ty, &module.types, &structs, None, &mut manager)) + .map(|ty| write_type( + ty, + &module.types, + &module.constants, + &structs, + None, + &mut manager + )) .transpose()? .as_deref() .unwrap_or("void"), @@ -661,7 +689,14 @@ pub fn write<'a>( .iter() .zip(args.values()) .map::, _>(|(ty, name)| { - let ty = write_type(*ty, &module.types, &structs, None, &mut manager)?; + let ty = write_type( + *ty, + &module.types, + &module.constants, + &structs, + None, + &mut manager, + )?; Ok(format!("{} {}", ty, name)) }) @@ -699,7 +734,14 @@ pub fn write<'a>( write!( &mut buf, "\t{} {}", - write_type(var.ty, &module.types, &structs, None, &mut manager)?, + write_type( + var.ty, + &module.types, + &module.constants, + &structs, + None, + &mut manager + )?, name )?; if let Some(init) = var.init { @@ -953,14 +995,27 @@ fn write_expression<'a, 'b>( columns as u8, rows as u8, ), - TypeInner::Array { .. } => { - write_type(ty, &module.types, builder.structs, None, manager)?.into_owned() - } + TypeInner::Array { .. } => write_type( + ty, + &module.types, + &module.constants, + builder.structs, + None, + manager, + )? + .into_owned(), TypeInner::Struct { .. } => builder.structs.get(&ty).unwrap().clone(), _ => { return Err(Error::Custom(format!( "Cannot compose type {}", - write_type(ty, &module.types, builder.structs, None, manager)? + write_type( + ty, + &module.types, + &module.constants, + builder.structs, + None, + manager + )? ))) } }; @@ -1334,12 +1389,25 @@ fn write_constant( Cow::Owned(format!("mat{}x{}", columns as u8, rows as u8,)), TypeInner::Struct { .. } => Cow::::Borrowed(builder.structs.get(&constant.ty).unwrap()), - TypeInner::Array { .. } => - write_type(constant.ty, &module.types, builder.structs, None, manager)?, + TypeInner::Array { .. } => write_type( + constant.ty, + &module.types, + &module.constants, + builder.structs, + None, + manager + )?, _ => return Err(Error::Custom(format!( "Cannot build constant of type {}", - write_type(constant.ty, &module.types, builder.structs, None, manager)? + write_type( + constant.ty, + &module.types, + &module.constants, + builder.structs, + None, + manager + )? ))), }, components @@ -1405,6 +1473,7 @@ fn map_scalar( fn write_type<'a>( ty: Handle, types: &Arena, + constants: &Arena, structs: &'a FastHashMap, String>, block: Option, manager: &mut FeaturesManager, @@ -1432,7 +1501,9 @@ fn write_type<'a>( rows as u8 )) } - TypeInner::Pointer { base, .. } => write_type(base, types, structs, None, manager)?, + TypeInner::Pointer { base, .. } => { + write_type(base, types, constants, structs, None, manager)? + } TypeInner::Array { base, size, .. } => { if let TypeInner::Array { .. } = types[base].inner { manager.request(Features::ARRAY_OF_ARRAYS) @@ -1440,8 +1511,8 @@ fn write_type<'a>( Cow::Owned(format!( "{}[{}]", - write_type(base, types, structs, None, manager)?, - write_array_size(size)? + write_type(base, types, constants, structs, None, manager)?, + write_array_size(size, constants)? )) } TypeInner::Struct { ref members } => { @@ -1453,7 +1524,7 @@ fn write_type<'a>( writeln!( &mut out, "\t{} {};", - write_type(member.ty, types, structs, None, manager)?, + write_type(member.ty, types, constants, structs, None, manager)?, member .name .clone() @@ -1551,9 +1622,12 @@ fn write_interpolation(interpolation: Interpolation) -> Result<&'static str, Err }) } -fn write_array_size(size: ArraySize) -> Result { +fn write_array_size(size: ArraySize, constants: &Arena) -> Result { Ok(match size { - ArraySize::Static(size) => size.to_string(), + ArraySize::Constant(const_handle) => match constants[const_handle].inner { + ConstantInner::Uint(size) => size.to_string(), + _ => unreachable!(), + }, ArraySize::Dynamic => String::from(""), }) } @@ -1615,7 +1689,14 @@ fn write_struct( writeln!( &mut tmp, "\t{} {};", - write_type(member.ty, &module.types, &structs, None, manager)?, + write_type( + member.ty, + &module.types, + &module.constants, + &structs, + None, + manager + )?, member .name .clone() diff --git a/src/back/msl.rs b/src/back/msl.rs index 6aa52d062..71adf8798 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -83,7 +83,6 @@ pub enum Error { UnsupportedCall(String), UnsupportedDynamicArrayLength, UnableToReturnValue(Handle), - AccessIndexExceedsStaticLength(u32, u32), /// The source IR is not valid. Validation, } @@ -450,19 +449,10 @@ impl Writer { let name = member.name.or_index(MemberIndex(index as usize)); write!(self.out, ".{}", name)?; } - crate::TypeInner::Matrix { rows: size, .. } - | crate::TypeInner::Vector { size, .. } => { - if index >= size as u32 { - return Err(Error::AccessIndexExceedsStaticLength(index, size as u32)); - } + crate::TypeInner::Matrix { .. } | crate::TypeInner::Vector { .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; } - crate::TypeInner::Array { size, .. } => { - if let crate::ArraySize::Static(length) = size { - if index >= length { - return Err(Error::AccessIndexExceedsStaticLength(index, length)); - } - } + crate::TypeInner::Array { .. } => { write!(self.out, "[{}]", index)?; } _ => { @@ -682,19 +672,16 @@ impl Writer { } other => return Err(Error::UnsupportedCall(other.to_owned())), }, - crate::Expression::ArrayLength(expr) => { - let size = match *self.typifier.get(expr, &module.types) { - crate::TypeInner::Array { - size: crate::ArraySize::Static(size), - .. - } => size, - crate::TypeInner::Array { .. } => { - return Err(Error::UnsupportedDynamicArrayLength) - } - _ => return Err(Error::Validation), - }; - write!(self.out, "{}", size)?; - } + crate::Expression::ArrayLength(expr) => match *self.typifier.get(expr, &module.types) { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(const_handle), + .. + } => { + self.put_constant(const_handle, module)?; + } + crate::TypeInner::Array { .. } => return Err(Error::UnsupportedDynamicArrayLength), + _ => return Err(Error::Validation), + }, } Ok(()) } @@ -900,15 +887,14 @@ impl Writer { stride: _, } => { let base_name = module.types[base].name.or_index(base); - let resolved_size = match size { - crate::ArraySize::Static(length) => length, - crate::ArraySize::Dynamic => 1, - }; - write!( - self.out, - "typedef {} {}[{}]", - base_name, name, resolved_size - )?; + write!(self.out, "typedef {} {}[", base_name, name)?; + match size { + crate::ArraySize::Constant(const_handle) => { + self.put_constant(const_handle, module)?; + write!(self.out, "]")?; + } + crate::ArraySize::Dynamic => write!(self.out, "1]")?, + } } crate::TypeInner::Struct { ref members } => { writeln!(self.out, "struct {} {{", name)?; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 879dcd829..c9aaf8144 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -564,8 +564,9 @@ impl Writer { let type_id = self.get_type_id(arena, LookupType::Handle(base)); match size { - crate::ArraySize::Static(length) => { - super::instructions::instruction_type_array(id, type_id, length) + crate::ArraySize::Constant(const_handle) => { + let length_id = self.lookup_constant[&const_handle]; + super::instructions::instruction_type_array(id, type_id, length_id) } crate::ArraySize::Dynamic => { super::instructions::instruction_type_runtime_array(id, type_id) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index f5aca1cf4..b7744ddcf 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1946,12 +1946,13 @@ impl> Parser { inst.expect(4)?; let id = self.next()?; let type_id = self.next()?; - let length = self.next()?; + let length_id = self.next()?; + let length_const = self.lookup_constant.lookup(length_id)?; let decor = self.future_decor.remove(&id); let inner = crate::TypeInner::Array { base: self.lookup_type.lookup(type_id)?.handle, - size: crate::ArraySize::Static(length), + size: crate::ArraySize::Constant(length_const.handle), stride: decor.as_ref().and_then(|dec| dec.array_stride), }; self.lookup_type.insert( diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index ee84b040b..83874bf0f 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -393,7 +393,7 @@ impl Parser { inner } _ => { - let composite_ty = self.parse_type_decl(lexer, None, type_arena)?; + let composite_ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -491,7 +491,7 @@ impl Parser { expr } else { *lexer = backup; - let ty = self.parse_type_decl(lexer, None, ctx.types)?; + let ty = self.parse_type_decl(lexer, None, ctx.types, ctx.constants)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -908,10 +908,11 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, type_arena: &mut Arena, + const_arena: &mut Arena, ) -> Result<(&'a str, Handle), Error<'a>> { let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; Ok((name, ty)) } @@ -930,7 +931,7 @@ impl Parser { } let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let access = match class { Some(crate::StorageClass::Storage) => crate::StorageAccess::all(), Some(crate::StorageClass::Handle) => { @@ -966,6 +967,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, type_arena: &mut Arena, + const_arena: &mut Arena, ) -> Result, Error<'a>> { let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; @@ -1002,7 +1004,7 @@ impl Parser { return Err(Error::MissingMemberOffset(name)); } lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Separator(';'))?; members.push(crate::StructMember { name: Some(name.to_owned()), @@ -1017,6 +1019,7 @@ impl Parser { lexer: &mut Lexer<'a>, self_name: Option<&'a str>, type_arena: &mut Arena, + const_arena: &mut Arena, ) -> Result, Error<'a>> { self.scopes.push(Scope::TypeDecl); let decoration_lexer = if lexer.skip(Token::DoubleParen('[')) { @@ -1138,18 +1141,30 @@ impl Parser { lexer.expect(Token::Paren('<'))?; let class = conv::map_storage_class(lexer.next_ident()?)?; lexer.expect(Token::Separator(','))?; - let base = self.parse_type_decl(lexer, None, type_arena)?; + let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Paren('>'))?; crate::TypeInner::Pointer { base, class } } Token::Word("array") => { lexer.expect(Token::Paren('<'))?; - let base = self.parse_type_decl(lexer, None, type_arena)?; + let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let size = match lexer.next() { Token::Separator(',') => { let value = lexer.next_uint_literal()?; lexer.expect(Token::Paren('>'))?; - crate::ArraySize::Static(value) + let const_handle = const_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Uint(value as u64), + ty: type_arena.fetch_or_append(crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: 4, + }, + }), + }); + crate::ArraySize::Constant(const_handle) } Token::Paren('>') => crate::ArraySize::Dynamic, other => return Err(Error::Unexpected(other)), @@ -1177,7 +1192,7 @@ impl Parser { crate::TypeInner::Array { base, size, stride } } Token::Word("struct") => { - let members = self.parse_struct_body(lexer, type_arena)?; + let members = self.parse_struct_body(lexer, type_arena, const_arena)?; crate::TypeInner::Struct { members } } Token::Word("sampler") => crate::TypeInner::Sampler { comparison: false }, @@ -1381,7 +1396,11 @@ impl Parser { Constant(Handle), Variable(Handle), } - let (name, ty) = self.parse_variable_ident_decl(lexer, context.types)?; + let (name, ty) = self.parse_variable_ident_decl( + lexer, + context.types, + context.constants, + )?; let init = if lexer.skip(Token::Operation('=')) { let value = self.parse_general_expression(lexer, context.as_expression())?; @@ -1533,7 +1552,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; } let (param_name, param_type) = - self.parse_variable_ident_decl(lexer, &mut module.types)?; + self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; let param_index = parameter_types.len() as u32; let expression_token = expressions.append(crate::Expression::FunctionParameter(param_index)); @@ -1545,7 +1564,7 @@ impl Parser { let return_type = if lexer.skip(Token::Word("void")) { None } else { - Some(self.parse_type_decl(lexer, None, &mut module.types)?) + Some(self.parse_type_decl(lexer, None, &mut module.types, &mut module.constants)?) }; let mut fun = crate::Function { @@ -1691,12 +1710,21 @@ impl Parser { Token::Word("type") => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; - let ty = self.parse_type_decl(lexer, Some(name), &mut module.types)?; + let ty = self.parse_type_decl( + lexer, + Some(name), + &mut module.types, + &mut module.constants, + )?; self.lookup_type.insert(name.to_owned(), ty); lexer.expect(Token::Separator(';'))?; } Token::Word("const") => { - let (name, ty) = self.parse_variable_ident_decl(lexer, &mut module.types)?; + let (name, ty) = self.parse_variable_ident_decl( + lexer, + &mut module.types, + &mut module.constants, + )?; lexer.expect(Token::Operation('='))?; let const_handle = self.parse_const_expression( lexer, diff --git a/src/lib.rs b/src/lib.rs index ceec1f2b8..c82e9c4e8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -192,8 +192,8 @@ pub enum ScalarKind { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ArraySize { - /// The array size is known at compilation. - Static(u32), + /// The array size is constant. + Constant(Handle), /// The array size can change at runtime. Dynamic, } diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 27576433a..b6d770ab7 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -80,6 +80,8 @@ pub enum ValidationError { InvalidTypeWidth(crate::ScalarKind, crate::Bytes), #[error("The type handle {0:?} can not be resolved")] UnresolvedType(Handle), + #[error("The constant {0:?} can not be used for an array size")] + InvalidArraySizeConstant(Handle), #[error("Global variable {handle:?} '{name}' is invalid: {error:?}")] GlobalVariable { handle: Handle, @@ -94,6 +96,8 @@ pub enum ValidationError { name: String, error: EntryPointError, }, + #[error("Module is corrupted")] + Corrupted, } impl crate::GlobalVariable { @@ -427,10 +431,22 @@ impl Validator { return Err(ValidationError::UnresolvedType(base)); } } - Ti::Array { base, .. } => { + Ti::Array { base, size, .. } => { if base >= handle { return Err(ValidationError::UnresolvedType(base)); } + if let crate::ArraySize::Constant(const_handle) = size { + let constant = module + .constants + .try_get(const_handle) + .ok_or(ValidationError::Corrupted)?; + match constant.inner { + crate::ConstantInner::Uint(_) => {} + _ => { + return Err(ValidationError::InvalidArraySizeConstant(const_handle)) + } + } + } } Ti::Struct { ref members } => { //TODO: check that offsets are not intersecting? From a54800afc1d8c1bbf9f227b45e88a1a790ba0d0d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 11 Nov 2020 00:50:19 -0500 Subject: [PATCH 0271/2212] Naming processor, used for [msl] --- src/back/msl.rs | 404 +++++++++++++++++-------------------------- src/proc/mod.rs | 2 + src/proc/namer.rs | 122 +++++++++++++ src/proc/typifier.rs | 10 ++ 4 files changed, 290 insertions(+), 248 deletions(-) create mode 100644 src/proc/namer.rs diff --git a/src/back/msl.rs b/src/back/msl.rs index 71adf8798..6cae5efa3 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -16,7 +16,7 @@ we move them up to the root output structure that we define ourselves. use crate::{ arena::Handle, - proc::{ResolveContext, ResolveError, Typifier}, + proc::{EntryPointIndex, NameKey, Namer, ResolveContext, ResolveError, Typifier}, FastHashMap, }; use std::{ @@ -25,6 +25,11 @@ use std::{ string::FromUtf8Error, }; +//TODO: find a complete list +const RESERVED_WORDS: &[&str] = &[ + "if", "switch", "while", "for", "main", "struct", "new", "const", "device", +]; + #[derive(Clone, Debug, Default, PartialEq)] pub struct BindTarget { pub buffer: Option, @@ -161,122 +166,9 @@ impl Options { } } -trait Indexed { - const CLASS: &'static str; - const PREFIX: bool = false; - fn id(&self) -> usize; -} - -impl Indexed for Handle { - const CLASS: &'static str = "Type"; - fn id(&self) -> usize { - self.index() - } -} -impl Indexed for Handle { - const CLASS: &'static str = "global"; - fn id(&self) -> usize { - self.index() - } -} -impl Indexed for Handle { - const CLASS: &'static str = "local"; - fn id(&self) -> usize { - self.index() - } -} -impl Indexed for Handle { - const CLASS: &'static str = "function"; - fn id(&self) -> usize { - self.index() - } -} - -struct MemberIndex(usize); -impl Indexed for MemberIndex { - const CLASS: &'static str = "field"; - fn id(&self) -> usize { - self.0 - } -} -struct ParameterIndex(usize); -impl Indexed for ParameterIndex { - const CLASS: &'static str = "param"; - fn id(&self) -> usize { - self.0 - } -} - -enum NameSource<'a> { - Custom { name: &'a str, prefix: bool }, - Index(usize), -} - -const RESERVED_NAMES: &[&str] = &["main"]; - -struct Name<'a> { - class: &'static str, - source: NameSource<'a>, -} -impl Display for Name<'_> { - fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - match self.source { - NameSource::Custom { - name, - prefix: false, - } if RESERVED_NAMES.contains(&name) => write!(formatter, "{}_", name), - NameSource::Custom { - name, - prefix: false, - } => formatter.write_str(name), - NameSource::Custom { name, prefix: true } => { - let (head, tail) = name.split_at(1); - write!(formatter, "{}{}{}", self.class, head.to_uppercase(), tail) - } - NameSource::Index(index) => write!(formatter, "{}{}", self.class, index), - } - } -} -impl From for Name<'_> { - fn from(index: I) -> Self { - Name { - class: I::CLASS, - source: NameSource::Index(index.id()), - } - } -} - -fn is_valid_identifier_name(s: &str) -> bool { - let mut chars = s.chars(); - match chars.next() { - Some(c) if c.is_ascii_alphabetic() || c == '_' => (), - _ => return false, - }; - chars.all(|c| c.is_ascii_alphanumeric() || c == '_') -} - -trait AsName { - fn or_index(&self, index: I) -> Name; -} -impl AsName for Option { - fn or_index(&self, index: I) -> Name { - Name { - class: I::CLASS, - source: match *self { - //TODO: handle name collisions - //TODO: try to use parts of the name if it contains invalid characters - Some(ref name) if is_valid_identifier_name(name) => NameSource::Custom { - name, - prefix: I::PREFIX, - }, - _ => NameSource::Index(index.id()), - }, - } - } -} - struct TypedGlobalVariable<'a> { module: &'a crate::Module, + names: &'a FastHashMap, handle: Handle, usage: crate::GlobalUse, } @@ -284,9 +176,9 @@ struct TypedGlobalVariable<'a> { impl<'a> TypedGlobalVariable<'a> { fn try_fmt(&self, out: &mut W) -> Result<(), Error> { let var = &self.module.global_variables[self.handle]; - let name = var.name.or_index(self.handle); + let name = &self.names[&NameKey::GlobalVariable(self.handle)]; let ty = &self.module.types[var.ty]; - let ty_name = ty.name.or_index(var.ty); + let ty_name = &self.names[&NameKey::Type(var.ty)]; let (space_qualifier, reference) = match ty.inner { crate::TypeInner::Struct { .. } => match var.class { @@ -367,6 +259,7 @@ impl ResolvedBinding { pub struct Writer { out: W, + names: FastHashMap, typifier: Typifier, } @@ -399,11 +292,23 @@ fn separate(is_last: bool) -> &'static str { } } +enum FunctionOrigin { + Handle(Handle), + EntryPoint(EntryPointIndex), +} + +struct ExpressionContext<'a> { + function: &'a crate::Function, + origin: FunctionOrigin, + module: &'a crate::Module, +} + impl Writer { /// Creates a new `Writer` instance pub fn new(out: W) -> Self { Writer { out, + names: FastHashMap::default(), typifier: Typifier::new(), } } @@ -412,15 +317,14 @@ impl Writer { &mut self, name: &str, parameters: &[Handle], - function: &crate::Function, - module: &crate::Module, + context: &ExpressionContext, ) -> Result<(), Error> { write!(self.out, "{}(", name)?; for (i, &handle) in parameters.iter().enumerate() { if i != 0 { write!(self.out, ", ")?; } - self.put_expression(handle, function, module)?; + self.put_expression(handle, context)?; } write!(self.out, ")")?; Ok(()) @@ -429,24 +333,24 @@ impl Writer { fn put_expression( &mut self, expr_handle: Handle, - function: &crate::Function, - module: &crate::Module, + context: &ExpressionContext, ) -> Result<(), Error> { - let expression = &function.expressions[expr_handle]; + let expression = &context.function.expressions[expr_handle]; log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { crate::Expression::Access { base, index } => { - self.put_expression(base, function, module)?; + self.put_expression(base, context)?; write!(self.out, "[")?; - self.put_expression(index, function, module)?; + self.put_expression(index, context)?; write!(self.out, "]")?; } crate::Expression::AccessIndex { base, index } => { - self.put_expression(base, function, module)?; - match *self.typifier.get(base, &module.types) { - crate::TypeInner::Struct { ref members } => { - let member = &members[index as usize]; - let name = member.name.or_index(MemberIndex(index as usize)); + self.put_expression(base, context)?; + let resolved = self.typifier.get(base, &context.module.types); + match *resolved { + crate::TypeInner::Struct { .. } => { + let base_ty = self.typifier.get_handle(base).unwrap(); + let name = &self.names[&NameKey::StructMember(base_ty, index)]; write!(self.out, ".{}", name)?; } crate::TypeInner::Matrix { .. } | crate::TypeInner::Vector { .. } => { @@ -460,9 +364,9 @@ impl Writer { } } } - crate::Expression::Constant(handle) => self.put_constant(handle, module)?, + crate::Expression::Constant(handle) => self.put_constant(handle, context.module)?, crate::Expression::Compose { ty, ref components } => { - let inner = &module.types[ty].inner; + let inner = &context.module.types[ty].inner; match *inner { crate::TypeInner::Vector { size, kind, .. } => { write!( @@ -471,23 +375,28 @@ impl Writer { scalar_kind_string(kind), vector_size_string(size) )?; - self.put_call("", components, function, module)?; + self.put_call("", components, context)?; } crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { - self.put_call(scalar_kind_string(kind), components, function, module)?; + self.put_call(scalar_kind_string(kind), components, context)?; } _ => return Err(Error::UnsupportedCompose(ty)), } } crate::Expression::FunctionParameter(index) => { - let name = Name::from(ParameterIndex(index as usize)); + let fun_handle = match context.origin { + FunctionOrigin::Handle(handle) => handle, + FunctionOrigin::EntryPoint(_) => unreachable!(), + }; + let name = &self.names[&NameKey::FunctionParameter(fun_handle, index)]; write!(self.out, "{}", name)?; } crate::Expression::GlobalVariable(handle) => { - let var = &module.global_variables[handle]; + let var = &context.module.global_variables[handle]; match var.class { crate::StorageClass::Output => { - if let crate::TypeInner::Struct { .. } = module.types[var.ty].inner { + if let crate::TypeInner::Struct { .. } = context.module.types[var.ty].inner + { return Ok(()); } write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; @@ -499,17 +408,24 @@ impl Writer { } _ => {} } - let name = var.name.or_index(handle); + let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; } crate::Expression::LocalVariable(handle) => { - let var = &function.local_variables[handle]; - let name = var.name.or_index(handle); + let name_key = match context.origin { + FunctionOrigin::Handle(fun_handle) => { + NameKey::FunctionLocal(fun_handle, handle) + } + FunctionOrigin::EntryPoint(ep_index) => { + NameKey::EntryPointLocal(ep_index, handle) + } + }; + let name = &self.names[&name_key]; write!(self.out, "{}", name)?; } crate::Expression::Load { pointer } => { //write!(self.out, "*")?; - self.put_expression(pointer, function, module)?; + self.put_expression(pointer, context)?; } crate::Expression::ImageSample { image, @@ -523,14 +439,14 @@ impl Writer { None => "sample", }; //TODO: handle arrayed images - self.put_expression(image, function, module)?; + self.put_expression(image, context)?; write!(self.out, ".{}(", op)?; - self.put_expression(sampler, function, module)?; + self.put_expression(sampler, context)?; write!(self.out, ", ")?; - self.put_expression(coordinate, function, module)?; + self.put_expression(coordinate, context)?; if let Some(dref) = depth_ref { write!(self.out, ", ")?; - self.put_expression(dref, function, module)?; + self.put_expression(dref, context)?; } match level { crate::SampleLevel::Auto => {} @@ -539,12 +455,12 @@ impl Writer { } crate::SampleLevel::Exact(h) => { write!(self.out, ", level(")?; - self.put_expression(h, function, module)?; + self.put_expression(h, context)?; write!(self.out, ")")?; } crate::SampleLevel::Bias(h) => { write!(self.out, ", bias(")?; - self.put_expression(h, function, module)?; + self.put_expression(h, context)?; write!(self.out, ")")?; } } @@ -556,12 +472,12 @@ impl Writer { index, } => { //TODO: handle arrayed images - self.put_expression(image, function, module)?; + self.put_expression(image, context)?; write!(self.out, ".read(")?; - self.put_expression(coordinate, function, module)?; + self.put_expression(coordinate, context)?; if let Some(index) = index { write!(self.out, ", ")?; - self.put_expression(index, function, module)?; + self.put_expression(index, context)?; } write!(self.out, ")")?; } @@ -571,7 +487,7 @@ impl Writer { crate::UnaryOperator::Not => "!", }; write!(self.out, "{}", op_str)?; - self.put_expression(expr, function, module)?; + self.put_expression(expr, context)?; } crate::Expression::Binary { op, left, right } => { let op_str = match op { @@ -591,20 +507,20 @@ impl Writer { }; let kind = self .typifier - .get(left, &module.types) + .get(left, &context.module.types) .scalar_kind() .ok_or(Error::UnsupportedBinaryOp(op))?; if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float { write!(self.out, "fmod(")?; - self.put_expression(left, function, module)?; + self.put_expression(left, context)?; write!(self.out, ", ")?; - self.put_expression(right, function, module)?; + self.put_expression(right, context)?; write!(self.out, ")")?; } else { //write!(self.out, "(")?; - self.put_expression(left, function, module)?; + self.put_expression(left, context)?; write!(self.out, " {} ", op_str)?; - self.put_expression(right, function, module)?; + self.put_expression(right, context)?; //write!(self.out, ")")?; } } @@ -617,16 +533,16 @@ impl Writer { crate::IntrinsicFunction::IsFinite => "", crate::IntrinsicFunction::IsNormal => "", }; - self.put_call(op, &[argument], function, module)?; + self.put_call(op, &[argument], context)?; } crate::Expression::Transpose(expr) => { - self.put_call("transpose", &[expr], function, module)?; + self.put_call("transpose", &[expr], context)?; } crate::Expression::DotProduct(a, b) => { - self.put_call("dot", &[a, b], function, module)?; + self.put_call("dot", &[a, b], context)?; } crate::Expression::CrossProduct(a, b) => { - self.put_call("cross", &[a, b], function, module)?; + self.put_call("cross", &[a, b], context)?; } crate::Expression::As { expr, @@ -634,14 +550,14 @@ impl Writer { convert, } => { let scalar = scalar_kind_string(kind); - let size = match *self.typifier.get(expr, &module.types) { + let size = match *self.typifier.get(expr, &context.module.types) { crate::TypeInner::Scalar { .. } => "", crate::TypeInner::Vector { size, .. } => vector_size_string(size), _ => return Err(Error::Validation), }; let op = if convert { "static_cast" } else { "as_type" }; write!(self.out, "{}<{}{}>(", op, scalar, size)?; - self.put_expression(expr, function, module)?; + self.put_expression(expr, context)?; write!(self.out, ")")?; } crate::Expression::Derivative { axis, expr } => { @@ -650,34 +566,37 @@ impl Writer { crate::DerivativeAxis::Y => "dfdy", crate::DerivativeAxis::Width => "fwidth", }; - self.put_call(op, &[expr], function, module)?; + self.put_call(op, &[expr], context)?; } crate::Expression::Call { origin: crate::FunctionOrigin::Local(handle), ref arguments, } => { - let name = module.functions[handle].name.or_index(handle); + let name = &self.names[&NameKey::Function(handle)]; write!(self.out, "{}", name)?; - self.put_call("", arguments, function, module)?; + self.put_call("", arguments, context)?; } crate::Expression::Call { origin: crate::FunctionOrigin::External(ref name), ref arguments, } => match name.as_str() { "atan2" | "cos" | "distance" | "length" | "mix" | "normalize" | "sin" => { - self.put_call(name, arguments, function, module)?; + self.put_call(name, arguments, context)?; } "fclamp" => { - self.put_call("clamp", arguments, function, module)?; + self.put_call("clamp", arguments, context)?; } other => return Err(Error::UnsupportedCall(other.to_owned())), }, - crate::Expression::ArrayLength(expr) => match *self.typifier.get(expr, &module.types) { + crate::Expression::ArrayLength(expr) => match *self + .typifier + .get(expr, &context.module.types) + { crate::TypeInner::Array { size: crate::ArraySize::Constant(const_handle), .. } => { - self.put_constant(const_handle, module)?; + self.put_constant(const_handle, context.module)?; } crate::TypeInner::Array { .. } => return Err(Error::UnsupportedDynamicArrayLength), _ => return Err(Error::Validation), @@ -692,8 +611,6 @@ impl Writer { module: &crate::Module, ) -> Result<(), Error> { let constant = &module.constants[handle]; - let ty = &module.types[constant.ty]; - match constant.inner { crate::ConstantInner::Sint(value) => { write!(self.out, "{}", value)?; @@ -711,18 +628,17 @@ impl Writer { write!(self.out, "{}", value)?; } crate::ConstantInner::Composite(ref constituents) => { - let ty_name = ty.name.or_index(constant.ty); + let ty_name = &self.names[&NameKey::Type(constant.ty)]; write!(self.out, "{}(", ty_name)?; - for (i, handle) in constituents.iter().enumerate() { + for (i, &handle) in constituents.iter().enumerate() { if i != 0 { write!(self.out, ", ")?; } - self.put_constant(*handle, module)?; + self.put_constant(handle, module)?; } write!(self.out, ")")?; } } - Ok(()) } @@ -730,8 +646,7 @@ impl Writer { &mut self, level: Level, statements: &[crate::Statement], - function: &crate::Function, - module: &crate::Module, + context: &ExpressionContext, return_value: Option<&str>, ) -> Result<(), Error> { for statement in statements { @@ -740,7 +655,7 @@ impl Writer { crate::Statement::Block(ref block) => { if !block.is_empty() { writeln!(self.out, "{}{{", level)?; - self.put_block(level.next(), block, function, module, return_value)?; + self.put_block(level.next(), block, context, return_value)?; writeln!(self.out, "{}}}", level)?; } } @@ -750,12 +665,12 @@ impl Writer { ref reject, } => { write!(self.out, "{}if (", level)?; - self.put_expression(condition, function, module)?; + self.put_expression(condition, context)?; writeln!(self.out, ") {{")?; - self.put_block(level.next(), accept, function, module, return_value)?; + self.put_block(level.next(), accept, context, return_value)?; if !reject.is_empty() { writeln!(self.out, "{}}} else {{", level)?; - self.put_block(level.next(), reject, function, module, return_value)?; + self.put_block(level.next(), reject, context, return_value)?; } writeln!(self.out, "{}}}", level)?; } @@ -765,19 +680,19 @@ impl Writer { ref default, } => { write!(self.out, "{}switch(", level)?; - self.put_expression(selector, function, module)?; + self.put_expression(selector, context)?; writeln!(self.out, ") {{")?; let lcase = level.next(); for (&value, &(ref block, ref fall_through)) in cases.iter() { writeln!(self.out, "{}case {}: {{", lcase, value)?; - self.put_block(lcase.next(), block, function, module, return_value)?; + self.put_block(lcase.next(), block, context, return_value)?; if fall_through.is_none() { writeln!(self.out, "{}break;", lcase.next())?; } writeln!(self.out, "{}}}", lcase)?; } writeln!(self.out, "{}default: {{", lcase)?; - self.put_block(lcase.next(), default, function, module, return_value)?; + self.put_block(lcase.next(), default, context, return_value)?; writeln!(self.out, "{}}}", lcase)?; writeln!(self.out, "{}}}", level)?; } @@ -786,7 +701,7 @@ impl Writer { ref continuing, } => { writeln!(self.out, "{}while(true) {{", level)?; - self.put_block(level.next(), body, function, module, return_value)?; + self.put_block(level.next(), body, context, return_value)?; if !continuing.is_empty() { //TODO } @@ -802,7 +717,7 @@ impl Writer { value: Some(expr_handle), } => { write!(self.out, "{}return ", level)?; - self.put_expression(expr_handle, function, module)?; + self.put_expression(expr_handle, context)?; writeln!(self.out, ";")?; } crate::Statement::Return { value: None } => { @@ -816,9 +731,9 @@ impl Writer { crate::Statement::Store { pointer, value } => { //write!(self.out, "\t*")?; write!(self.out, "{}", level)?; - self.put_expression(pointer, function, module)?; + self.put_expression(pointer, context)?; write!(self.out, " = ")?; - self.put_expression(value, function, module)?; + self.put_expression(value, context)?; writeln!(self.out, ";")?; } } @@ -827,6 +742,9 @@ impl Writer { } pub fn write(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { + self.names.clear(); + Namer::process(module, RESERVED_WORDS, &mut self.names); + writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; writeln!(self.out, "using namespace metal;")?; @@ -842,7 +760,7 @@ impl Writer { fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { for (handle, ty) in module.types.iter() { - let name = ty.name.or_index(handle); + let name = &self.names[&NameKey::Type(handle)]; match ty.inner { crate::TypeInner::Scalar { kind, .. } => { write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?; @@ -868,7 +786,7 @@ impl Writer { } crate::TypeInner::Pointer { base, class } => { use crate::StorageClass as Sc; - let base_name = module.types[base].name.or_index(base); + let base_name = &self.names[&NameKey::Type(base)]; let class_name = match class { Sc::Input | Sc::Output => continue, Sc::Uniform => "constant", @@ -886,7 +804,7 @@ impl Writer { size, stride: _, } => { - let base_name = module.types[base].name.or_index(base); + let base_name = &self.names[&NameKey::Type(base)]; write!(self.out, "typedef {} {}[", base_name, name)?; match size { crate::ArraySize::Constant(const_handle) => { @@ -899,9 +817,9 @@ impl Writer { crate::TypeInner::Struct { ref members } => { writeln!(self.out, "struct {} {{", name)?; for (index, member) in members.iter().enumerate() { - let name = member.name.or_index(MemberIndex(index)); - let base_name = module.types[member.ty].name.or_index(member.ty); - write!(self.out, "\t{} {}", base_name, name)?; + let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; + let base_name = &self.names[&NameKey::Type(member.ty)]; + write!(self.out, "\t{} {}", base_name, member_name)?; match member.origin { crate::MemberOrigin::Empty => {} crate::MemberOrigin::BuiltIn(built_in) => { @@ -986,40 +904,42 @@ impl Writer { }, )?; - let fun_name = fun.name.or_index(fun_handle); - let result_type_handle = fun.return_type.unwrap(); - let result_type_name = module.types[result_type_handle] - .name - .or_index(result_type_handle); + let fun_name = &self.names[&NameKey::Function(fun_handle)]; + let result_type_name = match fun.return_type { + Some(ret_ty) => &self.names[&NameKey::Type(ret_ty)], + None => "void", + }; writeln!(self.out, "{} {}(", result_type_name, fun_name)?; for (index, &ty) in fun.parameter_types.iter().enumerate() { - let name = Name::from(ParameterIndex(index)); - let member_type_name = module.types[ty].name.or_index(ty); + let name = &self.names[&NameKey::FunctionParameter(fun_handle, index as u32)]; + let param_type_name = &self.names[&NameKey::Type(ty)]; let separator = separate(index + 1 == fun.parameter_types.len()); - writeln!(self.out, "\t{} {}{}", member_type_name, name, separator)?; + writeln!(self.out, "\t{} {}{}", param_type_name, name, separator)?; } writeln!(self.out, ") {{")?; for (local_handle, local) in fun.local_variables.iter() { - let ty_name = module.types[local.ty].name.or_index(local.ty); - write!( - self.out, - "\t{} {}", - ty_name, - local.name.or_index(local_handle) - )?; + let ty_name = &self.names[&NameKey::Type(local.ty)]; + let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; + write!(self.out, "\t{} {}", ty_name, local_name)?; if let Some(value) = local.init { write!(self.out, " = ")?; self.put_constant(value, module)?; } writeln!(self.out, ";")?; } - self.put_block(Level(1), &fun.body, fun, module, None)?; + + let context = ExpressionContext { + function: fun, + origin: FunctionOrigin::Handle(fun_handle), + module, + }; + self.put_block(Level(1), &fun.body, &context, None)?; writeln!(self.out, "}}")?; } - for (&(stage, ref ep_name), ep) in module.entry_points.iter() { + for (ep_index, (&(stage, _), ep)) in module.entry_points.iter().enumerate() { let fun = &ep.function; self.typifier.resolve_all( &fun.expressions, @@ -1050,14 +970,9 @@ impl Writer { } } - let fun_name = format!("{}{:?}", ep_name, stage); - let output_name = Name { - class: "Output", - source: NameSource::Custom { - name: &fun_name, - prefix: true, - }, - }; + let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; + let output_name = format!("{}Output", fun_name); + let location_input_name = format!("{}Input", fun_name); let (em_str, in_mode, out_mode) = match stage { crate::ShaderStage::Vertex => ( @@ -1074,13 +989,6 @@ impl Writer { ("kernel", LocationMode::Uniform, LocationMode::Uniform) } }; - let location_input_name = Name { - class: "Input", - source: NameSource::Custom { - name: &fun_name, - prefix: true, - }, - }; let return_value = match stage { crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { @@ -1096,14 +1004,13 @@ impl Writer { continue; } // if it's a struct, lift all the built-in contents up to the root - let ty_handle = var.ty; - if let crate::TypeInner::Struct { ref members } = - module.types[ty_handle].inner + if let crate::TypeInner::Struct { ref members } = module.types[var.ty].inner { for (index, member) in members.iter().enumerate() { if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { - let name = member.name.or_index(MemberIndex(index)); - let ty_name = module.types[member.ty].name.or_index(member.ty); + let name = + &self.names[&NameKey::StructMember(var.ty, index as u32)]; + let ty_name = &self.names[&NameKey::Type(member.ty)]; write!(self.out, "\t{} {}", ty_name, name)?; ResolvedBinding::BuiltIn(built_in) .try_fmt_decorated(&mut self.out, ";\n")?; @@ -1113,6 +1020,7 @@ impl Writer { { let tyvar = TypedGlobalVariable { module, + names: &self.names, handle, usage: crate::GlobalUse::empty(), }; @@ -1135,13 +1043,12 @@ impl Writer { continue; } // if it's a struct, lift all the built-in contents up to the root - let ty_handle = var.ty; - if let crate::TypeInner::Struct { ref members } = - module.types[ty_handle].inner + if let crate::TypeInner::Struct { ref members } = module.types[var.ty].inner { for (index, member) in members.iter().enumerate() { - let name = member.name.or_index(MemberIndex(index)); - let ty_name = module.types[member.ty].name.or_index(member.ty); + let name = + &self.names[&NameKey::StructMember(var.ty, index as u32)]; + let ty_name = &self.names[&NameKey::Type(member.ty)]; match member.origin { crate::MemberOrigin::Empty => {} crate::MemberOrigin::BuiltIn(built_in) => { @@ -1157,6 +1064,7 @@ impl Writer { } else { let tyvar = TypedGlobalVariable { module, + names: &self.names, handle, usage: crate::GlobalUse::empty(), }; @@ -1214,6 +1122,7 @@ impl Writer { options.resolve_binding(stage, var.binding.as_ref().unwrap(), loc_mode)?; let tyvar = TypedGlobalVariable { module, + names: &self.names, handle, usage, }; @@ -1236,20 +1145,22 @@ impl Writer { crate::ShaderStage::Compute => {} } for (local_handle, local) in fun.local_variables.iter() { - let ty_name = module.types[local.ty].name.or_index(local.ty); - write!( - self.out, - "\t{} {}", - ty_name, - local.name.or_index(local_handle) - )?; + let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; + let ty_name = &self.names[&NameKey::Type(local.ty)]; + write!(self.out, "\t{} {}", ty_name, name)?; if let Some(value) = local.init { write!(self.out, " = ")?; self.put_constant(value, module)?; } writeln!(self.out, ";")?; } - self.put_block(Level(1), &fun.body, fun, module, return_value)?; + + let context = ExpressionContext { + function: fun, + origin: FunctionOrigin::EntryPoint(ep_index as _), + module, + }; + self.put_block(Level(1), &fun.body, &context, return_value)?; writeln!(self.out, "}}")?; } @@ -1258,10 +1169,7 @@ impl Writer { } pub fn write_string(module: &crate::Module, options: &Options) -> Result { - let mut w = Writer { - out: Vec::new(), - typifier: Typifier::new(), - }; + let mut w = Writer::new(Vec::new()); w.write(module, options)?; Ok(String::from_utf8(w.out)?) } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 65ee3a6be..2d5753ea0 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,10 +1,12 @@ //! Module processing functionality. mod interface; +mod namer; mod typifier; mod validator; pub use interface::{Interface, Visitor}; +pub use namer::{EntryPointIndex, NameKey, Namer}; pub use typifier::{check_constant_type, ResolveContext, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; diff --git a/src/proc/namer.rs b/src/proc/namer.rs new file mode 100644 index 000000000..d6296070f --- /dev/null +++ b/src/proc/namer.rs @@ -0,0 +1,122 @@ +use crate::{arena::Handle, FastHashMap}; +use std::collections::hash_map::Entry; + +pub type EntryPointIndex = u16; + +#[derive(Debug, Eq, Hash, PartialEq)] +pub enum NameKey { + GlobalVariable(Handle), + Type(Handle), + StructMember(Handle, u32), + Function(Handle), + FunctionParameter(Handle, u32), + FunctionLocal(Handle, Handle), + EntryPoint(EntryPointIndex), + EntryPointLocal(EntryPointIndex, Handle), +} + +/// This processor assigns names to all the things in a module +/// that may need identifiers in a textual backend. +pub struct Namer { + unique: FastHashMap, +} + +const MAX_PARAM_COUNT: u32 = 100; +const PARAM_NAME: &str = "param"; + +impl Namer { + fn sanitize(string: &str) -> String { + let mut base = string + .chars() + .skip_while(|c| c.is_numeric()) + .filter(|&c| c.is_ascii_alphanumeric() || c == '_') + .collect::(); + // close the name by '_' if the re is a number, so that + // we can have our own number! + match base.chars().next_back() { + Some(c) if !c.is_numeric() => {} + _ => base.push('_'), + }; + base + } + + fn call(&mut self, label_raw: &str) -> String { + let base = Self::sanitize(label_raw); + match self.unique.entry(base) { + Entry::Occupied(mut e) => { + *e.get_mut() += 1; + format!("{}{}", e.key(), e.get()) + } + Entry::Vacant(e) => { + let name = e.key().to_string(); + e.insert(0); + name + } + } + } + + fn call_or(&mut self, label: &Option, fallback: &str) -> String { + self.call(match *label { + Some(ref name) => name, + None => fallback, + }) + } + + pub fn process( + module: &crate::Module, + reserved: &[&str], + output: &mut FastHashMap, + ) { + let mut this = Namer { + unique: reserved + .iter() + .map(|string| (string.to_string(), 0)) + .collect(), + }; + // Force the starting suffix for the function parameter names + // to be higher than whatever we assign explicitly. + this.unique.insert(PARAM_NAME.to_string(), MAX_PARAM_COUNT); + + for (handle, var) in module.global_variables.iter() { + let name = this.call_or(&var.name, "global"); + output.insert(NameKey::GlobalVariable(handle), name); + } + + for (ty_handle, ty) in module.types.iter() { + let ty_name = this.call_or(&ty.name, "type"); + output.insert(NameKey::Type(ty_handle), ty_name); + + if let crate::TypeInner::Struct { ref members } = ty.inner { + for (index, member) in members.iter().enumerate() { + let name = this.call_or(&member.name, "member"); + output.insert(NameKey::StructMember(ty_handle, index as u32), name); + } + } + } + + for (fun_handle, fun) in module.functions.iter() { + let fun_name = this.call_or(&fun.name, "function"); + output.insert(NameKey::Function(fun_handle), fun_name); + if fun.parameter_types.len() >= MAX_PARAM_COUNT as usize { + unreachable!() + } + for (index, _) in fun.parameter_types.iter().enumerate() { + let name = format!("{}{}", PARAM_NAME, index + 1); + output.insert(NameKey::FunctionParameter(fun_handle, index as u32), name); + } + for (handle, var) in fun.local_variables.iter() { + let name = this.call_or(&var.name, "local"); + output.insert(NameKey::FunctionLocal(fun_handle, handle), name); + } + } + + for (ep_index, (&(_, ref base_name), ep)) in module.entry_points.iter().enumerate() { + let ep_name = this.call(base_name); + output.insert(NameKey::EntryPoint(ep_index as _), ep_name); + for (handle, var) in ep.function.local_variables.iter() { + let name = this.call_or(&var.name, "local"); + output.insert(NameKey::EntryPointLocal(ep_index as _, handle), name); + } + } + } +} diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 99ed0a699..0298768c8 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -91,6 +91,16 @@ impl Typifier { } } + pub fn get_handle( + &self, + expr_handle: Handle, + ) -> Option> { + match self.resolutions[expr_handle.index()] { + Resolution::Handle(ty_handle) => Some(ty_handle), + Resolution::Value(_) => None, + } + } + fn resolve_impl( &self, expr: &crate::Expression, From 8b56f3ef9694a60468999fb43bacdc0c6d9e3529 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 11 Nov 2020 15:34:37 -0500 Subject: [PATCH 0272/2212] [ir] support function argument names (#270) --- src/back/glsl.rs | 32 ++++++++++------- src/back/msl.rs | 16 ++++----- src/back/spv/writer.rs | 71 ++++++++++++++++++------------------- src/front/glsl/ast.rs | 4 +-- src/front/glsl/parser.rs | 2 +- src/front/spv/error.rs | 2 +- src/front/spv/function.rs | 11 +++--- src/front/wgsl/mod.rs | 29 ++++++++------- src/lib.rs | 18 +++++++--- src/proc/interface.rs | 4 +-- src/proc/namer.rs | 17 +++------ src/proc/typifier.rs | 6 ++-- src/proc/validator.rs | 2 +- test-data/simple/module.ron | 2 +- 14 files changed, 112 insertions(+), 104 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 79079eb1b..738b1f28f 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -422,10 +422,10 @@ pub fn write<'a>( .as_deref() .unwrap_or("void"), name, - func.parameter_types + func.arguments .iter() - .map(|ty| write_type( - *ty, + .map(|arg| write_type( + arg.ty, &module.types, &module.constants, &structs, @@ -658,15 +658,22 @@ pub fn write<'a>( global_vars: &module.global_variables, local_vars: &func.local_variables, functions: &module.functions, - parameter_types: &func.parameter_types, + arguments: &func.arguments, }, )?; let args: FastHashMap<_, _> = func - .parameter_types + .arguments .iter() .enumerate() - .map(|(pos, _)| (pos as u32, format!("arg_{}", pos))) + .map(|(pos, arg)| { + let name = arg + .name + .clone() + .filter(|ident| is_valid_ident(ident)) + .unwrap_or_else(|| format!("arg_{}", pos + 1)); + (pos as u32, name) + }) .collect(); writeln!( @@ -685,20 +692,19 @@ pub fn write<'a>( .as_deref() .unwrap_or("void"), name, - func.parameter_types + func.arguments .iter() - .zip(args.values()) - .map::, _>(|(ty, name)| { + .enumerate() + .map::, _>(|(pos, arg)| { let ty = write_type( - *ty, + arg.ty, &module.types, &module.constants, &structs, None, &mut manager, )?; - - Ok(format!("{} {}", ty, name)) + Ok(format!("{} {}", ty, args[&(pos as u32)])) }) .collect::, _>>()? .join(","), @@ -1035,7 +1041,7 @@ fn write_expression<'a, 'b>( .join(","), )) } - Expression::FunctionParameter(pos) => Cow::Borrowed(builder.args.get(&pos).unwrap()), + Expression::FunctionArgument(pos) => Cow::Borrowed(builder.args.get(&pos).unwrap()), Expression::GlobalVariable(handle) => Cow::Borrowed(builder.globals.get(&handle).unwrap()), Expression::LocalVariable(handle) => { Cow::Borrowed(builder.locals_lookup.get(&handle).unwrap()) diff --git a/src/back/msl.rs b/src/back/msl.rs index 6cae5efa3..61702e3bf 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -383,12 +383,12 @@ impl Writer { _ => return Err(Error::UnsupportedCompose(ty)), } } - crate::Expression::FunctionParameter(index) => { + crate::Expression::FunctionArgument(index) => { let fun_handle = match context.origin { FunctionOrigin::Handle(handle) => handle, FunctionOrigin::EntryPoint(_) => unreachable!(), }; - let name = &self.names[&NameKey::FunctionParameter(fun_handle, index)]; + let name = &self.names[&NameKey::FunctionArgument(fun_handle, index)]; write!(self.out, "{}", name)?; } crate::Expression::GlobalVariable(handle) => { @@ -900,7 +900,7 @@ impl Writer { global_vars: &module.global_variables, local_vars: &fun.local_variables, functions: &module.functions, - parameter_types: &fun.parameter_types, + arguments: &fun.arguments, }, )?; @@ -911,10 +911,10 @@ impl Writer { }; writeln!(self.out, "{} {}(", result_type_name, fun_name)?; - for (index, &ty) in fun.parameter_types.iter().enumerate() { - let name = &self.names[&NameKey::FunctionParameter(fun_handle, index as u32)]; - let param_type_name = &self.names[&NameKey::Type(ty)]; - let separator = separate(index + 1 == fun.parameter_types.len()); + for (index, arg) in fun.arguments.iter().enumerate() { + let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; + let param_type_name = &self.names[&NameKey::Type(arg.ty)]; + let separator = separate(index + 1 == fun.arguments.len()); writeln!(self.out, "\t{} {}{}", param_type_name, name, separator)?; } writeln!(self.out, ") {{")?; @@ -949,7 +949,7 @@ impl Writer { global_vars: &module.global_variables, local_vars: &fun.local_variables, functions: &module.functions, - parameter_types: &fun.parameter_types, + arguments: &fun.arguments, }, )?; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index c9aaf8144..823e6a32e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -324,21 +324,18 @@ impl Writer { let return_type_id = self.get_function_return_type(ir_function.return_type, &ir_module.types); - let mut parameter_type_ids = Vec::with_capacity(ir_function.parameter_types.len()); + let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); let mut function_parameter_pointer_ids = vec![]; - for parameter_type in ir_function.parameter_types.iter() { + for argument in ir_function.arguments.iter() { let id = self.generate_id(); - let pointer_id = self.get_pointer_id( - &ir_module.types, - *parameter_type, - crate::StorageClass::Function, - ); + let pointer_id = + self.get_pointer_id(&ir_module.types, argument.ty, crate::StorageClass::Function); function_parameter_pointer_ids.push(pointer_id); parameter_type_ids - .push(self.get_type_id(&ir_module.types, LookupType::Handle(*parameter_type))); + .push(self.get_type_id(&ir_module.types, LookupType::Handle(argument.ty))); function .parameters .push(super::instructions::instruction_function_parameter( @@ -868,21 +865,21 @@ impl Writer { block: &mut Block, function: &mut Function, ) -> Result { - match expression { + match *expression { crate::Expression::Access { base, index } => { let id = self.generate_id(); let (base_id, base_lookup_ty) = self.write_expression( ir_module, ir_function, - &ir_function.expressions[*base], + &ir_function.expressions[base], block, function, )?; let (index_id, _) = self.write_expression( ir_module, ir_function, - &ir_function.expressions[*index], + &ir_function.expressions[index], block, function, )?; @@ -926,7 +923,7 @@ impl Writer { .write_expression( ir_module, ir_function, - &ir_function.expressions[*base], + &ir_function.expressions[base], block, function, ) @@ -947,7 +944,7 @@ impl Writer { ) } crate::TypeInner::Struct { ref members } => { - let member = &members[*index as usize]; + let member = &members[index as usize]; let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(member.ty)); ( @@ -966,7 +963,7 @@ impl Writer { width: 4, }), ); - let const_id = self.create_constant(const_ty_id, &[*index]); + let const_id = self.create_constant(const_ty_id, &[index]); block .body @@ -985,18 +982,18 @@ impl Writer { Ok((load_id, Some(lookup_ty))) } crate::Expression::GlobalVariable(handle) => { - let var = &ir_module.global_variables[*handle]; - let id = self.get_global_variable_id(&ir_module, *handle); + let var = &ir_module.global_variables[handle]; + let id = self.get_global_variable_id(&ir_module, handle); Ok((id, Some(LookupType::Handle(var.ty)))) } crate::Expression::Constant(handle) => { - let var = &ir_module.constants[*handle]; - let id = self.get_constant_id(*handle, ir_module); + let var = &ir_module.constants[handle]; + let id = self.get_constant_id(handle, ir_module); Ok((id, Some(LookupType::Handle(var.ty)))) } crate::Expression::Compose { ty, ref components } => { - let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*ty)); + let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty)); let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { @@ -1013,7 +1010,7 @@ impl Writer { } let constituent_ids_slice = constituent_ids.as_slice(); - let id = match ir_module.types[*ty].inner { + let id = match ir_module.types[ty].inner { crate::TypeInner::Vector { .. } => { self.write_composite_construct(base_type_id, constituent_ids_slice, block) } @@ -1053,14 +1050,14 @@ impl Writer { _ => unreachable!(), }; - Ok((id, Some(LookupType::Handle(*ty)))) + Ok((id, Some(LookupType::Handle(ty)))) } crate::Expression::Binary { op, left, right } => { match op { crate::BinaryOperator::Multiply => { let id = self.generate_id(); - let left_expression = &ir_function.expressions[*left]; - let right_expression = &ir_function.expressions[*right]; + let left_expression = &ir_function.expressions[left]; + let right_expression = &ir_function.expressions[right]; let (left_id, left_lookup_ty) = self.write_expression( ir_module, ir_function, @@ -1205,7 +1202,7 @@ impl Writer { } } crate::Expression::LocalVariable(variable) => { - let var = &ir_function.local_variables[*variable]; + let var = &ir_function.local_variables[variable]; function .variables .iter() @@ -1213,25 +1210,25 @@ impl Writer { .map(|local_var| (local_var.id, Some(LookupType::Handle(var.ty)))) .ok_or_else(|| Error::UnknownLocalVariable(var.clone())) } - crate::Expression::FunctionParameter(index) => { - let handle = ir_function.parameter_types.get(*index as usize).unwrap(); - let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(*handle)); + crate::Expression::FunctionArgument(index) => { + let handle = ir_function.arguments[index as usize].ty; + let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(handle)); let load_id = self.generate_id(); block.body.push(super::instructions::instruction_load( type_id, load_id, - function.parameters[*index as usize].result_id.unwrap(), + function.parameters[index as usize].result_id.unwrap(), None, )); - Ok((load_id, Some(LookupType::Handle(*handle)))) + Ok((load_id, Some(LookupType::Handle(handle)))) } crate::Expression::Call { ref origin, ref arguments, - } => match origin { + } => match *origin { crate::FunctionOrigin::Local(local_function) => { - let origin_function = &ir_module.functions[*local_function]; + let origin_function = &ir_module.functions[local_function]; let id = self.generate_id(); let mut argument_ids = vec![]; @@ -1306,7 +1303,7 @@ impl Writer { let (expr_id, expr_type) = self.write_expression( ir_module, ir_function, - &ir_function.expressions[*expr], + &ir_function.expressions[expr], block, function, )?; @@ -1321,10 +1318,10 @@ impl Writer { } => { let kind_type_id = self.get_type_id( &ir_module.types, - LookupType::Local(LocalType::Scalar { kind: *kind, width }), + LookupType::Local(LocalType::Scalar { kind, width }), ); - if *convert { + if convert { super::instructions::instruction_bit_cast(kind_type_id, id, expr_id) } else { match (expr_kind, kind) { @@ -1375,7 +1372,7 @@ impl Writer { depth_ref: _, } => { // image - let image_expression = &ir_function.expressions[*image]; + let image_expression = &ir_function.expressions[image]; let (image_id, image_lookup_ty) = self.write_expression( ir_module, ir_function, @@ -1414,7 +1411,7 @@ impl Writer { ); // sampler - let sampler_expression = &ir_function.expressions[*sampler]; + let sampler_expression = &ir_function.expressions[sampler]; let (sampler_id, sampler_lookup_ty) = self.write_expression( ir_module, ir_function, @@ -1440,7 +1437,7 @@ impl Writer { }; // coordinate - let coordinate_expression = &ir_function.expressions[*coordinate]; + let coordinate_expression = &ir_function.expressions[coordinate]; let (coordinate_id, coordinate_lookup_ty) = self.write_expression( ir_module, ir_function, diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index a4acf3a91..58161ad7b 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -57,13 +57,13 @@ impl Program { handle: Handle, ) -> Result<&crate::TypeInner, ErrorKind> { let functions = Arena::new(); //TODO - let parameter_types: Vec> = vec![]; //TODO + let arguments = Vec::new(); //TODO let resolve_ctx = ResolveContext { constants: &self.module.constants, global_vars: &self.module.global_variables, local_vars: &self.context.local_variables, functions: &functions, - parameter_types: ¶meter_types, + arguments: &arguments, }; match self.context.typifier.grow( handle, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 341ef58bc..1171b4d0a 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1007,7 +1007,7 @@ pomelo! { function_header ::= fully_specified_type(t) Identifier(n) LeftParen { Function { name: Some(n.1), - parameter_types: vec![], + arguments: vec![], return_type: t.1, global_usage: vec![], local_variables: Arena::::new(), diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 5cc624970..0ebf60391 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -46,7 +46,7 @@ pub enum Error { InvalidAsType(Handle), InconsistentComparisonSampling(Handle), WrongFunctionResultType(spirv::Word), - WrongFunctionParameterType(spirv::Word), + WrongFunctionArgumentType(spirv::Word), MissingDecoration(spirv::Decoration), BadString, IncompleteData, diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index eed33ddfe..d2cb0551a 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -69,7 +69,7 @@ impl> super::Parser { } crate::Function { name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name), - parameter_types: Vec::with_capacity(ft.parameter_type_ids.len()), + arguments: Vec::with_capacity(ft.parameter_type_ids.len()), return_type: if self.lookup_void_type.contains(&result_type) { None } else { @@ -83,7 +83,7 @@ impl> super::Parser { }; // read parameters - for i in 0..fun.parameter_types.capacity() { + for i in 0..fun.arguments.capacity() { match self.next_inst()? { Instruction { op: spirv::Op::FunctionParameter, @@ -93,7 +93,7 @@ impl> super::Parser { let id = self.next()?; let handle = fun .expressions - .append(crate::Expression::FunctionParameter(i as u32)); + .append(crate::Expression::FunctionArgument(i as u32)); self.lookup_expression .insert(id, LookupExpression { type_id, handle }); //Note: we redo the lookup in order to work around `self` borrowing @@ -104,10 +104,11 @@ impl> super::Parser { .lookup(fun_type)? .parameter_type_ids[i] { - return Err(Error::WrongFunctionParameterType(type_id)); + return Err(Error::WrongFunctionArgumentType(type_id)); } let ty = self.lookup_type.lookup(type_id)?.handle; - fun.parameter_types.push(ty); + fun.arguments + .push(crate::FunctionArgument { name: None, ty }); } Instruction { op, .. } => return Err(Error::InvalidParameter(op)), } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 83874bf0f..3b1771900 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -97,7 +97,7 @@ struct StatementContext<'input, 'temp, 'out> { types: &'out mut Arena, constants: &'out mut Arena, global_vars: &'out Arena, - parameter_types: &'out [Handle], + arguments: &'out [crate::FunctionArgument], } impl<'a> StatementContext<'a, '_, '_> { @@ -110,7 +110,7 @@ impl<'a> StatementContext<'a, '_, '_> { types: self.types, constants: self.constants, global_vars: self.global_vars, - parameter_types: self.parameter_types, + arguments: self.arguments, } } @@ -123,7 +123,7 @@ impl<'a> StatementContext<'a, '_, '_> { constants: self.constants, global_vars: self.global_vars, local_vars: self.variables, - parameter_types: self.parameter_types, + arguments: self.arguments, } } } @@ -136,7 +136,7 @@ struct ExpressionContext<'input, 'temp, 'out> { constants: &'out mut Arena, global_vars: &'out Arena, local_vars: &'out Arena, - parameter_types: &'out [Handle], + arguments: &'out [crate::FunctionArgument], } impl<'a> ExpressionContext<'a, '_, '_> { @@ -149,7 +149,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { constants: self.constants, global_vars: self.global_vars, local_vars: self.local_vars, - parameter_types: self.parameter_types, + arguments: self.arguments, } } @@ -163,7 +163,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { global_vars: self.global_vars, local_vars: self.local_vars, functions: &functions, - parameter_types: self.parameter_types, + arguments: self.arguments, }; match self .typifier @@ -1545,19 +1545,22 @@ impl Parser { lookup_ident.insert(name, expr_handle); } // read parameter list - let mut parameter_types = Vec::new(); + let mut arguments = Vec::new(); lexer.expect(Token::Paren('('))?; while !lexer.skip(Token::Paren(')')) { - if !parameter_types.is_empty() { + if !arguments.is_empty() { lexer.expect(Token::Separator(','))?; } let (param_name, param_type) = self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; - let param_index = parameter_types.len() as u32; + let param_index = arguments.len() as u32; let expression_token = - expressions.append(crate::Expression::FunctionParameter(param_index)); + expressions.append(crate::Expression::FunctionArgument(param_index)); lookup_ident.insert(param_name, expression_token); - parameter_types.push(param_type); + arguments.push(crate::FunctionArgument { + name: Some(param_name.to_string()), + ty: param_type, + }); } // read return type lexer.expect(Token::Arrow)?; @@ -1569,7 +1572,7 @@ impl Parser { let mut fun = crate::Function { name: Some(fun_name.to_string()), - parameter_types, + arguments, return_type, global_usage: Vec::new(), local_variables: Arena::new(), @@ -1589,7 +1592,7 @@ impl Parser { types: &mut module.types, constants: &mut module.constants, global_vars: &module.global_variables, - parameter_types: &fun.parameter_types, + arguments: &fun.arguments, }, )?; // done diff --git a/src/lib.rs b/src/lib.rs index c82e9c4e8..aefc6d066 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -584,7 +584,7 @@ pub enum Expression { components: Vec>, }, /// Reference a function parameter, by its index. - FunctionParameter(u32), + FunctionArgument(u32), /// Reference a global variable. GlobalVariable(Handle), /// Reference a local variable. @@ -702,6 +702,17 @@ pub enum Statement { }, } +/// A function argument. +#[derive(Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub struct FunctionArgument { + /// Name of the argument, if any. + pub name: Option, + /// Type of the argument. + pub ty: Handle, +} + /// A function defined in the module. #[derive(Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -709,9 +720,8 @@ pub enum Statement { pub struct Function { /// Name of the function, if any. pub name: Option, - //pub control: spirv::FunctionControl, - /// The types of the parameters of this function. - pub parameter_types: Vec>, + /// Information about function argument. + pub arguments: Vec, /// The return type of this function, if any. pub return_type: Option>, /// Vector of global variable usages. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 03cbf3e40..f9389c29f 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -37,7 +37,7 @@ where self.traverse_expr(comp); } } - E::FunctionParameter(_) | E::GlobalVariable(_) | E::LocalVariable(_) => {} + E::FunctionArgument(_) | E::GlobalVariable(_) | E::LocalVariable(_) => {} E::Load { pointer } => { self.traverse_expr(pointer); } @@ -259,7 +259,7 @@ mod tests { let mut function = crate::Function { name: None, - parameter_types: Vec::new(), + arguments: Vec::new(), return_type: None, local_variables: Arena::new(), expressions, diff --git a/src/proc/namer.rs b/src/proc/namer.rs index d6296070f..03b508904 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -9,7 +9,7 @@ pub enum NameKey { Type(Handle), StructMember(Handle, u32), Function(Handle), - FunctionParameter(Handle, u32), + FunctionArgument(Handle, u32), FunctionLocal(Handle, Handle), EntryPoint(EntryPointIndex), EntryPointLocal(EntryPointIndex, Handle), @@ -21,9 +21,6 @@ pub struct Namer { unique: FastHashMap, } -const MAX_PARAM_COUNT: u32 = 100; -const PARAM_NAME: &str = "param"; - impl Namer { fn sanitize(string: &str) -> String { let mut base = string @@ -73,9 +70,6 @@ impl Namer { .map(|string| (string.to_string(), 0)) .collect(), }; - // Force the starting suffix for the function parameter names - // to be higher than whatever we assign explicitly. - this.unique.insert(PARAM_NAME.to_string(), MAX_PARAM_COUNT); for (handle, var) in module.global_variables.iter() { let name = this.call_or(&var.name, "global"); @@ -97,12 +91,9 @@ impl Namer { for (fun_handle, fun) in module.functions.iter() { let fun_name = this.call_or(&fun.name, "function"); output.insert(NameKey::Function(fun_handle), fun_name); - if fun.parameter_types.len() >= MAX_PARAM_COUNT as usize { - unreachable!() - } - for (index, _) in fun.parameter_types.iter().enumerate() { - let name = format!("{}{}", PARAM_NAME, index + 1); - output.insert(NameKey::FunctionParameter(fun_handle, index as u32), name); + for (index, arg) in fun.arguments.iter().enumerate() { + let name = this.call_or(&arg.name, "param"); + output.insert(NameKey::FunctionArgument(fun_handle, index as u32), name); } for (handle, var) in fun.local_variables.iter() { let name = this.call_or(&var.name, "local"); diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 0298768c8..70142ffe5 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -66,7 +66,7 @@ pub struct ResolveContext<'a> { pub global_vars: &'a Arena, pub local_vars: &'a Arena, pub functions: &'a Arena, - pub parameter_types: &'a [Handle], + pub arguments: &'a [crate::FunctionArgument], } impl Typifier { @@ -168,8 +168,8 @@ impl Typifier { }, crate::Expression::Constant(h) => Resolution::Handle(ctx.constants[h].ty), crate::Expression::Compose { ty, .. } => Resolution::Handle(ty), - crate::Expression::FunctionParameter(index) => { - Resolution::Handle(ctx.parameter_types[index as usize]) + crate::Expression::FunctionArgument(index) => { + Resolution::Handle(ctx.arguments[index as usize].ty) } crate::Expression::GlobalVariable(h) => Resolution::Handle(ctx.global_vars[h].ty), crate::Expression::LocalVariable(h) => Resolution::Handle(ctx.local_vars[h].ty), diff --git a/src/proc/validator.rs b/src/proc/validator.rs index b6d770ab7..a03d772c0 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -252,7 +252,7 @@ impl Validator { global_vars: &module.global_variables, local_vars: &fun.local_variables, functions: &module.functions, - parameter_types: &fun.parameter_types, + arguments: &fun.arguments, }; self.typifier .resolve_all(&fun.expressions, &module.types, &resolve_ctx)?; diff --git a/test-data/simple/module.ron b/test-data/simple/module.ron index bcc93f020..76a4b4857 100644 --- a/test-data/simple/module.ron +++ b/test-data/simple/module.ron @@ -73,7 +73,7 @@ workgroup_size: (0, 0, 0), function: ( name: Some("main"), - parameter_types: [], + arguments: [], return_type: None, global_usage: [ ( From 5e77653c557d7c6ae8a49a71b9fdf59f5b21a1e4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 12 Nov 2020 11:34:25 -0500 Subject: [PATCH 0273/2212] [ir] select expression --- src/back/glsl.rs | 16 ++++++++++++++++ src/back/msl.rs | 13 +++++++++++++ src/front/spv/mod.rs | 25 +++++++++++++++++++++++++ src/lib.rs | 7 +++++++ src/proc/interface.rs | 9 +++++++++ src/proc/typifier.rs | 1 + 6 files changed, 71 insertions(+) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 738b1f28f..2b1328305 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1208,6 +1208,22 @@ fn write_expression<'a, 'b>( Cow::Owned(format!("({} {} {})", left_expr, op_str, right_expr)) } + Expression::Select { + condition, + accept, + reject, + } => { + let cond_expr = + write_expression(&builder.expressions[condition], module, builder, manager)?; + let accept_expr = + write_expression(&builder.expressions[accept], module, builder, manager)?; + let reject_expr = + write_expression(&builder.expressions[reject], module, builder, manager)?; + Cow::Owned(format!( + "({} ? {} : {})", + cond_expr, accept_expr, reject_expr + )) + } Expression::Intrinsic { fun, argument } => { let expr = write_expression(&builder.expressions[argument], module, builder, manager)?; diff --git a/src/back/msl.rs b/src/back/msl.rs index 61702e3bf..9f105ddaf 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -524,6 +524,19 @@ impl Writer { //write!(self.out, ")")?; } } + crate::Expression::Select { + condition, + accept, + reject, + } => { + write!(self.out, "(")?; + self.put_expression(condition, context)?; + write!(self.out, " ? ")?; + self.put_expression(accept, context)?; + write!(self.out, " : ")?; + self.put_expression(reject, context)?; + write!(self.out, ")")?; + } crate::Expression::Intrinsic { fun, argument } => { let op = match fun { crate::IntrinsicFunction::Any => "any", diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index b7744ddcf..7940da269 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1067,6 +1067,31 @@ impl> Parser { }, ); } + Op::Select => { + inst.expect(6)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let condition = self.next()?; + let o1_id = self.next()?; + let o2_id = self.next()?; + + let cond_lexp = self.lookup_expression.lookup(condition)?; + let o1_lexp = self.lookup_expression.lookup(o1_id)?; + let o2_lexp = self.lookup_expression.lookup(o2_id)?; + + let expr = crate::Expression::Select { + condition: cond_lexp.handle, + accept: o1_lexp.handle, + reject: o2_lexp.handle, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } Op::VectorShuffle => { inst.expect_at_least(5)?; let result_type_id = self.next()?; diff --git a/src/lib.rs b/src/lib.rs index aefc6d066..4d24a7bb5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -619,6 +619,13 @@ pub enum Expression { left: Handle, right: Handle, }, + /// Select between two values based on a condition. + Select { + /// Boolean expression + condition: Handle, + accept: Handle, + reject: Handle, + }, /// Call an intrinsic function. Intrinsic { fun: IntrinsicFunction, diff --git a/src/proc/interface.rs b/src/proc/interface.rs index f9389c29f..b512452fe 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -79,6 +79,15 @@ where self.traverse_expr(left); self.traverse_expr(right); } + E::Select { + condition, + accept, + reject, + } => { + self.traverse_expr(condition); + self.traverse_expr(accept); + self.traverse_expr(reject); + } E::Intrinsic { argument, .. } => { self.traverse_expr(argument); } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 70142ffe5..be9e17afc 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -245,6 +245,7 @@ impl Typifier { | crate::BinaryOperator::ShiftLeft | crate::BinaryOperator::ShiftRight => self.resolutions[left.index()].clone(), }, + crate::Expression::Select { accept, .. } => self.resolutions[accept.index()].clone(), crate::Expression::Intrinsic { .. } => unimplemented!(), crate::Expression::Transpose(expr) => match *self.get(expr, types) { crate::TypeInner::Matrix { From 4d4e1cd4cbfad2b81264a7239a336b6ec1346611 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 12 Nov 2020 12:38:00 -0500 Subject: [PATCH 0274/2212] [spv] support GLSL's Distance --- src/front/spv/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 7940da269..f13c3c757 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1283,6 +1283,10 @@ impl> Parser { inst.expect(base_wc + 1)?; "length" } + Some(spirv::GLOp::Distance) => { + inst.expect(base_wc + 2)?; + "distance" + } Some(spirv::GLOp::Cross) => { inst.expect(base_wc + 2)?; "cross" From a1dc8c2d2896cf623a5b21409d704b6470615f01 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Tue, 10 Nov 2020 20:42:35 +0100 Subject: [PATCH 0275/2212] [spv-out] Fix duplicate scalar OpType --- src/back/spv/writer.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 823e6a32e..264091572 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -189,7 +189,16 @@ impl Writer { *e.get() } else { match lookup_ty { - LookupType::Handle(handle) => self.write_type_declaration_arena(arena, handle), + LookupType::Handle(handle) => match arena[handle].inner { + crate::TypeInner::Scalar { kind, width } => self.get_type_id( + arena, + LookupType::Local(LocalType::Scalar { + kind, + width, + }), + ), + _ => self.write_type_declaration_arena(arena, handle), + }, LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty), } } From cbcdcf470fbd6f97e2f8672dadc2b06c236ba6e1 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sat, 14 Nov 2020 11:36:57 +0100 Subject: [PATCH 0276/2212] [spv-out] Add and implement i_sub and f_sub --- src/back/spv/instructions.rs | 46 ++++-- src/back/spv/writer.rs | 302 ++++++++++++++++++----------------- 2 files changed, 190 insertions(+), 158 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 6741dbbf6..b763f7c54 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -571,6 +571,38 @@ pub(super) fn instruction_composite_construct( // // Arithmetic Instructions // +fn instruction_binary( + op: Op, + result_type_id: Word, + id: Word, + operand_1: Word, + operand_2: Word, +) -> Instruction { + let mut instruction = Instruction::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(operand_1); + instruction.add_operand(operand_2); + instruction +} + +pub(super) fn instruction_i_sub( + result_type_id: Word, + id: Word, + operand_1: Word, + operand_2: Word, +) -> Instruction { + instruction_binary(Op::ISub, result_type_id, id, operand_1, operand_2) +} + +pub(super) fn instruction_f_sub( + result_type_id: Word, + id: Word, + operand_1: Word, + operand_2: Word, +) -> Instruction { + instruction_binary(Op::FSub, result_type_id, id, operand_1, operand_2) +} pub(super) fn instruction_i_mul( result_type_id: Word, @@ -578,12 +610,7 @@ pub(super) fn instruction_i_mul( operand_1: Word, operand_2: Word, ) -> Instruction { - let mut instruction = Instruction::new(Op::IMul); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(operand_1); - instruction.add_operand(operand_2); - instruction + instruction_binary(Op::IMul, result_type_id, id, operand_1, operand_2) } pub(super) fn instruction_f_mul( @@ -592,12 +619,7 @@ pub(super) fn instruction_f_mul( operand_1: Word, operand_2: Word, ) -> Instruction { - let mut instruction = Instruction::new(Op::FMul); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(operand_1); - instruction.add_operand(operand_2); - instruction + instruction_binary(Op::FMul, result_type_id, id, operand_1, operand_2) } pub(super) fn instruction_vector_times_scalar( diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 264091572..96062ac01 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -190,13 +190,8 @@ impl Writer { } else { match lookup_ty { LookupType::Handle(handle) => match arena[handle].inner { - crate::TypeInner::Scalar { kind, width } => self.get_type_id( - arena, - LookupType::Local(LocalType::Scalar { - kind, - width, - }), - ), + crate::TypeInner::Scalar { kind, width } => self + .get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width })), _ => self.write_type_declaration_arena(arena, handle), }, LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty), @@ -1062,153 +1057,168 @@ impl Writer { Ok((id, Some(LookupType::Handle(ty)))) } crate::Expression::Binary { op, left, right } => { - match op { - crate::BinaryOperator::Multiply => { - let id = self.generate_id(); - let left_expression = &ir_function.expressions[left]; - let right_expression = &ir_function.expressions[right]; - let (left_id, left_lookup_ty) = self.write_expression( - ir_module, - ir_function, - left_expression, - block, - function, - )?; - let (right_id, right_lookup_ty) = self.write_expression( - ir_module, - ir_function, - right_expression, - block, - function, - )?; + let id = self.generate_id(); + let left_expression = &ir_function.expressions[left]; + let right_expression = &ir_function.expressions[right]; + let (left_id, left_lookup_ty) = self.write_expression( + ir_module, + ir_function, + left_expression, + block, + function, + )?; + let (right_id, right_lookup_ty) = self.write_expression( + ir_module, + ir_function, + right_expression, + block, + function, + )?; - let left_lookup_ty = left_lookup_ty.unwrap(); - let right_lookup_ty = right_lookup_ty.unwrap(); + let left_lookup_ty = left_lookup_ty.unwrap(); + let right_lookup_ty = right_lookup_ty.unwrap(); - let left_ty_inner = self.get_type_inner(&ir_module.types, left_lookup_ty); - let right_ty_inner = self.get_type_inner(&ir_module.types, right_lookup_ty); + let left_ty_inner = self.get_type_inner(&ir_module.types, left_lookup_ty); + let right_ty_inner = self.get_type_inner(&ir_module.types, right_lookup_ty); - let left_result_type_id = - self.get_type_id(&ir_module.types, left_lookup_ty); + let left_result_type_id = self.get_type_id(&ir_module.types, left_lookup_ty); - let right_result_type_id = - self.get_type_id(&ir_module.types, right_lookup_ty); + let right_result_type_id = self.get_type_id(&ir_module.types, right_lookup_ty); - let left_id = match *left_expression { - crate::Expression::LocalVariable(_) - | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - left_result_type_id, - load_id, - left_id, - None, - )); - load_id - } - _ => left_id, - }; - - let right_id = match *right_expression { - crate::Expression::LocalVariable(..) - | crate::Expression::GlobalVariable(..) => { - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - right_result_type_id, - load_id, - right_id, - None, - )); - load_id - } - _ => right_id, - }; - - let (instruction, lookup_ty) = match *left_ty_inner { - crate::TypeInner::Vector { .. } => match *right_ty_inner { - crate::TypeInner::Scalar { .. } => ( - super::instructions::instruction_vector_times_scalar( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - crate::TypeInner::Matrix { .. } => ( - super::instructions::instruction_vector_times_matrix( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - _ => unreachable!(), - }, - crate::TypeInner::Matrix { .. } => match *right_ty_inner { - crate::TypeInner::Scalar { .. } => ( - super::instructions::instruction_matrix_times_scalar( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - crate::TypeInner::Vector { .. } => ( - super::instructions::instruction_matrix_times_vector( - right_result_type_id, - id, - left_id, - right_id, - ), - right_lookup_ty, - ), - crate::TypeInner::Matrix { .. } => ( - super::instructions::instruction_matrix_times_matrix( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - _ => unreachable!(), - }, - crate::TypeInner::Scalar { kind, .. } => { - // Always assuming left and hand side are equal scalar types. - match kind { - crate::ScalarKind::Float => ( - super::instructions::instruction_f_mul( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - crate::ScalarKind::Sint | crate::ScalarKind::Uint => ( - super::instructions::instruction_i_mul( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - _ => unreachable!(), - } - } - _ => unreachable!(), - }; - - block.body.push(instruction); - Ok((id, Some(lookup_ty))) + let left_id = match *left_expression { + crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + left_result_type_id, + load_id, + left_id, + None, + )); + load_id } + _ => left_id, + }; + let right_id = match *right_expression { + crate::Expression::LocalVariable(..) + | crate::Expression::GlobalVariable(..) => { + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + right_result_type_id, + load_id, + right_id, + None, + )); + load_id + } + _ => right_id, + }; + + let (instruction, lookup_ty) = match op { + crate::BinaryOperator::Multiply => match *left_ty_inner { + crate::TypeInner::Vector { .. } => match *right_ty_inner { + crate::TypeInner::Scalar { .. } => ( + super::instructions::instruction_vector_times_scalar( + left_result_type_id, + id, + left_id, + right_id, + ), + left_lookup_ty, + ), + crate::TypeInner::Matrix { .. } => ( + super::instructions::instruction_vector_times_matrix( + left_result_type_id, + id, + left_id, + right_id, + ), + left_lookup_ty, + ), + _ => unreachable!(), + }, + crate::TypeInner::Matrix { .. } => match *right_ty_inner { + crate::TypeInner::Scalar { .. } => ( + super::instructions::instruction_matrix_times_scalar( + left_result_type_id, + id, + left_id, + right_id, + ), + left_lookup_ty, + ), + crate::TypeInner::Vector { .. } => ( + super::instructions::instruction_matrix_times_vector( + right_result_type_id, + id, + left_id, + right_id, + ), + right_lookup_ty, + ), + crate::TypeInner::Matrix { .. } => ( + super::instructions::instruction_matrix_times_matrix( + left_result_type_id, + id, + left_id, + right_id, + ), + left_lookup_ty, + ), + _ => unreachable!(), + }, + crate::TypeInner::Scalar { kind, .. } => match kind { + crate::ScalarKind::Sint | crate::ScalarKind::Uint => ( + super::instructions::instruction_i_mul( + left_result_type_id, + id, + left_id, + right_id, + ), + left_lookup_ty, + ), + crate::ScalarKind::Float => ( + super::instructions::instruction_f_mul( + left_result_type_id, + id, + left_id, + right_id, + ), + left_lookup_ty, + ), + _ => unreachable!(), + }, + _ => unreachable!(), + }, + crate::BinaryOperator::Subtract => match *left_ty_inner { + crate::TypeInner::Scalar { kind, .. } => match kind { + crate::ScalarKind::Sint | crate::ScalarKind::Uint => ( + super::instructions::instruction_i_sub( + left_result_type_id, + id, + left_id, + right_id, + ), + left_lookup_ty, + ), + crate::ScalarKind::Float => ( + super::instructions::instruction_f_sub( + left_result_type_id, + id, + left_id, + right_id, + ), + left_lookup_ty, + ), + _ => unreachable!(), + }, + _ => unreachable!(), + }, _ => unimplemented!("{:?}", op), - } + }; + + block.body.push(instruction); + Ok((id, Some(lookup_ty))) } crate::Expression::LocalVariable(variable) => { let var = &ir_function.local_variables[variable]; From d0de2faa7374875195d07bdf90c44ad3a09d7dfe Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sat, 14 Nov 2020 12:29:01 +0100 Subject: [PATCH 0277/2212] [spv-out] Add and implement bitwise_and --- src/back/spv/instructions.rs | 9 +++++++++ src/back/spv/writer.rs | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index b763f7c54..53bdcd314 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -696,6 +696,15 @@ pub(super) fn instruction_matrix_times_matrix( // Bit Instructions // +pub(super) fn instruction_bitwise_and( + result_type_id: Word, + id: Word, + operand_1: Word, + operand_2: Word, +) -> Instruction { + instruction_binary(Op::BitwiseAnd, result_type_id, id, operand_1, operand_2) +} + // // Relational and Logical Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 96062ac01..5621d1328 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1214,6 +1214,15 @@ impl Writer { }, _ => unreachable!(), }, + crate::BinaryOperator::And => ( + super::instructions::instruction_bitwise_and( + left_result_type_id, + id, + left_id, + right_id, + ), + left_lookup_ty, + ), _ => unimplemented!("{:?}", op), }; From 022b42c44b21283b5ac9bfb198e6aa1b9c0e9f5c Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sat, 14 Nov 2020 19:08:13 +0100 Subject: [PATCH 0278/2212] [spv-out] Reduce BinaryOperator::Multiply indentation --- src/back/spv/writer.rs | 133 ++++++++++++++++++++++------------------- 1 file changed, 73 insertions(+), 60 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 5621d1328..06149c693 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -135,6 +135,21 @@ impl<'a, T> ops::Deref for MaybeOwned<'a, T> { } } +enum Dimension { + Scalar, + Vector, + Matrix, +} + +fn get_dimension(ty_inner: &crate::TypeInner) -> Dimension { + match *ty_inner { + crate::TypeInner::Scalar { .. } => Dimension::Scalar, + crate::TypeInner::Vector { .. } => Dimension::Vector, + crate::TypeInner::Matrix { .. } => Dimension::Matrix, + _ => unreachable!(), + } +} + pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, @@ -1114,70 +1129,60 @@ impl Writer { _ => right_id, }; + let left_dimension = get_dimension(&left_ty_inner); + let right_dimension = get_dimension(&right_ty_inner); + let (instruction, lookup_ty) = match op { - crate::BinaryOperator::Multiply => match *left_ty_inner { - crate::TypeInner::Vector { .. } => match *right_ty_inner { - crate::TypeInner::Scalar { .. } => ( - super::instructions::instruction_vector_times_scalar( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, + crate::BinaryOperator::Multiply => match (left_dimension, right_dimension) { + (Dimension::Vector, Dimension::Scalar { .. }) => ( + super::instructions::instruction_vector_times_scalar( + left_result_type_id, + id, + left_id, + right_id, ), - crate::TypeInner::Matrix { .. } => ( - super::instructions::instruction_vector_times_matrix( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, + left_lookup_ty, + ), + (Dimension::Vector, Dimension::Matrix) => ( + super::instructions::instruction_vector_times_matrix( + left_result_type_id, + id, + left_id, + right_id, ), - _ => unreachable!(), - }, - crate::TypeInner::Matrix { .. } => match *right_ty_inner { - crate::TypeInner::Scalar { .. } => ( - super::instructions::instruction_matrix_times_scalar( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, + left_lookup_ty, + ), + (Dimension::Matrix, Dimension::Scalar { .. }) => ( + super::instructions::instruction_matrix_times_scalar( + left_result_type_id, + id, + left_id, + right_id, ), - crate::TypeInner::Vector { .. } => ( - super::instructions::instruction_matrix_times_vector( - right_result_type_id, - id, - left_id, - right_id, - ), - right_lookup_ty, + left_lookup_ty, + ), + (Dimension::Matrix, Dimension::Vector) => ( + super::instructions::instruction_matrix_times_vector( + right_result_type_id, + id, + left_id, + right_id, ), - crate::TypeInner::Matrix { .. } => ( - super::instructions::instruction_matrix_times_matrix( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, + right_lookup_ty, + ), + (Dimension::Matrix, Dimension::Matrix) => ( + super::instructions::instruction_matrix_times_matrix( + left_result_type_id, + id, + left_id, + right_id, ), - _ => unreachable!(), - }, - crate::TypeInner::Scalar { kind, .. } => match kind { - crate::ScalarKind::Sint | crate::ScalarKind::Uint => ( - super::instructions::instruction_i_mul( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - crate::ScalarKind::Float => ( + left_lookup_ty, + ), + (Dimension::Scalar, Dimension::Scalar) + if left_ty_inner.scalar_kind() == Some(crate::ScalarKind::Float) => + { + ( super::instructions::instruction_f_mul( left_result_type_id, id, @@ -1185,9 +1190,17 @@ impl Writer { right_id, ), left_lookup_ty, + ) + } + (Dimension::Scalar, Dimension::Scalar) => ( + super::instructions::instruction_i_mul( + left_result_type_id, + id, + left_id, + right_id, ), - _ => unreachable!(), - }, + left_lookup_ty, + ), _ => unreachable!(), }, crate::BinaryOperator::Subtract => match *left_ty_inner { From 9041cd4b10ec6105d9041d103fe0a78022c3472c Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 16 Nov 2020 08:08:35 +0000 Subject: [PATCH 0279/2212] [glsl-in] Handle simple casts --- src/front/glsl/parser.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 1171b4d0a..f16da82ba 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -244,10 +244,25 @@ pomelo! { function_call ::= function_call_or_method(fc) { match fc.kind { FunctionCallKind::TypeConstructor(ty) => { - let h = extra.context.expressions.append(Expression::Compose { - ty, - components: fc.args.iter().map(|a| a.expression).collect(), - }); + let h = if fc.args.len() == 1 { + let kind = match extra.module.types[ty].inner { + TypeInner::Scalar{kind, ..} => kind, + TypeInner::Vector{kind, ..} => kind, + _ => { + return Err(ErrorKind::SemanticError("Can only cast to scalar or vector")); + } + }; + extra.context.expressions.append(Expression::As { + kind, + expr: fc.args[0].expression, + convert: true, + }) + } else { + extra.context.expressions.append(Expression::Compose { + ty, + components: fc.args.iter().map(|a| a.expression).collect(), + }) + }; ExpressionRule { expression: h, statements: fc.args.into_iter().map(|a| a.statements).flatten().collect(), From 437b33d5366affcbb96576ab6df7565a91cf2ba5 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 16 Nov 2020 17:57:34 +0100 Subject: [PATCH 0280/2212] [glsl-in] use TypeInner::scalar_kind for casts (#279) * [glsl-in] use TypeInner::scalar_kind for casts * [glsl-in] Use .ok_or for casts --- src/front/glsl/parser.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index f16da82ba..293ab7010 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -245,13 +245,9 @@ pomelo! { match fc.kind { FunctionCallKind::TypeConstructor(ty) => { let h = if fc.args.len() == 1 { - let kind = match extra.module.types[ty].inner { - TypeInner::Scalar{kind, ..} => kind, - TypeInner::Vector{kind, ..} => kind, - _ => { - return Err(ErrorKind::SemanticError("Can only cast to scalar or vector")); - } - }; + let kind = extra.module.types[ty].inner + .scalar_kind() + .ok_or(ErrorKind::SemanticError("Can only cast to scalar or vector"))?; extra.context.expressions.append(Expression::As { kind, expr: fc.args[0].expression, From 820dc51e2f7fed217b35be1a057b8375f3476015 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Mon, 16 Nov 2020 22:49:35 +0100 Subject: [PATCH 0281/2212] [spv-out] Fix annotations not getting added to output (#281) --- src/back/spv/writer.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 06149c693..d9c2a28ba 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1671,10 +1671,6 @@ impl Writer { )); } - for annotation in self.annotations.iter() { - annotation.to_words(&mut self.logical_layout.annotations); - } - for (handle, ir_function) in ir_module.functions.iter() { let id = self.write_function(ir_function, ir_module); self.lookup_function.insert(handle, id); @@ -1703,6 +1699,10 @@ impl Writer { debug.to_words(&mut self.logical_layout.debugs); } } + + for annotation in self.annotations.iter() { + annotation.to_words(&mut self.logical_layout.annotations); + } } pub fn write(&mut self, ir_module: &crate::Module) -> Vec { From 27ec95a2381ae8e0afd07fa13c83a436a9e0bd41 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Mon, 16 Nov 2020 22:52:51 +0100 Subject: [PATCH 0282/2212] [spv-out] Load variables when using CompositeConstruct (#284) --- src/back/spv/writer.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d9c2a28ba..f1599e9c8 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1017,7 +1017,7 @@ impl Writer { let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { let expression = &ir_function.expressions[*component]; - let (component_id, _) = self.write_expression( + let (component_id, component_local_ty) = self.write_expression( ir_module, &ir_function, expression, @@ -1025,6 +1025,21 @@ impl Writer { function, )?; + let component_id = match expression { + crate::Expression::LocalVariable(_) + | crate::Expression::GlobalVariable(_) => { + let load_id = self.generate_id(); + block.body.push(super::instructions::instruction_load( + self.get_type_id(&ir_module.types, component_local_ty.unwrap()), + load_id, + component_id, + None, + )); + load_id + } + _ => component_id, + }; + constituent_ids.push(component_id); } let constituent_ids_slice = constituent_ids.as_slice(); From 929e07ff0c9d50f945a0499414768d7593bab1ae Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Wed, 18 Nov 2020 17:10:45 +0100 Subject: [PATCH 0283/2212] [spv-out] Add support for vector with vector multiplication --- src/back/spv/writer.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f1599e9c8..e5e37a28d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1194,7 +1194,8 @@ impl Writer { ), left_lookup_ty, ), - (Dimension::Scalar, Dimension::Scalar) + (Dimension::Vector, Dimension::Vector) + | (Dimension::Scalar, Dimension::Scalar) if left_ty_inner.scalar_kind() == Some(crate::ScalarKind::Float) => { ( @@ -1207,7 +1208,8 @@ impl Writer { left_lookup_ty, ) } - (Dimension::Scalar, Dimension::Scalar) => ( + (Dimension::Vector, Dimension::Vector) + | (Dimension::Scalar, Dimension::Scalar) => ( super::instructions::instruction_i_mul( left_result_type_id, id, From 4ed91330cfa80ec550d9bd257627be659524a8e6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Nov 2020 23:06:46 -0500 Subject: [PATCH 0284/2212] Derive PartialEq for validation errors --- src/proc/typifier.rs | 2 +- src/proc/validator.rs | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index be9e17afc..b09893c17 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -41,7 +41,7 @@ pub struct Typifier { resolutions: Vec, } -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug, Error, PartialEq)] pub enum ResolveError { #[error("Invalid index into array")] InvalidAccessIndex, diff --git a/src/proc/validator.rs b/src/proc/validator.rs index a03d772c0..d9d3eac65 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -13,7 +13,7 @@ pub struct Validator { typifier: Typifier, } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum GlobalVariableError { #[error("Usage isn't compatible with the storage class")] InvalidUsage, @@ -32,7 +32,7 @@ pub enum GlobalVariableError { OutOfRangeBinding, } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum LocalVariableError { #[error("Initializer is not a constant expression")] InitializerConst, @@ -40,7 +40,7 @@ pub enum LocalVariableError { InitializerType, } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum FunctionError { #[error(transparent)] Resolve(#[from] ResolveError), @@ -54,7 +54,7 @@ pub enum FunctionError { }, } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum EntryPointError { #[error("Early depth test is not applicable")] UnexpectedEarlyDepthTest, @@ -74,7 +74,7 @@ pub enum EntryPointError { Function(#[from] FunctionError), } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum ValidationError { #[error("The type {0:?} width {1} is not supported")] InvalidTypeWidth(crate::ScalarKind, crate::Bytes), From c19bcbe89c9163285cad37b2d18acbe1ed0a9386 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Nov 2020 23:15:45 -0500 Subject: [PATCH 0285/2212] Allow manual strip for clippy, temporarily --- src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 4d24a7bb5..936c3b69f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,8 @@ clippy::unneeded_field_pattern, clippy::match_like_matches_macro )] +// TODO: use `strip_prefix` instead when Rust 1.45 <= MSRV +#![allow(clippy::manual_strip, clippy::unknown_clippy_lints)] #![deny(clippy::panic)] mod arena; From d0f34505640a2cbfdd5d7b278078af1405413587 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Nov 2020 11:28:06 -0500 Subject: [PATCH 0286/2212] [msl make backend a folder module --- src/back/{msl.rs => msl/mod.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/back/{msl.rs => msl/mod.rs} (100%) diff --git a/src/back/msl.rs b/src/back/msl/mod.rs similarity index 100% rename from src/back/msl.rs rename to src/back/msl/mod.rs From 36bc6b8596331f576ff32d4f634c8103b249ca30 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Nov 2020 11:58:41 -0500 Subject: [PATCH 0287/2212] [mtl] populate reserved words more --- src/back/msl/mod.rs | 98 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 97 insertions(+), 1 deletion(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 9f105ddaf..3bc329e89 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -27,7 +27,103 @@ use std::{ //TODO: find a complete list const RESERVED_WORDS: &[&str] = &[ - "if", "switch", "while", "for", "main", "struct", "new", "const", "device", + // control flow + "break", + "if", + "else", + "continue", + "goto", + "do", + "while", + "for", + "switch", + "case", + // types and values + "void", + "unsigned", + "signed", + "bool", + "char", + "int", + "long", + "float", + "double", + "char8_t", + "wchar_t", + "true", + "false", + "nullptr", + "union", + "class", + "struct", + "enum", + // other + "main", + "decltype", + "sizeof", + "typeof", + "typedef", + "explicit", + "export", + "friend", + "namespace", + "operator", + "public", + "template", + "typename", + "typeid", + "co_await", + "co_return", + "co_yield", + "module", + "import", + "ray_data", + "vec_step", + "visible", + "as_type", + // qualifiers + "mutable", + "static", + "volatile", + "restrict", + "const", + "non-temporal", + "dereferenceable", + "invariant", + // exceptions + "throw", + "try", + "catch", + // operators + "const_cast", + "dynamic_cast", + "reinterpret_cast", + "static_cast", + "new", + "delete", + "and", + "and_eq", + "bitand", + "bitor", + "compl", + "not", + "not_eq", + "or", + "or_eq", + "xor", + "xor_eq", + "compl", + // Metal-specific + "constant", + "device", + "threadgroup", + "threadgroup_imageblock", + "compute", + "vertex", + "fragment", + "read_only", + "write_only", + "read_write", ]; #[derive(Clone, Debug, Default, PartialEq)] From 0f7b6e3e76ef1921930bf5c173582a1b41505ab5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Nov 2020 12:03:18 -0500 Subject: [PATCH 0288/2212] [mtl] dont include the std namespace --- src/back/msl/mod.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 3bc329e89..21b8a8251 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -415,7 +415,10 @@ impl Writer { parameters: &[Handle], context: &ExpressionContext, ) -> Result<(), Error> { - write!(self.out, "{}(", name)?; + if !name.is_empty() { + write!(self.out, "metal::{}", name)?; + } + write!(self.out, "(")?; for (i, &handle) in parameters.iter().enumerate() { if i != 0 { write!(self.out, ", ")?; @@ -474,7 +477,8 @@ impl Writer { self.put_call("", components, context)?; } crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { - self.put_call(scalar_kind_string(kind), components, context)?; + write!(self.out, "{}", scalar_kind_string(kind),)?; + self.put_call("", components, context)?; } _ => return Err(Error::UnsupportedCompose(ty)), } @@ -856,7 +860,6 @@ impl Writer { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; - writeln!(self.out, "using namespace metal;")?; writeln!(self.out)?; self.write_type_defs(module)?; From fa36ef194caf8299b782badd9d146bc6ffcd572b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Nov 2020 12:08:38 -0500 Subject: [PATCH 0289/2212] [mtl] move keywords into a separate file --- src/back/msl/keywords.rs | 100 +++++++++++++++++++++++++++++++++++++ src/back/msl/mod.rs | 103 +-------------------------------------- 2 files changed, 102 insertions(+), 101 deletions(-) create mode 100644 src/back/msl/keywords.rs diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs new file mode 100644 index 000000000..50764affd --- /dev/null +++ b/src/back/msl/keywords.rs @@ -0,0 +1,100 @@ +//TODO: find a complete list +pub const RESERVED: &[&str] = &[ + // control flow + "break", + "if", + "else", + "continue", + "goto", + "do", + "while", + "for", + "switch", + "case", + // types and values + "void", + "unsigned", + "signed", + "bool", + "char", + "int", + "long", + "float", + "double", + "char8_t", + "wchar_t", + "true", + "false", + "nullptr", + "union", + "class", + "struct", + "enum", + // other + "main", + "decltype", + "sizeof", + "typeof", + "typedef", + "explicit", + "export", + "friend", + "namespace", + "operator", + "public", + "template", + "typename", + "typeid", + "co_await", + "co_return", + "co_yield", + "module", + "import", + "ray_data", + "vec_step", + "visible", + "as_type", + // qualifiers + "mutable", + "static", + "volatile", + "restrict", + "const", + "non-temporal", + "dereferenceable", + "invariant", + // exceptions + "throw", + "try", + "catch", + // operators + "const_cast", + "dynamic_cast", + "reinterpret_cast", + "static_cast", + "new", + "delete", + "and", + "and_eq", + "bitand", + "bitor", + "compl", + "not", + "not_eq", + "or", + "or_eq", + "xor", + "xor_eq", + "compl", + // Metal-specific + "constant", + "device", + "threadgroup", + "threadgroup_imageblock", + "compute", + "vertex", + "fragment", + "read_only", + "write_only", + "read_write", +]; diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 21b8a8251..ca0066cc7 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -25,106 +25,7 @@ use std::{ string::FromUtf8Error, }; -//TODO: find a complete list -const RESERVED_WORDS: &[&str] = &[ - // control flow - "break", - "if", - "else", - "continue", - "goto", - "do", - "while", - "for", - "switch", - "case", - // types and values - "void", - "unsigned", - "signed", - "bool", - "char", - "int", - "long", - "float", - "double", - "char8_t", - "wchar_t", - "true", - "false", - "nullptr", - "union", - "class", - "struct", - "enum", - // other - "main", - "decltype", - "sizeof", - "typeof", - "typedef", - "explicit", - "export", - "friend", - "namespace", - "operator", - "public", - "template", - "typename", - "typeid", - "co_await", - "co_return", - "co_yield", - "module", - "import", - "ray_data", - "vec_step", - "visible", - "as_type", - // qualifiers - "mutable", - "static", - "volatile", - "restrict", - "const", - "non-temporal", - "dereferenceable", - "invariant", - // exceptions - "throw", - "try", - "catch", - // operators - "const_cast", - "dynamic_cast", - "reinterpret_cast", - "static_cast", - "new", - "delete", - "and", - "and_eq", - "bitand", - "bitor", - "compl", - "not", - "not_eq", - "or", - "or_eq", - "xor", - "xor_eq", - "compl", - // Metal-specific - "constant", - "device", - "threadgroup", - "threadgroup_imageblock", - "compute", - "vertex", - "fragment", - "read_only", - "write_only", - "read_write", -]; +mod keywords; #[derive(Clone, Debug, Default, PartialEq)] pub struct BindTarget { @@ -856,7 +757,7 @@ impl Writer { pub fn write(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { self.names.clear(); - Namer::process(module, RESERVED_WORDS, &mut self.names); + Namer::process(module, keywords::RESERVED, &mut self.names); writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; From 7c7702c9d8d59325328aa7081347e151a7bb63d7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Nov 2020 12:16:47 -0500 Subject: [PATCH 0290/2212] [mtl] move writer into a separate module --- src/back/msl/mod.rs | 989 +--------------------------------------- src/back/msl/writer.rs | 990 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 996 insertions(+), 983 deletions(-) create mode 100644 src/back/msl/writer.rs diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index ca0066cc7..493e7d0c8 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -14,18 +14,16 @@ the output struct. If there is a structure in the outputs, and it contains any b we move them up to the root output structure that we define ourselves. !*/ -use crate::{ - arena::Handle, - proc::{EntryPointIndex, NameKey, Namer, ResolveContext, ResolveError, Typifier}, - FastHashMap, -}; +use crate::{arena::Handle, proc::ResolveError, FastHashMap}; use std::{ - fmt::{Display, Error as FmtError, Formatter}, io::{Error as IoError, Write}, string::FromUtf8Error, }; mod keywords; +mod writer; + +pub use writer::Writer; #[derive(Clone, Debug, Default, PartialEq)] pub struct BindTarget { @@ -52,18 +50,6 @@ enum ResolvedBinding { Resource(BindTarget), } -struct Level(usize); -impl Level { - fn next(&self) -> Self { - Level(self.0 + 1) - } -} -impl Display for Level { - fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - (0..self.0).map(|_| formatter.write_str("\t")).collect() - } -} - // Note: some of these should be removed in favor of proper IR validation. #[derive(Debug)] @@ -163,42 +149,6 @@ impl Options { } } -struct TypedGlobalVariable<'a> { - module: &'a crate::Module, - names: &'a FastHashMap, - handle: Handle, - usage: crate::GlobalUse, -} - -impl<'a> TypedGlobalVariable<'a> { - fn try_fmt(&self, out: &mut W) -> Result<(), Error> { - let var = &self.module.global_variables[self.handle]; - let name = &self.names[&NameKey::GlobalVariable(self.handle)]; - let ty = &self.module.types[var.ty]; - let ty_name = &self.names[&NameKey::Type(var.ty)]; - - let (space_qualifier, reference) = match ty.inner { - crate::TypeInner::Struct { .. } => match var.class { - crate::StorageClass::Uniform | crate::StorageClass::Storage => { - let space = if self.usage.contains(crate::GlobalUse::STORE) { - "device " - } else { - "constant " - }; - (space, "&") - } - _ => ("", ""), - }, - _ => ("", ""), - }; - Ok(write!( - out, - "{}{}{} {}", - space_qualifier, ty_name, reference, name - )?) - } -} - impl ResolvedBinding { fn try_fmt(&self, out: &mut W) -> Result<(), Error> { match *self { @@ -254,935 +204,8 @@ impl ResolvedBinding { } } -pub struct Writer { - out: W, - names: FastHashMap, - typifier: Typifier, -} - -fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { - match kind { - crate::ScalarKind::Float => "float", - crate::ScalarKind::Sint => "int", - crate::ScalarKind::Uint => "uint", - crate::ScalarKind::Bool => "bool", - } -} - -fn vector_size_string(size: crate::VectorSize) -> &'static str { - match size { - crate::VectorSize::Bi => "2", - crate::VectorSize::Tri => "3", - crate::VectorSize::Quad => "4", - } -} - -const OUTPUT_STRUCT_NAME: &str = "output"; -const LOCATION_INPUT_STRUCT_NAME: &str = "input"; -const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; - -fn separate(is_last: bool) -> &'static str { - if is_last { - "" - } else { - "," - } -} - -enum FunctionOrigin { - Handle(Handle), - EntryPoint(EntryPointIndex), -} - -struct ExpressionContext<'a> { - function: &'a crate::Function, - origin: FunctionOrigin, - module: &'a crate::Module, -} - -impl Writer { - /// Creates a new `Writer` instance - pub fn new(out: W) -> Self { - Writer { - out, - names: FastHashMap::default(), - typifier: Typifier::new(), - } - } - - fn put_call( - &mut self, - name: &str, - parameters: &[Handle], - context: &ExpressionContext, - ) -> Result<(), Error> { - if !name.is_empty() { - write!(self.out, "metal::{}", name)?; - } - write!(self.out, "(")?; - for (i, &handle) in parameters.iter().enumerate() { - if i != 0 { - write!(self.out, ", ")?; - } - self.put_expression(handle, context)?; - } - write!(self.out, ")")?; - Ok(()) - } - - fn put_expression( - &mut self, - expr_handle: Handle, - context: &ExpressionContext, - ) -> Result<(), Error> { - let expression = &context.function.expressions[expr_handle]; - log::trace!("expression {:?} = {:?}", expr_handle, expression); - match *expression { - crate::Expression::Access { base, index } => { - self.put_expression(base, context)?; - write!(self.out, "[")?; - self.put_expression(index, context)?; - write!(self.out, "]")?; - } - crate::Expression::AccessIndex { base, index } => { - self.put_expression(base, context)?; - let resolved = self.typifier.get(base, &context.module.types); - match *resolved { - crate::TypeInner::Struct { .. } => { - let base_ty = self.typifier.get_handle(base).unwrap(); - let name = &self.names[&NameKey::StructMember(base_ty, index)]; - write!(self.out, ".{}", name)?; - } - crate::TypeInner::Matrix { .. } | crate::TypeInner::Vector { .. } => { - write!(self.out, ".{}", COMPONENTS[index as usize])?; - } - crate::TypeInner::Array { .. } => { - write!(self.out, "[{}]", index)?; - } - _ => { - // unexpected indexing, should fail validation - } - } - } - crate::Expression::Constant(handle) => self.put_constant(handle, context.module)?, - crate::Expression::Compose { ty, ref components } => { - let inner = &context.module.types[ty].inner; - match *inner { - crate::TypeInner::Vector { size, kind, .. } => { - write!( - self.out, - "{}{}", - scalar_kind_string(kind), - vector_size_string(size) - )?; - self.put_call("", components, context)?; - } - crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { - write!(self.out, "{}", scalar_kind_string(kind),)?; - self.put_call("", components, context)?; - } - _ => return Err(Error::UnsupportedCompose(ty)), - } - } - crate::Expression::FunctionArgument(index) => { - let fun_handle = match context.origin { - FunctionOrigin::Handle(handle) => handle, - FunctionOrigin::EntryPoint(_) => unreachable!(), - }; - let name = &self.names[&NameKey::FunctionArgument(fun_handle, index)]; - write!(self.out, "{}", name)?; - } - crate::Expression::GlobalVariable(handle) => { - let var = &context.module.global_variables[handle]; - match var.class { - crate::StorageClass::Output => { - if let crate::TypeInner::Struct { .. } = context.module.types[var.ty].inner - { - return Ok(()); - } - write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; - } - crate::StorageClass::Input => { - if let Some(crate::Binding::Location(_)) = var.binding { - write!(self.out, "{}.", LOCATION_INPUT_STRUCT_NAME)?; - } - } - _ => {} - } - let name = &self.names[&NameKey::GlobalVariable(handle)]; - write!(self.out, "{}", name)?; - } - crate::Expression::LocalVariable(handle) => { - let name_key = match context.origin { - FunctionOrigin::Handle(fun_handle) => { - NameKey::FunctionLocal(fun_handle, handle) - } - FunctionOrigin::EntryPoint(ep_index) => { - NameKey::EntryPointLocal(ep_index, handle) - } - }; - let name = &self.names[&name_key]; - write!(self.out, "{}", name)?; - } - crate::Expression::Load { pointer } => { - //write!(self.out, "*")?; - self.put_expression(pointer, context)?; - } - crate::Expression::ImageSample { - image, - sampler, - coordinate, - level, - depth_ref, - } => { - let op = match depth_ref { - Some(_) => "sample_compare", - None => "sample", - }; - //TODO: handle arrayed images - self.put_expression(image, context)?; - write!(self.out, ".{}(", op)?; - self.put_expression(sampler, context)?; - write!(self.out, ", ")?; - self.put_expression(coordinate, context)?; - if let Some(dref) = depth_ref { - write!(self.out, ", ")?; - self.put_expression(dref, context)?; - } - match level { - crate::SampleLevel::Auto => {} - crate::SampleLevel::Zero => { - write!(self.out, ", level(0)")?; - } - crate::SampleLevel::Exact(h) => { - write!(self.out, ", level(")?; - self.put_expression(h, context)?; - write!(self.out, ")")?; - } - crate::SampleLevel::Bias(h) => { - write!(self.out, ", bias(")?; - self.put_expression(h, context)?; - write!(self.out, ")")?; - } - } - write!(self.out, ")")?; - } - crate::Expression::ImageLoad { - image, - coordinate, - index, - } => { - //TODO: handle arrayed images - self.put_expression(image, context)?; - write!(self.out, ".read(")?; - self.put_expression(coordinate, context)?; - if let Some(index) = index { - write!(self.out, ", ")?; - self.put_expression(index, context)?; - } - write!(self.out, ")")?; - } - crate::Expression::Unary { op, expr } => { - let op_str = match op { - crate::UnaryOperator::Negate => "-", - crate::UnaryOperator::Not => "!", - }; - write!(self.out, "{}", op_str)?; - self.put_expression(expr, context)?; - } - crate::Expression::Binary { op, left, right } => { - let op_str = match op { - crate::BinaryOperator::Add => "+", - crate::BinaryOperator::Subtract => "-", - crate::BinaryOperator::Multiply => "*", - crate::BinaryOperator::Divide => "/", - crate::BinaryOperator::Modulo => "%", - crate::BinaryOperator::Equal => "==", - crate::BinaryOperator::NotEqual => "!=", - crate::BinaryOperator::Less => "<", - crate::BinaryOperator::LessEqual => "<=", - crate::BinaryOperator::Greater => "==", - crate::BinaryOperator::GreaterEqual => ">=", - crate::BinaryOperator::And => "&", - _ => return Err(Error::UnsupportedBinaryOp(op)), - }; - let kind = self - .typifier - .get(left, &context.module.types) - .scalar_kind() - .ok_or(Error::UnsupportedBinaryOp(op))?; - if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float { - write!(self.out, "fmod(")?; - self.put_expression(left, context)?; - write!(self.out, ", ")?; - self.put_expression(right, context)?; - write!(self.out, ")")?; - } else { - //write!(self.out, "(")?; - self.put_expression(left, context)?; - write!(self.out, " {} ", op_str)?; - self.put_expression(right, context)?; - //write!(self.out, ")")?; - } - } - crate::Expression::Select { - condition, - accept, - reject, - } => { - write!(self.out, "(")?; - self.put_expression(condition, context)?; - write!(self.out, " ? ")?; - self.put_expression(accept, context)?; - write!(self.out, " : ")?; - self.put_expression(reject, context)?; - write!(self.out, ")")?; - } - crate::Expression::Intrinsic { fun, argument } => { - let op = match fun { - crate::IntrinsicFunction::Any => "any", - crate::IntrinsicFunction::All => "all", - crate::IntrinsicFunction::IsNan => "", - crate::IntrinsicFunction::IsInf => "", - crate::IntrinsicFunction::IsFinite => "", - crate::IntrinsicFunction::IsNormal => "", - }; - self.put_call(op, &[argument], context)?; - } - crate::Expression::Transpose(expr) => { - self.put_call("transpose", &[expr], context)?; - } - crate::Expression::DotProduct(a, b) => { - self.put_call("dot", &[a, b], context)?; - } - crate::Expression::CrossProduct(a, b) => { - self.put_call("cross", &[a, b], context)?; - } - crate::Expression::As { - expr, - kind, - convert, - } => { - let scalar = scalar_kind_string(kind); - let size = match *self.typifier.get(expr, &context.module.types) { - crate::TypeInner::Scalar { .. } => "", - crate::TypeInner::Vector { size, .. } => vector_size_string(size), - _ => return Err(Error::Validation), - }; - let op = if convert { "static_cast" } else { "as_type" }; - write!(self.out, "{}<{}{}>(", op, scalar, size)?; - self.put_expression(expr, context)?; - write!(self.out, ")")?; - } - crate::Expression::Derivative { axis, expr } => { - let op = match axis { - crate::DerivativeAxis::X => "dfdx", - crate::DerivativeAxis::Y => "dfdy", - crate::DerivativeAxis::Width => "fwidth", - }; - self.put_call(op, &[expr], context)?; - } - crate::Expression::Call { - origin: crate::FunctionOrigin::Local(handle), - ref arguments, - } => { - let name = &self.names[&NameKey::Function(handle)]; - write!(self.out, "{}", name)?; - self.put_call("", arguments, context)?; - } - crate::Expression::Call { - origin: crate::FunctionOrigin::External(ref name), - ref arguments, - } => match name.as_str() { - "atan2" | "cos" | "distance" | "length" | "mix" | "normalize" | "sin" => { - self.put_call(name, arguments, context)?; - } - "fclamp" => { - self.put_call("clamp", arguments, context)?; - } - other => return Err(Error::UnsupportedCall(other.to_owned())), - }, - crate::Expression::ArrayLength(expr) => match *self - .typifier - .get(expr, &context.module.types) - { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(const_handle), - .. - } => { - self.put_constant(const_handle, context.module)?; - } - crate::TypeInner::Array { .. } => return Err(Error::UnsupportedDynamicArrayLength), - _ => return Err(Error::Validation), - }, - } - Ok(()) - } - - fn put_constant( - &mut self, - handle: Handle, - module: &crate::Module, - ) -> Result<(), Error> { - let constant = &module.constants[handle]; - match constant.inner { - crate::ConstantInner::Sint(value) => { - write!(self.out, "{}", value)?; - } - crate::ConstantInner::Uint(value) => { - write!(self.out, "{}", value)?; - } - crate::ConstantInner::Float(value) => { - write!(self.out, "{}", value)?; - if value.fract() == 0.0 { - write!(self.out, ".0")?; - } - } - crate::ConstantInner::Bool(value) => { - write!(self.out, "{}", value)?; - } - crate::ConstantInner::Composite(ref constituents) => { - let ty_name = &self.names[&NameKey::Type(constant.ty)]; - write!(self.out, "{}(", ty_name)?; - for (i, &handle) in constituents.iter().enumerate() { - if i != 0 { - write!(self.out, ", ")?; - } - self.put_constant(handle, module)?; - } - write!(self.out, ")")?; - } - } - Ok(()) - } - - fn put_block( - &mut self, - level: Level, - statements: &[crate::Statement], - context: &ExpressionContext, - return_value: Option<&str>, - ) -> Result<(), Error> { - for statement in statements { - log::trace!("statement[{}] {:?}", level.0, statement); - match *statement { - crate::Statement::Block(ref block) => { - if !block.is_empty() { - writeln!(self.out, "{}{{", level)?; - self.put_block(level.next(), block, context, return_value)?; - writeln!(self.out, "{}}}", level)?; - } - } - crate::Statement::If { - condition, - ref accept, - ref reject, - } => { - write!(self.out, "{}if (", level)?; - self.put_expression(condition, context)?; - writeln!(self.out, ") {{")?; - self.put_block(level.next(), accept, context, return_value)?; - if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", level)?; - self.put_block(level.next(), reject, context, return_value)?; - } - writeln!(self.out, "{}}}", level)?; - } - crate::Statement::Switch { - selector, - ref cases, - ref default, - } => { - write!(self.out, "{}switch(", level)?; - self.put_expression(selector, context)?; - writeln!(self.out, ") {{")?; - let lcase = level.next(); - for (&value, &(ref block, ref fall_through)) in cases.iter() { - writeln!(self.out, "{}case {}: {{", lcase, value)?; - self.put_block(lcase.next(), block, context, return_value)?; - if fall_through.is_none() { - writeln!(self.out, "{}break;", lcase.next())?; - } - writeln!(self.out, "{}}}", lcase)?; - } - writeln!(self.out, "{}default: {{", lcase)?; - self.put_block(lcase.next(), default, context, return_value)?; - writeln!(self.out, "{}}}", lcase)?; - writeln!(self.out, "{}}}", level)?; - } - crate::Statement::Loop { - ref body, - ref continuing, - } => { - writeln!(self.out, "{}while(true) {{", level)?; - self.put_block(level.next(), body, context, return_value)?; - if !continuing.is_empty() { - //TODO - } - writeln!(self.out, "{}}}", level)?; - } - crate::Statement::Break => { - writeln!(self.out, "{}break;", level)?; - } - crate::Statement::Continue => { - writeln!(self.out, "{}continue;", level)?; - } - crate::Statement::Return { - value: Some(expr_handle), - } => { - write!(self.out, "{}return ", level)?; - self.put_expression(expr_handle, context)?; - writeln!(self.out, ";")?; - } - crate::Statement::Return { value: None } => { - if let Some(string) = return_value { - writeln!(self.out, "{}return {};", level, string)?; - } - } - crate::Statement::Kill => { - writeln!(self.out, "{}discard_fragment();", level)?; - } - crate::Statement::Store { pointer, value } => { - //write!(self.out, "\t*")?; - write!(self.out, "{}", level)?; - self.put_expression(pointer, context)?; - write!(self.out, " = ")?; - self.put_expression(value, context)?; - writeln!(self.out, ";")?; - } - } - } - Ok(()) - } - - pub fn write(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { - self.names.clear(); - Namer::process(module, keywords::RESERVED, &mut self.names); - - writeln!(self.out, "#include ")?; - writeln!(self.out, "#include ")?; - - writeln!(self.out)?; - self.write_type_defs(module)?; - - writeln!(self.out)?; - self.write_functions(module, options)?; - - Ok(()) - } - - fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { - for (handle, ty) in module.types.iter() { - let name = &self.names[&NameKey::Type(handle)]; - match ty.inner { - crate::TypeInner::Scalar { kind, .. } => { - write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?; - } - crate::TypeInner::Vector { size, kind, .. } => { - write!( - self.out, - "typedef {}{} {}", - scalar_kind_string(kind), - vector_size_string(size), - name - )?; - } - crate::TypeInner::Matrix { columns, rows, .. } => { - write!( - self.out, - "typedef {}{}x{} {}", - scalar_kind_string(crate::ScalarKind::Float), - vector_size_string(columns), - vector_size_string(rows), - name - )?; - } - crate::TypeInner::Pointer { base, class } => { - use crate::StorageClass as Sc; - let base_name = &self.names[&NameKey::Type(base)]; - let class_name = match class { - Sc::Input | Sc::Output => continue, - Sc::Uniform => "constant", - Sc::Storage => "device", - Sc::Handle - | Sc::Private - | Sc::Function - | Sc::WorkGroup - | Sc::PushConstant => "", - }; - write!(self.out, "typedef {} {} *{}", class_name, base_name, name)?; - } - crate::TypeInner::Array { - base, - size, - stride: _, - } => { - let base_name = &self.names[&NameKey::Type(base)]; - write!(self.out, "typedef {} {}[", base_name, name)?; - match size { - crate::ArraySize::Constant(const_handle) => { - self.put_constant(const_handle, module)?; - write!(self.out, "]")?; - } - crate::ArraySize::Dynamic => write!(self.out, "1]")?, - } - } - crate::TypeInner::Struct { ref members } => { - writeln!(self.out, "struct {} {{", name)?; - for (index, member) in members.iter().enumerate() { - let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; - let base_name = &self.names[&NameKey::Type(member.ty)]; - write!(self.out, "\t{} {}", base_name, member_name)?; - match member.origin { - crate::MemberOrigin::Empty => {} - crate::MemberOrigin::BuiltIn(built_in) => { - ResolvedBinding::BuiltIn(built_in) - .try_fmt_decorated(&mut self.out, "")?; - } - crate::MemberOrigin::Offset(_) => { - //TODO - } - } - writeln!(self.out, ";")?; - } - write!(self.out, "}}")?; - } - crate::TypeInner::Image { - dim, - arrayed, - class, - } => { - let dim_str = match dim { - crate::ImageDimension::D1 => "1d", - crate::ImageDimension::D2 => "2d", - crate::ImageDimension::D3 => "3d", - crate::ImageDimension::Cube => "Cube", - }; - let (texture_str, msaa_str, kind, access) = match class { - crate::ImageClass::Sampled { kind, multi } => { - ("texture", if multi { "_ms" } else { "" }, kind, "sample") - } - crate::ImageClass::Depth => { - ("depth", "", crate::ScalarKind::Float, "sample") - } - crate::ImageClass::Storage(format) => { - let (_, global) = module - .global_variables - .iter() - .find(|(_, var)| var.ty == handle) - .expect("Unable to find a global variable using the image type"); - let access = if global - .storage_access - .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) - { - "read_write" - } else if global.storage_access.contains(crate::StorageAccess::STORE) { - "write" - } else if global.storage_access.contains(crate::StorageAccess::LOAD) { - "read" - } else { - return Err(Error::InvalidImageAccess(global.storage_access)); - }; - ("texture", "", format.into(), access) - } - }; - let base_name = scalar_kind_string(kind); - let array_str = if arrayed { "_array" } else { "" }; - write!( - self.out, - "typedef {}{}{}{}<{}, access::{}> {}", - texture_str, dim_str, msaa_str, array_str, base_name, access, name - )?; - } - crate::TypeInner::Sampler { comparison: _ } => { - write!(self.out, "typedef sampler {}", name)?; - } - } - writeln!(self.out, ";")?; - } - Ok(()) - } - - fn write_functions(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { - for (fun_handle, fun) in module.functions.iter() { - self.typifier.resolve_all( - &fun.expressions, - &module.types, - &ResolveContext { - constants: &module.constants, - global_vars: &module.global_variables, - local_vars: &fun.local_variables, - functions: &module.functions, - arguments: &fun.arguments, - }, - )?; - - let fun_name = &self.names[&NameKey::Function(fun_handle)]; - let result_type_name = match fun.return_type { - Some(ret_ty) => &self.names[&NameKey::Type(ret_ty)], - None => "void", - }; - writeln!(self.out, "{} {}(", result_type_name, fun_name)?; - - for (index, arg) in fun.arguments.iter().enumerate() { - let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; - let param_type_name = &self.names[&NameKey::Type(arg.ty)]; - let separator = separate(index + 1 == fun.arguments.len()); - writeln!(self.out, "\t{} {}{}", param_type_name, name, separator)?; - } - writeln!(self.out, ") {{")?; - - for (local_handle, local) in fun.local_variables.iter() { - let ty_name = &self.names[&NameKey::Type(local.ty)]; - let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; - write!(self.out, "\t{} {}", ty_name, local_name)?; - if let Some(value) = local.init { - write!(self.out, " = ")?; - self.put_constant(value, module)?; - } - writeln!(self.out, ";")?; - } - - let context = ExpressionContext { - function: fun, - origin: FunctionOrigin::Handle(fun_handle), - module, - }; - self.put_block(Level(1), &fun.body, &context, None)?; - writeln!(self.out, "}}")?; - } - - for (ep_index, (&(stage, _), ep)) in module.entry_points.iter().enumerate() { - let fun = &ep.function; - self.typifier.resolve_all( - &fun.expressions, - &module.types, - &ResolveContext { - constants: &module.constants, - global_vars: &module.global_variables, - local_vars: &fun.local_variables, - functions: &module.functions, - arguments: &fun.arguments, - }, - )?; - - // find the entry point(s) and inputs/outputs - let mut last_used_global = None; - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { - match var.class { - crate::StorageClass::Input => { - if let Some(crate::Binding::Location(_)) = var.binding { - continue; - } - } - crate::StorageClass::Output => continue, - _ => {} - } - if !usage.is_empty() { - last_used_global = Some(handle); - } - } - - let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; - let output_name = format!("{}Output", fun_name); - let location_input_name = format!("{}Input", fun_name); - - let (em_str, in_mode, out_mode) = match stage { - crate::ShaderStage::Vertex => ( - "vertex", - LocationMode::VertexInput, - LocationMode::Intermediate, - ), - crate::ShaderStage::Fragment { .. } => ( - "fragment", - LocationMode::Intermediate, - LocationMode::FragmentOutput, - ), - crate::ShaderStage::Compute { .. } => { - ("kernel", LocationMode::Uniform, LocationMode::Uniform) - } - }; - - let return_value = match stage { - crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { - // make dedicated input/output structs - writeln!(self.out, "struct {} {{", location_input_name)?; - - for ((handle, var), &usage) in - module.global_variables.iter().zip(&fun.global_usage) - { - if var.class != crate::StorageClass::Input - || !usage.contains(crate::GlobalUse::LOAD) - { - continue; - } - // if it's a struct, lift all the built-in contents up to the root - if let crate::TypeInner::Struct { ref members } = module.types[var.ty].inner - { - for (index, member) in members.iter().enumerate() { - if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { - let name = - &self.names[&NameKey::StructMember(var.ty, index as u32)]; - let ty_name = &self.names[&NameKey::Type(member.ty)]; - write!(self.out, "\t{} {}", ty_name, name)?; - ResolvedBinding::BuiltIn(built_in) - .try_fmt_decorated(&mut self.out, ";\n")?; - } - } - } else if let Some(ref binding @ crate::Binding::Location(_)) = var.binding - { - let tyvar = TypedGlobalVariable { - module, - names: &self.names, - handle, - usage: crate::GlobalUse::empty(), - }; - let resolved = options.resolve_binding(stage, binding, in_mode)?; - - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - resolved.try_fmt_decorated(&mut self.out, ";\n")?; - } - } - writeln!(self.out, "}};")?; - - writeln!(self.out, "struct {} {{", output_name)?; - for ((handle, var), &usage) in - module.global_variables.iter().zip(&fun.global_usage) - { - if var.class != crate::StorageClass::Output - || !usage.contains(crate::GlobalUse::STORE) - { - continue; - } - // if it's a struct, lift all the built-in contents up to the root - if let crate::TypeInner::Struct { ref members } = module.types[var.ty].inner - { - for (index, member) in members.iter().enumerate() { - let name = - &self.names[&NameKey::StructMember(var.ty, index as u32)]; - let ty_name = &self.names[&NameKey::Type(member.ty)]; - match member.origin { - crate::MemberOrigin::Empty => {} - crate::MemberOrigin::BuiltIn(built_in) => { - write!(self.out, "\t{} {}", ty_name, name)?; - ResolvedBinding::BuiltIn(built_in) - .try_fmt_decorated(&mut self.out, ";\n")?; - } - crate::MemberOrigin::Offset(_) => { - //TODO - } - } - } - } else { - let tyvar = TypedGlobalVariable { - module, - names: &self.names, - handle, - usage: crate::GlobalUse::empty(), - }; - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - if let Some(ref binding) = var.binding { - let resolved = options.resolve_binding(stage, binding, out_mode)?; - resolved.try_fmt_decorated(&mut self.out, "")?; - } - writeln!(self.out, ";")?; - } - } - writeln!(self.out, "}};")?; - - writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; - let separator = separate(last_used_global.is_none()); - writeln!( - self.out, - "\t{} {} [[stage_in]]{}", - location_input_name, LOCATION_INPUT_STRUCT_NAME, separator - )?; - - Some(OUTPUT_STRUCT_NAME) - } - crate::ShaderStage::Compute => { - writeln!(self.out, "{} void {}(", em_str, fun_name)?; - None - } - }; - - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { - if usage.is_empty() || var.class == crate::StorageClass::Output { - continue; - } - if var.class == crate::StorageClass::Input { - if let Some(crate::Binding::Location(_)) = var.binding { - // location inputs are put into a separate struct - continue; - } - } - let loc_mode = match (stage, var.class) { - (crate::ShaderStage::Vertex, crate::StorageClass::Input) => { - LocationMode::VertexInput - } - (crate::ShaderStage::Vertex, crate::StorageClass::Output) - | (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Input) => { - LocationMode::Intermediate - } - (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Output) => { - LocationMode::FragmentOutput - } - _ => LocationMode::Uniform, - }; - let resolved = - options.resolve_binding(stage, var.binding.as_ref().unwrap(), loc_mode)?; - let tyvar = TypedGlobalVariable { - module, - names: &self.names, - handle, - usage, - }; - let separator = separate(last_used_global == Some(handle)); - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - resolved.try_fmt_decorated(&mut self.out, separator)?; - if let Some(value) = var.init { - write!(self.out, " = ")?; - self.put_constant(value, module)?; - } - writeln!(self.out)?; - } - writeln!(self.out, ") {{")?; - - match stage { - crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { - writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?; - } - crate::ShaderStage::Compute => {} - } - for (local_handle, local) in fun.local_variables.iter() { - let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; - let ty_name = &self.names[&NameKey::Type(local.ty)]; - write!(self.out, "\t{} {}", ty_name, name)?; - if let Some(value) = local.init { - write!(self.out, " = ")?; - self.put_constant(value, module)?; - } - writeln!(self.out, ";")?; - } - - let context = ExpressionContext { - function: fun, - origin: FunctionOrigin::EntryPoint(ep_index as _), - module, - }; - self.put_block(Level(1), &fun.body, &context, return_value)?; - writeln!(self.out, "}}")?; - } - - Ok(()) - } -} - pub fn write_string(module: &crate::Module, options: &Options) -> Result { - let mut w = Writer::new(Vec::new()); + let mut w = writer::Writer::new(Vec::new()); w.write(module, options)?; - Ok(String::from_utf8(w.out)?) + Ok(String::from_utf8(w.finish())?) } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs new file mode 100644 index 000000000..e2adbea6b --- /dev/null +++ b/src/back/msl/writer.rs @@ -0,0 +1,990 @@ +use super::{keywords::RESERVED, Error, LocationMode, Options, ResolvedBinding}; +use crate::{ + arena::Handle, + proc::{EntryPointIndex, NameKey, Namer, ResolveContext, Typifier}, + FastHashMap, +}; +use std::{ + fmt::{Display, Error as FmtError, Formatter}, + io::Write, +}; + +struct Level(usize); +impl Level { + fn next(&self) -> Self { + Level(self.0 + 1) + } +} +impl Display for Level { + fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { + (0..self.0).map(|_| formatter.write_str("\t")).collect() + } +} + +struct TypedGlobalVariable<'a> { + module: &'a crate::Module, + names: &'a FastHashMap, + handle: Handle, + usage: crate::GlobalUse, +} + +impl<'a> TypedGlobalVariable<'a> { + fn try_fmt(&self, out: &mut W) -> Result<(), Error> { + let var = &self.module.global_variables[self.handle]; + let name = &self.names[&NameKey::GlobalVariable(self.handle)]; + let ty = &self.module.types[var.ty]; + let ty_name = &self.names[&NameKey::Type(var.ty)]; + + let (space_qualifier, reference) = match ty.inner { + crate::TypeInner::Struct { .. } => match var.class { + crate::StorageClass::Uniform | crate::StorageClass::Storage => { + let space = if self.usage.contains(crate::GlobalUse::STORE) { + "device " + } else { + "constant " + }; + (space, "&") + } + _ => ("", ""), + }, + _ => ("", ""), + }; + Ok(write!( + out, + "{}{}{} {}", + space_qualifier, ty_name, reference, name + )?) + } +} + +pub struct Writer { + out: W, + names: FastHashMap, + typifier: Typifier, +} + +fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { + match kind { + crate::ScalarKind::Float => "float", + crate::ScalarKind::Sint => "int", + crate::ScalarKind::Uint => "uint", + crate::ScalarKind::Bool => "bool", + } +} + +fn vector_size_string(size: crate::VectorSize) -> &'static str { + match size { + crate::VectorSize::Bi => "2", + crate::VectorSize::Tri => "3", + crate::VectorSize::Quad => "4", + } +} + +const OUTPUT_STRUCT_NAME: &str = "output"; +const LOCATION_INPUT_STRUCT_NAME: &str = "input"; +const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; + +fn separate(is_last: bool) -> &'static str { + if is_last { + "" + } else { + "," + } +} + +enum FunctionOrigin { + Handle(Handle), + EntryPoint(EntryPointIndex), +} + +struct ExpressionContext<'a> { + function: &'a crate::Function, + origin: FunctionOrigin, + module: &'a crate::Module, +} + +impl Writer { + /// Creates a new `Writer` instance. + pub fn new(out: W) -> Self { + Writer { + out, + names: FastHashMap::default(), + typifier: Typifier::new(), + } + } + + /// Finishes writing and returns the output. + pub fn finish(self) -> W { + self.out + } + + fn put_call( + &mut self, + name: &str, + parameters: &[Handle], + context: &ExpressionContext, + ) -> Result<(), Error> { + if !name.is_empty() { + write!(self.out, "metal::{}", name)?; + } + write!(self.out, "(")?; + for (i, &handle) in parameters.iter().enumerate() { + if i != 0 { + write!(self.out, ", ")?; + } + self.put_expression(handle, context)?; + } + write!(self.out, ")")?; + Ok(()) + } + + fn put_expression( + &mut self, + expr_handle: Handle, + context: &ExpressionContext, + ) -> Result<(), Error> { + let expression = &context.function.expressions[expr_handle]; + log::trace!("expression {:?} = {:?}", expr_handle, expression); + match *expression { + crate::Expression::Access { base, index } => { + self.put_expression(base, context)?; + write!(self.out, "[")?; + self.put_expression(index, context)?; + write!(self.out, "]")?; + } + crate::Expression::AccessIndex { base, index } => { + self.put_expression(base, context)?; + let resolved = self.typifier.get(base, &context.module.types); + match *resolved { + crate::TypeInner::Struct { .. } => { + let base_ty = self.typifier.get_handle(base).unwrap(); + let name = &self.names[&NameKey::StructMember(base_ty, index)]; + write!(self.out, ".{}", name)?; + } + crate::TypeInner::Matrix { .. } | crate::TypeInner::Vector { .. } => { + write!(self.out, ".{}", COMPONENTS[index as usize])?; + } + crate::TypeInner::Array { .. } => { + write!(self.out, "[{}]", index)?; + } + _ => { + // unexpected indexing, should fail validation + } + } + } + crate::Expression::Constant(handle) => self.put_constant(handle, context.module)?, + crate::Expression::Compose { ty, ref components } => { + let inner = &context.module.types[ty].inner; + match *inner { + crate::TypeInner::Vector { size, kind, .. } => { + write!( + self.out, + "{}{}", + scalar_kind_string(kind), + vector_size_string(size) + )?; + self.put_call("", components, context)?; + } + crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { + write!(self.out, "{}", scalar_kind_string(kind),)?; + self.put_call("", components, context)?; + } + _ => return Err(Error::UnsupportedCompose(ty)), + } + } + crate::Expression::FunctionArgument(index) => { + let fun_handle = match context.origin { + FunctionOrigin::Handle(handle) => handle, + FunctionOrigin::EntryPoint(_) => unreachable!(), + }; + let name = &self.names[&NameKey::FunctionArgument(fun_handle, index)]; + write!(self.out, "{}", name)?; + } + crate::Expression::GlobalVariable(handle) => { + let var = &context.module.global_variables[handle]; + match var.class { + crate::StorageClass::Output => { + if let crate::TypeInner::Struct { .. } = context.module.types[var.ty].inner + { + return Ok(()); + } + write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; + } + crate::StorageClass::Input => { + if let Some(crate::Binding::Location(_)) = var.binding { + write!(self.out, "{}.", LOCATION_INPUT_STRUCT_NAME)?; + } + } + _ => {} + } + let name = &self.names[&NameKey::GlobalVariable(handle)]; + write!(self.out, "{}", name)?; + } + crate::Expression::LocalVariable(handle) => { + let name_key = match context.origin { + FunctionOrigin::Handle(fun_handle) => { + NameKey::FunctionLocal(fun_handle, handle) + } + FunctionOrigin::EntryPoint(ep_index) => { + NameKey::EntryPointLocal(ep_index, handle) + } + }; + let name = &self.names[&name_key]; + write!(self.out, "{}", name)?; + } + crate::Expression::Load { pointer } => { + //write!(self.out, "*")?; + self.put_expression(pointer, context)?; + } + crate::Expression::ImageSample { + image, + sampler, + coordinate, + level, + depth_ref, + } => { + let op = match depth_ref { + Some(_) => "sample_compare", + None => "sample", + }; + //TODO: handle arrayed images + self.put_expression(image, context)?; + write!(self.out, ".{}(", op)?; + self.put_expression(sampler, context)?; + write!(self.out, ", ")?; + self.put_expression(coordinate, context)?; + if let Some(dref) = depth_ref { + write!(self.out, ", ")?; + self.put_expression(dref, context)?; + } + match level { + crate::SampleLevel::Auto => {} + crate::SampleLevel::Zero => { + write!(self.out, ", level(0)")?; + } + crate::SampleLevel::Exact(h) => { + write!(self.out, ", level(")?; + self.put_expression(h, context)?; + write!(self.out, ")")?; + } + crate::SampleLevel::Bias(h) => { + write!(self.out, ", bias(")?; + self.put_expression(h, context)?; + write!(self.out, ")")?; + } + } + write!(self.out, ")")?; + } + crate::Expression::ImageLoad { + image, + coordinate, + index, + } => { + //TODO: handle arrayed images + self.put_expression(image, context)?; + write!(self.out, ".read(")?; + self.put_expression(coordinate, context)?; + if let Some(index) = index { + write!(self.out, ", ")?; + self.put_expression(index, context)?; + } + write!(self.out, ")")?; + } + crate::Expression::Unary { op, expr } => { + let op_str = match op { + crate::UnaryOperator::Negate => "-", + crate::UnaryOperator::Not => "!", + }; + write!(self.out, "{}", op_str)?; + self.put_expression(expr, context)?; + } + crate::Expression::Binary { op, left, right } => { + let op_str = match op { + crate::BinaryOperator::Add => "+", + crate::BinaryOperator::Subtract => "-", + crate::BinaryOperator::Multiply => "*", + crate::BinaryOperator::Divide => "/", + crate::BinaryOperator::Modulo => "%", + crate::BinaryOperator::Equal => "==", + crate::BinaryOperator::NotEqual => "!=", + crate::BinaryOperator::Less => "<", + crate::BinaryOperator::LessEqual => "<=", + crate::BinaryOperator::Greater => "==", + crate::BinaryOperator::GreaterEqual => ">=", + crate::BinaryOperator::And => "&", + _ => return Err(Error::UnsupportedBinaryOp(op)), + }; + let kind = self + .typifier + .get(left, &context.module.types) + .scalar_kind() + .ok_or(Error::UnsupportedBinaryOp(op))?; + if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float { + write!(self.out, "fmod(")?; + self.put_expression(left, context)?; + write!(self.out, ", ")?; + self.put_expression(right, context)?; + write!(self.out, ")")?; + } else { + //write!(self.out, "(")?; + self.put_expression(left, context)?; + write!(self.out, " {} ", op_str)?; + self.put_expression(right, context)?; + //write!(self.out, ")")?; + } + } + crate::Expression::Select { + condition, + accept, + reject, + } => { + write!(self.out, "(")?; + self.put_expression(condition, context)?; + write!(self.out, " ? ")?; + self.put_expression(accept, context)?; + write!(self.out, " : ")?; + self.put_expression(reject, context)?; + write!(self.out, ")")?; + } + crate::Expression::Intrinsic { fun, argument } => { + let op = match fun { + crate::IntrinsicFunction::Any => "any", + crate::IntrinsicFunction::All => "all", + crate::IntrinsicFunction::IsNan => "", + crate::IntrinsicFunction::IsInf => "", + crate::IntrinsicFunction::IsFinite => "", + crate::IntrinsicFunction::IsNormal => "", + }; + self.put_call(op, &[argument], context)?; + } + crate::Expression::Transpose(expr) => { + self.put_call("transpose", &[expr], context)?; + } + crate::Expression::DotProduct(a, b) => { + self.put_call("dot", &[a, b], context)?; + } + crate::Expression::CrossProduct(a, b) => { + self.put_call("cross", &[a, b], context)?; + } + crate::Expression::As { + expr, + kind, + convert, + } => { + let scalar = scalar_kind_string(kind); + let size = match *self.typifier.get(expr, &context.module.types) { + crate::TypeInner::Scalar { .. } => "", + crate::TypeInner::Vector { size, .. } => vector_size_string(size), + _ => return Err(Error::Validation), + }; + let op = if convert { "static_cast" } else { "as_type" }; + write!(self.out, "{}<{}{}>(", op, scalar, size)?; + self.put_expression(expr, context)?; + write!(self.out, ")")?; + } + crate::Expression::Derivative { axis, expr } => { + let op = match axis { + crate::DerivativeAxis::X => "dfdx", + crate::DerivativeAxis::Y => "dfdy", + crate::DerivativeAxis::Width => "fwidth", + }; + self.put_call(op, &[expr], context)?; + } + crate::Expression::Call { + origin: crate::FunctionOrigin::Local(handle), + ref arguments, + } => { + let name = &self.names[&NameKey::Function(handle)]; + write!(self.out, "{}", name)?; + self.put_call("", arguments, context)?; + } + crate::Expression::Call { + origin: crate::FunctionOrigin::External(ref name), + ref arguments, + } => match name.as_str() { + "atan2" | "cos" | "distance" | "length" | "mix" | "normalize" | "sin" => { + self.put_call(name, arguments, context)?; + } + "fclamp" => { + self.put_call("clamp", arguments, context)?; + } + other => return Err(Error::UnsupportedCall(other.to_owned())), + }, + crate::Expression::ArrayLength(expr) => match *self + .typifier + .get(expr, &context.module.types) + { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(const_handle), + .. + } => { + self.put_constant(const_handle, context.module)?; + } + crate::TypeInner::Array { .. } => return Err(Error::UnsupportedDynamicArrayLength), + _ => return Err(Error::Validation), + }, + } + Ok(()) + } + + fn put_constant( + &mut self, + handle: Handle, + module: &crate::Module, + ) -> Result<(), Error> { + let constant = &module.constants[handle]; + match constant.inner { + crate::ConstantInner::Sint(value) => { + write!(self.out, "{}", value)?; + } + crate::ConstantInner::Uint(value) => { + write!(self.out, "{}", value)?; + } + crate::ConstantInner::Float(value) => { + write!(self.out, "{}", value)?; + if value.fract() == 0.0 { + write!(self.out, ".0")?; + } + } + crate::ConstantInner::Bool(value) => { + write!(self.out, "{}", value)?; + } + crate::ConstantInner::Composite(ref constituents) => { + let ty_name = &self.names[&NameKey::Type(constant.ty)]; + write!(self.out, "{}(", ty_name)?; + for (i, &handle) in constituents.iter().enumerate() { + if i != 0 { + write!(self.out, ", ")?; + } + self.put_constant(handle, module)?; + } + write!(self.out, ")")?; + } + } + Ok(()) + } + + fn put_block( + &mut self, + level: Level, + statements: &[crate::Statement], + context: &ExpressionContext, + return_value: Option<&str>, + ) -> Result<(), Error> { + for statement in statements { + log::trace!("statement[{}] {:?}", level.0, statement); + match *statement { + crate::Statement::Block(ref block) => { + if !block.is_empty() { + writeln!(self.out, "{}{{", level)?; + self.put_block(level.next(), block, context, return_value)?; + writeln!(self.out, "{}}}", level)?; + } + } + crate::Statement::If { + condition, + ref accept, + ref reject, + } => { + write!(self.out, "{}if (", level)?; + self.put_expression(condition, context)?; + writeln!(self.out, ") {{")?; + self.put_block(level.next(), accept, context, return_value)?; + if !reject.is_empty() { + writeln!(self.out, "{}}} else {{", level)?; + self.put_block(level.next(), reject, context, return_value)?; + } + writeln!(self.out, "{}}}", level)?; + } + crate::Statement::Switch { + selector, + ref cases, + ref default, + } => { + write!(self.out, "{}switch(", level)?; + self.put_expression(selector, context)?; + writeln!(self.out, ") {{")?; + let lcase = level.next(); + for (&value, &(ref block, ref fall_through)) in cases.iter() { + writeln!(self.out, "{}case {}: {{", lcase, value)?; + self.put_block(lcase.next(), block, context, return_value)?; + if fall_through.is_none() { + writeln!(self.out, "{}break;", lcase.next())?; + } + writeln!(self.out, "{}}}", lcase)?; + } + writeln!(self.out, "{}default: {{", lcase)?; + self.put_block(lcase.next(), default, context, return_value)?; + writeln!(self.out, "{}}}", lcase)?; + writeln!(self.out, "{}}}", level)?; + } + crate::Statement::Loop { + ref body, + ref continuing, + } => { + writeln!(self.out, "{}while(true) {{", level)?; + self.put_block(level.next(), body, context, return_value)?; + if !continuing.is_empty() { + //TODO + } + writeln!(self.out, "{}}}", level)?; + } + crate::Statement::Break => { + writeln!(self.out, "{}break;", level)?; + } + crate::Statement::Continue => { + writeln!(self.out, "{}continue;", level)?; + } + crate::Statement::Return { + value: Some(expr_handle), + } => { + write!(self.out, "{}return ", level)?; + self.put_expression(expr_handle, context)?; + writeln!(self.out, ";")?; + } + crate::Statement::Return { value: None } => { + if let Some(string) = return_value { + writeln!(self.out, "{}return {};", level, string)?; + } + } + crate::Statement::Kill => { + writeln!(self.out, "{}discard_fragment();", level)?; + } + crate::Statement::Store { pointer, value } => { + //write!(self.out, "\t*")?; + write!(self.out, "{}", level)?; + self.put_expression(pointer, context)?; + write!(self.out, " = ")?; + self.put_expression(value, context)?; + writeln!(self.out, ";")?; + } + } + } + Ok(()) + } + + pub fn write(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { + self.names.clear(); + Namer::process(module, RESERVED, &mut self.names); + + writeln!(self.out, "#include ")?; + writeln!(self.out, "#include ")?; + + writeln!(self.out)?; + self.write_type_defs(module)?; + + writeln!(self.out)?; + self.write_functions(module, options)?; + + Ok(()) + } + + fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { + for (handle, ty) in module.types.iter() { + let name = &self.names[&NameKey::Type(handle)]; + match ty.inner { + crate::TypeInner::Scalar { kind, .. } => { + write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?; + } + crate::TypeInner::Vector { size, kind, .. } => { + write!( + self.out, + "typedef {}{} {}", + scalar_kind_string(kind), + vector_size_string(size), + name + )?; + } + crate::TypeInner::Matrix { columns, rows, .. } => { + write!( + self.out, + "typedef {}{}x{} {}", + scalar_kind_string(crate::ScalarKind::Float), + vector_size_string(columns), + vector_size_string(rows), + name + )?; + } + crate::TypeInner::Pointer { base, class } => { + use crate::StorageClass as Sc; + let base_name = &self.names[&NameKey::Type(base)]; + let class_name = match class { + Sc::Input | Sc::Output => continue, + Sc::Uniform => "constant", + Sc::Storage => "device", + Sc::Handle + | Sc::Private + | Sc::Function + | Sc::WorkGroup + | Sc::PushConstant => "", + }; + write!(self.out, "typedef {} {} *{}", class_name, base_name, name)?; + } + crate::TypeInner::Array { + base, + size, + stride: _, + } => { + let base_name = &self.names[&NameKey::Type(base)]; + write!(self.out, "typedef {} {}[", base_name, name)?; + match size { + crate::ArraySize::Constant(const_handle) => { + self.put_constant(const_handle, module)?; + write!(self.out, "]")?; + } + crate::ArraySize::Dynamic => write!(self.out, "1]")?, + } + } + crate::TypeInner::Struct { ref members } => { + writeln!(self.out, "struct {} {{", name)?; + for (index, member) in members.iter().enumerate() { + let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; + let base_name = &self.names[&NameKey::Type(member.ty)]; + write!(self.out, "\t{} {}", base_name, member_name)?; + match member.origin { + crate::MemberOrigin::Empty => {} + crate::MemberOrigin::BuiltIn(built_in) => { + ResolvedBinding::BuiltIn(built_in) + .try_fmt_decorated(&mut self.out, "")?; + } + crate::MemberOrigin::Offset(_) => { + //TODO + } + } + writeln!(self.out, ";")?; + } + write!(self.out, "}}")?; + } + crate::TypeInner::Image { + dim, + arrayed, + class, + } => { + let dim_str = match dim { + crate::ImageDimension::D1 => "1d", + crate::ImageDimension::D2 => "2d", + crate::ImageDimension::D3 => "3d", + crate::ImageDimension::Cube => "Cube", + }; + let (texture_str, msaa_str, kind, access) = match class { + crate::ImageClass::Sampled { kind, multi } => { + ("texture", if multi { "_ms" } else { "" }, kind, "sample") + } + crate::ImageClass::Depth => { + ("depth", "", crate::ScalarKind::Float, "sample") + } + crate::ImageClass::Storage(format) => { + let (_, global) = module + .global_variables + .iter() + .find(|(_, var)| var.ty == handle) + .expect("Unable to find a global variable using the image type"); + let access = if global + .storage_access + .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) + { + "read_write" + } else if global.storage_access.contains(crate::StorageAccess::STORE) { + "write" + } else if global.storage_access.contains(crate::StorageAccess::LOAD) { + "read" + } else { + return Err(Error::InvalidImageAccess(global.storage_access)); + }; + ("texture", "", format.into(), access) + } + }; + let base_name = scalar_kind_string(kind); + let array_str = if arrayed { "_array" } else { "" }; + write!( + self.out, + "typedef {}{}{}{}<{}, access::{}> {}", + texture_str, dim_str, msaa_str, array_str, base_name, access, name + )?; + } + crate::TypeInner::Sampler { comparison: _ } => { + write!(self.out, "typedef sampler {}", name)?; + } + } + writeln!(self.out, ";")?; + } + Ok(()) + } + + fn write_functions(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { + for (fun_handle, fun) in module.functions.iter() { + self.typifier.resolve_all( + &fun.expressions, + &module.types, + &ResolveContext { + constants: &module.constants, + global_vars: &module.global_variables, + local_vars: &fun.local_variables, + functions: &module.functions, + arguments: &fun.arguments, + }, + )?; + + let fun_name = &self.names[&NameKey::Function(fun_handle)]; + let result_type_name = match fun.return_type { + Some(ret_ty) => &self.names[&NameKey::Type(ret_ty)], + None => "void", + }; + writeln!(self.out, "{} {}(", result_type_name, fun_name)?; + + for (index, arg) in fun.arguments.iter().enumerate() { + let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; + let param_type_name = &self.names[&NameKey::Type(arg.ty)]; + let separator = separate(index + 1 == fun.arguments.len()); + writeln!(self.out, "\t{} {}{}", param_type_name, name, separator)?; + } + writeln!(self.out, ") {{")?; + + for (local_handle, local) in fun.local_variables.iter() { + let ty_name = &self.names[&NameKey::Type(local.ty)]; + let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; + write!(self.out, "\t{} {}", ty_name, local_name)?; + if let Some(value) = local.init { + write!(self.out, " = ")?; + self.put_constant(value, module)?; + } + writeln!(self.out, ";")?; + } + + let context = ExpressionContext { + function: fun, + origin: FunctionOrigin::Handle(fun_handle), + module, + }; + self.put_block(Level(1), &fun.body, &context, None)?; + writeln!(self.out, "}}")?; + } + + for (ep_index, (&(stage, _), ep)) in module.entry_points.iter().enumerate() { + let fun = &ep.function; + self.typifier.resolve_all( + &fun.expressions, + &module.types, + &ResolveContext { + constants: &module.constants, + global_vars: &module.global_variables, + local_vars: &fun.local_variables, + functions: &module.functions, + arguments: &fun.arguments, + }, + )?; + + // find the entry point(s) and inputs/outputs + let mut last_used_global = None; + for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { + match var.class { + crate::StorageClass::Input => { + if let Some(crate::Binding::Location(_)) = var.binding { + continue; + } + } + crate::StorageClass::Output => continue, + _ => {} + } + if !usage.is_empty() { + last_used_global = Some(handle); + } + } + + let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; + let output_name = format!("{}Output", fun_name); + let location_input_name = format!("{}Input", fun_name); + + let (em_str, in_mode, out_mode) = match stage { + crate::ShaderStage::Vertex => ( + "vertex", + LocationMode::VertexInput, + LocationMode::Intermediate, + ), + crate::ShaderStage::Fragment { .. } => ( + "fragment", + LocationMode::Intermediate, + LocationMode::FragmentOutput, + ), + crate::ShaderStage::Compute { .. } => { + ("kernel", LocationMode::Uniform, LocationMode::Uniform) + } + }; + + let return_value = match stage { + crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { + // make dedicated input/output structs + writeln!(self.out, "struct {} {{", location_input_name)?; + + for ((handle, var), &usage) in + module.global_variables.iter().zip(&fun.global_usage) + { + if var.class != crate::StorageClass::Input + || !usage.contains(crate::GlobalUse::LOAD) + { + continue; + } + // if it's a struct, lift all the built-in contents up to the root + if let crate::TypeInner::Struct { ref members } = module.types[var.ty].inner + { + for (index, member) in members.iter().enumerate() { + if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { + let name = + &self.names[&NameKey::StructMember(var.ty, index as u32)]; + let ty_name = &self.names[&NameKey::Type(member.ty)]; + write!(self.out, "\t{} {}", ty_name, name)?; + ResolvedBinding::BuiltIn(built_in) + .try_fmt_decorated(&mut self.out, ";\n")?; + } + } + } else if let Some(ref binding @ crate::Binding::Location(_)) = var.binding + { + let tyvar = TypedGlobalVariable { + module, + names: &self.names, + handle, + usage: crate::GlobalUse::empty(), + }; + let resolved = options.resolve_binding(stage, binding, in_mode)?; + + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + resolved.try_fmt_decorated(&mut self.out, ";\n")?; + } + } + writeln!(self.out, "}};")?; + + writeln!(self.out, "struct {} {{", output_name)?; + for ((handle, var), &usage) in + module.global_variables.iter().zip(&fun.global_usage) + { + if var.class != crate::StorageClass::Output + || !usage.contains(crate::GlobalUse::STORE) + { + continue; + } + // if it's a struct, lift all the built-in contents up to the root + if let crate::TypeInner::Struct { ref members } = module.types[var.ty].inner + { + for (index, member) in members.iter().enumerate() { + let name = + &self.names[&NameKey::StructMember(var.ty, index as u32)]; + let ty_name = &self.names[&NameKey::Type(member.ty)]; + match member.origin { + crate::MemberOrigin::Empty => {} + crate::MemberOrigin::BuiltIn(built_in) => { + write!(self.out, "\t{} {}", ty_name, name)?; + ResolvedBinding::BuiltIn(built_in) + .try_fmt_decorated(&mut self.out, ";\n")?; + } + crate::MemberOrigin::Offset(_) => { + //TODO + } + } + } + } else { + let tyvar = TypedGlobalVariable { + module, + names: &self.names, + handle, + usage: crate::GlobalUse::empty(), + }; + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + if let Some(ref binding) = var.binding { + let resolved = options.resolve_binding(stage, binding, out_mode)?; + resolved.try_fmt_decorated(&mut self.out, "")?; + } + writeln!(self.out, ";")?; + } + } + writeln!(self.out, "}};")?; + + writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; + let separator = separate(last_used_global.is_none()); + writeln!( + self.out, + "\t{} {} [[stage_in]]{}", + location_input_name, LOCATION_INPUT_STRUCT_NAME, separator + )?; + + Some(OUTPUT_STRUCT_NAME) + } + crate::ShaderStage::Compute => { + writeln!(self.out, "{} void {}(", em_str, fun_name)?; + None + } + }; + + for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { + if usage.is_empty() || var.class == crate::StorageClass::Output { + continue; + } + if var.class == crate::StorageClass::Input { + if let Some(crate::Binding::Location(_)) = var.binding { + // location inputs are put into a separate struct + continue; + } + } + let loc_mode = match (stage, var.class) { + (crate::ShaderStage::Vertex, crate::StorageClass::Input) => { + LocationMode::VertexInput + } + (crate::ShaderStage::Vertex, crate::StorageClass::Output) + | (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Input) => { + LocationMode::Intermediate + } + (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Output) => { + LocationMode::FragmentOutput + } + _ => LocationMode::Uniform, + }; + let resolved = + options.resolve_binding(stage, var.binding.as_ref().unwrap(), loc_mode)?; + let tyvar = TypedGlobalVariable { + module, + names: &self.names, + handle, + usage, + }; + let separator = separate(last_used_global == Some(handle)); + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + resolved.try_fmt_decorated(&mut self.out, separator)?; + if let Some(value) = var.init { + write!(self.out, " = ")?; + self.put_constant(value, module)?; + } + writeln!(self.out)?; + } + writeln!(self.out, ") {{")?; + + match stage { + crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { + writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?; + } + crate::ShaderStage::Compute => {} + } + for (local_handle, local) in fun.local_variables.iter() { + let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; + let ty_name = &self.names[&NameKey::Type(local.ty)]; + write!(self.out, "\t{} {}", ty_name, name)?; + if let Some(value) = local.init { + write!(self.out, " = ")?; + self.put_constant(value, module)?; + } + writeln!(self.out, ";")?; + } + + let context = ExpressionContext { + function: fun, + origin: FunctionOrigin::EntryPoint(ep_index as _), + module, + }; + self.put_block(Level(1), &fun.body, &context, return_value)?; + writeln!(self.out, "}}")?; + } + + Ok(()) + } +} From 0f983572233dd45fedc677190aad28ee0ddc7ced Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 19 Nov 2020 19:42:27 +0000 Subject: [PATCH 0291/2212] [glsl-in] Skip gl_PerVertex --- src/front/glsl/parser.rs | 146 +++++++++++++++++++++------------------ 1 file changed, 77 insertions(+), 69 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 293ab7010..db4935b0b 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -98,7 +98,7 @@ pomelo! { %type initializer ExpressionRule; // declarations - %type declaration VarDeclaration; + %type declaration Option; %type init_declarator_list VarDeclaration; %type single_declaration VarDeclaration; %type layout_qualifier Binding; @@ -528,26 +528,30 @@ pomelo! { // declaration declaration ::= init_declarator_list(idl) Semicolon { - idl + Some(idl) } declaration ::= type_qualifier(t) Identifier(i) LeftBrace struct_declaration_list(sdl) RightBrace Semicolon { - VarDeclaration { - type_qualifiers: t, - ids_initializers: vec![(None, None)], - ty: extra.module.types.fetch_or_append(Type{ - name: Some(i.1), - inner: TypeInner::Struct { - members: sdl - } - }), + if i.1 == "gl_PerVertex" { + None + } else { + Some(VarDeclaration { + type_qualifiers: t, + ids_initializers: vec![(None, None)], + ty: extra.module.types.fetch_or_append(Type{ + name: Some(i.1), + inner: TypeInner::Struct { + members: sdl + } + }), + }) } } declaration ::= type_qualifier(t) Identifier(i1) LeftBrace struct_declaration_list(sdl) RightBrace Identifier(i2) Semicolon { - VarDeclaration { + Some(VarDeclaration { type_qualifiers: t, ids_initializers: vec![(Some(i2.1), None)], ty: extra.module.types.fetch_or_append(Type{ @@ -556,7 +560,7 @@ pomelo! { members: sdl } }), - } + }) } // declaration ::= type_qualifier(t) Identifier(i1) LeftBrace @@ -762,43 +766,45 @@ pomelo! { declaration_statement ::= declaration(d) { let mut statements = Vec::::new(); // local variables - for (id, initializer) in d.ids_initializers { - let id = id.ok_or(ErrorKind::SemanticError("local var must be named"))?; - // check if already declared in current scope - #[cfg(feature = "glsl-validate")] - { - if extra.context.lookup_local_var_current_scope(&id).is_some() { - return Err(ErrorKind::VariableAlreadyDeclared(id)) + if let Some(d) = d { + for (id, initializer) in d.ids_initializers { + let id = id.ok_or(ErrorKind::SemanticError("local var must be named"))?; + // check if already declared in current scope + #[cfg(feature = "glsl-validate")] + { + if extra.context.lookup_local_var_current_scope(&id).is_some() { + return Err(ErrorKind::VariableAlreadyDeclared(id)) + } } - } - let mut init_exp: Option> = None; - let localVar = extra.context.local_variables.append( - LocalVariable { - name: Some(id.clone()), - ty: d.ty, - init: initializer.map(|i| { - statements.extend(i.statements); - if let Expression::Constant(constant) = extra.context.expressions[i.expression] { - Some(constant) - } else { - init_exp = Some(i.expression); - None - } - }).flatten(), - } - ); - let exp = extra.context.expressions.append(Expression::LocalVariable(localVar)); - extra.context.add_local_var(id, exp); - - if let Some(value) = init_exp { - statements.push( - Statement::Store { - pointer: exp, - value, + let mut init_exp: Option> = None; + let localVar = extra.context.local_variables.append( + LocalVariable { + name: Some(id.clone()), + ty: d.ty, + init: initializer.map(|i| { + statements.extend(i.statements); + if let Expression::Constant(constant) = extra.context.expressions[i.expression] { + Some(constant) + } else { + init_exp = Some(i.expression); + None + } + }).flatten(), } ); + let exp = extra.context.expressions.append(Expression::LocalVariable(localVar)); + extra.context.add_local_var(id, exp); + + if let Some(value) = init_exp { + statements.push( + Statement::Store { + pointer: exp, + value, + } + ); + } } - } + }; match statements.len() { 1 => statements.remove(0), _ => Statement::Block(statements), @@ -1073,32 +1079,34 @@ pomelo! { } } external_declaration ::= declaration(d) { - let class = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::StorageClass(sc) = tq { Some(*sc) } else { None } - }).ok_or(ErrorKind::SemanticError("Missing storage class for global var"))?; + if let Some(d) = d { + let class = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::StorageClass(sc) = tq { Some(*sc) } else { None } + }).ok_or(ErrorKind::SemanticError("Missing storage class for global var"))?; - let binding = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } - }); + let binding = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } + }); - let interpolation = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Interpolation(i) = tq { Some(*i) } else { None } - }); + let interpolation = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Interpolation(i) = tq { Some(*i) } else { None } + }); - for (id, initializer) in d.ids_initializers { - let h = extra.module.global_variables.fetch_or_append( - GlobalVariable { - name: id.clone(), - class, - binding: binding.clone(), - ty: d.ty, - init: None, - interpolation, - storage_access: StorageAccess::empty(), //TODO - }, - ); - if let Some(id) = id { - extra.lookup_global_variables.insert(id, h); + for (id, initializer) in d.ids_initializers { + let h = extra.module.global_variables.fetch_or_append( + GlobalVariable { + name: id.clone(), + class, + binding: binding.clone(), + ty: d.ty, + init: None, + interpolation, + storage_access: StorageAccess::empty(), //TODO + }, + ); + if let Some(id) = id { + extra.lookup_global_variables.insert(id, h); + } } } } From 1b8b3845bec1972794b0327b71923ad33204f69e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 20 Nov 2020 10:54:09 -0500 Subject: [PATCH 0292/2212] [mtl] Add 'kernel' and 'using' keywords --- src/back/msl/keywords.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs index 50764affd..cd074ab43 100644 --- a/src/back/msl/keywords.rs +++ b/src/back/msl/keywords.rs @@ -32,6 +32,7 @@ pub const RESERVED: &[&str] = &[ "enum", // other "main", + "using", "decltype", "sizeof", "typeof", @@ -91,6 +92,7 @@ pub const RESERVED: &[&str] = &[ "device", "threadgroup", "threadgroup_imageblock", + "kernel", "compute", "vertex", "fragment", From 23b1e4dd76e13d9478c5fe10b76fadbc08439cce Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 20 Nov 2020 12:09:35 -0500 Subject: [PATCH 0293/2212] [spv-out] fix generation of OpConvert --- src/back/spv/instructions.rs | 42 ++++-------------------- src/back/spv/writer.rs | 62 +++++++++++------------------------- 2 files changed, 25 insertions(+), 79 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 53bdcd314..8c8275097 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -505,7 +505,12 @@ pub(super) fn instruction_image_sample_implicit_lod( // // Conversion Instructions // -fn instruction_unary(op: Op, result_type_id: Word, id: Word, value: Word) -> Instruction { +pub(super) fn instruction_unary( + op: Op, + result_type_id: Word, + id: Word, + value: Word, +) -> Instruction { let mut instruction = Instruction::new(op); instruction.set_type(result_type_id); instruction.set_result(id); @@ -513,41 +518,6 @@ fn instruction_unary(op: Op, result_type_id: Word, id: Word, value: Word) -> Ins instruction } -pub(super) fn instruction_convert_f_to_u( - result_type_id: Word, - id: Word, - float_value: Word, -) -> Instruction { - instruction_unary(Op::ConvertFToU, result_type_id, id, float_value) -} - -pub(super) fn instruction_convert_f_to_s( - result_type_id: Word, - id: Word, - float_value: Word, -) -> Instruction { - instruction_unary(Op::ConvertFToS, result_type_id, id, float_value) -} - -pub(super) fn instruction_convert_s_to_f( - result_type_id: Word, - id: Word, - signed_value: Word, -) -> Instruction { - instruction_unary(Op::ConvertSToF, result_type_id, id, signed_value) -} - -pub(super) fn instruction_convert_u_to_f( - result_type_id: Word, - id: Word, - unsigned_value: Word, -) -> Instruction { - instruction_unary(Op::ConvertUToF, result_type_id, id, unsigned_value) -} - -pub(super) fn instruction_bit_cast(result_type_id: Word, id: Word, operand: Word) -> Instruction { - instruction_unary(Op::Bitcast, result_type_id, id, operand) -} // // Composite Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e5e37a28d..af15469e1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1369,55 +1369,31 @@ impl Writer { let id = self.generate_id(); let expr_type_inner = self.get_type_inner(&ir_module.types, expr_type.unwrap()); - let instruction = match *expr_type_inner { + let (expr_kind, local_type) = match *expr_type_inner { crate::TypeInner::Scalar { kind: expr_kind, width, - } => { - let kind_type_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Scalar { kind, width }), - ); - - if convert { - super::instructions::instruction_bit_cast(kind_type_id, id, expr_id) - } else { - match (expr_kind, kind) { - (crate::ScalarKind::Float, crate::ScalarKind::Uint) => { - super::instructions::instruction_convert_f_to_u( - kind_type_id, - id, - expr_id, - ) - } - (crate::ScalarKind::Float, crate::ScalarKind::Sint) => { - super::instructions::instruction_convert_f_to_s( - kind_type_id, - id, - expr_id, - ) - } - (crate::ScalarKind::Sint, crate::ScalarKind::Float) => { - super::instructions::instruction_convert_s_to_f( - kind_type_id, - id, - expr_id, - ) - } - (crate::ScalarKind::Uint, crate::ScalarKind::Float) => { - super::instructions::instruction_convert_u_to_f( - kind_type_id, - id, - expr_id, - ) - } - _ => unreachable!(), - } - } - } + } => (expr_kind, LocalType::Scalar { kind, width }), + crate::TypeInner::Vector { + size, + kind: expr_kind, + width, + } => (expr_kind, LocalType::Vector { size, kind, width }), _ => unreachable!(), }; + let op = match (expr_kind, kind) { + _ if !convert => spirv::Op::Bitcast, + (crate::ScalarKind::Float, crate::ScalarKind::Uint) => spirv::Op::ConvertFToU, + (crate::ScalarKind::Float, crate::ScalarKind::Sint) => spirv::Op::ConvertFToS, + (crate::ScalarKind::Sint, crate::ScalarKind::Float) => spirv::Op::ConvertSToF, + (crate::ScalarKind::Uint, crate::ScalarKind::Float) => spirv::Op::ConvertUToF, + _ => unreachable!(), + }; + let kind_type_id = + self.get_type_id(&ir_module.types, LookupType::Local(local_type)); + let instruction = + super::instructions::instruction_unary(op, kind_type_id, id, expr_id); block.body.push(instruction); Ok((id, None)) From dd5021234d8550723c9cf2a3d3d102daf2aec672 Mon Sep 17 00:00:00 2001 From: Capucho Date: Sat, 21 Nov 2020 18:45:05 +0000 Subject: [PATCH 0294/2212] [glsl-out] Reworked the backend The backend now works in a similar way to the msl backend Should require less loops, allocations and backtracking Overall just better to work with it Added a build script which reads a file with the glsl keywords and generates a slice to be used in the Namer Added a way to build a call graph --- Cargo.toml | 3 +- build.rs | 26 + examples/convert.rs | 7 +- glsl-keywords.txt | 20 + src/back/glsl.rs | 2641 ++++++++++++++++++---------------------- src/proc/call_graph.rs | 74 ++ src/proc/mod.rs | 4 + 7 files changed, 1300 insertions(+), 1475 deletions(-) create mode 100644 build.rs create mode 100644 glsl-keywords.txt create mode 100644 src/proc/call_graph.rs diff --git a/Cargo.toml b/Cargo.toml index 5cf912cc2..c79c22573 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ homepage = "https://github.com/gfx-rs/naga" repository = "https://github.com/gfx-rs/naga" keywords = ["shader", "SPIR-V"] license = "MIT OR Apache-2.0" +build = "build.rs" [dependencies] bitflags = "1" @@ -24,7 +25,7 @@ petgraph = { version ="0.5", optional = true } default = [] glsl-in = ["pomelo"] glsl-validate = [] -glsl-out = [] +glsl-out = ["petgraph"] msl-out = [] serialize = ["serde"] deserialize = ["serde"] diff --git a/build.rs b/build.rs new file mode 100644 index 000000000..340a5d828 --- /dev/null +++ b/build.rs @@ -0,0 +1,26 @@ +use std::{ + env, + fs::{read_to_string, OpenOptions}, + io::{Result, Write}, +}; + +fn main() -> Result<()> { + println!("cargo:rerun-if-changed=glsl-keywords.txt"); + + let keywords = read_to_string("glsl-keywords.txt")?.replace('\n', " "); + let mut out = OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(format!("{}/glsl_keywords.rs", env::var("OUT_DIR").unwrap()))?; + + writeln!(&mut out, "const RESERVED_KEYWORDS: &[&str] = &[")?; + + for keyword in keywords.split(' ') { + writeln!(&mut out, "\"{}\",", keyword)?; + } + + writeln!(&mut out, "];")?; + + Ok(()) +} diff --git a/examples/convert.rs b/examples/convert.rs index b75b48c82..69b5c3750 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -216,14 +216,17 @@ fn main() { ), }; - let mut file = fs::OpenOptions::new() + let file = fs::OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&args[2]) .unwrap(); - glsl::write(&module, &mut file, options) + let mut writer = glsl::Writer::new(file, &module, &options).unwrap(); + + writer + .write() .map_err(|e| { fs::remove_file(&args[2]).unwrap(); e diff --git a/glsl-keywords.txt b/glsl-keywords.txt new file mode 100644 index 000000000..34b97552e --- /dev/null +++ b/glsl-keywords.txt @@ -0,0 +1,20 @@ +attribute const uniform varying buffer shared coherent volatile restrict readonly writeonly +atomic_uint layout centroid flat smooth noperspective patch sample break continue do for while +switch case default if else subroutine in out inout float double int void bool true false invariant +precise discard return mat2 mat3 mat4 dmat2 dmat3 dmat4 mat2x2 mat2x3 mat2x4 dmat2x2 dmat2x3 dmat2x4 +mat3x2 mat3x3 mat3x4 dmat3x2 dmat3x3 dmat3x4 mat4x2 mat4x3 mat4x4 dmat4x2 dmat4x3 dmat4x4 vec2 vec3 +vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 dvec2 dvec3 dvec4 uint uvec2 uvec3 uvec4 lowp mediump highp +precision sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow +samplerCubeShadow sampler1DArray sampler2DArray sampler1DArrayShadow sampler2DArrayShadow +isampler1D isampler2D isampler3D isamplerCube isampler1DArray isampler2DArray usampler1D usampler2D +usampler3D usamplerCube usampler1DArray usampler2DArray sampler2DRect sampler2DRectShadow isampler2D +Rect usampler2DRect samplerBuffer isamplerBuffer usamplerBuffer sampler2DMS isampler2DMS +usampler2DMS sampler2DMSArray isampler2DMSArray usampler2DMSArray samplerCubeArray +samplerCubeArrayShadow isamplerCubeArray usamplerCubeArray image1D iimage1D uimage1D image2D +iimage2D uimage2D image3D iimage3D uimage3D image2DRect iimage2DRect uimage2DRect imageCube +iimageCube uimageCube imageBuffer iimageBuffer uimageBuffer image1DArray iimage1DArray uimage1DArray +image2DArray iimage2DArray uimage2DArray imageCubeArray iimageCubeArray uimageCubeArray image2DMS +iimage2DMS uimage2DMS image2DMSArray iimage2DMSArray uimage2DMSArraystruct common partition active +asm class union enum typedef template this resource goto inline noinline public static extern +external interface long short half fixed unsigned superp input output hvec2 hvec3 hvec4 fvec2 fvec3 +fvec4 sampler3DRect filter sizeof cast namespace using main diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 2b1328305..25a4f74f7 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,15 +1,37 @@ +//! OpenGL shading language backend +//! +//! The main structure is [`Writer`](struct.Writer.html), it maintains internal state that is used +//! to output a `Module` into glsl +//! +//! # Supported versions +//! ### Core +//! - 330 +//! - 400 +//! - 410 +//! - 420 +//! - 430 +//! - 450 +//! - 460 +//! +//! ### ES +//! - 300 +//! - 310 +//! + use crate::{ - proc::{Interface, ResolveContext, ResolveError, Typifier, Visitor}, + proc::{ + CallGraph, CallGraphBuilder, Interface, NameKey, Namer, ResolveContext, ResolveError, + Typifier, Visitor, + }, Arena, ArraySize, BinaryOperator, BuiltIn, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, - ImageClass, Interpolation, IntrinsicFunction, LocalVariable, MemberOrigin, Module, ScalarKind, - ShaderStage, Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, - TypeInner, UnaryOperator, + ImageClass, Interpolation, IntrinsicFunction, LocalVariable, Module, ScalarKind, ShaderStage, + Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, + UnaryOperator, }; use std::{ - borrow::Cow, cmp::Ordering, - fmt::{self, Error as FmtError, Write as FmtWrite}, + fmt::{self, Error as FmtError}, io::{Error as IoError, Write}, }; @@ -63,6 +85,14 @@ impl Version { Version::Embedded(_) => true, } } + + fn is_valid(&self) -> bool { + match self { + Version::Desktop(v) if SUPPORTED_CORE_VERSIONS.contains(v) => true, + Version::Embedded(v) if SUPPORTED_ES_VERSIONS.contains(v) => true, + _ => false, + } + } } impl PartialOrd for Version { @@ -96,6 +126,8 @@ pub struct TextureMapping { pub sampler: Option>, } +// imports a list of reserved keywords called RESERVED_KEYWORDS +include!(concat!(env!("OUT_DIR"), "/glsl_keywords.rs")); const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310]; @@ -128,7 +160,7 @@ impl FeaturesManager { } #[allow(clippy::collapsible_if)] - pub fn write(&self, version: Version, out: &mut impl Write) -> Result<(), Error> { + pub fn write(&self, version: Version, mut out: impl Write) -> Result<(), Error> { if self.0.contains(Features::COMPUTE_SHADER) { if version < Version::Embedded(310) || version < Version::Desktop(420) { return Err(Error::Custom(format!( @@ -282,1168 +314,1114 @@ impl FeaturesManager { } } -pub fn write<'a>( +enum FunctionType { + Function(Handle), + EntryPoint(crate::proc::EntryPointIndex), +} + +struct FunctionCtx<'a, 'b> { + func: FunctionType, + expressions: &'a Arena, + typifier: &'b Typifier, +} + +impl<'a, 'b> FunctionCtx<'a, 'b> { + fn get_local<'c>( + &self, + local: Handle, + names: &'c FastHashMap, + ) -> &'c str { + match self.func { + FunctionType::Function(handle) => { + names.get(&NameKey::FunctionLocal(handle, local)).unwrap() + } + FunctionType::EntryPoint(idx) => { + names.get(&NameKey::EntryPointLocal(idx, local)).unwrap() + } + } + } + + fn get_arg<'c>(&self, arg: u32, names: &'c FastHashMap) -> &'c str { + match self.func { + FunctionType::Function(handle) => { + names.get(&NameKey::FunctionArgument(handle, arg)).unwrap() + } + FunctionType::EntryPoint(_) => unreachable!(), + } + } +} + +/// Helper structure that generates a number +#[derive(Default)] +struct IdGenerator(u32); + +impl IdGenerator { + fn generate(&mut self) -> u32 { + let ret = self.0; + self.0 += 1; + ret + } +} + +/// Main structure of the glsl backend responsible for all code generation +pub struct Writer<'a, W> { + // Inputs module: &'a Module, - out: &mut impl Write, - options: Options, -) -> Result, Error> { - let (version, es) = match options.version { - Version::Desktop(v) => (v, false), - Version::Embedded(v) => (v, true), - }; + out: W, + options: &'a Options, - if (!es && !SUPPORTED_CORE_VERSIONS.contains(&version)) - || (es && !SUPPORTED_ES_VERSIONS.contains(&version)) - { - return Err(Error::Custom(format!( - "Version not supported {}", - options.version - ))); - } + // Internal State + features: FeaturesManager, + names: FastHashMap, + entry_point: &'a crate::EntryPoint, + entry_point_idx: crate::proc::EntryPointIndex, + call_graph: CallGraph, - let mut manager = FeaturesManager::new(); - let mut buf = Vec::new(); + /// Used to generate a unique number for blocks + block_id: IdGenerator, +} - writeln!(out, "#version {}\n", options.version)?; - - if es { - writeln!(out, "precision highp float;\n")?; - } - - let entry_point = module - .entry_points - .get(&options.entry_point) - .ok_or_else(|| Error::Custom(String::from("Entry point not found")))?; - let func = &entry_point.function; - let stage = options.entry_point.0; - - if let Some(depth_test) = entry_point.early_depth_test { - manager.request(Features::IMAGE_LOAD_STORE); - writeln!(&mut buf, "layout(early_fragment_tests) in;\n")?; - - if let Some(conservative) = depth_test.conservative { - manager.request(Features::CONSERVATIVE_DEPTH); - - writeln!( - &mut buf, - "layout (depth_{}) out float gl_FragDepth;\n", - match conservative { - ConservativeDepth::GreaterEqual => "greater", - ConservativeDepth::LessEqual => "less", - ConservativeDepth::Unchanged => "unchanged", - } - )?; - } - } - - if let ShaderStage::Compute = stage { - manager.request(Features::COMPUTE_SHADER) - } - - let mut structs = FastHashMap::default(); - let mut built_structs = FastHashMap::default(); - - // Do a first pass to collect names - for (handle, ty) in module.types.iter() { - match ty.inner { - TypeInner::Struct { .. } => { - let name = ty - .name - .clone() - .filter(|ident| is_valid_ident(ident)) - .unwrap_or_else(|| format!("struct_{}", handle.index())); - - structs.insert(handle, name); - } - _ => continue, - } - } - - for ((_, global), usage) in module.global_variables.iter().zip(func.global_usage.iter()) { - if usage.is_empty() { - continue; +impl<'a, W: Write> Writer<'a, W> { + pub fn new(out: W, module: &'a Module, options: &'a Options) -> Result { + if !options.version.is_valid() { + return Err(Error::Custom(format!( + "Version not supported {}", + options.version + ))); } - let block = match global.class { - StorageClass::Storage | StorageClass::Uniform => true, - _ => false, - }; - - match module.types[global.ty].inner { - TypeInner::Struct { .. } if block => { - built_structs.insert(global.ty, ()); - } - _ => {} - } - } - - // Do a second pass to build the structs - for (handle, ty) in module.types.iter() { - match ty.inner { - TypeInner::Struct { ref members } => { - write_struct( - handle, - members, - module, - &structs, - &mut buf, - &mut built_structs, - &mut manager, - )?; - } - _ => continue, - } - } - - writeln!(&mut buf)?; - - let mut functions = FastHashMap::default(); - - for (handle, func) in module.functions.iter() { - let name = func - .name - .clone() - .filter(|ident| is_valid_ident(ident)) - .unwrap_or_else(|| format!("function_{}", handle.index())); - - writeln!( - &mut buf, - "{} {}({});", - func.return_type - .map(|ty| write_type( - ty, - &module.types, - &module.constants, - &structs, - None, - &mut manager - )) - .transpose()? - .as_deref() - .unwrap_or("void"), - name, - func.arguments - .iter() - .map(|arg| write_type( - arg.ty, - &module.types, - &module.constants, - &structs, - None, - &mut manager - )) - .collect::, _>>()? - .join(","), - )?; - - functions.insert(handle, name); - } - - writeln!(&mut buf)?; - - let texture_mappings = collect_texture_mapping( - functions - .keys() - .map(|handle| &module.functions[*handle]) - .chain(std::iter::once(func)), - )?; - let mut mappings_map = FastHashMap::default(); - let mut globals_lookup = FastHashMap::default(); - - for ((handle, global), _) in module - .global_variables - .iter() - .zip(func.global_usage.iter()) - .filter(|(_, usage)| !usage.is_empty()) - { - match module.types[global.ty].inner { - TypeInner::Image { - dim, - arrayed, - class, - } => { - let mapping = if let Some(map) = texture_mappings.get_key_value(&handle) { - map - } else { - log::warn!( - "Couldn't find a mapping for {:?}, handle {:?}", - global, - handle - ); - continue; - }; - - if let TypeInner::Image { - class: ImageClass::Storage(storage_format), - .. - } = module.types[global.ty].inner - { - write!( - &mut buf, - "layout({}) ", - write_format_glsl(storage_format, &mut manager) - )?; - } - - if global.storage_access == StorageAccess::LOAD { - write!(&mut buf, "readonly ")?; - } else if global.storage_access == StorageAccess::STORE { - write!(&mut buf, "writeonly ")?; - } - - let name = if let Some(ref binding) = global.binding { - match binding { - crate::Binding::Location(location) => format!("location_{}", location), - crate::Binding::Resource { group, binding } => { - format!("set_{}_binding_{}", group, binding) - } - crate::Binding::BuiltIn(_) => unreachable!(), - } - } else { - global - .name - .clone() - .filter(|ident| is_valid_ident(ident)) - .unwrap_or_else(|| format!("global_{}", handle.index())) - }; - - writeln!( - &mut buf, - "uniform {} {};", - write_image_type(dim, arrayed, class, &mut manager)?, - name - )?; - - mappings_map.insert( - name.clone(), - TextureMapping { - texture: *mapping.0, - sampler: *mapping.1, - }, - ); - globals_lookup.insert(handle, name); - } - TypeInner::Sampler { .. } => { - let name = global - .name - .clone() - .filter(|ident| is_valid_ident(ident)) - .unwrap_or_else(|| format!("global_{}", handle.index())); - - globals_lookup.insert(handle, name); - } - _ => continue, - } - } - - for ((handle, global), _) in module - .global_variables - .iter() - .zip(func.global_usage.iter()) - .filter(|(_, usage)| !usage.is_empty()) - { - match module.types[global.ty].inner { - TypeInner::Image { .. } | TypeInner::Sampler { .. } => continue, - _ => {} - } - - if let Some(crate::Binding::BuiltIn(built_in)) = global.binding { - let semantic = match built_in { - BuiltIn::Position => "gl_Position", - BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", - BuiltIn::BaseInstance => "gl_BaseInstance", - BuiltIn::BaseVertex => "gl_BaseVertex", - BuiltIn::ClipDistance => "gl_ClipDistance", - BuiltIn::InstanceIndex => "gl_InstanceIndex", - BuiltIn::VertexIndex => "gl_VertexIndex", - BuiltIn::PointSize => "gl_PointSize", - BuiltIn::FragCoord => "gl_FragCoord", - BuiltIn::FrontFacing => "gl_FrontFacing", - BuiltIn::SampleIndex => "gl_SampleID", - BuiltIn::FragDepth => "gl_FragDepth", - BuiltIn::LocalInvocationId => "gl_LocalInvocationID", - BuiltIn::LocalInvocationIndex => "gl_LocalInvocationIndex", - BuiltIn::WorkGroupId => "gl_WorkGroupID", - }; - - globals_lookup.insert(handle, String::from(semantic)); - continue; - } - - let name = if let Some(ref binding) = global.binding { - let prefix = match global.class { - StorageClass::Function => "fn", - StorageClass::Input => "in", - StorageClass::Output => "out", - StorageClass::Private => "priv", - StorageClass::Storage => "buffer", - StorageClass::Uniform => "uniform", - StorageClass::Handle => "handle", - StorageClass::WorkGroup => "wg", - StorageClass::PushConstant => "pc", - }; - - match binding { - crate::Binding::Location(location) => format!("{}_location_{}", prefix, location), - crate::Binding::Resource { group, binding } => { - format!("{}_set_{}_binding_{}", prefix, group, binding) - } - crate::Binding::BuiltIn(_) => unreachable!(), - } - } else { - global - .name - .clone() - .filter(|ident| is_valid_ident(ident)) - .unwrap_or_else(|| format!("global_{}", handle.index())) - }; - - if let TypeInner::Struct { .. } = module.types[global.ty].inner { - if built_structs.get(&global.ty).is_none() { - globals_lookup.insert(handle, name); - continue; - } - } - - if global.storage_access == StorageAccess::LOAD { - write!(&mut buf, "readonly ")?; - } else if global.storage_access == StorageAccess::STORE { - write!(&mut buf, "writeonly ")?; - } - - if let Some(interpolation) = global.interpolation { - match (stage, global.class) { - (ShaderStage::Fragment, StorageClass::Input) - | (ShaderStage::Vertex, StorageClass::Output) => { - write!(&mut buf, "{} ", write_interpolation(interpolation)?)?; - } - _ => {} - }; - } - - let block = match global.class { - StorageClass::Storage | StorageClass::Uniform => { - Some(format!("global_block_{}", handle.index())) - } - _ => None, - }; - - writeln!( - &mut buf, - "{}{} {};", - write_storage_class(global.class, &mut manager)?, - write_type( - global.ty, - &module.types, - &module.constants, - &structs, - block, - &mut manager - )?, - name - )?; - - globals_lookup.insert(handle, name); - } - - writeln!(&mut buf)?; - let mut typifier = Typifier::new(); - - let mut write_function = |func: &Function, name: &str| -> Result<(), Error> { - typifier.resolve_all( - &func.expressions, - &module.types, - &ResolveContext { - constants: &module.constants, - global_vars: &module.global_variables, - local_vars: &func.local_variables, - functions: &module.functions, - arguments: &func.arguments, - }, - )?; - - let args: FastHashMap<_, _> = func - .arguments + let (ep_idx, ep) = module + .entry_points .iter() .enumerate() - .map(|(pos, arg)| { - let name = arg - .name - .clone() - .filter(|ident| is_valid_ident(ident)) - .unwrap_or_else(|| format!("arg_{}", pos + 1)); - (pos as u32, name) + .find_map(|(i, (key, entry_point))| { + Some((i as u16, entry_point)).filter(|_| &options.entry_point == key) }) - .collect(); + .ok_or_else(|| Error::Custom(String::from("Entry point not found")))?; - writeln!( - &mut buf, - "{} {}({}) {{", - func.return_type - .map(|ty| write_type( - ty, - &module.types, - &module.constants, - &structs, - None, - &mut manager - )) - .transpose()? - .as_deref() - .unwrap_or("void"), - name, - func.arguments - .iter() - .enumerate() - .map::, _>(|(pos, arg)| { - let ty = write_type( - arg.ty, - &module.types, - &module.constants, - &structs, - None, - &mut manager, - )?; - Ok(format!("{} {}", ty, args[&(pos as u32)])) - }) - .collect::, _>>()? - .join(","), - )?; + let mut names = FastHashMap::default(); + Namer::process(module, RESERVED_KEYWORDS, &mut names); - let locals: FastHashMap<_, _> = func - .local_variables - .iter() - .map(|(handle, local)| { - ( - handle, - local - .name - .clone() - .filter(|ident| is_valid_ident(ident)) - .unwrap_or_else(|| format!("local_{}", handle.index())), - ) - }) - .collect(); + let call_graph = CallGraphBuilder { + functions: &module.functions, + } + .process(&ep.function); - let mut builder = StatementBuilder { - functions: &functions, - globals: &globals_lookup, - locals_lookup: &locals, - structs: &structs, - args: &args, - expressions: &func.expressions, - typifier: &typifier, + let mut this = Self { + module, + out, + options, + + features: FeaturesManager::new(), + names, + entry_point: ep, + entry_point_idx: ep_idx, + call_graph, + + block_id: IdGenerator::default(), }; - for (handle, name) in locals.iter() { - let var = &func.local_variables[*handle]; - write!( - &mut buf, - "\t{} {}", - write_type( - var.ty, - &module.types, - &module.constants, - &structs, - None, - &mut manager - )?, - name - )?; - if let Some(init) = var.init { - write!( - &mut buf, - " = {}", - write_constant(&module.constants[init], module, &mut builder, &mut manager)? - )?; - } - writeln!(&mut buf, ";")?; - } + this.collect_required_features()?; - writeln!(&mut buf)?; - - for sta in func.body.iter() { - writeln!( - &mut buf, - "{}", - write_statement(sta, module, &mut builder, &mut manager, 1)? - )?; - } - - writeln!(&mut buf, "}}")?; - - Ok(()) - }; - - for (handle, name) in functions.iter() { - let func = &module.functions[*handle]; - write_function(func, name)?; + Ok(this) } - write_function(func, "main")?; + fn collect_required_features(&mut self) -> Result<(), Error> { + let stage = self.options.entry_point.0; - writeln!(out)?; + if let Some(depth_test) = self.entry_point.early_depth_test { + self.features.request(Features::IMAGE_LOAD_STORE); - manager.write(options.version, out)?; - out.write_all(&buf)?; - - Ok(mappings_map) -} - -struct StatementBuilder<'a> { - functions: &'a FastHashMap, String>, - globals: &'a FastHashMap, String>, - locals_lookup: &'a FastHashMap, String>, - structs: &'a FastHashMap, String>, - args: &'a FastHashMap, - expressions: &'a Arena, - typifier: &'a Typifier, -} - -fn write_statement<'a, 'b>( - sta: &Statement, - module: &'a Module, - builder: &'b mut StatementBuilder<'a>, - manager: &mut FeaturesManager, - indent: usize, -) -> Result { - Ok(match sta { - Statement::Block(block) => block - .iter() - .map(|sta| write_statement(sta, module, builder, manager, indent)) - .collect::, _>>()? - .join("\n"), - Statement::If { - condition, - accept, - reject, - } => { - let mut out = String::new(); - - writeln!( - &mut out, - "{}if({}) {{", - "\t".repeat(indent), - write_expression(&builder.expressions[*condition], module, builder, manager)? - )?; - - for sta in accept { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, manager, indent + 1)? - )?; + if depth_test.conservative.is_some() { + self.features.request(Features::CONSERVATIVE_DEPTH); } - - if !reject.is_empty() { - writeln!(&mut out, "{}}} else {{", "\t".repeat(indent),)?; - for sta in reject { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, manager, indent + 1)? - )?; - } - } - - write!(&mut out, "{}}}", "\t".repeat(indent),)?; - - out } - Statement::Switch { - selector, - cases, - default, - } => { - let mut out = String::new(); - writeln!( - &mut out, - "{}switch({}) {{", - "\t".repeat(indent), - write_expression(&builder.expressions[*selector], module, builder, manager)? - )?; - - for (label, (block, fallthrough)) in cases { - writeln!(&mut out, "{}case {}:", "\t".repeat(indent + 1), label)?; - - for sta in block { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, manager, indent + 2)? - )?; - } - - if fallthrough.is_none() { - writeln!(&mut out, "{}break;", "\t".repeat(indent + 2),)?; - } - } - - if !default.is_empty() { - writeln!(&mut out, "{}default:", "\t".repeat(indent + 1),)?; - - for sta in default { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, manager, indent + 2)? - )?; - } - } - - write!(&mut out, "{}}}", "\t".repeat(indent),)?; - - out + if let ShaderStage::Compute = stage { + self.features.request(Features::COMPUTE_SHADER) } - Statement::Loop { body, continuing } => { - let mut out = String::new(); - writeln!(&mut out, "{}while(true) {{", "\t".repeat(indent),)?; - - for sta in body.iter().chain(continuing.iter()) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, manager, indent + 1)? - )?; - } - - write!(&mut out, "{}}}", "\t".repeat(indent),)?; - - out - } - Statement::Break => format!("{}break;", "\t".repeat(indent),), - Statement::Continue => format!("{}continue;", "\t".repeat(indent),), - Statement::Return { value } => format!( - "{}{}", - "\t".repeat(indent), - if let Some(expr) = value { - format!( - "return {};", - write_expression(&builder.expressions[*expr], module, builder, manager)? - ) - } else { - String::from("return;") - } - ), - Statement::Kill => format!("{}discard;", "\t".repeat(indent)), - Statement::Store { pointer, value } => format!( - "{}{} = {};", - "\t".repeat(indent), - write_expression(&builder.expressions[*pointer], module, builder, manager)?, - write_expression(&builder.expressions[*value], module, builder, manager)? - ), - }) -} - -fn write_expression<'a, 'b>( - expr: &Expression, - module: &'a Module, - builder: &'b mut StatementBuilder<'a>, - manager: &mut FeaturesManager, -) -> Result, Error> { - Ok(match *expr { - Expression::Access { base, index } => { - let base_expr = write_expression(&builder.expressions[base], module, builder, manager)?; - Cow::Owned(format!( - "{}[{}]", - base_expr, - write_expression(&builder.expressions[index], module, builder, manager)? - )) - } - Expression::AccessIndex { base, index } => { - let base_expr = write_expression(&builder.expressions[base], module, builder, manager)?; - - match *builder.typifier.get(base, &module.types) { - TypeInner::Vector { .. } => Cow::Owned(format!("{}[{}]", base_expr, index)), - TypeInner::Matrix { .. } | TypeInner::Array { .. } => { - Cow::Owned(format!("{}[{}]", base_expr, index)) - } - TypeInner::Struct { ref members } => { - if let MemberOrigin::BuiltIn(builtin) = members[index as usize].origin { - Cow::Borrowed(builtin_to_glsl(builtin)) - } else { - Cow::Owned(format!( - "{}.{}", - base_expr, - members[index as usize] - .name - .as_ref() - .filter(|s| is_valid_ident(s)) - .unwrap_or(&format!("_{}", index)) - )) + for (_, ty) in self.module.types.iter() { + match ty.inner { + TypeInner::Scalar { kind, width } => self.scalar_required_features(kind, width), + TypeInner::Vector { kind, width, .. } => self.scalar_required_features(kind, width), + TypeInner::Matrix { .. } => self.scalar_required_features(ScalarKind::Float, 8), + TypeInner::Array { base, .. } => { + if let TypeInner::Array { .. } = self.module.types[base].inner { + self.features.request(Features::ARRAY_OF_ARRAYS) } } - ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), - } - } - Expression::Constant(constant) => Cow::Owned(write_constant( - &module.constants[constant], - module, - builder, - manager, - )?), - Expression::Compose { ty, ref components } => { - let constructor = match module.types[ty].inner { - TypeInner::Vector { size, kind, width } => format!( - "{}vec{}", - map_scalar(kind, width, manager)?.prefix, - size as u8, - ), - TypeInner::Matrix { - columns, - rows, - width, - } => format!( - "{}mat{}x{}", - map_scalar(crate::ScalarKind::Float, width, manager)?.prefix, - columns as u8, - rows as u8, - ), - TypeInner::Array { .. } => write_type( - ty, - &module.types, - &module.constants, - builder.structs, - None, - manager, - )? - .into_owned(), - TypeInner::Struct { .. } => builder.structs.get(&ty).unwrap().clone(), - _ => { - return Err(Error::Custom(format!( - "Cannot compose type {}", - write_type( - ty, - &module.types, - &module.constants, - builder.structs, - None, - manager - )? - ))) - } - }; - - Cow::Owned(format!( - "{}({})", - constructor, - components - .iter() - .map::, _>(|arg| Ok(write_expression( - &builder.expressions[*arg], - module, - builder, - manager, - )?)) - .collect::, _>>()? - .join(","), - )) - } - Expression::FunctionArgument(pos) => Cow::Borrowed(builder.args.get(&pos).unwrap()), - Expression::GlobalVariable(handle) => Cow::Borrowed(builder.globals.get(&handle).unwrap()), - Expression::LocalVariable(handle) => { - Cow::Borrowed(builder.locals_lookup.get(&handle).unwrap()) - } - Expression::Load { pointer } => { - write_expression(&builder.expressions[pointer], module, builder, manager)? - } - Expression::ImageSample { - image, - sampler, - coordinate, - level, - depth_ref, - } => { - let image_expr = - write_expression(&builder.expressions[image], module, builder, manager)?; - write_expression(&builder.expressions[sampler], module, builder, manager)?; - let coordinate_expr = - write_expression(&builder.expressions[coordinate], module, builder, manager)?; - - let size = match *builder.typifier.get(coordinate, &module.types) { - TypeInner::Vector { size, .. } => size, - ref other => { - return Err(Error::Custom(format!( - "Cannot sample with coordinates of type {:?}", - other - ))) - } - }; - - let coordinate_expr = if let Some(depth_ref) = depth_ref { - Cow::Owned(format!( - "vec{}({},{})", - size as u8 + 1, - coordinate_expr, - write_expression(&builder.expressions[depth_ref], module, builder, manager)? - )) - } else { - coordinate_expr - }; - - //TODO: handle MS - Cow::Owned(match level { - crate::SampleLevel::Auto => format!("texture({},{})", image_expr, coordinate_expr), - crate::SampleLevel::Zero => { - format!("textureLod({},{},0)", image_expr, coordinate_expr) - } - crate::SampleLevel::Exact(expr) => { - let level_expr = - write_expression(&builder.expressions[expr], module, builder, manager)?; - format!( - "textureLod({}, {}, {})", - image_expr, coordinate_expr, level_expr - ) - } - crate::SampleLevel::Bias(bias) => { - let bias_expr = - write_expression(&builder.expressions[bias], module, builder, manager)?; - format!("texture({},{},{})", image_expr, coordinate_expr, bias_expr) - } - }) - } - Expression::ImageLoad { - image, - coordinate, - index, - } => { - let image_expr = - write_expression(&builder.expressions[image], module, builder, manager)?; - let coordinate_expr = - write_expression(&builder.expressions[coordinate], module, builder, manager)?; - - let (dim, arrayed, class) = match *builder.typifier.get(image, &module.types) { TypeInner::Image { dim, arrayed, class, - } => (dim, arrayed, class), - ref other => return Err(Error::Custom(format!("Cannot load {:?}", other))), - }; + } => { + if arrayed && dim == crate::ImageDimension::Cube { + self.features.request(Features::CUBE_TEXTURES_ARRAY) + } else if dim == crate::ImageDimension::D1 { + self.features.request(Features::TEXTURE_1D) + } - Cow::Owned(match class { - ImageClass::Sampled { kind, multi } => { - //TODO: fix this - let sampler_constructor = format!( - "{}sampler{}{}{}({})", - map_scalar(kind, 4, manager)?.prefix, - ImageDimension(dim), - if multi { "MS" } else { "" }, - if arrayed { "Array" } else { "" }, - image_expr, - ); - - let index_expr = write_expression( - &builder.expressions[index.unwrap()], - module, - builder, - manager, - )?; - format!( - "texelFetch({},{},{})", - sampler_constructor, coordinate_expr, index_expr - ) + match class { + ImageClass::Sampled { multi: true, .. } => { + self.features.request(Features::MULTISAMPLED_TEXTURES); + if arrayed { + self.features.request(Features::MULTISAMPLED_TEXTURE_ARRAYS); + } + } + ImageClass::Storage(format) => match format { + StorageFormat::R8Unorm + | StorageFormat::R8Snorm + | StorageFormat::R8Uint + | StorageFormat::R8Sint + | StorageFormat::R16Uint + | StorageFormat::R16Sint + | StorageFormat::R16Float + | StorageFormat::Rg8Unorm + | StorageFormat::Rg8Snorm + | StorageFormat::Rg8Uint + | StorageFormat::Rg8Sint + | StorageFormat::Rg16Uint + | StorageFormat::Rg16Sint + | StorageFormat::Rg16Float + | StorageFormat::Rgb10a2Unorm + | StorageFormat::Rg11b10Float + | StorageFormat::Rg32Uint + | StorageFormat::Rg32Sint + | StorageFormat::Rg32Float => { + self.features.request(Features::FULL_IMAGE_FORMATS) + } + _ => {} + }, + _ => {} + } } - ImageClass::Storage(_) => format!("imageLoad({},{})", image_expr, coordinate_expr), - ImageClass::Depth => todo!(), - }) + _ => {} + } } - Expression::Unary { op, expr } => { - let base_expr = write_expression(&builder.expressions[expr], module, builder, manager)?; - Cow::Owned(format!( - "({} {})", - match op { - UnaryOperator::Negate => "-", - UnaryOperator::Not => match *builder.typifier.get(expr, &module.types) { - TypeInner::Scalar { - kind: ScalarKind::Sint, - .. - } => "~", - TypeInner::Scalar { - kind: ScalarKind::Uint, - .. - } => "~", - TypeInner::Scalar { - kind: ScalarKind::Bool, - .. - } => "!", - ref other => - return Err(Error::Custom(format!( - "Cannot apply not to type {:?}", - other - ))), - }, - }, - base_expr - )) + for (_, global) in self.module.global_variables.iter() { + match global.class { + StorageClass::WorkGroup => self.features.request(Features::COMPUTE_SHADER), + StorageClass::Storage => self.features.request(Features::BUFFER_STORAGE), + StorageClass::PushConstant => self.features.request(Features::PUSH_CONSTANT), + _ => {} + } } - Expression::Binary { op, left, right } => { - let left_expr = write_expression(&builder.expressions[left], module, builder, manager)?; - let right_expr = - write_expression(&builder.expressions[right], module, builder, manager)?; - let op_str = match op { - BinaryOperator::Add => "+", - BinaryOperator::Subtract => "-", - BinaryOperator::Multiply => "*", - BinaryOperator::Divide => "/", - BinaryOperator::Modulo => "%", - BinaryOperator::Equal => "==", - BinaryOperator::NotEqual => "!=", - BinaryOperator::Less => "<", - BinaryOperator::LessEqual => "<=", - BinaryOperator::Greater => ">", - BinaryOperator::GreaterEqual => ">=", - BinaryOperator::And => "&", - BinaryOperator::ExclusiveOr => "^", - BinaryOperator::InclusiveOr => "|", - BinaryOperator::LogicalAnd => "&&", - BinaryOperator::LogicalOr => "||", - BinaryOperator::ShiftLeft => "<<", - BinaryOperator::ShiftRight => ">>", + Ok(()) + } + + fn scalar_required_features(&mut self, kind: ScalarKind, width: crate::Bytes) { + if kind == ScalarKind::Float && width == 8 { + self.features.request(Features::DOUBLE_TYPE); + } + } + + pub fn write(&mut self) -> Result, Error> { + let es = self.options.version.is_es(); + + writeln!(self.out, "#version {}", self.options.version)?; + self.features.write(self.options.version, &mut self.out)?; + writeln!(self.out)?; + + if es { + writeln!(self.out, "precision highp float;\n")?; + } + + if let Some(depth_test) = self.entry_point.early_depth_test { + writeln!(self.out, "layout(early_fragment_tests) in;\n")?; + + if let Some(conservative) = depth_test.conservative { + writeln!( + self.out, + "layout (depth_{}) out float gl_FragDepth;\n", + match conservative { + ConservativeDepth::GreaterEqual => "greater", + ConservativeDepth::LessEqual => "less", + ConservativeDepth::Unchanged => "unchanged", + } + )?; + } + } + + let mut built_structs = FastHashMap::default(); + + for (_, global) in self + .module + .global_variables + .iter() + .zip(&self.entry_point.function.global_usage) + .filter_map(|(global, usage)| Some(global).filter(|_| !usage.is_empty())) + { + match global.class { + StorageClass::Storage | StorageClass::Uniform => (), + _ => continue, + } + + if let TypeInner::Struct { .. } = self.module.types[global.ty].inner { + built_structs.insert(global.ty, ()); + } + } + + for (handle, ty) in self.module.types.iter() { + if let TypeInner::Struct { ref members } = ty.inner { + if built_structs.get(&handle).is_none() { + self.write_struct(handle, members)? + } + } + } + + writeln!(self.out)?; + + let texture_mappings = self.collect_texture_mapping( + self.call_graph + .raw_nodes() + .iter() + .map(|node| &self.module.functions[node.weight]) + .chain(std::iter::once(&self.entry_point.function)), + )?; + + for (handle, global) in self + .module + .global_variables + .iter() + .zip(&self.entry_point.function.global_usage) + .filter_map(|(global, usage)| Some(global).filter(|_| !usage.is_empty())) + { + if let TypeInner::Image { + dim, + arrayed, + class, + } = self.module.types[global.ty].inner + { + if let TypeInner::Image { + class: ImageClass::Storage(format), + .. + } = self.module.types[global.ty].inner + { + write!(self.out, "layout({}) ", glsl_storage_format(format))?; + } + + if global.storage_access == StorageAccess::LOAD { + write!(self.out, "readonly ")?; + } else if global.storage_access == StorageAccess::STORE { + write!(self.out, "writeonly ")?; + } + + write!(self.out, "uniform ")?; + + self.write_image_type(dim, arrayed, class)?; + + let name = self.names.get(&NameKey::GlobalVariable(handle)).unwrap(); + writeln!(self.out, " {};", name)? + } + } + + for (handle, global) in self + .module + .global_variables + .iter() + .zip(&self.entry_point.function.global_usage) + .filter_map(|(global, usage)| Some(global).filter(|_| !usage.is_empty())) + { + match self.module.types[global.ty].inner { + TypeInner::Image { .. } | TypeInner::Sampler { .. } => continue, + _ => {} + } + + if let Some(crate::Binding::BuiltIn(_)) = global.binding { + continue; + } + + if global.storage_access == StorageAccess::LOAD { + write!(self.out, "readonly ")?; + } else if global.storage_access == StorageAccess::STORE { + write!(self.out, "writeonly ")?; + } + + if let Some(interpolation) = global.interpolation { + match (self.options.entry_point.0, global.class) { + (ShaderStage::Fragment, StorageClass::Input) + | (ShaderStage::Vertex, StorageClass::Output) => { + write!(self.out, "{} ", glsl_interpolation(interpolation)?)?; + } + _ => {} + }; + } + + let block = match global.class { + StorageClass::Storage | StorageClass::Uniform => { + let block_name = self.names.get(&NameKey::Type(global.ty)).cloned().unwrap(); + + Some(block_name) + } + _ => None, }; - Cow::Owned(format!("({} {} {})", left_expr, op_str, right_expr)) - } - Expression::Select { - condition, - accept, - reject, - } => { - let cond_expr = - write_expression(&builder.expressions[condition], module, builder, manager)?; - let accept_expr = - write_expression(&builder.expressions[accept], module, builder, manager)?; - let reject_expr = - write_expression(&builder.expressions[reject], module, builder, manager)?; - Cow::Owned(format!( - "({} ? {} : {})", - cond_expr, accept_expr, reject_expr - )) - } - Expression::Intrinsic { fun, argument } => { - let expr = write_expression(&builder.expressions[argument], module, builder, manager)?; + write!(self.out, "{} ", glsl_storage_class(global.class))?; - Cow::Owned(format!( - "{:?}({})", - match fun { - IntrinsicFunction::IsFinite => "!isinf", - IntrinsicFunction::IsInf => "isinf", - IntrinsicFunction::IsNan => "isnan", - IntrinsicFunction::IsNormal => "!isnan", - IntrinsicFunction::All => "all", - IntrinsicFunction::Any => "any", + self.write_type(global.ty, block)?; + + let name = self.names.get(&NameKey::GlobalVariable(handle)).unwrap(); + writeln!(self.out, " {};", name)? + } + + writeln!(self.out)?; + + let functions: Vec<_> = self + .call_graph + .raw_nodes() + .iter() + .map(|node| node.weight) + .collect(); + for handle in functions { + let name = self.names.get(&NameKey::Function(handle)).cloned().unwrap(); + self.write_function( + FunctionType::Function(handle), + &self.module.functions[handle], + name, + )?; + } + + self.write_function( + FunctionType::EntryPoint(self.entry_point_idx), + &self.entry_point.function, + "main", + )?; + + Ok(texture_mappings) + } + + fn write_function>( + &mut self, + ty: FunctionType, + func: &Function, + name: N, + ) -> Result<(), Error> { + let mut typifier = Typifier::new(); + + typifier.resolve_all( + &func.expressions, + &self.module.types, + &ResolveContext { + constants: &self.module.constants, + global_vars: &self.module.global_variables, + local_vars: &func.local_variables, + functions: &self.module.functions, + arguments: &func.arguments, + }, + )?; + + let mut ctx = FunctionCtx { + func: ty, + expressions: &func.expressions, + typifier: &typifier, + }; + + self.write_fn_header(name.as_ref(), func, &ctx)?; + writeln!(self.out, " {{",)?; + + for (handle, local) in func.local_variables.iter() { + write!(self.out, "\t")?; + self.write_type(local.ty, None)?; + + let name = ctx.get_local(handle, &self.names); + + write!(self.out, " {}", name)?; + + if let Some(init) = local.init { + write!(self.out, " = ",)?; + + self.write_constant(&self.module.constants[init])?; + } + + writeln!(self.out, ";")? + } + + writeln!(self.out)?; + + for sta in func.body.iter() { + self.write_stmt(sta, &mut ctx, 1)?; + } + + Ok(writeln!(self.out, "}}")?) + } + + fn write_slice Result<(), Error>>( + &mut self, + data: &[T], + mut f: F, + ) -> Result<(), Error> { + for (i, item) in data.iter().enumerate() { + f(self, i as u32, item)?; + + if i != data.len().saturating_sub(1) { + write!(self.out, ",")?; + } + } + + Ok(()) + } + + fn write_fn_header( + &mut self, + name: &str, + func: &Function, + ctx: &FunctionCtx<'_, '_>, + ) -> Result<(), Error> { + if let Some(ty) = func.return_type { + self.write_type(ty, None)?; + } else { + write!(self.out, "void")?; + } + + write!(self.out, " {}(", name)?; + + self.write_slice(&func.arguments, |this, i, arg| { + this.write_type(arg.ty, None)?; + + let name = ctx.get_arg(i, &this.names); + + Ok(write!(this.out, " {}", name)?) + })?; + + write!(self.out, ")")?; + + Ok(()) + } + + fn write_type(&mut self, ty: Handle, block: Option) -> Result<(), Error> { + match self.module.types[ty].inner { + TypeInner::Scalar { kind, width } => { + write!(self.out, "{}", glsl_scalar(kind, width)?.full)? + } + TypeInner::Vector { size, kind, width } => write!( + self.out, + "{}vec{}", + glsl_scalar(kind, width)?.prefix, + size as u8 + )?, + TypeInner::Matrix { + columns, + rows, + width, + } => write!( + self.out, + "{}mat{}x{}", + glsl_scalar(ScalarKind::Float, width)?.prefix, + columns as u8, + rows as u8 + )?, + TypeInner::Pointer { base, .. } => self.write_type(base, None)?, + TypeInner::Array { base, size, .. } => { + self.write_type(base, None)?; + + write!(self.out, "[")?; + self.write_array_size(size)?; + write!(self.out, "]")? + } + TypeInner::Struct { ref members } => { + if let Some(name) = block { + writeln!(self.out, "{}_block_{} {{", name, self.block_id.generate())?; + + for (idx, member) in members.iter().enumerate() { + self.write_type(member.ty, None)?; + + writeln!( + self.out, + " {};", + self.names + .get(&NameKey::StructMember(ty, idx as u32)) + .unwrap() + )?; + } + + write!(self.out, "}}")? + } else { + write!(self.out, "{}", self.names.get(&NameKey::Type(ty)).unwrap())? + } + } + _ => unreachable!(), + } + + Ok(()) + } + + fn write_image_type( + &mut self, + dim: crate::ImageDimension, + arrayed: bool, + class: ImageClass, + ) -> Result<(), Error> { + let (base, kind, ms, comparison) = match class { + ImageClass::Sampled { kind, multi: true } => ("sampler", kind, "MS", ""), + ImageClass::Sampled { kind, multi: false } => ("sampler", kind, "", ""), + ImageClass::Depth => ("sampler", crate::ScalarKind::Float, "", "Shadow"), + ImageClass::Storage(format) => ("image", format.into(), "", ""), + }; + + Ok(write!( + self.out, + "{}{}{}{}{}{}", + glsl_scalar(kind, 4)?.prefix, + base, + ImageDimension(dim), + ms, + if arrayed { "Array" } else { "" }, + comparison + )?) + } + + fn write_array_size(&mut self, size: ArraySize) -> Result<(), Error> { + match size { + ArraySize::Constant(const_handle) => match self.module.constants[const_handle].inner { + ConstantInner::Uint(size) => write!(self.out, "{}", size)?, + _ => unreachable!(), + }, + ArraySize::Dynamic => (), + } + + Ok(()) + } + + fn collect_texture_mapping( + &self, + functions: impl Iterator, + ) -> Result, Error> { + let mut mappings = FastHashMap::default(); + + for func in functions { + let mut interface = Interface { + expressions: &func.expressions, + local_variables: &func.local_variables, + visitor: TextureMappingVisitor { + names: &self.names, + expressions: &func.expressions, + map: &mut mappings, + error: None, }, - expr - )) - } - Expression::Transpose(matrix) => { - let matrix_expr = - write_expression(&builder.expressions[matrix], module, builder, manager)?; - Cow::Owned(format!("transpose({})", matrix_expr)) - } - Expression::DotProduct(left, right) => { - let left_expr = write_expression(&builder.expressions[left], module, builder, manager)?; - let right_expr = - write_expression(&builder.expressions[right], module, builder, manager)?; - Cow::Owned(format!("dot({},{})", left_expr, right_expr)) - } - Expression::CrossProduct(left, right) => { - let left_expr = write_expression(&builder.expressions[left], module, builder, manager)?; - let right_expr = - write_expression(&builder.expressions[right], module, builder, manager)?; - Cow::Owned(format!("cross({},{})", left_expr, right_expr)) - } - Expression::As { - expr, - kind, - convert, - } => { - let value_expr = - write_expression(&builder.expressions[expr], module, builder, manager)?; - - let (source_kind, ty_expr) = match *builder.typifier.get(expr, &module.types) { - TypeInner::Scalar { - width, - kind: source_kind, - } => ( - source_kind, - Cow::Borrowed(map_scalar(kind, width, manager)?.full), - ), - TypeInner::Vector { - width, - kind: source_kind, - size, - } => ( - source_kind, - Cow::Owned(format!( - "{}vec{}", - map_scalar(kind, width, manager)?.prefix, - size as u32, - )), - ), - _ => return Err(Error::Custom(format!("Cannot convert {}", value_expr))), }; + interface.traverse(&func.body); - let op = if convert { - ty_expr - } else { - Cow::Borrowed(match (source_kind, kind) { - (ScalarKind::Float, ScalarKind::Sint) => "floatBitsToInt", - (ScalarKind::Float, ScalarKind::Uint) => "floatBitsToUInt", - (ScalarKind::Sint, ScalarKind::Float) => "intBitsToFloat", - (ScalarKind::Uint, ScalarKind::Float) => "uintBitsToFloat", - _ => { + if let Some(error) = interface.visitor.error { + return Err(error); + } + } + + Ok(mappings) + } + + fn write_struct( + &mut self, + handle: Handle, + members: &[StructMember], + ) -> Result<(), Error> { + let name = self.names.get(&NameKey::Type(handle)).unwrap(); + + writeln!(self.out, "struct {} {{", name)?; + for (idx, member) in members.iter().enumerate() { + write!(self.out, "\t")?; + self.write_type(member.ty, None)?; + writeln!( + self.out, + " {};", + self.names + .get(&NameKey::StructMember(handle, idx as u32)) + .unwrap() + )?; + } + writeln!(self.out, "}};")?; + + Ok(()) + } + + fn write_stmt( + &mut self, + sta: &Statement, + ctx: &mut FunctionCtx<'_, '_>, + indent: usize, + ) -> Result<(), Error> { + write!(self.out, "{}", "\t".repeat(indent))?; + + match sta { + Statement::Block(block) => { + writeln!(self.out, "{{")?; + for sta in block.iter() { + self.write_stmt(sta, ctx, indent + 1)? + } + writeln!(self.out, "{}}}", "\t".repeat(indent))? + } + Statement::If { + condition, + accept, + reject, + } => { + write!(self.out, "if(")?; + self.write_expr(*condition, ctx)?; + writeln!(self.out, ") {{")?; + + for sta in accept { + self.write_stmt(sta, ctx, indent + 1)?; + } + + if !reject.is_empty() { + writeln!(self.out, "{}}} else {{", "\t".repeat(indent))?; + + for sta in reject { + self.write_stmt(sta, ctx, indent + 1)?; + } + } + + writeln!(self.out, "{}}}", "\t".repeat(indent))? + } + Statement::Switch { + selector, + cases, + default, + } => { + write!(self.out, "switch(")?; + self.write_expr(*selector, ctx)?; + writeln!(self.out, ") {{")?; + + for (label, (block, fallthrough)) in cases { + writeln!(self.out, "{}case {}:", "\t".repeat(indent + 1), label)?; + + for sta in block { + self.write_stmt(sta, ctx, indent + 2)?; + } + + if fallthrough.is_none() { + writeln!(self.out, "{}break;", "\t".repeat(indent + 2))?; + } + } + + if !default.is_empty() { + writeln!(self.out, "{}default:", "\t".repeat(indent + 1))?; + + for sta in default { + self.write_stmt(sta, ctx, indent + 2)?; + } + } + + writeln!(self.out, "{}}}", "\t".repeat(indent))? + } + Statement::Loop { body, continuing } => { + writeln!(self.out, "while(true) {{")?; + + for sta in body.iter().chain(continuing.iter()) { + self.write_stmt(sta, ctx, indent + 1)?; + } + + writeln!(self.out, "{}}}", "\t".repeat(indent))? + } + Statement::Break => writeln!(self.out, "break;")?, + Statement::Continue => writeln!(self.out, "continue;")?, + Statement::Return { value } => { + write!(self.out, "return")?; + if let Some(expr) = value { + write!(self.out, " ")?; + self.write_expr(*expr, ctx)?; + } + writeln!(self.out, ";")?; + } + Statement::Kill => writeln!(self.out, "discard;")?, + Statement::Store { pointer, value } => { + self.write_expr(*pointer, ctx)?; + write!(self.out, " = ")?; + self.write_expr(*value, ctx)?; + writeln!(self.out, ";")? + } + } + + Ok(()) + } + + fn write_expr( + &mut self, + expr: Handle, + ctx: &mut FunctionCtx<'_, '_>, + ) -> Result<(), Error> { + match ctx.expressions[expr] { + Expression::Access { base, index } => { + self.write_expr(base, ctx)?; + write!(self.out, "[")?; + self.write_expr(index, ctx)?; + write!(self.out, "]")? + } + Expression::AccessIndex { base, index } => { + self.write_expr(base, ctx)?; + + match ctx.typifier.get(base, &self.module.types) { + TypeInner::Vector { .. } + | TypeInner::Matrix { .. } + | TypeInner::Array { .. } => write!(self.out, "[{}]", index)?, + TypeInner::Struct { .. } => { + let ty = ctx.typifier.get_handle(base).unwrap(); + + write!( + self.out, + ".{}", + self.names.get(&NameKey::StructMember(ty, index)).unwrap() + )? + } + ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), + } + } + Expression::Constant(constant) => { + self.write_constant(&self.module.constants[constant])? + } + Expression::Compose { ty, ref components } => { + match self.module.types[ty].inner { + TypeInner::Vector { .. } + | TypeInner::Matrix { .. } + | TypeInner::Array { .. } + | TypeInner::Struct { .. } => self.write_type(ty, None)?, + _ => unreachable!(), + } + + write!(self.out, "(")?; + self.write_slice(components, |this, _, arg| this.write_expr(*arg, ctx))?; + write!(self.out, ")")? + } + Expression::FunctionArgument(pos) => { + write!(self.out, "{}", ctx.get_arg(pos, &self.names))? + } + Expression::GlobalVariable(handle) => { + if let Some(crate::Binding::BuiltIn(built_in)) = + self.module.global_variables[handle].binding + { + write!(self.out, "{}", glsl_built_in(built_in))? + } else { + write!( + self.out, + "{}", + self.names.get(&NameKey::GlobalVariable(handle)).unwrap() + )? + } + } + Expression::LocalVariable(handle) => { + write!(self.out, "{}", ctx.get_local(handle, &self.names))? + } + Expression::Load { pointer } => self.write_expr(pointer, ctx)?, + Expression::ImageSample { + image, + coordinate, + level, + depth_ref, + .. + } => { + //TODO: handle MS + write!( + self.out, + "{}(", + match level { + crate::SampleLevel::Auto | crate::SampleLevel::Bias(_) => "texture", + crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => "textureLod", + } + )?; + self.write_expr(image, ctx)?; + write!(self.out, ", ")?; + + let size = match *ctx.typifier.get(coordinate, &self.module.types) { + TypeInner::Vector { size, .. } => size, + ref other => { return Err(Error::Custom(format!( - "Cannot bitcast {:?} to {:?}", - source_kind, kind + "Cannot sample with coordinates of type {:?}", + other ))) } - }) - }; - - Cow::Owned(format!("{}({})", op, value_expr)) - } - Expression::Derivative { axis, expr } => { - let expr = write_expression(&builder.expressions[expr], module, builder, manager)?; - - Cow::Owned(format!( - "{}({})", - match axis { - DerivativeAxis::X => "dFdx", - DerivativeAxis::Y => "dFdy", - DerivativeAxis::Width => "fwidth", - }, - expr - )) - } - Expression::Call { - origin: FunctionOrigin::Local(ref function), - ref arguments, - } => Cow::Owned(format!( - "{}({})", - builder.functions.get(function).unwrap(), - arguments - .iter() - .map::, _>(|arg| write_expression( - &builder.expressions[*arg], - module, - builder, - manager, - )) - .collect::, _>>()? - .join(","), - )), - Expression::Call { - origin: crate::FunctionOrigin::External(ref name), - ref arguments, - } => match name.as_str() { - "cos" | "normalize" | "sin" | "length" | "abs" | "floor" | "inverse" => { - let expr = - write_expression(&builder.expressions[arguments[0]], module, builder, manager)?; - - Cow::Owned(format!("{}({})", name, expr)) - } - "fclamp" | "clamp" | "mix" | "smoothstep" => { - let x = - write_expression(&builder.expressions[arguments[0]], module, builder, manager)?; - let y = - write_expression(&builder.expressions[arguments[1]], module, builder, manager)?; - let a = - write_expression(&builder.expressions[arguments[2]], module, builder, manager)?; - - let name = match name.as_str() { - "fclamp" => "clamp", - name => name, }; - Cow::Owned(format!("{}({}, {}, {})", name, x, y, a)) - } - "atan2" => { - let x = - write_expression(&builder.expressions[arguments[0]], module, builder, manager)?; - let y = - write_expression(&builder.expressions[arguments[1]], module, builder, manager)?; + if let Some(depth_ref) = depth_ref { + write!(self.out, "vec{}(", size as u8 + 1)?; + self.write_expr(coordinate, ctx)?; + write!(self.out, ", ")?; + self.write_expr(depth_ref, ctx)?; + write!(self.out, ")")? + } else { + self.write_expr(coordinate, ctx)? + } - Cow::Owned(format!("atan({}, {})", y, x)) - } - "distance" | "dot" | "min" | "max" | "reflect" | "pow" | "step" | "cross" => { - let x = - write_expression(&builder.expressions[arguments[0]], module, builder, manager)?; - let y = - write_expression(&builder.expressions[arguments[1]], module, builder, manager)?; + match level { + crate::SampleLevel::Auto => (), + crate::SampleLevel::Zero => write!(self.out, ", 0")?, + crate::SampleLevel::Exact(expr) | crate::SampleLevel::Bias(expr) => { + write!(self.out, ", ")?; + self.write_expr(expr, ctx)?; + } + } - Cow::Owned(format!("{}({}, {})", name, x, y)) + write!(self.out, ")")? } - other => { - return Err(Error::Custom(format!( - "Unsupported function call {}", - other - ))) - } - }, - Expression::ArrayLength(expr) => { - let base = write_expression(&builder.expressions[expr], module, builder, manager)?; - Cow::Owned(format!("uint({}.length())", base)) - } - }) -} + Expression::ImageLoad { + image, + coordinate, + index, + } => { + let class = match ctx.typifier.get(image, &self.module.types) { + TypeInner::Image { class, .. } => class, + _ => unreachable!(), + }; -fn write_constant( - constant: &Constant, - module: &Module, - builder: &mut StatementBuilder<'_>, - manager: &mut FeaturesManager, -) -> Result { - Ok(match constant.inner { - ConstantInner::Sint(int) => int.to_string(), - ConstantInner::Uint(int) => format!("{}u", int), - ConstantInner::Float(float) => format!("{:?}", float), - ConstantInner::Bool(boolean) => boolean.to_string(), - ConstantInner::Composite(ref components) => format!( - "{}({})", - match module.types[constant.ty].inner { - TypeInner::Vector { size, .. } => Cow::Owned(format!("vec{}", size as u8,)), - TypeInner::Matrix { columns, rows, .. } => - Cow::Owned(format!("mat{}x{}", columns as u8, rows as u8,)), - TypeInner::Struct { .. } => - Cow::::Borrowed(builder.structs.get(&constant.ty).unwrap()), - TypeInner::Array { .. } => write_type( - constant.ty, - &module.types, - &module.constants, - builder.structs, - None, - manager - )?, - _ => + match class { + ImageClass::Sampled { .. } => write!(self.out, "texelFetch(")?, + ImageClass::Storage(_) => write!(self.out, "imageLoad(")?, + ImageClass::Depth => todo!(), + } + + self.write_expr(image, ctx)?; + write!(self.out, ", ")?; + self.write_expr(coordinate, ctx)?; + + match class { + ImageClass::Sampled { .. } => { + write!(self.out, ", ")?; + self.write_expr(index.unwrap(), ctx)?; + write!(self.out, ")")? + } + ImageClass::Storage(_) => write!(self.out, ")")?, + ImageClass::Depth => todo!(), + } + } + Expression::Unary { op, expr } => { + write!( + self.out, + "({} ", + match op { + UnaryOperator::Negate => "-", + UnaryOperator::Not => match *ctx.typifier.get(expr, &self.module.types) { + TypeInner::Scalar { + kind: ScalarKind::Sint, + .. + } => "~", + TypeInner::Scalar { + kind: ScalarKind::Uint, + .. + } => "~", + TypeInner::Scalar { + kind: ScalarKind::Bool, + .. + } => "!", + ref other => + return Err(Error::Custom(format!( + "Cannot apply not to type {:?}", + other + ))), + }, + } + )?; + + self.write_expr(expr, ctx)?; + + write!(self.out, ")")? + } + Expression::Binary { op, left, right } => { + write!(self.out, "(")?; + self.write_expr(left, ctx)?; + + write!( + self.out, + " {} ", + match op { + BinaryOperator::Add => "+", + BinaryOperator::Subtract => "-", + BinaryOperator::Multiply => "*", + BinaryOperator::Divide => "/", + BinaryOperator::Modulo => "%", + BinaryOperator::Equal => "==", + BinaryOperator::NotEqual => "!=", + BinaryOperator::Less => "<", + BinaryOperator::LessEqual => "<=", + BinaryOperator::Greater => ">", + BinaryOperator::GreaterEqual => ">=", + BinaryOperator::And => "&", + BinaryOperator::ExclusiveOr => "^", + BinaryOperator::InclusiveOr => "|", + BinaryOperator::LogicalAnd => "&&", + BinaryOperator::LogicalOr => "||", + BinaryOperator::ShiftLeft => "<<", + BinaryOperator::ShiftRight => ">>", + } + )?; + + self.write_expr(right, ctx)?; + + write!(self.out, ")")? + } + Expression::Select { + condition, + accept, + reject, + } => { + write!(self.out, "(")?; + self.write_expr(condition, ctx)?; + write!(self.out, " ? ")?; + self.write_expr(accept, ctx)?; + write!(self.out, " : ")?; + self.write_expr(reject, ctx)?; + write!(self.out, ")")? + } + Expression::Intrinsic { fun, argument } => { + write!( + self.out, + "{}(", + match fun { + IntrinsicFunction::IsFinite => "!isinf", + IntrinsicFunction::IsInf => "isinf", + IntrinsicFunction::IsNan => "isnan", + IntrinsicFunction::IsNormal => "!isnan", + IntrinsicFunction::All => "all", + IntrinsicFunction::Any => "any", + } + )?; + + self.write_expr(argument, ctx)?; + + write!(self.out, ")")? + } + Expression::Transpose(matrix) => { + write!(self.out, "transpose(")?; + self.write_expr(matrix, ctx)?; + write!(self.out, ")")? + } + Expression::DotProduct(left, right) => { + write!(self.out, "dot(")?; + self.write_expr(left, ctx)?; + write!(self.out, ", ")?; + self.write_expr(right, ctx)?; + write!(self.out, ")")? + } + Expression::CrossProduct(left, right) => { + write!(self.out, "cross(")?; + self.write_expr(left, ctx)?; + write!(self.out, ", ")?; + self.write_expr(right, ctx)?; + write!(self.out, ")")? + } + Expression::As { + expr, + kind, + convert, + } => { + if convert { + self.write_type(ctx.typifier.get_handle(expr).unwrap(), None)?; + } else { + let source_kind = match *ctx.typifier.get(expr, &self.module.types) { + TypeInner::Scalar { + kind: source_kind, .. + } => source_kind, + TypeInner::Vector { + kind: source_kind, .. + } => source_kind, + _ => unreachable!(), + }; + + write!( + self.out, + "{}", + match (source_kind, kind) { + (ScalarKind::Float, ScalarKind::Sint) => "floatBitsToInt", + (ScalarKind::Float, ScalarKind::Uint) => "floatBitsToUInt", + (ScalarKind::Sint, ScalarKind::Float) => "intBitsToFloat", + (ScalarKind::Uint, ScalarKind::Float) => "uintBitsToFloat", + _ => { + return Err(Error::Custom(format!( + "Cannot bitcast {:?} to {:?}", + source_kind, kind + ))); + } + } + )?; + } + + write!(self.out, "(")?; + self.write_expr(expr, ctx)?; + write!(self.out, ")")? + } + Expression::Derivative { axis, expr } => { + write!( + self.out, + "{}(", + match axis { + DerivativeAxis::X => "dFdx", + DerivativeAxis::Y => "dFdy", + DerivativeAxis::Width => "fwidth", + } + )?; + self.write_expr(expr, ctx)?; + write!(self.out, ")")? + } + Expression::Call { + origin: FunctionOrigin::Local(ref function), + ref arguments, + } => { + write!( + self.out, + "{}(", + self.names.get(&NameKey::Function(*function)).unwrap() + )?; + self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; + write!(self.out, ")")? + } + Expression::Call { + origin: crate::FunctionOrigin::External(ref name), + ref arguments, + } => match name.as_str() { + "cos" | "normalize" | "sin" | "length" | "abs" | "floor" | "inverse" + | "distance" | "dot" | "min" | "max" | "reflect" | "pow" | "step" | "cross" + | "fclamp" | "clamp" | "mix" | "smoothstep" => { + let name = match name.as_str() { + "fclamp" => "clamp", + name => name, + }; + + write!(self.out, "{}(", name)?; + self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; + write!(self.out, ")")? + } + "atan2" => { + write!(self.out, "atan(")?; + self.write_expr(arguments[1], ctx)?; + write!(self.out, ", ")?; + self.write_expr(arguments[0], ctx)?; + write!(self.out, ")")? + } + other => { return Err(Error::Custom(format!( - "Cannot build constant of type {}", - write_type( - constant.ty, - &module.types, - &module.constants, - builder.structs, - None, - manager - )? - ))), + "Unsupported function call {}", + other + ))) + } }, - components - .iter() - .map(|component| write_constant( - &module.constants[*component], - module, - builder, - manager - )) - .collect::, _>>()? - .join(","), - ), - }) + Expression::ArrayLength(expr) => { + write!(self.out, "uint(")?; + self.write_expr(expr, ctx)?; + write!(self.out, ".length())")? + } + } + + Ok(()) + } + + fn write_constant(&mut self, constant: &Constant) -> Result<(), Error> { + match constant.inner { + ConstantInner::Sint(int) => write!(self.out, "{}", int)?, + ConstantInner::Uint(int) => write!(self.out, "{}u", int)?, + ConstantInner::Float(float) => write!(self.out, "{:?}", float)?, + ConstantInner::Bool(boolean) => write!(self.out, "{}", boolean)?, + ConstantInner::Composite(ref components) => { + self.write_type(constant.ty, None)?; + write!(self.out, "(")?; + self.write_slice(components, |this, _, arg| { + this.write_constant(&this.module.constants[*arg]) + })?; + write!(self.out, ")")? + } + } + + Ok(()) + } } struct ScalarString<'a> { @@ -1451,11 +1429,7 @@ struct ScalarString<'a> { full: &'a str, } -fn map_scalar( - kind: ScalarKind, - width: crate::Bytes, - manager: &mut FeaturesManager, -) -> Result, Error> { +fn glsl_scalar(kind: ScalarKind, width: crate::Bytes) -> Result, Error> { Ok(match kind { ScalarKind::Sint => ScalarString { prefix: "i", @@ -1470,14 +1444,10 @@ fn map_scalar( prefix: "", full: "float", }, - 8 => { - manager.request(Features::DOUBLE_TYPE); - - ScalarString { - prefix: "d", - full: "double", - } - } + 8 => ScalarString { + prefix: "d", + full: "double", + }, _ => { return Err(Error::Custom(format!( "Cannot build float of width {}", @@ -1492,144 +1462,41 @@ fn map_scalar( }) } -fn write_type<'a>( - ty: Handle, - types: &Arena, - constants: &Arena, - structs: &'a FastHashMap, String>, - block: Option, - manager: &mut FeaturesManager, -) -> Result, Error> { - Ok(match types[ty].inner { - TypeInner::Scalar { kind, width } => Cow::Borrowed(map_scalar(kind, width, manager)?.full), - TypeInner::Vector { size, kind, width } => Cow::Owned(format!( - "{}vec{}", - map_scalar(kind, width, manager)?.prefix, - size as u8 - )), - TypeInner::Matrix { - columns, - rows, - width, - } => { - if width == 8 { - manager.request(Features::DOUBLE_TYPE); - } - - Cow::Owned(format!( - "{}mat{}x{}", - map_scalar(crate::ScalarKind::Float, width, manager)?.prefix, - columns as u8, - rows as u8 - )) - } - TypeInner::Pointer { base, .. } => { - write_type(base, types, constants, structs, None, manager)? - } - TypeInner::Array { base, size, .. } => { - if let TypeInner::Array { .. } = types[base].inner { - manager.request(Features::ARRAY_OF_ARRAYS) - } - - Cow::Owned(format!( - "{}[{}]", - write_type(base, types, constants, structs, None, manager)?, - write_array_size(size, constants)? - )) - } - TypeInner::Struct { ref members } => { - if let Some(name) = block { - let mut out = String::new(); - writeln!(&mut out, "{} {{", name)?; - - for (idx, member) in members.iter().enumerate() { - writeln!( - &mut out, - "\t{} {};", - write_type(member.ty, types, constants, structs, None, manager)?, - member - .name - .clone() - .filter(|s| is_valid_ident(s)) - .unwrap_or_else(|| format!("_{}", idx)) - )?; - } - - write!(&mut out, "}}")?; - - Cow::Owned(out) - } else { - Cow::Borrowed(structs.get(&ty).unwrap()) - } - } - _ => unreachable!(), - }) -} - -fn write_image_type( - dim: crate::ImageDimension, - arrayed: bool, - class: ImageClass, - manager: &mut FeaturesManager, -) -> Result { - if arrayed && dim == crate::ImageDimension::Cube { - manager.request(Features::CUBE_TEXTURES_ARRAY) - } else if dim == crate::ImageDimension::D1 { - manager.request(Features::TEXTURE_1D) +fn glsl_built_in(built_in: BuiltIn) -> &'static str { + match built_in { + BuiltIn::Position => "gl_Position", + BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", + BuiltIn::BaseInstance => "gl_BaseInstance", + BuiltIn::BaseVertex => "gl_BaseVertex", + BuiltIn::ClipDistance => "gl_ClipDistance", + BuiltIn::InstanceIndex => "gl_InstanceIndex", + BuiltIn::VertexIndex => "gl_VertexIndex", + BuiltIn::PointSize => "gl_PointSize", + BuiltIn::FragCoord => "gl_FragCoord", + BuiltIn::FrontFacing => "gl_FrontFacing", + BuiltIn::SampleIndex => "gl_SampleID", + BuiltIn::FragDepth => "gl_FragDepth", + BuiltIn::LocalInvocationId => "gl_LocalInvocationID", + BuiltIn::LocalInvocationIndex => "gl_LocalInvocationIndex", + BuiltIn::WorkGroupId => "gl_WorkGroupID", } - - let (base, kind, ms, comparison) = match class { - ImageClass::Sampled { kind, multi: true } => { - manager.request(Features::MULTISAMPLED_TEXTURES); - if arrayed { - manager.request(Features::MULTISAMPLED_TEXTURE_ARRAYS); - } - - ("sampler", kind, "MS", "") - } - ImageClass::Sampled { kind, multi: false } => ("sampler", kind, "", ""), - ImageClass::Depth => ("sampler", crate::ScalarKind::Float, "", "Shadow"), - ImageClass::Storage(format) => ("image", format.into(), "", ""), - }; - - Ok(format!( - "{}{}{}{}{}{}", - map_scalar(kind, 4, manager)?.prefix, - base, - ImageDimension(dim), - ms, - if arrayed { "Array" } else { "" }, - comparison - )) } -fn write_storage_class( - class: StorageClass, - manager: &mut FeaturesManager, -) -> Result<&'static str, Error> { - Ok(match class { +fn glsl_storage_class(class: StorageClass) -> &'static str { + match class { StorageClass::Function => "", - StorageClass::Input => "in ", - StorageClass::Output => "out ", + StorageClass::Input => "in", + StorageClass::Output => "out", StorageClass::Private => "", - StorageClass::Storage => { - manager.request(Features::BUFFER_STORAGE); - "buffer " - } - StorageClass::Uniform => "uniform ", - StorageClass::Handle => "uniform ", - StorageClass::WorkGroup => { - manager.request(Features::COMPUTE_SHADER); - "shared " - } - StorageClass::PushConstant => { - manager.request(Features::PUSH_CONSTANT); - "" - } - }) + StorageClass::Storage => "buffer", + StorageClass::Uniform => "uniform", + StorageClass::Handle => "uniform", + StorageClass::WorkGroup => "shared", + StorageClass::PushConstant => "", + } } -fn write_interpolation(interpolation: Interpolation) -> Result<&'static str, Error> { +fn glsl_interpolation(interpolation: Interpolation) -> Result<&'static str, Error> { Ok(match interpolation { Interpolation::Perspective => "smooth", Interpolation::Linear => "noperspective", @@ -1644,16 +1511,6 @@ fn write_interpolation(interpolation: Interpolation) -> Result<&'static str, Err }) } -fn write_array_size(size: ArraySize, constants: &Arena) -> Result { - Ok(match size { - ArraySize::Constant(const_handle) => match constants[const_handle].inner { - ConstantInner::Uint(size) => size.to_string(), - _ => unreachable!(), - }, - ArraySize::Dynamic => String::from(""), - }) -} - struct ImageDimension(crate::ImageDimension); impl fmt::Display for ImageDimension { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -1670,186 +1527,34 @@ impl fmt::Display for ImageDimension { } } -fn write_struct( - handle: Handle, - members: &[StructMember], - module: &Module, - structs: &FastHashMap, String>, - out: &mut impl Write, - built_structs: &mut FastHashMap, ()>, - manager: &mut FeaturesManager, -) -> Result { - if built_structs.get(&handle).is_some() { - return Ok(true); - } - - let mut tmp = String::new(); - - let name = structs.get(&handle).unwrap(); - let mut fields = 0; - - writeln!(&mut tmp, "struct {} {{", name)?; - for (idx, member) in members.iter().enumerate() { - if let MemberOrigin::BuiltIn(_) = member.origin { - continue; - } - - if let TypeInner::Struct { ref members } = module.types[member.ty].inner { - if !write_struct( - member.ty, - members, - module, - structs, - out, - built_structs, - manager, - )? { - continue; - } - } - - writeln!( - &mut tmp, - "\t{} {};", - write_type( - member.ty, - &module.types, - &module.constants, - &structs, - None, - manager - )?, - member - .name - .clone() - .filter(|s| is_valid_ident(s)) - .unwrap_or_else(|| format!("_{}", idx)) - )?; - - fields += 1; - } - writeln!(&mut tmp, "}};")?; - - if fields != 0 { - built_structs.insert(handle, ()); - writeln!(out, "{}", tmp)?; - } - - Ok(fields != 0) -} - -fn is_valid_ident(ident: &str) -> bool { - ident.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') - && ident.contains(|c: char| c.is_ascii_alphanumeric() || c == '_') - && !ident.starts_with("gl_") - && ident != "main" -} - -fn builtin_to_glsl(builtin: BuiltIn) -> &'static str { - match builtin { - BuiltIn::Position => "gl_Position", - BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", - BuiltIn::BaseInstance => "gl_BaseInstance", - BuiltIn::BaseVertex => "gl_BaseVertex", - BuiltIn::ClipDistance => "gl_ClipDistance", - BuiltIn::InstanceIndex => "gl_InstanceIndex", - BuiltIn::VertexIndex => "gl_VertexIndex", - BuiltIn::PointSize => "gl_PointSize", - BuiltIn::FragCoord => "gl_FragCoord", - BuiltIn::FrontFacing => "gl_FrontFacing", - BuiltIn::SampleIndex => "gl_SampleID", - BuiltIn::FragDepth => "gl_FragDepth", - BuiltIn::LocalInvocationId => "gl_LocalInvocationID", - BuiltIn::LocalInvocationIndex => "gl_LocalInvocationIndex", - BuiltIn::WorkGroupId => "gl_WorkGroupID", - } -} - -fn write_format_glsl(format: StorageFormat, manager: &mut FeaturesManager) -> &'static str { +fn glsl_storage_format(format: StorageFormat) -> &'static str { match format { - StorageFormat::R8Unorm => { - manager.request(Features::FULL_IMAGE_FORMATS); - "r8" - } - StorageFormat::R8Snorm => { - manager.request(Features::FULL_IMAGE_FORMATS); - "r8_snorm" - } - StorageFormat::R8Uint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "r8ui" - } - StorageFormat::R8Sint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "r8i" - } - StorageFormat::R16Uint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "r16ui" - } - StorageFormat::R16Sint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "r16i" - } - StorageFormat::R16Float => { - manager.request(Features::FULL_IMAGE_FORMATS); - "r16f" - } - StorageFormat::Rg8Unorm => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg8" - } - StorageFormat::Rg8Snorm => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg8_snorm" - } - StorageFormat::Rg8Uint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg8ui" - } - StorageFormat::Rg8Sint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg8i" - } + StorageFormat::R8Unorm => "r8", + StorageFormat::R8Snorm => "r8_snorm", + StorageFormat::R8Uint => "r8ui", + StorageFormat::R8Sint => "r8i", + StorageFormat::R16Uint => "r16ui", + StorageFormat::R16Sint => "r16i", + StorageFormat::R16Float => "r16f", + StorageFormat::Rg8Unorm => "rg8", + StorageFormat::Rg8Snorm => "rg8_snorm", + StorageFormat::Rg8Uint => "rg8ui", + StorageFormat::Rg8Sint => "rg8i", StorageFormat::R32Uint => "r32ui", StorageFormat::R32Sint => "r32i", StorageFormat::R32Float => "r32f", - StorageFormat::Rg16Uint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg16ui" - } - StorageFormat::Rg16Sint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg16i" - } - StorageFormat::Rg16Float => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg16f" - } + StorageFormat::Rg16Uint => "rg16ui", + StorageFormat::Rg16Sint => "rg16i", + StorageFormat::Rg16Float => "rg16f", StorageFormat::Rgba8Unorm => "rgba8ui", StorageFormat::Rgba8Snorm => "rgba8_snorm", StorageFormat::Rgba8Uint => "rgba8ui", StorageFormat::Rgba8Sint => "rgba8i", - StorageFormat::Rgb10a2Unorm => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rgb10_a2ui" - } - StorageFormat::Rg11b10Float => { - manager.request(Features::FULL_IMAGE_FORMATS); - "r11f_g11f_b10f" - } - StorageFormat::Rg32Uint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg32ui" - } - StorageFormat::Rg32Sint => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg32i" - } - StorageFormat::Rg32Float => { - manager.request(Features::FULL_IMAGE_FORMATS); - "rg32f" - } + StorageFormat::Rgb10a2Unorm => "rgb10_a2ui", + StorageFormat::Rg11b10Float => "r11f_g11f_b10f", + StorageFormat::Rg32Uint => "rg32ui", + StorageFormat::Rg32Sint => "rg32i", + StorageFormat::Rg32Float => "rg32f", StorageFormat::Rgba16Uint => "rgba16ui", StorageFormat::Rgba16Sint => "rgba16i", StorageFormat::Rgba16Float => "rgba16f", @@ -1860,8 +1565,9 @@ fn write_format_glsl(format: StorageFormat, manager: &mut FeaturesManager) -> &' } struct TextureMappingVisitor<'a> { + names: &'a FastHashMap, expressions: &'a Arena, - map: &'a mut FastHashMap, Option>>, + map: &'a mut FastHashMap, error: Option, } @@ -1873,15 +1579,23 @@ impl<'a> Visitor for TextureMappingVisitor<'a> { Expression::GlobalVariable(global) => global, _ => unreachable!(), }; + let tex_name = self + .names + .get(&NameKey::GlobalVariable(tex_handle)) + .unwrap() + .clone(); let sampler_handle = match self.expressions[*sampler] { Expression::GlobalVariable(global) => global, _ => unreachable!(), }; - let sampler = self.map.entry(tex_handle).or_insert(Some(sampler_handle)); + let mapping = self.map.entry(tex_name).or_insert(TextureMapping { + texture: tex_handle, + sampler: Some(sampler_handle), + }); - if *sampler != Some(sampler_handle) { + if mapping.sampler != Some(sampler_handle) { self.error = Some(Error::Custom(String::from( "Cannot use texture with two different samplers", ))); @@ -1892,10 +1606,18 @@ impl<'a> Visitor for TextureMappingVisitor<'a> { Expression::GlobalVariable(global) => global, _ => unreachable!(), }; + let tex_name = self + .names + .get(&NameKey::GlobalVariable(tex_handle)) + .unwrap() + .clone(); - let sampler = self.map.entry(tex_handle).or_insert(None); + let mapping = self.map.entry(tex_name).or_insert(TextureMapping { + texture: tex_handle, + sampler: None, + }); - if *sampler != None { + if mapping.sampler != None { self.error = Some(Error::Custom(String::from( "Cannot use texture with two different samplers", ))); @@ -1905,28 +1627,3 @@ impl<'a> Visitor for TextureMappingVisitor<'a> { } } } - -fn collect_texture_mapping<'a>( - functions: impl Iterator, -) -> Result, Option>>, Error> { - let mut mappings = FastHashMap::default(); - - for func in functions { - let mut interface = Interface { - expressions: &func.expressions, - local_variables: &func.local_variables, - visitor: TextureMappingVisitor { - expressions: &func.expressions, - map: &mut mappings, - error: None, - }, - }; - interface.traverse(&func.body); - - if let Some(error) = interface.visitor.error { - return Err(error); - } - } - - Ok(mappings) -} diff --git a/src/proc/call_graph.rs b/src/proc/call_graph.rs new file mode 100644 index 000000000..1c580d5c1 --- /dev/null +++ b/src/proc/call_graph.rs @@ -0,0 +1,74 @@ +use crate::{ + arena::{Arena, Handle}, + proc::{Interface, Visitor}, + Function, +}; +use petgraph::{ + graph::{DefaultIx, NodeIndex}, + Graph, +}; + +pub type CallGraph = Graph, ()>; + +pub struct CallGraphBuilder<'a> { + pub functions: &'a Arena, +} + +impl<'a> CallGraphBuilder<'a> { + pub fn process(&self, func: &Function) -> CallGraph { + let mut graph = Graph::new(); + let mut children = Vec::new(); + + let visitor = CallGraphVisitor { + children: &mut children, + }; + + let mut interface = Interface { + expressions: &func.expressions, + local_variables: &func.local_variables, + visitor, + }; + + interface.traverse(&func.body); + + for handle in children { + let id = graph.add_node(handle); + self.collect(handle, id, &mut graph); + } + + graph + } + + fn collect(&self, handle: Handle, id: NodeIndex, graph: &mut CallGraph) { + let mut children = Vec::new(); + let visitor = CallGraphVisitor { + children: &mut children, + }; + let func = &self.functions[handle]; + + let mut interface = Interface { + expressions: &func.expressions, + local_variables: &func.local_variables, + visitor, + }; + + interface.traverse(&func.body); + + for handle in children { + let child_id = graph.add_node(handle); + graph.add_edge(id, child_id, ()); + + self.collect(handle, child_id, graph); + } + } +} + +struct CallGraphVisitor<'a> { + children: &'a mut Vec>, +} + +impl<'a> Visitor for CallGraphVisitor<'a> { + fn visit_fun(&mut self, func: Handle) { + self.children.push(func) + } +} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 2d5753ea0..961e55da7 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,10 +1,14 @@ //! Module processing functionality. +#[cfg(feature = "petgraph")] +mod call_graph; mod interface; mod namer; mod typifier; mod validator; +#[cfg(feature = "petgraph")] +pub use call_graph::{CallGraph, CallGraphBuilder}; pub use interface::{Interface, Visitor}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use typifier::{check_constant_type, ResolveContext, ResolveError, Typifier}; From bc0d876422604989d00c62ad36576dac0997122b Mon Sep 17 00:00:00 2001 From: Capucho Date: Sun, 22 Nov 2020 10:25:57 +0000 Subject: [PATCH 0295/2212] [glsl-out] Backend cleanup Moved the global writing part to it's own function Merged the texture and the global loop Applied some suggestions from kvark Added a topological sorting of the call graph before writing Removed the struct block loop and now every struct is written Organized the main backend file a bit --- Cargo.toml | 1 - build.rs | 26 ---- glsl-keywords.txt | 20 --- src/back/glsl.rs | 266 ++++++++++++++++---------------------- src/back/glsl/keywords.rs | 204 +++++++++++++++++++++++++++++ 5 files changed, 312 insertions(+), 205 deletions(-) delete mode 100644 build.rs delete mode 100644 glsl-keywords.txt create mode 100644 src/back/glsl/keywords.rs diff --git a/Cargo.toml b/Cargo.toml index c79c22573..55d65a753 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,6 @@ homepage = "https://github.com/gfx-rs/naga" repository = "https://github.com/gfx-rs/naga" keywords = ["shader", "SPIR-V"] license = "MIT OR Apache-2.0" -build = "build.rs" [dependencies] bitflags = "1" diff --git a/build.rs b/build.rs deleted file mode 100644 index 340a5d828..000000000 --- a/build.rs +++ /dev/null @@ -1,26 +0,0 @@ -use std::{ - env, - fs::{read_to_string, OpenOptions}, - io::{Result, Write}, -}; - -fn main() -> Result<()> { - println!("cargo:rerun-if-changed=glsl-keywords.txt"); - - let keywords = read_to_string("glsl-keywords.txt")?.replace('\n', " "); - let mut out = OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(format!("{}/glsl_keywords.rs", env::var("OUT_DIR").unwrap()))?; - - writeln!(&mut out, "const RESERVED_KEYWORDS: &[&str] = &[")?; - - for keyword in keywords.split(' ') { - writeln!(&mut out, "\"{}\",", keyword)?; - } - - writeln!(&mut out, "];")?; - - Ok(()) -} diff --git a/glsl-keywords.txt b/glsl-keywords.txt deleted file mode 100644 index 34b97552e..000000000 --- a/glsl-keywords.txt +++ /dev/null @@ -1,20 +0,0 @@ -attribute const uniform varying buffer shared coherent volatile restrict readonly writeonly -atomic_uint layout centroid flat smooth noperspective patch sample break continue do for while -switch case default if else subroutine in out inout float double int void bool true false invariant -precise discard return mat2 mat3 mat4 dmat2 dmat3 dmat4 mat2x2 mat2x3 mat2x4 dmat2x2 dmat2x3 dmat2x4 -mat3x2 mat3x3 mat3x4 dmat3x2 dmat3x3 dmat3x4 mat4x2 mat4x3 mat4x4 dmat4x2 dmat4x3 dmat4x4 vec2 vec3 -vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 dvec2 dvec3 dvec4 uint uvec2 uvec3 uvec4 lowp mediump highp -precision sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow -samplerCubeShadow sampler1DArray sampler2DArray sampler1DArrayShadow sampler2DArrayShadow -isampler1D isampler2D isampler3D isamplerCube isampler1DArray isampler2DArray usampler1D usampler2D -usampler3D usamplerCube usampler1DArray usampler2DArray sampler2DRect sampler2DRectShadow isampler2D -Rect usampler2DRect samplerBuffer isamplerBuffer usamplerBuffer sampler2DMS isampler2DMS -usampler2DMS sampler2DMSArray isampler2DMSArray usampler2DMSArray samplerCubeArray -samplerCubeArrayShadow isamplerCubeArray usamplerCubeArray image1D iimage1D uimage1D image2D -iimage2D uimage2D image3D iimage3D uimage3D image2DRect iimage2DRect uimage2DRect imageCube -iimageCube uimageCube imageBuffer iimageBuffer uimageBuffer image1DArray iimage1DArray uimage1DArray -image2DArray iimage2DArray uimage2DArray imageCubeArray iimageCubeArray uimageCubeArray image2DMS -iimage2DMS uimage2DMS image2DMSArray iimage2DMSArray uimage2DMSArraystruct common partition active -asm class union enum typedef template this resource goto inline noinline public static extern -external interface long short half fixed unsigned superp input output hvec2 hvec3 hvec4 fvec2 fvec3 -fvec4 sampler3DRect filter sizeof cast namespace using main diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 25a4f74f7..6a497a675 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -35,6 +35,12 @@ use std::{ io::{Error as IoError, Write}, }; +/// Contains a constant with a slice of all the reserved keywords RESERVED_KEYWORDS +mod keywords; + +const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; +const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310]; + #[derive(Debug)] pub enum Error { FormatError(FmtError), @@ -86,11 +92,10 @@ impl Version { } } - fn is_valid(&self) -> bool { + fn is_supported(&self) -> bool { match self { - Version::Desktop(v) if SUPPORTED_CORE_VERSIONS.contains(v) => true, - Version::Embedded(v) if SUPPORTED_ES_VERSIONS.contains(v) => true, - _ => false, + Version::Desktop(v) => SUPPORTED_CORE_VERSIONS.contains(v), + Version::Embedded(v) => SUPPORTED_ES_VERSIONS.contains(v), } } } @@ -126,11 +131,6 @@ pub struct TextureMapping { pub sampler: Option>, } -// imports a list of reserved keywords called RESERVED_KEYWORDS -include!(concat!(env!("OUT_DIR"), "/glsl_keywords.rs")); -const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; -const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310]; - bitflags::bitflags! { struct Features: u32 { const BUFFER_STORAGE = 1; @@ -326,26 +326,16 @@ struct FunctionCtx<'a, 'b> { } impl<'a, 'b> FunctionCtx<'a, 'b> { - fn get_local<'c>( - &self, - local: Handle, - names: &'c FastHashMap, - ) -> &'c str { + fn name_key(&self, local: Handle) -> NameKey { match self.func { - FunctionType::Function(handle) => { - names.get(&NameKey::FunctionLocal(handle, local)).unwrap() - } - FunctionType::EntryPoint(idx) => { - names.get(&NameKey::EntryPointLocal(idx, local)).unwrap() - } + FunctionType::Function(handle) => NameKey::FunctionLocal(handle, local), + FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, local), } } fn get_arg<'c>(&self, arg: u32, names: &'c FastHashMap) -> &'c str { match self.func { - FunctionType::Function(handle) => { - names.get(&NameKey::FunctionArgument(handle, arg)).unwrap() - } + FunctionType::Function(handle) => &names[&NameKey::FunctionArgument(handle, arg)], FunctionType::EntryPoint(_) => unreachable!(), } } @@ -383,7 +373,7 @@ pub struct Writer<'a, W> { impl<'a, W: Write> Writer<'a, W> { pub fn new(out: W, module: &'a Module, options: &'a Options) -> Result { - if !options.version.is_valid() { + if !options.version.is_supported() { return Err(Error::Custom(format!( "Version not supported {}", options.version @@ -400,7 +390,7 @@ impl<'a, W: Write> Writer<'a, W> { .ok_or_else(|| Error::Custom(String::from("Entry point not found")))?; let mut names = FastHashMap::default(); - Namer::process(module, RESERVED_KEYWORDS, &mut names); + Namer::process(module, keywords::RESERVED_KEYWORDS, &mut names); let call_graph = CallGraphBuilder { functions: &module.functions, @@ -545,30 +535,9 @@ impl<'a, W: Write> Writer<'a, W> { } } - let mut built_structs = FastHashMap::default(); - - for (_, global) in self - .module - .global_variables - .iter() - .zip(&self.entry_point.function.global_usage) - .filter_map(|(global, usage)| Some(global).filter(|_| !usage.is_empty())) - { - match global.class { - StorageClass::Storage | StorageClass::Uniform => (), - _ => continue, - } - - if let TypeInner::Struct { .. } = self.module.types[global.ty].inner { - built_structs.insert(global.ty, ()); - } - } - for (handle, ty) in self.module.types.iter() { if let TypeInner::Struct { ref members } = ty.inner { - if built_structs.get(&handle).is_none() { - self.write_struct(handle, members)? - } + self.write_struct(handle, members)? } } @@ -589,94 +558,54 @@ impl<'a, W: Write> Writer<'a, W> { .zip(&self.entry_point.function.global_usage) .filter_map(|(global, usage)| Some(global).filter(|_| !usage.is_empty())) { - if let TypeInner::Image { - dim, - arrayed, - class, - } = self.module.types[global.ty].inner - { - if let TypeInner::Image { - class: ImageClass::Storage(format), - .. - } = self.module.types[global.ty].inner - { - write!(self.out, "layout({}) ", glsl_storage_format(format))?; - } - - if global.storage_access == StorageAccess::LOAD { - write!(self.out, "readonly ")?; - } else if global.storage_access == StorageAccess::STORE { - write!(self.out, "writeonly ")?; - } - - write!(self.out, "uniform ")?; - - self.write_image_type(dim, arrayed, class)?; - - let name = self.names.get(&NameKey::GlobalVariable(handle)).unwrap(); - writeln!(self.out, " {};", name)? - } - } - - for (handle, global) in self - .module - .global_variables - .iter() - .zip(&self.entry_point.function.global_usage) - .filter_map(|(global, usage)| Some(global).filter(|_| !usage.is_empty())) - { - match self.module.types[global.ty].inner { - TypeInner::Image { .. } | TypeInner::Sampler { .. } => continue, - _ => {} - } - if let Some(crate::Binding::BuiltIn(_)) = global.binding { continue; } - if global.storage_access == StorageAccess::LOAD { - write!(self.out, "readonly ")?; - } else if global.storage_access == StorageAccess::STORE { - write!(self.out, "writeonly ")?; - } - - if let Some(interpolation) = global.interpolation { - match (self.options.entry_point.0, global.class) { - (ShaderStage::Fragment, StorageClass::Input) - | (ShaderStage::Vertex, StorageClass::Output) => { - write!(self.out, "{} ", glsl_interpolation(interpolation)?)?; + match self.module.types[global.ty].inner { + TypeInner::Image { + dim, + arrayed, + class, + } => { + if let TypeInner::Image { + class: ImageClass::Storage(format), + .. + } = self.module.types[global.ty].inner + { + write!(self.out, "layout({}) ", glsl_storage_format(format))?; } - _ => {} - }; - } - let block = match global.class { - StorageClass::Storage | StorageClass::Uniform => { - let block_name = self.names.get(&NameKey::Type(global.ty)).cloned().unwrap(); + if global.storage_access == StorageAccess::LOAD { + write!(self.out, "readonly ")?; + } else if global.storage_access == StorageAccess::STORE { + write!(self.out, "writeonly ")?; + } - Some(block_name) + write!(self.out, "uniform ")?; + + self.write_image_type(dim, arrayed, class)?; + + writeln!( + self.out, + " {};", + self.names[&NameKey::GlobalVariable(handle)] + )? } - _ => None, - }; - - write!(self.out, "{} ", glsl_storage_class(global.class))?; - - self.write_type(global.ty, block)?; - - let name = self.names.get(&NameKey::GlobalVariable(handle)).unwrap(); - writeln!(self.out, " {};", name)? + TypeInner::Sampler { .. } => continue, + _ => self.write_global(handle, global)?, + } } writeln!(self.out)?; - let functions: Vec<_> = self - .call_graph - .raw_nodes() - .iter() - .map(|node| node.weight) - .collect(); - for handle in functions { - let name = self.names.get(&NameKey::Function(handle)).cloned().unwrap(); + // Sort the graph topologically so that functions calls are valid + // It's impossible for this to panic because the IR forbids cycles + let functions = petgraph::algo::toposort(&self.call_graph, None).unwrap(); + + for node in functions { + let handle = self.call_graph[node]; + let name = self.names[&NameKey::Function(handle)].clone(); self.write_function( FunctionType::Function(handle), &self.module.functions[handle], @@ -693,6 +622,46 @@ impl<'a, W: Write> Writer<'a, W> { Ok(texture_mappings) } + fn write_global( + &mut self, + handle: Handle, + global: &GlobalVariable, + ) -> Result<(), Error> { + if global.storage_access == StorageAccess::LOAD { + write!(self.out, "readonly ")?; + } else if global.storage_access == StorageAccess::STORE { + write!(self.out, "writeonly ")?; + } + + if let Some(interpolation) = global.interpolation { + match (self.options.entry_point.0, global.class) { + (ShaderStage::Fragment, StorageClass::Input) + | (ShaderStage::Vertex, StorageClass::Output) => { + write!(self.out, "{} ", glsl_interpolation(interpolation)?)?; + } + _ => (), + }; + } + + let block = match global.class { + StorageClass::Storage | StorageClass::Uniform => { + let block_name = self.names[&NameKey::Type(global.ty)].clone(); + + Some(block_name) + } + _ => None, + }; + + write!(self.out, "{} ", glsl_storage_class(global.class))?; + + self.write_type(global.ty, block)?; + + let name = &self.names[&NameKey::GlobalVariable(handle)]; + writeln!(self.out, " {};", name)?; + + Ok(()) + } + fn write_function>( &mut self, ty: FunctionType, @@ -713,7 +682,7 @@ impl<'a, W: Write> Writer<'a, W> { }, )?; - let mut ctx = FunctionCtx { + let ctx = FunctionCtx { func: ty, expressions: &func.expressions, typifier: &typifier, @@ -726,9 +695,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "\t")?; self.write_type(local.ty, None)?; - let name = ctx.get_local(handle, &self.names); - - write!(self.out, " {}", name)?; + write!(self.out, " {}", self.names[&ctx.name_key(handle)])?; if let Some(init) = local.init { write!(self.out, " = ",)?; @@ -742,7 +709,7 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out)?; for sta in func.body.iter() { - self.write_stmt(sta, &mut ctx, 1)?; + self.write_stmt(sta, &ctx, 1)?; } Ok(writeln!(self.out, "}}")?) @@ -831,15 +798,13 @@ impl<'a, W: Write> Writer<'a, W> { writeln!( self.out, " {};", - self.names - .get(&NameKey::StructMember(ty, idx as u32)) - .unwrap() + &self.names[&NameKey::StructMember(ty, idx as u32)] )?; } write!(self.out, "}}")? } else { - write!(self.out, "{}", self.names.get(&NameKey::Type(ty)).unwrap())? + write!(self.out, "{}", &self.names[&NameKey::Type(ty)])? } } _ => unreachable!(), @@ -917,29 +882,26 @@ impl<'a, W: Write> Writer<'a, W> { handle: Handle, members: &[StructMember], ) -> Result<(), Error> { - let name = self.names.get(&NameKey::Type(handle)).unwrap(); + writeln!(self.out, "struct {} {{", self.names[&NameKey::Type(handle)])?; - writeln!(self.out, "struct {} {{", name)?; for (idx, member) in members.iter().enumerate() { write!(self.out, "\t")?; self.write_type(member.ty, None)?; writeln!( self.out, " {};", - self.names - .get(&NameKey::StructMember(handle, idx as u32)) - .unwrap() + self.names[&NameKey::StructMember(handle, idx as u32)] )?; } - writeln!(self.out, "}};")?; + writeln!(self.out, "}};")?; Ok(()) } fn write_stmt( &mut self, sta: &Statement, - ctx: &mut FunctionCtx<'_, '_>, + ctx: &FunctionCtx<'_, '_>, indent: usize, ) -> Result<(), Error> { write!(self.out, "{}", "\t".repeat(indent))?; @@ -1040,7 +1002,7 @@ impl<'a, W: Write> Writer<'a, W> { fn write_expr( &mut self, expr: Handle, - ctx: &mut FunctionCtx<'_, '_>, + ctx: &FunctionCtx<'_, '_>, ) -> Result<(), Error> { match ctx.expressions[expr] { Expression::Access { base, index } => { @@ -1062,7 +1024,7 @@ impl<'a, W: Write> Writer<'a, W> { write!( self.out, ".{}", - self.names.get(&NameKey::StructMember(ty, index)).unwrap() + &self.names[&NameKey::StructMember(ty, index)] )? } ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), @@ -1096,12 +1058,12 @@ impl<'a, W: Write> Writer<'a, W> { write!( self.out, "{}", - self.names.get(&NameKey::GlobalVariable(handle)).unwrap() + &self.names[&NameKey::GlobalVariable(handle)] )? } } Expression::LocalVariable(handle) => { - write!(self.out, "{}", ctx.get_local(handle, &self.names))? + write!(self.out, "{}", self.names[&ctx.name_key(handle)])? } Expression::Load { pointer } => self.write_expr(pointer, ctx)?, Expression::ImageSample { @@ -1356,11 +1318,7 @@ impl<'a, W: Write> Writer<'a, W> { origin: FunctionOrigin::Local(ref function), ref arguments, } => { - write!( - self.out, - "{}(", - self.names.get(&NameKey::Function(*function)).unwrap() - )?; + write!(self.out, "{}(", &self.names[&NameKey::Function(*function)])?; self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; write!(self.out, ")")? } @@ -1579,11 +1537,7 @@ impl<'a> Visitor for TextureMappingVisitor<'a> { Expression::GlobalVariable(global) => global, _ => unreachable!(), }; - let tex_name = self - .names - .get(&NameKey::GlobalVariable(tex_handle)) - .unwrap() - .clone(); + let tex_name = self.names[&NameKey::GlobalVariable(tex_handle)].clone(); let sampler_handle = match self.expressions[*sampler] { Expression::GlobalVariable(global) => global, @@ -1606,11 +1560,7 @@ impl<'a> Visitor for TextureMappingVisitor<'a> { Expression::GlobalVariable(global) => global, _ => unreachable!(), }; - let tex_name = self - .names - .get(&NameKey::GlobalVariable(tex_handle)) - .unwrap() - .clone(); + let tex_name = self.names[&NameKey::GlobalVariable(tex_handle)].clone(); let mapping = self.map.entry(tex_name).or_insert(TextureMapping { texture: tex_handle, diff --git a/src/back/glsl/keywords.rs b/src/back/glsl/keywords.rs new file mode 100644 index 000000000..5a2836c18 --- /dev/null +++ b/src/back/glsl/keywords.rs @@ -0,0 +1,204 @@ +pub const RESERVED_KEYWORDS: &[&str] = &[ + "attribute", + "const", + "uniform", + "varying", + "buffer", + "shared", + "coherent", + "volatile", + "restrict", + "readonly", + "writeonly", + "atomic_uint", + "layout", + "centroid", + "flat", + "smooth", + "noperspective", + "patch", + "sample", + "break", + "continue", + "do", + "for", + "while", + "switch", + "case", + "default", + "if", + "else", + "subroutine", + "in", + "out", + "inout", + "float", + "double", + "int", + "void", + "bool", + "true", + "false", + "invariant", + "precise", + "discard", + "return", + "mat2", + "mat3", + "mat4", + "dmat2", + "dmat3", + "dmat4", + "mat2x2", + "mat2x3", + "mat2x4", + "dmat2x2", + "dmat2x3", + "dmat2x4", + "mat3x2", + "mat3x3", + "mat3x4", + "dmat3x2", + "dmat3x3", + "dmat3x4", + "mat4x2", + "mat4x3", + "mat4x4", + "dmat4x2", + "dmat4x3", + "dmat4x4", + "vec2", + "vec3", + "vec4", + "ivec2", + "ivec3", + "ivec4", + "bvec2", + "bvec3", + "bvec4", + "dvec2", + "dvec3", + "dvec4", + "uint", + "uvec2", + "uvec3", + "uvec4", + "lowp", + "mediump", + "highp", + "precision", + "sampler1D", + "sampler2D", + "sampler3D", + "samplerCube", + "sampler1DShadow", + "sampler2DShadow", + "samplerCubeShadow", + "sampler1DArray", + "sampler2DArray", + "sampler1DArrayShadow", + "sampler2DArrayShadow", + "isampler1D", + "isampler2D", + "isampler3D", + "isamplerCube", + "isampler1DArray", + "isampler2DArray", + "usampler1D", + "usampler2D", + "usampler3D", + "usamplerCube", + "usampler1DArray", + "usampler2DArray", + "sampler2DRect", + "sampler2DRectShadow", + "isampler2D", + "Rect", + "usampler2DRect", + "samplerBuffer", + "isamplerBuffer", + "usamplerBuffer", + "sampler2DMS", + "isampler2DMS", + "usampler2DMS", + "sampler2DMSArray", + "isampler2DMSArray", + "usampler2DMSArray", + "samplerCubeArray", + "samplerCubeArrayShadow", + "isamplerCubeArray", + "usamplerCubeArray", + "image1D", + "iimage1D", + "uimage1D", + "image2D", + "iimage2D", + "uimage2D", + "image3D", + "iimage3D", + "uimage3D", + "image2DRect", + "iimage2DRect", + "uimage2DRect", + "imageCube", + "iimageCube", + "uimageCube", + "imageBuffer", + "iimageBuffer", + "uimageBuffer", + "image1DArray", + "iimage1DArray", + "uimage1DArray", + "image2DArray", + "iimage2DArray", + "uimage2DArray", + "imageCubeArray", + "iimageCubeArray", + "uimageCubeArray", + "image2DMS", + "iimage2DMS", + "uimage2DMS", + "image2DMSArray", + "iimage2DMSArray", + "uimage2DMSArraystruct", + "common", + "partition", + "active", + "asm", + "class", + "union", + "enum", + "typedef", + "template", + "this", + "resource", + "goto", + "inline", + "noinline", + "public", + "static", + "extern", + "external", + "interface", + "long", + "short", + "half", + "fixed", + "unsigned", + "superp", + "input", + "output", + "hvec2", + "hvec3", + "hvec4", + "fvec2", + "fvec3", + "fvec4", + "sampler3DRect", + "filter", + "sizeof", + "cast", + "namespace", + "using", + "main", +]; From 96c80738650822de35f77ab6a589f309460c8f39 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 20 Nov 2020 17:00:39 -0500 Subject: [PATCH 0296/2212] [spv-out] always return expression type --- src/back/spv/instructions.rs | 16 +++--- src/back/spv/writer.rs | 96 ++++++++++++++++++++++-------------- 2 files changed, 65 insertions(+), 47 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 8c8275097..ab8e56844 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -379,11 +379,9 @@ pub(super) fn instruction_load( instruction.set_result(id); instruction.add_operand(pointer_type_id); - instruction.add_operand(if let Some(memory_access) = memory_access { - memory_access.bits() - } else { - spirv::MemoryAccess::NONE.bits() - }); + if let Some(memory_access) = memory_access { + instruction.add_operand(memory_access.bits()); + } instruction } @@ -397,11 +395,9 @@ pub(super) fn instruction_store( instruction.add_operand(pointer_type_id); instruction.add_operand(object_id); - instruction.add_operand(if let Some(memory_access) = memory_access { - memory_access.bits() - } else { - spirv::MemoryAccess::NONE.bits() - }); + if let Some(memory_access) = memory_access { + instruction.add_operand(memory_access.bits()); + } instruction } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index af15469e1..f1b43f528 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -15,8 +15,6 @@ pub enum Error { #[error("not an image")] NotImage, #[error("empty value")] - EmptyValue, - #[error("feature is not yet implemented")] FeatureNotImplemented(), } @@ -81,6 +79,7 @@ impl Function { #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LocalType { + Void, Scalar { kind: crate::ScalarKind, width: crate::Bytes, @@ -167,7 +166,7 @@ pub struct Writer { } // type alias, for success return of write_expression -type WriteExpressionOutput = (Word, Option); +type WriteExpressionOutput = (Word, LookupType); impl Writer { pub fn new(header: &crate::Header, writer_flags: WriterFlags) -> Self { @@ -485,6 +484,7 @@ impl Writer { ) -> Word { let id = self.generate_id(); let instruction = match local_ty { + LocalType::Void => unreachable!(), LocalType::Scalar { kind, width } => self.write_scalar(id, kind, width), LocalType::Vector { size, kind, width } => { let scalar_id = @@ -903,7 +903,7 @@ impl Writer { function, )?; - let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty.unwrap()); + let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); let (pointer_id, type_id, lookup_ty) = match *base_ty_inner { crate::TypeInner::Vector { kind, width, .. } => { @@ -934,7 +934,7 @@ impl Writer { type_id, load_id, id, None, )); - Ok((load_id, Some(lookup_ty))) + Ok((load_id, lookup_ty)) } crate::Expression::AccessIndex { base, index } => { let id = self.generate_id(); @@ -948,7 +948,7 @@ impl Writer { ) .unwrap(); - let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty.unwrap()); + let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); let (pointer_id, type_id, lookup_ty) = match *base_ty_inner { crate::TypeInner::Vector { kind, width, .. } => { @@ -998,18 +998,18 @@ impl Writer { type_id, load_id, id, None, )); - Ok((load_id, Some(lookup_ty))) + Ok((load_id, lookup_ty)) } crate::Expression::GlobalVariable(handle) => { let var = &ir_module.global_variables[handle]; let id = self.get_global_variable_id(&ir_module, handle); - Ok((id, Some(LookupType::Handle(var.ty)))) + Ok((id, LookupType::Handle(var.ty))) } crate::Expression::Constant(handle) => { let var = &ir_module.constants[handle]; let id = self.get_constant_id(handle, ir_module); - Ok((id, Some(LookupType::Handle(var.ty)))) + Ok((id, LookupType::Handle(var.ty))) } crate::Expression::Compose { ty, ref components } => { let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty)); @@ -1030,7 +1030,7 @@ impl Writer { | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); block.body.push(super::instructions::instruction_load( - self.get_type_id(&ir_module.types, component_local_ty.unwrap()), + self.get_type_id(&ir_module.types, component_local_ty), load_id, component_id, None, @@ -1084,7 +1084,7 @@ impl Writer { _ => unreachable!(), }; - Ok((id, Some(LookupType::Handle(ty)))) + Ok((id, LookupType::Handle(ty))) } crate::Expression::Binary { op, left, right } => { let id = self.generate_id(); @@ -1105,8 +1105,8 @@ impl Writer { function, )?; - let left_lookup_ty = left_lookup_ty.unwrap(); - let right_lookup_ty = right_lookup_ty.unwrap(); + let left_lookup_ty = left_lookup_ty; + let right_lookup_ty = right_lookup_ty; let left_ty_inner = self.get_type_inner(&ir_module.types, left_lookup_ty); let right_ty_inner = self.get_type_inner(&ir_module.types, right_lookup_ty); @@ -1257,7 +1257,7 @@ impl Writer { }; block.body.push(instruction); - Ok((id, Some(lookup_ty))) + Ok((id, lookup_ty)) } crate::Expression::LocalVariable(variable) => { let var = &ir_function.local_variables[variable]; @@ -1265,7 +1265,7 @@ impl Writer { .variables .iter() .find(|&v| v.name.as_ref().unwrap() == var.name.as_ref().unwrap()) - .map(|local_var| (local_var.id, Some(LookupType::Handle(var.ty)))) + .map(|local_var| (local_var.id, LookupType::Handle(var.ty))) .ok_or_else(|| Error::UnknownLocalVariable(var.clone())) } crate::Expression::FunctionArgument(index) => { @@ -1279,7 +1279,7 @@ impl Writer { function.parameters[index as usize].result_id.unwrap(), None, )); - Ok((load_id, Some(LookupType::Handle(handle)))) + Ok((load_id, LookupType::Handle(handle))) } crate::Expression::Call { ref origin, @@ -1304,7 +1304,7 @@ impl Writer { // Store value to variable - OpStore // Use id of variable - let handle = match lookup_ty.unwrap() { + let handle = match lookup_ty { LookupType::Handle(handle) => handle, LookupType::Local(_) => unreachable!(), }; @@ -1345,7 +1345,12 @@ impl Writer { *self.lookup_function.get(&local_function).unwrap(), argument_ids.as_slice(), )); - Ok((id, None)) + + let result_type = match origin_function.return_type { + Some(ty_handle) => LookupType::Handle(ty_handle), + None => LookupType::Local(LocalType::Void), + }; + Ok((id, result_type)) } _ => unimplemented!("{:?}", origin), }, @@ -1366,8 +1371,7 @@ impl Writer { function, )?; - let id = self.generate_id(); - let expr_type_inner = self.get_type_inner(&ir_module.types, expr_type.unwrap()); + let expr_type_inner = self.get_type_inner(&ir_module.types, expr_type); let (expr_kind, local_type) = match *expr_type_inner { crate::TypeInner::Scalar { @@ -1382,21 +1386,42 @@ impl Writer { _ => unreachable!(), }; + let lookup_type = LookupType::Local(local_type); let op = match (expr_kind, kind) { _ if !convert => spirv::Op::Bitcast, (crate::ScalarKind::Float, crate::ScalarKind::Uint) => spirv::Op::ConvertFToU, (crate::ScalarKind::Float, crate::ScalarKind::Sint) => spirv::Op::ConvertFToS, (crate::ScalarKind::Sint, crate::ScalarKind::Float) => spirv::Op::ConvertSToF, (crate::ScalarKind::Uint, crate::ScalarKind::Float) => spirv::Op::ConvertUToF, - _ => unreachable!(), + // We assume it's either an identity cast, or int-uint. + // In both cases no SPIR-V instructions need to be generated. + _ => { + let id = match ir_function.expressions[expr] { + crate::Expression::LocalVariable(_) + | crate::Expression::GlobalVariable(_) => { + let load_id = self.generate_id(); + let kind_type_id = self.get_type_id(&ir_module.types, expr_type); + block.body.push(super::instructions::instruction_load( + kind_type_id, + load_id, + expr_id, + None, + )); + load_id + } + _ => expr_id, + }; + return Ok((id, lookup_type)); + } }; - let kind_type_id = - self.get_type_id(&ir_module.types, LookupType::Local(local_type)); + + let id = self.generate_id(); + let kind_type_id = self.get_type_id(&ir_module.types, lookup_type); let instruction = super::instructions::instruction_unary(op, kind_type_id, id, expr_id); block.body.push(instruction); - Ok((id, None)) + Ok((id, lookup_type)) } crate::Expression::ImageSample { image, @@ -1415,7 +1440,6 @@ impl Writer { function, )?; - let image_lookup_ty = image_lookup_ty.ok_or(Error::EmptyValue)?; let image_result_type_id = self.get_type_id(&ir_module.types, image_lookup_ty); let image_id = match *image_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { @@ -1454,8 +1478,7 @@ impl Writer { function, )?; - let sampler_result_type_id = - self.get_type_id(&ir_module.types, sampler_lookup_ty.unwrap()); + let sampler_result_type_id = self.get_type_id(&ir_module.types, sampler_lookup_ty); let sampler_id = match *sampler_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); @@ -1481,7 +1504,7 @@ impl Writer { )?; let coordinate_result_type_id = - self.get_type_id(&ir_module.types, coordinate_lookup_ty.unwrap()); + self.get_type_id(&ir_module.types, coordinate_lookup_ty); let coordinate_id = match *coordinate_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); @@ -1501,7 +1524,7 @@ impl Writer { let image_sample_result_type = if let crate::TypeInner::Image { class, .. } = image_type.inner { let width = 4; - let local_type = match class { + LookupType::Local(match class { crate::ImageClass::Sampled { kind, multi: _ } => LocalType::Vector { kind, width, @@ -1512,8 +1535,7 @@ impl Writer { width, }, _ => return Err(Error::BadImageClass(class)), - }; - self.get_type_id(&ir_module.types, LookupType::Local(local_type)) + }) } else { return Err(Error::NotImage); }; @@ -1528,15 +1550,17 @@ impl Writer { sampler_id, )); let id = self.generate_id(); + let image_sample_result_type_id = + self.get_type_id(&ir_module.types, image_sample_result_type); block .body .push(super::instructions::instruction_image_sample_implicit_lod( - image_sample_result_type, + image_sample_result_type_id, id, sampled_image_id, coordinate_id, )); - Ok((id, None)) + Ok((id, image_sample_result_type)) } _ => unimplemented!("{:?}", expression), } @@ -1579,8 +1603,7 @@ impl Writer { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); - let value_ty_id = - self.get_type_id(&ir_module.types, lookup_ty.unwrap()); + let value_ty_id = self.get_type_id(&ir_module.types, lookup_ty); block.body.push(super::instructions::instruction_load( value_ty_id, load_id, @@ -1623,8 +1646,7 @@ impl Writer { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); - let value_ty_id = - self.get_type_id(&ir_module.types, value_lookup_ty.unwrap()); + let value_ty_id = self.get_type_id(&ir_module.types, value_lookup_ty); block.body.push(super::instructions::instruction_load( value_ty_id, load_id, From 9d5b66934b5a8434d78553cd4efeb3c4840e7497 Mon Sep 17 00:00:00 2001 From: Capucho Date: Mon, 23 Nov 2020 22:01:57 +0000 Subject: [PATCH 0297/2212] [glsl-out] Refractoring Splitted the backend into two more modules (features, errors) Added a shorthand type for the backend Result Reorganized function ordering Moved from using a struct to write image dimension to a function Started documenting the backend --- src/back/glsl/error.rs | 44 ++ src/back/glsl/features.rs | 284 ++++++++ src/back/{glsl.rs => glsl/mod.rs} | 1003 ++++++++++++++--------------- 3 files changed, 803 insertions(+), 528 deletions(-) create mode 100644 src/back/glsl/error.rs create mode 100644 src/back/glsl/features.rs rename src/back/{glsl.rs => glsl/mod.rs} (69%) diff --git a/src/back/glsl/error.rs b/src/back/glsl/error.rs new file mode 100644 index 000000000..7edea5006 --- /dev/null +++ b/src/back/glsl/error.rs @@ -0,0 +1,44 @@ +use crate::proc::ResolveError; +use std::{ + fmt::{self, Error as FmtError}, + io::Error as IoError, +}; + +pub type BackendResult = std::result::Result<(), Error>; + +#[derive(Debug)] +pub enum Error { + FormatError(FmtError), + IoError(IoError), + Type(ResolveError), + Custom(String), +} + +impl From for Error { + fn from(err: FmtError) -> Self { + Error::FormatError(err) + } +} + +impl From for Error { + fn from(err: IoError) -> Self { + Error::IoError(err) + } +} + +impl From for Error { + fn from(err: ResolveError) -> Self { + Error::Type(err) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::FormatError(err) => write!(f, "Formatting error {}", err), + Error::IoError(err) => write!(f, "Io error: {}", err), + Error::Type(err) => write!(f, "Type error: {:?}", err), + Error::Custom(err) => write!(f, "{}", err), + } + } +} diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs new file mode 100644 index 000000000..3e7f33264 --- /dev/null +++ b/src/back/glsl/features.rs @@ -0,0 +1,284 @@ +use super::{ + error::{BackendResult, Error}, + Version, Writer, +}; +use crate::{ + Bytes, ImageClass, ImageDimension, ScalarKind, ShaderStage, StorageClass, StorageFormat, + TypeInner, +}; +use std::io::Write; + +bitflags::bitflags! { + pub struct Features: u32 { + const BUFFER_STORAGE = 1; + const ARRAY_OF_ARRAYS = 1 << 1; + const DOUBLE_TYPE = 1 << 2; + const FULL_IMAGE_FORMATS = 1 << 3; + const MULTISAMPLED_TEXTURES = 1 << 4; + const MULTISAMPLED_TEXTURE_ARRAYS = 1 << 5; + const CUBE_TEXTURES_ARRAY = 1 << 6; + const COMPUTE_SHADER = 1 << 7; + const IMAGE_LOAD_STORE = 1 << 8; + const CONSERVATIVE_DEPTH = 1 << 9; + const TEXTURE_1D = 1 << 10; + const PUSH_CONSTANT = 1 << 11; + } +} + +pub struct FeaturesManager(Features); + +impl FeaturesManager { + pub fn new() -> Self { + Self(Features::empty()) + } + + pub fn request(&mut self, features: Features) { + self.0 |= features + } + + #[allow(clippy::collapsible_if)] + pub fn write(&self, version: Version, mut out: impl Write) -> BackendResult { + if self.0.contains(Features::COMPUTE_SHADER) { + if version < Version::Embedded(310) || version < Version::Desktop(420) { + return Err(Error::Custom(format!( + "Version {} doesn't support compute shaders", + version + ))); + } + + if !version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_compute_shader.txt + writeln!(out, "#extension GL_ARB_compute_shader : require")?; + } + } + + if self.0.contains(Features::BUFFER_STORAGE) { + if version < Version::Embedded(310) || version < Version::Desktop(400) { + return Err(Error::Custom(format!( + "Version {} doesn't support buffer storage class", + version + ))); + } + + if let Version::Desktop(_) = version { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_storage_buffer_object.txt + writeln!( + out, + "#extension GL_ARB_shader_storage_buffer_object : require" + )?; + } + } + + if self.0.contains(Features::DOUBLE_TYPE) { + if version.is_es() || version < Version::Desktop(150) { + return Err(Error::Custom(format!( + "Version {} doesn't support doubles", + version + ))); + } + + if version < Version::Desktop(400) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_gpu_shader_fp64.txt + writeln!(out, "#extension GL_ARB_gpu_shader_fp64 : require")?; + } + } + + if self.0.contains(Features::CUBE_TEXTURES_ARRAY) { + if version < Version::Embedded(310) || version < Version::Desktop(130) { + return Err(Error::Custom(format!( + "Version {} doesn't support cube map array textures", + version + ))); + } + + if version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_cube_map_array.txt + writeln!(out, "#extension GL_EXT_texture_cube_map_array : require")?; + } else if version < Version::Desktop(400) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_cube_map_array.txt + writeln!(out, "#extension GL_ARB_texture_cube_map_array : require")?; + } + } + + if self.0.contains(Features::MULTISAMPLED_TEXTURES) { + if version < Version::Embedded(300) { + return Err(Error::Custom(format!( + "Version {} doesn't support multi sampled textures", + version + ))); + } + } + + if self.0.contains(Features::MULTISAMPLED_TEXTURE_ARRAYS) { + if version < Version::Embedded(310) { + return Err(Error::Custom(format!( + "Version {} doesn't support multi sampled texture arrays", + version + ))); + } + + if version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/OES/OES_texture_storage_multisample_2d_array.txt + writeln!( + out, + "#extension GL_OES_texture_storage_multisample_2d_array : require" + )?; + } + } + + if self.0.contains(Features::ARRAY_OF_ARRAYS) { + if version < Version::Embedded(310) || version < Version::Desktop(120) { + return Err(Error::Custom(format!( + "Version {} doesn't arrays of arrays", + version + ))); + } + + if version < Version::Desktop(430) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_arrays_of_arrays.txt + writeln!(out, "#extension ARB_arrays_of_arrays : require")?; + } + } + + if self.0.contains(Features::IMAGE_LOAD_STORE) { + if version < Version::Embedded(310) || version < Version::Desktop(130) { + return Err(Error::Custom(format!( + "Version {} doesn't support images load/stores", + version + ))); + } + + if self.0.contains(Features::FULL_IMAGE_FORMATS) && version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/NV/NV_image_formats.txt + writeln!(out, "#extension GL_NV_image_formats : require")?; + } + + if version < Version::Desktop(420) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_image_load_store.txt + writeln!(out, "#extension GL_ARB_shader_image_load_store : require")?; + } + } + + if self.0.contains(Features::CONSERVATIVE_DEPTH) { + if version < Version::Embedded(300) || version < Version::Desktop(130) { + return Err(Error::Custom(format!( + "Version {} doesn't support conservative depth", + version + ))); + } + + if version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_conservative_depth.txt + writeln!(out, "#extension GL_EXT_conservative_depth : require")?; + } + + if version < Version::Desktop(420) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_conservative_depth.txt + writeln!(out, "#extension GL_ARB_conservative_depth : require")?; + } + } + + if self.0.contains(Features::TEXTURE_1D) { + if version.is_es() { + return Err(Error::Custom(format!( + "Version {} doesn't support 1d textures", + version + ))); + } + } + + Ok(()) + } +} + +impl<'a, W> Writer<'a, W> { + pub(super) fn collect_required_features(&mut self) { + let stage = self.options.entry_point.0; + + if let Some(depth_test) = self.entry_point.early_depth_test { + self.features.request(Features::IMAGE_LOAD_STORE); + + if depth_test.conservative.is_some() { + self.features.request(Features::CONSERVATIVE_DEPTH); + } + } + + if let ShaderStage::Compute = stage { + self.features.request(Features::COMPUTE_SHADER) + } + + for (_, ty) in self.module.types.iter() { + match ty.inner { + TypeInner::Scalar { kind, width } => self.scalar_required_features(kind, width), + TypeInner::Vector { kind, width, .. } => self.scalar_required_features(kind, width), + TypeInner::Matrix { .. } => self.scalar_required_features(ScalarKind::Float, 8), + TypeInner::Array { base, .. } => { + if let TypeInner::Array { .. } = self.module.types[base].inner { + self.features.request(Features::ARRAY_OF_ARRAYS) + } + } + TypeInner::Image { + dim, + arrayed, + class, + } => { + if arrayed && dim == ImageDimension::Cube { + self.features.request(Features::CUBE_TEXTURES_ARRAY) + } else if dim == ImageDimension::D1 { + self.features.request(Features::TEXTURE_1D) + } + + match class { + ImageClass::Sampled { multi: true, .. } => { + self.features.request(Features::MULTISAMPLED_TEXTURES); + if arrayed { + self.features.request(Features::MULTISAMPLED_TEXTURE_ARRAYS); + } + } + ImageClass::Storage(format) => match format { + StorageFormat::R8Unorm + | StorageFormat::R8Snorm + | StorageFormat::R8Uint + | StorageFormat::R8Sint + | StorageFormat::R16Uint + | StorageFormat::R16Sint + | StorageFormat::R16Float + | StorageFormat::Rg8Unorm + | StorageFormat::Rg8Snorm + | StorageFormat::Rg8Uint + | StorageFormat::Rg8Sint + | StorageFormat::Rg16Uint + | StorageFormat::Rg16Sint + | StorageFormat::Rg16Float + | StorageFormat::Rgb10a2Unorm + | StorageFormat::Rg11b10Float + | StorageFormat::Rg32Uint + | StorageFormat::Rg32Sint + | StorageFormat::Rg32Float => { + self.features.request(Features::FULL_IMAGE_FORMATS) + } + _ => {} + }, + _ => {} + } + } + _ => {} + } + } + + for (_, global) in self.module.global_variables.iter() { + match global.class { + StorageClass::WorkGroup => self.features.request(Features::COMPUTE_SHADER), + StorageClass::Storage => self.features.request(Features::BUFFER_STORAGE), + StorageClass::PushConstant => self.features.request(Features::PUSH_CONSTANT), + _ => {} + } + } + } + + fn scalar_required_features(&mut self, kind: ScalarKind, width: Bytes) { + if kind == ScalarKind::Float && width == 8 { + self.features.request(Features::DOUBLE_TYPE); + } + } +} diff --git a/src/back/glsl.rs b/src/back/glsl/mod.rs similarity index 69% rename from src/back/glsl.rs rename to src/back/glsl/mod.rs index 6a497a675..cf4a5b5ea 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl/mod.rs @@ -18,10 +18,12 @@ //! - 310 //! +pub use error::Error; +pub use features::Features; + use crate::{ proc::{ - CallGraph, CallGraphBuilder, Interface, NameKey, Namer, ResolveContext, ResolveError, - Typifier, Visitor, + CallGraph, CallGraphBuilder, Interface, NameKey, Namer, ResolveContext, Typifier, Visitor, }, Arena, ArraySize, BinaryOperator, BuiltIn, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, @@ -29,62 +31,33 @@ use crate::{ Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, UnaryOperator, }; -use std::{ - cmp::Ordering, - fmt::{self, Error as FmtError}, - io::{Error as IoError, Write}, -}; +use error::BackendResult; +use features::FeaturesManager; +use std::{cmp::Ordering, fmt, io::Write}; +/// Contains the backend error enum and a shorthand Result type +mod error; +/// Contains the features related code and the features querying method +mod features; /// Contains a constant with a slice of all the reserved keywords RESERVED_KEYWORDS mod keywords; +/// List of supported core glsl versions const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; +/// List of supported es glsl versions const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310]; -#[derive(Debug)] -pub enum Error { - FormatError(FmtError), - IoError(IoError), - Type(ResolveError), - Custom(String), -} - -impl From for Error { - fn from(err: FmtError) -> Self { - Error::FormatError(err) - } -} - -impl From for Error { - fn from(err: IoError) -> Self { - Error::IoError(err) - } -} - -impl From for Error { - fn from(err: ResolveError) -> Self { - Error::Type(err) - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::FormatError(err) => write!(f, "Formatting error {}", err), - Error::IoError(err) => write!(f, "Io error: {}", err), - Error::Type(err) => write!(f, "Type error: {:?}", err), - Error::Custom(err) => write!(f, "{}", err), - } - } -} - +/// glsl version #[derive(Debug, Copy, Clone, PartialEq)] pub enum Version { + /// `core` glsl Desktop(u16), + /// `es` glsl Embedded(u16), } impl Version { + /// Returns true if self is `Version::Embedded` (i.e. is a es version) fn is_es(&self) -> bool { match self { Version::Desktop(_) => false, @@ -92,6 +65,12 @@ impl Version { } } + /// Checks the list of currently supported versions and returns true if it contains the + /// specified version + /// + /// # Notes + /// As an invalid version number will never be added to the supported version list + /// so this also checks for verson validity fn is_supported(&self) -> bool { match self { Version::Desktop(v) => SUPPORTED_CORE_VERSIONS.contains(v), @@ -119,213 +98,57 @@ impl fmt::Display for Version { } } +/// Structure that contains the configuration used in the [`Writer`](struct.Writer.html) #[derive(Debug, Clone)] pub struct Options { + /// The glsl version to be used pub version: Version, + /// The name and stage of the entry point + /// + /// If no enty point that matches is found a error will be thrown while creating a new instance + /// of [`Writer`](struct.Writer.html) pub entry_point: (ShaderStage, String), } +/// Structure that connects a texture to a sampler or not +/// +/// glsl pre vulkan has no concept of separate textures and samplers instead everything is a +/// `gsamplerN` where `g` is the scalar type and `N` is the dimension, but naga uses separate textures +/// and samplers in the IR so the backend produces a [`HashMap`](crate::FastHashMap) with the texture name +/// as a key and a [`TextureMapping`](TextureMapping) as a value this way the user knows where to bind. +/// +/// [`Storage`](crate::ImageClass::Storage) images produce `gimageN` and don't have an associated sampler +/// so the [`sampler`](Self::sampler) field will be [`None`](std::option::Option::None) #[derive(Debug, Clone)] pub struct TextureMapping { + /// Handle to the image global variable pub texture: Handle, + /// Handle to the associated sampler global variable if it exists pub sampler: Option>, } -bitflags::bitflags! { - struct Features: u32 { - const BUFFER_STORAGE = 1; - const ARRAY_OF_ARRAYS = 1 << 1; - const DOUBLE_TYPE = 1 << 2; - const FULL_IMAGE_FORMATS = 1 << 3; - const MULTISAMPLED_TEXTURES = 1 << 4; - const MULTISAMPLED_TEXTURE_ARRAYS = 1 << 5; - const CUBE_TEXTURES_ARRAY = 1 << 6; - const COMPUTE_SHADER = 1 << 7; - const IMAGE_LOAD_STORE = 1 << 8; - const CONSERVATIVE_DEPTH = 1 << 9; - const TEXTURE_1D = 1 << 10; - const PUSH_CONSTANT = 1 << 11; - } -} - -struct FeaturesManager(Features); - -impl FeaturesManager { - pub fn new() -> Self { - Self(Features::empty()) - } - - pub fn request(&mut self, features: Features) { - self.0 |= features - } - - #[allow(clippy::collapsible_if)] - pub fn write(&self, version: Version, mut out: impl Write) -> Result<(), Error> { - if self.0.contains(Features::COMPUTE_SHADER) { - if version < Version::Embedded(310) || version < Version::Desktop(420) { - return Err(Error::Custom(format!( - "Version {} doesn't support compute shaders", - version - ))); - } - - if !version.is_es() { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_compute_shader.txt - writeln!(out, "#extension GL_ARB_compute_shader : require")?; - } - } - - if self.0.contains(Features::BUFFER_STORAGE) { - if version < Version::Embedded(310) || version < Version::Desktop(400) { - return Err(Error::Custom(format!( - "Version {} doesn't support buffer storage class", - version - ))); - } - - if let Version::Desktop(_) = version { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_storage_buffer_object.txt - writeln!( - out, - "#extension GL_ARB_shader_storage_buffer_object : require" - )?; - } - } - - if self.0.contains(Features::DOUBLE_TYPE) { - if version.is_es() || version < Version::Desktop(150) { - return Err(Error::Custom(format!( - "Version {} doesn't support doubles", - version - ))); - } - - if version < Version::Desktop(400) { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_gpu_shader_fp64.txt - writeln!(out, "#extension GL_ARB_gpu_shader_fp64 : require")?; - } - } - - if self.0.contains(Features::CUBE_TEXTURES_ARRAY) { - if version < Version::Embedded(310) || version < Version::Desktop(130) { - return Err(Error::Custom(format!( - "Version {} doesn't support cube map array textures", - version - ))); - } - - if version.is_es() { - // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_cube_map_array.txt - writeln!(out, "#extension GL_EXT_texture_cube_map_array : require")?; - } else if version < Version::Desktop(400) { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_cube_map_array.txt - writeln!(out, "#extension GL_ARB_texture_cube_map_array : require")?; - } - } - - if self.0.contains(Features::MULTISAMPLED_TEXTURES) { - if version < Version::Embedded(300) { - return Err(Error::Custom(format!( - "Version {} doesn't support multi sampled textures", - version - ))); - } - } - - if self.0.contains(Features::MULTISAMPLED_TEXTURE_ARRAYS) { - if version < Version::Embedded(310) { - return Err(Error::Custom(format!( - "Version {} doesn't support multi sampled texture arrays", - version - ))); - } - - if version.is_es() { - // https://www.khronos.org/registry/OpenGL/extensions/OES/OES_texture_storage_multisample_2d_array.txt - writeln!( - out, - "#extension GL_OES_texture_storage_multisample_2d_array : require" - )?; - } - } - - if self.0.contains(Features::ARRAY_OF_ARRAYS) { - if version < Version::Embedded(310) || version < Version::Desktop(120) { - return Err(Error::Custom(format!( - "Version {} doesn't arrays of arrays", - version - ))); - } - - if version < Version::Desktop(430) { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_arrays_of_arrays.txt - writeln!(out, "#extension ARB_arrays_of_arrays : require")?; - } - } - - if self.0.contains(Features::IMAGE_LOAD_STORE) { - if version < Version::Embedded(310) || version < Version::Desktop(130) { - return Err(Error::Custom(format!( - "Version {} doesn't support images load/stores", - version - ))); - } - - if self.0.contains(Features::FULL_IMAGE_FORMATS) && version.is_es() { - // https://www.khronos.org/registry/OpenGL/extensions/NV/NV_image_formats.txt - writeln!(out, "#extension GL_NV_image_formats : require")?; - } - - if version < Version::Desktop(420) { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_image_load_store.txt - writeln!(out, "#extension GL_ARB_shader_image_load_store : require")?; - } - } - - if self.0.contains(Features::CONSERVATIVE_DEPTH) { - if version < Version::Embedded(300) || version < Version::Desktop(130) { - return Err(Error::Custom(format!( - "Version {} doesn't support conservative depth", - version - ))); - } - - if version.is_es() { - // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_conservative_depth.txt - writeln!(out, "#extension GL_EXT_conservative_depth : require")?; - } - - if version < Version::Desktop(420) { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_conservative_depth.txt - writeln!(out, "#extension GL_ARB_conservative_depth : require")?; - } - } - - if self.0.contains(Features::TEXTURE_1D) { - if version.is_es() { - return Err(Error::Custom(format!( - "Version {} doesn't support 1d textures", - version - ))); - } - } - - Ok(()) - } -} - +/// Stores the current function type (either a regular function or an entry point) +/// +/// Also stores data needed to identify it (handle for a regular function or index for an entry point) enum FunctionType { + /// A regular function and it's handle Function(Handle), + /// A entry point and it's index EntryPoint(crate::proc::EntryPointIndex), } +/// Helper structure that stores data needed when writing the function struct FunctionCtx<'a, 'b> { + /// The current function being written func: FunctionType, + /// The expression arena of the current function being written expressions: &'a Arena, + /// A typifier that has already resolved all expressions in the function being written typifier: &'b Typifier, } impl<'a, 'b> FunctionCtx<'a, 'b> { + /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function fn name_key(&self, local: Handle) -> NameKey { match self.func { FunctionType::Function(handle) => NameKey::FunctionLocal(handle, local), @@ -333,6 +156,12 @@ impl<'a, 'b> FunctionCtx<'a, 'b> { } } + /// Helper method that retrieves the name of the argument in the current function + /// + /// # Panics + /// - If the function is an entry point + /// - If the function arguments are less or equal to `arg` + /// - If `names` hasn't been filled properly fn get_arg<'c>(&self, arg: u32, names: &'c FastHashMap) -> &'c str { match self.func { FunctionType::Function(handle) => &names[&NameKey::FunctionArgument(handle, arg)], @@ -346,7 +175,9 @@ impl<'a, 'b> FunctionCtx<'a, 'b> { struct IdGenerator(u32); impl IdGenerator { + /// Generates a number that's guaranteed to be unique for this `IdGenerator` fn generate(&mut self) -> u32 { + // It's just an increasing number but it does the job let ret = self.0; self.0 += 1; ret @@ -356,23 +187,37 @@ impl IdGenerator { /// Main structure of the glsl backend responsible for all code generation pub struct Writer<'a, W> { // Inputs + /// The module being written module: &'a Module, + /// The output writer out: W, + /// User defined configuration to be used options: &'a Options, // Internal State + /// Features manager used to store all the needed features and write them features: FeaturesManager, + /// A map with all the names needed for writing the module + /// (generated by a [`Namer`](crate::proc::Namer)) names: FastHashMap, + /// The selected entry point entry_point: &'a crate::EntryPoint, + /// The index of the selected entry point entry_point_idx: crate::proc::EntryPointIndex, + /// The current entry point call_graph (doesn't contain the entry point) call_graph: CallGraph, - /// Used to generate a unique number for blocks block_id: IdGenerator, } impl<'a, W: Write> Writer<'a, W> { + /// Creates a new [`Writer`](Writer) instance + /// + /// # Errors + /// - If the version specified isn't supported (or invalid) + /// - If the entry point couldn't be found on the module pub fn new(out: W, module: &'a Module, options: &'a Options) -> Result { + // Check if the requested version is supported if !options.version.is_supported() { return Err(Error::Custom(format!( "Version not supported {}", @@ -380,6 +225,7 @@ impl<'a, W: Write> Writer<'a, W> { ))); } + // Try to find the entry point and correspoding index let (ep_idx, ep) = module .entry_points .iter() @@ -389,14 +235,17 @@ impl<'a, W: Write> Writer<'a, W> { }) .ok_or_else(|| Error::Custom(String::from("Entry point not found")))?; + // Generate a map with names required to write the module let mut names = FastHashMap::default(); Namer::process(module, keywords::RESERVED_KEYWORDS, &mut names); + // Generate a call graph for the entry point let call_graph = CallGraphBuilder { functions: &module.functions, } .process(&ep.function); + // Build the instance let mut this = Self { module, out, @@ -411,121 +260,48 @@ impl<'a, W: Write> Writer<'a, W> { block_id: IdGenerator::default(), }; - this.collect_required_features()?; + // Find all features required to print this module + // TODO: We should throw errors here and not in `write` + this.collect_required_features(); Ok(this) } - fn collect_required_features(&mut self) -> Result<(), Error> { - let stage = self.options.entry_point.0; - - if let Some(depth_test) = self.entry_point.early_depth_test { - self.features.request(Features::IMAGE_LOAD_STORE); - - if depth_test.conservative.is_some() { - self.features.request(Features::CONSERVATIVE_DEPTH); - } - } - - if let ShaderStage::Compute = stage { - self.features.request(Features::COMPUTE_SHADER) - } - - for (_, ty) in self.module.types.iter() { - match ty.inner { - TypeInner::Scalar { kind, width } => self.scalar_required_features(kind, width), - TypeInner::Vector { kind, width, .. } => self.scalar_required_features(kind, width), - TypeInner::Matrix { .. } => self.scalar_required_features(ScalarKind::Float, 8), - TypeInner::Array { base, .. } => { - if let TypeInner::Array { .. } = self.module.types[base].inner { - self.features.request(Features::ARRAY_OF_ARRAYS) - } - } - TypeInner::Image { - dim, - arrayed, - class, - } => { - if arrayed && dim == crate::ImageDimension::Cube { - self.features.request(Features::CUBE_TEXTURES_ARRAY) - } else if dim == crate::ImageDimension::D1 { - self.features.request(Features::TEXTURE_1D) - } - - match class { - ImageClass::Sampled { multi: true, .. } => { - self.features.request(Features::MULTISAMPLED_TEXTURES); - if arrayed { - self.features.request(Features::MULTISAMPLED_TEXTURE_ARRAYS); - } - } - ImageClass::Storage(format) => match format { - StorageFormat::R8Unorm - | StorageFormat::R8Snorm - | StorageFormat::R8Uint - | StorageFormat::R8Sint - | StorageFormat::R16Uint - | StorageFormat::R16Sint - | StorageFormat::R16Float - | StorageFormat::Rg8Unorm - | StorageFormat::Rg8Snorm - | StorageFormat::Rg8Uint - | StorageFormat::Rg8Sint - | StorageFormat::Rg16Uint - | StorageFormat::Rg16Sint - | StorageFormat::Rg16Float - | StorageFormat::Rgb10a2Unorm - | StorageFormat::Rg11b10Float - | StorageFormat::Rg32Uint - | StorageFormat::Rg32Sint - | StorageFormat::Rg32Float => { - self.features.request(Features::FULL_IMAGE_FORMATS) - } - _ => {} - }, - _ => {} - } - } - _ => {} - } - } - - for (_, global) in self.module.global_variables.iter() { - match global.class { - StorageClass::WorkGroup => self.features.request(Features::COMPUTE_SHADER), - StorageClass::Storage => self.features.request(Features::BUFFER_STORAGE), - StorageClass::PushConstant => self.features.request(Features::PUSH_CONSTANT), - _ => {} - } - } - - Ok(()) - } - - fn scalar_required_features(&mut self, kind: ScalarKind, width: crate::Bytes) { - if kind == ScalarKind::Float && width == 8 { - self.features.request(Features::DOUBLE_TYPE); - } - } - + /// Writes the [`Module`](crate::Module) as glsl to the output + /// + /// # Notes + /// If an error occurs while writing, the output might have been written partially pub fn write(&mut self) -> Result, Error> { + // We use `writeln!(self.out)` troughout the write to add newlines + // to make the output more readable + let es = self.options.version.is_es(); + // Write the version (It must be the first thing or it isn't a valid glsl output) writeln!(self.out, "#version {}", self.options.version)?; + // Write all the needed extensions + // + // This used to be the last thing being written as it allowed to search for features while + // writing the module saving some loops but some older versions (420 or less) required the + // extensions to appear before being used, even though extensions are part of the + // preprocessor not the processor ¯\_(ツ)_/¯ self.features.write(self.options.version, &mut self.out)?; writeln!(self.out)?; + // glsl es requires a precision to be specified for floats + // TODO: Should this be user configurable? if es { writeln!(self.out, "precision highp float;\n")?; } + // Enable early depth tests if needed if let Some(depth_test) = self.entry_point.early_depth_test { - writeln!(self.out, "layout(early_fragment_tests) in;\n")?; + writeln!(self.out, "layout(early_fragment_tests) in;")?; if let Some(conservative) = depth_test.conservative { writeln!( self.out, - "layout (depth_{}) out float gl_FragDepth;\n", + "layout (depth_{}) out float gl_FragDepth;", match conservative { ConservativeDepth::GreaterEqual => "greater", ConservativeDepth::LessEqual => "less", @@ -535,6 +311,12 @@ impl<'a, W: Write> Writer<'a, W> { } } + writeln!(self.out)?; + + // Write all structs + // + // This are always ordered because of the IR is structured in a way that you can't make a + // struct without adding all of it's members first for (handle, ty) in self.module.types.iter() { if let TypeInner::Struct { ref members } = ty.inner { self.write_struct(handle, members)? @@ -543,14 +325,11 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out)?; - let texture_mappings = self.collect_texture_mapping( - self.call_graph - .raw_nodes() - .iter() - .map(|node| &self.module.functions[node.weight]) - .chain(std::iter::once(&self.entry_point.function)), - )?; - + // Write the globals + // + // We filter all globals that aren't used by the selected entry point as they might be + // interfere with each other (i.e. two globals with the same location but different with + // different classes) for (handle, global) in self .module .global_variables @@ -558,16 +337,21 @@ impl<'a, W: Write> Writer<'a, W> { .zip(&self.entry_point.function.global_usage) .filter_map(|(global, usage)| Some(global).filter(|_| !usage.is_empty())) { + // Skip builtins + // TODO: Write them if they have modifiers if let Some(crate::Binding::BuiltIn(_)) = global.binding { continue; } match self.module.types[global.ty].inner { + // We treat images separately because they might require + // writing the storage format TypeInner::Image { dim, arrayed, class, } => { + // Write the storage format if needed if let TypeInner::Image { class: ImageClass::Storage(format), .. @@ -576,23 +360,38 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "layout({}) ", glsl_storage_format(format))?; } + // Write the storage access modifier + // + // glsl allows adding both `readonly` and `writeonly` but this means that + // they can only be used to query information about the image which isn't what + // we want here so when storage access is both `LOAD` and `STORE` add no modifiers if global.storage_access == StorageAccess::LOAD { write!(self.out, "readonly ")?; } else if global.storage_access == StorageAccess::STORE { write!(self.out, "writeonly ")?; } + // All images in glsl are `uniform` + // The trailing space is important write!(self.out, "uniform ")?; + // write the type + // + // This is way we need the leading space because `write_image_type` doesn't add + // any spaces at the beginning or end self.write_image_type(dim, arrayed, class)?; + // Finally write the name and end the global with a `;` + // The leading space is important writeln!( self.out, " {};", self.names[&NameKey::GlobalVariable(handle)] )? } + // glsl has no concept of samplers so we just ignore it TypeInner::Sampler { .. } => continue, + // All other globals are written by `write_global` _ => self.write_global(handle, global)?, } } @@ -603,14 +402,22 @@ impl<'a, W: Write> Writer<'a, W> { // It's impossible for this to panic because the IR forbids cycles let functions = petgraph::algo::toposort(&self.call_graph, None).unwrap(); + // Write all regular functions that are in the call graph this is important + // because other functions might require for example globals that weren't written for node in functions { + // We do this inside the loop instead of using `map` to sastify the borrow checker let handle = self.call_graph[node]; + // We also `clone` to sastify the borrow checker let name = self.names[&NameKey::Function(handle)].clone(); + + // Write the function self.write_function( FunctionType::Function(handle), &self.module.functions[handle], name, )?; + + writeln!(self.out)?; } self.write_function( @@ -619,20 +426,197 @@ impl<'a, W: Write> Writer<'a, W> { "main", )?; - Ok(texture_mappings) + // Collect all of the texture mappings and return them to the user + self.collect_texture_mapping( + // Create an iterator with all functions in the call graph and the entry point + self.call_graph + .raw_nodes() + .iter() + .map(|node| &self.module.functions[node.weight]) + .chain(std::iter::once(&self.entry_point.function)), + ) } + /// Helper method used to write non image/sampler types + /// + /// # Notes + /// Adds no trailing or leading whitespaces + /// + /// # Panics + /// - If type is either a image or sampler + /// - If it's an Array with a [`ArraySize::Constant`](crate::ArraySize::Constant) with a + /// constant that isn't [`Uint`](crate::ConstantInner::Uint) + fn write_type(&mut self, ty: Handle, block: bool) -> BackendResult { + match self.module.types[ty].inner { + // Scalars are simple we just get the full name from `glsl_scalar` + TypeInner::Scalar { kind, width } => { + write!(self.out, "{}", glsl_scalar(kind, width)?.full)? + } + // Vectors are just `gvecN` where `g` is the scalar prefix and `N` is the vector size + TypeInner::Vector { size, kind, width } => write!( + self.out, + "{}vec{}", + glsl_scalar(kind, width)?.prefix, + size as u8 + )?, + // Matrices are written with `gmatMxN` where `g` is the scalar prefix (only floats and + // doubles are allowed), `M` is the columns count and `N` is the rows count + // + // glsl supports a matrix shorthand `gmatN` where `N` = `M` but it doesn't justify the + // extra branch to write matrices this way + TypeInner::Matrix { + columns, + rows, + width, + } => write!( + self.out, + "{}mat{}x{}", + glsl_scalar(ScalarKind::Float, width)?.prefix, + columns as u8, + rows as u8 + )?, + // glsl has no pointer types so just write types as normal and loads are skipped + TypeInner::Pointer { base, .. } => self.write_type(base, false)?, + // Arrays are written as `base[size]` + TypeInner::Array { base, size, .. } => { + self.write_type(base, false)?; + + write!(self.out, "[")?; + + // Write the array size + // Writes nothing if `ArraySize::Dynamic` + // Panics if `ArraySize::Constant` has a constant that isn't an uint + match size { + ArraySize::Constant(const_handle) => { + match self.module.constants[const_handle].inner { + ConstantInner::Uint(size) => write!(self.out, "{}", size)?, + _ => unreachable!(), + } + } + ArraySize::Dynamic => (), + } + + write!(self.out, "]")? + } + // glsl structs are written as just the struct name if it isn't a block + // + // If it's a block we need to write `block_name { members }` where `block_name` must be + // unique between blocks and structs so we add `_block_ID` where `ID` is a `IdGenerator` + // generated number so it's unique and `members` are the same as in a struct + TypeInner::Struct { ref members } => { + // Get the struct name + let name = &self.names[&NameKey::Type(ty)]; + + if block { + // Write the block name, it's just the struct name appended with `_block_ID` + writeln!(self.out, "{}_block_{} {{", name, self.block_id.generate())?; + + // Write the block members + for (idx, member) in members.iter().enumerate() { + // Add a tab for identation (readability only) + writeln!(self.out, "\t")?; + // Write the member type + self.write_type(member.ty, false)?; + + // Finish the member with the name, a semicolon and a newline + // The leading space is important + writeln!( + self.out, + " {};", + &self.names[&NameKey::StructMember(ty, idx as u32)] + )?; + } + + // Close braces + write!(self.out, "}}")? + } else { + // Write the struct name + write!(self.out, "{}", name)? + } + } + // Panic if either Image or Sampler is being written + // + // Write all variants instead of `_` so that if new variants are added a + // no exhaustivenes error is thrown + TypeInner::Image { .. } | TypeInner::Sampler { .. } => unreachable!(), + } + + Ok(()) + } + + /// Helper method to write a image type + /// + /// # Notes + /// Adds no leading or trailing whitespaces + fn write_image_type( + &mut self, + dim: crate::ImageDimension, + arrayed: bool, + class: ImageClass, + ) -> BackendResult { + // glsl images consist of four parts the scalar prefix, the image "type", the dimensions + // and modifiers + // + // There exists two image types + // - sampler - for sampled images + // - image - for storage images + // + // There are three possible modifiers that can be used together and must be written in + // this order to be valid + // - MS - used if it's a multisampled image + // - Array - used if it's an image array + // - Shadow - used if it's a depth image + + let (base, kind, ms, comparison) = match class { + ImageClass::Sampled { kind, multi: true } => ("sampler", kind, "MS", ""), + ImageClass::Sampled { kind, multi: false } => ("sampler", kind, "", ""), + ImageClass::Depth => ("sampler", crate::ScalarKind::Float, "", "Shadow"), + ImageClass::Storage(format) => ("image", format.into(), "", ""), + }; + + write!( + self.out, + "{}{}{}{}{}{}", + glsl_scalar(kind, 4)?.prefix, + base, + glsl_dimension(dim), + ms, + if arrayed { "Array" } else { "" }, + comparison + )?; + + Ok(()) + } + + /// Helper method used to write non images/sampler globals + /// + /// # Notes + /// Adds a newline + /// + /// # Panics + /// If the global has type sampler fn write_global( &mut self, handle: Handle, global: &GlobalVariable, - ) -> Result<(), Error> { + ) -> BackendResult { + // Write the storage access modifier + // + // glsl allows adding both `readonly` and `writeonly` but this means that + // they can only be used to query information about the resource which isn't what + // we want here so when storage access is both `LOAD` and `STORE` add no modifiers if global.storage_access == StorageAccess::LOAD { write!(self.out, "readonly ")?; } else if global.storage_access == StorageAccess::STORE { write!(self.out, "writeonly ")?; } + // Write the interpolation modifier if needed + // + // We ignore all interpolation modifiers that aren't used in input globals in fragment + // shaders or output globals in vertex shaders + // + // TODO: Should this throw an error? if let Some(interpolation) = global.interpolation { match (self.options.entry_point.0, global.class) { (ShaderStage::Fragment, StorageClass::Input) @@ -643,33 +627,41 @@ impl<'a, W: Write> Writer<'a, W> { }; } + // glsl doesn't allow structures as types in `buffer` and `uniform` instead blocks must be + // used so we set block to true in `write_type` let block = match global.class { - StorageClass::Storage | StorageClass::Uniform => { - let block_name = self.names[&NameKey::Type(global.ty)].clone(); - - Some(block_name) - } - _ => None, + StorageClass::Storage | StorageClass::Uniform => true, + _ => false, }; + // Write the storage class + // Trailing space is important write!(self.out, "{} ", glsl_storage_class(global.class))?; + // Write the type + // `write_type` adds no leading or trailing spaces self.write_type(global.ty, block)?; + // Finally write the global name and end the global with a `;` and a newline + // Leading space is important let name = &self.names[&NameKey::GlobalVariable(handle)]; writeln!(self.out, " {};", name)?; Ok(()) } + /// Helper method used to write functions (both entry points and regular functions) + /// + /// # Notes + /// Adds a newline fn write_function>( &mut self, ty: FunctionType, func: &Function, name: N, - ) -> Result<(), Error> { + ) -> BackendResult { + // Create a new typifier and resolve all types for the current function let mut typifier = Typifier::new(); - typifier.resolve_all( &func.expressions, &self.module.types, @@ -682,211 +674,169 @@ impl<'a, W: Write> Writer<'a, W> { }, )?; + // Create a function context for the function being written let ctx = FunctionCtx { func: ty, expressions: &func.expressions, typifier: &typifier, }; - self.write_fn_header(name.as_ref(), func, &ctx)?; - writeln!(self.out, " {{",)?; + // Write the function header + // + // glsl headers are the same as in c: + // `ret_type name(args)` + // `ret_type` is the return type + // `name` is the function name + // `args` is a comma separated list of `type name` + // | - `type` is the argument type + // | - `name` is the argument name + // Start by writing the return type if any otherwise write void + // This is the only place where `void` is a valid type + // (though it's more a keyword than a type) + if let Some(ty) = func.return_type { + self.write_type(ty, false)?; + } else { + write!(self.out, "void")?; + } + + // Write the function name and open parantheses for the argument list + write!(self.out, " {}(", name.as_ref())?; + + // Write the comma separated argument list + // + // We need access to `Self` here so we use the reference passed to the closure as an + // argument instead of capturing as that would cause a borrow checker error + self.write_slice(&func.arguments, |this, i, arg| { + // Write the argument type + // `write_type` adds no trailing spaces + this.write_type(arg.ty, false)?; + + // Write the argument name + // The leading space is important + write!(this.out, " {}", ctx.get_arg(i, &this.names))?; + + Ok(()) + })?; + + // Close the parantheses and open braces to start the function body + writeln!(self.out, ") {{")?; + + // Write all function locals + // Locals are `type name (= init)?;` where the init part (including the =) are optional + // + // Always adds a newline for (handle, local) in func.local_variables.iter() { + // Write identation (only for readability) and the type + // `write_type` adds no trailing space write!(self.out, "\t")?; - self.write_type(local.ty, None)?; + self.write_type(local.ty, false)?; + // Write the local name + // The leading space is important write!(self.out, " {}", self.names[&ctx.name_key(handle)])?; + // Write the local initializer if needed if let Some(init) = local.init { - write!(self.out, " = ",)?; + // Put the equal signal only if there's a initializer + // The leading and trailing spaces aren't needed but help with readability + write!(self.out, " = ")?; + // Write the constant + // `write_constant` adds no trailing or leading space/newline self.write_constant(&self.module.constants[init])?; } + // Finish the local with `;` and add a newline (only for readability) writeln!(self.out, ";")? } writeln!(self.out)?; + // Write the function body (statement list) for sta in func.body.iter() { + // Write a statement, the indentation should always be 1 when writing the function body + // `write_stmt` adds a newline self.write_stmt(sta, &ctx, 1)?; } - Ok(writeln!(self.out, "}}")?) + // Close braces and add a newline + writeln!(self.out, "}}")?; + + Ok(()) } - fn write_slice Result<(), Error>>( + /// Helper method that writes a list of comma separated `T` with a writer function `F` + /// + /// The writer function `F` receives a mutable reference to `self` that if needed won't cause + /// borrow checker issues (using for example a closure with `self` will cause issues), the + /// second argument is the 0 based index of the element on the list, and the last element is + /// a reference to the element `T` being written + /// + /// # Notes + /// - Adds no newlines or leading/trailing whitespaces + /// - The last element won't have a trailing `,` + fn write_slice BackendResult>( &mut self, data: &[T], mut f: F, - ) -> Result<(), Error> { + ) -> BackendResult { + // Loop trough `data` invoking `f` for each element for (i, item) in data.iter().enumerate() { f(self, i as u32, item)?; + // Only write a comma if isn't the last element if i != data.len().saturating_sub(1) { - write!(self.out, ",")?; + // The leading space is for readability only + write!(self.out, ", ")?; } } Ok(()) } - fn write_fn_header( - &mut self, - name: &str, - func: &Function, - ctx: &FunctionCtx<'_, '_>, - ) -> Result<(), Error> { - if let Some(ty) = func.return_type { - self.write_type(ty, None)?; - } else { - write!(self.out, "void")?; - } + /// Helper method used to write constants + /// + /// # Notes + /// Adds no newlines or leading/trailing whitespaces + fn write_constant(&mut self, constant: &Constant) -> BackendResult { + match constant.inner { + // Signed integers don't need anything special + ConstantInner::Sint(int) => write!(self.out, "{}", int)?, + // Unsigned integers need a `u` at the end + // + // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we + // always write it as the extra branch wouldn't have any benefit in readability + ConstantInner::Uint(int) => write!(self.out, "{}u", int)?, + // Floats are written using `Debug` insted of `Display` because it always appends the + // decimal part even it's zero which is needed for a valid glsl float constant + ConstantInner::Float(float) => write!(self.out, "{:?}", float)?, + // Booleans are either `true` or `false` so nothing special needs to be done + ConstantInner::Bool(boolean) => write!(self.out, "{}", boolean)?, + // Composite constant are created using the same syntax as compose + // `type(components)` where `components` is a comma separated list of constants + ConstantInner::Composite(ref components) => { + self.write_type(constant.ty, false)?; + write!(self.out, "(")?; - write!(self.out, " {}(", name)?; + // Write the comma separated constants + self.write_slice(components, |this, _, arg| { + this.write_constant(&this.module.constants[*arg]) + })?; - self.write_slice(&func.arguments, |this, i, arg| { - this.write_type(arg.ty, None)?; - - let name = ctx.get_arg(i, &this.names); - - Ok(write!(this.out, " {}", name)?) - })?; - - write!(self.out, ")")?; - - Ok(()) - } - - fn write_type(&mut self, ty: Handle, block: Option) -> Result<(), Error> { - match self.module.types[ty].inner { - TypeInner::Scalar { kind, width } => { - write!(self.out, "{}", glsl_scalar(kind, width)?.full)? + write!(self.out, ")")? } - TypeInner::Vector { size, kind, width } => write!( - self.out, - "{}vec{}", - glsl_scalar(kind, width)?.prefix, - size as u8 - )?, - TypeInner::Matrix { - columns, - rows, - width, - } => write!( - self.out, - "{}mat{}x{}", - glsl_scalar(ScalarKind::Float, width)?.prefix, - columns as u8, - rows as u8 - )?, - TypeInner::Pointer { base, .. } => self.write_type(base, None)?, - TypeInner::Array { base, size, .. } => { - self.write_type(base, None)?; - - write!(self.out, "[")?; - self.write_array_size(size)?; - write!(self.out, "]")? - } - TypeInner::Struct { ref members } => { - if let Some(name) = block { - writeln!(self.out, "{}_block_{} {{", name, self.block_id.generate())?; - - for (idx, member) in members.iter().enumerate() { - self.write_type(member.ty, None)?; - - writeln!( - self.out, - " {};", - &self.names[&NameKey::StructMember(ty, idx as u32)] - )?; - } - - write!(self.out, "}}")? - } else { - write!(self.out, "{}", &self.names[&NameKey::Type(ty)])? - } - } - _ => unreachable!(), } Ok(()) } - fn write_image_type( - &mut self, - dim: crate::ImageDimension, - arrayed: bool, - class: ImageClass, - ) -> Result<(), Error> { - let (base, kind, ms, comparison) = match class { - ImageClass::Sampled { kind, multi: true } => ("sampler", kind, "MS", ""), - ImageClass::Sampled { kind, multi: false } => ("sampler", kind, "", ""), - ImageClass::Depth => ("sampler", crate::ScalarKind::Float, "", "Shadow"), - ImageClass::Storage(format) => ("image", format.into(), "", ""), - }; - - Ok(write!( - self.out, - "{}{}{}{}{}{}", - glsl_scalar(kind, 4)?.prefix, - base, - ImageDimension(dim), - ms, - if arrayed { "Array" } else { "" }, - comparison - )?) - } - - fn write_array_size(&mut self, size: ArraySize) -> Result<(), Error> { - match size { - ArraySize::Constant(const_handle) => match self.module.constants[const_handle].inner { - ConstantInner::Uint(size) => write!(self.out, "{}", size)?, - _ => unreachable!(), - }, - ArraySize::Dynamic => (), - } - - Ok(()) - } - - fn collect_texture_mapping( - &self, - functions: impl Iterator, - ) -> Result, Error> { - let mut mappings = FastHashMap::default(); - - for func in functions { - let mut interface = Interface { - expressions: &func.expressions, - local_variables: &func.local_variables, - visitor: TextureMappingVisitor { - names: &self.names, - expressions: &func.expressions, - map: &mut mappings, - error: None, - }, - }; - interface.traverse(&func.body); - - if let Some(error) = interface.visitor.error { - return Err(error); - } - } - - Ok(mappings) - } - - fn write_struct( - &mut self, - handle: Handle, - members: &[StructMember], - ) -> Result<(), Error> { + fn write_struct(&mut self, handle: Handle, members: &[StructMember]) -> BackendResult { writeln!(self.out, "struct {} {{", self.names[&NameKey::Type(handle)])?; for (idx, member) in members.iter().enumerate() { write!(self.out, "\t")?; - self.write_type(member.ty, None)?; + self.write_type(member.ty, false)?; writeln!( self.out, " {};", @@ -903,7 +853,7 @@ impl<'a, W: Write> Writer<'a, W> { sta: &Statement, ctx: &FunctionCtx<'_, '_>, indent: usize, - ) -> Result<(), Error> { + ) -> BackendResult { write!(self.out, "{}", "\t".repeat(indent))?; match sta { @@ -999,11 +949,7 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } - fn write_expr( - &mut self, - expr: Handle, - ctx: &FunctionCtx<'_, '_>, - ) -> Result<(), Error> { + fn write_expr(&mut self, expr: Handle, ctx: &FunctionCtx<'_, '_>) -> BackendResult { match ctx.expressions[expr] { Expression::Access { base, index } => { self.write_expr(base, ctx)?; @@ -1038,7 +984,7 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Vector { .. } | TypeInner::Matrix { .. } | TypeInner::Array { .. } - | TypeInner::Struct { .. } => self.write_type(ty, None)?, + | TypeInner::Struct { .. } => self.write_type(ty, false)?, _ => unreachable!(), } @@ -1267,7 +1213,7 @@ impl<'a, W: Write> Writer<'a, W> { convert, } => { if convert { - self.write_type(ctx.typifier.get_handle(expr).unwrap(), None)?; + self.write_type(ctx.typifier.get_handle(expr).unwrap(), false)?; } else { let source_kind = match *ctx.typifier.get(expr, &self.module.types) { TypeInner::Scalar { @@ -1362,23 +1308,31 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } - fn write_constant(&mut self, constant: &Constant) -> Result<(), Error> { - match constant.inner { - ConstantInner::Sint(int) => write!(self.out, "{}", int)?, - ConstantInner::Uint(int) => write!(self.out, "{}u", int)?, - ConstantInner::Float(float) => write!(self.out, "{:?}", float)?, - ConstantInner::Bool(boolean) => write!(self.out, "{}", boolean)?, - ConstantInner::Composite(ref components) => { - self.write_type(constant.ty, None)?; - write!(self.out, "(")?; - self.write_slice(components, |this, _, arg| { - this.write_constant(&this.module.constants[*arg]) - })?; - write!(self.out, ")")? + fn collect_texture_mapping( + &self, + functions: impl Iterator, + ) -> Result, Error> { + let mut mappings = FastHashMap::default(); + + for func in functions { + let mut interface = Interface { + expressions: &func.expressions, + local_variables: &func.local_variables, + visitor: TextureMappingVisitor { + names: &self.names, + expressions: &func.expressions, + map: &mut mappings, + error: None, + }, + }; + interface.traverse(&func.body); + + if let Some(error) = interface.visitor.error { + return Err(error); } } - Ok(()) + Ok(mappings) } } @@ -1469,19 +1423,12 @@ fn glsl_interpolation(interpolation: Interpolation) -> Result<&'static str, Erro }) } -struct ImageDimension(crate::ImageDimension); -impl fmt::Display for ImageDimension { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}", - match self.0 { - crate::ImageDimension::D1 => "1D", - crate::ImageDimension::D2 => "2D", - crate::ImageDimension::D3 => "3D", - crate::ImageDimension::Cube => "Cube", - } - ) +fn glsl_dimension(dim: crate::ImageDimension) -> &'static str { + match dim { + crate::ImageDimension::D1 => "1D", + crate::ImageDimension::D2 => "2D", + crate::ImageDimension::D3 => "3D", + crate::ImageDimension::Cube => "Cube", } } From 3fbc801b800c64865e1b65dd2653468577196a7e Mon Sep 17 00:00:00 2001 From: Capucho Date: Tue, 24 Nov 2020 22:20:59 +0000 Subject: [PATCH 0298/2212] [glsl-out] Wrote more documentation --- src/back/glsl/mod.rs | 233 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 220 insertions(+), 13 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index cf4a5b5ea..89f0455f6 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -18,6 +18,29 @@ //! - 310 //! +// GLSL is mostly a superset of C but it also removes some parts of it this is a list of relevant +// aspects for this backend. +// +// The most notable change is the introduction of the version preprocessor directive that must +// always be the first line of a glsl file and is written as +// `#version number profile` +// `number` is the version itself (i.e. 300) and `profile` is the +// shader profile we only support "core" and "es", the former is used in desktop applications and +// the later is used in embedded contexts, mobile devices and browsers. Each one as it's own +// versions (at the time of writing this the latest version for "core" is 460 and for "es" is 320) +// +// Other important preprocessor addition is the extension directive which is written as +// `#extension name: behaviour` +// Extensions provide increased features in a plugin fashion but they aren't required to be +// supported hence why they are called extensions, that's why `behaviour` is used it specifies +// wether the extension is strictly required or if it should only be enabled if needed. In our case +// when we use extensions we set behaviour to `require` always. +// +// The only thing that glsl removes that makes a difference are pointers. +// +// Addititions that are relevant for the backend are the discard keyword, the introduction of +// vector, matrices, samplers, image types and functions that provide common shader operations + pub use error::Error; pub use features::Features; @@ -831,12 +854,32 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper method used to write structs + /// + /// # Notes + /// Ends in a newline fn write_struct(&mut self, handle: Handle, members: &[StructMember]) -> BackendResult { + // glsl structs are written as in C + // `struct name() { members };` + // | `struct` is a keyword + // | `name` is the struct name + // | `members` is a semicolon separated list of `type name` + // | `type` is the member type + // | `name` is the member name + writeln!(self.out, "struct {} {{", self.names[&NameKey::Type(handle)])?; for (idx, member) in members.iter().enumerate() { + // The identation is only for readability write!(self.out, "\t")?; + + // Write the member type + // Adds no trailing space self.write_type(member.ty, false)?; + + // Write the member name and put a semicolon + // The leading space is important + // All members must have a semicolon even the last one writeln!( self.out, " {};", @@ -848,22 +891,39 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper method used to write statements + /// + /// # Notes + /// Always adds a newline fn write_stmt( &mut self, sta: &Statement, ctx: &FunctionCtx<'_, '_>, indent: usize, ) -> BackendResult { + // The indentation is only for readability write!(self.out, "{}", "\t".repeat(indent))?; match sta { + // Blocks are simple we just need to write the block statements between braces + // We could also just print the statements but this is more readable and maps more + // closely to the IR Statement::Block(block) => { writeln!(self.out, "{{")?; for sta in block.iter() { + // Increase the indentation to help with readability self.write_stmt(sta, ctx, indent + 1)? } writeln!(self.out, "{}}}", "\t".repeat(indent))? } + // Ifs are written as in C: + // ``` + // if(condition) { + // accept + // } else { + // reject + // } + // ``` Statement::If { condition, accept, @@ -874,28 +934,50 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ") {{")?; for sta in accept { + // Increase indentation to help with readability self.write_stmt(sta, ctx, indent + 1)?; } + // If there are no statements in the reject block we skip writing it + // This is only for readability if !reject.is_empty() { writeln!(self.out, "{}}} else {{", "\t".repeat(indent))?; for sta in reject { + // Increase identation to help with readability self.write_stmt(sta, ctx, indent + 1)?; } } writeln!(self.out, "{}}}", "\t".repeat(indent))? } + // Switch are written as in C: + // ``` + // switch (selector) { + // // Falltrough + // case label: + // block + // // Non fallthrough + // case label: + // block + // break; + // default: + // block + // } + // ``` + // Where the `default` case happens isn't important but we put it last + // so that we don't need to print a `break` for it Statement::Switch { selector, cases, default, } => { + // Start the switch write!(self.out, "switch(")?; self.write_expr(*selector, ctx)?; writeln!(self.out, ") {{")?; + // Write all cases for (label, (block, fallthrough)) in cases { writeln!(self.out, "{}case {}:", "\t".repeat(indent + 1), label)?; @@ -903,11 +985,14 @@ impl<'a, W: Write> Writer<'a, W> { self.write_stmt(sta, ctx, indent + 2)?; } + // Write `break;` if the block isn't fallthrough if fallthrough.is_none() { writeln!(self.out, "{}break;", "\t".repeat(indent + 2))?; } } + // Only write the default block if the block isn't empty + // Writing default without a block is valid but it's more readable this way if !default.is_empty() { writeln!(self.out, "{}default:", "\t".repeat(indent + 1))?; @@ -918,6 +1003,14 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, "{}}}", "\t".repeat(indent))? } + // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a + // while true loop and appending the continuing block to the body resulting on: + // ``` + // while(true) { + // body + // continuing + // } + // ``` Statement::Loop { body, continuing } => { writeln!(self.out, "while(true) {{")?; @@ -927,17 +1020,26 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, "{}}}", "\t".repeat(indent))? } + // Break, continue and return as written as in C + // `break;` Statement::Break => writeln!(self.out, "break;")?, + // `continue;` Statement::Continue => writeln!(self.out, "continue;")?, + // `return expr;`, `expr` is optional Statement::Return { value } => { write!(self.out, "return")?; + // Write the expression to be returned if needed if let Some(expr) = value { write!(self.out, " ")?; self.write_expr(*expr, ctx)?; } writeln!(self.out, ";")?; } + // This is one of the places were glsl adds to the syntax of C in this case the discard + // keyword which ceases all further processing in a fragment shader, it's called OpKill + // in spir-v that's why it's called `Statement::Kill` Statement::Kill => writeln!(self.out, "discard;")?, + // Stores in glsl are just variable assignments written as `pointer = value;` Statement::Store { pointer, value } => { self.write_expr(*pointer, ctx)?; write!(self.out, " = ")?; @@ -949,14 +1051,22 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper method to write expressions + /// + /// # Notes + /// Doesn't add any newlines or leading/trailing spaces fn write_expr(&mut self, expr: Handle, ctx: &FunctionCtx<'_, '_>) -> BackendResult { match ctx.expressions[expr] { + // `Access` is applied to arrays, vectors and matrices and is written as indexing Expression::Access { base, index } => { self.write_expr(base, ctx)?; write!(self.out, "[")?; self.write_expr(index, ctx)?; write!(self.out, "]")? } + // `AccessIndex` is the same as `Access` except that the index is a constant and it can + // be applied to structs, in this case we need to find the name of the field at that + // index and write `base.field_name` Expression::AccessIndex { base, index } => { self.write_expr(base, ctx)?; @@ -965,6 +1075,8 @@ impl<'a, W: Write> Writer<'a, W> { | TypeInner::Matrix { .. } | TypeInner::Array { .. } => write!(self.out, "[{}]", index)?, TypeInner::Struct { .. } => { + // This will never panic in case the type is a `Struct`, this is not true + // for other types so we can only check while inside this match arm let ty = ctx.typifier.get_handle(base).unwrap(); write!( @@ -976,31 +1088,34 @@ impl<'a, W: Write> Writer<'a, W> { ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), } } + // Constants are delegated to `write_constant` Expression::Constant(constant) => { self.write_constant(&self.module.constants[constant])? } + // `Compose` is pretty simple we just write `type(components)` where `components` is a + // comma separated list of expressions Expression::Compose { ty, ref components } => { - match self.module.types[ty].inner { - TypeInner::Vector { .. } - | TypeInner::Matrix { .. } - | TypeInner::Array { .. } - | TypeInner::Struct { .. } => self.write_type(ty, false)?, - _ => unreachable!(), - } + self.write_type(ty, false)?; write!(self.out, "(")?; self.write_slice(components, |this, _, arg| this.write_expr(*arg, ctx))?; write!(self.out, ")")? } + // Function arguments are written as the argument name Expression::FunctionArgument(pos) => { write!(self.out, "{}", ctx.get_arg(pos, &self.names))? } + // Global variables need some special work, if they are a builtin we write the glsl + // variable name produced by `glsl_built_in` otherwise we write the global name + // produced by the `Namer` Expression::GlobalVariable(handle) => { if let Some(crate::Binding::BuiltIn(built_in)) = self.module.global_variables[handle].binding { + // Global is a builtin so get the glsl variable name write!(self.out, "{}", glsl_built_in(built_in))? } else { + // Global isn't a builtin so just write the name write!( self.out, "{}", @@ -1008,10 +1123,21 @@ impl<'a, W: Write> Writer<'a, W> { )? } } + // A local is written as it's name Expression::LocalVariable(handle) => { write!(self.out, "{}", self.names[&ctx.name_key(handle)])? } + // glsl has no pointers so there's no load operation, just write the pointer expression Expression::Load { pointer } => self.write_expr(pointer, ctx)?, + // `ImageSample` is a bit complicated compared to the rest of the IR. + // + // First there are three variations depending wether the sample level is explicitly set, + // if it's automatic or it it's bias: + // `texture(image, coordinate)` - Automatic sample level + // `texture(image, coordinate, bias)` - Bias sample level + // `textureLod(image, coordinate, level)` - Zero or Exact sample level + // + // Furthermore if `depth_ref` is some we need to append it to the coordinate vector Expression::ImageSample { image, coordinate, @@ -1020,6 +1146,8 @@ impl<'a, W: Write> Writer<'a, W> { .. } => { //TODO: handle MS + + //Write the function to be used depending on the sample level write!( self.out, "{}(", @@ -1028,45 +1156,61 @@ impl<'a, W: Write> Writer<'a, W> { crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => "textureLod", } )?; + + // Write the image that will be used self.write_expr(image, ctx)?; + // The space here isn't required but it helps with readability write!(self.out, ", ")?; + // We need to get the coordinates vector size to later build a vector that's `size + 1` + // if `depth_ref` is some, if it isn't a vector we panic as that's not a valid expression let size = match *ctx.typifier.get(coordinate, &self.module.types) { TypeInner::Vector { size, .. } => size, - ref other => { - return Err(Error::Custom(format!( - "Cannot sample with coordinates of type {:?}", - other - ))) - } + _ => unreachable!(), }; if let Some(depth_ref) = depth_ref { + // Compose a new vector with the coordinates and `depth_ref` write!(self.out, "vec{}(", size as u8 + 1)?; self.write_expr(coordinate, ctx)?; + // The space here isn't required but it helps with readability write!(self.out, ", ")?; self.write_expr(depth_ref, ctx)?; write!(self.out, ")")? } else { + // There's no `depth_ref` so just write the coordinate expression self.write_expr(coordinate, ctx)? } match level { + // Auto needs no more arguments crate::SampleLevel::Auto => (), + // Zero needs level set to 0 crate::SampleLevel::Zero => write!(self.out, ", 0")?, + // Exact and bias require another argument crate::SampleLevel::Exact(expr) | crate::SampleLevel::Bias(expr) => { write!(self.out, ", ")?; self.write_expr(expr, ctx)?; } } + // End the function write!(self.out, ")")? } + // `ImageLoad` is also a bit complicated. + // There are two functions one for sampled + // images another for storage images, the former uses `texelFetch` and the latter uses + // `imageLoad`. + // Furthermore we have `index` which is always `Some` for sampled images + // and `None` for storage images, so we end up with two functions: + // `texelFetch(image, coordinate, index)` - for sampled images + // `imageLoad(image, coordinate)` - for storage images Expression::ImageLoad { image, coordinate, index, } => { + // This will only panic if the module is invalid let class = match ctx.typifier.get(image, &self.module.types) { TypeInner::Image { class, .. } => class, _ => unreachable!(), @@ -1075,6 +1219,7 @@ impl<'a, W: Write> Writer<'a, W> { match class { ImageClass::Sampled { .. } => write!(self.out, "texelFetch(")?, ImageClass::Storage(_) => write!(self.out, "imageLoad(")?, + // TODO: Is there even a function for this? ImageClass::Depth => todo!(), } @@ -1085,6 +1230,7 @@ impl<'a, W: Write> Writer<'a, W> { match class { ImageClass::Sampled { .. } => { write!(self.out, ", ")?; + // This will only panic if the module is invalid self.write_expr(index.unwrap(), ctx)?; write!(self.out, ")")? } @@ -1092,6 +1238,12 @@ impl<'a, W: Write> Writer<'a, W> { ImageClass::Depth => todo!(), } } + // `Unary` is pretty straightforward + // "-" - for `Negate` + // "~" - for `Not` if it's an integer + // "!" - for `Not` if it's a boolean + // + // We also wrap the everything in parantheses to avoid precedence issues Expression::Unary { op, expr } => { write!( self.out, @@ -1124,6 +1276,8 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } + // `Binary` we just write `left op right` + // Once again we wrap everything in parantheses to avoid precedence issues Expression::Binary { op, left, right } => { write!(self.out, "(")?; self.write_expr(left, ctx)?; @@ -1157,6 +1311,8 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } + // `Select` is written as `condition ? accept : reject` + // We wrap everything in parantheses to avoid precedence issues Expression::Select { condition, accept, @@ -1170,14 +1326,17 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(reject, ctx)?; write!(self.out, ")")? } + // `Intrinsic` is a normal function call to some glsl provided functions Expression::Intrinsic { fun, argument } => { write!( self.out, "{}(", match fun { + // There's no specific function for this but we can invert the result of `isinf` IntrinsicFunction::IsFinite => "!isinf", IntrinsicFunction::IsInf => "isinf", IntrinsicFunction::IsNan => "isnan", + // There's also no function for this but we can invert `isnan` IntrinsicFunction::IsNormal => "!isnan", IntrinsicFunction::All => "all", IntrinsicFunction::Any => "any", @@ -1188,11 +1347,14 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } + // `Transpose` is a call to the glsl function `transpose` Expression::Transpose(matrix) => { write!(self.out, "transpose(")?; self.write_expr(matrix, ctx)?; write!(self.out, ")")? } + // Both `Dot` and `Cross` products are a call to a glsl provide functions with `left` + // and `right` as arguments Expression::DotProduct(left, right) => { write!(self.out, "dot(")?; self.write_expr(left, ctx)?; @@ -1207,6 +1369,9 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(right, ctx)?; write!(self.out, ")")? } + // `As` is always a call. + // If `convert` is true the function name is the type + // Else the function name is one of the glsl provided bitcast functions Expression::As { expr, kind, @@ -1247,6 +1412,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(expr, ctx)?; write!(self.out, ")")? } + // `Derivative` is a function call to a glsl provided function Expression::Derivative { axis, expr } => { write!( self.out, @@ -1260,6 +1426,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(expr, ctx)?; write!(self.out, ")")? } + // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list Expression::Call { origin: FunctionOrigin::Local(ref function), ref arguments, @@ -1284,6 +1451,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; write!(self.out, ")")? } + // `atan2` is implemented as `atan(y,x)` so we must handle it separately "atan2" => { write!(self.out, "atan(")?; self.write_expr(arguments[1], ctx)?; @@ -1298,6 +1466,7 @@ impl<'a, W: Write> Writer<'a, W> { ))) } }, + // `ArrayLength` is written as `expr.length()` and we convert it to a uint Expression::ArrayLength(expr) => { write!(self.out, "uint(")?; self.write_expr(expr, ctx)?; @@ -1308,12 +1477,18 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper method used to produce the images mapping that's returned to the user + /// + /// It takes an iterator of [`Function`](crate::Function) references instead of + /// [`Handle`](crate::arena::Handle) because [`EntryPoint`](crate::EntryPoint) isn't in any + /// [`Arena`](crate::arena::Arena) and we need to traverse it fn collect_texture_mapping( &self, functions: impl Iterator, ) -> Result, Error> { let mut mappings = FastHashMap::default(); + // Traverse each function in the `functions` iterator with `TextureMappingVisitor` for func in functions { let mut interface = Interface { expressions: &func.expressions, @@ -1327,6 +1502,7 @@ impl<'a, W: Write> Writer<'a, W> { }; interface.traverse(&func.body); + // Check if any error occurred if let Some(error) = interface.visitor.error { return Err(error); } @@ -1336,11 +1512,22 @@ impl<'a, W: Write> Writer<'a, W> { } } +/// Structure returned by [`glsl_scalar`](glsl_scalar) +/// +/// It contains both a prefix used in other types and the full type name struct ScalarString<'a> { + /// The prefix used to compose other types prefix: &'a str, + /// The name of the scalar type full: &'a str, } +/// Helper function that returns scalar related strings +/// +/// Check [`ScalarString`](ScalarString) for the information provided +/// +/// # Errors +/// If a [`Float`](crate::ScalarKind::Float) with an width that isn't 4 or 8 fn glsl_scalar(kind: ScalarKind, width: crate::Bytes) -> Result, Error> { Ok(match kind { ScalarKind::Sint => ScalarString { @@ -1374,6 +1561,7 @@ fn glsl_scalar(kind: ScalarKind, width: crate::Bytes) -> Result &'static str { match built_in { BuiltIn::Position => "gl_Position", @@ -1394,6 +1582,7 @@ fn glsl_built_in(built_in: BuiltIn) -> &'static str { } } +/// Helper function that returns the string correspoding to the storage class fn glsl_storage_class(class: StorageClass) -> &'static str { match class { StorageClass::Function => "", @@ -1408,6 +1597,10 @@ fn glsl_storage_class(class: StorageClass) -> &'static str { } } +/// Helper function that returns the string correspoding to the glsl interpolation qualifier +/// +/// # Errors +/// If [`Patch`](crate::Interpolation::Patch) is passed, as it isn't supported in glsl fn glsl_interpolation(interpolation: Interpolation) -> Result<&'static str, Error> { Ok(match interpolation { Interpolation::Perspective => "smooth", @@ -1423,6 +1616,7 @@ fn glsl_interpolation(interpolation: Interpolation) -> Result<&'static str, Erro }) } +/// Helper function that returns the glsl dimension string of [`ImageDimension`](crate::ImageDimension) fn glsl_dimension(dim: crate::ImageDimension) -> &'static str { match dim { crate::ImageDimension::D1 => "1D", @@ -1432,6 +1626,7 @@ fn glsl_dimension(dim: crate::ImageDimension) -> &'static str { } } +/// Helper function that returns the glsl storage format string of [`StorageFormat`](crate::StorageFormat) fn glsl_storage_format(format: StorageFormat) -> &'static str { match format { StorageFormat::R8Unorm => "r8", @@ -1469,15 +1664,27 @@ fn glsl_storage_format(format: StorageFormat) -> &'static str { } } +/// [`Visitor`](crate::proc::Visitor) used by [`collect_texture_mapping`](Writer::collect_texture_mapping) struct TextureMappingVisitor<'a> { + /// Names needed by the module (used to get the image name) names: &'a FastHashMap, + /// [`Arena`](crate::arena::Arena) of expressions of the function being currently visited expressions: &'a Arena, + /// The mapping that we are building map: &'a mut FastHashMap, + /// Used to return errors since [`visit_expr`](crate::proc::Visitor::visit_expr) doesn't allow + /// us to return anything error: Option, } impl<'a> Visitor for TextureMappingVisitor<'a> { fn visit_expr(&mut self, expr: &crate::Expression) { + // We only care about `ImageSample` and `ImageLoad` + // + // Both `image` and `sampler` are `Expression::GlobalVariable` otherwise the module is + // invalid so it's okay to panic + // + // A image can only be used with one sampler or with none at all match expr { Expression::ImageSample { image, sampler, .. } => { let tex_handle = match self.expressions[*image] { From 181d8721cc9577fcd6e509eb5c1c6c3e16f95398 Mon Sep 17 00:00:00 2001 From: Capucho Date: Thu, 26 Nov 2020 21:37:28 +0000 Subject: [PATCH 0299/2212] [glsl-out] Refractoring Used thiserror for the error enum Moved the contents of the error module to the main module Made the error an actual enum and not just a string Splitted the write function on the feature manager into a function for checking for feature availability --- src/back/glsl/error.rs | 44 -------- src/back/glsl/features.rs | 211 ++++++++++++++++++-------------------- src/back/glsl/mod.rs | 107 +++++++++++-------- 3 files changed, 165 insertions(+), 197 deletions(-) delete mode 100644 src/back/glsl/error.rs diff --git a/src/back/glsl/error.rs b/src/back/glsl/error.rs deleted file mode 100644 index 7edea5006..000000000 --- a/src/back/glsl/error.rs +++ /dev/null @@ -1,44 +0,0 @@ -use crate::proc::ResolveError; -use std::{ - fmt::{self, Error as FmtError}, - io::Error as IoError, -}; - -pub type BackendResult = std::result::Result<(), Error>; - -#[derive(Debug)] -pub enum Error { - FormatError(FmtError), - IoError(IoError), - Type(ResolveError), - Custom(String), -} - -impl From for Error { - fn from(err: FmtError) -> Self { - Error::FormatError(err) - } -} - -impl From for Error { - fn from(err: IoError) -> Self { - Error::IoError(err) - } -} - -impl From for Error { - fn from(err: ResolveError) -> Self { - Error::Type(err) - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::FormatError(err) => write!(f, "Formatting error {}", err), - Error::IoError(err) => write!(f, "Io error: {}", err), - Error::Type(err) => write!(f, "Type error: {:?}", err), - Error::Custom(err) => write!(f, "{}", err), - } - } -} diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 3e7f33264..1ab952e5f 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -1,7 +1,4 @@ -use super::{ - error::{BackendResult, Error}, - Version, Writer, -}; +use super::{BackendResult, Error, Version, Writer}; use crate::{ Bytes, ImageClass, ImageDimension, ScalarKind, ShaderStage, StorageClass, StorageFormat, TypeInner, @@ -9,88 +6,118 @@ use crate::{ use std::io::Write; bitflags::bitflags! { + /// Structure used to encode a set of addittions to glsl that aren't supported by all versions pub struct Features: u32 { + /// Buffer storage class support const BUFFER_STORAGE = 1; const ARRAY_OF_ARRAYS = 1 << 1; + /// 8 byte floats const DOUBLE_TYPE = 1 << 2; + /// Includes support for more image formats const FULL_IMAGE_FORMATS = 1 << 3; const MULTISAMPLED_TEXTURES = 1 << 4; const MULTISAMPLED_TEXTURE_ARRAYS = 1 << 5; const CUBE_TEXTURES_ARRAY = 1 << 6; const COMPUTE_SHADER = 1 << 7; + /// Adds support for image load and early depth tests const IMAGE_LOAD_STORE = 1 << 8; const CONSERVATIVE_DEPTH = 1 << 9; + /// Isn't supported in ES const TEXTURE_1D = 1 << 10; - const PUSH_CONSTANT = 1 << 11; } } +/// Helper structure used to store the required [`Features`](Features) needed to output a +/// [`Module`](crate::Module) +/// +/// Provides helper methods to check for availability and writing required extensions pub struct FeaturesManager(Features); impl FeaturesManager { + /// Creates a new [`FeaturesManager`](FeaturesManager) instance pub fn new() -> Self { Self(Features::empty()) } + /// Adds to the list of required [`Features`](Features) pub fn request(&mut self, features: Features) { self.0 |= features } - #[allow(clippy::collapsible_if)] + /// Checks that all required [`Features`](Features) are available for the specified + /// [`Version`](super::Version) otherwise returns an + /// [`Error::MissingFeatures`](super::Error::MissingFeatures) + pub fn check_availability(&self, version: Version) -> BackendResult { + // Will store all the features that are unavailable + let mut missing = Features::empty(); + + // Helper macro to check for feature availability + macro_rules! check_feature { + // Used when only core glsl supports the feature + ($feature:ident, $core:literal) => { + if self.0.contains(Features::$feature) + && (version < Version::Desktop($core) || version.is_es()) + { + missing |= Features::$feature; + } + }; + // Used when both core and es support the feature + ($feature:ident, $core:literal, $es:literal) => { + if self.0.contains(Features::$feature) + && (version < Version::Desktop($core) || version < Version::Embedded($es)) + { + missing |= Features::$feature; + } + }; + } + + check_feature!(COMPUTE_SHADER, 420, 310); + check_feature!(BUFFER_STORAGE, 400, 310); + check_feature!(DOUBLE_TYPE, 150); + check_feature!(CUBE_TEXTURES_ARRAY, 130, 310); + check_feature!(MULTISAMPLED_TEXTURES, 150, 300); + check_feature!(MULTISAMPLED_TEXTURE_ARRAYS, 150, 310); + check_feature!(ARRAY_OF_ARRAYS, 120, 310); + check_feature!(IMAGE_LOAD_STORE, 130, 310); + check_feature!(CONSERVATIVE_DEPTH, 130, 300); + check_feature!(CONSERVATIVE_DEPTH, 130, 300); + // 1D textures are supported by all core versions and aren't supported by an es versions + // so use 0 that way the check will always be false and can be optimized away + check_feature!(TEXTURE_1D, 0); + + // Return an error if there are missing features + if missing.is_empty() { + Ok(()) + } else { + Err(Error::MissingFeatures(missing)) + } + } + + /// Helper method used to write all needed extensions + /// + /// # Notes + /// This won't check for feature availability so it might output extensions that aren't even + /// supported.[`check_availability`](Self::check_availability) will check feature availability pub fn write(&self, version: Version, mut out: impl Write) -> BackendResult { - if self.0.contains(Features::COMPUTE_SHADER) { - if version < Version::Embedded(310) || version < Version::Desktop(420) { - return Err(Error::Custom(format!( - "Version {} doesn't support compute shaders", - version - ))); - } - - if !version.is_es() { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_compute_shader.txt - writeln!(out, "#extension GL_ARB_compute_shader : require")?; - } + if self.0.contains(Features::COMPUTE_SHADER) && !version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_compute_shader.txt + writeln!(out, "#extension GL_ARB_compute_shader : require")?; } - if self.0.contains(Features::BUFFER_STORAGE) { - if version < Version::Embedded(310) || version < Version::Desktop(400) { - return Err(Error::Custom(format!( - "Version {} doesn't support buffer storage class", - version - ))); - } - - if let Version::Desktop(_) = version { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_storage_buffer_object.txt - writeln!( - out, - "#extension GL_ARB_shader_storage_buffer_object : require" - )?; - } + if self.0.contains(Features::BUFFER_STORAGE) && !version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_storage_buffer_object.txt + writeln!( + out, + "#extension GL_ARB_shader_storage_buffer_object : require" + )?; } - if self.0.contains(Features::DOUBLE_TYPE) { - if version.is_es() || version < Version::Desktop(150) { - return Err(Error::Custom(format!( - "Version {} doesn't support doubles", - version - ))); - } - - if version < Version::Desktop(400) { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_gpu_shader_fp64.txt - writeln!(out, "#extension GL_ARB_gpu_shader_fp64 : require")?; - } + if self.0.contains(Features::DOUBLE_TYPE) && version < Version::Desktop(400) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_gpu_shader_fp64.txt + writeln!(out, "#extension GL_ARB_gpu_shader_fp64 : require")?; } if self.0.contains(Features::CUBE_TEXTURES_ARRAY) { - if version < Version::Embedded(310) || version < Version::Desktop(130) { - return Err(Error::Custom(format!( - "Version {} doesn't support cube map array textures", - version - ))); - } - if version.is_es() { // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_cube_map_array.txt writeln!(out, "#extension GL_EXT_texture_cube_map_array : require")?; @@ -100,54 +127,20 @@ impl FeaturesManager { } } - if self.0.contains(Features::MULTISAMPLED_TEXTURES) { - if version < Version::Embedded(300) { - return Err(Error::Custom(format!( - "Version {} doesn't support multi sampled textures", - version - ))); - } + if self.0.contains(Features::MULTISAMPLED_TEXTURE_ARRAYS) && version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/OES/OES_texture_storage_multisample_2d_array.txt + writeln!( + out, + "#extension GL_OES_texture_storage_multisample_2d_array : require" + )?; } - if self.0.contains(Features::MULTISAMPLED_TEXTURE_ARRAYS) { - if version < Version::Embedded(310) { - return Err(Error::Custom(format!( - "Version {} doesn't support multi sampled texture arrays", - version - ))); - } - - if version.is_es() { - // https://www.khronos.org/registry/OpenGL/extensions/OES/OES_texture_storage_multisample_2d_array.txt - writeln!( - out, - "#extension GL_OES_texture_storage_multisample_2d_array : require" - )?; - } - } - - if self.0.contains(Features::ARRAY_OF_ARRAYS) { - if version < Version::Embedded(310) || version < Version::Desktop(120) { - return Err(Error::Custom(format!( - "Version {} doesn't arrays of arrays", - version - ))); - } - - if version < Version::Desktop(430) { - // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_arrays_of_arrays.txt - writeln!(out, "#extension ARB_arrays_of_arrays : require")?; - } + if self.0.contains(Features::ARRAY_OF_ARRAYS) && version < Version::Desktop(430) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_arrays_of_arrays.txt + writeln!(out, "#extension ARB_arrays_of_arrays : require")?; } if self.0.contains(Features::IMAGE_LOAD_STORE) { - if version < Version::Embedded(310) || version < Version::Desktop(130) { - return Err(Error::Custom(format!( - "Version {} doesn't support images load/stores", - version - ))); - } - if self.0.contains(Features::FULL_IMAGE_FORMATS) && version.is_es() { // https://www.khronos.org/registry/OpenGL/extensions/NV/NV_image_formats.txt writeln!(out, "#extension GL_NV_image_formats : require")?; @@ -160,13 +153,6 @@ impl FeaturesManager { } if self.0.contains(Features::CONSERVATIVE_DEPTH) { - if version < Version::Embedded(300) || version < Version::Desktop(130) { - return Err(Error::Custom(format!( - "Version {} doesn't support conservative depth", - version - ))); - } - if version.is_es() { // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_conservative_depth.txt writeln!(out, "#extension GL_EXT_conservative_depth : require")?; @@ -178,21 +164,17 @@ impl FeaturesManager { } } - if self.0.contains(Features::TEXTURE_1D) { - if version.is_es() { - return Err(Error::Custom(format!( - "Version {} doesn't support 1d textures", - version - ))); - } - } - Ok(()) } } impl<'a, W> Writer<'a, W> { - pub(super) fn collect_required_features(&mut self) { + /// Helper method that searches the module for all the needed [`Features`](Features) + /// + /// # Errors + /// If the version doesn't support any of the needed [`Features`](Features) a + /// [`Error::MissingFeatures`](super::Error::MissingFeatures) will be returned + pub(super) fn collect_required_features(&mut self) -> BackendResult { let stage = self.options.entry_point.0; if let Some(depth_test) = self.entry_point.early_depth_test { @@ -270,12 +252,15 @@ impl<'a, W> Writer<'a, W> { match global.class { StorageClass::WorkGroup => self.features.request(Features::COMPUTE_SHADER), StorageClass::Storage => self.features.request(Features::BUFFER_STORAGE), - StorageClass::PushConstant => self.features.request(Features::PUSH_CONSTANT), + StorageClass::PushConstant => return Err(Error::PushConstantNotSupported), _ => {} } } + + self.features.check_availability(self.options.version) } + /// Helper method that checks the [`Features`](Features) needed by a scalar fn scalar_required_features(&mut self, kind: ScalarKind, width: Bytes) { if kind == ScalarKind::Float && width == 8 { self.features.request(Features::DOUBLE_TYPE); diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 89f0455f6..96ec029d0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1,7 +1,7 @@ //! OpenGL shading language backend //! -//! The main structure is [`Writer`](struct.Writer.html), it maintains internal state that is used -//! to output a `Module` into glsl +//! The main structure is [`Writer`](Writer), it maintains internal state that is used +//! to output a [`Module`](crate::Module) into glsl //! //! # Supported versions //! ### Core @@ -41,25 +41,27 @@ // Addititions that are relevant for the backend are the discard keyword, the introduction of // vector, matrices, samplers, image types and functions that provide common shader operations -pub use error::Error; pub use features::Features; use crate::{ proc::{ - CallGraph, CallGraphBuilder, Interface, NameKey, Namer, ResolveContext, Typifier, Visitor, + CallGraph, CallGraphBuilder, Interface, NameKey, Namer, ResolveContext, ResolveError, + Typifier, Visitor, }, - Arena, ArraySize, BinaryOperator, BuiltIn, ConservativeDepth, Constant, ConstantInner, + Arena, ArraySize, BinaryOperator, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageClass, Interpolation, IntrinsicFunction, LocalVariable, Module, ScalarKind, ShaderStage, Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, UnaryOperator, }; -use error::BackendResult; use features::FeaturesManager; -use std::{cmp::Ordering, fmt, io::Write}; +use std::{ + cmp::Ordering, + fmt, + io::{Error as IoError, Write}, +}; +use thiserror::Error; -/// Contains the backend error enum and a shorthand Result type -mod error; /// Contains the features related code and the features querying method mod features; /// Contains a constant with a slice of all the reserved keywords RESERVED_KEYWORDS @@ -121,7 +123,7 @@ impl fmt::Display for Version { } } -/// Structure that contains the configuration used in the [`Writer`](struct.Writer.html) +/// Structure that contains the configuration used in the [`Writer`](Writer) #[derive(Debug, Clone)] pub struct Options { /// The glsl version to be used @@ -207,6 +209,49 @@ impl IdGenerator { } } +/// Shorthand result used internally by the backend +type BackendResult = std::result::Result<(), Error>; + +/// A glsl compilation error. +#[derive(Debug, Error)] +pub enum Error { + /// A error occurred while writing to the output + #[error("Io error: {0}")] + IoError(#[from] IoError), + /// The [`Module`](crate::Module) failed type resolution + #[error("Type error: {0}")] + Type(#[from] ResolveError), + /// The specified [`Version`](Version) doesn't have all required [`Features`](super) + /// + /// Contains the missing [`Features`](Features) + #[error("The selected version doesn't support {0:?}")] + MissingFeatures(Features), + /// [`StorageClass::PushConstant`](crate::StorageClass::PushConstant) was used and isn't + /// supported in the glsl backend + #[error("Push constants aren't supported")] + PushConstantNotSupported, + /// The specified [`Version`](Version) isn't supported + #[error("The specified version isn't supported")] + VersionNotSupported, + /// The entry point couldn't be found + #[error("The requested entry point couldn't be found")] + EntryPointNotFound, + /// A call was made to an unsupported external + #[error("A call was made to an unsupported external: {0}")] + UnsupportedExternal(String), + /// A scalar with an unsupported width was requested + #[error("A scalar with an unsupported width was requested: {0:?} {1:?}")] + UnsupportedScalar(ScalarKind, Bytes), + /// [`Interpolation::Patch`](crate::Interpolation::Patch) isn't supported + #[error("Patch interpolation isn't supported")] + PatchInterpolationNotSupported, + /// A image was used with multiple samplers, this isn't supported + #[error("A image was used with multiple samplers")] + ImageMultipleSamplers, + #[error("{0}")] + Custom(String), +} + /// Main structure of the glsl backend responsible for all code generation pub struct Writer<'a, W> { // Inputs @@ -239,13 +284,11 @@ impl<'a, W: Write> Writer<'a, W> { /// # Errors /// - If the version specified isn't supported (or invalid) /// - If the entry point couldn't be found on the module + /// - If the version specified doesn't support some used features pub fn new(out: W, module: &'a Module, options: &'a Options) -> Result { // Check if the requested version is supported if !options.version.is_supported() { - return Err(Error::Custom(format!( - "Version not supported {}", - options.version - ))); + return Err(Error::VersionNotSupported); } // Try to find the entry point and correspoding index @@ -256,7 +299,7 @@ impl<'a, W: Write> Writer<'a, W> { .find_map(|(i, (key, entry_point))| { Some((i as u16, entry_point)).filter(|_| &options.entry_point == key) }) - .ok_or_else(|| Error::Custom(String::from("Entry point not found")))?; + .ok_or(Error::EntryPointNotFound)?; // Generate a map with names required to write the module let mut names = FastHashMap::default(); @@ -284,8 +327,7 @@ impl<'a, W: Write> Writer<'a, W> { }; // Find all features required to print this module - // TODO: We should throw errors here and not in `write` - this.collect_required_features(); + this.collect_required_features()?; Ok(this) } @@ -294,6 +336,9 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// If an error occurs while writing, the output might have been written partially + /// + /// # Panics + /// Might panic if the module is invalid pub fn write(&mut self) -> Result, Error> { // We use `writeln!(self.out)` troughout the write to add newlines // to make the output more readable @@ -1459,12 +1504,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(arguments[0], ctx)?; write!(self.out, ")")? } - other => { - return Err(Error::Custom(format!( - "Unsupported function call {}", - other - ))) - } + _ => return Err(Error::UnsupportedExternal(name.clone())), }, // `ArrayLength` is written as `expr.length()` and we convert it to a uint Expression::ArrayLength(expr) => { @@ -1547,12 +1587,7 @@ fn glsl_scalar(kind: ScalarKind, width: crate::Bytes) -> Result { - return Err(Error::Custom(format!( - "Cannot build float of width {}", - width - ))) - } + _ => return Err(Error::UnsupportedScalar(kind, width)), }, ScalarKind::Bool => ScalarString { prefix: "b", @@ -1608,11 +1643,7 @@ fn glsl_interpolation(interpolation: Interpolation) -> Result<&'static str, Erro Interpolation::Flat => "flat", Interpolation::Centroid => "centroid", Interpolation::Sample => "sample", - Interpolation::Patch => { - return Err(Error::Custom( - "patch interpolation qualifier not supported".to_string(), - )) - } + Interpolation::Patch => return Err(Error::PatchInterpolationNotSupported), }) } @@ -1704,9 +1735,7 @@ impl<'a> Visitor for TextureMappingVisitor<'a> { }); if mapping.sampler != Some(sampler_handle) { - self.error = Some(Error::Custom(String::from( - "Cannot use texture with two different samplers", - ))); + self.error = Some(Error::ImageMultipleSamplers); } } Expression::ImageLoad { image, .. } => { @@ -1722,9 +1751,7 @@ impl<'a> Visitor for TextureMappingVisitor<'a> { }); if mapping.sampler != None { - self.error = Some(Error::Custom(String::from( - "Cannot use texture with two different samplers", - ))); + self.error = Some(Error::ImageMultipleSamplers); } } _ => {} From d190c6441faf2cfc77518a54e60bf227500ee275 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 2 Dec 2020 23:46:51 -0500 Subject: [PATCH 0300/2212] Add spv::write_vec helper. --- examples/convert.rs | 2 +- src/back/spv/mod.rs | 7 +++++++ src/back/spv/writer.rs | 9 +++------ tests/convert.rs | 9 ++------- tests/rosetta.rs | 2 +- 5 files changed, 14 insertions(+), 15 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 69b5c3750..22ff8c618 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -174,7 +174,7 @@ fn main() { } }); - let spv = spv::Writer::new(&module.header, debug_flag).write(&module); + let spv = spv::write_vec(&module, debug_flag); let bytes = spv .iter() diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 15f159835..65ae54a1b 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -50,3 +50,10 @@ pub(self) struct Instruction { result_id: Option, operands: Vec, } + +pub fn write_vec(module: &crate::Module, flags: WriterFlags) -> Vec { + let mut words = Vec::new(); + let mut w = Writer::new(&module.header, flags); + w.write(module, &mut words); + words +} diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f1b43f528..fc4cdea66 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1720,15 +1720,12 @@ impl Writer { } } - pub fn write(&mut self, ir_module: &crate::Module) -> Vec { - let mut words: Vec = vec![]; - + pub fn write(&mut self, ir_module: &crate::Module, words: &mut Vec) { self.write_logical_layout(ir_module); self.write_physical_layout(); - self.physical_layout.in_words(&mut words); - self.logical_layout.in_words(&mut words); - words + self.physical_layout.in_words(words); + self.logical_layout.in_words(words); } } diff --git a/tests/convert.rs b/tests/convert.rs index 238bb405f..a05be6eea 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -198,13 +198,8 @@ fn convert_phong_lighting() { #[cfg(feaure = "spv-out")] { - let header = naga::Header { - version: (1, 0, 0), - generator: 1234, - }; - let writer_flags = naga::back::spv::WriterFlags::empty(); - let mut w = naga::back::spv::Writer::new(&header, writer_flags); - w.write(&module); + let flags = naga::back::spv::WriterFlags::empty(); + let _ = naga::back::spv::write_vec(&module, flags); } } diff --git a/tests/rosetta.rs b/tests/rosetta.rs index c97da529c..117a74da3 100644 --- a/tests/rosetta.rs +++ b/tests/rosetta.rs @@ -13,7 +13,7 @@ fn test_rosetta(dir_name: &str) { #[cfg(feature = "spv-out")] { - let spv = spv::Writer::new(&module.header, spv::WriterFlags::NONE).write(&module); + let spv = spv::write_vec(&module, spv::WriterFlags::NONE); assert!(spv.len() > 0); } } From 0d81b1f78c763a2f564194ec108bcb8ead10ea2e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 3 Dec 2020 11:47:20 -0500 Subject: [PATCH 0301/2212] [msl] add TranslationInfo struct --- examples/convert.rs | 2 +- src/back/msl/mod.rs | 18 +++++++++++++++--- src/back/msl/writer.rs | 25 ++++++++++++++++++------- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 22ff8c618..df0879dc0 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -159,7 +159,7 @@ fn main() { spirv_cross_compatibility: false, binding_map, }; - let msl = msl::write_string(&module, &options).unwrap(); + let (msl, _) = msl::write_string(&module, &options).unwrap(); fs::write(&args[2], msl).unwrap(); } #[cfg(feature = "spv-out")] diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 493e7d0c8..e96991ba3 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -204,8 +204,20 @@ impl ResolvedBinding { } } -pub fn write_string(module: &crate::Module, options: &Options) -> Result { +/// Information about a translated module that is required +/// for the use of the result. +pub struct TranslationInfo { + /// Mapping of the entry point names. Each item in the array + /// corresponds to an entry point in `module.entry_points.iter()`. + pub entry_point_names: Vec, +} + +pub fn write_string( + module: &crate::Module, + options: &Options, +) -> Result<(String, TranslationInfo), Error> { let mut w = writer::Writer::new(Vec::new()); - w.write(module, options)?; - Ok(String::from_utf8(w.finish())?) + let info = w.write(module, options)?; + let string = String::from_utf8(w.finish())?; + Ok((string, info)) } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e2adbea6b..0a9f29e04 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,4 +1,4 @@ -use super::{keywords::RESERVED, Error, LocationMode, Options, ResolvedBinding}; +use super::{keywords::RESERVED, Error, LocationMode, Options, ResolvedBinding, TranslationInfo}; use crate::{ arena::Handle, proc::{EntryPointIndex, NameKey, Namer, ResolveContext, Typifier}, @@ -563,7 +563,11 @@ impl Writer { Ok(()) } - pub fn write(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { + pub fn write( + &mut self, + module: &crate::Module, + options: &Options, + ) -> Result { self.names.clear(); Namer::process(module, RESERVED, &mut self.names); @@ -574,9 +578,7 @@ impl Writer { self.write_type_defs(module)?; writeln!(self.out)?; - self.write_functions(module, options)?; - - Ok(()) + self.write_functions(module, options) } fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { @@ -711,7 +713,12 @@ impl Writer { Ok(()) } - fn write_functions(&mut self, module: &crate::Module, options: &Options) -> Result<(), Error> { + // Returns the array of mapped entry point names. + fn write_functions( + &mut self, + module: &crate::Module, + options: &Options, + ) -> Result { for (fun_handle, fun) in module.functions.iter() { self.typifier.resolve_all( &fun.expressions, @@ -760,6 +767,9 @@ impl Writer { writeln!(self.out, "}}")?; } + let mut info = TranslationInfo { + entry_point_names: Vec::with_capacity(module.entry_points.len()), + }; for (ep_index, (&(stage, _), ep)) in module.entry_points.iter().enumerate() { let fun = &ep.function; self.typifier.resolve_all( @@ -792,6 +802,7 @@ impl Writer { } let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; + info.entry_point_names.push(fun_name.clone()); let output_name = format!("{}Output", fun_name); let location_input_name = format!("{}Input", fun_name); @@ -985,6 +996,6 @@ impl Writer { writeln!(self.out, "}}")?; } - Ok(()) + Ok(info) } } From 92de5851d0c4d6b3588014f251c283d574fc2675 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 4 Dec 2020 15:34:29 -0500 Subject: [PATCH 0302/2212] [wgsl] update builtin names, have implicit function return type --- src/front/wgsl/conv.rs | 6 +++--- src/front/wgsl/mod.rs | 7 +++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 6fdea89e7..d3bccc7e6 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -15,8 +15,8 @@ pub fn map_built_in(word: &str) -> Result> { Ok(match word { // vertex "position" => crate::BuiltIn::Position, - "vertex_idx" => crate::BuiltIn::VertexIndex, - "instance_idx" => crate::BuiltIn::InstanceIndex, + "vertex_index" => crate::BuiltIn::VertexIndex, + "instance_index" => crate::BuiltIn::InstanceIndex, // fragment "front_facing" => crate::BuiltIn::FrontFacing, "frag_coord" => crate::BuiltIn::FragCoord, @@ -24,7 +24,7 @@ pub fn map_built_in(word: &str) -> Result> { // compute "global_invocation_id" => crate::BuiltIn::GlobalInvocationId, "local_invocation_id" => crate::BuiltIn::LocalInvocationId, - "local_invocation_idx" => crate::BuiltIn::LocalInvocationIndex, + "local_invocation_index" => crate::BuiltIn::LocalInvocationIndex, _ => return Err(Error::UnknownBuiltin(word)), }) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 3b1771900..08c2d1c3f 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1563,11 +1563,10 @@ impl Parser { }); } // read return type - lexer.expect(Token::Arrow)?; - let return_type = if lexer.skip(Token::Word("void")) { - None - } else { + let return_type = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { Some(self.parse_type_decl(lexer, None, &mut module.types, &mut module.constants)?) + } else { + None }; let mut fun = crate::Function { From f18443a79df480492cc25868711179bf82f7c991 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 4 Dec 2020 16:08:52 -0500 Subject: [PATCH 0303/2212] Validate builtin types --- examples/convert.rs | 3 ++ src/proc/validator.rs | 104 +++++++++++++++++++++++++++++------------- 2 files changed, 76 insertions(+), 31 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index df0879dc0..779294903 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -120,6 +120,9 @@ fn main() { } }; + // validate the IR + naga::proc::Validator::new().validate(&module).unwrap(); + if args.len() <= 2 { println!("{:#?}", module); return; diff --git a/src/proc/validator.rs b/src/proc/validator.rs index d9d3eac65..20061c1c4 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -30,6 +30,8 @@ pub enum GlobalVariableError { InvalidBinding, #[error("Binding is out of range")] OutOfRangeBinding, + #[error("BuiltIn type for {0:?} is invalid")] + InvalidBuiltInType(crate::BuiltIn), } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -110,18 +112,86 @@ impl crate::GlobalVariable { fn check_resource(&self) -> Result<(), GlobalVariableError> { match self.binding { - Some(crate::Binding::BuiltIn(_)) => {} // validated per entry point Some(crate::Binding::Resource { group, binding }) => { if group > MAX_BIND_GROUPS || binding > MAX_BIND_INDICES { return Err(GlobalVariableError::OutOfRangeBinding); } } - Some(crate::Binding::Location(_)) | None => { + Some(crate::Binding::BuiltIn(_)) | Some(crate::Binding::Location(_)) | None => { return Err(GlobalVariableError::InvalidBinding) } } self.forbid_interpolation() } + + fn check_varying(&self, types: &Arena) -> Result<(), GlobalVariableError> { + match self.binding { + Some(crate::Binding::BuiltIn(built_in)) => { + use crate::{BuiltIn as Bi, ScalarKind as Sk, TypeInner as Ti, VectorSize as Vs}; + // Only validate the type here. Whether or not it's legal to access + // this builtin is up to the entry point. + let width = 4; + let ty_inner = match built_in { + Bi::BaseInstance + | Bi::BaseVertex + | Bi::InstanceIndex + | Bi::VertexIndex + | Bi::SampleIndex + | Bi::LocalInvocationIndex => Ti::Scalar { + kind: Sk::Uint, + width, + }, + Bi::ClipDistance | Bi::PointSize | Bi::FragDepth => Ti::Scalar { + kind: Sk::Float, + width, + }, + Bi::Position | Bi::FragCoord => Ti::Vector { + size: Vs::Quad, + kind: Sk::Float, + width, + }, + Bi::FrontFacing => Ti::Scalar { + kind: Sk::Bool, + width, + }, + Bi::GlobalInvocationId | Bi::LocalInvocationId | Bi::WorkGroupId => { + Ti::Vector { + size: Vs::Tri, + kind: Sk::Uint, + width, + } + } + }; + if types[self.ty].inner != ty_inner { + log::warn!("Wrong builtin type: {:?}", types[self.ty]); + return Err(GlobalVariableError::InvalidBuiltInType(built_in)); + } + self.forbid_interpolation()? + } + Some(crate::Binding::Location(loc)) => { + if loc > MAX_LOCATIONS { + return Err(GlobalVariableError::OutOfRangeBinding); + } + match types[self.ty].inner { + crate::TypeInner::Scalar { .. } + | crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } => {} + _ => return Err(GlobalVariableError::InvalidType), + } + } + Some(crate::Binding::Resource { .. }) => { + return Err(GlobalVariableError::InvalidBinding) + } + None => { + match types[self.ty].inner { + //TODO: check the member types + crate::TypeInner::Struct { members: _ } => self.forbid_interpolation()?, + _ => return Err(GlobalVariableError::InvalidType), + } + } + } + Ok(()) + } } fn storage_usage(access: crate::StorageAccess) -> crate::GlobalUse { @@ -152,35 +222,7 @@ impl Validator { let allowed_storage_access = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), crate::StorageClass::Input | crate::StorageClass::Output => { - match var.binding { - Some(crate::Binding::BuiltIn(_)) => { - // validated per entry point - var.forbid_interpolation()? - } - Some(crate::Binding::Location(loc)) => { - if loc > MAX_LOCATIONS { - return Err(GlobalVariableError::OutOfRangeBinding); - } - match types[var.ty].inner { - crate::TypeInner::Scalar { .. } - | crate::TypeInner::Vector { .. } - | crate::TypeInner::Matrix { .. } => {} - _ => return Err(GlobalVariableError::InvalidType), - } - } - Some(crate::Binding::Resource { .. }) => { - return Err(GlobalVariableError::InvalidBinding) - } - None => { - match types[var.ty].inner { - //TODO: check the member types - crate::TypeInner::Struct { members: _ } => { - var.forbid_interpolation()? - } - _ => return Err(GlobalVariableError::InvalidType), - } - } - } + var.check_varying(types)?; crate::StorageAccess::empty() } crate::StorageClass::Storage => { From 5fe9429a633869794dc6a38b4d39ff4693eb02ac Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 4 Dec 2020 15:03:53 -0500 Subject: [PATCH 0304/2212] Terminator processor, used in WGSL and GLSL frontends --- src/front/glsl/parser.rs | 19 ++++++++++--------- src/front/wgsl/mod.rs | 4 +++- src/proc/mod.rs | 2 ++ src/proc/terminator.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 10 deletions(-) create mode 100644 src/proc/terminator.rs diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index db4935b0b..29cbbd3fc 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -5,10 +5,15 @@ pomelo! { //%verbose; %include { use super::super::{error::ErrorKind, token::*, ast::*}; - use crate::{proc::Typifier, Arena, BinaryOperator, Binding, Block, Constant, - ConstantInner, EntryPoint, Expression, FallThrough, FastHashMap, Function, GlobalVariable, Handle, Interpolation, - LocalVariable, MemberOrigin, SampleLevel, ScalarKind, Statement, StorageAccess, - StorageClass, StructMember, Type, TypeInner, UnaryOperator}; + use crate::{ + proc::{ensure_block_returns, Typifier}, + Arena, BinaryOperator, Binding, Block, Constant, + ConstantInner, EntryPoint, Expression, FallThrough, + FastHashMap, Function, GlobalVariable, Handle, Interpolation, + LocalVariable, MemberOrigin, SampleLevel, ScalarKind, + Statement, StorageAccess, + StorageClass, StructMember, Type, TypeInner, UnaryOperator, + }; } %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; %parser pub struct Parser<'a> {}; @@ -1117,11 +1122,7 @@ pomelo! { extra.context.clear_scopes(); extra.context.lookup_global_var_exps.clear(); extra.context.typifier = Typifier::new(); - // make sure function ends with return - match cs.last() { - Some(Statement::Return {..}) => {} - _ => {cs.push(Statement::Return { value:None });} - } + ensure_block_returns(&mut cs); f.body = cs; f.fill_global_use(&extra.module.global_variables); f diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 08c2d1c3f..e2c95ee77 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -7,7 +7,7 @@ mod lexer; use crate::{ arena::{Arena, Handle}, - proc::{ResolveContext, ResolveError, Typifier}, + proc::{ensure_block_returns, ResolveContext, ResolveError, Typifier}, FastHashMap, }; @@ -1594,6 +1594,8 @@ impl Parser { arguments: &fun.arguments, }, )?; + // fixup the IR + ensure_block_returns(&mut fun.body); // done fun.fill_global_use(&module.global_variables); self.scopes.pop(); diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 961e55da7..d8388b4c5 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -4,6 +4,7 @@ mod call_graph; mod interface; mod namer; +mod terminator; mod typifier; mod validator; @@ -11,6 +12,7 @@ mod validator; pub use call_graph::{CallGraph, CallGraphBuilder}; pub use interface::{Interface, Visitor}; pub use namer::{EntryPointIndex, NameKey, Namer}; +pub use terminator::ensure_block_returns; pub use typifier::{check_constant_type, ResolveContext, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs new file mode 100644 index 000000000..8b4d6ff33 --- /dev/null +++ b/src/proc/terminator.rs @@ -0,0 +1,40 @@ +/// Ensure that the given block has return statements +/// at the end of its control flow. +/// +/// Note: we don't want to blindly append a return statement +/// to the end, because it may be either redundant or invalid, +/// e.g. when the user already has returns in if/else branches. +pub fn ensure_block_returns(block: &mut crate::Block) { + match block.last_mut() { + Some(&mut crate::Statement::Block(ref mut b)) => { + ensure_block_returns(b); + } + Some(&mut crate::Statement::If { + condition: _, + ref mut accept, + ref mut reject, + }) => { + ensure_block_returns(accept); + ensure_block_returns(reject); + } + Some(&mut crate::Statement::Switch { + selector: _, + ref mut cases, + ref mut default, + }) => { + for case in cases.values_mut() { + if let (ref mut b, None) = *case { + ensure_block_returns(b); + } + } + ensure_block_returns(default); + } + Some(&mut crate::Statement::Break) + | Some(&mut crate::Statement::Continue) + | Some(&mut crate::Statement::Return { .. }) + | Some(&mut crate::Statement::Kill) => (), + Some(&mut crate::Statement::Loop { .. }) + | Some(&mut crate::Statement::Store { .. }) + | None => block.push(crate::Statement::Return { value: None }), + } +} From f7ca7f2aff384481dcd17132e277ad59a789f067 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 4 Dec 2020 19:26:01 -0500 Subject: [PATCH 0305/2212] Refactor Switch statement, implement on WGSL --- src/back/glsl/mod.rs | 8 +++--- src/back/msl/writer.rs | 8 +++--- src/front/glsl/parser.rs | 42 +++++++++++++++-------------- src/front/spv/flow.rs | 28 ++++++++------------ src/front/wgsl/lexer.rs | 2 +- src/front/wgsl/mod.rs | 57 ++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 16 ++++++++--- src/proc/interface.rs | 4 +-- src/proc/terminator.rs | 6 ++--- 9 files changed, 117 insertions(+), 54 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 96ec029d0..98bfe02c9 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1023,15 +1023,15 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ") {{")?; // Write all cases - for (label, (block, fallthrough)) in cases { - writeln!(self.out, "{}case {}:", "\t".repeat(indent + 1), label)?; + for case in cases { + writeln!(self.out, "{}case {}:", "\t".repeat(indent + 1), case.value)?; - for sta in block { + for sta in case.body.iter() { self.write_stmt(sta, ctx, indent + 2)?; } // Write `break;` if the block isn't fallthrough - if fallthrough.is_none() { + if case.fall_through { writeln!(self.out, "{}break;", "\t".repeat(indent + 2))?; } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0a9f29e04..936f78ac5 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -505,10 +505,10 @@ impl Writer { self.put_expression(selector, context)?; writeln!(self.out, ") {{")?; let lcase = level.next(); - for (&value, &(ref block, ref fall_through)) in cases.iter() { - writeln!(self.out, "{}case {}: {{", lcase, value)?; - self.put_block(lcase.next(), block, context, return_value)?; - if fall_through.is_none() { + for case in cases.iter() { + writeln!(self.out, "{}case {}: {{", lcase, case.value)?; + self.put_block(lcase.next(), &case.body, context, return_value)?; + if case.fall_through { writeln!(self.out, "{}break;", lcase.next())?; } writeln!(self.out, "{}}}", lcase)?; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 29cbbd3fc..797917dd9 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -8,11 +8,11 @@ pomelo! { use crate::{ proc::{ensure_block_returns, Typifier}, Arena, BinaryOperator, Binding, Block, Constant, - ConstantInner, EntryPoint, Expression, FallThrough, - FastHashMap, Function, GlobalVariable, Handle, Interpolation, + ConstantInner, EntryPoint, Expression, + Function, GlobalVariable, Handle, Interpolation, LocalVariable, MemberOrigin, SampleLevel, ScalarKind, - Statement, StorageAccess, - StorageClass, StructMember, Type, TypeInner, UnaryOperator, + Statement, StorageAccess, StorageClass, StructMember, + SwitchCase, Type, TypeInner, UnaryOperator, }; } %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; @@ -62,8 +62,8 @@ pomelo! { %type jump_statement Statement; %type iteration_statement Statement; %type selection_statement Statement; - %type switch_statement_list Vec<(Option, Block, Option)>; - %type switch_statement (Option, Block, Option); + %type switch_statement_list Vec<(Option, Block, bool)>; + %type switch_statement (Option, Block, bool); %type for_init_statement Statement; %type for_rest_statement (Option, Option); %type condition_opt Option; @@ -847,12 +847,16 @@ pomelo! { selection_statement ::= Switch LeftParen expression(e) RightParen LeftBrace switch_statement_list(ls) RightBrace { let mut default = Vec::new(); - let mut cases = FastHashMap::default(); - for (v, s, ft) in ls { - if let Some(v) = v { - cases.insert(v, (s, ft)); + let mut cases = Vec::new(); + for (v, body, fall_through) in ls { + if let Some(value) = v { + cases.push(SwitchCase { + value, + body, + fall_through, + }); } else { - default.extend_from_slice(&s); + default.extend_from_slice(&body); } } Statement::Switch { @@ -870,18 +874,18 @@ pomelo! { ssl } switch_statement ::= Case IntConstant(v) Colon statement_list(sl) { - let fallthrough = match sl.last() { - Some(Statement::Break) => None, - _ => Some(FallThrough), + let fall_through = match sl.last() { + Some(&Statement::Break) => false, + _ => true, }; - (Some(v.1 as i32), sl, fallthrough) + (Some(v.1 as i32), sl, fall_through) } switch_statement ::= Default Colon statement_list(sl) { - let fallthrough = match sl.last() { - Some(Statement::Break) => Some(FallThrough), - _ => None, + let fall_through = match sl.last() { + Some(&Statement::Break) => true, + _ => false, }; - (None, sl, fallthrough) + (None, sl, fall_through) } iteration_statement ::= While LeftParen expression(e) RightParen compound_statement_no_new_scope(sl) { diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 32eac6694..c11a1eda0 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -271,35 +271,29 @@ impl FlowGraph { } => { let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; let mut result = node.block.clone(); - - let mut cases = FastHashMap::default(); + let mut cases = Vec::with_capacity(targets.len()); for i in 0..targets.len() { let left_target_node_index = self.block_to_node[&targets[i].1]; - let fallthrough: Option = if i < targets.len() - 1 { + let fall_through = if i < targets.len() - 1 { let right_target_node_index = self.block_to_node[&targets[i + 1].1]; - if has_path_connecting( + has_path_connecting( &self.flow, left_target_node_index, right_target_node_index, None, - ) { - Some(crate::FallThrough {}) - } else { - None - } + ) } else { - None + false }; - cases.insert( - targets[i].0, - ( - self.naga_traverse(left_target_node_index, Some(merge_node_index))?, - fallthrough, - ), - ); + cases.push(crate::SwitchCase { + value: targets[i].0, + body: self + .naga_traverse(left_target_node_index, Some(merge_node_index))?, + fall_through, + }); } result.push(crate::Statement::Switch { diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index b991ecf61..0dd2627ef 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -198,7 +198,7 @@ impl<'a> Lexer<'a> { } } - fn _next_sint_literal(&mut self) -> Result> { + pub(super) fn next_sint_literal(&mut self) -> Result> { match self.next() { Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), other => Err(Error::Unexpected(other)), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e2c95ee77..620e221e7 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1460,6 +1460,63 @@ impl Parser { reject, } } + "switch" => { + lexer.expect(Token::Paren('('))?; + let selector = + self.parse_general_expression(lexer, context.as_expression())?; + lexer.expect(Token::Paren(')'))?; + lexer.expect(Token::Paren('{'))?; + let mut cases = Vec::new(); + let mut default = Vec::new(); + loop { + match lexer.next() { + Token::Word("case") => loop { + let value = lexer.next_sint_literal()?; + lexer.expect(Token::Separator(':'))?; + let mut body = Vec::new(); + if lexer.skip(Token::Separator(',')) { + cases.push(crate::SwitchCase { + value, + body, + fall_through: true, + }); + } else { + lexer.expect(Token::Paren('{'))?; + let fall_through = loop { + if lexer.skip(Token::Word("fallthrough")) { + lexer.expect(Token::Separator(';'))?; + lexer.expect(Token::Paren('}'))?; + break true; + } + if lexer.skip(Token::Paren('}')) { + break false; + } + let s = + self.parse_statement(lexer, context.reborrow())?; + body.push(s); + }; + cases.push(crate::SwitchCase { + value, + body, + fall_through, + }); + break; + } + }, + Token::Word("default") => { + lexer.expect(Token::Separator(':'))?; + default = self.parse_block(lexer, context.reborrow())?; + } + Token::Paren('}') => break, + other => return Err(Error::Unexpected(other)), + } + } + crate::Statement::Switch { + selector, + cases, + default, + } + } "loop" => { let mut body = Vec::new(); let mut continuing = Vec::new(); diff --git a/src/lib.rs b/src/lib.rs index 936c3b69f..7b141b538 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -666,12 +666,20 @@ pub enum Expression { /// A code block is just a vector of statements. pub type Block = Vec; -/// Marker type, used for falling through in a switch statement. +/// A case for a switch statement. // Clone is used only for error reporting and is not intended for end users -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] -pub struct FallThrough; +pub struct SwitchCase { + /// Value, upon which the case is considered true. + pub value: i32, + /// Body of the cae. + pub body: Block, + /// If true, the control flow continues to the next case in the list, + /// or default. + pub fall_through: bool, +} /// Instructions which make up an executable block. // Clone is used only for error reporting and is not intended for end users @@ -690,7 +698,7 @@ pub enum Statement { /// Conditionally executes one of multiple blocks, based on the value of the selector. Switch { selector: Handle, //int - cases: FastHashMap)>, + cases: Vec, default: Block, }, /// Executes a block repeatedly. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index b512452fe..e3835f263 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -148,8 +148,8 @@ where ref default, } => { self.traverse_expr(selector); - for &(ref case, _) in cases.values() { - self.traverse(case); + for case in cases.iter() { + self.traverse(&case.body); } self.traverse(default); } diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index 8b4d6ff33..1ad142981 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -22,9 +22,9 @@ pub fn ensure_block_returns(block: &mut crate::Block) { ref mut cases, ref mut default, }) => { - for case in cases.values_mut() { - if let (ref mut b, None) = *case { - ensure_block_returns(b); + for case in cases.iter_mut() { + if !case.fall_through { + ensure_block_returns(&mut case.body); } } ensure_block_returns(default); From 5b14e266591325e9123ca4cce4f4573441b2d5f6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 5 Dec 2020 11:13:12 -0500 Subject: [PATCH 0306/2212] [wgsl] add a test module with units for if/loop/switch statements --- src/front/wgsl/lexer.rs | 1 + src/front/wgsl/mod.rs | 360 ++++++++++++++++++++-------------------- src/front/wgsl/tests.rs | 60 +++++++ 3 files changed, 244 insertions(+), 177 deletions(-) create mode 100644 src/front/wgsl/tests.rs diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 0dd2627ef..a9e45da7a 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -163,6 +163,7 @@ impl<'a> Lexer<'a> { if token == expected { Ok(()) } else { + log::trace!("expect {:?}, got {:?}", expected, token); Err(Error::Unexpected(token)) } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 620e221e7..1b4e7a1cc 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -4,6 +4,8 @@ mod conv; mod lexer; +#[cfg(test)] +mod tests; use crate::{ arena::{Arena, Handle}, @@ -1385,188 +1387,198 @@ impl Parser { mut context: StatementContext<'a, '_, '_>, ) -> Result> { let backup = lexer.clone(); - match lexer.next() { - Token::Separator(';') => Ok(crate::Statement::Block(Vec::new())), - Token::Word(word) => { - self.scopes.push(Scope::Statement); - let statement = match word { - "var" => { - enum Init { - Empty, - Constant(Handle), - Variable(Handle), - } - let (name, ty) = self.parse_variable_ident_decl( - lexer, - context.types, - context.constants, - )?; - let init = if lexer.skip(Token::Operation('=')) { - let value = - self.parse_general_expression(lexer, context.as_expression())?; - if let crate::Expression::Constant(handle) = context.expressions[value] - { - Init::Constant(handle) - } else { - Init::Variable(value) - } - } else { - Init::Empty - }; - lexer.expect(Token::Separator(';'))?; - let var_id = context.variables.append(crate::LocalVariable { - name: Some(name.to_owned()), - ty, - init: match init { - Init::Constant(value) => Some(value), - _ => None, - }, - }); - let expr_id = context - .expressions - .append(crate::Expression::LocalVariable(var_id)); - context.lookup_ident.insert(name, expr_id); - match init { - Init::Variable(value) => crate::Statement::Store { - pointer: expr_id, - value, - }, - _ => crate::Statement::Block(Vec::new()), - } + let word = match lexer.next() { + Token::Separator(';') => return Ok(crate::Statement::Block(Vec::new())), + Token::Word(word) => word, + other => return Err(Error::Unexpected(other)), + }; + + self.scopes.push(Scope::Statement); + let statement = match word { + "var" => { + enum Init { + Empty, + Constant(Handle), + Variable(Handle), + } + + let (name, ty) = + self.parse_variable_ident_decl(lexer, context.types, context.constants)?; + + let init = if lexer.skip(Token::Operation('=')) { + let value = self.parse_general_expression(lexer, context.as_expression())?; + if let crate::Expression::Constant(handle) = context.expressions[value] { + Init::Constant(handle) + } else { + Init::Variable(value) } - "return" => { - let value = if lexer.peek() != Token::Separator(';') { - Some(self.parse_general_expression(lexer, context.as_expression())?) - } else { - None - }; - lexer.expect(Token::Separator(';'))?; - crate::Statement::Return { value } - } - "if" => { - lexer.expect(Token::Paren('('))?; - let condition = - self.parse_general_expression(lexer, context.as_expression())?; - lexer.expect(Token::Paren(')'))?; - let accept = self.parse_block(lexer, context.reborrow())?; - let reject = if lexer.skip(Token::Word("else")) { - self.parse_block(lexer, context.reborrow())? - } else { - Vec::new() - }; - crate::Statement::If { - condition, - accept, - reject, - } - } - "switch" => { - lexer.expect(Token::Paren('('))?; - let selector = - self.parse_general_expression(lexer, context.as_expression())?; - lexer.expect(Token::Paren(')'))?; - lexer.expect(Token::Paren('{'))?; - let mut cases = Vec::new(); - let mut default = Vec::new(); - loop { - match lexer.next() { - Token::Word("case") => loop { - let value = lexer.next_sint_literal()?; - lexer.expect(Token::Separator(':'))?; - let mut body = Vec::new(); - if lexer.skip(Token::Separator(',')) { + } else { + Init::Empty + }; + + lexer.expect(Token::Separator(';'))?; + let var_id = context.variables.append(crate::LocalVariable { + name: Some(name.to_owned()), + ty, + init: match init { + Init::Constant(value) => Some(value), + _ => None, + }, + }); + + let expr_id = context + .expressions + .append(crate::Expression::LocalVariable(var_id)); + context.lookup_ident.insert(name, expr_id); + + match init { + Init::Variable(value) => crate::Statement::Store { + pointer: expr_id, + value, + }, + _ => crate::Statement::Block(Vec::new()), + } + } + "return" => { + let value = if lexer.peek() != Token::Separator(';') { + Some(self.parse_general_expression(lexer, context.as_expression())?) + } else { + None + }; + lexer.expect(Token::Separator(';'))?; + crate::Statement::Return { value } + } + "if" => { + lexer.expect(Token::Paren('('))?; + let condition = self.parse_general_expression(lexer, context.as_expression())?; + lexer.expect(Token::Paren(')'))?; + + let accept = self.parse_block(lexer, context.reborrow())?; + let reject = if lexer.skip(Token::Word("else")) { + self.parse_block(lexer, context.reborrow())? + } else { + Vec::new() + }; + + crate::Statement::If { + condition, + accept, + reject, + } + } + "switch" => { + lexer.expect(Token::Paren('('))?; + let selector = self.parse_general_expression(lexer, context.as_expression())?; + lexer.expect(Token::Paren(')'))?; + lexer.expect(Token::Paren('{'))?; + let mut cases = Vec::new(); + let mut default = Vec::new(); + + loop { + // cases + default + match lexer.next() { + Token::Word("case") => { + let value = loop { + // values + let value = lexer.next_sint_literal()?; + match lexer.next() { + Token::Separator(',') => { cases.push(crate::SwitchCase { value, - body, + body: Vec::new(), fall_through: true, }); - } else { - lexer.expect(Token::Paren('{'))?; - let fall_through = loop { - if lexer.skip(Token::Word("fallthrough")) { - lexer.expect(Token::Separator(';'))?; - lexer.expect(Token::Paren('}'))?; - break true; - } - if lexer.skip(Token::Paren('}')) { - break false; - } - let s = - self.parse_statement(lexer, context.reborrow())?; - body.push(s); - }; - cases.push(crate::SwitchCase { - value, - body, - fall_through, - }); - break; } - }, - Token::Word("default") => { - lexer.expect(Token::Separator(':'))?; - default = self.parse_block(lexer, context.reborrow())?; + Token::Separator(':') => break value, + other => return Err(Error::Unexpected(other)), } - Token::Paren('}') => break, - other => return Err(Error::Unexpected(other)), - } - } - crate::Statement::Switch { - selector, - cases, - default, - } - } - "loop" => { - let mut body = Vec::new(); - let mut continuing = Vec::new(); - lexer.expect(Token::Paren('{'))?; - loop { - if lexer.skip(Token::Word("continuing")) { - continuing = self.parse_block(lexer, context.reborrow())?; - lexer.expect(Token::Paren('}'))?; - break; - } - if lexer.skip(Token::Paren('}')) { - break; - } - let s = self.parse_statement(lexer, context.reborrow())?; - body.push(s); - } - crate::Statement::Loop { body, continuing } - } - "break" => crate::Statement::Break, - "continue" => crate::Statement::Continue, - ident => { - // assignment - if let Some(&var_expr) = context.lookup_ident.get(ident) { - let left = - self.parse_postfix(lexer, context.as_expression(), var_expr)?; - lexer.expect(Token::Operation('='))?; - let value = - self.parse_general_expression(lexer, context.as_expression())?; - lexer.expect(Token::Separator(';'))?; - crate::Statement::Store { - pointer: left, + }; + + let mut body = Vec::new(); + lexer.expect(Token::Paren('{'))?; + let fall_through = loop { + // default statements + if lexer.skip(Token::Word("fallthrough")) { + lexer.expect(Token::Separator(';'))?; + lexer.expect(Token::Paren('}'))?; + break true; + } + if lexer.skip(Token::Paren('}')) { + break false; + } + let s = self.parse_statement(lexer, context.reborrow())?; + body.push(s); + }; + + cases.push(crate::SwitchCase { value, - } - } else if let Some((expr, new_lexer)) = - self.parse_function_call(&backup, context.as_expression())? - { - *lexer = new_lexer; - context.expressions.append(expr); - lexer.expect(Token::Separator(';'))?; - crate::Statement::Block(Vec::new()) - } else { - return Err(Error::UnknownIdent(ident)); + body, + fall_through, + }); } + Token::Word("default") => { + lexer.expect(Token::Separator(':'))?; + default = self.parse_block(lexer, context.reborrow())?; + } + Token::Paren('}') => break, + other => return Err(Error::Unexpected(other)), } - }; - self.scopes.pop(); - Ok(statement) + } + + crate::Statement::Switch { + selector, + cases, + default, + } } - other => Err(Error::Unexpected(other)), - } + "loop" => { + let mut body = Vec::new(); + let mut continuing = Vec::new(); + lexer.expect(Token::Paren('{'))?; + + loop { + if lexer.skip(Token::Word("continuing")) { + continuing = self.parse_block(lexer, context.reborrow())?; + lexer.expect(Token::Paren('}'))?; + break; + } + if lexer.skip(Token::Paren('}')) { + break; + } + let s = self.parse_statement(lexer, context.reborrow())?; + body.push(s); + } + + crate::Statement::Loop { body, continuing } + } + "break" => crate::Statement::Break, + "continue" => crate::Statement::Continue, + "discard" => crate::Statement::Kill, + ident => { + // assignment + if let Some(&var_expr) = context.lookup_ident.get(ident) { + let left = self.parse_postfix(lexer, context.as_expression(), var_expr)?; + lexer.expect(Token::Operation('='))?; + let value = self.parse_general_expression(lexer, context.as_expression())?; + lexer.expect(Token::Separator(';'))?; + crate::Statement::Store { + pointer: left, + value, + } + } else if let Some((expr, new_lexer)) = + self.parse_function_call(&backup, context.as_expression())? + { + *lexer = new_lexer; + context.expressions.append(expr); + lexer.expect(Token::Separator(';'))?; + crate::Statement::Block(Vec::new()) + } else { + return Err(Error::UnknownIdent(ident)); + } + } + }; + self.scopes.pop(); + Ok(statement) } fn parse_block<'a>( @@ -1900,9 +1912,3 @@ impl Parser { pub fn parse_str(source: &str) -> Result { Parser::new().parse(source) } - -#[test] -fn parse_types() { - assert!(parse_str("const a : i32 = 2;").is_ok()); - assert!(parse_str("const a : x32 = 2;").is_err()); -} diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs new file mode 100644 index 000000000..b5e25891c --- /dev/null +++ b/src/front/wgsl/tests.rs @@ -0,0 +1,60 @@ +use super::parse_str; + +#[test] +fn parse_types() { + parse_str("const a : i32 = 2;").unwrap(); + assert!(parse_str("const a : x32 = 2;").is_err()); +} + +#[test] +fn parse_if() { + parse_str( + " + fn main() { + if (true) { + discard; + } else {} + if (0 != 1) {} + } + ", + ) + .unwrap(); +} + +#[test] +fn parse_loop() { + parse_str( + " + fn main() { + var i: i32 = 0; + loop { + if (i == 1) { break; } + continuing { i = 1; } + } + loop { + if (i == 0) { continue; } + break; + } + } + ", + ) + .unwrap(); +} + +#[test] +fn parse_switch() { + parse_str( + " + fn main() { + var pos: f32; + switch (3) { + case 0, 1: { pos = 0.0; } + case 2: { pos = 1.0; fallthrough; } + case 3: {} + default: { pos = 3.0; } + } + } + ", + ) + .unwrap(); +} From ef4e8cacf9490a92fbc94750d9e2bb6114cfd572 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 6 Dec 2020 01:35:23 -0500 Subject: [PATCH 0307/2212] [spv] refactor binary operators, add module and addition --- src/back/spv/instructions.rs | 117 +-------------------------- src/back/spv/writer.rs | 153 ++++++++++++++--------------------- 2 files changed, 60 insertions(+), 210 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index ab8e56844..fe03a4d61 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -537,7 +537,7 @@ pub(super) fn instruction_composite_construct( // // Arithmetic Instructions // -fn instruction_binary( +pub(super) fn instruction_binary( op: Op, result_type_id: Word, id: Word, @@ -552,125 +552,10 @@ fn instruction_binary( instruction } -pub(super) fn instruction_i_sub( - result_type_id: Word, - id: Word, - operand_1: Word, - operand_2: Word, -) -> Instruction { - instruction_binary(Op::ISub, result_type_id, id, operand_1, operand_2) -} - -pub(super) fn instruction_f_sub( - result_type_id: Word, - id: Word, - operand_1: Word, - operand_2: Word, -) -> Instruction { - instruction_binary(Op::FSub, result_type_id, id, operand_1, operand_2) -} - -pub(super) fn instruction_i_mul( - result_type_id: Word, - id: Word, - operand_1: Word, - operand_2: Word, -) -> Instruction { - instruction_binary(Op::IMul, result_type_id, id, operand_1, operand_2) -} - -pub(super) fn instruction_f_mul( - result_type_id: Word, - id: Word, - operand_1: Word, - operand_2: Word, -) -> Instruction { - instruction_binary(Op::FMul, result_type_id, id, operand_1, operand_2) -} - -pub(super) fn instruction_vector_times_scalar( - result_type_id: Word, - id: Word, - vector_type_id: Word, - scalar_type_id: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::VectorTimesScalar); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(vector_type_id); - instruction.add_operand(scalar_type_id); - instruction -} - -pub(super) fn instruction_matrix_times_scalar( - result_type_id: Word, - id: Word, - matrix_id: Word, - scalar_id: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::MatrixTimesScalar); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(matrix_id); - instruction.add_operand(scalar_id); - instruction -} - -pub(super) fn instruction_vector_times_matrix( - result_type_id: Word, - id: Word, - vector_id: Word, - matrix_id: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::VectorTimesMatrix); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(vector_id); - instruction.add_operand(matrix_id); - instruction -} - -pub(super) fn instruction_matrix_times_vector( - result_type_id: Word, - id: Word, - matrix_id: Word, - vector_id: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::MatrixTimesVector); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(matrix_id); - instruction.add_operand(vector_id); - instruction -} - -pub(super) fn instruction_matrix_times_matrix( - result_type_id: Word, - id: Word, - left_matrix: Word, - right_matrix: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::MatrixTimesMatrix); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(left_matrix); - instruction.add_operand(right_matrix); - instruction -} - // // Bit Instructions // -pub(super) fn instruction_bitwise_and( - result_type_id: Word, - id: Word, - operand_1: Word, - operand_2: Word, -) -> Instruction { - instruction_binary(Op::BitwiseAnd, result_type_id, id, operand_1, operand_2) -} - // // Relational and Logical Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index fc4cdea66..f4d71b82f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1147,116 +1147,81 @@ impl Writer { let left_dimension = get_dimension(&left_ty_inner); let right_dimension = get_dimension(&right_ty_inner); - let (instruction, lookup_ty) = match op { + let (spirv_op, lookup_ty) = match op { + crate::BinaryOperator::Add => match *left_ty_inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } => match kind { + crate::ScalarKind::Float => (spirv::Op::FAdd, left_lookup_ty), + _ => (spirv::Op::IAdd, left_lookup_ty), + }, + _ => unreachable!(), + }, + crate::BinaryOperator::Subtract => match *left_ty_inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } => match kind { + crate::ScalarKind::Float => (spirv::Op::FSub, left_lookup_ty), + _ => (spirv::Op::ISub, left_lookup_ty), + }, + _ => unreachable!(), + }, crate::BinaryOperator::Multiply => match (left_dimension, right_dimension) { - (Dimension::Vector, Dimension::Scalar { .. }) => ( - super::instructions::instruction_vector_times_scalar( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - (Dimension::Vector, Dimension::Matrix) => ( - super::instructions::instruction_vector_times_matrix( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - (Dimension::Matrix, Dimension::Scalar { .. }) => ( - super::instructions::instruction_matrix_times_scalar( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - (Dimension::Matrix, Dimension::Vector) => ( - super::instructions::instruction_matrix_times_vector( - right_result_type_id, - id, - left_id, - right_id, - ), - right_lookup_ty, - ), - (Dimension::Matrix, Dimension::Matrix) => ( - super::instructions::instruction_matrix_times_matrix( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), + (Dimension::Vector, Dimension::Scalar { .. }) => { + (spirv::Op::VectorTimesScalar, left_lookup_ty) + } + (Dimension::Vector, Dimension::Matrix) => { + (spirv::Op::VectorTimesMatrix, left_lookup_ty) + } + (Dimension::Matrix, Dimension::Scalar { .. }) => { + (spirv::Op::MatrixTimesScalar, left_lookup_ty) + } + (Dimension::Matrix, Dimension::Vector) => { + (spirv::Op::MatrixTimesVector, right_lookup_ty) + } + (Dimension::Matrix, Dimension::Matrix) => { + (spirv::Op::MatrixTimesMatrix, left_lookup_ty) + } (Dimension::Vector, Dimension::Vector) | (Dimension::Scalar, Dimension::Scalar) if left_ty_inner.scalar_kind() == Some(crate::ScalarKind::Float) => { - ( - super::instructions::instruction_f_mul( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ) + (spirv::Op::FMul, left_lookup_ty) } (Dimension::Vector, Dimension::Vector) - | (Dimension::Scalar, Dimension::Scalar) => ( - super::instructions::instruction_i_mul( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), + | (Dimension::Scalar, Dimension::Scalar) => { + (spirv::Op::IMul, left_lookup_ty) + } _ => unreachable!(), }, - crate::BinaryOperator::Subtract => match *left_ty_inner { - crate::TypeInner::Scalar { kind, .. } => match kind { - crate::ScalarKind::Sint | crate::ScalarKind::Uint => ( - super::instructions::instruction_i_sub( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), - crate::ScalarKind::Float => ( - super::instructions::instruction_f_sub( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), + crate::BinaryOperator::Divide => match *left_ty_inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } => match kind { + crate::ScalarKind::Sint => (spirv::Op::SDiv, left_lookup_ty), + crate::ScalarKind::Uint => (spirv::Op::UDiv, left_lookup_ty), _ => unreachable!(), }, _ => unreachable!(), }, - crate::BinaryOperator::And => ( - super::instructions::instruction_bitwise_and( - left_result_type_id, - id, - left_id, - right_id, - ), - left_lookup_ty, - ), + crate::BinaryOperator::Modulo => match *left_ty_inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } => match kind { + crate::ScalarKind::Sint => (spirv::Op::SMod, left_lookup_ty), + crate::ScalarKind::Uint => (spirv::Op::UMod, left_lookup_ty), + crate::ScalarKind::Float => (spirv::Op::FMod, left_lookup_ty), + _ => unreachable!(), + }, + _ => unreachable!(), + }, + crate::BinaryOperator::And => (spirv::Op::BitwiseAnd, left_lookup_ty), _ => unimplemented!("{:?}", op), }; - block.body.push(instruction); + block.body.push(super::instructions::instruction_binary( + spirv_op, + left_result_type_id, + id, + left_id, + right_id, + )); Ok((id, lookup_ty)) } crate::Expression::LocalVariable(variable) => { From b597bc5af6f2affabb5a47dfcd5f8f2e32f766fe Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 6 Dec 2020 01:20:43 -0500 Subject: [PATCH 0308/2212] [wgsl] add min/max support --- src/front/wgsl/mod.rs | 11 +++++++++++ src/front/wgsl/tests.rs | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 1b4e7a1cc..fe36e2485 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -626,6 +626,17 @@ impl Parser { }) } else { match word { + "min" | "max" => { + lexer.expect(Token::Paren('('))?; + let a = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let b = self.parse_primary_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::Call { + origin: crate::FunctionOrigin::External(word.to_string()), + arguments: vec![a, b], + }) + } "dot" => { lexer.expect(Token::Paren('('))?; let a = self.parse_primary_expression(lexer, ctx.reborrow())?; diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index b5e25891c..ccc34f229 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -6,6 +6,20 @@ fn parse_types() { assert!(parse_str("const a : x32 = 2;").is_err()); } +#[test] +fn parse_type_cast() { + parse_str( + " + const a : i32 = 2; + fn main() { + var x: f32 = f32(a); + #x = f32(i32(a + 1) / 2); //TODO + } + ", + ) + .unwrap(); +} + #[test] fn parse_if() { parse_str( From e0c2178b3f1448ea0a4b3c08dcb936fe0dd4fe47 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 6 Dec 2020 15:23:58 -0500 Subject: [PATCH 0309/2212] [spv] write down workgroup size --- src/back/spv/instructions.rs | 4 ++++ src/back/spv/writer.rs | 15 ++++++++++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index fe03a4d61..064bfa001 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -93,10 +93,14 @@ pub(super) fn instruction_entry_point( pub(super) fn instruction_execution_mode( entry_point_id: Word, execution_mode: spirv::ExecutionMode, + args: &[Word], ) -> Instruction { let mut instruction = Instruction::new(Op::ExecutionMode); instruction.add_operand(entry_point_id); instruction.add_operand(execution_mode as u32); + for arg in args { + instruction.add_operand(*arg); + } instruction } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f4d71b82f..8a5bbbd2b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -421,11 +421,20 @@ impl Writer { crate::ShaderStage::Vertex => {} crate::ShaderStage::Fragment => { let execution_mode = spirv::ExecutionMode::OriginUpperLeft; - self.try_add_capabilities(execution_mode.required_capabilities()); - super::instructions::instruction_execution_mode(function_id, execution_mode) + //self.try_add_capabilities(execution_mode.required_capabilities()); + super::instructions::instruction_execution_mode(function_id, execution_mode, &[]) .to_words(&mut self.logical_layout.execution_modes); } - crate::ShaderStage::Compute => {} + crate::ShaderStage::Compute => { + let execution_mode = spirv::ExecutionMode::LocalSize; + //self.try_add_capabilities(execution_mode.required_capabilities()); + super::instructions::instruction_execution_mode( + function_id, + execution_mode, + &entry_point.workgroup_size, + ) + .to_words(&mut self.logical_layout.execution_modes); + } } if self.writer_flags.contains(WriterFlags::DEBUG) { From 4f958bf658de7ee4e285bd40a5975136582e1113 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 6 Dec 2020 23:24:44 -0500 Subject: [PATCH 0310/2212] [msl] refactor function call parsing --- src/front/wgsl/conv.rs | 9 +++++++ src/front/wgsl/mod.rs | 57 ++++++++++++++++++++++------------------- src/front/wgsl/tests.rs | 14 +++++++++- 3 files changed, 53 insertions(+), 27 deletions(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index d3bccc7e6..674f2fee9 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -107,6 +107,7 @@ pub fn get_intrinsic(word: &str) -> Option { _ => None, } } + pub fn get_derivative(word: &str) -> Option { match word { "dpdx" => Some(crate::DerivativeAxis::X), @@ -115,3 +116,11 @@ pub fn get_derivative(word: &str) -> Option { _ => None, } } + +// Returns argument count on success +pub fn get_standard_fun(word: &str) -> Option { + match word { + "min" | "max" => Some(2), + _ => None, + } +} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index fe36e2485..98d4cc513 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -607,49 +607,54 @@ impl Parser { Token::Word(word) => { if let Some(fun) = conv::get_intrinsic(word) { lexer.expect(Token::Paren('('))?; - let argument = self.parse_primary_expression(lexer, ctx.reborrow())?; + let argument = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::Intrinsic { fun, argument }) } else if let Some(axis) = conv::get_derivative(word) { lexer.expect(Token::Paren('('))?; - let expr = self.parse_primary_expression(lexer, ctx.reborrow())?; + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::Derivative { axis, expr }) } else if let Some((kind, _width)) = conv::get_scalar_type(word) { lexer.expect(Token::Paren('('))?; - let expr = self.parse_primary_expression(lexer, ctx.reborrow())?; + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::As { expr, kind, convert: true, }) + } else if let Some(arg_count) = conv::get_standard_fun(word) { + lexer.expect(Token::Paren('('))?; + let mut arguments = Vec::with_capacity(arg_count); + for i in 0..arg_count { + let arg = self.parse_general_expression(lexer, ctx.reborrow())?; + arguments.push(arg); + lexer.expect(if i + 1 == arg_count { + Token::Paren(')') + } else { + Token::Separator(',') + })?; + } + Some(crate::Expression::Call { + origin: crate::FunctionOrigin::External(word.to_string()), + arguments, + }) } else { match word { - "min" | "max" => { - lexer.expect(Token::Paren('('))?; - let a = self.parse_primary_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let b = self.parse_primary_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Call { - origin: crate::FunctionOrigin::External(word.to_string()), - arguments: vec![a, b], - }) - } "dot" => { lexer.expect(Token::Paren('('))?; - let a = self.parse_primary_expression(lexer, ctx.reborrow())?; + let a = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let b = self.parse_primary_expression(lexer, ctx.reborrow())?; + let b = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::DotProduct(a, b)) } "cross" => { lexer.expect(Token::Paren('('))?; - let a = self.parse_primary_expression(lexer, ctx.reborrow())?; + let a = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let b = self.parse_primary_expression(lexer, ctx.reborrow())?; + let b = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::CrossProduct(a, b)) } @@ -660,7 +665,7 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = - self.parse_primary_expression(lexer, ctx.reborrow())?; + self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageSample { image: ctx.lookup_ident.lookup(image_name)?, @@ -677,9 +682,9 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = - self.parse_primary_expression(lexer, ctx.reborrow())?; + self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let level = self.parse_primary_expression(lexer, ctx.reborrow())?; + let level = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageSample { image: ctx.lookup_ident.lookup(image_name)?, @@ -696,9 +701,9 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = - self.parse_primary_expression(lexer, ctx.reborrow())?; + self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let bias = self.parse_primary_expression(lexer, ctx.reborrow())?; + let bias = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageSample { image: ctx.lookup_ident.lookup(image_name)?, @@ -715,9 +720,9 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = - self.parse_primary_expression(lexer, ctx.reborrow())?; + self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let reference = self.parse_primary_expression(lexer, ctx.reborrow())?; + let reference = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageSample { image: ctx.lookup_ident.lookup(image_name)?, @@ -733,7 +738,7 @@ impl Parser { let image = ctx.lookup_ident.lookup(image_name)?; lexer.expect(Token::Separator(','))?; let coordinate = - self.parse_primary_expression(lexer, ctx.reborrow())?; + self.parse_general_expression(lexer, ctx.reborrow())?; let is_storage = match *ctx.resolve_type(image)? { crate::TypeInner::Image { class: crate::ImageClass::Storage(_), diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index ccc34f229..5d9f4f5a3 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -13,7 +13,19 @@ fn parse_type_cast() { const a : i32 = 2; fn main() { var x: f32 = f32(a); - #x = f32(i32(a + 1) / 2); //TODO + x = f32(i32(a + 1) / 2); + } + ", + ) + .unwrap(); +} + +#[test] +fn parse_standard_fun() { + parse_str( + " + fn main() { + var x: i32 = min(max(1, 2), 3); } ", ) From 31be5402bd577dbee957a4663919f09e1ce9629a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 7 Dec 2020 22:52:00 -0500 Subject: [PATCH 0311/2212] [spv] refactor the capability checks --- examples/convert.rs | 3 +- src/back/spv/layout_tests.rs | 7 +- src/back/spv/mod.rs | 19 +- src/back/spv/writer.rs | 424 ++++++++++++++++++----------------- tests/rosetta.rs | 3 +- 5 files changed, 237 insertions(+), 219 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 779294903..2589168ab 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -177,7 +177,8 @@ fn main() { } }); - let spv = spv::write_vec(&module, debug_flag); + let capabilities = Default::default(); //TODO + let spv = spv::write_vec(&module, debug_flag, capabilities).unwrap(); let bytes = spv .iter() diff --git a/src/back/spv/layout_tests.rs b/src/back/spv/layout_tests.rs index 37024b238..c09c91495 100644 --- a/src/back/spv/layout_tests.rs +++ b/src/back/spv/layout_tests.rs @@ -1,6 +1,7 @@ -use crate::back::spv::test_framework::*; -use crate::back::spv::{helpers, Instruction, LogicalLayout, PhysicalLayout}; -use crate::Header; +use crate::{ + back::spv::{helpers, test_framework::*, Instruction, LogicalLayout, PhysicalLayout}, + Header, +}; use spirv::*; #[test] diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 65ae54a1b..011645b50 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -9,9 +9,10 @@ mod test_framework; #[cfg(test)] mod layout_tests; -pub use writer::Writer; +pub use spirv::Capability; +pub use writer::{Error, Writer}; -use spirv::*; +use spirv::Word; bitflags::bitflags! { pub struct WriterFlags: u32 { @@ -44,16 +45,20 @@ struct LogicalLayout { } pub(self) struct Instruction { - op: Op, + op: spirv::Op, wc: u32, type_id: Option, result_id: Option, operands: Vec, } -pub fn write_vec(module: &crate::Module, flags: WriterFlags) -> Vec { +pub fn write_vec( + module: &crate::Module, + flags: WriterFlags, + capabilities: crate::FastHashSet, +) -> Result, Error> { let mut words = Vec::new(); - let mut w = Writer::new(&module.header, flags); - w.write(module, &mut words); - words + let mut w = Writer::new(&module.header, flags, capabilities); + w.write(module, &mut words)?; + Ok(words) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 8a5bbbd2b..f48a7aa42 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -8,14 +8,12 @@ const BITS_PER_BYTE: crate::Bytes = 8; #[derive(Clone, Debug, Error)] pub enum Error { + #[error("one of the required capabilities {0:?} is missing")] + MissingCapabilities(Vec), #[error("can't find local variable: {0:?}")] UnknownLocalVariable(crate::LocalVariable), - #[error("bad image class for op: {0:?}")] - BadImageClass(crate::ImageClass), - #[error("not an image")] - NotImage, - #[error("empty value")] - FeatureNotImplemented(), + #[error("unimplemented {0:}")] + FeatureNotImplemented(&'static str), } struct Block { @@ -156,7 +154,7 @@ pub struct Writer { capabilities: crate::FastHashSet, debugs: Vec, annotations: Vec, - writer_flags: WriterFlags, + flags: WriterFlags, void_type: Option, lookup_type: crate::FastHashMap, lookup_function: crate::FastHashMap, Word>, @@ -169,15 +167,19 @@ pub struct Writer { type WriteExpressionOutput = (Word, LookupType); impl Writer { - pub fn new(header: &crate::Header, writer_flags: WriterFlags) -> Self { + pub fn new( + header: &crate::Header, + flags: WriterFlags, + capabilities: crate::FastHashSet, + ) -> Self { Writer { physical_layout: PhysicalLayout::new(header), logical_layout: LogicalLayout::default(), id_count: 0, - capabilities: crate::FastHashSet::default(), + capabilities, debugs: vec![], annotations: vec![], - writer_flags, + flags, void_type: None, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), @@ -192,15 +194,25 @@ impl Writer { self.id_count } - fn try_add_capabilities(&mut self, capabilities: &[spirv::Capability]) { - for capability in capabilities.iter() { - self.capabilities.insert(*capability); + fn check(&mut self, capabilities: &[spirv::Capability]) -> Result<(), Error> { + if capabilities.is_empty() + || capabilities + .iter() + .any(|cap| self.capabilities.contains(cap)) + { + Ok(()) + } else { + Err(Error::MissingCapabilities(capabilities.to_vec())) } } - fn get_type_id(&mut self, arena: &crate::Arena, lookup_ty: LookupType) -> Word { + fn get_type_id( + &mut self, + arena: &crate::Arena, + lookup_ty: LookupType, + ) -> Result { if let Entry::Occupied(e) = self.lookup_type.entry(lookup_ty) { - *e.get() + Ok(*e.get()) } else { match lookup_ty { LookupType::Handle(handle) => match arena[handle].inner { @@ -217,14 +229,13 @@ impl Writer { &mut self, handle: crate::Handle, ir_module: &crate::Module, - ) -> Word { - match self.lookup_constant.entry(handle) { - Entry::Occupied(e) => *e.get(), - _ => { - let (instruction, id) = self.write_constant_type(handle, ir_module); - instruction.to_words(&mut self.logical_layout.declarations); - id - } + ) -> Result { + if let Entry::Occupied(e) = self.lookup_constant.entry(handle) { + Ok(*e.get()) + } else { + let (instruction, id) = self.write_constant_type(handle, ir_module)?; + instruction.to_words(&mut self.logical_layout.declarations); + Ok(id) } } @@ -232,25 +243,25 @@ impl Writer { &mut self, ir_module: &crate::Module, handle: crate::Handle, - ) -> Word { - match self.lookup_global_variable.entry(handle) { + ) -> Result { + Ok(match self.lookup_global_variable.entry(handle) { Entry::Occupied(e) => *e.get(), - _ => { - let (instruction, id) = self.write_global_variable(ir_module, handle); + Entry::Vacant(_) => { + let (instruction, id) = self.write_global_variable(ir_module, handle)?; instruction.to_words(&mut self.logical_layout.declarations); id } - } + }) } fn get_function_return_type( &mut self, ty: Option>, arena: &crate::Arena, - ) -> Word { + ) -> Result { match ty { Some(handle) => self.get_type_id(arena, LookupType::Handle(handle)), - None => match self.void_type { + None => Ok(match self.void_type { Some(id) => id, None => { let id = self.generate_id(); @@ -259,7 +270,7 @@ impl Writer { .to_words(&mut self.logical_layout.declarations); id } - }, + }), } } @@ -268,10 +279,10 @@ impl Writer { arena: &crate::Arena, handle: crate::Handle, class: crate::StorageClass, - ) -> Word { + ) -> Result { let ty = &arena[handle]; - let ty_id = self.get_type_id(arena, LookupType::Handle(handle)); - match ty.inner { + let ty_id = self.get_type_id(arena, LookupType::Handle(handle))?; + Ok(match ty.inner { crate::TypeInner::Pointer { .. } => ty_id, _ => { match self @@ -295,7 +306,7 @@ impl Writer { } } } - } + }) } fn create_pointer(&mut self, ty_id: Word, class: spirv::StorageClass) -> Word { @@ -316,7 +327,7 @@ impl Writer { &mut self, ir_function: &crate::Function, ir_module: &crate::Module, - ) -> spirv::Word { + ) -> Result { let mut function = Function::new(); for (_, variable) in ir_function.local_variables.iter() { @@ -324,10 +335,10 @@ impl Writer { let init_word = variable .init - .map(|constant| self.get_constant_id(constant, ir_module)); - + .map(|constant| self.get_constant_id(constant, ir_module)) + .transpose()?; let pointer_id = - self.get_pointer_id(&ir_module.types, variable.ty, crate::StorageClass::Function); + self.get_pointer_id(&ir_module.types, variable.ty, crate::StorageClass::Function)?; function.variables.push(LocalVariable { id, name: variable.name.clone(), @@ -341,7 +352,7 @@ impl Writer { } let return_type_id = - self.get_function_return_type(ir_function.return_type, &ir_module.types); + self.get_function_return_type(ir_function.return_type, &ir_module.types)?; let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); let mut function_parameter_pointer_ids = vec![]; @@ -349,11 +360,12 @@ impl Writer { for argument in ir_function.arguments.iter() { let id = self.generate_id(); let pointer_id = - self.get_pointer_id(&ir_module.types, argument.ty, crate::StorageClass::Function); + self.get_pointer_id(&ir_module.types, argument.ty, crate::StorageClass::Function)?; function_parameter_pointer_ids.push(pointer_id); - parameter_type_ids - .push(self.get_type_id(&ir_module.types, LookupType::Handle(argument.ty))); + let parameter_type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(argument.ty))?; + parameter_type_ids.push(parameter_type_id); function .parameters .push(super::instructions::instruction_function_parameter( @@ -376,13 +388,13 @@ impl Writer { function_type, )); - self.write_block(&ir_function.body, ir_module, ir_function, &mut function); + self.write_block(&ir_function.body, ir_module, ir_function, &mut function)?; function.to_words(&mut self.logical_layout.function_definitions); super::instructions::instruction_function_end() .to_words(&mut self.logical_layout.function_definitions); - function_id + Ok(function_id) } // TODO Move to instructions module @@ -392,14 +404,8 @@ impl Writer { stage: crate::ShaderStage, name: &str, ir_module: &crate::Module, - ) -> Instruction { - let function_id = self.write_function(&entry_point.function, ir_module); - - let exec_model = match stage { - crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, - crate::ShaderStage::Fragment { .. } => spirv::ExecutionModel::Fragment, - crate::ShaderStage::Compute { .. } => spirv::ExecutionModel::GLCompute, - }; + ) -> Result { + let function_id = self.write_function(&entry_point.function, ir_module)?; let mut interface_ids = vec![]; for ((handle, _), &usage) in ir_module @@ -411,43 +417,45 @@ impl Writer { .zip(&entry_point.function.global_usage) { if usage.contains(crate::GlobalUse::STORE) || usage.contains(crate::GlobalUse::LOAD) { - let id = self.get_global_variable_id(ir_module, handle); + let id = self.get_global_variable_id(ir_module, handle)?; interface_ids.push(id); } } - self.try_add_capabilities(exec_model.required_capabilities()); - match stage { - crate::ShaderStage::Vertex => {} + let exec_model = match stage { + crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, crate::ShaderStage::Fragment => { let execution_mode = spirv::ExecutionMode::OriginUpperLeft; - //self.try_add_capabilities(execution_mode.required_capabilities()); + self.check(execution_mode.required_capabilities())?; super::instructions::instruction_execution_mode(function_id, execution_mode, &[]) .to_words(&mut self.logical_layout.execution_modes); + spirv::ExecutionModel::Fragment } crate::ShaderStage::Compute => { let execution_mode = spirv::ExecutionMode::LocalSize; - //self.try_add_capabilities(execution_mode.required_capabilities()); + self.check(execution_mode.required_capabilities())?; super::instructions::instruction_execution_mode( function_id, execution_mode, &entry_point.workgroup_size, ) .to_words(&mut self.logical_layout.execution_modes); + spirv::ExecutionModel::GLCompute } - } + }; + self.check(exec_model.required_capabilities())?; - if self.writer_flags.contains(WriterFlags::DEBUG) { + if self.flags.contains(WriterFlags::DEBUG) { self.debugs .push(super::instructions::instruction_name(function_id, name)); } - super::instructions::instruction_entry_point( + Ok(super::instructions::instruction_entry_point( exec_model, function_id, name, interface_ids.as_slice(), - ) + )) } fn write_scalar(&self, id: Word, kind: crate::ScalarKind, width: crate::Bytes) -> Instruction { @@ -490,33 +498,35 @@ impl Writer { &mut self, arena: &crate::Arena, local_ty: LocalType, - ) -> Word { + ) -> Result { let id = self.generate_id(); let instruction = match local_ty { LocalType::Void => unreachable!(), LocalType::Scalar { kind, width } => self.write_scalar(id, kind, width), LocalType::Vector { size, kind, width } => { let scalar_id = - self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width })); + self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width }))?; super::instructions::instruction_type_vector(id, scalar_id, size) } - LocalType::Pointer { .. } => unimplemented!(), + LocalType::Pointer { .. } => { + return Err(Error::FeatureNotImplemented("pointer declaration")) + } LocalType::SampledImage { image_type } => { - let image_type_id = self.get_type_id(arena, LookupType::Handle(image_type)); + let image_type_id = self.get_type_id(arena, LookupType::Handle(image_type))?; super::instructions::instruction_type_sampled_image(id, image_type_id) } }; self.lookup_type.insert(LookupType::Local(local_ty), id); instruction.to_words(&mut self.logical_layout.declarations); - id + Ok(id) } fn write_type_declaration_arena( &mut self, arena: &crate::Arena, handle: crate::Handle, - ) -> Word { + ) -> Result { let ty = &arena[handle]; let id = self.generate_id(); @@ -528,7 +538,7 @@ impl Writer { } crate::TypeInner::Vector { size, kind, width } => { let scalar_id = - self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width })); + self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width }))?; self.lookup_type.insert( LookupType::Local(LocalType::Vector { size, kind, width }), id, @@ -547,7 +557,7 @@ impl Writer { kind: crate::ScalarKind::Float, width, }), - ); + )?; super::instructions::instruction_type_matrix(id, vector_id, columns) } crate::TypeInner::Image { @@ -569,9 +579,9 @@ impl Writer { width, }, }; - let type_id = self.get_type_id(arena, LookupType::Local(local_type)); + let type_id = self.get_type_id(arena, LookupType::Local(local_type))?; let dim = map_dim(dim); - self.try_add_capabilities(dim.required_capabilities()); + self.check(dim.required_capabilities())?; super::instructions::instruction_type_image(id, type_id, dim, arrayed, class) } crate::TypeInner::Sampler { comparison: _ } => { @@ -587,7 +597,7 @@ impl Writer { )); } - let type_id = self.get_type_id(arena, LookupType::Handle(base)); + let type_id = self.get_type_id(arena, LookupType::Handle(base))?; match size { crate::ArraySize::Constant(const_handle) => { let length_id = self.lookup_constant[&const_handle]; @@ -601,13 +611,13 @@ impl Writer { crate::TypeInner::Struct { ref members } => { let mut member_ids = Vec::with_capacity(members.len()); for member in members { - let member_id = self.get_type_id(arena, LookupType::Handle(member.ty)); + let member_id = self.get_type_id(arena, LookupType::Handle(member.ty))?; member_ids.push(member_id); } super::instructions::instruction_type_struct(id, member_ids.as_slice()) } crate::TypeInner::Pointer { base, class } => { - let type_id = self.get_type_id(arena, LookupType::Handle(base)); + let type_id = self.get_type_id(arena, LookupType::Handle(base))?; self.lookup_type .insert(LookupType::Local(LocalType::Pointer { base, class }), id); super::instructions::instruction_type_pointer( @@ -620,25 +630,25 @@ impl Writer { self.lookup_type.insert(LookupType::Handle(handle), id); instruction.to_words(&mut self.logical_layout.declarations); - id + Ok(id) } fn write_constant_type( &mut self, handle: crate::Handle, ir_module: &crate::Module, - ) -> (Instruction, Word) { + ) -> Result<(Instruction, Word), Error> { let id = self.generate_id(); self.lookup_constant.insert(handle, id); let constant = &ir_module.constants[handle]; let arena = &ir_module.types; - match constant.inner { + let instruction = match constant.inner { crate::ConstantInner::Sint(val) => { let ty = &ir_module.types[constant.ty]; - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; - let instruction = match ty.inner { + match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { 4 => super::instructions::instruction_constant(type_id, id, &[val as u32]), 8 => { @@ -648,14 +658,13 @@ impl Writer { _ => unreachable!(), }, _ => unreachable!(), - }; - (instruction, id) + } } crate::ConstantInner::Uint(val) => { let ty = &ir_module.types[constant.ty]; - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; - let instruction = match ty.inner { + match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { 4 => super::instructions::instruction_constant(type_id, id, &[val as u32]), 8 => { @@ -665,15 +674,13 @@ impl Writer { _ => unreachable!(), }, _ => unreachable!(), - }; - - (instruction, id) + } } crate::ConstantInner::Float(val) => { let ty = &ir_module.types[constant.ty]; - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; - let instruction = match ty.inner { + match ty.inner { crate::TypeInner::Scalar { kind: _, width } => match width { 4 => super::instructions::instruction_constant( type_id, @@ -688,58 +695,57 @@ impl Writer { _ => unreachable!(), }, _ => unreachable!(), - }; - (instruction, id) + } } crate::ConstantInner::Bool(val) => { - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; - let instruction = if val { + if val { super::instructions::instruction_constant_true(type_id, id) } else { super::instructions::instruction_constant_false(type_id, id) - }; - - (instruction, id) + } } crate::ConstantInner::Composite(ref constituents) => { let mut constituent_ids = Vec::with_capacity(constituents.len()); for constituent in constituents.iter() { - let constituent_id = self.get_constant_id(*constituent, &ir_module); + let constituent_id = self.get_constant_id(*constituent, &ir_module)?; constituent_ids.push(constituent_id); } - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty)); - let instruction = super::instructions::instruction_constant_composite( + let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; + super::instructions::instruction_constant_composite( type_id, id, constituent_ids.as_slice(), - ); - (instruction, id) + ) } - } + }; + + Ok((instruction, id)) } fn write_global_variable( &mut self, ir_module: &crate::Module, handle: crate::Handle, - ) -> (Instruction, Word) { + ) -> Result<(Instruction, Word), Error> { let global_variable = &ir_module.global_variables[handle]; let id = self.generate_id(); let class = self.parse_to_spirv_storage_class(global_variable.class); - self.try_add_capabilities(class.required_capabilities()); + self.check(class.required_capabilities())?; let init_word = global_variable .init - .map(|constant| self.get_constant_id(constant, ir_module)); + .map(|constant| self.get_constant_id(constant, ir_module)) + .transpose()?; let pointer_id = - self.get_pointer_id(&ir_module.types, global_variable.ty, global_variable.class); + self.get_pointer_id(&ir_module.types, global_variable.ty, global_variable.class)?; let instruction = super::instructions::instruction_variable(pointer_id, id, class, init_word); - if self.writer_flags.contains(WriterFlags::DEBUG) { + if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = global_variable.name { self.debugs .push(super::instructions::instruction_name(id, name.as_str())); @@ -819,7 +825,7 @@ impl Writer { // TODO Initializer is optional and not (yet) included in the IR self.lookup_global_variable.insert(handle, id); - (instruction, id) + Ok((instruction, id)) } fn get_function_type( @@ -919,14 +925,14 @@ impl Writer { let scalar_id = self.get_type_id( &ir_module.types, LookupType::Local(LocalType::Scalar { kind, width }), - ); + )?; ( self.create_pointer(scalar_id, spirv::StorageClass::Function), scalar_id, LookupType::Local(LocalType::Scalar { kind, width }), ) } - _ => unimplemented!(), + _ => return Err(Error::FeatureNotImplemented("accessing of non-vector")), }; block @@ -947,15 +953,13 @@ impl Writer { } crate::Expression::AccessIndex { base, index } => { let id = self.generate_id(); - let (base_id, base_lookup_ty) = self - .write_expression( - ir_module, - ir_function, - &ir_function.expressions[base], - block, - function, - ) - .unwrap(); + let (base_id, base_lookup_ty) = self.write_expression( + ir_module, + ir_function, + &ir_function.expressions[base], + block, + function, + )?; let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); @@ -964,7 +968,7 @@ impl Writer { let scalar_id = self.get_type_id( &ir_module.types, LookupType::Local(LocalType::Scalar { kind, width }), - ); + )?; ( self.create_pointer(scalar_id, spirv::StorageClass::Function), scalar_id, @@ -974,14 +978,18 @@ impl Writer { crate::TypeInner::Struct { ref members } => { let member = &members[index as usize]; let type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(member.ty)); + self.get_type_id(&ir_module.types, LookupType::Handle(member.ty))?; ( self.create_pointer(type_id, spirv::StorageClass::Uniform), type_id, LookupType::Handle(member.ty), ) } - _ => unimplemented!(), + _ => { + return Err(Error::FeatureNotImplemented( + "accessing index of non vector or struct", + )) + } }; let const_ty_id = self.get_type_id( @@ -990,7 +998,7 @@ impl Writer { kind: crate::ScalarKind::Sint, width: 4, }), - ); + )?; let const_id = self.create_constant(const_ty_id, &[index]); block @@ -1011,17 +1019,17 @@ impl Writer { } crate::Expression::GlobalVariable(handle) => { let var = &ir_module.global_variables[handle]; - let id = self.get_global_variable_id(&ir_module, handle); + let id = self.get_global_variable_id(&ir_module, handle)?; Ok((id, LookupType::Handle(var.ty))) } crate::Expression::Constant(handle) => { let var = &ir_module.constants[handle]; - let id = self.get_constant_id(handle, ir_module); + let id = self.get_constant_id(handle, ir_module)?; Ok((id, LookupType::Handle(var.ty))) } crate::Expression::Compose { ty, ref components } => { - let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty)); + let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty))?; let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { @@ -1039,7 +1047,7 @@ impl Writer { | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); block.body.push(super::instructions::instruction_load( - self.get_type_id(&ir_module.types, component_local_ty), + self.get_type_id(&ir_module.types, component_local_ty)?, load_id, component_id, None, @@ -1069,7 +1077,7 @@ impl Writer { kind: crate::ScalarKind::Float, size: columns, }), - ); + )?; let capacity = match rows { crate::VectorSize::Bi => 2, @@ -1120,9 +1128,9 @@ impl Writer { let left_ty_inner = self.get_type_inner(&ir_module.types, left_lookup_ty); let right_ty_inner = self.get_type_inner(&ir_module.types, right_lookup_ty); - let left_result_type_id = self.get_type_id(&ir_module.types, left_lookup_ty); + let left_result_type_id = self.get_type_id(&ir_module.types, left_lookup_ty)?; - let right_result_type_id = self.get_type_id(&ir_module.types, right_lookup_ty); + let right_result_type_id = self.get_type_id(&ir_module.types, right_lookup_ty)?; let left_id = match *left_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { @@ -1221,7 +1229,10 @@ impl Writer { _ => unreachable!(), }, crate::BinaryOperator::And => (spirv::Op::BitwiseAnd, left_lookup_ty), - _ => unimplemented!("{:?}", op), + _ => { + log::error!("unimplemented {:?}", op); + return Err(Error::FeatureNotImplemented("binary operator")); + } }; block.body.push(super::instructions::instruction_binary( @@ -1244,7 +1255,7 @@ impl Writer { } crate::Expression::FunctionArgument(index) => { let handle = ir_function.arguments[index as usize].ty; - let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(handle)); + let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(handle))?; let load_id = self.generate_id(); block.body.push(super::instructions::instruction_load( @@ -1287,7 +1298,7 @@ impl Writer { &ir_module.types, handle, crate::StorageClass::Function, - ); + )?; let variable_id = self.generate_id(); function.variables.push(LocalVariable { @@ -1309,7 +1320,7 @@ impl Writer { } let return_type_id = self - .get_function_return_type(origin_function.return_type, &ir_module.types); + .get_function_return_type(origin_function.return_type, &ir_module.types)?; block .body @@ -1326,7 +1337,10 @@ impl Writer { }; Ok((id, result_type)) } - _ => unimplemented!("{:?}", origin), + crate::FunctionOrigin::External(ref string) => { + log::error!("unimplemented stdlib function {}", string); + Err(Error::FeatureNotImplemented("stdlib function")) + } }, crate::Expression::As { expr, @@ -1334,7 +1348,7 @@ impl Writer { convert, } => { if !convert { - return Err(Error::FeatureNotImplemented()); + return Err(Error::FeatureNotImplemented("bitcast")); } let (expr_id, expr_type) = self.write_expression( @@ -1374,7 +1388,7 @@ impl Writer { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); - let kind_type_id = self.get_type_id(&ir_module.types, expr_type); + let kind_type_id = self.get_type_id(&ir_module.types, expr_type)?; block.body.push(super::instructions::instruction_load( kind_type_id, load_id, @@ -1390,7 +1404,7 @@ impl Writer { }; let id = self.generate_id(); - let kind_type_id = self.get_type_id(&ir_module.types, lookup_type); + let kind_type_id = self.get_type_id(&ir_module.types, lookup_type)?; let instruction = super::instructions::instruction_unary(op, kind_type_id, id, expr_id); block.body.push(instruction); @@ -1414,7 +1428,7 @@ impl Writer { function, )?; - let image_result_type_id = self.get_type_id(&ir_module.types, image_lookup_ty); + let image_result_type_id = self.get_type_id(&ir_module.types, image_lookup_ty)?; let image_id = match *image_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); @@ -1440,7 +1454,7 @@ impl Writer { LookupType::Local(LocalType::SampledImage { image_type: image_ty, }), - ); + )?; // sampler let sampler_expression = &ir_function.expressions[sampler]; @@ -1452,7 +1466,8 @@ impl Writer { function, )?; - let sampler_result_type_id = self.get_type_id(&ir_module.types, sampler_lookup_ty); + let sampler_result_type_id = + self.get_type_id(&ir_module.types, sampler_lookup_ty)?; let sampler_id = match *sampler_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); @@ -1478,7 +1493,7 @@ impl Writer { )?; let coordinate_result_type_id = - self.get_type_id(&ir_module.types, coordinate_lookup_ty); + self.get_type_id(&ir_module.types, coordinate_lookup_ty)?; let coordinate_id = match *coordinate_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); @@ -1495,8 +1510,8 @@ impl Writer { // component kind let image_type = &ir_module.types[image_ty]; - let image_sample_result_type = - if let crate::TypeInner::Image { class, .. } = image_type.inner { + let image_sample_result_type = match image_type.inner { + crate::TypeInner::Image { class, .. } => { let width = 4; LookupType::Local(match class { crate::ImageClass::Sampled { kind, multi: _ } => LocalType::Vector { @@ -1508,11 +1523,13 @@ impl Writer { kind: crate::ScalarKind::Float, width, }, - _ => return Err(Error::BadImageClass(class)), + crate::ImageClass::Storage(_) => { + unimplemented!("Unexpected storage image being sampled") + } }) - } else { - return Err(Error::NotImage); - }; + } + ref other => unimplemented!("Unexpected image type {:?}", other), + }; let sampled_image_id = self.generate_id(); block @@ -1525,7 +1542,7 @@ impl Writer { )); let id = self.generate_id(); let image_sample_result_type_id = - self.get_type_id(&ir_module.types, image_sample_result_type); + self.get_type_id(&ir_module.types, image_sample_result_type)?; block .body .push(super::instructions::instruction_image_sample_implicit_lod( @@ -1536,7 +1553,10 @@ impl Writer { )); Ok((id, image_sample_result_type)) } - _ => unimplemented!("{:?}", expression), + _ => { + log::error!("unimplemented {:?}", expression); + Err(Error::FeatureNotImplemented("expression")) + } } } @@ -1546,7 +1566,7 @@ impl Writer { ir_module: &crate::Module, ir_function: &crate::Function, function: &mut Function, - ) -> spirv::Word { + ) -> Result { let mut block = Block::new(); let id = self.generate_id(); block.label = Some(super::instructions::instruction_label(id)); @@ -1556,28 +1576,27 @@ impl Writer { crate::Statement::Block(ref ir_block) => { if !ir_block.is_empty() { //TODO: link the block with `OpBranch` - self.write_block(ir_block, ir_module, ir_function, function); + self.write_block(ir_block, ir_module, ir_function, function)?; } } crate::Statement::Return { value } => { block.termination = Some(match ir_function.return_type { Some(_) => { let expression = &ir_function.expressions[value.unwrap()]; - let (id, lookup_ty) = self - .write_expression( - ir_module, - ir_function, - expression, - &mut block, - function, - ) - .unwrap(); + let (id, lookup_ty) = self.write_expression( + ir_module, + ir_function, + expression, + &mut block, + function, + )?; let id = match *expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); - let value_ty_id = self.get_type_id(&ir_module.types, lookup_ty); + let value_ty_id = + self.get_type_id(&ir_module.types, lookup_ty)?; block.body.push(super::instructions::instruction_load( value_ty_id, load_id, @@ -1597,30 +1616,27 @@ impl Writer { crate::Statement::Store { pointer, value } => { let pointer_expression = &ir_function.expressions[pointer]; let value_expression = &ir_function.expressions[value]; - let (pointer_id, _) = self - .write_expression( - ir_module, - ir_function, - pointer_expression, - &mut block, - function, - ) - .unwrap(); - let (value_id, value_lookup_ty) = self - .write_expression( - ir_module, - ir_function, - value_expression, - &mut block, - function, - ) - .unwrap(); + let (pointer_id, _) = self.write_expression( + ir_module, + ir_function, + pointer_expression, + &mut block, + function, + )?; + let (value_id, value_lookup_ty) = self.write_expression( + ir_module, + ir_function, + value_expression, + &mut block, + function, + )?; let value_id = match value_expression { crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { let load_id = self.generate_id(); - let value_ty_id = self.get_type_id(&ir_module.types, value_lookup_ty); + let value_ty_id = + self.get_type_id(&ir_module.types, value_lookup_ty)?; block.body.push(super::instructions::instruction_load( value_ty_id, load_id, @@ -1636,24 +1652,27 @@ impl Writer { pointer_id, value_id, None, )); } - _ => unimplemented!("{:?}", statement), + _ => { + log::error!("unimplemented {:?}", statement); + return Err(Error::FeatureNotImplemented("statement")); + } } } function.blocks.push(block); - id + Ok(id) } fn write_physical_layout(&mut self) { self.physical_layout.bound = self.id_count + 1; } - fn write_logical_layout(&mut self, ir_module: &crate::Module) { + fn write_logical_layout(&mut self, ir_module: &crate::Module) -> Result<(), Error> { let id = self.generate_id(); super::instructions::instruction_ext_inst_import(id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); - if self.writer_flags.contains(WriterFlags::DEBUG) { + if self.flags.contains(WriterFlags::DEBUG) { self.debugs.push(super::instructions::instruction_source( spirv::SourceLanguage::GLSL, 450, @@ -1661,13 +1680,13 @@ impl Writer { } for (handle, ir_function) in ir_module.functions.iter() { - let id = self.write_function(ir_function, ir_module); + let id = self.write_function(ir_function, ir_module)?; self.lookup_function.insert(handle, id); } for (&(stage, ref name), ir_ep) in ir_module.entry_points.iter() { - let entry_point_instruction = self.write_entry_point(ir_ep, stage, name, ir_module); - entry_point_instruction.to_words(&mut self.logical_layout.entry_points); + let ep_instruction = self.write_entry_point(ir_ep, stage, name, ir_module)?; + ep_instruction.to_words(&mut self.logical_layout.entry_points); } for capability in self.capabilities.iter() { @@ -1677,13 +1696,13 @@ impl Writer { let addressing_model = spirv::AddressingModel::Logical; let memory_model = spirv::MemoryModel::GLSL450; - self.try_add_capabilities(addressing_model.required_capabilities()); - self.try_add_capabilities(memory_model.required_capabilities()); + self.check(addressing_model.required_capabilities())?; + self.check(memory_model.required_capabilities())?; super::instructions::instruction_memory_model(addressing_model, memory_model) .to_words(&mut self.logical_layout.memory_model); - if self.writer_flags.contains(WriterFlags::DEBUG) { + if self.flags.contains(WriterFlags::DEBUG) { for debug in self.debugs.iter() { debug.to_words(&mut self.logical_layout.debugs); } @@ -1692,14 +1711,17 @@ impl Writer { for annotation in self.annotations.iter() { annotation.to_words(&mut self.logical_layout.annotations); } + + Ok(()) } - pub fn write(&mut self, ir_module: &crate::Module, words: &mut Vec) { - self.write_logical_layout(ir_module); + pub fn write(&mut self, ir_module: &crate::Module, words: &mut Vec) -> Result<(), Error> { + self.write_logical_layout(ir_module)?; self.write_physical_layout(); self.physical_layout.in_words(words); self.logical_layout.in_words(words); + Ok(()) } } @@ -1717,18 +1739,6 @@ mod tests { assert_eq!(writer.id_count, 1); } - #[test] - fn test_try_add_capabilities() { - let mut writer = create_writer(); - - assert_eq!(writer.capabilities.len(), 0); - writer.try_add_capabilities(&[spirv::Capability::Shader]); - assert_eq!(writer.capabilities.len(), 1); - - writer.try_add_capabilities(&[spirv::Capability::Shader]); - assert_eq!(writer.capabilities.len(), 1); - } - #[test] fn test_write_physical_layout() { let mut writer = create_writer(); @@ -1742,6 +1752,6 @@ mod tests { generator: 0, version: (1, 0, 0), }; - Writer::new(&header, WriterFlags::NONE) + Writer::new(&header, WriterFlags::NONE, Default::default()) } } diff --git a/tests/rosetta.rs b/tests/rosetta.rs index 117a74da3..9f3c571bf 100644 --- a/tests/rosetta.rs +++ b/tests/rosetta.rs @@ -13,7 +13,8 @@ fn test_rosetta(dir_name: &str) { #[cfg(feature = "spv-out")] { - let spv = spv::write_vec(&module, spv::WriterFlags::NONE); + let capabilities = Some(spirv::Capability::Shader).into_iter().collect(); + let spv = spv::write_vec(&module, spv::WriterFlags::NONE, capabilities).unwrap(); assert!(spv.len() > 0); } } From 548bafaf40912908a0057fba396948cbddde4579 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 7 Dec 2020 23:02:00 -0500 Subject: [PATCH 0312/2212] [spv] refactor local variables --- src/back/spv/writer.rs | 95 +++++++++--------------------------------- 1 file changed, 19 insertions(+), 76 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f48a7aa42..3c8186e87 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -10,51 +10,31 @@ const BITS_PER_BYTE: crate::Bytes = 8; pub enum Error { #[error("one of the required capabilities {0:?} is missing")] MissingCapabilities(Vec), - #[error("can't find local variable: {0:?}")] - UnknownLocalVariable(crate::LocalVariable), #[error("unimplemented {0:}")] FeatureNotImplemented(&'static str), } +#[derive(Default)] struct Block { label: Option, body: Vec, termination: Option, } -impl Block { - pub fn new() -> Self { - Block { - label: None, - body: vec![], - termination: None, - } - } -} - struct LocalVariable { id: Word, - name: Option, instruction: Instruction, } +#[derive(Default)] struct Function { signature: Option, parameters: Vec, - variables: Vec, + variables: crate::FastHashMap, LocalVariable>, blocks: Vec, } impl Function { - pub fn new() -> Self { - Function { - signature: None, - parameters: vec![], - variables: vec![], - blocks: vec![], - } - } - fn to_words(&self, sink: &mut impl Extend) { self.signature.as_ref().unwrap().to_words(sink); for instruction in self.parameters.iter() { @@ -63,7 +43,7 @@ impl Function { for (index, block) in self.blocks.iter().enumerate() { block.label.as_ref().unwrap().to_words(sink); if index == 0 { - for local_var in self.variables.iter() { + for local_var in self.variables.values() { local_var.instruction.to_words(sink); } } @@ -328,9 +308,9 @@ impl Writer { ir_function: &crate::Function, ir_module: &crate::Module, ) -> Result { - let mut function = Function::new(); + let mut function = Function::default(); - for (_, variable) in ir_function.local_variables.iter() { + for (handle, variable) in ir_function.local_variables.iter() { let id = self.generate_id(); let init_word = variable @@ -339,16 +319,15 @@ impl Writer { .transpose()?; let pointer_id = self.get_pointer_id(&ir_module.types, variable.ty, crate::StorageClass::Function)?; - function.variables.push(LocalVariable { + let instruction = super::instructions::instruction_variable( + pointer_id, id, - name: variable.name.clone(), - instruction: super::instructions::instruction_variable( - pointer_id, - id, - spirv::StorageClass::Function, - init_word, - ), - }); + spirv::StorageClass::Function, + init_word, + ); + function + .variables + .insert(handle, LocalVariable { id, instruction }); } let return_type_id = @@ -1246,12 +1225,8 @@ impl Writer { } crate::Expression::LocalVariable(variable) => { let var = &ir_function.local_variables[variable]; - function - .variables - .iter() - .find(|&v| v.name.as_ref().unwrap() == var.name.as_ref().unwrap()) - .map(|local_var| (local_var.id, LookupType::Handle(var.ty))) - .ok_or_else(|| Error::UnknownLocalVariable(var.clone())) + let local_var = &function.variables[&variable]; + Ok((local_var.id, LookupType::Handle(var.ty))) } crate::Expression::FunctionArgument(index) => { let handle = ir_function.arguments[index as usize].ty; @@ -1277,46 +1252,14 @@ impl Writer { for argument in arguments { let expression = &ir_function.expressions[*argument]; - let (id, lookup_ty) = self.write_expression( + let (arg_id, _) = self.write_expression( ir_module, ir_function, expression, block, function, )?; - - // Create variable - OpVariable - // Store value to variable - OpStore - // Use id of variable - - let handle = match lookup_ty { - LookupType::Handle(handle) => handle, - LookupType::Local(_) => unreachable!(), - }; - - let pointer_id = self.get_pointer_id( - &ir_module.types, - handle, - crate::StorageClass::Function, - )?; - - let variable_id = self.generate_id(); - function.variables.push(LocalVariable { - id: variable_id, - name: None, - instruction: super::instructions::instruction_variable( - pointer_id, - variable_id, - spirv::StorageClass::Function, - None, - ), - }); - block.body.push(super::instructions::instruction_store( - variable_id, - id, - None, - )); - argument_ids.push(variable_id); + argument_ids.push(arg_id); } let return_type_id = self @@ -1567,7 +1510,7 @@ impl Writer { ir_function: &crate::Function, function: &mut Function, ) -> Result { - let mut block = Block::new(); + let mut block = Block::default(); let id = self.generate_id(); block.label = Some(super::instructions::instruction_label(id)); From 148fac0601775048a90a4c010f76845c429ed1c6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 8 Dec 2020 00:16:47 -0500 Subject: [PATCH 0313/2212] [spv] enable quad conversion test, refactor binary operations --- Cargo.toml | 3 +- examples/convert.rs | 20 ++++---- src/back/spv/writer.rs | 99 +++++++++++++++++++++------------------ test-data/boids.param.ron | 3 +- test-data/quad.param.ron | 3 +- tests/convert.rs | 15 ++++++ 6 files changed, 86 insertions(+), 57 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 55d65a753..b6ac07d55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ bitflags = "1" fxhash = "0.2" log = "0.4" num-traits = "0.2" -spirv = { package = "spirv_headers", version = "1.4.2", optional = true } +spirv = { package = "spirv_headers", version = "1.5", optional = true } pomelo = { version = "0.1.4", optional = true } thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } @@ -37,3 +37,4 @@ difference = "2.0" env_logger = "0.6" ron = "0.6" serde = { version = "1.0", features = ["derive"] } +spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } diff --git a/examples/convert.rs b/examples/convert.rs index 2589168ab..d4801fc93 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -1,21 +1,20 @@ -use serde::{Deserialize, Serialize}; use std::{env, fs, path::Path}; -#[derive(Hash, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Hash, PartialEq, Eq, serde::Deserialize)] enum Stage { Vertex, Fragment, Compute, } -#[derive(Hash, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Hash, PartialEq, Eq, serde::Deserialize)] struct BindSource { stage: Stage, group: u32, binding: u32, } -#[derive(Serialize, Deserialize)] +#[derive(serde::Deserialize)] struct BindTarget { #[serde(default)] buffer: Option, @@ -27,11 +26,15 @@ struct BindTarget { mutable: bool, } -#[derive(Default, Serialize, Deserialize)] +#[derive(Default, serde::Deserialize)] struct Parameters { #[serde(default)] + #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_flow_dump_prefix: String, - metal_bindings: naga::FastHashMap, + #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + spv_capabilities: naga::FastHashSet, + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] + mtl_bindings: naga::FastHashMap, } fn main() { @@ -138,7 +141,7 @@ fn main() { "metal" => { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); - for (key, value) in params.metal_bindings { + for (key, value) in params.mtl_bindings { binding_map.insert( msl::BindSource { stage: match key.stage { @@ -177,8 +180,7 @@ fn main() { } }); - let capabilities = Default::default(); //TODO - let spv = spv::write_vec(&module, debug_flag, capabilities).unwrap(); + let spv = spv::write_vec(&module, debug_flag, params.spv_capabilities).unwrap(); let bytes = spv .iter() diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 3c8186e87..50d354dc9 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -112,6 +112,7 @@ impl<'a, T> ops::Deref for MaybeOwned<'a, T> { } } +#[derive(Debug)] enum Dimension { Scalar, Vector, @@ -1101,14 +1102,10 @@ impl Writer { function, )?; - let left_lookup_ty = left_lookup_ty; - let right_lookup_ty = right_lookup_ty; - let left_ty_inner = self.get_type_inner(&ir_module.types, left_lookup_ty); let right_ty_inner = self.get_type_inner(&ir_module.types, right_lookup_ty); let left_result_type_id = self.get_type_id(&ir_module.types, left_lookup_ty)?; - let right_result_type_id = self.get_type_id(&ir_module.types, right_lookup_ty)?; let left_id = match *left_expression { @@ -1143,56 +1140,63 @@ impl Writer { let left_dimension = get_dimension(&left_ty_inner); let right_dimension = get_dimension(&right_ty_inner); - let (spirv_op, lookup_ty) = match op { + let mut result_side_left = true; + let mut preserve_order = true; + + let spirv_op = match op { crate::BinaryOperator::Add => match *left_ty_inner { crate::TypeInner::Scalar { kind, .. } | crate::TypeInner::Vector { kind, .. } => match kind { - crate::ScalarKind::Float => (spirv::Op::FAdd, left_lookup_ty), - _ => (spirv::Op::IAdd, left_lookup_ty), + crate::ScalarKind::Float => spirv::Op::FAdd, + _ => spirv::Op::IAdd, }, _ => unreachable!(), }, crate::BinaryOperator::Subtract => match *left_ty_inner { crate::TypeInner::Scalar { kind, .. } | crate::TypeInner::Vector { kind, .. } => match kind { - crate::ScalarKind::Float => (spirv::Op::FSub, left_lookup_ty), - _ => (spirv::Op::ISub, left_lookup_ty), + crate::ScalarKind::Float => spirv::Op::FSub, + _ => spirv::Op::ISub, }, _ => unreachable!(), }, - crate::BinaryOperator::Multiply => match (left_dimension, right_dimension) { - (Dimension::Vector, Dimension::Scalar { .. }) => { - (spirv::Op::VectorTimesScalar, left_lookup_ty) + crate::BinaryOperator::Multiply => { + // whenever there is a vector on the right, + // the result type is a vector. + if let Dimension::Vector = right_dimension { + result_side_left = false; } - (Dimension::Vector, Dimension::Matrix) => { - (spirv::Op::VectorTimesMatrix, left_lookup_ty) + match (left_dimension, right_dimension) { + (Dimension::Scalar, Dimension::Vector { .. }) => { + preserve_order = false; + spirv::Op::VectorTimesScalar + } + (Dimension::Vector, Dimension::Scalar { .. }) => { + spirv::Op::VectorTimesScalar + } + (Dimension::Vector, Dimension::Matrix) => spirv::Op::VectorTimesMatrix, + (Dimension::Matrix, Dimension::Scalar { .. }) => { + spirv::Op::MatrixTimesScalar + } + (Dimension::Matrix, Dimension::Vector) => spirv::Op::MatrixTimesVector, + (Dimension::Matrix, Dimension::Matrix) => spirv::Op::MatrixTimesMatrix, + (Dimension::Vector, Dimension::Vector) + | (Dimension::Scalar, Dimension::Scalar) + if left_ty_inner.scalar_kind() + == Some(crate::ScalarKind::Float) => + { + spirv::Op::FMul + } + (Dimension::Vector, Dimension::Vector) + | (Dimension::Scalar, Dimension::Scalar) => spirv::Op::IMul, + other => unreachable!("Mul {:?}", other), } - (Dimension::Matrix, Dimension::Scalar { .. }) => { - (spirv::Op::MatrixTimesScalar, left_lookup_ty) - } - (Dimension::Matrix, Dimension::Vector) => { - (spirv::Op::MatrixTimesVector, right_lookup_ty) - } - (Dimension::Matrix, Dimension::Matrix) => { - (spirv::Op::MatrixTimesMatrix, left_lookup_ty) - } - (Dimension::Vector, Dimension::Vector) - | (Dimension::Scalar, Dimension::Scalar) - if left_ty_inner.scalar_kind() == Some(crate::ScalarKind::Float) => - { - (spirv::Op::FMul, left_lookup_ty) - } - (Dimension::Vector, Dimension::Vector) - | (Dimension::Scalar, Dimension::Scalar) => { - (spirv::Op::IMul, left_lookup_ty) - } - _ => unreachable!(), - }, + } crate::BinaryOperator::Divide => match *left_ty_inner { crate::TypeInner::Scalar { kind, .. } | crate::TypeInner::Vector { kind, .. } => match kind { - crate::ScalarKind::Sint => (spirv::Op::SDiv, left_lookup_ty), - crate::ScalarKind::Uint => (spirv::Op::UDiv, left_lookup_ty), + crate::ScalarKind::Sint => spirv::Op::SDiv, + crate::ScalarKind::Uint => spirv::Op::UDiv, _ => unreachable!(), }, _ => unreachable!(), @@ -1200,28 +1204,33 @@ impl Writer { crate::BinaryOperator::Modulo => match *left_ty_inner { crate::TypeInner::Scalar { kind, .. } | crate::TypeInner::Vector { kind, .. } => match kind { - crate::ScalarKind::Sint => (spirv::Op::SMod, left_lookup_ty), - crate::ScalarKind::Uint => (spirv::Op::UMod, left_lookup_ty), - crate::ScalarKind::Float => (spirv::Op::FMod, left_lookup_ty), + crate::ScalarKind::Sint => spirv::Op::SMod, + crate::ScalarKind::Uint => spirv::Op::UMod, + crate::ScalarKind::Float => spirv::Op::FMod, _ => unreachable!(), }, _ => unreachable!(), }, - crate::BinaryOperator::And => (spirv::Op::BitwiseAnd, left_lookup_ty), + crate::BinaryOperator::And => spirv::Op::BitwiseAnd, _ => { log::error!("unimplemented {:?}", op); return Err(Error::FeatureNotImplemented("binary operator")); } }; + let (result_type_id, result_lookup_ty) = if result_side_left { + (left_result_type_id, left_lookup_ty) + } else { + (right_result_type_id, right_lookup_ty) + }; block.body.push(super::instructions::instruction_binary( spirv_op, - left_result_type_id, + result_type_id, id, - left_id, - right_id, + if preserve_order { left_id } else { right_id }, + if preserve_order { right_id } else { left_id }, )); - Ok((id, lookup_ty)) + Ok((id, result_lookup_ty)) } crate::Expression::LocalVariable(variable) => { let var = &ir_function.local_variables[variable]; diff --git a/test-data/boids.param.ron b/test-data/boids.param.ron index 4de90960b..da2365392 100644 --- a/test-data/boids.param.ron +++ b/test-data/boids.param.ron @@ -1,6 +1,7 @@ ( spv_flow_dump_prefix: "", - metal_bindings: { + spv_capabilities: [ Shader ], + mtl_bindings: { (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: false), (stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true), (stage: Compute, group: 0, binding: 2): (buffer: Some(2), mutable: true), diff --git a/test-data/quad.param.ron b/test-data/quad.param.ron index c4245bd18..25747c169 100644 --- a/test-data/quad.param.ron +++ b/test-data/quad.param.ron @@ -1,5 +1,6 @@ ( - metal_bindings: { + spv_capabilities: [ Shader ], + mtl_bindings: { (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), (stage: Fragment, group: 0, binding: 1): (sampler: Some(0)), } diff --git a/tests/convert.rs b/tests/convert.rs index a05be6eea..4b8f55fd6 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -65,6 +65,12 @@ fn convert_quad() { }; msl::write_string(&module, &options).unwrap(); } + #[cfg(feature = "spv-out")] + { + use naga::back::spv; + let capabilities = Some(spirv::Capability::Shader).into_iter().collect(); + spv::write_vec(&module, spv::WriterFlags::empty(), capabilities).unwrap(); + } } #[cfg(feature = "wgsl-in")] @@ -122,6 +128,15 @@ fn convert_boids() { }; msl::write_string(&module, &options).unwrap(); } + #[cfg(feature = "spv-out")] + { + use naga::back::spv; + let capabilities = Some(spirv::Capability::Shader).into_iter().collect(); + if let Err(e) = spv::write_vec(&module, spv::WriterFlags::empty(), capabilities) { + //TODO: panic here when `spv-out` supports it + println!("Quad SPIR-V error {:?}", e); + } + } } #[cfg(feature = "spv-in")] From 5786aac9c4a758009c54106df5adf43c71348a9b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 8 Dec 2020 00:20:31 -0500 Subject: [PATCH 0314/2212] [glsl] enable conversion testing for quad and boids --- Makefile | 4 ++++ examples/convert.rs | 7 +++++-- tests/convert.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 7a74b50c5..910db1543 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,10 @@ clean: %.metallib: %.air xcrun -sdk macosx metallib $< -o $@ +%.spv: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) + cargo run --example convert --features wgsl-in,spv-out -- $< $@ + spirv-val $@ + %.vert %.frag %.comp: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) cargo run --example convert --features wgsl-in,glsl-out -- $< $@ glslangValidator $@ diff --git a/examples/convert.rs b/examples/convert.rs index d4801fc93..23003d458 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -17,19 +17,23 @@ struct BindSource { #[derive(serde::Deserialize)] struct BindTarget { #[serde(default)] + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] buffer: Option, #[serde(default)] + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] texture: Option, #[serde(default)] + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] sampler: Option, #[serde(default)] + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] mutable: bool, } #[derive(Default, serde::Deserialize)] struct Parameters { #[serde(default)] - #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + #[cfg_attr(not(feature = "spv-in"), allow(dead_code))] spv_flow_dump_prefix: String, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_capabilities: naga::FastHashSet, @@ -41,7 +45,6 @@ fn main() { env_logger::init(); let args = env::args().collect::>(); - if args.len() <= 1 { println!("Call with "); return; diff --git a/tests/convert.rs b/tests/convert.rs index 4b8f55fd6..294661375 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -71,6 +71,26 @@ fn convert_quad() { let capabilities = Some(spirv::Capability::Shader).into_iter().collect(); spv::write_vec(&module, spv::WriterFlags::empty(), capabilities).unwrap(); } + #[cfg(feature = "glsl-out")] + { + use naga::back::glsl; + let mut options = glsl::Options { + version: glsl::Version::Embedded(310), + entry_point: (naga::ShaderStage::Compute, String::from("main")), + }; + + let mut output = Vec::new(); + { + options.entry_point.0 = naga::ShaderStage::Vertex; + let mut writer = glsl::Writer::new(&mut output, &module, &options).unwrap(); + writer.write().unwrap(); + } + { + options.entry_point.0 = naga::ShaderStage::Fragment; + let mut writer = glsl::Writer::new(&mut output, &module, &options).unwrap(); + writer.write().unwrap(); + } + } } #[cfg(feature = "wgsl-in")] @@ -137,6 +157,18 @@ fn convert_boids() { println!("Quad SPIR-V error {:?}", e); } } + #[cfg(feature = "glsl-out")] + { + use naga::back::glsl; + let options = glsl::Options { + version: glsl::Version::Embedded(310), + entry_point: (naga::ShaderStage::Compute, String::from("main")), + }; + + let mut output = Vec::new(); + let mut writer = glsl::Writer::new(&mut output, &module, &options).unwrap(); + writer.write().unwrap(); + } } #[cfg(feature = "spv-in")] From 6c1f4ac590d4978f2c5642a6fb662af38df6d7e7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 8 Dec 2020 01:31:11 -0500 Subject: [PATCH 0315/2212] [wgsl] populate standard functions --- src/front/wgsl/conv.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 674f2fee9..1c986a3cd 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -120,7 +120,13 @@ pub fn get_derivative(word: &str) -> Option { // Returns argument count on success pub fn get_standard_fun(word: &str) -> Option { match word { - "min" | "max" => Some(2), + "abs" | "acos" | "asin" | "atan" | "ceil" | "cos" | "cosh" | "exp" | "exp2" | "floor" + | "fract" | "inverseSqrt" | "length" | "log" | "log2" | "normalize" | "round" | "sign" + | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc" => Some(1), + "countOneBits" | "reverseBits" | "determinant" => Some(1), + "atan2" | "distance" | "frexp" | "ldexp" | "max" | "min" | "outerProduct" | "pow" + | "reflect" | "step" => Some(2), + "clamp" | "faceForward" | "fma" | "smoothStep" => Some(3), _ => None, } } From 66d994566c68c2da66fba783389e5fa87c54d737 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 8 Dec 2020 17:25:16 -0500 Subject: [PATCH 0316/2212] [spv] force treating the built-in scalar types as unsigned --- src/front/spv/mod.rs | 31 ++++++++++++++++++++++++++++++- test-data/spv/quad.vert.spv | Bin 0 -> 884 bytes tests/convert.rs | 21 ++++++++++++++++++++- 3 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 test-data/spv/quad.vert.spv diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index f13c3c757..ad7c20851 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2367,11 +2367,40 @@ impl> Parser { crate::StorageAccess::empty() }; + let ty = match binding { + // SPIR-V only cares about some of the built-in types being integer. + // Naga requires them to be strictly unsigned, so we have to patch it. + Some(crate::Binding::BuiltIn(built_in)) => { + let scalar_kind = module.types[lookup_type.handle].inner.scalar_kind(); + let needs_uint = match built_in { + crate::BuiltIn::BaseInstance + | crate::BuiltIn::BaseVertex + | crate::BuiltIn::InstanceIndex + | crate::BuiltIn::SampleIndex + | crate::BuiltIn::VertexIndex => true, + _ => false, + }; + if needs_uint && scalar_kind == Some(crate::ScalarKind::Sint) { + log::warn!("Treating {:?} as unsigned", built_in); + module.types.fetch_or_append(crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: 4, + }, + }) + } else { + lookup_type.handle + } + } + _ => lookup_type.handle, + }; + let var = crate::GlobalVariable { name: dec.name, class, binding, - ty: lookup_type.handle, + ty, init, interpolation: dec.interpolation, storage_access, diff --git a/test-data/spv/quad.vert.spv b/test-data/spv/quad.vert.spv new file mode 100644 index 0000000000000000000000000000000000000000..ea22e0c6c8c517586dffef3e917584826c32602b GIT binary patch literal 884 zcmZ9JO-lk{6os$asAXwpYM(Y{Z3?7CMGzIOEO0Rqw2iM|PZI36t_TkY15k<>Hfy9)QiOdMk z5B&l9ys#l;^h@jgP@t!XzcHSeS@~XuOw?74{Ns?JXzbof*Gv6%^OKaOAgXD`X7K7M-D1hdx*`maiZQ&osB3vlfJ9&?qL=LSigW$EyNV%(iwZTN(%OXp7DEsk4}UKQ}2YXjzm zV;<@>1h^Z;Gp{eeAqm%%4wn)FWpSHr!58pxKYCuO2KU<$xH)&GCpPils&FFw0HeY$ Aw*UYD literal 0 HcmV?d00001 diff --git a/tests/convert.rs b/tests/convert.rs index 294661375..593f9b433 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -173,7 +173,7 @@ fn convert_boids() { #[cfg(feature = "spv-in")] #[test] -fn convert_cube() { +fn convert_cube_spv() { let mut validator = naga::proc::Validator::new(); let vs = load_spv("cube.vert.spv"); validator.validate(&vs).unwrap(); @@ -232,6 +232,25 @@ fn convert_cube() { } } +#[cfg(feature = "spv-in")] +#[test] +fn convert_quad_spv() { + let mut validator = naga::proc::Validator::new(); + // check that integer `gl_VertexIndex` is treated as unsigned + let vs = load_spv("quad.vert.spv"); + validator.validate(&vs).unwrap(); + #[cfg(feature = "msl-out")] + { + use naga::back::msl; + let options = msl::Options { + lang_version: (1, 0), + spirv_cross_compatibility: false, + binding_map: msl::BindingMap::default(), + }; + msl::write_string(&vs, &options).unwrap(); + } +} + #[cfg(feature = "glsl-in")] #[test] #[ignore] From b35e901249ffd7a7857ddd396388fb7a017c41dd Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 9 Dec 2020 00:12:53 -0500 Subject: [PATCH 0317/2212] Add all standard library functions to the IR --- src/back/glsl/mod.rs | 175 +++++++++++++++++++-------------- src/back/msl/writer.rs | 127 +++++++++++++++++------- src/back/spv/writer.rs | 73 +++++++------- src/front/spv/function.rs | 16 ++- src/front/spv/mod.rs | 201 +++++++++++++++++--------------------- src/front/wgsl/conv.rs | 88 +++++++++++++---- src/front/wgsl/mod.rs | 130 ++++++++++++------------ src/lib.rs | 121 ++++++++++++++++------- src/proc/interface.rs | 33 ++++--- src/proc/mod.rs | 59 +++++++++++ src/proc/typifier.rs | 169 ++++++++++++++++++++++---------- test-data/boids.wgsl | 14 +-- 12 files changed, 744 insertions(+), 462 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 98bfe02c9..3f87d1c76 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -49,10 +49,9 @@ use crate::{ Typifier, Visitor, }, Arena, ArraySize, BinaryOperator, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, - DerivativeAxis, Expression, FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, - ImageClass, Interpolation, IntrinsicFunction, LocalVariable, Module, ScalarKind, ShaderStage, - Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, - UnaryOperator, + DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, + Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ShaderStage, Statement, + StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, UnaryOperator, }; use features::FeaturesManager; use std::{ @@ -1371,49 +1370,119 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(reject, ctx)?; write!(self.out, ")")? } - // `Intrinsic` is a normal function call to some glsl provided functions - Expression::Intrinsic { fun, argument } => { + // `Derivative` is a function call to a glsl provided function + Expression::Derivative { axis, expr } => { write!( self.out, "{}(", - match fun { - // There's no specific function for this but we can invert the result of `isinf` - IntrinsicFunction::IsFinite => "!isinf", - IntrinsicFunction::IsInf => "isinf", - IntrinsicFunction::IsNan => "isnan", - // There's also no function for this but we can invert `isnan` - IntrinsicFunction::IsNormal => "!isnan", - IntrinsicFunction::All => "all", - IntrinsicFunction::Any => "any", + match axis { + DerivativeAxis::X => "dFdx", + DerivativeAxis::Y => "dFdy", + DerivativeAxis::Width => "fwidth", } )?; + self.write_expr(expr, ctx)?; + write!(self.out, ")")? + } + // `Relational` is a normal function call to some glsl provided functions + Expression::Relational { fun, argument } => { + let fun_name = match fun { + // There's no specific function for this but we can invert the result of `isinf` + RelationalFunction::IsFinite => "!isinf", + RelationalFunction::IsInf => "isinf", + RelationalFunction::IsNan => "isnan", + // There's also no function for this but we can invert `isnan` + RelationalFunction::IsNormal => "!isnan", + RelationalFunction::All => "all", + RelationalFunction::Any => "any", + }; + write!(self.out, "{}(", fun_name)?; self.write_expr(argument, ctx)?; write!(self.out, ")")? } + Expression::Math { + fun, + arg, + arg1, + arg2, + } => { + use crate::MathFunction as Mf; + + let fun_name = match fun { + // comparison + Mf::Abs => "abs", + Mf::Min => "min", + Mf::Max => "max", + Mf::Clamp => "clamp", + // trigonometry + Mf::Cos => "cos", + Mf::Cosh => "cosh", + Mf::Sin => "sin", + Mf::Sinh => "sinh", + Mf::Tan => "tan", + Mf::Tanh => "tanh", + Mf::Acos => "acos", + Mf::Asin => "asin", + Mf::Atan => "atan", + Mf::Atan2 => "atan2", + // decomposition + Mf::Ceil => "ceil", + Mf::Floor => "floor", + Mf::Round => "round", + Mf::Fract => "fract", + Mf::Trunc => "trunc", + Mf::Modf => "modf", + Mf::Frexp => "frexp", + Mf::Ldexp => "ldexp", + // exponent + Mf::Exp => "exp", + Mf::Exp2 => "exp2", + Mf::Log => "log", + Mf::Log2 => "log2", + Mf::Pow => "pow", + // geometry + Mf::Dot => "dot", + Mf::Outer => "outerProduct", + Mf::Cross => "cross", + Mf::Distance => "distance", + Mf::Length => "length", + Mf::Normalize => "normalize", + Mf::FaceForward => "faceforward", + Mf::Reflect => "reflect", + // computational + Mf::Sign => "sign", + Mf::Fma => "fma", + Mf::Mix => "mix", + Mf::Step => "step", + Mf::SmoothStep => "smoothstep", + Mf::Sqrt => "sqrt", + Mf::InverseSqrt => "inversesqrt", + Mf::Determinant => "determinant", + // bits + Mf::CountOneBits => "bitCount", + Mf::ReverseBits => "bitfieldReverse", + }; + + write!(self.out, "{}(", fun_name)?; + self.write_expr(arg, ctx)?; + if let Some(arg) = arg1 { + write!(self.out, ", ")?; + self.write_expr(arg, ctx)?; + } + if let Some(arg) = arg2 { + write!(self.out, ", ")?; + self.write_expr(arg, ctx)?; + } + write!(self.out, ")")? + } // `Transpose` is a call to the glsl function `transpose` Expression::Transpose(matrix) => { write!(self.out, "transpose(")?; self.write_expr(matrix, ctx)?; write!(self.out, ")")? } - // Both `Dot` and `Cross` products are a call to a glsl provide functions with `left` - // and `right` as arguments - Expression::DotProduct(left, right) => { - write!(self.out, "dot(")?; - self.write_expr(left, ctx)?; - write!(self.out, ", ")?; - self.write_expr(right, ctx)?; - write!(self.out, ")")? - } - Expression::CrossProduct(left, right) => { - write!(self.out, "cross(")?; - self.write_expr(left, ctx)?; - write!(self.out, ", ")?; - self.write_expr(right, ctx)?; - write!(self.out, ")")? - } // `As` is always a call. // If `convert` is true the function name is the type // Else the function name is one of the glsl provided bitcast functions @@ -1457,55 +1526,15 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(expr, ctx)?; write!(self.out, ")")? } - // `Derivative` is a function call to a glsl provided function - Expression::Derivative { axis, expr } => { - write!( - self.out, - "{}(", - match axis { - DerivativeAxis::X => "dFdx", - DerivativeAxis::Y => "dFdy", - DerivativeAxis::Width => "fwidth", - } - )?; - self.write_expr(expr, ctx)?; - write!(self.out, ")")? - } // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list Expression::Call { - origin: FunctionOrigin::Local(ref function), + function, ref arguments, } => { - write!(self.out, "{}(", &self.names[&NameKey::Function(*function)])?; + write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; write!(self.out, ")")? } - Expression::Call { - origin: crate::FunctionOrigin::External(ref name), - ref arguments, - } => match name.as_str() { - "cos" | "normalize" | "sin" | "length" | "abs" | "floor" | "inverse" - | "distance" | "dot" | "min" | "max" | "reflect" | "pow" | "step" | "cross" - | "fclamp" | "clamp" | "mix" | "smoothstep" => { - let name = match name.as_str() { - "fclamp" => "clamp", - name => name, - }; - - write!(self.out, "{}(", name)?; - self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; - write!(self.out, ")")? - } - // `atan2` is implemented as `atan(y,x)` so we must handle it separately - "atan2" => { - write!(self.out, "atan(")?; - self.write_expr(arguments[1], ctx)?; - write!(self.out, ", ")?; - self.write_expr(arguments[0], ctx)?; - write!(self.out, ")")? - } - _ => return Err(Error::UnsupportedExternal(name.clone())), - }, // `ArrayLength` is written as `expr.length()` and we convert it to a uint Expression::ArrayLength(expr) => { write!(self.out, "uint(")?; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 936f78ac5..710948d62 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -346,26 +346,103 @@ impl Writer { self.put_expression(reject, context)?; write!(self.out, ")")?; } - crate::Expression::Intrinsic { fun, argument } => { + crate::Expression::Derivative { axis, expr } => { + let op = match axis { + crate::DerivativeAxis::X => "dfdx", + crate::DerivativeAxis::Y => "dfdy", + crate::DerivativeAxis::Width => "fwidth", + }; + self.put_call(op, &[expr], context)?; + } + crate::Expression::Relational { fun, argument } => { let op = match fun { - crate::IntrinsicFunction::Any => "any", - crate::IntrinsicFunction::All => "all", - crate::IntrinsicFunction::IsNan => "", - crate::IntrinsicFunction::IsInf => "", - crate::IntrinsicFunction::IsFinite => "", - crate::IntrinsicFunction::IsNormal => "", + crate::RelationalFunction::Any => "any", + crate::RelationalFunction::All => "all", + crate::RelationalFunction::IsNan => "isnan", + crate::RelationalFunction::IsInf => "isinf", + crate::RelationalFunction::IsFinite => "isfinite", + crate::RelationalFunction::IsNormal => "isnormal", }; self.put_call(op, &[argument], context)?; } + crate::Expression::Math { + fun, + arg, + arg1, + arg2, + } => { + use crate::MathFunction as Mf; + + let fun_name = match fun { + // comparison + Mf::Abs => "abs", + Mf::Min => "min", + Mf::Max => "max", + Mf::Clamp => "clamp", + // trigonometry + Mf::Cos => "cos", + Mf::Cosh => "cosh", + Mf::Sin => "sin", + Mf::Sinh => "sinh", + Mf::Tan => "tan", + Mf::Tanh => "tanh", + Mf::Acos => "acos", + Mf::Asin => "asin", + Mf::Atan => "atan", + Mf::Atan2 => "atan2", + // decomposition + Mf::Ceil => "ceil", + Mf::Floor => "floor", + Mf::Round => "round", + Mf::Fract => "fract", + Mf::Trunc => "trunc", + Mf::Modf => "modf", + Mf::Frexp => "frexp", + Mf::Ldexp => "ldexp", + // exponent + Mf::Exp => "exp", + Mf::Exp2 => "exp2", + Mf::Log => "log", + Mf::Log2 => "log2", + Mf::Pow => "pow", + // geometry + Mf::Dot => "dot", + Mf::Outer => return Err(Error::UnsupportedCall(format!("{:?}", fun))), + Mf::Cross => "cross", + Mf::Distance => "distance", + Mf::Length => "length", + Mf::Normalize => "normalize", + Mf::FaceForward => "faceforward", + Mf::Reflect => "reflect", + // computational + Mf::Sign => "sign", + Mf::Fma => "fma", + Mf::Mix => "mix", + Mf::Step => "step", + Mf::SmoothStep => "smoothstep", + Mf::Sqrt => "sqrt", + Mf::InverseSqrt => "rsqrt", + Mf::Determinant => "determinant", + // bits + Mf::CountOneBits => "popcount", + Mf::ReverseBits => "reverse_bits", + }; + + write!(self.out, "metal::{}(", fun_name)?; + self.put_expression(arg, context)?; + if let Some(arg) = arg1 { + write!(self.out, ", ")?; + self.put_expression(arg, context)?; + } + if let Some(arg) = arg2 { + write!(self.out, ", ")?; + self.put_expression(arg, context)?; + } + write!(self.out, ")")?; + } crate::Expression::Transpose(expr) => { self.put_call("transpose", &[expr], context)?; } - crate::Expression::DotProduct(a, b) => { - self.put_call("dot", &[a, b], context)?; - } - crate::Expression::CrossProduct(a, b) => { - self.put_call("cross", &[a, b], context)?; - } crate::Expression::As { expr, kind, @@ -382,34 +459,14 @@ impl Writer { self.put_expression(expr, context)?; write!(self.out, ")")?; } - crate::Expression::Derivative { axis, expr } => { - let op = match axis { - crate::DerivativeAxis::X => "dfdx", - crate::DerivativeAxis::Y => "dfdy", - crate::DerivativeAxis::Width => "fwidth", - }; - self.put_call(op, &[expr], context)?; - } crate::Expression::Call { - origin: crate::FunctionOrigin::Local(handle), + function, ref arguments, } => { - let name = &self.names[&NameKey::Function(handle)]; + let name = &self.names[&NameKey::Function(function)]; write!(self.out, "{}", name)?; self.put_call("", arguments, context)?; } - crate::Expression::Call { - origin: crate::FunctionOrigin::External(ref name), - ref arguments, - } => match name.as_str() { - "atan2" | "cos" | "distance" | "length" | "mix" | "normalize" | "sin" => { - self.put_call(name, arguments, context)?; - } - "fclamp" => { - self.put_call("clamp", arguments, context)?; - } - other => return Err(Error::UnsupportedCall(other.to_owned())), - }, crate::Expression::ArrayLength(expr) => match *self .typifier .get(expr, &context.module.types) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 50d354dc9..9279cce03 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1232,6 +1232,10 @@ impl Writer { )); Ok((id, result_lookup_ty)) } + crate::Expression::Math { fun, .. } => { + log::error!("unimplemented math function {:?}", fun); + Err(Error::FeatureNotImplemented("math function")) + } crate::Expression::LocalVariable(variable) => { let var = &ir_function.local_variables[variable]; let local_var = &function.variables[&variable]; @@ -1251,49 +1255,38 @@ impl Writer { Ok((load_id, LookupType::Handle(handle))) } crate::Expression::Call { - ref origin, + function: local_function, ref arguments, - } => match *origin { - crate::FunctionOrigin::Local(local_function) => { - let origin_function = &ir_module.functions[local_function]; - let id = self.generate_id(); - let mut argument_ids = vec![]; + } => { + let target_function = &ir_module.functions[local_function]; + let id = self.generate_id(); + let mut argument_ids = vec![]; - for argument in arguments { - let expression = &ir_function.expressions[*argument]; - let (arg_id, _) = self.write_expression( - ir_module, - ir_function, - expression, - block, - function, - )?; - argument_ids.push(arg_id); - } - - let return_type_id = self - .get_function_return_type(origin_function.return_type, &ir_module.types)?; - - block - .body - .push(super::instructions::instruction_function_call( - return_type_id, - id, - *self.lookup_function.get(&local_function).unwrap(), - argument_ids.as_slice(), - )); - - let result_type = match origin_function.return_type { - Some(ty_handle) => LookupType::Handle(ty_handle), - None => LookupType::Local(LocalType::Void), - }; - Ok((id, result_type)) + for argument in arguments { + let expression = &ir_function.expressions[*argument]; + let (arg_id, _) = + self.write_expression(ir_module, ir_function, expression, block, function)?; + argument_ids.push(arg_id); } - crate::FunctionOrigin::External(ref string) => { - log::error!("unimplemented stdlib function {}", string); - Err(Error::FeatureNotImplemented("stdlib function")) - } - }, + + let return_type_id = + self.get_function_return_type(target_function.return_type, &ir_module.types)?; + + block + .body + .push(super::instructions::instruction_function_call( + return_type_id, + id, + *self.lookup_function.get(&local_function).unwrap(), + argument_ids.as_slice(), + )); + + let result_type = match target_function.return_type { + Some(ty_handle) => LookupType::Handle(ty_handle), + None => LookupType::Local(LocalType::Void), + }; + Ok((id, result_type)) + } crate::Expression::As { expr, kind, diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index d2cb0551a..654160b30 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -115,8 +115,8 @@ impl> super::Parser { } // Read body - let mut local_function_calls = FastHashMap::default(); let mut flow_graph = FlowGraph::new(); + let base_deferred_call_index = self.deferred_function_calls.len(); // Scan the blocks and add them as nodes loop { @@ -135,7 +135,6 @@ impl> super::Parser { &module.types, &module.constants, &module.global_variables, - &mut local_function_calls, )?; flow_graph.add_node(node); @@ -176,9 +175,14 @@ impl> super::Parser { } }; + for dfc in self.deferred_function_calls[base_deferred_call_index..].iter_mut() { + dfc.source = source.clone(); + } + if let Some(ref prefix) = self.options.flow_graph_dump_prefix { let dump = flow_graph.to_graphviz().unwrap_or_default(); let suffix = match source { + DeferredSource::Undefined => unreachable!(), DeferredSource::EntryPoint(stage, ref name) => { format!("flow.{:?}-{}.dot", stage, name) } @@ -187,14 +191,6 @@ impl> super::Parser { let _ = std::fs::write(prefix.join(suffix), dump); } - for (expr_handle, dst_id) in local_function_calls { - self.deferred_function_calls.push(DeferredFunctionCall { - source: source.clone(), - expr_handle, - dst_id, - }); - } - self.lookup_expression.clear(); self.lookup_sampled_image.clear(); Ok(()) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index ad7c20851..782c62a6f 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -289,6 +289,7 @@ struct LookupSampledImage { } #[derive(Clone, Debug)] enum DeferredSource { + Undefined, EntryPoint(crate::ShaderStage, String), Function(Handle), } @@ -296,6 +297,7 @@ struct DeferredFunctionCall { source: DeferredSource, expr_handle: Handle, dst_id: spirv::Word, + arguments: Vec>, } #[derive(Clone, Debug)] @@ -530,7 +532,6 @@ impl> Parser { type_arena: &Arena, const_arena: &Arena, global_arena: &Arena, - local_function_calls: &mut FastHashMap, spirv::Word>, ) -> Result { let mut assignments = Vec::new(); let mut phis = Vec::new(); @@ -850,7 +851,12 @@ impl> Parser { let right_id = self.next()?; let left_lexp = self.lookup_expression.lookup(left_id)?; let right_lexp = self.lookup_expression.lookup(right_id)?; - let expr = crate::Expression::DotProduct(left_lexp.handle, right_lexp.handle); + let expr = crate::Expression::Math { + fun: crate::MathFunction::Dot, + arg: left_lexp.handle, + arg1: Some(right_lexp.handle), + arg2: None, + }; self.lookup_expression.insert( result_id, LookupExpression { @@ -1185,13 +1191,15 @@ impl> Parser { let arg_id = self.next()?; arguments.push(self.lookup_expression.lookup(arg_id)?.handle); } - let expr = crate::Expression::Call { - // will be replaced by `Local()` after all the functions are parsed - origin: crate::FunctionOrigin::External(String::new()), - arguments, - }; + // will be replaced by the actual expression + let expr = crate::Expression::FunctionArgument(!0); let expr_handle = expressions.append(expr); - local_function_calls.insert(expr_handle, func_id); + self.deferred_function_calls.push(DeferredFunctionCall { + source: DeferredSource::Undefined, + expr_handle, + dst_id: func_id, + arguments, + }); self.lookup_expression.insert( result_id, LookupExpression { @@ -1201,6 +1209,9 @@ impl> Parser { ); } Op::ExtInst => { + use crate::MathFunction as Mf; + use spirv::GLOp as Glo; + let base_wc = 5; inst.expect_at_least(base_wc)?; let result_type_id = self.next()?; @@ -1210,106 +1221,76 @@ impl> Parser { return Err(Error::UnsupportedExtInstSet(set_id)); } let inst_id = self.next()?; - let name = match spirv::GLOp::from_u32(inst_id) { - Some(spirv::GLOp::FAbs) | Some(spirv::GLOp::SAbs) => { - inst.expect(base_wc + 1)?; - "abs" - } - Some(spirv::GLOp::FSign) | Some(spirv::GLOp::SSign) => { - inst.expect(base_wc + 1)?; - "sign" - } - Some(spirv::GLOp::Floor) => { - inst.expect(base_wc + 1)?; - "floor" - } - Some(spirv::GLOp::Ceil) => { - inst.expect(base_wc + 1)?; - "ceil" - } - Some(spirv::GLOp::Fract) => { - inst.expect(base_wc + 1)?; - "fract" - } - Some(spirv::GLOp::Sin) => { - inst.expect(base_wc + 1)?; - "sin" - } - Some(spirv::GLOp::Cos) => { - inst.expect(base_wc + 1)?; - "cos" - } - Some(spirv::GLOp::Tan) => { - inst.expect(base_wc + 1)?; - "tan" - } - Some(spirv::GLOp::Atan2) => { - inst.expect(base_wc + 2)?; - "atan2" - } - Some(spirv::GLOp::Pow) => { - inst.expect(base_wc + 2)?; - "pow" - } - Some(spirv::GLOp::MatrixInverse) => { - inst.expect(base_wc + 1)?; - "inverse" - } - Some(spirv::GLOp::FMix) => { - inst.expect(base_wc + 3)?; - "mix" - } - Some(spirv::GLOp::Step) => { - inst.expect(base_wc + 2)?; - "step" - } - Some(spirv::GLOp::SmoothStep) => { - inst.expect(base_wc + 3)?; - "smoothstep" - } - Some(spirv::GLOp::FMin) => { - inst.expect(base_wc + 2)?; - "min" - } - Some(spirv::GLOp::FMax) => { - inst.expect(base_wc + 2)?; - "max" - } - Some(spirv::GLOp::FClamp) => { - inst.expect(base_wc + 3)?; - "clamp" - } - Some(spirv::GLOp::Length) => { - inst.expect(base_wc + 1)?; - "length" - } - Some(spirv::GLOp::Distance) => { - inst.expect(base_wc + 2)?; - "distance" - } - Some(spirv::GLOp::Cross) => { - inst.expect(base_wc + 2)?; - "cross" - } - Some(spirv::GLOp::Normalize) => { - inst.expect(base_wc + 1)?; - "normalize" - } - Some(spirv::GLOp::Reflect) => { - inst.expect(base_wc + 2)?; - "reflect" - } + let gl_op = Glo::from_u32(inst_id).ok_or(Error::UnsupportedExtInst(inst_id))?; + let fun = match gl_op { + Glo::Round => Mf::Round, + Glo::Trunc => Mf::Trunc, + Glo::FAbs | Glo::SAbs => Mf::Abs, + Glo::FSign | Glo::SSign => Mf::Sign, + Glo::Floor => Mf::Floor, + Glo::Ceil => Mf::Ceil, + Glo::Fract => Mf::Fract, + Glo::Sin => Mf::Sin, + Glo::Cos => Mf::Cos, + Glo::Tan => Mf::Tan, + Glo::Asin => Mf::Asin, + Glo::Acos => Mf::Acos, + Glo::Atan => Mf::Atan, + Glo::Sinh => Mf::Sinh, + Glo::Cosh => Mf::Cosh, + Glo::Tanh => Mf::Tanh, + Glo::Atan2 => Mf::Atan2, + Glo::Pow => Mf::Pow, + Glo::Exp => Mf::Exp, + Glo::Log => Mf::Log, + Glo::Exp2 => Mf::Exp2, + Glo::Log2 => Mf::Log2, + Glo::Sqrt => Mf::Sqrt, + Glo::InverseSqrt => Mf::InverseSqrt, + Glo::Determinant => Mf::Determinant, + Glo::Modf => Mf::Modf, + Glo::FMin | Glo::UMin | Glo::SMin | Glo::NMin => Mf::Min, + Glo::FMax | Glo::UMax | Glo::SMax | Glo::NMax => Mf::Max, + Glo::FClamp | Glo::UClamp | Glo::SClamp | Glo::NClamp => Mf::Clamp, + Glo::FMix => Mf::Mix, + Glo::Step => Mf::Step, + Glo::SmoothStep => Mf::SmoothStep, + Glo::Fma => Mf::Fma, + Glo::Frexp => Mf::Frexp, //TODO: FrexpStruct? + Glo::Ldexp => Mf::Ldexp, + Glo::Length => Mf::Length, + Glo::Distance => Mf::Distance, + Glo::Cross => Mf::Cross, + Glo::Normalize => Mf::Normalize, + Glo::FaceForward => Mf::FaceForward, + Glo::Reflect => Mf::Reflect, _ => return Err(Error::UnsupportedExtInst(inst_id)), }; - let mut arguments = Vec::with_capacity((inst.wc - base_wc) as usize); - for _ in 0..arguments.capacity() { + let arg_count = fun.argument_count(); + inst.expect(base_wc + arg_count as u16)?; + let arg = { let arg_id = self.next()?; - arguments.push(self.lookup_expression.lookup(arg_id)?.handle); - } - let expr = crate::Expression::Call { - origin: crate::FunctionOrigin::External(name.to_string()), - arguments, + self.lookup_expression.lookup(arg_id)?.handle + }; + let arg1 = if arg_count > 1 { + let arg_id = self.next()?; + Some(self.lookup_expression.lookup(arg_id)?.handle) + } else { + None + }; + let arg2 = if arg_count > 2 { + let arg_id = self.next()?; + Some(self.lookup_expression.lookup(arg_id)?.handle) + } else { + None + }; + + let expr = crate::Expression::Math { + fun, + arg, + arg1, + arg2, }; self.lookup_expression.insert( result_id, @@ -1553,6 +1534,7 @@ impl> Parser { for dfc in self.deferred_function_calls.drain(..) { let dst_handle = *self.lookup_function.lookup(dfc.dst_id)?; let fun = match dfc.source { + DeferredSource::Undefined => unreachable!(), DeferredSource::Function(fun_handle) => module.functions.get_mut(fun_handle), DeferredSource::EntryPoint(stage, name) => { &mut module @@ -1562,13 +1544,10 @@ impl> Parser { .function } }; - match *fun.expressions.get_mut(dfc.expr_handle) { - crate::Expression::Call { - ref mut origin, - arguments: _, - } => *origin = crate::FunctionOrigin::Local(dst_handle), - _ => unreachable!(), - } + *fun.expressions.get_mut(dfc.expr_handle) = crate::Expression::Call { + function: dst_handle, + arguments: dfc.arguments, + }; } if !self.future_decor.is_empty() { diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 1c986a3cd..18de009aa 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -97,18 +97,7 @@ pub fn get_scalar_type(word: &str) -> Option<(crate::ScalarKind, crate::Bytes)> } } -pub fn get_intrinsic(word: &str) -> Option { - match word { - "any" => Some(crate::IntrinsicFunction::Any), - "all" => Some(crate::IntrinsicFunction::All), - "is_nan" => Some(crate::IntrinsicFunction::IsNan), - "is_inf" => Some(crate::IntrinsicFunction::IsInf), - "is_normal" => Some(crate::IntrinsicFunction::IsNormal), - _ => None, - } -} - -pub fn get_derivative(word: &str) -> Option { +pub fn map_derivative_axis(word: &str) -> Option { match word { "dpdx" => Some(crate::DerivativeAxis::X), "dpdy" => Some(crate::DerivativeAxis::Y), @@ -117,16 +106,73 @@ pub fn get_derivative(word: &str) -> Option { } } -// Returns argument count on success -pub fn get_standard_fun(word: &str) -> Option { +pub fn map_relational_fun(word: &str) -> Option { match word { - "abs" | "acos" | "asin" | "atan" | "ceil" | "cos" | "cosh" | "exp" | "exp2" | "floor" - | "fract" | "inverseSqrt" | "length" | "log" | "log2" | "normalize" | "round" | "sign" - | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc" => Some(1), - "countOneBits" | "reverseBits" | "determinant" => Some(1), - "atan2" | "distance" | "frexp" | "ldexp" | "max" | "min" | "outerProduct" | "pow" - | "reflect" | "step" => Some(2), - "clamp" | "faceForward" | "fma" | "smoothStep" => Some(3), + "any" => Some(crate::RelationalFunction::Any), + "all" => Some(crate::RelationalFunction::All), + "isFinite" => Some(crate::RelationalFunction::IsFinite), + "isInf" => Some(crate::RelationalFunction::IsInf), + "isNan" => Some(crate::RelationalFunction::IsNan), + "isNormal" => Some(crate::RelationalFunction::IsNormal), _ => None, } } + +pub fn map_standard_fun(word: &str) -> Option { + use crate::MathFunction as Mf; + Some(match word { + // comparison + "abs" => Mf::Abs, + "min" => Mf::Min, + "max" => Mf::Max, + "clamp" => Mf::Clamp, + // trigonometry + "cos" => Mf::Cos, + "cosh" => Mf::Cosh, + "sin" => Mf::Sin, + "sinh" => Mf::Sinh, + "tan" => Mf::Tan, + "tanh" => Mf::Tanh, + "acos" => Mf::Acos, + "asin" => Mf::Asin, + "atan" => Mf::Atan, + "atan2" => Mf::Atan2, + // decomposition + "ceil" => Mf::Ceil, + "floor" => Mf::Floor, + "round" => Mf::Round, + "fract" => Mf::Fract, + "trunc" => Mf::Trunc, + "modf" => Mf::Modf, + "frexp" => Mf::Frexp, + "ldexp" => Mf::Ldexp, + // exponent + "exp" => Mf::Exp, + "exp2" => Mf::Exp2, + "log" => Mf::Log, + "log2" => Mf::Log2, + "pow" => Mf::Pow, + // geometry + "dot" => Mf::Dot, + "outerProduct" => Mf::Outer, + "cross" => Mf::Cross, + "distance" => Mf::Distance, + "length" => Mf::Length, + "normalize" => Mf::Normalize, + "faceForward" => Mf::FaceForward, + "reflect" => Mf::Reflect, + // computational + "sign" => Mf::Sign, + "fma" => Mf::Fma, + "mix" => Mf::Mix, + "step" => Mf::Step, + "smoothStep" => Mf::SmoothStep, + "sqrt" => Mf::Sqrt, + "inverseSqrt" => Mf::InverseSqrt, + "determinant" => Mf::Determinant, + // bits + "countOneBits" => Mf::CountOneBits, + "reverseBits" => Mf::ReverseBits, + _ => return None, + }) +} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 98d4cc513..4beeada22 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -336,40 +336,54 @@ impl Parser { ) -> Result)>, Error<'a>> { let mut lexer = lexer.clone(); - let external_function = if let Some(std_namespaces) = self.std_namespace.as_deref() { - std_namespaces.iter().all(|namespace| { - lexer.skip(Token::Word(namespace)) && lexer.skip(Token::DoubleColon) - }) - } else { - false - }; - - let origin = if external_function { - let function = lexer.next_ident()?; - crate::FunctionOrigin::External(function.to_string()) - } else if let Ok(function) = lexer.next_ident() { - if let Some(&function) = self.function_lookup.get(function) { - crate::FunctionOrigin::Local(function) + let name = lexer.next_ident()?; + //TODO: avoid code duplication with `parse_singular_expression` + Ok(if let Some(fun) = conv::map_standard_fun(name) { + lexer.expect(Token::Paren('('))?; + let arg_count = fun.argument_count(); + let arg = self.parse_general_expression(&mut lexer, ctx.reborrow())?; + let arg1 = if arg_count > 1 { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(&mut lexer, ctx.reborrow())?) } else { + None + }; + let arg2 = if arg_count > 1 { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(&mut lexer, ctx.reborrow())?) + } else { + None + }; + lexer.expect(Token::Paren(')'))?; + let expr = crate::Expression::Math { + fun, + arg, + arg1, + arg2, + }; + Some((expr, lexer)) + } else if let Some(&function) = self.function_lookup.get(name) { + if !lexer.skip(Token::Paren('(')) { return Ok(None); } - } else { - return Ok(None); - }; - if !lexer.skip(Token::Paren('(')) { - return Ok(None); - } - - let mut arguments = Vec::new(); - while !lexer.skip(Token::Paren(')')) { - if !arguments.is_empty() { - lexer.expect(Token::Separator(','))?; + let mut arguments = Vec::new(); + while !lexer.skip(Token::Paren(')')) { + if !arguments.is_empty() { + lexer.expect(Token::Separator(','))?; + } + let arg = self.parse_general_expression(&mut lexer, ctx.reborrow())?; + arguments.push(arg); } - let arg = self.parse_general_expression(&mut lexer, ctx.reborrow())?; - arguments.push(arg); - } - Ok(Some((crate::Expression::Call { origin, arguments }, lexer))) + + let expr = crate::Expression::Call { + function, + arguments, + }; + Some((expr, lexer)) + } else { + None + }) } fn parse_const_expression<'a>( @@ -605,12 +619,12 @@ impl Parser { expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }), Token::Word(word) => { - if let Some(fun) = conv::get_intrinsic(word) { + if let Some(fun) = conv::map_relational_fun(word) { lexer.expect(Token::Paren('('))?; let argument = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Intrinsic { fun, argument }) - } else if let Some(axis) = conv::get_derivative(word) { + Some(crate::Expression::Relational { fun, argument }) + } else if let Some(axis) = conv::map_derivative_axis(word) { lexer.expect(Token::Paren('('))?; let expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; @@ -624,40 +638,32 @@ impl Parser { kind, convert: true, }) - } else if let Some(arg_count) = conv::get_standard_fun(word) { + } else if let Some(fun) = conv::map_standard_fun(word) { lexer.expect(Token::Paren('('))?; - let mut arguments = Vec::with_capacity(arg_count); - for i in 0..arg_count { - let arg = self.parse_general_expression(lexer, ctx.reborrow())?; - arguments.push(arg); - lexer.expect(if i + 1 == arg_count { - Token::Paren(')') - } else { - Token::Separator(',') - })?; - } - Some(crate::Expression::Call { - origin: crate::FunctionOrigin::External(word.to_string()), - arguments, + let arg_count = fun.argument_count(); + let arg = self.parse_general_expression(lexer, ctx.reborrow())?; + let arg1 = if arg_count > 1 { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; + let arg2 = if arg_count > 2 { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::Math { + fun, + arg, + arg1, + arg2, }) } else { + // texture sampling match word { - "dot" => { - lexer.expect(Token::Paren('('))?; - let a = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let b = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::DotProduct(a, b)) - } - "cross" => { - lexer.expect(Token::Paren('('))?; - let a = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let b = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::CrossProduct(a, b)) - } "textureSample" => { lexer.expect(Token::Paren('('))?; let image_name = lexer.next_ident()?; diff --git a/src/lib.rs b/src/lib.rs index 7b141b538..61b835c4b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -516,19 +516,6 @@ pub enum BinaryOperator { ShiftRight, } -/// Built-in shader function. -#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] -#[cfg_attr(feature = "serialize", derive(Serialize))] -#[cfg_attr(feature = "deserialize", derive(Deserialize))] -pub enum IntrinsicFunction { - Any, - All, - IsNan, - IsInf, - IsFinite, - IsNormal, -} - /// Axis on which to compute a derivative. #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -539,17 +526,76 @@ pub enum DerivativeAxis { Width, } -/// Origin of a function to call. -#[derive(Clone, Debug, PartialEq)] +/// Built-in shader function for testing relation between values. +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] -pub enum FunctionOrigin { - Local(Handle), - // External { - // namespace: String, // Maybe this should be a handle to a namespace Arena? - // function: String, - // }, - External(String), +pub enum RelationalFunction { + All, + Any, + IsNan, + IsInf, + IsFinite, + IsNormal, +} + +/// Built-in shader function for math. +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum MathFunction { + // comparison + Abs, + Min, + Max, + Clamp, + // trigonometry + Cos, + Cosh, + Sin, + Sinh, + Tan, + Tanh, + Acos, + Asin, + Atan, + Atan2, + // decomposition + Ceil, + Floor, + Round, + Fract, + Trunc, + Modf, + Frexp, + Ldexp, + // exponent + Exp, + Exp2, + Log, + Log2, + Pow, + // geometry + Dot, + Outer, + Cross, + Distance, + Length, + Normalize, + FaceForward, + Reflect, + // computational + Sign, + Fma, + Mix, + Step, + SmoothStep, + Sqrt, + InverseSqrt, + Determinant, + // bits + CountOneBits, + ReverseBits, } /// Sampling modifier to control the level of detail. @@ -628,17 +674,26 @@ pub enum Expression { accept: Handle, reject: Handle, }, - /// Call an intrinsic function. - Intrinsic { - fun: IntrinsicFunction, + /// Compute the derivative on an axis. + Derivative { + axis: DerivativeAxis, + //modifier, + expr: Handle, + }, + /// Call a relational function. + Relational { + fun: RelationalFunction, argument: Handle, }, + /// Call a math function + Math { + fun: MathFunction, + arg: Handle, + arg1: Option>, + arg2: Option>, + }, /// Transpose of a matrix. Transpose(Handle), - /// Dot product between two vectors. - DotProduct(Handle, Handle), - /// Cross product between two vectors. - CrossProduct(Handle, Handle), /// Cast a simply type to another kind. As { /// Source expression, which can only be a scalar or a vector. @@ -648,15 +703,9 @@ pub enum Expression { /// True = conversion needs to take place; False = bitcast. convert: bool, }, - /// Compute the derivative on an axis. - Derivative { - axis: DerivativeAxis, - //modifier, - expr: Handle, - }, /// Call another function. Call { - origin: FunctionOrigin, + function: Handle, arguments: Vec>, }, /// Get the length of an array. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index e3835f263..29f117684 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -88,36 +88,37 @@ where self.traverse_expr(accept); self.traverse_expr(reject); } - E::Intrinsic { argument, .. } => { + E::Derivative { expr, .. } => { + self.traverse_expr(expr); + } + E::Relational { argument, .. } => { self.traverse_expr(argument); } + E::Math { + arg, arg1, arg2, .. + } => { + self.traverse_expr(arg); + if let Some(arg) = arg1 { + self.traverse_expr(arg); + } + if let Some(arg) = arg2 { + self.traverse_expr(arg); + } + } E::Transpose(matrix) => { self.traverse_expr(matrix); } - E::DotProduct(left, right) => { - self.traverse_expr(left); - self.traverse_expr(right); - } - E::CrossProduct(left, right) => { - self.traverse_expr(left); - self.traverse_expr(right); - } E::As { expr, .. } => { self.traverse_expr(expr); } - E::Derivative { expr, .. } => { - self.traverse_expr(expr); - } E::Call { - ref origin, + function, ref arguments, } => { for &argument in arguments { self.traverse_expr(argument); } - if let crate::FunctionOrigin::Local(fun) = *origin { - self.visitor.visit_fun(fun); - } + self.visitor.visit_fun(function); } E::ArrayLength(expr) => { self.traverse_expr(expr); diff --git a/src/proc/mod.rs b/src/proc/mod.rs index d8388b4c5..23ff41373 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -67,3 +67,62 @@ impl crate::TypeInner { } } } + +impl crate::MathFunction { + pub fn argument_count(&self) -> usize { + match *self { + // comparison + Self::Abs => 1, + Self::Min => 2, + Self::Max => 2, + Self::Clamp => 3, + // trigonometry + Self::Cos => 1, + Self::Cosh => 1, + Self::Sin => 1, + Self::Sinh => 1, + Self::Tan => 1, + Self::Tanh => 1, + Self::Acos => 1, + Self::Asin => 1, + Self::Atan => 1, + Self::Atan2 => 2, + // decomposition + Self::Ceil => 1, + Self::Floor => 1, + Self::Round => 1, + Self::Fract => 1, + Self::Trunc => 1, + Self::Modf => 2, + Self::Frexp => 2, + Self::Ldexp => 2, + // exponent + Self::Exp => 1, + Self::Exp2 => 1, + Self::Log => 1, + Self::Log2 => 1, + Self::Pow => 2, + // geometry + Self::Dot => 2, + Self::Outer => 2, + Self::Cross => 2, + Self::Distance => 2, + Self::Length => 1, + Self::Normalize => 1, + Self::FaceForward => 3, + Self::Reflect => 2, + // computational + Self::Sign => 1, + Self::Fma => 3, + Self::Mix => 3, + Self::Step => 2, + Self::SmoothStep => 3, + Self::Sqrt => 1, + Self::InverseSqrt => 1, + Self::Determinant => 1, + // bits + Self::CountOneBits => 1, + Self::ReverseBits => 1, + } + } +} diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index b09893c17..8fe370163 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -246,7 +246,122 @@ impl Typifier { | crate::BinaryOperator::ShiftRight => self.resolutions[left.index()].clone(), }, crate::Expression::Select { accept, .. } => self.resolutions[accept.index()].clone(), - crate::Expression::Intrinsic { .. } => unimplemented!(), + crate::Expression::Derivative { axis: _, expr } => { + self.resolutions[expr.index()].clone() + } + crate::Expression::Relational { .. } => Resolution::Value(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: 4, + }), + crate::Expression::Math { + fun, + arg, + arg1, + arg2: _, + } => { + use crate::MathFunction as Mf; + match fun { + // comparison + Mf::Abs | + Mf::Min | + Mf::Max | + Mf::Clamp | + // trigonometry + Mf::Cos | + Mf::Cosh | + Mf::Sin | + Mf::Sinh | + Mf::Tan | + Mf::Tanh | + Mf::Acos | + Mf::Asin | + Mf::Atan | + Mf::Atan2 | + // decomposition + Mf::Ceil | + Mf::Floor | + Mf::Round | + Mf::Fract | + Mf::Trunc | + Mf::Modf | + Mf::Frexp | + Mf::Ldexp | + // exponent + Mf::Exp | + Mf::Exp2 | + Mf::Log | + Mf::Log2 | + Mf::Pow => self.resolutions[arg.index()].clone(), + // geometry + Mf::Dot => match *self.get(arg, types) { + crate::TypeInner::Vector { + kind, + size: _, + width, + } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "dot product".to_string(), + operand: format!("{:?}", other), + }) + } + }, + Mf::Outer => { + let arg1 = arg1.ok_or_else(|| ResolveError::IncompatibleOperand { + op: "outer product".to_string(), + operand: "".to_string(), + })?; + match (self.get(arg, types), self.get(arg1,types)) { + (&crate::TypeInner::Vector {kind: _, size: columns,width}, &crate::TypeInner::Vector{ size: rows, .. }) => Resolution::Value(crate::TypeInner::Matrix { columns, rows, width }), + (left, right) => { + return Err(ResolveError::IncompatibleOperands { + op: "outer product".to_string(), + left: format!("{:?}", left), + right: format!("{:?}", right), + }) + } + } + }, + Mf::Cross => self.resolutions[arg.index()].clone(), + Mf::Distance | + Mf::Length => match *self.get(arg, types) { + crate::TypeInner::Scalar {width,kind} | + crate::TypeInner::Vector {width,kind,size:_} => Resolution::Value(crate::TypeInner::Scalar { kind, width }), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: format!("{:?}", fun), + operand: format!("{:?}", other), + }) + } + }, + Mf::Normalize | + Mf::FaceForward | + Mf::Reflect => self.resolutions[arg.index()].clone(), + // computational + Mf::Sign | + Mf::Fma | + Mf::Mix | + Mf::Step | + Mf::SmoothStep | + Mf::Sqrt | + Mf::InverseSqrt => self.resolutions[arg.index()].clone(), + Mf::Determinant => match *self.get(arg, types) { + crate::TypeInner::Matrix { + width, + .. + } => Resolution::Value(crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width }), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "determinant".to_string(), + operand: format!("{:?}", other), + }) + } + }, + // bits + Mf::CountOneBits | + Mf::ReverseBits => self.resolutions[arg.index()].clone(), + } + } crate::Expression::Transpose(expr) => match *self.get(expr, types) { crate::TypeInner::Matrix { columns, @@ -264,20 +379,6 @@ impl Typifier { }) } }, - crate::Expression::DotProduct(left_expr, _) => match *self.get(left_expr, types) { - crate::TypeInner::Vector { - kind, - size: _, - width, - } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "dot product".to_string(), - operand: format!("{:?}", other), - }) - } - }, - crate::Expression::CrossProduct(_, _) => unimplemented!(), crate::Expression::As { expr, kind, @@ -298,45 +399,11 @@ impl Typifier { }) } }, - crate::Expression::Derivative { .. } => unimplemented!(), crate::Expression::Call { - origin: crate::FunctionOrigin::External(ref name), - ref arguments, - } => match name.as_str() { - "distance" | "length" => match *self.get(arguments[0], types) { - crate::TypeInner::Vector { kind, width, .. } - | crate::TypeInner::Scalar { kind, width } => { - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: name.clone(), - operand: format!("{:?}", other), - }) - } - }, - "dot" => match *self.get(arguments[0], types) { - crate::TypeInner::Vector { kind, width, .. } => { - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: name.clone(), - operand: format!("{:?}", other), - }) - } - }, - //Note: `cross` is here too, we still need to figure out what to do with it - "abs" | "atan2" | "cos" | "sin" | "floor" | "inverse" | "normalize" | "min" - | "max" | "reflect" | "pow" | "clamp" | "fclamp" | "mix" | "step" - | "smoothstep" | "cross" => self.resolutions[arguments[0].index()].clone(), - _ => return Err(ResolveError::FunctionNotDefined { name: name.clone() }), - }, - crate::Expression::Call { - origin: crate::FunctionOrigin::Local(handle), + function, arguments: _, } => { - let ty = ctx.functions[handle] + let ty = ctx.functions[function] .return_type .ok_or(ResolveError::FunctionReturnsVoid)?; Resolution::Handle(ty) diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl index 9bc98052e..ec2376887 100644 --- a/test-data/boids.wgsl +++ b/test-data/boids.wgsl @@ -23,10 +23,10 @@ import "GLSL.std.450" as std; [[stage(vertex)]] fn main() -> void { - var angle : f32 = -std::atan2(a_particleVel.x, a_particleVel.y); + var angle : f32 = -atan2(a_particleVel.x, a_particleVel.y); var pos : vec2 = vec2( - (a_pos.x * std::cos(angle)) - (a_pos.y * std::sin(angle)), - (a_pos.x * std::sin(angle)) + (a_pos.y * std::cos(angle))); + (a_pos.x * cos(angle)) - (a_pos.y * sin(angle)), + (a_pos.x * sin(angle)) + (a_pos.y * cos(angle))); gl_Position = vec4(pos + a_particlePos, 0.0, 1.0); return; } @@ -97,14 +97,14 @@ fn main() -> void { pos = particlesA.particles[i].pos.xy; vel = particlesA.particles[i].vel.xy; - if (std::distance(pos, vPos) < params.rule1Distance) { + if (distance(pos, vPos) < params.rule1Distance) { cMass = cMass + pos; cMassCount = cMassCount + 1; } - if (std::distance(pos, vPos) < params.rule2Distance) { + if (distance(pos, vPos) < params.rule2Distance) { colVel = colVel - (pos - vPos); } - if (std::distance(pos, vPos) < params.rule3Distance) { + if (distance(pos, vPos) < params.rule3Distance) { cVel = cVel + vel; cVelCount = cVelCount + 1; } @@ -124,7 +124,7 @@ fn main() -> void { (cVel * params.rule3Scale); # clamp velocity for a more pleasing simulation - vVel = std::normalize(vVel) * std::fclamp(std::length(vVel), 0.0, 0.1); + vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1); # kinematic update vPos = vPos + (vVel * params.deltaT); From 9a625a570e5f0055f525ca5e1b44c5960d7c1ece Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Tue, 8 Dec 2020 01:53:29 -0330 Subject: [PATCH 0318/2212] Add insta prototype --- Cargo.toml | 2 + tests/convert.rs | 282 -------------------- tests/snapshots.rs | 112 ++++++++ tests/snapshots/in/quad.param.ron | 7 + tests/snapshots/in/quad.wgsl | 25 ++ tests/snapshots/snapshots__quad.msl.snap | 45 ++++ tests/snapshots/snapshots__quad.spvasm.snap | 68 +++++ 7 files changed, 259 insertions(+), 282 deletions(-) delete mode 100644 tests/convert.rs create mode 100644 tests/snapshots.rs create mode 100644 tests/snapshots/in/quad.param.ron create mode 100644 tests/snapshots/in/quad.wgsl create mode 100644 tests/snapshots/snapshots__quad.msl.snap create mode 100644 tests/snapshots/snapshots__quad.spvasm.snap diff --git a/Cargo.toml b/Cargo.toml index b6ac07d55..5de97e925 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,3 +38,5 @@ env_logger = "0.6" ron = "0.6" serde = { version = "1.0", features = ["derive"] } spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } +insta = { version = "1.3", features = ["glob"] } +rspirv = "0.7" diff --git a/tests/convert.rs b/tests/convert.rs deleted file mode 100644 index 593f9b433..000000000 --- a/tests/convert.rs +++ /dev/null @@ -1,282 +0,0 @@ -#[allow(dead_code)] -fn load_test_data(name: &str) -> String { - let path = format!("{}/test-data/{}", env!("CARGO_MANIFEST_DIR"), name); - std::fs::read_to_string(path).unwrap() -} - -#[cfg(feature = "wgsl-in")] -fn load_wgsl(name: &str) -> naga::Module { - let input = load_test_data(name); - naga::front::wgsl::parse_str(&input).unwrap() -} - -#[cfg(feature = "spv-in")] -fn load_spv(name: &str) -> naga::Module { - let path = format!("{}/test-data/spv/{}", env!("CARGO_MANIFEST_DIR"), name); - let input = std::fs::read(path).unwrap(); - naga::front::spv::parse_u8_slice(&input, &Default::default()).unwrap() -} - -#[cfg(feature = "glsl-in")] -fn load_glsl(name: &str, entry: &str, stage: naga::ShaderStage) -> naga::Module { - let input = load_test_data(name); - naga::front::glsl::parse_str(&input, entry, stage, Default::default()).unwrap() -} - -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_quad() { - let module = load_wgsl("quad.wgsl"); - naga::proc::Validator::new().validate(&module).unwrap(); - #[cfg(feature = "msl-out")] - { - use naga::back::msl; - let mut binding_map = msl::BindingMap::default(); - binding_map.insert( - msl::BindSource { - stage: naga::ShaderStage::Fragment, - group: 0, - binding: 0, - }, - msl::BindTarget { - buffer: None, - texture: Some(1), - sampler: None, - mutable: false, - }, - ); - binding_map.insert( - msl::BindSource { - stage: naga::ShaderStage::Fragment, - group: 0, - binding: 1, - }, - msl::BindTarget { - buffer: None, - texture: None, - sampler: Some(1), - mutable: false, - }, - ); - let options = msl::Options { - lang_version: (1, 0), - spirv_cross_compatibility: false, - binding_map, - }; - msl::write_string(&module, &options).unwrap(); - } - #[cfg(feature = "spv-out")] - { - use naga::back::spv; - let capabilities = Some(spirv::Capability::Shader).into_iter().collect(); - spv::write_vec(&module, spv::WriterFlags::empty(), capabilities).unwrap(); - } - #[cfg(feature = "glsl-out")] - { - use naga::back::glsl; - let mut options = glsl::Options { - version: glsl::Version::Embedded(310), - entry_point: (naga::ShaderStage::Compute, String::from("main")), - }; - - let mut output = Vec::new(); - { - options.entry_point.0 = naga::ShaderStage::Vertex; - let mut writer = glsl::Writer::new(&mut output, &module, &options).unwrap(); - writer.write().unwrap(); - } - { - options.entry_point.0 = naga::ShaderStage::Fragment; - let mut writer = glsl::Writer::new(&mut output, &module, &options).unwrap(); - writer.write().unwrap(); - } - } -} - -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_boids() { - let module = load_wgsl("boids.wgsl"); - naga::proc::Validator::new().validate(&module).unwrap(); - #[cfg(feature = "msl-out")] - { - use naga::back::msl; - let mut binding_map = msl::BindingMap::default(); - binding_map.insert( - msl::BindSource { - stage: naga::ShaderStage::Compute, - group: 0, - binding: 0, - }, - msl::BindTarget { - buffer: Some(0), - texture: None, - sampler: None, - mutable: false, - }, - ); - binding_map.insert( - msl::BindSource { - stage: naga::ShaderStage::Compute, - group: 0, - binding: 1, - }, - msl::BindTarget { - buffer: Some(1), - texture: None, - sampler: Some(1), - mutable: false, - }, - ); - binding_map.insert( - msl::BindSource { - stage: naga::ShaderStage::Compute, - group: 0, - binding: 2, - }, - msl::BindTarget { - buffer: Some(2), - texture: None, - sampler: Some(1), - mutable: false, - }, - ); - let options = msl::Options { - lang_version: (1, 0), - spirv_cross_compatibility: false, - binding_map, - }; - msl::write_string(&module, &options).unwrap(); - } - #[cfg(feature = "spv-out")] - { - use naga::back::spv; - let capabilities = Some(spirv::Capability::Shader).into_iter().collect(); - if let Err(e) = spv::write_vec(&module, spv::WriterFlags::empty(), capabilities) { - //TODO: panic here when `spv-out` supports it - println!("Quad SPIR-V error {:?}", e); - } - } - #[cfg(feature = "glsl-out")] - { - use naga::back::glsl; - let options = glsl::Options { - version: glsl::Version::Embedded(310), - entry_point: (naga::ShaderStage::Compute, String::from("main")), - }; - - let mut output = Vec::new(); - let mut writer = glsl::Writer::new(&mut output, &module, &options).unwrap(); - writer.write().unwrap(); - } -} - -#[cfg(feature = "spv-in")] -#[test] -fn convert_cube_spv() { - let mut validator = naga::proc::Validator::new(); - let vs = load_spv("cube.vert.spv"); - validator.validate(&vs).unwrap(); - let fs = load_spv("cube.frag.spv"); - validator.validate(&fs).unwrap(); - #[cfg(feature = "msl-out")] - { - use naga::back::msl; - let mut binding_map = msl::BindingMap::default(); - binding_map.insert( - msl::BindSource { - stage: naga::ShaderStage::Vertex, - group: 0, - binding: 0, - }, - msl::BindTarget { - buffer: Some(0), - texture: None, - sampler: None, - mutable: false, - }, - ); - binding_map.insert( - msl::BindSource { - stage: naga::ShaderStage::Fragment, - group: 0, - binding: 1, - }, - msl::BindTarget { - buffer: None, - texture: Some(1), - sampler: None, - mutable: false, - }, - ); - binding_map.insert( - msl::BindSource { - stage: naga::ShaderStage::Fragment, - group: 0, - binding: 2, - }, - msl::BindTarget { - buffer: None, - texture: None, - sampler: Some(1), - mutable: false, - }, - ); - let options = msl::Options { - lang_version: (1, 0), - spirv_cross_compatibility: false, - binding_map, - }; - msl::write_string(&vs, &options).unwrap(); - msl::write_string(&fs, &options).unwrap(); - } -} - -#[cfg(feature = "spv-in")] -#[test] -fn convert_quad_spv() { - let mut validator = naga::proc::Validator::new(); - // check that integer `gl_VertexIndex` is treated as unsigned - let vs = load_spv("quad.vert.spv"); - validator.validate(&vs).unwrap(); - #[cfg(feature = "msl-out")] - { - use naga::back::msl; - let options = msl::Options { - lang_version: (1, 0), - spirv_cross_compatibility: false, - binding_map: msl::BindingMap::default(), - }; - msl::write_string(&vs, &options).unwrap(); - } -} - -#[cfg(feature = "glsl-in")] -#[test] -#[ignore] -fn convert_phong_lighting() { - let module = load_glsl( - "glsl_phong_lighting.frag", - "main", - naga::ShaderStage::Fragment, - ); - naga::proc::Validator::new().validate(&module).unwrap(); - - #[cfg(feaure = "spv-out")] - { - let flags = naga::back::spv::WriterFlags::empty(); - let _ = naga::back::spv::write_vec(&module, flags); - } -} - -//TODO: get this working again (glsl-new) -// #[cfg(feature = "glsl-in")] -// #[test] -// fn constant_expressions() { -// let module = load_glsl( -// "glsl_constant_expression.vert", -// "main", -// naga::ShaderStage::Fragment, -// ); -// naga::proc::Validator::new().validate(&module).unwrap(); -// } diff --git a/tests/snapshots.rs b/tests/snapshots.rs new file mode 100644 index 000000000..6e20bcbe3 --- /dev/null +++ b/tests/snapshots.rs @@ -0,0 +1,112 @@ +use serde::Deserialize; + +#[derive(Hash, PartialEq, Eq, Deserialize)] +enum Stage { + Vertex, + Fragment, + Compute, +} + +#[derive(Hash, PartialEq, Eq, Deserialize)] +struct BindSource { + stage: Stage, + group: u32, + binding: u32, +} + +#[derive(Deserialize)] +struct BindTarget { + #[serde(default)] + buffer: Option, + #[serde(default)] + texture: Option, + #[serde(default)] + sampler: Option, + #[serde(default)] + mutable: bool, +} + +#[derive(Default, Deserialize)] +struct Parameters { + #[serde(default)] + spv_flow_dump_prefix: String, + #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + spv_capabilities: naga::FastHashSet, + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] + mtl_bindings: naga::FastHashMap, +} + +#[cfg(feature = "msl-out")] +fn check_output_msl(module: &naga::Module, name: &str, params: &Parameters) { + use naga::back::msl; + let mut binding_map = msl::BindingMap::default(); + for (key, value) in params.mtl_bindings.iter() { + binding_map.insert( + msl::BindSource { + stage: match key.stage { + Stage::Vertex => naga::ShaderStage::Vertex, + Stage::Fragment => naga::ShaderStage::Fragment, + Stage::Compute => naga::ShaderStage::Compute, + }, + group: key.group, + binding: key.binding, + }, + msl::BindTarget { + buffer: value.buffer, + texture: value.texture, + sampler: value.sampler, + mutable: value.mutable, + }, + ); + } + let options = msl::Options { + lang_version: (1, 0), + spirv_cross_compatibility: false, + binding_map, + }; + let (msl, _) = msl::write_string(&module, &options).unwrap(); + insta::assert_snapshot!(format!("{}{}", name, ".msl"), msl); +} + +#[cfg(feature = "spv-out")] +fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { + use naga::back::spv; + use rspirv::binary::Disassemble; + let spv = spv::write_vec( + &module, + spv::WriterFlags::NONE, + params.spv_capabilities.clone(), + ) + .unwrap(); + let dis = rspirv::dr::load_words(spv) + .expect("Produced invalid SPIR-V") + .disassemble(); + insta::assert_snapshot!(format!("{}{}", name, ".spvasm"), dis); +} + +#[cfg(feature = "wgsl-in")] +fn convert_wgsl(name: &str) { + let params = + match std::fs::read_to_string(format!("tests/snapshots/in/{}{}", name, ".param.ron")) { + Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), + Err(_) => Parameters::default(), + }; + + let module = naga::front::wgsl::parse_str( + &std::fs::read_to_string(format!("tests/snapshots/in/{}{}", name, ".wgsl")) + .expect("Couldn't find wgsl file"), + ) + .unwrap(); + naga::proc::Validator::new().validate(&module).unwrap(); + + #[cfg(feature = "msl-out")] + check_output_msl(&module, name, ¶ms); + #[cfg(feature = "spv-out")] + check_output_spv(&module, name, ¶ms); +} + +#[cfg(feature = "wgsl-in")] +#[test] +fn converts_wgsl_quad() { + convert_wgsl("quad"); +} diff --git a/tests/snapshots/in/quad.param.ron b/tests/snapshots/in/quad.param.ron new file mode 100644 index 000000000..25747c169 --- /dev/null +++ b/tests/snapshots/in/quad.param.ron @@ -0,0 +1,7 @@ +( + spv_capabilities: [ Shader ], + mtl_bindings: { + (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), + (stage: Fragment, group: 0, binding: 1): (sampler: Some(0)), + } +) diff --git a/tests/snapshots/in/quad.wgsl b/tests/snapshots/in/quad.wgsl new file mode 100644 index 000000000..16cbd2698 --- /dev/null +++ b/tests/snapshots/in/quad.wgsl @@ -0,0 +1,25 @@ +# vertex +const c_scale: f32 = 1.2; +[[location(0)]] var a_pos : vec2; +[[location(1)]] var a_uv : vec2; +[[location(0)]] var v_uv : vec2; +[[builtin(position)]] var o_position : vec4; + +[[stage(vertex)]] +fn main() -> void { + v_uv = a_uv; + o_position = vec4(c_scale * a_pos, 0.0, 1.0); + return; +} + +# fragment +[[location(0)]] var v_uv : vec2; +[[group(0), binding(0)]] var u_texture : texture_sampled_2d; +[[group(0), binding(1)]] var u_sampler : sampler; +[[location(0)]] var o_color : vec4; + +[[stage(fragment)]] +fn main() -> void { + o_color = textureSample(u_texture, u_sampler, v_uv); + return; +} diff --git a/tests/snapshots/snapshots__quad.msl.snap b/tests/snapshots/snapshots__quad.msl.snap new file mode 100644 index 000000000..d96f5e3e0 --- /dev/null +++ b/tests/snapshots/snapshots__quad.msl.snap @@ -0,0 +1,45 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +typedef float type; +typedef float2 type1; +typedef float4 type2; +typedef texture2d type3; +typedef sampler type4; + +struct main1Input { + type1 a_pos [[attribute(0)]]; + type1 a_uv [[attribute(1)]]; +}; +struct main1Output { + type1 v_uv [[user(loc0)]]; + type2 o_position [[position]]; +}; +vertex main1Output main1( + main1Input input [[stage_in]] +) { + main1Output output; + output.v_uv = input.a_uv; + output.o_position = float4(1.2 * input.a_pos, 0.0, 1.0); + return output; +} +struct main2Input { + type1 v_uv1 [[user(loc0)]]; +}; +struct main2Output { + type2 o_color [[color(0)]]; +}; +fragment main2Output main2( + main2Input input [[stage_in]], + type3 u_texture [[texture(0)]], + type4 u_sampler [[sampler(0)]] +) { + main2Output output; + output.o_color = u_texture.sample(u_sampler, input.v_uv1); + return output; +} + diff --git a/tests/snapshots/snapshots__quad.spvasm.snap b/tests/snapshots/snapshots__quad.spvasm.snap new file mode 100644 index 000000000..bfeeb453a --- /dev/null +++ b/tests/snapshots/snapshots__quad.spvasm.snap @@ -0,0 +1,68 @@ +--- +source: tests/snapshots.rs +expression: dis +--- +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 39 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %3 "main" %18 %10 %6 %13 +OpEntryPoint Fragment %23 "main" %35 %25 +OpExecutionMode %23 OriginUpperLeft +OpDecorate %6 Location 0 +OpDecorate %10 Location 1 +OpDecorate %13 BuiltIn Position +OpDecorate %18 Location 0 +OpDecorate %25 Location 0 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 0 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 1 +OpDecorate %35 Location 0 +%2 = OpTypeVoid +%4 = OpTypeFunction %2 +%8 = OpTypeFloat 32 +%7 = OpTypeVector %8 2 +%9 = OpTypePointer Output %7 +%6 = OpVariable %9 Output +%11 = OpTypePointer Input %7 +%10 = OpVariable %11 Input +%14 = OpTypeVector %8 4 +%15 = OpTypePointer Output %14 +%13 = OpVariable %15 Output +%17 = OpConstant %8 1.2 +%18 = OpVariable %11 Input +%20 = OpConstant %8 0.0 +%21 = OpConstant %8 1.0 +%25 = OpVariable %15 Output +%27 = OpTypeImage %8 2D 0 0 0 1 Unknown +%28 = OpTypePointer UniformConstant %27 +%26 = OpVariable %28 UniformConstant +%30 = OpTypeSampledImage %27 +%32 = OpTypeSampler +%33 = OpTypePointer UniformConstant %32 +%31 = OpVariable %33 UniformConstant +%35 = OpVariable %11 Input +%3 = OpFunction %2 None %4 +%5 = OpLabel +%12 = OpLoad %7 %10 +OpStore %6 %12 +%19 = OpLoad %7 %18 +%16 = OpVectorTimesScalar %7 %19 %17 +%22 = OpCompositeConstruct %14 %16 %20 %21 +OpStore %13 %22 +OpReturn +OpFunctionEnd +%23 = OpFunction %2 None %4 +%24 = OpLabel +%29 = OpLoad %27 %26 +%34 = OpLoad %32 %31 +%36 = OpLoad %7 %35 +%37 = OpSampledImage %30 %29 %34 +%38 = OpImageSampleImplicitLod %14 %37 %36 +OpStore %25 %38 +OpReturn +OpFunctionEnd From 51cdb0403a677a4899b27c7217cc8c9c3862e0f4 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Tue, 8 Dec 2020 23:19:59 -0330 Subject: [PATCH 0319/2212] Add snapshots for simple.wgsl --- tests/snapshots.rs | 6 +++++ tests/snapshots/in/simple.param.ron | 5 ++++ tests/snapshots/in/simple.wgsl | 8 ++++++ tests/snapshots/snapshots__simple.msl.snap | 23 ++++++++++++++++ tests/snapshots/snapshots__simple.spvasm.snap | 27 +++++++++++++++++++ 5 files changed, 69 insertions(+) create mode 100644 tests/snapshots/in/simple.param.ron create mode 100644 tests/snapshots/in/simple.wgsl create mode 100644 tests/snapshots/snapshots__simple.msl.snap create mode 100644 tests/snapshots/snapshots__simple.spvasm.snap diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 6e20bcbe3..6ceb0ad1b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -110,3 +110,9 @@ fn convert_wgsl(name: &str) { fn converts_wgsl_quad() { convert_wgsl("quad"); } + +#[cfg(feature = "wgsl-in")] +#[test] +fn converts_wgsl_simple() { + convert_wgsl("simple"); +} diff --git a/tests/snapshots/in/simple.param.ron b/tests/snapshots/in/simple.param.ron new file mode 100644 index 000000000..4adad3622 --- /dev/null +++ b/tests/snapshots/in/simple.param.ron @@ -0,0 +1,5 @@ +( + spv_capabilities: [ Shader ], + mtl_bindings: { + } +) diff --git a/tests/snapshots/in/simple.wgsl b/tests/snapshots/in/simple.wgsl new file mode 100644 index 000000000..bbe591d8f --- /dev/null +++ b/tests/snapshots/in/simple.wgsl @@ -0,0 +1,8 @@ +# vertex +[[builtin(position)]] var o_position : vec4; + +[[stage(vertex)]] +fn main() -> void { + o_position = vec4(1); + return; +} diff --git a/tests/snapshots/snapshots__simple.msl.snap b/tests/snapshots/snapshots__simple.msl.snap new file mode 100644 index 000000000..01314fdb2 --- /dev/null +++ b/tests/snapshots/snapshots__simple.msl.snap @@ -0,0 +1,23 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +typedef float4 type; +typedef int type1; + +struct main1Input { +}; +struct main1Output { + type o_position [[position]]; +}; +vertex main1Output main1( + main1Input input [[stage_in]] +) { + main1Output output; + output.o_position = float4(1); + return output; +} + diff --git a/tests/snapshots/snapshots__simple.spvasm.snap b/tests/snapshots/snapshots__simple.spvasm.snap new file mode 100644 index 000000000..1d6cad3c4 --- /dev/null +++ b/tests/snapshots/snapshots__simple.spvasm.snap @@ -0,0 +1,27 @@ +--- +source: tests/snapshots.rs +expression: dis +--- +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 13 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %3 "main" %6 +OpDecorate %6 BuiltIn Position +%2 = OpTypeVoid +%4 = OpTypeFunction %2 +%8 = OpTypeFloat 32 +%7 = OpTypeVector %8 4 +%9 = OpTypePointer Output %7 +%6 = OpVariable %9 Output +%11 = OpTypeInt 32 1 +%10 = OpConstant %11 1 +%3 = OpFunction %2 None %4 +%5 = OpLabel +%12 = OpCompositeConstruct %7 %10 +OpStore %6 %12 +OpReturn +OpFunctionEnd From d71ebe288104a75aacc28f9fb580af687485f303 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Wed, 9 Dec 2020 01:16:23 -0330 Subject: [PATCH 0320/2212] Add snapshots for function.wgsl --- tests/snapshots.rs | 6 ++++ tests/snapshots/in/function.param.ron | 5 +++ tests/snapshots/in/function.wgsl | 8 +++++ tests/snapshots/snapshots__function.msl.snap | 27 ++++++++++++++++ .../snapshots/snapshots__function.spvasm.snap | 31 +++++++++++++++++++ 5 files changed, 77 insertions(+) create mode 100644 tests/snapshots/in/function.param.ron create mode 100644 tests/snapshots/in/function.wgsl create mode 100644 tests/snapshots/snapshots__function.msl.snap create mode 100644 tests/snapshots/snapshots__function.spvasm.snap diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 6ceb0ad1b..453a078b3 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -116,3 +116,9 @@ fn converts_wgsl_quad() { fn converts_wgsl_simple() { convert_wgsl("simple"); } + +#[cfg(feature = "wgsl-in")] +#[test] +fn converts_wgsl_function() { + convert_wgsl("function"); +} diff --git a/tests/snapshots/in/function.param.ron b/tests/snapshots/in/function.param.ron new file mode 100644 index 000000000..4adad3622 --- /dev/null +++ b/tests/snapshots/in/function.param.ron @@ -0,0 +1,5 @@ +( + spv_capabilities: [ Shader ], + mtl_bindings: { + } +) diff --git a/tests/snapshots/in/function.wgsl b/tests/snapshots/in/function.wgsl new file mode 100644 index 000000000..12549c7f9 --- /dev/null +++ b/tests/snapshots/in/function.wgsl @@ -0,0 +1,8 @@ +fn test_function(test: f32) -> f32 { + return test; +} + +[[stage(vertex)]] +fn main() -> void { + var test: f32 = test_function(1.0); +} diff --git a/tests/snapshots/snapshots__function.msl.snap b/tests/snapshots/snapshots__function.msl.snap new file mode 100644 index 000000000..cbaab5634 --- /dev/null +++ b/tests/snapshots/snapshots__function.msl.snap @@ -0,0 +1,27 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +typedef float type; + +type test_function( + type test +) { + return test; +} +struct main1Input { +}; +struct main1Output { +}; +vertex main1Output main1( + main1Input input [[stage_in]] +) { + main1Output output; + type test1; + test1 = test_function(1.0); + return output; +} + diff --git a/tests/snapshots/snapshots__function.spvasm.snap b/tests/snapshots/snapshots__function.spvasm.snap new file mode 100644 index 000000000..a28f333e1 --- /dev/null +++ b/tests/snapshots/snapshots__function.spvasm.snap @@ -0,0 +1,31 @@ +--- +source: tests/snapshots.rs +expression: dis +--- +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 16 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %11 "main" +%2 = OpTypeFloat 32 +%4 = OpTypePointer Function %2 +%6 = OpTypeFunction %2 %4 +%10 = OpTypeVoid +%12 = OpTypeFunction %10 +%15 = OpConstant %2 1.0 +%5 = OpFunction %2 None %6 +%3 = OpFunctionParameter %4 +%7 = OpLabel +%8 = OpLoad %2 %3 +OpReturnValue %8 +OpFunctionEnd +%11 = OpFunction %10 None %12 +%13 = OpLabel +%9 = OpVariable %4 Function +%14 = OpFunctionCall %2 %5 %15 +OpStore %9 %14 +OpReturn +OpFunctionEnd From edf5d857b1ee4e3431e141beb1cae08facc78a33 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 10 Dec 2020 00:13:07 -0500 Subject: [PATCH 0321/2212] Add workgroup id and size builtins --- src/back/glsl/mod.rs | 1 + src/back/msl/mod.rs | 1 + src/back/spv/writer.rs | 1 + src/front/glsl/variables.rs | 35 +++++++++++++++++++++++++++++++++++ src/front/spv/convert.rs | 1 + src/front/wgsl/conv.rs | 2 ++ src/lib.rs | 1 + src/proc/validator.rs | 18 ++++++++++-------- 8 files changed, 52 insertions(+), 8 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 3f87d1c76..419452e1c 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1643,6 +1643,7 @@ fn glsl_built_in(built_in: BuiltIn) -> &'static str { BuiltIn::LocalInvocationId => "gl_LocalInvocationID", BuiltIn::LocalInvocationIndex => "gl_LocalInvocationIndex", BuiltIn::WorkGroupId => "gl_WorkGroupID", + BuiltIn::WorkGroupSize => "gl_WorkGroupSize", } } diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index e96991ba3..cc08869e7 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -173,6 +173,7 @@ impl ResolvedBinding { Bi::LocalInvocationId => "thread_position_in_threadgroup", Bi::LocalInvocationIndex => "thread_index_in_threadgroup", Bi::WorkGroupId => "threadgroup_position_in_grid", + Bi::WorkGroupSize => "dispatch_threads_per_threadgroup", }; Ok(write!(out, "{}", name)?) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 9279cce03..db06ba320 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -791,6 +791,7 @@ impl Writer { crate::BuiltIn::LocalInvocationId => spirv::BuiltIn::LocalInvocationId, crate::BuiltIn::LocalInvocationIndex => spirv::BuiltIn::LocalInvocationIndex, crate::BuiltIn::WorkGroupId => spirv::BuiltIn::WorkgroupId, + crate::BuiltIn::WorkGroupSize => spirv::BuiltIn::WorkgroupSize, }; self.annotations diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 9f7633568..50343ba92 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -86,6 +86,41 @@ impl Program { expression = Some(exp); } + "gl_InstanceIndex" => { + #[cfg(feature = "glsl-validate")] + match self.shader_stage { + ShaderStage::Vertex => {} + _ => { + return Err(ErrorKind::VariableNotAvailable(name.into())); + } + }; + let h = self + .module + .global_variables + .fetch_or_append(GlobalVariable { + name: Some(name.into()), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::InstanceIndex)), + ty: self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + }, + }), + init: None, + interpolation: None, + storage_access: StorageAccess::empty(), + }); + self.lookup_global_variables.insert(name.into(), h); + let exp = self + .context + .expressions + .append(Expression::GlobalVariable(h)); + self.context.lookup_global_var_exps.insert(name.into(), exp); + + expression = Some(exp); + } _ => {} } diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 6036d0894..167863efa 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -118,6 +118,7 @@ pub fn map_builtin(word: spirv::Word) -> Result { Some(Bi::LocalInvocationId) => crate::BuiltIn::LocalInvocationId, Some(Bi::LocalInvocationIndex) => crate::BuiltIn::LocalInvocationIndex, Some(Bi::WorkgroupId) => crate::BuiltIn::WorkGroupId, + Some(Bi::WorkgroupSize) => crate::BuiltIn::WorkGroupSize, _ => return Err(Error::UnsupportedBuiltIn(word)), }) } diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 18de009aa..8beada188 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -25,6 +25,8 @@ pub fn map_built_in(word: &str) -> Result> { "global_invocation_id" => crate::BuiltIn::GlobalInvocationId, "local_invocation_id" => crate::BuiltIn::LocalInvocationId, "local_invocation_index" => crate::BuiltIn::LocalInvocationIndex, + "workgroup_id" => crate::BuiltIn::WorkGroupId, + "workgroup_size" => crate::BuiltIn::WorkGroupSize, _ => return Err(Error::UnknownBuiltin(word)), }) } diff --git a/src/lib.rs b/src/lib.rs index 61b835c4b..dff0233ac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -153,6 +153,7 @@ pub enum BuiltIn { LocalInvocationId, LocalInvocationIndex, WorkGroupId, + WorkGroupSize, } /// Number of bytes. diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 20061c1c4..f39a5bf85 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -154,13 +154,14 @@ impl crate::GlobalVariable { kind: Sk::Bool, width, }, - Bi::GlobalInvocationId | Bi::LocalInvocationId | Bi::WorkGroupId => { - Ti::Vector { - size: Vs::Tri, - kind: Sk::Uint, - width, - } - } + Bi::GlobalInvocationId + | Bi::LocalInvocationId + | Bi::WorkGroupId + | Bi::WorkGroupSize => Ti::Vector { + size: Vs::Tri, + kind: Sk::Uint, + width, + }, }; if types[self.ty].inner != ty_inner { log::warn!("Wrong builtin type: {:?}", types[self.ty]); @@ -375,7 +376,8 @@ impl Validator { | (crate::ShaderStage::Compute, crate::BuiltIn::GlobalInvocationId) | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationId) | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationIndex) - | (crate::ShaderStage::Compute, crate::BuiltIn::WorkGroupId) => 0, + | (crate::ShaderStage::Compute, crate::BuiltIn::WorkGroupId) + | (crate::ShaderStage::Compute, crate::BuiltIn::WorkGroupSize) => 0, _ => return Err(EntryPointError::InvalidBuiltIn(built_in)), }, Some(crate::Binding::Location(loc)) => 1 << loc, From eeb479ae94101d30c7905185411d015f159efa13 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 10 Dec 2020 00:31:44 -0500 Subject: [PATCH 0322/2212] [wgsl] support const locals --- src/front/glsl/parser.rs | 6 ++++- src/front/wgsl/mod.rs | 49 ++++++++++++++++++++++--------------- test-data/boids.wgsl | 10 +++----- test-data/simple/module.ron | 1 - 4 files changed, 37 insertions(+), 29 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 797917dd9..2d03b3a44 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -981,7 +981,11 @@ pomelo! { } statement_list ::= statement(s) { - vec![s] + //TODO: catch this earlier and don't populate the statements + match s { + Statement::Block(ref block) if block.is_empty() => vec![], + _ => vec![s], + } } statement_list ::= statement_list(mut ss) statement(s) { ss.push(s); ss } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 4beeada22..2d563c07a 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1407,16 +1407,25 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: StatementContext<'a, '_, '_>, - ) -> Result> { + ) -> Result, Error<'a>> { let backup = lexer.clone(); let word = match lexer.next() { - Token::Separator(';') => return Ok(crate::Statement::Block(Vec::new())), + Token::Separator(';') => return Ok(None), Token::Word(word) => word, other => return Err(Error::Unexpected(other)), }; self.scopes.push(Scope::Statement); let statement = match word { + "const" => { + let (name, _ty) = + self.parse_variable_ident_decl(lexer, context.types, context.constants)?; + lexer.expect(Token::Operation('='))?; + let expr_id = self.parse_general_expression(lexer, context.as_expression())?; + lexer.expect(Token::Separator(';'))?; + context.lookup_ident.insert(name, expr_id); + None + } "var" => { enum Init { Empty, @@ -1454,11 +1463,11 @@ impl Parser { context.lookup_ident.insert(name, expr_id); match init { - Init::Variable(value) => crate::Statement::Store { + Init::Variable(value) => Some(crate::Statement::Store { pointer: expr_id, value, - }, - _ => crate::Statement::Block(Vec::new()), + }), + _ => None, } } "return" => { @@ -1468,7 +1477,7 @@ impl Parser { None }; lexer.expect(Token::Separator(';'))?; - crate::Statement::Return { value } + Some(crate::Statement::Return { value }) } "if" => { lexer.expect(Token::Paren('('))?; @@ -1482,11 +1491,11 @@ impl Parser { Vec::new() }; - crate::Statement::If { + Some(crate::Statement::If { condition, accept, reject, - } + }) } "switch" => { lexer.expect(Token::Paren('('))?; @@ -1529,7 +1538,7 @@ impl Parser { break false; } let s = self.parse_statement(lexer, context.reborrow())?; - body.push(s); + body.extend(s); }; cases.push(crate::SwitchCase { @@ -1547,11 +1556,11 @@ impl Parser { } } - crate::Statement::Switch { + Some(crate::Statement::Switch { selector, cases, default, - } + }) } "loop" => { let mut body = Vec::new(); @@ -1568,14 +1577,14 @@ impl Parser { break; } let s = self.parse_statement(lexer, context.reborrow())?; - body.push(s); + body.extend(s); } - crate::Statement::Loop { body, continuing } + Some(crate::Statement::Loop { body, continuing }) } - "break" => crate::Statement::Break, - "continue" => crate::Statement::Continue, - "discard" => crate::Statement::Kill, + "break" => Some(crate::Statement::Break), + "continue" => Some(crate::Statement::Continue), + "discard" => Some(crate::Statement::Kill), ident => { // assignment if let Some(&var_expr) = context.lookup_ident.get(ident) { @@ -1583,17 +1592,17 @@ impl Parser { lexer.expect(Token::Operation('='))?; let value = self.parse_general_expression(lexer, context.as_expression())?; lexer.expect(Token::Separator(';'))?; - crate::Statement::Store { + Some(crate::Statement::Store { pointer: left, value, - } + }) } else if let Some((expr, new_lexer)) = self.parse_function_call(&backup, context.as_expression())? { *lexer = new_lexer; context.expressions.append(expr); lexer.expect(Token::Separator(';'))?; - crate::Statement::Block(Vec::new()) + None } else { return Err(Error::UnknownIdent(ident)); } @@ -1613,7 +1622,7 @@ impl Parser { let mut statements = Vec::new(); while !lexer.skip(Token::Paren('}')) { let s = self.parse_statement(lexer, context.reborrow())?; - statements.push(s); + statements.extend(s); } self.scopes.pop(); Ok(statements) diff --git a/test-data/boids.wgsl b/test-data/boids.wgsl index ec2376887..bdcf36bed 100644 --- a/test-data/boids.wgsl +++ b/test-data/boids.wgsl @@ -23,12 +23,11 @@ import "GLSL.std.450" as std; [[stage(vertex)]] fn main() -> void { - var angle : f32 = -atan2(a_particleVel.x, a_particleVel.y); - var pos : vec2 = vec2( + const angle : f32 = -atan2(a_particleVel.x, a_particleVel.y); + const pos : vec2 = vec2( (a_pos.x * cos(angle)) - (a_pos.y * sin(angle)), (a_pos.x * sin(angle)) + (a_pos.y * cos(angle))); gl_Position = vec4(pos + a_particlePos, 0.0, 1.0); - return; } # fragment shader @@ -37,7 +36,6 @@ fn main() -> void { [[stage(fragment)]] fn main() -> void { fragColor = vec4(1.0, 1.0, 1.0, 1.0); - return; } # compute shader @@ -69,7 +67,7 @@ type Particles = struct { # https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp [[stage(compute), workgroup_size(1)]] fn main() -> void { - var index : u32 = gl_GlobalInvocationID.x; + const index : u32 = gl_GlobalInvocationID.x; if (index >= u32(5)) { return; } @@ -146,6 +144,4 @@ fn main() -> void { # Write back particlesB.particles[index].pos = vPos; particlesB.particles[index].vel = vVel; - - return; } diff --git a/test-data/simple/module.ron b/test-data/simple/module.ron index 76a4b4857..8fa007ef7 100644 --- a/test-data/simple/module.ron +++ b/test-data/simple/module.ron @@ -106,7 +106,6 @@ ), ], body: [ - Block([]), Store( pointer: 2, value: 6, From 82c5cff605d85f2bd78483bc4c69cd6b69b94ae7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 10 Dec 2020 01:19:51 -0500 Subject: [PATCH 0323/2212] [wgsl] refactor type declarations and function calls to avoid backups --- src/front/wgsl/mod.rs | 488 +++++++++++++++++++----------------------- 1 file changed, 223 insertions(+), 265 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2d563c07a..b9738781d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -329,60 +329,156 @@ impl Parser { } } - fn parse_function_call<'a>( + fn parse_function_call_inner<'a>( &mut self, - lexer: &Lexer<'a>, + lexer: &mut Lexer<'a>, + name: &'a str, mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result)>, Error<'a>> { - let mut lexer = lexer.clone(); - - let name = lexer.next_ident()?; - //TODO: avoid code duplication with `parse_singular_expression` - Ok(if let Some(fun) = conv::map_standard_fun(name) { + ) -> Result, Error<'a>> { + Ok(if let Some(fun) = conv::map_relational_fun(name) { + lexer.expect(Token::Paren('('))?; + let argument = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::Relational { fun, argument }) + } else if let Some(axis) = conv::map_derivative_axis(name) { + lexer.expect(Token::Paren('('))?; + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::Derivative { axis, expr }) + } else if let Some((kind, _width)) = conv::get_scalar_type(name) { + lexer.expect(Token::Paren('('))?; + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::As { + expr, + kind, + convert: true, + }) + } else if let Some(fun) = conv::map_standard_fun(name) { lexer.expect(Token::Paren('('))?; let arg_count = fun.argument_count(); - let arg = self.parse_general_expression(&mut lexer, ctx.reborrow())?; + let arg = self.parse_general_expression(lexer, ctx.reborrow())?; let arg1 = if arg_count > 1 { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(&mut lexer, ctx.reborrow())?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; - let arg2 = if arg_count > 1 { + let arg2 = if arg_count > 2 { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(&mut lexer, ctx.reborrow())?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; lexer.expect(Token::Paren(')'))?; - let expr = crate::Expression::Math { + Some(crate::Expression::Math { fun, arg, arg1, arg2, - }; - Some((expr, lexer)) - } else if let Some(&function) = self.function_lookup.get(name) { - if !lexer.skip(Token::Paren('(')) { - return Ok(None); - } - - let mut arguments = Vec::new(); - while !lexer.skip(Token::Paren(')')) { - if !arguments.is_empty() { - lexer.expect(Token::Separator(','))?; - } - let arg = self.parse_general_expression(&mut lexer, ctx.reborrow())?; - arguments.push(arg); - } - - let expr = crate::Expression::Call { - function, - arguments, - }; - Some((expr, lexer)) + }) } else { - None + // texture sampling + match name { + "textureSample" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let sampler_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageSample { + image: ctx.lookup_ident.lookup(image_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name)?, + coordinate, + level: crate::SampleLevel::Auto, + depth_ref: None, + }) + } + "textureSampleLevel" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let sampler_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let level = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageSample { + image: ctx.lookup_ident.lookup(image_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name)?, + coordinate, + level: crate::SampleLevel::Exact(level), + depth_ref: None, + }) + } + "textureSampleBias" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let sampler_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let bias = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageSample { + image: ctx.lookup_ident.lookup(image_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name)?, + coordinate, + level: crate::SampleLevel::Bias(bias), + depth_ref: None, + }) + } + "textureSampleCompare" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let sampler_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let reference = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageSample { + image: ctx.lookup_ident.lookup(image_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name)?, + coordinate, + level: crate::SampleLevel::Zero, + depth_ref: Some(reference), + }) + } + "textureLoad" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + let image = ctx.lookup_ident.lookup(image_name)?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let is_storage = match *ctx.resolve_type(image)? { + crate::TypeInner::Image { + class: crate::ImageClass::Storage(_), + .. + } => true, + _ => false, + }; + let index = if is_storage { + None + } else { + lexer.expect(Token::Separator(','))?; + let index_name = lexer.next_ident()?; + Some(ctx.lookup_ident.lookup(index_name)?) + }; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageLoad { + image, + coordinate, + index, + }) + } + _ => None, + } }) } @@ -444,7 +540,6 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { self.scopes.push(Scope::PrimaryExpr); - let backup = lexer.clone(); let expression = match lexer.next() { Token::Paren('(') => { let expr = self.parse_general_expression(lexer, ctx)?; @@ -500,14 +595,14 @@ impl Parser { self.scopes.pop(); return Ok(*handle); } - if let Some((expr, new_lexer)) = - self.parse_function_call(&backup, ctx.reborrow())? - { - *lexer = new_lexer; + //TODO: resolve the duplicate call in `parse_singular_expression` + if let Some(expr) = self.parse_function_call_inner(lexer, word, ctx.reborrow())? { expr } else { - *lexer = backup; - let ty = self.parse_type_decl(lexer, None, ctx.types, ctx.constants)?; + let inner = + self.parse_type_decl_impl(lexer, None, word, ctx.types, ctx.constants)?; + let ty = ctx.types.fetch_or_append(crate::Type { name: None, inner }); + lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -618,158 +713,7 @@ impl Parser { op: crate::UnaryOperator::Not, expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }), - Token::Word(word) => { - if let Some(fun) = conv::map_relational_fun(word) { - lexer.expect(Token::Paren('('))?; - let argument = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Relational { fun, argument }) - } else if let Some(axis) = conv::map_derivative_axis(word) { - lexer.expect(Token::Paren('('))?; - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Derivative { axis, expr }) - } else if let Some((kind, _width)) = conv::get_scalar_type(word) { - lexer.expect(Token::Paren('('))?; - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::As { - expr, - kind, - convert: true, - }) - } else if let Some(fun) = conv::map_standard_fun(word) { - lexer.expect(Token::Paren('('))?; - let arg_count = fun.argument_count(); - let arg = self.parse_general_expression(lexer, ctx.reborrow())?; - let arg1 = if arg_count > 1 { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - let arg2 = if arg_count > 2 { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Math { - fun, - arg, - arg1, - arg2, - }) - } else { - // texture sampling - match word { - "textureSample" => { - lexer.expect(Token::Paren('('))?; - let image_name = lexer.next_ident()?; - lexer.expect(Token::Separator(','))?; - let sampler_name = lexer.next_ident()?; - lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageSample { - image: ctx.lookup_ident.lookup(image_name)?, - sampler: ctx.lookup_ident.lookup(sampler_name)?, - coordinate, - level: crate::SampleLevel::Auto, - depth_ref: None, - }) - } - "textureSampleLevel" => { - lexer.expect(Token::Paren('('))?; - let image_name = lexer.next_ident()?; - lexer.expect(Token::Separator(','))?; - let sampler_name = lexer.next_ident()?; - lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let level = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageSample { - image: ctx.lookup_ident.lookup(image_name)?, - sampler: ctx.lookup_ident.lookup(sampler_name)?, - coordinate, - level: crate::SampleLevel::Exact(level), - depth_ref: None, - }) - } - "textureSampleBias" => { - lexer.expect(Token::Paren('('))?; - let image_name = lexer.next_ident()?; - lexer.expect(Token::Separator(','))?; - let sampler_name = lexer.next_ident()?; - lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let bias = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageSample { - image: ctx.lookup_ident.lookup(image_name)?, - sampler: ctx.lookup_ident.lookup(sampler_name)?, - coordinate, - level: crate::SampleLevel::Bias(bias), - depth_ref: None, - }) - } - "textureSampleCompare" => { - lexer.expect(Token::Paren('('))?; - let image_name = lexer.next_ident()?; - lexer.expect(Token::Separator(','))?; - let sampler_name = lexer.next_ident()?; - lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let reference = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageSample { - image: ctx.lookup_ident.lookup(image_name)?, - sampler: ctx.lookup_ident.lookup(sampler_name)?, - coordinate, - level: crate::SampleLevel::Zero, - depth_ref: Some(reference), - }) - } - "textureLoad" => { - lexer.expect(Token::Paren('('))?; - let image_name = lexer.next_ident()?; - let image = ctx.lookup_ident.lookup(image_name)?; - lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow())?; - let is_storage = match *ctx.resolve_type(image)? { - crate::TypeInner::Image { - class: crate::ImageClass::Storage(_), - .. - } => true, - _ => false, - }; - let index = if is_storage { - None - } else { - lexer.expect(Token::Separator(','))?; - let index_name = lexer.next_ident()?; - Some(ctx.lookup_ident.lookup(index_name)?) - }; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageLoad { - image, - coordinate, - index, - }) - } - _ => None, - } - } - } + Token::Word(word) => self.parse_function_call_inner(lexer, word, ctx.reborrow())?, _ => None, }; @@ -1038,34 +982,28 @@ impl Parser { } } - fn parse_type_decl<'a>( + fn parse_type_decl_impl<'a>( &mut self, lexer: &mut Lexer<'a>, - self_name: Option<&'a str>, + decoration_lexer: Option>, + word: &'a str, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result, Error<'a>> { - self.scopes.push(Scope::TypeDecl); - let decoration_lexer = if lexer.skip(Token::DoubleParen('[')) { - Some(lexer.take_until(Token::DoubleParen(']'))?) - } else { - None - }; - - let inner = match lexer.next() { - Token::Word("f32") => crate::TypeInner::Scalar { + ) -> Result> { + Ok(match word { + "f32" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: 4, }, - Token::Word("i32") => crate::TypeInner::Scalar { + "i32" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width: 4, }, - Token::Word("u32") => crate::TypeInner::Scalar { + "u32" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width: 4, }, - Token::Word("vec2") => { + "vec2" => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { size: crate::VectorSize::Bi, @@ -1073,7 +1011,7 @@ impl Parser { width, } } - Token::Word("vec3") => { + "vec3" => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { size: crate::VectorSize::Tri, @@ -1081,7 +1019,7 @@ impl Parser { width, } } - Token::Word("vec4") => { + "vec4" => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { size: crate::VectorSize::Quad, @@ -1089,7 +1027,7 @@ impl Parser { width, } } - Token::Word("mat2x2") => { + "mat2x2" => { let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Bi, @@ -1097,7 +1035,7 @@ impl Parser { width, } } - Token::Word("mat2x3") => { + "mat2x3" => { let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Bi, @@ -1105,7 +1043,7 @@ impl Parser { width, } } - Token::Word("mat2x4") => { + "mat2x4" => { let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Bi, @@ -1113,7 +1051,7 @@ impl Parser { width, } } - Token::Word("mat3x2") => { + "mat3x2" => { let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Tri, @@ -1121,7 +1059,7 @@ impl Parser { width, } } - Token::Word("mat3x3") => { + "mat3x3" => { let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Tri, @@ -1129,7 +1067,7 @@ impl Parser { width, } } - Token::Word("mat3x4") => { + "mat3x4" => { let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Tri, @@ -1137,7 +1075,7 @@ impl Parser { width, } } - Token::Word("mat4x2") => { + "mat4x2" => { let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Quad, @@ -1145,7 +1083,7 @@ impl Parser { width, } } - Token::Word("mat4x3") => { + "mat4x3" => { let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Quad, @@ -1153,7 +1091,7 @@ impl Parser { width, } } - Token::Word("mat4x4") => { + "mat4x4" => { let (_, width) = lexer.next_scalar_generic()?; crate::TypeInner::Matrix { columns: crate::VectorSize::Quad, @@ -1161,7 +1099,7 @@ impl Parser { width, } } - Token::Word("ptr") => { + "ptr" => { lexer.expect(Token::Paren('<'))?; let class = conv::map_storage_class(lexer.next_ident()?)?; lexer.expect(Token::Separator(','))?; @@ -1169,7 +1107,7 @@ impl Parser { lexer.expect(Token::Paren('>'))?; crate::TypeInner::Pointer { base, class } } - Token::Word("array") => { + "array" => { lexer.expect(Token::Paren('<'))?; let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let size = match lexer.next() { @@ -1215,13 +1153,13 @@ impl Parser { crate::TypeInner::Array { base, size, stride } } - Token::Word("struct") => { + "struct" => { let members = self.parse_struct_body(lexer, type_arena, const_arena)?; crate::TypeInner::Struct { members } } - Token::Word("sampler") => crate::TypeInner::Sampler { comparison: false }, - Token::Word("sampler_comparison") => crate::TypeInner::Sampler { comparison: true }, - Token::Word("texture_sampled_1d") => { + "sampler" => crate::TypeInner::Sampler { comparison: false }, + "sampler_comparison" => crate::TypeInner::Sampler { comparison: true }, + "texture_sampled_1d" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1229,7 +1167,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - Token::Word("texture_sampled_1d_array") => { + "texture_sampled_1d_array" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1237,7 +1175,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - Token::Word("texture_sampled_2d") => { + "texture_sampled_2d" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1245,7 +1183,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - Token::Word("texture_sampled_2d_array") => { + "texture_sampled_2d_array" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1253,7 +1191,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - Token::Word("texture_sampled_3d") => { + "texture_sampled_3d" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D3, @@ -1261,7 +1199,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - Token::Word("texture_sampled_cube") => { + "texture_sampled_cube" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::Cube, @@ -1269,7 +1207,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - Token::Word("texture_sampled_cube_array") => { + "texture_sampled_cube_array" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::Cube, @@ -1277,7 +1215,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - Token::Word("texture_multisampled_2d") => { + "texture_multisampled_2d" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1285,27 +1223,27 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: true }, } } - Token::Word("texture_depth_2d") => crate::TypeInner::Image { + "texture_depth_2d" => crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Depth, }, - Token::Word("texture_depth_2d_array") => crate::TypeInner::Image { + "texture_depth_2d_array" => crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: true, class: crate::ImageClass::Depth, }, - Token::Word("texture_depth_cube") => crate::TypeInner::Image { + "texture_depth_cube" => crate::TypeInner::Image { dim: crate::ImageDimension::Cube, arrayed: false, class: crate::ImageClass::Depth, }, - Token::Word("texture_depth_cube_array") => crate::TypeInner::Image { + "texture_depth_cube_array" => crate::TypeInner::Image { dim: crate::ImageDimension::Cube, arrayed: true, class: crate::ImageClass::Depth, }, - Token::Word("texture_ro_1d") => { + "texture_ro_1d" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1313,7 +1251,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word("texture_ro_1d_array") => { + "texture_ro_1d_array" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1321,7 +1259,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word("texture_ro_2d") => { + "texture_ro_2d" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1329,7 +1267,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word("texture_ro_2d_array") => { + "texture_ro_2d_array" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1337,7 +1275,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word("texture_ro_3d") => { + "texture_ro_3d" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D3, @@ -1345,7 +1283,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word("texture_wo_1d") => { + "texture_wo_1d" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1353,7 +1291,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word("texture_wo_1d_array") => { + "texture_wo_1d_array" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1361,7 +1299,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word("texture_wo_2d") => { + "texture_wo_2d" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1369,7 +1307,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word("texture_wo_2d_array") => { + "texture_wo_2d_array" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1377,7 +1315,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word("texture_wo_3d") => { + "texture_wo_3d" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D3, @@ -1385,21 +1323,43 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - Token::Word(name) => { - self.scopes.pop(); - return match self.lookup_type.get(name) { - Some(&handle) => Ok(handle), - None => Err(Error::UnknownType(name)), - }; - } - other => return Err(Error::Unexpected(other)), - }; - self.scopes.pop(); + _ => return Err(Error::UnknownType(word)), + }) + } - let handle = type_arena.fetch_or_append(crate::Type { - name: self_name.map(|s| s.to_string()), - inner, - }); + fn parse_type_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + self_name: Option<&'a str>, + type_arena: &mut Arena, + const_arena: &mut Arena, + ) -> Result, Error<'a>> { + self.scopes.push(Scope::TypeDecl); + let decoration_lexer = if lexer.skip(Token::DoubleParen('[')) { + Some(lexer.take_until(Token::DoubleParen(']'))?) + } else { + None + }; + + let name = lexer.next_ident()?; + let handle = match self.lookup_type.get(name) { + Some(&handle) => handle, + None => { + let inner = self.parse_type_decl_impl( + lexer, + decoration_lexer, + name, + type_arena, + const_arena, + )?; + type_arena.fetch_or_append(crate::Type { + name: self_name.map(|s| s.to_string()), + inner, + }) + } + }; + + self.scopes.pop(); Ok(handle) } @@ -1408,7 +1368,6 @@ impl Parser { lexer: &mut Lexer<'a>, mut context: StatementContext<'a, '_, '_>, ) -> Result, Error<'a>> { - let backup = lexer.clone(); let word = match lexer.next() { Token::Separator(';') => return Ok(None), Token::Word(word) => word, @@ -1596,10 +1555,9 @@ impl Parser { pointer: left, value, }) - } else if let Some((expr, new_lexer)) = - self.parse_function_call(&backup, context.as_expression())? + } else if let Some(expr) = + self.parse_function_call_inner(lexer, ident, context.as_expression())? { - *lexer = new_lexer; context.expressions.append(expr); lexer.expect(Token::Separator(';'))?; None From b7744a1ec567ea3922ca362fdcdb68abbac2a5d1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 10 Dec 2020 09:43:42 -0500 Subject: [PATCH 0324/2212] [wgsl] function lookup, improve error reporting --- src/front/wgsl/lexer.rs | 11 +++--- src/front/wgsl/mod.rs | 82 +++++++++++++++++++++-------------------- test-data/function.wgsl | 4 +- tests/snapshots.rs | 1 + 4 files changed, 50 insertions(+), 48 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index a9e45da7a..d5811604b 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -163,8 +163,7 @@ impl<'a> Lexer<'a> { if token == expected { Ok(()) } else { - log::trace!("expect {:?}, got {:?}", expected, token); - Err(Error::Unexpected(token)) + token.unexpected(expected) } } @@ -181,28 +180,28 @@ impl<'a> Lexer<'a> { pub(super) fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { match self.next() { Token::Word(word) => Ok(word), - other => Err(Error::Unexpected(other)), + other => other.unexpected("ident"), } } fn _next_float_literal(&mut self) -> Result> { match self.next() { Token::Number(word) => word.parse().map_err(|err| Error::BadFloat(word, err)), - other => Err(Error::Unexpected(other)), + other => other.unexpected("float literal"), } } pub(super) fn next_uint_literal(&mut self) -> Result> { match self.next() { Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), - other => Err(Error::Unexpected(other)), + other => other.unexpected("uint literal"), } } pub(super) fn next_sint_literal(&mut self) -> Result> { match self.next() { Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), - other => Err(Error::Unexpected(other)), + other => other.unexpected("sint literal"), } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b9738781d..365955d2f 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -34,6 +34,13 @@ pub enum Token<'a> { End, } +impl<'a> Token<'a> { + fn unexpected(self, expected: E) -> Result> { + log::error!("Unmet expectation for {:?}", expected); + Err(Error::Unexpected(self)) + } +} + #[derive(Clone, Debug, Error)] pub enum Error<'a> { #[error("unexpected token: {0:?}")] @@ -278,8 +285,7 @@ pub struct ParseError<'a> { pub struct Parser { scopes: Vec, lookup_type: FastHashMap>, - function_lookup: FastHashMap>, - std_namespace: Option>, + lookup_function: FastHashMap>, } impl Parser { @@ -287,8 +293,7 @@ impl Parser { Parser { scopes: Vec::new(), lookup_type: FastHashMap::default(), - function_lookup: FastHashMap::default(), - std_namespace: None, + lookup_function: FastHashMap::default(), } } @@ -477,7 +482,28 @@ impl Parser { index, }) } - _ => None, + _ => match self.lookup_function.get(name) { + Some(&function) => { + let mut arguments = Vec::new(); + lexer.expect(Token::Paren('('))?; + if !lexer.skip(Token::Paren(')')) { + loop { + let arg = self.parse_general_expression(lexer, ctx.reborrow())?; + arguments.push(arg); + match lexer.next() { + Token::Paren(')') => break, + Token::Separator(',') => (), + other => return other.unexpected("argument list separator"), + } + } + } + Some(crate::Expression::Call { + function, + arguments, + }) + } + None => None, + }, } }) } @@ -615,7 +641,7 @@ impl Parser { crate::Expression::Compose { ty, components } } } - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("primary expression"), }; self.scopes.pop(); Ok(ctx.expressions.append(expression)) @@ -958,7 +984,7 @@ impl Parser { lexer.expect(Token::Paren(')'))?; ready = false; } - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("decoration separator"), } } self.scopes.pop(); @@ -966,7 +992,7 @@ impl Parser { let name = match lexer.next() { Token::Word(word) => word, Token::Paren('}') => return Ok(members), - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("field name"), }; if offset == !0 { return Err(Error::MissingMemberOffset(name)); @@ -1129,7 +1155,7 @@ impl Parser { crate::ArraySize::Constant(const_handle) } Token::Paren('>') => crate::ArraySize::Dynamic, - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("generic separator"), }; let mut stride = None; @@ -1145,7 +1171,7 @@ impl Parser { ); } Token::End => break, - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("stride decoration"), } } self.scopes.pop(); @@ -1371,7 +1397,7 @@ impl Parser { let word = match lexer.next() { Token::Separator(';') => return Ok(None), Token::Word(word) => word, - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("statement"), }; self.scopes.push(Scope::Statement); @@ -1480,7 +1506,7 @@ impl Parser { }); } Token::Separator(':') => break value, - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("case separator"), } }; @@ -1511,7 +1537,7 @@ impl Parser { default = self.parse_block(lexer, context.reborrow())?; } Token::Paren('}') => break, - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("switch item"), } } @@ -1718,7 +1744,7 @@ impl Parser { match lexer.next() { Token::Paren(')') => break, Token::Separator(',') if i != 2 => (), - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("workgroup size separator"), } } for size in workgroup_size.iter_mut() { @@ -1734,7 +1760,7 @@ impl Parser { break; } Token::Separator(',') => {} - other => return Err(Error::Unexpected(other)), + other => return other.unexpected("decoration separator"), } } if let (Some(group), Some(index)) = (bind_group, bind_index) { @@ -1748,27 +1774,6 @@ impl Parser { // read items match lexer.next() { Token::Separator(';') => {} - Token::Word("import") => { - self.scopes.push(Scope::ImportDecl); - let path = match lexer.next() { - Token::String(path) => path, - other => return Err(Error::Unexpected(other)), - }; - lexer.expect(Token::Word("as"))?; - let mut namespaces = Vec::new(); - loop { - namespaces.push(lexer.next_ident()?.to_owned()); - if lexer.skip(Token::Separator(';')) { - break; - } - lexer.expect(Token::DoubleColon)?; - } - match path { - "GLSL.std.450" => self.std_namespace = Some(namespaces), - _ => return Err(Error::UnknownImport(path)), - } - self.scopes.pop(); - } Token::Word("type") => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; @@ -1840,7 +1845,7 @@ impl Parser { .is_some(), None => { let fun_handle = module.functions.append(function); - self.function_lookup + self.lookup_function .insert(name.to_string(), fun_handle) .is_some() } @@ -1850,7 +1855,7 @@ impl Parser { } } Token::End => return Ok(false), - token => return Err(Error::Unexpected(token)), + other => return other.unexpected("global item"), } match binding { None => Ok(true), @@ -1862,7 +1867,6 @@ impl Parser { pub fn parse<'a>(&mut self, source: &'a str) -> Result> { self.scopes.clear(); self.lookup_type.clear(); - self.std_namespace = None; let mut module = crate::Module::generate_empty(); let mut lexer = Lexer::new(source); diff --git a/test-data/function.wgsl b/test-data/function.wgsl index 5a968cadd..6e92dd5f4 100644 --- a/test-data/function.wgsl +++ b/test-data/function.wgsl @@ -1,11 +1,9 @@ -import "GLSL.std.450" as std::glsl; - fn test_function(test: f32) -> f32 { return test; } [[stage(vertex)]] fn main() -> void { - var foo: f32 = std::glsl::distance(0.0, 1.0); + var foo: f32 = distance(0.0, 1.0); var test: f32 = test_function(1.0); } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 453a078b3..630e48cfa 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -29,6 +29,7 @@ struct BindTarget { #[derive(Default, Deserialize)] struct Parameters { #[serde(default)] + #[allow(dead_code)] spv_flow_dump_prefix: String, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_capabilities: naga::FastHashSet, From 6a6e3c28f9367dd405c04f84b425b901fce255ff Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Thu, 10 Dec 2020 23:21:41 +0100 Subject: [PATCH 0325/2212] Update simple.wgsl to latest syntax --- test-data/simple.param.ron | 4 ++++ test-data/simple.wgsl | 11 ++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 test-data/simple.param.ron diff --git a/test-data/simple.param.ron b/test-data/simple.param.ron new file mode 100644 index 000000000..55250e1e7 --- /dev/null +++ b/test-data/simple.param.ron @@ -0,0 +1,4 @@ +( + spv_capabilities: [ Shader ], + mtl_bindings: { } +) diff --git a/test-data/simple.wgsl b/test-data/simple.wgsl index 35afac087..21bb517e3 100644 --- a/test-data/simple.wgsl +++ b/test-data/simple.wgsl @@ -1,8 +1,13 @@ # vertex -[[builtin position]] var o_position : vec4; +[[builtin(position)]] var o_position : vec4; +[[stage(vertex)]] fn main() -> void { - o_position = vec4(1); + o_position = vec4(1.0, 1.0, 1.0, 1.0); + + if (1 == 1) { + var a: f32 = 1.0; + } + return; } -entry_point vertex as "main" = main; From d18b73c3a71f9cc0d3bdf97a96eb86df278e44d6 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Thu, 10 Dec 2020 19:44:40 -0330 Subject: [PATCH 0326/2212] Remove duplicate wgsl from test-data --- test-data/function.wgsl | 9 --------- test-data/quad.param.ron | 7 ------- test-data/quad.wgsl | 25 ------------------------- test-data/simple.param.ron | 4 ---- test-data/simple.wgsl | 13 ------------- 5 files changed, 58 deletions(-) delete mode 100644 test-data/function.wgsl delete mode 100644 test-data/quad.param.ron delete mode 100644 test-data/quad.wgsl delete mode 100644 test-data/simple.param.ron delete mode 100644 test-data/simple.wgsl diff --git a/test-data/function.wgsl b/test-data/function.wgsl deleted file mode 100644 index 6e92dd5f4..000000000 --- a/test-data/function.wgsl +++ /dev/null @@ -1,9 +0,0 @@ -fn test_function(test: f32) -> f32 { - return test; -} - -[[stage(vertex)]] -fn main() -> void { - var foo: f32 = distance(0.0, 1.0); - var test: f32 = test_function(1.0); -} diff --git a/test-data/quad.param.ron b/test-data/quad.param.ron deleted file mode 100644 index 25747c169..000000000 --- a/test-data/quad.param.ron +++ /dev/null @@ -1,7 +0,0 @@ -( - spv_capabilities: [ Shader ], - mtl_bindings: { - (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), - (stage: Fragment, group: 0, binding: 1): (sampler: Some(0)), - } -) diff --git a/test-data/quad.wgsl b/test-data/quad.wgsl deleted file mode 100644 index 16cbd2698..000000000 --- a/test-data/quad.wgsl +++ /dev/null @@ -1,25 +0,0 @@ -# vertex -const c_scale: f32 = 1.2; -[[location(0)]] var a_pos : vec2; -[[location(1)]] var a_uv : vec2; -[[location(0)]] var v_uv : vec2; -[[builtin(position)]] var o_position : vec4; - -[[stage(vertex)]] -fn main() -> void { - v_uv = a_uv; - o_position = vec4(c_scale * a_pos, 0.0, 1.0); - return; -} - -# fragment -[[location(0)]] var v_uv : vec2; -[[group(0), binding(0)]] var u_texture : texture_sampled_2d; -[[group(0), binding(1)]] var u_sampler : sampler; -[[location(0)]] var o_color : vec4; - -[[stage(fragment)]] -fn main() -> void { - o_color = textureSample(u_texture, u_sampler, v_uv); - return; -} diff --git a/test-data/simple.param.ron b/test-data/simple.param.ron deleted file mode 100644 index 55250e1e7..000000000 --- a/test-data/simple.param.ron +++ /dev/null @@ -1,4 +0,0 @@ -( - spv_capabilities: [ Shader ], - mtl_bindings: { } -) diff --git a/test-data/simple.wgsl b/test-data/simple.wgsl deleted file mode 100644 index 21bb517e3..000000000 --- a/test-data/simple.wgsl +++ /dev/null @@ -1,13 +0,0 @@ -# vertex -[[builtin(position)]] var o_position : vec4; - -[[stage(vertex)]] -fn main() -> void { - o_position = vec4(1.0, 1.0, 1.0, 1.0); - - if (1 == 1) { - var a: f32 = 1.0; - } - - return; -} From dafca34877a9e558c507014905fafe6c7d3bf0d1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 00:50:36 -0500 Subject: [PATCH 0327/2212] Add block boolean to the structure types in IR Also update WGSL syntax for structures. Move the boids code into snapshots. --- src/back/glsl/mod.rs | 39 +++--- src/back/msl/writer.rs | 15 ++- src/back/spv/writer.rs | 28 +++- src/front/glsl/parser.rs | 17 ++- src/front/glsl/variables.rs | 5 +- src/front/spv/mod.rs | 17 ++- src/front/wgsl/mod.rs | 28 +++- src/lib.rs | 5 +- src/proc/namer.rs | 6 +- src/proc/typifier.rs | 5 +- src/proc/validator.rs | 12 +- tests/snapshots.rs | 4 +- .../snapshots/in}/boids.param.ron | 0 {test-data => tests/snapshots/in}/boids.wgsl | 17 +-- tests/snapshots/in/function.param.ron | 5 - tests/snapshots/in/function.wgsl | 8 -- tests/snapshots/in/quad.wgsl | 6 +- tests/snapshots/in/simple.wgsl | 3 +- tests/snapshots/snapshots__boids.msl.snap | 127 ++++++++++++++++++ tests/snapshots/snapshots__function.msl.snap | 27 ---- .../snapshots/snapshots__function.spvasm.snap | 31 ----- 21 files changed, 264 insertions(+), 141 deletions(-) rename {test-data => tests/snapshots/in}/boids.param.ron (100%) rename {test-data => tests/snapshots/in}/boids.wgsl (95%) delete mode 100644 tests/snapshots/in/function.param.ron delete mode 100644 tests/snapshots/in/function.wgsl create mode 100644 tests/snapshots/snapshots__boids.msl.snap delete mode 100644 tests/snapshots/snapshots__function.msl.snap delete mode 100644 tests/snapshots/snapshots__function.spvasm.snap diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 419452e1c..7c302b567 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -385,7 +385,11 @@ impl<'a, W: Write> Writer<'a, W> { // This are always ordered because of the IR is structured in a way that you can't make a // struct without adding all of it's members first for (handle, ty) in self.module.types.iter() { - if let TypeInner::Struct { ref members } = ty.inner { + if let TypeInner::Struct { + block: _, + ref members, + } = ty.inner + { self.write_struct(handle, members)? } } @@ -513,7 +517,7 @@ impl<'a, W: Write> Writer<'a, W> { /// - If type is either a image or sampler /// - If it's an Array with a [`ArraySize::Constant`](crate::ArraySize::Constant) with a /// constant that isn't [`Uint`](crate::ConstantInner::Uint) - fn write_type(&mut self, ty: Handle, block: bool) -> BackendResult { + fn write_type(&mut self, ty: Handle) -> BackendResult { match self.module.types[ty].inner { // Scalars are simple we just get the full name from `glsl_scalar` TypeInner::Scalar { kind, width } => { @@ -543,10 +547,10 @@ impl<'a, W: Write> Writer<'a, W> { rows as u8 )?, // glsl has no pointer types so just write types as normal and loads are skipped - TypeInner::Pointer { base, .. } => self.write_type(base, false)?, + TypeInner::Pointer { base, .. } => self.write_type(base)?, // Arrays are written as `base[size]` TypeInner::Array { base, size, .. } => { - self.write_type(base, false)?; + self.write_type(base)?; write!(self.out, "[")?; @@ -570,7 +574,7 @@ impl<'a, W: Write> Writer<'a, W> { // If it's a block we need to write `block_name { members }` where `block_name` must be // unique between blocks and structs so we add `_block_ID` where `ID` is a `IdGenerator` // generated number so it's unique and `members` are the same as in a struct - TypeInner::Struct { ref members } => { + TypeInner::Struct { block, ref members } => { // Get the struct name let name = &self.names[&NameKey::Type(ty)]; @@ -583,7 +587,7 @@ impl<'a, W: Write> Writer<'a, W> { // Add a tab for identation (readability only) writeln!(self.out, "\t")?; // Write the member type - self.write_type(member.ty, false)?; + self.write_type(member.ty)?; // Finish the member with the name, a semicolon and a newline // The leading space is important @@ -694,20 +698,13 @@ impl<'a, W: Write> Writer<'a, W> { }; } - // glsl doesn't allow structures as types in `buffer` and `uniform` instead blocks must be - // used so we set block to true in `write_type` - let block = match global.class { - StorageClass::Storage | StorageClass::Uniform => true, - _ => false, - }; - // Write the storage class // Trailing space is important write!(self.out, "{} ", glsl_storage_class(global.class))?; // Write the type // `write_type` adds no leading or trailing spaces - self.write_type(global.ty, block)?; + self.write_type(global.ty)?; // Finally write the global name and end the global with a `;` and a newline // Leading space is important @@ -762,7 +759,7 @@ impl<'a, W: Write> Writer<'a, W> { // This is the only place where `void` is a valid type // (though it's more a keyword than a type) if let Some(ty) = func.return_type { - self.write_type(ty, false)?; + self.write_type(ty)?; } else { write!(self.out, "void")?; } @@ -777,7 +774,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_slice(&func.arguments, |this, i, arg| { // Write the argument type // `write_type` adds no trailing spaces - this.write_type(arg.ty, false)?; + this.write_type(arg.ty)?; // Write the argument name // The leading space is important @@ -797,7 +794,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write identation (only for readability) and the type // `write_type` adds no trailing space write!(self.out, "\t")?; - self.write_type(local.ty, false)?; + self.write_type(local.ty)?; // Write the local name // The leading space is important @@ -883,7 +880,7 @@ impl<'a, W: Write> Writer<'a, W> { // Composite constant are created using the same syntax as compose // `type(components)` where `components` is a comma separated list of constants ConstantInner::Composite(ref components) => { - self.write_type(constant.ty, false)?; + self.write_type(constant.ty)?; write!(self.out, "(")?; // Write the comma separated constants @@ -919,7 +916,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the member type // Adds no trailing space - self.write_type(member.ty, false)?; + self.write_type(member.ty)?; // Write the member name and put a semicolon // The leading space is important @@ -1139,7 +1136,7 @@ impl<'a, W: Write> Writer<'a, W> { // `Compose` is pretty simple we just write `type(components)` where `components` is a // comma separated list of expressions Expression::Compose { ty, ref components } => { - self.write_type(ty, false)?; + self.write_type(ty)?; write!(self.out, "(")?; self.write_slice(components, |this, _, arg| this.write_expr(*arg, ctx))?; @@ -1492,7 +1489,7 @@ impl<'a, W: Write> Writer<'a, W> { convert, } => { if convert { - self.write_type(ctx.typifier.get_handle(expr).unwrap(), false)?; + self.write_type(ctx.typifier.get_handle(expr).unwrap())?; } else { let source_kind = match *ctx.typifier.get(expr, &self.module.types) { TypeInner::Scalar { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 710948d62..e151e9f69 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -694,7 +694,10 @@ impl Writer { crate::ArraySize::Dynamic => write!(self.out, "1]")?, } } - crate::TypeInner::Struct { ref members } => { + crate::TypeInner::Struct { + block: _, + ref members, + } => { writeln!(self.out, "struct {} {{", name)?; for (index, member) in members.iter().enumerate() { let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; @@ -893,7 +896,10 @@ impl Writer { continue; } // if it's a struct, lift all the built-in contents up to the root - if let crate::TypeInner::Struct { ref members } = module.types[var.ty].inner + if let crate::TypeInner::Struct { + block: _, + ref members, + } = module.types[var.ty].inner { for (index, member) in members.iter().enumerate() { if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { @@ -932,7 +938,10 @@ impl Writer { continue; } // if it's a struct, lift all the built-in contents up to the root - if let crate::TypeInner::Struct { ref members } = module.types[var.ty].inner + if let crate::TypeInner::Struct { + block: _, + ref members, + } = module.types[var.ty].inner { for (index, member) in members.iter().enumerate() { let name = diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index db06ba320..7650dac67 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -142,6 +142,7 @@ pub struct Writer { lookup_function_type: crate::FastHashMap, lookup_constant: crate::FastHashMap, Word>, lookup_global_variable: crate::FastHashMap, Word>, + storage_type_handles: crate::FastHashSet>, } // type alias, for success return of write_expression @@ -167,6 +168,7 @@ impl Writer { lookup_function_type: crate::FastHashMap::default(), lookup_constant: crate::FastHashMap::default(), lookup_global_variable: crate::FastHashMap::default(), + storage_type_handles: crate::FastHashSet::default(), } } @@ -588,7 +590,20 @@ impl Writer { } } } - crate::TypeInner::Struct { ref members } => { + crate::TypeInner::Struct { block, ref members } => { + if block { + let decoration = if self.storage_type_handles.contains(&handle) { + spirv::Decoration::BufferBlock + } else { + spirv::Decoration::Block + }; + self.annotations + .push(super::instructions::instruction_decorate( + id, + decoration, + &[], + )); + } let mut member_ids = Vec::with_capacity(members.len()); for member in members { let member_id = self.get_type_id(arena, LookupType::Handle(member.ty))?; @@ -956,7 +971,10 @@ impl Writer { LookupType::Local(LocalType::Scalar { kind, width }), ) } - crate::TypeInner::Struct { ref members } => { + crate::TypeInner::Struct { + block: _, + ref members, + } => { let member = &members[index as usize]; let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(member.ty))?; @@ -1625,6 +1643,12 @@ impl Writer { )); } + for (_, var) in ir_module.global_variables.iter() { + if !var.storage_access.is_empty() { + self.storage_type_handles.insert(var.ty); + } + } + for (handle, ir_function) in ir_module.functions.iter() { let id = self.write_function(ir_function, ir_module)?; self.lookup_function.insert(handle, id); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2d03b3a44..437272191 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -541,14 +541,16 @@ pomelo! { if i.1 == "gl_PerVertex" { None } else { + let block = !t.is_empty(); Some(VarDeclaration { type_qualifiers: t, ids_initializers: vec![(None, None)], ty: extra.module.types.fetch_or_append(Type{ name: Some(i.1), inner: TypeInner::Struct { - members: sdl - } + block, + members: sdl, + }, }), }) } @@ -556,14 +558,16 @@ pomelo! { declaration ::= type_qualifier(t) Identifier(i1) LeftBrace struct_declaration_list(sdl) RightBrace Identifier(i2) Semicolon { + let block = !t.is_empty(); Some(VarDeclaration { type_qualifiers: t, ids_initializers: vec![(Some(i2.1), None)], ty: extra.module.types.fetch_or_append(Type{ name: Some(i1.1), inner: TypeInner::Struct { - members: sdl - } + block, + members: sdl, + }, }), }) } @@ -720,7 +724,8 @@ pomelo! { Type{ name: Some(i.1), inner: TypeInner::Struct { - members: vec![] + block: false, + members: vec![], } } } @@ -1013,7 +1018,7 @@ pomelo! { } else { let ty = &extra.module.types[var.ty]; // anonymous structs - if let TypeInner::Struct { members } = &ty.inner { + if let TypeInner::Struct { block: _, ref members } = ty.inner { let base = extra.context.expressions.append( Expression::GlobalVariable(var_handle) ); diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 50343ba92..7fb1a3518 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -142,7 +142,10 @@ impl Program { meta: TokenMetadata, ) -> Result, ErrorKind> { match *self.resolve_type(expression)? { - TypeInner::Struct { ref members } => { + TypeInner::Struct { + block: _, + ref members, + } => { let index = members .iter() .position(|m| m.name == Some(name.into())) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 782c62a6f..0f16da030 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -142,7 +142,7 @@ fn check_sample_coordinates( type MemberIndex = u32; -#[derive(Debug, Default)] +#[derive(Clone, Debug, Default, PartialEq)] struct Block { buffer: bool, } @@ -2014,12 +2014,6 @@ impl> Parser { inst.expect_at_least(2)?; let id = self.next()?; let parent_decor = self.future_decor.remove(&id); - let is_buffer_block = parent_decor - .as_ref() - .map_or(false, |decor| match decor.block { - Some(Block { buffer }) => buffer, - _ => false, - }); let mut members = Vec::with_capacity(inst.wc as usize - 2); let mut member_type_ids = Vec::with_capacity(members.capacity()); @@ -2038,13 +2032,18 @@ impl> Parser { ty, }); } - let inner = crate::TypeInner::Struct { members }; + + let block_decor = parent_decor.as_ref().and_then(|decor| decor.block.clone()); + let inner = crate::TypeInner::Struct { + block: block_decor.is_some(), + members, + }; let ty_handle = module.types.append(crate::Type { name: parent_decor.and_then(|dec| dec.name), inner, }); - if is_buffer_block { + if block_decor == Some(Block { buffer: true }) { self.lookup_storage_buffer_types.insert(ty_handle); } for (i, type_id) in member_type_ids.into_iter().enumerate() { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 365955d2f..edc949c00 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -315,7 +315,7 @@ impl Parser { Ok(type_arena.fetch_or_append(crate::Type { name: None, inner })) } crate::TypeInner::Array { base, .. } => Ok(base), - crate::TypeInner::Struct { ref members } => Ok(members[index].ty), + crate::TypeInner::Struct { ref members, .. } => Ok(members[index].ty), _ => Err(Error::NotCompositeType(ty)), } } @@ -659,7 +659,7 @@ impl Parser { let _ = lexer.next(); let name = lexer.next_ident()?; let expression = match *ctx.resolve_type(handle)? { - crate::TypeInner::Struct { ref members } => { + crate::TypeInner::Struct { ref members, .. } => { let index = members .iter() .position(|m| m.name.as_deref() == Some(name)) @@ -1179,10 +1179,6 @@ impl Parser { crate::TypeInner::Array { base, size, stride } } - "struct" => { - let members = self.parse_struct_body(lexer, type_arena, const_arena)?; - crate::TypeInner::Struct { members } - } "sampler" => crate::TypeInner::Sampler { comparison: false }, "sampler_comparison" => crate::TypeInner::Sampler { comparison: true }, "texture_sampled_1d" => { @@ -1698,6 +1694,7 @@ impl Parser { // Perspective is the default qualifier. let mut interpolation = None; let mut stage = None; + let mut is_block = false; let mut workgroup_size = [0u32; 3]; if lexer.skip(Token::DoubleParen('[')) { @@ -1722,6 +1719,9 @@ impl Parser { bind_index = Some(lexer.next_uint_literal()?); lexer.expect(Token::Paren(')'))?; } + "block" => { + is_block = true; + } "group" => { lexer.expect(Token::Paren('('))?; bind_group = Some(lexer.next_uint_literal()?); @@ -1771,9 +1771,24 @@ impl Parser { } self.scopes.pop(); } + // read items match lexer.next() { Token::Separator(';') => {} + Token::Word("struct") => { + let name = lexer.next_ident()?; + let members = + self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?; + let ty = module.types.fetch_or_append(crate::Type { + name: Some(name.to_string()), + inner: crate::TypeInner::Struct { + block: is_block, + members, + }, + }); + self.lookup_type.insert(name.to_owned(), ty); + lexer.expect(Token::Separator(';'))?; + } Token::Word("type") => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; @@ -1857,6 +1872,7 @@ impl Parser { Token::End => return Ok(false), other => return other.unexpected("global item"), } + match binding { None => Ok(true), // we had the decoration but no var? diff --git a/src/lib.rs b/src/lib.rs index dff0233ac..6cc3bd4db 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -386,7 +386,10 @@ pub enum TypeInner { stride: Option, }, /// User-defined structure. - Struct { members: Vec }, + Struct { + block: bool, + members: Vec, + }, /// Possibly multidimensional array of texels. Image { dim: ImageDimension, diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 03b508904..4e6ddf997 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -80,7 +80,11 @@ impl Namer { let ty_name = this.call_or(&ty.name, "type"); output.insert(NameKey::Type(ty_handle), ty_name); - if let crate::TypeInner::Struct { ref members } = ty.inner { + if let crate::TypeInner::Struct { + block: _, + ref members, + } = ty.inner + { for (index, member) in members.iter().enumerate() { let name = this.call_or(&member.name, "member"); output.insert(NameKey::StructMember(ty_handle, index as u32), name); diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 8fe370163..07eb1274f 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -153,7 +153,10 @@ impl Typifier { }) } crate::TypeInner::Array { base, .. } => Resolution::Handle(base), - crate::TypeInner::Struct { ref members } => { + crate::TypeInner::Struct { + block: _, + ref members, + } => { let member = members .get(index as usize) .ok_or(ResolveError::InvalidAccessIndex)?; diff --git a/src/proc/validator.rs b/src/proc/validator.rs index f39a5bf85..fdb7fd0d8 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -186,7 +186,10 @@ impl crate::GlobalVariable { None => { match types[self.ty].inner { //TODO: check the member types - crate::TypeInner::Struct { members: _ } => self.forbid_interpolation()?, + crate::TypeInner::Struct { + block: _, + members: _, + } => self.forbid_interpolation()?, _ => return Err(GlobalVariableError::InvalidType), } } @@ -492,8 +495,11 @@ impl Validator { } } } - Ti::Struct { ref members } => { - //TODO: check that offsets are not intersecting? + Ti::Struct { + block: _, + ref members, + } => { + //TODO: check the offsets for member in members { if member.ty >= handle { return Err(ValidationError::UnresolvedType(member.ty)); diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 630e48cfa..32072f680 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -120,6 +120,6 @@ fn converts_wgsl_simple() { #[cfg(feature = "wgsl-in")] #[test] -fn converts_wgsl_function() { - convert_wgsl("function"); +fn converts_wgsl_boids() { + convert_wgsl("boids"); } diff --git a/test-data/boids.param.ron b/tests/snapshots/in/boids.param.ron similarity index 100% rename from test-data/boids.param.ron rename to tests/snapshots/in/boids.param.ron diff --git a/test-data/boids.wgsl b/tests/snapshots/in/boids.wgsl similarity index 95% rename from test-data/boids.wgsl rename to tests/snapshots/in/boids.wgsl index bdcf36bed..8c5ff2fd1 100644 --- a/test-data/boids.wgsl +++ b/tests/snapshots/in/boids.wgsl @@ -12,8 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import "GLSL.std.450" as std; - # vertex shader [[location(0)]] var a_particlePos : vec2; @@ -22,7 +20,7 @@ import "GLSL.std.450" as std; [[builtin(position)]] var gl_Position : vec4; [[stage(vertex)]] -fn main() -> void { +fn main() { const angle : f32 = -atan2(a_particleVel.x, a_particleVel.y); const pos : vec2 = vec2( (a_pos.x * cos(angle)) - (a_pos.y * sin(angle)), @@ -34,17 +32,19 @@ fn main() -> void { [[location(0)]] var fragColor : vec4; [[stage(fragment)]] -fn main() -> void { +fn main() { fragColor = vec4(1.0, 1.0, 1.0, 1.0); } # compute shader -type Particle = struct { +[[block]] +struct Particle { [[offset(0)]] pos : vec2; [[offset(8)]] vel : vec2; }; -type SimParams = struct { +[[block]] +struct SimParams { [[offset(0)]] deltaT : f32; [[offset(4)]] rule1Distance : f32; [[offset(8)]] rule2Distance : f32; @@ -54,7 +54,8 @@ type SimParams = struct { [[offset(24)]] rule3Scale : f32; }; -type Particles = struct { +[[block]] +struct Particles { [[offset(0)]] particles : [[stride 16]] array; }; @@ -66,7 +67,7 @@ type Particles = struct { # https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp [[stage(compute), workgroup_size(1)]] -fn main() -> void { +fn main() { const index : u32 = gl_GlobalInvocationID.x; if (index >= u32(5)) { return; diff --git a/tests/snapshots/in/function.param.ron b/tests/snapshots/in/function.param.ron deleted file mode 100644 index 4adad3622..000000000 --- a/tests/snapshots/in/function.param.ron +++ /dev/null @@ -1,5 +0,0 @@ -( - spv_capabilities: [ Shader ], - mtl_bindings: { - } -) diff --git a/tests/snapshots/in/function.wgsl b/tests/snapshots/in/function.wgsl deleted file mode 100644 index 12549c7f9..000000000 --- a/tests/snapshots/in/function.wgsl +++ /dev/null @@ -1,8 +0,0 @@ -fn test_function(test: f32) -> f32 { - return test; -} - -[[stage(vertex)]] -fn main() -> void { - var test: f32 = test_function(1.0); -} diff --git a/tests/snapshots/in/quad.wgsl b/tests/snapshots/in/quad.wgsl index 16cbd2698..50b367cf9 100644 --- a/tests/snapshots/in/quad.wgsl +++ b/tests/snapshots/in/quad.wgsl @@ -6,10 +6,9 @@ const c_scale: f32 = 1.2; [[builtin(position)]] var o_position : vec4; [[stage(vertex)]] -fn main() -> void { +fn main() { v_uv = a_uv; o_position = vec4(c_scale * a_pos, 0.0, 1.0); - return; } # fragment @@ -19,7 +18,6 @@ fn main() -> void { [[location(0)]] var o_color : vec4; [[stage(fragment)]] -fn main() -> void { +fn main() { o_color = textureSample(u_texture, u_sampler, v_uv); - return; } diff --git a/tests/snapshots/in/simple.wgsl b/tests/snapshots/in/simple.wgsl index bbe591d8f..ec4356412 100644 --- a/tests/snapshots/in/simple.wgsl +++ b/tests/snapshots/in/simple.wgsl @@ -2,7 +2,6 @@ [[builtin(position)]] var o_position : vec4; [[stage(vertex)]] -fn main() -> void { +fn main() { o_position = vec4(1); - return; } diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap new file mode 100644 index 000000000..2e3efb40c --- /dev/null +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -0,0 +1,127 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +typedef float2 type; +typedef float4 type1; +typedef float type2; +struct Particle { + type pos; + type vel; +}; +struct SimParams { + type2 deltaT; + type2 rule1Distance; + type2 rule2Distance; + type2 rule3Distance; + type2 rule1Scale; + type2 rule2Scale; + type2 rule3Scale; +}; +typedef uint type3; +typedef Particle type4[5]; +struct Particles { + type4 particles; +}; +typedef uint3 type5; +typedef int type6; + +struct main1Input { + type a_particlePos [[attribute(0)]]; + type a_particleVel [[attribute(1)]]; + type a_pos [[attribute(2)]]; +}; +struct main1Output { + type1 gl_Position [[position]]; +}; +vertex main1Output main1( + main1Input input [[stage_in]] +) { + main1Output output; + output.gl_Position = float4(float2(input.a_pos.x * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) - input.a_pos.y * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)), input.a_pos.x * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) + input.a_pos.y * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y))) + input.a_particlePos, 0.0, 1.0); + return output; +} +struct main2Input { +}; +struct main2Output { + type1 fragColor [[color(0)]]; +}; +fragment main2Output main2( + main2Input input [[stage_in]] +) { + main2Output output; + output.fragColor = float4(1.0, 1.0, 1.0, 1.0); + return output; +} +kernel void main3( + constant SimParams& params [[buffer(0)]], + constant Particles& particlesA [[buffer(1)]], + device Particles& particlesB [[buffer(2)]], + type5 gl_GlobalInvocationID [[thread_position_in_grid]] +) { + type vPos; + type vVel; + type cMass; + type cVel; + type colVel; + type6 cMassCount = 0; + type6 cVelCount = 0; + type pos1; + type vel1; + type3 i = 0; + if (gl_GlobalInvocationID.x >= static_cast(5)) { + } + vPos = particlesA.particles[gl_GlobalInvocationID.x].pos; + vVel = particlesA.particles[gl_GlobalInvocationID.x].vel; + cMass = float2(0.0, 0.0); + cVel = float2(0.0, 0.0); + colVel = float2(0.0, 0.0); + while(true) { + if (i >= static_cast(5)) { + break; + } + if (i == gl_GlobalInvocationID.x) { + continue; + } + pos1 = float2(particlesA.particles[i].pos.x, particlesA.particles[i].pos.y); + vel1 = float2(particlesA.particles[i].vel.x, particlesA.particles[i].vel.y); + if (metal::distance(pos1, vPos) < params.rule1Distance) { + cMass = cMass + pos1; + cMassCount = cMassCount + 1; + } + if (metal::distance(pos1, vPos) < params.rule2Distance) { + colVel = colVel - pos1 - vPos; + } + if (metal::distance(pos1, vPos) < params.rule3Distance) { + cVel = cVel + vel1; + cVelCount = cVelCount + 1; + } + } + if (cMassCount == 0) { + cMass = cMass / float2(cMassCount, cMassCount) + vPos; + } + if (cVelCount == 0) { + cVel = cVel / float2(cVelCount, cVelCount); + } + vVel = vVel + cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale; + vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); + vPos = vPos + vVel * params.deltaT; + if (vPos.x < -1.0) { + vPos.x = 1.0; + } + if (vPos.x == 1.0) { + vPos.x = -1.0; + } + if (vPos.y < -1.0) { + vPos.y = 1.0; + } + if (vPos.y == 1.0) { + vPos.y = -1.0; + } + particlesB.particles[gl_GlobalInvocationID.x].pos = vPos; + particlesB.particles[gl_GlobalInvocationID.x].vel = vVel; +} + diff --git a/tests/snapshots/snapshots__function.msl.snap b/tests/snapshots/snapshots__function.msl.snap deleted file mode 100644 index cbaab5634..000000000 --- a/tests/snapshots/snapshots__function.msl.snap +++ /dev/null @@ -1,27 +0,0 @@ ---- -source: tests/snapshots.rs -expression: msl ---- -#include -#include - -typedef float type; - -type test_function( - type test -) { - return test; -} -struct main1Input { -}; -struct main1Output { -}; -vertex main1Output main1( - main1Input input [[stage_in]] -) { - main1Output output; - type test1; - test1 = test_function(1.0); - return output; -} - diff --git a/tests/snapshots/snapshots__function.spvasm.snap b/tests/snapshots/snapshots__function.spvasm.snap deleted file mode 100644 index a28f333e1..000000000 --- a/tests/snapshots/snapshots__function.spvasm.snap +++ /dev/null @@ -1,31 +0,0 @@ ---- -source: tests/snapshots.rs -expression: dis ---- -; SPIR-V -; Version: 1.0 -; Generator: rspirv -; Bound: 16 -OpCapability Shader -%1 = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %11 "main" -%2 = OpTypeFloat 32 -%4 = OpTypePointer Function %2 -%6 = OpTypeFunction %2 %4 -%10 = OpTypeVoid -%12 = OpTypeFunction %10 -%15 = OpConstant %2 1.0 -%5 = OpFunction %2 None %6 -%3 = OpFunctionParameter %4 -%7 = OpLabel -%8 = OpLoad %2 %3 -OpReturnValue %8 -OpFunctionEnd -%11 = OpFunction %10 None %12 -%13 = OpLabel -%9 = OpVariable %4 Function -%14 = OpFunctionCall %2 %5 %15 -OpStore %9 %14 -OpReturn -OpFunctionEnd From 0efd6e75d7b3a9b8dbaa7f5e574b57fae903675e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 01:45:28 -0500 Subject: [PATCH 0328/2212] [wgsl] update texture definitions and storage access Add more tests, enhance the snapshot testing. --- src/front/wgsl/lexer.rs | 16 -- src/front/wgsl/mod.rs | 201 ++++++++---------- src/front/wgsl/tests.rs | 12 ++ src/lib.rs | 1 + tests/snapshots.rs | 93 ++++++-- tests/snapshots/in/boids.wgsl | 6 +- tests/snapshots/in/quad.wgsl | 2 +- .../snapshots__quad-Fragment.glsl.snap | 20 ++ .../snapshots__quad-Vertex.glsl.snap | 21 ++ .../snapshots__simple-Vertex.glsl.snap | 17 ++ 10 files changed, 231 insertions(+), 158 deletions(-) create mode 100644 tests/snapshots/snapshots__quad-Fragment.glsl.snap create mode 100644 tests/snapshots/snapshots__quad-Vertex.glsl.snap create mode 100644 tests/snapshots/snapshots__simple-Vertex.glsl.snap diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index d5811604b..31562a3d0 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -222,22 +222,6 @@ impl<'a> Lexer<'a> { Ok(format) } - pub(super) fn take_until(&mut self, what: Token<'_>) -> Result, Error<'a>> { - let original_input = self.input; - let initial_len = self.input.len(); - let mut used_len = 0; - loop { - if self.next() == what { - break; - } - used_len = initial_len - self.input.len(); - } - - Ok(Lexer { - input: &original_input[..used_len], - }) - } - pub(super) fn offset_from(&self, source: &'a str) -> usize { source.len() - self.input.len() } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index edc949c00..042e4e988 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -14,6 +14,7 @@ use crate::{ }; use self::lexer::Lexer; +use std::num::NonZeroU32; use thiserror::Error; #[derive(Copy, Clone, Debug, PartialEq)] @@ -63,6 +64,8 @@ pub enum Error<'a> { UnknownScalarKind(&'a str), #[error("unknown builtin: `{0}`")] UnknownBuiltin(&'a str), + #[error("unknown access: `{0}`")] + UnknownAccess(&'a str), #[error("unknown shader stage: `{0}`")] UnknownShaderStage(&'a str), #[error("unknown identifier: `{0}`")] @@ -251,6 +254,12 @@ impl Composition { } } +#[derive(Default)] +struct TypeDecoration { + stride: Option, + access: crate::StorageAccess, +} + #[derive(Clone, Debug, PartialEq)] pub enum Scope { Decoration, @@ -531,7 +540,8 @@ impl Parser { inner } _ => { - let composite_ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let (composite_ty, _access) = + self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { @@ -625,8 +635,13 @@ impl Parser { if let Some(expr) = self.parse_function_call_inner(lexer, word, ctx.reborrow())? { expr } else { - let inner = - self.parse_type_decl_impl(lexer, None, word, ctx.types, ctx.constants)?; + let inner = self.parse_type_decl_impl( + lexer, + TypeDecoration::default(), + word, + ctx.types, + ctx.constants, + )?; let ty = ctx.types.fetch_or_append(crate::Type { name: None, inner }); lexer.expect(Token::Paren('('))?; @@ -903,11 +918,11 @@ impl Parser { lexer: &mut Lexer<'a>, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result<(&'a str, Handle), Error<'a>> { + ) -> Result<(&'a str, Handle, crate::StorageAccess), Error<'a>> { let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; - Ok((name, ty)) + let (ty, access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + Ok((name, ty, access)) } fn parse_variable_decl<'a>( @@ -925,21 +940,8 @@ impl Parser { } let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; - let access = match class { - Some(crate::StorageClass::Storage) => crate::StorageAccess::all(), - Some(crate::StorageClass::Handle) => { - match type_arena[ty].inner { - //TODO: RW textures - crate::TypeInner::Image { - class: crate::ImageClass::Storage(_), - .. - } => crate::StorageAccess::LOAD, - _ => crate::StorageAccess::empty(), - } - } - _ => crate::StorageAccess::empty(), - }; + let (ty, access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let init = if lexer.skip(Token::Operation('=')) { let handle = self.parse_const_expression(lexer, ty, type_arena, const_arena)?; Some(handle) @@ -998,7 +1000,7 @@ impl Parser { return Err(Error::MissingMemberOffset(name)); } lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Separator(';'))?; members.push(crate::StructMember { name: Some(name.to_owned()), @@ -1011,7 +1013,7 @@ impl Parser { fn parse_type_decl_impl<'a>( &mut self, lexer: &mut Lexer<'a>, - decoration_lexer: Option>, + decoration: TypeDecoration, word: &'a str, type_arena: &mut Arena, const_arena: &mut Arena, @@ -1129,13 +1131,13 @@ impl Parser { lexer.expect(Token::Paren('<'))?; let class = conv::map_storage_class(lexer.next_ident()?)?; lexer.expect(Token::Separator(','))?; - let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Paren('>'))?; crate::TypeInner::Pointer { base, class } } "array" => { lexer.expect(Token::Paren('<'))?; - let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let size = match lexer.next() { Token::Separator(',') => { let value = lexer.next_uint_literal()?; @@ -1158,30 +1160,15 @@ impl Parser { other => return other.unexpected("generic separator"), }; - let mut stride = None; - if let Some(mut lexer) = decoration_lexer { - self.scopes.push(Scope::Decoration); - loop { - match lexer.next() { - Token::Word("stride") => { - use std::num::NonZeroU32; - stride = Some( - NonZeroU32::new(lexer.next_uint_literal()?) - .ok_or(Error::ZeroStride)?, - ); - } - Token::End => break, - other => return other.unexpected("stride decoration"), - } - } - self.scopes.pop(); + crate::TypeInner::Array { + base, + size, + stride: decoration.stride, } - - crate::TypeInner::Array { base, size, stride } } "sampler" => crate::TypeInner::Sampler { comparison: false }, "sampler_comparison" => crate::TypeInner::Sampler { comparison: true }, - "texture_sampled_1d" => { + "texture_1d" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1189,7 +1176,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - "texture_sampled_1d_array" => { + "texture_1d_array" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1197,7 +1184,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - "texture_sampled_2d" => { + "texture_2d" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1205,7 +1192,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - "texture_sampled_2d_array" => { + "texture_2d_array" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1213,7 +1200,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - "texture_sampled_3d" => { + "texture_3d" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D3, @@ -1221,7 +1208,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - "texture_sampled_cube" => { + "texture_cube" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::Cube, @@ -1229,7 +1216,7 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: false }, } } - "texture_sampled_cube_array" => { + "texture_cube_array" => { let (kind, _) = lexer.next_scalar_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::Cube, @@ -1265,7 +1252,7 @@ impl Parser { arrayed: true, class: crate::ImageClass::Depth, }, - "texture_ro_1d" => { + "texture_storage_1d" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1273,7 +1260,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - "texture_ro_1d_array" => { + "texture_storage_1d_array" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -1281,7 +1268,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - "texture_ro_2d" => { + "texture_storage_2d" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1289,7 +1276,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - "texture_ro_2d_array" => { + "texture_storage_2d_array" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -1297,47 +1284,7 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - "texture_ro_3d" => { - let format = lexer.next_format_generic()?; - crate::TypeInner::Image { - dim: crate::ImageDimension::D3, - arrayed: false, - class: crate::ImageClass::Storage(format), - } - } - "texture_wo_1d" => { - let format = lexer.next_format_generic()?; - crate::TypeInner::Image { - dim: crate::ImageDimension::D1, - arrayed: false, - class: crate::ImageClass::Storage(format), - } - } - "texture_wo_1d_array" => { - let format = lexer.next_format_generic()?; - crate::TypeInner::Image { - dim: crate::ImageDimension::D1, - arrayed: true, - class: crate::ImageClass::Storage(format), - } - } - "texture_wo_2d" => { - let format = lexer.next_format_generic()?; - crate::TypeInner::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Storage(format), - } - } - "texture_wo_2d_array" => { - let format = lexer.next_format_generic()?; - crate::TypeInner::Image { - dim: crate::ImageDimension::D2, - arrayed: true, - class: crate::ImageClass::Storage(format), - } - } - "texture_wo_3d" => { + "texture_storage_3d" => { let format = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D3, @@ -1355,25 +1302,45 @@ impl Parser { self_name: Option<&'a str>, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result, Error<'a>> { + ) -> Result<(Handle, crate::StorageAccess), Error<'a>> { self.scopes.push(Scope::TypeDecl); - let decoration_lexer = if lexer.skip(Token::DoubleParen('[')) { - Some(lexer.take_until(Token::DoubleParen(']'))?) - } else { - None - }; + let mut decoration = TypeDecoration::default(); + if lexer.skip(Token::DoubleParen('[')) { + self.scopes.push(Scope::Decoration); + loop { + match lexer.next() { + Token::Word("access") => { + lexer.expect(Token::Paren('('))?; + decoration.access = match lexer.next_ident()? { + "read" => crate::StorageAccess::LOAD, + "write" => crate::StorageAccess::STORE, + "read_write" => crate::StorageAccess::all(), + other => return Err(Error::UnknownAccess(other)), + }; + lexer.expect(Token::Paren(')'))?; + } + Token::Word("stride") => { + lexer.expect(Token::Paren('('))?; + decoration.stride = Some( + NonZeroU32::new(lexer.next_uint_literal()?).ok_or(Error::ZeroStride)?, + ); + lexer.expect(Token::Paren(')'))?; + } + Token::DoubleParen(']') => break, + other => return other.unexpected("type decoration"), + } + } + self.scopes.pop(); + } + + let storage_access = decoration.access; let name = lexer.next_ident()?; let handle = match self.lookup_type.get(name) { Some(&handle) => handle, None => { - let inner = self.parse_type_decl_impl( - lexer, - decoration_lexer, - name, - type_arena, - const_arena, - )?; + let inner = + self.parse_type_decl_impl(lexer, decoration, name, type_arena, const_arena)?; type_arena.fetch_or_append(crate::Type { name: self_name.map(|s| s.to_string()), inner, @@ -1382,7 +1349,7 @@ impl Parser { }; self.scopes.pop(); - Ok(handle) + Ok((handle, storage_access)) } fn parse_statement<'a>( @@ -1399,7 +1366,7 @@ impl Parser { self.scopes.push(Scope::Statement); let statement = match word { "const" => { - let (name, _ty) = + let (name, _ty, _access) = self.parse_variable_ident_decl(lexer, context.types, context.constants)?; lexer.expect(Token::Operation('='))?; let expr_id = self.parse_general_expression(lexer, context.as_expression())?; @@ -1414,7 +1381,7 @@ impl Parser { Variable(Handle), } - let (name, ty) = + let (name, ty, _access) = self.parse_variable_ident_decl(lexer, context.types, context.constants)?; let init = if lexer.skip(Token::Operation('=')) { @@ -1631,7 +1598,7 @@ impl Parser { if !arguments.is_empty() { lexer.expect(Token::Separator(','))?; } - let (param_name, param_type) = + let (param_name, param_type, _access) = self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; let param_index = arguments.len() as u32; let expression_token = @@ -1644,7 +1611,9 @@ impl Parser { } // read return type let return_type = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { - Some(self.parse_type_decl(lexer, None, &mut module.types, &mut module.constants)?) + let (handle, _access) = + self.parse_type_decl(lexer, None, &mut module.types, &mut module.constants)?; + Some(handle) } else { None }; @@ -1792,7 +1761,7 @@ impl Parser { Token::Word("type") => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; - let ty = self.parse_type_decl( + let (ty, _access) = self.parse_type_decl( lexer, Some(name), &mut module.types, @@ -1802,7 +1771,7 @@ impl Parser { lexer.expect(Token::Separator(';'))?; } Token::Word("const") => { - let (name, ty) = self.parse_variable_ident_decl( + let (name, ty, _access) = self.parse_variable_ident_decl( lexer, &mut module.types, &mut module.constants, diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 5d9f4f5a3..12fa67218 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -4,6 +4,18 @@ use super::parse_str; fn parse_types() { parse_str("const a : i32 = 2;").unwrap(); assert!(parse_str("const a : x32 = 2;").is_err()); + parse_str("var t: texture_2d;").unwrap(); + parse_str("var t: texture_cube_array;").unwrap(); + parse_str("var t: texture_multisampled_2d;").unwrap(); + parse_str("var t: [[access(write)]] texture_storage_1d;").unwrap(); + parse_str("var t: [[access(read)]] texture_storage_3d;").unwrap(); + parse_str( + " + [[block]] struct Foo { [[offset(0)]] x: i32; }; + var s: [[access(read_write)]] Foo; + ", + ) + .unwrap(); } #[test] diff --git a/src/lib.rs b/src/lib.rs index 6cc3bd4db..895f58386 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -268,6 +268,7 @@ bitflags::bitflags! { /// Flags describing an image. #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] + #[derive(Default)] pub struct StorageAccess: u32 { /// Storage can be used as a source for load ops. const LOAD = 0x1; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 32072f680..23b34e664 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -16,12 +16,16 @@ struct BindSource { #[derive(Deserialize)] struct BindTarget { + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] #[serde(default)] buffer: Option, + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] #[serde(default)] texture: Option, + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] #[serde(default)] sampler: Option, + #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] #[serde(default)] mutable: bool, } @@ -37,9 +41,36 @@ struct Parameters { mtl_bindings: naga::FastHashMap, } +bitflags::bitflags! { + struct Language: u32 { + const SPIRV = 0x1; + const METAL = 0x2; + const GLSL = 0x4; + } +} + +#[cfg(feature = "spv-out")] +fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { + use naga::back::spv; + use rspirv::binary::Disassemble; + + let spv = spv::write_vec( + &module, + spv::WriterFlags::NONE, + params.spv_capabilities.clone(), + ) + .unwrap(); + + let dis = rspirv::dr::load_words(spv) + .expect("Produced invalid SPIR-V") + .disassemble(); + insta::assert_snapshot!(format!("{}.spvasm", name), dis); +} + #[cfg(feature = "msl-out")] fn check_output_msl(module: &naga::Module, name: &str, params: &Parameters) { use naga::back::msl; + let mut binding_map = msl::BindingMap::default(); for (key, value) in params.mtl_bindings.iter() { binding_map.insert( @@ -65,28 +96,30 @@ fn check_output_msl(module: &naga::Module, name: &str, params: &Parameters) { spirv_cross_compatibility: false, binding_map, }; + let (msl, _) = msl::write_string(&module, &options).unwrap(); - insta::assert_snapshot!(format!("{}{}", name, ".msl"), msl); + insta::assert_snapshot!(format!("{}.msl", name), msl); } -#[cfg(feature = "spv-out")] -fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { - use naga::back::spv; - use rspirv::binary::Disassemble; - let spv = spv::write_vec( - &module, - spv::WriterFlags::NONE, - params.spv_capabilities.clone(), - ) - .unwrap(); - let dis = rspirv::dr::load_words(spv) - .expect("Produced invalid SPIR-V") - .disassemble(); - insta::assert_snapshot!(format!("{}{}", name, ".spvasm"), dis); +#[cfg(feature = "glsl-out")] +fn check_output_glsl(module: &naga::Module, name: &str, stage: naga::ShaderStage, ep_name: &str) { + use naga::back::glsl; + + let options = glsl::Options { + version: glsl::Version::Embedded(310), + entry_point: (stage, ep_name.to_string()), + }; + + let mut buffer = Vec::new(); + let mut writer = glsl::Writer::new(&mut buffer, &module, &options).unwrap(); + writer.write().unwrap(); + + let string = String::from_utf8(buffer).unwrap(); + insta::assert_snapshot!(format!("{}-{:?}.glsl", name, stage), string); } #[cfg(feature = "wgsl-in")] -fn convert_wgsl(name: &str) { +fn convert_wgsl(name: &str, language: Language) { let params = match std::fs::read_to_string(format!("tests/snapshots/in/{}{}", name, ".param.ron")) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), @@ -100,26 +133,42 @@ fn convert_wgsl(name: &str) { .unwrap(); naga::proc::Validator::new().validate(&module).unwrap(); - #[cfg(feature = "msl-out")] - check_output_msl(&module, name, ¶ms); #[cfg(feature = "spv-out")] - check_output_spv(&module, name, ¶ms); + { + if language.contains(Language::SPIRV) { + check_output_spv(&module, name, ¶ms); + } + } + #[cfg(feature = "msl-out")] + { + if language.contains(Language::METAL) { + check_output_msl(&module, name, ¶ms); + } + } + #[cfg(feature = "glsl-out")] + { + if language.contains(Language::GLSL) { + for &(stage, ref ep_name) in module.entry_points.keys() { + check_output_glsl(&module, name, stage, ep_name); + } + } + } } #[cfg(feature = "wgsl-in")] #[test] fn converts_wgsl_quad() { - convert_wgsl("quad"); + convert_wgsl("quad", Language::all()); } #[cfg(feature = "wgsl-in")] #[test] fn converts_wgsl_simple() { - convert_wgsl("simple"); + convert_wgsl("simple", Language::all()); } #[cfg(feature = "wgsl-in")] #[test] fn converts_wgsl_boids() { - convert_wgsl("boids"); + convert_wgsl("boids", Language::METAL); } diff --git a/tests/snapshots/in/boids.wgsl b/tests/snapshots/in/boids.wgsl index 8c5ff2fd1..022827774 100644 --- a/tests/snapshots/in/boids.wgsl +++ b/tests/snapshots/in/boids.wgsl @@ -56,12 +56,12 @@ struct SimParams { [[block]] struct Particles { - [[offset(0)]] particles : [[stride 16]] array; + [[offset(0)]] particles : [[stride(16)]] array; }; [[group(0), binding(0)]] var params : SimParams; -[[group(0), binding(1)]] var particlesA : Particles; -[[group(0), binding(2)]] var particlesB : Particles; +[[group(0), binding(1)]] var particlesA : [[access(read_write)]] Particles; +[[group(0), binding(2)]] var particlesB : [[access(read_write)]] Particles; [[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3; diff --git a/tests/snapshots/in/quad.wgsl b/tests/snapshots/in/quad.wgsl index 50b367cf9..d7b45f22d 100644 --- a/tests/snapshots/in/quad.wgsl +++ b/tests/snapshots/in/quad.wgsl @@ -13,7 +13,7 @@ fn main() { # fragment [[location(0)]] var v_uv : vec2; -[[group(0), binding(0)]] var u_texture : texture_sampled_2d; +[[group(0), binding(0)]] var u_texture : texture_2d; [[group(0), binding(1)]] var u_sampler : sampler; [[location(0)]] var o_color : vec4; diff --git a/tests/snapshots/snapshots__quad-Fragment.glsl.snap b/tests/snapshots/snapshots__quad-Fragment.glsl.snap new file mode 100644 index 000000000..8340d7ff8 --- /dev/null +++ b/tests/snapshots/snapshots__quad-Fragment.glsl.snap @@ -0,0 +1,20 @@ +--- +source: tests/snapshots.rs +expression: string +--- +#version 310 es + +precision highp float; + + + +in vec2 v_uv1; +uniform sampler2D u_texture; +out vec4 o_color; + +void main() { + + o_color = texture(u_texture, v_uv1); + return; +} + diff --git a/tests/snapshots/snapshots__quad-Vertex.glsl.snap b/tests/snapshots/snapshots__quad-Vertex.glsl.snap new file mode 100644 index 000000000..eb95684f4 --- /dev/null +++ b/tests/snapshots/snapshots__quad-Vertex.glsl.snap @@ -0,0 +1,21 @@ +--- +source: tests/snapshots.rs +expression: string +--- +#version 310 es + +precision highp float; + + + +in vec2 a_pos; +in vec2 a_uv; +out vec2 v_uv; + +void main() { + + v_uv = a_uv; + gl_Position = vec4((1.2 * a_pos), 0.0, 1.0); + return; +} + diff --git a/tests/snapshots/snapshots__simple-Vertex.glsl.snap b/tests/snapshots/snapshots__simple-Vertex.glsl.snap new file mode 100644 index 000000000..d32d80074 --- /dev/null +++ b/tests/snapshots/snapshots__simple-Vertex.glsl.snap @@ -0,0 +1,17 @@ +--- +source: tests/snapshots.rs +expression: string +--- +#version 310 es + +precision highp float; + + + + +void main() { + + gl_Position = vec4(1); + return; +} + From 087b5555a61dc48893a17f8e2dbb6b238ae0d4ca Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 09:56:10 -0500 Subject: [PATCH 0329/2212] Add tests for GLSL parsing --- tests/parse.rs | 33 +++++++++++++++++++++++++++++++++ tests/snapshots.rs | 10 ++++------ 2 files changed, 37 insertions(+), 6 deletions(-) create mode 100644 tests/parse.rs diff --git a/tests/parse.rs b/tests/parse.rs new file mode 100644 index 000000000..fe03f153b --- /dev/null +++ b/tests/parse.rs @@ -0,0 +1,33 @@ +//TODO: consider converting this to snapshots? + +#[cfg(feature = "glsl-in")] +fn check_glsl(name: &str) { + let path = std::path::PathBuf::from("test-data").join(name); + let input = std::fs::read_to_string(path).unwrap(); + let stage = if name.ends_with(".vert") { + naga::ShaderStage::Vertex + } else if name.ends_with(".frag") { + naga::ShaderStage::Fragment + } else if name.ends_with(".comp") { + naga::ShaderStage::Compute + } else { + panic!("Unknown extension in {:?}", name) + }; + + match naga::front::glsl::parse_str(&input, "main", stage, Default::default()) { + Ok(m) => match naga::proc::Validator::new().validate(&m) { + Ok(()) => (), + Err(e) => panic!("Unable to validate {}: {:?}", name, e), + }, + Err(e) => panic!("Unable to parse {}: {:?}", name, e), + }; +} + +#[cfg(feature = "glsl-in")] +#[test] +fn parse_glsl() { + //check_glsl("glsl_constant_expression.vert"); //TODO + //check_glsl("glsl_if_preprocessor.vert"); + check_glsl("glsl_preprocessor_abuse.vert"); + check_glsl("glsl_vertex_test_shader.vert"); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 23b34e664..5f262708d 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -1,20 +1,18 @@ -use serde::Deserialize; - -#[derive(Hash, PartialEq, Eq, Deserialize)] +#[derive(Hash, PartialEq, Eq, serde::Deserialize)] enum Stage { Vertex, Fragment, Compute, } -#[derive(Hash, PartialEq, Eq, Deserialize)] +#[derive(Hash, PartialEq, Eq, serde::Deserialize)] struct BindSource { stage: Stage, group: u32, binding: u32, } -#[derive(Deserialize)] +#[derive(serde::Deserialize)] struct BindTarget { #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] #[serde(default)] @@ -30,7 +28,7 @@ struct BindTarget { mutable: bool, } -#[derive(Default, Deserialize)] +#[derive(Default, serde::Deserialize)] struct Parameters { #[serde(default)] #[allow(dead_code)] From 211bec44a1b2821c0937bc3f6a924ad0e3c6ee31 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 12:25:03 -0500 Subject: [PATCH 0330/2212] Improve texture sampling IR, update WGSL parsing of it --- src/back/glsl/mod.rs | 104 ++++++---- src/back/msl/writer.rs | 24 ++- src/back/spv/writer.rs | 26 ++- src/front/glsl/parser.rs | 2 + src/front/spv/mod.rs | 49 +++-- src/front/wgsl/mod.rs | 193 ++++++++++++++++-- src/lib.rs | 7 + src/proc/interface.rs | 15 +- .../snapshots__quad-Fragment.glsl.snap | 2 +- tests/snapshots/snapshots__quad.msl.snap | 1 + 10 files changed, 339 insertions(+), 84 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 7c302b567..66a7cba62 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1181,22 +1181,22 @@ impl<'a, W: Write> Writer<'a, W> { // Furthermore if `depth_ref` is some we need to append it to the coordinate vector Expression::ImageSample { image, + sampler: _, //TODO coordinate, + array_index, + offset: _, //TODO level, depth_ref, - .. } => { //TODO: handle MS //Write the function to be used depending on the sample level - write!( - self.out, - "{}(", - match level { - crate::SampleLevel::Auto | crate::SampleLevel::Bias(_) => "texture", - crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => "textureLod", - } - )?; + let fun_name = match level { + crate::SampleLevel::Auto | crate::SampleLevel::Bias(_) => "texture", + crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => "textureLod", + crate::SampleLevel::Gradient { .. } => "textureGrad", + }; + write!(self.out, "{}(", fun_name)?; // Write the image that will be used self.write_expr(image, ctx)?; @@ -1210,18 +1210,26 @@ impl<'a, W: Write> Writer<'a, W> { _ => unreachable!(), }; - if let Some(depth_ref) = depth_ref { - // Compose a new vector with the coordinates and `depth_ref` - write!(self.out, "vec{}(", size as u8 + 1)?; - self.write_expr(coordinate, ctx)?; - // The space here isn't required but it helps with readability - write!(self.out, ", ")?; - self.write_expr(depth_ref, ctx)?; - write!(self.out, ")")? - } else { - // There's no `depth_ref` so just write the coordinate expression - self.write_expr(coordinate, ctx)? + let mut coord_dim = size as u8; + if array_index.is_some() { + coord_dim += 1; } + if depth_ref.is_some() { + coord_dim += 1; + } + + // Compose a new texture coordinates vector + write!(self.out, "vec{}(", coord_dim)?; + self.write_expr(coordinate, ctx)?; + if let Some(expr) = array_index { + write!(self.out, ", ")?; + self.write_expr(expr, ctx)?; + } + if let Some(expr) = depth_ref { + write!(self.out, ", ")?; + self.write_expr(expr, ctx)?; + } + write!(self.out, ")")?; match level { // Auto needs no more arguments @@ -1233,6 +1241,12 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ", ")?; self.write_expr(expr, ctx)?; } + crate::SampleLevel::Gradient { x, y } => { + write!(self.out, ", ")?; + self.write_expr(x, ctx)?; + write!(self.out, ", ")?; + self.write_expr(y, ctx)?; + } } // End the function @@ -1249,35 +1263,53 @@ impl<'a, W: Write> Writer<'a, W> { Expression::ImageLoad { image, coordinate, + array_index, index, } => { // This will only panic if the module is invalid - let class = match ctx.typifier.get(image, &self.module.types) { - TypeInner::Image { class, .. } => class, + let (dim, class) = match ctx.typifier.get(image, &self.module.types) { + TypeInner::Image { + dim, + arrayed: _, + class, + } => (dim, class), _ => unreachable!(), }; - match class { - ImageClass::Sampled { .. } => write!(self.out, "texelFetch(")?, - ImageClass::Storage(_) => write!(self.out, "imageLoad(")?, + let fun_name = match class { + ImageClass::Sampled { .. } => "texelFetch", + ImageClass::Storage(_) => "imageLoad", // TODO: Is there even a function for this? ImageClass::Depth => todo!(), - } + }; + write!(self.out, "{}(", fun_name)?; self.write_expr(image, ctx)?; - write!(self.out, ", ")?; - self.write_expr(coordinate, ctx)?; - - match class { - ImageClass::Sampled { .. } => { + match array_index { + Some(layer_expr) => { + let tex_coord_type = match dim { + crate::ImageDimension::D1 => "ivec2", + crate::ImageDimension::D2 => "ivec3", + crate::ImageDimension::D3 => "ivec4", + crate::ImageDimension::Cube => "ivec4", + }; + write!(self.out, ", {}(", tex_coord_type)?; + self.write_expr(coordinate, ctx)?; write!(self.out, ", ")?; - // This will only panic if the module is invalid - self.write_expr(index.unwrap(), ctx)?; - write!(self.out, ")")? + self.write_expr(layer_expr, ctx)?; + write!(self.out, ")")?; + } + None => { + write!(self.out, ", ")?; + self.write_expr(coordinate, ctx)?; } - ImageClass::Storage(_) => write!(self.out, ")")?, - ImageClass::Depth => todo!(), } + + if let Some(index_expr) = index { + write!(self.out, ", ")?; + self.write_expr(index_expr, ctx)?; + } + write!(self.out, ")")?; } // `Unary` is pretty straightforward // "-" - for `Negate` diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e151e9f69..16f323f3e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -240,6 +240,8 @@ impl Writer { image, sampler, coordinate, + array_index, + offset, level, depth_ref, } => { @@ -247,12 +249,15 @@ impl Writer { Some(_) => "sample_compare", None => "sample", }; - //TODO: handle arrayed images self.put_expression(image, context)?; write!(self.out, ".{}(", op)?; self.put_expression(sampler, context)?; write!(self.out, ", ")?; self.put_expression(coordinate, context)?; + if let Some(expr) = array_index { + write!(self.out, ", ")?; + self.put_expression(expr, context)?; + } if let Some(dref) = depth_ref { write!(self.out, ", ")?; self.put_expression(dref, context)?; @@ -272,18 +277,33 @@ impl Writer { self.put_expression(h, context)?; write!(self.out, ")")?; } + crate::SampleLevel::Gradient { x, y } => { + write!(self.out, ", gradient(")?; + self.put_expression(x, context)?; + write!(self.out, ", ")?; + self.put_expression(y, context)?; + write!(self.out, ")")?; + } + } + if let Some(constant) = offset { + write!(self.out, ", ")?; + self.put_constant(constant, context.module)?; } write!(self.out, ")")?; } crate::Expression::ImageLoad { image, coordinate, + array_index, index, } => { - //TODO: handle arrayed images self.put_expression(image, context)?; write!(self.out, ".read(")?; self.put_expression(coordinate, context)?; + if let Some(expr) = array_index { + write!(self.out, ", ")?; + self.put_expression(expr, context)?; + } if let Some(index) = index { write!(self.out, ", ")?; self.put_expression(index, context)?; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 7650dac67..b6023581f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1379,7 +1379,9 @@ impl Writer { image, sampler, coordinate, - level: _, + array_index: _, //TODO + offset: _, //TODO + level, depth_ref: _, } => { // image @@ -1507,14 +1509,20 @@ impl Writer { let id = self.generate_id(); let image_sample_result_type_id = self.get_type_id(&ir_module.types, image_sample_result_type)?; - block - .body - .push(super::instructions::instruction_image_sample_implicit_lod( - image_sample_result_type_id, - id, - sampled_image_id, - coordinate_id, - )); + + let main_instruction = match level { + crate::SampleLevel::Auto => { + super::instructions::instruction_image_sample_implicit_lod( + image_sample_result_type_id, + id, + sampled_image_id, + coordinate_id, + ) + } + _ => return Err(Error::FeatureNotImplemented("sample level")), + }; + + block.body.push(main_instruction); Ok((id, image_sample_result_type)) } _ => { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 437272191..05086ff65 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -288,6 +288,8 @@ pomelo! { image: fc.args[0].expression, sampler, coordinate: fc.args[1].expression, + array_index: None, //TODO + offset: None, //TODO level: SampleLevel::Auto, depth_ref: None, }), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 0f16da030..ceaf00e27 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -943,6 +943,7 @@ impl> Parser { crate::TypeInner::Sampler { comparison: false } => (), _ => return Err(Error::InvalidSampleSampler(sampler_type_handle)), }; + match type_arena[image_type_handle].inner { //TODO: compare the result type crate::TypeInner::Image { @@ -968,31 +969,41 @@ impl> Parser { let mut level = crate::SampleLevel::Auto; let mut base_wc = 5; - if base_wc < inst.wc { + while base_wc < inst.wc { let image_ops = self.next()?; base_wc += 1; - let mask = spirv::ImageOperands::from_bits_truncate(image_ops); - if mask.contains(spirv::ImageOperands::BIAS) { - let bias_expr = self.next()?; - let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; - level = crate::SampleLevel::Bias(bias_handle); - base_wc += 1; - } - if mask.contains(spirv::ImageOperands::LOD) { - let lod_expr = self.next()?; - let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; - level = crate::SampleLevel::Exact(lod_handle); - base_wc += 1; - } - for _ in base_wc..inst.wc { - self.next()?; + match spirv::ImageOperands::from_bits_truncate(image_ops) { + spirv::ImageOperands::BIAS => { + let bias_expr = self.next()?; + let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; + level = crate::SampleLevel::Bias(bias_handle); + base_wc += 1; + } + spirv::ImageOperands::LOD => { + let lod_expr = self.next()?; + let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; + level = crate::SampleLevel::Exact(lod_handle); + base_wc += 1; + } + other => { + log::warn!("Skipping {:?}", other); + for _ in base_wc..inst.wc { + self.next()?; + } + break; + } } } + //TODO: disassemble `coordinate_id` into the part responsible for + // texture coordinates, and the array index. + let expr = crate::Expression::ImageSample { image: si_lexp.image, sampler: si_lexp.sampler, coordinate: coord_lexp.handle, + array_index: None, //TODO + offset: None, //TODO level, depth_ref: None, }; @@ -1062,6 +1073,8 @@ impl> Parser { image: si_lexp.image, sampler: si_lexp.sampler, coordinate: coord_lexp.handle, + array_index: None, //TODO + offset: None, //TODO level: crate::SampleLevel::Auto, depth_ref: Some(dref_lexp.handle), }; @@ -1519,10 +1532,6 @@ impl> Parser { let ty = module.types.get_mut(handle); match ty.inner { crate::TypeInner::Sampler { ref mut comparison } => { - #[allow(clippy::panic)] - { - assert!(!*comparison) - }; *comparison = true; } _ => { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 042e4e988..2f17ca057 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -52,6 +52,10 @@ pub enum Error<'a> { BadFloat(&'a str, std::num::ParseFloatError), #[error("bad field accessor `{0}`")] BadAccessor(&'a str), + #[error("bad texture {0}`")] + BadTexture(&'a str), + #[error("bad texture coordinate")] + BadCoordinate, #[error(transparent)] InvalidResolve(ResolveError), #[error("unknown import: `{0}`")] @@ -140,6 +144,12 @@ impl<'a> StatementContext<'a, '_, '_> { } } +struct SamplingContext { + image: Handle, + arrayed: bool, + offset_type: Handle, +} + struct ExpressionContext<'input, 'temp, 'out> { lookup_ident: &'temp FastHashMap<&'input str, Handle>, typifier: &'temp mut Typifier, @@ -186,6 +196,38 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } + fn prepare_sampling( + &mut self, + image_name: &'a str, + coordinate: Handle, + ) -> Result> { + let image = self.lookup_ident.lookup(image_name)?; + let kind = crate::ScalarKind::Sint; + let offset_inner = match *self.resolve_type(coordinate)? { + crate::TypeInner::Scalar { width, kind: _ } => crate::TypeInner::Scalar { width, kind }, + crate::TypeInner::Vector { + size, + width, + kind: _, + } => crate::TypeInner::Vector { size, width, kind }, + ref other => { + log::error!("Unexpected coordinate type {:?}", other); + return Err(Error::BadCoordinate); + } + }; + Ok(SamplingContext { + image, + arrayed: match *self.resolve_type(image)? { + crate::TypeInner::Image { arrayed, .. } => arrayed, + _ => return Err(Error::BadTexture(image_name)), + }, + offset_type: self.types.fetch_or_append(crate::Type { + name: None, + inner: offset_inner, + }), + }) + } + fn parse_binary_op( &mut self, lexer: &mut Lexer<'a>, @@ -401,11 +443,30 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let sc = ctx.prepare_sampling(image_name, coordinate)?; + let array_index = if sc.arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; + let offset = if lexer.skip(Token::Separator(',')) { + Some(self.parse_const_expression( + lexer, + sc.offset_type, + ctx.types, + ctx.constants, + )?) + } else { + None + }; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageSample { - image: ctx.lookup_ident.lookup(image_name)?, + image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, + array_index, + offset, level: crate::SampleLevel::Auto, depth_ref: None, }) @@ -417,13 +478,32 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let sc = ctx.prepare_sampling(image_name, coordinate)?; + let array_index = if sc.arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; lexer.expect(Token::Separator(','))?; let level = self.parse_general_expression(lexer, ctx.reborrow())?; + let offset = if lexer.skip(Token::Separator(',')) { + Some(self.parse_const_expression( + lexer, + sc.offset_type, + ctx.types, + ctx.constants, + )?) + } else { + None + }; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageSample { - image: ctx.lookup_ident.lookup(image_name)?, + image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, + array_index, + offset, level: crate::SampleLevel::Exact(level), depth_ref: None, }) @@ -435,17 +515,75 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let sc = ctx.prepare_sampling(image_name, coordinate)?; + let array_index = if sc.arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; lexer.expect(Token::Separator(','))?; let bias = self.parse_general_expression(lexer, ctx.reborrow())?; + let offset = if lexer.skip(Token::Separator(',')) { + Some(self.parse_const_expression( + lexer, + sc.offset_type, + ctx.types, + ctx.constants, + )?) + } else { + None + }; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageSample { - image: ctx.lookup_ident.lookup(image_name)?, + image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, + array_index, + offset, level: crate::SampleLevel::Bias(bias), depth_ref: None, }) } + "textureSampleGrad" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let sampler_name = lexer.next_ident()?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let sc = ctx.prepare_sampling(image_name, coordinate)?; + let array_index = if sc.arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; + lexer.expect(Token::Separator(','))?; + let x = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let y = self.parse_general_expression(lexer, ctx.reborrow())?; + let offset = if lexer.skip(Token::Separator(',')) { + Some(self.parse_const_expression( + lexer, + sc.offset_type, + ctx.types, + ctx.constants, + )?) + } else { + None + }; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageSample { + image: sc.image, + sampler: ctx.lookup_ident.lookup(sampler_name)?, + coordinate, + array_index, + offset, + level: crate::SampleLevel::Gradient { x, y }, + depth_ref: None, + }) + } "textureSampleCompare" => { lexer.expect(Token::Paren('('))?; let image_name = lexer.next_ident()?; @@ -453,13 +591,32 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let sc = ctx.prepare_sampling(image_name, coordinate)?; + let array_index = if sc.arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; lexer.expect(Token::Separator(','))?; let reference = self.parse_general_expression(lexer, ctx.reborrow())?; + let offset = if lexer.skip(Token::Separator(',')) { + Some(self.parse_const_expression( + lexer, + sc.offset_type, + ctx.types, + ctx.constants, + )?) + } else { + None + }; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageSample { - image: ctx.lookup_ident.lookup(image_name)?, + image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, + array_index, + offset, level: crate::SampleLevel::Zero, depth_ref: Some(reference), }) @@ -470,24 +627,29 @@ impl Parser { let image = ctx.lookup_ident.lookup(image_name)?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let is_storage = match *ctx.resolve_type(image)? { - crate::TypeInner::Image { - class: crate::ImageClass::Storage(_), - .. - } => true, - _ => false, + let (class, arrayed) = match *ctx.resolve_type(image)? { + crate::TypeInner::Image { class, arrayed, .. } => (class, arrayed), + _ => return Err(Error::BadTexture(image_name)), }; - let index = if is_storage { - None - } else { + let array_index = if arrayed { lexer.expect(Token::Separator(','))?; - let index_name = lexer.next_ident()?; - Some(ctx.lookup_ident.lookup(index_name)?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; + let index = match class { + crate::ImageClass::Storage(_) => { + lexer.expect(Token::Separator(','))?; + let index_name = lexer.next_ident()?; + Some(ctx.lookup_ident.lookup(index_name)?) + } + crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth => None, }; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageLoad { image, coordinate, + array_index, index, }) } @@ -744,6 +906,7 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { self.scopes.push(Scope::SingularExpr); + //TODO: refactor this to avoid backing up let backup = lexer.clone(); let expression = match lexer.next() { Token::Operation('-') => Some(crate::Expression::Unary { diff --git a/src/lib.rs b/src/lib.rs index 895f58386..74b5cfd9e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -612,6 +612,10 @@ pub enum SampleLevel { Zero, Exact(Handle), Bias(Handle), + Gradient { + x: Handle, + y: Handle, + }, } /// An expression that can be evaluated to obtain a value. @@ -649,6 +653,8 @@ pub enum Expression { image: Handle, sampler: Handle, coordinate: Handle, + array_index: Option>, + offset: Option>, level: SampleLevel, depth_ref: Option>, }, @@ -656,6 +662,7 @@ pub enum Expression { ImageLoad { image: Handle, coordinate: Handle, + array_index: Option>, /// For storage images, this is None. /// For sampled images, this is the Some(Level). /// For multisampled images, this is Some(Sample). diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 29f117684..db6073b0b 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -45,16 +45,25 @@ where image, sampler, coordinate, + array_index, + offset: _, level, depth_ref, } => { self.traverse_expr(image); self.traverse_expr(sampler); self.traverse_expr(coordinate); + if let Some(layer) = array_index { + self.traverse_expr(layer); + } match level { crate::SampleLevel::Auto | crate::SampleLevel::Zero => (), crate::SampleLevel::Exact(h) | crate::SampleLevel::Bias(h) => { - self.traverse_expr(h) + self.traverse_expr(h); + } + crate::SampleLevel::Gradient { x, y } => { + self.traverse_expr(x); + self.traverse_expr(y); } } if let Some(dref) = depth_ref { @@ -64,10 +73,14 @@ where E::ImageLoad { image, coordinate, + array_index, index, } => { self.traverse_expr(image); self.traverse_expr(coordinate); + if let Some(layer) = array_index { + self.traverse_expr(layer); + } if let Some(index) = index { self.traverse_expr(index); } diff --git a/tests/snapshots/snapshots__quad-Fragment.glsl.snap b/tests/snapshots/snapshots__quad-Fragment.glsl.snap index 8340d7ff8..4bbecf0de 100644 --- a/tests/snapshots/snapshots__quad-Fragment.glsl.snap +++ b/tests/snapshots/snapshots__quad-Fragment.glsl.snap @@ -14,7 +14,7 @@ out vec4 o_color; void main() { - o_color = texture(u_texture, v_uv1); + o_color = texture(u_texture, vec2(v_uv1)); return; } diff --git a/tests/snapshots/snapshots__quad.msl.snap b/tests/snapshots/snapshots__quad.msl.snap index d96f5e3e0..8fe9dfede 100644 --- a/tests/snapshots/snapshots__quad.msl.snap +++ b/tests/snapshots/snapshots__quad.msl.snap @@ -10,6 +10,7 @@ typedef float2 type1; typedef float4 type2; typedef texture2d type3; typedef sampler type4; +typedef int2 type5; struct main1Input { type1 a_pos [[attribute(0)]]; From 2d1006835ad2bf8ea1eb723bb296ed87cbb13488 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 14:48:32 -0500 Subject: [PATCH 0331/2212] Fix WGSL variable storage classes, spv-out interface --- src/back/spv/writer.rs | 11 ++++++----- src/front/wgsl/mod.rs | 11 ++++++++++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b6023581f..f688c4481 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -390,15 +390,16 @@ impl Writer { let function_id = self.write_function(&entry_point.function, ir_module)?; let mut interface_ids = vec![]; - for ((handle, _), &usage) in ir_module + for ((handle, var), &usage) in ir_module .global_variables .iter() - .filter(|&(_, var)| { - var.class == crate::StorageClass::Input || var.class == crate::StorageClass::Output - }) .zip(&entry_point.function.global_usage) { - if usage.contains(crate::GlobalUse::STORE) || usage.contains(crate::GlobalUse::LOAD) { + let is_io = match var.class { + crate::StorageClass::Input | crate::StorageClass::Output => !usage.is_empty(), + _ => false, + }; + if is_io { let id = self.get_global_variable_id(ir_module, handle)?; interface_ids.push(id); } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2f17ca057..ec69381f2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1960,7 +1960,16 @@ impl Parser { crate::BuiltIn::Position => crate::StorageClass::Output, _ => unimplemented!(), }, - _ => crate::StorageClass::Handle, + Some(crate::Binding::Resource { .. }) => { + match module.types[pvar.ty].inner { + crate::TypeInner::Struct { .. } if pvar.access.is_empty() => { + crate::StorageClass::Uniform + } + crate::TypeInner::Struct { .. } => crate::StorageClass::Storage, + _ => crate::StorageClass::Handle, + } + } + _ => crate::StorageClass::Private, }, }; let var_handle = module.global_variables.append(crate::GlobalVariable { From 98857f09a2562492c6a16afd64dee1ef9f61b31d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 15:43:53 -0500 Subject: [PATCH 0332/2212] Move Transpose into math functions --- src/back/glsl/mod.rs | 7 +------ src/back/msl/writer.rs | 4 +--- src/front/spv/mod.rs | 7 ++++++- src/front/wgsl/conv.rs | 1 + src/lib.rs | 3 +-- src/proc/interface.rs | 3 --- src/proc/mod.rs | 1 + src/proc/typifier.rs | 34 +++++++++++++++++----------------- 8 files changed, 28 insertions(+), 32 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 66a7cba62..dd46411a7 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1488,6 +1488,7 @@ impl<'a, W: Write> Writer<'a, W> { Mf::SmoothStep => "smoothstep", Mf::Sqrt => "sqrt", Mf::InverseSqrt => "inversesqrt", + Mf::Transpose => "transpose", Mf::Determinant => "determinant", // bits Mf::CountOneBits => "bitCount", @@ -1506,12 +1507,6 @@ impl<'a, W: Write> Writer<'a, W> { } write!(self.out, ")")? } - // `Transpose` is a call to the glsl function `transpose` - Expression::Transpose(matrix) => { - write!(self.out, "transpose(")?; - self.write_expr(matrix, ctx)?; - write!(self.out, ")")? - } // `As` is always a call. // If `convert` is true the function name is the type // Else the function name is one of the glsl provided bitcast functions diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 16f323f3e..c2b66fe62 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -442,6 +442,7 @@ impl Writer { Mf::SmoothStep => "smoothstep", Mf::Sqrt => "sqrt", Mf::InverseSqrt => "rsqrt", + Mf::Transpose => "transpose", Mf::Determinant => "determinant", // bits Mf::CountOneBits => "popcount", @@ -460,9 +461,6 @@ impl Writer { } write!(self.out, ")")?; } - crate::Expression::Transpose(expr) => { - self.put_call("transpose", &[expr], context)?; - } crate::Expression::As { expr, kind, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index ceaf00e27..4328b635d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -834,7 +834,12 @@ impl> Parser { let result_id = self.next()?; let matrix_id = self.next()?; let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; - let expr = crate::Expression::Transpose(matrix_lexp.handle); + let expr = crate::Expression::Math { + fun: crate::MathFunction::Transpose, + arg: matrix_lexp.handle, + arg1: None, + arg2: None, + }; self.lookup_expression.insert( result_id, LookupExpression { diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 8beada188..d10a3afcd 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -171,6 +171,7 @@ pub fn map_standard_fun(word: &str) -> Option { "smoothStep" => Mf::SmoothStep, "sqrt" => Mf::Sqrt, "inverseSqrt" => Mf::InverseSqrt, + "transpose" => Mf::Transpose, "determinant" => Mf::Determinant, // bits "countOneBits" => Mf::CountOneBits, diff --git a/src/lib.rs b/src/lib.rs index 74b5cfd9e..262fd0264 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -597,6 +597,7 @@ pub enum MathFunction { SmoothStep, Sqrt, InverseSqrt, + Transpose, Determinant, // bits CountOneBits, @@ -704,8 +705,6 @@ pub enum Expression { arg1: Option>, arg2: Option>, }, - /// Transpose of a matrix. - Transpose(Handle), /// Cast a simply type to another kind. As { /// Source expression, which can only be a scalar or a vector. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index db6073b0b..6c000cc3c 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -118,9 +118,6 @@ where self.traverse_expr(arg); } } - E::Transpose(matrix) => { - self.traverse_expr(matrix); - } E::As { expr, .. } => { self.traverse_expr(expr); } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 23ff41373..74f814a07 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -119,6 +119,7 @@ impl crate::MathFunction { Self::SmoothStep => 3, Self::Sqrt => 1, Self::InverseSqrt => 1, + Self::Transpose => 1, Self::Determinant => 1, // bits Self::CountOneBits => 1, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 07eb1274f..c8ee18b1d 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -348,6 +348,23 @@ impl Typifier { Mf::SmoothStep | Mf::Sqrt | Mf::InverseSqrt => self.resolutions[arg.index()].clone(), + Mf::Transpose => match *self.get(arg, types) { + crate::TypeInner::Matrix { + columns, + rows, + width, + } => Resolution::Value(crate::TypeInner::Matrix { + columns: rows, + rows: columns, + width, + }), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "transpose".to_string(), + operand: format!("{:?}", other), + }) + } + }, Mf::Determinant => match *self.get(arg, types) { crate::TypeInner::Matrix { width, @@ -365,23 +382,6 @@ impl Typifier { Mf::ReverseBits => self.resolutions[arg.index()].clone(), } } - crate::Expression::Transpose(expr) => match *self.get(expr, types) { - crate::TypeInner::Matrix { - columns, - rows, - width, - } => Resolution::Value(crate::TypeInner::Matrix { - columns: rows, - rows: columns, - width, - }), - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "transpose".to_string(), - operand: format!("{:?}", other), - }) - } - }, crate::Expression::As { expr, kind, From a6240b498874beb31f06d80a22712aa6f3bed95f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 18:10:48 -0500 Subject: [PATCH 0333/2212] [spv] support transpose and access index on matrices --- src/back/spv/writer.rs | 137 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 126 insertions(+), 11 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f688c4481..b8d8c4674 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -67,6 +67,11 @@ enum LocalType { kind: crate::ScalarKind, width: crate::Bytes, }, + Matrix { + columns: crate::VectorSize, + rows: crate::VectorSize, + width: crate::Bytes, + }, Pointer { base: crate::Handle, class: crate::StorageClass, @@ -201,6 +206,10 @@ impl Writer { LookupType::Handle(handle) => match arena[handle].inner { crate::TypeInner::Scalar { kind, width } => self .get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width })), + crate::TypeInner::Vector { size, kind, width } => self.get_type_id( + arena, + LookupType::Local(LocalType::Vector { size, kind, width }), + ), _ => self.write_type_declaration_arena(arena, handle), }, LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty), @@ -491,6 +500,21 @@ impl Writer { self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width }))?; super::instructions::instruction_type_vector(id, scalar_id, size) } + LocalType::Matrix { + columns, + rows, + width, + } => { + let vector_id = self.get_type_id( + arena, + LookupType::Local(LocalType::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }), + )?; + super::instructions::instruction_type_matrix(id, vector_id, columns) + } LocalType::Pointer { .. } => { return Err(Error::FeatureNotImplemented("pointer declaration")) } @@ -530,7 +554,7 @@ impl Writer { } crate::TypeInner::Matrix { columns, - rows: _, + rows, width, } => { let vector_id = self.get_type_id( @@ -541,6 +565,14 @@ impl Writer { width, }), )?; + self.lookup_type.insert( + LookupType::Local(LocalType::Matrix { + columns, + rows, + width, + }), + id, + ); super::instructions::instruction_type_matrix(id, vector_id, columns) } crate::TypeInner::Image { @@ -880,10 +912,19 @@ impl Writer { LocalType::Vector { size, kind, width } => { MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }) } + LocalType::Matrix { + columns, + rows, + width, + } => MaybeOwned::Owned(crate::TypeInner::Matrix { + columns, + rows, + width, + }), LocalType::Pointer { base, class } => { MaybeOwned::Owned(crate::TypeInner::Pointer { base, class }) } - _ => unreachable!(), + LocalType::Void | LocalType::SampledImage { .. } => unreachable!(), }, } } @@ -961,15 +1002,34 @@ impl Writer { let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); let (pointer_id, type_id, lookup_ty) = match *base_ty_inner { - crate::TypeInner::Vector { kind, width, .. } => { - let scalar_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Scalar { kind, width }), - )?; + crate::TypeInner::Vector { + size: _, + kind, + width, + } => { + let lookup_type = LookupType::Local(LocalType::Scalar { kind, width }); + let scalar_id = self.get_type_id(&ir_module.types, lookup_type)?; ( self.create_pointer(scalar_id, spirv::StorageClass::Function), scalar_id, - LookupType::Local(LocalType::Scalar { kind, width }), + lookup_type, + ) + } + crate::TypeInner::Matrix { + columns: _, + rows, + width, + } => { + let lookup_type = LookupType::Local(LocalType::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }); + let vector_id = self.get_type_id(&ir_module.types, lookup_type)?; + ( + self.create_pointer(vector_id, spirv::StorageClass::Function), + vector_id, + lookup_type, ) } crate::TypeInner::Struct { @@ -1252,9 +1312,64 @@ impl Writer { )); Ok((id, result_lookup_ty)) } - crate::Expression::Math { fun, .. } => { - log::error!("unimplemented math function {:?}", fun); - Err(Error::FeatureNotImplemented("math function")) + crate::Expression::Math { fun, arg, .. } => { + use crate::MathFunction as Mf; + + let arg0_expression = &ir_function.expressions[arg]; + let (arg0_id, arg0_lookup_ty) = self.write_expression( + ir_module, + ir_function, + arg0_expression, + block, + function, + )?; + let arg0_id = match *arg0_expression { + crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { + let load_id = self.generate_id(); + let arg_result_id = self.get_type_id(&ir_module.types, arg0_lookup_ty)?; + block.body.push(super::instructions::instruction_load( + arg_result_id, + load_id, + arg0_id, + None, + )); + load_id + } + _ => arg0_id, + }; + + let id = self.generate_id(); + match fun { + Mf::Transpose => { + let result_lookup_ty = + match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { + crate::TypeInner::Matrix { + columns, + rows, + width, + } => LookupType::Local(LocalType::Matrix { + columns: rows, + rows: columns, + width, + }), + _ => unreachable!(), + }; + let result_type_id = + self.get_type_id(&ir_module.types, result_lookup_ty)?; + + block.body.push(super::instructions::instruction_unary( + spirv::Op::Transpose, + result_type_id, + id, + arg0_id, + )); + Ok((id, result_lookup_ty)) + } + _ => { + log::error!("unimplemented math function {:?}", fun); + Err(Error::FeatureNotImplemented("math function")) + } + } } crate::Expression::LocalVariable(variable) => { let var = &ir_function.local_variables[variable]; From 2781705bef2281795ae1fb8b6b970ae0291fe85d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 19:24:01 -0500 Subject: [PATCH 0334/2212] [spv] enforce the load/store semantics consistently --- src/back/spv/instructions.rs | 4 +- src/back/spv/writer.rs | 537 ++++++++++++----------------------- 2 files changed, 176 insertions(+), 365 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 064bfa001..7df29ec7f 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -375,13 +375,13 @@ pub(super) fn instruction_variable( pub(super) fn instruction_load( result_type_id: Word, id: Word, - pointer_type_id: Word, + pointer_id: Word, memory_access: Option, ) -> Instruction { let mut instruction = Instruction::new(Op::Load); instruction.set_type(result_type_id); instruction.set_result(id); - instruction.add_operand(pointer_type_id); + instruction.add_operand(pointer_id); if let Some(memory_access) = memory_access { instruction.add_operand(memory_access.bits()); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b8d8c4674..e14b773c7 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -26,6 +26,11 @@ struct LocalVariable { instruction: Instruction, } +enum RawExpression { + Value(Word), + Pointer(Word), +} + #[derive(Default)] struct Function { signature: Option, @@ -87,6 +92,12 @@ enum LookupType { Local(LocalType), } +impl From for LookupType { + fn from(local: LocalType) -> Self { + Self::Local(local) + } +} + fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { match dim { crate::ImageDimension::D1 => spirv::Dim::Dim1D, @@ -272,40 +283,48 @@ impl Writer { handle: crate::Handle, class: crate::StorageClass, ) -> Result { - let ty = &arena[handle]; let ty_id = self.get_type_id(arena, LookupType::Handle(handle))?; - Ok(match ty.inner { - crate::TypeInner::Pointer { .. } => ty_id, - _ => { - match self - .lookup_type - .entry(LookupType::Local(LocalType::Pointer { - base: handle, - class, - })) { - Entry::Occupied(e) => *e.get(), - _ => { - let id = - self.create_pointer(ty_id, self.parse_to_spirv_storage_class(class)); - self.lookup_type.insert( - LookupType::Local(LocalType::Pointer { - base: handle, - class, - }), - id, - ); - id - } + if let crate::TypeInner::Pointer { .. } = arena[handle].inner { + return Ok(ty_id); + } + Ok( + match self + .lookup_type + .entry(LookupType::Local(LocalType::Pointer { + base: handle, + class, + })) { + Entry::Occupied(e) => *e.get(), + _ => { + let storage_class = self.parse_to_spirv_storage_class(class); + let id = self.generate_id(); + let instruction = + super::instructions::instruction_type_pointer(id, storage_class, ty_id); + instruction.to_words(&mut self.logical_layout.declarations); + self.lookup_type.insert( + LookupType::Local(LocalType::Pointer { + base: handle, + class, + }), + id, + ); + id } - } - }) + }, + ) } - fn create_pointer(&mut self, ty_id: Word, class: spirv::StorageClass) -> Word { + fn create_pointer_type( + &mut self, + lookup_type: LookupType, + class: spirv::StorageClass, + type_arena: &crate::Arena, + ) -> Result<(Word, LookupType), Error> { + let type_id = self.get_type_id(type_arena, lookup_type)?; let id = self.generate_id(); - let instruction = super::instructions::instruction_type_pointer(id, class, ty_id); + let instruction = super::instructions::instruction_type_pointer(id, class, type_id); instruction.to_words(&mut self.logical_layout.declarations); - id + Ok((id, lookup_type)) } fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word { @@ -329,10 +348,10 @@ impl Writer { .init .map(|constant| self.get_constant_id(constant, ir_module)) .transpose()?; - let pointer_id = + let pointer_type_id = self.get_pointer_id(&ir_module.types, variable.ty, crate::StorageClass::Function)?; let instruction = super::instructions::instruction_variable( - pointer_id, + pointer_type_id, id, spirv::StorageClass::Function, init_word, @@ -350,17 +369,18 @@ impl Writer { for argument in ir_function.arguments.iter() { let id = self.generate_id(); - let pointer_id = + let pointer_type_id = self.get_pointer_id(&ir_module.types, argument.ty, crate::StorageClass::Function)?; - function_parameter_pointer_ids.push(pointer_id); + function_parameter_pointer_ids.push(pointer_type_id); let parameter_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(argument.ty))?; parameter_type_ids.push(parameter_type_id); function .parameters .push(super::instructions::instruction_function_parameter( - pointer_id, id, + pointer_type_id, + id, )); } @@ -768,10 +788,10 @@ impl Writer { .init .map(|constant| self.get_constant_id(constant, ir_module)) .transpose()?; - let pointer_id = + let pointer_type_id = self.get_pointer_id(&ir_module.types, global_variable.ty, global_variable.class)?; let instruction = - super::instructions::instruction_variable(pointer_id, id, class, init_word); + super::instructions::instruction_variable(pointer_type_id, id, class, init_word); if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = global_variable.name { @@ -799,7 +819,7 @@ impl Writer { } } - match *global_variable.binding.as_ref().unwrap() { + match global_variable.binding.clone().unwrap() { crate::Binding::Location(location) => { self.annotations .push(super::instructions::instruction_decorate( @@ -929,47 +949,75 @@ impl Writer { } } + /// Write an expression and return a value ID. fn write_expression<'a>( &mut self, ir_module: &'a crate::Module, ir_function: &crate::Function, - expression: &crate::Expression, + handle: crate::Handle, block: &mut Block, function: &mut Function, ) -> Result { - match *expression { + let (raw_expression, lookup_ty) = + self.write_expression_raw(ir_module, ir_function, handle, block, function)?; + Ok(match raw_expression { + RawExpression::Value(id) => (id, lookup_ty), + RawExpression::Pointer(id) => { + let load_id = self.generate_id(); + let type_id = self.get_type_id(&ir_module.types, lookup_ty)?; + block.body.push(super::instructions::instruction_load( + type_id, load_id, id, None, + )); + (load_id, lookup_ty) + } + }) + } + + /// Write an expression and return a pointer ID to the result. + fn write_expression_pointer<'a>( + &mut self, + ir_module: &'a crate::Module, + ir_function: &crate::Function, + handle: crate::Handle, + block: &mut Block, + function: &mut Function, + ) -> Result { + let (raw_expression, lookup_ty) = + self.write_expression_raw(ir_module, ir_function, handle, block, function)?; + Ok(match raw_expression { + RawExpression::Value(_id) => { + //TODO: create a local variable? + return Err(Error::FeatureNotImplemented("getting pointer of a value")); + } + RawExpression::Pointer(id) => (id, lookup_ty), + }) + } + + /// Write an expression, and the result may be either a pointer, or a value. + fn write_expression_raw<'a>( + &mut self, + ir_module: &'a crate::Module, + ir_function: &crate::Function, + expr_handle: crate::Handle, + block: &mut Block, + function: &mut Function, + ) -> Result<(RawExpression, LookupType), Error> { + match ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { let id = self.generate_id(); - let (base_id, base_lookup_ty) = self.write_expression( - ir_module, - ir_function, - &ir_function.expressions[base], - block, - function, - )?; - let (index_id, _) = self.write_expression( - ir_module, - ir_function, - &ir_function.expressions[index], - block, - function, - )?; + let (base_id, base_lookup_ty) = + self.write_expression_pointer(ir_module, ir_function, base, block, function)?; + let (index_id, _) = + self.write_expression(ir_module, ir_function, index, block, function)?; let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); - - let (pointer_id, type_id, lookup_ty) = match *base_ty_inner { - crate::TypeInner::Vector { kind, width, .. } => { - let scalar_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Scalar { kind, width }), - )?; - ( - self.create_pointer(scalar_id, spirv::StorageClass::Function), - scalar_id, - LookupType::Local(LocalType::Scalar { kind, width }), - ) - } + let (pointer_id, lookup_ty) = match *base_ty_inner { + crate::TypeInner::Vector { kind, width, .. } => self.create_pointer_type( + LocalType::Scalar { kind, width }.into(), + spirv::StorageClass::Function, + &ir_module.types, + )?, _ => return Err(Error::FeatureNotImplemented("accessing of non-vector")), }; @@ -982,68 +1030,50 @@ impl Writer { &[index_id], )); - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - type_id, load_id, id, None, - )); - - Ok((load_id, lookup_ty)) + Ok((RawExpression::Pointer(id), lookup_ty)) } crate::Expression::AccessIndex { base, index } => { let id = self.generate_id(); - let (base_id, base_lookup_ty) = self.write_expression( - ir_module, - ir_function, - &ir_function.expressions[base], - block, - function, - )?; + let (base_id, base_lookup_ty) = + self.write_expression_pointer(ir_module, ir_function, base, block, function)?; let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); - - let (pointer_id, type_id, lookup_ty) = match *base_ty_inner { + let (pointer_id, lookup_ty) = match *base_ty_inner { crate::TypeInner::Vector { size: _, kind, width, - } => { - let lookup_type = LookupType::Local(LocalType::Scalar { kind, width }); - let scalar_id = self.get_type_id(&ir_module.types, lookup_type)?; - ( - self.create_pointer(scalar_id, spirv::StorageClass::Function), - scalar_id, - lookup_type, - ) - } + } => self.create_pointer_type( + LocalType::Scalar { kind, width }.into(), + spirv::StorageClass::Function, + &ir_module.types, + )?, crate::TypeInner::Matrix { columns: _, rows, width, } => { - let lookup_type = LookupType::Local(LocalType::Vector { + let local_type = LocalType::Vector { size: rows, kind: crate::ScalarKind::Float, width, - }); - let vector_id = self.get_type_id(&ir_module.types, lookup_type)?; - ( - self.create_pointer(vector_id, spirv::StorageClass::Function), - vector_id, - lookup_type, - ) + }; + self.create_pointer_type( + local_type.into(), + spirv::StorageClass::Function, + &ir_module.types, + )? } crate::TypeInner::Struct { block: _, ref members, } => { let member = &members[index as usize]; - let type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(member.ty))?; - ( - self.create_pointer(type_id, spirv::StorageClass::Uniform), - type_id, + self.create_pointer_type( LookupType::Handle(member.ty), - ) + spirv::StorageClass::Uniform, + &ir_module.types, + )? } _ => { return Err(Error::FeatureNotImplemented( @@ -1070,53 +1100,31 @@ impl Writer { &[const_id], )); - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - type_id, load_id, id, None, - )); - - Ok((load_id, lookup_ty)) + Ok((RawExpression::Pointer(id), lookup_ty)) } crate::Expression::GlobalVariable(handle) => { let var = &ir_module.global_variables[handle]; let id = self.get_global_variable_id(&ir_module, handle)?; - Ok((id, LookupType::Handle(var.ty))) + Ok((RawExpression::Pointer(id), LookupType::Handle(var.ty))) } crate::Expression::Constant(handle) => { let var = &ir_module.constants[handle]; let id = self.get_constant_id(handle, ir_module)?; - Ok((id, LookupType::Handle(var.ty))) + Ok((RawExpression::Value(id), LookupType::Handle(var.ty))) } crate::Expression::Compose { ty, ref components } => { let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty))?; let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { - let expression = &ir_function.expressions[*component]; - let (component_id, component_local_ty) = self.write_expression( + let (component_id, _) = self.write_expression( ir_module, &ir_function, - expression, + *component, block, function, )?; - - let component_id = match expression { - crate::Expression::LocalVariable(_) - | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - self.get_type_id(&ir_module.types, component_local_ty)?, - load_id, - component_id, - None, - )); - load_id - } - _ => component_id, - }; - constituent_ids.push(component_id); } let constituent_ids_slice = constituent_ids.as_slice(); @@ -1161,26 +1169,14 @@ impl Writer { _ => unreachable!(), }; - Ok((id, LookupType::Handle(ty))) + Ok((RawExpression::Value(id), LookupType::Handle(ty))) } crate::Expression::Binary { op, left, right } => { let id = self.generate_id(); - let left_expression = &ir_function.expressions[left]; - let right_expression = &ir_function.expressions[right]; - let (left_id, left_lookup_ty) = self.write_expression( - ir_module, - ir_function, - left_expression, - block, - function, - )?; - let (right_id, right_lookup_ty) = self.write_expression( - ir_module, - ir_function, - right_expression, - block, - function, - )?; + let (left_id, left_lookup_ty) = + self.write_expression(ir_module, ir_function, left, block, function)?; + let (right_id, right_lookup_ty) = + self.write_expression(ir_module, ir_function, right, block, function)?; let left_ty_inner = self.get_type_inner(&ir_module.types, left_lookup_ty); let right_ty_inner = self.get_type_inner(&ir_module.types, right_lookup_ty); @@ -1188,35 +1184,6 @@ impl Writer { let left_result_type_id = self.get_type_id(&ir_module.types, left_lookup_ty)?; let right_result_type_id = self.get_type_id(&ir_module.types, right_lookup_ty)?; - let left_id = match *left_expression { - crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - left_result_type_id, - load_id, - left_id, - None, - )); - load_id - } - _ => left_id, - }; - - let right_id = match *right_expression { - crate::Expression::LocalVariable(..) - | crate::Expression::GlobalVariable(..) => { - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - right_result_type_id, - load_id, - right_id, - None, - )); - load_id - } - _ => right_id, - }; - let left_dimension = get_dimension(&left_ty_inner); let right_dimension = get_dimension(&right_ty_inner); @@ -1310,33 +1277,13 @@ impl Writer { if preserve_order { left_id } else { right_id }, if preserve_order { right_id } else { left_id }, )); - Ok((id, result_lookup_ty)) + Ok((RawExpression::Value(id), result_lookup_ty)) } crate::Expression::Math { fun, arg, .. } => { use crate::MathFunction as Mf; - let arg0_expression = &ir_function.expressions[arg]; - let (arg0_id, arg0_lookup_ty) = self.write_expression( - ir_module, - ir_function, - arg0_expression, - block, - function, - )?; - let arg0_id = match *arg0_expression { - crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - let arg_result_id = self.get_type_id(&ir_module.types, arg0_lookup_ty)?; - block.body.push(super::instructions::instruction_load( - arg_result_id, - load_id, - arg0_id, - None, - )); - load_id - } - _ => arg0_id, - }; + let (arg0_id, arg0_lookup_ty) = + self.write_expression(ir_module, ir_function, arg, block, function)?; let id = self.generate_id(); match fun { @@ -1363,7 +1310,7 @@ impl Writer { id, arg0_id, )); - Ok((id, result_lookup_ty)) + Ok((RawExpression::Value(id), result_lookup_ty)) } _ => { log::error!("unimplemented math function {:?}", fun); @@ -1374,20 +1321,15 @@ impl Writer { crate::Expression::LocalVariable(variable) => { let var = &ir_function.local_variables[variable]; let local_var = &function.variables[&variable]; - Ok((local_var.id, LookupType::Handle(var.ty))) + Ok(( + RawExpression::Pointer(local_var.id), + LookupType::Handle(var.ty), + )) } crate::Expression::FunctionArgument(index) => { let handle = ir_function.arguments[index as usize].ty; - let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(handle))?; - let load_id = self.generate_id(); - - block.body.push(super::instructions::instruction_load( - type_id, - load_id, - function.parameters[index as usize].result_id.unwrap(), - None, - )); - Ok((load_id, LookupType::Handle(handle))) + let id = function.parameters[index as usize].result_id.unwrap(); + Ok((RawExpression::Pointer(id), LookupType::Handle(handle))) } crate::Expression::Call { function: local_function, @@ -1398,9 +1340,8 @@ impl Writer { let mut argument_ids = vec![]; for argument in arguments { - let expression = &ir_function.expressions[*argument]; let (arg_id, _) = - self.write_expression(ir_module, ir_function, expression, block, function)?; + self.write_expression(ir_module, ir_function, *argument, block, function)?; argument_ids.push(arg_id); } @@ -1420,7 +1361,7 @@ impl Writer { Some(ty_handle) => LookupType::Handle(ty_handle), None => LookupType::Local(LocalType::Void), }; - Ok((id, result_type)) + Ok((RawExpression::Value(id), result_type)) } crate::Expression::As { expr, @@ -1431,13 +1372,8 @@ impl Writer { return Err(Error::FeatureNotImplemented("bitcast")); } - let (expr_id, expr_type) = self.write_expression( - ir_module, - ir_function, - &ir_function.expressions[expr], - block, - function, - )?; + let (expr_id, expr_type) = + self.write_expression(ir_module, ir_function, expr, block, function)?; let expr_type_inner = self.get_type_inner(&ir_module.types, expr_type); @@ -1463,24 +1399,7 @@ impl Writer { (crate::ScalarKind::Uint, crate::ScalarKind::Float) => spirv::Op::ConvertUToF, // We assume it's either an identity cast, or int-uint. // In both cases no SPIR-V instructions need to be generated. - _ => { - let id = match ir_function.expressions[expr] { - crate::Expression::LocalVariable(_) - | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - let kind_type_id = self.get_type_id(&ir_module.types, expr_type)?; - block.body.push(super::instructions::instruction_load( - kind_type_id, - load_id, - expr_id, - None, - )); - load_id - } - _ => expr_id, - }; - return Ok((id, lookup_type)); - } + _ => return Ok((RawExpression::Value(expr_id), lookup_type)), }; let id = self.generate_id(); @@ -1489,7 +1408,7 @@ impl Writer { super::instructions::instruction_unary(op, kind_type_id, id, expr_id); block.body.push(instruction); - Ok((id, lookup_type)) + Ok((RawExpression::Value(id), lookup_type)) } crate::Expression::ImageSample { image, @@ -1501,29 +1420,8 @@ impl Writer { depth_ref: _, } => { // image - let image_expression = &ir_function.expressions[image]; - let (image_id, image_lookup_ty) = self.write_expression( - ir_module, - ir_function, - image_expression, - block, - function, - )?; - - let image_result_type_id = self.get_type_id(&ir_module.types, image_lookup_ty)?; - let image_id = match *image_expression { - crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - image_result_type_id, - load_id, - image_id, - None, - )); - load_id - } - _ => image_id, - }; + let (image_id, image_lookup_ty) = + self.write_expression(ir_module, ir_function, image, block, function)?; let image_ty = match image_lookup_ty { LookupType::Handle(handle) => handle, @@ -1539,56 +1437,12 @@ impl Writer { )?; // sampler - let sampler_expression = &ir_function.expressions[sampler]; - let (sampler_id, sampler_lookup_ty) = self.write_expression( - ir_module, - ir_function, - sampler_expression, - block, - function, - )?; - - let sampler_result_type_id = - self.get_type_id(&ir_module.types, sampler_lookup_ty)?; - let sampler_id = match *sampler_expression { - crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - sampler_result_type_id, - load_id, - sampler_id, - None, - )); - load_id - } - _ => sampler_id, - }; + let (sampler_id, _) = + self.write_expression(ir_module, ir_function, sampler, block, function)?; // coordinate - let coordinate_expression = &ir_function.expressions[coordinate]; - let (coordinate_id, coordinate_lookup_ty) = self.write_expression( - ir_module, - ir_function, - coordinate_expression, - block, - function, - )?; - - let coordinate_result_type_id = - self.get_type_id(&ir_module.types, coordinate_lookup_ty)?; - let coordinate_id = match *coordinate_expression { - crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - coordinate_result_type_id, - load_id, - coordinate_id, - None, - )); - load_id - } - _ => coordinate_id, - }; + let (coordinate_id, _) = + self.write_expression(ir_module, ir_function, coordinate, block, function)?; // component kind let image_type = &ir_module.types[image_ty]; @@ -1639,10 +1493,10 @@ impl Writer { }; block.body.push(main_instruction); - Ok((id, image_sample_result_type)) + Ok((RawExpression::Value(id), image_sample_result_type)) } - _ => { - log::error!("unimplemented {:?}", expression); + ref other => { + log::error!("unimplemented {:?}", other); Err(Error::FeatureNotImplemented("expression")) } } @@ -1670,71 +1524,28 @@ impl Writer { crate::Statement::Return { value } => { block.termination = Some(match ir_function.return_type { Some(_) => { - let expression = &ir_function.expressions[value.unwrap()]; - let (id, lookup_ty) = self.write_expression( + let (id, _) = self.write_expression( ir_module, ir_function, - expression, + value.unwrap(), &mut block, function, )?; - - let id = match *expression { - crate::Expression::LocalVariable(_) - | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - let value_ty_id = - self.get_type_id(&ir_module.types, lookup_ty)?; - block.body.push(super::instructions::instruction_load( - value_ty_id, - load_id, - id, - None, - )); - load_id - } - - _ => id, - }; super::instructions::instruction_return_value(id) } None => super::instructions::instruction_return(), }); } crate::Statement::Store { pointer, value } => { - let pointer_expression = &ir_function.expressions[pointer]; - let value_expression = &ir_function.expressions[value]; - let (pointer_id, _) = self.write_expression( + let (pointer_id, _) = self.write_expression_pointer( ir_module, ir_function, - pointer_expression, + pointer, &mut block, function, )?; - let (value_id, value_lookup_ty) = self.write_expression( - ir_module, - ir_function, - value_expression, - &mut block, - function, - )?; - - let value_id = match value_expression { - crate::Expression::LocalVariable(_) - | crate::Expression::GlobalVariable(_) => { - let load_id = self.generate_id(); - let value_ty_id = - self.get_type_id(&ir_module.types, value_lookup_ty)?; - block.body.push(super::instructions::instruction_load( - value_ty_id, - load_id, - value_id, - None, - )); - load_id - } - _ => value_id, - }; + let (value_id, _) = + self.write_expression(ir_module, ir_function, value, &mut block, function)?; block.body.push(super::instructions::instruction_store( pointer_id, value_id, None, From 96dcf8bd055b6e85738928d722d15c829f8dabc6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 19:52:45 -0500 Subject: [PATCH 0335/2212] [spv] make the storage classes consistent across the expressions --- src/back/spv/writer.rs | 72 +++++++++++++++++++++++------------------- 1 file changed, 39 insertions(+), 33 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e14b773c7..f64a281bd 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -28,7 +28,7 @@ struct LocalVariable { enum RawExpression { Value(Word), - Pointer(Word), + Pointer(Word, spirv::StorageClass), } #[derive(Default)] @@ -157,12 +157,14 @@ pub struct Writer { lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, lookup_constant: crate::FastHashMap, Word>, - lookup_global_variable: crate::FastHashMap, Word>, + lookup_global_variable: + crate::FastHashMap, (Word, spirv::StorageClass)>, storage_type_handles: crate::FastHashSet>, } // type alias, for success return of write_expression type WriteExpressionOutput = (Word, LookupType); +type WritePointerExpressionOutput = (Word, LookupType, spirv::StorageClass); impl Writer { pub fn new( @@ -246,13 +248,14 @@ impl Writer { &mut self, ir_module: &crate::Module, handle: crate::Handle, - ) -> Result { + ) -> Result<(Word, spirv::StorageClass), Error> { Ok(match self.lookup_global_variable.entry(handle) { Entry::Occupied(e) => *e.get(), + //Note: this intentionally frees `self` from borrowing Entry::Vacant(_) => { - let (instruction, id) = self.write_global_variable(ir_module, handle)?; + let (instruction, id, class) = self.write_global_variable(ir_module, handle)?; instruction.to_words(&mut self.logical_layout.declarations); - id + (id, class) } }) } @@ -429,7 +432,7 @@ impl Writer { _ => false, }; if is_io { - let id = self.get_global_variable_id(ir_module, handle)?; + let (id, _) = self.get_global_variable_id(ir_module, handle)?; interface_ids.push(id); } } @@ -777,7 +780,7 @@ impl Writer { &mut self, ir_module: &crate::Module, handle: crate::Handle, - ) -> Result<(Instruction, Word), Error> { + ) -> Result<(Instruction, Word, spirv::StorageClass), Error> { let global_variable = &ir_module.global_variables[handle]; let id = self.generate_id(); @@ -873,8 +876,8 @@ impl Writer { // TODO Initializer is optional and not (yet) included in the IR - self.lookup_global_variable.insert(handle, id); - Ok((instruction, id)) + self.lookup_global_variable.insert(handle, (id, class)); + Ok((instruction, id, class)) } fn get_function_type( @@ -962,7 +965,7 @@ impl Writer { self.write_expression_raw(ir_module, ir_function, handle, block, function)?; Ok(match raw_expression { RawExpression::Value(id) => (id, lookup_ty), - RawExpression::Pointer(id) => { + RawExpression::Pointer(id, _) => { let load_id = self.generate_id(); let type_id = self.get_type_id(&ir_module.types, lookup_ty)?; block.body.push(super::instructions::instruction_load( @@ -981,15 +984,16 @@ impl Writer { handle: crate::Handle, block: &mut Block, function: &mut Function, - ) -> Result { + ) -> Result { let (raw_expression, lookup_ty) = self.write_expression_raw(ir_module, ir_function, handle, block, function)?; Ok(match raw_expression { RawExpression::Value(_id) => { //TODO: create a local variable? + log::error!("Pointer expression {:?}", ir_function.expressions[handle]); return Err(Error::FeatureNotImplemented("getting pointer of a value")); } - RawExpression::Pointer(id) => (id, lookup_ty), + RawExpression::Pointer(id, class) => (id, lookup_ty, class), }) } @@ -1006,16 +1010,16 @@ impl Writer { crate::Expression::Access { base, index } => { let id = self.generate_id(); - let (base_id, base_lookup_ty) = + let (base_id, base_lookup_ty, class) = self.write_expression_pointer(ir_module, ir_function, base, block, function)?; let (index_id, _) = self.write_expression(ir_module, ir_function, index, block, function)?; let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); - let (pointer_id, lookup_ty) = match *base_ty_inner { + let (pointer_type_id, lookup_ty) = match *base_ty_inner { crate::TypeInner::Vector { kind, width, .. } => self.create_pointer_type( LocalType::Scalar { kind, width }.into(), - spirv::StorageClass::Function, + class, &ir_module.types, )?, _ => return Err(Error::FeatureNotImplemented("accessing of non-vector")), @@ -1024,28 +1028,28 @@ impl Writer { block .body .push(super::instructions::instruction_access_chain( - pointer_id, + pointer_type_id, id, base_id, &[index_id], )); - Ok((RawExpression::Pointer(id), lookup_ty)) + Ok((RawExpression::Pointer(id, class), lookup_ty)) } crate::Expression::AccessIndex { base, index } => { let id = self.generate_id(); - let (base_id, base_lookup_ty) = + let (base_id, base_lookup_ty, class) = self.write_expression_pointer(ir_module, ir_function, base, block, function)?; let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); - let (pointer_id, lookup_ty) = match *base_ty_inner { + let (pointer_type_id, lookup_ty) = match *base_ty_inner { crate::TypeInner::Vector { size: _, kind, width, } => self.create_pointer_type( LocalType::Scalar { kind, width }.into(), - spirv::StorageClass::Function, + class, &ir_module.types, )?, crate::TypeInner::Matrix { @@ -1058,11 +1062,7 @@ impl Writer { kind: crate::ScalarKind::Float, width, }; - self.create_pointer_type( - local_type.into(), - spirv::StorageClass::Function, - &ir_module.types, - )? + self.create_pointer_type(local_type.into(), class, &ir_module.types)? } crate::TypeInner::Struct { block: _, @@ -1071,7 +1071,7 @@ impl Writer { let member = &members[index as usize]; self.create_pointer_type( LookupType::Handle(member.ty), - spirv::StorageClass::Uniform, + class, &ir_module.types, )? } @@ -1094,19 +1094,22 @@ impl Writer { block .body .push(super::instructions::instruction_access_chain( - pointer_id, + pointer_type_id, id, base_id, &[const_id], )); - Ok((RawExpression::Pointer(id), lookup_ty)) + Ok((RawExpression::Pointer(id, class), lookup_ty)) } crate::Expression::GlobalVariable(handle) => { let var = &ir_module.global_variables[handle]; - let id = self.get_global_variable_id(&ir_module, handle)?; + let (id, class) = self.get_global_variable_id(&ir_module, handle)?; - Ok((RawExpression::Pointer(id), LookupType::Handle(var.ty))) + Ok(( + RawExpression::Pointer(id, class), + LookupType::Handle(var.ty), + )) } crate::Expression::Constant(handle) => { let var = &ir_module.constants[handle]; @@ -1322,14 +1325,17 @@ impl Writer { let var = &ir_function.local_variables[variable]; let local_var = &function.variables[&variable]; Ok(( - RawExpression::Pointer(local_var.id), + RawExpression::Pointer(local_var.id, spirv::StorageClass::Function), LookupType::Handle(var.ty), )) } crate::Expression::FunctionArgument(index) => { let handle = ir_function.arguments[index as usize].ty; let id = function.parameters[index as usize].result_id.unwrap(); - Ok((RawExpression::Pointer(id), LookupType::Handle(handle))) + Ok(( + RawExpression::Pointer(id, spirv::StorageClass::Function), + LookupType::Handle(handle), + )) } crate::Expression::Call { function: local_function, @@ -1537,7 +1543,7 @@ impl Writer { }); } crate::Statement::Store { pointer, value } => { - let (pointer_id, _) = self.write_expression_pointer( + let (pointer_id, _, _) = self.write_expression_pointer( ir_module, ir_function, pointer, From 933ca3863b45bad83144d1e5fe344f77ab973774 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 11 Dec 2020 20:24:53 -0500 Subject: [PATCH 0336/2212] [spv] simplify the composing expression --- src/back/spv/writer.rs | 42 +----------------------------------------- 1 file changed, 1 insertion(+), 41 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f64a281bd..d345a3b6b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1130,48 +1130,8 @@ impl Writer { )?; constituent_ids.push(component_id); } - let constituent_ids_slice = constituent_ids.as_slice(); - - let id = match ir_module.types[ty].inner { - crate::TypeInner::Vector { .. } => { - self.write_composite_construct(base_type_id, constituent_ids_slice, block) - } - crate::TypeInner::Matrix { - rows, - columns, - width, - } => { - let vector_type_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Vector { - width, - kind: crate::ScalarKind::Float, - size: columns, - }), - )?; - - let capacity = match rows { - crate::VectorSize::Bi => 2, - crate::VectorSize::Tri => 3, - crate::VectorSize::Quad => 4, - }; - - let mut vector_ids = Vec::with_capacity(capacity); - - for _ in 0..capacity { - let vector_id = self.write_composite_construct( - vector_type_id, - constituent_ids_slice, - block, - ); - vector_ids.push(vector_id); - } - - self.write_composite_construct(base_type_id, vector_ids.as_slice(), block) - } - _ => unreachable!(), - }; + let id = self.write_composite_construct(base_type_id, &constituent_ids, block); Ok((RawExpression::Value(id), LookupType::Handle(ty))) } crate::Expression::Binary { op, left, right } => { From 018dfd6d29e4ca7f19418ffd81fece79d39e3876 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 12 Dec 2020 13:01:25 -0500 Subject: [PATCH 0337/2212] [msl] fix metal namespacing, matrix construction and indexing --- src/back/msl/writer.rs | 48 +++++++++++++++++----- tests/snapshots/snapshots__boids.msl.snap | 24 +++++------ tests/snapshots/snapshots__quad.msl.snap | 12 +++--- tests/snapshots/snapshots__simple.msl.snap | 4 +- 4 files changed, 58 insertions(+), 30 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c2b66fe62..feaa01098 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -9,6 +9,8 @@ use std::{ io::Write, }; +const NAMESPACE: &str = "metal"; + struct Level(usize); impl Level { fn next(&self) -> Self { @@ -161,9 +163,12 @@ impl Writer { let name = &self.names[&NameKey::StructMember(base_ty, index)]; write!(self.out, ".{}", name)?; } - crate::TypeInner::Matrix { .. } | crate::TypeInner::Vector { .. } => { + crate::TypeInner::Vector { .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; } + crate::TypeInner::Matrix { .. } => { + write!(self.out, "[{}]", index)?; + } crate::TypeInner::Array { .. } => { write!(self.out, "[{}]", index)?; } @@ -176,17 +181,30 @@ impl Writer { crate::Expression::Compose { ty, ref components } => { let inner = &context.module.types[ty].inner; match *inner { + crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { + write!(self.out, "{}", scalar_kind_string(kind),)?; + self.put_call("", components, context)?; + } crate::TypeInner::Vector { size, kind, .. } => { write!( self.out, - "{}{}", + "{}::{}{}", + NAMESPACE, scalar_kind_string(kind), vector_size_string(size) )?; self.put_call("", components, context)?; } - crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { - write!(self.out, "{}", scalar_kind_string(kind),)?; + crate::TypeInner::Matrix { columns, rows, .. } => { + let kind = crate::ScalarKind::Float; + write!( + self.out, + "{}::{}{}x{}", + NAMESPACE, + scalar_kind_string(kind), + vector_size_string(columns), + vector_size_string(rows) + )?; self.put_call("", components, context)?; } _ => return Err(Error::UnsupportedCompose(ty)), @@ -666,7 +684,8 @@ impl Writer { crate::TypeInner::Vector { size, kind, .. } => { write!( self.out, - "typedef {}{} {}", + "typedef {}::{}{} {}", + NAMESPACE, scalar_kind_string(kind), vector_size_string(size), name @@ -675,7 +694,8 @@ impl Writer { crate::TypeInner::Matrix { columns, rows, .. } => { write!( self.out, - "typedef {}{}x{} {}", + "typedef {}::{}{}x{} {}", + NAMESPACE, scalar_kind_string(crate::ScalarKind::Float), vector_size_string(columns), vector_size_string(rows), @@ -744,7 +764,7 @@ impl Writer { crate::ImageDimension::D1 => "1d", crate::ImageDimension::D2 => "2d", crate::ImageDimension::D3 => "3d", - crate::ImageDimension::Cube => "Cube", + crate::ImageDimension::Cube => "cube", }; let (texture_str, msaa_str, kind, access) = match class { crate::ImageClass::Sampled { kind, multi } => { @@ -778,12 +798,20 @@ impl Writer { let array_str = if arrayed { "_array" } else { "" }; write!( self.out, - "typedef {}{}{}{}<{}, access::{}> {}", - texture_str, dim_str, msaa_str, array_str, base_name, access, name + "typedef {}::{}{}{}{}<{}, {}::access::{}> {}", + NAMESPACE, + texture_str, + dim_str, + msaa_str, + array_str, + base_name, + NAMESPACE, + access, + name )?; } crate::TypeInner::Sampler { comparison: _ } => { - write!(self.out, "typedef sampler {}", name)?; + write!(self.out, "typedef {}::sampler {}", NAMESPACE, name)?; } } writeln!(self.out, ";")?; diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap index 2e3efb40c..1c1b6800f 100644 --- a/tests/snapshots/snapshots__boids.msl.snap +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -5,8 +5,8 @@ expression: msl #include #include -typedef float2 type; -typedef float4 type1; +typedef metal::float2 type; +typedef metal::float4 type1; typedef float type2; struct Particle { type pos; @@ -26,7 +26,7 @@ typedef Particle type4[5]; struct Particles { type4 particles; }; -typedef uint3 type5; +typedef metal::uint3 type5; typedef int type6; struct main1Input { @@ -41,7 +41,7 @@ vertex main1Output main1( main1Input input [[stage_in]] ) { main1Output output; - output.gl_Position = float4(float2(input.a_pos.x * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) - input.a_pos.y * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)), input.a_pos.x * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) + input.a_pos.y * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y))) + input.a_particlePos, 0.0, 1.0); + output.gl_Position = metal::float4(metal::float2(input.a_pos.x * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) - input.a_pos.y * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)), input.a_pos.x * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) + input.a_pos.y * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y))) + input.a_particlePos, 0.0, 1.0); return output; } struct main2Input { @@ -53,7 +53,7 @@ fragment main2Output main2( main2Input input [[stage_in]] ) { main2Output output; - output.fragColor = float4(1.0, 1.0, 1.0, 1.0); + output.fragColor = metal::float4(1.0, 1.0, 1.0, 1.0); return output; } kernel void main3( @@ -76,9 +76,9 @@ kernel void main3( } vPos = particlesA.particles[gl_GlobalInvocationID.x].pos; vVel = particlesA.particles[gl_GlobalInvocationID.x].vel; - cMass = float2(0.0, 0.0); - cVel = float2(0.0, 0.0); - colVel = float2(0.0, 0.0); + cMass = metal::float2(0.0, 0.0); + cVel = metal::float2(0.0, 0.0); + colVel = metal::float2(0.0, 0.0); while(true) { if (i >= static_cast(5)) { break; @@ -86,8 +86,8 @@ kernel void main3( if (i == gl_GlobalInvocationID.x) { continue; } - pos1 = float2(particlesA.particles[i].pos.x, particlesA.particles[i].pos.y); - vel1 = float2(particlesA.particles[i].vel.x, particlesA.particles[i].vel.y); + pos1 = metal::float2(particlesA.particles[i].pos.x, particlesA.particles[i].pos.y); + vel1 = metal::float2(particlesA.particles[i].vel.x, particlesA.particles[i].vel.y); if (metal::distance(pos1, vPos) < params.rule1Distance) { cMass = cMass + pos1; cMassCount = cMassCount + 1; @@ -101,10 +101,10 @@ kernel void main3( } } if (cMassCount == 0) { - cMass = cMass / float2(cMassCount, cMassCount) + vPos; + cMass = cMass / metal::float2(cMassCount, cMassCount) + vPos; } if (cVelCount == 0) { - cVel = cVel / float2(cVelCount, cVelCount); + cVel = cVel / metal::float2(cVelCount, cVelCount); } vVel = vVel + cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale; vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); diff --git a/tests/snapshots/snapshots__quad.msl.snap b/tests/snapshots/snapshots__quad.msl.snap index 8fe9dfede..da25574b1 100644 --- a/tests/snapshots/snapshots__quad.msl.snap +++ b/tests/snapshots/snapshots__quad.msl.snap @@ -6,11 +6,11 @@ expression: msl #include typedef float type; -typedef float2 type1; -typedef float4 type2; -typedef texture2d type3; -typedef sampler type4; -typedef int2 type5; +typedef metal::float2 type1; +typedef metal::float4 type2; +typedef metal::texture2d type3; +typedef metal::sampler type4; +typedef metal::int2 type5; struct main1Input { type1 a_pos [[attribute(0)]]; @@ -25,7 +25,7 @@ vertex main1Output main1( ) { main1Output output; output.v_uv = input.a_uv; - output.o_position = float4(1.2 * input.a_pos, 0.0, 1.0); + output.o_position = metal::float4(1.2 * input.a_pos, 0.0, 1.0); return output; } struct main2Input { diff --git a/tests/snapshots/snapshots__simple.msl.snap b/tests/snapshots/snapshots__simple.msl.snap index 01314fdb2..0bf6130e9 100644 --- a/tests/snapshots/snapshots__simple.msl.snap +++ b/tests/snapshots/snapshots__simple.msl.snap @@ -5,7 +5,7 @@ expression: msl #include #include -typedef float4 type; +typedef metal::float4 type; typedef int type1; struct main1Input { @@ -17,7 +17,7 @@ vertex main1Output main1( main1Input input [[stage_in]] ) { main1Output output; - output.o_position = float4(1); + output.o_position = metal::float4(1); return output; } From f1ad97b049f618e747d52fabc9da448cb5ac8e23 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 13 Dec 2020 01:17:41 -0500 Subject: [PATCH 0338/2212] [glsl-out] fix type conversion --- src/back/glsl/features.rs | 2 +- src/back/glsl/mod.rs | 34 +++++++++++++++++++++------------- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 1ab952e5f..4858e7e78 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -193,7 +193,7 @@ impl<'a, W> Writer<'a, W> { match ty.inner { TypeInner::Scalar { kind, width } => self.scalar_required_features(kind, width), TypeInner::Vector { kind, width, .. } => self.scalar_required_features(kind, width), - TypeInner::Matrix { .. } => self.scalar_required_features(ScalarKind::Float, 8), + TypeInner::Matrix { width, .. } => self.scalar_required_features(ScalarKind::Float, width), TypeInner::Array { base, .. } => { if let TypeInner::Array { .. } = self.module.types[base].inner { self.features.request(Features::ARRAY_OF_ARRAYS) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index dd46411a7..a8493e70b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1515,19 +1515,27 @@ impl<'a, W: Write> Writer<'a, W> { kind, convert, } => { + let inner = ctx.typifier.get(expr, &self.module.types); if convert { - self.write_type(ctx.typifier.get_handle(expr).unwrap())?; - } else { - let source_kind = match *ctx.typifier.get(expr, &self.module.types) { - TypeInner::Scalar { - kind: source_kind, .. - } => source_kind, + // this is similar to `write_type`, but with the target kind + match *inner { + TypeInner::Scalar { kind: _, width } => { + write!(self.out, "{}", glsl_scalar(kind, width)?.full)? + } TypeInner::Vector { - kind: source_kind, .. - } => source_kind, - _ => unreachable!(), - }; - + size, + kind: _, + width, + } => write!( + self.out, + "{}vec{}", + glsl_scalar(kind, width)?.prefix, + size as u8 + )?, + ref other => unreachable!("unexpected cast of {:?}", other), + } + } else { + let source_kind = inner.scalar_kind().unwrap(); write!( self.out, "{}", @@ -1657,8 +1665,8 @@ fn glsl_built_in(built_in: BuiltIn) -> &'static str { BuiltIn::BaseInstance => "gl_BaseInstance", BuiltIn::BaseVertex => "gl_BaseVertex", BuiltIn::ClipDistance => "gl_ClipDistance", - BuiltIn::InstanceIndex => "gl_InstanceIndex", - BuiltIn::VertexIndex => "gl_VertexIndex", + BuiltIn::InstanceIndex => "gl_InstanceID", + BuiltIn::VertexIndex => "gl_VertexID", BuiltIn::PointSize => "gl_PointSize", BuiltIn::FragCoord => "gl_FragCoord", BuiltIn::FrontFacing => "gl_FrontFacing", From 899a918bf2d1c41ad2da220907ac378a56859015 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 13 Dec 2020 01:20:22 -0500 Subject: [PATCH 0339/2212] [convert] allow entry point name for GLSL output --- .gitignore | 4 ++++ examples/convert.rs | 33 +++++++++++++++------------------ 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/.gitignore b/.gitignore index 798a1af6c..bdef2e67f 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,7 @@ Cargo.lock /*.metal /*.metallib /*.ron +/*.spv +/*.vert +/*.frag +/*.comp diff --git a/examples/convert.rs b/examples/convert.rs index 23003d458..eb42f8b6f 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -196,32 +196,29 @@ fn main() { } #[cfg(feature = "glsl-out")] stage @ "vert" | stage @ "frag" | stage @ "comp" => { - use naga::{ - back::glsl::{self, Options, Version}, - ShaderStage, - }; + use naga::back::glsl; - let version = match args.get(3).map(|p| p.as_str()) { - Some("core") => { - Version::Desktop(args.get(4).and_then(|v| v.parse().ok()).unwrap_or(330)) + let version = { + let arg = args.get(3).map_or("es", |p| p.as_str()); + if arg.starts_with("core") { + glsl::Version::Desktop(arg[4..].parse().unwrap_or(330)) + } else if arg.starts_with("es") { + glsl::Version::Embedded(arg[2..].parse().unwrap_or(310)) + } else { + panic!("Unknown profile: {}", arg) } - Some("es") => { - Version::Embedded(args.get(4).and_then(|v| v.parse().ok()).unwrap_or(310)) - } - Some(_) => panic!("Unknown profile"), - _ => Version::Embedded(310), }; - - let options = Options { + let name = args.get(4).map_or("main", |p| p.as_str()).to_string(); + let options = glsl::Options { version, entry_point: ( match stage { - "vert" => ShaderStage::Vertex, - "frag" => ShaderStage::Fragment, - "comp" => ShaderStage::Compute, + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, _ => unreachable!(), }, - String::from("main"), + name, ), }; From 77657b4c76a3abb82f0836c4fa4c9b138f2f53af Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 13 Dec 2020 01:20:39 -0500 Subject: [PATCH 0340/2212] Add skybox example snapshots --- tests/snapshots.rs | 22 +- tests/snapshots/in/skybox.param.ron | 9 + tests/snapshots/in/skybox.wgsl | 43 ++++ .../snapshots__skybox-Fragment.glsl.snap | 24 ++ .../snapshots__skybox-Vertex.glsl.snap | 30 +++ tests/snapshots/snapshots__skybox.msl.snap | 60 +++++ tests/snapshots/snapshots__skybox.spvasm.snap | 218 ++++++++++++++++++ 7 files changed, 398 insertions(+), 8 deletions(-) create mode 100644 tests/snapshots/in/skybox.param.ron create mode 100644 tests/snapshots/in/skybox.wgsl create mode 100644 tests/snapshots/snapshots__skybox-Fragment.glsl.snap create mode 100644 tests/snapshots/snapshots__skybox-Vertex.glsl.snap create mode 100644 tests/snapshots/snapshots__skybox.msl.snap create mode 100644 tests/snapshots/snapshots__skybox.spvasm.snap diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 5f262708d..b9c3412f7 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -1,3 +1,11 @@ +bitflags::bitflags! { + struct Language: u32 { + const SPIRV = 0x1; + const METAL = 0x2; + const GLSL = 0x4; + } +} + #[derive(Hash, PartialEq, Eq, serde::Deserialize)] enum Stage { Vertex, @@ -39,14 +47,6 @@ struct Parameters { mtl_bindings: naga::FastHashMap, } -bitflags::bitflags! { - struct Language: u32 { - const SPIRV = 0x1; - const METAL = 0x2; - const GLSL = 0x4; - } -} - #[cfg(feature = "spv-out")] fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { use naga::back::spv; @@ -170,3 +170,9 @@ fn converts_wgsl_simple() { fn converts_wgsl_boids() { convert_wgsl("boids", Language::METAL); } + +#[cfg(feature = "wgsl-in")] +#[test] +fn converts_wgsl_skybox() { + convert_wgsl("skybox", Language::all()); +} diff --git a/tests/snapshots/in/skybox.param.ron b/tests/snapshots/in/skybox.param.ron new file mode 100644 index 000000000..8d5a2e3ec --- /dev/null +++ b/tests/snapshots/in/skybox.param.ron @@ -0,0 +1,9 @@ +( + spv_flow_dump_prefix: "", + spv_capabilities: [ Shader ], + mtl_bindings: { + (stage: Vertex, group: 0, binding: 0): (buffer: Some(0)), + (stage: Fragment, group: 0, binding: 1): (texture: Some(0)), + (stage: Fragment, group: 0, binding: 2): (sampler: Some(1)), + } +) diff --git a/tests/snapshots/in/skybox.wgsl b/tests/snapshots/in/skybox.wgsl new file mode 100644 index 000000000..78de8bacd --- /dev/null +++ b/tests/snapshots/in/skybox.wgsl @@ -0,0 +1,43 @@ +[[builtin(position)]] +var out_position: vec4; +[[location(0)]] var out_uv: vec3; +[[builtin(vertex_index)]] var in_vertex_index: u32; + +#[[block]] +struct Data { + [[offset(0)]] proj_inv: mat4x4; + [[offset(64)]] view: mat4x4; +}; +[[group(0), binding(0)]] +var r_data: Data; + +[[stage(vertex)]] +fn vs_main() { + # hacky way to draw a large triangle + var tmp1: i32 = i32(in_vertex_index) / 2; + var tmp2: i32 = i32(in_vertex_index) & 1; + const pos: vec4 = vec4( + f32(tmp1) * 4.0 - 1.0, + f32(tmp2) * 4.0 - 1.0, + 0.0, + 1.0 + ); + + const inv_model_view: mat3x3 = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); + var unprojected: vec4 = r_data.proj_inv * pos; #TODO: const + out_uv = inv_model_view * unprojected.xyz; + out_position = pos; +} + +[[group(0), binding(1)]] +var r_texture: texture_cube; +[[group(0), binding(2)]] +var r_sampler: sampler; + +[[location(0)]] var in_uv: vec3; +[[location(0)]] var out_color: vec4; + +[[stage(fragment)]] +fn fs_main() { + out_color = textureSample(r_texture, r_sampler, in_uv); +} diff --git a/tests/snapshots/snapshots__skybox-Fragment.glsl.snap b/tests/snapshots/snapshots__skybox-Fragment.glsl.snap new file mode 100644 index 000000000..54bf9ef72 --- /dev/null +++ b/tests/snapshots/snapshots__skybox-Fragment.glsl.snap @@ -0,0 +1,24 @@ +--- +source: tests/snapshots.rs +expression: string +--- +#version 310 es + +precision highp float; + + +struct Data { + mat4x4 proj_inv; + mat4x4 view; +}; + +uniform samplerCube r_texture; +in vec3 in_uv; +out vec4 out_color; + +void main() { + + out_color = texture(r_texture, vec3(in_uv)); + return; +} + diff --git a/tests/snapshots/snapshots__skybox-Vertex.glsl.snap b/tests/snapshots/snapshots__skybox-Vertex.glsl.snap new file mode 100644 index 000000000..2dc3726d0 --- /dev/null +++ b/tests/snapshots/snapshots__skybox-Vertex.glsl.snap @@ -0,0 +1,30 @@ +--- +source: tests/snapshots.rs +expression: string +--- +#version 310 es + +precision highp float; + + +struct Data { + mat4x4 proj_inv; + mat4x4 view; +}; + +out vec3 out_uv; +uniform Data r_data; + +void main() { + int tmp1_; + int tmp2_; + vec4 unprojected; + + tmp1_ = (int(gl_VertexID) / 2); + tmp2_ = (int(gl_VertexID) & 1); + unprojected = (r_data.proj_inv * vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0)); + out_uv = (transpose(mat3x3(vec3(r_data.view[0][0], r_data.view[0][1], r_data.view[0][2]), vec3(r_data.view[1][0], r_data.view[1][1], r_data.view[1][2]), vec3(r_data.view[2][0], r_data.view[2][1], r_data.view[2][2]))) * vec3(unprojected[0], unprojected[1], unprojected[2])); + gl_Position = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + return; +} + diff --git a/tests/snapshots/snapshots__skybox.msl.snap b/tests/snapshots/snapshots__skybox.msl.snap new file mode 100644 index 000000000..e4a88144c --- /dev/null +++ b/tests/snapshots/snapshots__skybox.msl.snap @@ -0,0 +1,60 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +typedef metal::float4 type; +typedef metal::float3 type1; +typedef uint type2; +typedef metal::float4x4 type3; +struct Data { + type3 proj_inv; + type3 view; +}; +typedef int type4; +typedef float type5; +typedef metal::float3x3 type6; +typedef metal::texturecube type7; +typedef metal::sampler type8; +typedef metal::int3 type9; + +struct vs_mainInput { +}; +struct vs_mainOutput { + type out_position [[position]]; + type1 out_uv [[user(loc0)]]; +}; +vertex vs_mainOutput vs_main( + vs_mainInput input [[stage_in]], + type2 in_vertex_index [[vertex_id]], + constant Data& r_data [[buffer(0)]] +) { + vs_mainOutput output; + type4 tmp1_; + type4 tmp2_; + type unprojected; + tmp1_ = static_cast(in_vertex_index) / 2; + tmp2_ = static_cast(in_vertex_index) & 1; + unprojected = r_data.proj_inv * metal::float4(static_cast(tmp1_) * 4.0 - 1.0, static_cast(tmp2_) * 4.0 - 1.0, 0.0, 1.0); + output.out_uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z); + output.out_position = metal::float4(static_cast(tmp1_) * 4.0 - 1.0, static_cast(tmp2_) * 4.0 - 1.0, 0.0, 1.0); + return output; +} +struct fs_mainInput { + type1 in_uv [[user(loc0)]]; +}; +struct fs_mainOutput { + type out_color [[color(0)]]; +}; +fragment fs_mainOutput fs_main( + fs_mainInput input [[stage_in]], + type7 r_texture [[texture(0)]], + type8 r_sampler [[sampler(1)]] +) { + fs_mainOutput output; + output.out_color = r_texture.sample(r_sampler, input.in_uv); + return output; +} + diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap new file mode 100644 index 000000000..942d7f7f1 --- /dev/null +++ b/tests/snapshots/snapshots__skybox.spvasm.snap @@ -0,0 +1,218 @@ +--- +source: tests/snapshots.rs +expression: dis +--- +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 185 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %11 "vs_main" %157 %44 %15 +OpEntryPoint Fragment %168 "fs_main" %180 %170 +OpExecutionMode %168 OriginUpperLeft +OpDecorate %15 BuiltIn VertexIndex +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 0 +OpDecorate %44 Location 0 +OpDecorate %157 BuiltIn Position +OpDecorate %170 Location 0 +OpDecorate %171 DescriptorSet 0 +OpDecorate %171 Binding 1 +OpDecorate %176 DescriptorSet 0 +OpDecorate %176 Binding 2 +OpDecorate %180 Location 0 +%3 = OpTypeInt 32 1 +%4 = OpTypePointer Function %3 +%8 = OpTypeFloat 32 +%7 = OpTypeVector %8 4 +%9 = OpTypePointer Function %7 +%10 = OpTypeVoid +%12 = OpTypeFunction %10 +%16 = OpTypeInt 32 0 +%17 = OpTypePointer Input %16 +%15 = OpVariable %17 Input +%19 = OpConstant %3 2 +%22 = OpConstant %3 1 +%27 = OpTypeMatrix %7 4 +%26 = OpTypeStruct %27 %27 +%28 = OpTypePointer Uniform %26 +%25 = OpVariable %28 Uniform +%29 = OpTypePointer Uniform %27 +%30 = OpConstant %3 0 +%36 = OpConstant %8 4.0 +%37 = OpConstant %8 1.0 +%42 = OpConstant %8 0.0 +%45 = OpTypeVector %8 3 +%46 = OpTypePointer Output %45 +%44 = OpVariable %46 Output +%48 = OpTypeMatrix %45 3 +%52 = OpTypePointer Uniform %27 +%53 = OpConstant %3 1 +%54 = OpTypePointer Uniform %7 +%55 = OpConstant %3 0 +%56 = OpTypePointer Uniform %8 +%57 = OpConstant %3 0 +%62 = OpTypePointer Uniform %27 +%63 = OpConstant %3 1 +%64 = OpTypePointer Uniform %7 +%65 = OpConstant %3 0 +%66 = OpTypePointer Uniform %8 +%67 = OpConstant %3 1 +%72 = OpTypePointer Uniform %27 +%73 = OpConstant %3 1 +%74 = OpTypePointer Uniform %7 +%75 = OpConstant %3 0 +%76 = OpTypePointer Uniform %8 +%77 = OpConstant %3 2 +%83 = OpTypePointer Uniform %27 +%84 = OpConstant %3 1 +%85 = OpTypePointer Uniform %7 +%86 = OpConstant %3 1 +%87 = OpTypePointer Uniform %8 +%88 = OpConstant %3 0 +%93 = OpTypePointer Uniform %27 +%94 = OpConstant %3 1 +%95 = OpTypePointer Uniform %7 +%96 = OpConstant %3 1 +%97 = OpTypePointer Uniform %8 +%98 = OpConstant %3 1 +%103 = OpTypePointer Uniform %27 +%104 = OpConstant %3 1 +%105 = OpTypePointer Uniform %7 +%106 = OpConstant %3 1 +%107 = OpTypePointer Uniform %8 +%108 = OpConstant %3 2 +%114 = OpTypePointer Uniform %27 +%115 = OpConstant %3 1 +%116 = OpTypePointer Uniform %7 +%117 = OpConstant %3 2 +%118 = OpTypePointer Uniform %8 +%119 = OpConstant %3 0 +%124 = OpTypePointer Uniform %27 +%125 = OpConstant %3 1 +%126 = OpTypePointer Uniform %7 +%127 = OpConstant %3 2 +%128 = OpTypePointer Uniform %8 +%129 = OpConstant %3 1 +%134 = OpTypePointer Uniform %27 +%135 = OpConstant %3 1 +%136 = OpTypePointer Uniform %7 +%137 = OpConstant %3 2 +%138 = OpTypePointer Uniform %8 +%139 = OpConstant %3 2 +%145 = OpTypePointer Function %8 +%146 = OpConstant %3 0 +%149 = OpTypePointer Function %8 +%150 = OpConstant %3 1 +%153 = OpTypePointer Function %8 +%154 = OpConstant %3 2 +%158 = OpTypePointer Output %7 +%157 = OpVariable %158 Output +%170 = OpVariable %158 Output +%172 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%173 = OpTypePointer UniformConstant %172 +%171 = OpVariable %173 UniformConstant +%175 = OpTypeSampledImage %172 +%177 = OpTypeSampler +%178 = OpTypePointer UniformConstant %177 +%176 = OpVariable %178 UniformConstant +%181 = OpTypePointer Input %45 +%180 = OpVariable %181 Input +%11 = OpFunction %10 None %12 +%13 = OpLabel +%2 = OpVariable %4 Function +%5 = OpVariable %4 Function +%6 = OpVariable %9 Function +%18 = OpLoad %16 %15 +%14 = OpSDiv %3 %18 %19 +OpStore %2 %14 +%21 = OpLoad %16 %15 +%20 = OpBitwiseAnd %3 %21 %22 +OpStore %5 %20 +%24 = OpAccessChain %29 %25 %30 +%31 = OpLoad %27 %24 +%34 = OpLoad %3 %2 +%35 = OpConvertSToF %8 %34 +%33 = OpFMul %8 %35 %36 +%32 = OpFSub %8 %33 %37 +%40 = OpLoad %3 %5 +%41 = OpConvertSToF %8 %40 +%39 = OpFMul %8 %41 %36 +%38 = OpFSub %8 %39 %37 +%43 = OpCompositeConstruct %7 %32 %38 %42 %37 +%23 = OpMatrixTimesVector %7 %31 %43 +OpStore %6 %23 +%51 = OpAccessChain %52 %25 %53 +%50 = OpAccessChain %54 %51 %55 +%49 = OpAccessChain %56 %50 %57 +%58 = OpLoad %8 %49 +%61 = OpAccessChain %62 %25 %63 +%60 = OpAccessChain %64 %61 %65 +%59 = OpAccessChain %66 %60 %67 +%68 = OpLoad %8 %59 +%71 = OpAccessChain %72 %25 %73 +%70 = OpAccessChain %74 %71 %75 +%69 = OpAccessChain %76 %70 %77 +%78 = OpLoad %8 %69 +%79 = OpCompositeConstruct %45 %58 %68 %78 +%82 = OpAccessChain %83 %25 %84 +%81 = OpAccessChain %85 %82 %86 +%80 = OpAccessChain %87 %81 %88 +%89 = OpLoad %8 %80 +%92 = OpAccessChain %93 %25 %94 +%91 = OpAccessChain %95 %92 %96 +%90 = OpAccessChain %97 %91 %98 +%99 = OpLoad %8 %90 +%102 = OpAccessChain %103 %25 %104 +%101 = OpAccessChain %105 %102 %106 +%100 = OpAccessChain %107 %101 %108 +%109 = OpLoad %8 %100 +%110 = OpCompositeConstruct %45 %89 %99 %109 +%113 = OpAccessChain %114 %25 %115 +%112 = OpAccessChain %116 %113 %117 +%111 = OpAccessChain %118 %112 %119 +%120 = OpLoad %8 %111 +%123 = OpAccessChain %124 %25 %125 +%122 = OpAccessChain %126 %123 %127 +%121 = OpAccessChain %128 %122 %129 +%130 = OpLoad %8 %121 +%133 = OpAccessChain %134 %25 %135 +%132 = OpAccessChain %136 %133 %137 +%131 = OpAccessChain %138 %132 %139 +%140 = OpLoad %8 %131 +%141 = OpCompositeConstruct %45 %120 %130 %140 +%142 = OpCompositeConstruct %48 %79 %110 %141 +%143 = OpTranspose %48 %142 +%144 = OpAccessChain %145 %6 %146 +%147 = OpLoad %8 %144 +%148 = OpAccessChain %149 %6 %150 +%151 = OpLoad %8 %148 +%152 = OpAccessChain %153 %6 %154 +%155 = OpLoad %8 %152 +%156 = OpCompositeConstruct %45 %147 %151 %155 +%47 = OpMatrixTimesVector %45 %143 %156 +OpStore %44 %47 +%161 = OpLoad %3 %2 +%162 = OpConvertSToF %8 %161 +%160 = OpFMul %8 %162 %36 +%159 = OpFSub %8 %160 %37 +%165 = OpLoad %3 %5 +%166 = OpConvertSToF %8 %165 +%164 = OpFMul %8 %166 %36 +%163 = OpFSub %8 %164 %37 +%167 = OpCompositeConstruct %7 %159 %163 %42 %37 +OpStore %157 %167 +OpReturn +OpFunctionEnd +%168 = OpFunction %10 None %12 +%169 = OpLabel +%174 = OpLoad %172 %171 +%179 = OpLoad %177 %176 +%182 = OpLoad %45 %180 +%183 = OpSampledImage %175 %174 %179 +%184 = OpImageSampleImplicitLod %7 %183 %182 +OpStore %170 %184 +OpReturn +OpFunctionEnd From 6bb40ce27b41ebd263ef5f68dccd46f7bd253303 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Tue, 15 Dec 2020 15:24:48 +0100 Subject: [PATCH 0341/2212] [glsl-in] Cast gl_VertexIndex to SInt (#332) * [glsl-in] Cast gl_VertexIndex to SInt * [glsl-in] Use conversion cast (gl_VertexIndex) - Also cast gl_InstanceIndex * [glsl-in] Simplify global var lookup * [glsl-in] Fix missing comma --- src/front/glsl/variables.rs | 154 ++++++++++++++++++------------------ 1 file changed, 77 insertions(+), 77 deletions(-) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 7fb1a3518..37335987d 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -9,7 +9,12 @@ use super::token::TokenMetadata; impl Program { pub fn lookup_variable(&mut self, name: &str) -> Result>, ErrorKind> { - let mut expression: Option> = None; + if let Some(local_var) = self.context.lookup_local_var(name) { + return Ok(Some(local_var)); + } + if let Some(global_var) = self.context.lookup_global_var_exps.get(name) { + return Ok(Some(*global_var)); + } match name { "gl_Position" => { #[cfg(feature = "glsl-validate")] @@ -19,29 +24,26 @@ impl Program { return Err(ErrorKind::VariableNotAvailable(name.into())); } }; - let h = self - .module - .global_variables - .fetch_or_append(GlobalVariable { - name: Some(name.into()), - class: if self.shader_stage == ShaderStage::Vertex { - StorageClass::Output - } else { - StorageClass::Input + let h = self.module.global_variables.append(GlobalVariable { + name: Some(name.into()), + class: if self.shader_stage == ShaderStage::Vertex { + StorageClass::Output + } else { + StorageClass::Input + }, + binding: Some(Binding::BuiltIn(BuiltIn::Position)), + ty: self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 4, }, - binding: Some(Binding::BuiltIn(BuiltIn::Position)), - ty: self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, - }, - }), - init: None, - interpolation: None, - storage_access: StorageAccess::empty(), - }); + }), + init: None, + interpolation: None, + storage_access: StorageAccess::empty(), + }); self.lookup_global_variables.insert(name.into(), h); let exp = self .context @@ -49,7 +51,7 @@ impl Program { .append(Expression::GlobalVariable(h)); self.context.lookup_global_var_exps.insert(name.into(), exp); - expression = Some(exp); + Ok(Some(exp)) } "gl_VertexIndex" => { #[cfg(feature = "glsl-validate")] @@ -59,32 +61,36 @@ impl Program { return Err(ErrorKind::VariableNotAvailable(name.into())); } }; - let h = self - .module - .global_variables - .fetch_or_append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), - ty: self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - }), - init: None, - interpolation: None, - storage_access: StorageAccess::empty(), - }); + let h = self.module.global_variables.append(GlobalVariable { + name: Some(name.into()), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), + ty: self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + }, + }), + init: None, + interpolation: None, + storage_access: StorageAccess::empty(), + }); self.lookup_global_variables.insert(name.into(), h); - let exp = self + let mut expr = self .context .expressions .append(Expression::GlobalVariable(h)); - self.context.lookup_global_var_exps.insert(name.into(), exp); + expr = self.context.expressions.append(Expression::As { + expr, + kind: ScalarKind::Sint, + convert: true, + }); + self.context + .lookup_global_var_exps + .insert(name.into(), expr); - expression = Some(exp); + Ok(Some(expr)) } "gl_InstanceIndex" => { #[cfg(feature = "glsl-validate")] @@ -94,44 +100,38 @@ impl Program { return Err(ErrorKind::VariableNotAvailable(name.into())); } }; - let h = self - .module - .global_variables - .fetch_or_append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::InstanceIndex)), - ty: self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - }), - init: None, - interpolation: None, - storage_access: StorageAccess::empty(), - }); + let h = self.module.global_variables.append(GlobalVariable { + name: Some(name.into()), + class: StorageClass::Input, + binding: Some(Binding::BuiltIn(BuiltIn::InstanceIndex)), + ty: self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + }, + }), + init: None, + interpolation: None, + storage_access: StorageAccess::empty(), + }); self.lookup_global_variables.insert(name.into(), h); - let exp = self + let mut expr = self .context .expressions .append(Expression::GlobalVariable(h)); - self.context.lookup_global_var_exps.insert(name.into(), exp); + expr = self.context.expressions.append(Expression::As { + expr, + kind: ScalarKind::Sint, + convert: true, + }); + self.context + .lookup_global_var_exps + .insert(name.into(), expr); - expression = Some(exp); + Ok(Some(expr)) } - _ => {} - } - - if let Some(expression) = expression { - Ok(Some(expression)) - } else if let Some(local_var) = self.context.lookup_local_var(name) { - Ok(Some(local_var)) - } else if let Some(global_var) = self.context.lookup_global_var_exps.get(name) { - Ok(Some(*global_var)) - } else { - Ok(None) + _ => Ok(None), } } From 583f218c9dbca08daa6bf3efda60e80ecada63bb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 15 Dec 2020 09:31:08 -0500 Subject: [PATCH 0342/2212] Fix SPIR-V global binding check, add GLES 320 support (#333) --- src/back/glsl/features.rs | 4 +++- src/back/glsl/mod.rs | 5 +++-- src/back/spv/writer.rs | 9 +++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 4858e7e78..b71447657 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -193,7 +193,9 @@ impl<'a, W> Writer<'a, W> { match ty.inner { TypeInner::Scalar { kind, width } => self.scalar_required_features(kind, width), TypeInner::Vector { kind, width, .. } => self.scalar_required_features(kind, width), - TypeInner::Matrix { width, .. } => self.scalar_required_features(ScalarKind::Float, width), + TypeInner::Matrix { width, .. } => { + self.scalar_required_features(ScalarKind::Float, width) + } TypeInner::Array { base, .. } => { if let TypeInner::Array { .. } = self.module.types[base].inner { self.features.request(Features::ARRAY_OF_ARRAYS) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a8493e70b..fe807f70e 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -67,9 +67,9 @@ mod features; mod keywords; /// List of supported core glsl versions -const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; +pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; /// List of supported es glsl versions -const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310]; +pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; /// glsl version #[derive(Debug, Copy, Clone, PartialEq)] @@ -287,6 +287,7 @@ impl<'a, W: Write> Writer<'a, W> { pub fn new(out: W, module: &'a Module, options: &'a Options) -> Result { // Check if the requested version is supported if !options.version.is_supported() { + log::error!("Version {}", options.version); return Err(Error::VersionNotSupported); } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d345a3b6b..fed2232c0 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -822,8 +822,8 @@ impl Writer { } } - match global_variable.binding.clone().unwrap() { - crate::Binding::Location(location) => { + match global_variable.binding { + Some(crate::Binding::Location(location)) => { self.annotations .push(super::instructions::instruction_decorate( id, @@ -831,7 +831,7 @@ impl Writer { &[location], )); } - crate::Binding::Resource { group, binding } => { + Some(crate::Binding::Resource { group, binding }) => { self.annotations .push(super::instructions::instruction_decorate( id, @@ -845,7 +845,7 @@ impl Writer { &[binding], )); } - crate::Binding::BuiltIn(built_in) => { + Some(crate::Binding::BuiltIn(built_in)) => { let built_in = match built_in { crate::BuiltIn::BaseInstance => spirv::BuiltIn::BaseInstance, crate::BuiltIn::BaseVertex => spirv::BuiltIn::BaseVertex, @@ -872,6 +872,7 @@ impl Writer { &[built_in as u32], )); } + None => {} } // TODO Initializer is optional and not (yet) included in the IR From fca72fd333442c5682f19ae1a28b7c952317b69e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 17 Dec 2020 23:40:29 -0500 Subject: [PATCH 0343/2212] [wgsl] avoid recursion in token parsing --- src/front/wgsl/lexer.rs | 181 +++++++++++++++++++++------------------- src/front/wgsl/tests.rs | 14 ++++ 2 files changed, 107 insertions(+), 88 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 31562a3d0..88688da6e 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -36,103 +36,108 @@ fn consume_number(input: &str) -> (&str, &str) { } fn consume_token(mut input: &str) -> (Token<'_>, &str) { - input = input.trim_start(); - let mut chars = input.chars(); - let cur = match chars.next() { - Some(c) => c, - None => return (Token::End, input), - }; - match cur { - ':' => { - input = chars.as_str(); - if chars.next() == Some(':') { - (Token::DoubleColon, chars.as_str()) - } else { - (Token::Separator(cur), input) - } - } - ';' | ',' => (Token::Separator(cur), chars.as_str()), - '.' => { - let og_chars = chars.as_str(); - match chars.next() { - Some('0'..='9') => { - let (number, rest) = consume_number(input); - (Token::Number(number), rest) + loop { + input = input.trim_start(); + let mut chars = input.chars(); + let cur = match chars.next() { + Some(c) => c, + None => return (Token::End, input), + }; + break match cur { + ':' => { + input = chars.as_str(); + if chars.next() == Some(':') { + (Token::DoubleColon, chars.as_str()) + } else { + (Token::Separator(cur), input) } - _ => (Token::Separator(cur), og_chars), } - } - '(' | ')' | '{' | '}' => (Token::Paren(cur), chars.as_str()), - '<' | '>' => { - input = chars.as_str(); - let next = chars.next(); - if next == Some('=') { - (Token::LogicalOperation(cur), chars.as_str()) - } else if next == Some(cur) { - (Token::ShiftOperation(cur), chars.as_str()) - } else { - (Token::Paren(cur), input) + ';' | ',' => (Token::Separator(cur), chars.as_str()), + '.' => { + let og_chars = chars.as_str(); + match chars.next() { + Some('0'..='9') => { + let (number, rest) = consume_number(input); + (Token::Number(number), rest) + } + _ => (Token::Separator(cur), og_chars), + } } - } - '[' | ']' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::DoubleParen(cur), chars.as_str()) - } else { - (Token::Paren(cur), input) + '(' | ')' | '{' | '}' => (Token::Paren(cur), chars.as_str()), + '<' | '>' => { + input = chars.as_str(); + let next = chars.next(); + if next == Some('=') { + (Token::LogicalOperation(cur), chars.as_str()) + } else if next == Some(cur) { + (Token::ShiftOperation(cur), chars.as_str()) + } else { + (Token::Paren(cur), input) + } } - } - '0'..='9' => { - let (number, rest) = consume_number(input); - (Token::Number(number), rest) - } - 'a'..='z' | 'A'..='Z' | '_' => { - let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); - (Token::Word(word), rest) - } - '"' => { - let mut iter = chars.as_str().splitn(2, '"'); + '[' | ']' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + (Token::DoubleParen(cur), chars.as_str()) + } else { + (Token::Paren(cur), input) + } + } + '0'..='9' => { + let (number, rest) = consume_number(input); + (Token::Number(number), rest) + } + 'a'..='z' | 'A'..='Z' | '_' => { + let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); + (Token::Word(word), rest) + } + '"' => { + let mut iter = chars.as_str().splitn(2, '"'); - // splitn returns an iterator with at least one element, so unwrapping is fine - let quote_content = iter.next().unwrap(); - if let Some(rest) = iter.next() { - (Token::String(quote_content), rest) - } else { - (Token::UnterminatedString, quote_content) - } - } - '-' => { - let og_chars = chars.as_str(); - match chars.next() { - Some('>') => (Token::Arrow, chars.as_str()), - Some('0'..='9') | Some('.') => { - let (number, rest) = consume_number(input); - (Token::Number(number), rest) + // splitn returns an iterator with at least one element, so unwrapping is fine + let quote_content = iter.next().unwrap(); + if let Some(rest) = iter.next() { + (Token::String(quote_content), rest) + } else { + (Token::UnterminatedString, quote_content) } - _ => (Token::Operation(cur), og_chars), } - } - '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), - '!' => { - if chars.next() == Some('=') { - (Token::LogicalOperation(cur), chars.as_str()) - } else { - (Token::Operation(cur), input) + '-' => { + let og_chars = chars.as_str(); + match chars.next() { + Some('>') => (Token::Arrow, chars.as_str()), + Some('0'..='9') | Some('.') => { + let (number, rest) = consume_number(input); + (Token::Number(number), rest) + } + _ => (Token::Operation(cur), og_chars), + } } - } - '=' | '&' | '|' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::LogicalOperation(cur), chars.as_str()) - } else { - (Token::Operation(cur), input) + '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), + '!' => { + if chars.next() == Some('=') { + (Token::LogicalOperation(cur), chars.as_str()) + } else { + (Token::Operation(cur), input) + } } - } - '#' => match chars.position(|c| c == '\n' || c == '\r') { - Some(_) => consume_token(chars.as_str()), - None => (Token::End, chars.as_str()), - }, - _ => (Token::Unknown(cur), chars.as_str()), + '=' | '&' | '|' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + (Token::LogicalOperation(cur), chars.as_str()) + } else { + (Token::Operation(cur), input) + } + } + '#' => match chars.position(|c| c == '\n' || c == '\r') { + Some(_) => { + input = chars.as_str(); + continue; + } + None => (Token::End, chars.as_str()), + }, + _ => (Token::Unknown(cur), chars.as_str()), + }; } } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 12fa67218..e761e6b29 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -1,5 +1,19 @@ use super::parse_str; +#[test] +fn parse_comment() { + parse_str( + "# + ## + ######################################################### asda + #################### dad ########## # + ##################################################################################################### + # + ", + ) + .unwrap(); +} + #[test] fn parse_types() { parse_str("const a : i32 = 2;").unwrap(); From b95346877abbed2e6a242c6bea836d9fed49802f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Dec 2020 00:33:22 -0500 Subject: [PATCH 0344/2212] Remove MemberOrigin in favor of spans --- Makefile | 2 +- src/back/msl/mod.rs | 27 ++++---- src/back/msl/writer.rs | 109 ++++++++------------------------- src/front/glsl/parser.rs | 4 +- src/front/spv/mod.rs | 31 +--------- src/front/wgsl/mod.rs | 14 ++--- src/front/wgsl/tests.rs | 20 +++--- src/lib.rs | 15 +---- tests/snapshots/in/boids.wgsl | 20 +++--- tests/snapshots/in/skybox.wgsl | 4 +- 10 files changed, 79 insertions(+), 167 deletions(-) diff --git a/Makefile b/Makefile index 910db1543..db45f2362 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ all: clean: rm *.metal *.air *.metallib *.vert *.frag *.comp -%.metal: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) +%.metal: tests/snapshots/in/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) cargo run --example convert --features wgsl-in,msl-out -- $< $@ %.air: %.metal diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index cc08869e7..053704303 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -57,20 +57,15 @@ pub enum Error { IO(IoError), Utf8(FromUtf8Error), Type(ResolveError), - UnexpectedLocation, - MissingBinding(Handle), MissingBindTarget(BindSource), InvalidImageAccess(crate::StorageAccess), - MutabilityViolation(Handle), BadName(String), - UnexpectedGlobalType(Handle), UnimplementedBindTarget(BindTarget), UnsupportedCompose(Handle), UnsupportedBinaryOp(crate::BinaryOperator), UnexpectedSampleLevel(crate::SampleLevel), UnsupportedCall(String), UnsupportedDynamicArrayLength, - UnableToReturnValue(Handle), /// The source IR is not valid. Validation, } @@ -115,12 +110,12 @@ impl Options { fn resolve_binding( &self, stage: crate::ShaderStage, - binding: &crate::Binding, + var: &crate::GlobalVariable, mode: LocationMode, ) -> Result { - match *binding { - crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), - crate::Binding::Location(index) => match mode { + match var.binding { + Some(crate::Binding::BuiltIn(built_in)) => Ok(ResolvedBinding::BuiltIn(built_in)), + Some(crate::Binding::Location(index)) => match mode { LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(index)), LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(index)), LocationMode::Intermediate => Ok(ResolvedBinding::User { @@ -131,9 +126,15 @@ impl Options { }, index, }), - LocationMode::Uniform => Err(Error::UnexpectedLocation), + LocationMode::Uniform => { + log::error!( + "Unexpected Binding::Location({}) for the Uniform mode", + index + ); + Err(Error::Validation) + } }, - crate::Binding::Resource { group, binding } => { + Some(crate::Binding::Resource { group, binding }) => { let source = BindSource { stage, group, @@ -145,6 +146,10 @@ impl Options { .map(ResolvedBinding::Resource) .ok_or(Error::MissingBindTarget(source)) } + None => { + log::error!("Missing binding for {:?}", var.name); + Err(Error::Validation) + } } } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index feaa01098..671c8d166 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,4 +1,4 @@ -use super::{keywords::RESERVED, Error, LocationMode, Options, ResolvedBinding, TranslationInfo}; +use super::{keywords::RESERVED, Error, LocationMode, Options, TranslationInfo}; use crate::{ arena::Handle, proc::{EntryPointIndex, NameKey, Namer, ResolveContext, Typifier}, @@ -740,18 +740,7 @@ impl Writer { for (index, member) in members.iter().enumerate() { let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; let base_name = &self.names[&NameKey::Type(member.ty)]; - write!(self.out, "\t{} {}", base_name, member_name)?; - match member.origin { - crate::MemberOrigin::Empty => {} - crate::MemberOrigin::BuiltIn(built_in) => { - ResolvedBinding::BuiltIn(built_in) - .try_fmt_decorated(&mut self.out, "")?; - } - crate::MemberOrigin::Offset(_) => { - //TODO - } - } - writeln!(self.out, ";")?; + writeln!(self.out, "\t{} {};", base_name, member_name)?; } write!(self.out, "}}")?; } @@ -932,7 +921,6 @@ impl Writer { crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { // make dedicated input/output structs writeln!(self.out, "struct {} {{", location_input_name)?; - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { @@ -941,36 +929,20 @@ impl Writer { { continue; } - // if it's a struct, lift all the built-in contents up to the root - if let crate::TypeInner::Struct { - block: _, - ref members, - } = module.types[var.ty].inner - { - for (index, member) in members.iter().enumerate() { - if let crate::MemberOrigin::BuiltIn(built_in) = member.origin { - let name = - &self.names[&NameKey::StructMember(var.ty, index as u32)]; - let ty_name = &self.names[&NameKey::Type(member.ty)]; - write!(self.out, "\t{} {}", ty_name, name)?; - ResolvedBinding::BuiltIn(built_in) - .try_fmt_decorated(&mut self.out, ";\n")?; - } - } - } else if let Some(ref binding @ crate::Binding::Location(_)) = var.binding - { - let tyvar = TypedGlobalVariable { - module, - names: &self.names, - handle, - usage: crate::GlobalUse::empty(), - }; - let resolved = options.resolve_binding(stage, binding, in_mode)?; - - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - resolved.try_fmt_decorated(&mut self.out, ";\n")?; + if let Some(crate::Binding::BuiltIn(_)) = var.binding { + // MSL disallows built-ins in input structs + continue; } + let tyvar = TypedGlobalVariable { + module, + names: &self.names, + handle, + usage: crate::GlobalUse::empty(), + }; + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + let resolved = options.resolve_binding(stage, var, in_mode)?; + resolved.try_fmt_decorated(&mut self.out, ";\n")?; } writeln!(self.out, "}};")?; @@ -983,43 +955,17 @@ impl Writer { { continue; } - // if it's a struct, lift all the built-in contents up to the root - if let crate::TypeInner::Struct { - block: _, - ref members, - } = module.types[var.ty].inner - { - for (index, member) in members.iter().enumerate() { - let name = - &self.names[&NameKey::StructMember(var.ty, index as u32)]; - let ty_name = &self.names[&NameKey::Type(member.ty)]; - match member.origin { - crate::MemberOrigin::Empty => {} - crate::MemberOrigin::BuiltIn(built_in) => { - write!(self.out, "\t{} {}", ty_name, name)?; - ResolvedBinding::BuiltIn(built_in) - .try_fmt_decorated(&mut self.out, ";\n")?; - } - crate::MemberOrigin::Offset(_) => { - //TODO - } - } - } - } else { - let tyvar = TypedGlobalVariable { - module, - names: &self.names, - handle, - usage: crate::GlobalUse::empty(), - }; - write!(self.out, "\t")?; - tyvar.try_fmt(&mut self.out)?; - if let Some(ref binding) = var.binding { - let resolved = options.resolve_binding(stage, binding, out_mode)?; - resolved.try_fmt_decorated(&mut self.out, "")?; - } - writeln!(self.out, ";")?; - } + + let tyvar = TypedGlobalVariable { + module, + names: &self.names, + handle, + usage: crate::GlobalUse::empty(), + }; + write!(self.out, "\t")?; + tyvar.try_fmt(&mut self.out)?; + let resolved = options.resolve_binding(stage, var, out_mode)?; + resolved.try_fmt_decorated(&mut self.out, ";\n")?; } writeln!(self.out, "}};")?; @@ -1062,8 +1008,7 @@ impl Writer { } _ => LocationMode::Uniform, }; - let resolved = - options.resolve_binding(stage, var.binding.as_ref().unwrap(), loc_mode)?; + let resolved = options.resolve_binding(stage, var, loc_mode)?; let tyvar = TypedGlobalVariable { module, names: &self.names, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 05086ff65..0328060bb 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -10,7 +10,7 @@ pomelo! { Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, EntryPoint, Expression, Function, GlobalVariable, Handle, Interpolation, - LocalVariable, MemberOrigin, SampleLevel, ScalarKind, + LocalVariable, SampleLevel, ScalarKind, Statement, StorageAccess, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, }; @@ -745,7 +745,7 @@ pomelo! { if let Some(ty) = t { sdl.iter().map(|name| StructMember { name: Some(name.clone()), - origin: MemberOrigin::Empty, + span: None, ty, }).collect() } else { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 4328b635d..8b0bf98e0 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -204,32 +204,6 @@ impl Decoration { _ => None, } } - - fn get_origin(&self) -> Result { - match *self { - Decoration { - location: Some(_), .. - } - | Decoration { - desc_set: Some(_), .. - } - | Decoration { - desc_index: Some(_), - .. - } => Err(Error::MissingDecoration(spirv::Decoration::Offset)), - Decoration { - built_in: Some(built_in), - offset: None, - .. - } => Ok(crate::MemberOrigin::BuiltIn(built_in)), - Decoration { - built_in: None, - offset: Some(offset), - .. - } => Ok(crate::MemberOrigin::Offset(offset)), - _ => Ok(crate::MemberOrigin::Empty), - } - } } bitflags::bitflags! { @@ -2028,6 +2002,7 @@ impl> Parser { inst.expect_at_least(2)?; let id = self.next()?; let parent_decor = self.future_decor.remove(&id); + let block_decor = parent_decor.as_ref().and_then(|decor| decor.block.clone()); let mut members = Vec::with_capacity(inst.wc as usize - 2); let mut member_type_ids = Vec::with_capacity(members.capacity()); @@ -2039,15 +2014,13 @@ impl> Parser { .future_member_decor .remove(&(id, i)) .unwrap_or_default(); - let origin = decor.get_origin()?; members.push(crate::StructMember { name: decor.name, - origin, + span: None, //TODO ty, }); } - let block_decor = parent_decor.as_ref().and_then(|decor| decor.block.clone()); let inner = crate::TypeInner::Struct { block: block_decor.is_some(), members, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index ec69381f2..5235f8e5d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -82,8 +82,6 @@ pub enum Error<'a> { UnknownFunction(&'a str), #[error("unknown storage format: `{0}`")] UnknownStorageFormat(&'a str), - #[error("missing offset for structure member `{0}`")] - MissingMemberOffset(&'a str), #[error("array stride must not be 0")] ZeroStride, #[error("not a composite type: {0:?}")] @@ -1131,7 +1129,7 @@ impl Parser { let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; loop { - let mut offset = !0; + let mut span = 0; if lexer.skip(Token::DoubleParen('[')) { self.scopes.push(Scope::Decoration); let mut ready = true; @@ -1143,9 +1141,10 @@ impl Parser { Token::Separator(',') if !ready => { ready = true; } - Token::Word("offset") if ready => { + Token::Word("span") if ready => { lexer.expect(Token::Paren('('))?; - offset = lexer.next_uint_literal()?; + //Note: 0 is not handled + span = lexer.next_uint_literal()?; lexer.expect(Token::Paren(')'))?; ready = false; } @@ -1159,15 +1158,12 @@ impl Parser { Token::Paren('}') => return Ok(members), other => return other.unexpected("field name"), }; - if offset == !0 { - return Err(Error::MissingMemberOffset(name)); - } lexer.expect(Token::Separator(':'))?; let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Separator(';'))?; members.push(crate::StructMember { name: Some(name.to_owned()), - origin: crate::MemberOrigin::Offset(offset), + span: NonZeroU32::new(span), ty, }); } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index e761e6b29..c8b812497 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -23,13 +23,6 @@ fn parse_types() { parse_str("var t: texture_multisampled_2d;").unwrap(); parse_str("var t: [[access(write)]] texture_storage_1d;").unwrap(); parse_str("var t: [[access(read)]] texture_storage_3d;").unwrap(); - parse_str( - " - [[block]] struct Foo { [[offset(0)]] x: i32; }; - var s: [[access(read_write)]] Foo; - ", - ) - .unwrap(); } #[test] @@ -46,6 +39,19 @@ fn parse_type_cast() { .unwrap(); } +#[test] +fn parse_struct() { + parse_str( + " + [[block]] struct Foo { x: i32; }; + struct Bar { [[span(16)]] x: vec2; }; + struct Empty {}; + var s: [[access(read_write)]] Foo; + ", + ) + .unwrap(); +} + #[test] fn parse_standard_fun() { parse_str( diff --git a/src/lib.rs b/src/lib.rs index 262fd0264..b9e06d0d4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -201,19 +201,6 @@ pub enum ArraySize { Dynamic, } -/// Describes where a struct member is placed. -#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] -#[cfg_attr(feature = "serialize", derive(Serialize))] -#[cfg_attr(feature = "deserialize", derive(Deserialize))] -pub enum MemberOrigin { - /// Member is local to the shader. - Empty, - /// Built-in shader variable. - BuiltIn(BuiltIn), - /// Offset within the struct. - Offset(u32), -} - /// The interpolation qualifier of a binding or struct field. #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -245,7 +232,7 @@ pub enum Interpolation { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct StructMember { pub name: Option, - pub origin: MemberOrigin, + pub span: Option, pub ty: Handle, } diff --git a/tests/snapshots/in/boids.wgsl b/tests/snapshots/in/boids.wgsl index 022827774..3d6051867 100644 --- a/tests/snapshots/in/boids.wgsl +++ b/tests/snapshots/in/boids.wgsl @@ -39,24 +39,24 @@ fn main() { # compute shader [[block]] struct Particle { - [[offset(0)]] pos : vec2; - [[offset(8)]] vel : vec2; + [[span(8)]] pos : vec2; + [[span(8)]] vel : vec2; }; [[block]] struct SimParams { - [[offset(0)]] deltaT : f32; - [[offset(4)]] rule1Distance : f32; - [[offset(8)]] rule2Distance : f32; - [[offset(12)]] rule3Distance : f32; - [[offset(16)]] rule1Scale : f32; - [[offset(20)]] rule2Scale : f32; - [[offset(24)]] rule3Scale : f32; + deltaT : f32; + rule1Distance : f32; + rule2Distance : f32; + rule3Distance : f32; + rule1Scale : f32; + rule2Scale : f32; + rule3Scale : f32; }; [[block]] struct Particles { - [[offset(0)]] particles : [[stride(16)]] array; + particles : [[stride(16)]] array; }; [[group(0), binding(0)]] var params : SimParams; diff --git a/tests/snapshots/in/skybox.wgsl b/tests/snapshots/in/skybox.wgsl index 78de8bacd..42436f13b 100644 --- a/tests/snapshots/in/skybox.wgsl +++ b/tests/snapshots/in/skybox.wgsl @@ -5,8 +5,8 @@ var out_position: vec4; #[[block]] struct Data { - [[offset(0)]] proj_inv: mat4x4; - [[offset(64)]] view: mat4x4; + proj_inv: mat4x4; + view: mat4x4; }; [[group(0), binding(0)]] var r_data: Data; From c0dfb247b68c2f1485583d6768562711badbc11b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Dec 2020 01:11:47 -0500 Subject: [PATCH 0345/2212] Sizing processor --- src/proc/mod.rs | 2 ++ src/proc/sizer.rs | 65 ++++++++++++++++++++++++++++++++++++++++++++ src/proc/typifier.rs | 1 + 3 files changed, 68 insertions(+) create mode 100644 src/proc/sizer.rs diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 74f814a07..ee0baeada 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -4,6 +4,7 @@ mod call_graph; mod interface; mod namer; +mod sizer; mod terminator; mod typifier; mod validator; @@ -12,6 +13,7 @@ mod validator; pub use call_graph::{CallGraph, CallGraphBuilder}; pub use interface::{Interface, Visitor}; pub use namer::{EntryPointIndex, NameKey, Namer}; +pub use sizer::Sizer; pub use terminator::ensure_block_returns; pub use typifier::{check_constant_type, ResolveContext, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; diff --git a/src/proc/sizer.rs b/src/proc/sizer.rs new file mode 100644 index 000000000..a9c58f091 --- /dev/null +++ b/src/proc/sizer.rs @@ -0,0 +1,65 @@ +use crate::arena::Arena; + +/// Helper processor that derives the sizes of all types. +#[derive(Debug)] +pub struct Sizer { + sizes: Vec, +} + +impl Sizer { + pub fn new(types: &Arena, constants: &Arena) -> Self { + use crate::TypeInner as Ti; + + let mut sizes = Vec::with_capacity(types.len()); + for (_, ty) in types.iter() { + sizes.push(match ty.inner { + Ti::Scalar { kind: _, width } => width as u32, + Ti::Vector { + size, + kind: _, + width, + } => (size as u8 * width) as u32, + Ti::Matrix { + columns, + rows, + width, + } => (columns as u8 * rows as u8 * width) as u32, + Ti::Pointer { .. } => 0, + Ti::Array { base, size, stride } => { + let count = match size { + crate::ArraySize::Constant(handle) => match constants[handle].inner { + crate::ConstantInner::Uint(value) => value as u32, + ref other => unreachable!("Unexpected array size {:?}", other), + }, + crate::ArraySize::Dynamic => 1, + }; + let stride = match stride { + Some(value) => value.get(), + None => sizes[base.index()], + }; + count * stride + } + Ti::Struct { + block: _, + ref members, + } => { + let mut total = 0; + for member in members { + total += match member.span { + Some(span) => span.get(), + None => sizes[member.ty.index()], + }; + } + total + } + Ti::Image { .. } | Ti::Sampler { .. } => 0, + }); + } + + Sizer { sizes } + } + + pub fn resolve(&self, handle: crate::Handle) -> u32 { + self.sizes[handle.index()] + } +} diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index c8ee18b1d..6862773c5 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -36,6 +36,7 @@ impl Clone for Resolution { } } +/// Helper processor that derives the types of all expressions. #[derive(Debug)] pub struct Typifier { resolutions: Vec, From 300aa61de0ec9b9321ebdfc1cd3793977802cfff Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Dec 2020 21:14:34 -0500 Subject: [PATCH 0346/2212] [spv] improves division and modulo operators --- src/back/spv/writer.rs | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index fed2232c0..c91435d67 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1203,23 +1203,16 @@ impl Writer { other => unreachable!("Mul {:?}", other), } } - crate::BinaryOperator::Divide => match *left_ty_inner { - crate::TypeInner::Scalar { kind, .. } - | crate::TypeInner::Vector { kind, .. } => match kind { - crate::ScalarKind::Sint => spirv::Op::SDiv, - crate::ScalarKind::Uint => spirv::Op::UDiv, - _ => unreachable!(), - }, + crate::BinaryOperator::Divide => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SDiv, + Some(crate::ScalarKind::Uint) => spirv::Op::UDiv, + Some(crate::ScalarKind::Float) => spirv::Op::FDiv, _ => unreachable!(), }, - crate::BinaryOperator::Modulo => match *left_ty_inner { - crate::TypeInner::Scalar { kind, .. } - | crate::TypeInner::Vector { kind, .. } => match kind { - crate::ScalarKind::Sint => spirv::Op::SMod, - crate::ScalarKind::Uint => spirv::Op::UMod, - crate::ScalarKind::Float => spirv::Op::FMod, - _ => unreachable!(), - }, + crate::BinaryOperator::Modulo => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SMod, + Some(crate::ScalarKind::Uint) => spirv::Op::UMod, + Some(crate::ScalarKind::Float) => spirv::Op::FMod, _ => unreachable!(), }, crate::BinaryOperator::And => spirv::Op::BitwiseAnd, From 1e704326914c96ea58c4e5c5017b1ee8bf10c69a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Dec 2020 21:36:13 -0500 Subject: [PATCH 0347/2212] [validator] refactor type checks into a function --- src/proc/validator.rs | 143 ++++++++++++++++++++++++------------------ 1 file changed, 82 insertions(+), 61 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index fdb7fd0d8..ae81b724c 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -13,6 +13,16 @@ pub struct Validator { typifier: Typifier, } +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +pub enum TypeError { + #[error("The {0:?} scalar width {1} is not supported")] + InvalidWidth(crate::ScalarKind, crate::Bytes), + #[error("The base handle {0:?} can not be resolved")] + UnresolvedBase(Handle), + #[error("The constant {0:?} can not be used for an array size")] + InvalidArraySizeConstant(Handle), +} + #[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum GlobalVariableError { #[error("Usage isn't compatible with the storage class")] @@ -78,12 +88,12 @@ pub enum EntryPointError { #[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum ValidationError { - #[error("The type {0:?} width {1} is not supported")] - InvalidTypeWidth(crate::ScalarKind, crate::Bytes), - #[error("The type handle {0:?} can not be resolved")] - UnresolvedType(Handle), - #[error("The constant {0:?} can not be used for an array size")] - InvalidArraySizeConstant(Handle), + #[error("Type {handle:?} '{name}' is invalid: {error:?}")] + Type { + handle: Handle, + name: String, + error: TypeError, + }, #[error("Global variable {handle:?} '{name}' is invalid: {error:?}")] GlobalVariable { handle: Handle, @@ -217,6 +227,66 @@ impl Validator { } } + fn validate_type( + &self, + ty: &crate::Type, + handle: Handle, + constants: &Arena, + ) -> Result<(), TypeError> { + use crate::TypeInner as Ti; + match ty.inner { + Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { + let expected = match kind { + crate::ScalarKind::Bool => 1, + _ => 4, + }; + if width != expected { + return Err(TypeError::InvalidWidth(kind, width)); + } + } + Ti::Matrix { width, .. } => { + if width != 4 { + return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); + } + } + Ti::Pointer { base, class: _ } => { + if base >= handle { + return Err(TypeError::UnresolvedBase(base)); + } + } + Ti::Array { base, size, .. } => { + if base >= handle { + return Err(TypeError::UnresolvedBase(base)); + } + if let crate::ArraySize::Constant(const_handle) = size { + match constants.try_get(const_handle) { + Some(&crate::Constant { + inner: crate::ConstantInner::Uint(_), + .. + }) => {} + _ => { + return Err(TypeError::InvalidArraySizeConstant(const_handle)); + } + } + } + } + Ti::Struct { + block: _, + ref members, + } => { + //TODO: check the offsets + for member in members { + if member.ty >= handle { + return Err(TypeError::UnresolvedBase(member.ty)); + } + } + } + Ti::Image { .. } => {} + Ti::Sampler { comparison: _ } => {} + } + Ok(()) + } + fn validate_global_var( &self, var: &crate::GlobalVariable, @@ -454,61 +524,12 @@ impl Validator { pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { // check the types for (handle, ty) in module.types.iter() { - use crate::TypeInner as Ti; - match ty.inner { - Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { - let expected = match kind { - crate::ScalarKind::Bool => 1, - _ => 4, - }; - if width != expected { - return Err(ValidationError::InvalidTypeWidth(kind, width)); - } - } - Ti::Matrix { width, .. } => { - if width != 4 { - return Err(ValidationError::InvalidTypeWidth( - crate::ScalarKind::Float, - width, - )); - } - } - Ti::Pointer { base, class: _ } => { - if base >= handle { - return Err(ValidationError::UnresolvedType(base)); - } - } - Ti::Array { base, size, .. } => { - if base >= handle { - return Err(ValidationError::UnresolvedType(base)); - } - if let crate::ArraySize::Constant(const_handle) = size { - let constant = module - .constants - .try_get(const_handle) - .ok_or(ValidationError::Corrupted)?; - match constant.inner { - crate::ConstantInner::Uint(_) => {} - _ => { - return Err(ValidationError::InvalidArraySizeConstant(const_handle)) - } - } - } - } - Ti::Struct { - block: _, - ref members, - } => { - //TODO: check the offsets - for member in members { - if member.ty >= handle { - return Err(ValidationError::UnresolvedType(member.ty)); - } - } - } - Ti::Image { .. } => {} - Ti::Sampler { comparison: _ } => {} - } + self.validate_type(ty, handle, &module.constants) + .map_err(|error| ValidationError::Type { + handle, + name: ty.name.clone().unwrap_or_default(), + error, + })?; } for (var_handle, var) in module.global_variables.iter() { From 001336b457b5615333bff591d41514c54ba3b143 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 20 Dec 2020 00:49:55 -0500 Subject: [PATCH 0348/2212] Tidy up constants IR --- src/back/glsl/mod.rs | 43 ++++--- src/back/msl/writer.rs | 39 +++--- src/back/spv/layout.rs | 2 +- src/back/spv/writer.rs | 138 +++++++++++---------- src/front/glsl/parser.rs | 41 ++---- src/front/spv/mod.rs | 43 ++++--- src/front/wgsl/mod.rs | 74 +++++------ src/lib.rs | 25 +++- src/proc/mod.rs | 13 +- src/proc/sizer.rs | 5 +- src/proc/typifier.rs | 45 ++----- src/proc/validator.rs | 70 +++++++++-- test-data/simple/module.ron | 12 +- tests/snapshots/snapshots__boids.msl.snap | 12 +- tests/snapshots/snapshots__simple.msl.snap | 1 - tests/snapshots/snapshots__skybox.msl.snap | 4 +- 16 files changed, 318 insertions(+), 249 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index fe807f70e..77bd8dd38 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -50,8 +50,9 @@ use crate::{ }, Arena, ArraySize, BinaryOperator, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, - Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ShaderStage, Statement, - StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, UnaryOperator, + Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ScalarValue, ShaderStage, + Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, + UnaryOperator, }; use features::FeaturesManager; use std::{ @@ -561,7 +562,10 @@ impl<'a, W: Write> Writer<'a, W> { match size { ArraySize::Constant(const_handle) => { match self.module.constants[const_handle].inner { - ConstantInner::Uint(size) => write!(self.out, "{}", size)?, + ConstantInner::Scalar { + width: _, + value: ScalarValue::Uint(size), + } => write!(self.out, "{}", size)?, _ => unreachable!(), } } @@ -866,22 +870,27 @@ impl<'a, W: Write> Writer<'a, W> { /// Adds no newlines or leading/trailing whitespaces fn write_constant(&mut self, constant: &Constant) -> BackendResult { match constant.inner { - // Signed integers don't need anything special - ConstantInner::Sint(int) => write!(self.out, "{}", int)?, - // Unsigned integers need a `u` at the end - // - // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we - // always write it as the extra branch wouldn't have any benefit in readability - ConstantInner::Uint(int) => write!(self.out, "{}u", int)?, - // Floats are written using `Debug` insted of `Display` because it always appends the - // decimal part even it's zero which is needed for a valid glsl float constant - ConstantInner::Float(float) => write!(self.out, "{:?}", float)?, - // Booleans are either `true` or `false` so nothing special needs to be done - ConstantInner::Bool(boolean) => write!(self.out, "{}", boolean)?, + ConstantInner::Scalar { + width: _, + ref value, + } => match *value { + // Signed integers don't need anything special + ScalarValue::Sint(int) => write!(self.out, "{}", int)?, + // Unsigned integers need a `u` at the end + // + // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we + // always write it as the extra branch wouldn't have any benefit in readability + ScalarValue::Uint(int) => write!(self.out, "{}u", int)?, + // Floats are written using `Debug` insted of `Display` because it always appends the + // decimal part even it's zero which is needed for a valid glsl float constant + ScalarValue::Float(float) => write!(self.out, "{:?}", float)?, + // Booleans are either `true` or `false` so nothing special needs to be done + ScalarValue::Bool(boolean) => write!(self.out, "{}", boolean)?, + }, // Composite constant are created using the same syntax as compose // `type(components)` where `components` is a comma separated list of constants - ConstantInner::Composite(ref components) => { - self.write_type(constant.ty)?; + ConstantInner::Composite { ty, ref components } => { + self.write_type(ty)?; write!(self.out, "(")?; // Write the comma separated constants diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 671c8d166..8b85256f4 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -527,25 +527,30 @@ impl Writer { ) -> Result<(), Error> { let constant = &module.constants[handle]; match constant.inner { - crate::ConstantInner::Sint(value) => { - write!(self.out, "{}", value)?; - } - crate::ConstantInner::Uint(value) => { - write!(self.out, "{}", value)?; - } - crate::ConstantInner::Float(value) => { - write!(self.out, "{}", value)?; - if value.fract() == 0.0 { - write!(self.out, ".0")?; + crate::ConstantInner::Scalar { + width: _, + ref value, + } => match *value { + crate::ScalarValue::Sint(value) => { + write!(self.out, "{}", value)?; } - } - crate::ConstantInner::Bool(value) => { - write!(self.out, "{}", value)?; - } - crate::ConstantInner::Composite(ref constituents) => { - let ty_name = &self.names[&NameKey::Type(constant.ty)]; + crate::ScalarValue::Uint(value) => { + write!(self.out, "{}", value)?; + } + crate::ScalarValue::Float(value) => { + write!(self.out, "{}", value)?; + if value.fract() == 0.0 { + write!(self.out, ".0")?; + } + } + crate::ScalarValue::Bool(value) => { + write!(self.out, "{}", value)?; + } + }, + crate::ConstantInner::Composite { ty, ref components } => { + let ty_name = &self.names[&NameKey::Type(ty)]; write!(self.out, "{}(", ty_name)?; - for (i, &handle) in constituents.iter().enumerate() { + for (i, &handle) in components.iter().enumerate() { if i != 0 { write!(self.out, ", ")?; } diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index 006e78531..bba369741 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -1,4 +1,4 @@ -use crate::back::spv::{Instruction, LogicalLayout, PhysicalLayout}; +use super::{Instruction, LogicalLayout, PhysicalLayout}; use spirv::*; use std::iter; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index c91435d67..12299e66b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -695,76 +695,75 @@ impl Writer { let arena = &ir_module.types; let instruction = match constant.inner { - crate::ConstantInner::Sint(val) => { - let ty = &ir_module.types[constant.ty]; - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; - - match ty.inner { - crate::TypeInner::Scalar { kind: _, width } => match width { - 4 => super::instructions::instruction_constant(type_id, id, &[val as u32]), - 8 => { - let (low, high) = ((val >> 32) as u32, val as u32); - super::instructions::instruction_constant(type_id, id, &[low, high]) - } - _ => unreachable!(), - }, - _ => unreachable!(), + crate::ConstantInner::Scalar { width, ref value } => { + let type_id = self.get_type_id( + arena, + LookupType::Local(LocalType::Scalar { + kind: value.scalar_kind(), + width, + }), + )?; + let (solo, pair); + match *value { + crate::ScalarValue::Sint(val) => { + let words = match width { + 4 => { + solo = [val as u32]; + &solo[..] + } + 8 => { + pair = [(val >> 32) as u32, val as u32]; + &pair + } + _ => unreachable!(), + }; + super::instructions::instruction_constant(type_id, id, words) + } + crate::ScalarValue::Uint(val) => { + let words = match width { + 4 => { + solo = [val as u32]; + &solo[..] + } + 8 => { + pair = [(val >> 32) as u32, val as u32]; + &pair + } + _ => unreachable!(), + }; + super::instructions::instruction_constant(type_id, id, words) + } + crate::ScalarValue::Float(val) => { + let words = match width { + 4 => { + solo = [(val as f32).to_bits()]; + &solo[..] + } + 8 => { + let bits = f64::to_bits(val); + pair = [(bits >> 32) as u32, bits as u32]; + &pair + } + _ => unreachable!(), + }; + super::instructions::instruction_constant(type_id, id, words) + } + crate::ScalarValue::Bool(true) => { + super::instructions::instruction_constant_true(type_id, id) + } + crate::ScalarValue::Bool(false) => { + super::instructions::instruction_constant_false(type_id, id) + } } } - crate::ConstantInner::Uint(val) => { - let ty = &ir_module.types[constant.ty]; - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; - - match ty.inner { - crate::TypeInner::Scalar { kind: _, width } => match width { - 4 => super::instructions::instruction_constant(type_id, id, &[val as u32]), - 8 => { - let (low, high) = ((val >> 32) as u32, val as u32); - super::instructions::instruction_constant(type_id, id, &[low, high]) - } - _ => unreachable!(), - }, - _ => unreachable!(), - } - } - crate::ConstantInner::Float(val) => { - let ty = &ir_module.types[constant.ty]; - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; - - match ty.inner { - crate::TypeInner::Scalar { kind: _, width } => match width { - 4 => super::instructions::instruction_constant( - type_id, - id, - &[(val as f32).to_bits()], - ), - 8 => { - let bits = f64::to_bits(val); - let (low, high) = ((bits >> 32) as u32, bits as u32); - super::instructions::instruction_constant(type_id, id, &[low, high]) - } - _ => unreachable!(), - }, - _ => unreachable!(), - } - } - crate::ConstantInner::Bool(val) => { - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; - - if val { - super::instructions::instruction_constant_true(type_id, id) - } else { - super::instructions::instruction_constant_false(type_id, id) - } - } - crate::ConstantInner::Composite(ref constituents) => { - let mut constituent_ids = Vec::with_capacity(constituents.len()); - for constituent in constituents.iter() { + crate::ConstantInner::Composite { ty, ref components } => { + let mut constituent_ids = Vec::with_capacity(components.len()); + for constituent in components.iter() { let constituent_id = self.get_constant_id(*constituent, &ir_module)?; constituent_ids.push(constituent_id); } - let type_id = self.get_type_id(arena, LookupType::Handle(constant.ty))?; + let type_id = self.get_type_id(arena, LookupType::Handle(ty))?; super::instructions::instruction_constant_composite( type_id, id, @@ -1115,7 +1114,16 @@ impl Writer { crate::Expression::Constant(handle) => { let var = &ir_module.constants[handle]; let id = self.get_constant_id(handle, ir_module)?; - Ok((RawExpression::Value(id), LookupType::Handle(var.ty))) + let lookup_type = match var.inner { + crate::ConstantInner::Scalar { width, ref value } => { + LookupType::Local(LocalType::Scalar { + kind: value.scalar_kind(), + width, + }) + } + crate::ConstantInner::Composite { ty, components: _ } => LookupType::Handle(ty), + }; + Ok((RawExpression::Value(id), lookup_type)) } crate::Expression::Compose { ty, ref components } => { let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty))?; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0328060bb..adb405310 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -10,7 +10,7 @@ pomelo! { Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, EntryPoint, Expression, Function, GlobalVariable, Handle, Interpolation, - LocalVariable, SampleLevel, ScalarKind, + LocalVariable, SampleLevel, ScalarValue, Statement, StorageAccess, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, }; @@ -165,18 +165,13 @@ pomelo! { primary_expression ::= variable_identifier; primary_expression ::= IntConstant(i) { - let ty = extra.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - } - }); let ch = extra.module.constants.fetch_or_append(Constant { name: None, specialization: None, - ty, - inner: ConstantInner::Sint(i.1) + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(i.1), + }, }); ExpressionRule::from_expression( extra.context.expressions.append(Expression::Constant(ch)) @@ -184,36 +179,26 @@ pomelo! { } // primary_expression ::= UintConstant; primary_expression ::= FloatConstant(f) { - let ty = extra.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Float, - width: 4, - } - }); let ch = extra.module.constants.fetch_or_append(Constant { name: None, specialization: None, - ty, - inner: ConstantInner::Float(f.1 as f64) + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(f.1 as f64), + }, }); ExpressionRule::from_expression( extra.context.expressions.append(Expression::Constant(ch)) ) } primary_expression ::= BoolConstant(b) { - let ty = extra.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Bool, - width: 4, - } - }); let ch = extra.module.constants.fetch_or_append(Constant { name: None, specialization: None, - ty, - inner: ConstantInner::Bool(b.1) + inner: ConstantInner::Scalar { + width: 1, + value: ScalarValue::Bool(b.1) + }, }); ExpressionRule::from_expression( extra.context.expressions.append(Expression::Constant(ch)) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 8b0bf98e0..5b7cc15c7 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -624,8 +624,14 @@ impl> Parser { let index = match expressions[index_expr.handle] { crate::Expression::Constant(const_handle) => { match const_arena[const_handle].inner { - crate::ConstantInner::Uint(v) => v as u32, - crate::ConstantInner::Sint(v) => v as u32, + crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(v), + } => v as u32, + crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Sint(v), + } => v as u32, _ => { return Err(Error::InvalidAccess(index_expr.handle)) } @@ -2168,7 +2174,10 @@ impl> Parser { } else { 0 }; - crate::ConstantInner::Uint((u64::from(high) << 32) | u64::from(low)) + crate::ConstantInner::Scalar { + width, + value: crate::ScalarValue::Uint((u64::from(high) << 32) | u64::from(low)), + } } crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, @@ -2184,7 +2193,12 @@ impl> Parser { } Ordering::Equal => 0, }; - crate::ConstantInner::Sint(((u64::from(high) << 32) | u64::from(low)) as i64) + crate::ConstantInner::Scalar { + width, + value: crate::ScalarValue::Sint( + ((u64::from(high) << 32) | u64::from(low)) as i64, + ), + } } crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, @@ -2200,7 +2214,10 @@ impl> Parser { } _ => return Err(Error::InvalidTypeWidth(u32::from(width))), }; - crate::ConstantInner::Float(extended) + crate::ConstantInner::Scalar { + width, + value: crate::ScalarValue::Float(extended), + } } _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; @@ -2211,7 +2228,6 @@ impl> Parser { name: self.future_decor.remove(&id).and_then(|dec| dec.name), specialization: None, //TODO inner, - ty, }), type_id, }, @@ -2229,15 +2245,13 @@ impl> Parser { let type_id = self.next()?; let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; - let id = self.next()?; - let constituents_count = inst.wc - 3; - let mut constituents = Vec::with_capacity(constituents_count as usize); - for _ in 0..constituents_count { - let constituent_id = self.next()?; - let constant = self.lookup_constant.lookup(constituent_id)?; - constituents.push(constant.handle); + let mut components = Vec::with_capacity(inst.wc as usize - 3); + for _ in 0..components.capacity() { + let component_id = self.next()?; + let constant = self.lookup_constant.lookup(component_id)?; + components.push(constant.handle); } self.lookup_constant.insert( @@ -2246,8 +2260,7 @@ impl> Parser { handle: module.constants.append(crate::Constant { name: self.future_decor.remove(&id).and_then(|dec| dec.name), specialization: None, - inner: crate::ConstantInner::Composite(constituents), - ty, + inner: crate::ConstantInner::Composite { ty, components }, }), type_id, }, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5235f8e5d..578e94696 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -369,16 +369,14 @@ impl Parser { } } - fn get_constant_inner( - word: &str, - ) -> Result<(crate::ConstantInner, crate::ScalarKind), Error<'_>> { + fn get_scalar_value(word: &str) -> Result> { if word.contains('.') { word.parse() - .map(|f| (crate::ConstantInner::Float(f), crate::ScalarKind::Float)) + .map(crate::ScalarValue::Float) .map_err(|err| Error::BadFloat(word, err)) } else { word.parse() - .map(|i| (crate::ConstantInner::Sint(i), crate::ScalarKind::Sint)) + .map(crate::ScalarValue::Sint) .map_err(|err| Error::BadInteger(word, err)) } } @@ -688,16 +686,24 @@ impl Parser { let inner = match lexer.peek() { Token::Word("true") => { let _ = lexer.next(); - crate::ConstantInner::Bool(true) + crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(true), + } } Token::Word("false") => { let _ = lexer.next(); - crate::ConstantInner::Bool(false) + crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(false), + } } Token::Number(word) => { let _ = lexer.next(); - let (inner, _) = Self::get_constant_inner(word)?; - inner + crate::ConstantInner::Scalar { + width: 4, + value: Self::get_scalar_value(word)?, + } } _ => { let (composite_ty, _access) = @@ -717,14 +723,16 @@ impl Parser { self.parse_const_expression(lexer, ty, type_arena, const_arena)?; components.push(component); } - crate::ConstantInner::Composite(components) + crate::ConstantInner::Composite { + ty: self_ty, + components, + } } }; let handle = const_arena.fetch_or_append(crate::Constant { name: None, specialization: None, inner, - ty: self_ty, }); self.scopes.pop(); Ok(handle) @@ -747,14 +755,10 @@ impl Parser { let handle = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, - inner: crate::ConstantInner::Bool(true), - ty: ctx.types.fetch_or_append(crate::Type { - name: None, - inner: crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: 1, - }, - }), + inner: crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(true), + }, }); crate::Expression::Constant(handle) } @@ -762,27 +766,19 @@ impl Parser { let handle = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, - inner: crate::ConstantInner::Bool(false), - ty: ctx.types.fetch_or_append(crate::Type { - name: None, - inner: crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: 1, - }, - }), + inner: crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(false), + }, }); crate::Expression::Constant(handle) } Token::Number(word) => { - let (inner, kind) = Self::get_constant_inner(word)?; + let value = Self::get_scalar_value(word)?; let handle = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, - inner, - ty: ctx.types.fetch_or_append(crate::Type { - name: None, - inner: crate::TypeInner::Scalar { kind, width: 4 }, - }), + inner: crate::ConstantInner::Scalar { width: 4, value }, }); crate::Expression::Constant(handle) } @@ -1304,14 +1300,10 @@ impl Parser { let const_handle = const_arena.fetch_or_append(crate::Constant { name: None, specialization: None, - inner: crate::ConstantInner::Uint(value as u64), - ty: type_arena.fetch_or_append(crate::Type { - name: None, - inner: crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: 4, - }, - }), + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(value as u64), + }, }); crate::ArraySize::Constant(const_handle) } diff --git a/src/lib.rs b/src/lib.rs index b9e06d0d4..2719c40cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -396,7 +396,17 @@ pub struct Constant { pub name: Option, pub specialization: Option, pub inner: ConstantInner, - pub ty: Handle, +} + +/// A literal scalar value, used in constants. +#[derive(Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum ScalarValue { + Sint(i64), + Uint(u64), + Float(f64), + Bool(bool), } /// Additional information, dependendent on the kind of constant. @@ -404,11 +414,14 @@ pub struct Constant { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ConstantInner { - Sint(i64), - Uint(u64), - Float(f64), - Bool(bool), - Composite(Vec>), + Scalar { + width: Bytes, + value: ScalarValue, + }, + Composite { + ty: Handle, + components: Vec>, + }, } /// Describes how an input/output variable is to be bound. diff --git a/src/proc/mod.rs b/src/proc/mod.rs index ee0baeada..fae3ba209 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -15,7 +15,7 @@ pub use interface::{Interface, Visitor}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use sizer::Sizer; pub use terminator::ensure_block_returns; -pub use typifier::{check_constant_type, ResolveContext, ResolveError, Typifier}; +pub use typifier::{ResolveContext, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; impl From for super::ScalarKind { @@ -58,6 +58,17 @@ impl From for super::ScalarKind { } } +impl crate::ScalarValue { + pub fn scalar_kind(&self) -> crate::ScalarKind { + match *self { + Self::Uint(_) => crate::ScalarKind::Uint, + Self::Sint(_) => crate::ScalarKind::Sint, + Self::Float(_) => crate::ScalarKind::Float, + Self::Bool(_) => crate::ScalarKind::Bool, + } + } +} + impl crate::TypeInner { pub fn scalar_kind(&self) -> Option { match *self { diff --git a/src/proc/sizer.rs b/src/proc/sizer.rs index a9c58f091..8c17e48f6 100644 --- a/src/proc/sizer.rs +++ b/src/proc/sizer.rs @@ -28,7 +28,10 @@ impl Sizer { Ti::Array { base, size, stride } => { let count = match size { crate::ArraySize::Constant(handle) => match constants[handle].inner { - crate::ConstantInner::Uint(value) => value as u32, + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(value), + } => value as u32, ref other => unreachable!("Unexpected array size {:?}", other), }, crate::ArraySize::Dynamic => 1, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 6862773c5..f29fa12f1 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -170,7 +170,15 @@ impl Typifier { }) } }, - crate::Expression::Constant(h) => Resolution::Handle(ctx.constants[h].ty), + crate::Expression::Constant(h) => match ctx.constants[h].inner { + crate::ConstantInner::Scalar { width, ref value } => { + Resolution::Value(crate::TypeInner::Scalar { + kind: value.scalar_kind(), + width, + }) + } + crate::ConstantInner::Composite { ty, components: _ } => Resolution::Handle(ty), + }, crate::Expression::Compose { ty, .. } => Resolution::Handle(ty), crate::Expression::FunctionArgument(index) => { Resolution::Handle(ctx.arguments[index as usize].ty) @@ -458,38 +466,3 @@ impl Typifier { Ok(()) } } - -pub fn check_constant_type(inner: &crate::ConstantInner, type_inner: &crate::TypeInner) -> bool { - match (inner, type_inner) { - ( - crate::ConstantInner::Sint(_), - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Sint, - width: _, - }, - ) => true, - ( - crate::ConstantInner::Uint(_), - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: _, - }, - ) => true, - ( - crate::ConstantInner::Float(_), - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: _, - }, - ) => true, - ( - crate::ConstantInner::Bool(_), - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: _, - }, - ) => true, - (crate::ConstantInner::Composite(_inner), _) => true, // TODO recursively check composite types - (_, _) => false, - } -} diff --git a/src/proc/validator.rs b/src/proc/validator.rs index ae81b724c..51ddc46f0 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -23,6 +23,14 @@ pub enum TypeError { InvalidArraySizeConstant(Handle), } +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +pub enum ConstantError { + #[error("The type doesn't match the constant")] + InvalidType, + #[error("The component handle {0:?} can not be resolved")] + UnresolvedComponent(Handle), +} + #[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum GlobalVariableError { #[error("Usage isn't compatible with the storage class")] @@ -94,6 +102,12 @@ pub enum ValidationError { name: String, error: TypeError, }, + #[error("Constant {handle:?} '{name}' is invalid: {error:?}")] + Constant { + handle: Handle, + name: String, + error: ConstantError, + }, #[error("Global variable {handle:?} '{name}' is invalid: {error:?}")] GlobalVariable { handle: Handle, @@ -227,6 +241,13 @@ impl Validator { } } + fn check_width(kind: crate::ScalarKind, width: crate::Bytes) -> bool { + match kind { + crate::ScalarKind::Bool => width == 1, + _ => width == 4, + } + } + fn validate_type( &self, ty: &crate::Type, @@ -236,16 +257,12 @@ impl Validator { use crate::TypeInner as Ti; match ty.inner { Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { - let expected = match kind { - crate::ScalarKind::Bool => 1, - _ => 4, - }; - if width != expected { + if !Self::check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } } Ti::Matrix { width, .. } => { - if width != 4 { + if !Self::check_width(crate::ScalarKind::Float, width) { return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); } } @@ -261,7 +278,11 @@ impl Validator { if let crate::ArraySize::Constant(const_handle) = size { match constants.try_get(const_handle) { Some(&crate::Constant { - inner: crate::ConstantInner::Uint(_), + inner: + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(_), + }, .. }) => {} _ => { @@ -287,6 +308,32 @@ impl Validator { Ok(()) } + fn validate_constant( + &self, + handle: Handle, + constants: &Arena, + _types: &Arena, + ) -> Result<(), ConstantError> { + let con = &constants[handle]; + match con.inner { + crate::ConstantInner::Scalar { width, ref value } => { + if !Self::check_width(value.scalar_kind(), width) { + return Err(ConstantError::InvalidType); + } + } + crate::ConstantInner::Composite { + ty: _, + ref components, + } => { + if let Some(&comp) = components.iter().find(|&&comp| handle <= comp) { + return Err(ConstantError::UnresolvedComponent(comp)); + } + //TODO + } + } + Ok(()) + } + fn validate_global_var( &self, var: &crate::GlobalVariable, @@ -522,7 +569,6 @@ impl Validator { /// Check the given module to be valid. pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { - // check the types for (handle, ty) in module.types.iter() { self.validate_type(ty, handle, &module.constants) .map_err(|error| ValidationError::Type { @@ -532,6 +578,14 @@ impl Validator { })?; } + for (handle, constant) in module.constants.iter() { + self.validate_constant(handle, &module.constants, &module.types) + .map_err(|error| ValidationError::Constant { + handle, + name: constant.name.clone().unwrap_or_default(), + error, + })?; + } for (var_handle, var) in module.global_variables.iter() { self.validate_global_var(var, &module.types) .map_err(|error| ValidationError::GlobalVariable { diff --git a/test-data/simple/module.ron b/test-data/simple/module.ron index 8fa007ef7..b99b24575 100644 --- a/test-data/simple/module.ron +++ b/test-data/simple/module.ron @@ -32,14 +32,18 @@ ( name: None, specialization: None, - inner: Float(1), - ty: 3, + inner: Scalar( + width: 4, + value: Float(1), + ), ), ( name: None, specialization: None, - inner: Float(0), - ty: 3, + inner: Scalar( + width: 4, + value: Float(0), + ), ), ], global_variables: [ diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap index 1c1b6800f..358a97386 100644 --- a/tests/snapshots/snapshots__boids.msl.snap +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -21,12 +21,12 @@ struct SimParams { type2 rule2Scale; type2 rule3Scale; }; -typedef uint type3; -typedef Particle type4[5]; +typedef Particle type3[5]; struct Particles { - type4 particles; + type3 particles; }; -typedef metal::uint3 type5; +typedef metal::uint3 type4; +typedef uint type5; typedef int type6; struct main1Input { @@ -60,7 +60,7 @@ kernel void main3( constant SimParams& params [[buffer(0)]], constant Particles& particlesA [[buffer(1)]], device Particles& particlesB [[buffer(2)]], - type5 gl_GlobalInvocationID [[thread_position_in_grid]] + type4 gl_GlobalInvocationID [[thread_position_in_grid]] ) { type vPos; type vVel; @@ -71,7 +71,7 @@ kernel void main3( type6 cVelCount = 0; type pos1; type vel1; - type3 i = 0; + type5 i = 0; if (gl_GlobalInvocationID.x >= static_cast(5)) { } vPos = particlesA.particles[gl_GlobalInvocationID.x].pos; diff --git a/tests/snapshots/snapshots__simple.msl.snap b/tests/snapshots/snapshots__simple.msl.snap index 0bf6130e9..1102c4ea8 100644 --- a/tests/snapshots/snapshots__simple.msl.snap +++ b/tests/snapshots/snapshots__simple.msl.snap @@ -6,7 +6,6 @@ expression: msl #include typedef metal::float4 type; -typedef int type1; struct main1Input { }; diff --git a/tests/snapshots/snapshots__skybox.msl.snap b/tests/snapshots/snapshots__skybox.msl.snap index e4a88144c..8bfaad4ca 100644 --- a/tests/snapshots/snapshots__skybox.msl.snap +++ b/tests/snapshots/snapshots__skybox.msl.snap @@ -14,8 +14,8 @@ struct Data { type3 view; }; typedef int type4; -typedef float type5; -typedef metal::float3x3 type6; +typedef metal::float3x3 type5; +typedef float type6; typedef metal::texturecube type7; typedef metal::sampler type8; typedef metal::int3 type9; From 3f7ee8cd6ef9d37db73a5421f55755420cd9deec Mon Sep 17 00:00:00 2001 From: Capucho Date: Tue, 22 Dec 2020 16:06:23 +0000 Subject: [PATCH 0349/2212] Generate locations with fixed naming scheme for linking --- src/back/glsl/mod.rs | 62 ++++++++++++------- .../snapshots__quad-Fragment.glsl.snap | 6 +- .../snapshots__quad-Vertex.glsl.snap | 10 +-- .../snapshots__skybox-Fragment.glsl.snap | 6 +- .../snapshots__skybox-Vertex.glsl.snap | 8 +-- 5 files changed, 54 insertions(+), 38 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 77bd8dd38..a8c41faf8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -48,11 +48,11 @@ use crate::{ CallGraph, CallGraphBuilder, Interface, NameKey, Namer, ResolveContext, ResolveError, Typifier, Visitor, }, - Arena, ArraySize, BinaryOperator, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, - DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, - Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ScalarValue, ShaderStage, - Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, - UnaryOperator, + Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, + ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, + ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ScalarValue, + ShaderStage, Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, + TypeInner, UnaryOperator, }; use features::FeaturesManager; use std::{ @@ -713,12 +713,40 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important - let name = &self.names[&NameKey::GlobalVariable(handle)]; - writeln!(self.out, " {};", name)?; + writeln!(self.out, " {};", self.get_global_name(handle, global))?; Ok(()) } + /// Helper method used to get a name for a global + /// + /// Globals have different naming schemes depending on their binding: + /// - Globals without bindings use the name from the [`Namer`](crate::proc::Namer) + /// - Globals with builtin bindings get the from [`glsl_built_in`](glsl_built_in) + /// - Globals with location bindings are named `_location_X` where `X` is the location + /// - Globals with resource binding are named `_group_X_binding_Y` where `X` + /// is the group and `Y` is the binding + fn get_global_name(&self, handle: Handle, global: &GlobalVariable) -> String { + match global.binding { + Some(Binding::Location(location)) => { + format!( + " _location_{}{}", + location, + match (self.options.entry_point.0, global.class) { + (ShaderStage::Fragment, StorageClass::Input) => "_vs", + (ShaderStage::Vertex, StorageClass::Output) => "_vs", + _ => "", + } + ) + } + Some(Binding::Resource { group, binding }) => { + format!(" _group_{}_binding_{}", group, binding) + } + Some(Binding::BuiltIn(built_in)) => glsl_built_in(built_in).to_string(), + None => self.names[&NameKey::GlobalVariable(handle)].clone(), + } + } + /// Helper method used to write functions (both entry points and regular functions) /// /// # Notes @@ -1156,23 +1184,11 @@ impl<'a, W: Write> Writer<'a, W> { Expression::FunctionArgument(pos) => { write!(self.out, "{}", ctx.get_arg(pos, &self.names))? } - // Global variables need some special work, if they are a builtin we write the glsl - // variable name produced by `glsl_built_in` otherwise we write the global name - // produced by the `Namer` + // Global variables need some special work for their name but + // `get_global_name` does the work for us Expression::GlobalVariable(handle) => { - if let Some(crate::Binding::BuiltIn(built_in)) = - self.module.global_variables[handle].binding - { - // Global is a builtin so get the glsl variable name - write!(self.out, "{}", glsl_built_in(built_in))? - } else { - // Global isn't a builtin so just write the name - write!( - self.out, - "{}", - &self.names[&NameKey::GlobalVariable(handle)] - )? - } + let global = &self.module.global_variables[handle]; + write!(self.out, "{}", self.get_global_name(handle, global))? } // A local is written as it's name Expression::LocalVariable(handle) => { diff --git a/tests/snapshots/snapshots__quad-Fragment.glsl.snap b/tests/snapshots/snapshots__quad-Fragment.glsl.snap index 4bbecf0de..75d517f2f 100644 --- a/tests/snapshots/snapshots__quad-Fragment.glsl.snap +++ b/tests/snapshots/snapshots__quad-Fragment.glsl.snap @@ -8,13 +8,13 @@ precision highp float; -in vec2 v_uv1; +in vec2 _location_0_vs; uniform sampler2D u_texture; -out vec4 o_color; +out vec4 _location_0; void main() { - o_color = texture(u_texture, vec2(v_uv1)); + _location_0 = texture( _group_0_binding_0, vec2( _location_0_vs)); return; } diff --git a/tests/snapshots/snapshots__quad-Vertex.glsl.snap b/tests/snapshots/snapshots__quad-Vertex.glsl.snap index eb95684f4..d79cd676a 100644 --- a/tests/snapshots/snapshots__quad-Vertex.glsl.snap +++ b/tests/snapshots/snapshots__quad-Vertex.glsl.snap @@ -8,14 +8,14 @@ precision highp float; -in vec2 a_pos; -in vec2 a_uv; -out vec2 v_uv; +in vec2 _location_0; +in vec2 _location_1; +out vec2 _location_0_vs; void main() { - v_uv = a_uv; - gl_Position = vec4((1.2 * a_pos), 0.0, 1.0); + _location_0_vs = _location_1; + gl_Position = vec4((1.2 * _location_0), 0.0, 1.0); return; } diff --git a/tests/snapshots/snapshots__skybox-Fragment.glsl.snap b/tests/snapshots/snapshots__skybox-Fragment.glsl.snap index 54bf9ef72..24583ee9f 100644 --- a/tests/snapshots/snapshots__skybox-Fragment.glsl.snap +++ b/tests/snapshots/snapshots__skybox-Fragment.glsl.snap @@ -13,12 +13,12 @@ struct Data { }; uniform samplerCube r_texture; -in vec3 in_uv; -out vec4 out_color; +in vec3 _location_0_vs; +out vec4 _location_0; void main() { - out_color = texture(r_texture, vec3(in_uv)); + _location_0 = texture( _group_0_binding_1, vec3( _location_0_vs)); return; } diff --git a/tests/snapshots/snapshots__skybox-Vertex.glsl.snap b/tests/snapshots/snapshots__skybox-Vertex.glsl.snap index 2dc3726d0..14efd3e49 100644 --- a/tests/snapshots/snapshots__skybox-Vertex.glsl.snap +++ b/tests/snapshots/snapshots__skybox-Vertex.glsl.snap @@ -12,8 +12,8 @@ struct Data { mat4x4 view; }; -out vec3 out_uv; -uniform Data r_data; +out vec3 _location_0_vs; +uniform Data _group_0_binding_0; void main() { int tmp1_; @@ -22,8 +22,8 @@ void main() { tmp1_ = (int(gl_VertexID) / 2); tmp2_ = (int(gl_VertexID) & 1); - unprojected = (r_data.proj_inv * vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0)); - out_uv = (transpose(mat3x3(vec3(r_data.view[0][0], r_data.view[0][1], r_data.view[0][2]), vec3(r_data.view[1][0], r_data.view[1][1], r_data.view[1][2]), vec3(r_data.view[2][0], r_data.view[2][1], r_data.view[2][2]))) * vec3(unprojected[0], unprojected[1], unprojected[2])); + unprojected = ( _group_0_binding_0.proj_inv * vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0)); + _location_0_vs = (transpose(mat3x3(vec3( _group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3( _group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3( _group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(unprojected[0], unprojected[1], unprojected[2])); gl_Position = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); return; } From 511000d0228e0e537b02c136e5dea93a8561f719 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 14 Dec 2020 08:16:15 +0100 Subject: [PATCH 0350/2212] [glsl-in] Extract function logic out of parser --- src/front/glsl/functions.rs | 134 ++++++++++++++++++++++++++++++++++++ src/front/glsl/mod.rs | 1 + src/front/glsl/parser.rs | 102 ++------------------------- 3 files changed, 140 insertions(+), 97 deletions(-) create mode 100644 src/front/glsl/functions.rs diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs new file mode 100644 index 000000000..687a15f74 --- /dev/null +++ b/src/front/glsl/functions.rs @@ -0,0 +1,134 @@ +use crate::{Block, Expression, Function, SampleLevel, TypeInner, proc::{ensure_block_returns, Typifier}}; + +use super::{ast::*, error::ErrorKind}; + +impl Program { + pub fn function_call(&mut self, fc: FunctionCall) -> Result { + match fc.kind { + FunctionCallKind::TypeConstructor(ty) => { + let h = if fc.args.len() == 1 { + let kind = self.module.types[ty].inner.scalar_kind().ok_or( + ErrorKind::SemanticError("Can only cast to scalar or vector"), + )?; + self.context.expressions.append(Expression::As { + kind, + expr: fc.args[0].expression, + convert: true, + }) + } else { + self.context.expressions.append(Expression::Compose { + ty, + components: fc.args.iter().map(|a| a.expression).collect(), + }) + }; + Ok(ExpressionRule { + expression: h, + statements: fc + .args + .into_iter() + .map(|a| a.statements) + .flatten() + .collect(), + sampler: None, + }) + } + FunctionCallKind::Function(name) => { + match name.as_str() { + "sampler2D" => { + //TODO: check args len + Ok(ExpressionRule { + expression: fc.args[0].expression, + sampler: Some(fc.args[1].expression), + statements: fc + .args + .into_iter() + .map(|a| a.statements) + .flatten() + .collect(), + }) + } + "texture" => { + //TODO: check args len + if let Some(sampler) = fc.args[0].sampler { + Ok(ExpressionRule { + expression: self.context.expressions.append( + Expression::ImageSample { + image: fc.args[0].expression, + sampler, + coordinate: fc.args[1].expression, + array_index: None, //TODO + offset: None, //TODO + level: SampleLevel::Auto, + depth_ref: None, + }, + ), + sampler: None, + statements: fc + .args + .into_iter() + .map(|a| a.statements) + .flatten() + .collect(), + }) + } else { + return Err(ErrorKind::SemanticError("Bad call to texture")); + } + } + _ => { + return Err(ErrorKind::NotImplemented("Function call")); + } + } + } + } + } + + pub fn add_function_prelude(&mut self) { + for (var_handle, var) in self.module.global_variables.iter() { + if let Some(name) = var.name.as_ref() { + let expr = self + .context + .expressions + .append(Expression::GlobalVariable(var_handle)); + self.context + .lookup_global_var_exps + .insert(name.clone(), expr); + } else { + let ty = &self.module.types[var.ty]; + // anonymous structs + if let TypeInner::Struct { + block: _, + ref members, + } = ty.inner + { + let base = self + .context + .expressions + .append(Expression::GlobalVariable(var_handle)); + for (idx, member) in members.iter().enumerate() { + if let Some(name) = member.name.as_ref() { + let exp = self.context.expressions.append(Expression::AccessIndex { + base, + index: idx as u32, + }); + self.context + .lookup_global_var_exps + .insert(name.clone(), exp); + } + } + } + } + } + } + + pub fn function_definition(&mut self, mut f: Function, mut block: Block) -> Function { + std::mem::swap(&mut f.expressions, &mut self.context.expressions); + std::mem::swap(&mut f.local_variables, &mut self.context.local_variables); + self.context.clear_scopes(); + self.context.lookup_global_var_exps.clear(); + self.context.typifier = Typifier::new(); + ensure_block_returns(&mut block); + f.body = block; + f.fill_global_use(&self.module.global_variables); + f + } +} diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 466101182..9711aca90 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -20,6 +20,7 @@ mod parser_tests; mod token; mod types; mod variables; +mod functions; pub fn parse_str( source: &str, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index adb405310..87d3c461f 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -6,11 +6,10 @@ pomelo! { %include { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{ - proc::{ensure_block_returns, Typifier}, Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, EntryPoint, Expression, Function, GlobalVariable, Handle, Interpolation, - LocalVariable, SampleLevel, ScalarValue, + LocalVariable, ScalarValue, Statement, StorageAccess, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, }; @@ -232,63 +231,7 @@ pomelo! { integer_expression ::= expression; function_call ::= function_call_or_method(fc) { - match fc.kind { - FunctionCallKind::TypeConstructor(ty) => { - let h = if fc.args.len() == 1 { - let kind = extra.module.types[ty].inner - .scalar_kind() - .ok_or(ErrorKind::SemanticError("Can only cast to scalar or vector"))?; - extra.context.expressions.append(Expression::As { - kind, - expr: fc.args[0].expression, - convert: true, - }) - } else { - extra.context.expressions.append(Expression::Compose { - ty, - components: fc.args.iter().map(|a| a.expression).collect(), - }) - }; - ExpressionRule { - expression: h, - statements: fc.args.into_iter().map(|a| a.statements).flatten().collect(), - sampler: None - } - } - FunctionCallKind::Function(name) => { - match name.as_str() { - "sampler2D" => { - //TODO: check args len - ExpressionRule{ - expression: fc.args[0].expression, - sampler: Some(fc.args[1].expression), - statements: fc.args.into_iter().map(|a| a.statements).flatten().collect(), - } - } - "texture" => { - //TODO: check args len - if let Some(sampler) = fc.args[0].sampler { - ExpressionRule{ - expression: extra.context.expressions.append(Expression::ImageSample { - image: fc.args[0].expression, - sampler, - coordinate: fc.args[1].expression, - array_index: None, //TODO - offset: None, //TODO - level: SampleLevel::Auto, - depth_ref: None, - }), - sampler: None, - statements: fc.args.into_iter().map(|a| a.statements).flatten().collect(), - } - } else { - return Err(ErrorKind::SemanticError("Bad call to texture")); - } - } - _ => { return Err(ErrorKind::NotImplemented("Function call")); } - } - } - } + extra.function_call(fc)? } function_call_or_method ::= function_call_generic; function_call_generic ::= function_call_header_with_parameters(h) RightParen { @@ -995,34 +938,7 @@ pomelo! { // function function_prototype ::= function_declarator(f) RightParen { - // prelude, add global var expressions - for (var_handle, var) in extra.module.global_variables.iter() { - if let Some(name) = var.name.as_ref() { - let exp = extra.context.expressions.append( - Expression::GlobalVariable(var_handle) - ); - extra.context.lookup_global_var_exps.insert(name.clone(), exp); - } else { - let ty = &extra.module.types[var.ty]; - // anonymous structs - if let TypeInner::Struct { block: _, ref members } = ty.inner { - let base = extra.context.expressions.append( - Expression::GlobalVariable(var_handle) - ); - for (idx, member) in members.iter().enumerate() { - if let Some(name) = member.name.as_ref() { - let exp = extra.context.expressions.append( - Expression::AccessIndex{ - base, - index: idx as u32, - } - ); - extra.context.lookup_global_var_exps.insert(name.clone(), exp); - } - } - } - } - } + extra.add_function_prelude(); f } function_declarator ::= function_header; @@ -1116,16 +1032,8 @@ pomelo! { } } - function_definition ::= function_prototype(mut f) compound_statement_no_new_scope(mut cs) { - std::mem::swap(&mut f.expressions, &mut extra.context.expressions); - std::mem::swap(&mut f.local_variables, &mut extra.context.local_variables); - extra.context.clear_scopes(); - extra.context.lookup_global_var_exps.clear(); - extra.context.typifier = Typifier::new(); - ensure_block_returns(&mut cs); - f.body = cs; - f.fill_global_use(&extra.module.global_variables); - f + function_definition ::= function_prototype(f) compound_statement_no_new_scope(cs) { + extra.function_definition(f, cs) }; } From 9a51d82c3922eb4a5053ab591f5f8e5f44ec722a Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Fri, 18 Dec 2020 10:44:29 +0000 Subject: [PATCH 0351/2212] [glsl-in] Implement ceil Related to #330 --- src/back/spv/instructions.rs | 18 ++++++++++++++++++ src/back/spv/writer.rs | 33 +++++++++++++++++++++++++++++++++ src/front/glsl/functions.rs | 27 +++++++++++++++++++++++---- 3 files changed, 74 insertions(+), 4 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 7df29ec7f..e958febc5 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -58,6 +58,24 @@ pub(super) fn instruction_ext_inst_import(id: Word, name: &str) -> Instruction { instruction } +pub(super) fn instruction_ext_inst( + result_type_id: Word, + id: Word, + set_id: Word, + ext_instruction: u32, + operands: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::ExtInst); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(set_id); + instruction.add_operand(ext_instruction); + for operand in operands { + instruction.add_operand(*operand) + } + instruction +} + // // Mode-Setting Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 12299e66b..d42477e41 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1277,6 +1277,39 @@ impl Writer { )); Ok((RawExpression::Value(id), result_lookup_ty)) } + Mf::Ceil => { + let result_lookup_ty = + match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width, + } => LookupType::Local(LocalType::Scalar { + kind: crate::ScalarKind::Float, + width, + }), + crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + size, + width, + } => LookupType::Local(LocalType::Vector { + kind: crate::ScalarKind::Float, + size, + width, + }), + _ => unreachable!(), + }; + let result_type_id = + self.get_type_id(&ir_module.types, result_lookup_ty)?; + + block.body.push(super::instructions::instruction_ext_inst( + result_type_id, + id, + 1, //TODO get the actual import set id + spirv::GLOp::Ceil as u32, + &[arg0_id], + )); + Ok((RawExpression::Value(id), result_lookup_ty)) + } _ => { log::error!("unimplemented math function {:?}", fun); Err(Error::FeatureNotImplemented("math function")) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 687a15f74..a98daa4ca 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,4 +1,7 @@ -use crate::{Block, Expression, Function, SampleLevel, TypeInner, proc::{ensure_block_returns, Typifier}}; +use crate::{ + proc::{ensure_block_returns, Typifier}, + Block, Expression, Function, MathFunction, SampleLevel, TypeInner, +}; use super::{ast::*, error::ErrorKind}; @@ -71,12 +74,28 @@ impl Program { .collect(), }) } else { - return Err(ErrorKind::SemanticError("Bad call to texture")); + Err(ErrorKind::SemanticError("Bad call to texture")) } } - _ => { - return Err(ErrorKind::NotImplemented("Function call")); + "ceil" => { + //TODO: check args len + Ok(ExpressionRule { + expression: self.context.expressions.append(Expression::Math { + fun: MathFunction::Ceil, + arg: fc.args[0].expression, + arg1: None, + arg2: None, + }), + sampler: None, + statements: fc + .args + .into_iter() + .map(|a| a.statements) + .flatten() + .collect(), + }) } + _ => Err(ErrorKind::NotImplemented("Function call")), } } } From 7d9054f2c18d3f8212c6c71f12a5cfa3f750ac09 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Sun, 20 Dec 2020 07:59:55 +0000 Subject: [PATCH 0352/2212] [glsl-in] Implement more MathFunctions --- src/back/spv/writer.rs | 32 ++++++++++---------------------- src/front/glsl/functions.rs | 11 +++++++++-- 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d42477e41..dea5b4607 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1277,27 +1277,8 @@ impl Writer { )); Ok((RawExpression::Value(id), result_lookup_ty)) } - Mf::Ceil => { - let result_lookup_ty = - match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width, - } => LookupType::Local(LocalType::Scalar { - kind: crate::ScalarKind::Float, - width, - }), - crate::TypeInner::Vector { - kind: crate::ScalarKind::Float, - size, - width, - } => LookupType::Local(LocalType::Vector { - kind: crate::ScalarKind::Float, - size, - width, - }), - _ => unreachable!(), - }; + Mf::Ceil | Mf::Round | Mf::Floor | Mf::Fract | Mf::Trunc => { + let result_lookup_ty = arg0_lookup_ty; let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; @@ -1305,7 +1286,14 @@ impl Writer { result_type_id, id, 1, //TODO get the actual import set id - spirv::GLOp::Ceil as u32, + match fun { + Mf::Ceil => spirv::GLOp::Ceil, + Mf::Round => spirv::GLOp::Round, + Mf::Floor => spirv::GLOp::Floor, + Mf::Fract => spirv::GLOp::Fract, + Mf::Trunc => spirv::GLOp::Trunc, + _ => unreachable!(), + } as u32, &[arg0_id], )); Ok((RawExpression::Value(id), result_lookup_ty)) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index a98daa4ca..878b17dcf 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -77,11 +77,18 @@ impl Program { Err(ErrorKind::SemanticError("Bad call to texture")) } } - "ceil" => { + "ceil" | "round" | "floor" | "fract" | "trunc" => { //TODO: check args len Ok(ExpressionRule { expression: self.context.expressions.append(Expression::Math { - fun: MathFunction::Ceil, + fun: match name.as_str() { + "ceil" => MathFunction::Ceil, + "round" => MathFunction::Round, + "floor" => MathFunction::Floor, + "fract" => MathFunction::Fract, + "trunc" => MathFunction::Trunc, + _ => unreachable!(), + }, arg: fc.args[0].expression, arg1: None, arg2: None, From 6c8cdea93688c93bdf01448f5a3352c9fb23aac3 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 21 Dec 2020 07:42:31 +0000 Subject: [PATCH 0353/2212] [glsl-in] Check number of function args --- src/front/glsl/error.rs | 4 ++++ src/front/glsl/functions.rs | 12 +++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index db5ffbe9f..66f3e9f5d 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -22,6 +22,7 @@ pub enum ErrorKind { ExpectedConstant, SemanticError(&'static str), PreprocessorError(String), + WrongNumberArgs(String, usize, usize), } impl fmt::Display for ErrorKind { @@ -55,6 +56,9 @@ impl fmt::Display for ErrorKind { ErrorKind::ExpectedConstant => write!(f, "Expected constant"), ErrorKind::SemanticError(msg) => write!(f, "Semantic error: {}", msg), ErrorKind::PreprocessorError(val) => write!(f, "Preprocessor error: {}", val), + ErrorKind::WrongNumberArgs(fun, expected, actual) => { + write!(f, "{} requires {} args, got {}", fun, expected, actual) + } } } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 878b17dcf..91ad544bd 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -38,7 +38,9 @@ impl Program { FunctionCallKind::Function(name) => { match name.as_str() { "sampler2D" => { - //TODO: check args len + if fc.args.len() != 2 { + return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); + } Ok(ExpressionRule { expression: fc.args[0].expression, sampler: Some(fc.args[1].expression), @@ -51,7 +53,9 @@ impl Program { }) } "texture" => { - //TODO: check args len + if fc.args.len() != 2 { + return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); + } if let Some(sampler) = fc.args[0].sampler { Ok(ExpressionRule { expression: self.context.expressions.append( @@ -78,7 +82,9 @@ impl Program { } } "ceil" | "round" | "floor" | "fract" | "trunc" => { - //TODO: check args len + if fc.args.len() != 1 { + return Err(ErrorKind::WrongNumberArgs(name, 1, fc.args.len())); + } Ok(ExpressionRule { expression: self.context.expressions.append(Expression::Math { fun: match name.as_str() { From e062096a6a04454c5e704ba3f7a6751084db7f5f Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 4 Jan 2021 07:29:20 +0000 Subject: [PATCH 0354/2212] [spv-out] Handle import id for GLSL.std.450 --- src/back/spv/writer.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index dea5b4607..7f52906b1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -160,6 +160,7 @@ pub struct Writer { lookup_global_variable: crate::FastHashMap, (Word, spirv::StorageClass)>, storage_type_handles: crate::FastHashSet>, + gl450_ext_inst_id: Word, } // type alias, for success return of write_expression @@ -187,6 +188,7 @@ impl Writer { lookup_constant: crate::FastHashMap::default(), lookup_global_variable: crate::FastHashMap::default(), storage_type_handles: crate::FastHashSet::default(), + gl450_ext_inst_id: 0, } } @@ -1285,7 +1287,7 @@ impl Writer { block.body.push(super::instructions::instruction_ext_inst( result_type_id, id, - 1, //TODO get the actual import set id + self.gl450_ext_inst_id, match fun { Mf::Ceil => spirv::GLOp::Ceil, Mf::Round => spirv::GLOp::Round, @@ -1556,8 +1558,8 @@ impl Writer { } fn write_logical_layout(&mut self, ir_module: &crate::Module) -> Result<(), Error> { - let id = self.generate_id(); - super::instructions::instruction_ext_inst_import(id, "GLSL.std.450") + self.gl450_ext_inst_id = self.generate_id(); + super::instructions::instruction_ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); if self.flags.contains(WriterFlags::DEBUG) { From 6710f5954e707ca144805bab0b71a8cd46a82034 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Mon, 4 Jan 2021 09:07:20 +0000 Subject: [PATCH 0355/2212] Fix clippy issues --- src/back/msl/writer.rs | 2 +- src/front/glsl/lex.rs | 3 ++- src/front/glsl/parser.rs | 3 +-- src/front/spv/mod.rs | 6 ++++-- src/front/wgsl/lexer.rs | 6 +++--- 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8b85256f4..d7eb311fd 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -19,7 +19,7 @@ impl Level { } impl Display for Level { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - (0..self.0).map(|_| formatter.write_str("\t")).collect() + (0..self.0).try_for_each(|_| formatter.write_str("\t")) } } diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 57e86a4c2..2ea23da87 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -93,7 +93,8 @@ impl<'a> Lexer<'a> { } } '0'..='9' => { - let (number, _, pos) = consume_any(input, |c| (c >= '0' && c <= '9' || c == '.')); + let (number, _, pos) = + consume_any(input, |c| (('0'..='9').contains(&c) || c == '.')); if number.find('.').is_some() { if ( chars.next().map(|c| c.to_lowercase().next().unwrap()), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 87d3c461f..efc09fc8f 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,6 +1,5 @@ -#![allow(clippy::panic)] +#![allow(clippy::panic, clippy::needless_lifetimes)] use pomelo::pomelo; - pomelo! { //%verbose; %include { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 5b7cc15c7..d9fe103de 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -576,8 +576,10 @@ impl> Parser { }, ); - let mut phi = PhiInstruction::default(); - phi.id = result_id; + let mut phi = PhiInstruction { + id: result_id, + ..Default::default() + }; for _ in 0..(inst.wc - 3) / 2 { phi.variables.push((self.next()?, self.next()?)); } diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 88688da6e..4d8e057ec 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -20,15 +20,15 @@ fn consume_number(input: &str) -> (&str, &str) { let mut what = |c| { if is_first_char { is_first_char = false; - c == '-' || c >= '0' && c <= '9' || c == '.' + c == '-' || ('0'..='9').contains(&c) || c == '.' } else if c == 'e' || c == 'E' { right_after_exponent = true; true } else if right_after_exponent { right_after_exponent = false; - c >= '0' && c <= '9' || c == '-' + ('0'..='9').contains(&c) || c == '-' } else { - c >= '0' && c <= '9' || c == '.' + ('0'..='9').contains(&c) || c == '.' } }; let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); From 3bf7f4106837dfcb48d441b045b4540ce631978f Mon Sep 17 00:00:00 2001 From: Jay Oster Date: Tue, 5 Jan 2021 20:34:40 -0800 Subject: [PATCH 0356/2212] WGSL // comments - Update parser to match the latest spec: https://github.com/gpuweb/gpuweb/pull/1326 --- src/front/wgsl/lexer.rs | 16 +++++++------ src/front/wgsl/tests.rs | 12 +++++----- test-data/simple/x.wgsl | 2 +- tests/snapshots/in/boids.wgsl | 42 +++++++++++++++++----------------- tests/snapshots/in/quad.wgsl | 4 ++-- tests/snapshots/in/simple.wgsl | 2 +- tests/snapshots/in/skybox.wgsl | 6 ++--- 7 files changed, 43 insertions(+), 41 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 4d8e057ec..fed5214c7 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -102,6 +102,15 @@ fn consume_token(mut input: &str) -> (Token<'_>, &str) { (Token::UnterminatedString, quote_content) } } + '/' if chars.as_str().starts_with('/') => { + match chars.position(|c| c == '\n' || c == '\r') { + Some(_) => { + input = chars.as_str(); + continue; + } + None => (Token::End, chars.as_str()), + } + } '-' => { let og_chars = chars.as_str(); match chars.next() { @@ -129,13 +138,6 @@ fn consume_token(mut input: &str) -> (Token<'_>, &str) { (Token::Operation(cur), input) } } - '#' => match chars.position(|c| c == '\n' || c == '\r') { - Some(_) => { - input = chars.as_str(); - continue; - } - None => (Token::End, chars.as_str()), - }, _ => (Token::Unknown(cur), chars.as_str()), }; } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index c8b812497..439a14f8b 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -3,12 +3,12 @@ use super::parse_str; #[test] fn parse_comment() { parse_str( - "# - ## - ######################################################### asda - #################### dad ########## # - ##################################################################################################### - # + "// + //// + ///////////////////////////////////////////////////////// asda + //////////////////// dad ////////// / + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // ", ) .unwrap(); diff --git a/test-data/simple/x.wgsl b/test-data/simple/x.wgsl index b35b83b42..563cf1645 100644 --- a/test-data/simple/x.wgsl +++ b/test-data/simple/x.wgsl @@ -1,4 +1,4 @@ -# vertex +// vertex [[location(0)]] var a_pos : vec2; [[location(0)]] var o_pos : vec4; diff --git a/tests/snapshots/in/boids.wgsl b/tests/snapshots/in/boids.wgsl index 3d6051867..ec87eeab2 100644 --- a/tests/snapshots/in/boids.wgsl +++ b/tests/snapshots/in/boids.wgsl @@ -1,18 +1,18 @@ -# Copyright 2020 The Tint Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +// Copyright 2020 The Tint Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. -# vertex shader +// vertex shader [[location(0)]] var a_particlePos : vec2; [[location(1)]] var a_particleVel : vec2; @@ -28,7 +28,7 @@ fn main() { gl_Position = vec4(pos + a_particlePos, 0.0, 1.0); } -# fragment shader +// fragment shader [[location(0)]] var fragColor : vec4; [[stage(fragment)]] @@ -36,7 +36,7 @@ fn main() { fragColor = vec4(1.0, 1.0, 1.0, 1.0); } -# compute shader +// compute shader [[block]] struct Particle { [[span(8)]] pos : vec2; @@ -65,7 +65,7 @@ struct Particles { [[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3; -# https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp +// https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp [[stage(compute), workgroup_size(1)]] fn main() { const index : u32 = gl_GlobalInvocationID.x; @@ -122,13 +122,13 @@ fn main() { vVel = vVel + (cMass * params.rule1Scale) + (colVel * params.rule2Scale) + (cVel * params.rule3Scale); - # clamp velocity for a more pleasing simulation + // clamp velocity for a more pleasing simulation vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1); - # kinematic update + // kinematic update vPos = vPos + (vVel * params.deltaT); - # Wrap around boundary + // Wrap around boundary if (vPos.x < -1.0) { vPos.x = 1.0; } @@ -142,7 +142,7 @@ fn main() { vPos.y = -1.0; } - # Write back + // Write back particlesB.particles[index].pos = vPos; particlesB.particles[index].vel = vVel; } diff --git a/tests/snapshots/in/quad.wgsl b/tests/snapshots/in/quad.wgsl index d7b45f22d..bc619d5fc 100644 --- a/tests/snapshots/in/quad.wgsl +++ b/tests/snapshots/in/quad.wgsl @@ -1,4 +1,4 @@ -# vertex +// vertex const c_scale: f32 = 1.2; [[location(0)]] var a_pos : vec2; [[location(1)]] var a_uv : vec2; @@ -11,7 +11,7 @@ fn main() { o_position = vec4(c_scale * a_pos, 0.0, 1.0); } -# fragment +// fragment [[location(0)]] var v_uv : vec2; [[group(0), binding(0)]] var u_texture : texture_2d; [[group(0), binding(1)]] var u_sampler : sampler; diff --git a/tests/snapshots/in/simple.wgsl b/tests/snapshots/in/simple.wgsl index ec4356412..54d492356 100644 --- a/tests/snapshots/in/simple.wgsl +++ b/tests/snapshots/in/simple.wgsl @@ -1,4 +1,4 @@ -# vertex +// vertex [[builtin(position)]] var o_position : vec4; [[stage(vertex)]] diff --git a/tests/snapshots/in/skybox.wgsl b/tests/snapshots/in/skybox.wgsl index 42436f13b..4cd838133 100644 --- a/tests/snapshots/in/skybox.wgsl +++ b/tests/snapshots/in/skybox.wgsl @@ -3,7 +3,7 @@ var out_position: vec4; [[location(0)]] var out_uv: vec3; [[builtin(vertex_index)]] var in_vertex_index: u32; -#[[block]] +//[[block]] struct Data { proj_inv: mat4x4; view: mat4x4; @@ -13,7 +13,7 @@ var r_data: Data; [[stage(vertex)]] fn vs_main() { - # hacky way to draw a large triangle + // hacky way to draw a large triangle var tmp1: i32 = i32(in_vertex_index) / 2; var tmp2: i32 = i32(in_vertex_index) & 1; const pos: vec4 = vec4( @@ -24,7 +24,7 @@ fn vs_main() { ); const inv_model_view: mat3x3 = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); - var unprojected: vec4 = r_data.proj_inv * pos; #TODO: const + var unprojected: vec4 = r_data.proj_inv * pos; //TODO: const out_uv = inv_model_view * unprojected.xyz; out_position = pos; } From bd998f6c32f94dd66b98f23866ede7ed2878e87b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 7 Jan 2021 14:30:18 -0500 Subject: [PATCH 0357/2212] Validate constant array sizes --- src/front/glsl/mod.rs | 2 +- src/proc/validator.rs | 27 +++++++++++++++++++++------ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 9711aca90..c5ecfbbfe 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -14,13 +14,13 @@ use ast::Program; use lex::Lexer; mod error; use error::ParseError; +mod functions; mod parser; #[cfg(test)] mod parser_tests; mod token; mod types; mod variables; -mod functions; pub fn parse_str( source: &str, diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 51ddc46f0..396776636 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -29,6 +29,8 @@ pub enum ConstantError { InvalidType, #[error("The component handle {0:?} can not be resolved")] UnresolvedComponent(Handle), + #[error("The array size handle {0:?} can not be resolved")] + UnresolvedSize(Handle), } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -312,7 +314,7 @@ impl Validator { &self, handle: Handle, constants: &Arena, - _types: &Arena, + types: &Arena, ) -> Result<(), ConstantError> { let con = &constants[handle]; match con.inner { @@ -321,14 +323,27 @@ impl Validator { return Err(ConstantError::InvalidType); } } - crate::ConstantInner::Composite { - ty: _, - ref components, - } => { + crate::ConstantInner::Composite { ty, ref components } => { + match types[ty].inner { + crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } => { + return Err(ConstantError::InvalidType); + } + crate::TypeInner::Array { + size: crate::ArraySize::Constant(size_handle), + .. + } => { + if handle <= size_handle { + return Err(ConstantError::UnresolvedSize(size_handle)); + } + } + _ => {} //TODO + } if let Some(&comp) = components.iter().find(|&&comp| handle <= comp) { return Err(ConstantError::UnresolvedComponent(comp)); } - //TODO } } Ok(()) From 4e5b39f452c81091bb1bc8d70f818f8516e6ccae Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 8 Jan 2021 08:57:10 -0500 Subject: [PATCH 0358/2212] [spv] indexing arrays --- src/back/spv/writer.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 7f52906b1..bd4fbac0e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -765,6 +765,15 @@ impl Writer { constituent_ids.push(constituent_id); } + // Get the size constant for arrays + if let crate::TypeInner::Array { + size: crate::ArraySize::Constant(const_handle), + .. + } = arena[ty].inner + { + self.get_constant_id(const_handle, &ir_module)?; + } + let type_id = self.get_type_id(arena, LookupType::Handle(ty))?; super::instructions::instruction_constant_composite( type_id, @@ -1019,12 +1028,18 @@ impl Writer { let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); let (pointer_type_id, lookup_ty) = match *base_ty_inner { + crate::TypeInner::Array { base, .. } => { + self.create_pointer_type(LookupType::Handle(base), class, &ir_module.types)? + } crate::TypeInner::Vector { kind, width, .. } => self.create_pointer_type( LocalType::Scalar { kind, width }.into(), class, &ir_module.types, )?, - _ => return Err(Error::FeatureNotImplemented("accessing of non-vector")), + ref other => { + log::error!("Unable to index {:?}", other); + return Err(Error::FeatureNotImplemented("accessing of non-vector")); + } }; block @@ -1077,10 +1092,11 @@ impl Writer { &ir_module.types, )? } - _ => { + ref other => { + log::error!("Unable to access index {:?}", other); return Err(Error::FeatureNotImplemented( "accessing index of non vector or struct", - )) + )); } }; From 08b6c416a3b834ed5f257c8311142832ab6ea970 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 8 Jan 2021 10:05:14 -0500 Subject: [PATCH 0359/2212] Unlock arbitrary binding indices in the validator --- Cargo.toml | 1 + src/proc/validator.rs | 84 +++++++++++++++++++++---------------------- 2 files changed, 41 insertions(+), 44 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5de97e925..8db623000 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ license = "MIT OR Apache-2.0" [dependencies] bitflags = "1" +bit-set = "0.5" fxhash = "0.2" log = "0.4" num-traits = "0.2" diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 396776636..14de47ff7 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -1,9 +1,7 @@ use super::typifier::{ResolveContext, ResolveError, Typifier}; use crate::arena::{Arena, Handle}; +use bit_set::BitSet; -const MAX_BIND_GROUPS: u32 = 8; -const MAX_LOCATIONS: u32 = 64; // using u64 mask -const MAX_BIND_INDICES: u32 = 64; // using u64 mask const MAX_WORKGROUP_SIZE: u32 = 0x4000; #[derive(Debug)] @@ -11,6 +9,9 @@ pub struct Validator { //Note: this is a bit tricky: some of the front-ends as well as backends // already have to use the typifier, so the work here is redundant in a way. typifier: Typifier, + location_in_mask: BitSet, + location_out_mask: BitSet, + bind_group_masks: Vec, } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -48,8 +49,6 @@ pub enum GlobalVariableError { }, #[error("Binding decoration is missing or not applicable")] InvalidBinding, - #[error("Binding is out of range")] - OutOfRangeBinding, #[error("BuiltIn type for {0:?} is invalid")] InvalidBuiltInType(crate::BuiltIn), } @@ -138,11 +137,7 @@ impl crate::GlobalVariable { fn check_resource(&self) -> Result<(), GlobalVariableError> { match self.binding { - Some(crate::Binding::Resource { group, binding }) => { - if group > MAX_BIND_GROUPS || binding > MAX_BIND_INDICES { - return Err(GlobalVariableError::OutOfRangeBinding); - } - } + Some(crate::Binding::Resource { .. }) => {} Some(crate::Binding::BuiltIn(_)) | Some(crate::Binding::Location(_)) | None => { return Err(GlobalVariableError::InvalidBinding) } @@ -195,17 +190,12 @@ impl crate::GlobalVariable { } self.forbid_interpolation()? } - Some(crate::Binding::Location(loc)) => { - if loc > MAX_LOCATIONS { - return Err(GlobalVariableError::OutOfRangeBinding); - } - match types[self.ty].inner { - crate::TypeInner::Scalar { .. } - | crate::TypeInner::Vector { .. } - | crate::TypeInner::Matrix { .. } => {} - _ => return Err(GlobalVariableError::InvalidType), - } - } + Some(crate::Binding::Location(_)) => match types[self.ty].inner { + crate::TypeInner::Scalar { .. } + | crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } => {} + _ => return Err(GlobalVariableError::InvalidType), + }, Some(crate::Binding::Resource { .. }) => { return Err(GlobalVariableError::InvalidBinding) } @@ -240,6 +230,9 @@ impl Validator { pub fn new() -> Self { Validator { typifier: Typifier::new(), + location_in_mask: BitSet::new(), + location_out_mask: BitSet::new(), + bind_group_masks: Vec::new(), } } @@ -467,9 +460,12 @@ impl Validator { return Err(EntryPointError::UnexpectedWorkgroupSize); } - let mut bind_group_masks = [0u64; MAX_BIND_GROUPS as usize]; - let mut location_in_mask = 0u64; - let mut location_out_mask = 0u64; + self.location_in_mask.clear(); + self.location_out_mask.clear(); + for bg in self.bind_group_masks.iter_mut() { + bg.clear(); + } + for ((var_handle, var), &usage) in module .global_variables .iter() @@ -498,7 +494,7 @@ impl Validator { let allowed_usage = match var.class { crate::StorageClass::Function => unreachable!(), crate::StorageClass::Input => { - let mask = match var.binding { + match var.binding { Some(crate::Binding::BuiltIn(built_in)) => match (stage, built_in) { (crate::ShaderStage::Vertex, crate::BuiltIn::BaseInstance) | (crate::ShaderStage::Vertex, crate::BuiltIn::BaseVertex) @@ -512,36 +508,36 @@ impl Validator { | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationId) | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationIndex) | (crate::ShaderStage::Compute, crate::BuiltIn::WorkGroupId) - | (crate::ShaderStage::Compute, crate::BuiltIn::WorkGroupSize) => 0, + | (crate::ShaderStage::Compute, crate::BuiltIn::WorkGroupSize) => (), _ => return Err(EntryPointError::InvalidBuiltIn(built_in)), }, - Some(crate::Binding::Location(loc)) => 1 << loc, + Some(crate::Binding::Location(loc)) => { + if !self.location_in_mask.insert(loc as usize) { + return Err(EntryPointError::BindingCollision(var_handle)); + } + } Some(crate::Binding::Resource { .. }) => unreachable!(), - None => 0, - }; - if location_in_mask & mask != 0 { - return Err(EntryPointError::BindingCollision(var_handle)); + None => (), } - location_in_mask |= mask; crate::GlobalUse::LOAD } crate::StorageClass::Output => { - let mask = match var.binding { + match var.binding { Some(crate::Binding::BuiltIn(built_in)) => match (stage, built_in) { (crate::ShaderStage::Vertex, crate::BuiltIn::Position) | (crate::ShaderStage::Vertex, crate::BuiltIn::PointSize) | (crate::ShaderStage::Vertex, crate::BuiltIn::ClipDistance) - | (crate::ShaderStage::Fragment, crate::BuiltIn::FragDepth) => 0, + | (crate::ShaderStage::Fragment, crate::BuiltIn::FragDepth) => (), _ => return Err(EntryPointError::InvalidBuiltIn(built_in)), }, - Some(crate::Binding::Location(loc)) => 1 << loc, + Some(crate::Binding::Location(loc)) => { + if !self.location_out_mask.insert(loc as usize) { + return Err(EntryPointError::BindingCollision(var_handle)); + } + } Some(crate::Binding::Resource { .. }) => unreachable!(), - None => 0, - }; - if location_out_mask & mask != 0 { - return Err(EntryPointError::BindingCollision(var_handle)); + None => (), } - location_out_mask |= mask; crate::GlobalUse::LOAD | crate::GlobalUse::STORE } crate::StorageClass::Uniform => crate::GlobalUse::LOAD, @@ -569,12 +565,12 @@ impl Validator { } if let Some(crate::Binding::Resource { group, binding }) = var.binding { - let mask = 1 << binding; - let group_mask = &mut bind_group_masks[group as usize]; - if *group_mask & mask != 0 { + while self.bind_group_masks.len() <= group as usize { + self.bind_group_masks.push(BitSet::new()); + } + if !self.bind_group_masks[group as usize].insert(binding as usize) { return Err(EntryPointError::BindingCollision(var_handle)); } - *group_mask |= mask; } } From c6658e775ddb8731bd2f1131328c37906842651e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 9 Jan 2021 20:58:51 -0500 Subject: [PATCH 0360/2212] Typifier support for vector * matrix multiplication --- src/proc/typifier.rs | 50 +++++++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index f29fa12f1..d41b17f89 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -217,30 +217,38 @@ impl Typifier { let ty_right = self.get(right, types); if ty_left == ty_right { self.resolutions[left.index()].clone() + } else if let crate::TypeInner::Scalar { .. } = *ty_left { + self.resolutions[right.index()].clone() } else if let crate::TypeInner::Scalar { .. } = *ty_right { self.resolutions[left.index()].clone() + } else if let crate::TypeInner::Matrix { + columns, + rows: _, + width, + } = *ty_left + { + Resolution::Value(crate::TypeInner::Vector { + size: columns, + kind: crate::ScalarKind::Float, + width, + }) + } else if let crate::TypeInner::Matrix { + columns: _, + rows, + width, + } = *ty_right + { + Resolution::Value(crate::TypeInner::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }) } else { - match *ty_left { - crate::TypeInner::Scalar { .. } => { - self.resolutions[right.index()].clone() - } - crate::TypeInner::Matrix { - columns, - rows: _, - width, - } => Resolution::Value(crate::TypeInner::Vector { - size: columns, - kind: crate::ScalarKind::Float, - width, - }), - _ => { - return Err(ResolveError::IncompatibleOperands { - op: "x".to_string(), - left: format!("{:?}", ty_left), - right: format!("{:?}", ty_right), - }) - } - } + return Err(ResolveError::IncompatibleOperands { + op: "x".to_string(), + left: format!("{:?}", ty_left), + right: format!("{:?}", ty_right), + }); } } crate::BinaryOperator::Equal From 73cb6d4bdf3eb455717a17d7ec216d36f6f5b589 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 11 Jan 2021 09:20:38 -0500 Subject: [PATCH 0361/2212] [spv] Relax decoration checks for global variables --- src/front/spv/mod.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d9fe103de..d69b431d0 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2290,10 +2290,13 @@ impl> Parser { None }; let lookup_type = self.lookup_type.lookup(type_id)?; - let dec = self - .future_decor - .remove(&id) - .ok_or(Error::InvalidBinding(id))?; + let dec = match self.future_decor.remove(&id) { + Some(dec) => dec, + None => { + log::warn!("Missing decoration for global {:?}", id); + Decoration::default() + } + }; let class = { use spirv::StorageClass as Sc; @@ -2320,11 +2323,6 @@ impl> Parser { } }; - let binding = match (class, &module.types[lookup_type.handle].inner) { - (crate::StorageClass::Input, &crate::TypeInner::Struct { .. }) - | (crate::StorageClass::Output, &crate::TypeInner::Struct { .. }) => None, - _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?), - }; let is_storage = match module.types[lookup_type.handle].inner { crate::TypeInner::Struct { .. } => class == crate::StorageClass::Storage, crate::TypeInner::Image { @@ -2347,6 +2345,7 @@ impl> Parser { crate::StorageAccess::empty() }; + let binding = dec.get_binding(); let ty = match binding { // SPIR-V only cares about some of the built-in types being integer. // Naga requires them to be strictly unsigned, so we have to patch it. From 61d624c82e3267fa53b44a2e0ad41c6c4b451daf Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 13 Jan 2021 08:07:43 +0100 Subject: [PATCH 0362/2212] [glsl-in] Implement function call (#354) --- src/front/glsl/functions.rs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 91ad544bd..91ac166f2 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -100,15 +100,23 @@ impl Program { arg2: None, }), sampler: None, - statements: fc - .args - .into_iter() - .map(|a| a.statements) - .flatten() - .collect(), + statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), + }) + } + func_name => { + let function = *self + .lookup_function + .get(func_name) + .ok_or(ErrorKind::SemanticError("Unknown function"))?; + Ok(ExpressionRule { + expression: self.context.expressions.append(Expression::Call { + function, + arguments: fc.args.iter().map(|a| a.expression).collect(), + }), + sampler: None, + statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), }) } - _ => Err(ErrorKind::NotImplemented("Function call")), } } } From 6f5ff27701112abba35fa61e429e2916a157b0a1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 12 Jan 2021 15:36:58 -0500 Subject: [PATCH 0363/2212] Sample mask support --- src/back/glsl/mod.rs | 11 ++++++++--- src/back/msl/mod.rs | 2 ++ src/back/spv/writer.rs | 37 +++++++++++++++++++++---------------- src/front/spv/convert.rs | 13 ++++++++++--- src/front/spv/mod.rs | 20 +++++++++++--------- src/front/wgsl/conv.rs | 3 +++ src/lib.rs | 6 ++++-- src/proc/validator.rs | 7 +++++-- 8 files changed, 64 insertions(+), 35 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a8c41faf8..ddb1c6c6c 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1686,18 +1686,23 @@ fn glsl_scalar(kind: ScalarKind, width: crate::Bytes) -> Result &'static str { match built_in { + // vertex BuiltIn::Position => "gl_Position", - BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", BuiltIn::BaseInstance => "gl_BaseInstance", BuiltIn::BaseVertex => "gl_BaseVertex", BuiltIn::ClipDistance => "gl_ClipDistance", BuiltIn::InstanceIndex => "gl_InstanceID", - BuiltIn::VertexIndex => "gl_VertexID", BuiltIn::PointSize => "gl_PointSize", + BuiltIn::VertexIndex => "gl_VertexID", + // fragment BuiltIn::FragCoord => "gl_FragCoord", + BuiltIn::FragDepth => "gl_FragDepth", BuiltIn::FrontFacing => "gl_FrontFacing", BuiltIn::SampleIndex => "gl_SampleID", - BuiltIn::FragDepth => "gl_FragDepth", + BuiltIn::SampleMaskIn => "gl_SampleMaskIn", + BuiltIn::SampleMaskOut => "gl_SampleMask", + // compute + BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", BuiltIn::LocalInvocationId => "gl_LocalInvocationID", BuiltIn::LocalInvocationIndex => "gl_LocalInvocationIndex", BuiltIn::WorkGroupId => "gl_WorkGroupID", diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 053704303..53c8ddf38 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -173,6 +173,8 @@ impl ResolvedBinding { Bi::FragDepth => "depth(any)", Bi::FrontFacing => "front_facing", Bi::SampleIndex => "sample_id", + Bi::SampleMaskIn => "sample_mask", + Bi::SampleMaskOut => "sample_mask", // compute Bi::GlobalInvocationId => "thread_position_in_grid", Bi::LocalInvocationId => "thread_position_in_threadgroup", diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index bd4fbac0e..8f9d3ef93 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -856,23 +856,28 @@ impl Writer { )); } Some(crate::Binding::BuiltIn(built_in)) => { + use crate::BuiltIn as Bi; let built_in = match built_in { - crate::BuiltIn::BaseInstance => spirv::BuiltIn::BaseInstance, - crate::BuiltIn::BaseVertex => spirv::BuiltIn::BaseVertex, - crate::BuiltIn::ClipDistance => spirv::BuiltIn::ClipDistance, - crate::BuiltIn::InstanceIndex => spirv::BuiltIn::InstanceIndex, - crate::BuiltIn::Position => spirv::BuiltIn::Position, - crate::BuiltIn::VertexIndex => spirv::BuiltIn::VertexIndex, - crate::BuiltIn::PointSize => spirv::BuiltIn::PointSize, - crate::BuiltIn::FragCoord => spirv::BuiltIn::FragCoord, - crate::BuiltIn::FrontFacing => spirv::BuiltIn::FrontFacing, - crate::BuiltIn::SampleIndex => spirv::BuiltIn::SampleId, - crate::BuiltIn::FragDepth => spirv::BuiltIn::FragDepth, - crate::BuiltIn::GlobalInvocationId => spirv::BuiltIn::GlobalInvocationId, - crate::BuiltIn::LocalInvocationId => spirv::BuiltIn::LocalInvocationId, - crate::BuiltIn::LocalInvocationIndex => spirv::BuiltIn::LocalInvocationIndex, - crate::BuiltIn::WorkGroupId => spirv::BuiltIn::WorkgroupId, - crate::BuiltIn::WorkGroupSize => spirv::BuiltIn::WorkgroupSize, + Bi::BaseInstance => spirv::BuiltIn::BaseInstance, + Bi::BaseVertex => spirv::BuiltIn::BaseVertex, + Bi::ClipDistance => spirv::BuiltIn::ClipDistance, + Bi::InstanceIndex => spirv::BuiltIn::InstanceIndex, + Bi::PointSize => spirv::BuiltIn::PointSize, + Bi::Position => spirv::BuiltIn::Position, + Bi::VertexIndex => spirv::BuiltIn::VertexIndex, + // fragment + Bi::FragCoord => spirv::BuiltIn::FragCoord, + Bi::FragDepth => spirv::BuiltIn::FragDepth, + Bi::FrontFacing => spirv::BuiltIn::FrontFacing, + Bi::SampleIndex => spirv::BuiltIn::SampleId, + Bi::SampleMaskIn => spirv::BuiltIn::SampleMask, + Bi::SampleMaskOut => spirv::BuiltIn::SampleMask, + // compute + Bi::GlobalInvocationId => spirv::BuiltIn::GlobalInvocationId, + Bi::LocalInvocationId => spirv::BuiltIn::LocalInvocationId, + Bi::LocalInvocationIndex => spirv::BuiltIn::LocalInvocationIndex, + Bi::WorkGroupId => spirv::BuiltIn::WorkgroupId, + Bi::WorkGroupSize => spirv::BuiltIn::WorkgroupSize, }; self.annotations diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 167863efa..e2259aa4e 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -98,21 +98,28 @@ pub fn map_width(word: spirv::Word) -> Result { .map_err(|_| Error::InvalidTypeWidth(word)) } -pub fn map_builtin(word: spirv::Word) -> Result { +pub fn map_builtin(word: spirv::Word, is_output: bool) -> Result { use spirv::BuiltIn as Bi; Ok(match spirv::BuiltIn::from_u32(word) { Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, Some(Bi::BaseVertex) => crate::BuiltIn::BaseVertex, Some(Bi::ClipDistance) => crate::BuiltIn::ClipDistance, Some(Bi::InstanceIndex) => crate::BuiltIn::InstanceIndex, + Some(Bi::PointSize) => crate::BuiltIn::PointSize, Some(Bi::Position) => crate::BuiltIn::Position, Some(Bi::VertexIndex) => crate::BuiltIn::VertexIndex, // fragment - Some(Bi::PointSize) => crate::BuiltIn::PointSize, Some(Bi::FragCoord) => crate::BuiltIn::FragCoord, + Some(Bi::FragDepth) => crate::BuiltIn::FragDepth, Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing, Some(Bi::SampleId) => crate::BuiltIn::SampleIndex, - Some(Bi::FragDepth) => crate::BuiltIn::FragDepth, + Some(Bi::SampleMask) => { + if is_output { + crate::BuiltIn::SampleMaskOut + } else { + crate::BuiltIn::SampleMaskIn + } + } // compute Some(Bi::GlobalInvocationId) => crate::BuiltIn::GlobalInvocationId, Some(Bi::LocalInvocationId) => crate::BuiltIn::LocalInvocationId, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d69b431d0..fc07e58b4 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -158,7 +158,7 @@ bitflags::bitflags! { #[derive(Debug, Default)] struct Decoration { name: Option, - built_in: Option, + built_in: Option, location: Option, desc_set: Option, desc_index: Option, @@ -177,7 +177,7 @@ impl Decoration { } } - fn get_binding(&self) -> Option { + fn get_binding(&self, is_output: bool) -> Option { //TODO: validate this better match *self { Decoration { @@ -186,7 +186,13 @@ impl Decoration { desc_set: None, desc_index: None, .. - } => Some(crate::Binding::BuiltIn(built_in)), + } => match convert::map_builtin(built_in, is_output) { + Ok(built_in) => Some(crate::Binding::BuiltIn(built_in)), + Err(e) => { + log::warn!("{:?}", e); + None + } + }, Decoration { built_in: None, location: Some(loc), @@ -381,11 +387,7 @@ impl> Parser { match dec_typed { spirv::Decoration::BuiltIn => { inst.expect(base_words + 2)?; - let raw = self.next()?; - match map_builtin(raw) { - Ok(built_in) => dec.built_in = Some(built_in), - Err(_e) => log::warn!("Unsupported builtin {}", raw), - }; + dec.built_in = Some(self.next()?); } spirv::Decoration::Location => { inst.expect(base_words + 2)?; @@ -2345,7 +2347,7 @@ impl> Parser { crate::StorageAccess::empty() }; - let binding = dec.get_binding(); + let binding = dec.get_binding(class == crate::StorageClass::Output); let ty = match binding { // SPIR-V only cares about some of the built-in types being integer. // Naga requires them to be strictly unsigned, so we have to patch it. diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index d10a3afcd..8aa0d5238 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -21,6 +21,9 @@ pub fn map_built_in(word: &str) -> Result> { "front_facing" => crate::BuiltIn::FrontFacing, "frag_coord" => crate::BuiltIn::FragCoord, "frag_depth" => crate::BuiltIn::FragDepth, + "sample_index" => crate::BuiltIn::SampleIndex, + "sample_mask_in" => crate::BuiltIn::SampleMaskIn, + "sample_mask_out" => crate::BuiltIn::SampleMaskOut, // compute "global_invocation_id" => crate::BuiltIn::GlobalInvocationId, "local_invocation_id" => crate::BuiltIn::LocalInvocationId, diff --git a/src/lib.rs b/src/lib.rs index 2719c40cc..b002ac82d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -140,14 +140,16 @@ pub enum BuiltIn { BaseVertex, ClipDistance, InstanceIndex, + PointSize, Position, VertexIndex, // fragment - PointSize, FragCoord, + FragDepth, FrontFacing, SampleIndex, - FragDepth, + SampleMaskIn, + SampleMaskOut, // compute GlobalInvocationId, LocalInvocationId, diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 14de47ff7..619f1f349 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -158,6 +158,8 @@ impl crate::GlobalVariable { | Bi::InstanceIndex | Bi::VertexIndex | Bi::SampleIndex + | Bi::SampleMaskIn + | Bi::SampleMaskOut | Bi::LocalInvocationIndex => Ti::Scalar { kind: Sk::Uint, width, @@ -500,10 +502,10 @@ impl Validator { | (crate::ShaderStage::Vertex, crate::BuiltIn::BaseVertex) | (crate::ShaderStage::Vertex, crate::BuiltIn::InstanceIndex) | (crate::ShaderStage::Vertex, crate::BuiltIn::VertexIndex) - | (crate::ShaderStage::Fragment, crate::BuiltIn::PointSize) | (crate::ShaderStage::Fragment, crate::BuiltIn::FragCoord) | (crate::ShaderStage::Fragment, crate::BuiltIn::FrontFacing) | (crate::ShaderStage::Fragment, crate::BuiltIn::SampleIndex) + | (crate::ShaderStage::Fragment, crate::BuiltIn::SampleMaskIn) | (crate::ShaderStage::Compute, crate::BuiltIn::GlobalInvocationId) | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationId) | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationIndex) @@ -527,7 +529,8 @@ impl Validator { (crate::ShaderStage::Vertex, crate::BuiltIn::Position) | (crate::ShaderStage::Vertex, crate::BuiltIn::PointSize) | (crate::ShaderStage::Vertex, crate::BuiltIn::ClipDistance) - | (crate::ShaderStage::Fragment, crate::BuiltIn::FragDepth) => (), + | (crate::ShaderStage::Fragment, crate::BuiltIn::FragDepth) + | (crate::ShaderStage::Fragment, crate::BuiltIn::SampleMaskOut) => (), _ => return Err(EntryPointError::InvalidBuiltIn(built_in)), }, Some(crate::Binding::Location(loc)) => { From 92f970a69d7e0c8a223daf9beba45d348d4ee70e Mon Sep 17 00:00:00 2001 From: sotrh Date: Fri, 15 Jan 2021 07:33:48 -0700 Subject: [PATCH 0364/2212] Change ErrorKind::SemanticError to use Cow<'static, str> instead of &'static str (#356) * Changed front::glsl::error::ErrorKind::Semantic to use Cow * cargo fmt * appeasing clippy * Update src/front/glsl/functions.rs Co-authored-by: monocodus[bot] <49363530+monocodus[bot]@users.noreply.github.com> * Fixed more clippy errors Co-authored-by: Dzmitry Malyshau Co-authored-by: monocodus[bot] <49363530+monocodus[bot]@users.noreply.github.com> --- src/front/glsl/ast.rs | 2 +- src/front/glsl/error.rs | 4 ++-- src/front/glsl/functions.rs | 17 +++++++++-------- src/front/glsl/parser.rs | 12 ++++++------ src/front/glsl/variables.rs | 14 +++++++++++--- 5 files changed, 29 insertions(+), 20 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 58161ad7b..6f3669a75 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -72,7 +72,7 @@ impl Program { &resolve_ctx, ) { //TODO: better error report - Err(_) => Err(ErrorKind::SemanticError("Can't resolve type")), + Err(_) => Err(ErrorKind::SemanticError("Can't resolve type".into())), Ok(()) => Ok(self.context.typifier.get(handle, &self.module.types)), } } diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 66f3e9f5d..5c2d6f44c 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -1,6 +1,6 @@ use super::parser::Token; use super::token::TokenMetadata; -use std::{fmt, io}; +use std::{borrow::Cow, fmt, io}; #[derive(Debug)] pub enum ErrorKind { @@ -20,7 +20,7 @@ pub enum ErrorKind { #[cfg(feature = "glsl-validate")] VariableNotAvailable(String), ExpectedConstant, - SemanticError(&'static str), + SemanticError(Cow<'static, str>), PreprocessorError(String), WrongNumberArgs(String, usize, usize), } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 91ac166f2..fa07d891e 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -10,9 +10,9 @@ impl Program { match fc.kind { FunctionCallKind::TypeConstructor(ty) => { let h = if fc.args.len() == 1 { - let kind = self.module.types[ty].inner.scalar_kind().ok_or( - ErrorKind::SemanticError("Can only cast to scalar or vector"), - )?; + let kind = self.module.types[ty].inner.scalar_kind().ok_or_else(|| { + ErrorKind::SemanticError("Can only cast to scalar or vector".into()) + })?; self.context.expressions.append(Expression::As { kind, expr: fc.args[0].expression, @@ -78,7 +78,7 @@ impl Program { .collect(), }) } else { - Err(ErrorKind::SemanticError("Bad call to texture")) + Err(ErrorKind::SemanticError("Bad call to texture".into())) } } "ceil" | "round" | "floor" | "fract" | "trunc" => { @@ -104,10 +104,11 @@ impl Program { }) } func_name => { - let function = *self - .lookup_function - .get(func_name) - .ok_or(ErrorKind::SemanticError("Unknown function"))?; + let function = *self.lookup_function.get(func_name).ok_or_else(|| { + ErrorKind::SemanticError( + format!("Unknown function: {}", func_name).into(), + ) + })?; Ok(ExpressionRule { expression: self.context.expressions.append(Expression::Call { function, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index efc09fc8f..bd0cbb7e4 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -517,7 +517,7 @@ pomelo! { } single_declaration ::= fully_specified_type(t) { - let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; + let ty = t.1.ok_or_else(||ErrorKind::SemanticError("Empty type for declaration".into()))?; VarDeclaration { type_qualifiers: t.0, @@ -526,7 +526,7 @@ pomelo! { } } single_declaration ::= fully_specified_type(t) Identifier(i) { - let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; + let ty = t.1.ok_or_else(|| ErrorKind::SemanticError("Empty type for declaration".into()))?; VarDeclaration { type_qualifiers: t.0, @@ -537,7 +537,7 @@ pomelo! { // single_declaration ::= fully_specified_type Identifier array_specifier; // single_declaration ::= fully_specified_type Identifier array_specifier Equal initializer; single_declaration ::= fully_specified_type(t) Identifier(i) Equal initializer(init) { - let ty = t.1.ok_or(ErrorKind::SemanticError("Empty type for declaration"))?; + let ty = t.1.ok_or_else(|| ErrorKind::SemanticError("Empty type for declaration".into()))?; VarDeclaration { type_qualifiers: t.0, @@ -676,7 +676,7 @@ pomelo! { ty, }).collect() } else { - return Err(ErrorKind::SemanticError("Struct member can't be void")) + return Err(ErrorKind::SemanticError("Struct member can't be void".into())) } } //struct_declaration ::= type_qualifier type_specifier struct_declarator_list Semicolon; @@ -707,7 +707,7 @@ pomelo! { // local variables if let Some(d) = d { for (id, initializer) in d.ids_initializers { - let id = id.ok_or(ErrorKind::SemanticError("local var must be named"))?; + let id = id.ok_or_else(|| ErrorKind::SemanticError("Local var must be named".into()))?; // check if already declared in current scope #[cfg(feature = "glsl-validate")] { @@ -1002,7 +1002,7 @@ pomelo! { if let Some(d) = d { let class = d.type_qualifiers.iter().find_map(|tq| { if let TypeQualifier::StorageClass(sc) = tq { Some(*sc) } else { None } - }).ok_or(ErrorKind::SemanticError("Missing storage class for global var"))?; + }).ok_or_else(|| ErrorKind::SemanticError(format!("Missing storage class for global var \"{:?}\"", d).into()))?; let binding = d.type_qualifiers.iter().find_map(|tq| { if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 37335987d..70022a2ac 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -204,7 +204,11 @@ impl Program { 4 => VectorSize::Quad, _ => { return Err(ErrorKind::SemanticError( - "Bad swizzle size", + format!( + "Bad swizzle size for \"{:?}\": {:?}", + name, v + ) + .into(), )); } }, @@ -214,10 +218,14 @@ impl Program { })) } } else { - Err(ErrorKind::SemanticError("Invalid swizzle for vector")) + Err(ErrorKind::SemanticError( + format!("Invalid swizzle for vector \"{}\"", name).into(), + )) } } - _ => Err(ErrorKind::SemanticError("Can't lookup field on this type")), + _ => Err(ErrorKind::SemanticError( + format!("Can't lookup field on this type \"{}\"", name).into(), + )), } } } From da51f29d427c722a1198a472b7f4d5e5445daf48 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 22 Jan 2021 08:54:28 -0500 Subject: [PATCH 0365/2212] [spv] emit proper member layout decorations (#360) --- examples/convert.rs | 7 +- src/back/spv/instructions.rs | 16 ++- src/back/spv/writer.rs | 79 ++++++++++-- src/proc/layouter.rs | 122 ++++++++++++++++++ src/proc/mod.rs | 4 +- src/proc/sizer.rs | 68 ---------- src/proc/validator.rs | 2 + tests/snapshots/snapshots__skybox.spvasm.snap | 2 + 8 files changed, 218 insertions(+), 82 deletions(-) create mode 100644 src/proc/layouter.rs delete mode 100644 src/proc/sizer.rs diff --git a/examples/convert.rs b/examples/convert.rs index eb42f8b6f..b77da388a 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -53,7 +53,12 @@ fn main() { let param_path = std::path::PathBuf::from(&args[1]).with_extension("param.ron"); let params = match fs::read_to_string(param_path) { Ok(string) => ron::de::from_str(&string).unwrap(), - Err(_) => Parameters::default(), + Err(_) => { + let mut param = Parameters::default(); + // very useful to have this by default + param.spv_capabilities.insert(spirv::Capability::Shader); + param + } }; let module = match Path::new(&args[1]) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index e958febc5..682ce8c8c 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -39,11 +39,25 @@ pub(super) fn instruction_decorate( let mut instruction = Instruction::new(Op::Decorate); instruction.add_operand(target_id); instruction.add_operand(decoration as u32); - for operand in operands { instruction.add_operand(*operand) } + instruction +} +pub(super) fn instruction_member_decorate( + target_id: Word, + member_index: Word, + decoration: spirv::Decoration, + operands: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::MemberDecorate); + instruction.add_operand(target_id); + instruction.add_operand(member_index); + instruction.add_operand(decoration as u32); + for operand in operands { + instruction.add_operand(*operand) + } instruction } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 8f9d3ef93..3f67f212c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,5 +1,6 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ use super::{Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; +use crate::proc::Layouter; use spirv::Word; use std::{collections::hash_map::Entry, ops}; use thiserror::Error; @@ -161,6 +162,7 @@ pub struct Writer { crate::FastHashMap, (Word, spirv::StorageClass)>, storage_type_handles: crate::FastHashSet>, gl450_ext_inst_id: Word, + layouter: Layouter, } // type alias, for success return of write_expression @@ -189,6 +191,7 @@ impl Writer { lookup_global_variable: crate::FastHashMap::default(), storage_type_handles: crate::FastHashSet::default(), gl450_ext_inst_id: 0, + layouter: Layouter::default(), } } @@ -582,6 +585,12 @@ impl Writer { rows, width, } => { + self.annotations + .push(super::instructions::instruction_decorate( + id, + spirv::Decoration::RowMajor, + &[], + )); let vector_id = self.get_type_id( arena, LookupType::Local(LocalType::Vector { @@ -648,20 +657,67 @@ impl Writer { } } } - crate::TypeInner::Struct { block, ref members } => { - if block { - let decoration = if self.storage_type_handles.contains(&handle) { - spirv::Decoration::BufferBlock - } else { - spirv::Decoration::Block - }; + crate::TypeInner::Struct { + block: true, + ref members, + } => { + let decoration = if self.storage_type_handles.contains(&handle) { + spirv::Decoration::BufferBlock + } else { + spirv::Decoration::Block + }; + self.annotations + .push(super::instructions::instruction_decorate( + id, + decoration, + &[], + )); + + let mut current_offset = 0; + let mut member_ids = Vec::with_capacity(members.len()); + for (index, member) in members.iter().enumerate() { + let layout = self.layouter.resolve(member.ty); + current_offset += layout.pad(current_offset); self.annotations - .push(super::instructions::instruction_decorate( + .push(super::instructions::instruction_member_decorate( id, - decoration, - &[], + index as u32, + spirv::Decoration::Offset, + &[current_offset], )); + current_offset += match member.span { + Some(span) => span.get(), + None => layout.size, + }; + + if let crate::TypeInner::Matrix { + columns, + rows: _, + width, + } = arena[member.ty].inner + { + let byte_stride = match columns { + crate::VectorSize::Bi => 2 * width, + crate::VectorSize::Tri | crate::VectorSize::Quad => 4 * width, + }; + self.annotations + .push(super::instructions::instruction_member_decorate( + id, + index as u32, + spirv::Decoration::MatrixStride, + &[byte_stride as u32], + )); + } + + let member_id = self.get_type_id(arena, LookupType::Handle(member.ty))?; + member_ids.push(member_id); } + super::instructions::instruction_type_struct(id, member_ids.as_slice()) + } + crate::TypeInner::Struct { + block: false, + ref members, + } => { let mut member_ids = Vec::with_capacity(members.len()); for member in members { let member_id = self.get_type_id(arena, LookupType::Handle(member.ty))?; @@ -1633,6 +1689,9 @@ impl Writer { } pub fn write(&mut self, ir_module: &crate::Module, words: &mut Vec) -> Result<(), Error> { + self.layouter + .initialize(&ir_module.types, &ir_module.constants); + self.write_logical_layout(ir_module)?; self.write_physical_layout(); diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs new file mode 100644 index 000000000..a7d0f0f11 --- /dev/null +++ b/src/proc/layouter.rs @@ -0,0 +1,122 @@ +use crate::arena::Arena; +use std::num::NonZeroU32; + +pub type Alignment = NonZeroU32; + +/// Alignment information for a type. +#[derive(Clone, Copy, Debug, Hash, PartialEq)] +pub struct TypeLayout { + pub size: u32, + pub alignment: Alignment, +} + +impl TypeLayout { + /// Return padding to this type given an offset. + pub fn pad(&self, offset: u32) -> u32 { + match offset & self.alignment.get() { + 0 => 0, + other => self.alignment.get() - other, + } + } +} + +/// Helper processor that derives the sizes of all types. +#[derive(Debug, Default)] +pub struct Layouter { + layouts: Vec, +} + +impl Layouter { + pub fn new(types: &Arena, constants: &Arena) -> Self { + let mut this = Layouter::default(); + this.initialize(types, constants); + this + } + + pub fn initialize(&mut self, types: &Arena, constants: &Arena) { + use crate::TypeInner as Ti; + + self.layouts.clear(); + self.layouts.reserve(types.len()); + + for (_, ty) in types.iter() { + self.layouts.push(match ty.inner { + Ti::Scalar { kind: _, width } => TypeLayout { + size: width as u32, + alignment: Alignment::new(width as u32).unwrap(), + }, + Ti::Vector { + size, + kind: _, + width, + } => TypeLayout { + size: (size as u8 * width) as u32, + //TODO: reconsider if this needs to match the size + alignment: Alignment::new(width as u32).unwrap(), + }, + Ti::Matrix { + columns, + rows, + width, + } => TypeLayout { + size: (columns as u8 * rows as u8 * width) as u32, + alignment: Alignment::new((columns as u8 * width) as u32).unwrap(), + }, + Ti::Pointer { .. } => TypeLayout { + size: 4, + alignment: Alignment::new(1).unwrap(), + }, + Ti::Array { base, size, stride } => { + let count = match size { + crate::ArraySize::Constant(handle) => match constants[handle].inner { + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(value), + } => value as u32, + ref other => unreachable!("Unexpected array size {:?}", other), + }, + crate::ArraySize::Dynamic => 1, + }; + let stride = match stride { + Some(value) => value, + None => Alignment::new(self.layouts[base.index()].size.max(1)).unwrap(), + }; + TypeLayout { + size: count * stride.get(), + alignment: stride, + } + } + Ti::Struct { + block: _, + ref members, + } => { + let mut total = 0; + let mut biggest_alignment = Alignment::new(1).unwrap(); + for member in members { + let member_layout = self.layouts[member.ty.index()]; + biggest_alignment = biggest_alignment.max(member_layout.alignment); + // align up first + total += member_layout.pad(total); + // then add the size + total += match member.span { + Some(span) => span.get(), + None => member_layout.size, + }; + } + TypeLayout { + size: total, + alignment: biggest_alignment, + } + } + Ti::Image { .. } | Ti::Sampler { .. } => TypeLayout { + size: 0, + alignment: Alignment::new(1).unwrap(), + }, + }); + } + } + + pub fn resolve(&self, handle: crate::Handle) -> TypeLayout { + self.layouts[handle.index()] + } +} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index fae3ba209..101d8e1c1 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -3,8 +3,8 @@ #[cfg(feature = "petgraph")] mod call_graph; mod interface; +mod layouter; mod namer; -mod sizer; mod terminator; mod typifier; mod validator; @@ -12,8 +12,8 @@ mod validator; #[cfg(feature = "petgraph")] pub use call_graph::{CallGraph, CallGraphBuilder}; pub use interface::{Interface, Visitor}; +pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; -pub use sizer::Sizer; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; diff --git a/src/proc/sizer.rs b/src/proc/sizer.rs deleted file mode 100644 index 8c17e48f6..000000000 --- a/src/proc/sizer.rs +++ /dev/null @@ -1,68 +0,0 @@ -use crate::arena::Arena; - -/// Helper processor that derives the sizes of all types. -#[derive(Debug)] -pub struct Sizer { - sizes: Vec, -} - -impl Sizer { - pub fn new(types: &Arena, constants: &Arena) -> Self { - use crate::TypeInner as Ti; - - let mut sizes = Vec::with_capacity(types.len()); - for (_, ty) in types.iter() { - sizes.push(match ty.inner { - Ti::Scalar { kind: _, width } => width as u32, - Ti::Vector { - size, - kind: _, - width, - } => (size as u8 * width) as u32, - Ti::Matrix { - columns, - rows, - width, - } => (columns as u8 * rows as u8 * width) as u32, - Ti::Pointer { .. } => 0, - Ti::Array { base, size, stride } => { - let count = match size { - crate::ArraySize::Constant(handle) => match constants[handle].inner { - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(value), - } => value as u32, - ref other => unreachable!("Unexpected array size {:?}", other), - }, - crate::ArraySize::Dynamic => 1, - }; - let stride = match stride { - Some(value) => value.get(), - None => sizes[base.index()], - }; - count * stride - } - Ti::Struct { - block: _, - ref members, - } => { - let mut total = 0; - for member in members { - total += match member.span { - Some(span) => span.get(), - None => sizes[member.ty.index()], - }; - } - total - } - Ti::Image { .. } | Ti::Sampler { .. } => 0, - }); - } - - Sizer { sizes } - } - - pub fn resolve(&self, handle: crate::Handle) -> u32 { - self.sizes[handle.index()] - } -} diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 619f1f349..4aca857e1 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -583,6 +583,8 @@ impl Validator { /// Check the given module to be valid. pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { + self.typifier.clear(); + for (handle, ty) in module.types.iter() { self.validate_type(ty, handle, &module.constants) .map_err(|error| ValidationError::Type { diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap index 942d7f7f1..1dd5b6b3c 100644 --- a/tests/snapshots/snapshots__skybox.spvasm.snap +++ b/tests/snapshots/snapshots__skybox.spvasm.snap @@ -13,9 +13,11 @@ OpEntryPoint Vertex %11 "vs_main" %157 %44 %15 OpEntryPoint Fragment %168 "fs_main" %180 %170 OpExecutionMode %168 OriginUpperLeft OpDecorate %15 BuiltIn VertexIndex +OpDecorate %27 RowMajor OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 0 OpDecorate %44 Location 0 +OpDecorate %48 RowMajor OpDecorate %157 BuiltIn Position OpDecorate %170 Location 0 OpDecorate %171 DescriptorSet 0 From bc66f784c12e6e5f2a7b140fe4ab0dd3a26cae34 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 21 Jan 2021 19:53:48 -0500 Subject: [PATCH 0366/2212] Refactor builtin usage validation --- src/proc/mod.rs | 16 +++++------ src/proc/validator.rs | 64 +++++++++++++++++++++++++++---------------- 2 files changed, 48 insertions(+), 32 deletions(-) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 101d8e1c1..5dec4285b 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -58,18 +58,18 @@ impl From for super::ScalarKind { } } -impl crate::ScalarValue { - pub fn scalar_kind(&self) -> crate::ScalarKind { +impl super::ScalarValue { + pub fn scalar_kind(&self) -> super::ScalarKind { match *self { - Self::Uint(_) => crate::ScalarKind::Uint, - Self::Sint(_) => crate::ScalarKind::Sint, - Self::Float(_) => crate::ScalarKind::Float, - Self::Bool(_) => crate::ScalarKind::Bool, + Self::Uint(_) => super::ScalarKind::Uint, + Self::Sint(_) => super::ScalarKind::Sint, + Self::Float(_) => super::ScalarKind::Float, + Self::Bool(_) => super::ScalarKind::Bool, } } } -impl crate::TypeInner { +impl super::TypeInner { pub fn scalar_kind(&self) -> Option { match *self { super::TypeInner::Scalar { kind, .. } | super::TypeInner::Vector { kind, .. } => { @@ -81,7 +81,7 @@ impl crate::TypeInner { } } -impl crate::MathFunction { +impl super::MathFunction { pub fn argument_count(&self) -> usize { match *self { // comparison diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 4aca857e1..01e2bae60 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -227,6 +227,30 @@ fn storage_usage(access: crate::StorageAccess) -> crate::GlobalUse { storage_usage } +fn built_in_usage(built_in: crate::BuiltIn) -> (crate::ShaderStage, crate::GlobalUse) { + use crate::{BuiltIn as Bi, GlobalUse as Gu, ShaderStage as Ss}; + match built_in { + Bi::BaseInstance => (Ss::Vertex, Gu::LOAD), + Bi::BaseVertex => (Ss::Vertex, Gu::LOAD), + Bi::ClipDistance => (Ss::Vertex, Gu::STORE), + Bi::InstanceIndex => (Ss::Vertex, Gu::LOAD), + Bi::PointSize => (Ss::Vertex, Gu::STORE), + Bi::Position => (Ss::Vertex, Gu::STORE), + Bi::VertexIndex => (Ss::Vertex, Gu::LOAD), + Bi::FragCoord => (Ss::Fragment, Gu::LOAD), + Bi::FragDepth => (Ss::Fragment, Gu::LOAD), + Bi::FrontFacing => (Ss::Fragment, Gu::LOAD), + Bi::SampleIndex => (Ss::Fragment, Gu::LOAD), + Bi::SampleMaskIn => (Ss::Fragment, Gu::LOAD), + Bi::SampleMaskOut => (Ss::Fragment, Gu::STORE), + Bi::GlobalInvocationId => (Ss::Compute, Gu::LOAD), + Bi::LocalInvocationId => (Ss::Compute, Gu::LOAD), + Bi::LocalInvocationIndex => (Ss::Compute, Gu::LOAD), + Bi::WorkGroupId => (Ss::Compute, Gu::LOAD), + Bi::WorkGroupSize => (Ss::Compute, Gu::LOAD), + } +} + impl Validator { /// Construct a new validator instance. pub fn new() -> Self { @@ -497,22 +521,14 @@ impl Validator { crate::StorageClass::Function => unreachable!(), crate::StorageClass::Input => { match var.binding { - Some(crate::Binding::BuiltIn(built_in)) => match (stage, built_in) { - (crate::ShaderStage::Vertex, crate::BuiltIn::BaseInstance) - | (crate::ShaderStage::Vertex, crate::BuiltIn::BaseVertex) - | (crate::ShaderStage::Vertex, crate::BuiltIn::InstanceIndex) - | (crate::ShaderStage::Vertex, crate::BuiltIn::VertexIndex) - | (crate::ShaderStage::Fragment, crate::BuiltIn::FragCoord) - | (crate::ShaderStage::Fragment, crate::BuiltIn::FrontFacing) - | (crate::ShaderStage::Fragment, crate::BuiltIn::SampleIndex) - | (crate::ShaderStage::Fragment, crate::BuiltIn::SampleMaskIn) - | (crate::ShaderStage::Compute, crate::BuiltIn::GlobalInvocationId) - | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationId) - | (crate::ShaderStage::Compute, crate::BuiltIn::LocalInvocationIndex) - | (crate::ShaderStage::Compute, crate::BuiltIn::WorkGroupId) - | (crate::ShaderStage::Compute, crate::BuiltIn::WorkGroupSize) => (), - _ => return Err(EntryPointError::InvalidBuiltIn(built_in)), - }, + Some(crate::Binding::BuiltIn(built_in)) => { + let (allowed_stage, allowed_usage) = built_in_usage(built_in); + if allowed_stage != stage + || !allowed_usage.contains(crate::GlobalUse::LOAD) + { + return Err(EntryPointError::InvalidBuiltIn(built_in)); + } + } Some(crate::Binding::Location(loc)) => { if !self.location_in_mask.insert(loc as usize) { return Err(EntryPointError::BindingCollision(var_handle)); @@ -525,14 +541,14 @@ impl Validator { } crate::StorageClass::Output => { match var.binding { - Some(crate::Binding::BuiltIn(built_in)) => match (stage, built_in) { - (crate::ShaderStage::Vertex, crate::BuiltIn::Position) - | (crate::ShaderStage::Vertex, crate::BuiltIn::PointSize) - | (crate::ShaderStage::Vertex, crate::BuiltIn::ClipDistance) - | (crate::ShaderStage::Fragment, crate::BuiltIn::FragDepth) - | (crate::ShaderStage::Fragment, crate::BuiltIn::SampleMaskOut) => (), - _ => return Err(EntryPointError::InvalidBuiltIn(built_in)), - }, + Some(crate::Binding::BuiltIn(built_in)) => { + let (allowed_stage, allowed_usage) = built_in_usage(built_in); + if allowed_stage != stage + || !allowed_usage.contains(crate::GlobalUse::STORE) + { + return Err(EntryPointError::InvalidBuiltIn(built_in)); + } + } Some(crate::Binding::Location(loc)) => { if !self.location_out_mask.insert(loc as usize) { return Err(EntryPointError::BindingCollision(var_handle)); From b441a2595651f1ddcf5107b63e51fc33d3d4ab88 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 21 Jan 2021 20:00:36 -0500 Subject: [PATCH 0367/2212] Rename GlobalUse variants --- src/back/msl/writer.rs | 6 ++--- src/lib.rs | 4 ++-- src/proc/interface.rs | 12 +++++----- src/proc/validator.rs | 54 +++++++++++++++++++++--------------------- 4 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index d7eb311fd..afe4607fe 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -40,7 +40,7 @@ impl<'a> TypedGlobalVariable<'a> { let (space_qualifier, reference) = match ty.inner { crate::TypeInner::Struct { .. } => match var.class { crate::StorageClass::Uniform | crate::StorageClass::Storage => { - let space = if self.usage.contains(crate::GlobalUse::STORE) { + let space = if self.usage.contains(crate::GlobalUse::WRITE) { "device " } else { "constant " @@ -930,7 +930,7 @@ impl Writer { module.global_variables.iter().zip(&fun.global_usage) { if var.class != crate::StorageClass::Input - || !usage.contains(crate::GlobalUse::LOAD) + || !usage.contains(crate::GlobalUse::READ) { continue; } @@ -956,7 +956,7 @@ impl Writer { module.global_variables.iter().zip(&fun.global_usage) { if var.class != crate::StorageClass::Output - || !usage.contains(crate::GlobalUse::STORE) + || !usage.contains(crate::GlobalUse::WRITE) { continue; } diff --git a/src/lib.rs b/src/lib.rs index b002ac82d..297454fe9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -445,9 +445,9 @@ bitflags::bitflags! { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct GlobalUse: u8 { /// Data will be read from the variable. - const LOAD = 0x1; + const READ = 0x1; /// Data will be written to the variable. - const STORE = 0x2; + const WRITE = 0x2; } } diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 6c000cc3c..65c3e6d48 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -203,13 +203,13 @@ struct GlobalUseVisitor<'a>(&'a mut [crate::GlobalUse]); impl Visitor for GlobalUseVisitor<'_> { fn visit_expr(&mut self, expr: &crate::Expression) { if let crate::Expression::GlobalVariable(handle) = expr { - self.0[handle.index()] |= crate::GlobalUse::LOAD; + self.0[handle.index()] |= crate::GlobalUse::READ; } } fn visit_lhs_expr(&mut self, expr: &crate::Expression) { if let crate::Expression::GlobalVariable(handle) = expr { - self.0[handle.index()] |= crate::GlobalUse::STORE; + self.0[handle.index()] |= crate::GlobalUse::WRITE; } } } @@ -291,10 +291,10 @@ mod tests { assert_eq!( &function.global_usage, &[ - GlobalUse::LOAD, - GlobalUse::STORE, - GlobalUse::STORE, - GlobalUse::LOAD, + GlobalUse::READ, + GlobalUse::WRITE, + GlobalUse::WRITE, + GlobalUse::READ, ], ) } diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 01e2bae60..390e83b5a 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -219,10 +219,10 @@ impl crate::GlobalVariable { fn storage_usage(access: crate::StorageAccess) -> crate::GlobalUse { let mut storage_usage = crate::GlobalUse::empty(); if access.contains(crate::StorageAccess::LOAD) { - storage_usage |= crate::GlobalUse::LOAD; + storage_usage |= crate::GlobalUse::READ; } if access.contains(crate::StorageAccess::STORE) { - storage_usage |= crate::GlobalUse::STORE; + storage_usage |= crate::GlobalUse::WRITE; } storage_usage } @@ -230,24 +230,24 @@ fn storage_usage(access: crate::StorageAccess) -> crate::GlobalUse { fn built_in_usage(built_in: crate::BuiltIn) -> (crate::ShaderStage, crate::GlobalUse) { use crate::{BuiltIn as Bi, GlobalUse as Gu, ShaderStage as Ss}; match built_in { - Bi::BaseInstance => (Ss::Vertex, Gu::LOAD), - Bi::BaseVertex => (Ss::Vertex, Gu::LOAD), - Bi::ClipDistance => (Ss::Vertex, Gu::STORE), - Bi::InstanceIndex => (Ss::Vertex, Gu::LOAD), - Bi::PointSize => (Ss::Vertex, Gu::STORE), - Bi::Position => (Ss::Vertex, Gu::STORE), - Bi::VertexIndex => (Ss::Vertex, Gu::LOAD), - Bi::FragCoord => (Ss::Fragment, Gu::LOAD), - Bi::FragDepth => (Ss::Fragment, Gu::LOAD), - Bi::FrontFacing => (Ss::Fragment, Gu::LOAD), - Bi::SampleIndex => (Ss::Fragment, Gu::LOAD), - Bi::SampleMaskIn => (Ss::Fragment, Gu::LOAD), - Bi::SampleMaskOut => (Ss::Fragment, Gu::STORE), - Bi::GlobalInvocationId => (Ss::Compute, Gu::LOAD), - Bi::LocalInvocationId => (Ss::Compute, Gu::LOAD), - Bi::LocalInvocationIndex => (Ss::Compute, Gu::LOAD), - Bi::WorkGroupId => (Ss::Compute, Gu::LOAD), - Bi::WorkGroupSize => (Ss::Compute, Gu::LOAD), + Bi::BaseInstance => (Ss::Vertex, Gu::READ), + Bi::BaseVertex => (Ss::Vertex, Gu::READ), + Bi::ClipDistance => (Ss::Vertex, Gu::WRITE), + Bi::InstanceIndex => (Ss::Vertex, Gu::READ), + Bi::PointSize => (Ss::Vertex, Gu::WRITE), + Bi::Position => (Ss::Vertex, Gu::WRITE), + Bi::VertexIndex => (Ss::Vertex, Gu::READ), + Bi::FragCoord => (Ss::Fragment, Gu::READ), + Bi::FragDepth => (Ss::Fragment, Gu::READ), + Bi::FrontFacing => (Ss::Fragment, Gu::READ), + Bi::SampleIndex => (Ss::Fragment, Gu::READ), + Bi::SampleMaskIn => (Ss::Fragment, Gu::READ), + Bi::SampleMaskOut => (Ss::Fragment, Gu::WRITE), + Bi::GlobalInvocationId => (Ss::Compute, Gu::READ), + Bi::LocalInvocationId => (Ss::Compute, Gu::READ), + Bi::LocalInvocationIndex => (Ss::Compute, Gu::READ), + Bi::WorkGroupId => (Ss::Compute, Gu::READ), + Bi::WorkGroupSize => (Ss::Compute, Gu::READ), } } @@ -524,7 +524,7 @@ impl Validator { Some(crate::Binding::BuiltIn(built_in)) => { let (allowed_stage, allowed_usage) = built_in_usage(built_in); if allowed_stage != stage - || !allowed_usage.contains(crate::GlobalUse::LOAD) + || !allowed_usage.contains(crate::GlobalUse::READ) { return Err(EntryPointError::InvalidBuiltIn(built_in)); } @@ -537,14 +537,14 @@ impl Validator { Some(crate::Binding::Resource { .. }) => unreachable!(), None => (), } - crate::GlobalUse::LOAD + crate::GlobalUse::READ } crate::StorageClass::Output => { match var.binding { Some(crate::Binding::BuiltIn(built_in)) => { let (allowed_stage, allowed_usage) = built_in_usage(built_in); if allowed_stage != stage - || !allowed_usage.contains(crate::GlobalUse::STORE) + || !allowed_usage.contains(crate::GlobalUse::WRITE) { return Err(EntryPointError::InvalidBuiltIn(built_in)); } @@ -557,21 +557,21 @@ impl Validator { Some(crate::Binding::Resource { .. }) => unreachable!(), None => (), } - crate::GlobalUse::LOAD | crate::GlobalUse::STORE + crate::GlobalUse::READ | crate::GlobalUse::WRITE } - crate::StorageClass::Uniform => crate::GlobalUse::LOAD, + crate::StorageClass::Uniform => crate::GlobalUse::READ, crate::StorageClass::Storage => storage_usage(var.storage_access), crate::StorageClass::Handle => match module.types[var.ty].inner { crate::TypeInner::Image { class: crate::ImageClass::Storage(_), .. } => storage_usage(var.storage_access), - _ => crate::GlobalUse::LOAD, + _ => crate::GlobalUse::READ, }, crate::StorageClass::Private | crate::StorageClass::WorkGroup => { crate::GlobalUse::all() } - crate::StorageClass::PushConstant => crate::GlobalUse::LOAD, + crate::StorageClass::PushConstant => crate::GlobalUse::READ, }; if !allowed_usage.contains(usage) { log::warn!("\tUsage error for: {:?}", var); From 04b0f2443e938a3b29f195a5bb1bcd9a661fedcb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 21 Jan 2021 23:56:00 -0500 Subject: [PATCH 0368/2212] Validate local and argument types --- src/proc/validator.rs | 59 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 8 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 390e83b5a..d91773e66 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -55,8 +55,6 @@ pub enum GlobalVariableError { #[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum LocalVariableError { - #[error("Initializer is not a constant expression")] - InitializerConst, #[error("Initializer doesn't match the variable type")] InitializerType, } @@ -67,12 +65,16 @@ pub enum FunctionError { Resolve(#[from] ResolveError), #[error("There are instructions after `return`/`break`/`continue`")] InvalidControlFlowExitTail, + #[error("The global use array has a different length from the global variables")] + InvalidGlobalUsageLength, #[error("Local variable {handle:?} '{name}' is invalid: {error:?}")] LocalVariable { handle: Handle, name: String, error: LocalVariableError, }, + #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")] + InvalidArgumentType { index: usize, name: String }, } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -83,6 +85,10 @@ pub enum EntryPointError { UnexpectedWorkgroupSize, #[error("Workgroup size is out of range")] OutOfRangeWorkgroupSize, + #[error("Can't have arguments")] + UnexpectedArguments, + #[error("Can't have a return value")] + UnexpectedReturnValue, #[error("Global variable {0:?} is used incorrectly as {1:?}")] InvalidGlobalUsage(Handle, crate::GlobalUse), #[error("Bindings for {0:?} conflict with other global variables")] @@ -427,13 +433,26 @@ impl Validator { fn validate_local_var( &self, var: &crate::LocalVariable, - _fun: &crate::Function, - _types: &Arena, + types: &Arena, + constants: &Arena, ) -> Result<(), LocalVariableError> { log::debug!("var {:?}", var); - if let Some(_expr_handle) = var.init { - if false { - return Err(LocalVariableError::InitializerConst); + if let Some(const_handle) = var.init { + match constants[const_handle].inner { + crate::ConstantInner::Scalar { width, ref value } => { + let ty_inner = crate::TypeInner::Scalar { + width, + kind: value.scalar_kind(), + }; + if types[var.ty].inner != ty_inner { + return Err(LocalVariableError::InitializerType); + } + } + crate::ConstantInner::Composite { ty, components: _ } => { + if ty != var.ty { + return Err(LocalVariableError::InitializerType); + } + } } } Ok(()) @@ -454,14 +473,31 @@ impl Validator { self.typifier .resolve_all(&fun.expressions, &module.types, &resolve_ctx)?; + if fun.global_usage.len() > module.global_variables.len() { + return Err(FunctionError::InvalidGlobalUsageLength); + } + for (var_handle, var) in fun.local_variables.iter() { - self.validate_local_var(var, fun, &module.types) + self.validate_local_var(var, &module.types, &module.constants) .map_err(|error| FunctionError::LocalVariable { handle: var_handle, name: var.name.clone().unwrap_or_default(), error, })?; } + + for (index, argument) in fun.arguments.iter().enumerate() { + match module.types[argument.ty].inner { + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { + return Err(FunctionError::InvalidArgumentType { + index, + name: argument.name.clone().unwrap_or_default(), + }) + } + _ => (), + } + } + Ok(()) } @@ -593,6 +629,13 @@ impl Validator { } } + if !ep.function.arguments.is_empty() { + return Err(EntryPointError::UnexpectedArguments); + } + if ep.function.return_type.is_some() { + return Err(EntryPointError::UnexpectedReturnValue); + } + self.validate_function(&ep.function, module)?; Ok(()) } From c758399354221945d400c1b74daf1a824682c0a6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 21 Jan 2021 23:56:18 -0500 Subject: [PATCH 0369/2212] Add a collatz snapshot test --- tests/snapshots.rs | 6 ++++ tests/snapshots/in/boids.wgsl | 2 +- tests/snapshots/in/collatz.param.ron | 7 ++++ tests/snapshots/in/collatz.wgsl | 37 +++++++++++++++++++ tests/snapshots/snapshots__boids.msl.snap | 3 +- tests/snapshots/snapshots__collatz.msl.snap | 39 +++++++++++++++++++++ 6 files changed, 92 insertions(+), 2 deletions(-) create mode 100644 tests/snapshots/in/collatz.param.ron create mode 100644 tests/snapshots/in/collatz.wgsl create mode 100644 tests/snapshots/snapshots__collatz.msl.snap diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b9c3412f7..4732b19ce 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -176,3 +176,9 @@ fn converts_wgsl_boids() { fn converts_wgsl_skybox() { convert_wgsl("skybox", Language::all()); } + +#[cfg(feature = "wgsl-in")] +#[test] +fn converts_wgsl_collatz() { + convert_wgsl("collatz", Language::METAL); +} diff --git a/tests/snapshots/in/boids.wgsl b/tests/snapshots/in/boids.wgsl index ec87eeab2..2e8b07425 100644 --- a/tests/snapshots/in/boids.wgsl +++ b/tests/snapshots/in/boids.wgsl @@ -84,7 +84,7 @@ fn main() { var pos : vec2; var vel : vec2; - var i : u32 = 0; + var i : u32 = u32(0); loop { if (i >= u32(5)) { break; diff --git a/tests/snapshots/in/collatz.param.ron b/tests/snapshots/in/collatz.param.ron new file mode 100644 index 000000000..8a18d983a --- /dev/null +++ b/tests/snapshots/in/collatz.param.ron @@ -0,0 +1,7 @@ +( + spv_flow_dump_prefix: "", + spv_capabilities: [ Shader ], + mtl_bindings: { + (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: true), + } +) diff --git a/tests/snapshots/in/collatz.wgsl b/tests/snapshots/in/collatz.wgsl new file mode 100644 index 000000000..a0853e0e4 --- /dev/null +++ b/tests/snapshots/in/collatz.wgsl @@ -0,0 +1,37 @@ +[[builtin(global_invocation_id)]] +var global_id: vec3; + +struct PrimeIndices { + data: array; +}; // this is used as both input and output for convenience + +[[group(0), binding(0)]] +var v_indices: [[access(read_write)]] PrimeIndices; + +// The Collatz Conjecture states that for any integer n: +// If n is even, n = n/2 +// If n is odd, n = 3n+1 +// And repeat this process for each new n, you will always eventually reach 1. +// Though the conjecture has not been proven, no counterexample has ever been found. +// This function returns how many times this recurrence needs to be applied to reach 1. +fn collatz_iterations(n: u32) -> u32{ + var i: u32 = u32(0); + loop { + if (n <= u32(1)) { + break; + } + if (n % u32(2) == u32(0)) { + n = n / u32(2); + } + else { + n = u32(3) * n + i32(1); + } + i = i + u32(1); + } + return i; +} + +[[stage(compute), workgroup_size(1)]] +fn main() { + v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); +} diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap index 358a97386..ca9665c13 100644 --- a/tests/snapshots/snapshots__boids.msl.snap +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -71,7 +71,7 @@ kernel void main3( type6 cVelCount = 0; type pos1; type vel1; - type5 i = 0; + type5 i; if (gl_GlobalInvocationID.x >= static_cast(5)) { } vPos = particlesA.particles[gl_GlobalInvocationID.x].pos; @@ -79,6 +79,7 @@ kernel void main3( cMass = metal::float2(0.0, 0.0); cVel = metal::float2(0.0, 0.0); colVel = metal::float2(0.0, 0.0); + i = static_cast(0); while(true) { if (i >= static_cast(5)) { break; diff --git a/tests/snapshots/snapshots__collatz.msl.snap b/tests/snapshots/snapshots__collatz.msl.snap new file mode 100644 index 000000000..be5eb887a --- /dev/null +++ b/tests/snapshots/snapshots__collatz.msl.snap @@ -0,0 +1,39 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +typedef metal::uint3 type; +typedef uint type1; +typedef type1 type2[1]; +struct PrimeIndices { + type2 data; +}; + +type1 collatz_iterations( + type1 n +) { + type1 i; + i = static_cast(0); + while(true) { + if (n <= static_cast(1)) { + break; + } + if (n % static_cast(2) == static_cast(0)) { + n = n / static_cast(2); + } else { + n = static_cast(3) * n + static_cast(1); + } + i = i + static_cast(1); + } + return i; +} +kernel void main1( + type global_id [[thread_position_in_grid]], + device PrimeIndices& v_indices [[buffer(0)]] +) { + v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); +} + From 6ffd68d6a2dde0a90aa048b7fc99166b034e040e Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Fri, 22 Jan 2021 23:51:42 +0100 Subject: [PATCH 0370/2212] [spv-out] Add comparison operators --- src/back/spv/writer.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 3f67f212c..966c8f081 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1302,6 +1302,44 @@ impl Writer { Some(crate::ScalarKind::Float) => spirv::Op::FMod, _ => unreachable!(), }, + crate::BinaryOperator::Equal => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => + spirv::Op::IEqual, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdEqual, + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalEqual, + _ => unreachable!(), + }, + crate::BinaryOperator::NotEqual => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => + spirv::Op::INotEqual, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdNotEqual, + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNotEqual, + _ => unreachable!(), + }, + crate::BinaryOperator::Less => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SLessThan, + Some(crate::ScalarKind::Uint) => spirv::Op::ULessThan, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThan, + _ => unreachable!(), + }, + crate::BinaryOperator::LessEqual => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SLessThanEqual, + Some(crate::ScalarKind::Uint) => spirv::Op::ULessThanEqual, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThanEqual, + _ => unreachable!(), + }, + crate::BinaryOperator::Greater => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThan, + Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThan, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThan, + _ => unreachable!(), + }, + crate::BinaryOperator::GreaterEqual => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThanEqual, + Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThanEqual, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThanEqual, + _ => unreachable!(), + }, crate::BinaryOperator::And => spirv::Op::BitwiseAnd, _ => { log::error!("unimplemented {:?}", op); From 5b35b04546902180e286fea3dc78b8c5f749a735 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 23 Jan 2021 02:01:41 -0500 Subject: [PATCH 0371/2212] Remove rosetta tests --- src/back/spv/writer.rs | 10 +- test-data/simple.frag | 5 - test-data/simple.vert | 8 -- test-data/simple/module.ron | 124 ------------------ test-data/simple/x.spv | Bin 500 -> 0 bytes test-data/simple/x.vert | 10 -- test-data/simple/x.wgsl | 10 -- test-data/spv/cube.frag.spv | Bin 1208 -> 0 bytes test-data/spv/cube.vert.spv | Bin 1124 -> 0 bytes test-data/spv/quad.vert.spv | Bin 884 -> 0 bytes .../cases}/glsl_constant_expression.vert | 0 .../cases}/glsl_if_preprocessor.vert | 0 .../cases}/glsl_phong_lighting.frag | 0 .../cases}/glsl_preprocessor_abuse.vert | 0 .../cases}/glsl_vertex_test_shader.vert | 0 tests/parse.rs | 2 +- tests/rosetta.rs | 80 ----------- 17 files changed, 7 insertions(+), 242 deletions(-) delete mode 100644 test-data/simple.frag delete mode 100644 test-data/simple.vert delete mode 100644 test-data/simple/module.ron delete mode 100644 test-data/simple/x.spv delete mode 100644 test-data/simple/x.vert delete mode 100644 test-data/simple/x.wgsl delete mode 100644 test-data/spv/cube.frag.spv delete mode 100644 test-data/spv/cube.vert.spv delete mode 100644 test-data/spv/quad.vert.spv rename {test-data => tests/cases}/glsl_constant_expression.vert (100%) rename {test-data => tests/cases}/glsl_if_preprocessor.vert (100%) rename {test-data => tests/cases}/glsl_phong_lighting.frag (100%) rename {test-data => tests/cases}/glsl_preprocessor_abuse.vert (100%) rename {test-data => tests/cases}/glsl_vertex_test_shader.vert (100%) delete mode 100644 tests/rosetta.rs diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 966c8f081..d20232652 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1303,15 +1303,17 @@ impl Writer { _ => unreachable!(), }, crate::BinaryOperator::Equal => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => - spirv::Op::IEqual, + Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { + spirv::Op::IEqual + } Some(crate::ScalarKind::Float) => spirv::Op::FOrdEqual, Some(crate::ScalarKind::Bool) => spirv::Op::LogicalEqual, _ => unreachable!(), }, crate::BinaryOperator::NotEqual => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => - spirv::Op::INotEqual, + Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { + spirv::Op::INotEqual + } Some(crate::ScalarKind::Float) => spirv::Op::FOrdNotEqual, Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNotEqual, _ => unreachable!(), diff --git a/test-data/simple.frag b/test-data/simple.frag deleted file mode 100644 index 2aea31896..000000000 --- a/test-data/simple.frag +++ /dev/null @@ -1,5 +0,0 @@ -#version 450 core - -void main() { - gl_FragDepth = 0; -} diff --git a/test-data/simple.vert b/test-data/simple.vert deleted file mode 100644 index 3aa56b2e9..000000000 --- a/test-data/simple.vert +++ /dev/null @@ -1,8 +0,0 @@ -#version 450 core - -layout(location = 0) in vec2 position; - -void main() { - float w = 1.0; - gl_Position = vec4(position, 0.0, w); -} diff --git a/test-data/simple/module.ron b/test-data/simple/module.ron deleted file mode 100644 index b99b24575..000000000 --- a/test-data/simple/module.ron +++ /dev/null @@ -1,124 +0,0 @@ -( - header: ( - version: (1, 0, 0), - generator: 0, - ), - types: [ - ( - name: None, - inner: Vector( - size: Bi, - kind: Float, - width: 4, - ), - ), - ( - name: None, - inner: Vector( - size: Quad, - kind: Float, - width: 4, - ), - ), - ( - name: None, - inner: Scalar( - kind: Float, - width: 4, - ), - ), - ], - constants: [ - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(1), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(0), - ), - ), - ], - global_variables: [ - ( - name: Some("a_pos"), - class: Input, - binding: Some(Location(0)), - ty: 1, - init: None, - interpolation: None, - storage_access: ( - bits: 0, - ), - ), - ( - name: Some("o_pos"), - class: Output, - binding: Some(Location(0)), - ty: 2, - init: None, - interpolation: None, - storage_access: ( - bits: 0, - ), - ), - ], - functions: [], - entry_points: { - (Vertex, "main"): ( - early_depth_test: None, - workgroup_size: (0, 0, 0), - function: ( - name: Some("main"), - arguments: [], - return_type: None, - global_usage: [ - ( - bits: 1, - ), - ( - bits: 2, - ), - ], - local_variables: [ - ( - name: Some("w"), - ty: 3, - init: Some(1), - ), - ], - expressions: [ - GlobalVariable(1), - GlobalVariable(2), - Constant(1), - LocalVariable(1), - Constant(2), - Compose( - ty: 2, - components: [ - 1, - 5, - 4, - ], - ), - ], - body: [ - Store( - pointer: 2, - value: 6, - ), - Return( - value: None, - ), - ], - ), - ), - }, -) \ No newline at end of file diff --git a/test-data/simple/x.spv b/test-data/simple/x.spv deleted file mode 100644 index 924ff447e06a0ed4945161b4e1229042388b8c39..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 500 zcmYk2PfJ2k5XHy$e41MRNy%LpEdyy`AxO1!<09|_h|s1*8W^USd-lGo#&CnMgruRC+y zdcr*E-!v;wj%y043Ti$HJ@4!{@B2f^y}vE_vh**}JaYYt59!>1U(v;F%rD4Kz)6aF zv_L(z8*YnjBI4_54DXPsx#I+W3jY6th(*brsb>8dXuX>CUC=kETVHXtYF>}rbI*(2 z(ODk%`hoSq1)jV5Z`9rKfqw2cAe<+6_BmnQGu@m!B&>0cp4&dMl{@JD!so;v(JmGt diff --git a/test-data/simple/x.vert b/test-data/simple/x.vert deleted file mode 100644 index 27c9f0406..000000000 --- a/test-data/simple/x.vert +++ /dev/null @@ -1,10 +0,0 @@ -#version 450 core - -layout(location = 0) in vec2 a_pos; -layout(location = 0) out vec4 o_pos; - -void main() { - float w = 1.0; - o_pos = vec4(a_pos, 0.0, w); - return; -} diff --git a/test-data/simple/x.wgsl b/test-data/simple/x.wgsl deleted file mode 100644 index 563cf1645..000000000 --- a/test-data/simple/x.wgsl +++ /dev/null @@ -1,10 +0,0 @@ -// vertex -[[location(0)]] var a_pos : vec2; -[[location(0)]] var o_pos : vec4; - -[[stage(vertex)]] -fn main() -> void { - var w: f32 = 1.0; - o_pos = vec4(a_pos, 0.0, w); - return; -} diff --git a/test-data/spv/cube.frag.spv b/test-data/spv/cube.frag.spv deleted file mode 100644 index 41358746fd14ea891129cce085219a17fdedc963..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1208 zcmYk4T}xC^6o%J09krbN$kf!z8STrQCWDF~O2`XugcPMN2f;yv>cBXJmqPTP`f1(> zKF^-B!wv83z25b%&pGvxwXuj=+=}sd6T>qTBQOyYF`Dk3-GklE+2FYI_T8q6$*3ox znyDBgHWGdwo&M4>4_aUvojwZis*^S1A3+7IeAXBEZetI6=gHUb-Q6yKl>KB+W1s!E ziWit2kq~hc~#=8&o=6nv!k?j|i z{g*!UuLCvmdobpF3FI>xRjmy;^LK!C{cqInSGivCR^!Q>+8md;*A-`#e5kqaZ%02%;bg?L!}g7GF!yD1n+t5~cVr{5SqIUj)y$ z$%1Z}%$_r|XJ#iUmpU`XOqppjYdR)hbyE^!%z~*}-|Y|jM``wWbaHx3#nv^~R}eOi(4N`w2svB1m*Om97%;9e|vmg9)S z{mr9iIKDtvZ_dK?ie9yqVy@wOb>9_T$LXV+6&V_EXwVz?XvM|PZI36t_TkY15k<>Hfy9)QiOdMk z5B&l9ys#l;^h@jgP@t!XzcHSeS@~XuOw?74{Ns?JXzbof*Gv6%^OKaOAgXD`X7K7M-D1hdx*`maiZQ&osB3vlfJ9&?qL=LSigW$EyNV%(iwZTN(%OXp7DEsk4}UKQ}2YXjzm zV;<@>1h^Z;Gp{eeAqm%%4wn)FWpSHr!58pxKYCuO2KU<$xH)&GCpPils&FFw0HeY$ Aw*UYD diff --git a/test-data/glsl_constant_expression.vert b/tests/cases/glsl_constant_expression.vert similarity index 100% rename from test-data/glsl_constant_expression.vert rename to tests/cases/glsl_constant_expression.vert diff --git a/test-data/glsl_if_preprocessor.vert b/tests/cases/glsl_if_preprocessor.vert similarity index 100% rename from test-data/glsl_if_preprocessor.vert rename to tests/cases/glsl_if_preprocessor.vert diff --git a/test-data/glsl_phong_lighting.frag b/tests/cases/glsl_phong_lighting.frag similarity index 100% rename from test-data/glsl_phong_lighting.frag rename to tests/cases/glsl_phong_lighting.frag diff --git a/test-data/glsl_preprocessor_abuse.vert b/tests/cases/glsl_preprocessor_abuse.vert similarity index 100% rename from test-data/glsl_preprocessor_abuse.vert rename to tests/cases/glsl_preprocessor_abuse.vert diff --git a/test-data/glsl_vertex_test_shader.vert b/tests/cases/glsl_vertex_test_shader.vert similarity index 100% rename from test-data/glsl_vertex_test_shader.vert rename to tests/cases/glsl_vertex_test_shader.vert diff --git a/tests/parse.rs b/tests/parse.rs index fe03f153b..9e736d7ec 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -2,7 +2,7 @@ #[cfg(feature = "glsl-in")] fn check_glsl(name: &str) { - let path = std::path::PathBuf::from("test-data").join(name); + let path = std::path::PathBuf::from("tests/cases").join(name); let input = std::fs::read_to_string(path).unwrap(); let stage = if name.ends_with(".vert") { naga::ShaderStage::Vertex diff --git a/tests/rosetta.rs b/tests/rosetta.rs deleted file mode 100644 index 9f3c571bf..000000000 --- a/tests/rosetta.rs +++ /dev/null @@ -1,80 +0,0 @@ -use std::{fs, path::Path}; - -fn test_rosetta(dir_name: &str) { - let dir_path = Path::new("test-data").join(dir_name); - #[cfg_attr(not(feature = "serde"), allow(unused))] - let expected = fs::read_to_string(dir_path.join("module.ron")).unwrap(); - - #[cfg(feature = "deserialize")] - { - use naga::back::*; - let module = ron::de::from_str::(&expected).unwrap(); - naga::proc::Validator::new().validate(&module).unwrap(); - - #[cfg(feature = "spv-out")] - { - let capabilities = Some(spirv::Capability::Shader).into_iter().collect(); - let spv = spv::write_vec(&module, spv::WriterFlags::NONE, capabilities).unwrap(); - assert!(spv.len() > 0); - } - } - - #[cfg(feature = "serialize")] - { - use naga::front::*; - - fn check(name: &str, module: &naga::Module, expected: &str) { - let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); - if output != expected { - let changeset = difference::Changeset::new(expected, &output, ""); - panic!("'{}' failed with diff:\n{}", name, changeset); - } - } - - #[cfg(feature = "wgsl-in")] - { - let input = fs::read_to_string(dir_path.join("x.wgsl")).unwrap(); - let module = wgsl::parse_str(&input).unwrap(); - check("wgsl", &module, &expected); - } - - #[cfg(feature = "glsl-in")] - { - if let Ok(input) = fs::read_to_string(dir_path.join("x.vert")) { - let module = glsl::parse_str( - &input, - "main", - naga::ShaderStage::Vertex, - Default::default(), - ) - .unwrap(); - check("vert", &module, &expected); - } - if let Ok(input) = fs::read_to_string(dir_path.join("x.frag")) { - let module = glsl::parse_str( - &input, - "main", - naga::ShaderStage::Fragment, - Default::default(), - ) - .unwrap(); - check("frag", &module, &expected); - } - if let Ok(input) = fs::read_to_string(dir_path.join("x.comp")) { - let module = glsl::parse_str( - &input, - "main", - naga::ShaderStage::Compute, - Default::default(), - ) - .unwrap(); - check("comp", &module, &expected); - } - } - } -} - -#[test] -fn simple() { - test_rosetta("simple"); -} From 0ea8a0a3c2ce1211511d763915fcc511408240c0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 23 Jan 2021 01:57:02 -0500 Subject: [PATCH 0372/2212] [wgsl] support unsigned literals --- src/front/wgsl/lexer.rs | 91 +++++++++++++++---- src/front/wgsl/mod.rs | 60 ++++++++---- tests/snapshots.rs | 12 +-- tests/snapshots/in/boids.wgsl | 8 +- tests/snapshots/in/collatz.wgsl | 12 +-- .../in/{simple.param.ron => empty.param.ron} | 0 tests/snapshots/in/empty.wgsl | 2 + tests/snapshots/in/simple.wgsl | 7 -- tests/snapshots/snapshots__boids.msl.snap | 7 +- tests/snapshots/snapshots__collatz.msl.snap | 13 ++- ...nap => snapshots__empty-Compute.glsl.snap} | 1 - tests/snapshots/snapshots__empty.msl.snap | 12 +++ ...vasm.snap => snapshots__empty.spvasm.snap} | 14 +-- tests/snapshots/snapshots__simple.msl.snap | 22 ----- 14 files changed, 156 insertions(+), 105 deletions(-) rename tests/snapshots/in/{simple.param.ron => empty.param.ron} (100%) create mode 100644 tests/snapshots/in/empty.wgsl delete mode 100644 tests/snapshots/in/simple.wgsl rename tests/snapshots/{snapshots__simple-Vertex.glsl.snap => snapshots__empty-Compute.glsl.snap} (83%) create mode 100644 tests/snapshots/snapshots__empty.msl.snap rename tests/snapshots/{snapshots__simple.spvasm.snap => snapshots__empty.spvasm.snap} (51%) delete mode 100644 tests/snapshots/snapshots__simple.msl.snap diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index fed5214c7..fb68a4782 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -13,7 +13,8 @@ fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { input.split_at(pos) } -fn consume_number(input: &str) -> (&str, &str) { +fn consume_number(input: &str) -> (Token, &str) { + //Note: I wish this function was simpler and faster... let mut is_first_char = true; let mut right_after_exponent = false; @@ -32,7 +33,28 @@ fn consume_number(input: &str) -> (&str, &str) { } }; let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); - input.split_at(pos) + let (value, rest) = input.split_at(pos); + + let mut rest_iter = rest.chars(); + let ty = rest_iter.next().unwrap_or(' '); + match ty { + 'u' | 'i' | 'f' => { + let width_end = rest_iter + .position(|c| !('0'..='9').contains(&c)) + .unwrap_or_else(|| rest.len() - 1); + let (width, rest) = rest[1..].split_at(width_end); + (Token::Number { value, ty, width }, rest) + } + // default to `i32` or `f32` + _ => ( + Token::Number { + value, + ty: if value.contains('.') { 'f' } else { 'i' }, + width: "", + }, + rest, + ), + } } fn consume_token(mut input: &str) -> (Token<'_>, &str) { @@ -56,10 +78,7 @@ fn consume_token(mut input: &str) -> (Token<'_>, &str) { '.' => { let og_chars = chars.as_str(); match chars.next() { - Some('0'..='9') => { - let (number, rest) = consume_number(input); - (Token::Number(number), rest) - } + Some('0'..='9') => consume_number(input), _ => (Token::Separator(cur), og_chars), } } @@ -83,10 +102,7 @@ fn consume_token(mut input: &str) -> (Token<'_>, &str) { (Token::Paren(cur), input) } } - '0'..='9' => { - let (number, rest) = consume_number(input); - (Token::Number(number), rest) - } + '0'..='9' => consume_number(input), 'a'..='z' | 'A'..='Z' | '_' => { let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); (Token::Word(word), rest) @@ -115,10 +131,7 @@ fn consume_token(mut input: &str) -> (Token<'_>, &str) { let og_chars = chars.as_str(); match chars.next() { Some('>') => (Token::Arrow, chars.as_str()), - Some('0'..='9') | Some('.') => { - let (number, rest) = consume_number(input); - (Token::Number(number), rest) - } + Some('0'..='9') | Some('.') => consume_number(input), _ => (Token::Operation(cur), og_chars), } } @@ -193,21 +206,25 @@ impl<'a> Lexer<'a> { fn _next_float_literal(&mut self) -> Result> { match self.next() { - Token::Number(word) => word.parse().map_err(|err| Error::BadFloat(word, err)), + Token::Number { value, .. } => value.parse().map_err(|err| Error::BadFloat(value, err)), other => other.unexpected("float literal"), } } pub(super) fn next_uint_literal(&mut self) -> Result> { match self.next() { - Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), + Token::Number { value, .. } => { + value.parse().map_err(|err| Error::BadInteger(value, err)) + } other => other.unexpected("uint literal"), } } pub(super) fn next_sint_literal(&mut self) -> Result> { match self.next() { - Token::Number(word) => word.parse().map_err(|err| Error::BadInteger(word, err)), + Token::Number { value, .. } => { + value.parse().map_err(|err| Error::BadInteger(value, err)) + } other => other.unexpected("sint literal"), } } @@ -246,7 +263,39 @@ fn sub_test(source: &str, expected_tokens: &[Token]) { #[test] fn test_tokens() { sub_test("id123_OK", &[Token::Word("id123_OK")]); - sub_test("92No", &[Token::Number("92"), Token::Word("No")]); + sub_test( + "92No", + &[ + Token::Number { + value: "92", + ty: 'i', + width: "", + }, + Token::Word("No"), + ], + ); + sub_test( + "2u3o", + &[ + Token::Number { + value: "2", + ty: 'u', + width: "3", + }, + Token::Word("o"), + ], + ); + sub_test( + "2.4f44po", + &[ + Token::Number { + value: "2.4", + ty: 'f', + width: "44", + }, + Token::Word("po"), + ], + ); sub_test( "æNoø", &[Token::Unknown('æ'), Token::Word("No"), Token::Unknown('ø')], @@ -264,7 +313,11 @@ fn test_variable_decl() { Token::DoubleParen('['), Token::Word("group"), Token::Paren('('), - Token::Number("0"), + Token::Number { + value: "0", + ty: 'i', + width: "", + }, Token::Paren(')'), Token::DoubleParen(']'), Token::Word("var"), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 578e94696..fbff173b9 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -23,7 +23,11 @@ pub enum Token<'a> { DoubleColon, Paren(char), DoubleParen(char), - Number(&'a str), + Number { + value: &'a str, + ty: char, + width: &'a str, + }, String(&'a str), Word(&'a str), Operation(char), @@ -50,6 +54,8 @@ pub enum Error<'a> { BadInteger(&'a str, std::num::ParseIntError), #[error("unable to parse `{1}` as float: {1}")] BadFloat(&'a str, std::num::ParseFloatError), + #[error("unable to parse `{0}{1}{2}` as scalar width: {3}")] + BadScalarWidth(&'a str, char, &'a str, std::num::ParseIntError), #[error("bad field accessor `{0}`")] BadAccessor(&'a str), #[error("bad texture {0}`")] @@ -369,16 +375,37 @@ impl Parser { } } - fn get_scalar_value(word: &str) -> Result> { - if word.contains('.') { - word.parse() - .map(crate::ScalarValue::Float) - .map_err(|err| Error::BadFloat(word, err)) - } else { - word.parse() + fn get_constant_inner<'a>( + word: &'a str, + ty: char, + width: &'a str, + ) -> Result> { + let value = match ty { + 'i' => word + .parse() .map(crate::ScalarValue::Sint) - .map_err(|err| Error::BadInteger(word, err)) - } + .map_err(|err| Error::BadInteger(word, err))?, + 'u' => word + .parse() + .map(crate::ScalarValue::Uint) + .map_err(|err| Error::BadInteger(word, err))?, + 'f' => word + .parse() + .map(crate::ScalarValue::Float) + .map_err(|err| Error::BadFloat(word, err))?, + _ => unreachable!(), + }; + Ok(crate::ConstantInner::Scalar { + value, + width: if width.is_empty() { + 4 + } else { + match width.parse::() { + Ok(bits) => bits / 8, + Err(e) => return Err(Error::BadScalarWidth(word, ty, width, e)), + } + }, + }) } fn parse_function_call_inner<'a>( @@ -698,12 +725,9 @@ impl Parser { value: crate::ScalarValue::Bool(false), } } - Token::Number(word) => { + Token::Number { value, ty, width } => { let _ = lexer.next(); - crate::ConstantInner::Scalar { - width: 4, - value: Self::get_scalar_value(word)?, - } + Self::get_constant_inner(value, ty, width)? } _ => { let (composite_ty, _access) = @@ -773,12 +797,12 @@ impl Parser { }); crate::Expression::Constant(handle) } - Token::Number(word) => { - let value = Self::get_scalar_value(word)?; + Token::Number { value, ty, width } => { + let inner = Self::get_constant_inner(value, ty, width)?; let handle = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, - inner: crate::ConstantInner::Scalar { width: 4, value }, + inner, }); crate::Expression::Constant(handle) } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 4732b19ce..9016c3be0 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -155,30 +155,30 @@ fn convert_wgsl(name: &str, language: Language) { #[cfg(feature = "wgsl-in")] #[test] -fn converts_wgsl_quad() { +fn convert_wgsl_quad() { convert_wgsl("quad", Language::all()); } #[cfg(feature = "wgsl-in")] #[test] -fn converts_wgsl_simple() { - convert_wgsl("simple", Language::all()); +fn convert_wgsl_empty() { + convert_wgsl("empty", Language::all()); } #[cfg(feature = "wgsl-in")] #[test] -fn converts_wgsl_boids() { +fn convert_wgsl_boids() { convert_wgsl("boids", Language::METAL); } #[cfg(feature = "wgsl-in")] #[test] -fn converts_wgsl_skybox() { +fn convert_wgsl_skybox() { convert_wgsl("skybox", Language::all()); } #[cfg(feature = "wgsl-in")] #[test] -fn converts_wgsl_collatz() { +fn convert_wgsl_collatz() { convert_wgsl("collatz", Language::METAL); } diff --git a/tests/snapshots/in/boids.wgsl b/tests/snapshots/in/boids.wgsl index 2e8b07425..b75b671a0 100644 --- a/tests/snapshots/in/boids.wgsl +++ b/tests/snapshots/in/boids.wgsl @@ -69,7 +69,7 @@ struct Particles { [[stage(compute), workgroup_size(1)]] fn main() { const index : u32 = gl_GlobalInvocationID.x; - if (index >= u32(5)) { + if (index >= 5u) { return; } @@ -84,9 +84,9 @@ fn main() { var pos : vec2; var vel : vec2; - var i : u32 = u32(0); + var i : u32 = 0u; loop { - if (i >= u32(5)) { + if (i >= 5u) { break; } if (i == index) { @@ -109,7 +109,7 @@ fn main() { } continuing { - i = i + u32(1); + i = i + 1u; } } if (cMassCount > 0) { diff --git a/tests/snapshots/in/collatz.wgsl b/tests/snapshots/in/collatz.wgsl index a0853e0e4..5c9731026 100644 --- a/tests/snapshots/in/collatz.wgsl +++ b/tests/snapshots/in/collatz.wgsl @@ -15,18 +15,18 @@ var v_indices: [[access(read_write)]] PrimeIndices; // Though the conjecture has not been proven, no counterexample has ever been found. // This function returns how many times this recurrence needs to be applied to reach 1. fn collatz_iterations(n: u32) -> u32{ - var i: u32 = u32(0); + var i: u32 = 0u; loop { - if (n <= u32(1)) { + if (n <= 1u) { break; } - if (n % u32(2) == u32(0)) { - n = n / u32(2); + if (n % 2u == 0u) { + n = n / 2u; } else { - n = u32(3) * n + i32(1); + n = 3u * n + 1u; } - i = i + u32(1); + i = i + 1u; } return i; } diff --git a/tests/snapshots/in/simple.param.ron b/tests/snapshots/in/empty.param.ron similarity index 100% rename from tests/snapshots/in/simple.param.ron rename to tests/snapshots/in/empty.param.ron diff --git a/tests/snapshots/in/empty.wgsl b/tests/snapshots/in/empty.wgsl new file mode 100644 index 000000000..9bd04d80c --- /dev/null +++ b/tests/snapshots/in/empty.wgsl @@ -0,0 +1,2 @@ +[[stage(compute), workgroup_size(1)]] +fn main() {} diff --git a/tests/snapshots/in/simple.wgsl b/tests/snapshots/in/simple.wgsl deleted file mode 100644 index 54d492356..000000000 --- a/tests/snapshots/in/simple.wgsl +++ /dev/null @@ -1,7 +0,0 @@ -// vertex -[[builtin(position)]] var o_position : vec4; - -[[stage(vertex)]] -fn main() { - o_position = vec4(1); -} diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap index ca9665c13..13a3f32fd 100644 --- a/tests/snapshots/snapshots__boids.msl.snap +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -71,17 +71,16 @@ kernel void main3( type6 cVelCount = 0; type pos1; type vel1; - type5 i; - if (gl_GlobalInvocationID.x >= static_cast(5)) { + type5 i = 0; + if (gl_GlobalInvocationID.x >= 5) { } vPos = particlesA.particles[gl_GlobalInvocationID.x].pos; vVel = particlesA.particles[gl_GlobalInvocationID.x].vel; cMass = metal::float2(0.0, 0.0); cVel = metal::float2(0.0, 0.0); colVel = metal::float2(0.0, 0.0); - i = static_cast(0); while(true) { - if (i >= static_cast(5)) { + if (i >= 5) { break; } if (i == gl_GlobalInvocationID.x) { diff --git a/tests/snapshots/snapshots__collatz.msl.snap b/tests/snapshots/snapshots__collatz.msl.snap index be5eb887a..f076a55da 100644 --- a/tests/snapshots/snapshots__collatz.msl.snap +++ b/tests/snapshots/snapshots__collatz.msl.snap @@ -15,18 +15,17 @@ struct PrimeIndices { type1 collatz_iterations( type1 n ) { - type1 i; - i = static_cast(0); + type1 i = 0; while(true) { - if (n <= static_cast(1)) { + if (n <= 1) { break; } - if (n % static_cast(2) == static_cast(0)) { - n = n / static_cast(2); + if (n % 2 == 0) { + n = n / 2; } else { - n = static_cast(3) * n + static_cast(1); + n = 3 * n + 1; } - i = i + static_cast(1); + i = i + 1; } return i; } diff --git a/tests/snapshots/snapshots__simple-Vertex.glsl.snap b/tests/snapshots/snapshots__empty-Compute.glsl.snap similarity index 83% rename from tests/snapshots/snapshots__simple-Vertex.glsl.snap rename to tests/snapshots/snapshots__empty-Compute.glsl.snap index d32d80074..9fb9bfbaa 100644 --- a/tests/snapshots/snapshots__simple-Vertex.glsl.snap +++ b/tests/snapshots/snapshots__empty-Compute.glsl.snap @@ -11,7 +11,6 @@ precision highp float; void main() { - gl_Position = vec4(1); return; } diff --git a/tests/snapshots/snapshots__empty.msl.snap b/tests/snapshots/snapshots__empty.msl.snap new file mode 100644 index 000000000..6f2876dcc --- /dev/null +++ b/tests/snapshots/snapshots__empty.msl.snap @@ -0,0 +1,12 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + + +kernel void main1( +) { +} + diff --git a/tests/snapshots/snapshots__simple.spvasm.snap b/tests/snapshots/snapshots__empty.spvasm.snap similarity index 51% rename from tests/snapshots/snapshots__simple.spvasm.snap rename to tests/snapshots/snapshots__empty.spvasm.snap index 1d6cad3c4..ae2b9628b 100644 --- a/tests/snapshots/snapshots__simple.spvasm.snap +++ b/tests/snapshots/snapshots__empty.spvasm.snap @@ -5,23 +5,15 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 13 +; Bound: 6 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %3 "main" %6 -OpDecorate %6 BuiltIn Position +OpEntryPoint GLCompute %3 "main" +OpExecutionMode %3 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFunction %2 -%8 = OpTypeFloat 32 -%7 = OpTypeVector %8 4 -%9 = OpTypePointer Output %7 -%6 = OpVariable %9 Output -%11 = OpTypeInt 32 1 -%10 = OpConstant %11 1 %3 = OpFunction %2 None %4 %5 = OpLabel -%12 = OpCompositeConstruct %7 %10 -OpStore %6 %12 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__simple.msl.snap b/tests/snapshots/snapshots__simple.msl.snap deleted file mode 100644 index 1102c4ea8..000000000 --- a/tests/snapshots/snapshots__simple.msl.snap +++ /dev/null @@ -1,22 +0,0 @@ ---- -source: tests/snapshots.rs -expression: msl ---- -#include -#include - -typedef metal::float4 type; - -struct main1Input { -}; -struct main1Output { - type o_position [[position]]; -}; -vertex main1Output main1( - main1Input input [[stage_in]] -) { - main1Output output; - output.o_position = metal::float4(1); - return output; -} - From 98c18d71dbf4a18ff86f6e85890a9274aa3f30b6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 24 Jan 2021 20:24:26 -0500 Subject: [PATCH 0373/2212] Switch to column major --- src/back/spv/writer.rs | 8 +++++--- tests/snapshots/snapshots__skybox.spvasm.snap | 4 ++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d20232652..2b1d2c25d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -588,7 +588,7 @@ impl Writer { self.annotations .push(super::instructions::instruction_decorate( id, - spirv::Decoration::RowMajor, + spirv::Decoration::ColMajor, &[], )); let vector_id = self.get_type_id( @@ -1743,8 +1743,10 @@ impl Writer { #[cfg(test)] mod tests { - use crate::back::spv::{Writer, WriterFlags}; - use crate::Header; + use crate::{ + back::spv::{Writer, WriterFlags}, + Header, + }; #[test] fn test_writer_generate_id() { diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap index 1dd5b6b3c..191f5f0e2 100644 --- a/tests/snapshots/snapshots__skybox.spvasm.snap +++ b/tests/snapshots/snapshots__skybox.spvasm.snap @@ -13,11 +13,11 @@ OpEntryPoint Vertex %11 "vs_main" %157 %44 %15 OpEntryPoint Fragment %168 "fs_main" %180 %170 OpExecutionMode %168 OriginUpperLeft OpDecorate %15 BuiltIn VertexIndex -OpDecorate %27 RowMajor +OpDecorate %27 ColMajor OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 0 OpDecorate %44 Location 0 -OpDecorate %48 RowMajor +OpDecorate %48 ColMajor OpDecorate %157 BuiltIn Position OpDecorate %170 Location 0 OpDecorate %171 DescriptorSet 0 From 2bdcacc2b04351ffe7109913cee0f12793c408f1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 24 Jan 2021 20:44:30 -0500 Subject: [PATCH 0374/2212] Update MSRV to 1.43 --- .github/workflows/pipeline.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 927afb7be..5ee486280 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -7,7 +7,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - rust: [1.41.0, nightly] + rust: [1.43.0, nightly] steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 From c803240587d4360741365b9b7ef27358d5bf6be2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 25 Jan 2021 00:54:14 -0500 Subject: [PATCH 0375/2212] [wgsl] resolve types across functions --- src/front/wgsl/mod.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index fbff173b9..5d2ebee49 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -117,6 +117,7 @@ struct StatementContext<'input, 'temp, 'out> { types: &'out mut Arena, constants: &'out mut Arena, global_vars: &'out Arena, + functions: &'out Arena, arguments: &'out [crate::FunctionArgument], } @@ -130,6 +131,7 @@ impl<'a> StatementContext<'a, '_, '_> { types: self.types, constants: self.constants, global_vars: self.global_vars, + functions: self.functions, arguments: self.arguments, } } @@ -143,6 +145,7 @@ impl<'a> StatementContext<'a, '_, '_> { constants: self.constants, global_vars: self.global_vars, local_vars: self.variables, + functions: self.functions, arguments: self.arguments, } } @@ -163,6 +166,7 @@ struct ExpressionContext<'input, 'temp, 'out> { global_vars: &'out Arena, local_vars: &'out Arena, arguments: &'out [crate::FunctionArgument], + functions: &'out Arena, } impl<'a> ExpressionContext<'a, '_, '_> { @@ -175,6 +179,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { constants: self.constants, global_vars: self.global_vars, local_vars: self.local_vars, + functions: self.functions, arguments: self.arguments, } } @@ -183,12 +188,11 @@ impl<'a> ExpressionContext<'a, '_, '_> { &mut self, handle: Handle, ) -> Result<&crate::TypeInner, Error<'a>> { - let functions = Arena::new(); //TODO let resolve_ctx = ResolveContext { constants: self.constants, global_vars: self.global_vars, local_vars: self.local_vars, - functions: &functions, + functions: self.functions, arguments: self.arguments, }; match self @@ -1815,6 +1819,7 @@ impl Parser { types: &mut module.types, constants: &mut module.constants, global_vars: &module.global_variables, + functions: &module.functions, arguments: &fun.arguments, }, )?; From a5184fba491fe4c1a855297358871486a9c1dccb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 25 Jan 2021 01:30:59 -0500 Subject: [PATCH 0376/2212] Check for the block decorator in the validator --- src/proc/validator.rs | 22 +++++++++++++++++++ tests/snapshots/in/collatz.wgsl | 1 + tests/snapshots/in/skybox.wgsl | 2 +- .../snapshots__skybox-Vertex.glsl.snap | 7 +++++- tests/snapshots/snapshots__skybox.spvasm.snap | 5 +++++ 5 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index d91773e66..f6b1f153f 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -40,6 +40,8 @@ pub enum GlobalVariableError { InvalidUsage, #[error("Type isn't compatible with the storage class")] InvalidType, + #[error("Structure doesn't have a block decoration, can't be host-shared")] + MissingBlockDecoration, #[error("Interpolation is not valid")] InvalidInterpolation, #[error("Storage access {seen:?} exceed the allowed {allowed:?}")] @@ -222,6 +224,22 @@ impl crate::GlobalVariable { } } +impl crate::TypeInner { + fn check_block(&self) -> Result<(), GlobalVariableError> { + match *self { + Self::Struct { + block: true, + members: _, + } => Ok(()), + Self::Struct { + block: false, + members: _, + } => Err(GlobalVariableError::MissingBlockDecoration), + _ => Err(GlobalVariableError::InvalidType), + } + } +} + fn storage_usage(access: crate::StorageAccess) -> crate::GlobalUse { let mut storage_usage = crate::GlobalUse::empty(); if access.contains(crate::StorageAccess::LOAD) { @@ -388,10 +406,14 @@ impl Validator { } crate::StorageClass::Storage => { var.check_resource()?; + let ty = &types[var.ty]; + ty.inner.check_block()?; crate::StorageAccess::all() } crate::StorageClass::Uniform => { var.check_resource()?; + let ty = &types[var.ty]; + ty.inner.check_block()?; crate::StorageAccess::empty() } crate::StorageClass::Handle => { diff --git a/tests/snapshots/in/collatz.wgsl b/tests/snapshots/in/collatz.wgsl index 5c9731026..54312943d 100644 --- a/tests/snapshots/in/collatz.wgsl +++ b/tests/snapshots/in/collatz.wgsl @@ -1,6 +1,7 @@ [[builtin(global_invocation_id)]] var global_id: vec3; +[[block]] struct PrimeIndices { data: array; }; // this is used as both input and output for convenience diff --git a/tests/snapshots/in/skybox.wgsl b/tests/snapshots/in/skybox.wgsl index 4cd838133..9254ab6a2 100644 --- a/tests/snapshots/in/skybox.wgsl +++ b/tests/snapshots/in/skybox.wgsl @@ -3,7 +3,7 @@ var out_position: vec4; [[location(0)]] var out_uv: vec3; [[builtin(vertex_index)]] var in_vertex_index: u32; -//[[block]] +[[block]] struct Data { proj_inv: mat4x4; view: mat4x4; diff --git a/tests/snapshots/snapshots__skybox-Vertex.glsl.snap b/tests/snapshots/snapshots__skybox-Vertex.glsl.snap index 14efd3e49..651626a5f 100644 --- a/tests/snapshots/snapshots__skybox-Vertex.glsl.snap +++ b/tests/snapshots/snapshots__skybox-Vertex.glsl.snap @@ -13,7 +13,12 @@ struct Data { }; out vec3 _location_0_vs; -uniform Data _group_0_binding_0; +uniform Data_block_0 { + +mat4x4 proj_inv; + +mat4x4 view; +} _group_0_binding_0; void main() { int tmp1_; diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap index 191f5f0e2..3e5289334 100644 --- a/tests/snapshots/snapshots__skybox.spvasm.snap +++ b/tests/snapshots/snapshots__skybox.spvasm.snap @@ -13,7 +13,12 @@ OpEntryPoint Vertex %11 "vs_main" %157 %44 %15 OpEntryPoint Fragment %168 "fs_main" %180 %170 OpExecutionMode %168 OriginUpperLeft OpDecorate %15 BuiltIn VertexIndex +OpDecorate %26 Block +OpMemberDecorate %26 0 Offset 0 +OpMemberDecorate %26 0 MatrixStride 16 OpDecorate %27 ColMajor +OpMemberDecorate %26 1 Offset 64 +OpMemberDecorate %26 1 MatrixStride 16 OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 0 OpDecorate %44 Location 0 From 58f38ba61d4af4d1658a7fd2a6f15b2d3d0a97a3 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Mon, 25 Jan 2021 20:30:23 -0330 Subject: [PATCH 0377/2212] [msl-out] Improve formatting of whitespace --- src/back/msl/writer.rs | 51 ++++-- tests/snapshots/snapshots__boids.msl.snap | 191 +++++++++++--------- tests/snapshots/snapshots__collatz.msl.snap | 40 ++-- tests/snapshots/snapshots__empty.msl.snap | 1 - tests/snapshots/snapshots__quad.msl.snap | 44 +++-- tests/snapshots/snapshots__skybox.msl.snap | 65 ++++--- 6 files changed, 226 insertions(+), 166 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index afe4607fe..0ba3a5e70 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -10,6 +10,7 @@ use std::{ }; const NAMESPACE: &str = "metal"; +const INDENT: &str = " "; struct Level(usize); impl Level { @@ -19,7 +20,7 @@ impl Level { } impl Display for Level { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - (0..self.0).try_for_each(|_| formatter.write_str("\t")) + (0..self.0).try_for_each(|_| formatter.write_str(INDENT)) } } @@ -649,7 +650,7 @@ impl Writer { writeln!(self.out, "{}discard_fragment();", level)?; } crate::Statement::Store { pointer, value } => { - //write!(self.out, "\t*")?; + //write!(self.out, "{}*", INDENT)?; write!(self.out, "{}", level)?; self.put_expression(pointer, context)?; write!(self.out, " = ")?; @@ -671,11 +672,9 @@ impl Writer { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; - writeln!(self.out)?; + self.write_type_defs(module)?; - - writeln!(self.out)?; self.write_functions(module, options) } @@ -745,7 +744,7 @@ impl Writer { for (index, member) in members.iter().enumerate() { let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; let base_name = &self.names[&NameKey::Type(member.ty)]; - writeln!(self.out, "\t{} {};", base_name, member_name)?; + writeln!(self.out, "{}{} {};", INDENT, base_name, member_name)?; } write!(self.out, "}}")?; } @@ -809,6 +808,7 @@ impl Writer { } } writeln!(self.out, ";")?; + writeln!(self.out)?; } Ok(()) } @@ -843,14 +843,18 @@ impl Writer { let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; let param_type_name = &self.names[&NameKey::Type(arg.ty)]; let separator = separate(index + 1 == fun.arguments.len()); - writeln!(self.out, "\t{} {}{}", param_type_name, name, separator)?; + writeln!( + self.out, + "{}{} {}{}", + INDENT, param_type_name, name, separator + )?; } writeln!(self.out, ") {{")?; for (local_handle, local) in fun.local_variables.iter() { let ty_name = &self.names[&NameKey::Type(local.ty)]; let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; - write!(self.out, "\t{} {}", ty_name, local_name)?; + write!(self.out, "{}{} {}", INDENT, ty_name, local_name)?; if let Some(value) = local.init { write!(self.out, " = ")?; self.put_constant(value, module)?; @@ -865,6 +869,7 @@ impl Writer { }; self.put_block(Level(1), &fun.body, &context, None)?; writeln!(self.out, "}}")?; + writeln!(self.out)?; } let mut info = TranslationInfo { @@ -944,12 +949,14 @@ impl Writer { handle, usage: crate::GlobalUse::empty(), }; - write!(self.out, "\t")?; + write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; let resolved = options.resolve_binding(stage, var, in_mode)?; - resolved.try_fmt_decorated(&mut self.out, ";\n")?; + resolved.try_fmt_decorated(&mut self.out, ";")?; + writeln!(self.out)?; } writeln!(self.out, "}};")?; + writeln!(self.out)?; writeln!(self.out, "struct {} {{", output_name)?; for ((handle, var), &usage) in @@ -967,19 +974,21 @@ impl Writer { handle, usage: crate::GlobalUse::empty(), }; - write!(self.out, "\t")?; + write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; let resolved = options.resolve_binding(stage, var, out_mode)?; - resolved.try_fmt_decorated(&mut self.out, ";\n")?; + resolved.try_fmt_decorated(&mut self.out, ";")?; + writeln!(self.out)?; } writeln!(self.out, "}};")?; + writeln!(self.out)?; writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; let separator = separate(last_used_global.is_none()); writeln!( self.out, - "\t{} {} [[stage_in]]{}", - location_input_name, LOCATION_INPUT_STRUCT_NAME, separator + "{}{} {} [[stage_in]]{}", + INDENT, location_input_name, LOCATION_INPUT_STRUCT_NAME, separator )?; Some(OUTPUT_STRUCT_NAME) @@ -1021,7 +1030,7 @@ impl Writer { usage, }; let separator = separate(last_used_global == Some(handle)); - write!(self.out, "\t")?; + write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; resolved.try_fmt_decorated(&mut self.out, separator)?; if let Some(value) = var.init { @@ -1034,14 +1043,18 @@ impl Writer { match stage { crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { - writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?; + writeln!( + self.out, + "{}{} {};", + INDENT, output_name, OUTPUT_STRUCT_NAME + )?; } crate::ShaderStage::Compute => {} } for (local_handle, local) in fun.local_variables.iter() { let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; let ty_name = &self.names[&NameKey::Type(local.ty)]; - write!(self.out, "\t{} {}", ty_name, name)?; + write!(self.out, "{}{} {}", INDENT, ty_name, name)?; if let Some(value) = local.init { write!(self.out, " = ")?; self.put_constant(value, module)?; @@ -1056,6 +1069,10 @@ impl Writer { }; self.put_block(Level(1), &fun.body, &context, return_value)?; writeln!(self.out, "}}")?; + let is_last = ep_index == module.entry_points.len() - 1; + if !is_last { + writeln!(self.out)?; + } } Ok(info) diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap index 13a3f32fd..1e173def6 100644 --- a/tests/snapshots/snapshots__boids.msl.snap +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -6,122 +6,137 @@ expression: msl #include typedef metal::float2 type; + typedef metal::float4 type1; + typedef float type2; + struct Particle { - type pos; - type vel; + type pos; + type vel; }; + struct SimParams { - type2 deltaT; - type2 rule1Distance; - type2 rule2Distance; - type2 rule3Distance; - type2 rule1Scale; - type2 rule2Scale; - type2 rule3Scale; + type2 deltaT; + type2 rule1Distance; + type2 rule2Distance; + type2 rule3Distance; + type2 rule1Scale; + type2 rule2Scale; + type2 rule3Scale; }; + typedef Particle type3[5]; + struct Particles { - type3 particles; + type3 particles; }; + typedef metal::uint3 type4; + typedef uint type5; + typedef int type6; struct main1Input { - type a_particlePos [[attribute(0)]]; - type a_particleVel [[attribute(1)]]; - type a_pos [[attribute(2)]]; + type a_particlePos [[attribute(0)]]; + type a_particleVel [[attribute(1)]]; + type a_pos [[attribute(2)]]; }; + struct main1Output { - type1 gl_Position [[position]]; + type1 gl_Position [[position]]; }; + vertex main1Output main1( - main1Input input [[stage_in]] + main1Input input [[stage_in]] ) { - main1Output output; - output.gl_Position = metal::float4(metal::float2(input.a_pos.x * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) - input.a_pos.y * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)), input.a_pos.x * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) + input.a_pos.y * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y))) + input.a_particlePos, 0.0, 1.0); - return output; + main1Output output; + output.gl_Position = metal::float4(metal::float2(input.a_pos.x * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) - input.a_pos.y * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)), input.a_pos.x * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) + input.a_pos.y * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y))) + input.a_particlePos, 0.0, 1.0); + return output; } + struct main2Input { }; + struct main2Output { - type1 fragColor [[color(0)]]; + type1 fragColor [[color(0)]]; }; + fragment main2Output main2( - main2Input input [[stage_in]] + main2Input input [[stage_in]] ) { - main2Output output; - output.fragColor = metal::float4(1.0, 1.0, 1.0, 1.0); - return output; + main2Output output; + output.fragColor = metal::float4(1.0, 1.0, 1.0, 1.0); + return output; } + kernel void main3( - constant SimParams& params [[buffer(0)]], - constant Particles& particlesA [[buffer(1)]], - device Particles& particlesB [[buffer(2)]], - type4 gl_GlobalInvocationID [[thread_position_in_grid]] + constant SimParams& params [[buffer(0)]], + constant Particles& particlesA [[buffer(1)]], + device Particles& particlesB [[buffer(2)]], + type4 gl_GlobalInvocationID [[thread_position_in_grid]] ) { - type vPos; - type vVel; - type cMass; - type cVel; - type colVel; - type6 cMassCount = 0; - type6 cVelCount = 0; - type pos1; - type vel1; - type5 i = 0; - if (gl_GlobalInvocationID.x >= 5) { - } - vPos = particlesA.particles[gl_GlobalInvocationID.x].pos; - vVel = particlesA.particles[gl_GlobalInvocationID.x].vel; - cMass = metal::float2(0.0, 0.0); - cVel = metal::float2(0.0, 0.0); - colVel = metal::float2(0.0, 0.0); - while(true) { - if (i >= 5) { - break; - } - if (i == gl_GlobalInvocationID.x) { - continue; - } - pos1 = metal::float2(particlesA.particles[i].pos.x, particlesA.particles[i].pos.y); - vel1 = metal::float2(particlesA.particles[i].vel.x, particlesA.particles[i].vel.y); - if (metal::distance(pos1, vPos) < params.rule1Distance) { - cMass = cMass + pos1; - cMassCount = cMassCount + 1; - } - if (metal::distance(pos1, vPos) < params.rule2Distance) { - colVel = colVel - pos1 - vPos; - } - if (metal::distance(pos1, vPos) < params.rule3Distance) { - cVel = cVel + vel1; - cVelCount = cVelCount + 1; - } - } - if (cMassCount == 0) { - cMass = cMass / metal::float2(cMassCount, cMassCount) + vPos; - } - if (cVelCount == 0) { - cVel = cVel / metal::float2(cVelCount, cVelCount); - } - vVel = vVel + cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale; - vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); - vPos = vPos + vVel * params.deltaT; - if (vPos.x < -1.0) { - vPos.x = 1.0; - } - if (vPos.x == 1.0) { - vPos.x = -1.0; - } - if (vPos.y < -1.0) { - vPos.y = 1.0; - } - if (vPos.y == 1.0) { - vPos.y = -1.0; - } - particlesB.particles[gl_GlobalInvocationID.x].pos = vPos; - particlesB.particles[gl_GlobalInvocationID.x].vel = vVel; + type vPos; + type vVel; + type cMass; + type cVel; + type colVel; + type6 cMassCount = 0; + type6 cVelCount = 0; + type pos1; + type vel1; + type5 i = 0; + if (gl_GlobalInvocationID.x >= 5) { + } + vPos = particlesA.particles[gl_GlobalInvocationID.x].pos; + vVel = particlesA.particles[gl_GlobalInvocationID.x].vel; + cMass = metal::float2(0.0, 0.0); + cVel = metal::float2(0.0, 0.0); + colVel = metal::float2(0.0, 0.0); + while(true) { + if (i >= 5) { + break; + } + if (i == gl_GlobalInvocationID.x) { + continue; + } + pos1 = metal::float2(particlesA.particles[i].pos.x, particlesA.particles[i].pos.y); + vel1 = metal::float2(particlesA.particles[i].vel.x, particlesA.particles[i].vel.y); + if (metal::distance(pos1, vPos) < params.rule1Distance) { + cMass = cMass + pos1; + cMassCount = cMassCount + 1; + } + if (metal::distance(pos1, vPos) < params.rule2Distance) { + colVel = colVel - pos1 - vPos; + } + if (metal::distance(pos1, vPos) < params.rule3Distance) { + cVel = cVel + vel1; + cVelCount = cVelCount + 1; + } + } + if (cMassCount == 0) { + cMass = cMass / metal::float2(cMassCount, cMassCount) + vPos; + } + if (cVelCount == 0) { + cVel = cVel / metal::float2(cVelCount, cVelCount); + } + vVel = vVel + cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale; + vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); + vPos = vPos + vVel * params.deltaT; + if (vPos.x < -1.0) { + vPos.x = 1.0; + } + if (vPos.x == 1.0) { + vPos.x = -1.0; + } + if (vPos.y < -1.0) { + vPos.y = 1.0; + } + if (vPos.y == 1.0) { + vPos.y = -1.0; + } + particlesB.particles[gl_GlobalInvocationID.x].pos = vPos; + particlesB.particles[gl_GlobalInvocationID.x].vel = vVel; } diff --git a/tests/snapshots/snapshots__collatz.msl.snap b/tests/snapshots/snapshots__collatz.msl.snap index f076a55da..17840e041 100644 --- a/tests/snapshots/snapshots__collatz.msl.snap +++ b/tests/snapshots/snapshots__collatz.msl.snap @@ -6,33 +6,37 @@ expression: msl #include typedef metal::uint3 type; + typedef uint type1; + typedef type1 type2[1]; + struct PrimeIndices { - type2 data; + type2 data; }; type1 collatz_iterations( - type1 n + type1 n ) { - type1 i = 0; - while(true) { - if (n <= 1) { - break; - } - if (n % 2 == 0) { - n = n / 2; - } else { - n = 3 * n + 1; - } - i = i + 1; - } - return i; + type1 i = 0; + while(true) { + if (n <= 1) { + break; + } + if (n % 2 == 0) { + n = n / 2; + } else { + n = 3 * n + 1; + } + i = i + 1; + } + return i; } + kernel void main1( - type global_id [[thread_position_in_grid]], - device PrimeIndices& v_indices [[buffer(0)]] + type global_id [[thread_position_in_grid]], + device PrimeIndices& v_indices [[buffer(0)]] ) { - v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); + v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); } diff --git a/tests/snapshots/snapshots__empty.msl.snap b/tests/snapshots/snapshots__empty.msl.snap index 6f2876dcc..986df64c1 100644 --- a/tests/snapshots/snapshots__empty.msl.snap +++ b/tests/snapshots/snapshots__empty.msl.snap @@ -5,7 +5,6 @@ expression: msl #include #include - kernel void main1( ) { } diff --git a/tests/snapshots/snapshots__quad.msl.snap b/tests/snapshots/snapshots__quad.msl.snap index da25574b1..56d73255d 100644 --- a/tests/snapshots/snapshots__quad.msl.snap +++ b/tests/snapshots/snapshots__quad.msl.snap @@ -6,41 +6,51 @@ expression: msl #include typedef float type; + typedef metal::float2 type1; + typedef metal::float4 type2; + typedef metal::texture2d type3; + typedef metal::sampler type4; + typedef metal::int2 type5; struct main1Input { - type1 a_pos [[attribute(0)]]; - type1 a_uv [[attribute(1)]]; + type1 a_pos [[attribute(0)]]; + type1 a_uv [[attribute(1)]]; }; + struct main1Output { - type1 v_uv [[user(loc0)]]; - type2 o_position [[position]]; + type1 v_uv [[user(loc0)]]; + type2 o_position [[position]]; }; + vertex main1Output main1( - main1Input input [[stage_in]] + main1Input input [[stage_in]] ) { - main1Output output; - output.v_uv = input.a_uv; - output.o_position = metal::float4(1.2 * input.a_pos, 0.0, 1.0); - return output; + main1Output output; + output.v_uv = input.a_uv; + output.o_position = metal::float4(1.2 * input.a_pos, 0.0, 1.0); + return output; } + struct main2Input { - type1 v_uv1 [[user(loc0)]]; + type1 v_uv1 [[user(loc0)]]; }; + struct main2Output { - type2 o_color [[color(0)]]; + type2 o_color [[color(0)]]; }; + fragment main2Output main2( - main2Input input [[stage_in]], - type3 u_texture [[texture(0)]], - type4 u_sampler [[sampler(0)]] + main2Input input [[stage_in]], + type3 u_texture [[texture(0)]], + type4 u_sampler [[sampler(0)]] ) { - main2Output output; - output.o_color = u_texture.sample(u_sampler, input.v_uv1); - return output; + main2Output output; + output.o_color = u_texture.sample(u_sampler, input.v_uv1); + return output; } diff --git a/tests/snapshots/snapshots__skybox.msl.snap b/tests/snapshots/snapshots__skybox.msl.snap index 8bfaad4ca..ce8662f0d 100644 --- a/tests/snapshots/snapshots__skybox.msl.snap +++ b/tests/snapshots/snapshots__skybox.msl.snap @@ -6,55 +6,70 @@ expression: msl #include typedef metal::float4 type; + typedef metal::float3 type1; + typedef uint type2; + typedef metal::float4x4 type3; + struct Data { - type3 proj_inv; - type3 view; + type3 proj_inv; + type3 view; }; + typedef int type4; + typedef metal::float3x3 type5; + typedef float type6; + typedef metal::texturecube type7; + typedef metal::sampler type8; + typedef metal::int3 type9; struct vs_mainInput { }; + struct vs_mainOutput { - type out_position [[position]]; - type1 out_uv [[user(loc0)]]; + type out_position [[position]]; + type1 out_uv [[user(loc0)]]; }; + vertex vs_mainOutput vs_main( - vs_mainInput input [[stage_in]], - type2 in_vertex_index [[vertex_id]], - constant Data& r_data [[buffer(0)]] + vs_mainInput input [[stage_in]], + type2 in_vertex_index [[vertex_id]], + constant Data& r_data [[buffer(0)]] ) { - vs_mainOutput output; - type4 tmp1_; - type4 tmp2_; - type unprojected; - tmp1_ = static_cast(in_vertex_index) / 2; - tmp2_ = static_cast(in_vertex_index) & 1; - unprojected = r_data.proj_inv * metal::float4(static_cast(tmp1_) * 4.0 - 1.0, static_cast(tmp2_) * 4.0 - 1.0, 0.0, 1.0); - output.out_uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z); - output.out_position = metal::float4(static_cast(tmp1_) * 4.0 - 1.0, static_cast(tmp2_) * 4.0 - 1.0, 0.0, 1.0); - return output; + vs_mainOutput output; + type4 tmp1_; + type4 tmp2_; + type unprojected; + tmp1_ = static_cast(in_vertex_index) / 2; + tmp2_ = static_cast(in_vertex_index) & 1; + unprojected = r_data.proj_inv * metal::float4(static_cast(tmp1_) * 4.0 - 1.0, static_cast(tmp2_) * 4.0 - 1.0, 0.0, 1.0); + output.out_uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z); + output.out_position = metal::float4(static_cast(tmp1_) * 4.0 - 1.0, static_cast(tmp2_) * 4.0 - 1.0, 0.0, 1.0); + return output; } + struct fs_mainInput { - type1 in_uv [[user(loc0)]]; + type1 in_uv [[user(loc0)]]; }; + struct fs_mainOutput { - type out_color [[color(0)]]; + type out_color [[color(0)]]; }; + fragment fs_mainOutput fs_main( - fs_mainInput input [[stage_in]], - type7 r_texture [[texture(0)]], - type8 r_sampler [[sampler(1)]] + fs_mainInput input [[stage_in]], + type7 r_texture [[texture(0)]], + type8 r_sampler [[sampler(1)]] ) { - fs_mainOutput output; - output.out_color = r_texture.sample(r_sampler, input.in_uv); - return output; + fs_mainOutput output; + output.out_color = r_texture.sample(r_sampler, input.in_uv); + return output; } From d7225b4eb625f0a9ea0d89decb3c1443979229da Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Mon, 25 Jan 2021 21:03:45 -0330 Subject: [PATCH 0378/2212] [glsl-out] Improve formatting of whitespace --- src/back/glsl/mod.rs | 69 ++++++++++--------- .../snapshots__empty-Compute.glsl.snap | 6 +- .../snapshots__quad-Fragment.glsl.snap | 11 ++- .../snapshots__quad-Vertex.glsl.snap | 13 ++-- .../snapshots__skybox-Fragment.glsl.snap | 16 ++--- .../snapshots__skybox-Vertex.glsl.snap | 35 +++++----- 6 files changed, 73 insertions(+), 77 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ddb1c6c6c..a5fb8f27b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -38,7 +38,7 @@ // // The only thing that glsl removes that makes a difference are pointers. // -// Addititions that are relevant for the backend are the discard keyword, the introduction of +// Additions that are relevant for the backend are the discard keyword, the introduction of // vector, matrices, samplers, image types and functions that provide common shader operations pub use features::Features; @@ -71,6 +71,7 @@ mod keywords; pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; /// List of supported es glsl versions pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; +const INDENT: &str = " "; /// glsl version #[derive(Debug, Copy, Clone, PartialEq)] @@ -341,7 +342,7 @@ impl<'a, W: Write> Writer<'a, W> { /// # Panics /// Might panic if the module is invalid pub fn write(&mut self) -> Result, Error> { - // We use `writeln!(self.out)` troughout the write to add newlines + // We use `writeln!(self.out)` throughout the write to add newlines // to make the output more readable let es = self.options.version.is_es(); @@ -355,12 +356,13 @@ impl<'a, W: Write> Writer<'a, W> { // extensions to appear before being used, even though extensions are part of the // preprocessor not the processor ¯\_(ツ)_/¯ self.features.write(self.options.version, &mut self.out)?; - writeln!(self.out)?; // glsl es requires a precision to be specified for floats // TODO: Should this be user configurable? if es { - writeln!(self.out, "precision highp float;\n")?; + writeln!(self.out)?; + writeln!(self.out, "precision highp float;")?; + writeln!(self.out)?; } // Enable early depth tests if needed @@ -378,10 +380,9 @@ impl<'a, W: Write> Writer<'a, W> { } )?; } + writeln!(self.out)?; } - writeln!(self.out)?; - // Write all structs // // This are always ordered because of the IR is structured in a way that you can't make a @@ -396,8 +397,6 @@ impl<'a, W: Write> Writer<'a, W> { } } - writeln!(self.out)?; - // Write the globals // // We filter all globals that aren't used by the selected entry point as they might be @@ -460,7 +459,9 @@ impl<'a, W: Write> Writer<'a, W> { self.out, " {};", self.names[&NameKey::GlobalVariable(handle)] - )? + )?; + + writeln!(self.out)?; } // glsl has no concept of samplers so we just ignore it TypeInner::Sampler { .. } => continue, @@ -469,8 +470,6 @@ impl<'a, W: Write> Writer<'a, W> { } } - writeln!(self.out)?; - // Sort the graph topologically so that functions calls are valid // It's impossible for this to panic because the IR forbids cycles let functions = petgraph::algo::toposort(&self.call_graph, None).unwrap(); @@ -589,8 +588,8 @@ impl<'a, W: Write> Writer<'a, W> { // Write the block members for (idx, member) in members.iter().enumerate() { - // Add a tab for identation (readability only) - writeln!(self.out, "\t")?; + // Add a tab for indentation (readability only) + write!(self.out, "{}", INDENT)?; // Write the member type self.write_type(member.ty)?; @@ -714,6 +713,7 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important writeln!(self.out, " {};", self.get_global_name(handle, global))?; + writeln!(self.out)?; Ok(()) } @@ -730,7 +730,7 @@ impl<'a, W: Write> Writer<'a, W> { match global.binding { Some(Binding::Location(location)) => { format!( - " _location_{}{}", + "_location_{}{}", location, match (self.options.entry_point.0, global.class) { (ShaderStage::Fragment, StorageClass::Input) => "_vs", @@ -740,7 +740,7 @@ impl<'a, W: Write> Writer<'a, W> { ) } Some(Binding::Resource { group, binding }) => { - format!(" _group_{}_binding_{}", group, binding) + format!("_group_{}_binding_{}", group, binding) } Some(Binding::BuiltIn(built_in)) => glsl_built_in(built_in).to_string(), None => self.names[&NameKey::GlobalVariable(handle)].clone(), @@ -824,9 +824,9 @@ impl<'a, W: Write> Writer<'a, W> { // // Always adds a newline for (handle, local) in func.local_variables.iter() { - // Write identation (only for readability) and the type + // Write indentation (only for readability) and the type // `write_type` adds no trailing space - write!(self.out, "\t")?; + write!(self.out, "{}", INDENT)?; self.write_type(local.ty)?; // Write the local name @@ -848,8 +848,6 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ";")? } - writeln!(self.out)?; - // Write the function body (statement list) for sta in func.body.iter() { // Write a statement, the indentation should always be 1 when writing the function body @@ -949,8 +947,8 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, "struct {} {{", self.names[&NameKey::Type(handle)])?; for (idx, member) in members.iter().enumerate() { - // The identation is only for readability - write!(self.out, "\t")?; + // The indentation is only for readability + write!(self.out, "{}", INDENT)?; // Write the member type // Adds no trailing space @@ -967,6 +965,8 @@ impl<'a, W: Write> Writer<'a, W> { } writeln!(self.out, "}};")?; + writeln!(self.out)?; + Ok(()) } @@ -981,7 +981,7 @@ impl<'a, W: Write> Writer<'a, W> { indent: usize, ) -> BackendResult { // The indentation is only for readability - write!(self.out, "{}", "\t".repeat(indent))?; + write!(self.out, "{}", INDENT.repeat(indent))?; match sta { // Blocks are simple we just need to write the block statements between braces @@ -993,7 +993,7 @@ impl<'a, W: Write> Writer<'a, W> { // Increase the indentation to help with readability self.write_stmt(sta, ctx, indent + 1)? } - writeln!(self.out, "{}}}", "\t".repeat(indent))? + writeln!(self.out, "{}}}", INDENT.repeat(indent))? } // Ifs are written as in C: // ``` @@ -1020,15 +1020,15 @@ impl<'a, W: Write> Writer<'a, W> { // If there are no statements in the reject block we skip writing it // This is only for readability if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", "\t".repeat(indent))?; + writeln!(self.out, "{}}} else {{", INDENT.repeat(indent))?; for sta in reject { - // Increase identation to help with readability + // Increase indentation to help with readability self.write_stmt(sta, ctx, indent + 1)?; } } - writeln!(self.out, "{}}}", "\t".repeat(indent))? + writeln!(self.out, "{}}}", INDENT.repeat(indent))? } // Switch are written as in C: // ``` @@ -1058,7 +1058,12 @@ impl<'a, W: Write> Writer<'a, W> { // Write all cases for case in cases { - writeln!(self.out, "{}case {}:", "\t".repeat(indent + 1), case.value)?; + writeln!( + self.out, + "{}case {}:", + INDENT.repeat(indent + 1), + case.value + )?; for sta in case.body.iter() { self.write_stmt(sta, ctx, indent + 2)?; @@ -1066,21 +1071,21 @@ impl<'a, W: Write> Writer<'a, W> { // Write `break;` if the block isn't fallthrough if case.fall_through { - writeln!(self.out, "{}break;", "\t".repeat(indent + 2))?; + writeln!(self.out, "{}break;", INDENT.repeat(indent + 2))?; } } // Only write the default block if the block isn't empty // Writing default without a block is valid but it's more readable this way if !default.is_empty() { - writeln!(self.out, "{}default:", "\t".repeat(indent + 1))?; + writeln!(self.out, "{}default:", INDENT.repeat(indent + 1))?; for sta in default { self.write_stmt(sta, ctx, indent + 2)?; } } - writeln!(self.out, "{}}}", "\t".repeat(indent))? + writeln!(self.out, "{}}}", INDENT.repeat(indent))? } // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a // while true loop and appending the continuing block to the body resulting on: @@ -1097,7 +1102,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_stmt(sta, ctx, indent + 1)?; } - writeln!(self.out, "{}}}", "\t".repeat(indent))? + writeln!(self.out, "{}}}", INDENT.repeat(indent))? } // Break, continue and return as written as in C // `break;` @@ -1342,7 +1347,7 @@ impl<'a, W: Write> Writer<'a, W> { // "~" - for `Not` if it's an integer // "!" - for `Not` if it's a boolean // - // We also wrap the everything in parantheses to avoid precedence issues + // We also wrap the everything in parentheses to avoid precedence issues Expression::Unary { op, expr } => { write!( self.out, diff --git a/tests/snapshots/snapshots__empty-Compute.glsl.snap b/tests/snapshots/snapshots__empty-Compute.glsl.snap index 9fb9bfbaa..2a8a2b72e 100644 --- a/tests/snapshots/snapshots__empty-Compute.glsl.snap +++ b/tests/snapshots/snapshots__empty-Compute.glsl.snap @@ -6,11 +6,7 @@ expression: string precision highp float; - - - void main() { - - return; + return; } diff --git a/tests/snapshots/snapshots__quad-Fragment.glsl.snap b/tests/snapshots/snapshots__quad-Fragment.glsl.snap index 75d517f2f..d61405935 100644 --- a/tests/snapshots/snapshots__quad-Fragment.glsl.snap +++ b/tests/snapshots/snapshots__quad-Fragment.glsl.snap @@ -6,15 +6,14 @@ expression: string precision highp float; +in vec2 _location_0_vs; - -in vec2 _location_0_vs; uniform sampler2D u_texture; -out vec4 _location_0; + +out vec4 _location_0; void main() { - - _location_0 = texture( _group_0_binding_0, vec2( _location_0_vs)); - return; + _location_0 = texture(_group_0_binding_0, vec2(_location_0_vs)); + return; } diff --git a/tests/snapshots/snapshots__quad-Vertex.glsl.snap b/tests/snapshots/snapshots__quad-Vertex.glsl.snap index d79cd676a..63e133f4b 100644 --- a/tests/snapshots/snapshots__quad-Vertex.glsl.snap +++ b/tests/snapshots/snapshots__quad-Vertex.glsl.snap @@ -6,16 +6,15 @@ expression: string precision highp float; +in vec2 _location_0; +in vec2 _location_1; -in vec2 _location_0; -in vec2 _location_1; -out vec2 _location_0_vs; +out vec2 _location_0_vs; void main() { - - _location_0_vs = _location_1; - gl_Position = vec4((1.2 * _location_0), 0.0, 1.0); - return; + _location_0_vs = _location_1; + gl_Position = vec4((1.2 * _location_0), 0.0, 1.0); + return; } diff --git a/tests/snapshots/snapshots__skybox-Fragment.glsl.snap b/tests/snapshots/snapshots__skybox-Fragment.glsl.snap index 24583ee9f..175ebf3ce 100644 --- a/tests/snapshots/snapshots__skybox-Fragment.glsl.snap +++ b/tests/snapshots/snapshots__skybox-Fragment.glsl.snap @@ -6,19 +6,19 @@ expression: string precision highp float; - struct Data { - mat4x4 proj_inv; - mat4x4 view; + mat4x4 proj_inv; + mat4x4 view; }; uniform samplerCube r_texture; -in vec3 _location_0_vs; -out vec4 _location_0; + +in vec3 _location_0_vs; + +out vec4 _location_0; void main() { - - _location_0 = texture( _group_0_binding_1, vec3( _location_0_vs)); - return; + _location_0 = texture(_group_0_binding_1, vec3(_location_0_vs)); + return; } diff --git a/tests/snapshots/snapshots__skybox-Vertex.glsl.snap b/tests/snapshots/snapshots__skybox-Vertex.glsl.snap index 651626a5f..c5bd31b67 100644 --- a/tests/snapshots/snapshots__skybox-Vertex.glsl.snap +++ b/tests/snapshots/snapshots__skybox-Vertex.glsl.snap @@ -6,30 +6,27 @@ expression: string precision highp float; - struct Data { - mat4x4 proj_inv; - mat4x4 view; + mat4x4 proj_inv; + mat4x4 view; }; -out vec3 _location_0_vs; +out vec3 _location_0_vs; + uniform Data_block_0 { - -mat4x4 proj_inv; - -mat4x4 view; -} _group_0_binding_0; + mat4x4 proj_inv; + mat4x4 view; +} _group_0_binding_0; void main() { - int tmp1_; - int tmp2_; - vec4 unprojected; - - tmp1_ = (int(gl_VertexID) / 2); - tmp2_ = (int(gl_VertexID) & 1); - unprojected = ( _group_0_binding_0.proj_inv * vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0)); - _location_0_vs = (transpose(mat3x3(vec3( _group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3( _group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3( _group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(unprojected[0], unprojected[1], unprojected[2])); - gl_Position = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - return; + int tmp1_; + int tmp2_; + vec4 unprojected; + tmp1_ = (int(gl_VertexID) / 2); + tmp2_ = (int(gl_VertexID) & 1); + unprojected = (_group_0_binding_0.proj_inv * vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0)); + _location_0_vs = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(unprojected[0], unprojected[1], unprojected[2])); + gl_Position = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + return; } From ce15aa62fc1cb92365934ef7863321d73b8dfaea Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 26 Jan 2021 14:01:47 -0500 Subject: [PATCH 0379/2212] [spv] indexing values --- src/back/spv/instructions.rs | 34 ++++ src/back/spv/writer.rs | 189 ++++++++++-------- tests/snapshots/snapshots__skybox.spvasm.snap | 186 ++++++++--------- 3 files changed, 236 insertions(+), 173 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 682ce8c8c..b852dac79 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -570,6 +570,40 @@ pub(super) fn instruction_composite_construct( instruction } +pub(super) fn instruction_composite_extract( + result_type_id: Word, + id: Word, + composite_id: Word, + indices: &[Word], +) -> Instruction { + let mut instruction = Instruction::new(Op::CompositeExtract); + instruction.set_type(result_type_id); + instruction.set_result(id); + + instruction.add_operand(composite_id); + for index in indices { + instruction.add_operand(*index); + } + + instruction +} + +pub(super) fn instruction_vector_extract_dynamic( + result_type_id: Word, + id: Word, + vector_id: Word, + index_id: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::VectorExtractDynamic); + instruction.set_type(result_type_id); + instruction.set_result(id); + + instruction.add_operand(vector_id); + instruction.add_operand(index_id); + + instruction +} + // // Arithmetic Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 2b1d2c25d..91ad75edb 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1060,11 +1060,10 @@ impl Writer { let (raw_expression, lookup_ty) = self.write_expression_raw(ir_module, ir_function, handle, block, function)?; Ok(match raw_expression { - RawExpression::Value(_id) => { - //TODO: create a local variable? - log::error!("Pointer expression {:?}", ir_function.expressions[handle]); - return Err(Error::FeatureNotImplemented("getting pointer of a value")); - } + RawExpression::Value(_id) => unimplemented!( + "Expression {:?} is not a pointer", + ir_function.expressions[handle] + ), RawExpression::Pointer(id, class) => (id, lookup_ty, class), }) } @@ -1081,78 +1080,89 @@ impl Writer { match ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { let id = self.generate_id(); - - let (base_id, base_lookup_ty, class) = - self.write_expression_pointer(ir_module, ir_function, base, block, function)?; + let (raw_base_expression, base_lookup_ty) = + self.write_expression_raw(ir_module, ir_function, base, block, function)?; + let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); let (index_id, _) = self.write_expression(ir_module, ir_function, index, block, function)?; - let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); - let (pointer_type_id, lookup_ty) = match *base_ty_inner { - crate::TypeInner::Array { base, .. } => { - self.create_pointer_type(LookupType::Handle(base), class, &ir_module.types)? - } - crate::TypeInner::Vector { kind, width, .. } => self.create_pointer_type( - LocalType::Scalar { kind, width }.into(), - class, - &ir_module.types, - )?, - ref other => { - log::error!("Unable to index {:?}", other); - return Err(Error::FeatureNotImplemented("accessing of non-vector")); - } - }; - - block - .body - .push(super::instructions::instruction_access_chain( - pointer_type_id, - id, - base_id, - &[index_id], - )); - - Ok((RawExpression::Pointer(id, class), lookup_ty)) - } - crate::Expression::AccessIndex { base, index } => { - let id = self.generate_id(); - let (base_id, base_lookup_ty, class) = - self.write_expression_pointer(ir_module, ir_function, base, block, function)?; - - let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); - let (pointer_type_id, lookup_ty) = match *base_ty_inner { + let lookup_ty = match *base_ty_inner { crate::TypeInner::Vector { size: _, kind, width, - } => self.create_pointer_type( - LocalType::Scalar { kind, width }.into(), - class, - &ir_module.types, - )?, + } => LookupType::Local(LocalType::Scalar { kind, width }), + crate::TypeInner::Array { base, .. } => LookupType::Handle(base), + ref other => { + log::error!("Unable to index {:?}", other); + return Err(Error::FeatureNotImplemented( + "accessing index of non vector or array", + )); + } + }; + + Ok(match raw_base_expression { + RawExpression::Value(base_id) => { + if let crate::TypeInner::Array { .. } = *base_ty_inner { + return Err(Error::FeatureNotImplemented( + "accessing index of a value array", + )); + } + + let result_type_id = self.get_type_id(&ir_module.types, lookup_ty)?; + block + .body + .push(super::instructions::instruction_vector_extract_dynamic( + result_type_id, + id, + base_id, + index_id, + )); + + (RawExpression::Value(id), lookup_ty) + } + RawExpression::Pointer(base_id, class) => { + let (pointer_type_id, pointer_lookup_ty) = + self.create_pointer_type(lookup_ty, class, &ir_module.types)?; + + block + .body + .push(super::instructions::instruction_access_chain( + pointer_type_id, + id, + base_id, + &[index_id], + )); + + (RawExpression::Pointer(id, class), pointer_lookup_ty) + } + }) + } + crate::Expression::AccessIndex { base, index } => { + let id = self.generate_id(); + let (raw_base_expression, base_lookup_ty) = + self.write_expression_raw(ir_module, ir_function, base, block, function)?; + let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); + + let lookup_ty = match *base_ty_inner { + crate::TypeInner::Vector { + size: _, + kind, + width, + } => LookupType::Local(LocalType::Scalar { kind, width }), crate::TypeInner::Matrix { columns: _, rows, width, - } => { - let local_type = LocalType::Vector { - size: rows, - kind: crate::ScalarKind::Float, - width, - }; - self.create_pointer_type(local_type.into(), class, &ir_module.types)? - } + } => LookupType::Local(LocalType::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }), crate::TypeInner::Struct { block: _, ref members, - } => { - let member = &members[index as usize]; - self.create_pointer_type( - LookupType::Handle(member.ty), - class, - &ir_module.types, - )? - } + } => LookupType::Handle(members[index as usize].ty), ref other => { log::error!("Unable to access index {:?}", other); return Err(Error::FeatureNotImplemented( @@ -1161,25 +1171,44 @@ impl Writer { } }; - let const_ty_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Scalar { - kind: crate::ScalarKind::Sint, - width: 4, - }), - )?; - let const_id = self.create_constant(const_ty_id, &[index]); + Ok(match raw_base_expression { + RawExpression::Value(base_id) => { + let result_type_id = self.get_type_id(&ir_module.types, lookup_ty)?; + block + .body + .push(super::instructions::instruction_composite_extract( + result_type_id, + id, + base_id, + &[index], + )); - block - .body - .push(super::instructions::instruction_access_chain( - pointer_type_id, - id, - base_id, - &[const_id], - )); + (RawExpression::Value(id), lookup_ty) + } + RawExpression::Pointer(base_id, class) => { + let const_ty_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Scalar { + kind: crate::ScalarKind::Sint, + width: 4, + }), + )?; + let const_id = self.create_constant(const_ty_id, &[index]); + let (pointer_type_id, pointer_lookup_ty) = + self.create_pointer_type(lookup_ty, class, &ir_module.types)?; - Ok((RawExpression::Pointer(id, class), lookup_ty)) + block + .body + .push(super::instructions::instruction_access_chain( + pointer_type_id, + id, + base_id, + &[const_id], + )); + + (RawExpression::Pointer(id, class), pointer_lookup_ty) + } + }) } crate::Expression::GlobalVariable(handle) => { let var = &ir_module.global_variables[handle]; diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap index 3e5289334..a6a27f59f 100644 --- a/tests/snapshots/snapshots__skybox.spvasm.snap +++ b/tests/snapshots/snapshots__skybox.spvasm.snap @@ -46,8 +46,8 @@ OpDecorate %180 Location 0 %26 = OpTypeStruct %27 %27 %28 = OpTypePointer Uniform %26 %25 = OpVariable %28 Uniform -%29 = OpTypePointer Uniform %27 -%30 = OpConstant %3 0 +%29 = OpConstant %3 0 +%30 = OpTypePointer Uniform %27 %36 = OpConstant %8 4.0 %37 = OpConstant %8 1.0 %42 = OpConstant %8 0.0 @@ -55,66 +55,66 @@ OpDecorate %180 Location 0 %46 = OpTypePointer Output %45 %44 = OpVariable %46 Output %48 = OpTypeMatrix %45 3 -%52 = OpTypePointer Uniform %27 -%53 = OpConstant %3 1 -%54 = OpTypePointer Uniform %7 -%55 = OpConstant %3 0 -%56 = OpTypePointer Uniform %8 -%57 = OpConstant %3 0 -%62 = OpTypePointer Uniform %27 -%63 = OpConstant %3 1 -%64 = OpTypePointer Uniform %7 -%65 = OpConstant %3 0 -%66 = OpTypePointer Uniform %8 -%67 = OpConstant %3 1 -%72 = OpTypePointer Uniform %27 -%73 = OpConstant %3 1 -%74 = OpTypePointer Uniform %7 -%75 = OpConstant %3 0 -%76 = OpTypePointer Uniform %8 -%77 = OpConstant %3 2 -%83 = OpTypePointer Uniform %27 -%84 = OpConstant %3 1 -%85 = OpTypePointer Uniform %7 -%86 = OpConstant %3 1 -%87 = OpTypePointer Uniform %8 -%88 = OpConstant %3 0 -%93 = OpTypePointer Uniform %27 -%94 = OpConstant %3 1 -%95 = OpTypePointer Uniform %7 -%96 = OpConstant %3 1 -%97 = OpTypePointer Uniform %8 -%98 = OpConstant %3 1 -%103 = OpTypePointer Uniform %27 -%104 = OpConstant %3 1 -%105 = OpTypePointer Uniform %7 -%106 = OpConstant %3 1 -%107 = OpTypePointer Uniform %8 -%108 = OpConstant %3 2 -%114 = OpTypePointer Uniform %27 -%115 = OpConstant %3 1 -%116 = OpTypePointer Uniform %7 -%117 = OpConstant %3 2 -%118 = OpTypePointer Uniform %8 -%119 = OpConstant %3 0 -%124 = OpTypePointer Uniform %27 -%125 = OpConstant %3 1 -%126 = OpTypePointer Uniform %7 -%127 = OpConstant %3 2 -%128 = OpTypePointer Uniform %8 -%129 = OpConstant %3 1 -%134 = OpTypePointer Uniform %27 -%135 = OpConstant %3 1 -%136 = OpTypePointer Uniform %7 -%137 = OpConstant %3 2 -%138 = OpTypePointer Uniform %8 -%139 = OpConstant %3 2 -%145 = OpTypePointer Function %8 -%146 = OpConstant %3 0 -%149 = OpTypePointer Function %8 -%150 = OpConstant %3 1 -%153 = OpTypePointer Function %8 -%154 = OpConstant %3 2 +%52 = OpConstant %3 1 +%53 = OpTypePointer Uniform %27 +%54 = OpConstant %3 0 +%55 = OpTypePointer Uniform %7 +%56 = OpConstant %3 0 +%57 = OpTypePointer Uniform %8 +%62 = OpConstant %3 1 +%63 = OpTypePointer Uniform %27 +%64 = OpConstant %3 0 +%65 = OpTypePointer Uniform %7 +%66 = OpConstant %3 1 +%67 = OpTypePointer Uniform %8 +%72 = OpConstant %3 1 +%73 = OpTypePointer Uniform %27 +%74 = OpConstant %3 0 +%75 = OpTypePointer Uniform %7 +%76 = OpConstant %3 2 +%77 = OpTypePointer Uniform %8 +%83 = OpConstant %3 1 +%84 = OpTypePointer Uniform %27 +%85 = OpConstant %3 1 +%86 = OpTypePointer Uniform %7 +%87 = OpConstant %3 0 +%88 = OpTypePointer Uniform %8 +%93 = OpConstant %3 1 +%94 = OpTypePointer Uniform %27 +%95 = OpConstant %3 1 +%96 = OpTypePointer Uniform %7 +%97 = OpConstant %3 1 +%98 = OpTypePointer Uniform %8 +%103 = OpConstant %3 1 +%104 = OpTypePointer Uniform %27 +%105 = OpConstant %3 1 +%106 = OpTypePointer Uniform %7 +%107 = OpConstant %3 2 +%108 = OpTypePointer Uniform %8 +%114 = OpConstant %3 1 +%115 = OpTypePointer Uniform %27 +%116 = OpConstant %3 2 +%117 = OpTypePointer Uniform %7 +%118 = OpConstant %3 0 +%119 = OpTypePointer Uniform %8 +%124 = OpConstant %3 1 +%125 = OpTypePointer Uniform %27 +%126 = OpConstant %3 2 +%127 = OpTypePointer Uniform %7 +%128 = OpConstant %3 1 +%129 = OpTypePointer Uniform %8 +%134 = OpConstant %3 1 +%135 = OpTypePointer Uniform %27 +%136 = OpConstant %3 2 +%137 = OpTypePointer Uniform %7 +%138 = OpConstant %3 2 +%139 = OpTypePointer Uniform %8 +%145 = OpConstant %3 0 +%146 = OpTypePointer Function %8 +%149 = OpConstant %3 1 +%150 = OpTypePointer Function %8 +%153 = OpConstant %3 2 +%154 = OpTypePointer Function %8 %158 = OpTypePointer Output %7 %157 = OpVariable %158 Output %170 = OpVariable %158 Output @@ -138,7 +138,7 @@ OpStore %2 %14 %21 = OpLoad %16 %15 %20 = OpBitwiseAnd %3 %21 %22 OpStore %5 %20 -%24 = OpAccessChain %29 %25 %30 +%24 = OpAccessChain %30 %25 %29 %31 = OpLoad %27 %24 %34 = OpLoad %3 %2 %35 = OpConvertSToF %8 %34 @@ -151,52 +151,52 @@ OpStore %5 %20 %43 = OpCompositeConstruct %7 %32 %38 %42 %37 %23 = OpMatrixTimesVector %7 %31 %43 OpStore %6 %23 -%51 = OpAccessChain %52 %25 %53 -%50 = OpAccessChain %54 %51 %55 -%49 = OpAccessChain %56 %50 %57 +%51 = OpAccessChain %53 %25 %52 +%50 = OpAccessChain %55 %51 %54 +%49 = OpAccessChain %57 %50 %56 %58 = OpLoad %8 %49 -%61 = OpAccessChain %62 %25 %63 -%60 = OpAccessChain %64 %61 %65 -%59 = OpAccessChain %66 %60 %67 +%61 = OpAccessChain %63 %25 %62 +%60 = OpAccessChain %65 %61 %64 +%59 = OpAccessChain %67 %60 %66 %68 = OpLoad %8 %59 -%71 = OpAccessChain %72 %25 %73 -%70 = OpAccessChain %74 %71 %75 -%69 = OpAccessChain %76 %70 %77 +%71 = OpAccessChain %73 %25 %72 +%70 = OpAccessChain %75 %71 %74 +%69 = OpAccessChain %77 %70 %76 %78 = OpLoad %8 %69 %79 = OpCompositeConstruct %45 %58 %68 %78 -%82 = OpAccessChain %83 %25 %84 -%81 = OpAccessChain %85 %82 %86 -%80 = OpAccessChain %87 %81 %88 +%82 = OpAccessChain %84 %25 %83 +%81 = OpAccessChain %86 %82 %85 +%80 = OpAccessChain %88 %81 %87 %89 = OpLoad %8 %80 -%92 = OpAccessChain %93 %25 %94 -%91 = OpAccessChain %95 %92 %96 -%90 = OpAccessChain %97 %91 %98 +%92 = OpAccessChain %94 %25 %93 +%91 = OpAccessChain %96 %92 %95 +%90 = OpAccessChain %98 %91 %97 %99 = OpLoad %8 %90 -%102 = OpAccessChain %103 %25 %104 -%101 = OpAccessChain %105 %102 %106 -%100 = OpAccessChain %107 %101 %108 +%102 = OpAccessChain %104 %25 %103 +%101 = OpAccessChain %106 %102 %105 +%100 = OpAccessChain %108 %101 %107 %109 = OpLoad %8 %100 %110 = OpCompositeConstruct %45 %89 %99 %109 -%113 = OpAccessChain %114 %25 %115 -%112 = OpAccessChain %116 %113 %117 -%111 = OpAccessChain %118 %112 %119 +%113 = OpAccessChain %115 %25 %114 +%112 = OpAccessChain %117 %113 %116 +%111 = OpAccessChain %119 %112 %118 %120 = OpLoad %8 %111 -%123 = OpAccessChain %124 %25 %125 -%122 = OpAccessChain %126 %123 %127 -%121 = OpAccessChain %128 %122 %129 +%123 = OpAccessChain %125 %25 %124 +%122 = OpAccessChain %127 %123 %126 +%121 = OpAccessChain %129 %122 %128 %130 = OpLoad %8 %121 -%133 = OpAccessChain %134 %25 %135 -%132 = OpAccessChain %136 %133 %137 -%131 = OpAccessChain %138 %132 %139 +%133 = OpAccessChain %135 %25 %134 +%132 = OpAccessChain %137 %133 %136 +%131 = OpAccessChain %139 %132 %138 %140 = OpLoad %8 %131 %141 = OpCompositeConstruct %45 %120 %130 %140 %142 = OpCompositeConstruct %48 %79 %110 %141 %143 = OpTranspose %48 %142 -%144 = OpAccessChain %145 %6 %146 +%144 = OpAccessChain %146 %6 %145 %147 = OpLoad %8 %144 -%148 = OpAccessChain %149 %6 %150 +%148 = OpAccessChain %150 %6 %149 %151 = OpLoad %8 %148 -%152 = OpAccessChain %153 %6 %154 +%152 = OpAccessChain %154 %6 %153 %155 = OpLoad %8 %152 %156 = OpCompositeConstruct %45 %147 %151 %155 %47 = OpMatrixTimesVector %45 %143 %156 From 986550aff8767fe541fb9e2fc3a7e01e16f1dc21 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 26 Jan 2021 15:45:05 -0500 Subject: [PATCH 0380/2212] [wgsl] fix and update storage load --- src/front/wgsl/mod.rs | 16 ++++++++++++---- src/front/wgsl/tests.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5d2ebee49..b4925d2e2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -665,12 +665,12 @@ impl Parser { None }; let index = match class { - crate::ImageClass::Storage(_) => { + crate::ImageClass::Storage(_) => None, + // it's the MSAA index for multi-sampled, and LOD for the others + crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth => { lexer.expect(Token::Separator(','))?; - let index_name = lexer.next_ident()?; - Some(ctx.lookup_ident.lookup(index_name)?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } - crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth => None, }; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::ImageLoad { @@ -1411,6 +1411,14 @@ impl Parser { class: crate::ImageClass::Sampled { kind, multi: true }, } } + "texture_multisampled_2d_array" => { + let (kind, _) = lexer.next_scalar_generic()?; + crate::TypeInner::Image { + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Sampled { kind, multi: true }, + } + } "texture_depth_2d" => crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: false, diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 439a14f8b..ea13aad02 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -116,3 +116,34 @@ fn parse_switch() { ) .unwrap(); } + +#[test] +fn parse_texture_load() { + parse_str( + " + var t: texture_3d; + fn foo() { + const r: vec4 = textureLoad(t, vec3(0.0, 1.0, 2.0), 1); + } + ", + ) + .unwrap(); + parse_str( + " + var t: texture_multisampled_2d_array; + fn foo() { + const r: vec4 = textureLoad(t, vec2(10, 20), 2, 3); + } + ", + ) + .unwrap(); + parse_str( + " + var t: [[access(read)]] texture_storage_1d_array; + fn foo() { + const r: vec4 = textureLoad(t, 10, 2); + } + ", + ) + .unwrap(); +} From 292304b66f27c7f07b855c929bdf671c14dd904d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 26 Jan 2021 16:40:25 -0500 Subject: [PATCH 0381/2212] [wgsl] fix postfix expression parsing --- src/front/wgsl/mod.rs | 7 ++++--- src/front/wgsl/tests.rs | 5 +++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b4925d2e2..6a11e9174 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -947,12 +947,13 @@ impl Parser { Some(expr) => ctx.expressions.append(expr), None => { *lexer = backup; - let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; - self.parse_postfix(lexer, ctx, handle)? + self.parse_primary_expression(lexer, ctx.reborrow())? } }; + + let post_handle = self.parse_postfix(lexer, ctx, handle)?; self.scopes.pop(); - Ok(handle) + Ok(post_handle) } fn parse_equality_expression<'a>( diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index ea13aad02..359f722e9 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -147,3 +147,8 @@ fn parse_texture_load() { ) .unwrap(); } + +#[test] +fn parse_postfix() { + parse_str("fn foo() { const x: f32 = fract(vec2(0.5, 1.0)).x; }").unwrap(); +} From 9c74468f8140ad014f13669912e5058147b43ad8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 26 Jan 2021 16:54:25 -0500 Subject: [PATCH 0382/2212] [wgsl] enable access via rgba --- src/front/wgsl/mod.rs | 33 ++++++++++++++++++++------------- src/front/wgsl/tests.rs | 2 ++ 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6a11e9174..6f647e6f7 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -265,24 +265,31 @@ enum Composition { } impl Composition { + //TODO: could be `const fn` once MSRV allows + fn letter_pos(letter: char) -> u32 { + match letter { + 'x' | 'r' => 0, + 'y' | 'g' => 1, + 'z' | 'b' => 2, + 'w' | 'a' => 3, + _ => !0, + } + } + fn make<'a>( base: Handle, base_size: crate::VectorSize, name: &'a str, expressions: &mut Arena, ) -> Result> { - const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; - Ok(if name.len() > 1 { let mut components = Vec::with_capacity(name.len()); for ch in name.chars() { - let expr = crate::Expression::AccessIndex { - base, - index: MEMBERS[..base_size as usize] - .iter() - .position(|&m| m == ch) - .ok_or(Error::BadAccessor(name))? as u32, - }; + let index = Self::letter_pos(ch); + if index >= base_size as u32 { + return Err(Error::BadAccessor(name)); + } + let expr = crate::Expression::AccessIndex { base, index }; components.push(expressions.append(expr)); } @@ -295,10 +302,10 @@ impl Composition { Composition::Multi(size, components) } else { let ch = name.chars().next().ok_or(Error::BadAccessor(name))?; - let index = MEMBERS[..base_size as usize] - .iter() - .position(|&m| m == ch) - .ok_or(Error::BadAccessor(name))? as u32; + let index = Self::letter_pos(ch); + if index >= base_size as u32 { + return Err(Error::BadAccessor(name)); + } Composition::Single(crate::Expression::AccessIndex { base, index }) }) } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 359f722e9..6ef5e0460 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -150,5 +150,7 @@ fn parse_texture_load() { #[test] fn parse_postfix() { + parse_str("fn foo() { const x: f32 = vec4(1.0, 2.0, 3.0, 4.0).xyz.rgbr.aaaa.wz.g; }") + .unwrap(); parse_str("fn foo() { const x: f32 = fract(vec2(0.5, 1.0)).x; }").unwrap(); } From ab2cf8b84244470e31fcee76efaa04c16015e4b7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 26 Jan 2021 23:29:40 -0500 Subject: [PATCH 0383/2212] [wgsl] support vector type casts --- src/front/wgsl/mod.rs | 33 ++++++++++++---------- src/front/wgsl/tests.rs | 9 ++++++ tests/snapshots/snapshots__skybox.msl.snap | 4 +-- 3 files changed, 29 insertions(+), 17 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6f647e6f7..bd2412bf4 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -62,6 +62,8 @@ pub enum Error<'a> { BadTexture(&'a str), #[error("bad texture coordinate")] BadCoordinate, + #[error("invalid type cast to `{0}`")] + BadTypeCast(&'a str), #[error(transparent)] InvalidResolve(ResolveError), #[error("unknown import: `{0}`")] @@ -435,15 +437,6 @@ impl Parser { let expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; Some(crate::Expression::Derivative { axis, expr }) - } else if let Some((kind, _width)) = conv::get_scalar_type(name) { - lexer.expect(Token::Paren('('))?; - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::As { - expr, - kind, - convert: true, - }) } else if let Some(fun) = conv::map_standard_fun(name) { lexer.expect(Token::Paren('('))?; let arg_count = fun.argument_count(); @@ -833,18 +826,28 @@ impl Parser { ctx.types, ctx.constants, )?; + let kind = inner.scalar_kind(); let ty = ctx.types.fetch_or_append(crate::Type { name: None, inner }); lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); - while !lexer.skip(Token::Paren(')')) { - if !components.is_empty() { - lexer.expect(Token::Separator(','))?; + let mut last_component = + self.parse_general_expression(lexer, ctx.reborrow())?; + while lexer.skip(Token::Separator(',')) { + components.push(last_component); + last_component = self.parse_general_expression(lexer, ctx.reborrow())?; + } + lexer.expect(Token::Paren(')'))?; + if components.is_empty() { + crate::Expression::As { + expr: last_component, + kind: kind.ok_or(Error::BadTypeCast(word))?, + convert: true, } - let sub_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - components.push(sub_expr); + } else { + components.push(last_component); + crate::Expression::Compose { ty, components } } - crate::Expression::Compose { ty, components } } } other => return other.unexpected("primary expression"), diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 6ef5e0460..01dfc57c8 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -37,6 +37,15 @@ fn parse_type_cast() { ", ) .unwrap(); + parse_str( + " + fn main() { + const x: vec2 = vec2(1.0, 2.0); + const y: vec2 = vec2(x); + } + ", + ) + .unwrap(); } #[test] diff --git a/tests/snapshots/snapshots__skybox.msl.snap b/tests/snapshots/snapshots__skybox.msl.snap index ce8662f0d..ed0e4a72d 100644 --- a/tests/snapshots/snapshots__skybox.msl.snap +++ b/tests/snapshots/snapshots__skybox.msl.snap @@ -20,9 +20,9 @@ struct Data { typedef int type4; -typedef metal::float3x3 type5; +typedef float type5; -typedef float type6; +typedef metal::float3x3 type6; typedef metal::texturecube type7; From 61fd868a2263024826c739f0c64ffbf98c81a9b0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 26 Jan 2021 23:29:59 -0500 Subject: [PATCH 0384/2212] [spv] implement full image sampling --- src/back/spv/instructions.rs | 22 +++- src/back/spv/writer.rs | 219 +++++++++++++++++++++++++++++++---- 2 files changed, 216 insertions(+), 25 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index b852dac79..fed6b3c54 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -520,17 +520,35 @@ pub(super) fn instruction_sampled_image( instruction } -pub(super) fn instruction_image_sample_implicit_lod( +pub(super) enum SampleLod { + Explicit, + Implicit, +} + +pub(super) fn instruction_image_sample( result_type_id: Word, id: Word, + lod: SampleLod, sampled_image: Word, coordinates: Word, + depth_ref: Option, ) -> Instruction { - let mut instruction = Instruction::new(Op::ImageSampleImplicitLod); + let op = match (lod, depth_ref) { + (SampleLod::Explicit, None) => Op::ImageSampleExplicitLod, + (SampleLod::Implicit, None) => Op::ImageSampleImplicitLod, + (SampleLod::Explicit, Some(_)) => Op::ImageSampleDrefExplicitLod, + (SampleLod::Implicit, Some(_)) => Op::ImageSampleDrefImplicitLod, + }; + + let mut instruction = Instruction::new(op); instruction.set_type(result_type_id); instruction.set_result(id); instruction.add_operand(sampled_image); instruction.add_operand(coordinates); + if let Some(dref) = depth_ref { + instruction.add_operand(dref); + } + instruction } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 91ad75edb..2e91ac454 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -243,8 +243,10 @@ impl Writer { if let Entry::Occupied(e) = self.lookup_constant.entry(handle) { Ok(*e.get()) } else { - let (instruction, id) = self.write_constant_type(handle, ir_module)?; - instruction.to_words(&mut self.logical_layout.declarations); + let id = self.generate_id(); + self.lookup_constant.insert(handle, id); + let inner = &ir_module.constants[handle].inner; + self.write_constant_type(id, inner, ir_module)?; Ok(id) } } @@ -744,18 +746,14 @@ impl Writer { fn write_constant_type( &mut self, - handle: crate::Handle, + id: spirv::Word, + inner: &crate::ConstantInner, ir_module: &crate::Module, - ) -> Result<(Instruction, Word), Error> { - let id = self.generate_id(); - self.lookup_constant.insert(handle, id); - let constant = &ir_module.constants[handle]; - let arena = &ir_module.types; - - let instruction = match constant.inner { + ) -> Result<(), Error> { + let instruction = match *inner { crate::ConstantInner::Scalar { width, ref value } => { let type_id = self.get_type_id( - arena, + &ir_module.types, LookupType::Local(LocalType::Scalar { kind: value.scalar_kind(), width, @@ -825,12 +823,12 @@ impl Writer { if let crate::TypeInner::Array { size: crate::ArraySize::Constant(const_handle), .. - } = arena[ty].inner + } = ir_module.types[ty].inner { self.get_constant_id(const_handle, &ir_module)?; } - let type_id = self.get_type_id(arena, LookupType::Handle(ty))?; + let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty))?; super::instructions::instruction_constant_composite( type_id, id, @@ -839,7 +837,8 @@ impl Writer { } }; - Ok((instruction, id)) + instruction.to_words(&mut self.logical_layout.declarations); + Ok(()) } fn write_global_variable( @@ -1551,11 +1550,12 @@ impl Writer { image, sampler, coordinate, - array_index: _, //TODO - offset: _, //TODO + array_index, + offset, level, - depth_ref: _, + depth_ref, } => { + use super::instructions::SampleLod; // image let (image_id, image_lookup_ty) = self.write_expression(ir_module, ir_function, image, block, function)?; @@ -1578,9 +1578,82 @@ impl Writer { self.write_expression(ir_module, ir_function, sampler, block, function)?; // coordinate - let (coordinate_id, _) = + let (mut coordinate_id, coordinate_lookup_ty) = self.write_expression(ir_module, ir_function, coordinate, block, function)?; + if let Some(array_index) = array_index { + let coordinate_scalar_type_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Scalar { + kind: crate::ScalarKind::Float, + width: 4, + }), + )?; + + let mut constituent_ids = [0u32; 4]; + let size = match *self.get_type_inner(&ir_module.types, coordinate_lookup_ty) { + crate::TypeInner::Scalar { .. } => { + constituent_ids[0] = coordinate_id; + crate::VectorSize::Bi + } + crate::TypeInner::Vector { size, .. } => { + for i in 0..size as u32 { + let id = self.generate_id(); + constituent_ids[i as usize] = id; + block.body.push( + super::instructions::instruction_composite_extract( + coordinate_scalar_type_id, + id, + coordinate_id, + &[i], + ), + ); + } + match size { + crate::VectorSize::Bi => crate::VectorSize::Tri, + crate::VectorSize::Tri => crate::VectorSize::Quad, + crate::VectorSize::Quad => { + unimplemented!("Unable to extend the vec4 coordinate") + } + } + } + ref other => unimplemented!("wrong coordinate type {:?}", other), + }; + + let array_index_f32_id = self.generate_id(); + constituent_ids[size as usize - 1] = array_index_f32_id; + + let (array_index_u32_id, _) = self.write_expression( + ir_module, + ir_function, + array_index, + block, + function, + )?; + let cast_instruction = super::instructions::instruction_unary( + spirv::Op::ConvertUToF, + coordinate_scalar_type_id, + array_index_f32_id, + array_index_u32_id, + ); + block.body.push(cast_instruction); + + let extended_coordinate_type_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Vector { + size, + kind: crate::ScalarKind::Float, + width: 4, + }), + )?; + + coordinate_id = self.write_composite_construct( + extended_coordinate_type_id, + &constituent_ids[..size as usize], + block, + ); + } + // component kind let image_type = &ir_module.types[image_ty]; let image_sample_result_type = match image_type.inner { @@ -1617,18 +1690,118 @@ impl Writer { let image_sample_result_type_id = self.get_type_id(&ir_module.types, image_sample_result_type)?; - let main_instruction = match level { - crate::SampleLevel::Auto => { - super::instructions::instruction_image_sample_implicit_lod( + let depth_id = match depth_ref { + Some(handle) => { + let (expr_id, _) = + self.write_expression(ir_module, ir_function, handle, block, function)?; + Some(expr_id) + } + None => None, + }; + + let mut main_instruction = match level { + crate::SampleLevel::Zero => { + let mut inst = super::instructions::instruction_image_sample( image_sample_result_type_id, id, + SampleLod::Explicit, sampled_image_id, coordinate_id, - ) + depth_id, + ); + + //TODO: cache this! + let zero_id = self.generate_id(); + let zero_inner = crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Float(0.0), + }; + self.write_constant_type(zero_id, &zero_inner, ir_module)?; + inst.add_operand(spirv::ImageOperands::LOD.bits()); + inst.add_operand(zero_id); + + inst + } + crate::SampleLevel::Auto => super::instructions::instruction_image_sample( + image_sample_result_type_id, + id, + SampleLod::Implicit, + sampled_image_id, + coordinate_id, + depth_id, + ), + crate::SampleLevel::Exact(lod_handle) => { + let mut inst = super::instructions::instruction_image_sample( + image_sample_result_type_id, + id, + SampleLod::Explicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let (lod_id, _) = self.write_expression( + ir_module, + ir_function, + lod_handle, + block, + function, + )?; + inst.add_operand(spirv::ImageOperands::LOD.bits()); + inst.add_operand(lod_id); + + inst + } + crate::SampleLevel::Bias(bias_handle) => { + let mut inst = super::instructions::instruction_image_sample( + image_sample_result_type_id, + id, + SampleLod::Implicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let (bias_id, _) = self.write_expression( + ir_module, + ir_function, + bias_handle, + block, + function, + )?; + inst.add_operand(spirv::ImageOperands::BIAS.bits()); + inst.add_operand(bias_id); + + inst + } + crate::SampleLevel::Gradient { x, y } => { + let mut inst = super::instructions::instruction_image_sample( + image_sample_result_type_id, + id, + SampleLod::Explicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let (x_id, _) = + self.write_expression(ir_module, ir_function, x, block, function)?; + let (y_id, _) = + self.write_expression(ir_module, ir_function, y, block, function)?; + inst.add_operand(spirv::ImageOperands::GRAD.bits()); + inst.add_operand(x_id); + inst.add_operand(y_id); + + inst } - _ => return Err(Error::FeatureNotImplemented("sample level")), }; + if let Some(offset_const) = offset { + let offset_id = self.get_constant_id(offset_const, ir_module)?; + main_instruction.add_operand(spirv::ImageOperands::CONST_OFFSET.bits()); + main_instruction.add_operand(offset_id); + } + block.body.push(main_instruction); Ok((RawExpression::Value(id), image_sample_result_type)) } From 3e4cb21b9006ff83530a32fb9e6e9e6e05213bce Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 27 Jan 2021 15:24:11 -0500 Subject: [PATCH 0385/2212] [wgsl] support simple block statements --- src/front/wgsl/mod.rs | 11 +++++++++++ src/front/wgsl/tests.rs | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index bd2412bf4..9bd3c2917 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1557,6 +1557,17 @@ impl Parser { ) -> Result, Error<'a>> { let word = match lexer.next() { Token::Separator(';') => return Ok(None), + Token::Paren('{') => { + self.scopes.push(Scope::Block); + let mut statements = Vec::new(); + while !lexer.skip(Token::Paren('}')) { + let s = self.parse_statement(lexer, context.reborrow())?; + statements.extend(s); + } + self.scopes.pop(); + let block = crate::Statement::Block(statements); + return Ok(Some(block)); + } Token::Word(word) => word, other => return other.unexpected("statement"), }; diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 01dfc57c8..434a46059 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -73,6 +73,20 @@ fn parse_standard_fun() { .unwrap(); } +#[test] +fn parse_statement() { + parse_str( + " + fn main() { + ; + {} + {;} + } + ", + ) + .unwrap(); +} + #[test] fn parse_if() { parse_str( From 4f517f4af3b3b057eb04c3f4ab4e917ae07d44ce Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 27 Jan 2021 10:19:14 -0500 Subject: [PATCH 0386/2212] [wgsl] include the expected string into the error --- src/front/wgsl/lexer.rs | 28 ++++++++++++++++++------ src/front/wgsl/mod.rs | 47 +++++++++++++++++++++++------------------ 2 files changed, 48 insertions(+), 27 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index fb68a4782..3bd204279 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -178,12 +178,28 @@ impl<'a> Lexer<'a> { self.clone().next() } - pub(super) fn expect(&mut self, expected: Token<'_>) -> Result<(), Error<'a>> { + pub(super) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { let token = self.next(); if token == expected { Ok(()) } else { - token.unexpected(expected) + let description = match expected { + Token::Separator(_) => "separator", + Token::DoubleColon => "::", + Token::Paren(_) => "paren", + Token::DoubleParen(_) => "double paren", + Token::Number { .. } => "number", + Token::String(string) => string, + Token::Word(word) => word, + Token::Operation(_) => "operation", + Token::LogicalOperation(_) => "logical op", + Token::ShiftOperation(_) => "shift op", + Token::Arrow => "->", + Token::Unknown(_) => "unknown", + Token::UnterminatedString => "string", + Token::End => "", + }; + Err(Error::Unexpected(token, description)) } } @@ -200,14 +216,14 @@ impl<'a> Lexer<'a> { pub(super) fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { match self.next() { Token::Word(word) => Ok(word), - other => other.unexpected("ident"), + other => Err(Error::Unexpected(other, "ident")), } } fn _next_float_literal(&mut self) -> Result> { match self.next() { Token::Number { value, .. } => value.parse().map_err(|err| Error::BadFloat(value, err)), - other => other.unexpected("float literal"), + other => Err(Error::Unexpected(other, "float literal")), } } @@ -216,7 +232,7 @@ impl<'a> Lexer<'a> { Token::Number { value, .. } => { value.parse().map_err(|err| Error::BadInteger(value, err)) } - other => other.unexpected("uint literal"), + other => Err(Error::Unexpected(other, "uint literal")), } } @@ -225,7 +241,7 @@ impl<'a> Lexer<'a> { Token::Number { value, .. } => { value.parse().map_err(|err| Error::BadInteger(value, err)) } - other => other.unexpected("sint literal"), + other => Err(Error::Unexpected(other, "sint literal")), } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 9bd3c2917..b1914dca4 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -39,17 +39,10 @@ pub enum Token<'a> { End, } -impl<'a> Token<'a> { - fn unexpected(self, expected: E) -> Result> { - log::error!("Unmet expectation for {:?}", expected); - Err(Error::Unexpected(self)) - } -} - #[derive(Clone, Debug, Error)] pub enum Error<'a> { - #[error("unexpected token: {0:?}")] - Unexpected(Token<'a>), + #[error("unexpected token {0:?}, expected {1}")] + Unexpected(Token<'a>, &'a str), #[error("unable to parse `{0}` as integer: {1}")] BadInteger(&'a str, std::num::ParseIntError), #[error("unable to parse `{1}` as float: {1}")] @@ -691,7 +684,12 @@ impl Parser { match lexer.next() { Token::Paren(')') => break, Token::Separator(',') => (), - other => return other.unexpected("argument list separator"), + other => { + return Err(Error::Unexpected( + other, + "argument list separator", + )) + } } } } @@ -850,7 +848,7 @@ impl Parser { } } } - other => return other.unexpected("primary expression"), + other => return Err(Error::Unexpected(other, "primary expression")), }; self.scopes.pop(); Ok(ctx.expressions.append(expression)) @@ -1183,7 +1181,7 @@ impl Parser { lexer.expect(Token::Paren(')'))?; ready = false; } - other => return other.unexpected("decoration separator"), + other => return Err(Error::Unexpected(other, "decoration separator")), } } self.scopes.pop(); @@ -1191,7 +1189,7 @@ impl Parser { let name = match lexer.next() { Token::Word(word) => word, Token::Paren('}') => return Ok(members), - other => return other.unexpected("field name"), + other => return Err(Error::Unexpected(other, "field name")), }; lexer.expect(Token::Separator(':'))?; let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; @@ -1347,7 +1345,7 @@ impl Parser { crate::ArraySize::Constant(const_handle) } Token::Paren('>') => crate::ArraySize::Dynamic, - other => return other.unexpected("generic separator"), + other => return Err(Error::Unexpected(other, "generic separator")), }; crate::TypeInner::Array { @@ -1526,7 +1524,7 @@ impl Parser { lexer.expect(Token::Paren(')'))?; } Token::DoubleParen(']') => break, - other => return other.unexpected("type decoration"), + other => return Err(Error::Unexpected(other, "type decoration")), } } self.scopes.pop(); @@ -1569,7 +1567,7 @@ impl Parser { return Ok(Some(block)); } Token::Word(word) => word, - other => return other.unexpected("statement"), + other => return Err(Error::Unexpected(other, "statement")), }; self.scopes.push(Scope::Statement); @@ -1678,7 +1676,9 @@ impl Parser { }); } Token::Separator(':') => break value, - other => return other.unexpected("case separator"), + other => { + return Err(Error::Unexpected(other, "case separator")) + } } }; @@ -1709,7 +1709,7 @@ impl Parser { default = self.parse_block(lexer, context.reborrow())?; } Token::Paren('}') => break, - other => return other.unexpected("switch item"), + other => return Err(Error::Unexpected(other, "switch item")), } } @@ -1923,7 +1923,12 @@ impl Parser { match lexer.next() { Token::Paren(')') => break, Token::Separator(',') if i != 2 => (), - other => return other.unexpected("workgroup size separator"), + other => { + return Err(Error::Unexpected( + other, + "workgroup size separator", + )) + } } } for size in workgroup_size.iter_mut() { @@ -1939,7 +1944,7 @@ impl Parser { break; } Token::Separator(',') => {} - other => return other.unexpected("decoration separator"), + other => return Err(Error::Unexpected(other, "decoration separator")), } } if let (Some(group), Some(index)) = (bind_group, bind_index) { @@ -2058,7 +2063,7 @@ impl Parser { } } Token::End => return Ok(false), - other => return other.unexpected("global item"), + other => return Err(Error::Unexpected(other, "global item")), } match binding { From dc98305bb8cc3d326dbb08f861ed7678433b36fe Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 27 Jan 2021 10:51:12 -0500 Subject: [PATCH 0387/2212] Print out detailed WGSL errors --- Cargo.toml | 5 ++++- examples/convert.rs | 39 ++++++++++++++++++++++++++++----------- src/front/wgsl/mod.rs | 26 ++++++++++++++++++++++---- 3 files changed, 54 insertions(+), 16 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8db623000..0d0b4859c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,9 +33,12 @@ spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] wgsl-in = [] +#Note: it would be nice to do `cargo run` for conversion. +# Blocked on https://github.com/rust-lang/cargo/issues/4663 + [dev-dependencies] difference = "2.0" -env_logger = "0.6" +env_logger = "0.8" ron = "0.6" serde = { version = "1.0", features = ["derive"] } spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } diff --git a/examples/convert.rs b/examples/convert.rs index b77da388a..82c03a734 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -1,4 +1,4 @@ -use std::{env, fs, path::Path}; +use std::{env, fmt, fs, path::Path}; #[derive(Hash, PartialEq, Eq, serde::Deserialize)] enum Stage { @@ -41,6 +41,21 @@ struct Parameters { mtl_bindings: naga::FastHashMap, } +trait PrettyResult { + type Target; + fn unwrap_pretty(self) -> Self::Target; +} + +impl PrettyResult for Result { + type Target = T; + fn unwrap_pretty(self) -> T { + match self { + Result::Ok(value) => value, + Result::Err(e) => panic!("{}", e), + } + } +} + fn main() { env_logger::init(); @@ -52,7 +67,7 @@ fn main() { let param_path = std::path::PathBuf::from(&args[1]).with_extension("param.ron"); let params = match fs::read_to_string(param_path) { - Ok(string) => ron::de::from_str(&string).unwrap(), + Ok(string) => ron::de::from_str(&string).unwrap_pretty(), Err(_) => { let mut param = Parameters::default(); // very useful to have this by default @@ -82,7 +97,7 @@ fn main() { #[cfg(feature = "wgsl-in")] "wgsl" => { let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::wgsl::parse_str(&input).unwrap() + naga::front::wgsl::parse_str(&input).unwrap_pretty() } #[cfg(feature = "glsl-in")] "vert" => { @@ -93,7 +108,7 @@ fn main() { naga::ShaderStage::Vertex, Default::default(), ) - .unwrap() + .unwrap_pretty() } #[cfg(feature = "glsl-in")] "frag" => { @@ -104,7 +119,7 @@ fn main() { naga::ShaderStage::Fragment, Default::default(), ) - .unwrap() + .unwrap_pretty() } #[cfg(feature = "glsl-in")] "comp" => { @@ -115,12 +130,12 @@ fn main() { naga::ShaderStage::Compute, Default::default(), ) - .unwrap() + .unwrap_pretty() } #[cfg(feature = "deserialize")] "ron" => { let mut input = fs::File::open(&args[1]).unwrap(); - ron::de::from_reader(&mut input).unwrap() + ron::de::from_reader(&mut input).unwrap_pretty() } other => { if true { @@ -132,7 +147,9 @@ fn main() { }; // validate the IR - naga::proc::Validator::new().validate(&module).unwrap(); + naga::proc::Validator::new() + .validate(&module) + .unwrap_pretty(); if args.len() <= 2 { println!("{:#?}", module); @@ -188,7 +205,7 @@ fn main() { } }); - let spv = spv::write_vec(&module, debug_flag, params.spv_capabilities).unwrap(); + let spv = spv::write_vec(&module, debug_flag, params.spv_capabilities).unwrap_pretty(); let bytes = spv .iter() @@ -234,7 +251,7 @@ fn main() { .open(&args[2]) .unwrap(); - let mut writer = glsl::Writer::new(file, &module, &options).unwrap(); + let mut writer = glsl::Writer::new(file, &module, &options).unwrap_pretty(); writer .write() @@ -250,7 +267,7 @@ fn main() { .with_enumerate_arrays(true) .with_decimal_floats(true); - let output = ron::ser::to_string_pretty(&module, config).unwrap(); + let output = ron::ser::to_string_pretty(&module, config).unwrap_pretty(); fs::write(&args[2], output).unwrap(); } other => { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b1914dca4..d9b68c5bc 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -17,6 +17,8 @@ use self::lexer::Lexer; use std::num::NonZeroU32; use thiserror::Error; +const SPACE: &str = " "; + #[derive(Copy, Clone, Debug, PartialEq)] pub enum Token<'a> { Separator(char), @@ -336,11 +338,12 @@ struct ParsedVariable<'a> { } #[derive(Clone, Debug, Error)] -#[error("error while parsing WGSL in scopes {scopes:?} at position {pos:?}: {error}")] +#[error("error while parsing WGSL in scopes {scopes:?} at line {line} pos {pos}: {error}")] pub struct ParseError<'a> { pub error: Error<'a>, pub scopes: Vec, - pub pos: (usize, usize), + pub line: usize, + pub pos: usize, } pub struct Parser { @@ -2085,23 +2088,38 @@ impl Parser { Err(error) => { let pos = lexer.offset_from(source); let (mut rows, mut cols) = (0, 1); + let (mut prev_line, mut cur_line) = ("", ""); for line in source[..pos].lines() { rows += 1; cols = line.len(); + prev_line = cur_line; + cur_line = line; + } + log::error!("|\t{}", prev_line); + log::error!( + ">\t{}{}", + cur_line, + source[pos..].lines().next().unwrap_or_default() + ); + if cols <= SPACE.len() { + log::error!("|\t{}^", &SPACE[..cols]); } return Err(ParseError { error, scopes: std::mem::replace(&mut self.scopes, Vec::new()), - pos: (rows, cols), + line: rows, + pos: cols, }); } Ok(true) => {} Ok(false) => { if !self.scopes.is_empty() { + log::error!("Reached the end of file, but scopes are not closed"); return Err(ParseError { error: Error::Other, scopes: std::mem::replace(&mut self.scopes, Vec::new()), - pos: (0, 0), + line: 0, + pos: 0, }); }; return Ok(module); From 88f118a07dd21ed93e4f8743d1d4f004471c9fae Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Thu, 10 Dec 2020 23:22:35 +0100 Subject: [PATCH 0388/2212] Working prototype --- src/back/spv/instructions.rs | 29 +++++++++ src/back/spv/writer.rs | 118 ++++++++++++++++++++++++++++++----- 2 files changed, 133 insertions(+), 14 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index fed6b3c54..4a6f0a6f4 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -656,12 +656,41 @@ pub(super) fn instruction_binary( // Control-Flow Instructions // +pub(super) fn instruction_selection_merge( + id: Word, + selection_control: spirv::SelectionControl, +) -> Instruction { + let mut instruction = Instruction::new(Op::SelectionMerge); + instruction.add_operand(id); + instruction.add_operand(selection_control.bits()); + instruction +} + pub(super) fn instruction_label(id: Word) -> Instruction { let mut instruction = Instruction::new(Op::Label); instruction.set_result(id); instruction } +pub(super) fn instruction_branch(id: Word) -> Instruction { + let mut instruction = Instruction::new(Op::Branch); + instruction.add_operand(id); + instruction +} + +// TODO Branch Weights not implemented. +pub(super) fn instruction_branch_conditional( + condition_id: Word, + true_label: Word, + false_label: Word, +) -> Instruction { + let mut instruction = Instruction::new(Op::BranchConditional); + instruction.add_operand(condition_id); + instruction.add_operand(true_label); + instruction.add_operand(false_label); + instruction +} + pub(super) fn instruction_return() -> Instruction { Instruction::new(Op::Return) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 2e91ac454..714ce7d88 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -17,6 +17,7 @@ pub enum Error { #[derive(Default)] struct Block { + label_id: Option, label: Option, body: Vec, termination: Option, @@ -409,7 +410,14 @@ impl Writer { function_type, )); - self.write_block(&ir_function.body, ir_module, ir_function, &mut function)?; + let block = self.write_block( + &ir_function.body, + ir_module, + ir_function, + &mut function, + None, + )?; + function.blocks.push(block); function.to_words(&mut self.logical_layout.function_definitions); super::instructions::instruction_function_end() @@ -1377,11 +1385,29 @@ impl Writer { } }; - let (result_type_id, result_lookup_ty) = if result_side_left { + let is_comparison = match op { + crate::BinaryOperator::Equal + | crate::BinaryOperator::NotEqual + | crate::BinaryOperator::Less + | crate::BinaryOperator::LessEqual + | crate::BinaryOperator::Greater + | crate::BinaryOperator::GreaterEqual => true, + _ => false, + }; + + let (result_type_id, result_lookup_ty) = if is_comparison { + let local_ty = LookupType::Local(LocalType::Scalar { + kind: crate::ScalarKind::Bool, + width: 1, + }); + let result_ty_id = self.get_type_id(&ir_module.types, local_ty)?; + (result_ty_id, local_ty) + } else if result_side_left { (left_result_type_id, left_lookup_ty) } else { (right_result_type_id, right_lookup_ty) }; + block.body.push(super::instructions::instruction_binary( spirv_op, result_type_id, @@ -1812,24 +1838,85 @@ impl Writer { } } + fn create_block(&mut self) -> Block { + let mut block = Block::default(); + let label_id = self.generate_id(); + let label_instruction = super::instructions::instruction_label(label_id); + block.label_id = Some(label_id); + block.label = Some(label_instruction); + block + } + fn write_block( &mut self, - statements: &[crate::Statement], + statements: &crate::Block, ir_module: &crate::Module, ir_function: &crate::Function, function: &mut Function, - ) -> Result { - let mut block = Block::default(); - let id = self.generate_id(); - block.label = Some(super::instructions::instruction_label(id)); + merge_id: Option, + ) -> Result { + let mut block = self.create_block(); for statement in statements { match *statement { - crate::Statement::Block(ref ir_block) => { - if !ir_block.is_empty() { - //TODO: link the block with `OpBranch` - self.write_block(ir_block, ir_module, ir_function, function)?; - } + crate::Statement::Block(ref block_statements) => { + let scope_block = self.write_block( + block_statements, + ir_module, + ir_function, + function, + block.label_id, + )?; + function.blocks.push(scope_block); + } + crate::Statement::If { + ref condition, + ref accept, + ref reject, + } => { + let (condition_id, _) = self.write_expression( + ir_module, + ir_function, + *condition, + &mut block, + function, + )?; + + let pdom_block = self.create_block(); + + block + .body + .push(super::instructions::instruction_selection_merge( + pdom_block.label_id.unwrap(), + spirv::SelectionControl::NONE, + )); + + let accept_block = self.write_block( + accept, + ir_module, + ir_function, + function, + pdom_block.label_id, + )?; + let reject_block = self.write_block( + reject, + ir_module, + ir_function, + function, + pdom_block.label_id, + )?; + + block.termination = Some(super::instructions::instruction_branch_conditional( + condition_id, + accept_block.label_id.unwrap(), + reject_block.label_id.unwrap(), + )); + function.blocks.push(block); + function.blocks.push(accept_block); + function.blocks.push(reject_block); + + + block = pdom_block; } crate::Statement::Return { value } => { block.termination = Some(match ir_function.return_type { @@ -1868,8 +1955,11 @@ impl Writer { } } - function.blocks.push(block); - Ok(id) + if block.termination.is_none() { + block.termination = Some(super::instructions::instruction_branch(merge_id.unwrap())); + } + + Ok(block) } fn write_physical_layout(&mut self) { From e3328773d06a8cbea23ac0d582d164a1b0078c38 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 27 Jan 2021 16:46:56 -0500 Subject: [PATCH 0389/2212] [spv] Refactor struct Block, implement Statement::Block --- src/back/spv/writer.rs | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 714ce7d88..10551eb46 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -15,10 +15,8 @@ pub enum Error { FeatureNotImplemented(&'static str), } -#[derive(Default)] struct Block { - label_id: Option, - label: Option, + label_id: spirv::Word, body: Vec, termination: Option, } @@ -48,7 +46,7 @@ impl Function { instruction.to_words(sink); } for (index, block) in self.blocks.iter().enumerate() { - block.label.as_ref().unwrap().to_words(sink); + super::instructions::instruction_label(block.label_id).to_words(sink); if index == 0 { for local_var in self.variables.values() { local_var.instruction.to_words(sink); @@ -415,7 +413,7 @@ impl Writer { ir_module, ir_function, &mut function, - None, + 0, //isn't used )?; function.blocks.push(block); @@ -1839,12 +1837,11 @@ impl Writer { } fn create_block(&mut self) -> Block { - let mut block = Block::default(); - let label_id = self.generate_id(); - let label_instruction = super::instructions::instruction_label(label_id); - block.label_id = Some(label_id); - block.label = Some(label_instruction); - block + Block { + label_id: self.generate_id(), + body: Vec::new(), + termination: None, + } } fn write_block( @@ -1853,7 +1850,7 @@ impl Writer { ir_module: &crate::Module, ir_function: &crate::Function, function: &mut Function, - merge_id: Option, + merge_id: spirv::Word, ) -> Result { let mut block = self.create_block(); @@ -1867,7 +1864,16 @@ impl Writer { function, block.label_id, )?; + + let pdom_block = self.create_block(); + + block + .body + .push(super::instructions::instruction_branch(pdom_block.label_id)); + + function.blocks.push(block); function.blocks.push(scope_block); + block = pdom_block; } crate::Statement::If { ref condition, @@ -1887,7 +1893,7 @@ impl Writer { block .body .push(super::instructions::instruction_selection_merge( - pdom_block.label_id.unwrap(), + pdom_block.label_id, spirv::SelectionControl::NONE, )); @@ -1908,14 +1914,13 @@ impl Writer { block.termination = Some(super::instructions::instruction_branch_conditional( condition_id, - accept_block.label_id.unwrap(), - reject_block.label_id.unwrap(), + accept_block.label_id, + reject_block.label_id, )); function.blocks.push(block); function.blocks.push(accept_block); function.blocks.push(reject_block); - block = pdom_block; } crate::Statement::Return { value } => { @@ -1956,7 +1961,7 @@ impl Writer { } if block.termination.is_none() { - block.termination = Some(super::instructions::instruction_branch(merge_id.unwrap())); + block.termination = Some(super::instructions::instruction_branch(merge_id)); } Ok(block) From 3177df218854a61539e218aae97a181268ef8f60 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 27 Jan 2021 17:03:50 -0500 Subject: [PATCH 0390/2212] [spv] refactor the return statement handling --- src/back/spv/writer.rs | 46 +++++++++++++++++------------------------- 1 file changed, 19 insertions(+), 27 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 10551eb46..735544704 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1857,23 +1857,22 @@ impl Writer { for statement in statements { match *statement { crate::Statement::Block(ref block_statements) => { + let merge_block = self.create_block(); let scope_block = self.write_block( block_statements, ir_module, ir_function, function, - block.label_id, + merge_block.label_id, )?; - let pdom_block = self.create_block(); - - block - .body - .push(super::instructions::instruction_branch(pdom_block.label_id)); + block.termination = Some(super::instructions::instruction_branch( + scope_block.label_id, + )); function.blocks.push(block); function.blocks.push(scope_block); - block = pdom_block; + block = merge_block; } crate::Statement::If { ref condition, @@ -1888,12 +1887,12 @@ impl Writer { function, )?; - let pdom_block = self.create_block(); + let merge_block = self.create_block(); block .body .push(super::instructions::instruction_selection_merge( - pdom_block.label_id, + merge_block.label_id, spirv::SelectionControl::NONE, )); @@ -1902,14 +1901,14 @@ impl Writer { ir_module, ir_function, function, - pdom_block.label_id, + merge_block.label_id, )?; let reject_block = self.write_block( reject, ir_module, ir_function, function, - pdom_block.label_id, + merge_block.label_id, )?; block.termination = Some(super::instructions::instruction_branch_conditional( @@ -1917,26 +1916,19 @@ impl Writer { accept_block.label_id, reject_block.label_id, )); + function.blocks.push(block); function.blocks.push(accept_block); function.blocks.push(reject_block); - - block = pdom_block; + block = merge_block; } - crate::Statement::Return { value } => { - block.termination = Some(match ir_function.return_type { - Some(_) => { - let (id, _) = self.write_expression( - ir_module, - ir_function, - value.unwrap(), - &mut block, - function, - )?; - super::instructions::instruction_return_value(id) - } - None => super::instructions::instruction_return(), - }); + crate::Statement::Return { value: Some(value) } => { + let (id, _) = + self.write_expression(ir_module, ir_function, value, &mut block, function)?; + block.termination = Some(super::instructions::instruction_return_value(id)); + } + crate::Statement::Return { value: None } => { + block.termination = Some(super::instructions::instruction_return()); } crate::Statement::Store { pointer, value } => { let (pointer_id, _, _) = self.write_expression_pointer( From 16521a94d03bafa4ed0883c5758c0782d45869b4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 27 Jan 2021 21:53:42 -0500 Subject: [PATCH 0391/2212] [spv] implement trigonometry math functions --- src/back/spv/writer.rs | 124 ++++++++++++++++++++++++++++++----------- 1 file changed, 93 insertions(+), 31 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 735544704..93477bc7a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1256,6 +1256,34 @@ impl Writer { let id = self.write_composite_construct(base_type_id, &constituent_ids, block); Ok((RawExpression::Value(id), LookupType::Handle(ty))) } + crate::Expression::Unary { op, expr } => { + let id = self.generate_id(); + let (expr_id, expr_lookup_ty) = + self.write_expression(ir_module, ir_function, expr, block, function)?; + let expr_ty_inner = self.get_type_inner(&ir_module.types, expr_lookup_ty); + let result_type_id = self.get_type_id(&ir_module.types, expr_lookup_ty)?; + + let spirv_op = match op { + crate::UnaryOperator::Negate => match expr_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Float) => spirv::Op::FNegate, + Some(crate::ScalarKind::Sint) => spirv::Op::SNegate, + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNot, + Some(crate::ScalarKind::Uint) | None => { + log::error!("Unable to negate {:?}", &*expr_ty_inner); + return Err(Error::FeatureNotImplemented("negation")); + } + }, + crate::UnaryOperator::Not => spirv::Op::Not, + }; + + block.body.push(super::instructions::instruction_unary( + spirv_op, + result_type_id, + id, + expr_id, + )); + Ok((RawExpression::Value(id), expr_lookup_ty)) + } crate::Expression::Binary { op, left, right } => { let id = self.generate_id(); let (left_id, left_lookup_ty) = @@ -1415,14 +1443,25 @@ impl Writer { )); Ok((RawExpression::Value(id), result_lookup_ty)) } - crate::Expression::Math { fun, arg, .. } => { + crate::Expression::Math { + fun, + arg, + arg1, + arg2: _, + } => { use crate::MathFunction as Mf; + enum MathOp { + Single(spirv::GLOp), + Double(spirv::GLOp), + Other(super::Instruction, LookupType), + } let (arg0_id, arg0_lookup_ty) = self.write_expression(ir_module, ir_function, arg, block, function)?; + let arg0_type_id = self.get_type_id(&ir_module.types, arg0_lookup_ty)?; let id = self.generate_id(); - match fun { + let math_op = match fun { Mf::Transpose => { let result_lookup_ty = match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { @@ -1437,43 +1476,66 @@ impl Writer { }), _ => unreachable!(), }; - let result_type_id = - self.get_type_id(&ir_module.types, result_lookup_ty)?; - block.body.push(super::instructions::instruction_unary( + let inst = super::instructions::instruction_unary( spirv::Op::Transpose, - result_type_id, + arg0_type_id, id, arg0_id, - )); - Ok((RawExpression::Value(id), result_lookup_ty)) - } - Mf::Ceil | Mf::Round | Mf::Floor | Mf::Fract | Mf::Trunc => { - let result_lookup_ty = arg0_lookup_ty; - let result_type_id = - self.get_type_id(&ir_module.types, result_lookup_ty)?; - - block.body.push(super::instructions::instruction_ext_inst( - result_type_id, - id, - self.gl450_ext_inst_id, - match fun { - Mf::Ceil => spirv::GLOp::Ceil, - Mf::Round => spirv::GLOp::Round, - Mf::Floor => spirv::GLOp::Floor, - Mf::Fract => spirv::GLOp::Fract, - Mf::Trunc => spirv::GLOp::Trunc, - _ => unreachable!(), - } as u32, - &[arg0_id], - )); - Ok((RawExpression::Value(id), result_lookup_ty)) + ); + MathOp::Other(inst, result_lookup_ty) } + Mf::Sin => MathOp::Single(spirv::GLOp::Sin), + Mf::Asin => MathOp::Single(spirv::GLOp::Asin), + Mf::Cos => MathOp::Single(spirv::GLOp::Cos), + Mf::Acos => MathOp::Single(spirv::GLOp::Acos), + Mf::Tan => MathOp::Single(spirv::GLOp::Tan), + Mf::Atan => MathOp::Single(spirv::GLOp::Atan), + Mf::Atan2 => MathOp::Double(spirv::GLOp::Atan2), + Mf::Ceil => MathOp::Single(spirv::GLOp::Ceil), + Mf::Round => MathOp::Single(spirv::GLOp::Round), + Mf::Floor => MathOp::Single(spirv::GLOp::Floor), + Mf::Fract => MathOp::Single(spirv::GLOp::Fract), + Mf::Trunc => MathOp::Single(spirv::GLOp::Trunc), _ => { log::error!("unimplemented math function {:?}", fun); - Err(Error::FeatureNotImplemented("math function")) + return Err(Error::FeatureNotImplemented("math function")); } - } + }; + + let (instruction, result_lookup_ty) = match math_op { + MathOp::Single(op) => { + let inst = super::instructions::instruction_ext_inst( + arg0_type_id, + id, + self.gl450_ext_inst_id, + op as u32, + &[arg0_id], + ); + (inst, arg0_lookup_ty) + } + MathOp::Double(op) => { + let (arg1_id, _) = self.write_expression( + ir_module, + ir_function, + arg1.unwrap(), + block, + function, + )?; + let inst = super::instructions::instruction_ext_inst( + arg0_type_id, + id, + self.gl450_ext_inst_id, + op as u32, + &[arg0_id, arg1_id], + ); + (inst, arg0_lookup_ty) + } + MathOp::Other(inst, result_lookup_ty) => (inst, result_lookup_ty), + }; + + block.body.push(instruction); + Ok((RawExpression::Value(id), result_lookup_ty)) } crate::Expression::LocalVariable(variable) => { let var = &ir_function.local_variables[variable]; From b9cc890ca6b5d6748cef228d48c463af24891272 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 27 Jan 2021 23:56:29 -0500 Subject: [PATCH 0392/2212] [spv] implement loops --- src/back/spv/instructions.rs | 16 +++++++- src/back/spv/writer.rs | 77 ++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 2 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 4a6f0a6f4..b3e264328 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -657,11 +657,23 @@ pub(super) fn instruction_binary( // pub(super) fn instruction_selection_merge( - id: Word, + merge_id: Word, selection_control: spirv::SelectionControl, ) -> Instruction { let mut instruction = Instruction::new(Op::SelectionMerge); - instruction.add_operand(id); + instruction.add_operand(merge_id); + instruction.add_operand(selection_control.bits()); + instruction +} + +pub(super) fn instruction_loop_merge( + merge_id: Word, + continuing_id: Word, + selection_control: spirv::SelectionControl, +) -> Instruction { + let mut instruction = Instruction::new(Op::LoopMerge); + instruction.add_operand(merge_id); + instruction.add_operand(continuing_id); instruction.add_operand(selection_control.bits()); instruction } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 93477bc7a..45386845f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -144,6 +144,12 @@ fn get_dimension(ty_inner: &crate::TypeInner) -> Dimension { } } +#[derive(Clone, Copy, Default)] +struct LoopContext { + continuing_id: Option, + break_id: Option, +} + pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, @@ -414,6 +420,7 @@ impl Writer { ir_function, &mut function, 0, //isn't used + LoopContext::default(), )?; function.blocks.push(block); @@ -1913,10 +1920,15 @@ impl Writer { ir_function: &crate::Function, function: &mut Function, merge_id: spirv::Word, + loop_context: LoopContext, ) -> Result { let mut block = self.create_block(); for statement in statements { + assert!( + block.termination.is_none(), + "No statements are expected after block termination" + ); match *statement { crate::Statement::Block(ref block_statements) => { let merge_block = self.create_block(); @@ -1926,6 +1938,7 @@ impl Writer { ir_function, function, merge_block.label_id, + loop_context, )?; block.termination = Some(super::instructions::instruction_branch( @@ -1964,6 +1977,7 @@ impl Writer { ir_function, function, merge_block.label_id, + loop_context, )?; let reject_block = self.write_block( reject, @@ -1971,6 +1985,7 @@ impl Writer { ir_function, function, merge_block.label_id, + loop_context, )?; block.termination = Some(super::instructions::instruction_branch_conditional( @@ -1984,6 +1999,68 @@ impl Writer { function.blocks.push(reject_block); block = merge_block; } + crate::Statement::Loop { + ref body, + ref continuing, + } => { + let merge_block = self.create_block(); + let mut preamble_block = self.create_block(); + block.termination = Some(super::instructions::instruction_branch( + preamble_block.label_id, + )); + + let continuing_block = self.write_block( + continuing, + ir_module, + ir_function, + function, + preamble_block.label_id, + LoopContext { + continuing_id: None, + break_id: Some(merge_block.label_id), + }, + )?; + + let loop_block = self.write_block( + body, + ir_module, + ir_function, + function, + continuing_block.label_id, + LoopContext { + continuing_id: Some(continuing_block.label_id), + break_id: Some(merge_block.label_id), + }, + )?; + + // SPIR-V requires the continuing to the `OpLoopMerge`, + // so we have to start a new block with it. + preamble_block + .body + .push(super::instructions::instruction_loop_merge( + merge_block.label_id, + continuing_block.label_id, + spirv::SelectionControl::NONE, + )); + preamble_block.termination = + Some(super::instructions::instruction_branch(loop_block.label_id)); + + function.blocks.push(block); + function.blocks.push(preamble_block); + function.blocks.push(loop_block); + function.blocks.push(continuing_block); + block = merge_block; + } + crate::Statement::Break => { + block.termination = Some(super::instructions::instruction_branch( + loop_context.break_id.unwrap(), + )); + } + crate::Statement::Continue => { + block.termination = Some(super::instructions::instruction_branch( + loop_context.continuing_id.unwrap(), + )); + } crate::Statement::Return { value: Some(value) } => { let (id, _) = self.write_expression(ir_module, ir_function, value, &mut block, function)?; From 7d3342f2c987e5e6e65b4cac8038c95ebdbc7a34 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 28 Jan 2021 00:28:16 -0500 Subject: [PATCH 0393/2212] [spv] Implement math comparison functions --- src/back/spv/instructions.rs | 4 +- src/back/spv/writer.rs | 215 +++++++++++++++++++++++++++++++---- 2 files changed, 194 insertions(+), 25 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index b3e264328..1d891c646 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -73,17 +73,17 @@ pub(super) fn instruction_ext_inst_import(id: Word, name: &str) -> Instruction { } pub(super) fn instruction_ext_inst( + op: spirv::GLOp, result_type_id: Word, id: Word, set_id: Word, - ext_instruction: u32, operands: &[Word], ) -> Instruction { let mut instruction = Instruction::new(Op::ExtInst); instruction.set_type(result_type_id); instruction.set_result(id); instruction.add_operand(set_id); - instruction.add_operand(ext_instruction); + instruction.add_operand(op as u32); for operand in operands { instruction.add_operand(*operand) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 45386845f..e06ceef98 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1454,21 +1454,197 @@ impl Writer { fun, arg, arg1, - arg2: _, + arg2, } => { use crate::MathFunction as Mf; enum MathOp { Single(spirv::GLOp), Double(spirv::GLOp), + Triple(spirv::GLOp), Other(super::Instruction, LookupType), } let (arg0_id, arg0_lookup_ty) = self.write_expression(ir_module, ir_function, arg, block, function)?; let arg0_type_id = self.get_type_id(&ir_module.types, arg0_lookup_ty)?; + let arg1_id = match arg1 { + Some(id) => { + let (arg1_id, _) = + self.write_expression(ir_module, ir_function, id, block, function)?; + arg1_id + } + None => 0, + }; + let arg2_id = match arg2 { + Some(id) => { + let (arg2_id, _) = + self.write_expression(ir_module, ir_function, id, block, function)?; + arg2_id + } + None => 0, + }; let id = self.generate_id(); let math_op = match fun { + // comparison + Mf::Abs => { + let inst = match self + .get_type_inner(&ir_module.types, arg0_lookup_ty) + .scalar_kind() + { + Some(crate::ScalarKind::Float) => { + super::instructions::instruction_ext_inst( + spirv::GLOp::FAbs, + arg0_type_id, + self.gl450_ext_inst_id, + id, + &[arg0_id], + ) + } + Some(crate::ScalarKind::Sint) => { + super::instructions::instruction_ext_inst( + spirv::GLOp::SAbs, + arg0_type_id, + self.gl450_ext_inst_id, + id, + &[arg0_id], + ) + } + Some(crate::ScalarKind::Uint) => { + super::instructions::instruction_unary( + spirv::Op::CopyObject, // do nothing + arg0_type_id, + id, + arg0_id, + ) + } + other => unimplemented!("Unexpected abs({:?})", other), + }; + MathOp::Other(inst, arg0_lookup_ty) + } + Mf::Min => { + let op = match self + .get_type_inner(&ir_module.types, arg0_lookup_ty) + .scalar_kind() + { + Some(crate::ScalarKind::Float) => spirv::GLOp::FMin, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SMin, + Some(crate::ScalarKind::Uint) => spirv::GLOp::UMin, + other => unimplemented!("Unexpected min({:?})", other), + }; + MathOp::Double(op) + } + Mf::Max => { + let op = match self + .get_type_inner(&ir_module.types, arg0_lookup_ty) + .scalar_kind() + { + Some(crate::ScalarKind::Float) => spirv::GLOp::FMax, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SMax, + Some(crate::ScalarKind::Uint) => spirv::GLOp::UMax, + other => unimplemented!("Unexpected max({:?})", other), + }; + MathOp::Double(op) + } + Mf::Clamp => { + let op = match self + .get_type_inner(&ir_module.types, arg0_lookup_ty) + .scalar_kind() + { + Some(crate::ScalarKind::Float) => spirv::GLOp::FClamp, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SClamp, + Some(crate::ScalarKind::Uint) => spirv::GLOp::UClamp, + other => unimplemented!("Unexpected max({:?})", other), + }; + MathOp::Triple(op) + } + // trigonometry + Mf::Sin => MathOp::Single(spirv::GLOp::Sin), + Mf::Asin => MathOp::Single(spirv::GLOp::Asin), + Mf::Cos => MathOp::Single(spirv::GLOp::Cos), + Mf::Acos => MathOp::Single(spirv::GLOp::Acos), + Mf::Tan => MathOp::Single(spirv::GLOp::Tan), + Mf::Atan => MathOp::Single(spirv::GLOp::Atan), + Mf::Atan2 => MathOp::Double(spirv::GLOp::Atan2), + // decomposition + Mf::Ceil => MathOp::Single(spirv::GLOp::Ceil), + Mf::Round => MathOp::Single(spirv::GLOp::Round), + Mf::Floor => MathOp::Single(spirv::GLOp::Floor), + Mf::Fract => MathOp::Single(spirv::GLOp::Fract), + Mf::Trunc => MathOp::Single(spirv::GLOp::Trunc), + // geometry + Mf::Dot => { + let result_lookup_ty = + match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { + crate::TypeInner::Scalar { kind, width } + | crate::TypeInner::Vector { + size: _, + kind, + width, + } => LookupType::Local(LocalType::Scalar { kind, width }), + _ => unreachable!(), + }; + let result_type_id = + self.get_type_id(&ir_module.types, result_lookup_ty)?; + + let inst = super::instructions::instruction_binary( + spirv::Op::Dot, + result_type_id, + id, + arg0_id, + arg1_id, + ); + MathOp::Other(inst, result_lookup_ty) + } + Mf::Cross => MathOp::Double(spirv::GLOp::Cross), + Mf::Distance => { + let result_lookup_ty = + match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { + crate::TypeInner::Scalar { kind, width } + | crate::TypeInner::Vector { + size: _, + kind, + width, + } => LookupType::Local(LocalType::Scalar { kind, width }), + _ => unreachable!(), + }; + let result_type_id = + self.get_type_id(&ir_module.types, result_lookup_ty)?; + + let inst = super::instructions::instruction_ext_inst( + spirv::GLOp::Distance, + result_type_id, + self.gl450_ext_inst_id, + id, + &[arg0_id, arg1_id], + ); + MathOp::Other(inst, result_lookup_ty) + } + Mf::Length => { + let result_lookup_ty = + match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { + crate::TypeInner::Scalar { kind, width } + | crate::TypeInner::Vector { + size: _, + kind, + width, + } => LookupType::Local(LocalType::Scalar { kind, width }), + _ => unreachable!(), + }; + let result_type_id = + self.get_type_id(&ir_module.types, result_lookup_ty)?; + + let inst = super::instructions::instruction_ext_inst( + spirv::GLOp::Length, + result_type_id, + self.gl450_ext_inst_id, + id, + &[arg0_id, arg1_id], + ); + MathOp::Other(inst, result_lookup_ty) + } + Mf::Normalize => MathOp::Single(spirv::GLOp::Normalize), + // computational Mf::Transpose => { let result_lookup_ty = match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { @@ -1483,27 +1659,17 @@ impl Writer { }), _ => unreachable!(), }; + let result_type_id = + self.get_type_id(&ir_module.types, result_lookup_ty)?; let inst = super::instructions::instruction_unary( spirv::Op::Transpose, - arg0_type_id, + result_type_id, id, arg0_id, ); MathOp::Other(inst, result_lookup_ty) } - Mf::Sin => MathOp::Single(spirv::GLOp::Sin), - Mf::Asin => MathOp::Single(spirv::GLOp::Asin), - Mf::Cos => MathOp::Single(spirv::GLOp::Cos), - Mf::Acos => MathOp::Single(spirv::GLOp::Acos), - Mf::Tan => MathOp::Single(spirv::GLOp::Tan), - Mf::Atan => MathOp::Single(spirv::GLOp::Atan), - Mf::Atan2 => MathOp::Double(spirv::GLOp::Atan2), - Mf::Ceil => MathOp::Single(spirv::GLOp::Ceil), - Mf::Round => MathOp::Single(spirv::GLOp::Round), - Mf::Floor => MathOp::Single(spirv::GLOp::Floor), - Mf::Fract => MathOp::Single(spirv::GLOp::Fract), - Mf::Trunc => MathOp::Single(spirv::GLOp::Trunc), _ => { log::error!("unimplemented math function {:?}", fun); return Err(Error::FeatureNotImplemented("math function")); @@ -1513,31 +1679,34 @@ impl Writer { let (instruction, result_lookup_ty) = match math_op { MathOp::Single(op) => { let inst = super::instructions::instruction_ext_inst( + op, arg0_type_id, id, self.gl450_ext_inst_id, - op as u32, &[arg0_id], ); (inst, arg0_lookup_ty) } MathOp::Double(op) => { - let (arg1_id, _) = self.write_expression( - ir_module, - ir_function, - arg1.unwrap(), - block, - function, - )?; let inst = super::instructions::instruction_ext_inst( + op, arg0_type_id, id, self.gl450_ext_inst_id, - op as u32, &[arg0_id, arg1_id], ); (inst, arg0_lookup_ty) } + MathOp::Triple(op) => { + let inst = super::instructions::instruction_ext_inst( + op, + arg0_type_id, + id, + self.gl450_ext_inst_id, + &[arg0_id, arg1_id, arg2_id], + ); + (inst, arg0_lookup_ty) + } MathOp::Other(inst, result_lookup_ty) => (inst, result_lookup_ty), }; From 194a67eddace77bacf083cd0321baceaf2e9b155 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 28 Jan 2021 01:55:39 -0500 Subject: [PATCH 0394/2212] [spv] separate block ID creation from contents writing --- src/back/spv/writer.rs | 202 ++++++++++++++++++++--------------------- 1 file changed, 100 insertions(+), 102 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e06ceef98..4b0a09d3a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -16,11 +16,21 @@ pub enum Error { } struct Block { - label_id: spirv::Word, + label_id: Word, body: Vec, termination: Option, } +impl Block { + fn new(label_id: Word) -> Self { + Block { + label_id, + body: Vec::new(), + termination: None, + } + } +} + struct LocalVariable { id: Word, instruction: Instruction, @@ -58,6 +68,12 @@ impl Function { block.termination.as_ref().unwrap().to_words(sink); } } + + fn consume(&mut self, mut block: Block, termination: Instruction) { + assert!(block.termination.is_none()); + block.termination = Some(termination); + self.blocks.push(block); + } } #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] @@ -353,7 +369,7 @@ impl Writer { &mut self, ir_function: &crate::Function, ir_module: &crate::Module, - ) -> Result { + ) -> Result { let mut function = Function::default(); for (handle, variable) in ir_function.local_variables.iter() { @@ -380,21 +396,15 @@ impl Writer { self.get_function_return_type(ir_function.return_type, &ir_module.types)?; let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); - let mut function_parameter_pointer_ids = vec![]; - for argument in ir_function.arguments.iter() { let id = self.generate_id(); - let pointer_type_id = - self.get_pointer_id(&ir_module.types, argument.ty, crate::StorageClass::Function)?; - - function_parameter_pointer_ids.push(pointer_type_id); let parameter_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(argument.ty))?; parameter_type_ids.push(parameter_type_id); function .parameters .push(super::instructions::instruction_function_parameter( - pointer_type_id, + parameter_type_id, id, )); } @@ -405,8 +415,7 @@ impl Writer { }; let function_id = self.generate_id(); - let function_type = - self.get_function_type(lookup_function_type, function_parameter_pointer_ids); + let function_type = self.get_function_type(lookup_function_type); function.signature = Some(super::instructions::instruction_function( return_type_id, function_id, @@ -414,15 +423,16 @@ impl Writer { function_type, )); - let block = self.write_block( + let main_id = self.generate_id(); + self.write_block( + main_id, &ir_function.body, ir_module, ir_function, &mut function, - 0, //isn't used + None, LoopContext::default(), )?; - function.blocks.push(block); function.to_words(&mut self.logical_layout.function_definitions); super::instructions::instruction_function_end() @@ -759,7 +769,7 @@ impl Writer { fn write_constant_type( &mut self, - id: spirv::Word, + id: Word, inner: &crate::ConstantInner, ir_module: &crate::Module, ) -> Result<(), Error> { @@ -964,11 +974,7 @@ impl Writer { Ok((instruction, id, class)) } - fn get_function_type( - &mut self, - lookup_function_type: LookupFunctionType, - parameter_pointer_ids: Vec, - ) -> Word { + fn get_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { match self .lookup_function_type .entry(lookup_function_type.clone()) @@ -979,7 +985,7 @@ impl Writer { let instruction = super::instructions::instruction_type_function( id, lookup_function_type.return_type_id, - parameter_pointer_ids.as_slice(), + &lookup_function_type.parameter_type_ids, ); instruction.to_words(&mut self.logical_layout.declarations); self.lookup_function_type.insert(lookup_function_type, id); @@ -1722,12 +1728,9 @@ impl Writer { )) } crate::Expression::FunctionArgument(index) => { - let handle = ir_function.arguments[index as usize].ty; + let ty_handle = ir_function.arguments[index as usize].ty; let id = function.parameters[index as usize].result_id.unwrap(); - Ok(( - RawExpression::Pointer(id, spirv::StorageClass::Function), - LookupType::Handle(handle), - )) + Ok((RawExpression::Value(id), LookupType::Handle(ty_handle))) } crate::Expression::Call { function: local_function, @@ -2074,24 +2077,17 @@ impl Writer { } } - fn create_block(&mut self) -> Block { - Block { - label_id: self.generate_id(), - body: Vec::new(), - termination: None, - } - } - fn write_block( &mut self, + label_id: Word, statements: &crate::Block, ir_module: &crate::Module, ir_function: &crate::Function, function: &mut Function, - merge_id: spirv::Word, + exit_id: Option, loop_context: LoopContext, - ) -> Result { - let mut block = self.create_block(); + ) -> Result<(), Error> { + let mut block = Block::new(label_id); for statement in statements { assert!( @@ -2100,23 +2096,21 @@ impl Writer { ); match *statement { crate::Statement::Block(ref block_statements) => { - let merge_block = self.create_block(); - let scope_block = self.write_block( + let scope_id = self.generate_id(); + function.consume(block, super::instructions::instruction_branch(scope_id)); + + let merge_id = self.generate_id(); + self.write_block( + scope_id, block_statements, ir_module, ir_function, function, - merge_block.label_id, + Some(merge_id), loop_context, )?; - block.termination = Some(super::instructions::instruction_branch( - scope_block.label_id, - )); - - function.blocks.push(block); - function.blocks.push(scope_block); - block = merge_block; + block = Block::new(merge_id); } crate::Statement::If { ref condition, @@ -2131,94 +2125,94 @@ impl Writer { function, )?; - let merge_block = self.create_block(); - + let merge_id = self.generate_id(); block .body .push(super::instructions::instruction_selection_merge( - merge_block.label_id, + merge_id, spirv::SelectionControl::NONE, )); - let accept_block = self.write_block( + let accept_id = self.generate_id(); + let reject_id = self.generate_id(); + function.consume( + block, + super::instructions::instruction_branch_conditional( + condition_id, + accept_id, + reject_id, + ), + ); + + self.write_block( + accept_id, accept, ir_module, ir_function, function, - merge_block.label_id, + Some(merge_id), loop_context, )?; - let reject_block = self.write_block( + self.write_block( + reject_id, reject, ir_module, ir_function, function, - merge_block.label_id, + Some(merge_id), loop_context, )?; - block.termination = Some(super::instructions::instruction_branch_conditional( - condition_id, - accept_block.label_id, - reject_block.label_id, - )); - - function.blocks.push(block); - function.blocks.push(accept_block); - function.blocks.push(reject_block); - block = merge_block; + block = Block::new(merge_id); } crate::Statement::Loop { ref body, ref continuing, } => { - let merge_block = self.create_block(); - let mut preamble_block = self.create_block(); - block.termination = Some(super::instructions::instruction_branch( - preamble_block.label_id, + let preamble_id = self.generate_id(); + function.consume(block, super::instructions::instruction_branch(preamble_id)); + + let merge_id = self.generate_id(); + let body_id = self.generate_id(); + let continuing_id = self.generate_id(); + + // SPIR-V requires the continuing to the `OpLoopMerge`, + // so we have to start a new block with it. + block = Block::new(preamble_id); + block.body.push(super::instructions::instruction_loop_merge( + merge_id, + continuing_id, + spirv::SelectionControl::NONE, )); + function.consume(block, super::instructions::instruction_branch(body_id)); - let continuing_block = self.write_block( - continuing, - ir_module, - ir_function, - function, - preamble_block.label_id, - LoopContext { - continuing_id: None, - break_id: Some(merge_block.label_id), - }, - )?; - - let loop_block = self.write_block( + self.write_block( + body_id, body, ir_module, ir_function, function, - continuing_block.label_id, + Some(continuing_id), LoopContext { - continuing_id: Some(continuing_block.label_id), - break_id: Some(merge_block.label_id), + continuing_id: Some(continuing_id), + break_id: Some(merge_id), }, )?; - // SPIR-V requires the continuing to the `OpLoopMerge`, - // so we have to start a new block with it. - preamble_block - .body - .push(super::instructions::instruction_loop_merge( - merge_block.label_id, - continuing_block.label_id, - spirv::SelectionControl::NONE, - )); - preamble_block.termination = - Some(super::instructions::instruction_branch(loop_block.label_id)); + self.write_block( + continuing_id, + continuing, + ir_module, + ir_function, + function, + Some(preamble_id), + LoopContext { + continuing_id: None, + break_id: Some(merge_id), + }, + )?; - function.blocks.push(block); - function.blocks.push(preamble_block); - function.blocks.push(loop_block); - function.blocks.push(continuing_block); - block = merge_block; + block = Block::new(merge_id); } crate::Statement::Break => { block.termination = Some(super::instructions::instruction_branch( @@ -2261,10 +2255,14 @@ impl Writer { } if block.termination.is_none() { - block.termination = Some(super::instructions::instruction_branch(merge_id)); + block.termination = Some(match exit_id { + Some(id) => super::instructions::instruction_branch(id), + None => super::instructions::instruction_return(), + }); } - Ok(block) + function.blocks.push(block); + Ok(()) } fn write_physical_layout(&mut self) { From 162079c1606b47ccd480aaa978ec92256dbeb119 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 28 Jan 2021 00:31:21 -0500 Subject: [PATCH 0395/2212] Enable collatz and boids testing for spv-out --- src/back/spv/instructions.rs | 2 +- src/back/spv/writer.rs | 16 +- tests/snapshots.rs | 4 +- tests/snapshots/in/boids.wgsl | 4 +- tests/snapshots/in/collatz.wgsl | 5 +- tests/snapshots/snapshots__boids.msl.snap | 6 +- tests/snapshots/snapshots__boids.spvasm.snap | 543 ++++++++++++++++++ tests/snapshots/snapshots__collatz.msl.snap | 4 +- .../snapshots/snapshots__collatz.spvasm.snap | 109 ++++ 9 files changed, 675 insertions(+), 18 deletions(-) create mode 100644 tests/snapshots/snapshots__boids.spvasm.snap create mode 100644 tests/snapshots/snapshots__collatz.spvasm.snap diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 1d891c646..ec4a2935a 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -73,10 +73,10 @@ pub(super) fn instruction_ext_inst_import(id: Word, name: &str) -> Instruction { } pub(super) fn instruction_ext_inst( + set_id: Word, op: spirv::GLOp, result_type_id: Word, id: Word, - set_id: Word, operands: &[Word], ) -> Instruction { let mut instruction = Instruction::new(Op::ExtInst); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4b0a09d3a..237020de1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1500,18 +1500,18 @@ impl Writer { { Some(crate::ScalarKind::Float) => { super::instructions::instruction_ext_inst( + self.gl450_ext_inst_id, spirv::GLOp::FAbs, arg0_type_id, - self.gl450_ext_inst_id, id, &[arg0_id], ) } Some(crate::ScalarKind::Sint) => { super::instructions::instruction_ext_inst( + self.gl450_ext_inst_id, spirv::GLOp::SAbs, arg0_type_id, - self.gl450_ext_inst_id, id, &[arg0_id], ) @@ -1618,9 +1618,9 @@ impl Writer { self.get_type_id(&ir_module.types, result_lookup_ty)?; let inst = super::instructions::instruction_ext_inst( + self.gl450_ext_inst_id, spirv::GLOp::Distance, result_type_id, - self.gl450_ext_inst_id, id, &[arg0_id, arg1_id], ); @@ -1641,11 +1641,11 @@ impl Writer { self.get_type_id(&ir_module.types, result_lookup_ty)?; let inst = super::instructions::instruction_ext_inst( + self.gl450_ext_inst_id, spirv::GLOp::Length, result_type_id, - self.gl450_ext_inst_id, id, - &[arg0_id, arg1_id], + &[arg0_id], ); MathOp::Other(inst, result_lookup_ty) } @@ -1685,30 +1685,30 @@ impl Writer { let (instruction, result_lookup_ty) = match math_op { MathOp::Single(op) => { let inst = super::instructions::instruction_ext_inst( + self.gl450_ext_inst_id, op, arg0_type_id, id, - self.gl450_ext_inst_id, &[arg0_id], ); (inst, arg0_lookup_ty) } MathOp::Double(op) => { let inst = super::instructions::instruction_ext_inst( + self.gl450_ext_inst_id, op, arg0_type_id, id, - self.gl450_ext_inst_id, &[arg0_id, arg1_id], ); (inst, arg0_lookup_ty) } MathOp::Triple(op) => { let inst = super::instructions::instruction_ext_inst( + self.gl450_ext_inst_id, op, arg0_type_id, id, - self.gl450_ext_inst_id, &[arg0_id, arg1_id, arg2_id], ); (inst, arg0_lookup_ty) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 9016c3be0..1ab096343 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -168,7 +168,7 @@ fn convert_wgsl_empty() { #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_boids() { - convert_wgsl("boids", Language::METAL); + convert_wgsl("boids", Language::METAL | Language::SPIRV); } #[cfg(feature = "wgsl-in")] @@ -180,5 +180,5 @@ fn convert_wgsl_skybox() { #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_collatz() { - convert_wgsl("collatz", Language::METAL); + convert_wgsl("collatz", Language::METAL | Language::SPIRV); } diff --git a/tests/snapshots/in/boids.wgsl b/tests/snapshots/in/boids.wgsl index b75b671a0..a1594c7bd 100644 --- a/tests/snapshots/in/boids.wgsl +++ b/tests/snapshots/in/boids.wgsl @@ -113,10 +113,10 @@ fn main() { } } if (cMassCount > 0) { - cMass = (cMass / vec2(cMassCount, cMassCount)) + vPos; + cMass = (cMass / vec2(vec2(cMassCount, cMassCount))) + vPos; } if (cVelCount > 0) { - cVel = cVel / vec2(cVelCount, cVelCount); + cVel = cVel / vec2(vec2(cVelCount, cVelCount)); } vVel = vVel + (cMass * params.rule1Scale) + (colVel * params.rule2Scale) + diff --git a/tests/snapshots/in/collatz.wgsl b/tests/snapshots/in/collatz.wgsl index 54312943d..2433f3243 100644 --- a/tests/snapshots/in/collatz.wgsl +++ b/tests/snapshots/in/collatz.wgsl @@ -3,7 +3,7 @@ var global_id: vec3; [[block]] struct PrimeIndices { - data: array; + data: [[stride(4)]] array; }; // this is used as both input and output for convenience [[group(0), binding(0)]] @@ -15,7 +15,8 @@ var v_indices: [[access(read_write)]] PrimeIndices; // And repeat this process for each new n, you will always eventually reach 1. // Though the conjecture has not been proven, no counterexample has ever been found. // This function returns how many times this recurrence needs to be applied to reach 1. -fn collatz_iterations(n: u32) -> u32{ +fn collatz_iterations(n_base: u32) -> u32{ + var n: u32 = n_base; var i: u32 = 0u; loop { if (n <= 1u) { diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap index 1e173def6..0a5b99ec5 100644 --- a/tests/snapshots/snapshots__boids.msl.snap +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -38,6 +38,8 @@ typedef uint type5; typedef int type6; +typedef metal::int2 type7; + struct main1Input { type a_particlePos [[attribute(0)]]; type a_particleVel [[attribute(1)]]; @@ -116,10 +118,10 @@ kernel void main3( } } if (cMassCount == 0) { - cMass = cMass / metal::float2(cMassCount, cMassCount) + vPos; + cMass = cMass / static_cast(metal::int2(cMassCount, cMassCount)) + vPos; } if (cVelCount == 0) { - cVel = cVel / metal::float2(cVelCount, cVelCount); + cVel = cVel / static_cast(metal::int2(cVelCount, cVelCount)); } vVel = vVel + cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale; vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap new file mode 100644 index 000000000..e62898031 --- /dev/null +++ b/tests/snapshots/snapshots__boids.spvasm.snap @@ -0,0 +1,543 @@ +--- +source: tests/snapshots.rs +expression: dis +--- +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 418 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %3 "main" %83 %23 %15 %6 +OpEntryPoint Fragment %88 "main" %90 +OpEntryPoint GLCompute %108 "main" %112 +OpExecutionMode %88 OriginUpperLeft +OpExecutionMode %108 LocalSize 1 1 1 +OpDecorate %6 BuiltIn Position +OpDecorate %15 Location 2 +OpDecorate %23 Location 1 +OpDecorate %83 Location 0 +OpDecorate %90 Location 0 +OpDecorate %112 BuiltIn GlobalInvocationId +OpDecorate %127 BufferBlock +OpMemberDecorate %127 0 Offset 0 +OpDecorate %128 ArrayStride 16 +OpDecorate %129 Block +OpMemberDecorate %129 0 Offset 0 +OpMemberDecorate %129 1 Offset 8 +OpDecorate %126 DescriptorSet 0 +OpDecorate %126 Binding 1 +OpDecorate %235 Block +OpMemberDecorate %235 0 Offset 0 +OpMemberDecorate %235 1 Offset 4 +OpMemberDecorate %235 2 Offset 8 +OpMemberDecorate %235 3 Offset 12 +OpMemberDecorate %235 4 Offset 16 +OpMemberDecorate %235 5 Offset 20 +OpMemberDecorate %235 6 Offset 24 +OpDecorate %234 DescriptorSet 0 +OpDecorate %234 Binding 0 +OpDecorate %394 DescriptorSet 0 +OpDecorate %394 Binding 2 +%2 = OpTypeVoid +%4 = OpTypeFunction %2 +%8 = OpTypeFloat 32 +%7 = OpTypeVector %8 4 +%9 = OpTypePointer Output %7 +%6 = OpVariable %9 Output +%11 = OpTypeVector %8 2 +%16 = OpTypePointer Input %11 +%15 = OpVariable %16 Input +%17 = OpTypeInt 32 1 +%18 = OpConstant %17 0 +%19 = OpTypePointer Input %8 +%23 = OpVariable %16 Input +%24 = OpConstant %17 0 +%25 = OpTypePointer Input %8 +%28 = OpConstant %17 1 +%29 = OpTypePointer Input %8 +%35 = OpConstant %17 1 +%36 = OpTypePointer Input %8 +%40 = OpConstant %17 0 +%41 = OpTypePointer Input %8 +%44 = OpConstant %17 1 +%45 = OpTypePointer Input %8 +%52 = OpConstant %17 0 +%53 = OpTypePointer Input %8 +%57 = OpConstant %17 0 +%58 = OpTypePointer Input %8 +%61 = OpConstant %17 1 +%62 = OpTypePointer Input %8 +%68 = OpConstant %17 1 +%69 = OpTypePointer Input %8 +%73 = OpConstant %17 0 +%74 = OpTypePointer Input %8 +%77 = OpConstant %17 1 +%78 = OpTypePointer Input %8 +%83 = OpVariable %16 Input +%85 = OpConstant %8 0.0 +%86 = OpConstant %8 1.0 +%90 = OpVariable %9 Output +%93 = OpTypePointer Function %11 +%99 = OpConstant %17 0 +%100 = OpTypePointer Function %17 +%106 = OpTypeInt 32 0 +%105 = OpConstant %106 0 +%107 = OpTypePointer Function %106 +%113 = OpTypeVector %106 3 +%114 = OpTypePointer Input %113 +%112 = OpVariable %114 Input +%115 = OpConstant %17 0 +%116 = OpTypePointer Input %106 +%118 = OpConstant %106 5 +%119 = OpTypeBool +%129 = OpTypeStruct %11 %11 +%128 = OpTypeArray %129 %118 +%127 = OpTypeStruct %128 +%130 = OpTypePointer Uniform %127 +%126 = OpVariable %130 Uniform +%131 = OpConstant %17 0 +%132 = OpTypePointer Uniform %128 +%134 = OpConstant %17 0 +%135 = OpTypePointer Input %106 +%137 = OpTypePointer Uniform %129 +%138 = OpConstant %17 0 +%139 = OpTypePointer Uniform %11 +%144 = OpConstant %17 0 +%145 = OpTypePointer Uniform %128 +%147 = OpConstant %17 0 +%148 = OpTypePointer Input %106 +%150 = OpTypePointer Uniform %129 +%151 = OpConstant %17 1 +%152 = OpTypePointer Uniform %11 +%169 = OpConstant %17 0 +%170 = OpTypePointer Input %106 +%179 = OpConstant %17 0 +%180 = OpTypePointer Uniform %128 +%182 = OpTypePointer Uniform %129 +%183 = OpConstant %17 0 +%184 = OpTypePointer Uniform %11 +%185 = OpConstant %17 0 +%186 = OpTypePointer Uniform %8 +%192 = OpConstant %17 0 +%193 = OpTypePointer Uniform %128 +%195 = OpTypePointer Uniform %129 +%196 = OpConstant %17 0 +%197 = OpTypePointer Uniform %11 +%198 = OpConstant %17 1 +%199 = OpTypePointer Uniform %8 +%206 = OpConstant %17 0 +%207 = OpTypePointer Uniform %128 +%209 = OpTypePointer Uniform %129 +%210 = OpConstant %17 1 +%211 = OpTypePointer Uniform %11 +%212 = OpConstant %17 0 +%213 = OpTypePointer Uniform %8 +%219 = OpConstant %17 0 +%220 = OpTypePointer Uniform %128 +%222 = OpTypePointer Uniform %129 +%223 = OpConstant %17 1 +%224 = OpTypePointer Uniform %11 +%225 = OpConstant %17 1 +%226 = OpTypePointer Uniform %8 +%235 = OpTypeStruct %8 %8 %8 %8 %8 %8 %8 +%236 = OpTypePointer Uniform %235 +%234 = OpVariable %236 Uniform +%237 = OpConstant %17 1 +%238 = OpTypePointer Uniform %8 +%248 = OpConstant %17 1 +%254 = OpConstant %17 2 +%255 = OpTypePointer Uniform %8 +%270 = OpConstant %17 3 +%271 = OpTypePointer Uniform %8 +%283 = OpConstant %106 1 +%292 = OpTypeVector %17 2 +%316 = OpConstant %17 4 +%317 = OpTypePointer Uniform %8 +%322 = OpConstant %17 5 +%323 = OpTypePointer Uniform %8 +%328 = OpConstant %17 6 +%329 = OpTypePointer Uniform %8 +%336 = OpConstant %8 0.1 +%343 = OpConstant %17 0 +%344 = OpTypePointer Uniform %8 +%348 = OpConstant %17 0 +%349 = OpTypePointer Function %8 +%351 = OpConstant %8 -1.0 +%356 = OpConstant %17 0 +%357 = OpTypePointer Function %8 +%360 = OpConstant %17 0 +%361 = OpTypePointer Function %8 +%367 = OpConstant %17 0 +%368 = OpTypePointer Function %8 +%371 = OpConstant %17 1 +%372 = OpTypePointer Function %8 +%378 = OpConstant %17 1 +%379 = OpTypePointer Function %8 +%382 = OpConstant %17 1 +%383 = OpTypePointer Function %8 +%389 = OpConstant %17 1 +%390 = OpTypePointer Function %8 +%394 = OpVariable %130 Uniform +%395 = OpConstant %17 0 +%396 = OpTypePointer Uniform %128 +%398 = OpConstant %17 0 +%399 = OpTypePointer Input %106 +%401 = OpTypePointer Uniform %129 +%402 = OpConstant %17 0 +%403 = OpTypePointer Uniform %11 +%408 = OpConstant %17 0 +%409 = OpTypePointer Uniform %128 +%411 = OpConstant %17 0 +%412 = OpTypePointer Input %106 +%414 = OpTypePointer Uniform %129 +%415 = OpConstant %17 1 +%416 = OpTypePointer Uniform %11 +%3 = OpFunction %2 None %4 +%5 = OpLabel +%14 = OpAccessChain %19 %15 %18 +%20 = OpLoad %8 %14 +%22 = OpAccessChain %25 %23 %24 +%26 = OpLoad %8 %22 +%27 = OpAccessChain %29 %23 %28 +%30 = OpLoad %8 %27 +%31 = OpExtInst %8 %1 Atan2 %26 %30 +%21 = OpFNegate %8 %31 +%32 = OpExtInst %8 %1 Cos %21 +%13 = OpFMul %8 %20 %32 +%34 = OpAccessChain %36 %15 %35 +%37 = OpLoad %8 %34 +%39 = OpAccessChain %41 %23 %40 +%42 = OpLoad %8 %39 +%43 = OpAccessChain %45 %23 %44 +%46 = OpLoad %8 %43 +%47 = OpExtInst %8 %1 Atan2 %42 %46 +%38 = OpFNegate %8 %47 +%48 = OpExtInst %8 %1 Sin %38 +%33 = OpFMul %8 %37 %48 +%12 = OpFSub %8 %13 %33 +%51 = OpAccessChain %53 %15 %52 +%54 = OpLoad %8 %51 +%56 = OpAccessChain %58 %23 %57 +%59 = OpLoad %8 %56 +%60 = OpAccessChain %62 %23 %61 +%63 = OpLoad %8 %60 +%64 = OpExtInst %8 %1 Atan2 %59 %63 +%55 = OpFNegate %8 %64 +%65 = OpExtInst %8 %1 Sin %55 +%50 = OpFMul %8 %54 %65 +%67 = OpAccessChain %69 %15 %68 +%70 = OpLoad %8 %67 +%72 = OpAccessChain %74 %23 %73 +%75 = OpLoad %8 %72 +%76 = OpAccessChain %78 %23 %77 +%79 = OpLoad %8 %76 +%80 = OpExtInst %8 %1 Atan2 %75 %79 +%71 = OpFNegate %8 %80 +%81 = OpExtInst %8 %1 Cos %71 +%66 = OpFMul %8 %70 %81 +%49 = OpFAdd %8 %50 %66 +%82 = OpCompositeConstruct %11 %12 %49 +%84 = OpLoad %11 %83 +%10 = OpFAdd %11 %82 %84 +%87 = OpCompositeConstruct %7 %10 %85 %86 +OpStore %6 %87 +OpReturn +OpFunctionEnd +%88 = OpFunction %2 None %4 +%89 = OpLabel +%91 = OpCompositeConstruct %7 %86 %86 %86 %86 +OpStore %90 %91 +OpReturn +OpFunctionEnd +%108 = OpFunction %2 None %4 +%109 = OpLabel +%104 = OpVariable %107 Function %105 +%101 = OpVariable %100 Function %99 +%96 = OpVariable %93 Function +%92 = OpVariable %93 Function +%102 = OpVariable %93 Function +%97 = OpVariable %93 Function +%94 = OpVariable %93 Function +%103 = OpVariable %93 Function +%98 = OpVariable %100 Function %99 +%95 = OpVariable %93 Function +%111 = OpAccessChain %116 %112 %115 +%117 = OpLoad %106 %111 +%110 = OpUGreaterThanEqual %119 %117 %118 +OpSelectionMerge %120 None +OpBranchConditional %110 %121 %122 +%121 = OpLabel +OpReturn +%122 = OpLabel +OpBranch %120 +%120 = OpLabel +%125 = OpAccessChain %132 %126 %131 +%133 = OpAccessChain %135 %112 %134 +%136 = OpLoad %106 %133 +%124 = OpAccessChain %137 %125 %136 +%123 = OpAccessChain %139 %124 %138 +%140 = OpLoad %11 %123 +OpStore %92 %140 +%143 = OpAccessChain %145 %126 %144 +%146 = OpAccessChain %148 %112 %147 +%149 = OpLoad %106 %146 +%142 = OpAccessChain %150 %143 %149 +%141 = OpAccessChain %152 %142 %151 +%153 = OpLoad %11 %141 +OpStore %94 %153 +%154 = OpCompositeConstruct %11 %85 %85 +OpStore %95 %154 +%155 = OpCompositeConstruct %11 %85 %85 +OpStore %96 %155 +%156 = OpCompositeConstruct %11 %85 %85 +OpStore %97 %156 +OpBranch %157 +%157 = OpLabel +OpLoopMerge %158 %160 None +OpBranch %159 +%159 = OpLabel +%162 = OpLoad %106 %104 +%161 = OpUGreaterThanEqual %119 %162 %118 +OpSelectionMerge %163 None +OpBranchConditional %161 %164 %165 +%164 = OpLabel +OpBranch %158 +%165 = OpLabel +OpBranch %163 +%163 = OpLabel +%167 = OpLoad %106 %104 +%168 = OpAccessChain %170 %112 %169 +%171 = OpLoad %106 %168 +%166 = OpIEqual %119 %167 %171 +OpSelectionMerge %172 None +OpBranchConditional %166 %173 %174 +%173 = OpLabel +OpBranch %160 +%174 = OpLabel +OpBranch %172 +%172 = OpLabel +%178 = OpAccessChain %180 %126 %179 +%181 = OpLoad %106 %104 +%177 = OpAccessChain %182 %178 %181 +%176 = OpAccessChain %184 %177 %183 +%175 = OpAccessChain %186 %176 %185 +%187 = OpLoad %8 %175 +%191 = OpAccessChain %193 %126 %192 +%194 = OpLoad %106 %104 +%190 = OpAccessChain %195 %191 %194 +%189 = OpAccessChain %197 %190 %196 +%188 = OpAccessChain %199 %189 %198 +%200 = OpLoad %8 %188 +%201 = OpCompositeConstruct %11 %187 %200 +OpStore %102 %201 +%205 = OpAccessChain %207 %126 %206 +%208 = OpLoad %106 %104 +%204 = OpAccessChain %209 %205 %208 +%203 = OpAccessChain %211 %204 %210 +%202 = OpAccessChain %213 %203 %212 +%214 = OpLoad %8 %202 +%218 = OpAccessChain %220 %126 %219 +%221 = OpLoad %106 %104 +%217 = OpAccessChain %222 %218 %221 +%216 = OpAccessChain %224 %217 %223 +%215 = OpAccessChain %226 %216 %225 +%227 = OpLoad %8 %215 +%228 = OpCompositeConstruct %11 %214 %227 +OpStore %103 %228 +%230 = OpLoad %11 %102 +%231 = OpLoad %11 %92 +%232 = OpExtInst %8 %1 Distance %230 %231 +%233 = OpAccessChain %238 %234 %237 +%239 = OpLoad %8 %233 +%229 = OpFOrdLessThan %119 %232 %239 +OpSelectionMerge %240 None +OpBranchConditional %229 %241 %242 +%241 = OpLabel +%244 = OpLoad %11 %95 +%245 = OpLoad %11 %102 +%243 = OpFAdd %11 %244 %245 +OpStore %95 %243 +%247 = OpLoad %17 %98 +%246 = OpIAdd %17 %247 %248 +OpStore %98 %246 +OpBranch %240 +%242 = OpLabel +OpBranch %240 +%240 = OpLabel +%250 = OpLoad %11 %102 +%251 = OpLoad %11 %92 +%252 = OpExtInst %8 %1 Distance %250 %251 +%253 = OpAccessChain %255 %234 %254 +%256 = OpLoad %8 %253 +%249 = OpFOrdLessThan %119 %252 %256 +OpSelectionMerge %257 None +OpBranchConditional %249 %258 %259 +%258 = OpLabel +%261 = OpLoad %11 %97 +%263 = OpLoad %11 %102 +%264 = OpLoad %11 %92 +%262 = OpFSub %11 %263 %264 +%260 = OpFSub %11 %261 %262 +OpStore %97 %260 +OpBranch %257 +%259 = OpLabel +OpBranch %257 +%257 = OpLabel +%266 = OpLoad %11 %102 +%267 = OpLoad %11 %92 +%268 = OpExtInst %8 %1 Distance %266 %267 +%269 = OpAccessChain %271 %234 %270 +%272 = OpLoad %8 %269 +%265 = OpFOrdLessThan %119 %268 %272 +OpSelectionMerge %273 None +OpBranchConditional %265 %274 %275 +%274 = OpLabel +%277 = OpLoad %11 %96 +%278 = OpLoad %11 %103 +%276 = OpFAdd %11 %277 %278 +OpStore %96 %276 +%280 = OpLoad %17 %101 +%279 = OpIAdd %17 %280 %248 +OpStore %101 %279 +OpBranch %273 +%275 = OpLabel +OpBranch %273 +%273 = OpLabel +OpBranch %160 +%160 = OpLabel +%282 = OpLoad %106 %104 +%281 = OpIAdd %106 %282 %283 +OpStore %104 %281 +OpBranch %157 +%158 = OpLabel +%285 = OpLoad %17 %98 +%284 = OpSGreaterThan %119 %285 %99 +OpSelectionMerge %286 None +OpBranchConditional %284 %287 %288 +%287 = OpLabel +%291 = OpLoad %11 %95 +%293 = OpLoad %17 %98 +%294 = OpLoad %17 %98 +%295 = OpCompositeConstruct %292 %293 %294 +%296 = OpConvertSToF %11 %295 +%290 = OpFDiv %11 %291 %296 +%297 = OpLoad %11 %92 +%289 = OpFAdd %11 %290 %297 +OpStore %95 %289 +OpBranch %286 +%288 = OpLabel +OpBranch %286 +%286 = OpLabel +%299 = OpLoad %17 %101 +%298 = OpSGreaterThan %119 %299 %99 +OpSelectionMerge %300 None +OpBranchConditional %298 %301 %302 +%301 = OpLabel +%304 = OpLoad %11 %96 +%305 = OpLoad %17 %101 +%306 = OpLoad %17 %101 +%307 = OpCompositeConstruct %292 %305 %306 +%308 = OpConvertSToF %11 %307 +%303 = OpFDiv %11 %304 %308 +OpStore %96 %303 +OpBranch %300 +%302 = OpLabel +OpBranch %300 +%300 = OpLabel +%312 = OpLoad %11 %94 +%314 = OpLoad %11 %95 +%315 = OpAccessChain %317 %234 %316 +%318 = OpLoad %8 %315 +%313 = OpVectorTimesScalar %11 %314 %318 +%311 = OpFAdd %11 %312 %313 +%320 = OpLoad %11 %97 +%321 = OpAccessChain %323 %234 %322 +%324 = OpLoad %8 %321 +%319 = OpVectorTimesScalar %11 %320 %324 +%310 = OpFAdd %11 %311 %319 +%326 = OpLoad %11 %96 +%327 = OpAccessChain %329 %234 %328 +%330 = OpLoad %8 %327 +%325 = OpVectorTimesScalar %11 %326 %330 +%309 = OpFAdd %11 %310 %325 +OpStore %94 %309 +%332 = OpLoad %11 %94 +%333 = OpExtInst %11 %1 Normalize %332 +%334 = OpLoad %11 %94 +%335 = OpExtInst %8 %1 Length %334 +%337 = OpExtInst %8 %1 FClamp %335 %85 %336 +%331 = OpVectorTimesScalar %11 %333 %337 +OpStore %94 %331 +%339 = OpLoad %11 %92 +%341 = OpLoad %11 %94 +%342 = OpAccessChain %344 %234 %343 +%345 = OpLoad %8 %342 +%340 = OpVectorTimesScalar %11 %341 %345 +%338 = OpFAdd %11 %339 %340 +OpStore %92 %338 +%347 = OpAccessChain %349 %92 %348 +%350 = OpLoad %8 %347 +%346 = OpFOrdLessThan %119 %350 %351 +OpSelectionMerge %352 None +OpBranchConditional %346 %353 %354 +%353 = OpLabel +%355 = OpAccessChain %357 %92 %356 +OpStore %355 %86 +OpBranch %352 +%354 = OpLabel +OpBranch %352 +%352 = OpLabel +%359 = OpAccessChain %361 %92 %360 +%362 = OpLoad %8 %359 +%358 = OpFOrdGreaterThan %119 %362 %86 +OpSelectionMerge %363 None +OpBranchConditional %358 %364 %365 +%364 = OpLabel +%366 = OpAccessChain %368 %92 %367 +OpStore %366 %351 +OpBranch %363 +%365 = OpLabel +OpBranch %363 +%363 = OpLabel +%370 = OpAccessChain %372 %92 %371 +%373 = OpLoad %8 %370 +%369 = OpFOrdLessThan %119 %373 %351 +OpSelectionMerge %374 None +OpBranchConditional %369 %375 %376 +%375 = OpLabel +%377 = OpAccessChain %379 %92 %378 +OpStore %377 %86 +OpBranch %374 +%376 = OpLabel +OpBranch %374 +%374 = OpLabel +%381 = OpAccessChain %383 %92 %382 +%384 = OpLoad %8 %381 +%380 = OpFOrdGreaterThan %119 %384 %86 +OpSelectionMerge %385 None +OpBranchConditional %380 %386 %387 +%386 = OpLabel +%388 = OpAccessChain %390 %92 %389 +OpStore %388 %351 +OpBranch %385 +%387 = OpLabel +OpBranch %385 +%385 = OpLabel +%393 = OpAccessChain %396 %394 %395 +%397 = OpAccessChain %399 %112 %398 +%400 = OpLoad %106 %397 +%392 = OpAccessChain %401 %393 %400 +%391 = OpAccessChain %403 %392 %402 +%404 = OpLoad %11 %92 +OpStore %391 %404 +%407 = OpAccessChain %409 %394 %408 +%410 = OpAccessChain %412 %112 %411 +%413 = OpLoad %106 %410 +%406 = OpAccessChain %414 %407 %413 +%405 = OpAccessChain %416 %406 %415 +%417 = OpLoad %11 %94 +OpStore %405 %417 +OpReturn +OpFunctionEnd diff --git a/tests/snapshots/snapshots__collatz.msl.snap b/tests/snapshots/snapshots__collatz.msl.snap index 17840e041..4b0834ace 100644 --- a/tests/snapshots/snapshots__collatz.msl.snap +++ b/tests/snapshots/snapshots__collatz.msl.snap @@ -16,9 +16,11 @@ struct PrimeIndices { }; type1 collatz_iterations( - type1 n + type1 n_base ) { + type1 n; type1 i = 0; + n = n_base; while(true) { if (n <= 1) { break; diff --git a/tests/snapshots/snapshots__collatz.spvasm.snap b/tests/snapshots/snapshots__collatz.spvasm.snap new file mode 100644 index 000000000..5f789ffe7 --- /dev/null +++ b/tests/snapshots/snapshots__collatz.spvasm.snap @@ -0,0 +1,109 @@ +--- +source: tests/snapshots.rs +expression: dis +--- +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 70 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %39 "main" %52 +OpExecutionMode %39 LocalSize 1 1 1 +OpDecorate %45 BufferBlock +OpMemberDecorate %45 0 Offset 0 +OpDecorate %46 ArrayStride 4 +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 0 +OpDecorate %52 BuiltIn GlobalInvocationId +%3 = OpTypeInt 32 0 +%4 = OpTypePointer Function %3 +%6 = OpConstant %3 0 +%9 = OpTypeFunction %3 %3 +%17 = OpConstant %3 1 +%18 = OpTypeBool +%25 = OpConstant %3 2 +%33 = OpConstant %3 3 +%38 = OpTypeVoid +%40 = OpTypeFunction %38 +%46 = OpTypeRuntimeArray %3 +%45 = OpTypeStruct %46 +%47 = OpTypePointer Uniform %45 +%44 = OpVariable %47 Uniform +%48 = OpTypeInt 32 1 +%49 = OpConstant %48 0 +%50 = OpTypePointer Uniform %46 +%53 = OpTypeVector %3 3 +%54 = OpTypePointer Input %53 +%52 = OpVariable %54 Input +%55 = OpConstant %48 0 +%56 = OpTypePointer Input %3 +%58 = OpTypePointer Uniform %3 +%62 = OpConstant %48 0 +%63 = OpTypePointer Uniform %46 +%65 = OpConstant %48 0 +%66 = OpTypePointer Input %3 +%68 = OpTypePointer Uniform %3 +%8 = OpFunction %3 None %9 +%7 = OpFunctionParameter %3 +%10 = OpLabel +%2 = OpVariable %4 Function +%5 = OpVariable %4 Function %6 +OpStore %2 %7 +OpBranch %11 +%11 = OpLabel +OpLoopMerge %12 %14 None +OpBranch %13 +%13 = OpLabel +%16 = OpLoad %3 %2 +%15 = OpULessThanEqual %18 %16 %17 +OpSelectionMerge %19 None +OpBranchConditional %15 %20 %21 +%20 = OpLabel +OpBranch %12 +%21 = OpLabel +OpBranch %19 +%19 = OpLabel +%24 = OpLoad %3 %2 +%23 = OpUMod %3 %24 %25 +%22 = OpIEqual %18 %23 %6 +OpSelectionMerge %26 None +OpBranchConditional %22 %27 %28 +%27 = OpLabel +%30 = OpLoad %3 %2 +%29 = OpUDiv %3 %30 %25 +OpStore %2 %29 +OpBranch %26 +%28 = OpLabel +%34 = OpLoad %3 %2 +%32 = OpIMul %3 %33 %34 +%31 = OpIAdd %3 %32 %17 +OpStore %2 %31 +OpBranch %26 +%26 = OpLabel +%36 = OpLoad %3 %5 +%35 = OpIAdd %3 %36 %17 +OpStore %5 %35 +OpBranch %14 +%14 = OpLabel +OpBranch %11 +%12 = OpLabel +%37 = OpLoad %3 %5 +OpReturnValue %37 +OpFunctionEnd +%39 = OpFunction %38 None %40 +%41 = OpLabel +%43 = OpAccessChain %50 %44 %49 +%51 = OpAccessChain %56 %52 %55 +%57 = OpLoad %3 %51 +%42 = OpAccessChain %58 %43 %57 +%61 = OpAccessChain %63 %44 %62 +%64 = OpAccessChain %66 %52 %65 +%67 = OpLoad %3 %64 +%60 = OpAccessChain %68 %61 %67 +%69 = OpLoad %3 %60 +%59 = OpFunctionCall %3 %8 %69 +OpStore %42 %59 +OpReturn +OpFunctionEnd From 20b9aa68358440309d311baec2a28a9595157b8e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 28 Jan 2021 02:12:18 -0500 Subject: [PATCH 0396/2212] Address clippy issues --- src/back/spv/writer.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 237020de1..47a5f4e37 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -70,7 +70,6 @@ impl Function { } fn consume(&mut self, mut block: Block, termination: Instruction) { - assert!(block.termination.is_none()); block.termination = Some(termination); self.blocks.push(block); } @@ -2077,10 +2076,11 @@ impl Writer { } } + #[allow(clippy::too_many_arguments)] fn write_block( &mut self, label_id: Word, - statements: &crate::Block, + statements: &[crate::Statement], ir_module: &crate::Module, ir_function: &crate::Function, function: &mut Function, @@ -2090,10 +2090,9 @@ impl Writer { let mut block = Block::new(label_id); for statement in statements { - assert!( - block.termination.is_none(), - "No statements are expected after block termination" - ); + if block.termination.is_some() { + unimplemented!("No statements are expected after block termination"); + } match *statement { crate::Statement::Block(ref block_statements) => { let scope_id = self.generate_id(); From 089a5597c61cb41deb470440f62a628d430d6bf1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 28 Jan 2021 10:10:17 -0500 Subject: [PATCH 0397/2212] [spv] implement the rest of binary operators --- src/back/spv/writer.rs | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 47a5f4e37..6c56d0b1b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1322,7 +1322,7 @@ impl Writer { crate::ScalarKind::Float => spirv::Op::FAdd, _ => spirv::Op::IAdd, }, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::Subtract => match *left_ty_inner { crate::TypeInner::Scalar { kind, .. } @@ -1330,7 +1330,7 @@ impl Writer { crate::ScalarKind::Float => spirv::Op::FSub, _ => spirv::Op::ISub, }, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::Multiply => { // whenever there is a vector on the right, @@ -1361,20 +1361,20 @@ impl Writer { } (Dimension::Vector, Dimension::Vector) | (Dimension::Scalar, Dimension::Scalar) => spirv::Op::IMul, - other => unreachable!("Mul {:?}", other), + other => unimplemented!("Mul {:?}", other), } } crate::BinaryOperator::Divide => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) => spirv::Op::SDiv, Some(crate::ScalarKind::Uint) => spirv::Op::UDiv, Some(crate::ScalarKind::Float) => spirv::Op::FDiv, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::Modulo => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) => spirv::Op::SMod, Some(crate::ScalarKind::Uint) => spirv::Op::UMod, Some(crate::ScalarKind::Float) => spirv::Op::FMod, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::Equal => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { @@ -1382,7 +1382,7 @@ impl Writer { } Some(crate::ScalarKind::Float) => spirv::Op::FOrdEqual, Some(crate::ScalarKind::Bool) => spirv::Op::LogicalEqual, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::NotEqual => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { @@ -1390,37 +1390,43 @@ impl Writer { } Some(crate::ScalarKind::Float) => spirv::Op::FOrdNotEqual, Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNotEqual, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::Less => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) => spirv::Op::SLessThan, Some(crate::ScalarKind::Uint) => spirv::Op::ULessThan, Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThan, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::LessEqual => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) => spirv::Op::SLessThanEqual, Some(crate::ScalarKind::Uint) => spirv::Op::ULessThanEqual, Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThanEqual, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::Greater => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThan, Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThan, Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThan, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::GreaterEqual => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThanEqual, Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThanEqual, Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThanEqual, - _ => unreachable!(), + _ => unimplemented!(), }, crate::BinaryOperator::And => spirv::Op::BitwiseAnd, - _ => { - log::error!("unimplemented {:?}", op); - return Err(Error::FeatureNotImplemented("binary operator")); - } + crate::BinaryOperator::ExclusiveOr => spirv::Op::BitwiseXor, + crate::BinaryOperator::InclusiveOr => spirv::Op::BitwiseOr, + crate::BinaryOperator::LogicalAnd => spirv::Op::LogicalAnd, + crate::BinaryOperator::LogicalOr => spirv::Op::LogicalOr, + crate::BinaryOperator::ShiftLeft => spirv::Op::ShiftLeftLogical, + crate::BinaryOperator::ShiftRight => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::ShiftRightArithmetic, + Some(crate::ScalarKind::Uint) => spirv::Op::ShiftRightLogical, + _ => unimplemented!(), + }, }; let is_comparison = match op { From 4a13ce022b666a4896ba1dbcbd82121e8b06ad3e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 28 Jan 2021 10:45:14 -0500 Subject: [PATCH 0398/2212] [spv] debug labels for types, local variables, and struct members --- src/back/spv/instructions.rs | 8 ++++++++ src/back/spv/writer.rs | 27 ++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index ec4a2935a..7984bbc3e 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -27,6 +27,14 @@ pub(super) fn instruction_name(target_id: Word, name: &str) -> Instruction { instruction } +pub(super) fn instruction_member_name(target_id: Word, member: Word, name: &str) -> Instruction { + let mut instruction = Instruction::new(Op::MemberName); + instruction.add_operand(target_id); + instruction.add_operand(member); + instruction.add_operands(helpers::string_to_words(name)); + instruction +} + // // Annotation Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 6c56d0b1b..1099df591 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -374,6 +374,13 @@ impl Writer { for (handle, variable) in ir_function.local_variables.iter() { let id = self.generate_id(); + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = variable.name { + self.debugs + .push(super::instructions::instruction_name(id, name)); + } + } + let init_word = variable .init .map(|constant| self.get_constant_id(constant, ir_module)) @@ -589,6 +596,13 @@ impl Writer { let ty = &arena[handle]; let id = self.generate_id(); + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = ty.name { + self.debugs + .push(super::instructions::instruction_name(id, name)); + } + } + let instruction = match ty.inner { crate::TypeInner::Scalar { kind, width } => { self.lookup_type @@ -714,6 +728,17 @@ impl Writer { None => layout.size, }; + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = member.name { + self.debugs + .push(super::instructions::instruction_member_name( + id, + index as u32, + name, + )); + } + } + if let crate::TypeInner::Matrix { columns, rows: _, @@ -886,7 +911,7 @@ impl Writer { if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = global_variable.name { self.debugs - .push(super::instructions::instruction_name(id, name.as_str())); + .push(super::instructions::instruction_name(id, name)); } } From 0c5db60d69c35387ccd8a2eba4b19b197ac5209a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 29 Jan 2021 13:06:46 -0500 Subject: [PATCH 0399/2212] [spv] fix depth sampler type --- src/back/spv/instructions.rs | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 7984bbc3e..8aa98e70d 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -217,19 +217,15 @@ pub(super) fn instruction_type_image( instruction.add_operand(sampled_type_id); instruction.add_operand(dim as u32); - instruction.add_operand(match image_class { - crate::ImageClass::Depth => 1, - _ => 0, - }); + let (depth, multi, sampled) = match image_class { + crate::ImageClass::Sampled { kind: _, multi } => (false, multi, true), + crate::ImageClass::Depth => (true, false, true), + crate::ImageClass::Storage(_) => (false, false, false), + }; + instruction.add_operand(depth as u32); instruction.add_operand(arrayed as u32); - instruction.add_operand(match image_class { - crate::ImageClass::Sampled { multi: true, .. } => 1, - _ => 0, - }); - instruction.add_operand(match image_class { - crate::ImageClass::Sampled { .. } => 1, - _ => 0, - }); + instruction.add_operand(multi as u32); + instruction.add_operand(sampled as u32); let format = match image_class { crate::ImageClass::Storage(format) => match format { From ea64ab0431f2d504cdaf1c67a48649cd23114ad4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 29 Jan 2021 13:05:27 -0500 Subject: [PATCH 0400/2212] Check host shared decorations in the validator --- src/arena.rs | 2 +- src/proc/validator.rs | 133 +++++++++++++++++++++++++++--------------- 2 files changed, 87 insertions(+), 48 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 460d909c2..0f673fa68 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -118,7 +118,7 @@ impl Arena { /// Returns an iterator over the items stored in this arena, returning both /// the item's handle and a reference to it. - pub fn iter(&self) -> impl Iterator, &T)> { + pub fn iter(&self) -> impl DoubleEndedIterator, &T)> { self.data.iter().enumerate().map(|(i, v)| { let position = i + 1; let index = unsafe { Index::new_unchecked(position as u32) }; diff --git a/src/proc/validator.rs b/src/proc/validator.rs index f6b1f153f..934ffabf2 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -4,11 +4,20 @@ use bit_set::BitSet; const MAX_WORKGROUP_SIZE: u32 = 0x4000; +bitflags::bitflags! { + #[repr(transparent)] + struct TypeFlags: u8 { + const INTERFACE = 1; + const HOST_SHARED = 2; + } +} + #[derive(Debug)] pub struct Validator { //Note: this is a bit tricky: some of the front-ends as well as backends // already have to use the typifier, so the work here is redundant in a way. typifier: Typifier, + type_flags: Vec, location_in_mask: BitSet, location_out_mask: BitSet, bind_group_masks: Vec, @@ -22,6 +31,10 @@ pub enum TypeError { UnresolvedBase(Handle), #[error("The constant {0:?} can not be used for an array size")] InvalidArraySizeConstant(Handle), + #[error("Array doesn't have a stride decoration, can't be host-shared")] + MissingStrideDecoration, + #[error("Structure doesn't have a block decoration, can't be host-shared")] + MissingBlockDecoration, } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -40,8 +53,6 @@ pub enum GlobalVariableError { InvalidUsage, #[error("Type isn't compatible with the storage class")] InvalidType, - #[error("Structure doesn't have a block decoration, can't be host-shared")] - MissingBlockDecoration, #[error("Interpolation is not valid")] InvalidInterpolation, #[error("Storage access {seen:?} exceed the allowed {allowed:?}")] @@ -224,22 +235,6 @@ impl crate::GlobalVariable { } } -impl crate::TypeInner { - fn check_block(&self) -> Result<(), GlobalVariableError> { - match *self { - Self::Struct { - block: true, - members: _, - } => Ok(()), - Self::Struct { - block: false, - members: _, - } => Err(GlobalVariableError::MissingBlockDecoration), - _ => Err(GlobalVariableError::InvalidType), - } - } -} - fn storage_usage(access: crate::StorageAccess) -> crate::GlobalUse { let mut storage_usage = crate::GlobalUse::empty(); if access.contains(crate::StorageAccess::LOAD) { @@ -280,6 +275,7 @@ impl Validator { pub fn new() -> Self { Validator { typifier: Typifier::new(), + type_flags: Vec::new(), location_in_mask: BitSet::new(), location_out_mask: BitSet::new(), bind_group_masks: Vec::new(), @@ -293,6 +289,29 @@ impl Validator { } } + fn fill_type_flags(&mut self, arena: &Arena) { + for (handle, ty) in arena.iter().rev() { + let flags = self.type_flags[handle.index()]; + match ty.inner { + crate::TypeInner::Array { base, .. } => { + //Note: don't assume anything about the indices, + // they are checked in `validate_type` later on. + if let Some(f) = self.type_flags.get_mut(base.index()) { + *f |= flags; + } + } + crate::TypeInner::Struct { ref members, .. } => { + for member in members { + if let Some(f) = self.type_flags.get_mut(member.ty.index()) { + *f |= flags; + } + } + } + _ => {} + } + } + } + fn validate_type( &self, ty: &crate::Type, @@ -316,7 +335,7 @@ impl Validator { return Err(TypeError::UnresolvedBase(base)); } } - Ti::Array { base, size, .. } => { + Ti::Array { base, size, stride } => { if base >= handle { return Err(TypeError::UnresolvedBase(base)); } @@ -335,12 +354,18 @@ impl Validator { } } } + //TODO: check stride + if stride.is_none() + && self.type_flags[handle.index()].contains(TypeFlags::HOST_SHARED) + { + return Err(TypeError::MissingStrideDecoration); + } } - Ti::Struct { - block: _, - ref members, - } => { - //TODO: check the offsets + Ti::Struct { block, ref members } => { + if !block && self.type_flags[handle.index()].contains(TypeFlags::HOST_SHARED) { + return Err(TypeError::MissingBlockDecoration); + } + //TODO: check the spans for member in members { if member.ty >= handle { return Err(TypeError::UnresolvedBase(member.ty)); @@ -396,42 +421,47 @@ impl Validator { &self, var: &crate::GlobalVariable, types: &Arena, - ) -> Result<(), GlobalVariableError> { + ) -> Result { log::debug!("var {:?}", var); - let allowed_storage_access = match var.class { + let (allowed_storage_access, type_flags) = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), crate::StorageClass::Input | crate::StorageClass::Output => { var.check_varying(types)?; - crate::StorageAccess::empty() + (crate::StorageAccess::empty(), TypeFlags::INTERFACE) } crate::StorageClass::Storage => { var.check_resource()?; - let ty = &types[var.ty]; - ty.inner.check_block()?; - crate::StorageAccess::all() + match types[var.ty].inner { + crate::TypeInner::Struct { .. } => (), + _ => return Err(GlobalVariableError::InvalidType), + } + (crate::StorageAccess::all(), TypeFlags::HOST_SHARED) } crate::StorageClass::Uniform => { var.check_resource()?; - let ty = &types[var.ty]; - ty.inner.check_block()?; - crate::StorageAccess::empty() + match types[var.ty].inner { + crate::TypeInner::Struct { .. } => (), + _ => return Err(GlobalVariableError::InvalidType), + } + (crate::StorageAccess::empty(), TypeFlags::HOST_SHARED) } crate::StorageClass::Handle => { var.check_resource()?; - match types[var.ty].inner { + let allowed_access = match types[var.ty].inner { crate::TypeInner::Image { class: crate::ImageClass::Storage(_), .. } => crate::StorageAccess::all(), _ => crate::StorageAccess::empty(), - } + }; + (allowed_access, TypeFlags::empty()) } crate::StorageClass::Private | crate::StorageClass::WorkGroup => { if var.binding.is_some() { return Err(GlobalVariableError::InvalidBinding); } var.forbid_interpolation()?; - crate::StorageAccess::empty() + (crate::StorageAccess::empty(), TypeFlags::empty()) } crate::StorageClass::PushConstant => { //TODO @@ -449,7 +479,7 @@ impl Validator { }); } - Ok(()) + Ok(type_flags) } fn validate_local_var( @@ -665,15 +695,9 @@ impl Validator { /// Check the given module to be valid. pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { self.typifier.clear(); - - for (handle, ty) in module.types.iter() { - self.validate_type(ty, handle, &module.constants) - .map_err(|error| ValidationError::Type { - handle, - name: ty.name.clone().unwrap_or_default(), - error, - })?; - } + self.type_flags.clear(); + self.type_flags + .resize(module.types.len(), TypeFlags::empty()); for (handle, constant) in module.constants.iter() { self.validate_constant(handle, &module.constants, &module.types) @@ -683,13 +707,28 @@ impl Validator { error, })?; } + for (var_handle, var) in module.global_variables.iter() { - self.validate_global_var(var, &module.types) + let ty_flags = self + .validate_global_var(var, &module.types) .map_err(|error| ValidationError::GlobalVariable { handle: var_handle, name: var.name.clone().unwrap_or_default(), error, })?; + self.type_flags[var.ty.index()] |= ty_flags; + } + + self.fill_type_flags(&module.types); + + // doing after the globals, so that `type_flags` is ready + for (handle, ty) in module.types.iter() { + self.validate_type(ty, handle, &module.constants) + .map_err(|error| ValidationError::Type { + handle, + name: ty.name.clone().unwrap_or_default(), + error, + })?; } for (fun_handle, fun) in module.functions.iter() { From 0c725c0837b2a9f501332168429f4c154d6ef0c9 Mon Sep 17 00:00:00 2001 From: Baptiste Manson Date: Fri, 29 Jan 2021 12:53:34 -0800 Subject: [PATCH 0401/2212] added function pow from spirv backend --- src/back/spv/writer.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 1099df591..74d715a03 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1680,6 +1680,7 @@ impl Writer { MathOp::Other(inst, result_lookup_ty) } Mf::Normalize => MathOp::Single(spirv::GLOp::Normalize), + Mf::Pow => MathOp::Double(spirv::GLOp::Pow), // computational Mf::Transpose => { let result_lookup_ty = From 3b9f517446cf88ff5795c06b728872cf1e9781b6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 29 Jan 2021 23:51:39 -0500 Subject: [PATCH 0402/2212] [mtl] implement continuing, fix Greater op and scoping --- src/back/glsl/mod.rs | 2 +- src/back/msl/writer.rs | 33 +- src/proc/namer.rs | 31 +- tests/snapshots/in/boids.wgsl | 74 +- tests/snapshots/snapshots__boids.msl.snap | 142 ++- tests/snapshots/snapshots__boids.spvasm.snap | 920 ++++++++----------- tests/snapshots/snapshots__collatz.msl.snap | 11 +- tests/snapshots/snapshots__empty.msl.snap | 1 + tests/snapshots/snapshots__quad.msl.snap | 2 +- tests/snapshots/snapshots__skybox.msl.snap | 10 +- 10 files changed, 520 insertions(+), 706 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a5fb8f27b..7668a2cc5 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -305,7 +305,7 @@ impl<'a, W: Write> Writer<'a, W> { // Generate a map with names required to write the module let mut names = FastHashMap::default(); - Namer::process(module, keywords::RESERVED_KEYWORDS, &mut names); + Namer::default().reset(module, keywords::RESERVED_KEYWORDS, &mut names); // Generate a call graph for the entry point let call_graph = CallGraphBuilder { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0ba3a5e70..c5fe73cff 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -64,6 +64,7 @@ pub struct Writer { out: W, names: FastHashMap, typifier: Typifier, + namer: Namer, } fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { @@ -113,6 +114,7 @@ impl Writer { out, names: FastHashMap::default(), typifier: Typifier::new(), + namer: Namer::default(), } } @@ -348,7 +350,7 @@ impl Writer { crate::BinaryOperator::NotEqual => "!=", crate::BinaryOperator::Less => "<", crate::BinaryOperator::LessEqual => "<=", - crate::BinaryOperator::Greater => "==", + crate::BinaryOperator::Greater => ">", crate::BinaryOperator::GreaterEqual => ">=", crate::BinaryOperator::And => "&", _ => return Err(Error::UnsupportedBinaryOp(op)), @@ -365,11 +367,11 @@ impl Writer { self.put_expression(right, context)?; write!(self.out, ")")?; } else { - //write!(self.out, "(")?; + write!(self.out, "(")?; self.put_expression(left, context)?; write!(self.out, " {} ", op_str)?; self.put_expression(right, context)?; - //write!(self.out, ")")?; + write!(self.out, ")")?; } } crate::Expression::Select { @@ -621,11 +623,19 @@ impl Writer { ref body, ref continuing, } => { - writeln!(self.out, "{}while(true) {{", level)?; - self.put_block(level.next(), body, context, return_value)?; if !continuing.is_empty() { - //TODO + let gate_name = self.namer.call("loop_init"); + writeln!(self.out, "{}bool {} = true;", level, gate_name)?; + writeln!(self.out, "{}while(true) {{", level)?; + let lif = level.next(); + writeln!(self.out, "{}if (!loop_init) {{", lif)?; + self.put_block(lif.next(), continuing, context, return_value)?; + writeln!(self.out, "{}}}", lif)?; + writeln!(self.out, "{}loop_init = false;", lif)?; + } else { + writeln!(self.out, "{}while(true) {{", level)?; } + self.put_block(level.next(), body, context, return_value)?; writeln!(self.out, "{}}}", level)?; } crate::Statement::Break => { @@ -642,9 +652,12 @@ impl Writer { writeln!(self.out, ";")?; } crate::Statement::Return { value: None } => { - if let Some(string) = return_value { - writeln!(self.out, "{}return {};", level, string)?; - } + writeln!( + self.out, + "{}return {};", + level, + return_value.unwrap_or_default(), + )?; } crate::Statement::Kill => { writeln!(self.out, "{}discard_fragment();", level)?; @@ -668,7 +681,7 @@ impl Writer { options: &Options, ) -> Result { self.names.clear(); - Namer::process(module, RESERVED, &mut self.names); + self.namer.reset(module, RESERVED, &mut self.names); writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 4e6ddf997..bc083fbd5 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -17,6 +17,7 @@ pub enum NameKey { /// This processor assigns names to all the things in a module /// that may need identifiers in a textual backend. +#[derive(Default)] pub struct Namer { unique: FastHashMap, } @@ -37,7 +38,7 @@ impl Namer { base } - fn call(&mut self, label_raw: &str) -> String { + pub fn call(&mut self, label_raw: &str) -> String { let base = Self::sanitize(label_raw); match self.unique.entry(base) { Entry::Occupied(mut e) => { @@ -59,25 +60,23 @@ impl Namer { }) } - pub fn process( + pub fn reset( + &mut self, module: &crate::Module, reserved: &[&str], output: &mut FastHashMap, ) { - let mut this = Namer { - unique: reserved - .iter() - .map(|string| (string.to_string(), 0)) - .collect(), - }; + self.unique.clear(); + self.unique + .extend(reserved.iter().map(|string| (string.to_string(), 0))); for (handle, var) in module.global_variables.iter() { - let name = this.call_or(&var.name, "global"); + let name = self.call_or(&var.name, "global"); output.insert(NameKey::GlobalVariable(handle), name); } for (ty_handle, ty) in module.types.iter() { - let ty_name = this.call_or(&ty.name, "type"); + let ty_name = self.call_or(&ty.name, "type"); output.insert(NameKey::Type(ty_handle), ty_name); if let crate::TypeInner::Struct { @@ -86,30 +85,30 @@ impl Namer { } = ty.inner { for (index, member) in members.iter().enumerate() { - let name = this.call_or(&member.name, "member"); + let name = self.call_or(&member.name, "member"); output.insert(NameKey::StructMember(ty_handle, index as u32), name); } } } for (fun_handle, fun) in module.functions.iter() { - let fun_name = this.call_or(&fun.name, "function"); + let fun_name = self.call_or(&fun.name, "function"); output.insert(NameKey::Function(fun_handle), fun_name); for (index, arg) in fun.arguments.iter().enumerate() { - let name = this.call_or(&arg.name, "param"); + let name = self.call_or(&arg.name, "param"); output.insert(NameKey::FunctionArgument(fun_handle, index as u32), name); } for (handle, var) in fun.local_variables.iter() { - let name = this.call_or(&var.name, "local"); + let name = self.call_or(&var.name, "local"); output.insert(NameKey::FunctionLocal(fun_handle, handle), name); } } for (ep_index, (&(_, ref base_name), ep)) in module.entry_points.iter().enumerate() { - let ep_name = this.call(base_name); + let ep_name = self.call(base_name); output.insert(NameKey::EntryPoint(ep_index as _), ep_name); for (handle, var) in ep.function.local_variables.iter() { - let name = this.call_or(&var.name, "local"); + let name = self.call_or(&var.name, "local"); output.insert(NameKey::EntryPointLocal(ep_index as _, handle), name); } } diff --git a/tests/snapshots/in/boids.wgsl b/tests/snapshots/in/boids.wgsl index a1594c7bd..55ba3405f 100644 --- a/tests/snapshots/in/boids.wgsl +++ b/tests/snapshots/in/boids.wgsl @@ -1,46 +1,9 @@ -// Copyright 2020 The Tint Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +const NUM_PARTICLES: u32 = 1500; -// vertex shader - -[[location(0)]] var a_particlePos : vec2; -[[location(1)]] var a_particleVel : vec2; -[[location(2)]] var a_pos : vec2; -[[builtin(position)]] var gl_Position : vec4; - -[[stage(vertex)]] -fn main() { - const angle : f32 = -atan2(a_particleVel.x, a_particleVel.y); - const pos : vec2 = vec2( - (a_pos.x * cos(angle)) - (a_pos.y * sin(angle)), - (a_pos.x * sin(angle)) + (a_pos.y * cos(angle))); - gl_Position = vec4(pos + a_particlePos, 0.0, 1.0); -} - -// fragment shader -[[location(0)]] var fragColor : vec4; - -[[stage(fragment)]] -fn main() { - fragColor = vec4(1.0, 1.0, 1.0, 1.0); -} - -// compute shader [[block]] struct Particle { - [[span(8)]] pos : vec2; - [[span(8)]] vel : vec2; + pos : vec2; + vel : vec2; }; [[block]] @@ -56,25 +19,25 @@ struct SimParams { [[block]] struct Particles { - particles : [[stride(16)]] array; + particles : [[stride(16)]] array; }; [[group(0), binding(0)]] var params : SimParams; -[[group(0), binding(1)]] var particlesA : [[access(read_write)]] Particles; -[[group(0), binding(2)]] var particlesB : [[access(read_write)]] Particles; +[[group(0), binding(1)]] var particlesSrc : [[access(read)]] Particles; +[[group(0), binding(2)]] var particlesDst : [[access(read_write)]] Particles; [[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3; // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp -[[stage(compute), workgroup_size(1)]] +[[stage(compute), workgroup_size(64)]] fn main() { const index : u32 = gl_GlobalInvocationID.x; - if (index >= 5u) { + if (index >= NUM_PARTICLES) { return; } - var vPos : vec2 = particlesA.particles[index].pos; - var vVel : vec2 = particlesA.particles[index].vel; + var vPos : vec2 = particlesSrc.particles[index].pos; + var vVel : vec2 = particlesSrc.particles[index].vel; var cMass : vec2 = vec2(0.0, 0.0); var cVel : vec2 = vec2(0.0, 0.0); @@ -86,15 +49,15 @@ fn main() { var vel : vec2; var i : u32 = 0u; loop { - if (i >= 5u) { + if (i >= NUM_PARTICLES) { break; } if (i == index) { continue; } - pos = particlesA.particles[i].pos.xy; - vel = particlesA.particles[i].vel.xy; + pos = particlesSrc.particles[i].pos; + vel = particlesSrc.particles[i].vel; if (distance(pos, vPos) < params.rule1Distance) { cMass = cMass + pos; @@ -113,13 +76,14 @@ fn main() { } } if (cMassCount > 0) { - cMass = (cMass / vec2(vec2(cMassCount, cMassCount))) + vPos; + cMass = cMass * (1.0 / f32(cMassCount)) - vPos; } if (cVelCount > 0) { - cVel = cVel / vec2(vec2(cVelCount, cVelCount)); + cVel = cVel * (1.0 / f32(cVelCount)); } - vVel = vVel + (cMass * params.rule1Scale) + (colVel * params.rule2Scale) + + vVel = vVel + (cMass * params.rule1Scale) + + (colVel * params.rule2Scale) + (cVel * params.rule3Scale); // clamp velocity for a more pleasing simulation @@ -143,6 +107,6 @@ fn main() { } // Write back - particlesB.particles[index].pos = vPos; - particlesB.particles[index].vel = vVel; + particlesDst.particles[index].pos = vPos; + particlesDst.particles[index].vel = vVel; } diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap index 0a5b99ec5..63ea2b1a7 100644 --- a/tests/snapshots/snapshots__boids.msl.snap +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -5,17 +5,17 @@ expression: msl #include #include -typedef metal::float2 type; +typedef uint type; -typedef metal::float4 type1; - -typedef float type2; +typedef metal::float2 type1; struct Particle { - type pos; - type vel; + type1 pos; + type1 vel; }; +typedef float type2; + struct SimParams { type2 deltaT; type2 rule1Distance; @@ -26,7 +26,7 @@ struct SimParams { type2 rule3Scale; }; -typedef Particle type3[5]; +typedef Particle type3[1]; struct Particles { type3 particles; @@ -34,111 +34,81 @@ struct Particles { typedef metal::uint3 type4; -typedef uint type5; +typedef int type5; -typedef int type6; - -typedef metal::int2 type7; - -struct main1Input { - type a_particlePos [[attribute(0)]]; - type a_particleVel [[attribute(1)]]; - type a_pos [[attribute(2)]]; -}; - -struct main1Output { - type1 gl_Position [[position]]; -}; - -vertex main1Output main1( - main1Input input [[stage_in]] -) { - main1Output output; - output.gl_Position = metal::float4(metal::float2(input.a_pos.x * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) - input.a_pos.y * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)), input.a_pos.x * metal::sin(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y)) + input.a_pos.y * metal::cos(-metal::atan2(input.a_particleVel.x, input.a_particleVel.y))) + input.a_particlePos, 0.0, 1.0); - return output; -} - -struct main2Input { -}; - -struct main2Output { - type1 fragColor [[color(0)]]; -}; - -fragment main2Output main2( - main2Input input [[stage_in]] -) { - main2Output output; - output.fragColor = metal::float4(1.0, 1.0, 1.0, 1.0); - return output; -} - -kernel void main3( +kernel void main1( constant SimParams& params [[buffer(0)]], - constant Particles& particlesA [[buffer(1)]], - device Particles& particlesB [[buffer(2)]], + constant Particles& particlesSrc [[buffer(1)]], + device Particles& particlesDst [[buffer(2)]], type4 gl_GlobalInvocationID [[thread_position_in_grid]] ) { - type vPos; - type vVel; - type cMass; - type cVel; - type colVel; - type6 cMassCount = 0; - type6 cVelCount = 0; - type pos1; - type vel1; - type5 i = 0; - if (gl_GlobalInvocationID.x >= 5) { + type1 vPos; + type1 vVel; + type1 cMass; + type1 cVel; + type1 colVel; + type5 cMassCount = 0; + type5 cVelCount = 0; + type1 pos1; + type1 vel1; + type i = 0; + if ((gl_GlobalInvocationID.x >= 1500)) { + return ; } - vPos = particlesA.particles[gl_GlobalInvocationID.x].pos; - vVel = particlesA.particles[gl_GlobalInvocationID.x].vel; + vPos = particlesSrc.particles[gl_GlobalInvocationID.x].pos; + vVel = particlesSrc.particles[gl_GlobalInvocationID.x].vel; cMass = metal::float2(0.0, 0.0); cVel = metal::float2(0.0, 0.0); colVel = metal::float2(0.0, 0.0); + bool loop_init = true; while(true) { - if (i >= 5) { + if (!loop_init) { + i = (i + 1); + } + loop_init = false; + if ((i >= 1500)) { break; } - if (i == gl_GlobalInvocationID.x) { + if ((i == gl_GlobalInvocationID.x)) { continue; } - pos1 = metal::float2(particlesA.particles[i].pos.x, particlesA.particles[i].pos.y); - vel1 = metal::float2(particlesA.particles[i].vel.x, particlesA.particles[i].vel.y); - if (metal::distance(pos1, vPos) < params.rule1Distance) { - cMass = cMass + pos1; - cMassCount = cMassCount + 1; + pos1 = particlesSrc.particles[i].pos; + vel1 = particlesSrc.particles[i].vel; + if ((metal::distance(pos1, vPos) < params.rule1Distance)) { + cMass = (cMass + pos1); + cMassCount = (cMassCount + 1); } - if (metal::distance(pos1, vPos) < params.rule2Distance) { - colVel = colVel - pos1 - vPos; + if ((metal::distance(pos1, vPos) < params.rule2Distance)) { + colVel = (colVel - (pos1 - vPos)); } - if (metal::distance(pos1, vPos) < params.rule3Distance) { - cVel = cVel + vel1; - cVelCount = cVelCount + 1; + if ((metal::distance(pos1, vPos) < params.rule3Distance)) { + cVel = (cVel + vel1); + cVelCount = (cVelCount + 1); } } - if (cMassCount == 0) { - cMass = cMass / static_cast(metal::int2(cMassCount, cMassCount)) + vPos; + if ((cMassCount > 0)) { + cMass = ((cMass * (1.0 / static_cast(cMassCount))) - vPos); } - if (cVelCount == 0) { - cVel = cVel / static_cast(metal::int2(cVelCount, cVelCount)); + if ((cVelCount > 0)) { + cVel = (cVel * (1.0 / static_cast(cVelCount))); } - vVel = vVel + cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale; - vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); - vPos = vPos + vVel * params.deltaT; - if (vPos.x < -1.0) { + vVel = (((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale)); + vVel = (metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1)); + vPos = (vPos + (vVel * params.deltaT)); + if ((vPos.x < -1.0)) { vPos.x = 1.0; } - if (vPos.x == 1.0) { + if ((vPos.x > 1.0)) { vPos.x = -1.0; } - if (vPos.y < -1.0) { + if ((vPos.y < -1.0)) { vPos.y = 1.0; } - if (vPos.y == 1.0) { + if ((vPos.y > 1.0)) { vPos.y = -1.0; } - particlesB.particles[gl_GlobalInvocationID.x].pos = vPos; - particlesB.particles[gl_GlobalInvocationID.x].vel = vVel; + particlesDst.particles[gl_GlobalInvocationID.x].pos = vPos; + particlesDst.particles[gl_GlobalInvocationID.x].vel = vVel; + return ; } diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap index e62898031..ece073bbe 100644 --- a/tests/snapshots/snapshots__boids.spvasm.snap +++ b/tests/snapshots/snapshots__boids.spvasm.snap @@ -5,539 +5,405 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 418 +; Bound: 298 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %3 "main" %83 %23 %15 %6 -OpEntryPoint Fragment %88 "main" %90 -OpEntryPoint GLCompute %108 "main" %112 -OpExecutionMode %88 OriginUpperLeft -OpExecutionMode %108 LocalSize 1 1 1 -OpDecorate %6 BuiltIn Position -OpDecorate %15 Location 2 -OpDecorate %23 Location 1 -OpDecorate %83 Location 0 -OpDecorate %90 Location 0 -OpDecorate %112 BuiltIn GlobalInvocationId -OpDecorate %127 BufferBlock -OpMemberDecorate %127 0 Offset 0 -OpDecorate %128 ArrayStride 16 -OpDecorate %129 Block -OpMemberDecorate %129 0 Offset 0 -OpMemberDecorate %129 1 Offset 8 -OpDecorate %126 DescriptorSet 0 -OpDecorate %126 Binding 1 -OpDecorate %235 Block -OpMemberDecorate %235 0 Offset 0 -OpMemberDecorate %235 1 Offset 4 -OpMemberDecorate %235 2 Offset 8 -OpMemberDecorate %235 3 Offset 12 -OpMemberDecorate %235 4 Offset 16 -OpMemberDecorate %235 5 Offset 20 -OpMemberDecorate %235 6 Offset 24 -OpDecorate %234 DescriptorSet 0 -OpDecorate %234 Binding 0 -OpDecorate %394 DescriptorSet 0 -OpDecorate %394 Binding 2 -%2 = OpTypeVoid -%4 = OpTypeFunction %2 -%8 = OpTypeFloat 32 -%7 = OpTypeVector %8 4 -%9 = OpTypePointer Output %7 -%6 = OpVariable %9 Output -%11 = OpTypeVector %8 2 -%16 = OpTypePointer Input %11 -%15 = OpVariable %16 Input -%17 = OpTypeInt 32 1 -%18 = OpConstant %17 0 -%19 = OpTypePointer Input %8 -%23 = OpVariable %16 Input -%24 = OpConstant %17 0 -%25 = OpTypePointer Input %8 -%28 = OpConstant %17 1 -%29 = OpTypePointer Input %8 -%35 = OpConstant %17 1 -%36 = OpTypePointer Input %8 -%40 = OpConstant %17 0 -%41 = OpTypePointer Input %8 -%44 = OpConstant %17 1 -%45 = OpTypePointer Input %8 -%52 = OpConstant %17 0 -%53 = OpTypePointer Input %8 -%57 = OpConstant %17 0 -%58 = OpTypePointer Input %8 -%61 = OpConstant %17 1 -%62 = OpTypePointer Input %8 -%68 = OpConstant %17 1 -%69 = OpTypePointer Input %8 -%73 = OpConstant %17 0 -%74 = OpTypePointer Input %8 -%77 = OpConstant %17 1 -%78 = OpTypePointer Input %8 -%83 = OpVariable %16 Input -%85 = OpConstant %8 0.0 -%86 = OpConstant %8 1.0 -%90 = OpVariable %9 Output -%93 = OpTypePointer Function %11 -%99 = OpConstant %17 0 -%100 = OpTypePointer Function %17 -%106 = OpTypeInt 32 0 -%105 = OpConstant %106 0 -%107 = OpTypePointer Function %106 -%113 = OpTypeVector %106 3 -%114 = OpTypePointer Input %113 -%112 = OpVariable %114 Input -%115 = OpConstant %17 0 -%116 = OpTypePointer Input %106 -%118 = OpConstant %106 5 -%119 = OpTypeBool -%129 = OpTypeStruct %11 %11 -%128 = OpTypeArray %129 %118 -%127 = OpTypeStruct %128 -%130 = OpTypePointer Uniform %127 -%126 = OpVariable %130 Uniform -%131 = OpConstant %17 0 -%132 = OpTypePointer Uniform %128 -%134 = OpConstant %17 0 -%135 = OpTypePointer Input %106 -%137 = OpTypePointer Uniform %129 -%138 = OpConstant %17 0 -%139 = OpTypePointer Uniform %11 -%144 = OpConstant %17 0 -%145 = OpTypePointer Uniform %128 -%147 = OpConstant %17 0 -%148 = OpTypePointer Input %106 -%150 = OpTypePointer Uniform %129 -%151 = OpConstant %17 1 -%152 = OpTypePointer Uniform %11 -%169 = OpConstant %17 0 -%170 = OpTypePointer Input %106 -%179 = OpConstant %17 0 -%180 = OpTypePointer Uniform %128 -%182 = OpTypePointer Uniform %129 -%183 = OpConstant %17 0 -%184 = OpTypePointer Uniform %11 -%185 = OpConstant %17 0 -%186 = OpTypePointer Uniform %8 -%192 = OpConstant %17 0 -%193 = OpTypePointer Uniform %128 -%195 = OpTypePointer Uniform %129 -%196 = OpConstant %17 0 -%197 = OpTypePointer Uniform %11 -%198 = OpConstant %17 1 -%199 = OpTypePointer Uniform %8 -%206 = OpConstant %17 0 -%207 = OpTypePointer Uniform %128 -%209 = OpTypePointer Uniform %129 -%210 = OpConstant %17 1 -%211 = OpTypePointer Uniform %11 -%212 = OpConstant %17 0 -%213 = OpTypePointer Uniform %8 -%219 = OpConstant %17 0 -%220 = OpTypePointer Uniform %128 -%222 = OpTypePointer Uniform %129 -%223 = OpConstant %17 1 -%224 = OpTypePointer Uniform %11 -%225 = OpConstant %17 1 -%226 = OpTypePointer Uniform %8 -%235 = OpTypeStruct %8 %8 %8 %8 %8 %8 %8 -%236 = OpTypePointer Uniform %235 -%234 = OpVariable %236 Uniform -%237 = OpConstant %17 1 -%238 = OpTypePointer Uniform %8 -%248 = OpConstant %17 1 -%254 = OpConstant %17 2 -%255 = OpTypePointer Uniform %8 -%270 = OpConstant %17 3 -%271 = OpTypePointer Uniform %8 -%283 = OpConstant %106 1 -%292 = OpTypeVector %17 2 -%316 = OpConstant %17 4 -%317 = OpTypePointer Uniform %8 -%322 = OpConstant %17 5 -%323 = OpTypePointer Uniform %8 -%328 = OpConstant %17 6 -%329 = OpTypePointer Uniform %8 -%336 = OpConstant %8 0.1 -%343 = OpConstant %17 0 -%344 = OpTypePointer Uniform %8 -%348 = OpConstant %17 0 -%349 = OpTypePointer Function %8 -%351 = OpConstant %8 -1.0 -%356 = OpConstant %17 0 -%357 = OpTypePointer Function %8 -%360 = OpConstant %17 0 -%361 = OpTypePointer Function %8 -%367 = OpConstant %17 0 -%368 = OpTypePointer Function %8 -%371 = OpConstant %17 1 -%372 = OpTypePointer Function %8 -%378 = OpConstant %17 1 -%379 = OpTypePointer Function %8 -%382 = OpConstant %17 1 -%383 = OpTypePointer Function %8 -%389 = OpConstant %17 1 -%390 = OpTypePointer Function %8 -%394 = OpVariable %130 Uniform -%395 = OpConstant %17 0 -%396 = OpTypePointer Uniform %128 -%398 = OpConstant %17 0 -%399 = OpTypePointer Input %106 -%401 = OpTypePointer Uniform %129 -%402 = OpConstant %17 0 -%403 = OpTypePointer Uniform %11 -%408 = OpConstant %17 0 -%409 = OpTypePointer Uniform %128 -%411 = OpConstant %17 0 -%412 = OpTypePointer Input %106 -%414 = OpTypePointer Uniform %129 -%415 = OpConstant %17 1 -%416 = OpTypePointer Uniform %11 -%3 = OpFunction %2 None %4 -%5 = OpLabel -%14 = OpAccessChain %19 %15 %18 -%20 = OpLoad %8 %14 -%22 = OpAccessChain %25 %23 %24 -%26 = OpLoad %8 %22 -%27 = OpAccessChain %29 %23 %28 -%30 = OpLoad %8 %27 -%31 = OpExtInst %8 %1 Atan2 %26 %30 -%21 = OpFNegate %8 %31 -%32 = OpExtInst %8 %1 Cos %21 -%13 = OpFMul %8 %20 %32 -%34 = OpAccessChain %36 %15 %35 -%37 = OpLoad %8 %34 -%39 = OpAccessChain %41 %23 %40 -%42 = OpLoad %8 %39 -%43 = OpAccessChain %45 %23 %44 -%46 = OpLoad %8 %43 -%47 = OpExtInst %8 %1 Atan2 %42 %46 -%38 = OpFNegate %8 %47 -%48 = OpExtInst %8 %1 Sin %38 -%33 = OpFMul %8 %37 %48 -%12 = OpFSub %8 %13 %33 -%51 = OpAccessChain %53 %15 %52 -%54 = OpLoad %8 %51 -%56 = OpAccessChain %58 %23 %57 -%59 = OpLoad %8 %56 -%60 = OpAccessChain %62 %23 %61 -%63 = OpLoad %8 %60 -%64 = OpExtInst %8 %1 Atan2 %59 %63 -%55 = OpFNegate %8 %64 -%65 = OpExtInst %8 %1 Sin %55 -%50 = OpFMul %8 %54 %65 -%67 = OpAccessChain %69 %15 %68 -%70 = OpLoad %8 %67 -%72 = OpAccessChain %74 %23 %73 -%75 = OpLoad %8 %72 -%76 = OpAccessChain %78 %23 %77 -%79 = OpLoad %8 %76 -%80 = OpExtInst %8 %1 Atan2 %75 %79 -%71 = OpFNegate %8 %80 -%81 = OpExtInst %8 %1 Cos %71 -%66 = OpFMul %8 %70 %81 -%49 = OpFAdd %8 %50 %66 -%82 = OpCompositeConstruct %11 %12 %49 -%84 = OpLoad %11 %83 -%10 = OpFAdd %11 %82 %84 -%87 = OpCompositeConstruct %7 %10 %85 %86 -OpStore %6 %87 +OpEntryPoint GLCompute %22 "main" %27 +OpExecutionMode %22 LocalSize 64 1 1 +OpDecorate %27 BuiltIn GlobalInvocationId +OpDecorate %42 BufferBlock +OpMemberDecorate %42 0 Offset 0 +OpDecorate %43 ArrayStride 16 +OpDecorate %44 Block +OpMemberDecorate %44 0 Offset 0 +OpMemberDecorate %44 1 Offset 8 +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 1 +OpDecorate %117 Block +OpMemberDecorate %117 0 Offset 0 +OpMemberDecorate %117 1 Offset 4 +OpMemberDecorate %117 2 Offset 8 +OpMemberDecorate %117 3 Offset 12 +OpMemberDecorate %117 4 Offset 16 +OpMemberDecorate %117 5 Offset 20 +OpMemberDecorate %117 6 Offset 24 +OpDecorate %116 DescriptorSet 0 +OpDecorate %116 Binding 0 +OpDecorate %274 DescriptorSet 0 +OpDecorate %274 Binding 2 +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 2 +%5 = OpTypePointer Function %3 +%12 = OpTypeInt 32 1 +%11 = OpConstant %12 0 +%13 = OpTypePointer Function %12 +%19 = OpTypeInt 32 0 +%18 = OpConstant %19 0 +%20 = OpTypePointer Function %19 +%21 = OpTypeVoid +%23 = OpTypeFunction %21 +%28 = OpTypeVector %19 3 +%29 = OpTypePointer Input %28 +%27 = OpVariable %29 Input +%30 = OpConstant %12 0 +%31 = OpTypePointer Input %19 +%33 = OpConstant %12 1500 +%34 = OpTypeBool +%44 = OpTypeStruct %3 %3 +%43 = OpTypeRuntimeArray %44 +%42 = OpTypeStruct %43 +%45 = OpTypePointer Uniform %42 +%41 = OpVariable %45 Uniform +%46 = OpConstant %12 0 +%47 = OpTypePointer Uniform %43 +%49 = OpConstant %12 0 +%50 = OpTypePointer Input %19 +%52 = OpTypePointer Uniform %44 +%53 = OpConstant %12 0 +%54 = OpTypePointer Uniform %3 +%59 = OpConstant %12 0 +%60 = OpTypePointer Uniform %43 +%62 = OpConstant %12 0 +%63 = OpTypePointer Input %19 +%65 = OpTypePointer Uniform %44 +%66 = OpConstant %12 1 +%67 = OpTypePointer Uniform %3 +%69 = OpConstant %4 0.0 +%85 = OpConstant %12 0 +%86 = OpTypePointer Input %19 +%94 = OpConstant %12 0 +%95 = OpTypePointer Uniform %43 +%97 = OpTypePointer Uniform %44 +%98 = OpConstant %12 0 +%99 = OpTypePointer Uniform %3 +%104 = OpConstant %12 0 +%105 = OpTypePointer Uniform %43 +%107 = OpTypePointer Uniform %44 +%108 = OpConstant %12 1 +%109 = OpTypePointer Uniform %3 +%117 = OpTypeStruct %4 %4 %4 %4 %4 %4 %4 +%118 = OpTypePointer Uniform %117 +%116 = OpVariable %118 Uniform +%119 = OpConstant %12 1 +%120 = OpTypePointer Uniform %4 +%130 = OpConstant %12 1 +%136 = OpConstant %12 2 +%137 = OpTypePointer Uniform %4 +%152 = OpConstant %12 3 +%153 = OpTypePointer Uniform %4 +%165 = OpConstant %19 1 +%175 = OpConstant %4 1.0 +%196 = OpConstant %12 4 +%197 = OpTypePointer Uniform %4 +%202 = OpConstant %12 5 +%203 = OpTypePointer Uniform %4 +%208 = OpConstant %12 6 +%209 = OpTypePointer Uniform %4 +%216 = OpConstant %4 0.1 +%223 = OpConstant %12 0 +%224 = OpTypePointer Uniform %4 +%228 = OpConstant %12 0 +%229 = OpTypePointer Function %4 +%231 = OpConstant %4 -1.0 +%236 = OpConstant %12 0 +%237 = OpTypePointer Function %4 +%240 = OpConstant %12 0 +%241 = OpTypePointer Function %4 +%247 = OpConstant %12 0 +%248 = OpTypePointer Function %4 +%251 = OpConstant %12 1 +%252 = OpTypePointer Function %4 +%258 = OpConstant %12 1 +%259 = OpTypePointer Function %4 +%262 = OpConstant %12 1 +%263 = OpTypePointer Function %4 +%269 = OpConstant %12 1 +%270 = OpTypePointer Function %4 +%274 = OpVariable %45 Uniform +%275 = OpConstant %12 0 +%276 = OpTypePointer Uniform %43 +%278 = OpConstant %12 0 +%279 = OpTypePointer Input %19 +%281 = OpTypePointer Uniform %44 +%282 = OpConstant %12 0 +%283 = OpTypePointer Uniform %3 +%288 = OpConstant %12 0 +%289 = OpTypePointer Uniform %43 +%291 = OpConstant %12 0 +%292 = OpTypePointer Input %19 +%294 = OpTypePointer Uniform %44 +%295 = OpConstant %12 1 +%296 = OpTypePointer Uniform %3 +%22 = OpFunction %21 None %23 +%24 = OpLabel +%17 = OpVariable %20 Function %18 +%14 = OpVariable %13 Function %11 +%8 = OpVariable %5 Function +%2 = OpVariable %5 Function +%15 = OpVariable %5 Function +%9 = OpVariable %5 Function +%6 = OpVariable %5 Function +%16 = OpVariable %5 Function +%10 = OpVariable %13 Function %11 +%7 = OpVariable %5 Function +%26 = OpAccessChain %31 %27 %30 +%32 = OpLoad %19 %26 +%25 = OpUGreaterThanEqual %34 %32 %33 +OpSelectionMerge %35 None +OpBranchConditional %25 %36 %37 +%36 = OpLabel OpReturn -OpFunctionEnd -%88 = OpFunction %2 None %4 +%37 = OpLabel +OpBranch %35 +%35 = OpLabel +%40 = OpAccessChain %47 %41 %46 +%48 = OpAccessChain %50 %27 %49 +%51 = OpLoad %19 %48 +%39 = OpAccessChain %52 %40 %51 +%38 = OpAccessChain %54 %39 %53 +%55 = OpLoad %3 %38 +OpStore %2 %55 +%58 = OpAccessChain %60 %41 %59 +%61 = OpAccessChain %63 %27 %62 +%64 = OpLoad %19 %61 +%57 = OpAccessChain %65 %58 %64 +%56 = OpAccessChain %67 %57 %66 +%68 = OpLoad %3 %56 +OpStore %6 %68 +%70 = OpCompositeConstruct %3 %69 %69 +OpStore %7 %70 +%71 = OpCompositeConstruct %3 %69 %69 +OpStore %8 %71 +%72 = OpCompositeConstruct %3 %69 %69 +OpStore %9 %72 +OpBranch %73 +%73 = OpLabel +OpLoopMerge %74 %76 None +OpBranch %75 +%75 = OpLabel +%78 = OpLoad %19 %17 +%77 = OpUGreaterThanEqual %34 %78 %33 +OpSelectionMerge %79 None +OpBranchConditional %77 %80 %81 +%80 = OpLabel +OpBranch %74 +%81 = OpLabel +OpBranch %79 +%79 = OpLabel +%83 = OpLoad %19 %17 +%84 = OpAccessChain %86 %27 %85 +%87 = OpLoad %19 %84 +%82 = OpIEqual %34 %83 %87 +OpSelectionMerge %88 None +OpBranchConditional %82 %89 %90 %89 = OpLabel -%91 = OpCompositeConstruct %7 %86 %86 %86 %86 -OpStore %90 %91 -OpReturn -OpFunctionEnd -%108 = OpFunction %2 None %4 -%109 = OpLabel -%104 = OpVariable %107 Function %105 -%101 = OpVariable %100 Function %99 -%96 = OpVariable %93 Function -%92 = OpVariable %93 Function -%102 = OpVariable %93 Function -%97 = OpVariable %93 Function -%94 = OpVariable %93 Function -%103 = OpVariable %93 Function -%98 = OpVariable %100 Function %99 -%95 = OpVariable %93 Function -%111 = OpAccessChain %116 %112 %115 -%117 = OpLoad %106 %111 -%110 = OpUGreaterThanEqual %119 %117 %118 -OpSelectionMerge %120 None -OpBranchConditional %110 %121 %122 -%121 = OpLabel -OpReturn +OpBranch %76 +%90 = OpLabel +OpBranch %88 +%88 = OpLabel +%93 = OpAccessChain %95 %41 %94 +%96 = OpLoad %19 %17 +%92 = OpAccessChain %97 %93 %96 +%91 = OpAccessChain %99 %92 %98 +%100 = OpLoad %3 %91 +OpStore %15 %100 +%103 = OpAccessChain %105 %41 %104 +%106 = OpLoad %19 %17 +%102 = OpAccessChain %107 %103 %106 +%101 = OpAccessChain %109 %102 %108 +%110 = OpLoad %3 %101 +OpStore %16 %110 +%112 = OpLoad %3 %15 +%113 = OpLoad %3 %2 +%114 = OpExtInst %4 %1 Distance %112 %113 +%115 = OpAccessChain %120 %116 %119 +%121 = OpLoad %4 %115 +%111 = OpFOrdLessThan %34 %114 %121 +OpSelectionMerge %122 None +OpBranchConditional %111 %123 %124 +%123 = OpLabel +%126 = OpLoad %3 %7 +%127 = OpLoad %3 %15 +%125 = OpFAdd %3 %126 %127 +OpStore %7 %125 +%129 = OpLoad %12 %10 +%128 = OpIAdd %12 %129 %130 +OpStore %10 %128 +OpBranch %122 +%124 = OpLabel +OpBranch %122 %122 = OpLabel -OpBranch %120 -%120 = OpLabel -%125 = OpAccessChain %132 %126 %131 -%133 = OpAccessChain %135 %112 %134 -%136 = OpLoad %106 %133 -%124 = OpAccessChain %137 %125 %136 -%123 = OpAccessChain %139 %124 %138 -%140 = OpLoad %11 %123 -OpStore %92 %140 -%143 = OpAccessChain %145 %126 %144 -%146 = OpAccessChain %148 %112 %147 -%149 = OpLoad %106 %146 -%142 = OpAccessChain %150 %143 %149 -%141 = OpAccessChain %152 %142 %151 -%153 = OpLoad %11 %141 -OpStore %94 %153 -%154 = OpCompositeConstruct %11 %85 %85 -OpStore %95 %154 -%155 = OpCompositeConstruct %11 %85 %85 -OpStore %96 %155 -%156 = OpCompositeConstruct %11 %85 %85 -OpStore %97 %156 -OpBranch %157 +%132 = OpLoad %3 %15 +%133 = OpLoad %3 %2 +%134 = OpExtInst %4 %1 Distance %132 %133 +%135 = OpAccessChain %137 %116 %136 +%138 = OpLoad %4 %135 +%131 = OpFOrdLessThan %34 %134 %138 +OpSelectionMerge %139 None +OpBranchConditional %131 %140 %141 +%140 = OpLabel +%143 = OpLoad %3 %9 +%145 = OpLoad %3 %15 +%146 = OpLoad %3 %2 +%144 = OpFSub %3 %145 %146 +%142 = OpFSub %3 %143 %144 +OpStore %9 %142 +OpBranch %139 +%141 = OpLabel +OpBranch %139 +%139 = OpLabel +%148 = OpLoad %3 %15 +%149 = OpLoad %3 %2 +%150 = OpExtInst %4 %1 Distance %148 %149 +%151 = OpAccessChain %153 %116 %152 +%154 = OpLoad %4 %151 +%147 = OpFOrdLessThan %34 %150 %154 +OpSelectionMerge %155 None +OpBranchConditional %147 %156 %157 +%156 = OpLabel +%159 = OpLoad %3 %8 +%160 = OpLoad %3 %16 +%158 = OpFAdd %3 %159 %160 +OpStore %8 %158 +%162 = OpLoad %12 %14 +%161 = OpIAdd %12 %162 %130 +OpStore %14 %161 +OpBranch %155 %157 = OpLabel -OpLoopMerge %158 %160 None -OpBranch %159 -%159 = OpLabel -%162 = OpLoad %106 %104 -%161 = OpUGreaterThanEqual %119 %162 %118 -OpSelectionMerge %163 None -OpBranchConditional %161 %164 %165 -%164 = OpLabel -OpBranch %158 -%165 = OpLabel -OpBranch %163 -%163 = OpLabel -%167 = OpLoad %106 %104 -%168 = OpAccessChain %170 %112 %169 -%171 = OpLoad %106 %168 -%166 = OpIEqual %119 %167 %171 -OpSelectionMerge %172 None -OpBranchConditional %166 %173 %174 -%173 = OpLabel -OpBranch %160 -%174 = OpLabel -OpBranch %172 -%172 = OpLabel -%178 = OpAccessChain %180 %126 %179 -%181 = OpLoad %106 %104 -%177 = OpAccessChain %182 %178 %181 -%176 = OpAccessChain %184 %177 %183 -%175 = OpAccessChain %186 %176 %185 -%187 = OpLoad %8 %175 -%191 = OpAccessChain %193 %126 %192 -%194 = OpLoad %106 %104 -%190 = OpAccessChain %195 %191 %194 -%189 = OpAccessChain %197 %190 %196 -%188 = OpAccessChain %199 %189 %198 -%200 = OpLoad %8 %188 -%201 = OpCompositeConstruct %11 %187 %200 -OpStore %102 %201 -%205 = OpAccessChain %207 %126 %206 -%208 = OpLoad %106 %104 -%204 = OpAccessChain %209 %205 %208 -%203 = OpAccessChain %211 %204 %210 -%202 = OpAccessChain %213 %203 %212 -%214 = OpLoad %8 %202 -%218 = OpAccessChain %220 %126 %219 -%221 = OpLoad %106 %104 -%217 = OpAccessChain %222 %218 %221 -%216 = OpAccessChain %224 %217 %223 -%215 = OpAccessChain %226 %216 %225 -%227 = OpLoad %8 %215 -%228 = OpCompositeConstruct %11 %214 %227 -OpStore %103 %228 -%230 = OpLoad %11 %102 -%231 = OpLoad %11 %92 -%232 = OpExtInst %8 %1 Distance %230 %231 -%233 = OpAccessChain %238 %234 %237 -%239 = OpLoad %8 %233 -%229 = OpFOrdLessThan %119 %232 %239 -OpSelectionMerge %240 None -OpBranchConditional %229 %241 %242 -%241 = OpLabel -%244 = OpLoad %11 %95 -%245 = OpLoad %11 %102 -%243 = OpFAdd %11 %244 %245 -OpStore %95 %243 -%247 = OpLoad %17 %98 -%246 = OpIAdd %17 %247 %248 -OpStore %98 %246 -OpBranch %240 -%242 = OpLabel -OpBranch %240 -%240 = OpLabel -%250 = OpLoad %11 %102 -%251 = OpLoad %11 %92 -%252 = OpExtInst %8 %1 Distance %250 %251 -%253 = OpAccessChain %255 %234 %254 -%256 = OpLoad %8 %253 -%249 = OpFOrdLessThan %119 %252 %256 -OpSelectionMerge %257 None -OpBranchConditional %249 %258 %259 -%258 = OpLabel -%261 = OpLoad %11 %97 -%263 = OpLoad %11 %102 -%264 = OpLoad %11 %92 -%262 = OpFSub %11 %263 %264 -%260 = OpFSub %11 %261 %262 -OpStore %97 %260 -OpBranch %257 -%259 = OpLabel -OpBranch %257 -%257 = OpLabel -%266 = OpLoad %11 %102 -%267 = OpLoad %11 %92 -%268 = OpExtInst %8 %1 Distance %266 %267 -%269 = OpAccessChain %271 %234 %270 -%272 = OpLoad %8 %269 -%265 = OpFOrdLessThan %119 %268 %272 -OpSelectionMerge %273 None -OpBranchConditional %265 %274 %275 -%274 = OpLabel -%277 = OpLoad %11 %96 -%278 = OpLoad %11 %103 -%276 = OpFAdd %11 %277 %278 -OpStore %96 %276 -%280 = OpLoad %17 %101 -%279 = OpIAdd %17 %280 %248 -OpStore %101 %279 -OpBranch %273 -%275 = OpLabel -OpBranch %273 -%273 = OpLabel -OpBranch %160 -%160 = OpLabel -%282 = OpLoad %106 %104 -%281 = OpIAdd %106 %282 %283 -OpStore %104 %281 -OpBranch %157 -%158 = OpLabel -%285 = OpLoad %17 %98 -%284 = OpSGreaterThan %119 %285 %99 -OpSelectionMerge %286 None -OpBranchConditional %284 %287 %288 -%287 = OpLabel -%291 = OpLoad %11 %95 -%293 = OpLoad %17 %98 -%294 = OpLoad %17 %98 -%295 = OpCompositeConstruct %292 %293 %294 -%296 = OpConvertSToF %11 %295 -%290 = OpFDiv %11 %291 %296 -%297 = OpLoad %11 %92 -%289 = OpFAdd %11 %290 %297 -OpStore %95 %289 -OpBranch %286 -%288 = OpLabel -OpBranch %286 -%286 = OpLabel -%299 = OpLoad %17 %101 -%298 = OpSGreaterThan %119 %299 %99 -OpSelectionMerge %300 None -OpBranchConditional %298 %301 %302 -%301 = OpLabel -%304 = OpLoad %11 %96 -%305 = OpLoad %17 %101 -%306 = OpLoad %17 %101 -%307 = OpCompositeConstruct %292 %305 %306 -%308 = OpConvertSToF %11 %307 -%303 = OpFDiv %11 %304 %308 -OpStore %96 %303 -OpBranch %300 -%302 = OpLabel -OpBranch %300 -%300 = OpLabel -%312 = OpLoad %11 %94 -%314 = OpLoad %11 %95 -%315 = OpAccessChain %317 %234 %316 -%318 = OpLoad %8 %315 -%313 = OpVectorTimesScalar %11 %314 %318 -%311 = OpFAdd %11 %312 %313 -%320 = OpLoad %11 %97 -%321 = OpAccessChain %323 %234 %322 -%324 = OpLoad %8 %321 -%319 = OpVectorTimesScalar %11 %320 %324 -%310 = OpFAdd %11 %311 %319 -%326 = OpLoad %11 %96 -%327 = OpAccessChain %329 %234 %328 -%330 = OpLoad %8 %327 -%325 = OpVectorTimesScalar %11 %326 %330 -%309 = OpFAdd %11 %310 %325 -OpStore %94 %309 -%332 = OpLoad %11 %94 -%333 = OpExtInst %11 %1 Normalize %332 -%334 = OpLoad %11 %94 -%335 = OpExtInst %8 %1 Length %334 -%337 = OpExtInst %8 %1 FClamp %335 %85 %336 -%331 = OpVectorTimesScalar %11 %333 %337 -OpStore %94 %331 -%339 = OpLoad %11 %92 -%341 = OpLoad %11 %94 -%342 = OpAccessChain %344 %234 %343 -%345 = OpLoad %8 %342 -%340 = OpVectorTimesScalar %11 %341 %345 -%338 = OpFAdd %11 %339 %340 -OpStore %92 %338 -%347 = OpAccessChain %349 %92 %348 -%350 = OpLoad %8 %347 -%346 = OpFOrdLessThan %119 %350 %351 -OpSelectionMerge %352 None -OpBranchConditional %346 %353 %354 -%353 = OpLabel -%355 = OpAccessChain %357 %92 %356 -OpStore %355 %86 -OpBranch %352 -%354 = OpLabel -OpBranch %352 -%352 = OpLabel -%359 = OpAccessChain %361 %92 %360 -%362 = OpLoad %8 %359 -%358 = OpFOrdGreaterThan %119 %362 %86 -OpSelectionMerge %363 None -OpBranchConditional %358 %364 %365 -%364 = OpLabel -%366 = OpAccessChain %368 %92 %367 -OpStore %366 %351 -OpBranch %363 -%365 = OpLabel -OpBranch %363 -%363 = OpLabel -%370 = OpAccessChain %372 %92 %371 -%373 = OpLoad %8 %370 -%369 = OpFOrdLessThan %119 %373 %351 -OpSelectionMerge %374 None -OpBranchConditional %369 %375 %376 -%375 = OpLabel -%377 = OpAccessChain %379 %92 %378 -OpStore %377 %86 -OpBranch %374 -%376 = OpLabel -OpBranch %374 -%374 = OpLabel -%381 = OpAccessChain %383 %92 %382 -%384 = OpLoad %8 %381 -%380 = OpFOrdGreaterThan %119 %384 %86 -OpSelectionMerge %385 None -OpBranchConditional %380 %386 %387 -%386 = OpLabel -%388 = OpAccessChain %390 %92 %389 -OpStore %388 %351 -OpBranch %385 -%387 = OpLabel -OpBranch %385 -%385 = OpLabel -%393 = OpAccessChain %396 %394 %395 -%397 = OpAccessChain %399 %112 %398 -%400 = OpLoad %106 %397 -%392 = OpAccessChain %401 %393 %400 -%391 = OpAccessChain %403 %392 %402 -%404 = OpLoad %11 %92 -OpStore %391 %404 -%407 = OpAccessChain %409 %394 %408 -%410 = OpAccessChain %412 %112 %411 -%413 = OpLoad %106 %410 -%406 = OpAccessChain %414 %407 %413 -%405 = OpAccessChain %416 %406 %415 -%417 = OpLoad %11 %94 -OpStore %405 %417 +OpBranch %155 +%155 = OpLabel +OpBranch %76 +%76 = OpLabel +%164 = OpLoad %19 %17 +%163 = OpIAdd %19 %164 %165 +OpStore %17 %163 +OpBranch %73 +%74 = OpLabel +%167 = OpLoad %12 %10 +%166 = OpSGreaterThan %34 %167 %11 +OpSelectionMerge %168 None +OpBranchConditional %166 %169 %170 +%169 = OpLabel +%173 = OpLoad %3 %7 +%176 = OpLoad %12 %10 +%177 = OpConvertSToF %4 %176 +%174 = OpFDiv %4 %175 %177 +%172 = OpVectorTimesScalar %3 %173 %174 +%178 = OpLoad %3 %2 +%171 = OpFSub %3 %172 %178 +OpStore %7 %171 +OpBranch %168 +%170 = OpLabel +OpBranch %168 +%168 = OpLabel +%180 = OpLoad %12 %14 +%179 = OpSGreaterThan %34 %180 %11 +OpSelectionMerge %181 None +OpBranchConditional %179 %182 %183 +%182 = OpLabel +%185 = OpLoad %3 %8 +%187 = OpLoad %12 %14 +%188 = OpConvertSToF %4 %187 +%186 = OpFDiv %4 %175 %188 +%184 = OpVectorTimesScalar %3 %185 %186 +OpStore %8 %184 +OpBranch %181 +%183 = OpLabel +OpBranch %181 +%181 = OpLabel +%192 = OpLoad %3 %6 +%194 = OpLoad %3 %7 +%195 = OpAccessChain %197 %116 %196 +%198 = OpLoad %4 %195 +%193 = OpVectorTimesScalar %3 %194 %198 +%191 = OpFAdd %3 %192 %193 +%200 = OpLoad %3 %9 +%201 = OpAccessChain %203 %116 %202 +%204 = OpLoad %4 %201 +%199 = OpVectorTimesScalar %3 %200 %204 +%190 = OpFAdd %3 %191 %199 +%206 = OpLoad %3 %8 +%207 = OpAccessChain %209 %116 %208 +%210 = OpLoad %4 %207 +%205 = OpVectorTimesScalar %3 %206 %210 +%189 = OpFAdd %3 %190 %205 +OpStore %6 %189 +%212 = OpLoad %3 %6 +%213 = OpExtInst %3 %1 Normalize %212 +%214 = OpLoad %3 %6 +%215 = OpExtInst %4 %1 Length %214 +%217 = OpExtInst %4 %1 FClamp %215 %69 %216 +%211 = OpVectorTimesScalar %3 %213 %217 +OpStore %6 %211 +%219 = OpLoad %3 %2 +%221 = OpLoad %3 %6 +%222 = OpAccessChain %224 %116 %223 +%225 = OpLoad %4 %222 +%220 = OpVectorTimesScalar %3 %221 %225 +%218 = OpFAdd %3 %219 %220 +OpStore %2 %218 +%227 = OpAccessChain %229 %2 %228 +%230 = OpLoad %4 %227 +%226 = OpFOrdLessThan %34 %230 %231 +OpSelectionMerge %232 None +OpBranchConditional %226 %233 %234 +%233 = OpLabel +%235 = OpAccessChain %237 %2 %236 +OpStore %235 %175 +OpBranch %232 +%234 = OpLabel +OpBranch %232 +%232 = OpLabel +%239 = OpAccessChain %241 %2 %240 +%242 = OpLoad %4 %239 +%238 = OpFOrdGreaterThan %34 %242 %175 +OpSelectionMerge %243 None +OpBranchConditional %238 %244 %245 +%244 = OpLabel +%246 = OpAccessChain %248 %2 %247 +OpStore %246 %231 +OpBranch %243 +%245 = OpLabel +OpBranch %243 +%243 = OpLabel +%250 = OpAccessChain %252 %2 %251 +%253 = OpLoad %4 %250 +%249 = OpFOrdLessThan %34 %253 %231 +OpSelectionMerge %254 None +OpBranchConditional %249 %255 %256 +%255 = OpLabel +%257 = OpAccessChain %259 %2 %258 +OpStore %257 %175 +OpBranch %254 +%256 = OpLabel +OpBranch %254 +%254 = OpLabel +%261 = OpAccessChain %263 %2 %262 +%264 = OpLoad %4 %261 +%260 = OpFOrdGreaterThan %34 %264 %175 +OpSelectionMerge %265 None +OpBranchConditional %260 %266 %267 +%266 = OpLabel +%268 = OpAccessChain %270 %2 %269 +OpStore %268 %231 +OpBranch %265 +%267 = OpLabel +OpBranch %265 +%265 = OpLabel +%273 = OpAccessChain %276 %274 %275 +%277 = OpAccessChain %279 %27 %278 +%280 = OpLoad %19 %277 +%272 = OpAccessChain %281 %273 %280 +%271 = OpAccessChain %283 %272 %282 +%284 = OpLoad %3 %2 +OpStore %271 %284 +%287 = OpAccessChain %289 %274 %288 +%290 = OpAccessChain %292 %27 %291 +%293 = OpLoad %19 %290 +%286 = OpAccessChain %294 %287 %293 +%285 = OpAccessChain %296 %286 %295 +%297 = OpLoad %3 %6 +OpStore %285 %297 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__collatz.msl.snap b/tests/snapshots/snapshots__collatz.msl.snap index 4b0834ace..351441a3a 100644 --- a/tests/snapshots/snapshots__collatz.msl.snap +++ b/tests/snapshots/snapshots__collatz.msl.snap @@ -22,15 +22,15 @@ type1 collatz_iterations( type1 i = 0; n = n_base; while(true) { - if (n <= 1) { + if ((n <= 1)) { break; } - if (n % 2 == 0) { - n = n / 2; + if (((n % 2) == 0)) { + n = (n / 2); } else { - n = 3 * n + 1; + n = ((3 * n) + 1); } - i = i + 1; + i = (i + 1); } return i; } @@ -40,5 +40,6 @@ kernel void main1( device PrimeIndices& v_indices [[buffer(0)]] ) { v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); + return ; } diff --git a/tests/snapshots/snapshots__empty.msl.snap b/tests/snapshots/snapshots__empty.msl.snap index 986df64c1..1372996b8 100644 --- a/tests/snapshots/snapshots__empty.msl.snap +++ b/tests/snapshots/snapshots__empty.msl.snap @@ -7,5 +7,6 @@ expression: msl kernel void main1( ) { + return ; } diff --git a/tests/snapshots/snapshots__quad.msl.snap b/tests/snapshots/snapshots__quad.msl.snap index 56d73255d..7ad0b4dd1 100644 --- a/tests/snapshots/snapshots__quad.msl.snap +++ b/tests/snapshots/snapshots__quad.msl.snap @@ -32,7 +32,7 @@ vertex main1Output main1( ) { main1Output output; output.v_uv = input.a_uv; - output.o_position = metal::float4(1.2 * input.a_pos, 0.0, 1.0); + output.o_position = metal::float4((1.2 * input.a_pos), 0.0, 1.0); return output; } diff --git a/tests/snapshots/snapshots__skybox.msl.snap b/tests/snapshots/snapshots__skybox.msl.snap index ed0e4a72d..d8b5e725b 100644 --- a/tests/snapshots/snapshots__skybox.msl.snap +++ b/tests/snapshots/snapshots__skybox.msl.snap @@ -47,11 +47,11 @@ vertex vs_mainOutput vs_main( type4 tmp1_; type4 tmp2_; type unprojected; - tmp1_ = static_cast(in_vertex_index) / 2; - tmp2_ = static_cast(in_vertex_index) & 1; - unprojected = r_data.proj_inv * metal::float4(static_cast(tmp1_) * 4.0 - 1.0, static_cast(tmp2_) * 4.0 - 1.0, 0.0, 1.0); - output.out_uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z); - output.out_position = metal::float4(static_cast(tmp1_) * 4.0 - 1.0, static_cast(tmp2_) * 4.0 - 1.0, 0.0, 1.0); + tmp1_ = (static_cast(in_vertex_index) / 2); + tmp2_ = (static_cast(in_vertex_index) & 1); + unprojected = (r_data.proj_inv * metal::float4(((static_cast(tmp1_) * 4.0) - 1.0), ((static_cast(tmp2_) * 4.0) - 1.0), 0.0, 1.0)); + output.out_uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z)); + output.out_position = metal::float4(((static_cast(tmp1_) * 4.0) - 1.0), ((static_cast(tmp2_) * 4.0) - 1.0), 0.0, 1.0); return output; } From 0bbeec7d55af004a7da86117961efecff5a0d5f3 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 30 Jan 2021 00:11:23 -0500 Subject: [PATCH 0403/2212] Add shadow snapshot shader --- tests/snapshots.rs | 6 + tests/snapshots/in/shadow.param.ron | 10 + tests/snapshots/in/shadow.wgsl | 69 +++++ tests/snapshots/snapshots__boids.msl.snap | 4 +- tests/snapshots/snapshots__collatz.msl.snap | 12 +- tests/snapshots/snapshots__shadow.msl.snap | 87 ++++++ tests/snapshots/snapshots__shadow.spvasm.snap | 273 ++++++++++++++++++ 7 files changed, 453 insertions(+), 8 deletions(-) create mode 100644 tests/snapshots/in/shadow.param.ron create mode 100644 tests/snapshots/in/shadow.wgsl create mode 100644 tests/snapshots/snapshots__shadow.msl.snap create mode 100644 tests/snapshots/snapshots__shadow.spvasm.snap diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1ab096343..b366c5fc5 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -182,3 +182,9 @@ fn convert_wgsl_skybox() { fn convert_wgsl_collatz() { convert_wgsl("collatz", Language::METAL | Language::SPIRV); } + +#[cfg(feature = "wgsl-in")] +#[test] +fn convert_wgsl_shadow() { + convert_wgsl("shadow", Language::METAL | Language::SPIRV); +} diff --git a/tests/snapshots/in/shadow.param.ron b/tests/snapshots/in/shadow.param.ron new file mode 100644 index 000000000..760b8595d --- /dev/null +++ b/tests/snapshots/in/shadow.param.ron @@ -0,0 +1,10 @@ +( + spv_flow_dump_prefix: "", + spv_capabilities: [ Shader ], + mtl_bindings: { + (stage: Fragment, group: 0, binding: 0): (buffer: Some(0), mutable: false), + (stage: Fragment, group: 0, binding: 1): (buffer: Some(1), mutable: false), + (stage: Fragment, group: 0, binding: 2): (texture: Some(0), mutable: false), + (stage: Fragment, group: 0, binding: 3): (sampler: Some(0), mutable: false), + } +) diff --git a/tests/snapshots/in/shadow.wgsl b/tests/snapshots/in/shadow.wgsl new file mode 100644 index 000000000..4521aace8 --- /dev/null +++ b/tests/snapshots/in/shadow.wgsl @@ -0,0 +1,69 @@ +[[block]] +struct Globals { + num_lights: vec4; +}; + +[[group(0), binding(0)]] +var u_globals: Globals; + +[[block]] +struct Light { + proj: mat4x4; + pos: vec4; + color: vec4; +}; + +[[block]] +struct Lights { + data: [[stride(96)]] array; +}; + +[[group(0), binding(1)]] +var s_lights: [[access(read)]] Lights; +[[group(0), binding(2)]] +var t_shadow: texture_depth_2d_array; +[[group(0), binding(3)]] +var sampler_shadow: sampler; + +fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { + if (homogeneous_coords.w <= 0.0) { + return 1.0; + } + const flip_correction: vec2 = vec2(0.5, -0.5); + const proj_correction: f32 = 1.0 / homogeneous_coords.w; + const light_local: vec2 = homogeneous_coords.xy * flip_correction * proj_correction + vec2(0.5, 0.5); + return textureSampleCompare(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z * proj_correction); +} + +[[location(0)]] +var in_normal_fs: vec3; +[[location(1)]] +var in_position_fs: vec4; +[[location(0)]] +var out_color_fs: vec4; + +const c_ambient: vec3 = vec3(0.05, 0.05, 0.05); +const c_max_lights: u32 = 10u; + +[[stage(fragment)]] +fn fs_main() { + const normal: vec3 = normalize(in_normal_fs); + // accumulate color + var color: vec3 = c_ambient; + var i: u32 = 0u; + loop { + if (i >= min(u_globals.num_lights.x, c_max_lights)) { + break; + } + const light: Light = s_lights.data[i]; + const shadow: f32 = fetch_shadow(i, light.proj * in_position_fs); + const light_dir: vec3 = normalize(light.pos.xyz - in_position_fs.xyz); + const diffuse: f32 = max(0.0, dot(normal, light_dir)); + color = color + shadow * diffuse * light.color.xyz; + continuing { + i = i + 1u; + } + } + // multiply the light by material color + out_color_fs = vec4(color, 1.0); +} diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap index 63ea2b1a7..4cc30a553 100644 --- a/tests/snapshots/snapshots__boids.msl.snap +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -51,7 +51,7 @@ kernel void main1( type5 cVelCount = 0; type1 pos1; type1 vel1; - type i = 0; + type i = 0u; if ((gl_GlobalInvocationID.x >= 1500)) { return ; } @@ -63,7 +63,7 @@ kernel void main1( bool loop_init = true; while(true) { if (!loop_init) { - i = (i + 1); + i = (i + 1u); } loop_init = false; if ((i >= 1500)) { diff --git a/tests/snapshots/snapshots__collatz.msl.snap b/tests/snapshots/snapshots__collatz.msl.snap index 351441a3a..10912b0ef 100644 --- a/tests/snapshots/snapshots__collatz.msl.snap +++ b/tests/snapshots/snapshots__collatz.msl.snap @@ -19,18 +19,18 @@ type1 collatz_iterations( type1 n_base ) { type1 n; - type1 i = 0; + type1 i = 0u; n = n_base; while(true) { - if ((n <= 1)) { + if ((n <= 1u)) { break; } - if (((n % 2) == 0)) { - n = (n / 2); + if (((n % 2u) == 0u)) { + n = (n / 2u); } else { - n = ((3 * n) + 1); + n = ((3u * n) + 1u); } - i = (i + 1); + i = (i + 1u); } return i; } diff --git a/tests/snapshots/snapshots__shadow.msl.snap b/tests/snapshots/snapshots__shadow.msl.snap new file mode 100644 index 000000000..0c13f8cfc --- /dev/null +++ b/tests/snapshots/snapshots__shadow.msl.snap @@ -0,0 +1,87 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +typedef metal::uint4 type; + +struct Globals { + type num_lights; +}; + +typedef metal::float4x4 type1; + +typedef metal::float4 type2; + +struct Light { + type1 proj; + type2 pos; + type2 color; +}; + +typedef Light type3[1]; + +struct Lights { + type3 data; +}; + +typedef metal::depth2d_array type4; + +typedef metal::sampler type5; + +typedef uint type6; + +typedef float type7; + +typedef metal::float2 type8; + +typedef metal::int2 type9; + +typedef int type10; + +typedef metal::float3 type11; + +type7 fetch_shadow( + type6 light_id, + type2 homogeneous_coords +) { + if ((homogeneous_coords.w <= 0.0)) { + return 1.0; + } + return t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) * (1.0 / homogeneous_coords.w)) + metal::float2(0.5, 0.5)), static_cast(light_id), (homogeneous_coords.z * (1.0 / homogeneous_coords.w))); +} + +struct fs_mainInput { + type11 in_normal_fs [[user(loc0)]]; + type2 in_position_fs [[user(loc1)]]; +}; + +struct fs_mainOutput { + type2 out_color_fs [[color(0)]]; +}; + +fragment fs_mainOutput fs_main( + fs_mainInput input [[stage_in]], + constant Globals& u_globals [[buffer(0)]], + constant Lights& s_lights [[buffer(1)]] +) { + fs_mainOutput output; + type11 color1 = type11(0.05, 0.05, 0.05); + type6 i = 0u; + bool loop_init = true; + while(true) { + if (!loop_init) { + i = (i + 1u); + } + loop_init = false; + if ((i >= metal::min(u_globals.num_lights.x, 10u))) { + break; + } + color1 = (color1 + ((fetch_shadow(i, (s_lights.data[i].proj * input.in_position_fs)) * metal::max(0.0, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(s_lights.data[i].pos.x, s_lights.data[i].pos.y, s_lights.data[i].pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(s_lights.data[i].color.x, s_lights.data[i].color.y, s_lights.data[i].color.z))); + } + output.out_color_fs = metal::float4(color1, 1.0); + return output; +} + diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap new file mode 100644 index 000000000..203e43e54 --- /dev/null +++ b/tests/snapshots/snapshots__shadow.spvasm.snap @@ -0,0 +1,273 @@ +--- +source: tests/snapshots.rs +expression: dis +--- +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 220 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %60 "fs_main" %112 %109 %216 +OpExecutionMode %60 OriginUpperLeft +OpDecorate %18 DescriptorSet 0 +OpDecorate %18 Binding 2 +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 3 +OpDecorate %72 Block +OpMemberDecorate %72 0 Offset 0 +OpDecorate %71 DescriptorSet 0 +OpDecorate %71 Binding 0 +OpDecorate %97 BufferBlock +OpMemberDecorate %97 0 Offset 0 +OpDecorate %98 ArrayStride 96 +OpDecorate %99 Block +OpMemberDecorate %99 0 Offset 0 +OpMemberDecorate %99 0 MatrixStride 16 +OpDecorate %100 ColMajor +OpMemberDecorate %99 1 Offset 64 +OpMemberDecorate %99 2 Offset 80 +OpDecorate %96 DescriptorSet 0 +OpDecorate %96 Binding 1 +OpDecorate %109 Location 1 +OpDecorate %112 Location 0 +OpDecorate %216 Location 0 +%2 = OpTypeFloat 32 +%4 = OpTypeInt 32 0 +%6 = OpTypeVector %2 4 +%8 = OpTypeFunction %2 %4 %6 +%12 = OpConstant %2 0.0 +%13 = OpTypeBool +%17 = OpConstant %2 1.0 +%19 = OpTypeImage %2 2D 1 1 0 1 Unknown +%20 = OpTypePointer UniformConstant %19 +%18 = OpVariable %20 UniformConstant +%22 = OpTypeSampledImage %19 +%24 = OpTypeSampler +%25 = OpTypePointer UniformConstant %24 +%23 = OpVariable %25 UniformConstant +%30 = OpTypeVector %2 2 +%34 = OpConstant %2 0.5 +%35 = OpConstant %2 -0.5 +%43 = OpTypeVector %2 3 +%51 = OpConstant %2 0.0 +%54 = OpConstant %2 0.05 +%53 = OpConstantComposite %43 %54 %54 %54 +%55 = OpTypePointer Function %43 +%57 = OpConstant %4 0 +%58 = OpTypePointer Function %4 +%59 = OpTypeVoid +%61 = OpTypeFunction %59 +%73 = OpTypeVector %4 4 +%72 = OpTypeStruct %73 +%74 = OpTypePointer Uniform %72 +%71 = OpVariable %74 Uniform +%75 = OpTypeInt 32 1 +%76 = OpConstant %75 0 +%77 = OpTypePointer Uniform %73 +%78 = OpConstant %75 0 +%79 = OpTypePointer Uniform %4 +%81 = OpConstant %4 10 +%100 = OpTypeMatrix %6 4 +%99 = OpTypeStruct %100 %6 %6 +%98 = OpTypeRuntimeArray %99 +%97 = OpTypeStruct %98 +%101 = OpTypePointer Uniform %97 +%96 = OpVariable %101 Uniform +%102 = OpConstant %75 0 +%103 = OpTypePointer Uniform %98 +%105 = OpTypePointer Uniform %99 +%106 = OpConstant %75 0 +%107 = OpTypePointer Uniform %100 +%110 = OpTypePointer Input %6 +%109 = OpVariable %110 Input +%113 = OpTypePointer Input %43 +%112 = OpVariable %113 Input +%121 = OpConstant %75 0 +%122 = OpTypePointer Uniform %98 +%124 = OpTypePointer Uniform %99 +%125 = OpConstant %75 1 +%126 = OpTypePointer Uniform %6 +%127 = OpConstant %75 0 +%128 = OpTypePointer Uniform %2 +%134 = OpConstant %75 0 +%135 = OpTypePointer Uniform %98 +%137 = OpTypePointer Uniform %99 +%138 = OpConstant %75 1 +%139 = OpTypePointer Uniform %6 +%140 = OpConstant %75 1 +%141 = OpTypePointer Uniform %2 +%147 = OpConstant %75 0 +%148 = OpTypePointer Uniform %98 +%150 = OpTypePointer Uniform %99 +%151 = OpConstant %75 1 +%152 = OpTypePointer Uniform %6 +%153 = OpConstant %75 2 +%154 = OpTypePointer Uniform %2 +%158 = OpConstant %75 0 +%159 = OpTypePointer Input %2 +%162 = OpConstant %75 1 +%163 = OpTypePointer Input %2 +%166 = OpConstant %75 2 +%167 = OpTypePointer Input %2 +%177 = OpConstant %75 0 +%178 = OpTypePointer Uniform %98 +%180 = OpTypePointer Uniform %99 +%181 = OpConstant %75 2 +%182 = OpTypePointer Uniform %6 +%183 = OpConstant %75 0 +%184 = OpTypePointer Uniform %2 +%190 = OpConstant %75 0 +%191 = OpTypePointer Uniform %98 +%193 = OpTypePointer Uniform %99 +%194 = OpConstant %75 2 +%195 = OpTypePointer Uniform %6 +%196 = OpConstant %75 1 +%197 = OpTypePointer Uniform %2 +%203 = OpConstant %75 0 +%204 = OpTypePointer Uniform %98 +%206 = OpTypePointer Uniform %99 +%207 = OpConstant %75 2 +%208 = OpTypePointer Uniform %6 +%209 = OpConstant %75 2 +%210 = OpTypePointer Uniform %2 +%215 = OpConstant %4 1 +%217 = OpTypePointer Output %6 +%216 = OpVariable %217 Output +%7 = OpFunction %2 None %8 +%3 = OpFunctionParameter %4 +%5 = OpFunctionParameter %6 +%9 = OpLabel +%11 = OpCompositeExtract %2 %5 3 +%10 = OpFOrdLessThanEqual %13 %11 %12 +OpSelectionMerge %14 None +OpBranchConditional %10 %15 %16 +%15 = OpLabel +OpReturnValue %17 +%16 = OpLabel +OpBranch %14 +%14 = OpLabel +%21 = OpLoad %19 %18 +%26 = OpLoad %24 %23 +%31 = OpCompositeExtract %2 %5 0 +%32 = OpCompositeExtract %2 %5 1 +%33 = OpCompositeConstruct %30 %31 %32 +%36 = OpCompositeConstruct %30 %34 %35 +%29 = OpFMul %30 %33 %36 +%38 = OpCompositeExtract %2 %5 3 +%37 = OpFDiv %2 %17 %38 +%28 = OpVectorTimesScalar %30 %29 %37 +%39 = OpCompositeConstruct %30 %34 %34 +%27 = OpFAdd %30 %28 %39 +%40 = OpCompositeExtract %2 %27 0 +%41 = OpCompositeExtract %2 %27 1 +%42 = OpConvertUToF %2 %3 +%44 = OpCompositeConstruct %43 %40 %41 %42 +%45 = OpSampledImage %22 %21 %26 +%48 = OpCompositeExtract %2 %5 2 +%50 = OpCompositeExtract %2 %5 3 +%49 = OpFDiv %2 %17 %50 +%47 = OpFMul %2 %48 %49 +%46 = OpImageSampleDrefExplicitLod %2 %45 %44 %47 Lod %51 +OpReturnValue %46 +OpFunctionEnd +%60 = OpFunction %59 None %61 +%62 = OpLabel +%52 = OpVariable %55 Function %53 +%56 = OpVariable %58 Function %57 +OpBranch %63 +%63 = OpLabel +OpLoopMerge %64 %66 None +OpBranch %65 +%65 = OpLabel +%68 = OpLoad %4 %56 +%70 = OpAccessChain %77 %71 %76 +%69 = OpAccessChain %79 %70 %78 +%80 = OpLoad %4 %69 +%82 = OpExtInst %4 %1 UMin %80 %81 +%67 = OpUGreaterThanEqual %13 %68 %82 +OpSelectionMerge %83 None +OpBranchConditional %67 %84 %85 +%84 = OpLabel +OpBranch %64 +%85 = OpLabel +OpBranch %83 +%83 = OpLabel +%87 = OpLoad %43 %52 +%91 = OpLoad %4 %56 +%95 = OpAccessChain %103 %96 %102 +%104 = OpLoad %4 %56 +%94 = OpAccessChain %105 %95 %104 +%93 = OpAccessChain %107 %94 %106 +%108 = OpLoad %100 %93 +%111 = OpLoad %6 %109 +%92 = OpMatrixTimesVector %6 %108 %111 +%90 = OpFunctionCall %2 %7 %91 %92 +%114 = OpLoad %43 %112 +%115 = OpExtInst %43 %1 Normalize %114 +%120 = OpAccessChain %122 %96 %121 +%123 = OpLoad %4 %56 +%119 = OpAccessChain %124 %120 %123 +%118 = OpAccessChain %126 %119 %125 +%117 = OpAccessChain %128 %118 %127 +%129 = OpLoad %2 %117 +%133 = OpAccessChain %135 %96 %134 +%136 = OpLoad %4 %56 +%132 = OpAccessChain %137 %133 %136 +%131 = OpAccessChain %139 %132 %138 +%130 = OpAccessChain %141 %131 %140 +%142 = OpLoad %2 %130 +%146 = OpAccessChain %148 %96 %147 +%149 = OpLoad %4 %56 +%145 = OpAccessChain %150 %146 %149 +%144 = OpAccessChain %152 %145 %151 +%143 = OpAccessChain %154 %144 %153 +%155 = OpLoad %2 %143 +%156 = OpCompositeConstruct %43 %129 %142 %155 +%157 = OpAccessChain %159 %109 %158 +%160 = OpLoad %2 %157 +%161 = OpAccessChain %163 %109 %162 +%164 = OpLoad %2 %161 +%165 = OpAccessChain %167 %109 %166 +%168 = OpLoad %2 %165 +%169 = OpCompositeConstruct %43 %160 %164 %168 +%116 = OpFSub %43 %156 %169 +%170 = OpExtInst %43 %1 Normalize %116 +%171 = OpDot %2 %115 %170 +%172 = OpExtInst %2 %1 FMax %12 %171 +%89 = OpFMul %2 %90 %172 +%176 = OpAccessChain %178 %96 %177 +%179 = OpLoad %4 %56 +%175 = OpAccessChain %180 %176 %179 +%174 = OpAccessChain %182 %175 %181 +%173 = OpAccessChain %184 %174 %183 +%185 = OpLoad %2 %173 +%189 = OpAccessChain %191 %96 %190 +%192 = OpLoad %4 %56 +%188 = OpAccessChain %193 %189 %192 +%187 = OpAccessChain %195 %188 %194 +%186 = OpAccessChain %197 %187 %196 +%198 = OpLoad %2 %186 +%202 = OpAccessChain %204 %96 %203 +%205 = OpLoad %4 %56 +%201 = OpAccessChain %206 %202 %205 +%200 = OpAccessChain %208 %201 %207 +%199 = OpAccessChain %210 %200 %209 +%211 = OpLoad %2 %199 +%212 = OpCompositeConstruct %43 %185 %198 %211 +%88 = OpVectorTimesScalar %43 %212 %89 +%86 = OpFAdd %43 %87 %88 +OpStore %52 %86 +OpBranch %66 +%66 = OpLabel +%214 = OpLoad %4 %56 +%213 = OpIAdd %4 %214 %215 +OpStore %56 %213 +OpBranch %63 +%64 = OpLabel +%218 = OpLoad %43 %52 +%219 = OpCompositeConstruct %6 %218 %17 +OpStore %216 %219 +OpReturn +OpFunctionEnd From b8e9c209b0c0117a049f6d0f9628ae55c7b7bb31 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 30 Jan 2021 00:11:42 -0500 Subject: [PATCH 0404/2212] [mtl] fix unsigned constants, comparison level option --- src/back/msl/writer.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c5fe73cff..f5d0f3ec7 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -286,7 +286,7 @@ impl Writer { match level { crate::SampleLevel::Auto => {} crate::SampleLevel::Zero => { - write!(self.out, ", level(0)")?; + //TODO: do we support Zero on `Sampled` image classes? } crate::SampleLevel::Exact(h) => { write!(self.out, ", level(")?; @@ -538,7 +538,7 @@ impl Writer { write!(self.out, "{}", value)?; } crate::ScalarValue::Uint(value) => { - write!(self.out, "{}", value)?; + write!(self.out, "{}u", value)?; } crate::ScalarValue::Float(value) => { write!(self.out, "{}", value)?; From 40974d503c99506ee3b274041979a9656782420d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 29 Jan 2021 19:41:19 -0500 Subject: [PATCH 0405/2212] Bump version to 0.3 and update changelog --- CHANGELOG.md | 16 +++++++++++++++- Cargo.toml | 4 ++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 614c76834..5b166a8cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,21 @@ # Change Log ## v0.2 (2020-08-17) - - development release for wgpu-0.6 + - development release for wgpu-0.7 + - API: + - math functions + - type casts + - updated storage classes + - updated image sub-types + - image sampling/loading options + - storage images + - interpolation qualifiers + - early and conservative depth + - Processors: + - name manager + - automatic layout + - termination analysis + - validation of types, constants, variables, and entry points ## v0.1 (2020-02-26) - initial release diff --git a/Cargo.toml b/Cargo.toml index 0d0b4859c..ef9df97aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "naga" -version = "0.2.0" -authors = ["Dzmitry Malyshau "] +version = "0.3.0" +authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" homepage = "https://github.com/gfx-rs/naga" From be86f5b7cf799fc1368229976197d1a6d2896235 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 30 Jan 2021 11:54:15 -0500 Subject: [PATCH 0406/2212] Update README table --- README.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index e09db9182..bbfaf7c7f 100644 --- a/README.md +++ b/README.md @@ -9,23 +9,24 @@ This is an experimental shader translation library for the needs of gfx-rs proje ## Supported end-points +Everything is still a work-in-progress, but some end-points are usable: + Front-end | Status | Notes | --------------- | ------------------ | ----- | -SPIR-V (binary) | :construction: | | -WGSL | :construction: | | -GLSL (Vulkan) | :construction: | | +SPIR-V (binary) | :heavy_check_mark: | | +WGSL | :heavy_check_mark: | | +GLSL (Vulkan) | :white_check_mark: | | Rust | | | Back-end | Status | Notes | --------------- | ------------------ | ----- | -SPIR-V (binary) | :construction: | | +SPIR-V (binary) | :heavy_check_mark: | | WGSL | | | -Metal | :construction: | | +Metal | :heavy_check_mark: | | HLSL | | | -GLSL | :construction: | | +GLSL | :white_check_mark: | | AIR | | | -DXIR | | | -DXIL | | | +DXIL/DXIR | | | DXBC | | | :heavy_check_mark: = Primary support — :white_check_mark: = Secondary support — :construction: = Unsupported, but support in progress From b55aa51f657dac68f3c14e9d8dc192c7de74e560 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 30 Jan 2021 17:19:31 +0000 Subject: [PATCH 0407/2212] Add support for function declarations with arguments Change ParseError to be public Change globals to default to private instead of throwing error --- src/front/glsl/ast.rs | 10 ++++--- src/front/glsl/functions.rs | 1 + src/front/glsl/mod.rs | 2 +- src/front/glsl/parser.rs | 42 ++++++++++++++++++++++++++-- src/front/glsl/parser_tests.rs | 51 ++++++++++++++++++++++++++++++++++ 5 files changed, 99 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 6f3669a75..842d5c9bc 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,8 +1,9 @@ use super::error::ErrorKind; use crate::{ proc::{ResolveContext, Typifier}, - Arena, BinaryOperator, Binding, Expression, FastHashMap, Function, GlobalVariable, Handle, - Interpolation, LocalVariable, Module, ShaderStage, Statement, StorageClass, Type, + Arena, BinaryOperator, Binding, Expression, FastHashMap, Function, FunctionArgument, + GlobalVariable, Handle, Interpolation, LocalVariable, Module, ShaderStage, Statement, + StorageClass, Type, }; #[derive(Debug)] @@ -31,6 +32,7 @@ impl Program { context: Context { expressions: Arena::::new(), local_variables: Arena::::new(), + arguments: Vec::new(), scopes: vec![FastHashMap::default()], lookup_global_var_exps: FastHashMap::default(), typifier: Typifier::new(), @@ -57,13 +59,12 @@ impl Program { handle: Handle, ) -> Result<&crate::TypeInner, ErrorKind> { let functions = Arena::new(); //TODO - let arguments = Vec::new(); //TODO let resolve_ctx = ResolveContext { constants: &self.module.constants, global_vars: &self.module.global_variables, local_vars: &self.context.local_variables, functions: &functions, - arguments: &arguments, + arguments: &self.context.arguments, }; match self.context.typifier.grow( handle, @@ -87,6 +88,7 @@ pub enum Profile { pub struct Context { pub expressions: Arena, pub local_variables: Arena, + pub arguments: Vec, //TODO: Find less allocation heavy representation pub scopes: Vec>>, pub lookup_global_var_exps: FastHashMap>, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index fa07d891e..80132bfd2 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -164,6 +164,7 @@ impl Program { pub fn function_definition(&mut self, mut f: Function, mut block: Block) -> Function { std::mem::swap(&mut f.expressions, &mut self.context.expressions); std::mem::swap(&mut f.local_variables, &mut self.context.local_variables); + std::mem::swap(&mut f.arguments, &mut self.context.arguments); self.context.clear_scopes(); self.context.lookup_global_var_exps.clear(); self.context.typifier = Typifier::new(); diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index c5ecfbbfe..a05a62fd3 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -13,7 +13,7 @@ use ast::Program; use lex::Lexer; mod error; -use error::ParseError; +pub use error::ParseError; mod functions; mod parser; #[cfg(test)] diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index bd0cbb7e4..4eb76ddcf 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -10,7 +10,7 @@ pomelo! { Function, GlobalVariable, Handle, Interpolation, LocalVariable, ScalarValue, Statement, StorageAccess, StorageClass, StructMember, - SwitchCase, Type, TypeInner, UnaryOperator, + SwitchCase, Type, TypeInner, UnaryOperator, FunctionArgument }; } %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; @@ -47,6 +47,7 @@ pomelo! { %type function_prototype Function; %type function_declarator Function; %type function_header Function; + %type function_header_with_parameters (Function, Vec); %type function_definition Function; // statements @@ -80,6 +81,10 @@ pomelo! { %type function_call_header FunctionCall; %type function_identifier FunctionCallKind; + %type parameter_declarator FunctionArgument; + %type parameter_declaration FunctionArgument; + %type parameter_type_specifier Handle; + %type multiplicative_expression ExpressionRule; %type additive_expression ExpressionRule; %type shift_expression ExpressionRule; @@ -941,6 +946,16 @@ pomelo! { f } function_declarator ::= function_header; + function_declarator ::= function_header_with_parameters((f, args)) { + for (pos, arg) in args.into_iter().enumerate() { + if let Some(name) = arg.name.clone() { + let exp = extra.context.expressions.append(Expression::FunctionArgument(pos as u32)); + extra.context.add_local_var(name, exp); + } + extra.context.arguments.push(arg); + } + f + } function_header ::= fully_specified_type(t) Identifier(n) LeftParen { Function { name: Some(n.1), @@ -952,6 +967,29 @@ pomelo! { body: vec![], } } + function_header_with_parameters ::= function_header(h) parameter_declaration(p) { + (h, vec![p]) + } + function_header_with_parameters ::= function_header_with_parameters((h, mut args)) Comma parameter_declaration(p) { + args.push(p); + (h, args) + } + parameter_declarator ::= parameter_type_specifier(ty) Identifier(n) { + FunctionArgument { name: Some(n.1), ty } + } + // parameter_declarator ::= type_specifier(ty) Identifier(ident) array_specifier; + parameter_declaration ::= parameter_declarator; + parameter_declaration ::= parameter_type_specifier(ty) { + FunctionArgument { name: None, ty } + } + + parameter_type_specifier ::= type_specifier(t) { + if let Some(ty) = t { + ty + } else { + return Err(ErrorKind::SemanticError("Function parameter can't be void".into())) + } + } jump_statement ::= Continue Semicolon { Statement::Continue @@ -1002,7 +1040,7 @@ pomelo! { if let Some(d) = d { let class = d.type_qualifiers.iter().find_map(|tq| { if let TypeQualifier::StorageClass(sc) = tq { Some(*sc) } else { None } - }).ok_or_else(|| ErrorKind::SemanticError(format!("Missing storage class for global var \"{:?}\"", d).into()))?; + }).unwrap_or(StorageClass::Private); let binding = d.type_qualifiers.iter().find_map(|tq| { if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index ccdc657a7..b586c8bbc 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -180,3 +180,54 @@ fn textures() { ) .unwrap(); } + +#[test] +fn functions() { + // TODO: Add support for function prototypes + // parse_program( + // r#" + // # version 450 + // void test1(float); + // void test1(float) {} + + // void main() {} + // "#, + // ShaderStage::Vertex, + // ) + // .unwrap(); + + parse_program( + r#" + # version 450 + void test2(float a) {} + void test3(float a, float b) {} + void test4(float, float) {} + + void main() {} + "#, + ShaderStage::Vertex, + ) + .unwrap(); + + parse_program( + r#" + # version 450 + float test(float a) { return a; } + + void main() {} + "#, + ShaderStage::Vertex, + ) + .unwrap(); + + parse_program( + r#" + # version 450 + float test(vec4 p) { + return p.x; + } + "#, + ShaderStage::Vertex, + ) + .unwrap(); +} From 15b629b75094f1e9c09a1c1c4cc41b7726c1f722 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 30 Jan 2021 22:36:41 -0500 Subject: [PATCH 0408/2212] [spv] put ColMajor on the struct member --- src/back/spv/writer.rs | 13 +++++++------ tests/snapshots/snapshots__shadow.spvasm.snap | 2 +- tests/snapshots/snapshots__skybox.spvasm.snap | 4 ++-- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 74d715a03..5dd0f39e4 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -623,12 +623,6 @@ impl Writer { rows, width, } => { - self.annotations - .push(super::instructions::instruction_decorate( - id, - spirv::Decoration::ColMajor, - &[], - )); let vector_id = self.get_type_id( arena, LookupType::Local(LocalType::Vector { @@ -749,6 +743,13 @@ impl Writer { crate::VectorSize::Bi => 2 * width, crate::VectorSize::Tri | crate::VectorSize::Quad => 4 * width, }; + self.annotations + .push(super::instructions::instruction_member_decorate( + id, + index as u32, + spirv::Decoration::ColMajor, + &[], + )); self.annotations .push(super::instructions::instruction_member_decorate( id, diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap index 203e43e54..aa1fcdb4b 100644 --- a/tests/snapshots/snapshots__shadow.spvasm.snap +++ b/tests/snapshots/snapshots__shadow.spvasm.snap @@ -24,8 +24,8 @@ OpMemberDecorate %97 0 Offset 0 OpDecorate %98 ArrayStride 96 OpDecorate %99 Block OpMemberDecorate %99 0 Offset 0 +OpMemberDecorate %99 0 ColMajor OpMemberDecorate %99 0 MatrixStride 16 -OpDecorate %100 ColMajor OpMemberDecorate %99 1 Offset 64 OpMemberDecorate %99 2 Offset 80 OpDecorate %96 DescriptorSet 0 diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap index a6a27f59f..45fdbf18c 100644 --- a/tests/snapshots/snapshots__skybox.spvasm.snap +++ b/tests/snapshots/snapshots__skybox.spvasm.snap @@ -15,14 +15,14 @@ OpExecutionMode %168 OriginUpperLeft OpDecorate %15 BuiltIn VertexIndex OpDecorate %26 Block OpMemberDecorate %26 0 Offset 0 +OpMemberDecorate %26 0 ColMajor OpMemberDecorate %26 0 MatrixStride 16 -OpDecorate %27 ColMajor OpMemberDecorate %26 1 Offset 64 +OpMemberDecorate %26 1 ColMajor OpMemberDecorate %26 1 MatrixStride 16 OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 0 OpDecorate %44 Location 0 -OpDecorate %48 ColMajor OpDecorate %157 BuiltIn Position OpDecorate %170 Location 0 OpDecorate %171 DescriptorSet 0 From 1ec4c2b0d0ba9a482c1d245e759f9b90579ec6db Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 30 Jan 2021 22:51:56 -0500 Subject: [PATCH 0409/2212] [spv] implement NonReadable/NonWritable decorations --- src/back/spv/writer.rs | 44 ++++++++++++++++--- tests/snapshots/snapshots__shadow.spvasm.snap | 1 + 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 5dd0f39e4..e11fb6aae 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -180,7 +180,7 @@ pub struct Writer { lookup_constant: crate::FastHashMap, Word>, lookup_global_variable: crate::FastHashMap, (Word, spirv::StorageClass)>, - storage_type_handles: crate::FastHashSet>, + storage_type_handles: crate::FastHashMap, crate::StorageAccess>, gl450_ext_inst_id: Word, layouter: Layouter, } @@ -209,7 +209,7 @@ impl Writer { lookup_function_type: crate::FastHashMap::default(), lookup_constant: crate::FastHashMap::default(), lookup_global_variable: crate::FastHashMap::default(), - storage_type_handles: crate::FastHashSet::default(), + storage_type_handles: crate::FastHashMap::default(), gl450_ext_inst_id: 0, layouter: Layouter::default(), } @@ -693,10 +693,10 @@ impl Writer { block: true, ref members, } => { - let decoration = if self.storage_type_handles.contains(&handle) { - spirv::Decoration::BufferBlock - } else { - spirv::Decoration::Block + //TODO: put NonWritable/NonReadable on the global variable instead? + let (decoration, storage_access) = match self.storage_type_handles.get(&handle) { + Some(&access) => (spirv::Decoration::BufferBlock, access), + None => (spirv::Decoration::Block, crate::StorageAccess::empty()), }; self.annotations .push(super::instructions::instruction_decorate( @@ -733,6 +733,16 @@ impl Writer { } } + if storage_access == crate::StorageAccess::LOAD { + self.annotations + .push(super::instructions::instruction_member_decorate( + id, + index as u32, + spirv::Decoration::NonWritable, + &[], + )); + } + if let crate::TypeInner::Matrix { columns, rows: _, @@ -916,6 +926,26 @@ impl Writer { } } + if let crate::TypeInner::Image { + class: crate::ImageClass::Storage(_), + .. + } = ir_module.types[global_variable.ty].inner + { + let decoration = match global_variable.storage_access { + crate::StorageAccess::LOAD => Some(spirv::Decoration::NonWritable), + crate::StorageAccess::STORE => Some(spirv::Decoration::NonReadable), + _ => None, + }; + if let Some(decoration) = decoration { + self.annotations + .push(super::instructions::instruction_decorate( + id, + decoration, + &[], + )); + } + } + if let Some(interpolation) = global_variable.interpolation { let decoration = match interpolation { crate::Interpolation::Linear => Some(spirv::Decoration::NoPerspective), @@ -2315,7 +2345,7 @@ impl Writer { for (_, var) in ir_module.global_variables.iter() { if !var.storage_access.is_empty() { - self.storage_type_handles.insert(var.ty); + self.storage_type_handles.insert(var.ty, var.storage_access); } } diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap index aa1fcdb4b..e699d3d0c 100644 --- a/tests/snapshots/snapshots__shadow.spvasm.snap +++ b/tests/snapshots/snapshots__shadow.spvasm.snap @@ -21,6 +21,7 @@ OpDecorate %71 DescriptorSet 0 OpDecorate %71 Binding 0 OpDecorate %97 BufferBlock OpMemberDecorate %97 0 Offset 0 +OpMemberDecorate %97 0 NonWritable OpDecorate %98 ArrayStride 96 OpDecorate %99 Block OpMemberDecorate %99 0 Offset 0 From 7c6835bdbcff78b65eacf7f3363ba78433a99950 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 31 Jan 2021 01:41:20 -0500 Subject: [PATCH 0410/2212] [spv] fix support for fixed-size array, refactor constant writes --- src/back/spv/writer.rs | 51 +- tests/snapshots/snapshots__boids.spvasm.snap | 708 +++++++++--------- .../snapshots/snapshots__collatz.spvasm.snap | 100 +-- tests/snapshots/snapshots__quad.spvasm.snap | 68 +- tests/snapshots/snapshots__shadow.spvasm.snap | 504 ++++++------- tests/snapshots/snapshots__skybox.spvasm.snap | 246 +++--- 6 files changed, 828 insertions(+), 849 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e11fb6aae..bb5c2323e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -255,22 +255,6 @@ impl Writer { } } - fn get_constant_id( - &mut self, - handle: crate::Handle, - ir_module: &crate::Module, - ) -> Result { - if let Entry::Occupied(e) = self.lookup_constant.entry(handle) { - Ok(*e.get()) - } else { - let id = self.generate_id(); - self.lookup_constant.insert(handle, id); - let inner = &ir_module.constants[handle].inner; - self.write_constant_type(id, inner, ir_module)?; - Ok(id) - } - } - fn get_global_variable_id( &mut self, ir_module: &crate::Module, @@ -383,8 +367,7 @@ impl Writer { let init_word = variable .init - .map(|constant| self.get_constant_id(constant, ir_module)) - .transpose()?; + .map(|constant| self.lookup_constant[&constant]); let pointer_type_id = self.get_pointer_id(&ir_module.types, variable.ty, crate::StorageClass::Function)?; let instruction = super::instructions::instruction_variable( @@ -806,12 +789,12 @@ impl Writer { &mut self, id: Word, inner: &crate::ConstantInner, - ir_module: &crate::Module, + types: &crate::Arena, ) -> Result<(), Error> { let instruction = match *inner { crate::ConstantInner::Scalar { width, ref value } => { let type_id = self.get_type_id( - &ir_module.types, + types, LookupType::Local(LocalType::Scalar { kind: value.scalar_kind(), width, @@ -873,20 +856,11 @@ impl Writer { crate::ConstantInner::Composite { ty, ref components } => { let mut constituent_ids = Vec::with_capacity(components.len()); for constituent in components.iter() { - let constituent_id = self.get_constant_id(*constituent, &ir_module)?; + let constituent_id = self.lookup_constant[constituent]; constituent_ids.push(constituent_id); } - // Get the size constant for arrays - if let crate::TypeInner::Array { - size: crate::ArraySize::Constant(const_handle), - .. - } = ir_module.types[ty].inner - { - self.get_constant_id(const_handle, &ir_module)?; - } - - let type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty))?; + let type_id = self.get_type_id(types, LookupType::Handle(ty))?; super::instructions::instruction_constant_composite( type_id, id, @@ -912,8 +886,7 @@ impl Writer { let init_word = global_variable .init - .map(|constant| self.get_constant_id(constant, ir_module)) - .transpose()?; + .map(|constant| self.lookup_constant[&constant]); let pointer_type_id = self.get_pointer_id(&ir_module.types, global_variable.ty, global_variable.class)?; let instruction = @@ -1294,7 +1267,7 @@ impl Writer { } crate::Expression::Constant(handle) => { let var = &ir_module.constants[handle]; - let id = self.get_constant_id(handle, ir_module)?; + let id = self.lookup_constant[&handle]; let lookup_type = match var.inner { crate::ConstantInner::Scalar { width, ref value } => { LookupType::Local(LocalType::Scalar { @@ -2043,7 +2016,7 @@ impl Writer { width: 4, value: crate::ScalarValue::Float(0.0), }; - self.write_constant_type(zero_id, &zero_inner, ir_module)?; + self.write_constant_type(zero_id, &zero_inner, &ir_module.types)?; inst.add_operand(spirv::ImageOperands::LOD.bits()); inst.add_operand(zero_id); @@ -2124,7 +2097,7 @@ impl Writer { }; if let Some(offset_const) = offset { - let offset_id = self.get_constant_id(offset_const, ir_module)?; + let offset_id = self.lookup_constant[&offset_const]; main_instruction.add_operand(spirv::ImageOperands::CONST_OFFSET.bits()); main_instruction.add_operand(offset_id); } @@ -2343,6 +2316,12 @@ impl Writer { )); } + for (handle, constant) in ir_module.constants.iter() { + let id = self.generate_id(); + self.lookup_constant.insert(handle, id); + self.write_constant_type(id, &constant.inner, &ir_module.types)?; + } + for (_, var) in ir_module.global_variables.iter() { if !var.storage_access.is_empty() { self.storage_type_handles.insert(var.ty, var.storage_access); diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap index ece073bbe..dc2eea87a 100644 --- a/tests/snapshots/snapshots__boids.spvasm.snap +++ b/tests/snapshots/snapshots__boids.spvasm.snap @@ -9,401 +9,401 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %22 "main" %27 -OpExecutionMode %22 LocalSize 64 1 1 -OpDecorate %27 BuiltIn GlobalInvocationId -OpDecorate %42 BufferBlock -OpMemberDecorate %42 0 Offset 0 -OpDecorate %43 ArrayStride 16 -OpDecorate %44 Block -OpMemberDecorate %44 0 Offset 0 -OpMemberDecorate %44 1 Offset 8 -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 1 -OpDecorate %117 Block -OpMemberDecorate %117 0 Offset 0 -OpMemberDecorate %117 1 Offset 4 -OpMemberDecorate %117 2 Offset 8 -OpMemberDecorate %117 3 Offset 12 -OpMemberDecorate %117 4 Offset 16 -OpMemberDecorate %117 5 Offset 20 -OpMemberDecorate %117 6 Offset 24 -OpDecorate %116 DescriptorSet 0 -OpDecorate %116 Binding 0 +OpEntryPoint GLCompute %29 "main" %34 +OpExecutionMode %29 LocalSize 64 1 1 +OpDecorate %34 BuiltIn GlobalInvocationId +OpDecorate %48 BufferBlock +OpMemberDecorate %48 0 Offset 0 +OpDecorate %49 ArrayStride 16 +OpDecorate %50 Block +OpMemberDecorate %50 0 Offset 0 +OpMemberDecorate %50 1 Offset 8 +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 1 +OpDecorate %122 Block +OpMemberDecorate %122 0 Offset 0 +OpMemberDecorate %122 1 Offset 4 +OpMemberDecorate %122 2 Offset 8 +OpMemberDecorate %122 3 Offset 12 +OpMemberDecorate %122 4 Offset 16 +OpMemberDecorate %122 5 Offset 20 +OpMemberDecorate %122 6 Offset 24 +OpDecorate %121 DescriptorSet 0 +OpDecorate %121 Binding 0 OpDecorate %274 DescriptorSet 0 OpDecorate %274 Binding 2 -%4 = OpTypeFloat 32 -%3 = OpTypeVector %4 2 -%5 = OpTypePointer Function %3 -%12 = OpTypeInt 32 1 -%11 = OpConstant %12 0 -%13 = OpTypePointer Function %12 -%19 = OpTypeInt 32 0 -%18 = OpConstant %19 0 -%20 = OpTypePointer Function %19 -%21 = OpTypeVoid -%23 = OpTypeFunction %21 -%28 = OpTypeVector %19 3 -%29 = OpTypePointer Input %28 -%27 = OpVariable %29 Input -%30 = OpConstant %12 0 -%31 = OpTypePointer Input %19 -%33 = OpConstant %12 1500 -%34 = OpTypeBool -%44 = OpTypeStruct %3 %3 -%43 = OpTypeRuntimeArray %44 -%42 = OpTypeStruct %43 -%45 = OpTypePointer Uniform %42 -%41 = OpVariable %45 Uniform -%46 = OpConstant %12 0 -%47 = OpTypePointer Uniform %43 -%49 = OpConstant %12 0 -%50 = OpTypePointer Input %19 -%52 = OpTypePointer Uniform %44 -%53 = OpConstant %12 0 -%54 = OpTypePointer Uniform %3 -%59 = OpConstant %12 0 -%60 = OpTypePointer Uniform %43 -%62 = OpConstant %12 0 -%63 = OpTypePointer Input %19 -%65 = OpTypePointer Uniform %44 -%66 = OpConstant %12 1 -%67 = OpTypePointer Uniform %3 -%69 = OpConstant %4 0.0 -%85 = OpConstant %12 0 -%86 = OpTypePointer Input %19 -%94 = OpConstant %12 0 -%95 = OpTypePointer Uniform %43 -%97 = OpTypePointer Uniform %44 -%98 = OpConstant %12 0 -%99 = OpTypePointer Uniform %3 -%104 = OpConstant %12 0 -%105 = OpTypePointer Uniform %43 -%107 = OpTypePointer Uniform %44 -%108 = OpConstant %12 1 -%109 = OpTypePointer Uniform %3 -%117 = OpTypeStruct %4 %4 %4 %4 %4 %4 %4 -%118 = OpTypePointer Uniform %117 -%116 = OpVariable %118 Uniform -%119 = OpConstant %12 1 -%120 = OpTypePointer Uniform %4 -%130 = OpConstant %12 1 -%136 = OpConstant %12 2 -%137 = OpTypePointer Uniform %4 -%152 = OpConstant %12 3 -%153 = OpTypePointer Uniform %4 -%165 = OpConstant %19 1 -%175 = OpConstant %4 1.0 -%196 = OpConstant %12 4 -%197 = OpTypePointer Uniform %4 -%202 = OpConstant %12 5 -%203 = OpTypePointer Uniform %4 -%208 = OpConstant %12 6 -%209 = OpTypePointer Uniform %4 -%216 = OpConstant %4 0.1 -%223 = OpConstant %12 0 -%224 = OpTypePointer Uniform %4 -%228 = OpConstant %12 0 -%229 = OpTypePointer Function %4 -%231 = OpConstant %4 -1.0 -%236 = OpConstant %12 0 -%237 = OpTypePointer Function %4 -%240 = OpConstant %12 0 -%241 = OpTypePointer Function %4 -%247 = OpConstant %12 0 -%248 = OpTypePointer Function %4 -%251 = OpConstant %12 1 -%252 = OpTypePointer Function %4 -%258 = OpConstant %12 1 -%259 = OpTypePointer Function %4 -%262 = OpConstant %12 1 -%263 = OpTypePointer Function %4 -%269 = OpConstant %12 1 -%270 = OpTypePointer Function %4 -%274 = OpVariable %45 Uniform -%275 = OpConstant %12 0 -%276 = OpTypePointer Uniform %43 -%278 = OpConstant %12 0 -%279 = OpTypePointer Input %19 -%281 = OpTypePointer Uniform %44 -%282 = OpConstant %12 0 -%283 = OpTypePointer Uniform %3 -%288 = OpConstant %12 0 -%289 = OpTypePointer Uniform %43 -%291 = OpConstant %12 0 -%292 = OpTypePointer Input %19 -%294 = OpTypePointer Uniform %44 -%295 = OpConstant %12 1 -%296 = OpTypePointer Uniform %3 -%22 = OpFunction %21 None %23 -%24 = OpLabel -%17 = OpVariable %20 Function %18 -%14 = OpVariable %13 Function %11 -%8 = OpVariable %5 Function -%2 = OpVariable %5 Function -%15 = OpVariable %5 Function -%9 = OpVariable %5 Function -%6 = OpVariable %5 Function -%16 = OpVariable %5 Function -%10 = OpVariable %13 Function %11 -%7 = OpVariable %5 Function -%26 = OpAccessChain %31 %27 %30 -%32 = OpLoad %19 %26 -%25 = OpUGreaterThanEqual %34 %32 %33 -OpSelectionMerge %35 None -OpBranchConditional %25 %36 %37 -%36 = OpLabel +%3 = OpTypeInt 32 1 +%2 = OpConstant %3 1500 +%5 = OpTypeFloat 32 +%4 = OpConstant %5 0.0 +%6 = OpConstant %3 0 +%8 = OpTypeInt 32 0 +%7 = OpConstant %8 0 +%9 = OpConstant %3 1 +%10 = OpConstant %8 1 +%11 = OpConstant %5 1.0 +%12 = OpConstant %5 0.1 +%13 = OpConstant %5 -1.0 +%15 = OpTypeVector %5 2 +%16 = OpTypePointer Function %15 +%22 = OpTypePointer Function %3 +%27 = OpTypePointer Function %8 +%28 = OpTypeVoid +%30 = OpTypeFunction %28 +%35 = OpTypeVector %8 3 +%36 = OpTypePointer Input %35 +%34 = OpVariable %36 Input +%37 = OpConstant %3 0 +%38 = OpTypePointer Input %8 +%40 = OpTypeBool +%50 = OpTypeStruct %15 %15 +%49 = OpTypeRuntimeArray %50 +%48 = OpTypeStruct %49 +%51 = OpTypePointer Uniform %48 +%47 = OpVariable %51 Uniform +%52 = OpConstant %3 0 +%53 = OpTypePointer Uniform %49 +%55 = OpConstant %3 0 +%56 = OpTypePointer Input %8 +%58 = OpTypePointer Uniform %50 +%59 = OpConstant %3 0 +%60 = OpTypePointer Uniform %15 +%65 = OpConstant %3 0 +%66 = OpTypePointer Uniform %49 +%68 = OpConstant %3 0 +%69 = OpTypePointer Input %8 +%71 = OpTypePointer Uniform %50 +%72 = OpConstant %3 1 +%73 = OpTypePointer Uniform %15 +%90 = OpConstant %3 0 +%91 = OpTypePointer Input %8 +%99 = OpConstant %3 0 +%100 = OpTypePointer Uniform %49 +%102 = OpTypePointer Uniform %50 +%103 = OpConstant %3 0 +%104 = OpTypePointer Uniform %15 +%109 = OpConstant %3 0 +%110 = OpTypePointer Uniform %49 +%112 = OpTypePointer Uniform %50 +%113 = OpConstant %3 1 +%114 = OpTypePointer Uniform %15 +%122 = OpTypeStruct %5 %5 %5 %5 %5 %5 %5 +%123 = OpTypePointer Uniform %122 +%121 = OpVariable %123 Uniform +%124 = OpConstant %3 1 +%125 = OpTypePointer Uniform %5 +%140 = OpConstant %3 2 +%141 = OpTypePointer Uniform %5 +%156 = OpConstant %3 3 +%157 = OpTypePointer Uniform %5 +%198 = OpConstant %3 4 +%199 = OpTypePointer Uniform %5 +%204 = OpConstant %3 5 +%205 = OpTypePointer Uniform %5 +%210 = OpConstant %3 6 +%211 = OpTypePointer Uniform %5 +%224 = OpConstant %3 0 +%225 = OpTypePointer Uniform %5 +%229 = OpConstant %3 0 +%230 = OpTypePointer Function %5 +%236 = OpConstant %3 0 +%237 = OpTypePointer Function %5 +%240 = OpConstant %3 0 +%241 = OpTypePointer Function %5 +%247 = OpConstant %3 0 +%248 = OpTypePointer Function %5 +%251 = OpConstant %3 1 +%252 = OpTypePointer Function %5 +%258 = OpConstant %3 1 +%259 = OpTypePointer Function %5 +%262 = OpConstant %3 1 +%263 = OpTypePointer Function %5 +%269 = OpConstant %3 1 +%270 = OpTypePointer Function %5 +%274 = OpVariable %51 Uniform +%275 = OpConstant %3 0 +%276 = OpTypePointer Uniform %49 +%278 = OpConstant %3 0 +%279 = OpTypePointer Input %8 +%281 = OpTypePointer Uniform %50 +%282 = OpConstant %3 0 +%283 = OpTypePointer Uniform %15 +%288 = OpConstant %3 0 +%289 = OpTypePointer Uniform %49 +%291 = OpConstant %3 0 +%292 = OpTypePointer Input %8 +%294 = OpTypePointer Uniform %50 +%295 = OpConstant %3 1 +%296 = OpTypePointer Uniform %15 +%29 = OpFunction %28 None %30 +%31 = OpLabel +%26 = OpVariable %27 Function %7 +%23 = OpVariable %22 Function %6 +%19 = OpVariable %16 Function +%14 = OpVariable %16 Function +%24 = OpVariable %16 Function +%20 = OpVariable %16 Function +%17 = OpVariable %16 Function +%25 = OpVariable %16 Function +%21 = OpVariable %22 Function %6 +%18 = OpVariable %16 Function +%33 = OpAccessChain %38 %34 %37 +%39 = OpLoad %8 %33 +%32 = OpUGreaterThanEqual %40 %39 %2 +OpSelectionMerge %41 None +OpBranchConditional %32 %42 %43 +%42 = OpLabel OpReturn -%37 = OpLabel -OpBranch %35 -%35 = OpLabel -%40 = OpAccessChain %47 %41 %46 -%48 = OpAccessChain %50 %27 %49 -%51 = OpLoad %19 %48 -%39 = OpAccessChain %52 %40 %51 -%38 = OpAccessChain %54 %39 %53 -%55 = OpLoad %3 %38 -OpStore %2 %55 -%58 = OpAccessChain %60 %41 %59 -%61 = OpAccessChain %63 %27 %62 -%64 = OpLoad %19 %61 -%57 = OpAccessChain %65 %58 %64 -%56 = OpAccessChain %67 %57 %66 -%68 = OpLoad %3 %56 -OpStore %6 %68 -%70 = OpCompositeConstruct %3 %69 %69 -OpStore %7 %70 -%71 = OpCompositeConstruct %3 %69 %69 -OpStore %8 %71 -%72 = OpCompositeConstruct %3 %69 %69 -OpStore %9 %72 -OpBranch %73 -%73 = OpLabel -OpLoopMerge %74 %76 None -OpBranch %75 -%75 = OpLabel -%78 = OpLoad %19 %17 -%77 = OpUGreaterThanEqual %34 %78 %33 -OpSelectionMerge %79 None -OpBranchConditional %77 %80 %81 +%43 = OpLabel +OpBranch %41 +%41 = OpLabel +%46 = OpAccessChain %53 %47 %52 +%54 = OpAccessChain %56 %34 %55 +%57 = OpLoad %8 %54 +%45 = OpAccessChain %58 %46 %57 +%44 = OpAccessChain %60 %45 %59 +%61 = OpLoad %15 %44 +OpStore %14 %61 +%64 = OpAccessChain %66 %47 %65 +%67 = OpAccessChain %69 %34 %68 +%70 = OpLoad %8 %67 +%63 = OpAccessChain %71 %64 %70 +%62 = OpAccessChain %73 %63 %72 +%74 = OpLoad %15 %62 +OpStore %17 %74 +%75 = OpCompositeConstruct %15 %4 %4 +OpStore %18 %75 +%76 = OpCompositeConstruct %15 %4 %4 +OpStore %19 %76 +%77 = OpCompositeConstruct %15 %4 %4 +OpStore %20 %77 +OpBranch %78 +%78 = OpLabel +OpLoopMerge %79 %81 None +OpBranch %80 %80 = OpLabel -OpBranch %74 -%81 = OpLabel +%83 = OpLoad %8 %26 +%82 = OpUGreaterThanEqual %40 %83 %2 +OpSelectionMerge %84 None +OpBranchConditional %82 %85 %86 +%85 = OpLabel OpBranch %79 +%86 = OpLabel +OpBranch %84 +%84 = OpLabel +%88 = OpLoad %8 %26 +%89 = OpAccessChain %91 %34 %90 +%92 = OpLoad %8 %89 +%87 = OpIEqual %40 %88 %92 +OpSelectionMerge %93 None +OpBranchConditional %87 %94 %95 +%94 = OpLabel +OpBranch %81 +%95 = OpLabel +OpBranch %93 +%93 = OpLabel +%98 = OpAccessChain %100 %47 %99 +%101 = OpLoad %8 %26 +%97 = OpAccessChain %102 %98 %101 +%96 = OpAccessChain %104 %97 %103 +%105 = OpLoad %15 %96 +OpStore %24 %105 +%108 = OpAccessChain %110 %47 %109 +%111 = OpLoad %8 %26 +%107 = OpAccessChain %112 %108 %111 +%106 = OpAccessChain %114 %107 %113 +%115 = OpLoad %15 %106 +OpStore %25 %115 +%117 = OpLoad %15 %24 +%118 = OpLoad %15 %14 +%119 = OpExtInst %5 %1 Distance %117 %118 +%120 = OpAccessChain %125 %121 %124 +%126 = OpLoad %5 %120 +%116 = OpFOrdLessThan %40 %119 %126 +OpSelectionMerge %127 None +OpBranchConditional %116 %128 %129 +%128 = OpLabel +%131 = OpLoad %15 %18 +%132 = OpLoad %15 %24 +%130 = OpFAdd %15 %131 %132 +OpStore %18 %130 +%134 = OpLoad %3 %21 +%133 = OpIAdd %3 %134 %9 +OpStore %21 %133 +OpBranch %127 +%129 = OpLabel +OpBranch %127 +%127 = OpLabel +%136 = OpLoad %15 %24 +%137 = OpLoad %15 %14 +%138 = OpExtInst %5 %1 Distance %136 %137 +%139 = OpAccessChain %141 %121 %140 +%142 = OpLoad %5 %139 +%135 = OpFOrdLessThan %40 %138 %142 +OpSelectionMerge %143 None +OpBranchConditional %135 %144 %145 +%144 = OpLabel +%147 = OpLoad %15 %20 +%149 = OpLoad %15 %24 +%150 = OpLoad %15 %14 +%148 = OpFSub %15 %149 %150 +%146 = OpFSub %15 %147 %148 +OpStore %20 %146 +OpBranch %143 +%145 = OpLabel +OpBranch %143 +%143 = OpLabel +%152 = OpLoad %15 %24 +%153 = OpLoad %15 %14 +%154 = OpExtInst %5 %1 Distance %152 %153 +%155 = OpAccessChain %157 %121 %156 +%158 = OpLoad %5 %155 +%151 = OpFOrdLessThan %40 %154 %158 +OpSelectionMerge %159 None +OpBranchConditional %151 %160 %161 +%160 = OpLabel +%163 = OpLoad %15 %19 +%164 = OpLoad %15 %25 +%162 = OpFAdd %15 %163 %164 +OpStore %19 %162 +%166 = OpLoad %3 %23 +%165 = OpIAdd %3 %166 %9 +OpStore %23 %165 +OpBranch %159 +%161 = OpLabel +OpBranch %159 +%159 = OpLabel +OpBranch %81 +%81 = OpLabel +%168 = OpLoad %8 %26 +%167 = OpIAdd %8 %168 %10 +OpStore %26 %167 +OpBranch %78 %79 = OpLabel -%83 = OpLoad %19 %17 -%84 = OpAccessChain %86 %27 %85 -%87 = OpLoad %19 %84 -%82 = OpIEqual %34 %83 %87 -OpSelectionMerge %88 None -OpBranchConditional %82 %89 %90 -%89 = OpLabel -OpBranch %76 -%90 = OpLabel -OpBranch %88 -%88 = OpLabel -%93 = OpAccessChain %95 %41 %94 -%96 = OpLoad %19 %17 -%92 = OpAccessChain %97 %93 %96 -%91 = OpAccessChain %99 %92 %98 -%100 = OpLoad %3 %91 -OpStore %15 %100 -%103 = OpAccessChain %105 %41 %104 -%106 = OpLoad %19 %17 -%102 = OpAccessChain %107 %103 %106 -%101 = OpAccessChain %109 %102 %108 -%110 = OpLoad %3 %101 -OpStore %16 %110 -%112 = OpLoad %3 %15 -%113 = OpLoad %3 %2 -%114 = OpExtInst %4 %1 Distance %112 %113 -%115 = OpAccessChain %120 %116 %119 -%121 = OpLoad %4 %115 -%111 = OpFOrdLessThan %34 %114 %121 -OpSelectionMerge %122 None -OpBranchConditional %111 %123 %124 -%123 = OpLabel -%126 = OpLoad %3 %7 -%127 = OpLoad %3 %15 -%125 = OpFAdd %3 %126 %127 -OpStore %7 %125 -%129 = OpLoad %12 %10 -%128 = OpIAdd %12 %129 %130 -OpStore %10 %128 -OpBranch %122 -%124 = OpLabel -OpBranch %122 -%122 = OpLabel -%132 = OpLoad %3 %15 -%133 = OpLoad %3 %2 -%134 = OpExtInst %4 %1 Distance %132 %133 -%135 = OpAccessChain %137 %116 %136 -%138 = OpLoad %4 %135 -%131 = OpFOrdLessThan %34 %134 %138 -OpSelectionMerge %139 None -OpBranchConditional %131 %140 %141 -%140 = OpLabel -%143 = OpLoad %3 %9 -%145 = OpLoad %3 %15 -%146 = OpLoad %3 %2 -%144 = OpFSub %3 %145 %146 -%142 = OpFSub %3 %143 %144 -OpStore %9 %142 -OpBranch %139 -%141 = OpLabel -OpBranch %139 -%139 = OpLabel -%148 = OpLoad %3 %15 -%149 = OpLoad %3 %2 -%150 = OpExtInst %4 %1 Distance %148 %149 -%151 = OpAccessChain %153 %116 %152 -%154 = OpLoad %4 %151 -%147 = OpFOrdLessThan %34 %150 %154 -OpSelectionMerge %155 None -OpBranchConditional %147 %156 %157 -%156 = OpLabel -%159 = OpLoad %3 %8 -%160 = OpLoad %3 %16 -%158 = OpFAdd %3 %159 %160 -OpStore %8 %158 -%162 = OpLoad %12 %14 -%161 = OpIAdd %12 %162 %130 -OpStore %14 %161 -OpBranch %155 -%157 = OpLabel -OpBranch %155 -%155 = OpLabel -OpBranch %76 -%76 = OpLabel -%164 = OpLoad %19 %17 -%163 = OpIAdd %19 %164 %165 -OpStore %17 %163 -OpBranch %73 -%74 = OpLabel -%167 = OpLoad %12 %10 -%166 = OpSGreaterThan %34 %167 %11 -OpSelectionMerge %168 None -OpBranchConditional %166 %169 %170 -%169 = OpLabel -%173 = OpLoad %3 %7 -%176 = OpLoad %12 %10 -%177 = OpConvertSToF %4 %176 -%174 = OpFDiv %4 %175 %177 -%172 = OpVectorTimesScalar %3 %173 %174 -%178 = OpLoad %3 %2 -%171 = OpFSub %3 %172 %178 -OpStore %7 %171 -OpBranch %168 -%170 = OpLabel -OpBranch %168 -%168 = OpLabel -%180 = OpLoad %12 %14 -%179 = OpSGreaterThan %34 %180 %11 -OpSelectionMerge %181 None -OpBranchConditional %179 %182 %183 -%182 = OpLabel -%185 = OpLoad %3 %8 -%187 = OpLoad %12 %14 -%188 = OpConvertSToF %4 %187 -%186 = OpFDiv %4 %175 %188 -%184 = OpVectorTimesScalar %3 %185 %186 -OpStore %8 %184 -OpBranch %181 +%170 = OpLoad %3 %21 +%169 = OpSGreaterThan %40 %170 %6 +OpSelectionMerge %171 None +OpBranchConditional %169 %172 %173 +%172 = OpLabel +%176 = OpLoad %15 %18 +%178 = OpLoad %3 %21 +%179 = OpConvertSToF %5 %178 +%177 = OpFDiv %5 %11 %179 +%175 = OpVectorTimesScalar %15 %176 %177 +%180 = OpLoad %15 %14 +%174 = OpFSub %15 %175 %180 +OpStore %18 %174 +OpBranch %171 +%173 = OpLabel +OpBranch %171 +%171 = OpLabel +%182 = OpLoad %3 %23 +%181 = OpSGreaterThan %40 %182 %6 +OpSelectionMerge %183 None +OpBranchConditional %181 %184 %185 +%184 = OpLabel +%187 = OpLoad %15 %19 +%189 = OpLoad %3 %23 +%190 = OpConvertSToF %5 %189 +%188 = OpFDiv %5 %11 %190 +%186 = OpVectorTimesScalar %15 %187 %188 +OpStore %19 %186 +OpBranch %183 +%185 = OpLabel +OpBranch %183 %183 = OpLabel -OpBranch %181 -%181 = OpLabel -%192 = OpLoad %3 %6 -%194 = OpLoad %3 %7 -%195 = OpAccessChain %197 %116 %196 -%198 = OpLoad %4 %195 -%193 = OpVectorTimesScalar %3 %194 %198 -%191 = OpFAdd %3 %192 %193 -%200 = OpLoad %3 %9 -%201 = OpAccessChain %203 %116 %202 -%204 = OpLoad %4 %201 -%199 = OpVectorTimesScalar %3 %200 %204 -%190 = OpFAdd %3 %191 %199 -%206 = OpLoad %3 %8 -%207 = OpAccessChain %209 %116 %208 -%210 = OpLoad %4 %207 -%205 = OpVectorTimesScalar %3 %206 %210 -%189 = OpFAdd %3 %190 %205 -OpStore %6 %189 -%212 = OpLoad %3 %6 -%213 = OpExtInst %3 %1 Normalize %212 -%214 = OpLoad %3 %6 -%215 = OpExtInst %4 %1 Length %214 -%217 = OpExtInst %4 %1 FClamp %215 %69 %216 -%211 = OpVectorTimesScalar %3 %213 %217 -OpStore %6 %211 -%219 = OpLoad %3 %2 -%221 = OpLoad %3 %6 -%222 = OpAccessChain %224 %116 %223 -%225 = OpLoad %4 %222 -%220 = OpVectorTimesScalar %3 %221 %225 -%218 = OpFAdd %3 %219 %220 -OpStore %2 %218 -%227 = OpAccessChain %229 %2 %228 -%230 = OpLoad %4 %227 -%226 = OpFOrdLessThan %34 %230 %231 +%194 = OpLoad %15 %17 +%196 = OpLoad %15 %18 +%197 = OpAccessChain %199 %121 %198 +%200 = OpLoad %5 %197 +%195 = OpVectorTimesScalar %15 %196 %200 +%193 = OpFAdd %15 %194 %195 +%202 = OpLoad %15 %20 +%203 = OpAccessChain %205 %121 %204 +%206 = OpLoad %5 %203 +%201 = OpVectorTimesScalar %15 %202 %206 +%192 = OpFAdd %15 %193 %201 +%208 = OpLoad %15 %19 +%209 = OpAccessChain %211 %121 %210 +%212 = OpLoad %5 %209 +%207 = OpVectorTimesScalar %15 %208 %212 +%191 = OpFAdd %15 %192 %207 +OpStore %17 %191 +%214 = OpLoad %15 %17 +%215 = OpExtInst %15 %1 Normalize %214 +%216 = OpLoad %15 %17 +%217 = OpExtInst %5 %1 Length %216 +%218 = OpExtInst %5 %1 FClamp %217 %4 %12 +%213 = OpVectorTimesScalar %15 %215 %218 +OpStore %17 %213 +%220 = OpLoad %15 %14 +%222 = OpLoad %15 %17 +%223 = OpAccessChain %225 %121 %224 +%226 = OpLoad %5 %223 +%221 = OpVectorTimesScalar %15 %222 %226 +%219 = OpFAdd %15 %220 %221 +OpStore %14 %219 +%228 = OpAccessChain %230 %14 %229 +%231 = OpLoad %5 %228 +%227 = OpFOrdLessThan %40 %231 %13 OpSelectionMerge %232 None -OpBranchConditional %226 %233 %234 +OpBranchConditional %227 %233 %234 %233 = OpLabel -%235 = OpAccessChain %237 %2 %236 -OpStore %235 %175 +%235 = OpAccessChain %237 %14 %236 +OpStore %235 %11 OpBranch %232 %234 = OpLabel OpBranch %232 %232 = OpLabel -%239 = OpAccessChain %241 %2 %240 -%242 = OpLoad %4 %239 -%238 = OpFOrdGreaterThan %34 %242 %175 +%239 = OpAccessChain %241 %14 %240 +%242 = OpLoad %5 %239 +%238 = OpFOrdGreaterThan %40 %242 %11 OpSelectionMerge %243 None OpBranchConditional %238 %244 %245 %244 = OpLabel -%246 = OpAccessChain %248 %2 %247 -OpStore %246 %231 +%246 = OpAccessChain %248 %14 %247 +OpStore %246 %13 OpBranch %243 %245 = OpLabel OpBranch %243 %243 = OpLabel -%250 = OpAccessChain %252 %2 %251 -%253 = OpLoad %4 %250 -%249 = OpFOrdLessThan %34 %253 %231 +%250 = OpAccessChain %252 %14 %251 +%253 = OpLoad %5 %250 +%249 = OpFOrdLessThan %40 %253 %13 OpSelectionMerge %254 None OpBranchConditional %249 %255 %256 %255 = OpLabel -%257 = OpAccessChain %259 %2 %258 -OpStore %257 %175 +%257 = OpAccessChain %259 %14 %258 +OpStore %257 %11 OpBranch %254 %256 = OpLabel OpBranch %254 %254 = OpLabel -%261 = OpAccessChain %263 %2 %262 -%264 = OpLoad %4 %261 -%260 = OpFOrdGreaterThan %34 %264 %175 +%261 = OpAccessChain %263 %14 %262 +%264 = OpLoad %5 %261 +%260 = OpFOrdGreaterThan %40 %264 %11 OpSelectionMerge %265 None OpBranchConditional %260 %266 %267 %266 = OpLabel -%268 = OpAccessChain %270 %2 %269 -OpStore %268 %231 +%268 = OpAccessChain %270 %14 %269 +OpStore %268 %13 OpBranch %265 %267 = OpLabel OpBranch %265 %265 = OpLabel %273 = OpAccessChain %276 %274 %275 -%277 = OpAccessChain %279 %27 %278 -%280 = OpLoad %19 %277 +%277 = OpAccessChain %279 %34 %278 +%280 = OpLoad %8 %277 %272 = OpAccessChain %281 %273 %280 %271 = OpAccessChain %283 %272 %282 -%284 = OpLoad %3 %2 +%284 = OpLoad %15 %14 OpStore %271 %284 %287 = OpAccessChain %289 %274 %288 -%290 = OpAccessChain %292 %27 %291 -%293 = OpLoad %19 %290 +%290 = OpAccessChain %292 %34 %291 +%293 = OpLoad %8 %290 %286 = OpAccessChain %294 %287 %293 %285 = OpAccessChain %296 %286 %295 -%297 = OpLoad %3 %6 +%297 = OpLoad %15 %17 OpStore %285 %297 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__collatz.spvasm.snap b/tests/snapshots/snapshots__collatz.spvasm.snap index 5f789ffe7..b2d30f32d 100644 --- a/tests/snapshots/snapshots__collatz.spvasm.snap +++ b/tests/snapshots/snapshots__collatz.spvasm.snap @@ -18,13 +18,13 @@ OpDecorate %44 DescriptorSet 0 OpDecorate %44 Binding 0 OpDecorate %52 BuiltIn GlobalInvocationId %3 = OpTypeInt 32 0 -%4 = OpTypePointer Function %3 -%6 = OpConstant %3 0 -%9 = OpTypeFunction %3 %3 -%17 = OpConstant %3 1 -%18 = OpTypeBool -%25 = OpConstant %3 2 -%33 = OpConstant %3 3 +%2 = OpConstant %3 0 +%4 = OpConstant %3 1 +%5 = OpConstant %3 2 +%6 = OpConstant %3 3 +%8 = OpTypePointer Function %3 +%12 = OpTypeFunction %3 %3 +%20 = OpTypeBool %38 = OpTypeVoid %40 = OpTypeFunction %38 %46 = OpTypeRuntimeArray %3 @@ -45,51 +45,51 @@ OpDecorate %52 BuiltIn GlobalInvocationId %65 = OpConstant %48 0 %66 = OpTypePointer Input %3 %68 = OpTypePointer Uniform %3 -%8 = OpFunction %3 None %9 -%7 = OpFunctionParameter %3 -%10 = OpLabel -%2 = OpVariable %4 Function -%5 = OpVariable %4 Function %6 -OpStore %2 %7 -OpBranch %11 -%11 = OpLabel -OpLoopMerge %12 %14 None -OpBranch %13 +%11 = OpFunction %3 None %12 +%10 = OpFunctionParameter %3 %13 = OpLabel -%16 = OpLoad %3 %2 -%15 = OpULessThanEqual %18 %16 %17 -OpSelectionMerge %19 None -OpBranchConditional %15 %20 %21 -%20 = OpLabel -OpBranch %12 -%21 = OpLabel -OpBranch %19 -%19 = OpLabel -%24 = OpLoad %3 %2 -%23 = OpUMod %3 %24 %25 -%22 = OpIEqual %18 %23 %6 -OpSelectionMerge %26 None -OpBranchConditional %22 %27 %28 -%27 = OpLabel -%30 = OpLoad %3 %2 -%29 = OpUDiv %3 %30 %25 -OpStore %2 %29 -OpBranch %26 -%28 = OpLabel -%34 = OpLoad %3 %2 -%32 = OpIMul %3 %33 %34 -%31 = OpIAdd %3 %32 %17 -OpStore %2 %31 -OpBranch %26 -%26 = OpLabel -%36 = OpLoad %3 %5 -%35 = OpIAdd %3 %36 %17 -OpStore %5 %35 +%7 = OpVariable %8 Function +%9 = OpVariable %8 Function %2 +OpStore %7 %10 OpBranch %14 %14 = OpLabel -OpBranch %11 -%12 = OpLabel -%37 = OpLoad %3 %5 +OpLoopMerge %15 %17 None +OpBranch %16 +%16 = OpLabel +%19 = OpLoad %3 %7 +%18 = OpULessThanEqual %20 %19 %4 +OpSelectionMerge %21 None +OpBranchConditional %18 %22 %23 +%22 = OpLabel +OpBranch %15 +%23 = OpLabel +OpBranch %21 +%21 = OpLabel +%26 = OpLoad %3 %7 +%25 = OpUMod %3 %26 %5 +%24 = OpIEqual %20 %25 %2 +OpSelectionMerge %27 None +OpBranchConditional %24 %28 %29 +%28 = OpLabel +%31 = OpLoad %3 %7 +%30 = OpUDiv %3 %31 %5 +OpStore %7 %30 +OpBranch %27 +%29 = OpLabel +%34 = OpLoad %3 %7 +%33 = OpIMul %3 %6 %34 +%32 = OpIAdd %3 %33 %4 +OpStore %7 %32 +OpBranch %27 +%27 = OpLabel +%36 = OpLoad %3 %9 +%35 = OpIAdd %3 %36 %4 +OpStore %9 %35 +OpBranch %17 +%17 = OpLabel +OpBranch %14 +%15 = OpLabel +%37 = OpLoad %3 %9 OpReturnValue %37 OpFunctionEnd %39 = OpFunction %38 None %40 @@ -103,7 +103,7 @@ OpFunctionEnd %67 = OpLoad %3 %64 %60 = OpAccessChain %68 %61 %67 %69 = OpLoad %3 %60 -%59 = OpFunctionCall %3 %8 %69 +%59 = OpFunctionCall %3 %11 %69 OpStore %42 %59 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__quad.spvasm.snap b/tests/snapshots/snapshots__quad.spvasm.snap index bfeeb453a..145c7399a 100644 --- a/tests/snapshots/snapshots__quad.spvasm.snap +++ b/tests/snapshots/snapshots__quad.spvasm.snap @@ -9,60 +9,60 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %3 "main" %18 %10 %6 %13 +OpEntryPoint Vertex %7 "main" %20 %13 %10 %16 OpEntryPoint Fragment %23 "main" %35 %25 OpExecutionMode %23 OriginUpperLeft -OpDecorate %6 Location 0 -OpDecorate %10 Location 1 -OpDecorate %13 BuiltIn Position -OpDecorate %18 Location 0 +OpDecorate %10 Location 0 +OpDecorate %13 Location 1 +OpDecorate %16 BuiltIn Position +OpDecorate %20 Location 0 OpDecorate %25 Location 0 OpDecorate %26 DescriptorSet 0 OpDecorate %26 Binding 0 OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 1 OpDecorate %35 Location 0 -%2 = OpTypeVoid -%4 = OpTypeFunction %2 -%8 = OpTypeFloat 32 -%7 = OpTypeVector %8 2 -%9 = OpTypePointer Output %7 -%6 = OpVariable %9 Output -%11 = OpTypePointer Input %7 -%10 = OpVariable %11 Input -%14 = OpTypeVector %8 4 -%15 = OpTypePointer Output %14 -%13 = OpVariable %15 Output -%17 = OpConstant %8 1.2 -%18 = OpVariable %11 Input -%20 = OpConstant %8 0.0 -%21 = OpConstant %8 1.0 -%25 = OpVariable %15 Output -%27 = OpTypeImage %8 2D 0 0 0 1 Unknown +%3 = OpTypeFloat 32 +%2 = OpConstant %3 1.2 +%4 = OpConstant %3 0.0 +%5 = OpConstant %3 1.0 +%6 = OpTypeVoid +%8 = OpTypeFunction %6 +%11 = OpTypeVector %3 2 +%12 = OpTypePointer Output %11 +%10 = OpVariable %12 Output +%14 = OpTypePointer Input %11 +%13 = OpVariable %14 Input +%17 = OpTypeVector %3 4 +%18 = OpTypePointer Output %17 +%16 = OpVariable %18 Output +%20 = OpVariable %14 Input +%25 = OpVariable %18 Output +%27 = OpTypeImage %3 2D 0 0 0 1 Unknown %28 = OpTypePointer UniformConstant %27 %26 = OpVariable %28 UniformConstant %30 = OpTypeSampledImage %27 %32 = OpTypeSampler %33 = OpTypePointer UniformConstant %32 %31 = OpVariable %33 UniformConstant -%35 = OpVariable %11 Input -%3 = OpFunction %2 None %4 -%5 = OpLabel -%12 = OpLoad %7 %10 -OpStore %6 %12 -%19 = OpLoad %7 %18 -%16 = OpVectorTimesScalar %7 %19 %17 -%22 = OpCompositeConstruct %14 %16 %20 %21 -OpStore %13 %22 +%35 = OpVariable %14 Input +%7 = OpFunction %6 None %8 +%9 = OpLabel +%15 = OpLoad %11 %13 +OpStore %10 %15 +%21 = OpLoad %11 %20 +%19 = OpVectorTimesScalar %11 %21 %2 +%22 = OpCompositeConstruct %17 %19 %4 %5 +OpStore %16 %22 OpReturn OpFunctionEnd -%23 = OpFunction %2 None %4 +%23 = OpFunction %6 None %8 %24 = OpLabel %29 = OpLoad %27 %26 %34 = OpLoad %32 %31 -%36 = OpLoad %7 %35 +%36 = OpLoad %11 %35 %37 = OpSampledImage %30 %29 %34 -%38 = OpImageSampleImplicitLod %14 %37 %36 +%38 = OpImageSampleImplicitLod %17 %37 %36 OpStore %25 %38 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap index e699d3d0c..6e7ae4f4f 100644 --- a/tests/snapshots/snapshots__shadow.spvasm.snap +++ b/tests/snapshots/snapshots__shadow.spvasm.snap @@ -9,266 +9,266 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %60 "fs_main" %112 %109 %216 -OpExecutionMode %60 OriginUpperLeft -OpDecorate %18 DescriptorSet 0 -OpDecorate %18 Binding 2 -OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 3 -OpDecorate %72 Block -OpMemberDecorate %72 0 Offset 0 -OpDecorate %71 DescriptorSet 0 -OpDecorate %71 Binding 0 -OpDecorate %97 BufferBlock -OpMemberDecorate %97 0 Offset 0 -OpMemberDecorate %97 0 NonWritable -OpDecorate %98 ArrayStride 96 -OpDecorate %99 Block -OpMemberDecorate %99 0 Offset 0 -OpMemberDecorate %99 0 ColMajor -OpMemberDecorate %99 0 MatrixStride 16 -OpMemberDecorate %99 1 Offset 64 -OpMemberDecorate %99 2 Offset 80 -OpDecorate %96 DescriptorSet 0 -OpDecorate %96 Binding 1 -OpDecorate %109 Location 1 -OpDecorate %112 Location 0 +OpEntryPoint Fragment %62 "fs_main" %113 %110 %216 +OpExecutionMode %62 OriginUpperLeft +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 2 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 3 +OpDecorate %74 Block +OpMemberDecorate %74 0 Offset 0 +OpDecorate %73 DescriptorSet 0 +OpDecorate %73 Binding 0 +OpDecorate %98 BufferBlock +OpMemberDecorate %98 0 Offset 0 +OpMemberDecorate %98 0 NonWritable +OpDecorate %99 ArrayStride 96 +OpDecorate %100 Block +OpMemberDecorate %100 0 Offset 0 +OpMemberDecorate %100 0 ColMajor +OpMemberDecorate %100 0 MatrixStride 16 +OpMemberDecorate %100 1 Offset 64 +OpMemberDecorate %100 2 Offset 80 +OpDecorate %97 DescriptorSet 0 +OpDecorate %97 Binding 1 +OpDecorate %110 Location 1 +OpDecorate %113 Location 0 OpDecorate %216 Location 0 -%2 = OpTypeFloat 32 -%4 = OpTypeInt 32 0 -%6 = OpTypeVector %2 4 -%8 = OpTypeFunction %2 %4 %6 -%12 = OpConstant %2 0.0 -%13 = OpTypeBool -%17 = OpConstant %2 1.0 -%19 = OpTypeImage %2 2D 1 1 0 1 Unknown -%20 = OpTypePointer UniformConstant %19 -%18 = OpVariable %20 UniformConstant -%22 = OpTypeSampledImage %19 -%24 = OpTypeSampler -%25 = OpTypePointer UniformConstant %24 -%23 = OpVariable %25 UniformConstant -%30 = OpTypeVector %2 2 -%34 = OpConstant %2 0.5 -%35 = OpConstant %2 -0.5 -%43 = OpTypeVector %2 3 -%51 = OpConstant %2 0.0 -%54 = OpConstant %2 0.05 -%53 = OpConstantComposite %43 %54 %54 %54 -%55 = OpTypePointer Function %43 -%57 = OpConstant %4 0 -%58 = OpTypePointer Function %4 -%59 = OpTypeVoid -%61 = OpTypeFunction %59 -%73 = OpTypeVector %4 4 -%72 = OpTypeStruct %73 -%74 = OpTypePointer Uniform %72 -%71 = OpVariable %74 Uniform -%75 = OpTypeInt 32 1 -%76 = OpConstant %75 0 -%77 = OpTypePointer Uniform %73 -%78 = OpConstant %75 0 -%79 = OpTypePointer Uniform %4 -%81 = OpConstant %4 10 -%100 = OpTypeMatrix %6 4 -%99 = OpTypeStruct %100 %6 %6 -%98 = OpTypeRuntimeArray %99 -%97 = OpTypeStruct %98 -%101 = OpTypePointer Uniform %97 -%96 = OpVariable %101 Uniform -%102 = OpConstant %75 0 -%103 = OpTypePointer Uniform %98 -%105 = OpTypePointer Uniform %99 -%106 = OpConstant %75 0 -%107 = OpTypePointer Uniform %100 -%110 = OpTypePointer Input %6 -%109 = OpVariable %110 Input -%113 = OpTypePointer Input %43 -%112 = OpVariable %113 Input -%121 = OpConstant %75 0 -%122 = OpTypePointer Uniform %98 -%124 = OpTypePointer Uniform %99 -%125 = OpConstant %75 1 -%126 = OpTypePointer Uniform %6 -%127 = OpConstant %75 0 -%128 = OpTypePointer Uniform %2 -%134 = OpConstant %75 0 -%135 = OpTypePointer Uniform %98 -%137 = OpTypePointer Uniform %99 -%138 = OpConstant %75 1 -%139 = OpTypePointer Uniform %6 -%140 = OpConstant %75 1 -%141 = OpTypePointer Uniform %2 -%147 = OpConstant %75 0 -%148 = OpTypePointer Uniform %98 -%150 = OpTypePointer Uniform %99 -%151 = OpConstant %75 1 -%152 = OpTypePointer Uniform %6 -%153 = OpConstant %75 2 -%154 = OpTypePointer Uniform %2 -%158 = OpConstant %75 0 -%159 = OpTypePointer Input %2 -%162 = OpConstant %75 1 -%163 = OpTypePointer Input %2 -%166 = OpConstant %75 2 -%167 = OpTypePointer Input %2 -%177 = OpConstant %75 0 -%178 = OpTypePointer Uniform %98 -%180 = OpTypePointer Uniform %99 -%181 = OpConstant %75 2 -%182 = OpTypePointer Uniform %6 -%183 = OpConstant %75 0 -%184 = OpTypePointer Uniform %2 -%190 = OpConstant %75 0 -%191 = OpTypePointer Uniform %98 -%193 = OpTypePointer Uniform %99 -%194 = OpConstant %75 2 -%195 = OpTypePointer Uniform %6 -%196 = OpConstant %75 1 -%197 = OpTypePointer Uniform %2 -%203 = OpConstant %75 0 -%204 = OpTypePointer Uniform %98 -%206 = OpTypePointer Uniform %99 -%207 = OpConstant %75 2 -%208 = OpTypePointer Uniform %6 -%209 = OpConstant %75 2 -%210 = OpTypePointer Uniform %2 -%215 = OpConstant %4 1 -%217 = OpTypePointer Output %6 +%3 = OpTypeFloat 32 +%2 = OpConstant %3 0.0 +%4 = OpConstant %3 1.0 +%5 = OpConstant %3 0.5 +%6 = OpConstant %3 -0.5 +%7 = OpConstant %3 0.05 +%9 = OpTypeVector %3 3 +%8 = OpConstantComposite %9 %7 %7 %7 +%11 = OpTypeInt 32 0 +%10 = OpConstant %11 10 +%12 = OpConstant %11 0 +%13 = OpConstant %11 1 +%16 = OpTypeVector %3 4 +%18 = OpTypeFunction %3 %11 %16 +%22 = OpTypeBool +%27 = OpTypeImage %3 2D 1 1 0 1 Unknown +%28 = OpTypePointer UniformConstant %27 +%26 = OpVariable %28 UniformConstant +%30 = OpTypeSampledImage %27 +%32 = OpTypeSampler +%33 = OpTypePointer UniformConstant %32 +%31 = OpVariable %33 UniformConstant +%38 = OpTypeVector %3 2 +%56 = OpConstant %3 0.0 +%58 = OpTypePointer Function %9 +%60 = OpTypePointer Function %11 +%61 = OpTypeVoid +%63 = OpTypeFunction %61 +%75 = OpTypeVector %11 4 +%74 = OpTypeStruct %75 +%76 = OpTypePointer Uniform %74 +%73 = OpVariable %76 Uniform +%77 = OpTypeInt 32 1 +%78 = OpConstant %77 0 +%79 = OpTypePointer Uniform %75 +%80 = OpConstant %77 0 +%81 = OpTypePointer Uniform %11 +%101 = OpTypeMatrix %16 4 +%100 = OpTypeStruct %101 %16 %16 +%99 = OpTypeRuntimeArray %100 +%98 = OpTypeStruct %99 +%102 = OpTypePointer Uniform %98 +%97 = OpVariable %102 Uniform +%103 = OpConstant %77 0 +%104 = OpTypePointer Uniform %99 +%106 = OpTypePointer Uniform %100 +%107 = OpConstant %77 0 +%108 = OpTypePointer Uniform %101 +%111 = OpTypePointer Input %16 +%110 = OpVariable %111 Input +%114 = OpTypePointer Input %9 +%113 = OpVariable %114 Input +%122 = OpConstant %77 0 +%123 = OpTypePointer Uniform %99 +%125 = OpTypePointer Uniform %100 +%126 = OpConstant %77 1 +%127 = OpTypePointer Uniform %16 +%128 = OpConstant %77 0 +%129 = OpTypePointer Uniform %3 +%135 = OpConstant %77 0 +%136 = OpTypePointer Uniform %99 +%138 = OpTypePointer Uniform %100 +%139 = OpConstant %77 1 +%140 = OpTypePointer Uniform %16 +%141 = OpConstant %77 1 +%142 = OpTypePointer Uniform %3 +%148 = OpConstant %77 0 +%149 = OpTypePointer Uniform %99 +%151 = OpTypePointer Uniform %100 +%152 = OpConstant %77 1 +%153 = OpTypePointer Uniform %16 +%154 = OpConstant %77 2 +%155 = OpTypePointer Uniform %3 +%159 = OpConstant %77 0 +%160 = OpTypePointer Input %3 +%163 = OpConstant %77 1 +%164 = OpTypePointer Input %3 +%167 = OpConstant %77 2 +%168 = OpTypePointer Input %3 +%178 = OpConstant %77 0 +%179 = OpTypePointer Uniform %99 +%181 = OpTypePointer Uniform %100 +%182 = OpConstant %77 2 +%183 = OpTypePointer Uniform %16 +%184 = OpConstant %77 0 +%185 = OpTypePointer Uniform %3 +%191 = OpConstant %77 0 +%192 = OpTypePointer Uniform %99 +%194 = OpTypePointer Uniform %100 +%195 = OpConstant %77 2 +%196 = OpTypePointer Uniform %16 +%197 = OpConstant %77 1 +%198 = OpTypePointer Uniform %3 +%204 = OpConstant %77 0 +%205 = OpTypePointer Uniform %99 +%207 = OpTypePointer Uniform %100 +%208 = OpConstant %77 2 +%209 = OpTypePointer Uniform %16 +%210 = OpConstant %77 2 +%211 = OpTypePointer Uniform %3 +%217 = OpTypePointer Output %16 %216 = OpVariable %217 Output -%7 = OpFunction %2 None %8 -%3 = OpFunctionParameter %4 -%5 = OpFunctionParameter %6 -%9 = OpLabel -%11 = OpCompositeExtract %2 %5 3 -%10 = OpFOrdLessThanEqual %13 %11 %12 -OpSelectionMerge %14 None -OpBranchConditional %10 %15 %16 -%15 = OpLabel -OpReturnValue %17 -%16 = OpLabel -OpBranch %14 -%14 = OpLabel -%21 = OpLoad %19 %18 -%26 = OpLoad %24 %23 -%31 = OpCompositeExtract %2 %5 0 -%32 = OpCompositeExtract %2 %5 1 -%33 = OpCompositeConstruct %30 %31 %32 -%36 = OpCompositeConstruct %30 %34 %35 -%29 = OpFMul %30 %33 %36 -%38 = OpCompositeExtract %2 %5 3 -%37 = OpFDiv %2 %17 %38 -%28 = OpVectorTimesScalar %30 %29 %37 -%39 = OpCompositeConstruct %30 %34 %34 -%27 = OpFAdd %30 %28 %39 -%40 = OpCompositeExtract %2 %27 0 -%41 = OpCompositeExtract %2 %27 1 -%42 = OpConvertUToF %2 %3 -%44 = OpCompositeConstruct %43 %40 %41 %42 -%45 = OpSampledImage %22 %21 %26 -%48 = OpCompositeExtract %2 %5 2 -%50 = OpCompositeExtract %2 %5 3 -%49 = OpFDiv %2 %17 %50 -%47 = OpFMul %2 %48 %49 -%46 = OpImageSampleDrefExplicitLod %2 %45 %44 %47 Lod %51 -OpReturnValue %46 +%17 = OpFunction %3 None %18 +%14 = OpFunctionParameter %11 +%15 = OpFunctionParameter %16 +%19 = OpLabel +%21 = OpCompositeExtract %3 %15 3 +%20 = OpFOrdLessThanEqual %22 %21 %2 +OpSelectionMerge %23 None +OpBranchConditional %20 %24 %25 +%24 = OpLabel +OpReturnValue %4 +%25 = OpLabel +OpBranch %23 +%23 = OpLabel +%29 = OpLoad %27 %26 +%34 = OpLoad %32 %31 +%39 = OpCompositeExtract %3 %15 0 +%40 = OpCompositeExtract %3 %15 1 +%41 = OpCompositeConstruct %38 %39 %40 +%42 = OpCompositeConstruct %38 %5 %6 +%37 = OpFMul %38 %41 %42 +%44 = OpCompositeExtract %3 %15 3 +%43 = OpFDiv %3 %4 %44 +%36 = OpVectorTimesScalar %38 %37 %43 +%45 = OpCompositeConstruct %38 %5 %5 +%35 = OpFAdd %38 %36 %45 +%46 = OpCompositeExtract %3 %35 0 +%47 = OpCompositeExtract %3 %35 1 +%48 = OpConvertUToF %3 %14 +%49 = OpCompositeConstruct %9 %46 %47 %48 +%50 = OpSampledImage %30 %29 %34 +%53 = OpCompositeExtract %3 %15 2 +%55 = OpCompositeExtract %3 %15 3 +%54 = OpFDiv %3 %4 %55 +%52 = OpFMul %3 %53 %54 +%51 = OpImageSampleDrefExplicitLod %3 %50 %49 %52 Lod %56 +OpReturnValue %51 OpFunctionEnd -%60 = OpFunction %59 None %61 -%62 = OpLabel -%52 = OpVariable %55 Function %53 -%56 = OpVariable %58 Function %57 -OpBranch %63 -%63 = OpLabel -OpLoopMerge %64 %66 None +%62 = OpFunction %61 None %63 +%64 = OpLabel +%57 = OpVariable %58 Function %8 +%59 = OpVariable %60 Function %12 OpBranch %65 %65 = OpLabel -%68 = OpLoad %4 %56 -%70 = OpAccessChain %77 %71 %76 -%69 = OpAccessChain %79 %70 %78 -%80 = OpLoad %4 %69 -%82 = OpExtInst %4 %1 UMin %80 %81 -%67 = OpUGreaterThanEqual %13 %68 %82 -OpSelectionMerge %83 None -OpBranchConditional %67 %84 %85 -%84 = OpLabel -OpBranch %64 +OpLoopMerge %66 %68 None +OpBranch %67 +%67 = OpLabel +%70 = OpLoad %11 %59 +%72 = OpAccessChain %79 %73 %78 +%71 = OpAccessChain %81 %72 %80 +%82 = OpLoad %11 %71 +%83 = OpExtInst %11 %1 UMin %82 %10 +%69 = OpUGreaterThanEqual %22 %70 %83 +OpSelectionMerge %84 None +OpBranchConditional %69 %85 %86 %85 = OpLabel -OpBranch %83 -%83 = OpLabel -%87 = OpLoad %43 %52 -%91 = OpLoad %4 %56 -%95 = OpAccessChain %103 %96 %102 -%104 = OpLoad %4 %56 -%94 = OpAccessChain %105 %95 %104 -%93 = OpAccessChain %107 %94 %106 -%108 = OpLoad %100 %93 -%111 = OpLoad %6 %109 -%92 = OpMatrixTimesVector %6 %108 %111 -%90 = OpFunctionCall %2 %7 %91 %92 -%114 = OpLoad %43 %112 -%115 = OpExtInst %43 %1 Normalize %114 -%120 = OpAccessChain %122 %96 %121 -%123 = OpLoad %4 %56 -%119 = OpAccessChain %124 %120 %123 -%118 = OpAccessChain %126 %119 %125 -%117 = OpAccessChain %128 %118 %127 -%129 = OpLoad %2 %117 -%133 = OpAccessChain %135 %96 %134 -%136 = OpLoad %4 %56 -%132 = OpAccessChain %137 %133 %136 -%131 = OpAccessChain %139 %132 %138 -%130 = OpAccessChain %141 %131 %140 -%142 = OpLoad %2 %130 -%146 = OpAccessChain %148 %96 %147 -%149 = OpLoad %4 %56 -%145 = OpAccessChain %150 %146 %149 -%144 = OpAccessChain %152 %145 %151 -%143 = OpAccessChain %154 %144 %153 -%155 = OpLoad %2 %143 -%156 = OpCompositeConstruct %43 %129 %142 %155 -%157 = OpAccessChain %159 %109 %158 -%160 = OpLoad %2 %157 -%161 = OpAccessChain %163 %109 %162 -%164 = OpLoad %2 %161 -%165 = OpAccessChain %167 %109 %166 -%168 = OpLoad %2 %165 -%169 = OpCompositeConstruct %43 %160 %164 %168 -%116 = OpFSub %43 %156 %169 -%170 = OpExtInst %43 %1 Normalize %116 -%171 = OpDot %2 %115 %170 -%172 = OpExtInst %2 %1 FMax %12 %171 -%89 = OpFMul %2 %90 %172 -%176 = OpAccessChain %178 %96 %177 -%179 = OpLoad %4 %56 -%175 = OpAccessChain %180 %176 %179 -%174 = OpAccessChain %182 %175 %181 -%173 = OpAccessChain %184 %174 %183 -%185 = OpLoad %2 %173 -%189 = OpAccessChain %191 %96 %190 -%192 = OpLoad %4 %56 -%188 = OpAccessChain %193 %189 %192 -%187 = OpAccessChain %195 %188 %194 -%186 = OpAccessChain %197 %187 %196 -%198 = OpLoad %2 %186 -%202 = OpAccessChain %204 %96 %203 -%205 = OpLoad %4 %56 -%201 = OpAccessChain %206 %202 %205 -%200 = OpAccessChain %208 %201 %207 -%199 = OpAccessChain %210 %200 %209 -%211 = OpLoad %2 %199 -%212 = OpCompositeConstruct %43 %185 %198 %211 -%88 = OpVectorTimesScalar %43 %212 %89 -%86 = OpFAdd %43 %87 %88 -OpStore %52 %86 OpBranch %66 +%86 = OpLabel +OpBranch %84 +%84 = OpLabel +%88 = OpLoad %9 %57 +%92 = OpLoad %11 %59 +%96 = OpAccessChain %104 %97 %103 +%105 = OpLoad %11 %59 +%95 = OpAccessChain %106 %96 %105 +%94 = OpAccessChain %108 %95 %107 +%109 = OpLoad %101 %94 +%112 = OpLoad %16 %110 +%93 = OpMatrixTimesVector %16 %109 %112 +%91 = OpFunctionCall %3 %17 %92 %93 +%115 = OpLoad %9 %113 +%116 = OpExtInst %9 %1 Normalize %115 +%121 = OpAccessChain %123 %97 %122 +%124 = OpLoad %11 %59 +%120 = OpAccessChain %125 %121 %124 +%119 = OpAccessChain %127 %120 %126 +%118 = OpAccessChain %129 %119 %128 +%130 = OpLoad %3 %118 +%134 = OpAccessChain %136 %97 %135 +%137 = OpLoad %11 %59 +%133 = OpAccessChain %138 %134 %137 +%132 = OpAccessChain %140 %133 %139 +%131 = OpAccessChain %142 %132 %141 +%143 = OpLoad %3 %131 +%147 = OpAccessChain %149 %97 %148 +%150 = OpLoad %11 %59 +%146 = OpAccessChain %151 %147 %150 +%145 = OpAccessChain %153 %146 %152 +%144 = OpAccessChain %155 %145 %154 +%156 = OpLoad %3 %144 +%157 = OpCompositeConstruct %9 %130 %143 %156 +%158 = OpAccessChain %160 %110 %159 +%161 = OpLoad %3 %158 +%162 = OpAccessChain %164 %110 %163 +%165 = OpLoad %3 %162 +%166 = OpAccessChain %168 %110 %167 +%169 = OpLoad %3 %166 +%170 = OpCompositeConstruct %9 %161 %165 %169 +%117 = OpFSub %9 %157 %170 +%171 = OpExtInst %9 %1 Normalize %117 +%172 = OpDot %3 %116 %171 +%173 = OpExtInst %3 %1 FMax %2 %172 +%90 = OpFMul %3 %91 %173 +%177 = OpAccessChain %179 %97 %178 +%180 = OpLoad %11 %59 +%176 = OpAccessChain %181 %177 %180 +%175 = OpAccessChain %183 %176 %182 +%174 = OpAccessChain %185 %175 %184 +%186 = OpLoad %3 %174 +%190 = OpAccessChain %192 %97 %191 +%193 = OpLoad %11 %59 +%189 = OpAccessChain %194 %190 %193 +%188 = OpAccessChain %196 %189 %195 +%187 = OpAccessChain %198 %188 %197 +%199 = OpLoad %3 %187 +%203 = OpAccessChain %205 %97 %204 +%206 = OpLoad %11 %59 +%202 = OpAccessChain %207 %203 %206 +%201 = OpAccessChain %209 %202 %208 +%200 = OpAccessChain %211 %201 %210 +%212 = OpLoad %3 %200 +%213 = OpCompositeConstruct %9 %186 %199 %212 +%89 = OpVectorTimesScalar %9 %213 %90 +%87 = OpFAdd %9 %88 %89 +OpStore %57 %87 +OpBranch %68 +%68 = OpLabel +%215 = OpLoad %11 %59 +%214 = OpIAdd %11 %215 %13 +OpStore %59 %214 +OpBranch %65 %66 = OpLabel -%214 = OpLoad %4 %56 -%213 = OpIAdd %4 %214 %215 -OpStore %56 %213 -OpBranch %63 -%64 = OpLabel -%218 = OpLoad %43 %52 -%219 = OpCompositeConstruct %6 %218 %17 +%218 = OpLoad %9 %57 +%219 = OpCompositeConstruct %16 %218 %4 OpStore %216 %219 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap index 45fdbf18c..6c23904ab 100644 --- a/tests/snapshots/snapshots__skybox.spvasm.snap +++ b/tests/snapshots/snapshots__skybox.spvasm.snap @@ -9,19 +9,19 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %11 "vs_main" %157 %44 %15 +OpEntryPoint Vertex %16 "vs_main" %157 %44 %20 OpEntryPoint Fragment %168 "fs_main" %180 %170 OpExecutionMode %168 OriginUpperLeft -OpDecorate %15 BuiltIn VertexIndex -OpDecorate %26 Block -OpMemberDecorate %26 0 Offset 0 -OpMemberDecorate %26 0 ColMajor -OpMemberDecorate %26 0 MatrixStride 16 -OpMemberDecorate %26 1 Offset 64 -OpMemberDecorate %26 1 ColMajor -OpMemberDecorate %26 1 MatrixStride 16 -OpDecorate %25 DescriptorSet 0 -OpDecorate %25 Binding 0 +OpDecorate %20 BuiltIn VertexIndex +OpDecorate %29 Block +OpMemberDecorate %29 0 Offset 0 +OpMemberDecorate %29 0 ColMajor +OpMemberDecorate %29 0 MatrixStride 16 +OpMemberDecorate %29 1 Offset 64 +OpMemberDecorate %29 1 ColMajor +OpMemberDecorate %29 1 MatrixStride 16 +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 0 OpDecorate %44 Location 0 OpDecorate %157 BuiltIn Position OpDecorate %170 Location 0 @@ -31,94 +31,94 @@ OpDecorate %176 DescriptorSet 0 OpDecorate %176 Binding 2 OpDecorate %180 Location 0 %3 = OpTypeInt 32 1 -%4 = OpTypePointer Function %3 -%8 = OpTypeFloat 32 -%7 = OpTypeVector %8 4 -%9 = OpTypePointer Function %7 -%10 = OpTypeVoid -%12 = OpTypeFunction %10 -%16 = OpTypeInt 32 0 -%17 = OpTypePointer Input %16 -%15 = OpVariable %17 Input -%19 = OpConstant %3 2 -%22 = OpConstant %3 1 -%27 = OpTypeMatrix %7 4 -%26 = OpTypeStruct %27 %27 -%28 = OpTypePointer Uniform %26 -%25 = OpVariable %28 Uniform -%29 = OpConstant %3 0 -%30 = OpTypePointer Uniform %27 -%36 = OpConstant %8 4.0 -%37 = OpConstant %8 1.0 -%42 = OpConstant %8 0.0 -%45 = OpTypeVector %8 3 +%2 = OpConstant %3 2 +%4 = OpConstant %3 1 +%6 = OpTypeFloat 32 +%5 = OpConstant %6 4.0 +%7 = OpConstant %6 1.0 +%8 = OpConstant %6 0.0 +%10 = OpTypePointer Function %3 +%13 = OpTypeVector %6 4 +%14 = OpTypePointer Function %13 +%15 = OpTypeVoid +%17 = OpTypeFunction %15 +%21 = OpTypeInt 32 0 +%22 = OpTypePointer Input %21 +%20 = OpVariable %22 Input +%30 = OpTypeMatrix %13 4 +%29 = OpTypeStruct %30 %30 +%31 = OpTypePointer Uniform %29 +%28 = OpVariable %31 Uniform +%32 = OpConstant %3 0 +%33 = OpTypePointer Uniform %30 +%45 = OpTypeVector %6 3 %46 = OpTypePointer Output %45 %44 = OpVariable %46 Output %48 = OpTypeMatrix %45 3 %52 = OpConstant %3 1 -%53 = OpTypePointer Uniform %27 +%53 = OpTypePointer Uniform %30 %54 = OpConstant %3 0 -%55 = OpTypePointer Uniform %7 +%55 = OpTypePointer Uniform %13 %56 = OpConstant %3 0 -%57 = OpTypePointer Uniform %8 +%57 = OpTypePointer Uniform %6 %62 = OpConstant %3 1 -%63 = OpTypePointer Uniform %27 +%63 = OpTypePointer Uniform %30 %64 = OpConstant %3 0 -%65 = OpTypePointer Uniform %7 +%65 = OpTypePointer Uniform %13 %66 = OpConstant %3 1 -%67 = OpTypePointer Uniform %8 +%67 = OpTypePointer Uniform %6 %72 = OpConstant %3 1 -%73 = OpTypePointer Uniform %27 +%73 = OpTypePointer Uniform %30 %74 = OpConstant %3 0 -%75 = OpTypePointer Uniform %7 +%75 = OpTypePointer Uniform %13 %76 = OpConstant %3 2 -%77 = OpTypePointer Uniform %8 +%77 = OpTypePointer Uniform %6 %83 = OpConstant %3 1 -%84 = OpTypePointer Uniform %27 +%84 = OpTypePointer Uniform %30 %85 = OpConstant %3 1 -%86 = OpTypePointer Uniform %7 +%86 = OpTypePointer Uniform %13 %87 = OpConstant %3 0 -%88 = OpTypePointer Uniform %8 +%88 = OpTypePointer Uniform %6 %93 = OpConstant %3 1 -%94 = OpTypePointer Uniform %27 +%94 = OpTypePointer Uniform %30 %95 = OpConstant %3 1 -%96 = OpTypePointer Uniform %7 +%96 = OpTypePointer Uniform %13 %97 = OpConstant %3 1 -%98 = OpTypePointer Uniform %8 +%98 = OpTypePointer Uniform %6 %103 = OpConstant %3 1 -%104 = OpTypePointer Uniform %27 +%104 = OpTypePointer Uniform %30 %105 = OpConstant %3 1 -%106 = OpTypePointer Uniform %7 +%106 = OpTypePointer Uniform %13 %107 = OpConstant %3 2 -%108 = OpTypePointer Uniform %8 +%108 = OpTypePointer Uniform %6 %114 = OpConstant %3 1 -%115 = OpTypePointer Uniform %27 +%115 = OpTypePointer Uniform %30 %116 = OpConstant %3 2 -%117 = OpTypePointer Uniform %7 +%117 = OpTypePointer Uniform %13 %118 = OpConstant %3 0 -%119 = OpTypePointer Uniform %8 +%119 = OpTypePointer Uniform %6 %124 = OpConstant %3 1 -%125 = OpTypePointer Uniform %27 +%125 = OpTypePointer Uniform %30 %126 = OpConstant %3 2 -%127 = OpTypePointer Uniform %7 +%127 = OpTypePointer Uniform %13 %128 = OpConstant %3 1 -%129 = OpTypePointer Uniform %8 +%129 = OpTypePointer Uniform %6 %134 = OpConstant %3 1 -%135 = OpTypePointer Uniform %27 +%135 = OpTypePointer Uniform %30 %136 = OpConstant %3 2 -%137 = OpTypePointer Uniform %7 +%137 = OpTypePointer Uniform %13 %138 = OpConstant %3 2 -%139 = OpTypePointer Uniform %8 +%139 = OpTypePointer Uniform %6 %145 = OpConstant %3 0 -%146 = OpTypePointer Function %8 +%146 = OpTypePointer Function %6 %149 = OpConstant %3 1 -%150 = OpTypePointer Function %8 +%150 = OpTypePointer Function %6 %153 = OpConstant %3 2 -%154 = OpTypePointer Function %8 -%158 = OpTypePointer Output %7 +%154 = OpTypePointer Function %6 +%158 = OpTypePointer Output %13 %157 = OpVariable %158 Output %170 = OpVariable %158 Output -%172 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%172 = OpTypeImage %6 Cube 0 0 0 1 Unknown %173 = OpTypePointer UniformConstant %172 %171 = OpVariable %173 UniformConstant %175 = OpTypeSampledImage %172 @@ -127,99 +127,99 @@ OpDecorate %180 Location 0 %176 = OpVariable %178 UniformConstant %181 = OpTypePointer Input %45 %180 = OpVariable %181 Input -%11 = OpFunction %10 None %12 -%13 = OpLabel -%2 = OpVariable %4 Function -%5 = OpVariable %4 Function -%6 = OpVariable %9 Function -%18 = OpLoad %16 %15 -%14 = OpSDiv %3 %18 %19 -OpStore %2 %14 -%21 = OpLoad %16 %15 -%20 = OpBitwiseAnd %3 %21 %22 -OpStore %5 %20 -%24 = OpAccessChain %30 %25 %29 -%31 = OpLoad %27 %24 -%34 = OpLoad %3 %2 -%35 = OpConvertSToF %8 %34 -%33 = OpFMul %8 %35 %36 -%32 = OpFSub %8 %33 %37 -%40 = OpLoad %3 %5 -%41 = OpConvertSToF %8 %40 -%39 = OpFMul %8 %41 %36 -%38 = OpFSub %8 %39 %37 -%43 = OpCompositeConstruct %7 %32 %38 %42 %37 -%23 = OpMatrixTimesVector %7 %31 %43 -OpStore %6 %23 -%51 = OpAccessChain %53 %25 %52 +%16 = OpFunction %15 None %17 +%18 = OpLabel +%9 = OpVariable %10 Function +%11 = OpVariable %10 Function +%12 = OpVariable %14 Function +%23 = OpLoad %21 %20 +%19 = OpSDiv %3 %23 %2 +OpStore %9 %19 +%25 = OpLoad %21 %20 +%24 = OpBitwiseAnd %3 %25 %4 +OpStore %11 %24 +%27 = OpAccessChain %33 %28 %32 +%34 = OpLoad %30 %27 +%37 = OpLoad %3 %9 +%38 = OpConvertSToF %6 %37 +%36 = OpFMul %6 %38 %5 +%35 = OpFSub %6 %36 %7 +%41 = OpLoad %3 %11 +%42 = OpConvertSToF %6 %41 +%40 = OpFMul %6 %42 %5 +%39 = OpFSub %6 %40 %7 +%43 = OpCompositeConstruct %13 %35 %39 %8 %7 +%26 = OpMatrixTimesVector %13 %34 %43 +OpStore %12 %26 +%51 = OpAccessChain %53 %28 %52 %50 = OpAccessChain %55 %51 %54 %49 = OpAccessChain %57 %50 %56 -%58 = OpLoad %8 %49 -%61 = OpAccessChain %63 %25 %62 +%58 = OpLoad %6 %49 +%61 = OpAccessChain %63 %28 %62 %60 = OpAccessChain %65 %61 %64 %59 = OpAccessChain %67 %60 %66 -%68 = OpLoad %8 %59 -%71 = OpAccessChain %73 %25 %72 +%68 = OpLoad %6 %59 +%71 = OpAccessChain %73 %28 %72 %70 = OpAccessChain %75 %71 %74 %69 = OpAccessChain %77 %70 %76 -%78 = OpLoad %8 %69 +%78 = OpLoad %6 %69 %79 = OpCompositeConstruct %45 %58 %68 %78 -%82 = OpAccessChain %84 %25 %83 +%82 = OpAccessChain %84 %28 %83 %81 = OpAccessChain %86 %82 %85 %80 = OpAccessChain %88 %81 %87 -%89 = OpLoad %8 %80 -%92 = OpAccessChain %94 %25 %93 +%89 = OpLoad %6 %80 +%92 = OpAccessChain %94 %28 %93 %91 = OpAccessChain %96 %92 %95 %90 = OpAccessChain %98 %91 %97 -%99 = OpLoad %8 %90 -%102 = OpAccessChain %104 %25 %103 +%99 = OpLoad %6 %90 +%102 = OpAccessChain %104 %28 %103 %101 = OpAccessChain %106 %102 %105 %100 = OpAccessChain %108 %101 %107 -%109 = OpLoad %8 %100 +%109 = OpLoad %6 %100 %110 = OpCompositeConstruct %45 %89 %99 %109 -%113 = OpAccessChain %115 %25 %114 +%113 = OpAccessChain %115 %28 %114 %112 = OpAccessChain %117 %113 %116 %111 = OpAccessChain %119 %112 %118 -%120 = OpLoad %8 %111 -%123 = OpAccessChain %125 %25 %124 +%120 = OpLoad %6 %111 +%123 = OpAccessChain %125 %28 %124 %122 = OpAccessChain %127 %123 %126 %121 = OpAccessChain %129 %122 %128 -%130 = OpLoad %8 %121 -%133 = OpAccessChain %135 %25 %134 +%130 = OpLoad %6 %121 +%133 = OpAccessChain %135 %28 %134 %132 = OpAccessChain %137 %133 %136 %131 = OpAccessChain %139 %132 %138 -%140 = OpLoad %8 %131 +%140 = OpLoad %6 %131 %141 = OpCompositeConstruct %45 %120 %130 %140 %142 = OpCompositeConstruct %48 %79 %110 %141 %143 = OpTranspose %48 %142 -%144 = OpAccessChain %146 %6 %145 -%147 = OpLoad %8 %144 -%148 = OpAccessChain %150 %6 %149 -%151 = OpLoad %8 %148 -%152 = OpAccessChain %154 %6 %153 -%155 = OpLoad %8 %152 +%144 = OpAccessChain %146 %12 %145 +%147 = OpLoad %6 %144 +%148 = OpAccessChain %150 %12 %149 +%151 = OpLoad %6 %148 +%152 = OpAccessChain %154 %12 %153 +%155 = OpLoad %6 %152 %156 = OpCompositeConstruct %45 %147 %151 %155 %47 = OpMatrixTimesVector %45 %143 %156 OpStore %44 %47 -%161 = OpLoad %3 %2 -%162 = OpConvertSToF %8 %161 -%160 = OpFMul %8 %162 %36 -%159 = OpFSub %8 %160 %37 -%165 = OpLoad %3 %5 -%166 = OpConvertSToF %8 %165 -%164 = OpFMul %8 %166 %36 -%163 = OpFSub %8 %164 %37 -%167 = OpCompositeConstruct %7 %159 %163 %42 %37 +%161 = OpLoad %3 %9 +%162 = OpConvertSToF %6 %161 +%160 = OpFMul %6 %162 %5 +%159 = OpFSub %6 %160 %7 +%165 = OpLoad %3 %11 +%166 = OpConvertSToF %6 %165 +%164 = OpFMul %6 %166 %5 +%163 = OpFSub %6 %164 %7 +%167 = OpCompositeConstruct %13 %159 %163 %8 %7 OpStore %157 %167 OpReturn OpFunctionEnd -%168 = OpFunction %10 None %12 +%168 = OpFunction %15 None %17 %169 = OpLabel %174 = OpLoad %172 %171 %179 = OpLoad %177 %176 %182 = OpLoad %45 %180 %183 = OpSampledImage %175 %174 %179 -%184 = OpImageSampleImplicitLod %7 %183 %182 +%184 = OpImageSampleImplicitLod %13 %183 %182 OpStore %170 %184 OpReturn OpFunctionEnd From cb36c642eae18fd1793034de0bbb44cbb660554d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 31 Jan 2021 01:56:34 -0500 Subject: [PATCH 0411/2212] [wgsl] refactor constants processing, add support for array sizes --- src/front/wgsl/mod.rs | 234 ++++++++------------- src/proc/validator.rs | 3 +- tests/snapshots/snapshots__quad.msl.snap | 2 - tests/snapshots/snapshots__shadow.msl.snap | 10 +- tests/snapshots/snapshots__skybox.msl.snap | 2 - 5 files changed, 92 insertions(+), 159 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index d9b68c5bc..09d9725d9 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -151,7 +151,6 @@ impl<'a> StatementContext<'a, '_, '_> { struct SamplingContext { image: Handle, arrayed: bool, - offset_type: Handle, } struct ExpressionContext<'input, 'temp, 'out> { @@ -201,35 +200,14 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } - fn prepare_sampling( - &mut self, - image_name: &'a str, - coordinate: Handle, - ) -> Result> { + fn prepare_sampling(&mut self, image_name: &'a str) -> Result> { let image = self.lookup_ident.lookup(image_name)?; - let kind = crate::ScalarKind::Sint; - let offset_inner = match *self.resolve_type(coordinate)? { - crate::TypeInner::Scalar { width, kind: _ } => crate::TypeInner::Scalar { width, kind }, - crate::TypeInner::Vector { - size, - width, - kind: _, - } => crate::TypeInner::Vector { size, width, kind }, - ref other => { - log::error!("Unexpected coordinate type {:?}", other); - return Err(Error::BadCoordinate); - } - }; Ok(SamplingContext { image, arrayed: match *self.resolve_type(image)? { crate::TypeInner::Image { arrayed, .. } => arrayed, _ => return Err(Error::BadTexture(image_name)), }, - offset_type: self.types.fetch_or_append(crate::Type { - name: None, - inner: offset_inner, - }), }) } @@ -350,6 +328,7 @@ pub struct Parser { scopes: Vec, lookup_type: FastHashMap>, lookup_function: FastHashMap>, + lookup_constant: FastHashMap>, } impl Parser { @@ -358,29 +337,7 @@ impl Parser { scopes: Vec::new(), lookup_type: FastHashMap::default(), lookup_function: FastHashMap::default(), - } - } - - fn deconstruct_composite_type( - type_arena: &mut Arena, - ty: Handle, - index: usize, - ) -> Result, Error<'static>> { - match type_arena[ty].inner { - crate::TypeInner::Vector { kind, width, .. } => { - let inner = crate::TypeInner::Scalar { kind, width }; - Ok(type_arena.fetch_or_append(crate::Type { name: None, inner })) - } - crate::TypeInner::Matrix { width, .. } => { - let inner = crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width, - }; - Ok(type_arena.fetch_or_append(crate::Type { name: None, inner })) - } - crate::TypeInner::Array { base, .. } => Ok(base), - crate::TypeInner::Struct { ref members, .. } => Ok(members[index].ty), - _ => Err(Error::NotCompositeType(ty)), + lookup_constant: FastHashMap::default(), } } @@ -466,7 +423,7 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, coordinate)?; + let sc = ctx.prepare_sampling(image_name)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -474,12 +431,7 @@ impl Parser { None }; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression( - lexer, - sc.offset_type, - ctx.types, - ctx.constants, - )?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -501,7 +453,7 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, coordinate)?; + let sc = ctx.prepare_sampling(image_name)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -511,12 +463,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let level = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression( - lexer, - sc.offset_type, - ctx.types, - ctx.constants, - )?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -538,7 +485,7 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, coordinate)?; + let sc = ctx.prepare_sampling(image_name)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -548,12 +495,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let bias = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression( - lexer, - sc.offset_type, - ctx.types, - ctx.constants, - )?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -575,7 +517,7 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, coordinate)?; + let sc = ctx.prepare_sampling(image_name)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -587,12 +529,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let y = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression( - lexer, - sc.offset_type, - ctx.types, - ctx.constants, - )?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -614,7 +551,7 @@ impl Parser { let sampler_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, coordinate)?; + let sc = ctx.prepare_sampling(image_name)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -624,12 +561,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let reference = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression( - lexer, - sc.offset_type, - ctx.types, - ctx.constants, - )?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -710,54 +642,50 @@ impl Parser { fn parse_const_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - self_ty: Handle, type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result, Error<'a>> { self.scopes.push(Scope::ConstantExpr); - let inner = match lexer.peek() { - Token::Word("true") => { - let _ = lexer.next(); - crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(true), + let inner = match lexer.next() { + Token::Word("true") => crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(true), + }, + Token::Word("false") => crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(false), + }, + Token::Number { value, ty, width } => Self::get_constant_inner(value, ty, width)?, + Token::Word(type_name) => { + if let Some(&handle) = self.lookup_constant.get(type_name) { + self.scopes.pop(); + return Ok(handle); } - } - Token::Word("false") => { - let _ = lexer.next(); - crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(false), - } - } - Token::Number { value, ty, width } => { - let _ = lexer.next(); - Self::get_constant_inner(value, ty, width)? - } - _ => { - let (composite_ty, _access) = - self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let composite_ty = self.parse_type_decl_name( + lexer, + type_name, + None, + TypeDecoration::default(), + type_arena, + const_arena, + )?; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); while !lexer.skip(Token::Paren(')')) { if !components.is_empty() { lexer.expect(Token::Separator(','))?; } - let ty = Self::deconstruct_composite_type( - type_arena, - composite_ty, - components.len(), - )?; - let component = - self.parse_const_expression(lexer, ty, type_arena, const_arena)?; + let component = self.parse_const_expression(lexer, type_arena, const_arena)?; components.push(component); } crate::ConstantInner::Composite { - ty: self_ty, + ty: composite_ty, components, } } + other => return Err(Error::Unexpected(other, "constant")), }; + let handle = const_arena.fetch_or_append(crate::Constant { name: None, specialization: None, @@ -1140,7 +1068,7 @@ impl Parser { let (ty, access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let init = if lexer.skip(Token::Operation('=')) { - let handle = self.parse_const_expression(lexer, ty, type_arena, const_arena)?; + let handle = self.parse_const_expression(lexer, type_arena, const_arena)?; Some(handle) } else { None @@ -1333,23 +1261,14 @@ impl Parser { "array" => { lexer.expect(Token::Paren('<'))?; let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; - let size = match lexer.next() { - Token::Separator(',') => { - let value = lexer.next_uint_literal()?; - lexer.expect(Token::Paren('>'))?; - let const_handle = const_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(value as u64), - }, - }); - crate::ArraySize::Constant(const_handle) - } - Token::Paren('>') => crate::ArraySize::Dynamic, - other => return Err(Error::Unexpected(other, "generic separator")), + let size = if lexer.skip(Token::Separator(',')) { + let const_handle = + self.parse_const_expression(lexer, type_arena, const_arena)?; + crate::ArraySize::Constant(const_handle) + } else { + crate::ArraySize::Dynamic }; + lexer.expect(Token::Paren('>'))?; crate::TypeInner::Array { base, @@ -1495,10 +1414,33 @@ impl Parser { }) } + /// Parse type declaration of a given name and decoration. + fn parse_type_decl_name<'a>( + &mut self, + lexer: &mut Lexer<'a>, + name: &'a str, + debug_name: Option<&'a str>, + decoration: TypeDecoration, + type_arena: &mut Arena, + const_arena: &mut Arena, + ) -> Result, Error<'a>> { + Ok(match self.lookup_type.get(name) { + Some(&handle) => handle, + None => { + let inner = + self.parse_type_decl_impl(lexer, decoration, name, type_arena, const_arena)?; + type_arena.fetch_or_append(crate::Type { + name: debug_name.map(|s| s.to_string()), + inner, + }) + } + }) + } + fn parse_type_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - self_name: Option<&'a str>, + debug_name: Option<&'a str>, type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result<(Handle, crate::StorageAccess), Error<'a>> { @@ -1535,18 +1477,14 @@ impl Parser { let storage_access = decoration.access; let name = lexer.next_ident()?; - let handle = match self.lookup_type.get(name) { - Some(&handle) => handle, - None => { - let inner = - self.parse_type_decl_impl(lexer, decoration, name, type_arena, const_arena)?; - type_arena.fetch_or_append(crate::Type { - name: self_name.map(|s| s.to_string()), - inner, - }) - } - }; - + let handle = self.parse_type_decl_name( + lexer, + name, + debug_name, + decoration, + type_arena, + const_arena, + )?; self.scopes.pop(); Ok((handle, storage_access)) } @@ -1989,19 +1927,17 @@ impl Parser { lexer.expect(Token::Separator(';'))?; } Token::Word("const") => { - let (name, ty, _access) = self.parse_variable_ident_decl( + let (name, _ty, _access) = self.parse_variable_ident_decl( lexer, &mut module.types, &mut module.constants, )?; lexer.expect(Token::Operation('='))?; - let const_handle = self.parse_const_expression( - lexer, - ty, - &mut module.types, - &mut module.constants, - )?; + let const_handle = + self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; + //TODO: check `ty` against `const_handle`. lexer.expect(Token::Separator(';'))?; + self.lookup_constant.insert(name.to_string(), const_handle); lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); } Token::Word("var") => { @@ -2079,6 +2015,8 @@ impl Parser { pub fn parse<'a>(&mut self, source: &'a str) -> Result> { self.scopes.clear(); self.lookup_type.clear(); + self.lookup_function.clear(); + self.lookup_constant.clear(); let mut module = crate::Module::generate_empty(); let mut lexer = Lexer::new(source); diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 934ffabf2..7febb7f53 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -349,7 +349,8 @@ impl Validator { }, .. }) => {} - _ => { + other => { + log::warn!("Array size {:?}", other); return Err(TypeError::InvalidArraySizeConstant(const_handle)); } } diff --git a/tests/snapshots/snapshots__quad.msl.snap b/tests/snapshots/snapshots__quad.msl.snap index 7ad0b4dd1..488e66966 100644 --- a/tests/snapshots/snapshots__quad.msl.snap +++ b/tests/snapshots/snapshots__quad.msl.snap @@ -15,8 +15,6 @@ typedef metal::texture2d type3; typedef metal::sampler type4; -typedef metal::int2 type5; - struct main1Input { type1 a_pos [[attribute(0)]]; type1 a_uv [[attribute(1)]]; diff --git a/tests/snapshots/snapshots__shadow.msl.snap b/tests/snapshots/snapshots__shadow.msl.snap index 0c13f8cfc..b8ad9bf19 100644 --- a/tests/snapshots/snapshots__shadow.msl.snap +++ b/tests/snapshots/snapshots__shadow.msl.snap @@ -37,11 +37,9 @@ typedef float type7; typedef metal::float2 type8; -typedef metal::int2 type9; +typedef int type9; -typedef int type10; - -typedef metal::float3 type11; +typedef metal::float3 type10; type7 fetch_shadow( type6 light_id, @@ -54,7 +52,7 @@ type7 fetch_shadow( } struct fs_mainInput { - type11 in_normal_fs [[user(loc0)]]; + type10 in_normal_fs [[user(loc0)]]; type2 in_position_fs [[user(loc1)]]; }; @@ -68,7 +66,7 @@ fragment fs_mainOutput fs_main( constant Lights& s_lights [[buffer(1)]] ) { fs_mainOutput output; - type11 color1 = type11(0.05, 0.05, 0.05); + type10 color1 = type10(0.05, 0.05, 0.05); type6 i = 0u; bool loop_init = true; while(true) { diff --git a/tests/snapshots/snapshots__skybox.msl.snap b/tests/snapshots/snapshots__skybox.msl.snap index d8b5e725b..1faf661cf 100644 --- a/tests/snapshots/snapshots__skybox.msl.snap +++ b/tests/snapshots/snapshots__skybox.msl.snap @@ -28,8 +28,6 @@ typedef metal::texturecube type7; typedef metal::sampler type8; -typedef metal::int3 type9; - struct vs_mainInput { }; From 4a3ecc774f9892f1c67c94cf2699972b68bc0711 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 31 Jan 2021 17:24:02 -0500 Subject: [PATCH 0412/2212] [wgsl] remove function and constant lookup maps --- src/front/wgsl/mod.rs | 131 +++++++++++++++++++++++++----------------- 1 file changed, 78 insertions(+), 53 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 09d9725d9..e807ec5d2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -327,8 +327,6 @@ pub struct ParseError<'a> { pub struct Parser { scopes: Vec, lookup_type: FastHashMap>, - lookup_function: FastHashMap>, - lookup_constant: FastHashMap>, } impl Parser { @@ -336,8 +334,6 @@ impl Parser { Parser { scopes: Vec::new(), lookup_type: FastHashMap::default(), - lookup_function: FastHashMap::default(), - lookup_constant: FastHashMap::default(), } } @@ -431,7 +427,7 @@ impl Parser { None }; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) } else { None }; @@ -463,7 +459,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let level = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) } else { None }; @@ -495,7 +491,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let bias = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) } else { None }; @@ -529,7 +525,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let y = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) } else { None }; @@ -561,7 +557,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let reference = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) } else { None }; @@ -608,33 +604,39 @@ impl Parser { index, }) } - _ => match self.lookup_function.get(name) { - Some(&function) => { - let mut arguments = Vec::new(); - lexer.expect(Token::Paren('('))?; - if !lexer.skip(Token::Paren(')')) { - loop { - let arg = self.parse_general_expression(lexer, ctx.reborrow())?; - arguments.push(arg); - match lexer.next() { - Token::Paren(')') => break, - Token::Separator(',') => (), - other => { - return Err(Error::Unexpected( - other, - "argument list separator", - )) + _ => { + match ctx.functions.iter().find(|(_, fun)| match fun.name { + Some(ref string) => string == name, + None => false, + }) { + Some((function, _)) => { + let mut arguments = Vec::new(); + lexer.expect(Token::Paren('('))?; + if !lexer.skip(Token::Paren(')')) { + loop { + let arg = + self.parse_general_expression(lexer, ctx.reborrow())?; + arguments.push(arg); + match lexer.next() { + Token::Paren(')') => break, + Token::Separator(',') => (), + other => { + return Err(Error::Unexpected( + other, + "argument list separator", + )) + } } } } + Some(crate::Expression::Call { + function, + arguments, + }) } - Some(crate::Expression::Call { - function, - arguments, - }) + None => None, } - None => None, - }, + } } }) } @@ -642,6 +644,7 @@ impl Parser { fn parse_const_expression<'a>( &mut self, lexer: &mut Lexer<'a>, + register_name: Option<&'a str>, type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result, Error<'a>> { @@ -656,14 +659,20 @@ impl Parser { value: crate::ScalarValue::Bool(false), }, Token::Number { value, ty, width } => Self::get_constant_inner(value, ty, width)?, - Token::Word(type_name) => { - if let Some(&handle) = self.lookup_constant.get(type_name) { - self.scopes.pop(); - return Ok(handle); + Token::Word(name) => { + // look for an existing constant first + for (handle, var) in const_arena.iter() { + match var.name { + Some(ref string) if string == name => { + self.scopes.pop(); + return Ok(handle); + } + _ => {} + } } let composite_ty = self.parse_type_decl_name( lexer, - type_name, + name, None, TypeDecoration::default(), type_arena, @@ -675,7 +684,8 @@ impl Parser { if !components.is_empty() { lexer.expect(Token::Separator(','))?; } - let component = self.parse_const_expression(lexer, type_arena, const_arena)?; + let component = + self.parse_const_expression(lexer, None, type_arena, const_arena)?; components.push(component); } crate::ConstantInner::Composite { @@ -686,11 +696,20 @@ impl Parser { other => return Err(Error::Unexpected(other, "constant")), }; - let handle = const_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner, - }); + let handle = if let Some(name) = register_name { + const_arena.append(crate::Constant { + name: Some(name.to_string()), + specialization: None, + inner, + }) + } else { + const_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner, + }) + }; + self.scopes.pop(); Ok(handle) } @@ -1068,7 +1087,7 @@ impl Parser { let (ty, access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let init = if lexer.skip(Token::Operation('=')) { - let handle = self.parse_const_expression(lexer, type_arena, const_arena)?; + let handle = self.parse_const_expression(lexer, None, type_arena, const_arena)?; Some(handle) } else { None @@ -1263,7 +1282,7 @@ impl Parser { let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let size = if lexer.skip(Token::Separator(',')) { let const_handle = - self.parse_const_expression(lexer, type_arena, const_arena)?; + self.parse_const_expression(lexer, None, type_arena, const_arena)?; crate::ArraySize::Constant(const_handle) } else { crate::ArraySize::Dynamic @@ -1933,11 +1952,14 @@ impl Parser { &mut module.constants, )?; lexer.expect(Token::Operation('='))?; - let const_handle = - self.parse_const_expression(lexer, &mut module.types, &mut module.constants)?; + let const_handle = self.parse_const_expression( + lexer, + Some(name), + &mut module.types, + &mut module.constants, + )?; //TODO: check `ty` against `const_handle`. lexer.expect(Token::Separator(';'))?; - self.lookup_constant.insert(name.to_string(), const_handle); lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); } Token::Word("var") => { @@ -1991,10 +2013,15 @@ impl Parser { ) .is_some(), None => { - let fun_handle = module.functions.append(function); - self.lookup_function - .insert(name.to_string(), fun_handle) - .is_some() + if module.functions.iter().any(|(_, fun)| match fun.name { + Some(ref string) => string == name, + None => false, + }) { + true + } else { + module.functions.append(function); + false + } } }; if already_declared { @@ -2015,8 +2042,6 @@ impl Parser { pub fn parse<'a>(&mut self, source: &'a str) -> Result> { self.scopes.clear(); self.lookup_type.clear(); - self.lookup_function.clear(); - self.lookup_constant.clear(); let mut module = crate::Module::generate_empty(); let mut lexer = Lexer::new(source); From 6138e4ddd34977f10fdc342c980eb7cd0099429f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 31 Jan 2021 18:02:55 -0500 Subject: [PATCH 0413/2212] [spv] fix block decoration on nested structs --- src/back/spv/writer.rs | 35 ++++++++++++------- tests/snapshots/snapshots__boids.spvasm.snap | 1 - tests/snapshots/snapshots__shadow.spvasm.snap | 1 - 3 files changed, 22 insertions(+), 15 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index bb5c2323e..faae63371 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -180,7 +180,9 @@ pub struct Writer { lookup_constant: crate::FastHashMap, Word>, lookup_global_variable: crate::FastHashMap, (Word, spirv::StorageClass)>, - storage_type_handles: crate::FastHashMap, crate::StorageAccess>, + // TODO: this is a type property that depends on the global variable that uses it + // so it may require us to duplicate the type! + struct_type_handles: crate::FastHashMap, crate::StorageAccess>, gl450_ext_inst_id: Word, layouter: Layouter, } @@ -209,7 +211,7 @@ impl Writer { lookup_function_type: crate::FastHashMap::default(), lookup_constant: crate::FastHashMap::default(), lookup_global_variable: crate::FastHashMap::default(), - storage_type_handles: crate::FastHashMap::default(), + struct_type_handles: crate::FastHashMap::default(), gl450_ext_inst_id: 0, layouter: Layouter::default(), } @@ -677,16 +679,23 @@ impl Writer { ref members, } => { //TODO: put NonWritable/NonReadable on the global variable instead? - let (decoration, storage_access) = match self.storage_type_handles.get(&handle) { - Some(&access) => (spirv::Decoration::BufferBlock, access), - None => (spirv::Decoration::Block, crate::StorageAccess::empty()), + let storage_access = match self.struct_type_handles.get(&handle) { + Some(&access) => { + let decoration = if access.is_empty() { + spirv::Decoration::Block + } else { + spirv::Decoration::BufferBlock + }; + self.annotations + .push(super::instructions::instruction_decorate( + id, + decoration, + &[], + )); + access + } + None => crate::StorageAccess::empty(), }; - self.annotations - .push(super::instructions::instruction_decorate( - id, - decoration, - &[], - )); let mut current_offset = 0; let mut member_ids = Vec::with_capacity(members.len()); @@ -2323,8 +2332,8 @@ impl Writer { } for (_, var) in ir_module.global_variables.iter() { - if !var.storage_access.is_empty() { - self.storage_type_handles.insert(var.ty, var.storage_access); + if let crate::TypeInner::Struct { .. } = ir_module.types[var.ty].inner { + self.struct_type_handles.insert(var.ty, var.storage_access); } } diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap index dc2eea87a..d98c8e743 100644 --- a/tests/snapshots/snapshots__boids.spvasm.snap +++ b/tests/snapshots/snapshots__boids.spvasm.snap @@ -15,7 +15,6 @@ OpDecorate %34 BuiltIn GlobalInvocationId OpDecorate %48 BufferBlock OpMemberDecorate %48 0 Offset 0 OpDecorate %49 ArrayStride 16 -OpDecorate %50 Block OpMemberDecorate %50 0 Offset 0 OpMemberDecorate %50 1 Offset 8 OpDecorate %47 DescriptorSet 0 diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap index 6e7ae4f4f..c0f1f29a2 100644 --- a/tests/snapshots/snapshots__shadow.spvasm.snap +++ b/tests/snapshots/snapshots__shadow.spvasm.snap @@ -23,7 +23,6 @@ OpDecorate %98 BufferBlock OpMemberDecorate %98 0 Offset 0 OpMemberDecorate %98 0 NonWritable OpDecorate %99 ArrayStride 96 -OpDecorate %100 Block OpMemberDecorate %100 0 Offset 0 OpMemberDecorate %100 0 ColMajor OpMemberDecorate %100 0 MatrixStride 16 From 537a516ff5c1eae9dcc7680b0b25d2ed6dec8a8b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 30 Jan 2021 22:54:20 -0500 Subject: [PATCH 0414/2212] Version bump to 0.3.1 --- CHANGELOG.md | 14 +++++++++++++- Cargo.toml | 2 +- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b166a8cd..4081989bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,15 @@ # Change Log -## v0.2 (2020-08-17) +## v0.3.1 (2021-01-31) + - wgsl: + - support constant array sizes + - spv-out: + - fix block decorations on nested structures + - fix fixed-size arrays + - fix matrix decorations inside structures + - implement read-only decorations + +## v0.3 (2021-01-30) - development release for wgpu-0.7 - API: - math functions @@ -17,5 +26,8 @@ - termination analysis - validation of types, constants, variables, and entry points +## v0.2 (2020-08-17) + - development release for wgpu-0.6 + ## v0.1 (2020-02-26) - initial release diff --git a/Cargo.toml b/Cargo.toml index ef9df97aa..429295f32 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.3.0" +version = "0.3.1" authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" From 9f88c3e98688bd6e84df77eaa3670120ed85c4f5 Mon Sep 17 00:00:00 2001 From: Jay Oster Date: Sat, 30 Jan 2021 13:52:40 -0800 Subject: [PATCH 0415/2212] Update emoji in README --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index bbfaf7c7f..cc99d0108 100644 --- a/README.md +++ b/README.md @@ -13,20 +13,20 @@ Everything is still a work-in-progress, but some end-points are usable: Front-end | Status | Notes | --------------- | ------------------ | ----- | -SPIR-V (binary) | :heavy_check_mark: | | -WGSL | :heavy_check_mark: | | -GLSL (Vulkan) | :white_check_mark: | | +SPIR-V (binary) | :white_check_mark: | | +WGSL | :white_check_mark: | | +GLSL (Vulkan) | :ok: | | Rust | | | Back-end | Status | Notes | --------------- | ------------------ | ----- | -SPIR-V (binary) | :heavy_check_mark: | | +SPIR-V (binary) | :white_check_mark: | | WGSL | | | -Metal | :heavy_check_mark: | | +Metal | :white_check_mark: | | HLSL | | | -GLSL | :white_check_mark: | | +GLSL | :ok: | | AIR | | | DXIL/DXIR | | | DXBC | | | -:heavy_check_mark: = Primary support — :white_check_mark: = Secondary support — :construction: = Unsupported, but support in progress +:white_check_mark: = Primary support — :ok: = Secondary support — :construction: = Unsupported, but support in progress From df3759ebffee89d093150158f9d873865c09beb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 30 Jan 2021 18:20:29 +0000 Subject: [PATCH 0416/2212] Fix double constant lexing and lex uint constants --- src/front/glsl/lex.rs | 17 ++++--- src/front/glsl/lex_tests.rs | 88 +++++++++++++++++++++++++++++++++++++ src/front/glsl/parser.rs | 28 +++++++++++- 3 files changed, 124 insertions(+), 9 deletions(-) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 2ea23da87..ecbd4f082 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -93,21 +93,24 @@ impl<'a> Lexer<'a> { } } '0'..='9' => { - let (number, _, pos) = + let (number, remainder, pos) = consume_any(input, |c| (('0'..='9').contains(&c) || c == '.')); + let mut remainder_chars = remainder.chars(); + let first = remainder_chars.next().and_then(|c| c.to_lowercase().next()); + if number.find('.').is_some() { - if ( - chars.next().map(|c| c.to_lowercase().next().unwrap()), - chars.next().map(|c| c.to_lowercase().next().unwrap()), - ) == (Some('l'), Some('f')) - { + let second = remainder_chars.next().and_then(|c| c.to_lowercase().next()); + + if (first, second) == (Some('l'), Some('f')) { meta.chars.end = start + pos + 2; Some(Token::DoubleConstant((meta, number.parse().unwrap()))) } else { meta.chars.end = start + pos; - Some(Token::FloatConstant((meta, number.parse().unwrap()))) } + } else if first == Some('u') { + meta.chars.end = start + pos + 1; + Some(Token::UintConstant((meta, number.parse().unwrap()))) } else { meta.chars.end = start + pos; Some(Token::IntConstant((meta, number.parse().unwrap()))) diff --git a/src/front/glsl/lex_tests.rs b/src/front/glsl/lex_tests.rs index fde7fc979..74bc4a0ed 100644 --- a/src/front/glsl/lex_tests.rs +++ b/src/front/glsl/lex_tests.rs @@ -343,4 +343,92 @@ fn tokens() { }) ); assert_eq!(lex.next(), None); + + // float constants + let mut lex = Lexer::new("120.0 130.0lf 140.0Lf 150.0LF"); + assert_eq!( + lex.next().unwrap(), + FloatConstant(( + TokenMetadata { + line: 0, + chars: 0..5 + }, + 120.0, + )) + ); + assert_eq!( + lex.next().unwrap(), + DoubleConstant(( + TokenMetadata { + line: 0, + chars: 6..13 + }, + 130.0, + )) + ); + assert_eq!( + lex.next().unwrap(), + DoubleConstant(( + TokenMetadata { + line: 0, + chars: 14..21 + }, + 140.0, + )) + ); + assert_eq!( + lex.next().unwrap(), + DoubleConstant(( + TokenMetadata { + line: 0, + chars: 22..29 + }, + 150.0, + )) + ); + assert_eq!(lex.next(), None); + + // Integer constants + let mut lex = Lexer::new("120 130u 140U 150"); + assert_eq!( + lex.next().unwrap(), + IntConstant(( + TokenMetadata { + line: 0, + chars: 0..3 + }, + 120, + )) + ); + assert_eq!( + lex.next().unwrap(), + UintConstant(( + TokenMetadata { + line: 0, + chars: 4..8 + }, + 130, + )) + ); + assert_eq!( + lex.next().unwrap(), + UintConstant(( + TokenMetadata { + line: 0, + chars: 9..13 + }, + 140, + )) + ); + assert_eq!( + lex.next().unwrap(), + IntConstant(( + TokenMetadata { + line: 0, + chars: 14..17 + }, + 150, + )) + ); + assert_eq!(lex.next(), None); } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 4eb76ddcf..7985313c3 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -180,7 +180,19 @@ pomelo! { extra.context.expressions.append(Expression::Constant(ch)) ) } - // primary_expression ::= UintConstant; + primary_expression ::= UintConstant(i) { + let ch = extra.module.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Uint(i.1), + }, + }); + ExpressionRule::from_expression( + extra.context.expressions.append(Expression::Constant(ch)) + ) + } primary_expression ::= FloatConstant(f) { let ch = extra.module.constants.fetch_or_append(Constant { name: None, @@ -207,7 +219,19 @@ pomelo! { extra.context.expressions.append(Expression::Constant(ch)) ) } - // primary_expression ::= DoubleConstant; + primary_expression ::= DoubleConstant(f) { + let ch = extra.module.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 8, + value: ScalarValue::Float(f.1), + }, + }); + ExpressionRule::from_expression( + extra.context.expressions.append(Expression::Constant(ch)) + ) + } primary_expression ::= LeftParen expression(e) RightParen { e } From daf18642d77f33763d8edede5fd85bd5aff01410 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 30 Jan 2021 20:49:56 +0000 Subject: [PATCH 0417/2212] Add support for hexadecimal literals --- src/front/glsl/lex.rs | 34 ++++++++++++++++++++++++++++++---- src/front/glsl/lex_tests.rs | 32 +++++++++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index ecbd4f082..e5412c8a8 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -93,8 +93,20 @@ impl<'a> Lexer<'a> { } } '0'..='9' => { - let (number, remainder, pos) = - consume_any(input, |c| (('0'..='9').contains(&c) || c == '.')); + let next = chars.next().and_then(|c| c.to_lowercase().next()); + + let hexadecimal = cur == '0' && next.map_or(false, |c| c == 'x'); + + let (number, remainder, pos) = if hexadecimal { + consume_any(&input[2..], |c| { + ('0'..='9').contains(&c) + || ('a'..='f').contains(&c) + || ('A'..='F').contains(&c) + }) + } else { + consume_any(input, |c| (('0'..='9').contains(&c) || c == '.')) + }; + let mut remainder_chars = remainder.chars(); let first = remainder_chars.next().and_then(|c| c.to_lowercase().next()); @@ -109,8 +121,22 @@ impl<'a> Lexer<'a> { Some(Token::FloatConstant((meta, number.parse().unwrap()))) } } else if first == Some('u') { - meta.chars.end = start + pos + 1; - Some(Token::UintConstant((meta, number.parse().unwrap()))) + if hexadecimal { + meta.chars.end = start + pos + 3; + Some(Token::UintConstant(( + meta, + u64::from_str_radix(number, 16).unwrap(), + ))) + } else { + meta.chars.end = start + pos + 1; + Some(Token::UintConstant((meta, number.parse().unwrap()))) + } + } else if hexadecimal { + meta.chars.end = start + pos + 2; + Some(Token::IntConstant(( + meta, + i64::from_str_radix(number, 16).unwrap(), + ))) } else { meta.chars.end = start + pos; Some(Token::IntConstant((meta, number.parse().unwrap()))) diff --git a/src/front/glsl/lex_tests.rs b/src/front/glsl/lex_tests.rs index 74bc4a0ed..7a4e15f52 100644 --- a/src/front/glsl/lex_tests.rs +++ b/src/front/glsl/lex_tests.rs @@ -389,7 +389,7 @@ fn tokens() { assert_eq!(lex.next(), None); // Integer constants - let mut lex = Lexer::new("120 130u 140U 150"); + let mut lex = Lexer::new("120 130u 140U 150 0x1f 0xf2U 0xF1u"); assert_eq!( lex.next().unwrap(), IntConstant(( @@ -430,5 +430,35 @@ fn tokens() { 150, )) ); + assert_eq!( + lex.next().unwrap(), + IntConstant(( + TokenMetadata { + line: 0, + chars: 18..22 + }, + 31, + )) + ); + assert_eq!( + lex.next().unwrap(), + UintConstant(( + TokenMetadata { + line: 0, + chars: 23..28 + }, + 242, + )) + ); + assert_eq!( + lex.next().unwrap(), + UintConstant(( + TokenMetadata { + line: 0, + chars: 29..34 + }, + 241, + )) + ); assert_eq!(lex.next(), None); } From c12003f5648fcade5f20c01debc4cb12bd47073e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 31 Jan 2021 14:03:35 +0000 Subject: [PATCH 0418/2212] Populate ResolveContext with functions Add support for more math functions --- src/front/glsl/ast.rs | 3 +-- src/front/glsl/functions.rs | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 842d5c9bc..647c3a627 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -58,12 +58,11 @@ impl Program { &mut self, handle: Handle, ) -> Result<&crate::TypeInner, ErrorKind> { - let functions = Arena::new(); //TODO let resolve_ctx = ResolveContext { constants: &self.module.constants, global_vars: &self.module.global_variables, local_vars: &self.context.local_variables, - functions: &functions, + functions: &self.module.functions, arguments: &self.context.arguments, }; match self.context.typifier.grow( diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 80132bfd2..42d2721b1 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -81,7 +81,7 @@ impl Program { Err(ErrorKind::SemanticError("Bad call to texture".into())) } } - "ceil" | "round" | "floor" | "fract" | "trunc" => { + "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" => { if fc.args.len() != 1 { return Err(ErrorKind::WrongNumberArgs(name, 1, fc.args.len())); } @@ -93,6 +93,8 @@ impl Program { "floor" => MathFunction::Floor, "fract" => MathFunction::Fract, "trunc" => MathFunction::Trunc, + "sin" => MathFunction::Sin, + "abs" => MathFunction::Abs, _ => unreachable!(), }, arg: fc.args[0].expression, @@ -103,6 +105,24 @@ impl Program { statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), }) } + "mix" => { + if fc.args.len() != 3 { + return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); + } + Ok(ExpressionRule { + expression: self.context.expressions.append(Expression::Math { + fun: match name.as_str() { + "mix" => MathFunction::Mix, + _ => unreachable!(), + }, + arg: fc.args[0].expression, + arg1: Some(fc.args[1].expression), + arg2: None, + }), + sampler: None, + statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), + }) + } func_name => { let function = *self.lookup_function.get(func_name).ok_or_else(|| { ErrorKind::SemanticError( From 208346fad6a555ebb2889f7b44b83a0d3a28ef75 Mon Sep 17 00:00:00 2001 From: Lain-dono Date: Mon, 1 Feb 2021 05:51:39 +0300 Subject: [PATCH 0419/2212] [spv-out] implement discard --- src/back/spv/instructions.rs | 4 ++++ src/back/spv/writer.rs | 3 +++ 2 files changed, 7 insertions(+) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 8aa98e70d..c7df1604c 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -707,6 +707,10 @@ pub(super) fn instruction_branch_conditional( instruction } +pub(super) fn instruction_kill() -> Instruction { + Instruction::new(Op::Kill) +} + pub(super) fn instruction_return() -> Instruction { Instruction::new(Op::Return) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index faae63371..a7d450441 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2276,6 +2276,9 @@ impl Writer { crate::Statement::Return { value: None } => { block.termination = Some(super::instructions::instruction_return()); } + crate::Statement::Kill => { + block.termination = Some(super::instructions::instruction_kill()); + } crate::Statement::Store { pointer, value } => { let (pointer_id, _, _) = self.write_expression_pointer( ir_module, From 6ff725d89a38a09a63edfc2edf7cf3b581c1a30f Mon Sep 17 00:00:00 2001 From: Lain-dono Date: Mon, 1 Feb 2021 08:28:17 +0300 Subject: [PATCH 0420/2212] [spv-out] Add missing math functions (#401) * [spv-out] Add missing builtins * [spv-out] remove a non-existent integer version of mix --- src/back/spv/writer.rs | 65 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a7d450441..3feb3727d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1609,10 +1609,13 @@ impl Writer { } // trigonometry Mf::Sin => MathOp::Single(spirv::GLOp::Sin), + Mf::Sinh => MathOp::Single(spirv::GLOp::Sinh), Mf::Asin => MathOp::Single(spirv::GLOp::Asin), Mf::Cos => MathOp::Single(spirv::GLOp::Cos), + Mf::Cosh => MathOp::Single(spirv::GLOp::Cosh), Mf::Acos => MathOp::Single(spirv::GLOp::Acos), Mf::Tan => MathOp::Single(spirv::GLOp::Tan), + Mf::Tanh => MathOp::Single(spirv::GLOp::Tanh), Mf::Atan => MathOp::Single(spirv::GLOp::Atan), Mf::Atan2 => MathOp::Double(spirv::GLOp::Atan2), // decomposition @@ -1621,6 +1624,9 @@ impl Writer { Mf::Floor => MathOp::Single(spirv::GLOp::Floor), Mf::Fract => MathOp::Single(spirv::GLOp::Fract), Mf::Trunc => MathOp::Single(spirv::GLOp::Trunc), + Mf::Modf => MathOp::Double(spirv::GLOp::Modf), + Mf::Frexp => MathOp::Double(spirv::GLOp::Frexp), + Mf::Ldexp => MathOp::Double(spirv::GLOp::Ldexp), // geometry Mf::Dot => { let result_lookup_ty = @@ -1693,8 +1699,41 @@ impl Writer { MathOp::Other(inst, result_lookup_ty) } Mf::Normalize => MathOp::Single(spirv::GLOp::Normalize), + Mf::FaceForward => MathOp::Triple(spirv::GLOp::FaceForward), + Mf::Reflect => MathOp::Double(spirv::GLOp::Reflect), + // exponent + Mf::Exp => MathOp::Single(spirv::GLOp::Exp), + Mf::Exp2 => MathOp::Single(spirv::GLOp::Exp2), + Mf::Log => MathOp::Single(spirv::GLOp::Log), + Mf::Log2 => MathOp::Single(spirv::GLOp::Log2), Mf::Pow => MathOp::Double(spirv::GLOp::Pow), // computational + Mf::Sign => { + let op = match self + .get_type_inner(&ir_module.types, arg0_lookup_ty) + .scalar_kind() + { + Some(crate::ScalarKind::Float) => spirv::GLOp::FSign, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SSign, + other => unimplemented!("Unexpected sign({:?})", other), + }; + MathOp::Single(op) + } + Mf::Fma => MathOp::Triple(spirv::GLOp::Fma), + Mf::Mix => { + let op = match self + .get_type_inner(&ir_module.types, arg0_lookup_ty) + .scalar_kind() + { + Some(crate::ScalarKind::Float) => spirv::GLOp::FMix, + other => unimplemented!("Unexpected mix({:?})", other), + }; + MathOp::Triple(op) + } + Mf::Step => MathOp::Triple(spirv::GLOp::Step), + Mf::SmoothStep => MathOp::Triple(spirv::GLOp::SmoothStep), + Mf::Sqrt => MathOp::Single(spirv::GLOp::Sqrt), + Mf::InverseSqrt => MathOp::Single(spirv::GLOp::InverseSqrt), Mf::Transpose => { let result_lookup_ty = match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { @@ -1720,7 +1759,31 @@ impl Writer { ); MathOp::Other(inst, result_lookup_ty) } - _ => { + Mf::Determinant => { + let result_lookup_ty = + match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { + crate::TypeInner::Matrix { width, .. } => { + LookupType::Local(LocalType::Scalar { + kind: crate::ScalarKind::Float, + width, + }) + } + _ => unreachable!(), + }; + let result_type_id = + self.get_type_id(&ir_module.types, result_lookup_ty)?; + + let inst = super::instructions::instruction_ext_inst( + self.gl450_ext_inst_id, + spirv::GLOp::Determinant, + result_type_id, + id, + &[arg0_id], + ); + MathOp::Other(inst, result_lookup_ty) + } + + Mf::Outer | Mf::ReverseBits | Mf::CountOneBits => { log::error!("unimplemented math function {:?}", fun); return Err(Error::FeatureNotImplemented("math function")); } From 5def021b6ee3d5660f196825d8fcffc940c18974 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 1 Feb 2021 09:33:28 -0500 Subject: [PATCH 0421/2212] [spv] replace the internal type inferrence with the typifier (#403) Also, fix the Typifier's handling of logical operations. See https://github.com/gfx-rs/naga/pull/404 for v0.3 branch. --- src/back/spv/writer.rs | 865 ++++++------------ src/proc/typifier.rs | 24 +- tests/snapshots/snapshots__boids.msl.snap | 2 + tests/snapshots/snapshots__boids.spvasm.snap | 298 +++--- .../snapshots/snapshots__collatz.spvasm.snap | 60 +- tests/snapshots/snapshots__quad.spvasm.snap | 62 +- tests/snapshots/snapshots__shadow.msl.snap | 2 + tests/snapshots/snapshots__shadow.spvasm.snap | 407 ++++---- tests/snapshots/snapshots__skybox.spvasm.snap | 388 ++++---- 9 files changed, 901 insertions(+), 1207 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 3feb3727d..b5cfe69d7 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,8 +1,8 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ use super::{Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; -use crate::proc::Layouter; +use crate::proc::{Layouter, ResolveContext, ResolveError, Typifier}; use spirv::Word; -use std::{collections::hash_map::Entry, ops}; +use std::collections::hash_map::Entry; use thiserror::Error; const BITS_PER_BYTE: crate::Bytes = 8; @@ -13,6 +13,8 @@ pub enum Error { MissingCapabilities(Vec), #[error("unimplemented {0:}")] FeatureNotImplemented(&'static str), + #[error(transparent)] + Resolve(#[from] ResolveError), } struct Block { @@ -77,7 +79,6 @@ impl Function { #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LocalType { - Void, Scalar { kind: crate::ScalarKind, width: crate::Bytes, @@ -101,6 +102,28 @@ enum LocalType { }, } +impl LocalType { + fn from_inner(inner: &crate::TypeInner) -> Option { + Some(match *inner { + crate::TypeInner::Scalar { kind, width } => LocalType::Scalar { kind, width }, + crate::TypeInner::Vector { size, kind, width } => { + LocalType::Vector { size, kind, width } + } + crate::TypeInner::Matrix { + columns, + rows, + width, + } => LocalType::Matrix { + columns, + rows, + width, + }, + crate::TypeInner::Pointer { base, class } => LocalType::Pointer { base, class }, + _ => return None, + }) + } +} + #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LookupType { Handle(crate::Handle), @@ -128,21 +151,6 @@ struct LookupFunctionType { return_type_id: Word, } -enum MaybeOwned<'a, T> { - Owned(T), - Borrowed(&'a T), -} - -impl<'a, T> ops::Deref for MaybeOwned<'a, T> { - type Target = T; - fn deref(&self) -> &T { - match *self { - MaybeOwned::Owned(ref value) => value, - MaybeOwned::Borrowed(reference) => reference, - } - } -} - #[derive(Debug)] enum Dimension { Scalar, @@ -150,8 +158,8 @@ enum Dimension { Matrix, } -fn get_dimension(ty_inner: &crate::TypeInner) -> Dimension { - match *ty_inner { +fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { + match *type_inner { crate::TypeInner::Scalar { .. } => Dimension::Scalar, crate::TypeInner::Vector { .. } => Dimension::Vector, crate::TypeInner::Matrix { .. } => Dimension::Matrix, @@ -185,11 +193,12 @@ pub struct Writer { struct_type_handles: crate::FastHashMap, crate::StorageAccess>, gl450_ext_inst_id: Word, layouter: Layouter, + typifier: Typifier, } // type alias, for success return of write_expression -type WriteExpressionOutput = (Word, LookupType); -type WritePointerExpressionOutput = (Word, LookupType, spirv::StorageClass); +type ExpressionId = Word; +type PointerExpressionId = (Word, spirv::StorageClass); impl Writer { pub fn new( @@ -214,6 +223,7 @@ impl Writer { struct_type_handles: crate::FastHashMap::default(), gl450_ext_inst_id: 0, layouter: Layouter::default(), + typifier: Typifier::new(), } } @@ -250,6 +260,18 @@ impl Writer { arena, LookupType::Local(LocalType::Vector { size, kind, width }), ), + crate::TypeInner::Matrix { + columns, + rows, + width, + } => self.get_type_id( + arena, + LookupType::Local(LocalType::Matrix { + columns, + rows, + width, + }), + ), _ => self.write_type_declaration_arena(arena, handle), }, LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty), @@ -332,15 +354,13 @@ impl Writer { fn create_pointer_type( &mut self, - lookup_type: LookupType, + type_id: spirv::Word, class: spirv::StorageClass, - type_arena: &crate::Arena, - ) -> Result<(Word, LookupType), Error> { - let type_id = self.get_type_id(type_arena, lookup_type)?; + ) -> Result { let id = self.generate_id(); let instruction = super::instructions::instruction_type_pointer(id, class, type_id); instruction.to_words(&mut self.logical_layout.declarations); - Ok((id, lookup_type)) + Ok(id) } fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word { @@ -357,6 +377,18 @@ impl Writer { ) -> Result { let mut function = Function::default(); + self.typifier.resolve_all( + &ir_function.expressions, + &ir_module.types, + &ResolveContext { + constants: &ir_module.constants, + global_vars: &ir_module.global_variables, + local_vars: &ir_function.local_variables, + functions: &ir_module.functions, + arguments: &ir_function.arguments, + }, + )?; + for (handle, variable) in ir_function.local_variables.iter() { let id = self.generate_id(); @@ -537,7 +569,6 @@ impl Writer { ) -> Result { let id = self.generate_id(); let instruction = match local_ty { - LocalType::Void => unreachable!(), LocalType::Scalar { kind, width } => self.write_scalar(id, kind, width), LocalType::Vector { size, kind, width } => { let scalar_id = @@ -1048,37 +1079,6 @@ impl Writer { id } - fn get_type_inner<'a>( - &self, - ty_arena: &'a crate::Arena, - lookup_ty: LookupType, - ) -> MaybeOwned<'a, crate::TypeInner> { - match lookup_ty { - LookupType::Handle(handle) => MaybeOwned::Borrowed(&ty_arena[handle].inner), - LookupType::Local(local_ty) => match local_ty { - LocalType::Scalar { kind, width } => { - MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width }) - } - LocalType::Vector { size, kind, width } => { - MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }) - } - LocalType::Matrix { - columns, - rows, - width, - } => MaybeOwned::Owned(crate::TypeInner::Matrix { - columns, - rows, - width, - }), - LocalType::Pointer { base, class } => { - MaybeOwned::Owned(crate::TypeInner::Pointer { base, class }) - } - LocalType::Void | LocalType::SampledImage { .. } => unreachable!(), - }, - } - } - /// Write an expression and return a value ID. fn write_expression<'a>( &mut self, @@ -1087,18 +1087,20 @@ impl Writer { handle: crate::Handle, block: &mut Block, function: &mut Function, - ) -> Result { - let (raw_expression, lookup_ty) = + ) -> Result { + let (raw_expression, result_type_id) = self.write_expression_raw(ir_module, ir_function, handle, block, function)?; Ok(match raw_expression { - RawExpression::Value(id) => (id, lookup_ty), + RawExpression::Value(id) => id, RawExpression::Pointer(id, _) => { let load_id = self.generate_id(); - let type_id = self.get_type_id(&ir_module.types, lookup_ty)?; block.body.push(super::instructions::instruction_load( - type_id, load_id, id, None, + result_type_id, + load_id, + id, + None, )); - (load_id, lookup_ty) + load_id } }) } @@ -1111,15 +1113,15 @@ impl Writer { handle: crate::Handle, block: &mut Block, function: &mut Function, - ) -> Result { - let (raw_expression, lookup_ty) = + ) -> Result { + let (raw_expression, _) = self.write_expression_raw(ir_module, ir_function, handle, block, function)?; Ok(match raw_expression { RawExpression::Value(_id) => unimplemented!( "Expression {:?} is not a pointer", ir_function.expressions[handle] ), - RawExpression::Pointer(id, class) => (id, lookup_ty, class), + RawExpression::Pointer(id, class) => (id, class), }) } @@ -1131,40 +1133,30 @@ impl Writer { expr_handle: crate::Handle, block: &mut Block, function: &mut Function, - ) -> Result<(RawExpression, LookupType), Error> { - match ir_function.expressions[expr_handle] { + ) -> Result<(RawExpression, ExpressionId), Error> { + let result_lookup_ty = match self.typifier.get_handle(expr_handle) { + Ok(ty_handle) => LookupType::Handle(ty_handle), + Err(inner) => LookupType::Local(LocalType::from_inner(inner).unwrap()), + }; + let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; + + let raw_expr = match ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { let id = self.generate_id(); - let (raw_base_expression, base_lookup_ty) = + let (raw_base_expression, _) = self.write_expression_raw(ir_module, ir_function, base, block, function)?; - let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); - let (index_id, _) = + let index_id = self.write_expression(ir_module, ir_function, index, block, function)?; + let base_inner = self.typifier.get(base, &ir_module.types); - let lookup_ty = match *base_ty_inner { - crate::TypeInner::Vector { - size: _, - kind, - width, - } => LookupType::Local(LocalType::Scalar { kind, width }), - crate::TypeInner::Array { base, .. } => LookupType::Handle(base), - ref other => { - log::error!("Unable to index {:?}", other); - return Err(Error::FeatureNotImplemented( - "accessing index of non vector or array", - )); - } - }; - - Ok(match raw_base_expression { + match raw_base_expression { RawExpression::Value(base_id) => { - if let crate::TypeInner::Array { .. } = *base_ty_inner { + if let crate::TypeInner::Array { .. } = *base_inner { return Err(Error::FeatureNotImplemented( "accessing index of a value array", )); } - let result_type_id = self.get_type_id(&ir_module.types, lookup_ty)?; block .body .push(super::instructions::instruction_vector_extract_dynamic( @@ -1174,11 +1166,10 @@ impl Writer { index_id, )); - (RawExpression::Value(id), lookup_ty) + RawExpression::Value(id) } RawExpression::Pointer(base_id, class) => { - let (pointer_type_id, pointer_lookup_ty) = - self.create_pointer_type(lookup_ty, class, &ir_module.types)?; + let pointer_type_id = self.create_pointer_type(result_type_id, class)?; block .body @@ -1189,46 +1180,17 @@ impl Writer { &[index_id], )); - (RawExpression::Pointer(id, class), pointer_lookup_ty) + RawExpression::Pointer(id, class) } - }) + } } crate::Expression::AccessIndex { base, index } => { let id = self.generate_id(); - let (raw_base_expression, base_lookup_ty) = + let (raw_base_expression, _) = self.write_expression_raw(ir_module, ir_function, base, block, function)?; - let base_ty_inner = self.get_type_inner(&ir_module.types, base_lookup_ty); - let lookup_ty = match *base_ty_inner { - crate::TypeInner::Vector { - size: _, - kind, - width, - } => LookupType::Local(LocalType::Scalar { kind, width }), - crate::TypeInner::Matrix { - columns: _, - rows, - width, - } => LookupType::Local(LocalType::Vector { - size: rows, - kind: crate::ScalarKind::Float, - width, - }), - crate::TypeInner::Struct { - block: _, - ref members, - } => LookupType::Handle(members[index as usize].ty), - ref other => { - log::error!("Unable to access index {:?}", other); - return Err(Error::FeatureNotImplemented( - "accessing index of non vector or struct", - )); - } - }; - - Ok(match raw_base_expression { + match raw_base_expression { RawExpression::Value(base_id) => { - let result_type_id = self.get_type_id(&ir_module.types, lookup_ty)?; block .body .push(super::instructions::instruction_composite_extract( @@ -1238,9 +1200,11 @@ impl Writer { &[index], )); - (RawExpression::Value(id), lookup_ty) + RawExpression::Value(id) } RawExpression::Pointer(base_id, class) => { + let pointer_type_id = self.create_pointer_type(result_type_id, class)?; + let const_ty_id = self.get_type_id( &ir_module.types, LookupType::Local(LocalType::Scalar { @@ -1249,8 +1213,6 @@ impl Writer { }), )?; let const_id = self.create_constant(const_ty_id, &[index]); - let (pointer_type_id, pointer_lookup_ty) = - self.create_pointer_type(lookup_ty, class, &ir_module.types)?; block .body @@ -1261,39 +1223,24 @@ impl Writer { &[const_id], )); - (RawExpression::Pointer(id, class), pointer_lookup_ty) + RawExpression::Pointer(id, class) } - }) + } } crate::Expression::GlobalVariable(handle) => { - let var = &ir_module.global_variables[handle]; let (id, class) = self.get_global_variable_id(&ir_module, handle)?; - - Ok(( - RawExpression::Pointer(id, class), - LookupType::Handle(var.ty), - )) + RawExpression::Pointer(id, class) } crate::Expression::Constant(handle) => { - let var = &ir_module.constants[handle]; let id = self.lookup_constant[&handle]; - let lookup_type = match var.inner { - crate::ConstantInner::Scalar { width, ref value } => { - LookupType::Local(LocalType::Scalar { - kind: value.scalar_kind(), - width, - }) - } - crate::ConstantInner::Composite { ty, components: _ } => LookupType::Handle(ty), - }; - Ok((RawExpression::Value(id), lookup_type)) + RawExpression::Value(id) } crate::Expression::Compose { ty, ref components } => { let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty))?; let mut constituent_ids = Vec::with_capacity(components.len()); for component in components { - let (component_id, _) = self.write_expression( + let component_id = self.write_expression( ir_module, &ir_function, *component, @@ -1304,14 +1251,13 @@ impl Writer { } let id = self.write_composite_construct(base_type_id, &constituent_ids, block); - Ok((RawExpression::Value(id), LookupType::Handle(ty))) + RawExpression::Value(id) } crate::Expression::Unary { op, expr } => { let id = self.generate_id(); - let (expr_id, expr_lookup_ty) = + let expr_id = self.write_expression(ir_module, ir_function, expr, block, function)?; - let expr_ty_inner = self.get_type_inner(&ir_module.types, expr_lookup_ty); - let result_type_id = self.get_type_id(&ir_module.types, expr_lookup_ty)?; + let expr_ty_inner = self.typifier.get(expr, &ir_module.types); let spirv_op = match op { crate::UnaryOperator::Negate => match expr_ty_inner.scalar_kind() { @@ -1319,7 +1265,7 @@ impl Writer { Some(crate::ScalarKind::Sint) => spirv::Op::SNegate, Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNot, Some(crate::ScalarKind::Uint) | None => { - log::error!("Unable to negate {:?}", &*expr_ty_inner); + log::error!("Unable to negate {:?}", expr_ty_inner); return Err(Error::FeatureNotImplemented("negation")); } }, @@ -1332,25 +1278,21 @@ impl Writer { id, expr_id, )); - Ok((RawExpression::Value(id), expr_lookup_ty)) + RawExpression::Value(id) } crate::Expression::Binary { op, left, right } => { let id = self.generate_id(); - let (left_id, left_lookup_ty) = + let left_id = self.write_expression(ir_module, ir_function, left, block, function)?; - let (right_id, right_lookup_ty) = + let right_id = self.write_expression(ir_module, ir_function, right, block, function)?; - let left_ty_inner = self.get_type_inner(&ir_module.types, left_lookup_ty); - let right_ty_inner = self.get_type_inner(&ir_module.types, right_lookup_ty); + let left_ty_inner = self.typifier.get(left, &ir_module.types); + let right_ty_inner = self.typifier.get(right, &ir_module.types); - let left_result_type_id = self.get_type_id(&ir_module.types, left_lookup_ty)?; - let right_result_type_id = self.get_type_id(&ir_module.types, right_lookup_ty)?; + let left_dimension = get_dimension(left_ty_inner); + let right_dimension = get_dimension(right_ty_inner); - let left_dimension = get_dimension(&left_ty_inner); - let right_dimension = get_dimension(&right_ty_inner); - - let mut result_side_left = true; let mut preserve_order = true; let spirv_op = match op { @@ -1370,38 +1312,30 @@ impl Writer { }, _ => unimplemented!(), }, - crate::BinaryOperator::Multiply => { - // whenever there is a vector on the right, - // the result type is a vector. - if let Dimension::Vector = right_dimension { - result_side_left = false; + crate::BinaryOperator::Multiply => match (left_dimension, right_dimension) { + (Dimension::Scalar, Dimension::Vector { .. }) => { + preserve_order = false; + spirv::Op::VectorTimesScalar } - match (left_dimension, right_dimension) { - (Dimension::Scalar, Dimension::Vector { .. }) => { - preserve_order = false; - spirv::Op::VectorTimesScalar - } - (Dimension::Vector, Dimension::Scalar { .. }) => { - spirv::Op::VectorTimesScalar - } - (Dimension::Vector, Dimension::Matrix) => spirv::Op::VectorTimesMatrix, - (Dimension::Matrix, Dimension::Scalar { .. }) => { - spirv::Op::MatrixTimesScalar - } - (Dimension::Matrix, Dimension::Vector) => spirv::Op::MatrixTimesVector, - (Dimension::Matrix, Dimension::Matrix) => spirv::Op::MatrixTimesMatrix, - (Dimension::Vector, Dimension::Vector) - | (Dimension::Scalar, Dimension::Scalar) - if left_ty_inner.scalar_kind() - == Some(crate::ScalarKind::Float) => - { - spirv::Op::FMul - } - (Dimension::Vector, Dimension::Vector) - | (Dimension::Scalar, Dimension::Scalar) => spirv::Op::IMul, - other => unimplemented!("Mul {:?}", other), + (Dimension::Vector, Dimension::Scalar { .. }) => { + spirv::Op::VectorTimesScalar } - } + (Dimension::Vector, Dimension::Matrix) => spirv::Op::VectorTimesMatrix, + (Dimension::Matrix, Dimension::Scalar { .. }) => { + spirv::Op::MatrixTimesScalar + } + (Dimension::Matrix, Dimension::Vector) => spirv::Op::MatrixTimesVector, + (Dimension::Matrix, Dimension::Matrix) => spirv::Op::MatrixTimesMatrix, + (Dimension::Vector, Dimension::Vector) + | (Dimension::Scalar, Dimension::Scalar) + if left_ty_inner.scalar_kind() == Some(crate::ScalarKind::Float) => + { + spirv::Op::FMul + } + (Dimension::Vector, Dimension::Vector) + | (Dimension::Scalar, Dimension::Scalar) => spirv::Op::IMul, + other => unimplemented!("Mul {:?}", other), + }, crate::BinaryOperator::Divide => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) => spirv::Op::SDiv, Some(crate::ScalarKind::Uint) => spirv::Op::UDiv, @@ -1467,29 +1401,6 @@ impl Writer { }, }; - let is_comparison = match op { - crate::BinaryOperator::Equal - | crate::BinaryOperator::NotEqual - | crate::BinaryOperator::Less - | crate::BinaryOperator::LessEqual - | crate::BinaryOperator::Greater - | crate::BinaryOperator::GreaterEqual => true, - _ => false, - }; - - let (result_type_id, result_lookup_ty) = if is_comparison { - let local_ty = LookupType::Local(LocalType::Scalar { - kind: crate::ScalarKind::Bool, - width: 1, - }); - let result_ty_id = self.get_type_id(&ir_module.types, local_ty)?; - (result_ty_id, local_ty) - } else if result_side_left { - (left_result_type_id, left_lookup_ty) - } else { - (right_result_type_id, right_lookup_ty) - }; - block.body.push(super::instructions::instruction_binary( spirv_op, result_type_id, @@ -1497,7 +1408,7 @@ impl Writer { if preserve_order { left_id } else { right_id }, if preserve_order { right_id } else { left_id }, )); - Ok((RawExpression::Value(id), result_lookup_ty)) + RawExpression::Value(id) } crate::Expression::Math { fun, @@ -1507,28 +1418,22 @@ impl Writer { } => { use crate::MathFunction as Mf; enum MathOp { - Single(spirv::GLOp), - Double(spirv::GLOp), - Triple(spirv::GLOp), - Other(super::Instruction, LookupType), + Ext(spirv::GLOp), + Custom(super::Instruction), } - let (arg0_id, arg0_lookup_ty) = + let arg0_id = self.write_expression(ir_module, ir_function, arg, block, function)?; - let arg0_type_id = self.get_type_id(&ir_module.types, arg0_lookup_ty)?; + let arg_scalar_kind = self.typifier.get(arg, &ir_module.types).scalar_kind(); let arg1_id = match arg1 { Some(id) => { - let (arg1_id, _) = - self.write_expression(ir_module, ir_function, id, block, function)?; - arg1_id + self.write_expression(ir_module, ir_function, id, block, function)? } None => 0, }; let arg2_id = match arg2 { Some(id) => { - let (arg2_id, _) = - self.write_expression(ir_module, ir_function, id, block, function)?; - arg2_id + self.write_expression(ir_module, ir_function, id, block, function)? } None => 0, }; @@ -1537,339 +1442,147 @@ impl Writer { let math_op = match fun { // comparison Mf::Abs => { - let inst = match self - .get_type_inner(&ir_module.types, arg0_lookup_ty) - .scalar_kind() - { - Some(crate::ScalarKind::Float) => { - super::instructions::instruction_ext_inst( - self.gl450_ext_inst_id, - spirv::GLOp::FAbs, - arg0_type_id, - id, - &[arg0_id], - ) - } - Some(crate::ScalarKind::Sint) => { - super::instructions::instruction_ext_inst( - self.gl450_ext_inst_id, - spirv::GLOp::SAbs, - arg0_type_id, - id, - &[arg0_id], - ) - } + match arg_scalar_kind { + Some(crate::ScalarKind::Float) => MathOp::Ext(spirv::GLOp::FAbs), + Some(crate::ScalarKind::Sint) => MathOp::Ext(spirv::GLOp::SAbs), Some(crate::ScalarKind::Uint) => { - super::instructions::instruction_unary( + MathOp::Custom(super::instructions::instruction_unary( spirv::Op::CopyObject, // do nothing - arg0_type_id, + result_type_id, id, arg0_id, - ) + )) } other => unimplemented!("Unexpected abs({:?})", other), - }; - MathOp::Other(inst, arg0_lookup_ty) - } - Mf::Min => { - let op = match self - .get_type_inner(&ir_module.types, arg0_lookup_ty) - .scalar_kind() - { - Some(crate::ScalarKind::Float) => spirv::GLOp::FMin, - Some(crate::ScalarKind::Sint) => spirv::GLOp::SMin, - Some(crate::ScalarKind::Uint) => spirv::GLOp::UMin, - other => unimplemented!("Unexpected min({:?})", other), - }; - MathOp::Double(op) - } - Mf::Max => { - let op = match self - .get_type_inner(&ir_module.types, arg0_lookup_ty) - .scalar_kind() - { - Some(crate::ScalarKind::Float) => spirv::GLOp::FMax, - Some(crate::ScalarKind::Sint) => spirv::GLOp::SMax, - Some(crate::ScalarKind::Uint) => spirv::GLOp::UMax, - other => unimplemented!("Unexpected max({:?})", other), - }; - MathOp::Double(op) - } - Mf::Clamp => { - let op = match self - .get_type_inner(&ir_module.types, arg0_lookup_ty) - .scalar_kind() - { - Some(crate::ScalarKind::Float) => spirv::GLOp::FClamp, - Some(crate::ScalarKind::Sint) => spirv::GLOp::SClamp, - Some(crate::ScalarKind::Uint) => spirv::GLOp::UClamp, - other => unimplemented!("Unexpected max({:?})", other), - }; - MathOp::Triple(op) + } } + Mf::Min => MathOp::Ext(match arg_scalar_kind { + Some(crate::ScalarKind::Float) => spirv::GLOp::FMin, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SMin, + Some(crate::ScalarKind::Uint) => spirv::GLOp::UMin, + other => unimplemented!("Unexpected min({:?})", other), + }), + Mf::Max => MathOp::Ext(match arg_scalar_kind { + Some(crate::ScalarKind::Float) => spirv::GLOp::FMax, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SMax, + Some(crate::ScalarKind::Uint) => spirv::GLOp::UMax, + other => unimplemented!("Unexpected max({:?})", other), + }), + Mf::Clamp => MathOp::Ext(match arg_scalar_kind { + Some(crate::ScalarKind::Float) => spirv::GLOp::FClamp, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SClamp, + Some(crate::ScalarKind::Uint) => spirv::GLOp::UClamp, + other => unimplemented!("Unexpected max({:?})", other), + }), // trigonometry - Mf::Sin => MathOp::Single(spirv::GLOp::Sin), - Mf::Sinh => MathOp::Single(spirv::GLOp::Sinh), - Mf::Asin => MathOp::Single(spirv::GLOp::Asin), - Mf::Cos => MathOp::Single(spirv::GLOp::Cos), - Mf::Cosh => MathOp::Single(spirv::GLOp::Cosh), - Mf::Acos => MathOp::Single(spirv::GLOp::Acos), - Mf::Tan => MathOp::Single(spirv::GLOp::Tan), - Mf::Tanh => MathOp::Single(spirv::GLOp::Tanh), - Mf::Atan => MathOp::Single(spirv::GLOp::Atan), - Mf::Atan2 => MathOp::Double(spirv::GLOp::Atan2), + Mf::Sin => MathOp::Ext(spirv::GLOp::Sin), + Mf::Sinh => MathOp::Ext(spirv::GLOp::Sinh), + Mf::Asin => MathOp::Ext(spirv::GLOp::Asin), + Mf::Cos => MathOp::Ext(spirv::GLOp::Cos), + Mf::Cosh => MathOp::Ext(spirv::GLOp::Cosh), + Mf::Acos => MathOp::Ext(spirv::GLOp::Acos), + Mf::Tan => MathOp::Ext(spirv::GLOp::Tan), + Mf::Tanh => MathOp::Ext(spirv::GLOp::Tanh), + Mf::Atan => MathOp::Ext(spirv::GLOp::Atan), + Mf::Atan2 => MathOp::Ext(spirv::GLOp::Atan2), // decomposition - Mf::Ceil => MathOp::Single(spirv::GLOp::Ceil), - Mf::Round => MathOp::Single(spirv::GLOp::Round), - Mf::Floor => MathOp::Single(spirv::GLOp::Floor), - Mf::Fract => MathOp::Single(spirv::GLOp::Fract), - Mf::Trunc => MathOp::Single(spirv::GLOp::Trunc), - Mf::Modf => MathOp::Double(spirv::GLOp::Modf), - Mf::Frexp => MathOp::Double(spirv::GLOp::Frexp), - Mf::Ldexp => MathOp::Double(spirv::GLOp::Ldexp), + Mf::Ceil => MathOp::Ext(spirv::GLOp::Ceil), + Mf::Round => MathOp::Ext(spirv::GLOp::Round), + Mf::Floor => MathOp::Ext(spirv::GLOp::Floor), + Mf::Fract => MathOp::Ext(spirv::GLOp::Fract), + Mf::Trunc => MathOp::Ext(spirv::GLOp::Trunc), + Mf::Modf => MathOp::Ext(spirv::GLOp::Modf), + Mf::Frexp => MathOp::Ext(spirv::GLOp::Frexp), + Mf::Ldexp => MathOp::Ext(spirv::GLOp::Ldexp), // geometry - Mf::Dot => { - let result_lookup_ty = - match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { - crate::TypeInner::Scalar { kind, width } - | crate::TypeInner::Vector { - size: _, - kind, - width, - } => LookupType::Local(LocalType::Scalar { kind, width }), - _ => unreachable!(), - }; - let result_type_id = - self.get_type_id(&ir_module.types, result_lookup_ty)?; - - let inst = super::instructions::instruction_binary( - spirv::Op::Dot, - result_type_id, - id, - arg0_id, - arg1_id, - ); - MathOp::Other(inst, result_lookup_ty) - } - Mf::Cross => MathOp::Double(spirv::GLOp::Cross), - Mf::Distance => { - let result_lookup_ty = - match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { - crate::TypeInner::Scalar { kind, width } - | crate::TypeInner::Vector { - size: _, - kind, - width, - } => LookupType::Local(LocalType::Scalar { kind, width }), - _ => unreachable!(), - }; - let result_type_id = - self.get_type_id(&ir_module.types, result_lookup_ty)?; - - let inst = super::instructions::instruction_ext_inst( - self.gl450_ext_inst_id, - spirv::GLOp::Distance, - result_type_id, - id, - &[arg0_id, arg1_id], - ); - MathOp::Other(inst, result_lookup_ty) - } - Mf::Length => { - let result_lookup_ty = - match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { - crate::TypeInner::Scalar { kind, width } - | crate::TypeInner::Vector { - size: _, - kind, - width, - } => LookupType::Local(LocalType::Scalar { kind, width }), - _ => unreachable!(), - }; - let result_type_id = - self.get_type_id(&ir_module.types, result_lookup_ty)?; - - let inst = super::instructions::instruction_ext_inst( - self.gl450_ext_inst_id, - spirv::GLOp::Length, - result_type_id, - id, - &[arg0_id], - ); - MathOp::Other(inst, result_lookup_ty) - } - Mf::Normalize => MathOp::Single(spirv::GLOp::Normalize), - Mf::FaceForward => MathOp::Triple(spirv::GLOp::FaceForward), - Mf::Reflect => MathOp::Double(spirv::GLOp::Reflect), + Mf::Dot => MathOp::Custom(super::instructions::instruction_binary( + spirv::Op::Dot, + result_type_id, + id, + arg0_id, + arg1_id, + )), + Mf::Cross => MathOp::Ext(spirv::GLOp::Cross), + Mf::Distance => MathOp::Ext(spirv::GLOp::Distance), + Mf::Length => MathOp::Ext(spirv::GLOp::Length), + Mf::Normalize => MathOp::Ext(spirv::GLOp::Normalize), + Mf::FaceForward => MathOp::Ext(spirv::GLOp::FaceForward), + Mf::Reflect => MathOp::Ext(spirv::GLOp::Reflect), // exponent - Mf::Exp => MathOp::Single(spirv::GLOp::Exp), - Mf::Exp2 => MathOp::Single(spirv::GLOp::Exp2), - Mf::Log => MathOp::Single(spirv::GLOp::Log), - Mf::Log2 => MathOp::Single(spirv::GLOp::Log2), - Mf::Pow => MathOp::Double(spirv::GLOp::Pow), + Mf::Exp => MathOp::Ext(spirv::GLOp::Exp), + Mf::Exp2 => MathOp::Ext(spirv::GLOp::Exp2), + Mf::Log => MathOp::Ext(spirv::GLOp::Log), + Mf::Log2 => MathOp::Ext(spirv::GLOp::Log2), + Mf::Pow => MathOp::Ext(spirv::GLOp::Pow), // computational - Mf::Sign => { - let op = match self - .get_type_inner(&ir_module.types, arg0_lookup_ty) - .scalar_kind() - { - Some(crate::ScalarKind::Float) => spirv::GLOp::FSign, - Some(crate::ScalarKind::Sint) => spirv::GLOp::SSign, - other => unimplemented!("Unexpected sign({:?})", other), - }; - MathOp::Single(op) - } - Mf::Fma => MathOp::Triple(spirv::GLOp::Fma), - Mf::Mix => { - let op = match self - .get_type_inner(&ir_module.types, arg0_lookup_ty) - .scalar_kind() - { - Some(crate::ScalarKind::Float) => spirv::GLOp::FMix, - other => unimplemented!("Unexpected mix({:?})", other), - }; - MathOp::Triple(op) - } - Mf::Step => MathOp::Triple(spirv::GLOp::Step), - Mf::SmoothStep => MathOp::Triple(spirv::GLOp::SmoothStep), - Mf::Sqrt => MathOp::Single(spirv::GLOp::Sqrt), - Mf::InverseSqrt => MathOp::Single(spirv::GLOp::InverseSqrt), - Mf::Transpose => { - let result_lookup_ty = - match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { - crate::TypeInner::Matrix { - columns, - rows, - width, - } => LookupType::Local(LocalType::Matrix { - columns: rows, - rows: columns, - width, - }), - _ => unreachable!(), - }; - let result_type_id = - self.get_type_id(&ir_module.types, result_lookup_ty)?; - - let inst = super::instructions::instruction_unary( - spirv::Op::Transpose, - result_type_id, - id, - arg0_id, - ); - MathOp::Other(inst, result_lookup_ty) - } - Mf::Determinant => { - let result_lookup_ty = - match *self.get_type_inner(&ir_module.types, arg0_lookup_ty) { - crate::TypeInner::Matrix { width, .. } => { - LookupType::Local(LocalType::Scalar { - kind: crate::ScalarKind::Float, - width, - }) - } - _ => unreachable!(), - }; - let result_type_id = - self.get_type_id(&ir_module.types, result_lookup_ty)?; - - let inst = super::instructions::instruction_ext_inst( - self.gl450_ext_inst_id, - spirv::GLOp::Determinant, - result_type_id, - id, - &[arg0_id], - ); - MathOp::Other(inst, result_lookup_ty) - } - + Mf::Sign => MathOp::Ext(match arg_scalar_kind { + Some(crate::ScalarKind::Float) => spirv::GLOp::FSign, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SSign, + other => unimplemented!("Unexpected sign({:?})", other), + }), + Mf::Fma => MathOp::Ext(spirv::GLOp::Fma), + Mf::Mix => MathOp::Ext(spirv::GLOp::FMix), + Mf::Step => MathOp::Ext(spirv::GLOp::Step), + Mf::SmoothStep => MathOp::Ext(spirv::GLOp::SmoothStep), + Mf::Sqrt => MathOp::Ext(spirv::GLOp::Sqrt), + Mf::InverseSqrt => MathOp::Ext(spirv::GLOp::InverseSqrt), + Mf::Transpose => MathOp::Custom(super::instructions::instruction_unary( + spirv::Op::Transpose, + result_type_id, + id, + arg0_id, + )), + Mf::Determinant => MathOp::Ext(spirv::GLOp::Determinant), Mf::Outer | Mf::ReverseBits | Mf::CountOneBits => { log::error!("unimplemented math function {:?}", fun); return Err(Error::FeatureNotImplemented("math function")); } }; - let (instruction, result_lookup_ty) = match math_op { - MathOp::Single(op) => { - let inst = super::instructions::instruction_ext_inst( - self.gl450_ext_inst_id, - op, - arg0_type_id, - id, - &[arg0_id], - ); - (inst, arg0_lookup_ty) - } - MathOp::Double(op) => { - let inst = super::instructions::instruction_ext_inst( - self.gl450_ext_inst_id, - op, - arg0_type_id, - id, - &[arg0_id, arg1_id], - ); - (inst, arg0_lookup_ty) - } - MathOp::Triple(op) => { - let inst = super::instructions::instruction_ext_inst( - self.gl450_ext_inst_id, - op, - arg0_type_id, - id, - &[arg0_id, arg1_id, arg2_id], - ); - (inst, arg0_lookup_ty) - } - MathOp::Other(inst, result_lookup_ty) => (inst, result_lookup_ty), - }; - - block.body.push(instruction); - Ok((RawExpression::Value(id), result_lookup_ty)) + block.body.push(match math_op { + MathOp::Ext(op) => super::instructions::instruction_ext_inst( + self.gl450_ext_inst_id, + op, + result_type_id, + id, + &[arg0_id, arg1_id, arg2_id][..fun.argument_count()], + ), + MathOp::Custom(inst) => inst, + }); + RawExpression::Value(id) } crate::Expression::LocalVariable(variable) => { - let var = &ir_function.local_variables[variable]; let local_var = &function.variables[&variable]; - Ok(( - RawExpression::Pointer(local_var.id, spirv::StorageClass::Function), - LookupType::Handle(var.ty), - )) + RawExpression::Pointer(local_var.id, spirv::StorageClass::Function) } crate::Expression::FunctionArgument(index) => { - let ty_handle = ir_function.arguments[index as usize].ty; let id = function.parameters[index as usize].result_id.unwrap(); - Ok((RawExpression::Value(id), LookupType::Handle(ty_handle))) + RawExpression::Value(id) } crate::Expression::Call { function: local_function, ref arguments, } => { - let target_function = &ir_module.functions[local_function]; let id = self.generate_id(); + //TODO: avoid heap allocation let mut argument_ids = vec![]; for argument in arguments { - let (arg_id, _) = + let arg_id = self.write_expression(ir_module, ir_function, *argument, block, function)?; argument_ids.push(arg_id); } - let return_type_id = - self.get_function_return_type(target_function.return_type, &ir_module.types)?; - block .body .push(super::instructions::instruction_function_call( - return_type_id, + result_type_id, id, *self.lookup_function.get(&local_function).unwrap(), argument_ids.as_slice(), )); - let result_type = match target_function.return_type { - Some(ty_handle) => LookupType::Handle(ty_handle), - None => LookupType::Local(LocalType::Void), - }; - Ok((RawExpression::Value(id), result_type)) + RawExpression::Value(id) } crate::Expression::As { expr, @@ -1880,25 +1593,14 @@ impl Writer { return Err(Error::FeatureNotImplemented("bitcast")); } - let (expr_id, expr_type) = + let expr_id = self.write_expression(ir_module, ir_function, expr, block, function)?; + let expr_kind = self + .typifier + .get(expr, &ir_module.types) + .scalar_kind() + .unwrap(); - let expr_type_inner = self.get_type_inner(&ir_module.types, expr_type); - - let (expr_kind, local_type) = match *expr_type_inner { - crate::TypeInner::Scalar { - kind: expr_kind, - width, - } => (expr_kind, LocalType::Scalar { kind, width }), - crate::TypeInner::Vector { - size, - kind: expr_kind, - width, - } => (expr_kind, LocalType::Vector { size, kind, width }), - _ => unreachable!(), - }; - - let lookup_type = LookupType::Local(local_type); let op = match (expr_kind, kind) { _ if !convert => spirv::Op::Bitcast, (crate::ScalarKind::Float, crate::ScalarKind::Uint) => spirv::Op::ConvertFToU, @@ -1906,17 +1608,15 @@ impl Writer { (crate::ScalarKind::Sint, crate::ScalarKind::Float) => spirv::Op::ConvertSToF, (crate::ScalarKind::Uint, crate::ScalarKind::Float) => spirv::Op::ConvertUToF, // We assume it's either an identity cast, or int-uint. - // In both cases no SPIR-V instructions need to be generated. - _ => return Ok((RawExpression::Value(expr_id), lookup_type)), + _ => spirv::Op::Bitcast, }; let id = self.generate_id(); - let kind_type_id = self.get_type_id(&ir_module.types, lookup_type)?; let instruction = - super::instructions::instruction_unary(op, kind_type_id, id, expr_id); + super::instructions::instruction_unary(op, result_type_id, id, expr_id); block.body.push(instruction); - Ok((RawExpression::Value(id), lookup_type)) + RawExpression::Value(id) } crate::Expression::ImageSample { image, @@ -1929,28 +1629,22 @@ impl Writer { } => { use super::instructions::SampleLod; // image - let (image_id, image_lookup_ty) = + let image_id = self.write_expression(ir_module, ir_function, image, block, function)?; - - let image_ty = match image_lookup_ty { - LookupType::Handle(handle) => handle, - LookupType::Local(_) => unreachable!(), - }; + let image_type = self.typifier.get_handle(image).unwrap(); // OpTypeSampledImage let sampled_image_type_id = self.get_type_id( &ir_module.types, - LookupType::Local(LocalType::SampledImage { - image_type: image_ty, - }), + LookupType::Local(LocalType::SampledImage { image_type }), )?; // sampler - let (sampler_id, _) = + let sampler_id = self.write_expression(ir_module, ir_function, sampler, block, function)?; // coordinate - let (mut coordinate_id, coordinate_lookup_ty) = + let mut coordinate_id = self.write_expression(ir_module, ir_function, coordinate, block, function)?; if let Some(array_index) = array_index { @@ -1963,7 +1657,7 @@ impl Writer { )?; let mut constituent_ids = [0u32; 4]; - let size = match *self.get_type_inner(&ir_module.types, coordinate_lookup_ty) { + let size = match *self.typifier.get(coordinate, &ir_module.types) { crate::TypeInner::Scalar { .. } => { constituent_ids[0] = coordinate_id; crate::VectorSize::Bi @@ -1995,7 +1689,7 @@ impl Writer { let array_index_f32_id = self.generate_id(); constituent_ids[size as usize - 1] = array_index_f32_id; - let (array_index_u32_id, _) = self.write_expression( + let array_index_u32_id = self.write_expression( ir_module, ir_function, array_index, @@ -2026,29 +1720,6 @@ impl Writer { ); } - // component kind - let image_type = &ir_module.types[image_ty]; - let image_sample_result_type = match image_type.inner { - crate::TypeInner::Image { class, .. } => { - let width = 4; - LookupType::Local(match class { - crate::ImageClass::Sampled { kind, multi: _ } => LocalType::Vector { - kind, - width, - size: crate::VectorSize::Quad, - }, - crate::ImageClass::Depth => LocalType::Scalar { - kind: crate::ScalarKind::Float, - width, - }, - crate::ImageClass::Storage(_) => { - unimplemented!("Unexpected storage image being sampled") - } - }) - } - ref other => unimplemented!("Unexpected image type {:?}", other), - }; - let sampled_image_id = self.generate_id(); block .body @@ -2059,12 +1730,10 @@ impl Writer { sampler_id, )); let id = self.generate_id(); - let image_sample_result_type_id = - self.get_type_id(&ir_module.types, image_sample_result_type)?; let depth_id = match depth_ref { Some(handle) => { - let (expr_id, _) = + let expr_id = self.write_expression(ir_module, ir_function, handle, block, function)?; Some(expr_id) } @@ -2074,7 +1743,7 @@ impl Writer { let mut main_instruction = match level { crate::SampleLevel::Zero => { let mut inst = super::instructions::instruction_image_sample( - image_sample_result_type_id, + result_type_id, id, SampleLod::Explicit, sampled_image_id, @@ -2095,7 +1764,7 @@ impl Writer { inst } crate::SampleLevel::Auto => super::instructions::instruction_image_sample( - image_sample_result_type_id, + result_type_id, id, SampleLod::Implicit, sampled_image_id, @@ -2104,7 +1773,7 @@ impl Writer { ), crate::SampleLevel::Exact(lod_handle) => { let mut inst = super::instructions::instruction_image_sample( - image_sample_result_type_id, + result_type_id, id, SampleLod::Explicit, sampled_image_id, @@ -2112,7 +1781,7 @@ impl Writer { depth_id, ); - let (lod_id, _) = self.write_expression( + let lod_id = self.write_expression( ir_module, ir_function, lod_handle, @@ -2126,7 +1795,7 @@ impl Writer { } crate::SampleLevel::Bias(bias_handle) => { let mut inst = super::instructions::instruction_image_sample( - image_sample_result_type_id, + result_type_id, id, SampleLod::Implicit, sampled_image_id, @@ -2134,7 +1803,7 @@ impl Writer { depth_id, ); - let (bias_id, _) = self.write_expression( + let bias_id = self.write_expression( ir_module, ir_function, bias_handle, @@ -2148,7 +1817,7 @@ impl Writer { } crate::SampleLevel::Gradient { x, y } => { let mut inst = super::instructions::instruction_image_sample( - image_sample_result_type_id, + result_type_id, id, SampleLod::Explicit, sampled_image_id, @@ -2156,9 +1825,9 @@ impl Writer { depth_id, ); - let (x_id, _) = + let x_id = self.write_expression(ir_module, ir_function, x, block, function)?; - let (y_id, _) = + let y_id = self.write_expression(ir_module, ir_function, y, block, function)?; inst.add_operand(spirv::ImageOperands::GRAD.bits()); inst.add_operand(x_id); @@ -2175,13 +1844,15 @@ impl Writer { } block.body.push(main_instruction); - Ok((RawExpression::Value(id), image_sample_result_type)) + RawExpression::Value(id) } ref other => { log::error!("unimplemented {:?}", other); - Err(Error::FeatureNotImplemented("expression")) + return Err(Error::FeatureNotImplemented("expression")); } - } + }; + + Ok((raw_expr, result_type_id)) } #[allow(clippy::too_many_arguments)] @@ -2224,7 +1895,7 @@ impl Writer { ref accept, ref reject, } => { - let (condition_id, _) = self.write_expression( + let condition_id = self.write_expression( ir_module, ir_function, *condition, @@ -2332,7 +2003,7 @@ impl Writer { )); } crate::Statement::Return { value: Some(value) } => { - let (id, _) = + let id = self.write_expression(ir_module, ir_function, value, &mut block, function)?; block.termination = Some(super::instructions::instruction_return_value(id)); } @@ -2343,14 +2014,14 @@ impl Writer { block.termination = Some(super::instructions::instruction_kill()); } crate::Statement::Store { pointer, value } => { - let (pointer_id, _, _) = self.write_expression_pointer( + let (pointer_id, _) = self.write_expression_pointer( ir_module, ir_function, pointer, &mut block, function, )?; - let (value_id, _) = + let value_id = self.write_expression(ir_module, ir_function, value, &mut block, function)?; block.body.push(super::instructions::instruction_store( diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index d41b17f89..b367713c9 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -95,10 +95,10 @@ impl Typifier { pub fn get_handle( &self, expr_handle: Handle, - ) -> Option> { + ) -> Result, &crate::TypeInner> { match self.resolutions[expr_handle.index()] { - Resolution::Handle(ty_handle) => Some(ty_handle), - Resolution::Value(_) => None, + Resolution::Handle(ty_handle) => Ok(ty_handle), + Resolution::Value(ref inner) => Err(inner), } } @@ -258,7 +258,23 @@ impl Typifier { | crate::BinaryOperator::Greater | crate::BinaryOperator::GreaterEqual | crate::BinaryOperator::LogicalAnd - | crate::BinaryOperator::LogicalOr => self.resolutions[left.index()].clone(), + | crate::BinaryOperator::LogicalOr => { + let kind = crate::ScalarKind::Bool; + let width = 1; + let inner = match *self.get(left, types) { + crate::TypeInner::Scalar { .. } => crate::TypeInner::Scalar { kind, width }, + crate::TypeInner::Vector { size, .. } => { + crate::TypeInner::Vector { size, kind, width } + } + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "logical".to_string(), + operand: format!("{:?}", other), + }) + } + }; + Resolution::Value(inner) + } crate::BinaryOperator::And | crate::BinaryOperator::ExclusiveOr | crate::BinaryOperator::InclusiveOr diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/snapshots/snapshots__boids.msl.snap index 4cc30a553..47cdc704c 100644 --- a/tests/snapshots/snapshots__boids.msl.snap +++ b/tests/snapshots/snapshots__boids.msl.snap @@ -36,6 +36,8 @@ typedef metal::uint3 type4; typedef int type5; +typedef bool type6; + kernel void main1( constant SimParams& params [[buffer(0)]], constant Particles& particlesSrc [[buffer(1)]], diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap index d98c8e743..fac29f9aa 100644 --- a/tests/snapshots/snapshots__boids.spvasm.snap +++ b/tests/snapshots/snapshots__boids.spvasm.snap @@ -9,26 +9,26 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %29 "main" %34 +OpEntryPoint GLCompute %29 "main" %36 OpExecutionMode %29 LocalSize 64 1 1 -OpDecorate %34 BuiltIn GlobalInvocationId -OpDecorate %48 BufferBlock -OpMemberDecorate %48 0 Offset 0 -OpDecorate %49 ArrayStride 16 -OpMemberDecorate %50 0 Offset 0 -OpMemberDecorate %50 1 Offset 8 -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 1 -OpDecorate %122 Block -OpMemberDecorate %122 0 Offset 0 -OpMemberDecorate %122 1 Offset 4 -OpMemberDecorate %122 2 Offset 8 -OpMemberDecorate %122 3 Offset 12 -OpMemberDecorate %122 4 Offset 16 -OpMemberDecorate %122 5 Offset 20 -OpMemberDecorate %122 6 Offset 24 -OpDecorate %121 DescriptorSet 0 -OpDecorate %121 Binding 0 +OpDecorate %36 BuiltIn GlobalInvocationId +OpMemberDecorate %45 0 Offset 0 +OpMemberDecorate %45 1 Offset 8 +OpDecorate %47 ArrayStride 16 +OpDecorate %49 BufferBlock +OpMemberDecorate %49 0 Offset 0 +OpDecorate %50 DescriptorSet 0 +OpDecorate %50 Binding 1 +OpDecorate %121 Block +OpMemberDecorate %121 0 Offset 0 +OpMemberDecorate %121 1 Offset 4 +OpMemberDecorate %121 2 Offset 8 +OpMemberDecorate %121 3 Offset 12 +OpMemberDecorate %121 4 Offset 16 +OpMemberDecorate %121 5 Offset 20 +OpMemberDecorate %121 6 Offset 24 +OpDecorate %122 DescriptorSet 0 +OpDecorate %122 Binding 0 OpDecorate %274 DescriptorSet 0 OpDecorate %274 Binding 2 %3 = OpTypeInt 32 1 @@ -49,91 +49,91 @@ OpDecorate %274 Binding 2 %27 = OpTypePointer Function %8 %28 = OpTypeVoid %30 = OpTypeFunction %28 +%32 = OpTypeBool %35 = OpTypeVector %8 3 -%36 = OpTypePointer Input %35 -%34 = OpVariable %36 Input -%37 = OpConstant %3 0 +%37 = OpTypePointer Input %35 +%36 = OpVariable %37 Input %38 = OpTypePointer Input %8 -%40 = OpTypeBool -%50 = OpTypeStruct %15 %15 -%49 = OpTypeRuntimeArray %50 -%48 = OpTypeStruct %49 -%51 = OpTypePointer Uniform %48 -%47 = OpVariable %51 Uniform -%52 = OpConstant %3 0 -%53 = OpTypePointer Uniform %49 -%55 = OpConstant %3 0 -%56 = OpTypePointer Input %8 -%58 = OpTypePointer Uniform %50 -%59 = OpConstant %3 0 -%60 = OpTypePointer Uniform %15 -%65 = OpConstant %3 0 -%66 = OpTypePointer Uniform %49 -%68 = OpConstant %3 0 -%69 = OpTypePointer Input %8 -%71 = OpTypePointer Uniform %50 -%72 = OpConstant %3 1 -%73 = OpTypePointer Uniform %15 -%90 = OpConstant %3 0 -%91 = OpTypePointer Input %8 -%99 = OpConstant %3 0 -%100 = OpTypePointer Uniform %49 -%102 = OpTypePointer Uniform %50 -%103 = OpConstant %3 0 -%104 = OpTypePointer Uniform %15 -%109 = OpConstant %3 0 -%110 = OpTypePointer Uniform %49 -%112 = OpTypePointer Uniform %50 -%113 = OpConstant %3 1 -%114 = OpTypePointer Uniform %15 -%122 = OpTypeStruct %5 %5 %5 %5 %5 %5 %5 -%123 = OpTypePointer Uniform %122 -%121 = OpVariable %123 Uniform -%124 = OpConstant %3 1 -%125 = OpTypePointer Uniform %5 -%140 = OpConstant %3 2 -%141 = OpTypePointer Uniform %5 -%156 = OpConstant %3 3 -%157 = OpTypePointer Uniform %5 -%198 = OpConstant %3 4 -%199 = OpTypePointer Uniform %5 -%204 = OpConstant %3 5 -%205 = OpTypePointer Uniform %5 -%210 = OpConstant %3 6 -%211 = OpTypePointer Uniform %5 -%224 = OpConstant %3 0 -%225 = OpTypePointer Uniform %5 -%229 = OpConstant %3 0 -%230 = OpTypePointer Function %5 -%236 = OpConstant %3 0 -%237 = OpTypePointer Function %5 -%240 = OpConstant %3 0 -%241 = OpTypePointer Function %5 -%247 = OpConstant %3 0 -%248 = OpTypePointer Function %5 -%251 = OpConstant %3 1 -%252 = OpTypePointer Function %5 -%258 = OpConstant %3 1 -%259 = OpTypePointer Function %5 -%262 = OpConstant %3 1 -%263 = OpTypePointer Function %5 -%269 = OpConstant %3 1 -%270 = OpTypePointer Function %5 +%39 = OpConstant %3 0 +%45 = OpTypeStruct %15 %15 +%47 = OpTypeRuntimeArray %45 +%49 = OpTypeStruct %47 +%51 = OpTypePointer Uniform %49 +%50 = OpVariable %51 Uniform +%52 = OpTypePointer Uniform %47 +%53 = OpConstant %3 0 +%55 = OpTypePointer Input %8 +%56 = OpConstant %3 0 +%58 = OpTypePointer Uniform %45 +%59 = OpTypePointer Uniform %15 +%60 = OpConstant %3 0 +%65 = OpTypePointer Uniform %47 +%66 = OpConstant %3 0 +%68 = OpTypePointer Input %8 +%69 = OpConstant %3 0 +%71 = OpTypePointer Uniform %45 +%72 = OpTypePointer Uniform %15 +%73 = OpConstant %3 1 +%90 = OpTypePointer Input %8 +%91 = OpConstant %3 0 +%99 = OpTypePointer Uniform %47 +%100 = OpConstant %3 0 +%102 = OpTypePointer Uniform %45 +%103 = OpTypePointer Uniform %15 +%104 = OpConstant %3 0 +%109 = OpTypePointer Uniform %47 +%110 = OpConstant %3 0 +%112 = OpTypePointer Uniform %45 +%113 = OpTypePointer Uniform %15 +%114 = OpConstant %3 1 +%121 = OpTypeStruct %5 %5 %5 %5 %5 %5 %5 +%123 = OpTypePointer Uniform %121 +%122 = OpVariable %123 Uniform +%124 = OpTypePointer Uniform %5 +%125 = OpConstant %3 1 +%140 = OpTypePointer Uniform %5 +%141 = OpConstant %3 2 +%156 = OpTypePointer Uniform %5 +%157 = OpConstant %3 3 +%198 = OpTypePointer Uniform %5 +%199 = OpConstant %3 4 +%204 = OpTypePointer Uniform %5 +%205 = OpConstant %3 5 +%210 = OpTypePointer Uniform %5 +%211 = OpConstant %3 6 +%224 = OpTypePointer Uniform %5 +%225 = OpConstant %3 0 +%229 = OpTypePointer Function %5 +%230 = OpConstant %3 0 +%236 = OpTypePointer Function %5 +%237 = OpConstant %3 0 +%240 = OpTypePointer Function %5 +%241 = OpConstant %3 0 +%247 = OpTypePointer Function %5 +%248 = OpConstant %3 0 +%251 = OpTypePointer Function %5 +%252 = OpConstant %3 1 +%258 = OpTypePointer Function %5 +%259 = OpConstant %3 1 +%262 = OpTypePointer Function %5 +%263 = OpConstant %3 1 +%269 = OpTypePointer Function %5 +%270 = OpConstant %3 1 %274 = OpVariable %51 Uniform -%275 = OpConstant %3 0 -%276 = OpTypePointer Uniform %49 -%278 = OpConstant %3 0 -%279 = OpTypePointer Input %8 -%281 = OpTypePointer Uniform %50 -%282 = OpConstant %3 0 -%283 = OpTypePointer Uniform %15 -%288 = OpConstant %3 0 -%289 = OpTypePointer Uniform %49 -%291 = OpConstant %3 0 -%292 = OpTypePointer Input %8 -%294 = OpTypePointer Uniform %50 -%295 = OpConstant %3 1 -%296 = OpTypePointer Uniform %15 +%275 = OpTypePointer Uniform %47 +%276 = OpConstant %3 0 +%278 = OpTypePointer Input %8 +%279 = OpConstant %3 0 +%281 = OpTypePointer Uniform %45 +%282 = OpTypePointer Uniform %15 +%283 = OpConstant %3 0 +%288 = OpTypePointer Uniform %47 +%289 = OpConstant %3 0 +%291 = OpTypePointer Input %8 +%292 = OpConstant %3 0 +%294 = OpTypePointer Uniform %45 +%295 = OpTypePointer Uniform %15 +%296 = OpConstant %3 1 %29 = OpFunction %28 None %30 %31 = OpLabel %26 = OpVariable %27 Function %7 @@ -146,28 +146,28 @@ OpDecorate %274 Binding 2 %25 = OpVariable %16 Function %21 = OpVariable %22 Function %6 %18 = OpVariable %16 Function -%33 = OpAccessChain %38 %34 %37 -%39 = OpLoad %8 %33 -%32 = OpUGreaterThanEqual %40 %39 %2 +%34 = OpAccessChain %38 %36 %39 +%40 = OpLoad %8 %34 +%33 = OpUGreaterThanEqual %32 %40 %2 OpSelectionMerge %41 None -OpBranchConditional %32 %42 %43 +OpBranchConditional %33 %42 %43 %42 = OpLabel OpReturn %43 = OpLabel OpBranch %41 %41 = OpLabel -%46 = OpAccessChain %53 %47 %52 -%54 = OpAccessChain %56 %34 %55 +%48 = OpAccessChain %52 %50 %53 +%54 = OpAccessChain %55 %36 %56 %57 = OpLoad %8 %54 -%45 = OpAccessChain %58 %46 %57 -%44 = OpAccessChain %60 %45 %59 +%46 = OpAccessChain %58 %48 %57 +%44 = OpAccessChain %59 %46 %60 %61 = OpLoad %15 %44 OpStore %14 %61 -%64 = OpAccessChain %66 %47 %65 -%67 = OpAccessChain %69 %34 %68 +%64 = OpAccessChain %65 %50 %66 +%67 = OpAccessChain %68 %36 %69 %70 = OpLoad %8 %67 %63 = OpAccessChain %71 %64 %70 -%62 = OpAccessChain %73 %63 %72 +%62 = OpAccessChain %72 %63 %73 %74 = OpLoad %15 %62 OpStore %17 %74 %75 = OpCompositeConstruct %15 %4 %4 @@ -182,7 +182,7 @@ OpLoopMerge %79 %81 None OpBranch %80 %80 = OpLabel %83 = OpLoad %8 %26 -%82 = OpUGreaterThanEqual %40 %83 %2 +%82 = OpUGreaterThanEqual %32 %83 %2 OpSelectionMerge %84 None OpBranchConditional %82 %85 %86 %85 = OpLabel @@ -191,9 +191,9 @@ OpBranch %79 OpBranch %84 %84 = OpLabel %88 = OpLoad %8 %26 -%89 = OpAccessChain %91 %34 %90 +%89 = OpAccessChain %90 %36 %91 %92 = OpLoad %8 %89 -%87 = OpIEqual %40 %88 %92 +%87 = OpIEqual %32 %88 %92 OpSelectionMerge %93 None OpBranchConditional %87 %94 %95 %94 = OpLabel @@ -201,24 +201,24 @@ OpBranch %81 %95 = OpLabel OpBranch %93 %93 = OpLabel -%98 = OpAccessChain %100 %47 %99 +%98 = OpAccessChain %99 %50 %100 %101 = OpLoad %8 %26 %97 = OpAccessChain %102 %98 %101 -%96 = OpAccessChain %104 %97 %103 +%96 = OpAccessChain %103 %97 %104 %105 = OpLoad %15 %96 OpStore %24 %105 -%108 = OpAccessChain %110 %47 %109 +%108 = OpAccessChain %109 %50 %110 %111 = OpLoad %8 %26 %107 = OpAccessChain %112 %108 %111 -%106 = OpAccessChain %114 %107 %113 +%106 = OpAccessChain %113 %107 %114 %115 = OpLoad %15 %106 OpStore %25 %115 %117 = OpLoad %15 %24 %118 = OpLoad %15 %14 %119 = OpExtInst %5 %1 Distance %117 %118 -%120 = OpAccessChain %125 %121 %124 +%120 = OpAccessChain %124 %122 %125 %126 = OpLoad %5 %120 -%116 = OpFOrdLessThan %40 %119 %126 +%116 = OpFOrdLessThan %32 %119 %126 OpSelectionMerge %127 None OpBranchConditional %116 %128 %129 %128 = OpLabel @@ -236,9 +236,9 @@ OpBranch %127 %136 = OpLoad %15 %24 %137 = OpLoad %15 %14 %138 = OpExtInst %5 %1 Distance %136 %137 -%139 = OpAccessChain %141 %121 %140 +%139 = OpAccessChain %140 %122 %141 %142 = OpLoad %5 %139 -%135 = OpFOrdLessThan %40 %138 %142 +%135 = OpFOrdLessThan %32 %138 %142 OpSelectionMerge %143 None OpBranchConditional %135 %144 %145 %144 = OpLabel @@ -255,9 +255,9 @@ OpBranch %143 %152 = OpLoad %15 %24 %153 = OpLoad %15 %14 %154 = OpExtInst %5 %1 Distance %152 %153 -%155 = OpAccessChain %157 %121 %156 +%155 = OpAccessChain %156 %122 %157 %158 = OpLoad %5 %155 -%151 = OpFOrdLessThan %40 %154 %158 +%151 = OpFOrdLessThan %32 %154 %158 OpSelectionMerge %159 None OpBranchConditional %151 %160 %161 %160 = OpLabel @@ -280,7 +280,7 @@ OpStore %26 %167 OpBranch %78 %79 = OpLabel %170 = OpLoad %3 %21 -%169 = OpSGreaterThan %40 %170 %6 +%169 = OpSGreaterThan %32 %170 %6 OpSelectionMerge %171 None OpBranchConditional %169 %172 %173 %172 = OpLabel @@ -297,7 +297,7 @@ OpBranch %171 OpBranch %171 %171 = OpLabel %182 = OpLoad %3 %23 -%181 = OpSGreaterThan %40 %182 %6 +%181 = OpSGreaterThan %32 %182 %6 OpSelectionMerge %183 None OpBranchConditional %181 %184 %185 %184 = OpLabel @@ -313,17 +313,17 @@ OpBranch %183 %183 = OpLabel %194 = OpLoad %15 %17 %196 = OpLoad %15 %18 -%197 = OpAccessChain %199 %121 %198 +%197 = OpAccessChain %198 %122 %199 %200 = OpLoad %5 %197 %195 = OpVectorTimesScalar %15 %196 %200 %193 = OpFAdd %15 %194 %195 %202 = OpLoad %15 %20 -%203 = OpAccessChain %205 %121 %204 +%203 = OpAccessChain %204 %122 %205 %206 = OpLoad %5 %203 %201 = OpVectorTimesScalar %15 %202 %206 %192 = OpFAdd %15 %193 %201 %208 = OpLoad %15 %19 -%209 = OpAccessChain %211 %121 %210 +%209 = OpAccessChain %210 %122 %211 %212 = OpLoad %5 %209 %207 = OpVectorTimesScalar %15 %208 %212 %191 = OpFAdd %15 %192 %207 @@ -337,71 +337,71 @@ OpStore %17 %191 OpStore %17 %213 %220 = OpLoad %15 %14 %222 = OpLoad %15 %17 -%223 = OpAccessChain %225 %121 %224 +%223 = OpAccessChain %224 %122 %225 %226 = OpLoad %5 %223 %221 = OpVectorTimesScalar %15 %222 %226 %219 = OpFAdd %15 %220 %221 OpStore %14 %219 -%228 = OpAccessChain %230 %14 %229 +%228 = OpAccessChain %229 %14 %230 %231 = OpLoad %5 %228 -%227 = OpFOrdLessThan %40 %231 %13 +%227 = OpFOrdLessThan %32 %231 %13 OpSelectionMerge %232 None OpBranchConditional %227 %233 %234 %233 = OpLabel -%235 = OpAccessChain %237 %14 %236 +%235 = OpAccessChain %236 %14 %237 OpStore %235 %11 OpBranch %232 %234 = OpLabel OpBranch %232 %232 = OpLabel -%239 = OpAccessChain %241 %14 %240 +%239 = OpAccessChain %240 %14 %241 %242 = OpLoad %5 %239 -%238 = OpFOrdGreaterThan %40 %242 %11 +%238 = OpFOrdGreaterThan %32 %242 %11 OpSelectionMerge %243 None OpBranchConditional %238 %244 %245 %244 = OpLabel -%246 = OpAccessChain %248 %14 %247 +%246 = OpAccessChain %247 %14 %248 OpStore %246 %13 OpBranch %243 %245 = OpLabel OpBranch %243 %243 = OpLabel -%250 = OpAccessChain %252 %14 %251 +%250 = OpAccessChain %251 %14 %252 %253 = OpLoad %5 %250 -%249 = OpFOrdLessThan %40 %253 %13 +%249 = OpFOrdLessThan %32 %253 %13 OpSelectionMerge %254 None OpBranchConditional %249 %255 %256 %255 = OpLabel -%257 = OpAccessChain %259 %14 %258 +%257 = OpAccessChain %258 %14 %259 OpStore %257 %11 OpBranch %254 %256 = OpLabel OpBranch %254 %254 = OpLabel -%261 = OpAccessChain %263 %14 %262 +%261 = OpAccessChain %262 %14 %263 %264 = OpLoad %5 %261 -%260 = OpFOrdGreaterThan %40 %264 %11 +%260 = OpFOrdGreaterThan %32 %264 %11 OpSelectionMerge %265 None OpBranchConditional %260 %266 %267 %266 = OpLabel -%268 = OpAccessChain %270 %14 %269 +%268 = OpAccessChain %269 %14 %270 OpStore %268 %13 OpBranch %265 %267 = OpLabel OpBranch %265 %265 = OpLabel -%273 = OpAccessChain %276 %274 %275 -%277 = OpAccessChain %279 %34 %278 +%273 = OpAccessChain %275 %274 %276 +%277 = OpAccessChain %278 %36 %279 %280 = OpLoad %8 %277 %272 = OpAccessChain %281 %273 %280 -%271 = OpAccessChain %283 %272 %282 +%271 = OpAccessChain %282 %272 %283 %284 = OpLoad %15 %14 OpStore %271 %284 -%287 = OpAccessChain %289 %274 %288 -%290 = OpAccessChain %292 %34 %291 +%287 = OpAccessChain %288 %274 %289 +%290 = OpAccessChain %291 %36 %292 %293 = OpLoad %8 %290 %286 = OpAccessChain %294 %287 %293 -%285 = OpAccessChain %296 %286 %295 +%285 = OpAccessChain %295 %286 %296 %297 = OpLoad %15 %17 OpStore %285 %297 OpReturn diff --git a/tests/snapshots/snapshots__collatz.spvasm.snap b/tests/snapshots/snapshots__collatz.spvasm.snap index b2d30f32d..89a571a9c 100644 --- a/tests/snapshots/snapshots__collatz.spvasm.snap +++ b/tests/snapshots/snapshots__collatz.spvasm.snap @@ -9,14 +9,14 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %39 "main" %52 +OpEntryPoint GLCompute %39 "main" %53 OpExecutionMode %39 LocalSize 1 1 1 +OpDecorate %43 ArrayStride 4 OpDecorate %45 BufferBlock OpMemberDecorate %45 0 Offset 0 -OpDecorate %46 ArrayStride 4 -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 0 -OpDecorate %52 BuiltIn GlobalInvocationId +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 0 +OpDecorate %53 BuiltIn GlobalInvocationId %3 = OpTypeInt 32 0 %2 = OpConstant %3 0 %4 = OpConstant %3 1 @@ -24,26 +24,26 @@ OpDecorate %52 BuiltIn GlobalInvocationId %6 = OpConstant %3 3 %8 = OpTypePointer Function %3 %12 = OpTypeFunction %3 %3 -%20 = OpTypeBool +%18 = OpTypeBool %38 = OpTypeVoid %40 = OpTypeFunction %38 -%46 = OpTypeRuntimeArray %3 -%45 = OpTypeStruct %46 +%43 = OpTypeRuntimeArray %3 +%45 = OpTypeStruct %43 %47 = OpTypePointer Uniform %45 -%44 = OpVariable %47 Uniform -%48 = OpTypeInt 32 1 -%49 = OpConstant %48 0 -%50 = OpTypePointer Uniform %46 -%53 = OpTypeVector %3 3 -%54 = OpTypePointer Input %53 -%52 = OpVariable %54 Input -%55 = OpConstant %48 0 -%56 = OpTypePointer Input %3 +%46 = OpVariable %47 Uniform +%48 = OpTypePointer Uniform %43 +%49 = OpTypeInt 32 1 +%50 = OpConstant %49 0 +%52 = OpTypeVector %3 3 +%54 = OpTypePointer Input %52 +%53 = OpVariable %54 Input +%55 = OpTypePointer Input %3 +%56 = OpConstant %49 0 %58 = OpTypePointer Uniform %3 -%62 = OpConstant %48 0 -%63 = OpTypePointer Uniform %46 -%65 = OpConstant %48 0 -%66 = OpTypePointer Input %3 +%62 = OpTypePointer Uniform %43 +%63 = OpConstant %49 0 +%65 = OpTypePointer Input %3 +%66 = OpConstant %49 0 %68 = OpTypePointer Uniform %3 %11 = OpFunction %3 None %12 %10 = OpFunctionParameter %3 @@ -56,10 +56,10 @@ OpBranch %14 OpLoopMerge %15 %17 None OpBranch %16 %16 = OpLabel -%19 = OpLoad %3 %7 -%18 = OpULessThanEqual %20 %19 %4 +%20 = OpLoad %3 %7 +%19 = OpULessThanEqual %18 %20 %4 OpSelectionMerge %21 None -OpBranchConditional %18 %22 %23 +OpBranchConditional %19 %22 %23 %22 = OpLabel OpBranch %15 %23 = OpLabel @@ -67,7 +67,7 @@ OpBranch %21 %21 = OpLabel %26 = OpLoad %3 %7 %25 = OpUMod %3 %26 %5 -%24 = OpIEqual %20 %25 %2 +%24 = OpIEqual %18 %25 %2 OpSelectionMerge %27 None OpBranchConditional %24 %28 %29 %28 = OpLabel @@ -94,12 +94,12 @@ OpReturnValue %37 OpFunctionEnd %39 = OpFunction %38 None %40 %41 = OpLabel -%43 = OpAccessChain %50 %44 %49 -%51 = OpAccessChain %56 %52 %55 +%44 = OpAccessChain %48 %46 %50 +%51 = OpAccessChain %55 %53 %56 %57 = OpLoad %3 %51 -%42 = OpAccessChain %58 %43 %57 -%61 = OpAccessChain %63 %44 %62 -%64 = OpAccessChain %66 %52 %65 +%42 = OpAccessChain %58 %44 %57 +%61 = OpAccessChain %62 %46 %63 +%64 = OpAccessChain %65 %53 %66 %67 = OpLoad %3 %64 %60 = OpAccessChain %68 %61 %67 %69 = OpLoad %3 %60 diff --git a/tests/snapshots/snapshots__quad.spvasm.snap b/tests/snapshots/snapshots__quad.spvasm.snap index 145c7399a..1335b66ec 100644 --- a/tests/snapshots/snapshots__quad.spvasm.snap +++ b/tests/snapshots/snapshots__quad.spvasm.snap @@ -9,18 +9,18 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %7 "main" %20 %13 %10 %16 +OpEntryPoint Vertex %7 "main" %20 %13 %11 %17 OpEntryPoint Fragment %23 "main" %35 %25 OpExecutionMode %23 OriginUpperLeft -OpDecorate %10 Location 0 +OpDecorate %11 Location 0 OpDecorate %13 Location 1 -OpDecorate %16 BuiltIn Position +OpDecorate %17 BuiltIn Position OpDecorate %20 Location 0 OpDecorate %25 Location 0 -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 0 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 1 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 0 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 1 OpDecorate %35 Location 0 %3 = OpTypeFloat 32 %2 = OpConstant %3 1.2 @@ -28,41 +28,41 @@ OpDecorate %35 Location 0 %5 = OpConstant %3 1.0 %6 = OpTypeVoid %8 = OpTypeFunction %6 -%11 = OpTypeVector %3 2 -%12 = OpTypePointer Output %11 -%10 = OpVariable %12 Output -%14 = OpTypePointer Input %11 +%10 = OpTypeVector %3 2 +%12 = OpTypePointer Output %10 +%11 = OpVariable %12 Output +%14 = OpTypePointer Input %10 %13 = OpVariable %14 Input -%17 = OpTypeVector %3 4 -%18 = OpTypePointer Output %17 -%16 = OpVariable %18 Output +%16 = OpTypeVector %3 4 +%18 = OpTypePointer Output %16 +%17 = OpVariable %18 Output %20 = OpVariable %14 Input %25 = OpVariable %18 Output -%27 = OpTypeImage %3 2D 0 0 0 1 Unknown -%28 = OpTypePointer UniformConstant %27 -%26 = OpVariable %28 UniformConstant -%30 = OpTypeSampledImage %27 -%32 = OpTypeSampler -%33 = OpTypePointer UniformConstant %32 -%31 = OpVariable %33 UniformConstant +%26 = OpTypeImage %3 2D 0 0 0 1 Unknown +%28 = OpTypePointer UniformConstant %26 +%27 = OpVariable %28 UniformConstant +%30 = OpTypeSampledImage %26 +%31 = OpTypeSampler +%33 = OpTypePointer UniformConstant %31 +%32 = OpVariable %33 UniformConstant %35 = OpVariable %14 Input %7 = OpFunction %6 None %8 %9 = OpLabel -%15 = OpLoad %11 %13 -OpStore %10 %15 -%21 = OpLoad %11 %20 -%19 = OpVectorTimesScalar %11 %21 %2 -%22 = OpCompositeConstruct %17 %19 %4 %5 -OpStore %16 %22 +%15 = OpLoad %10 %13 +OpStore %11 %15 +%21 = OpLoad %10 %20 +%19 = OpVectorTimesScalar %10 %21 %2 +%22 = OpCompositeConstruct %16 %19 %4 %5 +OpStore %17 %22 OpReturn OpFunctionEnd %23 = OpFunction %6 None %8 %24 = OpLabel -%29 = OpLoad %27 %26 -%34 = OpLoad %32 %31 -%36 = OpLoad %11 %35 +%29 = OpLoad %26 %27 +%34 = OpLoad %31 %32 +%36 = OpLoad %10 %35 %37 = OpSampledImage %30 %29 %34 -%38 = OpImageSampleImplicitLod %17 %37 %36 +%38 = OpImageSampleImplicitLod %16 %37 %36 OpStore %25 %38 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__shadow.msl.snap b/tests/snapshots/snapshots__shadow.msl.snap index b8ad9bf19..0d62314ac 100644 --- a/tests/snapshots/snapshots__shadow.msl.snap +++ b/tests/snapshots/snapshots__shadow.msl.snap @@ -41,6 +41,8 @@ typedef int type9; typedef metal::float3 type10; +typedef bool type11; + type7 fetch_shadow( type6 light_id, type2 homogeneous_coords diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap index c0f1f29a2..8d13d1283 100644 --- a/tests/snapshots/snapshots__shadow.spvasm.snap +++ b/tests/snapshots/snapshots__shadow.spvasm.snap @@ -5,34 +5,34 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 220 +; Bound: 221 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %62 "fs_main" %113 %110 %216 -OpExecutionMode %62 OriginUpperLeft -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 2 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 3 -OpDecorate %74 Block -OpMemberDecorate %74 0 Offset 0 -OpDecorate %73 DescriptorSet 0 -OpDecorate %73 Binding 0 -OpDecorate %98 BufferBlock -OpMemberDecorate %98 0 Offset 0 -OpMemberDecorate %98 0 NonWritable +OpEntryPoint Fragment %64 "fs_main" %114 %111 %217 +OpExecutionMode %64 OriginUpperLeft +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 2 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 3 +OpDecorate %76 Block +OpMemberDecorate %76 0 Offset 0 +OpDecorate %77 DescriptorSet 0 +OpDecorate %77 Binding 0 +OpMemberDecorate %97 0 Offset 0 +OpMemberDecorate %97 0 ColMajor +OpMemberDecorate %97 0 MatrixStride 16 +OpMemberDecorate %97 1 Offset 64 +OpMemberDecorate %97 2 Offset 80 OpDecorate %99 ArrayStride 96 -OpMemberDecorate %100 0 Offset 0 -OpMemberDecorate %100 0 ColMajor -OpMemberDecorate %100 0 MatrixStride 16 -OpMemberDecorate %100 1 Offset 64 -OpMemberDecorate %100 2 Offset 80 -OpDecorate %97 DescriptorSet 0 -OpDecorate %97 Binding 1 -OpDecorate %110 Location 1 -OpDecorate %113 Location 0 -OpDecorate %216 Location 0 +OpDecorate %101 BufferBlock +OpMemberDecorate %101 0 Offset 0 +OpMemberDecorate %101 0 NonWritable +OpDecorate %102 DescriptorSet 0 +OpDecorate %102 Binding 1 +OpDecorate %111 Location 1 +OpDecorate %114 Location 0 +OpDecorate %217 Location 0 %3 = OpTypeFloat 32 %2 = OpConstant %3 0.0 %4 = OpConstant %3 1.0 @@ -47,227 +47,228 @@ OpDecorate %216 Location 0 %13 = OpConstant %11 1 %16 = OpTypeVector %3 4 %18 = OpTypeFunction %3 %11 %16 -%22 = OpTypeBool -%27 = OpTypeImage %3 2D 1 1 0 1 Unknown -%28 = OpTypePointer UniformConstant %27 -%26 = OpVariable %28 UniformConstant -%30 = OpTypeSampledImage %27 -%32 = OpTypeSampler -%33 = OpTypePointer UniformConstant %32 -%31 = OpVariable %33 UniformConstant -%38 = OpTypeVector %3 2 -%56 = OpConstant %3 0.0 -%58 = OpTypePointer Function %9 -%60 = OpTypePointer Function %11 -%61 = OpTypeVoid -%63 = OpTypeFunction %61 -%75 = OpTypeVector %11 4 -%74 = OpTypeStruct %75 -%76 = OpTypePointer Uniform %74 -%73 = OpVariable %76 Uniform -%77 = OpTypeInt 32 1 -%78 = OpConstant %77 0 -%79 = OpTypePointer Uniform %75 -%80 = OpConstant %77 0 +%20 = OpTypeBool +%26 = OpTypeImage %3 2D 1 1 0 1 Unknown +%28 = OpTypePointer UniformConstant %26 +%27 = OpVariable %28 UniformConstant +%30 = OpTypeSampledImage %26 +%31 = OpTypeSampler +%33 = OpTypePointer UniformConstant %31 +%32 = OpVariable %33 UniformConstant +%35 = OpTypeVector %3 2 +%49 = OpTypeInt 32 1 +%58 = OpConstant %3 0.0 +%60 = OpTypePointer Function %9 +%62 = OpTypePointer Function %11 +%63 = OpTypeVoid +%65 = OpTypeFunction %63 +%74 = OpTypeVector %11 4 +%76 = OpTypeStruct %74 +%78 = OpTypePointer Uniform %76 +%77 = OpVariable %78 Uniform +%79 = OpTypePointer Uniform %74 +%80 = OpConstant %49 0 %81 = OpTypePointer Uniform %11 -%101 = OpTypeMatrix %16 4 -%100 = OpTypeStruct %101 %16 %16 -%99 = OpTypeRuntimeArray %100 -%98 = OpTypeStruct %99 -%102 = OpTypePointer Uniform %98 -%97 = OpVariable %102 Uniform -%103 = OpConstant %77 0 +%82 = OpConstant %49 0 +%95 = OpTypeMatrix %16 4 +%97 = OpTypeStruct %95 %16 %16 +%99 = OpTypeRuntimeArray %97 +%101 = OpTypeStruct %99 +%103 = OpTypePointer Uniform %101 +%102 = OpVariable %103 Uniform %104 = OpTypePointer Uniform %99 -%106 = OpTypePointer Uniform %100 -%107 = OpConstant %77 0 -%108 = OpTypePointer Uniform %101 -%111 = OpTypePointer Input %16 -%110 = OpVariable %111 Input -%114 = OpTypePointer Input %9 -%113 = OpVariable %114 Input -%122 = OpConstant %77 0 +%105 = OpConstant %49 0 +%107 = OpTypePointer Uniform %97 +%108 = OpTypePointer Uniform %95 +%109 = OpConstant %49 0 +%112 = OpTypePointer Input %16 +%111 = OpVariable %112 Input +%115 = OpTypePointer Input %9 +%114 = OpVariable %115 Input %123 = OpTypePointer Uniform %99 -%125 = OpTypePointer Uniform %100 -%126 = OpConstant %77 1 +%124 = OpConstant %49 0 +%126 = OpTypePointer Uniform %97 %127 = OpTypePointer Uniform %16 -%128 = OpConstant %77 0 +%128 = OpConstant %49 1 %129 = OpTypePointer Uniform %3 -%135 = OpConstant %77 0 +%130 = OpConstant %49 0 %136 = OpTypePointer Uniform %99 -%138 = OpTypePointer Uniform %100 -%139 = OpConstant %77 1 +%137 = OpConstant %49 0 +%139 = OpTypePointer Uniform %97 %140 = OpTypePointer Uniform %16 -%141 = OpConstant %77 1 +%141 = OpConstant %49 1 %142 = OpTypePointer Uniform %3 -%148 = OpConstant %77 0 +%143 = OpConstant %49 1 %149 = OpTypePointer Uniform %99 -%151 = OpTypePointer Uniform %100 -%152 = OpConstant %77 1 +%150 = OpConstant %49 0 +%152 = OpTypePointer Uniform %97 %153 = OpTypePointer Uniform %16 -%154 = OpConstant %77 2 +%154 = OpConstant %49 1 %155 = OpTypePointer Uniform %3 -%159 = OpConstant %77 0 +%156 = OpConstant %49 2 %160 = OpTypePointer Input %3 -%163 = OpConstant %77 1 +%161 = OpConstant %49 0 %164 = OpTypePointer Input %3 -%167 = OpConstant %77 2 +%165 = OpConstant %49 1 %168 = OpTypePointer Input %3 -%178 = OpConstant %77 0 +%169 = OpConstant %49 2 %179 = OpTypePointer Uniform %99 -%181 = OpTypePointer Uniform %100 -%182 = OpConstant %77 2 +%180 = OpConstant %49 0 +%182 = OpTypePointer Uniform %97 %183 = OpTypePointer Uniform %16 -%184 = OpConstant %77 0 +%184 = OpConstant %49 2 %185 = OpTypePointer Uniform %3 -%191 = OpConstant %77 0 +%186 = OpConstant %49 0 %192 = OpTypePointer Uniform %99 -%194 = OpTypePointer Uniform %100 -%195 = OpConstant %77 2 +%193 = OpConstant %49 0 +%195 = OpTypePointer Uniform %97 %196 = OpTypePointer Uniform %16 -%197 = OpConstant %77 1 +%197 = OpConstant %49 2 %198 = OpTypePointer Uniform %3 -%204 = OpConstant %77 0 +%199 = OpConstant %49 1 %205 = OpTypePointer Uniform %99 -%207 = OpTypePointer Uniform %100 -%208 = OpConstant %77 2 +%206 = OpConstant %49 0 +%208 = OpTypePointer Uniform %97 %209 = OpTypePointer Uniform %16 -%210 = OpConstant %77 2 +%210 = OpConstant %49 2 %211 = OpTypePointer Uniform %3 -%217 = OpTypePointer Output %16 -%216 = OpVariable %217 Output +%212 = OpConstant %49 2 +%218 = OpTypePointer Output %16 +%217 = OpVariable %218 Output %17 = OpFunction %3 None %18 %14 = OpFunctionParameter %11 %15 = OpFunctionParameter %16 %19 = OpLabel -%21 = OpCompositeExtract %3 %15 3 -%20 = OpFOrdLessThanEqual %22 %21 %2 +%22 = OpCompositeExtract %3 %15 3 +%21 = OpFOrdLessThanEqual %20 %22 %2 OpSelectionMerge %23 None -OpBranchConditional %20 %24 %25 +OpBranchConditional %21 %24 %25 %24 = OpLabel OpReturnValue %4 %25 = OpLabel OpBranch %23 %23 = OpLabel -%29 = OpLoad %27 %26 -%34 = OpLoad %32 %31 +%29 = OpLoad %26 %27 +%34 = OpLoad %31 %32 %39 = OpCompositeExtract %3 %15 0 %40 = OpCompositeExtract %3 %15 1 -%41 = OpCompositeConstruct %38 %39 %40 -%42 = OpCompositeConstruct %38 %5 %6 -%37 = OpFMul %38 %41 %42 +%41 = OpCompositeConstruct %35 %39 %40 +%42 = OpCompositeConstruct %35 %5 %6 +%38 = OpFMul %35 %41 %42 %44 = OpCompositeExtract %3 %15 3 %43 = OpFDiv %3 %4 %44 -%36 = OpVectorTimesScalar %38 %37 %43 -%45 = OpCompositeConstruct %38 %5 %5 -%35 = OpFAdd %38 %36 %45 -%46 = OpCompositeExtract %3 %35 0 -%47 = OpCompositeExtract %3 %35 1 -%48 = OpConvertUToF %3 %14 -%49 = OpCompositeConstruct %9 %46 %47 %48 -%50 = OpSampledImage %30 %29 %34 -%53 = OpCompositeExtract %3 %15 2 -%55 = OpCompositeExtract %3 %15 3 -%54 = OpFDiv %3 %4 %55 -%52 = OpFMul %3 %53 %54 -%51 = OpImageSampleDrefExplicitLod %3 %50 %49 %52 Lod %56 -OpReturnValue %51 +%37 = OpVectorTimesScalar %35 %38 %43 +%45 = OpCompositeConstruct %35 %5 %5 +%36 = OpFAdd %35 %37 %45 +%46 = OpCompositeExtract %3 %36 0 +%47 = OpCompositeExtract %3 %36 1 +%50 = OpBitcast %49 %14 +%48 = OpConvertUToF %3 %50 +%51 = OpCompositeConstruct %9 %46 %47 %48 +%52 = OpSampledImage %30 %29 %34 +%55 = OpCompositeExtract %3 %15 2 +%57 = OpCompositeExtract %3 %15 3 +%56 = OpFDiv %3 %4 %57 +%54 = OpFMul %3 %55 %56 +%53 = OpImageSampleDrefExplicitLod %3 %52 %51 %54 Lod %58 +OpReturnValue %53 OpFunctionEnd -%62 = OpFunction %61 None %63 -%64 = OpLabel -%57 = OpVariable %58 Function %8 -%59 = OpVariable %60 Function %12 -OpBranch %65 -%65 = OpLabel -OpLoopMerge %66 %68 None +%64 = OpFunction %63 None %65 +%66 = OpLabel +%59 = OpVariable %60 Function %8 +%61 = OpVariable %62 Function %12 OpBranch %67 %67 = OpLabel -%70 = OpLoad %11 %59 -%72 = OpAccessChain %79 %73 %78 -%71 = OpAccessChain %81 %72 %80 -%82 = OpLoad %11 %71 -%83 = OpExtInst %11 %1 UMin %82 %10 -%69 = OpUGreaterThanEqual %22 %70 %83 -OpSelectionMerge %84 None -OpBranchConditional %69 %85 %86 -%85 = OpLabel -OpBranch %66 +OpLoopMerge %68 %70 None +OpBranch %69 +%69 = OpLabel +%72 = OpLoad %11 %61 +%75 = OpAccessChain %79 %77 %80 +%73 = OpAccessChain %81 %75 %82 +%83 = OpLoad %11 %73 +%84 = OpExtInst %11 %1 UMin %83 %10 +%71 = OpUGreaterThanEqual %20 %72 %84 +OpSelectionMerge %85 None +OpBranchConditional %71 %86 %87 %86 = OpLabel -OpBranch %84 -%84 = OpLabel -%88 = OpLoad %9 %57 -%92 = OpLoad %11 %59 -%96 = OpAccessChain %104 %97 %103 -%105 = OpLoad %11 %59 -%95 = OpAccessChain %106 %96 %105 -%94 = OpAccessChain %108 %95 %107 -%109 = OpLoad %101 %94 -%112 = OpLoad %16 %110 -%93 = OpMatrixTimesVector %16 %109 %112 -%91 = OpFunctionCall %3 %17 %92 %93 -%115 = OpLoad %9 %113 -%116 = OpExtInst %9 %1 Normalize %115 -%121 = OpAccessChain %123 %97 %122 -%124 = OpLoad %11 %59 -%120 = OpAccessChain %125 %121 %124 -%119 = OpAccessChain %127 %120 %126 -%118 = OpAccessChain %129 %119 %128 -%130 = OpLoad %3 %118 -%134 = OpAccessChain %136 %97 %135 -%137 = OpLoad %11 %59 -%133 = OpAccessChain %138 %134 %137 -%132 = OpAccessChain %140 %133 %139 -%131 = OpAccessChain %142 %132 %141 -%143 = OpLoad %3 %131 -%147 = OpAccessChain %149 %97 %148 -%150 = OpLoad %11 %59 -%146 = OpAccessChain %151 %147 %150 -%145 = OpAccessChain %153 %146 %152 -%144 = OpAccessChain %155 %145 %154 -%156 = OpLoad %3 %144 -%157 = OpCompositeConstruct %9 %130 %143 %156 -%158 = OpAccessChain %160 %110 %159 -%161 = OpLoad %3 %158 -%162 = OpAccessChain %164 %110 %163 -%165 = OpLoad %3 %162 -%166 = OpAccessChain %168 %110 %167 -%169 = OpLoad %3 %166 -%170 = OpCompositeConstruct %9 %161 %165 %169 -%117 = OpFSub %9 %157 %170 -%171 = OpExtInst %9 %1 Normalize %117 -%172 = OpDot %3 %116 %171 -%173 = OpExtInst %3 %1 FMax %2 %172 -%90 = OpFMul %3 %91 %173 -%177 = OpAccessChain %179 %97 %178 -%180 = OpLoad %11 %59 -%176 = OpAccessChain %181 %177 %180 -%175 = OpAccessChain %183 %176 %182 -%174 = OpAccessChain %185 %175 %184 -%186 = OpLoad %3 %174 -%190 = OpAccessChain %192 %97 %191 -%193 = OpLoad %11 %59 -%189 = OpAccessChain %194 %190 %193 -%188 = OpAccessChain %196 %189 %195 -%187 = OpAccessChain %198 %188 %197 -%199 = OpLoad %3 %187 -%203 = OpAccessChain %205 %97 %204 -%206 = OpLoad %11 %59 -%202 = OpAccessChain %207 %203 %206 -%201 = OpAccessChain %209 %202 %208 -%200 = OpAccessChain %211 %201 %210 -%212 = OpLoad %3 %200 -%213 = OpCompositeConstruct %9 %186 %199 %212 -%89 = OpVectorTimesScalar %9 %213 %90 -%87 = OpFAdd %9 %88 %89 -OpStore %57 %87 OpBranch %68 +%87 = OpLabel +OpBranch %85 +%85 = OpLabel +%89 = OpLoad %9 %59 +%93 = OpLoad %11 %61 +%100 = OpAccessChain %104 %102 %105 +%106 = OpLoad %11 %61 +%98 = OpAccessChain %107 %100 %106 +%96 = OpAccessChain %108 %98 %109 +%110 = OpLoad %95 %96 +%113 = OpLoad %16 %111 +%94 = OpMatrixTimesVector %16 %110 %113 +%92 = OpFunctionCall %3 %17 %93 %94 +%116 = OpLoad %9 %114 +%117 = OpExtInst %9 %1 Normalize %116 +%122 = OpAccessChain %123 %102 %124 +%125 = OpLoad %11 %61 +%121 = OpAccessChain %126 %122 %125 +%120 = OpAccessChain %127 %121 %128 +%119 = OpAccessChain %129 %120 %130 +%131 = OpLoad %3 %119 +%135 = OpAccessChain %136 %102 %137 +%138 = OpLoad %11 %61 +%134 = OpAccessChain %139 %135 %138 +%133 = OpAccessChain %140 %134 %141 +%132 = OpAccessChain %142 %133 %143 +%144 = OpLoad %3 %132 +%148 = OpAccessChain %149 %102 %150 +%151 = OpLoad %11 %61 +%147 = OpAccessChain %152 %148 %151 +%146 = OpAccessChain %153 %147 %154 +%145 = OpAccessChain %155 %146 %156 +%157 = OpLoad %3 %145 +%158 = OpCompositeConstruct %9 %131 %144 %157 +%159 = OpAccessChain %160 %111 %161 +%162 = OpLoad %3 %159 +%163 = OpAccessChain %164 %111 %165 +%166 = OpLoad %3 %163 +%167 = OpAccessChain %168 %111 %169 +%170 = OpLoad %3 %167 +%171 = OpCompositeConstruct %9 %162 %166 %170 +%118 = OpFSub %9 %158 %171 +%172 = OpExtInst %9 %1 Normalize %118 +%173 = OpDot %3 %117 %172 +%174 = OpExtInst %3 %1 FMax %2 %173 +%91 = OpFMul %3 %92 %174 +%178 = OpAccessChain %179 %102 %180 +%181 = OpLoad %11 %61 +%177 = OpAccessChain %182 %178 %181 +%176 = OpAccessChain %183 %177 %184 +%175 = OpAccessChain %185 %176 %186 +%187 = OpLoad %3 %175 +%191 = OpAccessChain %192 %102 %193 +%194 = OpLoad %11 %61 +%190 = OpAccessChain %195 %191 %194 +%189 = OpAccessChain %196 %190 %197 +%188 = OpAccessChain %198 %189 %199 +%200 = OpLoad %3 %188 +%204 = OpAccessChain %205 %102 %206 +%207 = OpLoad %11 %61 +%203 = OpAccessChain %208 %204 %207 +%202 = OpAccessChain %209 %203 %210 +%201 = OpAccessChain %211 %202 %212 +%213 = OpLoad %3 %201 +%214 = OpCompositeConstruct %9 %187 %200 %213 +%90 = OpVectorTimesScalar %9 %214 %91 +%88 = OpFAdd %9 %89 %90 +OpStore %59 %88 +OpBranch %70 +%70 = OpLabel +%216 = OpLoad %11 %61 +%215 = OpIAdd %11 %216 %13 +OpStore %61 %215 +OpBranch %67 %68 = OpLabel -%215 = OpLoad %11 %59 -%214 = OpIAdd %11 %215 %13 -OpStore %59 %214 -OpBranch %65 -%66 = OpLabel -%218 = OpLoad %9 %57 -%219 = OpCompositeConstruct %16 %218 %4 -OpStore %216 %219 +%219 = OpLoad %9 %59 +%220 = OpCompositeConstruct %16 %219 %4 +OpStore %217 %220 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap index 6c23904ab..d0577615b 100644 --- a/tests/snapshots/snapshots__skybox.spvasm.snap +++ b/tests/snapshots/snapshots__skybox.spvasm.snap @@ -5,31 +5,31 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 185 +; Bound: 187 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %16 "vs_main" %157 %44 %20 -OpEntryPoint Fragment %168 "fs_main" %180 %170 -OpExecutionMode %168 OriginUpperLeft -OpDecorate %20 BuiltIn VertexIndex -OpDecorate %29 Block -OpMemberDecorate %29 0 Offset 0 -OpMemberDecorate %29 0 ColMajor -OpMemberDecorate %29 0 MatrixStride 16 -OpMemberDecorate %29 1 Offset 64 -OpMemberDecorate %29 1 ColMajor -OpMemberDecorate %29 1 MatrixStride 16 -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 0 -OpDecorate %44 Location 0 -OpDecorate %157 BuiltIn Position -OpDecorate %170 Location 0 -OpDecorate %171 DescriptorSet 0 -OpDecorate %171 Binding 1 -OpDecorate %176 DescriptorSet 0 -OpDecorate %176 Binding 2 -OpDecorate %180 Location 0 +OpEntryPoint Vertex %16 "vs_main" %159 %47 %21 +OpEntryPoint Fragment %170 "fs_main" %182 %172 +OpExecutionMode %170 OriginUpperLeft +OpDecorate %21 BuiltIn VertexIndex +OpDecorate %31 Block +OpMemberDecorate %31 0 Offset 0 +OpMemberDecorate %31 0 ColMajor +OpMemberDecorate %31 0 MatrixStride 16 +OpMemberDecorate %31 1 Offset 64 +OpMemberDecorate %31 1 ColMajor +OpMemberDecorate %31 1 MatrixStride 16 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 0 +OpDecorate %47 Location 0 +OpDecorate %159 BuiltIn Position +OpDecorate %172 Location 0 +OpDecorate %174 DescriptorSet 0 +OpDecorate %174 Binding 1 +OpDecorate %179 DescriptorSet 0 +OpDecorate %179 Binding 2 +OpDecorate %182 Location 0 %3 = OpTypeInt 32 1 %2 = OpConstant %3 2 %4 = OpConstant %3 1 @@ -42,184 +42,186 @@ OpDecorate %180 Location 0 %14 = OpTypePointer Function %13 %15 = OpTypeVoid %17 = OpTypeFunction %15 -%21 = OpTypeInt 32 0 -%22 = OpTypePointer Input %21 -%20 = OpVariable %22 Input -%30 = OpTypeMatrix %13 4 -%29 = OpTypeStruct %30 %30 -%31 = OpTypePointer Uniform %29 -%28 = OpVariable %31 Uniform -%32 = OpConstant %3 0 -%33 = OpTypePointer Uniform %30 -%45 = OpTypeVector %6 3 -%46 = OpTypePointer Output %45 -%44 = OpVariable %46 Output -%48 = OpTypeMatrix %45 3 -%52 = OpConstant %3 1 -%53 = OpTypePointer Uniform %30 -%54 = OpConstant %3 0 -%55 = OpTypePointer Uniform %13 -%56 = OpConstant %3 0 -%57 = OpTypePointer Uniform %6 -%62 = OpConstant %3 1 -%63 = OpTypePointer Uniform %30 -%64 = OpConstant %3 0 -%65 = OpTypePointer Uniform %13 -%66 = OpConstant %3 1 -%67 = OpTypePointer Uniform %6 -%72 = OpConstant %3 1 -%73 = OpTypePointer Uniform %30 -%74 = OpConstant %3 0 -%75 = OpTypePointer Uniform %13 -%76 = OpConstant %3 2 -%77 = OpTypePointer Uniform %6 -%83 = OpConstant %3 1 -%84 = OpTypePointer Uniform %30 -%85 = OpConstant %3 1 -%86 = OpTypePointer Uniform %13 -%87 = OpConstant %3 0 -%88 = OpTypePointer Uniform %6 -%93 = OpConstant %3 1 -%94 = OpTypePointer Uniform %30 -%95 = OpConstant %3 1 -%96 = OpTypePointer Uniform %13 -%97 = OpConstant %3 1 -%98 = OpTypePointer Uniform %6 -%103 = OpConstant %3 1 -%104 = OpTypePointer Uniform %30 -%105 = OpConstant %3 1 -%106 = OpTypePointer Uniform %13 -%107 = OpConstant %3 2 -%108 = OpTypePointer Uniform %6 -%114 = OpConstant %3 1 -%115 = OpTypePointer Uniform %30 -%116 = OpConstant %3 2 -%117 = OpTypePointer Uniform %13 -%118 = OpConstant %3 0 -%119 = OpTypePointer Uniform %6 -%124 = OpConstant %3 1 -%125 = OpTypePointer Uniform %30 -%126 = OpConstant %3 2 -%127 = OpTypePointer Uniform %13 -%128 = OpConstant %3 1 -%129 = OpTypePointer Uniform %6 -%134 = OpConstant %3 1 -%135 = OpTypePointer Uniform %30 -%136 = OpConstant %3 2 -%137 = OpTypePointer Uniform %13 -%138 = OpConstant %3 2 -%139 = OpTypePointer Uniform %6 -%145 = OpConstant %3 0 -%146 = OpTypePointer Function %6 -%149 = OpConstant %3 1 -%150 = OpTypePointer Function %6 -%153 = OpConstant %3 2 -%154 = OpTypePointer Function %6 -%158 = OpTypePointer Output %13 -%157 = OpVariable %158 Output -%170 = OpVariable %158 Output -%172 = OpTypeImage %6 Cube 0 0 0 1 Unknown -%173 = OpTypePointer UniformConstant %172 -%171 = OpVariable %173 UniformConstant -%175 = OpTypeSampledImage %172 -%177 = OpTypeSampler -%178 = OpTypePointer UniformConstant %177 -%176 = OpVariable %178 UniformConstant -%181 = OpTypePointer Input %45 -%180 = OpVariable %181 Input +%20 = OpTypeInt 32 0 +%22 = OpTypePointer Input %20 +%21 = OpVariable %22 Input +%29 = OpTypeMatrix %13 4 +%31 = OpTypeStruct %29 %29 +%33 = OpTypePointer Uniform %31 +%32 = OpVariable %33 Uniform +%34 = OpTypePointer Uniform %29 +%35 = OpConstant %3 0 +%46 = OpTypeVector %6 3 +%48 = OpTypePointer Output %46 +%47 = OpVariable %48 Output +%50 = OpTypeMatrix %46 3 +%54 = OpTypePointer Uniform %29 +%55 = OpConstant %3 1 +%56 = OpTypePointer Uniform %13 +%57 = OpConstant %3 0 +%58 = OpTypePointer Uniform %6 +%59 = OpConstant %3 0 +%64 = OpTypePointer Uniform %29 +%65 = OpConstant %3 1 +%66 = OpTypePointer Uniform %13 +%67 = OpConstant %3 0 +%68 = OpTypePointer Uniform %6 +%69 = OpConstant %3 1 +%74 = OpTypePointer Uniform %29 +%75 = OpConstant %3 1 +%76 = OpTypePointer Uniform %13 +%77 = OpConstant %3 0 +%78 = OpTypePointer Uniform %6 +%79 = OpConstant %3 2 +%85 = OpTypePointer Uniform %29 +%86 = OpConstant %3 1 +%87 = OpTypePointer Uniform %13 +%88 = OpConstant %3 1 +%89 = OpTypePointer Uniform %6 +%90 = OpConstant %3 0 +%95 = OpTypePointer Uniform %29 +%96 = OpConstant %3 1 +%97 = OpTypePointer Uniform %13 +%98 = OpConstant %3 1 +%99 = OpTypePointer Uniform %6 +%100 = OpConstant %3 1 +%105 = OpTypePointer Uniform %29 +%106 = OpConstant %3 1 +%107 = OpTypePointer Uniform %13 +%108 = OpConstant %3 1 +%109 = OpTypePointer Uniform %6 +%110 = OpConstant %3 2 +%116 = OpTypePointer Uniform %29 +%117 = OpConstant %3 1 +%118 = OpTypePointer Uniform %13 +%119 = OpConstant %3 2 +%120 = OpTypePointer Uniform %6 +%121 = OpConstant %3 0 +%126 = OpTypePointer Uniform %29 +%127 = OpConstant %3 1 +%128 = OpTypePointer Uniform %13 +%129 = OpConstant %3 2 +%130 = OpTypePointer Uniform %6 +%131 = OpConstant %3 1 +%136 = OpTypePointer Uniform %29 +%137 = OpConstant %3 1 +%138 = OpTypePointer Uniform %13 +%139 = OpConstant %3 2 +%140 = OpTypePointer Uniform %6 +%141 = OpConstant %3 2 +%147 = OpTypePointer Function %6 +%148 = OpConstant %3 0 +%151 = OpTypePointer Function %6 +%152 = OpConstant %3 1 +%155 = OpTypePointer Function %6 +%156 = OpConstant %3 2 +%160 = OpTypePointer Output %13 +%159 = OpVariable %160 Output +%172 = OpVariable %160 Output +%173 = OpTypeImage %6 Cube 0 0 0 1 Unknown +%175 = OpTypePointer UniformConstant %173 +%174 = OpVariable %175 UniformConstant +%177 = OpTypeSampledImage %173 +%178 = OpTypeSampler +%180 = OpTypePointer UniformConstant %178 +%179 = OpVariable %180 UniformConstant +%183 = OpTypePointer Input %46 +%182 = OpVariable %183 Input %16 = OpFunction %15 None %17 %18 = OpLabel %9 = OpVariable %10 Function %11 = OpVariable %10 Function %12 = OpVariable %14 Function -%23 = OpLoad %21 %20 -%19 = OpSDiv %3 %23 %2 +%23 = OpLoad %20 %21 +%24 = OpBitcast %3 %23 +%19 = OpSDiv %3 %24 %2 OpStore %9 %19 -%25 = OpLoad %21 %20 -%24 = OpBitwiseAnd %3 %25 %4 -OpStore %11 %24 -%27 = OpAccessChain %33 %28 %32 -%34 = OpLoad %30 %27 -%37 = OpLoad %3 %9 -%38 = OpConvertSToF %6 %37 -%36 = OpFMul %6 %38 %5 -%35 = OpFSub %6 %36 %7 -%41 = OpLoad %3 %11 -%42 = OpConvertSToF %6 %41 -%40 = OpFMul %6 %42 %5 -%39 = OpFSub %6 %40 %7 -%43 = OpCompositeConstruct %13 %35 %39 %8 %7 -%26 = OpMatrixTimesVector %13 %34 %43 -OpStore %12 %26 -%51 = OpAccessChain %53 %28 %52 -%50 = OpAccessChain %55 %51 %54 -%49 = OpAccessChain %57 %50 %56 -%58 = OpLoad %6 %49 -%61 = OpAccessChain %63 %28 %62 -%60 = OpAccessChain %65 %61 %64 -%59 = OpAccessChain %67 %60 %66 -%68 = OpLoad %6 %59 -%71 = OpAccessChain %73 %28 %72 -%70 = OpAccessChain %75 %71 %74 -%69 = OpAccessChain %77 %70 %76 -%78 = OpLoad %6 %69 -%79 = OpCompositeConstruct %45 %58 %68 %78 -%82 = OpAccessChain %84 %28 %83 -%81 = OpAccessChain %86 %82 %85 -%80 = OpAccessChain %88 %81 %87 -%89 = OpLoad %6 %80 -%92 = OpAccessChain %94 %28 %93 -%91 = OpAccessChain %96 %92 %95 -%90 = OpAccessChain %98 %91 %97 -%99 = OpLoad %6 %90 -%102 = OpAccessChain %104 %28 %103 -%101 = OpAccessChain %106 %102 %105 -%100 = OpAccessChain %108 %101 %107 -%109 = OpLoad %6 %100 -%110 = OpCompositeConstruct %45 %89 %99 %109 -%113 = OpAccessChain %115 %28 %114 -%112 = OpAccessChain %117 %113 %116 -%111 = OpAccessChain %119 %112 %118 -%120 = OpLoad %6 %111 -%123 = OpAccessChain %125 %28 %124 -%122 = OpAccessChain %127 %123 %126 -%121 = OpAccessChain %129 %122 %128 -%130 = OpLoad %6 %121 -%133 = OpAccessChain %135 %28 %134 -%132 = OpAccessChain %137 %133 %136 -%131 = OpAccessChain %139 %132 %138 -%140 = OpLoad %6 %131 -%141 = OpCompositeConstruct %45 %120 %130 %140 -%142 = OpCompositeConstruct %48 %79 %110 %141 -%143 = OpTranspose %48 %142 -%144 = OpAccessChain %146 %12 %145 -%147 = OpLoad %6 %144 -%148 = OpAccessChain %150 %12 %149 -%151 = OpLoad %6 %148 -%152 = OpAccessChain %154 %12 %153 -%155 = OpLoad %6 %152 -%156 = OpCompositeConstruct %45 %147 %151 %155 -%47 = OpMatrixTimesVector %45 %143 %156 -OpStore %44 %47 -%161 = OpLoad %3 %9 -%162 = OpConvertSToF %6 %161 -%160 = OpFMul %6 %162 %5 -%159 = OpFSub %6 %160 %7 -%165 = OpLoad %3 %11 -%166 = OpConvertSToF %6 %165 -%164 = OpFMul %6 %166 %5 -%163 = OpFSub %6 %164 %7 -%167 = OpCompositeConstruct %13 %159 %163 %8 %7 -OpStore %157 %167 +%26 = OpLoad %20 %21 +%27 = OpBitcast %3 %26 +%25 = OpBitwiseAnd %3 %27 %4 +OpStore %11 %25 +%30 = OpAccessChain %34 %32 %35 +%36 = OpLoad %29 %30 +%39 = OpLoad %3 %9 +%40 = OpConvertSToF %6 %39 +%38 = OpFMul %6 %40 %5 +%37 = OpFSub %6 %38 %7 +%43 = OpLoad %3 %11 +%44 = OpConvertSToF %6 %43 +%42 = OpFMul %6 %44 %5 +%41 = OpFSub %6 %42 %7 +%45 = OpCompositeConstruct %13 %37 %41 %8 %7 +%28 = OpMatrixTimesVector %13 %36 %45 +OpStore %12 %28 +%53 = OpAccessChain %54 %32 %55 +%52 = OpAccessChain %56 %53 %57 +%51 = OpAccessChain %58 %52 %59 +%60 = OpLoad %6 %51 +%63 = OpAccessChain %64 %32 %65 +%62 = OpAccessChain %66 %63 %67 +%61 = OpAccessChain %68 %62 %69 +%70 = OpLoad %6 %61 +%73 = OpAccessChain %74 %32 %75 +%72 = OpAccessChain %76 %73 %77 +%71 = OpAccessChain %78 %72 %79 +%80 = OpLoad %6 %71 +%81 = OpCompositeConstruct %46 %60 %70 %80 +%84 = OpAccessChain %85 %32 %86 +%83 = OpAccessChain %87 %84 %88 +%82 = OpAccessChain %89 %83 %90 +%91 = OpLoad %6 %82 +%94 = OpAccessChain %95 %32 %96 +%93 = OpAccessChain %97 %94 %98 +%92 = OpAccessChain %99 %93 %100 +%101 = OpLoad %6 %92 +%104 = OpAccessChain %105 %32 %106 +%103 = OpAccessChain %107 %104 %108 +%102 = OpAccessChain %109 %103 %110 +%111 = OpLoad %6 %102 +%112 = OpCompositeConstruct %46 %91 %101 %111 +%115 = OpAccessChain %116 %32 %117 +%114 = OpAccessChain %118 %115 %119 +%113 = OpAccessChain %120 %114 %121 +%122 = OpLoad %6 %113 +%125 = OpAccessChain %126 %32 %127 +%124 = OpAccessChain %128 %125 %129 +%123 = OpAccessChain %130 %124 %131 +%132 = OpLoad %6 %123 +%135 = OpAccessChain %136 %32 %137 +%134 = OpAccessChain %138 %135 %139 +%133 = OpAccessChain %140 %134 %141 +%142 = OpLoad %6 %133 +%143 = OpCompositeConstruct %46 %122 %132 %142 +%144 = OpCompositeConstruct %50 %81 %112 %143 +%145 = OpTranspose %50 %144 +%146 = OpAccessChain %147 %12 %148 +%149 = OpLoad %6 %146 +%150 = OpAccessChain %151 %12 %152 +%153 = OpLoad %6 %150 +%154 = OpAccessChain %155 %12 %156 +%157 = OpLoad %6 %154 +%158 = OpCompositeConstruct %46 %149 %153 %157 +%49 = OpMatrixTimesVector %46 %145 %158 +OpStore %47 %49 +%163 = OpLoad %3 %9 +%164 = OpConvertSToF %6 %163 +%162 = OpFMul %6 %164 %5 +%161 = OpFSub %6 %162 %7 +%167 = OpLoad %3 %11 +%168 = OpConvertSToF %6 %167 +%166 = OpFMul %6 %168 %5 +%165 = OpFSub %6 %166 %7 +%169 = OpCompositeConstruct %13 %161 %165 %8 %7 +OpStore %159 %169 OpReturn OpFunctionEnd -%168 = OpFunction %15 None %17 -%169 = OpLabel -%174 = OpLoad %172 %171 -%179 = OpLoad %177 %176 -%182 = OpLoad %45 %180 -%183 = OpSampledImage %175 %174 %179 -%184 = OpImageSampleImplicitLod %13 %183 %182 -OpStore %170 %184 +%170 = OpFunction %15 None %17 +%171 = OpLabel +%176 = OpLoad %173 %174 +%181 = OpLoad %178 %179 +%184 = OpLoad %46 %182 +%185 = OpSampledImage %177 %176 %181 +%186 = OpImageSampleImplicitLod %13 %185 %184 +OpStore %172 %186 OpReturn OpFunctionEnd From e05baa2889e1d7cf6da436c3aa1d1536c330ae9d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 1 Feb 2021 20:17:50 -0500 Subject: [PATCH 0422/2212] [spv] put NonWritable on buffer variable itself (#405) --- src/back/spv/writer.rs | 71 +++++++------------ tests/snapshots/snapshots__boids.spvasm.snap | 1 + tests/snapshots/snapshots__shadow.spvasm.snap | 2 +- 3 files changed, 27 insertions(+), 47 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b5cfe69d7..ea806152b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -709,24 +709,19 @@ impl Writer { block: true, ref members, } => { - //TODO: put NonWritable/NonReadable on the global variable instead? - let storage_access = match self.struct_type_handles.get(&handle) { - Some(&access) => { - let decoration = if access.is_empty() { - spirv::Decoration::Block - } else { - spirv::Decoration::BufferBlock - }; - self.annotations - .push(super::instructions::instruction_decorate( - id, - decoration, - &[], - )); - access - } - None => crate::StorageAccess::empty(), - }; + if let Some(&access) = self.struct_type_handles.get(&handle) { + let decoration = if access.is_empty() { + spirv::Decoration::Block + } else { + spirv::Decoration::BufferBlock + }; + self.annotations + .push(super::instructions::instruction_decorate( + id, + decoration, + &[], + )); + } let mut current_offset = 0; let mut member_ids = Vec::with_capacity(members.len()); @@ -756,16 +751,6 @@ impl Writer { } } - if storage_access == crate::StorageAccess::LOAD { - self.annotations - .push(super::instructions::instruction_member_decorate( - id, - index as u32, - spirv::Decoration::NonWritable, - &[], - )); - } - if let crate::TypeInner::Matrix { columns, rows: _, @@ -939,24 +924,18 @@ impl Writer { } } - if let crate::TypeInner::Image { - class: crate::ImageClass::Storage(_), - .. - } = ir_module.types[global_variable.ty].inner - { - let decoration = match global_variable.storage_access { - crate::StorageAccess::LOAD => Some(spirv::Decoration::NonWritable), - crate::StorageAccess::STORE => Some(spirv::Decoration::NonReadable), - _ => None, - }; - if let Some(decoration) = decoration { - self.annotations - .push(super::instructions::instruction_decorate( - id, - decoration, - &[], - )); - } + let access_decoration = match global_variable.storage_access { + crate::StorageAccess::LOAD => Some(spirv::Decoration::NonWritable), + crate::StorageAccess::STORE => Some(spirv::Decoration::NonReadable), + _ => None, + }; + if let Some(decoration) = access_decoration { + self.annotations + .push(super::instructions::instruction_decorate( + id, + decoration, + &[], + )); } if let Some(interpolation) = global_variable.interpolation { diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap index fac29f9aa..19989836c 100644 --- a/tests/snapshots/snapshots__boids.spvasm.snap +++ b/tests/snapshots/snapshots__boids.spvasm.snap @@ -17,6 +17,7 @@ OpMemberDecorate %45 1 Offset 8 OpDecorate %47 ArrayStride 16 OpDecorate %49 BufferBlock OpMemberDecorate %49 0 Offset 0 +OpDecorate %50 NonWritable OpDecorate %50 DescriptorSet 0 OpDecorate %50 Binding 1 OpDecorate %121 Block diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap index 8d13d1283..e6e199112 100644 --- a/tests/snapshots/snapshots__shadow.spvasm.snap +++ b/tests/snapshots/snapshots__shadow.spvasm.snap @@ -27,7 +27,7 @@ OpMemberDecorate %97 2 Offset 80 OpDecorate %99 ArrayStride 96 OpDecorate %101 BufferBlock OpMemberDecorate %101 0 Offset 0 -OpMemberDecorate %101 0 NonWritable +OpDecorate %102 NonWritable OpDecorate %102 DescriptorSet 0 OpDecorate %102 Binding 1 OpDecorate %111 Location 1 From 68bbf00249451343046b0a9f84ea72f3effdcc12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 31 Jan 2021 16:57:01 +0000 Subject: [PATCH 0423/2212] Added support for initalizers and constants --- src/front/glsl/ast.rs | 31 ++++++- src/front/glsl/functions.rs | 10 +++ src/front/glsl/lex.rs | 1 + src/front/glsl/parser.rs | 91 +++++++++++++------ src/front/glsl/parser_tests.rs | 56 ++++++++++++ src/front/glsl/variables.rs | 3 + src/lib.rs | 4 +- src/proc/constants.rs | 157 +++++++++++++++++++++++++++++++++ src/proc/mod.rs | 2 + 9 files changed, 321 insertions(+), 34 deletions(-) create mode 100644 src/proc/constants.rs diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 647c3a627..4ebc2da02 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,7 +1,7 @@ use super::error::ErrorKind; use crate::{ - proc::{ResolveContext, Typifier}, - Arena, BinaryOperator, Binding, Expression, FastHashMap, Function, FunctionArgument, + proc::{ConstantSolver, ResolveContext, Typifier}, + Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, ShaderStage, Statement, StorageClass, Type, }; @@ -15,6 +15,7 @@ pub struct Program { pub lookup_function: FastHashMap>, pub lookup_type: FastHashMap>, pub lookup_global_variables: FastHashMap>, + pub lookup_constants: FastHashMap>, pub context: Context, pub module: Module, } @@ -29,12 +30,14 @@ impl Program { lookup_function: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_global_variables: FastHashMap::default(), + lookup_constants: FastHashMap::default(), context: Context { expressions: Arena::::new(), local_variables: Arena::::new(), arguments: Vec::new(), scopes: vec![FastHashMap::default()], lookup_global_var_exps: FastHashMap::default(), + lookup_constant_exps: FastHashMap::default(), typifier: Typifier::new(), }, module: Module::generate_empty(), @@ -76,6 +79,21 @@ impl Program { Ok(()) => Ok(self.context.typifier.get(handle, &self.module.types)), } } + + pub fn solve_constant( + &mut self, + root: Handle, + ) -> Result, ErrorKind> { + let mut solver = ConstantSolver { + types: &self.module.types, + expressions: &self.context.expressions, + constants: &mut self.module.constants, + }; + + solver + .solve(root) + .map_err(|_| ErrorKind::SemanticError("Can't solve constant".into())) + } } #[derive(Debug)] @@ -91,6 +109,7 @@ pub struct Context { //TODO: Find less allocation heavy representation pub scopes: Vec>>, pub lookup_global_var_exps: FastHashMap>, + pub lookup_constant_exps: FastHashMap>, pub typifier: Typifier, } @@ -154,7 +173,7 @@ impl ExpressionRule { #[derive(Debug)] pub enum TypeQualifier { - StorageClass(StorageClass), + StorageQualifier(StorageQualifier), Binding(Binding), Interpolation(Interpolation), } @@ -177,3 +196,9 @@ pub struct FunctionCall { pub kind: FunctionCallKind, pub args: Vec, } + +#[derive(Debug, Clone, Copy)] +pub enum StorageQualifier { + StorageClass(StorageClass), + Const, +} diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 42d2721b1..7ec4b4e11 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -179,6 +179,16 @@ impl Program { } } } + + for (handle, constant) in self.module.constants.iter() { + if let Some(name) = constant.name.as_ref() { + let expr = self + .context + .expressions + .append(Expression::Constant(handle)); + self.context.lookup_constant_exps.insert(name.clone(), expr); + } + } } pub fn function_definition(&mut self, mut f: Function, mut block: Block) -> Function { diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index e5412c8a8..d3bb1645b 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -182,6 +182,7 @@ impl<'a> Lexer<'a> { "for" => Some(Token::For(meta)), // types "void" => Some(Token::Void(meta)), + "const" => Some(Token::Const(meta)), word => { let token = match parse_type(word) { Some(t) => Token::TypeName((meta, t)), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 7985313c3..b9c889cd7 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -114,7 +114,7 @@ pomelo! { %type layout_qualifier_id (String, u32); %type type_qualifier Vec; %type single_type_qualifier TypeQualifier; - %type storage_qualifier StorageClass; + %type storage_qualifier StorageQualifier; %type interpolation_qualifier Interpolation; %type Interpolation Interpolation; @@ -627,7 +627,7 @@ pomelo! { } single_type_qualifier ::= storage_qualifier(s) { - TypeQualifier::StorageClass(s) + TypeQualifier::StorageQualifier(s) } single_type_qualifier ::= layout_qualifier(l) { TypeQualifier::Binding(l) @@ -639,19 +639,21 @@ pomelo! { // single_type_qualifier ::= invariant_qualifier; // single_type_qualifier ::= precise_qualifier; - // storage_qualifier ::= Const + storage_qualifier ::= Const { + StorageQualifier::Const + } // storage_qualifier ::= InOut; storage_qualifier ::= In { - StorageClass::Input + StorageQualifier::StorageClass(StorageClass::Input) } storage_qualifier ::= Out { - StorageClass::Output + StorageQualifier::StorageClass(StorageClass::Output) } // storage_qualifier ::= Centroid; // storage_qualifier ::= Patch; // storage_qualifier ::= Sample; storage_qualifier ::= Uniform { - StorageClass::Uniform + StorageQualifier::StorageClass(StorageClass::Uniform) } //TODO: other storage qualifiers @@ -1062,32 +1064,63 @@ pomelo! { } external_declaration ::= declaration(d) { if let Some(d) = d { - let class = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::StorageClass(sc) = tq { Some(*sc) } else { None } - }).unwrap_or(StorageClass::Private); + // TODO: handle multiple storage qualifiers + let storage = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::StorageQualifier(sc) = tq { Some(*sc) } else { None } + }).unwrap_or(StorageQualifier::StorageClass(StorageClass::Private)); - let binding = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } - }); + match storage { + StorageQualifier::StorageClass(class) => { + // TODO: Check that the storage qualifiers allow for the bindings + let binding = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } + }); - let interpolation = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Interpolation(i) = tq { Some(*i) } else { None } - }); + let interpolation = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Interpolation(i) = tq { Some(*i) } else { None } + }); - for (id, initializer) in d.ids_initializers { - let h = extra.module.global_variables.fetch_or_append( - GlobalVariable { - name: id.clone(), - class, - binding: binding.clone(), - ty: d.ty, - init: None, - interpolation, - storage_access: StorageAccess::empty(), //TODO - }, - ); - if let Some(id) = id { - extra.lookup_global_variables.insert(id, h); + for (id, initializer) in d.ids_initializers { + let init = initializer.map(|init| extra.solve_constant(init.expression)).transpose()?; + + let h = extra.module.global_variables.fetch_or_append( + GlobalVariable { + name: id.clone(), + class, + binding: binding.clone(), + ty: d.ty, + init, + interpolation, + storage_access: StorageAccess::empty(), //TODO + }, + ); + if let Some(id) = id { + extra.lookup_global_variables.insert(id, h); + } + } + } + StorageQualifier::Const => { + for (id, initializer) in d.ids_initializers { + if let Some(init) = initializer { + let constant = extra.solve_constant(init.expression)?; + let inner = extra.module.constants[constant].inner.clone(); + + let h = extra.module.constants.fetch_or_append( + Constant { + name: id.clone(), + specialization: None, // TODO + inner + }, + ); + if let Some(id) = id { + extra.lookup_constants.insert(id.clone(), h); + let expr = extra.context.expressions.append(Expression::Constant(h)); + extra.context.lookup_constant_exps.insert(id, expr); + } + } else { + return Err(ErrorKind::SemanticError("Constants must have an initalizer".into())) + } + } } } } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index b586c8bbc..1e0a8e719 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -231,3 +231,59 @@ fn functions() { ) .unwrap(); } + +#[test] +fn constants() { + use crate::{Constant, ConstantInner, ScalarValue}; + + let program = parse_program( + r#" + # version 450 + const float a = 1.0; + float global = a; + const flat float b = a; + "#, + ShaderStage::Vertex, + ) + .unwrap(); + + let mut constants = program.module.constants.iter(); + + assert_eq!( + constants.next().unwrap().1, + &Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(1.0) + } + } + ); + + assert_eq!( + constants.next().unwrap().1, + &Constant { + name: Some(String::from("a")), + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(1.0) + } + } + ); + + assert_eq!( + constants.next().unwrap().1, + &Constant { + name: Some(String::from("b")), + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(1.0) + } + } + ); + + assert!(constants.next().is_none()); +} diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 70022a2ac..78b522ec5 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -15,6 +15,9 @@ impl Program { if let Some(global_var) = self.context.lookup_global_var_exps.get(name) { return Ok(Some(*global_var)); } + if let Some(constant) = self.context.lookup_constant_exps.get(name) { + return Ok(Some(*constant)); + } match name { "gl_Position" => { #[cfg(feature = "glsl-validate")] diff --git a/src/lib.rs b/src/lib.rs index 297454fe9..9db837dd3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -401,7 +401,7 @@ pub struct Constant { } /// A literal scalar value, used in constants. -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Clone)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ScalarValue { @@ -412,7 +412,7 @@ pub enum ScalarValue { } /// Additional information, dependendent on the kind of constant. -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Clone)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ConstantInner { diff --git a/src/proc/constants.rs b/src/proc/constants.rs new file mode 100644 index 000000000..ec705515b --- /dev/null +++ b/src/proc/constants.rs @@ -0,0 +1,157 @@ +use crate::{ + arena::{Arena, Handle}, + ArraySize, Constant, ConstantInner, Expression, ScalarValue, Type, +}; + +#[derive(Debug)] +pub struct ConstantSolver<'a> { + pub types: &'a Arena, + pub expressions: &'a Arena, + pub constants: &'a mut Arena, +} + +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +pub enum ConstantSolvingError { + #[error("Constants cannot access function arguments")] + FunctionArg, + #[error("Constants cannot access global variables")] + GlobalVariable, + #[error("Constants cannot access local variables")] + LocalVariable, + #[error("Cannot get the array length of a non array type")] + InvalidArrayLengthArg, + #[error("Constants cannot get the array length of a dynamically sized array")] + ArrayLengthDynamic, + #[error("Constants cannot call functions")] + Call, + #[error("Constants don't support relational functions")] + Relational, + #[error("Constants don't support derivative functions")] + Derivative, + #[error("Constants don't support select expressions")] + Select, + #[error("Constants don't support load expressions")] + Load, + #[error("Constants don't support image expressions")] + ImageExpression, + #[error("Cannot access the type")] + InvalidAccessBase, + #[error("Cannot access at the index")] + InvalidAccessIndex, + #[error("Cannot access with index of type")] + InvalidAccessIndexTy, +} + +impl<'a> ConstantSolver<'a> { + pub fn solve( + &mut self, + expr: Handle, + ) -> Result, ConstantSolvingError> { + match self.expressions[expr] { + Expression::Constant(constant) => Ok(constant), + Expression::AccessIndex { base, index } => self.access(base, index as usize), + Expression::Access { base, index } => { + let index = self.solve(index)?; + + self.access(base, self.constant_index(index)?) + } + Expression::Compose { ty, ref components } => { + let components = components + .iter() + .map(|c| self.solve(*c)) + .collect::>()?; + + Ok(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { ty, components }, + })) + } + Expression::Unary { .. } => todo!(), + Expression::Binary { .. } => todo!(), + Expression::Math { .. } => todo!(), + Expression::As { .. } => todo!(), + Expression::ArrayLength(expr) => { + let array = self.solve(expr)?; + + match self.constants[array].inner { + crate::ConstantInner::Scalar { .. } => { + Err(ConstantSolvingError::InvalidArrayLengthArg) + } + crate::ConstantInner::Composite { ty, .. } => match self.types[ty].inner { + crate::TypeInner::Array { size, .. } => match size { + crate::ArraySize::Constant(constant) => Ok(constant), + crate::ArraySize::Dynamic => { + Err(ConstantSolvingError::ArrayLengthDynamic) + } + }, + _ => Err(ConstantSolvingError::InvalidArrayLengthArg), + }, + } + } + + Expression::Load { .. } => Err(ConstantSolvingError::Load), + Expression::Select { .. } => Err(ConstantSolvingError::Select), + Expression::LocalVariable(_) => Err(ConstantSolvingError::LocalVariable), + Expression::Derivative { .. } => Err(ConstantSolvingError::Derivative), + Expression::Relational { .. } => Err(ConstantSolvingError::Relational), + Expression::Call { .. } => Err(ConstantSolvingError::Call), + Expression::FunctionArgument(_) => Err(ConstantSolvingError::FunctionArg), + Expression::GlobalVariable(_) => Err(ConstantSolvingError::GlobalVariable), + Expression::ImageSample { .. } => Err(ConstantSolvingError::ImageExpression), + Expression::ImageLoad { .. } => Err(ConstantSolvingError::ImageExpression), + } + } + + fn access( + &mut self, + base: Handle, + index: usize, + ) -> Result, ConstantSolvingError> { + let base = self.solve(base)?; + + match self.constants[base].inner { + crate::ConstantInner::Scalar { .. } => Err(ConstantSolvingError::InvalidAccessBase), + crate::ConstantInner::Composite { ty, ref components } => match self.types[ty].inner { + crate::TypeInner::Vector { size, .. } => { + if size as usize <= index { + Err(ConstantSolvingError::InvalidAccessIndex) + } else { + Ok(components[index]) + } + } + crate::TypeInner::Matrix { .. } => todo!(), + crate::TypeInner::Array { size, .. } => match size { + ArraySize::Constant(constant) => { + let size = self.constant_index(constant)?; + + if size <= index { + Err(ConstantSolvingError::InvalidAccessIndex) + } else { + Ok(components[index]) + } + } + ArraySize::Dynamic => Err(ConstantSolvingError::ArrayLengthDynamic), + }, + crate::TypeInner::Struct { ref members, .. } => { + if members.len() <= index { + Err(ConstantSolvingError::InvalidAccessIndex) + } else { + Ok(components[index]) + } + } + _ => Err(ConstantSolvingError::InvalidAccessBase), + }, + } + } + + fn constant_index(&self, constant: Handle) -> Result { + match self.constants[constant].inner { + ConstantInner::Scalar { + value: ScalarValue::Uint(index), + .. + } => Ok(index as usize), + _ => Err(ConstantSolvingError::InvalidAccessIndexTy), + } + } +} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 5dec4285b..7aa2ca056 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -2,6 +2,7 @@ #[cfg(feature = "petgraph")] mod call_graph; +mod constants; mod interface; mod layouter; mod namer; @@ -11,6 +12,7 @@ mod validator; #[cfg(feature = "petgraph")] pub use call_graph::{CallGraph, CallGraphBuilder}; +pub use constants::{ConstantSolver, ConstantSolvingError}; pub use interface::{Interface, Visitor}; pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; From 53bd7218959694125be881718047684130d99695 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 31 Jan 2021 20:26:04 +0000 Subject: [PATCH 0424/2212] Add support for casts in constant expressions --- src/proc/constants.rs | 70 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/src/proc/constants.rs b/src/proc/constants.rs index ec705515b..37560a06b 100644 --- a/src/proc/constants.rs +++ b/src/proc/constants.rs @@ -1,6 +1,6 @@ use crate::{ arena::{Arena, Handle}, - ArraySize, Constant, ConstantInner, Expression, ScalarValue, Type, + ArraySize, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, }; #[derive(Debug)] @@ -40,6 +40,10 @@ pub enum ConstantSolvingError { InvalidAccessIndex, #[error("Cannot access with index of type")] InvalidAccessIndexTy, + #[error("Constants don't support bitcasts")] + Bitcast, + #[error("Cannot cast type")] + InvalidCastArg, } impl<'a> ConstantSolver<'a> { @@ -70,7 +74,19 @@ impl<'a> ConstantSolver<'a> { Expression::Unary { .. } => todo!(), Expression::Binary { .. } => todo!(), Expression::Math { .. } => todo!(), - Expression::As { .. } => todo!(), + Expression::As { + convert, + expr, + kind, + } => { + let tgt = self.solve(expr)?; + + if convert { + self.cast(tgt, kind) + } else { + Err(ConstantSolvingError::Bitcast) + } + } Expression::ArrayLength(expr) => { let array = self.solve(expr)?; @@ -154,4 +170,54 @@ impl<'a> ConstantSolver<'a> { _ => Err(ConstantSolvingError::InvalidAccessIndexTy), } } + + fn cast( + &mut self, + constant: Handle, + kind: ScalarKind, + ) -> Result, ConstantSolvingError> { + fn inner_cast(value: ScalarValue) -> A { + match value { + ScalarValue::Sint(v) => A::from_i64(v), + ScalarValue::Uint(v) => A::from_u64(v), + ScalarValue::Float(v) => A::from_f64(v), + ScalarValue::Bool(v) => A::from_u64(v as u64), + } + .unwrap() + } + + let mut inner = self.constants[constant].inner.clone(); + + match inner { + ConstantInner::Scalar { ref mut value, .. } => { + let intial = value.clone(); + + match kind { + ScalarKind::Sint => *value = ScalarValue::Sint(inner_cast(intial)), + ScalarKind::Uint => *value = ScalarValue::Uint(inner_cast(intial)), + ScalarKind::Float => *value = ScalarValue::Float(inner_cast(intial)), + ScalarKind::Bool => *value = ScalarValue::Bool(inner_cast::(intial) == 0), + } + } + ConstantInner::Composite { + ty, + ref mut components, + } => { + match self.types[ty].inner { + crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => (), + _ => return Err(ConstantSolvingError::InvalidCastArg), + } + + for component in components { + *component = self.cast(*component, kind)?; + } + } + } + + Ok(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner, + })) + } } From fcbf2aa4c48cb8874f15fade4df6320dbcbc8eaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 1 Feb 2021 14:58:26 +0000 Subject: [PATCH 0425/2212] Add support for unary ops to the constant solver Fix wrong result when casting to bool Add tests --- src/proc/constants.rs | 218 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 215 insertions(+), 3 deletions(-) diff --git a/src/proc/constants.rs b/src/proc/constants.rs index 37560a06b..8097ed80c 100644 --- a/src/proc/constants.rs +++ b/src/proc/constants.rs @@ -1,6 +1,6 @@ use crate::{ arena::{Arena, Handle}, - ArraySize, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, + ArraySize, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, UnaryOperator, }; #[derive(Debug)] @@ -44,6 +44,8 @@ pub enum ConstantSolvingError { Bitcast, #[error("Cannot cast type")] InvalidCastArg, + #[error("Cannot apply the unary op to the argument")] + InvalidUnaryOpArg, } impl<'a> ConstantSolver<'a> { @@ -71,7 +73,11 @@ impl<'a> ConstantSolver<'a> { inner: ConstantInner::Composite { ty, components }, })) } - Expression::Unary { .. } => todo!(), + Expression::Unary { expr, op } => { + let tgt = self.solve(expr)?; + + self.unary_op(op, tgt) + } Expression::Binary { .. } => todo!(), Expression::Math { .. } => todo!(), Expression::As { @@ -196,7 +202,7 @@ impl<'a> ConstantSolver<'a> { ScalarKind::Sint => *value = ScalarValue::Sint(inner_cast(intial)), ScalarKind::Uint => *value = ScalarValue::Uint(inner_cast(intial)), ScalarKind::Float => *value = ScalarValue::Float(inner_cast(intial)), - ScalarKind::Bool => *value = ScalarValue::Bool(inner_cast::(intial) == 0), + ScalarKind::Bool => *value = ScalarValue::Bool(inner_cast::(intial) != 0), } } ConstantInner::Composite { @@ -220,4 +226,210 @@ impl<'a> ConstantSolver<'a> { inner, })) } + + fn unary_op( + &mut self, + op: UnaryOperator, + constant: Handle, + ) -> Result, ConstantSolvingError> { + let mut inner = self.constants[constant].inner.clone(); + + match inner { + ConstantInner::Scalar { ref mut value, .. } => match op { + UnaryOperator::Negate => match value { + ScalarValue::Sint(v) => *v = -*v, + ScalarValue::Float(v) => *v = -*v, + _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + }, + UnaryOperator::Not => match value { + ScalarValue::Sint(v) => *v = !*v, + ScalarValue::Uint(v) => *v = !*v, + ScalarValue::Bool(v) => *v = !*v, + _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + }, + }, + ConstantInner::Composite { + ty, + ref mut components, + } => { + match self.types[ty].inner { + crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => (), + _ => return Err(ConstantSolvingError::InvalidCastArg), + } + + for component in components { + *component = self.unary_op(op, *component)? + } + } + } + + Ok(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner, + })) + } +} + +#[cfg(test)] +mod tests { + use std::vec; + + use crate::{ + Arena, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, TypeInner, + UnaryOperator, VectorSize, + }; + + use super::ConstantSolver; + + #[test] + fn unary_op() { + let mut types = Arena::new(); + let mut expressions = Arena::new(); + let mut constants = Arena::new(); + + let vec_ty = types.append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Sint, + width: 4, + }, + }); + + let h = constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(4), + }, + }); + + let h1 = constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(8), + }, + }); + + let vec_h = constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: vec_ty, + components: vec![h, h1], + }, + }); + + let expr = expressions.append(Expression::Constant(h)); + let expr1 = expressions.append(Expression::Constant(vec_h)); + + let root1 = expressions.append(Expression::Unary { + op: UnaryOperator::Negate, + expr, + }); + + let root2 = expressions.append(Expression::Unary { + op: UnaryOperator::Not, + expr, + }); + + let root3 = expressions.append(Expression::Unary { + op: UnaryOperator::Not, + expr: expr1, + }); + + let mut solver = ConstantSolver { + types: &types, + expressions: &expressions, + constants: &mut constants, + }; + + let res1 = solver.solve(root1).unwrap(); + let res2 = solver.solve(root2).unwrap(); + let res3 = solver.solve(root3).unwrap(); + + assert_eq!( + constants[res1].inner, + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(-4), + }, + ); + + assert_eq!( + constants[res2].inner, + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(!4), + }, + ); + + let res3_inner = &constants[res3].inner; + + match res3_inner { + ConstantInner::Composite { ty, components } => { + assert_eq!(*ty, vec_ty); + let mut components_iter = components.iter().copied(); + assert_eq!( + constants[components_iter.next().unwrap()].inner, + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(!4), + }, + ); + assert_eq!( + constants[components_iter.next().unwrap()].inner, + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(!8), + }, + ); + assert!(components_iter.next().is_none()); + } + _ => panic!("Expected vector"), + } + } + + #[test] + fn cast() { + let mut expressions = Arena::new(); + let mut constants = Arena::new(); + + let h = constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(4), + }, + }); + + let expr = expressions.append(Expression::Constant(h)); + + let root = expressions.append(Expression::As { + expr, + kind: ScalarKind::Bool, + convert: true, + }); + + let mut solver = ConstantSolver { + types: &Arena::new(), + expressions: &expressions, + constants: &mut constants, + }; + + let res = solver.solve(root).unwrap(); + + assert_eq!( + constants[res].inner, + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Bool(true), + }, + ); + } } From bb88aac937f2eed5ffe6b4ab2d137d32864392eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 1 Feb 2021 21:36:30 +0000 Subject: [PATCH 0426/2212] Add matrix access to ConstantSolver --- src/proc/constants.rs | 189 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 155 insertions(+), 34 deletions(-) diff --git a/src/proc/constants.rs b/src/proc/constants.rs index 8097ed80c..d7b28b2ba 100644 --- a/src/proc/constants.rs +++ b/src/proc/constants.rs @@ -1,6 +1,6 @@ use crate::{ arena::{Arena, Handle}, - ArraySize, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, UnaryOperator, + Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, UnaryOperator, }; #[derive(Debug)] @@ -134,36 +134,20 @@ impl<'a> ConstantSolver<'a> { match self.constants[base].inner { crate::ConstantInner::Scalar { .. } => Err(ConstantSolvingError::InvalidAccessBase), - crate::ConstantInner::Composite { ty, ref components } => match self.types[ty].inner { - crate::TypeInner::Vector { size, .. } => { - if size as usize <= index { - Err(ConstantSolvingError::InvalidAccessIndex) - } else { - Ok(components[index]) - } + crate::ConstantInner::Composite { ty, ref components } => { + match self.types[ty].inner { + crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } + | crate::TypeInner::Array { .. } + | crate::TypeInner::Struct { .. } => (), + _ => return Err(ConstantSolvingError::InvalidAccessBase), } - crate::TypeInner::Matrix { .. } => todo!(), - crate::TypeInner::Array { size, .. } => match size { - ArraySize::Constant(constant) => { - let size = self.constant_index(constant)?; - if size <= index { - Err(ConstantSolvingError::InvalidAccessIndex) - } else { - Ok(components[index]) - } - } - ArraySize::Dynamic => Err(ConstantSolvingError::ArrayLengthDynamic), - }, - crate::TypeInner::Struct { ref members, .. } => { - if members.len() <= index { - Err(ConstantSolvingError::InvalidAccessIndex) - } else { - Ok(components[index]) - } - } - _ => Err(ConstantSolvingError::InvalidAccessBase), - }, + components + .get(index) + .copied() + .ok_or(ConstantSolvingError::InvalidAccessIndex) + } } } @@ -198,11 +182,11 @@ impl<'a> ConstantSolver<'a> { ConstantInner::Scalar { ref mut value, .. } => { let intial = value.clone(); - match kind { - ScalarKind::Sint => *value = ScalarValue::Sint(inner_cast(intial)), - ScalarKind::Uint => *value = ScalarValue::Uint(inner_cast(intial)), - ScalarKind::Float => *value = ScalarValue::Float(inner_cast(intial)), - ScalarKind::Bool => *value = ScalarValue::Bool(inner_cast::(intial) != 0), + *value = match kind { + ScalarKind::Sint => ScalarValue::Sint(inner_cast(intial)), + ScalarKind::Uint => ScalarValue::Uint(inner_cast(intial)), + ScalarKind::Float => ScalarValue::Float(inner_cast(intial)), + ScalarKind::Bool => ScalarValue::Bool(inner_cast::(intial) != 0), } } ConstantInner::Composite { @@ -432,4 +416,141 @@ mod tests { }, ); } + + #[test] + fn access() { + let mut types = Arena::new(); + let mut expressions = Arena::new(); + let mut constants = Arena::new(); + + let matrix_ty = types.append(Type { + name: None, + inner: TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Tri, + width: 4, + }, + }); + + let vec_ty = types.append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Float, + width: 4, + }, + }); + + let mut vec1_components = Vec::with_capacity(3); + let mut vec2_components = Vec::with_capacity(3); + + for i in 0..3 { + let h = constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(i as f64), + }, + }); + + vec1_components.push(h) + } + + for i in 3..6 { + let h = constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(i as f64), + }, + }); + + vec2_components.push(h) + } + + let vec1 = constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: vec_ty, + components: vec1_components, + }, + }); + + let vec2 = constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: vec_ty, + components: vec2_components, + }, + }); + + let h = constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: matrix_ty, + components: vec![vec1, vec2], + }, + }); + + let base = expressions.append(Expression::Constant(h)); + let root1 = expressions.append(Expression::AccessIndex { base, index: 1 }); + let root2 = expressions.append(Expression::AccessIndex { + base: root1, + index: 2, + }); + + let mut solver = ConstantSolver { + types: &types, + expressions: &expressions, + constants: &mut constants, + }; + + let res1 = solver.solve(root1).unwrap(); + let res2 = solver.solve(root2).unwrap(); + + let res1_inner = &constants[res1].inner; + + match res1_inner { + ConstantInner::Composite { ty, components } => { + assert_eq!(*ty, vec_ty); + let mut components_iter = components.iter().copied(); + assert_eq!( + constants[components_iter.next().unwrap()].inner, + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(3.), + }, + ); + assert_eq!( + constants[components_iter.next().unwrap()].inner, + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(4.), + }, + ); + assert_eq!( + constants[components_iter.next().unwrap()].inner, + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(5.), + }, + ); + assert!(components_iter.next().is_none()); + } + _ => panic!("Expected vector"), + } + + assert_eq!( + constants[res2].inner, + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(5.), + }, + ); + } } From 71fdaedcecdb32ae62b039533e772bd1535b53f3 Mon Sep 17 00:00:00 2001 From: tfgast Date: Wed, 3 Feb 2021 16:11:39 -0800 Subject: [PATCH 0427/2212] FragDepth is a Write Property FragDepth is written to in a fragment shader, not read. --- src/proc/validator.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 7febb7f53..f31606f40 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -257,7 +257,7 @@ fn built_in_usage(built_in: crate::BuiltIn) -> (crate::ShaderStage, crate::Globa Bi::Position => (Ss::Vertex, Gu::WRITE), Bi::VertexIndex => (Ss::Vertex, Gu::READ), Bi::FragCoord => (Ss::Fragment, Gu::READ), - Bi::FragDepth => (Ss::Fragment, Gu::READ), + Bi::FragDepth => (Ss::Fragment, Gu::WRITE), Bi::FrontFacing => (Ss::Fragment, Gu::READ), Bi::SampleIndex => (Ss::Fragment, Gu::READ), Bi::SampleMaskIn => (Ss::Fragment, Gu::READ), From 0970ef0ea5d2b8e479b5337edc76fb99089a762d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 3 Feb 2021 11:32:12 -0500 Subject: [PATCH 0428/2212] [spv-in] derive the block status of a structure from its members --- src/front/spv/mod.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index fc07e58b4..b0a09dbcd 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -34,6 +34,7 @@ use std::{convert::TryInto, num::NonZeroU32, path::PathBuf}; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, spirv::Capability::CullDistance, + spirv::Capability::ImageQuery, spirv::Capability::StorageImageExtendedFormats, ]; pub const SUPPORTED_EXTENSIONS: &[&str] = &[]; @@ -2016,6 +2017,7 @@ impl> Parser { let mut members = Vec::with_capacity(inst.wc as usize - 2); let mut member_type_ids = Vec::with_capacity(members.capacity()); + let mut host_shared = false; for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; member_type_ids.push(type_id); @@ -2024,6 +2026,8 @@ impl> Parser { .future_member_decor .remove(&(id, i)) .unwrap_or_default(); + // this is a bit of a hack + host_shared |= decor.offset.is_some(); members.push(crate::StructMember { name: decor.name, span: None, //TODO @@ -2032,7 +2036,7 @@ impl> Parser { } let inner = crate::TypeInner::Struct { - block: block_decor.is_some(), + block: block_decor.is_some() || host_shared, members, }; let ty_handle = module.types.append(crate::Type { From 423ccc207441a150f6bb74e87a4e77993cad0b77 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 3 Feb 2021 11:55:43 -0500 Subject: [PATCH 0429/2212] [spv-in] parse OpConstantNull and OpUndef --- src/front/spv/mod.rs | 71 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index b0a09dbcd..9984b5a00 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -519,6 +519,12 @@ impl> Parser { log::debug!("\t\t{:?} [{}]", inst.op, inst.wc); match inst.op { + Op::Undef => { + inst.expect(3)?; + let _result_type_id = self.next()?; + let _result_id = self.next()?; + //TODO? + } Op::Variable => { inst.expect_at_least(4)?; let result_type_id = self.next()?; @@ -801,7 +807,7 @@ impl> Parser { inst.expect(5)?; self.parse_expr_binary_op(expressions, crate::BinaryOperator::Divide)?; } - Op::UMod | Op::FMod | Op::SRem | Op::FRem => { + Op::SMod | Op::UMod | Op::FMod | Op::SRem | Op::FRem => { inst.expect(5)?; self.parse_expr_binary_op(expressions, crate::BinaryOperator::Modulo)?; } @@ -1503,8 +1509,15 @@ impl> Parser { Op::TypeImage => self.parse_type_image(inst, &mut module), Op::TypeSampledImage => self.parse_type_sampled_image(inst), Op::TypeSampler => self.parse_type_sampler(inst, &mut module), + Op::Undef => { + inst.expect(3)?; + let _result_type_id = self.next()?; + let _result_id = self.next()?; + Ok(()) //TODO? + } Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), + Op::ConstantNull => self.parse_null_constant(inst, &mut module), Op::Variable => self.parse_global_variable(inst, &mut module), Op::Function => self.parse_function(inst, &mut module), _ => Err(Error::UnsupportedInstruction(self.state, inst.op)), //TODO @@ -2170,6 +2183,7 @@ impl> Parser { let id = self.next()?; let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; + let inner = match module.types[ty].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, @@ -2229,6 +2243,7 @@ impl> Parser { } _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; + self.lookup_constant.insert( id, LookupConstant { @@ -2273,7 +2288,61 @@ impl> Parser { type_id, }, ); + Ok(()) + } + fn parse_null_constant( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(3)?; + let type_id = self.next()?; + let id = self.next()?; + let type_lookup = self.lookup_type.lookup(type_id)?; + let ty = type_lookup.handle; + + fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { + crate::ConstantInner::Scalar { + width, + value: match kind { + crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), + crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), + crate::ScalarKind::Float => crate::ScalarValue::Float(0.0), + crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), + }, + } + } + + let inner = match module.types[ty].inner { + crate::TypeInner::Scalar { kind, width } => make_scalar_inner(kind, width), + crate::TypeInner::Vector { size, kind, width } => { + let mut components = Vec::with_capacity(size as usize); + for _ in 0..size as usize { + components.push(module.constants.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner: make_scalar_inner(kind, width), + })); + } + crate::ConstantInner::Composite { ty, components } + } + //TODO: handle matrices, arrays, and structures + _ => return Err(Error::UnsupportedType(type_lookup.handle)), + }; + + self.lookup_constant.insert( + id, + LookupConstant { + handle: module.constants.append(crate::Constant { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + specialization: None, //TODO + inner, + }), + type_id, + }, + ); Ok(()) } From f563b5810bac6458809899c5563af7c89140ece5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 3 Feb 2021 13:01:50 -0500 Subject: [PATCH 0430/2212] [spv-in] support OpImage, OpImageFetch, OpLogicalOr, OpLogicalAnd, relational functions, and fix OpUndef --- src/front/spv/convert.rs | 17 ++++- src/front/spv/error.rs | 4 +- src/front/spv/mod.rs | 153 ++++++++++++++++++++++++++------------- 3 files changed, 121 insertions(+), 53 deletions(-) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index e2259aa4e..269506719 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -30,7 +30,22 @@ pub fn map_binary_operator(word: spirv::Op) -> Result Ok(BinaryOperator::GreaterEqual), - _ => Err(Error::UnknownInstruction(word as u16)), + _ => Err(Error::UnknownBinaryOperator(word)), + } +} + +pub fn map_relational_fun(word: spirv::Op) -> Result { + use crate::RelationalFunction as Rf; + use spirv::Op; + + match word { + Op::All => Ok(Rf::All), + Op::Any => Ok(Rf::Any), + Op::IsNan => Ok(Rf::IsNan), + Op::IsInf => Ok(Rf::IsInf), + Op::IsFinite => Ok(Rf::IsFinite), + Op::IsNormal => Ok(Rf::IsNormal), + _ => Err(Error::UnknownRelationalFunction(word)), } } diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 0ebf60391..cc484ea47 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -22,6 +22,8 @@ pub enum Error { UnsupportedBuiltIn(spirv::Word), UnsupportedControlFlow(spirv::Word), UnsupportedBinaryOperator(spirv::Word), + UnknownBinaryOperator(spirv::Op), + UnknownRelationalFunction(spirv::Op), InvalidParameter(spirv::Op), InvalidOperandCount(spirv::Op, u16), InvalidOperand, @@ -39,9 +41,7 @@ pub enum Error { InvalidImageExpression(Handle), InvalidImageBaseType(Handle), InvalidSamplerExpression(Handle), - InvalidSampleImage(Handle), InvalidSampleSampler(Handle), - InvalidSampleCoordinates(Handle), InvalidDepthReference(Handle), InvalidAsType(Handle), InconsistentComparisonSampling(Handle), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 9984b5a00..1396221f0 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -730,6 +730,7 @@ impl> Parser { }, ); } + //TODO: Op::CompositeInsert Op::CompositeConstruct => { inst.expect_at_least(3)?; let result_type_id = self.next()?; @@ -893,6 +894,19 @@ impl> Parser { self.parse_expr_binary_op(expressions, crate::BinaryOperator::ShiftLeft)?; } // Sampling + Op::Image => { + inst.expect(4)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let sampled_image_id = self.next()?; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: self.lookup_sampled_image.lookup(sampled_image_id)?.image, + type_id: result_type_id, + }, + ); + } Op::SampledImage => { inst.expect(5)?; let _result_type_id = self.next()?; @@ -910,6 +924,64 @@ impl> Parser { }, ); } + Op::ImageFetch => { + inst.expect_at_least(5)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + let coordinate_id = self.next()?; + + let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?.clone(); + let image_type_handle = + reach_global_type(image_lexp.handle, &expressions, global_arena) + .ok_or(Error::InvalidImageExpression(image_lexp.handle))?; + *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= + SamplingFlags::REGULAR; + + let mut index = None; + let mut base_wc = 5; + while base_wc < inst.wc { + let image_ops = self.next()?; + base_wc += 1; + match spirv::ImageOperands::from_bits_truncate(image_ops) { + spirv::ImageOperands::LOD => { + let lod_expr = self.next()?; + let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; + index = Some(lod_handle); + base_wc += 1; + } + spirv::ImageOperands::SAMPLE => { + let sample_expr = self.next()?; + let sample_handle = + self.lookup_expression.lookup(sample_expr)?.handle; + index = Some(sample_handle); + base_wc += 1; + } + other => { + log::warn!("Skipping {:?}", other); + for _ in base_wc..inst.wc { + self.next()?; + } + break; + } + } + } + + let expr = crate::Expression::ImageLoad { + image: image_lexp.handle, + coordinate: coord_lexp.handle, + array_index: None, //TODO: this will break + index, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } Op::ImageSampleImplicitLod | Op::ImageSampleExplicitLod => { inst.expect_at_least(5)?; let result_type_id = self.next()?; @@ -918,7 +990,7 @@ impl> Parser { let coordinate_id = self.next()?; let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?.clone(); let coord_lexp = self.lookup_expression.lookup(coordinate_id)?.clone(); - let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + //let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; let sampler_type_handle = reach_global_type(si_lexp.sampler, &expressions, global_arena) @@ -940,29 +1012,6 @@ impl> Parser { _ => return Err(Error::InvalidSampleSampler(sampler_type_handle)), }; - match type_arena[image_type_handle].inner { - //TODO: compare the result type - crate::TypeInner::Image { - dim, - arrayed, - class: - crate::ImageClass::Sampled { - kind: _, - multi: false, - }, - } => { - if !check_sample_coordinates( - &type_arena[coord_type_handle], - crate::ScalarKind::Float, - dim, - arrayed, - ) { - return Err(Error::InvalidSampleCoordinates(coord_type_handle)); - } - } - _ => return Err(Error::InvalidSampleImage(image_type_handle)), - }; - let mut level = crate::SampleLevel::Auto; let mut base_wc = 5; while base_wc < inst.wc { @@ -1021,7 +1070,7 @@ impl> Parser { let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + //let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; let sampler_type_handle = reach_global_type(si_lexp.sampler, &expressions, global_arena) .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; @@ -1036,24 +1085,6 @@ impl> Parser { crate::TypeInner::Sampler { comparison: true } => (), _ => return Err(Error::InvalidSampleSampler(sampler_type_handle)), }; - match type_arena[image_type_handle].inner { - //TODO: compare the result type - crate::TypeInner::Image { - dim, - arrayed, - class: crate::ImageClass::Depth, - } => { - if !check_sample_coordinates( - &type_arena[coord_type_handle], - crate::ScalarKind::Float, - dim, - arrayed, - ) { - return Err(Error::InvalidSampleCoordinates(coord_type_handle)); - } - } - _ => return Err(Error::InvalidSampleImage(image_type_handle)), - }; let dref_lexp = self.lookup_expression.lookup(dref_id)?; let dref_type_handle = self.lookup_type.lookup(dref_lexp.type_id)?.handle; @@ -1314,10 +1345,38 @@ impl> Parser { inst.expect(4)?; self.parse_expr_unary_op(expressions, crate::UnaryOperator::Not)?; } + Op::LogicalOr => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::LogicalOr)?; + } + Op::LogicalAnd => { + inst.expect(5)?; + self.parse_expr_binary_op(expressions, crate::BinaryOperator::LogicalAnd)?; + } op if inst.op >= Op::IEqual && inst.op <= Op::FUnordGreaterThanEqual => { inst.expect(5)?; self.parse_expr_binary_op(expressions, map_binary_operator(op)?)?; } + op if inst.op >= Op::Any && inst.op <= Op::IsNormal => { + inst.expect(4)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let arg_id = self.next()?; + + let arg_lexp = self.lookup_expression.lookup(arg_id)?; + + let expr = crate::Expression::Relational { + fun: map_relational_fun(op)?, + argument: arg_lexp.handle, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } Op::Kill => { inst.expect(1)?; break Terminator::Kill; @@ -1509,15 +1568,9 @@ impl> Parser { Op::TypeImage => self.parse_type_image(inst, &mut module), Op::TypeSampledImage => self.parse_type_sampled_image(inst), Op::TypeSampler => self.parse_type_sampler(inst, &mut module), - Op::Undef => { - inst.expect(3)?; - let _result_type_id = self.next()?; - let _result_id = self.next()?; - Ok(()) //TODO? - } Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), - Op::ConstantNull => self.parse_null_constant(inst, &mut module), + Op::ConstantNull | Op::Undef => self.parse_null_constant(inst, &mut module), Op::Variable => self.parse_global_variable(inst, &mut module), Op::Function => self.parse_function(inst, &mut module), _ => Err(Error::UnsupportedInstruction(self.state, inst.op)), //TODO From ac27a1abaaadf142815ae0294e169b1cdb1b743c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 5 Feb 2021 00:44:28 -0500 Subject: [PATCH 0431/2212] Don't break upon a void function in the typifier --- src/proc/typifier.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index b367713c9..07577c412 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -48,8 +48,6 @@ pub enum ResolveError { InvalidAccessIndex, #[error("Function {name} not defined")] FunctionNotDefined { name: String }, - #[error("Function without return type")] - FunctionReturnsVoid, #[error("Type is not found in the given immutable arena")] TypeNotFound, #[error("Incompatible operand: {op} {operand}")] @@ -439,10 +437,13 @@ impl Typifier { function, arguments: _, } => { - let ty = ctx.functions[function] - .return_type - .ok_or(ResolveError::FunctionReturnsVoid)?; - Resolution::Handle(ty) + match ctx.functions[function].return_type { + Some(ty) => Resolution::Handle(ty), + // return a type that can't ever be returned... + // We don't have `void` in the IR, but we have to return something here. + // This is also not a place to validate anything. + None => Resolution::Value(crate::TypeInner::Sampler { comparison: false }), + } } crate::Expression::ArrayLength(_) => Resolution::Value(crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, From c496c05ba413af699c1d2621ce741d45ab04d499 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 5 Feb 2021 12:22:24 -0500 Subject: [PATCH 0432/2212] Makefile commands for native shader validation --- Makefile | 33 +++++++++++++++++-- README.md | 22 +++++++++++++ src/back/glsl/mod.rs | 6 +--- .../snapshots__quad-Fragment.glsl.snap | 2 +- .../snapshots__skybox-Fragment.glsl.snap | 2 +- 5 files changed, 55 insertions(+), 10 deletions(-) diff --git a/Makefile b/Makefile index db45f2362..f5d6b08b4 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,13 @@ -.PHONY: all clean +.PHONY: all clean validate-spv validate-msl .SECONDARY: boids.metal quad.metal +SNAPSHOTS=tests/snapshots all: clean: - rm *.metal *.air *.metallib *.vert *.frag *.comp + rm *.metal *.air *.metallib *.vert *.frag *.comp *.spv -%.metal: tests/snapshots/in/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) +%.metal: $(SNAPSHOTS)/in/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) cargo run --example convert --features wgsl-in,msl-out -- $< $@ %.air: %.metal @@ -22,3 +23,29 @@ clean: %.vert %.frag %.comp: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) cargo run --example convert --features wgsl-in,glsl-out -- $< $@ glslangValidator $@ + +validate-spv: $(SNAPSHOTS)/*.spvasm.snap + @for file in $^ ; do \ + echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"}; \ + tail -n +5 $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ + done + +validate-msl: $(SNAPSHOTS)/*.msl.snap + @for file in $^ ; do \ + echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"}; \ + tail -n +5 $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ + done + +validate-glsl: $(SNAPSHOTS)/*.glsl.snap + @for file in $(SNAPSHOTS)/*-Vertex.glsl.snap ; do \ + echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"};\ + tail -n +5 $${file} | glslangValidator --stdin -S vert; \ + done + @for file in $(SNAPSHOTS)/*-Fragment.glsl.snap ; do \ + echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"};\ + tail -n +5 $${file} | glslangValidator --stdin -S frag; \ + done + @for file in $(SNAPSHOTS)/*-Compute.glsl.snap ; do \ + echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"};\ + tail -n +5 $${file} | glslangValidator --stdin -S comp; \ + done diff --git a/README.md b/README.md index cc99d0108..bd7e5d44f 100644 --- a/README.md +++ b/README.md @@ -30,3 +30,25 @@ DXIL/DXIR | | | DXBC | | | :white_check_mark: = Primary support — :ok: = Secondary support — :construction: = Unsupported, but support in progress + +## Development workflow + +The main instrument aiding the development is the good old `cargo test --all-features`, +which will run the snapshot tests as well as the unit tests. +Any changes in the snapshots would then have to be reviewed with `cargo insta review` +before being accepted into the code. + +If working on a particular front-end or back-end, it may be convenient to +enable the relevant features in `Cargo.toml`, e.g. +```toml +default = ["spv-out"] #TEMP! +``` +This allows IDE basic checks to report errors there, unless your IDE is sufficiently configurable already. + +Finally, when changes to the snapshots are made, we should verify that the produced shaders +are indeed valid for the target platforms they are compiled for. We automate this with `Makefile`: +```bash +make validate-spv # for Vulkan shaders, requires SPIRV-Tools installed +make validate-msl # for Metal shaders, requires XCode command-line tools installed +make validate-glsl # for OpenGL shaders, requires GLSLang installed +``` diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 7668a2cc5..a10f9f96a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -455,11 +455,7 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the name and end the global with a `;` // The leading space is important - writeln!( - self.out, - " {};", - self.names[&NameKey::GlobalVariable(handle)] - )?; + writeln!(self.out, " {};", self.get_global_name(handle, global))?; writeln!(self.out)?; } diff --git a/tests/snapshots/snapshots__quad-Fragment.glsl.snap b/tests/snapshots/snapshots__quad-Fragment.glsl.snap index d61405935..b52fb02cd 100644 --- a/tests/snapshots/snapshots__quad-Fragment.glsl.snap +++ b/tests/snapshots/snapshots__quad-Fragment.glsl.snap @@ -8,7 +8,7 @@ precision highp float; in vec2 _location_0_vs; -uniform sampler2D u_texture; +uniform sampler2D _group_0_binding_0; out vec4 _location_0; diff --git a/tests/snapshots/snapshots__skybox-Fragment.glsl.snap b/tests/snapshots/snapshots__skybox-Fragment.glsl.snap index 175ebf3ce..4ca9f8087 100644 --- a/tests/snapshots/snapshots__skybox-Fragment.glsl.snap +++ b/tests/snapshots/snapshots__skybox-Fragment.glsl.snap @@ -11,7 +11,7 @@ struct Data { mat4x4 view; }; -uniform samplerCube r_texture; +uniform samplerCube _group_0_binding_1; in vec3 _location_0_vs; From 50f0ad624943c907ffbec26000ce507aee7c1284 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 5 Feb 2021 02:04:44 -0500 Subject: [PATCH 0433/2212] Image queries --- src/back/glsl/mod.rs | 68 +++++++++++++++++++++++++++++++++++++++++ src/back/msl/writer.rs | 69 ++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 23 ++++++++++++++ src/proc/constants.rs | 5 +-- src/proc/interface.rs | 10 ++++++ src/proc/typifier.rs | 29 ++++++++++++++++++ 6 files changed, 202 insertions(+), 2 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a10f9f96a..19f07392d 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1338,6 +1338,74 @@ impl<'a, W: Write> Writer<'a, W> { } write!(self.out, ")")?; } + // Query translates into one of the: + // - textureSize/imageSize + // - textureQueryLevels + // - textureSamples/imageSamples + Expression::ImageQuery { image, query } => { + // This will only panic if the module is invalid + let (dim, class) = match ctx.typifier.get(image, &self.module.types) { + TypeInner::Image { + dim, + arrayed: _, + class, + } => (dim, class), + _ => unreachable!(), + }; + let components = match dim { + crate::ImageDimension::D1 => 1, + crate::ImageDimension::D2 => 2, + crate::ImageDimension::D3 => 3, + crate::ImageDimension::Cube => 2, + }; + match query { + crate::ImageQuery::Size { level } => { + match class { + ImageClass::Sampled { .. } | ImageClass::Depth => { + write!(self.out, "textureSize(")?; + self.write_expr(image, ctx)?; + write!(self.out, ",")?; + if let Some(expr) = level { + self.write_expr(expr, ctx)?; + } else { + write!(self.out, "0",)?; + } + } + ImageClass::Storage(_) => { + write!(self.out, "imageSize(")?; + self.write_expr(image, ctx)?; + } + } + write!(self.out, ").{}", &"xyz"[..components])?; + } + crate::ImageQuery::NumLevels => { + write!(self.out, "textureQueryLevels(",)?; + self.write_expr(image, ctx)?; + write!(self.out, ")",)?; + } + crate::ImageQuery::NumLayers => { + let selector = ['x', 'y', 'z', 'w']; + let fun_name = match class { + ImageClass::Sampled { .. } | ImageClass::Depth => "textureSize", + ImageClass::Storage(_) => "imageSize", + }; + write!(self.out, "{}(", fun_name)?; + self.write_expr(image, ctx)?; + write!(self.out, ",0).{}", selector[components])?; + } + crate::ImageQuery::NumSamples => { + // assumes ARB_shader_texture_image_samples + let fun_name = match class { + ImageClass::Sampled { .. } | ImageClass::Depth => "textureSamples", + ImageClass::Storage(_) => "imageSamples", + }; + write!(self.out, "{}(", fun_name)?; + self.write_expr(image, ctx)?; + write!(self.out, ")",)?; + } + } + return Err(Error::Custom("ImageQuery not implemented".to_string())); + } // `Unary` is pretty straightforward // "-" - for `Negate` // "~" - for `Not` if it's an integer diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index f5d0f3ec7..ee3a5e987 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -143,6 +143,22 @@ impl Writer { Ok(()) } + fn put_image_query( + &mut self, + image: Handle, + query: &str, + level: Option>, + context: &ExpressionContext, + ) -> Result<(), Error> { + self.put_expression(image, context)?; + write!(self.out, ".get_{}(", query)?; + if let Some(expr) = level { + self.put_expression(expr, context)?; + } + write!(self.out, ")")?; + Ok(()) + } + fn put_expression( &mut self, expr_handle: Handle, @@ -331,6 +347,59 @@ impl Writer { } write!(self.out, ")")?; } + //Note: for all the queries, the signed integers are expected, + // so a conversion is needed. + crate::Expression::ImageQuery { image, query } => match query { + crate::ImageQuery::Size { level } => { + let dim = match *self.typifier.get(image, &context.module.types) { + crate::TypeInner::Image { dim, .. } => dim, + ref other => unreachable!("Unexpected type {:?}", other), + }; + match dim { + crate::ImageDimension::D1 => { + write!(self.out, "int(")?; + self.put_image_query(image, "width", level, context)?; + write!(self.out, ")")?; + } + crate::ImageDimension::D2 => { + write!(self.out, "int2(")?; + self.put_image_query(image, "width", level, context)?; + write!(self.out, ", ")?; + self.put_image_query(image, "height", level, context)?; + write!(self.out, ")")?; + } + crate::ImageDimension::D3 => { + write!(self.out, "int3(")?; + self.put_image_query(image, "width", level, context)?; + write!(self.out, ", ")?; + self.put_image_query(image, "height", level, context)?; + write!(self.out, ", ")?; + self.put_image_query(image, "depth", level, context)?; + write!(self.out, ")")?; + } + crate::ImageDimension::Cube => { + write!(self.out, "int(")?; + self.put_image_query(image, "width", level, context)?; + write!(self.out, ").xxx")?; + } + } + } + crate::ImageQuery::NumLevels => { + write!(self.out, "int(")?; + self.put_expression(image, context)?; + write!(self.out, ".get_num_mip_levels())")?; + } + crate::ImageQuery::NumLayers => { + write!(self.out, "int(")?; + self.put_expression(image, context)?; + write!(self.out, ".get_array_size())")?; + } + crate::ImageQuery::NumSamples => { + write!(self.out, "int(")?; + self.put_expression(image, context)?; + write!(self.out, ".get_num_samples())")?; + } + }, crate::Expression::Unary { op, expr } => { let op_str = match op { crate::UnaryOperator::Negate => "-", diff --git a/src/lib.rs b/src/lib.rs index 9db837dd3..86f9cb5bb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -621,6 +621,24 @@ pub enum SampleLevel { }, } +/// Type of an image query. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum ImageQuery { + /// Get the size at the specified level. + Size { + /// If `None`, the base level is considered. + level: Option>, + }, + /// Get the number of mipmap levels. + NumLevels, + /// Get the number of array layers. + NumLayers, + /// Get the number of samples. + NumSamples, +} + /// An expression that can be evaluated to obtain a value. #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -671,6 +689,11 @@ pub enum Expression { /// For multisampled images, this is Some(Sample). index: Option>, }, + /// Query information from an image. + ImageQuery { + image: Handle, + query: ImageQuery, + }, /// Apply an unary operator. Unary { op: UnaryOperator, diff --git a/src/proc/constants.rs b/src/proc/constants.rs index d7b28b2ba..f5bf3ea70 100644 --- a/src/proc/constants.rs +++ b/src/proc/constants.rs @@ -120,8 +120,9 @@ impl<'a> ConstantSolver<'a> { Expression::Call { .. } => Err(ConstantSolvingError::Call), Expression::FunctionArgument(_) => Err(ConstantSolvingError::FunctionArg), Expression::GlobalVariable(_) => Err(ConstantSolvingError::GlobalVariable), - Expression::ImageSample { .. } => Err(ConstantSolvingError::ImageExpression), - Expression::ImageLoad { .. } => Err(ConstantSolvingError::ImageExpression), + Expression::ImageSample { .. } + | Expression::ImageLoad { .. } + | Expression::ImageQuery { .. } => Err(ConstantSolvingError::ImageExpression), } } diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 65c3e6d48..41048a314 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -85,6 +85,16 @@ where self.traverse_expr(index); } } + E::ImageQuery { image, query } => { + self.traverse_expr(image); + match query { + crate::ImageQuery::Size { level: Some(expr) } => self.traverse_expr(expr), + crate::ImageQuery::Size { .. } + | crate::ImageQuery::NumLevels + | crate::ImageQuery::NumLayers + | crate::ImageQuery::NumSamples => (), + } + } E::Unary { expr, .. } => { self.traverse_expr(expr); } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 07577c412..615d94535 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -204,6 +204,35 @@ impl Typifier { }), _ => unreachable!(), }, + crate::Expression::ImageQuery { image, query } => Resolution::Value(match query { + crate::ImageQuery::Size { level: _ } => match *self.get(image, types) { + crate::TypeInner::Image { dim, .. } => match dim { + crate::ImageDimension::D1 => crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: 4, + }, + crate::ImageDimension::D2 => crate::TypeInner::Vector { + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Sint, + width: 4, + }, + crate::ImageDimension::D3 | crate::ImageDimension::Cube => { + crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Sint, + width: 4, + } + } + }, + _ => unreachable!(), + }, + crate::ImageQuery::NumLevels + | crate::ImageQuery::NumLayers + | crate::ImageQuery::NumSamples => crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: 4, + }, + }), crate::Expression::Unary { expr, .. } => self.resolutions[expr.index()].clone(), crate::Expression::Binary { op, left, right } => match op { crate::BinaryOperator::Add From b1fa7471d205499511afcbb5415548a112386dea Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 5 Feb 2021 10:27:01 -0500 Subject: [PATCH 0434/2212] Basic image query support in SPV and WGSL frontends --- src/back/msl/writer.rs | 2 + src/front/spv/mod.rs | 84 +++++++++++++++++++++++++++++++++++++++++ src/front/wgsl/mod.rs | 46 ++++++++++++++++++++++ src/front/wgsl/tests.rs | 18 ++++++++- 4 files changed, 149 insertions(+), 1 deletion(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ee3a5e987..7ad3bd9b3 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -351,6 +351,8 @@ impl Writer { // so a conversion is needed. crate::Expression::ImageQuery { image, query } => match query { crate::ImageQuery::Size { level } => { + //Note: MSL only has separate width/height/depth queries, + // so compose the result of them. let dim = match *self.typifier.get(image, &context.module.types) { crate::TypeInner::Image { dim, .. } => dim, ref other => unreachable!("Unexpected type {:?}", other), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 1396221f0..783245cb3 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1113,6 +1113,90 @@ impl> Parser { }, ); } + Op::ImageQuerySize => { + inst.expect(4)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + + //TODO: handle arrays and cubes + let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); + + let expr = crate::Expression::ImageQuery { + image: image_lexp.handle, + query: crate::ImageQuery::Size { level: None }, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } + Op::ImageQuerySizeLod => { + inst.expect(5)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + let level_id = self.next()?; + + //TODO: handle arrays and cubes + let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); + let level_lexp = self.lookup_expression.lookup(level_id)?.clone(); + + let expr = crate::Expression::ImageQuery { + image: image_lexp.handle, + query: crate::ImageQuery::Size { + level: Some(level_lexp.handle), + }, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } + Op::ImageQueryLevels => { + let result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + + let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); + + let expr = crate::Expression::ImageQuery { + image: image_lexp.handle, + query: crate::ImageQuery::NumLevels, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } + Op::ImageQuerySamples => { + let result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + + let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); + + let expr = crate::Expression::ImageQuery { + image: image_lexp.handle, + query: crate::ImageQuery::NumSamples, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } Op::Select => { inst.expect(6)?; let result_type_id = self.next()?; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e807ec5d2..508d01e4d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -604,6 +604,52 @@ impl Parser { index, }) } + "textureDimensions" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + let image = ctx.lookup_ident.lookup(image_name)?; + let level = if lexer.skip(Token::Separator(',')) { + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; + Some(expr) + } else { + None + }; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::Size { level }, + }) + } + "textureNumLevels" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + let image = ctx.lookup_ident.lookup(image_name)?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumLevels, + }) + } + "textureNumLayers" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + let image = ctx.lookup_ident.lookup(image_name)?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumLayers, + }) + } + "textureNumSamples" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + let image = ctx.lookup_ident.lookup(image_name)?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumSamples, + }) + } _ => { match ctx.functions.iter().find(|(_, fun)| match fun.name { Some(ref string) => string == name, diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 434a46059..2bb6707f1 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -155,7 +155,7 @@ fn parse_texture_load() { " var t: texture_multisampled_2d_array; fn foo() { - const r: vec4 = textureLoad(t, vec2(10, 20), 2, 3); + const r: vec4 = textureLoad(t, vec2(10, 20), 2, 3); } ", ) @@ -171,6 +171,22 @@ fn parse_texture_load() { .unwrap(); } +#[test] +fn parse_texture_query() { + parse_str( + " + var t: texture_multisampled_2d_array; + fn foo() { + var dim: vec2 = textureDimensions(t); + dim = textureDimensions(t, 0); + const layers: i32 = textureNumLayers(t); + const samples: i32 = textureNumSamples(t); + } + ", + ) + .unwrap(); +} + #[test] fn parse_postfix() { parse_str("fn foo() { const x: f32 = vec4(1.0, 2.0, 3.0, 4.0).xyz.rgbr.aaaa.wz.g; }") From 88eee833d77f2e9378c21ffa3b43e7e1ea80315a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 5 Feb 2021 20:39:23 +0000 Subject: [PATCH 0435/2212] Add binary op support for the ConstantSolver --- src/lib.rs | 2 +- src/proc/constants.rs | 128 +++++++++++++++++++++++++++++++++++++----- 2 files changed, 116 insertions(+), 14 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 86f9cb5bb..f2febc9ac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -401,7 +401,7 @@ pub struct Constant { } /// A literal scalar value, used in constants. -#[derive(Debug, PartialEq, Clone)] +#[derive(Debug, PartialEq, Clone, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ScalarValue { diff --git a/src/proc/constants.rs b/src/proc/constants.rs index f5bf3ea70..14f748a0f 100644 --- a/src/proc/constants.rs +++ b/src/proc/constants.rs @@ -1,6 +1,7 @@ use crate::{ arena::{Arena, Handle}, - Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, UnaryOperator, + BinaryOperator, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, TypeInner, + UnaryOperator, }; #[derive(Debug)] @@ -46,6 +47,8 @@ pub enum ConstantSolvingError { InvalidCastArg, #[error("Cannot apply the unary op to the argument")] InvalidUnaryOpArg, + #[error("Cannot apply the binary op to the arguments")] + InvalidBinaryOpArgs, } impl<'a> ConstantSolver<'a> { @@ -78,7 +81,12 @@ impl<'a> ConstantSolver<'a> { self.unary_op(op, tgt) } - Expression::Binary { .. } => todo!(), + Expression::Binary { left, right, op } => { + let left = self.solve(left)?; + let right = self.solve(right)?; + + self.binary_op(op, left, right) + } Expression::Math { .. } => todo!(), Expression::As { convert, @@ -97,11 +105,11 @@ impl<'a> ConstantSolver<'a> { let array = self.solve(expr)?; match self.constants[array].inner { - crate::ConstantInner::Scalar { .. } => { + ConstantInner::Scalar { .. } => { Err(ConstantSolvingError::InvalidArrayLengthArg) } - crate::ConstantInner::Composite { ty, .. } => match self.types[ty].inner { - crate::TypeInner::Array { size, .. } => match size { + ConstantInner::Composite { ty, .. } => match self.types[ty].inner { + TypeInner::Array { size, .. } => match size { crate::ArraySize::Constant(constant) => Ok(constant), crate::ArraySize::Dynamic => { Err(ConstantSolvingError::ArrayLengthDynamic) @@ -134,13 +142,13 @@ impl<'a> ConstantSolver<'a> { let base = self.solve(base)?; match self.constants[base].inner { - crate::ConstantInner::Scalar { .. } => Err(ConstantSolvingError::InvalidAccessBase), - crate::ConstantInner::Composite { ty, ref components } => { + ConstantInner::Scalar { .. } => Err(ConstantSolvingError::InvalidAccessBase), + ConstantInner::Composite { ty, ref components } => { match self.types[ty].inner { - crate::TypeInner::Vector { .. } - | crate::TypeInner::Matrix { .. } - | crate::TypeInner::Array { .. } - | crate::TypeInner::Struct { .. } => (), + TypeInner::Vector { .. } + | TypeInner::Matrix { .. } + | TypeInner::Array { .. } + | TypeInner::Struct { .. } => (), _ => return Err(ConstantSolvingError::InvalidAccessBase), } @@ -195,7 +203,7 @@ impl<'a> ConstantSolver<'a> { ref mut components, } => { match self.types[ty].inner { - crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => (), + TypeInner::Vector { .. } | TypeInner::Matrix { .. } => (), _ => return Err(ConstantSolvingError::InvalidCastArg), } @@ -238,7 +246,7 @@ impl<'a> ConstantSolver<'a> { ref mut components, } => { match self.types[ty].inner { - crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => (), + TypeInner::Vector { .. } | TypeInner::Matrix { .. } => (), _ => return Err(ConstantSolvingError::InvalidCastArg), } @@ -254,6 +262,100 @@ impl<'a> ConstantSolver<'a> { inner, })) } + + fn binary_op( + &mut self, + op: BinaryOperator, + left: Handle, + right: Handle, + ) -> Result, ConstantSolvingError> { + let left = &self.constants[left].inner; + let right = &self.constants[right].inner; + + let inner = match (left, right) { + ( + ConstantInner::Scalar { + value: left_value, + width, + }, + ConstantInner::Scalar { + value: right_value, .. + }, + ) => { + let value = match op { + BinaryOperator::Equal => ScalarValue::Bool(left_value == right_value), + BinaryOperator::NotEqual => ScalarValue::Bool(left_value != right_value), + BinaryOperator::Less => ScalarValue::Bool(left_value < right_value), + BinaryOperator::LessEqual => ScalarValue::Bool(left_value <= right_value), + BinaryOperator::Greater => ScalarValue::Bool(left_value > right_value), + BinaryOperator::GreaterEqual => ScalarValue::Bool(left_value >= right_value), + + _ => match (left_value, right_value) { + (ScalarValue::Sint(a), ScalarValue::Sint(b)) => { + ScalarValue::Sint(match op { + BinaryOperator::Add => a + b, + BinaryOperator::Subtract => a - b, + BinaryOperator::Multiply => a * b, + BinaryOperator::Divide => a / b, + BinaryOperator::Modulo => a % b, + BinaryOperator::And => a & b, + BinaryOperator::ExclusiveOr => a ^ b, + BinaryOperator::InclusiveOr => a | b, + BinaryOperator::ShiftLeft => a << b, + BinaryOperator::ShiftRight => a >> b, + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }) + } + (ScalarValue::Uint(a), ScalarValue::Uint(b)) => { + ScalarValue::Uint(match op { + BinaryOperator::Add => a + b, + BinaryOperator::Subtract => a - b, + BinaryOperator::Multiply => a * b, + BinaryOperator::Divide => a / b, + BinaryOperator::Modulo => a % b, + BinaryOperator::And => a & b, + BinaryOperator::ExclusiveOr => a ^ b, + BinaryOperator::InclusiveOr => a | b, + BinaryOperator::ShiftLeft => a << b, + BinaryOperator::ShiftRight => a >> b, + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }) + } + (ScalarValue::Float(a), ScalarValue::Float(b)) => { + ScalarValue::Float(match op { + BinaryOperator::Add => a + b, + BinaryOperator::Subtract => a - b, + BinaryOperator::Multiply => a * b, + BinaryOperator::Divide => a / b, + BinaryOperator::Modulo => a % b, + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }) + } + (ScalarValue::Bool(a), ScalarValue::Bool(b)) => { + ScalarValue::Bool(match op { + BinaryOperator::LogicalAnd => *a && *b, + BinaryOperator::LogicalOr => *a || *b, + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }) + } + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }, + }; + + ConstantInner::Scalar { + value, + width: *width, + } + } + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }; + + Ok(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner, + })) + } } #[cfg(test)] From 647dd76dba269f89e83a275298e36dc231a92524 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 5 Feb 2021 22:28:30 +0000 Subject: [PATCH 0436/2212] Moved the ConstantSolver to the glsl frontend --- src/front/glsl/ast.rs | 4 ++-- src/{proc => front/glsl}/constants.rs | 0 src/front/glsl/mod.rs | 1 + src/proc/mod.rs | 2 -- 4 files changed, 3 insertions(+), 4 deletions(-) rename src/{proc => front/glsl}/constants.rs (100%) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 4ebc2da02..7962f59b3 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,6 +1,6 @@ -use super::error::ErrorKind; +use super::{constants::ConstantSolver, error::ErrorKind}; use crate::{ - proc::{ConstantSolver, ResolveContext, Typifier}, + proc::{ResolveContext, Typifier}, Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, ShaderStage, Statement, StorageClass, Type, diff --git a/src/proc/constants.rs b/src/front/glsl/constants.rs similarity index 100% rename from src/proc/constants.rs rename to src/front/glsl/constants.rs diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index a05a62fd3..7d3faf3e8 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -14,6 +14,7 @@ use ast::Program; use lex::Lexer; mod error; pub use error::ParseError; +mod constants; mod functions; mod parser; #[cfg(test)] diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 7aa2ca056..5dec4285b 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -2,7 +2,6 @@ #[cfg(feature = "petgraph")] mod call_graph; -mod constants; mod interface; mod layouter; mod namer; @@ -12,7 +11,6 @@ mod validator; #[cfg(feature = "petgraph")] pub use call_graph::{CallGraph, CallGraphBuilder}; -pub use constants::{ConstantSolver, ConstantSolvingError}; pub use interface::{Interface, Visitor}; pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; From ae72fb093370b0ca091249ae79c0b59162d7db87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 5 Feb 2021 22:04:20 +0000 Subject: [PATCH 0437/2212] Add support for component wise comparison to glsl --- src/back/glsl/mod.rs | 71 ++++++++++++++++++++++++------------- src/front/glsl/functions.rs | 20 ++++++++++- 2 files changed, 65 insertions(+), 26 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 19f07392d..98d7b4c18 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1447,33 +1447,54 @@ impl<'a, W: Write> Writer<'a, W> { // `Binary` we just write `left op right` // Once again we wrap everything in parantheses to avoid precedence issues Expression::Binary { op, left, right } => { - write!(self.out, "(")?; + // Holds `Some(function_name)` if the binary operation is + // implemented as a function call + let function = if let (TypeInner::Vector { .. }, TypeInner::Vector { .. }) = ( + ctx.typifier.get(left, &self.module.types), + ctx.typifier.get(right, &self.module.types), + ) { + match op { + BinaryOperator::Less => Some("lessThan"), + BinaryOperator::LessEqual => Some("lessThanEqual"), + BinaryOperator::Greater => Some("greaterThan"), + BinaryOperator::GreaterEqual => Some("greaterThanEqual"), + _ => None, + } + } else { + None + }; + + write!(self.out, "{}(", function.unwrap_or(""))?; self.write_expr(left, ctx)?; - write!( - self.out, - " {} ", - match op { - BinaryOperator::Add => "+", - BinaryOperator::Subtract => "-", - BinaryOperator::Multiply => "*", - BinaryOperator::Divide => "/", - BinaryOperator::Modulo => "%", - BinaryOperator::Equal => "==", - BinaryOperator::NotEqual => "!=", - BinaryOperator::Less => "<", - BinaryOperator::LessEqual => "<=", - BinaryOperator::Greater => ">", - BinaryOperator::GreaterEqual => ">=", - BinaryOperator::And => "&", - BinaryOperator::ExclusiveOr => "^", - BinaryOperator::InclusiveOr => "|", - BinaryOperator::LogicalAnd => "&&", - BinaryOperator::LogicalOr => "||", - BinaryOperator::ShiftLeft => "<<", - BinaryOperator::ShiftRight => ">>", - } - )?; + if function.is_some() { + write!(self.out, ",")? + } else { + write!( + self.out, + " {} ", + match op { + BinaryOperator::Add => "+", + BinaryOperator::Subtract => "-", + BinaryOperator::Multiply => "*", + BinaryOperator::Divide => "/", + BinaryOperator::Modulo => "%", + BinaryOperator::Equal => "==", + BinaryOperator::NotEqual => "!=", + BinaryOperator::Less => "<", + BinaryOperator::LessEqual => "<=", + BinaryOperator::Greater => ">", + BinaryOperator::GreaterEqual => ">=", + BinaryOperator::And => "&", + BinaryOperator::ExclusiveOr => "^", + BinaryOperator::InclusiveOr => "|", + BinaryOperator::LogicalAnd => "&&", + BinaryOperator::LogicalOr => "||", + BinaryOperator::ShiftLeft => "<<", + BinaryOperator::ShiftRight => ">>", + } + )?; + } self.write_expr(right, ctx)?; diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 7ec4b4e11..a9f45bad8 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,6 +1,6 @@ use crate::{ proc::{ensure_block_returns, Typifier}, - Block, Expression, Function, MathFunction, SampleLevel, TypeInner, + BinaryOperator, Block, Expression, Function, MathFunction, SampleLevel, TypeInner, }; use super::{ast::*, error::ErrorKind}; @@ -123,6 +123,24 @@ impl Program { statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), }) } + "lessThan" | "greaterThan" => { + if fc.args.len() != 2 { + return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); + } + Ok(ExpressionRule { + expression: self.context.expressions.append(Expression::Binary { + op: match name.as_str() { + "lessThan" => BinaryOperator::Less, + "greaterThan" => BinaryOperator::Greater, + _ => unreachable!(), + }, + left: fc.args[0].expression, + right: fc.args[1].expression, + }), + sampler: None, + statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), + }) + } func_name => { let function = *self.lookup_function.get(func_name).ok_or_else(|| { ErrorKind::SemanticError( From 2f9c95719811352096e1d03e7fd02992a59ca0ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 5 Feb 2021 22:19:26 +0000 Subject: [PATCH 0438/2212] Add support for pow and fix mix arguments --- src/front/glsl/functions.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index a9f45bad8..d1798b1c3 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -105,6 +105,24 @@ impl Program { statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), }) } + "pow" => { + if fc.args.len() != 2 { + return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); + } + Ok(ExpressionRule { + expression: self.context.expressions.append(Expression::Math { + fun: match name.as_str() { + "pow" => MathFunction::Pow, + _ => unreachable!(), + }, + arg: fc.args[0].expression, + arg1: Some(fc.args[1].expression), + arg2: None, + }), + sampler: None, + statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), + }) + } "mix" => { if fc.args.len() != 3 { return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); @@ -117,7 +135,7 @@ impl Program { }, arg: fc.args[0].expression, arg1: Some(fc.args[1].expression), - arg2: None, + arg2: Some(fc.args[2].expression), }), sampler: None, statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), From f9f41fc9bf27ecca091e492892538afcdacd1419 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 5 Feb 2021 22:21:28 +0000 Subject: [PATCH 0439/2212] Add support for more math functions in glsl --- src/front/glsl/functions.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index d1798b1c3..3b6b880a9 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -81,7 +81,8 @@ impl Program { Err(ErrorKind::SemanticError("Bad call to texture".into())) } } - "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" => { + "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" + | "exp" | "sign" => { if fc.args.len() != 1 { return Err(ErrorKind::WrongNumberArgs(name, 1, fc.args.len())); } @@ -95,6 +96,9 @@ impl Program { "trunc" => MathFunction::Trunc, "sin" => MathFunction::Sin, "abs" => MathFunction::Abs, + "sqrt" => MathFunction::Sqrt, + "exp" => MathFunction::Exp, + "sign" => MathFunction::Sign, _ => unreachable!(), }, arg: fc.args[0].expression, @@ -123,7 +127,7 @@ impl Program { statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), }) } - "mix" => { + "mix" | "clamp" => { if fc.args.len() != 3 { return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); } @@ -131,6 +135,7 @@ impl Program { expression: self.context.expressions.append(Expression::Math { fun: match name.as_str() { "mix" => MathFunction::Mix, + "clamp" => MathFunction::Clamp, _ => unreachable!(), }, arg: fc.args[0].expression, From d949d58f7b10837a7eef92087f7d50eefb137b04 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 5 Feb 2021 10:54:50 -0500 Subject: [PATCH 0440/2212] Statement for void function call --- src/back/glsl/mod.rs | 36 +- src/back/msl/writer.rs | 9 + src/back/spv/writer.rs | 77 +-- src/lib.rs | 5 + src/proc/interface.rs | 9 + src/proc/terminator.rs | 1 + tests/snapshots/snapshots__boids.spvasm.snap | 440 +++++++++--------- .../snapshots/snapshots__collatz.spvasm.snap | 126 ++--- tests/snapshots/snapshots__empty.spvasm.snap | 6 +- tests/snapshots/snapshots__quad.spvasm.snap | 26 +- tests/snapshots/snapshots__shadow.spvasm.snap | 324 ++++++------- tests/snapshots/snapshots__skybox.spvasm.snap | 230 ++++----- 12 files changed, 668 insertions(+), 621 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 98d7b4c18..cfd53cf38 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -979,11 +979,11 @@ impl<'a, W: Write> Writer<'a, W> { // The indentation is only for readability write!(self.out, "{}", INDENT.repeat(indent))?; - match sta { + match *sta { // Blocks are simple we just need to write the block statements between braces // We could also just print the statements but this is more readable and maps more // closely to the IR - Statement::Block(block) => { + Statement::Block(ref block) => { writeln!(self.out, "{{")?; for sta in block.iter() { // Increase the indentation to help with readability @@ -1001,11 +1001,11 @@ impl<'a, W: Write> Writer<'a, W> { // ``` Statement::If { condition, - accept, - reject, + ref accept, + ref reject, } => { write!(self.out, "if(")?; - self.write_expr(*condition, ctx)?; + self.write_expr(condition, ctx)?; writeln!(self.out, ") {{")?; for sta in accept { @@ -1044,12 +1044,12 @@ impl<'a, W: Write> Writer<'a, W> { // so that we don't need to print a `break` for it Statement::Switch { selector, - cases, - default, + ref cases, + ref default, } => { // Start the switch write!(self.out, "switch(")?; - self.write_expr(*selector, ctx)?; + self.write_expr(selector, ctx)?; writeln!(self.out, ") {{")?; // Write all cases @@ -1091,7 +1091,10 @@ impl<'a, W: Write> Writer<'a, W> { // continuing // } // ``` - Statement::Loop { body, continuing } => { + Statement::Loop { + ref body, + ref continuing, + } => { writeln!(self.out, "while(true) {{")?; for sta in body.iter().chain(continuing.iter()) { @@ -1111,7 +1114,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the expression to be returned if needed if let Some(expr) = value { write!(self.out, " ")?; - self.write_expr(*expr, ctx)?; + self.write_expr(expr, ctx)?; } writeln!(self.out, ";")?; } @@ -1121,11 +1124,20 @@ impl<'a, W: Write> Writer<'a, W> { Statement::Kill => writeln!(self.out, "discard;")?, // Stores in glsl are just variable assignments written as `pointer = value;` Statement::Store { pointer, value } => { - self.write_expr(*pointer, ctx)?; + self.write_expr(pointer, ctx)?; write!(self.out, " = ")?; - self.write_expr(*value, ctx)?; + self.write_expr(value, ctx)?; writeln!(self.out, ";")? } + // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list + Statement::Call { + function, + ref arguments, + } => { + write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; + self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; + write!(self.out, ");")? + } } Ok(()) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7ad3bd9b3..76861c38c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -741,6 +741,15 @@ impl Writer { self.put_expression(value, context)?; writeln!(self.out, ";")?; } + crate::Statement::Call { + function, + ref arguments, + } => { + let name = &self.names[&NameKey::Function(function)]; + write!(self.out, "{}", name)?; + self.put_call("", arguments, context)?; + writeln!(self.out, ";")?; + } } } Ok(()) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index ea806152b..04f2b42c2 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -181,7 +181,7 @@ pub struct Writer { debugs: Vec, annotations: Vec, flags: WriterFlags, - void_type: Option, + void_type: u32, lookup_type: crate::FastHashMap, lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, @@ -209,19 +209,19 @@ impl Writer { Writer { physical_layout: PhysicalLayout::new(header), logical_layout: LogicalLayout::default(), - id_count: 0, + id_count: 2, // 0 is void type, 1 is the GLSL ext inst capabilities, debugs: vec![], annotations: vec![], flags, - void_type: None, + void_type: 0, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), lookup_function_type: crate::FastHashMap::default(), lookup_constant: crate::FastHashMap::default(), lookup_global_variable: crate::FastHashMap::default(), struct_type_handles: crate::FastHashMap::default(), - gl450_ext_inst_id: 0, + gl450_ext_inst_id: 1, layouter: Layouter::default(), typifier: Typifier::new(), } @@ -295,26 +295,6 @@ impl Writer { }) } - fn get_function_return_type( - &mut self, - ty: Option>, - arena: &crate::Arena, - ) -> Result { - match ty { - Some(handle) => self.get_type_id(arena, LookupType::Handle(handle)), - None => Ok(match self.void_type { - Some(id) => id, - None => { - let id = self.generate_id(); - self.void_type = Some(id); - super::instructions::instruction_type_void(id) - .to_words(&mut self.logical_layout.declarations); - id - } - }), - } - } - fn get_pointer_id( &mut self, arena: &crate::Arena, @@ -415,8 +395,10 @@ impl Writer { .insert(handle, LocalVariable { id, instruction }); } - let return_type_id = - self.get_function_return_type(ir_function.return_type, &ir_module.types)?; + let return_type_id = match ir_function.return_type { + Some(handle) => self.get_type_id(&ir_module.types, LookupType::Handle(handle))?, + None => self.void_type, + }; let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); for argument in ir_function.arguments.iter() { @@ -1922,6 +1904,10 @@ impl Writer { block = Block::new(merge_id); } + crate::Statement::Switch { .. } => { + log::error!("unimplemented Switch"); + return Err(Error::FeatureNotImplemented("switch")); + } crate::Statement::Loop { ref body, ref continuing, @@ -2007,9 +1993,33 @@ impl Writer { pointer_id, value_id, None, )); } - _ => { - log::error!("unimplemented {:?}", statement); - return Err(Error::FeatureNotImplemented("statement")); + crate::Statement::Call { + function: local_function, + ref arguments, + } => { + let id = self.generate_id(); + //TODO: avoid heap allocation + let mut argument_ids = vec![]; + + for argument in arguments { + let arg_id = self.write_expression( + ir_module, + ir_function, + *argument, + &mut block, + function, + )?; + argument_ids.push(arg_id); + } + + block + .body + .push(super::instructions::instruction_function_call( + self.void_type, + id, + *self.lookup_function.get(&local_function).unwrap(), + argument_ids.as_slice(), + )); } } } @@ -2030,7 +2040,8 @@ impl Writer { } fn write_logical_layout(&mut self, ir_module: &crate::Module) -> Result<(), Error> { - self.gl450_ext_inst_id = self.generate_id(); + super::instructions::instruction_type_void(self.void_type) + .to_words(&mut self.logical_layout.declarations); super::instructions::instruction_ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); @@ -2113,9 +2124,9 @@ mod tests { fn test_writer_generate_id() { let mut writer = create_writer(); - assert_eq!(writer.id_count, 0); + assert_eq!(writer.id_count, 2); writer.generate_id(); - assert_eq!(writer.id_count, 1); + assert_eq!(writer.id_count, 3); } #[test] @@ -2123,7 +2134,7 @@ mod tests { let mut writer = create_writer(); assert_eq!(writer.physical_layout.bound, 0); writer.write_physical_layout(); - assert_eq!(writer.physical_layout.bound, 1); + assert_eq!(writer.physical_layout.bound, 3); } fn create_writer() -> Writer { diff --git a/src/lib.rs b/src/lib.rs index f2febc9ac..92058c903 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -802,6 +802,11 @@ pub enum Statement { pointer: Handle, value: Handle, }, + /// Calls a function with no return value. + Call { + function: Handle, + arguments: Vec>, + }, } /// A function argument. diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 41048a314..36326a7ed 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -203,6 +203,15 @@ where self.visitor.visit_lhs_expr(&self.expressions[left]); self.traverse_expr(value); } + S::Call { + function, + ref arguments, + } => { + for &argument in arguments { + self.traverse_expr(argument); + } + self.visitor.visit_fun(function); + } } } } diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index 1ad142981..181c81532 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -35,6 +35,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) { | Some(&mut crate::Statement::Kill) => (), Some(&mut crate::Statement::Loop { .. }) | Some(&mut crate::Statement::Store { .. }) + | Some(&mut crate::Statement::Call { .. }) | None => block.push(crate::Statement::Return { value: None }), } } diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap index 19989836c..f155d920a 100644 --- a/tests/snapshots/snapshots__boids.spvasm.snap +++ b/tests/snapshots/snapshots__boids.spvasm.snap @@ -32,124 +32,124 @@ OpDecorate %122 DescriptorSet 0 OpDecorate %122 Binding 0 OpDecorate %274 DescriptorSet 0 OpDecorate %274 Binding 2 -%3 = OpTypeInt 32 1 -%2 = OpConstant %3 1500 -%5 = OpTypeFloat 32 -%4 = OpConstant %5 0.0 -%6 = OpConstant %3 0 -%8 = OpTypeInt 32 0 -%7 = OpConstant %8 0 -%9 = OpConstant %3 1 -%10 = OpConstant %8 1 -%11 = OpConstant %5 1.0 -%12 = OpConstant %5 0.1 -%13 = OpConstant %5 -1.0 -%15 = OpTypeVector %5 2 -%16 = OpTypePointer Function %15 -%22 = OpTypePointer Function %3 -%27 = OpTypePointer Function %8 -%28 = OpTypeVoid -%30 = OpTypeFunction %28 +%0 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 1500 +%6 = OpTypeFloat 32 +%5 = OpConstant %6 0.0 +%7 = OpConstant %4 0 +%9 = OpTypeInt 32 0 +%8 = OpConstant %9 0 +%10 = OpConstant %4 1 +%11 = OpConstant %9 1 +%12 = OpConstant %6 1.0 +%13 = OpConstant %6 0.1 +%14 = OpConstant %6 -1.0 +%16 = OpTypeVector %6 2 +%17 = OpTypePointer Function %16 +%23 = OpTypePointer Function %4 +%28 = OpTypePointer Function %9 +%30 = OpTypeFunction %0 %32 = OpTypeBool -%35 = OpTypeVector %8 3 +%35 = OpTypeVector %9 3 %37 = OpTypePointer Input %35 %36 = OpVariable %37 Input -%38 = OpTypePointer Input %8 -%39 = OpConstant %3 0 -%45 = OpTypeStruct %15 %15 +%38 = OpTypePointer Input %9 +%39 = OpConstant %4 0 +%45 = OpTypeStruct %16 %16 %47 = OpTypeRuntimeArray %45 %49 = OpTypeStruct %47 %51 = OpTypePointer Uniform %49 %50 = OpVariable %51 Uniform %52 = OpTypePointer Uniform %47 -%53 = OpConstant %3 0 -%55 = OpTypePointer Input %8 -%56 = OpConstant %3 0 +%53 = OpConstant %4 0 +%55 = OpTypePointer Input %9 +%56 = OpConstant %4 0 %58 = OpTypePointer Uniform %45 -%59 = OpTypePointer Uniform %15 -%60 = OpConstant %3 0 +%59 = OpTypePointer Uniform %16 +%60 = OpConstant %4 0 %65 = OpTypePointer Uniform %47 -%66 = OpConstant %3 0 -%68 = OpTypePointer Input %8 -%69 = OpConstant %3 0 +%66 = OpConstant %4 0 +%68 = OpTypePointer Input %9 +%69 = OpConstant %4 0 %71 = OpTypePointer Uniform %45 -%72 = OpTypePointer Uniform %15 -%73 = OpConstant %3 1 -%90 = OpTypePointer Input %8 -%91 = OpConstant %3 0 +%72 = OpTypePointer Uniform %16 +%73 = OpConstant %4 1 +%90 = OpTypePointer Input %9 +%91 = OpConstant %4 0 %99 = OpTypePointer Uniform %47 -%100 = OpConstant %3 0 +%100 = OpConstant %4 0 %102 = OpTypePointer Uniform %45 -%103 = OpTypePointer Uniform %15 -%104 = OpConstant %3 0 +%103 = OpTypePointer Uniform %16 +%104 = OpConstant %4 0 %109 = OpTypePointer Uniform %47 -%110 = OpConstant %3 0 +%110 = OpConstant %4 0 %112 = OpTypePointer Uniform %45 -%113 = OpTypePointer Uniform %15 -%114 = OpConstant %3 1 -%121 = OpTypeStruct %5 %5 %5 %5 %5 %5 %5 +%113 = OpTypePointer Uniform %16 +%114 = OpConstant %4 1 +%121 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 %123 = OpTypePointer Uniform %121 %122 = OpVariable %123 Uniform -%124 = OpTypePointer Uniform %5 -%125 = OpConstant %3 1 -%140 = OpTypePointer Uniform %5 -%141 = OpConstant %3 2 -%156 = OpTypePointer Uniform %5 -%157 = OpConstant %3 3 -%198 = OpTypePointer Uniform %5 -%199 = OpConstant %3 4 -%204 = OpTypePointer Uniform %5 -%205 = OpConstant %3 5 -%210 = OpTypePointer Uniform %5 -%211 = OpConstant %3 6 -%224 = OpTypePointer Uniform %5 -%225 = OpConstant %3 0 -%229 = OpTypePointer Function %5 -%230 = OpConstant %3 0 -%236 = OpTypePointer Function %5 -%237 = OpConstant %3 0 -%240 = OpTypePointer Function %5 -%241 = OpConstant %3 0 -%247 = OpTypePointer Function %5 -%248 = OpConstant %3 0 -%251 = OpTypePointer Function %5 -%252 = OpConstant %3 1 -%258 = OpTypePointer Function %5 -%259 = OpConstant %3 1 -%262 = OpTypePointer Function %5 -%263 = OpConstant %3 1 -%269 = OpTypePointer Function %5 -%270 = OpConstant %3 1 +%124 = OpTypePointer Uniform %6 +%125 = OpConstant %4 1 +%140 = OpTypePointer Uniform %6 +%141 = OpConstant %4 2 +%156 = OpTypePointer Uniform %6 +%157 = OpConstant %4 3 +%198 = OpTypePointer Uniform %6 +%199 = OpConstant %4 4 +%204 = OpTypePointer Uniform %6 +%205 = OpConstant %4 5 +%210 = OpTypePointer Uniform %6 +%211 = OpConstant %4 6 +%224 = OpTypePointer Uniform %6 +%225 = OpConstant %4 0 +%229 = OpTypePointer Function %6 +%230 = OpConstant %4 0 +%236 = OpTypePointer Function %6 +%237 = OpConstant %4 0 +%240 = OpTypePointer Function %6 +%241 = OpConstant %4 0 +%247 = OpTypePointer Function %6 +%248 = OpConstant %4 0 +%251 = OpTypePointer Function %6 +%252 = OpConstant %4 1 +%258 = OpTypePointer Function %6 +%259 = OpConstant %4 1 +%262 = OpTypePointer Function %6 +%263 = OpConstant %4 1 +%269 = OpTypePointer Function %6 +%270 = OpConstant %4 1 %274 = OpVariable %51 Uniform %275 = OpTypePointer Uniform %47 -%276 = OpConstant %3 0 -%278 = OpTypePointer Input %8 -%279 = OpConstant %3 0 +%276 = OpConstant %4 0 +%278 = OpTypePointer Input %9 +%279 = OpConstant %4 0 %281 = OpTypePointer Uniform %45 -%282 = OpTypePointer Uniform %15 -%283 = OpConstant %3 0 +%282 = OpTypePointer Uniform %16 +%283 = OpConstant %4 0 %288 = OpTypePointer Uniform %47 -%289 = OpConstant %3 0 -%291 = OpTypePointer Input %8 -%292 = OpConstant %3 0 +%289 = OpConstant %4 0 +%291 = OpTypePointer Input %9 +%292 = OpConstant %4 0 %294 = OpTypePointer Uniform %45 -%295 = OpTypePointer Uniform %15 -%296 = OpConstant %3 1 -%29 = OpFunction %28 None %30 +%295 = OpTypePointer Uniform %16 +%296 = OpConstant %4 1 +%29 = OpFunction %0 None %30 %31 = OpLabel -%26 = OpVariable %27 Function %7 -%23 = OpVariable %22 Function %6 -%19 = OpVariable %16 Function -%14 = OpVariable %16 Function -%24 = OpVariable %16 Function -%20 = OpVariable %16 Function -%17 = OpVariable %16 Function -%25 = OpVariable %16 Function -%21 = OpVariable %22 Function %6 -%18 = OpVariable %16 Function +%27 = OpVariable %28 Function %8 +%24 = OpVariable %23 Function %7 +%20 = OpVariable %17 Function +%15 = OpVariable %17 Function +%25 = OpVariable %17 Function +%21 = OpVariable %17 Function +%18 = OpVariable %17 Function +%26 = OpVariable %17 Function +%22 = OpVariable %23 Function %7 +%19 = OpVariable %17 Function %34 = OpAccessChain %38 %36 %39 -%40 = OpLoad %8 %34 -%33 = OpUGreaterThanEqual %32 %40 %2 +%40 = OpLoad %9 %34 +%33 = OpUGreaterThanEqual %32 %40 %3 OpSelectionMerge %41 None OpBranchConditional %33 %42 %43 %42 = OpLabel @@ -159,31 +159,31 @@ OpBranch %41 %41 = OpLabel %48 = OpAccessChain %52 %50 %53 %54 = OpAccessChain %55 %36 %56 -%57 = OpLoad %8 %54 +%57 = OpLoad %9 %54 %46 = OpAccessChain %58 %48 %57 %44 = OpAccessChain %59 %46 %60 -%61 = OpLoad %15 %44 -OpStore %14 %61 +%61 = OpLoad %16 %44 +OpStore %15 %61 %64 = OpAccessChain %65 %50 %66 %67 = OpAccessChain %68 %36 %69 -%70 = OpLoad %8 %67 +%70 = OpLoad %9 %67 %63 = OpAccessChain %71 %64 %70 %62 = OpAccessChain %72 %63 %73 -%74 = OpLoad %15 %62 -OpStore %17 %74 -%75 = OpCompositeConstruct %15 %4 %4 -OpStore %18 %75 -%76 = OpCompositeConstruct %15 %4 %4 -OpStore %19 %76 -%77 = OpCompositeConstruct %15 %4 %4 -OpStore %20 %77 +%74 = OpLoad %16 %62 +OpStore %18 %74 +%75 = OpCompositeConstruct %16 %5 %5 +OpStore %19 %75 +%76 = OpCompositeConstruct %16 %5 %5 +OpStore %20 %76 +%77 = OpCompositeConstruct %16 %5 %5 +OpStore %21 %77 OpBranch %78 %78 = OpLabel OpLoopMerge %79 %81 None OpBranch %80 %80 = OpLabel -%83 = OpLoad %8 %26 -%82 = OpUGreaterThanEqual %32 %83 %2 +%83 = OpLoad %9 %27 +%82 = OpUGreaterThanEqual %32 %83 %3 OpSelectionMerge %84 None OpBranchConditional %82 %85 %86 %85 = OpLabel @@ -191,9 +191,9 @@ OpBranch %79 %86 = OpLabel OpBranch %84 %84 = OpLabel -%88 = OpLoad %8 %26 +%88 = OpLoad %9 %27 %89 = OpAccessChain %90 %36 %91 -%92 = OpLoad %8 %89 +%92 = OpLoad %9 %89 %87 = OpIEqual %32 %88 %92 OpSelectionMerge %93 None OpBranchConditional %87 %94 %95 @@ -203,207 +203,207 @@ OpBranch %81 OpBranch %93 %93 = OpLabel %98 = OpAccessChain %99 %50 %100 -%101 = OpLoad %8 %26 +%101 = OpLoad %9 %27 %97 = OpAccessChain %102 %98 %101 %96 = OpAccessChain %103 %97 %104 -%105 = OpLoad %15 %96 -OpStore %24 %105 +%105 = OpLoad %16 %96 +OpStore %25 %105 %108 = OpAccessChain %109 %50 %110 -%111 = OpLoad %8 %26 +%111 = OpLoad %9 %27 %107 = OpAccessChain %112 %108 %111 %106 = OpAccessChain %113 %107 %114 -%115 = OpLoad %15 %106 -OpStore %25 %115 -%117 = OpLoad %15 %24 -%118 = OpLoad %15 %14 -%119 = OpExtInst %5 %1 Distance %117 %118 +%115 = OpLoad %16 %106 +OpStore %26 %115 +%117 = OpLoad %16 %25 +%118 = OpLoad %16 %15 +%119 = OpExtInst %6 %1 Distance %117 %118 %120 = OpAccessChain %124 %122 %125 -%126 = OpLoad %5 %120 +%126 = OpLoad %6 %120 %116 = OpFOrdLessThan %32 %119 %126 OpSelectionMerge %127 None OpBranchConditional %116 %128 %129 %128 = OpLabel -%131 = OpLoad %15 %18 -%132 = OpLoad %15 %24 -%130 = OpFAdd %15 %131 %132 -OpStore %18 %130 -%134 = OpLoad %3 %21 -%133 = OpIAdd %3 %134 %9 -OpStore %21 %133 +%131 = OpLoad %16 %19 +%132 = OpLoad %16 %25 +%130 = OpFAdd %16 %131 %132 +OpStore %19 %130 +%134 = OpLoad %4 %22 +%133 = OpIAdd %4 %134 %10 +OpStore %22 %133 OpBranch %127 %129 = OpLabel OpBranch %127 %127 = OpLabel -%136 = OpLoad %15 %24 -%137 = OpLoad %15 %14 -%138 = OpExtInst %5 %1 Distance %136 %137 +%136 = OpLoad %16 %25 +%137 = OpLoad %16 %15 +%138 = OpExtInst %6 %1 Distance %136 %137 %139 = OpAccessChain %140 %122 %141 -%142 = OpLoad %5 %139 +%142 = OpLoad %6 %139 %135 = OpFOrdLessThan %32 %138 %142 OpSelectionMerge %143 None OpBranchConditional %135 %144 %145 %144 = OpLabel -%147 = OpLoad %15 %20 -%149 = OpLoad %15 %24 -%150 = OpLoad %15 %14 -%148 = OpFSub %15 %149 %150 -%146 = OpFSub %15 %147 %148 -OpStore %20 %146 +%147 = OpLoad %16 %21 +%149 = OpLoad %16 %25 +%150 = OpLoad %16 %15 +%148 = OpFSub %16 %149 %150 +%146 = OpFSub %16 %147 %148 +OpStore %21 %146 OpBranch %143 %145 = OpLabel OpBranch %143 %143 = OpLabel -%152 = OpLoad %15 %24 -%153 = OpLoad %15 %14 -%154 = OpExtInst %5 %1 Distance %152 %153 +%152 = OpLoad %16 %25 +%153 = OpLoad %16 %15 +%154 = OpExtInst %6 %1 Distance %152 %153 %155 = OpAccessChain %156 %122 %157 -%158 = OpLoad %5 %155 +%158 = OpLoad %6 %155 %151 = OpFOrdLessThan %32 %154 %158 OpSelectionMerge %159 None OpBranchConditional %151 %160 %161 %160 = OpLabel -%163 = OpLoad %15 %19 -%164 = OpLoad %15 %25 -%162 = OpFAdd %15 %163 %164 -OpStore %19 %162 -%166 = OpLoad %3 %23 -%165 = OpIAdd %3 %166 %9 -OpStore %23 %165 +%163 = OpLoad %16 %20 +%164 = OpLoad %16 %26 +%162 = OpFAdd %16 %163 %164 +OpStore %20 %162 +%166 = OpLoad %4 %24 +%165 = OpIAdd %4 %166 %10 +OpStore %24 %165 OpBranch %159 %161 = OpLabel OpBranch %159 %159 = OpLabel OpBranch %81 %81 = OpLabel -%168 = OpLoad %8 %26 -%167 = OpIAdd %8 %168 %10 -OpStore %26 %167 +%168 = OpLoad %9 %27 +%167 = OpIAdd %9 %168 %11 +OpStore %27 %167 OpBranch %78 %79 = OpLabel -%170 = OpLoad %3 %21 -%169 = OpSGreaterThan %32 %170 %6 +%170 = OpLoad %4 %22 +%169 = OpSGreaterThan %32 %170 %7 OpSelectionMerge %171 None OpBranchConditional %169 %172 %173 %172 = OpLabel -%176 = OpLoad %15 %18 -%178 = OpLoad %3 %21 -%179 = OpConvertSToF %5 %178 -%177 = OpFDiv %5 %11 %179 -%175 = OpVectorTimesScalar %15 %176 %177 -%180 = OpLoad %15 %14 -%174 = OpFSub %15 %175 %180 -OpStore %18 %174 +%176 = OpLoad %16 %19 +%178 = OpLoad %4 %22 +%179 = OpConvertSToF %6 %178 +%177 = OpFDiv %6 %12 %179 +%175 = OpVectorTimesScalar %16 %176 %177 +%180 = OpLoad %16 %15 +%174 = OpFSub %16 %175 %180 +OpStore %19 %174 OpBranch %171 %173 = OpLabel OpBranch %171 %171 = OpLabel -%182 = OpLoad %3 %23 -%181 = OpSGreaterThan %32 %182 %6 +%182 = OpLoad %4 %24 +%181 = OpSGreaterThan %32 %182 %7 OpSelectionMerge %183 None OpBranchConditional %181 %184 %185 %184 = OpLabel -%187 = OpLoad %15 %19 -%189 = OpLoad %3 %23 -%190 = OpConvertSToF %5 %189 -%188 = OpFDiv %5 %11 %190 -%186 = OpVectorTimesScalar %15 %187 %188 -OpStore %19 %186 +%187 = OpLoad %16 %20 +%189 = OpLoad %4 %24 +%190 = OpConvertSToF %6 %189 +%188 = OpFDiv %6 %12 %190 +%186 = OpVectorTimesScalar %16 %187 %188 +OpStore %20 %186 OpBranch %183 %185 = OpLabel OpBranch %183 %183 = OpLabel -%194 = OpLoad %15 %17 -%196 = OpLoad %15 %18 +%194 = OpLoad %16 %18 +%196 = OpLoad %16 %19 %197 = OpAccessChain %198 %122 %199 -%200 = OpLoad %5 %197 -%195 = OpVectorTimesScalar %15 %196 %200 -%193 = OpFAdd %15 %194 %195 -%202 = OpLoad %15 %20 +%200 = OpLoad %6 %197 +%195 = OpVectorTimesScalar %16 %196 %200 +%193 = OpFAdd %16 %194 %195 +%202 = OpLoad %16 %21 %203 = OpAccessChain %204 %122 %205 -%206 = OpLoad %5 %203 -%201 = OpVectorTimesScalar %15 %202 %206 -%192 = OpFAdd %15 %193 %201 -%208 = OpLoad %15 %19 +%206 = OpLoad %6 %203 +%201 = OpVectorTimesScalar %16 %202 %206 +%192 = OpFAdd %16 %193 %201 +%208 = OpLoad %16 %20 %209 = OpAccessChain %210 %122 %211 -%212 = OpLoad %5 %209 -%207 = OpVectorTimesScalar %15 %208 %212 -%191 = OpFAdd %15 %192 %207 -OpStore %17 %191 -%214 = OpLoad %15 %17 -%215 = OpExtInst %15 %1 Normalize %214 -%216 = OpLoad %15 %17 -%217 = OpExtInst %5 %1 Length %216 -%218 = OpExtInst %5 %1 FClamp %217 %4 %12 -%213 = OpVectorTimesScalar %15 %215 %218 -OpStore %17 %213 -%220 = OpLoad %15 %14 -%222 = OpLoad %15 %17 +%212 = OpLoad %6 %209 +%207 = OpVectorTimesScalar %16 %208 %212 +%191 = OpFAdd %16 %192 %207 +OpStore %18 %191 +%214 = OpLoad %16 %18 +%215 = OpExtInst %16 %1 Normalize %214 +%216 = OpLoad %16 %18 +%217 = OpExtInst %6 %1 Length %216 +%218 = OpExtInst %6 %1 FClamp %217 %5 %13 +%213 = OpVectorTimesScalar %16 %215 %218 +OpStore %18 %213 +%220 = OpLoad %16 %15 +%222 = OpLoad %16 %18 %223 = OpAccessChain %224 %122 %225 -%226 = OpLoad %5 %223 -%221 = OpVectorTimesScalar %15 %222 %226 -%219 = OpFAdd %15 %220 %221 -OpStore %14 %219 -%228 = OpAccessChain %229 %14 %230 -%231 = OpLoad %5 %228 -%227 = OpFOrdLessThan %32 %231 %13 +%226 = OpLoad %6 %223 +%221 = OpVectorTimesScalar %16 %222 %226 +%219 = OpFAdd %16 %220 %221 +OpStore %15 %219 +%228 = OpAccessChain %229 %15 %230 +%231 = OpLoad %6 %228 +%227 = OpFOrdLessThan %32 %231 %14 OpSelectionMerge %232 None OpBranchConditional %227 %233 %234 %233 = OpLabel -%235 = OpAccessChain %236 %14 %237 -OpStore %235 %11 +%235 = OpAccessChain %236 %15 %237 +OpStore %235 %12 OpBranch %232 %234 = OpLabel OpBranch %232 %232 = OpLabel -%239 = OpAccessChain %240 %14 %241 -%242 = OpLoad %5 %239 -%238 = OpFOrdGreaterThan %32 %242 %11 +%239 = OpAccessChain %240 %15 %241 +%242 = OpLoad %6 %239 +%238 = OpFOrdGreaterThan %32 %242 %12 OpSelectionMerge %243 None OpBranchConditional %238 %244 %245 %244 = OpLabel -%246 = OpAccessChain %247 %14 %248 -OpStore %246 %13 +%246 = OpAccessChain %247 %15 %248 +OpStore %246 %14 OpBranch %243 %245 = OpLabel OpBranch %243 %243 = OpLabel -%250 = OpAccessChain %251 %14 %252 -%253 = OpLoad %5 %250 -%249 = OpFOrdLessThan %32 %253 %13 +%250 = OpAccessChain %251 %15 %252 +%253 = OpLoad %6 %250 +%249 = OpFOrdLessThan %32 %253 %14 OpSelectionMerge %254 None OpBranchConditional %249 %255 %256 %255 = OpLabel -%257 = OpAccessChain %258 %14 %259 -OpStore %257 %11 +%257 = OpAccessChain %258 %15 %259 +OpStore %257 %12 OpBranch %254 %256 = OpLabel OpBranch %254 %254 = OpLabel -%261 = OpAccessChain %262 %14 %263 -%264 = OpLoad %5 %261 -%260 = OpFOrdGreaterThan %32 %264 %11 +%261 = OpAccessChain %262 %15 %263 +%264 = OpLoad %6 %261 +%260 = OpFOrdGreaterThan %32 %264 %12 OpSelectionMerge %265 None OpBranchConditional %260 %266 %267 %266 = OpLabel -%268 = OpAccessChain %269 %14 %270 -OpStore %268 %13 +%268 = OpAccessChain %269 %15 %270 +OpStore %268 %14 OpBranch %265 %267 = OpLabel OpBranch %265 %265 = OpLabel %273 = OpAccessChain %275 %274 %276 %277 = OpAccessChain %278 %36 %279 -%280 = OpLoad %8 %277 +%280 = OpLoad %9 %277 %272 = OpAccessChain %281 %273 %280 %271 = OpAccessChain %282 %272 %283 -%284 = OpLoad %15 %14 +%284 = OpLoad %16 %15 OpStore %271 %284 %287 = OpAccessChain %288 %274 %289 %290 = OpAccessChain %291 %36 %292 -%293 = OpLoad %8 %290 +%293 = OpLoad %9 %290 %286 = OpAccessChain %294 %287 %293 %285 = OpAccessChain %295 %286 %296 -%297 = OpLoad %15 %17 +%297 = OpLoad %16 %18 OpStore %285 %297 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__collatz.spvasm.snap b/tests/snapshots/snapshots__collatz.spvasm.snap index 89a571a9c..b21b66ef0 100644 --- a/tests/snapshots/snapshots__collatz.spvasm.snap +++ b/tests/snapshots/snapshots__collatz.spvasm.snap @@ -17,93 +17,93 @@ OpMemberDecorate %45 0 Offset 0 OpDecorate %46 DescriptorSet 0 OpDecorate %46 Binding 0 OpDecorate %53 BuiltIn GlobalInvocationId -%3 = OpTypeInt 32 0 -%2 = OpConstant %3 0 -%4 = OpConstant %3 1 -%5 = OpConstant %3 2 -%6 = OpConstant %3 3 -%8 = OpTypePointer Function %3 -%12 = OpTypeFunction %3 %3 -%18 = OpTypeBool -%38 = OpTypeVoid -%40 = OpTypeFunction %38 -%43 = OpTypeRuntimeArray %3 +%0 = OpTypeVoid +%4 = OpTypeInt 32 0 +%3 = OpConstant %4 0 +%5 = OpConstant %4 1 +%6 = OpConstant %4 2 +%7 = OpConstant %4 3 +%9 = OpTypePointer Function %4 +%13 = OpTypeFunction %4 %4 +%19 = OpTypeBool +%40 = OpTypeFunction %0 +%43 = OpTypeRuntimeArray %4 %45 = OpTypeStruct %43 %47 = OpTypePointer Uniform %45 %46 = OpVariable %47 Uniform %48 = OpTypePointer Uniform %43 %49 = OpTypeInt 32 1 %50 = OpConstant %49 0 -%52 = OpTypeVector %3 3 +%52 = OpTypeVector %4 3 %54 = OpTypePointer Input %52 %53 = OpVariable %54 Input -%55 = OpTypePointer Input %3 +%55 = OpTypePointer Input %4 %56 = OpConstant %49 0 -%58 = OpTypePointer Uniform %3 +%58 = OpTypePointer Uniform %4 %62 = OpTypePointer Uniform %43 %63 = OpConstant %49 0 -%65 = OpTypePointer Input %3 +%65 = OpTypePointer Input %4 %66 = OpConstant %49 0 -%68 = OpTypePointer Uniform %3 -%11 = OpFunction %3 None %12 -%10 = OpFunctionParameter %3 -%13 = OpLabel -%7 = OpVariable %8 Function -%9 = OpVariable %8 Function %2 -OpStore %7 %10 -OpBranch %14 +%68 = OpTypePointer Uniform %4 +%12 = OpFunction %4 None %13 +%11 = OpFunctionParameter %4 %14 = OpLabel -OpLoopMerge %15 %17 None -OpBranch %16 -%16 = OpLabel -%20 = OpLoad %3 %7 -%19 = OpULessThanEqual %18 %20 %4 -OpSelectionMerge %21 None -OpBranchConditional %19 %22 %23 -%22 = OpLabel +%8 = OpVariable %9 Function +%10 = OpVariable %9 Function %3 +OpStore %8 %11 OpBranch %15 -%23 = OpLabel -OpBranch %21 -%21 = OpLabel -%26 = OpLoad %3 %7 -%25 = OpUMod %3 %26 %5 -%24 = OpIEqual %18 %25 %2 -OpSelectionMerge %27 None -OpBranchConditional %24 %28 %29 -%28 = OpLabel -%31 = OpLoad %3 %7 -%30 = OpUDiv %3 %31 %5 -OpStore %7 %30 -OpBranch %27 -%29 = OpLabel -%34 = OpLoad %3 %7 -%33 = OpIMul %3 %6 %34 -%32 = OpIAdd %3 %33 %4 -OpStore %7 %32 -OpBranch %27 -%27 = OpLabel -%36 = OpLoad %3 %9 -%35 = OpIAdd %3 %36 %4 -OpStore %9 %35 +%15 = OpLabel +OpLoopMerge %16 %18 None OpBranch %17 %17 = OpLabel -OpBranch %14 -%15 = OpLabel -%37 = OpLoad %3 %9 -OpReturnValue %37 +%21 = OpLoad %4 %8 +%20 = OpULessThanEqual %19 %21 %5 +OpSelectionMerge %22 None +OpBranchConditional %20 %23 %24 +%23 = OpLabel +OpBranch %16 +%24 = OpLabel +OpBranch %22 +%22 = OpLabel +%27 = OpLoad %4 %8 +%26 = OpUMod %4 %27 %6 +%25 = OpIEqual %19 %26 %3 +OpSelectionMerge %28 None +OpBranchConditional %25 %29 %30 +%29 = OpLabel +%32 = OpLoad %4 %8 +%31 = OpUDiv %4 %32 %6 +OpStore %8 %31 +OpBranch %28 +%30 = OpLabel +%35 = OpLoad %4 %8 +%34 = OpIMul %4 %7 %35 +%33 = OpIAdd %4 %34 %5 +OpStore %8 %33 +OpBranch %28 +%28 = OpLabel +%37 = OpLoad %4 %10 +%36 = OpIAdd %4 %37 %5 +OpStore %10 %36 +OpBranch %18 +%18 = OpLabel +OpBranch %15 +%16 = OpLabel +%38 = OpLoad %4 %10 +OpReturnValue %38 OpFunctionEnd -%39 = OpFunction %38 None %40 +%39 = OpFunction %0 None %40 %41 = OpLabel %44 = OpAccessChain %48 %46 %50 %51 = OpAccessChain %55 %53 %56 -%57 = OpLoad %3 %51 +%57 = OpLoad %4 %51 %42 = OpAccessChain %58 %44 %57 %61 = OpAccessChain %62 %46 %63 %64 = OpAccessChain %65 %53 %66 -%67 = OpLoad %3 %64 +%67 = OpLoad %4 %64 %60 = OpAccessChain %68 %61 %67 -%69 = OpLoad %3 %60 -%59 = OpFunctionCall %3 %11 %69 +%69 = OpLoad %4 %60 +%59 = OpFunctionCall %4 %12 %69 OpStore %42 %59 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__empty.spvasm.snap b/tests/snapshots/snapshots__empty.spvasm.snap index ae2b9628b..00397cf4a 100644 --- a/tests/snapshots/snapshots__empty.spvasm.snap +++ b/tests/snapshots/snapshots__empty.spvasm.snap @@ -11,9 +11,9 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %3 "main" OpExecutionMode %3 LocalSize 1 1 1 -%2 = OpTypeVoid -%4 = OpTypeFunction %2 -%3 = OpFunction %2 None %4 +%0 = OpTypeVoid +%4 = OpTypeFunction %0 +%3 = OpFunction %0 None %4 %5 = OpLabel OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__quad.spvasm.snap b/tests/snapshots/snapshots__quad.spvasm.snap index 1335b66ec..a96d97cdd 100644 --- a/tests/snapshots/snapshots__quad.spvasm.snap +++ b/tests/snapshots/snapshots__quad.spvasm.snap @@ -22,23 +22,23 @@ OpDecorate %27 Binding 0 OpDecorate %32 DescriptorSet 0 OpDecorate %32 Binding 1 OpDecorate %35 Location 0 -%3 = OpTypeFloat 32 -%2 = OpConstant %3 1.2 -%4 = OpConstant %3 0.0 -%5 = OpConstant %3 1.0 -%6 = OpTypeVoid -%8 = OpTypeFunction %6 -%10 = OpTypeVector %3 2 +%0 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.2 +%5 = OpConstant %4 0.0 +%6 = OpConstant %4 1.0 +%8 = OpTypeFunction %0 +%10 = OpTypeVector %4 2 %12 = OpTypePointer Output %10 %11 = OpVariable %12 Output %14 = OpTypePointer Input %10 %13 = OpVariable %14 Input -%16 = OpTypeVector %3 4 +%16 = OpTypeVector %4 4 %18 = OpTypePointer Output %16 %17 = OpVariable %18 Output %20 = OpVariable %14 Input %25 = OpVariable %18 Output -%26 = OpTypeImage %3 2D 0 0 0 1 Unknown +%26 = OpTypeImage %4 2D 0 0 0 1 Unknown %28 = OpTypePointer UniformConstant %26 %27 = OpVariable %28 UniformConstant %30 = OpTypeSampledImage %26 @@ -46,17 +46,17 @@ OpDecorate %35 Location 0 %33 = OpTypePointer UniformConstant %31 %32 = OpVariable %33 UniformConstant %35 = OpVariable %14 Input -%7 = OpFunction %6 None %8 +%7 = OpFunction %0 None %8 %9 = OpLabel %15 = OpLoad %10 %13 OpStore %11 %15 %21 = OpLoad %10 %20 -%19 = OpVectorTimesScalar %10 %21 %2 -%22 = OpCompositeConstruct %16 %19 %4 %5 +%19 = OpVectorTimesScalar %10 %21 %3 +%22 = OpCompositeConstruct %16 %19 %5 %6 OpStore %17 %22 OpReturn OpFunctionEnd -%23 = OpFunction %6 None %8 +%23 = OpFunction %0 None %8 %24 = OpLabel %29 = OpLoad %26 %27 %34 = OpLoad %31 %32 diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap index e6e199112..4e19de6a5 100644 --- a/tests/snapshots/snapshots__shadow.spvasm.snap +++ b/tests/snapshots/snapshots__shadow.spvasm.snap @@ -11,10 +11,10 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %64 "fs_main" %114 %111 %217 OpExecutionMode %64 OriginUpperLeft -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 2 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 3 +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 2 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 3 OpDecorate %76 Block OpMemberDecorate %76 0 Offset 0 OpDecorate %77 DescriptorSet 0 @@ -33,161 +33,161 @@ OpDecorate %102 Binding 1 OpDecorate %111 Location 1 OpDecorate %114 Location 0 OpDecorate %217 Location 0 -%3 = OpTypeFloat 32 -%2 = OpConstant %3 0.0 -%4 = OpConstant %3 1.0 -%5 = OpConstant %3 0.5 -%6 = OpConstant %3 -0.5 -%7 = OpConstant %3 0.05 -%9 = OpTypeVector %3 3 -%8 = OpConstantComposite %9 %7 %7 %7 -%11 = OpTypeInt 32 0 -%10 = OpConstant %11 10 -%12 = OpConstant %11 0 -%13 = OpConstant %11 1 -%16 = OpTypeVector %3 4 -%18 = OpTypeFunction %3 %11 %16 -%20 = OpTypeBool -%26 = OpTypeImage %3 2D 1 1 0 1 Unknown -%28 = OpTypePointer UniformConstant %26 -%27 = OpVariable %28 UniformConstant -%30 = OpTypeSampledImage %26 -%31 = OpTypeSampler -%33 = OpTypePointer UniformConstant %31 -%32 = OpVariable %33 UniformConstant -%35 = OpTypeVector %3 2 -%49 = OpTypeInt 32 1 -%58 = OpConstant %3 0.0 -%60 = OpTypePointer Function %9 -%62 = OpTypePointer Function %11 -%63 = OpTypeVoid -%65 = OpTypeFunction %63 -%74 = OpTypeVector %11 4 +%0 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 0.0 +%5 = OpConstant %4 1.0 +%6 = OpConstant %4 0.5 +%7 = OpConstant %4 -0.5 +%8 = OpConstant %4 0.05 +%10 = OpTypeVector %4 3 +%9 = OpConstantComposite %10 %8 %8 %8 +%12 = OpTypeInt 32 0 +%11 = OpConstant %12 10 +%13 = OpConstant %12 0 +%14 = OpConstant %12 1 +%17 = OpTypeVector %4 4 +%19 = OpTypeFunction %4 %12 %17 +%21 = OpTypeBool +%27 = OpTypeImage %4 2D 1 1 0 1 Unknown +%29 = OpTypePointer UniformConstant %27 +%28 = OpVariable %29 UniformConstant +%31 = OpTypeSampledImage %27 +%32 = OpTypeSampler +%34 = OpTypePointer UniformConstant %32 +%33 = OpVariable %34 UniformConstant +%36 = OpTypeVector %4 2 +%50 = OpTypeInt 32 1 +%59 = OpConstant %4 0.0 +%61 = OpTypePointer Function %10 +%63 = OpTypePointer Function %12 +%65 = OpTypeFunction %0 +%74 = OpTypeVector %12 4 %76 = OpTypeStruct %74 %78 = OpTypePointer Uniform %76 %77 = OpVariable %78 Uniform %79 = OpTypePointer Uniform %74 -%80 = OpConstant %49 0 -%81 = OpTypePointer Uniform %11 -%82 = OpConstant %49 0 -%95 = OpTypeMatrix %16 4 -%97 = OpTypeStruct %95 %16 %16 +%80 = OpConstant %50 0 +%81 = OpTypePointer Uniform %12 +%82 = OpConstant %50 0 +%95 = OpTypeMatrix %17 4 +%97 = OpTypeStruct %95 %17 %17 %99 = OpTypeRuntimeArray %97 %101 = OpTypeStruct %99 %103 = OpTypePointer Uniform %101 %102 = OpVariable %103 Uniform %104 = OpTypePointer Uniform %99 -%105 = OpConstant %49 0 +%105 = OpConstant %50 0 %107 = OpTypePointer Uniform %97 %108 = OpTypePointer Uniform %95 -%109 = OpConstant %49 0 -%112 = OpTypePointer Input %16 +%109 = OpConstant %50 0 +%112 = OpTypePointer Input %17 %111 = OpVariable %112 Input -%115 = OpTypePointer Input %9 +%115 = OpTypePointer Input %10 %114 = OpVariable %115 Input %123 = OpTypePointer Uniform %99 -%124 = OpConstant %49 0 +%124 = OpConstant %50 0 %126 = OpTypePointer Uniform %97 -%127 = OpTypePointer Uniform %16 -%128 = OpConstant %49 1 -%129 = OpTypePointer Uniform %3 -%130 = OpConstant %49 0 +%127 = OpTypePointer Uniform %17 +%128 = OpConstant %50 1 +%129 = OpTypePointer Uniform %4 +%130 = OpConstant %50 0 %136 = OpTypePointer Uniform %99 -%137 = OpConstant %49 0 +%137 = OpConstant %50 0 %139 = OpTypePointer Uniform %97 -%140 = OpTypePointer Uniform %16 -%141 = OpConstant %49 1 -%142 = OpTypePointer Uniform %3 -%143 = OpConstant %49 1 +%140 = OpTypePointer Uniform %17 +%141 = OpConstant %50 1 +%142 = OpTypePointer Uniform %4 +%143 = OpConstant %50 1 %149 = OpTypePointer Uniform %99 -%150 = OpConstant %49 0 +%150 = OpConstant %50 0 %152 = OpTypePointer Uniform %97 -%153 = OpTypePointer Uniform %16 -%154 = OpConstant %49 1 -%155 = OpTypePointer Uniform %3 -%156 = OpConstant %49 2 -%160 = OpTypePointer Input %3 -%161 = OpConstant %49 0 -%164 = OpTypePointer Input %3 -%165 = OpConstant %49 1 -%168 = OpTypePointer Input %3 -%169 = OpConstant %49 2 +%153 = OpTypePointer Uniform %17 +%154 = OpConstant %50 1 +%155 = OpTypePointer Uniform %4 +%156 = OpConstant %50 2 +%160 = OpTypePointer Input %4 +%161 = OpConstant %50 0 +%164 = OpTypePointer Input %4 +%165 = OpConstant %50 1 +%168 = OpTypePointer Input %4 +%169 = OpConstant %50 2 %179 = OpTypePointer Uniform %99 -%180 = OpConstant %49 0 +%180 = OpConstant %50 0 %182 = OpTypePointer Uniform %97 -%183 = OpTypePointer Uniform %16 -%184 = OpConstant %49 2 -%185 = OpTypePointer Uniform %3 -%186 = OpConstant %49 0 +%183 = OpTypePointer Uniform %17 +%184 = OpConstant %50 2 +%185 = OpTypePointer Uniform %4 +%186 = OpConstant %50 0 %192 = OpTypePointer Uniform %99 -%193 = OpConstant %49 0 +%193 = OpConstant %50 0 %195 = OpTypePointer Uniform %97 -%196 = OpTypePointer Uniform %16 -%197 = OpConstant %49 2 -%198 = OpTypePointer Uniform %3 -%199 = OpConstant %49 1 +%196 = OpTypePointer Uniform %17 +%197 = OpConstant %50 2 +%198 = OpTypePointer Uniform %4 +%199 = OpConstant %50 1 %205 = OpTypePointer Uniform %99 -%206 = OpConstant %49 0 +%206 = OpConstant %50 0 %208 = OpTypePointer Uniform %97 -%209 = OpTypePointer Uniform %16 -%210 = OpConstant %49 2 -%211 = OpTypePointer Uniform %3 -%212 = OpConstant %49 2 -%218 = OpTypePointer Output %16 +%209 = OpTypePointer Uniform %17 +%210 = OpConstant %50 2 +%211 = OpTypePointer Uniform %4 +%212 = OpConstant %50 2 +%218 = OpTypePointer Output %17 %217 = OpVariable %218 Output -%17 = OpFunction %3 None %18 -%14 = OpFunctionParameter %11 -%15 = OpFunctionParameter %16 -%19 = OpLabel -%22 = OpCompositeExtract %3 %15 3 -%21 = OpFOrdLessThanEqual %20 %22 %2 -OpSelectionMerge %23 None -OpBranchConditional %21 %24 %25 -%24 = OpLabel -OpReturnValue %4 +%18 = OpFunction %4 None %19 +%15 = OpFunctionParameter %12 +%16 = OpFunctionParameter %17 +%20 = OpLabel +%23 = OpCompositeExtract %4 %16 3 +%22 = OpFOrdLessThanEqual %21 %23 %3 +OpSelectionMerge %24 None +OpBranchConditional %22 %25 %26 %25 = OpLabel -OpBranch %23 -%23 = OpLabel -%29 = OpLoad %26 %27 -%34 = OpLoad %31 %32 -%39 = OpCompositeExtract %3 %15 0 -%40 = OpCompositeExtract %3 %15 1 -%41 = OpCompositeConstruct %35 %39 %40 -%42 = OpCompositeConstruct %35 %5 %6 -%38 = OpFMul %35 %41 %42 -%44 = OpCompositeExtract %3 %15 3 -%43 = OpFDiv %3 %4 %44 -%37 = OpVectorTimesScalar %35 %38 %43 -%45 = OpCompositeConstruct %35 %5 %5 -%36 = OpFAdd %35 %37 %45 -%46 = OpCompositeExtract %3 %36 0 -%47 = OpCompositeExtract %3 %36 1 -%50 = OpBitcast %49 %14 -%48 = OpConvertUToF %3 %50 -%51 = OpCompositeConstruct %9 %46 %47 %48 -%52 = OpSampledImage %30 %29 %34 -%55 = OpCompositeExtract %3 %15 2 -%57 = OpCompositeExtract %3 %15 3 -%56 = OpFDiv %3 %4 %57 -%54 = OpFMul %3 %55 %56 -%53 = OpImageSampleDrefExplicitLod %3 %52 %51 %54 Lod %58 -OpReturnValue %53 +OpReturnValue %5 +%26 = OpLabel +OpBranch %24 +%24 = OpLabel +%30 = OpLoad %27 %28 +%35 = OpLoad %32 %33 +%40 = OpCompositeExtract %4 %16 0 +%41 = OpCompositeExtract %4 %16 1 +%42 = OpCompositeConstruct %36 %40 %41 +%43 = OpCompositeConstruct %36 %6 %7 +%39 = OpFMul %36 %42 %43 +%45 = OpCompositeExtract %4 %16 3 +%44 = OpFDiv %4 %5 %45 +%38 = OpVectorTimesScalar %36 %39 %44 +%46 = OpCompositeConstruct %36 %6 %6 +%37 = OpFAdd %36 %38 %46 +%47 = OpCompositeExtract %4 %37 0 +%48 = OpCompositeExtract %4 %37 1 +%51 = OpBitcast %50 %15 +%49 = OpConvertUToF %4 %51 +%52 = OpCompositeConstruct %10 %47 %48 %49 +%53 = OpSampledImage %31 %30 %35 +%56 = OpCompositeExtract %4 %16 2 +%58 = OpCompositeExtract %4 %16 3 +%57 = OpFDiv %4 %5 %58 +%55 = OpFMul %4 %56 %57 +%54 = OpImageSampleDrefExplicitLod %4 %53 %52 %55 Lod %59 +OpReturnValue %54 OpFunctionEnd -%64 = OpFunction %63 None %65 +%64 = OpFunction %0 None %65 %66 = OpLabel -%59 = OpVariable %60 Function %8 -%61 = OpVariable %62 Function %12 +%60 = OpVariable %61 Function %9 +%62 = OpVariable %63 Function %13 OpBranch %67 %67 = OpLabel OpLoopMerge %68 %70 None OpBranch %69 %69 = OpLabel -%72 = OpLoad %11 %61 +%72 = OpLoad %12 %62 %75 = OpAccessChain %79 %77 %80 %73 = OpAccessChain %81 %75 %82 -%83 = OpLoad %11 %73 -%84 = OpExtInst %11 %1 UMin %83 %10 -%71 = OpUGreaterThanEqual %20 %72 %84 +%83 = OpLoad %12 %73 +%84 = OpExtInst %12 %1 UMin %83 %11 +%71 = OpUGreaterThanEqual %21 %72 %84 OpSelectionMerge %85 None OpBranchConditional %71 %86 %87 %86 = OpLabel @@ -195,80 +195,80 @@ OpBranch %68 %87 = OpLabel OpBranch %85 %85 = OpLabel -%89 = OpLoad %9 %59 -%93 = OpLoad %11 %61 +%89 = OpLoad %10 %60 +%93 = OpLoad %12 %62 %100 = OpAccessChain %104 %102 %105 -%106 = OpLoad %11 %61 +%106 = OpLoad %12 %62 %98 = OpAccessChain %107 %100 %106 %96 = OpAccessChain %108 %98 %109 %110 = OpLoad %95 %96 -%113 = OpLoad %16 %111 -%94 = OpMatrixTimesVector %16 %110 %113 -%92 = OpFunctionCall %3 %17 %93 %94 -%116 = OpLoad %9 %114 -%117 = OpExtInst %9 %1 Normalize %116 +%113 = OpLoad %17 %111 +%94 = OpMatrixTimesVector %17 %110 %113 +%92 = OpFunctionCall %4 %18 %93 %94 +%116 = OpLoad %10 %114 +%117 = OpExtInst %10 %1 Normalize %116 %122 = OpAccessChain %123 %102 %124 -%125 = OpLoad %11 %61 +%125 = OpLoad %12 %62 %121 = OpAccessChain %126 %122 %125 %120 = OpAccessChain %127 %121 %128 %119 = OpAccessChain %129 %120 %130 -%131 = OpLoad %3 %119 +%131 = OpLoad %4 %119 %135 = OpAccessChain %136 %102 %137 -%138 = OpLoad %11 %61 +%138 = OpLoad %12 %62 %134 = OpAccessChain %139 %135 %138 %133 = OpAccessChain %140 %134 %141 %132 = OpAccessChain %142 %133 %143 -%144 = OpLoad %3 %132 +%144 = OpLoad %4 %132 %148 = OpAccessChain %149 %102 %150 -%151 = OpLoad %11 %61 +%151 = OpLoad %12 %62 %147 = OpAccessChain %152 %148 %151 %146 = OpAccessChain %153 %147 %154 %145 = OpAccessChain %155 %146 %156 -%157 = OpLoad %3 %145 -%158 = OpCompositeConstruct %9 %131 %144 %157 +%157 = OpLoad %4 %145 +%158 = OpCompositeConstruct %10 %131 %144 %157 %159 = OpAccessChain %160 %111 %161 -%162 = OpLoad %3 %159 +%162 = OpLoad %4 %159 %163 = OpAccessChain %164 %111 %165 -%166 = OpLoad %3 %163 +%166 = OpLoad %4 %163 %167 = OpAccessChain %168 %111 %169 -%170 = OpLoad %3 %167 -%171 = OpCompositeConstruct %9 %162 %166 %170 -%118 = OpFSub %9 %158 %171 -%172 = OpExtInst %9 %1 Normalize %118 -%173 = OpDot %3 %117 %172 -%174 = OpExtInst %3 %1 FMax %2 %173 -%91 = OpFMul %3 %92 %174 +%170 = OpLoad %4 %167 +%171 = OpCompositeConstruct %10 %162 %166 %170 +%118 = OpFSub %10 %158 %171 +%172 = OpExtInst %10 %1 Normalize %118 +%173 = OpDot %4 %117 %172 +%174 = OpExtInst %4 %1 FMax %3 %173 +%91 = OpFMul %4 %92 %174 %178 = OpAccessChain %179 %102 %180 -%181 = OpLoad %11 %61 +%181 = OpLoad %12 %62 %177 = OpAccessChain %182 %178 %181 %176 = OpAccessChain %183 %177 %184 %175 = OpAccessChain %185 %176 %186 -%187 = OpLoad %3 %175 +%187 = OpLoad %4 %175 %191 = OpAccessChain %192 %102 %193 -%194 = OpLoad %11 %61 +%194 = OpLoad %12 %62 %190 = OpAccessChain %195 %191 %194 %189 = OpAccessChain %196 %190 %197 %188 = OpAccessChain %198 %189 %199 -%200 = OpLoad %3 %188 +%200 = OpLoad %4 %188 %204 = OpAccessChain %205 %102 %206 -%207 = OpLoad %11 %61 +%207 = OpLoad %12 %62 %203 = OpAccessChain %208 %204 %207 %202 = OpAccessChain %209 %203 %210 %201 = OpAccessChain %211 %202 %212 -%213 = OpLoad %3 %201 -%214 = OpCompositeConstruct %9 %187 %200 %213 -%90 = OpVectorTimesScalar %9 %214 %91 -%88 = OpFAdd %9 %89 %90 -OpStore %59 %88 +%213 = OpLoad %4 %201 +%214 = OpCompositeConstruct %10 %187 %200 %213 +%90 = OpVectorTimesScalar %10 %214 %91 +%88 = OpFAdd %10 %89 %90 +OpStore %60 %88 OpBranch %70 %70 = OpLabel -%216 = OpLoad %11 %61 -%215 = OpIAdd %11 %216 %13 -OpStore %61 %215 +%216 = OpLoad %12 %62 +%215 = OpIAdd %12 %216 %14 +OpStore %62 %215 OpBranch %67 %68 = OpLabel -%219 = OpLoad %9 %59 -%220 = OpCompositeConstruct %16 %219 %4 +%219 = OpLoad %10 %60 +%220 = OpCompositeConstruct %17 %219 %5 OpStore %217 %220 OpReturn OpFunctionEnd diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap index d0577615b..76696763d 100644 --- a/tests/snapshots/snapshots__skybox.spvasm.snap +++ b/tests/snapshots/snapshots__skybox.spvasm.snap @@ -30,95 +30,95 @@ OpDecorate %174 Binding 1 OpDecorate %179 DescriptorSet 0 OpDecorate %179 Binding 2 OpDecorate %182 Location 0 -%3 = OpTypeInt 32 1 -%2 = OpConstant %3 2 -%4 = OpConstant %3 1 -%6 = OpTypeFloat 32 -%5 = OpConstant %6 4.0 -%7 = OpConstant %6 1.0 -%8 = OpConstant %6 0.0 -%10 = OpTypePointer Function %3 -%13 = OpTypeVector %6 4 -%14 = OpTypePointer Function %13 -%15 = OpTypeVoid -%17 = OpTypeFunction %15 +%0 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 2 +%5 = OpConstant %4 1 +%7 = OpTypeFloat 32 +%6 = OpConstant %7 4.0 +%8 = OpConstant %7 1.0 +%9 = OpConstant %7 0.0 +%11 = OpTypePointer Function %4 +%14 = OpTypeVector %7 4 +%15 = OpTypePointer Function %14 +%17 = OpTypeFunction %0 %20 = OpTypeInt 32 0 %22 = OpTypePointer Input %20 %21 = OpVariable %22 Input -%29 = OpTypeMatrix %13 4 +%29 = OpTypeMatrix %14 4 %31 = OpTypeStruct %29 %29 %33 = OpTypePointer Uniform %31 %32 = OpVariable %33 Uniform %34 = OpTypePointer Uniform %29 -%35 = OpConstant %3 0 -%46 = OpTypeVector %6 3 +%35 = OpConstant %4 0 +%46 = OpTypeVector %7 3 %48 = OpTypePointer Output %46 %47 = OpVariable %48 Output %50 = OpTypeMatrix %46 3 %54 = OpTypePointer Uniform %29 -%55 = OpConstant %3 1 -%56 = OpTypePointer Uniform %13 -%57 = OpConstant %3 0 -%58 = OpTypePointer Uniform %6 -%59 = OpConstant %3 0 +%55 = OpConstant %4 1 +%56 = OpTypePointer Uniform %14 +%57 = OpConstant %4 0 +%58 = OpTypePointer Uniform %7 +%59 = OpConstant %4 0 %64 = OpTypePointer Uniform %29 -%65 = OpConstant %3 1 -%66 = OpTypePointer Uniform %13 -%67 = OpConstant %3 0 -%68 = OpTypePointer Uniform %6 -%69 = OpConstant %3 1 +%65 = OpConstant %4 1 +%66 = OpTypePointer Uniform %14 +%67 = OpConstant %4 0 +%68 = OpTypePointer Uniform %7 +%69 = OpConstant %4 1 %74 = OpTypePointer Uniform %29 -%75 = OpConstant %3 1 -%76 = OpTypePointer Uniform %13 -%77 = OpConstant %3 0 -%78 = OpTypePointer Uniform %6 -%79 = OpConstant %3 2 +%75 = OpConstant %4 1 +%76 = OpTypePointer Uniform %14 +%77 = OpConstant %4 0 +%78 = OpTypePointer Uniform %7 +%79 = OpConstant %4 2 %85 = OpTypePointer Uniform %29 -%86 = OpConstant %3 1 -%87 = OpTypePointer Uniform %13 -%88 = OpConstant %3 1 -%89 = OpTypePointer Uniform %6 -%90 = OpConstant %3 0 +%86 = OpConstant %4 1 +%87 = OpTypePointer Uniform %14 +%88 = OpConstant %4 1 +%89 = OpTypePointer Uniform %7 +%90 = OpConstant %4 0 %95 = OpTypePointer Uniform %29 -%96 = OpConstant %3 1 -%97 = OpTypePointer Uniform %13 -%98 = OpConstant %3 1 -%99 = OpTypePointer Uniform %6 -%100 = OpConstant %3 1 +%96 = OpConstant %4 1 +%97 = OpTypePointer Uniform %14 +%98 = OpConstant %4 1 +%99 = OpTypePointer Uniform %7 +%100 = OpConstant %4 1 %105 = OpTypePointer Uniform %29 -%106 = OpConstant %3 1 -%107 = OpTypePointer Uniform %13 -%108 = OpConstant %3 1 -%109 = OpTypePointer Uniform %6 -%110 = OpConstant %3 2 +%106 = OpConstant %4 1 +%107 = OpTypePointer Uniform %14 +%108 = OpConstant %4 1 +%109 = OpTypePointer Uniform %7 +%110 = OpConstant %4 2 %116 = OpTypePointer Uniform %29 -%117 = OpConstant %3 1 -%118 = OpTypePointer Uniform %13 -%119 = OpConstant %3 2 -%120 = OpTypePointer Uniform %6 -%121 = OpConstant %3 0 +%117 = OpConstant %4 1 +%118 = OpTypePointer Uniform %14 +%119 = OpConstant %4 2 +%120 = OpTypePointer Uniform %7 +%121 = OpConstant %4 0 %126 = OpTypePointer Uniform %29 -%127 = OpConstant %3 1 -%128 = OpTypePointer Uniform %13 -%129 = OpConstant %3 2 -%130 = OpTypePointer Uniform %6 -%131 = OpConstant %3 1 +%127 = OpConstant %4 1 +%128 = OpTypePointer Uniform %14 +%129 = OpConstant %4 2 +%130 = OpTypePointer Uniform %7 +%131 = OpConstant %4 1 %136 = OpTypePointer Uniform %29 -%137 = OpConstant %3 1 -%138 = OpTypePointer Uniform %13 -%139 = OpConstant %3 2 -%140 = OpTypePointer Uniform %6 -%141 = OpConstant %3 2 -%147 = OpTypePointer Function %6 -%148 = OpConstant %3 0 -%151 = OpTypePointer Function %6 -%152 = OpConstant %3 1 -%155 = OpTypePointer Function %6 -%156 = OpConstant %3 2 -%160 = OpTypePointer Output %13 +%137 = OpConstant %4 1 +%138 = OpTypePointer Uniform %14 +%139 = OpConstant %4 2 +%140 = OpTypePointer Uniform %7 +%141 = OpConstant %4 2 +%147 = OpTypePointer Function %7 +%148 = OpConstant %4 0 +%151 = OpTypePointer Function %7 +%152 = OpConstant %4 1 +%155 = OpTypePointer Function %7 +%156 = OpConstant %4 2 +%160 = OpTypePointer Output %14 %159 = OpVariable %160 Output %172 = OpVariable %160 Output -%173 = OpTypeImage %6 Cube 0 0 0 1 Unknown +%173 = OpTypeImage %7 Cube 0 0 0 1 Unknown %175 = OpTypePointer UniformConstant %173 %174 = OpVariable %175 UniformConstant %177 = OpTypeSampledImage %173 @@ -127,101 +127,101 @@ OpDecorate %182 Location 0 %179 = OpVariable %180 UniformConstant %183 = OpTypePointer Input %46 %182 = OpVariable %183 Input -%16 = OpFunction %15 None %17 +%16 = OpFunction %0 None %17 %18 = OpLabel -%9 = OpVariable %10 Function -%11 = OpVariable %10 Function -%12 = OpVariable %14 Function +%10 = OpVariable %11 Function +%12 = OpVariable %11 Function +%13 = OpVariable %15 Function %23 = OpLoad %20 %21 -%24 = OpBitcast %3 %23 -%19 = OpSDiv %3 %24 %2 -OpStore %9 %19 +%24 = OpBitcast %4 %23 +%19 = OpSDiv %4 %24 %3 +OpStore %10 %19 %26 = OpLoad %20 %21 -%27 = OpBitcast %3 %26 -%25 = OpBitwiseAnd %3 %27 %4 -OpStore %11 %25 +%27 = OpBitcast %4 %26 +%25 = OpBitwiseAnd %4 %27 %5 +OpStore %12 %25 %30 = OpAccessChain %34 %32 %35 %36 = OpLoad %29 %30 -%39 = OpLoad %3 %9 -%40 = OpConvertSToF %6 %39 -%38 = OpFMul %6 %40 %5 -%37 = OpFSub %6 %38 %7 -%43 = OpLoad %3 %11 -%44 = OpConvertSToF %6 %43 -%42 = OpFMul %6 %44 %5 -%41 = OpFSub %6 %42 %7 -%45 = OpCompositeConstruct %13 %37 %41 %8 %7 -%28 = OpMatrixTimesVector %13 %36 %45 -OpStore %12 %28 +%39 = OpLoad %4 %10 +%40 = OpConvertSToF %7 %39 +%38 = OpFMul %7 %40 %6 +%37 = OpFSub %7 %38 %8 +%43 = OpLoad %4 %12 +%44 = OpConvertSToF %7 %43 +%42 = OpFMul %7 %44 %6 +%41 = OpFSub %7 %42 %8 +%45 = OpCompositeConstruct %14 %37 %41 %9 %8 +%28 = OpMatrixTimesVector %14 %36 %45 +OpStore %13 %28 %53 = OpAccessChain %54 %32 %55 %52 = OpAccessChain %56 %53 %57 %51 = OpAccessChain %58 %52 %59 -%60 = OpLoad %6 %51 +%60 = OpLoad %7 %51 %63 = OpAccessChain %64 %32 %65 %62 = OpAccessChain %66 %63 %67 %61 = OpAccessChain %68 %62 %69 -%70 = OpLoad %6 %61 +%70 = OpLoad %7 %61 %73 = OpAccessChain %74 %32 %75 %72 = OpAccessChain %76 %73 %77 %71 = OpAccessChain %78 %72 %79 -%80 = OpLoad %6 %71 +%80 = OpLoad %7 %71 %81 = OpCompositeConstruct %46 %60 %70 %80 %84 = OpAccessChain %85 %32 %86 %83 = OpAccessChain %87 %84 %88 %82 = OpAccessChain %89 %83 %90 -%91 = OpLoad %6 %82 +%91 = OpLoad %7 %82 %94 = OpAccessChain %95 %32 %96 %93 = OpAccessChain %97 %94 %98 %92 = OpAccessChain %99 %93 %100 -%101 = OpLoad %6 %92 +%101 = OpLoad %7 %92 %104 = OpAccessChain %105 %32 %106 %103 = OpAccessChain %107 %104 %108 %102 = OpAccessChain %109 %103 %110 -%111 = OpLoad %6 %102 +%111 = OpLoad %7 %102 %112 = OpCompositeConstruct %46 %91 %101 %111 %115 = OpAccessChain %116 %32 %117 %114 = OpAccessChain %118 %115 %119 %113 = OpAccessChain %120 %114 %121 -%122 = OpLoad %6 %113 +%122 = OpLoad %7 %113 %125 = OpAccessChain %126 %32 %127 %124 = OpAccessChain %128 %125 %129 %123 = OpAccessChain %130 %124 %131 -%132 = OpLoad %6 %123 +%132 = OpLoad %7 %123 %135 = OpAccessChain %136 %32 %137 %134 = OpAccessChain %138 %135 %139 %133 = OpAccessChain %140 %134 %141 -%142 = OpLoad %6 %133 +%142 = OpLoad %7 %133 %143 = OpCompositeConstruct %46 %122 %132 %142 %144 = OpCompositeConstruct %50 %81 %112 %143 %145 = OpTranspose %50 %144 -%146 = OpAccessChain %147 %12 %148 -%149 = OpLoad %6 %146 -%150 = OpAccessChain %151 %12 %152 -%153 = OpLoad %6 %150 -%154 = OpAccessChain %155 %12 %156 -%157 = OpLoad %6 %154 +%146 = OpAccessChain %147 %13 %148 +%149 = OpLoad %7 %146 +%150 = OpAccessChain %151 %13 %152 +%153 = OpLoad %7 %150 +%154 = OpAccessChain %155 %13 %156 +%157 = OpLoad %7 %154 %158 = OpCompositeConstruct %46 %149 %153 %157 %49 = OpMatrixTimesVector %46 %145 %158 OpStore %47 %49 -%163 = OpLoad %3 %9 -%164 = OpConvertSToF %6 %163 -%162 = OpFMul %6 %164 %5 -%161 = OpFSub %6 %162 %7 -%167 = OpLoad %3 %11 -%168 = OpConvertSToF %6 %167 -%166 = OpFMul %6 %168 %5 -%165 = OpFSub %6 %166 %7 -%169 = OpCompositeConstruct %13 %161 %165 %8 %7 +%163 = OpLoad %4 %10 +%164 = OpConvertSToF %7 %163 +%162 = OpFMul %7 %164 %6 +%161 = OpFSub %7 %162 %8 +%167 = OpLoad %4 %12 +%168 = OpConvertSToF %7 %167 +%166 = OpFMul %7 %168 %6 +%165 = OpFSub %7 %166 %8 +%169 = OpCompositeConstruct %14 %161 %165 %9 %8 OpStore %159 %169 OpReturn OpFunctionEnd -%170 = OpFunction %15 None %17 +%170 = OpFunction %0 None %17 %171 = OpLabel %176 = OpLoad %173 %174 %181 = OpLoad %178 %179 %184 = OpLoad %46 %182 %185 = OpSampledImage %177 %176 %181 -%186 = OpImageSampleImplicitLod %13 %185 %184 +%186 = OpImageSampleImplicitLod %14 %185 %184 OpStore %172 %186 OpReturn OpFunctionEnd From 11a3ed9837f359473cbe6208e198f771899c7ce5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 6 Feb 2021 02:20:38 -0500 Subject: [PATCH 0441/2212] WGSL support for void function calls --- src/front/wgsl/mod.rs | 90 ++++++++++++++++++--------------- src/front/wgsl/tests.rs | 8 +++ tests/snapshots/in/collatz.wgsl | 2 +- 3 files changed, 58 insertions(+), 42 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 508d01e4d..f82b51950 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -91,6 +91,8 @@ pub enum Error<'a> { NotCompositeType(Handle), #[error("function redefinition: `{0}`")] FunctionRedefinition(&'a str), + #[error("call to local `{0}(..)` can't be resolved")] + UnknownLocalFunction(&'a str), #[error("other error")] Other, } @@ -307,6 +309,8 @@ pub enum Scope { GeneralExpr, } +type LocalFunctionCall = (Handle, Vec>); + struct ParsedVariable<'a> { name: &'a str, class: Option, @@ -370,6 +374,36 @@ impl Parser { }) } + fn parse_local_function_call<'a>( + &mut self, + lexer: &mut Lexer<'a>, + name: &'a str, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + let fun_handle = match ctx.functions.iter().find(|(_, fun)| match fun.name { + Some(ref string) => string == name, + None => false, + }) { + Some((fun_handle, _)) => fun_handle, + None => return Ok(None), + }; + + let mut arguments = Vec::new(); + lexer.expect(Token::Paren('('))?; + if !lexer.skip(Token::Paren(')')) { + loop { + let arg = self.parse_general_expression(lexer, ctx.reborrow())?; + arguments.push(arg); + match lexer.next() { + Token::Paren(')') => break, + Token::Separator(',') => (), + other => return Err(Error::Unexpected(other, "argument list separator")), + } + } + } + Ok(Some((fun_handle, arguments))) + } + fn parse_function_call_inner<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -650,39 +684,12 @@ impl Parser { query: crate::ImageQuery::NumSamples, }) } - _ => { - match ctx.functions.iter().find(|(_, fun)| match fun.name { - Some(ref string) => string == name, - None => false, - }) { - Some((function, _)) => { - let mut arguments = Vec::new(); - lexer.expect(Token::Paren('('))?; - if !lexer.skip(Token::Paren(')')) { - loop { - let arg = - self.parse_general_expression(lexer, ctx.reborrow())?; - arguments.push(arg); - match lexer.next() { - Token::Paren(')') => break, - Token::Separator(',') => (), - other => { - return Err(Error::Unexpected( - other, - "argument list separator", - )) - } - } - } - } - Some(crate::Expression::Call { - function, - arguments, - }) - } - None => None, - } - } + _ => self.parse_local_function_call(lexer, name, ctx)?.map( + |(function, arguments)| crate::Expression::Call { + function, + arguments, + }, + ), } }) } @@ -1748,8 +1755,8 @@ impl Parser { "break" => Some(crate::Statement::Break), "continue" => Some(crate::Statement::Continue), "discard" => Some(crate::Statement::Kill), + // assignment or a function call ident => { - // assignment if let Some(&var_expr) = context.lookup_ident.get(ident) { let left = self.parse_postfix(lexer, context.as_expression(), var_expr)?; lexer.expect(Token::Operation('='))?; @@ -1759,14 +1766,15 @@ impl Parser { pointer: left, value, }) - } else if let Some(expr) = - self.parse_function_call_inner(lexer, ident, context.as_expression())? - { - context.expressions.append(expr); - lexer.expect(Token::Separator(';'))?; - None } else { - return Err(Error::UnknownIdent(ident)); + let (function, arguments) = self + .parse_local_function_call(lexer, ident, context.as_expression())? + .ok_or(Error::UnknownLocalFunction(ident))?; + lexer.expect(Token::Separator(';'))?; + Some(crate::Statement::Call { + function, + arguments, + }) } } }; diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 2bb6707f1..72238dc1a 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -85,6 +85,14 @@ fn parse_statement() { ", ) .unwrap(); + + parse_str( + " + fn foo() {} + fn bar() { foo(); } + ", + ) + .unwrap(); } #[test] diff --git a/tests/snapshots/in/collatz.wgsl b/tests/snapshots/in/collatz.wgsl index 2433f3243..6edf54f96 100644 --- a/tests/snapshots/in/collatz.wgsl +++ b/tests/snapshots/in/collatz.wgsl @@ -15,7 +15,7 @@ var v_indices: [[access(read_write)]] PrimeIndices; // And repeat this process for each new n, you will always eventually reach 1. // Though the conjecture has not been proven, no counterexample has ever been found. // This function returns how many times this recurrence needs to be applied to reach 1. -fn collatz_iterations(n_base: u32) -> u32{ +fn collatz_iterations(n_base: u32) -> u32 { var n: u32 = n_base; var i: u32 = 0u; loop { From d0c84a5ffac3b2d4d3fe1101864006f0bbc17d50 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 6 Feb 2021 02:20:54 -0500 Subject: [PATCH 0442/2212] [spv-in] support for void function calls --- src/arena.rs | 10 +++ src/front/spv/function.rs | 39 ++++----- src/front/spv/mod.rs | 161 +++++++++++++++++++++++--------------- src/lib.rs | 2 +- 4 files changed, 125 insertions(+), 87 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 0f673fa68..347dfe206 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -126,6 +126,16 @@ impl Arena { }) } + /// Returns a iterator over the items stored in this arena, + /// returning both the item's handle and a mutable reference to it. + pub fn iter_mut(&mut self) -> impl DoubleEndedIterator, &mut T)> { + self.data.iter_mut().enumerate().map(|(i, v)| { + let position = i + 1; + let index = unsafe { Index::new_unchecked(position as u32) }; + (Handle::new(index), v) + }) + } + /// Adds a new value to the arena, returning a typed handle. /// /// The value is not linked to any SPIR-V module. diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 654160b30..78e87f677 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -57,23 +57,23 @@ impl> super::Parser { ) -> Result<(), Error> { self.switch(ModuleState::Function, inst.op)?; inst.expect(5)?; - let result_type = self.next()?; + let result_type_id = self.next()?; let fun_id = self.next()?; let _fun_control = self.next()?; - let fun_type = self.next()?; + let fun_type_id = self.next()?; let mut fun = { - let ft = self.lookup_function_type.lookup(fun_type)?; - if ft.return_type_id != result_type { - return Err(Error::WrongFunctionResultType(result_type)); + let ft = self.lookup_function_type.lookup(fun_type_id)?; + if ft.return_type_id != result_type_id { + return Err(Error::WrongFunctionResultType(result_type_id)); } crate::Function { name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name), arguments: Vec::with_capacity(ft.parameter_type_ids.len()), - return_type: if self.lookup_void_type.contains(&result_type) { + return_type: if self.lookup_void_type == Some(result_type_id) { None } else { - Some(self.lookup_type.lookup(result_type)?.handle) + Some(self.lookup_type.lookup(result_type_id)?.handle) }, global_usage: Vec::new(), local_variables: Arena::new(), @@ -101,7 +101,7 @@ impl> super::Parser { if type_id != self .lookup_function_type - .lookup(fun_type)? + .lookup(fun_type_id)? .parameter_type_ids[i] { return Err(Error::WrongFunctionArgumentType(type_id)); @@ -116,7 +116,6 @@ impl> super::Parser { // Read body let mut flow_graph = FlowGraph::new(); - let base_deferred_call_index = self.deferred_function_calls.len(); // Scan the blocks and add them as nodes loop { @@ -156,39 +155,29 @@ impl> super::Parser { // done fun.fill_global_use(&module.global_variables); - let source = match self.lookup_entry_point.remove(&fun_id) { + let dump_suffix = match self.lookup_entry_point.remove(&fun_id) { Some(ep) => { + let dump_name = format!("flow.{:?}-{}.dot", ep.stage, ep.name); module.entry_points.insert( - (ep.stage, ep.name.clone()), + (ep.stage, ep.name), crate::EntryPoint { early_depth_test: ep.early_depth_test, workgroup_size: ep.workgroup_size, function: fun, }, ); - DeferredSource::EntryPoint(ep.stage, ep.name) + dump_name } None => { let handle = module.functions.append(fun); self.lookup_function.insert(fun_id, handle); - DeferredSource::Function(handle) + format!("flow.Fun-{}.dot", handle.index()) } }; - for dfc in self.deferred_function_calls[base_deferred_call_index..].iter_mut() { - dfc.source = source.clone(); - } - if let Some(ref prefix) = self.options.flow_graph_dump_prefix { let dump = flow_graph.to_graphviz().unwrap_or_default(); - let suffix = match source { - DeferredSource::Undefined => unreachable!(), - DeferredSource::EntryPoint(stage, ref name) => { - format!("flow.{:?}-{}.dot", stage, name) - } - DeferredSource::Function(handle) => format!("flow.Fun-{}.dot", handle.index()), - }; - let _ = std::fs::write(prefix.join(suffix), dump); + let _ = std::fs::write(prefix.join(dump_suffix), dump); } self.lookup_expression.clear(); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 783245cb3..0652af078 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -268,18 +268,6 @@ struct LookupSampledImage { image: Handle, sampler: Handle, } -#[derive(Clone, Debug)] -enum DeferredSource { - Undefined, - EntryPoint(crate::ShaderStage, String), - Function(Handle), -} -struct DeferredFunctionCall { - source: DeferredSource, - expr_handle: Handle, - dst_id: spirv::Word, - arguments: Vec>, -} #[derive(Clone, Debug)] pub struct Assignment { @@ -302,7 +290,7 @@ pub struct Parser { lookup_member_type_id: FastHashMap<(Handle, MemberIndex), spirv::Word>, handle_sampling: FastHashMap, SamplingFlags>, lookup_type: FastHashMap, - lookup_void_type: FastHashSet, + lookup_void_type: Option, lookup_storage_buffer_types: FastHashSet>, // Lookup for samplers and sampled images, storing flags on how they are used. lookup_constant: FastHashMap, @@ -312,7 +300,9 @@ pub struct Parser { lookup_function_type: FastHashMap, lookup_function: FastHashMap>, lookup_entry_point: FastHashMap, - deferred_function_calls: Vec, + //Note: the key here is fully artificial, has nothing to do with the module + deferred_function_calls: FastHashMap, spirv::Word>, + dummy_functions: Arena, options: Options, } @@ -328,7 +318,7 @@ impl> Parser { handle_sampling: FastHashMap::default(), lookup_member_type_id: FastHashMap::default(), lookup_type: FastHashMap::default(), - lookup_void_type: FastHashSet::default(), + lookup_void_type: None, lookup_storage_buffer_types: FastHashSet::default(), lookup_constant: FastHashMap::default(), lookup_variable: FastHashMap::default(), @@ -337,7 +327,8 @@ impl> Parser { lookup_function_type: FastHashMap::default(), lookup_function: FastHashMap::default(), lookup_entry_point: FastHashMap::default(), - deferred_function_calls: Vec::new(), + deferred_function_calls: FastHashMap::default(), + dummy_functions: Arena::new(), options: options.clone(), } } @@ -510,7 +501,7 @@ impl> Parser { const_arena: &Arena, global_arena: &Arena, ) -> Result { - let mut assignments = Vec::new(); + let mut block = Vec::new(); let mut phis = Vec::new(); let mut merge = None; let terminator = loop { @@ -782,8 +773,8 @@ impl> Parser { } let base_expr = self.lookup_expression.lookup(pointer_id)?; let value_expr = self.lookup_expression.lookup(value_id)?; - assignments.push(Assignment { - to: base_expr.handle, + block.push(crate::Statement::Store { + pointer: base_expr.handle, value: value_expr.handle, }); } @@ -1315,22 +1306,29 @@ impl> Parser { let arg_id = self.next()?; arguments.push(self.lookup_expression.lookup(arg_id)?.handle); } - // will be replaced by the actual expression - let expr = crate::Expression::FunctionArgument(!0); - let expr_handle = expressions.append(expr); - self.deferred_function_calls.push(DeferredFunctionCall { - source: DeferredSource::Undefined, - expr_handle, - dst_id: func_id, - arguments, - }); - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expr_handle, - type_id: result_type_id, - }, - ); + + // We just need an unique handle here, nothing more. + let function = self.dummy_functions.append(crate::Function::default()); + self.deferred_function_calls.insert(function, func_id); + + if self.lookup_void_type == Some(result_type_id) { + block.push(crate::Statement::Call { + function, + arguments, + }); + } else { + let expr_handle = expressions.append(crate::Expression::Call { + function, + arguments, + }); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expr_handle, + type_id: result_type_id, + }, + ); + } } Op::ExtInst => { use crate::MathFunction as Mf; @@ -1551,14 +1549,6 @@ impl> Parser { } }; - let mut block = Vec::new(); - for assignment in assignments.iter() { - block.push(crate::Statement::Store { - pointer: assignment.to, - value: assignment.value, - }); - } - Ok(ControlFlowNode { id: block_id, ty: None, @@ -1610,6 +1600,67 @@ impl> Parser { } } + fn patch_function_call_statements( + &self, + statements: &mut [crate::Statement], + ) -> Result<(), Error> { + use crate::Statement as S; + for statement in statements.iter_mut() { + match *statement { + S::Block(ref mut block) => { + self.patch_function_call_statements(block)?; + } + S::If { + condition: _, + ref mut accept, + ref mut reject, + } => { + self.patch_function_call_statements(accept)?; + self.patch_function_call_statements(reject)?; + } + S::Switch { + selector: _, + ref mut cases, + ref mut default, + } => { + for case in cases.iter_mut() { + self.patch_function_call_statements(&mut case.body)?; + } + self.patch_function_call_statements(default)?; + } + S::Loop { + ref mut body, + ref mut continuing, + } => { + self.patch_function_call_statements(body)?; + self.patch_function_call_statements(continuing)?; + } + S::Break | S::Continue | S::Return { .. } | S::Kill | S::Store { .. } => {} + S::Call { + ref mut function, .. + } => { + let fun_id = self.deferred_function_calls[function]; + *function = *self.lookup_function.lookup(fun_id)?; + } + } + } + Ok(()) + } + + fn patch_function_calls(&self, fun: &mut crate::Function) -> Result<(), Error> { + for (_, expr) in fun.expressions.iter_mut() { + if let crate::Expression::Call { + ref mut function, .. + } = *expr + { + let fun_id = self.deferred_function_calls[function]; + *function = *self.lookup_function.lookup(fun_id)?; + } + } + self.patch_function_call_statements(&mut fun.body)?; + Ok(()) + } + pub fn parse(mut self) -> Result { let mut module = { if self.next()? != spirv::MAGIC_NUMBER { @@ -1680,23 +1731,11 @@ impl> Parser { } } - for dfc in self.deferred_function_calls.drain(..) { - let dst_handle = *self.lookup_function.lookup(dfc.dst_id)?; - let fun = match dfc.source { - DeferredSource::Undefined => unreachable!(), - DeferredSource::Function(fun_handle) => module.functions.get_mut(fun_handle), - DeferredSource::EntryPoint(stage, name) => { - &mut module - .entry_points - .get_mut(&(stage, name)) - .unwrap() - .function - } - }; - *fun.expressions.get_mut(dfc.expr_handle) = crate::Expression::Call { - function: dst_handle, - arguments: dfc.arguments, - }; + for (_, func) in module.functions.iter_mut() { + self.patch_function_calls(func)?; + } + for (_, ep) in module.entry_points.iter_mut() { + self.patch_function_calls(&mut ep.function)?; } if !self.future_decor.is_empty() { @@ -1912,7 +1951,7 @@ impl> Parser { self.switch(ModuleState::Type, inst.op)?; inst.expect(2)?; let id = self.next()?; - self.lookup_void_type.insert(id); + self.lookup_void_type = Some(id); Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index 92058c903..abad73cb4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -821,7 +821,7 @@ pub struct FunctionArgument { } /// A function defined in the module. -#[derive(Debug)] +#[derive(Debug, Default)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct Function { From 251f800825497bd1617eec9df634958c4226d526 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 6 Feb 2021 02:29:26 -0500 Subject: [PATCH 0443/2212] Remove the typifier hack for void functions --- src/proc/typifier.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 615d94535..f5d766639 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -48,6 +48,8 @@ pub enum ResolveError { InvalidAccessIndex, #[error("Function {name} not defined")] FunctionNotDefined { name: String }, + #[error("Function without return type")] + FunctionReturnsVoid, #[error("Type is not found in the given immutable arena")] TypeNotFound, #[error("Incompatible operand: {op} {operand}")] @@ -466,13 +468,10 @@ impl Typifier { function, arguments: _, } => { - match ctx.functions[function].return_type { - Some(ty) => Resolution::Handle(ty), - // return a type that can't ever be returned... - // We don't have `void` in the IR, but we have to return something here. - // This is also not a place to validate anything. - None => Resolution::Value(crate::TypeInner::Sampler { comparison: false }), - } + let ty = ctx.functions[function] + .return_type + .ok_or(ResolveError::FunctionReturnsVoid)?; + Resolution::Handle(ty) } crate::Expression::ArrayLength(_) => Resolution::Value(crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, From e0005211a3051497b7eed2553e5ee09c5d7ba720 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 6 Feb 2021 18:37:26 +0000 Subject: [PATCH 0444/2212] Fix the way equality is handled in glsl --- src/back/glsl/mod.rs | 6 ++++- src/front/glsl/ast.rs | 47 +++++++++++++++++++++++++++++++++++-- src/front/glsl/functions.rs | 7 +++++- src/front/glsl/parser.rs | 4 ++-- 4 files changed, 58 insertions(+), 6 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index cfd53cf38..4762b7975 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1456,7 +1456,9 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } - // `Binary` we just write `left op right` + // `Binary` we just write `left op right`, except when dealing with + // comparison operations on vectors as they are implemented with + // builtin functions. // Once again we wrap everything in parantheses to avoid precedence issues Expression::Binary { op, left, right } => { // Holds `Some(function_name)` if the binary operation is @@ -1470,6 +1472,8 @@ impl<'a, W: Write> Writer<'a, W> { BinaryOperator::LessEqual => Some("lessThanEqual"), BinaryOperator::Greater => Some("greaterThan"), BinaryOperator::GreaterEqual => Some("greaterThanEqual"), + BinaryOperator::Equal => Some("equal"), + BinaryOperator::NotEqual => Some("notEqual"), _ => None, } } else { diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 7962f59b3..157e72c0b 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -2,8 +2,8 @@ use super::{constants::ConstantSolver, error::ErrorKind}; use crate::{ proc::{ResolveContext, Typifier}, Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, FunctionArgument, - GlobalVariable, Handle, Interpolation, LocalVariable, Module, ShaderStage, Statement, - StorageClass, Type, + GlobalVariable, Handle, Interpolation, LocalVariable, Module, RelationalFunction, ShaderStage, + Statement, StorageClass, Type, }; #[derive(Debug)] @@ -57,6 +57,49 @@ impl Program { })) } + /// Helper function to insert equality expressions, this handles the special + /// case of `vec1 == vec2` and `vec1 != vec2` since in the IR they are + /// represented as `all(equal(vec1, vec2))` and `any(notEqual(vec1, vec2))` + pub fn equality_expr( + &mut self, + equals: bool, + left: &ExpressionRule, + right: &ExpressionRule, + ) -> Result { + let left_is_vector = match self.resolve_type(left.expression)? { + crate::TypeInner::Vector { .. } => true, + _ => false, + }; + + let rigth_is_vector = match self.resolve_type(right.expression)? { + crate::TypeInner::Vector { .. } => true, + _ => false, + }; + + let (op, fun) = match equals { + true => (BinaryOperator::Equal, RelationalFunction::All), + false => (BinaryOperator::NotEqual, RelationalFunction::Any), + }; + + let expr = + ExpressionRule::from_expression(self.context.expressions.append(Expression::Binary { + op, + left: left.expression, + right: right.expression, + })); + + Ok(if left_is_vector && rigth_is_vector { + ExpressionRule::from_expression(self.context.expressions.append( + Expression::Relational { + fun, + argument: expr.expression, + }, + )) + } else { + expr + }) + } + pub fn resolve_type( &mut self, handle: Handle, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 3b6b880a9..7238cac12 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -146,7 +146,8 @@ impl Program { statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), }) } - "lessThan" | "greaterThan" => { + "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" + | "notEqual" => { if fc.args.len() != 2 { return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); } @@ -155,6 +156,10 @@ impl Program { op: match name.as_str() { "lessThan" => BinaryOperator::Less, "greaterThan" => BinaryOperator::Greater, + "lessThanEqual" => BinaryOperator::LessEqual, + "greaterThanEqual" => BinaryOperator::GreaterEqual, + "equal" => BinaryOperator::Equal, + "notEqual" => BinaryOperator::NotEqual, _ => unreachable!(), }, left: fc.args[0].expression, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b9c889cd7..dc48cea8b 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -367,10 +367,10 @@ pomelo! { } equality_expression ::= relational_expression; equality_expression ::= equality_expression(left) EqOp relational_expression(right) { - extra.binary_expr(BinaryOperator::Equal, &left, &right) + extra.equality_expr(true, &left, &right)? } equality_expression ::= equality_expression(left) NeOp relational_expression(right) { - extra.binary_expr(BinaryOperator::NotEqual, &left, &right) + extra.equality_expr(false, &left, &right)? } and_expression ::= equality_expression; and_expression ::= and_expression(left) Ampersand equality_expression(right) { From da8f9ecbb9a2dab21f20f967ece0366cb79bde4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 6 Feb 2021 18:47:42 +0000 Subject: [PATCH 0445/2212] Add support for more math functions in glsl-in --- src/front/glsl/functions.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 7238cac12..71ae619af 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -109,14 +109,16 @@ impl Program { statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), }) } - "pow" => { + "pow" | "dot" | "max" => { if fc.args.len() != 2 { - return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); + return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); } Ok(ExpressionRule { expression: self.context.expressions.append(Expression::Math { fun: match name.as_str() { "pow" => MathFunction::Pow, + "dot" => MathFunction::Dot, + "max" => MathFunction::Max, _ => unreachable!(), }, arg: fc.args[0].expression, From 708751a8053019cb737ec256dd143f10c4370db9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 6 Feb 2021 20:24:07 +0000 Subject: [PATCH 0446/2212] Add support for relational functions to glsl-in --- src/front/glsl/functions.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 71ae619af..1fe37ca1c 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,6 +1,7 @@ use crate::{ proc::{ensure_block_returns, Typifier}, - BinaryOperator, Block, Expression, Function, MathFunction, SampleLevel, TypeInner, + BinaryOperator, Block, Expression, Function, MathFunction, RelationalFunction, SampleLevel, + TypeInner, }; use super::{ast::*, error::ErrorKind}; @@ -171,6 +172,10 @@ impl Program { statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), }) } + "isinf" => self.parse_relational_fun(name, fc.args, RelationalFunction::IsInf), + "isnan" => self.parse_relational_fun(name, fc.args, RelationalFunction::IsNan), + "all" => self.parse_relational_fun(name, fc.args, RelationalFunction::All), + "any" => self.parse_relational_fun(name, fc.args, RelationalFunction::Any), func_name => { let function = *self.lookup_function.get(func_name).ok_or_else(|| { ErrorKind::SemanticError( @@ -191,6 +196,25 @@ impl Program { } } + pub fn parse_relational_fun( + &mut self, + name: String, + args: Vec, + fun: RelationalFunction, + ) -> Result { + if args.len() != 1 { + return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); + } + Ok(ExpressionRule { + expression: self.context.expressions.append(Expression::Relational { + fun, + argument: args[0].expression, + }), + sampler: None, + statements: args.into_iter().flat_map(|a| a.statements).collect(), + }) + } + pub fn add_function_prelude(&mut self) { for (var_handle, var) in self.module.global_variables.iter() { if let Some(name) = var.name.as_ref() { From 993521965db00c427b339d27d75b92964cf5ce69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 6 Feb 2021 22:15:25 +0000 Subject: [PATCH 0447/2212] Add support for unary ops to glsl --- src/front/glsl/ast.rs | 9 ++++++++- src/front/glsl/parser.rs | 28 ++++++++++++++++++++-------- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 157e72c0b..4ece1ce9e 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -3,7 +3,7 @@ use crate::{ proc::{ResolveContext, Typifier}, Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, RelationalFunction, ShaderStage, - Statement, StorageClass, Type, + Statement, StorageClass, Type, UnaryOperator, }; #[derive(Debug)] @@ -57,6 +57,13 @@ impl Program { })) } + pub fn unary_expr(&mut self, op: UnaryOperator, tgt: &ExpressionRule) -> ExpressionRule { + ExpressionRule::from_expression(self.context.expressions.append(Expression::Unary { + op, + expr: tgt.expression, + })) + } + /// Helper function to insert equality expressions, this handles the special /// case of `vec1 == vec2` and `vec1 != vec2` since in the IR they are /// represented as `all(equal(vec1, vec2))` and `any(notEqual(vec1, vec2))` diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index dc48cea8b..474a28832 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -8,7 +8,7 @@ pomelo! { Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, EntryPoint, Expression, Function, GlobalVariable, Handle, Interpolation, - LocalVariable, ScalarValue, + LocalVariable, ScalarValue, ScalarKind, Statement, StorageAccess, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, FunctionArgument }; @@ -319,15 +319,27 @@ pomelo! { //TODO return Err(ErrorKind::NotImplemented("--pre")) } - unary_expression ::= unary_operator unary_expression { - //TODO - return Err(ErrorKind::NotImplemented("unary_op")) + unary_expression ::= Plus unary_expression(tgt) { + tgt + } + unary_expression ::= Dash unary_expression(tgt) { + extra.unary_expr(UnaryOperator::Negate, &tgt) + } + unary_expression ::= Bang unary_expression(tgt) { + if let TypeInner::Scalar { kind: ScalarKind::Bool, .. } = extra.resolve_type(tgt.expression)? { + extra.unary_expr(UnaryOperator::Not, &tgt) + } else { + return Err(ErrorKind::SemanticError("Cannot apply '!' to non bool type".into())) + } + } + unary_expression ::= Tilde unary_expression(tgt) { + if extra.resolve_type(tgt.expression)?.scalar_kind() != Some(ScalarKind::Bool) { + extra.unary_expr(UnaryOperator::Not, &tgt) + } else { + return Err(ErrorKind::SemanticError("Cannot apply '~' to type".into())) + } } - unary_operator ::= Plus; - unary_operator ::= Dash; - unary_operator ::= Bang; - unary_operator ::= Tilde; multiplicative_expression ::= unary_expression; multiplicative_expression ::= multiplicative_expression(left) Star unary_expression(right) { extra.binary_expr(BinaryOperator::Multiply, &left, &right) From 75427cf95cba22554c1c9b5b05e77dd157c6c25e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 7 Feb 2021 01:02:05 -0500 Subject: [PATCH 0448/2212] [spv-in] handle matrix decorations --- src/front/spv/error.rs | 3 ++ src/front/spv/mod.rs | 63 +++++++++++++++++++++++++++++++++--------- 2 files changed, 53 insertions(+), 13 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index cc484ea47..05520a561 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -53,4 +53,7 @@ pub enum Error { InvalidTerminator, InvalidEdgeClassification, UnexpectedComparisonType(Handle), + // incomplete implementation error + UnsupportedRowMajorMatrix, + UnsupportedMatrixStride(spirv::Word), } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 0652af078..466554736 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -156,6 +156,12 @@ bitflags::bitflags! { } } +#[derive(Debug)] +enum Majority { + Column, + Row, +} + #[derive(Debug, Default)] struct Decoration { name: Option, @@ -166,6 +172,8 @@ struct Decoration { block: Option, offset: Option, array_stride: Option, + matrix_stride: Option, + matrix_major: Option, interpolation: Option, flags: DecorationFlags, } @@ -407,6 +415,10 @@ impl> Parser { inst.expect(base_words + 2)?; dec.array_stride = NonZeroU32::new(self.next()?); } + spirv::Decoration::MatrixStride => { + inst.expect(base_words + 2)?; + dec.matrix_stride = NonZeroU32::new(self.next()?); + } spirv::Decoration::NoPerspective => { dec.interpolation = Some(crate::Interpolation::Linear); } @@ -428,6 +440,12 @@ impl> Parser { spirv::Decoration::NonWritable => { dec.flags |= DecorationFlags::NON_WRITABLE; } + spirv::Decoration::ColMajor => { + dec.matrix_major = Some(Majority::Column); + } + spirv::Decoration::RowMajor => { + dec.matrix_major = Some(Majority::Row); + } other => { log::warn!("Unknown decoration {:?}", other); for _ in base_words + 1..inst.wc { @@ -2080,20 +2098,45 @@ impl> Parser { let id = self.next()?; let vector_type_id = self.next()?; let num_columns = self.next()?; + let decor = self.future_decor.remove(&id); + let vector_type_lookup = self.lookup_type.lookup(vector_type_id)?; let inner = match module.types[vector_type_lookup.handle].inner { - crate::TypeInner::Vector { size, width, .. } => crate::TypeInner::Matrix { - columns: map_vector_size(num_columns)?, - rows: size, - width, - }, + crate::TypeInner::Vector { size, width, .. } => { + if let Some(Decoration { + matrix_stride: Some(stride), + .. + }) = decor + { + if stride.get() != (size as u32) * (width as u32) { + return Err(Error::UnsupportedMatrixStride(stride.get())); + } + } + crate::TypeInner::Matrix { + columns: map_vector_size(num_columns)?, + rows: size, + width, + } + } _ => return Err(Error::InvalidInnerType(vector_type_id)), }; + + if let Some(Decoration { + matrix_major: Some(ref major), + .. + }) = decor + { + match *major { + Majority::Column => (), + Majority::Row => return Err(Error::UnsupportedRowMajorMatrix), + } + } + self.lookup_type.insert( id, LookupType { handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), + name: decor.and_then(|dec| dec.name), inner, }), base_id: Some(vector_type_id), @@ -2541,13 +2584,7 @@ impl> Parser { None }; let lookup_type = self.lookup_type.lookup(type_id)?; - let dec = match self.future_decor.remove(&id) { - Some(dec) => dec, - None => { - log::warn!("Missing decoration for global {:?}", id); - Decoration::default() - } - }; + let dec = self.future_decor.remove(&id).unwrap_or_default(); let class = { use spirv::StorageClass as Sc; From 960aabec20dd619b6f5c0025de96a11bae341f42 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 7 Feb 2021 02:10:57 -0500 Subject: [PATCH 0449/2212] [spv-in] Implement OpCompositeInsert --- src/front/spv/mod.rs | 95 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 87 insertions(+), 8 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 466554736..e1d90d5cb 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -509,6 +509,62 @@ impl> Parser { Ok(()) } + fn insert_composite( + &self, + root_expr: Handle, + root_type_id: spirv::Word, + object_expr: Handle, + selections: &[spirv::Word], + type_arena: &Arena, + expressions: &mut Arena, + ) -> Result, Error> { + let selection = match selections.first() { + Some(&index) => index, + None => return Ok(object_expr), + }; + let root_lookup = self.lookup_type.lookup(root_type_id)?; + let (count, child_type_id) = match type_arena[root_lookup.handle].inner { + crate::TypeInner::Struct { ref members, .. } => { + let child_type_id = *self + .lookup_member_type_id + .get(&(root_lookup.handle, selection)) + .ok_or(Error::InvalidAccess(root_expr))?; + (members.len(), child_type_id) + } + // crate::TypeInner::Array //TODO? + crate::TypeInner::Vector { size, .. } + | crate::TypeInner::Matrix { columns: size, .. } => { + let child_type_id = root_lookup + .base_id + .ok_or(Error::InvalidAccessType(root_type_id))?; + (size as usize, child_type_id) + } + _ => return Err(Error::InvalidAccessType(root_type_id)), + }; + + let mut components = Vec::with_capacity(count); + for index in 0..count as u32 { + let expr = expressions.append(crate::Expression::AccessIndex { + base: root_expr, + index, + }); + components.push(expr); + } + components[selection as usize] = self.insert_composite( + components[selection as usize], + child_type_id, + object_expr, + &selections[1..], + type_arena, + expressions, + )?; + + Ok(expressions.append(crate::Expression::Compose { + ty: root_lookup.handle, + components, + })) + } + #[allow(clippy::too_many_arguments)] fn next_block( &mut self, @@ -699,13 +755,7 @@ impl> Parser { let result_id = self.next()?; let base_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", base_id); - let mut lexp = { - let expr = self.lookup_expression.lookup(base_id)?; - LookupExpression { - handle: expr.handle, - type_id: expr.type_id, - } - }; + let mut lexp = self.lookup_expression.lookup(base_id)?.clone(); for _ in 4..inst.wc { let index = self.next()?; log::trace!("\t\t\tlooking up type {:?}", lexp.type_id); @@ -739,7 +789,36 @@ impl> Parser { }, ); } - //TODO: Op::CompositeInsert + Op::CompositeInsert => { + inst.expect_at_least(5)?; + let result_type_id = self.next()?; + let id = self.next()?; + let object_id = self.next()?; + let composite_id = self.next()?; + let mut selections = Vec::with_capacity(inst.wc as usize - 5); + for _ in 5..inst.wc { + selections.push(self.next()?); + } + + let object_lexp = self.lookup_expression.lookup(object_id)?.clone(); + let root_lexp = self.lookup_expression.lookup(composite_id)?.clone(); + let handle = self.insert_composite( + root_lexp.handle, + result_type_id, + object_lexp.handle, + &selections, + type_arena, + expressions, + )?; + + self.lookup_expression.insert( + id, + LookupExpression { + handle, + type_id: result_type_id, + }, + ); + } Op::CompositeConstruct => { inst.expect_at_least(3)?; let result_type_id = self.next()?; From 6f50ca6bee3b021ef8ea210e2661f9a2e8fe2def Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 6 Feb 2021 21:02:49 -0500 Subject: [PATCH 0450/2212] Push constant support --- src/front/glsl/ast.rs | 6 ++ src/front/glsl/parser.rs | 13 +++- src/front/wgsl/conv.rs | 1 + src/proc/validator.rs | 6 +- tests/snapshots.rs | 6 ++ tests/snapshots/in/texture-array.param.ron | 9 +++ tests/snapshots/in/texture-array.wgsl | 21 ++++++ .../snapshots__texture-array.spvasm.snap | 75 +++++++++++++++++++ 8 files changed, 128 insertions(+), 9 deletions(-) create mode 100644 tests/snapshots/in/texture-array.param.ron create mode 100644 tests/snapshots/in/texture-array.wgsl create mode 100644 tests/snapshots/snapshots__texture-array.spvasm.snap diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 4ece1ce9e..8b9144430 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -252,3 +252,9 @@ pub enum StorageQualifier { StorageClass(StorageClass), Const, } + +#[derive(Debug, Clone)] +pub enum StructLayout { + Binding(Binding), + PushConstant, +} diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 474a28832..1cf4150d0 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -109,7 +109,7 @@ pomelo! { %type declaration Option; %type init_declarator_list VarDeclaration; %type single_declaration VarDeclaration; - %type layout_qualifier Binding; + %type layout_qualifier StructLayout; %type layout_qualifier_id_list Vec<(String, u32)>; %type layout_qualifier_id (String, u32); %type type_qualifier Vec; @@ -600,14 +600,16 @@ pomelo! { layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen { if let Some(&(_, loc)) = l.iter().find(|&q| q.0.as_str() == "location") { - Binding::Location(loc) + StructLayout::Binding(Binding::Location(loc)) } else if let Some(&(_, binding)) = l.iter().find(|&q| q.0.as_str() == "binding") { let group = if let Some(&(_, set)) = l.iter().find(|&q| q.0.as_str() == "set") { set } else { 0 }; - Binding::Resource{ group, binding } + StructLayout::Binding(Binding::Resource{ group, binding }) + } else if l.iter().any(|q| q.0.as_str() == "push_constant") { + StructLayout::PushConstant } else { return Err(ErrorKind::NotImplemented("unsupported layout qualifier(s)")); } @@ -642,7 +644,10 @@ pomelo! { TypeQualifier::StorageQualifier(s) } single_type_qualifier ::= layout_qualifier(l) { - TypeQualifier::Binding(l) + match l { + StructLayout::Binding(b) => TypeQualifier::Binding(b), + StructLayout::PushConstant => TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(StorageClass::PushConstant)), + } } // single_type_qualifier ::= precision_qualifier; single_type_qualifier ::= interpolation_qualifier(i) { diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 8aa0d5238..c15968484 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -7,6 +7,7 @@ pub fn map_storage_class(word: &str) -> Result> { "private" => Ok(crate::StorageClass::Private), "uniform" => Ok(crate::StorageClass::Uniform), "storage" => Ok(crate::StorageClass::Storage), + "push_constant" => Ok(crate::StorageClass::PushConstant), _ => Err(Error::UnknownStorageClass(word)), } } diff --git a/src/proc/validator.rs b/src/proc/validator.rs index f31606f40..b41972955 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -465,11 +465,7 @@ impl Validator { (crate::StorageAccess::empty(), TypeFlags::empty()) } crate::StorageClass::PushConstant => { - //TODO - return Err(GlobalVariableError::InvalidStorageAccess { - allowed: crate::StorageAccess::empty(), - seen: crate::StorageAccess::empty(), - }); + (crate::StorageAccess::LOAD, TypeFlags::HOST_SHARED) } }; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b366c5fc5..f0c995748 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -188,3 +188,9 @@ fn convert_wgsl_collatz() { fn convert_wgsl_shadow() { convert_wgsl("shadow", Language::METAL | Language::SPIRV); } + +#[cfg(feature = "wgsl-in")] +#[test] +fn convert_wgsl_texture_array() { + convert_wgsl("texture-array", Language::SPIRV); +} diff --git a/tests/snapshots/in/texture-array.param.ron b/tests/snapshots/in/texture-array.param.ron new file mode 100644 index 000000000..21435d3ae --- /dev/null +++ b/tests/snapshots/in/texture-array.param.ron @@ -0,0 +1,9 @@ +( + spv_flow_dump_prefix: "", + spv_capabilities: [ Shader ], + mtl_bindings: { + (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), + (stage: Fragment, group: 0, binding: 1): (texture: Some(1)), + (stage: Fragment, group: 0, binding: 2): (sampler: Some(0)), + } +) diff --git a/tests/snapshots/in/texture-array.wgsl b/tests/snapshots/in/texture-array.wgsl new file mode 100644 index 000000000..629a7c75f --- /dev/null +++ b/tests/snapshots/in/texture-array.wgsl @@ -0,0 +1,21 @@ +[[location(0)]] var tex_coord: vec2; +[[group(0), binding(0)]] var texture0: texture_2d; +[[group(0), binding(1)]] var texture1: texture_2d; +[[group(0), binding(2)]] var sampler: sampler; + +[[block]] +struct PushConstants { + index: u32; +}; +var pc: PushConstants; + +[[location(1)]] var color: vec4; + +[[stage(fragment)]] +fn main() { + if (pc.index == 0) { + color = textureSample(texture0, sampler, tex_coord); + } else { + color = textureSample(texture1, sampler, tex_coord); + } +} diff --git a/tests/snapshots/snapshots__texture-array.spvasm.snap b/tests/snapshots/snapshots__texture-array.spvasm.snap new file mode 100644 index 000000000..1108add38 --- /dev/null +++ b/tests/snapshots/snapshots__texture-array.spvasm.snap @@ -0,0 +1,75 @@ +--- +source: tests/snapshots.rs +expression: dis +--- +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 46 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %5 "main" %35 %23 +OpExecutionMode %5 OriginUpperLeft +OpDecorate %12 Block +OpMemberDecorate %12 0 Offset 0 +OpDecorate %23 Location 1 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 0 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 2 +OpDecorate %35 Location 0 +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 1 +%0 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 0 +%6 = OpTypeFunction %0 +%8 = OpTypeBool +%10 = OpTypeInt 32 0 +%12 = OpTypeStruct %10 +%14 = OpTypePointer PushConstant %12 +%13 = OpVariable %14 PushConstant +%15 = OpTypePointer PushConstant %10 +%16 = OpConstant %4 0 +%22 = OpTypeFloat 32 +%21 = OpTypeVector %22 4 +%24 = OpTypePointer Output %21 +%23 = OpVariable %24 Output +%25 = OpTypeImage %22 2D 0 0 0 1 Unknown +%27 = OpTypePointer UniformConstant %25 +%26 = OpVariable %27 UniformConstant +%29 = OpTypeSampledImage %25 +%30 = OpTypeSampler +%32 = OpTypePointer UniformConstant %30 +%31 = OpVariable %32 UniformConstant +%34 = OpTypeVector %22 2 +%36 = OpTypePointer Input %34 +%35 = OpVariable %36 Input +%40 = OpVariable %27 UniformConstant +%5 = OpFunction %0 None %6 +%7 = OpLabel +%11 = OpAccessChain %15 %13 %16 +%17 = OpLoad %10 %11 +%9 = OpIEqual %8 %17 %3 +OpSelectionMerge %18 None +OpBranchConditional %9 %19 %20 +%19 = OpLabel +%28 = OpLoad %25 %26 +%33 = OpLoad %30 %31 +%37 = OpLoad %34 %35 +%38 = OpSampledImage %29 %28 %33 +%39 = OpImageSampleImplicitLod %21 %38 %37 +OpStore %23 %39 +OpReturn +%20 = OpLabel +%41 = OpLoad %25 %40 +%42 = OpLoad %30 %31 +%43 = OpLoad %34 %35 +%44 = OpSampledImage %29 %41 %42 +%45 = OpImageSampleImplicitLod %21 %44 %43 +OpStore %23 %45 +OpReturn +%18 = OpLabel +OpReturn +OpFunctionEnd From 31be7099f204cc7b62e1ae581cd849f1f8edb0b1 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Sun, 7 Feb 2021 19:31:58 -0330 Subject: [PATCH 0451/2212] Move snapshot inputs and outputs around --- tests/{snapshots => }/in/boids.param.ron | 0 tests/{snapshots => }/in/boids.wgsl | 0 tests/{snapshots => }/in/collatz.param.ron | 0 tests/{snapshots => }/in/collatz.wgsl | 0 tests/{snapshots => }/in/empty.param.ron | 0 tests/{snapshots => }/in/empty.wgsl | 0 tests/{snapshots => }/in/quad.param.ron | 0 tests/{snapshots => }/in/quad.wgsl | 0 tests/{snapshots => }/in/shadow.param.ron | 0 tests/{snapshots => }/in/shadow.wgsl | 0 tests/{snapshots => }/in/skybox.param.ron | 0 tests/{snapshots => }/in/skybox.wgsl | 0 .../in/texture-array.param.ron | 0 tests/{snapshots => }/in/texture-array.wgsl | 0 .../boids.msl.snap} | 0 .../boids.spvasm.snap} | 0 .../collatz.msl.snap} | 0 .../collatz.spvasm.snap} | 0 .../empty-Compute.glsl.snap} | 0 .../empty.msl.snap} | 0 .../empty.spvasm.snap} | 0 .../quad-Fragment.glsl.snap} | 0 .../quad-Vertex.glsl.snap} | 0 .../quad.msl.snap} | 0 .../quad.spvasm.snap} | 0 .../shadow.msl.snap} | 0 .../shadow.spvasm.snap} | 0 .../skybox-Fragment.glsl.snap} | 0 .../skybox-Vertex.glsl.snap} | 0 .../skybox.msl.snap} | 0 .../skybox.spvasm.snap} | 0 .../texture-array.spvasm.snap} | 0 tests/snapshots.rs | 25 +++++++++++++++---- 33 files changed, 20 insertions(+), 5 deletions(-) rename tests/{snapshots => }/in/boids.param.ron (100%) rename tests/{snapshots => }/in/boids.wgsl (100%) rename tests/{snapshots => }/in/collatz.param.ron (100%) rename tests/{snapshots => }/in/collatz.wgsl (100%) rename tests/{snapshots => }/in/empty.param.ron (100%) rename tests/{snapshots => }/in/empty.wgsl (100%) rename tests/{snapshots => }/in/quad.param.ron (100%) rename tests/{snapshots => }/in/quad.wgsl (100%) rename tests/{snapshots => }/in/shadow.param.ron (100%) rename tests/{snapshots => }/in/shadow.wgsl (100%) rename tests/{snapshots => }/in/skybox.param.ron (100%) rename tests/{snapshots => }/in/skybox.wgsl (100%) rename tests/{snapshots => }/in/texture-array.param.ron (100%) rename tests/{snapshots => }/in/texture-array.wgsl (100%) rename tests/{snapshots/snapshots__boids.msl.snap => out/boids.msl.snap} (100%) rename tests/{snapshots/snapshots__boids.spvasm.snap => out/boids.spvasm.snap} (100%) rename tests/{snapshots/snapshots__collatz.msl.snap => out/collatz.msl.snap} (100%) rename tests/{snapshots/snapshots__collatz.spvasm.snap => out/collatz.spvasm.snap} (100%) rename tests/{snapshots/snapshots__empty-Compute.glsl.snap => out/empty-Compute.glsl.snap} (100%) rename tests/{snapshots/snapshots__empty.msl.snap => out/empty.msl.snap} (100%) rename tests/{snapshots/snapshots__empty.spvasm.snap => out/empty.spvasm.snap} (100%) rename tests/{snapshots/snapshots__quad-Fragment.glsl.snap => out/quad-Fragment.glsl.snap} (100%) rename tests/{snapshots/snapshots__quad-Vertex.glsl.snap => out/quad-Vertex.glsl.snap} (100%) rename tests/{snapshots/snapshots__quad.msl.snap => out/quad.msl.snap} (100%) rename tests/{snapshots/snapshots__quad.spvasm.snap => out/quad.spvasm.snap} (100%) rename tests/{snapshots/snapshots__shadow.msl.snap => out/shadow.msl.snap} (100%) rename tests/{snapshots/snapshots__shadow.spvasm.snap => out/shadow.spvasm.snap} (100%) rename tests/{snapshots/snapshots__skybox-Fragment.glsl.snap => out/skybox-Fragment.glsl.snap} (100%) rename tests/{snapshots/snapshots__skybox-Vertex.glsl.snap => out/skybox-Vertex.glsl.snap} (100%) rename tests/{snapshots/snapshots__skybox.msl.snap => out/skybox.msl.snap} (100%) rename tests/{snapshots/snapshots__skybox.spvasm.snap => out/skybox.spvasm.snap} (100%) rename tests/{snapshots/snapshots__texture-array.spvasm.snap => out/texture-array.spvasm.snap} (100%) diff --git a/tests/snapshots/in/boids.param.ron b/tests/in/boids.param.ron similarity index 100% rename from tests/snapshots/in/boids.param.ron rename to tests/in/boids.param.ron diff --git a/tests/snapshots/in/boids.wgsl b/tests/in/boids.wgsl similarity index 100% rename from tests/snapshots/in/boids.wgsl rename to tests/in/boids.wgsl diff --git a/tests/snapshots/in/collatz.param.ron b/tests/in/collatz.param.ron similarity index 100% rename from tests/snapshots/in/collatz.param.ron rename to tests/in/collatz.param.ron diff --git a/tests/snapshots/in/collatz.wgsl b/tests/in/collatz.wgsl similarity index 100% rename from tests/snapshots/in/collatz.wgsl rename to tests/in/collatz.wgsl diff --git a/tests/snapshots/in/empty.param.ron b/tests/in/empty.param.ron similarity index 100% rename from tests/snapshots/in/empty.param.ron rename to tests/in/empty.param.ron diff --git a/tests/snapshots/in/empty.wgsl b/tests/in/empty.wgsl similarity index 100% rename from tests/snapshots/in/empty.wgsl rename to tests/in/empty.wgsl diff --git a/tests/snapshots/in/quad.param.ron b/tests/in/quad.param.ron similarity index 100% rename from tests/snapshots/in/quad.param.ron rename to tests/in/quad.param.ron diff --git a/tests/snapshots/in/quad.wgsl b/tests/in/quad.wgsl similarity index 100% rename from tests/snapshots/in/quad.wgsl rename to tests/in/quad.wgsl diff --git a/tests/snapshots/in/shadow.param.ron b/tests/in/shadow.param.ron similarity index 100% rename from tests/snapshots/in/shadow.param.ron rename to tests/in/shadow.param.ron diff --git a/tests/snapshots/in/shadow.wgsl b/tests/in/shadow.wgsl similarity index 100% rename from tests/snapshots/in/shadow.wgsl rename to tests/in/shadow.wgsl diff --git a/tests/snapshots/in/skybox.param.ron b/tests/in/skybox.param.ron similarity index 100% rename from tests/snapshots/in/skybox.param.ron rename to tests/in/skybox.param.ron diff --git a/tests/snapshots/in/skybox.wgsl b/tests/in/skybox.wgsl similarity index 100% rename from tests/snapshots/in/skybox.wgsl rename to tests/in/skybox.wgsl diff --git a/tests/snapshots/in/texture-array.param.ron b/tests/in/texture-array.param.ron similarity index 100% rename from tests/snapshots/in/texture-array.param.ron rename to tests/in/texture-array.param.ron diff --git a/tests/snapshots/in/texture-array.wgsl b/tests/in/texture-array.wgsl similarity index 100% rename from tests/snapshots/in/texture-array.wgsl rename to tests/in/texture-array.wgsl diff --git a/tests/snapshots/snapshots__boids.msl.snap b/tests/out/boids.msl.snap similarity index 100% rename from tests/snapshots/snapshots__boids.msl.snap rename to tests/out/boids.msl.snap diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/out/boids.spvasm.snap similarity index 100% rename from tests/snapshots/snapshots__boids.spvasm.snap rename to tests/out/boids.spvasm.snap diff --git a/tests/snapshots/snapshots__collatz.msl.snap b/tests/out/collatz.msl.snap similarity index 100% rename from tests/snapshots/snapshots__collatz.msl.snap rename to tests/out/collatz.msl.snap diff --git a/tests/snapshots/snapshots__collatz.spvasm.snap b/tests/out/collatz.spvasm.snap similarity index 100% rename from tests/snapshots/snapshots__collatz.spvasm.snap rename to tests/out/collatz.spvasm.snap diff --git a/tests/snapshots/snapshots__empty-Compute.glsl.snap b/tests/out/empty-Compute.glsl.snap similarity index 100% rename from tests/snapshots/snapshots__empty-Compute.glsl.snap rename to tests/out/empty-Compute.glsl.snap diff --git a/tests/snapshots/snapshots__empty.msl.snap b/tests/out/empty.msl.snap similarity index 100% rename from tests/snapshots/snapshots__empty.msl.snap rename to tests/out/empty.msl.snap diff --git a/tests/snapshots/snapshots__empty.spvasm.snap b/tests/out/empty.spvasm.snap similarity index 100% rename from tests/snapshots/snapshots__empty.spvasm.snap rename to tests/out/empty.spvasm.snap diff --git a/tests/snapshots/snapshots__quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap similarity index 100% rename from tests/snapshots/snapshots__quad-Fragment.glsl.snap rename to tests/out/quad-Fragment.glsl.snap diff --git a/tests/snapshots/snapshots__quad-Vertex.glsl.snap b/tests/out/quad-Vertex.glsl.snap similarity index 100% rename from tests/snapshots/snapshots__quad-Vertex.glsl.snap rename to tests/out/quad-Vertex.glsl.snap diff --git a/tests/snapshots/snapshots__quad.msl.snap b/tests/out/quad.msl.snap similarity index 100% rename from tests/snapshots/snapshots__quad.msl.snap rename to tests/out/quad.msl.snap diff --git a/tests/snapshots/snapshots__quad.spvasm.snap b/tests/out/quad.spvasm.snap similarity index 100% rename from tests/snapshots/snapshots__quad.spvasm.snap rename to tests/out/quad.spvasm.snap diff --git a/tests/snapshots/snapshots__shadow.msl.snap b/tests/out/shadow.msl.snap similarity index 100% rename from tests/snapshots/snapshots__shadow.msl.snap rename to tests/out/shadow.msl.snap diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/out/shadow.spvasm.snap similarity index 100% rename from tests/snapshots/snapshots__shadow.spvasm.snap rename to tests/out/shadow.spvasm.snap diff --git a/tests/snapshots/snapshots__skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap similarity index 100% rename from tests/snapshots/snapshots__skybox-Fragment.glsl.snap rename to tests/out/skybox-Fragment.glsl.snap diff --git a/tests/snapshots/snapshots__skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap similarity index 100% rename from tests/snapshots/snapshots__skybox-Vertex.glsl.snap rename to tests/out/skybox-Vertex.glsl.snap diff --git a/tests/snapshots/snapshots__skybox.msl.snap b/tests/out/skybox.msl.snap similarity index 100% rename from tests/snapshots/snapshots__skybox.msl.snap rename to tests/out/skybox.msl.snap diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/out/skybox.spvasm.snap similarity index 100% rename from tests/snapshots/snapshots__skybox.spvasm.snap rename to tests/out/skybox.spvasm.snap diff --git a/tests/snapshots/snapshots__texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap similarity index 100% rename from tests/snapshots/snapshots__texture-array.spvasm.snap rename to tests/out/texture-array.spvasm.snap diff --git a/tests/snapshots.rs b/tests/snapshots.rs index f0c995748..913797e79 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -47,6 +47,13 @@ struct Parameters { mtl_bindings: naga::FastHashMap, } +fn with_snapshot_settings ()>(snapshot_assertion: F) { + let mut settings = insta::Settings::new(); + settings.set_snapshot_path("out"); + settings.set_prepend_module_to_snapshot(false); + settings.bind(|| snapshot_assertion()); +} + #[cfg(feature = "spv-out")] fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { use naga::back::spv; @@ -62,7 +69,9 @@ fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { let dis = rspirv::dr::load_words(spv) .expect("Produced invalid SPIR-V") .disassemble(); - insta::assert_snapshot!(format!("{}.spvasm", name), dis); + with_snapshot_settings(|| { + insta::assert_snapshot!(format!("{}.spvasm", name), dis); + }); } #[cfg(feature = "msl-out")] @@ -96,7 +105,10 @@ fn check_output_msl(module: &naga::Module, name: &str, params: &Parameters) { }; let (msl, _) = msl::write_string(&module, &options).unwrap(); - insta::assert_snapshot!(format!("{}.msl", name), msl); + + with_snapshot_settings(|| { + insta::assert_snapshot!(format!("{}.msl", name), msl); + }); } #[cfg(feature = "glsl-out")] @@ -113,19 +125,22 @@ fn check_output_glsl(module: &naga::Module, name: &str, stage: naga::ShaderStage writer.write().unwrap(); let string = String::from_utf8(buffer).unwrap(); - insta::assert_snapshot!(format!("{}-{:?}.glsl", name, stage), string); + + with_snapshot_settings(|| { + insta::assert_snapshot!(format!("{}-{:?}.glsl", name, stage), string); + }); } #[cfg(feature = "wgsl-in")] fn convert_wgsl(name: &str, language: Language) { let params = - match std::fs::read_to_string(format!("tests/snapshots/in/{}{}", name, ".param.ron")) { + match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), }; let module = naga::front::wgsl::parse_str( - &std::fs::read_to_string(format!("tests/snapshots/in/{}{}", name, ".wgsl")) + &std::fs::read_to_string(format!("tests/in/{}{}", name, ".wgsl")) .expect("Couldn't find wgsl file"), ) .unwrap(); From 832e259a036651dd37ffca08072d7e8f17ea1fba Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Sun, 7 Feb 2021 19:41:35 -0330 Subject: [PATCH 0452/2212] Ues updated paths in Makefile --- Makefile | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/Makefile b/Makefile index f5d6b08b4..294ab4f1e 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,14 @@ .PHONY: all clean validate-spv validate-msl .SECONDARY: boids.metal quad.metal -SNAPSHOTS=tests/snapshots +SNAPSHOTS_IN=tests/in +SNAPSHOTS_OUT=tests/out all: clean: rm *.metal *.air *.metallib *.vert *.frag *.comp *.spv -%.metal: $(SNAPSHOTS)/in/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) +%.metal: $(SNAPSHOTS_IN)/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) cargo run --example convert --features wgsl-in,msl-out -- $< $@ %.air: %.metal @@ -24,28 +25,28 @@ clean: cargo run --example convert --features wgsl-in,glsl-out -- $< $@ glslangValidator $@ -validate-spv: $(SNAPSHOTS)/*.spvasm.snap +validate-spv: $(SNAPSHOTS_OUT)/*.spvasm.snap @for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ tail -n +5 $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ done -validate-msl: $(SNAPSHOTS)/*.msl.snap +validate-msl: $(SNAPSHOTS_OUT)/*.msl.snap @for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ tail -n +5 $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ done -validate-glsl: $(SNAPSHOTS)/*.glsl.snap - @for file in $(SNAPSHOTS)/*-Vertex.glsl.snap ; do \ - echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"};\ +validate-glsl: $(SNAPSHOTS_OUT)/*.glsl.snap + @for file in $(SNAPSHOTS_OUT)/*-Vertex.glsl.snap ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ tail -n +5 $${file} | glslangValidator --stdin -S vert; \ done - @for file in $(SNAPSHOTS)/*-Fragment.glsl.snap ; do \ - echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"};\ + @for file in $(SNAPSHOTS_OUT)/*-Fragment.glsl.snap ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ tail -n +5 $${file} | glslangValidator --stdin -S frag; \ done - @for file in $(SNAPSHOTS)/*-Compute.glsl.snap ; do \ - echo "Validating" $${file#"$(SNAPSHOTS)/snapshots__"};\ + @for file in $(SNAPSHOTS_OUT)/*-Compute.glsl.snap ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ tail -n +5 $${file} | glslangValidator --stdin -S comp; \ done From 76094aa55393f45b3bac155c09170b32f52ae152 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 8 Feb 2021 00:08:28 -0500 Subject: [PATCH 0453/2212] [mtl] fix nested loop service variable --- src/back/msl/writer.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 76861c38c..75f814b20 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -699,10 +699,10 @@ impl Writer { writeln!(self.out, "{}bool {} = true;", level, gate_name)?; writeln!(self.out, "{}while(true) {{", level)?; let lif = level.next(); - writeln!(self.out, "{}if (!loop_init) {{", lif)?; + writeln!(self.out, "{}if (!{}) {{", lif, gate_name)?; self.put_block(lif.next(), continuing, context, return_value)?; writeln!(self.out, "{}}}", lif)?; - writeln!(self.out, "{}loop_init = false;", lif)?; + writeln!(self.out, "{}{} = false;", lif, gate_name)?; } else { writeln!(self.out, "{}while(true) {{", level)?; } From 680fda9e1ba26fee4b732addcd94e753765b03c3 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 7 Feb 2021 23:43:36 -0500 Subject: [PATCH 0454/2212] [spv-out] fix initial ID 0 and 1 assignments --- src/back/spv/writer.rs | 8 +++++--- tests/out/boids.spvasm.snap | 6 +++--- tests/out/collatz.spvasm.snap | 6 +++--- tests/out/empty.spvasm.snap | 6 +++--- tests/out/quad.spvasm.snap | 8 ++++---- tests/out/shadow.spvasm.snap | 6 +++--- tests/out/skybox.spvasm.snap | 8 ++++---- tests/out/texture-array.spvasm.snap | 6 +++--- 8 files changed, 28 insertions(+), 26 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 04f2b42c2..a0799106c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -206,22 +206,24 @@ impl Writer { flags: WriterFlags, capabilities: crate::FastHashSet, ) -> Self { + let gl450_ext_inst_id = 1; + let void_type = 2; Writer { physical_layout: PhysicalLayout::new(header), logical_layout: LogicalLayout::default(), - id_count: 2, // 0 is void type, 1 is the GLSL ext inst + id_count: 2, // see `gl450_ext_inst_id` and `void_type` capabilities, debugs: vec![], annotations: vec![], flags, - void_type: 0, + void_type, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), lookup_function_type: crate::FastHashMap::default(), lookup_constant: crate::FastHashMap::default(), lookup_global_variable: crate::FastHashMap::default(), struct_type_handles: crate::FastHashMap::default(), - gl450_ext_inst_id: 1, + gl450_ext_inst_id, layouter: Layouter::default(), typifier: Typifier::new(), } diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index f155d920a..fc28d8147 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -32,7 +32,7 @@ OpDecorate %122 DescriptorSet 0 OpDecorate %122 Binding 0 OpDecorate %274 DescriptorSet 0 OpDecorate %274 Binding 2 -%0 = OpTypeVoid +%2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1500 %6 = OpTypeFloat 32 @@ -49,7 +49,7 @@ OpDecorate %274 Binding 2 %17 = OpTypePointer Function %16 %23 = OpTypePointer Function %4 %28 = OpTypePointer Function %9 -%30 = OpTypeFunction %0 +%30 = OpTypeFunction %2 %32 = OpTypeBool %35 = OpTypeVector %9 3 %37 = OpTypePointer Input %35 @@ -135,7 +135,7 @@ OpDecorate %274 Binding 2 %294 = OpTypePointer Uniform %45 %295 = OpTypePointer Uniform %16 %296 = OpConstant %4 1 -%29 = OpFunction %0 None %30 +%29 = OpFunction %2 None %30 %31 = OpLabel %27 = OpVariable %28 Function %8 %24 = OpVariable %23 Function %7 diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index b21b66ef0..99f6590cf 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -17,7 +17,7 @@ OpMemberDecorate %45 0 Offset 0 OpDecorate %46 DescriptorSet 0 OpDecorate %46 Binding 0 OpDecorate %53 BuiltIn GlobalInvocationId -%0 = OpTypeVoid +%2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 %5 = OpConstant %4 1 @@ -26,7 +26,7 @@ OpDecorate %53 BuiltIn GlobalInvocationId %9 = OpTypePointer Function %4 %13 = OpTypeFunction %4 %4 %19 = OpTypeBool -%40 = OpTypeFunction %0 +%40 = OpTypeFunction %2 %43 = OpTypeRuntimeArray %4 %45 = OpTypeStruct %43 %47 = OpTypePointer Uniform %45 @@ -92,7 +92,7 @@ OpBranch %15 %38 = OpLoad %4 %10 OpReturnValue %38 OpFunctionEnd -%39 = OpFunction %0 None %40 +%39 = OpFunction %2 None %40 %41 = OpLabel %44 = OpAccessChain %48 %46 %50 %51 = OpAccessChain %55 %53 %56 diff --git a/tests/out/empty.spvasm.snap b/tests/out/empty.spvasm.snap index 00397cf4a..ae2b9628b 100644 --- a/tests/out/empty.spvasm.snap +++ b/tests/out/empty.spvasm.snap @@ -11,9 +11,9 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %3 "main" OpExecutionMode %3 LocalSize 1 1 1 -%0 = OpTypeVoid -%4 = OpTypeFunction %0 -%3 = OpFunction %0 None %4 +%2 = OpTypeVoid +%4 = OpTypeFunction %2 +%3 = OpFunction %2 None %4 %5 = OpLabel OpReturn OpFunctionEnd diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index a96d97cdd..0a0caa24a 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -22,12 +22,12 @@ OpDecorate %27 Binding 0 OpDecorate %32 DescriptorSet 0 OpDecorate %32 Binding 1 OpDecorate %35 Location 0 -%0 = OpTypeVoid +%2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.2 %5 = OpConstant %4 0.0 %6 = OpConstant %4 1.0 -%8 = OpTypeFunction %0 +%8 = OpTypeFunction %2 %10 = OpTypeVector %4 2 %12 = OpTypePointer Output %10 %11 = OpVariable %12 Output @@ -46,7 +46,7 @@ OpDecorate %35 Location 0 %33 = OpTypePointer UniformConstant %31 %32 = OpVariable %33 UniformConstant %35 = OpVariable %14 Input -%7 = OpFunction %0 None %8 +%7 = OpFunction %2 None %8 %9 = OpLabel %15 = OpLoad %10 %13 OpStore %11 %15 @@ -56,7 +56,7 @@ OpStore %11 %15 OpStore %17 %22 OpReturn OpFunctionEnd -%23 = OpFunction %0 None %8 +%23 = OpFunction %2 None %8 %24 = OpLabel %29 = OpLoad %26 %27 %34 = OpLoad %31 %32 diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index 4e19de6a5..97fdef6f7 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -33,7 +33,7 @@ OpDecorate %102 Binding 1 OpDecorate %111 Location 1 OpDecorate %114 Location 0 OpDecorate %217 Location 0 -%0 = OpTypeVoid +%2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 %5 = OpConstant %4 1.0 @@ -61,7 +61,7 @@ OpDecorate %217 Location 0 %59 = OpConstant %4 0.0 %61 = OpTypePointer Function %10 %63 = OpTypePointer Function %12 -%65 = OpTypeFunction %0 +%65 = OpTypeFunction %2 %74 = OpTypeVector %12 4 %76 = OpTypeStruct %74 %78 = OpTypePointer Uniform %76 @@ -173,7 +173,7 @@ OpBranch %24 %54 = OpImageSampleDrefExplicitLod %4 %53 %52 %55 Lod %59 OpReturnValue %54 OpFunctionEnd -%64 = OpFunction %0 None %65 +%64 = OpFunction %2 None %65 %66 = OpLabel %60 = OpVariable %61 Function %9 %62 = OpVariable %63 Function %13 diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index 76696763d..3733edaa1 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -30,7 +30,7 @@ OpDecorate %174 Binding 1 OpDecorate %179 DescriptorSet 0 OpDecorate %179 Binding 2 OpDecorate %182 Location 0 -%0 = OpTypeVoid +%2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 %5 = OpConstant %4 1 @@ -41,7 +41,7 @@ OpDecorate %182 Location 0 %11 = OpTypePointer Function %4 %14 = OpTypeVector %7 4 %15 = OpTypePointer Function %14 -%17 = OpTypeFunction %0 +%17 = OpTypeFunction %2 %20 = OpTypeInt 32 0 %22 = OpTypePointer Input %20 %21 = OpVariable %22 Input @@ -127,7 +127,7 @@ OpDecorate %182 Location 0 %179 = OpVariable %180 UniformConstant %183 = OpTypePointer Input %46 %182 = OpVariable %183 Input -%16 = OpFunction %0 None %17 +%16 = OpFunction %2 None %17 %18 = OpLabel %10 = OpVariable %11 Function %12 = OpVariable %11 Function @@ -215,7 +215,7 @@ OpStore %47 %49 OpStore %159 %169 OpReturn OpFunctionEnd -%170 = OpFunction %0 None %17 +%170 = OpFunction %2 None %17 %171 = OpLabel %176 = OpLoad %173 %174 %181 = OpLoad %178 %179 diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap index 1108add38..e83fab904 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm.snap @@ -21,10 +21,10 @@ OpDecorate %31 Binding 2 OpDecorate %35 Location 0 OpDecorate %40 DescriptorSet 0 OpDecorate %40 Binding 1 -%0 = OpTypeVoid +%2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 0 -%6 = OpTypeFunction %0 +%6 = OpTypeFunction %2 %8 = OpTypeBool %10 = OpTypeInt 32 0 %12 = OpTypeStruct %10 @@ -47,7 +47,7 @@ OpDecorate %40 Binding 1 %36 = OpTypePointer Input %34 %35 = OpVariable %36 Input %40 = OpVariable %27 UniformConstant -%5 = OpFunction %0 None %6 +%5 = OpFunction %2 None %6 %7 = OpLabel %11 = OpAccessChain %15 %13 %16 %17 = OpLoad %10 %11 From 10867879d44691dbc236720e91112d672abfefa5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 8 Feb 2021 02:06:42 -0500 Subject: [PATCH 0455/2212] [spv-in] support projection sampling and sampling from arrays --- src/front/spv/error.rs | 2 +- src/front/spv/mod.rs | 307 +++++++++++++++++++++++++++++++++-------- tests/snapshots.rs | 9 +- 3 files changed, 255 insertions(+), 63 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 05520a561..14e7d1cc3 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -40,8 +40,8 @@ pub enum Error { InvalidBinding(spirv::Word), InvalidImageExpression(Handle), InvalidImageBaseType(Handle), + InvalidSampleImage(Handle), InvalidSamplerExpression(Handle), - InvalidSampleSampler(Handle), InvalidDepthReference(Handle), InvalidAsType(Handle), InconsistentComparisonSampling(Handle), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e1d90d5cb..da6c20a06 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -565,6 +565,105 @@ impl> Parser { })) } + /// Return the texture coordinates separated from the array layer, + /// and/or divided by the projection term. + /// + /// The Proj sampling ops expect an extra coordinate for the W. + /// The arrayed (can't be Proj!) images expect an extra coordinate for the layer. + fn extract_image_coordinates( + image_dim: crate::ImageDimension, + image_arrayed: bool, + base: Handle, + coordinate_ty: Handle, + type_arena: &Arena, + expressions: &mut Arena, + ) -> (Handle, Option>) { + let (given_size, kind) = match type_arena[coordinate_ty].inner { + crate::TypeInner::Scalar { kind, .. } => (None, kind), + crate::TypeInner::Vector { size, kind, .. } => (Some(size), kind), + ref other => unreachable!("Unexpected texture coordinate {:?}", other), + }; + + let required_size = Self::required_coordinate_size(image_dim); + let required_ty = required_size.map(|size| { + type_arena + .fetch_if(|ty| { + ty.inner + == crate::TypeInner::Vector { + size, + kind, + width: 4, + } + }) + .expect("Required coordinate type should have been set up by `parse_type_image`!") + }); + let extra_expr = crate::Expression::AccessIndex { + base, + index: required_size.map_or(1, |size| size as u32), + }; + + if given_size == required_size { + // fast path, no complications + (base, None) + } else if image_arrayed { + // extra coordinate for the array index + let extracted = match required_size { + None => expressions.append(crate::Expression::AccessIndex { base, index: 0 }), + Some(size) => { + let mut components = Vec::with_capacity(size as usize); + for index in 0..size as u32 { + let comp = + expressions.append(crate::Expression::AccessIndex { base, index }); + components.push(comp); + } + expressions.append(crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }) + } + }; + let array_index_f32 = expressions.append(extra_expr); + let array_index = expressions.append(crate::Expression::As { + kind: crate::ScalarKind::Uint, + expr: array_index_f32, + convert: true, + }); + (extracted, Some(array_index)) + } else { + // extra coordinate for the projection W + let projection = expressions.append(extra_expr); + let divided = match required_size { + None => { + let temp = + expressions.append(crate::Expression::AccessIndex { base, index: 0 }); + expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: temp, + right: projection, + }) + } + Some(size) => { + let mut components = Vec::with_capacity(size as usize); + for index in 0..size as u32 { + let temp = + expressions.append(crate::Expression::AccessIndex { base, index }); + let comp = expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: temp, + right: projection, + }); + components.push(comp); + } + expressions.append(crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }) + } + }; + (divided, None) + } + } + #[allow(clippy::too_many_arguments)] fn next_block( &mut self, @@ -1019,14 +1118,6 @@ impl> Parser { let image_id = self.next()?; let coordinate_id = self.next()?; - let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); - let coord_lexp = self.lookup_expression.lookup(coordinate_id)?.clone(); - let image_type_handle = - reach_global_type(image_lexp.handle, &expressions, global_arena) - .ok_or(Error::InvalidImageExpression(image_lexp.handle))?; - *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= - SamplingFlags::REGULAR; - let mut index = None; let mut base_wc = 5; while base_wc < inst.wc { @@ -1056,10 +1147,33 @@ impl> Parser { } } + let image_lexp = self.lookup_expression.lookup(image_id)?; + let image_type_handle = + reach_global_type(image_lexp.handle, expressions, global_arena) + .ok_or(Error::InvalidImageExpression(image_lexp.handle))?; + + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + let (coordinate, array_index) = match type_arena[image_type_handle].inner { + crate::TypeInner::Image { + dim, + arrayed, + class: _, + } => Self::extract_image_coordinates( + dim, + arrayed, + coord_lexp.handle, + coord_type_handle, + type_arena, + expressions, + ), + _ => return Err(Error::InvalidSampleImage(image_type_handle)), + }; + let expr = crate::Expression::ImageLoad { image: image_lexp.handle, - coordinate: coord_lexp.handle, - array_index: None, //TODO: this will break + coordinate, + array_index, index, }; self.lookup_expression.insert( @@ -1070,38 +1184,18 @@ impl> Parser { }, ); } - Op::ImageSampleImplicitLod | Op::ImageSampleExplicitLod => { - inst.expect_at_least(5)?; + Op::ImageSampleImplicitLod + | Op::ImageSampleExplicitLod + | Op::ImageSampleProjImplicitLod + | Op::ImageSampleProjExplicitLod => { + let mut base_wc = 5; + inst.expect_at_least(base_wc)?; let result_type_id = self.next()?; let result_id = self.next()?; let sampled_image_id = self.next()?; let coordinate_id = self.next()?; - let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?.clone(); - let coord_lexp = self.lookup_expression.lookup(coordinate_id)?.clone(); - //let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - - let sampler_type_handle = - reach_global_type(si_lexp.sampler, &expressions, global_arena) - .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; - let image_type_handle = - reach_global_type(si_lexp.image, &expressions, global_arena) - .ok_or(Error::InvalidImageExpression(si_lexp.image))?; - log::debug!( - "\t\t\tImage {:?} with sampler {:?}", - image_type_handle, - sampler_type_handle - ); - *self.handle_sampling.get_mut(&sampler_type_handle).unwrap() |= - SamplingFlags::REGULAR; - *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= - SamplingFlags::REGULAR; - match type_arena[sampler_type_handle].inner { - crate::TypeInner::Sampler { comparison: false } => (), - _ => return Err(Error::InvalidSampleSampler(sampler_type_handle)), - }; let mut level = crate::SampleLevel::Auto; - let mut base_wc = 5; while base_wc < inst.wc { let image_ops = self.next()?; base_wc += 1; @@ -1128,15 +1222,48 @@ impl> Parser { } } - //TODO: disassemble `coordinate_id` into the part responsible for - // texture coordinates, and the array index. + let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + + let sampler_type_handle = + reach_global_type(si_lexp.sampler, expressions, global_arena) + .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; + let image_type_handle = + reach_global_type(si_lexp.image, expressions, global_arena) + .ok_or(Error::InvalidImageExpression(si_lexp.image))?; + log::debug!( + "\t\t\tImage {:?} with sampler {:?}", + image_type_handle, + sampler_type_handle + ); + *self.handle_sampling.get_mut(&sampler_type_handle).unwrap() |= + SamplingFlags::REGULAR; + *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= + SamplingFlags::REGULAR; + + let (coordinate, array_index) = match type_arena[image_type_handle].inner { + crate::TypeInner::Image { + dim, + arrayed, + class: _, + } => Self::extract_image_coordinates( + dim, + arrayed, + coord_lexp.handle, + coord_type_handle, + type_arena, + expressions, + ), + _ => return Err(Error::InvalidSampleImage(image_type_handle)), + }; let expr = crate::Expression::ImageSample { image: si_lexp.image, sampler: si_lexp.sampler, - coordinate: coord_lexp.handle, - array_index: None, //TODO - offset: None, //TODO + coordinate, + array_index, + offset: None, //TODO level, depth_ref: None, }; @@ -1148,31 +1275,58 @@ impl> Parser { }, ); } - Op::ImageSampleDrefImplicitLod => { - inst.expect_at_least(6)?; + Op::ImageSampleDrefImplicitLod + | Op::ImageSampleDrefExplicitLod + | Op::ImageSampleProjDrefImplicitLod + | Op::ImageSampleProjDrefExplicitLod => { + let mut base_wc = 6; + inst.expect_at_least(base_wc)?; let result_type_id = self.next()?; let result_id = self.next()?; let sampled_image_id = self.next()?; let coordinate_id = self.next()?; let dref_id = self.next()?; + let mut level = crate::SampleLevel::Auto; + while base_wc < inst.wc { + let image_ops = self.next()?; + base_wc += 1; + match spirv::ImageOperands::from_bits_truncate(image_ops) { + spirv::ImageOperands::BIAS => { + let bias_expr = self.next()?; + let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; + level = crate::SampleLevel::Bias(bias_handle); + base_wc += 1; + } + spirv::ImageOperands::LOD => { + let lod_expr = self.next()?; + let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; + level = crate::SampleLevel::Exact(lod_handle); + base_wc += 1; + } + other => { + log::warn!("Skipping {:?}", other); + for _ in base_wc..inst.wc { + self.next()?; + } + break; + } + } + } + let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - //let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; let sampler_type_handle = - reach_global_type(si_lexp.sampler, &expressions, global_arena) + reach_global_type(si_lexp.sampler, expressions, global_arena) .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; let image_type_handle = - reach_global_type(si_lexp.image, &expressions, global_arena) + reach_global_type(si_lexp.image, expressions, global_arena) .ok_or(Error::InvalidImageExpression(si_lexp.image))?; *self.handle_sampling.get_mut(&sampler_type_handle).unwrap() |= SamplingFlags::COMPARISON; *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= SamplingFlags::COMPARISON; - match type_arena[sampler_type_handle].inner { - crate::TypeInner::Sampler { comparison: true } => (), - _ => return Err(Error::InvalidSampleSampler(sampler_type_handle)), - }; let dref_lexp = self.lookup_expression.lookup(dref_id)?; let dref_type_handle = self.lookup_type.lookup(dref_lexp.type_id)?.handle; @@ -1184,13 +1338,29 @@ impl> Parser { _ => return Err(Error::InvalidDepthReference(dref_type_handle)), } + let (coordinate, array_index) = match type_arena[image_type_handle].inner { + crate::TypeInner::Image { + dim, + arrayed, + class: _, + } => Self::extract_image_coordinates( + dim, + arrayed, + coord_lexp.handle, + coord_type_handle, + type_arena, + expressions, + ), + _ => return Err(Error::InvalidSampleImage(image_type_handle)), + }; + let expr = crate::Expression::ImageSample { image: si_lexp.image, sampler: si_lexp.sampler, - coordinate: coord_lexp.handle, - array_index: None, //TODO - offset: None, //TODO - level: crate::SampleLevel::Auto, + coordinate, + array_index, + offset: None, //TODO + level, depth_ref: Some(dref_lexp.handle), }; self.lookup_expression.insert( @@ -2372,6 +2542,15 @@ impl> Parser { Ok(()) } + fn required_coordinate_size(dim: crate::ImageDimension) -> Option { + match dim { + crate::ImageDimension::D1 => None, + crate::ImageDimension::D2 => Some(crate::VectorSize::Bi), + crate::ImageDimension::D3 => Some(crate::VectorSize::Tri), + crate::ImageDimension::Cube => Some(crate::VectorSize::Tri), + } + } + fn parse_type_image( &mut self, inst: Instruction, @@ -2389,6 +2568,22 @@ impl> Parser { let _is_sampled = self.next()?; let format = self.next()?; + let dim = map_image_dim(dim)?; + let decor = self.future_decor.remove(&id).unwrap_or_default(); + + // ensure there is a type for texture coordinate without extra components + module.types.fetch_or_append(crate::Type { + name: None, + inner: { + let kind = crate::ScalarKind::Float; + let width = 4; + match Self::required_coordinate_size(dim) { + None => crate::TypeInner::Scalar { kind, width }, + Some(size) => crate::TypeInner::Vector { size, kind, width }, + } + }, + }); + let base_handle = self.lookup_type.lookup(sample_type_id)?.handle; let kind = module.types[base_handle] .inner @@ -2404,11 +2599,9 @@ impl> Parser { } }; - let decor = self.future_decor.remove(&id).unwrap_or_default(); - let inner = crate::TypeInner::Image { class, - dim: map_image_dim(dim)?, + dim, arrayed: is_array, }; let handle = module.types.append(crate::Type { diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 913797e79..934160c5c 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -133,11 +133,10 @@ fn check_output_glsl(module: &naga::Module, name: &str, stage: naga::ShaderStage #[cfg(feature = "wgsl-in")] fn convert_wgsl(name: &str, language: Language) { - let params = - match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { - Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), - Err(_) => Parameters::default(), - }; + let params = match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { + Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), + Err(_) => Parameters::default(), + }; let module = naga::front::wgsl::parse_str( &std::fs::read_to_string(format!("tests/in/{}{}", name, ".wgsl")) From 6b9d3eafc875231112de0eb841380ff6ca1c81fd Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 8 Feb 2021 11:15:08 -0500 Subject: [PATCH 0456/2212] [spv-in] Rewrite the comparison image/sample handling. Keep track of the comparison property per global variable instead of type. Only track images that can actually be comparison-sampled. Instead of mutating the type, just add a new type in the end if we detect it to be necessary, cloning the old name. --- src/front/spv/error.rs | 8 +- src/front/spv/mod.rs | 418 ++++++++++++++++++++++------------------- 2 files changed, 223 insertions(+), 203 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 14e7d1cc3..d05213643 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -35,16 +35,15 @@ pub enum Error { InvalidVectorSize(spirv::Word), InvalidVariableClass(spirv::StorageClass), InvalidAccessType(spirv::Word), - InvalidAccess(Handle), + InvalidAccess(crate::Expression), InvalidAccessIndex(spirv::Word), InvalidBinding(spirv::Word), - InvalidImageExpression(Handle), + InvalidGlobalVar(crate::Expression), InvalidImageBaseType(Handle), InvalidSampleImage(Handle), - InvalidSamplerExpression(Handle), InvalidDepthReference(Handle), InvalidAsType(Handle), - InconsistentComparisonSampling(Handle), + InconsistentComparisonSampling(Handle), WrongFunctionResultType(spirv::Word), WrongFunctionArgumentType(spirv::Word), MissingDecoration(spirv::Decoration), @@ -52,7 +51,6 @@ pub enum Error { IncompleteData, InvalidTerminator, InvalidEdgeClassification, - UnexpectedComparisonType(Handle), // incomplete implementation error UnsupportedRowMajorMatrix, UnsupportedMatrixStride(spirv::Word), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index da6c20a06..223b1373b 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -63,6 +63,33 @@ impl Instruction { } } } + +impl crate::Expression { + fn as_global_var(&self) -> Result, Error> { + match *self { + crate::Expression::GlobalVariable(handle) => Ok(handle), + _ => Err(Error::InvalidGlobalVar(self.clone())), + } + } +} + +impl crate::TypeInner { + fn can_comparison_sample(&self) -> bool { + match *self { + crate::TypeInner::Image { + class: + crate::ImageClass::Sampled { + kind: crate::ScalarKind::Float, + multi: false, + }, + .. + } => true, + crate::TypeInner::Sampler { .. } => true, + _ => false, + } + } +} + /// OpPhi instruction. #[derive(Clone, Default, Debug)] struct PhiInstruction { @@ -101,22 +128,6 @@ impl LookupHelper for FastHashMap { } } -//TODO: this method may need to be gone, depending on whether -// WGSL allows treating images and samplers as expressions and pass them around. -fn reach_global_type( - mut expr_handle: Handle, - expressions: &Arena, - globals: &Arena, -) -> Option> { - loop { - expr_handle = match expressions[expr_handle] { - crate::Expression::Load { pointer } => pointer, - crate::Expression::GlobalVariable(var) => return Some(globals[var].ty), - _ => return None, - }; - } -} - fn check_sample_coordinates( ty: &crate::Type, expect_kind: crate::ScalarKind, @@ -141,6 +152,113 @@ fn check_sample_coordinates( } } +impl crate::ImageDimension { + fn required_coordinate_size(&self) -> Option { + match *self { + crate::ImageDimension::D1 => None, + crate::ImageDimension::D2 => Some(crate::VectorSize::Bi), + crate::ImageDimension::D3 => Some(crate::VectorSize::Tri), + crate::ImageDimension::Cube => Some(crate::VectorSize::Tri), + } + } +} + +/// Return the texture coordinates separated from the array layer, +/// and/or divided by the projection term. +/// +/// The Proj sampling ops expect an extra coordinate for the W. +/// The arrayed (can't be Proj!) images expect an extra coordinate for the layer. +fn extract_image_coordinates( + image_dim: crate::ImageDimension, + image_arrayed: bool, + base: Handle, + coordinate_ty: Handle, + type_arena: &Arena, + expressions: &mut Arena, +) -> (Handle, Option>) { + let (given_size, kind) = match type_arena[coordinate_ty].inner { + crate::TypeInner::Scalar { kind, .. } => (None, kind), + crate::TypeInner::Vector { size, kind, .. } => (Some(size), kind), + ref other => unreachable!("Unexpected texture coordinate {:?}", other), + }; + + let required_size = image_dim.required_coordinate_size(); + let required_ty = required_size.map(|size| { + type_arena + .fetch_if(|ty| { + ty.inner + == crate::TypeInner::Vector { + size, + kind, + width: 4, + } + }) + .expect("Required coordinate type should have been set up by `parse_type_image`!") + }); + let extra_expr = crate::Expression::AccessIndex { + base, + index: required_size.map_or(1, |size| size as u32), + }; + + if given_size == required_size { + // fast path, no complications + (base, None) + } else if image_arrayed { + // extra coordinate for the array index + let extracted = match required_size { + None => expressions.append(crate::Expression::AccessIndex { base, index: 0 }), + Some(size) => { + let mut components = Vec::with_capacity(size as usize); + for index in 0..size as u32 { + let comp = expressions.append(crate::Expression::AccessIndex { base, index }); + components.push(comp); + } + expressions.append(crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }) + } + }; + let array_index_f32 = expressions.append(extra_expr); + let array_index = expressions.append(crate::Expression::As { + kind: crate::ScalarKind::Uint, + expr: array_index_f32, + convert: true, + }); + (extracted, Some(array_index)) + } else { + // extra coordinate for the projection W + let projection = expressions.append(extra_expr); + let divided = match required_size { + None => { + let temp = expressions.append(crate::Expression::AccessIndex { base, index: 0 }); + expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: temp, + right: projection, + }) + } + Some(size) => { + let mut components = Vec::with_capacity(size as usize); + for index in 0..size as u32 { + let temp = expressions.append(crate::Expression::AccessIndex { base, index }); + let comp = expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: temp, + right: projection, + }); + components.push(comp); + } + expressions.append(crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }) + } + }; + (divided, None) + } +} + type MemberIndex = u32; #[derive(Clone, Debug, Default, PartialEq)] @@ -296,7 +414,7 @@ pub struct Parser { future_decor: FastHashMap, future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>, lookup_member_type_id: FastHashMap<(Handle, MemberIndex), spirv::Word>, - handle_sampling: FastHashMap, SamplingFlags>, + handle_sampling: FastHashMap, SamplingFlags>, lookup_type: FastHashMap, lookup_void_type: Option, lookup_storage_buffer_types: FastHashSet>, @@ -528,7 +646,7 @@ impl> Parser { let child_type_id = *self .lookup_member_type_id .get(&(root_lookup.handle, selection)) - .ok_or(Error::InvalidAccess(root_expr))?; + .ok_or(Error::InvalidAccessType(root_type_id))?; (members.len(), child_type_id) } // crate::TypeInner::Array //TODO? @@ -565,105 +683,6 @@ impl> Parser { })) } - /// Return the texture coordinates separated from the array layer, - /// and/or divided by the projection term. - /// - /// The Proj sampling ops expect an extra coordinate for the W. - /// The arrayed (can't be Proj!) images expect an extra coordinate for the layer. - fn extract_image_coordinates( - image_dim: crate::ImageDimension, - image_arrayed: bool, - base: Handle, - coordinate_ty: Handle, - type_arena: &Arena, - expressions: &mut Arena, - ) -> (Handle, Option>) { - let (given_size, kind) = match type_arena[coordinate_ty].inner { - crate::TypeInner::Scalar { kind, .. } => (None, kind), - crate::TypeInner::Vector { size, kind, .. } => (Some(size), kind), - ref other => unreachable!("Unexpected texture coordinate {:?}", other), - }; - - let required_size = Self::required_coordinate_size(image_dim); - let required_ty = required_size.map(|size| { - type_arena - .fetch_if(|ty| { - ty.inner - == crate::TypeInner::Vector { - size, - kind, - width: 4, - } - }) - .expect("Required coordinate type should have been set up by `parse_type_image`!") - }); - let extra_expr = crate::Expression::AccessIndex { - base, - index: required_size.map_or(1, |size| size as u32), - }; - - if given_size == required_size { - // fast path, no complications - (base, None) - } else if image_arrayed { - // extra coordinate for the array index - let extracted = match required_size { - None => expressions.append(crate::Expression::AccessIndex { base, index: 0 }), - Some(size) => { - let mut components = Vec::with_capacity(size as usize); - for index in 0..size as u32 { - let comp = - expressions.append(crate::Expression::AccessIndex { base, index }); - components.push(comp); - } - expressions.append(crate::Expression::Compose { - ty: required_ty.unwrap(), - components, - }) - } - }; - let array_index_f32 = expressions.append(extra_expr); - let array_index = expressions.append(crate::Expression::As { - kind: crate::ScalarKind::Uint, - expr: array_index_f32, - convert: true, - }); - (extracted, Some(array_index)) - } else { - // extra coordinate for the projection W - let projection = expressions.append(extra_expr); - let divided = match required_size { - None => { - let temp = - expressions.append(crate::Expression::AccessIndex { base, index: 0 }); - expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Divide, - left: temp, - right: projection, - }) - } - Some(size) => { - let mut components = Vec::with_capacity(size as usize); - for index in 0..size as u32 { - let temp = - expressions.append(crate::Expression::AccessIndex { base, index }); - let comp = expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Divide, - left: temp, - right: projection, - }); - components.push(comp); - } - expressions.append(crate::Expression::Compose { - ty: required_ty.unwrap(), - components, - }) - } - }; - (divided, None) - } - } - #[allow(clippy::too_many_arguments)] fn next_block( &mut self, @@ -808,11 +827,13 @@ impl> Parser { value: crate::ScalarValue::Sint(v), } => v as u32, _ => { - return Err(Error::InvalidAccess(index_expr.handle)) + return Err(Error::InvalidAccess( + crate::Expression::Constant(const_handle), + )) } } } - _ => return Err(Error::InvalidAccess(index_expr.handle)), + ref other => return Err(Error::InvalidAccess(other.clone())), }; AccessExpression { base_handle: expressions.append( @@ -1148,18 +1169,17 @@ impl> Parser { } let image_lexp = self.lookup_expression.lookup(image_id)?; - let image_type_handle = - reach_global_type(image_lexp.handle, expressions, global_arena) - .ok_or(Error::InvalidImageExpression(image_lexp.handle))?; + let image_var_handle = expressions[image_lexp.handle].as_global_var()?; + let image_var = &global_arena[image_var_handle]; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let (coordinate, array_index) = match type_arena[image_type_handle].inner { + let (coordinate, array_index) = match type_arena[image_var.ty].inner { crate::TypeInner::Image { dim, arrayed, class: _, - } => Self::extract_image_coordinates( + } => extract_image_coordinates( dim, arrayed, coord_lexp.handle, @@ -1167,7 +1187,7 @@ impl> Parser { type_arena, expressions, ), - _ => return Err(Error::InvalidSampleImage(image_type_handle)), + _ => return Err(Error::InvalidSampleImage(image_var.ty)), }; let expr = crate::Expression::ImageLoad { @@ -1226,28 +1246,26 @@ impl> Parser { let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let sampler_type_handle = - reach_global_type(si_lexp.sampler, expressions, global_arena) - .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; - let image_type_handle = - reach_global_type(si_lexp.image, expressions, global_arena) - .ok_or(Error::InvalidImageExpression(si_lexp.image))?; + let image_var_handle = expressions[si_lexp.image].as_global_var()?; + let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?; log::debug!( - "\t\t\tImage {:?} with sampler {:?}", - image_type_handle, - sampler_type_handle + "\t\t\tImage {:?} sampled with {:?}", + image_var_handle, + sampler_var_handle ); - *self.handle_sampling.get_mut(&sampler_type_handle).unwrap() |= - SamplingFlags::REGULAR; - *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= + if let Some(flags) = self.handle_sampling.get_mut(&image_var_handle) { + *flags |= SamplingFlags::REGULAR; + } + *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= SamplingFlags::REGULAR; - let (coordinate, array_index) = match type_arena[image_type_handle].inner { + let image_var = &global_arena[image_var_handle]; + let (coordinate, array_index) = match type_arena[image_var.ty].inner { crate::TypeInner::Image { dim, arrayed, class: _, - } => Self::extract_image_coordinates( + } => extract_image_coordinates( dim, arrayed, coord_lexp.handle, @@ -1255,7 +1273,7 @@ impl> Parser { type_arena, expressions, ), - _ => return Err(Error::InvalidSampleImage(image_type_handle)), + _ => return Err(Error::InvalidSampleImage(image_var.ty)), }; let expr = crate::Expression::ImageSample { @@ -1317,15 +1335,17 @@ impl> Parser { let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let sampler_type_handle = - reach_global_type(si_lexp.sampler, expressions, global_arena) - .ok_or(Error::InvalidSamplerExpression(si_lexp.sampler))?; - let image_type_handle = - reach_global_type(si_lexp.image, expressions, global_arena) - .ok_or(Error::InvalidImageExpression(si_lexp.image))?; - *self.handle_sampling.get_mut(&sampler_type_handle).unwrap() |= - SamplingFlags::COMPARISON; - *self.handle_sampling.get_mut(&image_type_handle).unwrap() |= + let image_var_handle = expressions[si_lexp.image].as_global_var()?; + let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?; + log::debug!( + "\t\t\tImage {:?} sampled with comparison {:?}", + image_var_handle, + sampler_var_handle + ); + if let Some(flags) = self.handle_sampling.get_mut(&image_var_handle) { + *flags |= SamplingFlags::COMPARISON; + } + *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= SamplingFlags::COMPARISON; let dref_lexp = self.lookup_expression.lookup(dref_id)?; @@ -1338,12 +1358,13 @@ impl> Parser { _ => return Err(Error::InvalidDepthReference(dref_type_handle)), } - let (coordinate, array_index) = match type_arena[image_type_handle].inner { + let image_var = &global_arena[image_var_handle]; + let (coordinate, array_index) = match type_arena[image_var.ty].inner { crate::TypeInner::Image { dim, arrayed, class: _, - } => Self::extract_image_coordinates( + } => extract_image_coordinates( dim, arrayed, coord_lexp.handle, @@ -1351,7 +1372,7 @@ impl> Parser { type_arena, expressions, ), - _ => return Err(Error::InvalidSampleImage(image_type_handle)), + _ => return Err(Error::InvalidSampleImage(image_var.ty)), }; let expr = crate::Expression::ImageSample { @@ -1987,15 +2008,27 @@ impl> Parser { if flags == SamplingFlags::all() { return Err(Error::InconsistentComparisonSampling(handle)); } - let ty = module.types.get_mut(handle); - match ty.inner { - crate::TypeInner::Sampler { ref mut comparison } => { - *comparison = true; - } - _ => { - return Err(Error::UnexpectedComparisonType(handle)); - } - } + log::debug!("Flipping comparison for {:?}", handle); + let var = module.global_variables.get_mut(handle); + let original_ty = &module.types[var.ty]; + let ty_inner = match original_ty.inner { + crate::TypeInner::Image { + class: _, + dim, + arrayed, + } => crate::TypeInner::Image { + class: crate::ImageClass::Depth, + dim, + arrayed, + }, + crate::TypeInner::Sampler { .. } => crate::TypeInner::Sampler { comparison: true }, + ref other => unreachable!("Unexpected type for comparison mutation: {:?}", other), + }; + let name = original_ty.name.clone(); + var.ty = module.types.append(crate::Type { + name, + inner: ty_inner, + }); } for (_, func) in module.functions.iter_mut() { @@ -2542,15 +2575,6 @@ impl> Parser { Ok(()) } - fn required_coordinate_size(dim: crate::ImageDimension) -> Option { - match dim { - crate::ImageDimension::D1 => None, - crate::ImageDimension::D2 => Some(crate::VectorSize::Bi), - crate::ImageDimension::D3 => Some(crate::VectorSize::Tri), - crate::ImageDimension::Cube => Some(crate::VectorSize::Tri), - } - } - fn parse_type_image( &mut self, inst: Instruction, @@ -2577,7 +2601,7 @@ impl> Parser { inner: { let kind = crate::ScalarKind::Float; let width = 4; - match Self::required_coordinate_size(dim) { + match dim.required_coordinate_size() { None => crate::TypeInner::Scalar { kind, width }, Some(size) => crate::TypeInner::Vector { size, kind, width }, } @@ -2590,26 +2614,24 @@ impl> Parser { .scalar_kind() .ok_or(Error::InvalidImageBaseType(base_handle))?; - let class = if format != 0 { - crate::ImageClass::Storage(map_image_format(format)?) - } else { - crate::ImageClass::Sampled { - kind, - multi: is_msaa, - } - }; - let inner = crate::TypeInner::Image { - class, + class: if format != 0 { + crate::ImageClass::Storage(map_image_format(format)?) + } else { + crate::ImageClass::Sampled { + kind, + multi: is_msaa, + } + }, dim, arrayed: is_array, }; + let handle = module.types.append(crate::Type { name: decor.name, inner, }); - log::debug!("\t\ttracking {:?} for sampling properties", handle); - self.handle_sampling.insert(handle, SamplingFlags::empty()); + self.lookup_type.insert( id, LookupType { @@ -2644,15 +2666,10 @@ impl> Parser { inst.expect(2)?; let id = self.next()?; let decor = self.future_decor.remove(&id).unwrap_or_default(); - // The comparison bit is temporary, will be overwritten based on the - // accumulated sampling flags at the end. - let inner = crate::TypeInner::Sampler { comparison: false }; let handle = module.types.append(crate::Type { name: decor.name, - inner, + inner: crate::TypeInner::Sampler { comparison: false }, }); - log::debug!("\t\ttracking {:?} for sampling properties", handle); - self.handle_sampling.insert(handle, SamplingFlags::empty()); self.lookup_type.insert( id, LookupType { @@ -2883,7 +2900,8 @@ impl> Parser { } }; - let is_storage = match module.types[lookup_type.handle].inner { + let ty_inner = &module.types[lookup_type.handle].inner; + let is_storage = match *ty_inner { crate::TypeInner::Struct { .. } => class == crate::StorageClass::Storage, crate::TypeInner::Image { class: crate::ImageClass::Storage(_), @@ -2910,7 +2928,7 @@ impl> Parser { // SPIR-V only cares about some of the built-in types being integer. // Naga requires them to be strictly unsigned, so we have to patch it. Some(crate::Binding::BuiltIn(built_in)) => { - let scalar_kind = module.types[lookup_type.handle].inner.scalar_kind(); + let scalar_kind = ty_inner.scalar_kind(); let needs_uint = match built_in { crate::BuiltIn::BaseInstance | crate::BuiltIn::BaseVertex @@ -2944,13 +2962,17 @@ impl> Parser { interpolation: dec.interpolation, storage_access, }; - self.lookup_variable.insert( - id, - LookupVariable { - handle: module.global_variables.append(var), - type_id, - }, - ); + let handle = module.global_variables.append(var); + self.lookup_variable + .insert(id, LookupVariable { handle, type_id }); + + if module.types[lookup_type.handle] + .inner + .can_comparison_sample() + { + log::debug!("\t\ttracking {:?} for sampling properties", handle); + self.handle_sampling.insert(handle, SamplingFlags::empty()); + } Ok(()) } } From cf0a86afd4a6bbfdffcb90d8f4504bfa72f0b636 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 8 Feb 2021 12:13:12 -0500 Subject: [PATCH 0457/2212] [spv-in] move all the image-related logic into a sub-module --- src/front/spv/function.rs | 13 +- src/front/spv/image.rs | 511 ++++++++++++++++++++++++++++++++++++ src/front/spv/mod.rs | 529 +++----------------------------------- 3 files changed, 549 insertions(+), 504 deletions(-) create mode 100644 src/front/spv/image.rs diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 78e87f677..c0283eb23 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -1,7 +1,6 @@ -use crate::arena::Handle; +use crate::arena::{Arena, Handle}; -use super::flow::*; -use super::*; +use super::{flow::*, Error, Instruction, LookupExpression, LookupHelper as _}; pub type BlockId = u32; @@ -50,13 +49,7 @@ pub enum Terminator { } impl> super::Parser { - pub fn parse_function( - &mut self, - inst: Instruction, - module: &mut crate::Module, - ) -> Result<(), Error> { - self.switch(ModuleState::Function, inst.op)?; - inst.expect(5)?; + pub fn parse_function(&mut self, module: &mut crate::Module) -> Result<(), Error> { let result_type_id = self.next()?; let fun_id = self.next()?; let _fun_control = self.next()?; diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs new file mode 100644 index 000000000..3453e7048 --- /dev/null +++ b/src/front/spv/image.rs @@ -0,0 +1,511 @@ +use crate::arena::{Arena, Handle}; + +use super::{Error, LookupExpression, LookupHelper as _}; + +#[derive(Clone, Debug)] +pub(super) struct LookupSampledImage { + image: Handle, + sampler: Handle, +} + +bitflags::bitflags! { + /// Flags describing sampling method. + pub struct SamplingFlags: u32 { + /// Regular sampling. + const REGULAR = 0x1; + /// Comparison sampling. + const COMPARISON = 0x2; + } +} + +/// Return the texture coordinates separated from the array layer, +/// and/or divided by the projection term. +/// +/// The Proj sampling ops expect an extra coordinate for the W. +/// The arrayed (can't be Proj!) images expect an extra coordinate for the layer. +fn extract_image_coordinates( + image_dim: crate::ImageDimension, + image_arrayed: bool, + base: Handle, + coordinate_ty: Handle, + type_arena: &Arena, + expressions: &mut Arena, +) -> (Handle, Option>) { + let (given_size, kind) = match type_arena[coordinate_ty].inner { + crate::TypeInner::Scalar { kind, .. } => (None, kind), + crate::TypeInner::Vector { size, kind, .. } => (Some(size), kind), + ref other => unreachable!("Unexpected texture coordinate {:?}", other), + }; + + let required_size = image_dim.required_coordinate_size(); + let required_ty = required_size.map(|size| { + type_arena + .fetch_if(|ty| { + ty.inner + == crate::TypeInner::Vector { + size, + kind, + width: 4, + } + }) + .expect("Required coordinate type should have been set up by `parse_type_image`!") + }); + let extra_expr = crate::Expression::AccessIndex { + base, + index: required_size.map_or(1, |size| size as u32), + }; + + if given_size == required_size { + // fast path, no complications + (base, None) + } else if image_arrayed { + // extra coordinate for the array index + let extracted = match required_size { + None => expressions.append(crate::Expression::AccessIndex { base, index: 0 }), + Some(size) => { + let mut components = Vec::with_capacity(size as usize); + for index in 0..size as u32 { + let comp = expressions.append(crate::Expression::AccessIndex { base, index }); + components.push(comp); + } + expressions.append(crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }) + } + }; + let array_index_f32 = expressions.append(extra_expr); + let array_index = expressions.append(crate::Expression::As { + kind: crate::ScalarKind::Uint, + expr: array_index_f32, + convert: true, + }); + (extracted, Some(array_index)) + } else { + // extra coordinate for the projection W + let projection = expressions.append(extra_expr); + let divided = match required_size { + None => { + let temp = expressions.append(crate::Expression::AccessIndex { base, index: 0 }); + expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: temp, + right: projection, + }) + } + Some(size) => { + let mut components = Vec::with_capacity(size as usize); + for index in 0..size as u32 { + let temp = expressions.append(crate::Expression::AccessIndex { base, index }); + let comp = expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: temp, + right: projection, + }); + components.push(comp); + } + expressions.append(crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }) + } + }; + (divided, None) + } +} + +pub(super) fn patch_comparison_type( + flags: SamplingFlags, + var: &mut crate::GlobalVariable, + arena: &mut Arena, +) -> bool { + if !flags.contains(SamplingFlags::COMPARISON) { + return true; + } + if flags == SamplingFlags::all() { + return false; + } + + log::debug!("Flipping comparison for {:?}", var); + let original_ty = &arena[var.ty]; + let ty_inner = match original_ty.inner { + crate::TypeInner::Image { + class: _, + dim, + arrayed, + } => crate::TypeInner::Image { + class: crate::ImageClass::Depth, + dim, + arrayed, + }, + crate::TypeInner::Sampler { .. } => crate::TypeInner::Sampler { comparison: true }, + ref other => unreachable!("Unexpected type for comparison mutation: {:?}", other), + }; + + let name = original_ty.name.clone(); + var.ty = arena.append(crate::Type { + name, + inner: ty_inner, + }); + true +} + +impl> super::Parser { + pub(super) fn parse_image_couple(&mut self) -> Result<(), Error> { + let _result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + let sampler_id = self.next()?; + let image_lexp = self.lookup_expression.lookup(image_id)?; + let sampler_lexp = self.lookup_expression.lookup(sampler_id)?; + self.lookup_sampled_image.insert( + result_id, + LookupSampledImage { + image: image_lexp.handle, + sampler: sampler_lexp.handle, + }, + ); + Ok(()) + } + + pub(super) fn parse_image_uncouple(&mut self) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let sampled_image_id = self.next()?; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: self.lookup_sampled_image.lookup(sampled_image_id)?.image, + type_id: result_type_id, + }, + ); + Ok(()) + } + + pub(super) fn parse_image_fetch( + &mut self, + mut words_left: u16, + type_arena: &Arena, + global_arena: &Arena, + expressions: &mut Arena, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + let coordinate_id = self.next()?; + + let mut index = None; + while words_left != 0 { + let image_ops = self.next()?; + words_left -= 1; + match spirv::ImageOperands::from_bits_truncate(image_ops) { + spirv::ImageOperands::LOD => { + let lod_expr = self.next()?; + let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; + index = Some(lod_handle); + words_left -= 1; + } + spirv::ImageOperands::SAMPLE => { + let sample_expr = self.next()?; + let sample_handle = self.lookup_expression.lookup(sample_expr)?.handle; + index = Some(sample_handle); + words_left -= 1; + } + other => { + log::warn!("Skipping {:?}", other); + for _ in 0..words_left { + self.next()?; + } + break; + } + } + } + + let image_lexp = self.lookup_expression.lookup(image_id)?; + let image_var_handle = expressions[image_lexp.handle].as_global_var()?; + let image_var = &global_arena[image_var_handle]; + + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + let (coordinate, array_index) = match type_arena[image_var.ty].inner { + crate::TypeInner::Image { + dim, + arrayed, + class: _, + } => extract_image_coordinates( + dim, + arrayed, + coord_lexp.handle, + coord_type_handle, + type_arena, + expressions, + ), + _ => return Err(Error::InvalidSampleImage(image_var.ty)), + }; + + let expr = crate::Expression::ImageLoad { + image: image_lexp.handle, + coordinate, + array_index, + index, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } + + pub(super) fn parse_image_sample( + &mut self, + mut words_left: u16, + type_arena: &Arena, + global_arena: &Arena, + expressions: &mut Arena, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let sampled_image_id = self.next()?; + let coordinate_id = self.next()?; + + let mut level = crate::SampleLevel::Auto; + while words_left != 0 { + let image_ops = self.next()?; + words_left -= 1; + match spirv::ImageOperands::from_bits_truncate(image_ops) { + spirv::ImageOperands::BIAS => { + let bias_expr = self.next()?; + let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; + level = crate::SampleLevel::Bias(bias_handle); + words_left -= 1; + } + spirv::ImageOperands::LOD => { + let lod_expr = self.next()?; + let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; + level = crate::SampleLevel::Exact(lod_handle); + words_left -= 1; + } + other => { + log::warn!("Skipping {:?}", other); + for _ in 0..words_left { + self.next()?; + } + break; + } + } + } + + let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + + let image_var_handle = expressions[si_lexp.image].as_global_var()?; + let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?; + log::debug!( + "\t\t\tImage {:?} sampled with {:?}", + image_var_handle, + sampler_var_handle + ); + if let Some(flags) = self.handle_sampling.get_mut(&image_var_handle) { + *flags |= SamplingFlags::REGULAR; + } + *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= SamplingFlags::REGULAR; + + let image_var = &global_arena[image_var_handle]; + let (coordinate, array_index) = match type_arena[image_var.ty].inner { + crate::TypeInner::Image { + dim, + arrayed, + class: _, + } => extract_image_coordinates( + dim, + arrayed, + coord_lexp.handle, + coord_type_handle, + type_arena, + expressions, + ), + _ => return Err(Error::InvalidSampleImage(image_var.ty)), + }; + + let expr = crate::Expression::ImageSample { + image: si_lexp.image, + sampler: si_lexp.sampler, + coordinate, + array_index, + offset: None, //TODO + level, + depth_ref: None, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } + + pub(super) fn parse_image_sample_dref( + &mut self, + mut words_left: u16, + type_arena: &Arena, + global_arena: &Arena, + expressions: &mut Arena, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let sampled_image_id = self.next()?; + let coordinate_id = self.next()?; + let dref_id = self.next()?; + + let mut level = crate::SampleLevel::Auto; + while words_left != 0 { + let image_ops = self.next()?; + words_left -= 1; + match spirv::ImageOperands::from_bits_truncate(image_ops) { + spirv::ImageOperands::BIAS => { + let bias_expr = self.next()?; + let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; + level = crate::SampleLevel::Bias(bias_handle); + words_left -= 1; + } + spirv::ImageOperands::LOD => { + let lod_expr = self.next()?; + let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; + level = crate::SampleLevel::Exact(lod_handle); + words_left -= 1; + } + other => { + log::warn!("Skipping {:?}", other); + for _ in 0..words_left { + self.next()?; + } + break; + } + } + } + + let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + let image_var_handle = expressions[si_lexp.image].as_global_var()?; + let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?; + log::debug!( + "\t\t\tImage {:?} sampled with comparison {:?}", + image_var_handle, + sampler_var_handle + ); + if let Some(flags) = self.handle_sampling.get_mut(&image_var_handle) { + *flags |= SamplingFlags::COMPARISON; + } + *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= SamplingFlags::COMPARISON; + + let dref_lexp = self.lookup_expression.lookup(dref_id)?; + let dref_type_handle = self.lookup_type.lookup(dref_lexp.type_id)?.handle; + match type_arena[dref_type_handle].inner { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: _, + } => (), + _ => return Err(Error::InvalidDepthReference(dref_type_handle)), + } + + let image_var = &global_arena[image_var_handle]; + let (coordinate, array_index) = match type_arena[image_var.ty].inner { + crate::TypeInner::Image { + dim, + arrayed, + class: _, + } => extract_image_coordinates( + dim, + arrayed, + coord_lexp.handle, + coord_type_handle, + type_arena, + expressions, + ), + _ => return Err(Error::InvalidSampleImage(image_var.ty)), + }; + + let expr = crate::Expression::ImageSample { + image: si_lexp.image, + sampler: si_lexp.sampler, + coordinate, + array_index, + offset: None, //TODO + level, + depth_ref: Some(dref_lexp.handle), + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } + + pub(super) fn parse_image_query_size( + &mut self, + at_level: bool, + expressions: &mut Arena, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + let level = if at_level { + let level_id = self.next()?; + let level_lexp = self.lookup_expression.lookup(level_id)?; + Some(level_lexp.handle) + } else { + None + }; + + //TODO: handle arrays and cubes + let image_lexp = self.lookup_expression.lookup(image_id)?; + + let expr = crate::Expression::ImageQuery { + image: image_lexp.handle, + query: crate::ImageQuery::Size { level }, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } + + pub(super) fn parse_image_query_other( + &mut self, + query: crate::ImageQuery, + expressions: &mut Arena, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let image_id = self.next()?; + + let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); + + let expr = crate::Expression::ImageQuery { + image: image_lexp.handle, + query, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } +} diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 223b1373b..e37f94972 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -15,6 +15,7 @@ mod convert; mod error; mod flow; mod function; +mod image; #[cfg(all(test, feature = "serialize"))] mod rosetta; @@ -55,12 +56,10 @@ impl Instruction { } } - fn expect_at_least(self, count: u16) -> Result<(), Error> { - if self.wc >= count { - Ok(()) - } else { - Err(Error::InvalidOperandCount(self.op, self.wc)) - } + fn expect_at_least(self, count: u16) -> Result { + self.wc + .checked_sub(count) + .ok_or(Error::InvalidOperandCount(self.op, self.wc)) } } @@ -163,102 +162,6 @@ impl crate::ImageDimension { } } -/// Return the texture coordinates separated from the array layer, -/// and/or divided by the projection term. -/// -/// The Proj sampling ops expect an extra coordinate for the W. -/// The arrayed (can't be Proj!) images expect an extra coordinate for the layer. -fn extract_image_coordinates( - image_dim: crate::ImageDimension, - image_arrayed: bool, - base: Handle, - coordinate_ty: Handle, - type_arena: &Arena, - expressions: &mut Arena, -) -> (Handle, Option>) { - let (given_size, kind) = match type_arena[coordinate_ty].inner { - crate::TypeInner::Scalar { kind, .. } => (None, kind), - crate::TypeInner::Vector { size, kind, .. } => (Some(size), kind), - ref other => unreachable!("Unexpected texture coordinate {:?}", other), - }; - - let required_size = image_dim.required_coordinate_size(); - let required_ty = required_size.map(|size| { - type_arena - .fetch_if(|ty| { - ty.inner - == crate::TypeInner::Vector { - size, - kind, - width: 4, - } - }) - .expect("Required coordinate type should have been set up by `parse_type_image`!") - }); - let extra_expr = crate::Expression::AccessIndex { - base, - index: required_size.map_or(1, |size| size as u32), - }; - - if given_size == required_size { - // fast path, no complications - (base, None) - } else if image_arrayed { - // extra coordinate for the array index - let extracted = match required_size { - None => expressions.append(crate::Expression::AccessIndex { base, index: 0 }), - Some(size) => { - let mut components = Vec::with_capacity(size as usize); - for index in 0..size as u32 { - let comp = expressions.append(crate::Expression::AccessIndex { base, index }); - components.push(comp); - } - expressions.append(crate::Expression::Compose { - ty: required_ty.unwrap(), - components, - }) - } - }; - let array_index_f32 = expressions.append(extra_expr); - let array_index = expressions.append(crate::Expression::As { - kind: crate::ScalarKind::Uint, - expr: array_index_f32, - convert: true, - }); - (extracted, Some(array_index)) - } else { - // extra coordinate for the projection W - let projection = expressions.append(extra_expr); - let divided = match required_size { - None => { - let temp = expressions.append(crate::Expression::AccessIndex { base, index: 0 }); - expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Divide, - left: temp, - right: projection, - }) - } - Some(size) => { - let mut components = Vec::with_capacity(size as usize); - for index in 0..size as u32 { - let temp = expressions.append(crate::Expression::AccessIndex { base, index }); - let comp = expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Divide, - left: temp, - right: projection, - }); - components.push(comp); - } - expressions.append(crate::Expression::Compose { - ty: required_ty.unwrap(), - components, - }) - } - }; - (divided, None) - } -} - type MemberIndex = u32; #[derive(Clone, Debug, Default, PartialEq)] @@ -313,7 +216,7 @@ impl Decoration { desc_set: None, desc_index: None, .. - } => match convert::map_builtin(built_in, is_output) { + } => match map_builtin(built_in, is_output) { Ok(built_in) => Some(crate::Binding::BuiltIn(built_in)), Err(e) => { log::warn!("{:?}", e); @@ -339,16 +242,6 @@ impl Decoration { } } -bitflags::bitflags! { - /// Flags describing sampling method. - pub struct SamplingFlags: u32 { - /// Regular sampling. - const REGULAR = 0x1; - /// Comparison sampling. - const COMPARISON = 0x2; - } -} - #[derive(Debug)] struct LookupFunctionType { parameter_type_ids: Vec, @@ -389,12 +282,6 @@ struct LookupExpression { type_id: spirv::Word, } -#[derive(Clone, Debug)] -struct LookupSampledImage { - image: Handle, - sampler: Handle, -} - #[derive(Clone, Debug)] pub struct Assignment { to: Handle, @@ -414,7 +301,7 @@ pub struct Parser { future_decor: FastHashMap, future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>, lookup_member_type_id: FastHashMap<(Handle, MemberIndex), spirv::Word>, - handle_sampling: FastHashMap, SamplingFlags>, + handle_sampling: FastHashMap, image::SamplingFlags>, lookup_type: FastHashMap, lookup_void_type: Option, lookup_storage_buffer_types: FastHashSet>, @@ -422,7 +309,7 @@ pub struct Parser { lookup_constant: FastHashMap, lookup_variable: FastHashMap, lookup_expression: FastHashMap, - lookup_sampled_image: FastHashMap, + lookup_sampled_image: FastHashMap, lookup_function_type: FastHashMap, lookup_function: FastHashMap>, lookup_entry_point: FastHashMap, @@ -1104,378 +991,47 @@ impl> Parser { // Sampling Op::Image => { inst.expect(4)?; - let result_type_id = self.next()?; - let result_id = self.next()?; - let sampled_image_id = self.next()?; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: self.lookup_sampled_image.lookup(sampled_image_id)?.image, - type_id: result_type_id, - }, - ); + self.parse_image_uncouple()?; } Op::SampledImage => { inst.expect(5)?; - let _result_type_id = self.next()?; - let result_id = self.next()?; - let image_id = self.next()?; - let sampler_id = self.next()?; - let image_lexp = self.lookup_expression.lookup(image_id)?; - let sampler_lexp = self.lookup_expression.lookup(sampler_id)?; - //TODO: compare the result type - self.lookup_sampled_image.insert( - result_id, - LookupSampledImage { - image: image_lexp.handle, - sampler: sampler_lexp.handle, - }, - ); + self.parse_image_couple()?; } Op::ImageFetch => { - inst.expect_at_least(5)?; - let result_type_id = self.next()?; - let result_id = self.next()?; - let image_id = self.next()?; - let coordinate_id = self.next()?; - - let mut index = None; - let mut base_wc = 5; - while base_wc < inst.wc { - let image_ops = self.next()?; - base_wc += 1; - match spirv::ImageOperands::from_bits_truncate(image_ops) { - spirv::ImageOperands::LOD => { - let lod_expr = self.next()?; - let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; - index = Some(lod_handle); - base_wc += 1; - } - spirv::ImageOperands::SAMPLE => { - let sample_expr = self.next()?; - let sample_handle = - self.lookup_expression.lookup(sample_expr)?.handle; - index = Some(sample_handle); - base_wc += 1; - } - other => { - log::warn!("Skipping {:?}", other); - for _ in base_wc..inst.wc { - self.next()?; - } - break; - } - } - } - - let image_lexp = self.lookup_expression.lookup(image_id)?; - let image_var_handle = expressions[image_lexp.handle].as_global_var()?; - let image_var = &global_arena[image_var_handle]; - - let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let (coordinate, array_index) = match type_arena[image_var.ty].inner { - crate::TypeInner::Image { - dim, - arrayed, - class: _, - } => extract_image_coordinates( - dim, - arrayed, - coord_lexp.handle, - coord_type_handle, - type_arena, - expressions, - ), - _ => return Err(Error::InvalidSampleImage(image_var.ty)), - }; - - let expr = crate::Expression::ImageLoad { - image: image_lexp.handle, - coordinate, - array_index, - index, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + let extra = inst.expect_at_least(5)?; + self.parse_image_fetch(extra, type_arena, global_arena, expressions)?; } Op::ImageSampleImplicitLod | Op::ImageSampleExplicitLod | Op::ImageSampleProjImplicitLod | Op::ImageSampleProjExplicitLod => { - let mut base_wc = 5; - inst.expect_at_least(base_wc)?; - let result_type_id = self.next()?; - let result_id = self.next()?; - let sampled_image_id = self.next()?; - let coordinate_id = self.next()?; - - let mut level = crate::SampleLevel::Auto; - while base_wc < inst.wc { - let image_ops = self.next()?; - base_wc += 1; - match spirv::ImageOperands::from_bits_truncate(image_ops) { - spirv::ImageOperands::BIAS => { - let bias_expr = self.next()?; - let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; - level = crate::SampleLevel::Bias(bias_handle); - base_wc += 1; - } - spirv::ImageOperands::LOD => { - let lod_expr = self.next()?; - let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; - level = crate::SampleLevel::Exact(lod_handle); - base_wc += 1; - } - other => { - log::warn!("Skipping {:?}", other); - for _ in base_wc..inst.wc { - self.next()?; - } - break; - } - } - } - - let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; - let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - - let image_var_handle = expressions[si_lexp.image].as_global_var()?; - let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?; - log::debug!( - "\t\t\tImage {:?} sampled with {:?}", - image_var_handle, - sampler_var_handle - ); - if let Some(flags) = self.handle_sampling.get_mut(&image_var_handle) { - *flags |= SamplingFlags::REGULAR; - } - *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= - SamplingFlags::REGULAR; - - let image_var = &global_arena[image_var_handle]; - let (coordinate, array_index) = match type_arena[image_var.ty].inner { - crate::TypeInner::Image { - dim, - arrayed, - class: _, - } => extract_image_coordinates( - dim, - arrayed, - coord_lexp.handle, - coord_type_handle, - type_arena, - expressions, - ), - _ => return Err(Error::InvalidSampleImage(image_var.ty)), - }; - - let expr = crate::Expression::ImageSample { - image: si_lexp.image, - sampler: si_lexp.sampler, - coordinate, - array_index, - offset: None, //TODO - level, - depth_ref: None, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + let extra = inst.expect_at_least(5)?; + self.parse_image_sample(extra, type_arena, global_arena, expressions)?; } Op::ImageSampleDrefImplicitLod | Op::ImageSampleDrefExplicitLod | Op::ImageSampleProjDrefImplicitLod | Op::ImageSampleProjDrefExplicitLod => { - let mut base_wc = 6; - inst.expect_at_least(base_wc)?; - let result_type_id = self.next()?; - let result_id = self.next()?; - let sampled_image_id = self.next()?; - let coordinate_id = self.next()?; - let dref_id = self.next()?; - - let mut level = crate::SampleLevel::Auto; - while base_wc < inst.wc { - let image_ops = self.next()?; - base_wc += 1; - match spirv::ImageOperands::from_bits_truncate(image_ops) { - spirv::ImageOperands::BIAS => { - let bias_expr = self.next()?; - let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; - level = crate::SampleLevel::Bias(bias_handle); - base_wc += 1; - } - spirv::ImageOperands::LOD => { - let lod_expr = self.next()?; - let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; - level = crate::SampleLevel::Exact(lod_handle); - base_wc += 1; - } - other => { - log::warn!("Skipping {:?}", other); - for _ in base_wc..inst.wc { - self.next()?; - } - break; - } - } - } - - let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; - let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let image_var_handle = expressions[si_lexp.image].as_global_var()?; - let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?; - log::debug!( - "\t\t\tImage {:?} sampled with comparison {:?}", - image_var_handle, - sampler_var_handle - ); - if let Some(flags) = self.handle_sampling.get_mut(&image_var_handle) { - *flags |= SamplingFlags::COMPARISON; - } - *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= - SamplingFlags::COMPARISON; - - let dref_lexp = self.lookup_expression.lookup(dref_id)?; - let dref_type_handle = self.lookup_type.lookup(dref_lexp.type_id)?.handle; - match type_arena[dref_type_handle].inner { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: _, - } => (), - _ => return Err(Error::InvalidDepthReference(dref_type_handle)), - } - - let image_var = &global_arena[image_var_handle]; - let (coordinate, array_index) = match type_arena[image_var.ty].inner { - crate::TypeInner::Image { - dim, - arrayed, - class: _, - } => extract_image_coordinates( - dim, - arrayed, - coord_lexp.handle, - coord_type_handle, - type_arena, - expressions, - ), - _ => return Err(Error::InvalidSampleImage(image_var.ty)), - }; - - let expr = crate::Expression::ImageSample { - image: si_lexp.image, - sampler: si_lexp.sampler, - coordinate, - array_index, - offset: None, //TODO - level, - depth_ref: Some(dref_lexp.handle), - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + let extra = inst.expect_at_least(6)?; + self.parse_image_sample_dref(extra, type_arena, global_arena, expressions)?; } Op::ImageQuerySize => { inst.expect(4)?; - let result_type_id = self.next()?; - let result_id = self.next()?; - let image_id = self.next()?; - - //TODO: handle arrays and cubes - let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); - - let expr = crate::Expression::ImageQuery { - image: image_lexp.handle, - query: crate::ImageQuery::Size { level: None }, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + self.parse_image_query_size(false, expressions)?; } Op::ImageQuerySizeLod => { inst.expect(5)?; - let result_type_id = self.next()?; - let result_id = self.next()?; - let image_id = self.next()?; - let level_id = self.next()?; - - //TODO: handle arrays and cubes - let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); - let level_lexp = self.lookup_expression.lookup(level_id)?.clone(); - - let expr = crate::Expression::ImageQuery { - image: image_lexp.handle, - query: crate::ImageQuery::Size { - level: Some(level_lexp.handle), - }, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + self.parse_image_query_size(true, expressions)?; } Op::ImageQueryLevels => { - let result_type_id = self.next()?; - let result_id = self.next()?; - let image_id = self.next()?; - - let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); - - let expr = crate::Expression::ImageQuery { - image: image_lexp.handle, - query: crate::ImageQuery::NumLevels, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + inst.expect(4)?; + self.parse_image_query_other(crate::ImageQuery::NumLevels, expressions)?; } Op::ImageQuerySamples => { - let result_type_id = self.next()?; - let result_id = self.next()?; - let image_id = self.next()?; - - let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); - - let expr = crate::Expression::ImageQuery { - image: image_lexp.handle, - query: crate::ImageQuery::NumSamples, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + inst.expect(4)?; + self.parse_image_query_other(crate::ImageQuery::NumSamples, expressions)?; } + // other ops Op::Select => { inst.expect(6)?; let result_type_id = self.next()?; @@ -1995,40 +1551,24 @@ impl> Parser { Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), Op::ConstantNull | Op::Undef => self.parse_null_constant(inst, &mut module), Op::Variable => self.parse_global_variable(inst, &mut module), - Op::Function => self.parse_function(inst, &mut module), + Op::Function => { + self.switch(ModuleState::Function, inst.op)?; + inst.expect(5)?; + self.parse_function(&mut module) + } _ => Err(Error::UnsupportedInstruction(self.state, inst.op)), //TODO }?; } // Check all the images and samplers to have consistent comparison property. for (handle, flags) in self.handle_sampling.drain() { - if !flags.contains(SamplingFlags::COMPARISON) { - continue; - } - if flags == SamplingFlags::all() { + if !image::patch_comparison_type( + flags, + module.global_variables.get_mut(handle), + &mut module.types, + ) { return Err(Error::InconsistentComparisonSampling(handle)); } - log::debug!("Flipping comparison for {:?}", handle); - let var = module.global_variables.get_mut(handle); - let original_ty = &module.types[var.ty]; - let ty_inner = match original_ty.inner { - crate::TypeInner::Image { - class: _, - dim, - arrayed, - } => crate::TypeInner::Image { - class: crate::ImageClass::Depth, - dim, - arrayed, - }, - crate::TypeInner::Sampler { .. } => crate::TypeInner::Sampler { comparison: true }, - ref other => unreachable!("Unexpected type for comparison mutation: {:?}", other), - }; - let name = original_ty.name.clone(); - var.ty = module.types.append(crate::Type { - name, - inner: ty_inner, - }); } for (_, func) in module.functions.iter_mut() { @@ -2971,7 +2511,8 @@ impl> Parser { .can_comparison_sample() { log::debug!("\t\ttracking {:?} for sampling properties", handle); - self.handle_sampling.insert(handle, SamplingFlags::empty()); + self.handle_sampling + .insert(handle, image::SamplingFlags::empty()); } Ok(()) } From 5b94ecd9b2608ad3c03634498fa3bf0da1850f43 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 8 Feb 2021 12:30:21 -0500 Subject: [PATCH 0458/2212] Add a snapshot for parsing spirv input --- src/front/spv/mod.rs | 2 - src/front/spv/rosetta.rs | 23 - tests/in/shadow.spv | Bin 0 -> 4764 bytes tests/out/shadow.ron.snap | 1150 +++++++++++++++++++++++++++++++++++++ tests/snapshots.rs | 25 + 5 files changed, 1175 insertions(+), 25 deletions(-) delete mode 100644 src/front/spv/rosetta.rs create mode 100644 tests/in/shadow.spv create mode 100644 tests/out/shadow.ron.snap diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e37f94972..e13753ab4 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -16,8 +16,6 @@ mod error; mod flow; mod function; mod image; -#[cfg(all(test, feature = "serialize"))] -mod rosetta; use convert::*; use error::Error; diff --git a/src/front/spv/rosetta.rs b/src/front/spv/rosetta.rs deleted file mode 100644 index 027c0d0ad..000000000 --- a/src/front/spv/rosetta.rs +++ /dev/null @@ -1,23 +0,0 @@ -use std::{fs, path::Path}; - -const TEST_PATH: &str = "test-data"; - -fn rosetta_test(file_name: &str) { - if true { - return; //TODO: fix this test - } - let file_path = Path::new(TEST_PATH).join(file_name); - let input = fs::read(&file_path).unwrap(); - - let module = super::parse_u8_slice(&input, &Default::default()).unwrap(); - let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); - - let expected = fs::read_to_string(file_path.with_extension("expected.ron")).unwrap(); - - difference::assert_diff!(output.as_str(), expected.as_str(), "", 0); -} - -#[test] -fn simple() { - rosetta_test("simple/simple.spv") -} diff --git a/tests/in/shadow.spv b/tests/in/shadow.spv new file mode 100644 index 0000000000000000000000000000000000000000..265cf65fc08335dfb5180801283e218430a0fd67 GIT binary patch literal 4764 zcmZve2X|Ig7KU$3v499-FPMmq9ebtQ!i;eQdk>!=5KZ#MB z55>5T-{xs5PQ@%rMm{Z>b;%w%2`{=GlcK0 z_xIGgOLi#UGp#Qi>@0f^^G&}y|8{2fY_|liwA;{~TU)*A*B0JvJAXY>V`nh8x@-K9 zDDyqbYQDDlE^}%_>Tu4CI7jK`RbqTLMpw87bbC#!aLyt(6FC1IWDA&G+KuITH=^4+ z&)#^K`|<2ID)pvPug?_^xX_LGuxO9?K~?+XnRTchCxUKvQ=fSK98o zC>Bpm+xc0;w&%clDgA3;tbD&?@`hAf3q5P@$j-Ib1jZ!RCt@UaD{xsydjv2(?X}Te zX^%p8@Aeskw2x@xEXRg!9ewMu+x3wf(|yzMnVUc@b!976HdkR8J27mZP1mNJ&=#dE zicP57if&HcjkY=3ZNTM>TOpm#b9c|XAzMKM$g`V>?y}xwq-X0HXip8>J+(2zbfmSc z{U@Zn^~d4sK+2i-XQXj*&ZX^hFQ@;o(2aKv=kj@V>7Ru(*81r`9No1M{!V0`|G4-K zB`3c*^UOikfV26WYg>Ch(%N#)rtNc`vn>eS`0VZb(`EkYNMo(7-5s|5GrkAirN0l^ z0G!Ky+Wv0j^z#}kbF~|6Rf9zvut>?}c+l{f~uS-OuB2F8xm;tNVE> z?CO4=4$k;zLa)yAESyXK%g9yl>lK|W{jVXb{az2d+V73vjDIuqYQMMO8i4+l;jixR z12~udkC4@VABSD-_epTZe;RtV-)9y7SLltve19L>eplr7;vz!g6J7Le3^oDQQvU_n9Jc(A*yiY0PA1Ry zx!*wF<=U;t@t_UlEZd?xqbs@X(B&GyOuB4^+#VRKFS#Ai{XY8MJ}=_7K{r-k*4qi) zdhTs0ah}_b!1?v9h}=J*o3Af>OhC7XSQ2qtqZ_L)d+dxZ?@DeLbUF92h_1UKcL&~2 zAGUMs8r;nIUhjczEpzo9P0uZmdjikW^UM1Cpt~=hx#ac>uDaKK;oPe}&&j@f1M~GA zAOAn!3*A1>px?TFBfV>V`>+$AJNaqAH63{8`y(gf^E)~TcqeNHHx)T0xV4c!D+eIW zQ+~%p2OrAK5VaP+kpKg$bq^7@vc3>Z4{2d&Hboo2bcQiN#IGeh&I=i;KwmI5LXYl)W9PnInrjyWfFALD; zf_b0|WXx&k8FM=NDZn^+&!8JQ8_4$n^ZXX~g4tpF4mbnU!DZxVpA3wV-8Is8ul4LJWIkn{foJ?B3g{jb0{dGq{U{{_e|269V~ zX94+hfVG_OTp(}EQsf1|eiwr5cM*E_TZVoiEJUjnk>yB7TlV4S>p*C8(l^4ACFH~KOleN}U*wUB25=hL6h z#r^2{TEND0J_O{S1-b9%f;aDF^p}ABUIE$fRrKul8v2XCIC=A4N4@~$ z-w5tac!e-hlM$ajGJXCV81 z9(>;G7ufFEIrRDc^Ine!`n-cB!5xc!9MCs~+nR)w^F4Pk()XM)=l&nMb1x>}d-^Ys p8wJeQCujZvNb?Uwn(qu>1AF-W9fSNPxMrmJUk3LxPmtfEUjed&gEasE literal 0 HcmV?d00001 diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap new file mode 100644 index 000000000..e42f1c2ce --- /dev/null +++ b/tests/out/shadow.ron.snap @@ -0,0 +1,1150 @@ +--- +source: tests/snapshots.rs +expression: output +--- +( + header: ( + version: (1, 0, 0), + generator: 0, + ), + types: [ + ( + name: None, + inner: Scalar( + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Tri, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Scalar( + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Quad, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Scalar( + kind: Bool, + width: 1, + ), + ), + ( + name: None, + inner: Vector( + size: Bi, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Image( + dim: D2, + arrayed: true, + class: Sampled( + kind: Float, + multi: false, + ), + ), + ), + ( + name: None, + inner: Sampler( + comparison: false, + ), + ), + ( + name: None, + inner: Vector( + size: Bi, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Scalar( + kind: Sint, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Quad, + kind: Uint, + width: 4, + ), + ), + ( + name: Some("Globals"), + inner: Struct( + block: true, + members: [ + ( + name: Some("num_lights"), + span: None, + ty: 11, + ), + ], + ), + ), + ( + name: None, + inner: Matrix( + columns: Quad, + rows: Quad, + width: 4, + ), + ), + ( + name: Some("Light"), + inner: Struct( + block: true, + members: [ + ( + name: Some("proj"), + span: None, + ty: 13, + ), + ( + name: Some("pos"), + span: None, + ty: 4, + ), + ( + name: Some("color"), + span: None, + ty: 4, + ), + ], + ), + ), + ( + name: None, + inner: Array( + base: 14, + size: Dynamic, + stride: Some(96), + ), + ), + ( + name: Some("Lights"), + inner: Struct( + block: true, + members: [ + ( + name: Some("data"), + span: None, + ty: 15, + ), + ], + ), + ), + ( + name: None, + inner: Image( + dim: D2, + arrayed: true, + class: Depth, + ), + ), + ( + name: None, + inner: Sampler( + comparison: true, + ), + ), + ], + constants: [ + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(0.5), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(-0.5), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(0.05000000074505806), + ), + ), + ( + name: None, + specialization: None, + inner: Composite( + ty: 2, + components: [ + 5, + 5, + 5, + ], + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(10), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(2), + ), + ), + ], + global_variables: [ + ( + name: Some("t_shadow"), + class: Handle, + binding: Some(Resource( + group: 0, + binding: 2, + )), + ty: 17, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("sampler_shadow"), + class: Handle, + binding: Some(Resource( + group: 0, + binding: 3, + )), + ty: 18, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("u_globals"), + class: Uniform, + binding: Some(Resource( + group: 0, + binding: 0, + )), + ty: 12, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("s_lights"), + class: Storage, + binding: Some(Resource( + group: 0, + binding: 1, + )), + ty: 16, + init: None, + interpolation: None, + storage_access: ( + bits: 1, + ), + ), + ( + name: Some("in_position_fs"), + class: Input, + binding: Some(Location(1)), + ty: 4, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("in_normal_fs"), + class: Input, + binding: Some(Location(0)), + ty: 2, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("out_color_fs"), + class: Output, + binding: Some(Location(0)), + ty: 4, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ], + functions: [ + ( + name: None, + arguments: [ + ( + name: None, + ty: 3, + ), + ( + name: None, + ty: 4, + ), + ], + return_type: Some(1), + global_usage: [ + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + local_variables: [], + expressions: [ + GlobalVariable(3), + GlobalVariable(6), + GlobalVariable(5), + GlobalVariable(1), + GlobalVariable(2), + GlobalVariable(4), + GlobalVariable(7), + Constant(16), + Constant(3), + Constant(29), + Constant(27), + Constant(25), + Constant(23), + Constant(21), + Constant(11), + Constant(8), + Constant(19), + Constant(4), + Constant(32), + Constant(30), + Constant(10), + Constant(28), + Constant(26), + Constant(13), + Constant(22), + Constant(35), + Constant(9), + Constant(7), + Constant(5), + Constant(2), + Constant(17), + Constant(31), + Constant(15), + Constant(33), + Constant(14), + Constant(24), + Constant(12), + Constant(20), + Constant(34), + Constant(18), + Constant(6), + Constant(1), + FunctionArgument(0), + FunctionArgument(1), + AccessIndex( + base: 44, + index: 3, + ), + Binary( + op: LessEqual, + left: 45, + right: 42, + ), + AccessIndex( + base: 44, + index: 0, + ), + AccessIndex( + base: 44, + index: 1, + ), + Compose( + ty: 9, + components: [ + 47, + 48, + ], + ), + Compose( + ty: 9, + components: [ + 9, + 18, + ], + ), + Binary( + op: Multiply, + left: 49, + right: 50, + ), + AccessIndex( + base: 44, + index: 3, + ), + Binary( + op: Divide, + left: 30, + right: 52, + ), + Binary( + op: Multiply, + left: 51, + right: 53, + ), + Compose( + ty: 9, + components: [ + 9, + 9, + ], + ), + Binary( + op: Add, + left: 54, + right: 55, + ), + AccessIndex( + base: 56, + index: 0, + ), + AccessIndex( + base: 56, + index: 1, + ), + As( + expr: 43, + kind: Sint, + convert: false, + ), + As( + expr: 59, + kind: Float, + convert: true, + ), + Compose( + ty: 2, + components: [ + 57, + 58, + 60, + ], + ), + AccessIndex( + base: 44, + index: 2, + ), + AccessIndex( + base: 44, + index: 3, + ), + Binary( + op: Divide, + left: 30, + right: 63, + ), + Binary( + op: Multiply, + left: 62, + right: 64, + ), + AccessIndex( + base: 61, + index: 0, + ), + AccessIndex( + base: 61, + index: 1, + ), + Compose( + ty: 6, + components: [ + 66, + 67, + ], + ), + AccessIndex( + base: 61, + index: 2, + ), + As( + expr: 69, + kind: Uint, + convert: true, + ), + ImageSample( + image: 4, + sampler: 5, + coordinate: 68, + array_index: Some(70), + offset: None, + level: Exact(21), + depth_ref: Some(65), + ), + ], + body: [ + If( + condition: 46, + accept: [ + Return( + value: Some(30), + ), + ], + reject: [], + ), + Return( + value: Some(71), + ), + ], + ), + ], + entry_points: { + (Fragment, "fs_main"): ( + early_depth_test: None, + workgroup_size: (0, 0, 0), + function: ( + name: Some("fs_main"), + arguments: [], + return_type: None, + global_usage: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 2, + ), + ], + local_variables: [ + ( + name: Some("color"), + ty: 2, + init: Some(6), + ), + ( + name: Some("i"), + ty: 3, + init: Some(8), + ), + ], + expressions: [ + GlobalVariable(3), + GlobalVariable(6), + GlobalVariable(5), + GlobalVariable(1), + GlobalVariable(2), + GlobalVariable(4), + GlobalVariable(7), + Constant(16), + Constant(3), + Constant(29), + Constant(27), + Constant(25), + Constant(23), + Constant(21), + Constant(11), + Constant(8), + Constant(19), + Constant(4), + Constant(32), + Constant(30), + Constant(10), + Constant(28), + Constant(26), + Constant(13), + Constant(22), + Constant(35), + Constant(9), + Constant(7), + Constant(5), + Constant(2), + Constant(17), + Constant(31), + Constant(15), + Constant(33), + Constant(14), + Constant(24), + Constant(12), + Constant(20), + Constant(34), + Constant(18), + Constant(6), + Constant(1), + LocalVariable(1), + LocalVariable(2), + AccessIndex( + base: 1, + index: 0, + ), + Access( + base: 45, + index: 37, + ), + Math( + fun: Min, + arg: 46, + arg1: Some(28), + arg2: None, + ), + Binary( + op: GreaterEqual, + left: 44, + right: 47, + ), + AccessIndex( + base: 6, + index: 0, + ), + Access( + base: 49, + index: 44, + ), + AccessIndex( + base: 50, + index: 0, + ), + Binary( + op: Multiply, + left: 51, + right: 3, + ), + Call( + function: 1, + arguments: [ + 44, + 52, + ], + ), + Math( + fun: Normalize, + arg: 2, + arg1: None, + arg2: None, + ), + AccessIndex( + base: 6, + index: 0, + ), + Access( + base: 55, + index: 44, + ), + AccessIndex( + base: 56, + index: 1, + ), + Access( + base: 57, + index: 31, + ), + AccessIndex( + base: 6, + index: 0, + ), + Access( + base: 59, + index: 44, + ), + AccessIndex( + base: 60, + index: 1, + ), + Access( + base: 61, + index: 38, + ), + AccessIndex( + base: 6, + index: 0, + ), + Access( + base: 63, + index: 44, + ), + AccessIndex( + base: 64, + index: 1, + ), + Access( + base: 65, + index: 13, + ), + Compose( + ty: 2, + components: [ + 58, + 62, + 66, + ], + ), + Access( + base: 3, + index: 36, + ), + Access( + base: 3, + index: 12, + ), + Access( + base: 3, + index: 23, + ), + Compose( + ty: 2, + components: [ + 68, + 69, + 70, + ], + ), + Binary( + op: Subtract, + left: 67, + right: 71, + ), + Math( + fun: Normalize, + arg: 72, + arg1: None, + arg2: None, + ), + Math( + fun: Dot, + arg: 54, + arg1: Some(73), + arg2: None, + ), + Math( + fun: Max, + arg: 42, + arg1: Some(74), + arg2: None, + ), + Binary( + op: Multiply, + left: 53, + right: 75, + ), + AccessIndex( + base: 6, + index: 0, + ), + Access( + base: 77, + index: 44, + ), + AccessIndex( + base: 78, + index: 2, + ), + Access( + base: 79, + index: 10, + ), + AccessIndex( + base: 6, + index: 0, + ), + Access( + base: 81, + index: 44, + ), + AccessIndex( + base: 82, + index: 2, + ), + Access( + base: 83, + index: 19, + ), + AccessIndex( + base: 6, + index: 0, + ), + Access( + base: 85, + index: 44, + ), + AccessIndex( + base: 86, + index: 2, + ), + Access( + base: 87, + index: 26, + ), + Compose( + ty: 2, + components: [ + 80, + 84, + 88, + ], + ), + Binary( + op: Multiply, + left: 89, + right: 76, + ), + Binary( + op: Add, + left: 43, + right: 90, + ), + Binary( + op: Add, + left: 44, + right: 27, + ), + Compose( + ty: 4, + components: [ + 43, + 30, + ], + ), + ], + body: [ + Loop( + body: [ + If( + condition: 48, + accept: [ + Break, + ], + reject: [], + ), + Store( + pointer: 43, + value: 91, + ), + Store( + pointer: 44, + value: 92, + ), + Continue, + ], + continuing: [ + Store( + pointer: 44, + value: 92, + ), + ], + ), + Store( + pointer: 7, + value: 93, + ), + Return( + value: None, + ), + ], + ), + ), + }, +) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 934160c5c..40b472fb5 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -208,3 +208,28 @@ fn convert_wgsl_shadow() { fn convert_wgsl_texture_array() { convert_wgsl("texture-array", Language::SPIRV); } + +#[cfg(feature = "spv-in")] +fn convert_spv(name: &str) { + let module = naga::front::spv::parse_u8_slice( + &std::fs::read(format!("tests/in/{}{}", name, ".spv")).expect("Couldn't find spv file"), + &Default::default(), + ) + .unwrap(); + naga::proc::Validator::new().validate(&module).unwrap(); + + #[cfg(feature = "serialize")] + { + let config = ron::ser::PrettyConfig::default(); + let output = ron::ser::to_string_pretty(&module, config).unwrap(); + with_snapshot_settings(|| { + insta::assert_snapshot!(format!("{}.ron", name), output); + }); + } +} + +#[cfg(feature = "spv-in")] +#[test] +fn convert_spv_shadow() { + convert_spv("shadow"); +} From 4f19903f465b6970054b29b1750235e5e9b83ca5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 9 Feb 2021 00:39:47 -0500 Subject: [PATCH 0459/2212] [wgsl] fix variable initializers wrt control flow --- src/front/wgsl/mod.rs | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f82b51950..de1628961 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1565,6 +1565,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: StatementContext<'a, '_, '_>, + is_uniform_control_flow: bool, ) -> Result, Error<'a>> { let word = match lexer.next() { Token::Separator(';') => return Ok(None), @@ -1572,7 +1573,8 @@ impl Parser { self.scopes.push(Scope::Block); let mut statements = Vec::new(); while !lexer.skip(Token::Paren('}')) { - let s = self.parse_statement(lexer, context.reborrow())?; + let s = + self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)?; statements.extend(s); } self.scopes.pop(); @@ -1606,10 +1608,11 @@ impl Parser { let init = if lexer.skip(Token::Operation('=')) { let value = self.parse_general_expression(lexer, context.as_expression())?; - if let crate::Expression::Constant(handle) = context.expressions[value] { - Init::Constant(handle) - } else { - Init::Variable(value) + match context.expressions[value] { + crate::Expression::Constant(handle) if is_uniform_control_flow => { + Init::Constant(handle) + } + _ => Init::Variable(value), } } else { Init::Empty @@ -1652,9 +1655,9 @@ impl Parser { let condition = self.parse_general_expression(lexer, context.as_expression())?; lexer.expect(Token::Paren(')'))?; - let accept = self.parse_block(lexer, context.reborrow())?; + let accept = self.parse_block(lexer, context.reborrow(), false)?; let reject = if lexer.skip(Token::Word("else")) { - self.parse_block(lexer, context.reborrow())? + self.parse_block(lexer, context.reborrow(), false)? } else { Vec::new() }; @@ -1707,7 +1710,7 @@ impl Parser { if lexer.skip(Token::Paren('}')) { break false; } - let s = self.parse_statement(lexer, context.reborrow())?; + let s = self.parse_statement(lexer, context.reborrow(), false)?; body.extend(s); }; @@ -1719,7 +1722,7 @@ impl Parser { } Token::Word("default") => { lexer.expect(Token::Separator(':'))?; - default = self.parse_block(lexer, context.reborrow())?; + default = self.parse_block(lexer, context.reborrow(), false)?; } Token::Paren('}') => break, other => return Err(Error::Unexpected(other, "switch item")), @@ -1739,14 +1742,14 @@ impl Parser { loop { if lexer.skip(Token::Word("continuing")) { - continuing = self.parse_block(lexer, context.reborrow())?; + continuing = self.parse_block(lexer, context.reborrow(), false)?; lexer.expect(Token::Paren('}'))?; break; } if lexer.skip(Token::Paren('}')) { break; } - let s = self.parse_statement(lexer, context.reborrow())?; + let s = self.parse_statement(lexer, context.reborrow(), false)?; body.extend(s); } @@ -1786,12 +1789,13 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: StatementContext<'a, '_, '_>, + is_uniform_control_flow: bool, ) -> Result, Error<'a>> { self.scopes.push(Scope::Block); lexer.expect(Token::Paren('{'))?; let mut statements = Vec::new(); while !lexer.skip(Token::Paren('}')) { - let s = self.parse_statement(lexer, context.reborrow())?; + let s = self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)?; statements.extend(s); } self.scopes.pop(); @@ -1866,6 +1870,7 @@ impl Parser { functions: &module.functions, arguments: &fun.arguments, }, + true, )?; // fixup the IR ensure_block_returns(&mut fun.body); From 3aa11838c73178ed4960dfa370c2e95e388c3dbc Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 10 Feb 2021 00:56:50 -0500 Subject: [PATCH 0460/2212] Refactor the global usage code into a separate module, fix inheriting from the callees --- src/front/global_usage.rs | 111 ++++++++++++++++++++++++++++++++++++ src/front/glsl/functions.rs | 2 +- src/front/mod.rs | 2 + src/front/spv/function.rs | 2 +- src/front/wgsl/mod.rs | 2 +- src/proc/interface.rs | 102 --------------------------------- tests/out/shadow.msl.snap | 4 +- tests/out/shadow.ron.snap | 4 +- 8 files changed, 121 insertions(+), 108 deletions(-) create mode 100644 src/front/global_usage.rs diff --git a/src/front/global_usage.rs b/src/front/global_usage.rs new file mode 100644 index 000000000..0cc5fa866 --- /dev/null +++ b/src/front/global_usage.rs @@ -0,0 +1,111 @@ +use crate::{ + arena::{Arena, Handle}, + proc::{Interface, Visitor}, +}; + +struct GlobalUseVisitor<'a> { + usage: &'a mut [crate::GlobalUse], + functions: &'a Arena, +} + +impl Visitor for GlobalUseVisitor<'_> { + fn visit_expr(&mut self, expr: &crate::Expression) { + if let crate::Expression::GlobalVariable(handle) = expr { + self.usage[handle.index()] |= crate::GlobalUse::READ; + } + } + + fn visit_lhs_expr(&mut self, expr: &crate::Expression) { + if let crate::Expression::GlobalVariable(handle) = expr { + self.usage[handle.index()] |= crate::GlobalUse::WRITE; + } + } + + fn visit_fun(&mut self, fun: Handle) { + for (mine, other) in self.usage.iter_mut().zip(&self.functions[fun].global_usage) { + *mine |= *other; + } + } +} + +impl crate::Function { + pub fn fill_global_use(&mut self, globals_num: usize, functions: &Arena) { + self.global_usage.clear(); + self.global_usage + .resize(globals_num, crate::GlobalUse::empty()); + + let mut io = Interface { + expressions: &self.expressions, + local_variables: &self.local_variables, + visitor: GlobalUseVisitor { + usage: &mut self.global_usage, + functions, + }, + }; + io.traverse(&self.body); + } +} + +#[test] +fn global_usage_scan() { + let test_global = crate::GlobalVariable { + name: None, + class: crate::StorageClass::Uniform, + binding: None, + ty: Handle::new(std::num::NonZeroU32::new(1).unwrap()), + init: None, + interpolation: None, + storage_access: crate::StorageAccess::empty(), + }; + let mut test_globals = Arena::new(); + + let global_1 = test_globals.append(test_global.clone()); + let global_2 = test_globals.append(test_global.clone()); + let global_3 = test_globals.append(test_global.clone()); + let global_4 = test_globals.append(test_global); + + let mut expressions = Arena::new(); + let global_1_expr = expressions.append(crate::Expression::GlobalVariable(global_1)); + let global_2_expr = expressions.append(crate::Expression::GlobalVariable(global_2)); + let global_3_expr = expressions.append(crate::Expression::GlobalVariable(global_3)); + let global_4_expr = expressions.append(crate::Expression::GlobalVariable(global_4)); + + let test_body = vec![ + crate::Statement::Return { + value: Some(global_1_expr), + }, + crate::Statement::Store { + pointer: global_2_expr, + value: global_1_expr, + }, + crate::Statement::Store { + pointer: expressions.append(crate::Expression::Access { + base: global_3_expr, + index: global_4_expr, + }), + value: global_1_expr, + }, + ]; + + let mut function = crate::Function { + name: None, + arguments: Vec::new(), + return_type: None, + local_variables: Arena::new(), + expressions, + global_usage: Vec::new(), + body: test_body, + }; + let other_functions = Arena::new(); + function.fill_global_use(test_globals.len(), &other_functions); + + assert_eq!( + &function.global_usage, + &[ + crate::GlobalUse::READ, + crate::GlobalUse::WRITE, + crate::GlobalUse::WRITE, + crate::GlobalUse::READ, + ], + ) +} diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 1fe37ca1c..0e8e6a458 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -272,7 +272,7 @@ impl Program { self.context.typifier = Typifier::new(); ensure_block_returns(&mut block); f.body = block; - f.fill_global_use(&self.module.global_variables); + f.fill_global_use(self.module.global_variables.len(), &self.module.functions); f } } diff --git a/src/front/mod.rs b/src/front/mod.rs index cb543c72a..13ad35841 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,5 +1,7 @@ //! Parsers which load shaders into memory. +mod global_usage; + #[cfg(feature = "glsl-in")] pub mod glsl; #[cfg(feature = "spv-in")] diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index c0283eb23..0ffbbf8e9 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -146,7 +146,7 @@ impl> super::Parser { fun.body = flow_graph.to_naga()?; // done - fun.fill_global_use(&module.global_variables); + fun.fill_global_use(module.global_variables.len(), &module.functions); let dump_suffix = match self.lookup_entry_point.remove(&fun_id) { Some(ep) => { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index de1628961..32123deec 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1875,7 +1875,7 @@ impl Parser { // fixup the IR ensure_block_returns(&mut fun.body); // done - fun.fill_global_use(&module.global_variables); + fun.fill_global_use(module.global_variables.len(), &module.functions); self.scopes.pop(); Ok((fun, fun_name)) diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 36326a7ed..13f6f1f71 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -216,105 +216,3 @@ where } } } - -struct GlobalUseVisitor<'a>(&'a mut [crate::GlobalUse]); - -impl Visitor for GlobalUseVisitor<'_> { - fn visit_expr(&mut self, expr: &crate::Expression) { - if let crate::Expression::GlobalVariable(handle) = expr { - self.0[handle.index()] |= crate::GlobalUse::READ; - } - } - - fn visit_lhs_expr(&mut self, expr: &crate::Expression) { - if let crate::Expression::GlobalVariable(handle) = expr { - self.0[handle.index()] |= crate::GlobalUse::WRITE; - } - } -} - -impl crate::Function { - pub fn fill_global_use(&mut self, globals: &Arena) { - self.global_usage.clear(); - self.global_usage - .resize(globals.len(), crate::GlobalUse::empty()); - - let mut io = Interface { - expressions: &self.expressions, - local_variables: &self.local_variables, - visitor: GlobalUseVisitor(&mut self.global_usage), - }; - io.traverse(&self.body); - } -} - -#[cfg(test)] -mod tests { - use crate::{ - Arena, Expression, GlobalUse, GlobalVariable, Handle, Statement, StorageAccess, - StorageClass, - }; - - #[test] - fn global_use_scan() { - let test_global = GlobalVariable { - name: None, - class: StorageClass::Uniform, - binding: None, - ty: Handle::new(std::num::NonZeroU32::new(1).unwrap()), - init: None, - interpolation: None, - storage_access: StorageAccess::empty(), - }; - let mut test_globals = Arena::new(); - - let global_1 = test_globals.append(test_global.clone()); - let global_2 = test_globals.append(test_global.clone()); - let global_3 = test_globals.append(test_global.clone()); - let global_4 = test_globals.append(test_global); - - let mut expressions = Arena::new(); - let global_1_expr = expressions.append(Expression::GlobalVariable(global_1)); - let global_2_expr = expressions.append(Expression::GlobalVariable(global_2)); - let global_3_expr = expressions.append(Expression::GlobalVariable(global_3)); - let global_4_expr = expressions.append(Expression::GlobalVariable(global_4)); - - let test_body = vec![ - Statement::Return { - value: Some(global_1_expr), - }, - Statement::Store { - pointer: global_2_expr, - value: global_1_expr, - }, - Statement::Store { - pointer: expressions.append(Expression::Access { - base: global_3_expr, - index: global_4_expr, - }), - value: global_1_expr, - }, - ]; - - let mut function = crate::Function { - name: None, - arguments: Vec::new(), - return_type: None, - local_variables: Arena::new(), - expressions, - global_usage: Vec::new(), - body: test_body, - }; - function.fill_global_use(&test_globals); - - assert_eq!( - &function.global_usage, - &[ - GlobalUse::READ, - GlobalUse::WRITE, - GlobalUse::WRITE, - GlobalUse::READ, - ], - ) - } -} diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 0d62314ac..986efb089 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -65,7 +65,9 @@ struct fs_mainOutput { fragment fs_mainOutput fs_main( fs_mainInput input [[stage_in]], constant Globals& u_globals [[buffer(0)]], - constant Lights& s_lights [[buffer(1)]] + constant Lights& s_lights [[buffer(1)]], + type4 t_shadow [[texture(0)]], + type5 sampler_shadow [[sampler(0)]] ) { fs_mainOutput output; type10 color1 = type10(0.05, 0.05, 0.05); diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index e42f1c2ce..7a7e6c233 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -799,10 +799,10 @@ expression: output return_type: None, global_usage: [ ( - bits: 0, + bits: 1, ), ( - bits: 0, + bits: 1, ), ( bits: 1, From bfbb30b37551b62fb06697f55c91089bd5489c4b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 5 Feb 2021 15:12:08 -0500 Subject: [PATCH 0461/2212] Add CI action for validation of native shaders --- .github/workflows/validation.yml | 16 ++++++++++++++++ .gitignore | 1 + Makefile | 2 +- 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/validation.yml diff --git a/.github/workflows/validation.yml b/.github/workflows/validation.yml new file mode 100644 index 000000000..6b73690f4 --- /dev/null +++ b/.github/workflows/validation.yml @@ -0,0 +1,16 @@ +name: validation +on: + pull_request: + paths: + - 'tests/snapshots/*.snap' + +jobs: + linux: + name: SPIR-V and GLSL + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + - name: Install tools + run: sudo apt-get install spirv-tools glslang-tools + - run: make validate-spv + - run: make validate-glsl diff --git a/.gitignore b/.gitignore index bdef2e67f..40440d9b5 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ **/*.rs.bk Cargo.lock .DS_Store +.fuse_hidden* .idea /*.dot /*.metal diff --git a/Makefile b/Makefile index 294ab4f1e..fea66b622 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all clean validate-spv validate-msl +.PHONY: all clean validate-spv validate-msl validate-glsl .SECONDARY: boids.metal quad.metal SNAPSHOTS_IN=tests/in SNAPSHOTS_OUT=tests/out From 3b4935550d150cbb8d405781e4cc3d78078e11f9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 10 Feb 2021 22:44:48 -0500 Subject: [PATCH 0462/2212] Separate validation job on macOS --- .../{validation.yml => validation-linux.yml} | 9 +++++---- .github/workflows/validation-macos.yml | 13 +++++++++++++ Makefile | 10 +++++----- 3 files changed, 23 insertions(+), 9 deletions(-) rename .github/workflows/{validation.yml => validation-linux.yml} (67%) create mode 100644 .github/workflows/validation-macos.yml diff --git a/.github/workflows/validation.yml b/.github/workflows/validation-linux.yml similarity index 67% rename from .github/workflows/validation.yml rename to .github/workflows/validation-linux.yml index 6b73690f4..94929aebf 100644 --- a/.github/workflows/validation.yml +++ b/.github/workflows/validation-linux.yml @@ -1,12 +1,13 @@ -name: validation +name: validation-linux on: pull_request: paths: - - 'tests/snapshots/*.snap' + - 'tests/out/*.spvasm.snap' + - 'tests/out/*.glsl.snap' jobs: - linux: - name: SPIR-V and GLSL + validate-linux: + name: SPIR-V + GLSL runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/validation-macos.yml b/.github/workflows/validation-macos.yml new file mode 100644 index 000000000..850e9f08c --- /dev/null +++ b/.github/workflows/validation-macos.yml @@ -0,0 +1,13 @@ +name: validation-macos +on: + pull_request: + paths: + - 'tests/out/*.msl.snap' + +jobs: + validate-macos: + name: MSL + runs-on: macos-latest + steps: + - uses: actions/checkout@v2 + - run: make validate-msl diff --git a/Makefile b/Makefile index fea66b622..58aad1941 100644 --- a/Makefile +++ b/Makefile @@ -26,27 +26,27 @@ clean: glslangValidator $@ validate-spv: $(SNAPSHOTS_OUT)/*.spvasm.snap - @for file in $^ ; do \ + @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ tail -n +5 $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ done validate-msl: $(SNAPSHOTS_OUT)/*.msl.snap - @for file in $^ ; do \ + @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ tail -n +5 $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ done validate-glsl: $(SNAPSHOTS_OUT)/*.glsl.snap - @for file in $(SNAPSHOTS_OUT)/*-Vertex.glsl.snap ; do \ + @set -e && for file in $(SNAPSHOTS_OUT)/*-Vertex.glsl.snap ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ tail -n +5 $${file} | glslangValidator --stdin -S vert; \ done - @for file in $(SNAPSHOTS_OUT)/*-Fragment.glsl.snap ; do \ + @set -e && for file in $(SNAPSHOTS_OUT)/*-Fragment.glsl.snap ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ tail -n +5 $${file} | glslangValidator --stdin -S frag; \ done - @for file in $(SNAPSHOTS_OUT)/*-Compute.glsl.snap ; do \ + @set -e && for file in $(SNAPSHOTS_OUT)/*-Compute.glsl.snap ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ tail -n +5 $${file} | glslangValidator --stdin -S comp; \ done From dad02eb0a8cbc9f5209b80923267770a36527e21 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 10 Feb 2021 17:02:21 -0500 Subject: [PATCH 0463/2212] [msl-out] support all binary ops --- src/back/msl/writer.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 75f814b20..d1529847d 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -424,7 +424,12 @@ impl Writer { crate::BinaryOperator::Greater => ">", crate::BinaryOperator::GreaterEqual => ">=", crate::BinaryOperator::And => "&", - _ => return Err(Error::UnsupportedBinaryOp(op)), + crate::BinaryOperator::ExclusiveOr => "^", + crate::BinaryOperator::InclusiveOr => "|", + crate::BinaryOperator::LogicalAnd => "&&", + crate::BinaryOperator::LogicalOr => "||", + crate::BinaryOperator::ShiftLeft => "<<", + crate::BinaryOperator::ShiftRight => ">>", }; let kind = self .typifier From 20227e7c87467186fd0865a3f89d62a697078b05 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 10 Feb 2021 21:31:12 -0500 Subject: [PATCH 0464/2212] [msl] pass-through global resources in arguments --- src/back/msl/writer.rs | 122 ++++++++++++++++++++++++++++---------- tests/out/shadow.msl.snap | 6 +- 2 files changed, 96 insertions(+), 32 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index d1529847d..8fb22119f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -7,6 +7,7 @@ use crate::{ use std::{ fmt::{Display, Error as FmtError, Formatter}, io::Write, + iter, }; const NAMESPACE: &str = "metal"; @@ -96,6 +97,22 @@ fn separate(is_last: bool) -> &'static str { } } +impl crate::StorageClass { + /// Returns true for storage classes, for which the global + /// variables are passed in function arguments. + /// These arguments need to be passed through any functions + /// called from the entry point. + fn needs_pass_through(&self) -> bool { + match *self { + crate::StorageClass::Input + | crate::StorageClass::Uniform + | crate::StorageClass::Storage + | crate::StorageClass::Handle => true, + _ => false, + } + } +} + enum FunctionOrigin { Handle(Handle), EntryPoint(EntryPointIndex), @@ -123,22 +140,57 @@ impl Writer { self.out } - fn put_call( + fn put_call_parameters( &mut self, - name: &str, + parameters: impl Iterator>, + context: &ExpressionContext, + ) -> Result<(), Error> { + write!(self.out, "(")?; + for (i, handle) in parameters.enumerate() { + if i != 0 { + write!(self.out, ", ")?; + } + self.put_expression(handle, context)?; + } + write!(self.out, ")")?; + Ok(()) + } + + fn put_local_call( + &mut self, + fun_handle: Handle, parameters: &[Handle], context: &ExpressionContext, ) -> Result<(), Error> { - if !name.is_empty() { - write!(self.out, "metal::{}", name)?; - } - write!(self.out, "(")?; + let fun = &context.module.functions[fun_handle]; + let fun_name = &self.names[&NameKey::Function(fun_handle)]; + write!(self.out, "{}(", fun_name)?; + // first, write down the actual arguments for (i, &handle) in parameters.iter().enumerate() { if i != 0 { write!(self.out, ", ")?; } self.put_expression(handle, context)?; } + // follow-up with any global resources used + let mut separate = !parameters.is_empty(); + for ((handle, var), &usage) in context + .module + .global_variables + .iter() + .zip(&fun.global_usage) + { + if !usage.is_empty() && var.class.needs_pass_through() { + let name = &self.names[&NameKey::GlobalVariable(handle)]; + if separate { + write!(self.out, ", ")?; + } else { + separate = true; + } + write!(self.out, "{}", name)?; + } + } + // done write!(self.out, ")")?; Ok(()) } @@ -201,8 +253,8 @@ impl Writer { let inner = &context.module.types[ty].inner; match *inner { crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { - write!(self.out, "{}", scalar_kind_string(kind),)?; - self.put_call("", components, context)?; + write!(self.out, "{}", scalar_kind_string(kind))?; + self.put_call_parameters(components.iter().cloned(), context)?; } crate::TypeInner::Vector { size, kind, .. } => { write!( @@ -212,7 +264,7 @@ impl Writer { scalar_kind_string(kind), vector_size_string(size) )?; - self.put_call("", components, context)?; + self.put_call_parameters(components.iter().cloned(), context)?; } crate::TypeInner::Matrix { columns, rows, .. } => { let kind = crate::ScalarKind::Float; @@ -224,7 +276,7 @@ impl Writer { vector_size_string(columns), vector_size_string(rows) )?; - self.put_call("", components, context)?; + self.put_call_parameters(components.iter().cloned(), context)?; } _ => return Err(Error::UnsupportedCompose(ty)), } @@ -469,7 +521,8 @@ impl Writer { crate::DerivativeAxis::Y => "dfdy", crate::DerivativeAxis::Width => "fwidth", }; - self.put_call(op, &[expr], context)?; + write!(self.out, "{}::{}", NAMESPACE, op)?; + self.put_call_parameters(iter::once(expr), context)?; } crate::Expression::Relational { fun, argument } => { let op = match fun { @@ -480,7 +533,8 @@ impl Writer { crate::RelationalFunction::IsFinite => "isfinite", crate::RelationalFunction::IsNormal => "isnormal", }; - self.put_call(op, &[argument], context)?; + write!(self.out, "{}::{}", NAMESPACE, op)?; + self.put_call_parameters(iter::once(argument), context)?; } crate::Expression::Math { fun, @@ -546,17 +600,8 @@ impl Writer { Mf::ReverseBits => "reverse_bits", }; - write!(self.out, "metal::{}(", fun_name)?; - self.put_expression(arg, context)?; - if let Some(arg) = arg1 { - write!(self.out, ", ")?; - self.put_expression(arg, context)?; - } - if let Some(arg) = arg2 { - write!(self.out, ", ")?; - self.put_expression(arg, context)?; - } - write!(self.out, ")")?; + write!(self.out, "{}::{}", NAMESPACE, fun_name)?; + self.put_call_parameters(iter::once(arg).chain(arg1).chain(arg2), context)?; } crate::Expression::As { expr, @@ -578,9 +623,7 @@ impl Writer { function, ref arguments, } => { - let name = &self.names[&NameKey::Function(function)]; - write!(self.out, "{}", name)?; - self.put_call("", arguments, context)?; + self.put_local_call(function, arguments, context)?; } crate::Expression::ArrayLength(expr) => match *self .typifier @@ -750,9 +793,7 @@ impl Writer { function, ref arguments, } => { - let name = &self.names[&NameKey::Function(function)]; - write!(self.out, "{}", name)?; - self.put_call("", arguments, context)?; + self.put_local_call(function, arguments, context)?; writeln!(self.out, ";")?; } } @@ -917,6 +958,7 @@ impl Writer { module: &crate::Module, options: &Options, ) -> Result { + let mut pass_through_globals = Vec::new(); for (fun_handle, fun) in module.functions.iter() { self.typifier.resolve_all( &fun.expressions, @@ -930,6 +972,13 @@ impl Writer { }, )?; + pass_through_globals.clear(); + for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { + if !usage.is_empty() && var.class.needs_pass_through() { + pass_through_globals.push(handle); + } + } + let fun_name = &self.names[&NameKey::Function(fun_handle)]; let result_type_name = match fun.return_type { Some(ret_ty) => &self.names[&NameKey::Type(ret_ty)], @@ -940,13 +989,26 @@ impl Writer { for (index, arg) in fun.arguments.iter().enumerate() { let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; let param_type_name = &self.names[&NameKey::Type(arg.ty)]; - let separator = separate(index + 1 == fun.arguments.len()); + let separator = + separate(pass_through_globals.is_empty() && index + 1 == fun.arguments.len()); writeln!( self.out, "{}{} {}{}", INDENT, param_type_name, name, separator )?; } + for (index, &handle) in pass_through_globals.iter().enumerate() { + let tyvar = TypedGlobalVariable { + module, + names: &self.names, + handle, + usage: fun.global_usage[handle.index()], + }; + let separator = separate(index + 1 == pass_through_globals.len()); + write!(self.out, "{}", INDENT)?; + tyvar.try_fmt(&mut self.out)?; + writeln!(self.out, "{}", separator)?; + } writeln!(self.out, ") {{")?; for (local_handle, local) in fun.local_variables.iter() { diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 986efb089..2a8f90f46 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -45,7 +45,9 @@ typedef bool type11; type7 fetch_shadow( type6 light_id, - type2 homogeneous_coords + type2 homogeneous_coords, + type4 t_shadow, + type5 sampler_shadow ) { if ((homogeneous_coords.w <= 0.0)) { return 1.0; @@ -81,7 +83,7 @@ fragment fs_mainOutput fs_main( if ((i >= metal::min(u_globals.num_lights.x, 10u))) { break; } - color1 = (color1 + ((fetch_shadow(i, (s_lights.data[i].proj * input.in_position_fs)) * metal::max(0.0, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(s_lights.data[i].pos.x, s_lights.data[i].pos.y, s_lights.data[i].pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(s_lights.data[i].color.x, s_lights.data[i].color.y, s_lights.data[i].color.z))); + color1 = (color1 + ((fetch_shadow(i, (s_lights.data[i].proj * input.in_position_fs), t_shadow, sampler_shadow) * metal::max(0.0, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(s_lights.data[i].pos.x, s_lights.data[i].pos.y, s_lights.data[i].pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(s_lights.data[i].color.x, s_lights.data[i].color.y, s_lights.data[i].color.z))); } output.out_color_fs = metal::float4(color1, 1.0); return output; From c04c9719073b1a2fa839e1b3ca00bbcff163e906 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 10 Feb 2021 18:35:08 +0000 Subject: [PATCH 0465/2212] [glsl-in] Fix StorageClass for texture and sampler --- src/front/glsl/parser.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 1cf4150d0..bb7d473b9 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1087,7 +1087,7 @@ pomelo! { }).unwrap_or(StorageQualifier::StorageClass(StorageClass::Private)); match storage { - StorageQualifier::StorageClass(class) => { + StorageQualifier::StorageClass(storage_class) => { // TODO: Check that the storage qualifiers allow for the bindings let binding = d.type_qualifiers.iter().find_map(|tq| { if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } @@ -1100,6 +1100,16 @@ pomelo! { for (id, initializer) in d.ids_initializers { let init = initializer.map(|init| extra.solve_constant(init.expression)).transpose()?; + // use StorageClass::Handle for texture and sampler uniforms + let class = if storage_class == StorageClass::Uniform { + match extra.module.types[d.ty].inner { + TypeInner::Image{..} | TypeInner::Sampler{..} => StorageClass::Handle, + _ => storage_class, + } + } else { + storage_class + }; + let h = extra.module.global_variables.fetch_or_append( GlobalVariable { name: id.clone(), From 2507794bc64e2228e56113b1c57081b52081d395 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 10 Feb 2021 16:04:07 -0500 Subject: [PATCH 0466/2212] [spv-in] add more capabilities we support --- src/front/spv/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e13753ab4..46dc68add 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -32,9 +32,15 @@ use std::{convert::TryInto, num::NonZeroU32, path::PathBuf}; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, + spirv::Capability::ClipDistance, spirv::Capability::CullDistance, spirv::Capability::ImageQuery, + spirv::Capability::Image1D, + spirv::Capability::ImageCubeArray, + spirv::Capability::ImageMSArray, spirv::Capability::StorageImageExtendedFormats, + spirv::Capability::Sampled1D, + spirv::Capability::SampledCubeArray, ]; pub const SUPPORTED_EXTENSIONS: &[&str] = &[]; pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"]; From 49eb93cf7dfdf154d26a02c0e500422dc58b5d78 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 10 Feb 2021 16:09:54 -0500 Subject: [PATCH 0467/2212] [spv-in] support boolean constants --- src/front/spv/mod.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 46dc68add..1a78c8057 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1554,6 +1554,8 @@ impl> Parser { Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), Op::ConstantNull | Op::Undef => self.parse_null_constant(inst, &mut module), + Op::ConstantTrue => self.parse_bool_constant(inst, true, &mut module), + Op::ConstantFalse => self.parse_bool_constant(inst, false, &mut module), Op::Variable => self.parse_global_variable(inst, &mut module), Op::Function => { self.switch(ModuleState::Function, inst.op)?; @@ -2398,6 +2400,34 @@ impl> Parser { Ok(()) } + fn parse_bool_constant( + &mut self, + inst: Instruction, + value: bool, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(3)?; + let type_id = self.next()?; + let id = self.next()?; + + self.lookup_constant.insert( + id, + LookupConstant { + handle: module.constants.append(crate::Constant { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + specialization: None, //TODO + inner: crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(value), + }, + }), + type_id, + }, + ); + Ok(()) + } + fn parse_global_variable( &mut self, inst: Instruction, From 38f3c4eb192350fa2aa3dba9fec62ae2b4046cda Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 10 Feb 2021 16:54:48 -0500 Subject: [PATCH 0468/2212] [spv-in] support dynamic vector insert/extract --- src/front/spv/error.rs | 1 + src/front/spv/mod.rs | 112 +++++++++++++++++++++++++++++ src/proc/validator.rs | 2 +- tests/out/shadow.ron.snap | 146 +++++++++++++++++++++++--------------- 4 files changed, 203 insertions(+), 58 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index d05213643..194c279b8 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -43,6 +43,7 @@ pub enum Error { InvalidSampleImage(Handle), InvalidDepthReference(Handle), InvalidAsType(Handle), + InvalidVectorType(Handle), InconsistentComparisonSampling(Handle), WrongFunctionResultType(spirv::Word), WrongFunctionArgumentType(spirv::Word), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 1a78c8057..f8945c6ea 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -321,6 +321,7 @@ pub struct Parser { deferred_function_calls: FastHashMap, spirv::Word>, dummy_functions: Arena, options: Options, + index_constants: Vec>, } impl> Parser { @@ -347,6 +348,7 @@ impl> Parser { deferred_function_calls: FastHashMap::default(), dummy_functions: Arena::new(), options: options.clone(), + index_constants: Vec::new(), } } @@ -760,6 +762,103 @@ impl> Parser { }; self.lookup_expression.insert(result_id, lookup_expression); } + Op::VectorExtractDynamic => { + inst.expect(5)?; + let result_type_id = self.next()?; + let id = self.next()?; + let composite_id = self.next()?; + let index_id = self.next()?; + + let root_lexp = self.lookup_expression.lookup(composite_id)?; + let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; + let index_lexp = self.lookup_expression.lookup(index_id)?; + + let num_components = match type_arena[root_type_lookup.handle].inner { + crate::TypeInner::Vector { size, .. } => size as usize, + _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), + }; + + let mut index_expr = + expressions.append(crate::Expression::Constant(self.index_constants[0])); + let mut handle = expressions.append(crate::Expression::Access { + base: root_lexp.handle, + index: index_expr, + }); + for &index in self.index_constants[1..num_components].iter() { + index_expr = expressions.append(crate::Expression::Constant(index)); + let access_expr = expressions.append(crate::Expression::Access { + base: root_lexp.handle, + index: index_expr, + }); + let cond = expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Equal, + left: index_expr, + right: index_lexp.handle, + }); + handle = expressions.append(crate::Expression::Select { + condition: cond, + accept: access_expr, + reject: handle, + }); + } + + self.lookup_expression.insert( + id, + LookupExpression { + handle, + type_id: result_type_id, + }, + ); + } + Op::VectorInsertDynamic => { + inst.expect(6)?; + let result_type_id = self.next()?; + let id = self.next()?; + let composite_id = self.next()?; + let object_id = self.next()?; + let index_id = self.next()?; + + let object_lexp = self.lookup_expression.lookup(object_id)?; + let root_lexp = self.lookup_expression.lookup(composite_id)?; + let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; + let index_lexp = self.lookup_expression.lookup(index_id)?; + + let num_components = match type_arena[root_type_lookup.handle].inner { + crate::TypeInner::Vector { size, .. } => size as usize, + _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), + }; + let mut components = Vec::with_capacity(num_components); + for &index in self.index_constants[..num_components].iter() { + let index_expr = expressions.append(crate::Expression::Constant(index)); + let access_expr = expressions.append(crate::Expression::Access { + base: root_lexp.handle, + index: index_expr, + }); + let cond = expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Equal, + left: index_expr, + right: index_lexp.handle, + }); + let handle = expressions.append(crate::Expression::Select { + condition: cond, + accept: object_lexp.handle, + reject: access_expr, + }); + components.push(handle); + } + let handle = expressions.append(crate::Expression::Compose { + ty: root_type_lookup.handle, + components, + }); + + self.lookup_expression.insert( + id, + LookupExpression { + handle, + type_id: result_type_id, + }, + ); + } Op::CompositeExtract => { inst.expect_at_least(4)?; let result_type_id = self.next()?; @@ -1521,6 +1620,19 @@ impl> Parser { crate::Module::generate_empty() }; + self.index_constants.clear(); + for i in 0..4 { + let handle = module.constants.append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(i), + }, + }); + self.index_constants.push(handle); + } + while let Ok(inst) = self.next_inst() { use spirv::Op; log::debug!("\t{:?} [{}]", inst.op, inst.wc); diff --git a/src/proc/validator.rs b/src/proc/validator.rs index b41972955..628a5c48c 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -194,7 +194,7 @@ impl crate::GlobalVariable { }, Bi::FrontFacing => Ti::Scalar { kind: Sk::Bool, - width, + width: 1, }, Bi::GlobalInvocationId | Bi::LocalInvocationId diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index 7a7e6c233..dd89e4874 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -174,6 +174,38 @@ expression: output ), ], constants: [ + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(3), + ), + ), ( name: None, specialization: None, @@ -220,9 +252,9 @@ expression: output inner: Composite( ty: 2, components: [ - 5, - 5, - 5, + 9, + 9, + 9, ], ), ), @@ -596,41 +628,41 @@ expression: output GlobalVariable(2), GlobalVariable(4), GlobalVariable(7), - Constant(16), - Constant(3), + Constant(20), + Constant(7), + Constant(33), + Constant(31), Constant(29), Constant(27), Constant(25), + Constant(15), + Constant(12), Constant(23), - Constant(21), - Constant(11), Constant(8), - Constant(19), - Constant(4), + Constant(36), + Constant(34), + Constant(14), Constant(32), Constant(30), - Constant(10), - Constant(28), - Constant(26), - Constant(13), - Constant(22), - Constant(35), - Constant(9), - Constant(7), - Constant(5), - Constant(2), Constant(17), - Constant(31), - Constant(15), - Constant(33), - Constant(14), - Constant(24), - Constant(12), - Constant(20), - Constant(34), - Constant(18), + Constant(26), + Constant(39), + Constant(13), + Constant(11), + Constant(9), Constant(6), - Constant(1), + Constant(21), + Constant(35), + Constant(19), + Constant(37), + Constant(18), + Constant(28), + Constant(16), + Constant(24), + Constant(38), + Constant(22), + Constant(10), + Constant(5), FunctionArgument(0), FunctionArgument(1), AccessIndex( @@ -824,12 +856,12 @@ expression: output ( name: Some("color"), ty: 2, - init: Some(6), + init: Some(10), ), ( name: Some("i"), ty: 3, - init: Some(8), + init: Some(12), ), ], expressions: [ @@ -840,41 +872,41 @@ expression: output GlobalVariable(2), GlobalVariable(4), GlobalVariable(7), - Constant(16), - Constant(3), + Constant(20), + Constant(7), + Constant(33), + Constant(31), Constant(29), Constant(27), Constant(25), + Constant(15), + Constant(12), Constant(23), - Constant(21), - Constant(11), Constant(8), - Constant(19), - Constant(4), + Constant(36), + Constant(34), + Constant(14), Constant(32), Constant(30), - Constant(10), - Constant(28), - Constant(26), - Constant(13), - Constant(22), - Constant(35), - Constant(9), - Constant(7), - Constant(5), - Constant(2), Constant(17), - Constant(31), - Constant(15), - Constant(33), - Constant(14), - Constant(24), - Constant(12), - Constant(20), - Constant(34), - Constant(18), + Constant(26), + Constant(39), + Constant(13), + Constant(11), + Constant(9), Constant(6), - Constant(1), + Constant(21), + Constant(35), + Constant(19), + Constant(37), + Constant(18), + Constant(28), + Constant(16), + Constant(24), + Constant(38), + Constant(22), + Constant(10), + Constant(5), LocalVariable(1), LocalVariable(2), AccessIndex( From b3d80de9e1d9735041a0c25da278a79c62b2a6b7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 11 Feb 2021 11:20:05 -0500 Subject: [PATCH 0469/2212] [spv-out] fix the clippy warning about Result type --- src/back/spv/writer.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a0799106c..f15024643 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -334,15 +334,11 @@ impl Writer { ) } - fn create_pointer_type( - &mut self, - type_id: spirv::Word, - class: spirv::StorageClass, - ) -> Result { + fn create_pointer_type(&mut self, type_id: spirv::Word, class: spirv::StorageClass) -> Word { let id = self.generate_id(); let instruction = super::instructions::instruction_type_pointer(id, class, type_id); instruction.to_words(&mut self.logical_layout.declarations); - Ok(id) + id } fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word { @@ -1132,7 +1128,7 @@ impl Writer { RawExpression::Value(id) } RawExpression::Pointer(base_id, class) => { - let pointer_type_id = self.create_pointer_type(result_type_id, class)?; + let pointer_type_id = self.create_pointer_type(result_type_id, class); block .body @@ -1166,7 +1162,7 @@ impl Writer { RawExpression::Value(id) } RawExpression::Pointer(base_id, class) => { - let pointer_type_id = self.create_pointer_type(result_type_id, class)?; + let pointer_type_id = self.create_pointer_type(result_type_id, class); let const_ty_id = self.get_type_id( &ir_module.types, From 86bb611905ce16c315f2de14bf2beff9cc603697 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 11 Feb 2021 15:25:20 -0500 Subject: [PATCH 0470/2212] [wgsl] support select() --- src/front/wgsl/conv.rs | 1 + src/front/wgsl/mod.rs | 13 +++++++++++++ src/front/wgsl/tests.rs | 18 +++++++++++++++--- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index c15968484..a9362f3e5 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -99,6 +99,7 @@ pub fn get_scalar_type(word: &str) -> Option<(crate::ScalarKind, crate::Bytes)> "f32" => Some((crate::ScalarKind::Float, 4)), "i32" => Some((crate::ScalarKind::Sint, 4)), "u32" => Some((crate::ScalarKind::Uint, 4)), + "bool" => Some((crate::ScalarKind::Bool, 1)), _ => None, } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 32123deec..38aaf4095 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -443,6 +443,19 @@ impl Parser { arg1, arg2, }) + } else if name == "select" { + lexer.expect(Token::Paren('('))?; + let accept = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let reject = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let condition = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Expression::Select { + condition, + accept, + reject, + }) } else { // texture sampling match name { diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 72238dc1a..c0408415e 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -197,7 +197,19 @@ fn parse_texture_query() { #[test] fn parse_postfix() { - parse_str("fn foo() { const x: f32 = vec4(1.0, 2.0, 3.0, 4.0).xyz.rgbr.aaaa.wz.g; }") - .unwrap(); - parse_str("fn foo() { const x: f32 = fract(vec2(0.5, 1.0)).x; }").unwrap(); + parse_str( + "fn foo() { + const x: f32 = vec4(1.0, 2.0, 3.0, 4.0).xyz.rgbr.aaaa.wz.g; + const y: f32 = fract(vec2(0.5, x)).x; + }", + ) + .unwrap(); +} + +#[test] +fn parse_expressions() { + parse_str("fn foo() { + const x: f32 = select(0.0, 1.0, true); + const y: vec2 = select(vec2(1.0, 1.0), vec2(x, x), vec2(x < 0.5, x > 0.5)); + }").unwrap(); } From 9b358efea13017f3e033acce9c4a2c6c947d9a4d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 11 Feb 2021 16:41:09 -0500 Subject: [PATCH 0471/2212] [wgsl] support 'elseif' construct --- src/front/wgsl/mod.rs | 20 +++++++++++++++++++- src/front/wgsl/tests.rs | 5 +++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 38aaf4095..c2bb94e92 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1669,11 +1669,29 @@ impl Parser { lexer.expect(Token::Paren(')'))?; let accept = self.parse_block(lexer, context.reborrow(), false)?; - let reject = if lexer.skip(Token::Word("else")) { + let mut elsif_stack = Vec::new(); + while lexer.skip(Token::Word("elseif")) { + lexer.expect(Token::Paren('('))?; + let other_condition = + self.parse_general_expression(lexer, context.as_expression())?; + lexer.expect(Token::Paren(')'))?; + let other_block = self.parse_block(lexer, context.reborrow(), false)?; + elsif_stack.push((other_condition, other_block)); + } + let mut reject = if lexer.skip(Token::Word("else")) { self.parse_block(lexer, context.reborrow(), false)? } else { Vec::new() }; + // reverse-fold the else-if blocks + //Note: we may consider uplifting this to the IR + for (other_cond, other_block) in elsif_stack.drain(..).rev() { + reject = vec![crate::Statement::If { + condition: other_cond, + accept: other_block, + reject, + }]; + } Some(crate::Statement::If { condition, diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index c0408415e..4fdfc1088 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -104,6 +104,11 @@ fn parse_if() { discard; } else {} if (0 != 1) {} + if (false) { + return; + } elseif (true) { + return; + } else {} } ", ) From f3cab651bbdc125fb68682bcc3b009e2fa8cebde Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 11 Feb 2021 17:07:50 -0500 Subject: [PATCH 0472/2212] [spv-out] support Switch statements --- src/back/spv/instructions.rs | 20 ++++++++++ src/back/spv/writer.rs | 77 +++++++++++++++++++++++++++++++++--- 2 files changed, 92 insertions(+), 5 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index c7df1604c..982d85bfe 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -707,6 +707,26 @@ pub(super) fn instruction_branch_conditional( instruction } +pub struct Case { + pub value: Word, + pub label_id: Word, +} + +pub(super) fn instruction_switch( + selector_id: Word, + default_id: Word, + cases: &[Case], +) -> Instruction { + let mut instruction = Instruction::new(Op::Switch); + instruction.add_operand(selector_id); + instruction.add_operand(default_id); + for case in cases { + instruction.add_operand(case.value); + instruction.add_operand(case.label_id); + } + instruction +} + pub(super) fn instruction_kill() -> Instruction { Instruction::new(Op::Kill) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f15024643..e9bdda5ee 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1850,14 +1850,14 @@ impl Writer { block = Block::new(merge_id); } crate::Statement::If { - ref condition, + condition, ref accept, ref reject, } => { let condition_id = self.write_expression( ir_module, ir_function, - *condition, + condition, &mut block, function, )?; @@ -1902,9 +1902,76 @@ impl Writer { block = Block::new(merge_id); } - crate::Statement::Switch { .. } => { - log::error!("unimplemented Switch"); - return Err(Error::FeatureNotImplemented("switch")); + crate::Statement::Switch { + selector, + ref cases, + ref default, + } => { + let selector_id = self.write_expression( + ir_module, + ir_function, + selector, + &mut block, + function, + )?; + + let merge_id = self.generate_id(); + block + .body + .push(super::instructions::instruction_selection_merge( + merge_id, + spirv::SelectionControl::NONE, + )); + + let default_id = self.generate_id(); + let raw_cases = cases + .iter() + .map(|c| super::instructions::Case { + value: c.value as Word, + label_id: self.generate_id(), + }) + .collect::>(); + + function.consume( + block, + super::instructions::instruction_switch( + selector_id, + default_id, + &raw_cases, + ), + ); + + for (i, (case, raw_case)) in cases.iter().zip(raw_cases.iter()).enumerate() { + let case_finish_id = if case.fall_through { + match raw_cases.get(i + 1) { + Some(rc) => rc.label_id, + None => default_id, + } + } else { + merge_id + }; + self.write_block( + raw_case.label_id, + &case.body, + ir_module, + ir_function, + function, + Some(case_finish_id), + LoopContext::default(), + )?; + } + + self.write_block( + default_id, + default, + ir_module, + ir_function, + function, + Some(merge_id), + LoopContext::default(), + )?; + + block = Block::new(merge_id); } crate::Statement::Loop { ref body, From 141d2e76615c9cbdbe8bec7be4d65d01dc76994c Mon Sep 17 00:00:00 2001 From: Anthony Cowley Date: Fri, 12 Feb 2021 14:26:14 -0500 Subject: [PATCH 0473/2212] [wgsl] ignore offset decorations on struct fields naga does not require offset decorations on struct fields in WGSL source, and automatically adds them to spv output. The `tint` compiler does not automatically add them, and requires that they be present in the WGSL source. A potential confusion is that an spv binary missing required `OpMemberDecorate` instructions that set the field's offset will fail validation when run through `spirv-val`. But since naga automatically produces these offsets, the same spv binary passed through naga will be successfully validated. This change is to ignore these decorations in naga's WGSL front end so that the same WGSL source can be used with naga and tint to produce valid spv. --- src/front/wgsl/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index c2bb94e92..b66cfb713 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1197,6 +1197,12 @@ impl Parser { lexer.expect(Token::Paren(')'))?; ready = false; } + Token::Word("offset") if ready => { + lexer.expect(Token::Paren('('))?; + let _offset = lexer.next_uint_literal()?; + lexer.expect(Token::Paren(')'))?; + ready = false; + } other => return Err(Error::Unexpected(other, "decoration separator")), } } From 9c2a837a539f903f895feebc8a2b65fa78e589be Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Fri, 12 Feb 2021 10:25:47 -0330 Subject: [PATCH 0474/2212] [wgsl] track number of bytes consumed per token --- src/front/wgsl/lexer.rs | 186 ++++++++++++++++++++-------------------- src/front/wgsl/mod.rs | 1 + 2 files changed, 95 insertions(+), 92 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 3bd204279..5e07e29ce 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -58,101 +58,97 @@ fn consume_number(input: &str) -> (Token, &str) { } fn consume_token(mut input: &str) -> (Token<'_>, &str) { - loop { - input = input.trim_start(); - let mut chars = input.chars(); - let cur = match chars.next() { - Some(c) => c, - None => return (Token::End, input), - }; - break match cur { - ':' => { - input = chars.as_str(); - if chars.next() == Some(':') { - (Token::DoubleColon, chars.as_str()) - } else { - (Token::Separator(cur), input) - } + let mut chars = input.chars(); + let cur = match chars.next() { + Some(c) => c, + None => return (Token::End, input), + }; + match cur { + ':' => { + input = chars.as_str(); + if chars.next() == Some(':') { + (Token::DoubleColon, chars.as_str()) + } else { + (Token::Separator(cur), input) } - ';' | ',' => (Token::Separator(cur), chars.as_str()), - '.' => { - let og_chars = chars.as_str(); - match chars.next() { - Some('0'..='9') => consume_number(input), - _ => (Token::Separator(cur), og_chars), - } + } + ';' | ',' => (Token::Separator(cur), chars.as_str()), + '.' => { + let og_chars = chars.as_str(); + match chars.next() { + Some('0'..='9') => consume_number(input), + _ => (Token::Separator(cur), og_chars), } - '(' | ')' | '{' | '}' => (Token::Paren(cur), chars.as_str()), - '<' | '>' => { - input = chars.as_str(); - let next = chars.next(); - if next == Some('=') { - (Token::LogicalOperation(cur), chars.as_str()) - } else if next == Some(cur) { - (Token::ShiftOperation(cur), chars.as_str()) - } else { - (Token::Paren(cur), input) - } + } + '(' | ')' | '{' | '}' => (Token::Paren(cur), chars.as_str()), + '<' | '>' => { + input = chars.as_str(); + let next = chars.next(); + if next == Some('=') { + (Token::LogicalOperation(cur), chars.as_str()) + } else if next == Some(cur) { + (Token::ShiftOperation(cur), chars.as_str()) + } else { + (Token::Paren(cur), input) } - '[' | ']' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::DoubleParen(cur), chars.as_str()) - } else { - (Token::Paren(cur), input) - } + } + '[' | ']' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + (Token::DoubleParen(cur), chars.as_str()) + } else { + (Token::Paren(cur), input) } - '0'..='9' => consume_number(input), - 'a'..='z' | 'A'..='Z' | '_' => { - let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); - (Token::Word(word), rest) - } - '"' => { - let mut iter = chars.as_str().splitn(2, '"'); + } + '0'..='9' => consume_number(input), + 'a'..='z' | 'A'..='Z' | '_' => { + let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); + (Token::Word(word), rest) + } + '"' => { + let mut iter = chars.as_str().splitn(2, '"'); - // splitn returns an iterator with at least one element, so unwrapping is fine - let quote_content = iter.next().unwrap(); - if let Some(rest) = iter.next() { - (Token::String(quote_content), rest) - } else { - (Token::UnterminatedString, quote_content) - } + // splitn returns an iterator with at least one element, so unwrapping is fine + let quote_content = iter.next().unwrap(); + if let Some(rest) = iter.next() { + (Token::String(quote_content), rest) + } else { + (Token::UnterminatedString, quote_content) } - '/' if chars.as_str().starts_with('/') => { - match chars.position(|c| c == '\n' || c == '\r') { - Some(_) => { - input = chars.as_str(); - continue; - } - None => (Token::End, chars.as_str()), - } + } + '/' if chars.as_str().starts_with('/') => { + let _ = chars.position(|c| c == '\n' || c == '\r'); + (Token::Trivia, chars.as_str()) + } + '-' => { + let og_chars = chars.as_str(); + match chars.next() { + Some('>') => (Token::Arrow, chars.as_str()), + Some('0'..='9') | Some('.') => consume_number(input), + _ => (Token::Operation(cur), og_chars), } - '-' => { - let og_chars = chars.as_str(); - match chars.next() { - Some('>') => (Token::Arrow, chars.as_str()), - Some('0'..='9') | Some('.') => consume_number(input), - _ => (Token::Operation(cur), og_chars), - } + } + '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), + '!' => { + if chars.next() == Some('=') { + (Token::LogicalOperation(cur), chars.as_str()) + } else { + (Token::Operation(cur), input) } - '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), - '!' => { - if chars.next() == Some('=') { - (Token::LogicalOperation(cur), chars.as_str()) - } else { - (Token::Operation(cur), input) - } + } + '=' | '&' | '|' => { + input = chars.as_str(); + if chars.next() == Some(cur) { + (Token::LogicalOperation(cur), chars.as_str()) + } else { + (Token::Operation(cur), input) } - '=' | '&' | '|' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::LogicalOperation(cur), chars.as_str()) - } else { - (Token::Operation(cur), input) - } - } - _ => (Token::Unknown(cur), chars.as_str()), - }; + } + ' ' | '\n' | '\r' | '\t' => { + let (_, rest) = consume_any(input, |c| c == ' ' || c == '\n' || c == '\r' || c == '\t'); + (Token::Trivia, rest) + } + _ => (Token::Unknown(cur), chars.as_str()), } } @@ -168,9 +164,15 @@ impl<'a> Lexer<'a> { #[must_use] pub(super) fn next(&mut self) -> Token<'a> { - let (token, rest) = consume_token(self.input); - self.input = rest; - token + let original_len = self.input.len(); + loop { + let (token, rest) = consume_token(self.input); + self.input = rest; + if token != Token::Trivia { + let _bytes_read = original_len - self.input.len(); + return token; + } + } } #[must_use] @@ -197,6 +199,7 @@ impl<'a> Lexer<'a> { Token::Arrow => "->", Token::Unknown(_) => "unknown", Token::UnterminatedString => "string", + Token::Trivia => "trivia", Token::End => "", }; Err(Error::Unexpected(token, description)) @@ -204,9 +207,8 @@ impl<'a> Lexer<'a> { } pub(super) fn skip(&mut self, what: Token<'_>) -> bool { - let (token, rest) = consume_token(self.input); - if token == what { - self.input = rest; + if self.peek() == what { + let _ = self.next(); true } else { false diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b66cfb713..e2ed3c88c 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -38,6 +38,7 @@ pub enum Token<'a> { Arrow, Unknown(char), UnterminatedString, + Trivia, End, } From 9667a18980bac331b1d43d4219f8e3de28202576 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Sat, 13 Feb 2021 01:05:20 -0330 Subject: [PATCH 0475/2212] [wgsl] Avoid consuming token twice in some cases --- src/front/wgsl/lexer.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 5e07e29ce..a7eefe51d 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -162,6 +162,13 @@ impl<'a> Lexer<'a> { Lexer { input } } + fn peek_token_and_rest(&mut self) -> (Token<'a>, &'a str) { + let mut cloned = self.clone(); + let token = cloned.next(); + let rest = cloned.input; + (token, rest) + } + #[must_use] pub(super) fn next(&mut self) -> Token<'a> { let original_len = self.input.len(); @@ -177,7 +184,8 @@ impl<'a> Lexer<'a> { #[must_use] pub(super) fn peek(&mut self) -> Token<'a> { - self.clone().next() + let (token, _) = self.peek_token_and_rest(); + token } pub(super) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { @@ -207,8 +215,9 @@ impl<'a> Lexer<'a> { } pub(super) fn skip(&mut self, what: Token<'_>) -> bool { - if self.peek() == what { - let _ = self.next(); + let (peeked_token, rest) = self.peek_token_and_rest(); + if peeked_token == what { + self.input = rest; true } else { false From 89f62bc584cea78eee5c088ab4cab74db50bb98a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 12 Feb 2021 22:52:08 -0500 Subject: [PATCH 0476/2212] [spv-out] make instruction constructions to be methods --- src/back/spv/instructions.rs | 1447 +++++++++++++++++----------------- src/back/spv/mod.rs | 2 +- src/back/spv/writer.rs | 482 +++++------ 3 files changed, 908 insertions(+), 1023 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 982d85bfe..f4b50afb3 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -1,4 +1,4 @@ -use crate::back::spv::{helpers, Instruction}; +use super::helpers; use spirv::{Op, Word}; pub(super) enum Signedness { @@ -6,745 +6,728 @@ pub(super) enum Signedness { Signed = 1, } -// -// Debug Instructions -// - -pub(super) fn instruction_source( - source_language: spirv::SourceLanguage, - version: u32, -) -> Instruction { - let mut instruction = Instruction::new(Op::Source); - instruction.add_operand(source_language as u32); - instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); - instruction -} - -pub(super) fn instruction_name(target_id: Word, name: &str) -> Instruction { - let mut instruction = Instruction::new(Op::Name); - instruction.add_operand(target_id); - instruction.add_operands(helpers::string_to_words(name)); - instruction -} - -pub(super) fn instruction_member_name(target_id: Word, member: Word, name: &str) -> Instruction { - let mut instruction = Instruction::new(Op::MemberName); - instruction.add_operand(target_id); - instruction.add_operand(member); - instruction.add_operands(helpers::string_to_words(name)); - instruction -} - -// -// Annotation Instructions -// - -pub(super) fn instruction_decorate( - target_id: Word, - decoration: spirv::Decoration, - operands: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::Decorate); - instruction.add_operand(target_id); - instruction.add_operand(decoration as u32); - for operand in operands { - instruction.add_operand(*operand) - } - instruction -} - -pub(super) fn instruction_member_decorate( - target_id: Word, - member_index: Word, - decoration: spirv::Decoration, - operands: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::MemberDecorate); - instruction.add_operand(target_id); - instruction.add_operand(member_index); - instruction.add_operand(decoration as u32); - for operand in operands { - instruction.add_operand(*operand) - } - instruction -} - -// -// Extension Instructions -// - -pub(super) fn instruction_ext_inst_import(id: Word, name: &str) -> Instruction { - let mut instruction = Instruction::new(Op::ExtInstImport); - instruction.set_result(id); - instruction.add_operands(helpers::string_to_words(name)); - instruction -} - -pub(super) fn instruction_ext_inst( - set_id: Word, - op: spirv::GLOp, - result_type_id: Word, - id: Word, - operands: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::ExtInst); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(set_id); - instruction.add_operand(op as u32); - for operand in operands { - instruction.add_operand(*operand) - } - instruction -} - -// -// Mode-Setting Instructions -// - -pub(super) fn instruction_memory_model( - addressing_model: spirv::AddressingModel, - memory_model: spirv::MemoryModel, -) -> Instruction { - let mut instruction = Instruction::new(Op::MemoryModel); - instruction.add_operand(addressing_model as u32); - instruction.add_operand(memory_model as u32); - instruction -} - -pub(super) fn instruction_entry_point( - execution_model: spirv::ExecutionModel, - entry_point_id: Word, - name: &str, - interface_ids: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::EntryPoint); - instruction.add_operand(execution_model as u32); - instruction.add_operand(entry_point_id); - instruction.add_operands(helpers::string_to_words(name)); - - for interface_id in interface_ids { - instruction.add_operand(*interface_id); - } - - instruction -} - -pub(super) fn instruction_execution_mode( - entry_point_id: Word, - execution_mode: spirv::ExecutionMode, - args: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::ExecutionMode); - instruction.add_operand(entry_point_id); - instruction.add_operand(execution_mode as u32); - for arg in args { - instruction.add_operand(*arg); - } - instruction -} - -pub(super) fn instruction_capability(capability: spirv::Capability) -> Instruction { - let mut instruction = Instruction::new(Op::Capability); - instruction.add_operand(capability as u32); - instruction -} - -// -// Type-Declaration Instructions -// - -pub(super) fn instruction_type_void(id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeVoid); - instruction.set_result(id); - instruction -} - -pub(super) fn instruction_type_bool(id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeBool); - instruction.set_result(id); - instruction -} - -pub(super) fn instruction_type_int(id: Word, width: Word, signedness: Signedness) -> Instruction { - let mut instruction = Instruction::new(Op::TypeInt); - instruction.set_result(id); - instruction.add_operand(width); - instruction.add_operand(signedness as u32); - instruction -} - -pub(super) fn instruction_type_float(id: Word, width: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeFloat); - instruction.set_result(id); - instruction.add_operand(width); - instruction -} - -pub(super) fn instruction_type_vector( - id: Word, - component_type_id: Word, - component_count: crate::VectorSize, -) -> Instruction { - let mut instruction = Instruction::new(Op::TypeVector); - instruction.set_result(id); - instruction.add_operand(component_type_id); - instruction.add_operand(component_count as u32); - instruction -} - -pub(super) fn instruction_type_matrix( - id: Word, - column_type_id: Word, - column_count: crate::VectorSize, -) -> Instruction { - let mut instruction = Instruction::new(Op::TypeMatrix); - instruction.set_result(id); - instruction.add_operand(column_type_id); - instruction.add_operand(column_count as u32); - instruction -} - -pub(super) fn instruction_type_image( - id: Word, - sampled_type_id: Word, - dim: spirv::Dim, - arrayed: bool, - image_class: crate::ImageClass, -) -> Instruction { - let mut instruction = Instruction::new(Op::TypeImage); - instruction.set_result(id); - instruction.add_operand(sampled_type_id); - instruction.add_operand(dim as u32); - - let (depth, multi, sampled) = match image_class { - crate::ImageClass::Sampled { kind: _, multi } => (false, multi, true), - crate::ImageClass::Depth => (true, false, true), - crate::ImageClass::Storage(_) => (false, false, false), - }; - instruction.add_operand(depth as u32); - instruction.add_operand(arrayed as u32); - instruction.add_operand(multi as u32); - instruction.add_operand(sampled as u32); - - let format = match image_class { - crate::ImageClass::Storage(format) => match format { - crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8, - crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm, - crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui, - crate::StorageFormat::R8Sint => spirv::ImageFormat::R8i, - crate::StorageFormat::R16Uint => spirv::ImageFormat::R16ui, - crate::StorageFormat::R16Sint => spirv::ImageFormat::R16i, - crate::StorageFormat::R16Float => spirv::ImageFormat::R16f, - crate::StorageFormat::Rg8Unorm => spirv::ImageFormat::Rg8, - crate::StorageFormat::Rg8Snorm => spirv::ImageFormat::Rg8Snorm, - crate::StorageFormat::Rg8Uint => spirv::ImageFormat::Rg8ui, - crate::StorageFormat::Rg8Sint => spirv::ImageFormat::Rg8i, - crate::StorageFormat::R32Uint => spirv::ImageFormat::R32ui, - crate::StorageFormat::R32Sint => spirv::ImageFormat::R32i, - crate::StorageFormat::R32Float => spirv::ImageFormat::R32f, - crate::StorageFormat::Rg16Uint => spirv::ImageFormat::Rg16ui, - crate::StorageFormat::Rg16Sint => spirv::ImageFormat::Rg16i, - crate::StorageFormat::Rg16Float => spirv::ImageFormat::Rg16f, - crate::StorageFormat::Rgba8Unorm => spirv::ImageFormat::Rgba8, - crate::StorageFormat::Rgba8Snorm => spirv::ImageFormat::Rgba8Snorm, - crate::StorageFormat::Rgba8Uint => spirv::ImageFormat::Rgba8ui, - crate::StorageFormat::Rgba8Sint => spirv::ImageFormat::Rgba8i, - crate::StorageFormat::Rgb10a2Unorm => spirv::ImageFormat::Rgb10a2ui, - crate::StorageFormat::Rg11b10Float => spirv::ImageFormat::R11fG11fB10f, - crate::StorageFormat::Rg32Uint => spirv::ImageFormat::Rg32ui, - crate::StorageFormat::Rg32Sint => spirv::ImageFormat::Rg32i, - crate::StorageFormat::Rg32Float => spirv::ImageFormat::Rg32f, - crate::StorageFormat::Rgba16Uint => spirv::ImageFormat::Rgba16ui, - crate::StorageFormat::Rgba16Sint => spirv::ImageFormat::Rgba16i, - crate::StorageFormat::Rgba16Float => spirv::ImageFormat::Rgba16f, - crate::StorageFormat::Rgba32Uint => spirv::ImageFormat::Rgba32ui, - crate::StorageFormat::Rgba32Sint => spirv::ImageFormat::Rgba32i, - crate::StorageFormat::Rgba32Float => spirv::ImageFormat::Rgba32f, - }, - _ => spirv::ImageFormat::Unknown, - }; - - instruction.add_operand(format as u32); - instruction -} - -pub(super) fn instruction_type_sampler(id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeSampler); - instruction.set_result(id); - instruction -} - -pub(super) fn instruction_type_sampled_image(id: Word, image_type_id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeSampledImage); - instruction.set_result(id); - instruction.add_operand(image_type_id); - instruction -} - -pub(super) fn instruction_type_array( - id: Word, - element_type_id: Word, - length_id: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::TypeArray); - instruction.set_result(id); - instruction.add_operand(element_type_id); - instruction.add_operand(length_id); - instruction -} - -pub(super) fn instruction_type_runtime_array(id: Word, element_type_id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::TypeRuntimeArray); - instruction.set_result(id); - instruction.add_operand(element_type_id); - instruction -} - -pub(super) fn instruction_type_struct(id: Word, member_ids: &[Word]) -> Instruction { - let mut instruction = Instruction::new(Op::TypeStruct); - instruction.set_result(id); - - for member_id in member_ids { - instruction.add_operand(*member_id) - } - - instruction -} - -pub(super) fn instruction_type_pointer( - id: Word, - storage_class: spirv::StorageClass, - type_id: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::TypePointer); - instruction.set_result(id); - instruction.add_operand(storage_class as u32); - instruction.add_operand(type_id); - instruction -} - -pub(super) fn instruction_type_function( - id: Word, - return_type_id: Word, - parameter_ids: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::TypeFunction); - instruction.set_result(id); - instruction.add_operand(return_type_id); - - for parameter_id in parameter_ids { - instruction.add_operand(*parameter_id); - } - - instruction -} - -// -// Constant-Creation Instructions -// - -pub(super) fn instruction_constant_true(result_type_id: Word, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::ConstantTrue); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction -} - -pub(super) fn instruction_constant_false(result_type_id: Word, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::ConstantFalse); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction -} - -pub(super) fn instruction_constant(result_type_id: Word, id: Word, values: &[Word]) -> Instruction { - let mut instruction = Instruction::new(Op::Constant); - instruction.set_type(result_type_id); - instruction.set_result(id); - - for value in values { - instruction.add_operand(*value); - } - - instruction -} - -pub(super) fn instruction_constant_composite( - result_type_id: Word, - id: Word, - constituent_ids: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::ConstantComposite); - instruction.set_type(result_type_id); - instruction.set_result(id); - - for constituent_id in constituent_ids { - instruction.add_operand(*constituent_id); - } - - instruction -} - -// -// Memory Instructions -// - -pub(super) fn instruction_variable( - result_type_id: Word, - id: Word, - storage_class: spirv::StorageClass, - initializer_id: Option, -) -> Instruction { - let mut instruction = Instruction::new(Op::Variable); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(storage_class as u32); - - if let Some(initializer_id) = initializer_id { - instruction.add_operand(initializer_id); - } - - instruction -} - -pub(super) fn instruction_load( - result_type_id: Word, - id: Word, - pointer_id: Word, - memory_access: Option, -) -> Instruction { - let mut instruction = Instruction::new(Op::Load); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(pointer_id); - - if let Some(memory_access) = memory_access { - instruction.add_operand(memory_access.bits()); - } - - instruction -} - -pub(super) fn instruction_store( - pointer_type_id: Word, - object_id: Word, - memory_access: Option, -) -> Instruction { - let mut instruction = Instruction::new(Op::Store); - instruction.add_operand(pointer_type_id); - instruction.add_operand(object_id); - - if let Some(memory_access) = memory_access { - instruction.add_operand(memory_access.bits()); - } - - instruction -} - -pub(super) fn instruction_access_chain( - result_type_id: Word, - id: Word, - base_id: Word, - index_ids: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::AccessChain); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(base_id); - - for index_id in index_ids { - instruction.add_operand(*index_id); - } - - instruction -} - -// -// Function Instructions -// - -pub(super) fn instruction_function( - return_type_id: Word, - id: Word, - function_control: spirv::FunctionControl, - function_type_id: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::Function); - instruction.set_type(return_type_id); - instruction.set_result(id); - instruction.add_operand(function_control.bits()); - instruction.add_operand(function_type_id); - instruction -} - -pub(super) fn instruction_function_parameter(result_type_id: Word, id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::FunctionParameter); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction -} - -pub(super) fn instruction_function_end() -> Instruction { - Instruction::new(Op::FunctionEnd) -} - -pub(super) fn instruction_function_call( - result_type_id: Word, - id: Word, - function_id: Word, - argument_ids: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::FunctionCall); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(function_id); - - for argument_id in argument_ids { - instruction.add_operand(*argument_id); - } - - instruction -} - -// -// Image Instructions -// -pub(super) fn instruction_sampled_image( - result_type_id: Word, - id: Word, - image: Word, - sampler: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::SampledImage); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(image); - instruction.add_operand(sampler); - instruction -} - pub(super) enum SampleLod { Explicit, Implicit, } -pub(super) fn instruction_image_sample( - result_type_id: Word, - id: Word, - lod: SampleLod, - sampled_image: Word, - coordinates: Word, - depth_ref: Option, -) -> Instruction { - let op = match (lod, depth_ref) { - (SampleLod::Explicit, None) => Op::ImageSampleExplicitLod, - (SampleLod::Implicit, None) => Op::ImageSampleImplicitLod, - (SampleLod::Explicit, Some(_)) => Op::ImageSampleDrefExplicitLod, - (SampleLod::Implicit, Some(_)) => Op::ImageSampleDrefImplicitLod, - }; - - let mut instruction = Instruction::new(op); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(sampled_image); - instruction.add_operand(coordinates); - if let Some(dref) = depth_ref { - instruction.add_operand(dref); - } - - instruction -} - -// -// Conversion Instructions -// -pub(super) fn instruction_unary( - op: Op, - result_type_id: Word, - id: Word, - value: Word, -) -> Instruction { - let mut instruction = Instruction::new(op); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(value); - instruction -} - -// -// Composite Instructions -// - -pub(super) fn instruction_composite_construct( - result_type_id: Word, - id: Word, - constituent_ids: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::CompositeConstruct); - instruction.set_type(result_type_id); - instruction.set_result(id); - - for constituent_id in constituent_ids { - instruction.add_operand(*constituent_id); - } - - instruction -} - -pub(super) fn instruction_composite_extract( - result_type_id: Word, - id: Word, - composite_id: Word, - indices: &[Word], -) -> Instruction { - let mut instruction = Instruction::new(Op::CompositeExtract); - instruction.set_type(result_type_id); - instruction.set_result(id); - - instruction.add_operand(composite_id); - for index in indices { - instruction.add_operand(*index); - } - - instruction -} - -pub(super) fn instruction_vector_extract_dynamic( - result_type_id: Word, - id: Word, - vector_id: Word, - index_id: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::VectorExtractDynamic); - instruction.set_type(result_type_id); - instruction.set_result(id); - - instruction.add_operand(vector_id); - instruction.add_operand(index_id); - - instruction -} - -// -// Arithmetic Instructions -// -pub(super) fn instruction_binary( - op: Op, - result_type_id: Word, - id: Word, - operand_1: Word, - operand_2: Word, -) -> Instruction { - let mut instruction = Instruction::new(op); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(operand_1); - instruction.add_operand(operand_2); - instruction -} - -// -// Bit Instructions -// - -// -// Relational and Logical Instructions -// - -// -// Derivative Instructions -// - -// -// Control-Flow Instructions -// - -pub(super) fn instruction_selection_merge( - merge_id: Word, - selection_control: spirv::SelectionControl, -) -> Instruction { - let mut instruction = Instruction::new(Op::SelectionMerge); - instruction.add_operand(merge_id); - instruction.add_operand(selection_control.bits()); - instruction -} - -pub(super) fn instruction_loop_merge( - merge_id: Word, - continuing_id: Word, - selection_control: spirv::SelectionControl, -) -> Instruction { - let mut instruction = Instruction::new(Op::LoopMerge); - instruction.add_operand(merge_id); - instruction.add_operand(continuing_id); - instruction.add_operand(selection_control.bits()); - instruction -} - -pub(super) fn instruction_label(id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::Label); - instruction.set_result(id); - instruction -} - -pub(super) fn instruction_branch(id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::Branch); - instruction.add_operand(id); - instruction -} - -// TODO Branch Weights not implemented. -pub(super) fn instruction_branch_conditional( - condition_id: Word, - true_label: Word, - false_label: Word, -) -> Instruction { - let mut instruction = Instruction::new(Op::BranchConditional); - instruction.add_operand(condition_id); - instruction.add_operand(true_label); - instruction.add_operand(false_label); - instruction -} - -pub struct Case { +pub(super) struct Case { pub value: Word, pub label_id: Word, } -pub(super) fn instruction_switch( - selector_id: Word, - default_id: Word, - cases: &[Case], -) -> Instruction { - let mut instruction = Instruction::new(Op::Switch); - instruction.add_operand(selector_id); - instruction.add_operand(default_id); - for case in cases { - instruction.add_operand(case.value); - instruction.add_operand(case.label_id); +impl super::Instruction { + // + // Debug Instructions + // + + pub(super) fn source(source_language: spirv::SourceLanguage, version: u32) -> Self { + let mut instruction = Self::new(Op::Source); + instruction.add_operand(source_language as u32); + instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); + instruction } - instruction + + pub(super) fn name(target_id: Word, name: &str) -> Self { + let mut instruction = Self::new(Op::Name); + instruction.add_operand(target_id); + instruction.add_operands(helpers::string_to_words(name)); + instruction + } + + pub(super) fn member_name(target_id: Word, member: Word, name: &str) -> Self { + let mut instruction = Self::new(Op::MemberName); + instruction.add_operand(target_id); + instruction.add_operand(member); + instruction.add_operands(helpers::string_to_words(name)); + instruction + } + + // + // Annotation Instructions + // + + pub(super) fn decorate( + target_id: Word, + decoration: spirv::Decoration, + operands: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::Decorate); + instruction.add_operand(target_id); + instruction.add_operand(decoration as u32); + for operand in operands { + instruction.add_operand(*operand) + } + instruction + } + + pub(super) fn member_decorate( + target_id: Word, + member_index: Word, + decoration: spirv::Decoration, + operands: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::MemberDecorate); + instruction.add_operand(target_id); + instruction.add_operand(member_index); + instruction.add_operand(decoration as u32); + for operand in operands { + instruction.add_operand(*operand) + } + instruction + } + + // + // Extension Instructions + // + + pub(super) fn ext_inst_import(id: Word, name: &str) -> Self { + let mut instruction = Self::new(Op::ExtInstImport); + instruction.set_result(id); + instruction.add_operands(helpers::string_to_words(name)); + instruction + } + + pub(super) fn ext_inst( + set_id: Word, + op: spirv::GLOp, + result_type_id: Word, + id: Word, + operands: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::ExtInst); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(set_id); + instruction.add_operand(op as u32); + for operand in operands { + instruction.add_operand(*operand) + } + instruction + } + + // + // Mode-Setting Instructions + // + + pub(super) fn memory_model( + addressing_model: spirv::AddressingModel, + memory_model: spirv::MemoryModel, + ) -> Self { + let mut instruction = Self::new(Op::MemoryModel); + instruction.add_operand(addressing_model as u32); + instruction.add_operand(memory_model as u32); + instruction + } + + pub(super) fn entry_point( + execution_model: spirv::ExecutionModel, + entry_point_id: Word, + name: &str, + interface_ids: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::EntryPoint); + instruction.add_operand(execution_model as u32); + instruction.add_operand(entry_point_id); + instruction.add_operands(helpers::string_to_words(name)); + + for interface_id in interface_ids { + instruction.add_operand(*interface_id); + } + + instruction + } + + pub(super) fn execution_mode( + entry_point_id: Word, + execution_mode: spirv::ExecutionMode, + args: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::ExecutionMode); + instruction.add_operand(entry_point_id); + instruction.add_operand(execution_mode as u32); + for arg in args { + instruction.add_operand(*arg); + } + instruction + } + + pub(super) fn capability(capability: spirv::Capability) -> Self { + let mut instruction = Self::new(Op::Capability); + instruction.add_operand(capability as u32); + instruction + } + + // + // Type-Declaration Instructions + // + + pub(super) fn type_void(id: Word) -> Self { + let mut instruction = Self::new(Op::TypeVoid); + instruction.set_result(id); + instruction + } + + pub(super) fn type_bool(id: Word) -> Self { + let mut instruction = Self::new(Op::TypeBool); + instruction.set_result(id); + instruction + } + + pub(super) fn type_int(id: Word, width: Word, signedness: Signedness) -> Self { + let mut instruction = Self::new(Op::TypeInt); + instruction.set_result(id); + instruction.add_operand(width); + instruction.add_operand(signedness as u32); + instruction + } + + pub(super) fn type_float(id: Word, width: Word) -> Self { + let mut instruction = Self::new(Op::TypeFloat); + instruction.set_result(id); + instruction.add_operand(width); + instruction + } + + pub(super) fn type_vector( + id: Word, + component_type_id: Word, + component_count: crate::VectorSize, + ) -> Self { + let mut instruction = Self::new(Op::TypeVector); + instruction.set_result(id); + instruction.add_operand(component_type_id); + instruction.add_operand(component_count as u32); + instruction + } + + pub(super) fn type_matrix( + id: Word, + column_type_id: Word, + column_count: crate::VectorSize, + ) -> Self { + let mut instruction = Self::new(Op::TypeMatrix); + instruction.set_result(id); + instruction.add_operand(column_type_id); + instruction.add_operand(column_count as u32); + instruction + } + + pub(super) fn type_image( + id: Word, + sampled_type_id: Word, + dim: spirv::Dim, + arrayed: bool, + image_class: crate::ImageClass, + ) -> Self { + let mut instruction = Self::new(Op::TypeImage); + instruction.set_result(id); + instruction.add_operand(sampled_type_id); + instruction.add_operand(dim as u32); + + let (depth, multi, sampled) = match image_class { + crate::ImageClass::Sampled { kind: _, multi } => (false, multi, true), + crate::ImageClass::Depth => (true, false, true), + crate::ImageClass::Storage(_) => (false, false, false), + }; + instruction.add_operand(depth as u32); + instruction.add_operand(arrayed as u32); + instruction.add_operand(multi as u32); + instruction.add_operand(sampled as u32); + + let format = match image_class { + crate::ImageClass::Storage(format) => match format { + crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8, + crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm, + crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui, + crate::StorageFormat::R8Sint => spirv::ImageFormat::R8i, + crate::StorageFormat::R16Uint => spirv::ImageFormat::R16ui, + crate::StorageFormat::R16Sint => spirv::ImageFormat::R16i, + crate::StorageFormat::R16Float => spirv::ImageFormat::R16f, + crate::StorageFormat::Rg8Unorm => spirv::ImageFormat::Rg8, + crate::StorageFormat::Rg8Snorm => spirv::ImageFormat::Rg8Snorm, + crate::StorageFormat::Rg8Uint => spirv::ImageFormat::Rg8ui, + crate::StorageFormat::Rg8Sint => spirv::ImageFormat::Rg8i, + crate::StorageFormat::R32Uint => spirv::ImageFormat::R32ui, + crate::StorageFormat::R32Sint => spirv::ImageFormat::R32i, + crate::StorageFormat::R32Float => spirv::ImageFormat::R32f, + crate::StorageFormat::Rg16Uint => spirv::ImageFormat::Rg16ui, + crate::StorageFormat::Rg16Sint => spirv::ImageFormat::Rg16i, + crate::StorageFormat::Rg16Float => spirv::ImageFormat::Rg16f, + crate::StorageFormat::Rgba8Unorm => spirv::ImageFormat::Rgba8, + crate::StorageFormat::Rgba8Snorm => spirv::ImageFormat::Rgba8Snorm, + crate::StorageFormat::Rgba8Uint => spirv::ImageFormat::Rgba8ui, + crate::StorageFormat::Rgba8Sint => spirv::ImageFormat::Rgba8i, + crate::StorageFormat::Rgb10a2Unorm => spirv::ImageFormat::Rgb10a2ui, + crate::StorageFormat::Rg11b10Float => spirv::ImageFormat::R11fG11fB10f, + crate::StorageFormat::Rg32Uint => spirv::ImageFormat::Rg32ui, + crate::StorageFormat::Rg32Sint => spirv::ImageFormat::Rg32i, + crate::StorageFormat::Rg32Float => spirv::ImageFormat::Rg32f, + crate::StorageFormat::Rgba16Uint => spirv::ImageFormat::Rgba16ui, + crate::StorageFormat::Rgba16Sint => spirv::ImageFormat::Rgba16i, + crate::StorageFormat::Rgba16Float => spirv::ImageFormat::Rgba16f, + crate::StorageFormat::Rgba32Uint => spirv::ImageFormat::Rgba32ui, + crate::StorageFormat::Rgba32Sint => spirv::ImageFormat::Rgba32i, + crate::StorageFormat::Rgba32Float => spirv::ImageFormat::Rgba32f, + }, + _ => spirv::ImageFormat::Unknown, + }; + + instruction.add_operand(format as u32); + instruction + } + + pub(super) fn type_sampler(id: Word) -> Self { + let mut instruction = Self::new(Op::TypeSampler); + instruction.set_result(id); + instruction + } + + pub(super) fn type_sampled_image(id: Word, image_type_id: Word) -> Self { + let mut instruction = Self::new(Op::TypeSampledImage); + instruction.set_result(id); + instruction.add_operand(image_type_id); + instruction + } + + pub(super) fn type_array(id: Word, element_type_id: Word, length_id: Word) -> Self { + let mut instruction = Self::new(Op::TypeArray); + instruction.set_result(id); + instruction.add_operand(element_type_id); + instruction.add_operand(length_id); + instruction + } + + pub(super) fn type_runtime_array(id: Word, element_type_id: Word) -> Self { + let mut instruction = Self::new(Op::TypeRuntimeArray); + instruction.set_result(id); + instruction.add_operand(element_type_id); + instruction + } + + pub(super) fn type_struct(id: Word, member_ids: &[Word]) -> Self { + let mut instruction = Self::new(Op::TypeStruct); + instruction.set_result(id); + + for member_id in member_ids { + instruction.add_operand(*member_id) + } + + instruction + } + + pub(super) fn type_pointer( + id: Word, + storage_class: spirv::StorageClass, + type_id: Word, + ) -> Self { + let mut instruction = Self::new(Op::TypePointer); + instruction.set_result(id); + instruction.add_operand(storage_class as u32); + instruction.add_operand(type_id); + instruction + } + + pub(super) fn type_function(id: Word, return_type_id: Word, parameter_ids: &[Word]) -> Self { + let mut instruction = Self::new(Op::TypeFunction); + instruction.set_result(id); + instruction.add_operand(return_type_id); + + for parameter_id in parameter_ids { + instruction.add_operand(*parameter_id); + } + + instruction + } + + // + // Constant-Creation Instructions + // + + pub(super) fn constant_true(result_type_id: Word, id: Word) -> Self { + let mut instruction = Self::new(Op::ConstantTrue); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction + } + + pub(super) fn constant_false(result_type_id: Word, id: Word) -> Self { + let mut instruction = Self::new(Op::ConstantFalse); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction + } + + pub(super) fn constant(result_type_id: Word, id: Word, values: &[Word]) -> Self { + let mut instruction = Self::new(Op::Constant); + instruction.set_type(result_type_id); + instruction.set_result(id); + + for value in values { + instruction.add_operand(*value); + } + + instruction + } + + pub(super) fn constant_composite( + result_type_id: Word, + id: Word, + constituent_ids: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::ConstantComposite); + instruction.set_type(result_type_id); + instruction.set_result(id); + + for constituent_id in constituent_ids { + instruction.add_operand(*constituent_id); + } + + instruction + } + + // + // Memory Instructions + // + + pub(super) fn variable( + result_type_id: Word, + id: Word, + storage_class: spirv::StorageClass, + initializer_id: Option, + ) -> Self { + let mut instruction = Self::new(Op::Variable); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(storage_class as u32); + + if let Some(initializer_id) = initializer_id { + instruction.add_operand(initializer_id); + } + + instruction + } + + pub(super) fn load( + result_type_id: Word, + id: Word, + pointer_id: Word, + memory_access: Option, + ) -> Self { + let mut instruction = Self::new(Op::Load); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(pointer_id); + + if let Some(memory_access) = memory_access { + instruction.add_operand(memory_access.bits()); + } + + instruction + } + + pub(super) fn store( + pointer_type_id: Word, + object_id: Word, + memory_access: Option, + ) -> Self { + let mut instruction = Self::new(Op::Store); + instruction.add_operand(pointer_type_id); + instruction.add_operand(object_id); + + if let Some(memory_access) = memory_access { + instruction.add_operand(memory_access.bits()); + } + + instruction + } + + pub(super) fn access_chain( + result_type_id: Word, + id: Word, + base_id: Word, + index_ids: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::AccessChain); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(base_id); + + for index_id in index_ids { + instruction.add_operand(*index_id); + } + + instruction + } + + // + // Function Instructions + // + + pub(super) fn function( + return_type_id: Word, + id: Word, + function_control: spirv::FunctionControl, + function_type_id: Word, + ) -> Self { + let mut instruction = Self::new(Op::Function); + instruction.set_type(return_type_id); + instruction.set_result(id); + instruction.add_operand(function_control.bits()); + instruction.add_operand(function_type_id); + instruction + } + + pub(super) fn function_parameter(result_type_id: Word, id: Word) -> Self { + let mut instruction = Self::new(Op::FunctionParameter); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction + } + + pub(super) fn function_end() -> Self { + Self::new(Op::FunctionEnd) + } + + pub(super) fn function_call( + result_type_id: Word, + id: Word, + function_id: Word, + argument_ids: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::FunctionCall); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(function_id); + + for argument_id in argument_ids { + instruction.add_operand(*argument_id); + } + + instruction + } + + // + // Image Instructions + // + + pub(super) fn sampled_image( + result_type_id: Word, + id: Word, + image: Word, + sampler: Word, + ) -> Self { + let mut instruction = Self::new(Op::SampledImage); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(image); + instruction.add_operand(sampler); + instruction + } + + pub(super) fn image_sample( + result_type_id: Word, + id: Word, + lod: SampleLod, + sampled_image: Word, + coordinates: Word, + depth_ref: Option, + ) -> Self { + let op = match (lod, depth_ref) { + (SampleLod::Explicit, None) => Op::ImageSampleExplicitLod, + (SampleLod::Implicit, None) => Op::ImageSampleImplicitLod, + (SampleLod::Explicit, Some(_)) => Op::ImageSampleDrefExplicitLod, + (SampleLod::Implicit, Some(_)) => Op::ImageSampleDrefImplicitLod, + }; + + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(sampled_image); + instruction.add_operand(coordinates); + if let Some(dref) = depth_ref { + instruction.add_operand(dref); + } + + instruction + } + + // + // Conversion Instructions + // + pub(super) fn unary(op: Op, result_type_id: Word, id: Word, value: Word) -> Self { + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(value); + instruction + } + + // + // Composite Instructions + // + + pub(super) fn composite_construct( + result_type_id: Word, + id: Word, + constituent_ids: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::CompositeConstruct); + instruction.set_type(result_type_id); + instruction.set_result(id); + + for constituent_id in constituent_ids { + instruction.add_operand(*constituent_id); + } + + instruction + } + + pub(super) fn composite_extract( + result_type_id: Word, + id: Word, + composite_id: Word, + indices: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::CompositeExtract); + instruction.set_type(result_type_id); + instruction.set_result(id); + + instruction.add_operand(composite_id); + for index in indices { + instruction.add_operand(*index); + } + + instruction + } + + pub(super) fn vector_extract_dynamic( + result_type_id: Word, + id: Word, + vector_id: Word, + index_id: Word, + ) -> Self { + let mut instruction = Self::new(Op::VectorExtractDynamic); + instruction.set_type(result_type_id); + instruction.set_result(id); + + instruction.add_operand(vector_id); + instruction.add_operand(index_id); + + instruction + } + + // + // Arithmetic Instructions + // + pub(super) fn binary( + op: Op, + result_type_id: Word, + id: Word, + operand_1: Word, + operand_2: Word, + ) -> Self { + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(operand_1); + instruction.add_operand(operand_2); + instruction + } + + // + // Bit Instructions + // + + // + // Relational and Logical Instructions + // + + // + // Derivative Instructions + // + + // + // Control-Flow Instructions + // + + pub(super) fn selection_merge( + merge_id: Word, + selection_control: spirv::SelectionControl, + ) -> Self { + let mut instruction = Self::new(Op::SelectionMerge); + instruction.add_operand(merge_id); + instruction.add_operand(selection_control.bits()); + instruction + } + + pub(super) fn loop_merge( + merge_id: Word, + continuing_id: Word, + selection_control: spirv::SelectionControl, + ) -> Self { + let mut instruction = Self::new(Op::LoopMerge); + instruction.add_operand(merge_id); + instruction.add_operand(continuing_id); + instruction.add_operand(selection_control.bits()); + instruction + } + + pub(super) fn label(id: Word) -> Self { + let mut instruction = Self::new(Op::Label); + instruction.set_result(id); + instruction + } + + pub(super) fn branch(id: Word) -> Self { + let mut instruction = Self::new(Op::Branch); + instruction.add_operand(id); + instruction + } + + // TODO Branch Weights not implemented. + pub(super) fn branch_conditional( + condition_id: Word, + true_label: Word, + false_label: Word, + ) -> Self { + let mut instruction = Self::new(Op::BranchConditional); + instruction.add_operand(condition_id); + instruction.add_operand(true_label); + instruction.add_operand(false_label); + instruction + } + + pub(super) fn switch(selector_id: Word, default_id: Word, cases: &[Case]) -> Self { + let mut instruction = Self::new(Op::Switch); + instruction.add_operand(selector_id); + instruction.add_operand(default_id); + for case in cases { + instruction.add_operand(case.value); + instruction.add_operand(case.label_id); + } + instruction + } + + pub(super) fn kill() -> Self { + Self::new(Op::Kill) + } + + pub(super) fn return_void() -> Self { + Self::new(Op::Return) + } + + pub(super) fn return_value(value_id: Word) -> Self { + let mut instruction = Self::new(Op::ReturnValue); + instruction.add_operand(value_id); + instruction + } + + // + // Atomic Instructions + // + + // + // Primitive Instructions + // } - -pub(super) fn instruction_kill() -> Instruction { - Instruction::new(Op::Kill) -} - -pub(super) fn instruction_return() -> Instruction { - Instruction::new(Op::Return) -} - -pub(super) fn instruction_return_value(value_id: Word) -> Instruction { - let mut instruction = Instruction::new(Op::ReturnValue); - instruction.add_operand(value_id); - instruction -} - -// -// Atomic Instructions -// - -// -// Primitive Instructions -// diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 011645b50..bbad11f85 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -44,7 +44,7 @@ struct LogicalLayout { function_definitions: Vec, } -pub(self) struct Instruction { +struct Instruction { op: spirv::Op, wc: u32, type_id: Option, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e9bdda5ee..1a4f0d24b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -58,7 +58,7 @@ impl Function { instruction.to_words(sink); } for (index, block) in self.blocks.iter().enumerate() { - super::instructions::instruction_label(block.label_id).to_words(sink); + Instruction::label(block.label_id).to_words(sink); if index == 0 { for local_var in self.variables.values() { local_var.instruction.to_words(sink); @@ -318,8 +318,7 @@ impl Writer { _ => { let storage_class = self.parse_to_spirv_storage_class(class); let id = self.generate_id(); - let instruction = - super::instructions::instruction_type_pointer(id, storage_class, ty_id); + let instruction = Instruction::type_pointer(id, storage_class, ty_id); instruction.to_words(&mut self.logical_layout.declarations); self.lookup_type.insert( LookupType::Local(LocalType::Pointer { @@ -336,14 +335,14 @@ impl Writer { fn create_pointer_type(&mut self, type_id: spirv::Word, class: spirv::StorageClass) -> Word { let id = self.generate_id(); - let instruction = super::instructions::instruction_type_pointer(id, class, type_id); + let instruction = Instruction::type_pointer(id, class, type_id); instruction.to_words(&mut self.logical_layout.declarations); id } fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word { let id = self.generate_id(); - let instruction = super::instructions::instruction_constant(type_id, id, value); + let instruction = Instruction::constant(type_id, id, value); instruction.to_words(&mut self.logical_layout.declarations); id } @@ -372,8 +371,7 @@ impl Writer { if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = variable.name { - self.debugs - .push(super::instructions::instruction_name(id, name)); + self.debugs.push(Instruction::name(id, name)); } } @@ -382,7 +380,7 @@ impl Writer { .map(|constant| self.lookup_constant[&constant]); let pointer_type_id = self.get_pointer_id(&ir_module.types, variable.ty, crate::StorageClass::Function)?; - let instruction = super::instructions::instruction_variable( + let instruction = Instruction::variable( pointer_type_id, id, spirv::StorageClass::Function, @@ -406,10 +404,7 @@ impl Writer { parameter_type_ids.push(parameter_type_id); function .parameters - .push(super::instructions::instruction_function_parameter( - parameter_type_id, - id, - )); + .push(Instruction::function_parameter(parameter_type_id, id)); } let lookup_function_type = LookupFunctionType { @@ -419,7 +414,7 @@ impl Writer { let function_id = self.generate_id(); let function_type = self.get_function_type(lookup_function_type); - function.signature = Some(super::instructions::instruction_function( + function.signature = Some(Instruction::function( return_type_id, function_id, spirv::FunctionControl::empty(), @@ -438,8 +433,7 @@ impl Writer { )?; function.to_words(&mut self.logical_layout.function_definitions); - super::instructions::instruction_function_end() - .to_words(&mut self.logical_layout.function_definitions); + Instruction::function_end().to_words(&mut self.logical_layout.function_definitions); Ok(function_id) } @@ -475,14 +469,14 @@ impl Writer { crate::ShaderStage::Fragment => { let execution_mode = spirv::ExecutionMode::OriginUpperLeft; self.check(execution_mode.required_capabilities())?; - super::instructions::instruction_execution_mode(function_id, execution_mode, &[]) + Instruction::execution_mode(function_id, execution_mode, &[]) .to_words(&mut self.logical_layout.execution_modes); spirv::ExecutionModel::Fragment } crate::ShaderStage::Compute => { let execution_mode = spirv::ExecutionMode::LocalSize; self.check(execution_mode.required_capabilities())?; - super::instructions::instruction_execution_mode( + Instruction::execution_mode( function_id, execution_mode, &entry_point.workgroup_size, @@ -494,11 +488,10 @@ impl Writer { self.check(exec_model.required_capabilities())?; if self.flags.contains(WriterFlags::DEBUG) { - self.debugs - .push(super::instructions::instruction_name(function_id, name)); + self.debugs.push(Instruction::name(function_id, name)); } - Ok(super::instructions::instruction_entry_point( + Ok(Instruction::entry_point( exec_model, function_id, name, @@ -509,18 +502,14 @@ impl Writer { fn write_scalar(&self, id: Word, kind: crate::ScalarKind, width: crate::Bytes) -> Instruction { let bits = (width * BITS_PER_BYTE) as u32; match kind { - crate::ScalarKind::Sint => super::instructions::instruction_type_int( - id, - bits, - super::instructions::Signedness::Signed, - ), - crate::ScalarKind::Uint => super::instructions::instruction_type_int( - id, - bits, - super::instructions::Signedness::Unsigned, - ), - crate::ScalarKind::Float => super::instructions::instruction_type_float(id, bits), - crate::ScalarKind::Bool => super::instructions::instruction_type_bool(id), + crate::ScalarKind::Sint => { + Instruction::type_int(id, bits, super::instructions::Signedness::Signed) + } + crate::ScalarKind::Uint => { + Instruction::type_int(id, bits, super::instructions::Signedness::Unsigned) + } + crate::ScalarKind::Float => Instruction::type_float(id, bits), + crate::ScalarKind::Bool => Instruction::type_bool(id), } } @@ -553,7 +542,7 @@ impl Writer { LocalType::Vector { size, kind, width } => { let scalar_id = self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width }))?; - super::instructions::instruction_type_vector(id, scalar_id, size) + Instruction::type_vector(id, scalar_id, size) } LocalType::Matrix { columns, @@ -568,14 +557,14 @@ impl Writer { width, }), )?; - super::instructions::instruction_type_matrix(id, vector_id, columns) + Instruction::type_matrix(id, vector_id, columns) } LocalType::Pointer { .. } => { return Err(Error::FeatureNotImplemented("pointer declaration")) } LocalType::SampledImage { image_type } => { let image_type_id = self.get_type_id(arena, LookupType::Handle(image_type))?; - super::instructions::instruction_type_sampled_image(id, image_type_id) + Instruction::type_sampled_image(id, image_type_id) } }; @@ -594,8 +583,7 @@ impl Writer { if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = ty.name { - self.debugs - .push(super::instructions::instruction_name(id, name)); + self.debugs.push(Instruction::name(id, name)); } } @@ -612,7 +600,7 @@ impl Writer { LookupType::Local(LocalType::Vector { size, kind, width }), id, ); - super::instructions::instruction_type_vector(id, scalar_id, size) + Instruction::type_vector(id, scalar_id, size) } crate::TypeInner::Matrix { columns, @@ -635,7 +623,7 @@ impl Writer { }), id, ); - super::instructions::instruction_type_matrix(id, vector_id, columns) + Instruction::type_matrix(id, vector_id, columns) } crate::TypeInner::Image { dim, @@ -659,30 +647,25 @@ impl Writer { let type_id = self.get_type_id(arena, LookupType::Local(local_type))?; let dim = map_dim(dim); self.check(dim.required_capabilities())?; - super::instructions::instruction_type_image(id, type_id, dim, arrayed, class) - } - crate::TypeInner::Sampler { comparison: _ } => { - super::instructions::instruction_type_sampler(id) + Instruction::type_image(id, type_id, dim, arrayed, class) } + crate::TypeInner::Sampler { comparison: _ } => Instruction::type_sampler(id), crate::TypeInner::Array { base, size, stride } => { if let Some(array_stride) = stride { - self.annotations - .push(super::instructions::instruction_decorate( - id, - spirv::Decoration::ArrayStride, - &[array_stride.get()], - )); + self.annotations.push(Instruction::decorate( + id, + spirv::Decoration::ArrayStride, + &[array_stride.get()], + )); } let type_id = self.get_type_id(arena, LookupType::Handle(base))?; match size { crate::ArraySize::Constant(const_handle) => { let length_id = self.lookup_constant[&const_handle]; - super::instructions::instruction_type_array(id, type_id, length_id) - } - crate::ArraySize::Dynamic => { - super::instructions::instruction_type_runtime_array(id, type_id) + Instruction::type_array(id, type_id, length_id) } + crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), } } crate::TypeInner::Struct { @@ -696,11 +679,7 @@ impl Writer { spirv::Decoration::BufferBlock }; self.annotations - .push(super::instructions::instruction_decorate( - id, - decoration, - &[], - )); + .push(Instruction::decorate(id, decoration, &[])); } let mut current_offset = 0; @@ -708,13 +687,12 @@ impl Writer { for (index, member) in members.iter().enumerate() { let layout = self.layouter.resolve(member.ty); current_offset += layout.pad(current_offset); - self.annotations - .push(super::instructions::instruction_member_decorate( - id, - index as u32, - spirv::Decoration::Offset, - &[current_offset], - )); + self.annotations.push(Instruction::member_decorate( + id, + index as u32, + spirv::Decoration::Offset, + &[current_offset], + )); current_offset += match member.span { Some(span) => span.get(), None => layout.size, @@ -723,11 +701,7 @@ impl Writer { if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = member.name { self.debugs - .push(super::instructions::instruction_member_name( - id, - index as u32, - name, - )); + .push(Instruction::member_name(id, index as u32, name)); } } @@ -741,26 +715,24 @@ impl Writer { crate::VectorSize::Bi => 2 * width, crate::VectorSize::Tri | crate::VectorSize::Quad => 4 * width, }; - self.annotations - .push(super::instructions::instruction_member_decorate( - id, - index as u32, - spirv::Decoration::ColMajor, - &[], - )); - self.annotations - .push(super::instructions::instruction_member_decorate( - id, - index as u32, - spirv::Decoration::MatrixStride, - &[byte_stride as u32], - )); + self.annotations.push(Instruction::member_decorate( + id, + index as u32, + spirv::Decoration::ColMajor, + &[], + )); + self.annotations.push(Instruction::member_decorate( + id, + index as u32, + spirv::Decoration::MatrixStride, + &[byte_stride as u32], + )); } let member_id = self.get_type_id(arena, LookupType::Handle(member.ty))?; member_ids.push(member_id); } - super::instructions::instruction_type_struct(id, member_ids.as_slice()) + Instruction::type_struct(id, member_ids.as_slice()) } crate::TypeInner::Struct { block: false, @@ -771,17 +743,13 @@ impl Writer { let member_id = self.get_type_id(arena, LookupType::Handle(member.ty))?; member_ids.push(member_id); } - super::instructions::instruction_type_struct(id, member_ids.as_slice()) + Instruction::type_struct(id, member_ids.as_slice()) } crate::TypeInner::Pointer { base, class } => { let type_id = self.get_type_id(arena, LookupType::Handle(base))?; self.lookup_type .insert(LookupType::Local(LocalType::Pointer { base, class }), id); - super::instructions::instruction_type_pointer( - id, - self.parse_to_spirv_storage_class(class), - type_id, - ) + Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) } }; @@ -819,7 +787,7 @@ impl Writer { } _ => unreachable!(), }; - super::instructions::instruction_constant(type_id, id, words) + Instruction::constant(type_id, id, words) } crate::ScalarValue::Uint(val) => { let words = match width { @@ -833,7 +801,7 @@ impl Writer { } _ => unreachable!(), }; - super::instructions::instruction_constant(type_id, id, words) + Instruction::constant(type_id, id, words) } crate::ScalarValue::Float(val) => { let words = match width { @@ -848,14 +816,10 @@ impl Writer { } _ => unreachable!(), }; - super::instructions::instruction_constant(type_id, id, words) - } - crate::ScalarValue::Bool(true) => { - super::instructions::instruction_constant_true(type_id, id) - } - crate::ScalarValue::Bool(false) => { - super::instructions::instruction_constant_false(type_id, id) + Instruction::constant(type_id, id, words) } + crate::ScalarValue::Bool(true) => Instruction::constant_true(type_id, id), + crate::ScalarValue::Bool(false) => Instruction::constant_false(type_id, id), } } crate::ConstantInner::Composite { ty, ref components } => { @@ -866,11 +830,7 @@ impl Writer { } let type_id = self.get_type_id(types, LookupType::Handle(ty))?; - super::instructions::instruction_constant_composite( - type_id, - id, - constituent_ids.as_slice(), - ) + Instruction::constant_composite(type_id, id, constituent_ids.as_slice()) } }; @@ -894,13 +854,11 @@ impl Writer { .map(|constant| self.lookup_constant[&constant]); let pointer_type_id = self.get_pointer_id(&ir_module.types, global_variable.ty, global_variable.class)?; - let instruction = - super::instructions::instruction_variable(pointer_type_id, id, class, init_word); + let instruction = Instruction::variable(pointer_type_id, id, class, init_word); if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = global_variable.name { - self.debugs - .push(super::instructions::instruction_name(id, name)); + self.debugs.push(Instruction::name(id, name)); } } @@ -911,11 +869,7 @@ impl Writer { }; if let Some(decoration) = access_decoration { self.annotations - .push(super::instructions::instruction_decorate( - id, - decoration, - &[], - )); + .push(Instruction::decorate(id, decoration, &[])); } if let Some(interpolation) = global_variable.interpolation { @@ -929,36 +883,29 @@ impl Writer { }; if let Some(decoration) = decoration { self.annotations - .push(super::instructions::instruction_decorate( - id, - decoration, - &[], - )); + .push(Instruction::decorate(id, decoration, &[])); } } match global_variable.binding { Some(crate::Binding::Location(location)) => { - self.annotations - .push(super::instructions::instruction_decorate( - id, - spirv::Decoration::Location, - &[location], - )); + self.annotations.push(Instruction::decorate( + id, + spirv::Decoration::Location, + &[location], + )); } Some(crate::Binding::Resource { group, binding }) => { - self.annotations - .push(super::instructions::instruction_decorate( - id, - spirv::Decoration::DescriptorSet, - &[group], - )); - self.annotations - .push(super::instructions::instruction_decorate( - id, - spirv::Decoration::Binding, - &[binding], - )); + self.annotations.push(Instruction::decorate( + id, + spirv::Decoration::DescriptorSet, + &[group], + )); + self.annotations.push(Instruction::decorate( + id, + spirv::Decoration::Binding, + &[binding], + )); } Some(crate::Binding::BuiltIn(built_in)) => { use crate::BuiltIn as Bi; @@ -985,12 +932,11 @@ impl Writer { Bi::WorkGroupSize => spirv::BuiltIn::WorkgroupSize, }; - self.annotations - .push(super::instructions::instruction_decorate( - id, - spirv::Decoration::BuiltIn, - &[built_in as u32], - )); + self.annotations.push(Instruction::decorate( + id, + spirv::Decoration::BuiltIn, + &[built_in as u32], + )); } None => {} } @@ -1009,7 +955,7 @@ impl Writer { Entry::Occupied(e) => *e.get(), _ => { let id = self.generate_id(); - let instruction = super::instructions::instruction_type_function( + let instruction = Instruction::type_function( id, lookup_function_type.return_type_id, &lookup_function_type.parameter_type_ids, @@ -1028,13 +974,11 @@ impl Writer { block: &mut Block, ) -> Word { let id = self.generate_id(); - block - .body - .push(super::instructions::instruction_composite_construct( - base_type_id, - id, - constituent_ids, - )); + block.body.push(Instruction::composite_construct( + base_type_id, + id, + constituent_ids, + )); id } @@ -1053,12 +997,9 @@ impl Writer { RawExpression::Value(id) => id, RawExpression::Pointer(id, _) => { let load_id = self.generate_id(); - block.body.push(super::instructions::instruction_load( - result_type_id, - load_id, - id, - None, - )); + block + .body + .push(Instruction::load(result_type_id, load_id, id, None)); load_id } }) @@ -1116,28 +1057,24 @@ impl Writer { )); } - block - .body - .push(super::instructions::instruction_vector_extract_dynamic( - result_type_id, - id, - base_id, - index_id, - )); + block.body.push(Instruction::vector_extract_dynamic( + result_type_id, + id, + base_id, + index_id, + )); RawExpression::Value(id) } RawExpression::Pointer(base_id, class) => { let pointer_type_id = self.create_pointer_type(result_type_id, class); - block - .body - .push(super::instructions::instruction_access_chain( - pointer_type_id, - id, - base_id, - &[index_id], - )); + block.body.push(Instruction::access_chain( + pointer_type_id, + id, + base_id, + &[index_id], + )); RawExpression::Pointer(id, class) } @@ -1150,14 +1087,12 @@ impl Writer { match raw_base_expression { RawExpression::Value(base_id) => { - block - .body - .push(super::instructions::instruction_composite_extract( - result_type_id, - id, - base_id, - &[index], - )); + block.body.push(Instruction::composite_extract( + result_type_id, + id, + base_id, + &[index], + )); RawExpression::Value(id) } @@ -1173,14 +1108,12 @@ impl Writer { )?; let const_id = self.create_constant(const_ty_id, &[index]); - block - .body - .push(super::instructions::instruction_access_chain( - pointer_type_id, - id, - base_id, - &[const_id], - )); + block.body.push(Instruction::access_chain( + pointer_type_id, + id, + base_id, + &[const_id], + )); RawExpression::Pointer(id, class) } @@ -1231,12 +1164,9 @@ impl Writer { crate::UnaryOperator::Not => spirv::Op::Not, }; - block.body.push(super::instructions::instruction_unary( - spirv_op, - result_type_id, - id, - expr_id, - )); + block + .body + .push(Instruction::unary(spirv_op, result_type_id, id, expr_id)); RawExpression::Value(id) } crate::Expression::Binary { op, left, right } => { @@ -1360,7 +1290,7 @@ impl Writer { }, }; - block.body.push(super::instructions::instruction_binary( + block.body.push(Instruction::binary( spirv_op, result_type_id, id, @@ -1405,7 +1335,7 @@ impl Writer { Some(crate::ScalarKind::Float) => MathOp::Ext(spirv::GLOp::FAbs), Some(crate::ScalarKind::Sint) => MathOp::Ext(spirv::GLOp::SAbs), Some(crate::ScalarKind::Uint) => { - MathOp::Custom(super::instructions::instruction_unary( + MathOp::Custom(Instruction::unary( spirv::Op::CopyObject, // do nothing result_type_id, id, @@ -1454,7 +1384,7 @@ impl Writer { Mf::Frexp => MathOp::Ext(spirv::GLOp::Frexp), Mf::Ldexp => MathOp::Ext(spirv::GLOp::Ldexp), // geometry - Mf::Dot => MathOp::Custom(super::instructions::instruction_binary( + Mf::Dot => MathOp::Custom(Instruction::binary( spirv::Op::Dot, result_type_id, id, @@ -1485,7 +1415,7 @@ impl Writer { Mf::SmoothStep => MathOp::Ext(spirv::GLOp::SmoothStep), Mf::Sqrt => MathOp::Ext(spirv::GLOp::Sqrt), Mf::InverseSqrt => MathOp::Ext(spirv::GLOp::InverseSqrt), - Mf::Transpose => MathOp::Custom(super::instructions::instruction_unary( + Mf::Transpose => MathOp::Custom(Instruction::unary( spirv::Op::Transpose, result_type_id, id, @@ -1499,7 +1429,7 @@ impl Writer { }; block.body.push(match math_op { - MathOp::Ext(op) => super::instructions::instruction_ext_inst( + MathOp::Ext(op) => Instruction::ext_inst( self.gl450_ext_inst_id, op, result_type_id, @@ -1532,14 +1462,12 @@ impl Writer { argument_ids.push(arg_id); } - block - .body - .push(super::instructions::instruction_function_call( - result_type_id, - id, - *self.lookup_function.get(&local_function).unwrap(), - argument_ids.as_slice(), - )); + block.body.push(Instruction::function_call( + result_type_id, + id, + *self.lookup_function.get(&local_function).unwrap(), + argument_ids.as_slice(), + )); RawExpression::Value(id) } @@ -1571,8 +1499,7 @@ impl Writer { }; let id = self.generate_id(); - let instruction = - super::instructions::instruction_unary(op, result_type_id, id, expr_id); + let instruction = Instruction::unary(op, result_type_id, id, expr_id); block.body.push(instruction); RawExpression::Value(id) @@ -1625,14 +1552,12 @@ impl Writer { for i in 0..size as u32 { let id = self.generate_id(); constituent_ids[i as usize] = id; - block.body.push( - super::instructions::instruction_composite_extract( - coordinate_scalar_type_id, - id, - coordinate_id, - &[i], - ), - ); + block.body.push(Instruction::composite_extract( + coordinate_scalar_type_id, + id, + coordinate_id, + &[i], + )); } match size { crate::VectorSize::Bi => crate::VectorSize::Tri, @@ -1655,7 +1580,7 @@ impl Writer { block, function, )?; - let cast_instruction = super::instructions::instruction_unary( + let cast_instruction = Instruction::unary( spirv::Op::ConvertUToF, coordinate_scalar_type_id, array_index_f32_id, @@ -1680,14 +1605,12 @@ impl Writer { } let sampled_image_id = self.generate_id(); - block - .body - .push(super::instructions::instruction_sampled_image( - sampled_image_type_id, - sampled_image_id, - image_id, - sampler_id, - )); + block.body.push(Instruction::sampled_image( + sampled_image_type_id, + sampled_image_id, + image_id, + sampler_id, + )); let id = self.generate_id(); let depth_id = match depth_ref { @@ -1701,7 +1624,7 @@ impl Writer { let mut main_instruction = match level { crate::SampleLevel::Zero => { - let mut inst = super::instructions::instruction_image_sample( + let mut inst = Instruction::image_sample( result_type_id, id, SampleLod::Explicit, @@ -1722,7 +1645,7 @@ impl Writer { inst } - crate::SampleLevel::Auto => super::instructions::instruction_image_sample( + crate::SampleLevel::Auto => Instruction::image_sample( result_type_id, id, SampleLod::Implicit, @@ -1731,7 +1654,7 @@ impl Writer { depth_id, ), crate::SampleLevel::Exact(lod_handle) => { - let mut inst = super::instructions::instruction_image_sample( + let mut inst = Instruction::image_sample( result_type_id, id, SampleLod::Explicit, @@ -1753,7 +1676,7 @@ impl Writer { inst } crate::SampleLevel::Bias(bias_handle) => { - let mut inst = super::instructions::instruction_image_sample( + let mut inst = Instruction::image_sample( result_type_id, id, SampleLod::Implicit, @@ -1775,7 +1698,7 @@ impl Writer { inst } crate::SampleLevel::Gradient { x, y } => { - let mut inst = super::instructions::instruction_image_sample( + let mut inst = Instruction::image_sample( result_type_id, id, SampleLod::Explicit, @@ -1834,7 +1757,7 @@ impl Writer { match *statement { crate::Statement::Block(ref block_statements) => { let scope_id = self.generate_id(); - function.consume(block, super::instructions::instruction_branch(scope_id)); + function.consume(block, Instruction::branch(scope_id)); let merge_id = self.generate_id(); self.write_block( @@ -1863,22 +1786,16 @@ impl Writer { )?; let merge_id = self.generate_id(); - block - .body - .push(super::instructions::instruction_selection_merge( - merge_id, - spirv::SelectionControl::NONE, - )); + block.body.push(Instruction::selection_merge( + merge_id, + spirv::SelectionControl::NONE, + )); let accept_id = self.generate_id(); let reject_id = self.generate_id(); function.consume( block, - super::instructions::instruction_branch_conditional( - condition_id, - accept_id, - reject_id, - ), + Instruction::branch_conditional(condition_id, accept_id, reject_id), ); self.write_block( @@ -1916,12 +1833,10 @@ impl Writer { )?; let merge_id = self.generate_id(); - block - .body - .push(super::instructions::instruction_selection_merge( - merge_id, - spirv::SelectionControl::NONE, - )); + block.body.push(Instruction::selection_merge( + merge_id, + spirv::SelectionControl::NONE, + )); let default_id = self.generate_id(); let raw_cases = cases @@ -1934,11 +1849,7 @@ impl Writer { function.consume( block, - super::instructions::instruction_switch( - selector_id, - default_id, - &raw_cases, - ), + Instruction::switch(selector_id, default_id, &raw_cases), ); for (i, (case, raw_case)) in cases.iter().zip(raw_cases.iter()).enumerate() { @@ -1978,7 +1889,7 @@ impl Writer { ref continuing, } => { let preamble_id = self.generate_id(); - function.consume(block, super::instructions::instruction_branch(preamble_id)); + function.consume(block, Instruction::branch(preamble_id)); let merge_id = self.generate_id(); let body_id = self.generate_id(); @@ -1987,12 +1898,12 @@ impl Writer { // SPIR-V requires the continuing to the `OpLoopMerge`, // so we have to start a new block with it. block = Block::new(preamble_id); - block.body.push(super::instructions::instruction_loop_merge( + block.body.push(Instruction::loop_merge( merge_id, continuing_id, spirv::SelectionControl::NONE, )); - function.consume(block, super::instructions::instruction_branch(body_id)); + function.consume(block, Instruction::branch(body_id)); self.write_block( body_id, @@ -2023,25 +1934,22 @@ impl Writer { block = Block::new(merge_id); } crate::Statement::Break => { - block.termination = Some(super::instructions::instruction_branch( - loop_context.break_id.unwrap(), - )); + block.termination = Some(Instruction::branch(loop_context.break_id.unwrap())); } crate::Statement::Continue => { - block.termination = Some(super::instructions::instruction_branch( - loop_context.continuing_id.unwrap(), - )); + block.termination = + Some(Instruction::branch(loop_context.continuing_id.unwrap())); } crate::Statement::Return { value: Some(value) } => { let id = self.write_expression(ir_module, ir_function, value, &mut block, function)?; - block.termination = Some(super::instructions::instruction_return_value(id)); + block.termination = Some(Instruction::return_value(id)); } crate::Statement::Return { value: None } => { - block.termination = Some(super::instructions::instruction_return()); + block.termination = Some(Instruction::return_void()); } crate::Statement::Kill => { - block.termination = Some(super::instructions::instruction_kill()); + block.termination = Some(Instruction::kill()); } crate::Statement::Store { pointer, value } => { let (pointer_id, _) = self.write_expression_pointer( @@ -2054,9 +1962,9 @@ impl Writer { let value_id = self.write_expression(ir_module, ir_function, value, &mut block, function)?; - block.body.push(super::instructions::instruction_store( - pointer_id, value_id, None, - )); + block + .body + .push(Instruction::store(pointer_id, value_id, None)); } crate::Statement::Call { function: local_function, @@ -2077,22 +1985,20 @@ impl Writer { argument_ids.push(arg_id); } - block - .body - .push(super::instructions::instruction_function_call( - self.void_type, - id, - *self.lookup_function.get(&local_function).unwrap(), - argument_ids.as_slice(), - )); + block.body.push(Instruction::function_call( + self.void_type, + id, + *self.lookup_function.get(&local_function).unwrap(), + argument_ids.as_slice(), + )); } } } if block.termination.is_none() { block.termination = Some(match exit_id { - Some(id) => super::instructions::instruction_branch(id), - None => super::instructions::instruction_return(), + Some(id) => Instruction::branch(id), + None => Instruction::return_void(), }); } @@ -2105,16 +2011,13 @@ impl Writer { } fn write_logical_layout(&mut self, ir_module: &crate::Module) -> Result<(), Error> { - super::instructions::instruction_type_void(self.void_type) - .to_words(&mut self.logical_layout.declarations); - super::instructions::instruction_ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") + Instruction::type_void(self.void_type).to_words(&mut self.logical_layout.declarations); + Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); if self.flags.contains(WriterFlags::DEBUG) { - self.debugs.push(super::instructions::instruction_source( - spirv::SourceLanguage::GLSL, - 450, - )); + self.debugs + .push(Instruction::source(spirv::SourceLanguage::GLSL, 450)); } for (handle, constant) in ir_module.constants.iter() { @@ -2140,8 +2043,7 @@ impl Writer { } for capability in self.capabilities.iter() { - super::instructions::instruction_capability(*capability) - .to_words(&mut self.logical_layout.capabilities); + Instruction::capability(*capability).to_words(&mut self.logical_layout.capabilities); } let addressing_model = spirv::AddressingModel::Logical; @@ -2149,7 +2051,7 @@ impl Writer { self.check(addressing_model.required_capabilities())?; self.check(memory_model.required_capabilities())?; - super::instructions::instruction_memory_model(addressing_model, memory_model) + Instruction::memory_model(addressing_model, memory_model) .to_words(&mut self.logical_layout.memory_model); if self.flags.contains(WriterFlags::DEBUG) { From de39e7f4d120563ee5f4f1a9c1b29040ea3ad7c2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 12 Feb 2021 23:48:23 -0500 Subject: [PATCH 0477/2212] [spv-in] patch function calls before deriving the global use --- src/front/spv/function.rs | 1 + src/front/spv/mod.rs | 7 ------- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 0ffbbf8e9..c3c2045f1 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -146,6 +146,7 @@ impl> super::Parser { fun.body = flow_graph.to_naga()?; // done + self.patch_function_calls(&mut fun)?; fun.fill_global_use(module.global_variables.len(), &module.functions); let dump_suffix = match self.lookup_entry_point.remove(&fun_id) { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index f8945c6ea..a57d031a5 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1689,13 +1689,6 @@ impl> Parser { } } - for (_, func) in module.functions.iter_mut() { - self.patch_function_calls(func)?; - } - for (_, ep) in module.entry_points.iter_mut() { - self.patch_function_calls(&mut ep.function)?; - } - if !self.future_decor.is_empty() { log::warn!("Unused item decorations: {:?}", self.future_decor); self.future_decor.clear(); From 94bd97c0fb2f7bb91e09127add14cd7e6670c070 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Feb 2021 00:14:46 -0500 Subject: [PATCH 0478/2212] [wgsl] early depth test attribute --- src/front/wgsl/conv.rs | 10 ++++++++++ src/front/wgsl/mod.rs | 15 ++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index a9362f3e5..0aa14dbaa 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -184,3 +184,13 @@ pub fn map_standard_fun(word: &str) -> Option { _ => return None, }) } + +pub fn map_conservative_depth(word: &str) -> Result> { + use crate::ConservativeDepth as Cd; + match word { + "greater_equal" => Ok(Cd::GreaterEqual), + "less_equal" => Ok(Cd::LessEqual), + "unchanged" => Ok(Cd::Unchanged), + _ => Err(Error::UnknownConservativeDepth(word)), + } +} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e2ed3c88c..551c9da6c 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -86,6 +86,8 @@ pub enum Error<'a> { UnknownFunction(&'a str), #[error("unknown storage format: `{0}`")] UnknownStorageFormat(&'a str), + #[error("unknown conservative depth: `{0}`")] + UnknownConservativeDepth(&'a str), #[error("array stride must not be 0")] ZeroStride, #[error("not a composite type: {0:?}")] @@ -1932,6 +1934,7 @@ impl Parser { let mut stage = None; let mut is_block = false; let mut workgroup_size = [0u32; 3]; + let mut early_depth_test = None; if lexer.skip(Token::DoubleParen('[')) { let (mut bind_index, mut bind_group) = (None, None); @@ -1994,6 +1997,16 @@ impl Parser { } } } + "early_depth_test" => { + let conservative = if lexer.skip(Token::Paren('(')) { + let value = conv::map_conservative_depth(lexer.next_ident()?)?; + lexer.expect(Token::Paren(')'))?; + Some(value) + } else { + None + }; + early_depth_test = Some(crate::EarlyDepthTest { conservative }); + } word => return Err(Error::UnknownDecoration(word)), } match lexer.next() { @@ -2103,7 +2116,7 @@ impl Parser { .insert( (stage, name.to_string()), crate::EntryPoint { - early_depth_test: None, + early_depth_test, workgroup_size, function, }, From 8183f4ff6ff220d4b17db6bab2b5779a4886b1a7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Feb 2021 14:04:58 -0500 Subject: [PATCH 0479/2212] [spv-out] annotate function and constant names --- src/back/spv/writer.rs | 11 ++++++++++ tests/out/boids.spvasm.snap | 31 +++++++++++++++++++++++++++++ tests/out/collatz.spvasm.snap | 10 ++++++++++ tests/out/empty.spvasm.snap | 3 +++ tests/out/quad.spvasm.snap | 14 +++++++++++++ tests/out/shadow.spvasm.snap | 23 +++++++++++++++++++++ tests/out/skybox.spvasm.snap | 19 ++++++++++++++++++ tests/out/texture-array.spvasm.snap | 11 ++++++++++ tests/snapshots.rs | 2 +- 9 files changed, 123 insertions(+), 1 deletion(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 1a4f0d24b..b60f173db 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -413,6 +413,12 @@ impl Writer { }; let function_id = self.generate_id(); + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = ir_function.name { + self.debugs.push(Instruction::name(function_id, name)); + } + } + let function_type = self.get_function_type(lookup_function_type); function.signature = Some(Instruction::function( return_type_id, @@ -2023,6 +2029,11 @@ impl Writer { for (handle, constant) in ir_module.constants.iter() { let id = self.generate_id(); self.lookup_constant.insert(handle, id); + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = constant.name { + self.debugs.push(Instruction::name(id, name)); + } + } self.write_constant_type(id, &constant.inner, &ir_module.types)?; } diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index fc28d8147..dd7691411 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -11,6 +11,37 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %29 "main" %36 OpExecutionMode %29 LocalSize 64 1 1 +OpSource GLSL 450 +OpName %3 "NUM_PARTICLES" +OpName %15 "vPos" +OpName %18 "vVel" +OpName %19 "cMass" +OpName %20 "cVel" +OpName %21 "colVel" +OpName %22 "cMassCount" +OpName %24 "cVelCount" +OpName %25 "pos" +OpName %26 "vel" +OpName %27 "i" +OpName %29 "main" +OpName %36 "gl_GlobalInvocationID" +OpName %45 "Particle" +OpMemberName %45 0 "pos" +OpMemberName %45 1 "vel" +OpName %49 "Particles" +OpMemberName %49 0 "particles" +OpName %50 "particlesSrc" +OpName %121 "SimParams" +OpMemberName %121 0 "deltaT" +OpMemberName %121 1 "rule1Distance" +OpMemberName %121 2 "rule2Distance" +OpMemberName %121 3 "rule3Distance" +OpMemberName %121 4 "rule1Scale" +OpMemberName %121 5 "rule2Scale" +OpMemberName %121 6 "rule3Scale" +OpName %122 "params" +OpName %274 "particlesDst" +OpName %29 "main" OpDecorate %36 BuiltIn GlobalInvocationId OpMemberDecorate %45 0 Offset 0 OpMemberDecorate %45 1 Offset 8 diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index 99f6590cf..8bdea00cd 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -11,6 +11,16 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %39 "main" %53 OpExecutionMode %39 LocalSize 1 1 1 +OpSource GLSL 450 +OpName %8 "n" +OpName %10 "i" +OpName %12 "collatz_iterations" +OpName %39 "main" +OpName %45 "PrimeIndices" +OpMemberName %45 0 "data" +OpName %46 "v_indices" +OpName %53 "global_id" +OpName %39 "main" OpDecorate %43 ArrayStride 4 OpDecorate %45 BufferBlock OpMemberDecorate %45 0 Offset 0 diff --git a/tests/out/empty.spvasm.snap b/tests/out/empty.spvasm.snap index ae2b9628b..e764f3e4d 100644 --- a/tests/out/empty.spvasm.snap +++ b/tests/out/empty.spvasm.snap @@ -11,6 +11,9 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %3 "main" OpExecutionMode %3 LocalSize 1 1 1 +OpSource GLSL 450 +OpName %3 "main" +OpName %3 "main" %2 = OpTypeVoid %4 = OpTypeFunction %2 %3 = OpFunction %2 None %4 diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index 0a0caa24a..1cbbb2686 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -12,6 +12,20 @@ OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %7 "main" %20 %13 %11 %17 OpEntryPoint Fragment %23 "main" %35 %25 OpExecutionMode %23 OriginUpperLeft +OpSource GLSL 450 +OpName %3 "c_scale" +OpName %7 "main" +OpName %11 "v_uv" +OpName %13 "a_uv" +OpName %17 "o_position" +OpName %20 "a_pos" +OpName %7 "main" +OpName %23 "main" +OpName %25 "o_color" +OpName %27 "u_texture" +OpName %32 "u_sampler" +OpName %35 "v_uv" +OpName %23 "main" OpDecorate %11 Location 0 OpDecorate %13 Location 1 OpDecorate %17 BuiltIn Position diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index 97fdef6f7..e1fd5a558 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -11,6 +11,29 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %64 "fs_main" %114 %111 %217 OpExecutionMode %64 OriginUpperLeft +OpSource GLSL 450 +OpName %9 "c_ambient" +OpName %11 "c_max_lights" +OpName %18 "fetch_shadow" +OpName %28 "t_shadow" +OpName %33 "sampler_shadow" +OpName %60 "color" +OpName %62 "i" +OpName %64 "fs_main" +OpName %76 "Globals" +OpMemberName %76 0 "num_lights" +OpName %77 "u_globals" +OpName %97 "Light" +OpMemberName %97 0 "proj" +OpMemberName %97 1 "pos" +OpMemberName %97 2 "color" +OpName %101 "Lights" +OpMemberName %101 0 "data" +OpName %102 "s_lights" +OpName %111 "in_position_fs" +OpName %114 "in_normal_fs" +OpName %217 "out_color_fs" +OpName %64 "fs_main" OpDecorate %28 DescriptorSet 0 OpDecorate %28 Binding 2 OpDecorate %33 DescriptorSet 0 diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index 3733edaa1..71da0dc4a 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -12,6 +12,25 @@ OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %16 "vs_main" %159 %47 %21 OpEntryPoint Fragment %170 "fs_main" %182 %172 OpExecutionMode %170 OriginUpperLeft +OpSource GLSL 450 +OpName %10 "tmp1" +OpName %12 "tmp2" +OpName %13 "unprojected" +OpName %16 "vs_main" +OpName %21 "in_vertex_index" +OpName %31 "Data" +OpMemberName %31 0 "proj_inv" +OpMemberName %31 1 "view" +OpName %32 "r_data" +OpName %47 "out_uv" +OpName %159 "out_position" +OpName %16 "vs_main" +OpName %170 "fs_main" +OpName %172 "out_color" +OpName %174 "r_texture" +OpName %179 "r_sampler" +OpName %182 "in_uv" +OpName %170 "fs_main" OpDecorate %21 BuiltIn VertexIndex OpDecorate %31 Block OpMemberDecorate %31 0 Offset 0 diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap index e83fab904..78e25937d 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm.snap @@ -11,6 +11,17 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %5 "main" %35 %23 OpExecutionMode %5 OriginUpperLeft +OpSource GLSL 450 +OpName %5 "main" +OpName %12 "PushConstants" +OpMemberName %12 0 "index" +OpName %13 "pc" +OpName %23 "color" +OpName %26 "texture0" +OpName %31 "sampler" +OpName %35 "tex_coord" +OpName %40 "texture1" +OpName %5 "main" OpDecorate %12 Block OpMemberDecorate %12 0 Offset 0 OpDecorate %23 Location 1 diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 40b472fb5..7523bb0b9 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -61,7 +61,7 @@ fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { let spv = spv::write_vec( &module, - spv::WriterFlags::NONE, + spv::WriterFlags::DEBUG, params.spv_capabilities.clone(), ) .unwrap(); From d0ef4e9dbe27cadfe6f64765763db9cef2e30511 Mon Sep 17 00:00:00 2001 From: Anthony Cowley Date: Sat, 13 Feb 2021 03:33:23 -0500 Subject: [PATCH 0480/2212] [spv-out] support select expressions --- src/back/spv/instructions.rs | 16 ++++++++++++++++ src/back/spv/writer.rs | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index f4b50afb3..a4fe76706 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -709,6 +709,22 @@ impl super::Instruction { instruction } + pub(super) fn select( + result_type_id: Word, + id: Word, + condition_id: Word, + accept_id: Word, + reject_id: Word, + ) -> Self { + let mut instruction = Self::new(Op::Select); + instruction.add_operand(result_type_id); + instruction.add_operand(id); + instruction.add_operand(condition_id); + instruction.add_operand(accept_id); + instruction.add_operand(reject_id); + instruction + } + pub(super) fn kill() -> Self { Self::new(Op::Kill) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b60f173db..709dd8b92 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1734,6 +1734,29 @@ impl Writer { block.body.push(main_instruction); RawExpression::Value(id) } + crate::Expression::Select { + condition, + accept, + reject, + } => { + let id = self.generate_id(); + let condition_id = + self.write_expression(ir_module, ir_function, condition, block, function)?; + let accept_id = + self.write_expression(ir_module, ir_function, accept, block, function)?; + let reject_id = + self.write_expression(ir_module, ir_function, reject, block, function)?; + + let instruction = Instruction::select( + result_type_id, + id, + condition_id, + accept_id, + reject_id, + ); + block.body.push(instruction); + RawExpression::Value(id) + } ref other => { log::error!("unimplemented {:?}", other); return Err(Error::FeatureNotImplemented("expression")); From 747040ee8a5eb6ef7fe9624bf1030edc5365e952 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 10 Feb 2021 15:49:24 -0500 Subject: [PATCH 0481/2212] Analyzer processor - first draft --- src/proc/analyzer.rs | 350 +++++++++++++++++++++++++++++++++++++++++++ src/proc/mod.rs | 1 + 2 files changed, 351 insertions(+) create mode 100644 src/proc/analyzer.rs diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs new file mode 100644 index 000000000..fcf968030 --- /dev/null +++ b/src/proc/analyzer.rs @@ -0,0 +1,350 @@ +/*! Module analyzer. + +Figures out the following properties: + - control flow uniformity + - texture/sampler pairs + - expression reference counts +!*/ + +use crate::arena::{Arena, Handle}; + +bitflags::bitflags! { + #[derive(Default)] + pub struct ControlFlags: u8 { + /// The result is not dynamically uniform. + const NON_UNIFORM_RESULT = 0x1; + /// Uniform control flow is required by the code. + const REQUIRE_UNIFORM = 0x2; + /// The code may exit the control flow. + const MAY_EXIT = 0x4; + } +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct SamplingKey { + pub image: Handle, + pub sampler: Handle, +} + +#[derive(Clone, Default)] +pub struct ExpressionInfo { + pub control_flags: ControlFlags, + pub ref_count: usize, +} + +pub struct FunctionInfo { + pub control_flags: ControlFlags, + pub sampling_set: crate::FastHashSet, + pub expressions: Box<[ExpressionInfo]>, +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum AnalysisError { + #[error("Expression {0:?} is not a global variable!")] + ExpectedGlobalVariable(crate::Expression), + //TODO: add more information here! + #[error("Required uniformity of control flow is not fulfilled")] + NonUniformControlFlow, +} + +impl FunctionInfo { + #[must_use] + fn add_ref(&mut self, handle: Handle) -> ControlFlags { + let info = &mut self.expressions[handle.index()]; + info.ref_count += 1; + info.control_flags + } + + fn process_expression( + &mut self, + handle: Handle, + expression_arena: &Arena, + global_var_arena: &Arena, + other_functions: &[FunctionInfo], + ) -> Result<(), AnalysisError> { + use crate::{Expression as E, SampleLevel as Sl}; + + let control_flags = match expression_arena[handle] { + E::Access { base, index } => self.add_ref(base) | self.add_ref(index), + E::AccessIndex { base, .. } => self.add_ref(base), + E::Constant(_) => ControlFlags::empty(), + E::Compose { ref components, .. } => { + let mut accum = ControlFlags::empty(); + for &comp in components { + accum |= self.add_ref(comp); + } + accum + } + E::FunctionArgument(_) => ControlFlags::NON_UNIFORM_RESULT, //TODO? + E::GlobalVariable(handle) => { + let var = &global_var_arena[handle]; + match var.binding { + Some(crate::Binding::BuiltIn(built_in)) => match built_in { + crate::BuiltIn::FrontFacing + | crate::BuiltIn::WorkGroupId + | crate::BuiltIn::WorkGroupSize => ControlFlags::empty(), + _ => ControlFlags::NON_UNIFORM_RESULT, + }, + _ if var.class == crate::StorageClass::Input + && var.interpolation == Some(crate::Interpolation::Flat) => + { + ControlFlags::empty() + } + _ => ControlFlags::NON_UNIFORM_RESULT, + } + } + E::LocalVariable(_) => { + ControlFlags::NON_UNIFORM_RESULT //TODO? + } + E::Load { pointer } => self.add_ref(pointer), + E::ImageSample { + image, + sampler, + coordinate, + array_index, + offset: _, + level, + depth_ref, + } => { + self.sampling_set.insert(SamplingKey { + image: match expression_arena[image] { + crate::Expression::GlobalVariable(var) => var, + ref other => { + return Err(AnalysisError::ExpectedGlobalVariable(other.clone())) + } + }, + sampler: match expression_arena[sampler] { + crate::Expression::GlobalVariable(var) => var, + ref other => { + return Err(AnalysisError::ExpectedGlobalVariable(other.clone())) + } + }, + }); + let array_flags = match array_index { + Some(h) => self.add_ref(h), + None => ControlFlags::empty(), + }; + let level_flags = match level { + Sl::Auto => ControlFlags::REQUIRE_UNIFORM, + Sl::Zero => ControlFlags::empty(), + Sl::Exact(h) | Sl::Bias(h) => self.add_ref(h), + Sl::Gradient { x, y } => self.add_ref(x) | self.add_ref(y), + }; + let dref_flags = match depth_ref { + Some(h) => self.add_ref(h), + None => ControlFlags::empty(), + }; + self.add_ref(image) + | self.add_ref(sampler) + | self.add_ref(coordinate) + | array_flags + | level_flags + | dref_flags + } + E::ImageLoad { + image, + coordinate, + array_index, + index, + } => { + let array_flags = match array_index { + Some(h) => self.add_ref(h), + None => ControlFlags::empty(), + }; + let index_flags = match index { + Some(h) => self.add_ref(h), + None => ControlFlags::empty(), + }; + self.add_ref(image) | self.add_ref(coordinate) | array_flags | index_flags + } + E::ImageQuery { image, query } => { + let query_flags = match query { + crate::ImageQuery::Size { level: Some(h) } => self.add_ref(h), + _ => ControlFlags::empty(), + }; + self.add_ref(image) | query_flags + } + E::Unary { expr, .. } => self.add_ref(expr), + E::Binary { left, right, .. } => self.add_ref(left) | self.add_ref(right), + E::Select { + condition, + accept, + reject, + } => self.add_ref(condition) | self.add_ref(accept) | self.add_ref(reject), + E::Derivative { expr, .. } => ControlFlags::REQUIRE_UNIFORM | self.add_ref(expr), + E::Relational { argument, .. } => self.add_ref(argument), + E::Math { + arg, arg1, arg2, .. + } => { + let arg1_flags = match arg1 { + Some(h) => self.add_ref(h), + None => ControlFlags::empty(), + }; + let arg2_flags = match arg2 { + Some(h) => self.add_ref(h), + None => ControlFlags::empty(), + }; + self.add_ref(arg) | arg1_flags | arg2_flags + } + E::As { expr, .. } => self.add_ref(expr), + E::Call { + function, + ref arguments, + } => { + let other_info = &other_functions[function.index()]; + for key in other_info.sampling_set.iter() { + self.sampling_set.insert(key.clone()); + } + let mut accum = other_info.control_flags; + for &argument in arguments { + accum |= self.add_ref(argument); + } + accum + } + E::ArrayLength(expr) => self.add_ref(expr), + }; + + self.expressions[handle.index()] = ExpressionInfo { + control_flags, + ref_count: 0, + }; + Ok(()) + } + + fn process_block( + &mut self, + statements: &[crate::Statement], + other_functions: &[FunctionInfo], + mut is_uniform: bool, + ) -> Result { + use crate::Statement as S; + let mut block_flags = ControlFlags::empty(); + for statement in statements { + let flags = match *statement { + S::Break | S::Continue => ControlFlags::empty(), + S::Kill => ControlFlags::MAY_EXIT, + S::Block(ref b) => self.process_block(b, other_functions, is_uniform)?, + S::If { + condition, + ref accept, + ref reject, + } => { + let flags = self.add_ref(condition); + if flags.contains(ControlFlags::REQUIRE_UNIFORM) && !is_uniform { + log::warn!("If condition {:?} needs uniformity", condition); + return Err(AnalysisError::NonUniformControlFlow); + } + let branch_uniform = + is_uniform && !flags.contains(ControlFlags::NON_UNIFORM_RESULT); + flags + | self.process_block(accept, other_functions, branch_uniform)? + | self.process_block(reject, other_functions, branch_uniform)? + } + S::Switch { + selector, + ref cases, + ref default, + } => { + let mut flags = self.add_ref(selector); + if flags.contains(ControlFlags::REQUIRE_UNIFORM) && !is_uniform { + log::warn!("Switch selector {:?} needs uniformity", selector); + return Err(AnalysisError::NonUniformControlFlow); + } + let branch_uniform = + is_uniform && !flags.contains(ControlFlags::NON_UNIFORM_RESULT); + let mut still_uniform = branch_uniform; + for case in cases.iter() { + let case_flags = + self.process_block(&case.body, other_functions, still_uniform)?; + flags |= case_flags; + if case.fall_through { + still_uniform &= !case_flags.contains(ControlFlags::MAY_EXIT); + } else { + still_uniform = branch_uniform; + } + } + flags | self.process_block(default, other_functions, still_uniform)? + } + S::Loop { + ref body, + ref continuing, + } => { + let flags = self.process_block(body, other_functions, is_uniform)?; + let still_uniform = is_uniform && !flags.contains(ControlFlags::MAY_EXIT); + self.process_block(continuing, other_functions, still_uniform)? + } + S::Return { value } => { + let flags = match value { + Some(expr) => self.add_ref(expr), + None => ControlFlags::empty(), + }; + ControlFlags::MAY_EXIT | flags + } + S::Store { pointer, value } => self.add_ref(pointer) | self.add_ref(value), + S::Call { + function, + ref arguments, + } => { + let mut flags = other_functions[function.index()].control_flags; + for &argument in arguments { + flags |= self.add_ref(argument); + } + flags + } + }; + + if flags.contains(ControlFlags::REQUIRE_UNIFORM) && !is_uniform { + return Err(AnalysisError::NonUniformControlFlow); + } + is_uniform &= !flags.contains(ControlFlags::MAY_EXIT); + block_flags |= flags; + } + Ok(block_flags) + } +} + +#[derive(Default)] +pub struct Analysis { + functions: Vec, + entry_points: crate::FastHashMap<(crate::ShaderStage, String), FunctionInfo>, +} + +impl Analysis { + fn process_function( + &self, + fun: &crate::Function, + global_var_arena: &Arena, + ) -> Result { + let mut info = FunctionInfo { + control_flags: ControlFlags::empty(), + sampling_set: crate::FastHashSet::default(), + expressions: vec![ExpressionInfo::default(); fun.expressions.len()].into_boxed_slice(), + }; + + for (handle, _) in fun.expressions.iter() { + info.process_expression(handle, &fun.expressions, global_var_arena, &self.functions)?; + } + + info.control_flags = info.process_block(&fun.body, &self.functions, true)?; + + Ok(info) + } + + pub fn new(module: &crate::Module) -> Result { + let mut this = Analysis { + functions: Vec::with_capacity(module.functions.len()), + entry_points: crate::FastHashMap::default(), + }; + for (_, fun) in module.functions.iter() { + let info = this.process_function(fun, &module.global_variables)?; + this.functions.push(info); + } + + for (key, ep) in module.entry_points.iter() { + let info = this.process_function(&ep.function, &module.global_variables)?; + this.entry_points.insert(key.clone(), info); + } + + Ok(this) + } +} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 5dec4285b..6755fdfc6 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,5 +1,6 @@ //! Module processing functionality. +pub mod analyzer; #[cfg(feature = "petgraph")] mod call_graph; mod interface; From bde43cbec6e502d60cc3cf55b9e83d9fd33c9349 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 11 Feb 2021 01:24:40 -0500 Subject: [PATCH 0482/2212] First uniform control flow tests --- src/lib.rs | 1 + src/proc/analyzer.rs | 104 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index abad73cb4..d569af58a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -641,6 +641,7 @@ pub enum ImageQuery { /// An expression that can be evaluated to obtain a value. #[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Expression { diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index fcf968030..13d9d3691 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -39,6 +39,7 @@ pub struct FunctionInfo { } #[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] pub enum AnalysisError { #[error("Expression {0:?} is not a global variable!")] ExpectedGlobalVariable(crate::Expression), @@ -348,3 +349,106 @@ impl Analysis { Ok(this) } } + +#[test] +fn uniform_control_flow() { + use crate::{Expression as E, Statement as S}; + + let mut constant_arena = Arena::new(); + let constant = constant_arena.append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(0), + }, + }); + let mut type_arena = Arena::new(); + let ty = type_arena.append(crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width: 4, + }, + }); + let mut global_var_arena = Arena::new(); + let non_uniform_global = global_var_arena.append(crate::GlobalVariable { + name: None, + init: None, + ty, + binding: Some(crate::Binding::BuiltIn(crate::BuiltIn::VertexIndex)), + class: crate::StorageClass::Input, + interpolation: None, + storage_access: crate::StorageAccess::empty(), + }); + let uniform_global = global_var_arena.append(crate::GlobalVariable { + name: None, + init: None, + ty, + binding: Some(crate::Binding::Location(0)), + class: crate::StorageClass::Input, + interpolation: Some(crate::Interpolation::Flat), + storage_access: crate::StorageAccess::empty(), + }); + + let mut expressions = Arena::new(); + let constant_expr = expressions.append(E::Constant(constant)); + let derivative_expr = expressions.append(E::Derivative { + axis: crate::DerivativeAxis::X, + expr: constant_expr, + }); + let non_uniform_global_expr = expressions.append(E::GlobalVariable(non_uniform_global)); + let uniform_global_expr = expressions.append(E::GlobalVariable(uniform_global)); + + let mut info = FunctionInfo { + control_flags: ControlFlags::empty(), + sampling_set: crate::FastHashSet::default(), + expressions: vec![ExpressionInfo::default(); expressions.len()].into_boxed_slice(), + }; + for (handle, _) in expressions.iter() { + info.process_expression(handle, &expressions, &global_var_arena, &[]) + .unwrap(); + } + assert_eq!(info.expressions[non_uniform_global.index()].ref_count, 1); + assert_eq!(info.expressions[uniform_global_expr.index()].ref_count, 0); + + let stmt_if_uniform = S::If { + condition: uniform_global_expr, + accept: Vec::new(), + reject: vec![S::Store { + pointer: constant_expr, + value: derivative_expr, + }], + }; + assert_eq!( + info.process_block(&[stmt_if_uniform], &[], true), + Ok(ControlFlags::REQUIRE_UNIFORM), + ); + assert_eq!(info.expressions[constant_expr.index()].ref_count, 2); + + let stmt_if_non_uniform = S::If { + condition: non_uniform_global_expr, + accept: vec![S::Store { + pointer: constant_expr, + value: derivative_expr, + }], + reject: Vec::new(), + }; + assert_eq!( + info.process_block(&[stmt_if_non_uniform], &[], true), + Err(AnalysisError::NonUniformControlFlow), + ); + assert_eq!(info.expressions[derivative_expr.index()].ref_count, 2); + + let stmt_return_non_uniform = S::Return { + value: Some(non_uniform_global_expr), + }; + assert_eq!( + info.process_block(&[stmt_return_non_uniform], &[], false), + Ok(ControlFlags::NON_UNIFORM_RESULT | ControlFlags::MAY_EXIT), + ); + assert_eq!( + info.expressions[non_uniform_global_expr.index()].ref_count, + 2 + ); +} From eae40383d08d2d63af54d0f6990f471c74a96ac3 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 11 Feb 2021 21:17:36 -0500 Subject: [PATCH 0483/2212] Add uniform control flow analysis to the validator --- src/proc/analyzer.rs | 27 +++++++++++++++++---------- src/proc/validator.rs | 26 ++++++++++++++++---------- tests/parse.rs | 2 +- 3 files changed, 34 insertions(+), 21 deletions(-) diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 13d9d3691..6ff4c70fc 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -79,19 +79,26 @@ impl FunctionInfo { E::FunctionArgument(_) => ControlFlags::NON_UNIFORM_RESULT, //TODO? E::GlobalVariable(handle) => { let var = &global_var_arena[handle]; - match var.binding { - Some(crate::Binding::BuiltIn(built_in)) => match built_in { + let uniform = if let Some(crate::Binding::BuiltIn(built_in)) = var.binding { + match built_in { crate::BuiltIn::FrontFacing | crate::BuiltIn::WorkGroupId - | crate::BuiltIn::WorkGroupSize => ControlFlags::empty(), - _ => ControlFlags::NON_UNIFORM_RESULT, - }, - _ if var.class == crate::StorageClass::Input - && var.interpolation == Some(crate::Interpolation::Flat) => - { - ControlFlags::empty() + | crate::BuiltIn::WorkGroupSize => true, + _ => false, } - _ => ControlFlags::NON_UNIFORM_RESULT, + } else { + use crate::StorageClass as Sc; + match var.class { + Sc::Input => var.interpolation == Some(crate::Interpolation::Flat), + Sc::Output | Sc::Function | Sc::Private | Sc::WorkGroup => false, + Sc::Uniform | Sc::Handle | Sc::PushConstant => true, + Sc::Storage => !var.storage_access.contains(crate::StorageAccess::STORE), + } + }; + if uniform { + ControlFlags::empty() + } else { + ControlFlags::NON_UNIFORM_RESULT } } E::LocalVariable(_) => { diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 628a5c48c..a3e7fd15e 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -1,4 +1,7 @@ -use super::typifier::{ResolveContext, ResolveError, Typifier}; +use super::{ + analyzer::{Analysis, AnalysisError}, + typifier::{ResolveContext, ResolveError, Typifier}, +}; use crate::arena::{Arena, Handle}; use bit_set::BitSet; @@ -23,7 +26,7 @@ pub struct Validator { bind_group_masks: Vec, } -#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum TypeError { #[error("The {0:?} scalar width {1} is not supported")] InvalidWidth(crate::ScalarKind, crate::Bytes), @@ -37,7 +40,7 @@ pub enum TypeError { MissingBlockDecoration, } -#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum ConstantError { #[error("The type doesn't match the constant")] InvalidType, @@ -47,7 +50,7 @@ pub enum ConstantError { UnresolvedSize(Handle), } -#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum GlobalVariableError { #[error("Usage isn't compatible with the storage class")] InvalidUsage, @@ -66,13 +69,13 @@ pub enum GlobalVariableError { InvalidBuiltInType(crate::BuiltIn), } -#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum LocalVariableError { #[error("Initializer doesn't match the variable type")] InitializerType, } -#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum FunctionError { #[error(transparent)] Resolve(#[from] ResolveError), @@ -90,7 +93,7 @@ pub enum FunctionError { InvalidArgumentType { index: usize, name: String }, } -#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum EntryPointError { #[error("Early depth test is not applicable")] UnexpectedEarlyDepthTest, @@ -114,7 +117,7 @@ pub enum EntryPointError { Function(#[from] FunctionError), } -#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum ValidationError { #[error("Type {handle:?} '{name}' is invalid: {error:?}")] Type { @@ -142,6 +145,8 @@ pub enum ValidationError { name: String, error: EntryPointError, }, + #[error(transparent)] + Analysis(#[from] AnalysisError), #[error("Module is corrupted")] Corrupted, } @@ -690,7 +695,7 @@ impl Validator { } /// Check the given module to be valid. - pub fn validate(&mut self, module: &crate::Module) -> Result<(), ValidationError> { + pub fn validate(&mut self, module: &crate::Module) -> Result { self.typifier.clear(); self.type_flags.clear(); self.type_flags @@ -742,6 +747,7 @@ impl Validator { })?; } - Ok(()) + let analysis = Analysis::new(module)?; + Ok(analysis) } } diff --git a/tests/parse.rs b/tests/parse.rs index 9e736d7ec..e9d0cdf9b 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -16,7 +16,7 @@ fn check_glsl(name: &str) { match naga::front::glsl::parse_str(&input, "main", stage, Default::default()) { Ok(m) => match naga::proc::Validator::new().validate(&m) { - Ok(()) => (), + Ok(_analysis) => (), Err(e) => panic!("Unable to validate {}: {:?}", name, e), }, Err(e) => panic!("Unable to parse {}: {:?}", name, e), From c1fc5d6424c3188b6cbf39edaa86d8febdbf4082 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 12 Feb 2021 01:39:08 -0500 Subject: [PATCH 0484/2212] [msl] re-use expression results based on the analysis --- examples/convert.rs | 5 +- src/back/glsl/mod.rs | 2 +- src/back/msl/mod.rs | 10 +- src/back/msl/writer.rs | 197 ++++++++++++++++++++++++++++++++------ src/front/global_usage.rs | 4 +- src/lib.rs | 2 + src/proc/analyzer.rs | 26 ++++- src/proc/interface.rs | 10 +- tests/out/shadow.msl.snap | 7 +- tests/out/skybox.msl.snap | 5 +- tests/snapshots.rs | 14 ++- 11 files changed, 230 insertions(+), 52 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 82c03a734..4cb419fd5 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -147,7 +147,8 @@ fn main() { }; // validate the IR - naga::proc::Validator::new() + #[cfg_attr(not(feature = "msl-out"), allow(unused_variables))] + let analysis = naga::proc::Validator::new() .validate(&module) .unwrap_pretty(); @@ -190,7 +191,7 @@ fn main() { spirv_cross_compatibility: false, binding_map, }; - let (msl, _) = msl::write_string(&module, &options).unwrap(); + let (msl, _) = msl::write_string(&module, &analysis, &options).unwrap(); fs::write(&args[2], msl).unwrap(); } #[cfg(feature = "spv-out")] diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 4762b7975..528deed9f 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1908,7 +1908,7 @@ struct TextureMappingVisitor<'a> { } impl<'a> Visitor for TextureMappingVisitor<'a> { - fn visit_expr(&mut self, expr: &crate::Expression) { + fn visit_expr(&mut self, _: Handle, expr: &crate::Expression) { // We only care about `ImageSample` and `ImageLoad` // // Both `image` and `sampler` are `Expression::GlobalVariable` otherwise the module is diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 53c8ddf38..14dbaaed8 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -14,7 +14,11 @@ the output struct. If there is a structure in the outputs, and it contains any b we move them up to the root output structure that we define ourselves. !*/ -use crate::{arena::Handle, proc::ResolveError, FastHashMap}; +use crate::{ + arena::Handle, + proc::{analyzer::Analysis, ResolveError}, + FastHashMap, +}; use std::{ io::{Error as IoError, Write}, string::FromUtf8Error, @@ -66,6 +70,7 @@ pub enum Error { UnexpectedSampleLevel(crate::SampleLevel), UnsupportedCall(String), UnsupportedDynamicArrayLength, + FeatureNotImplemented(String), /// The source IR is not valid. Validation, } @@ -222,10 +227,11 @@ pub struct TranslationInfo { pub fn write_string( module: &crate::Module, + analysis: &Analysis, options: &Options, ) -> Result<(String, TranslationInfo), Error> { let mut w = writer::Writer::new(Vec::new()); - let info = w.write(module, options)?; + let info = w.write(module, analysis, options)?; let string = String::from_utf8(w.finish())?; Ok((string, info)) } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8fb22119f..c88f71b02 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,18 +1,23 @@ use super::{keywords::RESERVED, Error, LocationMode, Options, TranslationInfo}; use crate::{ arena::Handle, - proc::{EntryPointIndex, NameKey, Namer, ResolveContext, Typifier}, + proc::{ + analyzer::{Analysis, FunctionInfo}, + EntryPointIndex, Interface, NameKey, Namer, ResolveContext, Typifier, Visitor, + }, FastHashMap, }; +use bit_set::BitSet; use std::{ fmt::{Display, Error as FmtError, Formatter}, io::Write, - iter, + iter, mem, }; const NAMESPACE: &str = "metal"; const INDENT: &str = " "; +#[derive(Clone)] struct Level(usize); impl Level { fn next(&self) -> Self { @@ -64,8 +69,10 @@ impl<'a> TypedGlobalVariable<'a> { pub struct Writer { out: W, names: FastHashMap, + named_expressions: BitSet, typifier: Typifier, namer: Namer, + temp_bake_handles: Vec>, } fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { @@ -113,6 +120,39 @@ impl crate::StorageClass { } } +struct BakeExpressionVisitor<'a> { + named_expressions: &'a mut BitSet, + bake_handles: &'a mut Vec>, + fun_info: &'a FunctionInfo, + exclude: Option>, +} +impl Visitor for BakeExpressionVisitor<'_> { + fn visit_expr(&mut self, handle: Handle, expr: &crate::Expression) { + use crate::Expression as E; + // filter out the expressions that don't need to bake + let min_ref_count = match *expr { + // The following expressions can be inlined nicely. + E::AccessIndex { .. } + | E::Constant(_) + | E::FunctionArgument(_) + | E::GlobalVariable(_) + | E::LocalVariable(_) => !0, + // Image sampling and function calling are nice to isolate + // into separate statements even when done only once. + E::ImageSample { .. } | E::ImageLoad { .. } | E::Call { .. } => 1, + // Bake only expressions referenced more than once. + _ => 2, + }; + + let modifier = if self.exclude == Some(handle) { 1 } else { 0 }; + if self.fun_info[handle].ref_count - modifier >= min_ref_count + && self.named_expressions.insert(handle.index()) + { + self.bake_handles.push(handle); + } + } +} + enum FunctionOrigin { Handle(Handle), EntryPoint(EntryPointIndex), @@ -124,14 +164,22 @@ struct ExpressionContext<'a> { module: &'a crate::Module, } +struct StatementContext<'a> { + expression: ExpressionContext<'a>, + fun_info: &'a FunctionInfo, + return_value: Option<&'a str>, +} + impl Writer { /// Creates a new `Writer` instance. pub fn new(out: W) -> Self { Writer { out, names: FastHashMap::default(), + named_expressions: BitSet::new(), typifier: Typifier::new(), namer: Namer::default(), + temp_bake_handles: Vec::new(), } } @@ -216,6 +264,11 @@ impl Writer { expr_handle: Handle, context: &ExpressionContext, ) -> Result<(), Error> { + if self.named_expressions.contains(expr_handle.index()) { + write!(self.out, "expr{}", expr_handle.index())?; + return Ok(()); + } + let expression = &context.function.expressions[expr_handle]; log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { @@ -684,12 +737,76 @@ impl Writer { Ok(()) } + // Write down any required intermediate results + fn prepare_expression( + &mut self, + level: Level, + root_handle: Handle, + context: &StatementContext, + exclude_root: bool, + ) -> Result<(), Error> { + // set up the search + let mut interface = Interface { + expressions: &context.expression.function.expressions, + local_variables: &context.expression.function.local_variables, + visitor: BakeExpressionVisitor { + named_expressions: &mut self.named_expressions, + bake_handles: &mut self.temp_bake_handles, + fun_info: context.fun_info, + exclude: if exclude_root { + Some(root_handle) + } else { + None + }, + }, + }; + // populate the bake handles + interface.traverse_expr(root_handle); + // bake + let mut temp_bake_handles = mem::replace(&mut self.temp_bake_handles, Vec::new()); + for handle in temp_bake_handles.drain(..).rev() { + write!(self.out, "{}", level)?; + match self.typifier.get_handle(handle) { + Ok(ty_handle) => { + let ty_name = &self.names[&NameKey::Type(ty_handle)]; + write!(self.out, "{}", ty_name)?; + } + Err(&crate::TypeInner::Scalar { kind, .. }) => { + write!(self.out, "{}", scalar_kind_string(kind))?; + } + Err(&crate::TypeInner::Vector { size, kind, .. }) => { + write!( + self.out, + "{}::{}{}", + NAMESPACE, + scalar_kind_string(kind), + vector_size_string(size) + )?; + } + Err(other) => { + log::error!("Type {:?} isn't a known local", other); + return Err(Error::FeatureNotImplemented("weird local type".to_string())); + } + } + + //TODO: figure out the naming scheme that wouldn't collide with user names. + write!(self.out, " expr{} = ", handle.index())?; + // Make sure to temporarily unblock the expression before writing it down. + self.named_expressions.remove(handle.index()); + self.put_expression(handle, &context.expression)?; + self.named_expressions.insert(handle.index()); + writeln!(self.out, ";")?; + } + + self.temp_bake_handles = temp_bake_handles; + Ok(()) + } + fn put_block( &mut self, level: Level, statements: &[crate::Statement], - context: &ExpressionContext, - return_value: Option<&str>, + context: &StatementContext, ) -> Result<(), Error> { for statement in statements { log::trace!("statement[{}] {:?}", level.0, statement); @@ -697,7 +814,7 @@ impl Writer { crate::Statement::Block(ref block) => { if !block.is_empty() { writeln!(self.out, "{}{{", level)?; - self.put_block(level.next(), block, context, return_value)?; + self.put_block(level.next(), block, context)?; writeln!(self.out, "{}}}", level)?; } } @@ -706,13 +823,14 @@ impl Writer { ref accept, ref reject, } => { + self.prepare_expression(level.clone(), condition, context, false)?; write!(self.out, "{}if (", level)?; - self.put_expression(condition, context)?; + self.put_expression(condition, &context.expression)?; writeln!(self.out, ") {{")?; - self.put_block(level.next(), accept, context, return_value)?; + self.put_block(level.next(), accept, context)?; if !reject.is_empty() { writeln!(self.out, "{}}} else {{", level)?; - self.put_block(level.next(), reject, context, return_value)?; + self.put_block(level.next(), reject, context)?; } writeln!(self.out, "{}}}", level)?; } @@ -721,20 +839,21 @@ impl Writer { ref cases, ref default, } => { + self.prepare_expression(level.clone(), selector, context, false)?; write!(self.out, "{}switch(", level)?; - self.put_expression(selector, context)?; + self.put_expression(selector, &context.expression)?; writeln!(self.out, ") {{")?; let lcase = level.next(); for case in cases.iter() { writeln!(self.out, "{}case {}: {{", lcase, case.value)?; - self.put_block(lcase.next(), &case.body, context, return_value)?; + self.put_block(lcase.next(), &case.body, context)?; if case.fall_through { writeln!(self.out, "{}break;", lcase.next())?; } writeln!(self.out, "{}}}", lcase)?; } writeln!(self.out, "{}default: {{", lcase)?; - self.put_block(lcase.next(), default, context, return_value)?; + self.put_block(lcase.next(), default, context)?; writeln!(self.out, "{}}}", lcase)?; writeln!(self.out, "{}}}", level)?; } @@ -748,13 +867,13 @@ impl Writer { writeln!(self.out, "{}while(true) {{", level)?; let lif = level.next(); writeln!(self.out, "{}if (!{}) {{", lif, gate_name)?; - self.put_block(lif.next(), continuing, context, return_value)?; + self.put_block(lif.next(), continuing, context)?; writeln!(self.out, "{}}}", lif)?; writeln!(self.out, "{}{} = false;", lif, gate_name)?; } else { writeln!(self.out, "{}while(true) {{", level)?; } - self.put_block(level.next(), body, context, return_value)?; + self.put_block(level.next(), body, context)?; writeln!(self.out, "{}}}", level)?; } crate::Statement::Break => { @@ -766,8 +885,9 @@ impl Writer { crate::Statement::Return { value: Some(expr_handle), } => { + self.prepare_expression(level.clone(), expr_handle, context, true)?; write!(self.out, "{}return ", level)?; - self.put_expression(expr_handle, context)?; + self.put_expression(expr_handle, &context.expression)?; writeln!(self.out, ";")?; } crate::Statement::Return { value: None } => { @@ -775,25 +895,28 @@ impl Writer { self.out, "{}return {};", level, - return_value.unwrap_or_default(), + context.return_value.unwrap_or_default(), )?; } crate::Statement::Kill => { writeln!(self.out, "{}discard_fragment();", level)?; } crate::Statement::Store { pointer, value } => { - //write!(self.out, "{}*", INDENT)?; + self.prepare_expression(level.clone(), value, context, true)?; write!(self.out, "{}", level)?; - self.put_expression(pointer, context)?; + self.put_expression(pointer, &context.expression)?; write!(self.out, " = ")?; - self.put_expression(value, context)?; + self.put_expression(value, &context.expression)?; writeln!(self.out, ";")?; } crate::Statement::Call { function, ref arguments, } => { - self.put_local_call(function, arguments, context)?; + for &arg in arguments { + self.prepare_expression(level.clone(), arg, context, false)?; + } + self.put_local_call(function, arguments, &context.expression)?; writeln!(self.out, ";")?; } } @@ -804,6 +927,7 @@ impl Writer { pub fn write( &mut self, module: &crate::Module, + analysis: &Analysis, options: &Options, ) -> Result { self.names.clear(); @@ -814,7 +938,7 @@ impl Writer { writeln!(self.out)?; self.write_type_defs(module)?; - self.write_functions(module, options) + self.write_functions(module, analysis, options) } fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { @@ -956,6 +1080,7 @@ impl Writer { fn write_functions( &mut self, module: &crate::Module, + analysis: &Analysis, options: &Options, ) -> Result { let mut pass_through_globals = Vec::new(); @@ -1022,12 +1147,17 @@ impl Writer { writeln!(self.out, ";")?; } - let context = ExpressionContext { - function: fun, - origin: FunctionOrigin::Handle(fun_handle), - module, + let context = StatementContext { + expression: ExpressionContext { + function: fun, + origin: FunctionOrigin::Handle(fun_handle), + module, + }, + fun_info: &analysis[fun_handle], + return_value: None, }; - self.put_block(Level(1), &fun.body, &context, None)?; + self.named_expressions.clear(); + self.put_block(Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; writeln!(self.out)?; } @@ -1035,7 +1165,7 @@ impl Writer { let mut info = TranslationInfo { entry_point_names: Vec::with_capacity(module.entry_points.len()), }; - for (ep_index, (&(stage, _), ep)) in module.entry_points.iter().enumerate() { + for (ep_index, (&(stage, ref ep_name), ep)) in module.entry_points.iter().enumerate() { let fun = &ep.function; self.typifier.resolve_all( &fun.expressions, @@ -1222,12 +1352,17 @@ impl Writer { writeln!(self.out, ";")?; } - let context = ExpressionContext { - function: fun, - origin: FunctionOrigin::EntryPoint(ep_index as _), - module, + let context = StatementContext { + expression: ExpressionContext { + function: fun, + origin: FunctionOrigin::EntryPoint(ep_index as _), + module, + }, + fun_info: analysis.get_entry_point(stage, ep_name), + return_value, }; - self.put_block(Level(1), &fun.body, &context, return_value)?; + self.named_expressions.clear(); + self.put_block(Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; let is_last = ep_index == module.entry_points.len() - 1; if !is_last { diff --git a/src/front/global_usage.rs b/src/front/global_usage.rs index 0cc5fa866..e5a43509c 100644 --- a/src/front/global_usage.rs +++ b/src/front/global_usage.rs @@ -9,13 +9,13 @@ struct GlobalUseVisitor<'a> { } impl Visitor for GlobalUseVisitor<'_> { - fn visit_expr(&mut self, expr: &crate::Expression) { + fn visit_expr(&mut self, _: Handle, expr: &crate::Expression) { if let crate::Expression::GlobalVariable(handle) = expr { self.usage[handle.index()] |= crate::GlobalUse::READ; } } - fn visit_lhs_expr(&mut self, expr: &crate::Expression) { + fn visit_lhs_expr(&mut self, _: Handle, expr: &crate::Expression) { if let crate::Expression::GlobalVariable(handle) = expr { self.usage[handle.index()] |= crate::GlobalUse::WRITE; } diff --git a/src/lib.rs b/src/lib.rs index d569af58a..c87af3c53 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -640,6 +640,8 @@ pub enum ImageQuery { } /// An expression that can be evaluated to obtain a value. +/// +/// This is a Single Static Assignment (SSA) scheme similar to SPIR-V. #[derive(Clone, Debug)] #[cfg_attr(test, derive(PartialEq))] #[cfg_attr(feature = "serialize", derive(Serialize))] diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 6ff4c70fc..9dcfbf219 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -7,6 +7,7 @@ Figures out the following properties: !*/ use crate::arena::{Arena, Handle}; +use std::ops; bitflags::bitflags! { #[derive(Default)] @@ -35,7 +36,14 @@ pub struct ExpressionInfo { pub struct FunctionInfo { pub control_flags: ControlFlags, pub sampling_set: crate::FastHashSet, - pub expressions: Box<[ExpressionInfo]>, + expressions: Box<[ExpressionInfo]>, +} + +impl ops::Index> for FunctionInfo { + type Output = ExpressionInfo; + fn index(&self, handle: Handle) -> &ExpressionInfo { + &self.expressions[handle.index()] + } } #[derive(Clone, Debug, thiserror::Error)] @@ -355,6 +363,22 @@ impl Analysis { Ok(this) } + + pub fn get_entry_point(&self, stage: crate::ShaderStage, name: &str) -> &FunctionInfo { + let (_, info) = self + .entry_points + .iter() + .find(|(key, _)| key.0 == stage && key.1 == name) + .unwrap(); + info + } +} + +impl ops::Index> for Analysis { + type Output = FunctionInfo; + fn index(&self, handle: Handle) -> &FunctionInfo { + &self.functions[handle.index()] + } } #[test] diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 13f6f1f71..ca6804388 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -7,8 +7,8 @@ pub struct Interface<'a, T> { } pub trait Visitor { - fn visit_expr(&mut self, _: &crate::Expression) {} - fn visit_lhs_expr(&mut self, _: &crate::Expression) {} + fn visit_expr(&mut self, _: Handle, _: &crate::Expression) {} + fn visit_lhs_expr(&mut self, _: Handle, _: &crate::Expression) {} fn visit_fun(&mut self, _: Handle) {} } @@ -16,12 +16,12 @@ impl<'a, T> Interface<'a, T> where T: Visitor, { - fn traverse_expr(&mut self, handle: Handle) { + pub fn traverse_expr(&mut self, handle: Handle) { use crate::Expression as E; let expr = &self.expressions[handle]; - self.visitor.visit_expr(expr); + self.visitor.visit_expr(handle, expr); match *expr { E::Access { base, index } => { @@ -200,7 +200,7 @@ where _ => break, } } - self.visitor.visit_lhs_expr(&self.expressions[left]); + self.visitor.visit_lhs_expr(left, &self.expressions[left]); self.traverse_expr(value); } S::Call { diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 2a8f90f46..ccb2a01ba 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -52,7 +52,8 @@ type7 fetch_shadow( if ((homogeneous_coords.w <= 0.0)) { return 1.0; } - return t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) * (1.0 / homogeneous_coords.w)) + metal::float2(0.5, 0.5)), static_cast(light_id), (homogeneous_coords.z * (1.0 / homogeneous_coords.w))); + float expr15 = (1.0 / homogeneous_coords.w); + return t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) * expr15) + metal::float2(0.5, 0.5)), static_cast(light_id), (homogeneous_coords.z * expr15)); } struct fs_mainInput { @@ -83,7 +84,9 @@ fragment fs_mainOutput fs_main( if ((i >= metal::min(u_globals.num_lights.x, 10u))) { break; } - color1 = (color1 + ((fetch_shadow(i, (s_lights.data[i].proj * input.in_position_fs), t_shadow, sampler_shadow) * metal::max(0.0, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(s_lights.data[i].pos.x, s_lights.data[i].pos.y, s_lights.data[i].pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(s_lights.data[i].color.x, s_lights.data[i].color.y, s_lights.data[i].color.z))); + Light expr18 = s_lights.data[i]; + type7 expr21 = fetch_shadow(i, (expr18.proj * input.in_position_fs), t_shadow, sampler_shadow); + color1 = (color1 + ((expr21 * metal::max(0.0, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(expr18.pos.x, expr18.pos.y, expr18.pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(expr18.color.x, expr18.color.y, expr18.color.z))); } output.out_color_fs = metal::float4(color1, 1.0); return output; diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 1faf661cf..c05cba30c 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -47,9 +47,10 @@ vertex vs_mainOutput vs_main( type unprojected; tmp1_ = (static_cast(in_vertex_index) / 2); tmp2_ = (static_cast(in_vertex_index) & 1); - unprojected = (r_data.proj_inv * metal::float4(((static_cast(tmp1_) * 4.0) - 1.0), ((static_cast(tmp2_) * 4.0) - 1.0), 0.0, 1.0)); + type expr24 = metal::float4(((static_cast(tmp1_) * 4.0) - 1.0), ((static_cast(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + unprojected = (r_data.proj_inv * expr24); output.out_uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z)); - output.out_position = metal::float4(((static_cast(tmp1_) * 4.0) - 1.0), ((static_cast(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + output.out_position = expr24; return output; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 7523bb0b9..8fae779a6 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -75,7 +75,12 @@ fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { } #[cfg(feature = "msl-out")] -fn check_output_msl(module: &naga::Module, name: &str, params: &Parameters) { +fn check_output_msl( + module: &naga::Module, + analysis: &naga::proc::analyzer::Analysis, + name: &str, + params: &Parameters, +) { use naga::back::msl; let mut binding_map = msl::BindingMap::default(); @@ -104,7 +109,7 @@ fn check_output_msl(module: &naga::Module, name: &str, params: &Parameters) { binding_map, }; - let (msl, _) = msl::write_string(&module, &options).unwrap(); + let (msl, _) = msl::write_string(module, analysis, &options).unwrap(); with_snapshot_settings(|| { insta::assert_snapshot!(format!("{}.msl", name), msl); @@ -143,7 +148,8 @@ fn convert_wgsl(name: &str, language: Language) { .expect("Couldn't find wgsl file"), ) .unwrap(); - naga::proc::Validator::new().validate(&module).unwrap(); + #[cfg_attr(not(feature = "msl-out"), allow(unused_variables))] + let analysis = naga::proc::Validator::new().validate(&module).unwrap(); #[cfg(feature = "spv-out")] { @@ -154,7 +160,7 @@ fn convert_wgsl(name: &str, language: Language) { #[cfg(feature = "msl-out")] { if language.contains(Language::METAL) { - check_output_msl(&module, name, ¶ms); + check_output_msl(&module, &analysis, name, ¶ms); } } #[cfg(feature = "glsl-out")] From 08001981bad4f18b6f6e4ab29f98477bc709ff97 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Feb 2021 20:35:46 -0500 Subject: [PATCH 0485/2212] Add comments to Analysis methods and ControlFlags --- src/proc/analyzer.rs | 47 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 9dcfbf219..8c03f0623 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -12,11 +12,32 @@ use std::ops; bitflags::bitflags! { #[derive(Default)] pub struct ControlFlags: u8 { - /// The result is not dynamically uniform. + /// The result (of an expression) is not dynamically uniform. + /// + /// This means, when the relevant invocations are scheduled on a compute unit, + /// they have to use vector registers to store an individual value + /// per invocation. + /// + /// Whenever the control flow is conditioned on such value, + /// the hardware needs to keep track of the mask of invocations, + /// and process all branches of the control flow. + /// + /// Any operations that depend on non-uniform results also produce non-uniform. const NON_UNIFORM_RESULT = 0x1; /// Uniform control flow is required by the code. + /// + /// Some operations can only be done within uniform control flow: + /// derivatives and auto-level image sampling in fragment shaders, + /// and group barriers in compute shaders. + /// + /// This flag bubbles up from child expressions to parents. const REQUIRE_UNIFORM = 0x2; /// The code may exit the control flow. + /// + /// `Kill` and `Return` operations have an effect on all the other + /// expressions/statements that are evaluated after them. They act as + /// pervasive control flow branching. Thus, even after the remaining + /// merge together, we are blocked from considering the merged flow uniform. const MAY_EXIT = 0x4; } } @@ -64,6 +85,9 @@ impl FunctionInfo { info.control_flags } + /// Computes the control flags of a given expression, and store them + /// in `self.expressions`. Also, bumps the reference counts on + /// dependent expressions. fn process_expression( &mut self, handle: Handle, @@ -89,7 +113,9 @@ impl FunctionInfo { let var = &global_var_arena[handle]; let uniform = if let Some(crate::Binding::BuiltIn(built_in)) = var.binding { match built_in { + // per-polygon built-ins are uniform crate::BuiltIn::FrontFacing + // per-work-group built-ins are uniform | crate::BuiltIn::WorkGroupId | crate::BuiltIn::WorkGroupSize => true, _ => false, @@ -97,10 +123,15 @@ impl FunctionInfo { } else { use crate::StorageClass as Sc; match var.class { + // only flat inputs are uniform Sc::Input => var.interpolation == Some(crate::Interpolation::Flat), Sc::Output | Sc::Function | Sc::Private | Sc::WorkGroup => false, - Sc::Uniform | Sc::Handle | Sc::PushConstant => true, - Sc::Storage => !var.storage_access.contains(crate::StorageAccess::STORE), + // uniform data + Sc::Uniform | Sc::PushConstant => true, + // storage data is only uniform when read-only + Sc::Handle | Sc::Storage => { + !var.storage_access.contains(crate::StorageAccess::STORE) + } } }; if uniform { @@ -141,6 +172,7 @@ impl FunctionInfo { None => ControlFlags::empty(), }; let level_flags = match level { + // implicit derivatives for LOD require uniform Sl::Auto => ControlFlags::REQUIRE_UNIFORM, Sl::Zero => ControlFlags::empty(), Sl::Exact(h) | Sl::Bias(h) => self.add_ref(h), @@ -187,6 +219,7 @@ impl FunctionInfo { accept, reject, } => self.add_ref(condition) | self.add_ref(accept) | self.add_ref(reject), + // explicit derivatives require uniform E::Derivative { expr, .. } => ControlFlags::REQUIRE_UNIFORM | self.add_ref(expr), E::Relational { argument, .. } => self.add_ref(argument), E::Math { @@ -227,6 +260,11 @@ impl FunctionInfo { Ok(()) } + /// Computes the control flags on the block (as a sequence of statements), + /// and returns them. The parent control flow is uniform if `is_uniform` is true. + /// + /// Returns a `NonUniformControlFlow` error if any of the expressions in the block + /// have `ControlFlags::REQUIRE_UNIFORM` flag, but the current flow is non-uniform. fn process_block( &mut self, statements: &[crate::Statement], @@ -326,6 +364,8 @@ pub struct Analysis { } impl Analysis { + /// Builds the `FunctionInfo` based on the function, and validates the + /// uniform control flow if required by the expressions of this function. fn process_function( &self, fun: &crate::Function, @@ -346,6 +386,7 @@ impl Analysis { Ok(info) } + /// Analyze a module and return the `Analysis`, if successful. pub fn new(module: &crate::Module) -> Result { let mut this = Analysis { functions: Vec::with_capacity(module.functions.len()), From 5de69f72769be320262f14ab1d1306a3281bfd22 Mon Sep 17 00:00:00 2001 From: Systemcluster Date: Sun, 14 Feb 2021 12:21:33 +0100 Subject: [PATCH 0486/2212] Specify line endings in ron snapshot tests --- tests/snapshots.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 8fae779a6..f66fd8b8d 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -226,7 +226,7 @@ fn convert_spv(name: &str) { #[cfg(feature = "serialize")] { - let config = ron::ser::PrettyConfig::default(); + let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); let output = ron::ser::to_string_pretty(&module, config).unwrap(); with_snapshot_settings(|| { insta::assert_snapshot!(format!("{}.ron", name), output); From de5bd772792d9f6ea2282dde65c4b1e7544b9405 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Feb 2021 18:52:00 -0500 Subject: [PATCH 0487/2212] ImageStore statement in IR --- src/back/glsl/mod.rs | 78 +++++++--- src/back/msl/writer.rs | 17 +++ src/back/spv/instructions.rs | 24 +++- src/back/spv/writer.rs | 271 ++++++++++++++++++++++------------- src/front/spv/mod.rs | 7 +- src/front/wgsl/mod.rs | 26 ++++ src/lib.rs | 7 + src/proc/analyzer.rs | 15 ++ src/proc/interface.rs | 13 ++ src/proc/terminator.rs | 1 + 10 files changed, 337 insertions(+), 122 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 528deed9f..14959bbb3 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1129,6 +1129,27 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(value, ctx)?; writeln!(self.out, ";")? } + // Stores a value into an image. + Statement::ImageStore { + image, + coordinate, + array_index, + value, + } => { + // This will only panic if the module is invalid + let dim = match *ctx.typifier.get(image, &self.module.types) { + TypeInner::Image { dim, .. } => dim, + _ => unreachable!(), + }; + + write!(self.out, "imageStore(")?; + self.write_expr(image, ctx)?; + write!(self.out, ", ")?; + self.write_texture_coordinates(coordinate, array_index, dim, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + writeln!(self.out, ");")?; + } // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list Statement::Call { function, @@ -1136,7 +1157,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; - write!(self.out, ");")? + writeln!(self.out, ");")? } } @@ -1162,7 +1183,7 @@ impl<'a, W: Write> Writer<'a, W> { Expression::AccessIndex { base, index } => { self.write_expr(base, ctx)?; - match ctx.typifier.get(base, &self.module.types) { + match *ctx.typifier.get(base, &self.module.types) { TypeInner::Vector { .. } | TypeInner::Matrix { .. } | TypeInner::Array { .. } => write!(self.out, "[{}]", index)?, @@ -1306,7 +1327,7 @@ impl<'a, W: Write> Writer<'a, W> { index, } => { // This will only panic if the module is invalid - let (dim, class) = match ctx.typifier.get(image, &self.module.types) { + let (dim, class) = match *ctx.typifier.get(image, &self.module.types) { TypeInner::Image { dim, arrayed: _, @@ -1324,25 +1345,8 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}(", fun_name)?; self.write_expr(image, ctx)?; - match array_index { - Some(layer_expr) => { - let tex_coord_type = match dim { - crate::ImageDimension::D1 => "ivec2", - crate::ImageDimension::D2 => "ivec3", - crate::ImageDimension::D3 => "ivec4", - crate::ImageDimension::Cube => "ivec4", - }; - write!(self.out, ", {}(", tex_coord_type)?; - self.write_expr(coordinate, ctx)?; - write!(self.out, ", ")?; - self.write_expr(layer_expr, ctx)?; - write!(self.out, ")")?; - } - None => { - write!(self.out, ", ")?; - self.write_expr(coordinate, ctx)?; - } - } + write!(self.out, ", ")?; + self.write_texture_coordinates(coordinate, array_index, dim, ctx)?; if let Some(index_expr) = index { write!(self.out, ", ")?; @@ -1356,7 +1360,7 @@ impl<'a, W: Write> Writer<'a, W> { // - textureSamples/imageSamples Expression::ImageQuery { image, query } => { // This will only panic if the module is invalid - let (dim, class) = match ctx.typifier.get(image, &self.module.types) { + let (dim, class) = match *ctx.typifier.get(image, &self.module.types) { TypeInner::Image { dim, arrayed: _, @@ -1710,6 +1714,34 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + fn write_texture_coordinates( + &mut self, + coordinate: Handle, + array_index: Option>, + dim: crate::ImageDimension, + ctx: &FunctionCtx, + ) -> Result<(), Error> { + match array_index { + Some(layer_expr) => { + let tex_coord_type = match dim { + crate::ImageDimension::D1 => "ivec2", + crate::ImageDimension::D2 => "ivec3", + crate::ImageDimension::D3 => "ivec4", + crate::ImageDimension::Cube => "ivec4", + }; + write!(self.out, "{}(", tex_coord_type)?; + self.write_expr(coordinate, ctx)?; + write!(self.out, ", ")?; + self.write_expr(layer_expr, ctx)?; + write!(self.out, ")")?; + } + None => { + self.write_expr(coordinate, ctx)?; + } + } + Ok(()) + } + /// Helper method used to produce the images mapping that's returned to the user /// /// It takes an iterator of [`Function`](crate::Function) references instead of diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c88f71b02..d51a9e5d0 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -909,6 +909,23 @@ impl Writer { self.put_expression(value, &context.expression)?; writeln!(self.out, ";")?; } + crate::Statement::ImageStore { + image, + coordinate, + array_index, + value, + } => { + self.put_expression(image, &context.expression)?; + write!(self.out, ".write(")?; + self.put_expression(value, &context.expression)?; + write!(self.out, ", ")?; + self.put_expression(coordinate, &context.expression)?; + if let Some(expr) = array_index { + write!(self.out, ", ")?; + self.put_expression(expr, &context.expression)?; + } + write!(self.out, ");")?; + } crate::Statement::Call { function, ref arguments, diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index a4fe76706..82af2d35f 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -233,7 +233,7 @@ impl super::Instruction { instruction.add_operand(depth as u32); instruction.add_operand(arrayed as u32); instruction.add_operand(multi as u32); - instruction.add_operand(sampled as u32); + instruction.add_operand(if sampled { 1 } else { 2 }); let format = match image_class { crate::ImageClass::Storage(format) => match format { @@ -552,6 +552,28 @@ impl super::Instruction { instruction } + pub(super) fn image_read( + result_type_id: Word, + id: Word, + image: Word, + coordinates: Word, + ) -> Self { + let mut instruction = Self::new(Op::ImageRead); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(image); + instruction.add_operand(coordinates); + instruction + } + + pub(super) fn image_write(image: Word, coordinates: Word, value: Word) -> Self { + let mut instruction = Self::new(Op::ImageWrite); + instruction.add_operand(image); + instruction.add_operand(coordinates); + instruction.add_operand(value); + instruction + } + // // Conversion Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 709dd8b92..f5d7fa1e6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,6 +1,9 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ use super::{Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; -use crate::proc::{Layouter, ResolveContext, ResolveError, Typifier}; +use crate::{ + arena::{Arena, Handle}, + proc::{Layouter, ResolveContext, ResolveError, Typifier}, +}; use spirv::Word; use std::collections::hash_map::Entry; use thiserror::Error; @@ -47,7 +50,7 @@ enum RawExpression { struct Function { signature: Option, parameters: Vec, - variables: crate::FastHashMap, LocalVariable>, + variables: crate::FastHashMap, LocalVariable>, blocks: Vec, } @@ -94,11 +97,11 @@ enum LocalType { width: crate::Bytes, }, Pointer { - base: crate::Handle, + base: Handle, class: crate::StorageClass, }, SampledImage { - image_type: crate::Handle, + image_type: Handle, }, } @@ -126,7 +129,7 @@ impl LocalType { #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LookupType { - Handle(crate::Handle), + Handle(Handle), Local(LocalType), } @@ -183,14 +186,14 @@ pub struct Writer { flags: WriterFlags, void_type: u32, lookup_type: crate::FastHashMap, - lookup_function: crate::FastHashMap, Word>, + lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, - lookup_constant: crate::FastHashMap, Word>, + lookup_constant: crate::FastHashMap, Word>, lookup_global_variable: - crate::FastHashMap, (Word, spirv::StorageClass)>, + crate::FastHashMap, (Word, spirv::StorageClass)>, // TODO: this is a type property that depends on the global variable that uses it // so it may require us to duplicate the type! - struct_type_handles: crate::FastHashMap, crate::StorageAccess>, + struct_type_handles: crate::FastHashMap, crate::StorageAccess>, gl450_ext_inst_id: Word, layouter: Layouter, typifier: Typifier, @@ -248,7 +251,7 @@ impl Writer { fn get_type_id( &mut self, - arena: &crate::Arena, + arena: &Arena, lookup_ty: LookupType, ) -> Result { if let Entry::Occupied(e) = self.lookup_type.entry(lookup_ty) { @@ -284,7 +287,7 @@ impl Writer { fn get_global_variable_id( &mut self, ir_module: &crate::Module, - handle: crate::Handle, + handle: Handle, ) -> Result<(Word, spirv::StorageClass), Error> { Ok(match self.lookup_global_variable.entry(handle) { Entry::Occupied(e) => *e.get(), @@ -299,8 +302,8 @@ impl Writer { fn get_pointer_id( &mut self, - arena: &crate::Arena, - handle: crate::Handle, + arena: &Arena, + handle: Handle, class: crate::StorageClass, ) -> Result { let ty_id = self.get_type_id(arena, LookupType::Handle(handle))?; @@ -539,7 +542,7 @@ impl Writer { fn write_type_declaration_local( &mut self, - arena: &crate::Arena, + arena: &Arena, local_ty: LocalType, ) -> Result { let id = self.generate_id(); @@ -581,8 +584,8 @@ impl Writer { fn write_type_declaration_arena( &mut self, - arena: &crate::Arena, - handle: crate::Handle, + arena: &Arena, + handle: Handle, ) -> Result { let ty = &arena[handle]; let id = self.generate_id(); @@ -768,7 +771,7 @@ impl Writer { &mut self, id: Word, inner: &crate::ConstantInner, - types: &crate::Arena, + types: &Arena, ) -> Result<(), Error> { let instruction = match *inner { crate::ConstantInner::Scalar { width, ref value } => { @@ -847,7 +850,7 @@ impl Writer { fn write_global_variable( &mut self, ir_module: &crate::Module, - handle: crate::Handle, + handle: Handle, ) -> Result<(Instruction, Word, spirv::StorageClass), Error> { let global_variable = &ir_module.global_variables[handle]; let id = self.generate_id(); @@ -988,12 +991,93 @@ impl Writer { id } + fn write_texture_coordinates( + &mut self, + ir_module: &crate::Module, + ir_function: &crate::Function, + coordinates: Handle, + array_index: Option>, + block: &mut Block, + function: &mut Function, + ) -> Result { + let coordinate_id = + self.write_expression(ir_module, ir_function, coordinates, block, function)?; + + Ok(if let Some(array_index) = array_index { + let coordinate_scalar_type_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Scalar { + kind: crate::ScalarKind::Float, + width: 4, + }), + )?; + + let mut constituent_ids = [0u32; 4]; + let size = match *self.typifier.get(coordinates, &ir_module.types) { + crate::TypeInner::Scalar { .. } => { + constituent_ids[0] = coordinate_id; + crate::VectorSize::Bi + } + crate::TypeInner::Vector { size, .. } => { + for i in 0..size as u32 { + let id = self.generate_id(); + constituent_ids[i as usize] = id; + block.body.push(Instruction::composite_extract( + coordinate_scalar_type_id, + id, + coordinate_id, + &[i], + )); + } + match size { + crate::VectorSize::Bi => crate::VectorSize::Tri, + crate::VectorSize::Tri => crate::VectorSize::Quad, + crate::VectorSize::Quad => { + unimplemented!("Unable to extend the vec4 coordinate") + } + } + } + ref other => unimplemented!("wrong coordinate type {:?}", other), + }; + + let array_index_f32_id = self.generate_id(); + constituent_ids[size as usize - 1] = array_index_f32_id; + + let array_index_u32_id = + self.write_expression(ir_module, ir_function, array_index, block, function)?; + let cast_instruction = Instruction::unary( + spirv::Op::ConvertUToF, + coordinate_scalar_type_id, + array_index_f32_id, + array_index_u32_id, + ); + block.body.push(cast_instruction); + + let extended_coordinate_type_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Vector { + size, + kind: crate::ScalarKind::Float, + width: 4, + }), + )?; + + self.write_composite_construct( + extended_coordinate_type_id, + &constituent_ids[..size as usize], + block, + ) + } else { + coordinate_id + }) + } + /// Write an expression and return a value ID. fn write_expression<'a>( &mut self, ir_module: &'a crate::Module, ir_function: &crate::Function, - handle: crate::Handle, + handle: Handle, block: &mut Block, function: &mut Function, ) -> Result { @@ -1016,7 +1100,7 @@ impl Writer { &mut self, ir_module: &'a crate::Module, ir_function: &crate::Function, - handle: crate::Handle, + handle: Handle, block: &mut Block, function: &mut Function, ) -> Result { @@ -1036,7 +1120,7 @@ impl Writer { &mut self, ir_module: &'a crate::Module, ir_function: &crate::Function, - expr_handle: crate::Handle, + expr_handle: Handle, block: &mut Block, function: &mut Function, ) -> Result<(RawExpression, ExpressionId), Error> { @@ -1510,6 +1594,44 @@ impl Writer { RawExpression::Value(id) } + crate::Expression::ImageLoad { + image, + coordinate, + array_index, + index, + } => { + let image_id = + self.write_expression(ir_module, ir_function, image, block, function)?; + let coordinate_id = self.write_texture_coordinates( + ir_module, + ir_function, + coordinate, + array_index, + block, + function, + )?; + + let id = self.generate_id(); + let mut instruction = + Instruction::image_read(result_type_id, id, image_id, coordinate_id); + + if let Some(index) = index { + let index_id = + self.write_expression(ir_module, ir_function, index, block, function)?; + let image_ops = match *self.typifier.get(image, &ir_module.types) { + crate::TypeInner::Image { + class: crate::ImageClass::Sampled { multi: true, .. }, + .. + } => spirv::ImageOperands::SAMPLE, + _ => spirv::ImageOperands::LOD, + }; + instruction.add_operand(image_ops.bits()); + instruction.add_operand(index_id); + } + + block.body.push(instruction); + RawExpression::Value(id) + } crate::Expression::ImageSample { image, sampler, @@ -1531,84 +1653,16 @@ impl Writer { LookupType::Local(LocalType::SampledImage { image_type }), )?; - // sampler let sampler_id = self.write_expression(ir_module, ir_function, sampler, block, function)?; - - // coordinate - let mut coordinate_id = - self.write_expression(ir_module, ir_function, coordinate, block, function)?; - - if let Some(array_index) = array_index { - let coordinate_scalar_type_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Scalar { - kind: crate::ScalarKind::Float, - width: 4, - }), - )?; - - let mut constituent_ids = [0u32; 4]; - let size = match *self.typifier.get(coordinate, &ir_module.types) { - crate::TypeInner::Scalar { .. } => { - constituent_ids[0] = coordinate_id; - crate::VectorSize::Bi - } - crate::TypeInner::Vector { size, .. } => { - for i in 0..size as u32 { - let id = self.generate_id(); - constituent_ids[i as usize] = id; - block.body.push(Instruction::composite_extract( - coordinate_scalar_type_id, - id, - coordinate_id, - &[i], - )); - } - match size { - crate::VectorSize::Bi => crate::VectorSize::Tri, - crate::VectorSize::Tri => crate::VectorSize::Quad, - crate::VectorSize::Quad => { - unimplemented!("Unable to extend the vec4 coordinate") - } - } - } - ref other => unimplemented!("wrong coordinate type {:?}", other), - }; - - let array_index_f32_id = self.generate_id(); - constituent_ids[size as usize - 1] = array_index_f32_id; - - let array_index_u32_id = self.write_expression( - ir_module, - ir_function, - array_index, - block, - function, - )?; - let cast_instruction = Instruction::unary( - spirv::Op::ConvertUToF, - coordinate_scalar_type_id, - array_index_f32_id, - array_index_u32_id, - ); - block.body.push(cast_instruction); - - let extended_coordinate_type_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Vector { - size, - kind: crate::ScalarKind::Float, - width: 4, - }), - )?; - - coordinate_id = self.write_composite_construct( - extended_coordinate_type_id, - &constituent_ids[..size as usize], - block, - ); - } + let coordinate_id = self.write_texture_coordinates( + ir_module, + ir_function, + coordinate, + array_index, + block, + function, + )?; let sampled_image_id = self.generate_id(); block.body.push(Instruction::sampled_image( @@ -1995,6 +2049,29 @@ impl Writer { .body .push(Instruction::store(pointer_id, value_id, None)); } + crate::Statement::ImageStore { + image, + coordinate, + array_index, + value, + } => { + let image_id = + self.write_expression(ir_module, ir_function, image, &mut block, function)?; + let coordinate_id = self.write_texture_coordinates( + ir_module, + ir_function, + coordinate, + array_index, + &mut block, + function, + )?; + let value_id = + self.write_expression(ir_module, ir_function, value, &mut block, function)?; + + block + .body + .push(Instruction::image_write(image_id, coordinate_id, value_id)); + } crate::Statement::Call { function: local_function, ref arguments, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a57d031a5..3de5bebf4 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1582,7 +1582,12 @@ impl> Parser { self.patch_function_call_statements(body)?; self.patch_function_call_statements(continuing)?; } - S::Break | S::Continue | S::Return { .. } | S::Kill | S::Store { .. } => {} + S::Break + | S::Continue + | S::Return { .. } + | S::Kill + | S::Store { .. } + | S::ImageStore { .. } => {} S::Call { ref mut function, .. } => { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 551c9da6c..e4febf8a0 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1798,6 +1798,32 @@ impl Parser { "break" => Some(crate::Statement::Break), "continue" => Some(crate::Statement::Continue), "discard" => Some(crate::Statement::Kill), + "textureStore" => { + lexer.expect(Token::Paren('('))?; + let image_name = lexer.next_ident()?; + let image = context.lookup_ident.lookup(image_name)?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, context.as_expression())?; + let arrayed = match *context.as_expression().resolve_type(image)? { + crate::TypeInner::Image { arrayed, .. } => arrayed, + _ => return Err(Error::BadTexture(image_name)), + }; + let array_index = if arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, context.as_expression())?) + } else { + None + }; + lexer.expect(Token::Separator(','))?; + let value = self.parse_general_expression(lexer, context.as_expression())?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Statement::ImageStore { + image, + coordinate, + array_index, + value, + }) + } // assignment or a function call ident => { if let Some(&var_expr) = context.lookup_ident.get(ident) { diff --git a/src/lib.rs b/src/lib.rs index c87af3c53..38d2157cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -805,6 +805,13 @@ pub enum Statement { pointer: Handle, value: Handle, }, + /// Stores a value to an image. + ImageStore { + image: Handle, + coordinate: Handle, + array_index: Option>, + value: Handle, + }, /// Calls a function with no return value. Call { function: Handle, diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 8c03f0623..b35f9c680 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -335,6 +335,21 @@ impl FunctionInfo { ControlFlags::MAY_EXIT | flags } S::Store { pointer, value } => self.add_ref(pointer) | self.add_ref(value), + S::ImageStore { + image, + coordinate, + array_index, + value, + } => { + let array_flags = match array_index { + Some(expr) => self.add_ref(expr), + None => ControlFlags::empty(), + }; + array_flags + | self.add_ref(image) + | self.add_ref(coordinate) + | self.add_ref(value) + } S::Call { function, ref arguments, diff --git a/src/proc/interface.rs b/src/proc/interface.rs index ca6804388..051d42e1b 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -203,6 +203,19 @@ where self.visitor.visit_lhs_expr(left, &self.expressions[left]); self.traverse_expr(value); } + S::ImageStore { + image, + coordinate, + array_index, + value, + } => { + self.visitor.visit_lhs_expr(image, &self.expressions[image]); + self.traverse_expr(coordinate); + if let Some(expr) = array_index { + self.traverse_expr(expr); + } + self.traverse_expr(value); + } S::Call { function, ref arguments, diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index 181c81532..af5eaf54d 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -35,6 +35,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) { | Some(&mut crate::Statement::Kill) => (), Some(&mut crate::Statement::Loop { .. }) | Some(&mut crate::Statement::Store { .. }) + | Some(&mut crate::Statement::ImageStore { .. }) | Some(&mut crate::Statement::Call { .. }) | None => block.push(crate::Statement::Return { value: None }), } From 8e96085caf4f4c2ab812516f607fabb7e908db17 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Feb 2021 21:33:46 -0500 Subject: [PATCH 0488/2212] [spv-in] support image load/store ops --- src/back/spv/writer.rs | 9 ++----- src/front/spv/error.rs | 2 +- src/front/spv/image.rs | 60 +++++++++++++++++++++++++++++++++++++++--- src/front/spv/mod.rs | 10 +++++-- 4 files changed, 67 insertions(+), 14 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f5d7fa1e6..f9b05376f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1801,13 +1801,8 @@ impl Writer { let reject_id = self.write_expression(ir_module, ir_function, reject, block, function)?; - let instruction = Instruction::select( - result_type_id, - id, - condition_id, - accept_id, - reject_id, - ); + let instruction = + Instruction::select(result_type_id, id, condition_id, accept_id, reject_id); block.body.push(instruction); RawExpression::Value(id) } diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 194c279b8..c7bac4b17 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -40,7 +40,7 @@ pub enum Error { InvalidBinding(spirv::Word), InvalidGlobalVar(crate::Expression), InvalidImageBaseType(Handle), - InvalidSampleImage(Handle), + InvalidImage(Handle), InvalidDepthReference(Handle), InvalidAsType(Handle), InvalidVectorType(Handle), diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 3453e7048..6a01e7df3 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -182,7 +182,59 @@ impl> super::Parser { Ok(()) } - pub(super) fn parse_image_fetch( + pub(super) fn parse_image_write( + &mut self, + words_left: u16, + type_arena: &Arena, + global_arena: &Arena, + expressions: &mut Arena, + ) -> Result { + let image_id = self.next()?; + let coordinate_id = self.next()?; + let value_id = self.next()?; + + if words_left != 0 { + let image_ops = self.next()?; + let other = spirv::ImageOperands::from_bits_truncate(image_ops); + log::warn!("Skipping {:?}", other); + for _ in 1..words_left { + self.next()?; + } + } + + let image_lexp = self.lookup_expression.lookup(image_id)?; + let image_var_handle = expressions[image_lexp.handle].as_global_var()?; + let image_var = &global_arena[image_var_handle]; + + let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + let (coordinate, array_index) = match type_arena[image_var.ty].inner { + crate::TypeInner::Image { + dim, + arrayed, + class: _, + } => extract_image_coordinates( + dim, + arrayed, + coord_lexp.handle, + coord_type_handle, + type_arena, + expressions, + ), + _ => return Err(Error::InvalidImage(image_var.ty)), + }; + + let value_lexp = self.lookup_expression.lookup(value_id)?; + + Ok(crate::Statement::ImageStore { + image: image_lexp.handle, + coordinate, + array_index, + value: value_lexp.handle, + }) + } + + pub(super) fn parse_image_load( &mut self, mut words_left: u16, type_arena: &Arena, @@ -240,7 +292,7 @@ impl> super::Parser { type_arena, expressions, ), - _ => return Err(Error::InvalidSampleImage(image_var.ty)), + _ => return Err(Error::InvalidImage(image_var.ty)), }; let expr = crate::Expression::ImageLoad { @@ -328,7 +380,7 @@ impl> super::Parser { type_arena, expressions, ), - _ => return Err(Error::InvalidSampleImage(image_var.ty)), + _ => return Err(Error::InvalidImage(image_var.ty)), }; let expr = crate::Expression::ImageSample { @@ -429,7 +481,7 @@ impl> super::Parser { type_arena, expressions, ), - _ => return Err(Error::InvalidSampleImage(image_var.ty)), + _ => return Err(Error::InvalidImage(image_var.ty)), }; let expr = crate::Expression::ImageSample { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3de5bebf4..2bcad1625 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1100,9 +1100,15 @@ impl> Parser { inst.expect(5)?; self.parse_image_couple()?; } - Op::ImageFetch => { + Op::ImageWrite => { + let extra = inst.expect_at_least(4)?; + let stmt = + self.parse_image_write(extra, type_arena, global_arena, expressions)?; + block.push(stmt); + } + Op::ImageFetch | Op::ImageRead => { let extra = inst.expect_at_least(5)?; - self.parse_image_fetch(extra, type_arena, global_arena, expressions)?; + self.parse_image_load(extra, type_arena, global_arena, expressions)?; } Op::ImageSampleImplicitLod | Op::ImageSampleExplicitLod From 18853ab149fa7c757f82a17c16a5a813db537808 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Feb 2021 21:54:43 -0500 Subject: [PATCH 0489/2212] Add warnings for trivial casts and clean them up in the code --- src/back/glsl/mod.rs | 10 +++++----- src/back/spv/layout.rs | 2 +- src/back/spv/layout_tests.rs | 2 +- src/back/spv/mod.rs | 2 +- src/back/spv/test_framework.rs | 2 +- src/back/spv/writer.rs | 4 ++-- src/front/glsl/ast.rs | 2 +- src/lib.rs | 6 ++++++ 8 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 14959bbb3..d843dc920 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -211,7 +211,7 @@ impl IdGenerator { } /// Shorthand result used internally by the backend -type BackendResult = std::result::Result<(), Error>; +type BackendResult = Result<(), Error>; /// A glsl compilation error. #[derive(Debug, Error)] @@ -1716,8 +1716,8 @@ impl<'a, W: Write> Writer<'a, W> { fn write_texture_coordinates( &mut self, - coordinate: Handle, - array_index: Option>, + coordinate: Handle, + array_index: Option>, dim: crate::ImageDimension, ctx: &FunctionCtx, ) -> Result<(), Error> { @@ -1793,7 +1793,7 @@ struct ScalarString<'a> { /// /// # Errors /// If a [`Float`](crate::ScalarKind::Float) with an width that isn't 4 or 8 -fn glsl_scalar(kind: ScalarKind, width: crate::Bytes) -> Result, Error> { +fn glsl_scalar(kind: ScalarKind, width: Bytes) -> Result, Error> { Ok(match kind { ScalarKind::Sint => ScalarString { prefix: "i", @@ -1940,7 +1940,7 @@ struct TextureMappingVisitor<'a> { } impl<'a> Visitor for TextureMappingVisitor<'a> { - fn visit_expr(&mut self, _: Handle, expr: &crate::Expression) { + fn visit_expr(&mut self, _: Handle, expr: &Expression) { // We only care about `ImageSample` and `ImageLoad` // // Both `image` and `sampler` are `Expression::GlobalVariable` otherwise the module is diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index bba369741..bbd4ea764 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -83,7 +83,7 @@ impl Instruction { } pub(super) fn to_words(&self, sink: &mut impl Extend) { - sink.extend(Some((self.wc << 16 | self.op as u32) as u32)); + sink.extend(Some(self.wc << 16 | self.op as u32)); sink.extend(self.type_id); sink.extend(self.result_id); sink.extend(self.operands.iter().cloned()); diff --git a/src/back/spv/layout_tests.rs b/src/back/spv/layout_tests.rs index c09c91495..b5f1018b7 100644 --- a/src/back/spv/layout_tests.rs +++ b/src/back/spv/layout_tests.rs @@ -18,7 +18,7 @@ fn test_physical_layout_in_words() { layout.in_words(&mut output); - assert_eq!(output[0], spirv::MAGIC_NUMBER); + assert_eq!(output[0], MAGIC_NUMBER); assert_eq!( output[1], to_word(&[header.version.0, header.version.1, header.version.2, 1]) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index bbad11f85..5e9f1de62 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -55,7 +55,7 @@ struct Instruction { pub fn write_vec( module: &crate::Module, flags: WriterFlags, - capabilities: crate::FastHashSet, + capabilities: crate::FastHashSet, ) -> Result, Error> { let mut words = Vec::new(); let mut w = Writer::new(&module.header, flags, capabilities); diff --git a/src/back/spv/test_framework.rs b/src/back/spv/test_framework.rs index be2fa74fe..2b801ecf3 100644 --- a/src/back/spv/test_framework.rs +++ b/src/back/spv/test_framework.rs @@ -21,7 +21,7 @@ pub(super) fn validate_instruction( let mut op_index = 0; for i in inst_index..wc as usize { - assert_eq!(words[i as usize], instruction.operands[op_index]); + assert_eq!(words[i], instruction.operands[op_index]); op_index += 1; } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f9b05376f..d2a0270d1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -336,7 +336,7 @@ impl Writer { ) } - fn create_pointer_type(&mut self, type_id: spirv::Word, class: spirv::StorageClass) -> Word { + fn create_pointer_type(&mut self, type_id: Word, class: spirv::StorageClass) -> Word { let id = self.generate_id(); let instruction = Instruction::type_pointer(id, class, type_id); instruction.to_words(&mut self.logical_layout.declarations); @@ -1398,7 +1398,7 @@ impl Writer { use crate::MathFunction as Mf; enum MathOp { Ext(spirv::GLOp), - Custom(super::Instruction), + Custom(Instruction), } let arg0_id = diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 8b9144430..a19cab903 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -109,7 +109,7 @@ impl Program { pub fn resolve_type( &mut self, - handle: Handle, + handle: Handle, ) -> Result<&crate::TypeInner, ErrorKind> { let resolve_ctx = ResolveContext { constants: &self.module.constants, diff --git a/src/lib.rs b/src/lib.rs index 38d2157cc..e4adc32fa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,12 @@ //! //! To improve performance and reduce memory usage, most structures are stored //! in an [`Arena`], and can be retrieved using the corresponding [`Handle`]. +#![warn( + trivial_casts, + trivial_numeric_casts, + unused_extern_crates, + unused_qualifications +)] #![allow( clippy::new_without_default, clippy::unneeded_field_pattern, From dcd269782a16e55c284bbd8679c4cb9624656465 Mon Sep 17 00:00:00 2001 From: Systemcluster Date: Sun, 14 Feb 2021 00:29:08 +0100 Subject: [PATCH 0490/2212] [wgsl] restrict type casts to matching container types --- src/front/wgsl/mod.rs | 20 +++++++++++++++----- tests/out/shadow.msl.snap | 10 ++++------ tests/out/skybox.msl.snap | 4 ++-- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e4febf8a0..8275f38ea 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -844,7 +844,6 @@ impl Parser { ctx.constants, )?; let kind = inner.scalar_kind(); - let ty = ctx.types.fetch_or_append(crate::Type { name: None, inner }); lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); @@ -856,13 +855,24 @@ impl Parser { } lexer.expect(Token::Paren(')'))?; if components.is_empty() { - crate::Expression::As { - expr: last_component, - kind: kind.ok_or(Error::BadTypeCast(word))?, - convert: true, + let last_component_inner = ctx.resolve_type(last_component)?; + match (&inner, last_component_inner) { + (crate::TypeInner::Scalar { .. }, crate::TypeInner::Scalar { .. }) + | (crate::TypeInner::Matrix { .. }, crate::TypeInner::Matrix { .. }) + | (crate::TypeInner::Vector { .. }, crate::TypeInner::Vector { .. }) => { + crate::Expression::As { + expr: last_component, + kind: kind.ok_or(Error::BadTypeCast(word))?, + convert: true, + } + } + _ => { + return Err(Error::BadTypeCast(word)); + } } } else { components.push(last_component); + let ty = ctx.types.fetch_or_append(crate::Type { name: None, inner }); crate::Expression::Compose { ty, components } } } diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index ccb2a01ba..400381564 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -37,11 +37,9 @@ typedef float type7; typedef metal::float2 type8; -typedef int type9; +typedef metal::float3 type9; -typedef metal::float3 type10; - -typedef bool type11; +typedef bool type10; type7 fetch_shadow( type6 light_id, @@ -57,7 +55,7 @@ type7 fetch_shadow( } struct fs_mainInput { - type10 in_normal_fs [[user(loc0)]]; + type9 in_normal_fs [[user(loc0)]]; type2 in_position_fs [[user(loc1)]]; }; @@ -73,7 +71,7 @@ fragment fs_mainOutput fs_main( type5 sampler_shadow [[sampler(0)]] ) { fs_mainOutput output; - type10 color1 = type10(0.05, 0.05, 0.05); + type9 color1 = type9(0.05, 0.05, 0.05); type6 i = 0u; bool loop_init = true; while(true) { diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index c05cba30c..bb036f6ac 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -20,9 +20,9 @@ struct Data { typedef int type4; -typedef float type5; +typedef metal::float3x3 type5; -typedef metal::float3x3 type6; +typedef float type6; typedef metal::texturecube type7; From b642c5b89b3328ecdec0885cf7d5cfd3ba4dbd69 Mon Sep 17 00:00:00 2001 From: Systemcluster Date: Sun, 14 Feb 2021 10:47:30 +0100 Subject: [PATCH 0491/2212] [spv-in] support string instruction --- src/front/spv/mod.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 2bcad1625..5b13267d8 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1654,6 +1654,7 @@ impl> Parser { Op::MemoryModel => self.parse_memory_model(inst), Op::EntryPoint => self.parse_entry_point(inst), Op::ExecutionMode => self.parse_execution_mode(inst), + Op::String => self.parse_string(inst), Op::Source => self.parse_source(inst), Op::SourceExtension => self.parse_source_extension(inst), Op::Name => self.parse_name(inst), @@ -1840,6 +1841,13 @@ impl> Parser { Ok(()) } + fn parse_string(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Source, inst.op)?; + inst.expect_at_least(3)?; + let (_name, _) = self.next_string(inst.wc - 1)?; + Ok(()) + } + fn parse_source(&mut self, inst: Instruction) -> Result<(), Error> { self.switch(ModuleState::Source, inst.op)?; for _ in 1..inst.wc { From 7a124550d4f75a7089d1fe9d415a87e042fd88a8 Mon Sep 17 00:00:00 2001 From: Systemcluster Date: Sun, 14 Feb 2021 13:27:02 +0100 Subject: [PATCH 0492/2212] [glsl-in] support inverse function --- src/back/glsl/mod.rs | 1 + src/back/msl/writer.rs | 1 + src/back/spv/writer.rs | 1 + src/front/glsl/ast.rs | 4 +++- src/front/glsl/functions.rs | 8 +++++++- src/lib.rs | 1 + src/proc/mod.rs | 1 + src/proc/typifier.rs | 17 +++++++++++++++++ 8 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index d843dc920..9bccb8681 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1624,6 +1624,7 @@ impl<'a, W: Write> Writer<'a, W> { Mf::SmoothStep => "smoothstep", Mf::Sqrt => "sqrt", Mf::InverseSqrt => "inversesqrt", + Mf::Inverse => "inverse", Mf::Transpose => "transpose", Mf::Determinant => "determinant", // bits diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index d51a9e5d0..970e9210f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -646,6 +646,7 @@ impl Writer { Mf::SmoothStep => "smoothstep", Mf::Sqrt => "sqrt", Mf::InverseSqrt => "rsqrt", + Mf::Inverse => return Err(Error::UnsupportedCall(format!("{:?}", fun))), Mf::Transpose => "transpose", Mf::Determinant => "determinant", // bits diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d2a0270d1..affca9176 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1505,6 +1505,7 @@ impl Writer { Mf::SmoothStep => MathOp::Ext(spirv::GLOp::SmoothStep), Mf::Sqrt => MathOp::Ext(spirv::GLOp::Sqrt), Mf::InverseSqrt => MathOp::Ext(spirv::GLOp::InverseSqrt), + Mf::Inverse => MathOp::Ext(spirv::GLOp::MatrixInverse), Mf::Transpose => MathOp::Custom(Instruction::unary( spirv::Op::Transpose, result_type_id, diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index a19cab903..d00eb9736 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -125,7 +125,9 @@ impl Program { &resolve_ctx, ) { //TODO: better error report - Err(_) => Err(ErrorKind::SemanticError("Can't resolve type".into())), + Err(error) => Err(ErrorKind::SemanticError( + format!("Can't resolve type: {:?}", error).into(), + )), Ok(()) => Ok(self.context.typifier.get(handle, &self.module.types)), } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 0e8e6a458..78c0614c3 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -83,7 +83,8 @@ impl Program { } } "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" - | "exp" | "sign" => { + | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" + | "normalize" => { if fc.args.len() != 1 { return Err(ErrorKind::WrongNumberArgs(name, 1, fc.args.len())); } @@ -98,8 +99,13 @@ impl Program { "sin" => MathFunction::Sin, "abs" => MathFunction::Abs, "sqrt" => MathFunction::Sqrt, + "inversesqrt" => MathFunction::InverseSqrt, "exp" => MathFunction::Exp, + "exp2" => MathFunction::Exp2, "sign" => MathFunction::Sign, + "transpose" => MathFunction::Transpose, + "inverse" => MathFunction::Inverse, + "normalize" => MathFunction::Normalize, _ => unreachable!(), }, arg: fc.args[0].expression, diff --git a/src/lib.rs b/src/lib.rs index e4adc32fa..4d0a113b5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -605,6 +605,7 @@ pub enum MathFunction { SmoothStep, Sqrt, InverseSqrt, + Inverse, Transpose, Determinant, // bits diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 6755fdfc6..4e111aa93 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -133,6 +133,7 @@ impl super::MathFunction { Self::SmoothStep => 3, Self::Sqrt => 1, Self::InverseSqrt => 1, + Self::Inverse => 1, Self::Transpose => 1, Self::Determinant => 1, // bits diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index f5d766639..c97309e49 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -427,6 +427,23 @@ impl Typifier { }) } }, + Mf::Inverse => match *self.get(arg, types) { + crate::TypeInner::Matrix { + columns, + rows, + width, + } if columns == rows => Resolution::Value(crate::TypeInner::Matrix { + columns, + rows, + width, + }), + ref other => { + return Err(ResolveError::IncompatibleOperand { + op: "inverse".to_string(), + operand: format!("{:?}", other), + }) + } + }, Mf::Determinant => match *self.get(arg, types) { crate::TypeInner::Matrix { width, From 61d711b58f54ad47861c62e964d5181b6cd83066 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 14 Feb 2021 00:37:54 -0500 Subject: [PATCH 0493/2212] Remove the Header from IR --- examples/convert.rs | 24 ++-- src/back/msl/mod.rs | 12 +- src/back/spv/layout.rs | 109 ++++++++++++++++-- src/back/spv/layout_tests.rs | 167 ---------------------------- src/back/spv/mod.rs | 35 +++--- src/back/spv/test_framework.rs | 27 ----- src/back/spv/writer.rs | 70 +++++------- src/front/glsl/ast.rs | 2 +- src/front/mod.rs | 24 ---- src/front/spv/mod.rs | 17 ++- src/front/wgsl/mod.rs | 2 +- src/lib.rs | 21 +--- tests/in/boids.param.ron | 1 + tests/in/collatz.param.ron | 1 + tests/in/empty.param.ron | 1 + tests/in/quad.param.ron | 1 + tests/in/shadow.param.ron | 1 + tests/in/skybox.param.ron | 1 + tests/in/texture-array.param.ron | 1 + tests/out/empty.spvasm.snap | 2 +- tests/out/shadow.ron.snap | 4 - tests/out/shadow.spvasm.snap | 2 +- tests/out/texture-array.spvasm.snap | 2 +- tests/snapshots.rs | 15 ++- 24 files changed, 213 insertions(+), 329 deletions(-) delete mode 100644 src/back/spv/layout_tests.rs delete mode 100644 src/back/spv/test_framework.rs diff --git a/examples/convert.rs b/examples/convert.rs index 4cb419fd5..ee93dc13a 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -36,6 +36,8 @@ struct Parameters { #[cfg_attr(not(feature = "spv-in"), allow(dead_code))] spv_flow_dump_prefix: String, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + spv_version: (u8, u8), + #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_capabilities: naga::FastHashSet, #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] mtl_bindings: naga::FastHashMap, @@ -142,7 +144,7 @@ fn main() { // prevent "unreachable_code" warnings panic!("Unknown input extension: {}", other); } - naga::Module::generate_empty() + naga::Module::default() } }; @@ -198,15 +200,19 @@ fn main() { "spv" => { use naga::back::spv; - let debug_flag = args.get(3).map_or(spv::WriterFlags::DEBUG, |arg| { - if arg.parse().unwrap() { - spv::WriterFlags::DEBUG - } else { - spv::WriterFlags::NONE - } - }); + let options = spv::Options { + lang_version: params.spv_version, + flags: args.get(3).map_or(spv::WriterFlags::DEBUG, |arg| { + if arg.parse().unwrap() { + spv::WriterFlags::DEBUG + } else { + spv::WriterFlags::empty() + } + }), + capabilities: params.spv_capabilities, + }; - let spv = spv::write_vec(&module, debug_flag, params.spv_capabilities).unwrap_pretty(); + let spv = spv::write_vec(&module, &options).unwrap_pretty(); let bytes = spv .iter() diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 14dbaaed8..0953a5dad 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -101,7 +101,7 @@ enum LocationMode { Uniform, } -#[derive(Debug, Default, Clone)] +#[derive(Debug, Clone)] pub struct Options { /// (Major, Minor) target version of the Metal Shading Language. pub lang_version: (u8, u8), @@ -111,6 +111,16 @@ pub struct Options { pub binding_map: BindingMap, } +impl Default for Options { + fn default() -> Self { + Options { + lang_version: (1, 0), + spirv_cross_compatibility: false, + binding_map: BindingMap::default(), + } + } +} + impl Options { fn resolve_binding( &self, diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index bbd4ea764..1c3938cd8 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -1,17 +1,16 @@ use super::{Instruction, LogicalLayout, PhysicalLayout}; -use spirv::*; +use spirv::{Op, Word, MAGIC_NUMBER}; use std::iter; -impl PhysicalLayout { - pub(super) fn new(header: &crate::Header) -> Self { - let version: Word = ((header.version.0 as u32) << 16) - | ((header.version.1 as u32) << 8) - | header.version.2 as u32; +// https://github.com/KhronosGroup/SPIRV-Headers/pull/195 +const GENERATOR: Word = 28; +impl PhysicalLayout { + pub(super) fn new(version: Word) -> Self { PhysicalLayout { magic_number: MAGIC_NUMBER, version, - generator: header.generator, + generator: GENERATOR, bound: 0, instruction_schema: 0x0u32, } @@ -89,3 +88,99 @@ impl Instruction { sink.extend(self.operands.iter().cloned()); } } + +impl Instruction { + #[cfg(test)] + fn validate(&self, words: &[Word]) { + let mut inst_index = 0; + let (wc, op) = ((words[inst_index] >> 16) as u16, words[inst_index] as u16); + inst_index += 1; + + assert_eq!(wc, words.len() as u16); + assert_eq!(op, self.op as u16); + + if self.type_id.is_some() { + assert_eq!(words[inst_index], self.type_id.unwrap()); + inst_index += 1; + } + + if self.result_id.is_some() { + assert_eq!(words[inst_index], self.result_id.unwrap()); + inst_index += 1; + } + + let mut op_index = 0; + for i in inst_index..wc as usize { + assert_eq!(words[i], self.operands[op_index]); + op_index += 1; + } + } +} + +#[test] +fn test_physical_layout_in_words() { + let bound = 5; + let version = 0x10203; + + let mut output = vec![]; + let mut layout = PhysicalLayout::new(version); + layout.bound = bound; + + layout.in_words(&mut output); + + assert_eq!(&output, &[MAGIC_NUMBER, version, GENERATOR, bound, 0,]); +} + +#[test] +fn test_logical_layout_in_words() { + let mut output = vec![]; + let mut layout = LogicalLayout::default(); + let layout_vectors = 11; + let mut instructions = Vec::with_capacity(layout_vectors); + + let vector_names = &[ + "Capabilities", + "Extensions", + "External Instruction Imports", + "Memory Model", + "Entry Points", + "Execution Modes", + "Debugs", + "Annotations", + "Declarations", + "Function Declarations", + "Function Definitions", + ]; + + for i in 0..layout_vectors { + let mut dummy_instruction = Instruction::new(Op::Constant); + dummy_instruction.set_type((i + 1) as u32); + dummy_instruction.set_result((i + 2) as u32); + dummy_instruction.add_operand((i + 3) as u32); + dummy_instruction.add_operands(super::helpers::string_to_words( + format!("This is the vector: {}", vector_names[i]).as_str(), + )); + instructions.push(dummy_instruction); + } + + instructions[0].to_words(&mut layout.capabilities); + instructions[1].to_words(&mut layout.extensions); + instructions[2].to_words(&mut layout.ext_inst_imports); + instructions[3].to_words(&mut layout.memory_model); + instructions[4].to_words(&mut layout.entry_points); + instructions[5].to_words(&mut layout.execution_modes); + instructions[6].to_words(&mut layout.debugs); + instructions[7].to_words(&mut layout.annotations); + instructions[8].to_words(&mut layout.declarations); + instructions[9].to_words(&mut layout.function_declarations); + instructions[10].to_words(&mut layout.function_definitions); + + layout.in_words(&mut output); + + let mut index: usize = 0; + for instruction in instructions { + let wc = instruction.wc as usize; + instruction.validate(&output[index..index + wc]); + index += wc; + } +} diff --git a/src/back/spv/layout_tests.rs b/src/back/spv/layout_tests.rs deleted file mode 100644 index b5f1018b7..000000000 --- a/src/back/spv/layout_tests.rs +++ /dev/null @@ -1,167 +0,0 @@ -use crate::{ - back::spv::{helpers, test_framework::*, Instruction, LogicalLayout, PhysicalLayout}, - Header, -}; -use spirv::*; - -#[test] -fn test_physical_layout_in_words() { - let header = Header { - generator: 0, - version: (1, 2, 3), - }; - let bound = 5; - - let mut output = vec![]; - let mut layout = PhysicalLayout::new(&header); - layout.bound = bound; - - layout.in_words(&mut output); - - assert_eq!(output[0], MAGIC_NUMBER); - assert_eq!( - output[1], - to_word(&[header.version.0, header.version.1, header.version.2, 1]) - ); - assert_eq!(output[2], 0); - assert_eq!(output[3], bound); - assert_eq!(output[4], 0); -} - -#[test] -fn test_logical_layout_in_words() { - let mut output = vec![]; - let mut layout = LogicalLayout::default(); - let layout_vectors = 11; - let mut instructions = Vec::with_capacity(layout_vectors); - - let vector_names = &[ - "Capabilities", - "Extensions", - "External Instruction Imports", - "Memory Model", - "Entry Points", - "Execution Modes", - "Debugs", - "Annotations", - "Declarations", - "Function Declarations", - "Function Definitions", - ]; - - for i in 0..layout_vectors { - let mut dummy_instruction = Instruction::new(Op::Constant); - dummy_instruction.set_type((i + 1) as u32); - dummy_instruction.set_result((i + 2) as u32); - dummy_instruction.add_operand((i + 3) as u32); - dummy_instruction.add_operands(helpers::string_to_words( - format!("This is the vector: {}", vector_names[i]).as_str(), - )); - instructions.push(dummy_instruction); - } - - instructions[0].to_words(&mut layout.capabilities); - instructions[1].to_words(&mut layout.extensions); - instructions[2].to_words(&mut layout.ext_inst_imports); - instructions[3].to_words(&mut layout.memory_model); - instructions[4].to_words(&mut layout.entry_points); - instructions[5].to_words(&mut layout.execution_modes); - instructions[6].to_words(&mut layout.debugs); - instructions[7].to_words(&mut layout.annotations); - instructions[8].to_words(&mut layout.declarations); - instructions[9].to_words(&mut layout.function_declarations); - instructions[10].to_words(&mut layout.function_definitions); - - layout.in_words(&mut output); - - let mut index: usize = 0; - for instruction in instructions { - let wc = instruction.wc as usize; - let instruction_output = &output[index..index + wc]; - validate_instruction(instruction_output, &instruction); - index += wc; - } -} - -#[test] -fn test_instruction_set_type() { - let ty = 1; - let mut instruction = Instruction::new(Op::Constant); - assert_eq!(instruction.wc, 1); - - instruction.set_type(ty); - assert_eq!(instruction.type_id.unwrap(), ty); - assert_eq!(instruction.wc, 2); -} - -#[test] -#[should_panic] -fn test_instruction_set_type_twice() { - let ty = 1; - let mut instruction = Instruction::new(Op::Constant); - instruction.set_type(ty); - instruction.set_type(ty); -} - -#[test] -fn test_instruction_set_result() { - let result = 1; - let mut instruction = Instruction::new(Op::Constant); - assert_eq!(instruction.wc, 1); - - instruction.set_result(result); - assert_eq!(instruction.result_id.unwrap(), result); - assert_eq!(instruction.wc, 2); -} - -#[test] -#[should_panic] -fn test_instruction_set_result_twice() { - let result = 1; - let mut instruction = Instruction::new(Op::Constant); - instruction.set_result(result); - instruction.set_result(result); -} - -#[test] -fn test_instruction_add_operand() { - let operand = 1; - let mut instruction = Instruction::new(Op::Constant); - assert_eq!(instruction.operands.len(), 0); - assert_eq!(instruction.wc, 1); - - instruction.add_operand(operand); - assert_eq!(instruction.operands.len(), 1); - assert_eq!(instruction.wc, 2); -} - -#[test] -fn test_instruction_add_operands() { - let operands = vec![1, 2, 3]; - let mut instruction = Instruction::new(Op::Constant); - assert_eq!(instruction.operands.len(), 0); - assert_eq!(instruction.wc, 1); - - instruction.add_operands(operands); - assert_eq!(instruction.operands.len(), 3); - assert_eq!(instruction.wc, 4); -} - -#[test] -fn test_instruction_to_words() { - let ty = 1; - let result = 2; - let operand = 3; - let mut instruction = Instruction::new(Op::Constant); - instruction.set_type(ty); - instruction.set_result(result); - instruction.add_operand(operand); - - let mut output = vec![]; - instruction.to_words(&mut output); - validate_instruction(output.as_slice(), &instruction); -} - -fn to_word(bytes: &[u8]) -> Word { - ((bytes[0] as u32) << 16) | ((bytes[1] as u32) << 8) | bytes[2] as u32 -} diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 5e9f1de62..c717d23f1 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -3,12 +3,6 @@ mod instructions; mod layout; mod writer; -#[cfg(test)] -mod test_framework; - -#[cfg(test)] -mod layout_tests; - pub use spirv::Capability; pub use writer::{Error, Writer}; @@ -16,7 +10,6 @@ use spirv::Word; bitflags::bitflags! { pub struct WriterFlags: u32 { - const NONE = 0x0; const DEBUG = 0x1; } } @@ -52,13 +45,29 @@ struct Instruction { operands: Vec, } -pub fn write_vec( - module: &crate::Module, - flags: WriterFlags, - capabilities: crate::FastHashSet, -) -> Result, Error> { +#[derive(Debug, Clone)] +pub struct Options { + /// (Major, Minor) target version of the SPIR-V. + pub lang_version: (u8, u8), + /// Configuration flags for the writer. + pub flags: WriterFlags, + /// Set of SPIR-V capabilities. + pub capabilities: crate::FastHashSet, +} + +impl Default for Options { + fn default() -> Self { + Options { + lang_version: (1, 0), + flags: WriterFlags::empty(), + capabilities: Default::default(), + } + } +} + +pub fn write_vec(module: &crate::Module, options: &Options) -> Result, Error> { let mut words = Vec::new(); - let mut w = Writer::new(&module.header, flags, capabilities); + let mut w = Writer::new(options)?; w.write(module, &mut words)?; Ok(words) } diff --git a/src/back/spv/test_framework.rs b/src/back/spv/test_framework.rs deleted file mode 100644 index 2b801ecf3..000000000 --- a/src/back/spv/test_framework.rs +++ /dev/null @@ -1,27 +0,0 @@ -pub(super) fn validate_instruction( - words: &[spirv::Word], - instruction: &crate::back::spv::Instruction, -) { - let mut inst_index = 0; - let (wc, op) = ((words[inst_index] >> 16) as u16, words[inst_index] as u16); - inst_index += 1; - - assert_eq!(wc, words.len() as u16); - assert_eq!(op, instruction.op as u16); - - if instruction.type_id.is_some() { - assert_eq!(words[inst_index], instruction.type_id.unwrap()); - inst_index += 1; - } - - if instruction.result_id.is_some() { - assert_eq!(words[inst_index], instruction.result_id.unwrap()); - inst_index += 1; - } - - let mut op_index = 0; - for i in inst_index..wc as usize { - assert_eq!(words[i], instruction.operands[op_index]); - op_index += 1; - } -} diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index affca9176..6a639be92 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,5 +1,5 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ -use super::{Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; +use super::{Instruction, LogicalLayout, Options, PhysicalLayout, WriterFlags}; use crate::{ arena::{Arena, Handle}, proc::{Layouter, ResolveContext, ResolveError, Typifier}, @@ -12,6 +12,8 @@ const BITS_PER_BYTE: crate::Bytes = 8; #[derive(Clone, Debug, Error)] pub enum Error { + #[error("target SPIRV-{0}.{1} is not supported")] + UnsupportedVersion(u8, u8), #[error("one of the required capabilities {0:?} is missing")] MissingCapabilities(Vec), #[error("unimplemented {0:}")] @@ -204,21 +206,22 @@ type ExpressionId = Word; type PointerExpressionId = (Word, spirv::StorageClass); impl Writer { - pub fn new( - header: &crate::Header, - flags: WriterFlags, - capabilities: crate::FastHashSet, - ) -> Self { + pub fn new(options: &Options) -> Result { + let (major, minor) = options.lang_version; + if major != 1 { + return Err(Error::UnsupportedVersion(major, minor)); + } + let raw_version = ((major as u32) << 16) | ((minor as u32) << 8); let gl450_ext_inst_id = 1; let void_type = 2; - Writer { - physical_layout: PhysicalLayout::new(header), + Ok(Writer { + physical_layout: PhysicalLayout::new(raw_version), logical_layout: LogicalLayout::default(), id_count: 2, // see `gl450_ext_inst_id` and `void_type` - capabilities, + capabilities: options.capabilities.clone(), debugs: vec![], annotations: vec![], - flags, + flags: options.flags, void_type, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), @@ -229,7 +232,7 @@ impl Writer { gl450_ext_inst_id, layouter: Layouter::default(), typifier: Typifier::new(), - } + }) } fn generate_id(&mut self) -> Word { @@ -2187,35 +2190,18 @@ impl Writer { } } -#[cfg(test)] -mod tests { - use crate::{ - back::spv::{Writer, WriterFlags}, - Header, - }; - - #[test] - fn test_writer_generate_id() { - let mut writer = create_writer(); - - assert_eq!(writer.id_count, 2); - writer.generate_id(); - assert_eq!(writer.id_count, 3); - } - - #[test] - fn test_write_physical_layout() { - let mut writer = create_writer(); - assert_eq!(writer.physical_layout.bound, 0); - writer.write_physical_layout(); - assert_eq!(writer.physical_layout.bound, 3); - } - - fn create_writer() -> Writer { - let header = Header { - generator: 0, - version: (1, 0, 0), - }; - Writer::new(&header, WriterFlags::NONE, Default::default()) - } +#[test] +fn test_writer_generate_id() { + let mut writer = Writer::new(&Options::default()).unwrap(); + assert_eq!(writer.id_count, 2); + writer.generate_id(); + assert_eq!(writer.id_count, 3); +} + +#[test] +fn test_write_physical_layout() { + let mut writer = Writer::new(&Options::default()).unwrap(); + assert_eq!(writer.physical_layout.bound, 0); + writer.write_physical_layout(); + assert_eq!(writer.physical_layout.bound, 3); } diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index d00eb9736..bcad2b05d 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -40,7 +40,7 @@ impl Program { lookup_constant_exps: FastHashMap::default(), typifier: Typifier::new(), }, - module: Module::generate_empty(), + module: Module::default(), } } diff --git a/src/front/mod.rs b/src/front/mod.rs index 13ad35841..c7f696418 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -8,27 +8,3 @@ pub mod glsl; pub mod spv; #[cfg(feature = "wgsl-in")] pub mod wgsl; - -use crate::arena::Arena; - -pub const GENERATOR: u32 = 0; - -impl crate::Module { - pub fn from_header(header: crate::Header) -> Self { - crate::Module { - header, - types: Arena::new(), - constants: Arena::new(), - global_variables: Arena::new(), - functions: Arena::new(), - entry_points: crate::FastHashMap::default(), - } - } - - pub fn generate_empty() -> Self { - Self::from_header(crate::Header { - version: (1, 0, 0), - generator: GENERATOR, - }) - } -} diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 5b13267d8..3a8d77788 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -194,6 +194,7 @@ struct Decoration { location: Option, desc_set: Option, desc_index: Option, + specialization: Option, block: Option, offset: Option, array_stride: Option, @@ -457,6 +458,9 @@ impl> Parser { spirv::Decoration::RowMajor => { dec.matrix_major = Some(Majority::Row); } + spirv::Decoration::SpecId => { + dec.specialization = Some(self.next()?); + } other => { log::warn!("Unknown decoration {:?}", other); for _ in base_words + 1..inst.wc { @@ -1624,11 +1628,12 @@ impl> Parser { if self.next()? != spirv::MAGIC_NUMBER { return Err(Error::InvalidHeader); } - let _version_raw = self.next()?.to_le_bytes(); - let _generator = self.next()?; + let version_raw = self.next()?; + let generator = self.next()?; let _bound = self.next()?; let _schema = self.next()?; - crate::Module::generate_empty() + log::info!("Generated by {} version {:x}", generator, version_raw); + crate::Module::default() }; self.index_constants.clear(); @@ -2422,12 +2427,14 @@ impl> Parser { _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; + let decor = self.future_decor.remove(&id).unwrap_or_default(); + self.lookup_constant.insert( id, LookupConstant { handle: module.constants.append(crate::Constant { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - specialization: None, //TODO + specialization: decor.specialization, + name: decor.name, inner, }), type_id, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 8275f38ea..a34a5ef0a 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2189,7 +2189,7 @@ impl Parser { self.scopes.clear(); self.lookup_type.clear(); - let mut module = crate::Module::generate_empty(); + let mut module = crate::Module::default(); let mut lexer = Lexer::new(source); let mut lookup_global_expression = FastHashMap::default(); loop { diff --git a/src/lib.rs b/src/lib.rs index 4d0a113b5..38f78345d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,21 +42,6 @@ pub type FastHashMap = HashMap> /// Hash set that is faster but not resilient to DoS attacks. pub type FastHashSet = HashSet>; -/// Metadata for a given module. -#[derive(Clone, Debug)] -#[cfg_attr(feature = "serialize", derive(Serialize))] -#[cfg_attr(feature = "deserialize", derive(Deserialize))] -pub struct Header { - /// Major, minor and patch version. - /// - /// Currently used only for the SPIR-V back end. - pub version: (u8, u8, u8), - /// Magic number identifying the tool that generated the shader code. - /// - /// Can safely be set to 0. - pub generator: u32, -} - /// Early fragment tests. In a standard situation if a driver determines that it is possible to /// switch on early depth test it will. Typical situations when early depth test is switched off: /// - Calling ```discard``` in a shader. @@ -880,16 +865,14 @@ pub struct EntryPoint { /// /// Some functions are marked as entry points, to be used in a certain shader stage. /// -/// To create a new module, use [`Module::from_header`] or [`Module::generate_empty`]. +/// To create a new module, use the `Default` implementation. /// Alternatively, you can load an existing shader using one of the [available front ends][front]. /// /// When finished, you can export modules using one of the [available back ends][back]. -#[derive(Debug)] +#[derive(Debug, Default)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct Module { - /// Header containing module metadata. - pub header: Header, /// Storage for the types defined in this module. pub types: Arena, /// Storage for the constants defined in this module. diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index da2365392..ba48f483f 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -1,5 +1,6 @@ ( spv_flow_dump_prefix: "", + spv_version: (1, 0), spv_capabilities: [ Shader ], mtl_bindings: { (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: false), diff --git a/tests/in/collatz.param.ron b/tests/in/collatz.param.ron index 8a18d983a..5e2b5adaa 100644 --- a/tests/in/collatz.param.ron +++ b/tests/in/collatz.param.ron @@ -1,5 +1,6 @@ ( spv_flow_dump_prefix: "", + spv_version: (1, 0), spv_capabilities: [ Shader ], mtl_bindings: { (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: true), diff --git a/tests/in/empty.param.ron b/tests/in/empty.param.ron index 4adad3622..18fffb565 100644 --- a/tests/in/empty.param.ron +++ b/tests/in/empty.param.ron @@ -1,4 +1,5 @@ ( + spv_version: (1, 1), spv_capabilities: [ Shader ], mtl_bindings: { } diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index 25747c169..74dd08590 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -1,4 +1,5 @@ ( + spv_version: (1, 0), spv_capabilities: [ Shader ], mtl_bindings: { (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), diff --git a/tests/in/shadow.param.ron b/tests/in/shadow.param.ron index 760b8595d..0af3dcbba 100644 --- a/tests/in/shadow.param.ron +++ b/tests/in/shadow.param.ron @@ -1,5 +1,6 @@ ( spv_flow_dump_prefix: "", + spv_version: (1, 2), spv_capabilities: [ Shader ], mtl_bindings: { (stage: Fragment, group: 0, binding: 0): (buffer: Some(0), mutable: false), diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 8d5a2e3ec..f7e3b4f2e 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -1,5 +1,6 @@ ( spv_flow_dump_prefix: "", + spv_version: (1, 0), spv_capabilities: [ Shader ], mtl_bindings: { (stage: Vertex, group: 0, binding: 0): (buffer: Some(0)), diff --git a/tests/in/texture-array.param.ron b/tests/in/texture-array.param.ron index 21435d3ae..12ca44909 100644 --- a/tests/in/texture-array.param.ron +++ b/tests/in/texture-array.param.ron @@ -1,5 +1,6 @@ ( spv_flow_dump_prefix: "", + spv_version: (1, 5), spv_capabilities: [ Shader ], mtl_bindings: { (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), diff --git a/tests/out/empty.spvasm.snap b/tests/out/empty.spvasm.snap index e764f3e4d..fe37d10b6 100644 --- a/tests/out/empty.spvasm.snap +++ b/tests/out/empty.spvasm.snap @@ -3,7 +3,7 @@ source: tests/snapshots.rs expression: dis --- ; SPIR-V -; Version: 1.0 +; Version: 1.1 ; Generator: rspirv ; Bound: 6 OpCapability Shader diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index dd89e4874..59746a732 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -3,10 +3,6 @@ source: tests/snapshots.rs expression: output --- ( - header: ( - version: (1, 0, 0), - generator: 0, - ), types: [ ( name: None, diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index e1fd5a558..cb7d42040 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -3,7 +3,7 @@ source: tests/snapshots.rs expression: dis --- ; SPIR-V -; Version: 1.0 +; Version: 1.2 ; Generator: rspirv ; Bound: 221 OpCapability Shader diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap index 78e25937d..6b1e3e644 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm.snap @@ -3,7 +3,7 @@ source: tests/snapshots.rs expression: dis --- ; SPIR-V -; Version: 1.0 +; Version: 1.5 ; Generator: rspirv ; Bound: 46 OpCapability Shader diff --git a/tests/snapshots.rs b/tests/snapshots.rs index f66fd8b8d..98819997f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -42,6 +42,8 @@ struct Parameters { #[allow(dead_code)] spv_flow_dump_prefix: String, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + spv_version: (u8, u8), + #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_capabilities: naga::FastHashSet, #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] mtl_bindings: naga::FastHashMap, @@ -59,12 +61,13 @@ fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { use naga::back::spv; use rspirv::binary::Disassemble; - let spv = spv::write_vec( - &module, - spv::WriterFlags::DEBUG, - params.spv_capabilities.clone(), - ) - .unwrap(); + let options = spv::Options { + lang_version: params.spv_version, + flags: spv::WriterFlags::DEBUG, + capabilities: params.spv_capabilities.clone(), + }; + + let spv = spv::write_vec(&module, &options).unwrap(); let dis = rspirv::dr::load_words(spv) .expect("Produced invalid SPIR-V") From ad423124c0aebcd695c92838fca860f8e120ce6b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Feb 2021 13:43:36 -0500 Subject: [PATCH 0494/2212] Support constants in the naming processor --- src/back/msl/writer.rs | 119 +++++++++++++++++++------------------ src/proc/namer.rs | 63 ++++++++++++++++++-- tests/out/boids.msl.snap | 57 ++++++++++-------- tests/out/collatz.msl.snap | 16 +++-- tests/out/quad.msl.snap | 5 +- tests/out/shadow.msl.snap | 29 +++++---- tests/out/skybox.msl.snap | 11 +++- 7 files changed, 193 insertions(+), 107 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 970e9210f..8619b9ccd 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -301,7 +301,10 @@ impl Writer { } } } - crate::Expression::Constant(handle) => self.put_constant(handle, context.module)?, + crate::Expression::Constant(handle) => { + let handle_name = &self.names[&NameKey::Constant(handle)]; + write!(self.out, "{}", handle_name)?; + } crate::Expression::Compose { ty, ref components } => { let inner = &context.module.types[ty].inner; match *inner { @@ -428,8 +431,8 @@ impl Writer { } } if let Some(constant) = offset { - write!(self.out, ", ")?; - self.put_constant(constant, context.module)?; + let offset_str = &self.names[&NameKey::Constant(constant)]; + write!(self.out, ", {}", offset_str)?; } write!(self.out, ")")?; } @@ -687,7 +690,8 @@ impl Writer { size: crate::ArraySize::Constant(const_handle), .. } => { - self.put_constant(const_handle, context.module)?; + let size_str = &self.names[&NameKey::Constant(const_handle)]; + write!(self.out, "{}", size_str)?; } crate::TypeInner::Array { .. } => return Err(Error::UnsupportedDynamicArrayLength), _ => return Err(Error::Validation), @@ -696,48 +700,6 @@ impl Writer { Ok(()) } - fn put_constant( - &mut self, - handle: Handle, - module: &crate::Module, - ) -> Result<(), Error> { - let constant = &module.constants[handle]; - match constant.inner { - crate::ConstantInner::Scalar { - width: _, - ref value, - } => match *value { - crate::ScalarValue::Sint(value) => { - write!(self.out, "{}", value)?; - } - crate::ScalarValue::Uint(value) => { - write!(self.out, "{}u", value)?; - } - crate::ScalarValue::Float(value) => { - write!(self.out, "{}", value)?; - if value.fract() == 0.0 { - write!(self.out, ".0")?; - } - } - crate::ScalarValue::Bool(value) => { - write!(self.out, "{}", value)?; - } - }, - crate::ConstantInner::Composite { ty, ref components } => { - let ty_name = &self.names[&NameKey::Type(ty)]; - write!(self.out, "{}(", ty_name)?; - for (i, &handle) in components.iter().enumerate() { - if i != 0 { - write!(self.out, ", ")?; - } - self.put_constant(handle, module)?; - } - write!(self.out, ")")?; - } - } - Ok(()) - } - // Write down any required intermediate results fn prepare_expression( &mut self, @@ -956,6 +918,7 @@ impl Writer { writeln!(self.out)?; self.write_type_defs(module)?; + self.write_constants(module)?; self.write_functions(module, analysis, options) } @@ -1008,14 +971,13 @@ impl Writer { stride: _, } => { let base_name = &self.names[&NameKey::Type(base)]; - write!(self.out, "typedef {} {}[", base_name, name)?; - match size { + let size_str = match size { crate::ArraySize::Constant(const_handle) => { - self.put_constant(const_handle, module)?; - write!(self.out, "]")?; + &self.names[&NameKey::Constant(const_handle)] } - crate::ArraySize::Dynamic => write!(self.out, "1]")?, - } + crate::ArraySize::Dynamic => "1", + }; + write!(self.out, "typedef {} {}[{}]", base_name, name, size_str)?; } crate::TypeInner::Struct { block: _, @@ -1094,6 +1056,47 @@ impl Writer { Ok(()) } + fn write_constants(&mut self, module: &crate::Module) -> Result<(), Error> { + for (handle, constant) in module.constants.iter() { + write!(self.out, "constexpr constant ")?; + let name = &self.names[&NameKey::Constant(handle)]; + match constant.inner { + crate::ConstantInner::Scalar { + width: _, + ref value, + } => match *value { + crate::ScalarValue::Sint(value) => { + write!(self.out, "int {} = {}", name, value)?; + } + crate::ScalarValue::Uint(value) => { + write!(self.out, "unsigned {} = {}u", name, value)?; + } + crate::ScalarValue::Float(value) => { + write!(self.out, "float {} = {}", name, value)?; + if value.fract() == 0.0 { + write!(self.out, ".0")?; + } + } + crate::ScalarValue::Bool(value) => { + write!(self.out, "bool {} = {}", name, value)?; + } + }, + crate::ConstantInner::Composite { ty, ref components } => { + let ty_name = &self.names[&NameKey::Type(ty)]; + write!(self.out, "{} {} = {}(", ty_name, name, ty_name)?; + for (i, &sub_handle) in components.iter().enumerate() { + let separator = if i != 0 { ", " } else { "" }; + let sub_name = &self.names[&NameKey::Constant(sub_handle)]; + write!(self.out, "{}{}", separator, sub_name)?; + } + write!(self.out, ")")?; + } + } + writeln!(self.out, ";")?; + } + Ok(()) + } + // Returns the array of mapped entry point names. fn write_functions( &mut self, @@ -1159,8 +1162,8 @@ impl Writer { let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; write!(self.out, "{}{} {}", INDENT, ty_name, local_name)?; if let Some(value) = local.init { - write!(self.out, " = ")?; - self.put_constant(value, module)?; + let value_str = &self.names[&NameKey::Constant(value)]; + write!(self.out, " = {}", value_str)?; } writeln!(self.out, ";")?; } @@ -1342,8 +1345,8 @@ impl Writer { tyvar.try_fmt(&mut self.out)?; resolved.try_fmt_decorated(&mut self.out, separator)?; if let Some(value) = var.init { - write!(self.out, " = ")?; - self.put_constant(value, module)?; + let value_str = &self.names[&NameKey::Constant(value)]; + write!(self.out, " = {}", value_str)?; } writeln!(self.out)?; } @@ -1364,8 +1367,8 @@ impl Writer { let ty_name = &self.names[&NameKey::Type(local.ty)]; write!(self.out, "{}{} {}", INDENT, ty_name, name)?; if let Some(value) = local.init { - write!(self.out, " = ")?; - self.put_constant(value, module)?; + let value_str = &self.names[&NameKey::Constant(value)]; + write!(self.out, " = {}", value_str)?; } writeln!(self.out, ";")?; } diff --git a/src/proc/namer.rs b/src/proc/namer.rs index bc083fbd5..c76ab8914 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -5,6 +5,7 @@ pub type EntryPointIndex = u16; #[derive(Debug, Eq, Hash, PartialEq)] pub enum NameKey { + Constant(Handle), GlobalVariable(Handle), Type(Handle), StructMember(Handle, u32), @@ -69,11 +70,7 @@ impl Namer { self.unique.clear(); self.unique .extend(reserved.iter().map(|string| (string.to_string(), 0))); - - for (handle, var) in module.global_variables.iter() { - let name = self.call_or(&var.name, "global"); - output.insert(NameKey::GlobalVariable(handle), name); - } + let mut temp = String::new(); for (ty_handle, ty) in module.types.iter() { let ty_name = self.call_or(&ty.name, "type"); @@ -91,6 +88,62 @@ impl Namer { } } + for (handle, var) in module.global_variables.iter() { + let name = self.call_or(&var.name, "global"); + output.insert(NameKey::GlobalVariable(handle), name); + } + + for (handle, constant) in module.constants.iter() { + let label = match constant.name { + Some(ref name) => name, + None => { + use std::fmt::Write; + // Try to be more descriptive about the constant values + temp.clear(); + match constant.inner { + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Sint(v), + } => write!(temp, "const_{}i", v), + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(v), + } => write!(temp, "const_{}u", v), + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Float(v), + } => { + let abs = v.abs(); + write!( + temp, + "const_{}{}", + if v < 0.0 { "n" } else { "" }, + abs.trunc(), + ) + .unwrap(); + let fract = abs.fract(); + if fract == 0.0 { + write!(temp, "f") + } else { + write!(temp, "_{:02}f", (fract * 100.0) as i8) + } + } + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Bool(v), + } => write!(temp, "const_{}", v), + crate::ConstantInner::Composite { ty, components: _ } => { + write!(temp, "const_{}", output[&NameKey::Type(ty)]) + } + } + .unwrap(); + &temp + } + }; + let name = self.call(label); + output.insert(NameKey::Constant(handle), name); + } + for (fun_handle, fun) in module.functions.iter() { let fun_name = self.call_or(&fun.name, "function"); output.insert(NameKey::Function(fun_handle), fun_name); diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index 47cdc704c..13c88f756 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -38,6 +38,15 @@ typedef int type5; typedef bool type6; +constexpr constant int NUM_PARTICLES = 1500; +constexpr constant float const_0f = 0.0; +constexpr constant int const_0i = 0; +constexpr constant unsigned const_0u = 0u; +constexpr constant int const_1i = 1; +constexpr constant unsigned const_1u = 1u; +constexpr constant float const_1f = 1.0; +constexpr constant float const_0_10f = 0.1; +constexpr constant float const_n1f = -1.0; kernel void main1( constant SimParams& params [[buffer(0)]], constant Particles& particlesSrc [[buffer(1)]], @@ -49,26 +58,26 @@ kernel void main1( type1 cMass; type1 cVel; type1 colVel; - type5 cMassCount = 0; - type5 cVelCount = 0; + type5 cMassCount = const_0i; + type5 cVelCount = const_0i; type1 pos1; type1 vel1; - type i = 0u; - if ((gl_GlobalInvocationID.x >= 1500)) { + type i = const_0u; + if ((gl_GlobalInvocationID.x >= NUM_PARTICLES)) { return ; } vPos = particlesSrc.particles[gl_GlobalInvocationID.x].pos; vVel = particlesSrc.particles[gl_GlobalInvocationID.x].vel; - cMass = metal::float2(0.0, 0.0); - cVel = metal::float2(0.0, 0.0); - colVel = metal::float2(0.0, 0.0); + cMass = metal::float2(const_0f, const_0f); + cVel = metal::float2(const_0f, const_0f); + colVel = metal::float2(const_0f, const_0f); bool loop_init = true; while(true) { if (!loop_init) { - i = (i + 1u); + i = (i + const_1u); } loop_init = false; - if ((i >= 1500)) { + if ((i >= NUM_PARTICLES)) { break; } if ((i == gl_GlobalInvocationID.x)) { @@ -78,36 +87,36 @@ kernel void main1( vel1 = particlesSrc.particles[i].vel; if ((metal::distance(pos1, vPos) < params.rule1Distance)) { cMass = (cMass + pos1); - cMassCount = (cMassCount + 1); + cMassCount = (cMassCount + const_1i); } if ((metal::distance(pos1, vPos) < params.rule2Distance)) { colVel = (colVel - (pos1 - vPos)); } if ((metal::distance(pos1, vPos) < params.rule3Distance)) { cVel = (cVel + vel1); - cVelCount = (cVelCount + 1); + cVelCount = (cVelCount + const_1i); } } - if ((cMassCount > 0)) { - cMass = ((cMass * (1.0 / static_cast(cMassCount))) - vPos); + if ((cMassCount > const_0i)) { + cMass = ((cMass * (const_1f / static_cast(cMassCount))) - vPos); } - if ((cVelCount > 0)) { - cVel = (cVel * (1.0 / static_cast(cVelCount))); + if ((cVelCount > const_0i)) { + cVel = (cVel * (const_1f / static_cast(cVelCount))); } vVel = (((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale)); - vVel = (metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1)); + vVel = (metal::normalize(vVel) * metal::clamp(metal::length(vVel), const_0f, const_0_10f)); vPos = (vPos + (vVel * params.deltaT)); - if ((vPos.x < -1.0)) { - vPos.x = 1.0; + if ((vPos.x < const_n1f)) { + vPos.x = const_1f; } - if ((vPos.x > 1.0)) { - vPos.x = -1.0; + if ((vPos.x > const_1f)) { + vPos.x = const_n1f; } - if ((vPos.y < -1.0)) { - vPos.y = 1.0; + if ((vPos.y < const_n1f)) { + vPos.y = const_1f; } - if ((vPos.y > 1.0)) { - vPos.y = -1.0; + if ((vPos.y > const_1f)) { + vPos.y = const_n1f; } particlesDst.particles[gl_GlobalInvocationID.x].pos = vPos; particlesDst.particles[gl_GlobalInvocationID.x].vel = vVel; diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index 10912b0ef..2ab590d73 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -15,22 +15,26 @@ struct PrimeIndices { type2 data; }; +constexpr constant unsigned const_0u = 0u; +constexpr constant unsigned const_1u = 1u; +constexpr constant unsigned const_2u = 2u; +constexpr constant unsigned const_3u = 3u; type1 collatz_iterations( type1 n_base ) { type1 n; - type1 i = 0u; + type1 i = const_0u; n = n_base; while(true) { - if ((n <= 1u)) { + if ((n <= const_1u)) { break; } - if (((n % 2u) == 0u)) { - n = (n / 2u); + if (((n % const_2u) == const_0u)) { + n = (n / const_2u); } else { - n = ((3u * n) + 1u); + n = ((const_3u * n) + const_1u); } - i = (i + 1u); + i = (i + const_1u); } return i; } diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index 488e66966..be352e902 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -15,6 +15,9 @@ typedef metal::texture2d type3; typedef metal::sampler type4; +constexpr constant float c_scale = 1.2; +constexpr constant float const_0f = 0.0; +constexpr constant float const_1f = 1.0; struct main1Input { type1 a_pos [[attribute(0)]]; type1 a_uv [[attribute(1)]]; @@ -30,7 +33,7 @@ vertex main1Output main1( ) { main1Output output; output.v_uv = input.a_uv; - output.o_position = metal::float4((1.2 * input.a_pos), 0.0, 1.0); + output.o_position = metal::float4((c_scale * input.a_pos), const_0f, const_1f); return output; } diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 400381564..53984b124 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -41,17 +41,26 @@ typedef metal::float3 type9; typedef bool type10; +constexpr constant float const_0f = 0.0; +constexpr constant float const_1f = 1.0; +constexpr constant float const_0_50f = 0.5; +constexpr constant float const_n0_50f = -0.5; +constexpr constant float const_0_05f = 0.05; +constexpr constant type9 c_ambient = type9(const_0_05f, const_0_05f, const_0_05f); +constexpr constant unsigned c_max_lights = 10u; +constexpr constant unsigned const_0u = 0u; +constexpr constant unsigned const_1u = 1u; type7 fetch_shadow( type6 light_id, type2 homogeneous_coords, type4 t_shadow, type5 sampler_shadow ) { - if ((homogeneous_coords.w <= 0.0)) { - return 1.0; + if ((homogeneous_coords.w <= const_0f)) { + return const_1f; } - float expr15 = (1.0 / homogeneous_coords.w); - return t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) * expr15) + metal::float2(0.5, 0.5)), static_cast(light_id), (homogeneous_coords.z * expr15)); + float expr15 = (const_1f / homogeneous_coords.w); + return t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * expr15) + metal::float2(const_0_50f, const_0_50f)), static_cast(light_id), (homogeneous_coords.z * expr15)); } struct fs_mainInput { @@ -71,22 +80,22 @@ fragment fs_mainOutput fs_main( type5 sampler_shadow [[sampler(0)]] ) { fs_mainOutput output; - type9 color1 = type9(0.05, 0.05, 0.05); - type6 i = 0u; + type9 color1 = c_ambient; + type6 i = const_0u; bool loop_init = true; while(true) { if (!loop_init) { - i = (i + 1u); + i = (i + const_1u); } loop_init = false; - if ((i >= metal::min(u_globals.num_lights.x, 10u))) { + if ((i >= metal::min(u_globals.num_lights.x, c_max_lights))) { break; } Light expr18 = s_lights.data[i]; type7 expr21 = fetch_shadow(i, (expr18.proj * input.in_position_fs), t_shadow, sampler_shadow); - color1 = (color1 + ((expr21 * metal::max(0.0, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(expr18.pos.x, expr18.pos.y, expr18.pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(expr18.color.x, expr18.color.y, expr18.color.z))); + color1 = (color1 + ((expr21 * metal::max(const_0f, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(expr18.pos.x, expr18.pos.y, expr18.pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(expr18.color.x, expr18.color.y, expr18.color.z))); } - output.out_color_fs = metal::float4(color1, 1.0); + output.out_color_fs = metal::float4(color1, const_1f); return output; } diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index bb036f6ac..277e9e681 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -28,6 +28,11 @@ typedef metal::texturecube type7; typedef metal::sampler type8; +constexpr constant int const_2i = 2; +constexpr constant int const_1i = 1; +constexpr constant float const_4f = 4.0; +constexpr constant float const_1f = 1.0; +constexpr constant float const_0f = 0.0; struct vs_mainInput { }; @@ -45,9 +50,9 @@ vertex vs_mainOutput vs_main( type4 tmp1_; type4 tmp2_; type unprojected; - tmp1_ = (static_cast(in_vertex_index) / 2); - tmp2_ = (static_cast(in_vertex_index) & 1); - type expr24 = metal::float4(((static_cast(tmp1_) * 4.0) - 1.0), ((static_cast(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + tmp1_ = (static_cast(in_vertex_index) / const_2i); + tmp2_ = (static_cast(in_vertex_index) & const_1i); + type expr24 = metal::float4(((static_cast(tmp1_) * const_4f) - const_1f), ((static_cast(tmp2_) * const_4f) - const_1f), const_0f, const_1f); unprojected = (r_data.proj_inv * expr24); output.out_uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z)); output.out_position = expr24; From f42dc0c37708a7baa0c4e44e7d73ccb258069cb3 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Sun, 14 Feb 2021 23:09:08 -0330 Subject: [PATCH 0495/2212] Fix some typos --- src/back/glsl/features.rs | 2 +- src/back/glsl/mod.rs | 36 ++++++++++++++++++------------------ src/front/glsl/ast.rs | 4 ++-- src/front/glsl/constants.rs | 10 +++++----- src/front/glsl/error.rs | 2 +- src/front/glsl/parser.rs | 2 +- src/front/spv/flow.rs | 2 +- src/front/wgsl/mod.rs | 2 +- src/lib.rs | 2 +- src/proc/typifier.rs | 2 +- 10 files changed, 32 insertions(+), 32 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index b71447657..4f75cbd09 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -6,7 +6,7 @@ use crate::{ use std::io::Write; bitflags::bitflags! { - /// Structure used to encode a set of addittions to glsl that aren't supported by all versions + /// Structure used to encode a set of additions to glsl that aren't supported by all versions pub struct Features: u32 { /// Buffer storage class support const BUFFER_STORAGE = 1; diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9bccb8681..d695f6954 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -96,7 +96,7 @@ impl Version { /// /// # Notes /// As an invalid version number will never be added to the supported version list - /// so this also checks for verson validity + /// so this also checks for version validity fn is_supported(&self) -> bool { match self { Version::Desktop(v) => SUPPORTED_CORE_VERSIONS.contains(v), @@ -131,7 +131,7 @@ pub struct Options { pub version: Version, /// The name and stage of the entry point /// - /// If no enty point that matches is found a error will be thrown while creating a new instance + /// If no entry point that matches is found a error will be thrown while creating a new instance /// of [`Writer`](struct.Writer.html) pub entry_point: (ShaderStage, String), } @@ -293,7 +293,7 @@ impl<'a, W: Write> Writer<'a, W> { return Err(Error::VersionNotSupported); } - // Try to find the entry point and correspoding index + // Try to find the entry point and corresponding index let (ep_idx, ep) = module .entry_points .iter() @@ -473,9 +473,9 @@ impl<'a, W: Write> Writer<'a, W> { // Write all regular functions that are in the call graph this is important // because other functions might require for example globals that weren't written for node in functions { - // We do this inside the loop instead of using `map` to sastify the borrow checker + // We do this inside the loop instead of using `map` to satisfy the borrow checker let handle = self.call_graph[node]; - // We also `clone` to sastify the borrow checker + // We also `clone` to satisfy the borrow checker let name = self.names[&NameKey::Function(handle)].clone(); // Write the function @@ -508,7 +508,7 @@ impl<'a, W: Write> Writer<'a, W> { /// Helper method used to write non image/sampler types /// /// # Notes - /// Adds no trailing or leading whitespaces + /// Adds no trailing or leading whitespace /// /// # Panics /// - If type is either a image or sampler @@ -608,7 +608,7 @@ impl<'a, W: Write> Writer<'a, W> { // Panic if either Image or Sampler is being written // // Write all variants instead of `_` so that if new variants are added a - // no exhaustivenes error is thrown + // no exhaustiveness error is thrown TypeInner::Image { .. } | TypeInner::Sampler { .. } => unreachable!(), } @@ -618,7 +618,7 @@ impl<'a, W: Write> Writer<'a, W> { /// Helper method to write a image type /// /// # Notes - /// Adds no leading or trailing whitespaces + /// Adds no leading or trailing whitespace fn write_image_type( &mut self, dim: crate::ImageDimension, @@ -793,7 +793,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "void")?; } - // Write the function name and open parantheses for the argument list + // Write the function name and open parentheses for the argument list write!(self.out, " {}(", name.as_ref())?; // Write the comma separated argument list @@ -812,7 +812,7 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) })?; - // Close the parantheses and open braces to start the function body + // Close the parentheses and open braces to start the function body writeln!(self.out, ") {{")?; // Write all function locals @@ -865,7 +865,7 @@ impl<'a, W: Write> Writer<'a, W> { /// a reference to the element `T` being written /// /// # Notes - /// - Adds no newlines or leading/trailing whitespaces + /// - Adds no newlines or leading/trailing whitespace /// - The last element won't have a trailing `,` fn write_slice BackendResult>( &mut self, @@ -889,7 +889,7 @@ impl<'a, W: Write> Writer<'a, W> { /// Helper method used to write constants /// /// # Notes - /// Adds no newlines or leading/trailing whitespaces + /// Adds no newlines or leading/trailing whitespace fn write_constant(&mut self, constant: &Constant) -> BackendResult { match constant.inner { ConstantInner::Scalar { @@ -903,7 +903,7 @@ impl<'a, W: Write> Writer<'a, W> { // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we // always write it as the extra branch wouldn't have any benefit in readability ScalarValue::Uint(int) => write!(self.out, "{}u", int)?, - // Floats are written using `Debug` insted of `Display` because it always appends the + // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero which is needed for a valid glsl float constant ScalarValue::Float(float) => write!(self.out, "{:?}", float)?, // Booleans are either `true` or `false` so nothing special needs to be done @@ -1029,7 +1029,7 @@ impl<'a, W: Write> Writer<'a, W> { // Switch are written as in C: // ``` // switch (selector) { - // // Falltrough + // // Fallthrough // case label: // block // // Non fallthrough @@ -1463,7 +1463,7 @@ impl<'a, W: Write> Writer<'a, W> { // `Binary` we just write `left op right`, except when dealing with // comparison operations on vectors as they are implemented with // builtin functions. - // Once again we wrap everything in parantheses to avoid precedence issues + // Once again we wrap everything in parentheses to avoid precedence issues Expression::Binary { op, left, right } => { // Holds `Some(function_name)` if the binary operation is // implemented as a function call @@ -1521,7 +1521,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } // `Select` is written as `condition ? accept : reject` - // We wrap everything in parantheses to avoid precedence issues + // We wrap everything in parentheses to avoid precedence issues Expression::Select { condition, accept, @@ -1849,7 +1849,7 @@ fn glsl_built_in(built_in: BuiltIn) -> &'static str { } } -/// Helper function that returns the string correspoding to the storage class +/// Helper function that returns the string corresponding to the storage class fn glsl_storage_class(class: StorageClass) -> &'static str { match class { StorageClass::Function => "", @@ -1864,7 +1864,7 @@ fn glsl_storage_class(class: StorageClass) -> &'static str { } } -/// Helper function that returns the string correspoding to the glsl interpolation qualifier +/// Helper function that returns the string corresponding to the glsl interpolation qualifier /// /// # Errors /// If [`Patch`](crate::Interpolation::Patch) is passed, as it isn't supported in glsl diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index bcad2b05d..0d5ba6b7f 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -78,7 +78,7 @@ impl Program { _ => false, }; - let rigth_is_vector = match self.resolve_type(right.expression)? { + let right_is_vector = match self.resolve_type(right.expression)? { crate::TypeInner::Vector { .. } => true, _ => false, }; @@ -95,7 +95,7 @@ impl Program { right: right.expression, })); - Ok(if left_is_vector && rigth_is_vector { + Ok(if left_is_vector && right_is_vector { ExpressionRule::from_expression(self.context.expressions.append( Expression::Relational { fun, diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 14f748a0f..ba0e7381e 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -189,13 +189,13 @@ impl<'a> ConstantSolver<'a> { match inner { ConstantInner::Scalar { ref mut value, .. } => { - let intial = value.clone(); + let initial = value.clone(); *value = match kind { - ScalarKind::Sint => ScalarValue::Sint(inner_cast(intial)), - ScalarKind::Uint => ScalarValue::Uint(inner_cast(intial)), - ScalarKind::Float => ScalarValue::Float(inner_cast(intial)), - ScalarKind::Bool => ScalarValue::Bool(inner_cast::(intial) != 0), + ScalarKind::Sint => ScalarValue::Sint(inner_cast(initial)), + ScalarKind::Uint => ScalarValue::Uint(inner_cast(initial)), + ScalarKind::Float => ScalarValue::Float(inner_cast(initial)), + ScalarKind::Bool => ScalarValue::Bool(inner_cast::(initial) != 0), } } ConstantInner::Composite { diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 5c2d6f44c..2a8537086 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -47,7 +47,7 @@ impl fmt::Display for ErrorKind { ErrorKind::UnknownField(meta, val) => write!(f, "Unknown field {} at {:?}", val, meta), #[cfg(feature = "glsl-validate")] ErrorKind::VariableAlreadyDeclared(val) => { - write!(f, "Variable {} already decalred in current scope", val) + write!(f, "Variable {} already declared in current scope", val) } #[cfg(feature = "glsl-validate")] ErrorKind::VariableNotAvailable(val) => { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index bb7d473b9..0e1748311 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1145,7 +1145,7 @@ pomelo! { extra.context.lookup_constant_exps.insert(id, expr); } } else { - return Err(ErrorKind::SemanticError("Constants must have an initalizer".into())) + return Err(ErrorKind::SemanticError("Constants must have an initializer".into())) } } } diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index c11a1eda0..9a6c11366 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -191,7 +191,7 @@ impl FlowGraph { /// Removes OpPhi instructions from the control flow graph and turns them into ordinary variables. /// - /// Phi instructions are not supported inside Naga nor do they exist as instructions on CPUs. It is neccessary + /// Phi instructions are not supported inside Naga nor do they exist as instructions on CPUs. It is necessary /// to remove them and turn into ordinary variables before converting to Naga's IR and shader code. pub(super) fn remove_phi_instructions( &mut self, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index a34a5ef0a..b096dc6ea 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1888,7 +1888,7 @@ impl Parser { // read function name let mut lookup_ident = FastHashMap::default(); let fun_name = lexer.next_ident()?; - // populare initial expressions + // populate initial expressions let mut expressions = Arena::new(); for (&name, expression) in lookup_global_expression.iter() { let expr_handle = expressions.append(expression.clone()); diff --git a/src/lib.rs b/src/lib.rs index 38f78345d..f37eb625c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -402,7 +402,7 @@ pub enum ScalarValue { Bool(bool), } -/// Additional information, dependendent on the kind of constant. +/// Additional information, dependent on the kind of constant. #[derive(Debug, PartialEq, Clone)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index c97309e49..9bea6137c 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -30,7 +30,7 @@ impl Clone for Resolution { width, }, #[allow(clippy::panic)] - _ => panic!("Unepxected clone type: {:?}", v), + _ => panic!("Unexpected clone type: {:?}", v), }), } } From 6d0c608626704bdd2e85396ac6d53b86ee259ce7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 14 Feb 2021 17:26:31 -0500 Subject: [PATCH 0496/2212] [glsl-out] use existing Analysis instead of implementing Visitor --- examples/convert.rs | 3 +- src/back/glsl/mod.rs | 149 ++++++++++++++++--------------------------- tests/snapshots.rs | 13 ++-- 3 files changed, 64 insertions(+), 101 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index ee93dc13a..008279e5d 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -149,7 +149,6 @@ fn main() { }; // validate the IR - #[cfg_attr(not(feature = "msl-out"), allow(unused_variables))] let analysis = naga::proc::Validator::new() .validate(&module) .unwrap_pretty(); @@ -258,7 +257,7 @@ fn main() { .open(&args[2]) .unwrap(); - let mut writer = glsl::Writer::new(file, &module, &options).unwrap_pretty(); + let mut writer = glsl::Writer::new(file, &module, &analysis, &options).unwrap_pretty(); writer .write() diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index d695f6954..677911a1a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -45,8 +45,8 @@ pub use features::Features; use crate::{ proc::{ - CallGraph, CallGraphBuilder, Interface, NameKey, Namer, ResolveContext, ResolveError, - Typifier, Visitor, + analyzer::Analysis, CallGraph, CallGraphBuilder, NameKey, Namer, ResolveContext, + ResolveError, Typifier, }, Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, @@ -258,6 +258,8 @@ pub struct Writer<'a, W> { // Inputs /// The module being written module: &'a Module, + /// The module analysis. + analysis: &'a Analysis, /// The output writer out: W, /// User defined configuration to be used @@ -286,7 +288,12 @@ impl<'a, W: Write> Writer<'a, W> { /// - If the version specified isn't supported (or invalid) /// - If the entry point couldn't be found on the module /// - If the version specified doesn't support some used features - pub fn new(out: W, module: &'a Module, options: &'a Options) -> Result { + pub fn new( + out: W, + module: &'a Module, + analysis: &'a Analysis, + options: &'a Options, + ) -> Result { // Check if the requested version is supported if !options.version.is_supported() { log::error!("Version {}", options.version); @@ -316,6 +323,7 @@ impl<'a, W: Write> Writer<'a, W> { // Build the instance let mut this = Self { module, + analysis, out, options, @@ -495,14 +503,7 @@ impl<'a, W: Write> Writer<'a, W> { )?; // Collect all of the texture mappings and return them to the user - self.collect_texture_mapping( - // Create an iterator with all functions in the call graph and the entry point - self.call_graph - .raw_nodes() - .iter() - .map(|node| &self.module.functions[node.weight]) - .chain(std::iter::once(&self.entry_point.function)), - ) + self.collect_texture_mapping() } /// Helper method used to write non image/sampler types @@ -1748,29 +1749,51 @@ impl<'a, W: Write> Writer<'a, W> { /// It takes an iterator of [`Function`](crate::Function) references instead of /// [`Handle`](crate::arena::Handle) because [`EntryPoint`](crate::EntryPoint) isn't in any /// [`Arena`](crate::arena::Arena) and we need to traverse it - fn collect_texture_mapping( - &self, - functions: impl Iterator, - ) -> Result, Error> { + fn collect_texture_mapping(&self) -> Result, Error> { + use std::collections::hash_map::Entry; + let info = self + .analysis + .get_entry_point(self.options.entry_point.0, &self.options.entry_point.1); let mut mappings = FastHashMap::default(); - // Traverse each function in the `functions` iterator with `TextureMappingVisitor` - for func in functions { - let mut interface = Interface { - expressions: &func.expressions, - local_variables: &func.local_variables, - visitor: TextureMappingVisitor { - names: &self.names, - expressions: &func.expressions, - map: &mut mappings, - error: None, - }, - }; - interface.traverse(&func.body); + for sampling in info.sampling_set.iter() { + let tex_name = self.names[&NameKey::GlobalVariable(sampling.image)].clone(); - // Check if any error occurred - if let Some(error) = interface.visitor.error { - return Err(error); + match mappings.entry(tex_name) { + Entry::Vacant(v) => { + v.insert(TextureMapping { + texture: sampling.image, + sampler: Some(sampling.sampler), + }); + } + Entry::Occupied(e) => { + if e.get().sampler != Some(sampling.sampler) { + log::error!("Conflicting samplers for {}", e.key()); + return Err(Error::ImageMultipleSamplers); + } + } + } + } + + for ((handle, var), &usage) in self + .module + .global_variables + .iter() + .zip(&self.entry_point.function.global_usage) + { + if usage.is_empty() { + continue; + } + match self.module.types[var.ty].inner { + crate::TypeInner::Image { .. } => (), + _ => continue, + } + let tex_name = self.names[&NameKey::GlobalVariable(handle)].clone(); + if let Entry::Vacant(e) = mappings.entry(tex_name) { + e.insert(TextureMapping { + texture: handle, + sampler: None, + }); } } @@ -1926,67 +1949,3 @@ fn glsl_storage_format(format: StorageFormat) -> &'static str { StorageFormat::Rgba32Float => "rgba32f", } } - -/// [`Visitor`](crate::proc::Visitor) used by [`collect_texture_mapping`](Writer::collect_texture_mapping) -struct TextureMappingVisitor<'a> { - /// Names needed by the module (used to get the image name) - names: &'a FastHashMap, - /// [`Arena`](crate::arena::Arena) of expressions of the function being currently visited - expressions: &'a Arena, - /// The mapping that we are building - map: &'a mut FastHashMap, - /// Used to return errors since [`visit_expr`](crate::proc::Visitor::visit_expr) doesn't allow - /// us to return anything - error: Option, -} - -impl<'a> Visitor for TextureMappingVisitor<'a> { - fn visit_expr(&mut self, _: Handle, expr: &Expression) { - // We only care about `ImageSample` and `ImageLoad` - // - // Both `image` and `sampler` are `Expression::GlobalVariable` otherwise the module is - // invalid so it's okay to panic - // - // A image can only be used with one sampler or with none at all - match expr { - Expression::ImageSample { image, sampler, .. } => { - let tex_handle = match self.expressions[*image] { - Expression::GlobalVariable(global) => global, - _ => unreachable!(), - }; - let tex_name = self.names[&NameKey::GlobalVariable(tex_handle)].clone(); - - let sampler_handle = match self.expressions[*sampler] { - Expression::GlobalVariable(global) => global, - _ => unreachable!(), - }; - - let mapping = self.map.entry(tex_name).or_insert(TextureMapping { - texture: tex_handle, - sampler: Some(sampler_handle), - }); - - if mapping.sampler != Some(sampler_handle) { - self.error = Some(Error::ImageMultipleSamplers); - } - } - Expression::ImageLoad { image, .. } => { - let tex_handle = match self.expressions[*image] { - Expression::GlobalVariable(global) => global, - _ => unreachable!(), - }; - let tex_name = self.names[&NameKey::GlobalVariable(tex_handle)].clone(); - - let mapping = self.map.entry(tex_name).or_insert(TextureMapping { - texture: tex_handle, - sampler: None, - }); - - if mapping.sampler != None { - self.error = Some(Error::ImageMultipleSamplers); - } - } - _ => {} - } - } -} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 98819997f..29579025c 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -120,7 +120,13 @@ fn check_output_msl( } #[cfg(feature = "glsl-out")] -fn check_output_glsl(module: &naga::Module, name: &str, stage: naga::ShaderStage, ep_name: &str) { +fn check_output_glsl( + module: &naga::Module, + analysis: &naga::proc::analyzer::Analysis, + name: &str, + stage: naga::ShaderStage, + ep_name: &str, +) { use naga::back::glsl; let options = glsl::Options { @@ -129,7 +135,7 @@ fn check_output_glsl(module: &naga::Module, name: &str, stage: naga::ShaderStage }; let mut buffer = Vec::new(); - let mut writer = glsl::Writer::new(&mut buffer, &module, &options).unwrap(); + let mut writer = glsl::Writer::new(&mut buffer, module, analysis, &options).unwrap(); writer.write().unwrap(); let string = String::from_utf8(buffer).unwrap(); @@ -151,7 +157,6 @@ fn convert_wgsl(name: &str, language: Language) { .expect("Couldn't find wgsl file"), ) .unwrap(); - #[cfg_attr(not(feature = "msl-out"), allow(unused_variables))] let analysis = naga::proc::Validator::new().validate(&module).unwrap(); #[cfg(feature = "spv-out")] @@ -170,7 +175,7 @@ fn convert_wgsl(name: &str, language: Language) { { if language.contains(Language::GLSL) { for &(stage, ref ep_name) in module.entry_points.keys() { - check_output_glsl(&module, name, stage, ep_name); + check_output_glsl(&module, &analysis, name, stage, ep_name); } } } From 91a1f581e01d4cb20eea2d8a2bdee919a99a30b7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 15 Feb 2021 11:09:11 -0500 Subject: [PATCH 0497/2212] Fix insta dependency to 1.5.2 --- Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 429295f32..109f36584 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,5 +42,6 @@ env_logger = "0.8" ron = "0.6" serde = { version = "1.0", features = ["derive"] } spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } -insta = { version = "1.3", features = ["glob"] } +# `similar` dependency, introduced in 1.5.3, breaks MSRV +insta = { version = "=1.5.2", features = ["glob"] } rspirv = "0.7" From e6251a23fe011ccb3136458144e4678be074ab7f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 15 Feb 2021 22:54:25 -0500 Subject: [PATCH 0498/2212] [wgsl] fix boolean types and bang parsing --- src/front/wgsl/lexer.rs | 1 + src/front/wgsl/mod.rs | 4 ++++ src/front/wgsl/tests.rs | 1 + 3 files changed, 6 insertions(+) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index a7eefe51d..8b13c1aee 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -130,6 +130,7 @@ fn consume_token(mut input: &str) -> (Token<'_>, &str) { } '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), '!' => { + input = chars.as_str(); if chars.next() == Some('=') { (Token::LogicalOperation(cur), chars.as_str()) } else { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b096dc6ea..4f3a56fae 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1258,6 +1258,10 @@ impl Parser { kind: crate::ScalarKind::Uint, width: 4, }, + "bool" => crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: 1, + }, "vec2" => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 4fdfc1088..2c0c92853 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -216,5 +216,6 @@ fn parse_expressions() { parse_str("fn foo() { const x: f32 = select(0.0, 1.0, true); const y: vec2 = select(vec2(1.0, 1.0), vec2(x, x), vec2(x < 0.5, x > 0.5)); + const z: bool = !(0.0 == 1.0); }").unwrap(); } From 539db1a317d62c8c50e21ff908cf952c731a05b6 Mon Sep 17 00:00:00 2001 From: Systemcluster Date: Tue, 16 Feb 2021 05:12:23 +0100 Subject: [PATCH 0499/2212] [wgsl] support for statement --- src/front/wgsl/mod.rs | 59 +++++++++++++++++++++++++++++++++++++++++ src/front/wgsl/tests.rs | 11 ++++++++ 2 files changed, 70 insertions(+) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 4f3a56fae..965a1c2a1 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1809,6 +1809,65 @@ impl Parser { Some(crate::Statement::Loop { body, continuing }) } + "for" => { + let mut block = Vec::new(); + + lexer.expect(Token::Paren('('))?; + let initialization = + self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)?; + let condition = self.parse_general_expression(lexer, context.as_expression())?; + lexer.expect(Token::Separator(';'))?; + let mut continuing = None; + // manually parse the next statement here instead of calling parse_statement + // because the statement is not terminated with a semicolon + if let Token::Word(ident) = lexer.peek() { + let _ = lexer.next(); + continuing = Some(match context.lookup_ident.get(ident) { + Some(&var_expr) => { + let left = + self.parse_postfix(lexer, context.as_expression(), var_expr)?; + lexer.expect(Token::Operation('='))?; + let value = + self.parse_general_expression(lexer, context.as_expression())?; + crate::Statement::Store { + pointer: left, + value, + } + } + None => { + let (function, arguments) = self + .parse_local_function_call(lexer, ident, context.as_expression())? + .ok_or(Error::UnknownLocalFunction(ident))?; + crate::Statement::Call { + function, + arguments, + } + } + }); + } + lexer.expect(Token::Paren(')'))?; + lexer.expect(Token::Paren('{'))?; + + block.extend(initialization); + + let mut body = [crate::Statement::If { + condition, + accept: Vec::new(), + reject: [crate::Statement::Break].to_vec(), + }] + .to_vec(); + while !lexer.skip(Token::Paren('}')) { + let s = self.parse_statement(lexer, context.reborrow(), false)?; + body.extend(s); + } + + block.push(crate::Statement::Loop { + body, + continuing: continuing.into_iter().collect(), + }); + + Some(crate::Statement::Block(block)) + } "break" => Some(crate::Statement::Break), "continue" => Some(crate::Statement::Continue), "discard" => Some(crate::Statement::Kill), diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 2c0c92853..9a419f600 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -133,6 +133,17 @@ fn parse_loop() { ", ) .unwrap(); + parse_str( + " + fn main() { + var a: i32 = 0; + for(var i: i32 = 0; i < 4; i = i + 1) { + a = a + 2; + } + } + ", + ) + .unwrap(); } #[test] From 35ba4dac6650373c1da3176292b74afa41999edd Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Feb 2021 23:15:43 -0500 Subject: [PATCH 0500/2212] Fix the ClipDistance validation - expect an array --- src/proc/validator.rs | 44 +++++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index a3e7fd15e..149a4fd6f 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -176,7 +176,7 @@ impl crate::GlobalVariable { // Only validate the type here. Whether or not it's legal to access // this builtin is up to the entry point. let width = 4; - let ty_inner = match built_in { + let expected_ty_inner = match built_in { Bi::BaseInstance | Bi::BaseVertex | Bi::InstanceIndex @@ -184,35 +184,51 @@ impl crate::GlobalVariable { | Bi::SampleIndex | Bi::SampleMaskIn | Bi::SampleMaskOut - | Bi::LocalInvocationIndex => Ti::Scalar { + | Bi::LocalInvocationIndex => Some(Ti::Scalar { kind: Sk::Uint, width, - }, - Bi::ClipDistance | Bi::PointSize | Bi::FragDepth => Ti::Scalar { + }), + Bi::PointSize | Bi::FragDepth => Some(Ti::Scalar { kind: Sk::Float, width, - }, - Bi::Position | Bi::FragCoord => Ti::Vector { + }), + Bi::Position | Bi::FragCoord => Some(Ti::Vector { size: Vs::Quad, kind: Sk::Float, width, - }, - Bi::FrontFacing => Ti::Scalar { + }), + Bi::FrontFacing => Some(Ti::Scalar { kind: Sk::Bool, width: 1, - }, + }), Bi::GlobalInvocationId | Bi::LocalInvocationId | Bi::WorkGroupId - | Bi::WorkGroupSize => Ti::Vector { + | Bi::WorkGroupSize => Some(Ti::Vector { size: Vs::Tri, kind: Sk::Uint, width, - }, + }), + Bi::ClipDistance => None, }; - if types[self.ty].inner != ty_inner { - log::warn!("Wrong builtin type: {:?}", types[self.ty]); - return Err(GlobalVariableError::InvalidBuiltInType(built_in)); + + let ty_inner = &types[self.ty].inner; + if Some(ty_inner) != expected_ty_inner.as_ref() { + match (built_in, &types[self.ty].inner) { + (Bi::ClipDistance, &Ti::Array { base, .. }) => match types[base].inner { + Ti::Scalar { + kind: Sk::Float, .. + } => {} + ref other => { + log::warn!("Wrong array base type: {:?}", other); + return Err(GlobalVariableError::InvalidBuiltInType(built_in)); + } + }, + (_, other) => { + log::warn!("Wrong builtin type: {:?}", other); + return Err(GlobalVariableError::InvalidBuiltInType(built_in)); + } + } } self.forbid_interpolation()? } From e37268e60c264d251f3af0300a117144bccc4d24 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 14 Feb 2021 20:21:37 -0500 Subject: [PATCH 0501/2212] [msl] fix support for private globals --- src/back/msl/writer.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8619b9ccd..17d2751fd 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1333,7 +1333,6 @@ impl Writer { } _ => LocationMode::Uniform, }; - let resolved = options.resolve_binding(stage, var, loc_mode)?; let tyvar = TypedGlobalVariable { module, names: &self.names, @@ -1343,7 +1342,10 @@ impl Writer { let separator = separate(last_used_global == Some(handle)); write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; - resolved.try_fmt_decorated(&mut self.out, separator)?; + if var.binding.is_some() { + let resolved = options.resolve_binding(stage, var, loc_mode)?; + resolved.try_fmt_decorated(&mut self.out, separator)?; + } if let Some(value) = var.init { let value_str = &self.names[&NameKey::Constant(value)]; write!(self.out, " = {}", value_str)?; From 847d127ec86fe70ff9e4f09970bd7b0219318e4c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 15 Feb 2021 21:53:28 -0500 Subject: [PATCH 0502/2212] Optimize Interface with a bitmask to avoid re-visiting expressions --- src/back/msl/writer.rs | 4 ++++ src/front/global_usage.rs | 3 +++ src/proc/call_graph.rs | 17 ++++++++++++++--- src/proc/interface.rs | 12 +++++++----- 4 files changed, 28 insertions(+), 8 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 17d2751fd..f1be29695 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -70,6 +70,7 @@ pub struct Writer { out: W, names: FastHashMap, named_expressions: BitSet, + visit_mask: BitSet, typifier: Typifier, namer: Namer, temp_bake_handles: Vec>, @@ -177,6 +178,7 @@ impl Writer { out, names: FastHashMap::default(), named_expressions: BitSet::new(), + visit_mask: BitSet::new(), typifier: Typifier::new(), namer: Namer::default(), temp_bake_handles: Vec::new(), @@ -709,6 +711,7 @@ impl Writer { exclude_root: bool, ) -> Result<(), Error> { // set up the search + self.visit_mask.clear(); let mut interface = Interface { expressions: &context.expression.function.expressions, local_variables: &context.expression.function.local_variables, @@ -722,6 +725,7 @@ impl Writer { None }, }, + mask: &mut self.visit_mask, }; // populate the bake handles interface.traverse_expr(root_handle); diff --git a/src/front/global_usage.rs b/src/front/global_usage.rs index e5a43509c..99fe7fa73 100644 --- a/src/front/global_usage.rs +++ b/src/front/global_usage.rs @@ -2,6 +2,7 @@ use crate::{ arena::{Arena, Handle}, proc::{Interface, Visitor}, }; +use bit_set::BitSet; struct GlobalUseVisitor<'a> { usage: &'a mut [crate::GlobalUse], @@ -30,6 +31,7 @@ impl Visitor for GlobalUseVisitor<'_> { impl crate::Function { pub fn fill_global_use(&mut self, globals_num: usize, functions: &Arena) { + let mut mask = BitSet::with_capacity(self.expressions.len()); self.global_usage.clear(); self.global_usage .resize(globals_num, crate::GlobalUse::empty()); @@ -41,6 +43,7 @@ impl crate::Function { usage: &mut self.global_usage, functions, }, + mask: &mut mask, }; io.traverse(&self.body); } diff --git a/src/proc/call_graph.rs b/src/proc/call_graph.rs index 1c580d5c1..9c604bfe9 100644 --- a/src/proc/call_graph.rs +++ b/src/proc/call_graph.rs @@ -3,6 +3,7 @@ use crate::{ proc::{Interface, Visitor}, Function, }; +use bit_set::BitSet; use petgraph::{ graph::{DefaultIx, NodeIndex}, Graph, @@ -18,6 +19,7 @@ impl<'a> CallGraphBuilder<'a> { pub fn process(&self, func: &Function) -> CallGraph { let mut graph = Graph::new(); let mut children = Vec::new(); + let mut mask = BitSet::with_capacity(func.expressions.len()); let visitor = CallGraphVisitor { children: &mut children, @@ -27,29 +29,38 @@ impl<'a> CallGraphBuilder<'a> { expressions: &func.expressions, local_variables: &func.local_variables, visitor, + mask: &mut mask, }; interface.traverse(&func.body); for handle in children { let id = graph.add_node(handle); - self.collect(handle, id, &mut graph); + self.collect(handle, id, &mut graph, &mut mask); } graph } - fn collect(&self, handle: Handle, id: NodeIndex, graph: &mut CallGraph) { + fn collect( + &self, + handle: Handle, + id: NodeIndex, + graph: &mut CallGraph, + mask: &mut BitSet, + ) { let mut children = Vec::new(); let visitor = CallGraphVisitor { children: &mut children, }; let func = &self.functions[handle]; + mask.clear(); let mut interface = Interface { expressions: &func.expressions, local_variables: &func.local_variables, visitor, + mask, }; interface.traverse(&func.body); @@ -58,7 +69,7 @@ impl<'a> CallGraphBuilder<'a> { let child_id = graph.add_node(handle); graph.add_edge(id, child_id, ()); - self.collect(handle, child_id, graph); + self.collect(handle, child_id, graph, mask); } } } diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 051d42e1b..fd7436251 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -1,9 +1,11 @@ use crate::arena::{Arena, Handle}; +use bit_set::BitSet; pub struct Interface<'a, T> { + pub visitor: T, pub expressions: &'a Arena, pub local_variables: &'a Arena, - pub visitor: T, + pub mask: &'a mut BitSet, } pub trait Visitor { @@ -12,13 +14,13 @@ pub trait Visitor { fn visit_fun(&mut self, _: Handle) {} } -impl<'a, T> Interface<'a, T> -where - T: Visitor, -{ +impl<'a, T: Visitor> Interface<'a, T> { pub fn traverse_expr(&mut self, handle: Handle) { use crate::Expression as E; + if !self.mask.insert(handle.index()) { + return; + } let expr = &self.expressions[handle]; self.visitor.visit_expr(handle, expr); From 321420c019aea76e3c51a5829513e07ed0e5509a Mon Sep 17 00:00:00 2001 From: Systemcluster Date: Tue, 16 Feb 2021 03:21:54 +0100 Subject: [PATCH 0503/2212] Set default SPIR-V version in convert example --- examples/convert.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/convert.rs b/examples/convert.rs index 008279e5d..3d1671740 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -74,6 +74,7 @@ fn main() { let mut param = Parameters::default(); // very useful to have this by default param.spv_capabilities.insert(spirv::Capability::Shader); + param.spv_version = (1, 0); param } }; From 59479f137d7316b9b49d77e8e628b1e73b2a5814 Mon Sep 17 00:00:00 2001 From: Systemcluster Date: Mon, 15 Feb 2021 23:34:59 +0100 Subject: [PATCH 0504/2212] [wgsl] support nested type parameters --- src/front/wgsl/lexer.rs | 34 ++++++++++++++++++++++++++++------ src/front/wgsl/mod.rs | 8 ++++---- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 8b13c1aee..323c928a9 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -57,7 +57,7 @@ fn consume_number(input: &str) -> (Token, &str) { } } -fn consume_token(mut input: &str) -> (Token<'_>, &str) { +fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { let mut chars = input.chars(); let cur = match chars.next() { Some(c) => c, @@ -84,9 +84,9 @@ fn consume_token(mut input: &str) -> (Token<'_>, &str) { '<' | '>' => { input = chars.as_str(); let next = chars.next(); - if next == Some('=') { + if next == Some('=') && !generic { (Token::LogicalOperation(cur), chars.as_str()) - } else if next == Some(cur) { + } else if next == Some(cur) && !generic { (Token::ShiftOperation(cur), chars.as_str()) } else { (Token::Paren(cur), input) @@ -174,7 +174,20 @@ impl<'a> Lexer<'a> { pub(super) fn next(&mut self) -> Token<'a> { let original_len = self.input.len(); loop { - let (token, rest) = consume_token(self.input); + let (token, rest) = consume_token(self.input, false); + self.input = rest; + if token != Token::Trivia { + let _bytes_read = original_len - self.input.len(); + return token; + } + } + } + + #[must_use] + pub(super) fn next_generic(&mut self) -> Token<'a> { + let original_len = self.input.len(); + loop { + let (token, rest) = consume_token(self.input, true); self.input = rest; if token != Token::Trivia { let _bytes_read = original_len - self.input.len(); @@ -215,6 +228,15 @@ impl<'a> Lexer<'a> { } } + pub(super) fn expect_generic_paren(&mut self, expected: char) -> Result<(), Error<'a>> { + let token = self.next_generic(); + if token == Token::Paren(expected) { + Ok(()) + } else { + Err(Error::Unexpected(token, "paren")) + } + } + pub(super) fn skip(&mut self, what: Token<'_>) -> bool { let (peeked_token, rest) = self.peek_token_and_rest(); if peeked_token == what { @@ -260,10 +282,10 @@ impl<'a> Lexer<'a> { pub(super) fn next_scalar_generic( &mut self, ) -> Result<(crate::ScalarKind, crate::Bytes), Error<'a>> { - self.expect(Token::Paren('<'))?; + self.expect_generic_paren('<')?; let word = self.next_ident()?; let pair = conv::get_scalar_type(word).ok_or(Error::UnknownScalarType(word))?; - self.expect(Token::Paren('>'))?; + self.expect_generic_paren('>')?; Ok(pair) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 965a1c2a1..120d49e8d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1359,15 +1359,15 @@ impl Parser { } } "ptr" => { - lexer.expect(Token::Paren('<'))?; + lexer.expect_generic_paren('<')?; let class = conv::map_storage_class(lexer.next_ident()?)?; lexer.expect(Token::Separator(','))?; let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; - lexer.expect(Token::Paren('>'))?; + lexer.expect_generic_paren('>')?; crate::TypeInner::Pointer { base, class } } "array" => { - lexer.expect(Token::Paren('<'))?; + lexer.expect_generic_paren('<')?; let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let size = if lexer.skip(Token::Separator(',')) { let const_handle = @@ -1376,7 +1376,7 @@ impl Parser { } else { crate::ArraySize::Dynamic }; - lexer.expect(Token::Paren('>'))?; + lexer.expect_generic_paren('>')?; crate::TypeInner::Array { base, From dea3e0e1e1f2f5ccfef59f06d3fff58b226f9b78 Mon Sep 17 00:00:00 2001 From: Systemcluster Date: Wed, 17 Feb 2021 14:49:15 +0100 Subject: [PATCH 0505/2212] Add MIT license --- LICENSE-MIT | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LICENSE-MIT diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 000000000..58acb754a --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,19 @@ +Copyright (c) [yyyy] [name of copyright owner] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 1861fca4baae1d4c801fa6fe2461b198978d43ff Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Thu, 11 Feb 2021 19:43:37 +0000 Subject: [PATCH 0506/2212] [glsl-in] Support multiple entrypoints --- examples/convert.rs | 9 +- src/front/glsl/ast.rs | 12 +- src/front/glsl/functions.rs | 28 +++- src/front/glsl/mod.rs | 7 +- src/front/glsl/parser.rs | 18 +-- src/front/glsl/parser_tests.rs | 2 +- src/front/glsl/variables.rs | 27 +--- tests/in/quad-glsl.glsl | 28 ++++ tests/in/quad-glsl.param.ron | 8 + tests/out/quad-glsl.ron.snap | 258 ++++++++++++++++++++++++++++++++ tests/out/quad-glsl.spvasm.snap | 63 ++++++++ tests/parse.rs | 6 +- tests/snapshots.rs | 42 ++++++ 13 files changed, 452 insertions(+), 56 deletions(-) create mode 100644 tests/in/quad-glsl.glsl create mode 100644 tests/in/quad-glsl.param.ron create mode 100644 tests/out/quad-glsl.ron.snap create mode 100644 tests/out/quad-glsl.spvasm.snap diff --git a/examples/convert.rs b/examples/convert.rs index 3d1671740..5f6be4d85 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -107,8 +107,7 @@ fn main() { let input = fs::read_to_string(&args[1]).unwrap(); naga::front::glsl::parse_str( &input, - "main", - naga::ShaderStage::Vertex, + vec![("main".to_string(), naga::ShaderStage::Vertex)], Default::default(), ) .unwrap_pretty() @@ -118,8 +117,7 @@ fn main() { let input = fs::read_to_string(&args[1]).unwrap(); naga::front::glsl::parse_str( &input, - "main", - naga::ShaderStage::Fragment, + vec![("main".to_string(), naga::ShaderStage::Fragment)], Default::default(), ) .unwrap_pretty() @@ -129,8 +127,7 @@ fn main() { let input = fs::read_to_string(&args[1]).unwrap(); naga::front::glsl::parse_str( &input, - "main", - naga::ShaderStage::Compute, + vec![("main".to_string(), naga::ShaderStage::Compute)], Default::default(), ) .unwrap_pretty() diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 0d5ba6b7f..7c8987834 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -10,8 +10,7 @@ use crate::{ pub struct Program { pub version: u16, pub profile: Profile, - pub shader_stage: ShaderStage, - pub entry: Option, + pub entry_points: Vec<(String, ShaderStage)>, pub lookup_function: FastHashMap>, pub lookup_type: FastHashMap>, pub lookup_global_variables: FastHashMap>, @@ -21,12 +20,11 @@ pub struct Program { } impl Program { - pub fn new(shader_stage: ShaderStage, entry: &str) -> Program { + pub fn new(entry_points: Vec<(String, ShaderStage)>) -> Program { Program { version: 0, profile: Profile::Core, - shader_stage, - entry: Some(entry.to_string()), + entry_points, lookup_function: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_global_variables: FastHashMap::default(), @@ -44,6 +42,10 @@ impl Program { } } + pub fn has_stage(&self, stage: ShaderStage) -> bool { + self.entry_points.iter().any(|(_, s)| *s == stage) + } + pub fn binary_expr( &mut self, op: BinaryOperator, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 78c0614c3..81cf4554c 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,7 +1,7 @@ use crate::{ proc::{ensure_block_returns, Typifier}, - BinaryOperator, Block, Expression, Function, MathFunction, RelationalFunction, SampleLevel, - TypeInner, + BinaryOperator, Block, EntryPoint, Expression, Function, MathFunction, RelationalFunction, + SampleLevel, TypeInner, }; use super::{ast::*, error::ErrorKind}; @@ -281,4 +281,28 @@ impl Program { f.fill_global_use(self.module.global_variables.len(), &self.module.functions); f } + + pub fn declare_function(&mut self, f: Function) { + let stage = if let Some(ref name) = f.name { + self.entry_points + .iter() + .find_map(|(n, s)| if *name == *n { Some(*s) } else { None }) + } else { + None + }; + let name = f.name.clone().unwrap(); + if let Some(stage) = stage { + self.module.entry_points.insert( + (stage, name), + EntryPoint { + early_depth_test: None, + workgroup_size: [0; 3], //TODO + function: f, + }, + ); + } else { + let handle = self.module.functions.append(f); + self.lookup_function.insert(name, handle); + } + } } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 7d3faf3e8..088c39926 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -25,17 +25,14 @@ mod variables; pub fn parse_str( source: &str, - entry: &str, - stage: ShaderStage, + entry_points: Vec<(String, ShaderStage)>, defines: FastHashMap, ) -> Result { - let mut program = Program::new(stage, entry); + let mut program = Program::new(entry_points); let mut lex = Lexer::new(source); lex.pp.defines = defines; - let mut parser = parser::Parser::new(&mut program); - for token in lex { parser.parse(token)?; } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0e1748311..2e448d786 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -6,7 +6,7 @@ pomelo! { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{ Arena, BinaryOperator, Binding, Block, Constant, - ConstantInner, EntryPoint, Expression, + ConstantInner, Expression, Function, GlobalVariable, Handle, Interpolation, LocalVariable, ScalarValue, ScalarKind, Statement, StorageAccess, StorageClass, StructMember, @@ -1063,21 +1063,7 @@ pomelo! { translation_unit ::= translation_unit external_declaration; external_declaration ::= function_definition(f) { - if f.name == extra.entry { - let name = extra.entry.take().unwrap(); - extra.module.entry_points.insert( - (extra.shader_stage, name), - EntryPoint { - early_depth_test: None, - workgroup_size: [0; 3], //TODO - function: f, - }, - ); - } else { - let name = f.name.clone().unwrap(); - let handle = extra.module.functions.append(f); - extra.lookup_function.insert(name, handle); - } + extra.declare_function(f) } external_declaration ::= declaration(d) { if let Some(d) = d { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 1e0a8e719..3f265039a 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -5,7 +5,7 @@ use super::parser; use crate::ShaderStage; fn parse_program(source: &str, stage: ShaderStage) -> Result { - let mut program = Program::new(stage, ""); + let mut program = Program::new(vec![("".to_string(), stage)]); let lex = Lexer::new(source); let mut parser = parser::Parser::new(&mut program); diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 78b522ec5..f41b877e8 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -21,19 +21,12 @@ impl Program { match name { "gl_Position" => { #[cfg(feature = "glsl-validate")] - match self.shader_stage { - ShaderStage::Vertex | ShaderStage::Fragment { .. } => {} - _ => { - return Err(ErrorKind::VariableNotAvailable(name.into())); - } + if !self.has_stage(ShaderStage::Vertex) { + return Err(ErrorKind::VariableNotAvailable(name.into())); }; let h = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), - class: if self.shader_stage == ShaderStage::Vertex { - StorageClass::Output - } else { - StorageClass::Input - }, + class: StorageClass::Output, binding: Some(Binding::BuiltIn(BuiltIn::Position)), ty: self.module.types.fetch_or_append(Type { name: None, @@ -58,11 +51,8 @@ impl Program { } "gl_VertexIndex" => { #[cfg(feature = "glsl-validate")] - match self.shader_stage { - ShaderStage::Vertex => {} - _ => { - return Err(ErrorKind::VariableNotAvailable(name.into())); - } + if !self.has_stage(ShaderStage::Vertex) { + return Err(ErrorKind::VariableNotAvailable(name.into())); }; let h = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), @@ -97,11 +87,8 @@ impl Program { } "gl_InstanceIndex" => { #[cfg(feature = "glsl-validate")] - match self.shader_stage { - ShaderStage::Vertex => {} - _ => { - return Err(ErrorKind::VariableNotAvailable(name.into())); - } + if !self.has_stage(ShaderStage::Vertex) { + return Err(ErrorKind::VariableNotAvailable(name.into())); }; let h = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), diff --git a/tests/in/quad-glsl.glsl b/tests/in/quad-glsl.glsl new file mode 100644 index 000000000..b8d653206 --- /dev/null +++ b/tests/in/quad-glsl.glsl @@ -0,0 +1,28 @@ +#version 450 +// vertex +const float c_scale = 1.2; + +layout(location = 0) in vec2 a_pos; +layout(location = 1) in vec2 a_uv; +layout(location = 0) out vec2 v_uv; + +void vert_main() { + v_uv = a_uv; + gl_Position = vec4(c_scale * a_pos, 0.0, 1.0); +} + +// fragment +layout(location = 0) in vec2 v_uv; +#ifdef TEXTURE +layout(set = 0, binding = 0) uniform texture2D u_texture; +layout(set = 0, binding = 1) uniform sampler u_sampler; +#endif +layout(location = 0) out vec4 o_color; + +void frag_main() { +#ifdef TEXTURE + o_color = texture(sampler2D(u_texture, u_sampler), v_uv); +#else + o_color = vec4(1.0, 1.0, 1.0, 1.0); +#endif +} diff --git a/tests/in/quad-glsl.param.ron b/tests/in/quad-glsl.param.ron new file mode 100644 index 000000000..74dd08590 --- /dev/null +++ b/tests/in/quad-glsl.param.ron @@ -0,0 +1,8 @@ +( + spv_version: (1, 0), + spv_capabilities: [ Shader ], + mtl_bindings: { + (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), + (stage: Fragment, group: 0, binding: 1): (sampler: Some(0)), + } +) diff --git a/tests/out/quad-glsl.ron.snap b/tests/out/quad-glsl.ron.snap new file mode 100644 index 000000000..793c65df7 --- /dev/null +++ b/tests/out/quad-glsl.ron.snap @@ -0,0 +1,258 @@ +--- +source: tests/snapshots.rs +expression: output +--- +( + types: [ + ( + name: None, + inner: Scalar( + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Bi, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Quad, + kind: Float, + width: 4, + ), + ), + ], + constants: [ + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(1.2000000476837158), + ), + ), + ( + name: Some("c_scale"), + specialization: None, + inner: Scalar( + width: 4, + value: Float(1.2000000476837158), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(1), + ), + ), + ], + global_variables: [ + ( + name: Some("a_pos"), + class: Input, + binding: Some(Location(0)), + ty: 2, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("a_uv"), + class: Input, + binding: Some(Location(1)), + ty: 2, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("v_uv"), + class: Output, + binding: Some(Location(0)), + ty: 2, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("gl_Position"), + class: Output, + binding: Some(BuiltIn(Position)), + ty: 3, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("v_uv"), + class: Input, + binding: Some(Location(0)), + ty: 2, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("o_color"), + class: Output, + binding: Some(Location(0)), + ty: 3, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ], + functions: [], + entry_points: { + (Fragment, "frag_main"): ( + early_depth_test: None, + workgroup_size: (0, 0, 0), + function: ( + name: Some("frag_main"), + arguments: [], + return_type: None, + global_usage: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 2, + ), + ], + local_variables: [], + expressions: [ + GlobalVariable(1), + GlobalVariable(2), + GlobalVariable(3), + GlobalVariable(4), + GlobalVariable(5), + GlobalVariable(6), + Constant(2), + Constant(4), + Constant(4), + Constant(4), + Constant(4), + Compose( + ty: 3, + components: [ + 8, + 9, + 10, + 11, + ], + ), + ], + body: [ + Store( + pointer: 6, + value: 12, + ), + Return( + value: None, + ), + ], + ), + ), + (Vertex, "vert_main"): ( + early_depth_test: None, + workgroup_size: (0, 0, 0), + function: ( + name: Some("vert_main"), + arguments: [], + return_type: None, + global_usage: [ + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 2, + ), + ( + bits: 2, + ), + ], + local_variables: [], + expressions: [ + Constant(1), + Constant(2), + GlobalVariable(1), + GlobalVariable(2), + GlobalVariable(3), + Constant(2), + GlobalVariable(4), + Binary( + op: Multiply, + left: 6, + right: 3, + ), + Constant(3), + Constant(4), + Compose( + ty: 3, + components: [ + 8, + 9, + 10, + ], + ), + ], + body: [ + Store( + pointer: 5, + value: 4, + ), + Store( + pointer: 7, + value: 11, + ), + Return( + value: None, + ), + ], + ), + ), + }, +) diff --git a/tests/out/quad-glsl.spvasm.snap b/tests/out/quad-glsl.spvasm.snap new file mode 100644 index 000000000..1c68ac044 --- /dev/null +++ b/tests/out/quad-glsl.spvasm.snap @@ -0,0 +1,63 @@ +--- +source: tests/snapshots.rs +expression: dis +--- +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 28 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %8 "frag_main" %12 +OpEntryPoint Vertex %15 "vert_main" %25 %20 %18 %23 +OpExecutionMode %8 OriginUpperLeft +OpSource GLSL 450 +OpName %5 "c_scale" +OpName %8 "frag_main" +OpName %12 "o_color" +OpName %8 "frag_main" +OpName %15 "vert_main" +OpName %18 "v_uv" +OpName %20 "a_uv" +OpName %23 "gl_Position" +OpName %25 "a_pos" +OpName %15 "vert_main" +OpDecorate %12 Location 0 +OpDecorate %18 Location 0 +OpDecorate %20 Location 1 +OpDecorate %23 BuiltIn Position +OpDecorate %25 Location 0 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.2 +%5 = OpConstant %4 1.2 +%6 = OpConstant %4 0.0 +%7 = OpConstant %4 1.0 +%9 = OpTypeFunction %2 +%11 = OpTypeVector %4 4 +%13 = OpTypePointer Output %11 +%12 = OpVariable %13 Output +%17 = OpTypeVector %4 2 +%19 = OpTypePointer Output %17 +%18 = OpVariable %19 Output +%21 = OpTypePointer Input %17 +%20 = OpVariable %21 Input +%23 = OpVariable %13 Output +%25 = OpVariable %21 Input +%8 = OpFunction %2 None %9 +%10 = OpLabel +%14 = OpCompositeConstruct %11 %7 %7 %7 %7 +OpStore %12 %14 +OpReturn +OpFunctionEnd +%15 = OpFunction %2 None %9 +%16 = OpLabel +%22 = OpLoad %17 %20 +OpStore %18 %22 +%26 = OpLoad %17 %25 +%24 = OpVectorTimesScalar %17 %26 %5 +%27 = OpCompositeConstruct %11 %24 %6 %7 +OpStore %23 %27 +OpReturn +OpFunctionEnd diff --git a/tests/parse.rs b/tests/parse.rs index e9d0cdf9b..49ca56f04 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -14,7 +14,11 @@ fn check_glsl(name: &str) { panic!("Unknown extension in {:?}", name) }; - match naga::front::glsl::parse_str(&input, "main", stage, Default::default()) { + match naga::front::glsl::parse_str( + &input, + vec![("main".to_string(), stage)], + Default::default(), + ) { Ok(m) => match naga::proc::Validator::new().validate(&m) { Ok(_analysis) => (), Err(e) => panic!("Unable to validate {}: {:?}", name, e), diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 29579025c..a27cb3a86 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -247,3 +247,45 @@ fn convert_spv(name: &str) { fn convert_spv_shadow() { convert_spv("shadow"); } + +#[cfg(feature = "glsl-in")] +fn convert_glsl(name: &str, entry_points: Vec<(String, naga::ShaderStage)>) { + let params = match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { + Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), + Err(_) => Parameters::default(), + }; + + let module = naga::front::glsl::parse_str( + &std::fs::read_to_string(format!("tests/in/{}{}", name, ".glsl")) + .expect("Couldn't find glsl file"), + entry_points, + Default::default(), + ) + .unwrap(); + naga::proc::Validator::new().validate(&module).unwrap(); + + #[cfg(feature = "spv-out")] + { + check_output_spv(&module, name, ¶ms); + } + #[cfg(feature = "serialize")] + { + let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); + let output = ron::ser::to_string_pretty(&module, config).unwrap(); + with_snapshot_settings(|| { + insta::assert_snapshot!(format!("{}.ron", name), output); + }); + } +} + +#[cfg(feature = "glsl-in")] +#[test] +fn convert_glsl_quad() { + convert_glsl( + "quad-glsl", + vec![ + ("vert_main".to_string(), naga::ShaderStage::Vertex), + ("frag_main".to_string(), naga::ShaderStage::Fragment), + ], + ); +} From 408002815fbb9701be78b934978a4dc62c8b0a77 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 17 Feb 2021 11:23:36 +0000 Subject: [PATCH 0507/2212] [glsl-in] Multi entry points - address comments --- examples/convert.rs | 24 +++++++++--- src/front/glsl/ast.rs | 12 ++---- src/front/glsl/error.rs | 6 --- src/front/glsl/functions.rs | 21 ++++++----- src/front/glsl/lex.rs | 7 ++-- src/front/glsl/lex_tests.rs | 19 ++++++---- src/front/glsl/mod.rs | 16 ++++---- src/front/glsl/parser.rs | 6 +-- src/front/glsl/parser_tests.rs | 60 +++++++++++++++++++----------- src/front/glsl/preprocess.rs | 6 +-- src/front/glsl/preprocess_tests.rs | 14 ++++++- src/front/glsl/variables.rs | 18 ++------- tests/in/quad-glsl.param.ron | 5 +-- tests/parse.rs | 8 +++- tests/snapshots.rs | 19 +++++----- 15 files changed, 132 insertions(+), 109 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 5f6be4d85..9562a1fb8 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -105,30 +105,42 @@ fn main() { #[cfg(feature = "glsl-in")] "vert" => { let input = fs::read_to_string(&args[1]).unwrap(); + let mut entry_points = naga::FastHashMap::default(); + entry_points.insert("main".to_string(), naga::ShaderStage::Vertex); naga::front::glsl::parse_str( &input, - vec![("main".to_string(), naga::ShaderStage::Vertex)], - Default::default(), + &naga::front::glsl::Options { + entry_points, + defines: Default::default(), + }, ) .unwrap_pretty() } #[cfg(feature = "glsl-in")] "frag" => { let input = fs::read_to_string(&args[1]).unwrap(); + let mut entry_points = naga::FastHashMap::default(); + entry_points.insert("main".to_string(), naga::ShaderStage::Fragment); naga::front::glsl::parse_str( &input, - vec![("main".to_string(), naga::ShaderStage::Fragment)], - Default::default(), + &naga::front::glsl::Options { + entry_points, + defines: Default::default(), + }, ) .unwrap_pretty() } #[cfg(feature = "glsl-in")] "comp" => { let input = fs::read_to_string(&args[1]).unwrap(); + let mut entry_points = naga::FastHashMap::default(); + entry_points.insert("main".to_string(), naga::ShaderStage::Compute); naga::front::glsl::parse_str( &input, - vec![("main".to_string(), naga::ShaderStage::Compute)], - Default::default(), + &naga::front::glsl::Options { + entry_points, + defines: Default::default(), + }, ) .unwrap_pretty() } diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 7c8987834..8ca658eb1 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -7,10 +7,10 @@ use crate::{ }; #[derive(Debug)] -pub struct Program { +pub struct Program<'a> { pub version: u16, pub profile: Profile, - pub entry_points: Vec<(String, ShaderStage)>, + pub entry_points: &'a FastHashMap, pub lookup_function: FastHashMap>, pub lookup_type: FastHashMap>, pub lookup_global_variables: FastHashMap>, @@ -19,8 +19,8 @@ pub struct Program { pub module: Module, } -impl Program { - pub fn new(entry_points: Vec<(String, ShaderStage)>) -> Program { +impl<'a> Program<'a> { + pub fn new(entry_points: &'a FastHashMap) -> Program<'a> { Program { version: 0, profile: Profile::Core, @@ -42,10 +42,6 @@ impl Program { } } - pub fn has_stage(&self, stage: ShaderStage) -> bool { - self.entry_points.iter().any(|(_, s)| *s == stage) - } - pub fn binary_expr( &mut self, op: BinaryOperator, diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 2a8537086..771c99db1 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -17,8 +17,6 @@ pub enum ErrorKind { UnknownField(TokenMetadata, String), #[cfg(feature = "glsl-validate")] VariableAlreadyDeclared(String), - #[cfg(feature = "glsl-validate")] - VariableNotAvailable(String), ExpectedConstant, SemanticError(Cow<'static, str>), PreprocessorError(String), @@ -49,10 +47,6 @@ impl fmt::Display for ErrorKind { ErrorKind::VariableAlreadyDeclared(val) => { write!(f, "Variable {} already declared in current scope", val) } - #[cfg(feature = "glsl-validate")] - ErrorKind::VariableNotAvailable(val) => { - write!(f, "Variable {} not available in this stage", val) - } ErrorKind::ExpectedConstant => write!(f, "Expected constant"), ErrorKind::SemanticError(msg) => write!(f, "Semantic error: {}", msg), ErrorKind::PreprocessorError(val) => write!(f, "Preprocessor error: {}", val), diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 81cf4554c..38249d7a6 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -6,7 +6,7 @@ use crate::{ use super::{ast::*, error::ErrorKind}; -impl Program { +impl Program<'_> { pub fn function_call(&mut self, fc: FunctionCall) -> Result { match fc.kind { FunctionCallKind::TypeConstructor(ty) => { @@ -282,15 +282,15 @@ impl Program { f } - pub fn declare_function(&mut self, f: Function) { - let stage = if let Some(ref name) = f.name { - self.entry_points - .iter() - .find_map(|(n, s)| if *name == *n { Some(*s) } else { None }) - } else { - None - }; - let name = f.name.clone().unwrap(); + pub fn declare_function(&mut self, f: Function) -> Result<(), ErrorKind> { + let name = f + .name + .clone() + .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; + let stage = self + .entry_points + .iter() + .find_map(|(n, s)| if *name == *n { Some(*s) } else { None }); if let Some(stage) = stage { self.module.entry_points.insert( (stage, name), @@ -304,5 +304,6 @@ impl Program { let handle = self.module.functions.append(f); self.lookup_function.insert(name, handle); } + Ok(()) } } diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index d3bb1645b..d0638c3f4 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -1,5 +1,6 @@ use super::parser::Token; use super::{preprocess::LinePreProcessor, token::TokenMetadata, types::parse_type}; +use crate::FastHashMap; use std::{iter::Enumerate, str::Lines}; fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { @@ -23,7 +24,7 @@ pub struct Lexer<'a> { line: usize, offset: usize, inside_comment: bool, - pub pp: LinePreProcessor, + pp: LinePreProcessor, } impl<'a> Lexer<'a> { @@ -324,14 +325,14 @@ impl<'a> Lexer<'a> { } } - pub fn new(input: &'a str) -> Self { + pub fn new(input: &'a str, defines: &FastHashMap) -> Self { let mut lexer = Lexer { lines: input.lines().enumerate(), input: "".to_string(), line: 0, offset: 0, inside_comment: false, - pp: LinePreProcessor::new(), + pp: LinePreProcessor::new(defines), }; lexer.next_line(); lexer diff --git a/src/front/glsl/lex_tests.rs b/src/front/glsl/lex_tests.rs index 7a4e15f52..b2bde5fed 100644 --- a/src/front/glsl/lex_tests.rs +++ b/src/front/glsl/lex_tests.rs @@ -2,8 +2,10 @@ use super::{lex::Lexer, parser::Token::*, token::TokenMetadata}; #[test] fn tokens() { + let defines = crate::FastHashMap::default(); + // line comments - let mut lex = Lexer::new("void main // myfunction\n//()\n{}"); + let mut lex = Lexer::new("void main // myfunction\n//()\n{}", &defines); assert_eq!( lex.next().unwrap(), Void(TokenMetadata { @@ -38,7 +40,7 @@ fn tokens() { assert_eq!(lex.next(), None); // multi line comment - let mut lex = Lexer::new("void main /* comment [] {}\n/**\n{}*/{}"); + let mut lex = Lexer::new("void main /* comment [] {}\n/**\n{}*/{}", &defines); assert_eq!( lex.next().unwrap(), Void(TokenMetadata { @@ -73,7 +75,7 @@ fn tokens() { assert_eq!(lex.next(), None); // identifiers - let mut lex = Lexer::new("id123_OK 92No æNoø No¾ No好"); + let mut lex = Lexer::new("id123_OK 92No æNoø No¾ No好", &defines); assert_eq!( lex.next().unwrap(), Identifier(( @@ -177,7 +179,7 @@ fn tokens() { assert_eq!(lex.next(), None); // version - let mut lex = Lexer::new("#version 890 core"); + let mut lex = Lexer::new("#version 890 core", &defines); assert_eq!( lex.next().unwrap(), Version(TokenMetadata { @@ -208,7 +210,10 @@ fn tokens() { assert_eq!(lex.next(), None); // operators - let mut lex = Lexer::new("+ - * | & % / += -= *= |= &= %= /= ++ -- || && ^^"); + let mut lex = Lexer::new( + "+ - * | & % / += -= *= |= &= %= /= ++ -- || && ^^", + &defines, + ); assert_eq!( lex.next().unwrap(), Plus(TokenMetadata { @@ -345,7 +350,7 @@ fn tokens() { assert_eq!(lex.next(), None); // float constants - let mut lex = Lexer::new("120.0 130.0lf 140.0Lf 150.0LF"); + let mut lex = Lexer::new("120.0 130.0lf 140.0Lf 150.0LF", &defines); assert_eq!( lex.next().unwrap(), FloatConstant(( @@ -389,7 +394,7 @@ fn tokens() { assert_eq!(lex.next(), None); // Integer constants - let mut lex = Lexer::new("120 130u 140U 150 0x1f 0xf2U 0xF1u"); + let mut lex = Lexer::new("120 130u 140U 150 0x1f 0xf2U 0xF1u", &defines); assert_eq!( lex.next().unwrap(), IntConstant(( diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 088c39926..92365f59d 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -23,15 +23,15 @@ mod token; mod types; mod variables; -pub fn parse_str( - source: &str, - entry_points: Vec<(String, ShaderStage)>, - defines: FastHashMap, -) -> Result { - let mut program = Program::new(entry_points); +pub struct Options { + pub entry_points: FastHashMap, + pub defines: FastHashMap, +} - let mut lex = Lexer::new(source); - lex.pp.defines = defines; +pub fn parse_str(source: &str, options: &Options) -> Result { + let mut program = Program::new(&options.entry_points); + + let lex = Lexer::new(source, &options.defines); let mut parser = parser::Parser::new(&mut program); for token in lex { parser.parse(token)?; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2e448d786..d7d710fe5 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -14,8 +14,8 @@ pomelo! { }; } %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; - %parser pub struct Parser<'a> {}; - %extra_argument &'a mut Program; + %parser pub struct Parser<'a, 'b> {}; + %extra_argument &'a mut Program<'b>; %extra_token TokenMetadata; %error ErrorKind; %syntax_error { @@ -1063,7 +1063,7 @@ pomelo! { translation_unit ::= translation_unit external_declaration; external_declaration ::= function_definition(f) { - extra.declare_function(f) + extra.declare_function(f)? } external_declaration ::= declaration(d) { if let Some(d) = d { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 3f265039a..2fb3357de 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -4,9 +4,13 @@ use super::lex::Lexer; use super::parser; use crate::ShaderStage; -fn parse_program(source: &str, stage: ShaderStage) -> Result { - let mut program = Program::new(vec![("".to_string(), stage)]); - let lex = Lexer::new(source); +fn parse_program<'a>( + source: &str, + entry_points: &'a crate::FastHashMap, +) -> Result, ErrorKind> { + let mut program = Program::new(entry_points); + let defines = crate::FastHashMap::default(); + let lex = Lexer::new(source, &defines); let mut parser = parser::Parser::new(&mut program); for token in lex { @@ -18,11 +22,13 @@ fn parse_program(source: &str, stage: ShaderStage) -> Result #[test] fn version() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Vertex); // invalid versions assert_eq!( format!( "{:?}", - parse_program("#version 99000", ShaderStage::Vertex) + parse_program("#version 99000", &entry_points) .err() .unwrap() ), @@ -32,9 +38,7 @@ fn version() { assert_eq!( format!( "{:?}", - parse_program("#version 449", ShaderStage::Vertex) - .err() - .unwrap() + parse_program("#version 449", &entry_points).err().unwrap() ), "InvalidVersion(TokenMetadata { line: 0, chars: 9..12 }, 449)" ); @@ -42,7 +46,7 @@ fn version() { assert_eq!( format!( "{:?}", - parse_program("#version 450 smart", ShaderStage::Vertex) + parse_program("#version 450 smart", &entry_points) .err() .unwrap() ), @@ -52,7 +56,7 @@ fn version() { assert_eq!( format!( "{:?}", - parse_program("#version 450\nvoid f(){} #version 450", ShaderStage::Vertex) + parse_program("#version 450\nvoid f(){} #version 450", &entry_points) .err() .unwrap() ), @@ -60,19 +64,19 @@ fn version() { ); // valid versions - let program = parse_program(" # version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); + let program = parse_program(" # version 450\nvoid main() {}", &entry_points).unwrap(); assert_eq!( format!("{:?}", (program.version, program.profile)), "(450, Core)" ); - let program = parse_program("#version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); + let program = parse_program("#version 450\nvoid main() {}", &entry_points).unwrap(); assert_eq!( format!("{:?}", (program.version, program.profile)), "(450, Core)" ); - let program = parse_program("#version 450 core\nvoid main() {}", ShaderStage::Vertex).unwrap(); + let program = parse_program("#version 450 core\nvoid main() {}", &entry_points).unwrap(); assert_eq!( format!("{:?}", (program.version, program.profile)), "(450, Core)" @@ -81,6 +85,9 @@ fn version() { #[test] fn control_flow() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Vertex); + let _program = parse_program( r#" # version 450 @@ -92,7 +99,7 @@ fn control_flow() { } } "#, - ShaderStage::Vertex, + &entry_points, ) .unwrap(); @@ -105,7 +112,7 @@ fn control_flow() { } } "#, - ShaderStage::Vertex, + &entry_points, ) .unwrap(); @@ -127,7 +134,7 @@ fn control_flow() { } } "#, - ShaderStage::Vertex, + &entry_points, ) .unwrap(); let _program = parse_program( @@ -143,7 +150,7 @@ fn control_flow() { } while(x >= 4) } "#, - ShaderStage::Vertex, + &entry_points, ) .unwrap(); @@ -158,13 +165,16 @@ fn control_flow() { return x; } "#, - ShaderStage::Vertex, + &entry_points, ) .unwrap(); } #[test] fn textures() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Fragment); + let _program = parse_program( r#" #version 450 @@ -176,13 +186,16 @@ fn textures() { o_color = texture(sampler2D(tex, tex_sampler), v_uv); } "#, - ShaderStage::Fragment, + &entry_points, ) .unwrap(); } #[test] fn functions() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Vertex); + // TODO: Add support for function prototypes // parse_program( // r#" @@ -205,7 +218,7 @@ fn functions() { void main() {} "#, - ShaderStage::Vertex, + &entry_points, ) .unwrap(); @@ -216,7 +229,7 @@ fn functions() { void main() {} "#, - ShaderStage::Vertex, + &entry_points, ) .unwrap(); @@ -227,7 +240,7 @@ fn functions() { return p.x; } "#, - ShaderStage::Vertex, + &entry_points, ) .unwrap(); } @@ -236,6 +249,9 @@ fn functions() { fn constants() { use crate::{Constant, ConstantInner, ScalarValue}; + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Vertex); + let program = parse_program( r#" # version 450 @@ -243,7 +259,7 @@ fn constants() { float global = a; const flat float b = a; "#, - ShaderStage::Vertex, + &entry_points, ) .unwrap(); diff --git a/src/front/glsl/preprocess.rs b/src/front/glsl/preprocess.rs index 605059471..f9b5a3fe7 100644 --- a/src/front/glsl/preprocess.rs +++ b/src/front/glsl/preprocess.rs @@ -20,16 +20,16 @@ pub struct IfState { #[derive(Clone, Debug)] pub struct LinePreProcessor { - pub defines: FastHashMap, + defines: FastHashMap, if_stack: Vec, inside_comment: bool, in_preprocess: bool, } impl LinePreProcessor { - pub fn new() -> Self { + pub fn new(defines: &FastHashMap) -> Self { LinePreProcessor { - defines: FastHashMap::default(), + defines: defines.clone(), if_stack: vec![], inside_comment: false, in_preprocess: false, diff --git a/src/front/glsl/preprocess_tests.rs b/src/front/glsl/preprocess_tests.rs index 253a99935..44e9bf27b 100644 --- a/src/front/glsl/preprocess_tests.rs +++ b/src/front/glsl/preprocess_tests.rs @@ -11,13 +11,13 @@ pub struct PreProcessor<'a> { } impl<'a> PreProcessor<'a> { - pub fn new(input: &'a str) -> Self { + pub fn new(input: &'a str, defines: crate::FastHashMap) -> Self { let mut lexer = PreProcessor { lines: input.lines().enumerate(), input: "".to_string(), line: 0, offset: 0, - line_pp: LinePreProcessor::new(), + line_pp: LinePreProcessor::new(&defines), }; lexer.next_line(); lexer @@ -69,6 +69,7 @@ fn preprocess() { let mut pp = PreProcessor::new( "void main my_\ func", + Default::default(), ); assert_eq!(pp.process().unwrap(), "void main my_func"); @@ -76,6 +77,7 @@ fn preprocess() { let mut pp = PreProcessor::new( "#version 450 core\n\ void main()", + Default::default(), ); assert_eq!(pp.process().unwrap(), "#version 450 core\nvoid main()"); @@ -83,6 +85,7 @@ fn preprocess() { let mut pp = PreProcessor::new( "#define FOO 42 \n\ fun=FOO", + Default::default(), ); assert_eq!(pp.process().unwrap(), "\nfun=42"); @@ -99,6 +102,7 @@ fn preprocess() { mm=49\n\ #endif\n\ done=1", + Default::default(), ); assert_eq!( pp.process().unwrap(), @@ -133,6 +137,7 @@ fn preprocess() { mm=49\n\ #endif\n\ done=1", + Default::default(), ); assert_eq!( pp.process().unwrap(), @@ -166,6 +171,7 @@ fn preprocess() { nofoo=66\n\ #endif\n\ done=1", + Default::default(), ); assert_eq!( pp.process().unwrap(), @@ -183,6 +189,7 @@ fn preprocess() { let mut pp = PreProcessor::new( "#define FOO 42//1234\n\ fun=FOO", + Default::default(), ); assert_eq!(pp.process().unwrap(), "\nfun=42"); @@ -192,6 +199,7 @@ fn preprocess() { #define FOO 88\n\ end of comment*/ /* one more comment */ #define FOO 56\n\ fun=FOO", + Default::default(), ); assert_eq!(pp.process().unwrap(), "\nfun=56"); @@ -201,6 +209,7 @@ fn preprocess() { foo=42\n\ #endif\n\ #endif", + Default::default(), ); assert_eq!(pp.process(), Err(Error::UnmatchedEndif)); @@ -213,6 +222,7 @@ fn preprocess() { #else\n\ bad=true\n\ #endif", + Default::default(), ); assert_eq!(pp.process(), Err(Error::UnmatchedElse)); } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index f41b877e8..ba925f433 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,13 +1,13 @@ use crate::{ - Binding, BuiltIn, Expression, GlobalVariable, Handle, ScalarKind, ShaderStage, StorageAccess, - StorageClass, Type, TypeInner, VectorSize, + Binding, BuiltIn, Expression, GlobalVariable, Handle, ScalarKind, StorageAccess, StorageClass, + Type, TypeInner, VectorSize, }; use super::ast::*; use super::error::ErrorKind; use super::token::TokenMetadata; -impl Program { +impl Program<'_> { pub fn lookup_variable(&mut self, name: &str) -> Result>, ErrorKind> { if let Some(local_var) = self.context.lookup_local_var(name) { return Ok(Some(local_var)); @@ -20,10 +20,6 @@ impl Program { } match name { "gl_Position" => { - #[cfg(feature = "glsl-validate")] - if !self.has_stage(ShaderStage::Vertex) { - return Err(ErrorKind::VariableNotAvailable(name.into())); - }; let h = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), class: StorageClass::Output, @@ -50,10 +46,6 @@ impl Program { Ok(Some(exp)) } "gl_VertexIndex" => { - #[cfg(feature = "glsl-validate")] - if !self.has_stage(ShaderStage::Vertex) { - return Err(ErrorKind::VariableNotAvailable(name.into())); - }; let h = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), class: StorageClass::Input, @@ -86,10 +78,6 @@ impl Program { Ok(Some(expr)) } "gl_InstanceIndex" => { - #[cfg(feature = "glsl-validate")] - if !self.has_stage(ShaderStage::Vertex) { - return Err(ErrorKind::VariableNotAvailable(name.into())); - }; let h = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), class: StorageClass::Input, diff --git a/tests/in/quad-glsl.param.ron b/tests/in/quad-glsl.param.ron index 74dd08590..9f7b9d587 100644 --- a/tests/in/quad-glsl.param.ron +++ b/tests/in/quad-glsl.param.ron @@ -1,8 +1,5 @@ ( spv_version: (1, 0), spv_capabilities: [ Shader ], - mtl_bindings: { - (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), - (stage: Fragment, group: 0, binding: 1): (sampler: Some(0)), - } + mtl_bindings: {} ) diff --git a/tests/parse.rs b/tests/parse.rs index 49ca56f04..23fec0898 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -14,10 +14,14 @@ fn check_glsl(name: &str) { panic!("Unknown extension in {:?}", name) }; + let mut entry_points = naga::FastHashMap::default(); + entry_points.insert("main".to_string(), stage); match naga::front::glsl::parse_str( &input, - vec![("main".to_string(), stage)], - Default::default(), + &naga::front::glsl::Options { + entry_points, + defines: Default::default(), + }, ) { Ok(m) => match naga::proc::Validator::new().validate(&m) { Ok(_analysis) => (), diff --git a/tests/snapshots.rs b/tests/snapshots.rs index a27cb3a86..d1114b55a 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -249,7 +249,7 @@ fn convert_spv_shadow() { } #[cfg(feature = "glsl-in")] -fn convert_glsl(name: &str, entry_points: Vec<(String, naga::ShaderStage)>) { +fn convert_glsl(name: &str, entry_points: naga::FastHashMap) { let params = match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), @@ -258,8 +258,10 @@ fn convert_glsl(name: &str, entry_points: Vec<(String, naga::ShaderStage)>) { let module = naga::front::glsl::parse_str( &std::fs::read_to_string(format!("tests/in/{}{}", name, ".glsl")) .expect("Couldn't find glsl file"), - entry_points, - Default::default(), + &naga::front::glsl::Options { + entry_points, + defines: Default::default(), + }, ) .unwrap(); naga::proc::Validator::new().validate(&module).unwrap(); @@ -281,11 +283,8 @@ fn convert_glsl(name: &str, entry_points: Vec<(String, naga::ShaderStage)>) { #[cfg(feature = "glsl-in")] #[test] fn convert_glsl_quad() { - convert_glsl( - "quad-glsl", - vec![ - ("vert_main".to_string(), naga::ShaderStage::Vertex), - ("frag_main".to_string(), naga::ShaderStage::Fragment), - ], - ); + let mut entry_points = naga::FastHashMap::default(); + entry_points.insert("vert_main".to_string(), naga::ShaderStage::Vertex); + entry_points.insert("frag_main".to_string(), naga::ShaderStage::Fragment); + convert_glsl("quad-glsl", entry_points); } From 9f0cdfe9e58511f70f7e9ee5f3073f8fd8cdf723 Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 17 Feb 2021 15:01:30 +0000 Subject: [PATCH 0508/2212] [glsl-in] Multi entry, don't use find on hashmap --- src/front/glsl/functions.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 38249d7a6..05163043a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -287,11 +287,8 @@ impl Program<'_> { .name .clone() .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; - let stage = self - .entry_points - .iter() - .find_map(|(n, s)| if *name == *n { Some(*s) } else { None }); - if let Some(stage) = stage { + let stage = self.entry_points.get(&name); + if let Some(&stage) = stage { self.module.entry_points.insert( (stage, name), EntryPoint { From 8a0382a89dbc5db9558a6faf69d317812044e546 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 17 Feb 2021 14:55:46 -0500 Subject: [PATCH 0509/2212] Move global use flags into FunctionInfo --- examples/convert.rs | 2 +- src/back/glsl/mod.rs | 25 +++---- src/back/msl/writer.rs | 55 +++++++------- src/back/spv/mod.rs | 8 +- src/back/spv/writer.rs | 34 ++++++--- src/front/global_usage.rs | 114 ----------------------------- src/front/glsl/functions.rs | 1 - src/front/glsl/parser.rs | 1 - src/front/mod.rs | 2 - src/front/spv/function.rs | 2 - src/front/wgsl/mod.rs | 2 - src/lib.rs | 16 ---- src/proc/analyzer.rs | 138 ++++++++++++++++++++++++++++------- src/proc/validator.rs | 99 +++++++++++-------------- tests/out/quad-glsl.ron.snap | 34 --------- tests/out/shadow.ron.snap | 46 ------------ tests/snapshots.rs | 16 ++-- 17 files changed, 235 insertions(+), 360 deletions(-) delete mode 100644 src/front/global_usage.rs diff --git a/examples/convert.rs b/examples/convert.rs index 9562a1fb8..f3919ee89 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -221,7 +221,7 @@ fn main() { capabilities: params.spv_capabilities, }; - let spv = spv::write_vec(&module, &options).unwrap_pretty(); + let spv = spv::write_vec(&module, &analysis, &options).unwrap_pretty(); let bytes = spv .iter() diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 677911a1a..58a46287f 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -405,18 +405,20 @@ impl<'a, W: Write> Writer<'a, W> { } } + let ep_info = self + .analysis + .get_entry_point(self.options.entry_point.0, &self.options.entry_point.1); + // Write the globals // // We filter all globals that aren't used by the selected entry point as they might be // interfere with each other (i.e. two globals with the same location but different with // different classes) - for (handle, global) in self - .module - .global_variables - .iter() - .zip(&self.entry_point.function.global_usage) - .filter_map(|(global, usage)| Some(global).filter(|_| !usage.is_empty())) - { + for (handle, global) in self.module.global_variables.iter() { + if ep_info[handle].is_empty() { + continue; + } + // Skip builtins // TODO: Write them if they have modifiers if let Some(crate::Binding::BuiltIn(_)) = global.binding { @@ -1775,13 +1777,8 @@ impl<'a, W: Write> Writer<'a, W> { } } - for ((handle, var), &usage) in self - .module - .global_variables - .iter() - .zip(&self.entry_point.function.global_usage) - { - if usage.is_empty() { + for (handle, var) in self.module.global_variables.iter() { + if info[handle].is_empty() { continue; } match self.module.types[var.ty].inner { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index f1be29695..99bc0974c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2,7 +2,7 @@ use super::{keywords::RESERVED, Error, LocationMode, Options, TranslationInfo}; use crate::{ arena::Handle, proc::{ - analyzer::{Analysis, FunctionInfo}, + analyzer::{Analysis, FunctionInfo, GlobalUse}, EntryPointIndex, Interface, NameKey, Namer, ResolveContext, Typifier, Visitor, }, FastHashMap, @@ -34,7 +34,7 @@ struct TypedGlobalVariable<'a> { module: &'a crate::Module, names: &'a FastHashMap, handle: Handle, - usage: crate::GlobalUse, + usage: GlobalUse, } impl<'a> TypedGlobalVariable<'a> { @@ -47,7 +47,7 @@ impl<'a> TypedGlobalVariable<'a> { let (space_qualifier, reference) = match ty.inner { crate::TypeInner::Struct { .. } => match var.class { crate::StorageClass::Uniform | crate::StorageClass::Storage => { - let space = if self.usage.contains(crate::GlobalUse::WRITE) { + let space = if self.usage.contains(GlobalUse::WRITE) { "device " } else { "constant " @@ -163,6 +163,7 @@ struct ExpressionContext<'a> { function: &'a crate::Function, origin: FunctionOrigin, module: &'a crate::Module, + analysis: &'a Analysis, } struct StatementContext<'a> { @@ -212,7 +213,6 @@ impl Writer { parameters: &[Handle], context: &ExpressionContext, ) -> Result<(), Error> { - let fun = &context.module.functions[fun_handle]; let fun_name = &self.names[&NameKey::Function(fun_handle)]; write!(self.out, "{}(", fun_name)?; // first, write down the actual arguments @@ -224,13 +224,9 @@ impl Writer { } // follow-up with any global resources used let mut separate = !parameters.is_empty(); - for ((handle, var), &usage) in context - .module - .global_variables - .iter() - .zip(&fun.global_usage) - { - if !usage.is_empty() && var.class.needs_pass_through() { + let fun_info = &context.analysis[fun_handle]; + for (handle, var) in context.module.global_variables.iter() { + if !fun_info[handle].is_empty() && var.class.needs_pass_through() { let name = &self.names[&NameKey::GlobalVariable(handle)]; if separate { write!(self.out, ", ")?; @@ -1122,9 +1118,10 @@ impl Writer { }, )?; + let fun_info = &analysis[fun_handle]; pass_through_globals.clear(); - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { - if !usage.is_empty() && var.class.needs_pass_through() { + for (handle, var) in module.global_variables.iter() { + if !fun_info[handle].is_empty() && var.class.needs_pass_through() { pass_through_globals.push(handle); } } @@ -1152,7 +1149,7 @@ impl Writer { module, names: &self.names, handle, - usage: fun.global_usage[handle.index()], + usage: fun_info[handle], }; let separator = separate(index + 1 == pass_through_globals.len()); write!(self.out, "{}", INDENT)?; @@ -1177,8 +1174,9 @@ impl Writer { function: fun, origin: FunctionOrigin::Handle(fun_handle), module, + analysis, }, - fun_info: &analysis[fun_handle], + fun_info, return_value: None, }; self.named_expressions.clear(); @@ -1192,6 +1190,7 @@ impl Writer { }; for (ep_index, (&(stage, ref ep_name), ep)) in module.entry_points.iter().enumerate() { let fun = &ep.function; + let fun_info = analysis.get_entry_point(stage, ep_name); self.typifier.resolve_all( &fun.expressions, &module.types, @@ -1206,7 +1205,7 @@ impl Writer { // find the entry point(s) and inputs/outputs let mut last_used_global = None; - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { + for (handle, var) in module.global_variables.iter() { match var.class { crate::StorageClass::Input => { if let Some(crate::Binding::Location(_)) = var.binding { @@ -1216,7 +1215,7 @@ impl Writer { crate::StorageClass::Output => continue, _ => {} } - if !usage.is_empty() { + if !fun_info[handle].is_empty() { last_used_global = Some(handle); } } @@ -1246,11 +1245,9 @@ impl Writer { crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { // make dedicated input/output structs writeln!(self.out, "struct {} {{", location_input_name)?; - for ((handle, var), &usage) in - module.global_variables.iter().zip(&fun.global_usage) - { + for (handle, var) in module.global_variables.iter() { if var.class != crate::StorageClass::Input - || !usage.contains(crate::GlobalUse::READ) + || !fun_info[handle].contains(GlobalUse::READ) { continue; } @@ -1262,7 +1259,7 @@ impl Writer { module, names: &self.names, handle, - usage: crate::GlobalUse::empty(), + usage: GlobalUse::empty(), }; write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; @@ -1274,11 +1271,9 @@ impl Writer { writeln!(self.out)?; writeln!(self.out, "struct {} {{", output_name)?; - for ((handle, var), &usage) in - module.global_variables.iter().zip(&fun.global_usage) - { + for (handle, var) in module.global_variables.iter() { if var.class != crate::StorageClass::Output - || !usage.contains(crate::GlobalUse::WRITE) + || !fun_info[handle].contains(GlobalUse::WRITE) { continue; } @@ -1287,7 +1282,7 @@ impl Writer { module, names: &self.names, handle, - usage: crate::GlobalUse::empty(), + usage: GlobalUse::empty(), }; write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; @@ -1314,7 +1309,8 @@ impl Writer { } }; - for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) { + for (handle, var) in module.global_variables.iter() { + let usage = fun_info[handle]; if usage.is_empty() || var.class == crate::StorageClass::Output { continue; } @@ -1384,8 +1380,9 @@ impl Writer { function: fun, origin: FunctionOrigin::EntryPoint(ep_index as _), module, + analysis, }, - fun_info: analysis.get_entry_point(stage, ep_name), + fun_info, return_value, }; self.named_expressions.clear(); diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index c717d23f1..346aca071 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -65,9 +65,13 @@ impl Default for Options { } } -pub fn write_vec(module: &crate::Module, options: &Options) -> Result, Error> { +pub fn write_vec( + module: &crate::Module, + analysis: &crate::proc::analyzer::Analysis, + options: &Options, +) -> Result, Error> { let mut words = Vec::new(); let mut w = Writer::new(options)?; - w.write(module, &mut words)?; + w.write(module, analysis, &mut words)?; Ok(words) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 6a639be92..d71a84db2 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2,7 +2,10 @@ use super::{Instruction, LogicalLayout, Options, PhysicalLayout, WriterFlags}; use crate::{ arena::{Arena, Handle}, - proc::{Layouter, ResolveContext, ResolveError, Typifier}, + proc::{ + analyzer::{Analysis, FunctionInfo}, + Layouter, ResolveContext, ResolveError, Typifier, + }, }; use spirv::Word; use std::collections::hash_map::Entry; @@ -456,18 +459,17 @@ impl Writer { entry_point: &crate::EntryPoint, stage: crate::ShaderStage, name: &str, + info: &FunctionInfo, ir_module: &crate::Module, ) -> Result { let function_id = self.write_function(&entry_point.function, ir_module)?; let mut interface_ids = vec![]; - for ((handle, var), &usage) in ir_module - .global_variables - .iter() - .zip(&entry_point.function.global_usage) - { + for (handle, var) in ir_module.global_variables.iter() { let is_io = match var.class { - crate::StorageClass::Input | crate::StorageClass::Output => !usage.is_empty(), + crate::StorageClass::Input | crate::StorageClass::Output => { + !info[handle].is_empty() + } _ => false, }; if is_io { @@ -2115,7 +2117,11 @@ impl Writer { self.physical_layout.bound = self.id_count + 1; } - fn write_logical_layout(&mut self, ir_module: &crate::Module) -> Result<(), Error> { + fn write_logical_layout( + &mut self, + ir_module: &crate::Module, + analysis: &Analysis, + ) -> Result<(), Error> { Instruction::type_void(self.void_type).to_words(&mut self.logical_layout.declarations); Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); @@ -2148,7 +2154,8 @@ impl Writer { } for (&(stage, ref name), ir_ep) in ir_module.entry_points.iter() { - let ep_instruction = self.write_entry_point(ir_ep, stage, name, ir_module)?; + let info = analysis.get_entry_point(stage, name); + let ep_instruction = self.write_entry_point(ir_ep, stage, name, info, ir_module)?; ep_instruction.to_words(&mut self.logical_layout.entry_points); } @@ -2177,11 +2184,16 @@ impl Writer { Ok(()) } - pub fn write(&mut self, ir_module: &crate::Module, words: &mut Vec) -> Result<(), Error> { + pub fn write( + &mut self, + ir_module: &crate::Module, + analysis: &Analysis, + words: &mut Vec, + ) -> Result<(), Error> { self.layouter .initialize(&ir_module.types, &ir_module.constants); - self.write_logical_layout(ir_module)?; + self.write_logical_layout(ir_module, analysis)?; self.write_physical_layout(); self.physical_layout.in_words(words); diff --git a/src/front/global_usage.rs b/src/front/global_usage.rs deleted file mode 100644 index 99fe7fa73..000000000 --- a/src/front/global_usage.rs +++ /dev/null @@ -1,114 +0,0 @@ -use crate::{ - arena::{Arena, Handle}, - proc::{Interface, Visitor}, -}; -use bit_set::BitSet; - -struct GlobalUseVisitor<'a> { - usage: &'a mut [crate::GlobalUse], - functions: &'a Arena, -} - -impl Visitor for GlobalUseVisitor<'_> { - fn visit_expr(&mut self, _: Handle, expr: &crate::Expression) { - if let crate::Expression::GlobalVariable(handle) = expr { - self.usage[handle.index()] |= crate::GlobalUse::READ; - } - } - - fn visit_lhs_expr(&mut self, _: Handle, expr: &crate::Expression) { - if let crate::Expression::GlobalVariable(handle) = expr { - self.usage[handle.index()] |= crate::GlobalUse::WRITE; - } - } - - fn visit_fun(&mut self, fun: Handle) { - for (mine, other) in self.usage.iter_mut().zip(&self.functions[fun].global_usage) { - *mine |= *other; - } - } -} - -impl crate::Function { - pub fn fill_global_use(&mut self, globals_num: usize, functions: &Arena) { - let mut mask = BitSet::with_capacity(self.expressions.len()); - self.global_usage.clear(); - self.global_usage - .resize(globals_num, crate::GlobalUse::empty()); - - let mut io = Interface { - expressions: &self.expressions, - local_variables: &self.local_variables, - visitor: GlobalUseVisitor { - usage: &mut self.global_usage, - functions, - }, - mask: &mut mask, - }; - io.traverse(&self.body); - } -} - -#[test] -fn global_usage_scan() { - let test_global = crate::GlobalVariable { - name: None, - class: crate::StorageClass::Uniform, - binding: None, - ty: Handle::new(std::num::NonZeroU32::new(1).unwrap()), - init: None, - interpolation: None, - storage_access: crate::StorageAccess::empty(), - }; - let mut test_globals = Arena::new(); - - let global_1 = test_globals.append(test_global.clone()); - let global_2 = test_globals.append(test_global.clone()); - let global_3 = test_globals.append(test_global.clone()); - let global_4 = test_globals.append(test_global); - - let mut expressions = Arena::new(); - let global_1_expr = expressions.append(crate::Expression::GlobalVariable(global_1)); - let global_2_expr = expressions.append(crate::Expression::GlobalVariable(global_2)); - let global_3_expr = expressions.append(crate::Expression::GlobalVariable(global_3)); - let global_4_expr = expressions.append(crate::Expression::GlobalVariable(global_4)); - - let test_body = vec![ - crate::Statement::Return { - value: Some(global_1_expr), - }, - crate::Statement::Store { - pointer: global_2_expr, - value: global_1_expr, - }, - crate::Statement::Store { - pointer: expressions.append(crate::Expression::Access { - base: global_3_expr, - index: global_4_expr, - }), - value: global_1_expr, - }, - ]; - - let mut function = crate::Function { - name: None, - arguments: Vec::new(), - return_type: None, - local_variables: Arena::new(), - expressions, - global_usage: Vec::new(), - body: test_body, - }; - let other_functions = Arena::new(); - function.fill_global_use(test_globals.len(), &other_functions); - - assert_eq!( - &function.global_usage, - &[ - crate::GlobalUse::READ, - crate::GlobalUse::WRITE, - crate::GlobalUse::WRITE, - crate::GlobalUse::READ, - ], - ) -} diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 05163043a..973ed12b5 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -278,7 +278,6 @@ impl Program<'_> { self.context.typifier = Typifier::new(); ensure_block_returns(&mut block); f.body = block; - f.fill_global_use(self.module.global_variables.len(), &self.module.functions); f } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index d7d710fe5..06b2d3e6d 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1004,7 +1004,6 @@ pomelo! { name: Some(n.1), arguments: vec![], return_type: t.1, - global_usage: vec![], local_variables: Arena::::new(), expressions: Arena::::new(), body: vec![], diff --git a/src/front/mod.rs b/src/front/mod.rs index c7f696418..392c54b14 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,7 +1,5 @@ //! Parsers which load shaders into memory. -mod global_usage; - #[cfg(feature = "glsl-in")] pub mod glsl; #[cfg(feature = "spv-in")] diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index c3c2045f1..8675e5393 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -68,7 +68,6 @@ impl> super::Parser { } else { Some(self.lookup_type.lookup(result_type_id)?.handle) }, - global_usage: Vec::new(), local_variables: Arena::new(), expressions: self.make_expression_storage(), body: Vec::new(), @@ -147,7 +146,6 @@ impl> super::Parser { // done self.patch_function_calls(&mut fun)?; - fun.fill_global_use(module.global_variables.len(), &module.functions); let dump_suffix = match self.lookup_entry_point.remove(&fun_id) { Some(ep) => { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 120d49e8d..dd631448a 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1988,7 +1988,6 @@ impl Parser { name: Some(fun_name.to_string()), arguments, return_type, - global_usage: Vec::new(), local_variables: Arena::new(), expressions, body: Vec::new(), @@ -2014,7 +2013,6 @@ impl Parser { // fixup the IR ensure_block_returns(&mut fun.body); // done - fun.fill_global_use(module.global_variables.len(), &module.functions); self.scopes.pop(); Ok((fun, fun_name)) diff --git a/src/lib.rs b/src/lib.rs index f37eb625c..fd9c50671 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -430,18 +430,6 @@ pub enum Binding { Resource { group: u32, binding: u32 }, } -bitflags::bitflags! { - /// Indicates how a global variable is used. - #[cfg_attr(feature = "serialize", derive(Serialize))] - #[cfg_attr(feature = "deserialize", derive(Deserialize))] - pub struct GlobalUse: u8 { - /// Data will be read from the variable. - const READ = 0x1; - /// Data will be written to the variable. - const WRITE = 0x2; - } -} - /// Variable defined at module level. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -833,10 +821,6 @@ pub struct Function { pub arguments: Vec, /// The return type of this function, if any. pub return_type: Option>, - /// Vector of global variable usages. - /// - /// Each item corresponds to a global variable in the module. - pub global_usage: Vec, /// Local variables defined and used in the function. pub local_variables: Arena, /// Expressions used inside this function. diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index b35f9c680..fdbd7e6c9 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -42,6 +42,20 @@ bitflags::bitflags! { } } +bitflags::bitflags! { + /// Indicates how a global variable is used. + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + pub struct GlobalUse: u8 { + /// Data will be read from the variable. + const READ = 0x1; + /// Data will be written to the variable. + const WRITE = 0x2; + /// The information about the data is queried. + const QUERY = 0x4; + } +} + #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct SamplingKey { pub image: Handle, @@ -52,14 +66,40 @@ pub struct SamplingKey { pub struct ExpressionInfo { pub control_flags: ControlFlags, pub ref_count: usize, + assignable_global: Option>, } pub struct FunctionInfo { + /// Accumulated control flags of this function. pub control_flags: ControlFlags, + /// Set of image-sampler pais used with sampling. pub sampling_set: crate::FastHashSet, + /// Vector of global variable usages. + /// + /// Each item corresponds to a global variable in the module. + global_uses: Box<[GlobalUse]>, + /// Vector of expression infos. + /// + /// Each item corresponds to an expression in the function. expressions: Box<[ExpressionInfo]>, } +impl FunctionInfo { + pub fn global_variable_count(&self) -> usize { + self.global_uses.len() + } + pub fn expression_count(&self) -> usize { + self.expressions.len() + } +} + +impl ops::Index> for FunctionInfo { + type Output = GlobalUse; + fn index(&self, handle: Handle) -> &GlobalUse { + &self.global_uses[handle.index()] + } +} + impl ops::Index> for FunctionInfo { type Output = ExpressionInfo; fn index(&self, handle: Handle) -> &ExpressionInfo { @@ -78,13 +118,68 @@ pub enum AnalysisError { } impl FunctionInfo { + /// Adds a value-type reference to an expression. #[must_use] - fn add_ref(&mut self, handle: Handle) -> ControlFlags { + fn add_ref_impl( + &mut self, + handle: Handle, + global_use: GlobalUse, + ) -> ControlFlags { let info = &mut self.expressions[handle.index()]; info.ref_count += 1; + // mark the used global as read + if let Some(global) = info.assignable_global { + self.global_uses[global.index()] |= global_use; + } info.control_flags } + /// Adds a value-type reference to an expression. + #[must_use] + fn add_ref(&mut self, handle: Handle) -> ControlFlags { + self.add_ref_impl(handle, GlobalUse::READ) + } + + /// Adds a potentially assignable reference to an expression. + /// These are destinations for `Store` and `ImageStore` statements, + /// which can transit through `Access` and `AccessIndex`. + #[must_use] + fn add_assignable_ref( + &mut self, + handle: Handle, + assignable_global: &mut Option>, + ) -> ControlFlags { + let info = &mut self.expressions[handle.index()]; + info.ref_count += 1; + // propagate the assignable global up the chain, till it either hits + // a value-type expression, or the assignment statement. + if let Some(global) = info.assignable_global { + if let Some(_old) = assignable_global.replace(global) { + unreachable!() + } + } + info.control_flags + } + + /// Inherit information from a called function. + fn process_call( + &mut self, + info: &Self, + arguments: &[Handle], + ) -> ControlFlags { + for key in info.sampling_set.iter() { + self.sampling_set.insert(key.clone()); + } + for (mine, other) in self.global_uses.iter_mut().zip(info.global_uses.iter()) { + *mine |= *other; + } + let mut flags = info.control_flags; + for &argument in arguments { + flags |= self.add_ref(argument); + } + flags + } + /// Computes the control flags of a given expression, and store them /// in `self.expressions`. Also, bumps the reference counts on /// dependent expressions. @@ -97,9 +192,12 @@ impl FunctionInfo { ) -> Result<(), AnalysisError> { use crate::{Expression as E, SampleLevel as Sl}; + let mut assignable_global = None; let control_flags = match expression_arena[handle] { - E::Access { base, index } => self.add_ref(base) | self.add_ref(index), - E::AccessIndex { base, .. } => self.add_ref(base), + E::Access { base, index } => { + self.add_assignable_ref(base, &mut assignable_global) | self.add_ref(index) + } + E::AccessIndex { base, .. } => self.add_assignable_ref(base, &mut assignable_global), E::Constant(_) => ControlFlags::empty(), E::Compose { ref components, .. } => { let mut accum = ControlFlags::empty(); @@ -110,6 +208,7 @@ impl FunctionInfo { } E::FunctionArgument(_) => ControlFlags::NON_UNIFORM_RESULT, //TODO? E::GlobalVariable(handle) => { + assignable_global = Some(handle); let var = &global_var_arena[handle]; let uniform = if let Some(crate::Binding::BuiltIn(built_in)) = var.binding { match built_in { @@ -210,7 +309,7 @@ impl FunctionInfo { crate::ImageQuery::Size { level: Some(h) } => self.add_ref(h), _ => ControlFlags::empty(), }; - self.add_ref(image) | query_flags + self.add_ref_impl(image, GlobalUse::QUERY) | query_flags } E::Unary { expr, .. } => self.add_ref(expr), E::Binary { left, right, .. } => self.add_ref(left) | self.add_ref(right), @@ -239,23 +338,14 @@ impl FunctionInfo { E::Call { function, ref arguments, - } => { - let other_info = &other_functions[function.index()]; - for key in other_info.sampling_set.iter() { - self.sampling_set.insert(key.clone()); - } - let mut accum = other_info.control_flags; - for &argument in arguments { - accum |= self.add_ref(argument); - } - accum - } - E::ArrayLength(expr) => self.add_ref(expr), + } => self.process_call(&other_functions[function.index()], arguments), + E::ArrayLength(expr) => self.add_ref_impl(expr, GlobalUse::QUERY), }; self.expressions[handle.index()] = ExpressionInfo { control_flags, ref_count: 0, + assignable_global, }; Ok(()) } @@ -334,7 +424,9 @@ impl FunctionInfo { }; ControlFlags::MAY_EXIT | flags } - S::Store { pointer, value } => self.add_ref(pointer) | self.add_ref(value), + S::Store { pointer, value } => { + self.add_ref_impl(pointer, GlobalUse::WRITE) | self.add_ref(value) + } S::ImageStore { image, coordinate, @@ -346,20 +438,14 @@ impl FunctionInfo { None => ControlFlags::empty(), }; array_flags - | self.add_ref(image) + | self.add_ref_impl(image, GlobalUse::WRITE) | self.add_ref(coordinate) | self.add_ref(value) } S::Call { function, ref arguments, - } => { - let mut flags = other_functions[function.index()].control_flags; - for &argument in arguments { - flags |= self.add_ref(argument); - } - flags - } + } => self.process_call(&other_functions[function.index()], arguments), }; if flags.contains(ControlFlags::REQUIRE_UNIFORM) && !is_uniform { @@ -389,6 +475,7 @@ impl Analysis { let mut info = FunctionInfo { control_flags: ControlFlags::empty(), sampling_set: crate::FastHashSet::default(), + global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::default(); fun.expressions.len()].into_boxed_slice(), }; @@ -490,6 +577,7 @@ fn uniform_control_flow() { let mut info = FunctionInfo { control_flags: ControlFlags::empty(), sampling_set: crate::FastHashSet::default(), + global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::default(); expressions.len()].into_boxed_slice(), }; for (handle, _) in expressions.iter() { diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 149a4fd6f..50dc7ac79 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -1,5 +1,5 @@ use super::{ - analyzer::{Analysis, AnalysisError}, + analyzer::{Analysis, AnalysisError, FunctionInfo, GlobalUse}, typifier::{ResolveContext, ResolveError, Typifier}, }; use crate::arena::{Arena, Handle}; @@ -81,8 +81,6 @@ pub enum FunctionError { Resolve(#[from] ResolveError), #[error("There are instructions after `return`/`break`/`continue`")] InvalidControlFlowExitTail, - #[error("The global use array has a different length from the global variables")] - InvalidGlobalUsageLength, #[error("Local variable {handle:?} '{name}' is invalid: {error:?}")] LocalVariable { handle: Handle, @@ -106,7 +104,7 @@ pub enum EntryPointError { #[error("Can't have a return value")] UnexpectedReturnValue, #[error("Global variable {0:?} is used incorrectly as {1:?}")] - InvalidGlobalUsage(Handle, crate::GlobalUse), + InvalidGlobalUsage(Handle, GlobalUse), #[error("Bindings for {0:?} conflict with other global variables")] BindingCollision(Handle), #[error("Built-in {0:?} is not applicable to this entry point")] @@ -256,38 +254,38 @@ impl crate::GlobalVariable { } } -fn storage_usage(access: crate::StorageAccess) -> crate::GlobalUse { - let mut storage_usage = crate::GlobalUse::empty(); +fn storage_usage(access: crate::StorageAccess) -> GlobalUse { + let mut storage_usage = GlobalUse::QUERY; if access.contains(crate::StorageAccess::LOAD) { - storage_usage |= crate::GlobalUse::READ; + storage_usage |= GlobalUse::READ; } if access.contains(crate::StorageAccess::STORE) { - storage_usage |= crate::GlobalUse::WRITE; + storage_usage |= GlobalUse::WRITE; } storage_usage } -fn built_in_usage(built_in: crate::BuiltIn) -> (crate::ShaderStage, crate::GlobalUse) { - use crate::{BuiltIn as Bi, GlobalUse as Gu, ShaderStage as Ss}; +fn built_in_usage(built_in: crate::BuiltIn) -> (crate::ShaderStage, GlobalUse) { + use crate::{BuiltIn as Bi, ShaderStage as Ss}; match built_in { - Bi::BaseInstance => (Ss::Vertex, Gu::READ), - Bi::BaseVertex => (Ss::Vertex, Gu::READ), - Bi::ClipDistance => (Ss::Vertex, Gu::WRITE), - Bi::InstanceIndex => (Ss::Vertex, Gu::READ), - Bi::PointSize => (Ss::Vertex, Gu::WRITE), - Bi::Position => (Ss::Vertex, Gu::WRITE), - Bi::VertexIndex => (Ss::Vertex, Gu::READ), - Bi::FragCoord => (Ss::Fragment, Gu::READ), - Bi::FragDepth => (Ss::Fragment, Gu::WRITE), - Bi::FrontFacing => (Ss::Fragment, Gu::READ), - Bi::SampleIndex => (Ss::Fragment, Gu::READ), - Bi::SampleMaskIn => (Ss::Fragment, Gu::READ), - Bi::SampleMaskOut => (Ss::Fragment, Gu::WRITE), - Bi::GlobalInvocationId => (Ss::Compute, Gu::READ), - Bi::LocalInvocationId => (Ss::Compute, Gu::READ), - Bi::LocalInvocationIndex => (Ss::Compute, Gu::READ), - Bi::WorkGroupId => (Ss::Compute, Gu::READ), - Bi::WorkGroupSize => (Ss::Compute, Gu::READ), + Bi::BaseInstance => (Ss::Vertex, GlobalUse::READ), + Bi::BaseVertex => (Ss::Vertex, GlobalUse::READ), + Bi::ClipDistance => (Ss::Vertex, GlobalUse::WRITE), + Bi::InstanceIndex => (Ss::Vertex, GlobalUse::READ), + Bi::PointSize => (Ss::Vertex, GlobalUse::WRITE), + Bi::Position => (Ss::Vertex, GlobalUse::WRITE), + Bi::VertexIndex => (Ss::Vertex, GlobalUse::READ), + Bi::FragCoord => (Ss::Fragment, GlobalUse::READ), + Bi::FragDepth => (Ss::Fragment, GlobalUse::WRITE), + Bi::FrontFacing => (Ss::Fragment, GlobalUse::READ), + Bi::SampleIndex => (Ss::Fragment, GlobalUse::READ), + Bi::SampleMaskIn => (Ss::Fragment, GlobalUse::READ), + Bi::SampleMaskOut => (Ss::Fragment, GlobalUse::WRITE), + Bi::GlobalInvocationId => (Ss::Compute, GlobalUse::READ), + Bi::LocalInvocationId => (Ss::Compute, GlobalUse::READ), + Bi::LocalInvocationIndex => (Ss::Compute, GlobalUse::READ), + Bi::WorkGroupId => (Ss::Compute, GlobalUse::READ), + Bi::WorkGroupSize => (Ss::Compute, GlobalUse::READ), } } @@ -531,6 +529,7 @@ impl Validator { fn validate_function( &mut self, fun: &crate::Function, + _info: &FunctionInfo, module: &crate::Module, ) -> Result<(), FunctionError> { let resolve_ctx = ResolveContext { @@ -543,10 +542,6 @@ impl Validator { self.typifier .resolve_all(&fun.expressions, &module.types, &resolve_ctx)?; - if fun.global_usage.len() > module.global_variables.len() { - return Err(FunctionError::InvalidGlobalUsageLength); - } - for (var_handle, var) in fun.local_variables.iter() { self.validate_local_var(var, &module.types, &module.constants) .map_err(|error| FunctionError::LocalVariable { @@ -575,6 +570,7 @@ impl Validator { &mut self, ep: &crate::EntryPoint, stage: crate::ShaderStage, + info: &FunctionInfo, module: &crate::Module, ) -> Result<(), EntryPointError> { if ep.early_depth_test.is_some() && stage != crate::ShaderStage::Fragment { @@ -598,11 +594,8 @@ impl Validator { bg.clear(); } - for ((var_handle, var), &usage) in module - .global_variables - .iter() - .zip(&ep.function.global_usage) - { + for (var_handle, var) in module.global_variables.iter() { + let usage = info[var_handle]; if usage.is_empty() { continue; } @@ -629,9 +622,7 @@ impl Validator { match var.binding { Some(crate::Binding::BuiltIn(built_in)) => { let (allowed_stage, allowed_usage) = built_in_usage(built_in); - if allowed_stage != stage - || !allowed_usage.contains(crate::GlobalUse::READ) - { + if allowed_stage != stage || !allowed_usage.contains(GlobalUse::READ) { return Err(EntryPointError::InvalidBuiltIn(built_in)); } } @@ -643,15 +634,13 @@ impl Validator { Some(crate::Binding::Resource { .. }) => unreachable!(), None => (), } - crate::GlobalUse::READ + GlobalUse::READ } crate::StorageClass::Output => { match var.binding { Some(crate::Binding::BuiltIn(built_in)) => { let (allowed_stage, allowed_usage) = built_in_usage(built_in); - if allowed_stage != stage - || !allowed_usage.contains(crate::GlobalUse::WRITE) - { + if allowed_stage != stage || !allowed_usage.contains(GlobalUse::WRITE) { return Err(EntryPointError::InvalidBuiltIn(built_in)); } } @@ -663,21 +652,19 @@ impl Validator { Some(crate::Binding::Resource { .. }) => unreachable!(), None => (), } - crate::GlobalUse::READ | crate::GlobalUse::WRITE + GlobalUse::READ | GlobalUse::WRITE } - crate::StorageClass::Uniform => crate::GlobalUse::READ, + crate::StorageClass::Uniform => GlobalUse::READ | GlobalUse::QUERY, crate::StorageClass::Storage => storage_usage(var.storage_access), crate::StorageClass::Handle => match module.types[var.ty].inner { crate::TypeInner::Image { class: crate::ImageClass::Storage(_), .. } => storage_usage(var.storage_access), - _ => crate::GlobalUse::READ, + _ => GlobalUse::READ | GlobalUse::QUERY, }, - crate::StorageClass::Private | crate::StorageClass::WorkGroup => { - crate::GlobalUse::all() - } - crate::StorageClass::PushConstant => crate::GlobalUse::READ, + crate::StorageClass::Private | crate::StorageClass::WorkGroup => GlobalUse::all(), + crate::StorageClass::PushConstant => GlobalUse::READ, }; if !allowed_usage.contains(usage) { log::warn!("\tUsage error for: {:?}", var); @@ -706,7 +693,7 @@ impl Validator { return Err(EntryPointError::UnexpectedReturnValue); } - self.validate_function(&ep.function, module)?; + self.validate_function(&ep.function, info, module)?; Ok(()) } @@ -717,6 +704,8 @@ impl Validator { self.type_flags .resize(module.types.len(), TypeFlags::empty()); + let analysis = Analysis::new(module)?; + for (handle, constant) in module.constants.iter() { self.validate_constant(handle, &module.constants, &module.types) .map_err(|error| ValidationError::Constant { @@ -750,12 +739,13 @@ impl Validator { } for (fun_handle, fun) in module.functions.iter() { - self.validate_function(fun, module) + self.validate_function(fun, &analysis[fun_handle], module) .map_err(|e| ValidationError::Function(fun_handle, e))?; } for (&(stage, ref name), entry_point) in module.entry_points.iter() { - self.validate_entry_point(entry_point, stage, module) + let info = analysis.get_entry_point(stage, name); + self.validate_entry_point(entry_point, stage, info, module) .map_err(|error| ValidationError::EntryPoint { stage, name: name.to_string(), @@ -763,7 +753,6 @@ impl Validator { })?; } - let analysis = Analysis::new(module)?; Ok(analysis) } } diff --git a/tests/out/quad-glsl.ron.snap b/tests/out/quad-glsl.ron.snap index 793c65df7..2b8256eee 100644 --- a/tests/out/quad-glsl.ron.snap +++ b/tests/out/quad-glsl.ron.snap @@ -139,26 +139,6 @@ expression: output name: Some("frag_main"), arguments: [], return_type: None, - global_usage: [ - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 2, - ), - ], local_variables: [], expressions: [ GlobalVariable(1), @@ -200,20 +180,6 @@ expression: output name: Some("vert_main"), arguments: [], return_type: None, - global_usage: [ - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 2, - ), - ( - bits: 2, - ), - ], local_variables: [], expressions: [ Constant(1), diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index 59746a732..c79cdb6cd 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -592,29 +592,6 @@ expression: output ), ], return_type: Some(1), - global_usage: [ - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ], local_variables: [], expressions: [ GlobalVariable(3), @@ -825,29 +802,6 @@ expression: output name: Some("fs_main"), arguments: [], return_type: None, - global_usage: [ - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 2, - ), - ], local_variables: [ ( name: Some("color"), diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d1114b55a..e92863024 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -49,6 +49,7 @@ struct Parameters { mtl_bindings: naga::FastHashMap, } +#[allow(dead_code)] fn with_snapshot_settings ()>(snapshot_assertion: F) { let mut settings = insta::Settings::new(); settings.set_snapshot_path("out"); @@ -57,7 +58,12 @@ fn with_snapshot_settings ()>(snapshot_assertion: F) { } #[cfg(feature = "spv-out")] -fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { +fn check_output_spv( + module: &naga::Module, + analysis: &naga::proc::analyzer::Analysis, + name: &str, + params: &Parameters, +) { use naga::back::spv; use rspirv::binary::Disassemble; @@ -67,7 +73,7 @@ fn check_output_spv(module: &naga::Module, name: &str, params: &Parameters) { capabilities: params.spv_capabilities.clone(), }; - let spv = spv::write_vec(&module, &options).unwrap(); + let spv = spv::write_vec(module, analysis, &options).unwrap(); let dis = rspirv::dr::load_words(spv) .expect("Produced invalid SPIR-V") @@ -162,7 +168,7 @@ fn convert_wgsl(name: &str, language: Language) { #[cfg(feature = "spv-out")] { if language.contains(Language::SPIRV) { - check_output_spv(&module, name, ¶ms); + check_output_spv(&module, &analysis, name, ¶ms); } } #[cfg(feature = "msl-out")] @@ -264,11 +270,11 @@ fn convert_glsl(name: &str, entry_points: naga::FastHashMap Date: Wed, 17 Feb 2021 16:15:39 -0500 Subject: [PATCH 0510/2212] Global usage tests in the analyzer --- src/proc/analyzer.rs | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index fdbd7e6c9..ded6ec354 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -566,13 +566,22 @@ fn uniform_control_flow() { }); let mut expressions = Arena::new(); + // checks the uniform control flow let constant_expr = expressions.append(E::Constant(constant)); + // checks the non-uniform control flow let derivative_expr = expressions.append(E::Derivative { axis: crate::DerivativeAxis::X, expr: constant_expr, }); let non_uniform_global_expr = expressions.append(E::GlobalVariable(non_uniform_global)); let uniform_global_expr = expressions.append(E::GlobalVariable(uniform_global)); + // checks the QUERY flag + let query_expr = expressions.append(E::ArrayLength(uniform_global_expr)); + // checks the transitive WRITE flag + let access_expr = expressions.append(E::AccessIndex { + base: non_uniform_global_expr, + index: 1, + }); let mut info = FunctionInfo { control_flags: ControlFlags::empty(), @@ -584,8 +593,12 @@ fn uniform_control_flow() { info.process_expression(handle, &expressions, &global_var_arena, &[]) .unwrap(); } - assert_eq!(info.expressions[non_uniform_global.index()].ref_count, 1); - assert_eq!(info.expressions[uniform_global_expr.index()].ref_count, 0); + assert_eq!(info[non_uniform_global_expr].ref_count, 1); + assert_eq!(info[uniform_global_expr].ref_count, 1); + assert_eq!(info[query_expr].ref_count, 0); + assert_eq!(info[access_expr].ref_count, 0); + assert_eq!(info[non_uniform_global], GlobalUse::empty()); + assert_eq!(info[uniform_global], GlobalUse::QUERY); let stmt_if_uniform = S::If { condition: uniform_global_expr, @@ -599,7 +612,8 @@ fn uniform_control_flow() { info.process_block(&[stmt_if_uniform], &[], true), Ok(ControlFlags::REQUIRE_UNIFORM), ); - assert_eq!(info.expressions[constant_expr.index()].ref_count, 2); + assert_eq!(info[constant_expr].ref_count, 2); + assert_eq!(info[uniform_global], GlobalUse::READ | GlobalUse::QUERY); let stmt_if_non_uniform = S::If { condition: non_uniform_global_expr, @@ -613,7 +627,8 @@ fn uniform_control_flow() { info.process_block(&[stmt_if_non_uniform], &[], true), Err(AnalysisError::NonUniformControlFlow), ); - assert_eq!(info.expressions[derivative_expr.index()].ref_count, 2); + assert_eq!(info[derivative_expr].ref_count, 2); + assert_eq!(info[non_uniform_global], GlobalUse::READ); let stmt_return_non_uniform = S::Return { value: Some(non_uniform_global_expr), @@ -622,8 +637,15 @@ fn uniform_control_flow() { info.process_block(&[stmt_return_non_uniform], &[], false), Ok(ControlFlags::NON_UNIFORM_RESULT | ControlFlags::MAY_EXIT), ); + assert_eq!(info[non_uniform_global_expr].ref_count, 3); + + let stmt_assign = S::Store { + pointer: access_expr, + value: query_expr, + }; assert_eq!( - info.expressions[non_uniform_global_expr.index()].ref_count, - 2 + info.process_block(&[stmt_assign], &[], false), + Ok(ControlFlags::NON_UNIFORM_RESULT), ); + assert_eq!(info[non_uniform_global], GlobalUse::READ | GlobalUse::WRITE); } From 5f21cf360f8f447668b6b5c7d6ac0001816e4610 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 17 Feb 2021 21:46:32 -0500 Subject: [PATCH 0511/2212] Refactor snapshot testing to include some IR --- src/proc/analyzer.rs | 10 + tests/out/collatz.info.ron.snap | 245 ++++++ tests/out/collatz.ron.snap | 274 +++++++ tests/out/shadow.info.ron.snap | 1230 +++++++++++++++++++++++++++++++ tests/snapshots.rs | 147 ++-- 5 files changed, 1835 insertions(+), 71 deletions(-) create mode 100644 tests/out/collatz.info.ron.snap create mode 100644 tests/out/collatz.ron.snap create mode 100644 tests/out/shadow.info.ron.snap diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index ded6ec354..04081d646 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -11,6 +11,8 @@ use std::ops; bitflags::bitflags! { #[derive(Default)] + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ControlFlags: u8 { /// The result (of an expression) is not dynamically uniform. /// @@ -57,18 +59,24 @@ bitflags::bitflags! { } #[derive(Clone, Debug, Eq, Hash, PartialEq)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct SamplingKey { pub image: Handle, pub sampler: Handle, } #[derive(Clone, Default)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ExpressionInfo { pub control_flags: ControlFlags, pub ref_count: usize, assignable_global: Option>, } +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct FunctionInfo { /// Accumulated control flags of this function. pub control_flags: ControlFlags, @@ -459,6 +467,8 @@ impl FunctionInfo { } #[derive(Default)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Analysis { functions: Vec, entry_points: crate::FastHashMap<(crate::ShaderStage, String), FunctionInfo>, diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap new file mode 100644 index 000000000..4062a43b4 --- /dev/null +++ b/tests/out/collatz.info.ron.snap @@ -0,0 +1,245 @@ +--- +source: tests/snapshots.rs +expression: output +--- +( + functions: [ + ( + control_flags: ( + bits: 5, + ), + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + control_flags: ( + bits: 1, + ), + ref_count: 0, + assignable_global: Some(1), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 0, + assignable_global: Some(2), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 7, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 3, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ], + ), + ], + entry_points: { + (Compute, "main"): ( + control_flags: ( + bits: 5, + ), + sampling_set: [], + global_uses: [ + ( + bits: 1, + ), + ( + bits: 3, + ), + ], + expressions: [ + ( + control_flags: ( + bits: 1, + ), + ref_count: 2, + assignable_global: Some(1), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 2, + assignable_global: Some(2), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(2), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(1), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(2), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(2), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(1), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(2), + ), + ( + control_flags: ( + bits: 5, + ), + ref_count: 1, + assignable_global: None, + ), + ], + ), + }, +) diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap new file mode 100644 index 000000000..ec08b46ba --- /dev/null +++ b/tests/out/collatz.ron.snap @@ -0,0 +1,274 @@ +--- +source: tests/snapshots.rs +expression: output +--- +( + types: [ + ( + name: None, + inner: Vector( + size: Tri, + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Scalar( + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 2, + size: Dynamic, + stride: Some(4), + ), + ), + ( + name: Some("PrimeIndices"), + inner: Struct( + block: true, + members: [ + ( + name: Some("data"), + span: None, + ty: 3, + ), + ], + ), + ), + ], + constants: [ + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(3), + ), + ), + ], + global_variables: [ + ( + name: Some("global_id"), + class: Input, + binding: Some(BuiltIn(GlobalInvocationId)), + ty: 1, + init: None, + interpolation: None, + storage_access: ( + bits: 0, + ), + ), + ( + name: Some("v_indices"), + class: Storage, + binding: Some(Resource( + group: 0, + binding: 0, + )), + ty: 4, + init: None, + interpolation: None, + storage_access: ( + bits: 3, + ), + ), + ], + functions: [ + ( + name: Some("collatz_iterations"), + arguments: [ + ( + name: Some("n_base"), + ty: 2, + ), + ], + return_type: Some(2), + local_variables: [ + ( + name: Some("n"), + ty: 2, + init: None, + ), + ( + name: Some("i"), + ty: 2, + init: Some(1), + ), + ], + expressions: [ + GlobalVariable(1), + GlobalVariable(2), + FunctionArgument(0), + LocalVariable(1), + Constant(1), + LocalVariable(2), + Constant(2), + Binary( + op: LessEqual, + left: 4, + right: 7, + ), + Constant(3), + Binary( + op: Modulo, + left: 4, + right: 9, + ), + Constant(1), + Binary( + op: Equal, + left: 10, + right: 11, + ), + Constant(3), + Binary( + op: Divide, + left: 4, + right: 13, + ), + Constant(4), + Binary( + op: Multiply, + left: 15, + right: 4, + ), + Constant(2), + Binary( + op: Add, + left: 16, + right: 17, + ), + Constant(2), + Binary( + op: Add, + left: 6, + right: 19, + ), + ], + body: [ + Store( + pointer: 4, + value: 3, + ), + Loop( + body: [ + If( + condition: 8, + accept: [ + Break, + ], + reject: [], + ), + If( + condition: 12, + accept: [ + Store( + pointer: 4, + value: 14, + ), + ], + reject: [ + Store( + pointer: 4, + value: 18, + ), + ], + ), + Store( + pointer: 6, + value: 20, + ), + ], + continuing: [], + ), + Return( + value: Some(6), + ), + ], + ), + ], + entry_points: { + (Compute, "main"): ( + early_depth_test: None, + workgroup_size: (1, 1, 1), + function: ( + name: Some("main"), + arguments: [], + return_type: None, + local_variables: [], + expressions: [ + GlobalVariable(1), + GlobalVariable(2), + AccessIndex( + base: 2, + index: 0, + ), + AccessIndex( + base: 1, + index: 0, + ), + Access( + base: 3, + index: 4, + ), + AccessIndex( + base: 2, + index: 0, + ), + AccessIndex( + base: 1, + index: 0, + ), + Access( + base: 6, + index: 7, + ), + Call( + function: 1, + arguments: [ + 8, + ], + ), + ], + body: [ + Store( + pointer: 5, + value: 9, + ), + Return( + value: None, + ), + ], + ), + ), + }, +) diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap new file mode 100644 index 000000000..200c3206e --- /dev/null +++ b/tests/out/shadow.info.ron.snap @@ -0,0 +1,1230 @@ +--- +source: tests/snapshots.rs +expression: output +--- +( + functions: [ + ( + control_flags: ( + bits: 5, + ), + sampling_set: [ + ( + image: 1, + sampler: 2, + ), + ], + global_uses: [ + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: Some(3), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 0, + assignable_global: Some(6), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 0, + assignable_global: Some(5), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(1), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(2), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 0, + assignable_global: Some(7), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 3, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 3, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 6, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 2, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 3, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ], + ), + ], + entry_points: { + (Fragment, "fs_main"): ( + control_flags: ( + bits: 5, + ), + sampling_set: [ + ( + image: 1, + sampler: 2, + ), + ], + global_uses: [ + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 2, + ), + ], + expressions: [ + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(3), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(6), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 4, + assignable_global: Some(5), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: Some(1), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: Some(2), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 7, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(7), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 0, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 3, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 12, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(3), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(3), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 5, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(5), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(5), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(5), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 5, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 5, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 5, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 2, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ], + ), + }, +) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e92863024..f5148c7db 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -1,8 +1,10 @@ bitflags::bitflags! { - struct Language: u32 { - const SPIRV = 0x1; - const METAL = 0x2; - const GLSL = 0x4; + struct Targets: u32 { + const IR = 0x1; + const ANALYSIS = 0x2; + const SPIRV = 0x4; + const METAL = 0x8; + const GLSL = 0x10; } } @@ -57,6 +59,54 @@ fn with_snapshot_settings ()>(snapshot_assertion: F) { settings.bind(|| snapshot_assertion()); } +#[allow(unused_variables)] +fn check_targets(module: &naga::Module, name: &str, targets: Targets) { + let params = match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { + Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), + Err(_) => Parameters::default(), + }; + let analysis = naga::proc::Validator::new().validate(module).unwrap(); + + #[cfg(feature = "serialize")] + { + if targets.contains(Targets::IR) { + let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); + let output = ron::ser::to_string_pretty(module, config).unwrap(); + with_snapshot_settings(|| { + insta::assert_snapshot!(format!("{}.ron", name), output); + }); + } + if targets.contains(Targets::ANALYSIS) { + let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); + let output = ron::ser::to_string_pretty(&analysis, config).unwrap(); + with_snapshot_settings(|| { + insta::assert_snapshot!(format!("{}.info.ron", name), output); + }); + } + } + + #[cfg(feature = "spv-out")] + { + if targets.contains(Targets::SPIRV) { + check_output_spv(module, &analysis, name, ¶ms); + } + } + #[cfg(feature = "msl-out")] + { + if targets.contains(Targets::METAL) { + check_output_msl(module, &analysis, name, ¶ms); + } + } + #[cfg(feature = "glsl-out")] + { + if targets.contains(Targets::GLSL) { + for &(stage, ref ep_name) in module.entry_points.keys() { + check_output_glsl(module, &analysis, name, stage, ep_name); + } + } + } +} + #[cfg(feature = "spv-out")] fn check_output_spv( module: &naga::Module, @@ -152,115 +202,83 @@ fn check_output_glsl( } #[cfg(feature = "wgsl-in")] -fn convert_wgsl(name: &str, language: Language) { - let params = match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { - Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), - Err(_) => Parameters::default(), - }; - +fn convert_wgsl(name: &str, targets: Targets) { let module = naga::front::wgsl::parse_str( &std::fs::read_to_string(format!("tests/in/{}{}", name, ".wgsl")) .expect("Couldn't find wgsl file"), ) .unwrap(); - let analysis = naga::proc::Validator::new().validate(&module).unwrap(); - - #[cfg(feature = "spv-out")] - { - if language.contains(Language::SPIRV) { - check_output_spv(&module, &analysis, name, ¶ms); - } - } - #[cfg(feature = "msl-out")] - { - if language.contains(Language::METAL) { - check_output_msl(&module, &analysis, name, ¶ms); - } - } - #[cfg(feature = "glsl-out")] - { - if language.contains(Language::GLSL) { - for &(stage, ref ep_name) in module.entry_points.keys() { - check_output_glsl(&module, &analysis, name, stage, ep_name); - } - } - } + check_targets(&module, name, targets); } #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_quad() { - convert_wgsl("quad", Language::all()); + convert_wgsl("quad", Targets::SPIRV | Targets::METAL | Targets::GLSL); } #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_empty() { - convert_wgsl("empty", Language::all()); + convert_wgsl("empty", Targets::SPIRV | Targets::METAL | Targets::GLSL); } #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_boids() { - convert_wgsl("boids", Language::METAL | Language::SPIRV); + convert_wgsl("boids", Targets::SPIRV | Targets::METAL); } #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_skybox() { - convert_wgsl("skybox", Language::all()); + convert_wgsl("skybox", Targets::SPIRV | Targets::METAL | Targets::GLSL); } #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_collatz() { - convert_wgsl("collatz", Language::METAL | Language::SPIRV); + convert_wgsl( + "collatz", + Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS, + ); } #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_shadow() { - convert_wgsl("shadow", Language::METAL | Language::SPIRV); + convert_wgsl("shadow", Targets::SPIRV | Targets::METAL); } #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_texture_array() { - convert_wgsl("texture-array", Language::SPIRV); + convert_wgsl("texture-array", Targets::SPIRV); } #[cfg(feature = "spv-in")] -fn convert_spv(name: &str) { +fn convert_spv(name: &str, targets: Targets) { let module = naga::front::spv::parse_u8_slice( &std::fs::read(format!("tests/in/{}{}", name, ".spv")).expect("Couldn't find spv file"), &Default::default(), ) .unwrap(); + check_targets(&module, name, targets); naga::proc::Validator::new().validate(&module).unwrap(); - - #[cfg(feature = "serialize")] - { - let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); - let output = ron::ser::to_string_pretty(&module, config).unwrap(); - with_snapshot_settings(|| { - insta::assert_snapshot!(format!("{}.ron", name), output); - }); - } } #[cfg(feature = "spv-in")] #[test] fn convert_spv_shadow() { - convert_spv("shadow"); + convert_spv("shadow", Targets::IR | Targets::ANALYSIS); } #[cfg(feature = "glsl-in")] -fn convert_glsl(name: &str, entry_points: naga::FastHashMap) { - let params = match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { - Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), - Err(_) => Parameters::default(), - }; - +fn convert_glsl( + name: &str, + entry_points: naga::FastHashMap, + targets: Targets, +) { let module = naga::front::glsl::parse_str( &std::fs::read_to_string(format!("tests/in/{}{}", name, ".glsl")) .expect("Couldn't find glsl file"), @@ -270,20 +288,7 @@ fn convert_glsl(name: &str, entry_points: naga::FastHashMap Date: Thu, 18 Feb 2021 05:37:56 +0100 Subject: [PATCH 0512/2212] [wgsl] allow empty for statement headers --- src/front/wgsl/mod.rs | 46 ++++++++++++++++++++++++++--------------- src/front/wgsl/tests.rs | 10 +++++++++ 2 files changed, 39 insertions(+), 17 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index dd631448a..120d332ba 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1813,16 +1813,24 @@ impl Parser { let mut block = Vec::new(); lexer.expect(Token::Paren('('))?; - let initialization = - self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)?; - let condition = self.parse_general_expression(lexer, context.as_expression())?; - lexer.expect(Token::Separator(';'))?; - let mut continuing = None; - // manually parse the next statement here instead of calling parse_statement - // because the statement is not terminated with a semicolon - if let Token::Word(ident) = lexer.peek() { + let initialization = if lexer.skip(Token::Separator(';')) { + None + } else { + self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)? + }; + let condition = if lexer.skip(Token::Separator(';')) { + None + } else { + let condition = + Some(self.parse_general_expression(lexer, context.as_expression())?); + lexer.expect(Token::Separator(';'))?; + condition + }; + let continuing = if let Token::Word(ident) = lexer.peek() { + // manually parse the next statement here instead of calling parse_statement + // because the statement is not terminated with a semicolon let _ = lexer.next(); - continuing = Some(match context.lookup_ident.get(ident) { + Some(match context.lookup_ident.get(ident) { Some(&var_expr) => { let left = self.parse_postfix(lexer, context.as_expression(), var_expr)?; @@ -1843,19 +1851,23 @@ impl Parser { arguments, } } - }); - } + }) + } else { + None + }; lexer.expect(Token::Paren(')'))?; lexer.expect(Token::Paren('{'))?; block.extend(initialization); - let mut body = [crate::Statement::If { - condition, - accept: Vec::new(), - reject: [crate::Statement::Break].to_vec(), - }] - .to_vec(); + let mut body = Vec::new(); + if let Some(condition) = condition { + body.push(crate::Statement::If { + condition, + accept: Vec::new(), + reject: [crate::Statement::Break].to_vec(), + }); + } while !lexer.skip(Token::Paren('}')) { let s = self.parse_statement(lexer, context.reborrow(), false)?; body.extend(s); diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 9a419f600..e24b4f88d 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -144,6 +144,16 @@ fn parse_loop() { ", ) .unwrap(); + parse_str( + " + fn main() { + for(;;) { + break; + } + } + ", + ) + .unwrap(); } #[test] From 9f113bdd950085ff012bfe28576c0f66cb3e1bcb Mon Sep 17 00:00:00 2001 From: Systemcluster Date: Thu, 18 Feb 2021 06:29:37 +0100 Subject: [PATCH 0513/2212] [wgsl] limit allowed for statement initializer statements --- src/front/wgsl/mod.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 120d332ba..1903eb408 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -62,6 +62,8 @@ pub enum Error<'a> { BadTypeCast(&'a str), #[error(transparent)] InvalidResolve(ResolveError), + #[error("invalid statement {0:?}, expected {1}")] + InvalidStatement(crate::Statement, &'a str), #[error("unknown import: `{0}`")] UnknownImport(&'a str), #[error("unknown storage class: `{0}`")] @@ -1816,7 +1818,19 @@ impl Parser { let initialization = if lexer.skip(Token::Separator(';')) { None } else { - self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)? + let statement = + self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)?; + match statement { + Some(crate::Statement::Store { .. }) + | Some(crate::Statement::Call { .. }) => statement, + Some(other) => { + return Err(Error::InvalidStatement( + other, + "variable, assignment or function call", + )) + } + None => None, + } }; let condition = if lexer.skip(Token::Separator(';')) { None From 19e7f456c46560ffecf5714e7414525bee2cbcbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 18 Feb 2021 12:14:04 +0000 Subject: [PATCH 0514/2212] Remove the call graph processor Uses the GlobalUse in glsl-out to check for function availability --- examples/convert.rs | 16 ++++---- src/back/glsl/features.rs | 4 +- src/back/glsl/mod.rs | 58 ++++++++++---------------- src/proc/analyzer.rs | 10 +++++ src/proc/call_graph.rs | 85 --------------------------------------- src/proc/mod.rs | 4 -- tests/snapshots.rs | 3 +- 7 files changed, 41 insertions(+), 139 deletions(-) delete mode 100644 src/proc/call_graph.rs diff --git a/examples/convert.rs b/examples/convert.rs index f3919ee89..01522b1f3 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -249,15 +249,13 @@ fn main() { let name = args.get(4).map_or("main", |p| p.as_str()).to_string(); let options = glsl::Options { version, - entry_point: ( - match stage { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - _ => unreachable!(), - }, - name, - ), + shader_stage: match stage { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + _ => unreachable!(), + }, + entry_point: name, }; let file = fs::OpenOptions::new() diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 4f75cbd09..283c2ac7d 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -175,8 +175,6 @@ impl<'a, W> Writer<'a, W> { /// If the version doesn't support any of the needed [`Features`](Features) a /// [`Error::MissingFeatures`](super::Error::MissingFeatures) will be returned pub(super) fn collect_required_features(&mut self) -> BackendResult { - let stage = self.options.entry_point.0; - if let Some(depth_test) = self.entry_point.early_depth_test { self.features.request(Features::IMAGE_LOAD_STORE); @@ -185,7 +183,7 @@ impl<'a, W> Writer<'a, W> { } } - if let ShaderStage::Compute = stage { + if let ShaderStage::Compute = self.options.shader_stage { self.features.request(Features::COMPUTE_SHADER) } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 58a46287f..50d238eb8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -44,10 +44,7 @@ pub use features::Features; use crate::{ - proc::{ - analyzer::Analysis, CallGraph, CallGraphBuilder, NameKey, Namer, ResolveContext, - ResolveError, Typifier, - }, + proc::{analyzer::Analysis, NameKey, Namer, ResolveContext, ResolveError, Typifier}, Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ScalarValue, @@ -129,11 +126,13 @@ impl fmt::Display for Version { pub struct Options { /// The glsl version to be used pub version: Version, - /// The name and stage of the entry point + /// The stage of the entry point + pub shader_stage: ShaderStage, + /// The name of the entry point /// /// If no entry point that matches is found a error will be thrown while creating a new instance /// of [`Writer`](struct.Writer.html) - pub entry_point: (ShaderStage, String), + pub entry_point: String, } /// Structure that connects a texture to a sampler or not @@ -275,8 +274,6 @@ pub struct Writer<'a, W> { entry_point: &'a crate::EntryPoint, /// The index of the selected entry point entry_point_idx: crate::proc::EntryPointIndex, - /// The current entry point call_graph (doesn't contain the entry point) - call_graph: CallGraph, /// Used to generate a unique number for blocks block_id: IdGenerator, } @@ -301,12 +298,12 @@ impl<'a, W: Write> Writer<'a, W> { } // Try to find the entry point and corresponding index - let (ep_idx, ep) = module + let (ep_idx, (_, ep)) = module .entry_points .iter() .enumerate() - .find_map(|(i, (key, entry_point))| { - Some((i as u16, entry_point)).filter(|_| &options.entry_point == key) + .find(|(_, ((stage, name), _))| { + options.shader_stage == *stage && &options.entry_point == name }) .ok_or(Error::EntryPointNotFound)?; @@ -314,12 +311,6 @@ impl<'a, W: Write> Writer<'a, W> { let mut names = FastHashMap::default(); Namer::default().reset(module, keywords::RESERVED_KEYWORDS, &mut names); - // Generate a call graph for the entry point - let call_graph = CallGraphBuilder { - functions: &module.functions, - } - .process(&ep.function); - // Build the instance let mut this = Self { module, @@ -330,8 +321,7 @@ impl<'a, W: Write> Writer<'a, W> { features: FeaturesManager::new(), names, entry_point: ep, - entry_point_idx: ep_idx, - call_graph, + entry_point_idx: ep_idx as u16, block_id: IdGenerator::default(), }; @@ -407,7 +397,7 @@ impl<'a, W: Write> Writer<'a, W> { let ep_info = self .analysis - .get_entry_point(self.options.entry_point.0, &self.options.entry_point.1); + .get_entry_point(self.options.shader_stage, &self.options.entry_point); // Write the globals // @@ -475,25 +465,19 @@ impl<'a, W: Write> Writer<'a, W> { _ => self.write_global(handle, global)?, } } + // Write all regular functions + for (handle, function) in self.module.functions.iter() { + // Check that the function doesn't use globals that aren't supported + // by the current entry point + if !ep_info.dominates_global_use(&self.analysis[handle]) { + continue; + } - // Sort the graph topologically so that functions calls are valid - // It's impossible for this to panic because the IR forbids cycles - let functions = petgraph::algo::toposort(&self.call_graph, None).unwrap(); - - // Write all regular functions that are in the call graph this is important - // because other functions might require for example globals that weren't written - for node in functions { - // We do this inside the loop instead of using `map` to satisfy the borrow checker - let handle = self.call_graph[node]; // We also `clone` to satisfy the borrow checker let name = self.names[&NameKey::Function(handle)].clone(); // Write the function - self.write_function( - FunctionType::Function(handle), - &self.module.functions[handle], - name, - )?; + self.write_function(FunctionType::Function(handle), function, name)?; writeln!(self.out)?; } @@ -692,7 +676,7 @@ impl<'a, W: Write> Writer<'a, W> { // // TODO: Should this throw an error? if let Some(interpolation) = global.interpolation { - match (self.options.entry_point.0, global.class) { + match (self.options.shader_stage, global.class) { (ShaderStage::Fragment, StorageClass::Input) | (ShaderStage::Vertex, StorageClass::Output) => { write!(self.out, "{} ", glsl_interpolation(interpolation)?)?; @@ -731,7 +715,7 @@ impl<'a, W: Write> Writer<'a, W> { format!( "_location_{}{}", location, - match (self.options.entry_point.0, global.class) { + match (self.options.shader_stage, global.class) { (ShaderStage::Fragment, StorageClass::Input) => "_vs", (ShaderStage::Vertex, StorageClass::Output) => "_vs", _ => "", @@ -1755,7 +1739,7 @@ impl<'a, W: Write> Writer<'a, W> { use std::collections::hash_map::Entry; let info = self .analysis - .get_entry_point(self.options.entry_point.0, &self.options.entry_point.1); + .get_entry_point(self.options.shader_stage, &self.options.entry_point); let mut mappings = FastHashMap::default(); for sampling in info.sampling_set.iter() { diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 04081d646..805d344f5 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -99,6 +99,16 @@ impl FunctionInfo { pub fn expression_count(&self) -> usize { self.expressions.len() } + pub fn dominates_global_use(&self, other: &Self) -> bool { + for (self_global_uses, other_global_uses) in + self.global_uses.iter().zip(other.global_uses.iter()) + { + if !self_global_uses.contains(*other_global_uses) { + return false; + } + } + true + } } impl ops::Index> for FunctionInfo { diff --git a/src/proc/call_graph.rs b/src/proc/call_graph.rs deleted file mode 100644 index 9c604bfe9..000000000 --- a/src/proc/call_graph.rs +++ /dev/null @@ -1,85 +0,0 @@ -use crate::{ - arena::{Arena, Handle}, - proc::{Interface, Visitor}, - Function, -}; -use bit_set::BitSet; -use petgraph::{ - graph::{DefaultIx, NodeIndex}, - Graph, -}; - -pub type CallGraph = Graph, ()>; - -pub struct CallGraphBuilder<'a> { - pub functions: &'a Arena, -} - -impl<'a> CallGraphBuilder<'a> { - pub fn process(&self, func: &Function) -> CallGraph { - let mut graph = Graph::new(); - let mut children = Vec::new(); - let mut mask = BitSet::with_capacity(func.expressions.len()); - - let visitor = CallGraphVisitor { - children: &mut children, - }; - - let mut interface = Interface { - expressions: &func.expressions, - local_variables: &func.local_variables, - visitor, - mask: &mut mask, - }; - - interface.traverse(&func.body); - - for handle in children { - let id = graph.add_node(handle); - self.collect(handle, id, &mut graph, &mut mask); - } - - graph - } - - fn collect( - &self, - handle: Handle, - id: NodeIndex, - graph: &mut CallGraph, - mask: &mut BitSet, - ) { - let mut children = Vec::new(); - let visitor = CallGraphVisitor { - children: &mut children, - }; - let func = &self.functions[handle]; - mask.clear(); - - let mut interface = Interface { - expressions: &func.expressions, - local_variables: &func.local_variables, - visitor, - mask, - }; - - interface.traverse(&func.body); - - for handle in children { - let child_id = graph.add_node(handle); - graph.add_edge(id, child_id, ()); - - self.collect(handle, child_id, graph, mask); - } - } -} - -struct CallGraphVisitor<'a> { - children: &'a mut Vec>, -} - -impl<'a> Visitor for CallGraphVisitor<'a> { - fn visit_fun(&mut self, func: Handle) { - self.children.push(func) - } -} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 4e111aa93..3f545fb27 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,8 +1,6 @@ //! Module processing functionality. pub mod analyzer; -#[cfg(feature = "petgraph")] -mod call_graph; mod interface; mod layouter; mod namer; @@ -10,8 +8,6 @@ mod terminator; mod typifier; mod validator; -#[cfg(feature = "petgraph")] -pub use call_graph::{CallGraph, CallGraphBuilder}; pub use interface::{Interface, Visitor}; pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index f5148c7db..f68f4d6af 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -187,7 +187,8 @@ fn check_output_glsl( let options = glsl::Options { version: glsl::Version::Embedded(310), - entry_point: (stage, ep_name.to_string()), + shader_stage: stage, + entry_point: ep_name.to_string(), }; let mut buffer = Vec::new(); From db0a8875d9d77059d4bd8ea65b531674db7d60c0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 19 Feb 2021 15:29:39 -0500 Subject: [PATCH 0515/2212] TypifyError with the expression handle --- examples/convert.rs | 10 +++++----- src/back/glsl/mod.rs | 4 ++-- src/back/msl/mod.rs | 14 ++++++-------- src/back/spv/writer.rs | 4 ++-- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 12 +++++++++--- src/proc/validator.rs | 4 ++-- 7 files changed, 27 insertions(+), 23 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 01522b1f3..7e832e016 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -158,16 +158,16 @@ fn main() { } }; - // validate the IR - let analysis = naga::proc::Validator::new() - .validate(&module) - .unwrap_pretty(); - if args.len() <= 2 { println!("{:#?}", module); return; } + // validate the IR + let analysis = naga::proc::Validator::new() + .validate(&module) + .unwrap_pretty(); + match Path::new(&args[2]) .extension() .expect("Output has no extension?") diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 50d238eb8..ae22cb213 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -44,7 +44,7 @@ pub use features::Features; use crate::{ - proc::{analyzer::Analysis, NameKey, Namer, ResolveContext, ResolveError, Typifier}, + proc::{analyzer::Analysis, NameKey, Namer, ResolveContext, TypifyError, Typifier}, Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ScalarValue, @@ -220,7 +220,7 @@ pub enum Error { IoError(#[from] IoError), /// The [`Module`](crate::Module) failed type resolution #[error("Type error: {0}")] - Type(#[from] ResolveError), + Type(#[from] TypifyError), /// The specified [`Version`](Version) doesn't have all required [`Features`](super) /// /// Contains the missing [`Features`](Features) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 0953a5dad..585593ab5 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -16,7 +16,7 @@ we move them up to the root output structure that we define ourselves. use crate::{ arena::Handle, - proc::{analyzer::Analysis, ResolveError}, + proc::{analyzer::Analysis, TypifyError}, FastHashMap, }; use std::{ @@ -60,7 +60,7 @@ enum ResolvedBinding { pub enum Error { IO(IoError), Utf8(FromUtf8Error), - Type(ResolveError), + Type(TypifyError), MissingBindTarget(BindSource), InvalidImageAccess(crate::StorageAccess), BadName(String), @@ -87,8 +87,8 @@ impl From for Error { } } -impl From for Error { - fn from(e: ResolveError) -> Self { +impl From for Error { + fn from(e: TypifyError) -> Self { Error::Type(e) } } @@ -155,10 +155,8 @@ impl Options { group, binding, }; - self.binding_map - .get(&source) - .cloned() - .map(ResolvedBinding::Resource) + ResolvedBinding::Resource( + self.binding_map.get(&source).cloned(). .ok_or(Error::MissingBindTarget(source)) } None => { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d71a84db2..a6c279358 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -4,7 +4,7 @@ use crate::{ arena::{Arena, Handle}, proc::{ analyzer::{Analysis, FunctionInfo}, - Layouter, ResolveContext, ResolveError, Typifier, + Layouter, ResolveContext, TypifyError, Typifier, }, }; use spirv::Word; @@ -22,7 +22,7 @@ pub enum Error { #[error("unimplemented {0:}")] FeatureNotImplemented(&'static str), #[error(transparent)] - Resolve(#[from] ResolveError), + Resolve(#[from] TypifyError), } struct Block { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 3f545fb27..5ec34408b 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -12,7 +12,7 @@ pub use interface::{Interface, Visitor}; pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; -pub use typifier::{ResolveContext, ResolveError, Typifier}; +pub use typifier::{ResolveContext, ResolveError, Typifier, TypifyError}; pub use validator::{ValidationError, Validator}; impl From for super::ScalarKind { diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 9bea6137c..8cffd5bfd 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -62,6 +62,10 @@ pub enum ResolveError { }, } +#[derive(Clone, Debug, Error, PartialEq)] +#[error("Type resolution of {0:?} failed: {1}")] +pub struct TypifyError(Handle, #[source] ResolveError); + pub struct ResolveContext<'a> { pub constants: &'a Arena, pub global_vars: &'a Arena, @@ -527,10 +531,12 @@ impl Typifier { expressions: &Arena, types: &Arena, ctx: &ResolveContext, - ) -> Result<(), ResolveError> { + ) -> Result<(), TypifyError> { self.clear(); - for (_, expr) in expressions.iter() { - let resolution = self.resolve_impl(expr, types, ctx)?; + for (handle, expr) in expressions.iter() { + let resolution = self + .resolve_impl(expr, types, ctx) + .map_err(|err| TypifyError(handle, err))?; self.resolutions.push(resolution); } Ok(()) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 50dc7ac79..55bc96023 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -1,6 +1,6 @@ use super::{ analyzer::{Analysis, AnalysisError, FunctionInfo, GlobalUse}, - typifier::{ResolveContext, ResolveError, Typifier}, + typifier::{TypifyError, ResolveContext, Typifier}, }; use crate::arena::{Arena, Handle}; use bit_set::BitSet; @@ -78,7 +78,7 @@ pub enum LocalVariableError { #[derive(Clone, Debug, thiserror::Error)] pub enum FunctionError { #[error(transparent)] - Resolve(#[from] ResolveError), + Resolve(#[from] TypifyError), #[error("There are instructions after `return`/`break`/`continue`")] InvalidControlFlowExitTail, #[error("Local variable {handle:?} '{name}' is invalid: {error:?}")] From 0e3f745fb203c0df47ca2f587469dc2bc3ed7363 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 19 Feb 2021 16:40:44 -0500 Subject: [PATCH 0516/2212] [msl] derive thiserror --- src/back/glsl/mod.rs | 2 +- src/back/msl/mod.rs | 47 ++++++++++++++++-------------------------- src/back/msl/writer.rs | 31 +++++++++++++++------------- src/back/spv/writer.rs | 2 +- src/proc/validator.rs | 2 +- 5 files changed, 38 insertions(+), 46 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ae22cb213..6a0a74a94 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -44,7 +44,7 @@ pub use features::Features; use crate::{ - proc::{analyzer::Analysis, NameKey, Namer, ResolveContext, TypifyError, Typifier}, + proc::{analyzer::Analysis, NameKey, Namer, ResolveContext, Typifier, TypifyError}, Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ScalarValue, diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 585593ab5..9adeed2c6 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -56,43 +56,30 @@ enum ResolvedBinding { // Note: some of these should be removed in favor of proper IR validation. -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] pub enum Error { - IO(IoError), - Utf8(FromUtf8Error), - Type(TypifyError), + #[error(transparent)] + IO(#[from] IoError), + #[error(transparent)] + Utf8(#[from] FromUtf8Error), + #[error(transparent)] + Type(#[from] TypifyError), + #[error("bind source for {0:?} is missing from the map")] MissingBindTarget(BindSource), - InvalidImageAccess(crate::StorageAccess), - BadName(String), + #[error("bind target {0:?} is empty")] UnimplementedBindTarget(BindTarget), + #[error("composing of {0:?} is not implemented yet")] UnsupportedCompose(Handle), + #[error("operation {0:?} is not implemented yet")] UnsupportedBinaryOp(crate::BinaryOperator), - UnexpectedSampleLevel(crate::SampleLevel), + #[error("standard function '{0}' is not implemented yet")] UnsupportedCall(String), - UnsupportedDynamicArrayLength, + #[error("feature '{0}' is not implemented yet")] FeatureNotImplemented(String), - /// The source IR is not valid. + #[error("module is not valid")] Validation, } -impl From for Error { - fn from(e: IoError) -> Self { - Error::IO(e) - } -} - -impl From for Error { - fn from(e: FromUtf8Error) -> Self { - Error::Utf8(e) - } -} - -impl From for Error { - fn from(e: TypifyError) -> Self { - Error::Type(e) - } -} - #[derive(Clone, Copy, Debug)] enum LocationMode { VertexInput, @@ -155,8 +142,10 @@ impl Options { group, binding, }; - ResolvedBinding::Resource( - self.binding_map.get(&source).cloned(). + self.binding_map + .get(&source) + .cloned() + .map(ResolvedBinding::Resource) .ok_or(Error::MissingBindTarget(source)) } None => { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 99bc0974c..69086c260 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -680,20 +680,23 @@ impl Writer { } => { self.put_local_call(function, arguments, context)?; } - crate::Expression::ArrayLength(expr) => match *self - .typifier - .get(expr, &context.module.types) - { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(const_handle), - .. - } => { - let size_str = &self.names[&NameKey::Constant(const_handle)]; - write!(self.out, "{}", size_str)?; + crate::Expression::ArrayLength(expr) => { + match *self.typifier.get(expr, &context.module.types) { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(const_handle), + .. + } => { + let size_str = &self.names[&NameKey::Constant(const_handle)]; + write!(self.out, "{}", size_str)?; + } + crate::TypeInner::Array { .. } => { + return Err(Error::FeatureNotImplemented( + "dynamic array size".to_string(), + )) + } + _ => return Err(Error::Validation), } - crate::TypeInner::Array { .. } => return Err(Error::UnsupportedDynamicArrayLength), - _ => return Err(Error::Validation), - }, + } } Ok(()) } @@ -1025,7 +1028,7 @@ impl Writer { } else if global.storage_access.contains(crate::StorageAccess::LOAD) { "read" } else { - return Err(Error::InvalidImageAccess(global.storage_access)); + return Err(Error::Validation); }; ("texture", "", format.into(), access) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a6c279358..3476b480c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -4,7 +4,7 @@ use crate::{ arena::{Arena, Handle}, proc::{ analyzer::{Analysis, FunctionInfo}, - Layouter, ResolveContext, TypifyError, Typifier, + Layouter, ResolveContext, Typifier, TypifyError, }, }; use spirv::Word; diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 55bc96023..4188c8ba3 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -1,6 +1,6 @@ use super::{ analyzer::{Analysis, AnalysisError, FunctionInfo, GlobalUse}, - typifier::{TypifyError, ResolveContext, Typifier}, + typifier::{ResolveContext, Typifier, TypifyError}, }; use crate::arena::{Arena, Handle}; use bit_set::BitSet; From 99c1add3588484b189120bc2e19f462e182ae989 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 19 Feb 2021 17:26:49 -0500 Subject: [PATCH 0517/2212] [msl] fake bindings --- examples/convert.rs | 51 +++++++++++++++++++++++++-------------------- src/back/msl/mod.rs | 22 ++++++++++++------- tests/snapshots.rs | 3 ++- 3 files changed, 44 insertions(+), 32 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 7e832e016..03bdcdae0 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -40,7 +40,7 @@ struct Parameters { #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_capabilities: naga::FastHashSet, #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - mtl_bindings: naga::FastHashMap, + mtl_bindings: Option>, } trait PrettyResult { @@ -177,31 +177,36 @@ fn main() { #[cfg(feature = "msl-out")] "metal" => { use naga::back::msl; - let mut binding_map = msl::BindingMap::default(); - for (key, value) in params.mtl_bindings { - binding_map.insert( - msl::BindSource { - stage: match key.stage { - Stage::Vertex => naga::ShaderStage::Vertex, - Stage::Fragment => naga::ShaderStage::Fragment, - Stage::Compute => naga::ShaderStage::Compute, - }, - group: key.group, - binding: key.binding, - }, - msl::BindTarget { - buffer: value.buffer, - texture: value.texture, - sampler: value.sampler, - mutable: value.mutable, - }, - ); - } - let options = msl::Options { + let mut options = msl::Options { lang_version: (1, 0), + binding_map: msl::BindingMap::default(), spirv_cross_compatibility: false, - binding_map, + fake_missing_bindings: false, }; + if let Some(map) = params.mtl_bindings { + for (key, value) in map { + options.binding_map.insert( + msl::BindSource { + stage: match key.stage { + Stage::Vertex => naga::ShaderStage::Vertex, + Stage::Fragment => naga::ShaderStage::Fragment, + Stage::Compute => naga::ShaderStage::Compute, + }, + group: key.group, + binding: key.binding, + }, + msl::BindTarget { + buffer: value.buffer, + texture: value.texture, + sampler: value.sampler, + mutable: value.mutable, + }, + ); + } + } else { + log::warn!("Metal binding map is missing"); + options.fake_missing_bindings = true; + } let (msl, _) = msl::write_string(&module, &analysis, &options).unwrap(); fs::write(&args[2], msl).unwrap(); } diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 9adeed2c6..ecf9eee7d 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -92,18 +92,21 @@ enum LocationMode { pub struct Options { /// (Major, Minor) target version of the Metal Shading Language. pub lang_version: (u8, u8), - /// Make it possible to link different stages via SPIRV-Cross. - pub spirv_cross_compatibility: bool, /// Binding model mapping to Metal. pub binding_map: BindingMap, + /// Make it possible to link different stages via SPIRV-Cross. + pub spirv_cross_compatibility: bool, + /// Don't panic on missing bindings, instead generate invalid MSL. + pub fake_missing_bindings: bool, } impl Default for Options { fn default() -> Self { Options { lang_version: (1, 0), - spirv_cross_compatibility: false, binding_map: BindingMap::default(), + spirv_cross_compatibility: false, + fake_missing_bindings: false, } } } @@ -142,11 +145,14 @@ impl Options { group, binding, }; - self.binding_map - .get(&source) - .cloned() - .map(ResolvedBinding::Resource) - .ok_or(Error::MissingBindTarget(source)) + match self.binding_map.get(&source) { + Some(target) => Ok(ResolvedBinding::Resource(target.clone())), + None if self.fake_missing_bindings => Ok(ResolvedBinding::User { + prefix: "fake", + index: 0, + }), + None => Err(Error::MissingBindTarget(source)), + } } None => { log::error!("Missing binding for {:?}", var.name); diff --git a/tests/snapshots.rs b/tests/snapshots.rs index f68f4d6af..02e8cd2da 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -164,8 +164,9 @@ fn check_output_msl( } let options = msl::Options { lang_version: (1, 0), - spirv_cross_compatibility: false, binding_map, + spirv_cross_compatibility: false, + fake_missing_bindings: false, }; let (msl, _) = msl::write_string(module, analysis, &options).unwrap(); From 26e6c2bdacb7ccae62190eb75dea22cdb66bba16 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 19 Feb 2021 21:42:31 -0500 Subject: [PATCH 0518/2212] Use source attribute of errors --- examples/convert.rs | 29 +++++++++++++++-------- src/back/glsl/mod.rs | 4 ++-- src/front/glsl/error.rs | 1 + src/front/spv/error.rs | 1 + src/proc/typifier.rs | 2 +- src/proc/validator.rs | 51 ++++++++++++++++++++++++++--------------- 6 files changed, 57 insertions(+), 31 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 03bdcdae0..2174cdaf1 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -1,4 +1,4 @@ -use std::{env, fmt, fs, path::Path}; +use std::{env, error::Error, fs, path::Path}; #[derive(Hash, PartialEq, Eq, serde::Deserialize)] enum Stage { @@ -40,7 +40,7 @@ struct Parameters { #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_capabilities: naga::FastHashSet, #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - mtl_bindings: Option>, + mtl_bindings: naga::FastHashMap, } trait PrettyResult { @@ -48,12 +48,20 @@ trait PrettyResult { fn unwrap_pretty(self) -> Self::Target; } -impl PrettyResult for Result { +impl PrettyResult for Result { type Target = T; fn unwrap_pretty(self) -> T { match self { Result::Ok(value) => value, - Result::Err(e) => panic!("{}", e), + Result::Err(error) => { + println!("{}:", error); + let mut e = error.source(); + while let Some(source) = e { + println!("\t{}", source); + e = source.source(); + } + std::process::exit(1); + } } } } @@ -164,6 +172,7 @@ fn main() { } // validate the IR + #[allow(unused_variables)] let analysis = naga::proc::Validator::new() .validate(&module) .unwrap_pretty(); @@ -183,8 +192,11 @@ fn main() { spirv_cross_compatibility: false, fake_missing_bindings: false, }; - if let Some(map) = params.mtl_bindings { - for (key, value) in map { + if params.mtl_bindings.is_empty() { + log::warn!("Metal binding map is missing"); + options.fake_missing_bindings = true; + } else { + for (key, value) in params.mtl_bindings { options.binding_map.insert( msl::BindSource { stage: match key.stage { @@ -203,11 +215,8 @@ fn main() { }, ); } - } else { - log::warn!("Metal binding map is missing"); - options.fake_missing_bindings = true; } - let (msl, _) = msl::write_string(&module, &analysis, &options).unwrap(); + let (msl, _) = msl::write_string(&module, &analysis, &options).unwrap_pretty(); fs::write(&args[2], msl).unwrap(); } #[cfg(feature = "spv-out")] diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 6a0a74a94..31cabdecd 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -216,10 +216,10 @@ type BackendResult = Result<(), Error>; #[derive(Debug, Error)] pub enum Error { /// A error occurred while writing to the output - #[error("Io error: {0}")] + #[error("I/O error")] IoError(#[from] IoError), /// The [`Module`](crate::Module) failed type resolution - #[error("Type error: {0}")] + #[error("Type error")] Type(#[from] TypifyError), /// The specified [`Version`](Version) doesn't have all required [`Features`](super) /// diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 771c99db1..7fd4a2804 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -2,6 +2,7 @@ use super::parser::Token; use super::token::TokenMetadata; use std::{borrow::Cow, fmt, io}; +//TODO: use `thiserror` #[derive(Debug)] pub enum ErrorKind { EndOfFile, diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index c7bac4b17..b07053f98 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -1,6 +1,7 @@ use super::ModuleState; use crate::arena::Handle; +//TODO: use `thiserror` #[derive(Debug)] pub enum Error { InvalidHeader, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 8cffd5bfd..1ff75bc75 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -63,7 +63,7 @@ pub enum ResolveError { } #[derive(Clone, Debug, Error, PartialEq)] -#[error("Type resolution of {0:?} failed: {1}")] +#[error("Type resolution of {0:?} failed")] pub struct TypifyError(Handle, #[source] ResolveError); pub struct ResolveContext<'a> { diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 4188c8ba3..d44cc5e82 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -4,6 +4,7 @@ use super::{ }; use crate::arena::{Arena, Handle}; use bit_set::BitSet; +use thiserror::Error; const MAX_WORKGROUP_SIZE: u32 = 0x4000; @@ -26,7 +27,7 @@ pub struct Validator { bind_group_masks: Vec, } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, Error)] pub enum TypeError { #[error("The {0:?} scalar width {1} is not supported")] InvalidWidth(crate::ScalarKind, crate::Bytes), @@ -40,7 +41,7 @@ pub enum TypeError { MissingBlockDecoration, } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, Error)] pub enum ConstantError { #[error("The type doesn't match the constant")] InvalidType, @@ -50,7 +51,7 @@ pub enum ConstantError { UnresolvedSize(Handle), } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, Error)] pub enum GlobalVariableError { #[error("Usage isn't compatible with the storage class")] InvalidUsage, @@ -58,7 +59,7 @@ pub enum GlobalVariableError { InvalidType, #[error("Interpolation is not valid")] InvalidInterpolation, - #[error("Storage access {seen:?} exceed the allowed {allowed:?}")] + #[error("Storage access {seen:?} exceeds the allowed {allowed:?}")] InvalidStorageAccess { allowed: crate::StorageAccess, seen: crate::StorageAccess, @@ -69,29 +70,30 @@ pub enum GlobalVariableError { InvalidBuiltInType(crate::BuiltIn), } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, Error)] pub enum LocalVariableError { #[error("Initializer doesn't match the variable type")] InitializerType, } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, Error)] pub enum FunctionError { #[error(transparent)] Resolve(#[from] TypifyError), #[error("There are instructions after `return`/`break`/`continue`")] InvalidControlFlowExitTail, - #[error("Local variable {handle:?} '{name}' is invalid: {error:?}")] + #[error("Local variable {handle:?} '{name}' is invalid")] LocalVariable { handle: Handle, name: String, + #[source] error: LocalVariableError, }, #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")] InvalidArgumentType { index: usize, name: String }, } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, Error)] pub enum EntryPointError { #[error("Early depth test is not applicable")] UnexpectedEarlyDepthTest, @@ -115,32 +117,41 @@ pub enum EntryPointError { Function(#[from] FunctionError), } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, Error)] pub enum ValidationError { - #[error("Type {handle:?} '{name}' is invalid: {error:?}")] + #[error("Type {handle:?} '{name}' is invalid")] Type { handle: Handle, name: String, + #[source] error: TypeError, }, - #[error("Constant {handle:?} '{name}' is invalid: {error:?}")] + #[error("Constant {handle:?} '{name}' is invalid")] Constant { handle: Handle, name: String, + #[source] error: ConstantError, }, - #[error("Global variable {handle:?} '{name}' is invalid: {error:?}")] + #[error("Global variable {handle:?} '{name}' is invalid")] GlobalVariable { handle: Handle, name: String, + #[source] error: GlobalVariableError, }, - #[error("Function {0:?} is invalid: {1:?}")] - Function(Handle, FunctionError), - #[error("Entry point {name} at {stage:?} is invalid: {error:?}")] + #[error("Function {handle:?} '{name}' is invalid")] + Function { + handle: Handle, + name: String, + #[source] + error: FunctionError, + }, + #[error("Entry point {name} at {stage:?} is invalid")] EntryPoint { stage: crate::ShaderStage, name: String, + #[source] error: EntryPointError, }, #[error(transparent)] @@ -738,9 +749,13 @@ impl Validator { })?; } - for (fun_handle, fun) in module.functions.iter() { - self.validate_function(fun, &analysis[fun_handle], module) - .map_err(|e| ValidationError::Function(fun_handle, e))?; + for (handle, fun) in module.functions.iter() { + self.validate_function(fun, &analysis[handle], module) + .map_err(|error| ValidationError::Function { + handle, + name: fun.name.clone().unwrap_or_default(), + error, + })?; } for (&(stage, ref name), entry_point) in module.entry_points.iter() { From f03a99d6a3e670dbf3dbabc64afce300f162712d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 19 Feb 2021 23:15:12 -0500 Subject: [PATCH 0519/2212] Implement Debug for arena and handle --- src/arena.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 347dfe206..9af0808e4 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -45,7 +45,7 @@ impl Ord for Handle { } impl fmt::Debug for Handle { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "Handle({})", self.index) + write!(formatter, "[{}]", self.index) } } impl hash::Hash for Handle { @@ -81,7 +81,6 @@ impl Handle { /// Adding new items to the arena produces a strongly-typed [`Handle`]. /// The arena can be indexed using the given handle to obtain /// a reference to the stored item. -#[derive(Debug)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[cfg_attr( @@ -99,6 +98,11 @@ impl Default for Arena { Self::new() } } +impl fmt::Debug for Arena { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_map().entries(self.iter()).finish() + } +} impl Arena { /// Create a new arena with no initial capacity allocated. From 2a5c478b21976f4467e49155276415e31069e1dc Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 19 Feb 2021 23:48:48 -0500 Subject: [PATCH 0520/2212] Fix type resolves of matrix by vectors --- src/proc/typifier.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 1ff75bc75..11e17abf9 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -255,24 +255,24 @@ impl Typifier { } else if let crate::TypeInner::Scalar { .. } = *ty_right { self.resolutions[left.index()].clone() } else if let crate::TypeInner::Matrix { - columns, - rows: _, + columns: _, + rows, width, } = *ty_left { Resolution::Value(crate::TypeInner::Vector { - size: columns, + size: rows, kind: crate::ScalarKind::Float, width, }) } else if let crate::TypeInner::Matrix { - columns: _, - rows, + columns, + rows: _, width, } = *ty_right { Resolution::Value(crate::TypeInner::Vector { - size: rows, + size: columns, kind: crate::ScalarKind::Float, width, }) From fa7d4d8b51d4eeffe9f648d285466637f733a4a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Tal=C4=8D=C3=ADk?= Date: Sat, 20 Feb 2021 14:57:31 +0100 Subject: [PATCH 0521/2212] spv-in: fix if condition when merge node == false node format --- src/front/spv/flow.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 9a6c11366..f18746484 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -250,7 +250,6 @@ impl FlowGraph { accept: self.naga_traverse(true_node_index, Some(merge_node_index))?, reject: self.naga_traverse(false_node_index, Some(merge_node_index))?, }); - result.extend(self.naga_traverse(merge_node_index, stop_node_index)?); } else { result.push(crate::Statement::If { condition, @@ -258,10 +257,12 @@ impl FlowGraph { self.block_to_node[&true_id], Some(merge_node_index), )?, - reject: self.naga_traverse(merge_node_index, stop_node_index)?, + reject: vec![], }); } + result.extend(self.naga_traverse(merge_node_index, stop_node_index)?); + Ok(result) } Terminator::Switch { From ce84b1d1c0330241902a29a63fa37bcd5fae70a5 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Sat, 13 Feb 2021 17:24:31 -0330 Subject: [PATCH 0522/2212] [wgsl] Add parser error snapshot --- tests/errors.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 tests/errors.rs diff --git a/tests/errors.rs b/tests/errors.rs new file mode 100644 index 000000000..81841a82e --- /dev/null +++ b/tests/errors.rs @@ -0,0 +1,15 @@ +#[cfg(feature = "wgsl-in")] +macro_rules! err { + ($value:expr, @$snapshot:literal) => { + ::insta::assert_snapshot!(naga::front::wgsl::parse_str($value).expect_err("expected parser error").to_string(), @$snapshot); + }; +} + +#[cfg(feature = "wgsl-in")] +#[test] +fn function_without_identifier() { + err!( + "fn () {}", + @"error while parsing WGSL in scopes [FunctionDecl] at line 1 pos 4: unexpected token Paren('('), expected ident" + ); +} From 694a00afcbf2ed87944ff3aa8b703b5dcd22b715 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 22 Feb 2021 00:53:49 -0500 Subject: [PATCH 0523/2212] [spv-out] optimize if/else branching --- src/back/spv/writer.rs | 59 +-- tests/out/boids.spvasm.snap | 676 ++++++++++++++++------------------ tests/out/collatz.spvasm.snap | 140 ++++--- tests/out/shadow.spvasm.snap | 496 +++++++++++++------------ 4 files changed, 679 insertions(+), 692 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 3476b480c..212ac6fdc 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1875,31 +1875,48 @@ impl Writer { spirv::SelectionControl::NONE, )); - let accept_id = self.generate_id(); - let reject_id = self.generate_id(); + let accept_id = if accept.is_empty() { + None + } else { + Some(self.generate_id()) + }; + let reject_id = if reject.is_empty() { + None + } else { + Some(self.generate_id()) + }; + function.consume( block, - Instruction::branch_conditional(condition_id, accept_id, reject_id), + Instruction::branch_conditional( + condition_id, + accept_id.unwrap_or(merge_id), + reject_id.unwrap_or(merge_id), + ), ); - self.write_block( - accept_id, - accept, - ir_module, - ir_function, - function, - Some(merge_id), - loop_context, - )?; - self.write_block( - reject_id, - reject, - ir_module, - ir_function, - function, - Some(merge_id), - loop_context, - )?; + if let Some(block_id) = accept_id { + self.write_block( + block_id, + accept, + ir_module, + ir_function, + function, + Some(merge_id), + loop_context, + )?; + } + if let Some(block_id) = reject_id { + self.write_block( + block_id, + reject, + ir_module, + ir_function, + function, + Some(merge_id), + loop_context, + )?; + } block = Block::new(merge_id); } diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index dd7691411..0736aad44 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -5,7 +5,7 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 298 +; Bound: 286 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -25,44 +25,44 @@ OpName %26 "vel" OpName %27 "i" OpName %29 "main" OpName %36 "gl_GlobalInvocationID" -OpName %45 "Particle" -OpMemberName %45 0 "pos" -OpMemberName %45 1 "vel" -OpName %49 "Particles" -OpMemberName %49 0 "particles" -OpName %50 "particlesSrc" -OpName %121 "SimParams" -OpMemberName %121 0 "deltaT" -OpMemberName %121 1 "rule1Distance" -OpMemberName %121 2 "rule2Distance" -OpMemberName %121 3 "rule3Distance" -OpMemberName %121 4 "rule1Scale" -OpMemberName %121 5 "rule2Scale" -OpMemberName %121 6 "rule3Scale" -OpName %122 "params" -OpName %274 "particlesDst" +OpName %44 "Particle" +OpMemberName %44 0 "pos" +OpMemberName %44 1 "vel" +OpName %48 "Particles" +OpMemberName %48 0 "particles" +OpName %49 "particlesSrc" +OpName %118 "SimParams" +OpMemberName %118 0 "deltaT" +OpMemberName %118 1 "rule1Distance" +OpMemberName %118 2 "rule2Distance" +OpMemberName %118 3 "rule3Distance" +OpMemberName %118 4 "rule1Scale" +OpMemberName %118 5 "rule2Scale" +OpMemberName %118 6 "rule3Scale" +OpName %119 "params" +OpName %262 "particlesDst" OpName %29 "main" OpDecorate %36 BuiltIn GlobalInvocationId -OpMemberDecorate %45 0 Offset 0 -OpMemberDecorate %45 1 Offset 8 -OpDecorate %47 ArrayStride 16 -OpDecorate %49 BufferBlock -OpMemberDecorate %49 0 Offset 0 -OpDecorate %50 NonWritable -OpDecorate %50 DescriptorSet 0 -OpDecorate %50 Binding 1 -OpDecorate %121 Block -OpMemberDecorate %121 0 Offset 0 -OpMemberDecorate %121 1 Offset 4 -OpMemberDecorate %121 2 Offset 8 -OpMemberDecorate %121 3 Offset 12 -OpMemberDecorate %121 4 Offset 16 -OpMemberDecorate %121 5 Offset 20 -OpMemberDecorate %121 6 Offset 24 -OpDecorate %122 DescriptorSet 0 -OpDecorate %122 Binding 0 -OpDecorate %274 DescriptorSet 0 -OpDecorate %274 Binding 2 +OpMemberDecorate %44 0 Offset 0 +OpMemberDecorate %44 1 Offset 8 +OpDecorate %46 ArrayStride 16 +OpDecorate %48 BufferBlock +OpMemberDecorate %48 0 Offset 0 +OpDecorate %49 NonWritable +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 1 +OpDecorate %118 Block +OpMemberDecorate %118 0 Offset 0 +OpMemberDecorate %118 1 Offset 4 +OpMemberDecorate %118 2 Offset 8 +OpMemberDecorate %118 3 Offset 12 +OpMemberDecorate %118 4 Offset 16 +OpMemberDecorate %118 5 Offset 20 +OpMemberDecorate %118 6 Offset 24 +OpDecorate %119 DescriptorSet 0 +OpDecorate %119 Binding 0 +OpDecorate %262 DescriptorSet 0 +OpDecorate %262 Binding 2 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1500 @@ -87,85 +87,85 @@ OpDecorate %274 Binding 2 %36 = OpVariable %37 Input %38 = OpTypePointer Input %9 %39 = OpConstant %4 0 -%45 = OpTypeStruct %16 %16 -%47 = OpTypeRuntimeArray %45 -%49 = OpTypeStruct %47 -%51 = OpTypePointer Uniform %49 -%50 = OpVariable %51 Uniform -%52 = OpTypePointer Uniform %47 -%53 = OpConstant %4 0 -%55 = OpTypePointer Input %9 -%56 = OpConstant %4 0 -%58 = OpTypePointer Uniform %45 -%59 = OpTypePointer Uniform %16 -%60 = OpConstant %4 0 -%65 = OpTypePointer Uniform %47 -%66 = OpConstant %4 0 -%68 = OpTypePointer Input %9 -%69 = OpConstant %4 0 -%71 = OpTypePointer Uniform %45 -%72 = OpTypePointer Uniform %16 -%73 = OpConstant %4 1 -%90 = OpTypePointer Input %9 -%91 = OpConstant %4 0 -%99 = OpTypePointer Uniform %47 -%100 = OpConstant %4 0 -%102 = OpTypePointer Uniform %45 -%103 = OpTypePointer Uniform %16 -%104 = OpConstant %4 0 -%109 = OpTypePointer Uniform %47 -%110 = OpConstant %4 0 -%112 = OpTypePointer Uniform %45 -%113 = OpTypePointer Uniform %16 -%114 = OpConstant %4 1 -%121 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 -%123 = OpTypePointer Uniform %121 -%122 = OpVariable %123 Uniform -%124 = OpTypePointer Uniform %6 -%125 = OpConstant %4 1 -%140 = OpTypePointer Uniform %6 -%141 = OpConstant %4 2 -%156 = OpTypePointer Uniform %6 -%157 = OpConstant %4 3 -%198 = OpTypePointer Uniform %6 -%199 = OpConstant %4 4 -%204 = OpTypePointer Uniform %6 -%205 = OpConstant %4 5 -%210 = OpTypePointer Uniform %6 -%211 = OpConstant %4 6 -%224 = OpTypePointer Uniform %6 -%225 = OpConstant %4 0 -%229 = OpTypePointer Function %6 -%230 = OpConstant %4 0 -%236 = OpTypePointer Function %6 -%237 = OpConstant %4 0 -%240 = OpTypePointer Function %6 -%241 = OpConstant %4 0 +%44 = OpTypeStruct %16 %16 +%46 = OpTypeRuntimeArray %44 +%48 = OpTypeStruct %46 +%50 = OpTypePointer Uniform %48 +%49 = OpVariable %50 Uniform +%51 = OpTypePointer Uniform %46 +%52 = OpConstant %4 0 +%54 = OpTypePointer Input %9 +%55 = OpConstant %4 0 +%57 = OpTypePointer Uniform %44 +%58 = OpTypePointer Uniform %16 +%59 = OpConstant %4 0 +%64 = OpTypePointer Uniform %46 +%65 = OpConstant %4 0 +%67 = OpTypePointer Input %9 +%68 = OpConstant %4 0 +%70 = OpTypePointer Uniform %44 +%71 = OpTypePointer Uniform %16 +%72 = OpConstant %4 1 +%88 = OpTypePointer Input %9 +%89 = OpConstant %4 0 +%96 = OpTypePointer Uniform %46 +%97 = OpConstant %4 0 +%99 = OpTypePointer Uniform %44 +%100 = OpTypePointer Uniform %16 +%101 = OpConstant %4 0 +%106 = OpTypePointer Uniform %46 +%107 = OpConstant %4 0 +%109 = OpTypePointer Uniform %44 +%110 = OpTypePointer Uniform %16 +%111 = OpConstant %4 1 +%118 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 +%120 = OpTypePointer Uniform %118 +%119 = OpVariable %120 Uniform +%121 = OpTypePointer Uniform %6 +%122 = OpConstant %4 1 +%136 = OpTypePointer Uniform %6 +%137 = OpConstant %4 2 +%151 = OpTypePointer Uniform %6 +%152 = OpConstant %4 3 +%190 = OpTypePointer Uniform %6 +%191 = OpConstant %4 4 +%196 = OpTypePointer Uniform %6 +%197 = OpConstant %4 5 +%202 = OpTypePointer Uniform %6 +%203 = OpConstant %4 6 +%216 = OpTypePointer Uniform %6 +%217 = OpConstant %4 0 +%221 = OpTypePointer Function %6 +%222 = OpConstant %4 0 +%227 = OpTypePointer Function %6 +%228 = OpConstant %4 0 +%231 = OpTypePointer Function %6 +%232 = OpConstant %4 0 +%237 = OpTypePointer Function %6 +%238 = OpConstant %4 0 +%241 = OpTypePointer Function %6 +%242 = OpConstant %4 1 %247 = OpTypePointer Function %6 -%248 = OpConstant %4 0 +%248 = OpConstant %4 1 %251 = OpTypePointer Function %6 %252 = OpConstant %4 1 -%258 = OpTypePointer Function %6 -%259 = OpConstant %4 1 -%262 = OpTypePointer Function %6 -%263 = OpConstant %4 1 -%269 = OpTypePointer Function %6 -%270 = OpConstant %4 1 -%274 = OpVariable %51 Uniform -%275 = OpTypePointer Uniform %47 -%276 = OpConstant %4 0 -%278 = OpTypePointer Input %9 -%279 = OpConstant %4 0 -%281 = OpTypePointer Uniform %45 -%282 = OpTypePointer Uniform %16 -%283 = OpConstant %4 0 -%288 = OpTypePointer Uniform %47 -%289 = OpConstant %4 0 -%291 = OpTypePointer Input %9 -%292 = OpConstant %4 0 -%294 = OpTypePointer Uniform %45 -%295 = OpTypePointer Uniform %16 -%296 = OpConstant %4 1 +%257 = OpTypePointer Function %6 +%258 = OpConstant %4 1 +%262 = OpVariable %50 Uniform +%263 = OpTypePointer Uniform %46 +%264 = OpConstant %4 0 +%266 = OpTypePointer Input %9 +%267 = OpConstant %4 0 +%269 = OpTypePointer Uniform %44 +%270 = OpTypePointer Uniform %16 +%271 = OpConstant %4 0 +%276 = OpTypePointer Uniform %46 +%277 = OpConstant %4 0 +%279 = OpTypePointer Input %9 +%280 = OpConstant %4 0 +%282 = OpTypePointer Uniform %44 +%283 = OpTypePointer Uniform %16 +%284 = OpConstant %4 1 %29 = OpFunction %2 None %30 %31 = OpLabel %27 = OpVariable %28 Function %8 @@ -182,259 +182,235 @@ OpDecorate %274 Binding 2 %40 = OpLoad %9 %34 %33 = OpUGreaterThanEqual %32 %40 %3 OpSelectionMerge %41 None -OpBranchConditional %33 %42 %43 +OpBranchConditional %33 %42 %41 %42 = OpLabel OpReturn -%43 = OpLabel -OpBranch %41 %41 = OpLabel -%48 = OpAccessChain %52 %50 %53 -%54 = OpAccessChain %55 %36 %56 -%57 = OpLoad %9 %54 -%46 = OpAccessChain %58 %48 %57 -%44 = OpAccessChain %59 %46 %60 -%61 = OpLoad %16 %44 -OpStore %15 %61 -%64 = OpAccessChain %65 %50 %66 -%67 = OpAccessChain %68 %36 %69 -%70 = OpLoad %9 %67 -%63 = OpAccessChain %71 %64 %70 -%62 = OpAccessChain %72 %63 %73 -%74 = OpLoad %16 %62 -OpStore %18 %74 +%47 = OpAccessChain %51 %49 %52 +%53 = OpAccessChain %54 %36 %55 +%56 = OpLoad %9 %53 +%45 = OpAccessChain %57 %47 %56 +%43 = OpAccessChain %58 %45 %59 +%60 = OpLoad %16 %43 +OpStore %15 %60 +%63 = OpAccessChain %64 %49 %65 +%66 = OpAccessChain %67 %36 %68 +%69 = OpLoad %9 %66 +%62 = OpAccessChain %70 %63 %69 +%61 = OpAccessChain %71 %62 %72 +%73 = OpLoad %16 %61 +OpStore %18 %73 +%74 = OpCompositeConstruct %16 %5 %5 +OpStore %19 %74 %75 = OpCompositeConstruct %16 %5 %5 -OpStore %19 %75 +OpStore %20 %75 %76 = OpCompositeConstruct %16 %5 %5 -OpStore %20 %76 -%77 = OpCompositeConstruct %16 %5 %5 -OpStore %21 %77 +OpStore %21 %76 +OpBranch %77 +%77 = OpLabel +OpLoopMerge %78 %80 None +OpBranch %79 +%79 = OpLabel +%82 = OpLoad %9 %27 +%81 = OpUGreaterThanEqual %32 %82 %3 +OpSelectionMerge %83 None +OpBranchConditional %81 %84 %83 +%84 = OpLabel OpBranch %78 -%78 = OpLabel -OpLoopMerge %79 %81 None +%83 = OpLabel +%86 = OpLoad %9 %27 +%87 = OpAccessChain %88 %36 %89 +%90 = OpLoad %9 %87 +%85 = OpIEqual %32 %86 %90 +OpSelectionMerge %91 None +OpBranchConditional %85 %92 %91 +%92 = OpLabel +OpBranch %80 +%91 = OpLabel +%95 = OpAccessChain %96 %49 %97 +%98 = OpLoad %9 %27 +%94 = OpAccessChain %99 %95 %98 +%93 = OpAccessChain %100 %94 %101 +%102 = OpLoad %16 %93 +OpStore %25 %102 +%105 = OpAccessChain %106 %49 %107 +%108 = OpLoad %9 %27 +%104 = OpAccessChain %109 %105 %108 +%103 = OpAccessChain %110 %104 %111 +%112 = OpLoad %16 %103 +OpStore %26 %112 +%114 = OpLoad %16 %25 +%115 = OpLoad %16 %15 +%116 = OpExtInst %6 %1 Distance %114 %115 +%117 = OpAccessChain %121 %119 %122 +%123 = OpLoad %6 %117 +%113 = OpFOrdLessThan %32 %116 %123 +OpSelectionMerge %124 None +OpBranchConditional %113 %125 %124 +%125 = OpLabel +%127 = OpLoad %16 %19 +%128 = OpLoad %16 %25 +%126 = OpFAdd %16 %127 %128 +OpStore %19 %126 +%130 = OpLoad %4 %22 +%129 = OpIAdd %4 %130 %10 +OpStore %22 %129 +OpBranch %124 +%124 = OpLabel +%132 = OpLoad %16 %25 +%133 = OpLoad %16 %15 +%134 = OpExtInst %6 %1 Distance %132 %133 +%135 = OpAccessChain %136 %119 %137 +%138 = OpLoad %6 %135 +%131 = OpFOrdLessThan %32 %134 %138 +OpSelectionMerge %139 None +OpBranchConditional %131 %140 %139 +%140 = OpLabel +%142 = OpLoad %16 %21 +%144 = OpLoad %16 %25 +%145 = OpLoad %16 %15 +%143 = OpFSub %16 %144 %145 +%141 = OpFSub %16 %142 %143 +OpStore %21 %141 +OpBranch %139 +%139 = OpLabel +%147 = OpLoad %16 %25 +%148 = OpLoad %16 %15 +%149 = OpExtInst %6 %1 Distance %147 %148 +%150 = OpAccessChain %151 %119 %152 +%153 = OpLoad %6 %150 +%146 = OpFOrdLessThan %32 %149 %153 +OpSelectionMerge %154 None +OpBranchConditional %146 %155 %154 +%155 = OpLabel +%157 = OpLoad %16 %20 +%158 = OpLoad %16 %26 +%156 = OpFAdd %16 %157 %158 +OpStore %20 %156 +%160 = OpLoad %4 %24 +%159 = OpIAdd %4 %160 %10 +OpStore %24 %159 +OpBranch %154 +%154 = OpLabel OpBranch %80 %80 = OpLabel -%83 = OpLoad %9 %27 -%82 = OpUGreaterThanEqual %32 %83 %3 -OpSelectionMerge %84 None -OpBranchConditional %82 %85 %86 -%85 = OpLabel -OpBranch %79 -%86 = OpLabel -OpBranch %84 -%84 = OpLabel -%88 = OpLoad %9 %27 -%89 = OpAccessChain %90 %36 %91 -%92 = OpLoad %9 %89 -%87 = OpIEqual %32 %88 %92 -OpSelectionMerge %93 None -OpBranchConditional %87 %94 %95 -%94 = OpLabel -OpBranch %81 -%95 = OpLabel -OpBranch %93 -%93 = OpLabel -%98 = OpAccessChain %99 %50 %100 -%101 = OpLoad %9 %27 -%97 = OpAccessChain %102 %98 %101 -%96 = OpAccessChain %103 %97 %104 -%105 = OpLoad %16 %96 -OpStore %25 %105 -%108 = OpAccessChain %109 %50 %110 -%111 = OpLoad %9 %27 -%107 = OpAccessChain %112 %108 %111 -%106 = OpAccessChain %113 %107 %114 -%115 = OpLoad %16 %106 -OpStore %26 %115 -%117 = OpLoad %16 %25 -%118 = OpLoad %16 %15 -%119 = OpExtInst %6 %1 Distance %117 %118 -%120 = OpAccessChain %124 %122 %125 -%126 = OpLoad %6 %120 -%116 = OpFOrdLessThan %32 %119 %126 -OpSelectionMerge %127 None -OpBranchConditional %116 %128 %129 -%128 = OpLabel -%131 = OpLoad %16 %19 -%132 = OpLoad %16 %25 -%130 = OpFAdd %16 %131 %132 -OpStore %19 %130 -%134 = OpLoad %4 %22 -%133 = OpIAdd %4 %134 %10 -OpStore %22 %133 -OpBranch %127 -%129 = OpLabel -OpBranch %127 -%127 = OpLabel -%136 = OpLoad %16 %25 -%137 = OpLoad %16 %15 -%138 = OpExtInst %6 %1 Distance %136 %137 -%139 = OpAccessChain %140 %122 %141 -%142 = OpLoad %6 %139 -%135 = OpFOrdLessThan %32 %138 %142 -OpSelectionMerge %143 None -OpBranchConditional %135 %144 %145 -%144 = OpLabel -%147 = OpLoad %16 %21 -%149 = OpLoad %16 %25 -%150 = OpLoad %16 %15 -%148 = OpFSub %16 %149 %150 -%146 = OpFSub %16 %147 %148 -OpStore %21 %146 -OpBranch %143 -%145 = OpLabel -OpBranch %143 -%143 = OpLabel -%152 = OpLoad %16 %25 -%153 = OpLoad %16 %15 -%154 = OpExtInst %6 %1 Distance %152 %153 -%155 = OpAccessChain %156 %122 %157 -%158 = OpLoad %6 %155 -%151 = OpFOrdLessThan %32 %154 %158 -OpSelectionMerge %159 None -OpBranchConditional %151 %160 %161 -%160 = OpLabel -%163 = OpLoad %16 %20 -%164 = OpLoad %16 %26 -%162 = OpFAdd %16 %163 %164 -OpStore %20 %162 -%166 = OpLoad %4 %24 -%165 = OpIAdd %4 %166 %10 -OpStore %24 %165 -OpBranch %159 -%161 = OpLabel -OpBranch %159 -%159 = OpLabel -OpBranch %81 -%81 = OpLabel -%168 = OpLoad %9 %27 -%167 = OpIAdd %9 %168 %11 -OpStore %27 %167 -OpBranch %78 -%79 = OpLabel -%170 = OpLoad %4 %22 -%169 = OpSGreaterThan %32 %170 %7 -OpSelectionMerge %171 None -OpBranchConditional %169 %172 %173 -%172 = OpLabel -%176 = OpLoad %16 %19 -%178 = OpLoad %4 %22 -%179 = OpConvertSToF %6 %178 -%177 = OpFDiv %6 %12 %179 -%175 = OpVectorTimesScalar %16 %176 %177 -%180 = OpLoad %16 %15 -%174 = OpFSub %16 %175 %180 -OpStore %19 %174 -OpBranch %171 -%173 = OpLabel -OpBranch %171 -%171 = OpLabel -%182 = OpLoad %4 %24 -%181 = OpSGreaterThan %32 %182 %7 -OpSelectionMerge %183 None -OpBranchConditional %181 %184 %185 -%184 = OpLabel -%187 = OpLoad %16 %20 -%189 = OpLoad %4 %24 -%190 = OpConvertSToF %6 %189 -%188 = OpFDiv %6 %12 %190 -%186 = OpVectorTimesScalar %16 %187 %188 -OpStore %20 %186 -OpBranch %183 -%185 = OpLabel -OpBranch %183 -%183 = OpLabel -%194 = OpLoad %16 %18 -%196 = OpLoad %16 %19 -%197 = OpAccessChain %198 %122 %199 -%200 = OpLoad %6 %197 -%195 = OpVectorTimesScalar %16 %196 %200 -%193 = OpFAdd %16 %194 %195 -%202 = OpLoad %16 %21 -%203 = OpAccessChain %204 %122 %205 -%206 = OpLoad %6 %203 -%201 = OpVectorTimesScalar %16 %202 %206 -%192 = OpFAdd %16 %193 %201 -%208 = OpLoad %16 %20 -%209 = OpAccessChain %210 %122 %211 -%212 = OpLoad %6 %209 -%207 = OpVectorTimesScalar %16 %208 %212 -%191 = OpFAdd %16 %192 %207 -OpStore %18 %191 +%162 = OpLoad %9 %27 +%161 = OpIAdd %9 %162 %11 +OpStore %27 %161 +OpBranch %77 +%78 = OpLabel +%164 = OpLoad %4 %22 +%163 = OpSGreaterThan %32 %164 %7 +OpSelectionMerge %165 None +OpBranchConditional %163 %166 %165 +%166 = OpLabel +%169 = OpLoad %16 %19 +%171 = OpLoad %4 %22 +%172 = OpConvertSToF %6 %171 +%170 = OpFDiv %6 %12 %172 +%168 = OpVectorTimesScalar %16 %169 %170 +%173 = OpLoad %16 %15 +%167 = OpFSub %16 %168 %173 +OpStore %19 %167 +OpBranch %165 +%165 = OpLabel +%175 = OpLoad %4 %24 +%174 = OpSGreaterThan %32 %175 %7 +OpSelectionMerge %176 None +OpBranchConditional %174 %177 %176 +%177 = OpLabel +%179 = OpLoad %16 %20 +%181 = OpLoad %4 %24 +%182 = OpConvertSToF %6 %181 +%180 = OpFDiv %6 %12 %182 +%178 = OpVectorTimesScalar %16 %179 %180 +OpStore %20 %178 +OpBranch %176 +%176 = OpLabel +%186 = OpLoad %16 %18 +%188 = OpLoad %16 %19 +%189 = OpAccessChain %190 %119 %191 +%192 = OpLoad %6 %189 +%187 = OpVectorTimesScalar %16 %188 %192 +%185 = OpFAdd %16 %186 %187 +%194 = OpLoad %16 %21 +%195 = OpAccessChain %196 %119 %197 +%198 = OpLoad %6 %195 +%193 = OpVectorTimesScalar %16 %194 %198 +%184 = OpFAdd %16 %185 %193 +%200 = OpLoad %16 %20 +%201 = OpAccessChain %202 %119 %203 +%204 = OpLoad %6 %201 +%199 = OpVectorTimesScalar %16 %200 %204 +%183 = OpFAdd %16 %184 %199 +OpStore %18 %183 +%206 = OpLoad %16 %18 +%207 = OpExtInst %16 %1 Normalize %206 +%208 = OpLoad %16 %18 +%209 = OpExtInst %6 %1 Length %208 +%210 = OpExtInst %6 %1 FClamp %209 %5 %13 +%205 = OpVectorTimesScalar %16 %207 %210 +OpStore %18 %205 +%212 = OpLoad %16 %15 %214 = OpLoad %16 %18 -%215 = OpExtInst %16 %1 Normalize %214 -%216 = OpLoad %16 %18 -%217 = OpExtInst %6 %1 Length %216 -%218 = OpExtInst %6 %1 FClamp %217 %5 %13 -%213 = OpVectorTimesScalar %16 %215 %218 -OpStore %18 %213 -%220 = OpLoad %16 %15 -%222 = OpLoad %16 %18 -%223 = OpAccessChain %224 %122 %225 -%226 = OpLoad %6 %223 -%221 = OpVectorTimesScalar %16 %222 %226 -%219 = OpFAdd %16 %220 %221 -OpStore %15 %219 -%228 = OpAccessChain %229 %15 %230 -%231 = OpLoad %6 %228 -%227 = OpFOrdLessThan %32 %231 %14 -OpSelectionMerge %232 None -OpBranchConditional %227 %233 %234 -%233 = OpLabel -%235 = OpAccessChain %236 %15 %237 -OpStore %235 %12 -OpBranch %232 +%215 = OpAccessChain %216 %119 %217 +%218 = OpLoad %6 %215 +%213 = OpVectorTimesScalar %16 %214 %218 +%211 = OpFAdd %16 %212 %213 +OpStore %15 %211 +%220 = OpAccessChain %221 %15 %222 +%223 = OpLoad %6 %220 +%219 = OpFOrdLessThan %32 %223 %14 +OpSelectionMerge %224 None +OpBranchConditional %219 %225 %224 +%225 = OpLabel +%226 = OpAccessChain %227 %15 %228 +OpStore %226 %12 +OpBranch %224 +%224 = OpLabel +%230 = OpAccessChain %231 %15 %232 +%233 = OpLoad %6 %230 +%229 = OpFOrdGreaterThan %32 %233 %12 +OpSelectionMerge %234 None +OpBranchConditional %229 %235 %234 +%235 = OpLabel +%236 = OpAccessChain %237 %15 %238 +OpStore %236 %14 +OpBranch %234 %234 = OpLabel -OpBranch %232 -%232 = OpLabel -%239 = OpAccessChain %240 %15 %241 -%242 = OpLoad %6 %239 -%238 = OpFOrdGreaterThan %32 %242 %12 -OpSelectionMerge %243 None -OpBranchConditional %238 %244 %245 -%244 = OpLabel -%246 = OpAccessChain %247 %15 %248 -OpStore %246 %14 -OpBranch %243 +%240 = OpAccessChain %241 %15 %242 +%243 = OpLoad %6 %240 +%239 = OpFOrdLessThan %32 %243 %14 +OpSelectionMerge %244 None +OpBranchConditional %239 %245 %244 %245 = OpLabel -OpBranch %243 -%243 = OpLabel +%246 = OpAccessChain %247 %15 %248 +OpStore %246 %12 +OpBranch %244 +%244 = OpLabel %250 = OpAccessChain %251 %15 %252 %253 = OpLoad %6 %250 -%249 = OpFOrdLessThan %32 %253 %14 +%249 = OpFOrdGreaterThan %32 %253 %12 OpSelectionMerge %254 None -OpBranchConditional %249 %255 %256 +OpBranchConditional %249 %255 %254 %255 = OpLabel -%257 = OpAccessChain %258 %15 %259 -OpStore %257 %12 -OpBranch %254 -%256 = OpLabel +%256 = OpAccessChain %257 %15 %258 +OpStore %256 %14 OpBranch %254 %254 = OpLabel -%261 = OpAccessChain %262 %15 %263 -%264 = OpLoad %6 %261 -%260 = OpFOrdGreaterThan %32 %264 %12 -OpSelectionMerge %265 None -OpBranchConditional %260 %266 %267 -%266 = OpLabel -%268 = OpAccessChain %269 %15 %270 -OpStore %268 %14 -OpBranch %265 -%267 = OpLabel -OpBranch %265 -%265 = OpLabel -%273 = OpAccessChain %275 %274 %276 -%277 = OpAccessChain %278 %36 %279 -%280 = OpLoad %9 %277 -%272 = OpAccessChain %281 %273 %280 -%271 = OpAccessChain %282 %272 %283 -%284 = OpLoad %16 %15 -OpStore %271 %284 -%287 = OpAccessChain %288 %274 %289 -%290 = OpAccessChain %291 %36 %292 -%293 = OpLoad %9 %290 -%286 = OpAccessChain %294 %287 %293 -%285 = OpAccessChain %295 %286 %296 -%297 = OpLoad %16 %18 -OpStore %285 %297 +%261 = OpAccessChain %263 %262 %264 +%265 = OpAccessChain %266 %36 %267 +%268 = OpLoad %9 %265 +%260 = OpAccessChain %269 %261 %268 +%259 = OpAccessChain %270 %260 %271 +%272 = OpLoad %16 %15 +OpStore %259 %272 +%275 = OpAccessChain %276 %262 %277 +%278 = OpAccessChain %279 %36 %280 +%281 = OpLoad %9 %278 +%274 = OpAccessChain %282 %275 %281 +%273 = OpAccessChain %283 %274 %284 +%285 = OpLoad %16 %18 +OpStore %273 %285 OpReturn OpFunctionEnd diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index 8bdea00cd..9817753c0 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -5,28 +5,28 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 70 +; Bound: 69 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %39 "main" %53 -OpExecutionMode %39 LocalSize 1 1 1 +OpEntryPoint GLCompute %38 "main" %52 +OpExecutionMode %38 LocalSize 1 1 1 OpSource GLSL 450 OpName %8 "n" OpName %10 "i" OpName %12 "collatz_iterations" -OpName %39 "main" -OpName %45 "PrimeIndices" -OpMemberName %45 0 "data" -OpName %46 "v_indices" -OpName %53 "global_id" -OpName %39 "main" -OpDecorate %43 ArrayStride 4 -OpDecorate %45 BufferBlock -OpMemberDecorate %45 0 Offset 0 -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 0 -OpDecorate %53 BuiltIn GlobalInvocationId +OpName %38 "main" +OpName %44 "PrimeIndices" +OpMemberName %44 0 "data" +OpName %45 "v_indices" +OpName %52 "global_id" +OpName %38 "main" +OpDecorate %42 ArrayStride 4 +OpDecorate %44 BufferBlock +OpMemberDecorate %44 0 Offset 0 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 0 +OpDecorate %52 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -36,25 +36,25 @@ OpDecorate %53 BuiltIn GlobalInvocationId %9 = OpTypePointer Function %4 %13 = OpTypeFunction %4 %4 %19 = OpTypeBool -%40 = OpTypeFunction %2 -%43 = OpTypeRuntimeArray %4 -%45 = OpTypeStruct %43 -%47 = OpTypePointer Uniform %45 -%46 = OpVariable %47 Uniform -%48 = OpTypePointer Uniform %43 -%49 = OpTypeInt 32 1 -%50 = OpConstant %49 0 -%52 = OpTypeVector %4 3 -%54 = OpTypePointer Input %52 -%53 = OpVariable %54 Input -%55 = OpTypePointer Input %4 -%56 = OpConstant %49 0 -%58 = OpTypePointer Uniform %4 -%62 = OpTypePointer Uniform %43 -%63 = OpConstant %49 0 -%65 = OpTypePointer Input %4 -%66 = OpConstant %49 0 -%68 = OpTypePointer Uniform %4 +%39 = OpTypeFunction %2 +%42 = OpTypeRuntimeArray %4 +%44 = OpTypeStruct %42 +%46 = OpTypePointer Uniform %44 +%45 = OpVariable %46 Uniform +%47 = OpTypePointer Uniform %42 +%48 = OpTypeInt 32 1 +%49 = OpConstant %48 0 +%51 = OpTypeVector %4 3 +%53 = OpTypePointer Input %51 +%52 = OpVariable %53 Input +%54 = OpTypePointer Input %4 +%55 = OpConstant %48 0 +%57 = OpTypePointer Uniform %4 +%61 = OpTypePointer Uniform %42 +%62 = OpConstant %48 0 +%64 = OpTypePointer Input %4 +%65 = OpConstant %48 0 +%67 = OpTypePointer Uniform %4 %12 = OpFunction %4 None %13 %11 = OpFunctionParameter %4 %14 = OpLabel @@ -69,51 +69,49 @@ OpBranch %17 %21 = OpLoad %4 %8 %20 = OpULessThanEqual %19 %21 %5 OpSelectionMerge %22 None -OpBranchConditional %20 %23 %24 +OpBranchConditional %20 %23 %22 %23 = OpLabel OpBranch %16 -%24 = OpLabel -OpBranch %22 %22 = OpLabel -%27 = OpLoad %4 %8 -%26 = OpUMod %4 %27 %6 -%25 = OpIEqual %19 %26 %3 -OpSelectionMerge %28 None -OpBranchConditional %25 %29 %30 -%29 = OpLabel -%32 = OpLoad %4 %8 -%31 = OpUDiv %4 %32 %6 -OpStore %8 %31 -OpBranch %28 -%30 = OpLabel -%35 = OpLoad %4 %8 -%34 = OpIMul %4 %7 %35 -%33 = OpIAdd %4 %34 %5 -OpStore %8 %33 -OpBranch %28 +%26 = OpLoad %4 %8 +%25 = OpUMod %4 %26 %6 +%24 = OpIEqual %19 %25 %3 +OpSelectionMerge %27 None +OpBranchConditional %24 %28 %29 %28 = OpLabel -%37 = OpLoad %4 %10 -%36 = OpIAdd %4 %37 %5 -OpStore %10 %36 +%31 = OpLoad %4 %8 +%30 = OpUDiv %4 %31 %6 +OpStore %8 %30 +OpBranch %27 +%29 = OpLabel +%34 = OpLoad %4 %8 +%33 = OpIMul %4 %7 %34 +%32 = OpIAdd %4 %33 %5 +OpStore %8 %32 +OpBranch %27 +%27 = OpLabel +%36 = OpLoad %4 %10 +%35 = OpIAdd %4 %36 %5 +OpStore %10 %35 OpBranch %18 %18 = OpLabel OpBranch %15 %16 = OpLabel -%38 = OpLoad %4 %10 -OpReturnValue %38 +%37 = OpLoad %4 %10 +OpReturnValue %37 OpFunctionEnd -%39 = OpFunction %2 None %40 -%41 = OpLabel -%44 = OpAccessChain %48 %46 %50 -%51 = OpAccessChain %55 %53 %56 -%57 = OpLoad %4 %51 -%42 = OpAccessChain %58 %44 %57 -%61 = OpAccessChain %62 %46 %63 -%64 = OpAccessChain %65 %53 %66 -%67 = OpLoad %4 %64 -%60 = OpAccessChain %68 %61 %67 -%69 = OpLoad %4 %60 -%59 = OpFunctionCall %4 %12 %69 -OpStore %42 %59 +%38 = OpFunction %2 None %39 +%40 = OpLabel +%43 = OpAccessChain %47 %45 %49 +%50 = OpAccessChain %54 %52 %55 +%56 = OpLoad %4 %50 +%41 = OpAccessChain %57 %43 %56 +%60 = OpAccessChain %61 %45 %62 +%63 = OpAccessChain %64 %52 %65 +%66 = OpLoad %4 %63 +%59 = OpAccessChain %67 %60 %66 +%68 = OpLoad %4 %59 +%58 = OpFunctionCall %4 %12 %68 +OpStore %41 %58 OpReturn OpFunctionEnd diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index cb7d42040..75f9f7a81 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -5,57 +5,57 @@ expression: dis ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 221 +; Bound: 219 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %64 "fs_main" %114 %111 %217 -OpExecutionMode %64 OriginUpperLeft +OpEntryPoint Fragment %63 "fs_main" %112 %109 %215 +OpExecutionMode %63 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_ambient" OpName %11 "c_max_lights" OpName %18 "fetch_shadow" -OpName %28 "t_shadow" -OpName %33 "sampler_shadow" -OpName %60 "color" -OpName %62 "i" -OpName %64 "fs_main" -OpName %76 "Globals" -OpMemberName %76 0 "num_lights" -OpName %77 "u_globals" -OpName %97 "Light" -OpMemberName %97 0 "proj" -OpMemberName %97 1 "pos" -OpMemberName %97 2 "color" -OpName %101 "Lights" -OpMemberName %101 0 "data" -OpName %102 "s_lights" -OpName %111 "in_position_fs" -OpName %114 "in_normal_fs" -OpName %217 "out_color_fs" -OpName %64 "fs_main" -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 2 -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 3 -OpDecorate %76 Block -OpMemberDecorate %76 0 Offset 0 -OpDecorate %77 DescriptorSet 0 -OpDecorate %77 Binding 0 -OpMemberDecorate %97 0 Offset 0 -OpMemberDecorate %97 0 ColMajor -OpMemberDecorate %97 0 MatrixStride 16 -OpMemberDecorate %97 1 Offset 64 -OpMemberDecorate %97 2 Offset 80 -OpDecorate %99 ArrayStride 96 -OpDecorate %101 BufferBlock -OpMemberDecorate %101 0 Offset 0 -OpDecorate %102 NonWritable -OpDecorate %102 DescriptorSet 0 -OpDecorate %102 Binding 1 -OpDecorate %111 Location 1 -OpDecorate %114 Location 0 -OpDecorate %217 Location 0 +OpName %27 "t_shadow" +OpName %32 "sampler_shadow" +OpName %59 "color" +OpName %61 "i" +OpName %63 "fs_main" +OpName %75 "Globals" +OpMemberName %75 0 "num_lights" +OpName %76 "u_globals" +OpName %95 "Light" +OpMemberName %95 0 "proj" +OpMemberName %95 1 "pos" +OpMemberName %95 2 "color" +OpName %99 "Lights" +OpMemberName %99 0 "data" +OpName %100 "s_lights" +OpName %109 "in_position_fs" +OpName %112 "in_normal_fs" +OpName %215 "out_color_fs" +OpName %63 "fs_main" +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 2 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 3 +OpDecorate %75 Block +OpMemberDecorate %75 0 Offset 0 +OpDecorate %76 DescriptorSet 0 +OpDecorate %76 Binding 0 +OpMemberDecorate %95 0 Offset 0 +OpMemberDecorate %95 0 ColMajor +OpMemberDecorate %95 0 MatrixStride 16 +OpMemberDecorate %95 1 Offset 64 +OpMemberDecorate %95 2 Offset 80 +OpDecorate %97 ArrayStride 96 +OpDecorate %99 BufferBlock +OpMemberDecorate %99 0 Offset 0 +OpDecorate %100 NonWritable +OpDecorate %100 DescriptorSet 0 +OpDecorate %100 Binding 1 +OpDecorate %109 Location 1 +OpDecorate %112 Location 0 +OpDecorate %215 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 @@ -72,92 +72,92 @@ OpDecorate %217 Location 0 %17 = OpTypeVector %4 4 %19 = OpTypeFunction %4 %12 %17 %21 = OpTypeBool -%27 = OpTypeImage %4 2D 1 1 0 1 Unknown -%29 = OpTypePointer UniformConstant %27 -%28 = OpVariable %29 UniformConstant -%31 = OpTypeSampledImage %27 -%32 = OpTypeSampler -%34 = OpTypePointer UniformConstant %32 -%33 = OpVariable %34 UniformConstant -%36 = OpTypeVector %4 2 -%50 = OpTypeInt 32 1 -%59 = OpConstant %4 0.0 -%61 = OpTypePointer Function %10 -%63 = OpTypePointer Function %12 -%65 = OpTypeFunction %2 -%74 = OpTypeVector %12 4 -%76 = OpTypeStruct %74 -%78 = OpTypePointer Uniform %76 -%77 = OpVariable %78 Uniform -%79 = OpTypePointer Uniform %74 -%80 = OpConstant %50 0 -%81 = OpTypePointer Uniform %12 -%82 = OpConstant %50 0 -%95 = OpTypeMatrix %17 4 -%97 = OpTypeStruct %95 %17 %17 -%99 = OpTypeRuntimeArray %97 -%101 = OpTypeStruct %99 -%103 = OpTypePointer Uniform %101 -%102 = OpVariable %103 Uniform -%104 = OpTypePointer Uniform %99 -%105 = OpConstant %50 0 -%107 = OpTypePointer Uniform %97 -%108 = OpTypePointer Uniform %95 -%109 = OpConstant %50 0 -%112 = OpTypePointer Input %17 -%111 = OpVariable %112 Input -%115 = OpTypePointer Input %10 -%114 = OpVariable %115 Input -%123 = OpTypePointer Uniform %99 -%124 = OpConstant %50 0 -%126 = OpTypePointer Uniform %97 -%127 = OpTypePointer Uniform %17 -%128 = OpConstant %50 1 -%129 = OpTypePointer Uniform %4 -%130 = OpConstant %50 0 -%136 = OpTypePointer Uniform %99 -%137 = OpConstant %50 0 -%139 = OpTypePointer Uniform %97 -%140 = OpTypePointer Uniform %17 -%141 = OpConstant %50 1 -%142 = OpTypePointer Uniform %4 -%143 = OpConstant %50 1 -%149 = OpTypePointer Uniform %99 -%150 = OpConstant %50 0 -%152 = OpTypePointer Uniform %97 -%153 = OpTypePointer Uniform %17 -%154 = OpConstant %50 1 -%155 = OpTypePointer Uniform %4 -%156 = OpConstant %50 2 -%160 = OpTypePointer Input %4 -%161 = OpConstant %50 0 -%164 = OpTypePointer Input %4 -%165 = OpConstant %50 1 -%168 = OpTypePointer Input %4 -%169 = OpConstant %50 2 -%179 = OpTypePointer Uniform %99 -%180 = OpConstant %50 0 -%182 = OpTypePointer Uniform %97 -%183 = OpTypePointer Uniform %17 -%184 = OpConstant %50 2 -%185 = OpTypePointer Uniform %4 -%186 = OpConstant %50 0 -%192 = OpTypePointer Uniform %99 -%193 = OpConstant %50 0 -%195 = OpTypePointer Uniform %97 -%196 = OpTypePointer Uniform %17 -%197 = OpConstant %50 2 -%198 = OpTypePointer Uniform %4 -%199 = OpConstant %50 1 -%205 = OpTypePointer Uniform %99 -%206 = OpConstant %50 0 -%208 = OpTypePointer Uniform %97 -%209 = OpTypePointer Uniform %17 -%210 = OpConstant %50 2 -%211 = OpTypePointer Uniform %4 -%212 = OpConstant %50 2 -%218 = OpTypePointer Output %17 -%217 = OpVariable %218 Output +%26 = OpTypeImage %4 2D 1 1 0 1 Unknown +%28 = OpTypePointer UniformConstant %26 +%27 = OpVariable %28 UniformConstant +%30 = OpTypeSampledImage %26 +%31 = OpTypeSampler +%33 = OpTypePointer UniformConstant %31 +%32 = OpVariable %33 UniformConstant +%35 = OpTypeVector %4 2 +%49 = OpTypeInt 32 1 +%58 = OpConstant %4 0.0 +%60 = OpTypePointer Function %10 +%62 = OpTypePointer Function %12 +%64 = OpTypeFunction %2 +%73 = OpTypeVector %12 4 +%75 = OpTypeStruct %73 +%77 = OpTypePointer Uniform %75 +%76 = OpVariable %77 Uniform +%78 = OpTypePointer Uniform %73 +%79 = OpConstant %49 0 +%80 = OpTypePointer Uniform %12 +%81 = OpConstant %49 0 +%93 = OpTypeMatrix %17 4 +%95 = OpTypeStruct %93 %17 %17 +%97 = OpTypeRuntimeArray %95 +%99 = OpTypeStruct %97 +%101 = OpTypePointer Uniform %99 +%100 = OpVariable %101 Uniform +%102 = OpTypePointer Uniform %97 +%103 = OpConstant %49 0 +%105 = OpTypePointer Uniform %95 +%106 = OpTypePointer Uniform %93 +%107 = OpConstant %49 0 +%110 = OpTypePointer Input %17 +%109 = OpVariable %110 Input +%113 = OpTypePointer Input %10 +%112 = OpVariable %113 Input +%121 = OpTypePointer Uniform %97 +%122 = OpConstant %49 0 +%124 = OpTypePointer Uniform %95 +%125 = OpTypePointer Uniform %17 +%126 = OpConstant %49 1 +%127 = OpTypePointer Uniform %4 +%128 = OpConstant %49 0 +%134 = OpTypePointer Uniform %97 +%135 = OpConstant %49 0 +%137 = OpTypePointer Uniform %95 +%138 = OpTypePointer Uniform %17 +%139 = OpConstant %49 1 +%140 = OpTypePointer Uniform %4 +%141 = OpConstant %49 1 +%147 = OpTypePointer Uniform %97 +%148 = OpConstant %49 0 +%150 = OpTypePointer Uniform %95 +%151 = OpTypePointer Uniform %17 +%152 = OpConstant %49 1 +%153 = OpTypePointer Uniform %4 +%154 = OpConstant %49 2 +%158 = OpTypePointer Input %4 +%159 = OpConstant %49 0 +%162 = OpTypePointer Input %4 +%163 = OpConstant %49 1 +%166 = OpTypePointer Input %4 +%167 = OpConstant %49 2 +%177 = OpTypePointer Uniform %97 +%178 = OpConstant %49 0 +%180 = OpTypePointer Uniform %95 +%181 = OpTypePointer Uniform %17 +%182 = OpConstant %49 2 +%183 = OpTypePointer Uniform %4 +%184 = OpConstant %49 0 +%190 = OpTypePointer Uniform %97 +%191 = OpConstant %49 0 +%193 = OpTypePointer Uniform %95 +%194 = OpTypePointer Uniform %17 +%195 = OpConstant %49 2 +%196 = OpTypePointer Uniform %4 +%197 = OpConstant %49 1 +%203 = OpTypePointer Uniform %97 +%204 = OpConstant %49 0 +%206 = OpTypePointer Uniform %95 +%207 = OpTypePointer Uniform %17 +%208 = OpConstant %49 2 +%209 = OpTypePointer Uniform %4 +%210 = OpConstant %49 2 +%216 = OpTypePointer Output %17 +%215 = OpVariable %216 Output %18 = OpFunction %4 None %19 %15 = OpFunctionParameter %12 %16 = OpFunctionParameter %17 @@ -165,133 +165,129 @@ OpDecorate %217 Location 0 %23 = OpCompositeExtract %4 %16 3 %22 = OpFOrdLessThanEqual %21 %23 %3 OpSelectionMerge %24 None -OpBranchConditional %22 %25 %26 +OpBranchConditional %22 %25 %24 %25 = OpLabel OpReturnValue %5 -%26 = OpLabel -OpBranch %24 %24 = OpLabel -%30 = OpLoad %27 %28 -%35 = OpLoad %32 %33 -%40 = OpCompositeExtract %4 %16 0 -%41 = OpCompositeExtract %4 %16 1 -%42 = OpCompositeConstruct %36 %40 %41 -%43 = OpCompositeConstruct %36 %6 %7 -%39 = OpFMul %36 %42 %43 -%45 = OpCompositeExtract %4 %16 3 -%44 = OpFDiv %4 %5 %45 -%38 = OpVectorTimesScalar %36 %39 %44 -%46 = OpCompositeConstruct %36 %6 %6 -%37 = OpFAdd %36 %38 %46 -%47 = OpCompositeExtract %4 %37 0 -%48 = OpCompositeExtract %4 %37 1 -%51 = OpBitcast %50 %15 -%49 = OpConvertUToF %4 %51 -%52 = OpCompositeConstruct %10 %47 %48 %49 -%53 = OpSampledImage %31 %30 %35 -%56 = OpCompositeExtract %4 %16 2 -%58 = OpCompositeExtract %4 %16 3 -%57 = OpFDiv %4 %5 %58 -%55 = OpFMul %4 %56 %57 -%54 = OpImageSampleDrefExplicitLod %4 %53 %52 %55 Lod %59 -OpReturnValue %54 +%29 = OpLoad %26 %27 +%34 = OpLoad %31 %32 +%39 = OpCompositeExtract %4 %16 0 +%40 = OpCompositeExtract %4 %16 1 +%41 = OpCompositeConstruct %35 %39 %40 +%42 = OpCompositeConstruct %35 %6 %7 +%38 = OpFMul %35 %41 %42 +%44 = OpCompositeExtract %4 %16 3 +%43 = OpFDiv %4 %5 %44 +%37 = OpVectorTimesScalar %35 %38 %43 +%45 = OpCompositeConstruct %35 %6 %6 +%36 = OpFAdd %35 %37 %45 +%46 = OpCompositeExtract %4 %36 0 +%47 = OpCompositeExtract %4 %36 1 +%50 = OpBitcast %49 %15 +%48 = OpConvertUToF %4 %50 +%51 = OpCompositeConstruct %10 %46 %47 %48 +%52 = OpSampledImage %30 %29 %34 +%55 = OpCompositeExtract %4 %16 2 +%57 = OpCompositeExtract %4 %16 3 +%56 = OpFDiv %4 %5 %57 +%54 = OpFMul %4 %55 %56 +%53 = OpImageSampleDrefExplicitLod %4 %52 %51 %54 Lod %58 +OpReturnValue %53 OpFunctionEnd -%64 = OpFunction %2 None %65 +%63 = OpFunction %2 None %64 +%65 = OpLabel +%59 = OpVariable %60 Function %9 +%61 = OpVariable %62 Function %13 +OpBranch %66 %66 = OpLabel -%60 = OpVariable %61 Function %9 -%62 = OpVariable %63 Function %13 +OpLoopMerge %67 %69 None +OpBranch %68 +%68 = OpLabel +%71 = OpLoad %12 %61 +%74 = OpAccessChain %78 %76 %79 +%72 = OpAccessChain %80 %74 %81 +%82 = OpLoad %12 %72 +%83 = OpExtInst %12 %1 UMin %82 %11 +%70 = OpUGreaterThanEqual %21 %71 %83 +OpSelectionMerge %84 None +OpBranchConditional %70 %85 %84 +%85 = OpLabel OpBranch %67 -%67 = OpLabel -OpLoopMerge %68 %70 None +%84 = OpLabel +%87 = OpLoad %10 %59 +%91 = OpLoad %12 %61 +%98 = OpAccessChain %102 %100 %103 +%104 = OpLoad %12 %61 +%96 = OpAccessChain %105 %98 %104 +%94 = OpAccessChain %106 %96 %107 +%108 = OpLoad %93 %94 +%111 = OpLoad %17 %109 +%92 = OpMatrixTimesVector %17 %108 %111 +%90 = OpFunctionCall %4 %18 %91 %92 +%114 = OpLoad %10 %112 +%115 = OpExtInst %10 %1 Normalize %114 +%120 = OpAccessChain %121 %100 %122 +%123 = OpLoad %12 %61 +%119 = OpAccessChain %124 %120 %123 +%118 = OpAccessChain %125 %119 %126 +%117 = OpAccessChain %127 %118 %128 +%129 = OpLoad %4 %117 +%133 = OpAccessChain %134 %100 %135 +%136 = OpLoad %12 %61 +%132 = OpAccessChain %137 %133 %136 +%131 = OpAccessChain %138 %132 %139 +%130 = OpAccessChain %140 %131 %141 +%142 = OpLoad %4 %130 +%146 = OpAccessChain %147 %100 %148 +%149 = OpLoad %12 %61 +%145 = OpAccessChain %150 %146 %149 +%144 = OpAccessChain %151 %145 %152 +%143 = OpAccessChain %153 %144 %154 +%155 = OpLoad %4 %143 +%156 = OpCompositeConstruct %10 %129 %142 %155 +%157 = OpAccessChain %158 %109 %159 +%160 = OpLoad %4 %157 +%161 = OpAccessChain %162 %109 %163 +%164 = OpLoad %4 %161 +%165 = OpAccessChain %166 %109 %167 +%168 = OpLoad %4 %165 +%169 = OpCompositeConstruct %10 %160 %164 %168 +%116 = OpFSub %10 %156 %169 +%170 = OpExtInst %10 %1 Normalize %116 +%171 = OpDot %4 %115 %170 +%172 = OpExtInst %4 %1 FMax %3 %171 +%89 = OpFMul %4 %90 %172 +%176 = OpAccessChain %177 %100 %178 +%179 = OpLoad %12 %61 +%175 = OpAccessChain %180 %176 %179 +%174 = OpAccessChain %181 %175 %182 +%173 = OpAccessChain %183 %174 %184 +%185 = OpLoad %4 %173 +%189 = OpAccessChain %190 %100 %191 +%192 = OpLoad %12 %61 +%188 = OpAccessChain %193 %189 %192 +%187 = OpAccessChain %194 %188 %195 +%186 = OpAccessChain %196 %187 %197 +%198 = OpLoad %4 %186 +%202 = OpAccessChain %203 %100 %204 +%205 = OpLoad %12 %61 +%201 = OpAccessChain %206 %202 %205 +%200 = OpAccessChain %207 %201 %208 +%199 = OpAccessChain %209 %200 %210 +%211 = OpLoad %4 %199 +%212 = OpCompositeConstruct %10 %185 %198 %211 +%88 = OpVectorTimesScalar %10 %212 %89 +%86 = OpFAdd %10 %87 %88 +OpStore %59 %86 OpBranch %69 %69 = OpLabel -%72 = OpLoad %12 %62 -%75 = OpAccessChain %79 %77 %80 -%73 = OpAccessChain %81 %75 %82 -%83 = OpLoad %12 %73 -%84 = OpExtInst %12 %1 UMin %83 %11 -%71 = OpUGreaterThanEqual %21 %72 %84 -OpSelectionMerge %85 None -OpBranchConditional %71 %86 %87 -%86 = OpLabel -OpBranch %68 -%87 = OpLabel -OpBranch %85 -%85 = OpLabel -%89 = OpLoad %10 %60 -%93 = OpLoad %12 %62 -%100 = OpAccessChain %104 %102 %105 -%106 = OpLoad %12 %62 -%98 = OpAccessChain %107 %100 %106 -%96 = OpAccessChain %108 %98 %109 -%110 = OpLoad %95 %96 -%113 = OpLoad %17 %111 -%94 = OpMatrixTimesVector %17 %110 %113 -%92 = OpFunctionCall %4 %18 %93 %94 -%116 = OpLoad %10 %114 -%117 = OpExtInst %10 %1 Normalize %116 -%122 = OpAccessChain %123 %102 %124 -%125 = OpLoad %12 %62 -%121 = OpAccessChain %126 %122 %125 -%120 = OpAccessChain %127 %121 %128 -%119 = OpAccessChain %129 %120 %130 -%131 = OpLoad %4 %119 -%135 = OpAccessChain %136 %102 %137 -%138 = OpLoad %12 %62 -%134 = OpAccessChain %139 %135 %138 -%133 = OpAccessChain %140 %134 %141 -%132 = OpAccessChain %142 %133 %143 -%144 = OpLoad %4 %132 -%148 = OpAccessChain %149 %102 %150 -%151 = OpLoad %12 %62 -%147 = OpAccessChain %152 %148 %151 -%146 = OpAccessChain %153 %147 %154 -%145 = OpAccessChain %155 %146 %156 -%157 = OpLoad %4 %145 -%158 = OpCompositeConstruct %10 %131 %144 %157 -%159 = OpAccessChain %160 %111 %161 -%162 = OpLoad %4 %159 -%163 = OpAccessChain %164 %111 %165 -%166 = OpLoad %4 %163 -%167 = OpAccessChain %168 %111 %169 -%170 = OpLoad %4 %167 -%171 = OpCompositeConstruct %10 %162 %166 %170 -%118 = OpFSub %10 %158 %171 -%172 = OpExtInst %10 %1 Normalize %118 -%173 = OpDot %4 %117 %172 -%174 = OpExtInst %4 %1 FMax %3 %173 -%91 = OpFMul %4 %92 %174 -%178 = OpAccessChain %179 %102 %180 -%181 = OpLoad %12 %62 -%177 = OpAccessChain %182 %178 %181 -%176 = OpAccessChain %183 %177 %184 -%175 = OpAccessChain %185 %176 %186 -%187 = OpLoad %4 %175 -%191 = OpAccessChain %192 %102 %193 -%194 = OpLoad %12 %62 -%190 = OpAccessChain %195 %191 %194 -%189 = OpAccessChain %196 %190 %197 -%188 = OpAccessChain %198 %189 %199 -%200 = OpLoad %4 %188 -%204 = OpAccessChain %205 %102 %206 -%207 = OpLoad %12 %62 -%203 = OpAccessChain %208 %204 %207 -%202 = OpAccessChain %209 %203 %210 -%201 = OpAccessChain %211 %202 %212 -%213 = OpLoad %4 %201 -%214 = OpCompositeConstruct %10 %187 %200 %213 -%90 = OpVectorTimesScalar %10 %214 %91 -%88 = OpFAdd %10 %89 %90 -OpStore %60 %88 -OpBranch %70 -%70 = OpLabel -%216 = OpLoad %12 %62 -%215 = OpIAdd %12 %216 %14 -OpStore %62 %215 -OpBranch %67 -%68 = OpLabel -%219 = OpLoad %10 %60 -%220 = OpCompositeConstruct %17 %219 %5 -OpStore %217 %220 +%214 = OpLoad %12 %61 +%213 = OpIAdd %12 %214 %14 +OpStore %61 %213 +OpBranch %66 +%67 = OpLabel +%217 = OpLoad %10 %59 +%218 = OpCompositeConstruct %17 %217 %5 +OpStore %215 %218 OpReturn OpFunctionEnd From c0d5a6bde48a7b5c904f20698d696e8f64f1d0c0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 21 Feb 2021 23:08:16 -0500 Subject: [PATCH 0524/2212] Rewrite the type validation --- src/proc/mod.rs | 2 +- src/proc/validator.rs | 211 ++++++++++++++++++++++++------------------ 2 files changed, 123 insertions(+), 90 deletions(-) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 5ec34408b..a8b40c13f 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -13,7 +13,7 @@ pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, Typifier, TypifyError}; -pub use validator::{ValidationError, Validator}; +pub use validator::{TypeFlags, ValidationError, Validator}; impl From for super::ScalarKind { fn from(format: super::StorageFormat) -> Self { diff --git a/src/proc/validator.rs b/src/proc/validator.rs index d44cc5e82..618a79061 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -10,9 +10,15 @@ const MAX_WORKGROUP_SIZE: u32 = 0x4000; bitflags::bitflags! { #[repr(transparent)] - struct TypeFlags: u8 { - const INTERFACE = 1; - const HOST_SHARED = 2; + pub struct TypeFlags: u8 { + /// Can be used for data variables. + const DATA = 0x1; + /// The data type has known size. + const SIZED = 0x2; + /// Can be be used for interfacing between pipeline stages. + const INTERFACE = 0x4; + /// Can be used for host-shareable structures. + const HOST_SHARED = 0x8; } } @@ -33,12 +39,16 @@ pub enum TypeError { InvalidWidth(crate::ScalarKind, crate::Bytes), #[error("The base handle {0:?} can not be resolved")] UnresolvedBase(Handle), + #[error("Expected data type, found {0:?}")] + InvalidData(Handle), + #[error("Type {0:?} can not be a part of a host-shared structure")] + InvalidHostSharedType(Handle), + #[error("Base type {0:?} for the array is invalid")] + InvalidArrayBaseType(Handle), #[error("The constant {0:?} can not be used for an array size")] InvalidArraySizeConstant(Handle), - #[error("Array doesn't have a stride decoration, can't be host-shared")] - MissingStrideDecoration, - #[error("Structure doesn't have a block decoration, can't be host-shared")] - MissingBlockDecoration, + #[error("Field {0} can't be dynamically-sized, has type {1:?}")] + InvalidDynamicArray(String, Handle), } #[derive(Clone, Debug, Error)] @@ -64,6 +74,11 @@ pub enum GlobalVariableError { allowed: crate::StorageAccess, seen: crate::StorageAccess, }, + #[error("Type flags {seen:?} do not meet the required {required:?}")] + MissingTypeFlags { + required: TypeFlags, + seen: TypeFlags, + }, #[error("Binding decoration is missing or not applicable")] InvalidBinding, #[error("BuiltIn type for {0:?} is invalid")] @@ -319,94 +334,93 @@ impl Validator { } } - fn fill_type_flags(&mut self, arena: &Arena) { - for (handle, ty) in arena.iter().rev() { - let flags = self.type_flags[handle.index()]; - match ty.inner { - crate::TypeInner::Array { base, .. } => { - //Note: don't assume anything about the indices, - // they are checked in `validate_type` later on. - if let Some(f) = self.type_flags.get_mut(base.index()) { - *f |= flags; - } - } - crate::TypeInner::Struct { ref members, .. } => { - for member in members { - if let Some(f) = self.type_flags.get_mut(member.ty.index()) { - *f |= flags; - } - } - } - _ => {} - } - } - } - fn validate_type( &self, ty: &crate::Type, handle: Handle, constants: &Arena, - ) -> Result<(), TypeError> { + ) -> Result { use crate::TypeInner as Ti; - match ty.inner { + Ok(match ty.inner { Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { if !Self::check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } + TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED } Ti::Matrix { width, .. } => { if !Self::check_width(crate::ScalarKind::Float, width) { return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); } + TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED } Ti::Pointer { base, class: _ } => { if base >= handle { return Err(TypeError::UnresolvedBase(base)); } + TypeFlags::DATA | TypeFlags::SIZED } Ti::Array { base, size, stride } => { if base >= handle { return Err(TypeError::UnresolvedBase(base)); } - if let crate::ArraySize::Constant(const_handle) = size { - match constants.try_get(const_handle) { - Some(&crate::Constant { - inner: - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(_), - }, - .. - }) => {} - other => { - log::warn!("Array size {:?}", other); - return Err(TypeError::InvalidArraySizeConstant(const_handle)); + let base_flags = self.type_flags[base.index()]; + if !base_flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { + return Err(TypeError::InvalidArrayBaseType(base)); + } + + let sized_flag = match size { + crate::ArraySize::Constant(const_handle) => { + match constants.try_get(const_handle) { + Some(&crate::Constant { + inner: + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(_), + }, + .. + }) => {} + other => { + log::warn!("Array size {:?}", other); + return Err(TypeError::InvalidArraySizeConstant(const_handle)); + } } + TypeFlags::SIZED } - } - //TODO: check stride - if stride.is_none() - && self.type_flags[handle.index()].contains(TypeFlags::HOST_SHARED) - { - return Err(TypeError::MissingStrideDecoration); - } + crate::ArraySize::Dynamic => TypeFlags::empty(), + }; + let shared_flag = if stride.is_none() { + TypeFlags::empty() + } else { + base_flags & TypeFlags::HOST_SHARED + }; + TypeFlags::DATA | sized_flag | shared_flag } Ti::Struct { block, ref members } => { - if !block && self.type_flags[handle.index()].contains(TypeFlags::HOST_SHARED) { - return Err(TypeError::MissingBlockDecoration); - } - //TODO: check the spans - for member in members { + let mut flags = TypeFlags::all(); + for (i, member) in members.iter().enumerate() { if member.ty >= handle { return Err(TypeError::UnresolvedBase(member.ty)); } + let base_flags = self.type_flags[member.ty.index()]; + flags &= base_flags; + if !base_flags.contains(TypeFlags::DATA) { + return Err(TypeError::InvalidData(member.ty)); + } + if block && !base_flags.contains(TypeFlags::HOST_SHARED) { + return Err(TypeError::InvalidHostSharedType(member.ty)); + } + // only the last field can be unsized + if i + 1 != members.len() && !base_flags.contains(TypeFlags::SIZED) { + let name = member.name.clone().unwrap_or_default(); + return Err(TypeError::InvalidDynamicArray(name, member.ty)); + } } + //TODO: check the spans + flags } - Ti::Image { .. } => {} - Ti::Sampler { comparison: _ } => {} - } - Ok(()) + Ti::Image { .. } | Ti::Sampler { .. } => TypeFlags::empty(), + }) } fn validate_constant( @@ -452,13 +466,16 @@ impl Validator { &self, var: &crate::GlobalVariable, types: &Arena, - ) -> Result { + ) -> Result<(), GlobalVariableError> { log::debug!("var {:?}", var); - let (allowed_storage_access, type_flags) = match var.class { + let (allowed_storage_access, required_type_flags) = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), crate::StorageClass::Input | crate::StorageClass::Output => { var.check_varying(types)?; - (crate::StorageAccess::empty(), TypeFlags::INTERFACE) + ( + crate::StorageAccess::empty(), + TypeFlags::DATA | TypeFlags::INTERFACE, + ) } crate::StorageClass::Storage => { var.check_resource()?; @@ -466,7 +483,10 @@ impl Validator { crate::TypeInner::Struct { .. } => (), _ => return Err(GlobalVariableError::InvalidType), } - (crate::StorageAccess::all(), TypeFlags::HOST_SHARED) + ( + crate::StorageAccess::all(), + TypeFlags::DATA | TypeFlags::HOST_SHARED, + ) } crate::StorageClass::Uniform => { var.check_resource()?; @@ -474,39 +494,54 @@ impl Validator { crate::TypeInner::Struct { .. } => (), _ => return Err(GlobalVariableError::InvalidType), } - (crate::StorageAccess::empty(), TypeFlags::HOST_SHARED) + ( + crate::StorageAccess::empty(), + TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED, + ) } crate::StorageClass::Handle => { var.check_resource()?; - let allowed_access = match types[var.ty].inner { + let access = match types[var.ty].inner { crate::TypeInner::Image { class: crate::ImageClass::Storage(_), .. } => crate::StorageAccess::all(), - _ => crate::StorageAccess::empty(), + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { + crate::StorageAccess::empty() + } + _ => return Err(GlobalVariableError::InvalidType), }; - (allowed_access, TypeFlags::empty()) + (access, TypeFlags::empty()) } crate::StorageClass::Private | crate::StorageClass::WorkGroup => { if var.binding.is_some() { return Err(GlobalVariableError::InvalidBinding); } var.forbid_interpolation()?; - (crate::StorageAccess::empty(), TypeFlags::empty()) - } - crate::StorageClass::PushConstant => { - (crate::StorageAccess::LOAD, TypeFlags::HOST_SHARED) + (crate::StorageAccess::empty(), TypeFlags::DATA) } + crate::StorageClass::PushConstant => ( + crate::StorageAccess::LOAD, + TypeFlags::DATA | TypeFlags::HOST_SHARED, + ), }; if !allowed_storage_access.contains(var.storage_access) { return Err(GlobalVariableError::InvalidStorageAccess { - allowed: allowed_storage_access, seen: var.storage_access, + allowed: allowed_storage_access, }); } - Ok(type_flags) + let type_flags = self.type_flags[var.ty.index()]; + if !type_flags.contains(required_type_flags) { + return Err(GlobalVariableError::MissingTypeFlags { + seen: type_flags, + required: required_type_flags, + }); + } + + Ok(()) } fn validate_local_var( @@ -726,27 +761,25 @@ impl Validator { })?; } - for (var_handle, var) in module.global_variables.iter() { - let ty_flags = self - .validate_global_var(var, &module.types) - .map_err(|error| ValidationError::GlobalVariable { - handle: var_handle, - name: var.name.clone().unwrap_or_default(), - error, - })?; - self.type_flags[var.ty.index()] |= ty_flags; - } - - self.fill_type_flags(&module.types); - // doing after the globals, so that `type_flags` is ready for (handle, ty) in module.types.iter() { - self.validate_type(ty, handle, &module.constants) + let ty_flags = self + .validate_type(ty, handle, &module.constants) .map_err(|error| ValidationError::Type { handle, name: ty.name.clone().unwrap_or_default(), error, })?; + self.type_flags[handle.index()] = ty_flags; + } + + for (var_handle, var) in module.global_variables.iter() { + self.validate_global_var(var, &module.types) + .map_err(|error| ValidationError::GlobalVariable { + handle: var_handle, + name: var.name.clone().unwrap_or_default(), + error, + })?; } for (handle, fun) in module.functions.iter() { From d3062a2f3b423f0d3bc5d44f133f63a1b150666d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 22 Feb 2021 13:52:38 -0500 Subject: [PATCH 0525/2212] Statement validation --- src/proc/validator.rs | 275 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 263 insertions(+), 12 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 618a79061..c018505f2 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -2,7 +2,10 @@ use super::{ analyzer::{Analysis, AnalysisError, FunctionInfo, GlobalUse}, typifier::{ResolveContext, Typifier, TypifyError}, }; -use crate::arena::{Arena, Handle}; +use crate::{ + arena::{Arena, Handle}, + FastHashSet, +}; use bit_set::BitSet; use thiserror::Error; @@ -22,6 +25,45 @@ bitflags::bitflags! { } } +bitflags::bitflags! { + #[repr(transparent)] + pub struct BlockFlags: u8 { + /// The control can jump out of this block. + const CAN_JUMP = 0x1; + /// The control is in a loop, can break and continue. + const IN_LOOP = 0x2; + } +} + +struct BlockContext<'a> { + flags: BlockFlags, + expressions: &'a Arena, + types: &'a Arena, + functions: &'a Arena, + return_type: Option>, +} + +impl<'a> BlockContext<'a> { + fn with_flags(&self, flags: BlockFlags) -> Self { + BlockContext { + flags, + expressions: self.expressions, + types: self.types, + functions: self.functions, + return_type: self.return_type, + } + } + + fn get_expression( + &self, + handle: Handle, + ) -> Result<&'a crate::Expression, FunctionError> { + self.expressions + .try_get(handle) + .ok_or(FunctionError::InvalidExpression(handle)) + } +} + #[derive(Debug)] pub struct Validator { //Note: this is a bit tricky: some of the front-ends as well as backends @@ -31,6 +73,7 @@ pub struct Validator { location_in_mask: BitSet, location_out_mask: BitSet, bind_group_masks: Vec, + select_cases: FastHashSet, } #[derive(Clone, Debug, Error)] @@ -95,8 +138,6 @@ pub enum LocalVariableError { pub enum FunctionError { #[error(transparent)] Resolve(#[from] TypifyError), - #[error("There are instructions after `return`/`break`/`continue`")] - InvalidControlFlowExitTail, #[error("Local variable {handle:?} '{name}' is invalid")] LocalVariable { handle: Handle, @@ -106,6 +147,50 @@ pub enum FunctionError { }, #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")] InvalidArgumentType { index: usize, name: String }, + #[error("There are instructions after `return`/`break`/`continue`")] + InstructionsAfterReturn, + #[error("The `break`/`continue` is used outside of a loop context")] + BreakContinueOutsideOfLoop, + #[error("The `return` is called within a `continuing` block")] + InvalidReturnSpot, + #[error("The `return` value {0:?} does not match the function return value")] + InvalidReturnType(Option>), + #[error("The `if` condition {0:?} is not a boolean scalar")] + InvalidIfType(Handle), + #[error("The `switch` value {0:?} is not an integer scalar")] + InvalidSwitchType(Handle), + #[error("Multiple `switch` cases for {0} are present")] + ConflictingSwitchCase(i32), + #[error("The value {0:?} can not be stored")] + InvalidStoreValue(Handle), + #[error("Store of {value:?} into {pointer:?} doesn't have matching types")] + InvalidStore { + pointer: Handle, + value: Handle, + }, + #[error("The image array can't be indexed by {0:?}")] + InvalidArrayIndex(Handle), + #[error("The expression {0:?} is currupted")] + InvalidExpression(Handle), + #[error("The expression {0:?} is not an image")] + InvalidImage(Handle), + #[error("The called function {0:?} is invalid")] + InvalidCall(Handle), + #[error( + "The called function {function:?} requires {required} arguments, but {seen} are provided" + )] + InvalidCallArgumentCount { + function: Handle, + required: usize, + seen: usize, + }, + #[error("The called function {function:?} argument {index} requires {required:?} type, but {seen:?} type is provided")] + InvalidCallArgumentType { + function: Handle, + index: usize, + required: Handle, + seen: Option>, + }, } #[derive(Clone, Debug, Error)] @@ -324,6 +409,7 @@ impl Validator { location_in_mask: BitSet::new(), location_out_mask: BitSet::new(), bind_group_masks: Vec::new(), + select_cases: FastHashSet::default(), } } @@ -572,6 +658,165 @@ impl Validator { Ok(()) } + fn validate_block( + &mut self, + statements: &[crate::Statement], + context: &BlockContext, + ) -> Result<(), FunctionError> { + use crate::{Statement as S, TypeInner as Ti}; + //TODO: handle the cases of totally invalid expression handles + let mut finished = false; + for statement in statements { + if finished { + return Err(FunctionError::InstructionsAfterReturn); + } + match *statement { + S::Block(ref block) => self.validate_block(block, context)?, + S::If { + condition, + ref accept, + ref reject, + } => { + match *self.typifier.get(condition, context.types) { + Ti::Scalar { + kind: crate::ScalarKind::Bool, + width: _, + } => {} + _ => return Err(FunctionError::InvalidIfType(condition)), + } + self.validate_block(accept, context)?; + self.validate_block(reject, context)?; + } + S::Switch { + selector, + ref cases, + ref default, + } => { + match *self.typifier.get(selector, context.types) { + Ti::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => {} + _ => return Err(FunctionError::InvalidSwitchType(selector)), + } + self.select_cases.clear(); + for case in cases { + if !self.select_cases.insert(case.value) { + return Err(FunctionError::ConflictingSwitchCase(case.value)); + } + } + for case in cases { + self.validate_block(&case.body, context)?; + } + self.validate_block(default, context)?; + } + S::Loop { + ref body, + ref continuing, + } => { + self.validate_block( + body, + &context.with_flags(BlockFlags::CAN_JUMP | BlockFlags::IN_LOOP), + )?; + self.validate_block(continuing, &context.with_flags(BlockFlags::empty()))?; + } + S::Break | S::Continue => { + if !context.flags.contains(BlockFlags::IN_LOOP) { + return Err(FunctionError::BreakContinueOutsideOfLoop); + } + finished = true; + } + S::Return { value } => { + if !context.flags.contains(BlockFlags::CAN_JUMP) { + return Err(FunctionError::InvalidReturnSpot); + } + let value_ty = value.map(|expr| self.typifier.get(expr, context.types)); + let expected_ty = context.return_type.map(|ty| &context.types[ty].inner); + if value_ty != expected_ty { + log::error!( + "Returning {:?} where {:?} is expected", + value_ty, + expected_ty + ); + return Err(FunctionError::InvalidReturnType(value)); + } + finished = true; + } + S::Kill => { + finished = true; + } + S::Store { pointer, value } => { + let value_ty = self.typifier.get(value, context.types); + match *value_ty { + Ti::Image { .. } | Ti::Sampler { .. } => { + return Err(FunctionError::InvalidStoreValue(value)); + } + _ => {} + } + if self.typifier.get(pointer, context.types) != value_ty { + return Err(FunctionError::InvalidStore { pointer, value }); + } + //TODO: validate that the `pointer` reaches a variable through a sequence of accessors + } + S::ImageStore { + image, + coordinate: _, + array_index, + value, + } => { + let _expected_coordinate_ty = match *context.get_expression(image)? { + crate::Expression::GlobalVariable(_var_handle) => (), //TODO + _ => return Err(FunctionError::InvalidImage(image)), + }; + let value_ty = self.typifier.get(value, context.types); + match *value_ty { + Ti::Scalar { .. } | Ti::Vector { .. } => {} + _ => { + return Err(FunctionError::InvalidStoreValue(value)); + } + } + if let Some(expr) = array_index { + match *self.typifier.get(expr, context.types) { + Ti::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => (), + _ => return Err(FunctionError::InvalidArrayIndex(expr)), + } + } + } + S::Call { + function, + ref arguments, + } => { + let fun = context + .functions + .try_get(function) + .ok_or(FunctionError::InvalidCall(function))?; + if fun.arguments.len() != arguments.len() { + return Err(FunctionError::InvalidCallArgumentCount { + function, + required: fun.arguments.len(), + seen: arguments.len(), + }); + } + for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { + let ty = self.typifier.get_handle(expr); + if ty != Ok(arg.ty) { + return Err(FunctionError::InvalidCallArgumentType { + function, + index, + required: arg.ty, + seen: ty.ok(), + }); + } + } + } + } + } + Ok(()) + } + fn validate_function( &mut self, fun: &crate::Function, @@ -598,18 +843,24 @@ impl Validator { } for (index, argument) in fun.arguments.iter().enumerate() { - match module.types[argument.ty].inner { - crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { - return Err(FunctionError::InvalidArgumentType { - index, - name: argument.name.clone().unwrap_or_default(), - }) - } - _ => (), + if !self.type_flags[argument.ty.index()].contains(TypeFlags::DATA) { + return Err(FunctionError::InvalidArgumentType { + index, + name: argument.name.clone().unwrap_or_default(), + }); } } - Ok(()) + self.validate_block( + &fun.body, + &BlockContext { + flags: BlockFlags::CAN_JUMP, + expressions: &fun.expressions, + types: &module.types, + functions: &module.functions, + return_type: fun.return_type, + }, + ) } fn validate_entry_point( From 0cefc1c46c81a290afbde09117539a8b8daa9a58 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 21 Feb 2021 06:29:30 -0500 Subject: [PATCH 0526/2212] Remove mutation from the Call expression --- src/back/glsl/mod.rs | 22 +- src/back/msl/writer.rs | 141 ++++++------- src/back/spv/writer.rs | 44 ++-- src/front/glsl/functions.rs | 17 +- src/front/spv/mod.rs | 25 +-- src/front/wgsl/mod.rs | 345 ++++++++++++++++++-------------- src/lib.rs | 24 ++- src/proc/analyzer.rs | 29 ++- src/proc/interface.rs | 12 +- src/proc/typifier.rs | 5 +- src/proc/validator.rs | 105 ++++++---- tests/out/collatz.info.ron.snap | 2 +- tests/out/collatz.msl.snap | 3 +- tests/out/collatz.ron.snap | 6 +- tests/out/collatz.spvasm.snap | 80 ++++---- tests/out/shadow.info.ron.snap | 2 +- tests/out/shadow.msl.snap | 10 +- tests/out/shadow.ron.snap | 16 +- tests/out/shadow.spvasm.snap | 134 ++++++------- tests/out/skybox.msl.snap | 6 +- 20 files changed, 561 insertions(+), 467 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 31cabdecd..38a416ac6 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -276,6 +276,8 @@ pub struct Writer<'a, W> { entry_point_idx: crate::proc::EntryPointIndex, /// Used to generate a unique number for blocks block_id: IdGenerator, + /// Set of expressions that have associated temporary variables + cached_expressions: FastHashMap, String>, } impl<'a, W: Write> Writer<'a, W> { @@ -324,6 +326,7 @@ impl<'a, W: Write> Writer<'a, W> { entry_point_idx: ep_idx as u16, block_id: IdGenerator::default(), + cached_expressions: FastHashMap::default(), }; // Find all features required to print this module @@ -1141,7 +1144,15 @@ impl<'a, W: Write> Writer<'a, W> { Statement::Call { function, ref arguments, + result, } => { + if let Some(expr) = result { + let name = format!("_expr{}", expr.index()); + let ty = self.module.functions[function].return_type.unwrap(); + self.write_type(ty)?; + write!(self.out, "{} = ", name)?; + self.cached_expressions.insert(expr, name); + } write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; writeln!(self.out, ");")? @@ -1682,14 +1693,9 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(expr, ctx)?; write!(self.out, ")")? } - // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list - Expression::Call { - function, - ref arguments, - } => { - write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; - self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; - write!(self.out, ")")? + Expression::Call(_function) => { + let name = &self.cached_expressions[&expr]; + write!(self.out, "{}", name)?; } // `ArrayLength` is written as `expr.length()` and we convert it to a uint Expression::ArrayLength(expr) => { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 69086c260..52dcc7158 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -16,6 +16,7 @@ use std::{ const NAMESPACE: &str = "metal"; const INDENT: &str = " "; +const BAKE_PREFIX: &str = "_expr"; #[derive(Clone)] struct Level(usize); @@ -207,40 +208,6 @@ impl Writer { Ok(()) } - fn put_local_call( - &mut self, - fun_handle: Handle, - parameters: &[Handle], - context: &ExpressionContext, - ) -> Result<(), Error> { - let fun_name = &self.names[&NameKey::Function(fun_handle)]; - write!(self.out, "{}(", fun_name)?; - // first, write down the actual arguments - for (i, &handle) in parameters.iter().enumerate() { - if i != 0 { - write!(self.out, ", ")?; - } - self.put_expression(handle, context)?; - } - // follow-up with any global resources used - let mut separate = !parameters.is_empty(); - let fun_info = &context.analysis[fun_handle]; - for (handle, var) in context.module.global_variables.iter() { - if !fun_info[handle].is_empty() && var.class.needs_pass_through() { - let name = &self.names[&NameKey::GlobalVariable(handle)]; - if separate { - write!(self.out, ", ")?; - } else { - separate = true; - } - write!(self.out, "{}", name)?; - } - } - // done - write!(self.out, ")")?; - Ok(()) - } - fn put_image_query( &mut self, image: Handle, @@ -263,7 +230,7 @@ impl Writer { context: &ExpressionContext, ) -> Result<(), Error> { if self.named_expressions.contains(expr_handle.index()) { - write!(self.out, "expr{}", expr_handle.index())?; + write!(self.out, "{}{}", BAKE_PREFIX, expr_handle.index())?; return Ok(()); } @@ -674,12 +641,8 @@ impl Writer { self.put_expression(expr, context)?; write!(self.out, ")")?; } - crate::Expression::Call { - function, - ref arguments, - } => { - self.put_local_call(function, arguments, context)?; - } + // has to be a named expression + crate::Expression::Call(_) => unreachable!(), crate::Expression::ArrayLength(expr) => { match *self.typifier.get(expr, &context.module.types) { crate::TypeInner::Array { @@ -701,6 +664,35 @@ impl Writer { Ok(()) } + fn start_baking_expression(&mut self, handle: Handle) -> Result<(), Error> { + match self.typifier.get_handle(handle) { + Ok(ty_handle) => { + let ty_name = &self.names[&NameKey::Type(ty_handle)]; + write!(self.out, "{}", ty_name)?; + } + Err(&crate::TypeInner::Scalar { kind, .. }) => { + write!(self.out, "{}", scalar_kind_string(kind))?; + } + Err(&crate::TypeInner::Vector { size, kind, .. }) => { + write!( + self.out, + "{}::{}{}", + NAMESPACE, + scalar_kind_string(kind), + vector_size_string(size) + )?; + } + Err(other) => { + log::error!("Type {:?} isn't a known local", other); + return Err(Error::FeatureNotImplemented("weird local type".to_string())); + } + } + + //TODO: figure out the naming scheme that wouldn't collide with user names. + write!(self.out, " {}{} = ", BAKE_PREFIX, handle.index())?; + Ok(()) + } + // Write down any required intermediate results fn prepare_expression( &mut self, @@ -732,31 +724,7 @@ impl Writer { let mut temp_bake_handles = mem::replace(&mut self.temp_bake_handles, Vec::new()); for handle in temp_bake_handles.drain(..).rev() { write!(self.out, "{}", level)?; - match self.typifier.get_handle(handle) { - Ok(ty_handle) => { - let ty_name = &self.names[&NameKey::Type(ty_handle)]; - write!(self.out, "{}", ty_name)?; - } - Err(&crate::TypeInner::Scalar { kind, .. }) => { - write!(self.out, "{}", scalar_kind_string(kind))?; - } - Err(&crate::TypeInner::Vector { size, kind, .. }) => { - write!( - self.out, - "{}::{}{}", - NAMESPACE, - scalar_kind_string(kind), - vector_size_string(size) - )?; - } - Err(other) => { - log::error!("Type {:?} isn't a known local", other); - return Err(Error::FeatureNotImplemented("weird local type".to_string())); - } - } - - //TODO: figure out the naming scheme that wouldn't collide with user names. - write!(self.out, " expr{} = ", handle.index())?; + self.start_baking_expression(handle)?; // Make sure to temporarily unblock the expression before writing it down. self.named_expressions.remove(handle.index()); self.put_expression(handle, &context.expression)?; @@ -881,6 +849,12 @@ impl Writer { array_index, value, } => { + self.prepare_expression(level.clone(), value, context, true)?; + self.prepare_expression(level.clone(), coordinate, context, false)?; + if let Some(expr) = array_index { + self.prepare_expression(level.clone(), expr, context, false)?; + } + write!(self.out, "{}", level)?; self.put_expression(image, &context.expression)?; write!(self.out, ".write(")?; self.put_expression(value, &context.expression)?; @@ -890,17 +864,46 @@ impl Writer { write!(self.out, ", ")?; self.put_expression(expr, &context.expression)?; } - write!(self.out, ");")?; + writeln!(self.out, ");")?; } crate::Statement::Call { function, ref arguments, + result, } => { for &arg in arguments { self.prepare_expression(level.clone(), arg, context, false)?; } - self.put_local_call(function, arguments, &context.expression)?; - writeln!(self.out, ";")?; + write!(self.out, "{}", level)?; + if let Some(expr) = result { + self.start_baking_expression(expr)?; + self.named_expressions.insert(expr.index()); + } + let fun_name = &self.names[&NameKey::Function(function)]; + write!(self.out, "{}(", fun_name)?; + // first, write down the actual arguments + for (i, &handle) in arguments.iter().enumerate() { + if i != 0 { + write!(self.out, ", ")?; + } + self.put_expression(handle, &context.expression)?; + } + // follow-up with any global resources used + let mut separate = !arguments.is_empty(); + let fun_info = &context.expression.analysis[function]; + for (handle, var) in context.expression.module.global_variables.iter() { + if !fun_info[handle].is_empty() && var.class.needs_pass_through() { + let name = &self.names[&NameKey::GlobalVariable(handle)]; + if separate { + write!(self.out, ", ")?; + } else { + separate = true; + } + write!(self.out, "{}", name)?; + } + } + // done + writeln!(self.out, ");")?; } } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 212ac6fdc..984f01fab 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -193,6 +193,7 @@ pub struct Writer { lookup_type: crate::FastHashMap, lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, + lookup_function_call: crate::FastHashMap, Word>, lookup_constant: crate::FastHashMap, Word>, lookup_global_variable: crate::FastHashMap, (Word, spirv::StorageClass)>, @@ -229,6 +230,7 @@ impl Writer { lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), lookup_function_type: crate::FastHashMap::default(), + lookup_function_call: crate::FastHashMap::default(), lookup_constant: crate::FastHashMap::default(), lookup_global_variable: crate::FastHashMap::default(), struct_type_handles: crate::FastHashMap::default(), @@ -1544,27 +1546,8 @@ impl Writer { let id = function.parameters[index as usize].result_id.unwrap(); RawExpression::Value(id) } - crate::Expression::Call { - function: local_function, - ref arguments, - } => { - let id = self.generate_id(); - //TODO: avoid heap allocation - let mut argument_ids = vec![]; - - for argument in arguments { - let arg_id = - self.write_expression(ir_module, ir_function, *argument, block, function)?; - argument_ids.push(arg_id); - } - - block.body.push(Instruction::function_call( - result_type_id, - id, - *self.lookup_function.get(&local_function).unwrap(), - argument_ids.as_slice(), - )); - + crate::Expression::Call(_function) => { + let id = self.lookup_function_call[&expr_handle]; RawExpression::Value(id) } crate::Expression::As { @@ -2093,6 +2076,7 @@ impl Writer { crate::Statement::Call { function: local_function, ref arguments, + result, } => { let id = self.generate_id(); //TODO: avoid heap allocation @@ -2109,10 +2093,20 @@ impl Writer { argument_ids.push(arg_id); } + let type_id = match result { + Some(expr) => { + self.lookup_function_call.insert(expr, id); + let ty_handle = + ir_module.functions[local_function].return_type.unwrap(); + self.get_type_id(&ir_module.types, LookupType::Handle(ty_handle))? + } + None => self.void_type, + }; + block.body.push(Instruction::function_call( - self.void_type, + type_id, id, - *self.lookup_function.get(&local_function).unwrap(), + self.lookup_function[&local_function], argument_ids.as_slice(), )); } @@ -2207,6 +2201,10 @@ impl Writer { analysis: &Analysis, words: &mut Vec, ) -> Result<(), Error> { + self.lookup_function.clear(); + self.lookup_function_type.clear(); + self.lookup_function_call.clear(); + self.layouter .initialize(&ir_module.types, &ir_module.constants); diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 973ed12b5..dfbd3073f 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -188,13 +188,20 @@ impl Program<'_> { format!("Unknown function: {}", func_name).into(), ) })?; + let arguments: Vec<_> = fc.args.iter().map(|a| a.expression).collect(); + let mut statements: Vec<_> = + fc.args.into_iter().flat_map(|a| a.statements).collect(); + let expression = + self.context.expressions.append(Expression::Call(function)); + statements.push(crate::Statement::Call { + function, + arguments, + result: Some(expression), + }); Ok(ExpressionRule { - expression: self.context.expressions.append(Expression::Call { - function, - arguments: fc.args.iter().map(|a| a.expression).collect(), - }), + expression, sampler: None, - statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), + statements, }) } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3a8d77788..8aa5fbaea 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1268,16 +1268,10 @@ impl> Parser { let function = self.dummy_functions.append(crate::Function::default()); self.deferred_function_calls.insert(function, func_id); - if self.lookup_void_type == Some(result_type_id) { - block.push(crate::Statement::Call { - function, - arguments, - }); + let result = if self.lookup_void_type == Some(result_type_id) { + None } else { - let expr_handle = expressions.append(crate::Expression::Call { - function, - arguments, - }); + let expr_handle = expressions.append(crate::Expression::Call(function)); self.lookup_expression.insert( result_id, LookupExpression { @@ -1285,7 +1279,13 @@ impl> Parser { type_id: result_type_id, }, ); - } + Some(expr_handle) + }; + block.push(crate::Statement::Call { + function, + arguments, + result, + }); } Op::ExtInst => { use crate::MathFunction as Mf; @@ -1611,10 +1611,7 @@ impl> Parser { fn patch_function_calls(&self, fun: &mut crate::Function) -> Result<(), Error> { for (_, expr) in fun.expressions.iter_mut() { - if let crate::Expression::Call { - ref mut function, .. - } = *expr - { + if let crate::Expression::Call(ref mut function) = *expr { let fun_id = self.deferred_function_calls[function]; *function = *self.lookup_function.lookup(fun_id)?; } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 1903eb408..450f55c2f 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -125,7 +125,7 @@ struct StatementContext<'input, 'temp, 'out> { arguments: &'out [crate::FunctionArgument], } -impl<'a> StatementContext<'a, '_, '_> { +impl<'a, 'temp> StatementContext<'a, 'temp, '_> { fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { StatementContext { lookup_ident: self.lookup_ident, @@ -140,7 +140,10 @@ impl<'a> StatementContext<'a, '_, '_> { } } - fn as_expression(&mut self) -> ExpressionContext<'a, '_, '_> { + fn as_expression<'t>(&'t mut self, block: &'t mut crate::Block) -> ExpressionContext<'a, 't, '_> + where + 'temp: 't, + { ExpressionContext { lookup_ident: self.lookup_ident, typifier: self.typifier, @@ -151,6 +154,7 @@ impl<'a> StatementContext<'a, '_, '_> { local_vars: self.variables, functions: self.functions, arguments: self.arguments, + block, } } } @@ -170,6 +174,7 @@ struct ExpressionContext<'input, 'temp, 'out> { local_vars: &'out Arena, arguments: &'out [crate::FunctionArgument], functions: &'out Arena, + block: &'temp mut crate::Block, } impl<'a> ExpressionContext<'a, '_, '_> { @@ -184,6 +189,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { local_vars: self.local_vars, functions: self.functions, arguments: self.arguments, + block: self.block, } } @@ -414,17 +420,17 @@ impl Parser { lexer: &mut Lexer<'a>, name: &'a str, mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - Ok(if let Some(fun) = conv::map_relational_fun(name) { + ) -> Result>, Error<'a>> { + let expr = if let Some(fun) = conv::map_relational_fun(name) { lexer.expect(Token::Paren('('))?; let argument = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Relational { fun, argument }) + crate::Expression::Relational { fun, argument } } else if let Some(axis) = conv::map_derivative_axis(name) { lexer.expect(Token::Paren('('))?; let expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Derivative { axis, expr }) + crate::Expression::Derivative { axis, expr } } else if let Some(fun) = conv::map_standard_fun(name) { lexer.expect(Token::Paren('('))?; let arg_count = fun.argument_count(); @@ -442,12 +448,12 @@ impl Parser { None }; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Math { + crate::Expression::Math { fun, arg, arg1, arg2, - }) + } } else if name == "select" { lexer.expect(Token::Paren('('))?; let accept = self.parse_general_expression(lexer, ctx.reborrow())?; @@ -456,11 +462,11 @@ impl Parser { lexer.expect(Token::Separator(','))?; let condition = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::Select { + crate::Expression::Select { condition, accept, reject, - }) + } } else { // texture sampling match name { @@ -484,7 +490,7 @@ impl Parser { None }; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageSample { + crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, @@ -492,7 +498,7 @@ impl Parser { offset, level: crate::SampleLevel::Auto, depth_ref: None, - }) + } } "textureSampleLevel" => { lexer.expect(Token::Paren('('))?; @@ -516,7 +522,7 @@ impl Parser { None }; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageSample { + crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, @@ -524,7 +530,7 @@ impl Parser { offset, level: crate::SampleLevel::Exact(level), depth_ref: None, - }) + } } "textureSampleBias" => { lexer.expect(Token::Paren('('))?; @@ -548,7 +554,7 @@ impl Parser { None }; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageSample { + crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, @@ -556,7 +562,7 @@ impl Parser { offset, level: crate::SampleLevel::Bias(bias), depth_ref: None, - }) + } } "textureSampleGrad" => { lexer.expect(Token::Paren('('))?; @@ -582,7 +588,7 @@ impl Parser { None }; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageSample { + crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, @@ -590,7 +596,7 @@ impl Parser { offset, level: crate::SampleLevel::Gradient { x, y }, depth_ref: None, - }) + } } "textureSampleCompare" => { lexer.expect(Token::Paren('('))?; @@ -614,7 +620,7 @@ impl Parser { None }; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageSample { + crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, coordinate, @@ -622,7 +628,7 @@ impl Parser { offset, level: crate::SampleLevel::Zero, depth_ref: Some(reference), - }) + } } "textureLoad" => { lexer.expect(Token::Paren('('))?; @@ -649,12 +655,12 @@ impl Parser { } }; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageLoad { + crate::Expression::ImageLoad { image, coordinate, array_index, index, - }) + } } "textureDimensions" => { lexer.expect(Token::Paren('('))?; @@ -667,49 +673,61 @@ impl Parser { None }; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageQuery { + crate::Expression::ImageQuery { image, query: crate::ImageQuery::Size { level }, - }) + } } "textureNumLevels" => { lexer.expect(Token::Paren('('))?; let image_name = lexer.next_ident()?; let image = ctx.lookup_ident.lookup(image_name)?; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageQuery { + crate::Expression::ImageQuery { image, query: crate::ImageQuery::NumLevels, - }) + } } "textureNumLayers" => { lexer.expect(Token::Paren('('))?; let image_name = lexer.next_ident()?; let image = ctx.lookup_ident.lookup(image_name)?; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageQuery { + crate::Expression::ImageQuery { image, query: crate::ImageQuery::NumLayers, - }) + } } "textureNumSamples" => { lexer.expect(Token::Paren('('))?; let image_name = lexer.next_ident()?; let image = ctx.lookup_ident.lookup(image_name)?; lexer.expect(Token::Paren(')'))?; - Some(crate::Expression::ImageQuery { + crate::Expression::ImageQuery { image, query: crate::ImageQuery::NumSamples, - }) + } + } + _ => { + let handle = + match self.parse_local_function_call(lexer, name, ctx.reborrow())? { + Some((function, arguments)) => { + let result = + Some(ctx.expressions.append(crate::Expression::Call(function))); + ctx.block.push(crate::Statement::Call { + function, + arguments, + result, + }); + result + } + None => None, + }; + return Ok(handle); } - _ => self.parse_local_function_call(lexer, name, ctx)?.map( - |(function, arguments)| crate::Expression::Call { - function, - arguments, - }, - ), } - }) + }; + Ok(Some(ctx.expressions.append(expr))) } fn parse_const_expression<'a>( @@ -791,15 +809,14 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { self.scopes.push(Scope::PrimaryExpr); - let expression = match lexer.next() { + let handle = match lexer.next() { Token::Paren('(') => { let expr = self.parse_general_expression(lexer, ctx)?; lexer.expect(Token::Paren(')'))?; - self.scopes.pop(); - return Ok(expr); + expr } Token::Word("true") => { - let handle = ctx.constants.fetch_or_append(crate::Constant { + let expr = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, inner: crate::ConstantInner::Scalar { @@ -807,10 +824,10 @@ impl Parser { value: crate::ScalarValue::Bool(true), }, }); - crate::Expression::Constant(handle) + ctx.expressions.append(crate::Expression::Constant(expr)) } Token::Word("false") => { - let handle = ctx.constants.fetch_or_append(crate::Constant { + let expr = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, inner: crate::ConstantInner::Scalar { @@ -818,24 +835,24 @@ impl Parser { value: crate::ScalarValue::Bool(false), }, }); - crate::Expression::Constant(handle) + ctx.expressions.append(crate::Expression::Constant(expr)) } Token::Number { value, ty, width } => { let inner = Self::get_constant_inner(value, ty, width)?; - let handle = ctx.constants.fetch_or_append(crate::Constant { + let expr = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, inner, }); - crate::Expression::Constant(handle) + ctx.expressions.append(crate::Expression::Constant(expr)) } Token::Word(word) => { - if let Some(handle) = ctx.lookup_ident.get(word) { - self.scopes.pop(); - return Ok(*handle); - } - //TODO: resolve the duplicate call in `parse_singular_expression` - if let Some(expr) = self.parse_function_call_inner(lexer, word, ctx.reborrow())? { + if let Some(&expr) = ctx.lookup_ident.get(word) { + expr + } else if let Some(expr) = + self.parse_function_call_inner(lexer, word, ctx.reborrow())? + { + //TODO: resolve the duplicate call in `parse_singular_expression` expr } else { let inner = self.parse_type_decl_impl( @@ -856,7 +873,7 @@ impl Parser { last_component = self.parse_general_expression(lexer, ctx.reborrow())?; } lexer.expect(Token::Paren(')'))?; - if components.is_empty() { + let expr = if components.is_empty() { let last_component_inner = ctx.resolve_type(last_component)?; match (&inner, last_component_inner) { (crate::TypeInner::Scalar { .. }, crate::TypeInner::Scalar { .. }) @@ -876,13 +893,14 @@ impl Parser { components.push(last_component); let ty = ctx.types.fetch_or_append(crate::Type { name: None, inner }); crate::Expression::Compose { ty, components } - } + }; + ctx.expressions.append(expr) } } other => return Err(Error::Unexpected(other, "primary expression")), }; self.scopes.pop(); - Ok(ctx.expressions.append(expression)) + Ok(handle) } fn parse_postfix<'a>( @@ -969,22 +987,31 @@ impl Parser { self.scopes.push(Scope::SingularExpr); //TODO: refactor this to avoid backing up let backup = lexer.clone(); - let expression = match lexer.next() { - Token::Operation('-') => Some(crate::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr: self.parse_singular_expression(lexer, ctx.reborrow())?, - }), - Token::Operation('!') => Some(crate::Expression::Unary { - op: crate::UnaryOperator::Not, - expr: self.parse_singular_expression(lexer, ctx.reborrow())?, - }), - Token::Word(word) => self.parse_function_call_inner(lexer, word, ctx.reborrow())?, - _ => None, - }; - - let handle = match expression { - Some(expr) => ctx.expressions.append(expr), - None => { + let handle = match lexer.next() { + Token::Operation('-') => { + let expr = crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr: self.parse_singular_expression(lexer, ctx.reborrow())?, + }; + ctx.expressions.append(expr) + } + Token::Operation('!') => { + let expr = crate::Expression::Unary { + op: crate::UnaryOperator::Not, + expr: self.parse_singular_expression(lexer, ctx.reborrow())?, + }; + ctx.expressions.append(expr) + } + Token::Word(word) => { + match self.parse_function_call_inner(lexer, word, ctx.reborrow())? { + Some(handle) => handle, + None => { + *lexer = backup; + self.parse_primary_expression(lexer, ctx.reborrow())? + } + } + } + _ => { *lexer = backup; self.parse_primary_expression(lexer, ctx.reborrow())? } @@ -1599,40 +1626,43 @@ impl Parser { Ok((handle, storage_access)) } - fn parse_statement<'a>( + fn parse_statement<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, - mut context: StatementContext<'a, '_, '_>, + mut context: StatementContext<'a, '_, 'out>, + block: &'out mut crate::Block, is_uniform_control_flow: bool, - ) -> Result, Error<'a>> { + ) -> Result<(), Error<'a>> { let word = match lexer.next() { - Token::Separator(';') => return Ok(None), + Token::Separator(';') => return Ok(()), Token::Paren('{') => { self.scopes.push(Scope::Block); let mut statements = Vec::new(); while !lexer.skip(Token::Paren('}')) { - let s = - self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)?; - statements.extend(s); + self.parse_statement( + lexer, + context.reborrow(), + &mut statements, + is_uniform_control_flow, + )?; } self.scopes.pop(); - let block = crate::Statement::Block(statements); - return Ok(Some(block)); + block.push(crate::Statement::Block(statements)); + return Ok(()); } Token::Word(word) => word, other => return Err(Error::Unexpected(other, "statement")), }; self.scopes.push(Scope::Statement); - let statement = match word { + match word { "const" => { let (name, _ty, _access) = self.parse_variable_ident_decl(lexer, context.types, context.constants)?; lexer.expect(Token::Operation('='))?; - let expr_id = self.parse_general_expression(lexer, context.as_expression())?; + let expr_id = self.parse_general_expression(lexer, context.as_expression(block))?; lexer.expect(Token::Separator(';'))?; context.lookup_ident.insert(name, expr_id); - None } "var" => { enum Init { @@ -1645,7 +1675,8 @@ impl Parser { self.parse_variable_ident_decl(lexer, context.types, context.constants)?; let init = if lexer.skip(Token::Operation('=')) { - let value = self.parse_general_expression(lexer, context.as_expression())?; + let value = + self.parse_general_expression(lexer, context.as_expression(block))?; match context.expressions[value] { crate::Expression::Constant(handle) if is_uniform_control_flow => { Init::Constant(handle) @@ -1671,26 +1702,26 @@ impl Parser { .append(crate::Expression::LocalVariable(var_id)); context.lookup_ident.insert(name, expr_id); - match init { - Init::Variable(value) => Some(crate::Statement::Store { + if let Init::Variable(value) = init { + block.push(crate::Statement::Store { pointer: expr_id, value, - }), - _ => None, + }); } } "return" => { let value = if lexer.peek() != Token::Separator(';') { - Some(self.parse_general_expression(lexer, context.as_expression())?) + Some(self.parse_general_expression(lexer, context.as_expression(block))?) } else { None }; lexer.expect(Token::Separator(';'))?; - Some(crate::Statement::Return { value }) + block.push(crate::Statement::Return { value }); } "if" => { lexer.expect(Token::Paren('('))?; - let condition = self.parse_general_expression(lexer, context.as_expression())?; + let condition = + self.parse_general_expression(lexer, context.as_expression(block))?; lexer.expect(Token::Paren(')'))?; let accept = self.parse_block(lexer, context.reborrow(), false)?; @@ -1698,7 +1729,7 @@ impl Parser { while lexer.skip(Token::Word("elseif")) { lexer.expect(Token::Paren('('))?; let other_condition = - self.parse_general_expression(lexer, context.as_expression())?; + self.parse_general_expression(lexer, context.as_expression(block))?; lexer.expect(Token::Paren(')'))?; let other_block = self.parse_block(lexer, context.reborrow(), false)?; elsif_stack.push((other_condition, other_block)); @@ -1718,15 +1749,16 @@ impl Parser { }]; } - Some(crate::Statement::If { + block.push(crate::Statement::If { condition, accept, reject, - }) + }); } "switch" => { lexer.expect(Token::Paren('('))?; - let selector = self.parse_general_expression(lexer, context.as_expression())?; + let selector = + self.parse_general_expression(lexer, context.as_expression(block))?; lexer.expect(Token::Paren(')'))?; lexer.expect(Token::Paren('{'))?; let mut cases = Vec::new(); @@ -1766,8 +1798,7 @@ impl Parser { if lexer.skip(Token::Paren('}')) { break false; } - let s = self.parse_statement(lexer, context.reborrow(), false)?; - body.extend(s); + self.parse_statement(lexer, context.reborrow(), &mut body, false)?; }; cases.push(crate::SwitchCase { @@ -1785,11 +1816,11 @@ impl Parser { } } - Some(crate::Statement::Switch { + block.push(crate::Statement::Switch { selector, cases, default, - }) + }); } "loop" => { let mut body = Vec::new(); @@ -1805,41 +1836,43 @@ impl Parser { if lexer.skip(Token::Paren('}')) { break; } - let s = self.parse_statement(lexer, context.reborrow(), false)?; - body.extend(s); + self.parse_statement(lexer, context.reborrow(), &mut body, false)?; } - Some(crate::Statement::Loop { body, continuing }) + block.push(crate::Statement::Loop { body, continuing }); } "for" => { - let mut block = Vec::new(); - lexer.expect(Token::Paren('('))?; - let initialization = if lexer.skip(Token::Separator(';')) { - None - } else { - let statement = - self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)?; - match statement { - Some(crate::Statement::Store { .. }) - | Some(crate::Statement::Call { .. }) => statement, - Some(other) => { - return Err(Error::InvalidStatement( - other, - "variable, assignment or function call", - )) + if !lexer.skip(Token::Separator(';')) { + let num_statements = block.len(); + self.parse_statement( + lexer, + context.reborrow(), + block, + is_uniform_control_flow, + )?; + if block.len() != num_statements { + match block.last().unwrap() { + &crate::Statement::Store { .. } | &crate::Statement::Call { .. } => {} + other => { + return Err(Error::InvalidStatement( + other.clone(), + "variable, assignment or function call", + )) + } } - None => None, } }; + let condition = if lexer.skip(Token::Separator(';')) { None } else { let condition = - Some(self.parse_general_expression(lexer, context.as_expression())?); + Some(self.parse_general_expression(lexer, context.as_expression(block))?); lexer.expect(Token::Separator(';'))?; condition }; + let continuing = if let Token::Word(ident) = lexer.peek() { // manually parse the next statement here instead of calling parse_statement // because the statement is not terminated with a semicolon @@ -1847,10 +1880,10 @@ impl Parser { Some(match context.lookup_ident.get(ident) { Some(&var_expr) => { let left = - self.parse_postfix(lexer, context.as_expression(), var_expr)?; + self.parse_postfix(lexer, context.as_expression(block), var_expr)?; lexer.expect(Token::Operation('='))?; let value = - self.parse_general_expression(lexer, context.as_expression())?; + self.parse_general_expression(lexer, context.as_expression(block))?; crate::Statement::Store { pointer: left, value, @@ -1858,11 +1891,16 @@ impl Parser { } None => { let (function, arguments) = self - .parse_local_function_call(lexer, ident, context.as_expression())? + .parse_local_function_call( + lexer, + ident, + context.as_expression(block), + )? .ok_or(Error::UnknownLocalFunction(ident))?; crate::Statement::Call { function, arguments, + result: None, } } }) @@ -1872,8 +1910,6 @@ impl Parser { lexer.expect(Token::Paren(')'))?; lexer.expect(Token::Paren('{'))?; - block.extend(initialization); - let mut body = Vec::new(); if let Some(condition) = condition { body.push(crate::Statement::If { @@ -1883,71 +1919,72 @@ impl Parser { }); } while !lexer.skip(Token::Paren('}')) { - let s = self.parse_statement(lexer, context.reborrow(), false)?; - body.extend(s); + self.parse_statement(lexer, context.reborrow(), &mut body, false)?; } block.push(crate::Statement::Loop { body, continuing: continuing.into_iter().collect(), }); - - Some(crate::Statement::Block(block)) } - "break" => Some(crate::Statement::Break), - "continue" => Some(crate::Statement::Continue), - "discard" => Some(crate::Statement::Kill), + "break" => block.push(crate::Statement::Break), + "continue" => block.push(crate::Statement::Continue), + "discard" => block.push(crate::Statement::Kill), "textureStore" => { lexer.expect(Token::Paren('('))?; let image_name = lexer.next_ident()?; let image = context.lookup_ident.lookup(image_name)?; lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, context.as_expression())?; - let arrayed = match *context.as_expression().resolve_type(image)? { + let coordinate = + self.parse_general_expression(lexer, context.as_expression(block))?; + let arrayed = match *context.as_expression(block).resolve_type(image)? { crate::TypeInner::Image { arrayed, .. } => arrayed, _ => return Err(Error::BadTexture(image_name)), }; let array_index = if arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, context.as_expression())?) + Some(self.parse_general_expression(lexer, context.as_expression(block))?) } else { None }; lexer.expect(Token::Separator(','))?; - let value = self.parse_general_expression(lexer, context.as_expression())?; + let value = self.parse_general_expression(lexer, context.as_expression(block))?; lexer.expect(Token::Paren(')'))?; - Some(crate::Statement::ImageStore { + block.push(crate::Statement::ImageStore { image, coordinate, array_index, value, - }) + }); } // assignment or a function call ident => { - if let Some(&var_expr) = context.lookup_ident.get(ident) { - let left = self.parse_postfix(lexer, context.as_expression(), var_expr)?; + let stmt = if let Some(&var_expr) = context.lookup_ident.get(ident) { + let left = self.parse_postfix(lexer, context.as_expression(block), var_expr)?; lexer.expect(Token::Operation('='))?; - let value = self.parse_general_expression(lexer, context.as_expression())?; + let value = + self.parse_general_expression(lexer, context.as_expression(block))?; lexer.expect(Token::Separator(';'))?; - Some(crate::Statement::Store { + crate::Statement::Store { pointer: left, value, - }) + } } else { let (function, arguments) = self - .parse_local_function_call(lexer, ident, context.as_expression())? + .parse_local_function_call(lexer, ident, context.as_expression(block))? .ok_or(Error::UnknownLocalFunction(ident))?; lexer.expect(Token::Separator(';'))?; - Some(crate::Statement::Call { + crate::Statement::Call { function, arguments, - }) - } + result: None, + } + }; + block.push(stmt); } - }; + } self.scopes.pop(); - Ok(statement) + Ok(()) } fn parse_block<'a>( @@ -1958,13 +1995,17 @@ impl Parser { ) -> Result, Error<'a>> { self.scopes.push(Scope::Block); lexer.expect(Token::Paren('{'))?; - let mut statements = Vec::new(); + let mut block = Vec::new(); while !lexer.skip(Token::Paren('}')) { - let s = self.parse_statement(lexer, context.reborrow(), is_uniform_control_flow)?; - statements.extend(s); + self.parse_statement( + lexer, + context.reborrow(), + &mut block, + is_uniform_control_flow, + )?; } self.scopes.pop(); - Ok(statements) + Ok(block) } fn parse_function_decl<'a>( diff --git a/src/lib.rs b/src/lib.rs index fd9c50671..98b45c7dc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -722,11 +722,8 @@ pub enum Expression { /// True = conversion needs to take place; False = bitcast. convert: bool, }, - /// Call another function. - Call { - function: Handle, - arguments: Vec>, - }, + /// Result of calling another function. + Call(Handle), /// Get the length of an array. ArrayLength(Handle), } @@ -771,7 +768,6 @@ pub enum Statement { }, /// Executes a block repeatedly. Loop { body: Block, continuing: Block }, - //TODO: move terminator variations into a separate enum? /// Exits the loop. Break, /// Skips execution to the next iteration of the loop. @@ -781,21 +777,35 @@ pub enum Statement { /// Aborts the current shader execution. Kill, /// Stores a value at an address. + /// + /// This statement is a barrier for any operations on the + /// `Expression::LocalVariable` or `Expression::GlobalVariable` + /// that is the destination of an access chain, started + /// from the `pointer`. Store { pointer: Handle, value: Handle, }, /// Stores a value to an image. + /// + /// Image has to point into a global variable of type `TypeInner::Image`. + /// This statement is a barrier for any operations on the corresponding + /// `Expression::GlobalVariable` for this image. ImageStore { image: Handle, coordinate: Handle, array_index: Option>, value: Handle, }, - /// Calls a function with no return value. + /// Calls a function. + /// + /// If the `result` is `Some`, the corresponding expression has to be + /// `Expression::Call`, and this statement serves as a barrier for any + /// operations on that expression. Call { function: Handle, arguments: Vec>, + result: Option>, }, } diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 805d344f5..d5fddff64 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -180,22 +180,14 @@ impl FunctionInfo { } /// Inherit information from a called function. - fn process_call( - &mut self, - info: &Self, - arguments: &[Handle], - ) -> ControlFlags { + fn process_call(&mut self, info: &Self) -> ControlFlags { for key in info.sampling_set.iter() { self.sampling_set.insert(key.clone()); } for (mine, other) in self.global_uses.iter_mut().zip(info.global_uses.iter()) { *mine |= *other; } - let mut flags = info.control_flags; - for &argument in arguments { - flags |= self.add_ref(argument); - } - flags + info.control_flags } /// Computes the control flags of a given expression, and store them @@ -353,10 +345,7 @@ impl FunctionInfo { self.add_ref(arg) | arg1_flags | arg2_flags } E::As { expr, .. } => self.add_ref(expr), - E::Call { - function, - ref arguments, - } => self.process_call(&other_functions[function.index()], arguments), + E::Call(function) => self.process_call(&other_functions[function.index()]), E::ArrayLength(expr) => self.add_ref_impl(expr, GlobalUse::QUERY), }; @@ -463,7 +452,17 @@ impl FunctionInfo { S::Call { function, ref arguments, - } => self.process_call(&other_functions[function.index()], arguments), + result, + } => { + let mut flags = self.process_call(&other_functions[function.index()]); + for &argument in arguments { + flags |= self.add_ref(argument); + } + if let Some(expr) = result { + flags |= self.add_ref(expr); + } + flags + } }; if flags.contains(ControlFlags::REQUIRE_UNIFORM) && !is_uniform { diff --git a/src/proc/interface.rs b/src/proc/interface.rs index fd7436251..f05bebadf 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -133,13 +133,7 @@ impl<'a, T: Visitor> Interface<'a, T> { E::As { expr, .. } => { self.traverse_expr(expr); } - E::Call { - function, - ref arguments, - } => { - for &argument in arguments { - self.traverse_expr(argument); - } + E::Call(function) => { self.visitor.visit_fun(function); } E::ArrayLength(expr) => { @@ -221,11 +215,15 @@ impl<'a, T: Visitor> Interface<'a, T> { S::Call { function, ref arguments, + result, } => { for &argument in arguments { self.traverse_expr(argument); } self.visitor.visit_fun(function); + if let Some(expr) = result { + self.traverse_expr(expr); + } } } } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 11e17abf9..7be74b923 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -485,10 +485,7 @@ impl Typifier { }) } }, - crate::Expression::Call { - function, - arguments: _, - } => { + crate::Expression::Call(function) => { let ty = ctx.functions[function] .return_type .ok_or(ResolveError::FunctionReturnsVoid)?; diff --git a/src/proc/validator.rs b/src/proc/validator.rs index c018505f2..9288a1ac9 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -134,6 +134,25 @@ pub enum LocalVariableError { InitializerType, } +#[derive(Clone, Debug, Error)] +pub enum CallError { + #[error("Bad function")] + Function, + #[error("Requires {required} arguments, but {seen} are provided")] + ArgumentCount { required: usize, seen: usize }, + #[error("Argument {index} value {seen_expression:?} doesn't match the type {required:?}")] + ArgumentType { + index: usize, + required: Handle, + seen_expression: Handle, + }, + #[error("Return value {seen_expression:?} does not match the type {required:?}")] + ReturnType { + required: Option>, + seen_expression: Option>, + }, +} + #[derive(Clone, Debug, Error)] pub enum FunctionError { #[error(transparent)] @@ -174,22 +193,11 @@ pub enum FunctionError { InvalidExpression(Handle), #[error("The expression {0:?} is not an image")] InvalidImage(Handle), - #[error("The called function {0:?} is invalid")] - InvalidCall(Handle), - #[error( - "The called function {function:?} requires {required} arguments, but {seen} are provided" - )] - InvalidCallArgumentCount { + #[error("Call to {function:?} is invalid")] + InvalidCall { function: Handle, - required: usize, - seen: usize, - }, - #[error("The called function {function:?} argument {index} requires {required:?} type, but {seen:?} type is provided")] - InvalidCallArgumentType { - function: Handle, - index: usize, - required: Handle, - seen: Option>, + #[source] + error: CallError, }, } @@ -658,6 +666,49 @@ impl Validator { Ok(()) } + fn validate_call( + &self, + function: Handle, + arguments: &[Handle], + result: Option>, + context: &BlockContext, + ) -> Result<(), CallError> { + let fun = context + .functions + .try_get(function) + .ok_or(CallError::Function)?; + if fun.arguments.len() != arguments.len() { + return Err(CallError::ArgumentCount { + required: fun.arguments.len(), + seen: arguments.len(), + }); + } + for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { + let ty = self.typifier.get(expr, context.types); + if ty != &context.types[arg.ty].inner { + return Err(CallError::ArgumentType { + index, + required: arg.ty, + seen_expression: expr, + }); + } + } + let result_ty = result.map(|expr| self.typifier.get(expr, context.types)); + let expected_ty = fun.return_type.map(|ty| &context.types[ty].inner); + if result_ty != expected_ty { + log::error!( + "Called function returns {:?} where {:?} is expected", + result_ty, + expected_ty + ); + return Err(CallError::ReturnType { + required: fun.return_type, + seen_expression: result, + }); + } + Ok(()) + } + fn validate_block( &mut self, statements: &[crate::Statement], @@ -788,28 +839,10 @@ impl Validator { S::Call { function, ref arguments, + result, } => { - let fun = context - .functions - .try_get(function) - .ok_or(FunctionError::InvalidCall(function))?; - if fun.arguments.len() != arguments.len() { - return Err(FunctionError::InvalidCallArgumentCount { - function, - required: fun.arguments.len(), - seen: arguments.len(), - }); - } - for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { - let ty = self.typifier.get_handle(expr); - if ty != Ok(arg.ty) { - return Err(FunctionError::InvalidCallArgumentType { - function, - index, - required: arg.ty, - seen: ty.ok(), - }); - } + if let Err(error) = self.validate_call(function, arguments, result, context) { + return Err(FunctionError::InvalidCall { function, error }); } } } diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 4062a43b4..9342a5233 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -236,7 +236,7 @@ expression: output control_flags: ( bits: 5, ), - ref_count: 1, + ref_count: 2, assignable_global: None, ), ], diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index 2ab590d73..2b928187a 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -43,7 +43,8 @@ kernel void main1( type global_id [[thread_position_in_grid]], device PrimeIndices& v_indices [[buffer(0)]] ) { - v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); + type1 _expr8 = collatz_iterations(v_indices.data[global_id.x]); + v_indices.data[global_id.x] = _expr8; return ; } diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap index ec08b46ba..ef58ec585 100644 --- a/tests/out/collatz.ron.snap +++ b/tests/out/collatz.ron.snap @@ -252,14 +252,16 @@ expression: output base: 6, index: 7, ), + Call(1), + ], + body: [ Call( function: 1, arguments: [ 8, ], + result: Some(9), ), - ], - body: [ Store( pointer: 5, value: 9, diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index 9817753c0..02b2060f0 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -9,24 +9,24 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %38 "main" %52 +OpEntryPoint GLCompute %38 "main" %53 OpExecutionMode %38 LocalSize 1 1 1 OpSource GLSL 450 OpName %8 "n" OpName %10 "i" OpName %12 "collatz_iterations" OpName %38 "main" -OpName %44 "PrimeIndices" -OpMemberName %44 0 "data" -OpName %45 "v_indices" -OpName %52 "global_id" +OpName %45 "PrimeIndices" +OpMemberName %45 0 "data" +OpName %46 "v_indices" +OpName %53 "global_id" OpName %38 "main" -OpDecorate %42 ArrayStride 4 -OpDecorate %44 BufferBlock -OpMemberDecorate %44 0 Offset 0 -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 0 -OpDecorate %52 BuiltIn GlobalInvocationId +OpDecorate %43 ArrayStride 4 +OpDecorate %45 BufferBlock +OpMemberDecorate %45 0 Offset 0 +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 0 +OpDecorate %53 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -37,24 +37,24 @@ OpDecorate %52 BuiltIn GlobalInvocationId %13 = OpTypeFunction %4 %4 %19 = OpTypeBool %39 = OpTypeFunction %2 -%42 = OpTypeRuntimeArray %4 -%44 = OpTypeStruct %42 -%46 = OpTypePointer Uniform %44 -%45 = OpVariable %46 Uniform -%47 = OpTypePointer Uniform %42 -%48 = OpTypeInt 32 1 -%49 = OpConstant %48 0 -%51 = OpTypeVector %4 3 -%53 = OpTypePointer Input %51 -%52 = OpVariable %53 Input -%54 = OpTypePointer Input %4 -%55 = OpConstant %48 0 -%57 = OpTypePointer Uniform %4 -%61 = OpTypePointer Uniform %42 -%62 = OpConstant %48 0 -%64 = OpTypePointer Input %4 -%65 = OpConstant %48 0 -%67 = OpTypePointer Uniform %4 +%43 = OpTypeRuntimeArray %4 +%45 = OpTypeStruct %43 +%47 = OpTypePointer Uniform %45 +%46 = OpVariable %47 Uniform +%48 = OpTypePointer Uniform %43 +%49 = OpTypeInt 32 1 +%50 = OpConstant %49 0 +%52 = OpTypeVector %4 3 +%54 = OpTypePointer Input %52 +%53 = OpVariable %54 Input +%55 = OpTypePointer Input %4 +%56 = OpConstant %49 0 +%58 = OpTypePointer Uniform %4 +%62 = OpTypePointer Uniform %43 +%63 = OpConstant %49 0 +%65 = OpTypePointer Input %4 +%66 = OpConstant %49 0 +%68 = OpTypePointer Uniform %4 %12 = OpFunction %4 None %13 %11 = OpFunctionParameter %4 %14 = OpLabel @@ -102,16 +102,16 @@ OpReturnValue %37 OpFunctionEnd %38 = OpFunction %2 None %39 %40 = OpLabel -%43 = OpAccessChain %47 %45 %49 -%50 = OpAccessChain %54 %52 %55 -%56 = OpLoad %4 %50 -%41 = OpAccessChain %57 %43 %56 -%60 = OpAccessChain %61 %45 %62 -%63 = OpAccessChain %64 %52 %65 -%66 = OpLoad %4 %63 -%59 = OpAccessChain %67 %60 %66 -%68 = OpLoad %4 %59 -%58 = OpFunctionCall %4 %12 %68 -OpStore %41 %58 +%44 = OpAccessChain %48 %46 %50 +%51 = OpAccessChain %55 %53 %56 +%57 = OpLoad %4 %51 +%42 = OpAccessChain %58 %44 %57 +%59 = OpLoad %4 %42 +%41 = OpFunctionCall %4 %12 %59 +%61 = OpAccessChain %62 %46 %63 +%64 = OpAccessChain %65 %53 %66 +%67 = OpLoad %4 %64 +%60 = OpAccessChain %68 %61 %67 +OpStore %60 %41 OpReturn OpFunctionEnd diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 200c3206e..d0d632509 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -941,7 +941,7 @@ expression: output control_flags: ( bits: 5, ), - ref_count: 1, + ref_count: 2, assignable_global: None, ), ( diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 53984b124..623d4d1c5 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -59,8 +59,8 @@ type7 fetch_shadow( if ((homogeneous_coords.w <= const_0f)) { return const_1f; } - float expr15 = (const_1f / homogeneous_coords.w); - return t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * expr15) + metal::float2(const_0_50f, const_0_50f)), static_cast(light_id), (homogeneous_coords.z * expr15)); + float _expr15 = (const_1f / homogeneous_coords.w); + return t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * _expr15) + metal::float2(const_0_50f, const_0_50f)), static_cast(light_id), (homogeneous_coords.z * _expr15)); } struct fs_mainInput { @@ -91,9 +91,9 @@ fragment fs_mainOutput fs_main( if ((i >= metal::min(u_globals.num_lights.x, c_max_lights))) { break; } - Light expr18 = s_lights.data[i]; - type7 expr21 = fetch_shadow(i, (expr18.proj * input.in_position_fs), t_shadow, sampler_shadow); - color1 = (color1 + ((expr21 * metal::max(const_0f, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(expr18.pos.x, expr18.pos.y, expr18.pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(expr18.color.x, expr18.color.y, expr18.color.z))); + Light _expr18 = s_lights.data[i]; + type7 _expr21 = fetch_shadow(i, (_expr18.proj * input.in_position_fs), t_shadow, sampler_shadow); + color1 = (color1 + ((_expr21 * metal::max(const_0f, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(_expr18.pos.x, _expr18.pos.y, _expr18.pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(_expr18.color.x, _expr18.color.y, _expr18.color.z))); } output.out_color_fs = metal::float4(color1, const_1f); return output; diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index c79cdb6cd..3a7d33ffe 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -895,13 +895,7 @@ expression: output left: 51, right: 3, ), - Call( - function: 1, - arguments: [ - 44, - 52, - ], - ), + Call(1), Math( fun: Normalize, arg: 2, @@ -1101,6 +1095,14 @@ expression: output ], reject: [], ), + Call( + function: 1, + arguments: [ + 44, + 52, + ], + result: Some(53), + ), Store( pointer: 43, value: 91, diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index 75f9f7a81..94e7eba17 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -9,7 +9,7 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %63 "fs_main" %112 %109 %215 +OpEntryPoint Fragment %63 "fs_main" %112 %105 %215 OpExecutionMode %63 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_ambient" @@ -23,14 +23,14 @@ OpName %63 "fs_main" OpName %75 "Globals" OpMemberName %75 0 "num_lights" OpName %76 "u_globals" -OpName %95 "Light" -OpMemberName %95 0 "proj" -OpMemberName %95 1 "pos" -OpMemberName %95 2 "color" -OpName %99 "Lights" -OpMemberName %99 0 "data" -OpName %100 "s_lights" -OpName %109 "in_position_fs" +OpName %91 "Light" +OpMemberName %91 0 "proj" +OpMemberName %91 1 "pos" +OpMemberName %91 2 "color" +OpName %95 "Lights" +OpMemberName %95 0 "data" +OpName %96 "s_lights" +OpName %105 "in_position_fs" OpName %112 "in_normal_fs" OpName %215 "out_color_fs" OpName %63 "fs_main" @@ -42,18 +42,18 @@ OpDecorate %75 Block OpMemberDecorate %75 0 Offset 0 OpDecorate %76 DescriptorSet 0 OpDecorate %76 Binding 0 +OpMemberDecorate %91 0 Offset 0 +OpMemberDecorate %91 0 ColMajor +OpMemberDecorate %91 0 MatrixStride 16 +OpMemberDecorate %91 1 Offset 64 +OpMemberDecorate %91 2 Offset 80 +OpDecorate %93 ArrayStride 96 +OpDecorate %95 BufferBlock OpMemberDecorate %95 0 Offset 0 -OpMemberDecorate %95 0 ColMajor -OpMemberDecorate %95 0 MatrixStride 16 -OpMemberDecorate %95 1 Offset 64 -OpMemberDecorate %95 2 Offset 80 -OpDecorate %97 ArrayStride 96 -OpDecorate %99 BufferBlock -OpMemberDecorate %99 0 Offset 0 -OpDecorate %100 NonWritable -OpDecorate %100 DescriptorSet 0 -OpDecorate %100 Binding 1 -OpDecorate %109 Location 1 +OpDecorate %96 NonWritable +OpDecorate %96 DescriptorSet 0 +OpDecorate %96 Binding 1 +OpDecorate %105 Location 1 OpDecorate %112 Location 0 OpDecorate %215 Location 0 %2 = OpTypeVoid @@ -93,38 +93,38 @@ OpDecorate %215 Location 0 %79 = OpConstant %49 0 %80 = OpTypePointer Uniform %12 %81 = OpConstant %49 0 -%93 = OpTypeMatrix %17 4 -%95 = OpTypeStruct %93 %17 %17 -%97 = OpTypeRuntimeArray %95 -%99 = OpTypeStruct %97 -%101 = OpTypePointer Uniform %99 -%100 = OpVariable %101 Uniform -%102 = OpTypePointer Uniform %97 +%89 = OpTypeMatrix %17 4 +%91 = OpTypeStruct %89 %17 %17 +%93 = OpTypeRuntimeArray %91 +%95 = OpTypeStruct %93 +%97 = OpTypePointer Uniform %95 +%96 = OpVariable %97 Uniform +%98 = OpTypePointer Uniform %93 +%99 = OpConstant %49 0 +%101 = OpTypePointer Uniform %91 +%102 = OpTypePointer Uniform %89 %103 = OpConstant %49 0 -%105 = OpTypePointer Uniform %95 -%106 = OpTypePointer Uniform %93 -%107 = OpConstant %49 0 -%110 = OpTypePointer Input %17 -%109 = OpVariable %110 Input +%106 = OpTypePointer Input %17 +%105 = OpVariable %106 Input %113 = OpTypePointer Input %10 %112 = OpVariable %113 Input -%121 = OpTypePointer Uniform %97 +%121 = OpTypePointer Uniform %93 %122 = OpConstant %49 0 -%124 = OpTypePointer Uniform %95 +%124 = OpTypePointer Uniform %91 %125 = OpTypePointer Uniform %17 %126 = OpConstant %49 1 %127 = OpTypePointer Uniform %4 %128 = OpConstant %49 0 -%134 = OpTypePointer Uniform %97 +%134 = OpTypePointer Uniform %93 %135 = OpConstant %49 0 -%137 = OpTypePointer Uniform %95 +%137 = OpTypePointer Uniform %91 %138 = OpTypePointer Uniform %17 %139 = OpConstant %49 1 %140 = OpTypePointer Uniform %4 %141 = OpConstant %49 1 -%147 = OpTypePointer Uniform %97 +%147 = OpTypePointer Uniform %93 %148 = OpConstant %49 0 -%150 = OpTypePointer Uniform %95 +%150 = OpTypePointer Uniform %91 %151 = OpTypePointer Uniform %17 %152 = OpConstant %49 1 %153 = OpTypePointer Uniform %4 @@ -135,23 +135,23 @@ OpDecorate %215 Location 0 %163 = OpConstant %49 1 %166 = OpTypePointer Input %4 %167 = OpConstant %49 2 -%177 = OpTypePointer Uniform %97 +%177 = OpTypePointer Uniform %93 %178 = OpConstant %49 0 -%180 = OpTypePointer Uniform %95 +%180 = OpTypePointer Uniform %91 %181 = OpTypePointer Uniform %17 %182 = OpConstant %49 2 %183 = OpTypePointer Uniform %4 %184 = OpConstant %49 0 -%190 = OpTypePointer Uniform %97 +%190 = OpTypePointer Uniform %93 %191 = OpConstant %49 0 -%193 = OpTypePointer Uniform %95 +%193 = OpTypePointer Uniform %91 %194 = OpTypePointer Uniform %17 %195 = OpConstant %49 2 %196 = OpTypePointer Uniform %4 %197 = OpConstant %49 1 -%203 = OpTypePointer Uniform %97 +%203 = OpTypePointer Uniform %93 %204 = OpConstant %49 0 -%206 = OpTypePointer Uniform %95 +%206 = OpTypePointer Uniform %91 %207 = OpTypePointer Uniform %17 %208 = OpConstant %49 2 %209 = OpTypePointer Uniform %4 @@ -214,71 +214,71 @@ OpBranchConditional %70 %85 %84 %85 = OpLabel OpBranch %67 %84 = OpLabel -%87 = OpLoad %10 %59 -%91 = OpLoad %12 %61 -%98 = OpAccessChain %102 %100 %103 -%104 = OpLoad %12 %61 -%96 = OpAccessChain %105 %98 %104 -%94 = OpAccessChain %106 %96 %107 -%108 = OpLoad %93 %94 -%111 = OpLoad %17 %109 -%92 = OpMatrixTimesVector %17 %108 %111 -%90 = OpFunctionCall %4 %18 %91 %92 +%87 = OpLoad %12 %61 +%94 = OpAccessChain %98 %96 %99 +%100 = OpLoad %12 %61 +%92 = OpAccessChain %101 %94 %100 +%90 = OpAccessChain %102 %92 %103 +%104 = OpLoad %89 %90 +%107 = OpLoad %17 %105 +%88 = OpMatrixTimesVector %17 %104 %107 +%86 = OpFunctionCall %4 %18 %87 %88 +%109 = OpLoad %10 %59 %114 = OpLoad %10 %112 %115 = OpExtInst %10 %1 Normalize %114 -%120 = OpAccessChain %121 %100 %122 +%120 = OpAccessChain %121 %96 %122 %123 = OpLoad %12 %61 %119 = OpAccessChain %124 %120 %123 %118 = OpAccessChain %125 %119 %126 %117 = OpAccessChain %127 %118 %128 %129 = OpLoad %4 %117 -%133 = OpAccessChain %134 %100 %135 +%133 = OpAccessChain %134 %96 %135 %136 = OpLoad %12 %61 %132 = OpAccessChain %137 %133 %136 %131 = OpAccessChain %138 %132 %139 %130 = OpAccessChain %140 %131 %141 %142 = OpLoad %4 %130 -%146 = OpAccessChain %147 %100 %148 +%146 = OpAccessChain %147 %96 %148 %149 = OpLoad %12 %61 %145 = OpAccessChain %150 %146 %149 %144 = OpAccessChain %151 %145 %152 %143 = OpAccessChain %153 %144 %154 %155 = OpLoad %4 %143 %156 = OpCompositeConstruct %10 %129 %142 %155 -%157 = OpAccessChain %158 %109 %159 +%157 = OpAccessChain %158 %105 %159 %160 = OpLoad %4 %157 -%161 = OpAccessChain %162 %109 %163 +%161 = OpAccessChain %162 %105 %163 %164 = OpLoad %4 %161 -%165 = OpAccessChain %166 %109 %167 +%165 = OpAccessChain %166 %105 %167 %168 = OpLoad %4 %165 %169 = OpCompositeConstruct %10 %160 %164 %168 %116 = OpFSub %10 %156 %169 %170 = OpExtInst %10 %1 Normalize %116 %171 = OpDot %4 %115 %170 %172 = OpExtInst %4 %1 FMax %3 %171 -%89 = OpFMul %4 %90 %172 -%176 = OpAccessChain %177 %100 %178 +%111 = OpFMul %4 %86 %172 +%176 = OpAccessChain %177 %96 %178 %179 = OpLoad %12 %61 %175 = OpAccessChain %180 %176 %179 %174 = OpAccessChain %181 %175 %182 %173 = OpAccessChain %183 %174 %184 %185 = OpLoad %4 %173 -%189 = OpAccessChain %190 %100 %191 +%189 = OpAccessChain %190 %96 %191 %192 = OpLoad %12 %61 %188 = OpAccessChain %193 %189 %192 %187 = OpAccessChain %194 %188 %195 %186 = OpAccessChain %196 %187 %197 %198 = OpLoad %4 %186 -%202 = OpAccessChain %203 %100 %204 +%202 = OpAccessChain %203 %96 %204 %205 = OpLoad %12 %61 %201 = OpAccessChain %206 %202 %205 %200 = OpAccessChain %207 %201 %208 %199 = OpAccessChain %209 %200 %210 %211 = OpLoad %4 %199 %212 = OpCompositeConstruct %10 %185 %198 %211 -%88 = OpVectorTimesScalar %10 %212 %89 -%86 = OpFAdd %10 %87 %88 -OpStore %59 %86 +%110 = OpVectorTimesScalar %10 %212 %111 +%108 = OpFAdd %10 %109 %110 +OpStore %59 %108 OpBranch %69 %69 = OpLabel %214 = OpLoad %12 %61 diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 277e9e681..1a1c0d096 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -52,10 +52,10 @@ vertex vs_mainOutput vs_main( type unprojected; tmp1_ = (static_cast(in_vertex_index) / const_2i); tmp2_ = (static_cast(in_vertex_index) & const_1i); - type expr24 = metal::float4(((static_cast(tmp1_) * const_4f) - const_1f), ((static_cast(tmp2_) * const_4f) - const_1f), const_0f, const_1f); - unprojected = (r_data.proj_inv * expr24); + type _expr24 = metal::float4(((static_cast(tmp1_) * const_4f) - const_1f), ((static_cast(tmp2_) * const_4f) - const_1f), const_0f, const_1f); + unprojected = (r_data.proj_inv * _expr24); output.out_uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z)); - output.out_position = expr24; + output.out_position = _expr24; return output; } From 9c47a5fe176b6722cb08c63de8b6eba296ad9ff1 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Mon, 22 Feb 2021 08:59:48 -0330 Subject: [PATCH 0527/2212] [wgsl] Track token span for unexpected errors --- src/front/wgsl/lexer.rs | 64 +++++++++++++++------------ src/front/wgsl/mod.rs | 96 +++++++++++++++++++++-------------------- 2 files changed, 86 insertions(+), 74 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 323c928a9..cd2aa04d0 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -1,4 +1,4 @@ -use super::{conv, Error, Token}; +use super::{conv, Error, Token, TokenSpan}; fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { if input.starts_with(what) { @@ -156,55 +156,63 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { #[derive(Clone)] pub(super) struct Lexer<'a> { input: &'a str, + pub(super) source: &'a str, } impl<'a> Lexer<'a> { pub(super) fn new(input: &'a str) -> Self { - Lexer { input } + Lexer { + input, + source: input, + } } - fn peek_token_and_rest(&mut self) -> (Token<'a>, &'a str) { + fn peek_token_and_rest(&mut self) -> (TokenSpan<'a>, &'a str) { let mut cloned = self.clone(); let token = cloned.next(); let rest = cloned.input; (token, rest) } + fn current_byte_offset(&self) -> usize { + self.source.len() - self.input.len() + } + #[must_use] - pub(super) fn next(&mut self) -> Token<'a> { - let original_len = self.input.len(); + pub(super) fn next(&mut self) -> TokenSpan<'a> { + let mut start_byte_offset = self.current_byte_offset(); loop { let (token, rest) = consume_token(self.input, false); self.input = rest; - if token != Token::Trivia { - let _bytes_read = original_len - self.input.len(); - return token; + match token { + Token::Trivia => start_byte_offset = self.current_byte_offset(), + _ => return (token, start_byte_offset..self.current_byte_offset()), } } } #[must_use] - pub(super) fn next_generic(&mut self) -> Token<'a> { - let original_len = self.input.len(); + pub(super) fn next_generic(&mut self) -> TokenSpan<'a> { + let mut start_byte_offset = self.current_byte_offset(); loop { let (token, rest) = consume_token(self.input, true); self.input = rest; - if token != Token::Trivia { - let _bytes_read = original_len - self.input.len(); - return token; + match token { + Token::Trivia => start_byte_offset = self.current_byte_offset(), + _ => return (token, start_byte_offset..self.current_byte_offset()), } } } #[must_use] - pub(super) fn peek(&mut self) -> Token<'a> { + pub(super) fn peek(&mut self) -> TokenSpan<'a> { let (token, _) = self.peek_token_and_rest(); token } pub(super) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { - let token = self.next(); - if token == expected { + let next = self.next(); + if next.0 == expected { Ok(()) } else { let description = match expected { @@ -224,22 +232,22 @@ impl<'a> Lexer<'a> { Token::Trivia => "trivia", Token::End => "", }; - Err(Error::Unexpected(token, description)) + Err(Error::Unexpected(next, description)) } } pub(super) fn expect_generic_paren(&mut self, expected: char) -> Result<(), Error<'a>> { - let token = self.next_generic(); - if token == Token::Paren(expected) { + let next = self.next_generic(); + if next.0 == Token::Paren(expected) { Ok(()) } else { - Err(Error::Unexpected(token, "paren")) + Err(Error::Unexpected(next, "paren")) } } pub(super) fn skip(&mut self, what: Token<'_>) -> bool { let (peeked_token, rest) = self.peek_token_and_rest(); - if peeked_token == what { + if peeked_token.0 == what { self.input = rest; true } else { @@ -249,21 +257,23 @@ impl<'a> Lexer<'a> { pub(super) fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { match self.next() { - Token::Word(word) => Ok(word), + (Token::Word(word), _) => Ok(word), other => Err(Error::Unexpected(other, "ident")), } } fn _next_float_literal(&mut self) -> Result> { match self.next() { - Token::Number { value, .. } => value.parse().map_err(|err| Error::BadFloat(value, err)), + (Token::Number { value, .. }, _) => { + value.parse().map_err(|err| Error::BadFloat(value, err)) + } other => Err(Error::Unexpected(other, "float literal")), } } pub(super) fn next_uint_literal(&mut self) -> Result> { match self.next() { - Token::Number { value, .. } => { + (Token::Number { value, .. }, _) => { value.parse().map_err(|err| Error::BadInteger(value, err)) } other => Err(Error::Unexpected(other, "uint literal")), @@ -272,7 +282,7 @@ impl<'a> Lexer<'a> { pub(super) fn next_sint_literal(&mut self) -> Result> { match self.next() { - Token::Number { value, .. } => { + (Token::Number { value, .. }, _) => { value.parse().map_err(|err| Error::BadInteger(value, err)) } other => Err(Error::Unexpected(other, "sint literal")), @@ -305,9 +315,9 @@ impl<'a> Lexer<'a> { fn sub_test(source: &str, expected_tokens: &[Token]) { let mut lex = Lexer::new(source); for &token in expected_tokens { - assert_eq!(lex.next(), token); + assert_eq!(lex.next().0, token); } - assert_eq!(lex.next(), Token::End); + assert_eq!(lex.next().0, Token::End); } #[test] diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 450f55c2f..5e369f4e8 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -14,11 +14,13 @@ use crate::{ }; use self::lexer::Lexer; -use std::num::NonZeroU32; +use std::{num::NonZeroU32, ops::Range}; use thiserror::Error; const SPACE: &str = " "; +type TokenSpan<'a> = (Token<'a>, Range); + #[derive(Copy, Clone, Debug, PartialEq)] pub enum Token<'a> { Separator(char), @@ -44,8 +46,8 @@ pub enum Token<'a> { #[derive(Clone, Debug, Error)] pub enum Error<'a> { - #[error("unexpected token {0:?}, expected {1}")] - Unexpected(Token<'a>, &'a str), + #[error("unexpected token {:?}, expected {1}", (.0).0)] + Unexpected(TokenSpan<'a>, &'a str), #[error("unable to parse `{0}` as integer: {1}")] BadInteger(&'a str, std::num::ParseIntError), #[error("unable to parse `{1}` as float: {1}")] @@ -234,7 +236,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { ) -> Result, Error<'a>>, ) -> Result, Error<'a>> { let mut left = parser(lexer, self.reborrow())?; - while let Some(op) = classifier(lexer.peek()) { + while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); let expression = crate::Expression::Binary { op, @@ -406,8 +408,8 @@ impl Parser { let arg = self.parse_general_expression(lexer, ctx.reborrow())?; arguments.push(arg); match lexer.next() { - Token::Paren(')') => break, - Token::Separator(',') => (), + (Token::Paren(')'), _) => break, + (Token::Separator(','), _) => (), other => return Err(Error::Unexpected(other, "argument list separator")), } } @@ -739,16 +741,16 @@ impl Parser { ) -> Result, Error<'a>> { self.scopes.push(Scope::ConstantExpr); let inner = match lexer.next() { - Token::Word("true") => crate::ConstantInner::Scalar { + (Token::Word("true"), _) => crate::ConstantInner::Scalar { width: 1, value: crate::ScalarValue::Bool(true), }, - Token::Word("false") => crate::ConstantInner::Scalar { + (Token::Word("false"), _) => crate::ConstantInner::Scalar { width: 1, value: crate::ScalarValue::Bool(false), }, - Token::Number { value, ty, width } => Self::get_constant_inner(value, ty, width)?, - Token::Word(name) => { + (Token::Number { value, ty, width }, _) => Self::get_constant_inner(value, ty, width)?, + (Token::Word(name), _) => { // look for an existing constant first for (handle, var) in const_arena.iter() { match var.name { @@ -810,12 +812,12 @@ impl Parser { ) -> Result, Error<'a>> { self.scopes.push(Scope::PrimaryExpr); let handle = match lexer.next() { - Token::Paren('(') => { + (Token::Paren('('), _) => { let expr = self.parse_general_expression(lexer, ctx)?; lexer.expect(Token::Paren(')'))?; expr } - Token::Word("true") => { + (Token::Word("true"), _) => { let expr = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, @@ -826,7 +828,7 @@ impl Parser { }); ctx.expressions.append(crate::Expression::Constant(expr)) } - Token::Word("false") => { + (Token::Word("false"), _) => { let expr = ctx.constants.fetch_or_append(crate::Constant { name: None, specialization: None, @@ -837,7 +839,7 @@ impl Parser { }); ctx.expressions.append(crate::Expression::Constant(expr)) } - Token::Number { value, ty, width } => { + (Token::Number { value, ty, width }, _) => { let inner = Self::get_constant_inner(value, ty, width)?; let expr = ctx.constants.fetch_or_append(crate::Constant { name: None, @@ -846,7 +848,7 @@ impl Parser { }); ctx.expressions.append(crate::Expression::Constant(expr)) } - Token::Word(word) => { + (Token::Word(word), _) => { if let Some(&expr) = ctx.lookup_ident.get(word) { expr } else if let Some(expr) = @@ -910,7 +912,7 @@ impl Parser { mut handle: Handle, ) -> Result, Error<'a>> { loop { - match lexer.peek() { + match lexer.peek().0 { Token::Separator('.') => { let _ = lexer.next(); let name = lexer.next_ident()?; @@ -987,7 +989,7 @@ impl Parser { self.scopes.push(Scope::SingularExpr); //TODO: refactor this to avoid backing up let backup = lexer.clone(); - let handle = match lexer.next() { + let handle = match lexer.next().0 { Token::Operation('-') => { let expr = crate::Expression::Unary { op: crate::UnaryOperator::Negate, @@ -1226,20 +1228,20 @@ impl Parser { let mut ready = true; loop { match lexer.next() { - Token::DoubleParen(']') => { + (Token::DoubleParen(']'), _) => { break; } - Token::Separator(',') if !ready => { + (Token::Separator(','), _) if !ready => { ready = true; } - Token::Word("span") if ready => { + (Token::Word("span"), _) if ready => { lexer.expect(Token::Paren('('))?; //Note: 0 is not handled span = lexer.next_uint_literal()?; lexer.expect(Token::Paren(')'))?; ready = false; } - Token::Word("offset") if ready => { + (Token::Word("offset"), _) if ready => { lexer.expect(Token::Paren('('))?; let _offset = lexer.next_uint_literal()?; lexer.expect(Token::Paren(')'))?; @@ -1251,8 +1253,8 @@ impl Parser { self.scopes.pop(); } let name = match lexer.next() { - Token::Word(word) => word, - Token::Paren('}') => return Ok(members), + (Token::Word(word), _) => word, + (Token::Paren('}'), _) => return Ok(members), other => return Err(Error::Unexpected(other, "field name")), }; lexer.expect(Token::Separator(':'))?; @@ -1588,7 +1590,7 @@ impl Parser { self.scopes.push(Scope::Decoration); loop { match lexer.next() { - Token::Word("access") => { + (Token::Word("access"), _) => { lexer.expect(Token::Paren('('))?; decoration.access = match lexer.next_ident()? { "read" => crate::StorageAccess::LOAD, @@ -1598,14 +1600,14 @@ impl Parser { }; lexer.expect(Token::Paren(')'))?; } - Token::Word("stride") => { + (Token::Word("stride"), _) => { lexer.expect(Token::Paren('('))?; decoration.stride = Some( NonZeroU32::new(lexer.next_uint_literal()?).ok_or(Error::ZeroStride)?, ); lexer.expect(Token::Paren(')'))?; } - Token::DoubleParen(']') => break, + (Token::DoubleParen(']'), _) => break, other => return Err(Error::Unexpected(other, "type decoration")), } } @@ -1634,8 +1636,8 @@ impl Parser { is_uniform_control_flow: bool, ) -> Result<(), Error<'a>> { let word = match lexer.next() { - Token::Separator(';') => return Ok(()), - Token::Paren('{') => { + (Token::Separator(';'), _) => return Ok(()), + (Token::Paren('{'), _) => { self.scopes.push(Scope::Block); let mut statements = Vec::new(); while !lexer.skip(Token::Paren('}')) { @@ -1650,7 +1652,7 @@ impl Parser { block.push(crate::Statement::Block(statements)); return Ok(()); } - Token::Word(word) => word, + (Token::Word(word), _) => word, other => return Err(Error::Unexpected(other, "statement")), }; @@ -1710,7 +1712,7 @@ impl Parser { } } "return" => { - let value = if lexer.peek() != Token::Separator(';') { + let value = if lexer.peek().0 != Token::Separator(';') { Some(self.parse_general_expression(lexer, context.as_expression(block))?) } else { None @@ -1767,19 +1769,19 @@ impl Parser { loop { // cases + default match lexer.next() { - Token::Word("case") => { + (Token::Word("case"), _) => { let value = loop { // values let value = lexer.next_sint_literal()?; match lexer.next() { - Token::Separator(',') => { + (Token::Separator(','), _) => { cases.push(crate::SwitchCase { value, body: Vec::new(), fall_through: true, }); } - Token::Separator(':') => break value, + (Token::Separator(':'), _) => break value, other => { return Err(Error::Unexpected(other, "case separator")) } @@ -1807,11 +1809,11 @@ impl Parser { fall_through, }); } - Token::Word("default") => { + (Token::Word("default"), _) => { lexer.expect(Token::Separator(':'))?; default = self.parse_block(lexer, context.reborrow(), false)?; } - Token::Paren('}') => break, + (Token::Paren('}'), _) => break, other => return Err(Error::Unexpected(other, "switch item")), } } @@ -1873,7 +1875,7 @@ impl Parser { condition }; - let continuing = if let Token::Word(ident) = lexer.peek() { + let continuing = if let Token::Word(ident) = lexer.peek().0 { // manually parse the next statement here instead of calling parse_statement // because the statement is not terminated with a semicolon let _ = lexer.next(); @@ -2145,8 +2147,8 @@ impl Parser { for (i, size) in workgroup_size.iter_mut().enumerate() { *size = lexer.next_uint_literal()?; match lexer.next() { - Token::Paren(')') => break, - Token::Separator(',') if i != 2 => (), + (Token::Paren(')'), _) => break, + (Token::Separator(','), _) if i != 2 => (), other => { return Err(Error::Unexpected( other, @@ -2174,10 +2176,10 @@ impl Parser { word => return Err(Error::UnknownDecoration(word)), } match lexer.next() { - Token::DoubleParen(']') => { + (Token::DoubleParen(']'), _) => { break; } - Token::Separator(',') => {} + (Token::Separator(','), _) => {} other => return Err(Error::Unexpected(other, "decoration separator")), } } @@ -2192,8 +2194,8 @@ impl Parser { // read items match lexer.next() { - Token::Separator(';') => {} - Token::Word("struct") => { + (Token::Separator(';'), _) => {} + (Token::Word("struct"), _) => { let name = lexer.next_ident()?; let members = self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?; @@ -2207,7 +2209,7 @@ impl Parser { self.lookup_type.insert(name.to_owned(), ty); lexer.expect(Token::Separator(';'))?; } - Token::Word("type") => { + (Token::Word("type"), _) => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; let (ty, _access) = self.parse_type_decl( @@ -2219,7 +2221,7 @@ impl Parser { self.lookup_type.insert(name.to_owned(), ty); lexer.expect(Token::Separator(';'))?; } - Token::Word("const") => { + (Token::Word("const"), _) => { let (name, _ty, _access) = self.parse_variable_ident_decl( lexer, &mut module.types, @@ -2236,7 +2238,7 @@ impl Parser { lexer.expect(Token::Separator(';'))?; lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); } - Token::Word("var") => { + (Token::Word("var"), _) => { let pvar = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; let class = match pvar.class { @@ -2271,7 +2273,7 @@ impl Parser { lookup_global_expression .insert(pvar.name, crate::Expression::GlobalVariable(var_handle)); } - Token::Word("fn") => { + (Token::Word("fn"), _) => { let (function, name) = self.parse_function_decl(lexer, module, &lookup_global_expression)?; let already_declared = match stage { @@ -2302,7 +2304,7 @@ impl Parser { return Err(Error::FunctionRedefinition(name)); } } - Token::End => return Ok(false), + (Token::End, _) => return Ok(false), other => return Err(Error::Unexpected(other, "global item")), } From df14c4b7cad34edd99bf7599958615a2a95202a4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 23 Feb 2021 16:55:19 -0500 Subject: [PATCH 0528/2212] [spv-in] fix OpString and OpLine parsing --- src/front/spv/mod.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 8aa5fbaea..16ab05d80 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -599,6 +599,12 @@ impl> Parser { log::debug!("\t\t{:?} [{}]", inst.op, inst.wc); match inst.op { + Op::Line => { + inst.expect(4)?; + let _file_id = self.next()?; + let _row_id = self.next()?; + let _col_id = self.next()?; + } Op::Undef => { inst.expect(3)?; let _result_type_id = self.next()?; @@ -1646,9 +1652,16 @@ impl> Parser { self.index_constants.push(handle); } - while let Ok(inst) = self.next_inst() { + loop { use spirv::Op; + + let inst = match self.next_inst() { + Ok(inst) => inst, + Err(Error::IncompleteData) => break, + Err(other) => return Err(other), + }; log::debug!("\t{:?} [{}]", inst.op, inst.wc); + match inst.op { Op::Capability => self.parse_capability(inst), Op::Extension => self.parse_extension(inst), @@ -1846,7 +1859,8 @@ impl> Parser { fn parse_string(&mut self, inst: Instruction) -> Result<(), Error> { self.switch(ModuleState::Source, inst.op)?; inst.expect_at_least(3)?; - let (_name, _) = self.next_string(inst.wc - 1)?; + let _id = self.next()?; + let (_name, _) = self.next_string(inst.wc - 2)?; Ok(()) } From 51cbd4c1127d5df94b1aaad964482cf124a24bca Mon Sep 17 00:00:00 2001 From: Pelle Johnsen Date: Wed, 24 Feb 2021 18:07:09 +0100 Subject: [PATCH 0529/2212] [glsl-in] Add initial support for glslpp-rs (#513) * [glsl-in] Add initial support for glslpp-rs * [glsl-in] Add remaining Punct mappings Fix some tests. * [glsl-in] Add basic error handling for glslpp-rs * [glsl-in] Fix clippy issues * [glsl.in] Add pp-rs floats * [glsl-in] Remove old lex and preprocessor * [glsl-in] Improve lexer token code * [glsl-in] Rename lex_pp > lex Also LexerPP > Lexer * [glsl-in] glslpp-rs review feedback * [glsl-in] Use rev for pp-rs dep * [glsl-in] Parse on lexer err --- Cargo.toml | 3 +- src/front/glsl/lex.rs | 630 +++++++++++------------------ src/front/glsl/lex_tests.rs | 469 --------------------- src/front/glsl/mod.rs | 9 +- src/front/glsl/parser.rs | 7 +- src/front/glsl/parser_tests.rs | 8 +- src/front/glsl/preprocess.rs | 152 ------- src/front/glsl/preprocess_tests.rs | 228 ----------- 8 files changed, 244 insertions(+), 1262 deletions(-) delete mode 100644 src/front/glsl/lex_tests.rs delete mode 100644 src/front/glsl/preprocess.rs delete mode 100644 src/front/glsl/preprocess_tests.rs diff --git a/Cargo.toml b/Cargo.toml index 109f36584..880f246f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,10 +20,11 @@ pomelo = { version = "0.1.4", optional = true } thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } +pp-rs = { git = "https://github.com/Kangz/glslpp-rs", rev = "4f2f72a", optional = true } [features] default = [] -glsl-in = ["pomelo"] +glsl-in = ["pomelo", "pp-rs"] glsl-validate = [] glsl-out = ["petgraph"] msl-out = [] diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index d0638c3f4..6f72c5c80 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -1,412 +1,248 @@ -use super::parser::Token; -use super::{preprocess::LinePreProcessor, token::TokenMetadata, types::parse_type}; +use super::{parser::Token, token::TokenMetadata, types::parse_type}; use crate::FastHashMap; -use std::{iter::Enumerate, str::Lines}; +use pp_rs::{ + pp::Preprocessor, + token::{Punct, Token as PPToken, TokenValue}, +}; +use std::collections::VecDeque; -fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { - if input.starts_with(what) { - Some(&input[what.len()..]) - } else { - None - } -} - -fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str, usize) { - let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); - let (o, i) = input.split_at(pos); - (o, i, pos) -} - -#[derive(Clone, Debug)] pub struct Lexer<'a> { - lines: Enumerate>, - input: String, - line: usize, - offset: usize, - inside_comment: bool, - pp: LinePreProcessor, + pp: Preprocessor<'a>, + tokens: VecDeque, } impl<'a> Lexer<'a> { - pub fn consume_token(&mut self) -> Option { - let start = self - .input - .find(|c: char| !c.is_whitespace()) - .unwrap_or_else(|| self.input.chars().count()); - let input = &self.input[start..]; - - let mut chars = input.chars(); - let cur = match chars.next() { - Some(c) => c, - None => { - self.input = self.input[start..].into(); - return None; - } - }; - let mut meta = TokenMetadata { - line: 0, - chars: start..start + 1, - }; - let mut consume_all = false; - let token = match cur { - ':' => Some(Token::Colon(meta)), - ';' => Some(Token::Semicolon(meta)), - ',' => Some(Token::Comma(meta)), - '.' => Some(Token::Dot(meta)), - - '(' => Some(Token::LeftParen(meta)), - ')' => Some(Token::RightParen(meta)), - '{' => Some(Token::LeftBrace(meta)), - '}' => Some(Token::RightBrace(meta)), - '[' => Some(Token::LeftBracket(meta)), - ']' => Some(Token::RightBracket(meta)), - '<' | '>' => { - let n1 = chars.next(); - let n2 = chars.next(); - match (cur, n1, n2) { - ('<', Some('<'), Some('=')) => { - meta.chars.end = start + 3; - Some(Token::LeftAssign(meta)) - } - ('>', Some('>'), Some('=')) => { - meta.chars.end = start + 3; - Some(Token::RightAssign(meta)) - } - ('<', Some('<'), _) => { - meta.chars.end = start + 2; - Some(Token::LeftOp(meta)) - } - ('>', Some('>'), _) => { - meta.chars.end = start + 2; - Some(Token::RightOp(meta)) - } - ('<', Some('='), _) => { - meta.chars.end = start + 2; - Some(Token::LeOp(meta)) - } - ('>', Some('='), _) => { - meta.chars.end = start + 2; - Some(Token::GeOp(meta)) - } - ('<', _, _) => Some(Token::LeftAngle(meta)), - ('>', _, _) => Some(Token::RightAngle(meta)), - _ => None, - } - } - '0'..='9' => { - let next = chars.next().and_then(|c| c.to_lowercase().next()); - - let hexadecimal = cur == '0' && next.map_or(false, |c| c == 'x'); - - let (number, remainder, pos) = if hexadecimal { - consume_any(&input[2..], |c| { - ('0'..='9').contains(&c) - || ('a'..='f').contains(&c) - || ('A'..='F').contains(&c) - }) - } else { - consume_any(input, |c| (('0'..='9').contains(&c) || c == '.')) - }; - - let mut remainder_chars = remainder.chars(); - let first = remainder_chars.next().and_then(|c| c.to_lowercase().next()); - - if number.find('.').is_some() { - let second = remainder_chars.next().and_then(|c| c.to_lowercase().next()); - - if (first, second) == (Some('l'), Some('f')) { - meta.chars.end = start + pos + 2; - Some(Token::DoubleConstant((meta, number.parse().unwrap()))) - } else { - meta.chars.end = start + pos; - Some(Token::FloatConstant((meta, number.parse().unwrap()))) - } - } else if first == Some('u') { - if hexadecimal { - meta.chars.end = start + pos + 3; - Some(Token::UintConstant(( - meta, - u64::from_str_radix(number, 16).unwrap(), - ))) - } else { - meta.chars.end = start + pos + 1; - Some(Token::UintConstant((meta, number.parse().unwrap()))) - } - } else if hexadecimal { - meta.chars.end = start + pos + 2; - Some(Token::IntConstant(( - meta, - i64::from_str_radix(number, 16).unwrap(), - ))) - } else { - meta.chars.end = start + pos; - Some(Token::IntConstant((meta, number.parse().unwrap()))) - } - } - 'a'..='z' | 'A'..='Z' | '_' => { - let (word, _, pos) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); - meta.chars.end = start + pos; - match word { - "layout" => Some(Token::Layout(meta)), - "in" => Some(Token::In(meta)), - "out" => Some(Token::Out(meta)), - "uniform" => Some(Token::Uniform(meta)), - "flat" => Some(Token::Interpolation((meta, crate::Interpolation::Flat))), - "noperspective" => { - Some(Token::Interpolation((meta, crate::Interpolation::Linear))) - } - "smooth" => Some(Token::Interpolation(( - meta, - crate::Interpolation::Perspective, - ))), - "centroid" => { - Some(Token::Interpolation((meta, crate::Interpolation::Centroid))) - } - "sample" => Some(Token::Interpolation((meta, crate::Interpolation::Sample))), - // values - "true" => Some(Token::BoolConstant((meta, true))), - "false" => Some(Token::BoolConstant((meta, false))), - // jump statements - "continue" => Some(Token::Continue(meta)), - "break" => Some(Token::Break(meta)), - "return" => Some(Token::Return(meta)), - "discard" => Some(Token::Discard(meta)), - // selection statements - "if" => Some(Token::If(meta)), - "else" => Some(Token::Else(meta)), - "switch" => Some(Token::Switch(meta)), - "case" => Some(Token::Case(meta)), - "default" => Some(Token::Default(meta)), - // iteration statements - "while" => Some(Token::While(meta)), - "do" => Some(Token::Do(meta)), - "for" => Some(Token::For(meta)), - // types - "void" => Some(Token::Void(meta)), - "const" => Some(Token::Const(meta)), - word => { - let token = match parse_type(word) { - Some(t) => Token::TypeName((meta, t)), - None => Token::Identifier((meta, String::from(word))), - }; - Some(token) - } - } - } - '+' | '-' | '&' | '|' | '^' => { - let next = chars.next(); - if next == Some(cur) { - meta.chars.end = start + 2; - match cur { - '+' => Some(Token::IncOp(meta)), - '-' => Some(Token::DecOp(meta)), - '&' => Some(Token::AndOp(meta)), - '|' => Some(Token::OrOp(meta)), - '^' => Some(Token::XorOp(meta)), - _ => None, - } - } else { - match next { - Some('=') => { - meta.chars.end = start + 2; - match cur { - '+' => Some(Token::AddAssign(meta)), - '-' => Some(Token::SubAssign(meta)), - '&' => Some(Token::AndAssign(meta)), - '|' => Some(Token::OrAssign(meta)), - '^' => Some(Token::XorAssign(meta)), - _ => None, - } - } - _ => match cur { - '+' => Some(Token::Plus(meta)), - '-' => Some(Token::Dash(meta)), - '&' => Some(Token::Ampersand(meta)), - '|' => Some(Token::VerticalBar(meta)), - '^' => Some(Token::Caret(meta)), - _ => None, - }, - } - } - } - - '%' | '!' | '=' => match chars.next() { - Some('=') => { - meta.chars.end = start + 2; - match cur { - '%' => Some(Token::ModAssign(meta)), - '!' => Some(Token::NeOp(meta)), - '=' => Some(Token::EqOp(meta)), - _ => None, - } - } - _ => match cur { - '%' => Some(Token::Percent(meta)), - '!' => Some(Token::Bang(meta)), - '=' => Some(Token::Equal(meta)), - _ => None, - }, - }, - - '*' => match chars.next() { - Some('=') => { - meta.chars.end = start + 2; - Some(Token::MulAssign(meta)) - } - Some('/') => { - meta.chars.end = start + 2; - Some(Token::CommentEnd((meta, ()))) - } - _ => Some(Token::Star(meta)), - }, - '/' => { - match chars.next() { - Some('=') => { - meta.chars.end = start + 2; - Some(Token::DivAssign(meta)) - } - Some('/') => { - // consume rest of line - consume_all = true; - None - } - Some('*') => { - meta.chars.end = start + 2; - Some(Token::CommentStart((meta, ()))) - } - _ => Some(Token::Slash(meta)), - } - } - '#' => { - if self.offset == 0 { - let mut input = chars.as_str(); - - // skip whitespace - let word_start = input - .find(|c: char| !c.is_whitespace()) - .unwrap_or_else(|| input.chars().count()); - input = &input[word_start..]; - - let (word, _, pos) = consume_any(input, |c| c.is_alphanumeric() || c == '_'); - meta.chars.end = start + word_start + 1 + pos; - match word { - "version" => Some(Token::Version(meta)), - w => Some(Token::Unknown((meta, w.into()))), - } - - //TODO: preprocessor - // if chars.next() == Some(cur) { - // (Token::TokenPasting, chars.as_str(), start, start + 2) - // } else { - // (Token::Preprocessor, input, start, start + 1) - // } - } else { - Some(Token::Unknown((meta, '#'.to_string()))) - } - } - '~' => Some(Token::Tilde(meta)), - '?' => Some(Token::Question(meta)), - ch => Some(Token::Unknown((meta, ch.to_string()))), - }; - if let Some(token) = token { - let skip_bytes = input - .chars() - .take(token.extra().chars.end - start) - .fold(0, |acc, c| acc + c.len_utf8()); - self.input = input[skip_bytes..].into(); - Some(token) - } else { - if consume_all { - self.input = "".into(); - } else { - self.input = self.input[start..].into(); - } - None + pub fn new(input: &'a str, defines: &'a FastHashMap) -> Self { + let mut pp = Preprocessor::new(input); + for (define, value) in defines { + pp.add_define(define, value).unwrap(); //TODO: handle error + } + Lexer { + pp, + tokens: Default::default(), } } - - pub fn new(input: &'a str, defines: &FastHashMap) -> Self { - let mut lexer = Lexer { - lines: input.lines().enumerate(), - input: "".to_string(), - line: 0, - offset: 0, - inside_comment: false, - pp: LinePreProcessor::new(defines), - }; - lexer.next_line(); - lexer - } - - fn next_line(&mut self) -> bool { - if let Some((line, input)) = self.lines.next() { - let mut input = String::from(input); - - while input.ends_with('\\') { - if let Some((_, next)) = self.lines.next() { - input.pop(); - input.push_str(next); - } else { - break; - } - } - - if let Ok(processed) = self.pp.process_line(&input) { - self.input = processed.unwrap_or_default(); - self.line = line; - self.offset = 0; - true - } else { - //TODO: handle preprocessor error - false - } - } else { - false - } - } - - #[must_use] - pub fn next(&mut self) -> Option { - let token = self.consume_token(); - - if let Some(mut token) = token { - let meta = token.extra_mut(); - let end = meta.chars.end; - meta.line = self.line; - meta.chars.start += self.offset; - meta.chars.end += self.offset; - self.offset += end; - if !self.inside_comment { - match token { - Token::CommentStart(_) => { - self.inside_comment = true; - self.next() - } - _ => Some(token), - } - } else { - if let Token::CommentEnd(_) = token { - self.inside_comment = false; - } - self.next() - } - } else { - if !self.next_line() { - return None; - } - self.next() - } - } - - // #[must_use] - // pub fn peek(&mut self) -> Option { - // self.clone().next() - // } } impl<'a> Iterator for Lexer<'a> { type Item = Token; fn next(&mut self) -> Option { - self.next() + let mut meta = TokenMetadata { + line: 0, + chars: 0..0, + }; + let pp_token = match self.tokens.pop_front() { + Some(t) => t, + None => match self.pp.next()? { + Ok(t) => t, + Err((err, loc)) => { + meta.line = loc.line as usize; + meta.chars.start = loc.pos as usize; + //TODO: proper location end + meta.chars.end = loc.pos as usize + 1; + return Some(Token::Unknown((meta, err))); + } + }, + }; + + meta.line = pp_token.location.line as usize; + meta.chars.start = pp_token.location.pos as usize; + //TODO: proper location end + meta.chars.end = pp_token.location.pos as usize + 1; + Some(match pp_token.value { + TokenValue::Extension(extension) => { + for t in extension.tokens { + self.tokens.push_back(t); + } + Token::Extension((meta, ())) + } + TokenValue::Float(float) => Token::FloatConstant((meta, float.value)), + TokenValue::Ident(ident) => { + match ident.as_str() { + "layout" => Token::Layout(meta), + "in" => Token::In(meta), + "out" => Token::Out(meta), + "uniform" => Token::Uniform(meta), + "flat" => Token::Interpolation((meta, crate::Interpolation::Flat)), + "noperspective" => Token::Interpolation((meta, crate::Interpolation::Linear)), + "smooth" => Token::Interpolation((meta, crate::Interpolation::Perspective)), + "centroid" => Token::Interpolation((meta, crate::Interpolation::Centroid)), + "sample" => Token::Interpolation((meta, crate::Interpolation::Sample)), + // values + "true" => Token::BoolConstant((meta, true)), + "false" => Token::BoolConstant((meta, false)), + // jump statements + "continue" => Token::Continue(meta), + "break" => Token::Break(meta), + "return" => Token::Return(meta), + "discard" => Token::Discard(meta), + // selection statements + "if" => Token::If(meta), + "else" => Token::Else(meta), + "switch" => Token::Switch(meta), + "case" => Token::Case(meta), + "default" => Token::Default(meta), + // iteration statements + "while" => Token::While(meta), + "do" => Token::Do(meta), + "for" => Token::For(meta), + // types + "void" => Token::Void(meta), + "const" => Token::Const(meta), + + word => match parse_type(word) { + Some(t) => Token::TypeName((meta, t)), + None => Token::Identifier((meta, String::from(word))), + }, + } + } + //TODO: unsigned etc + TokenValue::Integer(integer) => Token::IntConstant((meta, integer.value as i64)), + TokenValue::Punct(punct) => match punct { + // Compound assignments + Punct::AddAssign => Token::AddAssign(meta), + Punct::SubAssign => Token::SubAssign(meta), + Punct::MulAssign => Token::MulAssign(meta), + Punct::DivAssign => Token::DivAssign(meta), + Punct::ModAssign => Token::ModAssign(meta), + Punct::LeftShiftAssign => Token::LeftAssign(meta), + Punct::RightShiftAssign => Token::RightAssign(meta), + Punct::AndAssign => Token::AndAssign(meta), + Punct::XorAssign => Token::XorAssign(meta), + Punct::OrAssign => Token::OrAssign(meta), + + // Two character punctuation + Punct::Increment => Token::IncOp(meta), + Punct::Decrement => Token::DecOp(meta), + Punct::LogicalAnd => Token::AndOp(meta), + Punct::LogicalOr => Token::OrOp(meta), + Punct::LogicalXor => Token::XorOp(meta), + Punct::LessEqual => Token::LeOp(meta), + Punct::GreaterEqual => Token::GeOp(meta), + Punct::EqualEqual => Token::EqOp(meta), + Punct::NotEqual => Token::NeOp(meta), + Punct::LeftShift => Token::LeftOp(meta), + Punct::RightShift => Token::RightOp(meta), + + // Parenthesis or similar + Punct::LeftBrace => Token::LeftBrace(meta), + Punct::RightBrace => Token::RightBrace(meta), + Punct::LeftParen => Token::LeftParen(meta), + Punct::RightParen => Token::RightParen(meta), + Punct::LeftBracket => Token::LeftBracket(meta), + Punct::RightBracket => Token::RightBracket(meta), + + // Other one character punctuation + Punct::LeftAngle => Token::LeftAngle(meta), + Punct::RightAngle => Token::RightAngle(meta), + Punct::Semicolon => Token::Semicolon(meta), + Punct::Comma => Token::Comma(meta), + Punct::Colon => Token::Colon(meta), + Punct::Dot => Token::Dot(meta), + Punct::Equal => Token::Equal(meta), + Punct::Bang => Token::Bang(meta), + Punct::Minus => Token::Dash(meta), + Punct::Tilde => Token::Tilde(meta), + Punct::Plus => Token::Plus(meta), + Punct::Star => Token::Star(meta), + Punct::Slash => Token::Slash(meta), + Punct::Percent => Token::Percent(meta), + Punct::Pipe => Token::VerticalBar(meta), + Punct::Caret => Token::Caret(meta), + Punct::Ampersand => Token::Ampersand(meta), + Punct::Question => Token::Question(meta), + }, + TokenValue::Pragma(pragma) => { + for t in pragma.tokens { + self.tokens.push_back(t); + } + Token::Pragma((meta, ())) + } + TokenValue::Version(version) => { + for t in version.tokens { + self.tokens.push_back(t); + } + Token::Version(meta) + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::{ + super::{parser::Token::*, token::TokenMetadata}, + Lexer, + }; + + #[test] + fn lex_tokens() { + let defines = crate::FastHashMap::default(); + + // line comments + let mut lex = Lexer::new("#version 450\nvoid main () {}", &defines); + assert_eq!( + lex.next().unwrap(), + Version(TokenMetadata { + line: 1, + chars: 1..2 //TODO + }) + ); + assert_eq!( + lex.next().unwrap(), + IntConstant(( + TokenMetadata { + line: 1, + chars: 9..10 //TODO + }, + 450 + )) + ); + assert_eq!( + lex.next().unwrap(), + Void(TokenMetadata { + line: 2, + chars: 0..1 //TODO + }) + ); + assert_eq!( + lex.next().unwrap(), + Identifier(( + TokenMetadata { + line: 2, + chars: 5..6 //TODO + }, + "main".into() + )) + ); + assert_eq!( + lex.next().unwrap(), + LeftParen(TokenMetadata { + line: 2, + chars: 10..11 //TODO + }) + ); + assert_eq!( + lex.next().unwrap(), + RightParen(TokenMetadata { + line: 2, + chars: 11..12 //TODO + }) + ); + assert_eq!( + lex.next().unwrap(), + LeftBrace(TokenMetadata { + line: 2, + chars: 13..14 //TODO + }) + ); + assert_eq!( + lex.next().unwrap(), + RightBrace(TokenMetadata { + line: 2, + chars: 14..15 //TODO + }) + ); + assert_eq!(lex.next(), None); } } diff --git a/src/front/glsl/lex_tests.rs b/src/front/glsl/lex_tests.rs deleted file mode 100644 index b2bde5fed..000000000 --- a/src/front/glsl/lex_tests.rs +++ /dev/null @@ -1,469 +0,0 @@ -use super::{lex::Lexer, parser::Token::*, token::TokenMetadata}; - -#[test] -fn tokens() { - let defines = crate::FastHashMap::default(); - - // line comments - let mut lex = Lexer::new("void main // myfunction\n//()\n{}", &defines); - assert_eq!( - lex.next().unwrap(), - Void(TokenMetadata { - line: 0, - chars: 0..4 - }) - ); - assert_eq!( - lex.next().unwrap(), - Identifier(( - TokenMetadata { - line: 0, - chars: 5..9 - }, - "main".into() - )) - ); - assert_eq!( - lex.next().unwrap(), - LeftBrace(TokenMetadata { - line: 2, - chars: 0..1 - }) - ); - assert_eq!( - lex.next().unwrap(), - RightBrace(TokenMetadata { - line: 2, - chars: 1..2 - }) - ); - assert_eq!(lex.next(), None); - - // multi line comment - let mut lex = Lexer::new("void main /* comment [] {}\n/**\n{}*/{}", &defines); - assert_eq!( - lex.next().unwrap(), - Void(TokenMetadata { - line: 0, - chars: 0..4 - }) - ); - assert_eq!( - lex.next().unwrap(), - Identifier(( - TokenMetadata { - line: 0, - chars: 5..9 - }, - "main".into() - )) - ); - assert_eq!( - lex.next().unwrap(), - LeftBrace(TokenMetadata { - line: 2, - chars: 4..5 - }) - ); - assert_eq!( - lex.next().unwrap(), - RightBrace(TokenMetadata { - line: 2, - chars: 5..6 - }) - ); - assert_eq!(lex.next(), None); - - // identifiers - let mut lex = Lexer::new("id123_OK 92No æNoø No¾ No好", &defines); - assert_eq!( - lex.next().unwrap(), - Identifier(( - TokenMetadata { - line: 0, - chars: 0..8 - }, - "id123_OK".into() - )) - ); - assert_eq!( - lex.next().unwrap(), - IntConstant(( - TokenMetadata { - line: 0, - chars: 9..11 - }, - 92 - )) - ); - assert_eq!( - lex.next().unwrap(), - Identifier(( - TokenMetadata { - line: 0, - chars: 11..13 - }, - "No".into() - )) - ); - assert_eq!( - lex.next().unwrap(), - Unknown(( - TokenMetadata { - line: 0, - chars: 14..15 - }, - 'æ'.to_string() - )) - ); - assert_eq!( - lex.next().unwrap(), - Identifier(( - TokenMetadata { - line: 0, - chars: 15..17 - }, - "No".into() - )) - ); - assert_eq!( - lex.next().unwrap(), - Unknown(( - TokenMetadata { - line: 0, - chars: 17..18 - }, - 'ø'.to_string() - )) - ); - assert_eq!( - lex.next().unwrap(), - Identifier(( - TokenMetadata { - line: 0, - chars: 19..21 - }, - "No".into() - )) - ); - assert_eq!( - lex.next().unwrap(), - Unknown(( - TokenMetadata { - line: 0, - chars: 21..22 - }, - '¾'.to_string() - )) - ); - assert_eq!( - lex.next().unwrap(), - Identifier(( - TokenMetadata { - line: 0, - chars: 23..25 - }, - "No".into() - )) - ); - assert_eq!( - lex.next().unwrap(), - Unknown(( - TokenMetadata { - line: 0, - chars: 25..26 - }, - '好'.to_string() - )) - ); - assert_eq!(lex.next(), None); - - // version - let mut lex = Lexer::new("#version 890 core", &defines); - assert_eq!( - lex.next().unwrap(), - Version(TokenMetadata { - line: 0, - chars: 0..8 - }) - ); - assert_eq!( - lex.next().unwrap(), - IntConstant(( - TokenMetadata { - line: 0, - chars: 9..12 - }, - 890 - )) - ); - assert_eq!( - lex.next().unwrap(), - Identifier(( - TokenMetadata { - line: 0, - chars: 13..17 - }, - "core".into() - )) - ); - assert_eq!(lex.next(), None); - - // operators - let mut lex = Lexer::new( - "+ - * | & % / += -= *= |= &= %= /= ++ -- || && ^^", - &defines, - ); - assert_eq!( - lex.next().unwrap(), - Plus(TokenMetadata { - line: 0, - chars: 0..1 - }) - ); - assert_eq!( - lex.next().unwrap(), - Dash(TokenMetadata { - line: 0, - chars: 2..3 - }) - ); - assert_eq!( - lex.next().unwrap(), - Star(TokenMetadata { - line: 0, - chars: 4..5 - }) - ); - assert_eq!( - lex.next().unwrap(), - VerticalBar(TokenMetadata { - line: 0, - chars: 6..7 - }) - ); - assert_eq!( - lex.next().unwrap(), - Ampersand(TokenMetadata { - line: 0, - chars: 8..9 - }) - ); - assert_eq!( - lex.next().unwrap(), - Percent(TokenMetadata { - line: 0, - chars: 10..11 - }) - ); - assert_eq!( - lex.next().unwrap(), - Slash(TokenMetadata { - line: 0, - chars: 12..13 - }) - ); - assert_eq!( - lex.next().unwrap(), - AddAssign(TokenMetadata { - line: 0, - chars: 14..16 - }) - ); - assert_eq!( - lex.next().unwrap(), - SubAssign(TokenMetadata { - line: 0, - chars: 17..19 - }) - ); - assert_eq!( - lex.next().unwrap(), - MulAssign(TokenMetadata { - line: 0, - chars: 20..22 - }) - ); - assert_eq!( - lex.next().unwrap(), - OrAssign(TokenMetadata { - line: 0, - chars: 23..25 - }) - ); - assert_eq!( - lex.next().unwrap(), - AndAssign(TokenMetadata { - line: 0, - chars: 26..28 - }) - ); - assert_eq!( - lex.next().unwrap(), - ModAssign(TokenMetadata { - line: 0, - chars: 29..31 - }) - ); - assert_eq!( - lex.next().unwrap(), - DivAssign(TokenMetadata { - line: 0, - chars: 32..34 - }) - ); - assert_eq!( - lex.next().unwrap(), - IncOp(TokenMetadata { - line: 0, - chars: 35..37 - }) - ); - assert_eq!( - lex.next().unwrap(), - DecOp(TokenMetadata { - line: 0, - chars: 38..40 - }) - ); - assert_eq!( - lex.next().unwrap(), - OrOp(TokenMetadata { - line: 0, - chars: 41..43 - }) - ); - assert_eq!( - lex.next().unwrap(), - AndOp(TokenMetadata { - line: 0, - chars: 44..46 - }) - ); - assert_eq!( - lex.next().unwrap(), - XorOp(TokenMetadata { - line: 0, - chars: 47..49 - }) - ); - assert_eq!(lex.next(), None); - - // float constants - let mut lex = Lexer::new("120.0 130.0lf 140.0Lf 150.0LF", &defines); - assert_eq!( - lex.next().unwrap(), - FloatConstant(( - TokenMetadata { - line: 0, - chars: 0..5 - }, - 120.0, - )) - ); - assert_eq!( - lex.next().unwrap(), - DoubleConstant(( - TokenMetadata { - line: 0, - chars: 6..13 - }, - 130.0, - )) - ); - assert_eq!( - lex.next().unwrap(), - DoubleConstant(( - TokenMetadata { - line: 0, - chars: 14..21 - }, - 140.0, - )) - ); - assert_eq!( - lex.next().unwrap(), - DoubleConstant(( - TokenMetadata { - line: 0, - chars: 22..29 - }, - 150.0, - )) - ); - assert_eq!(lex.next(), None); - - // Integer constants - let mut lex = Lexer::new("120 130u 140U 150 0x1f 0xf2U 0xF1u", &defines); - assert_eq!( - lex.next().unwrap(), - IntConstant(( - TokenMetadata { - line: 0, - chars: 0..3 - }, - 120, - )) - ); - assert_eq!( - lex.next().unwrap(), - UintConstant(( - TokenMetadata { - line: 0, - chars: 4..8 - }, - 130, - )) - ); - assert_eq!( - lex.next().unwrap(), - UintConstant(( - TokenMetadata { - line: 0, - chars: 9..13 - }, - 140, - )) - ); - assert_eq!( - lex.next().unwrap(), - IntConstant(( - TokenMetadata { - line: 0, - chars: 14..17 - }, - 150, - )) - ); - assert_eq!( - lex.next().unwrap(), - IntConstant(( - TokenMetadata { - line: 0, - chars: 18..22 - }, - 31, - )) - ); - assert_eq!( - lex.next().unwrap(), - UintConstant(( - TokenMetadata { - line: 0, - chars: 23..28 - }, - 242, - )) - ); - assert_eq!( - lex.next().unwrap(), - UintConstant(( - TokenMetadata { - line: 0, - chars: 29..34 - }, - 241, - )) - ); - assert_eq!(lex.next(), None); -} diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 92365f59d..327b8424c 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,17 +1,10 @@ use crate::{FastHashMap, Module, ShaderStage}; mod lex; -#[cfg(test)] -mod lex_tests; - -mod preprocess; -#[cfg(test)] -mod preprocess_tests; mod ast; use ast::Program; -use lex::Lexer; mod error; pub use error::ParseError; mod constants; @@ -31,7 +24,7 @@ pub struct Options { pub fn parse_str(source: &str, options: &Options) -> Result { let mut program = Program::new(&options.entry_points); - let lex = Lexer::new(source, &options.defines); + let lex = lex::Lexer::new(source, &options.defines); let mut parser = parser::Parser::new(&mut program); for token in lex { parser.parse(token)?; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 06b2d3e6d..97fa3a35c 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -12,6 +12,7 @@ pomelo! { Statement, StorageAccess, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, FunctionArgument }; + use pp_rs::token::PreprocessorError; } %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; %parser pub struct Parser<'a, 'b> {}; @@ -31,9 +32,9 @@ pomelo! { ErrorKind::ParserStackOverflow } - %type Unknown String; - %type CommentStart (); - %type CommentEnd (); + %type Unknown PreprocessorError; + %type Pragma (); + %type Extension (); %type Identifier String; // constants diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 2fb3357de..de0b4db41 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -32,7 +32,7 @@ fn version() { .err() .unwrap() ), - "InvalidVersion(TokenMetadata { line: 0, chars: 9..14 }, 99000)" + "InvalidVersion(TokenMetadata { line: 1, chars: 9..10 }, 99000)" //TODO: location ); assert_eq!( @@ -40,7 +40,7 @@ fn version() { "{:?}", parse_program("#version 449", &entry_points).err().unwrap() ), - "InvalidVersion(TokenMetadata { line: 0, chars: 9..12 }, 449)" + "InvalidVersion(TokenMetadata { line: 1, chars: 9..10 }, 449)" //TODO: location ); assert_eq!( @@ -50,7 +50,7 @@ fn version() { .err() .unwrap() ), - "InvalidProfile(TokenMetadata { line: 0, chars: 13..18 }, \"smart\")" + "InvalidProfile(TokenMetadata { line: 1, chars: 13..14 }, \"smart\")" //TODO: location ); assert_eq!( @@ -60,7 +60,7 @@ fn version() { .err() .unwrap() ), - "InvalidToken(Unknown((TokenMetadata { line: 1, chars: 11..12 }, \"#\")))" + "InvalidToken(Unknown((TokenMetadata { line: 2, chars: 11..12 }, UnexpectedHash)))" ); // valid versions diff --git a/src/front/glsl/preprocess.rs b/src/front/glsl/preprocess.rs deleted file mode 100644 index f9b5a3fe7..000000000 --- a/src/front/glsl/preprocess.rs +++ /dev/null @@ -1,152 +0,0 @@ -use crate::FastHashMap; -use thiserror::Error; - -#[derive(Clone, Debug, Error)] -#[cfg_attr(test, derive(PartialEq))] -pub enum Error { - #[error("unmatched else")] - UnmatchedElse, - #[error("unmatched endif")] - UnmatchedEndif, - #[error("missing macro name")] - MissingMacro, -} - -#[derive(Clone, Debug)] -pub struct IfState { - true_branch: bool, - else_seen: bool, -} - -#[derive(Clone, Debug)] -pub struct LinePreProcessor { - defines: FastHashMap, - if_stack: Vec, - inside_comment: bool, - in_preprocess: bool, -} - -impl LinePreProcessor { - pub fn new(defines: &FastHashMap) -> Self { - LinePreProcessor { - defines: defines.clone(), - if_stack: vec![], - inside_comment: false, - in_preprocess: false, - } - } - - fn subst_defines(&self, input: &str) -> String { - //TODO: don't subst in commments, strings literals? - self.defines - .iter() - .fold(input.to_string(), |acc, (k, v)| acc.replace(k, v)) - } - - pub fn process_line(&mut self, line: &str) -> Result, Error> { - let mut skip = !self.if_stack.last().map(|i| i.true_branch).unwrap_or(true); - let mut inside_comment = self.inside_comment; - let mut in_preprocess = inside_comment && self.in_preprocess; - // single-line comment - let mut processed = line; - if let Some(pos) = line.find("//") { - processed = line.split_at(pos).0; - } - // multi-line comment - let mut processed_string: String; - loop { - if inside_comment { - if let Some(pos) = processed.find("*/") { - processed = processed.split_at(pos + 2).1; - inside_comment = false; - self.inside_comment = false; - continue; - } - } else if let Some(pos) = processed.find("/*") { - if let Some(end_pos) = processed[pos + 2..].find("*/") { - // comment ends during this line - processed_string = processed.to_string(); - processed_string.replace_range(pos..pos + end_pos + 4, ""); - processed = &processed_string; - } else { - processed = processed.split_at(pos).0; - inside_comment = true; - } - continue; - } - break; - } - // strip leading whitespace - processed = processed.trim_start(); - if processed.starts_with('#') && !self.inside_comment { - let mut iter = processed[1..] - .trim_start() - .splitn(2, |c: char| c.is_whitespace()); - if let Some(directive) = iter.next() { - skip = true; - in_preprocess = true; - match directive { - "version" => { - skip = false; - } - "define" => { - let rest = iter.next().ok_or(Error::MissingMacro)?; - let pos = rest - .find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '(') - .unwrap_or_else(|| rest.len()); - let (key, mut value) = rest.split_at(pos); - value = value.trim(); - self.defines.insert(key.into(), self.subst_defines(value)); - } - "undef" => { - let rest = iter.next().ok_or(Error::MissingMacro)?; - let key = rest.trim(); - self.defines.remove(key); - } - "ifdef" => { - let rest = iter.next().ok_or(Error::MissingMacro)?; - let key = rest.trim(); - self.if_stack.push(IfState { - true_branch: self.defines.contains_key(key), - else_seen: false, - }); - } - "ifndef" => { - let rest = iter.next().ok_or(Error::MissingMacro)?; - let key = rest.trim(); - self.if_stack.push(IfState { - true_branch: !self.defines.contains_key(key), - else_seen: false, - }); - } - "else" => { - let if_state = self.if_stack.last_mut().ok_or(Error::UnmatchedElse)?; - if !if_state.else_seen { - // this is first else - if_state.true_branch = !if_state.true_branch; - if_state.else_seen = true; - } else { - return Err(Error::UnmatchedElse); - } - } - "endif" => { - self.if_stack.pop().ok_or(Error::UnmatchedEndif)?; - } - _ => {} - } - } - } - let res = if !skip && !self.inside_comment { - Ok(Some(self.subst_defines(&line))) - } else { - Ok(if in_preprocess && !self.in_preprocess { - Some("".to_string()) - } else { - None - }) - }; - self.in_preprocess = in_preprocess || skip; - self.inside_comment = inside_comment; - res - } -} diff --git a/src/front/glsl/preprocess_tests.rs b/src/front/glsl/preprocess_tests.rs deleted file mode 100644 index 44e9bf27b..000000000 --- a/src/front/glsl/preprocess_tests.rs +++ /dev/null @@ -1,228 +0,0 @@ -use super::preprocess::{Error, LinePreProcessor}; -use std::{iter::Enumerate, str::Lines}; - -#[derive(Clone, Debug)] -pub struct PreProcessor<'a> { - lines: Enumerate>, - input: String, - line: usize, - offset: usize, - line_pp: LinePreProcessor, -} - -impl<'a> PreProcessor<'a> { - pub fn new(input: &'a str, defines: crate::FastHashMap) -> Self { - let mut lexer = PreProcessor { - lines: input.lines().enumerate(), - input: "".to_string(), - line: 0, - offset: 0, - line_pp: LinePreProcessor::new(&defines), - }; - lexer.next_line(); - lexer - } - - fn next_line(&mut self) -> bool { - if let Some((line, input)) = self.lines.next() { - let mut input = String::from(input); - - while input.ends_with('\\') { - if let Some((_, next)) = self.lines.next() { - input.pop(); - input.push_str(next); - } else { - break; - } - } - - self.input = input; - self.line = line; - self.offset = 0; - true - } else { - false - } - } - - pub fn process(&mut self) -> Result { - let mut res = String::new(); - loop { - let line = &self.line_pp.process_line(&self.input)?; - if let Some(line) = line { - res.push_str(line); - } - if !self.next_line() { - break; - } - if line.is_some() { - res.push_str("\n"); - } - } - Ok(res) - } -} - -#[test] -fn preprocess() { - // line continuation - let mut pp = PreProcessor::new( - "void main my_\ - func", - Default::default(), - ); - assert_eq!(pp.process().unwrap(), "void main my_func"); - - // preserve #version - let mut pp = PreProcessor::new( - "#version 450 core\n\ - void main()", - Default::default(), - ); - assert_eq!(pp.process().unwrap(), "#version 450 core\nvoid main()"); - - // simple define - let mut pp = PreProcessor::new( - "#define FOO 42 \n\ - fun=FOO", - Default::default(), - ); - assert_eq!(pp.process().unwrap(), "\nfun=42"); - - // ifdef with else - let mut pp = PreProcessor::new( - "#define FOO\n\ - #ifdef FOO\n\ - foo=42\n\ - #endif\n\ - some=17\n\ - #ifdef BAR\n\ - bar=88\n\ - #else\n\ - mm=49\n\ - #endif\n\ - done=1", - Default::default(), - ); - assert_eq!( - pp.process().unwrap(), - "\n\ - foo=42\n\ - \n\ - some=17\n\ - \n\ - mm=49\n\ - \n\ - done=1" - ); - - // nested ifdef/ifndef - let mut pp = PreProcessor::new( - "#define FOO\n\ - #define BOO\n\ - #ifdef FOO\n\ - foo=42\n\ - #ifdef BOO\n\ - boo=44\n\ - #endif\n\ - ifd=0\n\ - #ifndef XYZ\n\ - nxyz=8\n\ - #endif\n\ - #endif\n\ - some=17\n\ - #ifdef BAR\n\ - bar=88\n\ - #else\n\ - mm=49\n\ - #endif\n\ - done=1", - Default::default(), - ); - assert_eq!( - pp.process().unwrap(), - "\n\ - foo=42\n\ - \n\ - boo=44\n\ - \n\ - ifd=0\n\ - \n\ - nxyz=8\n\ - \n\ - some=17\n\ - \n\ - mm=49\n\ - \n\ - done=1" - ); - - // undef - let mut pp = PreProcessor::new( - "#define FOO\n\ - #ifdef FOO\n\ - foo=42\n\ - #endif\n\ - some=17\n\ - #undef FOO\n\ - #ifdef FOO\n\ - foo=88\n\ - #else\n\ - nofoo=66\n\ - #endif\n\ - done=1", - Default::default(), - ); - assert_eq!( - pp.process().unwrap(), - "\n\ - foo=42\n\ - \n\ - some=17\n\ - \n\ - nofoo=66\n\ - \n\ - done=1" - ); - - // single-line comment - let mut pp = PreProcessor::new( - "#define FOO 42//1234\n\ - fun=FOO", - Default::default(), - ); - assert_eq!(pp.process().unwrap(), "\nfun=42"); - - // multi-line comments - let mut pp = PreProcessor::new( - "#define FOO 52/*/1234\n\ - #define FOO 88\n\ - end of comment*/ /* one more comment */ #define FOO 56\n\ - fun=FOO", - Default::default(), - ); - assert_eq!(pp.process().unwrap(), "\nfun=56"); - - // unmatched endif - let mut pp = PreProcessor::new( - "#ifdef FOO\n\ - foo=42\n\ - #endif\n\ - #endif", - Default::default(), - ); - assert_eq!(pp.process(), Err(Error::UnmatchedEndif)); - - // unmatched else - let mut pp = PreProcessor::new( - "#ifdef FOO\n\ - foo=42\n\ - #else\n\ - bar=88\n\ - #else\n\ - bad=true\n\ - #endif", - Default::default(), - ); - assert_eq!(pp.process(), Err(Error::UnmatchedElse)); -} From 822be23f358c980986f393702a80dbe608f1f7a7 Mon Sep 17 00:00:00 2001 From: Anthony Cowley Date: Wed, 24 Feb 2021 12:47:02 -0500 Subject: [PATCH 0530/2212] Validate signed integer array size constants (#517) Until we have some amount of type inference, an integer literal used as a constant array size must have a `u` suffix. This is inconsistent with the surface syntax presented in the spec, and is a minor inconvenience. For now, allow a signed integer array size to pass validation so that user code need not change when type inference deduces values of the correct type. --- src/proc/layouter.rs | 8 ++++++++ src/proc/validator.rs | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index a7d0f0f11..89986e5ae 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -73,6 +73,14 @@ impl Layouter { width: _, value: crate::ScalarValue::Uint(value), } => value as u32, + // Accept a signed integer size to avoid + // requiring an explicit uint + // literal. Type inference should make + // this unnecessary. + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Sint(value), + } => value as u32, ref other => unreachable!("Unexpected array size {:?}", other), }, crate::ArraySize::Dynamic => 1, diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 9288a1ac9..8643e6036 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -474,6 +474,18 @@ impl Validator { }, .. }) => {} + // Accept a signed integer size to avoid + // requiring an explicit uint + // literal. Type inference should make + // this unnecessary. + Some(&crate::Constant { + inner: + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Sint(_), + }, + .. + }) => {} other => { log::warn!("Array size {:?}", other); return Err(TypeError::InvalidArraySizeConstant(const_handle)); From 1dc955551bdcd91fd4e1e96cab823dadd1fc8493 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Feb 2021 09:57:35 -0500 Subject: [PATCH 0531/2212] [spv-out] use image_fetch where appropriate (#522) --- src/back/spv/instructions.rs | 14 ++++++++++++++ src/back/spv/writer.rs | 17 ++++++++++++----- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 82af2d35f..f8366b96c 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -552,6 +552,20 @@ impl super::Instruction { instruction } + pub(super) fn image_fetch( + result_type_id: Word, + id: Word, + image: Word, + coordinates: Word, + ) -> Self { + let mut instruction = Self::new(Op::ImageFetch); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(image); + instruction.add_operand(coordinates); + instruction + } + pub(super) fn image_read( result_type_id: Word, id: Word, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 984f01fab..189876b00 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1601,19 +1601,26 @@ impl Writer { )?; let id = self.generate_id(); - let mut instruction = - Instruction::image_read(result_type_id, id, image_id, coordinate_id); + + let image_ty = self.typifier.get(image, &ir_module.types); + let mut instruction = match *image_ty { + crate::TypeInner::Image { + class: crate::ImageClass::Storage { .. }, + .. + } => Instruction::image_read(result_type_id, id, image_id, coordinate_id), + _ => Instruction::image_fetch(result_type_id, id, image_id, coordinate_id), + }; if let Some(index) = index { - let index_id = - self.write_expression(ir_module, ir_function, index, block, function)?; - let image_ops = match *self.typifier.get(image, &ir_module.types) { + let image_ops = match *image_ty { crate::TypeInner::Image { class: crate::ImageClass::Sampled { multi: true, .. }, .. } => spirv::ImageOperands::SAMPLE, _ => spirv::ImageOperands::LOD, }; + let index_id = + self.write_expression(ir_module, ir_function, index, block, function)?; instruction.add_operand(image_ops.bits()); instruction.add_operand(index_id); } From cb45cd9011a4ea3d73f57176eace36a1a457a5b2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 24 Feb 2021 09:37:19 -0500 Subject: [PATCH 0532/2212] [spv-in] dump the flow graph before it's serialized --- examples/convert.rs | 3 ++- src/front/spv/function.rs | 23 ++++++++++++++--------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/examples/convert.rs b/examples/convert.rs index 2174cdaf1..e14804901 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -76,9 +76,10 @@ fn main() { } let param_path = std::path::PathBuf::from(&args[1]).with_extension("param.ron"); - let params = match fs::read_to_string(param_path) { + let params = match fs::read_to_string(¶m_path) { Ok(string) => ron::de::from_str(&string).unwrap_pretty(), Err(_) => { + log::warn!("Param file {:?} not found, using defaults", param_path); let mut param = Parameters::default(); // very useful to have this by default param.spv_capabilities.insert(spirv::Capability::Shader); diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 8675e5393..307d39855 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -142,14 +142,26 @@ impl> super::Parser { flow_graph.classify(); flow_graph.remove_phi_instructions(&self.lookup_expression); + + if let Some(ref prefix) = self.options.flow_graph_dump_prefix { + let dump = flow_graph.to_graphviz().unwrap_or_default(); + let dump_suffix = match self.lookup_entry_point.get(&fun_id) { + Some(ep) => format!("flow.{:?}-{}.dot", ep.stage, ep.name), + None => format!("flow.Fun-{}.dot", module.functions.len()), + }; + let dest = prefix.join(dump_suffix); + if let Err(e) = std::fs::write(&dest, dump) { + log::error!("Unable to dump the flow graph into {:?}: {}", dest, e); + } + } + fun.body = flow_graph.to_naga()?; // done self.patch_function_calls(&mut fun)?; - let dump_suffix = match self.lookup_entry_point.remove(&fun_id) { + match self.lookup_entry_point.remove(&fun_id) { Some(ep) => { - let dump_name = format!("flow.{:?}-{}.dot", ep.stage, ep.name); module.entry_points.insert( (ep.stage, ep.name), crate::EntryPoint { @@ -158,20 +170,13 @@ impl> super::Parser { function: fun, }, ); - dump_name } None => { let handle = module.functions.append(fun); self.lookup_function.insert(fun_id, handle); - format!("flow.Fun-{}.dot", handle.index()) } }; - if let Some(ref prefix) = self.options.flow_graph_dump_prefix { - let dump = flow_graph.to_graphviz().unwrap_or_default(); - let _ = std::fs::write(prefix.join(dump_suffix), dump); - } - self.lookup_expression.clear(); self.lookup_sampled_image.clear(); Ok(()) From afbcf05006dd789012caa115cbc40af6b4c59c3c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 24 Feb 2021 10:49:27 -0500 Subject: [PATCH 0533/2212] Move the convert from an example to a binary target --- Cargo.toml | 8 +- README.md | 9 ++ bin/convert.rs | 233 ++++++++++++++++++++++++++++++++ examples/convert.rs | 310 ------------------------------------------- src/back/glsl/mod.rs | 10 ++ src/back/msl/mod.rs | 2 +- src/back/spv/mod.rs | 10 +- 7 files changed, 265 insertions(+), 317 deletions(-) create mode 100644 bin/convert.rs delete mode 100644 examples/convert.rs diff --git a/Cargo.toml b/Cargo.toml index 880f246f2..6c85ab552 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,8 +34,9 @@ spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] wgsl-in = [] -#Note: it would be nice to do `cargo run` for conversion. -# Blocked on https://github.com/rust-lang/cargo/issues/4663 +[[bin]] +name = "convert" +path = "bin/convert.rs" [dev-dependencies] difference = "2.0" @@ -43,6 +44,5 @@ env_logger = "0.8" ron = "0.6" serde = { version = "1.0", features = ["derive"] } spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } -# `similar` dependency, introduced in 1.5.3, breaks MSRV -insta = { version = "=1.5.2", features = ["glob"] } +insta = { version = "1.6", features = ["glob"] } rspirv = "0.7" diff --git a/README.md b/README.md index bd7e5d44f..5e04f2372 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,15 @@ DXBC | | | :white_check_mark: = Primary support — :ok: = Secondary support — :construction: = Unsupported, but support in progress +## Conversion tool + +Naga includes a default binary target "convert", which allows to test the conversion of different code paths. +```bash +cargo run --features spv-in -- my_shader.spv # dump the IR module to debug output +cargo run --features spv-in,msl-out -- my_shader.spv my_shader.metal --flow-dir flow-dir # convert the SPV to Metal, also dump the SPIR-V flow graph to `flow-dir` +cargo run --features wgsl-in,glsl-out -- my_shader.wgsl my_shader.vert --profile es310 # convert the WGSL to GLSL vertex stage under ES 3.20 profile +``` + ## Development workflow The main instrument aiding the development is the good old `cargo test --all-features`, diff --git a/bin/convert.rs b/bin/convert.rs new file mode 100644 index 000000000..f3cf33e50 --- /dev/null +++ b/bin/convert.rs @@ -0,0 +1,233 @@ +#![allow(clippy::manual_strip)] +#[allow(unused_imports)] +use std::fs; +use std::{env, error::Error, path::Path}; + +#[derive(Default)] +struct Parameters { + spv_flow_dump_prefix: Option, + #[cfg(feature = "spv-out")] + spv: naga::back::spv::Options, + #[cfg(feature = "msl-out")] + msl: naga::back::msl::Options, + #[cfg(feature = "glsl-out")] + glsl: naga::back::glsl::Options, +} + +trait PrettyResult { + type Target; + fn unwrap_pretty(self) -> Self::Target; +} + +impl PrettyResult for Result { + type Target = T; + fn unwrap_pretty(self) -> T { + match self { + Result::Ok(value) => value, + Result::Err(error) => { + println!("{}:", error); + let mut e = error.source(); + while let Some(source) = e { + println!("\t{}", source); + e = source.source(); + } + std::process::exit(1); + } + } + } +} + +fn main() { + let mut input_path = None; + let mut output_path = None; + //TODO: read the parameters from RON? + let mut params = Parameters::default(); + + let mut args = env::args(); + let _ = args.next().unwrap(); + while let Some(arg) = args.next() { + //TODO: use `strip_prefix` when MSRV reaches 1.45.0 + if arg.starts_with("--") { + match &arg[2..] { + "flow-dir" => params.spv_flow_dump_prefix = args.next(), + #[cfg(feature = "glsl-out")] + "entry-point" => params.glsl.entry_point = args.next().unwrap(), + #[cfg(feature = "glsl-out")] + "profile" => { + use naga::back::glsl::Version; + let string = args.next().unwrap(); + //TODO: use `strip_prefix` in 1.45.0 + params.glsl.version = if string.starts_with("core") { + Version::Desktop(string[4..].parse().unwrap_or(330)) + } else if string.starts_with("es") { + Version::Embedded(string[2..].parse().unwrap_or(310)) + } else { + panic!("Unknown profile: {}", string) + }; + } + other => log::warn!("Unknown parameter: {}", other), + } + } else if input_path.is_none() { + input_path = Some(arg); + } else if output_path.is_none() { + output_path = Some(arg); + } else { + log::warn!("Extra parameter: {}", arg); + } + } + + let input_path = match input_path { + Some(ref string) => string, + None => { + println!("Call with []"); + return; + } + }; + let module = match Path::new(input_path) + .extension() + .expect("Input has no extension?") + .to_str() + .unwrap() + { + #[cfg(feature = "spv-in")] + "spv" => { + let options = naga::front::spv::Options { + flow_graph_dump_prefix: params.spv_flow_dump_prefix.map(std::path::PathBuf::from), + }; + let input = fs::read(input_path).unwrap(); + naga::front::spv::parse_u8_slice(&input, &options).unwrap() + } + #[cfg(feature = "wgsl-in")] + "wgsl" => { + let input = fs::read_to_string(input_path).unwrap(); + naga::front::wgsl::parse_str(&input).unwrap_pretty() + } + #[cfg(feature = "glsl-in")] + "vert" => { + let input = fs::read_to_string(input_path).unwrap(); + let mut entry_points = naga::FastHashMap::default(); + entry_points.insert("main".to_string(), naga::ShaderStage::Vertex); + naga::front::glsl::parse_str( + &input, + &naga::front::glsl::Options { + entry_points, + defines: Default::default(), + }, + ) + .unwrap_pretty() + } + #[cfg(feature = "glsl-in")] + "frag" => { + let input = fs::read_to_string(input_path).unwrap(); + let mut entry_points = naga::FastHashMap::default(); + entry_points.insert("main".to_string(), naga::ShaderStage::Fragment); + naga::front::glsl::parse_str( + &input, + &naga::front::glsl::Options { + entry_points, + defines: Default::default(), + }, + ) + .unwrap_pretty() + } + #[cfg(feature = "glsl-in")] + "comp" => { + let input = fs::read_to_string(input_path).unwrap(); + let mut entry_points = naga::FastHashMap::default(); + entry_points.insert("main".to_string(), naga::ShaderStage::Compute); + naga::front::glsl::parse_str( + &input, + &naga::front::glsl::Options { + entry_points, + defines: Default::default(), + }, + ) + .unwrap_pretty() + } + other => { + if true { + // prevent "unreachable_code" warnings + panic!("Unknown input extension: {}", other); + } + naga::Module::default() + } + }; + + let output_path = match output_path { + Some(ref string) => string, + None => { + println!("{:#?}", module); + return; + } + }; + + // validate the IR + #[allow(unused_variables)] + let analysis = naga::proc::Validator::new() + .validate(&module) + .unwrap_pretty(); + + match Path::new(output_path) + .extension() + .expect("Output has no extension?") + .to_str() + .unwrap() + { + #[cfg(feature = "msl-out")] + "metal" => { + use naga::back::msl; + let (msl, _) = msl::write_string(&module, &analysis, ¶ms.msl).unwrap_pretty(); + fs::write(output_path, msl).unwrap(); + } + #[cfg(feature = "spv-out")] + "spv" => { + use naga::back::spv; + + let spv = spv::write_vec(&module, &analysis, ¶ms.spv).unwrap_pretty(); + let bytes = spv + .iter() + .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { + v.extend_from_slice(&w.to_le_bytes()); + v + }); + + fs::write(output_path, bytes.as_slice()).unwrap(); + } + #[cfg(feature = "glsl-out")] + stage @ "vert" | stage @ "frag" | stage @ "comp" => { + use naga::back::glsl; + + params.glsl.shader_stage = match stage { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + _ => unreachable!(), + }; + + let file = fs::OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(output_path) + .unwrap(); + + let mut writer = + glsl::Writer::new(file, &module, &analysis, ¶ms.glsl).unwrap_pretty(); + + writer + .write() + .map_err(|e| { + fs::remove_file(output_path).unwrap(); + e + }) + .unwrap(); + } + other => { + let _ = params; + panic!( + "Unknown output extension: {}, forgot to enable a feature?", + other + ); + } + } +} diff --git a/examples/convert.rs b/examples/convert.rs deleted file mode 100644 index e14804901..000000000 --- a/examples/convert.rs +++ /dev/null @@ -1,310 +0,0 @@ -use std::{env, error::Error, fs, path::Path}; - -#[derive(Hash, PartialEq, Eq, serde::Deserialize)] -enum Stage { - Vertex, - Fragment, - Compute, -} - -#[derive(Hash, PartialEq, Eq, serde::Deserialize)] -struct BindSource { - stage: Stage, - group: u32, - binding: u32, -} - -#[derive(serde::Deserialize)] -struct BindTarget { - #[serde(default)] - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - buffer: Option, - #[serde(default)] - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - texture: Option, - #[serde(default)] - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - sampler: Option, - #[serde(default)] - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - mutable: bool, -} - -#[derive(Default, serde::Deserialize)] -struct Parameters { - #[serde(default)] - #[cfg_attr(not(feature = "spv-in"), allow(dead_code))] - spv_flow_dump_prefix: String, - #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] - spv_version: (u8, u8), - #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] - spv_capabilities: naga::FastHashSet, - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - mtl_bindings: naga::FastHashMap, -} - -trait PrettyResult { - type Target; - fn unwrap_pretty(self) -> Self::Target; -} - -impl PrettyResult for Result { - type Target = T; - fn unwrap_pretty(self) -> T { - match self { - Result::Ok(value) => value, - Result::Err(error) => { - println!("{}:", error); - let mut e = error.source(); - while let Some(source) = e { - println!("\t{}", source); - e = source.source(); - } - std::process::exit(1); - } - } - } -} - -fn main() { - env_logger::init(); - - let args = env::args().collect::>(); - if args.len() <= 1 { - println!("Call with "); - return; - } - - let param_path = std::path::PathBuf::from(&args[1]).with_extension("param.ron"); - let params = match fs::read_to_string(¶m_path) { - Ok(string) => ron::de::from_str(&string).unwrap_pretty(), - Err(_) => { - log::warn!("Param file {:?} not found, using defaults", param_path); - let mut param = Parameters::default(); - // very useful to have this by default - param.spv_capabilities.insert(spirv::Capability::Shader); - param.spv_version = (1, 0); - param - } - }; - - let module = match Path::new(&args[1]) - .extension() - .expect("Input has no extension?") - .to_str() - .unwrap() - { - #[cfg(feature = "spv-in")] - "spv" => { - let options = naga::front::spv::Options { - flow_graph_dump_prefix: if params.spv_flow_dump_prefix.is_empty() { - None - } else { - Some(params.spv_flow_dump_prefix.into()) - }, - }; - let input = fs::read(&args[1]).unwrap(); - naga::front::spv::parse_u8_slice(&input, &options).unwrap() - } - #[cfg(feature = "wgsl-in")] - "wgsl" => { - let input = fs::read_to_string(&args[1]).unwrap(); - naga::front::wgsl::parse_str(&input).unwrap_pretty() - } - #[cfg(feature = "glsl-in")] - "vert" => { - let input = fs::read_to_string(&args[1]).unwrap(); - let mut entry_points = naga::FastHashMap::default(); - entry_points.insert("main".to_string(), naga::ShaderStage::Vertex); - naga::front::glsl::parse_str( - &input, - &naga::front::glsl::Options { - entry_points, - defines: Default::default(), - }, - ) - .unwrap_pretty() - } - #[cfg(feature = "glsl-in")] - "frag" => { - let input = fs::read_to_string(&args[1]).unwrap(); - let mut entry_points = naga::FastHashMap::default(); - entry_points.insert("main".to_string(), naga::ShaderStage::Fragment); - naga::front::glsl::parse_str( - &input, - &naga::front::glsl::Options { - entry_points, - defines: Default::default(), - }, - ) - .unwrap_pretty() - } - #[cfg(feature = "glsl-in")] - "comp" => { - let input = fs::read_to_string(&args[1]).unwrap(); - let mut entry_points = naga::FastHashMap::default(); - entry_points.insert("main".to_string(), naga::ShaderStage::Compute); - naga::front::glsl::parse_str( - &input, - &naga::front::glsl::Options { - entry_points, - defines: Default::default(), - }, - ) - .unwrap_pretty() - } - #[cfg(feature = "deserialize")] - "ron" => { - let mut input = fs::File::open(&args[1]).unwrap(); - ron::de::from_reader(&mut input).unwrap_pretty() - } - other => { - if true { - // prevent "unreachable_code" warnings - panic!("Unknown input extension: {}", other); - } - naga::Module::default() - } - }; - - if args.len() <= 2 { - println!("{:#?}", module); - return; - } - - // validate the IR - #[allow(unused_variables)] - let analysis = naga::proc::Validator::new() - .validate(&module) - .unwrap_pretty(); - - match Path::new(&args[2]) - .extension() - .expect("Output has no extension?") - .to_str() - .unwrap() - { - #[cfg(feature = "msl-out")] - "metal" => { - use naga::back::msl; - let mut options = msl::Options { - lang_version: (1, 0), - binding_map: msl::BindingMap::default(), - spirv_cross_compatibility: false, - fake_missing_bindings: false, - }; - if params.mtl_bindings.is_empty() { - log::warn!("Metal binding map is missing"); - options.fake_missing_bindings = true; - } else { - for (key, value) in params.mtl_bindings { - options.binding_map.insert( - msl::BindSource { - stage: match key.stage { - Stage::Vertex => naga::ShaderStage::Vertex, - Stage::Fragment => naga::ShaderStage::Fragment, - Stage::Compute => naga::ShaderStage::Compute, - }, - group: key.group, - binding: key.binding, - }, - msl::BindTarget { - buffer: value.buffer, - texture: value.texture, - sampler: value.sampler, - mutable: value.mutable, - }, - ); - } - } - let (msl, _) = msl::write_string(&module, &analysis, &options).unwrap_pretty(); - fs::write(&args[2], msl).unwrap(); - } - #[cfg(feature = "spv-out")] - "spv" => { - use naga::back::spv; - - let options = spv::Options { - lang_version: params.spv_version, - flags: args.get(3).map_or(spv::WriterFlags::DEBUG, |arg| { - if arg.parse().unwrap() { - spv::WriterFlags::DEBUG - } else { - spv::WriterFlags::empty() - } - }), - capabilities: params.spv_capabilities, - }; - - let spv = spv::write_vec(&module, &analysis, &options).unwrap_pretty(); - - let bytes = spv - .iter() - .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { - v.extend_from_slice(&w.to_le_bytes()); - v - }); - - fs::write(&args[2], bytes.as_slice()).unwrap(); - } - #[cfg(feature = "glsl-out")] - stage @ "vert" | stage @ "frag" | stage @ "comp" => { - use naga::back::glsl; - - let version = { - let arg = args.get(3).map_or("es", |p| p.as_str()); - if arg.starts_with("core") { - glsl::Version::Desktop(arg[4..].parse().unwrap_or(330)) - } else if arg.starts_with("es") { - glsl::Version::Embedded(arg[2..].parse().unwrap_or(310)) - } else { - panic!("Unknown profile: {}", arg) - } - }; - let name = args.get(4).map_or("main", |p| p.as_str()).to_string(); - let options = glsl::Options { - version, - shader_stage: match stage { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - _ => unreachable!(), - }, - entry_point: name, - }; - - let file = fs::OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(&args[2]) - .unwrap(); - - let mut writer = glsl::Writer::new(file, &module, &analysis, &options).unwrap_pretty(); - - writer - .write() - .map_err(|e| { - fs::remove_file(&args[2]).unwrap(); - e - }) - .unwrap(); - } - #[cfg(feature = "serialize")] - "ron" => { - let config = ron::ser::PrettyConfig::new() - .with_enumerate_arrays(true) - .with_decimal_floats(true); - - let output = ron::ser::to_string_pretty(&module, config).unwrap_pretty(); - fs::write(&args[2], output).unwrap(); - } - other => { - let _ = params; - panic!( - "Unknown output extension: {}, forgot to enable a feature?", - other - ); - } - } -} diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 38a416ac6..e1b03ab2d 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -135,6 +135,16 @@ pub struct Options { pub entry_point: String, } +impl Default for Options { + fn default() -> Self { + Options { + version: Version::Embedded(320), + shader_stage: ShaderStage::Compute, + entry_point: "main".to_string(), + } + } +} + /// Structure that connects a texture to a sampler or not /// /// glsl pre vulkan has no concept of separate textures and samplers instead everything is a diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index ecf9eee7d..353b1e148 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -106,7 +106,7 @@ impl Default for Options { lang_version: (1, 0), binding_map: BindingMap::default(), spirv_cross_compatibility: false, - fake_missing_bindings: false, + fake_missing_bindings: true, } } } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 346aca071..4a780f2ef 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -57,10 +57,16 @@ pub struct Options { impl Default for Options { fn default() -> Self { + let mut flags = WriterFlags::empty(); + if cfg!(debug_assertions) { + flags |= WriterFlags::DEBUG; + } + let mut capabilities = crate::FastHashSet::default(); + capabilities.insert(Capability::Shader); Options { lang_version: (1, 0), - flags: WriterFlags::empty(), - capabilities: Default::default(), + flags, + capabilities, } } } From 7c2f4eac2e09d657ed345160b7e284ba214ca7c5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Feb 2021 21:08:54 -0500 Subject: [PATCH 0534/2212] [spv] fix unsigned selector and bitcast --- src/back/spv/writer.rs | 4 ---- src/front/spv/mod.rs | 22 +++++++++++++++++++++- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 189876b00..02485c02a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1555,10 +1555,6 @@ impl Writer { kind, convert, } => { - if !convert { - return Err(Error::FeatureNotImplemented("bitcast")); - } - let expr_id = self.write_expression(ir_module, ir_function, expr, block, function)?; let expr_kind = self diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 16ab05d80..2bf98b8b9 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1466,9 +1466,29 @@ impl> Parser { inst.expect_at_least(3)?; let selector = self.next()?; - let selector = self.lookup_expression[&selector].handle; let default = self.next()?; + let selector_lexp = &self.lookup_expression[&selector]; + let selector_lty = self.lookup_type.lookup(selector_lexp.type_id)?; + let selector = match type_arena[selector_lty.handle].inner { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + } => { + // IR expects a signed integer, so do a bitcast + expressions.append(crate::Expression::As { + kind: crate::ScalarKind::Sint, + expr: selector_lexp.handle, + convert: false, + }) + } + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => selector_lexp.handle, + ref other => unimplemented!("Unexpected selector {:?}", other), + }; + let mut targets = Vec::new(); for _ in 0..(inst.wc - 3) / 2 { let literal = self.next()?; From 53f7f9de9255fd01023788d533573ec48388c576 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Tal=C4=8D=C3=ADk?= Date: Fri, 26 Feb 2021 10:39:44 +0100 Subject: [PATCH 0535/2212] spv-in: fix if branches in CFG format --- src/front/spv/flow.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index f18746484..7471281ab 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -251,12 +251,21 @@ impl FlowGraph { reject: self.naga_traverse(false_node_index, Some(merge_node_index))?, }); } else { + let true_merges_to_false = has_path_connecting( + &self.flow, + true_node_index, + false_node_index, + None, + ); + let stop_node_index = if true_merges_to_false { + Some(merge_node_index) + } else { + stop_node_index + }; + result.push(crate::Statement::If { condition, - accept: self.naga_traverse( - self.block_to_node[&true_id], - Some(merge_node_index), - )?, + accept: self.naga_traverse(true_node_index, stop_node_index)?, reject: vec![], }); } From bb7105387d8ce07180f8e183eb315363189c5ae7 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Sun, 28 Feb 2021 00:52:34 -0330 Subject: [PATCH 0536/2212] [wgsl-in] Use codespan to report errors --- Cargo.toml | 3 +- bin/convert.rs | 9 ++- src/front/wgsl/lexer.rs | 6 +- src/front/wgsl/mod.rs | 164 ++++++++++++++++++++++++++++++---------- tests/errors.rs | 16 +++- 5 files changed, 148 insertions(+), 50 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6c85ab552..43e16fde9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ license = "MIT OR Apache-2.0" [dependencies] bitflags = "1" bit-set = "0.5" +codespan-reporting = { version = "0.11.0", optional = true } fxhash = "0.2" log = "0.4" num-traits = "0.2" @@ -32,7 +33,7 @@ serialize = ["serde"] deserialize = ["serde"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] -wgsl-in = [] +wgsl-in = ["codespan-reporting"] [[bin]] name = "convert" diff --git a/bin/convert.rs b/bin/convert.rs index f3cf33e50..2726ae44b 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -100,7 +100,14 @@ fn main() { #[cfg(feature = "wgsl-in")] "wgsl" => { let input = fs::read_to_string(input_path).unwrap(); - naga::front::wgsl::parse_str(&input).unwrap_pretty() + let result = naga::front::wgsl::parse_str(&input); + match result { + Ok(v) => v, + Err(ref e) => { + e.emit_to_stderr(); + panic!("unable to parse WGSL"); + } + } } #[cfg(feature = "glsl-in")] "vert" => { diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index cd2aa04d0..bc6e9fe05 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -258,7 +258,7 @@ impl<'a> Lexer<'a> { pub(super) fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { match self.next() { (Token::Word(word), _) => Ok(word), - other => Err(Error::Unexpected(other, "ident")), + other => Err(Error::Unexpected(other, "identifier")), } } @@ -305,10 +305,6 @@ impl<'a> Lexer<'a> { self.expect(Token::Paren('>'))?; Ok(format) } - - pub(super) fn offset_from(&self, source: &'a str) -> usize { - source.len() - self.input.len() - } } #[cfg(test)] diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5e369f4e8..e313bc553 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -14,11 +14,21 @@ use crate::{ }; use self::lexer::Lexer; -use std::{num::NonZeroU32, ops::Range}; +use codespan_reporting::{ + diagnostic::{Diagnostic, Label}, + files::SimpleFile, + term::{ + self, + termcolor::{ColorChoice, ColorSpec, StandardStream, WriteColor}, + }, +}; +use std::{ + io::{self, Write}, + num::NonZeroU32, + ops::Range, +}; use thiserror::Error; -const SPACE: &str = " "; - type TokenSpan<'a> = (Token<'a>, Range); #[derive(Copy, Clone, Debug, PartialEq)] @@ -44,6 +54,27 @@ pub enum Token<'a> { End, } +impl<'a> Error<'a> { + fn as_parse_error(&self, source: &'a str) -> ParseError<'a> { + match self { + Error::Unexpected((_, unexpected_span), expected) => ParseError { + message: format!( + "expected {}, found '{}'", + expected, + &source[unexpected_span.clone()] + ), + labels: vec![(unexpected_span.clone(), format!("expected {}", expected))], + source, + }, + error => ParseError { + message: error.to_string(), + labels: Vec::new(), + source, + }, + } + } +} + #[derive(Clone, Debug, Error)] pub enum Error<'a> { #[error("unexpected token {:?}, expected {1}", (.0).0)] @@ -332,13 +363,55 @@ struct ParsedVariable<'a> { init: Option>, } -#[derive(Clone, Debug, Error)] -#[error("error while parsing WGSL in scopes {scopes:?} at line {line} pos {pos}: {error}")] +#[derive(Clone, Debug)] pub struct ParseError<'a> { - pub error: Error<'a>, - pub scopes: Vec, - pub line: usize, - pub pos: usize, + message: String, + labels: Vec<(Range, String)>, + source: &'a str, +} + +impl<'a> ParseError<'a> { + fn diagnostic(&self) -> Diagnostic<()> { + let diagnostic = Diagnostic::error() + .with_message(self.message.to_string()) + .with_labels( + self.labels + .iter() + .map(|label| { + Label::primary((), label.0.clone()).with_message(label.1.to_string()) + }) + .collect(), + ); + diagnostic + } + + pub fn emit_to_stderr(&self) { + let files = SimpleFile::new("wgsl", self.source); + let config = codespan_reporting::term::Config::default(); + let writer = StandardStream::stderr(ColorChoice::Always); + term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) + .expect("cannot write error"); + } + + pub fn emit_to_string(&self) -> String { + let files = SimpleFile::new("wgsl", self.source); + let config = codespan_reporting::term::Config::default(); + let mut writer = StringErrorBuffer::new(); + term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); + writer.into_string() + } +} + +impl<'a> std::fmt::Display for ParseError<'a> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.message) + } +} + +impl<'a> std::error::Error for ParseError<'a> { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + None + } } pub struct Parser { @@ -2324,42 +2397,12 @@ impl Parser { let mut lookup_global_expression = FastHashMap::default(); loop { match self.parse_global_decl(&mut lexer, &mut module, &mut lookup_global_expression) { - Err(error) => { - let pos = lexer.offset_from(source); - let (mut rows, mut cols) = (0, 1); - let (mut prev_line, mut cur_line) = ("", ""); - for line in source[..pos].lines() { - rows += 1; - cols = line.len(); - prev_line = cur_line; - cur_line = line; - } - log::error!("|\t{}", prev_line); - log::error!( - ">\t{}{}", - cur_line, - source[pos..].lines().next().unwrap_or_default() - ); - if cols <= SPACE.len() { - log::error!("|\t{}^", &SPACE[..cols]); - } - return Err(ParseError { - error, - scopes: std::mem::replace(&mut self.scopes, Vec::new()), - line: rows, - pos: cols, - }); - } + Err(error) => return Err(error.as_parse_error(lexer.source)), Ok(true) => {} Ok(false) => { if !self.scopes.is_empty() { log::error!("Reached the end of file, but scopes are not closed"); - return Err(ParseError { - error: Error::Other, - scopes: std::mem::replace(&mut self.scopes, Vec::new()), - line: 0, - pos: 0, - }); + return Err(Error::Other.as_parse_error(lexer.source)); }; return Ok(module); } @@ -2371,3 +2414,42 @@ impl Parser { pub fn parse_str(source: &str) -> Result { Parser::new().parse(source) } + +pub struct StringErrorBuffer { + buf: Vec, +} + +impl StringErrorBuffer { + pub fn new() -> Self { + Self { buf: Vec::new() } + } + + pub fn into_string(self) -> String { + String::from_utf8(self.buf).unwrap() + } +} + +impl Write for StringErrorBuffer { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.buf.extend(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl WriteColor for StringErrorBuffer { + fn supports_color(&self) -> bool { + false + } + + fn set_color(&mut self, _spec: &ColorSpec) -> io::Result<()> { + Ok(()) + } + + fn reset(&mut self) -> io::Result<()> { + Ok(()) + } +} diff --git a/tests/errors.rs b/tests/errors.rs index 81841a82e..d8d355e3e 100644 --- a/tests/errors.rs +++ b/tests/errors.rs @@ -1,7 +1,12 @@ #[cfg(feature = "wgsl-in")] macro_rules! err { ($value:expr, @$snapshot:literal) => { - ::insta::assert_snapshot!(naga::front::wgsl::parse_str($value).expect_err("expected parser error").to_string(), @$snapshot); + ::insta::assert_snapshot!( + naga::front::wgsl::parse_str($value) + .expect_err("expected parser error") + .emit_to_string(), + @$snapshot + ); }; } @@ -10,6 +15,13 @@ macro_rules! err { fn function_without_identifier() { err!( "fn () {}", - @"error while parsing WGSL in scopes [FunctionDecl] at line 1 pos 4: unexpected token Paren('('), expected ident" + @r###" + error: expected identifier, found '(' + ┌─ wgsl:1:4 + │ + 1 │ fn () {} + │ ^ expected identifier + + "### ); } From 34c549d49d85ac947405377cf63d8a3f09f7c73b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Tal=C4=8D=C3=ADk?= Date: Mon, 1 Mar 2021 09:41:48 +0100 Subject: [PATCH 0537/2212] spv-in flow: fix loop --- src/front/spv/flow.rs | 16 ++-------------- tests/out/shadow.info.ron.snap | 5 +++-- tests/out/shadow.ron.snap | 5 ----- 3 files changed, 5 insertions(+), 21 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 7471281ab..c4b910c8f 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -1,4 +1,4 @@ -#![allow(dead_code)] + #![allow(dead_code)] use super::error::Error; ///! see https://en.wikipedia.org/wiki/Control-flow_graph @@ -394,19 +394,7 @@ impl FlowGraph { }; Ok(result) } - Some(ControlFlowNodeType::Continue) => { - let back_block = match node.terminator { - Terminator::Branch { target_id } => { - self.naga_traverse(self.block_to_node[&target_id], None)? - } - _ => return Err(Error::InvalidTerminator), - }; - - let mut result = node.block.clone(); - result.extend(back_block); - result.push(crate::Statement::Continue); - Ok(result) - } + Some(ControlFlowNodeType::Continue) => Ok(node.block.clone()), Some(ControlFlowNodeType::Back) => Ok(node.block.clone()), Some(ControlFlowNodeType::Kill) => { let mut result = node.block.clone(); diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index d0d632509..1e2dc996e 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -1,6 +1,7 @@ --- source: tests/snapshots.rs expression: output + --- ( functions: [ @@ -878,7 +879,7 @@ expression: output control_flags: ( bits: 1, ), - ref_count: 12, + ref_count: 11, assignable_global: None, ), ( @@ -1214,7 +1215,7 @@ expression: output control_flags: ( bits: 1, ), - ref_count: 2, + ref_count: 1, assignable_global: None, ), ( diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index 3a7d33ffe..e20132627 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -1107,11 +1107,6 @@ expression: output pointer: 43, value: 91, ), - Store( - pointer: 44, - value: 92, - ), - Continue, ], continuing: [ Store( From 96527290f3829a5fdd437b7f055b1baf2e04f525 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 27 Feb 2021 22:06:57 -0500 Subject: [PATCH 0538/2212] [wgsl-in] encapsulate logic into parse_statement_restricted --- src/front/wgsl/mod.rs | 86 +++++++++++++++++++------------------------ 1 file changed, 38 insertions(+), 48 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e313bc553..6dcda90bc 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1701,6 +1701,36 @@ impl Parser { Ok((handle, storage_access)) } + /// Parse a statement that is either an assignment or a function call. + fn parse_statement_restricted<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + ident: &'a str, + mut context: ExpressionContext<'a, '_, 'out>, + ) -> Result> { + Ok(match context.lookup_ident.get(ident) { + Some(&expr) => { + let left = self.parse_postfix(lexer, context.reborrow(), expr)?; + lexer.expect(Token::Operation('='))?; + let value = self.parse_general_expression(lexer, context)?; + crate::Statement::Store { + pointer: left, + value, + } + } + None => { + let (function, arguments) = self + .parse_local_function_call(lexer, ident, context)? + .ok_or(Error::UnknownLocalFunction(ident))?; + crate::Statement::Call { + function, + arguments, + result: None, + } + } + }) + } + fn parse_statement<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, @@ -1952,33 +1982,11 @@ impl Parser { // manually parse the next statement here instead of calling parse_statement // because the statement is not terminated with a semicolon let _ = lexer.next(); - Some(match context.lookup_ident.get(ident) { - Some(&var_expr) => { - let left = - self.parse_postfix(lexer, context.as_expression(block), var_expr)?; - lexer.expect(Token::Operation('='))?; - let value = - self.parse_general_expression(lexer, context.as_expression(block))?; - crate::Statement::Store { - pointer: left, - value, - } - } - None => { - let (function, arguments) = self - .parse_local_function_call( - lexer, - ident, - context.as_expression(block), - )? - .ok_or(Error::UnknownLocalFunction(ident))?; - crate::Statement::Call { - function, - arguments, - result: None, - } - } - }) + Some(self.parse_statement_restricted( + lexer, + ident, + context.as_expression(block), + )?) } else { None }; @@ -2034,27 +2042,9 @@ impl Parser { } // assignment or a function call ident => { - let stmt = if let Some(&var_expr) = context.lookup_ident.get(ident) { - let left = self.parse_postfix(lexer, context.as_expression(block), var_expr)?; - lexer.expect(Token::Operation('='))?; - let value = - self.parse_general_expression(lexer, context.as_expression(block))?; - lexer.expect(Token::Separator(';'))?; - crate::Statement::Store { - pointer: left, - value, - } - } else { - let (function, arguments) = self - .parse_local_function_call(lexer, ident, context.as_expression(block))? - .ok_or(Error::UnknownLocalFunction(ident))?; - lexer.expect(Token::Separator(';'))?; - crate::Statement::Call { - function, - arguments, - result: None, - } - }; + let stmt = + self.parse_statement_restricted(lexer, ident, context.as_expression(block))?; + lexer.expect(Token::Separator(';'))?; block.push(stmt); } } From 69bf7f5f17b346bd4f634fc569211d84a3bb587e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 1 Mar 2021 09:30:32 -0500 Subject: [PATCH 0539/2212] Miscellaneous fixes --- Cargo.toml | 1 - README.md | 2 +- src/front/spv/flow.rs | 2 +- tests/snapshots.rs | 3 --- 4 files changed, 2 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 43e16fde9..8e9b5dac5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,6 @@ path = "bin/convert.rs" [dev-dependencies] difference = "2.0" -env_logger = "0.8" ron = "0.6" serde = { version = "1.0", features = ["derive"] } spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } diff --git a/README.md b/README.md index 5e04f2372..ff661d556 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Back-end | Status | Notes | SPIR-V (binary) | :white_check_mark: | | WGSL | | | Metal | :white_check_mark: | | -HLSL | | | +HLSL | :construction: | | GLSL | :ok: | | AIR | | | DXIL/DXIR | | | diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index c4b910c8f..9c9386c14 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -1,4 +1,4 @@ - #![allow(dead_code)] +#![allow(dead_code)] use super::error::Error; ///! see https://en.wikipedia.org/wiki/Control-flow_graph diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 02e8cd2da..01b21dedc 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -40,9 +40,6 @@ struct BindTarget { #[derive(Default, serde::Deserialize)] struct Parameters { - #[serde(default)] - #[allow(dead_code)] - spv_flow_dump_prefix: String, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_version: (u8, u8), #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] From 04b1f44396604b4038606b83014423e309bc215c Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 1 Mar 2021 18:10:01 +0300 Subject: [PATCH 0540/2212] [glsl-out] Fix atan2 math function --- src/back/glsl/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index e1b03ab2d..c5de5a1d8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1599,7 +1599,9 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Acos => "acos", Mf::Asin => "asin", Mf::Atan => "atan", - Mf::Atan2 => "atan2", + // glsl doesn't have atan2 function + // use two-argument variation of the atan function + Mf::Atan2 => "atan", // decomposition Mf::Ceil => "ceil", Mf::Floor => "floor", From 6e37f336bd1a095de3e49ca8e2bcd28607657b29 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 2 Mar 2021 19:12:00 +0000 Subject: [PATCH 0541/2212] [glsl-out] Set workgroup_size for compute shaders --- src/back/glsl/mod.rs | 10 ++++++++++ tests/out/empty-Compute.glsl.snap | 2 ++ 2 files changed, 12 insertions(+) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c5de5a1d8..d5a091a86 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -376,6 +376,16 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out)?; } + if self.options.shader_stage == ShaderStage::Compute { + let workgroup_size = self.entry_point.workgroup_size; + writeln!( + self.out, + "layout(local_size_x = {}, local_size_y = {}, local_size_z = {}) in;", + workgroup_size[0], workgroup_size[1], workgroup_size[2] + )?; + writeln!(self.out)?; + } + // Enable early depth tests if needed if let Some(depth_test) = self.entry_point.early_depth_test { writeln!(self.out, "layout(early_fragment_tests) in;")?; diff --git a/tests/out/empty-Compute.glsl.snap b/tests/out/empty-Compute.glsl.snap index 2a8a2b72e..1ec91e280 100644 --- a/tests/out/empty-Compute.glsl.snap +++ b/tests/out/empty-Compute.glsl.snap @@ -6,6 +6,8 @@ expression: string precision highp float; +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + void main() { return; } From 230ec601ed77af734312c23a369865420a5724ca Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 2 Mar 2021 22:40:25 +0000 Subject: [PATCH 0542/2212] [glsl-out] Fix array writing --- src/back/glsl/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index d5a091a86..229d68b14 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -557,8 +557,9 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Pointer { base, .. } => self.write_type(base)?, // Arrays are written as `base[size]` TypeInner::Array { base, size, .. } => { - self.write_type(base)?; + let ty_name = &self.names[&NameKey::Type(base)]; + write!(self.out, "{}", ty_name)?; write!(self.out, "[")?; // Write the array size From 89e37d6e9073d6cb3cbd4815a2502a0b84c7fee0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 24 Feb 2021 09:12:14 -0500 Subject: [PATCH 0543/2212] Explicitly emit expressions by Statement::Emit --- src/arena.rs | 67 ++- src/back/glsl/mod.rs | 53 +- src/back/mod.rs | 16 + src/back/msl/writer.rs | 109 +---- src/back/spv/writer.rs | 633 ++++++++++++------------ src/front/mod.rs | 26 + src/front/spv/image.rs | 24 +- src/front/spv/mod.rs | 53 +- src/front/wgsl/mod.rs | 291 ++++++----- src/lib.rs | 32 +- src/proc/analyzer.rs | 2 +- src/proc/interface.rs | 5 +- src/proc/mod.rs | 13 + src/proc/terminator.rs | 26 +- src/proc/typifier.rs | 16 +- src/proc/validator.rs | 156 +++++- tests/out/boids.spvasm.snap | 722 +++++++++++++--------------- tests/out/collatz.info.ron.snap | 81 +++- tests/out/collatz.msl.snap | 4 +- tests/out/collatz.ron.snap | 151 ++++-- tests/out/collatz.spvasm.snap | 188 ++++---- tests/out/empty.spvasm.snap | 4 +- tests/out/quad-Fragment.glsl.snap | 1 + tests/out/quad-Vertex.glsl.snap | 3 + tests/out/quad.msl.snap | 3 +- tests/out/quad.spvasm.snap | 120 ++--- tests/out/shadow.info.ron.snap | 328 ++++++++++--- tests/out/shadow.msl.snap | 10 +- tests/out/shadow.ron.snap | 273 +++++++---- tests/out/shadow.spvasm.snap | 446 +++++++---------- tests/out/skybox-Fragment.glsl.snap | 1 + tests/out/skybox-Vertex.glsl.snap | 19 +- tests/out/skybox.msl.snap | 16 +- tests/out/skybox.spvasm.snap | 365 ++++++-------- tests/out/texture-array.spvasm.snap | 133 ++--- tests/parse.rs | 3 +- tests/snapshots.rs | 7 +- 37 files changed, 2486 insertions(+), 1914 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 9af0808e4..35171e3f1 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -1,11 +1,11 @@ -use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32}; +use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32, ops}; /// An unique index in the arena array that a handle points to. /// The "non-zero" part ensures that an `Option>` has /// the same size and representation as `Handle`. type Index = NonZeroU32; -/// A strongly typed reference to a SPIR-V element. +/// A strongly typed reference to an arena item. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[cfg_attr( @@ -75,6 +75,47 @@ impl Handle { } } +/// A strongly typed range of handles. +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +#[cfg_attr( + any(feature = "serialize", feature = "deserialize"), + serde(transparent) +)] +pub struct Range { + inner: ops::Range, + #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))] + marker: PhantomData, +} + +impl Clone for Range { + fn clone(&self) -> Self { + Range { + inner: self.inner.clone(), + marker: self.marker, + } + } +} +impl fmt::Debug for Range { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "{}..{}", self.inner.start, self.inner.end) + } +} +impl Iterator for Range { + type Item = Handle; + fn next(&mut self) -> Option { + if self.inner.start < self.inner.end { + self.inner.start += 1; + Some(Handle { + index: NonZeroU32::new(self.inner.start).unwrap(), + marker: self.marker, + }) + } else { + None + } + } +} + /// An arena holding some kind of component (e.g., type, constant, /// instruction, etc.) that can be referenced. /// @@ -141,8 +182,6 @@ impl Arena { } /// Adds a new value to the arena, returning a typed handle. - /// - /// The value is not linked to any SPIR-V module. pub fn append(&mut self, value: T) -> Handle { let position = self.data.len() + 1; let index = unsafe { Index::new_unchecked(position as u32) }; @@ -187,13 +226,27 @@ impl Arena { pub fn get_mut(&mut self, handle: Handle) -> &mut T { self.data.get_mut(handle.index.get() as usize - 1).unwrap() } + + /// Get the range of handles from a particular number of elements to the end. + pub fn range_from(&self, old_length: usize) -> Range { + Range { + inner: old_length as u32..self.data.len() as u32, + marker: PhantomData, + } + } } -impl std::ops::Index> for Arena { +impl ops::Index> for Arena { type Output = T; fn index(&self, handle: Handle) -> &T { - let index = handle.index.get() - 1; - &self.data[index as usize] + &self.data[handle.index()] + } +} + +impl ops::Index> for Arena { + type Output = [T]; + fn index(&self, range: Range) -> &[T] { + &self.data[range.inner.start as usize..range.inner.end as usize] } } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 229d68b14..59be2ffb6 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -44,7 +44,10 @@ pub use features::Features; use crate::{ - proc::{analyzer::Analysis, NameKey, Namer, ResolveContext, Typifier, TypifyError}, + proc::{ + analyzer::{Analysis, FunctionInfo}, + EntryPointIndex, NameKey, Namer, ResolveContext, Typifier, TypifyError, + }, Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ScalarValue, @@ -169,13 +172,15 @@ enum FunctionType { /// A regular function and it's handle Function(Handle), /// A entry point and it's index - EntryPoint(crate::proc::EntryPointIndex), + EntryPoint(EntryPointIndex), } /// Helper structure that stores data needed when writing the function struct FunctionCtx<'a, 'b> { /// The current function being written func: FunctionType, + /// Analysis about the function + info: &'a FunctionInfo, /// The expression arena of the current function being written expressions: &'a Arena, /// A typifier that has already resolved all expressions in the function being written @@ -283,7 +288,7 @@ pub struct Writer<'a, W> { /// The selected entry point entry_point: &'a crate::EntryPoint, /// The index of the selected entry point - entry_point_idx: crate::proc::EntryPointIndex, + entry_point_idx: EntryPointIndex, /// Used to generate a unique number for blocks block_id: IdGenerator, /// Set of expressions that have associated temporary variables @@ -499,8 +504,10 @@ impl<'a, W: Write> Writer<'a, W> { // We also `clone` to satisfy the borrow checker let name = self.names[&NameKey::Function(handle)].clone(); + let fun_info = &self.analysis[handle]; + // Write the function - self.write_function(FunctionType::Function(handle), function, name)?; + self.write_function(FunctionType::Function(handle), function, fun_info, name)?; writeln!(self.out)?; } @@ -508,6 +515,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_function( FunctionType::EntryPoint(self.entry_point_idx), &self.entry_point.function, + ep_info, "main", )?; @@ -762,6 +770,7 @@ impl<'a, W: Write> Writer<'a, W> { &mut self, ty: FunctionType, func: &Function, + info: &FunctionInfo, name: N, ) -> BackendResult { // Create a new typifier and resolve all types for the current function @@ -781,6 +790,7 @@ impl<'a, W: Write> Writer<'a, W> { // Create a function context for the function being written let ctx = FunctionCtx { func: ty, + info, expressions: &func.expressions, typifier: &typifier, }; @@ -991,6 +1001,30 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}", INDENT.repeat(indent))?; match *sta { + // This is where we can generate intermediate constants for some expression types. + Statement::Emit(ref range) => { + let mut indented = true; + for handle in range.clone() { + if let Ok(ty_handle) = ctx.typifier.get_handle(handle) { + let min_ref_count = ctx.expressions[handle].bake_ref_count(); + if min_ref_count <= ctx.info[handle].ref_count { + if !indented { + write!(self.out, "{}", INDENT.repeat(indent))?; + } + let name = format!("_expr{}", handle.index()); + self.write_type(ty_handle)?; + write!(self.out, " {} = ", name)?; + self.write_expr(handle, ctx)?; + writeln!(self.out, ";")?; + self.cached_expressions.insert(handle, name); + indented = false; + } + } + } + if indented { + writeln!(self.out, ";")?; + } + } // Blocks are simple we just need to write the block statements between braces // We could also just print the statements but this is more readable and maps more // closely to the IR @@ -1171,7 +1205,7 @@ impl<'a, W: Write> Writer<'a, W> { let name = format!("_expr{}", expr.index()); let ty = self.module.functions[function].return_type.unwrap(); self.write_type(ty)?; - write!(self.out, "{} = ", name)?; + write!(self.out, " {} = ", name)?; self.cached_expressions.insert(expr, name); } write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; @@ -1188,6 +1222,10 @@ impl<'a, W: Write> Writer<'a, W> { /// # Notes /// Doesn't add any newlines or leading/trailing spaces fn write_expr(&mut self, expr: Handle, ctx: &FunctionCtx<'_, '_>) -> BackendResult { + if let Some(name) = self.cached_expressions.get(&expr) { + write!(self.out, "{}", name)?; + return Ok(()); + } match ctx.expressions[expr] { // `Access` is applied to arrays, vectors and matrices and is written as indexing Expression::Access { base, index } => { @@ -1716,10 +1754,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(expr, ctx)?; write!(self.out, ")")? } - Expression::Call(_function) => { - let name = &self.cached_expressions[&expr]; - write!(self.out, "{}", name)?; - } + Expression::Call(_function) => unreachable!(), // `ArrayLength` is written as `expr.length()` and we convert it to a uint Expression::ArrayLength(expr) => { write!(self.out, "uint(")?; diff --git a/src/back/mod.rs b/src/back/mod.rs index bc96dd349..b3369c0d7 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -6,3 +6,19 @@ pub mod glsl; pub mod msl; #[cfg(feature = "spv-out")] pub mod spv; + +impl crate::Expression { + /// Returns the ref count, upon reaching which this expression + /// should be considered for baking. + #[allow(dead_code)] + fn bake_ref_count(&self) -> usize { + match *self { + // accesses are never cached, only loads are + crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => !0, + // image operations look better when isolated + crate::Expression::ImageSample { .. } | crate::Expression::ImageLoad { .. } => 1, + // cache expressions that are referenced multiple times + _ => 2, + } + } +} diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 52dcc7158..01d29368c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3,7 +3,7 @@ use crate::{ arena::Handle, proc::{ analyzer::{Analysis, FunctionInfo, GlobalUse}, - EntryPointIndex, Interface, NameKey, Namer, ResolveContext, Typifier, Visitor, + EntryPointIndex, NameKey, Namer, ResolveContext, Typifier, }, FastHashMap, }; @@ -11,7 +11,7 @@ use bit_set::BitSet; use std::{ fmt::{Display, Error as FmtError, Formatter}, io::Write, - iter, mem, + iter, }; const NAMESPACE: &str = "metal"; @@ -71,10 +71,8 @@ pub struct Writer { out: W, names: FastHashMap, named_expressions: BitSet, - visit_mask: BitSet, typifier: Typifier, namer: Namer, - temp_bake_handles: Vec>, } fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { @@ -122,39 +120,6 @@ impl crate::StorageClass { } } -struct BakeExpressionVisitor<'a> { - named_expressions: &'a mut BitSet, - bake_handles: &'a mut Vec>, - fun_info: &'a FunctionInfo, - exclude: Option>, -} -impl Visitor for BakeExpressionVisitor<'_> { - fn visit_expr(&mut self, handle: Handle, expr: &crate::Expression) { - use crate::Expression as E; - // filter out the expressions that don't need to bake - let min_ref_count = match *expr { - // The following expressions can be inlined nicely. - E::AccessIndex { .. } - | E::Constant(_) - | E::FunctionArgument(_) - | E::GlobalVariable(_) - | E::LocalVariable(_) => !0, - // Image sampling and function calling are nice to isolate - // into separate statements even when done only once. - E::ImageSample { .. } | E::ImageLoad { .. } | E::Call { .. } => 1, - // Bake only expressions referenced more than once. - _ => 2, - }; - - let modifier = if self.exclude == Some(handle) { 1 } else { 0 }; - if self.fun_info[handle].ref_count - modifier >= min_ref_count - && self.named_expressions.insert(handle.index()) - { - self.bake_handles.push(handle); - } - } -} - enum FunctionOrigin { Handle(Handle), EntryPoint(EntryPointIndex), @@ -180,10 +145,8 @@ impl Writer { out, names: FastHashMap::default(), named_expressions: BitSet::new(), - visit_mask: BitSet::new(), typifier: Typifier::new(), namer: Namer::default(), - temp_bake_handles: Vec::new(), } } @@ -693,49 +656,6 @@ impl Writer { Ok(()) } - // Write down any required intermediate results - fn prepare_expression( - &mut self, - level: Level, - root_handle: Handle, - context: &StatementContext, - exclude_root: bool, - ) -> Result<(), Error> { - // set up the search - self.visit_mask.clear(); - let mut interface = Interface { - expressions: &context.expression.function.expressions, - local_variables: &context.expression.function.local_variables, - visitor: BakeExpressionVisitor { - named_expressions: &mut self.named_expressions, - bake_handles: &mut self.temp_bake_handles, - fun_info: context.fun_info, - exclude: if exclude_root { - Some(root_handle) - } else { - None - }, - }, - mask: &mut self.visit_mask, - }; - // populate the bake handles - interface.traverse_expr(root_handle); - // bake - let mut temp_bake_handles = mem::replace(&mut self.temp_bake_handles, Vec::new()); - for handle in temp_bake_handles.drain(..).rev() { - write!(self.out, "{}", level)?; - self.start_baking_expression(handle)?; - // Make sure to temporarily unblock the expression before writing it down. - self.named_expressions.remove(handle.index()); - self.put_expression(handle, &context.expression)?; - self.named_expressions.insert(handle.index()); - writeln!(self.out, ";")?; - } - - self.temp_bake_handles = temp_bake_handles; - Ok(()) - } - fn put_block( &mut self, level: Level, @@ -745,6 +665,19 @@ impl Writer { for statement in statements { log::trace!("statement[{}] {:?}", level.0, statement); match *statement { + crate::Statement::Emit(ref range) => { + for handle in range.clone() { + let min_ref_count = + context.expression.function.expressions[handle].bake_ref_count(); + if min_ref_count <= context.fun_info[handle].ref_count { + write!(self.out, "{}", level)?; + self.start_baking_expression(handle)?; + self.put_expression(handle, &context.expression)?; + writeln!(self.out, ";")?; + self.named_expressions.insert(handle.index()); + } + } + } crate::Statement::Block(ref block) => { if !block.is_empty() { writeln!(self.out, "{}{{", level)?; @@ -757,7 +690,6 @@ impl Writer { ref accept, ref reject, } => { - self.prepare_expression(level.clone(), condition, context, false)?; write!(self.out, "{}if (", level)?; self.put_expression(condition, &context.expression)?; writeln!(self.out, ") {{")?; @@ -773,7 +705,6 @@ impl Writer { ref cases, ref default, } => { - self.prepare_expression(level.clone(), selector, context, false)?; write!(self.out, "{}switch(", level)?; self.put_expression(selector, &context.expression)?; writeln!(self.out, ") {{")?; @@ -819,7 +750,6 @@ impl Writer { crate::Statement::Return { value: Some(expr_handle), } => { - self.prepare_expression(level.clone(), expr_handle, context, true)?; write!(self.out, "{}return ", level)?; self.put_expression(expr_handle, &context.expression)?; writeln!(self.out, ";")?; @@ -836,7 +766,6 @@ impl Writer { writeln!(self.out, "{}discard_fragment();", level)?; } crate::Statement::Store { pointer, value } => { - self.prepare_expression(level.clone(), value, context, true)?; write!(self.out, "{}", level)?; self.put_expression(pointer, &context.expression)?; write!(self.out, " = ")?; @@ -849,11 +778,6 @@ impl Writer { array_index, value, } => { - self.prepare_expression(level.clone(), value, context, true)?; - self.prepare_expression(level.clone(), coordinate, context, false)?; - if let Some(expr) = array_index { - self.prepare_expression(level.clone(), expr, context, false)?; - } write!(self.out, "{}", level)?; self.put_expression(image, &context.expression)?; write!(self.out, ".write(")?; @@ -871,9 +795,6 @@ impl Writer { ref arguments, result, } => { - for &arg in arguments { - self.prepare_expression(level.clone(), arg, context, false)?; - } write!(self.out, "{}", level)?; if let Some(expr) = result { self.start_baking_expression(expr)?; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 02485c02a..47375182d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -8,7 +8,7 @@ use crate::{ }, }; use spirv::Word; -use std::collections::hash_map::Entry; +use std::{collections::hash_map::Entry, ops}; use thiserror::Error; const BITS_PER_BYTE: crate::Bytes = 8; @@ -19,7 +19,7 @@ pub enum Error { UnsupportedVersion(u8, u8), #[error("one of the required capabilities {0:?} is missing")] MissingCapabilities(Vec), - #[error("unimplemented {0:}")] + #[error("unimplemented {0}")] FeatureNotImplemented(&'static str), #[error(transparent)] Resolve(#[from] TypifyError), @@ -46,11 +46,6 @@ struct LocalVariable { instruction: Instruction, } -enum RawExpression { - Value(Word), - Pointer(Word, spirv::StorageClass), -} - #[derive(Default)] struct Function { signature: Option, @@ -181,6 +176,47 @@ struct LoopContext { break_id: Option, } +#[derive(Default)] +struct CachedExpressions { + ids: Vec, +} +impl CachedExpressions { + fn reset(&mut self, length: usize) { + self.ids.clear(); + self.ids.resize(length, 0); + } +} +impl ops::Index> for CachedExpressions { + type Output = Word; + fn index(&self, h: Handle) -> &Word { + let id = &self.ids[h.index()]; + if *id == 0 { + unreachable!("Expression {:?} is not cached!", h); + } + id + } +} +impl ops::IndexMut> for CachedExpressions { + fn index_mut(&mut self, h: Handle) -> &mut Word { + let id = &mut self.ids[h.index()]; + if *id != 0 { + unreachable!("Expression {:?} is already cached!", h); + } + id + } +} + +struct GlobalVariable { + /// Actual ID of the variable. + id: Word, + /// For `StorageClass::Handle` variables, this ID is recorded in the function + /// prelude block (and reset before every function) as `OpLoad` of the variable. + /// It is then used for all the global ops, such as `OpImageSample`. + handle_id: Word, + /// SPIR-V storage class. + class: spirv::StorageClass, +} + pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, @@ -190,25 +226,23 @@ pub struct Writer { annotations: Vec, flags: WriterFlags, void_type: u32, + //TODO: convert most of these into vectors, addressable by handle indices lookup_type: crate::FastHashMap, lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, lookup_function_call: crate::FastHashMap, Word>, lookup_constant: crate::FastHashMap, Word>, - lookup_global_variable: - crate::FastHashMap, (Word, spirv::StorageClass)>, + global_variables: Vec, + cached: CachedExpressions, // TODO: this is a type property that depends on the global variable that uses it // so it may require us to duplicate the type! struct_type_handles: crate::FastHashMap, crate::StorageAccess>, gl450_ext_inst_id: Word, layouter: Layouter, typifier: Typifier, + temp_chain: Vec, } -// type alias, for success return of write_expression -type ExpressionId = Word; -type PointerExpressionId = (Word, spirv::StorageClass); - impl Writer { pub fn new(options: &Options) -> Result { let (major, minor) = options.lang_version; @@ -232,11 +266,13 @@ impl Writer { lookup_function_type: crate::FastHashMap::default(), lookup_function_call: crate::FastHashMap::default(), lookup_constant: crate::FastHashMap::default(), - lookup_global_variable: crate::FastHashMap::default(), + global_variables: Vec::new(), + cached: CachedExpressions::default(), struct_type_handles: crate::FastHashMap::default(), gl450_ext_inst_id, layouter: Layouter::default(), typifier: Typifier::new(), + temp_chain: Vec::new(), }) } @@ -292,22 +328,6 @@ impl Writer { } } - fn get_global_variable_id( - &mut self, - ir_module: &crate::Module, - handle: Handle, - ) -> Result<(Word, spirv::StorageClass), Error> { - Ok(match self.lookup_global_variable.entry(handle) { - Entry::Occupied(e) => *e.get(), - //Note: this intentionally frees `self` from borrowing - Entry::Vacant(_) => { - let (instruction, id, class) = self.write_global_variable(ir_module, handle)?; - instruction.to_words(&mut self.logical_layout.declarations); - (id, class) - } - }) - } - fn get_pointer_id( &mut self, arena: &Arena, @@ -361,6 +381,7 @@ impl Writer { fn write_function( &mut self, ir_function: &crate::Function, + info: &FunctionInfo, ir_module: &crate::Module, ) -> Result { let mut function = Function::default(); @@ -438,7 +459,42 @@ impl Writer { function_type, )); + let prelude_id = self.generate_id(); + let mut prelude = Block::new(prelude_id); + + // fill up the `GlobalVariable::handle_id` + for gv in self.global_variables.iter_mut() { + gv.handle_id = 0; + } + for (handle, var) in ir_module.global_variables.iter() { + // Handle globals are pre-emitted and should be loaded automatically. + if info[handle].is_empty() || var.class != crate::StorageClass::Handle { + continue; + } + let id = self.generate_id(); + let result_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(var.ty))?; + let gv = &mut self.global_variables[handle.index()]; + prelude + .body + .push(Instruction::load(result_type_id, id, gv.id, None)); + gv.handle_id = id; + } + // fill up the pre-emitted expressions + self.cached.reset(ir_function.expressions.len()); + for (handle, expr) in ir_function.expressions.iter() { + if expr.needs_pre_emit() { + self.cache_expression_value( + ir_module, + ir_function, + handle, + &mut prelude, + &mut function, + )?; + } + } + let main_id = self.generate_id(); + function.consume(prelude, Instruction::branch(main_id)); self.write_block( main_id, &ir_function.body, @@ -464,18 +520,15 @@ impl Writer { info: &FunctionInfo, ir_module: &crate::Module, ) -> Result { - let function_id = self.write_function(&entry_point.function, ir_module)?; + let function_id = self.write_function(&entry_point.function, info, ir_module)?; - let mut interface_ids = vec![]; + let mut interface_ids = Vec::new(); for (handle, var) in ir_module.global_variables.iter() { - let is_io = match var.class { - crate::StorageClass::Input | crate::StorageClass::Output => { - !info[handle].is_empty() - } - _ => false, - }; - if is_io { - let (id, _) = self.get_global_variable_id(ir_module, handle)?; + if info[handle].is_empty() { + continue; + } + if let crate::StorageClass::Input | crate::StorageClass::Output = var.class { + let id = self.global_variables[handle.index()].id; interface_ids.push(id); } } @@ -958,8 +1011,6 @@ impl Writer { } // TODO Initializer is optional and not (yet) included in the IR - - self.lookup_global_variable.insert(handle, (id, class)); Ok((instruction, id, class)) } @@ -1001,14 +1052,11 @@ impl Writer { fn write_texture_coordinates( &mut self, ir_module: &crate::Module, - ir_function: &crate::Function, coordinates: Handle, array_index: Option>, block: &mut Block, - function: &mut Function, ) -> Result { - let coordinate_id = - self.write_expression(ir_module, ir_function, coordinates, block, function)?; + let coordinate_id = self.cached[coordinates]; Ok(if let Some(array_index) = array_index { let coordinate_scalar_type_id = self.get_type_id( @@ -1050,8 +1098,7 @@ impl Writer { let array_index_f32_id = self.generate_id(); constituent_ids[size as usize - 1] = array_index_f32_id; - let array_index_u32_id = - self.write_expression(ir_module, ir_function, array_index, block, function)?; + let array_index_u32_id = self.cached[array_index]; let cast_instruction = Instruction::unary( spirv::Op::ConvertUToF, coordinate_scalar_type_id, @@ -1079,173 +1126,102 @@ impl Writer { }) } - /// Write an expression and return a value ID. - fn write_expression<'a>( - &mut self, - ir_module: &'a crate::Module, - ir_function: &crate::Function, - handle: Handle, - block: &mut Block, - function: &mut Function, - ) -> Result { - let (raw_expression, result_type_id) = - self.write_expression_raw(ir_module, ir_function, handle, block, function)?; - Ok(match raw_expression { - RawExpression::Value(id) => id, - RawExpression::Pointer(id, _) => { - let load_id = self.generate_id(); - block - .body - .push(Instruction::load(result_type_id, load_id, id, None)); - load_id - } - }) - } - - /// Write an expression and return a pointer ID to the result. - fn write_expression_pointer<'a>( - &mut self, - ir_module: &'a crate::Module, - ir_function: &crate::Function, - handle: Handle, - block: &mut Block, - function: &mut Function, - ) -> Result { - let (raw_expression, _) = - self.write_expression_raw(ir_module, ir_function, handle, block, function)?; - Ok(match raw_expression { - RawExpression::Value(_id) => unimplemented!( - "Expression {:?} is not a pointer", - ir_function.expressions[handle] - ), - RawExpression::Pointer(id, class) => (id, class), - }) - } - - /// Write an expression, and the result may be either a pointer, or a value. - fn write_expression_raw<'a>( + /// Cache an expression for a value. + fn cache_expression_value<'a>( &mut self, ir_module: &'a crate::Module, ir_function: &crate::Function, expr_handle: Handle, block: &mut Block, function: &mut Function, - ) -> Result<(RawExpression, ExpressionId), Error> { + ) -> Result<(), Error> { let result_lookup_ty = match self.typifier.get_handle(expr_handle) { Ok(ty_handle) => LookupType::Handle(ty_handle), Err(inner) => LookupType::Local(LocalType::from_inner(inner).unwrap()), }; let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; - let raw_expr = match ir_function.expressions[expr_handle] { + let id = match ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { - let id = self.generate_id(); - let (raw_base_expression, _) = - self.write_expression_raw(ir_module, ir_function, base, block, function)?; - let index_id = - self.write_expression(ir_module, ir_function, index, block, function)?; - let base_inner = self.typifier.get(base, &ir_module.types); - - match raw_base_expression { - RawExpression::Value(base_id) => { - if let crate::TypeInner::Array { .. } = *base_inner { - return Err(Error::FeatureNotImplemented( - "accessing index of a value array", - )); - } - - block.body.push(Instruction::vector_extract_dynamic( - result_type_id, - id, - base_id, - index_id, - )); - - RawExpression::Value(id) + let base_is_var = match ir_function.expressions[base] { + crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => { + true } - RawExpression::Pointer(base_id, class) => { - let pointer_type_id = self.create_pointer_type(result_type_id, class); - - block.body.push(Instruction::access_chain( - pointer_type_id, - id, - base_id, - &[index_id], - )); - - RawExpression::Pointer(id, class) + _ => self.cached.ids[base.index()] == 0, + }; + if base_is_var { + 0 + } else { + let index_id = self.cached[index]; + match *self.typifier.get(base, &ir_module.types) { + crate::TypeInner::Vector { .. } => { + let id = self.generate_id(); + let base_id = self.cached[base]; + block.body.push(Instruction::vector_extract_dynamic( + result_type_id, + id, + base_id, + index_id, + )); + id + } + //TODO: support `crate::TypeInner::Array { .. }` ? + ref other => { + log::error!("Unable to access {:?}", other); + return Err(Error::FeatureNotImplemented("access for type")); + } } } } crate::Expression::AccessIndex { base, index } => { - let id = self.generate_id(); - let (raw_base_expression, _) = - self.write_expression_raw(ir_module, ir_function, base, block, function)?; - - match raw_base_expression { - RawExpression::Value(base_id) => { - block.body.push(Instruction::composite_extract( - result_type_id, - id, - base_id, - &[index], - )); - - RawExpression::Value(id) + let base_is_var = match ir_function.expressions[base] { + crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => { + true } - RawExpression::Pointer(base_id, class) => { - let pointer_type_id = self.create_pointer_type(result_type_id, class); - - let const_ty_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Scalar { - kind: crate::ScalarKind::Sint, - width: 4, - }), - )?; - let const_id = self.create_constant(const_ty_id, &[index]); - - block.body.push(Instruction::access_chain( - pointer_type_id, - id, - base_id, - &[const_id], - )); - - RawExpression::Pointer(id, class) + _ => self.cached.ids[base.index()] == 0, + }; + if base_is_var { + 0 + } else { + match *self.typifier.get(base, &ir_module.types) { + crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } + | crate::TypeInner::Array { .. } + | crate::TypeInner::Struct { .. } => { + let id = self.generate_id(); + let base_id = self.cached[base]; + block.body.push(Instruction::composite_extract( + result_type_id, + id, + base_id, + &[index], + )); + id + } + ref other => { + log::error!("Unable to access index of {:?}", other); + return Err(Error::FeatureNotImplemented("access index for type")); + } } } } - crate::Expression::GlobalVariable(handle) => { - let (id, class) = self.get_global_variable_id(&ir_module, handle)?; - RawExpression::Pointer(id, class) - } - crate::Expression::Constant(handle) => { - let id = self.lookup_constant[&handle]; - RawExpression::Value(id) - } - crate::Expression::Compose { ty, ref components } => { - let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty))?; - + crate::Expression::GlobalVariable(handle) => self.global_variables[handle.index()].id, + crate::Expression::Constant(handle) => self.lookup_constant[&handle], + crate::Expression::Compose { + ty: _, + ref components, + } => { + //TODO: avoid allocation let mut constituent_ids = Vec::with_capacity(components.len()); - for component in components { - let component_id = self.write_expression( - ir_module, - &ir_function, - *component, - block, - function, - )?; + for &component in components { + let component_id = self.cached[component]; constituent_ids.push(component_id); } - - let id = self.write_composite_construct(base_type_id, &constituent_ids, block); - RawExpression::Value(id) + self.write_composite_construct(result_type_id, &constituent_ids, block) } crate::Expression::Unary { op, expr } => { let id = self.generate_id(); - let expr_id = - self.write_expression(ir_module, ir_function, expr, block, function)?; + let expr_id = self.cached[expr]; let expr_ty_inner = self.typifier.get(expr, &ir_module.types); let spirv_op = match op { @@ -1264,14 +1240,12 @@ impl Writer { block .body .push(Instruction::unary(spirv_op, result_type_id, id, expr_id)); - RawExpression::Value(id) + id } crate::Expression::Binary { op, left, right } => { let id = self.generate_id(); - let left_id = - self.write_expression(ir_module, ir_function, left, block, function)?; - let right_id = - self.write_expression(ir_module, ir_function, right, block, function)?; + let left_id = self.cached[left]; + let right_id = self.cached[right]; let left_ty_inner = self.typifier.get(left, &ir_module.types); let right_ty_inner = self.typifier.get(right, &ir_module.types); @@ -1394,7 +1368,7 @@ impl Writer { if preserve_order { left_id } else { right_id }, if preserve_order { right_id } else { left_id }, )); - RawExpression::Value(id) + id } crate::Expression::Math { fun, @@ -1408,19 +1382,14 @@ impl Writer { Custom(Instruction), } - let arg0_id = - self.write_expression(ir_module, ir_function, arg, block, function)?; + let arg0_id = self.cached[arg]; let arg_scalar_kind = self.typifier.get(arg, &ir_module.types).scalar_kind(); let arg1_id = match arg1 { - Some(id) => { - self.write_expression(ir_module, ir_function, id, block, function)? - } + Some(handle) => self.cached[handle], None => 0, }; let arg2_id = match arg2 { - Some(id) => { - self.write_expression(ir_module, ir_function, id, block, function)? - } + Some(handle) => self.cached[handle], None => 0, }; @@ -1536,27 +1505,34 @@ impl Writer { ), MathOp::Custom(inst) => inst, }); - RawExpression::Value(id) + id } - crate::Expression::LocalVariable(variable) => { - let local_var = &function.variables[&variable]; - RawExpression::Pointer(local_var.id, spirv::StorageClass::Function) + crate::Expression::LocalVariable(variable) => function.variables[&variable].id, + crate::Expression::Load { pointer } => { + let (pointer_id, _) = self.write_expression_pointer( + ir_module, + ir_function, + pointer, + block, + function, + )?; + + let id = self.generate_id(); + block + .body + .push(Instruction::load(result_type_id, id, pointer_id, None)); + id } crate::Expression::FunctionArgument(index) => { - let id = function.parameters[index as usize].result_id.unwrap(); - RawExpression::Value(id) - } - crate::Expression::Call(_function) => { - let id = self.lookup_function_call[&expr_handle]; - RawExpression::Value(id) + function.parameters[index as usize].result_id.unwrap() } + crate::Expression::Call(_function) => self.lookup_function_call[&expr_handle], crate::Expression::As { expr, kind, convert, } => { - let expr_id = - self.write_expression(ir_module, ir_function, expr, block, function)?; + let expr_id = self.cached[expr]; let expr_kind = self .typifier .get(expr, &ir_module.types) @@ -1576,8 +1552,7 @@ impl Writer { let id = self.generate_id(); let instruction = Instruction::unary(op, result_type_id, id, expr_id); block.body.push(instruction); - - RawExpression::Value(id) + id } crate::Expression::ImageLoad { image, @@ -1585,16 +1560,9 @@ impl Writer { array_index, index, } => { - let image_id = - self.write_expression(ir_module, ir_function, image, block, function)?; - let coordinate_id = self.write_texture_coordinates( - ir_module, - ir_function, - coordinate, - array_index, - block, - function, - )?; + let image_id = self.get_expression_global(ir_function, image); + let coordinate_id = + self.write_texture_coordinates(ir_module, coordinate, array_index, block)?; let id = self.generate_id(); @@ -1608,21 +1576,20 @@ impl Writer { }; if let Some(index) = index { - let image_ops = match *image_ty { + let index_id = self.cached[index]; + let image_ops = match *self.typifier.get(image, &ir_module.types) { crate::TypeInner::Image { class: crate::ImageClass::Sampled { multi: true, .. }, .. } => spirv::ImageOperands::SAMPLE, _ => spirv::ImageOperands::LOD, }; - let index_id = - self.write_expression(ir_module, ir_function, index, block, function)?; instruction.add_operand(image_ops.bits()); instruction.add_operand(index_id); } block.body.push(instruction); - RawExpression::Value(id) + id } crate::Expression::ImageSample { image, @@ -1635,8 +1602,7 @@ impl Writer { } => { use super::instructions::SampleLod; // image - let image_id = - self.write_expression(ir_module, ir_function, image, block, function)?; + let image_id = self.get_expression_global(ir_function, image); let image_type = self.typifier.get_handle(image).unwrap(); // OpTypeSampledImage @@ -1645,16 +1611,9 @@ impl Writer { LookupType::Local(LocalType::SampledImage { image_type }), )?; - let sampler_id = - self.write_expression(ir_module, ir_function, sampler, block, function)?; - let coordinate_id = self.write_texture_coordinates( - ir_module, - ir_function, - coordinate, - array_index, - block, - function, - )?; + let sampler_id = self.get_expression_global(ir_function, sampler); + let coordinate_id = + self.write_texture_coordinates(ir_module, coordinate, array_index, block)?; let sampled_image_id = self.generate_id(); block.body.push(Instruction::sampled_image( @@ -1665,14 +1624,7 @@ impl Writer { )); let id = self.generate_id(); - let depth_id = match depth_ref { - Some(handle) => { - let expr_id = - self.write_expression(ir_module, ir_function, handle, block, function)?; - Some(expr_id) - } - None => None, - }; + let depth_id = depth_ref.map(|handle| self.cached[handle]); let mut main_instruction = match level { crate::SampleLevel::Zero => { @@ -1715,13 +1667,7 @@ impl Writer { depth_id, ); - let lod_id = self.write_expression( - ir_module, - ir_function, - lod_handle, - block, - function, - )?; + let lod_id = self.cached[lod_handle]; inst.add_operand(spirv::ImageOperands::LOD.bits()); inst.add_operand(lod_id); @@ -1737,13 +1683,7 @@ impl Writer { depth_id, ); - let bias_id = self.write_expression( - ir_module, - ir_function, - bias_handle, - block, - function, - )?; + let bias_id = self.cached[bias_handle]; inst.add_operand(spirv::ImageOperands::BIAS.bits()); inst.add_operand(bias_id); @@ -1759,10 +1699,8 @@ impl Writer { depth_id, ); - let x_id = - self.write_expression(ir_module, ir_function, x, block, function)?; - let y_id = - self.write_expression(ir_module, ir_function, y, block, function)?; + let x_id = self.cached[x]; + let y_id = self.cached[y]; inst.add_operand(spirv::ImageOperands::GRAD.bits()); inst.add_operand(x_id); inst.add_operand(y_id); @@ -1778,7 +1716,7 @@ impl Writer { } block.body.push(main_instruction); - RawExpression::Value(id) + id } crate::Expression::Select { condition, @@ -1786,17 +1724,14 @@ impl Writer { reject, } => { let id = self.generate_id(); - let condition_id = - self.write_expression(ir_module, ir_function, condition, block, function)?; - let accept_id = - self.write_expression(ir_module, ir_function, accept, block, function)?; - let reject_id = - self.write_expression(ir_module, ir_function, reject, block, function)?; + let condition_id = self.cached[condition]; + let accept_id = self.cached[accept]; + let reject_id = self.cached[reject]; let instruction = Instruction::select(result_type_id, id, condition_id, accept_id, reject_id); block.body.push(instruction); - RawExpression::Value(id) + id } ref other => { log::error!("unimplemented {:?}", other); @@ -1804,7 +1739,88 @@ impl Writer { } }; - Ok((raw_expr, result_type_id)) + self.cached[expr_handle] = id; + Ok(()) + } + + /// Write a left-hand-side expression, returning an `id` of the pointer. + fn write_expression_pointer<'a>( + &mut self, + ir_module: &'a crate::Module, + ir_function: &crate::Function, + mut expr_handle: Handle, + block: &mut Block, + function: &mut Function, + ) -> Result<(Word, spirv::StorageClass), Error> { + let result_lookup_ty = match self.typifier.get_handle(expr_handle) { + Ok(ty_handle) => LookupType::Handle(ty_handle), + Err(inner) => LookupType::Local(LocalType::from_inner(inner).unwrap()), + }; + let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; + self.temp_chain.clear(); + let (root_id, class) = loop { + expr_handle = match ir_function.expressions[expr_handle] { + crate::Expression::Access { base, index } => { + let index_id = self.cached[index]; + self.temp_chain.push(index_id); + base + } + crate::Expression::AccessIndex { base, index } => { + let const_ty_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Scalar { + kind: crate::ScalarKind::Sint, + width: 4, + }), + )?; + let const_id = self.create_constant(const_ty_id, &[index]); + self.temp_chain.push(const_id); + base + } + crate::Expression::GlobalVariable(handle) => { + let gv = &self.global_variables[handle.index()]; + break (gv.id, gv.class); + } + crate::Expression::LocalVariable(variable) => { + let local_var = &function.variables[&variable]; + break (local_var.id, spirv::StorageClass::Function); + } + ref other => unimplemented!("Unexpected pointer expression {:?}", other), + } + }; + + let id = if self.temp_chain.is_empty() { + root_id + } else { + self.temp_chain.reverse(); + let id = self.generate_id(); + let pointer_type_id = self.create_pointer_type(result_type_id, class); + block.body.push(Instruction::access_chain( + pointer_type_id, + id, + root_id, + &self.temp_chain, + )); + id + }; + Ok((id, class)) + } + + fn get_expression_global( + &self, + ir_function: &crate::Function, + expr_handle: Handle, + ) -> Word { + match ir_function.expressions[expr_handle] { + crate::Expression::GlobalVariable(handle) => { + let id = self.global_variables[handle.index()].handle_id; + if id == 0 { + unreachable!("Global variable {:?} doesn't have a handle ID", handle); + } + id + } + ref other => unreachable!("Unexpected global expression {:?}", other), + } } #[allow(clippy::too_many_arguments)] @@ -1825,6 +1841,17 @@ impl Writer { unimplemented!("No statements are expected after block termination"); } match *statement { + crate::Statement::Emit(ref range) => { + for handle in range.clone() { + self.cache_expression_value( + ir_module, + ir_function, + handle, + &mut block, + function, + )?; + } + } crate::Statement::Block(ref block_statements) => { let scope_id = self.generate_id(); function.consume(block, Instruction::branch(scope_id)); @@ -1847,13 +1874,7 @@ impl Writer { ref accept, ref reject, } => { - let condition_id = self.write_expression( - ir_module, - ir_function, - condition, - &mut block, - function, - )?; + let condition_id = self.cached[condition]; let merge_id = self.generate_id(); block.body.push(Instruction::selection_merge( @@ -1911,13 +1932,7 @@ impl Writer { ref cases, ref default, } => { - let selector_id = self.write_expression( - ir_module, - ir_function, - selector, - &mut block, - function, - )?; + let selector_id = self.cached[selector]; let merge_id = self.generate_id(); block.body.push(Instruction::selection_merge( @@ -2028,8 +2043,7 @@ impl Writer { Some(Instruction::branch(loop_context.continuing_id.unwrap())); } crate::Statement::Return { value: Some(value) } => { - let id = - self.write_expression(ir_module, ir_function, value, &mut block, function)?; + let id = self.cached[value]; block.termination = Some(Instruction::return_value(id)); } crate::Statement::Return { value: None } => { @@ -2046,8 +2060,7 @@ impl Writer { &mut block, function, )?; - let value_id = - self.write_expression(ir_module, ir_function, value, &mut block, function)?; + let value_id = self.cached[value]; block .body @@ -2059,18 +2072,14 @@ impl Writer { array_index, value, } => { - let image_id = - self.write_expression(ir_module, ir_function, image, &mut block, function)?; + let image_id = self.get_expression_global(ir_function, image); let coordinate_id = self.write_texture_coordinates( ir_module, - ir_function, coordinate, array_index, &mut block, - function, )?; - let value_id = - self.write_expression(ir_module, ir_function, value, &mut block, function)?; + let value_id = self.cached[value]; block .body @@ -2085,19 +2094,14 @@ impl Writer { //TODO: avoid heap allocation let mut argument_ids = vec![]; - for argument in arguments { - let arg_id = self.write_expression( - ir_module, - ir_function, - *argument, - &mut block, - function, - )?; + for &argument in arguments { + let arg_id = self.cached[argument]; argument_ids.push(arg_id); } let type_id = match result { Some(expr) => { + self.cached[expr] = id; self.lookup_function_call.insert(expr, id); let ty_handle = ir_module.functions[local_function].return_type.unwrap(); @@ -2156,14 +2160,23 @@ impl Writer { self.write_constant_type(id, &constant.inner, &ir_module.types)?; } - for (_, var) in ir_module.global_variables.iter() { + self.global_variables.clear(); + for (handle, var) in ir_module.global_variables.iter() { if let crate::TypeInner::Struct { .. } = ir_module.types[var.ty].inner { self.struct_type_handles.insert(var.ty, var.storage_access); } + let (instruction, id, class) = self.write_global_variable(ir_module, handle)?; + instruction.to_words(&mut self.logical_layout.declarations); + self.global_variables.push(GlobalVariable { + id, + handle_id: 0, + class, + }); } for (handle, ir_function) in ir_module.functions.iter() { - let id = self.write_function(ir_function, ir_module)?; + let info = &analysis[handle]; + let id = self.write_function(ir_function, info, ir_module)?; self.lookup_function.insert(handle, id); } diff --git a/src/front/mod.rs b/src/front/mod.rs index 392c54b14..6ae985cd0 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -6,3 +6,29 @@ pub mod glsl; pub mod spv; #[cfg(feature = "wgsl-in")] pub mod wgsl; + +/// Helper class to emit expressions +#[allow(dead_code)] +#[derive(Default)] +struct Emitter { + start_len: Option, +} + +#[allow(dead_code)] +impl Emitter { + fn start(&mut self, arena: &crate::Arena) { + if self.start_len.is_some() { + unreachable!("Emitting has already started!"); + } + self.start_len = Some(arena.len()); + } + #[must_use] + fn finish(&mut self, arena: &crate::Arena) -> Option { + let start_len = self.start_len.take().unwrap(); + if start_len != arena.len() { + Some(crate::Statement::Emit(arena.range_from(start_len))) + } else { + None + } + } +} diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 6a01e7df3..915df2803 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -18,6 +18,18 @@ bitflags::bitflags! { } } +impl Arena { + fn get_global_var( + &self, + handle: Handle, + ) -> Result, Error> { + match self[handle] { + crate::Expression::GlobalVariable(handle) => Ok(handle), + ref other => Err(Error::InvalidGlobalVar(other.clone())), + } + } +} + /// Return the texture coordinates separated from the array layer, /// and/or divided by the projection term. /// @@ -203,7 +215,7 @@ impl> super::Parser { } let image_lexp = self.lookup_expression.lookup(image_id)?; - let image_var_handle = expressions[image_lexp.handle].as_global_var()?; + let image_var_handle = expressions.get_global_var(image_lexp.handle)?; let image_var = &global_arena[image_var_handle]; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; @@ -274,7 +286,7 @@ impl> super::Parser { } let image_lexp = self.lookup_expression.lookup(image_id)?; - let image_var_handle = expressions[image_lexp.handle].as_global_var()?; + let image_var_handle = expressions.get_global_var(image_lexp.handle)?; let image_var = &global_arena[image_var_handle]; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; @@ -354,8 +366,8 @@ impl> super::Parser { let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let image_var_handle = expressions[si_lexp.image].as_global_var()?; - let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?; + let image_var_handle = expressions.get_global_var(si_lexp.image)?; + let sampler_var_handle = expressions.get_global_var(si_lexp.sampler)?; log::debug!( "\t\t\tImage {:?} sampled with {:?}", image_var_handle, @@ -445,8 +457,8 @@ impl> super::Parser { let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let image_var_handle = expressions[si_lexp.image].as_global_var()?; - let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?; + let image_var_handle = expressions.get_global_var(si_lexp.image)?; + let sampler_var_handle = expressions.get_global_var(si_lexp.sampler)?; log::debug!( "\t\t\tImage {:?} sampled with comparison {:?}", image_var_handle, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 2bf98b8b9..64fac1758 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -67,15 +67,6 @@ impl Instruction { } } -impl crate::Expression { - fn as_global_var(&self) -> Result, Error> { - match *self { - crate::Expression::GlobalVariable(handle) => Ok(handle), - _ => Err(Error::InvalidGlobalVar(self.clone())), - } - } -} - impl crate::TypeInner { fn can_comparison_sample(&self) -> bool { match *self { @@ -592,6 +583,8 @@ impl> Parser { ) -> Result { let mut block = Vec::new(); let mut phis = Vec::new(); + let mut emitter = super::Emitter::default(); + emitter.start(expressions); let mut merge = None; let terminator = loop { use spirv::Op; @@ -613,6 +606,8 @@ impl> Parser { } Op::Variable => { inst.expect_at_least(4)?; + block.extend(emitter.finish(expressions)); + let result_type_id = self.next()?; let result_id = self.next()?; let storage = self.next()?; @@ -629,6 +624,7 @@ impl> Parser { } else { None }; + let name = self .future_decor .remove(&result_id) @@ -641,6 +637,7 @@ impl> Parser { ty: self.lookup_type.lookup(result_type_id)?.handle, init, }); + self.lookup_expression.insert( result_id, LookupExpression { @@ -649,9 +646,11 @@ impl> Parser { type_id: result_type_id, }, ); + emitter.start(expressions); } Op::Phi => { inst.expect_at_least(3)?; + block.extend(emitter.finish(expressions)); let result_type_id = self.next()?; let result_id = self.next()?; @@ -680,13 +679,16 @@ impl> Parser { } phis.push(phi); + emitter.start(expressions); } Op::AccessChain => { struct AccessExpression { base_handle: Handle, type_id: spirv::Word, } + inst.expect_at_least(4)?; + let result_type_id = self.next()?; let result_id = self.next()?; let base_id = self.next()?; @@ -774,6 +776,7 @@ impl> Parser { } Op::VectorExtractDynamic => { inst.expect(5)?; + let result_type_id = self.next()?; let id = self.next()?; let composite_id = self.next()?; @@ -822,6 +825,7 @@ impl> Parser { } Op::VectorInsertDynamic => { inst.expect(6)?; + let result_type_id = self.next()?; let id = self.next()?; let composite_id = self.next()?; @@ -871,6 +875,7 @@ impl> Parser { } Op::CompositeExtract => { inst.expect_at_least(4)?; + let result_type_id = self.next()?; let result_id = self.next()?; let base_id = self.next()?; @@ -911,6 +916,7 @@ impl> Parser { } Op::CompositeInsert => { inst.expect_at_least(5)?; + let result_type_id = self.next()?; let id = self.next()?; let object_id = self.next()?; @@ -941,6 +947,7 @@ impl> Parser { } Op::CompositeConstruct => { inst.expect_at_least(3)?; + let result_type_id = self.next()?; let id = self.next()?; let mut components = Vec::with_capacity(inst.wc as usize - 2); @@ -964,6 +971,7 @@ impl> Parser { } Op::Load => { inst.expect_at_least(4)?; + let result_type_id = self.next()?; let result_id = self.next()?; let pointer_id = self.next()?; @@ -971,17 +979,30 @@ impl> Parser { inst.expect(5)?; let _memory_access = self.next()?; } - let base_expr = self.lookup_expression.lookup(pointer_id)?.clone(); + + let base_lexp = self.lookup_expression.lookup(pointer_id)?; + let type_lookup = self.lookup_type.lookup(base_lexp.type_id)?; + let handle = match type_arena[type_lookup.handle].inner { + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { + base_lexp.handle + } + _ => expressions.append(crate::Expression::Load { + pointer: base_lexp.handle, + }), + }; + self.lookup_expression.insert( result_id, LookupExpression { - handle: base_expr.handle, // pass-through pointers + handle, type_id: result_type_id, }, ); } Op::Store => { inst.expect_at_least(3)?; + block.extend(emitter.finish(expressions)); + let pointer_id = self.next()?; let value_id = self.next()?; if inst.wc != 3 { @@ -994,6 +1015,7 @@ impl> Parser { pointer: base_expr.handle, value: value_expr.handle, }); + emitter.start(expressions); } // Arithmetic Instructions +, -, *, /, % Op::SNegate | Op::FNegate => { @@ -1030,6 +1052,7 @@ impl> Parser { } Op::Transpose => { inst.expect(4)?; + let result_type_id = self.next()?; let result_id = self.next()?; let matrix_id = self.next()?; @@ -1050,6 +1073,7 @@ impl> Parser { } Op::Dot => { inst.expect(5)?; + let result_type_id = self.next()?; let result_id = self.next()?; let left_id = self.next()?; @@ -1260,6 +1284,8 @@ impl> Parser { } Op::FunctionCall => { inst.expect_at_least(4)?; + block.extend(emitter.finish(expressions)); + let result_type_id = self.next()?; let result_id = self.next()?; let func_id = self.next()?; @@ -1292,6 +1318,7 @@ impl> Parser { arguments, result, }); + emitter.start(expressions); } Op::ExtInst => { use crate::MathFunction as Mf; @@ -1299,6 +1326,7 @@ impl> Parser { let base_wc = 5; inst.expect_at_least(base_wc)?; + let result_type_id = self.next()?; let result_id = self.next()?; let set_id = self.next()?; @@ -1464,7 +1492,6 @@ impl> Parser { } Op::Switch => { inst.expect_at_least(3)?; - let selector = self.next()?; let default = self.next()?; @@ -1532,6 +1559,7 @@ impl> Parser { } }; + block.extend(emitter.finish(expressions)); Ok(ControlFlowNode { id: block_id, ty: None, @@ -1590,6 +1618,7 @@ impl> Parser { use crate::Statement as S; for statement in statements.iter_mut() { match *statement { + S::Emit(_) => {} S::Block(ref mut block) => { self.patch_function_call_statements(block)?; } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6dcda90bc..d5a3e5f01 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -24,6 +24,7 @@ use codespan_reporting::{ }; use std::{ io::{self, Write}, + iter, num::NonZeroU32, ops::Range, }; @@ -173,7 +174,11 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { } } - fn as_expression<'t>(&'t mut self, block: &'t mut crate::Block) -> ExpressionContext<'a, 't, '_> + fn as_expression<'t>( + &'t mut self, + block: &'t mut crate::Block, + emitter: &'t mut super::Emitter, + ) -> ExpressionContext<'a, 't, '_> where 'temp: 't, { @@ -188,6 +193,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { functions: self.functions, arguments: self.arguments, block, + emitter, } } } @@ -208,6 +214,7 @@ struct ExpressionContext<'input, 'temp, 'out> { arguments: &'out [crate::FunctionArgument], functions: &'out Arena, block: &'temp mut crate::Block, + emitter: &'temp mut super::Emitter, } impl<'a> ExpressionContext<'a, '_, '_> { @@ -223,6 +230,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { functions: self.functions, arguments: self.arguments, block: self.block, + emitter: self.emitter, } } @@ -560,7 +568,7 @@ impl Parser { None }; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -592,7 +600,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let level = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -624,7 +632,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let bias = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -658,7 +666,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let y = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -690,7 +698,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let reference = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?) + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { None }; @@ -787,6 +795,7 @@ impl Parser { let handle = match self.parse_local_function_call(lexer, name, ctx.reborrow())? { Some((function, arguments)) => { + ctx.block.extend(ctx.emitter.finish(ctx.expressions)); let result = Some(ctx.expressions.append(crate::Expression::Call(function))); ctx.block.push(crate::Statement::Call { @@ -794,6 +803,8 @@ impl Parser { arguments, result, }); + // restart the emitter + ctx.emitter.start(ctx.expressions); result } None => None, @@ -805,15 +816,16 @@ impl Parser { Ok(Some(ctx.expressions.append(expr))) } - fn parse_const_expression<'a>( + fn parse_const_expression_impl<'a>( &mut self, + first_token_span: TokenSpan<'a>, lexer: &mut Lexer<'a>, register_name: Option<&'a str>, type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result, Error<'a>> { self.scopes.push(Scope::ConstantExpr); - let inner = match lexer.next() { + let inner = match first_token_span { (Token::Word("true"), _) => crate::ConstantInner::Scalar { width: 1, value: crate::ScalarValue::Bool(true), @@ -848,8 +860,7 @@ impl Parser { if !components.is_empty() { lexer.expect(Token::Separator(','))?; } - let component = - self.parse_const_expression(lexer, None, type_arena, const_arena)?; + let component = self.parse_const_expression(lexer, type_arena, const_arena)?; components.push(component); } crate::ConstantInner::Composite { @@ -878,6 +889,15 @@ impl Parser { Ok(handle) } + fn parse_const_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + type_arena: &mut Arena, + const_arena: &mut Arena, + ) -> Result, Error<'a>> { + self.parse_const_expression_impl(lexer.next(), lexer, None, type_arena, const_arena) + } + fn parse_primary_expression<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -890,36 +910,18 @@ impl Parser { lexer.expect(Token::Paren(')'))?; expr } - (Token::Word("true"), _) => { - let expr = ctx.constants.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(true), - }, - }); - ctx.expressions.append(crate::Expression::Constant(expr)) - } - (Token::Word("false"), _) => { - let expr = ctx.constants.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(false), - }, - }); - ctx.expressions.append(crate::Expression::Constant(expr)) - } - (Token::Number { value, ty, width }, _) => { - let inner = Self::get_constant_inner(value, ty, width)?; - let expr = ctx.constants.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner, - }); - ctx.expressions.append(crate::Expression::Constant(expr)) + token @ (Token::Word("true"), _) + | token @ (Token::Word("false"), _) + | token @ (Token::Number { .. }, _) => { + let const_handle = + self.parse_const_expression_impl(token, lexer, None, ctx.types, ctx.constants)?; + // pause the emitter while generating this expression, since it's pre-emitted + ctx.block.extend(ctx.emitter.finish(ctx.expressions)); + let expr = ctx + .expressions + .append(crate::Expression::Constant(const_handle)); + ctx.emitter.start(ctx.expressions); + expr } (Token::Word(word), _) => { if let Some(&expr) = ctx.lookup_ident.get(word) { @@ -983,13 +985,27 @@ impl Parser { lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, mut handle: Handle, + allow_deref: bool, ) -> Result, Error<'a>> { + let mut needs_deref = match ctx.expressions[handle] { + crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { + allow_deref + } + _ => false, + }; loop { - match lexer.peek().0 { + // insert the E::Load when we reach a value + if needs_deref && ctx.resolve_type(handle)?.scalar_kind().is_some() { + let expression = crate::Expression::Load { pointer: handle }; + handle = ctx.expressions.append(expression); + needs_deref = false; + } + + let expression = match lexer.peek().0 { Token::Separator('.') => { let _ = lexer.next(); let name = lexer.next_ident()?; - let expression = match *ctx.resolve_type(handle)? { + match *ctx.resolve_type(handle)? { crate::TypeInner::Struct { ref members, .. } => { let index = members .iter() @@ -1016,8 +1032,8 @@ impl Parser { } } crate::TypeInner::Matrix { - rows, columns, + rows, width, } => match Composition::make(handle, columns, name, ctx.expressions)? { Composition::Multi(columns, components) => { @@ -1036,21 +1052,29 @@ impl Parser { Composition::Single(expr) => expr, }, _ => return Err(Error::BadAccessor(name)), - }; - handle = ctx.expressions.append(expression); + } } Token::Paren('[') => { let _ = lexer.next(); let index = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(']'))?; - let expr = crate::Expression::Access { + crate::Expression::Access { base: handle, index, - }; - handle = ctx.expressions.append(expr); + } } - _ => return Ok(handle), - } + _ => { + // after we reached for the value, load it + return Ok(if needs_deref { + let expression = crate::Expression::Load { pointer: handle }; + ctx.expressions.append(expression) + } else { + handle + }); + } + }; + + handle = ctx.expressions.append(expression); } } @@ -1092,7 +1116,7 @@ impl Parser { } }; - let post_handle = self.parse_postfix(lexer, ctx, handle)?; + let post_handle = self.parse_postfix(lexer, ctx, handle, true)?; self.scopes.pop(); Ok(post_handle) } @@ -1270,7 +1294,7 @@ impl Parser { let (ty, access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let init = if lexer.skip(Token::Operation('=')) { - let handle = self.parse_const_expression(lexer, None, type_arena, const_arena)?; + let handle = self.parse_const_expression(lexer, type_arena, const_arena)?; Some(handle) } else { None @@ -1475,7 +1499,7 @@ impl Parser { let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let size = if lexer.skip(Token::Separator(',')) { let const_handle = - self.parse_const_expression(lexer, None, type_arena, const_arena)?; + self.parse_const_expression(lexer, type_arena, const_arena)?; crate::ArraySize::Constant(const_handle) } else { crate::ArraySize::Dynamic @@ -1707,12 +1731,13 @@ impl Parser { lexer: &mut Lexer<'a>, ident: &'a str, mut context: ExpressionContext<'a, '_, 'out>, - ) -> Result> { - Ok(match context.lookup_ident.get(ident) { + ) -> Result<(), Error<'a>> { + context.emitter.start(context.expressions); + let stmt = match context.lookup_ident.get(ident) { Some(&expr) => { - let left = self.parse_postfix(lexer, context.reborrow(), expr)?; + let left = self.parse_postfix(lexer, context.reborrow(), expr, false)?; lexer.expect(Token::Operation('='))?; - let value = self.parse_general_expression(lexer, context)?; + let value = self.parse_general_expression(lexer, context.reborrow())?; crate::Statement::Store { pointer: left, value, @@ -1720,7 +1745,7 @@ impl Parser { } None => { let (function, arguments) = self - .parse_local_function_call(lexer, ident, context)? + .parse_local_function_call(lexer, ident, context.reborrow())? .ok_or(Error::UnknownLocalFunction(ident))?; crate::Statement::Call { function, @@ -1728,7 +1753,12 @@ impl Parser { result: None, } } - }) + }; + context + .block + .extend(context.emitter.finish(context.expressions)); + context.block.push(stmt); + Ok(()) } fn parse_statement<'a, 'out>( @@ -1760,13 +1790,17 @@ impl Parser { }; self.scopes.push(Scope::Statement); + let mut emitter = super::Emitter::default(); match word { "const" => { + emitter.start(context.expressions); let (name, _ty, _access) = self.parse_variable_ident_decl(lexer, context.types, context.constants)?; lexer.expect(Token::Operation('='))?; - let expr_id = self.parse_general_expression(lexer, context.as_expression(block))?; + let expr_id = self + .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; lexer.expect(Token::Separator(';'))?; + block.extend(emitter.finish(context.expressions)); context.lookup_ident.insert(name, expr_id); } "var" => { @@ -1780,8 +1814,12 @@ impl Parser { self.parse_variable_ident_decl(lexer, context.types, context.constants)?; let init = if lexer.skip(Token::Operation('=')) { - let value = - self.parse_general_expression(lexer, context.as_expression(block))?; + emitter.start(context.expressions); + let value = self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?; + block.extend(emitter.finish(context.expressions)); match context.expressions[value] { crate::Expression::Constant(handle) if is_uniform_control_flow => { Init::Constant(handle) @@ -1816,7 +1854,13 @@ impl Parser { } "return" => { let value = if lexer.peek().0 != Token::Separator(';') { - Some(self.parse_general_expression(lexer, context.as_expression(block))?) + emitter.start(context.expressions); + let handle = self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?; + block.extend(emitter.finish(context.expressions)); + Some(handle) } else { None }; @@ -1824,20 +1868,27 @@ impl Parser { block.push(crate::Statement::Return { value }); } "if" => { + emitter.start(context.expressions); lexer.expect(Token::Paren('('))?; - let condition = - self.parse_general_expression(lexer, context.as_expression(block))?; + let condition = self + .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; lexer.expect(Token::Paren(')'))?; + block.extend(emitter.finish(context.expressions)); let accept = self.parse_block(lexer, context.reborrow(), false)?; let mut elsif_stack = Vec::new(); while lexer.skip(Token::Word("elseif")) { + let mut sub_emitter = super::Emitter::default(); + sub_emitter.start(context.expressions); lexer.expect(Token::Paren('('))?; - let other_condition = - self.parse_general_expression(lexer, context.as_expression(block))?; + let other_condition = self.parse_general_expression( + lexer, + context.as_expression(block, &mut sub_emitter), + )?; lexer.expect(Token::Paren(')'))?; + let other_emit = sub_emitter.finish(context.expressions); let other_block = self.parse_block(lexer, context.reborrow(), false)?; - elsif_stack.push((other_condition, other_block)); + elsif_stack.push((other_condition, other_emit, other_block)); } let mut reject = if lexer.skip(Token::Word("else")) { self.parse_block(lexer, context.reborrow(), false)? @@ -1846,12 +1897,15 @@ impl Parser { }; // reverse-fold the else-if blocks //Note: we may consider uplifting this to the IR - for (other_cond, other_block) in elsif_stack.drain(..).rev() { - reject = vec![crate::Statement::If { - condition: other_cond, - accept: other_block, - reject, - }]; + for (other_cond, other_emit, other_block) in elsif_stack.drain(..).rev() { + reject = other_emit + .into_iter() + .chain(iter::once(crate::Statement::If { + condition: other_cond, + accept: other_block, + reject, + })) + .collect(); } block.push(crate::Statement::If { @@ -1861,10 +1915,12 @@ impl Parser { }); } "switch" => { + emitter.start(context.expressions); lexer.expect(Token::Paren('('))?; - let selector = - self.parse_general_expression(lexer, context.as_expression(block))?; + let selector = self + .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; lexer.expect(Token::Paren(')'))?; + block.extend(emitter.finish(context.expressions)); lexer.expect(Token::Paren('{'))?; let mut cases = Vec::new(); let mut default = Vec::new(); @@ -1969,70 +2025,71 @@ impl Parser { } }; - let condition = if lexer.skip(Token::Separator(';')) { - None - } else { - let condition = - Some(self.parse_general_expression(lexer, context.as_expression(block))?); - lexer.expect(Token::Separator(';'))?; - condition - }; - - let continuing = if let Token::Word(ident) = lexer.peek().0 { - // manually parse the next statement here instead of calling parse_statement - // because the statement is not terminated with a semicolon - let _ = lexer.next(); - Some(self.parse_statement_restricted( - lexer, - ident, - context.as_expression(block), - )?) - } else { - None - }; - lexer.expect(Token::Paren(')'))?; - lexer.expect(Token::Paren('{'))?; - let mut body = Vec::new(); - if let Some(condition) = condition { + if !lexer.skip(Token::Separator(';')) { + emitter.start(context.expressions); + let condition = self.parse_general_expression( + lexer, + context.as_expression(&mut body, &mut emitter), + )?; + lexer.expect(Token::Separator(';'))?; + body.extend(emitter.finish(context.expressions)); body.push(crate::Statement::If { condition, accept: Vec::new(), - reject: [crate::Statement::Break].to_vec(), + reject: vec![crate::Statement::Break], }); + }; + + let mut continuing = Vec::new(); + if let Token::Word(ident) = lexer.peek().0 { + // manually parse the next statement here instead of calling parse_statement + // because the statement is not terminated with a semicolon + let _ = lexer.next(); + self.parse_statement_restricted( + lexer, + ident, + context.as_expression(&mut continuing, &mut emitter), + )?; } + lexer.expect(Token::Paren(')'))?; + lexer.expect(Token::Paren('{'))?; + while !lexer.skip(Token::Paren('}')) { self.parse_statement(lexer, context.reborrow(), &mut body, false)?; } - block.push(crate::Statement::Loop { - body, - continuing: continuing.into_iter().collect(), - }); + block.push(crate::Statement::Loop { body, continuing }); } "break" => block.push(crate::Statement::Break), "continue" => block.push(crate::Statement::Continue), "discard" => block.push(crate::Statement::Kill), "textureStore" => { + emitter.start(context.expressions); lexer.expect(Token::Paren('('))?; let image_name = lexer.next_ident()?; let image = context.lookup_ident.lookup(image_name)?; lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, context.as_expression(block))?; - let arrayed = match *context.as_expression(block).resolve_type(image)? { + let mut expr_context = context.as_expression(block, &mut emitter); + let arrayed = match *expr_context.resolve_type(image)? { crate::TypeInner::Image { arrayed, .. } => arrayed, _ => return Err(Error::BadTexture(image_name)), }; + let coordinate = self.parse_general_expression(lexer, expr_context)?; let array_index = if arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, context.as_expression(block))?) + Some(self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?) } else { None }; lexer.expect(Token::Separator(','))?; - let value = self.parse_general_expression(lexer, context.as_expression(block))?; + let value = self + .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; lexer.expect(Token::Paren(')'))?; + block.extend(emitter.finish(context.expressions)); block.push(crate::Statement::ImageStore { image, coordinate, @@ -2042,10 +2099,12 @@ impl Parser { } // assignment or a function call ident => { - let stmt = - self.parse_statement_restricted(lexer, ident, context.as_expression(block))?; + self.parse_statement_restricted( + lexer, + ident, + context.as_expression(block, &mut emitter), + )?; lexer.expect(Token::Separator(';'))?; - block.push(stmt); } } self.scopes.pop(); @@ -2291,7 +2350,9 @@ impl Parser { &mut module.constants, )?; lexer.expect(Token::Operation('='))?; - let const_handle = self.parse_const_expression( + let first_token_span = lexer.next(); + let const_handle = self.parse_const_expression_impl( + first_token_span, lexer, Some(name), &mut module.types, diff --git a/src/lib.rs b/src/lib.rs index 98b45c7dc..8af9270f9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,9 +1,25 @@ -//! Universal shader translator. -//! -//! The central structure of the crate is [`Module`]. -//! -//! To improve performance and reduce memory usage, most structures are stored -//! in an [`Arena`], and can be retrieved using the corresponding [`Handle`]. +/*! Universal shader translator. + +The central structure of the crate is [`Module`]. + +To improve performance and reduce memory usage, most structures are stored +in an [`Arena`], and can be retrieved using the corresponding [`Handle`]. + +Functions are described in terms of statement trees. A statement may have +branching control flow, and it may be mutating. Statements refer to expressions. + +Expressions form a DAG, without any side effects. Expressions need to be +emitted in order to take effect. This happens in one of the following ways: + 1. Constants and function arguments are implicitly emitted at function start. + This corresponds to `expression.needs_pre_emit()` condition. + 2. Local and global variables are implicitly emitted. However, in order to use parts + of them in right-hand-side expressions, the `Expression::Load` must be explicitly emitted, + with an exception of `StorageClass::Handle` global variables. + 3. Result of `Statement::Call` is automatically emitted. + 4. `Statement::Emit` range is explicitly emitted. + +!*/ + #![warn( trivial_casts, trivial_numeric_casts, @@ -24,7 +40,7 @@ pub mod back; pub mod front; pub mod proc; -pub use crate::arena::{Arena, Handle}; +pub use crate::arena::{Arena, Handle, Range}; use std::{ collections::{HashMap, HashSet}, @@ -752,6 +768,8 @@ pub struct SwitchCase { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Statement { + /// Emit a range of expressions, visible to all statements that follow in this block. + Emit(Range), /// A block containing more statements, to be executed sequentially. Block(Block), /// Conditionally executes one of two blocks, based on the value of the condition. diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index d5fddff64..296a3c4c7 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -372,7 +372,7 @@ impl FunctionInfo { let mut block_flags = ControlFlags::empty(); for statement in statements { let flags = match *statement { - S::Break | S::Continue => ControlFlags::empty(), + S::Emit(_) | S::Break | S::Continue => ControlFlags::empty(), S::Kill => ControlFlags::MAY_EXIT, S::Block(ref b) => self.process_block(b, other_functions, is_uniform)?, S::If { diff --git a/src/proc/interface.rs b/src/proc/interface.rs index f05bebadf..2d11f29ef 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -146,7 +146,10 @@ impl<'a, T: Visitor> Interface<'a, T> { for statement in block { use crate::Statement as S; match *statement { - S::Break | S::Continue | S::Kill => (), + //TODO: we could make `traverse_expr` to work on the emitted expressions + // instead of recursive descend. + // Or we can just remove the whole `Interface` entirely. + S::Emit(_) | S::Break | S::Continue | S::Kill => (), S::Block(ref b) => { self.traverse(b); } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index a8b40c13f..4b8e46817 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -138,3 +138,16 @@ impl super::MathFunction { } } } + +impl crate::Expression { + /// Returns true if the expression is considered emitted at the start of a function. + pub fn needs_pre_emit(&self) -> bool { + match *self { + Self::Constant(_) + | Self::FunctionArgument(_) + | Self::GlobalVariable(_) + | Self::LocalVariable(_) => true, + _ => false, + } + } +} diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index af5eaf54d..96822e579 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -5,11 +5,12 @@ /// to the end, because it may be either redundant or invalid, /// e.g. when the user already has returns in if/else branches. pub fn ensure_block_returns(block: &mut crate::Block) { + use crate::Statement as S; match block.last_mut() { - Some(&mut crate::Statement::Block(ref mut b)) => { + Some(&mut S::Block(ref mut b)) => { ensure_block_returns(b); } - Some(&mut crate::Statement::If { + Some(&mut S::If { condition: _, ref mut accept, ref mut reject, @@ -17,7 +18,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) { ensure_block_returns(accept); ensure_block_returns(reject); } - Some(&mut crate::Statement::Switch { + Some(&mut S::Switch { selector: _, ref mut cases, ref mut default, @@ -29,14 +30,15 @@ pub fn ensure_block_returns(block: &mut crate::Block) { } ensure_block_returns(default); } - Some(&mut crate::Statement::Break) - | Some(&mut crate::Statement::Continue) - | Some(&mut crate::Statement::Return { .. }) - | Some(&mut crate::Statement::Kill) => (), - Some(&mut crate::Statement::Loop { .. }) - | Some(&mut crate::Statement::Store { .. }) - | Some(&mut crate::Statement::ImageStore { .. }) - | Some(&mut crate::Statement::Call { .. }) - | None => block.push(crate::Statement::Return { value: None }), + Some(&mut S::Emit(_)) + | Some(&mut S::Break) + | Some(&mut S::Continue) + | Some(&mut S::Return { .. }) + | Some(&mut S::Kill) => (), + Some(&mut S::Loop { .. }) + | Some(&mut S::Store { .. }) + | Some(&mut S::ImageStore { .. }) + | Some(&mut S::Call { .. }) + | None => block.push(S::Return { value: None }), } } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 7be74b923..d9a05b97c 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -96,6 +96,18 @@ impl Typifier { } } + pub fn try_get<'a>( + &'a self, + expr_handle: Handle, + types: &'a Arena, + ) -> Option<&'a crate::TypeInner> { + let resolution = self.resolutions.get(expr_handle.index())?; + Some(match *resolution { + Resolution::Handle(ty_handle) => &types[ty_handle].inner, + Resolution::Value(ref inner) => inner, + }) + } + pub fn get_handle( &self, expr_handle: Handle, @@ -106,6 +118,7 @@ impl Typifier { } } + //TODO: resolve `*Variable` and `Access*` expressions to `Pointer` type. fn resolve_impl( &self, expr: &crate::Expression, @@ -189,7 +202,8 @@ impl Typifier { } crate::Expression::GlobalVariable(h) => Resolution::Handle(ctx.global_vars[h].ty), crate::Expression::LocalVariable(h) => Resolution::Handle(ctx.local_vars[h].ty), - crate::Expression::Load { .. } => unimplemented!(), + // we treat Load as a transparent operation for the type system + crate::Expression::Load { pointer } => self.resolutions[pointer.index()].clone(), crate::Expression::ImageSample { image, .. } | crate::Expression::ImageLoad { image, .. } => match *self.get(image, types) { crate::TypeInner::Image { class, .. } => Resolution::Value(match class { diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 8643e6036..4f9f6317d 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -74,6 +74,8 @@ pub struct Validator { location_out_mask: BitSet, bind_group_masks: Vec, select_cases: FastHashSet, + valid_expression_list: Vec>, + valid_expression_set: BitSet, } #[derive(Clone, Debug, Error)] @@ -134,10 +136,28 @@ pub enum LocalVariableError { InitializerType, } +#[derive(Clone, Debug, Error)] +pub enum ExpressionError { + #[error("Is invalid")] + Invalid, + #[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")] + NotInScope, +} + #[derive(Clone, Debug, Error)] pub enum CallError { #[error("Bad function")] Function, + #[error("Argument {index} expression is invalid")] + Argument { + index: usize, + #[source] + error: ExpressionError, + }, + #[error("Result expression {0:?} has already been introduced earlier")] + ResultAlreadyInScope(Handle), + #[error("Result value is invalid")] + ResultValue(#[source] ExpressionError), #[error("Requires {required} arguments, but {seen} are provided")] ArgumentCount { required: usize, seen: usize }, #[error("Argument {index} value {seen_expression:?} doesn't match the type {required:?}")] @@ -146,8 +166,8 @@ pub enum CallError { required: Handle, seen_expression: Handle, }, - #[error("Return value {seen_expression:?} does not match the type {required:?}")] - ReturnType { + #[error("Result value {seen_expression:?} does not match the type {required:?}")] + ResultType { required: Option>, seen_expression: Option>, }, @@ -157,6 +177,14 @@ pub enum CallError { pub enum FunctionError { #[error(transparent)] Resolve(#[from] TypifyError), + #[error("Expression {handle:?} is invalid")] + Expression { + handle: Handle, + #[source] + error: ExpressionError, + }, + #[error("Expression {0:?} can't be introduced - it's already in scope")] + ExpressionAlreadyInScope(Handle), #[error("Local variable {handle:?} '{name}' is invalid")] LocalVariable { handle: Handle, @@ -180,10 +208,12 @@ pub enum FunctionError { InvalidSwitchType(Handle), #[error("Multiple `switch` cases for {0} are present")] ConflictingSwitchCase(i32), + #[error("The pointer {0:?} doesn't relate to a valid destination for a store")] + InvalidStorePointer(Handle), #[error("The value {0:?} can not be stored")] InvalidStoreValue(Handle), #[error("Store of {value:?} into {pointer:?} doesn't have matching types")] - InvalidStore { + InvalidStoreTypes { pointer: Handle, value: Handle, }, @@ -418,6 +448,8 @@ impl Validator { location_out_mask: BitSet::new(), bind_group_masks: Vec::new(), select_cases: FastHashSet::default(), + valid_expression_list: Vec::new(), + valid_expression_set: BitSet::new(), } } @@ -679,7 +711,7 @@ impl Validator { } fn validate_call( - &self, + &mut self, function: Handle, arguments: &[Handle], result: Option>, @@ -696,7 +728,9 @@ impl Validator { }); } for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { - let ty = self.typifier.get(expr, context.types); + let ty = self + .resolve_type_impl(expr, context.types) + .map_err(|error| CallError::Argument { index, error })?; if ty != &context.types[arg.ty].inner { return Err(CallError::ArgumentType { index, @@ -705,7 +739,19 @@ impl Validator { }); } } - let result_ty = result.map(|expr| self.typifier.get(expr, context.types)); + + if let Some(expr) = result { + if self.valid_expression_set.insert(expr.index()) { + self.valid_expression_list.push(expr); + } else { + return Err(CallError::ResultAlreadyInScope(expr)); + } + } + + let result_ty = result + .map(|expr| self.resolve_type_impl(expr, context.types)) + .transpose() + .map_err(CallError::ResultValue)?; let expected_ty = fun.return_type.map(|ty| &context.types[ty].inner); if result_ty != expected_ty { log::error!( @@ -713,7 +759,7 @@ impl Validator { result_ty, expected_ty ); - return Err(CallError::ReturnType { + return Err(CallError::ResultType { required: fun.return_type, seen_expression: result, }); @@ -721,26 +767,56 @@ impl Validator { Ok(()) } - fn validate_block( + fn resolve_type_impl<'a>( + &'a self, + handle: Handle, + types: &'a Arena, + ) -> Result<&'a crate::TypeInner, ExpressionError> { + if !self.valid_expression_set.contains(handle.index()) { + return Err(ExpressionError::NotInScope); + } + self.typifier + .try_get(handle, types) + .ok_or(ExpressionError::Invalid) + } + + fn resolve_type<'a>( + &'a self, + handle: Handle, + types: &'a Arena, + ) -> Result<&'a crate::TypeInner, FunctionError> { + self.resolve_type_impl(handle, types) + .map_err(|error| FunctionError::Expression { handle, error }) + } + + fn validate_block_impl( &mut self, statements: &[crate::Statement], context: &BlockContext, ) -> Result<(), FunctionError> { use crate::{Statement as S, TypeInner as Ti}; - //TODO: handle the cases of totally invalid expression handles let mut finished = false; for statement in statements { if finished { return Err(FunctionError::InstructionsAfterReturn); } match *statement { + S::Emit(ref range) => { + for handle in range.clone() { + if self.valid_expression_set.insert(handle.index()) { + self.valid_expression_list.push(handle); + } else { + return Err(FunctionError::ExpressionAlreadyInScope(handle)); + } + } + } S::Block(ref block) => self.validate_block(block, context)?, S::If { condition, ref accept, ref reject, } => { - match *self.typifier.get(condition, context.types) { + match *self.resolve_type(condition, context.types)? { Ti::Scalar { kind: crate::ScalarKind::Bool, width: _, @@ -755,7 +831,7 @@ impl Validator { ref cases, ref default, } => { - match *self.typifier.get(selector, context.types) { + match *self.resolve_type(selector, context.types)? { Ti::Scalar { kind: crate::ScalarKind::Sint, width: _, @@ -777,11 +853,17 @@ impl Validator { ref body, ref continuing, } => { - self.validate_block( + // special handling for block scoping is needed here, + // because the continuing{} block inherits the scope + let base_expression_count = self.valid_expression_list.len(); + self.validate_block_impl( body, &context.with_flags(BlockFlags::CAN_JUMP | BlockFlags::IN_LOOP), )?; - self.validate_block(continuing, &context.with_flags(BlockFlags::empty()))?; + self.validate_block_impl(continuing, &context.with_flags(BlockFlags::empty()))?; + for handle in self.valid_expression_list.drain(base_expression_count..) { + self.valid_expression_set.remove(handle.index()); + } } S::Break | S::Continue => { if !context.flags.contains(BlockFlags::IN_LOOP) { @@ -793,7 +875,9 @@ impl Validator { if !context.flags.contains(BlockFlags::CAN_JUMP) { return Err(FunctionError::InvalidReturnSpot); } - let value_ty = value.map(|expr| self.typifier.get(expr, context.types)); + let value_ty = value + .map(|expr| self.resolve_type(expr, context.types)) + .transpose()?; let expected_ty = context.return_type.map(|ty| &context.types[ty].inner); if value_ty != expected_ty { log::error!( @@ -809,17 +893,33 @@ impl Validator { finished = true; } S::Store { pointer, value } => { - let value_ty = self.typifier.get(value, context.types); + let mut current = pointer; + loop { + self.typifier.try_get(current, context.types).ok_or( + FunctionError::Expression { + handle: current, + error: ExpressionError::Invalid, + }, + )?; + match context.expressions[current] { + crate::Expression::Access { base, .. } + | crate::Expression::AccessIndex { base, .. } => current = base, + crate::Expression::LocalVariable(_) + | crate::Expression::GlobalVariable(_) => break, + _ => return Err(FunctionError::InvalidStorePointer(current)), + } + } + + let value_ty = self.resolve_type(value, context.types)?; match *value_ty { Ti::Image { .. } | Ti::Sampler { .. } => { return Err(FunctionError::InvalidStoreValue(value)); } _ => {} } - if self.typifier.get(pointer, context.types) != value_ty { - return Err(FunctionError::InvalidStore { pointer, value }); + if self.typifier.try_get(pointer, context.types) != Some(value_ty) { + return Err(FunctionError::InvalidStoreTypes { pointer, value }); } - //TODO: validate that the `pointer` reaches a variable through a sequence of accessors } S::ImageStore { image, @@ -862,6 +962,19 @@ impl Validator { Ok(()) } + fn validate_block( + &mut self, + statements: &[crate::Statement], + context: &BlockContext, + ) -> Result<(), FunctionError> { + let base_expression_count = self.valid_expression_list.len(); + self.validate_block_impl(statements, context)?; + for handle in self.valid_expression_list.drain(base_expression_count..) { + self.valid_expression_set.remove(handle.index()); + } + Ok(()) + } + fn validate_function( &mut self, fun: &crate::Function, @@ -896,6 +1009,13 @@ impl Validator { } } + self.valid_expression_set.clear(); + for (handle, expr) in fun.expressions.iter() { + if expr.needs_pre_emit() { + self.valid_expression_set.insert(handle.index()); + } + } + self.validate_block( &fun.body, &BlockContext { diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index 0736aad44..f1d9a2824 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -5,64 +5,64 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 286 +; Bound: 233 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %29 "main" %36 -OpExecutionMode %29 LocalSize 64 1 1 +OpEntryPoint GLCompute %41 "main" %25 +OpExecutionMode %41 LocalSize 64 1 1 OpSource GLSL 450 OpName %3 "NUM_PARTICLES" -OpName %15 "vPos" -OpName %18 "vVel" -OpName %19 "cMass" -OpName %20 "cVel" -OpName %21 "colVel" -OpName %22 "cMassCount" -OpName %24 "cVelCount" -OpName %25 "pos" -OpName %26 "vel" -OpName %27 "i" -OpName %29 "main" -OpName %36 "gl_GlobalInvocationID" -OpName %44 "Particle" -OpMemberName %44 0 "pos" -OpMemberName %44 1 "vel" -OpName %48 "Particles" -OpMemberName %48 0 "particles" -OpName %49 "particlesSrc" -OpName %118 "SimParams" -OpMemberName %118 0 "deltaT" -OpMemberName %118 1 "rule1Distance" -OpMemberName %118 2 "rule2Distance" -OpMemberName %118 3 "rule3Distance" -OpMemberName %118 4 "rule1Scale" -OpMemberName %118 5 "rule2Scale" -OpMemberName %118 6 "rule3Scale" -OpName %119 "params" -OpName %262 "particlesDst" -OpName %29 "main" -OpDecorate %36 BuiltIn GlobalInvocationId -OpMemberDecorate %44 0 Offset 0 -OpMemberDecorate %44 1 Offset 8 -OpDecorate %46 ArrayStride 16 -OpDecorate %48 BufferBlock -OpMemberDecorate %48 0 Offset 0 -OpDecorate %49 NonWritable -OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 1 -OpDecorate %118 Block -OpMemberDecorate %118 0 Offset 0 -OpMemberDecorate %118 1 Offset 4 -OpMemberDecorate %118 2 Offset 8 -OpMemberDecorate %118 3 Offset 12 -OpMemberDecorate %118 4 Offset 16 -OpMemberDecorate %118 5 Offset 20 -OpMemberDecorate %118 6 Offset 24 -OpDecorate %119 DescriptorSet 0 -OpDecorate %119 Binding 0 -OpDecorate %262 DescriptorSet 0 -OpDecorate %262 Binding 2 +OpName %16 "SimParams" +OpMemberName %16 0 "deltaT" +OpMemberName %16 1 "rule1Distance" +OpMemberName %16 2 "rule2Distance" +OpMemberName %16 3 "rule3Distance" +OpMemberName %16 4 "rule1Scale" +OpMemberName %16 5 "rule2Scale" +OpMemberName %16 6 "rule3Scale" +OpName %15 "params" +OpName %19 "Particles" +OpMemberName %19 0 "particles" +OpName %21 "Particle" +OpMemberName %21 0 "pos" +OpMemberName %21 1 "vel" +OpName %18 "particlesSrc" +OpName %24 "particlesDst" +OpName %25 "gl_GlobalInvocationID" +OpName %28 "vPos" +OpName %30 "vVel" +OpName %31 "cMass" +OpName %32 "cVel" +OpName %33 "colVel" +OpName %34 "cMassCount" +OpName %36 "cVelCount" +OpName %37 "pos" +OpName %38 "vel" +OpName %39 "i" +OpName %41 "main" +OpName %41 "main" +OpDecorate %16 Block +OpMemberDecorate %16 0 Offset 0 +OpMemberDecorate %16 1 Offset 4 +OpMemberDecorate %16 2 Offset 8 +OpMemberDecorate %16 3 Offset 12 +OpMemberDecorate %16 4 Offset 16 +OpMemberDecorate %16 5 Offset 20 +OpMemberDecorate %16 6 Offset 24 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 0 +OpDecorate %19 BufferBlock +OpMemberDecorate %19 0 Offset 0 +OpDecorate %20 ArrayStride 16 +OpMemberDecorate %21 0 Offset 0 +OpMemberDecorate %21 1 Offset 8 +OpDecorate %18 NonWritable +OpDecorate %18 DescriptorSet 0 +OpDecorate %18 Binding 1 +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 2 +OpDecorate %25 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1500 @@ -76,341 +76,289 @@ OpDecorate %262 Binding 2 %12 = OpConstant %6 1.0 %13 = OpConstant %6 0.1 %14 = OpConstant %6 -1.0 -%16 = OpTypeVector %6 2 -%17 = OpTypePointer Function %16 -%23 = OpTypePointer Function %4 -%28 = OpTypePointer Function %9 -%30 = OpTypeFunction %2 -%32 = OpTypeBool -%35 = OpTypeVector %9 3 -%37 = OpTypePointer Input %35 -%36 = OpVariable %37 Input -%38 = OpTypePointer Input %9 -%39 = OpConstant %4 0 -%44 = OpTypeStruct %16 %16 -%46 = OpTypeRuntimeArray %44 -%48 = OpTypeStruct %46 -%50 = OpTypePointer Uniform %48 -%49 = OpVariable %50 Uniform -%51 = OpTypePointer Uniform %46 +%16 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 +%17 = OpTypePointer Uniform %16 +%15 = OpVariable %17 Uniform +%22 = OpTypeVector %6 2 +%21 = OpTypeStruct %22 %22 +%20 = OpTypeRuntimeArray %21 +%19 = OpTypeStruct %20 +%23 = OpTypePointer Uniform %19 +%18 = OpVariable %23 Uniform +%24 = OpVariable %23 Uniform +%26 = OpTypeVector %9 3 +%27 = OpTypePointer Input %26 +%25 = OpVariable %27 Input +%29 = OpTypePointer Function %22 +%35 = OpTypePointer Function %4 +%40 = OpTypePointer Function %9 +%42 = OpTypeFunction %2 +%47 = OpTypeBool +%51 = OpConstant %4 0 %52 = OpConstant %4 0 -%54 = OpTypePointer Input %9 -%55 = OpConstant %4 0 -%57 = OpTypePointer Uniform %44 -%58 = OpTypePointer Uniform %16 -%59 = OpConstant %4 0 -%64 = OpTypePointer Uniform %46 -%65 = OpConstant %4 0 -%67 = OpTypePointer Input %9 -%68 = OpConstant %4 0 -%70 = OpTypePointer Uniform %44 -%71 = OpTypePointer Uniform %16 -%72 = OpConstant %4 1 -%88 = OpTypePointer Input %9 -%89 = OpConstant %4 0 -%96 = OpTypePointer Uniform %46 -%97 = OpConstant %4 0 -%99 = OpTypePointer Uniform %44 -%100 = OpTypePointer Uniform %16 -%101 = OpConstant %4 0 -%106 = OpTypePointer Uniform %46 -%107 = OpConstant %4 0 -%109 = OpTypePointer Uniform %44 -%110 = OpTypePointer Uniform %16 -%111 = OpConstant %4 1 -%118 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 -%120 = OpTypePointer Uniform %118 -%119 = OpVariable %120 Uniform -%121 = OpTypePointer Uniform %6 -%122 = OpConstant %4 1 -%136 = OpTypePointer Uniform %6 -%137 = OpConstant %4 2 -%151 = OpTypePointer Uniform %6 -%152 = OpConstant %4 3 -%190 = OpTypePointer Uniform %6 -%191 = OpConstant %4 4 -%196 = OpTypePointer Uniform %6 -%197 = OpConstant %4 5 -%202 = OpTypePointer Uniform %6 -%203 = OpConstant %4 6 -%216 = OpTypePointer Uniform %6 -%217 = OpConstant %4 0 -%221 = OpTypePointer Function %6 -%222 = OpConstant %4 0 -%227 = OpTypePointer Function %6 -%228 = OpConstant %4 0 -%231 = OpTypePointer Function %6 -%232 = OpConstant %4 0 -%237 = OpTypePointer Function %6 -%238 = OpConstant %4 0 -%241 = OpTypePointer Function %6 -%242 = OpConstant %4 1 -%247 = OpTypePointer Function %6 -%248 = OpConstant %4 1 -%251 = OpTypePointer Function %6 -%252 = OpConstant %4 1 -%257 = OpTypePointer Function %6 -%258 = OpConstant %4 1 -%262 = OpVariable %50 Uniform -%263 = OpTypePointer Uniform %46 -%264 = OpConstant %4 0 -%266 = OpTypePointer Input %9 -%267 = OpConstant %4 0 -%269 = OpTypePointer Uniform %44 -%270 = OpTypePointer Uniform %16 -%271 = OpConstant %4 0 -%276 = OpTypePointer Uniform %46 -%277 = OpConstant %4 0 -%279 = OpTypePointer Input %9 -%280 = OpConstant %4 0 -%282 = OpTypePointer Uniform %44 -%283 = OpTypePointer Uniform %16 -%284 = OpConstant %4 1 -%29 = OpFunction %2 None %30 -%31 = OpLabel -%27 = OpVariable %28 Function %8 -%24 = OpVariable %23 Function %7 -%20 = OpVariable %17 Function -%15 = OpVariable %17 Function -%25 = OpVariable %17 Function -%21 = OpVariable %17 Function -%18 = OpVariable %17 Function -%26 = OpVariable %17 Function -%22 = OpVariable %23 Function %7 -%19 = OpVariable %17 Function -%34 = OpAccessChain %38 %36 %39 -%40 = OpLoad %9 %34 -%33 = OpUGreaterThanEqual %32 %40 %3 -OpSelectionMerge %41 None -OpBranchConditional %33 %42 %41 -%42 = OpLabel +%54 = OpTypePointer Uniform %22 +%56 = OpConstant %4 1 +%57 = OpConstant %4 0 +%59 = OpTypePointer Uniform %22 +%77 = OpConstant %4 0 +%78 = OpConstant %4 0 +%80 = OpTypePointer Uniform %22 +%83 = OpConstant %4 1 +%84 = OpConstant %4 0 +%86 = OpTypePointer Uniform %22 +%91 = OpConstant %4 1 +%93 = OpTypePointer Uniform %6 +%106 = OpConstant %4 2 +%108 = OpTypePointer Uniform %6 +%121 = OpConstant %4 3 +%123 = OpTypePointer Uniform %6 +%157 = OpConstant %4 4 +%159 = OpTypePointer Uniform %6 +%164 = OpConstant %4 5 +%166 = OpTypePointer Uniform %6 +%171 = OpConstant %4 6 +%173 = OpTypePointer Uniform %6 +%185 = OpConstant %4 0 +%187 = OpTypePointer Uniform %6 +%196 = OpConstant %4 0 +%198 = OpTypePointer Function %6 +%204 = OpConstant %4 0 +%206 = OpTypePointer Function %6 +%212 = OpConstant %4 1 +%214 = OpTypePointer Function %6 +%220 = OpConstant %4 1 +%222 = OpTypePointer Function %6 +%224 = OpConstant %4 0 +%225 = OpConstant %4 0 +%227 = OpTypePointer Uniform %22 +%229 = OpConstant %4 1 +%230 = OpConstant %4 0 +%232 = OpTypePointer Uniform %22 +%41 = OpFunction %2 None %42 +%43 = OpLabel +%39 = OpVariable %40 Function %8 +%36 = OpVariable %35 Function %7 +%32 = OpVariable %29 Function +%28 = OpVariable %29 Function +%37 = OpVariable %29 Function +%33 = OpVariable %29 Function +%30 = OpVariable %29 Function +%38 = OpVariable %29 Function +%34 = OpVariable %35 Function %7 +%31 = OpVariable %29 Function +OpBranch %44 +%44 = OpLabel +%45 = OpLoad %26 %25 +%46 = OpCompositeExtract %9 %45 0 +%48 = OpUGreaterThanEqual %47 %46 %3 +OpSelectionMerge %49 None +OpBranchConditional %48 %50 %49 +%50 = OpLabel OpReturn -%41 = OpLabel -%47 = OpAccessChain %51 %49 %52 -%53 = OpAccessChain %54 %36 %55 -%56 = OpLoad %9 %53 -%45 = OpAccessChain %57 %47 %56 -%43 = OpAccessChain %58 %45 %59 -%60 = OpLoad %16 %43 -OpStore %15 %60 -%63 = OpAccessChain %64 %49 %65 -%66 = OpAccessChain %67 %36 %68 -%69 = OpLoad %9 %66 -%62 = OpAccessChain %70 %63 %69 -%61 = OpAccessChain %71 %62 %72 -%73 = OpLoad %16 %61 -OpStore %18 %73 -%74 = OpCompositeConstruct %16 %5 %5 -OpStore %19 %74 -%75 = OpCompositeConstruct %16 %5 %5 -OpStore %20 %75 -%76 = OpCompositeConstruct %16 %5 %5 -OpStore %21 %76 -OpBranch %77 -%77 = OpLabel -OpLoopMerge %78 %80 None -OpBranch %79 -%79 = OpLabel -%82 = OpLoad %9 %27 -%81 = OpUGreaterThanEqual %32 %82 %3 -OpSelectionMerge %83 None -OpBranchConditional %81 %84 %83 -%84 = OpLabel -OpBranch %78 -%83 = OpLabel -%86 = OpLoad %9 %27 -%87 = OpAccessChain %88 %36 %89 -%90 = OpLoad %9 %87 -%85 = OpIEqual %32 %86 %90 -OpSelectionMerge %91 None -OpBranchConditional %85 %92 %91 -%92 = OpLabel -OpBranch %80 -%91 = OpLabel -%95 = OpAccessChain %96 %49 %97 -%98 = OpLoad %9 %27 -%94 = OpAccessChain %99 %95 %98 -%93 = OpAccessChain %100 %94 %101 -%102 = OpLoad %16 %93 -OpStore %25 %102 -%105 = OpAccessChain %106 %49 %107 -%108 = OpLoad %9 %27 -%104 = OpAccessChain %109 %105 %108 -%103 = OpAccessChain %110 %104 %111 -%112 = OpLoad %16 %103 -OpStore %26 %112 -%114 = OpLoad %16 %25 -%115 = OpLoad %16 %15 -%116 = OpExtInst %6 %1 Distance %114 %115 -%117 = OpAccessChain %121 %119 %122 -%123 = OpLoad %6 %117 -%113 = OpFOrdLessThan %32 %116 %123 -OpSelectionMerge %124 None -OpBranchConditional %113 %125 %124 -%125 = OpLabel -%127 = OpLoad %16 %19 -%128 = OpLoad %16 %25 -%126 = OpFAdd %16 %127 %128 -OpStore %19 %126 -%130 = OpLoad %4 %22 -%129 = OpIAdd %4 %130 %10 -OpStore %22 %129 -OpBranch %124 -%124 = OpLabel -%132 = OpLoad %16 %25 -%133 = OpLoad %16 %15 -%134 = OpExtInst %6 %1 Distance %132 %133 -%135 = OpAccessChain %136 %119 %137 -%138 = OpLoad %6 %135 -%131 = OpFOrdLessThan %32 %134 %138 -OpSelectionMerge %139 None -OpBranchConditional %131 %140 %139 -%140 = OpLabel -%142 = OpLoad %16 %21 -%144 = OpLoad %16 %25 -%145 = OpLoad %16 %15 -%143 = OpFSub %16 %144 %145 -%141 = OpFSub %16 %142 %143 -OpStore %21 %141 -OpBranch %139 -%139 = OpLabel -%147 = OpLoad %16 %25 -%148 = OpLoad %16 %15 -%149 = OpExtInst %6 %1 Distance %147 %148 -%150 = OpAccessChain %151 %119 %152 -%153 = OpLoad %6 %150 -%146 = OpFOrdLessThan %32 %149 %153 -OpSelectionMerge %154 None -OpBranchConditional %146 %155 %154 -%155 = OpLabel -%157 = OpLoad %16 %20 -%158 = OpLoad %16 %26 -%156 = OpFAdd %16 %157 %158 -OpStore %20 %156 -%160 = OpLoad %4 %24 -%159 = OpIAdd %4 %160 %10 -OpStore %24 %159 -OpBranch %154 -%154 = OpLabel -OpBranch %80 -%80 = OpLabel -%162 = OpLoad %9 %27 -%161 = OpIAdd %9 %162 %11 -OpStore %27 %161 -OpBranch %77 -%78 = OpLabel -%164 = OpLoad %4 %22 -%163 = OpSGreaterThan %32 %164 %7 -OpSelectionMerge %165 None -OpBranchConditional %163 %166 %165 -%166 = OpLabel -%169 = OpLoad %16 %19 -%171 = OpLoad %4 %22 -%172 = OpConvertSToF %6 %171 -%170 = OpFDiv %6 %12 %172 -%168 = OpVectorTimesScalar %16 %169 %170 -%173 = OpLoad %16 %15 -%167 = OpFSub %16 %168 %173 -OpStore %19 %167 -OpBranch %165 -%165 = OpLabel -%175 = OpLoad %4 %24 -%174 = OpSGreaterThan %32 %175 %7 -OpSelectionMerge %176 None -OpBranchConditional %174 %177 %176 -%177 = OpLabel -%179 = OpLoad %16 %20 -%181 = OpLoad %4 %24 -%182 = OpConvertSToF %6 %181 -%180 = OpFDiv %6 %12 %182 -%178 = OpVectorTimesScalar %16 %179 %180 -OpStore %20 %178 -OpBranch %176 -%176 = OpLabel -%186 = OpLoad %16 %18 -%188 = OpLoad %16 %19 -%189 = OpAccessChain %190 %119 %191 -%192 = OpLoad %6 %189 -%187 = OpVectorTimesScalar %16 %188 %192 -%185 = OpFAdd %16 %186 %187 -%194 = OpLoad %16 %21 -%195 = OpAccessChain %196 %119 %197 -%198 = OpLoad %6 %195 -%193 = OpVectorTimesScalar %16 %194 %198 -%184 = OpFAdd %16 %185 %193 -%200 = OpLoad %16 %20 -%201 = OpAccessChain %202 %119 %203 -%204 = OpLoad %6 %201 -%199 = OpVectorTimesScalar %16 %200 %204 -%183 = OpFAdd %16 %184 %199 -OpStore %18 %183 -%206 = OpLoad %16 %18 -%207 = OpExtInst %16 %1 Normalize %206 -%208 = OpLoad %16 %18 -%209 = OpExtInst %6 %1 Length %208 -%210 = OpExtInst %6 %1 FClamp %209 %5 %13 -%205 = OpVectorTimesScalar %16 %207 %210 -OpStore %18 %205 -%212 = OpLoad %16 %15 -%214 = OpLoad %16 %18 -%215 = OpAccessChain %216 %119 %217 -%218 = OpLoad %6 %215 -%213 = OpVectorTimesScalar %16 %214 %218 -%211 = OpFAdd %16 %212 %213 -OpStore %15 %211 -%220 = OpAccessChain %221 %15 %222 -%223 = OpLoad %6 %220 -%219 = OpFOrdLessThan %32 %223 %14 -OpSelectionMerge %224 None -OpBranchConditional %219 %225 %224 -%225 = OpLabel -%226 = OpAccessChain %227 %15 %228 -OpStore %226 %12 -OpBranch %224 -%224 = OpLabel -%230 = OpAccessChain %231 %15 %232 -%233 = OpLoad %6 %230 -%229 = OpFOrdGreaterThan %32 %233 %12 -OpSelectionMerge %234 None -OpBranchConditional %229 %235 %234 -%235 = OpLabel -%236 = OpAccessChain %237 %15 %238 -OpStore %236 %14 -OpBranch %234 -%234 = OpLabel -%240 = OpAccessChain %241 %15 %242 -%243 = OpLoad %6 %240 -%239 = OpFOrdLessThan %32 %243 %14 -OpSelectionMerge %244 None -OpBranchConditional %239 %245 %244 -%245 = OpLabel -%246 = OpAccessChain %247 %15 %248 -OpStore %246 %12 -OpBranch %244 -%244 = OpLabel -%250 = OpAccessChain %251 %15 %252 -%253 = OpLoad %6 %250 -%249 = OpFOrdGreaterThan %32 %253 %12 -OpSelectionMerge %254 None -OpBranchConditional %249 %255 %254 -%255 = OpLabel -%256 = OpAccessChain %257 %15 %258 -OpStore %256 %14 -OpBranch %254 -%254 = OpLabel -%261 = OpAccessChain %263 %262 %264 -%265 = OpAccessChain %266 %36 %267 -%268 = OpLoad %9 %265 -%260 = OpAccessChain %269 %261 %268 -%259 = OpAccessChain %270 %260 %271 -%272 = OpLoad %16 %15 -OpStore %259 %272 -%275 = OpAccessChain %276 %262 %277 -%278 = OpAccessChain %279 %36 %280 -%281 = OpLoad %9 %278 -%274 = OpAccessChain %282 %275 %281 -%273 = OpAccessChain %283 %274 %284 -%285 = OpLoad %16 %18 -OpStore %273 %285 +%49 = OpLabel +%53 = OpAccessChain %54 %18 %52 %46 %51 +%55 = OpLoad %22 %53 +OpStore %28 %55 +%58 = OpAccessChain %59 %18 %57 %46 %56 +%60 = OpLoad %22 %58 +OpStore %30 %60 +%61 = OpCompositeConstruct %22 %5 %5 +OpStore %31 %61 +%62 = OpCompositeConstruct %22 %5 %5 +OpStore %32 %62 +%63 = OpCompositeConstruct %22 %5 %5 +OpStore %33 %63 +OpBranch %64 +%64 = OpLabel +OpLoopMerge %65 %67 None +OpBranch %66 +%66 = OpLabel +%68 = OpLoad %9 %39 +%69 = OpUGreaterThanEqual %47 %68 %3 +OpSelectionMerge %70 None +OpBranchConditional %69 %71 %70 +%71 = OpLabel +OpBranch %65 +%70 = OpLabel +%72 = OpLoad %9 %39 +%73 = OpIEqual %47 %72 %46 +OpSelectionMerge %74 None +OpBranchConditional %73 %75 %74 +%75 = OpLabel +OpBranch %67 +%74 = OpLabel +%76 = OpLoad %9 %39 +%79 = OpAccessChain %80 %18 %78 %76 %77 +%81 = OpLoad %22 %79 +OpStore %37 %81 +%82 = OpLoad %9 %39 +%85 = OpAccessChain %86 %18 %84 %82 %83 +%87 = OpLoad %22 %85 +OpStore %38 %87 +%88 = OpLoad %22 %37 +%89 = OpLoad %22 %28 +%90 = OpExtInst %6 %1 Distance %88 %89 +%92 = OpAccessChain %93 %15 %91 +%94 = OpLoad %6 %92 +%95 = OpFOrdLessThan %47 %90 %94 +OpSelectionMerge %96 None +OpBranchConditional %95 %97 %96 +%97 = OpLabel +%98 = OpLoad %22 %31 +%99 = OpLoad %22 %37 +%100 = OpFAdd %22 %98 %99 +OpStore %31 %100 +%101 = OpLoad %4 %34 +%102 = OpIAdd %4 %101 %10 +OpStore %34 %102 +OpBranch %96 +%96 = OpLabel +%103 = OpLoad %22 %37 +%104 = OpLoad %22 %28 +%105 = OpExtInst %6 %1 Distance %103 %104 +%107 = OpAccessChain %108 %15 %106 +%109 = OpLoad %6 %107 +%110 = OpFOrdLessThan %47 %105 %109 +OpSelectionMerge %111 None +OpBranchConditional %110 %112 %111 +%112 = OpLabel +%113 = OpLoad %22 %33 +%114 = OpLoad %22 %37 +%115 = OpLoad %22 %28 +%116 = OpFSub %22 %114 %115 +%117 = OpFSub %22 %113 %116 +OpStore %33 %117 +OpBranch %111 +%111 = OpLabel +%118 = OpLoad %22 %37 +%119 = OpLoad %22 %28 +%120 = OpExtInst %6 %1 Distance %118 %119 +%122 = OpAccessChain %123 %15 %121 +%124 = OpLoad %6 %122 +%125 = OpFOrdLessThan %47 %120 %124 +OpSelectionMerge %126 None +OpBranchConditional %125 %127 %126 +%127 = OpLabel +%128 = OpLoad %22 %32 +%129 = OpLoad %22 %38 +%130 = OpFAdd %22 %128 %129 +OpStore %32 %130 +%131 = OpLoad %4 %36 +%132 = OpIAdd %4 %131 %10 +OpStore %36 %132 +OpBranch %126 +%126 = OpLabel +OpBranch %67 +%67 = OpLabel +%133 = OpLoad %9 %39 +%134 = OpIAdd %9 %133 %11 +OpStore %39 %134 +OpBranch %64 +%65 = OpLabel +%135 = OpLoad %4 %34 +%136 = OpSGreaterThan %47 %135 %7 +OpSelectionMerge %137 None +OpBranchConditional %136 %138 %137 +%138 = OpLabel +%139 = OpLoad %22 %31 +%140 = OpLoad %4 %34 +%141 = OpConvertSToF %6 %140 +%142 = OpFDiv %6 %12 %141 +%143 = OpVectorTimesScalar %22 %139 %142 +%144 = OpLoad %22 %28 +%145 = OpFSub %22 %143 %144 +OpStore %31 %145 +OpBranch %137 +%137 = OpLabel +%146 = OpLoad %4 %36 +%147 = OpSGreaterThan %47 %146 %7 +OpSelectionMerge %148 None +OpBranchConditional %147 %149 %148 +%149 = OpLabel +%150 = OpLoad %22 %32 +%151 = OpLoad %4 %36 +%152 = OpConvertSToF %6 %151 +%153 = OpFDiv %6 %12 %152 +%154 = OpVectorTimesScalar %22 %150 %153 +OpStore %32 %154 +OpBranch %148 +%148 = OpLabel +%155 = OpLoad %22 %30 +%156 = OpLoad %22 %31 +%158 = OpAccessChain %159 %15 %157 +%160 = OpLoad %6 %158 +%161 = OpVectorTimesScalar %22 %156 %160 +%162 = OpFAdd %22 %155 %161 +%163 = OpLoad %22 %33 +%165 = OpAccessChain %166 %15 %164 +%167 = OpLoad %6 %165 +%168 = OpVectorTimesScalar %22 %163 %167 +%169 = OpFAdd %22 %162 %168 +%170 = OpLoad %22 %32 +%172 = OpAccessChain %173 %15 %171 +%174 = OpLoad %6 %172 +%175 = OpVectorTimesScalar %22 %170 %174 +%176 = OpFAdd %22 %169 %175 +OpStore %30 %176 +%177 = OpLoad %22 %30 +%178 = OpExtInst %22 %1 Normalize %177 +%179 = OpLoad %22 %30 +%180 = OpExtInst %6 %1 Length %179 +%181 = OpExtInst %6 %1 FClamp %180 %5 %13 +%182 = OpVectorTimesScalar %22 %178 %181 +OpStore %30 %182 +%183 = OpLoad %22 %28 +%184 = OpLoad %22 %30 +%186 = OpAccessChain %187 %15 %185 +%188 = OpLoad %6 %186 +%189 = OpVectorTimesScalar %22 %184 %188 +%190 = OpFAdd %22 %183 %189 +OpStore %28 %190 +%191 = OpLoad %22 %28 +%192 = OpCompositeExtract %6 %191 0 +%193 = OpFOrdLessThan %47 %192 %14 +OpSelectionMerge %194 None +OpBranchConditional %193 %195 %194 +%195 = OpLabel +%197 = OpAccessChain %198 %28 %196 +OpStore %197 %12 +OpBranch %194 +%194 = OpLabel +%199 = OpLoad %22 %28 +%200 = OpCompositeExtract %6 %199 0 +%201 = OpFOrdGreaterThan %47 %200 %12 +OpSelectionMerge %202 None +OpBranchConditional %201 %203 %202 +%203 = OpLabel +%205 = OpAccessChain %206 %28 %204 +OpStore %205 %14 +OpBranch %202 +%202 = OpLabel +%207 = OpLoad %22 %28 +%208 = OpCompositeExtract %6 %207 1 +%209 = OpFOrdLessThan %47 %208 %14 +OpSelectionMerge %210 None +OpBranchConditional %209 %211 %210 +%211 = OpLabel +%213 = OpAccessChain %214 %28 %212 +OpStore %213 %12 +OpBranch %210 +%210 = OpLabel +%215 = OpLoad %22 %28 +%216 = OpCompositeExtract %6 %215 1 +%217 = OpFOrdGreaterThan %47 %216 %12 +OpSelectionMerge %218 None +OpBranchConditional %217 %219 %218 +%219 = OpLabel +%221 = OpAccessChain %222 %28 %220 +OpStore %221 %14 +OpBranch %218 +%218 = OpLabel +%223 = OpLoad %22 %28 +%226 = OpAccessChain %227 %24 %225 %46 %224 +OpStore %226 %223 +%228 = OpLoad %22 %30 +%231 = OpAccessChain %232 %24 %230 %46 %229 +OpStore %231 %228 OpReturn OpFunctionEnd diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 9342a5233..78eff2adb 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -60,6 +60,13 @@ expression: output ref_count: 3, assignable_global: None, ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 0, @@ -74,6 +81,13 @@ expression: output ref_count: 1, assignable_global: None, ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 0, @@ -102,13 +116,6 @@ expression: output ref_count: 1, assignable_global: None, ), - ( - control_flags: ( - bits: 0, - ), - ref_count: 1, - assignable_global: None, - ), ( control_flags: ( bits: 1, @@ -144,6 +151,13 @@ expression: output ref_count: 1, assignable_global: None, ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 0, @@ -158,6 +172,34 @@ expression: output ref_count: 1, assignable_global: None, ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ], ), ], @@ -202,7 +244,14 @@ expression: output bits: 1, ), ref_count: 1, - assignable_global: Some(1), + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, ), ( control_flags: ( @@ -223,7 +272,14 @@ expression: output bits: 1, ), ref_count: 1, - assignable_global: Some(1), + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, ), ( control_flags: ( @@ -232,6 +288,13 @@ expression: output ref_count: 1, assignable_global: Some(2), ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 5, diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index 2b928187a..9ff843e53 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -43,8 +43,8 @@ kernel void main1( type global_id [[thread_position_in_grid]], device PrimeIndices& v_indices [[buffer(0)]] ) { - type1 _expr8 = collatz_iterations(v_indices.data[global_id.x]); - v_indices.data[global_id.x] = _expr8; + type1 _expr11 = collatz_iterations(v_indices.data[global_id.x]); + v_indices.data[global_id.x] = _expr11; return ; } diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap index ef58ec585..4dbd43883 100644 --- a/tests/out/collatz.ron.snap +++ b/tests/out/collatz.ron.snap @@ -131,48 +131,66 @@ expression: output LocalVariable(1), Constant(1), LocalVariable(2), + Load( + pointer: 4, + ), Constant(2), Binary( op: LessEqual, - left: 4, - right: 7, + left: 7, + right: 8, + ), + Load( + pointer: 4, ), Constant(3), Binary( op: Modulo, - left: 4, - right: 9, + left: 10, + right: 11, ), Constant(1), Binary( op: Equal, - left: 10, - right: 11, + left: 12, + right: 13, + ), + Load( + pointer: 4, ), Constant(3), Binary( op: Divide, - left: 4, - right: 13, + left: 15, + right: 16, ), Constant(4), + Load( + pointer: 4, + ), Binary( op: Multiply, - left: 15, - right: 4, - ), - Constant(2), - Binary( - op: Add, - left: 16, - right: 17, - ), - Constant(2), - Binary( - op: Add, - left: 6, + left: 18, right: 19, ), + Constant(2), + Binary( + op: Add, + left: 20, + right: 21, + ), + Load( + pointer: 6, + ), + Constant(2), + Binary( + op: Add, + left: 23, + right: 24, + ), + Load( + pointer: 6, + ), ], body: [ Store( @@ -181,37 +199,85 @@ expression: output ), Loop( body: [ + Emit(( + start: 6, + end: 7, + )), + Emit(( + start: 8, + end: 9, + )), If( - condition: 8, + condition: 9, accept: [ Break, ], reject: [], ), + Emit(( + start: 9, + end: 10, + )), + Emit(( + start: 11, + end: 12, + )), + Emit(( + start: 13, + end: 14, + )), If( - condition: 12, + condition: 14, accept: [ + Emit(( + start: 14, + end: 15, + )), + Emit(( + start: 16, + end: 17, + )), Store( pointer: 4, - value: 14, + value: 17, ), ], reject: [ + Emit(( + start: 18, + end: 20, + )), + Emit(( + start: 21, + end: 22, + )), Store( pointer: 4, - value: 18, + value: 22, ), ], ), + Emit(( + start: 22, + end: 23, + )), + Emit(( + start: 24, + end: 25, + )), Store( pointer: 6, - value: 20, + value: 25, ), ], continuing: [], ), + Emit(( + start: 25, + end: 26, + )), Return( - value: Some(6), + value: Some(26), ), ], ), @@ -232,39 +298,52 @@ expression: output base: 2, index: 0, ), + Load( + pointer: 1, + ), AccessIndex( - base: 1, + base: 4, index: 0, ), Access( base: 3, - index: 4, + index: 5, ), AccessIndex( base: 2, index: 0, ), + Load( + pointer: 1, + ), AccessIndex( - base: 1, + base: 8, index: 0, ), Access( - base: 6, - index: 7, + base: 7, + index: 9, + ), + Load( + pointer: 10, ), Call(1), ], body: [ + Emit(( + start: 2, + end: 11, + )), Call( function: 1, arguments: [ - 8, + 11, ], - result: Some(9), + result: Some(12), ), Store( - pointer: 5, - value: 9, + pointer: 6, + value: 12, ), Return( value: None, diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index 02b2060f0..c24901735 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -5,113 +5,109 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 69 +; Bound: 63 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %38 "main" %53 -OpExecutionMode %38 LocalSize 1 1 1 +OpEntryPoint GLCompute %46 "main" %8 +OpExecutionMode %46 LocalSize 1 1 1 OpSource GLSL 450 -OpName %8 "n" -OpName %10 "i" -OpName %12 "collatz_iterations" -OpName %38 "main" -OpName %45 "PrimeIndices" -OpMemberName %45 0 "data" -OpName %46 "v_indices" -OpName %53 "global_id" -OpName %38 "main" -OpDecorate %43 ArrayStride 4 -OpDecorate %45 BufferBlock -OpMemberDecorate %45 0 Offset 0 -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 0 -OpDecorate %53 BuiltIn GlobalInvocationId +OpName %8 "global_id" +OpName %12 "PrimeIndices" +OpMemberName %12 0 "data" +OpName %11 "v_indices" +OpName %15 "n" +OpName %17 "i" +OpName %19 "collatz_iterations" +OpName %46 "main" +OpName %46 "main" +OpDecorate %8 BuiltIn GlobalInvocationId +OpDecorate %12 BufferBlock +OpMemberDecorate %12 0 Offset 0 +OpDecorate %13 ArrayStride 4 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 %5 = OpConstant %4 1 %6 = OpConstant %4 2 %7 = OpConstant %4 3 -%9 = OpTypePointer Function %4 -%13 = OpTypeFunction %4 %4 -%19 = OpTypeBool -%39 = OpTypeFunction %2 -%43 = OpTypeRuntimeArray %4 -%45 = OpTypeStruct %43 -%47 = OpTypePointer Uniform %45 -%46 = OpVariable %47 Uniform -%48 = OpTypePointer Uniform %43 -%49 = OpTypeInt 32 1 -%50 = OpConstant %49 0 -%52 = OpTypeVector %4 3 -%54 = OpTypePointer Input %52 -%53 = OpVariable %54 Input -%55 = OpTypePointer Input %4 -%56 = OpConstant %49 0 -%58 = OpTypePointer Uniform %4 -%62 = OpTypePointer Uniform %43 -%63 = OpConstant %49 0 -%65 = OpTypePointer Input %4 -%66 = OpConstant %49 0 -%68 = OpTypePointer Uniform %4 -%12 = OpFunction %4 None %13 -%11 = OpFunctionParameter %4 -%14 = OpLabel -%8 = OpVariable %9 Function -%10 = OpVariable %9 Function %3 -OpStore %8 %11 -OpBranch %15 -%15 = OpLabel -OpLoopMerge %16 %18 None -OpBranch %17 -%17 = OpLabel -%21 = OpLoad %4 %8 -%20 = OpULessThanEqual %19 %21 %5 -OpSelectionMerge %22 None -OpBranchConditional %20 %23 %22 -%23 = OpLabel -OpBranch %16 +%9 = OpTypeVector %4 3 +%10 = OpTypePointer Input %9 +%8 = OpVariable %10 Input +%13 = OpTypeRuntimeArray %4 +%12 = OpTypeStruct %13 +%14 = OpTypePointer Uniform %12 +%11 = OpVariable %14 Uniform +%16 = OpTypePointer Function %4 +%20 = OpTypeFunction %4 %4 +%28 = OpTypeBool +%47 = OpTypeFunction %2 +%54 = OpTypeInt 32 1 +%55 = OpConstant %54 0 +%57 = OpTypePointer Uniform %4 +%60 = OpConstant %54 0 +%62 = OpTypePointer Uniform %4 +%19 = OpFunction %4 None %20 +%18 = OpFunctionParameter %4 +%21 = OpLabel +%15 = OpVariable %16 Function +%17 = OpVariable %16 Function %3 +OpBranch %22 %22 = OpLabel -%26 = OpLoad %4 %8 -%25 = OpUMod %4 %26 %6 -%24 = OpIEqual %19 %25 %3 -OpSelectionMerge %27 None -OpBranchConditional %24 %28 %29 -%28 = OpLabel -%31 = OpLoad %4 %8 -%30 = OpUDiv %4 %31 %6 -OpStore %8 %30 -OpBranch %27 -%29 = OpLabel -%34 = OpLoad %4 %8 -%33 = OpIMul %4 %7 %34 -%32 = OpIAdd %4 %33 %5 -OpStore %8 %32 -OpBranch %27 -%27 = OpLabel -%36 = OpLoad %4 %10 -%35 = OpIAdd %4 %36 %5 -OpStore %10 %35 -OpBranch %18 -%18 = OpLabel -OpBranch %15 -%16 = OpLabel -%37 = OpLoad %4 %10 -OpReturnValue %37 +OpStore %15 %18 +OpBranch %23 +%23 = OpLabel +OpLoopMerge %24 %26 None +OpBranch %25 +%25 = OpLabel +%27 = OpLoad %4 %15 +%29 = OpULessThanEqual %28 %27 %5 +OpSelectionMerge %30 None +OpBranchConditional %29 %31 %30 +%31 = OpLabel +OpBranch %24 +%30 = OpLabel +%32 = OpLoad %4 %15 +%33 = OpUMod %4 %32 %6 +%34 = OpIEqual %28 %33 %3 +OpSelectionMerge %35 None +OpBranchConditional %34 %36 %37 +%36 = OpLabel +%38 = OpLoad %4 %15 +%39 = OpUDiv %4 %38 %6 +OpStore %15 %39 +OpBranch %35 +%37 = OpLabel +%40 = OpLoad %4 %15 +%41 = OpIMul %4 %7 %40 +%42 = OpIAdd %4 %41 %5 +OpStore %15 %42 +OpBranch %35 +%35 = OpLabel +%43 = OpLoad %4 %17 +%44 = OpIAdd %4 %43 %5 +OpStore %17 %44 +OpBranch %26 +%26 = OpLabel +OpBranch %23 +%24 = OpLabel +%45 = OpLoad %4 %17 +OpReturnValue %45 OpFunctionEnd -%38 = OpFunction %2 None %39 -%40 = OpLabel -%44 = OpAccessChain %48 %46 %50 -%51 = OpAccessChain %55 %53 %56 -%57 = OpLoad %4 %51 -%42 = OpAccessChain %58 %44 %57 -%59 = OpLoad %4 %42 -%41 = OpFunctionCall %4 %12 %59 -%61 = OpAccessChain %62 %46 %63 -%64 = OpAccessChain %65 %53 %66 -%67 = OpLoad %4 %64 -%60 = OpAccessChain %68 %61 %67 -OpStore %60 %41 +%46 = OpFunction %2 None %47 +%48 = OpLabel +OpBranch %49 +%49 = OpLabel +%50 = OpLoad %9 %8 +%51 = OpCompositeExtract %4 %50 0 +%52 = OpLoad %9 %8 +%53 = OpCompositeExtract %4 %52 0 +%56 = OpAccessChain %57 %11 %55 %53 +%58 = OpLoad %4 %56 +%59 = OpFunctionCall %4 %19 %58 +%61 = OpAccessChain %62 %11 %60 %51 +OpStore %61 %59 OpReturn OpFunctionEnd diff --git a/tests/out/empty.spvasm.snap b/tests/out/empty.spvasm.snap index fe37d10b6..c26ec0c45 100644 --- a/tests/out/empty.spvasm.snap +++ b/tests/out/empty.spvasm.snap @@ -5,7 +5,7 @@ expression: dis ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 6 +; Bound: 7 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -18,5 +18,7 @@ OpName %3 "main" %4 = OpTypeFunction %2 %3 = OpFunction %2 None %4 %5 = OpLabel +OpBranch %6 +%6 = OpLabel OpReturn OpFunctionEnd diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap index b52fb02cd..976075594 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad-Fragment.glsl.snap @@ -13,6 +13,7 @@ uniform sampler2D _group_0_binding_0; out vec4 _location_0; void main() { + ; _location_0 = texture(_group_0_binding_0, vec2(_location_0_vs)); return; } diff --git a/tests/out/quad-Vertex.glsl.snap b/tests/out/quad-Vertex.glsl.snap index 63e133f4b..b430f8475 100644 --- a/tests/out/quad-Vertex.glsl.snap +++ b/tests/out/quad-Vertex.glsl.snap @@ -13,7 +13,10 @@ in vec2 _location_1; out vec2 _location_0_vs; void main() { + ; _location_0_vs = _location_1; + ; + ; gl_Position = vec4((1.2 * _location_0), 0.0, 1.0); return; } diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index be352e902..e9b69c0cd 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -51,7 +51,8 @@ fragment main2Output main2( type4 u_sampler [[sampler(0)]] ) { main2Output output; - output.o_color = u_texture.sample(u_sampler, input.v_uv1); + metal::float4 _expr9 = u_texture.sample(u_sampler, input.v_uv1); + output.o_color = _expr9; return output; } diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index 1cbbb2686..99f99eee9 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -5,78 +5,82 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 39 +; Bound: 41 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %7 "main" %20 %13 %11 %17 -OpEntryPoint Fragment %23 "main" %35 %25 -OpExecutionMode %23 OriginUpperLeft +OpEntryPoint Vertex %24 "main" %7 %10 %11 %13 +OpEntryPoint Fragment %32 "main" %16 %23 +OpExecutionMode %32 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" -OpName %7 "main" +OpName %7 "a_pos" +OpName %10 "a_uv" OpName %11 "v_uv" -OpName %13 "a_uv" -OpName %17 "o_position" -OpName %20 "a_pos" -OpName %7 "main" -OpName %23 "main" -OpName %25 "o_color" -OpName %27 "u_texture" -OpName %32 "u_sampler" -OpName %35 "v_uv" -OpName %23 "main" +OpName %13 "o_position" +OpName %16 "v_uv" +OpName %17 "u_texture" +OpName %20 "u_sampler" +OpName %23 "o_color" +OpName %24 "main" +OpName %24 "main" +OpName %32 "main" +OpName %32 "main" +OpDecorate %7 Location 0 +OpDecorate %10 Location 1 OpDecorate %11 Location 0 -OpDecorate %13 Location 1 -OpDecorate %17 BuiltIn Position -OpDecorate %20 Location 0 -OpDecorate %25 Location 0 -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 0 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 1 -OpDecorate %35 Location 0 +OpDecorate %13 BuiltIn Position +OpDecorate %16 Location 0 +OpDecorate %17 DescriptorSet 0 +OpDecorate %17 Binding 0 +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 1 +OpDecorate %23 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.2 %5 = OpConstant %4 0.0 %6 = OpConstant %4 1.0 -%8 = OpTypeFunction %2 -%10 = OpTypeVector %4 2 -%12 = OpTypePointer Output %10 +%8 = OpTypeVector %4 2 +%9 = OpTypePointer Input %8 +%7 = OpVariable %9 Input +%10 = OpVariable %9 Input +%12 = OpTypePointer Output %8 %11 = OpVariable %12 Output -%14 = OpTypePointer Input %10 -%13 = OpVariable %14 Input -%16 = OpTypeVector %4 4 -%18 = OpTypePointer Output %16 -%17 = OpVariable %18 Output -%20 = OpVariable %14 Input -%25 = OpVariable %18 Output -%26 = OpTypeImage %4 2D 0 0 0 1 Unknown -%28 = OpTypePointer UniformConstant %26 -%27 = OpVariable %28 UniformConstant -%30 = OpTypeSampledImage %26 -%31 = OpTypeSampler -%33 = OpTypePointer UniformConstant %31 -%32 = OpVariable %33 UniformConstant -%35 = OpVariable %14 Input -%7 = OpFunction %2 None %8 -%9 = OpLabel -%15 = OpLoad %10 %13 -OpStore %11 %15 -%21 = OpLoad %10 %20 -%19 = OpVectorTimesScalar %10 %21 %3 -%22 = OpCompositeConstruct %16 %19 %5 %6 -OpStore %17 %22 +%14 = OpTypeVector %4 4 +%15 = OpTypePointer Output %14 +%13 = OpVariable %15 Output +%16 = OpVariable %9 Input +%18 = OpTypeImage %4 2D 0 0 0 1 Unknown +%19 = OpTypePointer UniformConstant %18 +%17 = OpVariable %19 UniformConstant +%21 = OpTypeSampler +%22 = OpTypePointer UniformConstant %21 +%20 = OpVariable %22 UniformConstant +%23 = OpVariable %15 Output +%25 = OpTypeFunction %2 +%38 = OpTypeSampledImage %18 +%24 = OpFunction %2 None %25 +%26 = OpLabel +OpBranch %27 +%27 = OpLabel +%28 = OpLoad %8 %10 +OpStore %11 %28 +%29 = OpLoad %8 %7 +%30 = OpVectorTimesScalar %8 %29 %3 +%31 = OpCompositeConstruct %14 %30 %5 %6 +OpStore %13 %31 OpReturn OpFunctionEnd -%23 = OpFunction %2 None %8 -%24 = OpLabel -%29 = OpLoad %26 %27 -%34 = OpLoad %31 %32 -%36 = OpLoad %10 %35 -%37 = OpSampledImage %30 %29 %34 -%38 = OpImageSampleImplicitLod %16 %37 %36 -OpStore %25 %38 +%32 = OpFunction %2 None %25 +%33 = OpLabel +%34 = OpLoad %18 %17 +%35 = OpLoad %21 %20 +OpBranch %36 +%36 = OpLabel +%37 = OpLoad %8 %16 +%39 = OpSampledImage %38 %34 %35 +%40 = OpImageSampleImplicitLod %14 %39 %37 +OpStore %23 %40 OpReturn OpFunctionEnd diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 1e2dc996e..93429ed88 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -1,7 +1,6 @@ --- source: tests/snapshots.rs expression: output - --- ( functions: [ @@ -884,10 +883,10 @@ expression: output ), ( control_flags: ( - bits: 0, + bits: 1, ), ref_count: 1, - assignable_global: Some(3), + assignable_global: None, ), ( control_flags: ( @@ -901,6 +900,34 @@ expression: output bits: 0, ), ref_count: 1, + assignable_global: Some(3), + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, assignable_global: None, ), ( @@ -917,6 +944,13 @@ expression: output ref_count: 1, assignable_global: Some(4), ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 1, @@ -938,6 +972,20 @@ expression: output ref_count: 1, assignable_global: None, ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 5, @@ -952,33 +1000,12 @@ expression: output ref_count: 1, assignable_global: None, ), - ( - control_flags: ( - bits: 0, - ), - ref_count: 1, - assignable_global: Some(4), - ), ( control_flags: ( bits: 1, ), ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), + assignable_global: None, ), ( control_flags: ( @@ -992,7 +1019,7 @@ expression: output bits: 1, ), ref_count: 1, - assignable_global: Some(4), + assignable_global: None, ), ( control_flags: ( @@ -1008,6 +1035,20 @@ expression: output ref_count: 1, assignable_global: Some(4), ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 0, @@ -1015,6 +1056,55 @@ expression: output ref_count: 1, assignable_global: Some(4), ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 1, @@ -1048,7 +1138,7 @@ expression: output bits: 1, ), ref_count: 1, - assignable_global: Some(5), + assignable_global: None, ), ( control_flags: ( @@ -1057,6 +1147,13 @@ expression: output ref_count: 1, assignable_global: Some(5), ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 1, @@ -1071,6 +1168,27 @@ expression: output ref_count: 1, assignable_global: None, ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(5), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 1, @@ -1118,56 +1236,7 @@ expression: output bits: 1, ), ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 0, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 0, - ), - ref_count: 1, - assignable_global: Some(4), + assignable_global: None, ), ( control_flags: ( @@ -1197,6 +1266,97 @@ expression: output ref_count: 1, assignable_global: None, ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 0, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ( control_flags: ( bits: 5, @@ -1225,6 +1385,20 @@ expression: output ref_count: 1, assignable_global: None, ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), + ( + control_flags: ( + bits: 1, + ), + ref_count: 1, + assignable_global: None, + ), ], ), }, diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 623d4d1c5..5633a65f7 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -60,7 +60,8 @@ type7 fetch_shadow( return const_1f; } float _expr15 = (const_1f / homogeneous_coords.w); - return t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * _expr15) + metal::float2(const_0_50f, const_0_50f)), static_cast(light_id), (homogeneous_coords.z * _expr15)); + float _expr28 = t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * _expr15) + metal::float2(const_0_50f, const_0_50f)), static_cast(light_id), (homogeneous_coords.z * _expr15)); + return _expr28; } struct fs_mainInput { @@ -91,9 +92,10 @@ fragment fs_mainOutput fs_main( if ((i >= metal::min(u_globals.num_lights.x, c_max_lights))) { break; } - Light _expr18 = s_lights.data[i]; - type7 _expr21 = fetch_shadow(i, (_expr18.proj * input.in_position_fs), t_shadow, sampler_shadow); - color1 = (color1 + ((_expr21 * metal::max(const_0f, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(_expr18.pos.x, _expr18.pos.y, _expr18.pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(_expr18.color.x, _expr18.color.y, _expr18.color.z))); + Light _expr23 = s_lights.data[i]; + type7 _expr28 = fetch_shadow(i, (_expr23.proj * input.in_position_fs), t_shadow, sampler_shadow); + type2 _expr34 = input.in_position_fs; + color1 = (color1 + ((_expr28 * metal::max(const_0f, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(_expr23.pos.x, _expr23.pos.y, _expr23.pos.z) - metal::float3(_expr34.x, _expr34.y, _expr34.z)))))) * metal::float3(_expr23.color.x, _expr23.color.y, _expr23.color.z))); } output.out_color_fs = metal::float4(color1, const_1f); return output; diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index e20132627..a63e07a90 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -779,6 +779,10 @@ expression: output ), ], body: [ + Emit(( + start: 44, + end: 46, + )), If( condition: 46, accept: [ @@ -788,6 +792,10 @@ expression: output ], reject: [], ), + Emit(( + start: 46, + end: 71, + )), Return( value: Some(71), ), @@ -859,46 +867,70 @@ expression: output Constant(5), LocalVariable(1), LocalVariable(2), + Load( + pointer: 44, + ), AccessIndex( base: 1, index: 0, ), Access( - base: 45, + base: 46, index: 37, ), + Load( + pointer: 47, + ), Math( fun: Min, - arg: 46, + arg: 48, arg1: Some(28), arg2: None, ), Binary( op: GreaterEqual, - left: 44, - right: 47, + left: 45, + right: 49, + ), + Load( + pointer: 43, + ), + Load( + pointer: 44, ), AccessIndex( base: 6, index: 0, ), + Load( + pointer: 44, + ), Access( - base: 49, - index: 44, + base: 53, + index: 54, ), AccessIndex( - base: 50, + base: 55, index: 0, ), + Load( + pointer: 56, + ), + Load( + pointer: 3, + ), Binary( op: Multiply, - left: 51, - right: 3, + left: 57, + right: 58, ), Call(1), + Load( + pointer: 2, + ), Math( fun: Normalize, - arg: 2, + arg: 61, arg1: None, arg2: None, ), @@ -906,181 +938,232 @@ expression: output base: 6, index: 0, ), - Access( - base: 55, - index: 44, - ), - AccessIndex( - base: 56, - index: 1, - ), - Access( - base: 57, - index: 31, - ), - AccessIndex( - base: 6, - index: 0, - ), - Access( - base: 59, - index: 44, - ), - AccessIndex( - base: 60, - index: 1, - ), - Access( - base: 61, - index: 38, - ), - AccessIndex( - base: 6, - index: 0, + Load( + pointer: 44, ), Access( base: 63, - index: 44, + index: 64, ), AccessIndex( - base: 64, + base: 65, index: 1, ), Access( - base: 65, + base: 66, + index: 31, + ), + Load( + pointer: 67, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( + base: 69, + index: 70, + ), + AccessIndex( + base: 71, + index: 1, + ), + Access( + base: 72, + index: 38, + ), + Load( + pointer: 73, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( + base: 75, + index: 76, + ), + AccessIndex( + base: 77, + index: 1, + ), + Access( + base: 78, index: 13, ), + Load( + pointer: 79, + ), Compose( ty: 2, components: [ - 58, - 62, - 66, + 68, + 74, + 80, ], ), Access( base: 3, index: 36, ), + Load( + pointer: 82, + ), Access( base: 3, index: 12, ), + Load( + pointer: 84, + ), Access( base: 3, index: 23, ), + Load( + pointer: 86, + ), Compose( ty: 2, components: [ - 68, - 69, - 70, + 83, + 85, + 87, ], ), Binary( op: Subtract, - left: 67, - right: 71, + left: 81, + right: 88, ), Math( fun: Normalize, - arg: 72, + arg: 89, arg1: None, arg2: None, ), Math( fun: Dot, - arg: 54, - arg1: Some(73), + arg: 62, + arg1: Some(90), arg2: None, ), Math( fun: Max, arg: 42, - arg1: Some(74), + arg1: Some(91), arg2: None, ), Binary( op: Multiply, - left: 53, - right: 75, + left: 60, + right: 92, ), AccessIndex( base: 6, index: 0, ), + Load( + pointer: 44, + ), Access( - base: 77, - index: 44, + base: 94, + index: 95, ), AccessIndex( - base: 78, + base: 96, index: 2, ), Access( - base: 79, + base: 97, index: 10, ), + Load( + pointer: 98, + ), AccessIndex( base: 6, index: 0, ), + Load( + pointer: 44, + ), Access( - base: 81, - index: 44, + base: 100, + index: 101, ), AccessIndex( - base: 82, + base: 102, index: 2, ), Access( - base: 83, + base: 103, index: 19, ), + Load( + pointer: 104, + ), AccessIndex( base: 6, index: 0, ), + Load( + pointer: 44, + ), Access( - base: 85, - index: 44, + base: 106, + index: 107, ), AccessIndex( - base: 86, + base: 108, index: 2, ), Access( - base: 87, + base: 109, index: 26, ), + Load( + pointer: 110, + ), Compose( ty: 2, components: [ - 80, - 84, - 88, + 99, + 105, + 111, ], ), Binary( op: Multiply, - left: 89, - right: 76, + left: 112, + right: 93, ), Binary( op: Add, - left: 43, - right: 90, + left: 51, + right: 113, + ), + Load( + pointer: 44, ), Binary( op: Add, - left: 44, + left: 115, right: 27, ), + Load( + pointer: 43, + ), Compose( ty: 4, components: [ - 43, + 117, 30, ], ), @@ -1088,36 +1171,56 @@ expression: output body: [ Loop( body: [ + Emit(( + start: 44, + end: 50, + )), If( - condition: 48, + condition: 50, accept: [ Break, ], reject: [], ), + Emit(( + start: 50, + end: 59, + )), Call( function: 1, arguments: [ - 44, 52, + 59, ], - result: Some(53), + result: Some(60), ), + Emit(( + start: 60, + end: 114, + )), Store( pointer: 43, - value: 91, + value: 114, ), ], continuing: [ + Emit(( + start: 114, + end: 116, + )), Store( pointer: 44, - value: 92, + value: 116, ), ], ), + Emit(( + start: 116, + end: 118, + )), Store( pointer: 7, - value: 93, + value: 118, ), Return( value: None, diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index 94e7eba17..9b1792524 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -5,57 +5,57 @@ expression: dis ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 219 +; Bound: 137 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %63 "fs_main" %112 %105 %215 -OpExecutionMode %63 OriginUpperLeft +OpEntryPoint Fragment %78 "fs_main" %32 %34 %36 +OpExecutionMode %78 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_ambient" OpName %11 "c_max_lights" -OpName %18 "fetch_shadow" -OpName %27 "t_shadow" -OpName %32 "sampler_shadow" -OpName %59 "color" -OpName %61 "i" -OpName %63 "fs_main" -OpName %75 "Globals" -OpMemberName %75 0 "num_lights" -OpName %76 "u_globals" -OpName %91 "Light" -OpMemberName %91 0 "proj" -OpMemberName %91 1 "pos" -OpMemberName %91 2 "color" -OpName %95 "Lights" -OpMemberName %95 0 "data" -OpName %96 "s_lights" -OpName %105 "in_position_fs" -OpName %112 "in_normal_fs" -OpName %215 "out_color_fs" -OpName %63 "fs_main" -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 2 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 3 -OpDecorate %75 Block -OpMemberDecorate %75 0 Offset 0 -OpDecorate %76 DescriptorSet 0 -OpDecorate %76 Binding 0 -OpMemberDecorate %91 0 Offset 0 -OpMemberDecorate %91 0 ColMajor -OpMemberDecorate %91 0 MatrixStride 16 -OpMemberDecorate %91 1 Offset 64 -OpMemberDecorate %91 2 Offset 80 -OpDecorate %93 ArrayStride 96 -OpDecorate %95 BufferBlock -OpMemberDecorate %95 0 Offset 0 -OpDecorate %96 NonWritable -OpDecorate %96 DescriptorSet 0 -OpDecorate %96 Binding 1 -OpDecorate %105 Location 1 -OpDecorate %112 Location 0 -OpDecorate %215 Location 0 +OpName %16 "Globals" +OpMemberName %16 0 "num_lights" +OpName %15 "u_globals" +OpName %20 "Lights" +OpMemberName %20 0 "data" +OpName %22 "Light" +OpMemberName %22 0 "proj" +OpMemberName %22 1 "pos" +OpMemberName %22 2 "color" +OpName %19 "s_lights" +OpName %26 "t_shadow" +OpName %29 "sampler_shadow" +OpName %32 "in_normal_fs" +OpName %34 "in_position_fs" +OpName %36 "out_color_fs" +OpName %40 "fetch_shadow" +OpName %74 "color" +OpName %76 "i" +OpName %78 "fs_main" +OpName %78 "fs_main" +OpDecorate %16 Block +OpMemberDecorate %16 0 Offset 0 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 0 +OpDecorate %20 BufferBlock +OpMemberDecorate %20 0 Offset 0 +OpDecorate %21 ArrayStride 96 +OpMemberDecorate %22 0 Offset 0 +OpMemberDecorate %22 0 ColMajor +OpMemberDecorate %22 0 MatrixStride 16 +OpMemberDecorate %22 1 Offset 64 +OpMemberDecorate %22 2 Offset 80 +OpDecorate %19 NonWritable +OpDecorate %19 DescriptorSet 0 +OpDecorate %19 Binding 1 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 2 +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 3 +OpDecorate %32 Location 0 +OpDecorate %34 Location 1 +OpDecorate %36 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 @@ -69,225 +69,145 @@ OpDecorate %215 Location 0 %11 = OpConstant %12 10 %13 = OpConstant %12 0 %14 = OpConstant %12 1 -%17 = OpTypeVector %4 4 -%19 = OpTypeFunction %4 %12 %17 -%21 = OpTypeBool -%26 = OpTypeImage %4 2D 1 1 0 1 Unknown -%28 = OpTypePointer UniformConstant %26 -%27 = OpVariable %28 UniformConstant -%30 = OpTypeSampledImage %26 -%31 = OpTypeSampler -%33 = OpTypePointer UniformConstant %31 -%32 = OpVariable %33 UniformConstant -%35 = OpTypeVector %4 2 -%49 = OpTypeInt 32 1 -%58 = OpConstant %4 0.0 -%60 = OpTypePointer Function %10 -%62 = OpTypePointer Function %12 -%64 = OpTypeFunction %2 -%73 = OpTypeVector %12 4 -%75 = OpTypeStruct %73 -%77 = OpTypePointer Uniform %75 -%76 = OpVariable %77 Uniform -%78 = OpTypePointer Uniform %73 -%79 = OpConstant %49 0 -%80 = OpTypePointer Uniform %12 -%81 = OpConstant %49 0 -%89 = OpTypeMatrix %17 4 -%91 = OpTypeStruct %89 %17 %17 -%93 = OpTypeRuntimeArray %91 -%95 = OpTypeStruct %93 -%97 = OpTypePointer Uniform %95 -%96 = OpVariable %97 Uniform -%98 = OpTypePointer Uniform %93 -%99 = OpConstant %49 0 -%101 = OpTypePointer Uniform %91 -%102 = OpTypePointer Uniform %89 -%103 = OpConstant %49 0 -%106 = OpTypePointer Input %17 -%105 = OpVariable %106 Input -%113 = OpTypePointer Input %10 -%112 = OpVariable %113 Input -%121 = OpTypePointer Uniform %93 -%122 = OpConstant %49 0 -%124 = OpTypePointer Uniform %91 -%125 = OpTypePointer Uniform %17 -%126 = OpConstant %49 1 -%127 = OpTypePointer Uniform %4 -%128 = OpConstant %49 0 -%134 = OpTypePointer Uniform %93 -%135 = OpConstant %49 0 -%137 = OpTypePointer Uniform %91 -%138 = OpTypePointer Uniform %17 -%139 = OpConstant %49 1 -%140 = OpTypePointer Uniform %4 -%141 = OpConstant %49 1 -%147 = OpTypePointer Uniform %93 -%148 = OpConstant %49 0 -%150 = OpTypePointer Uniform %91 -%151 = OpTypePointer Uniform %17 -%152 = OpConstant %49 1 -%153 = OpTypePointer Uniform %4 -%154 = OpConstant %49 2 -%158 = OpTypePointer Input %4 -%159 = OpConstant %49 0 -%162 = OpTypePointer Input %4 -%163 = OpConstant %49 1 -%166 = OpTypePointer Input %4 -%167 = OpConstant %49 2 -%177 = OpTypePointer Uniform %93 -%178 = OpConstant %49 0 -%180 = OpTypePointer Uniform %91 -%181 = OpTypePointer Uniform %17 -%182 = OpConstant %49 2 -%183 = OpTypePointer Uniform %4 -%184 = OpConstant %49 0 -%190 = OpTypePointer Uniform %93 -%191 = OpConstant %49 0 -%193 = OpTypePointer Uniform %91 -%194 = OpTypePointer Uniform %17 -%195 = OpConstant %49 2 -%196 = OpTypePointer Uniform %4 -%197 = OpConstant %49 1 -%203 = OpTypePointer Uniform %93 -%204 = OpConstant %49 0 -%206 = OpTypePointer Uniform %91 -%207 = OpTypePointer Uniform %17 -%208 = OpConstant %49 2 -%209 = OpTypePointer Uniform %4 -%210 = OpConstant %49 2 -%216 = OpTypePointer Output %17 -%215 = OpVariable %216 Output -%18 = OpFunction %4 None %19 -%15 = OpFunctionParameter %12 -%16 = OpFunctionParameter %17 -%20 = OpLabel -%23 = OpCompositeExtract %4 %16 3 -%22 = OpFOrdLessThanEqual %21 %23 %3 -OpSelectionMerge %24 None -OpBranchConditional %22 %25 %24 -%25 = OpLabel +%17 = OpTypeVector %12 4 +%16 = OpTypeStruct %17 +%18 = OpTypePointer Uniform %16 +%15 = OpVariable %18 Uniform +%24 = OpTypeVector %4 4 +%23 = OpTypeMatrix %24 4 +%22 = OpTypeStruct %23 %24 %24 +%21 = OpTypeRuntimeArray %22 +%20 = OpTypeStruct %21 +%25 = OpTypePointer Uniform %20 +%19 = OpVariable %25 Uniform +%27 = OpTypeImage %4 2D 1 1 0 1 Unknown +%28 = OpTypePointer UniformConstant %27 +%26 = OpVariable %28 UniformConstant +%30 = OpTypeSampler +%31 = OpTypePointer UniformConstant %30 +%29 = OpVariable %31 UniformConstant +%33 = OpTypePointer Input %10 +%32 = OpVariable %33 Input +%35 = OpTypePointer Input %24 +%34 = OpVariable %35 Input +%37 = OpTypePointer Output %24 +%36 = OpVariable %37 Output +%41 = OpTypeFunction %4 %12 %24 +%47 = OpTypeBool +%51 = OpTypeVector %4 2 +%62 = OpTypeInt 32 1 +%66 = OpTypeSampledImage %27 +%73 = OpConstant %4 0.0 +%75 = OpTypePointer Function %10 +%77 = OpTypePointer Function %12 +%79 = OpTypeFunction %2 +%91 = OpConstant %62 0 +%93 = OpTypePointer Uniform %17 +%101 = OpConstant %62 0 +%103 = OpTypePointer Uniform %22 +%40 = OpFunction %4 None %41 +%38 = OpFunctionParameter %12 +%39 = OpFunctionParameter %24 +%42 = OpLabel +%43 = OpLoad %27 %26 +%44 = OpLoad %30 %29 +OpBranch %45 +%45 = OpLabel +%46 = OpCompositeExtract %4 %39 3 +%48 = OpFOrdLessThanEqual %47 %46 %3 +OpSelectionMerge %49 None +OpBranchConditional %48 %50 %49 +%50 = OpLabel OpReturnValue %5 -%24 = OpLabel -%29 = OpLoad %26 %27 -%34 = OpLoad %31 %32 -%39 = OpCompositeExtract %4 %16 0 -%40 = OpCompositeExtract %4 %16 1 -%41 = OpCompositeConstruct %35 %39 %40 -%42 = OpCompositeConstruct %35 %6 %7 -%38 = OpFMul %35 %41 %42 -%44 = OpCompositeExtract %4 %16 3 -%43 = OpFDiv %4 %5 %44 -%37 = OpVectorTimesScalar %35 %38 %43 -%45 = OpCompositeConstruct %35 %6 %6 -%36 = OpFAdd %35 %37 %45 -%46 = OpCompositeExtract %4 %36 0 -%47 = OpCompositeExtract %4 %36 1 -%50 = OpBitcast %49 %15 -%48 = OpConvertUToF %4 %50 -%51 = OpCompositeConstruct %10 %46 %47 %48 -%52 = OpSampledImage %30 %29 %34 -%55 = OpCompositeExtract %4 %16 2 -%57 = OpCompositeExtract %4 %16 3 -%56 = OpFDiv %4 %5 %57 -%54 = OpFMul %4 %55 %56 -%53 = OpImageSampleDrefExplicitLod %4 %52 %51 %54 Lod %58 -OpReturnValue %53 +%49 = OpLabel +%52 = OpCompositeConstruct %51 %6 %7 +%53 = OpCompositeExtract %4 %39 3 +%54 = OpFDiv %4 %5 %53 +%55 = OpCompositeExtract %4 %39 0 +%56 = OpCompositeExtract %4 %39 1 +%57 = OpCompositeConstruct %51 %55 %56 +%58 = OpFMul %51 %57 %52 +%59 = OpVectorTimesScalar %51 %58 %54 +%60 = OpCompositeConstruct %51 %6 %6 +%61 = OpFAdd %51 %59 %60 +%63 = OpBitcast %62 %38 +%64 = OpCompositeExtract %4 %39 2 +%65 = OpFMul %4 %64 %54 +%67 = OpCompositeExtract %4 %61 0 +%68 = OpCompositeExtract %4 %61 1 +%69 = OpConvertUToF %4 %63 +%70 = OpCompositeConstruct %10 %67 %68 %69 +%71 = OpSampledImage %66 %43 %44 +%72 = OpImageSampleDrefExplicitLod %4 %71 %70 %65 Lod %73 +OpReturnValue %72 OpFunctionEnd -%63 = OpFunction %2 None %64 -%65 = OpLabel -%59 = OpVariable %60 Function %9 -%61 = OpVariable %62 Function %13 -OpBranch %66 -%66 = OpLabel -OpLoopMerge %67 %69 None -OpBranch %68 -%68 = OpLabel -%71 = OpLoad %12 %61 -%74 = OpAccessChain %78 %76 %79 -%72 = OpAccessChain %80 %74 %81 -%82 = OpLoad %12 %72 -%83 = OpExtInst %12 %1 UMin %82 %11 -%70 = OpUGreaterThanEqual %21 %71 %83 -OpSelectionMerge %84 None -OpBranchConditional %70 %85 %84 -%85 = OpLabel -OpBranch %67 -%84 = OpLabel -%87 = OpLoad %12 %61 -%94 = OpAccessChain %98 %96 %99 -%100 = OpLoad %12 %61 -%92 = OpAccessChain %101 %94 %100 -%90 = OpAccessChain %102 %92 %103 -%104 = OpLoad %89 %90 -%107 = OpLoad %17 %105 -%88 = OpMatrixTimesVector %17 %104 %107 -%86 = OpFunctionCall %4 %18 %87 %88 -%109 = OpLoad %10 %59 -%114 = OpLoad %10 %112 -%115 = OpExtInst %10 %1 Normalize %114 -%120 = OpAccessChain %121 %96 %122 -%123 = OpLoad %12 %61 -%119 = OpAccessChain %124 %120 %123 -%118 = OpAccessChain %125 %119 %126 -%117 = OpAccessChain %127 %118 %128 -%129 = OpLoad %4 %117 -%133 = OpAccessChain %134 %96 %135 -%136 = OpLoad %12 %61 -%132 = OpAccessChain %137 %133 %136 -%131 = OpAccessChain %138 %132 %139 -%130 = OpAccessChain %140 %131 %141 -%142 = OpLoad %4 %130 -%146 = OpAccessChain %147 %96 %148 -%149 = OpLoad %12 %61 -%145 = OpAccessChain %150 %146 %149 -%144 = OpAccessChain %151 %145 %152 -%143 = OpAccessChain %153 %144 %154 -%155 = OpLoad %4 %143 -%156 = OpCompositeConstruct %10 %129 %142 %155 -%157 = OpAccessChain %158 %105 %159 -%160 = OpLoad %4 %157 -%161 = OpAccessChain %162 %105 %163 -%164 = OpLoad %4 %161 -%165 = OpAccessChain %166 %105 %167 -%168 = OpLoad %4 %165 -%169 = OpCompositeConstruct %10 %160 %164 %168 -%116 = OpFSub %10 %156 %169 -%170 = OpExtInst %10 %1 Normalize %116 -%171 = OpDot %4 %115 %170 -%172 = OpExtInst %4 %1 FMax %3 %171 -%111 = OpFMul %4 %86 %172 -%176 = OpAccessChain %177 %96 %178 -%179 = OpLoad %12 %61 -%175 = OpAccessChain %180 %176 %179 -%174 = OpAccessChain %181 %175 %182 -%173 = OpAccessChain %183 %174 %184 -%185 = OpLoad %4 %173 -%189 = OpAccessChain %190 %96 %191 -%192 = OpLoad %12 %61 -%188 = OpAccessChain %193 %189 %192 -%187 = OpAccessChain %194 %188 %195 -%186 = OpAccessChain %196 %187 %197 -%198 = OpLoad %4 %186 -%202 = OpAccessChain %203 %96 %204 -%205 = OpLoad %12 %61 -%201 = OpAccessChain %206 %202 %205 -%200 = OpAccessChain %207 %201 %208 -%199 = OpAccessChain %209 %200 %210 -%211 = OpLoad %4 %199 -%212 = OpCompositeConstruct %10 %185 %198 %211 -%110 = OpVectorTimesScalar %10 %212 %111 -%108 = OpFAdd %10 %109 %110 -OpStore %59 %108 -OpBranch %69 -%69 = OpLabel -%214 = OpLoad %12 %61 -%213 = OpIAdd %12 %214 %14 -OpStore %61 %213 -OpBranch %66 -%67 = OpLabel -%217 = OpLoad %10 %59 -%218 = OpCompositeConstruct %17 %217 %5 -OpStore %215 %218 +%78 = OpFunction %2 None %79 +%80 = OpLabel +%74 = OpVariable %75 Function %9 +%76 = OpVariable %77 Function %13 +%81 = OpLoad %27 %26 +%82 = OpLoad %30 %29 +OpBranch %83 +%83 = OpLabel +%84 = OpLoad %10 %32 +%85 = OpExtInst %10 %1 Normalize %84 +OpBranch %86 +%86 = OpLabel +OpLoopMerge %87 %89 None +OpBranch %88 +%88 = OpLabel +%90 = OpLoad %12 %76 +%92 = OpAccessChain %93 %15 %91 +%94 = OpLoad %17 %92 +%95 = OpCompositeExtract %12 %94 0 +%96 = OpExtInst %12 %1 UMin %95 %11 +%97 = OpUGreaterThanEqual %47 %90 %96 +OpSelectionMerge %98 None +OpBranchConditional %97 %99 %98 +%99 = OpLabel +OpBranch %87 +%98 = OpLabel +%100 = OpLoad %12 %76 +%102 = OpAccessChain %103 %19 %101 %100 +%104 = OpLoad %22 %102 +%105 = OpLoad %12 %76 +%106 = OpCompositeExtract %23 %104 0 +%107 = OpLoad %24 %34 +%108 = OpMatrixTimesVector %24 %106 %107 +%109 = OpFunctionCall %4 %40 %105 %108 +%110 = OpCompositeExtract %24 %104 1 +%111 = OpCompositeExtract %4 %110 0 +%112 = OpCompositeExtract %4 %110 1 +%113 = OpCompositeExtract %4 %110 2 +%114 = OpCompositeConstruct %10 %111 %112 %113 +%115 = OpLoad %24 %34 +%116 = OpCompositeExtract %4 %115 0 +%117 = OpCompositeExtract %4 %115 1 +%118 = OpCompositeExtract %4 %115 2 +%119 = OpCompositeConstruct %10 %116 %117 %118 +%120 = OpFSub %10 %114 %119 +%121 = OpExtInst %10 %1 Normalize %120 +%122 = OpDot %4 %85 %121 +%123 = OpExtInst %4 %1 FMax %3 %122 +%124 = OpLoad %10 %74 +%125 = OpFMul %4 %109 %123 +%126 = OpCompositeExtract %24 %104 2 +%127 = OpCompositeExtract %4 %126 0 +%128 = OpCompositeExtract %4 %126 1 +%129 = OpCompositeExtract %4 %126 2 +%130 = OpCompositeConstruct %10 %127 %128 %129 +%131 = OpVectorTimesScalar %10 %130 %125 +%132 = OpFAdd %10 %124 %131 +OpStore %74 %132 +OpBranch %89 +%89 = OpLabel +%133 = OpLoad %12 %76 +%134 = OpIAdd %12 %133 %14 +OpStore %76 %134 +OpBranch %86 +%87 = OpLabel +%135 = OpLoad %10 %74 +%136 = OpCompositeConstruct %24 %135 %5 +OpStore %36 %136 OpReturn OpFunctionEnd diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap index 4ca9f8087..680e73ca5 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox-Fragment.glsl.snap @@ -18,6 +18,7 @@ in vec3 _location_0_vs; out vec4 _location_0; void main() { + ; _location_0 = texture(_group_0_binding_1, vec3(_location_0_vs)); return; } diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap index c5bd31b67..7833e0c27 100644 --- a/tests/out/skybox-Vertex.glsl.snap +++ b/tests/out/skybox-Vertex.glsl.snap @@ -22,11 +22,24 @@ void main() { int tmp1_; int tmp2_; vec4 unprojected; + ; + ; tmp1_ = (int(gl_VertexID) / 2); + ; + ; tmp2_ = (int(gl_VertexID) & 1); - unprojected = (_group_0_binding_0.proj_inv * vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0)); - _location_0_vs = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(unprojected[0], unprojected[1], unprojected[2])); - gl_Position = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + ; + ; + ; + ; + ; + vec4 _expr28 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + ; + ; + unprojected = (_group_0_binding_0.proj_inv * _expr28); + vec4 _expr56 = unprojected; + _location_0_vs = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr56[0], _expr56[1], _expr56[2])); + gl_Position = _expr28; return; } diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 1a1c0d096..65701abf9 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -20,9 +20,9 @@ struct Data { typedef int type4; -typedef metal::float3x3 type5; +typedef float type5; -typedef float type6; +typedef metal::float3x3 type6; typedef metal::texturecube type7; @@ -52,10 +52,11 @@ vertex vs_mainOutput vs_main( type unprojected; tmp1_ = (static_cast(in_vertex_index) / const_2i); tmp2_ = (static_cast(in_vertex_index) & const_1i); - type _expr24 = metal::float4(((static_cast(tmp1_) * const_4f) - const_1f), ((static_cast(tmp2_) * const_4f) - const_1f), const_0f, const_1f); - unprojected = (r_data.proj_inv * _expr24); - output.out_uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z)); - output.out_position = _expr24; + type _expr28 = metal::float4(((static_cast(tmp1_) * const_4f) - const_1f), ((static_cast(tmp2_) * const_4f) - const_1f), const_0f, const_1f); + unprojected = (r_data.proj_inv * _expr28); + type _expr56 = unprojected; + output.out_uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr56.x, _expr56.y, _expr56.z)); + output.out_position = _expr28; return output; } @@ -73,7 +74,8 @@ fragment fs_mainOutput fs_main( type8 r_sampler [[sampler(1)]] ) { fs_mainOutput output; - output.out_color = r_texture.sample(r_sampler, input.in_uv); + metal::float4 _expr9 = r_texture.sample(r_sampler, input.in_uv); + output.out_color = _expr9; return output; } diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index 71da0dc4a..a4e8ce6d0 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -5,50 +5,50 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 187 +; Bound: 106 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %16 "vs_main" %159 %47 %21 -OpEntryPoint Fragment %170 "fs_main" %182 %172 -OpExecutionMode %170 OriginUpperLeft +OpEntryPoint Vertex %37 "vs_main" %10 %13 %16 +OpEntryPoint Fragment %97 "fs_main" %29 %31 +OpExecutionMode %97 OriginUpperLeft OpSource GLSL 450 -OpName %10 "tmp1" -OpName %12 "tmp2" -OpName %13 "unprojected" -OpName %16 "vs_main" -OpName %21 "in_vertex_index" -OpName %31 "Data" -OpMemberName %31 0 "proj_inv" -OpMemberName %31 1 "view" -OpName %32 "r_data" -OpName %47 "out_uv" -OpName %159 "out_position" -OpName %16 "vs_main" -OpName %170 "fs_main" -OpName %172 "out_color" -OpName %174 "r_texture" -OpName %179 "r_sampler" -OpName %182 "in_uv" -OpName %170 "fs_main" -OpDecorate %21 BuiltIn VertexIndex -OpDecorate %31 Block -OpMemberDecorate %31 0 Offset 0 -OpMemberDecorate %31 0 ColMajor -OpMemberDecorate %31 0 MatrixStride 16 -OpMemberDecorate %31 1 Offset 64 -OpMemberDecorate %31 1 ColMajor -OpMemberDecorate %31 1 MatrixStride 16 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 0 -OpDecorate %47 Location 0 -OpDecorate %159 BuiltIn Position -OpDecorate %172 Location 0 -OpDecorate %174 DescriptorSet 0 -OpDecorate %174 Binding 1 -OpDecorate %179 DescriptorSet 0 -OpDecorate %179 Binding 2 -OpDecorate %182 Location 0 +OpName %10 "out_position" +OpName %13 "out_uv" +OpName %16 "in_vertex_index" +OpName %20 "Data" +OpMemberName %20 0 "proj_inv" +OpMemberName %20 1 "view" +OpName %19 "r_data" +OpName %23 "r_texture" +OpName %26 "r_sampler" +OpName %29 "in_uv" +OpName %31 "out_color" +OpName %32 "tmp1" +OpName %34 "tmp2" +OpName %35 "unprojected" +OpName %37 "vs_main" +OpName %37 "vs_main" +OpName %97 "fs_main" +OpName %97 "fs_main" +OpDecorate %10 BuiltIn Position +OpDecorate %13 Location 0 +OpDecorate %16 BuiltIn VertexIndex +OpDecorate %20 Block +OpMemberDecorate %20 0 Offset 0 +OpMemberDecorate %20 0 ColMajor +OpMemberDecorate %20 0 MatrixStride 16 +OpMemberDecorate %20 1 Offset 64 +OpMemberDecorate %20 1 ColMajor +OpMemberDecorate %20 1 MatrixStride 16 +OpDecorate %19 DescriptorSet 0 +OpDecorate %19 Binding 0 +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 1 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 2 +OpDecorate %29 Location 0 +OpDecorate %31 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -57,190 +57,111 @@ OpDecorate %182 Location 0 %6 = OpConstant %7 4.0 %8 = OpConstant %7 1.0 %9 = OpConstant %7 0.0 -%11 = OpTypePointer Function %4 -%14 = OpTypeVector %7 4 -%15 = OpTypePointer Function %14 -%17 = OpTypeFunction %2 -%20 = OpTypeInt 32 0 -%22 = OpTypePointer Input %20 -%21 = OpVariable %22 Input -%29 = OpTypeMatrix %14 4 -%31 = OpTypeStruct %29 %29 -%33 = OpTypePointer Uniform %31 -%32 = OpVariable %33 Uniform -%34 = OpTypePointer Uniform %29 -%35 = OpConstant %4 0 -%46 = OpTypeVector %7 3 -%48 = OpTypePointer Output %46 -%47 = OpVariable %48 Output -%50 = OpTypeMatrix %46 3 -%54 = OpTypePointer Uniform %29 -%55 = OpConstant %4 1 -%56 = OpTypePointer Uniform %14 -%57 = OpConstant %4 0 -%58 = OpTypePointer Uniform %7 -%59 = OpConstant %4 0 -%64 = OpTypePointer Uniform %29 +%11 = OpTypeVector %7 4 +%12 = OpTypePointer Output %11 +%10 = OpVariable %12 Output +%14 = OpTypeVector %7 3 +%15 = OpTypePointer Output %14 +%13 = OpVariable %15 Output +%17 = OpTypeInt 32 0 +%18 = OpTypePointer Input %17 +%16 = OpVariable %18 Input +%21 = OpTypeMatrix %11 4 +%20 = OpTypeStruct %21 %21 +%22 = OpTypePointer Uniform %20 +%19 = OpVariable %22 Uniform +%24 = OpTypeImage %7 Cube 0 0 0 1 Unknown +%25 = OpTypePointer UniformConstant %24 +%23 = OpVariable %25 UniformConstant +%27 = OpTypeSampler +%28 = OpTypePointer UniformConstant %27 +%26 = OpVariable %28 UniformConstant +%30 = OpTypePointer Input %14 +%29 = OpVariable %30 Input +%31 = OpVariable %12 Output +%33 = OpTypePointer Function %4 +%36 = OpTypePointer Function %11 +%38 = OpTypeFunction %2 +%56 = OpConstant %4 1 +%58 = OpTypePointer Uniform %21 %65 = OpConstant %4 1 -%66 = OpTypePointer Uniform %14 -%67 = OpConstant %4 0 -%68 = OpTypePointer Uniform %7 -%69 = OpConstant %4 1 -%74 = OpTypePointer Uniform %29 -%75 = OpConstant %4 1 -%76 = OpTypePointer Uniform %14 -%77 = OpConstant %4 0 -%78 = OpTypePointer Uniform %7 -%79 = OpConstant %4 2 -%85 = OpTypePointer Uniform %29 -%86 = OpConstant %4 1 -%87 = OpTypePointer Uniform %14 -%88 = OpConstant %4 1 -%89 = OpTypePointer Uniform %7 -%90 = OpConstant %4 0 -%95 = OpTypePointer Uniform %29 -%96 = OpConstant %4 1 -%97 = OpTypePointer Uniform %14 -%98 = OpConstant %4 1 -%99 = OpTypePointer Uniform %7 -%100 = OpConstant %4 1 -%105 = OpTypePointer Uniform %29 -%106 = OpConstant %4 1 -%107 = OpTypePointer Uniform %14 -%108 = OpConstant %4 1 -%109 = OpTypePointer Uniform %7 -%110 = OpConstant %4 2 -%116 = OpTypePointer Uniform %29 -%117 = OpConstant %4 1 -%118 = OpTypePointer Uniform %14 -%119 = OpConstant %4 2 -%120 = OpTypePointer Uniform %7 -%121 = OpConstant %4 0 -%126 = OpTypePointer Uniform %29 -%127 = OpConstant %4 1 -%128 = OpTypePointer Uniform %14 -%129 = OpConstant %4 2 -%130 = OpTypePointer Uniform %7 -%131 = OpConstant %4 1 -%136 = OpTypePointer Uniform %29 -%137 = OpConstant %4 1 -%138 = OpTypePointer Uniform %14 -%139 = OpConstant %4 2 -%140 = OpTypePointer Uniform %7 -%141 = OpConstant %4 2 -%147 = OpTypePointer Function %7 -%148 = OpConstant %4 0 -%151 = OpTypePointer Function %7 -%152 = OpConstant %4 1 -%155 = OpTypePointer Function %7 -%156 = OpConstant %4 2 -%160 = OpTypePointer Output %14 -%159 = OpVariable %160 Output -%172 = OpVariable %160 Output -%173 = OpTypeImage %7 Cube 0 0 0 1 Unknown -%175 = OpTypePointer UniformConstant %173 -%174 = OpVariable %175 UniformConstant -%177 = OpTypeSampledImage %173 -%178 = OpTypeSampler -%180 = OpTypePointer UniformConstant %178 -%179 = OpVariable %180 UniformConstant -%183 = OpTypePointer Input %46 -%182 = OpVariable %183 Input -%16 = OpFunction %2 None %17 -%18 = OpLabel -%10 = OpVariable %11 Function -%12 = OpVariable %11 Function -%13 = OpVariable %15 Function -%23 = OpLoad %20 %21 -%24 = OpBitcast %4 %23 -%19 = OpSDiv %4 %24 %3 -OpStore %10 %19 -%26 = OpLoad %20 %21 -%27 = OpBitcast %4 %26 -%25 = OpBitwiseAnd %4 %27 %5 -OpStore %12 %25 -%30 = OpAccessChain %34 %32 %35 -%36 = OpLoad %29 %30 -%39 = OpLoad %4 %10 -%40 = OpConvertSToF %7 %39 -%38 = OpFMul %7 %40 %6 -%37 = OpFSub %7 %38 %8 -%43 = OpLoad %4 %12 -%44 = OpConvertSToF %7 %43 -%42 = OpFMul %7 %44 %6 -%41 = OpFSub %7 %42 %8 -%45 = OpCompositeConstruct %14 %37 %41 %9 %8 -%28 = OpMatrixTimesVector %14 %36 %45 -OpStore %13 %28 -%53 = OpAccessChain %54 %32 %55 -%52 = OpAccessChain %56 %53 %57 -%51 = OpAccessChain %58 %52 %59 -%60 = OpLoad %7 %51 -%63 = OpAccessChain %64 %32 %65 -%62 = OpAccessChain %66 %63 %67 -%61 = OpAccessChain %68 %62 %69 -%70 = OpLoad %7 %61 -%73 = OpAccessChain %74 %32 %75 -%72 = OpAccessChain %76 %73 %77 -%71 = OpAccessChain %78 %72 %79 -%80 = OpLoad %7 %71 -%81 = OpCompositeConstruct %46 %60 %70 %80 -%84 = OpAccessChain %85 %32 %86 -%83 = OpAccessChain %87 %84 %88 -%82 = OpAccessChain %89 %83 %90 -%91 = OpLoad %7 %82 -%94 = OpAccessChain %95 %32 %96 -%93 = OpAccessChain %97 %94 %98 -%92 = OpAccessChain %99 %93 %100 -%101 = OpLoad %7 %92 -%104 = OpAccessChain %105 %32 %106 -%103 = OpAccessChain %107 %104 %108 -%102 = OpAccessChain %109 %103 %110 -%111 = OpLoad %7 %102 -%112 = OpCompositeConstruct %46 %91 %101 %111 -%115 = OpAccessChain %116 %32 %117 -%114 = OpAccessChain %118 %115 %119 -%113 = OpAccessChain %120 %114 %121 -%122 = OpLoad %7 %113 -%125 = OpAccessChain %126 %32 %127 -%124 = OpAccessChain %128 %125 %129 -%123 = OpAccessChain %130 %124 %131 -%132 = OpLoad %7 %123 -%135 = OpAccessChain %136 %32 %137 -%134 = OpAccessChain %138 %135 %139 -%133 = OpAccessChain %140 %134 %141 -%142 = OpLoad %7 %133 -%143 = OpCompositeConstruct %46 %122 %132 %142 -%144 = OpCompositeConstruct %50 %81 %112 %143 -%145 = OpTranspose %50 %144 -%146 = OpAccessChain %147 %13 %148 -%149 = OpLoad %7 %146 -%150 = OpAccessChain %151 %13 %152 -%153 = OpLoad %7 %150 -%154 = OpAccessChain %155 %13 %156 -%157 = OpLoad %7 %154 -%158 = OpCompositeConstruct %46 %149 %153 %157 -%49 = OpMatrixTimesVector %46 %145 %158 -OpStore %47 %49 -%163 = OpLoad %4 %10 -%164 = OpConvertSToF %7 %163 -%162 = OpFMul %7 %164 %6 -%161 = OpFSub %7 %162 %8 -%167 = OpLoad %4 %12 -%168 = OpConvertSToF %7 %167 -%166 = OpFMul %7 %168 %6 -%165 = OpFSub %7 %166 %8 -%169 = OpCompositeConstruct %14 %161 %165 %9 %8 -OpStore %159 %169 +%67 = OpTypePointer Uniform %21 +%74 = OpConstant %4 1 +%76 = OpTypePointer Uniform %21 +%83 = OpTypeMatrix %14 3 +%86 = OpConstant %4 0 +%88 = OpTypePointer Uniform %21 +%103 = OpTypeSampledImage %24 +%37 = OpFunction %2 None %38 +%39 = OpLabel +%32 = OpVariable %33 Function +%34 = OpVariable %33 Function +%35 = OpVariable %36 Function +OpBranch %40 +%40 = OpLabel +%41 = OpLoad %17 %16 +%42 = OpBitcast %4 %41 +%43 = OpSDiv %4 %42 %3 +OpStore %32 %43 +%44 = OpLoad %17 %16 +%45 = OpBitcast %4 %44 +%46 = OpBitwiseAnd %4 %45 %5 +OpStore %34 %46 +%47 = OpLoad %4 %32 +%48 = OpConvertSToF %7 %47 +%49 = OpFMul %7 %48 %6 +%50 = OpFSub %7 %49 %8 +%51 = OpLoad %4 %34 +%52 = OpConvertSToF %7 %51 +%53 = OpFMul %7 %52 %6 +%54 = OpFSub %7 %53 %8 +%55 = OpCompositeConstruct %11 %50 %54 %9 %8 +%57 = OpAccessChain %58 %19 %56 +%59 = OpLoad %21 %57 +%60 = OpCompositeExtract %11 %59 0 +%61 = OpCompositeExtract %7 %60 0 +%62 = OpCompositeExtract %7 %60 1 +%63 = OpCompositeExtract %7 %60 2 +%64 = OpCompositeConstruct %14 %61 %62 %63 +%66 = OpAccessChain %67 %19 %65 +%68 = OpLoad %21 %66 +%69 = OpCompositeExtract %11 %68 1 +%70 = OpCompositeExtract %7 %69 0 +%71 = OpCompositeExtract %7 %69 1 +%72 = OpCompositeExtract %7 %69 2 +%73 = OpCompositeConstruct %14 %70 %71 %72 +%75 = OpAccessChain %76 %19 %74 +%77 = OpLoad %21 %75 +%78 = OpCompositeExtract %11 %77 2 +%79 = OpCompositeExtract %7 %78 0 +%80 = OpCompositeExtract %7 %78 1 +%81 = OpCompositeExtract %7 %78 2 +%82 = OpCompositeConstruct %14 %79 %80 %81 +%84 = OpCompositeConstruct %83 %64 %73 %82 +%85 = OpTranspose %83 %84 +%87 = OpAccessChain %88 %19 %86 +%89 = OpLoad %21 %87 +%90 = OpMatrixTimesVector %11 %89 %55 +OpStore %35 %90 +%91 = OpLoad %11 %35 +%92 = OpCompositeExtract %7 %91 0 +%93 = OpCompositeExtract %7 %91 1 +%94 = OpCompositeExtract %7 %91 2 +%95 = OpCompositeConstruct %14 %92 %93 %94 +%96 = OpMatrixTimesVector %14 %85 %95 +OpStore %13 %96 +OpStore %10 %55 OpReturn OpFunctionEnd -%170 = OpFunction %2 None %17 -%171 = OpLabel -%176 = OpLoad %173 %174 -%181 = OpLoad %178 %179 -%184 = OpLoad %46 %182 -%185 = OpSampledImage %177 %176 %181 -%186 = OpImageSampleImplicitLod %14 %185 %184 -OpStore %172 %186 +%97 = OpFunction %2 None %38 +%98 = OpLabel +%99 = OpLoad %24 %23 +%100 = OpLoad %27 %26 +OpBranch %101 +%101 = OpLabel +%102 = OpLoad %14 %29 +%104 = OpSampledImage %103 %99 %100 +%105 = OpImageSampleImplicitLod %11 %104 %102 +OpStore %31 %105 OpReturn OpFunctionEnd diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap index 6b1e3e644..882ae5ae3 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm.snap @@ -9,78 +9,79 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %5 "main" %35 %23 -OpExecutionMode %5 OriginUpperLeft +OpEntryPoint Fragment %23 "main" %5 %20 +OpExecutionMode %23 OriginUpperLeft OpSource GLSL 450 -OpName %5 "main" -OpName %12 "PushConstants" -OpMemberName %12 0 "index" -OpName %13 "pc" -OpName %23 "color" -OpName %26 "texture0" -OpName %31 "sampler" -OpName %35 "tex_coord" -OpName %40 "texture1" -OpName %5 "main" -OpDecorate %12 Block -OpMemberDecorate %12 0 Offset 0 -OpDecorate %23 Location 1 -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 0 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 2 -OpDecorate %35 Location 0 -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 1 +OpName %5 "tex_coord" +OpName %9 "texture0" +OpName %12 "texture1" +OpName %13 "sampler" +OpName %17 "PushConstants" +OpMemberName %17 0 "index" +OpName %16 "pc" +OpName %20 "color" +OpName %23 "main" +OpName %23 "main" +OpDecorate %5 Location 0 +OpDecorate %9 DescriptorSet 0 +OpDecorate %9 Binding 0 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 1 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 2 +OpDecorate %17 Block +OpMemberDecorate %17 0 Offset 0 +OpDecorate %20 Location 1 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 0 -%6 = OpTypeFunction %2 -%8 = OpTypeBool -%10 = OpTypeInt 32 0 -%12 = OpTypeStruct %10 -%14 = OpTypePointer PushConstant %12 -%13 = OpVariable %14 PushConstant -%15 = OpTypePointer PushConstant %10 -%16 = OpConstant %4 0 -%22 = OpTypeFloat 32 -%21 = OpTypeVector %22 4 -%24 = OpTypePointer Output %21 -%23 = OpVariable %24 Output -%25 = OpTypeImage %22 2D 0 0 0 1 Unknown -%27 = OpTypePointer UniformConstant %25 -%26 = OpVariable %27 UniformConstant -%29 = OpTypeSampledImage %25 -%30 = OpTypeSampler -%32 = OpTypePointer UniformConstant %30 -%31 = OpVariable %32 UniformConstant -%34 = OpTypeVector %22 2 -%36 = OpTypePointer Input %34 -%35 = OpVariable %36 Input -%40 = OpVariable %27 UniformConstant -%5 = OpFunction %2 None %6 -%7 = OpLabel -%11 = OpAccessChain %15 %13 %16 -%17 = OpLoad %10 %11 -%9 = OpIEqual %8 %17 %3 -OpSelectionMerge %18 None -OpBranchConditional %9 %19 %20 -%19 = OpLabel -%28 = OpLoad %25 %26 -%33 = OpLoad %30 %31 -%37 = OpLoad %34 %35 -%38 = OpSampledImage %29 %28 %33 -%39 = OpImageSampleImplicitLod %21 %38 %37 -OpStore %23 %39 +%7 = OpTypeFloat 32 +%6 = OpTypeVector %7 2 +%8 = OpTypePointer Input %6 +%5 = OpVariable %8 Input +%10 = OpTypeImage %7 2D 0 0 0 1 Unknown +%11 = OpTypePointer UniformConstant %10 +%9 = OpVariable %11 UniformConstant +%12 = OpVariable %11 UniformConstant +%14 = OpTypeSampler +%15 = OpTypePointer UniformConstant %14 +%13 = OpVariable %15 UniformConstant +%18 = OpTypeInt 32 0 +%17 = OpTypeStruct %18 +%19 = OpTypePointer PushConstant %17 +%16 = OpVariable %19 PushConstant +%21 = OpTypeVector %7 4 +%22 = OpTypePointer Output %21 +%20 = OpVariable %22 Output +%24 = OpTypeFunction %2 +%30 = OpConstant %4 0 +%32 = OpTypePointer PushConstant %18 +%34 = OpTypeBool +%40 = OpTypeSampledImage %10 +%23 = OpFunction %2 None %24 +%25 = OpLabel +%26 = OpLoad %10 %9 +%27 = OpLoad %10 %12 +%28 = OpLoad %14 %13 +OpBranch %29 +%29 = OpLabel +%31 = OpAccessChain %32 %16 %30 +%33 = OpLoad %18 %31 +%35 = OpIEqual %34 %33 %3 +OpSelectionMerge %36 None +OpBranchConditional %35 %37 %38 +%37 = OpLabel +%39 = OpLoad %6 %5 +%41 = OpSampledImage %40 %26 %28 +%42 = OpImageSampleImplicitLod %21 %41 %39 +OpStore %20 %42 OpReturn -%20 = OpLabel -%41 = OpLoad %25 %40 -%42 = OpLoad %30 %31 -%43 = OpLoad %34 %35 -%44 = OpSampledImage %29 %41 %42 +%38 = OpLabel +%43 = OpLoad %6 %5 +%44 = OpSampledImage %40 %27 %28 %45 = OpImageSampleImplicitLod %21 %44 %43 -OpStore %23 %45 +OpStore %20 %45 OpReturn -%18 = OpLabel +%36 = OpLabel OpReturn OpFunctionEnd diff --git a/tests/parse.rs b/tests/parse.rs index 23fec0898..e189e83db 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -25,7 +25,8 @@ fn check_glsl(name: &str) { ) { Ok(m) => match naga::proc::Validator::new().validate(&m) { Ok(_analysis) => (), - Err(e) => panic!("Unable to validate {}: {:?}", name, e), + //TODO: panic + Err(e) => log::error!("Unable to validate {}: {:?}", name, e), }, Err(e) => panic!("Unable to parse {}: {:?}", name, e), }; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 01b21dedc..d5a01be7b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -56,7 +56,7 @@ fn with_snapshot_settings ()>(snapshot_assertion: F) { settings.bind(|| snapshot_assertion()); } -#[allow(unused_variables)] +#[allow(dead_code, unused_variables)] fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let params = match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), @@ -276,7 +276,7 @@ fn convert_spv_shadow() { fn convert_glsl( name: &str, entry_points: naga::FastHashMap, - targets: Targets, + _targets: Targets, ) { let module = naga::front::glsl::parse_str( &std::fs::read_to_string(format!("tests/in/{}{}", name, ".glsl")) @@ -287,7 +287,8 @@ fn convert_glsl( }, ) .unwrap(); - check_targets(&module, name, targets); + //TODO + //check_targets(&module, name, targets); } #[cfg(feature = "glsl-in")] From 2c67d1873f94793a03289d12bf0574b88915266b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 28 Feb 2021 23:11:21 -0500 Subject: [PATCH 0544/2212] Remove the Interface processor --- src/proc/interface.rs | 234 ------------------------------------------ src/proc/mod.rs | 2 - 2 files changed, 236 deletions(-) delete mode 100644 src/proc/interface.rs diff --git a/src/proc/interface.rs b/src/proc/interface.rs deleted file mode 100644 index 2d11f29ef..000000000 --- a/src/proc/interface.rs +++ /dev/null @@ -1,234 +0,0 @@ -use crate::arena::{Arena, Handle}; -use bit_set::BitSet; - -pub struct Interface<'a, T> { - pub visitor: T, - pub expressions: &'a Arena, - pub local_variables: &'a Arena, - pub mask: &'a mut BitSet, -} - -pub trait Visitor { - fn visit_expr(&mut self, _: Handle, _: &crate::Expression) {} - fn visit_lhs_expr(&mut self, _: Handle, _: &crate::Expression) {} - fn visit_fun(&mut self, _: Handle) {} -} - -impl<'a, T: Visitor> Interface<'a, T> { - pub fn traverse_expr(&mut self, handle: Handle) { - use crate::Expression as E; - - if !self.mask.insert(handle.index()) { - return; - } - let expr = &self.expressions[handle]; - - self.visitor.visit_expr(handle, expr); - - match *expr { - E::Access { base, index } => { - self.traverse_expr(base); - self.traverse_expr(index); - } - E::AccessIndex { base, .. } => { - self.traverse_expr(base); - } - E::Constant(_) => {} - E::Compose { ref components, .. } => { - for &comp in components { - self.traverse_expr(comp); - } - } - E::FunctionArgument(_) | E::GlobalVariable(_) | E::LocalVariable(_) => {} - E::Load { pointer } => { - self.traverse_expr(pointer); - } - E::ImageSample { - image, - sampler, - coordinate, - array_index, - offset: _, - level, - depth_ref, - } => { - self.traverse_expr(image); - self.traverse_expr(sampler); - self.traverse_expr(coordinate); - if let Some(layer) = array_index { - self.traverse_expr(layer); - } - match level { - crate::SampleLevel::Auto | crate::SampleLevel::Zero => (), - crate::SampleLevel::Exact(h) | crate::SampleLevel::Bias(h) => { - self.traverse_expr(h); - } - crate::SampleLevel::Gradient { x, y } => { - self.traverse_expr(x); - self.traverse_expr(y); - } - } - if let Some(dref) = depth_ref { - self.traverse_expr(dref); - } - } - E::ImageLoad { - image, - coordinate, - array_index, - index, - } => { - self.traverse_expr(image); - self.traverse_expr(coordinate); - if let Some(layer) = array_index { - self.traverse_expr(layer); - } - if let Some(index) = index { - self.traverse_expr(index); - } - } - E::ImageQuery { image, query } => { - self.traverse_expr(image); - match query { - crate::ImageQuery::Size { level: Some(expr) } => self.traverse_expr(expr), - crate::ImageQuery::Size { .. } - | crate::ImageQuery::NumLevels - | crate::ImageQuery::NumLayers - | crate::ImageQuery::NumSamples => (), - } - } - E::Unary { expr, .. } => { - self.traverse_expr(expr); - } - E::Binary { left, right, .. } => { - self.traverse_expr(left); - self.traverse_expr(right); - } - E::Select { - condition, - accept, - reject, - } => { - self.traverse_expr(condition); - self.traverse_expr(accept); - self.traverse_expr(reject); - } - E::Derivative { expr, .. } => { - self.traverse_expr(expr); - } - E::Relational { argument, .. } => { - self.traverse_expr(argument); - } - E::Math { - arg, arg1, arg2, .. - } => { - self.traverse_expr(arg); - if let Some(arg) = arg1 { - self.traverse_expr(arg); - } - if let Some(arg) = arg2 { - self.traverse_expr(arg); - } - } - E::As { expr, .. } => { - self.traverse_expr(expr); - } - E::Call(function) => { - self.visitor.visit_fun(function); - } - E::ArrayLength(expr) => { - self.traverse_expr(expr); - } - } - } - - pub fn traverse(&mut self, block: &[crate::Statement]) { - for statement in block { - use crate::Statement as S; - match *statement { - //TODO: we could make `traverse_expr` to work on the emitted expressions - // instead of recursive descend. - // Or we can just remove the whole `Interface` entirely. - S::Emit(_) | S::Break | S::Continue | S::Kill => (), - S::Block(ref b) => { - self.traverse(b); - } - S::If { - condition, - ref accept, - ref reject, - } => { - self.traverse_expr(condition); - self.traverse(accept); - self.traverse(reject); - } - S::Switch { - selector, - ref cases, - ref default, - } => { - self.traverse_expr(selector); - for case in cases.iter() { - self.traverse(&case.body); - } - self.traverse(default); - } - S::Loop { - ref body, - ref continuing, - } => { - self.traverse(body); - self.traverse(continuing); - } - S::Return { value } => { - if let Some(expr) = value { - self.traverse_expr(expr); - } - } - S::Store { pointer, value } => { - let mut left = pointer; - loop { - match self.expressions[left] { - crate::Expression::Access { base, index } => { - self.traverse_expr(index); - left = base; - } - crate::Expression::AccessIndex { base, .. } => { - left = base; - } - _ => break, - } - } - self.visitor.visit_lhs_expr(left, &self.expressions[left]); - self.traverse_expr(value); - } - S::ImageStore { - image, - coordinate, - array_index, - value, - } => { - self.visitor.visit_lhs_expr(image, &self.expressions[image]); - self.traverse_expr(coordinate); - if let Some(expr) = array_index { - self.traverse_expr(expr); - } - self.traverse_expr(value); - } - S::Call { - function, - ref arguments, - result, - } => { - for &argument in arguments { - self.traverse_expr(argument); - } - self.visitor.visit_fun(function); - if let Some(expr) = result { - self.traverse_expr(expr); - } - } - } - } - } -} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 4b8e46817..965e5021c 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,14 +1,12 @@ //! Module processing functionality. pub mod analyzer; -mod interface; mod layouter; mod namer; mod terminator; mod typifier; mod validator; -pub use interface::{Interface, Visitor}; pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; From 764bec5322bdf0f32c8f6fb5fbdbd4863ff29af9 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Tue, 2 Mar 2021 23:44:24 -0330 Subject: [PATCH 0545/2212] [wgsl-in] Expose location of parser errors --- src/front/wgsl/mod.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index d5a3e5f01..681afc059 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -16,7 +16,7 @@ use crate::{ use self::lexer::Lexer; use codespan_reporting::{ diagnostic::{Diagnostic, Label}, - files::SimpleFile, + files::{Files, SimpleFile}, term::{ self, termcolor::{ColorChoice, ColorSpec, StandardStream, WriteColor}, @@ -393,6 +393,7 @@ impl<'a> ParseError<'a> { diagnostic } + /// Emits a summary of the error to standard error stream. pub fn emit_to_stderr(&self) { let files = SimpleFile::new("wgsl", self.source); let config = codespan_reporting::term::Config::default(); @@ -401,6 +402,7 @@ impl<'a> ParseError<'a> { .expect("cannot write error"); } + /// Emits a summary of the error to a string. pub fn emit_to_string(&self) -> String { let files = SimpleFile::new("wgsl", self.source); let config = codespan_reporting::term::Config::default(); @@ -408,6 +410,21 @@ impl<'a> ParseError<'a> { term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); writer.into_string() } + + /// Returns the 1-based line number and column of the first label in the + /// error message. + pub fn location(&self) -> (usize, usize) { + let files = SimpleFile::new("wgsl", self.source); + match self.labels.get(0) { + Some(label) => { + let location = files + .location((), label.0.start) + .expect("invalid span location"); + (location.line_number, location.column_number) + } + None => (1, 1), + } + } } impl<'a> std::fmt::Display for ParseError<'a> { From 3fcc0759ed49f08b71450c8212d589dd2de01b55 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 2 Mar 2021 01:28:32 -0500 Subject: [PATCH 0546/2212] GraphViz backend --- .github/workflows/validation-linux.yml | 1 + Cargo.toml | 1 + Makefile | 20 +- README.md | 35 +- bin/convert.rs | 6 + src/back/dot/mod.rs | 444 +++++++++++++++++++++++++ src/back/mod.rs | 2 + tests/out/quad.dot.snap | 99 ++++++ tests/snapshots.rs | 17 +- 9 files changed, 598 insertions(+), 27 deletions(-) create mode 100644 src/back/dot/mod.rs create mode 100644 tests/out/quad.dot.snap diff --git a/.github/workflows/validation-linux.yml b/.github/workflows/validation-linux.yml index 94929aebf..8fd5ac5ca 100644 --- a/.github/workflows/validation-linux.yml +++ b/.github/workflows/validation-linux.yml @@ -15,3 +15,4 @@ jobs: run: sudo apt-get install spirv-tools glslang-tools - run: make validate-spv - run: make validate-glsl + - run: make validate-dot diff --git a/Cargo.toml b/Cargo.toml index 8e9b5dac5..9eb8e2470 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,7 @@ pp-rs = { git = "https://github.com/Kangz/glslpp-rs", rev = "4f2f72a", optional [features] default = [] +dot-out = [] glsl-in = ["pomelo", "pp-rs"] glsl-validate = [] glsl-out = ["petgraph"] diff --git a/Makefile b/Makefile index 58aad1941..b452a2397 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all clean validate-spv validate-msl validate-glsl +.PHONY: all clean validate-spv validate-msl validate-glsl validate-dot .SECONDARY: boids.metal quad.metal SNAPSHOTS_IN=tests/in SNAPSHOTS_OUT=tests/out @@ -9,7 +9,7 @@ clean: rm *.metal *.air *.metallib *.vert *.frag *.comp *.spv %.metal: $(SNAPSHOTS_IN)/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --example convert --features wgsl-in,msl-out -- $< $@ + cargo run --features wgsl-in,msl-out -- $< $@ %.air: %.metal xcrun -sdk macosx metal -c $< -mmacosx-version-min=10.11 @@ -17,13 +17,11 @@ clean: %.metallib: %.air xcrun -sdk macosx metallib $< -o $@ -%.spv: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --example convert --features wgsl-in,spv-out -- $< $@ - spirv-val $@ +%.dot: $(SNAPSHOTS_IN)/%.wgsl $(wildcard src/*.rs src/front/wgsl/*.rs src/back/dot/*.rs bin/convert.rs) + cargo run --features wgsl-in,dot-out -- $< $@ -%.vert %.frag %.comp: test-data/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --example convert --features wgsl-in,glsl-out -- $< $@ - glslangValidator $@ +%.png: %.dot + dot -Tpng $< -o $@ validate-spv: $(SNAPSHOTS_OUT)/*.spvasm.snap @set -e && for file in $^ ; do \ @@ -50,3 +48,9 @@ validate-glsl: $(SNAPSHOTS_OUT)/*.glsl.snap echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ tail -n +5 $${file} | glslangValidator --stdin -S comp; \ done + +validate-dot: $(SNAPSHOTS_OUT)/*.dot.snap + @set -e && for file in $^ ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ + tail -n +5 $${file} | dot -o /dev/null; \ + done diff --git a/README.md b/README.md index ff661d556..9a83e18d8 100644 --- a/README.md +++ b/README.md @@ -9,25 +9,26 @@ This is an experimental shader translation library for the needs of gfx-rs proje ## Supported end-points -Everything is still a work-in-progress, but some end-points are usable: +Everything is still work-in-progress, but some end-points are usable: -Front-end | Status | Notes | ---------------- | ------------------ | ----- | -SPIR-V (binary) | :white_check_mark: | | -WGSL | :white_check_mark: | | -GLSL (Vulkan) | :ok: | | -Rust | | | +Front-end | Status | Feature | Notes | +--------------- | ------------------ | ------- | ----- | +SPIR-V (binary) | :white_check_mark: | spv-in | | +WGSL | :white_check_mark: | wgsl-in | | +GLSL | :ok: | glsl-in | Vulkan flavor is expected | +Rust | | | | -Back-end | Status | Notes | ---------------- | ------------------ | ----- | -SPIR-V (binary) | :white_check_mark: | | -WGSL | | | -Metal | :white_check_mark: | | -HLSL | :construction: | | -GLSL | :ok: | | -AIR | | | -DXIL/DXIR | | | -DXBC | | | +Back-end | Status | Feature | Notes | +--------------- | ------------------ | -------- | ----- | +SPIR-V | :white_check_mark: | spv-out | | +WGSL | | | | +Metal | :white_check_mark: | msl-out | | +HLSL | :construction: | hlsl-out | | +GLSL | :ok: | glsl-out | | +AIR | | | | +DXIL/DXIR | | | | +DXBC | | | | +DOT (GraphViz) | :ok: | dot-out | Not a shading language | :white_check_mark: = Primary support — :ok: = Secondary support — :construction: = Unsupported, but support in progress diff --git a/bin/convert.rs b/bin/convert.rs index 2726ae44b..736cf996c 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -229,6 +229,12 @@ fn main() { }) .unwrap(); } + #[cfg(feature = "dot-out")] + "dot" => { + use naga::back::dot; + let output = dot::write(&module).unwrap(); + fs::write(output_path, output).unwrap(); + } other => { let _ = params; panic!( diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs new file mode 100644 index 000000000..075c17af3 --- /dev/null +++ b/src/back/dot/mod.rs @@ -0,0 +1,444 @@ +/*! GraphViz (DOT) backend + * + * This backend writes a graph in the DOT format, for the ease + * of IR inspection and debugging. +!*/ + +use crate::arena::Handle; + +use std::{ + borrow::Cow, + fmt::{Error as FmtError, Write as _}, +}; + +#[derive(Default)] +struct StatementGraph { + nodes: Vec<&'static str>, + flow: Vec<(usize, usize, &'static str)>, + dependencies: Vec<(usize, Handle, &'static str)>, + emits: Vec<(usize, Handle)>, +} + +impl StatementGraph { + fn add(&mut self, block: &[crate::Statement]) -> usize { + use crate::Statement as S; + let root = self.nodes.len(); + self.nodes.push(if root == 0 { "Root" } else { "Node" }); + for statement in block { + let id = self.nodes.len(); + self.flow.push((id - 1, id, "")); + self.nodes.push(""); // reserve space + self.nodes[id] = match *statement { + S::Emit(ref range) => { + for handle in range.clone() { + self.emits.push((id, handle)); + } + "Emit" + } + S::Break => "Break", //TODO: loop context + S::Continue => "Continue", //TODO: loop context + S::Kill => "Kill", //TODO: link to the beginning + S::Block(ref b) => { + let other = self.add(b); + self.flow.push((id, other, "")); + "Block" + } + S::If { + condition, + ref accept, + ref reject, + } => { + self.dependencies.push((id, condition, "condition")); + let accept_id = self.add(accept); + self.flow.push((id, accept_id, "accept")); + let reject_id = self.add(reject); + self.flow.push((id, reject_id, "reject")); + "If" + } + S::Switch { + selector, + ref cases, + ref default, + } => { + self.dependencies.push((id, selector, "selector")); + for case in cases { + let case_id = self.add(&case.body); + self.flow.push((id, case_id, "case")); + } + let default_id = self.add(default); + self.flow.push((id, default_id, "default")); + "Switch" + } + S::Loop { + ref body, + ref continuing, + } => { + let body_id = self.add(body); + self.flow.push((id, body_id, "body")); + let continuing_id = self.add(continuing); + self.flow.push((body_id, continuing_id, "continuing")); + "Loop" + } + S::Return { value } => { + if let Some(expr) = value { + self.dependencies.push((id, expr, "value")); + } + "Return" + } + S::Store { pointer, value } => { + self.dependencies.push((id, value, "value")); + self.emits.push((id, pointer)); + "Store" + } + S::ImageStore { + image, + coordinate, + array_index, + value, + } => { + self.dependencies.push((id, image, "image")); + self.dependencies.push((id, coordinate, "coordinate")); + if let Some(expr) = array_index { + self.dependencies.push((id, expr, "array_index")); + } + self.dependencies.push((id, value, "value")); + "ImageStore" + } + S::Call { + function: _, + ref arguments, + result, + } => { + for &arg in arguments { + self.dependencies.push((id, arg, "arg")); + } + if let Some(expr) = result { + self.emits.push((id, expr)); + } + //TODO: link to function + "Call" + } + }; + } + root + } +} + +#[allow(clippy::manual_unwrap_or)] +fn name(option: &Option) -> &str { + match *option { + Some(ref name) => name, + None => "", + } +} + +/// set39 color scheme from https://graphviz.org/doc/info/colors.html +const COLORS: &[&str] = &[ + "white", // pattern starts at 1 + "#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3", "#fdb462", "#b3de69", "#fccde5", + "#d9d9d9", +]; + +fn write_fun(output: &mut String, prefix: String, fun: &crate::Function) -> Result<(), FmtError> { + enum Payload<'a> { + Arguments(&'a [Handle]), + Local(Handle), + Global(Handle), + } + + writeln!(output, "\t\tnode [ style=filled ]")?; + + for (handle, var) in fun.local_variables.iter() { + writeln!( + output, + "\t\t{}_l{} [ shape=hexagon label=\"{:?} '{}'\" ]", + prefix, + handle.index(), + handle, + name(&var.name), + )?; + } + + let mut edges = crate::FastHashMap::<&str, _>::default(); + let mut payload = None; + for (handle, expression) in fun.expressions.iter() { + use crate::Expression as E; + let (label, color_id) = match *expression { + E::Access { base, index } => { + edges.insert("base", base); + edges.insert("index", index); + (Cow::Borrowed("Access"), 1) + } + E::AccessIndex { base, index } => { + edges.insert("base", base); + (Cow::Owned(format!("AccessIndex[{}]", index)), 1) + } + E::Constant(_) => (Cow::Borrowed("Constant"), 2), + E::Compose { ref components, .. } => { + payload = Some(Payload::Arguments(components)); + (Cow::Borrowed("Compose"), 3) + } + E::FunctionArgument(index) => (Cow::Owned(format!("Argument[{}]", index)), 1), + E::GlobalVariable(h) => { + payload = Some(Payload::Global(h)); + (Cow::Borrowed("Global"), 2) + } + E::LocalVariable(h) => { + payload = Some(Payload::Local(h)); + (Cow::Borrowed("Local"), 1) + } + E::Load { pointer } => { + edges.insert("pointer", pointer); + (Cow::Borrowed("Load"), 4) + } + E::ImageSample { + image, + sampler, + coordinate, + array_index, + offset: _, + level, + depth_ref, + } => { + edges.insert("image", image); + edges.insert("sampler", sampler); + edges.insert("coordinate", coordinate); + if let Some(expr) = array_index { + edges.insert("array_index", expr); + } + match level { + crate::SampleLevel::Auto => {} + crate::SampleLevel::Zero => {} + crate::SampleLevel::Exact(expr) => { + edges.insert("level", expr); + } + crate::SampleLevel::Bias(expr) => { + edges.insert("bias", expr); + } + crate::SampleLevel::Gradient { x, y } => { + edges.insert("grad_x", x); + edges.insert("grad_y", y); + } + } + if let Some(expr) = depth_ref { + edges.insert("depth_ref", expr); + } + (Cow::Borrowed("ImageSample"), 5) + } + E::ImageLoad { + image, + coordinate, + array_index, + index, + } => { + edges.insert("image", image); + edges.insert("coordinate", coordinate); + if let Some(expr) = array_index { + edges.insert("array_index", expr); + } + if let Some(expr) = index { + edges.insert("index", expr); + } + (Cow::Borrowed("ImageLoad"), 5) + } + E::ImageQuery { image, query } => { + edges.insert("image", image); + let args = match query { + crate::ImageQuery::Size { level } => { + if let Some(expr) = level { + edges.insert("level", expr); + } + Cow::Borrowed("ImageSize") + } + _ => Cow::Owned(format!("{:?}", query)), + }; + (args, 7) + } + E::Unary { op, expr } => { + edges.insert("expr", expr); + (Cow::Owned(format!("{:?}", op)), 6) + } + E::Binary { op, left, right } => { + edges.insert("left", left); + edges.insert("right", right); + (Cow::Owned(format!("{:?}", op)), 6) + } + E::Select { + condition, + accept, + reject, + } => { + edges.insert("condition", condition); + edges.insert("accept", accept); + edges.insert("reject", reject); + (Cow::Borrowed("Select"), 3) + } + E::Derivative { axis, expr } => { + edges.insert("", expr); + (Cow::Owned(format!("d{:?}", axis)), 8) + } + E::Relational { fun, argument } => { + edges.insert("arg", argument); + (Cow::Owned(format!("{:?}", fun)), 6) + } + E::Math { + fun, + arg, + arg1, + arg2, + } => { + edges.insert("arg", arg); + if let Some(expr) = arg1 { + edges.insert("arg1", expr); + } + if let Some(expr) = arg2 { + edges.insert("arg2", expr); + } + (Cow::Owned(format!("{:?}", fun)), 7) + } + E::As { + kind, + expr, + convert, + } => { + let fun = if convert { "Convert" } else { "Cast" }; + edges.insert("", expr); + (Cow::Owned(format!("{}<{:?}>", fun, kind)), 3) + } + E::Call(_function) => (Cow::Borrowed("Call"), 4), + E::ArrayLength(expr) => { + edges.insert("", expr); + (Cow::Borrowed("ArrayLength"), 7) + } + }; + writeln!( + output, + "\t\t{}_e{} [ color=\"{}\" label=\"{:?} {}\" ]", + prefix, + handle.index(), + COLORS[color_id], + handle, + label, + )?; + + for (key, edge) in edges.drain() { + writeln!( + output, + "\t\t{}_e{} -> {}_e{} [ label=\"{}\" ]", + prefix, + edge.index(), + prefix, + handle.index(), + key, + )?; + } + match payload.take() { + Some(Payload::Arguments(list)) => { + write!(output, "\t\t{{")?; + for &comp in list { + write!(output, " {}_e{}", prefix, comp.index())?; + } + writeln!(output, " }} -> {}_e{}", prefix, handle.index())?; + } + Some(Payload::Local(h)) => { + writeln!( + output, + "\t\t{}_l{} -> {}_e{}", + prefix, + h.index(), + prefix, + handle.index(), + )?; + } + Some(Payload::Global(h)) => { + writeln!( + output, + "\t\tg{} -> {}_e{} [color=gray]", + h.index(), + prefix, + handle.index(), + )?; + } + None => {} + } + } + + let mut sg = StatementGraph::default(); + sg.add(&fun.body); + for (index, label) in sg.nodes.into_iter().enumerate() { + writeln!( + output, + "\t\t{}_s{} [ shape=square label=\"{}\" ]", + prefix, index, label, + )?; + } + for (from, to, label) in sg.flow { + writeln!( + output, + "\t\t{}_s{} -> {}_s{} [ arrowhead=tee label=\"{}\" ]", + prefix, from, prefix, to, label, + )?; + } + for (to, expr, label) in sg.dependencies { + writeln!( + output, + "\t\t{}_e{} -> {}_s{} [ label=\"{}\" ]", + prefix, + expr.index(), + prefix, + to, + label, + )?; + } + for (from, to) in sg.emits { + writeln!( + output, + "\t\t{}_s{} -> {}_e{} [ style=dotted ]", + prefix, + from, + prefix, + to.index(), + )?; + } + + Ok(()) +} + +pub fn write(module: &crate::Module) -> Result { + use std::fmt::Write as _; + + let mut output = String::new(); + output += "digraph Module {\n"; + + writeln!(output, "\tsubgraph cluster_globals {{")?; + writeln!(output, "\t\tlabel=\"Globals\"")?; + for (handle, var) in module.global_variables.iter() { + writeln!( + output, + "\t\tg{} [ shape=hexagon label=\"{:?} {:?}/'{}'\" ]", + handle.index(), + handle, + var.class, + name(&var.name), + )?; + } + writeln!(output, "\t}}")?; + + for (handle, fun) in module.functions.iter() { + let prefix = format!("f{}", handle.index()); + writeln!(output, "\tsubgraph cluster_{} {{", prefix)?; + writeln!(output, "\t\tlabel=\"Function/'{}'\"", name(&fun.name))?; + write_fun(&mut output, prefix, fun)?; + writeln!(output, "\t}}")?; + } + for (ep_index, (&(stage, ref name), ep)) in module.entry_points.iter().enumerate() { + let prefix = format!("ep{}", ep_index); + writeln!(output, "\tsubgraph cluster_{} {{", prefix)?; + writeln!(output, "\t\tlabel=\"{:?}/'{}'\"", stage, name)?; + write_fun(&mut output, prefix, &ep.function)?; + writeln!(output, "\t}}")?; + } + + output += "}\n"; + Ok(output) +} diff --git a/src/back/mod.rs b/src/back/mod.rs index b3369c0d7..1b0d826e2 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -1,5 +1,7 @@ //! Functions which export shader modules into binary and text formats. +#[cfg(feature = "dot-out")] +pub mod dot; #[cfg(feature = "glsl-out")] pub mod glsl; #[cfg(feature = "msl-out")] diff --git a/tests/out/quad.dot.snap b/tests/out/quad.dot.snap new file mode 100644 index 000000000..f00e3c15e --- /dev/null +++ b/tests/out/quad.dot.snap @@ -0,0 +1,99 @@ +--- +source: tests/snapshots.rs +expression: string +--- +digraph Module { + subgraph cluster_globals { + label="Globals" + g0 [ shape=hexagon label="[1] Input/'a_pos'" ] + g1 [ shape=hexagon label="[2] Input/'a_uv'" ] + g2 [ shape=hexagon label="[3] Output/'v_uv'" ] + g3 [ shape=hexagon label="[4] Output/'o_position'" ] + g4 [ shape=hexagon label="[5] Input/'v_uv'" ] + g5 [ shape=hexagon label="[6] Handle/'u_texture'" ] + g6 [ shape=hexagon label="[7] Handle/'u_sampler'" ] + g7 [ shape=hexagon label="[8] Output/'o_color'" ] + } + subgraph cluster_ep0 { + label="Vertex/'main'" + node [ style=filled ] + ep0_e0 [ color="#ffffb3" label="[1] Constant" ] + ep0_e1 [ color="#ffffb3" label="[2] Global" ] + g0 -> ep0_e1 [color=gray] + ep0_e2 [ color="#ffffb3" label="[3] Global" ] + g2 -> ep0_e2 [color=gray] + ep0_e3 [ color="#ffffb3" label="[4] Global" ] + g3 -> ep0_e3 [color=gray] + ep0_e4 [ color="#ffffb3" label="[5] Global" ] + g1 -> ep0_e4 [color=gray] + ep0_e5 [ color="#fb8072" label="[6] Load" ] + ep0_e4 -> ep0_e5 [ label="pointer" ] + ep0_e6 [ color="#fb8072" label="[7] Load" ] + ep0_e1 -> ep0_e6 [ label="pointer" ] + ep0_e7 [ color="#fdb462" label="[8] Multiply" ] + ep0_e6 -> ep0_e7 [ label="right" ] + ep0_e0 -> ep0_e7 [ label="left" ] + ep0_e8 [ color="#ffffb3" label="[9] Constant" ] + ep0_e9 [ color="#ffffb3" label="[10] Constant" ] + ep0_e10 [ color="#bebada" label="[11] Compose" ] + { ep0_e7 ep0_e8 ep0_e9 } -> ep0_e10 + ep0_s0 [ shape=square label="Root" ] + ep0_s1 [ shape=square label="Emit" ] + ep0_s2 [ shape=square label="Store" ] + ep0_s3 [ shape=square label="Emit" ] + ep0_s4 [ shape=square label="Emit" ] + ep0_s5 [ shape=square label="Store" ] + ep0_s6 [ shape=square label="Return" ] + ep0_s0 -> ep0_s1 [ arrowhead=tee label="" ] + ep0_s1 -> ep0_s2 [ arrowhead=tee label="" ] + ep0_s2 -> ep0_s3 [ arrowhead=tee label="" ] + ep0_s3 -> ep0_s4 [ arrowhead=tee label="" ] + ep0_s4 -> ep0_s5 [ arrowhead=tee label="" ] + ep0_s5 -> ep0_s6 [ arrowhead=tee label="" ] + ep0_e5 -> ep0_s2 [ label="value" ] + ep0_e10 -> ep0_s5 [ label="value" ] + ep0_s1 -> ep0_e5 [ style=dotted ] + ep0_s2 -> ep0_e2 [ style=dotted ] + ep0_s3 -> ep0_e6 [ style=dotted ] + ep0_s3 -> ep0_e7 [ style=dotted ] + ep0_s4 -> ep0_e10 [ style=dotted ] + ep0_s5 -> ep0_e3 [ style=dotted ] + } + subgraph cluster_ep1 { + label="Fragment/'main'" + node [ style=filled ] + ep1_e0 [ color="#ffffb3" label="[1] Global" ] + g3 -> ep1_e0 [color=gray] + ep1_e1 [ color="#ffffb3" label="[2] Global" ] + g6 -> ep1_e1 [color=gray] + ep1_e2 [ color="#ffffb3" label="[3] Global" ] + g5 -> ep1_e2 [color=gray] + ep1_e3 [ color="#ffffb3" label="[4] Constant" ] + ep1_e4 [ color="#ffffb3" label="[5] Global" ] + g0 -> ep1_e4 [color=gray] + ep1_e5 [ color="#ffffb3" label="[6] Global" ] + g4 -> ep1_e5 [color=gray] + ep1_e6 [ color="#ffffb3" label="[7] Global" ] + g1 -> ep1_e6 [color=gray] + ep1_e7 [ color="#ffffb3" label="[8] Global" ] + g7 -> ep1_e7 [color=gray] + ep1_e8 [ color="#fb8072" label="[9] Load" ] + ep1_e5 -> ep1_e8 [ label="pointer" ] + ep1_e9 [ color="#80b1d3" label="[10] ImageSample" ] + ep1_e1 -> ep1_e9 [ label="sampler" ] + ep1_e2 -> ep1_e9 [ label="image" ] + ep1_e8 -> ep1_e9 [ label="coordinate" ] + ep1_s0 [ shape=square label="Root" ] + ep1_s1 [ shape=square label="Emit" ] + ep1_s2 [ shape=square label="Store" ] + ep1_s3 [ shape=square label="Return" ] + ep1_s0 -> ep1_s1 [ arrowhead=tee label="" ] + ep1_s1 -> ep1_s2 [ arrowhead=tee label="" ] + ep1_s2 -> ep1_s3 [ arrowhead=tee label="" ] + ep1_e9 -> ep1_s2 [ label="value" ] + ep1_s1 -> ep1_e8 [ style=dotted ] + ep1_s1 -> ep1_e9 [ style=dotted ] + ep1_s2 -> ep1_e7 [ style=dotted ] + } +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d5a01be7b..e7b93f030 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -5,6 +5,7 @@ bitflags::bitflags! { const SPIRV = 0x4; const METAL = 0x8; const GLSL = 0x10; + const DOT = 0x20; } } @@ -102,6 +103,15 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { } } } + #[cfg(feature = "dot-out")] + { + if targets.contains(Targets::DOT) { + let string = naga::back::dot::write(module).unwrap(); + with_snapshot_settings(|| { + insta::assert_snapshot!(format!("{}.dot", name), string); + }); + } + } } #[cfg(feature = "spv-out")] @@ -213,7 +223,10 @@ fn convert_wgsl(name: &str, targets: Targets) { #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_quad() { - convert_wgsl("quad", Targets::SPIRV | Targets::METAL | Targets::GLSL); + convert_wgsl( + "quad", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::DOT, + ); } #[cfg(feature = "wgsl-in")] @@ -278,7 +291,7 @@ fn convert_glsl( entry_points: naga::FastHashMap, _targets: Targets, ) { - let module = naga::front::glsl::parse_str( + let _module = naga::front::glsl::parse_str( &std::fs::read_to_string(format!("tests/in/{}{}", name, ".glsl")) .expect("Couldn't find glsl file"), &naga::front::glsl::Options { From 667f01ce17cb96c2adaff6aefc87e9ee48dbb1cf Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Wed, 3 Mar 2021 23:58:54 -0330 Subject: [PATCH 0547/2212] [wgsl-in] Add descriptions for more errors --- src/front/wgsl/lexer.rs | 26 +++++---- src/front/wgsl/mod.rs | 115 +++++++++++++++++++++++++++++++--------- tests/errors.rs | 72 +++++++++++++++++++++++++ 3 files changed, 178 insertions(+), 35 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index bc6e9fe05..7e7c3019e 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -1,4 +1,5 @@ use super::{conv, Error, Token, TokenSpan}; +use std::ops::Range; fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { if input.starts_with(what) { @@ -255,6 +256,13 @@ impl<'a> Lexer<'a> { } } + pub(super) fn next_ident_with_span(&mut self) -> Result<(&'a str, Range), Error<'a>> { + match self.next() { + (Token::Word(word), span) => Ok((word, span)), + other => Err(Error::Unexpected(other, "identifier")), + } + } + pub(super) fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { match self.next() { (Token::Word(word), _) => Ok(word), @@ -264,28 +272,26 @@ impl<'a> Lexer<'a> { fn _next_float_literal(&mut self) -> Result> { match self.next() { - (Token::Number { value, .. }, _) => { - value.parse().map_err(|err| Error::BadFloat(value, err)) - } - other => Err(Error::Unexpected(other, "float literal")), + (Token::Number { value, .. }, span) => value.parse().map_err(|_| Error::BadFloat(span)), + other => Err(Error::Unexpected(other, "floating-point literal")), } } pub(super) fn next_uint_literal(&mut self) -> Result> { match self.next() { - (Token::Number { value, .. }, _) => { - value.parse().map_err(|err| Error::BadInteger(value, err)) + (Token::Number { value, .. }, span) => { + value.parse().map_err(|_| Error::BadInteger(span)) } - other => Err(Error::Unexpected(other, "uint literal")), + other => Err(Error::Unexpected(other, "unsigned integer literal")), } } pub(super) fn next_sint_literal(&mut self) -> Result> { match self.next() { - (Token::Number { value, .. }, _) => { - value.parse().map_err(|err| Error::BadInteger(value, err)) + (Token::Number { value, .. }, span) => { + value.parse().map_err(|_| Error::BadInteger(span)) } - other => Err(Error::Unexpected(other, "sint literal")), + other => Err(Error::Unexpected(other, "signed integer literal")), } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 681afc059..5b64c90bb 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -62,14 +62,52 @@ impl<'a> Error<'a> { message: format!( "expected {}, found '{}'", expected, - &source[unexpected_span.clone()] + &source[unexpected_span.clone()], ), labels: vec![(unexpected_span.clone(), format!("expected {}", expected))], + notes: vec![], + source, + }, + Error::BadInteger(bad_span) => ParseError { + message: format!( + "expected integer literal, found `{}`", + &source[bad_span.clone()], + ), + labels: vec![(bad_span.clone(), "expected integer".to_string())], + notes: vec![], + source, + }, + Error::BadFloat(bad_span) => ParseError { + message: format!( + "expected floating-point literal, found `{}`", + &source[bad_span.clone()], + ), + labels: vec![( + bad_span.clone(), + "expected floating-point literal".to_string(), + )], + notes: vec![], + source, + }, + Error::BadScalarWidth(bad_span, width) => ParseError { + message: format!("invalid width of `{}` for literal", width,), + labels: vec![(bad_span.clone(), "invalid width".to_string())], + notes: vec!["valid width is 32".to_string()], + source, + }, + Error::BadAccessor(accessor_span) => ParseError { + message: format!( + "invalid field accessor `{}`", + &source[accessor_span.clone()], + ), + labels: vec![(accessor_span.clone(), "invalid accessor".to_string())], + notes: vec![], source, }, error => ParseError { message: error.to_string(), - labels: Vec::new(), + labels: vec![], + notes: vec![], source, }, } @@ -78,16 +116,16 @@ impl<'a> Error<'a> { #[derive(Clone, Debug, Error)] pub enum Error<'a> { - #[error("unexpected token {:?}, expected {1}", (.0).0)] + #[error("")] Unexpected(TokenSpan<'a>, &'a str), - #[error("unable to parse `{0}` as integer: {1}")] - BadInteger(&'a str, std::num::ParseIntError), - #[error("unable to parse `{1}` as float: {1}")] - BadFloat(&'a str, std::num::ParseFloatError), - #[error("unable to parse `{0}{1}{2}` as scalar width: {3}")] - BadScalarWidth(&'a str, char, &'a str, std::num::ParseIntError), - #[error("bad field accessor `{0}`")] - BadAccessor(&'a str), + #[error("")] + BadInteger(Range), + #[error("")] + BadFloat(Range), + #[error("")] + BadScalarWidth(Range, &'a str), + #[error("")] + BadAccessor(Range), #[error("bad texture {0}`")] BadTexture(&'a str), #[error("bad texture coordinate")] @@ -309,6 +347,7 @@ impl Composition { base: Handle, base_size: crate::VectorSize, name: &'a str, + name_span: Range, expressions: &mut Arena, ) -> Result> { Ok(if name.len() > 1 { @@ -316,7 +355,7 @@ impl Composition { for ch in name.chars() { let index = Self::letter_pos(ch); if index >= base_size as u32 { - return Err(Error::BadAccessor(name)); + return Err(Error::BadAccessor(name_span)); } let expr = crate::Expression::AccessIndex { base, index }; components.push(expressions.append(expr)); @@ -326,14 +365,17 @@ impl Composition { 2 => crate::VectorSize::Bi, 3 => crate::VectorSize::Tri, 4 => crate::VectorSize::Quad, - _ => return Err(Error::BadAccessor(name)), + _ => return Err(Error::BadAccessor(name_span)), }; Composition::Multi(size, components) } else { - let ch = name.chars().next().ok_or(Error::BadAccessor(name))?; + let ch = name + .chars() + .next() + .ok_or_else(|| Error::BadAccessor(name_span.clone()))?; let index = Self::letter_pos(ch); if index >= base_size as u32 { - return Err(Error::BadAccessor(name)); + return Err(Error::BadAccessor(name_span)); } Composition::Single(crate::Expression::AccessIndex { base, index }) }) @@ -375,6 +417,7 @@ struct ParsedVariable<'a> { pub struct ParseError<'a> { message: String, labels: Vec<(Range, String)>, + notes: Vec, source: &'a str, } @@ -389,6 +432,12 @@ impl<'a> ParseError<'a> { Label::primary((), label.0.clone()).with_message(label.1.to_string()) }) .collect(), + ) + .with_notes( + self.notes + .iter() + .map(|note| format!("note: {}", note)) + .collect(), ); diagnostic } @@ -456,20 +505,22 @@ impl Parser { word: &'a str, ty: char, width: &'a str, + token: TokenSpan<'a>, ) -> Result> { + let span = token.1; let value = match ty { 'i' => word .parse() .map(crate::ScalarValue::Sint) - .map_err(|err| Error::BadInteger(word, err))?, + .map_err(|_| Error::BadInteger(span.clone()))?, 'u' => word .parse() .map(crate::ScalarValue::Uint) - .map_err(|err| Error::BadInteger(word, err))?, + .map_err(|_| Error::BadInteger(span.clone()))?, 'f' => word .parse() .map(crate::ScalarValue::Float) - .map_err(|err| Error::BadFloat(word, err))?, + .map_err(|_| Error::BadFloat(span.clone()))?, _ => unreachable!(), }; Ok(crate::ConstantInner::Scalar { @@ -479,7 +530,7 @@ impl Parser { } else { match width.parse::() { Ok(bits) => bits / 8, - Err(e) => return Err(Error::BadScalarWidth(word, ty, width, e)), + Err(_) => return Err(Error::BadScalarWidth(span, width)), } }, }) @@ -851,7 +902,14 @@ impl Parser { width: 1, value: crate::ScalarValue::Bool(false), }, - (Token::Number { value, ty, width }, _) => Self::get_constant_inner(value, ty, width)?, + ( + Token::Number { + ref value, + ref ty, + ref width, + }, + _, + ) => Self::get_constant_inner(*value, *ty, *width, first_token_span)?, (Token::Word(name), _) => { // look for an existing constant first for (handle, var) in const_arena.iter() { @@ -1021,13 +1079,13 @@ impl Parser { let expression = match lexer.peek().0 { Token::Separator('.') => { let _ = lexer.next(); - let name = lexer.next_ident()?; + let (name, name_span) = lexer.next_ident_with_span()?; match *ctx.resolve_type(handle)? { crate::TypeInner::Struct { ref members, .. } => { let index = members .iter() .position(|m| m.name.as_deref() == Some(name)) - .ok_or(Error::BadAccessor(name))? + .ok_or(Error::BadAccessor(name_span))? as u32; crate::Expression::AccessIndex { base: handle, @@ -1035,7 +1093,8 @@ impl Parser { } } crate::TypeInner::Vector { size, kind, width } => { - match Composition::make(handle, size, name, ctx.expressions)? { + match Composition::make(handle, size, name, name_span, ctx.expressions)? + { Composition::Multi(size, components) => { let inner = crate::TypeInner::Vector { size, kind, width }; crate::Expression::Compose { @@ -1052,7 +1111,13 @@ impl Parser { columns, rows, width, - } => match Composition::make(handle, columns, name, ctx.expressions)? { + } => match Composition::make( + handle, + columns, + name, + name_span, + ctx.expressions, + )? { Composition::Multi(columns, components) => { let inner = crate::TypeInner::Matrix { columns, @@ -1068,7 +1133,7 @@ impl Parser { } Composition::Single(expr) => expr, }, - _ => return Err(Error::BadAccessor(name)), + _ => return Err(Error::BadAccessor(name_span)), } } Token::Paren('[') => { diff --git a/tests/errors.rs b/tests/errors.rs index d8d355e3e..97611b8c6 100644 --- a/tests/errors.rs +++ b/tests/errors.rs @@ -25,3 +25,75 @@ fn function_without_identifier() { "### ); } + +#[cfg(feature = "wgsl-in")] +#[test] +fn invalid_integer() { + err!( + "[[location(1.)]] var pos : vec2;", + @r###" + error: expected integer literal, found `1.` + ┌─ wgsl:1:12 + │ + 1 │ [[location(1.)]] var pos : vec2; + │ ^^ expected integer + + "### + ); +} + +#[cfg(feature = "wgsl-in")] +#[test] +fn invalid_float() { + err!( + "const scale: f32 = 1.1.;", + @r###" + error: expected floating-point literal, found `1.1.` + ┌─ wgsl:1:20 + │ + 1 │ const scale: f32 = 1.1.; + │ ^^^^ expected floating-point literal + + "### + ); +} + +#[cfg(feature = "wgsl-in")] +#[test] +fn invalid_scalar_width() { + err!( + "const scale: f32 = 1.1f1000;", + @r###" + error: invalid width of `1000` for literal + ┌─ wgsl:1:20 + │ + 1 │ const scale: f32 = 1.1f1000; + │ ^^^^^^^^ invalid width + │ + = note: valid width is 32 + + "### + ); +} + +#[cfg(feature = "wgsl-in")] +#[test] +fn invalid_accessor() { + err!( + r###" + [[stage(vertex)]] + fn vs_main() { + var color: vec3 = vec3(1.0, 2.0, 3.0); + var i: f32 = color.a; + } + "###, + @r###" + error: invalid field accessor `a` + ┌─ wgsl:5:32 + │ + 5 │ var i: f32 = color.a; + │ ^ invalid accessor + + "### + ); +} From fd34e0abb514c8bdb22d5512b07e66bc77342146 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 4 Mar 2021 09:54:25 -0500 Subject: [PATCH 0548/2212] Install graphviz on CI --- .github/workflows/validation-linux.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/validation-linux.yml b/.github/workflows/validation-linux.yml index 8fd5ac5ca..870299b4b 100644 --- a/.github/workflows/validation-linux.yml +++ b/.github/workflows/validation-linux.yml @@ -4,6 +4,7 @@ on: paths: - 'tests/out/*.spvasm.snap' - 'tests/out/*.glsl.snap' + - 'tests/out/*.dot.snap' jobs: validate-linux: @@ -12,7 +13,7 @@ jobs: steps: - uses: actions/checkout@v2 - name: Install tools - run: sudo apt-get install spirv-tools glslang-tools + run: sudo apt-get install spirv-tools glslang-tools graphviz - run: make validate-spv - run: make validate-glsl - run: make validate-dot From 52b34eb51bbf58b8ac79d5e9d12e6b32084e3043 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 4 Mar 2021 09:59:03 -0500 Subject: [PATCH 0549/2212] Fix warning in the convert example --- bin/convert.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/bin/convert.rs b/bin/convert.rs index 736cf996c..2aed07927 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -5,6 +5,7 @@ use std::{env, error::Error, path::Path}; #[derive(Default)] struct Parameters { + #[cfg(feature = "spv-in")] spv_flow_dump_prefix: Option, #[cfg(feature = "spv-out")] spv: naga::back::spv::Options, @@ -41,6 +42,7 @@ fn main() { let mut input_path = None; let mut output_path = None; //TODO: read the parameters from RON? + #[allow(unused_mut)] let mut params = Parameters::default(); let mut args = env::args(); @@ -49,6 +51,7 @@ fn main() { //TODO: use `strip_prefix` when MSRV reaches 1.45.0 if arg.starts_with("--") { match &arg[2..] { + #[cfg(feature = "spv-in")] "flow-dir" => params.spv_flow_dump_prefix = args.next(), #[cfg(feature = "glsl-out")] "entry-point" => params.glsl.entry_point = args.next().unwrap(), From 50e5904addf8d5e1d486a26a0464914d978d5d1b Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 4 Mar 2021 17:47:48 +0300 Subject: [PATCH 0550/2212] [glsl-out] Fix statement indentation --- src/back/glsl/mod.rs | 38 ++++++++++++++++++----------- tests/out/quad-Fragment.glsl.snap | 2 -- tests/out/quad-Vertex.glsl.snap | 4 --- tests/out/skybox-Fragment.glsl.snap | 2 -- tests/out/skybox-Vertex.glsl.snap | 12 --------- 5 files changed, 24 insertions(+), 34 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 59be2ffb6..ef6c8de57 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -519,6 +519,9 @@ impl<'a, W: Write> Writer<'a, W> { "main", )?; + // Add newline at the end of file + writeln!(self.out)?; + // Collect all of the texture mappings and return them to the user self.collect_texture_mapping() } @@ -997,38 +1000,29 @@ impl<'a, W: Write> Writer<'a, W> { ctx: &FunctionCtx<'_, '_>, indent: usize, ) -> BackendResult { - // The indentation is only for readability - write!(self.out, "{}", INDENT.repeat(indent))?; - match *sta { // This is where we can generate intermediate constants for some expression types. Statement::Emit(ref range) => { - let mut indented = true; for handle in range.clone() { if let Ok(ty_handle) = ctx.typifier.get_handle(handle) { let min_ref_count = ctx.expressions[handle].bake_ref_count(); if min_ref_count <= ctx.info[handle].ref_count { - if !indented { - write!(self.out, "{}", INDENT.repeat(indent))?; - } + write!(self.out, "{}", INDENT.repeat(indent))?; let name = format!("_expr{}", handle.index()); self.write_type(ty_handle)?; write!(self.out, " {} = ", name)?; self.write_expr(handle, ctx)?; writeln!(self.out, ";")?; self.cached_expressions.insert(handle, name); - indented = false; } } } - if indented { - writeln!(self.out, ";")?; - } } // Blocks are simple we just need to write the block statements between braces // We could also just print the statements but this is more readable and maps more // closely to the IR Statement::Block(ref block) => { + write!(self.out, "{}", INDENT.repeat(indent))?; writeln!(self.out, "{{")?; for sta in block.iter() { // Increase the indentation to help with readability @@ -1049,6 +1043,7 @@ impl<'a, W: Write> Writer<'a, W> { ref accept, ref reject, } => { + write!(self.out, "{}", INDENT.repeat(indent))?; write!(self.out, "if(")?; self.write_expr(condition, ctx)?; writeln!(self.out, ") {{")?; @@ -1093,6 +1088,7 @@ impl<'a, W: Write> Writer<'a, W> { ref default, } => { // Start the switch + write!(self.out, "{}", INDENT.repeat(indent))?; write!(self.out, "switch(")?; self.write_expr(selector, ctx)?; writeln!(self.out, ") {{")?; @@ -1140,6 +1136,7 @@ impl<'a, W: Write> Writer<'a, W> { ref body, ref continuing, } => { + write!(self.out, "{}", INDENT.repeat(indent))?; writeln!(self.out, "while(true) {{")?; for sta in body.iter().chain(continuing.iter()) { @@ -1150,11 +1147,18 @@ impl<'a, W: Write> Writer<'a, W> { } // Break, continue and return as written as in C // `break;` - Statement::Break => writeln!(self.out, "break;")?, + Statement::Break => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "break;")? + } // `continue;` - Statement::Continue => writeln!(self.out, "continue;")?, + Statement::Continue => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "continue;")? + } // `return expr;`, `expr` is optional Statement::Return { value } => { + write!(self.out, "{}", INDENT.repeat(indent))?; write!(self.out, "return")?; // Write the expression to be returned if needed if let Some(expr) = value { @@ -1166,9 +1170,13 @@ impl<'a, W: Write> Writer<'a, W> { // This is one of the places were glsl adds to the syntax of C in this case the discard // keyword which ceases all further processing in a fragment shader, it's called OpKill // in spir-v that's why it's called `Statement::Kill` - Statement::Kill => writeln!(self.out, "discard;")?, + Statement::Kill => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "discard;")? + } // Stores in glsl are just variable assignments written as `pointer = value;` Statement::Store { pointer, value } => { + write!(self.out, "{}", INDENT.repeat(indent))?; self.write_expr(pointer, ctx)?; write!(self.out, " = ")?; self.write_expr(value, ctx)?; @@ -1181,6 +1189,7 @@ impl<'a, W: Write> Writer<'a, W> { array_index, value, } => { + write!(self.out, "{}", INDENT.repeat(indent))?; // This will only panic if the module is invalid let dim = match *ctx.typifier.get(image, &self.module.types) { TypeInner::Image { dim, .. } => dim, @@ -1201,6 +1210,7 @@ impl<'a, W: Write> Writer<'a, W> { ref arguments, result, } => { + write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { let name = format!("_expr{}", expr.index()); let ty = self.module.functions[function].return_type.unwrap(); diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap index 976075594..4804f2389 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad-Fragment.glsl.snap @@ -13,8 +13,6 @@ uniform sampler2D _group_0_binding_0; out vec4 _location_0; void main() { - ; _location_0 = texture(_group_0_binding_0, vec2(_location_0_vs)); return; } - diff --git a/tests/out/quad-Vertex.glsl.snap b/tests/out/quad-Vertex.glsl.snap index b430f8475..badab76ce 100644 --- a/tests/out/quad-Vertex.glsl.snap +++ b/tests/out/quad-Vertex.glsl.snap @@ -13,11 +13,7 @@ in vec2 _location_1; out vec2 _location_0_vs; void main() { - ; _location_0_vs = _location_1; - ; - ; gl_Position = vec4((1.2 * _location_0), 0.0, 1.0); return; } - diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap index 680e73ca5..d9f9cea18 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox-Fragment.glsl.snap @@ -18,8 +18,6 @@ in vec3 _location_0_vs; out vec4 _location_0; void main() { - ; _location_0 = texture(_group_0_binding_1, vec3(_location_0_vs)); return; } - diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap index 7833e0c27..d04405dbc 100644 --- a/tests/out/skybox-Vertex.glsl.snap +++ b/tests/out/skybox-Vertex.glsl.snap @@ -22,24 +22,12 @@ void main() { int tmp1_; int tmp2_; vec4 unprojected; - ; - ; tmp1_ = (int(gl_VertexID) / 2); - ; - ; tmp2_ = (int(gl_VertexID) & 1); - ; - ; - ; - ; - ; vec4 _expr28 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - ; - ; unprojected = (_group_0_binding_0.proj_inv * _expr28); vec4 _expr56 = unprojected; _location_0_vs = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr56[0], _expr56[1], _expr56[2])); gl_Position = _expr28; return; } - From d1c47d1705dd710670cad07a285559822eda37ca Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 5 Mar 2021 19:44:18 +0000 Subject: [PATCH 0551/2212] [glsl-out] Set precision for image type --- src/back/glsl/mod.rs | 2 +- tests/out/quad-Fragment.glsl.snap | 2 +- tests/out/skybox-Fragment.glsl.snap | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ef6c8de57..3118b45bd 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -669,7 +669,7 @@ impl<'a, W: Write> Writer<'a, W> { write!( self.out, - "{}{}{}{}{}{}", + "highp {}{}{}{}{}{}", glsl_scalar(kind, 4)?.prefix, base, glsl_dimension(dim), diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap index 4804f2389..90c672343 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad-Fragment.glsl.snap @@ -8,7 +8,7 @@ precision highp float; in vec2 _location_0_vs; -uniform sampler2D _group_0_binding_0; +uniform highp sampler2D _group_0_binding_0; out vec4 _location_0; diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap index d9f9cea18..8770f21df 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox-Fragment.glsl.snap @@ -11,7 +11,7 @@ struct Data { mat4x4 view; }; -uniform samplerCube _group_0_binding_1; +uniform highp samplerCube _group_0_binding_1; in vec3 _location_0_vs; From 7bc72888284c6241d7bdcd7c436bf87a401b7f9a Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 5 Mar 2021 19:48:06 +0000 Subject: [PATCH 0552/2212] [glsl-out] Properly write structure type in statement --- src/back/glsl/mod.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 3118b45bd..5b926b891 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1008,8 +1008,16 @@ impl<'a, W: Write> Writer<'a, W> { let min_ref_count = ctx.expressions[handle].bake_ref_count(); if min_ref_count <= ctx.info[handle].ref_count { write!(self.out, "{}", INDENT.repeat(indent))?; + match self.module.types[ty_handle].inner { + TypeInner::Struct { .. } => { + let ty_name = &self.names[&NameKey::Type(ty_handle)]; + write!(self.out, "{}", ty_name)?; + } + _ => { + self.write_type(ty_handle)?; + } + }; let name = format!("_expr{}", handle.index()); - self.write_type(ty_handle)?; write!(self.out, " {} = ", name)?; self.write_expr(handle, ctx)?; writeln!(self.out, ";")?; From dd823a4b84daaceaf1151b251761f5f165bc4510 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 5 Mar 2021 00:58:16 -0500 Subject: [PATCH 0553/2212] Enforce pointer semantics at the type level. --- Cargo.toml | 1 + bin/convert.rs | 2 + src/back/glsl/mod.rs | 34 ++- src/back/msl/writer.rs | 79 ++++- src/back/spv/writer.rs | 222 +++++++++----- src/front/wgsl/mod.rs | 97 ++++-- src/lib.rs | 12 +- src/proc/layouter.rs | 2 +- src/proc/typifier.rs | 332 +++++++++++++++------ src/proc/validator.rs | 33 ++- tests/out/boids.msl.snap | 2 - tests/out/boids.spvasm.snap | 440 ++++++++++++++-------------- tests/out/collatz.spvasm.snap | 28 +- tests/out/shadow.msl.snap | 2 - tests/out/shadow.spvasm.snap | 91 +++--- tests/out/skybox.msl.snap | 12 +- tests/out/skybox.spvasm.snap | 101 ++++--- tests/out/texture-array.spvasm.snap | 8 +- tests/parse.rs | 2 +- 19 files changed, 934 insertions(+), 566 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9eb8e2470..2607cf33e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } pp-rs = { git = "https://github.com/Kangz/glslpp-rs", rev = "4f2f72a", optional = true } +#env_logger = "0.8" # uncomment temporarily for developing with `convert` [features] default = [] diff --git a/bin/convert.rs b/bin/convert.rs index 2aed07927..c33753265 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -39,6 +39,8 @@ impl PrettyResult for Result { } fn main() { + //env_logger::init(); // uncomment during development + let mut input_path = None; let mut output_path = None; //TODO: read the parameters from RON? diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5b926b891..6645998e4 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -538,11 +538,21 @@ impl<'a, W: Write> Writer<'a, W> { fn write_type(&mut self, ty: Handle) -> BackendResult { match self.module.types[ty].inner { // Scalars are simple we just get the full name from `glsl_scalar` - TypeInner::Scalar { kind, width } => { - write!(self.out, "{}", glsl_scalar(kind, width)?.full)? - } + TypeInner::Scalar { kind, width } + | TypeInner::ValuePointer { + size: None, + kind, + width, + class: _, + } => write!(self.out, "{}", glsl_scalar(kind, width)?.full)?, // Vectors are just `gvecN` where `g` is the scalar prefix and `N` is the vector size - TypeInner::Vector { size, kind, width } => write!( + TypeInner::Vector { size, kind, width } + | TypeInner::ValuePointer { + size: Some(size), + kind, + width, + class: _, + } => write!( self.out, "{}vec{}", glsl_scalar(kind, width)?.prefix, @@ -1258,14 +1268,24 @@ impl<'a, W: Write> Writer<'a, W> { Expression::AccessIndex { base, index } => { self.write_expr(base, ctx)?; - match *ctx.typifier.get(base, &self.module.types) { + let mut resolved = ctx.typifier.get(base, &self.module.types); + let base_ty_handle = match *resolved { + TypeInner::Pointer { base, class: _ } => { + resolved = &self.module.types[base].inner; + Ok(base) + } + _ => ctx.typifier.get_handle(base), + }; + + match *resolved { TypeInner::Vector { .. } | TypeInner::Matrix { .. } - | TypeInner::Array { .. } => write!(self.out, "[{}]", index)?, + | TypeInner::Array { .. } + | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, TypeInner::Struct { .. } => { // This will never panic in case the type is a `Struct`, this is not true // for other types so we can only check while inside this match arm - let ty = ctx.typifier.get_handle(base).unwrap(); + let ty = base_ty_handle.unwrap(); write!( self.out, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 01d29368c..4f9219428 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -118,6 +118,20 @@ impl crate::StorageClass { _ => false, } } + + fn get_name(&self, global_use: GlobalUse) -> Option<&'static str> { + match *self { + Self::Input | Self::Output | Self::Handle => None, + Self::Uniform => Some("constant"), + //TODO: should still be "constant" for read-only buffers + Self::Storage => Some(if global_use.contains(GlobalUse::WRITE) { + "device" + } else { + "storage " + }), + Self::Private | Self::Function | Self::WorkGroup | Self::PushConstant => Some(""), + } + } } enum FunctionOrigin { @@ -208,14 +222,21 @@ impl Writer { } crate::Expression::AccessIndex { base, index } => { self.put_expression(base, context)?; - let resolved = self.typifier.get(base, &context.module.types); + let mut resolved = self.typifier.get(base, &context.module.types); + let base_ty_handle = match *resolved { + crate::TypeInner::Pointer { base, class: _ } => { + resolved = &context.module.types[base].inner; + Ok(base) + } + _ => self.typifier.get_handle(base), + }; match *resolved { crate::TypeInner::Struct { .. } => { - let base_ty = self.typifier.get_handle(base).unwrap(); + let base_ty = base_ty_handle.unwrap(); let name = &self.names[&NameKey::StructMember(base_ty, index)]; write!(self.out, ".{}", name)?; } - crate::TypeInner::Vector { .. } => { + crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; } crate::TypeInner::Matrix { .. } => { @@ -852,6 +873,7 @@ impl Writer { fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { for (handle, ty) in module.types.iter() { let name = &self.names[&NameKey::Type(handle)]; + let global_use = GlobalUse::all(); //TODO match ty.inner { crate::TypeInner::Scalar { kind, .. } => { write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?; @@ -878,20 +900,51 @@ impl Writer { )?; } crate::TypeInner::Pointer { base, class } => { - use crate::StorageClass as Sc; let base_name = &self.names[&NameKey::Type(base)]; - let class_name = match class { - Sc::Input | Sc::Output => continue, - Sc::Uniform => "constant", - Sc::Storage => "device", - Sc::Handle - | Sc::Private - | Sc::Function - | Sc::WorkGroup - | Sc::PushConstant => "", + let class_name = match class.get_name(global_use) { + Some(name) => name, + None => continue, }; write!(self.out, "typedef {} {} *{}", class_name, base_name, name)?; } + crate::TypeInner::ValuePointer { + size: None, + kind, + width: _, + class, + } => { + let class_name = match class.get_name(global_use) { + Some(name) => name, + None => continue, + }; + write!( + self.out, + "typedef {} {} *{}", + class_name, + scalar_kind_string(kind), + name + )?; + } + crate::TypeInner::ValuePointer { + size: Some(size), + kind, + width: _, + class, + } => { + let class_name = match class.get_name(global_use) { + Some(name) => name, + None => continue, + }; + write!( + self.out, + "typedef {} {}::{}{} {}", + class_name, + NAMESPACE, + scalar_kind_string(kind), + vector_size_string(size), + name + )?; + } crate::TypeInner::Array { base, size, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 47375182d..4f2d601dc 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -82,14 +82,11 @@ impl Function { #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LocalType { - Scalar { - kind: crate::ScalarKind, - width: crate::Bytes, - }, - Vector { - size: crate::VectorSize, + Value { + vector_size: Option, kind: crate::ScalarKind, width: crate::Bytes, + pointer_class: Option, }, Matrix { columns: crate::VectorSize, @@ -108,10 +105,18 @@ enum LocalType { impl LocalType { fn from_inner(inner: &crate::TypeInner) -> Option { Some(match *inner { - crate::TypeInner::Scalar { kind, width } => LocalType::Scalar { kind, width }, - crate::TypeInner::Vector { size, kind, width } => { - LocalType::Vector { size, kind, width } - } + crate::TypeInner::Scalar { kind, width } => LocalType::Value { + vector_size: None, + kind, + width, + pointer_class: None, + }, + crate::TypeInner::Vector { size, kind, width } => LocalType::Value { + vector_size: Some(size), + kind, + width, + pointer_class: None, + }, crate::TypeInner::Matrix { columns, rows, @@ -122,6 +127,17 @@ impl LocalType { width, }, crate::TypeInner::Pointer { base, class } => LocalType::Pointer { base, class }, + crate::TypeInner::ValuePointer { + size, + kind, + width, + class, + } => LocalType::Value { + vector_size: size, + kind, + width, + pointer_class: Some(class), + }, _ => return None, }) } @@ -302,26 +318,9 @@ impl Writer { Ok(*e.get()) } else { match lookup_ty { - LookupType::Handle(handle) => match arena[handle].inner { - crate::TypeInner::Scalar { kind, width } => self - .get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width })), - crate::TypeInner::Vector { size, kind, width } => self.get_type_id( - arena, - LookupType::Local(LocalType::Vector { size, kind, width }), - ), - crate::TypeInner::Matrix { - columns, - rows, - width, - } => self.get_type_id( - arena, - LookupType::Local(LocalType::Matrix { - columns, - rows, - width, - }), - ), - _ => self.write_type_declaration_arena(arena, handle), + LookupType::Handle(handle) => match LocalType::from_inner(&arena[handle].inner) { + Some(local) => self.get_type_id(arena, LookupType::Local(local)), + None => self.write_type_declaration_arena(arena, handle), }, LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty), } @@ -364,13 +363,6 @@ impl Writer { ) } - fn create_pointer_type(&mut self, type_id: Word, class: spirv::StorageClass) -> Word { - let id = self.generate_id(); - let instruction = Instruction::type_pointer(id, class, type_id); - instruction.to_words(&mut self.logical_layout.declarations); - id - } - fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word { let id = self.generate_id(); let instruction = Instruction::constant(type_id, id, value); @@ -607,10 +599,27 @@ impl Writer { ) -> Result { let id = self.generate_id(); let instruction = match local_ty { - LocalType::Scalar { kind, width } => self.write_scalar(id, kind, width), - LocalType::Vector { size, kind, width } => { - let scalar_id = - self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width }))?; + LocalType::Value { + vector_size: None, + kind, + width, + pointer_class: None, + } => self.write_scalar(id, kind, width), + LocalType::Value { + vector_size: Some(size), + kind, + width, + pointer_class: None, + } => { + let scalar_id = self.get_type_id( + arena, + LookupType::Local(LocalType::Value { + vector_size: None, + kind, + width, + pointer_class: None, + }), + )?; Instruction::type_vector(id, scalar_id, size) } LocalType::Matrix { @@ -620,16 +629,35 @@ impl Writer { } => { let vector_id = self.get_type_id( arena, - LookupType::Local(LocalType::Vector { - size: rows, + LookupType::Local(LocalType::Value { + vector_size: Some(rows), kind: crate::ScalarKind::Float, width, + pointer_class: None, }), )?; Instruction::type_matrix(id, vector_id, columns) } - LocalType::Pointer { .. } => { - return Err(Error::FeatureNotImplemented("pointer declaration")) + LocalType::Pointer { base, class } => { + let type_id = self.get_type_id(arena, LookupType::Handle(base))?; + Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) + } + LocalType::Value { + vector_size, + kind, + width, + pointer_class: Some(class), + } => { + let type_id = self.get_type_id( + arena, + LookupType::Local(LocalType::Value { + vector_size, + kind, + width, + pointer_class: None, + }), + )?; + Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) } LocalType::SampledImage { image_type } => { let image_type_id = self.get_type_id(arena, LookupType::Handle(image_type))?; @@ -658,15 +686,34 @@ impl Writer { let instruction = match ty.inner { crate::TypeInner::Scalar { kind, width } => { - self.lookup_type - .insert(LookupType::Local(LocalType::Scalar { kind, width }), id); + self.lookup_type.insert( + LookupType::Local(LocalType::Value { + vector_size: None, + kind, + width, + pointer_class: None, + }), + id, + ); self.write_scalar(id, kind, width) } crate::TypeInner::Vector { size, kind, width } => { - let scalar_id = - self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width }))?; + let scalar_id = self.get_type_id( + arena, + LookupType::Local(LocalType::Value { + vector_size: None, + kind, + width, + pointer_class: None, + }), + )?; self.lookup_type.insert( - LookupType::Local(LocalType::Vector { size, kind, width }), + LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind, + width, + pointer_class: None, + }), id, ); Instruction::type_vector(id, scalar_id, size) @@ -678,10 +725,11 @@ impl Writer { } => { let vector_id = self.get_type_id( arena, - LookupType::Local(LocalType::Vector { - size: columns, + LookupType::Local(LocalType::Value { + vector_size: Some(columns), kind: crate::ScalarKind::Float, width, + pointer_class: None, }), )?; self.lookup_type.insert( @@ -699,19 +747,16 @@ impl Writer { arrayed, class, } => { - let width = 4; - let local_type = match class { - crate::ImageClass::Sampled { kind, multi: _ } => { - LocalType::Scalar { kind, width } - } - crate::ImageClass::Depth => LocalType::Scalar { - kind: crate::ScalarKind::Float, - width, - }, - crate::ImageClass::Storage(format) => LocalType::Scalar { - kind: format.into(), - width, - }, + let kind = match class { + crate::ImageClass::Sampled { kind, multi: _ } => kind, + crate::ImageClass::Depth => crate::ScalarKind::Float, + crate::ImageClass::Storage(format) => format.into(), + }; + let local_type = LocalType::Value { + vector_size: None, + kind, + width: 4, + pointer_class: None, }; let type_id = self.get_type_id(arena, LookupType::Local(local_type))?; let dim = map_dim(dim); @@ -820,6 +865,32 @@ impl Writer { .insert(LookupType::Local(LocalType::Pointer { base, class }), id); Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) } + crate::TypeInner::ValuePointer { + size, + kind, + width, + class, + } => { + let type_id = self.get_type_id( + arena, + LookupType::Local(LocalType::Value { + vector_size: size, + kind, + width, + pointer_class: None, + }), + )?; + self.lookup_type.insert( + LookupType::Local(LocalType::Value { + vector_size: size, + kind, + width, + pointer_class: Some(class), + }), + id, + ); + Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) + } }; self.lookup_type.insert(LookupType::Handle(handle), id); @@ -837,9 +908,11 @@ impl Writer { crate::ConstantInner::Scalar { width, ref value } => { let type_id = self.get_type_id( types, - LookupType::Local(LocalType::Scalar { + LookupType::Local(LocalType::Value { + vector_size: None, kind: value.scalar_kind(), width, + pointer_class: None, }), )?; let (solo, pair); @@ -1061,9 +1134,11 @@ impl Writer { Ok(if let Some(array_index) = array_index { let coordinate_scalar_type_id = self.get_type_id( &ir_module.types, - LookupType::Local(LocalType::Scalar { + LookupType::Local(LocalType::Value { + vector_size: None, kind: crate::ScalarKind::Float, width: 4, + pointer_class: None, }), )?; @@ -1109,10 +1184,11 @@ impl Writer { let extended_coordinate_type_id = self.get_type_id( &ir_module.types, - LookupType::Local(LocalType::Vector { - size, + LookupType::Local(LocalType::Value { + vector_size: Some(size), kind: crate::ScalarKind::Float, width: 4, + pointer_class: None, }), )?; @@ -1757,6 +1833,7 @@ impl Writer { Err(inner) => LookupType::Local(LocalType::from_inner(inner).unwrap()), }; let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; + self.temp_chain.clear(); let (root_id, class) = loop { expr_handle = match ir_function.expressions[expr_handle] { @@ -1768,9 +1845,11 @@ impl Writer { crate::Expression::AccessIndex { base, index } => { let const_ty_id = self.get_type_id( &ir_module.types, - LookupType::Local(LocalType::Scalar { + LookupType::Local(LocalType::Value { + vector_size: None, kind: crate::ScalarKind::Sint, width: 4, + pointer_class: None, }), )?; let const_id = self.create_constant(const_ty_id, &[index]); @@ -1794,9 +1873,8 @@ impl Writer { } else { self.temp_chain.reverse(); let id = self.generate_id(); - let pointer_type_id = self.create_pointer_type(result_type_id, class); block.body.push(Instruction::access_chain( - pointer_type_id, + result_type_id, id, root_id, &self.temp_chain, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5b64c90bb..a028954c3 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -136,6 +136,8 @@ pub enum Error<'a> { InvalidResolve(ResolveError), #[error("invalid statement {0:?}, expected {1}")] InvalidStatement(crate::Statement, &'a str), + #[error("resource type {0:?} is invalid")] + InvalidResourceType(Handle), #[error("unknown import: `{0}`")] UnknownImport(&'a str), #[error("unknown storage class: `{0}`")] @@ -170,6 +172,8 @@ pub enum Error<'a> { FunctionRedefinition(&'a str), #[error("call to local `{0}(..)` can't be resolved")] UnknownLocalFunction(&'a str), + #[error("builtin {0:?} is not implemented")] + UnimplementedBuiltin(crate::BuiltIn), #[error("other error")] Other, } @@ -343,6 +347,23 @@ impl Composition { } } + fn extract( + base: Handle, + base_size: crate::VectorSize, + name: &str, + name_span: Range, + ) -> Result { + let ch = name + .chars() + .next() + .ok_or_else(|| Error::BadAccessor(name_span.clone()))?; + let index = Self::letter_pos(ch); + if index >= base_size as u32 { + return Err(Error::BadAccessor(name_span)); + } + Ok(crate::Expression::AccessIndex { base, index }) + } + fn make<'a>( base: Handle, base_size: crate::VectorSize, @@ -350,7 +371,7 @@ impl Composition { name_span: Range, expressions: &mut Arena, ) -> Result> { - Ok(if name.len() > 1 { + if name.len() > 1 { let mut components = Vec::with_capacity(name.len()); for ch in name.chars() { let index = Self::letter_pos(ch); @@ -367,18 +388,10 @@ impl Composition { 4 => crate::VectorSize::Quad, _ => return Err(Error::BadAccessor(name_span)), }; - Composition::Multi(size, components) + Ok(Composition::Multi(size, components)) } else { - let ch = name - .chars() - .next() - .ok_or_else(|| Error::BadAccessor(name_span.clone()))?; - let index = Self::letter_pos(ch); - if index >= base_size as u32 { - return Err(Error::BadAccessor(name_span)); - } - Composition::Single(crate::Expression::AccessIndex { base, index }) - }) + Self::extract(base, base_size, name, name_span).map(Composition::Single) + } } } @@ -1070,10 +1083,19 @@ impl Parser { }; loop { // insert the E::Load when we reach a value - if needs_deref && ctx.resolve_type(handle)?.scalar_kind().is_some() { - let expression = crate::Expression::Load { pointer: handle }; - handle = ctx.expressions.append(expression); - needs_deref = false; + if needs_deref { + let now = match *ctx.resolve_type(handle)? { + crate::TypeInner::Pointer { base, class: _ } => { + ctx.types[base].inner.scalar_kind().is_some() + } + crate::TypeInner::ValuePointer { .. } => true, + _ => false, + }; + if now { + let expression = crate::Expression::Load { pointer: handle }; + handle = ctx.expressions.append(expression); + needs_deref = false; + } } let expression = match lexer.peek().0 { @@ -1133,6 +1155,30 @@ impl Parser { } Composition::Single(expr) => expr, }, + crate::TypeInner::ValuePointer { + size: Some(size), .. + } => Composition::extract(handle, size, name, name_span)?, + crate::TypeInner::Pointer { base, class: _ } => match ctx.types[base].inner + { + crate::TypeInner::Struct { ref members, .. } => { + let index = members + .iter() + .position(|m| m.name.as_deref() == Some(name)) + .ok_or(Error::BadAccessor(name_span))? + as u32; + crate::Expression::AccessIndex { + base: handle, + index, + } + } + crate::TypeInner::Vector { size, .. } => { + Composition::extract(handle, size, name, name_span)? + } + crate::TypeInner::Matrix { columns, .. } => { + Composition::extract(handle, columns, name, name_span)? + } + _ => return Err(Error::BadAccessor(name_span)), + }, _ => return Err(Error::BadAccessor(name_span)), } } @@ -2453,18 +2499,29 @@ impl Parser { Some(crate::Binding::BuiltIn(builtin)) => match builtin { crate::BuiltIn::GlobalInvocationId => crate::StorageClass::Input, crate::BuiltIn::Position => crate::StorageClass::Output, - _ => unimplemented!(), + _ => return Err(Error::UnimplementedBuiltin(builtin)), }, Some(crate::Binding::Resource { .. }) => { match module.types[pvar.ty].inner { crate::TypeInner::Struct { .. } if pvar.access.is_empty() => { crate::StorageClass::Uniform } - crate::TypeInner::Struct { .. } => crate::StorageClass::Storage, - _ => crate::StorageClass::Handle, + crate::TypeInner::Struct { .. } + | crate::TypeInner::Array { .. } => crate::StorageClass::Storage, + crate::TypeInner::Image { .. } + | crate::TypeInner::Sampler { .. } => crate::StorageClass::Handle, + ref other => { + log::error!("Resource type {:?}", other); + return Err(Error::InvalidResourceType(pvar.ty)); + } } } - _ => crate::StorageClass::Private, + _ => match module.types[pvar.ty].inner { + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { + crate::StorageClass::Handle + } + _ => crate::StorageClass::Private, + }, }, }; let var_handle = module.global_variables.append(crate::GlobalVariable { diff --git a/src/lib.rs b/src/lib.rs index 8af9270f9..6f491d6f4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,6 +53,9 @@ use serde::Deserialize; #[cfg(feature = "serialize")] use serde::Serialize; +/// Width of a boolean type, in bytes. +pub const BOOL_WIDTH: Bytes = 1; + /// Hash map that is faster but not resilient to DoS attacks. pub type FastHashMap = HashMap>; /// Hash set that is faster but not resilient to DoS attacks. @@ -371,11 +374,18 @@ pub enum TypeInner { rows: VectorSize, width: Bytes, }, - /// Pointer to a value. + /// Pointer to another type. Pointer { base: Handle, class: StorageClass, }, + /// Pointer to a value. + ValuePointer { + size: Option, + kind: ScalarKind, + width: Bytes, + class: StorageClass, + }, /// Homogenous list of elements. Array { base: Handle, diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 89986e5ae..8512e96d5 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -62,7 +62,7 @@ impl Layouter { size: (columns as u8 * rows as u8 * width) as u32, alignment: Alignment::new((columns as u8 * width) as u32).unwrap(), }, - Ti::Pointer { .. } => TypeLayout { + Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { size: 4, alignment: Alignment::new(1).unwrap(), }, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index d9a05b97c..498fec736 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -11,26 +11,34 @@ enum Resolution { // Clone is only implemented for numeric variants of `TypeInner`. impl Clone for Resolution { fn clone(&self) -> Self { + use crate::TypeInner as Ti; match *self { Resolution::Handle(handle) => Resolution::Handle(handle), Resolution::Value(ref v) => Resolution::Value(match *v { - crate::TypeInner::Scalar { kind, width } => { - crate::TypeInner::Scalar { kind, width } - } - crate::TypeInner::Vector { size, kind, width } => { - crate::TypeInner::Vector { size, kind, width } - } - crate::TypeInner::Matrix { + Ti::Scalar { kind, width } => Ti::Scalar { kind, width }, + Ti::Vector { size, kind, width } => Ti::Vector { size, kind, width }, + Ti::Matrix { rows, columns, width, - } => crate::TypeInner::Matrix { + } => Ti::Matrix { rows, columns, width, }, - #[allow(clippy::panic)] - _ => panic!("Unexpected clone type: {:?}", v), + Ti::Pointer { base, class } => Ti::Pointer { base, class }, + Ti::ValuePointer { + size, + kind, + width, + class, + } => Ti::ValuePointer { + size, + kind, + width, + class, + }, + _ => unreachable!("Unexpected clone type: {:?}", v), }), } } @@ -44,8 +52,25 @@ pub struct Typifier { #[derive(Clone, Debug, Error, PartialEq)] pub enum ResolveError { - #[error("Invalid index into array")] - InvalidAccessIndex, + #[error("Index {index} is out of bounds for expression {expr:?}")] + OutOfBoundsIndex { + expr: Handle, + index: u32, + }, + #[error("Invalid access into expression {expr:?}, indexed: {indexed}")] + InvalidAccess { + expr: Handle, + indexed: bool, + }, + #[error("Invalid sub-access into type {ty:?}, indexed: {indexed}")] + InvalidSubAccess { + ty: Handle, + indexed: bool, + }, + #[error("Invalid pointer {0:?}")] + InvalidPointer(Handle), + #[error("Invalid image {0:?}")] + InvalidImage(Handle), #[error("Function {name} not defined")] FunctionNotDefined { name: String }, #[error("Function without return type")] @@ -118,51 +143,74 @@ impl Typifier { } } - //TODO: resolve `*Variable` and `Access*` expressions to `Pointer` type. fn resolve_impl( &self, expr: &crate::Expression, types: &Arena, ctx: &ResolveContext, ) -> Result { + use crate::TypeInner as Ti; Ok(match *expr { crate::Expression::Access { base, .. } => match *self.get(base, types) { - crate::TypeInner::Array { base, .. } => Resolution::Handle(base), - crate::TypeInner::Vector { + Ti::Array { base, .. } => Resolution::Handle(base), + Ti::Vector { size: _, kind, width, - } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), - crate::TypeInner::Matrix { - rows: size, - columns: _, + } => Resolution::Value(Ti::Scalar { kind, width }), + Ti::ValuePointer { + size: Some(_), + kind, width, - } => Resolution::Value(crate::TypeInner::Vector { - size, - kind: crate::ScalarKind::Float, + class, + } => Resolution::Value(Ti::ValuePointer { + size: None, + kind, width, + class, + }), + Ti::Pointer { base, class } => Resolution::Value(match types[base].inner { + Ti::Array { base, .. } => Ti::Pointer { base, class }, + Ti::Vector { + size: _, + kind, + width, + } => Ti::ValuePointer { + size: None, + kind, + width, + class, + }, + ref other => { + log::error!("Access sub-type {:?}", other); + return Err(ResolveError::InvalidSubAccess { + ty: base, + indexed: false, + }); + } }), ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "access".to_string(), - operand: format!("{:?}", other), - }) + log::error!("Access type {:?}", other); + return Err(ResolveError::InvalidAccess { + expr: base, + indexed: false, + }); } }, crate::Expression::AccessIndex { base, index } => match *self.get(base, types) { - crate::TypeInner::Vector { size, kind, width } => { + Ti::Vector { size, kind, width } => { if index >= size as u32 { - return Err(ResolveError::InvalidAccessIndex); + return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } - Resolution::Value(crate::TypeInner::Scalar { kind, width }) + Resolution::Value(Ti::Scalar { kind, width }) } - crate::TypeInner::Matrix { + Ti::Matrix { columns, rows, width, } => { if index >= columns as u32 { - return Err(ResolveError::InvalidAccessIndex); + return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } Resolution::Value(crate::TypeInner::Vector { size: rows, @@ -170,26 +218,94 @@ impl Typifier { width, }) } - crate::TypeInner::Array { base, .. } => Resolution::Handle(base), - crate::TypeInner::Struct { + Ti::Array { base, .. } => Resolution::Handle(base), + Ti::Struct { block: _, ref members, } => { let member = members .get(index as usize) - .ok_or(ResolveError::InvalidAccessIndex)?; + .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; Resolution::Handle(member.ty) } - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "access index".to_string(), - operand: format!("{:?}", other), + Ti::ValuePointer { + size: Some(size), + kind, + width, + class, + } => { + if index >= size as u32 { + return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); + } + Resolution::Value(Ti::ValuePointer { + size: None, + kind, + width, + class, }) } + Ti::Pointer { + base: ty_base, + class, + } => Resolution::Value(match types[ty_base].inner { + Ti::Array { base, .. } => Ti::Pointer { base, class }, + Ti::Vector { size, kind, width } => { + if index >= size as u32 { + return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); + } + Ti::ValuePointer { + size: None, + kind, + width, + class, + } + } + Ti::Matrix { + rows, + columns, + width, + } => { + if index >= columns as u32 { + return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); + } + Ti::ValuePointer { + size: Some(rows), + kind: crate::ScalarKind::Float, + width, + class, + } + } + Ti::Struct { + block: _, + ref members, + } => { + let member = members + .get(index as usize) + .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; + Ti::Pointer { + base: member.ty, + class, + } + } + ref other => { + log::error!("Access index sub-type {:?}", other); + return Err(ResolveError::InvalidSubAccess { + ty: ty_base, + indexed: true, + }); + } + }), + ref other => { + log::error!("Access index type {:?}", other); + return Err(ResolveError::InvalidAccess { + expr: base, + indexed: true, + }); + } }, crate::Expression::Constant(h) => match ctx.constants[h].inner { crate::ConstantInner::Scalar { width, ref value } => { - Resolution::Value(crate::TypeInner::Scalar { + Resolution::Value(Ti::Scalar { kind: value.scalar_kind(), width, }) @@ -200,55 +316,89 @@ impl Typifier { crate::Expression::FunctionArgument(index) => { Resolution::Handle(ctx.arguments[index as usize].ty) } - crate::Expression::GlobalVariable(h) => Resolution::Handle(ctx.global_vars[h].ty), - crate::Expression::LocalVariable(h) => Resolution::Handle(ctx.local_vars[h].ty), - // we treat Load as a transparent operation for the type system - crate::Expression::Load { pointer } => self.resolutions[pointer.index()].clone(), + crate::Expression::GlobalVariable(h) => { + let var = &ctx.global_vars[h]; + if var.class == crate::StorageClass::Handle { + Resolution::Handle(var.ty) + } else { + Resolution::Value(Ti::Pointer { + base: var.ty, + class: var.class, + }) + } + } + crate::Expression::LocalVariable(h) => { + let var = &ctx.local_vars[h]; + Resolution::Value(Ti::Pointer { + base: var.ty, + class: crate::StorageClass::Function, + }) + } + crate::Expression::Load { pointer } => match *self.get(pointer, types) { + Ti::Pointer { base, class: _ } => Resolution::Handle(base), + Ti::ValuePointer { + size, + kind, + width, + class: _, + } => Resolution::Value(match size { + Some(size) => Ti::Vector { size, kind, width }, + None => Ti::Scalar { kind, width }, + }), + ref other => { + log::error!("Pointer type {:?}", other); + return Err(ResolveError::InvalidPointer(pointer)); + } + }, crate::Expression::ImageSample { image, .. } | crate::Expression::ImageLoad { image, .. } => match *self.get(image, types) { - crate::TypeInner::Image { class, .. } => Resolution::Value(match class { - crate::ImageClass::Depth => crate::TypeInner::Scalar { + Ti::Image { class, .. } => Resolution::Value(match class { + crate::ImageClass::Depth => Ti::Scalar { kind: crate::ScalarKind::Float, width: 4, }, - crate::ImageClass::Sampled { kind, multi: _ } => crate::TypeInner::Vector { + crate::ImageClass::Sampled { kind, multi: _ } => Ti::Vector { kind, width: 4, size: crate::VectorSize::Quad, }, - crate::ImageClass::Storage(format) => crate::TypeInner::Vector { + crate::ImageClass::Storage(format) => Ti::Vector { kind: format.into(), width: 4, size: crate::VectorSize::Quad, }, }), - _ => unreachable!(), + ref other => { + log::error!("Image type {:?}", other); + return Err(ResolveError::InvalidImage(image)); + } }, crate::Expression::ImageQuery { image, query } => Resolution::Value(match query { crate::ImageQuery::Size { level: _ } => match *self.get(image, types) { - crate::TypeInner::Image { dim, .. } => match dim { - crate::ImageDimension::D1 => crate::TypeInner::Scalar { + Ti::Image { dim, .. } => match dim { + crate::ImageDimension::D1 => Ti::Scalar { kind: crate::ScalarKind::Sint, width: 4, }, - crate::ImageDimension::D2 => crate::TypeInner::Vector { + crate::ImageDimension::D2 => Ti::Vector { size: crate::VectorSize::Bi, kind: crate::ScalarKind::Sint, width: 4, }, - crate::ImageDimension::D3 | crate::ImageDimension::Cube => { - crate::TypeInner::Vector { - size: crate::VectorSize::Tri, - kind: crate::ScalarKind::Sint, - width: 4, - } - } + crate::ImageDimension::D3 | crate::ImageDimension::Cube => Ti::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Sint, + width: 4, + }, }, - _ => unreachable!(), + ref other => { + log::error!("Image type {:?}", other); + return Err(ResolveError::InvalidImage(image)); + } }, crate::ImageQuery::NumLevels | crate::ImageQuery::NumLayers - | crate::ImageQuery::NumSamples => crate::TypeInner::Scalar { + | crate::ImageQuery::NumSamples => Ti::Scalar { kind: crate::ScalarKind::Sint, width: 4, }, @@ -264,28 +414,28 @@ impl Typifier { let ty_right = self.get(right, types); if ty_left == ty_right { self.resolutions[left.index()].clone() - } else if let crate::TypeInner::Scalar { .. } = *ty_left { + } else if let Ti::Scalar { .. } = *ty_left { self.resolutions[right.index()].clone() - } else if let crate::TypeInner::Scalar { .. } = *ty_right { + } else if let Ti::Scalar { .. } = *ty_right { self.resolutions[left.index()].clone() - } else if let crate::TypeInner::Matrix { + } else if let Ti::Matrix { columns: _, rows, width, } = *ty_left { - Resolution::Value(crate::TypeInner::Vector { + Resolution::Value(Ti::Vector { size: rows, kind: crate::ScalarKind::Float, width, }) - } else if let crate::TypeInner::Matrix { + } else if let Ti::Matrix { columns, rows: _, width, } = *ty_right { - Resolution::Value(crate::TypeInner::Vector { + Resolution::Value(Ti::Vector { size: columns, kind: crate::ScalarKind::Float, width, @@ -309,10 +459,8 @@ impl Typifier { let kind = crate::ScalarKind::Bool; let width = 1; let inner = match *self.get(left, types) { - crate::TypeInner::Scalar { .. } => crate::TypeInner::Scalar { kind, width }, - crate::TypeInner::Vector { size, .. } => { - crate::TypeInner::Vector { size, kind, width } - } + Ti::Scalar { .. } => Ti::Scalar { kind, width }, + Ti::Vector { size, .. } => Ti::Vector { size, kind, width }, ref other => { return Err(ResolveError::IncompatibleOperand { op: "logical".to_string(), @@ -332,7 +480,7 @@ impl Typifier { crate::Expression::Derivative { axis: _, expr } => { self.resolutions[expr.index()].clone() } - crate::Expression::Relational { .. } => Resolution::Value(crate::TypeInner::Scalar { + crate::Expression::Relational { .. } => Resolution::Value(Ti::Scalar { kind: crate::ScalarKind::Bool, width: 4, }), @@ -377,11 +525,11 @@ impl Typifier { Mf::Pow => self.resolutions[arg.index()].clone(), // geometry Mf::Dot => match *self.get(arg, types) { - crate::TypeInner::Vector { + Ti::Vector { kind, size: _, width, - } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), + } => Resolution::Value(Ti::Scalar { kind, width }), ref other => { return Err(ResolveError::IncompatibleOperand { op: "dot product".to_string(), @@ -395,7 +543,7 @@ impl Typifier { operand: "".to_string(), })?; match (self.get(arg, types), self.get(arg1,types)) { - (&crate::TypeInner::Vector {kind: _, size: columns,width}, &crate::TypeInner::Vector{ size: rows, .. }) => Resolution::Value(crate::TypeInner::Matrix { columns, rows, width }), + (&Ti::Vector {kind: _, size: columns,width}, &Ti::Vector{ size: rows, .. }) => Resolution::Value(Ti::Matrix { columns, rows, width }), (left, right) => { return Err(ResolveError::IncompatibleOperands { op: "outer product".to_string(), @@ -408,8 +556,8 @@ impl Typifier { Mf::Cross => self.resolutions[arg.index()].clone(), Mf::Distance | Mf::Length => match *self.get(arg, types) { - crate::TypeInner::Scalar {width,kind} | - crate::TypeInner::Vector {width,kind,size:_} => Resolution::Value(crate::TypeInner::Scalar { kind, width }), + Ti::Scalar {width,kind} | + Ti::Vector {width,kind,size:_} => Resolution::Value(Ti::Scalar { kind, width }), ref other => { return Err(ResolveError::IncompatibleOperand { op: format!("{:?}", fun), @@ -429,11 +577,11 @@ impl Typifier { Mf::Sqrt | Mf::InverseSqrt => self.resolutions[arg.index()].clone(), Mf::Transpose => match *self.get(arg, types) { - crate::TypeInner::Matrix { + Ti::Matrix { columns, rows, width, - } => Resolution::Value(crate::TypeInner::Matrix { + } => Resolution::Value(Ti::Matrix { columns: rows, rows: columns, width, @@ -446,11 +594,11 @@ impl Typifier { } }, Mf::Inverse => match *self.get(arg, types) { - crate::TypeInner::Matrix { + Ti::Matrix { columns, rows, width, - } if columns == rows => Resolution::Value(crate::TypeInner::Matrix { + } if columns == rows => Resolution::Value(Ti::Matrix { columns, rows, width, @@ -463,10 +611,10 @@ impl Typifier { } }, Mf::Determinant => match *self.get(arg, types) { - crate::TypeInner::Matrix { + Ti::Matrix { width, .. - } => Resolution::Value(crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width }), + } => Resolution::Value(Ti::Scalar { kind: crate::ScalarKind::Float, width }), ref other => { return Err(ResolveError::IncompatibleOperand { op: "determinant".to_string(), @@ -484,14 +632,12 @@ impl Typifier { kind, convert: _, } => match *self.get(expr, types) { - crate::TypeInner::Scalar { kind: _, width } => { - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - crate::TypeInner::Vector { + Ti::Scalar { kind: _, width } => Resolution::Value(Ti::Scalar { kind, width }), + Ti::Vector { kind: _, size, width, - } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }), + } => Resolution::Value(Ti::Vector { kind, size, width }), ref other => { return Err(ResolveError::IncompatibleOperand { op: "as".to_string(), @@ -505,7 +651,7 @@ impl Typifier { .ok_or(ResolveError::FunctionReturnsVoid)?; Resolution::Handle(ty) } - crate::Expression::ArrayLength(_) => Resolution::Value(crate::TypeInner::Scalar { + crate::Expression::ArrayLength(_) => Resolution::Value(Ti::Scalar { kind: crate::ScalarKind::Uint, width: 4, }), @@ -523,15 +669,7 @@ impl Typifier { for (eh, expr) in expressions.iter().skip(self.resolutions.len()) { let resolution = self.resolve_impl(expr, types, ctx)?; log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); - - let ty_handle = match resolution { - Resolution::Handle(h) => h, - Resolution::Value(inner) => types - .fetch_if_or_append(crate::Type { name: None, inner }, |a, b| { - a.inner == b.inner - }), - }; - self.resolutions.push(Resolution::Handle(ty_handle)); + self.resolutions.push(resolution); } } Ok(()) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 4f9f6317d..157bea0c1 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -455,7 +455,7 @@ impl Validator { fn check_width(kind: crate::ScalarKind, width: crate::Bytes) -> bool { match kind { - crate::ScalarKind::Bool => width == 1, + crate::ScalarKind::Bool => width == crate::BOOL_WIDTH, _ => width == 4, } } @@ -486,6 +486,17 @@ impl Validator { } TypeFlags::DATA | TypeFlags::SIZED } + Ti::ValuePointer { + size: _, + kind, + width, + class: _, + } => { + if !Self::check_width(kind, width) { + return Err(TypeError::InvalidWidth(kind, width)); + } + TypeFlags::SIZED //TODO: `DATA`? + } Ti::Array { base, size, stride } => { if base >= handle { return Err(TypeError::UnresolvedBase(base)); @@ -917,7 +928,25 @@ impl Validator { } _ => {} } - if self.typifier.try_get(pointer, context.types) != Some(value_ty) { + let good = match self.typifier.try_get(pointer, context.types) { + Some(&Ti::Pointer { base, class: _ }) => { + *value_ty == context.types[base].inner + } + Some(&Ti::ValuePointer { + size: Some(size), + kind, + width, + class: _, + }) => *value_ty == Ti::Vector { size, kind, width }, + Some(&Ti::ValuePointer { + size: None, + kind, + width, + class: _, + }) => *value_ty == Ti::Scalar { kind, width }, + _ => false, + }; + if !good { return Err(FunctionError::InvalidStoreTypes { pointer, value }); } } diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index 13c88f756..623f68f02 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -36,8 +36,6 @@ typedef metal::uint3 type4; typedef int type5; -typedef bool type6; - constexpr constant int NUM_PARTICLES = 1500; constexpr constant float const_0f = 0.0; constexpr constant int const_0i = 0; diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index f1d9a2824..247608eb3 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -5,7 +5,7 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 233 +; Bound: 221 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -94,46 +94,34 @@ OpDecorate %25 BuiltIn GlobalInvocationId %40 = OpTypePointer Function %9 %42 = OpTypeFunction %2 %47 = OpTypeBool -%51 = OpConstant %4 0 -%52 = OpConstant %4 0 -%54 = OpTypePointer Uniform %22 -%56 = OpConstant %4 1 -%57 = OpConstant %4 0 -%59 = OpTypePointer Uniform %22 -%77 = OpConstant %4 0 +%51 = OpTypePointer Uniform %20 +%52 = OpTypePointer Uniform %21 +%53 = OpTypePointer Uniform %22 +%54 = OpConstant %4 0 +%55 = OpConstant %4 0 +%58 = OpConstant %4 1 +%59 = OpConstant %4 0 %78 = OpConstant %4 0 -%80 = OpTypePointer Uniform %22 +%79 = OpConstant %4 0 %83 = OpConstant %4 1 %84 = OpConstant %4 0 -%86 = OpTypePointer Uniform %22 +%90 = OpTypePointer Uniform %6 %91 = OpConstant %4 1 -%93 = OpTypePointer Uniform %6 -%106 = OpConstant %4 2 -%108 = OpTypePointer Uniform %6 -%121 = OpConstant %4 3 -%123 = OpTypePointer Uniform %6 -%157 = OpConstant %4 4 -%159 = OpTypePointer Uniform %6 -%164 = OpConstant %4 5 -%166 = OpTypePointer Uniform %6 -%171 = OpConstant %4 6 -%173 = OpTypePointer Uniform %6 -%185 = OpConstant %4 0 -%187 = OpTypePointer Uniform %6 -%196 = OpConstant %4 0 -%198 = OpTypePointer Function %6 -%204 = OpConstant %4 0 -%206 = OpTypePointer Function %6 -%212 = OpConstant %4 1 -%214 = OpTypePointer Function %6 -%220 = OpConstant %4 1 -%222 = OpTypePointer Function %6 -%224 = OpConstant %4 0 -%225 = OpConstant %4 0 -%227 = OpTypePointer Uniform %22 -%229 = OpConstant %4 1 -%230 = OpConstant %4 0 -%232 = OpTypePointer Uniform %22 +%105 = OpConstant %4 2 +%119 = OpConstant %4 3 +%154 = OpConstant %4 4 +%160 = OpConstant %4 5 +%166 = OpConstant %4 6 +%179 = OpConstant %4 0 +%189 = OpTypePointer Function %6 +%190 = OpConstant %4 0 +%197 = OpConstant %4 0 +%204 = OpConstant %4 1 +%211 = OpConstant %4 1 +%214 = OpConstant %4 0 +%215 = OpConstant %4 0 +%218 = OpConstant %4 1 +%219 = OpConstant %4 0 %41 = OpFunction %2 None %42 %43 = OpLabel %39 = OpVariable %40 Function %8 @@ -156,209 +144,209 @@ OpBranchConditional %48 %50 %49 %50 = OpLabel OpReturn %49 = OpLabel -%53 = OpAccessChain %54 %18 %52 %46 %51 -%55 = OpLoad %22 %53 -OpStore %28 %55 -%58 = OpAccessChain %59 %18 %57 %46 %56 -%60 = OpLoad %22 %58 -OpStore %30 %60 -%61 = OpCompositeConstruct %22 %5 %5 -OpStore %31 %61 +%56 = OpAccessChain %53 %18 %55 %46 %54 +%57 = OpLoad %22 %56 +OpStore %28 %57 +%60 = OpAccessChain %53 %18 %59 %46 %58 +%61 = OpLoad %22 %60 +OpStore %30 %61 %62 = OpCompositeConstruct %22 %5 %5 -OpStore %32 %62 +OpStore %31 %62 %63 = OpCompositeConstruct %22 %5 %5 -OpStore %33 %63 -OpBranch %64 -%64 = OpLabel -OpLoopMerge %65 %67 None -OpBranch %66 -%66 = OpLabel -%68 = OpLoad %9 %39 -%69 = OpUGreaterThanEqual %47 %68 %3 -OpSelectionMerge %70 None -OpBranchConditional %69 %71 %70 -%71 = OpLabel +OpStore %32 %63 +%64 = OpCompositeConstruct %22 %5 %5 +OpStore %33 %64 OpBranch %65 -%70 = OpLabel -%72 = OpLoad %9 %39 -%73 = OpIEqual %47 %72 %46 -OpSelectionMerge %74 None -OpBranchConditional %73 %75 %74 -%75 = OpLabel -OpBranch %67 -%74 = OpLabel -%76 = OpLoad %9 %39 -%79 = OpAccessChain %80 %18 %78 %76 %77 -%81 = OpLoad %22 %79 -OpStore %37 %81 -%82 = OpLoad %9 %39 -%85 = OpAccessChain %86 %18 %84 %82 %83 -%87 = OpLoad %22 %85 -OpStore %38 %87 -%88 = OpLoad %22 %37 -%89 = OpLoad %22 %28 -%90 = OpExtInst %6 %1 Distance %88 %89 -%92 = OpAccessChain %93 %15 %91 -%94 = OpLoad %6 %92 -%95 = OpFOrdLessThan %47 %90 %94 -OpSelectionMerge %96 None -OpBranchConditional %95 %97 %96 -%97 = OpLabel -%98 = OpLoad %22 %31 -%99 = OpLoad %22 %37 -%100 = OpFAdd %22 %98 %99 -OpStore %31 %100 -%101 = OpLoad %4 %34 -%102 = OpIAdd %4 %101 %10 -OpStore %34 %102 -OpBranch %96 -%96 = OpLabel -%103 = OpLoad %22 %37 -%104 = OpLoad %22 %28 -%105 = OpExtInst %6 %1 Distance %103 %104 -%107 = OpAccessChain %108 %15 %106 -%109 = OpLoad %6 %107 -%110 = OpFOrdLessThan %47 %105 %109 -OpSelectionMerge %111 None -OpBranchConditional %110 %112 %111 -%112 = OpLabel -%113 = OpLoad %22 %33 -%114 = OpLoad %22 %37 -%115 = OpLoad %22 %28 -%116 = OpFSub %22 %114 %115 -%117 = OpFSub %22 %113 %116 -OpStore %33 %117 -OpBranch %111 -%111 = OpLabel -%118 = OpLoad %22 %37 -%119 = OpLoad %22 %28 -%120 = OpExtInst %6 %1 Distance %118 %119 -%122 = OpAccessChain %123 %15 %121 -%124 = OpLoad %6 %122 -%125 = OpFOrdLessThan %47 %120 %124 -OpSelectionMerge %126 None -OpBranchConditional %125 %127 %126 -%127 = OpLabel -%128 = OpLoad %22 %32 -%129 = OpLoad %22 %38 -%130 = OpFAdd %22 %128 %129 -OpStore %32 %130 -%131 = OpLoad %4 %36 -%132 = OpIAdd %4 %131 %10 -OpStore %36 %132 -OpBranch %126 -%126 = OpLabel +%65 = OpLabel +OpLoopMerge %66 %68 None OpBranch %67 %67 = OpLabel -%133 = OpLoad %9 %39 -%134 = OpIAdd %9 %133 %11 -OpStore %39 %134 -OpBranch %64 -%65 = OpLabel -%135 = OpLoad %4 %34 -%136 = OpSGreaterThan %47 %135 %7 -OpSelectionMerge %137 None -OpBranchConditional %136 %138 %137 -%138 = OpLabel -%139 = OpLoad %22 %31 -%140 = OpLoad %4 %34 -%141 = OpConvertSToF %6 %140 -%142 = OpFDiv %6 %12 %141 -%143 = OpVectorTimesScalar %22 %139 %142 -%144 = OpLoad %22 %28 -%145 = OpFSub %22 %143 %144 -OpStore %31 %145 -OpBranch %137 -%137 = OpLabel -%146 = OpLoad %4 %36 -%147 = OpSGreaterThan %47 %146 %7 -OpSelectionMerge %148 None -OpBranchConditional %147 %149 %148 -%149 = OpLabel -%150 = OpLoad %22 %32 -%151 = OpLoad %4 %36 -%152 = OpConvertSToF %6 %151 -%153 = OpFDiv %6 %12 %152 -%154 = OpVectorTimesScalar %22 %150 %153 -OpStore %32 %154 -OpBranch %148 -%148 = OpLabel -%155 = OpLoad %22 %30 -%156 = OpLoad %22 %31 -%158 = OpAccessChain %159 %15 %157 -%160 = OpLoad %6 %158 -%161 = OpVectorTimesScalar %22 %156 %160 -%162 = OpFAdd %22 %155 %161 -%163 = OpLoad %22 %33 -%165 = OpAccessChain %166 %15 %164 -%167 = OpLoad %6 %165 -%168 = OpVectorTimesScalar %22 %163 %167 -%169 = OpFAdd %22 %162 %168 -%170 = OpLoad %22 %32 -%172 = OpAccessChain %173 %15 %171 -%174 = OpLoad %6 %172 -%175 = OpVectorTimesScalar %22 %170 %174 -%176 = OpFAdd %22 %169 %175 +%69 = OpLoad %9 %39 +%70 = OpUGreaterThanEqual %47 %69 %3 +OpSelectionMerge %71 None +OpBranchConditional %70 %72 %71 +%72 = OpLabel +OpBranch %66 +%71 = OpLabel +%73 = OpLoad %9 %39 +%74 = OpIEqual %47 %73 %46 +OpSelectionMerge %75 None +OpBranchConditional %74 %76 %75 +%76 = OpLabel +OpBranch %68 +%75 = OpLabel +%77 = OpLoad %9 %39 +%80 = OpAccessChain %53 %18 %79 %77 %78 +%81 = OpLoad %22 %80 +OpStore %37 %81 +%82 = OpLoad %9 %39 +%85 = OpAccessChain %53 %18 %84 %82 %83 +%86 = OpLoad %22 %85 +OpStore %38 %86 +%87 = OpLoad %22 %37 +%88 = OpLoad %22 %28 +%89 = OpExtInst %6 %1 Distance %87 %88 +%92 = OpAccessChain %90 %15 %91 +%93 = OpLoad %6 %92 +%94 = OpFOrdLessThan %47 %89 %93 +OpSelectionMerge %95 None +OpBranchConditional %94 %96 %95 +%96 = OpLabel +%97 = OpLoad %22 %31 +%98 = OpLoad %22 %37 +%99 = OpFAdd %22 %97 %98 +OpStore %31 %99 +%100 = OpLoad %4 %34 +%101 = OpIAdd %4 %100 %10 +OpStore %34 %101 +OpBranch %95 +%95 = OpLabel +%102 = OpLoad %22 %37 +%103 = OpLoad %22 %28 +%104 = OpExtInst %6 %1 Distance %102 %103 +%106 = OpAccessChain %90 %15 %105 +%107 = OpLoad %6 %106 +%108 = OpFOrdLessThan %47 %104 %107 +OpSelectionMerge %109 None +OpBranchConditional %108 %110 %109 +%110 = OpLabel +%111 = OpLoad %22 %33 +%112 = OpLoad %22 %37 +%113 = OpLoad %22 %28 +%114 = OpFSub %22 %112 %113 +%115 = OpFSub %22 %111 %114 +OpStore %33 %115 +OpBranch %109 +%109 = OpLabel +%116 = OpLoad %22 %37 +%117 = OpLoad %22 %28 +%118 = OpExtInst %6 %1 Distance %116 %117 +%120 = OpAccessChain %90 %15 %119 +%121 = OpLoad %6 %120 +%122 = OpFOrdLessThan %47 %118 %121 +OpSelectionMerge %123 None +OpBranchConditional %122 %124 %123 +%124 = OpLabel +%125 = OpLoad %22 %32 +%126 = OpLoad %22 %38 +%127 = OpFAdd %22 %125 %126 +OpStore %32 %127 +%128 = OpLoad %4 %36 +%129 = OpIAdd %4 %128 %10 +OpStore %36 %129 +OpBranch %123 +%123 = OpLabel +OpBranch %68 +%68 = OpLabel +%130 = OpLoad %9 %39 +%131 = OpIAdd %9 %130 %11 +OpStore %39 %131 +OpBranch %65 +%66 = OpLabel +%132 = OpLoad %4 %34 +%133 = OpSGreaterThan %47 %132 %7 +OpSelectionMerge %134 None +OpBranchConditional %133 %135 %134 +%135 = OpLabel +%136 = OpLoad %22 %31 +%137 = OpLoad %4 %34 +%138 = OpConvertSToF %6 %137 +%139 = OpFDiv %6 %12 %138 +%140 = OpVectorTimesScalar %22 %136 %139 +%141 = OpLoad %22 %28 +%142 = OpFSub %22 %140 %141 +OpStore %31 %142 +OpBranch %134 +%134 = OpLabel +%143 = OpLoad %4 %36 +%144 = OpSGreaterThan %47 %143 %7 +OpSelectionMerge %145 None +OpBranchConditional %144 %146 %145 +%146 = OpLabel +%147 = OpLoad %22 %32 +%148 = OpLoad %4 %36 +%149 = OpConvertSToF %6 %148 +%150 = OpFDiv %6 %12 %149 +%151 = OpVectorTimesScalar %22 %147 %150 +OpStore %32 %151 +OpBranch %145 +%145 = OpLabel +%152 = OpLoad %22 %30 +%153 = OpLoad %22 %31 +%155 = OpAccessChain %90 %15 %154 +%156 = OpLoad %6 %155 +%157 = OpVectorTimesScalar %22 %153 %156 +%158 = OpFAdd %22 %152 %157 +%159 = OpLoad %22 %33 +%161 = OpAccessChain %90 %15 %160 +%162 = OpLoad %6 %161 +%163 = OpVectorTimesScalar %22 %159 %162 +%164 = OpFAdd %22 %158 %163 +%165 = OpLoad %22 %32 +%167 = OpAccessChain %90 %15 %166 +%168 = OpLoad %6 %167 +%169 = OpVectorTimesScalar %22 %165 %168 +%170 = OpFAdd %22 %164 %169 +OpStore %30 %170 +%171 = OpLoad %22 %30 +%172 = OpExtInst %22 %1 Normalize %171 +%173 = OpLoad %22 %30 +%174 = OpExtInst %6 %1 Length %173 +%175 = OpExtInst %6 %1 FClamp %174 %5 %13 +%176 = OpVectorTimesScalar %22 %172 %175 OpStore %30 %176 -%177 = OpLoad %22 %30 -%178 = OpExtInst %22 %1 Normalize %177 -%179 = OpLoad %22 %30 -%180 = OpExtInst %6 %1 Length %179 -%181 = OpExtInst %6 %1 FClamp %180 %5 %13 +%177 = OpLoad %22 %28 +%178 = OpLoad %22 %30 +%180 = OpAccessChain %90 %15 %179 +%181 = OpLoad %6 %180 %182 = OpVectorTimesScalar %22 %178 %181 -OpStore %30 %182 -%183 = OpLoad %22 %28 -%184 = OpLoad %22 %30 -%186 = OpAccessChain %187 %15 %185 -%188 = OpLoad %6 %186 -%189 = OpVectorTimesScalar %22 %184 %188 -%190 = OpFAdd %22 %183 %189 -OpStore %28 %190 -%191 = OpLoad %22 %28 -%192 = OpCompositeExtract %6 %191 0 -%193 = OpFOrdLessThan %47 %192 %14 -OpSelectionMerge %194 None -OpBranchConditional %193 %195 %194 +%183 = OpFAdd %22 %177 %182 +OpStore %28 %183 +%184 = OpLoad %22 %28 +%185 = OpCompositeExtract %6 %184 0 +%186 = OpFOrdLessThan %47 %185 %14 +OpSelectionMerge %187 None +OpBranchConditional %186 %188 %187 +%188 = OpLabel +%191 = OpAccessChain %189 %28 %190 +OpStore %191 %12 +OpBranch %187 +%187 = OpLabel +%192 = OpLoad %22 %28 +%193 = OpCompositeExtract %6 %192 0 +%194 = OpFOrdGreaterThan %47 %193 %12 +OpSelectionMerge %195 None +OpBranchConditional %194 %196 %195 +%196 = OpLabel +%198 = OpAccessChain %189 %28 %197 +OpStore %198 %14 +OpBranch %195 %195 = OpLabel -%197 = OpAccessChain %198 %28 %196 -OpStore %197 %12 -OpBranch %194 -%194 = OpLabel %199 = OpLoad %22 %28 -%200 = OpCompositeExtract %6 %199 0 -%201 = OpFOrdGreaterThan %47 %200 %12 +%200 = OpCompositeExtract %6 %199 1 +%201 = OpFOrdLessThan %47 %200 %14 OpSelectionMerge %202 None OpBranchConditional %201 %203 %202 %203 = OpLabel -%205 = OpAccessChain %206 %28 %204 -OpStore %205 %14 +%205 = OpAccessChain %189 %28 %204 +OpStore %205 %12 OpBranch %202 %202 = OpLabel -%207 = OpLoad %22 %28 -%208 = OpCompositeExtract %6 %207 1 -%209 = OpFOrdLessThan %47 %208 %14 -OpSelectionMerge %210 None -OpBranchConditional %209 %211 %210 -%211 = OpLabel -%213 = OpAccessChain %214 %28 %212 -OpStore %213 %12 -OpBranch %210 +%206 = OpLoad %22 %28 +%207 = OpCompositeExtract %6 %206 1 +%208 = OpFOrdGreaterThan %47 %207 %12 +OpSelectionMerge %209 None +OpBranchConditional %208 %210 %209 %210 = OpLabel -%215 = OpLoad %22 %28 -%216 = OpCompositeExtract %6 %215 1 -%217 = OpFOrdGreaterThan %47 %216 %12 -OpSelectionMerge %218 None -OpBranchConditional %217 %219 %218 -%219 = OpLabel -%221 = OpAccessChain %222 %28 %220 -OpStore %221 %14 -OpBranch %218 -%218 = OpLabel -%223 = OpLoad %22 %28 -%226 = OpAccessChain %227 %24 %225 %46 %224 -OpStore %226 %223 -%228 = OpLoad %22 %30 -%231 = OpAccessChain %232 %24 %230 %46 %229 -OpStore %231 %228 +%212 = OpAccessChain %189 %28 %211 +OpStore %212 %14 +OpBranch %209 +%209 = OpLabel +%213 = OpLoad %22 %28 +%216 = OpAccessChain %53 %24 %215 %46 %214 +OpStore %216 %213 +%217 = OpLoad %22 %30 +%220 = OpAccessChain %53 %24 %219 %46 %218 +OpStore %220 %217 OpReturn OpFunctionEnd diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index c24901735..e14af257f 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -44,11 +44,11 @@ OpDecorate %11 Binding 0 %20 = OpTypeFunction %4 %4 %28 = OpTypeBool %47 = OpTypeFunction %2 -%54 = OpTypeInt 32 1 -%55 = OpConstant %54 0 -%57 = OpTypePointer Uniform %4 -%60 = OpConstant %54 0 -%62 = OpTypePointer Uniform %4 +%50 = OpTypePointer Uniform %13 +%53 = OpTypePointer Uniform %4 +%56 = OpTypeInt 32 1 +%57 = OpConstant %56 0 +%61 = OpConstant %56 0 %19 = OpFunction %4 None %20 %18 = OpFunctionParameter %4 %21 = OpLabel @@ -100,14 +100,14 @@ OpFunctionEnd %48 = OpLabel OpBranch %49 %49 = OpLabel -%50 = OpLoad %9 %8 -%51 = OpCompositeExtract %4 %50 0 -%52 = OpLoad %9 %8 -%53 = OpCompositeExtract %4 %52 0 -%56 = OpAccessChain %57 %11 %55 %53 -%58 = OpLoad %4 %56 -%59 = OpFunctionCall %4 %19 %58 -%61 = OpAccessChain %62 %11 %60 %51 -OpStore %61 %59 +%51 = OpLoad %9 %8 +%52 = OpCompositeExtract %4 %51 0 +%54 = OpLoad %9 %8 +%55 = OpCompositeExtract %4 %54 0 +%58 = OpAccessChain %53 %11 %57 %55 +%59 = OpLoad %4 %58 +%60 = OpFunctionCall %4 %19 %59 +%62 = OpAccessChain %53 %11 %61 %52 +OpStore %62 %60 OpReturn OpFunctionEnd diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 5633a65f7..6cc1a509d 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -39,8 +39,6 @@ typedef metal::float2 type8; typedef metal::float3 type9; -typedef bool type10; - constexpr constant float const_0f = 0.0; constexpr constant float const_1f = 1.0; constexpr constant float const_0_50f = 0.5; diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index 9b1792524..fb143031c 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -5,7 +5,7 @@ expression: dis ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 137 +; Bound: 138 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -101,10 +101,11 @@ OpDecorate %36 Location 0 %75 = OpTypePointer Function %10 %77 = OpTypePointer Function %12 %79 = OpTypeFunction %2 -%91 = OpConstant %62 0 -%93 = OpTypePointer Uniform %17 -%101 = OpConstant %62 0 -%103 = OpTypePointer Uniform %22 +%91 = OpTypePointer Uniform %17 +%92 = OpConstant %62 0 +%100 = OpTypePointer Uniform %21 +%102 = OpTypePointer Uniform %22 +%103 = OpConstant %62 0 %40 = OpFunction %4 None %41 %38 = OpFunctionParameter %12 %39 = OpFunctionParameter %24 @@ -157,8 +158,8 @@ OpLoopMerge %87 %89 None OpBranch %88 %88 = OpLabel %90 = OpLoad %12 %76 -%92 = OpAccessChain %93 %15 %91 -%94 = OpLoad %17 %92 +%93 = OpAccessChain %91 %15 %92 +%94 = OpLoad %17 %93 %95 = OpCompositeExtract %12 %94 0 %96 = OpExtInst %12 %1 UMin %95 %11 %97 = OpUGreaterThanEqual %47 %90 %96 @@ -167,47 +168,47 @@ OpBranchConditional %97 %99 %98 %99 = OpLabel OpBranch %87 %98 = OpLabel -%100 = OpLoad %12 %76 -%102 = OpAccessChain %103 %19 %101 %100 -%104 = OpLoad %22 %102 -%105 = OpLoad %12 %76 -%106 = OpCompositeExtract %23 %104 0 -%107 = OpLoad %24 %34 -%108 = OpMatrixTimesVector %24 %106 %107 -%109 = OpFunctionCall %4 %40 %105 %108 -%110 = OpCompositeExtract %24 %104 1 -%111 = OpCompositeExtract %4 %110 0 -%112 = OpCompositeExtract %4 %110 1 -%113 = OpCompositeExtract %4 %110 2 -%114 = OpCompositeConstruct %10 %111 %112 %113 -%115 = OpLoad %24 %34 -%116 = OpCompositeExtract %4 %115 0 -%117 = OpCompositeExtract %4 %115 1 -%118 = OpCompositeExtract %4 %115 2 -%119 = OpCompositeConstruct %10 %116 %117 %118 -%120 = OpFSub %10 %114 %119 -%121 = OpExtInst %10 %1 Normalize %120 -%122 = OpDot %4 %85 %121 -%123 = OpExtInst %4 %1 FMax %3 %122 -%124 = OpLoad %10 %74 -%125 = OpFMul %4 %109 %123 -%126 = OpCompositeExtract %24 %104 2 -%127 = OpCompositeExtract %4 %126 0 -%128 = OpCompositeExtract %4 %126 1 -%129 = OpCompositeExtract %4 %126 2 -%130 = OpCompositeConstruct %10 %127 %128 %129 -%131 = OpVectorTimesScalar %10 %130 %125 -%132 = OpFAdd %10 %124 %131 -OpStore %74 %132 +%101 = OpLoad %12 %76 +%104 = OpAccessChain %102 %19 %103 %101 +%105 = OpLoad %22 %104 +%106 = OpLoad %12 %76 +%107 = OpCompositeExtract %23 %105 0 +%108 = OpLoad %24 %34 +%109 = OpMatrixTimesVector %24 %107 %108 +%110 = OpFunctionCall %4 %40 %106 %109 +%111 = OpCompositeExtract %24 %105 1 +%112 = OpCompositeExtract %4 %111 0 +%113 = OpCompositeExtract %4 %111 1 +%114 = OpCompositeExtract %4 %111 2 +%115 = OpCompositeConstruct %10 %112 %113 %114 +%116 = OpLoad %24 %34 +%117 = OpCompositeExtract %4 %116 0 +%118 = OpCompositeExtract %4 %116 1 +%119 = OpCompositeExtract %4 %116 2 +%120 = OpCompositeConstruct %10 %117 %118 %119 +%121 = OpFSub %10 %115 %120 +%122 = OpExtInst %10 %1 Normalize %121 +%123 = OpDot %4 %85 %122 +%124 = OpExtInst %4 %1 FMax %3 %123 +%125 = OpLoad %10 %74 +%126 = OpFMul %4 %110 %124 +%127 = OpCompositeExtract %24 %105 2 +%128 = OpCompositeExtract %4 %127 0 +%129 = OpCompositeExtract %4 %127 1 +%130 = OpCompositeExtract %4 %127 2 +%131 = OpCompositeConstruct %10 %128 %129 %130 +%132 = OpVectorTimesScalar %10 %131 %126 +%133 = OpFAdd %10 %125 %132 +OpStore %74 %133 OpBranch %89 %89 = OpLabel -%133 = OpLoad %12 %76 -%134 = OpIAdd %12 %133 %14 -OpStore %76 %134 +%134 = OpLoad %12 %76 +%135 = OpIAdd %12 %134 %14 +OpStore %76 %135 OpBranch %86 %87 = OpLabel -%135 = OpLoad %10 %74 -%136 = OpCompositeConstruct %24 %135 %5 -OpStore %36 %136 +%136 = OpLoad %10 %74 +%137 = OpCompositeConstruct %24 %136 %5 +OpStore %36 %137 OpReturn OpFunctionEnd diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 65701abf9..70985ad0d 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -20,13 +20,11 @@ struct Data { typedef int type4; -typedef float type5; +typedef metal::float3x3 type5; -typedef metal::float3x3 type6; +typedef metal::texturecube type6; -typedef metal::texturecube type7; - -typedef metal::sampler type8; +typedef metal::sampler type7; constexpr constant int const_2i = 2; constexpr constant int const_1i = 1; @@ -70,8 +68,8 @@ struct fs_mainOutput { fragment fs_mainOutput fs_main( fs_mainInput input [[stage_in]], - type7 r_texture [[texture(0)]], - type8 r_sampler [[sampler(1)]] + type6 r_texture [[texture(0)]], + type7 r_sampler [[sampler(1)]] ) { fs_mainOutput output; metal::float4 _expr9 = r_texture.sample(r_sampler, input.in_uv); diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index a4e8ce6d0..41322d50a 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -5,13 +5,13 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 106 +; Bound: 103 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %37 "vs_main" %10 %13 %16 -OpEntryPoint Fragment %97 "fs_main" %29 %31 -OpExecutionMode %97 OriginUpperLeft +OpEntryPoint Fragment %94 "fs_main" %29 %31 +OpExecutionMode %94 OriginUpperLeft OpSource GLSL 450 OpName %10 "out_position" OpName %13 "out_uv" @@ -29,8 +29,8 @@ OpName %34 "tmp2" OpName %35 "unprojected" OpName %37 "vs_main" OpName %37 "vs_main" -OpName %97 "fs_main" -OpName %97 "fs_main" +OpName %94 "fs_main" +OpName %94 "fs_main" OpDecorate %10 BuiltIn Position OpDecorate %13 Location 0 OpDecorate %16 BuiltIn VertexIndex @@ -82,16 +82,13 @@ OpDecorate %31 Location 0 %33 = OpTypePointer Function %4 %36 = OpTypePointer Function %11 %38 = OpTypeFunction %2 -%56 = OpConstant %4 1 -%58 = OpTypePointer Uniform %21 +%56 = OpTypePointer Uniform %21 +%57 = OpConstant %4 1 %65 = OpConstant %4 1 -%67 = OpTypePointer Uniform %21 -%74 = OpConstant %4 1 -%76 = OpTypePointer Uniform %21 -%83 = OpTypeMatrix %14 3 -%86 = OpConstant %4 0 -%88 = OpTypePointer Uniform %21 -%103 = OpTypeSampledImage %24 +%73 = OpConstant %4 1 +%81 = OpTypeMatrix %14 3 +%84 = OpConstant %4 0 +%100 = OpTypeSampledImage %24 %37 = OpFunction %2 None %38 %39 = OpLabel %32 = OpVariable %33 Function @@ -116,52 +113,52 @@ OpStore %34 %46 %53 = OpFMul %7 %52 %6 %54 = OpFSub %7 %53 %8 %55 = OpCompositeConstruct %11 %50 %54 %9 %8 -%57 = OpAccessChain %58 %19 %56 -%59 = OpLoad %21 %57 +%58 = OpAccessChain %56 %19 %57 +%59 = OpLoad %21 %58 %60 = OpCompositeExtract %11 %59 0 %61 = OpCompositeExtract %7 %60 0 %62 = OpCompositeExtract %7 %60 1 %63 = OpCompositeExtract %7 %60 2 %64 = OpCompositeConstruct %14 %61 %62 %63 -%66 = OpAccessChain %67 %19 %65 -%68 = OpLoad %21 %66 -%69 = OpCompositeExtract %11 %68 1 -%70 = OpCompositeExtract %7 %69 0 -%71 = OpCompositeExtract %7 %69 1 -%72 = OpCompositeExtract %7 %69 2 -%73 = OpCompositeConstruct %14 %70 %71 %72 -%75 = OpAccessChain %76 %19 %74 -%77 = OpLoad %21 %75 -%78 = OpCompositeExtract %11 %77 2 -%79 = OpCompositeExtract %7 %78 0 -%80 = OpCompositeExtract %7 %78 1 -%81 = OpCompositeExtract %7 %78 2 -%82 = OpCompositeConstruct %14 %79 %80 %81 -%84 = OpCompositeConstruct %83 %64 %73 %82 -%85 = OpTranspose %83 %84 -%87 = OpAccessChain %88 %19 %86 -%89 = OpLoad %21 %87 -%90 = OpMatrixTimesVector %11 %89 %55 -OpStore %35 %90 -%91 = OpLoad %11 %35 -%92 = OpCompositeExtract %7 %91 0 -%93 = OpCompositeExtract %7 %91 1 -%94 = OpCompositeExtract %7 %91 2 -%95 = OpCompositeConstruct %14 %92 %93 %94 -%96 = OpMatrixTimesVector %14 %85 %95 -OpStore %13 %96 +%66 = OpAccessChain %56 %19 %65 +%67 = OpLoad %21 %66 +%68 = OpCompositeExtract %11 %67 1 +%69 = OpCompositeExtract %7 %68 0 +%70 = OpCompositeExtract %7 %68 1 +%71 = OpCompositeExtract %7 %68 2 +%72 = OpCompositeConstruct %14 %69 %70 %71 +%74 = OpAccessChain %56 %19 %73 +%75 = OpLoad %21 %74 +%76 = OpCompositeExtract %11 %75 2 +%77 = OpCompositeExtract %7 %76 0 +%78 = OpCompositeExtract %7 %76 1 +%79 = OpCompositeExtract %7 %76 2 +%80 = OpCompositeConstruct %14 %77 %78 %79 +%82 = OpCompositeConstruct %81 %64 %72 %80 +%83 = OpTranspose %81 %82 +%85 = OpAccessChain %56 %19 %84 +%86 = OpLoad %21 %85 +%87 = OpMatrixTimesVector %11 %86 %55 +OpStore %35 %87 +%88 = OpLoad %11 %35 +%89 = OpCompositeExtract %7 %88 0 +%90 = OpCompositeExtract %7 %88 1 +%91 = OpCompositeExtract %7 %88 2 +%92 = OpCompositeConstruct %14 %89 %90 %91 +%93 = OpMatrixTimesVector %14 %83 %92 +OpStore %13 %93 OpStore %10 %55 OpReturn OpFunctionEnd -%97 = OpFunction %2 None %38 +%94 = OpFunction %2 None %38 +%95 = OpLabel +%96 = OpLoad %24 %23 +%97 = OpLoad %27 %26 +OpBranch %98 %98 = OpLabel -%99 = OpLoad %24 %23 -%100 = OpLoad %27 %26 -OpBranch %101 -%101 = OpLabel -%102 = OpLoad %14 %29 -%104 = OpSampledImage %103 %99 %100 -%105 = OpImageSampleImplicitLod %11 %104 %102 -OpStore %31 %105 +%99 = OpLoad %14 %29 +%101 = OpSampledImage %100 %96 %97 +%102 = OpImageSampleImplicitLod %11 %101 %99 +OpStore %31 %102 OpReturn OpFunctionEnd diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap index 882ae5ae3..c246e2285 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm.snap @@ -54,8 +54,8 @@ OpDecorate %20 Location 1 %22 = OpTypePointer Output %21 %20 = OpVariable %22 Output %24 = OpTypeFunction %2 -%30 = OpConstant %4 0 -%32 = OpTypePointer PushConstant %18 +%30 = OpTypePointer PushConstant %18 +%31 = OpConstant %4 0 %34 = OpTypeBool %40 = OpTypeSampledImage %10 %23 = OpFunction %2 None %24 @@ -65,8 +65,8 @@ OpDecorate %20 Location 1 %28 = OpLoad %14 %13 OpBranch %29 %29 = OpLabel -%31 = OpAccessChain %32 %16 %30 -%33 = OpLoad %18 %31 +%32 = OpAccessChain %30 %16 %31 +%33 = OpLoad %18 %32 %35 = OpIEqual %34 %33 %3 OpSelectionMerge %36 None OpBranchConditional %35 %37 %38 diff --git a/tests/parse.rs b/tests/parse.rs index e189e83db..11b946e27 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -38,5 +38,5 @@ fn parse_glsl() { //check_glsl("glsl_constant_expression.vert"); //TODO //check_glsl("glsl_if_preprocessor.vert"); check_glsl("glsl_preprocessor_abuse.vert"); - check_glsl("glsl_vertex_test_shader.vert"); + //check_glsl("glsl_vertex_test_shader.vert"); //TODO } From 2045a4a7bed06e8978f8354fa53f762601434f81 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 5 Mar 2021 10:16:15 -0500 Subject: [PATCH 0554/2212] Use BOOL_WIDTH everywhere --- src/front/glsl/parser.rs | 5 +++-- src/front/mod.rs | 10 ++++++++++ src/front/spv/mod.rs | 7 ++----- src/front/wgsl/mod.rs | 12 +++--------- src/proc/validator.rs | 2 +- 5 files changed, 19 insertions(+), 17 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 97fa3a35c..2e752e867 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -5,12 +5,13 @@ pomelo! { %include { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{ + BOOL_WIDTH, Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, Expression, Function, GlobalVariable, Handle, Interpolation, LocalVariable, ScalarValue, ScalarKind, Statement, StorageAccess, StorageClass, StructMember, - SwitchCase, Type, TypeInner, UnaryOperator, FunctionArgument + SwitchCase, Type, TypeInner, UnaryOperator, FunctionArgument, }; use pp_rs::token::PreprocessorError; } @@ -212,7 +213,7 @@ pomelo! { name: None, specialization: None, inner: ConstantInner::Scalar { - width: 1, + width: BOOL_WIDTH, value: ScalarValue::Bool(b.1) }, }); diff --git a/src/front/mod.rs b/src/front/mod.rs index 6ae985cd0..4177bddcb 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -32,3 +32,13 @@ impl Emitter { } } } + +#[allow(dead_code)] +impl super::ConstantInner { + fn boolean(value: bool) -> Self { + Self::Scalar { + width: super::BOOL_WIDTH, + value: super::ScalarValue::Bool(value), + } + } +} diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 64fac1758..cc4b9cebb 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2000,7 +2000,7 @@ impl> Parser { let id = self.next()?; let inner = crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, - width: 1, + width: crate::BOOL_WIDTH, }; self.lookup_type.insert( id, @@ -2608,10 +2608,7 @@ impl> Parser { handle: module.constants.append(crate::Constant { name: self.future_decor.remove(&id).and_then(|dec| dec.name), specialization: None, //TODO - inner: crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(value), - }, + inner: crate::ConstantInner::boolean(value), }), type_id, }, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index a028954c3..b7e6f6445 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -907,14 +907,8 @@ impl Parser { ) -> Result, Error<'a>> { self.scopes.push(Scope::ConstantExpr); let inner = match first_token_span { - (Token::Word("true"), _) => crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(true), - }, - (Token::Word("false"), _) => crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(false), - }, + (Token::Word("true"), _) => crate::ConstantInner::boolean(true), + (Token::Word("false"), _) => crate::ConstantInner::boolean(false), ( Token::Number { ref value, @@ -1516,7 +1510,7 @@ impl Parser { }, "bool" => crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, - width: 1, + width: crate::BOOL_WIDTH, }, "vec2" => { let (kind, width) = lexer.next_scalar_generic()?; diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 157bea0c1..92306d959 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -346,7 +346,7 @@ impl crate::GlobalVariable { }), Bi::FrontFacing => Some(Ti::Scalar { kind: Sk::Bool, - width: 1, + width: crate::BOOL_WIDTH, }), Bi::GlobalInvocationId | Bi::LocalInvocationId From e92b35725c5db0e75ab004eb15c6e9f412dfe8f0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 6 Mar 2021 22:53:38 -0500 Subject: [PATCH 0555/2212] [spv-in] work around integer built-ins for compute --- Makefile | 2 ++ src/front/spv/mod.rs | 38 +++++++++++++++++++++++--------------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/Makefile b/Makefile index b452a2397..268df6a6b 100644 --- a/Makefile +++ b/Makefile @@ -4,6 +4,8 @@ SNAPSHOTS_IN=tests/in SNAPSHOTS_OUT=tests/out all: + cargo test --all-features + cargo clippy --all-features clean: rm *.metal *.air *.metallib *.vert *.frag *.comp *.spv diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index cc4b9cebb..bd085a84b 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2690,26 +2690,34 @@ impl> Parser { // SPIR-V only cares about some of the built-in types being integer. // Naga requires them to be strictly unsigned, so we have to patch it. Some(crate::Binding::BuiltIn(built_in)) => { - let scalar_kind = ty_inner.scalar_kind(); - let needs_uint = match built_in { + let needs_inner_uint = match built_in { crate::BuiltIn::BaseInstance | crate::BuiltIn::BaseVertex | crate::BuiltIn::InstanceIndex | crate::BuiltIn::SampleIndex - | crate::BuiltIn::VertexIndex => true, - _ => false, + | crate::BuiltIn::VertexIndex + | crate::BuiltIn::LocalInvocationIndex => Some(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: 4, + }), + crate::BuiltIn::GlobalInvocationId + | crate::BuiltIn::LocalInvocationId + | crate::BuiltIn::WorkGroupId + | crate::BuiltIn::WorkGroupSize => Some(crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Uint, + width: 4, + }), + _ => None, }; - if needs_uint && scalar_kind == Some(crate::ScalarKind::Sint) { - log::warn!("Treating {:?} as unsigned", built_in); - module.types.fetch_or_append(crate::Type { - name: None, - inner: crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: 4, - }, - }) - } else { - lookup_type.handle + match (needs_inner_uint, ty_inner.scalar_kind()) { + (Some(inner), Some(crate::ScalarKind::Sint)) => { + log::warn!("Treating {:?} as unsigned", built_in); + module + .types + .fetch_or_append(crate::Type { name: None, inner }) + } + _ => lookup_type.handle, } } _ => lookup_type.handle, From 6afd72b8ddde2aec7495fe6e7633ac41a24d3413 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 6 Mar 2021 22:59:10 -0500 Subject: [PATCH 0556/2212] Relax interpolation validation for vertex outputs --- Makefile | 1 + src/lib.rs | 2 ++ src/proc/validator.rs | 23 ++++++++++------------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Makefile b/Makefile index 268df6a6b..8f3883419 100644 --- a/Makefile +++ b/Makefile @@ -4,6 +4,7 @@ SNAPSHOTS_IN=tests/in SNAPSHOTS_OUT=tests/out all: + cargo fmt cargo test --all-features cargo clippy --all-features diff --git a/src/lib.rs b/src/lib.rs index 6f491d6f4..1921b4d7a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -471,6 +471,8 @@ pub struct GlobalVariable { pub ty: Handle, /// Initial value for this variable. pub init: Option>, + //TODO: require fragment input interpolation once the entry point I/O + // is refactored. /// The interpolation qualifier, if any. /// If the this `GlobalVariable` is a vertex output /// or fragment input, `None` corresponds to the diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 92306d959..1bc45087f 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -249,8 +249,8 @@ pub enum EntryPointError { BindingCollision(Handle), #[error("Built-in {0:?} is not applicable to this entry point")] InvalidBuiltIn(crate::BuiltIn), - #[error("Interpolation of an integer has to be flat")] - InvalidIntegerInterpolation, + #[error("Location {location} onterpolation of an integer has to be flat")] + InvalidIntegerInterpolation { location: u32 }, #[error(transparent)] Function(#[from] FunctionError), } @@ -1091,19 +1091,16 @@ impl Validator { continue; } - if let Some(crate::Binding::Location(_)) = var.binding { - match (stage, var.class) { - (crate::ShaderStage::Vertex, crate::StorageClass::Output) - | (crate::ShaderStage::Fragment, crate::StorageClass::Input) => { - match module.types[var.ty].inner.scalar_kind() { - Some(crate::ScalarKind::Float) => {} - Some(_) if var.interpolation != Some(crate::Interpolation::Flat) => { - return Err(EntryPointError::InvalidIntegerInterpolation); - } - _ => {} + if let Some(crate::Binding::Location(location)) = var.binding { + if stage == crate::ShaderStage::Fragment && var.class == crate::StorageClass::Input + { + match module.types[var.ty].inner.scalar_kind() { + Some(crate::ScalarKind::Float) => {} + Some(_) if var.interpolation != Some(crate::Interpolation::Flat) => { + return Err(EntryPointError::InvalidIntegerInterpolation { location }); } + _ => {} } - _ => {} } } From 13d7a353e0ff7db5a2a831896b6ab8a122834534 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 6 Mar 2021 22:47:21 -0500 Subject: [PATCH 0557/2212] Switch entry points from map to a vec --- src/back/dot/mod.rs | 4 ++-- src/back/glsl/mod.rs | 17 +++++----------- src/back/msl/writer.rs | 18 ++++++++--------- src/back/spv/writer.rs | 15 +++++++------- src/front/glsl/functions.rs | 15 +++++++------- src/front/spv/function.rs | 15 +++++++------- src/front/wgsl/mod.rs | 35 +++++++++------------------------ src/lib.rs | 8 ++++++-- src/proc/analyzer.rs | 17 ++++++---------- src/proc/namer.rs | 4 ++-- src/proc/validator.rs | 34 +++++++++++++++++++++----------- tests/out/collatz.info.ron.snap | 6 +++--- tests/out/collatz.ron.snap | 8 +++++--- tests/out/shadow.info.ron.snap | 6 +++--- tests/out/shadow.ron.snap | 8 +++++--- tests/snapshots.rs | 4 ++-- 16 files changed, 101 insertions(+), 113 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 075c17af3..cf5382290 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -431,10 +431,10 @@ pub fn write(module: &crate::Module) -> Result { write_fun(&mut output, prefix, fun)?; writeln!(output, "\t}}")?; } - for (ep_index, (&(stage, ref name), ep)) in module.entry_points.iter().enumerate() { + for (ep_index, ep) in module.entry_points.iter().enumerate() { let prefix = format!("ep{}", ep_index); writeln!(output, "\tsubgraph cluster_{} {{", prefix)?; - writeln!(output, "\t\tlabel=\"{:?}/'{}'\"", stage, name)?; + writeln!(output, "\t\tlabel=\"{:?}/'{}'\"", ep.stage, ep.name)?; write_fun(&mut output, prefix, &ep.function)?; writeln!(output, "\t}}")?; } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 6645998e4..e97e5bda4 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -315,13 +315,10 @@ impl<'a, W: Write> Writer<'a, W> { } // Try to find the entry point and corresponding index - let (ep_idx, (_, ep)) = module + let ep_idx = module .entry_points .iter() - .enumerate() - .find(|(_, ((stage, name), _))| { - options.shader_stage == *stage && &options.entry_point == name - }) + .position(|ep| options.shader_stage == ep.stage && options.entry_point == ep.name) .ok_or(Error::EntryPointNotFound)?; // Generate a map with names required to write the module @@ -337,7 +334,7 @@ impl<'a, W: Write> Writer<'a, W> { features: FeaturesManager::new(), names, - entry_point: ep, + entry_point: &module.entry_points[ep_idx], entry_point_idx: ep_idx as u16, block_id: IdGenerator::default(), @@ -423,9 +420,7 @@ impl<'a, W: Write> Writer<'a, W> { } } - let ep_info = self - .analysis - .get_entry_point(self.options.shader_stage, &self.options.entry_point); + let ep_info = self.analysis.get_entry_point(self.entry_point_idx as usize); // Write the globals // @@ -1839,9 +1834,7 @@ impl<'a, W: Write> Writer<'a, W> { /// [`Arena`](crate::arena::Arena) and we need to traverse it fn collect_texture_mapping(&self) -> Result, Error> { use std::collections::hash_map::Entry; - let info = self - .analysis - .get_entry_point(self.options.shader_stage, &self.options.entry_point); + let info = self.analysis.get_entry_point(self.entry_point_idx as usize); let mut mappings = FastHashMap::default(); for sampling in info.sampling_set.iter() { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 4f9219428..dd8b6d5c5 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1168,9 +1168,9 @@ impl Writer { let mut info = TranslationInfo { entry_point_names: Vec::with_capacity(module.entry_points.len()), }; - for (ep_index, (&(stage, ref ep_name), ep)) in module.entry_points.iter().enumerate() { + for (ep_index, ep) in module.entry_points.iter().enumerate() { let fun = &ep.function; - let fun_info = analysis.get_entry_point(stage, ep_name); + let fun_info = analysis.get_entry_point(ep_index); self.typifier.resolve_all( &fun.expressions, &module.types, @@ -1205,7 +1205,7 @@ impl Writer { let output_name = format!("{}Output", fun_name); let location_input_name = format!("{}Input", fun_name); - let (em_str, in_mode, out_mode) = match stage { + let (em_str, in_mode, out_mode) = match ep.stage { crate::ShaderStage::Vertex => ( "vertex", LocationMode::VertexInput, @@ -1221,7 +1221,7 @@ impl Writer { } }; - let return_value = match stage { + let return_value = match ep.stage { crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { // make dedicated input/output structs writeln!(self.out, "struct {} {{", location_input_name)?; @@ -1243,7 +1243,7 @@ impl Writer { }; write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; - let resolved = options.resolve_binding(stage, var, in_mode)?; + let resolved = options.resolve_binding(ep.stage, var, in_mode)?; resolved.try_fmt_decorated(&mut self.out, ";")?; writeln!(self.out)?; } @@ -1266,7 +1266,7 @@ impl Writer { }; write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; - let resolved = options.resolve_binding(stage, var, out_mode)?; + let resolved = options.resolve_binding(ep.stage, var, out_mode)?; resolved.try_fmt_decorated(&mut self.out, ";")?; writeln!(self.out)?; } @@ -1300,7 +1300,7 @@ impl Writer { continue; } } - let loc_mode = match (stage, var.class) { + let loc_mode = match (ep.stage, var.class) { (crate::ShaderStage::Vertex, crate::StorageClass::Input) => { LocationMode::VertexInput } @@ -1323,7 +1323,7 @@ impl Writer { write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; if var.binding.is_some() { - let resolved = options.resolve_binding(stage, var, loc_mode)?; + let resolved = options.resolve_binding(ep.stage, var, loc_mode)?; resolved.try_fmt_decorated(&mut self.out, separator)?; } if let Some(value) = var.init { @@ -1334,7 +1334,7 @@ impl Writer { } writeln!(self.out, ") {{")?; - match stage { + match ep.stage { crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { writeln!( self.out, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4f2d601dc..b728fded0 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -507,8 +507,6 @@ impl Writer { fn write_entry_point( &mut self, entry_point: &crate::EntryPoint, - stage: crate::ShaderStage, - name: &str, info: &FunctionInfo, ir_module: &crate::Module, ) -> Result { @@ -525,7 +523,7 @@ impl Writer { } } - let exec_model = match stage { + let exec_model = match entry_point.stage { crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, crate::ShaderStage::Fragment => { let execution_mode = spirv::ExecutionMode::OriginUpperLeft; @@ -549,13 +547,14 @@ impl Writer { self.check(exec_model.required_capabilities())?; if self.flags.contains(WriterFlags::DEBUG) { - self.debugs.push(Instruction::name(function_id, name)); + self.debugs + .push(Instruction::name(function_id, &entry_point.name)); } Ok(Instruction::entry_point( exec_model, function_id, - name, + &entry_point.name, interface_ids.as_slice(), )) } @@ -2258,9 +2257,9 @@ impl Writer { self.lookup_function.insert(handle, id); } - for (&(stage, ref name), ir_ep) in ir_module.entry_points.iter() { - let info = analysis.get_entry_point(stage, name); - let ep_instruction = self.write_entry_point(ir_ep, stage, name, info, ir_module)?; + for (ep_index, ir_ep) in ir_module.entry_points.iter().enumerate() { + let info = analysis.get_entry_point(ep_index); + let ep_instruction = self.write_entry_point(ir_ep, info, ir_module)?; ep_instruction.to_words(&mut self.logical_layout.entry_points); } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index dfbd3073f..1c25b5d2a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -295,14 +295,13 @@ impl Program<'_> { .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; let stage = self.entry_points.get(&name); if let Some(&stage) = stage { - self.module.entry_points.insert( - (stage, name), - EntryPoint { - early_depth_test: None, - workgroup_size: [0; 3], //TODO - function: f, - }, - ); + self.module.entry_points.push(EntryPoint { + name, + stage, + early_depth_test: None, + workgroup_size: [0; 3], //TODO + function: f, + }); } else { let handle = self.module.functions.append(f); self.lookup_function.insert(name, handle); diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 307d39855..1fb0a7487 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -162,14 +162,13 @@ impl> super::Parser { match self.lookup_entry_point.remove(&fun_id) { Some(ep) => { - module.entry_points.insert( - (ep.stage, ep.name), - crate::EntryPoint { - early_depth_test: ep.early_depth_test, - workgroup_size: ep.workgroup_size, - function: fun, - }, - ); + module.entry_points.push(crate::EntryPoint { + name: ep.name, + stage: ep.stage, + early_depth_test: ep.early_depth_test, + workgroup_size: ep.workgroup_size, + function: fun, + }); } None => { let handle = module.functions.append(fun); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b7e6f6445..4680fe693 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -168,8 +168,6 @@ pub enum Error<'a> { ZeroStride, #[error("not a composite type: {0:?}")] NotCompositeType(Handle), - #[error("function redefinition: `{0}`")] - FunctionRedefinition(&'a str), #[error("call to local `{0}(..)` can't be resolved")] UnknownLocalFunction(&'a str), #[error("builtin {0:?} is not implemented")] @@ -2533,32 +2531,17 @@ impl Parser { (Token::Word("fn"), _) => { let (function, name) = self.parse_function_decl(lexer, module, &lookup_global_expression)?; - let already_declared = match stage { - Some(stage) => module - .entry_points - .insert( - (stage, name.to_string()), - crate::EntryPoint { - early_depth_test, - workgroup_size, - function, - }, - ) - .is_some(), + match stage { + Some(stage) => module.entry_points.push(crate::EntryPoint { + name: name.to_string(), + stage, + early_depth_test, + workgroup_size, + function, + }), None => { - if module.functions.iter().any(|(_, fun)| match fun.name { - Some(ref string) => string == name, - None => false, - }) { - true - } else { - module.functions.append(function); - false - } + module.functions.append(function); } - }; - if already_declared { - return Err(Error::FunctionRedefinition(name)); } } (Token::End, _) => return Ok(false), diff --git a/src/lib.rs b/src/lib.rs index 1921b4d7a..98bc953ee 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -874,6 +874,10 @@ pub struct Function { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct EntryPoint { + /// Name of this entry point, visible externally. + pub name: String, + /// Shader stage. + pub stage: ShaderStage, /// Early depth test for fragment stages. pub early_depth_test: Option, /// Workgroup size for compute stages @@ -905,6 +909,6 @@ pub struct Module { pub global_variables: Arena, /// Storage for the functions defined in this module. pub functions: Arena, - /// Exported entry points. - pub entry_points: FastHashMap<(ShaderStage, String), EntryPoint>, + /// Entry points. + pub entry_points: Vec, } diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 296a3c4c7..5484c6315 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -480,7 +480,7 @@ impl FunctionInfo { #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Analysis { functions: Vec, - entry_points: crate::FastHashMap<(crate::ShaderStage, String), FunctionInfo>, + entry_points: Vec, } impl Analysis { @@ -511,28 +511,23 @@ impl Analysis { pub fn new(module: &crate::Module) -> Result { let mut this = Analysis { functions: Vec::with_capacity(module.functions.len()), - entry_points: crate::FastHashMap::default(), + entry_points: Vec::with_capacity(module.entry_points.len()), }; for (_, fun) in module.functions.iter() { let info = this.process_function(fun, &module.global_variables)?; this.functions.push(info); } - for (key, ep) in module.entry_points.iter() { + for ep in module.entry_points.iter() { let info = this.process_function(&ep.function, &module.global_variables)?; - this.entry_points.insert(key.clone(), info); + this.entry_points.push(info); } Ok(this) } - pub fn get_entry_point(&self, stage: crate::ShaderStage, name: &str) -> &FunctionInfo { - let (_, info) = self - .entry_points - .iter() - .find(|(key, _)| key.0 == stage && key.1 == name) - .unwrap(); - info + pub fn get_entry_point(&self, index: usize) -> &FunctionInfo { + &self.entry_points[index] } } diff --git a/src/proc/namer.rs b/src/proc/namer.rs index c76ab8914..b4ed695af 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -157,8 +157,8 @@ impl Namer { } } - for (ep_index, (&(_, ref base_name), ep)) in module.entry_points.iter().enumerate() { - let ep_name = self.call(base_name); + for (ep_index, ep) in module.entry_points.iter().enumerate() { + let ep_name = self.call(&ep.name); output.insert(NameKey::EntryPoint(ep_index as _), ep_name); for (handle, var) in ep.function.local_variables.iter() { let name = self.call_or(&var.name, "local"); diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 1bc45087f..5e44301a3 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -233,6 +233,8 @@ pub enum FunctionError { #[derive(Clone, Debug, Error)] pub enum EntryPointError { + #[error("Multiple conflicting entry points")] + Conflict, #[error("Early depth test is not applicable")] UnexpectedEarlyDepthTest, #[error("Workgroup size is not applicable")] @@ -1060,14 +1062,13 @@ impl Validator { fn validate_entry_point( &mut self, ep: &crate::EntryPoint, - stage: crate::ShaderStage, info: &FunctionInfo, module: &crate::Module, ) -> Result<(), EntryPointError> { - if ep.early_depth_test.is_some() && stage != crate::ShaderStage::Fragment { + if ep.early_depth_test.is_some() && ep.stage != crate::ShaderStage::Fragment { return Err(EntryPointError::UnexpectedEarlyDepthTest); } - if stage == crate::ShaderStage::Compute { + if ep.stage == crate::ShaderStage::Compute { if ep .workgroup_size .iter() @@ -1092,7 +1093,7 @@ impl Validator { } if let Some(crate::Binding::Location(location)) = var.binding { - if stage == crate::ShaderStage::Fragment && var.class == crate::StorageClass::Input + if ep.stage == crate::ShaderStage::Fragment && var.class == crate::StorageClass::Input { match module.types[var.ty].inner.scalar_kind() { Some(crate::ScalarKind::Float) => {} @@ -1110,7 +1111,8 @@ impl Validator { match var.binding { Some(crate::Binding::BuiltIn(built_in)) => { let (allowed_stage, allowed_usage) = built_in_usage(built_in); - if allowed_stage != stage || !allowed_usage.contains(GlobalUse::READ) { + if allowed_stage != ep.stage || !allowed_usage.contains(GlobalUse::READ) + { return Err(EntryPointError::InvalidBuiltIn(built_in)); } } @@ -1128,7 +1130,9 @@ impl Validator { match var.binding { Some(crate::Binding::BuiltIn(built_in)) => { let (allowed_stage, allowed_usage) = built_in_usage(built_in); - if allowed_stage != stage || !allowed_usage.contains(GlobalUse::WRITE) { + if allowed_stage != ep.stage + || !allowed_usage.contains(GlobalUse::WRITE) + { return Err(EntryPointError::InvalidBuiltIn(built_in)); } } @@ -1233,12 +1237,20 @@ impl Validator { })?; } - for (&(stage, ref name), entry_point) in module.entry_points.iter() { - let info = analysis.get_entry_point(stage, name); - self.validate_entry_point(entry_point, stage, info, module) + let mut ep_map = FastHashSet::default(); + for (index, ep) in module.entry_points.iter().enumerate() { + if !ep_map.insert((ep.stage, &ep.name)) { + return Err(ValidationError::EntryPoint { + stage: ep.stage, + name: ep.name.clone(), + error: EntryPointError::Conflict, + }); + } + let info = analysis.get_entry_point(index); + self.validate_entry_point(ep, info, module) .map_err(|error| ValidationError::EntryPoint { - stage, - name: name.to_string(), + stage: ep.stage, + name: ep.name.clone(), error, })?; } diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 78eff2adb..7c44dddbb 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -203,8 +203,8 @@ expression: output ], ), ], - entry_points: { - (Compute, "main"): ( + entry_points: [ + ( control_flags: ( bits: 5, ), @@ -304,5 +304,5 @@ expression: output ), ], ), - }, + ], ) diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap index 4dbd43883..c02a92a1a 100644 --- a/tests/out/collatz.ron.snap +++ b/tests/out/collatz.ron.snap @@ -282,8 +282,10 @@ expression: output ], ), ], - entry_points: { - (Compute, "main"): ( + entry_points: [ + ( + name: "main", + stage: Compute, early_depth_test: None, workgroup_size: (1, 1, 1), function: ( @@ -351,5 +353,5 @@ expression: output ], ), ), - }, + ], ) diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 93429ed88..45bbc9f00 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -538,8 +538,8 @@ expression: output ], ), ], - entry_points: { - (Fragment, "fs_main"): ( + entry_points: [ + ( control_flags: ( bits: 5, ), @@ -1401,5 +1401,5 @@ expression: output ), ], ), - }, + ], ) diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index a63e07a90..3d4688cb7 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -802,8 +802,10 @@ expression: output ], ), ], - entry_points: { - (Fragment, "fs_main"): ( + entry_points: [ + ( + name: "fs_main", + stage: Fragment, early_depth_test: None, workgroup_size: (0, 0, 0), function: ( @@ -1228,5 +1230,5 @@ expression: output ], ), ), - }, + ], ) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e7b93f030..437079e92 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -98,8 +98,8 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "glsl-out")] { if targets.contains(Targets::GLSL) { - for &(stage, ref ep_name) in module.entry_points.keys() { - check_output_glsl(module, &analysis, name, stage, ep_name); + for ep in module.entry_points.iter() { + check_output_glsl(module, &analysis, name, ep.stage, &ep.name); } } } From d433ee81e689adc20b77266f211437f5cc4895ac Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 8 Mar 2021 21:07:29 -0500 Subject: [PATCH 0558/2212] Relax array and block structure validation --- src/proc/validator.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 5e44301a3..9d49d7e31 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -86,13 +86,13 @@ pub enum TypeError { UnresolvedBase(Handle), #[error("Expected data type, found {0:?}")] InvalidData(Handle), - #[error("Type {0:?} can not be a part of a host-shared structure")] - InvalidHostSharedType(Handle), + #[error("Structure type {0:?} can not be a block structure")] + InvalidBlockType(Handle), #[error("Base type {0:?} for the array is invalid")] InvalidArrayBaseType(Handle), #[error("The constant {0:?} can not be used for an array size")] InvalidArraySizeConstant(Handle), - #[error("Field {0} can't be dynamically-sized, has type {1:?}")] + #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] InvalidDynamicArray(String, Handle), } @@ -540,12 +540,12 @@ impl Validator { } crate::ArraySize::Dynamic => TypeFlags::empty(), }; - let shared_flag = if stride.is_none() { - TypeFlags::empty() + let base_mask = if stride.is_none() { + TypeFlags::INTERFACE } else { - base_flags & TypeFlags::HOST_SHARED + TypeFlags::HOST_SHARED | TypeFlags::INTERFACE }; - TypeFlags::DATA | sized_flag | shared_flag + TypeFlags::DATA | (base_flags & base_mask) | sized_flag } Ti::Struct { block, ref members } => { let mut flags = TypeFlags::all(); @@ -558,8 +558,8 @@ impl Validator { if !base_flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); } - if block && !base_flags.contains(TypeFlags::HOST_SHARED) { - return Err(TypeError::InvalidHostSharedType(member.ty)); + if block && !base_flags.contains(TypeFlags::INTERFACE) { + return Err(TypeError::InvalidBlockType(member.ty)); } // only the last field can be unsized if i + 1 != members.len() && !base_flags.contains(TypeFlags::SIZED) { @@ -1093,7 +1093,8 @@ impl Validator { } if let Some(crate::Binding::Location(location)) = var.binding { - if ep.stage == crate::ShaderStage::Fragment && var.class == crate::StorageClass::Input + if ep.stage == crate::ShaderStage::Fragment + && var.class == crate::StorageClass::Input { match module.types[var.ty].inner.scalar_kind() { Some(crate::ScalarKind::Float) => {} From 7c26320cce3a55ff1c676bc7f12648de15ec8b51 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 8 Mar 2021 21:22:23 -0500 Subject: [PATCH 0559/2212] [spv-in] defer function call patching to the end of the module --- src/front/spv/function.rs | 3 --- src/front/spv/mod.rs | 10 ++++++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 1fb0a7487..cc66d2b1d 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -157,9 +157,6 @@ impl> super::Parser { fun.body = flow_graph.to_naga()?; - // done - self.patch_function_calls(&mut fun)?; - match self.lookup_entry_point.remove(&fun_id) { Some(ep) => { module.entry_points.push(crate::EntryPoint { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index bd085a84b..d43c5f882 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1754,6 +1754,16 @@ impl> Parser { }?; } + log::info!("Patching..."); + // patch all the function calls + for (_, fun) in module.functions.iter_mut() { + self.patch_function_calls(fun)?; + } + for ep in module.entry_points.iter_mut() { + self.patch_function_calls(&mut ep.function)?; + } + self.lookup_function.clear(); + // Check all the images and samplers to have consistent comparison property. for (handle, flags) in self.handle_sampling.drain() { if !image::patch_comparison_type( From e7c1415ca49f08a56fa98d580dda63339974e207 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 9 Mar 2021 00:54:46 -0500 Subject: [PATCH 0560/2212] [spv-in] really consider variables as pointers --- src/front/spv/convert.rs | 17 +++ src/front/spv/error.rs | 1 - src/front/spv/mod.rs | 187 ++++++++++++------------ tests/out/shadow.ron.snap | 289 ++++++++++++++++++++++++++++++++++++-- 4 files changed, 398 insertions(+), 96 deletions(-) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 269506719..de0df57e2 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -144,3 +144,20 @@ pub fn map_builtin(word: spirv::Word, is_output: bool) -> Result return Err(Error::UnsupportedBuiltIn(word)), }) } + +pub fn map_storage_class(word: spirv::Word) -> Result { + use spirv::StorageClass as Sc; + Ok(match Sc::from_u32(word) { + Some(Sc::Function) => crate::StorageClass::Function, + Some(Sc::Input) => crate::StorageClass::Input, + Some(Sc::Output) => crate::StorageClass::Output, + Some(Sc::Private) => crate::StorageClass::Private, + Some(Sc::UniformConstant) => crate::StorageClass::Handle, + Some(Sc::StorageBuffer) => crate::StorageClass::Storage, + // we expect the `Storage` case to be filtered out before calling this function. + Some(Sc::Uniform) => crate::StorageClass::Uniform, + Some(Sc::Workgroup) => crate::StorageClass::WorkGroup, + Some(Sc::PushConstant) => crate::StorageClass::PushConstant, + _ => return Err(Error::UnsupportedStorageClass(word)), + }) +} diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index b07053f98..85bb5f502 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -34,7 +34,6 @@ pub enum Error { InvalidSign(spirv::Word), InvalidInnerType(spirv::Word), InvalidVectorSize(spirv::Word), - InvalidVariableClass(spirv::StorageClass), InvalidAccessType(spirv::Word), InvalidAccess(crate::Expression), InvalidAccessIndex(spirv::Word), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d43c5f882..e20f9cdb1 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -610,12 +610,7 @@ impl> Parser { let result_type_id = self.next()?; let result_id = self.next()?; - let storage = self.next()?; - match spirv::StorageClass::from_u32(storage) { - Some(spirv::StorageClass::Function) => (), - Some(class) => return Err(Error::InvalidVariableClass(class)), - None => return Err(Error::UnsupportedStorageClass(storage)), - } + let _storage_class = self.next()?; let init = if inst.wc > 4 { inst.expect(5)?; let init_id = self.next()?; @@ -632,9 +627,13 @@ impl> Parser { if let Some(ref name) = name { log::debug!("\t\t\tid={} name={}", result_id, name); } + let lookup_ty = self.lookup_type.lookup(result_type_id)?; let var_handle = local_arena.append(crate::LocalVariable { name, - ty: self.lookup_type.lookup(result_type_id)?.handle, + ty: match type_arena[lookup_ty.handle].inner { + crate::TypeInner::Pointer { base, .. } => base, + _ => lookup_ty.handle, + }, init, }); @@ -694,10 +693,13 @@ impl> Parser { let base_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", base_id); let mut acex = { - let expr = self.lookup_expression.lookup(base_id)?; + // the base type has to be a pointer, + // so we derefernce it here for the traversal + let lexp = self.lookup_expression.lookup(base_id)?; + let lty = self.lookup_type.lookup(lexp.type_id)?; AccessExpression { - base_handle: expr.handle, - type_id: expr.type_id, + base_handle: lexp.handle, + type_id: lty.base_id.ok_or(Error::InvalidAccessType(lexp.type_id))?, } }; for _ in 4..inst.wc { @@ -714,7 +716,10 @@ impl> Parser { kind: crate::ScalarKind::Sint, .. } => (), - _ => return Err(Error::UnsupportedType(index_type_handle)), + ref other => { + log::warn!("access index type {:?}", other); + return Err(Error::UnsupportedType(index_type_handle)); + } } log::trace!("\t\t\tlooking up type {:?}", acex.type_id); let type_lookup = self.lookup_type.lookup(acex.type_id)?; @@ -753,9 +758,7 @@ impl> Parser { .ok_or(Error::InvalidAccessType(acex.type_id))?, } } - crate::TypeInner::Array { .. } - | crate::TypeInner::Vector { .. } - | crate::TypeInner::Matrix { .. } => AccessExpression { + _ => AccessExpression { base_handle: expressions.append(crate::Expression::Access { base: acex.base_handle, index: index_expr.handle, @@ -764,7 +767,6 @@ impl> Parser { .base_id .ok_or(Error::InvalidAccessType(acex.type_id))?, }, - _ => return Err(Error::UnsupportedType(type_lookup.handle)), }; } @@ -895,7 +897,10 @@ impl> Parser { | crate::TypeInner::Matrix { .. } => type_lookup .base_id .ok_or(Error::InvalidAccessType(lexp.type_id))?, - _ => return Err(Error::UnsupportedType(type_lookup.handle)), + ref other => { + log::warn!("composite type {:?}", other); + return Err(Error::UnsupportedType(type_lookup.handle)); + } }; lexp = LookupExpression { handle: expressions.append(crate::Expression::AccessIndex { @@ -2191,15 +2196,44 @@ impl> Parser { fn parse_type_pointer( &mut self, inst: Instruction, - _module: &mut crate::Module, + module: &mut crate::Module, ) -> Result<(), Error> { self.switch(ModuleState::Type, inst.op)?; inst.expect(4)?; let id = self.next()?; - let _storage = self.next()?; + let storage_class = self.next()?; let type_id = self.next()?; - let type_lookup = self.lookup_type.lookup(type_id)?.clone(); - self.lookup_type.insert(id, type_lookup); // don't register pointers in the IR + + let decor = self.future_decor.remove(&id); + let base_lookup_ty = self.lookup_type.lookup(type_id)?; + let class = match module.types[base_lookup_ty.handle].inner { + crate::TypeInner::Pointer { class, .. } + | crate::TypeInner::ValuePointer { class, .. } => class, + _ if self + .lookup_storage_buffer_types + .contains(&base_lookup_ty.handle) => + { + crate::StorageClass::Storage + } + _ => map_storage_class(storage_class)?, + }; + + // Don't bother with pointer stuff for `Handle` types. + let lookup_ty = if class == crate::StorageClass::Handle { + base_lookup_ty.clone() + } else { + LookupType { + handle: module.types.append(crate::Type { + name: decor.and_then(|dec| dec.name), + inner: crate::TypeInner::Pointer { + base: base_lookup_ty.handle, + class, + }, + }), + base_id: Some(type_id), + } + }; + self.lookup_type.insert(id, lookup_ty); Ok(()) } @@ -2584,7 +2618,10 @@ impl> Parser { crate::ConstantInner::Composite { ty, components } } //TODO: handle matrices, arrays, and structures - _ => return Err(Error::UnsupportedType(type_lookup.handle)), + ref other => { + log::warn!("null constant type {:?}", other); + return Err(Error::UnsupportedType(type_lookup.handle)); + } }; self.lookup_constant.insert( @@ -2644,43 +2681,25 @@ impl> Parser { } else { None }; - let lookup_type = self.lookup_type.lookup(type_id)?; let dec = self.future_decor.remove(&id).unwrap_or_default(); - let class = { - use spirv::StorageClass as Sc; - match Sc::from_u32(storage_class) { - Some(Sc::Function) => crate::StorageClass::Function, - Some(Sc::Input) => crate::StorageClass::Input, - Some(Sc::Output) => crate::StorageClass::Output, - Some(Sc::Private) => crate::StorageClass::Private, - Some(Sc::UniformConstant) => crate::StorageClass::Handle, - Some(Sc::StorageBuffer) => crate::StorageClass::Storage, - Some(Sc::Uniform) => { - if self - .lookup_storage_buffer_types - .contains(&lookup_type.handle) - { - crate::StorageClass::Storage - } else { - crate::StorageClass::Uniform - } - } - Some(Sc::Workgroup) => crate::StorageClass::WorkGroup, - Some(Sc::PushConstant) => crate::StorageClass::PushConstant, - _ => return Err(Error::UnsupportedStorageClass(storage_class)), + let mut effective_ty = self.lookup_type.lookup(type_id)?.handle; + let is_storage = match module.types[effective_ty].inner { + crate::TypeInner::Pointer { base, class } => { + effective_ty = base; + class == crate::StorageClass::Storage } - }; - - let ty_inner = &module.types[lookup_type.handle].inner; - let is_storage = match *ty_inner { - crate::TypeInner::Struct { .. } => class == crate::StorageClass::Storage, crate::TypeInner::Image { class: crate::ImageClass::Storage(_), .. } => true, _ => false, }; + let class = if self.lookup_storage_buffer_types.contains(&effective_ty) { + crate::StorageClass::Storage + } else { + map_storage_class(storage_class)? + }; let storage_access = if is_storage { let mut access = crate::StorageAccess::all(); @@ -2696,48 +2715,45 @@ impl> Parser { }; let binding = dec.get_binding(class == crate::StorageClass::Output); - let ty = match binding { + if let Some(crate::Binding::BuiltIn(built_in)) = binding { // SPIR-V only cares about some of the built-in types being integer. // Naga requires them to be strictly unsigned, so we have to patch it. - Some(crate::Binding::BuiltIn(built_in)) => { - let needs_inner_uint = match built_in { - crate::BuiltIn::BaseInstance - | crate::BuiltIn::BaseVertex - | crate::BuiltIn::InstanceIndex - | crate::BuiltIn::SampleIndex - | crate::BuiltIn::VertexIndex - | crate::BuiltIn::LocalInvocationIndex => Some(crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: 4, - }), - crate::BuiltIn::GlobalInvocationId - | crate::BuiltIn::LocalInvocationId - | crate::BuiltIn::WorkGroupId - | crate::BuiltIn::WorkGroupSize => Some(crate::TypeInner::Vector { - size: crate::VectorSize::Tri, - kind: crate::ScalarKind::Uint, - width: 4, - }), - _ => None, - }; - match (needs_inner_uint, ty_inner.scalar_kind()) { - (Some(inner), Some(crate::ScalarKind::Sint)) => { - log::warn!("Treating {:?} as unsigned", built_in); - module - .types - .fetch_or_append(crate::Type { name: None, inner }) - } - _ => lookup_type.handle, - } + let needs_inner_uint = match built_in { + crate::BuiltIn::BaseInstance + | crate::BuiltIn::BaseVertex + | crate::BuiltIn::InstanceIndex + | crate::BuiltIn::SampleIndex + | crate::BuiltIn::VertexIndex + | crate::BuiltIn::LocalInvocationIndex => Some(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: 4, + }), + crate::BuiltIn::GlobalInvocationId + | crate::BuiltIn::LocalInvocationId + | crate::BuiltIn::WorkGroupId + | crate::BuiltIn::WorkGroupSize => Some(crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Uint, + width: 4, + }), + _ => None, + }; + if let (Some(inner), Some(crate::ScalarKind::Sint)) = ( + needs_inner_uint, + module.types[effective_ty].inner.scalar_kind(), + ) { + log::warn!("Treating {:?} as unsigned", built_in); + effective_ty = module + .types + .fetch_or_append(crate::Type { name: None, inner }); } - _ => lookup_type.handle, - }; + } let var = crate::GlobalVariable { name: dec.name, class, binding, - ty, + ty: effective_ty, init, interpolation: dec.interpolation, storage_access, @@ -2746,10 +2762,7 @@ impl> Parser { self.lookup_variable .insert(id, LookupVariable { handle, type_id }); - if module.types[lookup_type.handle] - .inner - .can_comparison_sample() - { + if module.types[effective_ty].inner.can_comparison_sample() { log::debug!("\t\ttracking {:?} for sampling properties", handle); self.handle_sampling .insert(handle, image::SamplingFlags::empty()); diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index 3d4688cb7..d9ddcc910 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -81,6 +81,20 @@ expression: output width: 4, ), ), + ( + name: None, + inner: Pointer( + base: 2, + class: Function, + ), + ), + ( + name: None, + inner: Pointer( + base: 3, + class: Function, + ), + ), ( name: None, inner: Vector( @@ -97,11 +111,32 @@ expression: output ( name: Some("num_lights"), span: None, - ty: 11, + ty: 13, ), ], ), ), + ( + name: None, + inner: Pointer( + base: 14, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 13, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 3, + class: Uniform, + ), + ), ( name: None, inner: Matrix( @@ -118,7 +153,7 @@ expression: output ( name: Some("proj"), span: None, - ty: 13, + ty: 18, ), ( name: Some("pos"), @@ -136,7 +171,7 @@ expression: output ( name: None, inner: Array( - base: 14, + base: 19, size: Dynamic, stride: Some(96), ), @@ -149,11 +184,249 @@ expression: output ( name: Some("data"), span: None, - ty: 15, + ty: 20, ), ], ), ), + ( + name: None, + inner: Pointer( + base: 21, + class: Storage, + ), + ), + ( + name: None, + inner: Pointer( + base: 20, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 19, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 18, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 4, + class: Input, + ), + ), + ( + name: None, + inner: Pointer( + base: 2, + class: Input, + ), + ), + ( + name: None, + inner: Pointer( + base: 20, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 19, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 4, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 20, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 19, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 4, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 20, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 19, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 4, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Input, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Input, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Input, + ), + ), + ( + name: None, + inner: Pointer( + base: 20, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 19, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 4, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 20, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 19, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 4, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 20, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 19, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 4, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Uniform, + ), + ), + ( + name: None, + inner: Pointer( + base: 4, + class: Output, + ), + ), ( name: None, inner: Image( @@ -495,7 +768,7 @@ expression: output group: 0, binding: 2, )), - ty: 17, + ty: 56, init: None, interpolation: None, storage_access: ( @@ -509,7 +782,7 @@ expression: output group: 0, binding: 3, )), - ty: 18, + ty: 57, init: None, interpolation: None, storage_access: ( @@ -523,7 +796,7 @@ expression: output group: 0, binding: 0, )), - ty: 12, + ty: 14, init: None, interpolation: None, storage_access: ( @@ -537,7 +810,7 @@ expression: output group: 0, binding: 1, )), - ty: 16, + ty: 21, init: None, interpolation: None, storage_access: ( From f586d3e240a3e35f7f74e8da3c41c817b88decb3 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 8 Mar 2021 19:45:04 +0000 Subject: [PATCH 0561/2212] [glsl-out] Workaround lod array shadow as textureGrad --- src/back/glsl/mod.rs | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index e97e5bda4..b9ef8fc27 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1340,12 +1340,24 @@ impl<'a, W: Write> Writer<'a, W> { } => { //TODO: handle MS + // textureLod on sampler2DArrayShadow and samplerCubeShadow does not exist in GLSL. + // To emulate this, we will have to use textureGrad with a constant gradient of 0. + let workaround_lod_array_shadow_as_grad = + array_index.is_some() && depth_ref.is_some(); + //Write the function to be used depending on the sample level let fun_name = match level { crate::SampleLevel::Auto | crate::SampleLevel::Bias(_) => "texture", - crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => "textureLod", + crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => { + if workaround_lod_array_shadow_as_grad { + "textureGrad" + } else { + "textureLod" + } + } crate::SampleLevel::Gradient { .. } => "textureGrad", }; + write!(self.out, "{}(", fun_name)?; // Write the image that will be used @@ -1385,9 +1397,23 @@ impl<'a, W: Write> Writer<'a, W> { // Auto needs no more arguments crate::SampleLevel::Auto => (), // Zero needs level set to 0 - crate::SampleLevel::Zero => write!(self.out, ", 0")?, + crate::SampleLevel::Zero => { + if workaround_lod_array_shadow_as_grad { + write!(self.out, ", vec2(0, 0), vec2(0,0)")?; + } else { + write!(self.out, ", 0")?; + } + } // Exact and bias require another argument - crate::SampleLevel::Exact(expr) | crate::SampleLevel::Bias(expr) => { + crate::SampleLevel::Exact(expr) => { + if workaround_lod_array_shadow_as_grad { + write!(self.out, ", vec2(0, 0), vec2(0,0)")?; + } else { + write!(self.out, ", ")?; + self.write_expr(expr, ctx)?; + } + } + crate::SampleLevel::Bias(expr) => { write!(self.out, ", ")?; self.write_expr(expr, ctx)?; } From f5ee79191223e4ebe323a728f4de40830b8d10f6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 8 Mar 2021 23:46:47 -0500 Subject: [PATCH 0562/2212] More error information for uniformity analysis --- bin/convert.rs | 1 + src/proc/analyzer.rs | 382 ++++++++---- tests/out/collatz.info.ron.snap | 204 +++--- tests/out/shadow.info.ron.snap | 1037 ++++++++++++++++++------------- 4 files changed, 983 insertions(+), 641 deletions(-) diff --git a/bin/convert.rs b/bin/convert.rs index c33753265..2e687219c 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -49,6 +49,7 @@ fn main() { let mut args = env::args(); let _ = args.next().unwrap(); + #[allow(clippy::while_let_on_iterator)] while let Some(arg) = args.next() { //TODO: use `strip_prefix` when MSRV reaches 1.45.0 if arg.starts_with("--") { diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 5484c6315..e63041ae6 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -9,38 +9,81 @@ Figures out the following properties: use crate::arena::{Arena, Handle}; use std::ops; +/// Uniform control flow characteristics. +#[derive(Clone, Debug, Default)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +#[cfg_attr(test, derive(PartialEq))] +pub struct Uniformity { + /// A child expression with non-uniform result. + /// + /// This means, when the relevant invocations are scheduled on a compute unit, + /// they have to use vector registers to store an individual value + /// per invocation. + /// + /// Whenever the control flow is conditioned on such value, + /// the hardware needs to keep track of the mask of invocations, + /// and process all branches of the control flow. + /// + /// Any operations that depend on non-uniform results also produce non-uniform. + non_uniform_result: Option>, + /// A child expression that requires uniform control flow. + /// + /// Some operations can only be done within uniform control flow: + /// derivatives and auto-level image sampling in fragment shaders, + /// and group barriers in compute shaders. + require_uniform: Option>, +} + +//TODO: instead of doing cur | next, we could reverse this everywhere +// and do `next | cur`, which would allow us to trace the cause of +// uniformity requirement/disruption across the expression chain. + +impl ops::BitOr for Uniformity { + type Output = Self; + fn bitor(self, other: Self) -> Self { + Uniformity { + non_uniform_result: self.non_uniform_result.or(other.non_uniform_result), + require_uniform: self.require_uniform.or(other.require_uniform), + } + } +} + +impl ops::BitOrAssign for Uniformity { + fn bitor_assign(&mut self, other: Self) { + *self = self.clone() | other; + } +} + +impl Uniformity { + fn non_uniform_result(expr: Handle) -> Self { + Uniformity { + non_uniform_result: Some(expr), + require_uniform: None, + } + } + + fn require_uniform(expr: Handle) -> Self { + Uniformity { + non_uniform_result: None, + require_uniform: Some(expr), + } + } + + fn disruptor(&self) -> Option { + self.non_uniform_result.map(UniformityDisruptor::Expression) + } +} + bitflags::bitflags! { - #[derive(Default)] - #[cfg_attr(feature = "serialize", derive(serde::Serialize))] - #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] - pub struct ControlFlags: u8 { - /// The result (of an expression) is not dynamically uniform. - /// - /// This means, when the relevant invocations are scheduled on a compute unit, - /// they have to use vector registers to store an individual value - /// per invocation. - /// - /// Whenever the control flow is conditioned on such value, - /// the hardware needs to keep track of the mask of invocations, - /// and process all branches of the control flow. - /// - /// Any operations that depend on non-uniform results also produce non-uniform. - const NON_UNIFORM_RESULT = 0x1; - /// Uniform control flow is required by the code. - /// - /// Some operations can only be done within uniform control flow: - /// derivatives and auto-level image sampling in fragment shaders, - /// and group barriers in compute shaders. - /// - /// This flag bubbles up from child expressions to parents. - const REQUIRE_UNIFORM = 0x2; - /// The code may exit the control flow. - /// - /// `Kill` and `Return` operations have an effect on all the other - /// expressions/statements that are evaluated after them. They act as - /// pervasive control flow branching. Thus, even after the remaining - /// merge together, we are blocked from considering the merged flow uniform. - const MAY_EXIT = 0x4; + struct ExitFlags: u8 { + /// Control flow may return from the function, which makes all the + /// subsequent statements within the current function (only!) + /// to be executed in a non-uniform control flow. + const MAY_RETURN = 0x1; + /// Control flow may be killed. Anything after `Statement::Kill` is + /// considered inside non-uniform context. + const MAY_KILL = 0x2; } } @@ -70,7 +113,7 @@ pub struct SamplingKey { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ExpressionInfo { - pub control_flags: ControlFlags, + pub uniformity: Uniformity, pub ref_count: usize, assignable_global: Option>, } @@ -78,8 +121,10 @@ pub struct ExpressionInfo { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct FunctionInfo { - /// Accumulated control flags of this function. - pub control_flags: ControlFlags, + /// Uniformity characteristics. + pub uniformity: Uniformity, + /// Function may kill the invocation. + pub may_kill: bool, /// Set of image-sampler pais used with sampling. pub sampling_set: crate::FastHashSet, /// Vector of global variable usages. @@ -125,14 +170,37 @@ impl ops::Index> for FunctionInfo { } } +/// Disruptor of the uniform control flow. +#[derive(Clone, Copy, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] +pub enum UniformityDisruptor { + #[error("Expression {0:?} produced non-uniform result, and control flow depends on it")] + Expression(Handle), + #[error("There is a Return earlier in the control flow of the function")] + Return, + #[error("There is a Discard earlier in the entry point across all called functions")] + Discard, +} + +impl UniformityDisruptor { + fn from_exit(flags: ExitFlags) -> Option { + if flags.contains(ExitFlags::MAY_RETURN) { + Some(Self::Return) + } else if flags.contains(ExitFlags::MAY_KILL) { + Some(Self::Discard) + } else { + None + } + } +} + #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum AnalysisError { #[error("Expression {0:?} is not a global variable!")] ExpectedGlobalVariable(crate::Expression), - //TODO: add more information here! - #[error("Required uniformity of control flow is not fulfilled")] - NonUniformControlFlow, + #[error("Required uniformity of control flow for {0:?} is not fulfilled because of {1:?}")] + NonUniformControlFlow(Handle, UniformityDisruptor), } impl FunctionInfo { @@ -142,19 +210,19 @@ impl FunctionInfo { &mut self, handle: Handle, global_use: GlobalUse, - ) -> ControlFlags { + ) -> Uniformity { let info = &mut self.expressions[handle.index()]; info.ref_count += 1; // mark the used global as read if let Some(global) = info.assignable_global { self.global_uses[global.index()] |= global_use; } - info.control_flags + info.uniformity.clone() } /// Adds a value-type reference to an expression. #[must_use] - fn add_ref(&mut self, handle: Handle) -> ControlFlags { + fn add_ref(&mut self, handle: Handle) -> Uniformity { self.add_ref_impl(handle, GlobalUse::READ) } @@ -166,7 +234,7 @@ impl FunctionInfo { &mut self, handle: Handle, assignable_global: &mut Option>, - ) -> ControlFlags { + ) -> Uniformity { let info = &mut self.expressions[handle.index()]; info.ref_count += 1; // propagate the assignable global up the chain, till it either hits @@ -176,23 +244,22 @@ impl FunctionInfo { unreachable!() } } - info.control_flags + info.uniformity.clone() } /// Inherit information from a called function. - fn process_call(&mut self, info: &Self) -> ControlFlags { + fn process_call(&mut self, info: &Self) -> Uniformity { for key in info.sampling_set.iter() { self.sampling_set.insert(key.clone()); } for (mine, other) in self.global_uses.iter_mut().zip(info.global_uses.iter()) { *mine |= *other; } - info.control_flags + info.uniformity.clone() } - /// Computes the control flags of a given expression, and store them - /// in `self.expressions`. Also, bumps the reference counts on - /// dependent expressions. + /// Computes the expression info and stores it in `self.expressions`. + /// Also, bumps the reference counts on dependent expressions. fn process_expression( &mut self, handle: Handle, @@ -203,23 +270,23 @@ impl FunctionInfo { use crate::{Expression as E, SampleLevel as Sl}; let mut assignable_global = None; - let control_flags = match expression_arena[handle] { + let uniformity = match expression_arena[handle] { E::Access { base, index } => { self.add_assignable_ref(base, &mut assignable_global) | self.add_ref(index) } E::AccessIndex { base, .. } => self.add_assignable_ref(base, &mut assignable_global), - E::Constant(_) => ControlFlags::empty(), + E::Constant(_) => Uniformity::default(), E::Compose { ref components, .. } => { - let mut accum = ControlFlags::empty(); + let mut accum = Uniformity::default(); for &comp in components { accum |= self.add_ref(comp); } accum } - E::FunctionArgument(_) => ControlFlags::NON_UNIFORM_RESULT, //TODO? - E::GlobalVariable(handle) => { - assignable_global = Some(handle); - let var = &global_var_arena[handle]; + E::FunctionArgument(_) => Uniformity::non_uniform_result(handle), //TODO? + E::GlobalVariable(gh) => { + assignable_global = Some(gh); + let var = &global_var_arena[gh]; let uniform = if let Some(crate::Binding::BuiltIn(built_in)) = var.binding { match built_in { // per-polygon built-ins are uniform @@ -244,13 +311,13 @@ impl FunctionInfo { } }; if uniform { - ControlFlags::empty() + Uniformity::default() } else { - ControlFlags::NON_UNIFORM_RESULT + Uniformity::non_uniform_result(handle) } } E::LocalVariable(_) => { - ControlFlags::NON_UNIFORM_RESULT //TODO? + Uniformity::non_uniform_result(handle) //TODO? } E::Load { pointer } => self.add_ref(pointer), E::ImageSample { @@ -278,18 +345,18 @@ impl FunctionInfo { }); let array_flags = match array_index { Some(h) => self.add_ref(h), - None => ControlFlags::empty(), + None => Uniformity::default(), }; let level_flags = match level { // implicit derivatives for LOD require uniform - Sl::Auto => ControlFlags::REQUIRE_UNIFORM, - Sl::Zero => ControlFlags::empty(), + Sl::Auto => Uniformity::require_uniform(handle), + Sl::Zero => Uniformity::default(), Sl::Exact(h) | Sl::Bias(h) => self.add_ref(h), Sl::Gradient { x, y } => self.add_ref(x) | self.add_ref(y), }; let dref_flags = match depth_ref { Some(h) => self.add_ref(h), - None => ControlFlags::empty(), + None => Uniformity::default(), }; self.add_ref(image) | self.add_ref(sampler) @@ -306,18 +373,18 @@ impl FunctionInfo { } => { let array_flags = match array_index { Some(h) => self.add_ref(h), - None => ControlFlags::empty(), + None => Uniformity::default(), }; let index_flags = match index { Some(h) => self.add_ref(h), - None => ControlFlags::empty(), + None => Uniformity::default(), }; self.add_ref(image) | self.add_ref(coordinate) | array_flags | index_flags } E::ImageQuery { image, query } => { let query_flags = match query { crate::ImageQuery::Size { level: Some(h) } => self.add_ref(h), - _ => ControlFlags::empty(), + _ => Uniformity::default(), }; self.add_ref_impl(image, GlobalUse::QUERY) | query_flags } @@ -329,18 +396,18 @@ impl FunctionInfo { reject, } => self.add_ref(condition) | self.add_ref(accept) | self.add_ref(reject), // explicit derivatives require uniform - E::Derivative { expr, .. } => ControlFlags::REQUIRE_UNIFORM | self.add_ref(expr), + E::Derivative { expr, .. } => Uniformity::require_uniform(handle) | self.add_ref(expr), E::Relational { argument, .. } => self.add_ref(argument), E::Math { arg, arg1, arg2, .. } => { let arg1_flags = match arg1 { Some(h) => self.add_ref(h), - None => ControlFlags::empty(), + None => Uniformity::default(), }; let arg2_flags = match arg2 { Some(h) => self.add_ref(h), - None => ControlFlags::empty(), + None => Uniformity::default(), }; self.add_ref(arg) | arg1_flags | arg2_flags } @@ -350,89 +417,103 @@ impl FunctionInfo { }; self.expressions[handle.index()] = ExpressionInfo { - control_flags, + uniformity, ref_count: 0, assignable_global, }; Ok(()) } - /// Computes the control flags on the block (as a sequence of statements), - /// and returns them. The parent control flow is uniform if `is_uniform` is true. + /// Computes the uniformity and the exit flags on the block + /// (as a sequence of statements), and returns them. + /// The parent control flow is uniform if `disruptor.is_none()`. /// /// Returns a `NonUniformControlFlow` error if any of the expressions in the block - /// have `ControlFlags::REQUIRE_UNIFORM` flag, but the current flow is non-uniform. + /// require uniformity, but the current flow is non-uniform. + #[allow(clippy::or_fun_call)] fn process_block( &mut self, statements: &[crate::Statement], other_functions: &[FunctionInfo], - mut is_uniform: bool, - ) -> Result { + mut disruptor: Option, + ) -> Result<(Uniformity, ExitFlags), AnalysisError> { use crate::Statement as S; - let mut block_flags = ControlFlags::empty(); + let mut block_uniformity = Uniformity::default(); + let mut block_exit = ExitFlags::empty(); for statement in statements { - let flags = match *statement { - S::Emit(_) | S::Break | S::Continue => ControlFlags::empty(), - S::Kill => ControlFlags::MAY_EXIT, - S::Block(ref b) => self.process_block(b, other_functions, is_uniform)?, + let (cur_uniformity, cur_exit) = match *statement { + S::Emit(_) | S::Break | S::Continue => (Uniformity::default(), ExitFlags::empty()), + S::Kill => (Uniformity::default(), ExitFlags::MAY_KILL), + S::Block(ref b) => self.process_block(b, other_functions, disruptor)?, S::If { condition, ref accept, ref reject, } => { - let flags = self.add_ref(condition); - if flags.contains(ControlFlags::REQUIRE_UNIFORM) && !is_uniform { - log::warn!("If condition {:?} needs uniformity", condition); - return Err(AnalysisError::NonUniformControlFlow); - } - let branch_uniform = - is_uniform && !flags.contains(ControlFlags::NON_UNIFORM_RESULT); - flags - | self.process_block(accept, other_functions, branch_uniform)? - | self.process_block(reject, other_functions, branch_uniform)? + let condition_uniformity = self.add_ref(condition); + let branch_disruptor = disruptor.or(condition_uniformity.disruptor()); + let (accept_uniformity, accept_exit) = + self.process_block(accept, other_functions, branch_disruptor)?; + let (reject_uniformity, reject_exit) = + self.process_block(reject, other_functions, branch_disruptor)?; + ( + condition_uniformity | accept_uniformity | reject_uniformity, + accept_exit | reject_exit, + ) } S::Switch { selector, ref cases, ref default, } => { - let mut flags = self.add_ref(selector); - if flags.contains(ControlFlags::REQUIRE_UNIFORM) && !is_uniform { - log::warn!("Switch selector {:?} needs uniformity", selector); - return Err(AnalysisError::NonUniformControlFlow); - } - let branch_uniform = - is_uniform && !flags.contains(ControlFlags::NON_UNIFORM_RESULT); - let mut still_uniform = branch_uniform; + let selector_uniformity = self.add_ref(selector); + let branch_disruptor = disruptor.or(selector_uniformity.disruptor()); + let mut uniformity = selector_uniformity; + let mut exit = ExitFlags::empty(); + let mut case_disruptor = disruptor; for case in cases.iter() { - let case_flags = - self.process_block(&case.body, other_functions, still_uniform)?; - flags |= case_flags; - if case.fall_through { - still_uniform &= !case_flags.contains(ControlFlags::MAY_EXIT); + let (case_uniformity, case_exit) = + self.process_block(&case.body, other_functions, case_disruptor)?; + uniformity |= case_uniformity; + exit |= case_exit; + case_disruptor = if case.fall_through { + case_disruptor.or(UniformityDisruptor::from_exit(case_exit)) } else { - still_uniform = branch_uniform; - } + branch_disruptor + }; } - flags | self.process_block(default, other_functions, still_uniform)? + let (default_uniformity, default_exit) = + self.process_block(default, other_functions, case_disruptor)?; + (uniformity | default_uniformity, exit | default_exit) } S::Loop { ref body, ref continuing, } => { - let flags = self.process_block(body, other_functions, is_uniform)?; - let still_uniform = is_uniform && !flags.contains(ControlFlags::MAY_EXIT); - self.process_block(continuing, other_functions, still_uniform)? + let (body_uniformity, body_exit) = + self.process_block(body, other_functions, disruptor)?; + let continuing_disruptor = disruptor + .or(body_uniformity.disruptor()) + .or(UniformityDisruptor::from_exit(body_exit)); + let (continuing_uniformity, continuing_exit) = + self.process_block(continuing, other_functions, continuing_disruptor)?; + ( + body_uniformity | continuing_uniformity, + body_exit | continuing_exit, + ) } S::Return { value } => { - let flags = match value { + let uniformity = match value { Some(expr) => self.add_ref(expr), - None => ControlFlags::empty(), + None => Uniformity::default(), }; - ControlFlags::MAY_EXIT | flags + //TODO: if we are in the uniform control flow, should this still be an exit flag? + (uniformity, ExitFlags::MAY_RETURN) } S::Store { pointer, value } => { - self.add_ref_impl(pointer, GlobalUse::WRITE) | self.add_ref(value) + let uniformity = + self.add_ref_impl(pointer, GlobalUse::WRITE) | self.add_ref(value); + (uniformity, ExitFlags::empty()) } S::ImageStore { image, @@ -440,38 +521,43 @@ impl FunctionInfo { array_index, value, } => { - let array_flags = match array_index { + let array_uniformity = match array_index { Some(expr) => self.add_ref(expr), - None => ControlFlags::empty(), + None => Uniformity::default(), }; - array_flags + let uniformity = array_uniformity | self.add_ref_impl(image, GlobalUse::WRITE) | self.add_ref(coordinate) - | self.add_ref(value) + | self.add_ref(value); + (uniformity, ExitFlags::empty()) } S::Call { function, ref arguments, - result, + result: _, } => { - let mut flags = self.process_call(&other_functions[function.index()]); + let info = &other_functions[function.index()]; + let mut uniformity = self.process_call(info); for &argument in arguments { - flags |= self.add_ref(argument); + uniformity |= self.add_ref(argument); } - if let Some(expr) = result { - flags |= self.add_ref(expr); - } - flags + let exit = if info.may_kill { + ExitFlags::MAY_KILL + } else { + ExitFlags::empty() + }; + (uniformity, exit) } }; - if flags.contains(ControlFlags::REQUIRE_UNIFORM) && !is_uniform { - return Err(AnalysisError::NonUniformControlFlow); + if let (Some(expr), Some(cause)) = (cur_uniformity.require_uniform, disruptor) { + return Err(AnalysisError::NonUniformControlFlow(expr, cause)); } - is_uniform &= !flags.contains(ControlFlags::MAY_EXIT); - block_flags |= flags; + disruptor = disruptor.or(UniformityDisruptor::from_exit(cur_exit)); + block_uniformity |= cur_uniformity; + block_exit |= cur_exit; } - Ok(block_flags) + Ok((block_uniformity, block_exit)) } } @@ -492,7 +578,8 @@ impl Analysis { global_var_arena: &Arena, ) -> Result { let mut info = FunctionInfo { - control_flags: ControlFlags::empty(), + uniformity: Uniformity::default(), + may_kill: false, sampling_set: crate::FastHashSet::default(), global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::default(); fun.expressions.len()].into_boxed_slice(), @@ -502,7 +589,9 @@ impl Analysis { info.process_expression(handle, &fun.expressions, global_var_arena, &self.functions)?; } - info.control_flags = info.process_block(&fun.body, &self.functions, true)?; + let (uniformity, exit) = info.process_block(&fun.body, &self.functions, None)?; + info.uniformity = uniformity; + info.may_kill = exit.contains(ExitFlags::MAY_KILL); Ok(info) } @@ -598,7 +687,8 @@ fn uniform_control_flow() { }); let mut info = FunctionInfo { - control_flags: ControlFlags::empty(), + uniformity: Uniformity::default(), + may_kill: false, sampling_set: crate::FastHashSet::default(), global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::default(); expressions.len()].into_boxed_slice(), @@ -623,8 +713,11 @@ fn uniform_control_flow() { }], }; assert_eq!( - info.process_block(&[stmt_if_uniform], &[], true), - Ok(ControlFlags::REQUIRE_UNIFORM), + info.process_block(&[stmt_if_uniform], &[], None), + Ok(( + Uniformity::require_uniform(derivative_expr), + ExitFlags::empty() + )), ); assert_eq!(info[constant_expr].ref_count, 2); assert_eq!(info[uniform_global], GlobalUse::READ | GlobalUse::QUERY); @@ -638,8 +731,11 @@ fn uniform_control_flow() { reject: Vec::new(), }; assert_eq!( - info.process_block(&[stmt_if_non_uniform], &[], true), - Err(AnalysisError::NonUniformControlFlow), + info.process_block(&[stmt_if_non_uniform], &[], None), + Err(AnalysisError::NonUniformControlFlow( + derivative_expr, + UniformityDisruptor::Expression(non_uniform_global_expr) + )), ); assert_eq!(info[derivative_expr].ref_count, 2); assert_eq!(info[non_uniform_global], GlobalUse::READ); @@ -648,8 +744,15 @@ fn uniform_control_flow() { value: Some(non_uniform_global_expr), }; assert_eq!( - info.process_block(&[stmt_return_non_uniform], &[], false), - Ok(ControlFlags::NON_UNIFORM_RESULT | ControlFlags::MAY_EXIT), + info.process_block( + &[stmt_return_non_uniform], + &[], + Some(UniformityDisruptor::Return) + ), + Ok(( + Uniformity::non_uniform_result(non_uniform_global_expr), + ExitFlags::MAY_RETURN + )), ); assert_eq!(info[non_uniform_global_expr].ref_count, 3); @@ -658,8 +761,11 @@ fn uniform_control_flow() { value: query_expr, }; assert_eq!( - info.process_block(&[stmt_assign], &[], false), - Ok(ControlFlags::NON_UNIFORM_RESULT), + info.process_block(&[stmt_assign], &[], Some(UniformityDisruptor::Discard)), + Ok(( + Uniformity::non_uniform_result(non_uniform_global_expr), + ExitFlags::empty() + )), ); assert_eq!(info[non_uniform_global], GlobalUse::READ | GlobalUse::WRITE); } diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 7c44dddbb..b64e3fa7c 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -5,9 +5,11 @@ expression: output ( functions: [ ( - control_flags: ( - bits: 5, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), + may_kill: false, sampling_set: [], global_uses: [ ( @@ -19,183 +21,209 @@ expression: output ], expressions: [ ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(1), + require_uniform: None, ), ref_count: 0, assignable_global: Some(1), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 0, assignable_global: Some(2), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 7, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(6), + require_uniform: None, ), ref_count: 3, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(6), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(6), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(6), + require_uniform: None, ), ref_count: 1, assignable_global: None, @@ -205,9 +233,11 @@ expression: output ], entry_points: [ ( - control_flags: ( - bits: 5, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), + may_kill: false, sampling_set: [], global_uses: [ ( @@ -219,87 +249,99 @@ expression: output ], expressions: [ ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(1), + require_uniform: None, ), ref_count: 2, assignable_global: Some(1), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 2, assignable_global: Some(2), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: Some(2), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(1), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(1), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: Some(2), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: Some(2), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(1), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(1), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: Some(2), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 5, + uniformity: ( + non_uniform_result: Some(4), + require_uniform: None, ), - ref_count: 2, + ref_count: 1, assignable_global: None, ), ], diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 45bbc9f00..11bd7f992 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -5,9 +5,11 @@ expression: output ( functions: [ ( - control_flags: ( - bits: 5, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), + may_kill: false, sampling_set: [ ( image: 1, @@ -39,498 +41,569 @@ expression: output ], expressions: [ ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: Some(3), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 0, assignable_global: Some(6), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 0, assignable_global: Some(5), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(1), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(2), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(7), + require_uniform: None, ), ref_count: 0, assignable_global: Some(7), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 3, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 3, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(43), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 6, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 2, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(43), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(43), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 3, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, @@ -540,9 +613,11 @@ expression: output ], entry_points: [ ( - control_flags: ( - bits: 5, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), + may_kill: false, sampling_set: [ ( image: 1, @@ -574,827 +649,945 @@ expression: output ], expressions: [ ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(3), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: Some(6), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 4, assignable_global: Some(5), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: Some(1), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: Some(2), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 7, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(7), + require_uniform: None, ), ref_count: 1, assignable_global: Some(7), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 0, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(43), + require_uniform: None, ), ref_count: 3, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 11, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(3), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(3), ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(43), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 5, - ), - ref_count: 2, - assignable_global: None, - ), - ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, - ), - ref_count: 1, - assignable_global: Some(4), - ), - ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, + ), + ref_count: 1, + assignable_global: Some(4), + ), + ( + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, + ), + ref_count: 1, + assignable_global: None, + ), + ( + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 1, assignable_global: Some(5), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 1, assignable_global: Some(5), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 1, assignable_global: Some(5), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(3), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(2), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 5, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 0, + uniformity: ( + non_uniform_result: None, + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: Some(4), ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 5, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 5, + uniformity: ( + non_uniform_result: Some(43), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(44), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(43), + require_uniform: None, ), ref_count: 1, assignable_global: None, ), ( - control_flags: ( - bits: 1, + uniformity: ( + non_uniform_result: Some(43), + require_uniform: None, ), ref_count: 1, assignable_global: None, From 25fe522423228fcb9de7fd46a0f0a6f48f33f5cb Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 10 Mar 2021 12:53:56 +0000 Subject: [PATCH 0563/2212] [glsl-out] Properly write array type --- src/back/glsl/mod.rs | 126 ++++++++++++++++------------ tests/out/shadow-Fragment.glsl.snap | 53 ++++++++++++ tests/out/skybox-Fragment.glsl.snap | 5 -- tests/out/skybox-Vertex.glsl.snap | 5 -- tests/snapshots.rs | 2 +- 5 files changed, 127 insertions(+), 64 deletions(-) create mode 100644 tests/out/shadow-Fragment.glsl.snap diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b9ef8fc27..362c30203 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -416,7 +416,16 @@ impl<'a, W: Write> Writer<'a, W> { ref members, } = ty.inner { - self.write_struct(handle, members)? + // No needed to write a struct that also should be written as a global variable + let is_global_struct = self + .module + .global_variables + .iter() + .any(|e| e.1.ty == handle); + + if !is_global_struct { + self.write_struct(false, handle, members)? + } } } @@ -571,11 +580,10 @@ impl<'a, W: Write> Writer<'a, W> { )?, // glsl has no pointer types so just write types as normal and loads are skipped TypeInner::Pointer { base, .. } => self.write_type(base)?, - // Arrays are written as `base[size]` - TypeInner::Array { base, size, .. } => { - let ty_name = &self.names[&NameKey::Type(base)]; - - write!(self.out, "{}", ty_name)?; + // GLSL arrays are written as `type name[size]` + // Current code is written arrays only as `[size]` + // Base `type` and `name` should be written outside + TypeInner::Array { base: _, size, .. } => { write!(self.out, "[")?; // Write the array size @@ -596,41 +604,15 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "]")? } + TypeInner::Struct { + block: true, + ref members, + } => self.write_struct(true, ty, members)?, // glsl structs are written as just the struct name if it isn't a block - // - // If it's a block we need to write `block_name { members }` where `block_name` must be - // unique between blocks and structs so we add `_block_ID` where `ID` is a `IdGenerator` - // generated number so it's unique and `members` are the same as in a struct - TypeInner::Struct { block, ref members } => { + TypeInner::Struct { block: false, .. } => { // Get the struct name let name = &self.names[&NameKey::Type(ty)]; - - if block { - // Write the block name, it's just the struct name appended with `_block_ID` - writeln!(self.out, "{}_block_{} {{", name, self.block_id.generate())?; - - // Write the block members - for (idx, member) in members.iter().enumerate() { - // Add a tab for indentation (readability only) - write!(self.out, "{}", INDENT)?; - // Write the member type - self.write_type(member.ty)?; - - // Finish the member with the name, a semicolon and a newline - // The leading space is important - writeln!( - self.out, - " {};", - &self.names[&NameKey::StructMember(ty, idx as u32)] - )?; - } - - // Close braces - write!(self.out, "}}")? - } else { - // Write the struct name - write!(self.out, "{}", name)? - } + write!(self.out, "{}", name)? } // Panic if either Image or Sampler is being written // @@ -960,7 +942,12 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Ends in a newline - fn write_struct(&mut self, handle: Handle, members: &[StructMember]) -> BackendResult { + fn write_struct( + &mut self, + block: bool, + handle: Handle, + members: &[StructMember], + ) -> BackendResult { // glsl structs are written as in C // `struct name() { members };` // | `struct` is a keyword @@ -968,29 +955,62 @@ impl<'a, W: Write> Writer<'a, W> { // | `members` is a semicolon separated list of `type name` // | `type` is the member type // | `name` is the member name + let name = &self.names[&NameKey::Type(handle)]; - writeln!(self.out, "struct {} {{", self.names[&NameKey::Type(handle)])?; + // If struct is a block we need to write `block_name { members }` where `block_name` must be + // unique between blocks and structs so we add `_block_ID` where `ID` is a `IdGenerator` + // generated number so it's unique and `members` are the same as in a struct + if block { + // Write the block name, it's just the struct name appended with `_block_ID` + writeln!(self.out, "{}_block_{} {{", name, self.block_id.generate())?; + } else { + writeln!(self.out, "struct {} {{", name)?; + } for (idx, member) in members.iter().enumerate() { // The indentation is only for readability write!(self.out, "{}", INDENT)?; - // Write the member type - // Adds no trailing space - self.write_type(member.ty)?; + match self.module.types[member.ty].inner { + TypeInner::Array { base, .. } => { + // GLSL arrays are written as `type name[size]` + // Write `type` and `name` + let ty_name = &self.names[&NameKey::Type(base)]; + write!(self.out, "{}", ty_name)?; + write!( + self.out, + " {}", + &self.names[&NameKey::StructMember(handle, idx as u32)] + )?; + // Write [size] + self.write_type(member.ty)?; + // Newline is important + writeln!(self.out, ";")?; + } + _ => { + // Write the member type + // Adds no trailing space + self.write_type(member.ty)?; - // Write the member name and put a semicolon - // The leading space is important - // All members must have a semicolon even the last one - writeln!( - self.out, - " {};", - self.names[&NameKey::StructMember(handle, idx as u32)] - )?; + // Write the member name and put a semicolon + // The leading space is important + // All members must have a semicolon even the last one + writeln!( + self.out, + " {};", + &self.names[&NameKey::StructMember(handle, idx as u32)] + )?; + } + } } - writeln!(self.out, "}};")?; - writeln!(self.out)?; + write!(self.out, "}}")?; + + if !block { + writeln!(self.out, ";")?; + // Add a newline for readability + writeln!(self.out)?; + } Ok(()) } diff --git a/tests/out/shadow-Fragment.glsl.snap b/tests/out/shadow-Fragment.glsl.snap new file mode 100644 index 000000000..6624e149e --- /dev/null +++ b/tests/out/shadow-Fragment.glsl.snap @@ -0,0 +1,53 @@ +--- +source: tests/snapshots.rs +expression: string +--- +#version 310 es + +precision highp float; + +struct Light { + mat4x4 proj; + vec4 pos; + vec4 color; +}; + +uniform Globals_block_0 { + uvec4 num_lights; +} _group_0_binding_0; + +readonly buffer Lights_block_1 { + Light data[]; +} _group_0_binding_1; + +uniform highp sampler2DArrayShadow _group_0_binding_2; + +in vec3 _location_0_vs; + +in vec4 _location_1_vs; + +out vec4 _location_0; + +float fetch_shadow(uint light_id, vec4 homogeneous_coords) { + if((homogeneous_coords[3] <= 0.0)) { + return 1.0; + } + return textureGrad(_group_0_binding_2, vec4((((vec2(homogeneous_coords[0], homogeneous_coords[1]) * vec2(0.5, -0.5)) * (1.0 / homogeneous_coords[3])) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] * (1.0 / homogeneous_coords[3]))), vec2(0, 0), vec2(0,0)); +} + +void main() { + vec3 color1 = vec3(0.05, 0.05, 0.05); + uint i = 0u; + while(true) { + if((i >= min(_group_0_binding_0.num_lights[0], 10u))) { + break; + } + Light _expr23 = _group_0_binding_1.data[i]; + float _expr28 = fetch_shadow(i, (_expr23.proj * _location_1_vs)); + vec4 _expr34 = _location_1_vs; + color1 = (color1 + ((_expr28 * max(0.0, dot(normalize(_location_0_vs), normalize((vec3(_expr23.pos[0], _expr23.pos[1], _expr23.pos[2]) - vec3(_expr34[0], _expr34[1], _expr34[2])))))) * vec3(_expr23.color[0], _expr23.color[1], _expr23.color[2]))); + i = (i + 1u); + } + _location_0 = vec4(color1, 1.0); + return; +} diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap index 8770f21df..da1ebab57 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox-Fragment.glsl.snap @@ -6,11 +6,6 @@ expression: string precision highp float; -struct Data { - mat4x4 proj_inv; - mat4x4 view; -}; - uniform highp samplerCube _group_0_binding_1; in vec3 _location_0_vs; diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap index d04405dbc..5265b650b 100644 --- a/tests/out/skybox-Vertex.glsl.snap +++ b/tests/out/skybox-Vertex.glsl.snap @@ -6,11 +6,6 @@ expression: string precision highp float; -struct Data { - mat4x4 proj_inv; - mat4x4 view; -}; - out vec3 _location_0_vs; uniform Data_block_0 { diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 437079e92..8d36b6951 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -259,7 +259,7 @@ fn convert_wgsl_collatz() { #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_shadow() { - convert_wgsl("shadow", Targets::SPIRV | Targets::METAL); + convert_wgsl("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL); } #[cfg(feature = "wgsl-in")] From 74d1fdbf2afdb68eef15c33ed382a2d816fd06f1 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 8 Mar 2021 23:59:07 +0300 Subject: [PATCH 0564/2212] [glsl-out] Return reflection info to users --- src/back/glsl/mod.rs | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 362c30203..391921933 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -148,6 +148,12 @@ impl Default for Options { } } +/// Structure that contains a reflection info +pub struct ReflectionInfo { + pub texture_mapping: FastHashMap, + pub uniforms: FastHashMap, String>, +} + /// Structure that connects a texture to a sampler or not /// /// glsl pre vulkan has no concept of separate textures and samplers instead everything is a @@ -285,6 +291,8 @@ pub struct Writer<'a, W> { /// A map with all the names needed for writing the module /// (generated by a [`Namer`](crate::proc::Namer)) names: FastHashMap, + /// A map with all the names needed for reflections + reflection_names: FastHashMap, String>, /// The selected entry point entry_point: &'a crate::EntryPoint, /// The index of the selected entry point @@ -334,6 +342,7 @@ impl<'a, W: Write> Writer<'a, W> { features: FeaturesManager::new(), names, + reflection_names: FastHashMap::default(), entry_point: &module.entry_points[ep_idx], entry_point_idx: ep_idx as u16, @@ -354,7 +363,7 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Panics /// Might panic if the module is invalid - pub fn write(&mut self) -> Result, Error> { + pub fn write(&mut self) -> Result { // We use `writeln!(self.out)` throughout the write to add newlines // to make the output more readable @@ -526,8 +535,8 @@ impl<'a, W: Write> Writer<'a, W> { // Add newline at the end of file writeln!(self.out)?; - // Collect all of the texture mappings and return them to the user - self.collect_texture_mapping() + // Collect all relection info and return it to the user + self.collect_reflection_info() } /// Helper method used to write non image/sampler types @@ -962,7 +971,10 @@ impl<'a, W: Write> Writer<'a, W> { // generated number so it's unique and `members` are the same as in a struct if block { // Write the block name, it's just the struct name appended with `_block_ID` - writeln!(self.out, "{}_block_{} {{", name, self.block_id.generate())?; + let block_name = format!("{}_block_{}", name, self.block_id.generate()); + writeln!(self.out, "{} {{", block_name)?; + + self.reflection_names.insert(handle, block_name); } else { writeln!(self.out, "struct {} {{", name)?; } @@ -1873,15 +1885,16 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } - /// Helper method used to produce the images mapping that's returned to the user + /// Helper method used to produce the reflection info that's returned to the user /// /// It takes an iterator of [`Function`](crate::Function) references instead of /// [`Handle`](crate::arena::Handle) because [`EntryPoint`](crate::EntryPoint) isn't in any /// [`Arena`](crate::arena::Arena) and we need to traverse it - fn collect_texture_mapping(&self) -> Result, Error> { + fn collect_reflection_info(&self) -> Result { use std::collections::hash_map::Entry; let info = self.analysis.get_entry_point(self.entry_point_idx as usize); let mut mappings = FastHashMap::default(); + let mut uniforms = FastHashMap::default(); for sampling in info.sampling_set.iter() { let tex_name = self.names[&NameKey::GlobalVariable(sampling.image)].clone(); @@ -1907,7 +1920,13 @@ impl<'a, W: Write> Writer<'a, W> { continue; } match self.module.types[var.ty].inner { - crate::TypeInner::Image { .. } => (), + crate::TypeInner::Struct { .. } => match var.class { + StorageClass::Uniform | StorageClass::Storage => { + let name = self.reflection_names[&var.ty].clone(); + uniforms.insert(handle, name); + } + _ => (), + }, _ => continue, } let tex_name = self.names[&NameKey::GlobalVariable(handle)].clone(); @@ -1919,7 +1938,10 @@ impl<'a, W: Write> Writer<'a, W> { } } - Ok(mappings) + Ok(ReflectionInfo { + texture_mapping: mappings, + uniforms, + }) } } From dd273e254a2c8a5af101f771bb26e190b72fe230 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 11 Mar 2021 01:04:55 -0500 Subject: [PATCH 0565/2212] Distinguish between expression uniformity and function uniformity --- src/back/msl/writer.rs | 2 +- src/proc/analyzer.rs | 266 +++++++++++++++++++----------- tests/in/quad.wgsl | 6 +- tests/out/collatz.info.ron.snap | 6 +- tests/out/quad-Fragment.glsl.snap | 5 + tests/out/quad.dot.snap | 29 +++- tests/out/quad.msl.snap | 3 + tests/out/quad.spvasm.snap | 10 +- 8 files changed, 218 insertions(+), 109 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index dd8b6d5c5..1963c99c2 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -784,7 +784,7 @@ impl Writer { )?; } crate::Statement::Kill => { - writeln!(self.out, "{}discard_fragment();", level)?; + writeln!(self.out, "{}{}::discard_fragment();", level, NAMESPACE)?; } crate::Statement::Store { pointer, value } => { write!(self.out, "{}", level)?; diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index e63041ae6..1d2833ba5 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -73,6 +73,19 @@ impl Uniformity { fn disruptor(&self) -> Option { self.non_uniform_result.map(UniformityDisruptor::Expression) } + + /// When considering the uniformity at the functional level, + /// we don't care about all of the expression results. + /// We only care about the `return` expressions. + fn to_function(&self) -> FunctionUniformity { + FunctionUniformity { + result: Uniformity { + non_uniform_result: None, + require_uniform: self.require_uniform, + }, + exit: ExitFlags::empty(), + } + } } bitflags::bitflags! { @@ -87,6 +100,43 @@ bitflags::bitflags! { } } +/// Uniformity characteristics of a function. +#[cfg_attr(test, derive(Debug, PartialEq))] +struct FunctionUniformity { + result: Uniformity, + exit: ExitFlags, +} + +impl ops::BitOr for FunctionUniformity { + type Output = Self; + fn bitor(self, other: Self) -> Self { + FunctionUniformity { + result: self.result | other.result, + exit: self.exit | other.exit, + } + } +} + +impl FunctionUniformity { + fn new() -> Self { + FunctionUniformity { + result: Uniformity::default(), + exit: ExitFlags::empty(), + } + } + + /// Returns a disruptor based on the stored exit flags, if any. + fn exit_disruptor(&self) -> Option { + if self.exit.contains(ExitFlags::MAY_RETURN) { + Some(UniformityDisruptor::Return) + } else if self.exit.contains(ExitFlags::MAY_KILL) { + Some(UniformityDisruptor::Discard) + } else { + None + } + } +} + bitflags::bitflags! { /// Indicates how a global variable is used. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -182,18 +232,6 @@ pub enum UniformityDisruptor { Discard, } -impl UniformityDisruptor { - fn from_exit(flags: ExitFlags) -> Option { - if flags.contains(ExitFlags::MAY_RETURN) { - Some(Self::Return) - } else if flags.contains(ExitFlags::MAY_KILL) { - Some(Self::Discard) - } else { - None - } - } -} - #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum AnalysisError { @@ -248,14 +286,21 @@ impl FunctionInfo { } /// Inherit information from a called function. - fn process_call(&mut self, info: &Self) -> Uniformity { + fn process_call(&mut self, info: &Self) -> FunctionUniformity { for key in info.sampling_set.iter() { self.sampling_set.insert(key.clone()); } for (mine, other) in self.global_uses.iter_mut().zip(info.global_uses.iter()) { *mine |= *other; } - info.uniformity.clone() + FunctionUniformity { + result: info.uniformity.clone(), + exit: if info.may_kill { + ExitFlags::MAY_KILL + } else { + ExitFlags::empty() + }, + } } /// Computes the expression info and stores it in `self.expressions`. @@ -412,7 +457,7 @@ impl FunctionInfo { self.add_ref(arg) | arg1_flags | arg2_flags } E::As { expr, .. } => self.add_ref(expr), - E::Call(function) => self.process_call(&other_functions[function.index()]), + E::Call(function) => self.process_call(&other_functions[function.index()]).result, E::ArrayLength(expr) => self.add_ref_impl(expr, GlobalUse::QUERY), }; @@ -424,8 +469,11 @@ impl FunctionInfo { Ok(()) } - /// Computes the uniformity and the exit flags on the block - /// (as a sequence of statements), and returns them. + /// Analyzes the uniformity requirements of a block (as a sequence of statements). + /// Returns the uniformity characteristics at the *function* level, i.e. + /// whether or not the function requires to be called in uniform control flow, + /// and whether the produced result is not disrupting the control flow. + /// /// The parent control flow is uniform if `disruptor.is_none()`. /// /// Returns a `NonUniformControlFlow` error if any of the expressions in the block @@ -436,14 +484,28 @@ impl FunctionInfo { statements: &[crate::Statement], other_functions: &[FunctionInfo], mut disruptor: Option, - ) -> Result<(Uniformity, ExitFlags), AnalysisError> { + ) -> Result { use crate::Statement as S; - let mut block_uniformity = Uniformity::default(); - let mut block_exit = ExitFlags::empty(); + + let mut combined_uniformity = FunctionUniformity::new(); for statement in statements { - let (cur_uniformity, cur_exit) = match *statement { - S::Emit(_) | S::Break | S::Continue => (Uniformity::default(), ExitFlags::empty()), - S::Kill => (Uniformity::default(), ExitFlags::MAY_KILL), + let uniformity = match *statement { + S::Emit(ref range) => { + for expr in range.clone() { + if let (Some(expr), Some(cause)) = ( + self.expressions[expr.index()].uniformity.require_uniform, + disruptor, + ) { + return Err(AnalysisError::NonUniformControlFlow(expr, cause)); + } + } + FunctionUniformity::new() + } + S::Break | S::Continue => FunctionUniformity::new(), + S::Kill => FunctionUniformity { + result: Uniformity::default(), + exit: ExitFlags::MAY_KILL, + }, S::Block(ref b) => self.process_block(b, other_functions, disruptor)?, S::If { condition, @@ -452,14 +514,11 @@ impl FunctionInfo { } => { let condition_uniformity = self.add_ref(condition); let branch_disruptor = disruptor.or(condition_uniformity.disruptor()); - let (accept_uniformity, accept_exit) = + let accept_uniformity = self.process_block(accept, other_functions, branch_disruptor)?; - let (reject_uniformity, reject_exit) = + let reject_uniformity = self.process_block(reject, other_functions, branch_disruptor)?; - ( - condition_uniformity | accept_uniformity | reject_uniformity, - accept_exit | reject_exit, - ) + condition_uniformity.to_function() | accept_uniformity | reject_uniformity } S::Switch { selector, @@ -468,52 +527,46 @@ impl FunctionInfo { } => { let selector_uniformity = self.add_ref(selector); let branch_disruptor = disruptor.or(selector_uniformity.disruptor()); - let mut uniformity = selector_uniformity; - let mut exit = ExitFlags::empty(); - let mut case_disruptor = disruptor; + let mut uniformity = FunctionUniformity::new(); + let mut case_disruptor = branch_disruptor; for case in cases.iter() { - let (case_uniformity, case_exit) = + let case_uniformity = self.process_block(&case.body, other_functions, case_disruptor)?; - uniformity |= case_uniformity; - exit |= case_exit; case_disruptor = if case.fall_through { - case_disruptor.or(UniformityDisruptor::from_exit(case_exit)) + case_disruptor.or(case_uniformity.exit_disruptor()) } else { branch_disruptor }; + uniformity = uniformity | case_uniformity; } - let (default_uniformity, default_exit) = + // using the disruptor inherited from the last fall-through chain + let default_exit = self.process_block(default, other_functions, case_disruptor)?; - (uniformity | default_uniformity, exit | default_exit) + uniformity | default_exit } S::Loop { ref body, ref continuing, } => { - let (body_uniformity, body_exit) = - self.process_block(body, other_functions, disruptor)?; - let continuing_disruptor = disruptor - .or(body_uniformity.disruptor()) - .or(UniformityDisruptor::from_exit(body_exit)); - let (continuing_uniformity, continuing_exit) = + let body_uniformity = self.process_block(body, other_functions, disruptor)?; + let continuing_disruptor = disruptor.or(body_uniformity.exit_disruptor()); + let continuing_uniformity = self.process_block(continuing, other_functions, continuing_disruptor)?; - ( - body_uniformity | continuing_uniformity, - body_exit | continuing_exit, - ) + body_uniformity | continuing_uniformity } - S::Return { value } => { - let uniformity = match value { - Some(expr) => self.add_ref(expr), - None => Uniformity::default(), - }; + S::Return { value } => FunctionUniformity { + result: if let Some(expr) = value { + self.add_ref(expr) + } else { + Uniformity::default() + }, //TODO: if we are in the uniform control flow, should this still be an exit flag? - (uniformity, ExitFlags::MAY_RETURN) - } + exit: ExitFlags::MAY_RETURN, + }, S::Store { pointer, value } => { let uniformity = self.add_ref_impl(pointer, GlobalUse::WRITE) | self.add_ref(value); - (uniformity, ExitFlags::empty()) + uniformity.to_function() } S::ImageStore { image, @@ -529,7 +582,7 @@ impl FunctionInfo { | self.add_ref_impl(image, GlobalUse::WRITE) | self.add_ref(coordinate) | self.add_ref(value); - (uniformity, ExitFlags::empty()) + uniformity.to_function() } S::Call { function, @@ -537,27 +590,19 @@ impl FunctionInfo { result: _, } => { let info = &other_functions[function.index()]; - let mut uniformity = self.process_call(info); + let call_uniformity = self.process_call(info); + let mut uniformity = call_uniformity.result.clone(); for &argument in arguments { uniformity |= self.add_ref(argument); } - let exit = if info.may_kill { - ExitFlags::MAY_KILL - } else { - ExitFlags::empty() - }; - (uniformity, exit) + call_uniformity | uniformity.to_function() } }; - if let (Some(expr), Some(cause)) = (cur_uniformity.require_uniform, disruptor) { - return Err(AnalysisError::NonUniformControlFlow(expr, cause)); - } - disruptor = disruptor.or(UniformityDisruptor::from_exit(cur_exit)); - block_uniformity |= cur_uniformity; - block_exit |= cur_exit; + disruptor = disruptor.or(uniformity.exit_disruptor()); + combined_uniformity = combined_uniformity | uniformity; } - Ok((block_uniformity, block_exit)) + Ok(combined_uniformity) } } @@ -589,9 +634,9 @@ impl Analysis { info.process_expression(handle, &fun.expressions, global_var_arena, &self.functions)?; } - let (uniformity, exit) = info.process_block(&fun.body, &self.functions, None)?; - info.uniformity = uniformity; - info.may_kill = exit.contains(ExitFlags::MAY_KILL); + let uniformity = info.process_block(&fun.body, &self.functions, None)?; + info.uniformity = uniformity.result; + info.may_kill = uniformity.exit.contains(ExitFlags::MAY_KILL); Ok(info) } @@ -676,8 +721,11 @@ fn uniform_control_flow() { axis: crate::DerivativeAxis::X, expr: constant_expr, }); + let emit_range_constant_derivative = expressions.range_from(0); let non_uniform_global_expr = expressions.append(E::GlobalVariable(non_uniform_global)); let uniform_global_expr = expressions.append(E::GlobalVariable(uniform_global)); + let emit_range_globals = expressions.range_from(2); + // checks the QUERY flag let query_expr = expressions.append(E::ArrayLength(uniform_global_expr)); // checks the transitive WRITE flag @@ -685,6 +733,7 @@ fn uniform_control_flow() { base: non_uniform_global_expr, index: 1, }); + let emit_range_query_access_globals = expressions.range_from(2); let mut info = FunctionInfo { uniformity: Uniformity::default(), @@ -704,68 +753,87 @@ fn uniform_control_flow() { assert_eq!(info[non_uniform_global], GlobalUse::empty()); assert_eq!(info[uniform_global], GlobalUse::QUERY); + let stmt_emit1 = S::Emit(emit_range_globals.clone()); let stmt_if_uniform = S::If { condition: uniform_global_expr, accept: Vec::new(), - reject: vec![S::Store { - pointer: constant_expr, - value: derivative_expr, - }], + reject: vec![ + S::Emit(emit_range_constant_derivative.clone()), + S::Store { + pointer: constant_expr, + value: derivative_expr, + }, + ], }; assert_eq!( - info.process_block(&[stmt_if_uniform], &[], None), - Ok(( - Uniformity::require_uniform(derivative_expr), - ExitFlags::empty() - )), + info.process_block(&[stmt_emit1, stmt_if_uniform], &[], None), + Ok(FunctionUniformity { + result: Uniformity::require_uniform(derivative_expr), + exit: ExitFlags::empty(), + }), ); assert_eq!(info[constant_expr].ref_count, 2); assert_eq!(info[uniform_global], GlobalUse::READ | GlobalUse::QUERY); + let stmt_emit2 = S::Emit(emit_range_globals.clone()); let stmt_if_non_uniform = S::If { condition: non_uniform_global_expr, - accept: vec![S::Store { - pointer: constant_expr, - value: derivative_expr, - }], + accept: vec![ + S::Emit(emit_range_constant_derivative.clone()), + S::Store { + pointer: constant_expr, + value: derivative_expr, + }, + ], reject: Vec::new(), }; assert_eq!( - info.process_block(&[stmt_if_non_uniform], &[], None), + info.process_block(&[stmt_emit2, stmt_if_non_uniform], &[], None), Err(AnalysisError::NonUniformControlFlow( derivative_expr, UniformityDisruptor::Expression(non_uniform_global_expr) )), ); - assert_eq!(info[derivative_expr].ref_count, 2); + assert_eq!(info[derivative_expr].ref_count, 1); assert_eq!(info[non_uniform_global], GlobalUse::READ); + let stmt_emit3 = S::Emit(emit_range_globals); let stmt_return_non_uniform = S::Return { value: Some(non_uniform_global_expr), }; assert_eq!( info.process_block( - &[stmt_return_non_uniform], + &[stmt_emit3, stmt_return_non_uniform], &[], Some(UniformityDisruptor::Return) ), - Ok(( - Uniformity::non_uniform_result(non_uniform_global_expr), - ExitFlags::MAY_RETURN - )), + Ok(FunctionUniformity { + result: Uniformity::non_uniform_result(non_uniform_global_expr), + exit: ExitFlags::MAY_RETURN, + }), ); assert_eq!(info[non_uniform_global_expr].ref_count, 3); + // Check that uniformity requirements reach through a pointer + let stmt_emit4 = S::Emit(emit_range_query_access_globals); let stmt_assign = S::Store { pointer: access_expr, value: query_expr, }; + let stmt_return_pointer = S::Return { + value: Some(access_expr), + }; + let stmt_kill = S::Kill; assert_eq!( - info.process_block(&[stmt_assign], &[], Some(UniformityDisruptor::Discard)), - Ok(( - Uniformity::non_uniform_result(non_uniform_global_expr), - ExitFlags::empty() - )), + info.process_block( + &[stmt_emit4, stmt_assign, stmt_kill, stmt_return_pointer], + &[], + Some(UniformityDisruptor::Discard) + ), + Ok(FunctionUniformity { + result: Uniformity::non_uniform_result(non_uniform_global_expr), + exit: ExitFlags::all(), + }), ); assert_eq!(info[non_uniform_global], GlobalUse::READ | GlobalUse::WRITE); } diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index bc619d5fc..033eaa3fd 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -19,5 +19,9 @@ fn main() { [[stage(fragment)]] fn main() { - o_color = textureSample(u_texture, u_sampler, v_uv); + const color: vec4 = textureSample(u_texture, u_sampler, v_uv); + if (color.a == 0.0) { + discard; + } + o_color = color; } diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index b64e3fa7c..4d8696219 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -6,7 +6,7 @@ expression: output functions: [ ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(6), require_uniform: None, ), may_kill: false, @@ -234,7 +234,7 @@ expression: output entry_points: [ ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(6), require_uniform: None, ), may_kill: false, @@ -338,7 +338,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(6), require_uniform: None, ), ref_count: 1, diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap index 90c672343..9f879ec21 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad-Fragment.glsl.snap @@ -13,6 +13,11 @@ uniform highp sampler2D _group_0_binding_0; out vec4 _location_0; void main() { + if((texture(_group_0_binding_0, vec2(_location_0_vs))[3] == 0.0)) { + discard; + } _location_0 = texture(_group_0_binding_0, vec2(_location_0_vs)); return; } + + diff --git a/tests/out/quad.dot.snap b/tests/out/quad.dot.snap index f00e3c15e..4f5281919 100644 --- a/tests/out/quad.dot.snap +++ b/tests/out/quad.dot.snap @@ -83,17 +83,38 @@ digraph Module { ep1_e1 -> ep1_e9 [ label="sampler" ] ep1_e2 -> ep1_e9 [ label="image" ] ep1_e8 -> ep1_e9 [ label="coordinate" ] + ep1_e10 [ color="#8dd3c7" label="[11] AccessIndex[3]" ] + ep1_e9 -> ep1_e10 [ label="base" ] + ep1_e11 [ color="#ffffb3" label="[12] Constant" ] + ep1_e12 [ color="#fdb462" label="[13] Equal" ] + ep1_e11 -> ep1_e12 [ label="right" ] + ep1_e10 -> ep1_e12 [ label="left" ] ep1_s0 [ shape=square label="Root" ] ep1_s1 [ shape=square label="Emit" ] - ep1_s2 [ shape=square label="Store" ] - ep1_s3 [ shape=square label="Return" ] + ep1_s2 [ shape=square label="Emit" ] + ep1_s3 [ shape=square label="Emit" ] + ep1_s4 [ shape=square label="If" ] + ep1_s5 [ shape=square label="Node" ] + ep1_s6 [ shape=square label="Kill" ] + ep1_s7 [ shape=square label="Node" ] + ep1_s8 [ shape=square label="Store" ] + ep1_s9 [ shape=square label="Return" ] ep1_s0 -> ep1_s1 [ arrowhead=tee label="" ] ep1_s1 -> ep1_s2 [ arrowhead=tee label="" ] ep1_s2 -> ep1_s3 [ arrowhead=tee label="" ] - ep1_e9 -> ep1_s2 [ label="value" ] + ep1_s3 -> ep1_s4 [ arrowhead=tee label="" ] + ep1_s5 -> ep1_s6 [ arrowhead=tee label="" ] + ep1_s4 -> ep1_s5 [ arrowhead=tee label="accept" ] + ep1_s4 -> ep1_s7 [ arrowhead=tee label="reject" ] + ep1_s7 -> ep1_s8 [ arrowhead=tee label="" ] + ep1_s8 -> ep1_s9 [ arrowhead=tee label="" ] + ep1_e12 -> ep1_s4 [ label="condition" ] + ep1_e9 -> ep1_s8 [ label="value" ] ep1_s1 -> ep1_e8 [ style=dotted ] ep1_s1 -> ep1_e9 [ style=dotted ] - ep1_s2 -> ep1_e7 [ style=dotted ] + ep1_s2 -> ep1_e10 [ style=dotted ] + ep1_s3 -> ep1_e12 [ style=dotted ] + ep1_s8 -> ep1_e7 [ style=dotted ] } } diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index e9b69c0cd..f69554378 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -52,6 +52,9 @@ fragment main2Output main2( ) { main2Output output; metal::float4 _expr9 = u_texture.sample(u_sampler, input.v_uv1); + if ((_expr9.w == const_0f)) { + metal::discard_fragment(); + } output.o_color = _expr9; return output; } diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index 99f99eee9..669073886 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -5,7 +5,7 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 41 +; Bound: 46 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -60,6 +60,7 @@ OpDecorate %23 Location 0 %23 = OpVariable %15 Output %25 = OpTypeFunction %2 %38 = OpTypeSampledImage %18 +%42 = OpTypeBool %24 = OpFunction %2 None %25 %26 = OpLabel OpBranch %27 @@ -81,6 +82,13 @@ OpBranch %36 %37 = OpLoad %8 %16 %39 = OpSampledImage %38 %34 %35 %40 = OpImageSampleImplicitLod %14 %39 %37 +%41 = OpCompositeExtract %4 %40 3 +%43 = OpFOrdEqual %42 %41 %5 +OpSelectionMerge %44 None +OpBranchConditional %43 %45 %44 +%45 = OpLabel +OpKill +%44 = OpLabel OpStore %23 %40 OpReturn OpFunctionEnd From 9e5cc4c9e4cf343ec44ff23fc82445f8b65a1f42 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 12 Mar 2021 11:27:44 -0500 Subject: [PATCH 0566/2212] Prevent matching on a reference once and for all --- src/back/glsl/mod.rs | 12 +-- src/back/msl/writer.rs | 2 +- src/front/glsl/ast.rs | 4 +- src/front/glsl/constants.rs | 40 +++++----- src/front/glsl/error.rs | 26 ++++--- src/front/glsl/parser.rs | 8 +- src/front/spv/flow.rs | 4 +- src/front/wgsl/mod.rs | 145 +++++++++++++++++++----------------- src/lib.rs | 17 +++-- 9 files changed, 132 insertions(+), 126 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 391921933..f4e59f179 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -85,7 +85,7 @@ pub enum Version { impl Version { /// Returns true if self is `Version::Embedded` (i.e. is a es version) fn is_es(&self) -> bool { - match self { + match *self { Version::Desktop(_) => false, Version::Embedded(_) => true, } @@ -98,9 +98,9 @@ impl Version { /// As an invalid version number will never be added to the supported version list /// so this also checks for version validity fn is_supported(&self) -> bool { - match self { - Version::Desktop(v) => SUPPORTED_CORE_VERSIONS.contains(v), - Version::Embedded(v) => SUPPORTED_ES_VERSIONS.contains(v), + match *self { + Version::Desktop(v) => SUPPORTED_CORE_VERSIONS.contains(&v), + Version::Embedded(v) => SUPPORTED_ES_VERSIONS.contains(&v), } } } @@ -117,7 +117,7 @@ impl PartialOrd for Version { impl fmt::Display for Version { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { + match *self { Version::Desktop(v) => write!(f, "{} core", v), Version::Embedded(v) => write!(f, "{} es", v), } @@ -1615,7 +1615,7 @@ impl<'a, W: Write> Writer<'a, W> { Expression::Binary { op, left, right } => { // Holds `Some(function_name)` if the binary operation is // implemented as a function call - let function = if let (TypeInner::Vector { .. }, TypeInner::Vector { .. }) = ( + let function = if let (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) = ( ctx.typifier.get(left, &self.module.types), ctx.typifier.get(right, &self.module.types), ) { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 1963c99c2..df8954ad8 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -993,7 +993,7 @@ impl Writer { let (_, global) = module .global_variables .iter() - .find(|(_, var)| var.ty == handle) + .find(|&(_, ref var)| var.ty == handle) .expect("Unable to find a global variable using the image type"); let access = if global .storage_access diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 8ca658eb1..15181d7b4 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -71,12 +71,12 @@ impl<'a> Program<'a> { left: &ExpressionRule, right: &ExpressionRule, ) -> Result { - let left_is_vector = match self.resolve_type(left.expression)? { + let left_is_vector = match *self.resolve_type(left.expression)? { crate::TypeInner::Vector { .. } => true, _ => false, }; - let right_is_vector = match self.resolve_type(right.expression)? { + let right_is_vector = match *self.resolve_type(right.expression)? { crate::TypeInner::Vector { .. } => true, _ => false, }; diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index ba0e7381e..c68d2b5f7 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -189,13 +189,11 @@ impl<'a> ConstantSolver<'a> { match inner { ConstantInner::Scalar { ref mut value, .. } => { - let initial = value.clone(); - *value = match kind { - ScalarKind::Sint => ScalarValue::Sint(inner_cast(initial)), - ScalarKind::Uint => ScalarValue::Uint(inner_cast(initial)), - ScalarKind::Float => ScalarValue::Float(inner_cast(initial)), - ScalarKind::Bool => ScalarValue::Bool(inner_cast::(initial) != 0), + ScalarKind::Sint => ScalarValue::Sint(inner_cast(*value)), + ScalarKind::Uint => ScalarValue::Uint(inner_cast(*value)), + ScalarKind::Float => ScalarValue::Float(inner_cast(*value)), + ScalarKind::Bool => ScalarValue::Bool(inner_cast::(*value) != 0), } } ConstantInner::Composite { @@ -229,15 +227,15 @@ impl<'a> ConstantSolver<'a> { match inner { ConstantInner::Scalar { ref mut value, .. } => match op { - UnaryOperator::Negate => match value { - ScalarValue::Sint(v) => *v = -*v, - ScalarValue::Float(v) => *v = -*v, + UnaryOperator::Negate => match *value { + ScalarValue::Sint(ref mut v) => *v = -*v, + ScalarValue::Float(ref mut v) => *v = -*v, _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), }, - UnaryOperator::Not => match value { - ScalarValue::Sint(v) => *v = !*v, - ScalarValue::Uint(v) => *v = !*v, - ScalarValue::Bool(v) => *v = !*v, + UnaryOperator::Not => match *value { + ScalarValue::Sint(ref mut v) => *v = !*v, + ScalarValue::Uint(ref mut v) => *v = !*v, + ScalarValue::Bool(ref mut v) => *v = !*v, _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), }, }, @@ -274,12 +272,13 @@ impl<'a> ConstantSolver<'a> { let inner = match (left, right) { ( - ConstantInner::Scalar { + &ConstantInner::Scalar { value: left_value, width, }, - ConstantInner::Scalar { - value: right_value, .. + &ConstantInner::Scalar { + value: right_value, + width: _, }, ) => { let value = match op { @@ -333,8 +332,8 @@ impl<'a> ConstantSolver<'a> { } (ScalarValue::Bool(a), ScalarValue::Bool(b)) => { ScalarValue::Bool(match op { - BinaryOperator::LogicalAnd => *a && *b, - BinaryOperator::LogicalOr => *a || *b, + BinaryOperator::LogicalAnd => a && b, + BinaryOperator::LogicalOr => a || b, _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), }) } @@ -342,10 +341,7 @@ impl<'a> ConstantSolver<'a> { }, }; - ConstantInner::Scalar { - value, - width: *width, - } + ConstantInner::Scalar { value, width } } _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), }; diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 7fd4a2804..a0daaccf1 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -26,32 +26,34 @@ pub enum ErrorKind { impl fmt::Display for ErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { + match *self { ErrorKind::EndOfFile => write!(f, "Unexpected end of file"), ErrorKind::InvalidInput => write!(f, "InvalidInput"), - ErrorKind::InvalidProfile(meta, val) => { + ErrorKind::InvalidProfile(ref meta, ref val) => { write!(f, "Invalid profile {} at {:?}", val, meta) } - ErrorKind::InvalidToken(token) => write!(f, "Invalid Token {:?}", token), - ErrorKind::InvalidVersion(meta, val) => { + ErrorKind::InvalidToken(ref token) => write!(f, "Invalid Token {:?}", token), + ErrorKind::InvalidVersion(ref meta, ref val) => { write!(f, "Invalid version {} at {:?}", val, meta) } - ErrorKind::IoError(error) => write!(f, "IO Error {}", error), + ErrorKind::IoError(ref error) => write!(f, "IO Error {}", error), ErrorKind::ParserFail => write!(f, "Parser failed"), ErrorKind::ParserStackOverflow => write!(f, "Parser stack overflow"), - ErrorKind::NotImplemented(msg) => write!(f, "Not implemented: {}", msg), - ErrorKind::UnknownVariable(meta, val) => { + ErrorKind::NotImplemented(ref msg) => write!(f, "Not implemented: {}", msg), + ErrorKind::UnknownVariable(ref meta, ref val) => { write!(f, "Unknown variable {} at {:?}", val, meta) } - ErrorKind::UnknownField(meta, val) => write!(f, "Unknown field {} at {:?}", val, meta), + ErrorKind::UnknownField(ref meta, ref val) => { + write!(f, "Unknown field {} at {:?}", val, meta) + } #[cfg(feature = "glsl-validate")] - ErrorKind::VariableAlreadyDeclared(val) => { + ErrorKind::VariableAlreadyDeclared(ref val) => { write!(f, "Variable {} already declared in current scope", val) } ErrorKind::ExpectedConstant => write!(f, "Expected constant"), - ErrorKind::SemanticError(msg) => write!(f, "Semantic error: {}", msg), - ErrorKind::PreprocessorError(val) => write!(f, "Preprocessor error: {}", val), - ErrorKind::WrongNumberArgs(fun, expected, actual) => { + ErrorKind::SemanticError(ref msg) => write!(f, "Semantic error: {}", msg), + ErrorKind::PreprocessorError(ref val) => write!(f, "Preprocessor error: {}", val), + ErrorKind::WrongNumberArgs(ref fun, expected, actual) => { write!(f, "{} requires {} args, got {}", fun, expected, actual) } } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2e752e867..6a917734d 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -328,7 +328,7 @@ pomelo! { extra.unary_expr(UnaryOperator::Negate, &tgt) } unary_expression ::= Bang unary_expression(tgt) { - if let TypeInner::Scalar { kind: ScalarKind::Bool, .. } = extra.resolve_type(tgt.expression)? { + if let TypeInner::Scalar { kind: ScalarKind::Bool, .. } = *extra.resolve_type(tgt.expression)? { extra.unary_expr(UnaryOperator::Not, &tgt) } else { return Err(ErrorKind::SemanticError("Cannot apply '!' to non bool type".into())) @@ -1070,18 +1070,18 @@ pomelo! { if let Some(d) = d { // TODO: handle multiple storage qualifiers let storage = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::StorageQualifier(sc) = tq { Some(*sc) } else { None } + if let TypeQualifier::StorageQualifier(sc) = *tq { Some(sc) } else { None } }).unwrap_or(StorageQualifier::StorageClass(StorageClass::Private)); match storage { StorageQualifier::StorageClass(storage_class) => { // TODO: Check that the storage qualifiers allow for the bindings let binding = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Binding(b) = tq { Some(b.clone()) } else { None } + if let TypeQualifier::Binding(ref b) = *tq { Some(b.clone()) } else { None } }); let interpolation = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Interpolation(i) = tq { Some(*i) } else { None } + if let TypeQualifier::Interpolation(interp) = *tq { Some(interp) } else { None } }); for (id, initializer) in d.ids_initializers { diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 9c9386c14..27a72ddf9 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -126,7 +126,7 @@ impl FlowGraph { ControlFlowEdgeType::Forward, ); - for (_, target_block_id) in targets.iter() { + for &(_, target_block_id) in targets.iter() { let target_node_index = block_to_node[&target_block_id]; self.flow.add_edge( @@ -201,7 +201,7 @@ impl FlowGraph { let phis = std::mem::replace(&mut self.flow[node_index].phis, Vec::new()); for phi in phis.iter() { let phi_var = &lookup_expression[&phi.id]; - for (variable_id, parent_id) in phi.variables.iter() { + for &(variable_id, parent_id) in phi.variables.iter() { let variable = &lookup_expression[&variable_id]; let parent_node = &mut self.flow[self.block_to_node[&parent_id]]; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 4680fe693..fdc3967bc 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -55,65 +55,6 @@ pub enum Token<'a> { End, } -impl<'a> Error<'a> { - fn as_parse_error(&self, source: &'a str) -> ParseError<'a> { - match self { - Error::Unexpected((_, unexpected_span), expected) => ParseError { - message: format!( - "expected {}, found '{}'", - expected, - &source[unexpected_span.clone()], - ), - labels: vec![(unexpected_span.clone(), format!("expected {}", expected))], - notes: vec![], - source, - }, - Error::BadInteger(bad_span) => ParseError { - message: format!( - "expected integer literal, found `{}`", - &source[bad_span.clone()], - ), - labels: vec![(bad_span.clone(), "expected integer".to_string())], - notes: vec![], - source, - }, - Error::BadFloat(bad_span) => ParseError { - message: format!( - "expected floating-point literal, found `{}`", - &source[bad_span.clone()], - ), - labels: vec![( - bad_span.clone(), - "expected floating-point literal".to_string(), - )], - notes: vec![], - source, - }, - Error::BadScalarWidth(bad_span, width) => ParseError { - message: format!("invalid width of `{}` for literal", width,), - labels: vec![(bad_span.clone(), "invalid width".to_string())], - notes: vec!["valid width is 32".to_string()], - source, - }, - Error::BadAccessor(accessor_span) => ParseError { - message: format!( - "invalid field accessor `{}`", - &source[accessor_span.clone()], - ), - labels: vec![(accessor_span.clone(), "invalid accessor".to_string())], - notes: vec![], - source, - }, - error => ParseError { - message: error.to_string(), - labels: vec![], - notes: vec![], - source, - }, - } - } -} - #[derive(Clone, Debug, Error)] pub enum Error<'a> { #[error("")] @@ -176,6 +117,65 @@ pub enum Error<'a> { Other, } +impl<'a> Error<'a> { + fn as_parse_error(&self, source: &'a str) -> ParseError<'a> { + match *self { + Error::Unexpected((_, ref unexpected_span), expected) => ParseError { + message: format!( + "expected {}, found '{}'", + expected, + &source[unexpected_span.clone()], + ), + labels: vec![(unexpected_span.clone(), format!("expected {}", expected))], + notes: vec![], + source, + }, + Error::BadInteger(ref bad_span) => ParseError { + message: format!( + "expected integer literal, found `{}`", + &source[bad_span.clone()], + ), + labels: vec![(bad_span.clone(), "expected integer".to_string())], + notes: vec![], + source, + }, + Error::BadFloat(ref bad_span) => ParseError { + message: format!( + "expected floating-point literal, found `{}`", + &source[bad_span.clone()], + ), + labels: vec![( + bad_span.clone(), + "expected floating-point literal".to_string(), + )], + notes: vec![], + source, + }, + Error::BadScalarWidth(ref bad_span, width) => ParseError { + message: format!("invalid width of `{}` for literal", width,), + labels: vec![(bad_span.clone(), "invalid width".to_string())], + notes: vec!["valid width is 32".to_string()], + source, + }, + Error::BadAccessor(ref accessor_span) => ParseError { + message: format!( + "invalid field accessor `{}`", + &source[accessor_span.clone()], + ), + labels: vec![(accessor_span.clone(), "invalid accessor".to_string())], + notes: vec![], + source, + }, + ref error => ParseError { + message: error.to_string(), + labels: vec![], + notes: vec![], + source, + }, + } + } +} + trait StringValueLookup<'a> { type Value; fn lookup(&self, key: &'a str) -> Result>; @@ -553,7 +553,7 @@ impl Parser { name: &'a str, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { - let fun_handle = match ctx.functions.iter().find(|(_, fun)| match fun.name { + let fun_handle = match ctx.functions.iter().find(|&(_, fun)| match fun.name { Some(ref string) => string == name, None => false, }) { @@ -1033,15 +1033,22 @@ impl Parser { let expr = if components.is_empty() { let last_component_inner = ctx.resolve_type(last_component)?; match (&inner, last_component_inner) { - (crate::TypeInner::Scalar { .. }, crate::TypeInner::Scalar { .. }) - | (crate::TypeInner::Matrix { .. }, crate::TypeInner::Matrix { .. }) - | (crate::TypeInner::Vector { .. }, crate::TypeInner::Vector { .. }) => { - crate::Expression::As { - expr: last_component, - kind: kind.ok_or(Error::BadTypeCast(word))?, - convert: true, - } - } + ( + &crate::TypeInner::Scalar { .. }, + &crate::TypeInner::Scalar { .. }, + ) + | ( + &crate::TypeInner::Matrix { .. }, + &crate::TypeInner::Matrix { .. }, + ) + | ( + &crate::TypeInner::Vector { .. }, + &crate::TypeInner::Vector { .. }, + ) => crate::Expression::As { + expr: last_component, + kind: kind.ok_or(Error::BadTypeCast(word))?, + convert: true, + }, _ => { return Err(Error::BadTypeCast(word)); } diff --git a/src/lib.rs b/src/lib.rs index 98bc953ee..e4c130f6a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,12 +20,6 @@ emitted in order to take effect. This happens in one of the following ways: !*/ -#![warn( - trivial_casts, - trivial_numeric_casts, - unused_extern_crates, - unused_qualifications -)] #![allow( clippy::new_without_default, clippy::unneeded_field_pattern, @@ -33,6 +27,13 @@ emitted in order to take effect. This happens in one of the following ways: )] // TODO: use `strip_prefix` instead when Rust 1.45 <= MSRV #![allow(clippy::manual_strip, clippy::unknown_clippy_lints)] +#![warn( + trivial_casts, + trivial_numeric_casts, + unused_extern_crates, + unused_qualifications, + clippy::pattern_type_mismatch +)] #![deny(clippy::panic)] mod arena; @@ -418,7 +419,7 @@ pub struct Constant { } /// A literal scalar value, used in constants. -#[derive(Debug, PartialEq, Clone, PartialOrd)] +#[derive(Debug, PartialEq, Clone, Copy, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ScalarValue { @@ -429,7 +430,7 @@ pub enum ScalarValue { } /// Additional information, dependent on the kind of constant. -#[derive(Debug, PartialEq, Clone)] +#[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ConstantInner { From 7ebd96b597ac2495a829c6a6a8625523dfedc5f4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 12 Mar 2021 10:52:59 -0500 Subject: [PATCH 0567/2212] Fix uniformity requirements of emitted expressions --- src/proc/analyzer.rs | 347 +++++++++++++++------------ src/proc/mod.rs | 9 + tests/in/quad.wgsl | 3 +- tests/out/collatz.info.ron.snap | 80 +++---- tests/out/quad-Fragment.glsl.snap | 2 +- tests/out/quad.dot.snap | 17 +- tests/out/quad.msl.snap | 2 +- tests/out/quad.spvasm.snap | 6 +- tests/out/shadow.info.ron.snap | 382 +++++++++++++++--------------- 9 files changed, 451 insertions(+), 397 deletions(-) diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 1d2833ba5..56b3d5f95 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -9,6 +9,19 @@ Figures out the following properties: use crate::arena::{Arena, Handle}; use std::ops; +pub type NonUniformResult = Option>; + +/// Expressions that require uniform control flow. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +#[cfg_attr(test, derive(PartialEq))] +pub enum UniformityRequirement { + WorkGroupBarrier, + Derivative, + ImplicitLevel, +} + /// Uniform control flow characteristics. #[derive(Clone, Debug, Default)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -26,64 +39,17 @@ pub struct Uniformity { /// and process all branches of the control flow. /// /// Any operations that depend on non-uniform results also produce non-uniform. - non_uniform_result: Option>, - /// A child expression that requires uniform control flow. - /// - /// Some operations can only be done within uniform control flow: - /// derivatives and auto-level image sampling in fragment shaders, - /// and group barriers in compute shaders. - require_uniform: Option>, -} - -//TODO: instead of doing cur | next, we could reverse this everywhere -// and do `next | cur`, which would allow us to trace the cause of -// uniformity requirement/disruption across the expression chain. - -impl ops::BitOr for Uniformity { - type Output = Self; - fn bitor(self, other: Self) -> Self { - Uniformity { - non_uniform_result: self.non_uniform_result.or(other.non_uniform_result), - require_uniform: self.require_uniform.or(other.require_uniform), - } - } -} - -impl ops::BitOrAssign for Uniformity { - fn bitor_assign(&mut self, other: Self) { - *self = self.clone() | other; - } + pub non_uniform_result: NonUniformResult, + /// If this expression requires uniform control flow, store the reason here. + pub requirement: Option, } impl Uniformity { + //TODO: is this helper really useful? fn non_uniform_result(expr: Handle) -> Self { Uniformity { non_uniform_result: Some(expr), - require_uniform: None, - } - } - - fn require_uniform(expr: Handle) -> Self { - Uniformity { - non_uniform_result: None, - require_uniform: Some(expr), - } - } - - fn disruptor(&self) -> Option { - self.non_uniform_result.map(UniformityDisruptor::Expression) - } - - /// When considering the uniformity at the functional level, - /// we don't care about all of the expression results. - /// We only care about the `return` expressions. - fn to_function(&self) -> FunctionUniformity { - FunctionUniformity { - result: Uniformity { - non_uniform_result: None, - require_uniform: self.require_uniform, - }, - exit: ExitFlags::empty(), + requirement: None, } } } @@ -111,7 +77,13 @@ impl ops::BitOr for FunctionUniformity { type Output = Self; fn bitor(self, other: Self) -> Self { FunctionUniformity { - result: self.result | other.result, + result: Uniformity { + non_uniform_result: self + .result + .non_uniform_result + .or(other.result.non_uniform_result), + requirement: self.result.requirement.or(other.result.requirement), + }, exit: self.exit | other.exit, } } @@ -237,8 +209,14 @@ pub enum UniformityDisruptor { pub enum AnalysisError { #[error("Expression {0:?} is not a global variable!")] ExpectedGlobalVariable(crate::Expression), - #[error("Required uniformity of control flow for {0:?} is not fulfilled because of {1:?}")] - NonUniformControlFlow(Handle, UniformityDisruptor), + #[error( + "Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}" + )] + NonUniformControlFlow( + UniformityRequirement, + Handle, + UniformityDisruptor, + ), } impl FunctionInfo { @@ -248,19 +226,19 @@ impl FunctionInfo { &mut self, handle: Handle, global_use: GlobalUse, - ) -> Uniformity { + ) -> NonUniformResult { let info = &mut self.expressions[handle.index()]; info.ref_count += 1; // mark the used global as read if let Some(global) = info.assignable_global { self.global_uses[global.index()] |= global_use; } - info.uniformity.clone() + info.uniformity.non_uniform_result } /// Adds a value-type reference to an expression. #[must_use] - fn add_ref(&mut self, handle: Handle) -> Uniformity { + fn add_ref(&mut self, handle: Handle) -> NonUniformResult { self.add_ref_impl(handle, GlobalUse::READ) } @@ -272,7 +250,7 @@ impl FunctionInfo { &mut self, handle: Handle, assignable_global: &mut Option>, - ) -> Uniformity { + ) -> NonUniformResult { let info = &mut self.expressions[handle.index()]; info.ref_count += 1; // propagate the assignable global up the chain, till it either hits @@ -282,7 +260,7 @@ impl FunctionInfo { unreachable!() } } - info.uniformity.clone() + info.uniformity.non_uniform_result } /// Inherit information from a called function. @@ -305,6 +283,7 @@ impl FunctionInfo { /// Computes the expression info and stores it in `self.expressions`. /// Also, bumps the reference counts on dependent expressions. + #[allow(clippy::or_fun_call)] fn process_expression( &mut self, handle: Handle, @@ -316,19 +295,30 @@ impl FunctionInfo { let mut assignable_global = None; let uniformity = match expression_arena[handle] { - E::Access { base, index } => { - self.add_assignable_ref(base, &mut assignable_global) | self.add_ref(index) - } - E::AccessIndex { base, .. } => self.add_assignable_ref(base, &mut assignable_global), + E::Access { base, index } => Uniformity { + non_uniform_result: self + .add_assignable_ref(base, &mut assignable_global) + .or(self.add_ref(index)), + requirement: None, + }, + E::AccessIndex { base, .. } => Uniformity { + non_uniform_result: self.add_assignable_ref(base, &mut assignable_global), + requirement: None, + }, + // always uniform E::Constant(_) => Uniformity::default(), E::Compose { ref components, .. } => { - let mut accum = Uniformity::default(); - for &comp in components { - accum |= self.add_ref(comp); + let non_uniform_result = components + .iter() + .fold(None, |nur, &comp| nur.or(self.add_ref(comp))); + Uniformity { + non_uniform_result, + requirement: None, } - accum } - E::FunctionArgument(_) => Uniformity::non_uniform_result(handle), //TODO? + // same as `LocalVariable` - generally non-uniform + E::FunctionArgument(_) => Uniformity::non_uniform_result(handle), + // depends on the builtin and storage class E::GlobalVariable(gh) => { assignable_global = Some(gh); let var = &global_var_arena[gh]; @@ -355,16 +345,16 @@ impl FunctionInfo { } } }; - if uniform { - Uniformity::default() - } else { - Uniformity::non_uniform_result(handle) + Uniformity { + non_uniform_result: if uniform { None } else { Some(handle) }, + requirement: None, } } - E::LocalVariable(_) => { - Uniformity::non_uniform_result(handle) //TODO? - } - E::Load { pointer } => self.add_ref(pointer), + E::LocalVariable(_) => Uniformity::non_uniform_result(handle), + E::Load { pointer } => Uniformity { + non_uniform_result: self.add_ref(pointer), + requirement: None, + }, E::ImageSample { image, sampler, @@ -388,27 +378,28 @@ impl FunctionInfo { } }, }); - let array_flags = match array_index { - Some(h) => self.add_ref(h), - None => Uniformity::default(), - }; - let level_flags = match level { - // implicit derivatives for LOD require uniform - Sl::Auto => Uniformity::require_uniform(handle), - Sl::Zero => Uniformity::default(), + // "nur" == "Non-Uniform Result" + let array_nur = array_index.and_then(|h| self.add_ref(h)); + let level_nur = match level { + Sl::Auto | Sl::Zero => None, Sl::Exact(h) | Sl::Bias(h) => self.add_ref(h), - Sl::Gradient { x, y } => self.add_ref(x) | self.add_ref(y), + Sl::Gradient { x, y } => self.add_ref(x).or(self.add_ref(y)), }; - let dref_flags = match depth_ref { - Some(h) => self.add_ref(h), - None => Uniformity::default(), - }; - self.add_ref(image) - | self.add_ref(sampler) - | self.add_ref(coordinate) - | array_flags - | level_flags - | dref_flags + let dref_nur = depth_ref.and_then(|h| self.add_ref(h)); + Uniformity { + non_uniform_result: self + .add_ref(image) + .or(self.add_ref(sampler)) + .or(self.add_ref(coordinate)) + .or(array_nur) + .or(level_nur) + .or(dref_nur), + requirement: if level.implicit_derivatives() { + Some(UniformityRequirement::ImplicitLevel) + } else { + None + }, + } } E::ImageLoad { image, @@ -416,49 +407,75 @@ impl FunctionInfo { array_index, index, } => { - let array_flags = match array_index { - Some(h) => self.add_ref(h), - None => Uniformity::default(), - }; - let index_flags = match index { - Some(h) => self.add_ref(h), - None => Uniformity::default(), - }; - self.add_ref(image) | self.add_ref(coordinate) | array_flags | index_flags + let array_nur = array_index.and_then(|h| self.add_ref(h)); + let index_nur = index.and_then(|h| self.add_ref(h)); + Uniformity { + non_uniform_result: self + .add_ref(image) + .or(self.add_ref(coordinate)) + .or(array_nur) + .or(index_nur), + requirement: None, + } } E::ImageQuery { image, query } => { - let query_flags = match query { + let query_nur = match query { crate::ImageQuery::Size { level: Some(h) } => self.add_ref(h), - _ => Uniformity::default(), + _ => None, }; - self.add_ref_impl(image, GlobalUse::QUERY) | query_flags + Uniformity { + non_uniform_result: self.add_ref_impl(image, GlobalUse::QUERY).or(query_nur), + requirement: None, + } } - E::Unary { expr, .. } => self.add_ref(expr), - E::Binary { left, right, .. } => self.add_ref(left) | self.add_ref(right), + E::Unary { expr, .. } => Uniformity { + non_uniform_result: self.add_ref(expr), + requirement: None, + }, + E::Binary { left, right, .. } => Uniformity { + non_uniform_result: self.add_ref(left).or(self.add_ref(right)), + requirement: None, + }, E::Select { condition, accept, reject, - } => self.add_ref(condition) | self.add_ref(accept) | self.add_ref(reject), + } => Uniformity { + non_uniform_result: self + .add_ref(condition) + .or(self.add_ref(accept)) + .or(self.add_ref(reject)), + requirement: None, + }, // explicit derivatives require uniform - E::Derivative { expr, .. } => Uniformity::require_uniform(handle) | self.add_ref(expr), - E::Relational { argument, .. } => self.add_ref(argument), + E::Derivative { expr, .. } => Uniformity { + //Note: taking a derivative of a uniform doesn't make it non-uniform + non_uniform_result: self.add_ref(expr), + requirement: Some(UniformityRequirement::Derivative), + }, + E::Relational { argument, .. } => Uniformity { + non_uniform_result: self.add_ref(argument), + requirement: None, + }, E::Math { arg, arg1, arg2, .. } => { - let arg1_flags = match arg1 { - Some(h) => self.add_ref(h), - None => Uniformity::default(), - }; - let arg2_flags = match arg2 { - Some(h) => self.add_ref(h), - None => Uniformity::default(), - }; - self.add_ref(arg) | arg1_flags | arg2_flags + let arg1_nur = arg1.and_then(|h| self.add_ref(h)); + let arg2_nur = arg2.and_then(|h| self.add_ref(h)); + Uniformity { + non_uniform_result: self.add_ref(arg).or(arg1_nur).or(arg2_nur), + requirement: None, + } } - E::As { expr, .. } => self.add_ref(expr), + E::As { expr, .. } => Uniformity { + non_uniform_result: self.add_ref(expr), + requirement: None, + }, E::Call(function) => self.process_call(&other_functions[function.index()]).result, - E::ArrayLength(expr) => self.add_ref_impl(expr, GlobalUse::QUERY), + E::ArrayLength(expr) => Uniformity { + non_uniform_result: self.add_ref_impl(expr, GlobalUse::QUERY), + requirement: None, + }, }; self.expressions[handle.index()] = ExpressionInfo { @@ -491,15 +508,27 @@ impl FunctionInfo { for statement in statements { let uniformity = match *statement { S::Emit(ref range) => { + let mut requirement = None; for expr in range.clone() { - if let (Some(expr), Some(cause)) = ( - self.expressions[expr.index()].uniformity.require_uniform, - disruptor, - ) { - return Err(AnalysisError::NonUniformControlFlow(expr, cause)); + if let Some(req) = self.expressions[expr.index()].uniformity.requirement { + requirement = match disruptor { + Some(cause) => { + return Err(AnalysisError::NonUniformControlFlow( + req, expr, cause, + )) + } + // remember the requirement of any emitted expressions + None => Some(req), + }; } } - FunctionUniformity::new() + FunctionUniformity { + result: Uniformity { + non_uniform_result: None, + requirement, + }, + exit: ExitFlags::empty(), + } } S::Break | S::Continue => FunctionUniformity::new(), S::Kill => FunctionUniformity { @@ -512,21 +541,23 @@ impl FunctionInfo { ref accept, ref reject, } => { - let condition_uniformity = self.add_ref(condition); - let branch_disruptor = disruptor.or(condition_uniformity.disruptor()); + let condition_nur = self.add_ref(condition); + let branch_disruptor = + disruptor.or(condition_nur.map(UniformityDisruptor::Expression)); let accept_uniformity = self.process_block(accept, other_functions, branch_disruptor)?; let reject_uniformity = self.process_block(reject, other_functions, branch_disruptor)?; - condition_uniformity.to_function() | accept_uniformity | reject_uniformity + accept_uniformity | reject_uniformity } S::Switch { selector, ref cases, ref default, } => { - let selector_uniformity = self.add_ref(selector); - let branch_disruptor = disruptor.or(selector_uniformity.disruptor()); + let selector_nur = self.add_ref(selector); + let branch_disruptor = + disruptor.or(selector_nur.map(UniformityDisruptor::Expression)); let mut uniformity = FunctionUniformity::new(); let mut case_disruptor = branch_disruptor; for case in cases.iter() { @@ -555,18 +586,20 @@ impl FunctionInfo { body_uniformity | continuing_uniformity } S::Return { value } => FunctionUniformity { - result: if let Some(expr) = value { - self.add_ref(expr) - } else { - Uniformity::default() + result: Uniformity { + non_uniform_result: value.and_then(|expr| self.add_ref(expr)), + requirement: None, }, //TODO: if we are in the uniform control flow, should this still be an exit flag? exit: ExitFlags::MAY_RETURN, }, + // Here and below, the used expressions are already emitted, + // and their results do not affect the function return value, + // so we can ignore their non-uniformity. S::Store { pointer, value } => { - let uniformity = - self.add_ref_impl(pointer, GlobalUse::WRITE) | self.add_ref(value); - uniformity.to_function() + let _ = self.add_ref_impl(pointer, GlobalUse::WRITE); + let _ = self.add_ref(value); + FunctionUniformity::new() } S::ImageStore { image, @@ -574,28 +607,24 @@ impl FunctionInfo { array_index, value, } => { - let array_uniformity = match array_index { - Some(expr) => self.add_ref(expr), - None => Uniformity::default(), - }; - let uniformity = array_uniformity - | self.add_ref_impl(image, GlobalUse::WRITE) - | self.add_ref(coordinate) - | self.add_ref(value); - uniformity.to_function() + let _ = self.add_ref_impl(image, GlobalUse::WRITE); + if let Some(expr) = array_index { + let _ = self.add_ref(expr); + } + let _ = self.add_ref(coordinate); + let _ = self.add_ref(value); + FunctionUniformity::new() } S::Call { function, ref arguments, result: _, } => { - let info = &other_functions[function.index()]; - let call_uniformity = self.process_call(info); - let mut uniformity = call_uniformity.result.clone(); for &argument in arguments { - uniformity |= self.add_ref(argument); + let _ = self.add_ref(argument); } - call_uniformity | uniformity.to_function() + let info = &other_functions[function.index()]; + self.process_call(info) } }; @@ -768,7 +797,10 @@ fn uniform_control_flow() { assert_eq!( info.process_block(&[stmt_emit1, stmt_if_uniform], &[], None), Ok(FunctionUniformity { - result: Uniformity::require_uniform(derivative_expr), + result: Uniformity { + non_uniform_result: None, + requirement: Some(UniformityRequirement::Derivative), + }, exit: ExitFlags::empty(), }), ); @@ -790,6 +822,7 @@ fn uniform_control_flow() { assert_eq!( info.process_block(&[stmt_emit2, stmt_if_non_uniform], &[], None), Err(AnalysisError::NonUniformControlFlow( + UniformityRequirement::Derivative, derivative_expr, UniformityDisruptor::Expression(non_uniform_global_expr) )), diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 965e5021c..aa383fcb0 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -149,3 +149,12 @@ impl crate::Expression { } } } + +impl crate::SampleLevel { + pub fn implicit_derivatives(&self) -> bool { + match *self { + Self::Auto | Self::Bias(_) => true, + Self::Zero | Self::Exact(_) | Self::Gradient { .. } => false, + } + } +} diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 033eaa3fd..d85e5f247 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -23,5 +23,6 @@ fn main() { if (color.a == 0.0) { discard; } - o_color = color; + const premultiplied: vec4 = color.a * color; + o_color = premultiplied; } diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 4d8696219..75f3241a0 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -7,7 +7,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(6), - require_uniform: None, + requirement: None, ), may_kill: false, sampling_set: [], @@ -23,7 +23,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: Some(1), @@ -31,7 +31,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: Some(2), @@ -39,7 +39,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -47,7 +47,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 7, assignable_global: None, @@ -55,7 +55,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -63,7 +63,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(6), - require_uniform: None, + requirement: None, ), ref_count: 3, assignable_global: None, @@ -71,7 +71,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -79,7 +79,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -87,7 +87,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -95,7 +95,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -103,7 +103,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -111,7 +111,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -119,7 +119,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -127,7 +127,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -135,7 +135,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -143,7 +143,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -151,7 +151,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -159,7 +159,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -167,7 +167,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -175,7 +175,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -183,7 +183,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -191,7 +191,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -199,7 +199,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(6), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -207,7 +207,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -215,7 +215,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(6), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -223,7 +223,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(6), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -235,7 +235,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(6), - require_uniform: None, + requirement: None, ), may_kill: false, sampling_set: [], @@ -251,7 +251,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - require_uniform: None, + requirement: None, ), ref_count: 2, assignable_global: Some(1), @@ -259,7 +259,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 2, assignable_global: Some(2), @@ -267,7 +267,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(2), @@ -275,7 +275,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -283,7 +283,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -291,7 +291,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(2), @@ -299,7 +299,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(2), @@ -307,7 +307,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -315,7 +315,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -323,7 +323,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(2), @@ -331,7 +331,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -339,7 +339,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(6), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap index 9f879ec21..b76490738 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad-Fragment.glsl.snap @@ -16,7 +16,7 @@ void main() { if((texture(_group_0_binding_0, vec2(_location_0_vs))[3] == 0.0)) { discard; } - _location_0 = texture(_group_0_binding_0, vec2(_location_0_vs)); + _location_0 = (texture(_group_0_binding_0, vec2(_location_0_vs))[3] * texture(_group_0_binding_0, vec2(_location_0_vs))); return; } diff --git a/tests/out/quad.dot.snap b/tests/out/quad.dot.snap index 4f5281919..333de1596 100644 --- a/tests/out/quad.dot.snap +++ b/tests/out/quad.dot.snap @@ -89,6 +89,11 @@ digraph Module { ep1_e12 [ color="#fdb462" label="[13] Equal" ] ep1_e11 -> ep1_e12 [ label="right" ] ep1_e10 -> ep1_e12 [ label="left" ] + ep1_e13 [ color="#8dd3c7" label="[14] AccessIndex[3]" ] + ep1_e9 -> ep1_e13 [ label="base" ] + ep1_e14 [ color="#fdb462" label="[15] Multiply" ] + ep1_e9 -> ep1_e14 [ label="right" ] + ep1_e13 -> ep1_e14 [ label="left" ] ep1_s0 [ shape=square label="Root" ] ep1_s1 [ shape=square label="Emit" ] ep1_s2 [ shape=square label="Emit" ] @@ -97,8 +102,9 @@ digraph Module { ep1_s5 [ shape=square label="Node" ] ep1_s6 [ shape=square label="Kill" ] ep1_s7 [ shape=square label="Node" ] - ep1_s8 [ shape=square label="Store" ] - ep1_s9 [ shape=square label="Return" ] + ep1_s8 [ shape=square label="Emit" ] + ep1_s9 [ shape=square label="Store" ] + ep1_s10 [ shape=square label="Return" ] ep1_s0 -> ep1_s1 [ arrowhead=tee label="" ] ep1_s1 -> ep1_s2 [ arrowhead=tee label="" ] ep1_s2 -> ep1_s3 [ arrowhead=tee label="" ] @@ -108,13 +114,16 @@ digraph Module { ep1_s4 -> ep1_s7 [ arrowhead=tee label="reject" ] ep1_s7 -> ep1_s8 [ arrowhead=tee label="" ] ep1_s8 -> ep1_s9 [ arrowhead=tee label="" ] + ep1_s9 -> ep1_s10 [ arrowhead=tee label="" ] ep1_e12 -> ep1_s4 [ label="condition" ] - ep1_e9 -> ep1_s8 [ label="value" ] + ep1_e14 -> ep1_s9 [ label="value" ] ep1_s1 -> ep1_e8 [ style=dotted ] ep1_s1 -> ep1_e9 [ style=dotted ] ep1_s2 -> ep1_e10 [ style=dotted ] ep1_s3 -> ep1_e12 [ style=dotted ] - ep1_s8 -> ep1_e7 [ style=dotted ] + ep1_s8 -> ep1_e13 [ style=dotted ] + ep1_s8 -> ep1_e14 [ style=dotted ] + ep1_s9 -> ep1_e7 [ style=dotted ] } } diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index f69554378..35424fe75 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -55,7 +55,7 @@ fragment main2Output main2( if ((_expr9.w == const_0f)) { metal::discard_fragment(); } - output.o_color = _expr9; + output.o_color = (_expr9.w * _expr9); return output; } diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index 669073886..8aadbe5f9 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -5,7 +5,7 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 46 +; Bound: 48 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -89,6 +89,8 @@ OpBranchConditional %43 %45 %44 %45 = OpLabel OpKill %44 = OpLabel -OpStore %23 %40 +%46 = OpCompositeExtract %4 %40 3 +%47 = OpVectorTimesScalar %14 %40 %46 +OpStore %23 %47 OpReturn OpFunctionEnd diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 11bd7f992..08924616f 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -7,7 +7,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), may_kill: false, sampling_set: [ @@ -43,7 +43,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: Some(3), @@ -51,7 +51,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: Some(6), @@ -59,7 +59,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: Some(5), @@ -67,7 +67,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(1), @@ -75,7 +75,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(2), @@ -83,7 +83,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: Some(4), @@ -91,7 +91,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(7), - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: Some(7), @@ -99,7 +99,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -107,7 +107,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 3, assignable_global: None, @@ -115,7 +115,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -123,7 +123,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -131,7 +131,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -139,7 +139,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -147,7 +147,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -155,7 +155,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -163,7 +163,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -171,7 +171,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -179,7 +179,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -187,7 +187,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -195,7 +195,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -203,7 +203,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -211,7 +211,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -219,7 +219,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -227,7 +227,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -235,7 +235,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -243,7 +243,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -251,7 +251,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -259,7 +259,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -267,7 +267,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -275,7 +275,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 3, assignable_global: None, @@ -283,7 +283,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -291,7 +291,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -299,7 +299,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -307,7 +307,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -315,7 +315,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -323,7 +323,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -331,7 +331,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -339,7 +339,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -347,7 +347,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -355,7 +355,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -363,7 +363,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -371,7 +371,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -379,7 +379,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -387,7 +387,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 6, assignable_global: None, @@ -395,7 +395,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -403,7 +403,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -411,7 +411,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -419,7 +419,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -427,7 +427,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -435,7 +435,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -443,7 +443,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -451,7 +451,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -459,7 +459,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -467,7 +467,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -475,7 +475,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -483,7 +483,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 2, assignable_global: None, @@ -491,7 +491,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -499,7 +499,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -507,7 +507,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -515,7 +515,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -523,7 +523,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 3, assignable_global: None, @@ -531,7 +531,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -539,7 +539,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -547,7 +547,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -555,7 +555,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -563,7 +563,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -571,7 +571,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -579,7 +579,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -587,7 +587,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -595,7 +595,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -603,7 +603,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -615,7 +615,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), may_kill: false, sampling_set: [ @@ -651,7 +651,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(3), @@ -659,7 +659,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(6), @@ -667,7 +667,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 4, assignable_global: Some(5), @@ -675,7 +675,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: Some(1), @@ -683,7 +683,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: Some(2), @@ -691,7 +691,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 7, assignable_global: Some(4), @@ -699,7 +699,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(7), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(7), @@ -707,7 +707,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -715,7 +715,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -723,7 +723,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -731,7 +731,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -739,7 +739,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -747,7 +747,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -755,7 +755,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -763,7 +763,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -771,7 +771,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -779,7 +779,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -787,7 +787,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -795,7 +795,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -803,7 +803,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -811,7 +811,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -819,7 +819,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -827,7 +827,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -835,7 +835,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -843,7 +843,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -851,7 +851,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -859,7 +859,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -867,7 +867,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -875,7 +875,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -883,7 +883,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -891,7 +891,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -899,7 +899,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -907,7 +907,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -915,7 +915,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -923,7 +923,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -931,7 +931,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -939,7 +939,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -947,7 +947,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -955,7 +955,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -963,7 +963,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -971,7 +971,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 0, assignable_global: None, @@ -979,7 +979,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -987,7 +987,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - require_uniform: None, + requirement: None, ), ref_count: 3, assignable_global: None, @@ -995,7 +995,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 11, assignable_global: None, @@ -1003,7 +1003,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1011,7 +1011,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(3), @@ -1019,7 +1019,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(3), @@ -1027,7 +1027,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1035,7 +1035,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1043,7 +1043,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1051,7 +1051,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1059,7 +1059,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1067,7 +1067,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1075,7 +1075,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1083,7 +1083,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1091,7 +1091,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1099,7 +1099,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1107,7 +1107,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1115,7 +1115,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1123,7 +1123,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1131,7 +1131,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1139,7 +1139,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1147,7 +1147,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1155,7 +1155,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1163,7 +1163,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1171,7 +1171,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1179,7 +1179,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1187,7 +1187,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1195,7 +1195,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1203,7 +1203,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1211,7 +1211,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1219,7 +1219,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1227,7 +1227,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1235,7 +1235,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1243,7 +1243,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1251,7 +1251,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1259,7 +1259,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1267,7 +1267,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1275,7 +1275,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1283,7 +1283,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1291,7 +1291,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1299,7 +1299,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(5), @@ -1307,7 +1307,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1315,7 +1315,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(5), @@ -1323,7 +1323,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1331,7 +1331,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(5), @@ -1339,7 +1339,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1347,7 +1347,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1355,7 +1355,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1363,7 +1363,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1371,7 +1371,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1379,7 +1379,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1387,7 +1387,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1395,7 +1395,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1403,7 +1403,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1411,7 +1411,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1419,7 +1419,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1427,7 +1427,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1435,7 +1435,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1443,7 +1443,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1451,7 +1451,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1459,7 +1459,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1467,7 +1467,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1475,7 +1475,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1483,7 +1483,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1491,7 +1491,7 @@ expression: output ( uniformity: ( non_uniform_result: None, - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1499,7 +1499,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1507,7 +1507,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1515,7 +1515,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1523,7 +1523,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: Some(4), @@ -1531,7 +1531,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1539,7 +1539,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1547,7 +1547,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1555,7 +1555,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1563,7 +1563,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1571,7 +1571,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1579,7 +1579,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, @@ -1587,7 +1587,7 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - require_uniform: None, + requirement: None, ), ref_count: 1, assignable_global: None, From 58a4e330dcfc8dff560101c22e03d5b4568791e5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Mar 2021 01:06:58 -0500 Subject: [PATCH 0568/2212] [glsl-out] fix cached expressions --- src/back/glsl/mod.rs | 76 +++++++++++++++++++---------- src/back/mod.rs | 7 ++- tests/out/quad-Fragment.glsl.snap | 5 +- tests/out/shadow-Fragment.glsl.snap | 6 ++- tests/out/skybox-Fragment.glsl.snap | 5 +- 5 files changed, 68 insertions(+), 31 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index f4e59f179..c7c5a194e 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -539,17 +539,17 @@ impl<'a, W: Write> Writer<'a, W> { self.collect_reflection_info() } - /// Helper method used to write non image/sampler types + /// Helper method used to write value types /// /// # Notes /// Adds no trailing or leading whitespace /// /// # Panics - /// - If type is either a image or sampler + /// - If type is either a image, a sampler, a pointer, or a struct /// - If it's an Array with a [`ArraySize::Constant`](crate::ArraySize::Constant) with a /// constant that isn't [`Uint`](crate::ConstantInner::Uint) - fn write_type(&mut self, ty: Handle) -> BackendResult { - match self.module.types[ty].inner { + fn write_value_type(&mut self, inner: &TypeInner) -> BackendResult { + match *inner { // Scalars are simple we just get the full name from `glsl_scalar` TypeInner::Scalar { kind, width } | TypeInner::ValuePointer { @@ -587,8 +587,6 @@ impl<'a, W: Write> Writer<'a, W> { columns as u8, rows as u8 )?, - // glsl has no pointer types so just write types as normal and loads are skipped - TypeInner::Pointer { base, .. } => self.write_type(base)?, // GLSL arrays are written as `type name[size]` // Current code is written arrays only as `[size]` // Base `type` and `name` should be written outside @@ -613,24 +611,45 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "]")? } + // Panic if either Image, Sampler, Pointer, or a Struct is being written + // + // Write all variants instead of `_` so that if new variants are added a + // no exhaustiveness error is thrown + TypeInner::Pointer { .. } + | TypeInner::Struct { .. } + | TypeInner::Image { .. } + | TypeInner::Sampler { .. } => unreachable!(), + } + + Ok(()) + } + + /// Helper method used to write non image/sampler types + /// + /// # Notes + /// Adds no trailing or leading whitespace + /// + /// # Panics + /// - If type is either a image or sampler + /// - If it's an Array with a [`ArraySize::Constant`](crate::ArraySize::Constant) with a + /// constant that isn't [`Uint`](crate::ConstantInner::Uint) + fn write_type(&mut self, ty: Handle) -> BackendResult { + match self.module.types[ty].inner { + // glsl has no pointer types so just write types as normal and loads are skipped + TypeInner::Pointer { base, .. } => self.write_type(base), TypeInner::Struct { block: true, ref members, - } => self.write_struct(true, ty, members)?, + } => self.write_struct(true, ty, members), // glsl structs are written as just the struct name if it isn't a block TypeInner::Struct { block: false, .. } => { // Get the struct name let name = &self.names[&NameKey::Type(ty)]; - write!(self.out, "{}", name)? + write!(self.out, "{}", name)?; + Ok(()) } - // Panic if either Image or Sampler is being written - // - // Write all variants instead of `_` so that if new variants are added a - // no exhaustiveness error is thrown - TypeInner::Image { .. } | TypeInner::Sampler { .. } => unreachable!(), + ref other => self.write_value_type(other), } - - Ok(()) } /// Helper method to write a image type @@ -794,6 +813,8 @@ impl<'a, W: Write> Writer<'a, W> { typifier: &typifier, }; + self.cached_expressions.clear(); + // Write the function header // // glsl headers are the same as in c: @@ -1041,11 +1062,11 @@ impl<'a, W: Write> Writer<'a, W> { // This is where we can generate intermediate constants for some expression types. Statement::Emit(ref range) => { for handle in range.clone() { - if let Ok(ty_handle) = ctx.typifier.get_handle(handle) { - let min_ref_count = ctx.expressions[handle].bake_ref_count(); - if min_ref_count <= ctx.info[handle].ref_count { - write!(self.out, "{}", INDENT.repeat(indent))?; - match self.module.types[ty_handle].inner { + let min_ref_count = ctx.expressions[handle].bake_ref_count(); + if min_ref_count <= ctx.info[handle].ref_count { + write!(self.out, "{}", INDENT.repeat(indent))?; + match ctx.typifier.get_handle(handle) { + Ok(ty_handle) => match self.module.types[ty_handle].inner { TypeInner::Struct { .. } => { let ty_name = &self.names[&NameKey::Type(ty_handle)]; write!(self.out, "{}", ty_name)?; @@ -1053,13 +1074,16 @@ impl<'a, W: Write> Writer<'a, W> { _ => { self.write_type(ty_handle)?; } - }; - let name = format!("_expr{}", handle.index()); - write!(self.out, " {} = ", name)?; - self.write_expr(handle, ctx)?; - writeln!(self.out, ";")?; - self.cached_expressions.insert(handle, name); + }, + Err(inner) => { + self.write_value_type(inner)?; + } } + let name = format!("_expr{}", handle.index()); + write!(self.out, " {} = ", name)?; + self.write_expr(handle, ctx)?; + writeln!(self.out, ";")?; + self.cached_expressions.insert(handle, name); } } } diff --git a/src/back/mod.rs b/src/back/mod.rs index 1b0d826e2..c7d513a66 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -12,13 +12,18 @@ pub mod spv; impl crate::Expression { /// Returns the ref count, upon reaching which this expression /// should be considered for baking. + /// + /// Note: we have to cache any expressions that depend on the control flow, + /// or otherwise they may be moved into a non-uniform contol flow, accidentally. #[allow(dead_code)] fn bake_ref_count(&self) -> usize { match *self { // accesses are never cached, only loads are crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => !0, - // image operations look better when isolated + // sampling may use the control flow, and image ops look better by themselves crate::Expression::ImageSample { .. } | crate::Expression::ImageLoad { .. } => 1, + // derivatives use the control flow + crate::Expression::Derivative { .. } => 1, // cache expressions that are referenced multiple times _ => 2, } diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap index b76490738..7b875449f 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad-Fragment.glsl.snap @@ -13,10 +13,11 @@ uniform highp sampler2D _group_0_binding_0; out vec4 _location_0; void main() { - if((texture(_group_0_binding_0, vec2(_location_0_vs))[3] == 0.0)) { + vec4 _expr9 = texture(_group_0_binding_0, vec2(_location_0_vs)); + if((_expr9[3] == 0.0)) { discard; } - _location_0 = (texture(_group_0_binding_0, vec2(_location_0_vs))[3] * texture(_group_0_binding_0, vec2(_location_0_vs))); + _location_0 = (_expr9[3] * _expr9); return; } diff --git a/tests/out/shadow-Fragment.glsl.snap b/tests/out/shadow-Fragment.glsl.snap index 6624e149e..df8300b46 100644 --- a/tests/out/shadow-Fragment.glsl.snap +++ b/tests/out/shadow-Fragment.glsl.snap @@ -32,7 +32,9 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { if((homogeneous_coords[3] <= 0.0)) { return 1.0; } - return textureGrad(_group_0_binding_2, vec4((((vec2(homogeneous_coords[0], homogeneous_coords[1]) * vec2(0.5, -0.5)) * (1.0 / homogeneous_coords[3])) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] * (1.0 / homogeneous_coords[3]))), vec2(0, 0), vec2(0,0)); + float _expr15 = (1.0 / homogeneous_coords[3]); + float _expr28 = textureGrad(_group_0_binding_2, vec4((((vec2(homogeneous_coords[0], homogeneous_coords[1]) * vec2(0.5, -0.5)) * _expr15) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] * _expr15)), vec2(0, 0), vec2(0,0)); + return _expr28; } void main() { @@ -51,3 +53,5 @@ void main() { _location_0 = vec4(color1, 1.0); return; } + + diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap index da1ebab57..6d949cd3c 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox-Fragment.glsl.snap @@ -13,6 +13,9 @@ in vec3 _location_0_vs; out vec4 _location_0; void main() { - _location_0 = texture(_group_0_binding_1, vec3(_location_0_vs)); + vec4 _expr9 = texture(_group_0_binding_1, vec3(_location_0_vs)); + _location_0 = _expr9; return; } + + From ebcd815250229beaa1bfd1c382bf4ecaad8bf933 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 7 Mar 2021 00:03:05 -0500 Subject: [PATCH 0569/2212] Update IR to have entry points with inputs/outputs --- src/back/glsl/mod.rs | 266 +++++--- src/back/msl/mod.rs | 67 ++- src/back/msl/writer.rs | 388 +++++++----- src/back/spv/layout.rs | 16 + src/back/spv/writer.rs | 428 ++++++++----- src/front/glsl/ast.rs | 8 +- src/front/glsl/parser.rs | 63 +- src/front/glsl/variables.rs | 25 +- src/front/spv/convert.rs | 35 +- src/front/spv/function.rs | 131 +++- src/front/spv/mod.rs | 236 +++++--- src/front/wgsl/conv.rs | 2 - src/front/wgsl/mod.rs | 186 ++++-- src/lib.rs | 54 +- src/proc/analyzer.rs | 71 ++- src/proc/namer.rs | 8 + src/proc/typifier.rs | 7 +- src/proc/validator.rs | 470 ++++++++------- tests/errors.rs | 10 +- tests/in/boids.wgsl | 6 +- tests/in/collatz.wgsl | 5 +- tests/in/quad.wgsl | 25 +- tests/in/shadow.wgsl | 20 +- tests/in/skybox.wgsl | 27 +- tests/in/texture-array.wgsl | 9 +- tests/out/boids.msl.snap | 26 +- tests/out/boids.spvasm.snap | 204 +++---- tests/out/collatz.info.ron.snap | 106 ++-- tests/out/collatz.msl.snap | 30 +- tests/out/collatz.ron.snap | 208 +++---- tests/out/collatz.spvasm.snap | 175 +++--- tests/out/empty-Compute.glsl.snap | 2 + tests/out/empty.msl.snap | 2 +- tests/out/empty.spvasm.snap | 14 +- tests/out/quad-Fragment.glsl.snap | 15 +- tests/out/quad-Vertex.glsl.snap | 22 +- tests/out/quad.dot.snap | 134 ++--- tests/out/quad.msl.snap | 49 +- tests/out/quad.spvasm.snap | 164 ++--- tests/out/shadow-Fragment.glsl.snap | 19 +- tests/out/shadow.info.ron.snap | 90 ++- tests/out/shadow.msl.snap | 31 +- tests/out/shadow.ron.snap | 901 +++++++++++++++------------- tests/out/shadow.spvasm.snap | 260 ++++---- tests/out/skybox-Fragment.glsl.snap | 15 +- tests/out/skybox-Vertex.glsl.snap | 27 +- tests/out/skybox.msl.snap | 62 +- tests/out/skybox.spvasm.snap | 287 ++++----- tests/out/texture-array.spvasm.snap | 132 ++-- tests/parse.rs | 4 +- 50 files changed, 3175 insertions(+), 2367 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c7c5a194e..1af0f869c 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -202,16 +202,14 @@ impl<'a, 'b> FunctionCtx<'a, 'b> { } } - /// Helper method that retrieves the name of the argument in the current function + /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a function argument. /// /// # Panics - /// - If the function is an entry point /// - If the function arguments are less or equal to `arg` - /// - If `names` hasn't been filled properly - fn get_arg<'c>(&self, arg: u32, names: &'c FastHashMap) -> &'c str { + fn argument_key(&self, arg: u32) -> NameKey { match self.func { - FunctionType::Function(handle) => &names[&NameKey::FunctionArgument(handle, arg)], - FunctionType::EntryPoint(_) => unreachable!(), + FunctionType::Function(handle) => NameKey::FunctionArgument(handle, arg), + FunctionType::EntryPoint(ep_index) => NameKey::EntryPointArgument(ep_index, arg), } } } @@ -230,6 +228,33 @@ impl IdGenerator { } } +/// Helper wrapper used to get a name for a varying +/// +/// Varying have different naming schemes depending on their binding: +/// - Varyings with builtin bindings get the from [`glsl_built_in`](glsl_built_in) +/// - Varyings with location bindings are named `_location_X` where `X` is the location +struct VaryingName<'a> { + binding: &'a Binding, + output: bool, +} +impl fmt::Display for VaryingName<'_> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self.binding { + Binding::Location(location, _) => { + write!( + f, + "_{}_location_{}", + if self.output { "out" } else { "in" }, + location, + ) + } + Binding::BuiltIn(built_in) => { + write!(f, "{}", glsl_built_in(built_in)) + } + } + } +} + /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; @@ -450,12 +475,6 @@ impl<'a, W: Write> Writer<'a, W> { continue; } - // Skip builtins - // TODO: Write them if they have modifiers - if let Some(crate::Binding::BuiltIn(_)) = global.binding { - continue; - } - match self.module.types[global.ty].inner { // We treat images separately because they might require // writing the storage format @@ -506,6 +525,15 @@ impl<'a, W: Write> Writer<'a, W> { _ => self.write_global(handle, global)?, } } + + for arg in self.entry_point.function.arguments.iter() { + self.write_varying(arg.binding.as_ref(), arg.ty, false)?; + } + if let Some(ref result) = self.entry_point.function.result { + self.write_varying(result.binding.as_ref(), result.ty, true)?; + } + writeln!(self.out)?; + // Write all regular functions for (handle, function) in self.module.functions.iter() { // Check that the function doesn't use globals that aren't supported @@ -516,7 +544,6 @@ impl<'a, W: Write> Writer<'a, W> { // We also `clone` to satisfy the borrow checker let name = self.names[&NameKey::Function(handle)].clone(); - let fun_info = &self.analysis[handle]; // Write the function @@ -719,22 +746,6 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "writeonly ")?; } - // Write the interpolation modifier if needed - // - // We ignore all interpolation modifiers that aren't used in input globals in fragment - // shaders or output globals in vertex shaders - // - // TODO: Should this throw an error? - if let Some(interpolation) = global.interpolation { - match (self.options.shader_stage, global.class) { - (ShaderStage::Fragment, StorageClass::Input) - | (ShaderStage::Vertex, StorageClass::Output) => { - write!(self.out, "{} ", glsl_interpolation(interpolation)?)?; - } - _ => (), - }; - } - // Write the storage class // Trailing space is important write!(self.out, "{} ", glsl_storage_class(global.class))?; @@ -755,31 +766,65 @@ impl<'a, W: Write> Writer<'a, W> { /// /// Globals have different naming schemes depending on their binding: /// - Globals without bindings use the name from the [`Namer`](crate::proc::Namer) - /// - Globals with builtin bindings get the from [`glsl_built_in`](glsl_built_in) - /// - Globals with location bindings are named `_location_X` where `X` is the location /// - Globals with resource binding are named `_group_X_binding_Y` where `X` /// is the group and `Y` is the binding fn get_global_name(&self, handle: Handle, global: &GlobalVariable) -> String { match global.binding { - Some(Binding::Location(location)) => { - format!( - "_location_{}{}", - location, - match (self.options.shader_stage, global.class) { - (ShaderStage::Fragment, StorageClass::Input) => "_vs", - (ShaderStage::Vertex, StorageClass::Output) => "_vs", - _ => "", - } - ) + Some(ref br) => { + format!("_group_{}_binding_{}", br.group, br.binding) } - Some(Binding::Resource { group, binding }) => { - format!("_group_{}_binding_{}", group, binding) - } - Some(Binding::BuiltIn(built_in)) => glsl_built_in(built_in).to_string(), None => self.names[&NameKey::GlobalVariable(handle)].clone(), } } + /// Writes the varying declaration. + fn write_varying( + &mut self, + binding: Option<&Binding>, + ty: Handle, + output: bool, + ) -> Result<(), Error> { + match self.module.types[ty].inner { + crate::TypeInner::Struct { + block: _, + ref members, + } => { + for member in members { + self.write_varying(member.binding.as_ref(), member.ty, output)?; + } + } + _ => { + let binding = match binding { + Some(binding @ &Binding::Location(..)) => binding, + _ => return Ok(()), + }; + // Write the interpolation modifier if needed + // + // We ignore all interpolation modifiers that aren't used in input globals in fragment + // shaders or output globals in vertex shaders + // + // TODO: Should this throw an error? + if let Binding::Location(_, Some(interp)) = *binding { + if self.options.shader_stage == ShaderStage::Fragment { + write!(self.out, "{} ", glsl_interpolation(interp))?; + } + } + + // Write the storage class + write!(self.out, "{} ", if output { "out" } else { "in" })?; + + // Write the type + // `write_type` adds no leading or trailing spaces + self.write_type(ty)?; + + // Finally write the global name and end the global with a `;` and a newline + // Leading space is important + writeln!(self.out, " {};", VaryingName { binding, output })?; + } + } + Ok(()) + } + /// Helper method used to write functions (both entry points and regular functions) /// /// # Notes @@ -828,8 +873,10 @@ impl<'a, W: Write> Writer<'a, W> { // Start by writing the return type if any otherwise write void // This is the only place where `void` is a valid type // (though it's more a keyword than a type) - if let Some(ty) = func.return_type { - self.write_type(ty)?; + if let FunctionType::EntryPoint(_) = ctx.func { + write!(self.out, "void")?; + } else if let Some(ref result) = func.result { + self.write_type(result.ty)?; } else { write!(self.out, "void")?; } @@ -841,14 +888,18 @@ impl<'a, W: Write> Writer<'a, W> { // // We need access to `Self` here so we use the reference passed to the closure as an // argument instead of capturing as that would cause a borrow checker error - self.write_slice(&func.arguments, |this, i, arg| { + let arguments = match ctx.func { + FunctionType::EntryPoint(_) => &[][..], + FunctionType::Function(_) => &func.arguments, + }; + self.write_slice(arguments, |this, i, arg| { // Write the argument type // `write_type` adds no trailing spaces this.write_type(arg.ty)?; // Write the argument name // The leading space is important - write!(this.out, " {}", ctx.get_arg(i, &this.names))?; + write!(this.out, " {}", &this.names[&ctx.argument_key(i)])?; Ok(()) })?; @@ -856,6 +907,44 @@ impl<'a, W: Write> Writer<'a, W> { // Close the parentheses and open braces to start the function body writeln!(self.out, ") {{")?; + // Compose the function arguments from globals, in case of an entry point. + if let FunctionType::EntryPoint(ep_index) = ctx.func { + for (index, arg) in func.arguments.iter().enumerate() { + write!(self.out, "{}", INDENT)?; + self.write_type(arg.ty)?; + let name = &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)]; + write!(self.out, " {}", name)?; + write!(self.out, " = ")?; + match self.module.types[arg.ty].inner { + crate::TypeInner::Struct { + block: _, + ref members, + } => { + self.write_type(arg.ty)?; + write!(self.out, "(")?; + for (index, member) in members.iter().enumerate() { + let varying_name = VaryingName { + binding: member.binding.as_ref().unwrap(), + output: false, + }; + if index != 0 { + write!(self.out, ", ")?; + } + write!(self.out, "{}", varying_name)?; + } + writeln!(self.out, ");")?; + } + _ => { + let varying_name = VaryingName { + binding: arg.binding.as_ref().unwrap(), + output: false, + }; + writeln!(self.out, "{};", varying_name)?; + } + } + } + } + // Write all function locals // Locals are `type name (= init)?;` where the init part (including the =) are optional // @@ -1228,13 +1317,54 @@ impl<'a, W: Write> Writer<'a, W> { // `return expr;`, `expr` is optional Statement::Return { value } => { write!(self.out, "{}", INDENT.repeat(indent))?; - write!(self.out, "return")?; - // Write the expression to be returned if needed - if let Some(expr) = value { - write!(self.out, " ")?; - self.write_expr(expr, ctx)?; + match ctx.func { + FunctionType::Function(_) => { + write!(self.out, "return")?; + // Write the expression to be returned if needed + if let Some(expr) = value { + write!(self.out, " ")?; + self.write_expr(expr, ctx)?; + } + writeln!(self.out, ";")?; + } + FunctionType::EntryPoint(ep_index) => { + if let Some(ref result) = + self.module.entry_points[ep_index as usize].function.result + { + let value = value.unwrap(); + match self.module.types[result.ty].inner { + crate::TypeInner::Struct { + block: _, + ref members, + } => { + for (index, member) in members.iter().enumerate() { + let varying_name = VaryingName { + binding: member.binding.as_ref().unwrap(), + output: true, + }; + write!(self.out, "{} = ", varying_name)?; + self.write_expr(value, ctx)?; + let field_name = &self.names + [&NameKey::StructMember(result.ty, index as u32)]; + writeln!(self.out, ".{};", field_name)?; + write!(self.out, "{}", INDENT.repeat(indent))?; + } + } + _ => { + let name = VaryingName { + binding: result.binding.as_ref().unwrap(), + output: true, + }; + write!(self.out, "{} = ", name)?; + self.write_expr(value, ctx)?; + writeln!(self.out, ";")?; + write!(self.out, "{}", INDENT.repeat(indent))?; + } + } + } + writeln!(self.out, "return;")?; + } } - writeln!(self.out, ";")?; } // This is one of the places were glsl adds to the syntax of C in this case the discard // keyword which ceases all further processing in a fragment shader, it's called OpKill @@ -1282,8 +1412,8 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { let name = format!("_expr{}", expr.index()); - let ty = self.module.functions[function].return_type.unwrap(); - self.write_type(ty)?; + let result = self.module.functions[function].result.as_ref().unwrap(); + self.write_type(result.ty)?; write!(self.out, " {} = ", name)?; self.cached_expressions.insert(expr, name); } @@ -1362,7 +1492,7 @@ impl<'a, W: Write> Writer<'a, W> { } // Function arguments are written as the argument name Expression::FunctionArgument(pos) => { - write!(self.out, "{}", ctx.get_arg(pos, &self.names))? + write!(self.out, "{}", &self.names[&ctx.argument_key(pos)])? } // Global variables need some special work for their name but // `get_global_name` does the work for us @@ -2018,12 +2148,12 @@ fn glsl_built_in(built_in: BuiltIn) -> &'static str { match built_in { // vertex BuiltIn::Position => "gl_Position", - BuiltIn::BaseInstance => "gl_BaseInstance", - BuiltIn::BaseVertex => "gl_BaseVertex", + BuiltIn::BaseInstance => "uint(gl_BaseInstance)", + BuiltIn::BaseVertex => "uint(gl_BaseVertex)", BuiltIn::ClipDistance => "gl_ClipDistance", - BuiltIn::InstanceIndex => "gl_InstanceID", + BuiltIn::InstanceIndex => "uint(gl_InstanceID)", BuiltIn::PointSize => "gl_PointSize", - BuiltIn::VertexIndex => "gl_VertexID", + BuiltIn::VertexIndex => "uint(gl_VertexID)", // fragment BuiltIn::FragCoord => "gl_FragCoord", BuiltIn::FragDepth => "gl_FragDepth", @@ -2044,8 +2174,6 @@ fn glsl_built_in(built_in: BuiltIn) -> &'static str { fn glsl_storage_class(class: StorageClass) -> &'static str { match class { StorageClass::Function => "", - StorageClass::Input => "in", - StorageClass::Output => "out", StorageClass::Private => "", StorageClass::Storage => "buffer", StorageClass::Uniform => "uniform", @@ -2056,18 +2184,14 @@ fn glsl_storage_class(class: StorageClass) -> &'static str { } /// Helper function that returns the string corresponding to the glsl interpolation qualifier -/// -/// # Errors -/// If [`Patch`](crate::Interpolation::Patch) is passed, as it isn't supported in glsl -fn glsl_interpolation(interpolation: Interpolation) -> Result<&'static str, Error> { - Ok(match interpolation { +fn glsl_interpolation(interpolation: Interpolation) -> &'static str { + match interpolation { Interpolation::Perspective => "smooth", Interpolation::Linear => "noperspective", Interpolation::Flat => "flat", Interpolation::Centroid => "centroid", Interpolation::Sample => "sample", - Interpolation::Patch => return Err(Error::PatchInterpolationNotSupported), - }) + } } /// Helper function that returns the glsl dimension string of [`ImageDimension`](crate::ImageDimension) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 353b1e148..e9ae61e5b 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -7,11 +7,20 @@ from SPIR-V's descriptor sets, we require a separate mapping provided in the opt This mapping may have one or more resource end points for each descriptor set + index pair. -## Outputs +## Entry points -In Metal, built-in shader outputs can not be nested into structures within -the output struct. If there is a structure in the outputs, and it contains any built-ins, -we move them up to the root output structure that we define ourselves. +Even though MSL and our IR appear to be similar in that the entry points in both can +accept arguments and return values, the restrictions are different. +MSL allows the varyings to be either in separate arguments, or inside a single +`[[stage_in]]` struct. We gather input varyings and form this artificial structure. +We also add all the (non-Private) globals into the arguments. + +At the beginning of the entry point, we assign the local constants and re-compose +the arguments as they are declared on IR side, so that the rest of the logic can +pretend that MSL doesn't have all the restrictions it has. + +For the result type, if it's a structure, we re-compose it with a temporary value +holding the result. !*/ use crate::{ @@ -112,15 +121,14 @@ impl Default for Options { } impl Options { - fn resolve_binding( + fn resolve_local_binding( &self, - stage: crate::ShaderStage, - var: &crate::GlobalVariable, + binding: &crate::Binding, mode: LocationMode, ) -> Result { - match var.binding { - Some(crate::Binding::BuiltIn(built_in)) => Ok(ResolvedBinding::BuiltIn(built_in)), - Some(crate::Binding::Location(index)) => match mode { + match *binding { + crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), + crate::Binding::Location(index, _) => match mode { LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(index)), LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(index)), LocationMode::Intermediate => Ok(ResolvedBinding::User { @@ -139,25 +147,26 @@ impl Options { Err(Error::Validation) } }, - Some(crate::Binding::Resource { group, binding }) => { - let source = BindSource { - stage, - group, - binding, - }; - match self.binding_map.get(&source) { - Some(target) => Ok(ResolvedBinding::Resource(target.clone())), - None if self.fake_missing_bindings => Ok(ResolvedBinding::User { - prefix: "fake", - index: 0, - }), - None => Err(Error::MissingBindTarget(source)), - } - } - None => { - log::error!("Missing binding for {:?}", var.name); - Err(Error::Validation) - } + } + } + + fn resolve_global_binding( + &self, + stage: crate::ShaderStage, + res_binding: &crate::ResourceBinding, + ) -> Result { + let source = BindSource { + stage, + group: res_binding.group, + binding: res_binding.binding, + }; + match self.binding_map.get(&source) { + Some(target) => Ok(ResolvedBinding::Resource(target.clone())), + None if self.fake_missing_bindings => Ok(ResolvedBinding::User { + prefix: "fake", + index: 0, + }), + None => Err(Error::MissingBindTarget(source)), } } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index df8954ad8..39d3e1e19 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -92,15 +92,13 @@ fn vector_size_string(size: crate::VectorSize) -> &'static str { } } -const OUTPUT_STRUCT_NAME: &str = "output"; -const LOCATION_INPUT_STRUCT_NAME: &str = "input"; const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; -fn separate(is_last: bool) -> &'static str { - if is_last { - "" - } else { +fn separate(need_separator: bool) -> &'static str { + if need_separator { "," + } else { + "" } } @@ -111,8 +109,7 @@ impl crate::StorageClass { /// called from the entry point. fn needs_pass_through(&self) -> bool { match *self { - crate::StorageClass::Input - | crate::StorageClass::Uniform + crate::StorageClass::Uniform | crate::StorageClass::Storage | crate::StorageClass::Handle => true, _ => false, @@ -121,7 +118,7 @@ impl crate::StorageClass { fn get_name(&self, global_use: GlobalUse) -> Option<&'static str> { match *self { - Self::Input | Self::Output | Self::Handle => None, + Self::Handle => None, Self::Uniform => Some("constant"), //TODO: should still be "constant" for read-only buffers Self::Storage => Some(if global_use.contains(GlobalUse::WRITE) { @@ -149,7 +146,7 @@ struct ExpressionContext<'a> { struct StatementContext<'a> { expression: ExpressionContext<'a>, fun_info: &'a FunctionInfo, - return_value: Option<&'a str>, + result_struct: Option<&'a str>, } impl Writer { @@ -287,30 +284,16 @@ impl Writer { } } crate::Expression::FunctionArgument(index) => { - let fun_handle = match context.origin { - FunctionOrigin::Handle(handle) => handle, - FunctionOrigin::EntryPoint(_) => unreachable!(), + let name_key = match context.origin { + FunctionOrigin::Handle(handle) => NameKey::FunctionArgument(handle, index), + FunctionOrigin::EntryPoint(ep_index) => { + NameKey::EntryPointArgument(ep_index, index) + } }; - let name = &self.names[&NameKey::FunctionArgument(fun_handle, index)]; + let name = &self.names[&name_key]; write!(self.out, "{}", name)?; } crate::Expression::GlobalVariable(handle) => { - let var = &context.module.global_variables[handle]; - match var.class { - crate::StorageClass::Output => { - if let crate::TypeInner::Struct { .. } = context.module.types[var.ty].inner - { - return Ok(()); - } - write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; - } - crate::StorageClass::Input => { - if let Some(crate::Binding::Location(_)) = var.binding { - write!(self.out, "{}.", LOCATION_INPUT_STRUCT_NAME)?; - } - } - _ => {} - } let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; } @@ -771,17 +754,42 @@ impl Writer { crate::Statement::Return { value: Some(expr_handle), } => { - write!(self.out, "{}return ", level)?; - self.put_expression(expr_handle, &context.expression)?; + match context.result_struct { + Some(struct_name) => { + let result_ty = context.expression.function.result.as_ref().unwrap().ty; + match context.expression.module.types[result_ty].inner { + crate::TypeInner::Struct { + block: _, + ref members, + } => { + let tmp = "_tmp"; + write!(self.out, "{}const auto {} = ", level, tmp)?; + self.put_expression(expr_handle, &context.expression)?; + writeln!(self.out, ";")?; + write!(self.out, "{}return {} {{", level, struct_name)?; + for index in 0..members.len() as u32 { + let comma = if index == 0 { "" } else { "," }; + let name = + &self.names[&NameKey::StructMember(result_ty, index)]; + write!(self.out, "{} {}.{}", comma, tmp, name)?; + } + } + _ => { + write!(self.out, "{}return {} {{ ", level, struct_name)?; + self.put_expression(expr_handle, &context.expression)?; + } + } + write!(self.out, " }}")?; + } + None => { + write!(self.out, "{}return ", level)?; + self.put_expression(expr_handle, &context.expression)?; + } + } writeln!(self.out, ";")?; } crate::Statement::Return { value: None } => { - writeln!( - self.out, - "{}return {};", - level, - context.return_value.unwrap_or_default(), - )?; + writeln!(self.out, "{}return;", level)?; } crate::Statement::Kill => { writeln!(self.out, "{}{}::discard_fragment();", level, NAMESPACE)?; @@ -1107,8 +1115,8 @@ impl Writer { } let fun_name = &self.names[&NameKey::Function(fun_handle)]; - let result_type_name = match fun.return_type { - Some(ret_ty) => &self.names[&NameKey::Type(ret_ty)], + let result_type_name = match fun.result { + Some(ref result) => &self.names[&NameKey::Type(result.ty)], None => "void", }; writeln!(self.out, "{} {}(", result_type_name, fun_name)?; @@ -1117,7 +1125,7 @@ impl Writer { let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; let param_type_name = &self.names[&NameKey::Type(arg.ty)]; let separator = - separate(pass_through_globals.is_empty() && index + 1 == fun.arguments.len()); + separate(!pass_through_globals.is_empty() || index + 1 != fun.arguments.len()); writeln!( self.out, "{}{} {}{}", @@ -1131,7 +1139,7 @@ impl Writer { handle, usage: fun_info[handle], }; - let separator = separate(index + 1 == pass_through_globals.len()); + let separator = separate(index + 1 != pass_through_globals.len()); write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; writeln!(self.out, "{}", separator)?; @@ -1157,7 +1165,7 @@ impl Writer { analysis, }, fun_info, - return_value: None, + result_struct: None, }; self.named_expressions.clear(); self.put_block(Level(1), &fun.body, &context)?; @@ -1183,27 +1191,11 @@ impl Writer { }, )?; - // find the entry point(s) and inputs/outputs - let mut last_used_global = None; - for (handle, var) in module.global_variables.iter() { - match var.class { - crate::StorageClass::Input => { - if let Some(crate::Binding::Location(_)) = var.binding { - continue; - } - } - crate::StorageClass::Output => continue, - _ => {} - } - if !fun_info[handle].is_empty() { - last_used_global = Some(handle); - } - } - let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; info.entry_point_names.push(fun_name.clone()); - let output_name = format!("{}Output", fun_name); - let location_input_name = format!("{}Input", fun_name); + + let stage_out_name = format!("{}Output", fun_name); + let stage_in_name = format!("{}Input", fun_name); let (em_str, in_mode, out_mode) = match ep.stage { crate::ShaderStage::Vertex => ( @@ -1221,110 +1213,135 @@ impl Writer { } }; - let return_value = match ep.stage { - crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { - // make dedicated input/output structs - writeln!(self.out, "struct {} {{", location_input_name)?; - for (handle, var) in module.global_variables.iter() { - if var.class != crate::StorageClass::Input - || !fun_info[handle].contains(GlobalUse::READ) - { - continue; + let mut argument_members = Vec::new(); + for (arg_index, arg) in fun.arguments.iter().enumerate() { + match module.types[arg.ty].inner { + crate::TypeInner::Struct { + block: _, + ref members, + } => { + for (member_index, member) in members.iter().enumerate() { + argument_members.push(( + NameKey::StructMember(arg.ty, member_index as u32), + member.ty, + member.binding.as_ref(), + )) } - if let Some(crate::Binding::BuiltIn(_)) = var.binding { - // MSL disallows built-ins in input structs - continue; + } + _ => argument_members.push(( + NameKey::EntryPointArgument(ep_index as _, arg_index as u32), + arg.ty, + arg.binding.as_ref(), + )), + } + } + let varyings_member_name = self.namer.call("varyings"); + let mut varying_count = 0; + if !argument_members.is_empty() { + writeln!(self.out, "struct {} {{", stage_in_name)?; + for &(ref name_key, ty, binding) in argument_members.iter() { + let binding = match binding { + Some(ref binding @ &crate::Binding::Location(..)) => binding, + _ => continue, + }; + varying_count += 1; + let name = &self.names[&name_key]; + let type_name = &self.names[&NameKey::Type(ty)]; + let resolved = options.resolve_local_binding(binding, in_mode)?; + write!(self.out, "{}{} {}", INDENT, type_name, name)?; + resolved.try_fmt_decorated(&mut self.out, "")?; + writeln!(self.out, ";")?; + } + writeln!(self.out, "}};")?; + } + + let result_member_name = self.namer.call("member"); + let result_type_name = match fun.result { + Some(ref result) => { + let mut result_members = Vec::new(); + if let crate::TypeInner::Struct { + block: _, + ref members, + } = module.types[result.ty].inner + { + for (member_index, member) in members.iter().enumerate() { + result_members.push(( + &self.names[&NameKey::StructMember(result.ty, member_index as u32)], + member.ty, + member.binding.as_ref(), + )); } - let tyvar = TypedGlobalVariable { - module, - names: &self.names, - handle, - usage: GlobalUse::empty(), - }; - write!(self.out, "{}", INDENT)?; - tyvar.try_fmt(&mut self.out)?; - let resolved = options.resolve_binding(ep.stage, var, in_mode)?; - resolved.try_fmt_decorated(&mut self.out, ";")?; - writeln!(self.out)?; + } else { + result_members.push(( + &result_member_name, + result.ty, + result.binding.as_ref(), + )); + } + writeln!(self.out, "struct {} {{", stage_out_name)?; + for (name, ty, binding) in result_members { + let type_name = &self.names[&NameKey::Type(ty)]; + let binding = binding.ok_or(Error::Validation)?; + let resolved = options.resolve_local_binding(binding, out_mode)?; + write!(self.out, "{}{} {}", INDENT, type_name, name)?; + resolved.try_fmt_decorated(&mut self.out, "")?; + writeln!(self.out, ";")?; } writeln!(self.out, "}};")?; - writeln!(self.out)?; - - writeln!(self.out, "struct {} {{", output_name)?; - for (handle, var) in module.global_variables.iter() { - if var.class != crate::StorageClass::Output - || !fun_info[handle].contains(GlobalUse::WRITE) - { - continue; - } - - let tyvar = TypedGlobalVariable { - module, - names: &self.names, - handle, - usage: GlobalUse::empty(), - }; - write!(self.out, "{}", INDENT)?; - tyvar.try_fmt(&mut self.out)?; - let resolved = options.resolve_binding(ep.stage, var, out_mode)?; - resolved.try_fmt_decorated(&mut self.out, ";")?; - writeln!(self.out)?; - } - writeln!(self.out, "}};")?; - writeln!(self.out)?; - - writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?; - let separator = separate(last_used_global.is_none()); - writeln!( - self.out, - "{}{} {} [[stage_in]]{}", - INDENT, location_input_name, LOCATION_INPUT_STRUCT_NAME, separator - )?; - - Some(OUTPUT_STRUCT_NAME) - } - crate::ShaderStage::Compute => { - writeln!(self.out, "{} void {}(", em_str, fun_name)?; - None + &stage_out_name } + None => "void", }; + writeln!(self.out, "{} {} {}(", em_str, result_type_name, fun_name)?; + let mut is_first_argument = true; + if varying_count != 0 { + writeln!( + self.out, + " {} {} [[stage_in]]", + stage_in_name, varyings_member_name + )?; + is_first_argument = false; + } + for &(ref name_key, ty, binding) in argument_members.iter() { + let binding = match binding { + Some(ref binding @ &crate::Binding::BuiltIn(..)) => binding, + _ => continue, + }; + let name = &self.names[&name_key]; + let type_name = &self.names[&NameKey::Type(ty)]; + let resolved = options.resolve_local_binding(binding, in_mode)?; + let separator = if is_first_argument { + is_first_argument = false; + ' ' + } else { + ',' + }; + write!(self.out, "{} {} {}", separator, type_name, name)?; + resolved.try_fmt_decorated(&mut self.out, "\n")?; + } for (handle, var) in module.global_variables.iter() { let usage = fun_info[handle]; - if usage.is_empty() || var.class == crate::StorageClass::Output { + if usage.is_empty() || var.class == crate::StorageClass::Private { continue; } - if var.class == crate::StorageClass::Input { - if let Some(crate::Binding::Location(_)) = var.binding { - // location inputs are put into a separate struct - continue; - } - } - let loc_mode = match (ep.stage, var.class) { - (crate::ShaderStage::Vertex, crate::StorageClass::Input) => { - LocationMode::VertexInput - } - (crate::ShaderStage::Vertex, crate::StorageClass::Output) - | (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Input) => { - LocationMode::Intermediate - } - (crate::ShaderStage::Fragment { .. }, crate::StorageClass::Output) => { - LocationMode::FragmentOutput - } - _ => LocationMode::Uniform, - }; let tyvar = TypedGlobalVariable { module, names: &self.names, handle, usage, }; - let separator = separate(last_used_global == Some(handle)); - write!(self.out, "{}", INDENT)?; + let separator = if is_first_argument { + is_first_argument = false; + ' ' + } else { + ',' + }; + write!(self.out, "{} ", separator)?; tyvar.try_fmt(&mut self.out)?; - if var.binding.is_some() { - let resolved = options.resolve_binding(ep.stage, var, loc_mode)?; - resolved.try_fmt_decorated(&mut self.out, separator)?; + if let Some(ref binding) = var.binding { + let resolved = options.resolve_global_binding(ep.stage, binding)?; + resolved.try_fmt_decorated(&mut self.out, "")?; } if let Some(value) = var.init { let value_str = &self.names[&NameKey::Constant(value)]; @@ -1332,18 +1349,72 @@ impl Writer { } writeln!(self.out)?; } + + // end of the entry point argument list writeln!(self.out, ") {{")?; - match ep.stage { - crate::ShaderStage::Vertex | crate::ShaderStage::Fragment => { - writeln!( - self.out, - "{}{} {};", - INDENT, output_name, OUTPUT_STRUCT_NAME - )?; + // Metal doesn't support private mutable variables outside of functions, + // so we put them here, just like the locals. + for (handle, var) in module.global_variables.iter() { + let usage = fun_info[handle]; + if usage.is_empty() || var.class != crate::StorageClass::Private { + continue; } - crate::ShaderStage::Compute => {} + let tyvar = TypedGlobalVariable { + module, + names: &self.names, + handle, + usage, + }; + write!(self.out, "{}", INDENT)?; + tyvar.try_fmt(&mut self.out)?; + if let Some(value) = var.init { + let value_str = &self.names[&NameKey::Constant(value)]; + write!(self.out, " = {}", value_str)?; + } + writeln!(self.out, ";")?; } + + // Now refactor the inputs in a way that the rest of the code expects + for (arg_index, arg) in fun.arguments.iter().enumerate() { + let arg_name = + &self.names[&NameKey::EntryPointArgument(ep_index as _, arg_index as u32)]; + match module.types[arg.ty].inner { + crate::TypeInner::Struct { + block: _, + ref members, + } => { + let struct_name = &self.names[&NameKey::Type(arg.ty)]; + write!( + self.out, + "{}const {} {} = {{", + INDENT, struct_name, arg_name + )?; + for member_index in 0..members.len() { + let name = + &self.names[&NameKey::StructMember(arg.ty, member_index as u32)]; + let separator = if member_index != 0 { ", " } else { "" }; + write!(self.out, "{}{}", INDENT, separator)?; + if let Some(crate::Binding::Location(..)) = arg.binding { + write!(self.out, "{}.", varyings_member_name)?; + } + write!(self.out, "{}", name)?; + } + } + _ => { + if let Some(crate::Binding::Location(..)) = arg.binding { + writeln!( + self.out, + "{}const auto {} = {}.{};", + INDENT, arg_name, varyings_member_name, arg_name + )?; + } + } + } + } + + // Finally, declare all the local variables that we need + //TODO: we can postpone this till the relevant expressions are emitted for (local_handle, local) in fun.local_variables.iter() { let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; let ty_name = &self.names[&NameKey::Type(local.ty)]; @@ -1363,13 +1434,12 @@ impl Writer { analysis, }, fun_info, - return_value, + result_struct: Some(&stage_out_name), }; self.named_expressions.clear(); self.put_block(Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; - let is_last = ep_index == module.entry_points.len() - 1; - if !is_last { + if ep_index + 1 != module.entry_points.len() { writeln!(self.out)?; } } diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index 1c3938cd8..b2879089f 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -27,6 +27,22 @@ impl PhysicalLayout { pub(super) fn supports_storage_buffers(&self) -> bool { self.version >= 0x10300 } + + pub(super) fn map_storage_class(&self, class: crate::StorageClass) -> spirv::StorageClass { + match class { + crate::StorageClass::Handle => spirv::StorageClass::UniformConstant, + crate::StorageClass::Function => spirv::StorageClass::Function, + crate::StorageClass::Private => spirv::StorageClass::Private, + crate::StorageClass::Storage if self.supports_storage_buffers() => { + spirv::StorageClass::StorageBuffer + } + crate::StorageClass::Storage | crate::StorageClass::Uniform => { + spirv::StorageClass::Uniform + } + crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, + crate::StorageClass::PushConstant => spirv::StorageClass::PushConstant, + } + } } impl LogicalLayout { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b728fded0..28732354c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -46,12 +46,19 @@ struct LocalVariable { instruction: Instruction, } +#[derive(Default)] +struct EntryPointContext { + argument_ids: Vec, + result_ids_typed: Vec<(Word, Word)>, +} + #[derive(Default)] struct Function { signature: Option, parameters: Vec, variables: crate::FastHashMap, LocalVariable>, blocks: Vec, + entry_point_context: Option, } impl Function { @@ -86,7 +93,7 @@ enum LocalType { vector_size: Option, kind: crate::ScalarKind, width: crate::Bytes, - pointer_class: Option, + pointer_class: Option, }, Matrix { columns: crate::VectorSize, @@ -95,15 +102,15 @@ enum LocalType { }, Pointer { base: Handle, - class: crate::StorageClass, + class: spirv::StorageClass, }, SampledImage { image_type: Handle, }, } -impl LocalType { - fn from_inner(inner: &crate::TypeInner) -> Option { +impl PhysicalLayout { + fn make_local(&self, inner: &crate::TypeInner) -> Option { Some(match *inner { crate::TypeInner::Scalar { kind, width } => LocalType::Value { vector_size: None, @@ -126,7 +133,10 @@ impl LocalType { rows, width, }, - crate::TypeInner::Pointer { base, class } => LocalType::Pointer { base, class }, + crate::TypeInner::Pointer { base, class } => LocalType::Pointer { + base, + class: self.map_storage_class(class), + }, crate::TypeInner::ValuePointer { size, kind, @@ -136,7 +146,7 @@ impl LocalType { vector_size: size, kind, width, - pointer_class: Some(class), + pointer_class: Some(self.map_storage_class(class)), }, _ => return None, }) @@ -318,10 +328,12 @@ impl Writer { Ok(*e.get()) } else { match lookup_ty { - LookupType::Handle(handle) => match LocalType::from_inner(&arena[handle].inner) { - Some(local) => self.get_type_id(arena, LookupType::Local(local)), - None => self.write_type_declaration_arena(arena, handle), - }, + LookupType::Handle(handle) => { + match self.physical_layout.make_local(&arena[handle].inner) { + Some(local) => self.get_type_id(arena, LookupType::Local(local)), + None => self.write_type_declaration_arena(arena, handle), + } + } LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty), } } @@ -331,36 +343,25 @@ impl Writer { &mut self, arena: &Arena, handle: Handle, - class: crate::StorageClass, + class: spirv::StorageClass, ) -> Result { let ty_id = self.get_type_id(arena, LookupType::Handle(handle))?; if let crate::TypeInner::Pointer { .. } = arena[handle].inner { return Ok(ty_id); } - Ok( - match self - .lookup_type - .entry(LookupType::Local(LocalType::Pointer { - base: handle, - class, - })) { - Entry::Occupied(e) => *e.get(), - _ => { - let storage_class = self.parse_to_spirv_storage_class(class); - let id = self.generate_id(); - let instruction = Instruction::type_pointer(id, storage_class, ty_id); - instruction.to_words(&mut self.logical_layout.declarations); - self.lookup_type.insert( - LookupType::Local(LocalType::Pointer { - base: handle, - class, - }), - id, - ); - id - } - }, - ) + let lookup_type = LookupType::Local(LocalType::Pointer { + base: handle, + class, + }); + Ok(if let Some(&id) = self.lookup_type.get(&lookup_type) { + id + } else { + let id = self.generate_id(); + let instruction = Instruction::type_pointer(id, class, ty_id); + instruction.to_words(&mut self.logical_layout.declarations); + self.lookup_type.insert(lookup_type, id); + id + }) } fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word { @@ -375,6 +376,7 @@ impl Writer { ir_function: &crate::Function, info: &FunctionInfo, ir_module: &crate::Module, + mut varying_ids: Option<&mut Vec>, ) -> Result { let mut function = Function::default(); @@ -403,7 +405,7 @@ impl Writer { .init .map(|constant| self.lookup_constant[&constant]); let pointer_type_id = - self.get_pointer_id(&ir_module.types, variable.ty, crate::StorageClass::Function)?; + self.get_pointer_id(&ir_module.types, variable.ty, spirv::StorageClass::Function)?; let instruction = Instruction::variable( pointer_type_id, id, @@ -415,21 +417,101 @@ impl Writer { .insert(handle, LocalVariable { id, instruction }); } - let return_type_id = match ir_function.return_type { - Some(handle) => self.get_type_id(&ir_module.types, LookupType::Handle(handle))?, + let prelude_id = self.generate_id(); + let mut prelude = Block::new(prelude_id); + let mut ep_context = EntryPointContext::default(); + + let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); + for argument in ir_function.arguments.iter() { + let class = spirv::StorageClass::Input; + let argument_type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(argument.ty))?; + if let Some(ref mut list) = varying_ids { + let id = if let Some(ref binding) = argument.binding { + let name = argument.name.as_ref().map(AsRef::as_ref); + let varying_id = + self.write_varying(ir_module, class, name, argument.ty, binding)?; + list.push(varying_id); + let id = self.generate_id(); + prelude + .body + .push(Instruction::load(argument_type_id, id, varying_id, None)); + id + } else if let crate::TypeInner::Struct { + block: _, + ref members, + } = ir_module.types[argument.ty].inner + { + let struct_id = self.generate_id(); + let mut constituent_ids = Vec::with_capacity(members.len()); + for member in members { + let type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(member.ty))?; + let name = member.name.as_ref().map(AsRef::as_ref); + let binding = member.binding.as_ref().unwrap(); + let varying_id = + self.write_varying(ir_module, class, name, member.ty, binding)?; + list.push(varying_id); + let id = self.generate_id(); + prelude + .body + .push(Instruction::load(type_id, id, varying_id, None)); + constituent_ids.push(id); + } + prelude.body.push(Instruction::composite_construct( + argument_type_id, + struct_id, + &constituent_ids, + )); + struct_id + } else { + unreachable!("Missing argument binding on an entry point"); + }; + ep_context.argument_ids.push(id); + } else { + let id = self.generate_id(); + let instruction = Instruction::function_parameter(argument_type_id, id); + function.parameters.push(instruction); + parameter_type_ids.push(argument_type_id); + }; + } + + let return_type_id = match ir_function.result { + Some(ref result) => { + if let Some(ref mut list) = varying_ids { + let class = spirv::StorageClass::Output; + if let Some(ref binding) = result.binding { + let type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(result.ty))?; + let varying_id = + self.write_varying(ir_module, class, None, result.ty, binding)?; + list.push(varying_id); + ep_context.result_ids_typed.push((varying_id, type_id)); + } else if let crate::TypeInner::Struct { + block: _, + ref members, + } = ir_module.types[result.ty].inner + { + for member in members { + let type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(member.ty))?; + let name = member.name.as_ref().map(AsRef::as_ref); + let binding = member.binding.as_ref().unwrap(); + let varying_id = + self.write_varying(ir_module, class, name, member.ty, binding)?; + list.push(varying_id); + ep_context.result_ids_typed.push((varying_id, type_id)); + } + } else { + unreachable!("Missing result binding on an entry point"); + } + self.void_type + } else { + self.get_type_id(&ir_module.types, LookupType::Handle(result.ty))? + } + } None => self.void_type, }; - let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); - - for argument in ir_function.arguments.iter() { - let id = self.generate_id(); - let parameter_type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(argument.ty))?; - parameter_type_ids.push(parameter_type_id); - function - .parameters - .push(Instruction::function_parameter(parameter_type_id, id)); - } let lookup_function_type = LookupFunctionType { return_type_id, @@ -451,8 +533,9 @@ impl Writer { function_type, )); - let prelude_id = self.generate_id(); - let mut prelude = Block::new(prelude_id); + if varying_ids.is_some() { + function.entry_point_context = Some(ep_context); + } // fill up the `GlobalVariable::handle_id` for gv in self.global_variables.iter_mut() { @@ -510,18 +593,13 @@ impl Writer { info: &FunctionInfo, ir_module: &crate::Module, ) -> Result { - let function_id = self.write_function(&entry_point.function, info, ir_module)?; - let mut interface_ids = Vec::new(); - for (handle, var) in ir_module.global_variables.iter() { - if info[handle].is_empty() { - continue; - } - if let crate::StorageClass::Input | crate::StorageClass::Output = var.class { - let id = self.global_variables[handle.index()].id; - interface_ids.push(id); - } - } + let function_id = self.write_function( + &entry_point.function, + info, + ir_module, + Some(&mut interface_ids), + )?; let exec_model = match entry_point.stage { crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, @@ -573,24 +651,6 @@ impl Writer { } } - fn parse_to_spirv_storage_class(&self, class: crate::StorageClass) -> spirv::StorageClass { - match class { - crate::StorageClass::Handle => spirv::StorageClass::UniformConstant, - crate::StorageClass::Function => spirv::StorageClass::Function, - crate::StorageClass::Input => spirv::StorageClass::Input, - crate::StorageClass::Output => spirv::StorageClass::Output, - crate::StorageClass::Private => spirv::StorageClass::Private, - crate::StorageClass::Storage if self.physical_layout.supports_storage_buffers() => { - spirv::StorageClass::StorageBuffer - } - crate::StorageClass::Storage | crate::StorageClass::Uniform => { - spirv::StorageClass::Uniform - } - crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, - crate::StorageClass::PushConstant => spirv::StorageClass::PushConstant, - } - } - fn write_type_declaration_local( &mut self, arena: &Arena, @@ -639,7 +699,7 @@ impl Writer { } LocalType::Pointer { base, class } => { let type_id = self.get_type_id(arena, LookupType::Handle(base))?; - Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) + Instruction::type_pointer(id, class, type_id) } LocalType::Value { vector_size, @@ -656,7 +716,7 @@ impl Writer { pointer_class: None, }), )?; - Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) + Instruction::type_pointer(id, class, type_id) } LocalType::SampledImage { image_type } => { let image_type_id = self.get_type_id(arena, LookupType::Handle(image_type))?; @@ -860,9 +920,15 @@ impl Writer { } crate::TypeInner::Pointer { base, class } => { let type_id = self.get_type_id(arena, LookupType::Handle(base))?; - self.lookup_type - .insert(LookupType::Local(LocalType::Pointer { base, class }), id); - Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) + let raw_class = self.physical_layout.map_storage_class(class); + self.lookup_type.insert( + LookupType::Local(LocalType::Pointer { + base, + class: raw_class, + }), + id, + ); + Instruction::type_pointer(id, raw_class, type_id) } crate::TypeInner::ValuePointer { size, @@ -870,6 +936,7 @@ impl Writer { width, class, } => { + let raw_class = self.physical_layout.map_storage_class(class); let type_id = self.get_type_id( arena, LookupType::Local(LocalType::Value { @@ -884,11 +951,11 @@ impl Writer { vector_size: size, kind, width, - pointer_class: Some(class), + pointer_class: Some(raw_class), }), id, ); - Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id) + Instruction::type_pointer(id, raw_class, type_id) } }; @@ -979,76 +1046,45 @@ impl Writer { Ok(()) } - fn write_global_variable( + fn write_varying( &mut self, ir_module: &crate::Module, - handle: Handle, - ) -> Result<(Instruction, Word, spirv::StorageClass), Error> { - let global_variable = &ir_module.global_variables[handle]; + class: spirv::StorageClass, + debug_name: Option<&str>, + ty: Handle, + binding: &crate::Binding, + ) -> Result { let id = self.generate_id(); - - let class = self.parse_to_spirv_storage_class(global_variable.class); - self.check(class.required_capabilities())?; - - let init_word = global_variable - .init - .map(|constant| self.lookup_constant[&constant]); - let pointer_type_id = - self.get_pointer_id(&ir_module.types, global_variable.ty, global_variable.class)?; - let instruction = Instruction::variable(pointer_type_id, id, class, init_word); + let pointer_type_id = self.get_pointer_id(&ir_module.types, ty, class)?; + Instruction::variable(pointer_type_id, id, class, None) + .to_words(&mut self.logical_layout.declarations); if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = global_variable.name { + if let Some(name) = debug_name { self.debugs.push(Instruction::name(id, name)); } } - let access_decoration = match global_variable.storage_access { - crate::StorageAccess::LOAD => Some(spirv::Decoration::NonWritable), - crate::StorageAccess::STORE => Some(spirv::Decoration::NonReadable), - _ => None, - }; - if let Some(decoration) = access_decoration { - self.annotations - .push(Instruction::decorate(id, decoration, &[])); - } - - if let Some(interpolation) = global_variable.interpolation { - let decoration = match interpolation { - crate::Interpolation::Linear => Some(spirv::Decoration::NoPerspective), - crate::Interpolation::Flat => Some(spirv::Decoration::Flat), - crate::Interpolation::Patch => Some(spirv::Decoration::Patch), - crate::Interpolation::Centroid => Some(spirv::Decoration::Centroid), - crate::Interpolation::Sample => Some(spirv::Decoration::Sample), - crate::Interpolation::Perspective => None, - }; - if let Some(decoration) = decoration { - self.annotations - .push(Instruction::decorate(id, decoration, &[])); - } - } - - match global_variable.binding { - Some(crate::Binding::Location(location)) => { + match *binding { + crate::Binding::Location(location, interpolation) => { self.annotations.push(Instruction::decorate( id, spirv::Decoration::Location, &[location], )); + let interp_decoration = match interpolation { + Some(crate::Interpolation::Linear) => Some(spirv::Decoration::NoPerspective), + Some(crate::Interpolation::Flat) => Some(spirv::Decoration::Flat), + Some(crate::Interpolation::Centroid) => Some(spirv::Decoration::Centroid), + Some(crate::Interpolation::Sample) => Some(spirv::Decoration::Sample), + Some(crate::Interpolation::Perspective) | None => None, + }; + if let Some(decoration) = interp_decoration { + self.annotations + .push(Instruction::decorate(id, decoration, &[])); + } } - Some(crate::Binding::Resource { group, binding }) => { - self.annotations.push(Instruction::decorate( - id, - spirv::Decoration::DescriptorSet, - &[group], - )); - self.annotations.push(Instruction::decorate( - id, - spirv::Decoration::Binding, - &[binding], - )); - } - Some(crate::Binding::BuiltIn(built_in)) => { + crate::Binding::BuiltIn(built_in) => { use crate::BuiltIn as Bi; let built_in = match built_in { Bi::BaseInstance => spirv::BuiltIn::BaseInstance, @@ -1079,7 +1115,57 @@ impl Writer { &[built_in as u32], )); } - None => {} + } + + Ok(id) + } + + fn write_global_variable( + &mut self, + ir_module: &crate::Module, + handle: Handle, + ) -> Result<(Instruction, Word, spirv::StorageClass), Error> { + let global_variable = &ir_module.global_variables[handle]; + let id = self.generate_id(); + + let class = self + .physical_layout + .map_storage_class(global_variable.class); + self.check(class.required_capabilities())?; + + let init_word = global_variable + .init + .map(|constant| self.lookup_constant[&constant]); + let pointer_type_id = self.get_pointer_id(&ir_module.types, global_variable.ty, class)?; + let instruction = Instruction::variable(pointer_type_id, id, class, init_word); + + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = global_variable.name { + self.debugs.push(Instruction::name(id, name)); + } + } + + let access_decoration = match global_variable.storage_access { + crate::StorageAccess::LOAD => Some(spirv::Decoration::NonWritable), + crate::StorageAccess::STORE => Some(spirv::Decoration::NonReadable), + _ => None, + }; + if let Some(decoration) = access_decoration { + self.annotations + .push(Instruction::decorate(id, decoration, &[])); + } + + if let Some(ref res_binding) = global_variable.binding { + self.annotations.push(Instruction::decorate( + id, + spirv::Decoration::DescriptorSet, + &[res_binding.group], + )); + self.annotations.push(Instruction::decorate( + id, + spirv::Decoration::Binding, + &[res_binding.binding], + )); } // TODO Initializer is optional and not (yet) included in the IR @@ -1212,7 +1298,7 @@ impl Writer { ) -> Result<(), Error> { let result_lookup_ty = match self.typifier.get_handle(expr_handle) { Ok(ty_handle) => LookupType::Handle(ty_handle), - Err(inner) => LookupType::Local(LocalType::from_inner(inner).unwrap()), + Err(inner) => LookupType::Local(self.physical_layout.make_local(inner).unwrap()), }; let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; @@ -1598,9 +1684,10 @@ impl Writer { .push(Instruction::load(result_type_id, id, pointer_id, None)); id } - crate::Expression::FunctionArgument(index) => { - function.parameters[index as usize].result_id.unwrap() - } + crate::Expression::FunctionArgument(index) => match function.entry_point_context { + Some(ref context) => context.argument_ids[index as usize], + None => function.parameters[index as usize].result_id.unwrap(), + }, crate::Expression::Call(_function) => self.lookup_function_call[&expr_handle], crate::Expression::As { expr, @@ -1829,7 +1916,7 @@ impl Writer { ) -> Result<(Word, spirv::StorageClass), Error> { let result_lookup_ty = match self.typifier.get_handle(expr_handle) { Ok(ty_handle) => LookupType::Handle(ty_handle), - Err(inner) => LookupType::Local(LocalType::from_inner(inner).unwrap()), + Err(inner) => LookupType::Local(self.physical_layout.make_local(inner).unwrap()), }; let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; @@ -2120,8 +2207,40 @@ impl Writer { Some(Instruction::branch(loop_context.continuing_id.unwrap())); } crate::Statement::Return { value: Some(value) } => { - let id = self.cached[value]; - block.termination = Some(Instruction::return_value(id)); + let value_id = self.cached[value]; + let instruction = match function.entry_point_context { + // If this is an entry point, and we need to return anything, + // let's instead store the output variables and return `void`. + Some(ref context) => { + let result = ir_function.result.as_ref().unwrap(); + if result.binding.is_none() { + for (index, &(varying_id, type_id)) in + context.result_ids_typed.iter().enumerate() + { + let member_value_id = self.generate_id(); + block.body.push(Instruction::composite_extract( + type_id, + member_value_id, + value_id, + &[index as u32], + )); + block.body.push(Instruction::store( + varying_id, + member_value_id, + None, + )); + } + } else { + let (varying_id, _) = context.result_ids_typed[0]; + block + .body + .push(Instruction::store(varying_id, value_id, None)); + }; + Instruction::return_void() + } + None => Instruction::return_value(value_id), + }; + block.termination = Some(instruction); } crate::Statement::Return { value: None } => { block.termination = Some(Instruction::return_void()); @@ -2180,8 +2299,11 @@ impl Writer { Some(expr) => { self.cached[expr] = id; self.lookup_function_call.insert(expr, id); - let ty_handle = - ir_module.functions[local_function].return_type.unwrap(); + let ty_handle = ir_module.functions[local_function] + .result + .as_ref() + .unwrap() + .ty; self.get_type_id(&ir_module.types, LookupType::Handle(ty_handle))? } None => self.void_type, @@ -2253,7 +2375,7 @@ impl Writer { for (handle, ir_function) in ir_module.functions.iter() { let info = &analysis[handle]; - let id = self.write_function(ir_function, info, ir_module)?; + let id = self.write_function(ir_function, info, ir_module, None)?; self.lookup_function.insert(handle, id); } diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 15181d7b4..ab592495f 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -2,8 +2,8 @@ use super::{constants::ConstantSolver, error::ErrorKind}; use crate::{ proc::{ResolveContext, Typifier}, Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, FunctionArgument, - GlobalVariable, Handle, Interpolation, LocalVariable, Module, RelationalFunction, ShaderStage, - Statement, StorageClass, Type, UnaryOperator, + GlobalVariable, Handle, Interpolation, LocalVariable, Module, RelationalFunction, + ResourceBinding, ShaderStage, Statement, StorageClass, Type, UnaryOperator, }; #[derive(Debug)] @@ -224,6 +224,7 @@ impl ExpressionRule { #[derive(Debug)] pub enum TypeQualifier { StorageQualifier(StorageQualifier), + ResourceBinding(ResourceBinding), Binding(Binding), Interpolation(Interpolation), } @@ -250,11 +251,14 @@ pub struct FunctionCall { #[derive(Debug, Clone, Copy)] pub enum StorageQualifier { StorageClass(StorageClass), + Input, + Output, Const, } #[derive(Debug, Clone)] pub enum StructLayout { Binding(Binding), + Resource(ResourceBinding), PushConstant, } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 6a917734d..5efd1076e 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -8,10 +8,11 @@ pomelo! { BOOL_WIDTH, Arena, BinaryOperator, Binding, Block, Constant, ConstantInner, Expression, - Function, GlobalVariable, Handle, Interpolation, - LocalVariable, ScalarValue, ScalarKind, + Function, FunctionArgument, FunctionResult, + GlobalVariable, Handle, Interpolation, + LocalVariable, ResourceBinding, ScalarValue, ScalarKind, Statement, StorageAccess, StorageClass, StructMember, - SwitchCase, Type, TypeInner, UnaryOperator, FunctionArgument, + SwitchCase, Type, TypeInner, UnaryOperator, }; use pp_rs::token::PreprocessorError; } @@ -602,14 +603,15 @@ pomelo! { layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen { if let Some(&(_, loc)) = l.iter().find(|&q| q.0.as_str() == "location") { - StructLayout::Binding(Binding::Location(loc)) + let interpolation = None; //TODO + StructLayout::Binding(Binding::Location(loc, interpolation)) } else if let Some(&(_, binding)) = l.iter().find(|&q| q.0.as_str() == "binding") { let group = if let Some(&(_, set)) = l.iter().find(|&q| q.0.as_str() == "set") { set } else { 0 }; - StructLayout::Binding(Binding::Resource{ group, binding }) + StructLayout::Resource(ResourceBinding{ group, binding }) } else if l.iter().any(|q| q.0.as_str() == "push_constant") { StructLayout::PushConstant } else { @@ -648,6 +650,7 @@ pomelo! { single_type_qualifier ::= layout_qualifier(l) { match l { StructLayout::Binding(b) => TypeQualifier::Binding(b), + StructLayout::Resource(b) => TypeQualifier::ResourceBinding(b), StructLayout::PushConstant => TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(StorageClass::PushConstant)), } } @@ -663,10 +666,10 @@ pomelo! { } // storage_qualifier ::= InOut; storage_qualifier ::= In { - StorageQualifier::StorageClass(StorageClass::Input) + StorageQualifier::Input } storage_qualifier ::= Out { - StorageQualifier::StorageClass(StorageClass::Output) + StorageQualifier::Output } // storage_qualifier ::= Centroid; // storage_qualifier ::= Patch; @@ -724,6 +727,7 @@ pomelo! { name: Some(name.clone()), span: None, ty, + binding: None, //TODO }).collect() } else { return Err(ErrorKind::SemanticError("Struct member can't be void".into())) @@ -1005,7 +1009,7 @@ pomelo! { Function { name: Some(n.1), arguments: vec![], - return_type: t.1, + result: t.1.map(|ty| FunctionResult { ty, binding: None }), local_variables: Arena::::new(), expressions: Arena::::new(), body: vec![], @@ -1019,12 +1023,12 @@ pomelo! { (h, args) } parameter_declarator ::= parameter_type_specifier(ty) Identifier(n) { - FunctionArgument { name: Some(n.1), ty } + FunctionArgument { name: Some(n.1), ty, binding: None } } // parameter_declarator ::= type_specifier(ty) Identifier(ident) array_specifier; parameter_declaration ::= parameter_declarator; parameter_declaration ::= parameter_type_specifier(ty) { - FunctionArgument { name: None, ty } + FunctionArgument { name: None, ty, binding: None } } parameter_type_specifier ::= type_specifier(t) { @@ -1077,13 +1081,8 @@ pomelo! { StorageQualifier::StorageClass(storage_class) => { // TODO: Check that the storage qualifiers allow for the bindings let binding = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Binding(ref b) = *tq { Some(b.clone()) } else { None } + if let TypeQualifier::ResourceBinding(ref b) = *tq { Some(b.clone()) } else { None } }); - - let interpolation = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Interpolation(interp) = *tq { Some(interp) } else { None } - }); - for (id, initializer) in d.ids_initializers { let init = initializer.map(|init| extra.solve_constant(init.expression)).transpose()?; @@ -1104,7 +1103,6 @@ pomelo! { binding: binding.clone(), ty: d.ty, init, - interpolation, storage_access: StorageAccess::empty(), //TODO }, ); @@ -1113,6 +1111,37 @@ pomelo! { } } } + StorageQualifier::Input => { + let mut binding = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Binding(ref b) = *tq { Some(b.clone()) } else { None } + }); + let interpolation = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Interpolation(interp) = *tq { Some(interp) } else { None } + }); + if let Some(Binding::Location(_, ref mut interp)) = binding { + *interp = interpolation; + } + + for (id, _initializer) in d.ids_initializers { + if let Some(id) = id { + //TODO! + let expr = extra.context.expressions.append(Expression::FunctionArgument(0)); + extra.context.lookup_global_var_exps.insert(id, expr); + } + } + } + StorageQualifier::Output => { + let _binding = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Binding(ref b) = *tq { Some(b.clone()) } else { None } + }); + for (id, _initializer) in d.ids_initializers { + if let Some(id) = id { + //TODO! + let expr = extra.context.expressions.append(Expression::FunctionArgument(0)); + extra.context.lookup_global_var_exps.insert(id, expr); + } + } + } StorageQualifier::Const => { for (id, initializer) in d.ids_initializers { if let Some(init) = initializer { diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index ba925f433..d08c59347 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,7 +1,4 @@ -use crate::{ - Binding, BuiltIn, Expression, GlobalVariable, Handle, ScalarKind, StorageAccess, StorageClass, - Type, TypeInner, VectorSize, -}; +use crate::{Expression, Handle, Type, TypeInner, VectorSize}; use super::ast::*; use super::error::ErrorKind; @@ -20,7 +17,7 @@ impl Program<'_> { } match name { "gl_Position" => { - let h = self.module.global_variables.append(GlobalVariable { + /*let h = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), class: StorageClass::Output, binding: Some(Binding::BuiltIn(BuiltIn::Position)), @@ -40,12 +37,17 @@ impl Program<'_> { let exp = self .context .expressions - .append(Expression::GlobalVariable(h)); + .append(Expression::GlobalVariable(h));*/ + let exp = self + .context + .expressions + .append(Expression::FunctionArgument(0)); //TODO self.context.lookup_global_var_exps.insert(name.into(), exp); Ok(Some(exp)) } "gl_VertexIndex" => { + /* TODO let h = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), class: StorageClass::Input, @@ -71,6 +73,11 @@ impl Program<'_> { kind: ScalarKind::Sint, convert: true, }); + */ + let expr = self + .context + .expressions + .append(Expression::FunctionArgument(0)); //TODO self.context .lookup_global_var_exps .insert(name.into(), expr); @@ -78,6 +85,7 @@ impl Program<'_> { Ok(Some(expr)) } "gl_InstanceIndex" => { + /* TODO let h = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), class: StorageClass::Input, @@ -103,6 +111,11 @@ impl Program<'_> { kind: ScalarKind::Sint, convert: true, }); + */ + let expr = self + .context + .expressions + .append(Expression::FunctionArgument(0)); //TODO self.context .lookup_global_var_exps .insert(name.into(), expr); diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index de0df57e2..f1086d0c0 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -2,7 +2,7 @@ use super::error::Error; use num_traits::cast::FromPrimitive; use std::convert::TryInto; -pub fn map_binary_operator(word: spirv::Op) -> Result { +pub(super) fn map_binary_operator(word: spirv::Op) -> Result { use crate::BinaryOperator; use spirv::Op; @@ -34,7 +34,7 @@ pub fn map_binary_operator(word: spirv::Op) -> Result Result { +pub(super) fn map_relational_fun(word: spirv::Op) -> Result { use crate::RelationalFunction as Rf; use spirv::Op; @@ -49,7 +49,7 @@ pub fn map_relational_fun(word: spirv::Op) -> Result Result { +pub(super) fn map_vector_size(word: spirv::Word) -> Result { match word { 2 => Ok(crate::VectorSize::Bi), 3 => Ok(crate::VectorSize::Tri), @@ -58,7 +58,7 @@ pub fn map_vector_size(word: spirv::Word) -> Result { } } -pub fn map_image_dim(word: spirv::Word) -> Result { +pub(super) fn map_image_dim(word: spirv::Word) -> Result { use spirv::Dim as D; match D::from_u32(word) { Some(D::Dim1D) => Ok(crate::ImageDimension::D1), @@ -69,7 +69,7 @@ pub fn map_image_dim(word: spirv::Word) -> Result } } -pub fn map_image_format(word: spirv::Word) -> Result { +pub(super) fn map_image_format(word: spirv::Word) -> Result { match spirv::ImageFormat::from_u32(word) { Some(spirv::ImageFormat::R8) => Ok(crate::StorageFormat::R8Unorm), Some(spirv::ImageFormat::R8Snorm) => Ok(crate::StorageFormat::R8Snorm), @@ -107,13 +107,13 @@ pub fn map_image_format(word: spirv::Word) -> Result Result { +pub(super) fn map_width(word: spirv::Word) -> Result { (word >> 3) // bits to bytes .try_into() .map_err(|_| Error::InvalidTypeWidth(word)) } -pub fn map_builtin(word: spirv::Word, is_output: bool) -> Result { +pub(super) fn map_builtin(word: spirv::Word, is_output: bool) -> Result { use spirv::BuiltIn as Bi; Ok(match spirv::BuiltIn::from_u32(word) { Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, @@ -145,19 +145,20 @@ pub fn map_builtin(word: spirv::Word, is_output: bool) -> Result Result { +pub(super) fn map_storage_class(word: spirv::Word) -> Result { + use super::ExtendedClass as Ec; use spirv::StorageClass as Sc; Ok(match Sc::from_u32(word) { - Some(Sc::Function) => crate::StorageClass::Function, - Some(Sc::Input) => crate::StorageClass::Input, - Some(Sc::Output) => crate::StorageClass::Output, - Some(Sc::Private) => crate::StorageClass::Private, - Some(Sc::UniformConstant) => crate::StorageClass::Handle, - Some(Sc::StorageBuffer) => crate::StorageClass::Storage, + Some(Sc::Function) => Ec::Global(crate::StorageClass::Function), + Some(Sc::Input) => Ec::Input, + Some(Sc::Output) => Ec::Output, + Some(Sc::Private) => Ec::Global(crate::StorageClass::Private), + Some(Sc::UniformConstant) => Ec::Global(crate::StorageClass::Handle), + Some(Sc::StorageBuffer) => Ec::Global(crate::StorageClass::Storage), // we expect the `Storage` case to be filtered out before calling this function. - Some(Sc::Uniform) => crate::StorageClass::Uniform, - Some(Sc::Workgroup) => crate::StorageClass::WorkGroup, - Some(Sc::PushConstant) => crate::StorageClass::PushConstant, + Some(Sc::Uniform) => Ec::Global(crate::StorageClass::Uniform), + Some(Sc::Workgroup) => Ec::Global(crate::StorageClass::WorkGroup), + Some(Sc::PushConstant) => Ec::Global(crate::StorageClass::PushConstant), _ => return Err(Error::UnsupportedStorageClass(word)), }) } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index cc66d2b1d..3003417cb 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -63,10 +63,14 @@ impl> super::Parser { crate::Function { name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name), arguments: Vec::with_capacity(ft.parameter_type_ids.len()), - return_type: if self.lookup_void_type == Some(result_type_id) { + result: if self.lookup_void_type == Some(result_type_id) { None } else { - Some(self.lookup_type.lookup(result_type_id)?.handle) + let lookup_result_ty = self.lookup_type.lookup(result_type_id)?; + Some(crate::FunctionResult { + ty: lookup_result_ty.handle, + binding: None, + }) }, local_variables: Arena::new(), expressions: self.make_expression_storage(), @@ -99,8 +103,12 @@ impl> super::Parser { return Err(Error::WrongFunctionArgumentType(type_id)); } let ty = self.lookup_type.lookup(type_id)?.handle; - fun.arguments - .push(crate::FunctionArgument { name: None, ty }); + let decor = self.future_decor.remove(&id).unwrap_or_default(); + fun.arguments.push(crate::FunctionArgument { + name: decor.name, + ty, + binding: None, + }); } Instruction { op, .. } => return Err(Error::InvalidParameter(op)), } @@ -157,19 +165,128 @@ impl> super::Parser { fun.body = flow_graph.to_naga()?; + // done + let fun_handle = module.functions.append(fun); match self.lookup_entry_point.remove(&fun_id) { Some(ep) => { + // create a wrapping function + let mut function = crate::Function { + name: None, + arguments: Vec::new(), + result: None, + local_variables: Arena::new(), + expressions: Arena::new(), + body: Vec::new(), + }; + + // 1. copy the inputs from arguments to privates + for &v_id in ep.variable_ids.iter() { + let lvar = self.lookup_variable.lookup(v_id)?; + if let super::Variable::Input(ref arg) = lvar.inner { + function.body.push(crate::Statement::Store { + pointer: function + .expressions + .append(crate::Expression::GlobalVariable(lvar.handle)), + value: + function + .expressions + .append(crate::Expression::FunctionArgument( + function.arguments.len() as u32, + )), + }); + let mut arg = arg.clone(); + if ep.stage == crate::ShaderStage::Fragment { + if let Some(crate::Binding::Location(_, ref mut interpolation @ None)) = + arg.binding + { + *interpolation = Some(crate::Interpolation::Perspective); + // default + } + } + function.arguments.push(arg); + } + } + // 2. call the wrapped function + function.body.push(crate::Statement::Call { + function: fun_handle, + arguments: Vec::new(), + result: None, + }); + + // 3. copy the outputs from privates to the result + let mut members = Vec::new(); + let mut components = Vec::new(); + for &v_id in ep.variable_ids.iter() { + let lvar = self.lookup_variable.lookup(v_id)?; + if let super::Variable::Output(ref result) = lvar.inner { + members.push(crate::StructMember { + name: None, + span: None, + ty: result.ty, + binding: result.binding.clone(), + }); + // populate just the globals first, then do `Load` in a + // separate step, so that we can get a range. + components.push( + function + .expressions + .append(crate::Expression::GlobalVariable(lvar.handle)), + ); + } + } + + let old_len = function.expressions.len(); + for component in components.iter_mut() { + *component = function.expressions.append(crate::Expression::Load { + pointer: *component, + }); + } + match members.len() { + 0 => {} + 1 => { + let member = members.remove(0); + function.body.push(crate::Statement::Emit( + function.expressions.range_from(old_len), + )); + function.body.push(crate::Statement::Return { + value: components.first().cloned(), + }); + function.result = Some(crate::FunctionResult { + ty: member.ty, + binding: member.binding, + }); + } + _ => { + let ty = module.types.append(crate::Type { + name: None, + inner: crate::TypeInner::Struct { + block: false, + members, + }, + }); + let result_expr = function + .expressions + .append(crate::Expression::Compose { ty, components }); + function.body.push(crate::Statement::Emit( + function.expressions.range_from(old_len), + )); + function.body.push(crate::Statement::Return { + value: Some(result_expr), + }); + function.result = Some(crate::FunctionResult { ty, binding: None }); + } + } + module.entry_points.push(crate::EntryPoint { name: ep.name, stage: ep.stage, early_depth_test: ep.early_depth_test, workgroup_size: ep.workgroup_size, - function: fun, + function, }); } None => { - let handle = module.functions.append(fun); - self.lookup_function.insert(fun_id, handle); + self.lookup_function.insert(fun_id, fun_handle); } }; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e20f9cdb1..572a0f9e7 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -8,6 +8,14 @@ There map `spv::Word` into a specific IR handle, plus potentially a bit of extra info, such as the related SPIR-V type ID. TODO: would be nice to find ways that avoid looking up as much +## Inputs/Outputs + +We create a private variable for each input/output. The relevant inputs are +populated at the start of an entry point. The outputs are saved at the end. + +The function associated with an entry point is wrapped in another function, +such that we can handle any `Return` statements without problems. + !*/ #![allow(dead_code)] @@ -203,37 +211,31 @@ impl Decoration { } } - fn get_binding(&self, is_output: bool) -> Option { - //TODO: validate this better + fn resource_binding(&self) -> Option { + match *self { + Decoration { + desc_set: Some(group), + desc_index: Some(binding), + .. + } => Some(crate::ResourceBinding { group, binding }), + _ => None, + } + } + + fn io_binding(&self, is_output: bool) -> Result { match *self { Decoration { built_in: Some(built_in), location: None, - desc_set: None, - desc_index: None, .. - } => match map_builtin(built_in, is_output) { - Ok(built_in) => Some(crate::Binding::BuiltIn(built_in)), - Err(e) => { - log::warn!("{:?}", e); - None - } - }, + } => map_builtin(built_in, is_output).map(crate::Binding::BuiltIn), Decoration { built_in: None, location: Some(loc), - desc_set: None, - desc_index: None, + interpolation, .. - } => Some(crate::Binding::Location(loc)), - Decoration { - built_in: None, - location: None, - desc_set: Some(group), - desc_index: Some(binding), - .. - } => Some(crate::Binding::Resource { group, binding }), - _ => None, + } => Ok(crate::Binding::Location(loc, interpolation)), + _ => Err(Error::MissingDecoration(spirv::Decoration::Location)), } } } @@ -266,8 +268,16 @@ struct LookupConstant { type_id: spirv::Word, } +#[derive(Debug)] +enum Variable { + Global, + Input(crate::FunctionArgument), + Output(crate::FunctionResult), +} + #[derive(Debug)] struct LookupVariable { + inner: Variable, handle: Handle, type_id: spirv::Word, } @@ -279,11 +289,17 @@ struct LookupExpression { } #[derive(Clone, Debug)] -pub struct Assignment { +struct Assignment { to: Handle, value: Handle, } +enum ExtendedClass { + Global(crate::StorageClass), + Input, + Output, +} + #[derive(Clone, Debug, Default)] pub struct Options { pub flow_graph_dump_prefix: Option, @@ -429,7 +445,7 @@ impl> Parser { dec.interpolation = Some(crate::Interpolation::Flat); } spirv::Decoration::Patch => { - dec.interpolation = Some(crate::Interpolation::Patch); + // skip } spirv::Decoration::Centroid => { dec.interpolation = Some(crate::Interpolation::Centroid); @@ -1706,6 +1722,9 @@ impl> Parser { self.index_constants.push(handle); } + self.dummy_functions = Arena::new(); + self.lookup_function.clear(); + loop { use spirv::Op; @@ -1764,10 +1783,8 @@ impl> Parser { for (_, fun) in module.functions.iter_mut() { self.patch_function_calls(fun)?; } - for ep in module.entry_points.iter_mut() { - self.patch_function_calls(&mut ep.function)?; - } - self.lookup_function.clear(); + // Note: we aren't patching the entry point functions, because they are simply + // wrappers behind real functions, and are already resolved. // Check all the images and samplers to have consistent comparison property. for (handle, flags) in self.handle_sampling.drain() { @@ -2215,7 +2232,10 @@ impl> Parser { { crate::StorageClass::Storage } - _ => map_storage_class(storage_class)?, + _ => match map_storage_class(storage_class)? { + ExtendedClass::Global(class) => class, + ExtendedClass::Input | ExtendedClass::Output => crate::StorageClass::Private, + }, }; // Don't bother with pointer stuff for `Handle` types. @@ -2325,6 +2345,7 @@ impl> Parser { name: decor.name, span: None, //TODO ty, + binding: None, }); } @@ -2695,78 +2716,119 @@ impl> Parser { } => true, _ => false, }; - let class = if self.lookup_storage_buffer_types.contains(&effective_ty) { - crate::StorageClass::Storage + let ext_class = if self.lookup_storage_buffer_types.contains(&effective_ty) { + ExtendedClass::Global(crate::StorageClass::Storage) } else { map_storage_class(storage_class)? }; - let storage_access = if is_storage { - let mut access = crate::StorageAccess::all(); - if dec.flags.contains(DecorationFlags::NON_READABLE) { - access ^= crate::StorageAccess::LOAD; + let (inner, var) = match ext_class { + ExtendedClass::Global(class) => { + let storage_access = if is_storage { + let mut access = crate::StorageAccess::all(); + if dec.flags.contains(DecorationFlags::NON_READABLE) { + access ^= crate::StorageAccess::LOAD; + } + if dec.flags.contains(DecorationFlags::NON_WRITABLE) { + access ^= crate::StorageAccess::STORE; + } + access + } else { + crate::StorageAccess::empty() + }; + + let var = crate::GlobalVariable { + binding: dec.resource_binding(), + name: dec.name, + class, + ty: effective_ty, + init, + storage_access, + }; + (Variable::Global, var) } - if dec.flags.contains(DecorationFlags::NON_WRITABLE) { - access ^= crate::StorageAccess::STORE; + ExtendedClass::Input => { + let binding = dec.io_binding(false)?; + if let crate::Binding::BuiltIn(built_in) = binding { + let needs_inner_uint = match built_in { + crate::BuiltIn::BaseInstance + | crate::BuiltIn::BaseVertex + | crate::BuiltIn::InstanceIndex + | crate::BuiltIn::SampleIndex + | crate::BuiltIn::VertexIndex + | crate::BuiltIn::LocalInvocationIndex => Some(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: 4, + }), + crate::BuiltIn::GlobalInvocationId + | crate::BuiltIn::LocalInvocationId + | crate::BuiltIn::WorkGroupId + | crate::BuiltIn::WorkGroupSize => Some(crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Uint, + width: 4, + }), + _ => None, + }; + if let (Some(inner), Some(crate::ScalarKind::Sint)) = ( + needs_inner_uint, + module.types[effective_ty].inner.scalar_kind(), + ) { + log::warn!("Treating {:?} as unsigned", built_in); + effective_ty = module + .types + .fetch_or_append(crate::Type { name: None, inner }); + } + } + + let var = crate::GlobalVariable { + name: dec.name.clone(), + class: crate::StorageClass::Private, + binding: None, + ty: effective_ty, + init: None, + storage_access: crate::StorageAccess::empty(), + }; + let inner = Variable::Input(crate::FunctionArgument { + name: dec.name, + ty: effective_ty, + binding: Some(binding), + }); + (inner, var) + } + ExtendedClass::Output => { + let binding = dec.io_binding(true)?; + let var = crate::GlobalVariable { + name: dec.name, + class: crate::StorageClass::Private, + binding: None, + ty: effective_ty, + init: None, + storage_access: crate::StorageAccess::empty(), + }; + let inner = Variable::Output(crate::FunctionResult { + ty: effective_ty, + binding: Some(binding), + }); + (inner, var) } - access - } else { - crate::StorageAccess::empty() }; - let binding = dec.get_binding(class == crate::StorageClass::Output); - if let Some(crate::Binding::BuiltIn(built_in)) = binding { - // SPIR-V only cares about some of the built-in types being integer. - // Naga requires them to be strictly unsigned, so we have to patch it. - let needs_inner_uint = match built_in { - crate::BuiltIn::BaseInstance - | crate::BuiltIn::BaseVertex - | crate::BuiltIn::InstanceIndex - | crate::BuiltIn::SampleIndex - | crate::BuiltIn::VertexIndex - | crate::BuiltIn::LocalInvocationIndex => Some(crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: 4, - }), - crate::BuiltIn::GlobalInvocationId - | crate::BuiltIn::LocalInvocationId - | crate::BuiltIn::WorkGroupId - | crate::BuiltIn::WorkGroupSize => Some(crate::TypeInner::Vector { - size: crate::VectorSize::Tri, - kind: crate::ScalarKind::Uint, - width: 4, - }), - _ => None, - }; - if let (Some(inner), Some(crate::ScalarKind::Sint)) = ( - needs_inner_uint, - module.types[effective_ty].inner.scalar_kind(), - ) { - log::warn!("Treating {:?} as unsigned", built_in); - effective_ty = module - .types - .fetch_or_append(crate::Type { name: None, inner }); - } - } - - let var = crate::GlobalVariable { - name: dec.name, - class, - binding, - ty: effective_ty, - init, - interpolation: dec.interpolation, - storage_access, - }; let handle = module.global_variables.append(var); - self.lookup_variable - .insert(id, LookupVariable { handle, type_id }); - if module.types[effective_ty].inner.can_comparison_sample() { log::debug!("\t\ttracking {:?} for sampling properties", handle); self.handle_sampling .insert(handle, image::SamplingFlags::empty()); } + + self.lookup_variable.insert( + id, + LookupVariable { + inner, + handle, + type_id, + }, + ); Ok(()) } } diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 0aa14dbaa..7a70da638 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -2,8 +2,6 @@ use super::Error; pub fn map_storage_class(word: &str) -> Result> { match word { - "in" => Ok(crate::StorageClass::Input), - "out" => Ok(crate::StorageClass::Output), "private" => Ok(crate::StorageClass::Private), "uniform" => Ok(crate::StorageClass::Uniform), "storage" => Ok(crate::StorageClass::Storage), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index fdc3967bc..d2d64afd4 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -109,6 +109,12 @@ pub enum Error<'a> { ZeroStride, #[error("not a composite type: {0:?}")] NotCompositeType(Handle), + #[error("Input/output binding is not consistent: location {0:?}, built-in {1:?} and interpolation {2:?}")] + InconsistentBinding( + Option, + Option, + Option, + ), #[error("call to local `{0}(..)` can't be resolved")] UnknownLocalFunction(&'a str), #[error("builtin {0:?} is not implemented")] @@ -416,6 +422,54 @@ pub enum Scope { type LocalFunctionCall = (Handle, Vec>); +#[derive(Default)] +struct BindingParser { + location: Option, + built_in: Option, + interpolation: Option, +} + +impl BindingParser { + fn parse<'a>(&mut self, lexer: &mut Lexer<'a>, name: &'a str) -> Result<(), Error<'a>> { + match name { + "location" => { + lexer.expect(Token::Paren('('))?; + self.location = Some(lexer.next_uint_literal()?); + lexer.expect(Token::Paren(')'))?; + } + "builtin" => { + lexer.expect(Token::Paren('('))?; + let raw = lexer.next_ident()?; + self.built_in = Some(conv::map_built_in(raw)?); + lexer.expect(Token::Paren(')'))?; + } + "interpolate" => { + lexer.expect(Token::Paren('('))?; + let raw = lexer.next_ident()?; + self.interpolation = Some(conv::map_interpolation(raw)?); + lexer.expect(Token::Paren(')'))?; + } + _ => return Err(Error::UnknownDecoration(name)), + } + Ok(()) + } + + fn finish<'a>(self) -> Result, Error<'a>> { + match (self.location, self.built_in, self.interpolation) { + (None, None, None) => Ok(None), + (Some(loc), None, interpolation) => { + Ok(Some(crate::Binding::Location(loc, interpolation))) + } + (None, Some(bi), None) => Ok(Some(crate::Binding::BuiltIn(bi))), + (location, built_in, interpolation) => Err(Error::InconsistentBinding( + location, + built_in, + interpolation, + )), + } + } +} + struct ParsedVariable<'a> { name: &'a str, class: Option, @@ -1447,6 +1501,7 @@ impl Parser { lexer.expect(Token::Paren('{'))?; loop { let mut span = 0; + let mut bind_parser = BindingParser::default(); if lexer.skip(Token::DoubleParen('[')) { self.scopes.push(Scope::Decoration); let mut ready = true; @@ -1458,17 +1513,22 @@ impl Parser { (Token::Separator(','), _) if !ready => { ready = true; } - (Token::Word("span"), _) if ready => { - lexer.expect(Token::Paren('('))?; - //Note: 0 is not handled - span = lexer.next_uint_literal()?; - lexer.expect(Token::Paren(')'))?; - ready = false; - } - (Token::Word("offset"), _) if ready => { - lexer.expect(Token::Paren('('))?; - let _offset = lexer.next_uint_literal()?; - lexer.expect(Token::Paren(')'))?; + (Token::Word(word), _) if ready => { + match word { + "span" => { + lexer.expect(Token::Paren('('))?; + //Note: 0 is not handled + span = lexer.next_uint_literal()?; + lexer.expect(Token::Paren(')'))?; + } + "offset" => { + // skip - only here for parsing compatibility + lexer.expect(Token::Paren('('))?; + let _offset = lexer.next_uint_literal()?; + lexer.expect(Token::Paren(')'))?; + } + _ => bind_parser.parse(lexer, word)?, + } ready = false; } other => return Err(Error::Unexpected(other, "decoration separator")), @@ -1476,6 +1536,7 @@ impl Parser { } self.scopes.pop(); } + let name = match lexer.next() { (Token::Word(word), _) => word, (Token::Paren('}'), _) => return Ok(members), @@ -1484,10 +1545,12 @@ impl Parser { lexer.expect(Token::Separator(':'))?; let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Separator(';'))?; + members.push(crate::StructMember { name: Some(name.to_owned()), span: NonZeroU32::new(span), ty, + binding: bind_parser.finish()?, }); } } @@ -2259,6 +2322,31 @@ impl Parser { Ok(block) } + fn parse_varying_binding<'a>( + &mut self, + lexer: &mut Lexer<'a>, + ) -> Result, Error<'a>> { + if !lexer.skip(Token::DoubleParen('[')) { + return Ok(None); + } + + let mut bind_parser = BindingParser::default(); + self.scopes.push(Scope::Decoration); + loop { + let word = lexer.next_ident()?; + bind_parser.parse(lexer, word)?; + match lexer.next() { + (Token::DoubleParen(']'), _) => { + break; + } + (Token::Separator(','), _) => {} + other => return Err(Error::Unexpected(other, "decoration separator")), + } + } + self.scopes.pop(); + bind_parser.finish() + } + fn parse_function_decl<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -2278,10 +2366,12 @@ impl Parser { // read parameter list let mut arguments = Vec::new(); lexer.expect(Token::Paren('('))?; + let mut ready = true; while !lexer.skip(Token::Paren(')')) { - if !arguments.is_empty() { - lexer.expect(Token::Separator(','))?; + if !ready { + return Err(Error::Unexpected(lexer.next(), "comma")); } + let binding = self.parse_varying_binding(lexer)?; let (param_name, param_type, _access) = self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; let param_index = arguments.len() as u32; @@ -2291,13 +2381,16 @@ impl Parser { arguments.push(crate::FunctionArgument { name: Some(param_name.to_string()), ty: param_type, + binding, }); + ready = lexer.skip(Token::Separator(',')); } // read return type - let return_type = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { - let (handle, _access) = + let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { + let binding = self.parse_varying_binding(lexer)?; + let (ty, _access) = self.parse_type_decl(lexer, None, &mut module.types, &mut module.constants)?; - Some(handle) + Some(crate::FunctionResult { ty, binding }) } else { None }; @@ -2305,7 +2398,7 @@ impl Parser { let mut fun = crate::Function { name: Some(fun_name.to_string()), arguments, - return_type, + result, local_variables: Arena::new(), expressions, body: Vec::new(), @@ -2345,7 +2438,6 @@ impl Parser { // read decorations let mut binding = None; // Perspective is the default qualifier. - let mut interpolation = None; let mut stage = None; let mut is_block = false; let mut workgroup_size = [0u32; 3]; @@ -2356,18 +2448,6 @@ impl Parser { self.scopes.push(Scope::Decoration); loop { match lexer.next_ident()? { - "location" => { - lexer.expect(Token::Paren('('))?; - let loc = lexer.next_uint_literal()?; - lexer.expect(Token::Paren(')'))?; - binding = Some(crate::Binding::Location(loc)); - } - "builtin" => { - lexer.expect(Token::Paren('('))?; - let builtin = conv::map_built_in(lexer.next_ident()?)?; - lexer.expect(Token::Paren(')'))?; - binding = Some(crate::Binding::BuiltIn(builtin)); - } "binding" => { lexer.expect(Token::Paren('('))?; bind_index = Some(lexer.next_uint_literal()?); @@ -2381,11 +2461,6 @@ impl Parser { bind_group = Some(lexer.next_uint_literal()?); lexer.expect(Token::Paren(')'))?; } - "interpolate" => { - lexer.expect(Token::Paren('('))?; - interpolation = Some(conv::map_interpolation(lexer.next_ident()?)?); - lexer.expect(Token::Paren(')'))?; - } "stage" => { lexer.expect(Token::Paren('('))?; stage = Some(conv::map_shader_stage(lexer.next_ident()?)?); @@ -2433,7 +2508,7 @@ impl Parser { } } if let (Some(group), Some(index)) = (bind_group, bind_index) { - binding = Some(crate::Binding::Resource { + binding = Some(crate::ResourceBinding { group, binding: index, }); @@ -2494,33 +2569,21 @@ impl Parser { self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; let class = match pvar.class { Some(c) => c, - None => match binding { - Some(crate::Binding::BuiltIn(builtin)) => match builtin { - crate::BuiltIn::GlobalInvocationId => crate::StorageClass::Input, - crate::BuiltIn::Position => crate::StorageClass::Output, - _ => return Err(Error::UnimplementedBuiltin(builtin)), - }, - Some(crate::Binding::Resource { .. }) => { - match module.types[pvar.ty].inner { - crate::TypeInner::Struct { .. } if pvar.access.is_empty() => { - crate::StorageClass::Uniform - } - crate::TypeInner::Struct { .. } - | crate::TypeInner::Array { .. } => crate::StorageClass::Storage, - crate::TypeInner::Image { .. } - | crate::TypeInner::Sampler { .. } => crate::StorageClass::Handle, - ref other => { - log::error!("Resource type {:?}", other); - return Err(Error::InvalidResourceType(pvar.ty)); - } + None => match module.types[pvar.ty].inner { + crate::TypeInner::Struct { .. } if binding.is_some() => { + if pvar.access.is_empty() { + crate::StorageClass::Uniform + } else { + crate::StorageClass::Storage } } - _ => match module.types[pvar.ty].inner { - crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { - crate::StorageClass::Handle - } - _ => crate::StorageClass::Private, - }, + crate::TypeInner::Array { .. } if binding.is_some() => { + crate::StorageClass::Storage + } + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { + crate::StorageClass::Handle + } + _ => crate::StorageClass::Private, }, }; let var_handle = module.global_variables.append(crate::GlobalVariable { @@ -2529,7 +2592,6 @@ impl Parser { binding: binding.take(), ty: pvar.ty, init: pvar.init, - interpolation, storage_access: pvar.access, }); lookup_global_expression diff --git a/src/lib.rs b/src/lib.rs index e4c130f6a..bdd759443 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -123,10 +123,6 @@ pub enum ShaderStage { pub enum StorageClass { /// Function locals. Function, - /// Pipeline input, per invocation. - Input, - /// Pipeline output, per invocation, mutable. - Output, /// Private data, per invocation, mutable. Private, /// Workgroup shared data, mutable. @@ -228,8 +224,6 @@ pub enum Interpolation { Linear, /// Indicates that no interpolation will be performed. Flat, - /// Indicates a tessellation patch. - Patch, /// When used with multi-sampling rasterization, allow /// a single interpolation location for an entire pixel. Centroid, @@ -247,6 +241,8 @@ pub struct StructMember { pub name: Option, pub span: Option, pub ty: Handle, + /// For I/O structs, defines the binding. + pub binding: Option, } /// The number of dimensions an image has. @@ -452,9 +448,18 @@ pub enum Binding { /// Built-in shader variable. BuiltIn(BuiltIn), /// Indexed location. - Location(u32), - /// Binding within a resource group. - Resource { group: u32, binding: u32 }, + Location(u32, Option), +} + +/// Pipeline binding information for global resources. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub struct ResourceBinding { + /// The bind group index. + pub group: u32, + /// Binding number within the group. + pub binding: u32, } /// Variable defined at module level. @@ -466,19 +471,12 @@ pub struct GlobalVariable { pub name: Option, /// How this variable is to be stored. pub class: StorageClass, - /// How this variable is to be bound. - pub binding: Option, + /// For resources, defines the binding point. + pub binding: Option, /// The type of this variable. pub ty: Handle, /// Initial value for this variable. pub init: Option>, - //TODO: require fragment input interpolation once the entry point I/O - // is refactored. - /// The interpolation qualifier, if any. - /// If the this `GlobalVariable` is a vertex output - /// or fragment input, `None` corresponds to the - /// `smooth`/`perspective` interpolation qualifier. - pub interpolation: Option, /// Access bit for storage types of images and buffers. pub storage_access: StorageAccess, } @@ -841,7 +839,7 @@ pub enum Statement { } /// A function argument. -#[derive(Debug)] +#[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct FunctionArgument { @@ -849,6 +847,20 @@ pub struct FunctionArgument { pub name: Option, /// Type of the argument. pub ty: Handle, + /// For entry points, an argument has to have a binding + /// unless it's a structure. + pub binding: Option, +} + +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub struct FunctionResult { + /// Type of the result. + pub ty: Handle, + /// For entry points, the result has to have a binding + /// unless it's a structure. + pub binding: Option, } /// A function defined in the module. @@ -860,8 +872,8 @@ pub struct Function { pub name: Option, /// Information about function argument. pub arguments: Vec, - /// The return type of this function, if any. - pub return_type: Option>, + /// The result of this function, if any. + pub result: Option, /// Local variables defined and used in the function. pub local_variables: Arena, /// Expressions used inside this function. diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 56b3d5f95..81d872eff 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -288,6 +288,7 @@ impl FunctionInfo { &mut self, handle: Handle, expression_arena: &Arena, + arguments: &[crate::FunctionArgument], global_var_arena: &Arena, other_functions: &[FunctionInfo], ) -> Result<(), AnalysisError> { @@ -316,33 +317,39 @@ impl FunctionInfo { requirement: None, } } - // same as `LocalVariable` - generally non-uniform - E::FunctionArgument(_) => Uniformity::non_uniform_result(handle), - // depends on the builtin and storage class - E::GlobalVariable(gh) => { - assignable_global = Some(gh); - let var = &global_var_arena[gh]; - let uniform = if let Some(crate::Binding::BuiltIn(built_in)) = var.binding { - match built_in { + // depends on the builtin or interpolation + E::FunctionArgument(index) => { + let arg = &arguments[index as usize]; + let uniform = match arg.binding { + Some(crate::Binding::BuiltIn(built_in)) => match built_in { // per-polygon built-ins are uniform crate::BuiltIn::FrontFacing // per-work-group built-ins are uniform | crate::BuiltIn::WorkGroupId | crate::BuiltIn::WorkGroupSize => true, _ => false, - } - } else { - use crate::StorageClass as Sc; - match var.class { - // only flat inputs are uniform - Sc::Input => var.interpolation == Some(crate::Interpolation::Flat), - Sc::Output | Sc::Function | Sc::Private | Sc::WorkGroup => false, - // uniform data - Sc::Uniform | Sc::PushConstant => true, - // storage data is only uniform when read-only - Sc::Handle | Sc::Storage => { - !var.storage_access.contains(crate::StorageAccess::STORE) - } + }, + // only flat inputs are uniform + Some(crate::Binding::Location(_, Some(crate::Interpolation::Flat))) => true, + _ => false, + }; + Uniformity { + non_uniform_result: if uniform { None } else { Some(handle) }, + requirement: None, + } + } + // depends on the storage class + E::GlobalVariable(gh) => { + use crate::StorageClass as Sc; + assignable_global = Some(gh); + let var = &global_var_arena[gh]; + let uniform = match var.class { + Sc::Function | Sc::Private | Sc::WorkGroup => false, + // uniform data + Sc::Uniform | Sc::PushConstant => true, + // storage data is only uniform when read-only + Sc::Handle | Sc::Storage => { + !var.storage_access.contains(crate::StorageAccess::STORE) } }; Uniformity { @@ -660,7 +667,13 @@ impl Analysis { }; for (handle, _) in fun.expressions.iter() { - info.process_expression(handle, &fun.expressions, global_var_arena, &self.functions)?; + info.process_expression( + handle, + &fun.expressions, + &fun.arguments, + global_var_arena, + &self.functions, + )?; } let uniformity = info.process_block(&fun.body, &self.functions, None)?; @@ -727,18 +740,16 @@ fn uniform_control_flow() { name: None, init: None, ty, - binding: Some(crate::Binding::BuiltIn(crate::BuiltIn::VertexIndex)), - class: crate::StorageClass::Input, - interpolation: None, - storage_access: crate::StorageAccess::empty(), + class: crate::StorageClass::Handle, + binding: None, + storage_access: crate::StorageAccess::STORE, }); let uniform_global = global_var_arena.append(crate::GlobalVariable { name: None, init: None, ty, - binding: Some(crate::Binding::Location(0)), - class: crate::StorageClass::Input, - interpolation: Some(crate::Interpolation::Flat), + binding: None, + class: crate::StorageClass::Uniform, storage_access: crate::StorageAccess::empty(), }); @@ -772,7 +783,7 @@ fn uniform_control_flow() { expressions: vec![ExpressionInfo::default(); expressions.len()].into_boxed_slice(), }; for (handle, _) in expressions.iter() { - info.process_expression(handle, &expressions, &global_var_arena, &[]) + info.process_expression(handle, &expressions, &[], &global_var_arena, &[]) .unwrap(); } assert_eq!(info[non_uniform_global_expr].ref_count, 1); diff --git a/src/proc/namer.rs b/src/proc/namer.rs index b4ed695af..87ef357ac 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -14,6 +14,7 @@ pub enum NameKey { FunctionLocal(Handle, Handle), EntryPoint(EntryPointIndex), EntryPointLocal(EntryPointIndex, Handle), + EntryPointArgument(EntryPointIndex, u32), } /// This processor assigns names to all the things in a module @@ -160,6 +161,13 @@ impl Namer { for (ep_index, ep) in module.entry_points.iter().enumerate() { let ep_name = self.call(&ep.name); output.insert(NameKey::EntryPoint(ep_index as _), ep_name); + for (index, arg) in ep.function.arguments.iter().enumerate() { + let name = self.call_or(&arg.name, "param"); + output.insert( + NameKey::EntryPointArgument(ep_index as _, index as u32), + name, + ); + } for (handle, var) in ep.function.local_variables.iter() { let name = self.call_or(&var.name, "local"); output.insert(NameKey::EntryPointLocal(ep_index as _, handle), name); diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 498fec736..32c70113d 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -646,10 +646,11 @@ impl Typifier { } }, crate::Expression::Call(function) => { - let ty = ctx.functions[function] - .return_type + let result = ctx.functions[function] + .result + .as_ref() .ok_or(ResolveError::FunctionReturnsVoid)?; - Resolution::Handle(ty) + Resolution::Handle(result.ty) } crate::Expression::ArrayLength(_) => Resolution::Value(Ti::Scalar { kind: crate::ScalarKind::Uint, diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 9d49d7e31..8f4b7ffe1 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -70,8 +70,7 @@ pub struct Validator { // already have to use the typifier, so the work here is redundant in a way. typifier: Typifier, type_flags: Vec, - location_in_mask: BitSet, - location_out_mask: BitSet, + location_mask: BitSet, bind_group_masks: Vec, select_cases: FastHashSet, valid_expression_list: Vec>, @@ -112,8 +111,6 @@ pub enum GlobalVariableError { InvalidUsage, #[error("Type isn't compatible with the storage class")] InvalidType, - #[error("Interpolation is not valid")] - InvalidInterpolation, #[error("Storage access {seen:?} exceeds the allowed {allowed:?}")] InvalidStorageAccess { allowed: crate::StorageAccess, @@ -126,8 +123,6 @@ pub enum GlobalVariableError { }, #[error("Binding decoration is missing or not applicable")] InvalidBinding, - #[error("BuiltIn type for {0:?} is invalid")] - InvalidBuiltInType(crate::BuiltIn), } #[derive(Clone, Debug, Error)] @@ -136,6 +131,22 @@ pub enum LocalVariableError { InitializerType, } +#[derive(Clone, Debug, Error)] +pub enum VaryingError { + #[error("The type does not match the varying")] + InvalidType(Handle), + #[error("Interpolation is not valid")] + InvalidInterpolation, + #[error("BuiltIn {0:?} is not available at this stage")] + InvalidBuiltInStage(crate::BuiltIn), + #[error("BuiltIn type for {0:?} is invalid")] + InvalidBuiltInType(crate::BuiltIn), + #[error("Struct member {0} is missing a binding")] + MemberMissingBinding(u32), + #[error("Multiple bindings at location {location} are present")] + BindingCollision { location: u32 }, +} + #[derive(Clone, Debug, Error)] pub enum ExpressionError { #[error("Is invalid")] @@ -241,16 +252,14 @@ pub enum EntryPointError { UnexpectedWorkgroupSize, #[error("Workgroup size is out of range")] OutOfRangeWorkgroupSize, - #[error("Can't have arguments")] - UnexpectedArguments, - #[error("Can't have a return value")] - UnexpectedReturnValue, #[error("Global variable {0:?} is used incorrectly as {1:?}")] InvalidGlobalUsage(Handle, GlobalUse), - #[error("Bindings for {0:?} conflict with other global variables")] + #[error("Bindings for {0:?} conflict with other resource")] BindingCollision(Handle), - #[error("Built-in {0:?} is not applicable to this entry point")] - InvalidBuiltIn(crate::BuiltIn), + #[error("Argument {0} varying error")] + Argument(u32, #[source] VaryingError), + #[error("Result varying error")] + Result(#[source] VaryingError), #[error("Location {location} onterpolation of an integer has to be flat")] InvalidIntegerInterpolation { location: u32 }, #[error(transparent)] @@ -300,111 +309,6 @@ pub enum ValidationError { Corrupted, } -impl crate::GlobalVariable { - fn forbid_interpolation(&self) -> Result<(), GlobalVariableError> { - match self.interpolation { - Some(_) => Err(GlobalVariableError::InvalidInterpolation), - None => Ok(()), - } - } - - fn check_resource(&self) -> Result<(), GlobalVariableError> { - match self.binding { - Some(crate::Binding::Resource { .. }) => {} - Some(crate::Binding::BuiltIn(_)) | Some(crate::Binding::Location(_)) | None => { - return Err(GlobalVariableError::InvalidBinding) - } - } - self.forbid_interpolation() - } - - fn check_varying(&self, types: &Arena) -> Result<(), GlobalVariableError> { - match self.binding { - Some(crate::Binding::BuiltIn(built_in)) => { - use crate::{BuiltIn as Bi, ScalarKind as Sk, TypeInner as Ti, VectorSize as Vs}; - // Only validate the type here. Whether or not it's legal to access - // this builtin is up to the entry point. - let width = 4; - let expected_ty_inner = match built_in { - Bi::BaseInstance - | Bi::BaseVertex - | Bi::InstanceIndex - | Bi::VertexIndex - | Bi::SampleIndex - | Bi::SampleMaskIn - | Bi::SampleMaskOut - | Bi::LocalInvocationIndex => Some(Ti::Scalar { - kind: Sk::Uint, - width, - }), - Bi::PointSize | Bi::FragDepth => Some(Ti::Scalar { - kind: Sk::Float, - width, - }), - Bi::Position | Bi::FragCoord => Some(Ti::Vector { - size: Vs::Quad, - kind: Sk::Float, - width, - }), - Bi::FrontFacing => Some(Ti::Scalar { - kind: Sk::Bool, - width: crate::BOOL_WIDTH, - }), - Bi::GlobalInvocationId - | Bi::LocalInvocationId - | Bi::WorkGroupId - | Bi::WorkGroupSize => Some(Ti::Vector { - size: Vs::Tri, - kind: Sk::Uint, - width, - }), - Bi::ClipDistance => None, - }; - - let ty_inner = &types[self.ty].inner; - if Some(ty_inner) != expected_ty_inner.as_ref() { - match (built_in, &types[self.ty].inner) { - (Bi::ClipDistance, &Ti::Array { base, .. }) => match types[base].inner { - Ti::Scalar { - kind: Sk::Float, .. - } => {} - ref other => { - log::warn!("Wrong array base type: {:?}", other); - return Err(GlobalVariableError::InvalidBuiltInType(built_in)); - } - }, - (_, other) => { - log::warn!("Wrong builtin type: {:?}", other); - return Err(GlobalVariableError::InvalidBuiltInType(built_in)); - } - } - } - self.forbid_interpolation()? - } - Some(crate::Binding::Location(_)) => match types[self.ty].inner { - crate::TypeInner::Scalar { .. } - | crate::TypeInner::Vector { .. } - | crate::TypeInner::Matrix { .. } => {} - _ => return Err(GlobalVariableError::InvalidType), - }, - Some(crate::Binding::Resource { .. }) => { - return Err(GlobalVariableError::InvalidBinding) - } - None => { - match types[self.ty].inner { - //TODO: check the member types - crate::TypeInner::Struct { - block: _, - members: _, - } => self.forbid_interpolation()?, - _ => return Err(GlobalVariableError::InvalidType), - } - } - } - Ok(()) - } -} - fn storage_usage(access: crate::StorageAccess) -> GlobalUse { let mut storage_usage = GlobalUse::QUERY; if access.contains(crate::StorageAccess::LOAD) { @@ -416,27 +320,184 @@ fn storage_usage(access: crate::StorageAccess) -> GlobalUse { storage_usage } -fn built_in_usage(built_in: crate::BuiltIn) -> (crate::ShaderStage, GlobalUse) { - use crate::{BuiltIn as Bi, ShaderStage as Ss}; - match built_in { - Bi::BaseInstance => (Ss::Vertex, GlobalUse::READ), - Bi::BaseVertex => (Ss::Vertex, GlobalUse::READ), - Bi::ClipDistance => (Ss::Vertex, GlobalUse::WRITE), - Bi::InstanceIndex => (Ss::Vertex, GlobalUse::READ), - Bi::PointSize => (Ss::Vertex, GlobalUse::WRITE), - Bi::Position => (Ss::Vertex, GlobalUse::WRITE), - Bi::VertexIndex => (Ss::Vertex, GlobalUse::READ), - Bi::FragCoord => (Ss::Fragment, GlobalUse::READ), - Bi::FragDepth => (Ss::Fragment, GlobalUse::WRITE), - Bi::FrontFacing => (Ss::Fragment, GlobalUse::READ), - Bi::SampleIndex => (Ss::Fragment, GlobalUse::READ), - Bi::SampleMaskIn => (Ss::Fragment, GlobalUse::READ), - Bi::SampleMaskOut => (Ss::Fragment, GlobalUse::WRITE), - Bi::GlobalInvocationId => (Ss::Compute, GlobalUse::READ), - Bi::LocalInvocationId => (Ss::Compute, GlobalUse::READ), - Bi::LocalInvocationIndex => (Ss::Compute, GlobalUse::READ), - Bi::WorkGroupId => (Ss::Compute, GlobalUse::READ), - Bi::WorkGroupSize => (Ss::Compute, GlobalUse::READ), +struct VaryingContext<'a> { + ty: Handle, + stage: crate::ShaderStage, + output: bool, + types: &'a Arena, + location_mask: &'a mut BitSet, +} + +impl VaryingContext<'_> { + fn validate_impl(&mut self, binding: &crate::Binding) -> Result<(), VaryingError> { + use crate::{ + BuiltIn as Bi, ScalarKind as Sk, ShaderStage as St, TypeInner as Ti, VectorSize as Vs, + }; + + let ty_inner = &self.types[self.ty].inner; + match *binding { + crate::Binding::BuiltIn(built_in) => { + let width = 4; + let (visible, type_good) = match built_in { + Bi::BaseInstance | Bi::BaseVertex | Bi::InstanceIndex | Bi::VertexIndex => ( + self.stage == St::Vertex && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ), + Bi::ClipDistance => ( + self.stage == St::Vertex && self.output, + match *ty_inner { + Ti::Array { base, .. } => { + self.types[base].inner + == Ti::Scalar { + kind: Sk::Float, + width, + } + } + _ => false, + }, + ), + Bi::PointSize => ( + self.stage == St::Vertex && self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Float, + width, + }, + ), + Bi::Position => ( + self.stage == St::Vertex && self.output, + *ty_inner + == Ti::Vector { + size: Vs::Quad, + kind: Sk::Float, + width, + }, + ), + Bi::FragCoord => ( + self.stage == St::Fragment && !self.output, + *ty_inner + == Ti::Vector { + size: Vs::Quad, + kind: Sk::Float, + width, + }, + ), + Bi::FragDepth => ( + self.stage == St::Fragment && self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Float, + width, + }, + ), + Bi::FrontFacing => ( + self.stage == St::Fragment && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Bool, + width: crate::BOOL_WIDTH, + }, + ), + Bi::SampleIndex | Bi::SampleMaskIn => ( + self.stage == St::Fragment && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ), + Bi::SampleMaskOut => ( + self.stage == St::Fragment && self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ), + Bi::LocalInvocationIndex => ( + self.stage == St::Compute && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ), + Bi::GlobalInvocationId + | Bi::LocalInvocationId + | Bi::WorkGroupId + | Bi::WorkGroupSize => ( + self.stage == St::Compute && !self.output, + *ty_inner + == Ti::Vector { + size: Vs::Tri, + kind: Sk::Uint, + width, + }, + ), + }; + + if !visible { + return Err(VaryingError::InvalidBuiltInStage(built_in)); + } + if !type_good { + log::warn!("Wrong builtin type: {:?}", ty_inner); + return Err(VaryingError::InvalidBuiltInType(built_in)); + } + } + crate::Binding::Location(location, interpolation) => { + if !self.location_mask.insert(location as usize) { + return Err(VaryingError::BindingCollision { location }); + } + let needs_interpolation = + self.stage == crate::ShaderStage::Fragment && !self.output; + if !needs_interpolation && interpolation.is_some() { + return Err(VaryingError::InvalidInterpolation); + } + match ty_inner.scalar_kind() { + Some(crate::ScalarKind::Float) => {} + Some(_) + if needs_interpolation + && interpolation != Some(crate::Interpolation::Flat) => + { + return Err(VaryingError::InvalidInterpolation); + } + _ => return Err(VaryingError::InvalidType(self.ty)), + } + } + } + + Ok(()) + } + + fn validate(mut self, binding: Option<&crate::Binding>) -> Result<(), VaryingError> { + match binding { + Some(binding) => self.validate_impl(binding), + None => { + match self.types[self.ty].inner { + //TODO: check the member types + crate::TypeInner::Struct { + block: false, + ref members, + } => { + for (index, member) in members.iter().enumerate() { + self.ty = member.ty; + match member.binding { + None => { + return Err(VaryingError::MemberMissingBinding(index as u32)) + } + Some(ref binding) => self.validate_impl(binding)?, + } + } + } + _ => return Err(VaryingError::InvalidType(self.ty)), + } + Ok(()) + } + } } } @@ -446,8 +507,7 @@ impl Validator { Validator { typifier: Typifier::new(), type_flags: Vec::new(), - location_in_mask: BitSet::new(), - location_out_mask: BitSet::new(), + location_mask: BitSet::new(), bind_group_masks: Vec::new(), select_cases: FastHashSet::default(), valid_expression_list: Vec::new(), @@ -619,17 +679,9 @@ impl Validator { types: &Arena, ) -> Result<(), GlobalVariableError> { log::debug!("var {:?}", var); - let (allowed_storage_access, required_type_flags) = match var.class { + let (allowed_storage_access, required_type_flags, is_resource) = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), - crate::StorageClass::Input | crate::StorageClass::Output => { - var.check_varying(types)?; - ( - crate::StorageAccess::empty(), - TypeFlags::DATA | TypeFlags::INTERFACE, - ) - } crate::StorageClass::Storage => { - var.check_resource()?; match types[var.ty].inner { crate::TypeInner::Struct { .. } => (), _ => return Err(GlobalVariableError::InvalidType), @@ -637,10 +689,10 @@ impl Validator { ( crate::StorageAccess::all(), TypeFlags::DATA | TypeFlags::HOST_SHARED, + true, ) } crate::StorageClass::Uniform => { - var.check_resource()?; match types[var.ty].inner { crate::TypeInner::Struct { .. } => (), _ => return Err(GlobalVariableError::InvalidType), @@ -648,10 +700,10 @@ impl Validator { ( crate::StorageAccess::empty(), TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED, + true, ) } crate::StorageClass::Handle => { - var.check_resource()?; let access = match types[var.ty].inner { crate::TypeInner::Image { class: crate::ImageClass::Storage(_), @@ -662,18 +714,15 @@ impl Validator { } _ => return Err(GlobalVariableError::InvalidType), }; - (access, TypeFlags::empty()) + (access, TypeFlags::empty(), true) } crate::StorageClass::Private | crate::StorageClass::WorkGroup => { - if var.binding.is_some() { - return Err(GlobalVariableError::InvalidBinding); - } - var.forbid_interpolation()?; - (crate::StorageAccess::empty(), TypeFlags::DATA) + (crate::StorageAccess::empty(), TypeFlags::DATA, false) } crate::StorageClass::PushConstant => ( crate::StorageAccess::LOAD, TypeFlags::DATA | TypeFlags::HOST_SHARED, + false, ), }; @@ -692,6 +741,10 @@ impl Validator { }); } + if is_resource != var.binding.is_some() { + return Err(GlobalVariableError::InvalidBinding); + } + Ok(()) } @@ -765,7 +818,7 @@ impl Validator { .map(|expr| self.resolve_type_impl(expr, context.types)) .transpose() .map_err(CallError::ResultValue)?; - let expected_ty = fun.return_type.map(|ty| &context.types[ty].inner); + let expected_ty = fun.result.as_ref().map(|fr| &context.types[fr.ty].inner); if result_ty != expected_ty { log::error!( "Called function returns {:?} where {:?} is expected", @@ -773,7 +826,7 @@ impl Validator { expected_ty ); return Err(CallError::ResultType { - required: fun.return_type, + required: fun.result.as_ref().map(|fr| fr.ty), seen_expression: result, }); } @@ -1054,7 +1107,7 @@ impl Validator { expressions: &fun.expressions, types: &module.types, functions: &module.functions, - return_type: fun.return_type, + return_type: fun.result.as_ref().map(|fr| fr.ty), }, ) } @@ -1080,73 +1133,43 @@ impl Validator { return Err(EntryPointError::UnexpectedWorkgroupSize); } - self.location_in_mask.clear(); - self.location_out_mask.clear(); + self.location_mask.clear(); + for (index, fa) in ep.function.arguments.iter().enumerate() { + let ctx = VaryingContext { + ty: fa.ty, + stage: ep.stage, + output: false, + types: &module.types, + location_mask: &mut self.location_mask, + }; + ctx.validate(fa.binding.as_ref()) + .map_err(|e| EntryPointError::Argument(index as u32, e))?; + } + + self.location_mask.clear(); + if let Some(ref fr) = ep.function.result { + let ctx = VaryingContext { + ty: fr.ty, + stage: ep.stage, + output: true, + types: &module.types, + location_mask: &mut self.location_mask, + }; + ctx.validate(fr.binding.as_ref()) + .map_err(EntryPointError::Result)?; + } + for bg in self.bind_group_masks.iter_mut() { bg.clear(); } - for (var_handle, var) in module.global_variables.iter() { let usage = info[var_handle]; if usage.is_empty() { continue; } - if let Some(crate::Binding::Location(location)) = var.binding { - if ep.stage == crate::ShaderStage::Fragment - && var.class == crate::StorageClass::Input - { - match module.types[var.ty].inner.scalar_kind() { - Some(crate::ScalarKind::Float) => {} - Some(_) if var.interpolation != Some(crate::Interpolation::Flat) => { - return Err(EntryPointError::InvalidIntegerInterpolation { location }); - } - _ => {} - } - } - } - let allowed_usage = match var.class { crate::StorageClass::Function => unreachable!(), - crate::StorageClass::Input => { - match var.binding { - Some(crate::Binding::BuiltIn(built_in)) => { - let (allowed_stage, allowed_usage) = built_in_usage(built_in); - if allowed_stage != ep.stage || !allowed_usage.contains(GlobalUse::READ) - { - return Err(EntryPointError::InvalidBuiltIn(built_in)); - } - } - Some(crate::Binding::Location(loc)) => { - if !self.location_in_mask.insert(loc as usize) { - return Err(EntryPointError::BindingCollision(var_handle)); - } - } - Some(crate::Binding::Resource { .. }) => unreachable!(), - None => (), - } - GlobalUse::READ - } - crate::StorageClass::Output => { - match var.binding { - Some(crate::Binding::BuiltIn(built_in)) => { - let (allowed_stage, allowed_usage) = built_in_usage(built_in); - if allowed_stage != ep.stage - || !allowed_usage.contains(GlobalUse::WRITE) - { - return Err(EntryPointError::InvalidBuiltIn(built_in)); - } - } - Some(crate::Binding::Location(loc)) => { - if !self.location_out_mask.insert(loc as usize) { - return Err(EntryPointError::BindingCollision(var_handle)); - } - } - Some(crate::Binding::Resource { .. }) => unreachable!(), - None => (), - } - GlobalUse::READ | GlobalUse::WRITE - } crate::StorageClass::Uniform => GlobalUse::READ | GlobalUse::QUERY, crate::StorageClass::Storage => storage_usage(var.storage_access), crate::StorageClass::Handle => match module.types[var.ty].inner { @@ -1169,23 +1192,16 @@ impl Validator { return Err(EntryPointError::InvalidGlobalUsage(var_handle, usage)); } - if let Some(crate::Binding::Resource { group, binding }) = var.binding { - while self.bind_group_masks.len() <= group as usize { + if let Some(ref bind) = var.binding { + while self.bind_group_masks.len() <= bind.group as usize { self.bind_group_masks.push(BitSet::new()); } - if !self.bind_group_masks[group as usize].insert(binding as usize) { + if !self.bind_group_masks[bind.group as usize].insert(bind.binding as usize) { return Err(EntryPointError::BindingCollision(var_handle)); } } } - if !ep.function.arguments.is_empty() { - return Err(EntryPointError::UnexpectedArguments); - } - if ep.function.return_type.is_some() { - return Err(EntryPointError::UnexpectedReturnValue); - } - self.validate_function(&ep.function, info, module)?; Ok(()) } diff --git a/tests/errors.rs b/tests/errors.rs index 97611b8c6..2f159c744 100644 --- a/tests/errors.rs +++ b/tests/errors.rs @@ -30,13 +30,13 @@ fn function_without_identifier() { #[test] fn invalid_integer() { err!( - "[[location(1.)]] var pos : vec2;", + "fn foo([location(1.)] x: i32) {}", @r###" - error: expected integer literal, found `1.` - ┌─ wgsl:1:12 + error: expected identifier, found '[' + ┌─ wgsl:1:8 │ - 1 │ [[location(1.)]] var pos : vec2; - │ ^^ expected integer + 1 │ fn foo([location(1.)] x: i32) {} + │ ^ expected identifier "### ); diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 55ba3405f..3b404f9f0 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -26,12 +26,10 @@ struct Particles { [[group(0), binding(1)]] var particlesSrc : [[access(read)]] Particles; [[group(0), binding(2)]] var particlesDst : [[access(read_write)]] Particles; -[[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3; - // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp [[stage(compute), workgroup_size(64)]] -fn main() { - const index : u32 = gl_GlobalInvocationID.x; +fn main([[builtin(global_invocation_id)]] global_invocation_id : vec3) { + const index : u32 = global_invocation_id.x; if (index >= NUM_PARTICLES) { return; } diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index 6edf54f96..4d2168f46 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -1,6 +1,3 @@ -[[builtin(global_invocation_id)]] -var global_id: vec3; - [[block]] struct PrimeIndices { data: [[stride(4)]] array; @@ -34,6 +31,6 @@ fn collatz_iterations(n_base: u32) -> u32 { } [[stage(compute), workgroup_size(1)]] -fn main() { +fn main([[builtin(global_invocation_id)]] global_id: vec3) { v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); } diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index d85e5f247..514f11e9b 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -1,28 +1,29 @@ // vertex const c_scale: f32 = 1.2; -[[location(0)]] var a_pos : vec2; -[[location(1)]] var a_uv : vec2; -[[location(0)]] var v_uv : vec2; -[[builtin(position)]] var o_position : vec4; + +struct VertexOutput { + [[location(0)]] uv : vec2; + [[builtin(position)]] position : vec4; +}; [[stage(vertex)]] -fn main() { - v_uv = a_uv; - o_position = vec4(c_scale * a_pos, 0.0, 1.0); +fn main([[location(0)]] pos : vec2, [[location(1)]] uv : vec2) -> VertexOutput { + var out: VertexOutput; + out.uv = uv; + out.position = vec4(c_scale * pos, 0.0, 1.0); + return out; } // fragment -[[location(0)]] var v_uv : vec2; [[group(0), binding(0)]] var u_texture : texture_2d; [[group(0), binding(1)]] var u_sampler : sampler; -[[location(0)]] var o_color : vec4; [[stage(fragment)]] -fn main() { - const color: vec4 = textureSample(u_texture, u_sampler, v_uv); +fn main([[location(0)]] uv : vec2) -> [[location(0)]] vec4 { + const color: vec4 = textureSample(u_texture, u_sampler, uv); if (color.a == 0.0) { discard; } const premultiplied: vec4 = color.a * color; - o_color = premultiplied; + return premultiplied; } diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 4521aace8..e6c2408a5 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -35,19 +35,15 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { return textureSampleCompare(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z * proj_correction); } -[[location(0)]] -var in_normal_fs: vec3; -[[location(1)]] -var in_position_fs: vec4; -[[location(0)]] -var out_color_fs: vec4; - const c_ambient: vec3 = vec3(0.05, 0.05, 0.05); const c_max_lights: u32 = 10u; [[stage(fragment)]] -fn fs_main() { - const normal: vec3 = normalize(in_normal_fs); +fn fs_main( + [[location(0)]] raw_normal: vec3, + [[location(1)]] position: vec4 +) -> [[location(0)]] vec4 { + const normal: vec3 = normalize(raw_normal); // accumulate color var color: vec3 = c_ambient; var i: u32 = 0u; @@ -56,8 +52,8 @@ fn fs_main() { break; } const light: Light = s_lights.data[i]; - const shadow: f32 = fetch_shadow(i, light.proj * in_position_fs); - const light_dir: vec3 = normalize(light.pos.xyz - in_position_fs.xyz); + const shadow: f32 = fetch_shadow(i, light.proj * position); + const light_dir: vec3 = normalize(light.pos.xyz - position.xyz); const diffuse: f32 = max(0.0, dot(normal, light_dir)); color = color + shadow * diffuse * light.color.xyz; continuing { @@ -65,5 +61,5 @@ fn fs_main() { } } // multiply the light by material color - out_color_fs = vec4(color, 1.0); + return vec4(color, 1.0); } diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index 9254ab6a2..bdb9ea820 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -1,7 +1,7 @@ -[[builtin(position)]] -var out_position: vec4; -[[location(0)]] var out_uv: vec3; -[[builtin(vertex_index)]] var in_vertex_index: u32; +struct VertexOutput { + [[builtin(position)]] position: vec4; + [[location(0)]] uv: vec3; +}; [[block]] struct Data { @@ -12,10 +12,10 @@ struct Data { var r_data: Data; [[stage(vertex)]] -fn vs_main() { +fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { // hacky way to draw a large triangle - var tmp1: i32 = i32(in_vertex_index) / 2; - var tmp2: i32 = i32(in_vertex_index) & 1; + var tmp1: i32 = i32(vertex_index) / 2; + var tmp2: i32 = i32(vertex_index) & 1; const pos: vec4 = vec4( f32(tmp1) * 4.0 - 1.0, f32(tmp2) * 4.0 - 1.0, @@ -25,8 +25,10 @@ fn vs_main() { const inv_model_view: mat3x3 = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); var unprojected: vec4 = r_data.proj_inv * pos; //TODO: const - out_uv = inv_model_view * unprojected.xyz; - out_position = pos; + var out: VertexOutput; + out.uv = inv_model_view * unprojected.xyz; + out.position = pos; + return out; } [[group(0), binding(1)]] @@ -34,10 +36,7 @@ var r_texture: texture_cube; [[group(0), binding(2)]] var r_sampler: sampler; -[[location(0)]] var in_uv: vec3; -[[location(0)]] var out_color: vec4; - [[stage(fragment)]] -fn fs_main() { - out_color = textureSample(r_texture, r_sampler, in_uv); +fn fs_main([[location(0)]] uv: vec3) -> [[location(0)]] vec4 { + return textureSample(r_texture, r_sampler, uv); } diff --git a/tests/in/texture-array.wgsl b/tests/in/texture-array.wgsl index 629a7c75f..ca14d8c23 100644 --- a/tests/in/texture-array.wgsl +++ b/tests/in/texture-array.wgsl @@ -1,4 +1,3 @@ -[[location(0)]] var tex_coord: vec2; [[group(0), binding(0)]] var texture0: texture_2d; [[group(0), binding(1)]] var texture1: texture_2d; [[group(0), binding(2)]] var sampler: sampler; @@ -9,13 +8,11 @@ struct PushConstants { }; var pc: PushConstants; -[[location(1)]] var color: vec4; - [[stage(fragment)]] -fn main() { +fn main([[location(0)]] tex_coord: vec2) -> [[location(1)]] vec4 { if (pc.index == 0) { - color = textureSample(texture0, sampler, tex_coord); + return textureSample(texture0, sampler, tex_coord); } else { - color = textureSample(texture1, sampler, tex_coord); + return textureSample(texture1, sampler, tex_coord); } } diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index 623f68f02..237e6de6e 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -45,11 +45,13 @@ constexpr constant unsigned const_1u = 1u; constexpr constant float const_1f = 1.0; constexpr constant float const_0_10f = 0.1; constexpr constant float const_n1f = -1.0; +struct main1Input { +}; kernel void main1( - constant SimParams& params [[buffer(0)]], - constant Particles& particlesSrc [[buffer(1)]], - device Particles& particlesDst [[buffer(2)]], - type4 gl_GlobalInvocationID [[thread_position_in_grid]] + type4 global_invocation_id [[thread_position_in_grid]] +, constant SimParams& params [[buffer(0)]] +, constant Particles& particlesSrc [[buffer(1)]] +, device Particles& particlesDst [[buffer(2)]] ) { type1 vPos; type1 vVel; @@ -61,11 +63,11 @@ kernel void main1( type1 pos1; type1 vel1; type i = const_0u; - if ((gl_GlobalInvocationID.x >= NUM_PARTICLES)) { - return ; + if ((global_invocation_id.x >= NUM_PARTICLES)) { + return; } - vPos = particlesSrc.particles[gl_GlobalInvocationID.x].pos; - vVel = particlesSrc.particles[gl_GlobalInvocationID.x].vel; + vPos = particlesSrc.particles[global_invocation_id.x].pos; + vVel = particlesSrc.particles[global_invocation_id.x].vel; cMass = metal::float2(const_0f, const_0f); cVel = metal::float2(const_0f, const_0f); colVel = metal::float2(const_0f, const_0f); @@ -78,7 +80,7 @@ kernel void main1( if ((i >= NUM_PARTICLES)) { break; } - if ((i == gl_GlobalInvocationID.x)) { + if ((i == global_invocation_id.x)) { continue; } pos1 = particlesSrc.particles[i].pos; @@ -116,8 +118,8 @@ kernel void main1( if ((vPos.y > const_1f)) { vPos.y = const_n1f; } - particlesDst.particles[gl_GlobalInvocationID.x].pos = vPos; - particlesDst.particles[gl_GlobalInvocationID.x].vel = vVel; - return ; + particlesDst.particles[global_invocation_id.x].pos = vPos; + particlesDst.particles[global_invocation_id.x].vel = vVel; + return; } diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index 247608eb3..80e3f0860 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -9,8 +9,8 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %41 "main" %25 -OpExecutionMode %41 LocalSize 64 1 1 +OpEntryPoint GLCompute %43 "main" %40 +OpExecutionMode %43 LocalSize 64 1 1 OpSource GLSL 450 OpName %3 "NUM_PARTICLES" OpName %16 "SimParams" @@ -29,19 +29,19 @@ OpMemberName %21 0 "pos" OpMemberName %21 1 "vel" OpName %18 "particlesSrc" OpName %24 "particlesDst" -OpName %25 "gl_GlobalInvocationID" -OpName %28 "vPos" -OpName %30 "vVel" -OpName %31 "cMass" -OpName %32 "cVel" -OpName %33 "colVel" -OpName %34 "cMassCount" -OpName %36 "cVelCount" -OpName %37 "pos" -OpName %38 "vel" -OpName %39 "i" -OpName %41 "main" -OpName %41 "main" +OpName %25 "vPos" +OpName %27 "vVel" +OpName %28 "cMass" +OpName %29 "cVel" +OpName %30 "colVel" +OpName %31 "cMassCount" +OpName %33 "cVelCount" +OpName %34 "pos" +OpName %35 "vel" +OpName %36 "i" +OpName %40 "global_invocation_id" +OpName %43 "main" +OpName %43 "main" OpDecorate %16 Block OpMemberDecorate %16 0 Offset 0 OpMemberDecorate %16 1 Offset 4 @@ -62,7 +62,7 @@ OpDecorate %18 DescriptorSet 0 OpDecorate %18 Binding 1 OpDecorate %24 DescriptorSet 0 OpDecorate %24 Binding 2 -OpDecorate %25 BuiltIn GlobalInvocationId +OpDecorate %40 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1500 @@ -86,13 +86,13 @@ OpDecorate %25 BuiltIn GlobalInvocationId %23 = OpTypePointer Uniform %19 %18 = OpVariable %23 Uniform %24 = OpVariable %23 Uniform -%26 = OpTypeVector %9 3 -%27 = OpTypePointer Input %26 -%25 = OpVariable %27 Input -%29 = OpTypePointer Function %22 -%35 = OpTypePointer Function %4 -%40 = OpTypePointer Function %9 -%42 = OpTypeFunction %2 +%26 = OpTypePointer Function %22 +%32 = OpTypePointer Function %4 +%37 = OpTypePointer Function %9 +%39 = OpTypeVector %9 3 +%41 = OpTypePointer Input %39 +%40 = OpVariable %41 Input +%44 = OpTypeFunction %2 %47 = OpTypeBool %51 = OpTypePointer Uniform %20 %52 = OpTypePointer Uniform %21 @@ -122,22 +122,22 @@ OpDecorate %25 BuiltIn GlobalInvocationId %215 = OpConstant %4 0 %218 = OpConstant %4 1 %219 = OpConstant %4 0 -%41 = OpFunction %2 None %42 -%43 = OpLabel -%39 = OpVariable %40 Function %8 -%36 = OpVariable %35 Function %7 -%32 = OpVariable %29 Function -%28 = OpVariable %29 Function -%37 = OpVariable %29 Function -%33 = OpVariable %29 Function -%30 = OpVariable %29 Function -%38 = OpVariable %29 Function -%34 = OpVariable %35 Function %7 -%31 = OpVariable %29 Function -OpBranch %44 -%44 = OpLabel -%45 = OpLoad %26 %25 -%46 = OpCompositeExtract %9 %45 0 +%43 = OpFunction %2 None %44 +%38 = OpLabel +%36 = OpVariable %37 Function %8 +%33 = OpVariable %32 Function %7 +%29 = OpVariable %26 Function +%25 = OpVariable %26 Function +%34 = OpVariable %26 Function +%30 = OpVariable %26 Function +%27 = OpVariable %26 Function +%35 = OpVariable %26 Function +%31 = OpVariable %32 Function %7 +%28 = OpVariable %26 Function +%42 = OpLoad %39 %40 +OpBranch %45 +%45 = OpLabel +%46 = OpCompositeExtract %9 %42 0 %48 = OpUGreaterThanEqual %47 %46 %3 OpSelectionMerge %49 None OpBranchConditional %48 %50 %49 @@ -146,45 +146,45 @@ OpReturn %49 = OpLabel %56 = OpAccessChain %53 %18 %55 %46 %54 %57 = OpLoad %22 %56 -OpStore %28 %57 +OpStore %25 %57 %60 = OpAccessChain %53 %18 %59 %46 %58 %61 = OpLoad %22 %60 -OpStore %30 %61 +OpStore %27 %61 %62 = OpCompositeConstruct %22 %5 %5 -OpStore %31 %62 +OpStore %28 %62 %63 = OpCompositeConstruct %22 %5 %5 -OpStore %32 %63 +OpStore %29 %63 %64 = OpCompositeConstruct %22 %5 %5 -OpStore %33 %64 +OpStore %30 %64 OpBranch %65 %65 = OpLabel OpLoopMerge %66 %68 None OpBranch %67 %67 = OpLabel -%69 = OpLoad %9 %39 +%69 = OpLoad %9 %36 %70 = OpUGreaterThanEqual %47 %69 %3 OpSelectionMerge %71 None OpBranchConditional %70 %72 %71 %72 = OpLabel OpBranch %66 %71 = OpLabel -%73 = OpLoad %9 %39 +%73 = OpLoad %9 %36 %74 = OpIEqual %47 %73 %46 OpSelectionMerge %75 None OpBranchConditional %74 %76 %75 %76 = OpLabel OpBranch %68 %75 = OpLabel -%77 = OpLoad %9 %39 +%77 = OpLoad %9 %36 %80 = OpAccessChain %53 %18 %79 %77 %78 %81 = OpLoad %22 %80 -OpStore %37 %81 -%82 = OpLoad %9 %39 +OpStore %34 %81 +%82 = OpLoad %9 %36 %85 = OpAccessChain %53 %18 %84 %82 %83 %86 = OpLoad %22 %85 -OpStore %38 %86 -%87 = OpLoad %22 %37 -%88 = OpLoad %22 %28 +OpStore %35 %86 +%87 = OpLoad %22 %34 +%88 = OpLoad %22 %25 %89 = OpExtInst %6 %1 Distance %87 %88 %92 = OpAccessChain %90 %15 %91 %93 = OpLoad %6 %92 @@ -192,17 +192,17 @@ OpStore %38 %86 OpSelectionMerge %95 None OpBranchConditional %94 %96 %95 %96 = OpLabel -%97 = OpLoad %22 %31 -%98 = OpLoad %22 %37 +%97 = OpLoad %22 %28 +%98 = OpLoad %22 %34 %99 = OpFAdd %22 %97 %98 -OpStore %31 %99 -%100 = OpLoad %4 %34 +OpStore %28 %99 +%100 = OpLoad %4 %31 %101 = OpIAdd %4 %100 %10 -OpStore %34 %101 +OpStore %31 %101 OpBranch %95 %95 = OpLabel -%102 = OpLoad %22 %37 -%103 = OpLoad %22 %28 +%102 = OpLoad %22 %34 +%103 = OpLoad %22 %25 %104 = OpExtInst %6 %1 Distance %102 %103 %106 = OpAccessChain %90 %15 %105 %107 = OpLoad %6 %106 @@ -210,16 +210,16 @@ OpBranch %95 OpSelectionMerge %109 None OpBranchConditional %108 %110 %109 %110 = OpLabel -%111 = OpLoad %22 %33 -%112 = OpLoad %22 %37 -%113 = OpLoad %22 %28 +%111 = OpLoad %22 %30 +%112 = OpLoad %22 %34 +%113 = OpLoad %22 %25 %114 = OpFSub %22 %112 %113 %115 = OpFSub %22 %111 %114 -OpStore %33 %115 +OpStore %30 %115 OpBranch %109 %109 = OpLabel -%116 = OpLoad %22 %37 -%117 = OpLoad %22 %28 +%116 = OpLoad %22 %34 +%117 = OpLoad %22 %25 %118 = OpExtInst %6 %1 Distance %116 %117 %120 = OpAccessChain %90 %15 %119 %121 = OpLoad %6 %120 @@ -227,125 +227,125 @@ OpBranch %109 OpSelectionMerge %123 None OpBranchConditional %122 %124 %123 %124 = OpLabel -%125 = OpLoad %22 %32 -%126 = OpLoad %22 %38 +%125 = OpLoad %22 %29 +%126 = OpLoad %22 %35 %127 = OpFAdd %22 %125 %126 -OpStore %32 %127 -%128 = OpLoad %4 %36 +OpStore %29 %127 +%128 = OpLoad %4 %33 %129 = OpIAdd %4 %128 %10 -OpStore %36 %129 +OpStore %33 %129 OpBranch %123 %123 = OpLabel OpBranch %68 %68 = OpLabel -%130 = OpLoad %9 %39 +%130 = OpLoad %9 %36 %131 = OpIAdd %9 %130 %11 -OpStore %39 %131 +OpStore %36 %131 OpBranch %65 %66 = OpLabel -%132 = OpLoad %4 %34 +%132 = OpLoad %4 %31 %133 = OpSGreaterThan %47 %132 %7 OpSelectionMerge %134 None OpBranchConditional %133 %135 %134 %135 = OpLabel -%136 = OpLoad %22 %31 -%137 = OpLoad %4 %34 +%136 = OpLoad %22 %28 +%137 = OpLoad %4 %31 %138 = OpConvertSToF %6 %137 %139 = OpFDiv %6 %12 %138 %140 = OpVectorTimesScalar %22 %136 %139 -%141 = OpLoad %22 %28 +%141 = OpLoad %22 %25 %142 = OpFSub %22 %140 %141 -OpStore %31 %142 +OpStore %28 %142 OpBranch %134 %134 = OpLabel -%143 = OpLoad %4 %36 +%143 = OpLoad %4 %33 %144 = OpSGreaterThan %47 %143 %7 OpSelectionMerge %145 None OpBranchConditional %144 %146 %145 %146 = OpLabel -%147 = OpLoad %22 %32 -%148 = OpLoad %4 %36 +%147 = OpLoad %22 %29 +%148 = OpLoad %4 %33 %149 = OpConvertSToF %6 %148 %150 = OpFDiv %6 %12 %149 %151 = OpVectorTimesScalar %22 %147 %150 -OpStore %32 %151 +OpStore %29 %151 OpBranch %145 %145 = OpLabel -%152 = OpLoad %22 %30 -%153 = OpLoad %22 %31 +%152 = OpLoad %22 %27 +%153 = OpLoad %22 %28 %155 = OpAccessChain %90 %15 %154 %156 = OpLoad %6 %155 %157 = OpVectorTimesScalar %22 %153 %156 %158 = OpFAdd %22 %152 %157 -%159 = OpLoad %22 %33 +%159 = OpLoad %22 %30 %161 = OpAccessChain %90 %15 %160 %162 = OpLoad %6 %161 %163 = OpVectorTimesScalar %22 %159 %162 %164 = OpFAdd %22 %158 %163 -%165 = OpLoad %22 %32 +%165 = OpLoad %22 %29 %167 = OpAccessChain %90 %15 %166 %168 = OpLoad %6 %167 %169 = OpVectorTimesScalar %22 %165 %168 %170 = OpFAdd %22 %164 %169 -OpStore %30 %170 -%171 = OpLoad %22 %30 +OpStore %27 %170 +%171 = OpLoad %22 %27 %172 = OpExtInst %22 %1 Normalize %171 -%173 = OpLoad %22 %30 +%173 = OpLoad %22 %27 %174 = OpExtInst %6 %1 Length %173 %175 = OpExtInst %6 %1 FClamp %174 %5 %13 %176 = OpVectorTimesScalar %22 %172 %175 -OpStore %30 %176 -%177 = OpLoad %22 %28 -%178 = OpLoad %22 %30 +OpStore %27 %176 +%177 = OpLoad %22 %25 +%178 = OpLoad %22 %27 %180 = OpAccessChain %90 %15 %179 %181 = OpLoad %6 %180 %182 = OpVectorTimesScalar %22 %178 %181 %183 = OpFAdd %22 %177 %182 -OpStore %28 %183 -%184 = OpLoad %22 %28 +OpStore %25 %183 +%184 = OpLoad %22 %25 %185 = OpCompositeExtract %6 %184 0 %186 = OpFOrdLessThan %47 %185 %14 OpSelectionMerge %187 None OpBranchConditional %186 %188 %187 %188 = OpLabel -%191 = OpAccessChain %189 %28 %190 +%191 = OpAccessChain %189 %25 %190 OpStore %191 %12 OpBranch %187 %187 = OpLabel -%192 = OpLoad %22 %28 +%192 = OpLoad %22 %25 %193 = OpCompositeExtract %6 %192 0 %194 = OpFOrdGreaterThan %47 %193 %12 OpSelectionMerge %195 None OpBranchConditional %194 %196 %195 %196 = OpLabel -%198 = OpAccessChain %189 %28 %197 +%198 = OpAccessChain %189 %25 %197 OpStore %198 %14 OpBranch %195 %195 = OpLabel -%199 = OpLoad %22 %28 +%199 = OpLoad %22 %25 %200 = OpCompositeExtract %6 %199 1 %201 = OpFOrdLessThan %47 %200 %14 OpSelectionMerge %202 None OpBranchConditional %201 %203 %202 %203 = OpLabel -%205 = OpAccessChain %189 %28 %204 +%205 = OpAccessChain %189 %25 %204 OpStore %205 %12 OpBranch %202 %202 = OpLabel -%206 = OpLoad %22 %28 +%206 = OpLoad %22 %25 %207 = OpCompositeExtract %6 %206 1 %208 = OpFOrdGreaterThan %47 %207 %12 OpSelectionMerge %209 None OpBranchConditional %208 %210 %209 %210 = OpLabel -%212 = OpAccessChain %189 %28 %211 +%212 = OpAccessChain %189 %25 %211 OpStore %212 %14 OpBranch %209 %209 = OpLabel -%213 = OpLoad %22 %28 +%213 = OpLoad %22 %25 %216 = OpAccessChain %53 %24 %215 %46 %214 OpStore %216 %213 -%217 = OpLoad %22 %30 +%217 = OpLoad %22 %27 %220 = OpAccessChain %53 %24 %219 %46 %218 OpStore %220 %217 OpReturn diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 75f3241a0..fcb66a51b 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -6,7 +6,7 @@ expression: output functions: [ ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(5), requirement: None, ), may_kill: false, @@ -15,9 +15,6 @@ expression: output ( bits: 0, ), - ( - bits: 0, - ), ], expressions: [ ( @@ -33,20 +30,12 @@ expression: output non_uniform_result: Some(2), requirement: None, ), - ref_count: 0, - assignable_global: Some(2), - ), - ( - uniformity: ( - non_uniform_result: Some(3), - requirement: None, - ), ref_count: 1, assignable_global: None, ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 7, @@ -62,7 +51,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(5), requirement: None, ), ref_count: 3, @@ -70,7 +59,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -86,7 +75,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -94,7 +83,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -110,7 +99,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -126,7 +115,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -134,7 +123,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -150,7 +139,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -166,7 +155,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -174,7 +163,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -190,7 +179,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(3), requirement: None, ), ref_count: 1, @@ -198,7 +187,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(5), requirement: None, ), ref_count: 1, @@ -214,7 +203,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(5), requirement: None, ), ref_count: 1, @@ -222,7 +211,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(5), requirement: None, ), ref_count: 1, @@ -234,15 +223,12 @@ expression: output entry_points: [ ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(5), requirement: None, ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 1, - ), ( bits: 3, ), @@ -262,15 +248,7 @@ expression: output requirement: None, ), ref_count: 2, - assignable_global: Some(2), - ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirement: None, - ), - ref_count: 1, - assignable_global: Some(2), + assignable_global: None, ), ( uniformity: ( @@ -278,6 +256,14 @@ expression: output requirement: None, ), ref_count: 1, + assignable_global: Some(1), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirement: None, + ), + ref_count: 1, assignable_global: None, ), ( @@ -286,23 +272,7 @@ expression: output requirement: None, ), ref_count: 1, - assignable_global: None, - ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirement: None, - ), - ref_count: 1, - assignable_global: Some(2), - ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirement: None, - ), - ref_count: 1, - assignable_global: Some(2), + assignable_global: Some(1), ), ( uniformity: ( @@ -310,6 +280,14 @@ expression: output requirement: None, ), ref_count: 1, + assignable_global: Some(1), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirement: None, + ), + ref_count: 1, assignable_global: None, ), ( @@ -318,19 +296,11 @@ expression: output requirement: None, ), ref_count: 1, - assignable_global: None, + assignable_global: Some(1), ), ( uniformity: ( - non_uniform_result: Some(2), - requirement: None, - ), - ref_count: 1, - assignable_global: Some(2), - ), - ( - uniformity: ( - non_uniform_result: Some(2), + non_uniform_result: Some(1), requirement: None, ), ref_count: 1, @@ -338,7 +308,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(5), requirement: None, ), ref_count: 1, diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index 9ff843e53..13e4a1e0c 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -5,25 +5,25 @@ expression: msl #include #include -typedef metal::uint3 type; +typedef uint type; -typedef uint type1; - -typedef type1 type2[1]; +typedef type type1[1]; struct PrimeIndices { - type2 data; + type1 data; }; +typedef metal::uint3 type2; + constexpr constant unsigned const_0u = 0u; constexpr constant unsigned const_1u = 1u; constexpr constant unsigned const_2u = 2u; constexpr constant unsigned const_3u = 3u; -type1 collatz_iterations( - type1 n_base +type collatz_iterations( + type n_base ) { - type1 n; - type1 i = const_0u; + type n; + type i = const_0u; n = n_base; while(true) { if ((n <= const_1u)) { @@ -39,12 +39,14 @@ type1 collatz_iterations( return i; } +struct main1Input { +}; kernel void main1( - type global_id [[thread_position_in_grid]], - device PrimeIndices& v_indices [[buffer(0)]] + type2 global_id [[thread_position_in_grid]] +, device PrimeIndices& v_indices [[buffer(0)]] ) { - type1 _expr11 = collatz_iterations(v_indices.data[global_id.x]); - v_indices.data[global_id.x] = _expr11; - return ; + type _expr9 = collatz_iterations(v_indices.data[global_id.x]); + v_indices.data[global_id.x] = _expr9; + return; } diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap index c02a92a1a..5b3a5eca4 100644 --- a/tests/out/collatz.ron.snap +++ b/tests/out/collatz.ron.snap @@ -4,14 +4,6 @@ expression: output --- ( types: [ - ( - name: None, - inner: Vector( - size: Tri, - kind: Uint, - width: 4, - ), - ), ( name: None, inner: Scalar( @@ -22,7 +14,7 @@ expression: output ( name: None, inner: Array( - base: 2, + base: 1, size: Dynamic, stride: Some(4), ), @@ -35,11 +27,20 @@ expression: output ( name: Some("data"), span: None, - ty: 3, + ty: 2, + binding: None, ), ], ), ), + ( + name: None, + inner: Vector( + size: Tri, + kind: Uint, + width: 4, + ), + ), ], constants: [ ( @@ -76,27 +77,15 @@ expression: output ), ], global_variables: [ - ( - name: Some("global_id"), - class: Input, - binding: Some(BuiltIn(GlobalInvocationId)), - ty: 1, - init: None, - interpolation: None, - storage_access: ( - bits: 0, - ), - ), ( name: Some("v_indices"), class: Storage, - binding: Some(Resource( + binding: Some(( group: 0, binding: 0, )), - ty: 4, + ty: 3, init: None, - interpolation: None, storage_access: ( bits: 3, ), @@ -108,176 +97,179 @@ expression: output arguments: [ ( name: Some("n_base"), - ty: 2, + ty: 1, + binding: None, ), ], - return_type: Some(2), + result: Some(( + ty: 1, + binding: None, + )), local_variables: [ ( name: Some("n"), - ty: 2, + ty: 1, init: None, ), ( name: Some("i"), - ty: 2, + ty: 1, init: Some(1), ), ], expressions: [ GlobalVariable(1), - GlobalVariable(2), FunctionArgument(0), LocalVariable(1), Constant(1), LocalVariable(2), Load( - pointer: 4, + pointer: 3, ), Constant(2), Binary( op: LessEqual, - left: 7, - right: 8, + left: 6, + right: 7, ), Load( - pointer: 4, + pointer: 3, ), Constant(3), Binary( op: Modulo, - left: 10, - right: 11, + left: 9, + right: 10, ), Constant(1), Binary( op: Equal, - left: 12, - right: 13, + left: 11, + right: 12, ), Load( - pointer: 4, + pointer: 3, ), Constant(3), Binary( op: Divide, - left: 15, - right: 16, + left: 14, + right: 15, ), Constant(4), Load( - pointer: 4, + pointer: 3, ), Binary( op: Multiply, - left: 18, - right: 19, + left: 17, + right: 18, ), Constant(2), Binary( op: Add, - left: 20, - right: 21, + left: 19, + right: 20, ), Load( - pointer: 6, + pointer: 5, ), Constant(2), Binary( op: Add, - left: 23, - right: 24, + left: 22, + right: 23, ), Load( - pointer: 6, + pointer: 5, ), ], body: [ Store( - pointer: 4, - value: 3, + pointer: 3, + value: 2, ), Loop( body: [ Emit(( - start: 6, - end: 7, + start: 5, + end: 6, )), Emit(( - start: 8, - end: 9, + start: 7, + end: 8, )), If( - condition: 9, + condition: 8, accept: [ Break, ], reject: [], ), Emit(( - start: 9, - end: 10, + start: 8, + end: 9, )), Emit(( - start: 11, - end: 12, + start: 10, + end: 11, )), Emit(( - start: 13, - end: 14, + start: 12, + end: 13, )), If( - condition: 14, + condition: 13, accept: [ Emit(( - start: 14, - end: 15, + start: 13, + end: 14, )), Emit(( - start: 16, - end: 17, + start: 15, + end: 16, )), Store( - pointer: 4, - value: 17, + pointer: 3, + value: 16, ), ], reject: [ Emit(( - start: 18, - end: 20, + start: 17, + end: 19, )), Emit(( - start: 21, - end: 22, + start: 20, + end: 21, )), Store( - pointer: 4, - value: 22, + pointer: 3, + value: 21, ), ], ), Emit(( - start: 22, - end: 23, + start: 21, + end: 22, )), Emit(( - start: 24, - end: 25, + start: 23, + end: 24, )), Store( - pointer: 6, - value: 25, + pointer: 5, + value: 24, ), ], continuing: [], ), Emit(( - start: 25, - end: 26, + start: 24, + end: 25, )), Return( - value: Some(26), + value: Some(25), ), ], ), @@ -290,62 +282,62 @@ expression: output workgroup_size: (1, 1, 1), function: ( name: Some("main"), - arguments: [], - return_type: None, + arguments: [ + ( + name: Some("global_id"), + ty: 4, + binding: Some(BuiltIn(GlobalInvocationId)), + ), + ], + result: None, local_variables: [], expressions: [ GlobalVariable(1), - GlobalVariable(2), + FunctionArgument(0), AccessIndex( - base: 2, + base: 1, index: 0, ), - Load( - pointer: 1, - ), AccessIndex( - base: 4, + base: 2, index: 0, ), Access( base: 3, - index: 5, + index: 4, + ), + AccessIndex( + base: 1, + index: 0, ), AccessIndex( base: 2, index: 0, ), - Load( - pointer: 1, - ), - AccessIndex( - base: 8, - index: 0, - ), Access( - base: 7, - index: 9, + base: 6, + index: 7, ), Load( - pointer: 10, + pointer: 8, ), Call(1), ], body: [ Emit(( start: 2, - end: 11, + end: 9, )), Call( function: 1, arguments: [ - 11, + 9, ], - result: Some(12), + result: Some(10), ), Store( - pointer: 6, - value: 12, + pointer: 5, + value: 10, ), Return( value: None, diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index e14af257f..6064a6fdb 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -5,109 +5,108 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 63 +; Bound: 62 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %46 "main" %8 -OpExecutionMode %46 LocalSize 1 1 1 +OpEntryPoint GLCompute %48 "main" %45 +OpExecutionMode %48 LocalSize 1 1 1 OpSource GLSL 450 -OpName %8 "global_id" -OpName %12 "PrimeIndices" -OpMemberName %12 0 "data" -OpName %11 "v_indices" -OpName %15 "n" -OpName %17 "i" -OpName %19 "collatz_iterations" -OpName %46 "main" -OpName %46 "main" -OpDecorate %8 BuiltIn GlobalInvocationId -OpDecorate %12 BufferBlock -OpMemberDecorate %12 0 Offset 0 -OpDecorate %13 ArrayStride 4 -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 0 +OpName %9 "PrimeIndices" +OpMemberName %9 0 "data" +OpName %8 "v_indices" +OpName %12 "n" +OpName %14 "i" +OpName %17 "collatz_iterations" +OpName %45 "global_id" +OpName %48 "main" +OpName %48 "main" +OpDecorate %9 BufferBlock +OpMemberDecorate %9 0 Offset 0 +OpDecorate %10 ArrayStride 4 +OpDecorate %8 DescriptorSet 0 +OpDecorate %8 Binding 0 +OpDecorate %45 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 %5 = OpConstant %4 1 %6 = OpConstant %4 2 %7 = OpConstant %4 3 -%9 = OpTypeVector %4 3 -%10 = OpTypePointer Input %9 -%8 = OpVariable %10 Input -%13 = OpTypeRuntimeArray %4 -%12 = OpTypeStruct %13 -%14 = OpTypePointer Uniform %12 -%11 = OpVariable %14 Uniform -%16 = OpTypePointer Function %4 -%20 = OpTypeFunction %4 %4 -%28 = OpTypeBool -%47 = OpTypeFunction %2 -%50 = OpTypePointer Uniform %13 +%10 = OpTypeRuntimeArray %4 +%9 = OpTypeStruct %10 +%11 = OpTypePointer Uniform %9 +%8 = OpVariable %11 Uniform +%13 = OpTypePointer Function %4 +%18 = OpTypeFunction %4 %4 +%25 = OpTypeBool +%44 = OpTypeVector %4 3 +%46 = OpTypePointer Input %44 +%45 = OpVariable %46 Input +%49 = OpTypeFunction %2 +%51 = OpTypePointer Uniform %10 %53 = OpTypePointer Uniform %4 -%56 = OpTypeInt 32 1 -%57 = OpConstant %56 0 -%61 = OpConstant %56 0 -%19 = OpFunction %4 None %20 -%18 = OpFunctionParameter %4 -%21 = OpLabel -%15 = OpVariable %16 Function -%17 = OpVariable %16 Function %3 +%55 = OpTypeInt 32 1 +%56 = OpConstant %55 0 +%60 = OpConstant %55 0 +%17 = OpFunction %4 None %18 +%16 = OpFunctionParameter %4 +%15 = OpLabel +%12 = OpVariable %13 Function +%14 = OpVariable %13 Function %3 +OpBranch %19 +%19 = OpLabel +OpStore %12 %16 +OpBranch %20 +%20 = OpLabel +OpLoopMerge %21 %23 None OpBranch %22 %22 = OpLabel -OpStore %15 %18 +%24 = OpLoad %4 %12 +%26 = OpULessThanEqual %25 %24 %5 +OpSelectionMerge %27 None +OpBranchConditional %26 %28 %27 +%28 = OpLabel +OpBranch %21 +%27 = OpLabel +%29 = OpLoad %4 %12 +%30 = OpUMod %4 %29 %6 +%31 = OpIEqual %25 %30 %3 +OpSelectionMerge %32 None +OpBranchConditional %31 %33 %34 +%33 = OpLabel +%35 = OpLoad %4 %12 +%36 = OpUDiv %4 %35 %6 +OpStore %12 %36 +OpBranch %32 +%34 = OpLabel +%37 = OpLoad %4 %12 +%38 = OpIMul %4 %7 %37 +%39 = OpIAdd %4 %38 %5 +OpStore %12 %39 +OpBranch %32 +%32 = OpLabel +%40 = OpLoad %4 %14 +%41 = OpIAdd %4 %40 %5 +OpStore %14 %41 OpBranch %23 %23 = OpLabel -OpLoopMerge %24 %26 None -OpBranch %25 -%25 = OpLabel -%27 = OpLoad %4 %15 -%29 = OpULessThanEqual %28 %27 %5 -OpSelectionMerge %30 None -OpBranchConditional %29 %31 %30 -%31 = OpLabel -OpBranch %24 -%30 = OpLabel -%32 = OpLoad %4 %15 -%33 = OpUMod %4 %32 %6 -%34 = OpIEqual %28 %33 %3 -OpSelectionMerge %35 None -OpBranchConditional %34 %36 %37 -%36 = OpLabel -%38 = OpLoad %4 %15 -%39 = OpUDiv %4 %38 %6 -OpStore %15 %39 -OpBranch %35 -%37 = OpLabel -%40 = OpLoad %4 %15 -%41 = OpIMul %4 %7 %40 -%42 = OpIAdd %4 %41 %5 -OpStore %15 %42 -OpBranch %35 -%35 = OpLabel -%43 = OpLoad %4 %17 -%44 = OpIAdd %4 %43 %5 -OpStore %17 %44 -OpBranch %26 -%26 = OpLabel -OpBranch %23 -%24 = OpLabel -%45 = OpLoad %4 %17 -OpReturnValue %45 +OpBranch %20 +%21 = OpLabel +%42 = OpLoad %4 %14 +OpReturnValue %42 OpFunctionEnd -%46 = OpFunction %2 None %47 -%48 = OpLabel -OpBranch %49 -%49 = OpLabel -%51 = OpLoad %9 %8 -%52 = OpCompositeExtract %4 %51 0 -%54 = OpLoad %9 %8 -%55 = OpCompositeExtract %4 %54 0 -%58 = OpAccessChain %53 %11 %57 %55 -%59 = OpLoad %4 %58 -%60 = OpFunctionCall %4 %19 %59 -%62 = OpAccessChain %53 %11 %61 %52 -OpStore %62 %60 +%48 = OpFunction %2 None %49 +%43 = OpLabel +%47 = OpLoad %44 %45 +OpBranch %50 +%50 = OpLabel +%52 = OpCompositeExtract %4 %47 0 +%54 = OpCompositeExtract %4 %47 0 +%57 = OpAccessChain %53 %8 %56 %54 +%58 = OpLoad %4 %57 +%59 = OpFunctionCall %4 %17 %58 +%61 = OpAccessChain %53 %8 %60 %52 +OpStore %61 %59 OpReturn OpFunctionEnd diff --git a/tests/out/empty-Compute.glsl.snap b/tests/out/empty-Compute.glsl.snap index 1ec91e280..4fbc229db 100644 --- a/tests/out/empty-Compute.glsl.snap +++ b/tests/out/empty-Compute.glsl.snap @@ -8,7 +8,9 @@ precision highp float; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + void main() { return; } + diff --git a/tests/out/empty.msl.snap b/tests/out/empty.msl.snap index 1372996b8..6cbbbb4bd 100644 --- a/tests/out/empty.msl.snap +++ b/tests/out/empty.msl.snap @@ -7,6 +7,6 @@ expression: msl kernel void main1( ) { - return ; + return; } diff --git a/tests/out/empty.spvasm.snap b/tests/out/empty.spvasm.snap index c26ec0c45..dabf551e5 100644 --- a/tests/out/empty.spvasm.snap +++ b/tests/out/empty.spvasm.snap @@ -9,15 +9,15 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %3 "main" -OpExecutionMode %3 LocalSize 1 1 1 +OpEntryPoint GLCompute %4 "main" +OpExecutionMode %4 LocalSize 1 1 1 OpSource GLSL 450 -OpName %3 "main" -OpName %3 "main" +OpName %4 "main" +OpName %4 "main" %2 = OpTypeVoid -%4 = OpTypeFunction %2 -%3 = OpFunction %2 None %4 -%5 = OpLabel +%5 = OpTypeFunction %2 +%4 = OpFunction %2 None %5 +%3 = OpLabel OpBranch %6 %6 = OpLabel OpReturn diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap index 7b875449f..8773ca4cc 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad-Fragment.glsl.snap @@ -6,18 +6,23 @@ expression: string precision highp float; -in vec2 _location_0_vs; +struct VertexOutput { + vec2 uv; + vec4 position; +}; uniform highp sampler2D _group_0_binding_0; -out vec4 _location_0; +in vec2 _in_location_0; +out vec4 _out_location_0; void main() { - vec4 _expr9 = texture(_group_0_binding_0, vec2(_location_0_vs)); - if((_expr9[3] == 0.0)) { + vec2 uv2 = _in_location_0; + vec4 _expr4 = texture(_group_0_binding_0, vec2(uv2)); + if((_expr4[3] == 0.0)) { discard; } - _location_0 = (_expr9[3] * _expr9); + _out_location_0 = (_expr4[3] * _expr4); return; } diff --git a/tests/out/quad-Vertex.glsl.snap b/tests/out/quad-Vertex.glsl.snap index badab76ce..c4d67cef9 100644 --- a/tests/out/quad-Vertex.glsl.snap +++ b/tests/out/quad-Vertex.glsl.snap @@ -6,14 +6,24 @@ expression: string precision highp float; -in vec2 _location_0; +struct VertexOutput { + vec2 uv; + vec4 position; +}; -in vec2 _location_1; - -out vec2 _location_0_vs; +in vec2 _in_location_0; +in vec2 _in_location_1; +out vec2 _out_location_0; void main() { - _location_0_vs = _location_1; - gl_Position = vec4((1.2 * _location_0), 0.0, 1.0); + vec2 pos = _in_location_0; + vec2 uv1 = _in_location_1; + VertexOutput out1; + out1.uv = uv1; + out1.position = vec4((1.2 * pos), 0.0, 1.0); + _out_location_0 = out1.uv; + gl_Position = out1.position; return; } + + diff --git a/tests/out/quad.dot.snap b/tests/out/quad.dot.snap index 333de1596..6a564fad2 100644 --- a/tests/out/quad.dot.snap +++ b/tests/out/quad.dot.snap @@ -5,95 +5,81 @@ expression: string digraph Module { subgraph cluster_globals { label="Globals" - g0 [ shape=hexagon label="[1] Input/'a_pos'" ] - g1 [ shape=hexagon label="[2] Input/'a_uv'" ] - g2 [ shape=hexagon label="[3] Output/'v_uv'" ] - g3 [ shape=hexagon label="[4] Output/'o_position'" ] - g4 [ shape=hexagon label="[5] Input/'v_uv'" ] - g5 [ shape=hexagon label="[6] Handle/'u_texture'" ] - g6 [ shape=hexagon label="[7] Handle/'u_sampler'" ] - g7 [ shape=hexagon label="[8] Output/'o_color'" ] + g0 [ shape=hexagon label="[1] Handle/'u_texture'" ] + g1 [ shape=hexagon label="[2] Handle/'u_sampler'" ] } subgraph cluster_ep0 { label="Vertex/'main'" node [ style=filled ] + ep0_l0 [ shape=hexagon label="[1] 'out'" ] ep0_e0 [ color="#ffffb3" label="[1] Constant" ] - ep0_e1 [ color="#ffffb3" label="[2] Global" ] - g0 -> ep0_e1 [color=gray] - ep0_e2 [ color="#ffffb3" label="[3] Global" ] - g2 -> ep0_e2 [color=gray] - ep0_e3 [ color="#ffffb3" label="[4] Global" ] - g3 -> ep0_e3 [color=gray] - ep0_e4 [ color="#ffffb3" label="[5] Global" ] - g1 -> ep0_e4 [color=gray] - ep0_e5 [ color="#fb8072" label="[6] Load" ] - ep0_e4 -> ep0_e5 [ label="pointer" ] - ep0_e6 [ color="#fb8072" label="[7] Load" ] - ep0_e1 -> ep0_e6 [ label="pointer" ] - ep0_e7 [ color="#fdb462" label="[8] Multiply" ] - ep0_e6 -> ep0_e7 [ label="right" ] - ep0_e0 -> ep0_e7 [ label="left" ] + ep0_e1 [ color="#8dd3c7" label="[2] Argument[0]" ] + ep0_e2 [ color="#8dd3c7" label="[3] Argument[1]" ] + ep0_e3 [ color="#8dd3c7" label="[4] Local" ] + ep0_l0 -> ep0_e3 + ep0_e4 [ color="#8dd3c7" label="[5] AccessIndex[0]" ] + ep0_e3 -> ep0_e4 [ label="base" ] + ep0_e5 [ color="#8dd3c7" label="[6] AccessIndex[1]" ] + ep0_e3 -> ep0_e5 [ label="base" ] + ep0_e6 [ color="#fdb462" label="[7] Multiply" ] + ep0_e1 -> ep0_e6 [ label="right" ] + ep0_e0 -> ep0_e6 [ label="left" ] + ep0_e7 [ color="#ffffb3" label="[8] Constant" ] ep0_e8 [ color="#ffffb3" label="[9] Constant" ] - ep0_e9 [ color="#ffffb3" label="[10] Constant" ] - ep0_e10 [ color="#bebada" label="[11] Compose" ] - { ep0_e7 ep0_e8 ep0_e9 } -> ep0_e10 + ep0_e9 [ color="#bebada" label="[10] Compose" ] + { ep0_e6 ep0_e7 ep0_e8 } -> ep0_e9 + ep0_e10 [ color="#fb8072" label="[11] Load" ] + ep0_e3 -> ep0_e10 [ label="pointer" ] ep0_s0 [ shape=square label="Root" ] ep0_s1 [ shape=square label="Emit" ] ep0_s2 [ shape=square label="Store" ] ep0_s3 [ shape=square label="Emit" ] ep0_s4 [ shape=square label="Emit" ] ep0_s5 [ shape=square label="Store" ] - ep0_s6 [ shape=square label="Return" ] + ep0_s6 [ shape=square label="Emit" ] + ep0_s7 [ shape=square label="Return" ] ep0_s0 -> ep0_s1 [ arrowhead=tee label="" ] ep0_s1 -> ep0_s2 [ arrowhead=tee label="" ] ep0_s2 -> ep0_s3 [ arrowhead=tee label="" ] ep0_s3 -> ep0_s4 [ arrowhead=tee label="" ] ep0_s4 -> ep0_s5 [ arrowhead=tee label="" ] ep0_s5 -> ep0_s6 [ arrowhead=tee label="" ] - ep0_e5 -> ep0_s2 [ label="value" ] - ep0_e10 -> ep0_s5 [ label="value" ] - ep0_s1 -> ep0_e5 [ style=dotted ] - ep0_s2 -> ep0_e2 [ style=dotted ] + ep0_s6 -> ep0_s7 [ arrowhead=tee label="" ] + ep0_e2 -> ep0_s2 [ label="value" ] + ep0_e9 -> ep0_s5 [ label="value" ] + ep0_e10 -> ep0_s7 [ label="value" ] + ep0_s1 -> ep0_e4 [ style=dotted ] + ep0_s2 -> ep0_e4 [ style=dotted ] + ep0_s3 -> ep0_e5 [ style=dotted ] ep0_s3 -> ep0_e6 [ style=dotted ] - ep0_s3 -> ep0_e7 [ style=dotted ] - ep0_s4 -> ep0_e10 [ style=dotted ] - ep0_s5 -> ep0_e3 [ style=dotted ] + ep0_s4 -> ep0_e9 [ style=dotted ] + ep0_s5 -> ep0_e5 [ style=dotted ] + ep0_s6 -> ep0_e10 [ style=dotted ] } subgraph cluster_ep1 { label="Fragment/'main'" node [ style=filled ] - ep1_e0 [ color="#ffffb3" label="[1] Global" ] - g3 -> ep1_e0 [color=gray] + ep1_e0 [ color="#ffffb3" label="[1] Constant" ] ep1_e1 [ color="#ffffb3" label="[2] Global" ] - g6 -> ep1_e1 [color=gray] + g1 -> ep1_e1 [color=gray] ep1_e2 [ color="#ffffb3" label="[3] Global" ] - g5 -> ep1_e2 [color=gray] - ep1_e3 [ color="#ffffb3" label="[4] Constant" ] - ep1_e4 [ color="#ffffb3" label="[5] Global" ] - g0 -> ep1_e4 [color=gray] - ep1_e5 [ color="#ffffb3" label="[6] Global" ] - g4 -> ep1_e5 [color=gray] - ep1_e6 [ color="#ffffb3" label="[7] Global" ] - g1 -> ep1_e6 [color=gray] - ep1_e7 [ color="#ffffb3" label="[8] Global" ] - g7 -> ep1_e7 [color=gray] - ep1_e8 [ color="#fb8072" label="[9] Load" ] - ep1_e5 -> ep1_e8 [ label="pointer" ] - ep1_e9 [ color="#80b1d3" label="[10] ImageSample" ] - ep1_e1 -> ep1_e9 [ label="sampler" ] - ep1_e2 -> ep1_e9 [ label="image" ] - ep1_e8 -> ep1_e9 [ label="coordinate" ] - ep1_e10 [ color="#8dd3c7" label="[11] AccessIndex[3]" ] - ep1_e9 -> ep1_e10 [ label="base" ] - ep1_e11 [ color="#ffffb3" label="[12] Constant" ] - ep1_e12 [ color="#fdb462" label="[13] Equal" ] - ep1_e11 -> ep1_e12 [ label="right" ] - ep1_e10 -> ep1_e12 [ label="left" ] - ep1_e13 [ color="#8dd3c7" label="[14] AccessIndex[3]" ] - ep1_e9 -> ep1_e13 [ label="base" ] - ep1_e14 [ color="#fdb462" label="[15] Multiply" ] - ep1_e9 -> ep1_e14 [ label="right" ] - ep1_e13 -> ep1_e14 [ label="left" ] + g0 -> ep1_e2 [color=gray] + ep1_e3 [ color="#8dd3c7" label="[4] Argument[0]" ] + ep1_e4 [ color="#80b1d3" label="[5] ImageSample" ] + ep1_e1 -> ep1_e4 [ label="sampler" ] + ep1_e2 -> ep1_e4 [ label="image" ] + ep1_e3 -> ep1_e4 [ label="coordinate" ] + ep1_e5 [ color="#8dd3c7" label="[6] AccessIndex[3]" ] + ep1_e4 -> ep1_e5 [ label="base" ] + ep1_e6 [ color="#ffffb3" label="[7] Constant" ] + ep1_e7 [ color="#fdb462" label="[8] Equal" ] + ep1_e6 -> ep1_e7 [ label="right" ] + ep1_e5 -> ep1_e7 [ label="left" ] + ep1_e8 [ color="#8dd3c7" label="[9] AccessIndex[3]" ] + ep1_e4 -> ep1_e8 [ label="base" ] + ep1_e9 [ color="#fdb462" label="[10] Multiply" ] + ep1_e4 -> ep1_e9 [ label="right" ] + ep1_e8 -> ep1_e9 [ label="left" ] ep1_s0 [ shape=square label="Root" ] ep1_s1 [ shape=square label="Emit" ] ep1_s2 [ shape=square label="Emit" ] @@ -103,8 +89,7 @@ digraph Module { ep1_s6 [ shape=square label="Kill" ] ep1_s7 [ shape=square label="Node" ] ep1_s8 [ shape=square label="Emit" ] - ep1_s9 [ shape=square label="Store" ] - ep1_s10 [ shape=square label="Return" ] + ep1_s9 [ shape=square label="Return" ] ep1_s0 -> ep1_s1 [ arrowhead=tee label="" ] ep1_s1 -> ep1_s2 [ arrowhead=tee label="" ] ep1_s2 -> ep1_s3 [ arrowhead=tee label="" ] @@ -114,16 +99,13 @@ digraph Module { ep1_s4 -> ep1_s7 [ arrowhead=tee label="reject" ] ep1_s7 -> ep1_s8 [ arrowhead=tee label="" ] ep1_s8 -> ep1_s9 [ arrowhead=tee label="" ] - ep1_s9 -> ep1_s10 [ arrowhead=tee label="" ] - ep1_e12 -> ep1_s4 [ label="condition" ] - ep1_e14 -> ep1_s9 [ label="value" ] - ep1_s1 -> ep1_e8 [ style=dotted ] - ep1_s1 -> ep1_e9 [ style=dotted ] - ep1_s2 -> ep1_e10 [ style=dotted ] - ep1_s3 -> ep1_e12 [ style=dotted ] - ep1_s8 -> ep1_e13 [ style=dotted ] - ep1_s8 -> ep1_e14 [ style=dotted ] - ep1_s9 -> ep1_e7 [ style=dotted ] + ep1_e7 -> ep1_s4 [ label="condition" ] + ep1_e9 -> ep1_s9 [ label="value" ] + ep1_s1 -> ep1_e4 [ style=dotted ] + ep1_s2 -> ep1_e5 [ style=dotted ] + ep1_s3 -> ep1_e7 [ style=dotted ] + ep1_s8 -> ep1_e8 [ style=dotted ] + ep1_s8 -> ep1_e9 [ style=dotted ] } } diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index 35424fe75..32d695f2f 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -11,6 +11,11 @@ typedef metal::float2 type1; typedef metal::float4 type2; +struct VertexOutput { + type1 uv; + type2 position; +}; + typedef metal::texture2d type3; typedef metal::sampler type4; @@ -19,43 +24,41 @@ constexpr constant float c_scale = 1.2; constexpr constant float const_0f = 0.0; constexpr constant float const_1f = 1.0; struct main1Input { - type1 a_pos [[attribute(0)]]; - type1 a_uv [[attribute(1)]]; + type1 pos [[attribute(0)]]; + type1 uv1 [[attribute(1)]]; }; - struct main1Output { - type1 v_uv [[user(loc0)]]; - type2 o_position [[position]]; + type1 uv [[user(loc0)]]; + type2 position [[position]]; }; - vertex main1Output main1( - main1Input input [[stage_in]] + main1Input varyings [[stage_in]] ) { - main1Output output; - output.v_uv = input.a_uv; - output.o_position = metal::float4((c_scale * input.a_pos), const_0f, const_1f); - return output; + const auto pos = varyings.pos; + const auto uv1 = varyings.uv1; + VertexOutput out; + out.uv = uv1; + out.position = metal::float4((c_scale * pos), const_0f, const_1f); + const auto _tmp = out; + return main1Output { _tmp.uv, _tmp.position }; } struct main2Input { - type1 v_uv1 [[user(loc0)]]; + type1 uv2 [[user(loc0)]]; }; - struct main2Output { - type2 o_color [[color(0)]]; + type2 member1 [[color(0)]]; }; - fragment main2Output main2( - main2Input input [[stage_in]], - type3 u_texture [[texture(0)]], - type4 u_sampler [[sampler(0)]] + main2Input varyings1 [[stage_in]] +, type3 u_texture [[texture(0)]] +, type4 u_sampler [[sampler(0)]] ) { - main2Output output; - metal::float4 _expr9 = u_texture.sample(u_sampler, input.v_uv1); - if ((_expr9.w == const_0f)) { + const auto uv2 = varyings1.uv2; + metal::float4 _expr4 = u_texture.sample(u_sampler, uv2); + if ((_expr4.w == const_0f)) { metal::discard_fragment(); } - output.o_color = (_expr9.w * _expr9); - return output; + return main2Output { (_expr4.w * _expr4) }; } diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index 8aadbe5f9..c3a3ff351 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -5,92 +5,108 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 48 +; Bound: 61 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %24 "main" %7 %10 %11 %13 -OpEntryPoint Fragment %32 "main" %16 %23 -OpExecutionMode %32 OriginUpperLeft +OpEntryPoint Vertex %28 "main" %19 %22 %24 %26 +OpEntryPoint Fragment %47 "main" %44 %46 +OpExecutionMode %47 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" -OpName %7 "a_pos" -OpName %10 "a_uv" -OpName %11 "v_uv" -OpName %13 "o_position" -OpName %16 "v_uv" -OpName %17 "u_texture" -OpName %20 "u_sampler" -OpName %23 "o_color" -OpName %24 "main" -OpName %24 "main" -OpName %32 "main" -OpName %32 "main" -OpDecorate %7 Location 0 -OpDecorate %10 Location 1 -OpDecorate %11 Location 0 -OpDecorate %13 BuiltIn Position -OpDecorate %16 Location 0 -OpDecorate %17 DescriptorSet 0 -OpDecorate %17 Binding 0 -OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 1 -OpDecorate %23 Location 0 +OpName %7 "u_texture" +OpName %10 "u_sampler" +OpName %13 "out" +OpName %14 "VertexOutput" +OpName %19 "pos" +OpName %22 "uv" +OpName %24 "uv" +OpName %26 "position" +OpName %28 "main" +OpName %28 "main" +OpName %44 "uv" +OpName %47 "main" +OpName %47 "main" +OpDecorate %7 DescriptorSet 0 +OpDecorate %7 Binding 0 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 1 +OpDecorate %19 Location 0 +OpDecorate %22 Location 1 +OpDecorate %24 Location 0 +OpDecorate %26 BuiltIn Position +OpDecorate %44 Location 0 +OpDecorate %46 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.2 %5 = OpConstant %4 0.0 %6 = OpConstant %4 1.0 -%8 = OpTypeVector %4 2 -%9 = OpTypePointer Input %8 -%7 = OpVariable %9 Input -%10 = OpVariable %9 Input -%12 = OpTypePointer Output %8 -%11 = OpVariable %12 Output -%14 = OpTypeVector %4 4 -%15 = OpTypePointer Output %14 -%13 = OpVariable %15 Output -%16 = OpVariable %9 Input -%18 = OpTypeImage %4 2D 0 0 0 1 Unknown -%19 = OpTypePointer UniformConstant %18 -%17 = OpVariable %19 UniformConstant -%21 = OpTypeSampler -%22 = OpTypePointer UniformConstant %21 -%20 = OpVariable %22 UniformConstant -%23 = OpVariable %15 Output -%25 = OpTypeFunction %2 -%38 = OpTypeSampledImage %18 -%42 = OpTypeBool -%24 = OpFunction %2 None %25 -%26 = OpLabel -OpBranch %27 -%27 = OpLabel -%28 = OpLoad %8 %10 -OpStore %11 %28 -%29 = OpLoad %8 %7 -%30 = OpVectorTimesScalar %8 %29 %3 -%31 = OpCompositeConstruct %14 %30 %5 %6 -OpStore %13 %31 +%8 = OpTypeImage %4 2D 0 0 0 1 Unknown +%9 = OpTypePointer UniformConstant %8 +%7 = OpVariable %9 UniformConstant +%11 = OpTypeSampler +%12 = OpTypePointer UniformConstant %11 +%10 = OpVariable %12 UniformConstant +%15 = OpTypeVector %4 2 +%16 = OpTypeVector %4 4 +%14 = OpTypeStruct %15 %16 +%17 = OpTypePointer Function %14 +%20 = OpTypePointer Input %15 +%19 = OpVariable %20 Input +%22 = OpVariable %20 Input +%25 = OpTypePointer Output %15 +%24 = OpVariable %25 Output +%27 = OpTypePointer Output %16 +%26 = OpVariable %27 Output +%29 = OpTypeFunction %2 +%31 = OpTypePointer Function %15 +%32 = OpTypeInt 32 1 +%33 = OpConstant %32 0 +%35 = OpTypePointer Function %16 +%38 = OpConstant %32 1 +%44 = OpVariable %20 Input +%46 = OpVariable %27 Output +%51 = OpTypeSampledImage %8 +%55 = OpTypeBool +%28 = OpFunction %2 None %29 +%18 = OpLabel +%13 = OpVariable %17 Function +%21 = OpLoad %15 %19 +%23 = OpLoad %15 %22 +OpBranch %30 +%30 = OpLabel +%34 = OpAccessChain %31 %13 %33 +OpStore %34 %23 +%36 = OpVectorTimesScalar %15 %21 %3 +%37 = OpCompositeConstruct %16 %36 %5 %6 +%39 = OpAccessChain %35 %13 %38 +OpStore %39 %37 +%40 = OpLoad %14 %13 +%41 = OpCompositeExtract %15 %40 0 +OpStore %24 %41 +%42 = OpCompositeExtract %16 %40 1 +OpStore %26 %42 OpReturn OpFunctionEnd -%32 = OpFunction %2 None %25 -%33 = OpLabel -%34 = OpLoad %18 %17 -%35 = OpLoad %21 %20 -OpBranch %36 -%36 = OpLabel -%37 = OpLoad %8 %16 -%39 = OpSampledImage %38 %34 %35 -%40 = OpImageSampleImplicitLod %14 %39 %37 -%41 = OpCompositeExtract %4 %40 3 -%43 = OpFOrdEqual %42 %41 %5 -OpSelectionMerge %44 None -OpBranchConditional %43 %45 %44 -%45 = OpLabel +%47 = OpFunction %2 None %29 +%43 = OpLabel +%45 = OpLoad %15 %44 +%48 = OpLoad %8 %7 +%49 = OpLoad %11 %10 +OpBranch %50 +%50 = OpLabel +%52 = OpSampledImage %51 %48 %49 +%53 = OpImageSampleImplicitLod %16 %52 %45 +%54 = OpCompositeExtract %4 %53 3 +%56 = OpFOrdEqual %55 %54 %5 +OpSelectionMerge %57 None +OpBranchConditional %56 %58 %57 +%58 = OpLabel OpKill -%44 = OpLabel -%46 = OpCompositeExtract %4 %40 3 -%47 = OpVectorTimesScalar %14 %40 %46 -OpStore %23 %47 +%57 = OpLabel +%59 = OpCompositeExtract %4 %53 3 +%60 = OpVectorTimesScalar %16 %53 %59 +OpStore %46 %60 OpReturn OpFunctionEnd diff --git a/tests/out/shadow-Fragment.glsl.snap b/tests/out/shadow-Fragment.glsl.snap index df8300b46..fa0739596 100644 --- a/tests/out/shadow-Fragment.glsl.snap +++ b/tests/out/shadow-Fragment.glsl.snap @@ -22,11 +22,9 @@ readonly buffer Lights_block_1 { uniform highp sampler2DArrayShadow _group_0_binding_2; -in vec3 _location_0_vs; - -in vec4 _location_1_vs; - -out vec4 _location_0; +in vec3 _in_location_0; +in vec4 _in_location_1; +out vec4 _out_location_0; float fetch_shadow(uint light_id, vec4 homogeneous_coords) { if((homogeneous_coords[3] <= 0.0)) { @@ -38,19 +36,20 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } void main() { + vec3 raw_normal = _in_location_0; + vec4 position = _in_location_1; vec3 color1 = vec3(0.05, 0.05, 0.05); uint i = 0u; while(true) { if((i >= min(_group_0_binding_0.num_lights[0], 10u))) { break; } - Light _expr23 = _group_0_binding_1.data[i]; - float _expr28 = fetch_shadow(i, (_expr23.proj * _location_1_vs)); - vec4 _expr34 = _location_1_vs; - color1 = (color1 + ((_expr28 * max(0.0, dot(normalize(_location_0_vs), normalize((vec3(_expr23.pos[0], _expr23.pos[1], _expr23.pos[2]) - vec3(_expr34[0], _expr34[1], _expr34[2])))))) * vec3(_expr23.color[0], _expr23.color[1], _expr23.color[2]))); + Light _expr21 = _group_0_binding_1.data[i]; + float _expr25 = fetch_shadow(i, (_expr21.proj * position)); + color1 = (color1 + ((_expr25 * max(0.0, dot(normalize(raw_normal), normalize((vec3(_expr21.pos[0], _expr21.pos[1], _expr21.pos[2]) - vec3(position[0], position[1], position[2])))))) * vec3(_expr21.color[0], _expr21.color[1], _expr21.color[2]))); i = (i + 1u); } - _location_0 = vec4(color1, 1.0); + _out_location_0 = vec4(color1, 1.0); return; } diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 08924616f..91998563b 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -610,8 +610,6 @@ expression: output ), ], ), - ], - entry_points: [ ( uniformity: ( non_uniform_result: Some(44), @@ -1595,4 +1593,92 @@ expression: output ], ), ], + entry_points: [ + ( + uniformity: ( + non_uniform_result: Some(44), + requirement: None, + ), + may_kill: false, + sampling_set: [ + ( + image: 1, + sampler: 2, + ), + ], + global_uses: [ + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 3, + ), + ( + bits: 3, + ), + ( + bits: 3, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirement: None, + ), + ref_count: 1, + assignable_global: Some(6), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirement: None, + ), + ref_count: 1, + assignable_global: None, + ), + ( + uniformity: ( + non_uniform_result: Some(3), + requirement: None, + ), + ref_count: 1, + assignable_global: Some(5), + ), + ( + uniformity: ( + non_uniform_result: Some(4), + requirement: None, + ), + ref_count: 1, + assignable_global: None, + ), + ( + uniformity: ( + non_uniform_result: Some(5), + requirement: None, + ), + ref_count: 1, + assignable_global: Some(7), + ), + ( + uniformity: ( + non_uniform_result: Some(5), + requirement: None, + ), + ref_count: 1, + assignable_global: None, + ), + ], + ), + ], ) diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 6cc1a509d..4d3963439 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -63,22 +63,21 @@ type7 fetch_shadow( } struct fs_mainInput { - type9 in_normal_fs [[user(loc0)]]; - type2 in_position_fs [[user(loc1)]]; + type9 raw_normal [[user(loc0)]]; + type2 position [[user(loc1)]]; }; - struct fs_mainOutput { - type2 out_color_fs [[color(0)]]; + type2 member [[color(0)]]; }; - fragment fs_mainOutput fs_main( - fs_mainInput input [[stage_in]], - constant Globals& u_globals [[buffer(0)]], - constant Lights& s_lights [[buffer(1)]], - type4 t_shadow [[texture(0)]], - type5 sampler_shadow [[sampler(0)]] + fs_mainInput varyings [[stage_in]] +, constant Globals& u_globals [[buffer(0)]] +, constant Lights& s_lights [[buffer(1)]] +, type4 t_shadow [[texture(0)]] +, type5 sampler_shadow [[sampler(0)]] ) { - fs_mainOutput output; + const auto raw_normal = varyings.raw_normal; + const auto position = varyings.position; type9 color1 = c_ambient; type6 i = const_0u; bool loop_init = true; @@ -90,12 +89,10 @@ fragment fs_mainOutput fs_main( if ((i >= metal::min(u_globals.num_lights.x, c_max_lights))) { break; } - Light _expr23 = s_lights.data[i]; - type7 _expr28 = fetch_shadow(i, (_expr23.proj * input.in_position_fs), t_shadow, sampler_shadow); - type2 _expr34 = input.in_position_fs; - color1 = (color1 + ((_expr28 * metal::max(const_0f, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(_expr23.pos.x, _expr23.pos.y, _expr23.pos.z) - metal::float3(_expr34.x, _expr34.y, _expr34.z)))))) * metal::float3(_expr23.color.x, _expr23.color.y, _expr23.color.z))); + Light _expr21 = s_lights.data[i]; + type7 _expr25 = fetch_shadow(i, (_expr21.proj * position), t_shadow, sampler_shadow); + color1 = (color1 + ((_expr25 * metal::max(const_0f, metal::dot(metal::normalize(raw_normal), metal::normalize((metal::float3(_expr21.pos.x, _expr21.pos.y, _expr21.pos.z) - metal::float3(position.x, position.y, position.z)))))) * metal::float3(_expr21.color.x, _expr21.color.y, _expr21.color.z))); } - output.out_color_fs = metal::float4(color1, const_1f); - return output; + return fs_mainOutput { metal::float4(color1, const_1f) }; } diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index d9ddcc910..e1276ca7b 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -112,6 +112,7 @@ expression: output name: Some("num_lights"), span: None, ty: 13, + binding: None, ), ], ), @@ -154,16 +155,19 @@ expression: output name: Some("proj"), span: None, ty: 18, + binding: None, ), ( name: Some("pos"), span: None, ty: 4, + binding: None, ), ( name: Some("color"), span: None, ty: 4, + binding: None, ), ], ), @@ -185,6 +189,7 @@ expression: output name: Some("data"), span: None, ty: 20, + binding: None, ), ], ), @@ -221,14 +226,14 @@ expression: output name: None, inner: Pointer( base: 4, - class: Input, + class: Private, ), ), ( name: None, inner: Pointer( base: 2, - class: Input, + class: Private, ), ), ( @@ -319,21 +324,21 @@ expression: output name: None, inner: Pointer( base: 1, - class: Input, + class: Private, ), ), ( name: None, inner: Pointer( base: 1, - class: Input, + class: Private, ), ), ( name: None, inner: Pointer( base: 1, - class: Input, + class: Private, ), ), ( @@ -424,7 +429,7 @@ expression: output name: None, inner: Pointer( base: 4, - class: Output, + class: Private, ), ), ( @@ -764,13 +769,12 @@ expression: output ( name: Some("t_shadow"), class: Handle, - binding: Some(Resource( + binding: Some(( group: 0, binding: 2, )), ty: 56, init: None, - interpolation: None, storage_access: ( bits: 0, ), @@ -778,13 +782,12 @@ expression: output ( name: Some("sampler_shadow"), class: Handle, - binding: Some(Resource( + binding: Some(( group: 0, binding: 3, )), ty: 57, init: None, - interpolation: None, storage_access: ( bits: 0, ), @@ -792,13 +795,12 @@ expression: output ( name: Some("u_globals"), class: Uniform, - binding: Some(Resource( + binding: Some(( group: 0, binding: 0, )), ty: 14, init: None, - interpolation: None, storage_access: ( bits: 0, ), @@ -806,46 +808,42 @@ expression: output ( name: Some("s_lights"), class: Storage, - binding: Some(Resource( + binding: Some(( group: 0, binding: 1, )), ty: 21, init: None, - interpolation: None, storage_access: ( bits: 1, ), ), ( name: Some("in_position_fs"), - class: Input, - binding: Some(Location(1)), + class: Private, + binding: None, ty: 4, init: None, - interpolation: None, storage_access: ( bits: 0, ), ), ( name: Some("in_normal_fs"), - class: Input, - binding: Some(Location(0)), + class: Private, + binding: None, ty: 2, init: None, - interpolation: None, storage_access: ( bits: 0, ), ), ( name: Some("out_color_fs"), - class: Output, - binding: Some(Location(0)), + class: Private, + binding: None, ty: 4, init: None, - interpolation: None, storage_access: ( bits: 0, ), @@ -858,13 +856,18 @@ expression: output ( name: None, ty: 3, + binding: None, ), ( name: None, ty: 4, + binding: None, ), ], - return_type: Some(1), + result: Some(( + ty: 1, + binding: None, + )), local_variables: [], expressions: [ GlobalVariable(3), @@ -1074,6 +1077,427 @@ expression: output ), ], ), + ( + name: Some("fs_main"), + arguments: [], + result: None, + local_variables: [ + ( + name: Some("color"), + ty: 2, + init: Some(10), + ), + ( + name: Some("i"), + ty: 3, + init: Some(12), + ), + ], + expressions: [ + GlobalVariable(3), + GlobalVariable(6), + GlobalVariable(5), + GlobalVariable(1), + GlobalVariable(2), + GlobalVariable(4), + GlobalVariable(7), + Constant(20), + Constant(7), + Constant(33), + Constant(31), + Constant(29), + Constant(27), + Constant(25), + Constant(15), + Constant(12), + Constant(23), + Constant(8), + Constant(36), + Constant(34), + Constant(14), + Constant(32), + Constant(30), + Constant(17), + Constant(26), + Constant(39), + Constant(13), + Constant(11), + Constant(9), + Constant(6), + Constant(21), + Constant(35), + Constant(19), + Constant(37), + Constant(18), + Constant(28), + Constant(16), + Constant(24), + Constant(38), + Constant(22), + Constant(10), + Constant(5), + LocalVariable(1), + LocalVariable(2), + Load( + pointer: 44, + ), + AccessIndex( + base: 1, + index: 0, + ), + Access( + base: 46, + index: 37, + ), + Load( + pointer: 47, + ), + Math( + fun: Min, + arg: 48, + arg1: Some(28), + arg2: None, + ), + Binary( + op: GreaterEqual, + left: 45, + right: 49, + ), + Load( + pointer: 43, + ), + Load( + pointer: 44, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( + base: 53, + index: 54, + ), + AccessIndex( + base: 55, + index: 0, + ), + Load( + pointer: 56, + ), + Load( + pointer: 3, + ), + Binary( + op: Multiply, + left: 57, + right: 58, + ), + Call(1), + Load( + pointer: 2, + ), + Math( + fun: Normalize, + arg: 61, + arg1: None, + arg2: None, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( + base: 63, + index: 64, + ), + AccessIndex( + base: 65, + index: 1, + ), + Access( + base: 66, + index: 31, + ), + Load( + pointer: 67, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( + base: 69, + index: 70, + ), + AccessIndex( + base: 71, + index: 1, + ), + Access( + base: 72, + index: 38, + ), + Load( + pointer: 73, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( + base: 75, + index: 76, + ), + AccessIndex( + base: 77, + index: 1, + ), + Access( + base: 78, + index: 13, + ), + Load( + pointer: 79, + ), + Compose( + ty: 2, + components: [ + 68, + 74, + 80, + ], + ), + Access( + base: 3, + index: 36, + ), + Load( + pointer: 82, + ), + Access( + base: 3, + index: 12, + ), + Load( + pointer: 84, + ), + Access( + base: 3, + index: 23, + ), + Load( + pointer: 86, + ), + Compose( + ty: 2, + components: [ + 83, + 85, + 87, + ], + ), + Binary( + op: Subtract, + left: 81, + right: 88, + ), + Math( + fun: Normalize, + arg: 89, + arg1: None, + arg2: None, + ), + Math( + fun: Dot, + arg: 62, + arg1: Some(90), + arg2: None, + ), + Math( + fun: Max, + arg: 42, + arg1: Some(91), + arg2: None, + ), + Binary( + op: Multiply, + left: 60, + right: 92, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( + base: 94, + index: 95, + ), + AccessIndex( + base: 96, + index: 2, + ), + Access( + base: 97, + index: 10, + ), + Load( + pointer: 98, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( + base: 100, + index: 101, + ), + AccessIndex( + base: 102, + index: 2, + ), + Access( + base: 103, + index: 19, + ), + Load( + pointer: 104, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( + base: 106, + index: 107, + ), + AccessIndex( + base: 108, + index: 2, + ), + Access( + base: 109, + index: 26, + ), + Load( + pointer: 110, + ), + Compose( + ty: 2, + components: [ + 99, + 105, + 111, + ], + ), + Binary( + op: Multiply, + left: 112, + right: 93, + ), + Binary( + op: Add, + left: 51, + right: 113, + ), + Load( + pointer: 44, + ), + Binary( + op: Add, + left: 115, + right: 27, + ), + Load( + pointer: 43, + ), + Compose( + ty: 4, + components: [ + 117, + 30, + ], + ), + ], + body: [ + Loop( + body: [ + Emit(( + start: 44, + end: 50, + )), + If( + condition: 50, + accept: [ + Break, + ], + reject: [], + ), + Emit(( + start: 50, + end: 59, + )), + Call( + function: 1, + arguments: [ + 52, + 59, + ], + result: Some(60), + ), + Emit(( + start: 60, + end: 114, + )), + Store( + pointer: 43, + value: 114, + ), + ], + continuing: [ + Emit(( + start: 114, + end: 116, + )), + Store( + pointer: 44, + value: 116, + ), + ], + ), + Emit(( + start: 116, + end: 118, + )), + Store( + pointer: 7, + value: 118, + ), + Return( + value: None, + ), + ], + ), ], entry_points: [ ( @@ -1082,423 +1506,54 @@ expression: output early_depth_test: None, workgroup_size: (0, 0, 0), function: ( - name: Some("fs_main"), - arguments: [], - return_type: None, - local_variables: [ + name: None, + arguments: [ ( - name: Some("color"), + name: Some("in_normal_fs"), ty: 2, - init: Some(10), + binding: Some(Location(0, Some(Perspective))), ), ( - name: Some("i"), - ty: 3, - init: Some(12), + name: Some("in_position_fs"), + ty: 4, + binding: Some(Location(1, Some(Perspective))), ), ], + result: Some(( + ty: 4, + binding: Some(Location(0, None)), + )), + local_variables: [], expressions: [ - GlobalVariable(3), GlobalVariable(6), + FunctionArgument(0), GlobalVariable(5), - GlobalVariable(1), - GlobalVariable(2), - GlobalVariable(4), + FunctionArgument(1), GlobalVariable(7), - Constant(20), - Constant(7), - Constant(33), - Constant(31), - Constant(29), - Constant(27), - Constant(25), - Constant(15), - Constant(12), - Constant(23), - Constant(8), - Constant(36), - Constant(34), - Constant(14), - Constant(32), - Constant(30), - Constant(17), - Constant(26), - Constant(39), - Constant(13), - Constant(11), - Constant(9), - Constant(6), - Constant(21), - Constant(35), - Constant(19), - Constant(37), - Constant(18), - Constant(28), - Constant(16), - Constant(24), - Constant(38), - Constant(22), - Constant(10), - Constant(5), - LocalVariable(1), - LocalVariable(2), Load( - pointer: 44, - ), - AccessIndex( - base: 1, - index: 0, - ), - Access( - base: 46, - index: 37, - ), - Load( - pointer: 47, - ), - Math( - fun: Min, - arg: 48, - arg1: Some(28), - arg2: None, - ), - Binary( - op: GreaterEqual, - left: 45, - right: 49, - ), - Load( - pointer: 43, - ), - Load( - pointer: 44, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 44, - ), - Access( - base: 53, - index: 54, - ), - AccessIndex( - base: 55, - index: 0, - ), - Load( - pointer: 56, - ), - Load( - pointer: 3, - ), - Binary( - op: Multiply, - left: 57, - right: 58, - ), - Call(1), - Load( - pointer: 2, - ), - Math( - fun: Normalize, - arg: 61, - arg1: None, - arg2: None, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 44, - ), - Access( - base: 63, - index: 64, - ), - AccessIndex( - base: 65, - index: 1, - ), - Access( - base: 66, - index: 31, - ), - Load( - pointer: 67, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 44, - ), - Access( - base: 69, - index: 70, - ), - AccessIndex( - base: 71, - index: 1, - ), - Access( - base: 72, - index: 38, - ), - Load( - pointer: 73, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 44, - ), - Access( - base: 75, - index: 76, - ), - AccessIndex( - base: 77, - index: 1, - ), - Access( - base: 78, - index: 13, - ), - Load( - pointer: 79, - ), - Compose( - ty: 2, - components: [ - 68, - 74, - 80, - ], - ), - Access( - base: 3, - index: 36, - ), - Load( - pointer: 82, - ), - Access( - base: 3, - index: 12, - ), - Load( - pointer: 84, - ), - Access( - base: 3, - index: 23, - ), - Load( - pointer: 86, - ), - Compose( - ty: 2, - components: [ - 83, - 85, - 87, - ], - ), - Binary( - op: Subtract, - left: 81, - right: 88, - ), - Math( - fun: Normalize, - arg: 89, - arg1: None, - arg2: None, - ), - Math( - fun: Dot, - arg: 62, - arg1: Some(90), - arg2: None, - ), - Math( - fun: Max, - arg: 42, - arg1: Some(91), - arg2: None, - ), - Binary( - op: Multiply, - left: 60, - right: 92, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 44, - ), - Access( - base: 94, - index: 95, - ), - AccessIndex( - base: 96, - index: 2, - ), - Access( - base: 97, - index: 10, - ), - Load( - pointer: 98, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 44, - ), - Access( - base: 100, - index: 101, - ), - AccessIndex( - base: 102, - index: 2, - ), - Access( - base: 103, - index: 19, - ), - Load( - pointer: 104, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 44, - ), - Access( - base: 106, - index: 107, - ), - AccessIndex( - base: 108, - index: 2, - ), - Access( - base: 109, - index: 26, - ), - Load( - pointer: 110, - ), - Compose( - ty: 2, - components: [ - 99, - 105, - 111, - ], - ), - Binary( - op: Multiply, - left: 112, - right: 93, - ), - Binary( - op: Add, - left: 51, - right: 113, - ), - Load( - pointer: 44, - ), - Binary( - op: Add, - left: 115, - right: 27, - ), - Load( - pointer: 43, - ), - Compose( - ty: 4, - components: [ - 117, - 30, - ], + pointer: 5, ), ], body: [ - Loop( - body: [ - Emit(( - start: 44, - end: 50, - )), - If( - condition: 50, - accept: [ - Break, - ], - reject: [], - ), - Emit(( - start: 50, - end: 59, - )), - Call( - function: 1, - arguments: [ - 52, - 59, - ], - result: Some(60), - ), - Emit(( - start: 60, - end: 114, - )), - Store( - pointer: 43, - value: 114, - ), - ], - continuing: [ - Emit(( - start: 114, - end: 116, - )), - Store( - pointer: 44, - value: 116, - ), - ], + Store( + pointer: 1, + value: 2, + ), + Store( + pointer: 3, + value: 4, + ), + Call( + function: 2, + arguments: [], + result: None, ), Emit(( - start: 116, - end: 118, + start: 5, + end: 6, )), - Store( - pointer: 7, - value: 118, - ), Return( - value: None, + value: Some(6), ), ], ), diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index fb143031c..c4138feb3 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -5,12 +5,12 @@ expression: dis ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 138 +; Bound: 137 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %78 "fs_main" %32 %34 %36 -OpExecutionMode %78 OriginUpperLeft +OpEntryPoint Fragment %81 "fs_main" %73 %76 %79 +OpExecutionMode %81 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_ambient" OpName %11 "c_max_lights" @@ -26,14 +26,13 @@ OpMemberName %22 2 "color" OpName %19 "s_lights" OpName %26 "t_shadow" OpName %29 "sampler_shadow" -OpName %32 "in_normal_fs" -OpName %34 "in_position_fs" -OpName %36 "out_color_fs" -OpName %40 "fetch_shadow" -OpName %74 "color" -OpName %76 "i" -OpName %78 "fs_main" -OpName %78 "fs_main" +OpName %35 "fetch_shadow" +OpName %68 "color" +OpName %70 "i" +OpName %73 "raw_normal" +OpName %76 "position" +OpName %81 "fs_main" +OpName %81 "fs_main" OpDecorate %16 Block OpMemberDecorate %16 0 Offset 0 OpDecorate %15 DescriptorSet 0 @@ -53,9 +52,9 @@ OpDecorate %26 DescriptorSet 0 OpDecorate %26 Binding 2 OpDecorate %29 DescriptorSet 0 OpDecorate %29 Binding 3 -OpDecorate %32 Location 0 -OpDecorate %34 Location 1 -OpDecorate %36 Location 0 +OpDecorate %73 Location 0 +OpDecorate %76 Location 1 +OpDecorate %79 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 @@ -86,129 +85,128 @@ OpDecorate %36 Location 0 %30 = OpTypeSampler %31 = OpTypePointer UniformConstant %30 %29 = OpVariable %31 UniformConstant -%33 = OpTypePointer Input %10 -%32 = OpVariable %33 Input -%35 = OpTypePointer Input %24 -%34 = OpVariable %35 Input -%37 = OpTypePointer Output %24 -%36 = OpVariable %37 Output -%41 = OpTypeFunction %4 %12 %24 -%47 = OpTypeBool -%51 = OpTypeVector %4 2 -%62 = OpTypeInt 32 1 -%66 = OpTypeSampledImage %27 -%73 = OpConstant %4 0.0 -%75 = OpTypePointer Function %10 -%77 = OpTypePointer Function %12 -%79 = OpTypeFunction %2 -%91 = OpTypePointer Uniform %17 -%92 = OpConstant %62 0 -%100 = OpTypePointer Uniform %21 -%102 = OpTypePointer Uniform %22 -%103 = OpConstant %62 0 -%40 = OpFunction %4 None %41 -%38 = OpFunctionParameter %12 -%39 = OpFunctionParameter %24 -%42 = OpLabel -%43 = OpLoad %27 %26 -%44 = OpLoad %30 %29 -OpBranch %45 -%45 = OpLabel -%46 = OpCompositeExtract %4 %39 3 -%48 = OpFOrdLessThanEqual %47 %46 %3 -OpSelectionMerge %49 None -OpBranchConditional %48 %50 %49 -%50 = OpLabel +%36 = OpTypeFunction %4 %12 %24 +%41 = OpTypeBool +%45 = OpTypeVector %4 2 +%56 = OpTypeInt 32 1 +%60 = OpTypeSampledImage %27 +%67 = OpConstant %4 0.0 +%69 = OpTypePointer Function %10 +%71 = OpTypePointer Function %12 +%74 = OpTypePointer Input %10 +%73 = OpVariable %74 Input +%77 = OpTypePointer Input %24 +%76 = OpVariable %77 Input +%80 = OpTypePointer Output %24 +%79 = OpVariable %80 Output +%82 = OpTypeFunction %2 +%92 = OpTypePointer Uniform %17 +%93 = OpConstant %56 0 +%101 = OpTypePointer Uniform %21 +%103 = OpTypePointer Uniform %22 +%104 = OpConstant %56 0 +%35 = OpFunction %4 None %36 +%33 = OpFunctionParameter %12 +%34 = OpFunctionParameter %24 +%32 = OpLabel +%37 = OpLoad %27 %26 +%38 = OpLoad %30 %29 +OpBranch %39 +%39 = OpLabel +%40 = OpCompositeExtract %4 %34 3 +%42 = OpFOrdLessThanEqual %41 %40 %3 +OpSelectionMerge %43 None +OpBranchConditional %42 %44 %43 +%44 = OpLabel OpReturnValue %5 -%49 = OpLabel -%52 = OpCompositeConstruct %51 %6 %7 -%53 = OpCompositeExtract %4 %39 3 -%54 = OpFDiv %4 %5 %53 -%55 = OpCompositeExtract %4 %39 0 -%56 = OpCompositeExtract %4 %39 1 -%57 = OpCompositeConstruct %51 %55 %56 -%58 = OpFMul %51 %57 %52 -%59 = OpVectorTimesScalar %51 %58 %54 -%60 = OpCompositeConstruct %51 %6 %6 -%61 = OpFAdd %51 %59 %60 -%63 = OpBitcast %62 %38 -%64 = OpCompositeExtract %4 %39 2 -%65 = OpFMul %4 %64 %54 -%67 = OpCompositeExtract %4 %61 0 -%68 = OpCompositeExtract %4 %61 1 -%69 = OpConvertUToF %4 %63 -%70 = OpCompositeConstruct %10 %67 %68 %69 -%71 = OpSampledImage %66 %43 %44 -%72 = OpImageSampleDrefExplicitLod %4 %71 %70 %65 Lod %73 -OpReturnValue %72 +%43 = OpLabel +%46 = OpCompositeConstruct %45 %6 %7 +%47 = OpCompositeExtract %4 %34 3 +%48 = OpFDiv %4 %5 %47 +%49 = OpCompositeExtract %4 %34 0 +%50 = OpCompositeExtract %4 %34 1 +%51 = OpCompositeConstruct %45 %49 %50 +%52 = OpFMul %45 %51 %46 +%53 = OpVectorTimesScalar %45 %52 %48 +%54 = OpCompositeConstruct %45 %6 %6 +%55 = OpFAdd %45 %53 %54 +%57 = OpBitcast %56 %33 +%58 = OpCompositeExtract %4 %34 2 +%59 = OpFMul %4 %58 %48 +%61 = OpCompositeExtract %4 %55 0 +%62 = OpCompositeExtract %4 %55 1 +%63 = OpConvertUToF %4 %57 +%64 = OpCompositeConstruct %10 %61 %62 %63 +%65 = OpSampledImage %60 %37 %38 +%66 = OpImageSampleDrefExplicitLod %4 %65 %64 %59 Lod %67 +OpReturnValue %66 OpFunctionEnd -%78 = OpFunction %2 None %79 -%80 = OpLabel -%74 = OpVariable %75 Function %9 -%76 = OpVariable %77 Function %13 -%81 = OpLoad %27 %26 -%82 = OpLoad %30 %29 -OpBranch %83 -%83 = OpLabel -%84 = OpLoad %10 %32 -%85 = OpExtInst %10 %1 Normalize %84 -OpBranch %86 -%86 = OpLabel -OpLoopMerge %87 %89 None -OpBranch %88 -%88 = OpLabel -%90 = OpLoad %12 %76 -%93 = OpAccessChain %91 %15 %92 -%94 = OpLoad %17 %93 -%95 = OpCompositeExtract %12 %94 0 -%96 = OpExtInst %12 %1 UMin %95 %11 -%97 = OpUGreaterThanEqual %47 %90 %96 -OpSelectionMerge %98 None -OpBranchConditional %97 %99 %98 -%99 = OpLabel +%81 = OpFunction %2 None %82 +%72 = OpLabel +%68 = OpVariable %69 Function %9 +%70 = OpVariable %71 Function %13 +%75 = OpLoad %10 %73 +%78 = OpLoad %24 %76 +%83 = OpLoad %27 %26 +%84 = OpLoad %30 %29 +OpBranch %85 +%85 = OpLabel +%86 = OpExtInst %10 %1 Normalize %75 OpBranch %87 -%98 = OpLabel -%101 = OpLoad %12 %76 -%104 = OpAccessChain %102 %19 %103 %101 -%105 = OpLoad %22 %104 -%106 = OpLoad %12 %76 -%107 = OpCompositeExtract %23 %105 0 -%108 = OpLoad %24 %34 -%109 = OpMatrixTimesVector %24 %107 %108 -%110 = OpFunctionCall %4 %40 %106 %109 -%111 = OpCompositeExtract %24 %105 1 +%87 = OpLabel +OpLoopMerge %88 %90 None +OpBranch %89 +%89 = OpLabel +%91 = OpLoad %12 %70 +%94 = OpAccessChain %92 %15 %93 +%95 = OpLoad %17 %94 +%96 = OpCompositeExtract %12 %95 0 +%97 = OpExtInst %12 %1 UMin %96 %11 +%98 = OpUGreaterThanEqual %41 %91 %97 +OpSelectionMerge %99 None +OpBranchConditional %98 %100 %99 +%100 = OpLabel +OpBranch %88 +%99 = OpLabel +%102 = OpLoad %12 %70 +%105 = OpAccessChain %103 %19 %104 %102 +%106 = OpLoad %22 %105 +%107 = OpLoad %12 %70 +%108 = OpCompositeExtract %23 %106 0 +%109 = OpMatrixTimesVector %24 %108 %78 +%110 = OpFunctionCall %4 %35 %107 %109 +%111 = OpCompositeExtract %24 %106 1 %112 = OpCompositeExtract %4 %111 0 %113 = OpCompositeExtract %4 %111 1 %114 = OpCompositeExtract %4 %111 2 %115 = OpCompositeConstruct %10 %112 %113 %114 -%116 = OpLoad %24 %34 -%117 = OpCompositeExtract %4 %116 0 -%118 = OpCompositeExtract %4 %116 1 -%119 = OpCompositeExtract %4 %116 2 -%120 = OpCompositeConstruct %10 %117 %118 %119 -%121 = OpFSub %10 %115 %120 -%122 = OpExtInst %10 %1 Normalize %121 -%123 = OpDot %4 %85 %122 -%124 = OpExtInst %4 %1 FMax %3 %123 -%125 = OpLoad %10 %74 -%126 = OpFMul %4 %110 %124 -%127 = OpCompositeExtract %24 %105 2 -%128 = OpCompositeExtract %4 %127 0 -%129 = OpCompositeExtract %4 %127 1 -%130 = OpCompositeExtract %4 %127 2 -%131 = OpCompositeConstruct %10 %128 %129 %130 -%132 = OpVectorTimesScalar %10 %131 %126 -%133 = OpFAdd %10 %125 %132 -OpStore %74 %133 -OpBranch %89 -%89 = OpLabel -%134 = OpLoad %12 %76 -%135 = OpIAdd %12 %134 %14 -OpStore %76 %135 -OpBranch %86 -%87 = OpLabel -%136 = OpLoad %10 %74 -%137 = OpCompositeConstruct %24 %136 %5 -OpStore %36 %137 +%116 = OpCompositeExtract %4 %78 0 +%117 = OpCompositeExtract %4 %78 1 +%118 = OpCompositeExtract %4 %78 2 +%119 = OpCompositeConstruct %10 %116 %117 %118 +%120 = OpFSub %10 %115 %119 +%121 = OpExtInst %10 %1 Normalize %120 +%122 = OpDot %4 %86 %121 +%123 = OpExtInst %4 %1 FMax %3 %122 +%124 = OpLoad %10 %68 +%125 = OpFMul %4 %110 %123 +%126 = OpCompositeExtract %24 %106 2 +%127 = OpCompositeExtract %4 %126 0 +%128 = OpCompositeExtract %4 %126 1 +%129 = OpCompositeExtract %4 %126 2 +%130 = OpCompositeConstruct %10 %127 %128 %129 +%131 = OpVectorTimesScalar %10 %130 %125 +%132 = OpFAdd %10 %124 %131 +OpStore %68 %132 +OpBranch %90 +%90 = OpLabel +%133 = OpLoad %12 %70 +%134 = OpIAdd %12 %133 %14 +OpStore %70 %134 +OpBranch %87 +%88 = OpLabel +%135 = OpLoad %10 %68 +%136 = OpCompositeConstruct %24 %135 %5 +OpStore %79 %136 OpReturn OpFunctionEnd diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap index 6d949cd3c..e08e83c48 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox-Fragment.glsl.snap @@ -6,15 +6,20 @@ expression: string precision highp float; +struct VertexOutput { + vec4 position; + vec3 uv; +}; + uniform highp samplerCube _group_0_binding_1; -in vec3 _location_0_vs; - -out vec4 _location_0; +in vec3 _in_location_0; +out vec4 _out_location_0; void main() { - vec4 _expr9 = texture(_group_0_binding_1, vec3(_location_0_vs)); - _location_0 = _expr9; + vec3 uv1 = _in_location_0; + vec4 _expr4 = texture(_group_0_binding_1, vec3(uv1)); + _out_location_0 = _expr4; return; } diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap index 5265b650b..50667e689 100644 --- a/tests/out/skybox-Vertex.glsl.snap +++ b/tests/out/skybox-Vertex.glsl.snap @@ -6,23 +6,34 @@ expression: string precision highp float; -out vec3 _location_0_vs; +struct VertexOutput { + vec4 position; + vec3 uv; +}; uniform Data_block_0 { mat4x4 proj_inv; mat4x4 view; } _group_0_binding_0; +out vec3 _out_location_0; + void main() { + uint vertex_index = uint(gl_VertexID); int tmp1_; int tmp2_; vec4 unprojected; - tmp1_ = (int(gl_VertexID) / 2); - tmp2_ = (int(gl_VertexID) & 1); - vec4 _expr28 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - unprojected = (_group_0_binding_0.proj_inv * _expr28); - vec4 _expr56 = unprojected; - _location_0_vs = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr56[0], _expr56[1], _expr56[2])); - gl_Position = _expr28; + VertexOutput out1; + tmp1_ = (int(vertex_index) / 2); + tmp2_ = (int(vertex_index) & 1); + vec4 _expr24 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + unprojected = (_group_0_binding_0.proj_inv * _expr24); + vec4 _expr54 = unprojected; + out1.uv = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr54[0], _expr54[1], _expr54[2])); + out1.position = _expr24; + gl_Position = out1.position; + _out_location_0 = out1.uv; return; } + + diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 70985ad0d..effce33ea 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -9,15 +9,20 @@ typedef metal::float4 type; typedef metal::float3 type1; -typedef uint type2; +struct VertexOutput { + type position; + type1 uv; +}; -typedef metal::float4x4 type3; +typedef metal::float4x4 type2; struct Data { - type3 proj_inv; - type3 view; + type2 proj_inv; + type2 view; }; +typedef uint type3; + typedef int type4; typedef metal::float3x3 type5; @@ -33,47 +38,42 @@ constexpr constant float const_1f = 1.0; constexpr constant float const_0f = 0.0; struct vs_mainInput { }; - struct vs_mainOutput { - type out_position [[position]]; - type1 out_uv [[user(loc0)]]; + type position [[position]]; + type1 uv [[user(loc0)]]; }; - vertex vs_mainOutput vs_main( - vs_mainInput input [[stage_in]], - type2 in_vertex_index [[vertex_id]], - constant Data& r_data [[buffer(0)]] + type3 vertex_index [[vertex_id]] +, constant Data& r_data [[buffer(0)]] ) { - vs_mainOutput output; type4 tmp1_; type4 tmp2_; type unprojected; - tmp1_ = (static_cast(in_vertex_index) / const_2i); - tmp2_ = (static_cast(in_vertex_index) & const_1i); - type _expr28 = metal::float4(((static_cast(tmp1_) * const_4f) - const_1f), ((static_cast(tmp2_) * const_4f) - const_1f), const_0f, const_1f); - unprojected = (r_data.proj_inv * _expr28); - type _expr56 = unprojected; - output.out_uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr56.x, _expr56.y, _expr56.z)); - output.out_position = _expr28; - return output; + VertexOutput out; + tmp1_ = (static_cast(vertex_index) / const_2i); + tmp2_ = (static_cast(vertex_index) & const_1i); + type _expr24 = metal::float4(((static_cast(tmp1_) * const_4f) - const_1f), ((static_cast(tmp2_) * const_4f) - const_1f), const_0f, const_1f); + unprojected = (r_data.proj_inv * _expr24); + type _expr54 = unprojected; + out.uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr54.x, _expr54.y, _expr54.z)); + out.position = _expr24; + const auto _tmp = out; + return vs_mainOutput { _tmp.position, _tmp.uv }; } struct fs_mainInput { - type1 in_uv [[user(loc0)]]; + type1 uv1 [[user(loc0)]]; }; - struct fs_mainOutput { - type out_color [[color(0)]]; + type member1 [[color(0)]]; }; - fragment fs_mainOutput fs_main( - fs_mainInput input [[stage_in]], - type6 r_texture [[texture(0)]], - type7 r_sampler [[sampler(1)]] + fs_mainInput varyings1 [[stage_in]] +, type6 r_texture [[texture(0)]] +, type7 r_sampler [[sampler(1)]] ) { - fs_mainOutput output; - metal::float4 _expr9 = r_texture.sample(r_sampler, input.in_uv); - output.out_color = _expr9; - return output; + const auto uv1 = varyings1.uv1; + metal::float4 _expr4 = r_texture.sample(r_sampler, uv1); + return fs_mainOutput { _expr4 }; } diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index 41322d50a..19e3b1070 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -5,50 +5,51 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 103 +; Bound: 113 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %37 "vs_main" %10 %13 %16 -OpEntryPoint Fragment %94 "fs_main" %29 %31 -OpExecutionMode %94 OriginUpperLeft +OpEntryPoint Vertex %39 "vs_main" %32 %35 %37 +OpEntryPoint Fragment %106 "fs_main" %102 %105 +OpExecutionMode %106 OriginUpperLeft OpSource GLSL 450 -OpName %10 "out_position" -OpName %13 "out_uv" -OpName %16 "in_vertex_index" -OpName %20 "Data" -OpMemberName %20 0 "proj_inv" -OpMemberName %20 1 "view" -OpName %19 "r_data" -OpName %23 "r_texture" -OpName %26 "r_sampler" -OpName %29 "in_uv" -OpName %31 "out_color" -OpName %32 "tmp1" -OpName %34 "tmp2" -OpName %35 "unprojected" -OpName %37 "vs_main" -OpName %37 "vs_main" -OpName %94 "fs_main" -OpName %94 "fs_main" -OpDecorate %10 BuiltIn Position -OpDecorate %13 Location 0 -OpDecorate %16 BuiltIn VertexIndex -OpDecorate %20 Block -OpMemberDecorate %20 0 Offset 0 -OpMemberDecorate %20 0 ColMajor -OpMemberDecorate %20 0 MatrixStride 16 -OpMemberDecorate %20 1 Offset 64 -OpMemberDecorate %20 1 ColMajor -OpMemberDecorate %20 1 MatrixStride 16 -OpDecorate %19 DescriptorSet 0 -OpDecorate %19 Binding 0 -OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 1 -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 2 -OpDecorate %29 Location 0 -OpDecorate %31 Location 0 +OpName %11 "Data" +OpMemberName %11 0 "proj_inv" +OpMemberName %11 1 "view" +OpName %10 "r_data" +OpName %15 "r_texture" +OpName %18 "r_sampler" +OpName %21 "tmp1" +OpName %23 "tmp2" +OpName %24 "unprojected" +OpName %26 "out" +OpName %27 "VertexOutput" +OpName %32 "vertex_index" +OpName %35 "position" +OpName %37 "uv" +OpName %39 "vs_main" +OpName %39 "vs_main" +OpName %102 "uv" +OpName %106 "fs_main" +OpName %106 "fs_main" +OpDecorate %11 Block +OpMemberDecorate %11 0 Offset 0 +OpMemberDecorate %11 0 ColMajor +OpMemberDecorate %11 0 MatrixStride 16 +OpMemberDecorate %11 1 Offset 64 +OpMemberDecorate %11 1 ColMajor +OpMemberDecorate %11 1 MatrixStride 16 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 0 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 1 +OpDecorate %18 DescriptorSet 0 +OpDecorate %18 Binding 2 +OpDecorate %32 BuiltIn VertexIndex +OpDecorate %35 BuiltIn Position +OpDecorate %37 Location 0 +OpDecorate %102 Location 0 +OpDecorate %105 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -57,108 +58,120 @@ OpDecorate %31 Location 0 %6 = OpConstant %7 4.0 %8 = OpConstant %7 1.0 %9 = OpConstant %7 0.0 -%11 = OpTypeVector %7 4 -%12 = OpTypePointer Output %11 -%10 = OpVariable %12 Output -%14 = OpTypeVector %7 3 -%15 = OpTypePointer Output %14 -%13 = OpVariable %15 Output -%17 = OpTypeInt 32 0 -%18 = OpTypePointer Input %17 -%16 = OpVariable %18 Input -%21 = OpTypeMatrix %11 4 -%20 = OpTypeStruct %21 %21 -%22 = OpTypePointer Uniform %20 -%19 = OpVariable %22 Uniform -%24 = OpTypeImage %7 Cube 0 0 0 1 Unknown -%25 = OpTypePointer UniformConstant %24 -%23 = OpVariable %25 UniformConstant -%27 = OpTypeSampler -%28 = OpTypePointer UniformConstant %27 -%26 = OpVariable %28 UniformConstant -%30 = OpTypePointer Input %14 -%29 = OpVariable %30 Input -%31 = OpVariable %12 Output -%33 = OpTypePointer Function %4 -%36 = OpTypePointer Function %11 -%38 = OpTypeFunction %2 -%56 = OpTypePointer Uniform %21 -%57 = OpConstant %4 1 -%65 = OpConstant %4 1 -%73 = OpConstant %4 1 -%81 = OpTypeMatrix %14 3 -%84 = OpConstant %4 0 -%100 = OpTypeSampledImage %24 -%37 = OpFunction %2 None %38 -%39 = OpLabel -%32 = OpVariable %33 Function -%34 = OpVariable %33 Function -%35 = OpVariable %36 Function -OpBranch %40 -%40 = OpLabel -%41 = OpLoad %17 %16 -%42 = OpBitcast %4 %41 +%13 = OpTypeVector %7 4 +%12 = OpTypeMatrix %13 4 +%11 = OpTypeStruct %12 %12 +%14 = OpTypePointer Uniform %11 +%10 = OpVariable %14 Uniform +%16 = OpTypeImage %7 Cube 0 0 0 1 Unknown +%17 = OpTypePointer UniformConstant %16 +%15 = OpVariable %17 UniformConstant +%19 = OpTypeSampler +%20 = OpTypePointer UniformConstant %19 +%18 = OpVariable %20 UniformConstant +%22 = OpTypePointer Function %4 +%25 = OpTypePointer Function %13 +%28 = OpTypeVector %7 3 +%27 = OpTypeStruct %13 %28 +%29 = OpTypePointer Function %27 +%31 = OpTypeInt 32 0 +%33 = OpTypePointer Input %31 +%32 = OpVariable %33 Input +%36 = OpTypePointer Output %13 +%35 = OpVariable %36 Output +%38 = OpTypePointer Output %28 +%37 = OpVariable %38 Output +%40 = OpTypeFunction %2 +%55 = OpTypePointer Uniform %12 +%56 = OpConstant %4 1 +%64 = OpConstant %4 1 +%72 = OpConstant %4 1 +%80 = OpTypeMatrix %28 3 +%83 = OpConstant %4 0 +%87 = OpTypePointer Function %28 +%94 = OpConstant %4 1 +%96 = OpConstant %4 0 +%103 = OpTypePointer Input %28 +%102 = OpVariable %103 Input +%105 = OpVariable %36 Output +%110 = OpTypeSampledImage %16 +%39 = OpFunction %2 None %40 +%30 = OpLabel +%23 = OpVariable %22 Function +%26 = OpVariable %29 Function +%21 = OpVariable %22 Function +%24 = OpVariable %25 Function +%34 = OpLoad %31 %32 +OpBranch %41 +%41 = OpLabel +%42 = OpBitcast %4 %34 %43 = OpSDiv %4 %42 %3 -OpStore %32 %43 -%44 = OpLoad %17 %16 -%45 = OpBitcast %4 %44 -%46 = OpBitwiseAnd %4 %45 %5 -OpStore %34 %46 -%47 = OpLoad %4 %32 -%48 = OpConvertSToF %7 %47 -%49 = OpFMul %7 %48 %6 -%50 = OpFSub %7 %49 %8 -%51 = OpLoad %4 %34 -%52 = OpConvertSToF %7 %51 -%53 = OpFMul %7 %52 %6 -%54 = OpFSub %7 %53 %8 -%55 = OpCompositeConstruct %11 %50 %54 %9 %8 -%58 = OpAccessChain %56 %19 %57 -%59 = OpLoad %21 %58 -%60 = OpCompositeExtract %11 %59 0 -%61 = OpCompositeExtract %7 %60 0 -%62 = OpCompositeExtract %7 %60 1 -%63 = OpCompositeExtract %7 %60 2 -%64 = OpCompositeConstruct %14 %61 %62 %63 -%66 = OpAccessChain %56 %19 %65 -%67 = OpLoad %21 %66 -%68 = OpCompositeExtract %11 %67 1 -%69 = OpCompositeExtract %7 %68 0 -%70 = OpCompositeExtract %7 %68 1 -%71 = OpCompositeExtract %7 %68 2 -%72 = OpCompositeConstruct %14 %69 %70 %71 -%74 = OpAccessChain %56 %19 %73 -%75 = OpLoad %21 %74 -%76 = OpCompositeExtract %11 %75 2 -%77 = OpCompositeExtract %7 %76 0 -%78 = OpCompositeExtract %7 %76 1 -%79 = OpCompositeExtract %7 %76 2 -%80 = OpCompositeConstruct %14 %77 %78 %79 -%82 = OpCompositeConstruct %81 %64 %72 %80 -%83 = OpTranspose %81 %82 -%85 = OpAccessChain %56 %19 %84 -%86 = OpLoad %21 %85 -%87 = OpMatrixTimesVector %11 %86 %55 -OpStore %35 %87 -%88 = OpLoad %11 %35 +OpStore %21 %43 +%44 = OpBitcast %4 %34 +%45 = OpBitwiseAnd %4 %44 %5 +OpStore %23 %45 +%46 = OpLoad %4 %21 +%47 = OpConvertSToF %7 %46 +%48 = OpFMul %7 %47 %6 +%49 = OpFSub %7 %48 %8 +%50 = OpLoad %4 %23 +%51 = OpConvertSToF %7 %50 +%52 = OpFMul %7 %51 %6 +%53 = OpFSub %7 %52 %8 +%54 = OpCompositeConstruct %13 %49 %53 %9 %8 +%57 = OpAccessChain %55 %10 %56 +%58 = OpLoad %12 %57 +%59 = OpCompositeExtract %13 %58 0 +%60 = OpCompositeExtract %7 %59 0 +%61 = OpCompositeExtract %7 %59 1 +%62 = OpCompositeExtract %7 %59 2 +%63 = OpCompositeConstruct %28 %60 %61 %62 +%65 = OpAccessChain %55 %10 %64 +%66 = OpLoad %12 %65 +%67 = OpCompositeExtract %13 %66 1 +%68 = OpCompositeExtract %7 %67 0 +%69 = OpCompositeExtract %7 %67 1 +%70 = OpCompositeExtract %7 %67 2 +%71 = OpCompositeConstruct %28 %68 %69 %70 +%73 = OpAccessChain %55 %10 %72 +%74 = OpLoad %12 %73 +%75 = OpCompositeExtract %13 %74 2 +%76 = OpCompositeExtract %7 %75 0 +%77 = OpCompositeExtract %7 %75 1 +%78 = OpCompositeExtract %7 %75 2 +%79 = OpCompositeConstruct %28 %76 %77 %78 +%81 = OpCompositeConstruct %80 %63 %71 %79 +%82 = OpTranspose %80 %81 +%84 = OpAccessChain %55 %10 %83 +%85 = OpLoad %12 %84 +%86 = OpMatrixTimesVector %13 %85 %54 +OpStore %24 %86 +%88 = OpLoad %13 %24 %89 = OpCompositeExtract %7 %88 0 %90 = OpCompositeExtract %7 %88 1 %91 = OpCompositeExtract %7 %88 2 -%92 = OpCompositeConstruct %14 %89 %90 %91 -%93 = OpMatrixTimesVector %14 %83 %92 -OpStore %13 %93 -OpStore %10 %55 +%92 = OpCompositeConstruct %28 %89 %90 %91 +%93 = OpMatrixTimesVector %28 %82 %92 +%95 = OpAccessChain %87 %26 %94 +OpStore %95 %93 +%97 = OpAccessChain %25 %26 %96 +OpStore %97 %54 +%98 = OpLoad %27 %26 +%99 = OpCompositeExtract %13 %98 0 +OpStore %35 %99 +%100 = OpCompositeExtract %28 %98 1 +OpStore %37 %100 OpReturn OpFunctionEnd -%94 = OpFunction %2 None %38 -%95 = OpLabel -%96 = OpLoad %24 %23 -%97 = OpLoad %27 %26 -OpBranch %98 -%98 = OpLabel -%99 = OpLoad %14 %29 -%101 = OpSampledImage %100 %96 %97 -%102 = OpImageSampleImplicitLod %11 %101 %99 -OpStore %31 %102 +%106 = OpFunction %2 None %40 +%101 = OpLabel +%104 = OpLoad %28 %102 +%107 = OpLoad %16 %15 +%108 = OpLoad %19 %18 +OpBranch %109 +%109 = OpLabel +%111 = OpSampledImage %110 %107 %108 +%112 = OpImageSampleImplicitLod %13 %111 %104 +OpStore %105 %112 OpReturn OpFunctionEnd diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap index c246e2285..aa9942f94 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm.snap @@ -5,83 +5,81 @@ expression: dis ; SPIR-V ; Version: 1.5 ; Generator: rspirv -; Bound: 46 +; Bound: 45 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %23 "main" %5 %20 -OpExecutionMode %23 OriginUpperLeft +OpEntryPoint Fragment %25 "main" %19 %23 +OpExecutionMode %25 OriginUpperLeft OpSource GLSL 450 -OpName %5 "tex_coord" -OpName %9 "texture0" -OpName %12 "texture1" -OpName %13 "sampler" -OpName %17 "PushConstants" -OpMemberName %17 0 "index" -OpName %16 "pc" -OpName %20 "color" -OpName %23 "main" -OpName %23 "main" -OpDecorate %5 Location 0 +OpName %5 "texture0" +OpName %9 "texture1" +OpName %10 "sampler" +OpName %14 "PushConstants" +OpMemberName %14 0 "index" +OpName %13 "pc" +OpName %19 "tex_coord" +OpName %25 "main" +OpName %25 "main" +OpDecorate %5 DescriptorSet 0 +OpDecorate %5 Binding 0 OpDecorate %9 DescriptorSet 0 -OpDecorate %9 Binding 0 -OpDecorate %12 DescriptorSet 0 -OpDecorate %12 Binding 1 -OpDecorate %13 DescriptorSet 0 -OpDecorate %13 Binding 2 -OpDecorate %17 Block -OpMemberDecorate %17 0 Offset 0 -OpDecorate %20 Location 1 +OpDecorate %9 Binding 1 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 2 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpDecorate %19 Location 0 +OpDecorate %23 Location 1 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 0 %7 = OpTypeFloat 32 -%6 = OpTypeVector %7 2 -%8 = OpTypePointer Input %6 -%5 = OpVariable %8 Input -%10 = OpTypeImage %7 2D 0 0 0 1 Unknown -%11 = OpTypePointer UniformConstant %10 -%9 = OpVariable %11 UniformConstant -%12 = OpVariable %11 UniformConstant -%14 = OpTypeSampler -%15 = OpTypePointer UniformConstant %14 -%13 = OpVariable %15 UniformConstant -%18 = OpTypeInt 32 0 -%17 = OpTypeStruct %18 -%19 = OpTypePointer PushConstant %17 -%16 = OpVariable %19 PushConstant -%21 = OpTypeVector %7 4 -%22 = OpTypePointer Output %21 -%20 = OpVariable %22 Output -%24 = OpTypeFunction %2 -%30 = OpTypePointer PushConstant %18 -%31 = OpConstant %4 0 -%34 = OpTypeBool -%40 = OpTypeSampledImage %10 -%23 = OpFunction %2 None %24 -%25 = OpLabel -%26 = OpLoad %10 %9 -%27 = OpLoad %10 %12 -%28 = OpLoad %14 %13 -OpBranch %29 -%29 = OpLabel -%32 = OpAccessChain %30 %16 %31 -%33 = OpLoad %18 %32 -%35 = OpIEqual %34 %33 %3 -OpSelectionMerge %36 None -OpBranchConditional %35 %37 %38 -%37 = OpLabel -%39 = OpLoad %6 %5 -%41 = OpSampledImage %40 %26 %28 -%42 = OpImageSampleImplicitLod %21 %41 %39 -OpStore %20 %42 -OpReturn +%6 = OpTypeImage %7 2D 0 0 0 1 Unknown +%8 = OpTypePointer UniformConstant %6 +%5 = OpVariable %8 UniformConstant +%9 = OpVariable %8 UniformConstant +%11 = OpTypeSampler +%12 = OpTypePointer UniformConstant %11 +%10 = OpVariable %12 UniformConstant +%15 = OpTypeInt 32 0 +%14 = OpTypeStruct %15 +%16 = OpTypePointer PushConstant %14 +%13 = OpVariable %16 PushConstant +%18 = OpTypeVector %7 2 +%20 = OpTypePointer Input %18 +%19 = OpVariable %20 Input +%22 = OpTypeVector %7 4 +%24 = OpTypePointer Output %22 +%23 = OpVariable %24 Output +%26 = OpTypeFunction %2 +%31 = OpTypePointer PushConstant %15 +%32 = OpConstant %4 0 +%35 = OpTypeBool +%40 = OpTypeSampledImage %6 +%25 = OpFunction %2 None %26 +%17 = OpLabel +%21 = OpLoad %18 %19 +%27 = OpLoad %6 %5 +%28 = OpLoad %6 %9 +%29 = OpLoad %11 %10 +OpBranch %30 +%30 = OpLabel +%33 = OpAccessChain %31 %13 %32 +%34 = OpLoad %15 %33 +%36 = OpIEqual %35 %34 %3 +OpSelectionMerge %37 None +OpBranchConditional %36 %38 %39 %38 = OpLabel -%43 = OpLoad %6 %5 -%44 = OpSampledImage %40 %27 %28 -%45 = OpImageSampleImplicitLod %21 %44 %43 -OpStore %20 %45 +%41 = OpSampledImage %40 %27 %29 +%42 = OpImageSampleImplicitLod %22 %41 %21 +OpStore %23 %42 OpReturn -%36 = OpLabel +%39 = OpLabel +%43 = OpSampledImage %40 %28 %29 +%44 = OpImageSampleImplicitLod %22 %43 %21 +OpStore %23 %44 +OpReturn +%37 = OpLabel OpReturn OpFunctionEnd diff --git a/tests/parse.rs b/tests/parse.rs index 11b946e27..6c7301e1a 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -1,7 +1,7 @@ //TODO: consider converting this to snapshots? #[cfg(feature = "glsl-in")] -fn check_glsl(name: &str) { +fn _check_glsl(name: &str) { let path = std::path::PathBuf::from("tests/cases").join(name); let input = std::fs::read_to_string(path).unwrap(); let stage = if name.ends_with(".vert") { @@ -37,6 +37,6 @@ fn check_glsl(name: &str) { fn parse_glsl() { //check_glsl("glsl_constant_expression.vert"); //TODO //check_glsl("glsl_if_preprocessor.vert"); - check_glsl("glsl_preprocessor_abuse.vert"); + //check_glsl("glsl_preprocessor_abuse.vert"); //check_glsl("glsl_vertex_test_shader.vert"); //TODO } From 32a11752af99e818b14da9aa37c914a89b57b7ad Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 13 Mar 2021 22:37:42 -0500 Subject: [PATCH 0570/2212] Rename FragCoord builtin into Position --- src/back/glsl/mod.rs | 13 +++++++++---- src/back/msl/mod.rs | 3 +-- src/back/spv/writer.rs | 10 ++++++++-- src/front/spv/convert.rs | 4 ++-- src/front/wgsl/conv.rs | 3 +-- src/lib.rs | 3 +-- src/proc/validator.rs | 20 ++++++++------------ 7 files changed, 30 insertions(+), 26 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 1af0f869c..d9ae2848d 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -249,7 +249,7 @@ impl fmt::Display for VaryingName<'_> { ) } Binding::BuiltIn(built_in) => { - write!(f, "{}", glsl_built_in(built_in)) + write!(f, "{}", glsl_built_in(built_in, self.output)) } } } @@ -2144,10 +2144,16 @@ fn glsl_scalar(kind: ScalarKind, width: Bytes) -> Result, } /// Helper function that returns the glsl variable name for a builtin -fn glsl_built_in(built_in: BuiltIn) -> &'static str { +fn glsl_built_in(built_in: BuiltIn, output: bool) -> &'static str { match built_in { + BuiltIn::Position => { + if output { + "gl_Position" + } else { + "gl_FragCoord" + } + } // vertex - BuiltIn::Position => "gl_Position", BuiltIn::BaseInstance => "uint(gl_BaseInstance)", BuiltIn::BaseVertex => "uint(gl_BaseVertex)", BuiltIn::ClipDistance => "gl_ClipDistance", @@ -2155,7 +2161,6 @@ fn glsl_built_in(built_in: BuiltIn) -> &'static str { BuiltIn::PointSize => "gl_PointSize", BuiltIn::VertexIndex => "uint(gl_VertexID)", // fragment - BuiltIn::FragCoord => "gl_FragCoord", BuiltIn::FragDepth => "gl_FragDepth", BuiltIn::FrontFacing => "gl_FrontFacing", BuiltIn::SampleIndex => "gl_SampleID", diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index e9ae61e5b..f95ff8f3c 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -177,16 +177,15 @@ impl ResolvedBinding { ResolvedBinding::BuiltIn(built_in) => { use crate::BuiltIn as Bi; let name = match built_in { + Bi::Position => "position", // vertex Bi::BaseInstance => "base_instance", Bi::BaseVertex => "base_vertex", Bi::ClipDistance => "clip_distance", Bi::InstanceIndex => "instance_id", Bi::PointSize => "point_size", - Bi::Position => "position", Bi::VertexIndex => "vertex_id", // fragment - Bi::FragCoord => "position", Bi::FragDepth => "depth(any)", Bi::FrontFacing => "front_facing", Bi::SampleIndex => "sample_id", diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 28732354c..59fe3b5cd 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1087,15 +1087,21 @@ impl Writer { crate::Binding::BuiltIn(built_in) => { use crate::BuiltIn as Bi; let built_in = match built_in { + Bi::Position => { + if class == spirv::StorageClass::Output { + spirv::BuiltIn::Position + } else { + spirv::BuiltIn::FragCoord + } + } + // vertex Bi::BaseInstance => spirv::BuiltIn::BaseInstance, Bi::BaseVertex => spirv::BuiltIn::BaseVertex, Bi::ClipDistance => spirv::BuiltIn::ClipDistance, Bi::InstanceIndex => spirv::BuiltIn::InstanceIndex, Bi::PointSize => spirv::BuiltIn::PointSize, - Bi::Position => spirv::BuiltIn::Position, Bi::VertexIndex => spirv::BuiltIn::VertexIndex, // fragment - Bi::FragCoord => spirv::BuiltIn::FragCoord, Bi::FragDepth => spirv::BuiltIn::FragDepth, Bi::FrontFacing => spirv::BuiltIn::FrontFacing, Bi::SampleIndex => spirv::BuiltIn::SampleId, diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index f1086d0c0..baad81286 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -116,15 +116,15 @@ pub(super) fn map_width(word: spirv::Word) -> Result { pub(super) fn map_builtin(word: spirv::Word, is_output: bool) -> Result { use spirv::BuiltIn as Bi; Ok(match spirv::BuiltIn::from_u32(word) { + Some(Bi::Position) | Some(Bi::FragCoord) => crate::BuiltIn::Position, + // vertex Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, Some(Bi::BaseVertex) => crate::BuiltIn::BaseVertex, Some(Bi::ClipDistance) => crate::BuiltIn::ClipDistance, Some(Bi::InstanceIndex) => crate::BuiltIn::InstanceIndex, Some(Bi::PointSize) => crate::BuiltIn::PointSize, - Some(Bi::Position) => crate::BuiltIn::Position, Some(Bi::VertexIndex) => crate::BuiltIn::VertexIndex, // fragment - Some(Bi::FragCoord) => crate::BuiltIn::FragCoord, Some(Bi::FragDepth) => crate::BuiltIn::FragDepth, Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing, Some(Bi::SampleId) => crate::BuiltIn::SampleIndex, diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 7a70da638..2bdc7051d 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -12,13 +12,12 @@ pub fn map_storage_class(word: &str) -> Result> { pub fn map_built_in(word: &str) -> Result> { Ok(match word { - // vertex "position" => crate::BuiltIn::Position, + // vertex "vertex_index" => crate::BuiltIn::VertexIndex, "instance_index" => crate::BuiltIn::InstanceIndex, // fragment "front_facing" => crate::BuiltIn::FrontFacing, - "frag_coord" => crate::BuiltIn::FragCoord, "frag_depth" => crate::BuiltIn::FragDepth, "sample_index" => crate::BuiltIn::SampleIndex, "sample_mask_in" => crate::BuiltIn::SampleMaskIn, diff --git a/src/lib.rs b/src/lib.rs index bdd759443..ebca7842a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -142,16 +142,15 @@ pub enum StorageClass { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum BuiltIn { + Position, // vertex BaseInstance, BaseVertex, ClipDistance, InstanceIndex, PointSize, - Position, VertexIndex, // fragment - FragCoord, FragDepth, FrontFacing, SampleIndex, diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 8f4b7ffe1..1ce08d2e4 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -133,7 +133,7 @@ pub enum LocalVariableError { #[derive(Clone, Debug, Error)] pub enum VaryingError { - #[error("The type does not match the varying")] + #[error("The type {0:?} does not match the varying")] InvalidType(Handle), #[error("Interpolation is not valid")] InvalidInterpolation, @@ -369,16 +369,11 @@ impl VaryingContext<'_> { }, ), Bi::Position => ( - self.stage == St::Vertex && self.output, - *ty_inner - == Ti::Vector { - size: Vs::Quad, - kind: Sk::Float, - width, - }, - ), - Bi::FragCoord => ( - self.stage == St::Fragment && !self.output, + match self.stage { + St::Vertex => self.output, + St::Fragment => !self.output, + St::Compute => false, + }, *ty_inner == Ti::Vector { size: Vs::Quad, @@ -465,7 +460,8 @@ impl VaryingContext<'_> { { return Err(VaryingError::InvalidInterpolation); } - _ => return Err(VaryingError::InvalidType(self.ty)), + Some(_) => {} + None => return Err(VaryingError::InvalidType(self.ty)), } } } From 4fb82bd9554d1aa4d9eb4d8a17723f62bbc5457e Mon Sep 17 00:00:00 2001 From: Lain-dono Date: Mon, 15 Mar 2021 02:39:36 +0300 Subject: [PATCH 0571/2212] [spv-out] implement derivatives --- src/back/spv/instructions.rs | 24 ++++++++++++++++++++++++ src/back/spv/writer.rs | 12 ++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index f8366b96c..b1033c802 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -683,6 +683,30 @@ impl super::Instruction { // Derivative Instructions // + pub(super) fn derive_x(result_type_id: Word, id: Word, expr_id: Word) -> Self { + let mut instruction = Self::new(Op::DPdx); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(expr_id); + instruction + } + + pub(super) fn derive_y(result_type_id: Word, id: Word, expr_id: Word) -> Self { + let mut instruction = Self::new(Op::DPdy); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(expr_id); + instruction + } + + pub(super) fn derive_width(result_type_id: Word, id: Word, expr_id: Word) -> Self { + let mut instruction = Self::new(Op::Fwidth); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(expr_id); + instruction + } + // // Control-Flow Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 59fe3b5cd..db143edab 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1901,6 +1901,18 @@ impl Writer { block.body.push(instruction); id } + crate::Expression::Derivative { axis, expr } => { + use crate::DerivativeAxis; + + let id = self.generate_id(); + let expr_id = self.cached[expr]; + block.body.push(match axis { + DerivativeAxis::X => Instruction::derive_x(result_type_id, id, expr_id), + DerivativeAxis::Y => Instruction::derive_y(result_type_id, id, expr_id), + DerivativeAxis::Width => Instruction::derive_width(result_type_id, id, expr_id), + }); + id + } ref other => { log::error!("unimplemented {:?}", other); return Err(Error::FeatureNotImplemented("expression")); From 20979b480088511dea4820d98c3c3a412d159d3f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 15 Mar 2021 01:24:40 -0400 Subject: [PATCH 0572/2212] [wgsl] type inference for constants --- src/front/wgsl/mod.rs | 28 +++- src/front/wgsl/tests.rs | 17 +++ tests/in/quad.wgsl | 6 +- tests/in/shadow.wgsl | 14 +- tests/in/skybox.wgsl | 6 +- tests/out/skybox-Vertex.glsl.snap | 6 +- tests/out/skybox.msl.snap | 6 +- tests/out/skybox.spvasm.snap | 234 +++++++++++++++--------------- 8 files changed, 176 insertions(+), 141 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index d2d64afd4..182b16e7b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -119,6 +119,8 @@ pub enum Error<'a> { UnknownLocalFunction(&'a str), #[error("builtin {0:?} is not implemented")] UnimplementedBuiltin(crate::BuiltIn), + #[error("expression {0} doesn't match its given type {1:?}")] + ConstTypeMismatch(&'a str, Handle), #[error("other error")] Other, } @@ -1984,12 +1986,34 @@ impl Parser { match word { "const" => { emitter.start(context.expressions); - let (name, _ty, _access) = - self.parse_variable_ident_decl(lexer, context.types, context.constants)?; + let name = lexer.next_ident()?; + let given_ty = if lexer.skip(Token::Separator(':')) { + let (ty, _access) = + self.parse_type_decl(lexer, None, context.types, context.constants)?; + Some(ty) + } else { + None + }; lexer.expect(Token::Operation('='))?; let expr_id = self .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; lexer.expect(Token::Separator(';'))?; + if let Some(ty) = given_ty { + // prepare the typifier, but work around mutable borrowing... + let _ = context + .as_expression(block, &mut emitter) + .resolve_type(expr_id)?; + let expr_inner = context.typifier.get(expr_id, context.types); + let given_inner = &context.types[ty].inner; + if given_inner != expr_inner { + log::error!( + "Given type {:?} doesn't match expected {:?}", + given_inner, + expr_inner + ); + return Err(Error::ConstTypeMismatch(name, ty)); + } + } block.extend(emitter.finish(context.expressions)); context.lookup_ident.insert(name, expr_id); } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index e24b4f88d..847e3dea7 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -25,6 +25,23 @@ fn parse_types() { parse_str("var t: [[access(read)]] texture_storage_3d;").unwrap(); } +#[test] +fn parse_type_inference() { + parse_str( + " + fn foo() { + const a = 2u; + const b: u32 = a; + }", + ) + .unwrap(); + assert!(parse_str( + " + fn foo() { const c : i32 = 2.0; }", + ) + .is_err()); +} + #[test] fn parse_type_cast() { parse_str( diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 514f11e9b..6283687ef 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -20,10 +20,12 @@ fn main([[location(0)]] pos : vec2, [[location(1)]] uv : vec2) -> Vert [[stage(fragment)]] fn main([[location(0)]] uv : vec2) -> [[location(0)]] vec4 { - const color: vec4 = textureSample(u_texture, u_sampler, uv); + const color = textureSample(u_texture, u_sampler, uv); if (color.a == 0.0) { discard; } - const premultiplied: vec4 = color.a * color; + // forcing the expression here to be emitted in order to check the + // uniformity of the control flow a bit more strongly. + const premultiplied = color.a * color; return premultiplied; } diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index e6c2408a5..d68b93ef5 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -29,9 +29,9 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { if (homogeneous_coords.w <= 0.0) { return 1.0; } - const flip_correction: vec2 = vec2(0.5, -0.5); - const proj_correction: f32 = 1.0 / homogeneous_coords.w; - const light_local: vec2 = homogeneous_coords.xy * flip_correction * proj_correction + vec2(0.5, 0.5); + const flip_correction = vec2(0.5, -0.5); + const proj_correction = 1.0 / homogeneous_coords.w; + const light_local = homogeneous_coords.xy * flip_correction * proj_correction + vec2(0.5, 0.5); return textureSampleCompare(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z * proj_correction); } @@ -51,10 +51,10 @@ fn fs_main( if (i >= min(u_globals.num_lights.x, c_max_lights)) { break; } - const light: Light = s_lights.data[i]; - const shadow: f32 = fetch_shadow(i, light.proj * position); - const light_dir: vec3 = normalize(light.pos.xyz - position.xyz); - const diffuse: f32 = max(0.0, dot(normal, light_dir)); + const light = s_lights.data[i]; + const shadow = fetch_shadow(i, light.proj * position); + const light_dir = normalize(light.pos.xyz - position.xyz); + const diffuse = max(0.0, dot(normal, light_dir)); color = color + shadow * diffuse * light.color.xyz; continuing { i = i + 1u; diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index bdb9ea820..cd6d46721 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -16,15 +16,15 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { // hacky way to draw a large triangle var tmp1: i32 = i32(vertex_index) / 2; var tmp2: i32 = i32(vertex_index) & 1; - const pos: vec4 = vec4( + const pos = vec4( f32(tmp1) * 4.0 - 1.0, f32(tmp2) * 4.0 - 1.0, 0.0, 1.0 ); - const inv_model_view: mat3x3 = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); - var unprojected: vec4 = r_data.proj_inv * pos; //TODO: const + const inv_model_view = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); + const unprojected = r_data.proj_inv * pos; var out: VertexOutput; out.uv = inv_model_view * unprojected.xyz; out.position = pos; diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap index 50667e689..4b71a76fa 100644 --- a/tests/out/skybox-Vertex.glsl.snap +++ b/tests/out/skybox-Vertex.glsl.snap @@ -22,14 +22,12 @@ void main() { uint vertex_index = uint(gl_VertexID); int tmp1_; int tmp2_; - vec4 unprojected; VertexOutput out1; tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); vec4 _expr24 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - unprojected = (_group_0_binding_0.proj_inv * _expr24); - vec4 _expr54 = unprojected; - out1.uv = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr54[0], _expr54[1], _expr54[2])); + vec4 _expr50 = (_group_0_binding_0.proj_inv * _expr24); + out1.uv = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr50[0], _expr50[1], _expr50[2])); out1.position = _expr24; gl_Position = out1.position; _out_location_0 = out1.uv; diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index effce33ea..4345f5813 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -48,14 +48,12 @@ vertex vs_mainOutput vs_main( ) { type4 tmp1_; type4 tmp2_; - type unprojected; VertexOutput out; tmp1_ = (static_cast(vertex_index) / const_2i); tmp2_ = (static_cast(vertex_index) & const_1i); type _expr24 = metal::float4(((static_cast(tmp1_) * const_4f) - const_1f), ((static_cast(tmp2_) * const_4f) - const_1f), const_0f, const_1f); - unprojected = (r_data.proj_inv * _expr24); - type _expr54 = unprojected; - out.uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr54.x, _expr54.y, _expr54.z)); + metal::float4 _expr50 = (r_data.proj_inv * _expr24); + out.uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr50.x, _expr50.y, _expr50.z)); out.position = _expr24; const auto _tmp = out; return vs_mainOutput { _tmp.position, _tmp.uv }; diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index 19e3b1070..8b197e2db 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -5,13 +5,13 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 113 +; Bound: 111 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %39 "vs_main" %32 %35 %37 -OpEntryPoint Fragment %106 "fs_main" %102 %105 -OpExecutionMode %106 OriginUpperLeft +OpEntryPoint Vertex %37 "vs_main" %30 %33 %35 +OpEntryPoint Fragment %104 "fs_main" %100 %103 +OpExecutionMode %104 OriginUpperLeft OpSource GLSL 450 OpName %11 "Data" OpMemberName %11 0 "proj_inv" @@ -21,17 +21,16 @@ OpName %15 "r_texture" OpName %18 "r_sampler" OpName %21 "tmp1" OpName %23 "tmp2" -OpName %24 "unprojected" -OpName %26 "out" -OpName %27 "VertexOutput" -OpName %32 "vertex_index" -OpName %35 "position" -OpName %37 "uv" -OpName %39 "vs_main" -OpName %39 "vs_main" -OpName %102 "uv" -OpName %106 "fs_main" -OpName %106 "fs_main" +OpName %24 "out" +OpName %25 "VertexOutput" +OpName %30 "vertex_index" +OpName %33 "position" +OpName %35 "uv" +OpName %37 "vs_main" +OpName %37 "vs_main" +OpName %100 "uv" +OpName %104 "fs_main" +OpName %104 "fs_main" OpDecorate %11 Block OpMemberDecorate %11 0 Offset 0 OpMemberDecorate %11 0 ColMajor @@ -45,11 +44,11 @@ OpDecorate %15 DescriptorSet 0 OpDecorate %15 Binding 1 OpDecorate %18 DescriptorSet 0 OpDecorate %18 Binding 2 -OpDecorate %32 BuiltIn VertexIndex -OpDecorate %35 BuiltIn Position -OpDecorate %37 Location 0 -OpDecorate %102 Location 0 -OpDecorate %105 Location 0 +OpDecorate %30 BuiltIn VertexIndex +OpDecorate %33 BuiltIn Position +OpDecorate %35 Location 0 +OpDecorate %100 Location 0 +OpDecorate %103 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -70,108 +69,105 @@ OpDecorate %105 Location 0 %20 = OpTypePointer UniformConstant %19 %18 = OpVariable %20 UniformConstant %22 = OpTypePointer Function %4 -%25 = OpTypePointer Function %13 -%28 = OpTypeVector %7 3 -%27 = OpTypeStruct %13 %28 -%29 = OpTypePointer Function %27 -%31 = OpTypeInt 32 0 -%33 = OpTypePointer Input %31 -%32 = OpVariable %33 Input -%36 = OpTypePointer Output %13 +%26 = OpTypeVector %7 3 +%25 = OpTypeStruct %13 %26 +%27 = OpTypePointer Function %25 +%29 = OpTypeInt 32 0 +%31 = OpTypePointer Input %29 +%30 = OpVariable %31 Input +%34 = OpTypePointer Output %13 +%33 = OpVariable %34 Output +%36 = OpTypePointer Output %26 %35 = OpVariable %36 Output -%38 = OpTypePointer Output %28 -%37 = OpVariable %38 Output -%40 = OpTypeFunction %2 -%55 = OpTypePointer Uniform %12 -%56 = OpConstant %4 1 -%64 = OpConstant %4 1 -%72 = OpConstant %4 1 -%80 = OpTypeMatrix %28 3 -%83 = OpConstant %4 0 -%87 = OpTypePointer Function %28 -%94 = OpConstant %4 1 -%96 = OpConstant %4 0 -%103 = OpTypePointer Input %28 -%102 = OpVariable %103 Input -%105 = OpVariable %36 Output -%110 = OpTypeSampledImage %16 -%39 = OpFunction %2 None %40 -%30 = OpLabel -%23 = OpVariable %22 Function -%26 = OpVariable %29 Function +%38 = OpTypeFunction %2 +%53 = OpTypePointer Uniform %12 +%54 = OpConstant %4 1 +%62 = OpConstant %4 1 +%70 = OpConstant %4 1 +%78 = OpTypeMatrix %26 3 +%81 = OpConstant %4 0 +%85 = OpTypePointer Function %26 +%91 = OpConstant %4 1 +%93 = OpTypePointer Function %13 +%94 = OpConstant %4 0 +%101 = OpTypePointer Input %26 +%100 = OpVariable %101 Input +%103 = OpVariable %34 Output +%108 = OpTypeSampledImage %16 +%37 = OpFunction %2 None %38 +%28 = OpLabel %21 = OpVariable %22 Function -%24 = OpVariable %25 Function -%34 = OpLoad %31 %32 -OpBranch %41 -%41 = OpLabel -%42 = OpBitcast %4 %34 -%43 = OpSDiv %4 %42 %3 -OpStore %21 %43 -%44 = OpBitcast %4 %34 -%45 = OpBitwiseAnd %4 %44 %5 -OpStore %23 %45 -%46 = OpLoad %4 %21 -%47 = OpConvertSToF %7 %46 -%48 = OpFMul %7 %47 %6 -%49 = OpFSub %7 %48 %8 -%50 = OpLoad %4 %23 -%51 = OpConvertSToF %7 %50 -%52 = OpFMul %7 %51 %6 -%53 = OpFSub %7 %52 %8 -%54 = OpCompositeConstruct %13 %49 %53 %9 %8 -%57 = OpAccessChain %55 %10 %56 -%58 = OpLoad %12 %57 -%59 = OpCompositeExtract %13 %58 0 -%60 = OpCompositeExtract %7 %59 0 -%61 = OpCompositeExtract %7 %59 1 -%62 = OpCompositeExtract %7 %59 2 -%63 = OpCompositeConstruct %28 %60 %61 %62 -%65 = OpAccessChain %55 %10 %64 -%66 = OpLoad %12 %65 -%67 = OpCompositeExtract %13 %66 1 -%68 = OpCompositeExtract %7 %67 0 -%69 = OpCompositeExtract %7 %67 1 -%70 = OpCompositeExtract %7 %67 2 -%71 = OpCompositeConstruct %28 %68 %69 %70 -%73 = OpAccessChain %55 %10 %72 -%74 = OpLoad %12 %73 -%75 = OpCompositeExtract %13 %74 2 -%76 = OpCompositeExtract %7 %75 0 -%77 = OpCompositeExtract %7 %75 1 -%78 = OpCompositeExtract %7 %75 2 -%79 = OpCompositeConstruct %28 %76 %77 %78 -%81 = OpCompositeConstruct %80 %63 %71 %79 -%82 = OpTranspose %80 %81 -%84 = OpAccessChain %55 %10 %83 -%85 = OpLoad %12 %84 -%86 = OpMatrixTimesVector %13 %85 %54 -OpStore %24 %86 -%88 = OpLoad %13 %24 -%89 = OpCompositeExtract %7 %88 0 -%90 = OpCompositeExtract %7 %88 1 -%91 = OpCompositeExtract %7 %88 2 -%92 = OpCompositeConstruct %28 %89 %90 %91 -%93 = OpMatrixTimesVector %28 %82 %92 -%95 = OpAccessChain %87 %26 %94 -OpStore %95 %93 -%97 = OpAccessChain %25 %26 %96 -OpStore %97 %54 -%98 = OpLoad %27 %26 -%99 = OpCompositeExtract %13 %98 0 -OpStore %35 %99 -%100 = OpCompositeExtract %28 %98 1 -OpStore %37 %100 +%23 = OpVariable %22 Function +%24 = OpVariable %27 Function +%32 = OpLoad %29 %30 +OpBranch %39 +%39 = OpLabel +%40 = OpBitcast %4 %32 +%41 = OpSDiv %4 %40 %3 +OpStore %21 %41 +%42 = OpBitcast %4 %32 +%43 = OpBitwiseAnd %4 %42 %5 +OpStore %23 %43 +%44 = OpLoad %4 %21 +%45 = OpConvertSToF %7 %44 +%46 = OpFMul %7 %45 %6 +%47 = OpFSub %7 %46 %8 +%48 = OpLoad %4 %23 +%49 = OpConvertSToF %7 %48 +%50 = OpFMul %7 %49 %6 +%51 = OpFSub %7 %50 %8 +%52 = OpCompositeConstruct %13 %47 %51 %9 %8 +%55 = OpAccessChain %53 %10 %54 +%56 = OpLoad %12 %55 +%57 = OpCompositeExtract %13 %56 0 +%58 = OpCompositeExtract %7 %57 0 +%59 = OpCompositeExtract %7 %57 1 +%60 = OpCompositeExtract %7 %57 2 +%61 = OpCompositeConstruct %26 %58 %59 %60 +%63 = OpAccessChain %53 %10 %62 +%64 = OpLoad %12 %63 +%65 = OpCompositeExtract %13 %64 1 +%66 = OpCompositeExtract %7 %65 0 +%67 = OpCompositeExtract %7 %65 1 +%68 = OpCompositeExtract %7 %65 2 +%69 = OpCompositeConstruct %26 %66 %67 %68 +%71 = OpAccessChain %53 %10 %70 +%72 = OpLoad %12 %71 +%73 = OpCompositeExtract %13 %72 2 +%74 = OpCompositeExtract %7 %73 0 +%75 = OpCompositeExtract %7 %73 1 +%76 = OpCompositeExtract %7 %73 2 +%77 = OpCompositeConstruct %26 %74 %75 %76 +%79 = OpCompositeConstruct %78 %61 %69 %77 +%80 = OpTranspose %78 %79 +%82 = OpAccessChain %53 %10 %81 +%83 = OpLoad %12 %82 +%84 = OpMatrixTimesVector %13 %83 %52 +%86 = OpCompositeExtract %7 %84 0 +%87 = OpCompositeExtract %7 %84 1 +%88 = OpCompositeExtract %7 %84 2 +%89 = OpCompositeConstruct %26 %86 %87 %88 +%90 = OpMatrixTimesVector %26 %80 %89 +%92 = OpAccessChain %85 %24 %91 +OpStore %92 %90 +%95 = OpAccessChain %93 %24 %94 +OpStore %95 %52 +%96 = OpLoad %25 %24 +%97 = OpCompositeExtract %13 %96 0 +OpStore %33 %97 +%98 = OpCompositeExtract %26 %96 1 +OpStore %35 %98 OpReturn OpFunctionEnd -%106 = OpFunction %2 None %40 -%101 = OpLabel -%104 = OpLoad %28 %102 -%107 = OpLoad %16 %15 -%108 = OpLoad %19 %18 -OpBranch %109 -%109 = OpLabel -%111 = OpSampledImage %110 %107 %108 -%112 = OpImageSampleImplicitLod %13 %111 %104 -OpStore %105 %112 +%104 = OpFunction %2 None %38 +%99 = OpLabel +%102 = OpLoad %26 %100 +%105 = OpLoad %16 %15 +%106 = OpLoad %19 %18 +OpBranch %107 +%107 = OpLabel +%109 = OpSampledImage %108 %105 %106 +%110 = OpImageSampleImplicitLod %13 %109 %102 +OpStore %103 %110 OpReturn OpFunctionEnd From 7d47a1b5851c70a7be157fc590cc691b8e23096d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 15 Mar 2021 01:01:36 -0400 Subject: [PATCH 0573/2212] [spv-in] re-order the functions for the IR --- src/arena.rs | 5 + src/front/spv/error.rs | 1 + src/front/spv/function.rs | 240 ++++++++++++++++++++------------------ src/front/spv/mod.rs | 40 +++++-- src/proc/validator.rs | 3 +- 5 files changed, 167 insertions(+), 122 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 35171e3f1..28560ef0e 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -151,6 +151,11 @@ impl Arena { Arena { data: Vec::new() } } + /// Extracts the inner vector. + pub fn into_inner(self) -> Vec { + self.data + } + /// Returns the current number of items stored in this arena. pub fn len(&self) -> usize { self.data.len() diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 85bb5f502..0893f9cd3 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -52,6 +52,7 @@ pub enum Error { IncompleteData, InvalidTerminator, InvalidEdgeClassification, + FunctionCallCycle(spirv::Word), // incomplete implementation error UnsupportedRowMajorMatrix, UnsupportedMatrixStride(spirv::Word), diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 3003417cb..ed804e59b 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -49,7 +49,20 @@ pub enum Terminator { } impl> super::Parser { - pub fn parse_function(&mut self, module: &mut crate::Module) -> Result<(), Error> { + // Registers a function call. It will generate a dummy handle to call, which + // gets resolved after all the functions are processed. + pub(super) fn add_call( + &mut self, + from: spirv::Word, + to: spirv::Word, + ) -> Handle { + let dummy_handle = self.dummy_functions.append(crate::Function::default()); + self.deferred_function_calls.push(to); + self.function_call_graph.add_edge(from, to, ()); + dummy_handle + } + + pub(super) fn parse_function(&mut self, module: &mut crate::Module) -> Result<(), Error> { let result_type_id = self.next()?; let fun_id = self.next()?; let _fun_control = self.next()?; @@ -115,6 +128,7 @@ impl> super::Parser { } // Read body + self.function_call_graph.add_node(fun_id); let mut flow_graph = FlowGraph::new(); // Scan the blocks and add them as nodes @@ -129,6 +143,7 @@ impl> super::Parser { let node = self.next_block( block_id, + fun_id, &mut fun.expressions, &mut fun.local_variables, &module.types, @@ -167,128 +182,125 @@ impl> super::Parser { // done let fun_handle = module.functions.append(fun); - match self.lookup_entry_point.remove(&fun_id) { - Some(ep) => { - // create a wrapping function - let mut function = crate::Function { - name: None, - arguments: Vec::new(), - result: None, - local_variables: Arena::new(), - expressions: Arena::new(), - body: Vec::new(), - }; + self.lookup_function.insert(fun_id, fun_handle); + if let Some(ep) = self.lookup_entry_point.remove(&fun_id) { + // create a wrapping function + let mut function = crate::Function { + name: None, + arguments: Vec::new(), + result: None, + local_variables: Arena::new(), + expressions: Arena::new(), + body: Vec::new(), + }; - // 1. copy the inputs from arguments to privates - for &v_id in ep.variable_ids.iter() { - let lvar = self.lookup_variable.lookup(v_id)?; - if let super::Variable::Input(ref arg) = lvar.inner { - function.body.push(crate::Statement::Store { - pointer: function - .expressions - .append(crate::Expression::GlobalVariable(lvar.handle)), - value: - function - .expressions - .append(crate::Expression::FunctionArgument( - function.arguments.len() as u32, - )), - }); - let mut arg = arg.clone(); - if ep.stage == crate::ShaderStage::Fragment { - if let Some(crate::Binding::Location(_, ref mut interpolation @ None)) = - arg.binding - { - *interpolation = Some(crate::Interpolation::Perspective); - // default - } + // 1. copy the inputs from arguments to privates + for &v_id in ep.variable_ids.iter() { + let lvar = self.lookup_variable.lookup(v_id)?; + if let super::Variable::Input(ref arg) = lvar.inner { + function.body.push(crate::Statement::Store { + pointer: function + .expressions + .append(crate::Expression::GlobalVariable(lvar.handle)), + value: function + .expressions + .append(crate::Expression::FunctionArgument( + function.arguments.len() as u32, + )), + }); + let mut arg = arg.clone(); + if ep.stage == crate::ShaderStage::Fragment { + if let Some(crate::Binding::Location(_, ref mut interpolation @ None)) = + arg.binding + { + *interpolation = Some(crate::Interpolation::Perspective); + // default } - function.arguments.push(arg); } + function.arguments.push(arg); } - // 2. call the wrapped function - function.body.push(crate::Statement::Call { - function: fun_handle, - arguments: Vec::new(), - result: None, + } + // 2. call the wrapped function + let fake_id = !(module.entry_points.len() as u32); // doesn't matter, as long as it's not a collision + let dummy_handle = self.add_call(fake_id, fun_id); + function.body.push(crate::Statement::Call { + function: dummy_handle, + arguments: Vec::new(), + result: None, + }); + + // 3. copy the outputs from privates to the result + let mut members = Vec::new(); + let mut components = Vec::new(); + for &v_id in ep.variable_ids.iter() { + let lvar = self.lookup_variable.lookup(v_id)?; + if let super::Variable::Output(ref result) = lvar.inner { + members.push(crate::StructMember { + name: None, + span: None, + ty: result.ty, + binding: result.binding.clone(), + }); + // populate just the globals first, then do `Load` in a + // separate step, so that we can get a range. + components.push( + function + .expressions + .append(crate::Expression::GlobalVariable(lvar.handle)), + ); + } + } + + let old_len = function.expressions.len(); + for component in components.iter_mut() { + *component = function.expressions.append(crate::Expression::Load { + pointer: *component, }); - - // 3. copy the outputs from privates to the result - let mut members = Vec::new(); - let mut components = Vec::new(); - for &v_id in ep.variable_ids.iter() { - let lvar = self.lookup_variable.lookup(v_id)?; - if let super::Variable::Output(ref result) = lvar.inner { - members.push(crate::StructMember { - name: None, - span: None, - ty: result.ty, - binding: result.binding.clone(), - }); - // populate just the globals first, then do `Load` in a - // separate step, so that we can get a range. - components.push( - function - .expressions - .append(crate::Expression::GlobalVariable(lvar.handle)), - ); - } - } - - let old_len = function.expressions.len(); - for component in components.iter_mut() { - *component = function.expressions.append(crate::Expression::Load { - pointer: *component, + } + match members.len() { + 0 => {} + 1 => { + let member = members.remove(0); + function.body.push(crate::Statement::Emit( + function.expressions.range_from(old_len), + )); + function.body.push(crate::Statement::Return { + value: components.first().cloned(), + }); + function.result = Some(crate::FunctionResult { + ty: member.ty, + binding: member.binding, }); } - match members.len() { - 0 => {} - 1 => { - let member = members.remove(0); - function.body.push(crate::Statement::Emit( - function.expressions.range_from(old_len), - )); - function.body.push(crate::Statement::Return { - value: components.first().cloned(), - }); - function.result = Some(crate::FunctionResult { - ty: member.ty, - binding: member.binding, - }); - } - _ => { - let ty = module.types.append(crate::Type { - name: None, - inner: crate::TypeInner::Struct { - block: false, - members, - }, - }); - let result_expr = function - .expressions - .append(crate::Expression::Compose { ty, components }); - function.body.push(crate::Statement::Emit( - function.expressions.range_from(old_len), - )); - function.body.push(crate::Statement::Return { - value: Some(result_expr), - }); - function.result = Some(crate::FunctionResult { ty, binding: None }); - } + _ => { + let ty = module.types.append(crate::Type { + name: None, + inner: crate::TypeInner::Struct { + block: false, + members, + }, + }); + let result_expr = function + .expressions + .append(crate::Expression::Compose { ty, components }); + function.body.push(crate::Statement::Emit( + function.expressions.range_from(old_len), + )); + function.body.push(crate::Statement::Return { + value: Some(result_expr), + }); + function.result = Some(crate::FunctionResult { ty, binding: None }); } + } - module.entry_points.push(crate::EntryPoint { - name: ep.name, - stage: ep.stage, - early_depth_test: ep.early_depth_test, - workgroup_size: ep.workgroup_size, - function, - }); - } - None => { - self.lookup_function.insert(fun_id, fun_handle); - } - }; + module.entry_points.push(crate::EntryPoint { + name: ep.name, + stage: ep.stage, + early_depth_test: ep.early_depth_test, + workgroup_size: ep.workgroup_size, + function, + }); + } self.lookup_expression.clear(); self.lookup_sampled_image.clear(); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 572a0f9e7..318b7f513 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -36,6 +36,7 @@ use crate::{ }; use num_traits::cast::FromPrimitive; +use petgraph::graphmap::GraphMap; use std::{convert::TryInto, num::NonZeroU32, path::PathBuf}; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ @@ -325,9 +326,14 @@ pub struct Parser { lookup_function_type: FastHashMap, lookup_function: FastHashMap>, lookup_entry_point: FastHashMap, - //Note: the key here is fully artificial, has nothing to do with the module - deferred_function_calls: FastHashMap, spirv::Word>, + //Note: each `OpFunctionCall` gets a single entry here, indexed by the + // dummy `Handle` of the call site. + deferred_function_calls: Vec, dummy_functions: Arena, + // Graph of all function calls through the module. + // It's used to sort the functions (as nodes) topologically, + // so that in the IR any called function is already known. + function_call_graph: GraphMap, options: Options, index_constants: Vec>, } @@ -353,8 +359,9 @@ impl> Parser { lookup_function_type: FastHashMap::default(), lookup_function: FastHashMap::default(), lookup_entry_point: FastHashMap::default(), - deferred_function_calls: FastHashMap::default(), + deferred_function_calls: Vec::default(), dummy_functions: Arena::new(), + function_call_graph: GraphMap::new(), options: options.clone(), index_constants: Vec::new(), } @@ -591,6 +598,7 @@ impl> Parser { fn next_block( &mut self, block_id: spirv::Word, + function_id: spirv::Word, expressions: &mut Arena, local_arena: &mut Arena, type_arena: &Arena, @@ -1318,8 +1326,7 @@ impl> Parser { } // We just need an unique handle here, nothing more. - let function = self.dummy_functions.append(crate::Function::default()); - self.deferred_function_calls.insert(function, func_id); + let function = self.add_call(function_id, func_id); let result = if self.lookup_void_type == Some(result_type_id) { None @@ -1677,7 +1684,7 @@ impl> Parser { S::Call { ref mut function, .. } => { - let fun_id = self.deferred_function_calls[function]; + let fun_id = self.deferred_function_calls[function.index()]; *function = *self.lookup_function.lookup(fun_id)?; } } @@ -1688,7 +1695,7 @@ impl> Parser { fn patch_function_calls(&self, fun: &mut crate::Function) -> Result<(), Error> { for (_, expr) in fun.expressions.iter_mut() { if let crate::Expression::Call(ref mut function) = *expr { - let fun_id = self.deferred_function_calls[function]; + let fun_id = self.deferred_function_calls[function.index()]; *function = *self.lookup_function.lookup(fun_id)?; } } @@ -1724,6 +1731,7 @@ impl> Parser { self.dummy_functions = Arena::new(); self.lookup_function.clear(); + self.function_call_graph.clear(); loop { use spirv::Op; @@ -1779,6 +1787,24 @@ impl> Parser { } log::info!("Patching..."); + { + use std::mem::take; + let mut nodes = petgraph::algo::toposort(&self.function_call_graph, None) + .map_err(|cycle| Error::FunctionCallCycle(cycle.node_id()))?; + nodes.reverse(); // we need dominated first + let mut functions = take(&mut module.functions).into_inner(); + for fun_id in nodes { + if fun_id > !(functions.len() as u32) { + // skip all the fake IDs registered for the entry points + continue; + } + let handle = self.lookup_function.get_mut(&fun_id).unwrap(); + // take out the function from the old array + let fun = take(&mut functions[handle.index()]); + // add it to the newly formed arena, and adjust the lookup + *handle = module.functions.append(fun); + } + } // patch all the function calls for (_, fun) in module.functions.iter_mut() { self.patch_function_calls(fun)?; diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 1ce08d2e4..90fad50a2 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -967,7 +967,8 @@ impl Validator { crate::Expression::Access { base, .. } | crate::Expression::AccessIndex { base, .. } => current = base, crate::Expression::LocalVariable(_) - | crate::Expression::GlobalVariable(_) => break, + | crate::Expression::GlobalVariable(_) + | crate::Expression::FunctionArgument(_) => break, _ => return Err(FunctionError::InvalidStorePointer(current)), } } From 0945889dd7244adbcfdc8b2e66a354e590683ef4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 15 Mar 2021 10:25:10 -0400 Subject: [PATCH 0574/2212] [msl] filter out entry points based on the bindings --- src/back/msl/mod.rs | 18 ++++++++++++------ src/back/msl/writer.rs | 25 +++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index f95ff8f3c..177a94596 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -73,8 +73,6 @@ pub enum Error { Utf8(#[from] FromUtf8Error), #[error(transparent)] Type(#[from] TypifyError), - #[error("bind source for {0:?} is missing from the map")] - MissingBindTarget(BindSource), #[error("bind target {0:?} is empty")] UnimplementedBindTarget(BindTarget), #[error("composing of {0:?} is not implemented yet")] @@ -89,6 +87,12 @@ pub enum Error { Validation, } +#[derive(Debug, thiserror::Error)] +pub enum EntryPointError { + #[error("bind source for {0:?} is missing from the map")] + MissingBinding(BindSource), +} + #[derive(Clone, Copy, Debug)] enum LocationMode { VertexInput, @@ -154,7 +158,7 @@ impl Options { &self, stage: crate::ShaderStage, res_binding: &crate::ResourceBinding, - ) -> Result { + ) -> Result { let source = BindSource { stage, group: res_binding.group, @@ -166,7 +170,7 @@ impl Options { prefix: "fake", index: 0, }), - None => Err(Error::MissingBindTarget(source)), + None => Err(EntryPointError::MissingBinding(source)), } } } @@ -232,8 +236,10 @@ impl ResolvedBinding { /// for the use of the result. pub struct TranslationInfo { /// Mapping of the entry point names. Each item in the array - /// corresponds to an entry point in `module.entry_points.iter()`. - pub entry_point_names: Vec, + /// corresponds to an entry point index. + /// + ///Note: Some entry points may fail translation because of missing bindings. + pub entry_point_names: Vec>, } pub fn write_string( diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 39d3e1e19..97e563fc2 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1179,6 +1179,27 @@ impl Writer { for (ep_index, ep) in module.entry_points.iter().enumerate() { let fun = &ep.function; let fun_info = analysis.get_entry_point(ep_index); + // skip this entry point if any global bindings are missing + if !options.fake_missing_bindings { + if let Some(err) = module + .global_variables + .iter() + .find_map(|(var_handle, var)| { + if !fun_info[var_handle].is_empty() { + if let Some(ref br) = var.binding { + if let Err(e) = options.resolve_global_binding(ep.stage, br) { + return Some(e); + } + } + } + None + }) + { + info.entry_point_names.push(Err(err)); + continue; + } + } + self.typifier.resolve_all( &fun.expressions, &module.types, @@ -1192,7 +1213,7 @@ impl Writer { )?; let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; - info.entry_point_names.push(fun_name.clone()); + info.entry_point_names.push(Ok(fun_name.clone())); let stage_out_name = format!("{}Output", fun_name); let stage_in_name = format!("{}Input", fun_name); @@ -1340,7 +1361,7 @@ impl Writer { write!(self.out, "{} ", separator)?; tyvar.try_fmt(&mut self.out)?; if let Some(ref binding) = var.binding { - let resolved = options.resolve_global_binding(ep.stage, binding)?; + let resolved = options.resolve_global_binding(ep.stage, binding).unwrap(); resolved.try_fmt_decorated(&mut self.out, "")?; } if let Some(value) = var.init { From 889e487b629bc6499999f8d6485af9020b16f0e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Tal=C4=8D=C3=ADk?= Date: Mon, 15 Mar 2021 16:04:32 +0100 Subject: [PATCH 0575/2212] spv-in: fix classification of back edges fix clippy another fix --- src/front/spv/flow.rs | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 27a72ddf9..9eb139b28 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -81,6 +81,14 @@ impl FlowGraph { continue_block_index, ControlFlowEdgeType::ForwardContinue, ); + + // Back edge + self.flow[continue_block_index].ty = Some(ControlFlowNodeType::Back); + self.flow.add_edge( + continue_block_index, + source_node_index, + ControlFlowEdgeType::Back, + ); } } @@ -90,11 +98,13 @@ impl FlowGraph { Terminator::Branch { target_id } => { let target_node_index = block_to_node[&target_id]; - self.flow.add_edge( - source_node_index, - target_node_index, - ControlFlowEdgeType::Forward, - ); + if self.flow[source_node_index].ty != Some(ControlFlowNodeType::Back) { + self.flow.add_edge( + source_node_index, + target_node_index, + ControlFlowEdgeType::Forward, + ); + } } Terminator::BranchConditional { true_id, false_id, .. @@ -158,14 +168,6 @@ impl FlowGraph { continue; } - // Back - if self.flow[node_target_index].ty == Some(ControlFlowNodeType::Loop) - && self.flow[node_source_index].id > self.flow[node_target_index].id - { - self.flow[node_source_index].ty = Some(ControlFlowNodeType::Back); - self.flow[edge_index] = ControlFlowEdgeType::Back; - } - let mut target_incoming_edges = self .flow .neighbors_directed(node_target_index, Direction::Incoming) From 08eaad89dbabd1be1f9da876d7756e1bf1d46108 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 15 Mar 2021 22:08:58 -0400 Subject: [PATCH 0576/2212] Implement default layout in the IR and WGSL --- src/back/spv/writer.rs | 10 ++---- src/front/glsl/parser.rs | 5 ++- src/front/spv/function.rs | 3 +- src/front/spv/mod.rs | 3 +- src/front/wgsl/mod.rs | 21 +++++++----- src/front/wgsl/tests.rs | 6 +++- src/lib.rs | 6 +++- src/proc/layouter.rs | 70 ++++++++++++++++++++++++-------------- src/proc/validator.rs | 12 +++---- tests/out/collatz.ron.snap | 3 +- tests/out/shadow.ron.snap | 15 +++++--- 11 files changed, 96 insertions(+), 58 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index db143edab..ff2be31b9 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -858,18 +858,14 @@ impl Writer { let mut current_offset = 0; let mut member_ids = Vec::with_capacity(members.len()); for (index, member) in members.iter().enumerate() { - let layout = self.layouter.resolve(member.ty); - current_offset += layout.pad(current_offset); + let (placement, _) = self.layouter.member_placement(current_offset, member); self.annotations.push(Instruction::member_decorate( id, index as u32, spirv::Decoration::Offset, - &[current_offset], + &[placement.start], )); - current_offset += match member.span { - Some(span) => span.get(), - None => layout.size, - }; + current_offset = placement.end; if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = member.name { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 5efd1076e..4255ec495 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -725,9 +725,12 @@ pomelo! { if let Some(ty) = t { sdl.iter().map(|name| StructMember { name: Some(name.clone()), - span: None, ty, binding: None, //TODO + //TODO: if the struct is a uniform struct, these values have to reflect + // std140 layout. Otherwise, std430. + size: None, + align: None, }).collect() } else { return Err(ErrorKind::SemanticError("Struct member can't be void".into())) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index ed804e59b..8bd683a1b 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -237,9 +237,10 @@ impl> super::Parser { if let super::Variable::Output(ref result) = lvar.inner { members.push(crate::StructMember { name: None, - span: None, ty: result.ty, binding: result.binding.clone(), + size: None, + align: None, }); // populate just the globals first, then do `Load` in a // separate step, so that we can get a range. diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 318b7f513..9e35bd5f8 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2369,9 +2369,10 @@ impl> Parser { host_shared |= decor.offset.is_some(); members.push(crate::StructMember { name: decor.name, - span: None, //TODO ty, binding: None, + size: None, //TODO + align: None, }); } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 182b16e7b..7586dc1af 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -107,6 +107,8 @@ pub enum Error<'a> { UnknownConservativeDepth(&'a str), #[error("array stride must not be 0")] ZeroStride, + #[error("struct member size or array must not be 0")] + ZeroSizeOrAlign, #[error("not a composite type: {0:?}")] NotCompositeType(Handle), #[error("Input/output binding is not consistent: location {0:?}, built-in {1:?} and interpolation {2:?}")] @@ -1502,7 +1504,7 @@ impl Parser { let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; loop { - let mut span = 0; + let (mut size, mut align) = (None, None); let mut bind_parser = BindingParser::default(); if lexer.skip(Token::DoubleParen('[')) { self.scopes.push(Scope::Decoration); @@ -1517,17 +1519,19 @@ impl Parser { } (Token::Word(word), _) if ready => { match word { - "span" => { + "size" => { lexer.expect(Token::Paren('('))?; - //Note: 0 is not handled - span = lexer.next_uint_literal()?; + let value = lexer.next_uint_literal()?; lexer.expect(Token::Paren(')'))?; + size = + Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign)?); } - "offset" => { - // skip - only here for parsing compatibility + "align" => { lexer.expect(Token::Paren('('))?; - let _offset = lexer.next_uint_literal()?; + let value = lexer.next_uint_literal()?; lexer.expect(Token::Paren(')'))?; + align = + Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign)?); } _ => bind_parser.parse(lexer, word)?, } @@ -1550,9 +1554,10 @@ impl Parser { members.push(crate::StructMember { name: Some(name.to_owned()), - span: NonZeroU32::new(span), ty, binding: bind_parser.finish()?, + size, + align, }); } } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 847e3dea7..fbad55201 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -70,7 +70,11 @@ fn parse_struct() { parse_str( " [[block]] struct Foo { x: i32; }; - struct Bar { [[span(16)]] x: vec2; }; + struct Bar { + [[size(16)]] x: vec2; + [[align(16)]] y: f32; + [[size(32), align(8)]] z: vec3; + }; struct Empty {}; var s: [[access(read_write)]] Foo; ", diff --git a/src/lib.rs b/src/lib.rs index ebca7842a..52de57311 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -238,10 +238,14 @@ pub enum Interpolation { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct StructMember { pub name: Option, - pub span: Option, + /// Type of the field. pub ty: Handle, /// For I/O structs, defines the binding. pub binding: Option, + /// Overrides the size computed off the type. + pub size: Option, + /// Overrides the alignment computed off the type. + pub align: Option, } /// The number of dimensions an image has. diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 8512e96d5..48056d310 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -1,5 +1,5 @@ use crate::arena::Arena; -use std::num::NonZeroU32; +use std::{num::NonZeroU32, ops}; pub type Alignment = NonZeroU32; @@ -10,17 +10,9 @@ pub struct TypeLayout { pub alignment: Alignment, } -impl TypeLayout { - /// Return padding to this type given an offset. - pub fn pad(&self, offset: u32) -> u32 { - match offset & self.alignment.get() { - 0 => 0, - other => self.alignment.get() - other, - } - } -} - /// Helper processor that derives the sizes of all types. +/// It uses the default layout algorithm/table, described in +/// https://github.com/gpuweb/gpuweb/issues/1393 #[derive(Debug, Default)] pub struct Layouter { layouts: Vec, @@ -33,6 +25,29 @@ impl Layouter { this } + pub fn round_up(alignment: NonZeroU32, offset: u32) -> u32 { + match offset & alignment.get() { + 0 => offset, + other => offset + alignment.get() - other, + } + } + + pub fn member_placement( + &self, + offset: u32, + member: &crate::StructMember, + ) -> (ops::Range, NonZeroU32) { + let layout = self.layouts[member.ty.index()]; + let alignment = member.align.unwrap_or(layout.alignment); + let start = Self::round_up(alignment, offset); + let end = start + + match member.size { + Some(size) => size.get(), + None => layout.size, + }; + (start..end, alignment) + } + pub fn initialize(&mut self, types: &Arena, constants: &Arena) { use crate::TypeInner as Ti; @@ -51,8 +66,10 @@ impl Layouter { width, } => TypeLayout { size: (size as u8 * width) as u32, - //TODO: reconsider if this needs to match the size - alignment: Alignment::new(width as u32).unwrap(), + alignment: { + let count = if size >= crate::VectorSize::Tri { 4 } else { 2 }; + Alignment::new((count * width) as u32).unwrap() + }, }, Ti::Matrix { columns, @@ -60,7 +77,10 @@ impl Layouter { width, } => TypeLayout { size: (columns as u8 * rows as u8 * width) as u32, - alignment: Alignment::new((columns as u8 * width) as u32).unwrap(), + alignment: { + let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; + Alignment::new((count * width) as u32).unwrap() + }, }, Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { size: 4, @@ -83,11 +103,15 @@ impl Layouter { } => value as u32, ref other => unreachable!("Unexpected array size {:?}", other), }, - crate::ArraySize::Dynamic => 1, + crate::ArraySize::Dynamic => 0, }; let stride = match stride { Some(value) => value, - None => Alignment::new(self.layouts[base.index()].size.max(1)).unwrap(), + None => { + let layout = &self.layouts[base.index()]; + let stride = Self::round_up(layout.alignment, layout.size); + Alignment::new(stride).unwrap() + } }; TypeLayout { size: count * stride.get(), @@ -101,18 +125,12 @@ impl Layouter { let mut total = 0; let mut biggest_alignment = Alignment::new(1).unwrap(); for member in members { - let member_layout = self.layouts[member.ty.index()]; - biggest_alignment = biggest_alignment.max(member_layout.alignment); - // align up first - total += member_layout.pad(total); - // then add the size - total += match member.span { - Some(span) => span.get(), - None => member_layout.size, - }; + let (placement, alignment) = self.member_placement(total, member); + biggest_alignment = biggest_alignment.max(alignment); + total = placement.end; } TypeLayout { - size: total, + size: Self::round_up(biggest_alignment, total), alignment: biggest_alignment, } } diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 90fad50a2..2d198237a 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -555,7 +555,11 @@ impl Validator { } TypeFlags::SIZED //TODO: `DATA`? } - Ti::Array { base, size, stride } => { + Ti::Array { + base, + size, + stride: _, + } => { if base >= handle { return Err(TypeError::UnresolvedBase(base)); } @@ -596,11 +600,7 @@ impl Validator { } crate::ArraySize::Dynamic => TypeFlags::empty(), }; - let base_mask = if stride.is_none() { - TypeFlags::INTERFACE - } else { - TypeFlags::HOST_SHARED | TypeFlags::INTERFACE - }; + let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; TypeFlags::DATA | (base_flags & base_mask) | sized_flag } Ti::Struct { block, ref members } => { diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap index 5b3a5eca4..e4e9224c7 100644 --- a/tests/out/collatz.ron.snap +++ b/tests/out/collatz.ron.snap @@ -26,9 +26,10 @@ expression: output members: [ ( name: Some("data"), - span: None, ty: 2, binding: None, + size: None, + align: None, ), ], ), diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index e1276ca7b..cda0423ff 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -110,9 +110,10 @@ expression: output members: [ ( name: Some("num_lights"), - span: None, ty: 13, binding: None, + size: None, + align: None, ), ], ), @@ -153,21 +154,24 @@ expression: output members: [ ( name: Some("proj"), - span: None, ty: 18, binding: None, + size: None, + align: None, ), ( name: Some("pos"), - span: None, ty: 4, binding: None, + size: None, + align: None, ), ( name: Some("color"), - span: None, ty: 4, binding: None, + size: None, + align: None, ), ], ), @@ -187,9 +191,10 @@ expression: output members: [ ( name: Some("data"), - span: None, ty: 20, binding: None, + size: None, + align: None, ), ], ), From 7de42d6f68631534da36fd2547bdfdaa6e73be17 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 15 Mar 2021 22:28:52 -0400 Subject: [PATCH 0577/2212] Don't panic too fast on failed analysis --- bin/convert.rs | 41 ++++++++++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/bin/convert.rs b/bin/convert.rs index 2e687219c..121c2a371 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -20,18 +20,22 @@ trait PrettyResult { fn unwrap_pretty(self) -> Self::Target; } +fn print_err(error: impl Error) { + println!("{}:", error); + let mut e = error.source(); + while let Some(source) = e { + println!("\t{}", source); + e = source.source(); + } +} + impl PrettyResult for Result { type Target = T; fn unwrap_pretty(self) -> T { match self { Result::Ok(value) => value, Result::Err(error) => { - println!("{}:", error); - let mut e = error.source(); - while let Some(source) = e { - println!("\t{}", source); - e = source.source(); - } + print_err(error); std::process::exit(1); } } @@ -166,6 +170,16 @@ fn main() { } }; + // validate the IR + #[allow(unused_variables)] + let analysis = match naga::proc::Validator::new().validate(&module) { + Ok(analysis) => Some(analysis), + Err(error) => { + print_err(error); + None + } + }; + let output_path = match output_path { Some(ref string) => string, None => { @@ -174,12 +188,6 @@ fn main() { } }; - // validate the IR - #[allow(unused_variables)] - let analysis = naga::proc::Validator::new() - .validate(&module) - .unwrap_pretty(); - match Path::new(output_path) .extension() .expect("Output has no extension?") @@ -189,14 +197,16 @@ fn main() { #[cfg(feature = "msl-out")] "metal" => { use naga::back::msl; - let (msl, _) = msl::write_string(&module, &analysis, ¶ms.msl).unwrap_pretty(); + let (msl, _) = + msl::write_string(&module, analysis.as_ref().unwrap(), ¶ms.msl).unwrap_pretty(); fs::write(output_path, msl).unwrap(); } #[cfg(feature = "spv-out")] "spv" => { use naga::back::spv; - let spv = spv::write_vec(&module, &analysis, ¶ms.spv).unwrap_pretty(); + let spv = + spv::write_vec(&module, analysis.as_ref().unwrap(), ¶ms.spv).unwrap_pretty(); let bytes = spv .iter() .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { @@ -225,7 +235,8 @@ fn main() { .unwrap(); let mut writer = - glsl::Writer::new(file, &module, &analysis, ¶ms.glsl).unwrap_pretty(); + glsl::Writer::new(file, &module, analysis.as_ref().unwrap(), ¶ms.glsl) + .unwrap_pretty(); writer .write() From 196523de7820d4907a14bd22517c4d572d26b0be Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 15 Mar 2021 22:29:00 -0400 Subject: [PATCH 0578/2212] Add v0.4 changelog --- CHANGELOG.md | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4081989bc..c23cb5aae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,41 @@ # Change Log -## v0.3.1 (2021-01-31) +## v0.4 (TBD) + - development release for wgpu-0.8 + - API: + - expressions are explicitly emitted with `Statement::Emit` + - entry points have inputs in arguments and outputs in the result type + - `input`/`output` storage classes are gone, but `push_constant` is added + - `Interpolation` is moved into `Binding::Location` variant + - real pointer semantics with required `Expression::Load` + - `TypeInner::ValuePointer` is added + - image query expressions are added + - new `Statement::ImageStore` + - all function calls are `Statement::Call` + - `GlobalUse` is moved out into processing + - field layout is controlled by `size` and `alignment` overrides, based on a default layout + - `Header` is removed + - entry points are an array instead of a map + - Infrastructure: + - control flow uniformity analysis + - texture-sampler combination gathering + - `CallGraph` processor is moved out into `glsl` backend + - `Interface` is removed + - statement tree and constants are validated + - code linting is more strict for matches + - new GraphViz `dot` backend for pretty visualization of the IR + - `convert` is default a binary target, published with the crate + +### v0.3.2 (2021-02-15) + - fix logical expression types + - fix _FragDepth_ semantics + - spv-in: + - derive block status of structures + - spv-out: + - add lots of missing math functions + - implement discard + +### v0.3.1 (2021-01-31) - wgsl: - support constant array sizes - spv-out: From 2b888e4c091268a78cea414d677af40c241e3e43 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Mar 2021 17:08:51 -0400 Subject: [PATCH 0579/2212] Detect the forward function calls --- src/proc/analyzer.rs | 13 +++++++++++-- src/proc/validator.rs | 6 ++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 81d872eff..843a827aa 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -209,6 +209,8 @@ pub enum UniformityDisruptor { pub enum AnalysisError { #[error("Expression {0:?} is not a global variable!")] ExpectedGlobalVariable(crate::Expression), + #[error("Called function {0:?} that hasn't been declared in the IR yet")] + ForwardCall(Handle), #[error( "Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}" )] @@ -478,7 +480,12 @@ impl FunctionInfo { non_uniform_result: self.add_ref(expr), requirement: None, }, - E::Call(function) => self.process_call(&other_functions[function.index()]).result, + E::Call(function) => { + let fun = other_functions + .get(function.index()) + .ok_or(AnalysisError::ForwardCall(function))?; + self.process_call(fun).result + } E::ArrayLength(expr) => Uniformity { non_uniform_result: self.add_ref_impl(expr, GlobalUse::QUERY), requirement: None, @@ -630,7 +637,9 @@ impl FunctionInfo { for &argument in arguments { let _ = self.add_ref(argument); } - let info = &other_functions[function.index()]; + let info = other_functions + .get(function.index()) + .ok_or(AnalysisError::ForwardCall(function))?; self.process_call(info) } }; diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 2d198237a..327c0ac6b 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -158,7 +158,9 @@ pub enum ExpressionError { #[derive(Clone, Debug, Error)] pub enum CallError { #[error("Bad function")] - Function, + InvalidFunction, + #[error("The callee is declared after the caller")] + ForwardDeclaredFunction, #[error("Argument {index} expression is invalid")] Argument { index: usize, @@ -782,7 +784,7 @@ impl Validator { let fun = context .functions .try_get(function) - .ok_or(CallError::Function)?; + .ok_or(CallError::InvalidFunction)?; if fun.arguments.len() != arguments.len() { return Err(CallError::ArgumentCount { required: fun.arguments.len(), From 259a56761f1439f2b687b154fc6b23ddb008f15f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Mar 2021 17:10:01 -0400 Subject: [PATCH 0580/2212] Consider dynamic arrays to have at least 1 element for the layout --- src/proc/layouter.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 48056d310..ce798bc88 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -103,7 +103,8 @@ impl Layouter { } => value as u32, ref other => unreachable!("Unexpected array size {:?}", other), }, - crate::ArraySize::Dynamic => 0, + // A dynamically-sized array has to have at least one element + crate::ArraySize::Dynamic => 1, }; let stride = match stride { Some(value) => value, From c5fe1d53c7d9d82117663b504f39ffe233f69a04 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Mar 2021 21:47:14 -0400 Subject: [PATCH 0581/2212] [dot] function calls --- src/back/dot/mod.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index cf5382290..401635248 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -17,6 +17,7 @@ struct StatementGraph { flow: Vec<(usize, usize, &'static str)>, dependencies: Vec<(usize, Handle, &'static str)>, emits: Vec<(usize, Handle)>, + calls: Vec<(usize, Handle)>, } impl StatementGraph { @@ -105,7 +106,7 @@ impl StatementGraph { "ImageStore" } S::Call { - function: _, + function, ref arguments, result, } => { @@ -115,7 +116,7 @@ impl StatementGraph { if let Some(expr) = result { self.emits.push((id, expr)); } - //TODO: link to function + self.calls.push((id, function)); "Call" } }; @@ -400,6 +401,15 @@ fn write_fun(output: &mut String, prefix: String, fun: &crate::Function) -> Resu to.index(), )?; } + for (from, function) in sg.calls { + writeln!( + output, + "\t\t{}_s{} -> f{}_s0", + prefix, + from, + function.index(), + )?; + } Ok(()) } @@ -427,7 +437,12 @@ pub fn write(module: &crate::Module) -> Result { for (handle, fun) in module.functions.iter() { let prefix = format!("f{}", handle.index()); writeln!(output, "\tsubgraph cluster_{} {{", prefix)?; - writeln!(output, "\t\tlabel=\"Function/'{}'\"", name(&fun.name))?; + writeln!( + output, + "\t\tlabel=\"Function{:?}/'{}'\"", + handle, + name(&fun.name) + )?; write_fun(&mut output, prefix, fun)?; writeln!(output, "\t}}")?; } From 9846a8517426b3b6fcd73012e961ea23c8c0bee2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Mar 2021 21:47:29 -0400 Subject: [PATCH 0582/2212] [spv-in] patch calls from the entry points --- src/front/spv/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 9e35bd5f8..bac5cd008 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1809,8 +1809,9 @@ impl> Parser { for (_, fun) in module.functions.iter_mut() { self.patch_function_calls(fun)?; } - // Note: we aren't patching the entry point functions, because they are simply - // wrappers behind real functions, and are already resolved. + for ep in module.entry_points.iter_mut() { + self.patch_function_calls(&mut ep.function)?; + } // Check all the images and samplers to have consistent comparison property. for (handle, flags) in self.handle_sampling.drain() { From e715bda507f2809f84e1196ad8918743b0ecaf7b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Mar 2021 22:30:35 -0400 Subject: [PATCH 0583/2212] [msl-out] implement composing arrays and structs --- src/back/msl/writer.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 97e563fc2..86b3b5a09 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -280,6 +280,16 @@ impl Writer { )?; self.put_call_parameters(components.iter().cloned(), context)?; } + crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { + write!(self.out, "{} {{", &self.names[&NameKey::Type(ty)])?; + for (i, &component) in components.iter().enumerate() { + if i != 0 { + write!(self.out, ", ")?; + } + self.put_expression(component, context)?; + } + write!(self.out, "}}")?; + } _ => return Err(Error::UnsupportedCompose(ty)), } } From e3818bb23699711829892a5683f2403ee25c44e7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Mar 2021 22:30:51 -0400 Subject: [PATCH 0584/2212] [spv-in] fix treating OpPhi variables as pointers --- src/front/spv/flow.rs | 3 +-- src/front/spv/mod.rs | 33 +++++++++++++++++++++------------ 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 9eb139b28..3a96b5405 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -202,13 +202,12 @@ impl FlowGraph { for node_index in self.flow.node_indices() { let phis = std::mem::replace(&mut self.flow[node_index].phis, Vec::new()); for phi in phis.iter() { - let phi_var = &lookup_expression[&phi.id]; for &(variable_id, parent_id) in phi.variables.iter() { let variable = &lookup_expression[&variable_id]; let parent_node = &mut self.flow[self.block_to_node[&parent_id]]; parent_node.block.push(crate::Statement::Store { - pointer: phi_var.handle, + pointer: phi.pointer, value: variable.handle, }); } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index bac5cd008..234280e4f 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -94,11 +94,13 @@ impl crate::TypeInner { } /// OpPhi instruction. -#[derive(Clone, Default, Debug)] +#[derive(Debug)] struct PhiInstruction { /// SPIR-V's ID. id: u32, + pointer: Handle, + /// Tuples of (variable, parent). variables: Vec<(u32, u32)>, } @@ -684,25 +686,32 @@ impl> Parser { ty: self.lookup_type.lookup(result_type_id)?.handle, init: None, }); - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions - .append(crate::Expression::LocalVariable(var_handle)), - type_id: result_type_id, - }, - ); + let pointer = expressions.append(crate::Expression::LocalVariable(var_handle)); + let in_count = (inst.wc - 3) / 2; let mut phi = PhiInstruction { id: result_id, - ..Default::default() + pointer, + variables: Vec::with_capacity(in_count as usize), }; - for _ in 0..(inst.wc - 3) / 2 { - phi.variables.push((self.next()?, self.next()?)); + for _ in 0..in_count { + let source_id = self.next()?; + let value = self.next()?; + phi.variables.push((source_id, value)); } phis.push(phi); emitter.start(expressions); + + // Associate the lookup with an actual value, which is emitted + // into the current block. + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(crate::Expression::Load { pointer }), + type_id: result_type_id, + }, + ); } Op::AccessChain => { struct AccessExpression { From 665ac49a01be65251bdf7a41b9a77dc494aba1f1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 16 Mar 2021 23:27:57 -0400 Subject: [PATCH 0585/2212] Show expression uniformity in the Dot backend --- bin/convert.rs | 2 +- src/back/dot/mod.rs | 31 ++++++++++++++++++++++++------- tests/out/quad.dot.snap | 18 +++++++++--------- tests/snapshots.rs | 2 +- 4 files changed, 35 insertions(+), 18 deletions(-) diff --git a/bin/convert.rs b/bin/convert.rs index 121c2a371..89ce8759e 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -249,7 +249,7 @@ fn main() { #[cfg(feature = "dot-out")] "dot" => { use naga::back::dot; - let output = dot::write(&module).unwrap(); + let output = dot::write(&module, analysis.as_ref()).unwrap(); fs::write(output_path, output).unwrap(); } other => { diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 401635248..899605840 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -4,7 +4,10 @@ * of IR inspection and debugging. !*/ -use crate::arena::Handle; +use crate::{ + arena::Handle, + proc::analyzer::{Analysis, FunctionInfo}, +}; use std::{ borrow::Cow, @@ -140,7 +143,12 @@ const COLORS: &[&str] = &[ "#d9d9d9", ]; -fn write_fun(output: &mut String, prefix: String, fun: &crate::Function) -> Result<(), FmtError> { +fn write_fun( + output: &mut String, + prefix: String, + fun: &crate::Function, + info: Option<&FunctionInfo>, +) -> Result<(), FmtError> { enum Payload<'a> { Arguments(&'a [Handle]), Local(Handle), @@ -312,11 +320,18 @@ fn write_fun(output: &mut String, prefix: String, fun: &crate::Function) -> Resu (Cow::Borrowed("ArrayLength"), 7) } }; + + // give uniform expressions an outline + let color_attr = match info { + Some(info) if info[handle].uniformity.non_uniform_result.is_none() => "fillcolor", + _ => "color", + }; writeln!( output, - "\t\t{}_e{} [ color=\"{}\" label=\"{:?} {}\" ]", + "\t\t{}_e{} [ {}=\"{}\" label=\"{:?} {}\" ]", prefix, handle.index(), + color_attr, COLORS[color_id], handle, label, @@ -354,7 +369,7 @@ fn write_fun(output: &mut String, prefix: String, fun: &crate::Function) -> Resu Some(Payload::Global(h)) => { writeln!( output, - "\t\tg{} -> {}_e{} [color=gray]", + "\t\tg{} -> {}_e{} [fillcolor=gray]", h.index(), prefix, handle.index(), @@ -414,7 +429,7 @@ fn write_fun(output: &mut String, prefix: String, fun: &crate::Function) -> Resu Ok(()) } -pub fn write(module: &crate::Module) -> Result { +pub fn write(module: &crate::Module, analysis: Option<&Analysis>) -> Result { use std::fmt::Write as _; let mut output = String::new(); @@ -443,14 +458,16 @@ pub fn write(module: &crate::Module) -> Result { handle, name(&fun.name) )?; - write_fun(&mut output, prefix, fun)?; + let info = analysis.map(|a| &a[handle]); + write_fun(&mut output, prefix, fun, info)?; writeln!(output, "\t}}")?; } for (ep_index, ep) in module.entry_points.iter().enumerate() { let prefix = format!("ep{}", ep_index); writeln!(output, "\tsubgraph cluster_{} {{", prefix)?; writeln!(output, "\t\tlabel=\"{:?}/'{}'\"", ep.stage, ep.name)?; - write_fun(&mut output, prefix, &ep.function)?; + let info = analysis.map(|a| a.get_entry_point(ep_index)); + write_fun(&mut output, prefix, &ep.function, info)?; writeln!(output, "\t}}")?; } diff --git a/tests/out/quad.dot.snap b/tests/out/quad.dot.snap index 6a564fad2..b839e856d 100644 --- a/tests/out/quad.dot.snap +++ b/tests/out/quad.dot.snap @@ -12,7 +12,7 @@ digraph Module { label="Vertex/'main'" node [ style=filled ] ep0_l0 [ shape=hexagon label="[1] 'out'" ] - ep0_e0 [ color="#ffffb3" label="[1] Constant" ] + ep0_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] ep0_e1 [ color="#8dd3c7" label="[2] Argument[0]" ] ep0_e2 [ color="#8dd3c7" label="[3] Argument[1]" ] ep0_e3 [ color="#8dd3c7" label="[4] Local" ] @@ -24,8 +24,8 @@ digraph Module { ep0_e6 [ color="#fdb462" label="[7] Multiply" ] ep0_e1 -> ep0_e6 [ label="right" ] ep0_e0 -> ep0_e6 [ label="left" ] - ep0_e7 [ color="#ffffb3" label="[8] Constant" ] - ep0_e8 [ color="#ffffb3" label="[9] Constant" ] + ep0_e7 [ fillcolor="#ffffb3" label="[8] Constant" ] + ep0_e8 [ fillcolor="#ffffb3" label="[9] Constant" ] ep0_e9 [ color="#bebada" label="[10] Compose" ] { ep0_e6 ep0_e7 ep0_e8 } -> ep0_e9 ep0_e10 [ color="#fb8072" label="[11] Load" ] @@ -59,11 +59,11 @@ digraph Module { subgraph cluster_ep1 { label="Fragment/'main'" node [ style=filled ] - ep1_e0 [ color="#ffffb3" label="[1] Constant" ] - ep1_e1 [ color="#ffffb3" label="[2] Global" ] - g1 -> ep1_e1 [color=gray] - ep1_e2 [ color="#ffffb3" label="[3] Global" ] - g0 -> ep1_e2 [color=gray] + ep1_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] + ep1_e1 [ fillcolor="#ffffb3" label="[2] Global" ] + g1 -> ep1_e1 [fillcolor=gray] + ep1_e2 [ fillcolor="#ffffb3" label="[3] Global" ] + g0 -> ep1_e2 [fillcolor=gray] ep1_e3 [ color="#8dd3c7" label="[4] Argument[0]" ] ep1_e4 [ color="#80b1d3" label="[5] ImageSample" ] ep1_e1 -> ep1_e4 [ label="sampler" ] @@ -71,7 +71,7 @@ digraph Module { ep1_e3 -> ep1_e4 [ label="coordinate" ] ep1_e5 [ color="#8dd3c7" label="[6] AccessIndex[3]" ] ep1_e4 -> ep1_e5 [ label="base" ] - ep1_e6 [ color="#ffffb3" label="[7] Constant" ] + ep1_e6 [ fillcolor="#ffffb3" label="[7] Constant" ] ep1_e7 [ color="#fdb462" label="[8] Equal" ] ep1_e6 -> ep1_e7 [ label="right" ] ep1_e5 -> ep1_e7 [ label="left" ] diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 8d36b6951..225042ef7 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -106,7 +106,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "dot-out")] { if targets.contains(Targets::DOT) { - let string = naga::back::dot::write(module).unwrap(); + let string = naga::back::dot::write(module, Some(&analysis)).unwrap(); with_snapshot_settings(|| { insta::assert_snapshot!(format!("{}.dot", name), string); }); From a17ae022c676dc4ef6f04a49663f6b0c59e1e72a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 17 Mar 2021 00:45:34 -0400 Subject: [PATCH 0586/2212] Make analysis errors carry the function handle --- src/arena.rs | 2 +- src/front/spv/mod.rs | 3 --- src/proc/analyzer.rs | 48 +++++++++++++++++++++++++++++++------------- 3 files changed, 35 insertions(+), 18 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 28560ef0e..af3fba55d 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -98,7 +98,7 @@ impl Clone for Range { } impl fmt::Debug for Range { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "{}..{}", self.inner.start, self.inner.end) + write!(formatter, "[{}..{}]", self.inner.start + 1, self.inner.end) } } impl Iterator for Range { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 234280e4f..bf244bfb1 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -453,9 +453,6 @@ impl> Parser { spirv::Decoration::Flat => { dec.interpolation = Some(crate::Interpolation::Flat); } - spirv::Decoration::Patch => { - // skip - } spirv::Decoration::Centroid => { dec.interpolation = Some(crate::Interpolation::Centroid); } diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 843a827aa..793c01e28 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -206,7 +206,7 @@ pub enum UniformityDisruptor { #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] -pub enum AnalysisError { +pub enum FunctionAnalysisError { #[error("Expression {0:?} is not a global variable!")] ExpectedGlobalVariable(crate::Expression), #[error("Called function {0:?} that hasn't been declared in the IR yet")] @@ -221,6 +221,15 @@ pub enum AnalysisError { ), } +#[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] +pub enum AnalysisError { + #[error("Function {0:?} analysis failed")] + Function(Handle, #[source] FunctionAnalysisError), + #[error("Entry point {0:?}/'{1}' function analysis failed")] + EntryPoint(crate::ShaderStage, String, #[source] FunctionAnalysisError), +} + impl FunctionInfo { /// Adds a value-type reference to an expression. #[must_use] @@ -293,7 +302,7 @@ impl FunctionInfo { arguments: &[crate::FunctionArgument], global_var_arena: &Arena, other_functions: &[FunctionInfo], - ) -> Result<(), AnalysisError> { + ) -> Result<(), FunctionAnalysisError> { use crate::{Expression as E, SampleLevel as Sl}; let mut assignable_global = None; @@ -346,7 +355,10 @@ impl FunctionInfo { assignable_global = Some(gh); let var = &global_var_arena[gh]; let uniform = match var.class { - Sc::Function | Sc::Private | Sc::WorkGroup => false, + // local data is non-uniform + Sc::Function | Sc::Private => false, + // workgroup memory is exclusively accessed by the group + Sc::WorkGroup => true, // uniform data Sc::Uniform | Sc::PushConstant => true, // storage data is only uniform when read-only @@ -377,13 +389,17 @@ impl FunctionInfo { image: match expression_arena[image] { crate::Expression::GlobalVariable(var) => var, ref other => { - return Err(AnalysisError::ExpectedGlobalVariable(other.clone())) + return Err(FunctionAnalysisError::ExpectedGlobalVariable( + other.clone(), + )) } }, sampler: match expression_arena[sampler] { crate::Expression::GlobalVariable(var) => var, ref other => { - return Err(AnalysisError::ExpectedGlobalVariable(other.clone())) + return Err(FunctionAnalysisError::ExpectedGlobalVariable( + other.clone(), + )) } }, }); @@ -483,7 +499,7 @@ impl FunctionInfo { E::Call(function) => { let fun = other_functions .get(function.index()) - .ok_or(AnalysisError::ForwardCall(function))?; + .ok_or(FunctionAnalysisError::ForwardCall(function))?; self.process_call(fun).result } E::ArrayLength(expr) => Uniformity { @@ -515,7 +531,7 @@ impl FunctionInfo { statements: &[crate::Statement], other_functions: &[FunctionInfo], mut disruptor: Option, - ) -> Result { + ) -> Result { use crate::Statement as S; let mut combined_uniformity = FunctionUniformity::new(); @@ -527,7 +543,7 @@ impl FunctionInfo { if let Some(req) = self.expressions[expr.index()].uniformity.requirement { requirement = match disruptor { Some(cause) => { - return Err(AnalysisError::NonUniformControlFlow( + return Err(FunctionAnalysisError::NonUniformControlFlow( req, expr, cause, )) } @@ -639,7 +655,7 @@ impl FunctionInfo { } let info = other_functions .get(function.index()) - .ok_or(AnalysisError::ForwardCall(function))?; + .ok_or(FunctionAnalysisError::ForwardCall(function))?; self.process_call(info) } }; @@ -666,7 +682,7 @@ impl Analysis { &self, fun: &crate::Function, global_var_arena: &Arena, - ) -> Result { + ) -> Result { let mut info = FunctionInfo { uniformity: Uniformity::default(), may_kill: false, @@ -698,13 +714,17 @@ impl Analysis { functions: Vec::with_capacity(module.functions.len()), entry_points: Vec::with_capacity(module.entry_points.len()), }; - for (_, fun) in module.functions.iter() { - let info = this.process_function(fun, &module.global_variables)?; + for (fun_handle, fun) in module.functions.iter() { + let info = this + .process_function(fun, &module.global_variables) + .map_err(|source| AnalysisError::Function(fun_handle, source))?; this.functions.push(info); } for ep in module.entry_points.iter() { - let info = this.process_function(&ep.function, &module.global_variables)?; + let info = this + .process_function(&ep.function, &module.global_variables) + .map_err(|source| AnalysisError::EntryPoint(ep.stage, ep.name.clone(), source))?; this.entry_points.push(info); } @@ -841,7 +861,7 @@ fn uniform_control_flow() { }; assert_eq!( info.process_block(&[stmt_emit2, stmt_if_non_uniform], &[], None), - Err(AnalysisError::NonUniformControlFlow( + Err(FunctionAnalysisError::NonUniformControlFlow( UniformityRequirement::Derivative, derivative_expr, UniformityDisruptor::Expression(non_uniform_global_expr) From 6736bcefa6f1bf5f72efb7622f3500515e17661c Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 17 Mar 2021 15:37:18 +0300 Subject: [PATCH 0587/2212] [glsl-out] Explicitly set location bindings --- src/back/glsl/mod.rs | 18 ++++++++++++++++-- tests/out/quad-Fragment.glsl.snap | 4 ++-- tests/out/quad-Vertex.glsl.snap | 6 +++--- tests/out/shadow-Fragment.glsl.snap | 6 +++--- tests/out/skybox-Fragment.glsl.snap | 4 ++-- tests/out/skybox-Vertex.glsl.snap | 2 +- 6 files changed, 27 insertions(+), 13 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index d9ae2848d..25a883e90 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -811,8 +811,22 @@ impl<'a, W: Write> Writer<'a, W> { } // Write the storage class - write!(self.out, "{} ", if output { "out" } else { "in" })?; - + if self.options.version >= Version::Embedded(310) + || self.options.version >= Version::Desktop(410) + { + if let Binding::Location(index, ..) = *binding { + write!( + self.out, + "layout(location = {}) {} ", + index, + if output { "out" } else { "in" } + )?; + } else { + write!(self.out, "{} ", if output { "out" } else { "in" })?; + } + } else { + write!(self.out, "{} ", if output { "out" } else { "in" })?; + } // Write the type // `write_type` adds no leading or trailing spaces self.write_type(ty)?; diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap index 8773ca4cc..28e2a75f1 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad-Fragment.glsl.snap @@ -13,8 +13,8 @@ struct VertexOutput { uniform highp sampler2D _group_0_binding_0; -in vec2 _in_location_0; -out vec4 _out_location_0; +layout(location = 0) in vec2 _in_location_0; +layout(location = 0) out vec4 _out_location_0; void main() { vec2 uv2 = _in_location_0; diff --git a/tests/out/quad-Vertex.glsl.snap b/tests/out/quad-Vertex.glsl.snap index c4d67cef9..51a1aa2b0 100644 --- a/tests/out/quad-Vertex.glsl.snap +++ b/tests/out/quad-Vertex.glsl.snap @@ -11,9 +11,9 @@ struct VertexOutput { vec4 position; }; -in vec2 _in_location_0; -in vec2 _in_location_1; -out vec2 _out_location_0; +layout(location = 0) in vec2 _in_location_0; +layout(location = 1) in vec2 _in_location_1; +layout(location = 0) out vec2 _out_location_0; void main() { vec2 pos = _in_location_0; diff --git a/tests/out/shadow-Fragment.glsl.snap b/tests/out/shadow-Fragment.glsl.snap index fa0739596..ff052ae0f 100644 --- a/tests/out/shadow-Fragment.glsl.snap +++ b/tests/out/shadow-Fragment.glsl.snap @@ -22,9 +22,9 @@ readonly buffer Lights_block_1 { uniform highp sampler2DArrayShadow _group_0_binding_2; -in vec3 _in_location_0; -in vec4 _in_location_1; -out vec4 _out_location_0; +layout(location = 0) in vec3 _in_location_0; +layout(location = 1) in vec4 _in_location_1; +layout(location = 0) out vec4 _out_location_0; float fetch_shadow(uint light_id, vec4 homogeneous_coords) { if((homogeneous_coords[3] <= 0.0)) { diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap index e08e83c48..532203d3d 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox-Fragment.glsl.snap @@ -13,8 +13,8 @@ struct VertexOutput { uniform highp samplerCube _group_0_binding_1; -in vec3 _in_location_0; -out vec4 _out_location_0; +layout(location = 0) in vec3 _in_location_0; +layout(location = 0) out vec4 _out_location_0; void main() { vec3 uv1 = _in_location_0; diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap index 4b71a76fa..3f7c221d5 100644 --- a/tests/out/skybox-Vertex.glsl.snap +++ b/tests/out/skybox-Vertex.glsl.snap @@ -16,7 +16,7 @@ uniform Data_block_0 { mat4x4 view; } _group_0_binding_0; -out vec3 _out_location_0; +layout(location = 0) out vec3 _out_location_0; void main() { uint vertex_index = uint(gl_VertexID); From 9390aa472da5111e2b325d7aa4a2bee13c6fe92c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 17 Mar 2021 10:05:47 -0400 Subject: [PATCH 0588/2212] [glsl-out] make varying names to match --- src/back/glsl/mod.rs | 75 +++++++++++++++++------------ tests/out/quad-Fragment.glsl.snap | 8 +-- tests/out/quad-Vertex.glsl.snap | 12 ++--- tests/out/shadow-Fragment.glsl.snap | 12 ++--- tests/out/skybox-Fragment.glsl.snap | 8 +-- tests/out/skybox-Vertex.glsl.snap | 4 +- 6 files changed, 65 insertions(+), 54 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 25a883e90..960fc449a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -103,6 +103,11 @@ impl Version { Version::Embedded(v) => SUPPORTED_ES_VERSIONS.contains(&v), } } + + /// Checks if the version supports explicit `layout(location=)` qualifiers. + fn supports_explicit_locations(&self) -> bool { + *self >= Version::Embedded(310) || *self >= Version::Desktop(410) + } } impl PartialOrd for Version { @@ -235,18 +240,23 @@ impl IdGenerator { /// - Varyings with location bindings are named `_location_X` where `X` is the location struct VaryingName<'a> { binding: &'a Binding, + stage: ShaderStage, output: bool, } impl fmt::Display for VaryingName<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self.binding { Binding::Location(location, _) => { - write!( - f, - "_{}_location_{}", - if self.output { "out" } else { "in" }, - location, - ) + let prefix = match (self.stage, self.output) { + (ShaderStage::Compute, _) => unreachable!(), + // pipeline to vertex + (ShaderStage::Vertex, false) => "p2vs", + // vertex to fragment + (ShaderStage::Vertex, true) | (ShaderStage::Fragment, false) => "vs2fs", + // fragment to pipeline + (ShaderStage::Fragment, true) => "fs2p", + }; + write!(f, "_{}_location{}", prefix, location,) } Binding::BuiltIn(built_in) => { write!(f, "{}", glsl_built_in(built_in, self.output)) @@ -547,7 +557,7 @@ impl<'a, W: Write> Writer<'a, W> { let fun_info = &self.analysis[handle]; // Write the function - self.write_function(FunctionType::Function(handle), function, fun_info, name)?; + self.write_function(FunctionType::Function(handle), function, fun_info, &name)?; writeln!(self.out)?; } @@ -794,36 +804,28 @@ impl<'a, W: Write> Writer<'a, W> { } } _ => { - let binding = match binding { - Some(binding @ &Binding::Location(..)) => binding, + let (location, interpolation) = match binding { + Some(&Binding::Location(location, interpolation)) => (location, interpolation), _ => return Ok(()), }; // Write the interpolation modifier if needed // // We ignore all interpolation modifiers that aren't used in input globals in fragment // shaders or output globals in vertex shaders - // - // TODO: Should this throw an error? - if let Binding::Location(_, Some(interp)) = *binding { + if let Some(interp) = interpolation { if self.options.shader_stage == ShaderStage::Fragment { write!(self.out, "{} ", glsl_interpolation(interp))?; } } // Write the storage class - if self.options.version >= Version::Embedded(310) - || self.options.version >= Version::Desktop(410) - { - if let Binding::Location(index, ..) = *binding { - write!( - self.out, - "layout(location = {}) {} ", - index, - if output { "out" } else { "in" } - )?; - } else { - write!(self.out, "{} ", if output { "out" } else { "in" })?; - } + if self.options.version.supports_explicit_locations() { + write!( + self.out, + "layout(location = {}) {} ", + location, + if output { "out" } else { "in" } + )?; } else { write!(self.out, "{} ", if output { "out" } else { "in" })?; } @@ -833,7 +835,12 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important - writeln!(self.out, " {};", VaryingName { binding, output })?; + let vname = VaryingName { + binding: &Binding::Location(location, None), + stage: self.entry_point.stage, + output, + }; + writeln!(self.out, " {};", vname)?; } } Ok(()) @@ -843,12 +850,12 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Adds a newline - fn write_function>( + fn write_function( &mut self, ty: FunctionType, func: &Function, info: &FunctionInfo, - name: N, + name: &str, ) -> BackendResult { // Create a new typifier and resolve all types for the current function let mut typifier = Typifier::new(); @@ -896,7 +903,7 @@ impl<'a, W: Write> Writer<'a, W> { } // Write the function name and open parentheses for the argument list - write!(self.out, " {}(", name.as_ref())?; + write!(self.out, " {}(", name)?; // Write the comma separated argument list // @@ -923,6 +930,7 @@ impl<'a, W: Write> Writer<'a, W> { // Compose the function arguments from globals, in case of an entry point. if let FunctionType::EntryPoint(ep_index) = ctx.func { + let stage = self.module.entry_points[ep_index as usize].stage; for (index, arg) in func.arguments.iter().enumerate() { write!(self.out, "{}", INDENT)?; self.write_type(arg.ty)?; @@ -939,6 +947,7 @@ impl<'a, W: Write> Writer<'a, W> { for (index, member) in members.iter().enumerate() { let varying_name = VaryingName { binding: member.binding.as_ref().unwrap(), + stage, output: false, }; if index != 0 { @@ -951,6 +960,7 @@ impl<'a, W: Write> Writer<'a, W> { _ => { let varying_name = VaryingName { binding: arg.binding.as_ref().unwrap(), + stage, output: false, }; writeln!(self.out, "{};", varying_name)?; @@ -1342,9 +1352,8 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ";")?; } FunctionType::EntryPoint(ep_index) => { - if let Some(ref result) = - self.module.entry_points[ep_index as usize].function.result - { + let ep = &self.module.entry_points[ep_index as usize]; + if let Some(ref result) = ep.function.result { let value = value.unwrap(); match self.module.types[result.ty].inner { crate::TypeInner::Struct { @@ -1354,6 +1363,7 @@ impl<'a, W: Write> Writer<'a, W> { for (index, member) in members.iter().enumerate() { let varying_name = VaryingName { binding: member.binding.as_ref().unwrap(), + stage: ep.stage, output: true, }; write!(self.out, "{} = ", varying_name)?; @@ -1367,6 +1377,7 @@ impl<'a, W: Write> Writer<'a, W> { _ => { let name = VaryingName { binding: result.binding.as_ref().unwrap(), + stage: ep.stage, output: true, }; write!(self.out, "{} = ", name)?; diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap index 28e2a75f1..7d873bc76 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad-Fragment.glsl.snap @@ -13,16 +13,16 @@ struct VertexOutput { uniform highp sampler2D _group_0_binding_0; -layout(location = 0) in vec2 _in_location_0; -layout(location = 0) out vec4 _out_location_0; +layout(location = 0) in vec2 _vs2fs_location0; +layout(location = 0) out vec4 _fs2p_location0; void main() { - vec2 uv2 = _in_location_0; + vec2 uv2 = _vs2fs_location0; vec4 _expr4 = texture(_group_0_binding_0, vec2(uv2)); if((_expr4[3] == 0.0)) { discard; } - _out_location_0 = (_expr4[3] * _expr4); + _fs2p_location0 = (_expr4[3] * _expr4); return; } diff --git a/tests/out/quad-Vertex.glsl.snap b/tests/out/quad-Vertex.glsl.snap index 51a1aa2b0..99ff87ef1 100644 --- a/tests/out/quad-Vertex.glsl.snap +++ b/tests/out/quad-Vertex.glsl.snap @@ -11,17 +11,17 @@ struct VertexOutput { vec4 position; }; -layout(location = 0) in vec2 _in_location_0; -layout(location = 1) in vec2 _in_location_1; -layout(location = 0) out vec2 _out_location_0; +layout(location = 0) in vec2 _p2vs_location0; +layout(location = 1) in vec2 _p2vs_location1; +layout(location = 0) out vec2 _vs2fs_location0; void main() { - vec2 pos = _in_location_0; - vec2 uv1 = _in_location_1; + vec2 pos = _p2vs_location0; + vec2 uv1 = _p2vs_location1; VertexOutput out1; out1.uv = uv1; out1.position = vec4((1.2 * pos), 0.0, 1.0); - _out_location_0 = out1.uv; + _vs2fs_location0 = out1.uv; gl_Position = out1.position; return; } diff --git a/tests/out/shadow-Fragment.glsl.snap b/tests/out/shadow-Fragment.glsl.snap index ff052ae0f..14501be8d 100644 --- a/tests/out/shadow-Fragment.glsl.snap +++ b/tests/out/shadow-Fragment.glsl.snap @@ -22,9 +22,9 @@ readonly buffer Lights_block_1 { uniform highp sampler2DArrayShadow _group_0_binding_2; -layout(location = 0) in vec3 _in_location_0; -layout(location = 1) in vec4 _in_location_1; -layout(location = 0) out vec4 _out_location_0; +layout(location = 0) in vec3 _vs2fs_location0; +layout(location = 1) in vec4 _vs2fs_location1; +layout(location = 0) out vec4 _fs2p_location0; float fetch_shadow(uint light_id, vec4 homogeneous_coords) { if((homogeneous_coords[3] <= 0.0)) { @@ -36,8 +36,8 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } void main() { - vec3 raw_normal = _in_location_0; - vec4 position = _in_location_1; + vec3 raw_normal = _vs2fs_location0; + vec4 position = _vs2fs_location1; vec3 color1 = vec3(0.05, 0.05, 0.05); uint i = 0u; while(true) { @@ -49,7 +49,7 @@ void main() { color1 = (color1 + ((_expr25 * max(0.0, dot(normalize(raw_normal), normalize((vec3(_expr21.pos[0], _expr21.pos[1], _expr21.pos[2]) - vec3(position[0], position[1], position[2])))))) * vec3(_expr21.color[0], _expr21.color[1], _expr21.color[2]))); i = (i + 1u); } - _out_location_0 = vec4(color1, 1.0); + _fs2p_location0 = vec4(color1, 1.0); return; } diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap index 532203d3d..caf3117b9 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox-Fragment.glsl.snap @@ -13,13 +13,13 @@ struct VertexOutput { uniform highp samplerCube _group_0_binding_1; -layout(location = 0) in vec3 _in_location_0; -layout(location = 0) out vec4 _out_location_0; +layout(location = 0) in vec3 _vs2fs_location0; +layout(location = 0) out vec4 _fs2p_location0; void main() { - vec3 uv1 = _in_location_0; + vec3 uv1 = _vs2fs_location0; vec4 _expr4 = texture(_group_0_binding_1, vec3(uv1)); - _out_location_0 = _expr4; + _fs2p_location0 = _expr4; return; } diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap index 3f7c221d5..8c27eed33 100644 --- a/tests/out/skybox-Vertex.glsl.snap +++ b/tests/out/skybox-Vertex.glsl.snap @@ -16,7 +16,7 @@ uniform Data_block_0 { mat4x4 view; } _group_0_binding_0; -layout(location = 0) out vec3 _out_location_0; +layout(location = 0) out vec3 _vs2fs_location0; void main() { uint vertex_index = uint(gl_VertexID); @@ -30,7 +30,7 @@ void main() { out1.uv = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr50[0], _expr50[1], _expr50[2])); out1.position = _expr24; gl_Position = out1.position; - _out_location_0 = out1.uv; + _vs2fs_location0 = out1.uv; return; } From f18728ed9238ecf2f66a48ac1a0aebbb001e7f4b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 17 Mar 2021 16:08:17 -0400 Subject: [PATCH 0589/2212] Enable more SPIR-V capabilities in the frontend --- src/front/spv/mod.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index bf244bfb1..9ddb61ab6 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -43,13 +43,22 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, spirv::Capability::ClipDistance, spirv::Capability::CullDistance, + spirv::Capability::SampleRateShading, + spirv::Capability::DerivativeControl, + spirv::Capability::InterpolationFunction, + spirv::Capability::Matrix, spirv::Capability::ImageQuery, + spirv::Capability::Sampled1D, spirv::Capability::Image1D, + spirv::Capability::SampledCubeArray, spirv::Capability::ImageCubeArray, spirv::Capability::ImageMSArray, spirv::Capability::StorageImageExtendedFormats, spirv::Capability::Sampled1D, spirv::Capability::SampledCubeArray, + // tricky ones + spirv::Capability::UniformBufferArrayDynamicIndexing, + spirv::Capability::StorageBufferArrayDynamicIndexing, ]; pub const SUPPORTED_EXTENSIONS: &[&str] = &[]; pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"]; From dd2cd923315fd1cc36ed873f1d0e8751e2599144 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 17 Mar 2021 16:49:00 -0400 Subject: [PATCH 0590/2212] [msl-out] fix varying input structures --- src/back/msl/writer.rs | 44 +++++++++++++------------- tests/in/skybox.wgsl | 4 +-- tests/out/boids.msl.snap | 9 ------ tests/out/collatz.msl.snap | 4 --- tests/out/quad.msl.snap | 6 ---- tests/out/shadow.msl.snap | 13 -------- tests/out/skybox-Fragment.glsl.snap | 6 ++-- tests/out/skybox.msl.snap | 19 +++-------- tests/out/skybox.spvasm.snap | 49 ++++++++++++++++------------- 9 files changed, 60 insertions(+), 94 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 86b3b5a09..0c82e7229 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -894,12 +894,12 @@ impl Writer { let global_use = GlobalUse::all(); //TODO match ty.inner { crate::TypeInner::Scalar { kind, .. } => { - write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?; + writeln!(self.out, "typedef {} {};", scalar_kind_string(kind), name)?; } crate::TypeInner::Vector { size, kind, .. } => { - write!( + writeln!( self.out, - "typedef {}::{}{} {}", + "typedef {}::{}{} {};", NAMESPACE, scalar_kind_string(kind), vector_size_string(size), @@ -907,9 +907,9 @@ impl Writer { )?; } crate::TypeInner::Matrix { columns, rows, .. } => { - write!( + writeln!( self.out, - "typedef {}::{}{}x{} {}", + "typedef {}::{}{}x{} {};", NAMESPACE, scalar_kind_string(crate::ScalarKind::Float), vector_size_string(columns), @@ -923,7 +923,7 @@ impl Writer { Some(name) => name, None => continue, }; - write!(self.out, "typedef {} {} *{}", class_name, base_name, name)?; + writeln!(self.out, "typedef {} {} *{};", class_name, base_name, name)?; } crate::TypeInner::ValuePointer { size: None, @@ -935,9 +935,9 @@ impl Writer { Some(name) => name, None => continue, }; - write!( + writeln!( self.out, - "typedef {} {} *{}", + "typedef {} {} *{};", class_name, scalar_kind_string(kind), name @@ -953,9 +953,9 @@ impl Writer { Some(name) => name, None => continue, }; - write!( + writeln!( self.out, - "typedef {} {}::{}{} {}", + "typedef {} {}::{}{} {};", class_name, NAMESPACE, scalar_kind_string(kind), @@ -975,7 +975,7 @@ impl Writer { } crate::ArraySize::Dynamic => "1", }; - write!(self.out, "typedef {} {}[{}]", base_name, name, size_str)?; + writeln!(self.out, "typedef {} {}[{}];", base_name, name, size_str)?; } crate::TypeInner::Struct { block: _, @@ -987,7 +987,7 @@ impl Writer { let base_name = &self.names[&NameKey::Type(member.ty)]; writeln!(self.out, "{}{} {};", INDENT, base_name, member_name)?; } - write!(self.out, "}}")?; + writeln!(self.out, "}};")?; } crate::TypeInner::Image { dim, @@ -1030,9 +1030,9 @@ impl Writer { }; let base_name = scalar_kind_string(kind); let array_str = if arrayed { "_array" } else { "" }; - write!( + writeln!( self.out, - "typedef {}::{}{}{}{}<{}, {}::access::{}> {}", + "typedef {}::{}{}{}{}<{}, {}::access::{}> {};", NAMESPACE, texture_str, dim_str, @@ -1045,11 +1045,9 @@ impl Writer { )?; } crate::TypeInner::Sampler { comparison: _ } => { - write!(self.out, "typedef {}::sampler {}", NAMESPACE, name)?; + writeln!(self.out, "typedef {}::sampler {};", NAMESPACE, name)?; } } - writeln!(self.out, ";")?; - writeln!(self.out)?; } Ok(()) } @@ -1418,19 +1416,21 @@ impl Writer { let struct_name = &self.names[&NameKey::Type(arg.ty)]; write!( self.out, - "{}const {} {} = {{", + "{}const {} {} = {{ ", INDENT, struct_name, arg_name )?; - for member_index in 0..members.len() { + for (member_index, member) in members.iter().enumerate() { let name = &self.names[&NameKey::StructMember(arg.ty, member_index as u32)]; - let separator = if member_index != 0 { ", " } else { "" }; - write!(self.out, "{}{}", INDENT, separator)?; - if let Some(crate::Binding::Location(..)) = arg.binding { + if member_index != 0 { + write!(self.out, ", ")?; + } + if let Some(crate::Binding::Location(..)) = member.binding { write!(self.out, "{}.", varyings_member_name)?; } write!(self.out, "{}", name)?; } + writeln!(self.out, " }};")?; } _ => { if let Some(crate::Binding::Location(..)) = arg.binding { diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index cd6d46721..32ad80ca1 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -37,6 +37,6 @@ var r_texture: texture_cube; var r_sampler: sampler; [[stage(fragment)]] -fn fs_main([[location(0)]] uv: vec3) -> [[location(0)]] vec4 { - return textureSample(r_texture, r_sampler, uv); +fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 { + return textureSample(r_texture, r_sampler, in.uv); } diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index 237e6de6e..7fe3c2c82 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -6,16 +6,12 @@ expression: msl #include typedef uint type; - typedef metal::float2 type1; - struct Particle { type1 pos; type1 vel; }; - typedef float type2; - struct SimParams { type2 deltaT; type2 rule1Distance; @@ -25,17 +21,12 @@ struct SimParams { type2 rule2Scale; type2 rule3Scale; }; - typedef Particle type3[1]; - struct Particles { type3 particles; }; - typedef metal::uint3 type4; - typedef int type5; - constexpr constant int NUM_PARTICLES = 1500; constexpr constant float const_0f = 0.0; constexpr constant int const_0i = 0; diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index 13e4a1e0c..6c9e2f0a6 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -6,15 +6,11 @@ expression: msl #include typedef uint type; - typedef type type1[1]; - struct PrimeIndices { type1 data; }; - typedef metal::uint3 type2; - constexpr constant unsigned const_0u = 0u; constexpr constant unsigned const_1u = 1u; constexpr constant unsigned const_2u = 2u; diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index 32d695f2f..ebea304a2 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -6,20 +6,14 @@ expression: msl #include typedef float type; - typedef metal::float2 type1; - typedef metal::float4 type2; - struct VertexOutput { type1 uv; type2 position; }; - typedef metal::texture2d type3; - typedef metal::sampler type4; - constexpr constant float c_scale = 1.2; constexpr constant float const_0f = 0.0; constexpr constant float const_1f = 1.0; diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 4d3963439..0e2e67067 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -6,39 +6,26 @@ expression: msl #include typedef metal::uint4 type; - struct Globals { type num_lights; }; - typedef metal::float4x4 type1; - typedef metal::float4 type2; - struct Light { type1 proj; type2 pos; type2 color; }; - typedef Light type3[1]; - struct Lights { type3 data; }; - typedef metal::depth2d_array type4; - typedef metal::sampler type5; - typedef uint type6; - typedef float type7; - typedef metal::float2 type8; - typedef metal::float3 type9; - constexpr constant float const_0f = 0.0; constexpr constant float const_1f = 1.0; constexpr constant float const_0_50f = 0.5; diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap index caf3117b9..2975a920b 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox-Fragment.glsl.snap @@ -17,9 +17,9 @@ layout(location = 0) in vec3 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { - vec3 uv1 = _vs2fs_location0; - vec4 _expr4 = texture(_group_0_binding_1, vec3(uv1)); - _fs2p_location0 = _expr4; + VertexOutput in1 = VertexOutput(gl_FragCoord, _vs2fs_location0); + vec4 _expr5 = texture(_group_0_binding_1, vec3(in1.uv)); + _fs2p_location0 = _expr5; return; } diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 4345f5813..83ce8194a 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -6,31 +6,21 @@ expression: msl #include typedef metal::float4 type; - typedef metal::float3 type1; - struct VertexOutput { type position; type1 uv; }; - typedef metal::float4x4 type2; - struct Data { type2 proj_inv; type2 view; }; - typedef uint type3; - typedef int type4; - typedef metal::float3x3 type5; - typedef metal::texturecube type6; - typedef metal::sampler type7; - constexpr constant int const_2i = 2; constexpr constant int const_1i = 1; constexpr constant float const_4f = 4.0; @@ -60,18 +50,19 @@ vertex vs_mainOutput vs_main( } struct fs_mainInput { - type1 uv1 [[user(loc0)]]; + type1 uv [[user(loc0)]]; }; struct fs_mainOutput { type member1 [[color(0)]]; }; fragment fs_mainOutput fs_main( fs_mainInput varyings1 [[stage_in]] +, type position [[position]] , type6 r_texture [[texture(0)]] , type7 r_sampler [[sampler(1)]] ) { - const auto uv1 = varyings1.uv1; - metal::float4 _expr4 = r_texture.sample(r_sampler, uv1); - return fs_mainOutput { _expr4 }; + const VertexOutput in = { position, varyings1.uv }; + metal::float4 _expr5 = r_texture.sample(r_sampler, in.uv); + return fs_mainOutput { _expr5 }; } diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index 8b197e2db..b0dd48114 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -5,13 +5,13 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 111 +; Bound: 116 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %37 "vs_main" %30 %33 %35 -OpEntryPoint Fragment %104 "fs_main" %100 %103 -OpExecutionMode %104 OriginUpperLeft +OpEntryPoint Fragment %108 "fs_main" %101 %104 %107 +OpExecutionMode %108 OriginUpperLeft OpSource GLSL 450 OpName %11 "Data" OpMemberName %11 0 "proj_inv" @@ -28,9 +28,10 @@ OpName %33 "position" OpName %35 "uv" OpName %37 "vs_main" OpName %37 "vs_main" -OpName %100 "uv" -OpName %104 "fs_main" -OpName %104 "fs_main" +OpName %101 "position" +OpName %104 "uv" +OpName %108 "fs_main" +OpName %108 "fs_main" OpDecorate %11 Block OpMemberDecorate %11 0 Offset 0 OpMemberDecorate %11 0 ColMajor @@ -47,8 +48,9 @@ OpDecorate %18 Binding 2 OpDecorate %30 BuiltIn VertexIndex OpDecorate %33 BuiltIn Position OpDecorate %35 Location 0 -OpDecorate %100 Location 0 -OpDecorate %103 Location 0 +OpDecorate %101 BuiltIn FragCoord +OpDecorate %104 Location 0 +OpDecorate %107 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -90,10 +92,12 @@ OpDecorate %103 Location 0 %91 = OpConstant %4 1 %93 = OpTypePointer Function %13 %94 = OpConstant %4 0 -%101 = OpTypePointer Input %26 -%100 = OpVariable %101 Input -%103 = OpVariable %34 Output -%108 = OpTypeSampledImage %16 +%102 = OpTypePointer Input %13 +%101 = OpVariable %102 Input +%105 = OpTypePointer Input %26 +%104 = OpVariable %105 Input +%107 = OpVariable %34 Output +%113 = OpTypeSampledImage %16 %37 = OpFunction %2 None %38 %28 = OpLabel %21 = OpVariable %22 Function @@ -159,15 +163,18 @@ OpStore %33 %97 OpStore %35 %98 OpReturn OpFunctionEnd -%104 = OpFunction %2 None %38 +%108 = OpFunction %2 None %38 %99 = OpLabel -%102 = OpLoad %26 %100 -%105 = OpLoad %16 %15 -%106 = OpLoad %19 %18 -OpBranch %107 -%107 = OpLabel -%109 = OpSampledImage %108 %105 %106 -%110 = OpImageSampleImplicitLod %13 %109 %102 -OpStore %103 %110 +%103 = OpLoad %13 %101 +%106 = OpLoad %26 %104 +%100 = OpCompositeConstruct %25 %103 %106 +%109 = OpLoad %16 %15 +%110 = OpLoad %19 %18 +OpBranch %111 +%111 = OpLabel +%112 = OpCompositeExtract %26 %100 1 +%114 = OpSampledImage %113 %109 %110 +%115 = OpImageSampleImplicitLod %13 %114 %112 +OpStore %107 %115 OpReturn OpFunctionEnd From 6e71366bd3353d163e90a41ba451a6f70411763e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 18 Mar 2021 09:53:42 -0400 Subject: [PATCH 0591/2212] Test typifier error sizes --- src/proc/typifier.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 32c70113d..2f3d3831e 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -692,3 +692,10 @@ impl Typifier { Ok(()) } } + +#[test] +fn test_error_size() { + use std::mem::size_of; + assert_eq!(size_of::(), 80); + assert_eq!(size_of::(), 88); +} From 8c4598a141b29515d9ee377dcfdbd097a0db889f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 18 Mar 2021 09:53:57 -0400 Subject: [PATCH 0592/2212] [msl-out] test put_expession stack footprint in debug Also change io::Error to fmt::Error --- src/back/msl/mod.rs | 15 ++++++++----- src/back/msl/writer.rs | 48 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 7 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 177a94596..54082701d 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -29,7 +29,7 @@ use crate::{ FastHashMap, }; use std::{ - io::{Error as IoError, Write}, + fmt::{Error as FmtError, Write}, string::FromUtf8Error, }; @@ -68,7 +68,7 @@ enum ResolvedBinding { #[derive(Debug, thiserror::Error)] pub enum Error { #[error(transparent)] - IO(#[from] IoError), + Format(#[from] FmtError), #[error(transparent)] Utf8(#[from] FromUtf8Error), #[error(transparent)] @@ -247,8 +247,13 @@ pub fn write_string( analysis: &Analysis, options: &Options, ) -> Result<(String, TranslationInfo), Error> { - let mut w = writer::Writer::new(Vec::new()); + let mut w = writer::Writer::new(String::new()); let info = w.write(module, analysis, options)?; - let string = String::from_utf8(w.finish())?; - Ok((string, info)) + Ok((w.finish(), info)) +} + +#[test] +fn test_error_size() { + use std::mem::size_of; + assert_eq!(size_of::(), 96); } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0c82e7229..ea37f8207 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -9,8 +9,7 @@ use crate::{ }; use bit_set::BitSet; use std::{ - fmt::{Display, Error as FmtError, Formatter}, - io::Write, + fmt::{Display, Error as FmtError, Formatter, Write}, iter, }; @@ -73,6 +72,8 @@ pub struct Writer { named_expressions: BitSet, typifier: Typifier, namer: Namer, + #[cfg(test)] + put_expression_stack_pointers: crate::FastHashSet<*const ()>, } fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { @@ -158,6 +159,8 @@ impl Writer { named_expressions: BitSet::new(), typifier: Typifier::new(), namer: Namer::default(), + #[cfg(test)] + put_expression_stack_pointers: Default::default(), } } @@ -203,6 +206,11 @@ impl Writer { expr_handle: Handle, context: &ExpressionContext, ) -> Result<(), Error> { + // Add to the set in order to track the stack size. + #[cfg(test)] + #[allow(trivial_casts)] + self.put_expression_stack_pointers.insert(&expr_handle as *const _ as *const ()); + if self.named_expressions.contains(expr_handle.index()) { write!(self.out, "{}{}", BAKE_PREFIX, expr_handle.index())?; return Ok(()); @@ -1478,3 +1486,39 @@ impl Writer { Ok(info) } } + +#[test] +fn test_stack_size() { + // create a module with at least one expression nested + let mut module = crate::Module::default(); + let constant = module.constants.append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + value: crate::ScalarValue::Float(1.0), + width: 4, + }, + }); + let mut fun = crate::Function::default(); + let const_expr = fun.expressions.append(crate::Expression::Constant(constant)); + let nested_expr = fun.expressions.append(crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr: const_expr, + }); + fun.body.push(crate::Statement::Emit(fun.expressions.range_from(1))); + fun.body.push(crate::Statement::If { condition: nested_expr, accept: Vec::new(), reject: Vec::new() }); + let _ = module.functions.append(fun); + // analyse the module + let analysis = Analysis::new(&module).unwrap(); + // process the module + let mut writer = Writer::new(String::new()); + writer.write(&module, &analysis, &Default::default()).unwrap(); + let (mut min_addr, mut max_addr) = (!0usize, 0usize); + for pointer in writer.put_expression_stack_pointers { + min_addr = min_addr.min(pointer as usize); + max_addr = max_addr.max(pointer as usize); + } + let stack_size = max_addr - min_addr; + // check the size (in debug only) + debug_assert_eq!(stack_size, 39856); +} From 72ede02888f139b4f618aa08fc733b9babf648aa Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 18 Mar 2021 10:20:16 -0400 Subject: [PATCH 0593/2212] Reduce the typifier error sizes --- src/back/msl/mod.rs | 2 +- src/back/msl/writer.rs | 25 +++++++--- src/proc/typifier.rs | 104 ++++++++++++++++------------------------- 3 files changed, 60 insertions(+), 71 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 54082701d..e08df6b9d 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -255,5 +255,5 @@ pub fn write_string( #[test] fn test_error_size() { use std::mem::size_of; - assert_eq!(size_of::(), 96); + assert_eq!(size_of::(), 48); } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ea37f8207..5ccbf842f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -209,7 +209,8 @@ impl Writer { // Add to the set in order to track the stack size. #[cfg(test)] #[allow(trivial_casts)] - self.put_expression_stack_pointers.insert(&expr_handle as *const _ as *const ()); + self.put_expression_stack_pointers + .insert(&expr_handle as *const _ as *const ()); if self.named_expressions.contains(expr_handle.index()) { write!(self.out, "{}{}", BAKE_PREFIX, expr_handle.index())?; @@ -1500,19 +1501,28 @@ fn test_stack_size() { }, }); let mut fun = crate::Function::default(); - let const_expr = fun.expressions.append(crate::Expression::Constant(constant)); + let const_expr = fun + .expressions + .append(crate::Expression::Constant(constant)); let nested_expr = fun.expressions.append(crate::Expression::Unary { op: crate::UnaryOperator::Negate, expr: const_expr, }); - fun.body.push(crate::Statement::Emit(fun.expressions.range_from(1))); - fun.body.push(crate::Statement::If { condition: nested_expr, accept: Vec::new(), reject: Vec::new() }); + fun.body + .push(crate::Statement::Emit(fun.expressions.range_from(1))); + fun.body.push(crate::Statement::If { + condition: nested_expr, + accept: Vec::new(), + reject: Vec::new(), + }); let _ = module.functions.append(fun); // analyse the module let analysis = Analysis::new(&module).unwrap(); // process the module let mut writer = Writer::new(String::new()); - writer.write(&module, &analysis, &Default::default()).unwrap(); + writer + .write(&module, &analysis, &Default::default()) + .unwrap(); let (mut min_addr, mut max_addr) = (!0usize, 0usize); for pointer in writer.put_expression_stack_pointers { min_addr = min_addr.min(pointer as usize); @@ -1520,5 +1530,8 @@ fn test_stack_size() { } let stack_size = max_addr - min_addr; // check the size (in debug only) - debug_assert_eq!(stack_size, 39856); + // last observed macOS value: 25696 + if stack_size > 26000 { + panic!("`put_expression` stack size {} is too large!", stack_size); + } } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 2f3d3831e..e849c3188 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -77,16 +77,11 @@ pub enum ResolveError { FunctionReturnsVoid, #[error("Type is not found in the given immutable arena")] TypeNotFound, - #[error("Incompatible operand: {op} {operand}")] - IncompatibleOperand { op: String, operand: String }, - #[error("Incompatible operands: {left} {op} {right}")] - IncompatibleOperands { - op: String, - left: String, - right: String, - }, + #[error("Incompatible operands: {0}")] + IncompatibleOperands(String), } +#[repr(C)] // pack this tighter: 48 -> 40 bytes #[derive(Clone, Debug, Error, PartialEq)] #[error("Type resolution of {0:?} failed")] pub struct TypifyError(Handle, #[source] ResolveError); @@ -441,11 +436,10 @@ impl Typifier { width, }) } else { - return Err(ResolveError::IncompatibleOperands { - op: "x".to_string(), - left: format!("{:?}", ty_left), - right: format!("{:?}", ty_right), - }); + return Err(ResolveError::IncompatibleOperands(format!( + "{:?} * {:?}", + ty_left, ty_right + ))); } } crate::BinaryOperator::Equal @@ -462,10 +456,10 @@ impl Typifier { Ti::Scalar { .. } => Ti::Scalar { kind, width }, Ti::Vector { size, .. } => Ti::Vector { size, kind, width }, ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "logical".to_string(), - operand: format!("{:?}", other), - }) + return Err(ResolveError::IncompatibleOperands(format!( + "{:?}({:?}, _)", + op, other + ))) } }; Resolution::Value(inner) @@ -530,27 +524,21 @@ impl Typifier { size: _, width, } => Resolution::Value(Ti::Scalar { kind, width }), - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "dot product".to_string(), - operand: format!("{:?}", other), - }) - } + ref other => + return Err(ResolveError::IncompatibleOperands( + format!("{:?}({:?}, _)", fun, other) + )), }, Mf::Outer => { - let arg1 = arg1.ok_or_else(|| ResolveError::IncompatibleOperand { - op: "outer product".to_string(), - operand: "".to_string(), - })?; + let arg1 = arg1.ok_or_else(|| ResolveError::IncompatibleOperands( + format!("{:?}(_, None)", fun) + ))?; match (self.get(arg, types), self.get(arg1,types)) { (&Ti::Vector {kind: _, size: columns,width}, &Ti::Vector{ size: rows, .. }) => Resolution::Value(Ti::Matrix { columns, rows, width }), - (left, right) => { - return Err(ResolveError::IncompatibleOperands { - op: "outer product".to_string(), - left: format!("{:?}", left), - right: format!("{:?}", right), - }) - } + (left, right) => + return Err(ResolveError::IncompatibleOperands( + format!("{:?}({:?}, {:?})", fun, left, right) + )), } }, Mf::Cross => self.resolutions[arg.index()].clone(), @@ -558,12 +546,9 @@ impl Typifier { Mf::Length => match *self.get(arg, types) { Ti::Scalar {width,kind} | Ti::Vector {width,kind,size:_} => Resolution::Value(Ti::Scalar { kind, width }), - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: format!("{:?}", fun), - operand: format!("{:?}", other), - }) - } + ref other => return Err(ResolveError::IncompatibleOperands( + format!("{:?}({:?})", fun, other) + )), }, Mf::Normalize | Mf::FaceForward | @@ -586,12 +571,9 @@ impl Typifier { rows: columns, width, }), - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "transpose".to_string(), - operand: format!("{:?}", other), - }) - } + ref other => return Err(ResolveError::IncompatibleOperands( + format!("{:?}({:?})", fun, other) + )), }, Mf::Inverse => match *self.get(arg, types) { Ti::Matrix { @@ -603,24 +585,18 @@ impl Typifier { rows, width, }), - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "inverse".to_string(), - operand: format!("{:?}", other), - }) - } + ref other => return Err(ResolveError::IncompatibleOperands( + format!("{:?}({:?})", fun, other) + )), }, Mf::Determinant => match *self.get(arg, types) { Ti::Matrix { width, .. } => Resolution::Value(Ti::Scalar { kind: crate::ScalarKind::Float, width }), - ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "determinant".to_string(), - operand: format!("{:?}", other), - }) - } + ref other => return Err(ResolveError::IncompatibleOperands( + format!("{:?}({:?})", fun, other) + )), }, // bits Mf::CountOneBits | @@ -639,10 +615,10 @@ impl Typifier { width, } => Resolution::Value(Ti::Vector { kind, size, width }), ref other => { - return Err(ResolveError::IncompatibleOperand { - op: "as".to_string(), - operand: format!("{:?}", other), - }) + return Err(ResolveError::IncompatibleOperands(format!( + "{:?} as {:?}", + other, kind + ))) } }, crate::Expression::Call(function) => { @@ -696,6 +672,6 @@ impl Typifier { #[test] fn test_error_size() { use std::mem::size_of; - assert_eq!(size_of::(), 80); - assert_eq!(size_of::(), 88); + assert_eq!(size_of::(), 32); + assert_eq!(size_of::(), 40); } From 67ca0e7e7fe6de5f59cfc45518b9e361f14e7254 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 18 Mar 2021 01:12:06 -0400 Subject: [PATCH 0594/2212] First bits of expression validation --- src/proc/validator.rs | 240 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 225 insertions(+), 15 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 327c0ac6b..9ab67e025 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -149,10 +149,30 @@ pub enum VaryingError { #[derive(Clone, Debug, Error)] pub enum ExpressionError { - #[error("Is invalid")] - Invalid, + #[error("Doesn't exist")] + DoesntExist, #[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")] NotInScope, + #[error("Depends on {0:?}, which has not been processed yet")] + ForwardDependency(Handle), + #[error("Base type {0:?} is not compatible with this expression")] + InvalidBaseType(Handle), + #[error("Accessing with index {0:?} can't be done")] + InvalidIndexType(Handle), + #[error("Accessing index {1} is out of {0:?} bounds")] + IndexOutOfBounds(Handle, u32), + #[error("Function argument {0:?} doesn't exist")] + FunctionArgumentDoesntExist(u32), + #[error("Constant {0:?} doesn't exist")] + ConstantDoesntExist(Handle), + #[error("Global variable {0:?} doesn't exist")] + GlobalVarDoesntExist(Handle), + #[error("Local variable {0:?} doesn't exist")] + LocalVarDoesntExist(Handle), + #[error("Loading of {0:?} can't be done")] + InvalidPointerType(Handle), + #[error("Array length of {0:?} can't be done")] + InvalidArrayType(Handle), } #[derive(Clone, Debug, Error)] @@ -499,6 +519,25 @@ impl VaryingContext<'_> { } } +struct ExpressionTypeResolver<'a> { + root: Handle, + types: &'a Arena, + typifier: &'a Typifier, +} + +impl<'a> ExpressionTypeResolver<'a> { + fn resolve( + &self, + handle: Handle, + ) -> Result<&'a crate::TypeInner, ExpressionError> { + if handle < self.root { + Ok(self.typifier.get(handle, self.types)) + } else { + Err(ExpressionError::ForwardDependency(handle)) + } + } +} + impl Validator { /// Construct a new validator instance. pub fn new() -> Self { @@ -793,7 +832,7 @@ impl Validator { } for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { let ty = self - .resolve_type_impl(expr, context.types) + .resolve_statement_type_impl(expr, context.types) .map_err(|error| CallError::Argument { index, error })?; if ty != &context.types[arg.ty].inner { return Err(CallError::ArgumentType { @@ -813,7 +852,7 @@ impl Validator { } let result_ty = result - .map(|expr| self.resolve_type_impl(expr, context.types)) + .map(|expr| self.resolve_statement_type_impl(expr, context.types)) .transpose() .map_err(CallError::ResultValue)?; let expected_ty = fun.result.as_ref().map(|fr| &context.types[fr.ty].inner); @@ -831,7 +870,174 @@ impl Validator { Ok(()) } - fn resolve_type_impl<'a>( + #[allow(unused)] + fn validate_expression( + &self, + root: Handle, + expression: &crate::Expression, + function: &crate::Function, + stage: Option, + module: &crate::Module, + ) -> Result<(), ExpressionError> { + use crate::{Expression as E, TypeInner as Ti}; + use std::convert::TryInto; + + let resolver = ExpressionTypeResolver { + root, + types: &module.types, + typifier: &self.typifier, + }; + + match *expression { + E::Access { base, index } => { + match *resolver.resolve(base)? { + Ti::Vector { .. } + | Ti::Matrix { .. } + | Ti::Array { .. } + | Ti::Pointer { .. } => {} + ref other => { + log::error!("Indexing of {:?}", other); + return Err(ExpressionError::InvalidBaseType(base)); + } + } + match *resolver.resolve(index)? { + //TODO: only allow one of these + Ti::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } + | Ti::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + } => {} + ref other => { + log::error!("Indexing by {:?}", other); + return Err(ExpressionError::InvalidIndexType(index)); + } + } + } + E::AccessIndex { base, index } => { + let limit = match *resolver.resolve(base)? { + Ti::Vector { size, .. } => size as u32, + Ti::Matrix { columns, .. } => columns as u32, + Ti::Array { + size: crate::ArraySize::Constant(handle), + .. + } => { + match module + .constants + .try_get(handle) + .ok_or(ExpressionError::ConstantDoesntExist(handle))? + .inner + { + crate::ConstantInner::Scalar { value, width: _ } => match value { + crate::ScalarValue::Sint(value) => { + value.max(0).try_into().unwrap_or(!0) + } + crate::ScalarValue::Uint(value) => value.try_into().unwrap_or(!0), + _ => unreachable!(), + }, + // caught by type validation + crate::ConstantInner::Composite { .. } => unreachable!(), + } + } + Ti::Array { .. } => !0, // can't statically know, but need run-time checks + Ti::Pointer { .. } => !0, //TODO + Ti::Struct { + ref members, + block: _, + } => members.len() as u32, + ref other => { + log::error!("Indexing of {:?}", other); + return Err(ExpressionError::InvalidBaseType(base)); + } + }; + if index >= limit { + return Err(ExpressionError::IndexOutOfBounds(base, index)); + } + } + E::Constant(handle) => { + let _ = module + .constants + .try_get(handle) + .ok_or(ExpressionError::ConstantDoesntExist(handle))?; + } + E::Compose { ref components, ty } => { + //TODO + } + E::FunctionArgument(index) => { + if index >= function.arguments.len() as u32 { + return Err(ExpressionError::FunctionArgumentDoesntExist(index)); + } + } + E::GlobalVariable(handle) => { + let _ = module + .global_variables + .try_get(handle) + .ok_or(ExpressionError::GlobalVarDoesntExist(handle))?; + } + E::LocalVariable(handle) => { + let _ = function + .local_variables + .try_get(handle) + .ok_or(ExpressionError::LocalVarDoesntExist(handle))?; + } + E::Load { pointer } => match *resolver.resolve(pointer)? { + Ti::Pointer { .. } | Ti::ValuePointer { .. } => {} + ref other => { + log::error!("Loading {:?}", other); + return Err(ExpressionError::InvalidPointerType(pointer)); + } + }, + E::ImageSample { + image, + sampler, + coordinate, + array_index, + offset, + level, + depth_ref, + } => {} + E::ImageLoad { + image, + coordinate, + array_index, + index, + } => {} + E::ImageQuery { image, query } => {} + E::Unary { op, expr } => {} + E::Binary { op, left, right } => {} + E::Select { + condition, + accept, + reject, + } => {} + E::Derivative { axis, expr } => {} + E::Relational { argument, .. } => {} + E::Math { + fun, + arg, + arg1, + arg2, + } => {} + E::As { + expr, + kind, + convert, + } => {} + E::Call(function) => {} + E::ArrayLength(expr) => match *resolver.resolve(expr)? { + Ti::Array { .. } => {} + ref other => { + log::error!("Array length of {:?}", other); + return Err(ExpressionError::InvalidArrayType(expr)); + } + }, + } + Ok(()) + } + + fn resolve_statement_type_impl<'a>( &'a self, handle: Handle, types: &'a Arena, @@ -841,15 +1047,15 @@ impl Validator { } self.typifier .try_get(handle, types) - .ok_or(ExpressionError::Invalid) + .ok_or(ExpressionError::DoesntExist) } - fn resolve_type<'a>( + fn resolve_statement_type<'a>( &'a self, handle: Handle, types: &'a Arena, ) -> Result<&'a crate::TypeInner, FunctionError> { - self.resolve_type_impl(handle, types) + self.resolve_statement_type_impl(handle, types) .map_err(|error| FunctionError::Expression { handle, error }) } @@ -880,7 +1086,7 @@ impl Validator { ref accept, ref reject, } => { - match *self.resolve_type(condition, context.types)? { + match *self.resolve_statement_type(condition, context.types)? { Ti::Scalar { kind: crate::ScalarKind::Bool, width: _, @@ -895,7 +1101,7 @@ impl Validator { ref cases, ref default, } => { - match *self.resolve_type(selector, context.types)? { + match *self.resolve_statement_type(selector, context.types)? { Ti::Scalar { kind: crate::ScalarKind::Sint, width: _, @@ -940,7 +1146,7 @@ impl Validator { return Err(FunctionError::InvalidReturnSpot); } let value_ty = value - .map(|expr| self.resolve_type(expr, context.types)) + .map(|expr| self.resolve_statement_type(expr, context.types)) .transpose()?; let expected_ty = context.return_type.map(|ty| &context.types[ty].inner); if value_ty != expected_ty { @@ -962,7 +1168,7 @@ impl Validator { self.typifier.try_get(current, context.types).ok_or( FunctionError::Expression { handle: current, - error: ExpressionError::Invalid, + error: ExpressionError::DoesntExist, }, )?; match context.expressions[current] { @@ -975,7 +1181,7 @@ impl Validator { } } - let value_ty = self.resolve_type(value, context.types)?; + let value_ty = self.resolve_statement_type(value, context.types)?; match *value_ty { Ti::Image { .. } | Ti::Sampler { .. } => { return Err(FunctionError::InvalidStoreValue(value)); @@ -1063,6 +1269,7 @@ impl Validator { fun: &crate::Function, _info: &FunctionInfo, module: &crate::Module, + stage: Option, ) -> Result<(), FunctionError> { let resolve_ctx = ResolveContext { constants: &module.constants, @@ -1097,6 +1304,9 @@ impl Validator { if expr.needs_pre_emit() { self.valid_expression_set.insert(handle.index()); } + if let Err(error) = self.validate_expression(handle, expr, fun, stage, module) { + return Err(FunctionError::Expression { handle, error }); + } } self.validate_block( @@ -1201,7 +1411,7 @@ impl Validator { } } - self.validate_function(&ep.function, info, module)?; + self.validate_function(&ep.function, info, module, Some(ep.stage))?; Ok(()) } @@ -1245,7 +1455,7 @@ impl Validator { } for (handle, fun) in module.functions.iter() { - self.validate_function(fun, &analysis[handle], module) + self.validate_function(fun, &analysis[handle], module, None) .map_err(|error| ValidationError::Function { handle, name: fun.name.clone().unwrap_or_default(), From d58f9bdfde77c7a8f5782cc0672a0b4b8af724e8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 18 Mar 2021 21:43:36 -0400 Subject: [PATCH 0595/2212] Merge sample mask in/out builtins --- src/back/glsl/mod.rs | 9 +++++++-- src/back/msl/mod.rs | 3 +-- src/back/spv/writer.rs | 3 +-- src/front/spv/convert.rs | 10 ++-------- src/front/spv/mod.rs | 8 ++++---- src/front/wgsl/conv.rs | 3 +-- src/lib.rs | 3 +-- src/proc/validator.rs | 6 +++--- 8 files changed, 20 insertions(+), 25 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 960fc449a..943f64c33 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2189,8 +2189,13 @@ fn glsl_built_in(built_in: BuiltIn, output: bool) -> &'static str { BuiltIn::FragDepth => "gl_FragDepth", BuiltIn::FrontFacing => "gl_FrontFacing", BuiltIn::SampleIndex => "gl_SampleID", - BuiltIn::SampleMaskIn => "gl_SampleMaskIn", - BuiltIn::SampleMaskOut => "gl_SampleMask", + BuiltIn::SampleMask => { + if output { + "gl_SampleMask" + } else { + "gl_SampleMaskIn" + } + } // compute BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", BuiltIn::LocalInvocationId => "gl_LocalInvocationID", diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index e08df6b9d..9eda260cf 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -193,8 +193,7 @@ impl ResolvedBinding { Bi::FragDepth => "depth(any)", Bi::FrontFacing => "front_facing", Bi::SampleIndex => "sample_id", - Bi::SampleMaskIn => "sample_mask", - Bi::SampleMaskOut => "sample_mask", + Bi::SampleMask => "sample_mask", // compute Bi::GlobalInvocationId => "thread_position_in_grid", Bi::LocalInvocationId => "thread_position_in_threadgroup", diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index ff2be31b9..b75db1573 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1101,8 +1101,7 @@ impl Writer { Bi::FragDepth => spirv::BuiltIn::FragDepth, Bi::FrontFacing => spirv::BuiltIn::FrontFacing, Bi::SampleIndex => spirv::BuiltIn::SampleId, - Bi::SampleMaskIn => spirv::BuiltIn::SampleMask, - Bi::SampleMaskOut => spirv::BuiltIn::SampleMask, + Bi::SampleMask => spirv::BuiltIn::SampleMask, // compute Bi::GlobalInvocationId => spirv::BuiltIn::GlobalInvocationId, Bi::LocalInvocationId => spirv::BuiltIn::LocalInvocationId, diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index baad81286..76c234e6f 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -113,7 +113,7 @@ pub(super) fn map_width(word: spirv::Word) -> Result { .map_err(|_| Error::InvalidTypeWidth(word)) } -pub(super) fn map_builtin(word: spirv::Word, is_output: bool) -> Result { +pub(super) fn map_builtin(word: spirv::Word) -> Result { use spirv::BuiltIn as Bi; Ok(match spirv::BuiltIn::from_u32(word) { Some(Bi::Position) | Some(Bi::FragCoord) => crate::BuiltIn::Position, @@ -128,13 +128,7 @@ pub(super) fn map_builtin(word: spirv::Word, is_output: bool) -> Result crate::BuiltIn::FragDepth, Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing, Some(Bi::SampleId) => crate::BuiltIn::SampleIndex, - Some(Bi::SampleMask) => { - if is_output { - crate::BuiltIn::SampleMaskOut - } else { - crate::BuiltIn::SampleMaskIn - } - } + Some(Bi::SampleMask) => crate::BuiltIn::SampleMask, // compute Some(Bi::GlobalInvocationId) => crate::BuiltIn::GlobalInvocationId, Some(Bi::LocalInvocationId) => crate::BuiltIn::LocalInvocationId, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 9ddb61ab6..90dbb4f16 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -234,13 +234,13 @@ impl Decoration { } } - fn io_binding(&self, is_output: bool) -> Result { + fn io_binding(&self) -> Result { match *self { Decoration { built_in: Some(built_in), location: None, .. - } => map_builtin(built_in, is_output).map(crate::Binding::BuiltIn), + } => map_builtin(built_in).map(crate::Binding::BuiltIn), Decoration { built_in: None, location: Some(loc), @@ -2791,7 +2791,7 @@ impl> Parser { (Variable::Global, var) } ExtendedClass::Input => { - let binding = dec.io_binding(false)?; + let binding = dec.io_binding()?; if let crate::Binding::BuiltIn(built_in) = binding { let needs_inner_uint = match built_in { crate::BuiltIn::BaseInstance @@ -2840,7 +2840,7 @@ impl> Parser { (inner, var) } ExtendedClass::Output => { - let binding = dec.io_binding(true)?; + let binding = dec.io_binding()?; let var = crate::GlobalVariable { name: dec.name, class: crate::StorageClass::Private, diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 2bdc7051d..396dbd24a 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -20,8 +20,7 @@ pub fn map_built_in(word: &str) -> Result> { "front_facing" => crate::BuiltIn::FrontFacing, "frag_depth" => crate::BuiltIn::FragDepth, "sample_index" => crate::BuiltIn::SampleIndex, - "sample_mask_in" => crate::BuiltIn::SampleMaskIn, - "sample_mask_out" => crate::BuiltIn::SampleMaskOut, + "sample_mask" => crate::BuiltIn::SampleMask, // compute "global_invocation_id" => crate::BuiltIn::GlobalInvocationId, "local_invocation_id" => crate::BuiltIn::LocalInvocationId, diff --git a/src/lib.rs b/src/lib.rs index 52de57311..1df4e0004 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -154,8 +154,7 @@ pub enum BuiltIn { FragDepth, FrontFacing, SampleIndex, - SampleMaskIn, - SampleMaskOut, + SampleMask, // compute GlobalInvocationId, LocalInvocationId, diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 9ab67e025..4c5a804e4 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -419,7 +419,7 @@ impl VaryingContext<'_> { width: crate::BOOL_WIDTH, }, ), - Bi::SampleIndex | Bi::SampleMaskIn => ( + Bi::SampleIndex => ( self.stage == St::Fragment && !self.output, *ty_inner == Ti::Scalar { @@ -427,8 +427,8 @@ impl VaryingContext<'_> { width, }, ), - Bi::SampleMaskOut => ( - self.stage == St::Fragment && self.output, + Bi::SampleMask => ( + self.stage == St::Fragment, *ty_inner == Ti::Scalar { kind: Sk::Uint, From daab319dc091a1bfed07e1cd7c09d238545f984d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 18 Mar 2021 22:38:13 -0400 Subject: [PATCH 0596/2212] Validate Expression::Compose --- src/proc/layouter.rs | 18 +----- src/proc/mod.rs | 19 ++++++ src/proc/validator.rs | 144 ++++++++++++++++++++++++++++++++++++------ 3 files changed, 146 insertions(+), 35 deletions(-) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index ce798bc88..280305bcd 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -88,21 +88,9 @@ impl Layouter { }, Ti::Array { base, size, stride } => { let count = match size { - crate::ArraySize::Constant(handle) => match constants[handle].inner { - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(value), - } => value as u32, - // Accept a signed integer size to avoid - // requiring an explicit uint - // literal. Type inference should make - // this unnecessary. - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Sint(value), - } => value as u32, - ref other => unreachable!("Unexpected array size {:?}", other), - }, + crate::ArraySize::Constant(handle) => { + constants[handle].to_array_length().unwrap() + } // A dynamically-sized array has to have at least one element crate::ArraySize::Dynamic => 1, }; diff --git a/src/proc/mod.rs b/src/proc/mod.rs index aa383fcb0..c4ad803af 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -158,3 +158,22 @@ impl crate::SampleLevel { } } } + +impl crate::Constant { + pub fn to_array_length(&self) -> Option { + use std::convert::TryInto; + match self.inner { + crate::ConstantInner::Scalar { value, width: _ } => match value { + crate::ScalarValue::Uint(value) => value.try_into().ok(), + // Accept a signed integer size to avoid + // requiring an explicit uint + // literal. Type inference should make + // this unnecessary. + crate::ScalarValue::Sint(value) => value.try_into().ok(), + _ => None, + }, + // caught by type validation + crate::ConstantInner::Composite { .. } => None, + } + } +} diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 4c5a804e4..49466d83b 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -173,6 +173,14 @@ pub enum ExpressionError { InvalidPointerType(Handle), #[error("Array length of {0:?} can't be done")] InvalidArrayType(Handle), + #[error("Compose type {0:?} doesn't exist")] + ComposeTypeDoesntExist(Handle), + #[error("Composing of type {0:?} can't be done")] + InvalidComposeType(Handle), + #[error("Composing expects {expected} components but {given} were given")] + InvalidComposeCount { given: u32, expected: u32 }, + #[error("Composing {0}'s component {1:?} is not expected")] + InvalidComponentType(u32, Handle), } #[derive(Clone, Debug, Error)] @@ -880,7 +888,6 @@ impl Validator { module: &crate::Module, ) -> Result<(), ExpressionError> { use crate::{Expression as E, TypeInner as Ti}; - use std::convert::TryInto; let resolver = ExpressionTypeResolver { root, @@ -923,24 +930,7 @@ impl Validator { Ti::Array { size: crate::ArraySize::Constant(handle), .. - } => { - match module - .constants - .try_get(handle) - .ok_or(ExpressionError::ConstantDoesntExist(handle))? - .inner - { - crate::ConstantInner::Scalar { value, width: _ } => match value { - crate::ScalarValue::Sint(value) => { - value.max(0).try_into().unwrap_or(!0) - } - crate::ScalarValue::Uint(value) => value.try_into().unwrap_or(!0), - _ => unreachable!(), - }, - // caught by type validation - crate::ConstantInner::Composite { .. } => unreachable!(), - } - } + } => module.constants[handle].to_array_length().unwrap(), Ti::Array { .. } => !0, // can't statically know, but need run-time checks Ti::Pointer { .. } => !0, //TODO Ti::Struct { @@ -963,7 +953,121 @@ impl Validator { .ok_or(ExpressionError::ConstantDoesntExist(handle))?; } E::Compose { ref components, ty } => { - //TODO + match module + .types + .try_get(ty) + .ok_or(ExpressionError::ComposeTypeDoesntExist(ty))? + .inner + { + // vectors are composed from scalars or other vectors + Ti::Vector { size, kind, width } => { + let inner = Ti::Scalar { kind, width }; + let mut total = 0; + for (index, &comp) in components.iter().enumerate() { + total += match *resolver.resolve(comp)? { + Ti::Scalar { + kind: comp_kind, + width: comp_width, + } if comp_kind == kind && comp_width == width => 1, + Ti::Vector { + size: comp_size, + kind: comp_kind, + width: comp_width, + } if comp_kind == kind && comp_width == width => comp_size as u32, + ref other => { + log::error!("Vector component[{}] type {:?}", index, other); + return Err(ExpressionError::InvalidComponentType( + index as u32, + comp, + )); + } + }; + } + if size as u32 != total { + return Err(ExpressionError::InvalidComposeCount { + expected: size as u32, + given: total, + }); + } + } + // matrix are composed from column vectors + Ti::Matrix { + columns, + rows, + width, + } => { + let inner = Ti::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }; + if columns as usize != components.len() { + return Err(ExpressionError::InvalidComposeCount { + expected: columns as u32, + given: components.len() as u32, + }); + } + for (index, &comp) in components.iter().enumerate() { + let tin = resolver.resolve(comp)?; + if tin != &inner { + log::error!("Matrix component[{}] type {:?}", index, tin); + return Err(ExpressionError::InvalidComponentType( + index as u32, + comp, + )); + } + } + } + Ti::Array { + base, + size: crate::ArraySize::Constant(handle), + stride: _, + } => { + let count = module.constants[handle].to_array_length().unwrap(); + if count as usize != components.len() { + return Err(ExpressionError::InvalidComposeCount { + expected: count, + given: components.len() as u32, + }); + } + let base_inner = &module.types[base].inner; + for (index, &comp) in components.iter().enumerate() { + let tin = resolver.resolve(comp)?; + if tin != base_inner { + log::error!("Array component[{}] type {:?}", index, tin); + return Err(ExpressionError::InvalidComponentType( + index as u32, + comp, + )); + } + } + } + Ti::Struct { + block: _, + ref members, + } => { + for (index, (member, &comp)) in members.iter().zip(components).enumerate() { + let tin = resolver.resolve(comp)?; + if tin != &module.types[member.ty].inner { + log::error!("Struct component[{}] type {:?}", index, tin); + return Err(ExpressionError::InvalidComponentType( + index as u32, + comp, + )); + } + } + if members.len() != components.len() { + return Err(ExpressionError::InvalidComposeCount { + given: components.len() as u32, + expected: members.len() as u32, + }); + } + } + ref other => { + log::error!("Composing of {:?}", other); + return Err(ExpressionError::InvalidComposeType(ty)); + } + } } E::FunctionArgument(index) => { if index >= function.arguments.len() as u32 { From c2f70aaf809b6ba5733dbf07878304d003d9f9fa Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 19 Mar 2021 00:40:48 -0400 Subject: [PATCH 0597/2212] Validate binary expressions --- src/front/wgsl/mod.rs | 16 ++- src/proc/validator.rs | 190 +++++++++++++++++++++++++++- tests/in/boids.wgsl | 2 +- tests/in/texture-array.wgsl | 2 +- tests/out/boids.msl.snap | 2 +- tests/out/boids.spvasm.snap | 96 +++++++------- tests/out/texture-array.spvasm.snap | 74 +++++------ 7 files changed, 287 insertions(+), 95 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7586dc1af..e54fac72a 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2575,7 +2575,7 @@ impl Parser { lexer.expect(Token::Separator(';'))?; } (Token::Word("const"), _) => { - let (name, _ty, _access) = self.parse_variable_ident_decl( + let (name, explicit_ty, _access) = self.parse_variable_ident_decl( lexer, &mut module.types, &mut module.constants, @@ -2589,6 +2589,20 @@ impl Parser { &mut module.types, &mut module.constants, )?; + let con = &module.constants[const_handle]; + let type_match = match con.inner { + crate::ConstantInner::Scalar { width, value } => { + module.types[explicit_ty].inner + == crate::TypeInner::Scalar { + kind: value.scalar_kind(), + width, + } + } + crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty, + }; + if !type_match { + return Err(Error::ConstTypeMismatch(name, explicit_ty)); + } //TODO: check `ty` against `const_handle`. lexer.expect(Token::Separator(';'))?; lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 49466d83b..d18240c87 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -181,6 +181,14 @@ pub enum ExpressionError { InvalidComposeCount { given: u32, expected: u32 }, #[error("Composing {0}'s component {1:?} is not expected")] InvalidComponentType(u32, Handle), + #[error("Operation {0:?} can't work with {1:?}")] + InvalidUnaryOperandType(crate::UnaryOperator, Handle), + #[error("Operation {0:?} can't work with {1:?} and {2:?}")] + InvalidBinaryOperandTypes( + crate::BinaryOperator, + Handle, + Handle, + ), } #[derive(Clone, Debug, Error)] @@ -887,7 +895,7 @@ impl Validator { stage: Option, module: &crate::Module, ) -> Result<(), ExpressionError> { - use crate::{Expression as E, TypeInner as Ti}; + use crate::{Expression as E, ScalarKind as Sk, TypeInner as Ti}; let resolver = ExpressionTypeResolver { root, @@ -910,11 +918,11 @@ impl Validator { match *resolver.resolve(index)? { //TODO: only allow one of these Ti::Scalar { - kind: crate::ScalarKind::Sint, + kind: Sk::Sint, width: _, } | Ti::Scalar { - kind: crate::ScalarKind::Uint, + kind: Sk::Uint, width: _, } => {} ref other => { @@ -998,7 +1006,7 @@ impl Validator { } => { let inner = Ti::Vector { size: rows, - kind: crate::ScalarKind::Float, + kind: Sk::Float, width, }; if columns as usize != components.len() { @@ -1109,8 +1117,178 @@ impl Validator { index, } => {} E::ImageQuery { image, query } => {} - E::Unary { op, expr } => {} - E::Binary { op, left, right } => {} + E::Unary { op, expr } => { + use crate::UnaryOperator as Uo; + let inner = resolver.resolve(expr)?; + match (op, inner.scalar_kind()) { + (_, Some(Sk::Sint)) + | (_, Some(Sk::Bool)) + | (Uo::Negate, Some(Sk::Float)) + | (Uo::Not, Some(Sk::Uint)) => {} + other => { + log::error!("Op {:?} kind {:?}", op, other); + return Err(ExpressionError::InvalidUnaryOperandType(op, expr)); + } + } + } + E::Binary { op, left, right } => { + use crate::BinaryOperator as Bo; + let left_inner = resolver.resolve(left)?; + let right_inner = resolver.resolve(right)?; + let good = match op { + Bo::Add | Bo::Subtract | Bo::Divide | Bo::Modulo => match *left_inner { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { + Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner, + Sk::Bool => false, + }, + _ => false, + }, + Bo::Multiply => { + let kind_match = match left_inner.scalar_kind() { + Some(Sk::Uint) | Some(Sk::Sint) | Some(Sk::Float) => true, + Some(Sk::Bool) | None => false, + }; + //TODO: should we be more restrictive here? I.e. expect scalar only to the left. + let types_match = match (left_inner, right_inner) { + (&Ti::Scalar { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) + | (&Ti::Vector { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) + | (&Ti::Scalar { kind: kind1, .. }, &Ti::Vector { kind: kind2, .. }) => { + kind1 == kind2 + } + ( + &Ti::Scalar { + kind: Sk::Float, .. + }, + &Ti::Matrix { .. }, + ) + | ( + &Ti::Matrix { .. }, + &Ti::Scalar { + kind: Sk::Float, .. + }, + ) => true, + ( + &Ti::Vector { + kind: kind1, + size: size1, + .. + }, + &Ti::Vector { + kind: kind2, + size: size2, + .. + }, + ) => kind1 == kind2 && size1 == size2, + ( + &Ti::Matrix { columns, .. }, + &Ti::Vector { + kind: Sk::Float, + size, + .. + }, + ) => columns == size, + ( + &Ti::Vector { + kind: Sk::Float, + size, + .. + }, + &Ti::Matrix { rows, .. }, + ) => size == rows, + (&Ti::Matrix { columns, .. }, &Ti::Matrix { rows, .. }) => { + columns == rows + } + _ => false, + }; + let left_width = match *left_inner { + Ti::Scalar { width, .. } + | Ti::Vector { width, .. } + | Ti::Matrix { width, .. } => width, + _ => 0, + }; + let right_width = match *right_inner { + Ti::Scalar { width, .. } + | Ti::Vector { width, .. } + | Ti::Matrix { width, .. } => width, + _ => 0, + }; + kind_match && types_match && left_width == right_width + } + Bo::Equal | Bo::NotEqual => match *left_inner { + Ti::Scalar { .. } + | Ti::Vector { .. } + | Ti::Matrix { .. } + | Ti::Array { + size: crate::ArraySize::Constant(_), + .. + } + | Ti::Pointer { .. } + | Ti::ValuePointer { .. } + | Ti::Struct { .. } => left_inner == right_inner, + Ti::Array { .. } | Ti::Image { .. } | Ti::Sampler { .. } => false, + }, + Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual => { + match *left_inner { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { + Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner, + Sk::Bool => false, + }, + ref other => { + log::error!("Op {:?} left type {:?}", op, other); + false + } + } + } + Bo::LogicalAnd | Bo::LogicalOr => match *left_inner { + Ti::Scalar { kind: Sk::Bool, .. } | Ti::Vector { kind: Sk::Bool, .. } => { + left_inner == right_inner + } + ref other => { + log::error!("Op {:?} left type {:?}", op, other); + false + } + }, + Bo::And | Bo::ExclusiveOr | Bo::InclusiveOr => match *left_inner { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { + Sk::Sint | Sk::Uint => left_inner == right_inner, + Sk::Bool | Sk::Float => false, + }, + ref other => { + log::error!("Op {:?} left type {:?}", op, other); + false + } + }, + Bo::ShiftLeft | Bo::ShiftRight => { + let (base_size, base_kind) = match *left_inner { + Ti::Scalar { kind, .. } => (Ok(None), kind), + Ti::Vector { size, kind, .. } => (Ok(Some(size)), kind), + ref other => { + log::error!("Op {:?} base type {:?}", op, other); + (Err(()), Sk::Bool) + } + }; + let shift_size = match *right_inner { + Ti::Scalar { kind: Sk::Uint, .. } => Ok(None), + Ti::Vector { + size, + kind: Sk::Uint, + .. + } => Ok(Some(size)), + ref other => { + log::error!("Op {:?} shift type {:?}", op, other); + Err(()) + } + }; + match base_kind { + Sk::Sint | Sk::Uint => base_size.is_ok() && base_size == shift_size, + Sk::Float | Sk::Bool => false, + } + } + }; + if !good { + return Err(ExpressionError::InvalidBinaryOperandTypes(op, left, right)); + } + } E::Select { condition, accept, diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 3b404f9f0..f41a6ffa0 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -1,4 +1,4 @@ -const NUM_PARTICLES: u32 = 1500; +const NUM_PARTICLES: u32 = 1500u; [[block]] struct Particle { diff --git a/tests/in/texture-array.wgsl b/tests/in/texture-array.wgsl index ca14d8c23..5f2e09b35 100644 --- a/tests/in/texture-array.wgsl +++ b/tests/in/texture-array.wgsl @@ -10,7 +10,7 @@ var pc: PushConstants; [[stage(fragment)]] fn main([[location(0)]] tex_coord: vec2) -> [[location(1)]] vec4 { - if (pc.index == 0) { + if (pc.index == 0u) { return textureSample(texture0, sampler, tex_coord); } else { return textureSample(texture1, sampler, tex_coord); diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index 7fe3c2c82..816ad79a4 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -27,7 +27,7 @@ struct Particles { }; typedef metal::uint3 type4; typedef int type5; -constexpr constant int NUM_PARTICLES = 1500; +constexpr constant unsigned NUM_PARTICLES = 1500u; constexpr constant float const_0f = 0.0; constexpr constant int const_0i = 0; constexpr constant unsigned const_0u = 0u; diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index 80e3f0860..1564f5c01 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -64,15 +64,15 @@ OpDecorate %24 DescriptorSet 0 OpDecorate %24 Binding 2 OpDecorate %40 BuiltIn GlobalInvocationId %2 = OpTypeVoid -%4 = OpTypeInt 32 1 +%4 = OpTypeInt 32 0 %3 = OpConstant %4 1500 %6 = OpTypeFloat 32 %5 = OpConstant %6 0.0 -%7 = OpConstant %4 0 -%9 = OpTypeInt 32 0 -%8 = OpConstant %9 0 -%10 = OpConstant %4 1 -%11 = OpConstant %9 1 +%8 = OpTypeInt 32 1 +%7 = OpConstant %8 0 +%9 = OpConstant %4 0 +%10 = OpConstant %8 1 +%11 = OpConstant %4 1 %12 = OpConstant %6 1.0 %13 = OpConstant %6 0.1 %14 = OpConstant %6 -1.0 @@ -87,9 +87,9 @@ OpDecorate %40 BuiltIn GlobalInvocationId %18 = OpVariable %23 Uniform %24 = OpVariable %23 Uniform %26 = OpTypePointer Function %22 -%32 = OpTypePointer Function %4 -%37 = OpTypePointer Function %9 -%39 = OpTypeVector %9 3 +%32 = OpTypePointer Function %8 +%37 = OpTypePointer Function %4 +%39 = OpTypeVector %4 3 %41 = OpTypePointer Input %39 %40 = OpVariable %41 Input %44 = OpTypeFunction %2 @@ -97,34 +97,34 @@ OpDecorate %40 BuiltIn GlobalInvocationId %51 = OpTypePointer Uniform %20 %52 = OpTypePointer Uniform %21 %53 = OpTypePointer Uniform %22 -%54 = OpConstant %4 0 -%55 = OpConstant %4 0 -%58 = OpConstant %4 1 -%59 = OpConstant %4 0 -%78 = OpConstant %4 0 -%79 = OpConstant %4 0 -%83 = OpConstant %4 1 -%84 = OpConstant %4 0 +%54 = OpConstant %8 0 +%55 = OpConstant %8 0 +%58 = OpConstant %8 1 +%59 = OpConstant %8 0 +%78 = OpConstant %8 0 +%79 = OpConstant %8 0 +%83 = OpConstant %8 1 +%84 = OpConstant %8 0 %90 = OpTypePointer Uniform %6 -%91 = OpConstant %4 1 -%105 = OpConstant %4 2 -%119 = OpConstant %4 3 -%154 = OpConstant %4 4 -%160 = OpConstant %4 5 -%166 = OpConstant %4 6 -%179 = OpConstant %4 0 +%91 = OpConstant %8 1 +%105 = OpConstant %8 2 +%119 = OpConstant %8 3 +%154 = OpConstant %8 4 +%160 = OpConstant %8 5 +%166 = OpConstant %8 6 +%179 = OpConstant %8 0 %189 = OpTypePointer Function %6 -%190 = OpConstant %4 0 -%197 = OpConstant %4 0 -%204 = OpConstant %4 1 -%211 = OpConstant %4 1 -%214 = OpConstant %4 0 -%215 = OpConstant %4 0 -%218 = OpConstant %4 1 -%219 = OpConstant %4 0 +%190 = OpConstant %8 0 +%197 = OpConstant %8 0 +%204 = OpConstant %8 1 +%211 = OpConstant %8 1 +%214 = OpConstant %8 0 +%215 = OpConstant %8 0 +%218 = OpConstant %8 1 +%219 = OpConstant %8 0 %43 = OpFunction %2 None %44 %38 = OpLabel -%36 = OpVariable %37 Function %8 +%36 = OpVariable %37 Function %9 %33 = OpVariable %32 Function %7 %29 = OpVariable %26 Function %25 = OpVariable %26 Function @@ -137,7 +137,7 @@ OpDecorate %40 BuiltIn GlobalInvocationId %42 = OpLoad %39 %40 OpBranch %45 %45 = OpLabel -%46 = OpCompositeExtract %9 %42 0 +%46 = OpCompositeExtract %4 %42 0 %48 = OpUGreaterThanEqual %47 %46 %3 OpSelectionMerge %49 None OpBranchConditional %48 %50 %49 @@ -161,25 +161,25 @@ OpBranch %65 OpLoopMerge %66 %68 None OpBranch %67 %67 = OpLabel -%69 = OpLoad %9 %36 +%69 = OpLoad %4 %36 %70 = OpUGreaterThanEqual %47 %69 %3 OpSelectionMerge %71 None OpBranchConditional %70 %72 %71 %72 = OpLabel OpBranch %66 %71 = OpLabel -%73 = OpLoad %9 %36 +%73 = OpLoad %4 %36 %74 = OpIEqual %47 %73 %46 OpSelectionMerge %75 None OpBranchConditional %74 %76 %75 %76 = OpLabel OpBranch %68 %75 = OpLabel -%77 = OpLoad %9 %36 +%77 = OpLoad %4 %36 %80 = OpAccessChain %53 %18 %79 %77 %78 %81 = OpLoad %22 %80 OpStore %34 %81 -%82 = OpLoad %9 %36 +%82 = OpLoad %4 %36 %85 = OpAccessChain %53 %18 %84 %82 %83 %86 = OpLoad %22 %85 OpStore %35 %86 @@ -196,8 +196,8 @@ OpBranchConditional %94 %96 %95 %98 = OpLoad %22 %34 %99 = OpFAdd %22 %97 %98 OpStore %28 %99 -%100 = OpLoad %4 %31 -%101 = OpIAdd %4 %100 %10 +%100 = OpLoad %8 %31 +%101 = OpIAdd %8 %100 %10 OpStore %31 %101 OpBranch %95 %95 = OpLabel @@ -231,25 +231,25 @@ OpBranchConditional %122 %124 %123 %126 = OpLoad %22 %35 %127 = OpFAdd %22 %125 %126 OpStore %29 %127 -%128 = OpLoad %4 %33 -%129 = OpIAdd %4 %128 %10 +%128 = OpLoad %8 %33 +%129 = OpIAdd %8 %128 %10 OpStore %33 %129 OpBranch %123 %123 = OpLabel OpBranch %68 %68 = OpLabel -%130 = OpLoad %9 %36 -%131 = OpIAdd %9 %130 %11 +%130 = OpLoad %4 %36 +%131 = OpIAdd %4 %130 %11 OpStore %36 %131 OpBranch %65 %66 = OpLabel -%132 = OpLoad %4 %31 +%132 = OpLoad %8 %31 %133 = OpSGreaterThan %47 %132 %7 OpSelectionMerge %134 None OpBranchConditional %133 %135 %134 %135 = OpLabel %136 = OpLoad %22 %28 -%137 = OpLoad %4 %31 +%137 = OpLoad %8 %31 %138 = OpConvertSToF %6 %137 %139 = OpFDiv %6 %12 %138 %140 = OpVectorTimesScalar %22 %136 %139 @@ -258,13 +258,13 @@ OpBranchConditional %133 %135 %134 OpStore %28 %142 OpBranch %134 %134 = OpLabel -%143 = OpLoad %4 %33 +%143 = OpLoad %8 %33 %144 = OpSGreaterThan %47 %143 %7 OpSelectionMerge %145 None OpBranchConditional %144 %146 %145 %146 = OpLabel %147 = OpLoad %22 %29 -%148 = OpLoad %4 %33 +%148 = OpLoad %8 %33 %149 = OpConvertSToF %6 %148 %150 = OpFDiv %6 %12 %149 %151 = OpVectorTimesScalar %22 %147 %150 diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap index aa9942f94..ae41626ab 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm.snap @@ -9,8 +9,8 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %25 "main" %19 %23 -OpExecutionMode %25 OriginUpperLeft +OpEntryPoint Fragment %24 "main" %18 %22 +OpExecutionMode %24 OriginUpperLeft OpSource GLSL 450 OpName %5 "texture0" OpName %9 "texture1" @@ -18,9 +18,9 @@ OpName %10 "sampler" OpName %14 "PushConstants" OpMemberName %14 0 "index" OpName %13 "pc" -OpName %19 "tex_coord" -OpName %25 "main" -OpName %25 "main" +OpName %18 "tex_coord" +OpName %24 "main" +OpName %24 "main" OpDecorate %5 DescriptorSet 0 OpDecorate %5 Binding 0 OpDecorate %9 DescriptorSet 0 @@ -29,10 +29,10 @@ OpDecorate %10 DescriptorSet 0 OpDecorate %10 Binding 2 OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 -OpDecorate %19 Location 0 -OpDecorate %23 Location 1 +OpDecorate %18 Location 0 +OpDecorate %22 Location 1 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 +%4 = OpTypeInt 32 0 %3 = OpConstant %4 0 %7 = OpTypeFloat 32 %6 = OpTypeImage %7 2D 0 0 0 1 Unknown @@ -42,43 +42,43 @@ OpDecorate %23 Location 1 %11 = OpTypeSampler %12 = OpTypePointer UniformConstant %11 %10 = OpVariable %12 UniformConstant -%15 = OpTypeInt 32 0 -%14 = OpTypeStruct %15 -%16 = OpTypePointer PushConstant %14 -%13 = OpVariable %16 PushConstant -%18 = OpTypeVector %7 2 -%20 = OpTypePointer Input %18 -%19 = OpVariable %20 Input -%22 = OpTypeVector %7 4 -%24 = OpTypePointer Output %22 -%23 = OpVariable %24 Output -%26 = OpTypeFunction %2 -%31 = OpTypePointer PushConstant %15 -%32 = OpConstant %4 0 +%14 = OpTypeStruct %4 +%15 = OpTypePointer PushConstant %14 +%13 = OpVariable %15 PushConstant +%17 = OpTypeVector %7 2 +%19 = OpTypePointer Input %17 +%18 = OpVariable %19 Input +%21 = OpTypeVector %7 4 +%23 = OpTypePointer Output %21 +%22 = OpVariable %23 Output +%25 = OpTypeFunction %2 +%30 = OpTypePointer PushConstant %4 +%31 = OpTypeInt 32 1 +%32 = OpConstant %31 0 %35 = OpTypeBool %40 = OpTypeSampledImage %6 -%25 = OpFunction %2 None %26 -%17 = OpLabel -%21 = OpLoad %18 %19 -%27 = OpLoad %6 %5 -%28 = OpLoad %6 %9 -%29 = OpLoad %11 %10 -OpBranch %30 -%30 = OpLabel -%33 = OpAccessChain %31 %13 %32 -%34 = OpLoad %15 %33 +%24 = OpFunction %2 None %25 +%16 = OpLabel +%20 = OpLoad %17 %18 +%26 = OpLoad %6 %5 +%27 = OpLoad %6 %9 +%28 = OpLoad %11 %10 +OpBranch %29 +%29 = OpLabel +%33 = OpAccessChain %30 %13 %32 +%34 = OpLoad %4 %33 %36 = OpIEqual %35 %34 %3 OpSelectionMerge %37 None OpBranchConditional %36 %38 %39 %38 = OpLabel -%41 = OpSampledImage %40 %27 %29 -%42 = OpImageSampleImplicitLod %22 %41 %21 -OpStore %23 %42 +%41 = OpSampledImage %40 %26 %28 +%42 = OpImageSampleImplicitLod %21 %41 %20 +OpStore %22 %42 OpReturn %39 = OpLabel -%43 = OpSampledImage %40 %28 %29 -%44 = OpImageSampleImplicitLod %22 %43 %21 -OpStore %23 %44 +%43 = OpSampledImage %40 %27 %28 +%44 = OpImageSampleImplicitLod %21 %43 %20 +OpStore %22 %44 OpReturn %37 = OpLabel OpReturn From d5fbb193c354ec4886345435288a83df321c1c8e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 19 Mar 2021 01:02:56 -0400 Subject: [PATCH 0598/2212] Validate Select and Relational expressions --- src/proc/validator.rs | 101 +++++++++++++++++++++++++++++++++--------- 1 file changed, 80 insertions(+), 21 deletions(-) diff --git a/src/proc/validator.rs b/src/proc/validator.rs index d18240c87..4ca67bf3a 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -189,6 +189,12 @@ pub enum ExpressionError { Handle, Handle, ), + #[error("Selecting is not possible")] + InvalidSelectTypes, + #[error("Relational argument {0:?} is not a boolean vector")] + InvalidBooleanVector(Handle), + #[error("Relational argument {0:?} is not a float")] + InvalidFloatArgument(Handle), } #[derive(Clone, Debug, Error)] @@ -358,6 +364,24 @@ fn storage_usage(access: crate::StorageAccess) -> GlobalUse { storage_usage } +impl crate::TypeInner { + fn is_sized(&self) -> bool { + match *self { + Self::Scalar { .. } + | Self::Vector { .. } + | Self::Matrix { .. } + | Self::Array { + size: crate::ArraySize::Constant(_), + .. + } + | Self::Pointer { .. } + | Self::ValuePointer { .. } + | Self::Struct { .. } => true, + Self::Array { .. } | Self::Image { .. } | Self::Sampler { .. } => false, + } + } +} + struct VaryingContext<'a> { ty: Handle, stage: crate::ShaderStage, @@ -892,7 +916,6 @@ impl Validator { root: Handle, expression: &crate::Expression, function: &crate::Function, - stage: Option, module: &crate::Module, ) -> Result<(), ExpressionError> { use crate::{Expression as E, ScalarKind as Sk, TypeInner as Ti}; @@ -1214,19 +1237,7 @@ impl Validator { }; kind_match && types_match && left_width == right_width } - Bo::Equal | Bo::NotEqual => match *left_inner { - Ti::Scalar { .. } - | Ti::Vector { .. } - | Ti::Matrix { .. } - | Ti::Array { - size: crate::ArraySize::Constant(_), - .. - } - | Ti::Pointer { .. } - | Ti::ValuePointer { .. } - | Ti::Struct { .. } => left_inner == right_inner, - Ti::Array { .. } | Ti::Image { .. } | Ti::Sampler { .. } => false, - }, + Bo::Equal | Bo::NotEqual => left_inner.is_sized() && left_inner == right_inner, Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual => { match *left_inner { Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { @@ -1293,9 +1304,58 @@ impl Validator { condition, accept, reject, - } => {} - E::Derivative { axis, expr } => {} - E::Relational { argument, .. } => {} + } => { + let accept_inner = resolver.resolve(accept)?; + let reject_inner = resolver.resolve(reject)?; + let condition_good = match *resolver.resolve(condition)? { + Ti::Scalar { + kind: Sk::Bool, + width: _, + } => accept_inner.is_sized(), + Ti::Vector { + size, + kind: Sk::Bool, + width: _, + } => match *accept_inner { + Ti::Vector { + size: other_size, .. + } => size == other_size, + _ => false, + }, + _ => false, + }; + if !condition_good || accept_inner != reject_inner { + return Err(ExpressionError::InvalidSelectTypes); + } + } + E::Derivative { axis, expr } => { + //TODO: check stage + } + E::Relational { fun, argument } => { + use crate::RelationalFunction as Rf; + let argument_inner = resolver.resolve(argument)?; + match fun { + Rf::All | Rf::Any => match *argument_inner { + Ti::Vector { kind: Sk::Bool, .. } => {} + ref other => { + log::error!("All/Any of type {:?}", other); + return Err(ExpressionError::InvalidBooleanVector(argument)); + } + }, + Rf::IsNan | Rf::IsInf | Rf::IsFinite | Rf::IsNormal => match *argument_inner { + Ti::Scalar { + kind: Sk::Float, .. + } + | Ti::Vector { + kind: Sk::Float, .. + } => {} + ref other => { + log::error!("Float test of type {:?}", other); + return Err(ExpressionError::InvalidFloatArgument(argument)); + } + }, + } + } E::Math { fun, arg, @@ -1551,7 +1611,6 @@ impl Validator { fun: &crate::Function, _info: &FunctionInfo, module: &crate::Module, - stage: Option, ) -> Result<(), FunctionError> { let resolve_ctx = ResolveContext { constants: &module.constants, @@ -1586,7 +1645,7 @@ impl Validator { if expr.needs_pre_emit() { self.valid_expression_set.insert(handle.index()); } - if let Err(error) = self.validate_expression(handle, expr, fun, stage, module) { + if let Err(error) = self.validate_expression(handle, expr, fun, module) { return Err(FunctionError::Expression { handle, error }); } } @@ -1693,7 +1752,7 @@ impl Validator { } } - self.validate_function(&ep.function, info, module, Some(ep.stage))?; + self.validate_function(&ep.function, info, module)?; Ok(()) } @@ -1737,7 +1796,7 @@ impl Validator { } for (handle, fun) in module.functions.iter() { - self.validate_function(fun, &analysis[handle], module, None) + self.validate_function(fun, &analysis[handle], module) .map_err(|error| ValidationError::Function { handle, name: fun.name.clone().unwrap_or_default(), From caee860b70361022e3c81eadd2c6664a8c61c92e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 19 Mar 2021 23:45:36 -0400 Subject: [PATCH 0599/2212] Make uniformity analysis optional --- bin/convert.rs | 4 +- src/back/msl/writer.rs | 3 +- src/proc/analyzer.rs | 160 ++++--- src/proc/validator.rs | 8 +- tests/out/collatz.info.ron.snap | 157 +++++-- tests/out/shadow.info.ron.snap | 804 ++++++++++++++++++++++++-------- tests/parse.rs | 4 +- tests/snapshots.rs | 8 +- 8 files changed, 841 insertions(+), 307 deletions(-) diff --git a/bin/convert.rs b/bin/convert.rs index 89ce8759e..a5870b848 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -172,7 +172,9 @@ fn main() { // validate the IR #[allow(unused_variables)] - let analysis = match naga::proc::Validator::new().validate(&module) { + let analysis = match naga::proc::Validator::new(naga::proc::analyzer::AnalysisFlags::all()) + .validate(&module) + { Ok(analysis) => Some(analysis), Err(error) => { print_err(error); diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 5ccbf842f..2a9442352 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1490,6 +1490,7 @@ impl Writer { #[test] fn test_stack_size() { + use crate::proc::analyzer::AnalysisFlags; // create a module with at least one expression nested let mut module = crate::Module::default(); let constant = module.constants.append(crate::Constant { @@ -1517,7 +1518,7 @@ fn test_stack_size() { }); let _ = module.functions.append(fun); // analyse the module - let analysis = Analysis::new(&module).unwrap(); + let analysis = Analysis::new(&module, AnalysisFlags::empty()).unwrap(); // process the module let mut writer = Writer::new(String::new()); writer diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs index 793c01e28..c0b131a9b 100644 --- a/src/proc/analyzer.rs +++ b/src/proc/analyzer.rs @@ -11,19 +11,19 @@ use std::ops; pub type NonUniformResult = Option>; -/// Expressions that require uniform control flow. -#[derive(Clone, Copy, Debug)] -#[cfg_attr(feature = "serialize", derive(serde::Serialize))] -#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] -#[cfg_attr(test, derive(PartialEq))] -pub enum UniformityRequirement { - WorkGroupBarrier, - Derivative, - ImplicitLevel, +bitflags::bitflags! { + /// Kinds of expressions that require uniform control flow. + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + pub struct UniformityRequirements: u8 { + const WORK_GROUP_BARRIER = 0x1; + const DERIVATIVE = 0x2; + const IMPLICIT_LEVEL = 0x4; + } } /// Uniform control flow characteristics. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[cfg_attr(test, derive(PartialEq))] @@ -41,15 +41,14 @@ pub struct Uniformity { /// Any operations that depend on non-uniform results also produce non-uniform. pub non_uniform_result: NonUniformResult, /// If this expression requires uniform control flow, store the reason here. - pub requirement: Option, + pub requirements: UniformityRequirements, } impl Uniformity { - //TODO: is this helper really useful? - fn non_uniform_result(expr: Handle) -> Self { + fn new() -> Self { Uniformity { - non_uniform_result: Some(expr), - requirement: None, + non_uniform_result: None, + requirements: UniformityRequirements::empty(), } } } @@ -82,7 +81,7 @@ impl ops::BitOr for FunctionUniformity { .result .non_uniform_result .or(other.result.non_uniform_result), - requirement: self.result.requirement.or(other.result.requirement), + requirements: self.result.requirements | other.result.requirements, }, exit: self.exit | other.exit, } @@ -92,7 +91,7 @@ impl ops::BitOr for FunctionUniformity { impl FunctionUniformity { fn new() -> Self { FunctionUniformity { - result: Uniformity::default(), + result: Uniformity::new(), exit: ExitFlags::empty(), } } @@ -131,7 +130,7 @@ pub struct SamplingKey { pub sampler: Handle, } -#[derive(Clone, Default)] +#[derive(Clone)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ExpressionInfo { @@ -140,9 +139,21 @@ pub struct ExpressionInfo { assignable_global: Option>, } +impl ExpressionInfo { + fn new() -> Self { + ExpressionInfo { + uniformity: Uniformity::new(), + ref_count: 0, + assignable_global: None, + } + } +} + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct FunctionInfo { + /// Options. + flags: AnalysisFlags, /// Uniformity characteristics. pub uniformity: Uniformity, /// Function may kill the invocation. @@ -215,7 +226,7 @@ pub enum FunctionAnalysisError { "Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}" )] NonUniformControlFlow( - UniformityRequirement, + UniformityRequirements, Handle, UniformityDisruptor, ), @@ -311,21 +322,21 @@ impl FunctionInfo { non_uniform_result: self .add_assignable_ref(base, &mut assignable_global) .or(self.add_ref(index)), - requirement: None, + requirements: UniformityRequirements::empty(), }, E::AccessIndex { base, .. } => Uniformity { non_uniform_result: self.add_assignable_ref(base, &mut assignable_global), - requirement: None, + requirements: UniformityRequirements::empty(), }, // always uniform - E::Constant(_) => Uniformity::default(), + E::Constant(_) => Uniformity::new(), E::Compose { ref components, .. } => { let non_uniform_result = components .iter() .fold(None, |nur, &comp| nur.or(self.add_ref(comp))); Uniformity { non_uniform_result, - requirement: None, + requirements: UniformityRequirements::empty(), } } // depends on the builtin or interpolation @@ -346,7 +357,7 @@ impl FunctionInfo { }; Uniformity { non_uniform_result: if uniform { None } else { Some(handle) }, - requirement: None, + requirements: UniformityRequirements::empty(), } } // depends on the storage class @@ -368,13 +379,16 @@ impl FunctionInfo { }; Uniformity { non_uniform_result: if uniform { None } else { Some(handle) }, - requirement: None, + requirements: UniformityRequirements::empty(), } } - E::LocalVariable(_) => Uniformity::non_uniform_result(handle), + E::LocalVariable(_) => Uniformity { + non_uniform_result: Some(handle), + requirements: UniformityRequirements::empty(), + }, E::Load { pointer } => Uniformity { non_uniform_result: self.add_ref(pointer), - requirement: None, + requirements: UniformityRequirements::empty(), }, E::ImageSample { image, @@ -419,10 +433,10 @@ impl FunctionInfo { .or(array_nur) .or(level_nur) .or(dref_nur), - requirement: if level.implicit_derivatives() { - Some(UniformityRequirement::ImplicitLevel) + requirements: if level.implicit_derivatives() { + UniformityRequirements::IMPLICIT_LEVEL } else { - None + UniformityRequirements::empty() }, } } @@ -440,7 +454,7 @@ impl FunctionInfo { .or(self.add_ref(coordinate)) .or(array_nur) .or(index_nur), - requirement: None, + requirements: UniformityRequirements::empty(), } } E::ImageQuery { image, query } => { @@ -450,16 +464,16 @@ impl FunctionInfo { }; Uniformity { non_uniform_result: self.add_ref_impl(image, GlobalUse::QUERY).or(query_nur), - requirement: None, + requirements: UniformityRequirements::empty(), } } E::Unary { expr, .. } => Uniformity { non_uniform_result: self.add_ref(expr), - requirement: None, + requirements: UniformityRequirements::empty(), }, E::Binary { left, right, .. } => Uniformity { non_uniform_result: self.add_ref(left).or(self.add_ref(right)), - requirement: None, + requirements: UniformityRequirements::empty(), }, E::Select { condition, @@ -470,17 +484,17 @@ impl FunctionInfo { .add_ref(condition) .or(self.add_ref(accept)) .or(self.add_ref(reject)), - requirement: None, + requirements: UniformityRequirements::empty(), }, // explicit derivatives require uniform E::Derivative { expr, .. } => Uniformity { //Note: taking a derivative of a uniform doesn't make it non-uniform non_uniform_result: self.add_ref(expr), - requirement: Some(UniformityRequirement::Derivative), + requirements: UniformityRequirements::DERIVATIVE, }, E::Relational { argument, .. } => Uniformity { non_uniform_result: self.add_ref(argument), - requirement: None, + requirements: UniformityRequirements::empty(), }, E::Math { arg, arg1, arg2, .. @@ -489,12 +503,12 @@ impl FunctionInfo { let arg2_nur = arg2.and_then(|h| self.add_ref(h)); Uniformity { non_uniform_result: self.add_ref(arg).or(arg1_nur).or(arg2_nur), - requirement: None, + requirements: UniformityRequirements::empty(), } } E::As { expr, .. } => Uniformity { non_uniform_result: self.add_ref(expr), - requirement: None, + requirements: UniformityRequirements::empty(), }, E::Call(function) => { let fun = other_functions @@ -504,7 +518,7 @@ impl FunctionInfo { } E::ArrayLength(expr) => Uniformity { non_uniform_result: self.add_ref_impl(expr, GlobalUse::QUERY), - requirement: None, + requirements: UniformityRequirements::empty(), }, }; @@ -538,31 +552,31 @@ impl FunctionInfo { for statement in statements { let uniformity = match *statement { S::Emit(ref range) => { - let mut requirement = None; + let mut requirements = UniformityRequirements::empty(); for expr in range.clone() { - if let Some(req) = self.expressions[expr.index()].uniformity.requirement { - requirement = match disruptor { - Some(cause) => { - return Err(FunctionAnalysisError::NonUniformControlFlow( - req, expr, cause, - )) - } - // remember the requirement of any emitted expressions - None => Some(req), - }; + let req = self.expressions[expr.index()].uniformity.requirements; + if self.flags.contains(AnalysisFlags::CONTROL_FLOW_UNIFORMITY) + && !req.is_empty() + { + if let Some(cause) = disruptor { + return Err(FunctionAnalysisError::NonUniformControlFlow( + req, expr, cause, + )); + } } + requirements |= req; } FunctionUniformity { result: Uniformity { non_uniform_result: None, - requirement, + requirements, }, exit: ExitFlags::empty(), } } S::Break | S::Continue => FunctionUniformity::new(), S::Kill => FunctionUniformity { - result: Uniformity::default(), + result: Uniformity::new(), exit: ExitFlags::MAY_KILL, }, S::Block(ref b) => self.process_block(b, other_functions, disruptor)?, @@ -618,7 +632,7 @@ impl FunctionInfo { S::Return { value } => FunctionUniformity { result: Uniformity { non_uniform_result: value.and_then(|expr| self.add_ref(expr)), - requirement: None, + requirements: UniformityRequirements::empty(), }, //TODO: if we are in the uniform control flow, should this still be an exit flag? exit: ExitFlags::MAY_RETURN, @@ -667,10 +681,19 @@ impl FunctionInfo { } } -#[derive(Default)] +bitflags::bitflags! { + /// Analysis flags. + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + pub struct AnalysisFlags: u8 { + const CONTROL_FLOW_UNIFORMITY = 0x1; + } +} + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Analysis { + flags: AnalysisFlags, functions: Vec, entry_points: Vec, } @@ -684,11 +707,12 @@ impl Analysis { global_var_arena: &Arena, ) -> Result { let mut info = FunctionInfo { - uniformity: Uniformity::default(), + flags: self.flags, + uniformity: Uniformity::new(), may_kill: false, sampling_set: crate::FastHashSet::default(), global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), - expressions: vec![ExpressionInfo::default(); fun.expressions.len()].into_boxed_slice(), + expressions: vec![ExpressionInfo::new(); fun.expressions.len()].into_boxed_slice(), }; for (handle, _) in fun.expressions.iter() { @@ -709,8 +733,9 @@ impl Analysis { } /// Analyze a module and return the `Analysis`, if successful. - pub fn new(module: &crate::Module) -> Result { + pub fn new(module: &crate::Module, flags: AnalysisFlags) -> Result { let mut this = Analysis { + flags, functions: Vec::with_capacity(module.functions.len()), entry_points: Vec::with_capacity(module.entry_points.len()), }; @@ -805,11 +830,12 @@ fn uniform_control_flow() { let emit_range_query_access_globals = expressions.range_from(2); let mut info = FunctionInfo { - uniformity: Uniformity::default(), + flags: AnalysisFlags::all(), + uniformity: Uniformity::new(), may_kill: false, sampling_set: crate::FastHashSet::default(), global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), - expressions: vec![ExpressionInfo::default(); expressions.len()].into_boxed_slice(), + expressions: vec![ExpressionInfo::new(); expressions.len()].into_boxed_slice(), }; for (handle, _) in expressions.iter() { info.process_expression(handle, &expressions, &[], &global_var_arena, &[]) @@ -839,7 +865,7 @@ fn uniform_control_flow() { Ok(FunctionUniformity { result: Uniformity { non_uniform_result: None, - requirement: Some(UniformityRequirement::Derivative), + requirements: UniformityRequirements::DERIVATIVE, }, exit: ExitFlags::empty(), }), @@ -862,7 +888,7 @@ fn uniform_control_flow() { assert_eq!( info.process_block(&[stmt_emit2, stmt_if_non_uniform], &[], None), Err(FunctionAnalysisError::NonUniformControlFlow( - UniformityRequirement::Derivative, + UniformityRequirements::DERIVATIVE, derivative_expr, UniformityDisruptor::Expression(non_uniform_global_expr) )), @@ -881,7 +907,10 @@ fn uniform_control_flow() { Some(UniformityDisruptor::Return) ), Ok(FunctionUniformity { - result: Uniformity::non_uniform_result(non_uniform_global_expr), + result: Uniformity { + non_uniform_result: Some(non_uniform_global_expr), + requirements: UniformityRequirements::empty(), + }, exit: ExitFlags::MAY_RETURN, }), ); @@ -904,7 +933,10 @@ fn uniform_control_flow() { Some(UniformityDisruptor::Discard) ), Ok(FunctionUniformity { - result: Uniformity::non_uniform_result(non_uniform_global_expr), + result: Uniformity { + non_uniform_result: Some(non_uniform_global_expr), + requirements: UniformityRequirements::empty(), + }, exit: ExitFlags::all(), }), ); diff --git a/src/proc/validator.rs b/src/proc/validator.rs index 4ca67bf3a..837fed50b 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -1,5 +1,5 @@ use super::{ - analyzer::{Analysis, AnalysisError, FunctionInfo, GlobalUse}, + analyzer::{Analysis, AnalysisError, AnalysisFlags, FunctionInfo, GlobalUse}, typifier::{ResolveContext, Typifier, TypifyError}, }; use crate::{ @@ -66,6 +66,7 @@ impl<'a> BlockContext<'a> { #[derive(Debug)] pub struct Validator { + analysis_flags: AnalysisFlags, //Note: this is a bit tricky: some of the front-ends as well as backends // already have to use the typifier, so the work here is redundant in a way. typifier: Typifier, @@ -580,8 +581,9 @@ impl<'a> ExpressionTypeResolver<'a> { impl Validator { /// Construct a new validator instance. - pub fn new() -> Self { + pub fn new(analysis_flags: AnalysisFlags) -> Self { Validator { + analysis_flags, typifier: Typifier::new(), type_flags: Vec::new(), location_mask: BitSet::new(), @@ -1763,7 +1765,7 @@ impl Validator { self.type_flags .resize(module.types.len(), TypeFlags::empty()); - let analysis = Analysis::new(module)?; + let analysis = Analysis::new(module, self.analysis_flags)?; for (handle, constant) in module.constants.iter() { self.validate_constant(handle, &module.constants, &module.types) diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index fcb66a51b..f3a956feb 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -3,11 +3,19 @@ source: tests/snapshots.rs expression: output --- ( + flags: ( + bits: 1, + ), functions: [ ( + flags: ( + bits: 1, + ), uniformity: ( non_uniform_result: Some(5), - requirement: None, + requirements: ( + bits: 0, + ), ), may_kill: false, sampling_set: [], @@ -20,7 +28,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: Some(1), @@ -28,7 +38,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -36,7 +48,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 7, assignable_global: None, @@ -44,7 +58,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -52,7 +68,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(5), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 3, assignable_global: None, @@ -60,7 +78,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -68,7 +88,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -76,7 +98,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -84,7 +108,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -92,7 +118,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -100,7 +128,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -108,7 +138,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -116,7 +148,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -124,7 +158,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -132,7 +168,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -140,7 +178,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -148,7 +188,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -156,7 +198,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -164,7 +208,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -172,7 +218,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -180,7 +228,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -188,7 +238,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(5), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -196,7 +248,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -204,7 +258,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(5), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -212,7 +268,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(5), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -222,9 +280,14 @@ expression: output ], entry_points: [ ( + flags: ( + bits: 1, + ), uniformity: ( non_uniform_result: Some(5), - requirement: None, + requirements: ( + bits: 0, + ), ), may_kill: false, sampling_set: [], @@ -237,7 +300,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 2, assignable_global: Some(1), @@ -245,7 +310,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 2, assignable_global: None, @@ -253,7 +320,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(1), @@ -261,7 +330,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -269,7 +340,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(1), @@ -277,7 +350,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(1), @@ -285,7 +360,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -293,7 +370,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(1), @@ -301,7 +380,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -309,7 +390,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(5), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 91998563b..d4162fd4c 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -3,11 +3,19 @@ source: tests/snapshots.rs expression: output --- ( + flags: ( + bits: 1, + ), functions: [ ( + flags: ( + bits: 1, + ), uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), may_kill: false, sampling_set: [ @@ -43,7 +51,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: Some(3), @@ -51,7 +61,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: Some(6), @@ -59,7 +71,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: Some(5), @@ -67,7 +81,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(1), @@ -75,7 +91,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(2), @@ -83,7 +101,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: Some(4), @@ -91,7 +111,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(7), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: Some(7), @@ -99,7 +121,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -107,7 +131,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 3, assignable_global: None, @@ -115,7 +141,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -123,7 +151,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -131,7 +161,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -139,7 +171,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -147,7 +181,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -155,7 +191,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -163,7 +201,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -171,7 +211,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -179,7 +221,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -187,7 +231,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -195,7 +241,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -203,7 +251,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -211,7 +261,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -219,7 +271,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -227,7 +281,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -235,7 +291,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -243,7 +301,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -251,7 +311,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -259,7 +321,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -267,7 +331,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -275,7 +341,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 3, assignable_global: None, @@ -283,7 +351,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -291,7 +361,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -299,7 +371,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -307,7 +381,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -315,7 +391,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -323,7 +401,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -331,7 +411,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -339,7 +421,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -347,7 +431,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -355,7 +441,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -363,7 +451,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -371,7 +461,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -379,7 +471,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -387,7 +481,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 6, assignable_global: None, @@ -395,7 +491,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -403,7 +501,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -411,7 +511,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -419,7 +521,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -427,7 +531,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -435,7 +541,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -443,7 +551,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -451,7 +561,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -459,7 +571,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -467,7 +581,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -475,7 +591,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -483,7 +601,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 2, assignable_global: None, @@ -491,7 +611,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -499,7 +621,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -507,7 +631,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -515,7 +641,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -523,7 +651,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 3, assignable_global: None, @@ -531,7 +661,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -539,7 +671,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -547,7 +681,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -555,7 +691,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -563,7 +701,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -571,7 +711,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -579,7 +721,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -587,7 +731,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -595,7 +741,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -603,7 +751,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -611,9 +761,14 @@ expression: output ], ), ( + flags: ( + bits: 1, + ), uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), may_kill: false, sampling_set: [ @@ -649,7 +804,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(3), @@ -657,7 +814,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(6), @@ -665,7 +824,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 4, assignable_global: Some(5), @@ -673,7 +834,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: Some(1), @@ -681,7 +844,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: Some(2), @@ -689,7 +854,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 7, assignable_global: Some(4), @@ -697,7 +864,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(7), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(7), @@ -705,7 +874,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -713,7 +884,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -721,7 +894,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -729,7 +904,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -737,7 +914,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -745,7 +924,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -753,7 +934,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -761,7 +944,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -769,7 +954,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -777,7 +964,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -785,7 +974,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -793,7 +984,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -801,7 +994,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -809,7 +1004,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -817,7 +1014,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -825,7 +1024,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -833,7 +1034,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -841,7 +1044,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -849,7 +1054,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -857,7 +1064,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -865,7 +1074,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -873,7 +1084,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -881,7 +1094,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -889,7 +1104,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -897,7 +1114,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -905,7 +1124,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -913,7 +1134,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -921,7 +1144,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -929,7 +1154,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -937,7 +1164,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -945,7 +1174,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -953,7 +1184,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -961,7 +1194,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -969,7 +1204,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 0, assignable_global: None, @@ -977,7 +1214,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -985,7 +1224,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 3, assignable_global: None, @@ -993,7 +1234,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 11, assignable_global: None, @@ -1001,7 +1244,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1009,7 +1254,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(3), @@ -1017,7 +1264,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(3), @@ -1025,7 +1274,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1033,7 +1284,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1041,7 +1294,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1049,7 +1304,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1057,7 +1314,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1065,7 +1324,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1073,7 +1334,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1081,7 +1344,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1089,7 +1354,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1097,7 +1364,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1105,7 +1374,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1113,7 +1384,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1121,7 +1394,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1129,7 +1404,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1137,7 +1414,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1145,7 +1424,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1153,7 +1434,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1161,7 +1444,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1169,7 +1454,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1177,7 +1464,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1185,7 +1474,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1193,7 +1484,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1201,7 +1494,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1209,7 +1504,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1217,7 +1514,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1225,7 +1524,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1233,7 +1534,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1241,7 +1544,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1249,7 +1554,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1257,7 +1564,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1265,7 +1574,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1273,7 +1584,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1281,7 +1594,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1289,7 +1604,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1297,7 +1614,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(5), @@ -1305,7 +1624,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1313,7 +1634,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(5), @@ -1321,7 +1644,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1329,7 +1654,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(5), @@ -1337,7 +1664,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1345,7 +1674,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1353,7 +1684,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1361,7 +1694,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1369,7 +1704,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1377,7 +1714,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1385,7 +1724,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1393,7 +1734,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1401,7 +1744,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1409,7 +1754,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1417,7 +1764,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1425,7 +1774,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1433,7 +1784,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1441,7 +1794,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1449,7 +1804,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1457,7 +1814,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1465,7 +1824,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1473,7 +1834,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1481,7 +1844,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1489,7 +1854,9 @@ expression: output ( uniformity: ( non_uniform_result: None, - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1497,7 +1864,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1505,7 +1874,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1513,7 +1884,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1521,7 +1894,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(4), @@ -1529,7 +1904,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1537,7 +1914,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1545,7 +1924,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1553,7 +1934,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1561,7 +1944,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1569,7 +1954,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1577,7 +1964,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1585,7 +1974,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(43), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1595,9 +1986,14 @@ expression: output ], entry_points: [ ( + flags: ( + bits: 1, + ), uniformity: ( non_uniform_result: Some(44), - requirement: None, + requirements: ( + bits: 0, + ), ), may_kill: false, sampling_set: [ @@ -1633,7 +2029,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(1), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(6), @@ -1641,7 +2039,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(2), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1649,7 +2049,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(3), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(5), @@ -1657,7 +2059,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(4), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, @@ -1665,7 +2069,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(5), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: Some(7), @@ -1673,7 +2079,9 @@ expression: output ( uniformity: ( non_uniform_result: Some(5), - requirement: None, + requirements: ( + bits: 0, + ), ), ref_count: 1, assignable_global: None, diff --git a/tests/parse.rs b/tests/parse.rs index 6c7301e1a..95c7fc85a 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -23,7 +23,9 @@ fn _check_glsl(name: &str) { defines: Default::default(), }, ) { - Ok(m) => match naga::proc::Validator::new().validate(&m) { + Ok(m) => match naga::proc::Validator::new(naga::proc::analyzer::AnalysisFlags::all()) + .validate(&m) + { Ok(_analysis) => (), //TODO: panic Err(e) => log::error!("Unable to validate {}: {:?}", name, e), diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 225042ef7..8cbcd8751 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -63,7 +63,9 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), }; - let analysis = naga::proc::Validator::new().validate(module).unwrap(); + let analysis = naga::proc::Validator::new(naga::proc::analyzer::AnalysisFlags::all()) + .validate(module) + .unwrap(); #[cfg(feature = "serialize")] { @@ -276,7 +278,9 @@ fn convert_spv(name: &str, targets: Targets) { ) .unwrap(); check_targets(&module, name, targets); - naga::proc::Validator::new().validate(&module).unwrap(); + naga::proc::Validator::new(naga::proc::analyzer::AnalysisFlags::all()) + .validate(&module) + .unwrap(); } #[cfg(feature = "spv-in")] From c992e638fe3fcdb506573b2bdd1592ddf79a1e9b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 20 Mar 2021 01:09:29 -0400 Subject: [PATCH 0600/2212] Move all the validation into a separate meta-module --- bin/convert.rs | 29 +- src/back/dot/mod.rs | 8 +- src/back/glsl/mod.rs | 20 +- src/back/msl/mod.rs | 10 +- src/back/msl/writer.rs | 32 +- src/back/spv/mod.rs | 4 +- src/back/spv/writer.rs | 16 +- src/lib.rs | 1 + src/proc/mod.rs | 3 - src/proc/validator.rs | 1829 ------------------------------- src/{proc => valid}/analyzer.rs | 10 +- src/valid/expression.rs | 549 ++++++++++ src/valid/function.rs | 510 +++++++++ src/valid/interface.rs | 428 ++++++++ src/valid/mod.rs | 382 +++++++ tests/parse.rs | 14 +- tests/snapshots.rs | 26 +- 17 files changed, 1947 insertions(+), 1924 deletions(-) delete mode 100644 src/proc/validator.rs rename src/{proc => valid}/analyzer.rs (99%) create mode 100644 src/valid/expression.rs create mode 100644 src/valid/function.rs create mode 100644 src/valid/interface.rs create mode 100644 src/valid/mod.rs diff --git a/bin/convert.rs b/bin/convert.rs index a5870b848..14aa6cdf7 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -172,15 +172,14 @@ fn main() { // validate the IR #[allow(unused_variables)] - let analysis = match naga::proc::Validator::new(naga::proc::analyzer::AnalysisFlags::all()) - .validate(&module) - { - Ok(analysis) => Some(analysis), - Err(error) => { - print_err(error); - None - } - }; + let info = + match naga::valid::Validator::new(naga::valid::AnalysisFlags::all()).validate(&module) { + Ok(info) => Some(info), + Err(error) => { + print_err(error); + None + } + }; let output_path = match output_path { Some(ref string) => string, @@ -200,15 +199,14 @@ fn main() { "metal" => { use naga::back::msl; let (msl, _) = - msl::write_string(&module, analysis.as_ref().unwrap(), ¶ms.msl).unwrap_pretty(); + msl::write_string(&module, info.as_ref().unwrap(), ¶ms.msl).unwrap_pretty(); fs::write(output_path, msl).unwrap(); } #[cfg(feature = "spv-out")] "spv" => { use naga::back::spv; - let spv = - spv::write_vec(&module, analysis.as_ref().unwrap(), ¶ms.spv).unwrap_pretty(); + let spv = spv::write_vec(&module, info.as_ref().unwrap(), ¶ms.spv).unwrap_pretty(); let bytes = spv .iter() .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { @@ -236,9 +234,8 @@ fn main() { .open(output_path) .unwrap(); - let mut writer = - glsl::Writer::new(file, &module, analysis.as_ref().unwrap(), ¶ms.glsl) - .unwrap_pretty(); + let mut writer = glsl::Writer::new(file, &module, info.as_ref().unwrap(), ¶ms.glsl) + .unwrap_pretty(); writer .write() @@ -251,7 +248,7 @@ fn main() { #[cfg(feature = "dot-out")] "dot" => { use naga::back::dot; - let output = dot::write(&module, analysis.as_ref()).unwrap(); + let output = dot::write(&module, info.as_ref()).unwrap(); fs::write(output_path, output).unwrap(); } other => { diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 899605840..8296e0ba2 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -6,7 +6,7 @@ use crate::{ arena::Handle, - proc::analyzer::{Analysis, FunctionInfo}, + valid::{FunctionInfo, ModuleInfo}, }; use std::{ @@ -429,7 +429,7 @@ fn write_fun( Ok(()) } -pub fn write(module: &crate::Module, analysis: Option<&Analysis>) -> Result { +pub fn write(module: &crate::Module, mod_info: Option<&ModuleInfo>) -> Result { use std::fmt::Write as _; let mut output = String::new(); @@ -458,7 +458,7 @@ pub fn write(module: &crate::Module, analysis: Option<&Analysis>) -> Result) -> Result { /// The module being written module: &'a Module, /// The module analysis. - analysis: &'a Analysis, + info: &'a ModuleInfo, /// The output writer out: W, /// User defined configuration to be used @@ -348,7 +346,7 @@ impl<'a, W: Write> Writer<'a, W> { pub fn new( out: W, module: &'a Module, - analysis: &'a Analysis, + info: &'a ModuleInfo, options: &'a Options, ) -> Result { // Check if the requested version is supported @@ -371,7 +369,7 @@ impl<'a, W: Write> Writer<'a, W> { // Build the instance let mut this = Self { module, - analysis, + info, out, options, @@ -473,7 +471,7 @@ impl<'a, W: Write> Writer<'a, W> { } } - let ep_info = self.analysis.get_entry_point(self.entry_point_idx as usize); + let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); // Write the globals // @@ -548,13 +546,13 @@ impl<'a, W: Write> Writer<'a, W> { for (handle, function) in self.module.functions.iter() { // Check that the function doesn't use globals that aren't supported // by the current entry point - if !ep_info.dominates_global_use(&self.analysis[handle]) { + if !ep_info.dominates_global_use(&self.info[handle]) { continue; } // We also `clone` to satisfy the borrow checker let name = self.names[&NameKey::Function(handle)].clone(); - let fun_info = &self.analysis[handle]; + let fun_info = &self.info[handle]; // Write the function self.write_function(FunctionType::Function(handle), function, fun_info, &name)?; @@ -2071,7 +2069,7 @@ impl<'a, W: Write> Writer<'a, W> { /// [`Arena`](crate::arena::Arena) and we need to traverse it fn collect_reflection_info(&self) -> Result { use std::collections::hash_map::Entry; - let info = self.analysis.get_entry_point(self.entry_point_idx as usize); + let info = self.info.get_entry_point(self.entry_point_idx as usize); let mut mappings = FastHashMap::default(); let mut uniforms = FastHashMap::default(); diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 9eda260cf..b651a25d7 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -23,11 +23,7 @@ For the result type, if it's a structure, we re-compose it with a temporary valu holding the result. !*/ -use crate::{ - arena::Handle, - proc::{analyzer::Analysis, TypifyError}, - FastHashMap, -}; +use crate::{arena::Handle, proc::TypifyError, valid::ModuleInfo, FastHashMap}; use std::{ fmt::{Error as FmtError, Write}, string::FromUtf8Error, @@ -243,11 +239,11 @@ pub struct TranslationInfo { pub fn write_string( module: &crate::Module, - analysis: &Analysis, + info: &ModuleInfo, options: &Options, ) -> Result<(String, TranslationInfo), Error> { let mut w = writer::Writer::new(String::new()); - let info = w.write(module, analysis, options)?; + let info = w.write(module, info, options)?; Ok((w.finish(), info)) } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 2a9442352..56f4a695b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,10 +1,8 @@ use super::{keywords::RESERVED, Error, LocationMode, Options, TranslationInfo}; use crate::{ arena::Handle, - proc::{ - analyzer::{Analysis, FunctionInfo, GlobalUse}, - EntryPointIndex, NameKey, Namer, ResolveContext, Typifier, - }, + proc::{EntryPointIndex, NameKey, Namer, ResolveContext, Typifier}, + valid::{FunctionInfo, GlobalUse, ModuleInfo}, FastHashMap, }; use bit_set::BitSet; @@ -141,7 +139,7 @@ struct ExpressionContext<'a> { function: &'a crate::Function, origin: FunctionOrigin, module: &'a crate::Module, - analysis: &'a Analysis, + mod_info: &'a ModuleInfo, } struct StatementContext<'a> { @@ -859,7 +857,7 @@ impl Writer { } // follow-up with any global resources used let mut separate = !arguments.is_empty(); - let fun_info = &context.expression.analysis[function]; + let fun_info = &context.expression.mod_info[function]; for (handle, var) in context.expression.module.global_variables.iter() { if !fun_info[handle].is_empty() && var.class.needs_pass_through() { let name = &self.names[&NameKey::GlobalVariable(handle)]; @@ -882,7 +880,7 @@ impl Writer { pub fn write( &mut self, module: &crate::Module, - analysis: &Analysis, + info: &ModuleInfo, options: &Options, ) -> Result { self.names.clear(); @@ -894,7 +892,7 @@ impl Writer { self.write_type_defs(module)?; self.write_constants(module)?; - self.write_functions(module, analysis, options) + self.write_functions(module, info, options) } fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { @@ -1106,7 +1104,7 @@ impl Writer { fn write_functions( &mut self, module: &crate::Module, - analysis: &Analysis, + mod_info: &ModuleInfo, options: &Options, ) -> Result { let mut pass_through_globals = Vec::new(); @@ -1123,7 +1121,7 @@ impl Writer { }, )?; - let fun_info = &analysis[fun_handle]; + let fun_info = &mod_info[fun_handle]; pass_through_globals.clear(); for (handle, var) in module.global_variables.iter() { if !fun_info[handle].is_empty() && var.class.needs_pass_through() { @@ -1179,7 +1177,7 @@ impl Writer { function: fun, origin: FunctionOrigin::Handle(fun_handle), module, - analysis, + mod_info, }, fun_info, result_struct: None, @@ -1195,7 +1193,7 @@ impl Writer { }; for (ep_index, ep) in module.entry_points.iter().enumerate() { let fun = &ep.function; - let fun_info = analysis.get_entry_point(ep_index); + let fun_info = mod_info.get_entry_point(ep_index); // skip this entry point if any global bindings are missing if !options.fake_missing_bindings { if let Some(err) = module @@ -1471,7 +1469,7 @@ impl Writer { function: fun, origin: FunctionOrigin::EntryPoint(ep_index as _), module, - analysis, + mod_info, }, fun_info, result_struct: Some(&stage_out_name), @@ -1490,7 +1488,7 @@ impl Writer { #[test] fn test_stack_size() { - use crate::proc::analyzer::AnalysisFlags; + use crate::valid::AnalysisFlags; // create a module with at least one expression nested let mut module = crate::Module::default(); let constant = module.constants.append(crate::Constant { @@ -1518,12 +1516,10 @@ fn test_stack_size() { }); let _ = module.functions.append(fun); // analyse the module - let analysis = Analysis::new(&module, AnalysisFlags::empty()).unwrap(); + let info = ModuleInfo::new(&module, AnalysisFlags::empty()).unwrap(); // process the module let mut writer = Writer::new(String::new()); - writer - .write(&module, &analysis, &Default::default()) - .unwrap(); + writer.write(&module, &info, &Default::default()).unwrap(); let (mut min_addr, mut max_addr) = (!0usize, 0usize); for pointer in writer.put_expression_stack_pointers { min_addr = min_addr.min(pointer as usize); diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 4a780f2ef..4251b5cb4 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -73,11 +73,11 @@ impl Default for Options { pub fn write_vec( module: &crate::Module, - analysis: &crate::proc::analyzer::Analysis, + info: &crate::valid::ModuleInfo, options: &Options, ) -> Result, Error> { let mut words = Vec::new(); let mut w = Writer::new(options)?; - w.write(module, analysis, &mut words)?; + w.write(module, info, &mut words)?; Ok(words) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b75db1573..912a840a1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2,10 +2,8 @@ use super::{Instruction, LogicalLayout, Options, PhysicalLayout, WriterFlags}; use crate::{ arena::{Arena, Handle}, - proc::{ - analyzer::{Analysis, FunctionInfo}, - Layouter, ResolveContext, Typifier, TypifyError, - }, + proc::{Layouter, ResolveContext, Typifier, TypifyError}, + valid::{FunctionInfo, ModuleInfo}, }; use spirv::Word; use std::{collections::hash_map::Entry, ops}; @@ -2350,7 +2348,7 @@ impl Writer { fn write_logical_layout( &mut self, ir_module: &crate::Module, - analysis: &Analysis, + mod_info: &ModuleInfo, ) -> Result<(), Error> { Instruction::type_void(self.void_type).to_words(&mut self.logical_layout.declarations); Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") @@ -2387,13 +2385,13 @@ impl Writer { } for (handle, ir_function) in ir_module.functions.iter() { - let info = &analysis[handle]; + let info = &mod_info[handle]; let id = self.write_function(ir_function, info, ir_module, None)?; self.lookup_function.insert(handle, id); } for (ep_index, ir_ep) in ir_module.entry_points.iter().enumerate() { - let info = analysis.get_entry_point(ep_index); + let info = mod_info.get_entry_point(ep_index); let ep_instruction = self.write_entry_point(ir_ep, info, ir_module)?; ep_instruction.to_words(&mut self.logical_layout.entry_points); } @@ -2426,7 +2424,7 @@ impl Writer { pub fn write( &mut self, ir_module: &crate::Module, - analysis: &Analysis, + info: &ModuleInfo, words: &mut Vec, ) -> Result<(), Error> { self.lookup_function.clear(); @@ -2436,7 +2434,7 @@ impl Writer { self.layouter .initialize(&ir_module.types, &ir_module.constants); - self.write_logical_layout(ir_module, analysis)?; + self.write_logical_layout(ir_module, info)?; self.write_physical_layout(); self.physical_layout.in_words(words); diff --git a/src/lib.rs b/src/lib.rs index 1df4e0004..4f1992d3d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -40,6 +40,7 @@ mod arena; pub mod back; pub mod front; pub mod proc; +pub mod valid; pub use crate::arena::{Arena, Handle, Range}; diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c4ad803af..c1eea6a2a 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,17 +1,14 @@ //! Module processing functionality. -pub mod analyzer; mod layouter; mod namer; mod terminator; mod typifier; -mod validator; pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, Typifier, TypifyError}; -pub use validator::{TypeFlags, ValidationError, Validator}; impl From for super::ScalarKind { fn from(format: super::StorageFormat) -> Self { diff --git a/src/proc/validator.rs b/src/proc/validator.rs deleted file mode 100644 index 837fed50b..000000000 --- a/src/proc/validator.rs +++ /dev/null @@ -1,1829 +0,0 @@ -use super::{ - analyzer::{Analysis, AnalysisError, AnalysisFlags, FunctionInfo, GlobalUse}, - typifier::{ResolveContext, Typifier, TypifyError}, -}; -use crate::{ - arena::{Arena, Handle}, - FastHashSet, -}; -use bit_set::BitSet; -use thiserror::Error; - -const MAX_WORKGROUP_SIZE: u32 = 0x4000; - -bitflags::bitflags! { - #[repr(transparent)] - pub struct TypeFlags: u8 { - /// Can be used for data variables. - const DATA = 0x1; - /// The data type has known size. - const SIZED = 0x2; - /// Can be be used for interfacing between pipeline stages. - const INTERFACE = 0x4; - /// Can be used for host-shareable structures. - const HOST_SHARED = 0x8; - } -} - -bitflags::bitflags! { - #[repr(transparent)] - pub struct BlockFlags: u8 { - /// The control can jump out of this block. - const CAN_JUMP = 0x1; - /// The control is in a loop, can break and continue. - const IN_LOOP = 0x2; - } -} - -struct BlockContext<'a> { - flags: BlockFlags, - expressions: &'a Arena, - types: &'a Arena, - functions: &'a Arena, - return_type: Option>, -} - -impl<'a> BlockContext<'a> { - fn with_flags(&self, flags: BlockFlags) -> Self { - BlockContext { - flags, - expressions: self.expressions, - types: self.types, - functions: self.functions, - return_type: self.return_type, - } - } - - fn get_expression( - &self, - handle: Handle, - ) -> Result<&'a crate::Expression, FunctionError> { - self.expressions - .try_get(handle) - .ok_or(FunctionError::InvalidExpression(handle)) - } -} - -#[derive(Debug)] -pub struct Validator { - analysis_flags: AnalysisFlags, - //Note: this is a bit tricky: some of the front-ends as well as backends - // already have to use the typifier, so the work here is redundant in a way. - typifier: Typifier, - type_flags: Vec, - location_mask: BitSet, - bind_group_masks: Vec, - select_cases: FastHashSet, - valid_expression_list: Vec>, - valid_expression_set: BitSet, -} - -#[derive(Clone, Debug, Error)] -pub enum TypeError { - #[error("The {0:?} scalar width {1} is not supported")] - InvalidWidth(crate::ScalarKind, crate::Bytes), - #[error("The base handle {0:?} can not be resolved")] - UnresolvedBase(Handle), - #[error("Expected data type, found {0:?}")] - InvalidData(Handle), - #[error("Structure type {0:?} can not be a block structure")] - InvalidBlockType(Handle), - #[error("Base type {0:?} for the array is invalid")] - InvalidArrayBaseType(Handle), - #[error("The constant {0:?} can not be used for an array size")] - InvalidArraySizeConstant(Handle), - #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] - InvalidDynamicArray(String, Handle), -} - -#[derive(Clone, Debug, Error)] -pub enum ConstantError { - #[error("The type doesn't match the constant")] - InvalidType, - #[error("The component handle {0:?} can not be resolved")] - UnresolvedComponent(Handle), - #[error("The array size handle {0:?} can not be resolved")] - UnresolvedSize(Handle), -} - -#[derive(Clone, Debug, Error)] -pub enum GlobalVariableError { - #[error("Usage isn't compatible with the storage class")] - InvalidUsage, - #[error("Type isn't compatible with the storage class")] - InvalidType, - #[error("Storage access {seen:?} exceeds the allowed {allowed:?}")] - InvalidStorageAccess { - allowed: crate::StorageAccess, - seen: crate::StorageAccess, - }, - #[error("Type flags {seen:?} do not meet the required {required:?}")] - MissingTypeFlags { - required: TypeFlags, - seen: TypeFlags, - }, - #[error("Binding decoration is missing or not applicable")] - InvalidBinding, -} - -#[derive(Clone, Debug, Error)] -pub enum LocalVariableError { - #[error("Initializer doesn't match the variable type")] - InitializerType, -} - -#[derive(Clone, Debug, Error)] -pub enum VaryingError { - #[error("The type {0:?} does not match the varying")] - InvalidType(Handle), - #[error("Interpolation is not valid")] - InvalidInterpolation, - #[error("BuiltIn {0:?} is not available at this stage")] - InvalidBuiltInStage(crate::BuiltIn), - #[error("BuiltIn type for {0:?} is invalid")] - InvalidBuiltInType(crate::BuiltIn), - #[error("Struct member {0} is missing a binding")] - MemberMissingBinding(u32), - #[error("Multiple bindings at location {location} are present")] - BindingCollision { location: u32 }, -} - -#[derive(Clone, Debug, Error)] -pub enum ExpressionError { - #[error("Doesn't exist")] - DoesntExist, - #[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")] - NotInScope, - #[error("Depends on {0:?}, which has not been processed yet")] - ForwardDependency(Handle), - #[error("Base type {0:?} is not compatible with this expression")] - InvalidBaseType(Handle), - #[error("Accessing with index {0:?} can't be done")] - InvalidIndexType(Handle), - #[error("Accessing index {1} is out of {0:?} bounds")] - IndexOutOfBounds(Handle, u32), - #[error("Function argument {0:?} doesn't exist")] - FunctionArgumentDoesntExist(u32), - #[error("Constant {0:?} doesn't exist")] - ConstantDoesntExist(Handle), - #[error("Global variable {0:?} doesn't exist")] - GlobalVarDoesntExist(Handle), - #[error("Local variable {0:?} doesn't exist")] - LocalVarDoesntExist(Handle), - #[error("Loading of {0:?} can't be done")] - InvalidPointerType(Handle), - #[error("Array length of {0:?} can't be done")] - InvalidArrayType(Handle), - #[error("Compose type {0:?} doesn't exist")] - ComposeTypeDoesntExist(Handle), - #[error("Composing of type {0:?} can't be done")] - InvalidComposeType(Handle), - #[error("Composing expects {expected} components but {given} were given")] - InvalidComposeCount { given: u32, expected: u32 }, - #[error("Composing {0}'s component {1:?} is not expected")] - InvalidComponentType(u32, Handle), - #[error("Operation {0:?} can't work with {1:?}")] - InvalidUnaryOperandType(crate::UnaryOperator, Handle), - #[error("Operation {0:?} can't work with {1:?} and {2:?}")] - InvalidBinaryOperandTypes( - crate::BinaryOperator, - Handle, - Handle, - ), - #[error("Selecting is not possible")] - InvalidSelectTypes, - #[error("Relational argument {0:?} is not a boolean vector")] - InvalidBooleanVector(Handle), - #[error("Relational argument {0:?} is not a float")] - InvalidFloatArgument(Handle), -} - -#[derive(Clone, Debug, Error)] -pub enum CallError { - #[error("Bad function")] - InvalidFunction, - #[error("The callee is declared after the caller")] - ForwardDeclaredFunction, - #[error("Argument {index} expression is invalid")] - Argument { - index: usize, - #[source] - error: ExpressionError, - }, - #[error("Result expression {0:?} has already been introduced earlier")] - ResultAlreadyInScope(Handle), - #[error("Result value is invalid")] - ResultValue(#[source] ExpressionError), - #[error("Requires {required} arguments, but {seen} are provided")] - ArgumentCount { required: usize, seen: usize }, - #[error("Argument {index} value {seen_expression:?} doesn't match the type {required:?}")] - ArgumentType { - index: usize, - required: Handle, - seen_expression: Handle, - }, - #[error("Result value {seen_expression:?} does not match the type {required:?}")] - ResultType { - required: Option>, - seen_expression: Option>, - }, -} - -#[derive(Clone, Debug, Error)] -pub enum FunctionError { - #[error(transparent)] - Resolve(#[from] TypifyError), - #[error("Expression {handle:?} is invalid")] - Expression { - handle: Handle, - #[source] - error: ExpressionError, - }, - #[error("Expression {0:?} can't be introduced - it's already in scope")] - ExpressionAlreadyInScope(Handle), - #[error("Local variable {handle:?} '{name}' is invalid")] - LocalVariable { - handle: Handle, - name: String, - #[source] - error: LocalVariableError, - }, - #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")] - InvalidArgumentType { index: usize, name: String }, - #[error("There are instructions after `return`/`break`/`continue`")] - InstructionsAfterReturn, - #[error("The `break`/`continue` is used outside of a loop context")] - BreakContinueOutsideOfLoop, - #[error("The `return` is called within a `continuing` block")] - InvalidReturnSpot, - #[error("The `return` value {0:?} does not match the function return value")] - InvalidReturnType(Option>), - #[error("The `if` condition {0:?} is not a boolean scalar")] - InvalidIfType(Handle), - #[error("The `switch` value {0:?} is not an integer scalar")] - InvalidSwitchType(Handle), - #[error("Multiple `switch` cases for {0} are present")] - ConflictingSwitchCase(i32), - #[error("The pointer {0:?} doesn't relate to a valid destination for a store")] - InvalidStorePointer(Handle), - #[error("The value {0:?} can not be stored")] - InvalidStoreValue(Handle), - #[error("Store of {value:?} into {pointer:?} doesn't have matching types")] - InvalidStoreTypes { - pointer: Handle, - value: Handle, - }, - #[error("The image array can't be indexed by {0:?}")] - InvalidArrayIndex(Handle), - #[error("The expression {0:?} is currupted")] - InvalidExpression(Handle), - #[error("The expression {0:?} is not an image")] - InvalidImage(Handle), - #[error("Call to {function:?} is invalid")] - InvalidCall { - function: Handle, - #[source] - error: CallError, - }, -} - -#[derive(Clone, Debug, Error)] -pub enum EntryPointError { - #[error("Multiple conflicting entry points")] - Conflict, - #[error("Early depth test is not applicable")] - UnexpectedEarlyDepthTest, - #[error("Workgroup size is not applicable")] - UnexpectedWorkgroupSize, - #[error("Workgroup size is out of range")] - OutOfRangeWorkgroupSize, - #[error("Global variable {0:?} is used incorrectly as {1:?}")] - InvalidGlobalUsage(Handle, GlobalUse), - #[error("Bindings for {0:?} conflict with other resource")] - BindingCollision(Handle), - #[error("Argument {0} varying error")] - Argument(u32, #[source] VaryingError), - #[error("Result varying error")] - Result(#[source] VaryingError), - #[error("Location {location} onterpolation of an integer has to be flat")] - InvalidIntegerInterpolation { location: u32 }, - #[error(transparent)] - Function(#[from] FunctionError), -} - -#[derive(Clone, Debug, Error)] -pub enum ValidationError { - #[error("Type {handle:?} '{name}' is invalid")] - Type { - handle: Handle, - name: String, - #[source] - error: TypeError, - }, - #[error("Constant {handle:?} '{name}' is invalid")] - Constant { - handle: Handle, - name: String, - #[source] - error: ConstantError, - }, - #[error("Global variable {handle:?} '{name}' is invalid")] - GlobalVariable { - handle: Handle, - name: String, - #[source] - error: GlobalVariableError, - }, - #[error("Function {handle:?} '{name}' is invalid")] - Function { - handle: Handle, - name: String, - #[source] - error: FunctionError, - }, - #[error("Entry point {name} at {stage:?} is invalid")] - EntryPoint { - stage: crate::ShaderStage, - name: String, - #[source] - error: EntryPointError, - }, - #[error(transparent)] - Analysis(#[from] AnalysisError), - #[error("Module is corrupted")] - Corrupted, -} - -fn storage_usage(access: crate::StorageAccess) -> GlobalUse { - let mut storage_usage = GlobalUse::QUERY; - if access.contains(crate::StorageAccess::LOAD) { - storage_usage |= GlobalUse::READ; - } - if access.contains(crate::StorageAccess::STORE) { - storage_usage |= GlobalUse::WRITE; - } - storage_usage -} - -impl crate::TypeInner { - fn is_sized(&self) -> bool { - match *self { - Self::Scalar { .. } - | Self::Vector { .. } - | Self::Matrix { .. } - | Self::Array { - size: crate::ArraySize::Constant(_), - .. - } - | Self::Pointer { .. } - | Self::ValuePointer { .. } - | Self::Struct { .. } => true, - Self::Array { .. } | Self::Image { .. } | Self::Sampler { .. } => false, - } - } -} - -struct VaryingContext<'a> { - ty: Handle, - stage: crate::ShaderStage, - output: bool, - types: &'a Arena, - location_mask: &'a mut BitSet, -} - -impl VaryingContext<'_> { - fn validate_impl(&mut self, binding: &crate::Binding) -> Result<(), VaryingError> { - use crate::{ - BuiltIn as Bi, ScalarKind as Sk, ShaderStage as St, TypeInner as Ti, VectorSize as Vs, - }; - - let ty_inner = &self.types[self.ty].inner; - match *binding { - crate::Binding::BuiltIn(built_in) => { - let width = 4; - let (visible, type_good) = match built_in { - Bi::BaseInstance | Bi::BaseVertex | Bi::InstanceIndex | Bi::VertexIndex => ( - self.stage == St::Vertex && !self.output, - *ty_inner - == Ti::Scalar { - kind: Sk::Uint, - width, - }, - ), - Bi::ClipDistance => ( - self.stage == St::Vertex && self.output, - match *ty_inner { - Ti::Array { base, .. } => { - self.types[base].inner - == Ti::Scalar { - kind: Sk::Float, - width, - } - } - _ => false, - }, - ), - Bi::PointSize => ( - self.stage == St::Vertex && self.output, - *ty_inner - == Ti::Scalar { - kind: Sk::Float, - width, - }, - ), - Bi::Position => ( - match self.stage { - St::Vertex => self.output, - St::Fragment => !self.output, - St::Compute => false, - }, - *ty_inner - == Ti::Vector { - size: Vs::Quad, - kind: Sk::Float, - width, - }, - ), - Bi::FragDepth => ( - self.stage == St::Fragment && self.output, - *ty_inner - == Ti::Scalar { - kind: Sk::Float, - width, - }, - ), - Bi::FrontFacing => ( - self.stage == St::Fragment && !self.output, - *ty_inner - == Ti::Scalar { - kind: Sk::Bool, - width: crate::BOOL_WIDTH, - }, - ), - Bi::SampleIndex => ( - self.stage == St::Fragment && !self.output, - *ty_inner - == Ti::Scalar { - kind: Sk::Uint, - width, - }, - ), - Bi::SampleMask => ( - self.stage == St::Fragment, - *ty_inner - == Ti::Scalar { - kind: Sk::Uint, - width, - }, - ), - Bi::LocalInvocationIndex => ( - self.stage == St::Compute && !self.output, - *ty_inner - == Ti::Scalar { - kind: Sk::Uint, - width, - }, - ), - Bi::GlobalInvocationId - | Bi::LocalInvocationId - | Bi::WorkGroupId - | Bi::WorkGroupSize => ( - self.stage == St::Compute && !self.output, - *ty_inner - == Ti::Vector { - size: Vs::Tri, - kind: Sk::Uint, - width, - }, - ), - }; - - if !visible { - return Err(VaryingError::InvalidBuiltInStage(built_in)); - } - if !type_good { - log::warn!("Wrong builtin type: {:?}", ty_inner); - return Err(VaryingError::InvalidBuiltInType(built_in)); - } - } - crate::Binding::Location(location, interpolation) => { - if !self.location_mask.insert(location as usize) { - return Err(VaryingError::BindingCollision { location }); - } - let needs_interpolation = - self.stage == crate::ShaderStage::Fragment && !self.output; - if !needs_interpolation && interpolation.is_some() { - return Err(VaryingError::InvalidInterpolation); - } - match ty_inner.scalar_kind() { - Some(crate::ScalarKind::Float) => {} - Some(_) - if needs_interpolation - && interpolation != Some(crate::Interpolation::Flat) => - { - return Err(VaryingError::InvalidInterpolation); - } - Some(_) => {} - None => return Err(VaryingError::InvalidType(self.ty)), - } - } - } - - Ok(()) - } - - fn validate(mut self, binding: Option<&crate::Binding>) -> Result<(), VaryingError> { - match binding { - Some(binding) => self.validate_impl(binding), - None => { - match self.types[self.ty].inner { - //TODO: check the member types - crate::TypeInner::Struct { - block: false, - ref members, - } => { - for (index, member) in members.iter().enumerate() { - self.ty = member.ty; - match member.binding { - None => { - return Err(VaryingError::MemberMissingBinding(index as u32)) - } - Some(ref binding) => self.validate_impl(binding)?, - } - } - } - _ => return Err(VaryingError::InvalidType(self.ty)), - } - Ok(()) - } - } - } -} - -struct ExpressionTypeResolver<'a> { - root: Handle, - types: &'a Arena, - typifier: &'a Typifier, -} - -impl<'a> ExpressionTypeResolver<'a> { - fn resolve( - &self, - handle: Handle, - ) -> Result<&'a crate::TypeInner, ExpressionError> { - if handle < self.root { - Ok(self.typifier.get(handle, self.types)) - } else { - Err(ExpressionError::ForwardDependency(handle)) - } - } -} - -impl Validator { - /// Construct a new validator instance. - pub fn new(analysis_flags: AnalysisFlags) -> Self { - Validator { - analysis_flags, - typifier: Typifier::new(), - type_flags: Vec::new(), - location_mask: BitSet::new(), - bind_group_masks: Vec::new(), - select_cases: FastHashSet::default(), - valid_expression_list: Vec::new(), - valid_expression_set: BitSet::new(), - } - } - - fn check_width(kind: crate::ScalarKind, width: crate::Bytes) -> bool { - match kind { - crate::ScalarKind::Bool => width == crate::BOOL_WIDTH, - _ => width == 4, - } - } - - fn validate_type( - &self, - ty: &crate::Type, - handle: Handle, - constants: &Arena, - ) -> Result { - use crate::TypeInner as Ti; - Ok(match ty.inner { - Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { - if !Self::check_width(kind, width) { - return Err(TypeError::InvalidWidth(kind, width)); - } - TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED - } - Ti::Matrix { width, .. } => { - if !Self::check_width(crate::ScalarKind::Float, width) { - return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); - } - TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED - } - Ti::Pointer { base, class: _ } => { - if base >= handle { - return Err(TypeError::UnresolvedBase(base)); - } - TypeFlags::DATA | TypeFlags::SIZED - } - Ti::ValuePointer { - size: _, - kind, - width, - class: _, - } => { - if !Self::check_width(kind, width) { - return Err(TypeError::InvalidWidth(kind, width)); - } - TypeFlags::SIZED //TODO: `DATA`? - } - Ti::Array { - base, - size, - stride: _, - } => { - if base >= handle { - return Err(TypeError::UnresolvedBase(base)); - } - let base_flags = self.type_flags[base.index()]; - if !base_flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { - return Err(TypeError::InvalidArrayBaseType(base)); - } - - let sized_flag = match size { - crate::ArraySize::Constant(const_handle) => { - match constants.try_get(const_handle) { - Some(&crate::Constant { - inner: - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(_), - }, - .. - }) => {} - // Accept a signed integer size to avoid - // requiring an explicit uint - // literal. Type inference should make - // this unnecessary. - Some(&crate::Constant { - inner: - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Sint(_), - }, - .. - }) => {} - other => { - log::warn!("Array size {:?}", other); - return Err(TypeError::InvalidArraySizeConstant(const_handle)); - } - } - TypeFlags::SIZED - } - crate::ArraySize::Dynamic => TypeFlags::empty(), - }; - let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; - TypeFlags::DATA | (base_flags & base_mask) | sized_flag - } - Ti::Struct { block, ref members } => { - let mut flags = TypeFlags::all(); - for (i, member) in members.iter().enumerate() { - if member.ty >= handle { - return Err(TypeError::UnresolvedBase(member.ty)); - } - let base_flags = self.type_flags[member.ty.index()]; - flags &= base_flags; - if !base_flags.contains(TypeFlags::DATA) { - return Err(TypeError::InvalidData(member.ty)); - } - if block && !base_flags.contains(TypeFlags::INTERFACE) { - return Err(TypeError::InvalidBlockType(member.ty)); - } - // only the last field can be unsized - if i + 1 != members.len() && !base_flags.contains(TypeFlags::SIZED) { - let name = member.name.clone().unwrap_or_default(); - return Err(TypeError::InvalidDynamicArray(name, member.ty)); - } - } - //TODO: check the spans - flags - } - Ti::Image { .. } | Ti::Sampler { .. } => TypeFlags::empty(), - }) - } - - fn validate_constant( - &self, - handle: Handle, - constants: &Arena, - types: &Arena, - ) -> Result<(), ConstantError> { - let con = &constants[handle]; - match con.inner { - crate::ConstantInner::Scalar { width, ref value } => { - if !Self::check_width(value.scalar_kind(), width) { - return Err(ConstantError::InvalidType); - } - } - crate::ConstantInner::Composite { ty, ref components } => { - match types[ty].inner { - crate::TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } => { - return Err(ConstantError::InvalidType); - } - crate::TypeInner::Array { - size: crate::ArraySize::Constant(size_handle), - .. - } => { - if handle <= size_handle { - return Err(ConstantError::UnresolvedSize(size_handle)); - } - } - _ => {} //TODO - } - if let Some(&comp) = components.iter().find(|&&comp| handle <= comp) { - return Err(ConstantError::UnresolvedComponent(comp)); - } - } - } - Ok(()) - } - - fn validate_global_var( - &self, - var: &crate::GlobalVariable, - types: &Arena, - ) -> Result<(), GlobalVariableError> { - log::debug!("var {:?}", var); - let (allowed_storage_access, required_type_flags, is_resource) = match var.class { - crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), - crate::StorageClass::Storage => { - match types[var.ty].inner { - crate::TypeInner::Struct { .. } => (), - _ => return Err(GlobalVariableError::InvalidType), - } - ( - crate::StorageAccess::all(), - TypeFlags::DATA | TypeFlags::HOST_SHARED, - true, - ) - } - crate::StorageClass::Uniform => { - match types[var.ty].inner { - crate::TypeInner::Struct { .. } => (), - _ => return Err(GlobalVariableError::InvalidType), - } - ( - crate::StorageAccess::empty(), - TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED, - true, - ) - } - crate::StorageClass::Handle => { - let access = match types[var.ty].inner { - crate::TypeInner::Image { - class: crate::ImageClass::Storage(_), - .. - } => crate::StorageAccess::all(), - crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { - crate::StorageAccess::empty() - } - _ => return Err(GlobalVariableError::InvalidType), - }; - (access, TypeFlags::empty(), true) - } - crate::StorageClass::Private | crate::StorageClass::WorkGroup => { - (crate::StorageAccess::empty(), TypeFlags::DATA, false) - } - crate::StorageClass::PushConstant => ( - crate::StorageAccess::LOAD, - TypeFlags::DATA | TypeFlags::HOST_SHARED, - false, - ), - }; - - if !allowed_storage_access.contains(var.storage_access) { - return Err(GlobalVariableError::InvalidStorageAccess { - seen: var.storage_access, - allowed: allowed_storage_access, - }); - } - - let type_flags = self.type_flags[var.ty.index()]; - if !type_flags.contains(required_type_flags) { - return Err(GlobalVariableError::MissingTypeFlags { - seen: type_flags, - required: required_type_flags, - }); - } - - if is_resource != var.binding.is_some() { - return Err(GlobalVariableError::InvalidBinding); - } - - Ok(()) - } - - fn validate_local_var( - &self, - var: &crate::LocalVariable, - types: &Arena, - constants: &Arena, - ) -> Result<(), LocalVariableError> { - log::debug!("var {:?}", var); - if let Some(const_handle) = var.init { - match constants[const_handle].inner { - crate::ConstantInner::Scalar { width, ref value } => { - let ty_inner = crate::TypeInner::Scalar { - width, - kind: value.scalar_kind(), - }; - if types[var.ty].inner != ty_inner { - return Err(LocalVariableError::InitializerType); - } - } - crate::ConstantInner::Composite { ty, components: _ } => { - if ty != var.ty { - return Err(LocalVariableError::InitializerType); - } - } - } - } - Ok(()) - } - - fn validate_call( - &mut self, - function: Handle, - arguments: &[Handle], - result: Option>, - context: &BlockContext, - ) -> Result<(), CallError> { - let fun = context - .functions - .try_get(function) - .ok_or(CallError::InvalidFunction)?; - if fun.arguments.len() != arguments.len() { - return Err(CallError::ArgumentCount { - required: fun.arguments.len(), - seen: arguments.len(), - }); - } - for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { - let ty = self - .resolve_statement_type_impl(expr, context.types) - .map_err(|error| CallError::Argument { index, error })?; - if ty != &context.types[arg.ty].inner { - return Err(CallError::ArgumentType { - index, - required: arg.ty, - seen_expression: expr, - }); - } - } - - if let Some(expr) = result { - if self.valid_expression_set.insert(expr.index()) { - self.valid_expression_list.push(expr); - } else { - return Err(CallError::ResultAlreadyInScope(expr)); - } - } - - let result_ty = result - .map(|expr| self.resolve_statement_type_impl(expr, context.types)) - .transpose() - .map_err(CallError::ResultValue)?; - let expected_ty = fun.result.as_ref().map(|fr| &context.types[fr.ty].inner); - if result_ty != expected_ty { - log::error!( - "Called function returns {:?} where {:?} is expected", - result_ty, - expected_ty - ); - return Err(CallError::ResultType { - required: fun.result.as_ref().map(|fr| fr.ty), - seen_expression: result, - }); - } - Ok(()) - } - - #[allow(unused)] - fn validate_expression( - &self, - root: Handle, - expression: &crate::Expression, - function: &crate::Function, - module: &crate::Module, - ) -> Result<(), ExpressionError> { - use crate::{Expression as E, ScalarKind as Sk, TypeInner as Ti}; - - let resolver = ExpressionTypeResolver { - root, - types: &module.types, - typifier: &self.typifier, - }; - - match *expression { - E::Access { base, index } => { - match *resolver.resolve(base)? { - Ti::Vector { .. } - | Ti::Matrix { .. } - | Ti::Array { .. } - | Ti::Pointer { .. } => {} - ref other => { - log::error!("Indexing of {:?}", other); - return Err(ExpressionError::InvalidBaseType(base)); - } - } - match *resolver.resolve(index)? { - //TODO: only allow one of these - Ti::Scalar { - kind: Sk::Sint, - width: _, - } - | Ti::Scalar { - kind: Sk::Uint, - width: _, - } => {} - ref other => { - log::error!("Indexing by {:?}", other); - return Err(ExpressionError::InvalidIndexType(index)); - } - } - } - E::AccessIndex { base, index } => { - let limit = match *resolver.resolve(base)? { - Ti::Vector { size, .. } => size as u32, - Ti::Matrix { columns, .. } => columns as u32, - Ti::Array { - size: crate::ArraySize::Constant(handle), - .. - } => module.constants[handle].to_array_length().unwrap(), - Ti::Array { .. } => !0, // can't statically know, but need run-time checks - Ti::Pointer { .. } => !0, //TODO - Ti::Struct { - ref members, - block: _, - } => members.len() as u32, - ref other => { - log::error!("Indexing of {:?}", other); - return Err(ExpressionError::InvalidBaseType(base)); - } - }; - if index >= limit { - return Err(ExpressionError::IndexOutOfBounds(base, index)); - } - } - E::Constant(handle) => { - let _ = module - .constants - .try_get(handle) - .ok_or(ExpressionError::ConstantDoesntExist(handle))?; - } - E::Compose { ref components, ty } => { - match module - .types - .try_get(ty) - .ok_or(ExpressionError::ComposeTypeDoesntExist(ty))? - .inner - { - // vectors are composed from scalars or other vectors - Ti::Vector { size, kind, width } => { - let inner = Ti::Scalar { kind, width }; - let mut total = 0; - for (index, &comp) in components.iter().enumerate() { - total += match *resolver.resolve(comp)? { - Ti::Scalar { - kind: comp_kind, - width: comp_width, - } if comp_kind == kind && comp_width == width => 1, - Ti::Vector { - size: comp_size, - kind: comp_kind, - width: comp_width, - } if comp_kind == kind && comp_width == width => comp_size as u32, - ref other => { - log::error!("Vector component[{}] type {:?}", index, other); - return Err(ExpressionError::InvalidComponentType( - index as u32, - comp, - )); - } - }; - } - if size as u32 != total { - return Err(ExpressionError::InvalidComposeCount { - expected: size as u32, - given: total, - }); - } - } - // matrix are composed from column vectors - Ti::Matrix { - columns, - rows, - width, - } => { - let inner = Ti::Vector { - size: rows, - kind: Sk::Float, - width, - }; - if columns as usize != components.len() { - return Err(ExpressionError::InvalidComposeCount { - expected: columns as u32, - given: components.len() as u32, - }); - } - for (index, &comp) in components.iter().enumerate() { - let tin = resolver.resolve(comp)?; - if tin != &inner { - log::error!("Matrix component[{}] type {:?}", index, tin); - return Err(ExpressionError::InvalidComponentType( - index as u32, - comp, - )); - } - } - } - Ti::Array { - base, - size: crate::ArraySize::Constant(handle), - stride: _, - } => { - let count = module.constants[handle].to_array_length().unwrap(); - if count as usize != components.len() { - return Err(ExpressionError::InvalidComposeCount { - expected: count, - given: components.len() as u32, - }); - } - let base_inner = &module.types[base].inner; - for (index, &comp) in components.iter().enumerate() { - let tin = resolver.resolve(comp)?; - if tin != base_inner { - log::error!("Array component[{}] type {:?}", index, tin); - return Err(ExpressionError::InvalidComponentType( - index as u32, - comp, - )); - } - } - } - Ti::Struct { - block: _, - ref members, - } => { - for (index, (member, &comp)) in members.iter().zip(components).enumerate() { - let tin = resolver.resolve(comp)?; - if tin != &module.types[member.ty].inner { - log::error!("Struct component[{}] type {:?}", index, tin); - return Err(ExpressionError::InvalidComponentType( - index as u32, - comp, - )); - } - } - if members.len() != components.len() { - return Err(ExpressionError::InvalidComposeCount { - given: components.len() as u32, - expected: members.len() as u32, - }); - } - } - ref other => { - log::error!("Composing of {:?}", other); - return Err(ExpressionError::InvalidComposeType(ty)); - } - } - } - E::FunctionArgument(index) => { - if index >= function.arguments.len() as u32 { - return Err(ExpressionError::FunctionArgumentDoesntExist(index)); - } - } - E::GlobalVariable(handle) => { - let _ = module - .global_variables - .try_get(handle) - .ok_or(ExpressionError::GlobalVarDoesntExist(handle))?; - } - E::LocalVariable(handle) => { - let _ = function - .local_variables - .try_get(handle) - .ok_or(ExpressionError::LocalVarDoesntExist(handle))?; - } - E::Load { pointer } => match *resolver.resolve(pointer)? { - Ti::Pointer { .. } | Ti::ValuePointer { .. } => {} - ref other => { - log::error!("Loading {:?}", other); - return Err(ExpressionError::InvalidPointerType(pointer)); - } - }, - E::ImageSample { - image, - sampler, - coordinate, - array_index, - offset, - level, - depth_ref, - } => {} - E::ImageLoad { - image, - coordinate, - array_index, - index, - } => {} - E::ImageQuery { image, query } => {} - E::Unary { op, expr } => { - use crate::UnaryOperator as Uo; - let inner = resolver.resolve(expr)?; - match (op, inner.scalar_kind()) { - (_, Some(Sk::Sint)) - | (_, Some(Sk::Bool)) - | (Uo::Negate, Some(Sk::Float)) - | (Uo::Not, Some(Sk::Uint)) => {} - other => { - log::error!("Op {:?} kind {:?}", op, other); - return Err(ExpressionError::InvalidUnaryOperandType(op, expr)); - } - } - } - E::Binary { op, left, right } => { - use crate::BinaryOperator as Bo; - let left_inner = resolver.resolve(left)?; - let right_inner = resolver.resolve(right)?; - let good = match op { - Bo::Add | Bo::Subtract | Bo::Divide | Bo::Modulo => match *left_inner { - Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { - Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner, - Sk::Bool => false, - }, - _ => false, - }, - Bo::Multiply => { - let kind_match = match left_inner.scalar_kind() { - Some(Sk::Uint) | Some(Sk::Sint) | Some(Sk::Float) => true, - Some(Sk::Bool) | None => false, - }; - //TODO: should we be more restrictive here? I.e. expect scalar only to the left. - let types_match = match (left_inner, right_inner) { - (&Ti::Scalar { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) - | (&Ti::Vector { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) - | (&Ti::Scalar { kind: kind1, .. }, &Ti::Vector { kind: kind2, .. }) => { - kind1 == kind2 - } - ( - &Ti::Scalar { - kind: Sk::Float, .. - }, - &Ti::Matrix { .. }, - ) - | ( - &Ti::Matrix { .. }, - &Ti::Scalar { - kind: Sk::Float, .. - }, - ) => true, - ( - &Ti::Vector { - kind: kind1, - size: size1, - .. - }, - &Ti::Vector { - kind: kind2, - size: size2, - .. - }, - ) => kind1 == kind2 && size1 == size2, - ( - &Ti::Matrix { columns, .. }, - &Ti::Vector { - kind: Sk::Float, - size, - .. - }, - ) => columns == size, - ( - &Ti::Vector { - kind: Sk::Float, - size, - .. - }, - &Ti::Matrix { rows, .. }, - ) => size == rows, - (&Ti::Matrix { columns, .. }, &Ti::Matrix { rows, .. }) => { - columns == rows - } - _ => false, - }; - let left_width = match *left_inner { - Ti::Scalar { width, .. } - | Ti::Vector { width, .. } - | Ti::Matrix { width, .. } => width, - _ => 0, - }; - let right_width = match *right_inner { - Ti::Scalar { width, .. } - | Ti::Vector { width, .. } - | Ti::Matrix { width, .. } => width, - _ => 0, - }; - kind_match && types_match && left_width == right_width - } - Bo::Equal | Bo::NotEqual => left_inner.is_sized() && left_inner == right_inner, - Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual => { - match *left_inner { - Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { - Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner, - Sk::Bool => false, - }, - ref other => { - log::error!("Op {:?} left type {:?}", op, other); - false - } - } - } - Bo::LogicalAnd | Bo::LogicalOr => match *left_inner { - Ti::Scalar { kind: Sk::Bool, .. } | Ti::Vector { kind: Sk::Bool, .. } => { - left_inner == right_inner - } - ref other => { - log::error!("Op {:?} left type {:?}", op, other); - false - } - }, - Bo::And | Bo::ExclusiveOr | Bo::InclusiveOr => match *left_inner { - Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { - Sk::Sint | Sk::Uint => left_inner == right_inner, - Sk::Bool | Sk::Float => false, - }, - ref other => { - log::error!("Op {:?} left type {:?}", op, other); - false - } - }, - Bo::ShiftLeft | Bo::ShiftRight => { - let (base_size, base_kind) = match *left_inner { - Ti::Scalar { kind, .. } => (Ok(None), kind), - Ti::Vector { size, kind, .. } => (Ok(Some(size)), kind), - ref other => { - log::error!("Op {:?} base type {:?}", op, other); - (Err(()), Sk::Bool) - } - }; - let shift_size = match *right_inner { - Ti::Scalar { kind: Sk::Uint, .. } => Ok(None), - Ti::Vector { - size, - kind: Sk::Uint, - .. - } => Ok(Some(size)), - ref other => { - log::error!("Op {:?} shift type {:?}", op, other); - Err(()) - } - }; - match base_kind { - Sk::Sint | Sk::Uint => base_size.is_ok() && base_size == shift_size, - Sk::Float | Sk::Bool => false, - } - } - }; - if !good { - return Err(ExpressionError::InvalidBinaryOperandTypes(op, left, right)); - } - } - E::Select { - condition, - accept, - reject, - } => { - let accept_inner = resolver.resolve(accept)?; - let reject_inner = resolver.resolve(reject)?; - let condition_good = match *resolver.resolve(condition)? { - Ti::Scalar { - kind: Sk::Bool, - width: _, - } => accept_inner.is_sized(), - Ti::Vector { - size, - kind: Sk::Bool, - width: _, - } => match *accept_inner { - Ti::Vector { - size: other_size, .. - } => size == other_size, - _ => false, - }, - _ => false, - }; - if !condition_good || accept_inner != reject_inner { - return Err(ExpressionError::InvalidSelectTypes); - } - } - E::Derivative { axis, expr } => { - //TODO: check stage - } - E::Relational { fun, argument } => { - use crate::RelationalFunction as Rf; - let argument_inner = resolver.resolve(argument)?; - match fun { - Rf::All | Rf::Any => match *argument_inner { - Ti::Vector { kind: Sk::Bool, .. } => {} - ref other => { - log::error!("All/Any of type {:?}", other); - return Err(ExpressionError::InvalidBooleanVector(argument)); - } - }, - Rf::IsNan | Rf::IsInf | Rf::IsFinite | Rf::IsNormal => match *argument_inner { - Ti::Scalar { - kind: Sk::Float, .. - } - | Ti::Vector { - kind: Sk::Float, .. - } => {} - ref other => { - log::error!("Float test of type {:?}", other); - return Err(ExpressionError::InvalidFloatArgument(argument)); - } - }, - } - } - E::Math { - fun, - arg, - arg1, - arg2, - } => {} - E::As { - expr, - kind, - convert, - } => {} - E::Call(function) => {} - E::ArrayLength(expr) => match *resolver.resolve(expr)? { - Ti::Array { .. } => {} - ref other => { - log::error!("Array length of {:?}", other); - return Err(ExpressionError::InvalidArrayType(expr)); - } - }, - } - Ok(()) - } - - fn resolve_statement_type_impl<'a>( - &'a self, - handle: Handle, - types: &'a Arena, - ) -> Result<&'a crate::TypeInner, ExpressionError> { - if !self.valid_expression_set.contains(handle.index()) { - return Err(ExpressionError::NotInScope); - } - self.typifier - .try_get(handle, types) - .ok_or(ExpressionError::DoesntExist) - } - - fn resolve_statement_type<'a>( - &'a self, - handle: Handle, - types: &'a Arena, - ) -> Result<&'a crate::TypeInner, FunctionError> { - self.resolve_statement_type_impl(handle, types) - .map_err(|error| FunctionError::Expression { handle, error }) - } - - fn validate_block_impl( - &mut self, - statements: &[crate::Statement], - context: &BlockContext, - ) -> Result<(), FunctionError> { - use crate::{Statement as S, TypeInner as Ti}; - let mut finished = false; - for statement in statements { - if finished { - return Err(FunctionError::InstructionsAfterReturn); - } - match *statement { - S::Emit(ref range) => { - for handle in range.clone() { - if self.valid_expression_set.insert(handle.index()) { - self.valid_expression_list.push(handle); - } else { - return Err(FunctionError::ExpressionAlreadyInScope(handle)); - } - } - } - S::Block(ref block) => self.validate_block(block, context)?, - S::If { - condition, - ref accept, - ref reject, - } => { - match *self.resolve_statement_type(condition, context.types)? { - Ti::Scalar { - kind: crate::ScalarKind::Bool, - width: _, - } => {} - _ => return Err(FunctionError::InvalidIfType(condition)), - } - self.validate_block(accept, context)?; - self.validate_block(reject, context)?; - } - S::Switch { - selector, - ref cases, - ref default, - } => { - match *self.resolve_statement_type(selector, context.types)? { - Ti::Scalar { - kind: crate::ScalarKind::Sint, - width: _, - } => {} - _ => return Err(FunctionError::InvalidSwitchType(selector)), - } - self.select_cases.clear(); - for case in cases { - if !self.select_cases.insert(case.value) { - return Err(FunctionError::ConflictingSwitchCase(case.value)); - } - } - for case in cases { - self.validate_block(&case.body, context)?; - } - self.validate_block(default, context)?; - } - S::Loop { - ref body, - ref continuing, - } => { - // special handling for block scoping is needed here, - // because the continuing{} block inherits the scope - let base_expression_count = self.valid_expression_list.len(); - self.validate_block_impl( - body, - &context.with_flags(BlockFlags::CAN_JUMP | BlockFlags::IN_LOOP), - )?; - self.validate_block_impl(continuing, &context.with_flags(BlockFlags::empty()))?; - for handle in self.valid_expression_list.drain(base_expression_count..) { - self.valid_expression_set.remove(handle.index()); - } - } - S::Break | S::Continue => { - if !context.flags.contains(BlockFlags::IN_LOOP) { - return Err(FunctionError::BreakContinueOutsideOfLoop); - } - finished = true; - } - S::Return { value } => { - if !context.flags.contains(BlockFlags::CAN_JUMP) { - return Err(FunctionError::InvalidReturnSpot); - } - let value_ty = value - .map(|expr| self.resolve_statement_type(expr, context.types)) - .transpose()?; - let expected_ty = context.return_type.map(|ty| &context.types[ty].inner); - if value_ty != expected_ty { - log::error!( - "Returning {:?} where {:?} is expected", - value_ty, - expected_ty - ); - return Err(FunctionError::InvalidReturnType(value)); - } - finished = true; - } - S::Kill => { - finished = true; - } - S::Store { pointer, value } => { - let mut current = pointer; - loop { - self.typifier.try_get(current, context.types).ok_or( - FunctionError::Expression { - handle: current, - error: ExpressionError::DoesntExist, - }, - )?; - match context.expressions[current] { - crate::Expression::Access { base, .. } - | crate::Expression::AccessIndex { base, .. } => current = base, - crate::Expression::LocalVariable(_) - | crate::Expression::GlobalVariable(_) - | crate::Expression::FunctionArgument(_) => break, - _ => return Err(FunctionError::InvalidStorePointer(current)), - } - } - - let value_ty = self.resolve_statement_type(value, context.types)?; - match *value_ty { - Ti::Image { .. } | Ti::Sampler { .. } => { - return Err(FunctionError::InvalidStoreValue(value)); - } - _ => {} - } - let good = match self.typifier.try_get(pointer, context.types) { - Some(&Ti::Pointer { base, class: _ }) => { - *value_ty == context.types[base].inner - } - Some(&Ti::ValuePointer { - size: Some(size), - kind, - width, - class: _, - }) => *value_ty == Ti::Vector { size, kind, width }, - Some(&Ti::ValuePointer { - size: None, - kind, - width, - class: _, - }) => *value_ty == Ti::Scalar { kind, width }, - _ => false, - }; - if !good { - return Err(FunctionError::InvalidStoreTypes { pointer, value }); - } - } - S::ImageStore { - image, - coordinate: _, - array_index, - value, - } => { - let _expected_coordinate_ty = match *context.get_expression(image)? { - crate::Expression::GlobalVariable(_var_handle) => (), //TODO - _ => return Err(FunctionError::InvalidImage(image)), - }; - let value_ty = self.typifier.get(value, context.types); - match *value_ty { - Ti::Scalar { .. } | Ti::Vector { .. } => {} - _ => { - return Err(FunctionError::InvalidStoreValue(value)); - } - } - if let Some(expr) = array_index { - match *self.typifier.get(expr, context.types) { - Ti::Scalar { - kind: crate::ScalarKind::Sint, - width: _, - } => (), - _ => return Err(FunctionError::InvalidArrayIndex(expr)), - } - } - } - S::Call { - function, - ref arguments, - result, - } => { - if let Err(error) = self.validate_call(function, arguments, result, context) { - return Err(FunctionError::InvalidCall { function, error }); - } - } - } - } - Ok(()) - } - - fn validate_block( - &mut self, - statements: &[crate::Statement], - context: &BlockContext, - ) -> Result<(), FunctionError> { - let base_expression_count = self.valid_expression_list.len(); - self.validate_block_impl(statements, context)?; - for handle in self.valid_expression_list.drain(base_expression_count..) { - self.valid_expression_set.remove(handle.index()); - } - Ok(()) - } - - fn validate_function( - &mut self, - fun: &crate::Function, - _info: &FunctionInfo, - module: &crate::Module, - ) -> Result<(), FunctionError> { - let resolve_ctx = ResolveContext { - constants: &module.constants, - global_vars: &module.global_variables, - local_vars: &fun.local_variables, - functions: &module.functions, - arguments: &fun.arguments, - }; - self.typifier - .resolve_all(&fun.expressions, &module.types, &resolve_ctx)?; - - for (var_handle, var) in fun.local_variables.iter() { - self.validate_local_var(var, &module.types, &module.constants) - .map_err(|error| FunctionError::LocalVariable { - handle: var_handle, - name: var.name.clone().unwrap_or_default(), - error, - })?; - } - - for (index, argument) in fun.arguments.iter().enumerate() { - if !self.type_flags[argument.ty.index()].contains(TypeFlags::DATA) { - return Err(FunctionError::InvalidArgumentType { - index, - name: argument.name.clone().unwrap_or_default(), - }); - } - } - - self.valid_expression_set.clear(); - for (handle, expr) in fun.expressions.iter() { - if expr.needs_pre_emit() { - self.valid_expression_set.insert(handle.index()); - } - if let Err(error) = self.validate_expression(handle, expr, fun, module) { - return Err(FunctionError::Expression { handle, error }); - } - } - - self.validate_block( - &fun.body, - &BlockContext { - flags: BlockFlags::CAN_JUMP, - expressions: &fun.expressions, - types: &module.types, - functions: &module.functions, - return_type: fun.result.as_ref().map(|fr| fr.ty), - }, - ) - } - - fn validate_entry_point( - &mut self, - ep: &crate::EntryPoint, - info: &FunctionInfo, - module: &crate::Module, - ) -> Result<(), EntryPointError> { - if ep.early_depth_test.is_some() && ep.stage != crate::ShaderStage::Fragment { - return Err(EntryPointError::UnexpectedEarlyDepthTest); - } - if ep.stage == crate::ShaderStage::Compute { - if ep - .workgroup_size - .iter() - .any(|&s| s == 0 || s > MAX_WORKGROUP_SIZE) - { - return Err(EntryPointError::OutOfRangeWorkgroupSize); - } - } else if ep.workgroup_size != [0; 3] { - return Err(EntryPointError::UnexpectedWorkgroupSize); - } - - self.location_mask.clear(); - for (index, fa) in ep.function.arguments.iter().enumerate() { - let ctx = VaryingContext { - ty: fa.ty, - stage: ep.stage, - output: false, - types: &module.types, - location_mask: &mut self.location_mask, - }; - ctx.validate(fa.binding.as_ref()) - .map_err(|e| EntryPointError::Argument(index as u32, e))?; - } - - self.location_mask.clear(); - if let Some(ref fr) = ep.function.result { - let ctx = VaryingContext { - ty: fr.ty, - stage: ep.stage, - output: true, - types: &module.types, - location_mask: &mut self.location_mask, - }; - ctx.validate(fr.binding.as_ref()) - .map_err(EntryPointError::Result)?; - } - - for bg in self.bind_group_masks.iter_mut() { - bg.clear(); - } - for (var_handle, var) in module.global_variables.iter() { - let usage = info[var_handle]; - if usage.is_empty() { - continue; - } - - let allowed_usage = match var.class { - crate::StorageClass::Function => unreachable!(), - crate::StorageClass::Uniform => GlobalUse::READ | GlobalUse::QUERY, - crate::StorageClass::Storage => storage_usage(var.storage_access), - crate::StorageClass::Handle => match module.types[var.ty].inner { - crate::TypeInner::Image { - class: crate::ImageClass::Storage(_), - .. - } => storage_usage(var.storage_access), - _ => GlobalUse::READ | GlobalUse::QUERY, - }, - crate::StorageClass::Private | crate::StorageClass::WorkGroup => GlobalUse::all(), - crate::StorageClass::PushConstant => GlobalUse::READ, - }; - if !allowed_usage.contains(usage) { - log::warn!("\tUsage error for: {:?}", var); - log::warn!( - "\tAllowed usage: {:?}, requested: {:?}", - allowed_usage, - usage - ); - return Err(EntryPointError::InvalidGlobalUsage(var_handle, usage)); - } - - if let Some(ref bind) = var.binding { - while self.bind_group_masks.len() <= bind.group as usize { - self.bind_group_masks.push(BitSet::new()); - } - if !self.bind_group_masks[bind.group as usize].insert(bind.binding as usize) { - return Err(EntryPointError::BindingCollision(var_handle)); - } - } - } - - self.validate_function(&ep.function, info, module)?; - Ok(()) - } - - /// Check the given module to be valid. - pub fn validate(&mut self, module: &crate::Module) -> Result { - self.typifier.clear(); - self.type_flags.clear(); - self.type_flags - .resize(module.types.len(), TypeFlags::empty()); - - let analysis = Analysis::new(module, self.analysis_flags)?; - - for (handle, constant) in module.constants.iter() { - self.validate_constant(handle, &module.constants, &module.types) - .map_err(|error| ValidationError::Constant { - handle, - name: constant.name.clone().unwrap_or_default(), - error, - })?; - } - - // doing after the globals, so that `type_flags` is ready - for (handle, ty) in module.types.iter() { - let ty_flags = self - .validate_type(ty, handle, &module.constants) - .map_err(|error| ValidationError::Type { - handle, - name: ty.name.clone().unwrap_or_default(), - error, - })?; - self.type_flags[handle.index()] = ty_flags; - } - - for (var_handle, var) in module.global_variables.iter() { - self.validate_global_var(var, &module.types) - .map_err(|error| ValidationError::GlobalVariable { - handle: var_handle, - name: var.name.clone().unwrap_or_default(), - error, - })?; - } - - for (handle, fun) in module.functions.iter() { - self.validate_function(fun, &analysis[handle], module) - .map_err(|error| ValidationError::Function { - handle, - name: fun.name.clone().unwrap_or_default(), - error, - })?; - } - - let mut ep_map = FastHashSet::default(); - for (index, ep) in module.entry_points.iter().enumerate() { - if !ep_map.insert((ep.stage, &ep.name)) { - return Err(ValidationError::EntryPoint { - stage: ep.stage, - name: ep.name.clone(), - error: EntryPointError::Conflict, - }); - } - let info = analysis.get_entry_point(index); - self.validate_entry_point(ep, info, module) - .map_err(|error| ValidationError::EntryPoint { - stage: ep.stage, - name: ep.name.clone(), - error, - })?; - } - - Ok(analysis) - } -} diff --git a/src/proc/analyzer.rs b/src/valid/analyzer.rs similarity index 99% rename from src/proc/analyzer.rs rename to src/valid/analyzer.rs index c0b131a9b..3264dfdf5 100644 --- a/src/proc/analyzer.rs +++ b/src/valid/analyzer.rs @@ -692,13 +692,13 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] -pub struct Analysis { +pub struct ModuleInfo { flags: AnalysisFlags, functions: Vec, entry_points: Vec, } -impl Analysis { +impl ModuleInfo { /// Builds the `FunctionInfo` based on the function, and validates the /// uniform control flow if required by the expressions of this function. fn process_function( @@ -732,9 +732,9 @@ impl Analysis { Ok(info) } - /// Analyze a module and return the `Analysis`, if successful. + /// Analyze a module and return the `ModuleInfo`, if successful. pub fn new(module: &crate::Module, flags: AnalysisFlags) -> Result { - let mut this = Analysis { + let mut this = ModuleInfo { flags, functions: Vec::with_capacity(module.functions.len()), entry_points: Vec::with_capacity(module.entry_points.len()), @@ -761,7 +761,7 @@ impl Analysis { } } -impl ops::Index> for Analysis { +impl ops::Index> for ModuleInfo { type Output = FunctionInfo; fn index(&self, handle: Handle) -> &FunctionInfo { &self.functions[handle.index()] diff --git a/src/valid/expression.rs b/src/valid/expression.rs new file mode 100644 index 000000000..119d1f4d8 --- /dev/null +++ b/src/valid/expression.rs @@ -0,0 +1,549 @@ +use crate::{ + arena::{Arena, Handle}, + proc::Typifier, +}; + +#[derive(Clone, Debug, thiserror::Error)] +pub enum ExpressionError { + #[error("Doesn't exist")] + DoesntExist, + #[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")] + NotInScope, + #[error("Depends on {0:?}, which has not been processed yet")] + ForwardDependency(Handle), + #[error("Base type {0:?} is not compatible with this expression")] + InvalidBaseType(Handle), + #[error("Accessing with index {0:?} can't be done")] + InvalidIndexType(Handle), + #[error("Accessing index {1} is out of {0:?} bounds")] + IndexOutOfBounds(Handle, u32), + #[error("Function argument {0:?} doesn't exist")] + FunctionArgumentDoesntExist(u32), + #[error("Constant {0:?} doesn't exist")] + ConstantDoesntExist(Handle), + #[error("Global variable {0:?} doesn't exist")] + GlobalVarDoesntExist(Handle), + #[error("Local variable {0:?} doesn't exist")] + LocalVarDoesntExist(Handle), + #[error("Loading of {0:?} can't be done")] + InvalidPointerType(Handle), + #[error("Array length of {0:?} can't be done")] + InvalidArrayType(Handle), + #[error("Compose type {0:?} doesn't exist")] + ComposeTypeDoesntExist(Handle), + #[error("Composing of type {0:?} can't be done")] + InvalidComposeType(Handle), + #[error("Composing expects {expected} components but {given} were given")] + InvalidComposeCount { given: u32, expected: u32 }, + #[error("Composing {0}'s component {1:?} is not expected")] + InvalidComponentType(u32, Handle), + #[error("Operation {0:?} can't work with {1:?}")] + InvalidUnaryOperandType(crate::UnaryOperator, Handle), + #[error("Operation {0:?} can't work with {1:?} and {2:?}")] + InvalidBinaryOperandTypes( + crate::BinaryOperator, + Handle, + Handle, + ), + #[error("Selecting is not possible")] + InvalidSelectTypes, + #[error("Relational argument {0:?} is not a boolean vector")] + InvalidBooleanVector(Handle), + #[error("Relational argument {0:?} is not a float")] + InvalidFloatArgument(Handle), +} + +struct ExpressionTypeResolver<'a> { + root: Handle, + types: &'a Arena, + typifier: &'a Typifier, +} + +impl<'a> ExpressionTypeResolver<'a> { + fn resolve( + &self, + handle: Handle, + ) -> Result<&'a crate::TypeInner, ExpressionError> { + if handle < self.root { + Ok(self.typifier.get(handle, self.types)) + } else { + Err(ExpressionError::ForwardDependency(handle)) + } + } +} + +impl super::Validator { + pub(super) fn validate_expression( + &self, + root: Handle, + expression: &crate::Expression, + function: &crate::Function, + module: &crate::Module, + ) -> Result<(), ExpressionError> { + use crate::{Expression as E, ScalarKind as Sk, TypeInner as Ti}; + + let resolver = ExpressionTypeResolver { + root, + types: &module.types, + typifier: &self.typifier, + }; + + match *expression { + E::Access { base, index } => { + match *resolver.resolve(base)? { + Ti::Vector { .. } + | Ti::Matrix { .. } + | Ti::Array { .. } + | Ti::Pointer { .. } => {} + ref other => { + log::error!("Indexing of {:?}", other); + return Err(ExpressionError::InvalidBaseType(base)); + } + } + match *resolver.resolve(index)? { + //TODO: only allow one of these + Ti::Scalar { + kind: Sk::Sint, + width: _, + } + | Ti::Scalar { + kind: Sk::Uint, + width: _, + } => {} + ref other => { + log::error!("Indexing by {:?}", other); + return Err(ExpressionError::InvalidIndexType(index)); + } + } + } + E::AccessIndex { base, index } => { + let limit = match *resolver.resolve(base)? { + Ti::Vector { size, .. } => size as u32, + Ti::Matrix { columns, .. } => columns as u32, + Ti::Array { + size: crate::ArraySize::Constant(handle), + .. + } => module.constants[handle].to_array_length().unwrap(), + Ti::Array { .. } => !0, // can't statically know, but need run-time checks + Ti::Pointer { .. } => !0, //TODO + Ti::Struct { + ref members, + block: _, + } => members.len() as u32, + ref other => { + log::error!("Indexing of {:?}", other); + return Err(ExpressionError::InvalidBaseType(base)); + } + }; + if index >= limit { + return Err(ExpressionError::IndexOutOfBounds(base, index)); + } + } + E::Constant(handle) => { + let _ = module + .constants + .try_get(handle) + .ok_or(ExpressionError::ConstantDoesntExist(handle))?; + } + E::Compose { ref components, ty } => { + match module + .types + .try_get(ty) + .ok_or(ExpressionError::ComposeTypeDoesntExist(ty))? + .inner + { + // vectors are composed from scalars or other vectors + Ti::Vector { size, kind, width } => { + let mut total = 0; + for (index, &comp) in components.iter().enumerate() { + total += match *resolver.resolve(comp)? { + Ti::Scalar { + kind: comp_kind, + width: comp_width, + } if comp_kind == kind && comp_width == width => 1, + Ti::Vector { + size: comp_size, + kind: comp_kind, + width: comp_width, + } if comp_kind == kind && comp_width == width => comp_size as u32, + ref other => { + log::error!("Vector component[{}] type {:?}", index, other); + return Err(ExpressionError::InvalidComponentType( + index as u32, + comp, + )); + } + }; + } + if size as u32 != total { + return Err(ExpressionError::InvalidComposeCount { + expected: size as u32, + given: total, + }); + } + } + // matrix are composed from column vectors + Ti::Matrix { + columns, + rows, + width, + } => { + let inner = Ti::Vector { + size: rows, + kind: Sk::Float, + width, + }; + if columns as usize != components.len() { + return Err(ExpressionError::InvalidComposeCount { + expected: columns as u32, + given: components.len() as u32, + }); + } + for (index, &comp) in components.iter().enumerate() { + let tin = resolver.resolve(comp)?; + if tin != &inner { + log::error!("Matrix component[{}] type {:?}", index, tin); + return Err(ExpressionError::InvalidComponentType( + index as u32, + comp, + )); + } + } + } + Ti::Array { + base, + size: crate::ArraySize::Constant(handle), + stride: _, + } => { + let count = module.constants[handle].to_array_length().unwrap(); + if count as usize != components.len() { + return Err(ExpressionError::InvalidComposeCount { + expected: count, + given: components.len() as u32, + }); + } + let base_inner = &module.types[base].inner; + for (index, &comp) in components.iter().enumerate() { + let tin = resolver.resolve(comp)?; + if tin != base_inner { + log::error!("Array component[{}] type {:?}", index, tin); + return Err(ExpressionError::InvalidComponentType( + index as u32, + comp, + )); + } + } + } + Ti::Struct { + block: _, + ref members, + } => { + for (index, (member, &comp)) in members.iter().zip(components).enumerate() { + let tin = resolver.resolve(comp)?; + if tin != &module.types[member.ty].inner { + log::error!("Struct component[{}] type {:?}", index, tin); + return Err(ExpressionError::InvalidComponentType( + index as u32, + comp, + )); + } + } + if members.len() != components.len() { + return Err(ExpressionError::InvalidComposeCount { + given: components.len() as u32, + expected: members.len() as u32, + }); + } + } + ref other => { + log::error!("Composing of {:?}", other); + return Err(ExpressionError::InvalidComposeType(ty)); + } + } + } + E::FunctionArgument(index) => { + if index >= function.arguments.len() as u32 { + return Err(ExpressionError::FunctionArgumentDoesntExist(index)); + } + } + E::GlobalVariable(handle) => { + let _ = module + .global_variables + .try_get(handle) + .ok_or(ExpressionError::GlobalVarDoesntExist(handle))?; + } + E::LocalVariable(handle) => { + let _ = function + .local_variables + .try_get(handle) + .ok_or(ExpressionError::LocalVarDoesntExist(handle))?; + } + E::Load { pointer } => match *resolver.resolve(pointer)? { + Ti::Pointer { .. } | Ti::ValuePointer { .. } => {} + ref other => { + log::error!("Loading {:?}", other); + return Err(ExpressionError::InvalidPointerType(pointer)); + } + }, + #[allow(unused)] + E::ImageSample { + image, + sampler, + coordinate, + array_index, + offset, + level, + depth_ref, + } => {} + #[allow(unused)] + E::ImageLoad { + image, + coordinate, + array_index, + index, + } => {} + #[allow(unused)] + E::ImageQuery { image, query } => {} + E::Unary { op, expr } => { + use crate::UnaryOperator as Uo; + let inner = resolver.resolve(expr)?; + match (op, inner.scalar_kind()) { + (_, Some(Sk::Sint)) + | (_, Some(Sk::Bool)) + | (Uo::Negate, Some(Sk::Float)) + | (Uo::Not, Some(Sk::Uint)) => {} + other => { + log::error!("Op {:?} kind {:?}", op, other); + return Err(ExpressionError::InvalidUnaryOperandType(op, expr)); + } + } + } + E::Binary { op, left, right } => { + use crate::BinaryOperator as Bo; + let left_inner = resolver.resolve(left)?; + let right_inner = resolver.resolve(right)?; + let good = match op { + Bo::Add | Bo::Subtract | Bo::Divide | Bo::Modulo => match *left_inner { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { + Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner, + Sk::Bool => false, + }, + _ => false, + }, + Bo::Multiply => { + let kind_match = match left_inner.scalar_kind() { + Some(Sk::Uint) | Some(Sk::Sint) | Some(Sk::Float) => true, + Some(Sk::Bool) | None => false, + }; + //TODO: should we be more restrictive here? I.e. expect scalar only to the left. + let types_match = match (left_inner, right_inner) { + (&Ti::Scalar { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) + | (&Ti::Vector { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) + | (&Ti::Scalar { kind: kind1, .. }, &Ti::Vector { kind: kind2, .. }) => { + kind1 == kind2 + } + ( + &Ti::Scalar { + kind: Sk::Float, .. + }, + &Ti::Matrix { .. }, + ) + | ( + &Ti::Matrix { .. }, + &Ti::Scalar { + kind: Sk::Float, .. + }, + ) => true, + ( + &Ti::Vector { + kind: kind1, + size: size1, + .. + }, + &Ti::Vector { + kind: kind2, + size: size2, + .. + }, + ) => kind1 == kind2 && size1 == size2, + ( + &Ti::Matrix { columns, .. }, + &Ti::Vector { + kind: Sk::Float, + size, + .. + }, + ) => columns == size, + ( + &Ti::Vector { + kind: Sk::Float, + size, + .. + }, + &Ti::Matrix { rows, .. }, + ) => size == rows, + (&Ti::Matrix { columns, .. }, &Ti::Matrix { rows, .. }) => { + columns == rows + } + _ => false, + }; + let left_width = match *left_inner { + Ti::Scalar { width, .. } + | Ti::Vector { width, .. } + | Ti::Matrix { width, .. } => width, + _ => 0, + }; + let right_width = match *right_inner { + Ti::Scalar { width, .. } + | Ti::Vector { width, .. } + | Ti::Matrix { width, .. } => width, + _ => 0, + }; + kind_match && types_match && left_width == right_width + } + Bo::Equal | Bo::NotEqual => left_inner.is_sized() && left_inner == right_inner, + Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual => { + match *left_inner { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { + Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner, + Sk::Bool => false, + }, + ref other => { + log::error!("Op {:?} left type {:?}", op, other); + false + } + } + } + Bo::LogicalAnd | Bo::LogicalOr => match *left_inner { + Ti::Scalar { kind: Sk::Bool, .. } | Ti::Vector { kind: Sk::Bool, .. } => { + left_inner == right_inner + } + ref other => { + log::error!("Op {:?} left type {:?}", op, other); + false + } + }, + Bo::And | Bo::ExclusiveOr | Bo::InclusiveOr => match *left_inner { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { + Sk::Sint | Sk::Uint => left_inner == right_inner, + Sk::Bool | Sk::Float => false, + }, + ref other => { + log::error!("Op {:?} left type {:?}", op, other); + false + } + }, + Bo::ShiftLeft | Bo::ShiftRight => { + let (base_size, base_kind) = match *left_inner { + Ti::Scalar { kind, .. } => (Ok(None), kind), + Ti::Vector { size, kind, .. } => (Ok(Some(size)), kind), + ref other => { + log::error!("Op {:?} base type {:?}", op, other); + (Err(()), Sk::Bool) + } + }; + let shift_size = match *right_inner { + Ti::Scalar { kind: Sk::Uint, .. } => Ok(None), + Ti::Vector { + size, + kind: Sk::Uint, + .. + } => Ok(Some(size)), + ref other => { + log::error!("Op {:?} shift type {:?}", op, other); + Err(()) + } + }; + match base_kind { + Sk::Sint | Sk::Uint => base_size.is_ok() && base_size == shift_size, + Sk::Float | Sk::Bool => false, + } + } + }; + if !good { + return Err(ExpressionError::InvalidBinaryOperandTypes(op, left, right)); + } + } + E::Select { + condition, + accept, + reject, + } => { + let accept_inner = resolver.resolve(accept)?; + let reject_inner = resolver.resolve(reject)?; + let condition_good = match *resolver.resolve(condition)? { + Ti::Scalar { + kind: Sk::Bool, + width: _, + } => accept_inner.is_sized(), + Ti::Vector { + size, + kind: Sk::Bool, + width: _, + } => match *accept_inner { + Ti::Vector { + size: other_size, .. + } => size == other_size, + _ => false, + }, + _ => false, + }; + if !condition_good || accept_inner != reject_inner { + return Err(ExpressionError::InvalidSelectTypes); + } + } + #[allow(unused)] + E::Derivative { axis, expr } => { + //TODO: check stage + } + E::Relational { fun, argument } => { + use crate::RelationalFunction as Rf; + let argument_inner = resolver.resolve(argument)?; + match fun { + Rf::All | Rf::Any => match *argument_inner { + Ti::Vector { kind: Sk::Bool, .. } => {} + ref other => { + log::error!("All/Any of type {:?}", other); + return Err(ExpressionError::InvalidBooleanVector(argument)); + } + }, + Rf::IsNan | Rf::IsInf | Rf::IsFinite | Rf::IsNormal => match *argument_inner { + Ti::Scalar { + kind: Sk::Float, .. + } + | Ti::Vector { + kind: Sk::Float, .. + } => {} + ref other => { + log::error!("Float test of type {:?}", other); + return Err(ExpressionError::InvalidFloatArgument(argument)); + } + }, + } + } + #[allow(unused)] + E::Math { + fun, + arg, + arg1, + arg2, + } => {} + #[allow(unused)] + E::As { + expr, + kind, + convert, + } => {} + #[allow(unused)] + E::Call(function) => {} + E::ArrayLength(expr) => match *resolver.resolve(expr)? { + Ti::Array { .. } => {} + ref other => { + log::error!("Array length of {:?}", other); + return Err(ExpressionError::InvalidArrayType(expr)); + } + }, + } + Ok(()) + } +} diff --git a/src/valid/function.rs b/src/valid/function.rs new file mode 100644 index 000000000..2edf339c7 --- /dev/null +++ b/src/valid/function.rs @@ -0,0 +1,510 @@ +use super::{analyzer::FunctionInfo, ExpressionError, TypeFlags}; +use crate::{ + arena::{Arena, Handle}, + proc::{ResolveContext, TypifyError}, +}; + +#[derive(Clone, Debug, thiserror::Error)] +pub enum CallError { + #[error("Bad function")] + InvalidFunction, + #[error("The callee is declared after the caller")] + ForwardDeclaredFunction, + #[error("Argument {index} expression is invalid")] + Argument { + index: usize, + #[source] + error: ExpressionError, + }, + #[error("Result expression {0:?} has already been introduced earlier")] + ResultAlreadyInScope(Handle), + #[error("Result value is invalid")] + ResultValue(#[source] ExpressionError), + #[error("Requires {required} arguments, but {seen} are provided")] + ArgumentCount { required: usize, seen: usize }, + #[error("Argument {index} value {seen_expression:?} doesn't match the type {required:?}")] + ArgumentType { + index: usize, + required: Handle, + seen_expression: Handle, + }, + #[error("Result value {seen_expression:?} does not match the type {required:?}")] + ResultType { + required: Option>, + seen_expression: Option>, + }, +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum LocalVariableError { + #[error("Initializer doesn't match the variable type")] + InitializerType, +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum FunctionError { + #[error(transparent)] + Resolve(#[from] TypifyError), + #[error("Expression {handle:?} is invalid")] + Expression { + handle: Handle, + #[source] + error: ExpressionError, + }, + #[error("Expression {0:?} can't be introduced - it's already in scope")] + ExpressionAlreadyInScope(Handle), + #[error("Local variable {handle:?} '{name}' is invalid")] + LocalVariable { + handle: Handle, + name: String, + #[source] + error: LocalVariableError, + }, + #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")] + InvalidArgumentType { index: usize, name: String }, + #[error("There are instructions after `return`/`break`/`continue`")] + InstructionsAfterReturn, + #[error("The `break`/`continue` is used outside of a loop context")] + BreakContinueOutsideOfLoop, + #[error("The `return` is called within a `continuing` block")] + InvalidReturnSpot, + #[error("The `return` value {0:?} does not match the function return value")] + InvalidReturnType(Option>), + #[error("The `if` condition {0:?} is not a boolean scalar")] + InvalidIfType(Handle), + #[error("The `switch` value {0:?} is not an integer scalar")] + InvalidSwitchType(Handle), + #[error("Multiple `switch` cases for {0} are present")] + ConflictingSwitchCase(i32), + #[error("The pointer {0:?} doesn't relate to a valid destination for a store")] + InvalidStorePointer(Handle), + #[error("The value {0:?} can not be stored")] + InvalidStoreValue(Handle), + #[error("Store of {value:?} into {pointer:?} doesn't have matching types")] + InvalidStoreTypes { + pointer: Handle, + value: Handle, + }, + #[error("The image array can't be indexed by {0:?}")] + InvalidArrayIndex(Handle), + #[error("The expression {0:?} is currupted")] + InvalidExpression(Handle), + #[error("The expression {0:?} is not an image")] + InvalidImage(Handle), + #[error("Call to {function:?} is invalid")] + InvalidCall { + function: Handle, + #[source] + error: CallError, + }, +} + +bitflags::bitflags! { + #[repr(transparent)] + struct Flags: u8 { + /// The control can jump out of this block. + const CAN_JUMP = 0x1; + /// The control is in a loop, can break and continue. + const IN_LOOP = 0x2; + } +} + +struct BlockContext<'a> { + flags: Flags, + expressions: &'a Arena, + types: &'a Arena, + functions: &'a Arena, + return_type: Option>, +} + +impl<'a> BlockContext<'a> { + pub(super) fn new(fun: &'a crate::Function, module: &'a crate::Module) -> Self { + Self { + flags: Flags::CAN_JUMP, + expressions: &fun.expressions, + types: &module.types, + functions: &module.functions, + return_type: fun.result.as_ref().map(|fr| fr.ty), + } + } + + fn with_flags(&self, flags: Flags) -> Self { + BlockContext { + flags, + expressions: self.expressions, + types: self.types, + functions: self.functions, + return_type: self.return_type, + } + } + + fn get_expression( + &self, + handle: Handle, + ) -> Result<&'a crate::Expression, FunctionError> { + self.expressions + .try_get(handle) + .ok_or(FunctionError::InvalidExpression(handle)) + } +} + +impl super::Validator { + fn validate_call( + &mut self, + function: Handle, + arguments: &[Handle], + result: Option>, + context: &BlockContext, + ) -> Result<(), CallError> { + let fun = context + .functions + .try_get(function) + .ok_or(CallError::InvalidFunction)?; + if fun.arguments.len() != arguments.len() { + return Err(CallError::ArgumentCount { + required: fun.arguments.len(), + seen: arguments.len(), + }); + } + for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { + let ty = self + .resolve_statement_type_impl(expr, context.types) + .map_err(|error| CallError::Argument { index, error })?; + if ty != &context.types[arg.ty].inner { + return Err(CallError::ArgumentType { + index, + required: arg.ty, + seen_expression: expr, + }); + } + } + + if let Some(expr) = result { + if self.valid_expression_set.insert(expr.index()) { + self.valid_expression_list.push(expr); + } else { + return Err(CallError::ResultAlreadyInScope(expr)); + } + } + + let result_ty = result + .map(|expr| self.resolve_statement_type_impl(expr, context.types)) + .transpose() + .map_err(CallError::ResultValue)?; + let expected_ty = fun.result.as_ref().map(|fr| &context.types[fr.ty].inner); + if result_ty != expected_ty { + log::error!( + "Called function returns {:?} where {:?} is expected", + result_ty, + expected_ty + ); + return Err(CallError::ResultType { + required: fun.result.as_ref().map(|fr| fr.ty), + seen_expression: result, + }); + } + Ok(()) + } + + fn resolve_statement_type_impl<'a>( + &'a self, + handle: Handle, + types: &'a Arena, + ) -> Result<&'a crate::TypeInner, ExpressionError> { + if !self.valid_expression_set.contains(handle.index()) { + return Err(ExpressionError::NotInScope); + } + self.typifier + .try_get(handle, types) + .ok_or(ExpressionError::DoesntExist) + } + + fn resolve_statement_type<'a>( + &'a self, + handle: Handle, + types: &'a Arena, + ) -> Result<&'a crate::TypeInner, FunctionError> { + self.resolve_statement_type_impl(handle, types) + .map_err(|error| FunctionError::Expression { handle, error }) + } + + fn validate_block_impl( + &mut self, + statements: &[crate::Statement], + context: &BlockContext, + ) -> Result<(), FunctionError> { + use crate::{Statement as S, TypeInner as Ti}; + let mut finished = false; + for statement in statements { + if finished { + return Err(FunctionError::InstructionsAfterReturn); + } + match *statement { + S::Emit(ref range) => { + for handle in range.clone() { + if self.valid_expression_set.insert(handle.index()) { + self.valid_expression_list.push(handle); + } else { + return Err(FunctionError::ExpressionAlreadyInScope(handle)); + } + } + } + S::Block(ref block) => self.validate_block(block, context)?, + S::If { + condition, + ref accept, + ref reject, + } => { + match *self.resolve_statement_type(condition, context.types)? { + Ti::Scalar { + kind: crate::ScalarKind::Bool, + width: _, + } => {} + _ => return Err(FunctionError::InvalidIfType(condition)), + } + self.validate_block(accept, context)?; + self.validate_block(reject, context)?; + } + S::Switch { + selector, + ref cases, + ref default, + } => { + match *self.resolve_statement_type(selector, context.types)? { + Ti::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => {} + _ => return Err(FunctionError::InvalidSwitchType(selector)), + } + self.select_cases.clear(); + for case in cases { + if !self.select_cases.insert(case.value) { + return Err(FunctionError::ConflictingSwitchCase(case.value)); + } + } + for case in cases { + self.validate_block(&case.body, context)?; + } + self.validate_block(default, context)?; + } + S::Loop { + ref body, + ref continuing, + } => { + // special handling for block scoping is needed here, + // because the continuing{} block inherits the scope + let base_expression_count = self.valid_expression_list.len(); + self.validate_block_impl( + body, + &context.with_flags(Flags::CAN_JUMP | Flags::IN_LOOP), + )?; + self.validate_block_impl(continuing, &context.with_flags(Flags::empty()))?; + for handle in self.valid_expression_list.drain(base_expression_count..) { + self.valid_expression_set.remove(handle.index()); + } + } + S::Break | S::Continue => { + if !context.flags.contains(Flags::IN_LOOP) { + return Err(FunctionError::BreakContinueOutsideOfLoop); + } + finished = true; + } + S::Return { value } => { + if !context.flags.contains(Flags::CAN_JUMP) { + return Err(FunctionError::InvalidReturnSpot); + } + let value_ty = value + .map(|expr| self.resolve_statement_type(expr, context.types)) + .transpose()?; + let expected_ty = context.return_type.map(|ty| &context.types[ty].inner); + if value_ty != expected_ty { + log::error!( + "Returning {:?} where {:?} is expected", + value_ty, + expected_ty + ); + return Err(FunctionError::InvalidReturnType(value)); + } + finished = true; + } + S::Kill => { + finished = true; + } + S::Store { pointer, value } => { + let mut current = pointer; + loop { + self.typifier.try_get(current, context.types).ok_or( + FunctionError::Expression { + handle: current, + error: ExpressionError::DoesntExist, + }, + )?; + match context.expressions[current] { + crate::Expression::Access { base, .. } + | crate::Expression::AccessIndex { base, .. } => current = base, + crate::Expression::LocalVariable(_) + | crate::Expression::GlobalVariable(_) + | crate::Expression::FunctionArgument(_) => break, + _ => return Err(FunctionError::InvalidStorePointer(current)), + } + } + + let value_ty = self.resolve_statement_type(value, context.types)?; + match *value_ty { + Ti::Image { .. } | Ti::Sampler { .. } => { + return Err(FunctionError::InvalidStoreValue(value)); + } + _ => {} + } + let good = match self.typifier.try_get(pointer, context.types) { + Some(&Ti::Pointer { base, class: _ }) => { + *value_ty == context.types[base].inner + } + Some(&Ti::ValuePointer { + size: Some(size), + kind, + width, + class: _, + }) => *value_ty == Ti::Vector { size, kind, width }, + Some(&Ti::ValuePointer { + size: None, + kind, + width, + class: _, + }) => *value_ty == Ti::Scalar { kind, width }, + _ => false, + }; + if !good { + return Err(FunctionError::InvalidStoreTypes { pointer, value }); + } + } + S::ImageStore { + image, + coordinate: _, + array_index, + value, + } => { + let _expected_coordinate_ty = match *context.get_expression(image)? { + crate::Expression::GlobalVariable(_var_handle) => (), //TODO + _ => return Err(FunctionError::InvalidImage(image)), + }; + let value_ty = self.typifier.get(value, context.types); + match *value_ty { + Ti::Scalar { .. } | Ti::Vector { .. } => {} + _ => { + return Err(FunctionError::InvalidStoreValue(value)); + } + } + if let Some(expr) = array_index { + match *self.typifier.get(expr, context.types) { + Ti::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => (), + _ => return Err(FunctionError::InvalidArrayIndex(expr)), + } + } + } + S::Call { + function, + ref arguments, + result, + } => { + if let Err(error) = self.validate_call(function, arguments, result, context) { + return Err(FunctionError::InvalidCall { function, error }); + } + } + } + } + Ok(()) + } + + fn validate_block( + &mut self, + statements: &[crate::Statement], + context: &BlockContext, + ) -> Result<(), FunctionError> { + let base_expression_count = self.valid_expression_list.len(); + self.validate_block_impl(statements, context)?; + for handle in self.valid_expression_list.drain(base_expression_count..) { + self.valid_expression_set.remove(handle.index()); + } + Ok(()) + } + + fn validate_local_var( + &self, + var: &crate::LocalVariable, + types: &Arena, + constants: &Arena, + ) -> Result<(), LocalVariableError> { + log::debug!("var {:?}", var); + if let Some(const_handle) = var.init { + match constants[const_handle].inner { + crate::ConstantInner::Scalar { width, ref value } => { + let ty_inner = crate::TypeInner::Scalar { + width, + kind: value.scalar_kind(), + }; + if types[var.ty].inner != ty_inner { + return Err(LocalVariableError::InitializerType); + } + } + crate::ConstantInner::Composite { ty, components: _ } => { + if ty != var.ty { + return Err(LocalVariableError::InitializerType); + } + } + } + } + Ok(()) + } + + pub(super) fn validate_function( + &mut self, + fun: &crate::Function, + _info: &FunctionInfo, + module: &crate::Module, + ) -> Result<(), FunctionError> { + let resolve_ctx = ResolveContext { + constants: &module.constants, + global_vars: &module.global_variables, + local_vars: &fun.local_variables, + functions: &module.functions, + arguments: &fun.arguments, + }; + self.typifier + .resolve_all(&fun.expressions, &module.types, &resolve_ctx)?; + + for (var_handle, var) in fun.local_variables.iter() { + self.validate_local_var(var, &module.types, &module.constants) + .map_err(|error| FunctionError::LocalVariable { + handle: var_handle, + name: var.name.clone().unwrap_or_default(), + error, + })?; + } + + for (index, argument) in fun.arguments.iter().enumerate() { + if !self.type_flags[argument.ty.index()].contains(TypeFlags::DATA) { + return Err(FunctionError::InvalidArgumentType { + index, + name: argument.name.clone().unwrap_or_default(), + }); + } + } + + self.valid_expression_set.clear(); + for (handle, expr) in fun.expressions.iter() { + if expr.needs_pre_emit() { + self.valid_expression_set.insert(handle.index()); + } + if let Err(error) = self.validate_expression(handle, expr, fun, module) { + return Err(FunctionError::Expression { handle, error }); + } + } + + self.validate_block(&fun.body, &BlockContext::new(fun, module)) + } +} diff --git a/src/valid/interface.rs b/src/valid/interface.rs new file mode 100644 index 000000000..39d5ebdef --- /dev/null +++ b/src/valid/interface.rs @@ -0,0 +1,428 @@ +use super::{ + analyzer::{FunctionInfo, GlobalUse}, + FunctionError, TypeFlags, +}; +use crate::arena::{Arena, Handle}; + +use bit_set::BitSet; + +const MAX_WORKGROUP_SIZE: u32 = 0x4000; + +#[derive(Clone, Debug, thiserror::Error)] +pub enum GlobalVariableError { + #[error("Usage isn't compatible with the storage class")] + InvalidUsage, + #[error("Type isn't compatible with the storage class")] + InvalidType, + #[error("Storage access {seen:?} exceeds the allowed {allowed:?}")] + InvalidStorageAccess { + allowed: crate::StorageAccess, + seen: crate::StorageAccess, + }, + #[error("Type flags {seen:?} do not meet the required {required:?}")] + MissingTypeFlags { + required: TypeFlags, + seen: TypeFlags, + }, + #[error("Binding decoration is missing or not applicable")] + InvalidBinding, +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum VaryingError { + #[error("The type {0:?} does not match the varying")] + InvalidType(Handle), + #[error("Interpolation is not valid")] + InvalidInterpolation, + #[error("BuiltIn {0:?} is not available at this stage")] + InvalidBuiltInStage(crate::BuiltIn), + #[error("BuiltIn type for {0:?} is invalid")] + InvalidBuiltInType(crate::BuiltIn), + #[error("Struct member {0} is missing a binding")] + MemberMissingBinding(u32), + #[error("Multiple bindings at location {location} are present")] + BindingCollision { location: u32 }, +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum EntryPointError { + #[error("Multiple conflicting entry points")] + Conflict, + #[error("Early depth test is not applicable")] + UnexpectedEarlyDepthTest, + #[error("Workgroup size is not applicable")] + UnexpectedWorkgroupSize, + #[error("Workgroup size is out of range")] + OutOfRangeWorkgroupSize, + #[error("Global variable {0:?} is used incorrectly as {1:?}")] + InvalidGlobalUsage(Handle, GlobalUse), + #[error("Bindings for {0:?} conflict with other resource")] + BindingCollision(Handle), + #[error("Argument {0} varying error")] + Argument(u32, #[source] VaryingError), + #[error("Result varying error")] + Result(#[source] VaryingError), + #[error("Location {location} onterpolation of an integer has to be flat")] + InvalidIntegerInterpolation { location: u32 }, + #[error(transparent)] + Function(#[from] FunctionError), +} + +fn storage_usage(access: crate::StorageAccess) -> GlobalUse { + let mut storage_usage = GlobalUse::QUERY; + if access.contains(crate::StorageAccess::LOAD) { + storage_usage |= GlobalUse::READ; + } + if access.contains(crate::StorageAccess::STORE) { + storage_usage |= GlobalUse::WRITE; + } + storage_usage +} + +struct VaryingContext<'a> { + ty: Handle, + stage: crate::ShaderStage, + output: bool, + types: &'a Arena, + location_mask: &'a mut BitSet, +} + +impl VaryingContext<'_> { + fn validate_impl(&mut self, binding: &crate::Binding) -> Result<(), VaryingError> { + use crate::{ + BuiltIn as Bi, ScalarKind as Sk, ShaderStage as St, TypeInner as Ti, VectorSize as Vs, + }; + + let ty_inner = &self.types[self.ty].inner; + match *binding { + crate::Binding::BuiltIn(built_in) => { + let width = 4; + let (visible, type_good) = match built_in { + Bi::BaseInstance | Bi::BaseVertex | Bi::InstanceIndex | Bi::VertexIndex => ( + self.stage == St::Vertex && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ), + Bi::ClipDistance => ( + self.stage == St::Vertex && self.output, + match *ty_inner { + Ti::Array { base, .. } => { + self.types[base].inner + == Ti::Scalar { + kind: Sk::Float, + width, + } + } + _ => false, + }, + ), + Bi::PointSize => ( + self.stage == St::Vertex && self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Float, + width, + }, + ), + Bi::Position => ( + match self.stage { + St::Vertex => self.output, + St::Fragment => !self.output, + St::Compute => false, + }, + *ty_inner + == Ti::Vector { + size: Vs::Quad, + kind: Sk::Float, + width, + }, + ), + Bi::FragDepth => ( + self.stage == St::Fragment && self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Float, + width, + }, + ), + Bi::FrontFacing => ( + self.stage == St::Fragment && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Bool, + width: crate::BOOL_WIDTH, + }, + ), + Bi::SampleIndex => ( + self.stage == St::Fragment && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ), + Bi::SampleMask => ( + self.stage == St::Fragment, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ), + Bi::LocalInvocationIndex => ( + self.stage == St::Compute && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ), + Bi::GlobalInvocationId + | Bi::LocalInvocationId + | Bi::WorkGroupId + | Bi::WorkGroupSize => ( + self.stage == St::Compute && !self.output, + *ty_inner + == Ti::Vector { + size: Vs::Tri, + kind: Sk::Uint, + width, + }, + ), + }; + + if !visible { + return Err(VaryingError::InvalidBuiltInStage(built_in)); + } + if !type_good { + log::warn!("Wrong builtin type: {:?}", ty_inner); + return Err(VaryingError::InvalidBuiltInType(built_in)); + } + } + crate::Binding::Location(location, interpolation) => { + if !self.location_mask.insert(location as usize) { + return Err(VaryingError::BindingCollision { location }); + } + let needs_interpolation = + self.stage == crate::ShaderStage::Fragment && !self.output; + if !needs_interpolation && interpolation.is_some() { + return Err(VaryingError::InvalidInterpolation); + } + match ty_inner.scalar_kind() { + Some(crate::ScalarKind::Float) => {} + Some(_) + if needs_interpolation + && interpolation != Some(crate::Interpolation::Flat) => + { + return Err(VaryingError::InvalidInterpolation); + } + Some(_) => {} + None => return Err(VaryingError::InvalidType(self.ty)), + } + } + } + + Ok(()) + } + + fn validate(mut self, binding: Option<&crate::Binding>) -> Result<(), VaryingError> { + match binding { + Some(binding) => self.validate_impl(binding), + None => { + match self.types[self.ty].inner { + //TODO: check the member types + crate::TypeInner::Struct { + block: false, + ref members, + } => { + for (index, member) in members.iter().enumerate() { + self.ty = member.ty; + match member.binding { + None => { + return Err(VaryingError::MemberMissingBinding(index as u32)) + } + Some(ref binding) => self.validate_impl(binding)?, + } + } + } + _ => return Err(VaryingError::InvalidType(self.ty)), + } + Ok(()) + } + } + } +} + +impl super::Validator { + pub(super) fn validate_global_var( + &self, + var: &crate::GlobalVariable, + types: &Arena, + ) -> Result<(), GlobalVariableError> { + log::debug!("var {:?}", var); + let (allowed_storage_access, required_type_flags, is_resource) = match var.class { + crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), + crate::StorageClass::Storage => { + match types[var.ty].inner { + crate::TypeInner::Struct { .. } => (), + _ => return Err(GlobalVariableError::InvalidType), + } + ( + crate::StorageAccess::all(), + TypeFlags::DATA | TypeFlags::HOST_SHARED, + true, + ) + } + crate::StorageClass::Uniform => { + match types[var.ty].inner { + crate::TypeInner::Struct { .. } => (), + _ => return Err(GlobalVariableError::InvalidType), + } + ( + crate::StorageAccess::empty(), + TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED, + true, + ) + } + crate::StorageClass::Handle => { + let access = match types[var.ty].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Storage(_), + .. + } => crate::StorageAccess::all(), + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { + crate::StorageAccess::empty() + } + _ => return Err(GlobalVariableError::InvalidType), + }; + (access, TypeFlags::empty(), true) + } + crate::StorageClass::Private | crate::StorageClass::WorkGroup => { + (crate::StorageAccess::empty(), TypeFlags::DATA, false) + } + crate::StorageClass::PushConstant => ( + crate::StorageAccess::LOAD, + TypeFlags::DATA | TypeFlags::HOST_SHARED, + false, + ), + }; + + if !allowed_storage_access.contains(var.storage_access) { + return Err(GlobalVariableError::InvalidStorageAccess { + seen: var.storage_access, + allowed: allowed_storage_access, + }); + } + + let type_flags = self.type_flags[var.ty.index()]; + if !type_flags.contains(required_type_flags) { + return Err(GlobalVariableError::MissingTypeFlags { + seen: type_flags, + required: required_type_flags, + }); + } + + if is_resource != var.binding.is_some() { + return Err(GlobalVariableError::InvalidBinding); + } + + Ok(()) + } + + pub(super) fn validate_entry_point( + &mut self, + ep: &crate::EntryPoint, + info: &FunctionInfo, + module: &crate::Module, + ) -> Result<(), EntryPointError> { + if ep.early_depth_test.is_some() && ep.stage != crate::ShaderStage::Fragment { + return Err(EntryPointError::UnexpectedEarlyDepthTest); + } + if ep.stage == crate::ShaderStage::Compute { + if ep + .workgroup_size + .iter() + .any(|&s| s == 0 || s > MAX_WORKGROUP_SIZE) + { + return Err(EntryPointError::OutOfRangeWorkgroupSize); + } + } else if ep.workgroup_size != [0; 3] { + return Err(EntryPointError::UnexpectedWorkgroupSize); + } + + self.location_mask.clear(); + for (index, fa) in ep.function.arguments.iter().enumerate() { + let ctx = VaryingContext { + ty: fa.ty, + stage: ep.stage, + output: false, + types: &module.types, + location_mask: &mut self.location_mask, + }; + ctx.validate(fa.binding.as_ref()) + .map_err(|e| EntryPointError::Argument(index as u32, e))?; + } + + self.location_mask.clear(); + if let Some(ref fr) = ep.function.result { + let ctx = VaryingContext { + ty: fr.ty, + stage: ep.stage, + output: true, + types: &module.types, + location_mask: &mut self.location_mask, + }; + ctx.validate(fr.binding.as_ref()) + .map_err(EntryPointError::Result)?; + } + + for bg in self.bind_group_masks.iter_mut() { + bg.clear(); + } + for (var_handle, var) in module.global_variables.iter() { + let usage = info[var_handle]; + if usage.is_empty() { + continue; + } + + let allowed_usage = match var.class { + crate::StorageClass::Function => unreachable!(), + crate::StorageClass::Uniform => GlobalUse::READ | GlobalUse::QUERY, + crate::StorageClass::Storage => storage_usage(var.storage_access), + crate::StorageClass::Handle => match module.types[var.ty].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Storage(_), + .. + } => storage_usage(var.storage_access), + _ => GlobalUse::READ | GlobalUse::QUERY, + }, + crate::StorageClass::Private | crate::StorageClass::WorkGroup => GlobalUse::all(), + crate::StorageClass::PushConstant => GlobalUse::READ, + }; + if !allowed_usage.contains(usage) { + log::warn!("\tUsage error for: {:?}", var); + log::warn!( + "\tAllowed usage: {:?}, requested: {:?}", + allowed_usage, + usage + ); + return Err(EntryPointError::InvalidGlobalUsage(var_handle, usage)); + } + + if let Some(ref bind) = var.binding { + while self.bind_group_masks.len() <= bind.group as usize { + self.bind_group_masks.push(BitSet::new()); + } + if !self.bind_group_masks[bind.group as usize].insert(bind.binding as usize) { + return Err(EntryPointError::BindingCollision(var_handle)); + } + } + } + + self.validate_function(&ep.function, info, module)?; + Ok(()) + } +} diff --git a/src/valid/mod.rs b/src/valid/mod.rs new file mode 100644 index 000000000..03ece2a5a --- /dev/null +++ b/src/valid/mod.rs @@ -0,0 +1,382 @@ +mod analyzer; +mod expression; +mod function; +mod interface; + +use crate::{ + arena::{Arena, Handle}, + proc::Typifier, + FastHashSet, +}; +use bit_set::BitSet; +use thiserror::Error; + +//TODO: analyze the model at the same time as we validate it, +// merge the corresponding matches over expressions and statements. +pub use analyzer::{ + AnalysisError, AnalysisFlags, ExpressionInfo, FunctionInfo, GlobalUse, ModuleInfo, Uniformity, + UniformityRequirements, +}; +pub use expression::ExpressionError; +pub use function::{CallError, FunctionError, LocalVariableError}; +pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; + +bitflags::bitflags! { + #[repr(transparent)] + pub struct TypeFlags: u8 { + /// Can be used for data variables. + const DATA = 0x1; + /// The data type has known size. + const SIZED = 0x2; + /// Can be be used for interfacing between pipeline stages. + const INTERFACE = 0x4; + /// Can be used for host-shareable structures. + const HOST_SHARED = 0x8; + } +} + +#[derive(Debug)] +pub struct Validator { + analysis_flags: AnalysisFlags, + //Note: this is a bit tricky: some of the front-ends as well as backends + // already have to use the typifier, so the work here is redundant in a way. + typifier: Typifier, + type_flags: Vec, + location_mask: BitSet, + bind_group_masks: Vec, + select_cases: FastHashSet, + valid_expression_list: Vec>, + valid_expression_set: BitSet, +} + +#[derive(Clone, Debug, Error)] +pub enum TypeError { + #[error("The {0:?} scalar width {1} is not supported")] + InvalidWidth(crate::ScalarKind, crate::Bytes), + #[error("The base handle {0:?} can not be resolved")] + UnresolvedBase(Handle), + #[error("Expected data type, found {0:?}")] + InvalidData(Handle), + #[error("Structure type {0:?} can not be a block structure")] + InvalidBlockType(Handle), + #[error("Base type {0:?} for the array is invalid")] + InvalidArrayBaseType(Handle), + #[error("The constant {0:?} can not be used for an array size")] + InvalidArraySizeConstant(Handle), + #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] + InvalidDynamicArray(String, Handle), +} + +#[derive(Clone, Debug, Error)] +pub enum ConstantError { + #[error("The type doesn't match the constant")] + InvalidType, + #[error("The component handle {0:?} can not be resolved")] + UnresolvedComponent(Handle), + #[error("The array size handle {0:?} can not be resolved")] + UnresolvedSize(Handle), +} + +#[derive(Clone, Debug, Error)] +pub enum ValidationError { + #[error("Type {handle:?} '{name}' is invalid")] + Type { + handle: Handle, + name: String, + #[source] + error: TypeError, + }, + #[error("Constant {handle:?} '{name}' is invalid")] + Constant { + handle: Handle, + name: String, + #[source] + error: ConstantError, + }, + #[error("Global variable {handle:?} '{name}' is invalid")] + GlobalVariable { + handle: Handle, + name: String, + #[source] + error: GlobalVariableError, + }, + #[error("Function {handle:?} '{name}' is invalid")] + Function { + handle: Handle, + name: String, + #[source] + error: FunctionError, + }, + #[error("Entry point {name} at {stage:?} is invalid")] + EntryPoint { + stage: crate::ShaderStage, + name: String, + #[source] + error: EntryPointError, + }, + #[error(transparent)] + Analysis(#[from] AnalysisError), + #[error("Module is corrupted")] + Corrupted, +} + +impl crate::TypeInner { + fn is_sized(&self) -> bool { + match *self { + Self::Scalar { .. } + | Self::Vector { .. } + | Self::Matrix { .. } + | Self::Array { + size: crate::ArraySize::Constant(_), + .. + } + | Self::Pointer { .. } + | Self::ValuePointer { .. } + | Self::Struct { .. } => true, + Self::Array { .. } | Self::Image { .. } | Self::Sampler { .. } => false, + } + } +} + +impl Validator { + /// Construct a new validator instance. + pub fn new(analysis_flags: AnalysisFlags) -> Self { + Validator { + analysis_flags, + typifier: Typifier::new(), + type_flags: Vec::new(), + location_mask: BitSet::new(), + bind_group_masks: Vec::new(), + select_cases: FastHashSet::default(), + valid_expression_list: Vec::new(), + valid_expression_set: BitSet::new(), + } + } + + fn check_width(kind: crate::ScalarKind, width: crate::Bytes) -> bool { + match kind { + crate::ScalarKind::Bool => width == crate::BOOL_WIDTH, + _ => width == 4, + } + } + + fn validate_type( + &self, + ty: &crate::Type, + handle: Handle, + constants: &Arena, + ) -> Result { + use crate::TypeInner as Ti; + Ok(match ty.inner { + Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { + if !Self::check_width(kind, width) { + return Err(TypeError::InvalidWidth(kind, width)); + } + TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED + } + Ti::Matrix { width, .. } => { + if !Self::check_width(crate::ScalarKind::Float, width) { + return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); + } + TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED + } + Ti::Pointer { base, class: _ } => { + if base >= handle { + return Err(TypeError::UnresolvedBase(base)); + } + TypeFlags::DATA | TypeFlags::SIZED + } + Ti::ValuePointer { + size: _, + kind, + width, + class: _, + } => { + if !Self::check_width(kind, width) { + return Err(TypeError::InvalidWidth(kind, width)); + } + TypeFlags::SIZED //TODO: `DATA`? + } + Ti::Array { + base, + size, + stride: _, + } => { + if base >= handle { + return Err(TypeError::UnresolvedBase(base)); + } + let base_flags = self.type_flags[base.index()]; + if !base_flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { + return Err(TypeError::InvalidArrayBaseType(base)); + } + + let sized_flag = match size { + crate::ArraySize::Constant(const_handle) => { + match constants.try_get(const_handle) { + Some(&crate::Constant { + inner: + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(_), + }, + .. + }) => {} + // Accept a signed integer size to avoid + // requiring an explicit uint + // literal. Type inference should make + // this unnecessary. + Some(&crate::Constant { + inner: + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Sint(_), + }, + .. + }) => {} + other => { + log::warn!("Array size {:?}", other); + return Err(TypeError::InvalidArraySizeConstant(const_handle)); + } + } + TypeFlags::SIZED + } + crate::ArraySize::Dynamic => TypeFlags::empty(), + }; + let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; + TypeFlags::DATA | (base_flags & base_mask) | sized_flag + } + Ti::Struct { block, ref members } => { + let mut flags = TypeFlags::all(); + for (i, member) in members.iter().enumerate() { + if member.ty >= handle { + return Err(TypeError::UnresolvedBase(member.ty)); + } + let base_flags = self.type_flags[member.ty.index()]; + flags &= base_flags; + if !base_flags.contains(TypeFlags::DATA) { + return Err(TypeError::InvalidData(member.ty)); + } + if block && !base_flags.contains(TypeFlags::INTERFACE) { + return Err(TypeError::InvalidBlockType(member.ty)); + } + // only the last field can be unsized + if i + 1 != members.len() && !base_flags.contains(TypeFlags::SIZED) { + let name = member.name.clone().unwrap_or_default(); + return Err(TypeError::InvalidDynamicArray(name, member.ty)); + } + } + //TODO: check the spans + flags + } + Ti::Image { .. } | Ti::Sampler { .. } => TypeFlags::empty(), + }) + } + + fn validate_constant( + &self, + handle: Handle, + constants: &Arena, + types: &Arena, + ) -> Result<(), ConstantError> { + let con = &constants[handle]; + match con.inner { + crate::ConstantInner::Scalar { width, ref value } => { + if !Self::check_width(value.scalar_kind(), width) { + return Err(ConstantError::InvalidType); + } + } + crate::ConstantInner::Composite { ty, ref components } => { + match types[ty].inner { + crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } => { + return Err(ConstantError::InvalidType); + } + crate::TypeInner::Array { + size: crate::ArraySize::Constant(size_handle), + .. + } => { + if handle <= size_handle { + return Err(ConstantError::UnresolvedSize(size_handle)); + } + } + _ => {} //TODO + } + if let Some(&comp) = components.iter().find(|&&comp| handle <= comp) { + return Err(ConstantError::UnresolvedComponent(comp)); + } + } + } + Ok(()) + } + + /// Check the given module to be valid. + pub fn validate(&mut self, module: &crate::Module) -> Result { + self.typifier.clear(); + self.type_flags.clear(); + self.type_flags + .resize(module.types.len(), TypeFlags::empty()); + + let analysis = ModuleInfo::new(module, self.analysis_flags)?; + + for (handle, constant) in module.constants.iter() { + self.validate_constant(handle, &module.constants, &module.types) + .map_err(|error| ValidationError::Constant { + handle, + name: constant.name.clone().unwrap_or_default(), + error, + })?; + } + + // doing after the globals, so that `type_flags` is ready + for (handle, ty) in module.types.iter() { + let ty_flags = self + .validate_type(ty, handle, &module.constants) + .map_err(|error| ValidationError::Type { + handle, + name: ty.name.clone().unwrap_or_default(), + error, + })?; + self.type_flags[handle.index()] = ty_flags; + } + + for (var_handle, var) in module.global_variables.iter() { + self.validate_global_var(var, &module.types) + .map_err(|error| ValidationError::GlobalVariable { + handle: var_handle, + name: var.name.clone().unwrap_or_default(), + error, + })?; + } + + for (handle, fun) in module.functions.iter() { + self.validate_function(fun, &analysis[handle], module) + .map_err(|error| ValidationError::Function { + handle, + name: fun.name.clone().unwrap_or_default(), + error, + })?; + } + + let mut ep_map = FastHashSet::default(); + for (index, ep) in module.entry_points.iter().enumerate() { + if !ep_map.insert((ep.stage, &ep.name)) { + return Err(ValidationError::EntryPoint { + stage: ep.stage, + name: ep.name.clone(), + error: EntryPointError::Conflict, + }); + } + let info = analysis.get_entry_point(index); + self.validate_entry_point(ep, info, module) + .map_err(|error| ValidationError::EntryPoint { + stage: ep.stage, + name: ep.name.clone(), + error, + })?; + } + + Ok(analysis) + } +} diff --git a/tests/parse.rs b/tests/parse.rs index 95c7fc85a..93faa1526 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -23,13 +23,13 @@ fn _check_glsl(name: &str) { defines: Default::default(), }, ) { - Ok(m) => match naga::proc::Validator::new(naga::proc::analyzer::AnalysisFlags::all()) - .validate(&m) - { - Ok(_analysis) => (), - //TODO: panic - Err(e) => log::error!("Unable to validate {}: {:?}", name, e), - }, + Ok(m) => { + match naga::valid::Validator::new(naga::valid::AnalysisFlags::all()).validate(&m) { + Ok(_info) => (), + //TODO: panic + Err(e) => log::error!("Unable to validate {}: {:?}", name, e), + } + } Err(e) => panic!("Unable to parse {}: {:?}", name, e), }; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 8cbcd8751..1b06427aa 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -63,7 +63,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), }; - let analysis = naga::proc::Validator::new(naga::proc::analyzer::AnalysisFlags::all()) + let info = naga::valid::Validator::new(naga::valid::AnalysisFlags::all()) .validate(module) .unwrap(); @@ -78,7 +78,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { } if targets.contains(Targets::ANALYSIS) { let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); - let output = ron::ser::to_string_pretty(&analysis, config).unwrap(); + let output = ron::ser::to_string_pretty(&info, config).unwrap(); with_snapshot_settings(|| { insta::assert_snapshot!(format!("{}.info.ron", name), output); }); @@ -88,27 +88,27 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "spv-out")] { if targets.contains(Targets::SPIRV) { - check_output_spv(module, &analysis, name, ¶ms); + check_output_spv(module, &info, name, ¶ms); } } #[cfg(feature = "msl-out")] { if targets.contains(Targets::METAL) { - check_output_msl(module, &analysis, name, ¶ms); + check_output_msl(module, &info, name, ¶ms); } } #[cfg(feature = "glsl-out")] { if targets.contains(Targets::GLSL) { for ep in module.entry_points.iter() { - check_output_glsl(module, &analysis, name, ep.stage, &ep.name); + check_output_glsl(module, &info, name, ep.stage, &ep.name); } } } #[cfg(feature = "dot-out")] { if targets.contains(Targets::DOT) { - let string = naga::back::dot::write(module, Some(&analysis)).unwrap(); + let string = naga::back::dot::write(module, Some(&info)).unwrap(); with_snapshot_settings(|| { insta::assert_snapshot!(format!("{}.dot", name), string); }); @@ -119,7 +119,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "spv-out")] fn check_output_spv( module: &naga::Module, - analysis: &naga::proc::analyzer::Analysis, + info: &naga::valid::ModuleInfo, name: &str, params: &Parameters, ) { @@ -132,7 +132,7 @@ fn check_output_spv( capabilities: params.spv_capabilities.clone(), }; - let spv = spv::write_vec(module, analysis, &options).unwrap(); + let spv = spv::write_vec(module, info, &options).unwrap(); let dis = rspirv::dr::load_words(spv) .expect("Produced invalid SPIR-V") @@ -145,7 +145,7 @@ fn check_output_spv( #[cfg(feature = "msl-out")] fn check_output_msl( module: &naga::Module, - analysis: &naga::proc::analyzer::Analysis, + info: &naga::valid::ModuleInfo, name: &str, params: &Parameters, ) { @@ -178,7 +178,7 @@ fn check_output_msl( fake_missing_bindings: false, }; - let (msl, _) = msl::write_string(module, analysis, &options).unwrap(); + let (msl, _) = msl::write_string(module, info, &options).unwrap(); with_snapshot_settings(|| { insta::assert_snapshot!(format!("{}.msl", name), msl); @@ -188,7 +188,7 @@ fn check_output_msl( #[cfg(feature = "glsl-out")] fn check_output_glsl( module: &naga::Module, - analysis: &naga::proc::analyzer::Analysis, + info: &naga::valid::ModuleInfo, name: &str, stage: naga::ShaderStage, ep_name: &str, @@ -202,7 +202,7 @@ fn check_output_glsl( }; let mut buffer = Vec::new(); - let mut writer = glsl::Writer::new(&mut buffer, module, analysis, &options).unwrap(); + let mut writer = glsl::Writer::new(&mut buffer, module, info, &options).unwrap(); writer.write().unwrap(); let string = String::from_utf8(buffer).unwrap(); @@ -278,7 +278,7 @@ fn convert_spv(name: &str, targets: Targets) { ) .unwrap(); check_targets(&module, name, targets); - naga::proc::Validator::new(naga::proc::analyzer::AnalysisFlags::all()) + naga::valid::Validator::new(naga::valid::AnalysisFlags::all()) .validate(&module) .unwrap(); } From efcfa37634fc1762d279d256682f6c288fc7fb54 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 20 Mar 2021 01:21:21 -0400 Subject: [PATCH 0601/2212] Implement Index for Layouter --- src/proc/layouter.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 280305bcd..697d119d9 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -1,4 +1,4 @@ -use crate::arena::Arena; +use crate::arena::{Arena, Handle}; use std::{num::NonZeroU32, ops}; pub type Alignment = NonZeroU32; @@ -130,8 +130,11 @@ impl Layouter { }); } } +} - pub fn resolve(&self, handle: crate::Handle) -> TypeLayout { - self.layouts[handle.index()] +impl ops::Index> for Layouter { + type Output = TypeLayout; + fn index(&self, handle: Handle) -> &TypeLayout { + &self.layouts[handle.index()] } } From e3ae5904ba312d10fcc356256b75a418eb0321f8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 20 Mar 2021 22:10:31 -0400 Subject: [PATCH 0602/2212] Move AnalysisFlags into ValidationFlags, add bits for expressions and blocks --- bin/convert.rs | 2 +- src/back/msl/writer.rs | 4 ++-- src/valid/analyzer.rs | 31 ++++++++++++------------------- src/valid/function.rs | 14 ++++++++++---- src/valid/mod.rs | 27 +++++++++++++++++++-------- tests/out/collatz.info.ron.snap | 7 ++----- tests/out/shadow.info.ron.snap | 9 +++------ tests/parse.rs | 2 +- tests/snapshots.rs | 4 ++-- 9 files changed, 52 insertions(+), 48 deletions(-) diff --git a/bin/convert.rs b/bin/convert.rs index 14aa6cdf7..aab31be55 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -173,7 +173,7 @@ fn main() { // validate the IR #[allow(unused_variables)] let info = - match naga::valid::Validator::new(naga::valid::AnalysisFlags::all()).validate(&module) { + match naga::valid::Validator::new(naga::valid::ValidationFlags::all()).validate(&module) { Ok(info) => Some(info), Err(error) => { print_err(error); diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 56f4a695b..5bb2b4369 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1488,7 +1488,7 @@ impl Writer { #[test] fn test_stack_size() { - use crate::valid::AnalysisFlags; + use crate::valid::ValidationFlags; // create a module with at least one expression nested let mut module = crate::Module::default(); let constant = module.constants.append(crate::Constant { @@ -1516,7 +1516,7 @@ fn test_stack_size() { }); let _ = module.functions.append(fun); // analyse the module - let info = ModuleInfo::new(&module, AnalysisFlags::empty()).unwrap(); + let info = ModuleInfo::new(&module, ValidationFlags::empty()).unwrap(); // process the module let mut writer = Writer::new(String::new()); writer.write(&module, &info, &Default::default()).unwrap(); diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 3264dfdf5..520042bba 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -6,6 +6,7 @@ Figures out the following properties: - expression reference counts !*/ +use super::ValidationFlags; use crate::arena::{Arena, Handle}; use std::ops; @@ -152,8 +153,8 @@ impl ExpressionInfo { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct FunctionInfo { - /// Options. - flags: AnalysisFlags, + /// Validation flags. + flags: ValidationFlags, /// Uniformity characteristics. pub uniformity: Uniformity, /// Function may kill the invocation. @@ -555,7 +556,9 @@ impl FunctionInfo { let mut requirements = UniformityRequirements::empty(); for expr in range.clone() { let req = self.expressions[expr.index()].uniformity.requirements; - if self.flags.contains(AnalysisFlags::CONTROL_FLOW_UNIFORMITY) + if self + .flags + .contains(super::ValidationFlags::CONTROL_FLOW_UNIFORMITY) && !req.is_empty() { if let Some(cause) = disruptor { @@ -681,19 +684,9 @@ impl FunctionInfo { } } -bitflags::bitflags! { - /// Analysis flags. - #[cfg_attr(feature = "serialize", derive(serde::Serialize))] - #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] - pub struct AnalysisFlags: u8 { - const CONTROL_FLOW_UNIFORMITY = 0x1; - } -} - #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ModuleInfo { - flags: AnalysisFlags, functions: Vec, entry_points: Vec, } @@ -705,9 +698,10 @@ impl ModuleInfo { &self, fun: &crate::Function, global_var_arena: &Arena, + flags: ValidationFlags, ) -> Result { let mut info = FunctionInfo { - flags: self.flags, + flags, uniformity: Uniformity::new(), may_kill: false, sampling_set: crate::FastHashSet::default(), @@ -733,22 +727,21 @@ impl ModuleInfo { } /// Analyze a module and return the `ModuleInfo`, if successful. - pub fn new(module: &crate::Module, flags: AnalysisFlags) -> Result { + pub fn new(module: &crate::Module, flags: ValidationFlags) -> Result { let mut this = ModuleInfo { - flags, functions: Vec::with_capacity(module.functions.len()), entry_points: Vec::with_capacity(module.entry_points.len()), }; for (fun_handle, fun) in module.functions.iter() { let info = this - .process_function(fun, &module.global_variables) + .process_function(fun, &module.global_variables, flags) .map_err(|source| AnalysisError::Function(fun_handle, source))?; this.functions.push(info); } for ep in module.entry_points.iter() { let info = this - .process_function(&ep.function, &module.global_variables) + .process_function(&ep.function, &module.global_variables, flags) .map_err(|source| AnalysisError::EntryPoint(ep.stage, ep.name.clone(), source))?; this.entry_points.push(info); } @@ -830,7 +823,7 @@ fn uniform_control_flow() { let emit_range_query_access_globals = expressions.range_from(2); let mut info = FunctionInfo { - flags: AnalysisFlags::all(), + flags: ValidationFlags::all(), uniformity: Uniformity::new(), may_kill: false, sampling_set: crate::FastHashSet::default(), diff --git a/src/valid/function.rs b/src/valid/function.rs index 2edf339c7..800c858fc 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -1,4 +1,4 @@ -use super::{analyzer::FunctionInfo, ExpressionError, TypeFlags}; +use super::{analyzer::FunctionInfo, ExpressionError, TypeFlags, ValidationFlags}; use crate::{ arena::{Arena, Handle}, proc::{ResolveContext, TypifyError}, @@ -500,11 +500,17 @@ impl super::Validator { if expr.needs_pre_emit() { self.valid_expression_set.insert(handle.index()); } - if let Err(error) = self.validate_expression(handle, expr, fun, module) { - return Err(FunctionError::Expression { handle, error }); + if !self.flags.contains(ValidationFlags::EXPRESSIONS) { + if let Err(error) = self.validate_expression(handle, expr, fun, module) { + return Err(FunctionError::Expression { handle, error }); + } } } - self.validate_block(&fun.body, &BlockContext::new(fun, module)) + if self.flags.contains(ValidationFlags::BLOCKS) { + self.validate_block(&fun.body, &BlockContext::new(fun, module)) + } else { + Ok(()) + } } } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 03ece2a5a..fac55f2af 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -14,13 +14,24 @@ use thiserror::Error; //TODO: analyze the model at the same time as we validate it, // merge the corresponding matches over expressions and statements. pub use analyzer::{ - AnalysisError, AnalysisFlags, ExpressionInfo, FunctionInfo, GlobalUse, ModuleInfo, Uniformity, + AnalysisError, ExpressionInfo, FunctionInfo, GlobalUse, ModuleInfo, Uniformity, UniformityRequirements, }; pub use expression::ExpressionError; pub use function::{CallError, FunctionError, LocalVariableError}; pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; +bitflags::bitflags! { + /// Validation flags. + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + pub struct ValidationFlags: u8 { + const EXPRESSIONS = 0x1; + const BLOCKS = 0x2; + const CONTROL_FLOW_UNIFORMITY = 0x4; + } +} + bitflags::bitflags! { #[repr(transparent)] pub struct TypeFlags: u8 { @@ -37,7 +48,7 @@ bitflags::bitflags! { #[derive(Debug)] pub struct Validator { - analysis_flags: AnalysisFlags, + flags: ValidationFlags, //Note: this is a bit tricky: some of the front-ends as well as backends // already have to use the typifier, so the work here is redundant in a way. typifier: Typifier, @@ -140,9 +151,9 @@ impl crate::TypeInner { impl Validator { /// Construct a new validator instance. - pub fn new(analysis_flags: AnalysisFlags) -> Self { + pub fn new(flags: ValidationFlags) -> Self { Validator { - analysis_flags, + flags, typifier: Typifier::new(), type_flags: Vec::new(), location_mask: BitSet::new(), @@ -318,7 +329,7 @@ impl Validator { self.type_flags .resize(module.types.len(), TypeFlags::empty()); - let analysis = ModuleInfo::new(module, self.analysis_flags)?; + let mod_info = ModuleInfo::new(module, self.flags)?; for (handle, constant) in module.constants.iter() { self.validate_constant(handle, &module.constants, &module.types) @@ -351,7 +362,7 @@ impl Validator { } for (handle, fun) in module.functions.iter() { - self.validate_function(fun, &analysis[handle], module) + self.validate_function(fun, &mod_info[handle], module) .map_err(|error| ValidationError::Function { handle, name: fun.name.clone().unwrap_or_default(), @@ -368,7 +379,7 @@ impl Validator { error: EntryPointError::Conflict, }); } - let info = analysis.get_entry_point(index); + let info = mod_info.get_entry_point(index); self.validate_entry_point(ep, info, module) .map_err(|error| ValidationError::EntryPoint { stage: ep.stage, @@ -377,6 +388,6 @@ impl Validator { })?; } - Ok(analysis) + Ok(mod_info) } } diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index f3a956feb..28ace1076 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -3,13 +3,10 @@ source: tests/snapshots.rs expression: output --- ( - flags: ( - bits: 1, - ), functions: [ ( flags: ( - bits: 1, + bits: 7, ), uniformity: ( non_uniform_result: Some(5), @@ -281,7 +278,7 @@ expression: output entry_points: [ ( flags: ( - bits: 1, + bits: 7, ), uniformity: ( non_uniform_result: Some(5), diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index d4162fd4c..497d65c3c 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -3,13 +3,10 @@ source: tests/snapshots.rs expression: output --- ( - flags: ( - bits: 1, - ), functions: [ ( flags: ( - bits: 1, + bits: 7, ), uniformity: ( non_uniform_result: Some(44), @@ -762,7 +759,7 @@ expression: output ), ( flags: ( - bits: 1, + bits: 7, ), uniformity: ( non_uniform_result: Some(44), @@ -1987,7 +1984,7 @@ expression: output entry_points: [ ( flags: ( - bits: 1, + bits: 7, ), uniformity: ( non_uniform_result: Some(44), diff --git a/tests/parse.rs b/tests/parse.rs index 93faa1526..ff8eacbc9 100644 --- a/tests/parse.rs +++ b/tests/parse.rs @@ -24,7 +24,7 @@ fn _check_glsl(name: &str) { }, ) { Ok(m) => { - match naga::valid::Validator::new(naga::valid::AnalysisFlags::all()).validate(&m) { + match naga::valid::Validator::new(naga::valid::ValidationFlags::all()).validate(&m) { Ok(_info) => (), //TODO: panic Err(e) => log::error!("Unable to validate {}: {:?}", name, e), diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1b06427aa..ab51a9bc4 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -63,7 +63,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), }; - let info = naga::valid::Validator::new(naga::valid::AnalysisFlags::all()) + let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all()) .validate(module) .unwrap(); @@ -278,7 +278,7 @@ fn convert_spv(name: &str, targets: Targets) { ) .unwrap(); check_targets(&module, name, targets); - naga::valid::Validator::new(naga::valid::AnalysisFlags::all()) + naga::valid::Validator::new(naga::valid::ValidationFlags::all()) .validate(&module) .unwrap(); } From 1ddea0fdbbd6402bfdba33da74db671c61bf97ab Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 21 Mar 2021 01:11:55 -0400 Subject: [PATCH 0603/2212] Validate layouts --- src/valid/function.rs | 5 +- src/valid/interface.rs | 29 ++++-- src/valid/mod.rs | 227 ++++++++++++++++++++++++++++++++++------- 3 files changed, 218 insertions(+), 43 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 800c858fc..09ca6b44e 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -487,7 +487,10 @@ impl super::Validator { } for (index, argument) in fun.arguments.iter().enumerate() { - if !self.type_flags[argument.ty.index()].contains(TypeFlags::DATA) { + if !self.types[argument.ty.index()] + .flags + .contains(TypeFlags::DATA) + { return Err(FunctionError::InvalidArgumentType { index, name: argument.name.clone().unwrap_or_default(), diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 39d5ebdef..2e5b27520 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -1,6 +1,6 @@ use super::{ analyzer::{FunctionInfo, GlobalUse}, - FunctionError, TypeFlags, + Disalignment, FunctionError, TypeFlags, }; use crate::arena::{Arena, Handle}; @@ -26,6 +26,8 @@ pub enum GlobalVariableError { }, #[error("Binding decoration is missing or not applicable")] InvalidBinding, + #[error("Alignment requirements for this storage class are not met by {0:?}")] + Alignment(Handle, #[source] Disalignment), } #[derive(Clone, Debug, thiserror::Error)] @@ -263,11 +265,20 @@ impl super::Validator { types: &Arena, ) -> Result<(), GlobalVariableError> { log::debug!("var {:?}", var); + let type_info = &self.types[var.ty.index()]; + let (allowed_storage_access, required_type_flags, is_resource) = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), crate::StorageClass::Storage => { match types[var.ty].inner { - crate::TypeInner::Struct { .. } => (), + crate::TypeInner::Struct { block: true, .. } => { + if let Err((ty_handle, ref disalignment)) = type_info.storage_layout { + return Err(GlobalVariableError::Alignment( + ty_handle, + disalignment.clone(), + )); + } + } _ => return Err(GlobalVariableError::InvalidType), } ( @@ -278,7 +289,14 @@ impl super::Validator { } crate::StorageClass::Uniform => { match types[var.ty].inner { - crate::TypeInner::Struct { .. } => (), + crate::TypeInner::Struct { block: true, .. } => { + if let Err((ty_handle, ref disalignment)) = type_info.uniform_layout { + return Err(GlobalVariableError::Alignment( + ty_handle, + disalignment.clone(), + )); + } + } _ => return Err(GlobalVariableError::InvalidType), } ( @@ -317,10 +335,9 @@ impl super::Validator { }); } - let type_flags = self.type_flags[var.ty.index()]; - if !type_flags.contains(required_type_flags) { + if !type_info.flags.contains(required_type_flags) { return Err(GlobalVariableError::MissingTypeFlags { - seen: type_flags, + seen: type_info.flags, required: required_type_flags, }); } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index fac55f2af..111040366 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -5,7 +5,7 @@ mod interface; use crate::{ arena::{Arena, Handle}, - proc::Typifier, + proc::{Layouter, Typifier}, FastHashSet, }; use bit_set::BitSet; @@ -46,13 +46,60 @@ bitflags::bitflags! { } } +#[derive(Clone, Debug, Error)] +pub enum Disalignment { + #[error("The array stride {stride} is not a multiple of the required alignment {alignment}")] + ArrayStride { stride: u32, alignment: u32 }, + #[error("The struct size {size}, is not a multiple of the required alignment {alignment}")] + StructSize { size: u32, alignment: u32 }, + #[error("The struct member[{index}] offset {offset} is not a multiple of the required alignment {alignment}")] + Member { + index: u32, + offset: u32, + alignment: u32, + }, + #[error("The struct member[{index}] is not statically sized")] + UnsizedMember { index: u32 }, +} + +// Only makes sense if `flags.contains(HOST_SHARED)` +type LayoutCompatibility = Result<(), (Handle, Disalignment)>; + +// For the uniform buffer alignment, array strides and struct sizes must be multiples of 16. +const UNIFORM_LAYOUT_ALIGNMENT_MASK: u32 = 0xF; + +#[derive(Clone, Debug)] +struct TypeInfo { + flags: TypeFlags, + uniform_layout: LayoutCompatibility, + storage_layout: LayoutCompatibility, +} + +impl TypeInfo { + fn new() -> Self { + TypeInfo { + flags: TypeFlags::empty(), + uniform_layout: Ok(()), + storage_layout: Ok(()), + } + } + + fn from_flags(flags: TypeFlags) -> Self { + TypeInfo { + flags, + uniform_layout: Ok(()), + storage_layout: Ok(()), + } + } +} + #[derive(Debug)] pub struct Validator { flags: ValidationFlags, //Note: this is a bit tricky: some of the front-ends as well as backends // already have to use the typifier, so the work here is redundant in a way. typifier: Typifier, - type_flags: Vec, + types: Vec, location_mask: BitSet, bind_group_masks: Vec, select_cases: FastHashSet, @@ -74,8 +121,20 @@ pub enum TypeError { InvalidArrayBaseType(Handle), #[error("The constant {0:?} can not be used for an array size")] InvalidArraySizeConstant(Handle), + #[error( + "Array stride {stride} is not a multiple of the base element alignment {base_alignment}" + )] + UnalignedArrayStride { stride: u32, base_alignment: u32 }, + #[error("Array stride {stride} is smaller than the base element size {base_size}")] + InsufficientArrayStride { stride: u32, base_size: u32 }, #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] InvalidDynamicArray(String, Handle), + #[error("Structure member[{index}] size {size} is not a sufficient to hold {base_size}")] + InsufficientMemberSize { + index: u32, + size: u32, + base_size: u32, + }, } #[derive(Clone, Debug, Error)] @@ -155,7 +214,7 @@ impl Validator { Validator { flags, typifier: Typifier::new(), - type_flags: Vec::new(), + types: Vec::new(), location_mask: BitSet::new(), bind_group_masks: Vec::new(), select_cases: FastHashSet::default(), @@ -176,26 +235,37 @@ impl Validator { ty: &crate::Type, handle: Handle, constants: &Arena, - ) -> Result { + layouter: &Layouter, + ) -> Result { use crate::TypeInner as Ti; Ok(match ty.inner { Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { if !Self::check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } - TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED + TypeInfo::from_flags( + TypeFlags::DATA + | TypeFlags::SIZED + | TypeFlags::INTERFACE + | TypeFlags::HOST_SHARED, + ) } Ti::Matrix { width, .. } => { if !Self::check_width(crate::ScalarKind::Float, width) { return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); } - TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED + TypeInfo::from_flags( + TypeFlags::DATA + | TypeFlags::SIZED + | TypeFlags::INTERFACE + | TypeFlags::HOST_SHARED, + ) } Ti::Pointer { base, class: _ } => { if base >= handle { return Err(TypeError::UnresolvedBase(base)); } - TypeFlags::DATA | TypeFlags::SIZED + TypeInfo::from_flags(TypeFlags::DATA | TypeFlags::SIZED) } Ti::ValuePointer { size: _, @@ -206,22 +276,34 @@ impl Validator { if !Self::check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } - TypeFlags::SIZED //TODO: `DATA`? + TypeInfo::from_flags(TypeFlags::SIZED) } - Ti::Array { - base, - size, - stride: _, - } => { + Ti::Array { base, size, stride } => { if base >= handle { return Err(TypeError::UnresolvedBase(base)); } - let base_flags = self.type_flags[base.index()]; - if !base_flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { + let base_info = &self.types[base.index()]; + if !base_info.flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { return Err(TypeError::InvalidArrayBaseType(base)); } - let sized_flag = match size { + let base_layout = &layouter[base]; + if let Some(stride) = stride { + if stride.get() % base_layout.alignment.get() != 0 { + return Err(TypeError::UnalignedArrayStride { + stride: stride.get(), + base_alignment: base_layout.alignment.get(), + }); + } + if stride.get() < base_layout.size { + return Err(TypeError::InsufficientArrayStride { + stride: stride.get(), + base_size: base_layout.size, + }); + } + } + + let (sized_flag, uniform_layout) = match size { crate::ArraySize::Constant(const_handle) => { match constants.try_get(const_handle) { Some(&crate::Constant { @@ -249,37 +331,109 @@ impl Validator { return Err(TypeError::InvalidArraySizeConstant(const_handle)); } } - TypeFlags::SIZED + + let effective_alignment = match stride { + Some(stride) => stride.get(), + None => base_layout.size, + }; + let uniform_layout = + if effective_alignment & UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { + base_info.uniform_layout.clone() + } else { + Err(( + handle, + Disalignment::ArrayStride { + stride: effective_alignment, + alignment: effective_alignment, + }, + )) + }; + (TypeFlags::SIZED, uniform_layout) } - crate::ArraySize::Dynamic => TypeFlags::empty(), + //Note: this will be detected at the struct level + crate::ArraySize::Dynamic => (TypeFlags::empty(), Ok(())), }; + let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; - TypeFlags::DATA | (base_flags & base_mask) | sized_flag + TypeInfo { + flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag, + uniform_layout, + storage_layout: base_info.storage_layout.clone(), + } } Ti::Struct { block, ref members } => { let mut flags = TypeFlags::all(); + let mut uniform_layout = Ok(()); + let mut storage_layout = Ok(()); + let mut offset = 0; for (i, member) in members.iter().enumerate() { if member.ty >= handle { return Err(TypeError::UnresolvedBase(member.ty)); } - let base_flags = self.type_flags[member.ty.index()]; - flags &= base_flags; - if !base_flags.contains(TypeFlags::DATA) { + let base_info = &self.types[member.ty.index()]; + flags &= base_info.flags; + if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); } - if block && !base_flags.contains(TypeFlags::INTERFACE) { + if block && !base_info.flags.contains(TypeFlags::INTERFACE) { return Err(TypeError::InvalidBlockType(member.ty)); } - // only the last field can be unsized - if i + 1 != members.len() && !base_flags.contains(TypeFlags::SIZED) { - let name = member.name.clone().unwrap_or_default(); - return Err(TypeError::InvalidDynamicArray(name, member.ty)); + + let base_layout = &layouter[member.ty]; + let (range, _alignment) = layouter.member_placement(offset, member); + if range.end - range.start < base_layout.size { + return Err(TypeError::InsufficientMemberSize { + index: i as u32, + size: range.end - range.start, + base_size: base_layout.size, + }); } + if range.start % base_layout.alignment.get() != 0 { + let result = Err(( + handle, + Disalignment::Member { + index: i as u32, + offset: range.start, + alignment: base_layout.alignment.get(), + }, + )); + uniform_layout = uniform_layout.or_else(|_| result.clone()); + storage_layout = storage_layout.or(result); + } + offset = range.end; + + // only the last field can be unsized + if !base_info.flags.contains(TypeFlags::SIZED) { + if i + 1 != members.len() { + let name = member.name.clone().unwrap_or_default(); + return Err(TypeError::InvalidDynamicArray(name, member.ty)); + } + if uniform_layout.is_ok() { + uniform_layout = + Err((handle, Disalignment::UnsizedMember { index: i as u32 })); + } + } + + uniform_layout = uniform_layout.or_else(|_| base_info.uniform_layout.clone()); + storage_layout = storage_layout.or_else(|_| base_info.storage_layout.clone()); + } + + if uniform_layout.is_ok() && offset % UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { + uniform_layout = Err(( + handle, + Disalignment::StructSize { + size: offset, + alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK, + }, + )); + } + TypeInfo { + flags, + uniform_layout, + storage_layout, } - //TODO: check the spans - flags } - Ti::Image { .. } | Ti::Sampler { .. } => TypeFlags::empty(), + Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::from_flags(TypeFlags::empty()), }) } @@ -325,12 +479,13 @@ impl Validator { /// Check the given module to be valid. pub fn validate(&mut self, module: &crate::Module) -> Result { self.typifier.clear(); - self.type_flags.clear(); - self.type_flags - .resize(module.types.len(), TypeFlags::empty()); + self.types.clear(); + self.types.resize(module.types.len(), TypeInfo::new()); let mod_info = ModuleInfo::new(module, self.flags)?; + let layouter = Layouter::new(&module.types, &module.constants); + for (handle, constant) in module.constants.iter() { self.validate_constant(handle, &module.constants, &module.types) .map_err(|error| ValidationError::Constant { @@ -342,14 +497,14 @@ impl Validator { // doing after the globals, so that `type_flags` is ready for (handle, ty) in module.types.iter() { - let ty_flags = self - .validate_type(ty, handle, &module.constants) + let ty_info = self + .validate_type(ty, handle, &module.constants, &layouter) .map_err(|error| ValidationError::Type { handle, name: ty.name.clone().unwrap_or_default(), error, })?; - self.type_flags[handle.index()] = ty_flags; + self.types[handle.index()] = ty_info; } for (var_handle, var) in module.global_variables.iter() { From 1b3e7294fd839f46097c97e56a21caed0578f58b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 21 Mar 2021 01:22:25 -0400 Subject: [PATCH 0604/2212] Move type validation into a sub-module --- src/valid/mod.rs | 318 +--------------------------------------------- src/valid/type.rs | 317 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 323 insertions(+), 312 deletions(-) create mode 100644 src/valid/type.rs diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 111040366..3d5092e76 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -2,6 +2,7 @@ mod analyzer; mod expression; mod function; mod interface; +mod r#type; use crate::{ arena::{Arena, Handle}, @@ -9,7 +10,6 @@ use crate::{ FastHashSet, }; use bit_set::BitSet; -use thiserror::Error; //TODO: analyze the model at the same time as we validate it, // merge the corresponding matches over expressions and statements. @@ -20,6 +20,7 @@ pub use analyzer::{ pub use expression::ExpressionError; pub use function::{CallError, FunctionError, LocalVariableError}; pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; +pub use r#type::{Disalignment, TypeError, TypeFlags}; bitflags::bitflags! { /// Validation flags. @@ -32,74 +33,13 @@ bitflags::bitflags! { } } -bitflags::bitflags! { - #[repr(transparent)] - pub struct TypeFlags: u8 { - /// Can be used for data variables. - const DATA = 0x1; - /// The data type has known size. - const SIZED = 0x2; - /// Can be be used for interfacing between pipeline stages. - const INTERFACE = 0x4; - /// Can be used for host-shareable structures. - const HOST_SHARED = 0x8; - } -} - -#[derive(Clone, Debug, Error)] -pub enum Disalignment { - #[error("The array stride {stride} is not a multiple of the required alignment {alignment}")] - ArrayStride { stride: u32, alignment: u32 }, - #[error("The struct size {size}, is not a multiple of the required alignment {alignment}")] - StructSize { size: u32, alignment: u32 }, - #[error("The struct member[{index}] offset {offset} is not a multiple of the required alignment {alignment}")] - Member { - index: u32, - offset: u32, - alignment: u32, - }, - #[error("The struct member[{index}] is not statically sized")] - UnsizedMember { index: u32 }, -} - -// Only makes sense if `flags.contains(HOST_SHARED)` -type LayoutCompatibility = Result<(), (Handle, Disalignment)>; - -// For the uniform buffer alignment, array strides and struct sizes must be multiples of 16. -const UNIFORM_LAYOUT_ALIGNMENT_MASK: u32 = 0xF; - -#[derive(Clone, Debug)] -struct TypeInfo { - flags: TypeFlags, - uniform_layout: LayoutCompatibility, - storage_layout: LayoutCompatibility, -} - -impl TypeInfo { - fn new() -> Self { - TypeInfo { - flags: TypeFlags::empty(), - uniform_layout: Ok(()), - storage_layout: Ok(()), - } - } - - fn from_flags(flags: TypeFlags) -> Self { - TypeInfo { - flags, - uniform_layout: Ok(()), - storage_layout: Ok(()), - } - } -} - #[derive(Debug)] pub struct Validator { flags: ValidationFlags, //Note: this is a bit tricky: some of the front-ends as well as backends // already have to use the typifier, so the work here is redundant in a way. typifier: Typifier, - types: Vec, + types: Vec, location_mask: BitSet, bind_group_masks: Vec, select_cases: FastHashSet, @@ -107,37 +47,7 @@ pub struct Validator { valid_expression_set: BitSet, } -#[derive(Clone, Debug, Error)] -pub enum TypeError { - #[error("The {0:?} scalar width {1} is not supported")] - InvalidWidth(crate::ScalarKind, crate::Bytes), - #[error("The base handle {0:?} can not be resolved")] - UnresolvedBase(Handle), - #[error("Expected data type, found {0:?}")] - InvalidData(Handle), - #[error("Structure type {0:?} can not be a block structure")] - InvalidBlockType(Handle), - #[error("Base type {0:?} for the array is invalid")] - InvalidArrayBaseType(Handle), - #[error("The constant {0:?} can not be used for an array size")] - InvalidArraySizeConstant(Handle), - #[error( - "Array stride {stride} is not a multiple of the base element alignment {base_alignment}" - )] - UnalignedArrayStride { stride: u32, base_alignment: u32 }, - #[error("Array stride {stride} is smaller than the base element size {base_size}")] - InsufficientArrayStride { stride: u32, base_size: u32 }, - #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] - InvalidDynamicArray(String, Handle), - #[error("Structure member[{index}] size {size} is not a sufficient to hold {base_size}")] - InsufficientMemberSize { - index: u32, - size: u32, - base_size: u32, - }, -} - -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum ConstantError { #[error("The type doesn't match the constant")] InvalidType, @@ -147,7 +57,7 @@ pub enum ConstantError { UnresolvedSize(Handle), } -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum ValidationError { #[error("Type {handle:?} '{name}' is invalid")] Type { @@ -223,220 +133,6 @@ impl Validator { } } - fn check_width(kind: crate::ScalarKind, width: crate::Bytes) -> bool { - match kind { - crate::ScalarKind::Bool => width == crate::BOOL_WIDTH, - _ => width == 4, - } - } - - fn validate_type( - &self, - ty: &crate::Type, - handle: Handle, - constants: &Arena, - layouter: &Layouter, - ) -> Result { - use crate::TypeInner as Ti; - Ok(match ty.inner { - Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { - if !Self::check_width(kind, width) { - return Err(TypeError::InvalidWidth(kind, width)); - } - TypeInfo::from_flags( - TypeFlags::DATA - | TypeFlags::SIZED - | TypeFlags::INTERFACE - | TypeFlags::HOST_SHARED, - ) - } - Ti::Matrix { width, .. } => { - if !Self::check_width(crate::ScalarKind::Float, width) { - return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); - } - TypeInfo::from_flags( - TypeFlags::DATA - | TypeFlags::SIZED - | TypeFlags::INTERFACE - | TypeFlags::HOST_SHARED, - ) - } - Ti::Pointer { base, class: _ } => { - if base >= handle { - return Err(TypeError::UnresolvedBase(base)); - } - TypeInfo::from_flags(TypeFlags::DATA | TypeFlags::SIZED) - } - Ti::ValuePointer { - size: _, - kind, - width, - class: _, - } => { - if !Self::check_width(kind, width) { - return Err(TypeError::InvalidWidth(kind, width)); - } - TypeInfo::from_flags(TypeFlags::SIZED) - } - Ti::Array { base, size, stride } => { - if base >= handle { - return Err(TypeError::UnresolvedBase(base)); - } - let base_info = &self.types[base.index()]; - if !base_info.flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { - return Err(TypeError::InvalidArrayBaseType(base)); - } - - let base_layout = &layouter[base]; - if let Some(stride) = stride { - if stride.get() % base_layout.alignment.get() != 0 { - return Err(TypeError::UnalignedArrayStride { - stride: stride.get(), - base_alignment: base_layout.alignment.get(), - }); - } - if stride.get() < base_layout.size { - return Err(TypeError::InsufficientArrayStride { - stride: stride.get(), - base_size: base_layout.size, - }); - } - } - - let (sized_flag, uniform_layout) = match size { - crate::ArraySize::Constant(const_handle) => { - match constants.try_get(const_handle) { - Some(&crate::Constant { - inner: - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(_), - }, - .. - }) => {} - // Accept a signed integer size to avoid - // requiring an explicit uint - // literal. Type inference should make - // this unnecessary. - Some(&crate::Constant { - inner: - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Sint(_), - }, - .. - }) => {} - other => { - log::warn!("Array size {:?}", other); - return Err(TypeError::InvalidArraySizeConstant(const_handle)); - } - } - - let effective_alignment = match stride { - Some(stride) => stride.get(), - None => base_layout.size, - }; - let uniform_layout = - if effective_alignment & UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { - base_info.uniform_layout.clone() - } else { - Err(( - handle, - Disalignment::ArrayStride { - stride: effective_alignment, - alignment: effective_alignment, - }, - )) - }; - (TypeFlags::SIZED, uniform_layout) - } - //Note: this will be detected at the struct level - crate::ArraySize::Dynamic => (TypeFlags::empty(), Ok(())), - }; - - let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; - TypeInfo { - flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag, - uniform_layout, - storage_layout: base_info.storage_layout.clone(), - } - } - Ti::Struct { block, ref members } => { - let mut flags = TypeFlags::all(); - let mut uniform_layout = Ok(()); - let mut storage_layout = Ok(()); - let mut offset = 0; - for (i, member) in members.iter().enumerate() { - if member.ty >= handle { - return Err(TypeError::UnresolvedBase(member.ty)); - } - let base_info = &self.types[member.ty.index()]; - flags &= base_info.flags; - if !base_info.flags.contains(TypeFlags::DATA) { - return Err(TypeError::InvalidData(member.ty)); - } - if block && !base_info.flags.contains(TypeFlags::INTERFACE) { - return Err(TypeError::InvalidBlockType(member.ty)); - } - - let base_layout = &layouter[member.ty]; - let (range, _alignment) = layouter.member_placement(offset, member); - if range.end - range.start < base_layout.size { - return Err(TypeError::InsufficientMemberSize { - index: i as u32, - size: range.end - range.start, - base_size: base_layout.size, - }); - } - if range.start % base_layout.alignment.get() != 0 { - let result = Err(( - handle, - Disalignment::Member { - index: i as u32, - offset: range.start, - alignment: base_layout.alignment.get(), - }, - )); - uniform_layout = uniform_layout.or_else(|_| result.clone()); - storage_layout = storage_layout.or(result); - } - offset = range.end; - - // only the last field can be unsized - if !base_info.flags.contains(TypeFlags::SIZED) { - if i + 1 != members.len() { - let name = member.name.clone().unwrap_or_default(); - return Err(TypeError::InvalidDynamicArray(name, member.ty)); - } - if uniform_layout.is_ok() { - uniform_layout = - Err((handle, Disalignment::UnsizedMember { index: i as u32 })); - } - } - - uniform_layout = uniform_layout.or_else(|_| base_info.uniform_layout.clone()); - storage_layout = storage_layout.or_else(|_| base_info.storage_layout.clone()); - } - - if uniform_layout.is_ok() && offset % UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { - uniform_layout = Err(( - handle, - Disalignment::StructSize { - size: offset, - alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK, - }, - )); - } - TypeInfo { - flags, - uniform_layout, - storage_layout, - } - } - Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::from_flags(TypeFlags::empty()), - }) - } - fn validate_constant( &self, handle: Handle, @@ -478,9 +174,7 @@ impl Validator { /// Check the given module to be valid. pub fn validate(&mut self, module: &crate::Module) -> Result { - self.typifier.clear(); - self.types.clear(); - self.types.resize(module.types.len(), TypeInfo::new()); + self.reset_types(module.types.len()); let mod_info = ModuleInfo::new(module, self.flags)?; diff --git a/src/valid/type.rs b/src/valid/type.rs new file mode 100644 index 000000000..b1a6b7b13 --- /dev/null +++ b/src/valid/type.rs @@ -0,0 +1,317 @@ +use crate::{ + arena::{Arena, Handle}, + proc::Layouter, +}; + +bitflags::bitflags! { + #[repr(transparent)] + pub struct TypeFlags: u8 { + /// Can be used for data variables. + const DATA = 0x1; + /// The data type has known size. + const SIZED = 0x2; + /// Can be be used for interfacing between pipeline stages. + const INTERFACE = 0x4; + /// Can be used for host-shareable structures. + const HOST_SHARED = 0x8; + } +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum Disalignment { + #[error("The array stride {stride} is not a multiple of the required alignment {alignment}")] + ArrayStride { stride: u32, alignment: u32 }, + #[error("The struct size {size}, is not a multiple of the required alignment {alignment}")] + StructSize { size: u32, alignment: u32 }, + #[error("The struct member[{index}] offset {offset} is not a multiple of the required alignment {alignment}")] + Member { + index: u32, + offset: u32, + alignment: u32, + }, + #[error("The struct member[{index}] is not statically sized")] + UnsizedMember { index: u32 }, +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum TypeError { + #[error("The {0:?} scalar width {1} is not supported")] + InvalidWidth(crate::ScalarKind, crate::Bytes), + #[error("The base handle {0:?} can not be resolved")] + UnresolvedBase(Handle), + #[error("Expected data type, found {0:?}")] + InvalidData(Handle), + #[error("Structure type {0:?} can not be a block structure")] + InvalidBlockType(Handle), + #[error("Base type {0:?} for the array is invalid")] + InvalidArrayBaseType(Handle), + #[error("The constant {0:?} can not be used for an array size")] + InvalidArraySizeConstant(Handle), + #[error( + "Array stride {stride} is not a multiple of the base element alignment {base_alignment}" + )] + UnalignedArrayStride { stride: u32, base_alignment: u32 }, + #[error("Array stride {stride} is smaller than the base element size {base_size}")] + InsufficientArrayStride { stride: u32, base_size: u32 }, + #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] + InvalidDynamicArray(String, Handle), + #[error("Structure member[{index}] size {size} is not a sufficient to hold {base_size}")] + InsufficientMemberSize { + index: u32, + size: u32, + base_size: u32, + }, +} + +// Only makes sense if `flags.contains(HOST_SHARED)` +type LayoutCompatibility = Result<(), (Handle, Disalignment)>; + +// For the uniform buffer alignment, array strides and struct sizes must be multiples of 16. +const UNIFORM_LAYOUT_ALIGNMENT_MASK: u32 = 0xF; + +#[derive(Clone, Debug)] +pub(super) struct TypeInfo { + pub flags: TypeFlags, + pub uniform_layout: LayoutCompatibility, + pub storage_layout: LayoutCompatibility, +} + +impl TypeInfo { + fn new() -> Self { + TypeInfo { + flags: TypeFlags::empty(), + uniform_layout: Ok(()), + storage_layout: Ok(()), + } + } + + fn from_flags(flags: TypeFlags) -> Self { + TypeInfo { + flags, + uniform_layout: Ok(()), + storage_layout: Ok(()), + } + } +} + +impl super::Validator { + pub(super) fn check_width(kind: crate::ScalarKind, width: crate::Bytes) -> bool { + match kind { + crate::ScalarKind::Bool => width == crate::BOOL_WIDTH, + _ => width == 4, + } + } + + pub(super) fn reset_types(&mut self, size: usize) { + self.typifier.clear(); + self.types.clear(); + self.types.resize(size, TypeInfo::new()); + } + + pub(super) fn validate_type( + &self, + ty: &crate::Type, + handle: Handle, + constants: &Arena, + layouter: &Layouter, + ) -> Result { + use crate::TypeInner as Ti; + Ok(match ty.inner { + Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { + if !Self::check_width(kind, width) { + return Err(TypeError::InvalidWidth(kind, width)); + } + TypeInfo::from_flags( + TypeFlags::DATA + | TypeFlags::SIZED + | TypeFlags::INTERFACE + | TypeFlags::HOST_SHARED, + ) + } + Ti::Matrix { width, .. } => { + if !Self::check_width(crate::ScalarKind::Float, width) { + return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); + } + TypeInfo::from_flags( + TypeFlags::DATA + | TypeFlags::SIZED + | TypeFlags::INTERFACE + | TypeFlags::HOST_SHARED, + ) + } + Ti::Pointer { base, class: _ } => { + if base >= handle { + return Err(TypeError::UnresolvedBase(base)); + } + TypeInfo::from_flags(TypeFlags::DATA | TypeFlags::SIZED) + } + Ti::ValuePointer { + size: _, + kind, + width, + class: _, + } => { + if !Self::check_width(kind, width) { + return Err(TypeError::InvalidWidth(kind, width)); + } + TypeInfo::from_flags(TypeFlags::SIZED) + } + Ti::Array { base, size, stride } => { + if base >= handle { + return Err(TypeError::UnresolvedBase(base)); + } + let base_info = &self.types[base.index()]; + if !base_info.flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { + return Err(TypeError::InvalidArrayBaseType(base)); + } + + let base_layout = &layouter[base]; + if let Some(stride) = stride { + if stride.get() % base_layout.alignment.get() != 0 { + return Err(TypeError::UnalignedArrayStride { + stride: stride.get(), + base_alignment: base_layout.alignment.get(), + }); + } + if stride.get() < base_layout.size { + return Err(TypeError::InsufficientArrayStride { + stride: stride.get(), + base_size: base_layout.size, + }); + } + } + + let (sized_flag, uniform_layout) = match size { + crate::ArraySize::Constant(const_handle) => { + match constants.try_get(const_handle) { + Some(&crate::Constant { + inner: + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(_), + }, + .. + }) => {} + // Accept a signed integer size to avoid + // requiring an explicit uint + // literal. Type inference should make + // this unnecessary. + Some(&crate::Constant { + inner: + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Sint(_), + }, + .. + }) => {} + other => { + log::warn!("Array size {:?}", other); + return Err(TypeError::InvalidArraySizeConstant(const_handle)); + } + } + + let effective_alignment = match stride { + Some(stride) => stride.get(), + None => base_layout.size, + }; + let uniform_layout = + if effective_alignment & UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { + base_info.uniform_layout.clone() + } else { + Err(( + handle, + Disalignment::ArrayStride { + stride: effective_alignment, + alignment: effective_alignment, + }, + )) + }; + (TypeFlags::SIZED, uniform_layout) + } + //Note: this will be detected at the struct level + crate::ArraySize::Dynamic => (TypeFlags::empty(), Ok(())), + }; + + let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; + TypeInfo { + flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag, + uniform_layout, + storage_layout: base_info.storage_layout.clone(), + } + } + Ti::Struct { block, ref members } => { + let mut flags = TypeFlags::all(); + let mut uniform_layout = Ok(()); + let mut storage_layout = Ok(()); + let mut offset = 0; + for (i, member) in members.iter().enumerate() { + if member.ty >= handle { + return Err(TypeError::UnresolvedBase(member.ty)); + } + let base_info = &self.types[member.ty.index()]; + flags &= base_info.flags; + if !base_info.flags.contains(TypeFlags::DATA) { + return Err(TypeError::InvalidData(member.ty)); + } + if block && !base_info.flags.contains(TypeFlags::INTERFACE) { + return Err(TypeError::InvalidBlockType(member.ty)); + } + + let base_layout = &layouter[member.ty]; + let (range, _alignment) = layouter.member_placement(offset, member); + if range.end - range.start < base_layout.size { + return Err(TypeError::InsufficientMemberSize { + index: i as u32, + size: range.end - range.start, + base_size: base_layout.size, + }); + } + if range.start % base_layout.alignment.get() != 0 { + let result = Err(( + handle, + Disalignment::Member { + index: i as u32, + offset: range.start, + alignment: base_layout.alignment.get(), + }, + )); + uniform_layout = uniform_layout.or_else(|_| result.clone()); + storage_layout = storage_layout.or(result); + } + offset = range.end; + + // only the last field can be unsized + if !base_info.flags.contains(TypeFlags::SIZED) { + if i + 1 != members.len() { + let name = member.name.clone().unwrap_or_default(); + return Err(TypeError::InvalidDynamicArray(name, member.ty)); + } + if uniform_layout.is_ok() { + uniform_layout = + Err((handle, Disalignment::UnsizedMember { index: i as u32 })); + } + } + + uniform_layout = uniform_layout.or_else(|_| base_info.uniform_layout.clone()); + storage_layout = storage_layout.or_else(|_| base_info.storage_layout.clone()); + } + + if uniform_layout.is_ok() && offset % UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { + uniform_layout = Err(( + handle, + Disalignment::StructSize { + size: offset, + alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK, + }, + )); + } + TypeInfo { + flags, + uniform_layout, + storage_layout, + } + } + Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::from_flags(TypeFlags::empty()), + }) + } +} From 1d3f2bbdb1c27b167a584908fb562e7742650d65 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 22 Mar 2021 00:45:11 -0400 Subject: [PATCH 0605/2212] Merge FunctionAnalysisError into FunctionError --- src/back/msl/writer.rs | 4 +- src/valid/analyzer.rs | 99 +++++++++-------------------------------- src/valid/expression.rs | 1 + src/valid/function.rs | 28 +++++++++--- src/valid/interface.rs | 11 ++--- src/valid/mod.rs | 56 ++++++++++++++--------- 6 files changed, 88 insertions(+), 111 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 5bb2b4369..f9c8e7eb1 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1516,7 +1516,9 @@ fn test_stack_size() { }); let _ = module.functions.append(fun); // analyse the module - let info = ModuleInfo::new(&module, ValidationFlags::empty()).unwrap(); + let info = crate::valid::Validator::new(ValidationFlags::empty()) + .validate(&module) + .unwrap(); // process the module let mut writer = Writer::new(String::new()); writer.write(&module, &info, &Default::default()).unwrap(); diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 520042bba..20da97ad8 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -6,7 +6,7 @@ Figures out the following properties: - expression reference counts !*/ -use super::ValidationFlags; +use super::{CallError, FunctionError, ModuleInfo, ValidationFlags}; use crate::arena::{Arena, Handle}; use std::ops; @@ -216,32 +216,6 @@ pub enum UniformityDisruptor { Discard, } -#[derive(Clone, Debug, thiserror::Error)] -#[cfg_attr(test, derive(PartialEq))] -pub enum FunctionAnalysisError { - #[error("Expression {0:?} is not a global variable!")] - ExpectedGlobalVariable(crate::Expression), - #[error("Called function {0:?} that hasn't been declared in the IR yet")] - ForwardCall(Handle), - #[error( - "Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}" - )] - NonUniformControlFlow( - UniformityRequirements, - Handle, - UniformityDisruptor, - ), -} - -#[derive(Clone, Debug, thiserror::Error)] -#[cfg_attr(test, derive(PartialEq))] -pub enum AnalysisError { - #[error("Function {0:?} analysis failed")] - Function(Handle, #[source] FunctionAnalysisError), - #[error("Entry point {0:?}/'{1}' function analysis failed")] - EntryPoint(crate::ShaderStage, String, #[source] FunctionAnalysisError), -} - impl FunctionInfo { /// Adds a value-type reference to an expression. #[must_use] @@ -314,7 +288,7 @@ impl FunctionInfo { arguments: &[crate::FunctionArgument], global_var_arena: &Arena, other_functions: &[FunctionInfo], - ) -> Result<(), FunctionAnalysisError> { + ) -> Result<(), FunctionError> { use crate::{Expression as E, SampleLevel as Sl}; let mut assignable_global = None; @@ -404,17 +378,13 @@ impl FunctionInfo { image: match expression_arena[image] { crate::Expression::GlobalVariable(var) => var, ref other => { - return Err(FunctionAnalysisError::ExpectedGlobalVariable( - other.clone(), - )) + return Err(FunctionError::ExpectedGlobalVariable(other.clone())) } }, sampler: match expression_arena[sampler] { crate::Expression::GlobalVariable(var) => var, ref other => { - return Err(FunctionAnalysisError::ExpectedGlobalVariable( - other.clone(), - )) + return Err(FunctionError::ExpectedGlobalVariable(other.clone())) } }, }); @@ -512,9 +482,13 @@ impl FunctionInfo { requirements: UniformityRequirements::empty(), }, E::Call(function) => { - let fun = other_functions - .get(function.index()) - .ok_or(FunctionAnalysisError::ForwardCall(function))?; + let fun = + other_functions + .get(function.index()) + .ok_or(FunctionError::InvalidCall { + function, + error: CallError::ForwardDeclaredFunction, + })?; self.process_call(fun).result } E::ArrayLength(expr) => Uniformity { @@ -546,7 +520,7 @@ impl FunctionInfo { statements: &[crate::Statement], other_functions: &[FunctionInfo], mut disruptor: Option, - ) -> Result { + ) -> Result { use crate::Statement as S; let mut combined_uniformity = FunctionUniformity::new(); @@ -562,9 +536,7 @@ impl FunctionInfo { && !req.is_empty() { if let Some(cause) = disruptor { - return Err(FunctionAnalysisError::NonUniformControlFlow( - req, expr, cause, - )); + return Err(FunctionError::NonUniformControlFlow(req, expr, cause)); } } requirements |= req; @@ -670,9 +642,12 @@ impl FunctionInfo { for &argument in arguments { let _ = self.add_ref(argument); } - let info = other_functions - .get(function.index()) - .ok_or(FunctionAnalysisError::ForwardCall(function))?; + let info = other_functions.get(function.index()).ok_or( + FunctionError::InvalidCall { + function, + error: CallError::ForwardDeclaredFunction, + }, + )?; self.process_call(info) } }; @@ -684,22 +659,15 @@ impl FunctionInfo { } } -#[cfg_attr(feature = "serialize", derive(serde::Serialize))] -#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] -pub struct ModuleInfo { - functions: Vec, - entry_points: Vec, -} - impl ModuleInfo { /// Builds the `FunctionInfo` based on the function, and validates the /// uniform control flow if required by the expressions of this function. - fn process_function( + pub(super) fn process_function( &self, fun: &crate::Function, global_var_arena: &Arena, flags: ValidationFlags, - ) -> Result { + ) -> Result { let mut info = FunctionInfo { flags, uniformity: Uniformity::new(), @@ -726,29 +694,6 @@ impl ModuleInfo { Ok(info) } - /// Analyze a module and return the `ModuleInfo`, if successful. - pub fn new(module: &crate::Module, flags: ValidationFlags) -> Result { - let mut this = ModuleInfo { - functions: Vec::with_capacity(module.functions.len()), - entry_points: Vec::with_capacity(module.entry_points.len()), - }; - for (fun_handle, fun) in module.functions.iter() { - let info = this - .process_function(fun, &module.global_variables, flags) - .map_err(|source| AnalysisError::Function(fun_handle, source))?; - this.functions.push(info); - } - - for ep in module.entry_points.iter() { - let info = this - .process_function(&ep.function, &module.global_variables, flags) - .map_err(|source| AnalysisError::EntryPoint(ep.stage, ep.name.clone(), source))?; - this.entry_points.push(info); - } - - Ok(this) - } - pub fn get_entry_point(&self, index: usize) -> &FunctionInfo { &self.entry_points[index] } @@ -880,7 +825,7 @@ fn uniform_control_flow() { }; assert_eq!( info.process_block(&[stmt_emit2, stmt_if_non_uniform], &[], None), - Err(FunctionAnalysisError::NonUniformControlFlow( + Err(FunctionError::NonUniformControlFlow( UniformityRequirements::DERIVATIVE, derivative_expr, UniformityDisruptor::Expression(non_uniform_global_expr) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 119d1f4d8..0e460f793 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -4,6 +4,7 @@ use crate::{ }; #[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] pub enum ExpressionError { #[error("Doesn't exist")] DoesntExist, diff --git a/src/valid/function.rs b/src/valid/function.rs index 09ca6b44e..770f70c85 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -1,10 +1,14 @@ -use super::{analyzer::FunctionInfo, ExpressionError, TypeFlags, ValidationFlags}; +use super::{ + analyzer::{FunctionInfo, UniformityDisruptor, UniformityRequirements}, + ExpressionError, ModuleInfo, TypeFlags, ValidationFlags, +}; use crate::{ arena::{Arena, Handle}, proc::{ResolveContext, TypifyError}, }; #[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] pub enum CallError { #[error("Bad function")] InvalidFunction, @@ -36,12 +40,14 @@ pub enum CallError { } #[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] pub enum LocalVariableError { #[error("Initializer doesn't match the variable type")] InitializerType, } #[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] pub enum FunctionError { #[error(transparent)] Resolve(#[from] TypifyError), @@ -97,6 +103,16 @@ pub enum FunctionError { #[source] error: CallError, }, + #[error("Expression {0:?} is not a global variable!")] + ExpectedGlobalVariable(crate::Expression), + #[error( + "Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}" + )] + NonUniformControlFlow( + UniformityRequirements, + Handle, + UniformityDisruptor, + ), } bitflags::bitflags! { @@ -464,9 +480,9 @@ impl super::Validator { pub(super) fn validate_function( &mut self, fun: &crate::Function, - _info: &FunctionInfo, module: &crate::Module, - ) -> Result<(), FunctionError> { + mod_info: &ModuleInfo, + ) -> Result { let resolve_ctx = ResolveContext { constants: &module.constants, global_vars: &module.global_variables, @@ -476,6 +492,7 @@ impl super::Validator { }; self.typifier .resolve_all(&fun.expressions, &module.types, &resolve_ctx)?; + let info = mod_info.process_function(fun, &module.global_variables, self.flags)?; for (var_handle, var) in fun.local_variables.iter() { self.validate_local_var(var, &module.types, &module.constants) @@ -511,9 +528,8 @@ impl super::Validator { } if self.flags.contains(ValidationFlags::BLOCKS) { - self.validate_block(&fun.body, &BlockContext::new(fun, module)) - } else { - Ok(()) + self.validate_block(&fun.body, &BlockContext::new(fun, module))?; } + Ok(info) } } diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 2e5b27520..b6fe1a5a4 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -1,6 +1,6 @@ use super::{ analyzer::{FunctionInfo, GlobalUse}, - Disalignment, FunctionError, TypeFlags, + Disalignment, FunctionError, ModuleInfo, TypeFlags, }; use crate::arena::{Arena, Handle}; @@ -352,9 +352,9 @@ impl super::Validator { pub(super) fn validate_entry_point( &mut self, ep: &crate::EntryPoint, - info: &FunctionInfo, module: &crate::Module, - ) -> Result<(), EntryPointError> { + mod_info: &ModuleInfo, + ) -> Result { if ep.early_depth_test.is_some() && ep.stage != crate::ShaderStage::Fragment { return Err(EntryPointError::UnexpectedEarlyDepthTest); } @@ -370,6 +370,8 @@ impl super::Validator { return Err(EntryPointError::UnexpectedWorkgroupSize); } + let info = self.validate_function(&ep.function, module, &mod_info)?; + self.location_mask.clear(); for (index, fa) in ep.function.arguments.iter().enumerate() { let ctx = VaryingContext { @@ -439,7 +441,6 @@ impl super::Validator { } } - self.validate_function(&ep.function, info, module)?; - Ok(()) + Ok(info) } } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 3d5092e76..b3223adf8 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -13,10 +13,7 @@ use bit_set::BitSet; //TODO: analyze the model at the same time as we validate it, // merge the corresponding matches over expressions and statements. -pub use analyzer::{ - AnalysisError, ExpressionInfo, FunctionInfo, GlobalUse, ModuleInfo, Uniformity, - UniformityRequirements, -}; +pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements}; pub use expression::ExpressionError; pub use function::{CallError, FunctionError, LocalVariableError}; pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; @@ -33,6 +30,13 @@ bitflags::bitflags! { } } +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct ModuleInfo { + functions: Vec, + entry_points: Vec, +} + #[derive(Debug)] pub struct Validator { flags: ValidationFlags, @@ -94,8 +98,6 @@ pub enum ValidationError { #[source] error: EntryPointError, }, - #[error(transparent)] - Analysis(#[from] AnalysisError), #[error("Module is corrupted")] Corrupted, } @@ -176,8 +178,10 @@ impl Validator { pub fn validate(&mut self, module: &crate::Module) -> Result { self.reset_types(module.types.len()); - let mod_info = ModuleInfo::new(module, self.flags)?; - + let mut mod_info = ModuleInfo { + functions: Vec::with_capacity(module.functions.len()), + entry_points: Vec::with_capacity(module.entry_points.len()), + }; let layouter = Layouter::new(&module.types, &module.constants); for (handle, constant) in module.constants.iter() { @@ -211,16 +215,20 @@ impl Validator { } for (handle, fun) in module.functions.iter() { - self.validate_function(fun, &mod_info[handle], module) - .map_err(|error| ValidationError::Function { - handle, - name: fun.name.clone().unwrap_or_default(), - error, - })?; + match self.validate_function(fun, module, &mod_info) { + Ok(info) => mod_info.functions.push(info), + Err(error) => { + return Err(ValidationError::Function { + handle, + name: fun.name.clone().unwrap_or_default(), + error, + }) + } + } } let mut ep_map = FastHashSet::default(); - for (index, ep) in module.entry_points.iter().enumerate() { + for ep in module.entry_points.iter() { if !ep_map.insert((ep.stage, &ep.name)) { return Err(ValidationError::EntryPoint { stage: ep.stage, @@ -228,13 +236,17 @@ impl Validator { error: EntryPointError::Conflict, }); } - let info = mod_info.get_entry_point(index); - self.validate_entry_point(ep, info, module) - .map_err(|error| ValidationError::EntryPoint { - stage: ep.stage, - name: ep.name.clone(), - error, - })?; + + match self.validate_entry_point(ep, module, &mod_info) { + Ok(info) => mod_info.entry_points.push(info), + Err(error) => { + return Err(ValidationError::EntryPoint { + stage: ep.stage, + name: ep.name.clone(), + error, + }) + } + } } Ok(mod_info) From 970b77abaf10051831f0fca4f8e2f2ab71f711cc Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 22 Mar 2021 11:33:33 -0400 Subject: [PATCH 0606/2212] Make type a part of ExpressionInfo --- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 276 +++++++------ src/valid/analyzer.rs | 96 +++-- src/valid/expression.rs | 16 +- src/valid/function.rs | 143 +++---- src/valid/mod.rs | 6 +- src/valid/type.rs | 1 - tests/out/collatz.info.ron.snap | 101 +++++ tests/out/shadow.info.ron.snap | 663 ++++++++++++++++++++++++++++++++ 9 files changed, 1043 insertions(+), 261 deletions(-) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c1eea6a2a..5e8a2550c 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -8,7 +8,7 @@ mod typifier; pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; -pub use typifier::{ResolveContext, ResolveError, Typifier, TypifyError}; +pub use typifier::{ResolveContext, ResolveError, TypeResolution, Typifier, TypifyError}; impl From for super::ScalarKind { fn from(format: super::StorageFormat) -> Self { diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index e849c3188..f1a07a374 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -3,18 +3,36 @@ use crate::arena::{Arena, Handle}; use thiserror::Error; #[derive(Debug, PartialEq)] -enum Resolution { +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub enum TypeResolution { Handle(Handle), Value(crate::TypeInner), } +impl TypeResolution { + pub fn handle(&self) -> Option> { + match *self { + Self::Handle(handle) => Some(handle), + Self::Value(_) => None, + } + } + + pub fn inner_with<'a>(&'a self, arena: &'a Arena) -> &'a crate::TypeInner { + match *self { + Self::Handle(handle) => &arena[handle].inner, + Self::Value(ref inner) => inner, + } + } +} + // Clone is only implemented for numeric variants of `TypeInner`. -impl Clone for Resolution { +impl Clone for TypeResolution { fn clone(&self) -> Self { use crate::TypeInner as Ti; match *self { - Resolution::Handle(handle) => Resolution::Handle(handle), - Resolution::Value(ref v) => Resolution::Value(match *v { + Self::Handle(handle) => Self::Handle(handle), + Self::Value(ref v) => Self::Value(match *v { Ti::Scalar { kind, width } => Ti::Scalar { kind, width }, Ti::Vector { size, kind, width } => Ti::Vector { size, kind, width }, Ti::Matrix { @@ -47,7 +65,7 @@ impl Clone for Resolution { /// Helper processor that derives the types of all expressions. #[derive(Debug)] pub struct Typifier { - resolutions: Vec, + resolutions: Vec, } #[derive(Clone, Debug, Error, PartialEq)] @@ -81,6 +99,7 @@ pub enum ResolveError { IncompatibleOperands(String), } +//TODO: remove this #[repr(C)] // pack this tighter: 48 -> 40 bytes #[derive(Clone, Debug, Error, PartialEq)] #[error("Type resolution of {0:?} failed")] @@ -94,77 +113,34 @@ pub struct ResolveContext<'a> { pub arguments: &'a [crate::FunctionArgument], } -impl Typifier { - pub fn new() -> Self { - Typifier { - resolutions: Vec::new(), - } - } - - pub fn clear(&mut self) { - self.resolutions.clear() - } - - pub fn get<'a>( - &'a self, - expr_handle: Handle, - types: &'a Arena, - ) -> &'a crate::TypeInner { - match self.resolutions[expr_handle.index()] { - Resolution::Handle(ty_handle) => &types[ty_handle].inner, - Resolution::Value(ref inner) => inner, - } - } - - pub fn try_get<'a>( - &'a self, - expr_handle: Handle, - types: &'a Arena, - ) -> Option<&'a crate::TypeInner> { - let resolution = self.resolutions.get(expr_handle.index())?; - Some(match *resolution { - Resolution::Handle(ty_handle) => &types[ty_handle].inner, - Resolution::Value(ref inner) => inner, - }) - } - - pub fn get_handle( - &self, - expr_handle: Handle, - ) -> Result, &crate::TypeInner> { - match self.resolutions[expr_handle.index()] { - Resolution::Handle(ty_handle) => Ok(ty_handle), - Resolution::Value(ref inner) => Err(inner), - } - } - - fn resolve_impl( - &self, +impl TypeResolution { + pub fn new<'a>( expr: &crate::Expression, - types: &Arena, + types: &'a Arena, ctx: &ResolveContext, - ) -> Result { + past: impl Fn(Handle) -> &'a Self, + ) -> Result { use crate::TypeInner as Ti; Ok(match *expr { - crate::Expression::Access { base, .. } => match *self.get(base, types) { - Ti::Array { base, .. } => Resolution::Handle(base), + crate::Expression::Access { base, .. } => match *past(base).inner_with(types) { + Ti::Array { base, .. } => Self::Handle(base), Ti::Vector { size: _, kind, width, - } => Resolution::Value(Ti::Scalar { kind, width }), + } => Self::Value(Ti::Scalar { kind, width }), Ti::ValuePointer { size: Some(_), kind, width, class, - } => Resolution::Value(Ti::ValuePointer { + } => Self::Value(Ti::ValuePointer { size: None, kind, width, class, }), - Ti::Pointer { base, class } => Resolution::Value(match types[base].inner { + Ti::Pointer { base, class } => Self::Value(match types[base].inner { Ti::Array { base, .. } => Ti::Pointer { base, class }, Ti::Vector { size: _, @@ -192,12 +168,12 @@ impl Typifier { }); } }, - crate::Expression::AccessIndex { base, index } => match *self.get(base, types) { + crate::Expression::AccessIndex { base, index } => match *past(base).inner_with(types) { Ti::Vector { size, kind, width } => { if index >= size as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } - Resolution::Value(Ti::Scalar { kind, width }) + Self::Value(Ti::Scalar { kind, width }) } Ti::Matrix { columns, @@ -207,13 +183,13 @@ impl Typifier { if index >= columns as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } - Resolution::Value(crate::TypeInner::Vector { + Self::Value(crate::TypeInner::Vector { size: rows, kind: crate::ScalarKind::Float, width, }) } - Ti::Array { base, .. } => Resolution::Handle(base), + Ti::Array { base, .. } => Self::Handle(base), Ti::Struct { block: _, ref members, @@ -221,7 +197,7 @@ impl Typifier { let member = members .get(index as usize) .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; - Resolution::Handle(member.ty) + Self::Handle(member.ty) } Ti::ValuePointer { size: Some(size), @@ -232,7 +208,7 @@ impl Typifier { if index >= size as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } - Resolution::Value(Ti::ValuePointer { + Self::Value(Ti::ValuePointer { size: None, kind, width, @@ -242,7 +218,7 @@ impl Typifier { Ti::Pointer { base: ty_base, class, - } => Resolution::Value(match types[ty_base].inner { + } => Self::Value(match types[ty_base].inner { Ti::Array { base, .. } => Ti::Pointer { base, class }, Ti::Vector { size, kind, width } => { if index >= size as u32 { @@ -299,24 +275,22 @@ impl Typifier { } }, crate::Expression::Constant(h) => match ctx.constants[h].inner { - crate::ConstantInner::Scalar { width, ref value } => { - Resolution::Value(Ti::Scalar { - kind: value.scalar_kind(), - width, - }) - } - crate::ConstantInner::Composite { ty, components: _ } => Resolution::Handle(ty), + crate::ConstantInner::Scalar { width, ref value } => Self::Value(Ti::Scalar { + kind: value.scalar_kind(), + width, + }), + crate::ConstantInner::Composite { ty, components: _ } => Self::Handle(ty), }, - crate::Expression::Compose { ty, .. } => Resolution::Handle(ty), + crate::Expression::Compose { ty, .. } => Self::Handle(ty), crate::Expression::FunctionArgument(index) => { - Resolution::Handle(ctx.arguments[index as usize].ty) + Self::Handle(ctx.arguments[index as usize].ty) } crate::Expression::GlobalVariable(h) => { let var = &ctx.global_vars[h]; if var.class == crate::StorageClass::Handle { - Resolution::Handle(var.ty) + Self::Handle(var.ty) } else { - Resolution::Value(Ti::Pointer { + Self::Value(Ti::Pointer { base: var.ty, class: var.class, }) @@ -324,19 +298,19 @@ impl Typifier { } crate::Expression::LocalVariable(h) => { let var = &ctx.local_vars[h]; - Resolution::Value(Ti::Pointer { + Self::Value(Ti::Pointer { base: var.ty, class: crate::StorageClass::Function, }) } - crate::Expression::Load { pointer } => match *self.get(pointer, types) { - Ti::Pointer { base, class: _ } => Resolution::Handle(base), + crate::Expression::Load { pointer } => match *past(pointer).inner_with(types) { + Ti::Pointer { base, class: _ } => Self::Handle(base), Ti::ValuePointer { size, kind, width, class: _, - } => Resolution::Value(match size { + } => Self::Value(match size { Some(size) => Ti::Vector { size, kind, width }, None => Ti::Scalar { kind, width }, }), @@ -346,8 +320,8 @@ impl Typifier { } }, crate::Expression::ImageSample { image, .. } - | crate::Expression::ImageLoad { image, .. } => match *self.get(image, types) { - Ti::Image { class, .. } => Resolution::Value(match class { + | crate::Expression::ImageLoad { image, .. } => match *past(image).inner_with(types) { + Ti::Image { class, .. } => Self::Value(match class { crate::ImageClass::Depth => Ti::Scalar { kind: crate::ScalarKind::Float, width: 4, @@ -368,8 +342,8 @@ impl Typifier { return Err(ResolveError::InvalidImage(image)); } }, - crate::Expression::ImageQuery { image, query } => Resolution::Value(match query { - crate::ImageQuery::Size { level: _ } => match *self.get(image, types) { + crate::Expression::ImageQuery { image, query } => Self::Value(match query { + crate::ImageQuery::Size { level: _ } => match *past(image).inner_with(types) { Ti::Image { dim, .. } => match dim { crate::ImageDimension::D1 => Ti::Scalar { kind: crate::ScalarKind::Sint, @@ -398,28 +372,30 @@ impl Typifier { width: 4, }, }), - crate::Expression::Unary { expr, .. } => self.resolutions[expr.index()].clone(), + crate::Expression::Unary { expr, .. } => past(expr).clone(), crate::Expression::Binary { op, left, right } => match op { crate::BinaryOperator::Add | crate::BinaryOperator::Subtract | crate::BinaryOperator::Divide - | crate::BinaryOperator::Modulo => self.resolutions[left.index()].clone(), + | crate::BinaryOperator::Modulo => past(left).clone(), crate::BinaryOperator::Multiply => { - let ty_left = self.get(left, types); - let ty_right = self.get(right, types); + let res_left = past(left); + let ty_left = res_left.inner_with(types); + let res_right = past(right); + let ty_right = res_right.inner_with(types); if ty_left == ty_right { - self.resolutions[left.index()].clone() + res_left.clone() } else if let Ti::Scalar { .. } = *ty_left { - self.resolutions[right.index()].clone() + res_right.clone() } else if let Ti::Scalar { .. } = *ty_right { - self.resolutions[left.index()].clone() + res_left.clone() } else if let Ti::Matrix { columns: _, rows, width, } = *ty_left { - Resolution::Value(Ti::Vector { + Self::Value(Ti::Vector { size: rows, kind: crate::ScalarKind::Float, width, @@ -430,7 +406,7 @@ impl Typifier { width, } = *ty_right { - Resolution::Value(Ti::Vector { + Self::Value(Ti::Vector { size: columns, kind: crate::ScalarKind::Float, width, @@ -452,7 +428,7 @@ impl Typifier { | crate::BinaryOperator::LogicalOr => { let kind = crate::ScalarKind::Bool; let width = 1; - let inner = match *self.get(left, types) { + let inner = match *past(left).inner_with(types) { Ti::Scalar { .. } => Ti::Scalar { kind, width }, Ti::Vector { size, .. } => Ti::Vector { size, kind, width }, ref other => { @@ -462,19 +438,17 @@ impl Typifier { ))) } }; - Resolution::Value(inner) + Self::Value(inner) } crate::BinaryOperator::And | crate::BinaryOperator::ExclusiveOr | crate::BinaryOperator::InclusiveOr | crate::BinaryOperator::ShiftLeft - | crate::BinaryOperator::ShiftRight => self.resolutions[left.index()].clone(), + | crate::BinaryOperator::ShiftRight => past(left).clone(), }, - crate::Expression::Select { accept, .. } => self.resolutions[accept.index()].clone(), - crate::Expression::Derivative { axis: _, expr } => { - self.resolutions[expr.index()].clone() - } - crate::Expression::Relational { .. } => Resolution::Value(Ti::Scalar { + crate::Expression::Select { accept, .. } => past(accept).clone(), + crate::Expression::Derivative { axis: _, expr } => past(expr).clone(), + crate::Expression::Relational { .. } => Self::Value(Ti::Scalar { kind: crate::ScalarKind::Bool, width: 4, }), @@ -485,6 +459,7 @@ impl Typifier { arg2: _, } => { use crate::MathFunction as Mf; + let res_arg = past(arg); match fun { // comparison Mf::Abs | @@ -516,14 +491,14 @@ impl Typifier { Mf::Exp2 | Mf::Log | Mf::Log2 | - Mf::Pow => self.resolutions[arg.index()].clone(), + Mf::Pow => res_arg.clone(), // geometry - Mf::Dot => match *self.get(arg, types) { + Mf::Dot => match *res_arg.inner_with(types) { Ti::Vector { kind, size: _, width, - } => Resolution::Value(Ti::Scalar { kind, width }), + } => Self::Value(Ti::Scalar { kind, width }), ref other => return Err(ResolveError::IncompatibleOperands( format!("{:?}({:?}, _)", fun, other) @@ -533,26 +508,26 @@ impl Typifier { let arg1 = arg1.ok_or_else(|| ResolveError::IncompatibleOperands( format!("{:?}(_, None)", fun) ))?; - match (self.get(arg, types), self.get(arg1,types)) { - (&Ti::Vector {kind: _, size: columns,width}, &Ti::Vector{ size: rows, .. }) => Resolution::Value(Ti::Matrix { columns, rows, width }), + match (res_arg.inner_with(types), past(arg1).inner_with(types)) { + (&Ti::Vector {kind: _, size: columns,width}, &Ti::Vector{ size: rows, .. }) => Self::Value(Ti::Matrix { columns, rows, width }), (left, right) => return Err(ResolveError::IncompatibleOperands( format!("{:?}({:?}, {:?})", fun, left, right) )), } }, - Mf::Cross => self.resolutions[arg.index()].clone(), + Mf::Cross => res_arg.clone(), Mf::Distance | - Mf::Length => match *self.get(arg, types) { + Mf::Length => match *res_arg.inner_with(types) { Ti::Scalar {width,kind} | - Ti::Vector {width,kind,size:_} => Resolution::Value(Ti::Scalar { kind, width }), + Ti::Vector {width,kind,size:_} => Self::Value(Ti::Scalar { kind, width }), ref other => return Err(ResolveError::IncompatibleOperands( format!("{:?}({:?})", fun, other) )), }, Mf::Normalize | Mf::FaceForward | - Mf::Reflect => self.resolutions[arg.index()].clone(), + Mf::Reflect => res_arg.clone(), // computational Mf::Sign | Mf::Fma | @@ -560,13 +535,13 @@ impl Typifier { Mf::Step | Mf::SmoothStep | Mf::Sqrt | - Mf::InverseSqrt => self.resolutions[arg.index()].clone(), - Mf::Transpose => match *self.get(arg, types) { + Mf::InverseSqrt => res_arg.clone(), + Mf::Transpose => match *res_arg.inner_with(types) { Ti::Matrix { columns, rows, width, - } => Resolution::Value(Ti::Matrix { + } => Self::Value(Ti::Matrix { columns: rows, rows: columns, width, @@ -575,12 +550,12 @@ impl Typifier { format!("{:?}({:?})", fun, other) )), }, - Mf::Inverse => match *self.get(arg, types) { + Mf::Inverse => match *res_arg.inner_with(types) { Ti::Matrix { columns, rows, width, - } if columns == rows => Resolution::Value(Ti::Matrix { + } if columns == rows => Self::Value(Ti::Matrix { columns, rows, width, @@ -589,31 +564,31 @@ impl Typifier { format!("{:?}({:?})", fun, other) )), }, - Mf::Determinant => match *self.get(arg, types) { + Mf::Determinant => match *res_arg.inner_with(types) { Ti::Matrix { width, .. - } => Resolution::Value(Ti::Scalar { kind: crate::ScalarKind::Float, width }), + } => Self::Value(Ti::Scalar { kind: crate::ScalarKind::Float, width }), ref other => return Err(ResolveError::IncompatibleOperands( format!("{:?}({:?})", fun, other) )), }, // bits Mf::CountOneBits | - Mf::ReverseBits => self.resolutions[arg.index()].clone(), + Mf::ReverseBits => res_arg.clone(), } } crate::Expression::As { expr, kind, convert: _, - } => match *self.get(expr, types) { - Ti::Scalar { kind: _, width } => Resolution::Value(Ti::Scalar { kind, width }), + } => match *past(expr).inner_with(types) { + Ti::Scalar { kind: _, width } => Self::Value(Ti::Scalar { kind, width }), Ti::Vector { kind: _, size, width, - } => Resolution::Value(Ti::Vector { kind, size, width }), + } => Self::Value(Ti::Vector { kind, size, width }), ref other => { return Err(ResolveError::IncompatibleOperands(format!( "{:?} as {:?}", @@ -626,14 +601,60 @@ impl Typifier { .result .as_ref() .ok_or(ResolveError::FunctionReturnsVoid)?; - Resolution::Handle(result.ty) + Self::Handle(result.ty) } - crate::Expression::ArrayLength(_) => Resolution::Value(Ti::Scalar { + crate::Expression::ArrayLength(_) => Self::Value(Ti::Scalar { kind: crate::ScalarKind::Uint, width: 4, }), }) } +} + +impl Typifier { + pub fn new() -> Self { + Typifier { + resolutions: Vec::new(), + } + } + + pub fn clear(&mut self) { + self.resolutions.clear() + } + + //TODO: remove most of these + pub fn get<'a>( + &'a self, + expr_handle: Handle, + types: &'a Arena, + ) -> &'a crate::TypeInner { + match self.resolutions[expr_handle.index()] { + TypeResolution::Handle(ty_handle) => &types[ty_handle].inner, + TypeResolution::Value(ref inner) => inner, + } + } + + pub fn try_get<'a>( + &'a self, + expr_handle: Handle, + types: &'a Arena, + ) -> Option<&'a crate::TypeInner> { + let resolution = self.resolutions.get(expr_handle.index())?; + Some(match *resolution { + TypeResolution::Handle(ty_handle) => &types[ty_handle].inner, + TypeResolution::Value(ref inner) => inner, + }) + } + + pub fn get_handle( + &self, + expr_handle: Handle, + ) -> Result, &crate::TypeInner> { + match self.resolutions[expr_handle.index()] { + TypeResolution::Handle(ty_handle) => Ok(ty_handle), + TypeResolution::Value(ref inner) => Err(inner), + } + } pub fn grow( &mut self, @@ -644,7 +665,8 @@ impl Typifier { ) -> Result<(), ResolveError> { if self.resolutions.len() <= expr_handle.index() { for (eh, expr) in expressions.iter().skip(self.resolutions.len()) { - let resolution = self.resolve_impl(expr, types, ctx)?; + let resolution = + TypeResolution::new(expr, types, ctx, |h| &self.resolutions[h.index()])?; log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); self.resolutions.push(resolution); } @@ -660,9 +682,9 @@ impl Typifier { ) -> Result<(), TypifyError> { self.clear(); for (handle, expr) in expressions.iter() { - let resolution = self - .resolve_impl(expr, types, ctx) - .map_err(|err| TypifyError(handle, err))?; + let resolution = + TypeResolution::new(expr, types, ctx, |h| &self.resolutions[h.index()]) + .map_err(|err| TypifyError(handle, err))?; self.resolutions.push(resolution); } Ok(()) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 20da97ad8..bcb63316b 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -6,8 +6,11 @@ Figures out the following properties: - expression reference counts !*/ -use super::{CallError, FunctionError, ModuleInfo, ValidationFlags}; -use crate::arena::{Arena, Handle}; +use super::{CallError, ExpressionError, FunctionError, ModuleInfo, ValidationFlags}; +use crate::{ + arena::{Arena, Handle}, + proc::{ResolveContext, TypeResolution}, +}; use std::ops; pub type NonUniformResult = Option>; @@ -138,6 +141,7 @@ pub struct ExpressionInfo { pub uniformity: Uniformity, pub ref_count: usize, assignable_global: Option>, + pub ty: TypeResolution, } impl ExpressionInfo { @@ -146,6 +150,11 @@ impl ExpressionInfo { uniformity: Uniformity::new(), ref_count: 0, assignable_global: None, + // this doesn't matter at this point, will be overwritten + ty: TypeResolution::Value(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: 0, + }), } } } @@ -284,15 +293,16 @@ impl FunctionInfo { fn process_expression( &mut self, handle: Handle, + expression: &crate::Expression, expression_arena: &Arena, - arguments: &[crate::FunctionArgument], - global_var_arena: &Arena, other_functions: &[FunctionInfo], - ) -> Result<(), FunctionError> { + type_arena: &Arena, + resolve_context: &ResolveContext, + ) -> Result<(), ExpressionError> { use crate::{Expression as E, SampleLevel as Sl}; let mut assignable_global = None; - let uniformity = match expression_arena[handle] { + let uniformity = match *expression { E::Access { base, index } => Uniformity { non_uniform_result: self .add_assignable_ref(base, &mut assignable_global) @@ -316,7 +326,7 @@ impl FunctionInfo { } // depends on the builtin or interpolation E::FunctionArgument(index) => { - let arg = &arguments[index as usize]; + let arg = &resolve_context.arguments[index as usize]; let uniform = match arg.binding { Some(crate::Binding::BuiltIn(built_in)) => match built_in { // per-polygon built-ins are uniform @@ -339,7 +349,7 @@ impl FunctionInfo { E::GlobalVariable(gh) => { use crate::StorageClass as Sc; assignable_global = Some(gh); - let var = &global_var_arena[gh]; + let var = &resolve_context.global_vars[gh]; let uniform = match var.class { // local data is non-uniform Sc::Function | Sc::Private => false, @@ -377,15 +387,11 @@ impl FunctionInfo { self.sampling_set.insert(SamplingKey { image: match expression_arena[image] { crate::Expression::GlobalVariable(var) => var, - ref other => { - return Err(FunctionError::ExpectedGlobalVariable(other.clone())) - } + _ => return Err(ExpressionError::ExpectedGlobalVariable), }, sampler: match expression_arena[sampler] { crate::Expression::GlobalVariable(var) => var, - ref other => { - return Err(FunctionError::ExpectedGlobalVariable(other.clone())) - } + _ => return Err(ExpressionError::ExpectedGlobalVariable), }, }); // "nur" == "Non-Uniform Result" @@ -482,13 +488,9 @@ impl FunctionInfo { requirements: UniformityRequirements::empty(), }, E::Call(function) => { - let fun = - other_functions - .get(function.index()) - .ok_or(FunctionError::InvalidCall { - function, - error: CallError::ForwardDeclaredFunction, - })?; + let fun = other_functions + .get(function.index()) + .ok_or(ExpressionError::CallToUndeclaredFunction(function))?; self.process_call(fun).result } E::ArrayLength(expr) => Uniformity { @@ -497,10 +499,14 @@ impl FunctionInfo { }, }; + let ty = TypeResolution::new(expression, type_arena, resolve_context, |h| { + &self.expressions[h.index()].ty + })?; self.expressions[handle.index()] = ExpressionInfo { uniformity, ref_count: 0, assignable_global, + ty, }; Ok(()) } @@ -648,6 +654,7 @@ impl FunctionInfo { error: CallError::ForwardDeclaredFunction, }, )?; + //Note: the result is validated by the Validator, not here self.process_call(info) } }; @@ -665,7 +672,7 @@ impl ModuleInfo { pub(super) fn process_function( &self, fun: &crate::Function, - global_var_arena: &Arena, + module: &crate::Module, flags: ValidationFlags, ) -> Result { let mut info = FunctionInfo { @@ -673,18 +680,28 @@ impl ModuleInfo { uniformity: Uniformity::new(), may_kill: false, sampling_set: crate::FastHashSet::default(), - global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), + global_uses: vec![GlobalUse::empty(); module.global_variables.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::new(); fun.expressions.len()].into_boxed_slice(), }; + let resolve_context = ResolveContext { + constants: &module.constants, + global_vars: &module.global_variables, + local_vars: &fun.local_variables, + functions: &module.functions, + arguments: &fun.arguments, + }; - for (handle, _) in fun.expressions.iter() { - info.process_expression( + for (handle, expr) in fun.expressions.iter() { + if let Err(error) = info.process_expression( handle, + expr, &fun.expressions, - &fun.arguments, - global_var_arena, &self.functions, - )?; + &module.types, + &resolve_context, + ) { + return Err(FunctionError::Expression { handle, error }); + } } let uniformity = info.process_block(&fun.body, &self.functions, None)?; @@ -722,7 +739,8 @@ fn uniform_control_flow() { let mut type_arena = Arena::new(); let ty = type_arena.append(crate::Type { name: None, - inner: crate::TypeInner::Scalar { + inner: crate::TypeInner::Vector { + size: crate::VectorSize::Bi, kind: crate::ScalarKind::Float, width: 4, }, @@ -775,9 +793,23 @@ fn uniform_control_flow() { global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::new(); expressions.len()].into_boxed_slice(), }; - for (handle, _) in expressions.iter() { - info.process_expression(handle, &expressions, &[], &global_var_arena, &[]) - .unwrap(); + let resolve_context = ResolveContext { + constants: &constant_arena, + global_vars: &global_var_arena, + local_vars: &Arena::new(), + functions: &Arena::new(), + arguments: &[], + }; + for (handle, expression) in expressions.iter() { + info.process_expression( + handle, + expression, + &expressions, + &[], + &type_arena, + &resolve_context, + ) + .unwrap(); } assert_eq!(info[non_uniform_global_expr].ref_count, 1); assert_eq!(info[uniform_global_expr].ref_count, 1); diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 0e460f793..457a86789 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,6 +1,7 @@ +use super::FunctionInfo; use crate::{ arena::{Arena, Handle}, - proc::Typifier, + proc::ResolveError, }; #[derive(Clone, Debug, thiserror::Error)] @@ -52,12 +53,18 @@ pub enum ExpressionError { InvalidBooleanVector(Handle), #[error("Relational argument {0:?} is not a float")] InvalidFloatArgument(Handle), + #[error("Type resolution failed")] + Type(#[from] ResolveError), + #[error("Not a global variable")] + ExpectedGlobalVariable, + #[error("Calling an undeclared function {0:?}")] + CallToUndeclaredFunction(Handle), } struct ExpressionTypeResolver<'a> { root: Handle, types: &'a Arena, - typifier: &'a Typifier, + info: &'a FunctionInfo, } impl<'a> ExpressionTypeResolver<'a> { @@ -66,7 +73,7 @@ impl<'a> ExpressionTypeResolver<'a> { handle: Handle, ) -> Result<&'a crate::TypeInner, ExpressionError> { if handle < self.root { - Ok(self.typifier.get(handle, self.types)) + Ok(self.info[handle].ty.inner_with(self.types)) } else { Err(ExpressionError::ForwardDependency(handle)) } @@ -80,13 +87,14 @@ impl super::Validator { expression: &crate::Expression, function: &crate::Function, module: &crate::Module, + info: &FunctionInfo, ) -> Result<(), ExpressionError> { use crate::{Expression as E, ScalarKind as Sk, TypeInner as Ti}; let resolver = ExpressionTypeResolver { root, types: &module.types, - typifier: &self.typifier, + info, }; match *expression { diff --git a/src/valid/function.rs b/src/valid/function.rs index 770f70c85..88f2a2795 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -1,11 +1,8 @@ use super::{ - analyzer::{FunctionInfo, UniformityDisruptor, UniformityRequirements}, - ExpressionError, ModuleInfo, TypeFlags, ValidationFlags, -}; -use crate::{ - arena::{Arena, Handle}, - proc::{ResolveContext, TypifyError}, + analyzer::{UniformityDisruptor, UniformityRequirements}, + ExpressionError, FunctionInfo, ModuleInfo, TypeFlags, ValidationFlags, }; +use crate::arena::{Arena, Handle}; #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] @@ -32,11 +29,8 @@ pub enum CallError { required: Handle, seen_expression: Handle, }, - #[error("Result value {seen_expression:?} does not match the type {required:?}")] - ResultType { - required: Option>, - seen_expression: Option>, - }, + #[error("The emitted expression doesn't match the call")] + ExpressionMismatch(Option>), } #[derive(Clone, Debug, thiserror::Error)] @@ -49,8 +43,6 @@ pub enum LocalVariableError { #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum FunctionError { - #[error(transparent)] - Resolve(#[from] TypifyError), #[error("Expression {handle:?} is invalid")] Expression { handle: Handle, @@ -103,8 +95,6 @@ pub enum FunctionError { #[source] error: CallError, }, - #[error("Expression {0:?} is not a global variable!")] - ExpectedGlobalVariable(crate::Expression), #[error( "Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}" )] @@ -127,6 +117,7 @@ bitflags::bitflags! { struct BlockContext<'a> { flags: Flags, + info: &'a FunctionInfo, expressions: &'a Arena, types: &'a Arena, functions: &'a Arena, @@ -134,9 +125,10 @@ struct BlockContext<'a> { } impl<'a> BlockContext<'a> { - pub(super) fn new(fun: &'a crate::Function, module: &'a crate::Module) -> Self { + fn new(fun: &'a crate::Function, module: &'a crate::Module, info: &'a FunctionInfo) -> Self { Self { flags: Flags::CAN_JUMP, + info, expressions: &fun.expressions, types: &module.types, functions: &module.functions, @@ -147,6 +139,7 @@ impl<'a> BlockContext<'a> { fn with_flags(&self, flags: Flags) -> Self { BlockContext { flags, + info: self.info, expressions: self.expressions, types: self.types, functions: self.functions, @@ -162,6 +155,25 @@ impl<'a> BlockContext<'a> { .try_get(handle) .ok_or(FunctionError::InvalidExpression(handle)) } + + fn resolve_type_impl( + &self, + handle: Handle, + ) -> Result<&crate::TypeInner, ExpressionError> { + if handle.index() < self.expressions.len() { + Ok(self.info[handle].ty.inner_with(self.types)) + } else { + Err(ExpressionError::DoesntExist) + } + } + + fn resolve_type( + &self, + handle: Handle, + ) -> Result<&crate::TypeInner, FunctionError> { + self.resolve_type_impl(handle) + .map_err(|error| FunctionError::Expression { handle, error }) + } } impl super::Validator { @@ -183,8 +195,8 @@ impl super::Validator { }); } for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { - let ty = self - .resolve_statement_type_impl(expr, context.types) + let ty = context + .resolve_type_impl(expr) .map_err(|error| CallError::Argument { index, error })?; if ty != &context.types[arg.ty].inner { return Err(CallError::ArgumentType { @@ -201,49 +213,17 @@ impl super::Validator { } else { return Err(CallError::ResultAlreadyInScope(expr)); } + match context.expressions[expr] { + crate::Expression::Call(callee) if fun.result.is_some() && callee == function => {} + _ => return Err(CallError::ExpressionMismatch(result)), + } + } else if fun.result.is_some() { + return Err(CallError::ExpressionMismatch(result)); } - let result_ty = result - .map(|expr| self.resolve_statement_type_impl(expr, context.types)) - .transpose() - .map_err(CallError::ResultValue)?; - let expected_ty = fun.result.as_ref().map(|fr| &context.types[fr.ty].inner); - if result_ty != expected_ty { - log::error!( - "Called function returns {:?} where {:?} is expected", - result_ty, - expected_ty - ); - return Err(CallError::ResultType { - required: fun.result.as_ref().map(|fr| fr.ty), - seen_expression: result, - }); - } Ok(()) } - fn resolve_statement_type_impl<'a>( - &'a self, - handle: Handle, - types: &'a Arena, - ) -> Result<&'a crate::TypeInner, ExpressionError> { - if !self.valid_expression_set.contains(handle.index()) { - return Err(ExpressionError::NotInScope); - } - self.typifier - .try_get(handle, types) - .ok_or(ExpressionError::DoesntExist) - } - - fn resolve_statement_type<'a>( - &'a self, - handle: Handle, - types: &'a Arena, - ) -> Result<&'a crate::TypeInner, FunctionError> { - self.resolve_statement_type_impl(handle, types) - .map_err(|error| FunctionError::Expression { handle, error }) - } - fn validate_block_impl( &mut self, statements: &[crate::Statement], @@ -271,7 +251,7 @@ impl super::Validator { ref accept, ref reject, } => { - match *self.resolve_statement_type(condition, context.types)? { + match *context.resolve_type(condition)? { Ti::Scalar { kind: crate::ScalarKind::Bool, width: _, @@ -286,7 +266,7 @@ impl super::Validator { ref cases, ref default, } => { - match *self.resolve_statement_type(selector, context.types)? { + match *context.resolve_type(selector)? { Ti::Scalar { kind: crate::ScalarKind::Sint, width: _, @@ -330,9 +310,7 @@ impl super::Validator { if !context.flags.contains(Flags::CAN_JUMP) { return Err(FunctionError::InvalidReturnSpot); } - let value_ty = value - .map(|expr| self.resolve_statement_type(expr, context.types)) - .transpose()?; + let value_ty = value.map(|expr| context.resolve_type(expr)).transpose()?; let expected_ty = context.return_type.map(|ty| &context.types[ty].inner); if value_ty != expected_ty { log::error!( @@ -350,12 +328,7 @@ impl super::Validator { S::Store { pointer, value } => { let mut current = pointer; loop { - self.typifier.try_get(current, context.types).ok_or( - FunctionError::Expression { - handle: current, - error: ExpressionError::DoesntExist, - }, - )?; + let _ = context.resolve_type(current)?; match context.expressions[current] { crate::Expression::Access { base, .. } | crate::Expression::AccessIndex { base, .. } => current = base, @@ -366,29 +339,27 @@ impl super::Validator { } } - let value_ty = self.resolve_statement_type(value, context.types)?; + let value_ty = context.resolve_type(value)?; match *value_ty { Ti::Image { .. } | Ti::Sampler { .. } => { return Err(FunctionError::InvalidStoreValue(value)); } _ => {} } - let good = match self.typifier.try_get(pointer, context.types) { - Some(&Ti::Pointer { base, class: _ }) => { - *value_ty == context.types[base].inner - } - Some(&Ti::ValuePointer { + let good = match *context.resolve_type(pointer)? { + Ti::Pointer { base, class: _ } => *value_ty == context.types[base].inner, + Ti::ValuePointer { size: Some(size), kind, width, class: _, - }) => *value_ty == Ti::Vector { size, kind, width }, - Some(&Ti::ValuePointer { + } => *value_ty == Ti::Vector { size, kind, width }, + Ti::ValuePointer { size: None, kind, width, class: _, - }) => *value_ty == Ti::Scalar { kind, width }, + } => *value_ty == Ti::Scalar { kind, width }, _ => false, }; if !good { @@ -405,15 +376,14 @@ impl super::Validator { crate::Expression::GlobalVariable(_var_handle) => (), //TODO _ => return Err(FunctionError::InvalidImage(image)), }; - let value_ty = self.typifier.get(value, context.types); - match *value_ty { + match *context.resolve_type(value)? { Ti::Scalar { .. } | Ti::Vector { .. } => {} _ => { return Err(FunctionError::InvalidStoreValue(value)); } } if let Some(expr) = array_index { - match *self.typifier.get(expr, context.types) { + match *context.resolve_type(expr)? { Ti::Scalar { kind: crate::ScalarKind::Sint, width: _, @@ -483,16 +453,7 @@ impl super::Validator { module: &crate::Module, mod_info: &ModuleInfo, ) -> Result { - let resolve_ctx = ResolveContext { - constants: &module.constants, - global_vars: &module.global_variables, - local_vars: &fun.local_variables, - functions: &module.functions, - arguments: &fun.arguments, - }; - self.typifier - .resolve_all(&fun.expressions, &module.types, &resolve_ctx)?; - let info = mod_info.process_function(fun, &module.global_variables, self.flags)?; + let info = mod_info.process_function(fun, module, self.flags)?; for (var_handle, var) in fun.local_variables.iter() { self.validate_local_var(var, &module.types, &module.constants) @@ -521,14 +482,14 @@ impl super::Validator { self.valid_expression_set.insert(handle.index()); } if !self.flags.contains(ValidationFlags::EXPRESSIONS) { - if let Err(error) = self.validate_expression(handle, expr, fun, module) { + if let Err(error) = self.validate_expression(handle, expr, fun, module, &info) { return Err(FunctionError::Expression { handle, error }); } } } if self.flags.contains(ValidationFlags::BLOCKS) { - self.validate_block(&fun.body, &BlockContext::new(fun, module))?; + self.validate_block(&fun.body, &BlockContext::new(fun, module, &info))?; } Ok(info) } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index b3223adf8..b80d6e5dd 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -6,7 +6,7 @@ mod r#type; use crate::{ arena::{Arena, Handle}, - proc::{Layouter, Typifier}, + proc::Layouter, FastHashSet, }; use bit_set::BitSet; @@ -40,9 +40,6 @@ pub struct ModuleInfo { #[derive(Debug)] pub struct Validator { flags: ValidationFlags, - //Note: this is a bit tricky: some of the front-ends as well as backends - // already have to use the typifier, so the work here is redundant in a way. - typifier: Typifier, types: Vec, location_mask: BitSet, bind_group_masks: Vec, @@ -125,7 +122,6 @@ impl Validator { pub fn new(flags: ValidationFlags) -> Self { Validator { flags, - typifier: Typifier::new(), types: Vec::new(), location_mask: BitSet::new(), bind_group_masks: Vec::new(), diff --git a/src/valid/type.rs b/src/valid/type.rs index b1a6b7b13..ff89d3f6f 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -103,7 +103,6 @@ impl super::Validator { } pub(super) fn reset_types(&mut self, size: usize) { - self.typifier.clear(); self.types.clear(); self.types.resize(size, TypeInfo::new()); } diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 28ace1076..894722419 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -31,6 +31,10 @@ expression: output ), ref_count: 0, assignable_global: Some(1), + ty: Value(Pointer( + base: 3, + class: Storage, + )), ), ( uniformity: ( @@ -41,6 +45,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -51,6 +56,10 @@ expression: output ), ref_count: 7, assignable_global: None, + ty: Value(Pointer( + base: 1, + class: Function, + )), ), ( uniformity: ( @@ -61,6 +70,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -71,6 +84,10 @@ expression: output ), ref_count: 3, assignable_global: None, + ty: Value(Pointer( + base: 1, + class: Function, + )), ), ( uniformity: ( @@ -81,6 +98,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -91,6 +109,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -101,6 +123,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Bool, + width: 1, + )), ), ( uniformity: ( @@ -111,6 +137,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -121,6 +148,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -131,6 +162,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -141,6 +173,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -151,6 +187,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Bool, + width: 1, + )), ), ( uniformity: ( @@ -161,6 +201,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -171,6 +212,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -181,6 +226,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -191,6 +237,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -201,6 +251,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -211,6 +262,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -221,6 +276,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -231,6 +290,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -241,6 +304,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -251,6 +315,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -261,6 +329,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -271,6 +340,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ], ), @@ -303,6 +373,10 @@ expression: output ), ref_count: 2, assignable_global: Some(1), + ty: Value(Pointer( + base: 3, + class: Storage, + )), ), ( uniformity: ( @@ -313,6 +387,7 @@ expression: output ), ref_count: 2, assignable_global: None, + ty: Handle(4), ), ( uniformity: ( @@ -323,6 +398,10 @@ expression: output ), ref_count: 1, assignable_global: Some(1), + ty: Value(Pointer( + base: 2, + class: Storage, + )), ), ( uniformity: ( @@ -333,6 +412,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -343,6 +426,10 @@ expression: output ), ref_count: 1, assignable_global: Some(1), + ty: Value(Pointer( + base: 1, + class: Storage, + )), ), ( uniformity: ( @@ -353,6 +440,10 @@ expression: output ), ref_count: 1, assignable_global: Some(1), + ty: Value(Pointer( + base: 2, + class: Storage, + )), ), ( uniformity: ( @@ -363,6 +454,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -373,6 +468,10 @@ expression: output ), ref_count: 1, assignable_global: Some(1), + ty: Value(Pointer( + base: 1, + class: Storage, + )), ), ( uniformity: ( @@ -383,6 +482,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -393,6 +493,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ], ), diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 497d65c3c..f0d4c9c29 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -54,6 +54,10 @@ expression: output ), ref_count: 0, assignable_global: Some(3), + ty: Value(Pointer( + base: 14, + class: Uniform, + )), ), ( uniformity: ( @@ -64,6 +68,10 @@ expression: output ), ref_count: 0, assignable_global: Some(6), + ty: Value(Pointer( + base: 2, + class: Private, + )), ), ( uniformity: ( @@ -74,6 +82,10 @@ expression: output ), ref_count: 0, assignable_global: Some(5), + ty: Value(Pointer( + base: 4, + class: Private, + )), ), ( uniformity: ( @@ -84,6 +96,7 @@ expression: output ), ref_count: 1, assignable_global: Some(1), + ty: Handle(56), ), ( uniformity: ( @@ -94,6 +107,7 @@ expression: output ), ref_count: 1, assignable_global: Some(2), + ty: Handle(57), ), ( uniformity: ( @@ -104,6 +118,10 @@ expression: output ), ref_count: 0, assignable_global: Some(4), + ty: Value(Pointer( + base: 21, + class: Storage, + )), ), ( uniformity: ( @@ -114,6 +132,10 @@ expression: output ), ref_count: 0, assignable_global: Some(7), + ty: Value(Pointer( + base: 4, + class: Private, + )), ), ( uniformity: ( @@ -124,6 +146,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -134,6 +160,10 @@ expression: output ), ref_count: 3, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -144,6 +174,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -154,6 +188,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -164,6 +202,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -174,6 +216,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -184,6 +230,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -194,6 +244,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -204,6 +258,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -214,6 +272,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -224,6 +286,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -234,6 +300,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -244,6 +314,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -254,6 +328,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -264,6 +342,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -274,6 +356,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -284,6 +370,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -294,6 +384,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -304,6 +398,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -314,6 +412,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -324,6 +426,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -334,6 +440,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -344,6 +454,10 @@ expression: output ), ref_count: 3, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -354,6 +468,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -364,6 +482,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -374,6 +496,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -384,6 +510,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -394,6 +524,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -404,6 +538,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -414,6 +552,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -424,6 +566,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -434,6 +580,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -444,6 +594,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -454,6 +608,7 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -464,6 +619,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -474,6 +633,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -484,6 +644,7 @@ expression: output ), ref_count: 6, assignable_global: None, + ty: Handle(4), ), ( uniformity: ( @@ -494,6 +655,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -504,6 +669,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Bool, + width: 1, + )), ), ( uniformity: ( @@ -514,6 +683,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -524,6 +697,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -534,6 +711,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(9), ), ( uniformity: ( @@ -544,6 +722,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(9), ), ( uniformity: ( @@ -554,6 +733,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(9), ), ( uniformity: ( @@ -564,6 +744,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -574,6 +758,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -584,6 +772,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(9), ), ( uniformity: ( @@ -594,6 +783,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(9), ), ( uniformity: ( @@ -604,6 +794,7 @@ expression: output ), ref_count: 2, assignable_global: None, + ty: Handle(9), ), ( uniformity: ( @@ -614,6 +805,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -624,6 +819,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -634,6 +833,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -644,6 +847,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -654,6 +861,7 @@ expression: output ), ref_count: 3, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -664,6 +872,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -674,6 +886,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -684,6 +900,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -694,6 +914,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -704,6 +928,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -714,6 +942,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -724,6 +956,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(6), ), ( uniformity: ( @@ -734,6 +967,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -744,6 +981,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -754,6 +995,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ], ), @@ -807,6 +1052,10 @@ expression: output ), ref_count: 1, assignable_global: Some(3), + ty: Value(Pointer( + base: 14, + class: Uniform, + )), ), ( uniformity: ( @@ -817,6 +1066,10 @@ expression: output ), ref_count: 1, assignable_global: Some(6), + ty: Value(Pointer( + base: 2, + class: Private, + )), ), ( uniformity: ( @@ -827,6 +1080,10 @@ expression: output ), ref_count: 4, assignable_global: Some(5), + ty: Value(Pointer( + base: 4, + class: Private, + )), ), ( uniformity: ( @@ -837,6 +1094,7 @@ expression: output ), ref_count: 0, assignable_global: Some(1), + ty: Handle(56), ), ( uniformity: ( @@ -847,6 +1105,7 @@ expression: output ), ref_count: 0, assignable_global: Some(2), + ty: Handle(57), ), ( uniformity: ( @@ -857,6 +1116,10 @@ expression: output ), ref_count: 7, assignable_global: Some(4), + ty: Value(Pointer( + base: 21, + class: Storage, + )), ), ( uniformity: ( @@ -867,6 +1130,10 @@ expression: output ), ref_count: 1, assignable_global: Some(7), + ty: Value(Pointer( + base: 4, + class: Private, + )), ), ( uniformity: ( @@ -877,6 +1144,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -887,6 +1158,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -897,6 +1172,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -907,6 +1186,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -917,6 +1200,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -927,6 +1214,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -937,6 +1228,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -947,6 +1242,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -957,6 +1256,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -967,6 +1270,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -977,6 +1284,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -987,6 +1298,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -997,6 +1312,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1007,6 +1326,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1017,6 +1340,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1027,6 +1354,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1037,6 +1368,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1047,6 +1382,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1057,6 +1396,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1067,6 +1410,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -1077,6 +1424,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -1087,6 +1438,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1097,6 +1452,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1107,6 +1466,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1117,6 +1480,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1127,6 +1494,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1137,6 +1508,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1147,6 +1522,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1157,6 +1536,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1167,6 +1550,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1177,6 +1564,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1187,6 +1578,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1197,6 +1592,10 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), ), ( uniformity: ( @@ -1207,6 +1606,7 @@ expression: output ), ref_count: 0, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1217,6 +1617,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1227,6 +1631,10 @@ expression: output ), ref_count: 3, assignable_global: None, + ty: Value(Pointer( + base: 2, + class: Function, + )), ), ( uniformity: ( @@ -1237,6 +1645,10 @@ expression: output ), ref_count: 11, assignable_global: None, + ty: Value(Pointer( + base: 3, + class: Function, + )), ), ( uniformity: ( @@ -1247,6 +1659,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1257,6 +1670,10 @@ expression: output ), ref_count: 1, assignable_global: Some(3), + ty: Value(Pointer( + base: 13, + class: Uniform, + )), ), ( uniformity: ( @@ -1267,6 +1684,12 @@ expression: output ), ref_count: 1, assignable_global: Some(3), + ty: Value(ValuePointer( + size: None, + kind: Uint, + width: 4, + class: Uniform, + )), ), ( uniformity: ( @@ -1277,6 +1700,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -1287,6 +1714,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), ), ( uniformity: ( @@ -1297,6 +1728,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Bool, + width: 1, + )), ), ( uniformity: ( @@ -1307,6 +1742,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1317,6 +1753,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1327,6 +1764,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 20, + class: Storage, + )), ), ( uniformity: ( @@ -1337,6 +1778,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1347,6 +1789,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 19, + class: Storage, + )), ), ( uniformity: ( @@ -1357,6 +1803,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 18, + class: Storage, + )), ), ( uniformity: ( @@ -1367,6 +1817,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(18), ), ( uniformity: ( @@ -1377,6 +1828,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(4), ), ( uniformity: ( @@ -1387,6 +1839,11 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Vector( + size: Quad, + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1397,6 +1854,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -1407,6 +1865,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1417,6 +1876,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1427,6 +1887,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 20, + class: Storage, + )), ), ( uniformity: ( @@ -1437,6 +1901,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1447,6 +1912,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 19, + class: Storage, + )), ), ( uniformity: ( @@ -1457,6 +1926,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1467,6 +1940,12 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1477,6 +1956,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1487,6 +1970,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 20, + class: Storage, + )), ), ( uniformity: ( @@ -1497,6 +1984,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1507,6 +1995,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 19, + class: Storage, + )), ), ( uniformity: ( @@ -1517,6 +2009,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1527,6 +2023,12 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1537,6 +2039,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1547,6 +2053,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 20, + class: Storage, + )), ), ( uniformity: ( @@ -1557,6 +2067,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1567,6 +2078,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 19, + class: Storage, + )), ), ( uniformity: ( @@ -1577,6 +2092,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1587,6 +2106,12 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1597,6 +2122,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1607,6 +2136,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1617,6 +2147,12 @@ expression: output ), ref_count: 1, assignable_global: Some(5), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + class: Private, + )), ), ( uniformity: ( @@ -1627,6 +2163,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1637,6 +2177,12 @@ expression: output ), ref_count: 1, assignable_global: Some(5), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + class: Private, + )), ), ( uniformity: ( @@ -1647,6 +2193,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1657,6 +2207,12 @@ expression: output ), ref_count: 1, assignable_global: Some(5), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + class: Private, + )), ), ( uniformity: ( @@ -1667,6 +2223,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1677,6 +2237,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1687,6 +2248,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1697,6 +2259,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1707,6 +2270,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1717,6 +2284,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1727,6 +2298,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(1), ), ( uniformity: ( @@ -1737,6 +2309,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 20, + class: Storage, + )), ), ( uniformity: ( @@ -1747,6 +2323,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1757,6 +2334,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 19, + class: Storage, + )), ), ( uniformity: ( @@ -1767,6 +2348,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1777,6 +2362,12 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1787,6 +2378,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1797,6 +2392,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 20, + class: Storage, + )), ), ( uniformity: ( @@ -1807,6 +2406,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1817,6 +2417,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 19, + class: Storage, + )), ), ( uniformity: ( @@ -1827,6 +2431,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1837,6 +2445,12 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1847,6 +2461,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1857,6 +2475,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 20, + class: Storage, + )), ), ( uniformity: ( @@ -1867,6 +2489,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1877,6 +2500,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 19, + class: Storage, + )), ), ( uniformity: ( @@ -1887,6 +2514,10 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(Pointer( + base: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1897,6 +2528,12 @@ expression: output ), ref_count: 1, assignable_global: Some(4), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + class: Storage, + )), ), ( uniformity: ( @@ -1907,6 +2544,10 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( @@ -1917,6 +2558,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1927,6 +2569,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1937,6 +2580,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1947,6 +2591,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1957,6 +2602,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(3), ), ( uniformity: ( @@ -1967,6 +2613,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -1977,6 +2624,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(4), ), ], ), @@ -2032,6 +2680,10 @@ expression: output ), ref_count: 1, assignable_global: Some(6), + ty: Value(Pointer( + base: 2, + class: Private, + )), ), ( uniformity: ( @@ -2042,6 +2694,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -2052,6 +2705,10 @@ expression: output ), ref_count: 1, assignable_global: Some(5), + ty: Value(Pointer( + base: 4, + class: Private, + )), ), ( uniformity: ( @@ -2062,6 +2719,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(4), ), ( uniformity: ( @@ -2072,6 +2730,10 @@ expression: output ), ref_count: 1, assignable_global: Some(7), + ty: Value(Pointer( + base: 4, + class: Private, + )), ), ( uniformity: ( @@ -2082,6 +2744,7 @@ expression: output ), ref_count: 1, assignable_global: None, + ty: Handle(4), ), ], ), From d4bc463d50139103f3a4713566633d9c76beb6c2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 22 Mar 2021 12:02:52 -0400 Subject: [PATCH 0607/2212] Stop using the old Typifier in the backends --- src/back/glsl/mod.rs | 109 +++++++++++++++++--------------------- src/back/msl/writer.rs | 116 +++++++++++++++++------------------------ src/back/spv/writer.rs | 96 ++++++++++++++++++++-------------- 3 files changed, 153 insertions(+), 168 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 651ea5c6a..54c5c7e58 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -44,7 +44,7 @@ pub use features::Features; use crate::{ - proc::{EntryPointIndex, NameKey, Namer, ResolveContext, Typifier, TypifyError}, + proc::{EntryPointIndex, NameKey, Namer, TypeResolution, TypifyError}, valid::{FunctionInfo, ModuleInfo}, Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, @@ -185,18 +185,16 @@ enum FunctionType { } /// Helper structure that stores data needed when writing the function -struct FunctionCtx<'a, 'b> { +struct FunctionCtx<'a> { /// The current function being written func: FunctionType, /// Analysis about the function info: &'a FunctionInfo, /// The expression arena of the current function being written expressions: &'a Arena, - /// A typifier that has already resolved all expressions in the function being written - typifier: &'b Typifier, } -impl<'a, 'b> FunctionCtx<'a, 'b> { +impl<'a> FunctionCtx<'a> { /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function fn name_key(&self, local: Handle) -> NameKey { match self.func { @@ -855,26 +853,11 @@ impl<'a, W: Write> Writer<'a, W> { info: &FunctionInfo, name: &str, ) -> BackendResult { - // Create a new typifier and resolve all types for the current function - let mut typifier = Typifier::new(); - typifier.resolve_all( - &func.expressions, - &self.module.types, - &ResolveContext { - constants: &self.module.constants, - global_vars: &self.module.global_variables, - local_vars: &func.local_variables, - functions: &self.module.functions, - arguments: &func.arguments, - }, - )?; - // Create a function context for the function being written let ctx = FunctionCtx { func: ty, info, expressions: &func.expressions, - typifier: &typifier, }; self.cached_expressions.clear(); @@ -1166,7 +1149,7 @@ impl<'a, W: Write> Writer<'a, W> { fn write_stmt( &mut self, sta: &Statement, - ctx: &FunctionCtx<'_, '_>, + ctx: &FunctionCtx<'_>, indent: usize, ) -> BackendResult { match *sta { @@ -1176,17 +1159,19 @@ impl<'a, W: Write> Writer<'a, W> { let min_ref_count = ctx.expressions[handle].bake_ref_count(); if min_ref_count <= ctx.info[handle].ref_count { write!(self.out, "{}", INDENT.repeat(indent))?; - match ctx.typifier.get_handle(handle) { - Ok(ty_handle) => match self.module.types[ty_handle].inner { - TypeInner::Struct { .. } => { - let ty_name = &self.names[&NameKey::Type(ty_handle)]; - write!(self.out, "{}", ty_name)?; + match ctx.info[handle].ty { + TypeResolution::Handle(ty_handle) => { + match self.module.types[ty_handle].inner { + TypeInner::Struct { .. } => { + let ty_name = &self.names[&NameKey::Type(ty_handle)]; + write!(self.out, "{}", ty_name)?; + } + _ => { + self.write_type(ty_handle)?; + } } - _ => { - self.write_type(ty_handle)?; - } - }, - Err(inner) => { + } + TypeResolution::Value(ref inner) => { self.write_value_type(inner)?; } } @@ -1413,7 +1398,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { write!(self.out, "{}", INDENT.repeat(indent))?; // This will only panic if the module is invalid - let dim = match *ctx.typifier.get(image, &self.module.types) { + let dim = match *ctx.info[image].ty.inner_with(&self.module.types) { TypeInner::Image { dim, .. } => dim, _ => unreachable!(), }; @@ -1453,7 +1438,7 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Doesn't add any newlines or leading/trailing spaces - fn write_expr(&mut self, expr: Handle, ctx: &FunctionCtx<'_, '_>) -> BackendResult { + fn write_expr(&mut self, expr: Handle, ctx: &FunctionCtx<'_>) -> BackendResult { if let Some(name) = self.cached_expressions.get(&expr) { write!(self.out, "{}", name)?; return Ok(()); @@ -1472,13 +1457,14 @@ impl<'a, W: Write> Writer<'a, W> { Expression::AccessIndex { base, index } => { self.write_expr(base, ctx)?; - let mut resolved = ctx.typifier.get(base, &self.module.types); + let base_ty_res = &ctx.info[base].ty; + let mut resolved = base_ty_res.inner_with(&self.module.types); let base_ty_handle = match *resolved { TypeInner::Pointer { base, class: _ } => { resolved = &self.module.types[base].inner; - Ok(base) + Some(base) } - _ => ctx.typifier.get_handle(base), + _ => base_ty_res.handle(), }; match *resolved { @@ -1576,7 +1562,7 @@ impl<'a, W: Write> Writer<'a, W> { // We need to get the coordinates vector size to later build a vector that's `size + 1` // if `depth_ref` is some, if it isn't a vector we panic as that's not a valid expression - let size = match *ctx.typifier.get(coordinate, &self.module.types) { + let size = match *ctx.info[coordinate].ty.inner_with(&self.module.types) { TypeInner::Vector { size, .. } => size, _ => unreachable!(), }; @@ -1652,7 +1638,7 @@ impl<'a, W: Write> Writer<'a, W> { index, } => { // This will only panic if the module is invalid - let (dim, class) = match *ctx.typifier.get(image, &self.module.types) { + let (dim, class) = match *ctx.info[image].ty.inner_with(&self.module.types) { TypeInner::Image { dim, arrayed: _, @@ -1685,7 +1671,7 @@ impl<'a, W: Write> Writer<'a, W> { // - textureSamples/imageSamples Expression::ImageQuery { image, query } => { // This will only panic if the module is invalid - let (dim, class) = match *ctx.typifier.get(image, &self.module.types) { + let (dim, class) = match *ctx.info[image].ty.inner_with(&self.module.types) { TypeInner::Image { dim, arrayed: _, @@ -1759,25 +1745,26 @@ impl<'a, W: Write> Writer<'a, W> { "({} ", match op { UnaryOperator::Negate => "-", - UnaryOperator::Not => match *ctx.typifier.get(expr, &self.module.types) { - TypeInner::Scalar { - kind: ScalarKind::Sint, - .. - } => "~", - TypeInner::Scalar { - kind: ScalarKind::Uint, - .. - } => "~", - TypeInner::Scalar { - kind: ScalarKind::Bool, - .. - } => "!", - ref other => - return Err(Error::Custom(format!( - "Cannot apply not to type {:?}", - other - ))), - }, + UnaryOperator::Not => + match *ctx.info[expr].ty.inner_with(&self.module.types) { + TypeInner::Scalar { + kind: ScalarKind::Sint, + .. + } => "~", + TypeInner::Scalar { + kind: ScalarKind::Uint, + .. + } => "~", + TypeInner::Scalar { + kind: ScalarKind::Bool, + .. + } => "!", + ref other => + return Err(Error::Custom(format!( + "Cannot apply not to type {:?}", + other + ))), + }, } )?; @@ -1793,8 +1780,8 @@ impl<'a, W: Write> Writer<'a, W> { // Holds `Some(function_name)` if the binary operation is // implemented as a function call let function = if let (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) = ( - ctx.typifier.get(left, &self.module.types), - ctx.typifier.get(right, &self.module.types), + ctx.info[left].ty.inner_with(&self.module.types), + ctx.info[right].ty.inner_with(&self.module.types), ) { match op { BinaryOperator::Less => Some("lessThan"), @@ -1979,7 +1966,7 @@ impl<'a, W: Write> Writer<'a, W> { kind, convert, } => { - let inner = ctx.typifier.get(expr, &self.module.types); + let inner = ctx.info[expr].ty.inner_with(&self.module.types); if convert { // this is similar to `write_type`, but with the target kind match *inner { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index f9c8e7eb1..f6246da9c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,7 +1,7 @@ use super::{keywords::RESERVED, Error, LocationMode, Options, TranslationInfo}; use crate::{ arena::Handle, - proc::{EntryPointIndex, NameKey, Namer, ResolveContext, Typifier}, + proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, GlobalUse, ModuleInfo}, FastHashMap, }; @@ -68,7 +68,6 @@ pub struct Writer { out: W, names: FastHashMap, named_expressions: BitSet, - typifier: Typifier, namer: Namer, #[cfg(test)] put_expression_stack_pointers: crate::FastHashSet<*const ()>, @@ -138,13 +137,19 @@ enum FunctionOrigin { struct ExpressionContext<'a> { function: &'a crate::Function, origin: FunctionOrigin, + info: &'a FunctionInfo, module: &'a crate::Module, - mod_info: &'a ModuleInfo, +} + +impl<'a> ExpressionContext<'a> { + fn resolve_type(&self, handle: Handle) -> &'a crate::TypeInner { + self.info[handle].ty.inner_with(&self.module.types) + } } struct StatementContext<'a> { expression: ExpressionContext<'a>, - fun_info: &'a FunctionInfo, + mod_info: &'a ModuleInfo, result_struct: Option<&'a str>, } @@ -155,7 +160,6 @@ impl Writer { out, names: FastHashMap::default(), named_expressions: BitSet::new(), - typifier: Typifier::new(), namer: Namer::default(), #[cfg(test)] put_expression_stack_pointers: Default::default(), @@ -226,13 +230,14 @@ impl Writer { } crate::Expression::AccessIndex { base, index } => { self.put_expression(base, context)?; - let mut resolved = self.typifier.get(base, &context.module.types); + let base_res = &context.info[base].ty; + let mut resolved = base_res.inner_with(&context.module.types); let base_ty_handle = match *resolved { crate::TypeInner::Pointer { base, class: _ } => { resolved = &context.module.types[base].inner; - Ok(base) + Some(base) } - _ => self.typifier.get_handle(base), + _ => base_res.handle(), }; match *resolved { crate::TypeInner::Struct { .. } => { @@ -410,7 +415,7 @@ impl Writer { crate::ImageQuery::Size { level } => { //Note: MSL only has separate width/height/depth queries, // so compose the result of them. - let dim = match *self.typifier.get(image, &context.module.types) { + let dim = match *context.resolve_type(image) { crate::TypeInner::Image { dim, .. } => dim, ref other => unreachable!("Unexpected type {:?}", other), }; @@ -488,9 +493,8 @@ impl Writer { crate::BinaryOperator::ShiftLeft => "<<", crate::BinaryOperator::ShiftRight => ">>", }; - let kind = self - .typifier - .get(left, &context.module.types) + let kind = context + .resolve_type(left) .scalar_kind() .ok_or(Error::UnsupportedBinaryOp(op))?; if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float { @@ -615,7 +619,7 @@ impl Writer { convert, } => { let scalar = scalar_kind_string(kind); - let size = match *self.typifier.get(expr, &context.module.types) { + let size = match *context.resolve_type(expr) { crate::TypeInner::Scalar { .. } => "", crate::TypeInner::Vector { size, .. } => vector_size_string(size), _ => return Err(Error::Validation), @@ -627,37 +631,39 @@ impl Writer { } // has to be a named expression crate::Expression::Call(_) => unreachable!(), - crate::Expression::ArrayLength(expr) => { - match *self.typifier.get(expr, &context.module.types) { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(const_handle), - .. - } => { - let size_str = &self.names[&NameKey::Constant(const_handle)]; - write!(self.out, "{}", size_str)?; - } - crate::TypeInner::Array { .. } => { - return Err(Error::FeatureNotImplemented( - "dynamic array size".to_string(), - )) - } - _ => return Err(Error::Validation), + crate::Expression::ArrayLength(expr) => match *context.resolve_type(expr) { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(const_handle), + .. + } => { + let size_str = &self.names[&NameKey::Constant(const_handle)]; + write!(self.out, "{}", size_str)?; } - } + crate::TypeInner::Array { .. } => { + return Err(Error::FeatureNotImplemented( + "dynamic array size".to_string(), + )) + } + _ => return Err(Error::Validation), + }, } Ok(()) } - fn start_baking_expression(&mut self, handle: Handle) -> Result<(), Error> { - match self.typifier.get_handle(handle) { - Ok(ty_handle) => { + fn start_baking_expression( + &mut self, + handle: Handle, + context: &ExpressionContext, + ) -> Result<(), Error> { + match context.info[handle].ty { + TypeResolution::Handle(ty_handle) => { let ty_name = &self.names[&NameKey::Type(ty_handle)]; write!(self.out, "{}", ty_name)?; } - Err(&crate::TypeInner::Scalar { kind, .. }) => { + TypeResolution::Value(crate::TypeInner::Scalar { kind, .. }) => { write!(self.out, "{}", scalar_kind_string(kind))?; } - Err(&crate::TypeInner::Vector { size, kind, .. }) => { + TypeResolution::Value(crate::TypeInner::Vector { size, kind, .. }) => { write!( self.out, "{}::{}{}", @@ -666,7 +672,7 @@ impl Writer { vector_size_string(size) )?; } - Err(other) => { + TypeResolution::Value(ref other) => { log::error!("Type {:?} isn't a known local", other); return Err(Error::FeatureNotImplemented("weird local type".to_string())); } @@ -690,9 +696,9 @@ impl Writer { for handle in range.clone() { let min_ref_count = context.expression.function.expressions[handle].bake_ref_count(); - if min_ref_count <= context.fun_info[handle].ref_count { + if min_ref_count <= context.expression.info[handle].ref_count { write!(self.out, "{}", level)?; - self.start_baking_expression(handle)?; + self.start_baking_expression(handle, &context.expression)?; self.put_expression(handle, &context.expression)?; writeln!(self.out, ";")?; self.named_expressions.insert(handle.index()); @@ -843,7 +849,7 @@ impl Writer { } => { write!(self.out, "{}", level)?; if let Some(expr) = result { - self.start_baking_expression(expr)?; + self.start_baking_expression(expr, &context.expression)?; self.named_expressions.insert(expr.index()); } let fun_name = &self.names[&NameKey::Function(function)]; @@ -857,7 +863,7 @@ impl Writer { } // follow-up with any global resources used let mut separate = !arguments.is_empty(); - let fun_info = &context.expression.mod_info[function]; + let fun_info = &context.mod_info[function]; for (handle, var) in context.expression.module.global_variables.iter() { if !fun_info[handle].is_empty() && var.class.needs_pass_through() { let name = &self.names[&NameKey::GlobalVariable(handle)]; @@ -1109,18 +1115,6 @@ impl Writer { ) -> Result { let mut pass_through_globals = Vec::new(); for (fun_handle, fun) in module.functions.iter() { - self.typifier.resolve_all( - &fun.expressions, - &module.types, - &ResolveContext { - constants: &module.constants, - global_vars: &module.global_variables, - local_vars: &fun.local_variables, - functions: &module.functions, - arguments: &fun.arguments, - }, - )?; - let fun_info = &mod_info[fun_handle]; pass_through_globals.clear(); for (handle, var) in module.global_variables.iter() { @@ -1176,10 +1170,10 @@ impl Writer { expression: ExpressionContext { function: fun, origin: FunctionOrigin::Handle(fun_handle), + info: fun_info, module, - mod_info, }, - fun_info, + mod_info, result_struct: None, }; self.named_expressions.clear(); @@ -1215,18 +1209,6 @@ impl Writer { } } - self.typifier.resolve_all( - &fun.expressions, - &module.types, - &ResolveContext { - constants: &module.constants, - global_vars: &module.global_variables, - local_vars: &fun.local_variables, - functions: &module.functions, - arguments: &fun.arguments, - }, - )?; - let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; info.entry_point_names.push(Ok(fun_name.clone())); @@ -1468,10 +1450,10 @@ impl Writer { expression: ExpressionContext { function: fun, origin: FunctionOrigin::EntryPoint(ep_index as _), + info: fun_info, module, - mod_info, }, - fun_info, + mod_info, result_struct: Some(&stage_out_name), }; self.named_expressions.clear(); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 912a840a1..5e065e1ca 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2,7 +2,7 @@ use super::{Instruction, LogicalLayout, Options, PhysicalLayout, WriterFlags}; use crate::{ arena::{Arena, Handle}, - proc::{Layouter, ResolveContext, Typifier, TypifyError}, + proc::{Layouter, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, }; use spirv::Word; @@ -19,8 +19,6 @@ pub enum Error { MissingCapabilities(Vec), #[error("unimplemented {0}")] FeatureNotImplemented(&'static str), - #[error(transparent)] - Resolve(#[from] TypifyError), } struct Block { @@ -263,7 +261,6 @@ pub struct Writer { struct_type_handles: crate::FastHashMap, crate::StorageAccess>, gl450_ext_inst_id: Word, layouter: Layouter, - typifier: Typifier, temp_chain: Vec, } @@ -295,7 +292,6 @@ impl Writer { struct_type_handles: crate::FastHashMap::default(), gl450_ext_inst_id, layouter: Layouter::default(), - typifier: Typifier::new(), temp_chain: Vec::new(), }) } @@ -378,18 +374,6 @@ impl Writer { ) -> Result { let mut function = Function::default(); - self.typifier.resolve_all( - &ir_function.expressions, - &ir_module.types, - &ResolveContext { - constants: &ir_module.constants, - global_vars: &ir_module.global_variables, - local_vars: &ir_function.local_variables, - functions: &ir_module.functions, - arguments: &ir_function.arguments, - }, - )?; - for (handle, variable) in ir_function.local_variables.iter() { let id = self.generate_id(); @@ -559,6 +543,7 @@ impl Writer { self.cache_expression_value( ir_module, ir_function, + info, handle, &mut prelude, &mut function, @@ -573,6 +558,7 @@ impl Writer { &ir_function.body, ir_module, ir_function, + info, &mut function, None, LoopContext::default(), @@ -1209,6 +1195,7 @@ impl Writer { fn write_texture_coordinates( &mut self, ir_module: &crate::Module, + fun_info: &FunctionInfo, coordinates: Handle, array_index: Option>, block: &mut Block, @@ -1227,7 +1214,7 @@ impl Writer { )?; let mut constituent_ids = [0u32; 4]; - let size = match *self.typifier.get(coordinates, &ir_module.types) { + let size = match *fun_info[coordinates].ty.inner_with(&ir_module.types) { crate::TypeInner::Scalar { .. } => { constituent_ids[0] = coordinate_id; crate::VectorSize::Bi @@ -1291,13 +1278,16 @@ impl Writer { &mut self, ir_module: &'a crate::Module, ir_function: &crate::Function, + fun_info: &FunctionInfo, expr_handle: Handle, block: &mut Block, function: &mut Function, ) -> Result<(), Error> { - let result_lookup_ty = match self.typifier.get_handle(expr_handle) { - Ok(ty_handle) => LookupType::Handle(ty_handle), - Err(inner) => LookupType::Local(self.physical_layout.make_local(inner).unwrap()), + let result_lookup_ty = match fun_info[expr_handle].ty { + TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), + TypeResolution::Value(ref inner) => { + LookupType::Local(self.physical_layout.make_local(inner).unwrap()) + } }; let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; @@ -1313,7 +1303,7 @@ impl Writer { 0 } else { let index_id = self.cached[index]; - match *self.typifier.get(base, &ir_module.types) { + match *fun_info[base].ty.inner_with(&ir_module.types) { crate::TypeInner::Vector { .. } => { let id = self.generate_id(); let base_id = self.cached[base]; @@ -1343,7 +1333,7 @@ impl Writer { if base_is_var { 0 } else { - match *self.typifier.get(base, &ir_module.types) { + match *fun_info[base].ty.inner_with(&ir_module.types) { crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } | crate::TypeInner::Array { .. } @@ -1382,7 +1372,7 @@ impl Writer { crate::Expression::Unary { op, expr } => { let id = self.generate_id(); let expr_id = self.cached[expr]; - let expr_ty_inner = self.typifier.get(expr, &ir_module.types); + let expr_ty_inner = fun_info[expr].ty.inner_with(&ir_module.types); let spirv_op = match op { crate::UnaryOperator::Negate => match expr_ty_inner.scalar_kind() { @@ -1407,8 +1397,8 @@ impl Writer { let left_id = self.cached[left]; let right_id = self.cached[right]; - let left_ty_inner = self.typifier.get(left, &ir_module.types); - let right_ty_inner = self.typifier.get(right, &ir_module.types); + let left_ty_inner = fun_info[left].ty.inner_with(&ir_module.types); + let right_ty_inner = fun_info[right].ty.inner_with(&ir_module.types); let left_dimension = get_dimension(left_ty_inner); let right_dimension = get_dimension(right_ty_inner); @@ -1543,7 +1533,7 @@ impl Writer { } let arg0_id = self.cached[arg]; - let arg_scalar_kind = self.typifier.get(arg, &ir_module.types).scalar_kind(); + let arg_scalar_kind = fun_info[arg].ty.inner_with(&ir_module.types).scalar_kind(); let arg1_id = match arg1 { Some(handle) => self.cached[handle], None => 0, @@ -1672,6 +1662,7 @@ impl Writer { let (pointer_id, _) = self.write_expression_pointer( ir_module, ir_function, + fun_info, pointer, block, function, @@ -1694,9 +1685,9 @@ impl Writer { convert, } => { let expr_id = self.cached[expr]; - let expr_kind = self - .typifier - .get(expr, &ir_module.types) + let expr_kind = fun_info[expr] + .ty + .inner_with(&ir_module.types) .scalar_kind() .unwrap(); @@ -1722,12 +1713,17 @@ impl Writer { index, } => { let image_id = self.get_expression_global(ir_function, image); - let coordinate_id = - self.write_texture_coordinates(ir_module, coordinate, array_index, block)?; + let coordinate_id = self.write_texture_coordinates( + ir_module, + fun_info, + coordinate, + array_index, + block, + )?; let id = self.generate_id(); - let image_ty = self.typifier.get(image, &ir_module.types); + let image_ty = fun_info[image].ty.inner_with(&ir_module.types); let mut instruction = match *image_ty { crate::TypeInner::Image { class: crate::ImageClass::Storage { .. }, @@ -1738,7 +1734,7 @@ impl Writer { if let Some(index) = index { let index_id = self.cached[index]; - let image_ops = match *self.typifier.get(image, &ir_module.types) { + let image_ops = match *fun_info[image].ty.inner_with(&ir_module.types) { crate::TypeInner::Image { class: crate::ImageClass::Sampled { multi: true, .. }, .. @@ -1764,7 +1760,7 @@ impl Writer { use super::instructions::SampleLod; // image let image_id = self.get_expression_global(ir_function, image); - let image_type = self.typifier.get_handle(image).unwrap(); + let image_type = fun_info[image].ty.handle().unwrap(); // OpTypeSampledImage let sampled_image_type_id = self.get_type_id( @@ -1773,8 +1769,13 @@ impl Writer { )?; let sampler_id = self.get_expression_global(ir_function, sampler); - let coordinate_id = - self.write_texture_coordinates(ir_module, coordinate, array_index, block)?; + let coordinate_id = self.write_texture_coordinates( + ir_module, + fun_info, + coordinate, + array_index, + block, + )?; let sampled_image_id = self.generate_id(); block.body.push(Instruction::sampled_image( @@ -1921,13 +1922,16 @@ impl Writer { &mut self, ir_module: &'a crate::Module, ir_function: &crate::Function, + fun_info: &FunctionInfo, mut expr_handle: Handle, block: &mut Block, function: &mut Function, ) -> Result<(Word, spirv::StorageClass), Error> { - let result_lookup_ty = match self.typifier.get_handle(expr_handle) { - Ok(ty_handle) => LookupType::Handle(ty_handle), - Err(inner) => LookupType::Local(self.physical_layout.make_local(inner).unwrap()), + let result_lookup_ty = match fun_info[expr_handle].ty { + TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), + TypeResolution::Value(ref inner) => { + LookupType::Local(self.physical_layout.make_local(inner).unwrap()) + } }; let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; @@ -1998,6 +2002,7 @@ impl Writer { } } + //TODO: put most of these into a `BlockContext` structure! #[allow(clippy::too_many_arguments)] fn write_block( &mut self, @@ -2005,6 +2010,7 @@ impl Writer { statements: &[crate::Statement], ir_module: &crate::Module, ir_function: &crate::Function, + fun_info: &FunctionInfo, function: &mut Function, exit_id: Option, loop_context: LoopContext, @@ -2021,6 +2027,7 @@ impl Writer { self.cache_expression_value( ir_module, ir_function, + fun_info, handle, &mut block, function, @@ -2037,6 +2044,7 @@ impl Writer { block_statements, ir_module, ir_function, + fun_info, function, Some(merge_id), loop_context, @@ -2083,6 +2091,7 @@ impl Writer { accept, ir_module, ir_function, + fun_info, function, Some(merge_id), loop_context, @@ -2094,6 +2103,7 @@ impl Writer { reject, ir_module, ir_function, + fun_info, function, Some(merge_id), loop_context, @@ -2143,6 +2153,7 @@ impl Writer { &case.body, ir_module, ir_function, + fun_info, function, Some(case_finish_id), LoopContext::default(), @@ -2154,6 +2165,7 @@ impl Writer { default, ir_module, ir_function, + fun_info, function, Some(merge_id), LoopContext::default(), @@ -2187,6 +2199,7 @@ impl Writer { body, ir_module, ir_function, + fun_info, function, Some(continuing_id), LoopContext { @@ -2200,6 +2213,7 @@ impl Writer { continuing, ir_module, ir_function, + fun_info, function, Some(preamble_id), LoopContext { @@ -2263,6 +2277,7 @@ impl Writer { let (pointer_id, _) = self.write_expression_pointer( ir_module, ir_function, + fun_info, pointer, &mut block, function, @@ -2282,6 +2297,7 @@ impl Writer { let image_id = self.get_expression_global(ir_function, image); let coordinate_id = self.write_texture_coordinates( ir_module, + fun_info, coordinate, array_index, &mut block, From 6086f13bf0532d439d4beb58e17e0e5531d41eab Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 22 Mar 2021 13:46:06 -0400 Subject: [PATCH 0608/2212] Move the growable typifier into frontend helpers --- src/back/glsl/mod.rs | 5 +- src/back/msl/mod.rs | 4 +- src/front/glsl/ast.rs | 9 +- src/front/glsl/functions.rs | 6 +- src/front/mod.rs | 48 ++++++++- src/front/wgsl/mod.rs | 8 +- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 189 ++++++++++-------------------------- src/valid/analyzer.rs | 5 +- 9 files changed, 111 insertions(+), 165 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 54c5c7e58..222ba8e40 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -44,7 +44,7 @@ pub use features::Features; use crate::{ - proc::{EntryPointIndex, NameKey, Namer, TypeResolution, TypifyError}, + proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, @@ -270,9 +270,6 @@ pub enum Error { /// A error occurred while writing to the output #[error("I/O error")] IoError(#[from] IoError), - /// The [`Module`](crate::Module) failed type resolution - #[error("Type error")] - Type(#[from] TypifyError), /// The specified [`Version`](Version) doesn't have all required [`Features`](super) /// /// Contains the missing [`Features`](Features) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index b651a25d7..dd424eee8 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -23,7 +23,7 @@ For the result type, if it's a structure, we re-compose it with a temporary valu holding the result. !*/ -use crate::{arena::Handle, proc::TypifyError, valid::ModuleInfo, FastHashMap}; +use crate::{arena::Handle, valid::ModuleInfo, FastHashMap}; use std::{ fmt::{Error as FmtError, Write}, string::FromUtf8Error, @@ -67,8 +67,6 @@ pub enum Error { Format(#[from] FmtError), #[error(transparent)] Utf8(#[from] FromUtf8Error), - #[error(transparent)] - Type(#[from] TypifyError), #[error("bind target {0:?} is empty")] UnimplementedBindTarget(BindTarget), #[error("composing of {0:?} is not implemented yet")] diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index ab592495f..78f914af5 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,9 +1,8 @@ -use super::{constants::ConstantSolver, error::ErrorKind}; +use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind}; use crate::{ - proc::{ResolveContext, Typifier}, - Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, FunctionArgument, - GlobalVariable, Handle, Interpolation, LocalVariable, Module, RelationalFunction, - ResourceBinding, ShaderStage, Statement, StorageClass, Type, UnaryOperator, + proc::ResolveContext, Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, + Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, + RelationalFunction, ResourceBinding, ShaderStage, Statement, StorageClass, Type, UnaryOperator, }; #[derive(Debug)] diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 1c25b5d2a..e1492e84b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,7 +1,7 @@ +use super::super::Typifier; use crate::{ - proc::{ensure_block_returns, Typifier}, - BinaryOperator, Block, EntryPoint, Expression, Function, MathFunction, RelationalFunction, - SampleLevel, TypeInner, + proc::ensure_block_returns, BinaryOperator, Block, EntryPoint, Expression, Function, + MathFunction, RelationalFunction, SampleLevel, TypeInner, }; use super::{ast::*, error::ErrorKind}; diff --git a/src/front/mod.rs b/src/front/mod.rs index 4177bddcb..aa39bc259 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -7,6 +7,11 @@ pub mod spv; #[cfg(feature = "wgsl-in")] pub mod wgsl; +use crate::{ + arena::{Arena, Handle}, + proc::{ResolveContext, ResolveError, TypeResolution}, +}; + /// Helper class to emit expressions #[allow(dead_code)] #[derive(Default)] @@ -16,14 +21,14 @@ struct Emitter { #[allow(dead_code)] impl Emitter { - fn start(&mut self, arena: &crate::Arena) { + fn start(&mut self, arena: &Arena) { if self.start_len.is_some() { unreachable!("Emitting has already started!"); } self.start_len = Some(arena.len()); } #[must_use] - fn finish(&mut self, arena: &crate::Arena) -> Option { + fn finish(&mut self, arena: &Arena) -> Option { let start_len = self.start_len.take().unwrap(); if start_len != arena.len() { Some(crate::Statement::Emit(arena.range_from(start_len))) @@ -42,3 +47,42 @@ impl super::ConstantInner { } } } + +/// Helper processor that derives the types of all expressions. +#[derive(Debug)] +pub struct Typifier { + resolutions: Vec, +} + +impl Typifier { + pub fn new() -> Self { + Typifier { + resolutions: Vec::new(), + } + } + + pub fn get<'a>( + &'a self, + expr_handle: Handle, + types: &'a Arena, + ) -> &'a crate::TypeInner { + self.resolutions[expr_handle.index()].inner_with(types) + } + + pub fn grow( + &mut self, + expr_handle: Handle, + expressions: &Arena, + types: &mut Arena, + ctx: &ResolveContext, + ) -> Result<(), ResolveError> { + if self.resolutions.len() <= expr_handle.index() { + for (eh, expr) in expressions.iter().skip(self.resolutions.len()) { + let resolution = ctx.resolve(expr, types, |h| &self.resolutions[h.index()])?; + log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); + self.resolutions.push(resolution); + } + } + Ok(()) + } +} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e54fac72a..8bae91cff 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -9,7 +9,7 @@ mod tests; use crate::{ arena::{Arena, Handle}, - proc::{ensure_block_returns, ResolveContext, ResolveError, Typifier}, + proc::{ensure_block_returns, ResolveContext, ResolveError}, FastHashMap, }; @@ -199,7 +199,7 @@ impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle { lookup_ident: &'temp mut FastHashMap<&'input str, Handle>, - typifier: &'temp mut Typifier, + typifier: &'temp mut super::Typifier, variables: &'out mut Arena, expressions: &'out mut Arena, types: &'out mut Arena, @@ -255,7 +255,7 @@ struct SamplingContext { struct ExpressionContext<'input, 'temp, 'out> { lookup_ident: &'temp FastHashMap<&'input str, Handle>, - typifier: &'temp mut Typifier, + typifier: &'temp mut super::Typifier, expressions: &'out mut Arena, types: &'out mut Arena, constants: &'out mut Arena, @@ -2434,7 +2434,7 @@ impl Parser { }; // read body - let mut typifier = Typifier::new(); + let mut typifier = super::Typifier::new(); fun.body = self.parse_block( lexer, StatementContext { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 5e8a2550c..baab6c3be 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -8,7 +8,7 @@ mod typifier; pub use layouter::{Alignment, Layouter}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; -pub use typifier::{ResolveContext, ResolveError, TypeResolution, Typifier, TypifyError}; +pub use typifier::{ResolveContext, ResolveError, TypeResolution}; impl From for super::ScalarKind { fn from(format: super::StorageFormat) -> Self { diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index f1a07a374..0bf23993c 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -62,12 +62,6 @@ impl Clone for TypeResolution { } } -/// Helper processor that derives the types of all expressions. -#[derive(Debug)] -pub struct Typifier { - resolutions: Vec, -} - #[derive(Clone, Debug, Error, PartialEq)] pub enum ResolveError { #[error("Index {index} is out of bounds for expression {expr:?}")] @@ -99,12 +93,6 @@ pub enum ResolveError { IncompatibleOperands(String), } -//TODO: remove this -#[repr(C)] // pack this tighter: 48 -> 40 bytes -#[derive(Clone, Debug, Error, PartialEq)] -#[error("Type resolution of {0:?} failed")] -pub struct TypifyError(Handle, #[source] ResolveError); - pub struct ResolveContext<'a> { pub constants: &'a Arena, pub global_vars: &'a Arena, @@ -113,34 +101,34 @@ pub struct ResolveContext<'a> { pub arguments: &'a [crate::FunctionArgument], } -impl TypeResolution { - pub fn new<'a>( +impl<'a> ResolveContext<'a> { + pub fn resolve( + &self, expr: &crate::Expression, types: &'a Arena, - ctx: &ResolveContext, - past: impl Fn(Handle) -> &'a Self, - ) -> Result { + past: impl Fn(Handle) -> &'a TypeResolution, + ) -> Result { use crate::TypeInner as Ti; Ok(match *expr { crate::Expression::Access { base, .. } => match *past(base).inner_with(types) { - Ti::Array { base, .. } => Self::Handle(base), + Ti::Array { base, .. } => TypeResolution::Handle(base), Ti::Vector { size: _, kind, width, - } => Self::Value(Ti::Scalar { kind, width }), + } => TypeResolution::Value(Ti::Scalar { kind, width }), Ti::ValuePointer { size: Some(_), kind, width, class, - } => Self::Value(Ti::ValuePointer { + } => TypeResolution::Value(Ti::ValuePointer { size: None, kind, width, class, }), - Ti::Pointer { base, class } => Self::Value(match types[base].inner { + Ti::Pointer { base, class } => TypeResolution::Value(match types[base].inner { Ti::Array { base, .. } => Ti::Pointer { base, class }, Ti::Vector { size: _, @@ -173,7 +161,7 @@ impl TypeResolution { if index >= size as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } - Self::Value(Ti::Scalar { kind, width }) + TypeResolution::Value(Ti::Scalar { kind, width }) } Ti::Matrix { columns, @@ -183,13 +171,13 @@ impl TypeResolution { if index >= columns as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } - Self::Value(crate::TypeInner::Vector { + TypeResolution::Value(crate::TypeInner::Vector { size: rows, kind: crate::ScalarKind::Float, width, }) } - Ti::Array { base, .. } => Self::Handle(base), + Ti::Array { base, .. } => TypeResolution::Handle(base), Ti::Struct { block: _, ref members, @@ -197,7 +185,7 @@ impl TypeResolution { let member = members .get(index as usize) .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; - Self::Handle(member.ty) + TypeResolution::Handle(member.ty) } Ti::ValuePointer { size: Some(size), @@ -208,7 +196,7 @@ impl TypeResolution { if index >= size as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } - Self::Value(Ti::ValuePointer { + TypeResolution::Value(Ti::ValuePointer { size: None, kind, width, @@ -218,7 +206,7 @@ impl TypeResolution { Ti::Pointer { base: ty_base, class, - } => Self::Value(match types[ty_base].inner { + } => TypeResolution::Value(match types[ty_base].inner { Ti::Array { base, .. } => Ti::Pointer { base, class }, Ti::Vector { size, kind, width } => { if index >= size as u32 { @@ -274,43 +262,45 @@ impl TypeResolution { }); } }, - crate::Expression::Constant(h) => match ctx.constants[h].inner { - crate::ConstantInner::Scalar { width, ref value } => Self::Value(Ti::Scalar { - kind: value.scalar_kind(), - width, - }), - crate::ConstantInner::Composite { ty, components: _ } => Self::Handle(ty), + crate::Expression::Constant(h) => match self.constants[h].inner { + crate::ConstantInner::Scalar { width, ref value } => { + TypeResolution::Value(Ti::Scalar { + kind: value.scalar_kind(), + width, + }) + } + crate::ConstantInner::Composite { ty, components: _ } => TypeResolution::Handle(ty), }, - crate::Expression::Compose { ty, .. } => Self::Handle(ty), + crate::Expression::Compose { ty, .. } => TypeResolution::Handle(ty), crate::Expression::FunctionArgument(index) => { - Self::Handle(ctx.arguments[index as usize].ty) + TypeResolution::Handle(self.arguments[index as usize].ty) } crate::Expression::GlobalVariable(h) => { - let var = &ctx.global_vars[h]; + let var = &self.global_vars[h]; if var.class == crate::StorageClass::Handle { - Self::Handle(var.ty) + TypeResolution::Handle(var.ty) } else { - Self::Value(Ti::Pointer { + TypeResolution::Value(Ti::Pointer { base: var.ty, class: var.class, }) } } crate::Expression::LocalVariable(h) => { - let var = &ctx.local_vars[h]; - Self::Value(Ti::Pointer { + let var = &self.local_vars[h]; + TypeResolution::Value(Ti::Pointer { base: var.ty, class: crate::StorageClass::Function, }) } crate::Expression::Load { pointer } => match *past(pointer).inner_with(types) { - Ti::Pointer { base, class: _ } => Self::Handle(base), + Ti::Pointer { base, class: _ } => TypeResolution::Handle(base), Ti::ValuePointer { size, kind, width, class: _, - } => Self::Value(match size { + } => TypeResolution::Value(match size { Some(size) => Ti::Vector { size, kind, width }, None => Ti::Scalar { kind, width }, }), @@ -321,7 +311,7 @@ impl TypeResolution { }, crate::Expression::ImageSample { image, .. } | crate::Expression::ImageLoad { image, .. } => match *past(image).inner_with(types) { - Ti::Image { class, .. } => Self::Value(match class { + Ti::Image { class, .. } => TypeResolution::Value(match class { crate::ImageClass::Depth => Ti::Scalar { kind: crate::ScalarKind::Float, width: 4, @@ -342,7 +332,7 @@ impl TypeResolution { return Err(ResolveError::InvalidImage(image)); } }, - crate::Expression::ImageQuery { image, query } => Self::Value(match query { + crate::Expression::ImageQuery { image, query } => TypeResolution::Value(match query { crate::ImageQuery::Size { level: _ } => match *past(image).inner_with(types) { Ti::Image { dim, .. } => match dim { crate::ImageDimension::D1 => Ti::Scalar { @@ -395,7 +385,7 @@ impl TypeResolution { width, } = *ty_left { - Self::Value(Ti::Vector { + TypeResolution::Value(Ti::Vector { size: rows, kind: crate::ScalarKind::Float, width, @@ -406,7 +396,7 @@ impl TypeResolution { width, } = *ty_right { - Self::Value(Ti::Vector { + TypeResolution::Value(Ti::Vector { size: columns, kind: crate::ScalarKind::Float, width, @@ -438,7 +428,7 @@ impl TypeResolution { ))) } }; - Self::Value(inner) + TypeResolution::Value(inner) } crate::BinaryOperator::And | crate::BinaryOperator::ExclusiveOr @@ -448,7 +438,7 @@ impl TypeResolution { }, crate::Expression::Select { accept, .. } => past(accept).clone(), crate::Expression::Derivative { axis: _, expr } => past(expr).clone(), - crate::Expression::Relational { .. } => Self::Value(Ti::Scalar { + crate::Expression::Relational { .. } => TypeResolution::Value(Ti::Scalar { kind: crate::ScalarKind::Bool, width: 4, }), @@ -498,7 +488,7 @@ impl TypeResolution { kind, size: _, width, - } => Self::Value(Ti::Scalar { kind, width }), + } => TypeResolution::Value(Ti::Scalar { kind, width }), ref other => return Err(ResolveError::IncompatibleOperands( format!("{:?}({:?}, _)", fun, other) @@ -509,7 +499,7 @@ impl TypeResolution { format!("{:?}(_, None)", fun) ))?; match (res_arg.inner_with(types), past(arg1).inner_with(types)) { - (&Ti::Vector {kind: _, size: columns,width}, &Ti::Vector{ size: rows, .. }) => Self::Value(Ti::Matrix { columns, rows, width }), + (&Ti::Vector {kind: _, size: columns,width}, &Ti::Vector{ size: rows, .. }) => TypeResolution::Value(Ti::Matrix { columns, rows, width }), (left, right) => return Err(ResolveError::IncompatibleOperands( format!("{:?}({:?}, {:?})", fun, left, right) @@ -520,7 +510,7 @@ impl TypeResolution { Mf::Distance | Mf::Length => match *res_arg.inner_with(types) { Ti::Scalar {width,kind} | - Ti::Vector {width,kind,size:_} => Self::Value(Ti::Scalar { kind, width }), + Ti::Vector {width,kind,size:_} => TypeResolution::Value(Ti::Scalar { kind, width }), ref other => return Err(ResolveError::IncompatibleOperands( format!("{:?}({:?})", fun, other) )), @@ -541,7 +531,7 @@ impl TypeResolution { columns, rows, width, - } => Self::Value(Ti::Matrix { + } => TypeResolution::Value(Ti::Matrix { columns: rows, rows: columns, width, @@ -555,7 +545,7 @@ impl TypeResolution { columns, rows, width, - } if columns == rows => Self::Value(Ti::Matrix { + } if columns == rows => TypeResolution::Value(Ti::Matrix { columns, rows, width, @@ -568,7 +558,7 @@ impl TypeResolution { Ti::Matrix { width, .. - } => Self::Value(Ti::Scalar { kind: crate::ScalarKind::Float, width }), + } => TypeResolution::Value(Ti::Scalar { kind: crate::ScalarKind::Float, width }), ref other => return Err(ResolveError::IncompatibleOperands( format!("{:?}({:?})", fun, other) )), @@ -583,12 +573,12 @@ impl TypeResolution { kind, convert: _, } => match *past(expr).inner_with(types) { - Ti::Scalar { kind: _, width } => Self::Value(Ti::Scalar { kind, width }), + Ti::Scalar { kind: _, width } => TypeResolution::Value(Ti::Scalar { kind, width }), Ti::Vector { kind: _, size, width, - } => Self::Value(Ti::Vector { kind, size, width }), + } => TypeResolution::Value(Ti::Vector { kind, size, width }), ref other => { return Err(ResolveError::IncompatibleOperands(format!( "{:?} as {:?}", @@ -597,13 +587,13 @@ impl TypeResolution { } }, crate::Expression::Call(function) => { - let result = ctx.functions[function] + let result = self.functions[function] .result .as_ref() .ok_or(ResolveError::FunctionReturnsVoid)?; - Self::Handle(result.ty) + TypeResolution::Handle(result.ty) } - crate::Expression::ArrayLength(_) => Self::Value(Ti::Scalar { + crate::Expression::ArrayLength(_) => TypeResolution::Value(Ti::Scalar { kind: crate::ScalarKind::Uint, width: 4, }), @@ -611,89 +601,8 @@ impl TypeResolution { } } -impl Typifier { - pub fn new() -> Self { - Typifier { - resolutions: Vec::new(), - } - } - - pub fn clear(&mut self) { - self.resolutions.clear() - } - - //TODO: remove most of these - pub fn get<'a>( - &'a self, - expr_handle: Handle, - types: &'a Arena, - ) -> &'a crate::TypeInner { - match self.resolutions[expr_handle.index()] { - TypeResolution::Handle(ty_handle) => &types[ty_handle].inner, - TypeResolution::Value(ref inner) => inner, - } - } - - pub fn try_get<'a>( - &'a self, - expr_handle: Handle, - types: &'a Arena, - ) -> Option<&'a crate::TypeInner> { - let resolution = self.resolutions.get(expr_handle.index())?; - Some(match *resolution { - TypeResolution::Handle(ty_handle) => &types[ty_handle].inner, - TypeResolution::Value(ref inner) => inner, - }) - } - - pub fn get_handle( - &self, - expr_handle: Handle, - ) -> Result, &crate::TypeInner> { - match self.resolutions[expr_handle.index()] { - TypeResolution::Handle(ty_handle) => Ok(ty_handle), - TypeResolution::Value(ref inner) => Err(inner), - } - } - - pub fn grow( - &mut self, - expr_handle: Handle, - expressions: &Arena, - types: &mut Arena, - ctx: &ResolveContext, - ) -> Result<(), ResolveError> { - if self.resolutions.len() <= expr_handle.index() { - for (eh, expr) in expressions.iter().skip(self.resolutions.len()) { - let resolution = - TypeResolution::new(expr, types, ctx, |h| &self.resolutions[h.index()])?; - log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); - self.resolutions.push(resolution); - } - } - Ok(()) - } - - pub fn resolve_all( - &mut self, - expressions: &Arena, - types: &Arena, - ctx: &ResolveContext, - ) -> Result<(), TypifyError> { - self.clear(); - for (handle, expr) in expressions.iter() { - let resolution = - TypeResolution::new(expr, types, ctx, |h| &self.resolutions[h.index()]) - .map_err(|err| TypifyError(handle, err))?; - self.resolutions.push(resolution); - } - Ok(()) - } -} - #[test] fn test_error_size() { use std::mem::size_of; assert_eq!(size_of::(), 32); - assert_eq!(size_of::(), 40); } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index bcb63316b..fba0df985 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -499,9 +499,8 @@ impl FunctionInfo { }, }; - let ty = TypeResolution::new(expression, type_arena, resolve_context, |h| { - &self.expressions[h.index()].ty - })?; + let ty = + resolve_context.resolve(expression, type_arena, |h| &self.expressions[h.index()].ty)?; self.expressions[handle.index()] = ExpressionInfo { uniformity, ref_count: 0, From 15a1941d6a7d8cf19893def8f38283c6a2cb2e5c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 22 Mar 2021 13:50:20 -0400 Subject: [PATCH 0609/2212] [msl-out] adjust error/stack size expectations --- src/back/msl/mod.rs | 9 ++------- src/back/msl/writer.rs | 4 ++-- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index dd424eee8..120e8532a 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -24,10 +24,7 @@ holding the result. !*/ use crate::{arena::Handle, valid::ModuleInfo, FastHashMap}; -use std::{ - fmt::{Error as FmtError, Write}, - string::FromUtf8Error, -}; +use std::fmt::{Error as FmtError, Write}; mod keywords; mod writer; @@ -65,8 +62,6 @@ enum ResolvedBinding { pub enum Error { #[error(transparent)] Format(#[from] FmtError), - #[error(transparent)] - Utf8(#[from] FromUtf8Error), #[error("bind target {0:?} is empty")] UnimplementedBindTarget(BindTarget), #[error("composing of {0:?} is not implemented yet")] @@ -248,5 +243,5 @@ pub fn write_string( #[test] fn test_error_size() { use std::mem::size_of; - assert_eq!(size_of::(), 48); + assert_eq!(size_of::(), 32); } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index f6246da9c..060f1a9cd 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1511,8 +1511,8 @@ fn test_stack_size() { } let stack_size = max_addr - min_addr; // check the size (in debug only) - // last observed macOS value: 25696 - if stack_size > 26000 { + // last observed macOS value: 20672 + if stack_size > 21000 { panic!("`put_expression` stack size {} is too large!", stack_size); } } From 8712020115b7817e213b07f4a6ea962644dc7dcf Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 22 Mar 2021 22:57:08 -0400 Subject: [PATCH 0610/2212] Move Layouter into ModuleInfo --- src/back/spv/writer.rs | 291 +++++++++++------------ src/proc/layouter.rs | 4 + src/proc/mod.rs | 2 +- src/valid/analyzer.rs | 7 - src/valid/mod.rs | 20 +- tests/out/boids.spvasm.snap | 342 ++++++++++++++-------------- tests/out/collatz.info.ron.snap | 20 ++ tests/out/collatz.spvasm.snap | 126 +++++----- tests/out/quad.spvasm.snap | 76 +++---- tests/out/shadow.info.ron.snap | 232 +++++++++++++++++++ tests/out/shadow.spvasm.snap | 258 ++++++++++----------- tests/out/skybox.spvasm.snap | 266 +++++++++++----------- tests/out/texture-array.spvasm.snap | 84 +++---- 13 files changed, 997 insertions(+), 731 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 5e065e1ca..cfc7e924b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -260,7 +260,6 @@ pub struct Writer { // so it may require us to duplicate the type! struct_type_handles: crate::FastHashMap, crate::StorageAccess>, gl450_ext_inst_id: Word, - layouter: Layouter, temp_chain: Vec, } @@ -291,7 +290,6 @@ impl Writer { cached: CachedExpressions::default(), struct_type_handles: crate::FastHashMap::default(), gl450_ext_inst_id, - layouter: Layouter::default(), temp_chain: Vec::new(), }) } @@ -322,12 +320,7 @@ impl Writer { Ok(*e.get()) } else { match lookup_ty { - LookupType::Handle(handle) => { - match self.physical_layout.make_local(&arena[handle].inner) { - Some(local) => self.get_type_id(arena, LookupType::Local(local)), - None => self.write_type_declaration_arena(arena, handle), - } - } + LookupType::Handle(_handle) => unreachable!("Handles are populated at start"), LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty), } } @@ -716,10 +709,28 @@ impl Writer { fn write_type_declaration_arena( &mut self, arena: &Arena, + layouter: &Layouter, handle: Handle, ) -> Result { let ty = &arena[handle]; + + if let Some(local) = self.physical_layout.make_local(&ty.inner) { + match self.lookup_type.entry(LookupType::Local(local)) { + // if it's already known as local, re-use it + Entry::Occupied(e) => { + let id = *e.into_mut(); + self.lookup_type.insert(LookupType::Handle(handle), id); + return Ok(id); + } + // also register the type as "local", to avoid duplication + Entry::Vacant(e) => { + let id = self.id_count + 1; // has to match the next ID + e.insert(id); + } + } + } let id = self.generate_id(); + self.lookup_type.insert(LookupType::Handle(handle), id); if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = ty.name { @@ -728,18 +739,7 @@ impl Writer { } let instruction = match ty.inner { - crate::TypeInner::Scalar { kind, width } => { - self.lookup_type.insert( - LookupType::Local(LocalType::Value { - vector_size: None, - kind, - width, - pointer_class: None, - }), - id, - ); - self.write_scalar(id, kind, width) - } + crate::TypeInner::Scalar { kind, width } => self.write_scalar(id, kind, width), crate::TypeInner::Vector { size, kind, width } => { let scalar_id = self.get_type_id( arena, @@ -750,15 +750,6 @@ impl Writer { pointer_class: None, }), )?; - self.lookup_type.insert( - LookupType::Local(LocalType::Value { - vector_size: Some(size), - kind, - width, - pointer_class: None, - }), - id, - ); Instruction::type_vector(id, scalar_id, size) } crate::TypeInner::Matrix { @@ -769,20 +760,12 @@ impl Writer { let vector_id = self.get_type_id( arena, LookupType::Local(LocalType::Value { - vector_size: Some(columns), + vector_size: Some(rows), kind: crate::ScalarKind::Float, width, pointer_class: None, }), )?; - self.lookup_type.insert( - LookupType::Local(LocalType::Matrix { - columns, - rows, - width, - }), - id, - ); Instruction::type_matrix(id, vector_id, columns) } crate::TypeInner::Image { @@ -842,7 +825,7 @@ impl Writer { let mut current_offset = 0; let mut member_ids = Vec::with_capacity(members.len()); for (index, member) in members.iter().enumerate() { - let (placement, _) = self.layouter.member_placement(current_offset, member); + let (placement, _) = layouter.member_placement(current_offset, member); self.annotations.push(Instruction::member_decorate( id, index as u32, @@ -901,13 +884,6 @@ impl Writer { crate::TypeInner::Pointer { base, class } => { let type_id = self.get_type_id(arena, LookupType::Handle(base))?; let raw_class = self.physical_layout.map_storage_class(class); - self.lookup_type.insert( - LookupType::Local(LocalType::Pointer { - base, - class: raw_class, - }), - id, - ); Instruction::type_pointer(id, raw_class, type_id) } crate::TypeInner::ValuePointer { @@ -926,106 +902,102 @@ impl Writer { pointer_class: None, }), )?; - self.lookup_type.insert( - LookupType::Local(LocalType::Value { - vector_size: size, - kind, - width, - pointer_class: Some(raw_class), - }), - id, - ); Instruction::type_pointer(id, raw_class, type_id) } }; - self.lookup_type.insert(LookupType::Handle(handle), id); instruction.to_words(&mut self.logical_layout.declarations); Ok(id) } - fn write_constant_type( + fn write_constant_scalar( &mut self, id: Word, - inner: &crate::ConstantInner, + value: &crate::ScalarValue, + width: crate::Bytes, types: &Arena, ) -> Result<(), Error> { - let instruction = match *inner { - crate::ConstantInner::Scalar { width, ref value } => { - let type_id = self.get_type_id( - types, - LookupType::Local(LocalType::Value { - vector_size: None, - kind: value.scalar_kind(), - width, - pointer_class: None, - }), - )?; - let (solo, pair); - match *value { - crate::ScalarValue::Sint(val) => { - let words = match width { - 4 => { - solo = [val as u32]; - &solo[..] - } - 8 => { - pair = [(val >> 32) as u32, val as u32]; - &pair - } - _ => unreachable!(), - }; - Instruction::constant(type_id, id, words) + let type_id = self.get_type_id( + types, + LookupType::Local(LocalType::Value { + vector_size: None, + kind: value.scalar_kind(), + width, + pointer_class: None, + }), + )?; + let (solo, pair); + let instruction = match *value { + crate::ScalarValue::Sint(val) => { + let words = match width { + 4 => { + solo = [val as u32]; + &solo[..] } - crate::ScalarValue::Uint(val) => { - let words = match width { - 4 => { - solo = [val as u32]; - &solo[..] - } - 8 => { - pair = [(val >> 32) as u32, val as u32]; - &pair - } - _ => unreachable!(), - }; - Instruction::constant(type_id, id, words) + 8 => { + pair = [(val >> 32) as u32, val as u32]; + &pair } - crate::ScalarValue::Float(val) => { - let words = match width { - 4 => { - solo = [(val as f32).to_bits()]; - &solo[..] - } - 8 => { - let bits = f64::to_bits(val); - pair = [(bits >> 32) as u32, bits as u32]; - &pair - } - _ => unreachable!(), - }; - Instruction::constant(type_id, id, words) - } - crate::ScalarValue::Bool(true) => Instruction::constant_true(type_id, id), - crate::ScalarValue::Bool(false) => Instruction::constant_false(type_id, id), - } + _ => unreachable!(), + }; + Instruction::constant(type_id, id, words) } - crate::ConstantInner::Composite { ty, ref components } => { - let mut constituent_ids = Vec::with_capacity(components.len()); - for constituent in components.iter() { - let constituent_id = self.lookup_constant[constituent]; - constituent_ids.push(constituent_id); - } - - let type_id = self.get_type_id(types, LookupType::Handle(ty))?; - Instruction::constant_composite(type_id, id, constituent_ids.as_slice()) + crate::ScalarValue::Uint(val) => { + let words = match width { + 4 => { + solo = [val as u32]; + &solo[..] + } + 8 => { + pair = [(val >> 32) as u32, val as u32]; + &pair + } + _ => unreachable!(), + }; + Instruction::constant(type_id, id, words) } + crate::ScalarValue::Float(val) => { + let words = match width { + 4 => { + solo = [(val as f32).to_bits()]; + &solo[..] + } + 8 => { + let bits = f64::to_bits(val); + pair = [(bits >> 32) as u32, bits as u32]; + &pair + } + _ => unreachable!(), + }; + Instruction::constant(type_id, id, words) + } + crate::ScalarValue::Bool(true) => Instruction::constant_true(type_id, id), + crate::ScalarValue::Bool(false) => Instruction::constant_false(type_id, id), }; instruction.to_words(&mut self.logical_layout.declarations); Ok(()) } + fn write_constant_composite( + &mut self, + id: Word, + ty: Handle, + components: &[Handle], + types: &Arena, + ) -> Result<(), Error> { + let mut constituent_ids = Vec::with_capacity(components.len()); + for constituent in components.iter() { + let constituent_id = self.lookup_constant[constituent]; + constituent_ids.push(constituent_id); + } + + let type_id = self.get_type_id(types, LookupType::Handle(ty))?; + Instruction::constant_composite(type_id, id, constituent_ids.as_slice()) + .to_words(&mut self.logical_layout.declarations); + Ok(()) + } + fn write_varying( &mut self, ir_module: &crate::Module, @@ -1108,9 +1080,8 @@ impl Writer { fn write_global_variable( &mut self, ir_module: &crate::Module, - handle: Handle, + global_variable: &crate::GlobalVariable, ) -> Result<(Instruction, Word, spirv::StorageClass), Error> { - let global_variable = &ir_module.global_variables[handle]; let id = self.generate_id(); let class = self @@ -1801,11 +1772,12 @@ impl Writer { //TODO: cache this! let zero_id = self.generate_id(); - let zero_inner = crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Float(0.0), - }; - self.write_constant_type(zero_id, &zero_inner, &ir_module.types)?; + self.write_constant_scalar( + zero_id, + &crate::ScalarValue::Float(0.0), + 4, + &ir_module.types, + )?; inst.add_operand(spirv::ImageOperands::LOD.bits()); inst.add_operand(zero_id); @@ -2375,23 +2347,57 @@ impl Writer { .push(Instruction::source(spirv::SourceLanguage::GLSL, 450)); } + // first, output all the scalar constants for (handle, constant) in ir_module.constants.iter() { - let id = self.generate_id(); - self.lookup_constant.insert(handle, id); - if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = constant.name { - self.debugs.push(Instruction::name(id, name)); + match constant.inner { + crate::ConstantInner::Composite { .. } => continue, + crate::ConstantInner::Scalar { width, ref value } => { + let id = self.generate_id(); + self.lookup_constant.insert(handle, id); + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = constant.name { + self.debugs.push(Instruction::name(id, name)); + } + } + self.write_constant_scalar(id, value, width, &ir_module.types)?; } } - self.write_constant_type(id, &constant.inner, &ir_module.types)?; } - self.global_variables.clear(); - for (handle, var) in ir_module.global_variables.iter() { + // then gather the struct type handles, then affect types + self.struct_type_handles.clear(); + for (_, var) in ir_module.global_variables.iter() { if let crate::TypeInner::Struct { .. } = ir_module.types[var.ty].inner { self.struct_type_handles.insert(var.ty, var.storage_access); } - let (instruction, id, class) = self.write_global_variable(ir_module, handle)?; + } + + // then all types, some of them may rely on constants and struct type set + for (handle, _) in ir_module.types.iter() { + self.write_type_declaration_arena(&ir_module.types, &mod_info.layouter, handle)?; + } + + // the all the composite constants, they rely on types + for (handle, constant) in ir_module.constants.iter() { + match constant.inner { + crate::ConstantInner::Scalar { .. } => continue, + crate::ConstantInner::Composite { ty, ref components } => { + let id = self.generate_id(); + self.lookup_constant.insert(handle, id); + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = constant.name { + self.debugs.push(Instruction::name(id, name)); + } + } + self.write_constant_composite(id, ty, components, &ir_module.types)?; + } + } + } + + // now write all globals + self.global_variables.clear(); + for (_, var) in ir_module.global_variables.iter() { + let (instruction, id, class) = self.write_global_variable(ir_module, var)?; instruction.to_words(&mut self.logical_layout.declarations); self.global_variables.push(GlobalVariable { id, @@ -2400,12 +2406,14 @@ impl Writer { }); } + // all functions for (handle, ir_function) in ir_module.functions.iter() { let info = &mod_info[handle]; let id = self.write_function(ir_function, info, ir_module, None)?; self.lookup_function.insert(handle, id); } + // and entry points for (ep_index, ir_ep) in ir_module.entry_points.iter().enumerate() { let info = mod_info.get_entry_point(ep_index); let ep_instruction = self.write_entry_point(ir_ep, info, ir_module)?; @@ -2447,9 +2455,6 @@ impl Writer { self.lookup_function_type.clear(); self.lookup_function_call.clear(); - self.layouter - .initialize(&ir_module.types, &ir_module.constants); - self.write_logical_layout(ir_module, info)?; self.write_physical_layout(); diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 697d119d9..8a90cc8f4 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -5,6 +5,8 @@ pub type Alignment = NonZeroU32; /// Alignment information for a type. #[derive(Clone, Copy, Debug, Hash, PartialEq)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct TypeLayout { pub size: u32, pub alignment: Alignment, @@ -14,6 +16,8 @@ pub struct TypeLayout { /// It uses the default layout algorithm/table, described in /// https://github.com/gpuweb/gpuweb/issues/1393 #[derive(Debug, Default)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Layouter { layouts: Vec, } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index baab6c3be..c0d1e74a2 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -5,7 +5,7 @@ mod namer; mod terminator; mod typifier; -pub use layouter::{Alignment, Layouter}; +pub use layouter::{Alignment, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, TypeResolution}; diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index fba0df985..7175e9462 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -715,13 +715,6 @@ impl ModuleInfo { } } -impl ops::Index> for ModuleInfo { - type Output = FunctionInfo; - fn index(&self, handle: Handle) -> &FunctionInfo { - &self.functions[handle.index()] - } -} - #[test] fn uniform_control_flow() { use crate::{Expression as E, Statement as S}; diff --git a/src/valid/mod.rs b/src/valid/mod.rs index b80d6e5dd..615b2c1e5 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -10,9 +10,11 @@ use crate::{ FastHashSet, }; use bit_set::BitSet; +use std::ops; //TODO: analyze the model at the same time as we validate it, // merge the corresponding matches over expressions and statements. + pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements}; pub use expression::ExpressionError; pub use function::{CallError, FunctionError, LocalVariableError}; @@ -35,6 +37,14 @@ bitflags::bitflags! { pub struct ModuleInfo { functions: Vec, entry_points: Vec, + pub layouter: Layouter, +} + +impl ops::Index> for ModuleInfo { + type Output = FunctionInfo; + fn index(&self, handle: Handle) -> &Self::Output { + &self.functions[handle.index()] + } } #[derive(Debug)] @@ -174,10 +184,6 @@ impl Validator { pub fn validate(&mut self, module: &crate::Module) -> Result { self.reset_types(module.types.len()); - let mut mod_info = ModuleInfo { - functions: Vec::with_capacity(module.functions.len()), - entry_points: Vec::with_capacity(module.entry_points.len()), - }; let layouter = Layouter::new(&module.types, &module.constants); for (handle, constant) in module.constants.iter() { @@ -210,6 +216,12 @@ impl Validator { })?; } + let mut mod_info = ModuleInfo { + functions: Vec::with_capacity(module.functions.len()), + entry_points: Vec::with_capacity(module.entry_points.len()), + layouter, + }; + for (handle, fun) in module.functions.iter() { match self.validate_function(fun, module, &mod_info) { Ok(info) => mod_info.functions.push(info), diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index 1564f5c01..0df16acec 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -13,55 +13,55 @@ OpEntryPoint GLCompute %43 "main" %40 OpExecutionMode %43 LocalSize 64 1 1 OpSource GLSL 450 OpName %3 "NUM_PARTICLES" -OpName %16 "SimParams" -OpMemberName %16 0 "deltaT" -OpMemberName %16 1 "rule1Distance" -OpMemberName %16 2 "rule2Distance" -OpMemberName %16 3 "rule3Distance" -OpMemberName %16 4 "rule1Scale" -OpMemberName %16 5 "rule2Scale" -OpMemberName %16 6 "rule3Scale" -OpName %15 "params" +OpName %16 "Particle" +OpMemberName %16 0 "pos" +OpMemberName %16 1 "vel" +OpName %17 "SimParams" +OpMemberName %17 0 "deltaT" +OpMemberName %17 1 "rule1Distance" +OpMemberName %17 2 "rule2Distance" +OpMemberName %17 3 "rule3Distance" +OpMemberName %17 4 "rule1Scale" +OpMemberName %17 5 "rule2Scale" +OpMemberName %17 6 "rule3Scale" OpName %19 "Particles" OpMemberName %19 0 "particles" -OpName %21 "Particle" -OpMemberName %21 0 "pos" -OpMemberName %21 1 "vel" -OpName %18 "particlesSrc" -OpName %24 "particlesDst" -OpName %25 "vPos" -OpName %27 "vVel" -OpName %28 "cMass" -OpName %29 "cVel" -OpName %30 "colVel" -OpName %31 "cMassCount" -OpName %33 "cVelCount" -OpName %34 "pos" -OpName %35 "vel" -OpName %36 "i" +OpName %21 "params" +OpName %23 "particlesSrc" +OpName %25 "particlesDst" +OpName %26 "vPos" +OpName %28 "vVel" +OpName %29 "cMass" +OpName %30 "cVel" +OpName %31 "colVel" +OpName %32 "cMassCount" +OpName %34 "cVelCount" +OpName %35 "pos" +OpName %36 "vel" +OpName %37 "i" OpName %40 "global_invocation_id" OpName %43 "main" OpName %43 "main" -OpDecorate %16 Block OpMemberDecorate %16 0 Offset 0 -OpMemberDecorate %16 1 Offset 4 -OpMemberDecorate %16 2 Offset 8 -OpMemberDecorate %16 3 Offset 12 -OpMemberDecorate %16 4 Offset 16 -OpMemberDecorate %16 5 Offset 20 -OpMemberDecorate %16 6 Offset 24 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 0 +OpMemberDecorate %16 1 Offset 8 +OpDecorate %17 Block +OpMemberDecorate %17 0 Offset 0 +OpMemberDecorate %17 1 Offset 4 +OpMemberDecorate %17 2 Offset 8 +OpMemberDecorate %17 3 Offset 12 +OpMemberDecorate %17 4 Offset 16 +OpMemberDecorate %17 5 Offset 20 +OpMemberDecorate %17 6 Offset 24 +OpDecorate %18 ArrayStride 16 OpDecorate %19 BufferBlock OpMemberDecorate %19 0 Offset 0 -OpDecorate %20 ArrayStride 16 -OpMemberDecorate %21 0 Offset 0 -OpMemberDecorate %21 1 Offset 8 -OpDecorate %18 NonWritable -OpDecorate %18 DescriptorSet 0 -OpDecorate %18 Binding 1 -OpDecorate %24 DescriptorSet 0 -OpDecorate %24 Binding 2 +OpDecorate %21 DescriptorSet 0 +OpDecorate %21 Binding 0 +OpDecorate %23 NonWritable +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 1 +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 2 OpDecorate %40 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 @@ -76,27 +76,27 @@ OpDecorate %40 BuiltIn GlobalInvocationId %12 = OpConstant %6 1.0 %13 = OpConstant %6 0.1 %14 = OpConstant %6 -1.0 -%16 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 -%17 = OpTypePointer Uniform %16 -%15 = OpVariable %17 Uniform -%22 = OpTypeVector %6 2 -%21 = OpTypeStruct %22 %22 -%20 = OpTypeRuntimeArray %21 -%19 = OpTypeStruct %20 -%23 = OpTypePointer Uniform %19 -%18 = OpVariable %23 Uniform -%24 = OpVariable %23 Uniform -%26 = OpTypePointer Function %22 -%32 = OpTypePointer Function %8 -%37 = OpTypePointer Function %4 -%39 = OpTypeVector %4 3 -%41 = OpTypePointer Input %39 +%15 = OpTypeVector %6 2 +%16 = OpTypeStruct %15 %15 +%17 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 +%18 = OpTypeRuntimeArray %16 +%19 = OpTypeStruct %18 +%20 = OpTypeVector %4 3 +%22 = OpTypePointer Uniform %17 +%21 = OpVariable %22 Uniform +%24 = OpTypePointer Uniform %19 +%23 = OpVariable %24 Uniform +%25 = OpVariable %24 Uniform +%27 = OpTypePointer Function %15 +%33 = OpTypePointer Function %8 +%38 = OpTypePointer Function %4 +%41 = OpTypePointer Input %20 %40 = OpVariable %41 Input %44 = OpTypeFunction %2 %47 = OpTypeBool -%51 = OpTypePointer Uniform %20 -%52 = OpTypePointer Uniform %21 -%53 = OpTypePointer Uniform %22 +%51 = OpTypePointer Uniform %18 +%52 = OpTypePointer Uniform %16 +%53 = OpTypePointer Uniform %15 %54 = OpConstant %8 0 %55 = OpConstant %8 0 %58 = OpConstant %8 1 @@ -123,18 +123,18 @@ OpDecorate %40 BuiltIn GlobalInvocationId %218 = OpConstant %8 1 %219 = OpConstant %8 0 %43 = OpFunction %2 None %44 -%38 = OpLabel -%36 = OpVariable %37 Function %9 -%33 = OpVariable %32 Function %7 -%29 = OpVariable %26 Function -%25 = OpVariable %26 Function -%34 = OpVariable %26 Function -%30 = OpVariable %26 Function -%27 = OpVariable %26 Function -%35 = OpVariable %26 Function -%31 = OpVariable %32 Function %7 -%28 = OpVariable %26 Function -%42 = OpLoad %39 %40 +%39 = OpLabel +%37 = OpVariable %38 Function %9 +%34 = OpVariable %33 Function %7 +%30 = OpVariable %27 Function +%26 = OpVariable %27 Function +%35 = OpVariable %27 Function +%31 = OpVariable %27 Function +%28 = OpVariable %27 Function +%36 = OpVariable %27 Function +%32 = OpVariable %33 Function %7 +%29 = OpVariable %27 Function +%42 = OpLoad %20 %40 OpBranch %45 %45 = OpLabel %46 = OpCompositeExtract %4 %42 0 @@ -144,209 +144,209 @@ OpBranchConditional %48 %50 %49 %50 = OpLabel OpReturn %49 = OpLabel -%56 = OpAccessChain %53 %18 %55 %46 %54 -%57 = OpLoad %22 %56 -OpStore %25 %57 -%60 = OpAccessChain %53 %18 %59 %46 %58 -%61 = OpLoad %22 %60 -OpStore %27 %61 -%62 = OpCompositeConstruct %22 %5 %5 -OpStore %28 %62 -%63 = OpCompositeConstruct %22 %5 %5 -OpStore %29 %63 -%64 = OpCompositeConstruct %22 %5 %5 -OpStore %30 %64 +%56 = OpAccessChain %53 %23 %55 %46 %54 +%57 = OpLoad %15 %56 +OpStore %26 %57 +%60 = OpAccessChain %53 %23 %59 %46 %58 +%61 = OpLoad %15 %60 +OpStore %28 %61 +%62 = OpCompositeConstruct %15 %5 %5 +OpStore %29 %62 +%63 = OpCompositeConstruct %15 %5 %5 +OpStore %30 %63 +%64 = OpCompositeConstruct %15 %5 %5 +OpStore %31 %64 OpBranch %65 %65 = OpLabel OpLoopMerge %66 %68 None OpBranch %67 %67 = OpLabel -%69 = OpLoad %4 %36 +%69 = OpLoad %4 %37 %70 = OpUGreaterThanEqual %47 %69 %3 OpSelectionMerge %71 None OpBranchConditional %70 %72 %71 %72 = OpLabel OpBranch %66 %71 = OpLabel -%73 = OpLoad %4 %36 +%73 = OpLoad %4 %37 %74 = OpIEqual %47 %73 %46 OpSelectionMerge %75 None OpBranchConditional %74 %76 %75 %76 = OpLabel OpBranch %68 %75 = OpLabel -%77 = OpLoad %4 %36 -%80 = OpAccessChain %53 %18 %79 %77 %78 -%81 = OpLoad %22 %80 -OpStore %34 %81 -%82 = OpLoad %4 %36 -%85 = OpAccessChain %53 %18 %84 %82 %83 -%86 = OpLoad %22 %85 -OpStore %35 %86 -%87 = OpLoad %22 %34 -%88 = OpLoad %22 %25 +%77 = OpLoad %4 %37 +%80 = OpAccessChain %53 %23 %79 %77 %78 +%81 = OpLoad %15 %80 +OpStore %35 %81 +%82 = OpLoad %4 %37 +%85 = OpAccessChain %53 %23 %84 %82 %83 +%86 = OpLoad %15 %85 +OpStore %36 %86 +%87 = OpLoad %15 %35 +%88 = OpLoad %15 %26 %89 = OpExtInst %6 %1 Distance %87 %88 -%92 = OpAccessChain %90 %15 %91 +%92 = OpAccessChain %90 %21 %91 %93 = OpLoad %6 %92 %94 = OpFOrdLessThan %47 %89 %93 OpSelectionMerge %95 None OpBranchConditional %94 %96 %95 %96 = OpLabel -%97 = OpLoad %22 %28 -%98 = OpLoad %22 %34 -%99 = OpFAdd %22 %97 %98 -OpStore %28 %99 -%100 = OpLoad %8 %31 +%97 = OpLoad %15 %29 +%98 = OpLoad %15 %35 +%99 = OpFAdd %15 %97 %98 +OpStore %29 %99 +%100 = OpLoad %8 %32 %101 = OpIAdd %8 %100 %10 -OpStore %31 %101 +OpStore %32 %101 OpBranch %95 %95 = OpLabel -%102 = OpLoad %22 %34 -%103 = OpLoad %22 %25 +%102 = OpLoad %15 %35 +%103 = OpLoad %15 %26 %104 = OpExtInst %6 %1 Distance %102 %103 -%106 = OpAccessChain %90 %15 %105 +%106 = OpAccessChain %90 %21 %105 %107 = OpLoad %6 %106 %108 = OpFOrdLessThan %47 %104 %107 OpSelectionMerge %109 None OpBranchConditional %108 %110 %109 %110 = OpLabel -%111 = OpLoad %22 %30 -%112 = OpLoad %22 %34 -%113 = OpLoad %22 %25 -%114 = OpFSub %22 %112 %113 -%115 = OpFSub %22 %111 %114 -OpStore %30 %115 +%111 = OpLoad %15 %31 +%112 = OpLoad %15 %35 +%113 = OpLoad %15 %26 +%114 = OpFSub %15 %112 %113 +%115 = OpFSub %15 %111 %114 +OpStore %31 %115 OpBranch %109 %109 = OpLabel -%116 = OpLoad %22 %34 -%117 = OpLoad %22 %25 +%116 = OpLoad %15 %35 +%117 = OpLoad %15 %26 %118 = OpExtInst %6 %1 Distance %116 %117 -%120 = OpAccessChain %90 %15 %119 +%120 = OpAccessChain %90 %21 %119 %121 = OpLoad %6 %120 %122 = OpFOrdLessThan %47 %118 %121 OpSelectionMerge %123 None OpBranchConditional %122 %124 %123 %124 = OpLabel -%125 = OpLoad %22 %29 -%126 = OpLoad %22 %35 -%127 = OpFAdd %22 %125 %126 -OpStore %29 %127 -%128 = OpLoad %8 %33 +%125 = OpLoad %15 %30 +%126 = OpLoad %15 %36 +%127 = OpFAdd %15 %125 %126 +OpStore %30 %127 +%128 = OpLoad %8 %34 %129 = OpIAdd %8 %128 %10 -OpStore %33 %129 +OpStore %34 %129 OpBranch %123 %123 = OpLabel OpBranch %68 %68 = OpLabel -%130 = OpLoad %4 %36 +%130 = OpLoad %4 %37 %131 = OpIAdd %4 %130 %11 -OpStore %36 %131 +OpStore %37 %131 OpBranch %65 %66 = OpLabel -%132 = OpLoad %8 %31 +%132 = OpLoad %8 %32 %133 = OpSGreaterThan %47 %132 %7 OpSelectionMerge %134 None OpBranchConditional %133 %135 %134 %135 = OpLabel -%136 = OpLoad %22 %28 -%137 = OpLoad %8 %31 +%136 = OpLoad %15 %29 +%137 = OpLoad %8 %32 %138 = OpConvertSToF %6 %137 %139 = OpFDiv %6 %12 %138 -%140 = OpVectorTimesScalar %22 %136 %139 -%141 = OpLoad %22 %25 -%142 = OpFSub %22 %140 %141 -OpStore %28 %142 +%140 = OpVectorTimesScalar %15 %136 %139 +%141 = OpLoad %15 %26 +%142 = OpFSub %15 %140 %141 +OpStore %29 %142 OpBranch %134 %134 = OpLabel -%143 = OpLoad %8 %33 +%143 = OpLoad %8 %34 %144 = OpSGreaterThan %47 %143 %7 OpSelectionMerge %145 None OpBranchConditional %144 %146 %145 %146 = OpLabel -%147 = OpLoad %22 %29 -%148 = OpLoad %8 %33 +%147 = OpLoad %15 %30 +%148 = OpLoad %8 %34 %149 = OpConvertSToF %6 %148 %150 = OpFDiv %6 %12 %149 -%151 = OpVectorTimesScalar %22 %147 %150 -OpStore %29 %151 +%151 = OpVectorTimesScalar %15 %147 %150 +OpStore %30 %151 OpBranch %145 %145 = OpLabel -%152 = OpLoad %22 %27 -%153 = OpLoad %22 %28 -%155 = OpAccessChain %90 %15 %154 +%152 = OpLoad %15 %28 +%153 = OpLoad %15 %29 +%155 = OpAccessChain %90 %21 %154 %156 = OpLoad %6 %155 -%157 = OpVectorTimesScalar %22 %153 %156 -%158 = OpFAdd %22 %152 %157 -%159 = OpLoad %22 %30 -%161 = OpAccessChain %90 %15 %160 +%157 = OpVectorTimesScalar %15 %153 %156 +%158 = OpFAdd %15 %152 %157 +%159 = OpLoad %15 %31 +%161 = OpAccessChain %90 %21 %160 %162 = OpLoad %6 %161 -%163 = OpVectorTimesScalar %22 %159 %162 -%164 = OpFAdd %22 %158 %163 -%165 = OpLoad %22 %29 -%167 = OpAccessChain %90 %15 %166 +%163 = OpVectorTimesScalar %15 %159 %162 +%164 = OpFAdd %15 %158 %163 +%165 = OpLoad %15 %30 +%167 = OpAccessChain %90 %21 %166 %168 = OpLoad %6 %167 -%169 = OpVectorTimesScalar %22 %165 %168 -%170 = OpFAdd %22 %164 %169 -OpStore %27 %170 -%171 = OpLoad %22 %27 -%172 = OpExtInst %22 %1 Normalize %171 -%173 = OpLoad %22 %27 +%169 = OpVectorTimesScalar %15 %165 %168 +%170 = OpFAdd %15 %164 %169 +OpStore %28 %170 +%171 = OpLoad %15 %28 +%172 = OpExtInst %15 %1 Normalize %171 +%173 = OpLoad %15 %28 %174 = OpExtInst %6 %1 Length %173 %175 = OpExtInst %6 %1 FClamp %174 %5 %13 -%176 = OpVectorTimesScalar %22 %172 %175 -OpStore %27 %176 -%177 = OpLoad %22 %25 -%178 = OpLoad %22 %27 -%180 = OpAccessChain %90 %15 %179 +%176 = OpVectorTimesScalar %15 %172 %175 +OpStore %28 %176 +%177 = OpLoad %15 %26 +%178 = OpLoad %15 %28 +%180 = OpAccessChain %90 %21 %179 %181 = OpLoad %6 %180 -%182 = OpVectorTimesScalar %22 %178 %181 -%183 = OpFAdd %22 %177 %182 -OpStore %25 %183 -%184 = OpLoad %22 %25 +%182 = OpVectorTimesScalar %15 %178 %181 +%183 = OpFAdd %15 %177 %182 +OpStore %26 %183 +%184 = OpLoad %15 %26 %185 = OpCompositeExtract %6 %184 0 %186 = OpFOrdLessThan %47 %185 %14 OpSelectionMerge %187 None OpBranchConditional %186 %188 %187 %188 = OpLabel -%191 = OpAccessChain %189 %25 %190 +%191 = OpAccessChain %189 %26 %190 OpStore %191 %12 OpBranch %187 %187 = OpLabel -%192 = OpLoad %22 %25 +%192 = OpLoad %15 %26 %193 = OpCompositeExtract %6 %192 0 %194 = OpFOrdGreaterThan %47 %193 %12 OpSelectionMerge %195 None OpBranchConditional %194 %196 %195 %196 = OpLabel -%198 = OpAccessChain %189 %25 %197 +%198 = OpAccessChain %189 %26 %197 OpStore %198 %14 OpBranch %195 %195 = OpLabel -%199 = OpLoad %22 %25 +%199 = OpLoad %15 %26 %200 = OpCompositeExtract %6 %199 1 %201 = OpFOrdLessThan %47 %200 %14 OpSelectionMerge %202 None OpBranchConditional %201 %203 %202 %203 = OpLabel -%205 = OpAccessChain %189 %25 %204 +%205 = OpAccessChain %189 %26 %204 OpStore %205 %12 OpBranch %202 %202 = OpLabel -%206 = OpLoad %22 %25 +%206 = OpLoad %15 %26 %207 = OpCompositeExtract %6 %206 1 %208 = OpFOrdGreaterThan %47 %207 %12 OpSelectionMerge %209 None OpBranchConditional %208 %210 %209 %210 = OpLabel -%212 = OpAccessChain %189 %25 %211 +%212 = OpAccessChain %189 %26 %211 OpStore %212 %14 OpBranch %209 %209 = OpLabel -%213 = OpLoad %22 %25 -%216 = OpAccessChain %53 %24 %215 %46 %214 +%213 = OpLoad %15 %26 +%216 = OpAccessChain %53 %25 %215 %46 %214 OpStore %216 %213 -%217 = OpLoad %22 %27 -%220 = OpAccessChain %53 %24 %219 %46 %218 +%217 = OpLoad %15 %28 +%220 = OpAccessChain %53 %25 %219 %46 %218 OpStore %220 %217 OpReturn OpFunctionEnd diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 894722419..7a6949094 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -498,4 +498,24 @@ expression: output ], ), ], + layouter: ( + layouts: [ + ( + size: 4, + alignment: 4, + ), + ( + size: 4, + alignment: 4, + ), + ( + size: 4, + alignment: 4, + ), + ( + size: 12, + alignment: 16, + ), + ], + ), ) diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index 6064a6fdb..379b5a3f0 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -14,18 +14,18 @@ OpExecutionMode %48 LocalSize 1 1 1 OpSource GLSL 450 OpName %9 "PrimeIndices" OpMemberName %9 0 "data" -OpName %8 "v_indices" -OpName %12 "n" -OpName %14 "i" -OpName %17 "collatz_iterations" +OpName %11 "v_indices" +OpName %13 "n" +OpName %15 "i" +OpName %18 "collatz_iterations" OpName %45 "global_id" OpName %48 "main" OpName %48 "main" +OpDecorate %8 ArrayStride 4 OpDecorate %9 BufferBlock OpMemberDecorate %9 0 Offset 0 -OpDecorate %10 ArrayStride 4 -OpDecorate %8 DescriptorSet 0 -OpDecorate %8 Binding 0 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 0 OpDecorate %45 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 @@ -33,80 +33,80 @@ OpDecorate %45 BuiltIn GlobalInvocationId %5 = OpConstant %4 1 %6 = OpConstant %4 2 %7 = OpConstant %4 3 -%10 = OpTypeRuntimeArray %4 -%9 = OpTypeStruct %10 -%11 = OpTypePointer Uniform %9 -%8 = OpVariable %11 Uniform -%13 = OpTypePointer Function %4 -%18 = OpTypeFunction %4 %4 -%25 = OpTypeBool -%44 = OpTypeVector %4 3 -%46 = OpTypePointer Input %44 +%8 = OpTypeRuntimeArray %4 +%9 = OpTypeStruct %8 +%10 = OpTypeVector %4 3 +%12 = OpTypePointer Uniform %9 +%11 = OpVariable %12 Uniform +%14 = OpTypePointer Function %4 +%19 = OpTypeFunction %4 %4 +%26 = OpTypeBool +%46 = OpTypePointer Input %10 %45 = OpVariable %46 Input %49 = OpTypeFunction %2 -%51 = OpTypePointer Uniform %10 +%51 = OpTypePointer Uniform %8 %53 = OpTypePointer Uniform %4 %55 = OpTypeInt 32 1 %56 = OpConstant %55 0 %60 = OpConstant %55 0 -%17 = OpFunction %4 None %18 -%16 = OpFunctionParameter %4 -%15 = OpLabel -%12 = OpVariable %13 Function -%14 = OpVariable %13 Function %3 -OpBranch %19 -%19 = OpLabel -OpStore %12 %16 +%18 = OpFunction %4 None %19 +%17 = OpFunctionParameter %4 +%16 = OpLabel +%13 = OpVariable %14 Function +%15 = OpVariable %14 Function %3 OpBranch %20 %20 = OpLabel -OpLoopMerge %21 %23 None -OpBranch %22 -%22 = OpLabel -%24 = OpLoad %4 %12 -%26 = OpULessThanEqual %25 %24 %5 -OpSelectionMerge %27 None -OpBranchConditional %26 %28 %27 -%28 = OpLabel +OpStore %13 %17 OpBranch %21 -%27 = OpLabel -%29 = OpLoad %4 %12 -%30 = OpUMod %4 %29 %6 -%31 = OpIEqual %25 %30 %3 -OpSelectionMerge %32 None -OpBranchConditional %31 %33 %34 -%33 = OpLabel -%35 = OpLoad %4 %12 -%36 = OpUDiv %4 %35 %6 -OpStore %12 %36 -OpBranch %32 -%34 = OpLabel -%37 = OpLoad %4 %12 -%38 = OpIMul %4 %7 %37 -%39 = OpIAdd %4 %38 %5 -OpStore %12 %39 -OpBranch %32 -%32 = OpLabel -%40 = OpLoad %4 %14 -%41 = OpIAdd %4 %40 %5 -OpStore %14 %41 +%21 = OpLabel +OpLoopMerge %22 %24 None OpBranch %23 %23 = OpLabel -OpBranch %20 -%21 = OpLabel -%42 = OpLoad %4 %14 -OpReturnValue %42 +%25 = OpLoad %4 %13 +%27 = OpULessThanEqual %26 %25 %5 +OpSelectionMerge %28 None +OpBranchConditional %27 %29 %28 +%29 = OpLabel +OpBranch %22 +%28 = OpLabel +%30 = OpLoad %4 %13 +%31 = OpUMod %4 %30 %6 +%32 = OpIEqual %26 %31 %3 +OpSelectionMerge %33 None +OpBranchConditional %32 %34 %35 +%34 = OpLabel +%36 = OpLoad %4 %13 +%37 = OpUDiv %4 %36 %6 +OpStore %13 %37 +OpBranch %33 +%35 = OpLabel +%38 = OpLoad %4 %13 +%39 = OpIMul %4 %7 %38 +%40 = OpIAdd %4 %39 %5 +OpStore %13 %40 +OpBranch %33 +%33 = OpLabel +%41 = OpLoad %4 %15 +%42 = OpIAdd %4 %41 %5 +OpStore %15 %42 +OpBranch %24 +%24 = OpLabel +OpBranch %21 +%22 = OpLabel +%43 = OpLoad %4 %15 +OpReturnValue %43 OpFunctionEnd %48 = OpFunction %2 None %49 -%43 = OpLabel -%47 = OpLoad %44 %45 +%44 = OpLabel +%47 = OpLoad %10 %45 OpBranch %50 %50 = OpLabel %52 = OpCompositeExtract %4 %47 0 %54 = OpCompositeExtract %4 %47 0 -%57 = OpAccessChain %53 %8 %56 %54 +%57 = OpAccessChain %53 %11 %56 %54 %58 = OpLoad %4 %57 -%59 = OpFunctionCall %4 %17 %58 -%61 = OpAccessChain %53 %8 %60 %52 +%59 = OpFunctionCall %4 %18 %58 +%61 = OpAccessChain %53 %11 %60 %52 OpStore %61 %59 OpReturn OpFunctionEnd diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index c3a3ff351..62a1dd336 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -14,10 +14,10 @@ OpEntryPoint Fragment %47 "main" %44 %46 OpExecutionMode %47 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" -OpName %7 "u_texture" -OpName %10 "u_sampler" -OpName %13 "out" -OpName %14 "VertexOutput" +OpName %9 "VertexOutput" +OpName %12 "u_texture" +OpName %14 "u_sampler" +OpName %16 "out" OpName %19 "pos" OpName %22 "uv" OpName %24 "uv" @@ -27,10 +27,10 @@ OpName %28 "main" OpName %44 "uv" OpName %47 "main" OpName %47 "main" -OpDecorate %7 DescriptorSet 0 -OpDecorate %7 Binding 0 -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 1 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 0 +OpDecorate %14 DescriptorSet 0 +OpDecorate %14 Binding 1 OpDecorate %19 Location 0 OpDecorate %22 Location 1 OpDecorate %24 Location 0 @@ -42,62 +42,62 @@ OpDecorate %46 Location 0 %3 = OpConstant %4 1.2 %5 = OpConstant %4 0.0 %6 = OpConstant %4 1.0 -%8 = OpTypeImage %4 2D 0 0 0 1 Unknown -%9 = OpTypePointer UniformConstant %8 -%7 = OpVariable %9 UniformConstant +%7 = OpTypeVector %4 2 +%8 = OpTypeVector %4 4 +%9 = OpTypeStruct %7 %8 +%10 = OpTypeImage %4 2D 0 0 0 1 Unknown %11 = OpTypeSampler -%12 = OpTypePointer UniformConstant %11 -%10 = OpVariable %12 UniformConstant -%15 = OpTypeVector %4 2 -%16 = OpTypeVector %4 4 -%14 = OpTypeStruct %15 %16 -%17 = OpTypePointer Function %14 -%20 = OpTypePointer Input %15 +%13 = OpTypePointer UniformConstant %10 +%12 = OpVariable %13 UniformConstant +%15 = OpTypePointer UniformConstant %11 +%14 = OpVariable %15 UniformConstant +%17 = OpTypePointer Function %9 +%20 = OpTypePointer Input %7 %19 = OpVariable %20 Input %22 = OpVariable %20 Input -%25 = OpTypePointer Output %15 +%25 = OpTypePointer Output %7 %24 = OpVariable %25 Output -%27 = OpTypePointer Output %16 +%27 = OpTypePointer Output %8 %26 = OpVariable %27 Output %29 = OpTypeFunction %2 -%31 = OpTypePointer Function %15 +%31 = OpTypePointer Function %7 %32 = OpTypeInt 32 1 %33 = OpConstant %32 0 -%35 = OpTypePointer Function %16 +%35 = OpTypePointer Function %8 %38 = OpConstant %32 1 %44 = OpVariable %20 Input %46 = OpVariable %27 Output -%51 = OpTypeSampledImage %8 +%51 = OpTypeSampledImage %10 %55 = OpTypeBool %28 = OpFunction %2 None %29 %18 = OpLabel -%13 = OpVariable %17 Function -%21 = OpLoad %15 %19 -%23 = OpLoad %15 %22 +%16 = OpVariable %17 Function +%21 = OpLoad %7 %19 +%23 = OpLoad %7 %22 OpBranch %30 %30 = OpLabel -%34 = OpAccessChain %31 %13 %33 +%34 = OpAccessChain %31 %16 %33 OpStore %34 %23 -%36 = OpVectorTimesScalar %15 %21 %3 -%37 = OpCompositeConstruct %16 %36 %5 %6 -%39 = OpAccessChain %35 %13 %38 +%36 = OpVectorTimesScalar %7 %21 %3 +%37 = OpCompositeConstruct %8 %36 %5 %6 +%39 = OpAccessChain %35 %16 %38 OpStore %39 %37 -%40 = OpLoad %14 %13 -%41 = OpCompositeExtract %15 %40 0 +%40 = OpLoad %9 %16 +%41 = OpCompositeExtract %7 %40 0 OpStore %24 %41 -%42 = OpCompositeExtract %16 %40 1 +%42 = OpCompositeExtract %8 %40 1 OpStore %26 %42 OpReturn OpFunctionEnd %47 = OpFunction %2 None %29 %43 = OpLabel -%45 = OpLoad %15 %44 -%48 = OpLoad %8 %7 -%49 = OpLoad %11 %10 +%45 = OpLoad %7 %44 +%48 = OpLoad %10 %12 +%49 = OpLoad %11 %14 OpBranch %50 %50 = OpLabel %52 = OpSampledImage %51 %48 %49 -%53 = OpImageSampleImplicitLod %16 %52 %45 +%53 = OpImageSampleImplicitLod %8 %52 %45 %54 = OpCompositeExtract %4 %53 3 %56 = OpFOrdEqual %55 %54 %5 OpSelectionMerge %57 None @@ -106,7 +106,7 @@ OpBranchConditional %56 %58 %57 OpKill %57 = OpLabel %59 = OpCompositeExtract %4 %53 3 -%60 = OpVectorTimesScalar %16 %53 %59 +%60 = OpVectorTimesScalar %8 %53 %59 OpStore %46 %60 OpReturn OpFunctionEnd diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index f0d4c9c29..817820f84 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -2749,4 +2749,236 @@ expression: output ], ), ], + layouter: ( + layouts: [ + ( + size: 4, + alignment: 4, + ), + ( + size: 12, + alignment: 16, + ), + ( + size: 4, + alignment: 4, + ), + ( + size: 16, + alignment: 16, + ), + ( + size: 1, + alignment: 1, + ), + ( + size: 8, + alignment: 8, + ), + ( + size: 0, + alignment: 1, + ), + ( + size: 0, + alignment: 1, + ), + ( + size: 8, + alignment: 8, + ), + ( + size: 4, + alignment: 4, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 16, + alignment: 16, + ), + ( + size: 16, + alignment: 16, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 64, + alignment: 16, + ), + ( + size: 96, + alignment: 16, + ), + ( + size: 96, + alignment: 96, + ), + ( + size: 96, + alignment: 96, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 4, + alignment: 1, + ), + ( + size: 0, + alignment: 1, + ), + ( + size: 0, + alignment: 1, + ), + ], + ), ) diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index c4138feb3..23bee506c 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -12,46 +12,46 @@ OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %81 "fs_main" %73 %76 %79 OpExecutionMode %81 OriginUpperLeft OpSource GLSL 450 -OpName %9 "c_ambient" -OpName %11 "c_max_lights" -OpName %16 "Globals" -OpMemberName %16 0 "num_lights" -OpName %15 "u_globals" -OpName %20 "Lights" -OpMemberName %20 0 "data" -OpName %22 "Light" -OpMemberName %22 0 "proj" -OpMemberName %22 1 "pos" -OpMemberName %22 2 "color" -OpName %19 "s_lights" -OpName %26 "t_shadow" -OpName %29 "sampler_shadow" -OpName %35 "fetch_shadow" +OpName %9 "c_max_lights" +OpName %14 "Globals" +OpMemberName %14 0 "num_lights" +OpName %17 "Light" +OpMemberName %17 0 "proj" +OpMemberName %17 1 "pos" +OpMemberName %17 2 "color" +OpName %19 "Lights" +OpMemberName %19 0 "data" +OpName %24 "c_ambient" +OpName %25 "u_globals" +OpName %27 "s_lights" +OpName %29 "t_shadow" +OpName %31 "sampler_shadow" +OpName %36 "fetch_shadow" OpName %68 "color" OpName %70 "i" OpName %73 "raw_normal" OpName %76 "position" OpName %81 "fs_main" OpName %81 "fs_main" -OpDecorate %16 Block -OpMemberDecorate %16 0 Offset 0 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 0 -OpDecorate %20 BufferBlock -OpMemberDecorate %20 0 Offset 0 -OpDecorate %21 ArrayStride 96 -OpMemberDecorate %22 0 Offset 0 -OpMemberDecorate %22 0 ColMajor -OpMemberDecorate %22 0 MatrixStride 16 -OpMemberDecorate %22 1 Offset 64 -OpMemberDecorate %22 2 Offset 80 -OpDecorate %19 NonWritable -OpDecorate %19 DescriptorSet 0 -OpDecorate %19 Binding 1 -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 2 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %17 0 Offset 0 +OpMemberDecorate %17 0 ColMajor +OpMemberDecorate %17 0 MatrixStride 16 +OpMemberDecorate %17 1 Offset 64 +OpMemberDecorate %17 2 Offset 80 +OpDecorate %18 ArrayStride 96 +OpDecorate %19 BufferBlock +OpMemberDecorate %19 0 Offset 0 +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 0 +OpDecorate %27 NonWritable +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 1 OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 3 +OpDecorate %29 Binding 2 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 3 OpDecorate %73 Location 0 OpDecorate %76 Location 1 OpDecorate %79 Location 0 @@ -62,151 +62,151 @@ OpDecorate %79 Location 0 %6 = OpConstant %4 0.5 %7 = OpConstant %4 -0.5 %8 = OpConstant %4 0.05 -%10 = OpTypeVector %4 3 -%9 = OpConstantComposite %10 %8 %8 %8 -%12 = OpTypeInt 32 0 -%11 = OpConstant %12 10 -%13 = OpConstant %12 0 -%14 = OpConstant %12 1 -%17 = OpTypeVector %12 4 -%16 = OpTypeStruct %17 -%18 = OpTypePointer Uniform %16 -%15 = OpVariable %18 Uniform -%24 = OpTypeVector %4 4 -%23 = OpTypeMatrix %24 4 -%22 = OpTypeStruct %23 %24 %24 -%21 = OpTypeRuntimeArray %22 -%20 = OpTypeStruct %21 -%25 = OpTypePointer Uniform %20 -%19 = OpVariable %25 Uniform -%27 = OpTypeImage %4 2D 1 1 0 1 Unknown -%28 = OpTypePointer UniformConstant %27 -%26 = OpVariable %28 UniformConstant -%30 = OpTypeSampler -%31 = OpTypePointer UniformConstant %30 -%29 = OpVariable %31 UniformConstant -%36 = OpTypeFunction %4 %12 %24 -%41 = OpTypeBool -%45 = OpTypeVector %4 2 +%10 = OpTypeInt 32 0 +%9 = OpConstant %10 10 +%11 = OpConstant %10 0 +%12 = OpConstant %10 1 +%13 = OpTypeVector %10 4 +%14 = OpTypeStruct %13 +%16 = OpTypeVector %4 4 +%15 = OpTypeMatrix %16 4 +%17 = OpTypeStruct %15 %16 %16 +%18 = OpTypeRuntimeArray %17 +%19 = OpTypeStruct %18 +%20 = OpTypeImage %4 2D 1 1 0 1 Unknown +%21 = OpTypeSampler +%22 = OpTypeVector %4 2 +%23 = OpTypeVector %4 3 +%24 = OpConstantComposite %23 %8 %8 %8 +%26 = OpTypePointer Uniform %14 +%25 = OpVariable %26 Uniform +%28 = OpTypePointer Uniform %19 +%27 = OpVariable %28 Uniform +%30 = OpTypePointer UniformConstant %20 +%29 = OpVariable %30 UniformConstant +%32 = OpTypePointer UniformConstant %21 +%31 = OpVariable %32 UniformConstant +%37 = OpTypeFunction %4 %10 %16 +%42 = OpTypeBool %56 = OpTypeInt 32 1 -%60 = OpTypeSampledImage %27 +%60 = OpTypeSampledImage %20 %67 = OpConstant %4 0.0 -%69 = OpTypePointer Function %10 -%71 = OpTypePointer Function %12 -%74 = OpTypePointer Input %10 +%69 = OpTypePointer Function %23 +%71 = OpTypePointer Function %10 +%74 = OpTypePointer Input %23 %73 = OpVariable %74 Input -%77 = OpTypePointer Input %24 +%77 = OpTypePointer Input %16 %76 = OpVariable %77 Input -%80 = OpTypePointer Output %24 +%80 = OpTypePointer Output %16 %79 = OpVariable %80 Output %82 = OpTypeFunction %2 -%92 = OpTypePointer Uniform %17 +%92 = OpTypePointer Uniform %13 %93 = OpConstant %56 0 -%101 = OpTypePointer Uniform %21 -%103 = OpTypePointer Uniform %22 +%101 = OpTypePointer Uniform %18 +%103 = OpTypePointer Uniform %17 %104 = OpConstant %56 0 -%35 = OpFunction %4 None %36 -%33 = OpFunctionParameter %12 -%34 = OpFunctionParameter %24 -%32 = OpLabel -%37 = OpLoad %27 %26 -%38 = OpLoad %30 %29 -OpBranch %39 -%39 = OpLabel -%40 = OpCompositeExtract %4 %34 3 -%42 = OpFOrdLessThanEqual %41 %40 %3 -OpSelectionMerge %43 None -OpBranchConditional %42 %44 %43 -%44 = OpLabel +%36 = OpFunction %4 None %37 +%34 = OpFunctionParameter %10 +%35 = OpFunctionParameter %16 +%33 = OpLabel +%38 = OpLoad %20 %29 +%39 = OpLoad %21 %31 +OpBranch %40 +%40 = OpLabel +%41 = OpCompositeExtract %4 %35 3 +%43 = OpFOrdLessThanEqual %42 %41 %3 +OpSelectionMerge %44 None +OpBranchConditional %43 %45 %44 +%45 = OpLabel OpReturnValue %5 -%43 = OpLabel -%46 = OpCompositeConstruct %45 %6 %7 -%47 = OpCompositeExtract %4 %34 3 +%44 = OpLabel +%46 = OpCompositeConstruct %22 %6 %7 +%47 = OpCompositeExtract %4 %35 3 %48 = OpFDiv %4 %5 %47 -%49 = OpCompositeExtract %4 %34 0 -%50 = OpCompositeExtract %4 %34 1 -%51 = OpCompositeConstruct %45 %49 %50 -%52 = OpFMul %45 %51 %46 -%53 = OpVectorTimesScalar %45 %52 %48 -%54 = OpCompositeConstruct %45 %6 %6 -%55 = OpFAdd %45 %53 %54 -%57 = OpBitcast %56 %33 -%58 = OpCompositeExtract %4 %34 2 +%49 = OpCompositeExtract %4 %35 0 +%50 = OpCompositeExtract %4 %35 1 +%51 = OpCompositeConstruct %22 %49 %50 +%52 = OpFMul %22 %51 %46 +%53 = OpVectorTimesScalar %22 %52 %48 +%54 = OpCompositeConstruct %22 %6 %6 +%55 = OpFAdd %22 %53 %54 +%57 = OpBitcast %56 %34 +%58 = OpCompositeExtract %4 %35 2 %59 = OpFMul %4 %58 %48 %61 = OpCompositeExtract %4 %55 0 %62 = OpCompositeExtract %4 %55 1 %63 = OpConvertUToF %4 %57 -%64 = OpCompositeConstruct %10 %61 %62 %63 -%65 = OpSampledImage %60 %37 %38 +%64 = OpCompositeConstruct %23 %61 %62 %63 +%65 = OpSampledImage %60 %38 %39 %66 = OpImageSampleDrefExplicitLod %4 %65 %64 %59 Lod %67 OpReturnValue %66 OpFunctionEnd %81 = OpFunction %2 None %82 %72 = OpLabel -%68 = OpVariable %69 Function %9 -%70 = OpVariable %71 Function %13 -%75 = OpLoad %10 %73 -%78 = OpLoad %24 %76 -%83 = OpLoad %27 %26 -%84 = OpLoad %30 %29 +%68 = OpVariable %69 Function %24 +%70 = OpVariable %71 Function %11 +%75 = OpLoad %23 %73 +%78 = OpLoad %16 %76 +%83 = OpLoad %20 %29 +%84 = OpLoad %21 %31 OpBranch %85 %85 = OpLabel -%86 = OpExtInst %10 %1 Normalize %75 +%86 = OpExtInst %23 %1 Normalize %75 OpBranch %87 %87 = OpLabel OpLoopMerge %88 %90 None OpBranch %89 %89 = OpLabel -%91 = OpLoad %12 %70 -%94 = OpAccessChain %92 %15 %93 -%95 = OpLoad %17 %94 -%96 = OpCompositeExtract %12 %95 0 -%97 = OpExtInst %12 %1 UMin %96 %11 -%98 = OpUGreaterThanEqual %41 %91 %97 +%91 = OpLoad %10 %70 +%94 = OpAccessChain %92 %25 %93 +%95 = OpLoad %13 %94 +%96 = OpCompositeExtract %10 %95 0 +%97 = OpExtInst %10 %1 UMin %96 %9 +%98 = OpUGreaterThanEqual %42 %91 %97 OpSelectionMerge %99 None OpBranchConditional %98 %100 %99 %100 = OpLabel OpBranch %88 %99 = OpLabel -%102 = OpLoad %12 %70 -%105 = OpAccessChain %103 %19 %104 %102 -%106 = OpLoad %22 %105 -%107 = OpLoad %12 %70 -%108 = OpCompositeExtract %23 %106 0 -%109 = OpMatrixTimesVector %24 %108 %78 -%110 = OpFunctionCall %4 %35 %107 %109 -%111 = OpCompositeExtract %24 %106 1 +%102 = OpLoad %10 %70 +%105 = OpAccessChain %103 %27 %104 %102 +%106 = OpLoad %17 %105 +%107 = OpLoad %10 %70 +%108 = OpCompositeExtract %15 %106 0 +%109 = OpMatrixTimesVector %16 %108 %78 +%110 = OpFunctionCall %4 %36 %107 %109 +%111 = OpCompositeExtract %16 %106 1 %112 = OpCompositeExtract %4 %111 0 %113 = OpCompositeExtract %4 %111 1 %114 = OpCompositeExtract %4 %111 2 -%115 = OpCompositeConstruct %10 %112 %113 %114 +%115 = OpCompositeConstruct %23 %112 %113 %114 %116 = OpCompositeExtract %4 %78 0 %117 = OpCompositeExtract %4 %78 1 %118 = OpCompositeExtract %4 %78 2 -%119 = OpCompositeConstruct %10 %116 %117 %118 -%120 = OpFSub %10 %115 %119 -%121 = OpExtInst %10 %1 Normalize %120 +%119 = OpCompositeConstruct %23 %116 %117 %118 +%120 = OpFSub %23 %115 %119 +%121 = OpExtInst %23 %1 Normalize %120 %122 = OpDot %4 %86 %121 %123 = OpExtInst %4 %1 FMax %3 %122 -%124 = OpLoad %10 %68 +%124 = OpLoad %23 %68 %125 = OpFMul %4 %110 %123 -%126 = OpCompositeExtract %24 %106 2 +%126 = OpCompositeExtract %16 %106 2 %127 = OpCompositeExtract %4 %126 0 %128 = OpCompositeExtract %4 %126 1 %129 = OpCompositeExtract %4 %126 2 -%130 = OpCompositeConstruct %10 %127 %128 %129 -%131 = OpVectorTimesScalar %10 %130 %125 -%132 = OpFAdd %10 %124 %131 +%130 = OpCompositeConstruct %23 %127 %128 %129 +%131 = OpVectorTimesScalar %23 %130 %125 +%132 = OpFAdd %23 %124 %131 OpStore %68 %132 OpBranch %90 %90 = OpLabel -%133 = OpLoad %12 %70 -%134 = OpIAdd %12 %133 %14 +%133 = OpLoad %10 %70 +%134 = OpIAdd %10 %133 %12 OpStore %70 %134 OpBranch %87 %88 = OpLabel -%135 = OpLoad %10 %68 -%136 = OpCompositeConstruct %24 %135 %5 +%135 = OpLoad %23 %68 +%136 = OpCompositeConstruct %16 %135 %5 OpStore %79 %136 OpReturn OpFunctionEnd diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index b0dd48114..3f544eae7 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -9,45 +9,45 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %37 "vs_main" %30 %33 %35 +OpEntryPoint Vertex %38 "vs_main" %31 %34 %36 OpEntryPoint Fragment %108 "fs_main" %101 %104 %107 OpExecutionMode %108 OriginUpperLeft OpSource GLSL 450 -OpName %11 "Data" -OpMemberName %11 0 "proj_inv" -OpMemberName %11 1 "view" -OpName %10 "r_data" -OpName %15 "r_texture" -OpName %18 "r_sampler" -OpName %21 "tmp1" -OpName %23 "tmp2" -OpName %24 "out" -OpName %25 "VertexOutput" -OpName %30 "vertex_index" -OpName %33 "position" -OpName %35 "uv" -OpName %37 "vs_main" -OpName %37 "vs_main" +OpName %12 "VertexOutput" +OpName %14 "Data" +OpMemberName %14 0 "proj_inv" +OpMemberName %14 1 "view" +OpName %19 "r_data" +OpName %21 "r_texture" +OpName %23 "r_sampler" +OpName %25 "tmp1" +OpName %27 "tmp2" +OpName %28 "out" +OpName %31 "vertex_index" +OpName %34 "position" +OpName %36 "uv" +OpName %38 "vs_main" +OpName %38 "vs_main" OpName %101 "position" OpName %104 "uv" OpName %108 "fs_main" OpName %108 "fs_main" -OpDecorate %11 Block -OpMemberDecorate %11 0 Offset 0 -OpMemberDecorate %11 0 ColMajor -OpMemberDecorate %11 0 MatrixStride 16 -OpMemberDecorate %11 1 Offset 64 -OpMemberDecorate %11 1 ColMajor -OpMemberDecorate %11 1 MatrixStride 16 -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 0 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 1 -OpDecorate %18 DescriptorSet 0 -OpDecorate %18 Binding 2 -OpDecorate %30 BuiltIn VertexIndex -OpDecorate %33 BuiltIn Position -OpDecorate %35 Location 0 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 0 ColMajor +OpMemberDecorate %14 0 MatrixStride 16 +OpMemberDecorate %14 1 Offset 64 +OpMemberDecorate %14 1 ColMajor +OpMemberDecorate %14 1 MatrixStride 16 +OpDecorate %19 DescriptorSet 0 +OpDecorate %19 Binding 0 +OpDecorate %21 DescriptorSet 0 +OpDecorate %21 Binding 1 +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 2 +OpDecorate %31 BuiltIn VertexIndex +OpDecorate %34 BuiltIn Position +OpDecorate %36 Location 0 OpDecorate %101 BuiltIn FragCoord OpDecorate %104 Location 0 OpDecorate %107 Location 0 @@ -59,122 +59,122 @@ OpDecorate %107 Location 0 %6 = OpConstant %7 4.0 %8 = OpConstant %7 1.0 %9 = OpConstant %7 0.0 -%13 = OpTypeVector %7 4 -%12 = OpTypeMatrix %13 4 -%11 = OpTypeStruct %12 %12 -%14 = OpTypePointer Uniform %11 -%10 = OpVariable %14 Uniform -%16 = OpTypeImage %7 Cube 0 0 0 1 Unknown -%17 = OpTypePointer UniformConstant %16 -%15 = OpVariable %17 UniformConstant -%19 = OpTypeSampler -%20 = OpTypePointer UniformConstant %19 -%18 = OpVariable %20 UniformConstant -%22 = OpTypePointer Function %4 -%26 = OpTypeVector %7 3 -%25 = OpTypeStruct %13 %26 -%27 = OpTypePointer Function %25 -%29 = OpTypeInt 32 0 -%31 = OpTypePointer Input %29 -%30 = OpVariable %31 Input -%34 = OpTypePointer Output %13 -%33 = OpVariable %34 Output -%36 = OpTypePointer Output %26 -%35 = OpVariable %36 Output -%38 = OpTypeFunction %2 -%53 = OpTypePointer Uniform %12 -%54 = OpConstant %4 1 -%62 = OpConstant %4 1 -%70 = OpConstant %4 1 -%78 = OpTypeMatrix %26 3 +%10 = OpTypeVector %7 4 +%11 = OpTypeVector %7 3 +%12 = OpTypeStruct %10 %11 +%13 = OpTypeMatrix %10 4 +%14 = OpTypeStruct %13 %13 +%15 = OpTypeInt 32 0 +%16 = OpTypeMatrix %11 3 +%17 = OpTypeImage %7 Cube 0 0 0 1 Unknown +%18 = OpTypeSampler +%20 = OpTypePointer Uniform %14 +%19 = OpVariable %20 Uniform +%22 = OpTypePointer UniformConstant %17 +%21 = OpVariable %22 UniformConstant +%24 = OpTypePointer UniformConstant %18 +%23 = OpVariable %24 UniformConstant +%26 = OpTypePointer Function %4 +%29 = OpTypePointer Function %12 +%32 = OpTypePointer Input %15 +%31 = OpVariable %32 Input +%35 = OpTypePointer Output %10 +%34 = OpVariable %35 Output +%37 = OpTypePointer Output %11 +%36 = OpVariable %37 Output +%39 = OpTypeFunction %2 +%54 = OpTypePointer Uniform %13 +%55 = OpConstant %4 1 +%63 = OpConstant %4 1 +%71 = OpConstant %4 1 %81 = OpConstant %4 0 -%85 = OpTypePointer Function %26 +%85 = OpTypePointer Function %11 %91 = OpConstant %4 1 -%93 = OpTypePointer Function %13 +%93 = OpTypePointer Function %10 %94 = OpConstant %4 0 -%102 = OpTypePointer Input %13 +%102 = OpTypePointer Input %10 %101 = OpVariable %102 Input -%105 = OpTypePointer Input %26 +%105 = OpTypePointer Input %11 %104 = OpVariable %105 Input -%107 = OpVariable %34 Output -%113 = OpTypeSampledImage %16 -%37 = OpFunction %2 None %38 -%28 = OpLabel -%21 = OpVariable %22 Function -%23 = OpVariable %22 Function -%24 = OpVariable %27 Function -%32 = OpLoad %29 %30 -OpBranch %39 -%39 = OpLabel -%40 = OpBitcast %4 %32 -%41 = OpSDiv %4 %40 %3 -OpStore %21 %41 -%42 = OpBitcast %4 %32 -%43 = OpBitwiseAnd %4 %42 %5 -OpStore %23 %43 -%44 = OpLoad %4 %21 -%45 = OpConvertSToF %7 %44 -%46 = OpFMul %7 %45 %6 -%47 = OpFSub %7 %46 %8 -%48 = OpLoad %4 %23 -%49 = OpConvertSToF %7 %48 -%50 = OpFMul %7 %49 %6 -%51 = OpFSub %7 %50 %8 -%52 = OpCompositeConstruct %13 %47 %51 %9 %8 -%55 = OpAccessChain %53 %10 %54 -%56 = OpLoad %12 %55 -%57 = OpCompositeExtract %13 %56 0 -%58 = OpCompositeExtract %7 %57 0 -%59 = OpCompositeExtract %7 %57 1 -%60 = OpCompositeExtract %7 %57 2 -%61 = OpCompositeConstruct %26 %58 %59 %60 -%63 = OpAccessChain %53 %10 %62 -%64 = OpLoad %12 %63 -%65 = OpCompositeExtract %13 %64 1 -%66 = OpCompositeExtract %7 %65 0 -%67 = OpCompositeExtract %7 %65 1 -%68 = OpCompositeExtract %7 %65 2 -%69 = OpCompositeConstruct %26 %66 %67 %68 -%71 = OpAccessChain %53 %10 %70 -%72 = OpLoad %12 %71 -%73 = OpCompositeExtract %13 %72 2 -%74 = OpCompositeExtract %7 %73 0 -%75 = OpCompositeExtract %7 %73 1 -%76 = OpCompositeExtract %7 %73 2 -%77 = OpCompositeConstruct %26 %74 %75 %76 -%79 = OpCompositeConstruct %78 %61 %69 %77 -%80 = OpTranspose %78 %79 -%82 = OpAccessChain %53 %10 %81 -%83 = OpLoad %12 %82 -%84 = OpMatrixTimesVector %13 %83 %52 +%107 = OpVariable %35 Output +%113 = OpTypeSampledImage %17 +%38 = OpFunction %2 None %39 +%30 = OpLabel +%25 = OpVariable %26 Function +%27 = OpVariable %26 Function +%28 = OpVariable %29 Function +%33 = OpLoad %15 %31 +OpBranch %40 +%40 = OpLabel +%41 = OpBitcast %4 %33 +%42 = OpSDiv %4 %41 %3 +OpStore %25 %42 +%43 = OpBitcast %4 %33 +%44 = OpBitwiseAnd %4 %43 %5 +OpStore %27 %44 +%45 = OpLoad %4 %25 +%46 = OpConvertSToF %7 %45 +%47 = OpFMul %7 %46 %6 +%48 = OpFSub %7 %47 %8 +%49 = OpLoad %4 %27 +%50 = OpConvertSToF %7 %49 +%51 = OpFMul %7 %50 %6 +%52 = OpFSub %7 %51 %8 +%53 = OpCompositeConstruct %10 %48 %52 %9 %8 +%56 = OpAccessChain %54 %19 %55 +%57 = OpLoad %13 %56 +%58 = OpCompositeExtract %10 %57 0 +%59 = OpCompositeExtract %7 %58 0 +%60 = OpCompositeExtract %7 %58 1 +%61 = OpCompositeExtract %7 %58 2 +%62 = OpCompositeConstruct %11 %59 %60 %61 +%64 = OpAccessChain %54 %19 %63 +%65 = OpLoad %13 %64 +%66 = OpCompositeExtract %10 %65 1 +%67 = OpCompositeExtract %7 %66 0 +%68 = OpCompositeExtract %7 %66 1 +%69 = OpCompositeExtract %7 %66 2 +%70 = OpCompositeConstruct %11 %67 %68 %69 +%72 = OpAccessChain %54 %19 %71 +%73 = OpLoad %13 %72 +%74 = OpCompositeExtract %10 %73 2 +%75 = OpCompositeExtract %7 %74 0 +%76 = OpCompositeExtract %7 %74 1 +%77 = OpCompositeExtract %7 %74 2 +%78 = OpCompositeConstruct %11 %75 %76 %77 +%79 = OpCompositeConstruct %16 %62 %70 %78 +%80 = OpTranspose %16 %79 +%82 = OpAccessChain %54 %19 %81 +%83 = OpLoad %13 %82 +%84 = OpMatrixTimesVector %10 %83 %53 %86 = OpCompositeExtract %7 %84 0 %87 = OpCompositeExtract %7 %84 1 %88 = OpCompositeExtract %7 %84 2 -%89 = OpCompositeConstruct %26 %86 %87 %88 -%90 = OpMatrixTimesVector %26 %80 %89 -%92 = OpAccessChain %85 %24 %91 +%89 = OpCompositeConstruct %11 %86 %87 %88 +%90 = OpMatrixTimesVector %11 %80 %89 +%92 = OpAccessChain %85 %28 %91 OpStore %92 %90 -%95 = OpAccessChain %93 %24 %94 -OpStore %95 %52 -%96 = OpLoad %25 %24 -%97 = OpCompositeExtract %13 %96 0 -OpStore %33 %97 -%98 = OpCompositeExtract %26 %96 1 -OpStore %35 %98 +%95 = OpAccessChain %93 %28 %94 +OpStore %95 %53 +%96 = OpLoad %12 %28 +%97 = OpCompositeExtract %10 %96 0 +OpStore %34 %97 +%98 = OpCompositeExtract %11 %96 1 +OpStore %36 %98 OpReturn OpFunctionEnd -%108 = OpFunction %2 None %38 +%108 = OpFunction %2 None %39 %99 = OpLabel -%103 = OpLoad %13 %101 -%106 = OpLoad %26 %104 -%100 = OpCompositeConstruct %25 %103 %106 -%109 = OpLoad %16 %15 -%110 = OpLoad %19 %18 +%103 = OpLoad %10 %101 +%106 = OpLoad %11 %104 +%100 = OpCompositeConstruct %12 %103 %106 +%109 = OpLoad %17 %21 +%110 = OpLoad %18 %23 OpBranch %111 %111 = OpLabel -%112 = OpCompositeExtract %26 %100 1 +%112 = OpCompositeExtract %11 %100 1 %114 = OpSampledImage %113 %109 %110 -%115 = OpImageSampleImplicitLod %13 %114 %112 +%115 = OpImageSampleImplicitLod %10 %114 %112 OpStore %107 %115 OpReturn OpFunctionEnd diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap index ae41626ab..6023540f9 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm.snap @@ -9,75 +9,75 @@ expression: dis OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %24 "main" %18 %22 +OpEntryPoint Fragment %24 "main" %19 %22 OpExecutionMode %24 OriginUpperLeft OpSource GLSL 450 -OpName %5 "texture0" -OpName %9 "texture1" -OpName %10 "sampler" -OpName %14 "PushConstants" -OpMemberName %14 0 "index" -OpName %13 "pc" -OpName %18 "tex_coord" +OpName %8 "PushConstants" +OpMemberName %8 0 "index" +OpName %11 "texture0" +OpName %13 "texture1" +OpName %14 "sampler" +OpName %16 "pc" +OpName %19 "tex_coord" OpName %24 "main" OpName %24 "main" -OpDecorate %5 DescriptorSet 0 -OpDecorate %5 Binding 0 -OpDecorate %9 DescriptorSet 0 -OpDecorate %9 Binding 1 -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 2 -OpDecorate %14 Block -OpMemberDecorate %14 0 Offset 0 -OpDecorate %18 Location 0 +OpDecorate %8 Block +OpMemberDecorate %8 0 Offset 0 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 0 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 1 +OpDecorate %14 DescriptorSet 0 +OpDecorate %14 Binding 2 +OpDecorate %19 Location 0 OpDecorate %22 Location 1 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 -%7 = OpTypeFloat 32 -%6 = OpTypeImage %7 2D 0 0 0 1 Unknown -%8 = OpTypePointer UniformConstant %6 -%5 = OpVariable %8 UniformConstant -%9 = OpVariable %8 UniformConstant -%11 = OpTypeSampler -%12 = OpTypePointer UniformConstant %11 -%10 = OpVariable %12 UniformConstant -%14 = OpTypeStruct %4 -%15 = OpTypePointer PushConstant %14 -%13 = OpVariable %15 PushConstant -%17 = OpTypeVector %7 2 -%19 = OpTypePointer Input %17 -%18 = OpVariable %19 Input -%21 = OpTypeVector %7 4 -%23 = OpTypePointer Output %21 +%6 = OpTypeFloat 32 +%5 = OpTypeImage %6 2D 0 0 0 1 Unknown +%7 = OpTypeSampler +%8 = OpTypeStruct %4 +%9 = OpTypeVector %6 2 +%10 = OpTypeVector %6 4 +%12 = OpTypePointer UniformConstant %5 +%11 = OpVariable %12 UniformConstant +%13 = OpVariable %12 UniformConstant +%15 = OpTypePointer UniformConstant %7 +%14 = OpVariable %15 UniformConstant +%17 = OpTypePointer PushConstant %8 +%16 = OpVariable %17 PushConstant +%20 = OpTypePointer Input %9 +%19 = OpVariable %20 Input +%23 = OpTypePointer Output %10 %22 = OpVariable %23 Output %25 = OpTypeFunction %2 %30 = OpTypePointer PushConstant %4 %31 = OpTypeInt 32 1 %32 = OpConstant %31 0 %35 = OpTypeBool -%40 = OpTypeSampledImage %6 +%40 = OpTypeSampledImage %5 %24 = OpFunction %2 None %25 -%16 = OpLabel -%20 = OpLoad %17 %18 -%26 = OpLoad %6 %5 -%27 = OpLoad %6 %9 -%28 = OpLoad %11 %10 +%18 = OpLabel +%21 = OpLoad %9 %19 +%26 = OpLoad %5 %11 +%27 = OpLoad %5 %13 +%28 = OpLoad %7 %14 OpBranch %29 %29 = OpLabel -%33 = OpAccessChain %30 %13 %32 +%33 = OpAccessChain %30 %16 %32 %34 = OpLoad %4 %33 %36 = OpIEqual %35 %34 %3 OpSelectionMerge %37 None OpBranchConditional %36 %38 %39 %38 = OpLabel %41 = OpSampledImage %40 %26 %28 -%42 = OpImageSampleImplicitLod %21 %41 %20 +%42 = OpImageSampleImplicitLod %10 %41 %21 OpStore %22 %42 OpReturn %39 = OpLabel %43 = OpSampledImage %40 %27 %28 -%44 = OpImageSampleImplicitLod %21 %43 %20 +%44 = OpImageSampleImplicitLod %10 %43 %21 OpStore %22 %44 OpReturn %37 = OpLabel From 374f12b6ab90c4fb3b30161508b186611b8f5525 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 23 Mar 2021 10:03:35 -0400 Subject: [PATCH 0611/2212] ID generator for SPIR-V --- src/back/spv/writer.rs | 141 ++++++++++++++++++++--------------------- 1 file changed, 70 insertions(+), 71 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index cfc7e924b..cabceae44 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -21,6 +21,16 @@ pub enum Error { FeatureNotImplemented(&'static str), } +#[derive(Default)] +struct IdGenerator(Word); + +impl IdGenerator { + fn next(&mut self) -> Word { + self.0 += 1; + self.0 + } +} + struct Block { label_id: Word, body: Vec, @@ -242,7 +252,7 @@ struct GlobalVariable { pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, - id_count: u32, + id_gen: IdGenerator, capabilities: crate::FastHashSet, debugs: Vec, annotations: Vec, @@ -270,12 +280,13 @@ impl Writer { return Err(Error::UnsupportedVersion(major, minor)); } let raw_version = ((major as u32) << 16) | ((minor as u32) << 8); - let gl450_ext_inst_id = 1; - let void_type = 2; + let mut id_gen = IdGenerator::default(); + let gl450_ext_inst_id = id_gen.next(); + let void_type = id_gen.next(); Ok(Writer { physical_layout: PhysicalLayout::new(raw_version), logical_layout: LogicalLayout::default(), - id_count: 2, // see `gl450_ext_inst_id` and `void_type` + id_gen, capabilities: options.capabilities.clone(), debugs: vec![], annotations: vec![], @@ -294,11 +305,6 @@ impl Writer { }) } - fn generate_id(&mut self) -> Word { - self.id_count += 1; - self.id_count - } - fn check(&mut self, capabilities: &[spirv::Capability]) -> Result<(), Error> { if capabilities.is_empty() || capabilities @@ -343,7 +349,7 @@ impl Writer { Ok(if let Some(&id) = self.lookup_type.get(&lookup_type) { id } else { - let id = self.generate_id(); + let id = self.id_gen.next(); let instruction = Instruction::type_pointer(id, class, ty_id); instruction.to_words(&mut self.logical_layout.declarations); self.lookup_type.insert(lookup_type, id); @@ -352,7 +358,7 @@ impl Writer { } fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word { - let id = self.generate_id(); + let id = self.id_gen.next(); let instruction = Instruction::constant(type_id, id, value); instruction.to_words(&mut self.logical_layout.declarations); id @@ -368,7 +374,7 @@ impl Writer { let mut function = Function::default(); for (handle, variable) in ir_function.local_variables.iter() { - let id = self.generate_id(); + let id = self.id_gen.next(); if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = variable.name { @@ -392,7 +398,7 @@ impl Writer { .insert(handle, LocalVariable { id, instruction }); } - let prelude_id = self.generate_id(); + let prelude_id = self.id_gen.next(); let mut prelude = Block::new(prelude_id); let mut ep_context = EntryPointContext::default(); @@ -407,7 +413,7 @@ impl Writer { let varying_id = self.write_varying(ir_module, class, name, argument.ty, binding)?; list.push(varying_id); - let id = self.generate_id(); + let id = self.id_gen.next(); prelude .body .push(Instruction::load(argument_type_id, id, varying_id, None)); @@ -417,7 +423,7 @@ impl Writer { ref members, } = ir_module.types[argument.ty].inner { - let struct_id = self.generate_id(); + let struct_id = self.id_gen.next(); let mut constituent_ids = Vec::with_capacity(members.len()); for member in members { let type_id = @@ -427,7 +433,7 @@ impl Writer { let varying_id = self.write_varying(ir_module, class, name, member.ty, binding)?; list.push(varying_id); - let id = self.generate_id(); + let id = self.id_gen.next(); prelude .body .push(Instruction::load(type_id, id, varying_id, None)); @@ -444,7 +450,7 @@ impl Writer { }; ep_context.argument_ids.push(id); } else { - let id = self.generate_id(); + let id = self.id_gen.next(); let instruction = Instruction::function_parameter(argument_type_id, id); function.parameters.push(instruction); parameter_type_ids.push(argument_type_id); @@ -493,7 +499,7 @@ impl Writer { parameter_type_ids, }; - let function_id = self.generate_id(); + let function_id = self.id_gen.next(); if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = ir_function.name { self.debugs.push(Instruction::name(function_id, name)); @@ -521,7 +527,7 @@ impl Writer { if info[handle].is_empty() || var.class != crate::StorageClass::Handle { continue; } - let id = self.generate_id(); + let id = self.id_gen.next(); let result_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(var.ty))?; let gv = &mut self.global_variables[handle.index()]; prelude @@ -544,7 +550,7 @@ impl Writer { } } - let main_id = self.generate_id(); + let main_id = self.id_gen.next(); function.consume(prelude, Instruction::branch(main_id)); self.write_block( main_id, @@ -633,7 +639,7 @@ impl Writer { arena: &Arena, local_ty: LocalType, ) -> Result { - let id = self.generate_id(); + let id = self.id_gen.next(); let instruction = match local_ty { LocalType::Value { vector_size: None, @@ -714,7 +720,7 @@ impl Writer { ) -> Result { let ty = &arena[handle]; - if let Some(local) = self.physical_layout.make_local(&ty.inner) { + let id = if let Some(local) = self.physical_layout.make_local(&ty.inner) { match self.lookup_type.entry(LookupType::Local(local)) { // if it's already known as local, re-use it Entry::Occupied(e) => { @@ -724,12 +730,13 @@ impl Writer { } // also register the type as "local", to avoid duplication Entry::Vacant(e) => { - let id = self.id_count + 1; // has to match the next ID - e.insert(id); + let id = self.id_gen.next(); + *e.insert(id) } } - } - let id = self.generate_id(); + } else { + self.id_gen.next() + }; self.lookup_type.insert(LookupType::Handle(handle), id); if self.flags.contains(WriterFlags::DEBUG) { @@ -1006,7 +1013,7 @@ impl Writer { ty: Handle, binding: &crate::Binding, ) -> Result { - let id = self.generate_id(); + let id = self.id_gen.next(); let pointer_type_id = self.get_pointer_id(&ir_module.types, ty, class)?; Instruction::variable(pointer_type_id, id, class, None) .to_words(&mut self.logical_layout.declarations); @@ -1082,7 +1089,7 @@ impl Writer { ir_module: &crate::Module, global_variable: &crate::GlobalVariable, ) -> Result<(Instruction, Word, spirv::StorageClass), Error> { - let id = self.generate_id(); + let id = self.id_gen.next(); let class = self .physical_layout @@ -1135,7 +1142,7 @@ impl Writer { { Entry::Occupied(e) => *e.get(), _ => { - let id = self.generate_id(); + let id = self.id_gen.next(); let instruction = Instruction::type_function( id, lookup_function_type.return_type_id, @@ -1154,7 +1161,7 @@ impl Writer { constituent_ids: &[Word], block: &mut Block, ) -> Word { - let id = self.generate_id(); + let id = self.id_gen.next(); block.body.push(Instruction::composite_construct( base_type_id, id, @@ -1192,7 +1199,7 @@ impl Writer { } crate::TypeInner::Vector { size, .. } => { for i in 0..size as u32 { - let id = self.generate_id(); + let id = self.id_gen.next(); constituent_ids[i as usize] = id; block.body.push(Instruction::composite_extract( coordinate_scalar_type_id, @@ -1212,7 +1219,7 @@ impl Writer { ref other => unimplemented!("wrong coordinate type {:?}", other), }; - let array_index_f32_id = self.generate_id(); + let array_index_f32_id = self.id_gen.next(); constituent_ids[size as usize - 1] = array_index_f32_id; let array_index_u32_id = self.cached[array_index]; @@ -1276,7 +1283,7 @@ impl Writer { let index_id = self.cached[index]; match *fun_info[base].ty.inner_with(&ir_module.types) { crate::TypeInner::Vector { .. } => { - let id = self.generate_id(); + let id = self.id_gen.next(); let base_id = self.cached[base]; block.body.push(Instruction::vector_extract_dynamic( result_type_id, @@ -1309,7 +1316,7 @@ impl Writer { | crate::TypeInner::Matrix { .. } | crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { - let id = self.generate_id(); + let id = self.id_gen.next(); let base_id = self.cached[base]; block.body.push(Instruction::composite_extract( result_type_id, @@ -1341,7 +1348,7 @@ impl Writer { self.write_composite_construct(result_type_id, &constituent_ids, block) } crate::Expression::Unary { op, expr } => { - let id = self.generate_id(); + let id = self.id_gen.next(); let expr_id = self.cached[expr]; let expr_ty_inner = fun_info[expr].ty.inner_with(&ir_module.types); @@ -1364,7 +1371,7 @@ impl Writer { id } crate::Expression::Binary { op, left, right } => { - let id = self.generate_id(); + let id = self.id_gen.next(); let left_id = self.cached[left]; let right_id = self.cached[right]; @@ -1514,7 +1521,7 @@ impl Writer { None => 0, }; - let id = self.generate_id(); + let id = self.id_gen.next(); let math_op = match fun { // comparison Mf::Abs => { @@ -1639,7 +1646,7 @@ impl Writer { function, )?; - let id = self.generate_id(); + let id = self.id_gen.next(); block .body .push(Instruction::load(result_type_id, id, pointer_id, None)); @@ -1672,7 +1679,7 @@ impl Writer { _ => spirv::Op::Bitcast, }; - let id = self.generate_id(); + let id = self.id_gen.next(); let instruction = Instruction::unary(op, result_type_id, id, expr_id); block.body.push(instruction); id @@ -1692,7 +1699,7 @@ impl Writer { block, )?; - let id = self.generate_id(); + let id = self.id_gen.next(); let image_ty = fun_info[image].ty.inner_with(&ir_module.types); let mut instruction = match *image_ty { @@ -1748,14 +1755,14 @@ impl Writer { block, )?; - let sampled_image_id = self.generate_id(); + let sampled_image_id = self.id_gen.next(); block.body.push(Instruction::sampled_image( sampled_image_type_id, sampled_image_id, image_id, sampler_id, )); - let id = self.generate_id(); + let id = self.id_gen.next(); let depth_id = depth_ref.map(|handle| self.cached[handle]); @@ -1771,7 +1778,7 @@ impl Writer { ); //TODO: cache this! - let zero_id = self.generate_id(); + let zero_id = self.id_gen.next(); self.write_constant_scalar( zero_id, &crate::ScalarValue::Float(0.0), @@ -1857,7 +1864,7 @@ impl Writer { accept, reject, } => { - let id = self.generate_id(); + let id = self.id_gen.next(); let condition_id = self.cached[condition]; let accept_id = self.cached[accept]; let reject_id = self.cached[reject]; @@ -1870,7 +1877,7 @@ impl Writer { crate::Expression::Derivative { axis, expr } => { use crate::DerivativeAxis; - let id = self.generate_id(); + let id = self.id_gen.next(); let expr_id = self.cached[expr]; block.body.push(match axis { DerivativeAxis::X => Instruction::derive_x(result_type_id, id, expr_id), @@ -1945,7 +1952,7 @@ impl Writer { root_id } else { self.temp_chain.reverse(); - let id = self.generate_id(); + let id = self.id_gen.next(); block.body.push(Instruction::access_chain( result_type_id, id, @@ -2007,10 +2014,10 @@ impl Writer { } } crate::Statement::Block(ref block_statements) => { - let scope_id = self.generate_id(); + let scope_id = self.id_gen.next(); function.consume(block, Instruction::branch(scope_id)); - let merge_id = self.generate_id(); + let merge_id = self.id_gen.next(); self.write_block( scope_id, block_statements, @@ -2031,7 +2038,7 @@ impl Writer { } => { let condition_id = self.cached[condition]; - let merge_id = self.generate_id(); + let merge_id = self.id_gen.next(); block.body.push(Instruction::selection_merge( merge_id, spirv::SelectionControl::NONE, @@ -2040,12 +2047,12 @@ impl Writer { let accept_id = if accept.is_empty() { None } else { - Some(self.generate_id()) + Some(self.id_gen.next()) }; let reject_id = if reject.is_empty() { None } else { - Some(self.generate_id()) + Some(self.id_gen.next()) }; function.consume( @@ -2091,18 +2098,18 @@ impl Writer { } => { let selector_id = self.cached[selector]; - let merge_id = self.generate_id(); + let merge_id = self.id_gen.next(); block.body.push(Instruction::selection_merge( merge_id, spirv::SelectionControl::NONE, )); - let default_id = self.generate_id(); + let default_id = self.id_gen.next(); let raw_cases = cases .iter() .map(|c| super::instructions::Case { value: c.value as Word, - label_id: self.generate_id(), + label_id: self.id_gen.next(), }) .collect::>(); @@ -2149,12 +2156,12 @@ impl Writer { ref body, ref continuing, } => { - let preamble_id = self.generate_id(); + let preamble_id = self.id_gen.next(); function.consume(block, Instruction::branch(preamble_id)); - let merge_id = self.generate_id(); - let body_id = self.generate_id(); - let continuing_id = self.generate_id(); + let merge_id = self.id_gen.next(); + let body_id = self.id_gen.next(); + let continuing_id = self.id_gen.next(); // SPIR-V requires the continuing to the `OpLoopMerge`, // so we have to start a new block with it. @@ -2214,7 +2221,7 @@ impl Writer { for (index, &(varying_id, type_id)) in context.result_ids_typed.iter().enumerate() { - let member_value_id = self.generate_id(); + let member_value_id = self.id_gen.next(); block.body.push(Instruction::composite_extract( type_id, member_value_id, @@ -2285,7 +2292,7 @@ impl Writer { ref arguments, result, } => { - let id = self.generate_id(); + let id = self.id_gen.next(); //TODO: avoid heap allocation let mut argument_ids = vec![]; @@ -2330,7 +2337,7 @@ impl Writer { } fn write_physical_layout(&mut self) { - self.physical_layout.bound = self.id_count + 1; + self.physical_layout.bound = self.id_gen.0 + 1; } fn write_logical_layout( @@ -2352,7 +2359,7 @@ impl Writer { match constant.inner { crate::ConstantInner::Composite { .. } => continue, crate::ConstantInner::Scalar { width, ref value } => { - let id = self.generate_id(); + let id = self.id_gen.next(); self.lookup_constant.insert(handle, id); if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = constant.name { @@ -2382,7 +2389,7 @@ impl Writer { match constant.inner { crate::ConstantInner::Scalar { .. } => continue, crate::ConstantInner::Composite { ty, ref components } => { - let id = self.generate_id(); + let id = self.id_gen.next(); self.lookup_constant.insert(handle, id); if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = constant.name { @@ -2464,14 +2471,6 @@ impl Writer { } } -#[test] -fn test_writer_generate_id() { - let mut writer = Writer::new(&Options::default()).unwrap(); - assert_eq!(writer.id_count, 2); - writer.generate_id(); - assert_eq!(writer.id_count, 3); -} - #[test] fn test_write_physical_layout() { let mut writer = Writer::new(&Options::default()).unwrap(); From ee43776c0820e6eafd12a833674976fe527daa8a Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 23 Mar 2021 21:20:01 +0300 Subject: [PATCH 0612/2212] [glsl-out] Add samplers to reflection info --- src/back/glsl/mod.rs | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 222ba8e40..cbc367cd8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -518,9 +518,11 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the name and end the global with a `;` // The leading space is important - writeln!(self.out, " {};", self.get_global_name(handle, global))?; - + let global_name = self.get_global_name(handle, global); + writeln!(self.out, " {};", global_name)?; writeln!(self.out)?; + + self.reflection_names.insert(global.ty, global_name); } // glsl has no concept of samplers so we just ignore it TypeInner::Sampler { .. } => continue, @@ -2058,7 +2060,8 @@ impl<'a, W: Write> Writer<'a, W> { let mut uniforms = FastHashMap::default(); for sampling in info.sampling_set.iter() { - let tex_name = self.names[&NameKey::GlobalVariable(sampling.image)].clone(); + let global = self.module.global_variables[sampling.image].clone(); + let tex_name = self.reflection_names[&global.ty].clone(); match mappings.entry(tex_name) { Entry::Vacant(v) => { @@ -2090,13 +2093,6 @@ impl<'a, W: Write> Writer<'a, W> { }, _ => continue, } - let tex_name = self.names[&NameKey::GlobalVariable(handle)].clone(); - if let Entry::Vacant(e) = mappings.entry(tex_name) { - e.insert(TextureMapping { - texture: handle, - sampler: None, - }); - } } Ok(ReflectionInfo { From 7a246f6a14feefee871e24fa8ead2da1cde70abe Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 23 Mar 2021 22:48:02 -0400 Subject: [PATCH 0613/2212] Validate image queries and valid shader stages for derivatives --- src/lib.rs | 1 - src/valid/analyzer.rs | 6 ++- src/valid/expression.rs | 95 +++++++++++++++++++++++++-------- src/valid/function.rs | 14 +++-- src/valid/interface.rs | 14 ++++- src/valid/mod.rs | 11 ++++ tests/out/collatz.info.ron.snap | 6 +++ tests/out/shadow.info.ron.snap | 9 ++++ 8 files changed, 127 insertions(+), 29 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 4f1992d3d..8d2590f3f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -120,7 +120,6 @@ pub enum ShaderStage { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] -#[allow(missing_docs)] // The names are self evident pub enum StorageClass { /// Function locals. Function, diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 7175e9462..9e8e81c91 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -6,7 +6,7 @@ Figures out the following properties: - expression reference counts !*/ -use super::{CallError, ExpressionError, FunctionError, ModuleInfo, ValidationFlags}; +use super::{CallError, ExpressionError, FunctionError, ModuleInfo, ShaderStages, ValidationFlags}; use crate::{ arena::{Arena, Handle}, proc::{ResolveContext, TypeResolution}, @@ -164,6 +164,8 @@ impl ExpressionInfo { pub struct FunctionInfo { /// Validation flags. flags: ValidationFlags, + /// Set of shader stages where calling this function is valid. + pub available_stages: ShaderStages, /// Uniformity characteristics. pub uniformity: Uniformity, /// Function may kill the invocation. @@ -676,6 +678,7 @@ impl ModuleInfo { ) -> Result { let mut info = FunctionInfo { flags, + available_stages: ShaderStages::all(), uniformity: Uniformity::new(), may_kill: false, sampling_set: crate::FastHashSet::default(), @@ -779,6 +782,7 @@ fn uniform_control_flow() { let mut info = FunctionInfo { flags: ValidationFlags::all(), + available_stages: ShaderStages::all(), uniformity: Uniformity::new(), may_kill: false, sampling_set: crate::FastHashSet::default(), diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 457a86789..fbcd5b67e 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,4 +1,4 @@ -use super::FunctionInfo; +use super::{FunctionInfo, ShaderStages, TypeFlags}; use crate::{ arena::{Arena, Handle}, proc::ResolveError, @@ -59,6 +59,12 @@ pub enum ExpressionError { ExpectedGlobalVariable, #[error("Calling an undeclared function {0:?}")] CallToUndeclaredFunction(Handle), + #[error("Needs to be an image instead of {0:?}")] + ExpectedImageType(Handle), + #[error("Needs to be an image instead of {0:?}")] + ExpectedSamplerType(Handle), + #[error("Unable to operate on image class {0:?}")] + InvalidImageClass(crate::ImageClass), } struct ExpressionTypeResolver<'a> { @@ -88,7 +94,8 @@ impl super::Validator { function: &crate::Function, module: &crate::Module, info: &FunctionInfo, - ) -> Result<(), ExpressionError> { + other_infos: &[FunctionInfo], + ) -> Result { use crate::{Expression as E, ScalarKind as Sk, TypeInner as Ti}; let resolver = ExpressionTypeResolver { @@ -97,7 +104,7 @@ impl super::Validator { info, }; - match *expression { + let stages = match *expression { E::Access { base, index } => { match *resolver.resolve(base)? { Ti::Vector { .. } @@ -124,6 +131,7 @@ impl super::Validator { return Err(ExpressionError::InvalidIndexType(index)); } } + ShaderStages::all() } E::AccessIndex { base, index } => { let limit = match *resolver.resolve(base)? { @@ -147,12 +155,14 @@ impl super::Validator { if index >= limit { return Err(ExpressionError::IndexOutOfBounds(base, index)); } + ShaderStages::all() } E::Constant(handle) => { let _ = module .constants .try_get(handle) .ok_or(ExpressionError::ConstantDoesntExist(handle))?; + ShaderStages::all() } E::Compose { ref components, ty } => { match module @@ -269,31 +279,42 @@ impl super::Validator { return Err(ExpressionError::InvalidComposeType(ty)); } } + ShaderStages::all() } E::FunctionArgument(index) => { if index >= function.arguments.len() as u32 { return Err(ExpressionError::FunctionArgumentDoesntExist(index)); } + ShaderStages::all() } E::GlobalVariable(handle) => { let _ = module .global_variables .try_get(handle) .ok_or(ExpressionError::GlobalVarDoesntExist(handle))?; + ShaderStages::all() } E::LocalVariable(handle) => { let _ = function .local_variables .try_get(handle) .ok_or(ExpressionError::LocalVarDoesntExist(handle))?; + ShaderStages::all() } - E::Load { pointer } => match *resolver.resolve(pointer)? { - Ti::Pointer { .. } | Ti::ValuePointer { .. } => {} - ref other => { - log::error!("Loading {:?}", other); - return Err(ExpressionError::InvalidPointerType(pointer)); + E::Load { pointer } => { + match *resolver.resolve(pointer)? { + Ti::Pointer { base, .. } + if self.types[base.index()] + .flags + .contains(TypeFlags::SIZED | TypeFlags::DATA) => {} + Ti::ValuePointer { .. } => {} + ref other => { + log::error!("Loading {:?}", other); + return Err(ExpressionError::InvalidPointerType(pointer)); + } } - }, + ShaderStages::all() + } #[allow(unused)] E::ImageSample { image, @@ -303,16 +324,43 @@ impl super::Validator { offset, level, depth_ref, - } => {} + } => ShaderStages::all(), #[allow(unused)] E::ImageLoad { image, coordinate, array_index, index, - } => {} - #[allow(unused)] - E::ImageQuery { image, query } => {} + } => ShaderStages::all(), + E::ImageQuery { image, query } => { + match function.expressions[image] { + crate::Expression::GlobalVariable(var_handle) => { + let var = &module.global_variables[var_handle]; + match module.types[var.ty].inner { + Ti::Image { class, arrayed, .. } => { + let can_level = match class { + crate::ImageClass::Sampled { multi, .. } => !multi, + crate::ImageClass::Storage { .. } => false, + crate::ImageClass::Depth { .. } => true, + }; + let good = match query { + crate::ImageQuery::NumLayers => arrayed, + crate::ImageQuery::Size { level: Some(_) } + | crate::ImageQuery::NumLevels => can_level, + crate::ImageQuery::Size { level: None } + | crate::ImageQuery::NumSamples => !can_level, + }; + if !good { + return Err(ExpressionError::InvalidImageClass(class)); + } + } + _ => return Err(ExpressionError::ExpectedImageType(var.ty)), + } + } + _ => return Err(ExpressionError::ExpectedGlobalVariable), + } + ShaderStages::all() + } E::Unary { op, expr } => { use crate::UnaryOperator as Uo; let inner = resolver.resolve(expr)?; @@ -326,6 +374,7 @@ impl super::Validator { return Err(ExpressionError::InvalidUnaryOperandType(op, expr)); } } + ShaderStages::all() } E::Binary { op, left, right } => { use crate::BinaryOperator as Bo; @@ -472,6 +521,7 @@ impl super::Validator { if !good { return Err(ExpressionError::InvalidBinaryOperandTypes(op, left, right)); } + ShaderStages::all() } E::Select { condition, @@ -500,11 +550,10 @@ impl super::Validator { if !condition_good || accept_inner != reject_inner { return Err(ExpressionError::InvalidSelectTypes); } + ShaderStages::all() } #[allow(unused)] - E::Derivative { axis, expr } => { - //TODO: check stage - } + E::Derivative { axis, expr } => ShaderStages::FRAGMENT, E::Relational { fun, argument } => { use crate::RelationalFunction as Rf; let argument_inner = resolver.resolve(argument)?; @@ -529,6 +578,7 @@ impl super::Validator { } }, } + ShaderStages::all() } #[allow(unused)] E::Math { @@ -536,23 +586,22 @@ impl super::Validator { arg, arg1, arg2, - } => {} + } => ShaderStages::all(), #[allow(unused)] E::As { expr, kind, convert, - } => {} - #[allow(unused)] - E::Call(function) => {} + } => ShaderStages::all(), + E::Call(function) => other_infos[function.index()].available_stages, E::ArrayLength(expr) => match *resolver.resolve(expr)? { - Ti::Array { .. } => {} + Ti::Array { .. } => ShaderStages::all(), ref other => { log::error!("Array length of {:?}", other); return Err(ExpressionError::InvalidArrayType(expr)); } }, - } - Ok(()) + }; + Ok(stages) } } diff --git a/src/valid/function.rs b/src/valid/function.rs index 88f2a2795..50653a78d 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -453,7 +453,7 @@ impl super::Validator { module: &crate::Module, mod_info: &ModuleInfo, ) -> Result { - let info = mod_info.process_function(fun, module, self.flags)?; + let mut info = mod_info.process_function(fun, module, self.flags)?; for (var_handle, var) in fun.local_variables.iter() { self.validate_local_var(var, &module.types, &module.constants) @@ -482,8 +482,16 @@ impl super::Validator { self.valid_expression_set.insert(handle.index()); } if !self.flags.contains(ValidationFlags::EXPRESSIONS) { - if let Err(error) = self.validate_expression(handle, expr, fun, module, &info) { - return Err(FunctionError::Expression { handle, error }); + match self.validate_expression( + handle, + expr, + fun, + module, + &info, + &mod_info.functions, + ) { + Ok(stages) => info.available_stages &= stages, + Err(error) => return Err(FunctionError::Expression { handle, error }), } } } diff --git a/src/valid/interface.rs b/src/valid/interface.rs index b6fe1a5a4..ee54a9f86 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -1,6 +1,6 @@ use super::{ analyzer::{FunctionInfo, GlobalUse}, - Disalignment, FunctionError, ModuleInfo, TypeFlags, + Disalignment, FunctionError, ModuleInfo, ShaderStages, TypeFlags, }; use crate::arena::{Arena, Handle}; @@ -56,6 +56,8 @@ pub enum EntryPointError { UnexpectedWorkgroupSize, #[error("Workgroup size is out of range")] OutOfRangeWorkgroupSize, + #[error("Uses operations forbidden at this stage")] + ForbiddenStageOperations, #[error("Global variable {0:?} is used incorrectly as {1:?}")] InvalidGlobalUsage(Handle, GlobalUse), #[error("Bindings for {0:?} conflict with other resource")] @@ -370,8 +372,18 @@ impl super::Validator { return Err(EntryPointError::UnexpectedWorkgroupSize); } + let stage_bit = match ep.stage { + crate::ShaderStage::Vertex => ShaderStages::VERTEX, + crate::ShaderStage::Fragment => ShaderStages::FRAGMENT, + crate::ShaderStage::Compute => ShaderStages::COMPUTE, + }; + let info = self.validate_function(&ep.function, module, &mod_info)?; + if !info.available_stages.contains(stage_bit) { + return Err(EntryPointError::ForbiddenStageOperations); + } + self.location_mask.clear(); for (index, fa) in ep.function.arguments.iter().enumerate() { let ctx = VaryingContext { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 615b2c1e5..aff271475 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -32,6 +32,17 @@ bitflags::bitflags! { } } +bitflags::bitflags! { + /// Validation flags. + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + pub struct ShaderStages: u8 { + const VERTEX = 0x1; + const FRAGMENT = 0x2; + const COMPUTE = 0x4; + } +} + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ModuleInfo { diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 7a6949094..77dcd1958 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -8,6 +8,9 @@ expression: output flags: ( bits: 7, ), + available_stages: ( + bits: 7, + ), uniformity: ( non_uniform_result: Some(5), requirements: ( @@ -350,6 +353,9 @@ expression: output flags: ( bits: 7, ), + available_stages: ( + bits: 7, + ), uniformity: ( non_uniform_result: Some(5), requirements: ( diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 817820f84..622aa4b80 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -8,6 +8,9 @@ expression: output flags: ( bits: 7, ), + available_stages: ( + bits: 7, + ), uniformity: ( non_uniform_result: Some(44), requirements: ( @@ -1006,6 +1009,9 @@ expression: output flags: ( bits: 7, ), + available_stages: ( + bits: 7, + ), uniformity: ( non_uniform_result: Some(44), requirements: ( @@ -2634,6 +2640,9 @@ expression: output flags: ( bits: 7, ), + available_stages: ( + bits: 7, + ), uniformity: ( non_uniform_result: Some(44), requirements: ( From 8c73c0c5df8828fc32fc8f1c75eeb06f87d8aaac Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 23 Mar 2021 23:21:36 -0400 Subject: [PATCH 0614/2212] Validate derivatives and image loads --- src/valid/expression.rs | 150 ++++++++++++++++++++++++++++++++-------- 1 file changed, 123 insertions(+), 27 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index fbcd5b67e..c2d18d415 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -65,6 +65,18 @@ pub enum ExpressionError { ExpectedSamplerType(Handle), #[error("Unable to operate on image class {0:?}")] InvalidImageClass(crate::ImageClass), + #[error("Derivatives can only be taken from scalar and vector floats")] + InvalidDerivative, + #[error("Image array index parameter is misplaced")] + InvalidImageArrayIndex, + #[error("Image other index parameter is misplaced")] + InvalidImageOtherIndex, + #[error("Image array index type of {0:?} is not an integer scalar")] + InvalidImageArrayIndexType(Handle), + #[error("Image other index type of {0:?} is not an integer scalar")] + InvalidImageOtherIndexType(Handle), + #[error("Image coordinate index type of {1:?} does not match dimension {0:?}")] + InvalidImageCoordinateType(crate::ImageDimension, Handle), } struct ExpressionTypeResolver<'a> { @@ -325,39 +337,111 @@ impl super::Validator { level, depth_ref, } => ShaderStages::all(), - #[allow(unused)] E::ImageLoad { image, coordinate, array_index, index, - } => ShaderStages::all(), - E::ImageQuery { image, query } => { - match function.expressions[image] { + } => { + let var = match function.expressions[image] { crate::Expression::GlobalVariable(var_handle) => { - let var = &module.global_variables[var_handle]; - match module.types[var.ty].inner { - Ti::Image { class, arrayed, .. } => { - let can_level = match class { - crate::ImageClass::Sampled { multi, .. } => !multi, - crate::ImageClass::Storage { .. } => false, - crate::ImageClass::Depth { .. } => true, - }; - let good = match query { - crate::ImageQuery::NumLayers => arrayed, - crate::ImageQuery::Size { level: Some(_) } - | crate::ImageQuery::NumLevels => can_level, - crate::ImageQuery::Size { level: None } - | crate::ImageQuery::NumSamples => !can_level, - }; - if !good { - return Err(ExpressionError::InvalidImageClass(class)); - } - } - _ => return Err(ExpressionError::ExpectedImageType(var.ty)), - } + &module.global_variables[var_handle] } _ => return Err(ExpressionError::ExpectedGlobalVariable), + }; + match module.types[var.ty].inner { + Ti::Image { + class, + arrayed, + dim, + } => { + match (dim, resolver.resolve(coordinate)?) { + ( + crate::ImageDimension::D1, + &Ti::Scalar { + kind: crate::ScalarKind::Sint, + .. + }, + ) + | ( + crate::ImageDimension::D2, + &Ti::Vector { + kind: crate::ScalarKind::Sint, + .. + }, + ) + | ( + crate::ImageDimension::D3, + &Ti::Vector { + kind: crate::ScalarKind::Sint, + .. + }, + ) => {} + _ => { + return Err(ExpressionError::InvalidImageCoordinateType( + dim, coordinate, + )) + } + } + let needs_index = match class { + crate::ImageClass::Storage { .. } => false, + _ => true, + }; + if arrayed != array_index.is_some() { + return Err(ExpressionError::InvalidImageArrayIndex); + } + if needs_index != index.is_some() { + return Err(ExpressionError::InvalidImageOtherIndex); + } + if let Some(expr) = array_index { + match *resolver.resolve(expr)? { + Ti::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => {} + _ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)), + } + } + if let Some(expr) = index { + match *resolver.resolve(expr)? { + Ti::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => {} + _ => return Err(ExpressionError::InvalidImageOtherIndexType(expr)), + } + } + } + _ => return Err(ExpressionError::ExpectedImageType(var.ty)), + } + ShaderStages::all() + } + E::ImageQuery { image, query } => { + let var = match function.expressions[image] { + crate::Expression::GlobalVariable(var_handle) => { + &module.global_variables[var_handle] + } + _ => return Err(ExpressionError::ExpectedGlobalVariable), + }; + match module.types[var.ty].inner { + Ti::Image { class, arrayed, .. } => { + let can_level = match class { + crate::ImageClass::Sampled { multi, .. } => !multi, + crate::ImageClass::Storage { .. } => false, + crate::ImageClass::Depth { .. } => true, + }; + let good = match query { + crate::ImageQuery::NumLayers => arrayed, + crate::ImageQuery::Size { level: Some(_) } + | crate::ImageQuery::NumLevels => can_level, + crate::ImageQuery::Size { level: None } + | crate::ImageQuery::NumSamples => !can_level, + }; + if !good { + return Err(ExpressionError::InvalidImageClass(class)); + } + } + _ => return Err(ExpressionError::ExpectedImageType(var.ty)), } ShaderStages::all() } @@ -552,8 +636,20 @@ impl super::Validator { } ShaderStages::all() } - #[allow(unused)] - E::Derivative { axis, expr } => ShaderStages::FRAGMENT, + E::Derivative { axis: _, expr } => { + match *resolver.resolve(expr)? { + Ti::Scalar { + kind: crate::ScalarKind::Float, + .. + } + | Ti::Vector { + kind: crate::ScalarKind::Float, + .. + } => {} + _ => return Err(ExpressionError::InvalidDerivative), + } + ShaderStages::FRAGMENT + } E::Relational { fun, argument } => { use crate::RelationalFunction as Rf; let argument_inner = resolver.resolve(argument)?; From 69a0fbd00e72ff8c9196dfbee7452e389ef40d91 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 24 Mar 2021 00:00:03 -0400 Subject: [PATCH 0615/2212] Validate image sampling and value casting --- src/valid/expression.rs | 206 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 202 insertions(+), 4 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index c2d18d415..c996c9dbc 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -77,6 +77,26 @@ pub enum ExpressionError { InvalidImageOtherIndexType(Handle), #[error("Image coordinate index type of {1:?} does not match dimension {0:?}")] InvalidImageCoordinateType(crate::ImageDimension, Handle), + #[error("Comparison sampling mismatch: image has class {image:?}, but the sampler is comparison={sampler}, and the reference was provided={has_ref}")] + ComparisonSamplingMismatch { + image: crate::ImageClass, + sampler: bool, + has_ref: bool, + }, + #[error("Sample offset constant {1:?} doesn't match the image dimension {0:?}")] + InvalidSampleOffset(crate::ImageDimension, Handle), + #[error("Depth reference {0:?} is not a scalar float")] + InvalidDepthReference(Handle), + #[error("Sample level is not compatible with the image dimension {0:?}")] + InvalidSampleLevel(crate::ImageDimension), + #[error("Sample level (exact) type {0:?} is not a scalar float")] + InvalidSampleLevelExactType(Handle), + #[error("Sample level (bias) type {0:?} is not a scalar float")] + InvalidSampleLevelBiasType(Handle), + #[error("Sample level (gradient) of {1:?} doesn't match the image dimension {0:?}")] + InvalidSampleLevelGradientType(crate::ImageDimension, Handle), + #[error("Unable to cast")] + InvalidCastArgument, } struct ExpressionTypeResolver<'a> { @@ -327,7 +347,6 @@ impl super::Validator { } ShaderStages::all() } - #[allow(unused)] E::ImageSample { image, sampler, @@ -336,7 +355,176 @@ impl super::Validator { offset, level, depth_ref, - } => ShaderStages::all(), + } => { + let image_var = match function.expressions[image] { + crate::Expression::GlobalVariable(var_handle) => { + &module.global_variables[var_handle] + } + _ => return Err(ExpressionError::ExpectedGlobalVariable), + }; + let sampler_var = match function.expressions[sampler] { + crate::Expression::GlobalVariable(var_handle) => { + &module.global_variables[var_handle] + } + _ => return Err(ExpressionError::ExpectedGlobalVariable), + }; + let comparison = match module.types[sampler_var.ty].inner { + Ti::Sampler { comparison } => comparison, + _ => return Err(ExpressionError::ExpectedSamplerType(sampler_var.ty)), + }; + + let (class, dim) = match module.types[image_var.ty].inner { + Ti::Image { + //TODO: should we check that this is Float-only? + class, + arrayed, + dim, + } => { + let image_depth = match class { + crate::ImageClass::Sampled { + kind: _, + multi: false, + } => false, + crate::ImageClass::Depth => true, + _ => return Err(ExpressionError::InvalidImageClass(class)), + }; + if comparison != depth_ref.is_some() || (comparison && !image_depth) { + return Err(ExpressionError::ComparisonSamplingMismatch { + image: class, + sampler: comparison, + has_ref: depth_ref.is_some(), + }); + } + if arrayed != array_index.is_some() { + return Err(ExpressionError::InvalidImageArrayIndex); + } + if let Some(expr) = array_index { + match *resolver.resolve(expr)? { + Ti::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => {} + _ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)), + } + } + (class, dim) + } + _ => return Err(ExpressionError::ExpectedImageType(image_var.ty)), + }; + + let num_components = match dim { + crate::ImageDimension::D1 => 1, + crate::ImageDimension::D2 => 2, + crate::ImageDimension::D3 | crate::ImageDimension::Cube => 3, + }; + match *resolver.resolve(coordinate)? { + Ti::Scalar { + kind: crate::ScalarKind::Float, + .. + } if num_components == 1 => {} + Ti::Vector { + size, + kind: crate::ScalarKind::Float, + .. + } if size as u32 == num_components => {} + _ => return Err(ExpressionError::InvalidImageCoordinateType(dim, coordinate)), + } + if let Some(const_handle) = offset { + let good = match module.constants[const_handle].inner { + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Sint(_), + } => num_components == 1, + crate::ConstantInner::Scalar { .. } => false, + crate::ConstantInner::Composite { ty, .. } => { + match module.types[ty].inner { + Ti::Vector { + size, + kind: crate::ScalarKind::Float, + .. + } => size as u32 == num_components, + _ => false, + } + } + }; + if !good { + return Err(ExpressionError::InvalidSampleOffset(dim, const_handle)); + } + } + + if let Some(expr) = depth_ref { + match *resolver.resolve(expr)? { + Ti::Scalar { + kind: crate::ScalarKind::Float, + .. + } => {} + _ => return Err(ExpressionError::InvalidDepthReference(expr)), + } + } + let can_level = match class { + crate::ImageClass::Sampled { multi, .. } => !multi, + crate::ImageClass::Storage { .. } => false, + crate::ImageClass::Depth { .. } => true, + }; + + match level { + // require `can_level` here? + crate::SampleLevel::Auto => ShaderStages::FRAGMENT, + crate::SampleLevel::Zero => ShaderStages::all(), + crate::SampleLevel::Exact(expr) if can_level => { + match *resolver.resolve(expr)? { + Ti::Scalar { + kind: crate::ScalarKind::Float, + .. + } => {} + _ => return Err(ExpressionError::InvalidSampleLevelExactType(expr)), + } + ShaderStages::all() + } + crate::SampleLevel::Bias(expr) => { + match *resolver.resolve(expr)? { + Ti::Scalar { + kind: crate::ScalarKind::Float, + .. + } => {} + _ => return Err(ExpressionError::InvalidSampleLevelBiasType(expr)), + } + ShaderStages::all() + } + crate::SampleLevel::Gradient { x, y } => { + match *resolver.resolve(x)? { + Ti::Scalar { + kind: crate::ScalarKind::Float, + .. + } if num_components == 1 => {} + Ti::Vector { + size, + kind: crate::ScalarKind::Float, + .. + } if size as u32 == num_components => {} + _ => { + return Err(ExpressionError::InvalidSampleLevelGradientType(dim, x)) + } + } + match *resolver.resolve(y)? { + Ti::Scalar { + kind: crate::ScalarKind::Float, + .. + } if num_components == 1 => {} + Ti::Vector { + size, + kind: crate::ScalarKind::Float, + .. + } if size as u32 == num_components => {} + _ => { + return Err(ExpressionError::InvalidSampleLevelGradientType(dim, y)) + } + } + ShaderStages::all() + } + _ => return Err(ExpressionError::InvalidSampleLevel(dim)), + } + } E::ImageLoad { image, coordinate, @@ -683,12 +871,22 @@ impl super::Validator { arg1, arg2, } => ShaderStages::all(), - #[allow(unused)] E::As { expr, kind, convert, - } => ShaderStages::all(), + } => { + let prev_kind = resolver + .resolve(expr)? + .scalar_kind() + .ok_or(ExpressionError::InvalidCastArgument)?; + if !convert && prev_kind == crate::ScalarKind::Bool + || kind == crate::ScalarKind::Bool + { + return Err(ExpressionError::InvalidCastArgument); + } + ShaderStages::all() + } E::Call(function) => other_infos[function.index()].available_stages, E::ArrayLength(expr) => match *resolver.resolve(expr)? { Ti::Array { .. } => ShaderStages::all(), From a0b5717fed0bd1c8536fb2204f308d6db39d295f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 24 Mar 2021 11:50:36 -0400 Subject: [PATCH 0616/2212] Validate image stores --- src/valid/expression.rs | 28 ++---------- src/valid/function.rs | 97 ++++++++++++++++++++++++++++++++--------- src/valid/mod.rs | 20 +++++++++ 3 files changed, 100 insertions(+), 45 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index c996c9dbc..7128a0c23 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -75,7 +75,7 @@ pub enum ExpressionError { InvalidImageArrayIndexType(Handle), #[error("Image other index type of {0:?} is not an integer scalar")] InvalidImageOtherIndexType(Handle), - #[error("Image coordinate index type of {1:?} does not match dimension {0:?}")] + #[error("Image coordinate type of {1:?} does not match dimension {0:?}")] InvalidImageCoordinateType(crate::ImageDimension, Handle), #[error("Comparison sampling mismatch: image has class {image:?}, but the sampler is comparison={sampler}, and the reference was provided={has_ref}")] ComparisonSamplingMismatch { @@ -543,34 +543,14 @@ impl super::Validator { arrayed, dim, } => { - match (dim, resolver.resolve(coordinate)?) { - ( - crate::ImageDimension::D1, - &Ti::Scalar { - kind: crate::ScalarKind::Sint, - .. - }, - ) - | ( - crate::ImageDimension::D2, - &Ti::Vector { - kind: crate::ScalarKind::Sint, - .. - }, - ) - | ( - crate::ImageDimension::D3, - &Ti::Vector { - kind: crate::ScalarKind::Sint, - .. - }, - ) => {} + match resolver.resolve(coordinate)?.image_storage_coordinates() { + Some(coord_dim) if coord_dim == dim => {} _ => { return Err(ExpressionError::InvalidImageCoordinateType( dim, coordinate, )) } - } + }; let needs_index = match class { crate::ImageClass::Storage { .. } => false, _ => true, diff --git a/src/valid/function.rs b/src/valid/function.rs index 50653a78d..081b2decd 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -83,12 +83,10 @@ pub enum FunctionError { pointer: Handle, value: Handle, }, - #[error("The image array can't be indexed by {0:?}")] - InvalidArrayIndex(Handle), #[error("The expression {0:?} is currupted")] InvalidExpression(Handle), - #[error("The expression {0:?} is not an image")] - InvalidImage(Handle), + #[error("Image store parameters are invalid")] + InvalidImageStore(#[source] ExpressionError), #[error("Call to {function:?} is invalid")] InvalidCall { function: Handle, @@ -120,6 +118,7 @@ struct BlockContext<'a> { info: &'a FunctionInfo, expressions: &'a Arena, types: &'a Arena, + global_vars: &'a Arena, functions: &'a Arena, return_type: Option>, } @@ -131,6 +130,7 @@ impl<'a> BlockContext<'a> { info, expressions: &fun.expressions, types: &module.types, + global_vars: &module.global_variables, functions: &module.functions, return_type: fun.result.as_ref().map(|fr| fr.ty), } @@ -142,6 +142,7 @@ impl<'a> BlockContext<'a> { info: self.info, expressions: self.expressions, types: self.types, + global_vars: self.global_vars, functions: self.functions, return_type: self.return_type, } @@ -329,7 +330,7 @@ impl super::Validator { let mut current = pointer; loop { let _ = context.resolve_type(current)?; - match context.expressions[current] { + match *context.get_expression(current)? { crate::Expression::Access { base, .. } | crate::Expression::AccessIndex { base, .. } => current = base, crate::Expression::LocalVariable(_) @@ -368,28 +369,82 @@ impl super::Validator { } S::ImageStore { image, - coordinate: _, + coordinate, array_index, value, } => { - let _expected_coordinate_ty = match *context.get_expression(image)? { - crate::Expression::GlobalVariable(_var_handle) => (), //TODO - _ => return Err(FunctionError::InvalidImage(image)), - }; - match *context.resolve_type(value)? { - Ti::Scalar { .. } | Ti::Vector { .. } => {} + //Note: this code uses a lot of `FunctionError::InvalidImageStore`, + // and could probably be refactored. + let var = match *context.get_expression(image)? { + crate::Expression::GlobalVariable(var_handle) => { + &context.global_vars[var_handle] + } _ => { - return Err(FunctionError::InvalidStoreValue(value)); + return Err(FunctionError::InvalidImageStore( + ExpressionError::ExpectedGlobalVariable, + )) } - } - if let Some(expr) = array_index { - match *context.resolve_type(expr)? { - Ti::Scalar { - kind: crate::ScalarKind::Sint, - width: _, - } => (), - _ => return Err(FunctionError::InvalidArrayIndex(expr)), + }; + + let value_ty = match context.types[var.ty].inner { + Ti::Image { + class, + arrayed, + dim, + } => { + match context + .resolve_type(coordinate)? + .image_storage_coordinates() + { + Some(coord_dim) if coord_dim == dim => {} + _ => { + return Err(FunctionError::InvalidImageStore( + ExpressionError::InvalidImageCoordinateType( + dim, coordinate, + ), + )) + } + }; + if arrayed != array_index.is_some() { + return Err(FunctionError::InvalidImageStore( + ExpressionError::InvalidImageArrayIndex, + )); + } + if let Some(expr) = array_index { + match *context.resolve_type(expr)? { + Ti::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => {} + _ => { + return Err(FunctionError::InvalidImageStore( + ExpressionError::InvalidImageArrayIndexType(expr), + )) + } + } + } + match class { + crate::ImageClass::Storage(format) => crate::TypeInner::Vector { + kind: format.into(), + size: crate::VectorSize::Quad, + width: 4, + }, + _ => { + return Err(FunctionError::InvalidImageStore( + ExpressionError::InvalidImageClass(class), + )) + } + } } + _ => { + return Err(FunctionError::InvalidImageStore( + ExpressionError::ExpectedImageType(var.ty), + )) + } + }; + + if *context.resolve_type(value)? != value_ty { + return Err(FunctionError::InvalidStoreValue(value)); } } S::Call { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index aff271475..0d316e1f6 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -136,6 +136,26 @@ impl crate::TypeInner { Self::Array { .. } | Self::Image { .. } | Self::Sampler { .. } => false, } } + + fn image_storage_coordinates(&self) -> Option { + match *self { + Self::Scalar { + kind: crate::ScalarKind::Sint, + .. + } => Some(crate::ImageDimension::D1), + Self::Vector { + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Sint, + .. + } => Some(crate::ImageDimension::D2), + Self::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Sint, + .. + } => Some(crate::ImageDimension::D3), + _ => None, + } + } } impl Validator { From 06d777b609973ea12858766aea9b6008f75d043b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 24 Mar 2021 16:01:33 -0400 Subject: [PATCH 0617/2212] Make layout validation optional, disable the struct size check --- src/valid/interface.rs | 22 +++++++++++++--------- src/valid/mod.rs | 5 +++++ src/valid/type.rs | 17 +++++++++++------ tests/out/collatz.info.ron.snap | 4 ++-- tests/out/shadow.info.ron.snap | 6 +++--- 5 files changed, 34 insertions(+), 20 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index ee54a9f86..a66ed65e1 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -1,6 +1,6 @@ use super::{ analyzer::{FunctionInfo, GlobalUse}, - Disalignment, FunctionError, ModuleInfo, ShaderStages, TypeFlags, + Disalignment, FunctionError, ModuleInfo, ShaderStages, TypeFlags, ValidationFlags, }; use crate::arena::{Arena, Handle}; @@ -275,10 +275,12 @@ impl super::Validator { match types[var.ty].inner { crate::TypeInner::Struct { block: true, .. } => { if let Err((ty_handle, ref disalignment)) = type_info.storage_layout { - return Err(GlobalVariableError::Alignment( - ty_handle, - disalignment.clone(), - )); + if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { + return Err(GlobalVariableError::Alignment( + ty_handle, + disalignment.clone(), + )); + } } } _ => return Err(GlobalVariableError::InvalidType), @@ -293,10 +295,12 @@ impl super::Validator { match types[var.ty].inner { crate::TypeInner::Struct { block: true, .. } => { if let Err((ty_handle, ref disalignment)) = type_info.uniform_layout { - return Err(GlobalVariableError::Alignment( - ty_handle, - disalignment.clone(), - )); + if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { + return Err(GlobalVariableError::Alignment( + ty_handle, + disalignment.clone(), + )); + } } } _ => return Err(GlobalVariableError::InvalidType), diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 0d316e1f6..5ed602521 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -26,9 +26,14 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ValidationFlags: u8 { + /// Expressions. const EXPRESSIONS = 0x1; + /// Statements and blocks of them. const BLOCKS = 0x2; + /// Uniformity of control flow for operations that require it. const CONTROL_FLOW_UNIFORMITY = 0x4; + /// Host-shareable structure layouts. + const STRUCT_LAYOUTS = 0x8; } } diff --git a/src/valid/type.rs b/src/valid/type.rs index ff89d3f6f..508666722 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -209,19 +209,19 @@ impl super::Validator { } } - let effective_alignment = match stride { + let effective_stride = match stride { Some(stride) => stride.get(), None => base_layout.size, }; let uniform_layout = - if effective_alignment & UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { + if effective_stride & UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { base_info.uniform_layout.clone() } else { Err(( handle, Disalignment::ArrayStride { - stride: effective_alignment, - alignment: effective_alignment, + stride: effective_stride, + alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK + 1, }, )) }; @@ -295,12 +295,17 @@ impl super::Validator { storage_layout = storage_layout.or_else(|_| base_info.storage_layout.clone()); } - if uniform_layout.is_ok() && offset % UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { + // disabled temporarily, see https://github.com/gpuweb/gpuweb/issues/1558 + const CHECK_STRUCT_SIZE: bool = false; + if CHECK_STRUCT_SIZE + && uniform_layout.is_ok() + && offset & UNIFORM_LAYOUT_ALIGNMENT_MASK != 0 + { uniform_layout = Err(( handle, Disalignment::StructSize { size: offset, - alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK, + alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK + 1, }, )); } diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 77dcd1958..517e4c545 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -6,7 +6,7 @@ expression: output functions: [ ( flags: ( - bits: 7, + bits: 15, ), available_stages: ( bits: 7, @@ -351,7 +351,7 @@ expression: output entry_points: [ ( flags: ( - bits: 7, + bits: 15, ), available_stages: ( bits: 7, diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 622aa4b80..0abf67c0c 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -6,7 +6,7 @@ expression: output functions: [ ( flags: ( - bits: 7, + bits: 15, ), available_stages: ( bits: 7, @@ -1007,7 +1007,7 @@ expression: output ), ( flags: ( - bits: 7, + bits: 15, ), available_stages: ( bits: 7, @@ -2638,7 +2638,7 @@ expression: output entry_points: [ ( flags: ( - bits: 7, + bits: 15, ), available_stages: ( bits: 7, From c8bac4b618aa0f331078881ced860e6a4b45f659 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Mar 2021 00:46:31 -0400 Subject: [PATCH 0618/2212] [spv-in] convert the shift to unsigned --- src/front/spv/mod.rs | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 90dbb4f16..dd7a791f1 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -546,6 +546,40 @@ impl> Parser { Ok(()) } + fn parse_expr_shift_op( + &mut self, + expressions: &mut Arena, + op: crate::BinaryOperator, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let p1_id = self.next()?; + let p2_id = self.next()?; + + let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let p2_lexp = self.lookup_expression.lookup(p2_id)?; + // convert the shift to Uint + let p2_handle = expressions.append(crate::Expression::As { + expr: p2_lexp.handle, + kind: crate::ScalarKind::Uint, + convert: false, + }); + + let expr = crate::Expression::Binary { + op, + left: p1_lexp.handle, + right: p2_handle, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } + fn insert_composite( &self, root_expr: Handle, @@ -1158,16 +1192,16 @@ impl> Parser { Op::ShiftRightLogical => { inst.expect(5)?; //TODO: convert input and result to usigned - self.parse_expr_binary_op(expressions, crate::BinaryOperator::ShiftRight)?; + self.parse_expr_shift_op(expressions, crate::BinaryOperator::ShiftRight)?; } Op::ShiftRightArithmetic => { inst.expect(5)?; //TODO: convert input and result to signed - self.parse_expr_binary_op(expressions, crate::BinaryOperator::ShiftRight)?; + self.parse_expr_shift_op(expressions, crate::BinaryOperator::ShiftRight)?; } Op::ShiftLeftLogical => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::ShiftLeft)?; + self.parse_expr_shift_op(expressions, crate::BinaryOperator::ShiftLeft)?; } // Sampling Op::Image => { From 26f629ccb4734ce8a736a93f06725970947a3668 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Mar 2021 00:47:18 -0400 Subject: [PATCH 0619/2212] [spv-in] fix image operand iteration, add support for constant offsets --- src/front/spv/image.rs | 76 +++++++++++++++++++++++++++++++----------- 1 file changed, 56 insertions(+), 20 deletions(-) diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 915df2803..b280953c8 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -205,10 +205,11 @@ impl> super::Parser { let coordinate_id = self.next()?; let value_id = self.next()?; - if words_left != 0 { - let image_ops = self.next()?; + let image_ops = if words_left != 0 { self.next()? } else { 0 }; + + if image_ops != 0 { let other = spirv::ImageOperands::from_bits_truncate(image_ops); - log::warn!("Skipping {:?}", other); + log::warn!("Unknown image write ops {:?}", other); for _ in 1..words_left { self.next()?; } @@ -258,11 +259,17 @@ impl> super::Parser { let image_id = self.next()?; let coordinate_id = self.next()?; - let mut index = None; - while words_left != 0 { - let image_ops = self.next()?; + let mut image_ops = if words_left != 0 { words_left -= 1; - match spirv::ImageOperands::from_bits_truncate(image_ops) { + self.next()? + } else { + 0 + }; + + let mut index = None; + while image_ops != 0 { + let bit = 1 << image_ops.trailing_zeros(); + match spirv::ImageOperands::from_bits_truncate(bit) { spirv::ImageOperands::LOD => { let lod_expr = self.next()?; let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; @@ -276,13 +283,14 @@ impl> super::Parser { words_left -= 1; } other => { - log::warn!("Skipping {:?}", other); + log::warn!("Unknown image load op {:?}", other); for _ in 0..words_left { self.next()?; } break; } } + image_ops ^= bit; } let image_lexp = self.lookup_expression.lookup(image_id)?; @@ -335,11 +343,18 @@ impl> super::Parser { let sampled_image_id = self.next()?; let coordinate_id = self.next()?; - let mut level = crate::SampleLevel::Auto; - while words_left != 0 { - let image_ops = self.next()?; + let mut image_ops = if words_left != 0 { words_left -= 1; - match spirv::ImageOperands::from_bits_truncate(image_ops) { + self.next()? + } else { + 0 + }; + + let mut level = crate::SampleLevel::Auto; + let mut offset = None; + while image_ops != 0 { + let bit = 1 << image_ops.trailing_zeros(); + match spirv::ImageOperands::from_bits_truncate(bit) { spirv::ImageOperands::BIAS => { let bias_expr = self.next()?; let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; @@ -352,14 +367,21 @@ impl> super::Parser { level = crate::SampleLevel::Exact(lod_handle); words_left -= 1; } + spirv::ImageOperands::CONST_OFFSET => { + let offset_constant = self.next()?; + let offset_handle = self.lookup_constant.lookup(offset_constant)?.handle; + offset = Some(offset_handle); + words_left -= 1; + } other => { - log::warn!("Skipping {:?}", other); + log::warn!("Unknown image sample op {:?}", other); for _ in 0..words_left { self.next()?; } break; } } + image_ops ^= bit; } let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; @@ -400,7 +422,7 @@ impl> super::Parser { sampler: si_lexp.sampler, coordinate, array_index, - offset: None, //TODO + offset, level, depth_ref: None, }; @@ -427,11 +449,18 @@ impl> super::Parser { let coordinate_id = self.next()?; let dref_id = self.next()?; - let mut level = crate::SampleLevel::Auto; - while words_left != 0 { - let image_ops = self.next()?; + let mut image_ops = if words_left != 0 { words_left -= 1; - match spirv::ImageOperands::from_bits_truncate(image_ops) { + self.next()? + } else { + 0 + }; + + let mut level = crate::SampleLevel::Auto; + let mut offset = None; + while image_ops != 0 { + let bit = 1 << image_ops.trailing_zeros(); + match spirv::ImageOperands::from_bits_truncate(bit) { spirv::ImageOperands::BIAS => { let bias_expr = self.next()?; let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; @@ -444,14 +473,21 @@ impl> super::Parser { level = crate::SampleLevel::Exact(lod_handle); words_left -= 1; } + spirv::ImageOperands::CONST_OFFSET => { + let offset_constant = self.next()?; + let offset_handle = self.lookup_constant.lookup(offset_constant)?.handle; + offset = Some(offset_handle); + words_left -= 1; + } other => { - log::warn!("Skipping {:?}", other); + log::warn!("Unknown image sample dref op {:?}", other); for _ in 0..words_left { self.next()?; } break; } } + image_ops ^= bit; } let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; @@ -501,7 +537,7 @@ impl> super::Parser { sampler: si_lexp.sampler, coordinate, array_index, - offset: None, //TODO + offset, level, depth_ref: Some(dref_lexp.handle), }; From 4fb41332982a03528640a73bccfcfe14bc066ac7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Mar 2021 01:04:37 -0400 Subject: [PATCH 0620/2212] [spv-in] fix image array index type to be signed --- src/front/spv/image.rs | 2 +- tests/out/shadow.info.ron.snap | 2 +- tests/out/shadow.ron.snap | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index b280953c8..1859ecceb 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -88,7 +88,7 @@ fn extract_image_coordinates( }; let array_index_f32 = expressions.append(extra_expr); let array_index = expressions.append(crate::Expression::As { - kind: crate::ScalarKind::Uint, + kind: crate::ScalarKind::Sint, expr: array_index_f32, convert: true, }); diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 0abf67c0c..ee2b1c2c8 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -985,7 +985,7 @@ expression: output ref_count: 1, assignable_global: None, ty: Value(Scalar( - kind: Uint, + kind: Sint, width: 4, )), ), diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index cda0423ff..8ba659a14 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -1046,7 +1046,7 @@ expression: output ), As( expr: 69, - kind: Uint, + kind: Sint, convert: true, ), ImageSample( From e87f57d82c44b12fe0288d876b050e9ddd1d6e1b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Mar 2021 01:05:33 -0400 Subject: [PATCH 0621/2212] Fix expression validation check --- src/valid/function.rs | 2 +- tests/in/shadow.wgsl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 081b2decd..cc67fa68e 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -536,7 +536,7 @@ impl super::Validator { if expr.needs_pre_emit() { self.valid_expression_set.insert(handle.index()); } - if !self.flags.contains(ValidationFlags::EXPRESSIONS) { + if self.flags.contains(ValidationFlags::EXPRESSIONS) { match self.validate_expression( handle, expr, diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index d68b93ef5..8ccea6700 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -23,7 +23,7 @@ var s_lights: [[access(read)]] Lights; [[group(0), binding(2)]] var t_shadow: texture_depth_2d_array; [[group(0), binding(3)]] -var sampler_shadow: sampler; +var sampler_shadow: sampler_comparison; fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { if (homogeneous_coords.w <= 0.0) { From 7d042337e29ce51248bd25b0339a579e744cde5b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Mar 2021 11:30:18 -0400 Subject: [PATCH 0622/2212] Align the block decoration with SPIR-V, require storage buffers --- src/back/spv/helpers.rs | 16 +++++++-- src/back/spv/instructions.rs | 6 ++++ src/back/spv/layout.rs | 20 ----------- src/back/spv/mod.rs | 3 ++ src/back/spv/writer.rs | 64 ++++++++++++----------------------- src/front/spv/mod.rs | 5 +-- src/lib.rs | 1 + src/valid/interface.rs | 38 ++++++++------------- src/valid/type.rs | 20 +++++++++-- tests/in/boids.wgsl | 1 - tests/in/shadow.wgsl | 1 - tests/out/boids.spvasm.snap | 15 ++++---- tests/out/collatz.spvasm.snap | 11 +++--- tests/out/quad.spvasm.snap | 4 +++ tests/out/shadow.ron.snap | 2 +- tests/out/shadow.spvasm.snap | 11 +++--- tests/out/skybox.spvasm.snap | 4 +++ 17 files changed, 107 insertions(+), 115 deletions(-) diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index 5facbe8b6..35b138959 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -1,13 +1,13 @@ use spirv::Word; -pub(crate) fn bytes_to_words(bytes: &[u8]) -> Vec { +pub(super) fn bytes_to_words(bytes: &[u8]) -> Vec { bytes .chunks(4) .map(|chars| chars.iter().rev().fold(0u32, |u, c| (u << 8) | *c as u32)) .collect() } -pub(crate) fn string_to_words(input: &str) -> Vec { +pub(super) fn string_to_words(input: &str) -> Vec { let bytes = input.as_bytes(); let mut words = bytes_to_words(bytes); @@ -18,3 +18,15 @@ pub(crate) fn string_to_words(input: &str) -> Vec { words } + +pub(super) fn map_storage_class(class: crate::StorageClass) -> spirv::StorageClass { + match class { + crate::StorageClass::Handle => spirv::StorageClass::UniformConstant, + crate::StorageClass::Function => spirv::StorageClass::Function, + crate::StorageClass::Private => spirv::StorageClass::Private, + crate::StorageClass::Storage => spirv::StorageClass::StorageBuffer, + crate::StorageClass::Uniform => spirv::StorageClass::Uniform, + crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, + crate::StorageClass::PushConstant => spirv::StorageClass::PushConstant, + } +} diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index b1033c802..18de62be0 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -81,6 +81,12 @@ impl super::Instruction { // Extension Instructions // + pub(super) fn extension(name: &str) -> Self { + let mut instruction = Self::new(Op::Extension); + instruction.add_operands(helpers::string_to_words(name)); + instruction + } + pub(super) fn ext_inst_import(id: Word, name: &str) -> Self { let mut instruction = Self::new(Op::ExtInstImport); instruction.set_result(id); diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index b2879089f..5708157ba 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -23,26 +23,6 @@ impl PhysicalLayout { sink.extend(iter::once(self.bound)); sink.extend(iter::once(self.instruction_schema)); } - - pub(super) fn supports_storage_buffers(&self) -> bool { - self.version >= 0x10300 - } - - pub(super) fn map_storage_class(&self, class: crate::StorageClass) -> spirv::StorageClass { - match class { - crate::StorageClass::Handle => spirv::StorageClass::UniformConstant, - crate::StorageClass::Function => spirv::StorageClass::Function, - crate::StorageClass::Private => spirv::StorageClass::Private, - crate::StorageClass::Storage if self.supports_storage_buffers() => { - spirv::StorageClass::StorageBuffer - } - crate::StorageClass::Storage | crate::StorageClass::Uniform => { - spirv::StorageClass::Uniform - } - crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, - crate::StorageClass::PushConstant => spirv::StorageClass::PushConstant, - } - } } impl LogicalLayout { diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 4251b5cb4..e4fa14019 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -1,3 +1,6 @@ +/*! Standard Portable Intermediate Representation (SPIR-V) backend +!*/ + mod helpers; mod instructions; mod layout; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index cabceae44..91fcada40 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,5 +1,6 @@ -/*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ -use super::{Instruction, LogicalLayout, Options, PhysicalLayout, WriterFlags}; +use super::{ + helpers::map_storage_class, Instruction, LogicalLayout, Options, PhysicalLayout, WriterFlags, +}; use crate::{ arena::{Arena, Handle}, proc::{Layouter, TypeResolution}, @@ -141,7 +142,7 @@ impl PhysicalLayout { }, crate::TypeInner::Pointer { base, class } => LocalType::Pointer { base, - class: self.map_storage_class(class), + class: map_storage_class(class), }, crate::TypeInner::ValuePointer { size, @@ -152,7 +153,7 @@ impl PhysicalLayout { vector_size: size, kind, width, - pointer_class: Some(self.map_storage_class(class)), + pointer_class: Some(map_storage_class(class)), }, _ => return None, }) @@ -266,9 +267,6 @@ pub struct Writer { lookup_constant: crate::FastHashMap, Word>, global_variables: Vec, cached: CachedExpressions, - // TODO: this is a type property that depends on the global variable that uses it - // so it may require us to duplicate the type! - struct_type_handles: crate::FastHashMap, crate::StorageAccess>, gl450_ext_inst_id: Word, temp_chain: Vec, } @@ -283,6 +281,7 @@ impl Writer { let mut id_gen = IdGenerator::default(); let gl450_ext_inst_id = id_gen.next(); let void_type = id_gen.next(); + Ok(Writer { physical_layout: PhysicalLayout::new(raw_version), logical_layout: LogicalLayout::default(), @@ -299,7 +298,6 @@ impl Writer { lookup_constant: crate::FastHashMap::default(), global_variables: Vec::new(), cached: CachedExpressions::default(), - struct_type_handles: crate::FastHashMap::default(), gl450_ext_inst_id, temp_chain: Vec::new(), }) @@ -815,18 +813,10 @@ impl Writer { crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), } } - crate::TypeInner::Struct { - block: true, - ref members, - } => { - if let Some(&access) = self.struct_type_handles.get(&handle) { - let decoration = if access.is_empty() { - spirv::Decoration::Block - } else { - spirv::Decoration::BufferBlock - }; + crate::TypeInner::Struct { block, ref members } => { + if block { self.annotations - .push(Instruction::decorate(id, decoration, &[])); + .push(Instruction::decorate(id, spirv::Decoration::Block, &[])); } let mut current_offset = 0; @@ -877,20 +867,9 @@ impl Writer { } Instruction::type_struct(id, member_ids.as_slice()) } - crate::TypeInner::Struct { - block: false, - ref members, - } => { - let mut member_ids = Vec::with_capacity(members.len()); - for member in members { - let member_id = self.get_type_id(arena, LookupType::Handle(member.ty))?; - member_ids.push(member_id); - } - Instruction::type_struct(id, member_ids.as_slice()) - } crate::TypeInner::Pointer { base, class } => { let type_id = self.get_type_id(arena, LookupType::Handle(base))?; - let raw_class = self.physical_layout.map_storage_class(class); + let raw_class = map_storage_class(class); Instruction::type_pointer(id, raw_class, type_id) } crate::TypeInner::ValuePointer { @@ -899,7 +878,7 @@ impl Writer { width, class, } => { - let raw_class = self.physical_layout.map_storage_class(class); + let raw_class = map_storage_class(class); let type_id = self.get_type_id( arena, LookupType::Local(LocalType::Value { @@ -1091,9 +1070,7 @@ impl Writer { ) -> Result<(Instruction, Word, spirv::StorageClass), Error> { let id = self.id_gen.next(); - let class = self - .physical_layout - .map_storage_class(global_variable.class); + let class = map_storage_class(global_variable.class); self.check(class.required_capabilities())?; let init_word = global_variable @@ -2345,6 +2322,15 @@ impl Writer { ir_module: &crate::Module, mod_info: &ModuleInfo, ) -> Result<(), Error> { + let has_storage_buffers = ir_module + .global_variables + .iter() + .any(|(_, var)| var.class == crate::StorageClass::Storage); + if self.physical_layout.version < 0x10300 && has_storage_buffers { + // enable the storage buffer class on < SPV-1.3 + Instruction::extension("SPV_KHR_storage_buffer_storage_class") + .to_words(&mut self.logical_layout.extensions); + } Instruction::type_void(self.void_type).to_words(&mut self.logical_layout.declarations); Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); @@ -2371,14 +2357,6 @@ impl Writer { } } - // then gather the struct type handles, then affect types - self.struct_type_handles.clear(); - for (_, var) in ir_module.global_variables.iter() { - if let crate::TypeInner::Struct { .. } = ir_module.types[var.ty].inner { - self.struct_type_handles.insert(var.ty, var.storage_access); - } - } - // then all types, some of them may rely on constants and struct type set for (handle, _) in ir_module.types.iter() { self.write_type_declaration_arena(&ir_module.types, &mod_info.layouter, handle)?; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index dd7a791f1..46e1453ff 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2406,7 +2406,6 @@ impl> Parser { let mut members = Vec::with_capacity(inst.wc as usize - 2); let mut member_type_ids = Vec::with_capacity(members.capacity()); - let mut host_shared = false; for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; member_type_ids.push(type_id); @@ -2415,8 +2414,6 @@ impl> Parser { .future_member_decor .remove(&(id, i)) .unwrap_or_default(); - // this is a bit of a hack - host_shared |= decor.offset.is_some(); members.push(crate::StructMember { name: decor.name, ty, @@ -2427,7 +2424,7 @@ impl> Parser { } let inner = crate::TypeInner::Struct { - block: block_decor.is_some() || host_shared, + block: block_decor.is_some(), members, }; let ty_handle = module.types.append(crate::Type { diff --git a/src/lib.rs b/src/lib.rs index 8d2590f3f..ee1ca0869 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -393,6 +393,7 @@ pub enum TypeInner { }, /// User-defined structure. Struct { + /// This is a top-level host-shareable structure. block: bool, members: Vec, }, diff --git a/src/valid/interface.rs b/src/valid/interface.rs index a66ed65e1..576f4448c 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -272,42 +272,32 @@ impl super::Validator { let (allowed_storage_access, required_type_flags, is_resource) = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), crate::StorageClass::Storage => { - match types[var.ty].inner { - crate::TypeInner::Struct { block: true, .. } => { - if let Err((ty_handle, ref disalignment)) = type_info.storage_layout { - if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { - return Err(GlobalVariableError::Alignment( - ty_handle, - disalignment.clone(), - )); - } - } + if let Err((ty_handle, ref disalignment)) = type_info.storage_layout { + if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { + return Err(GlobalVariableError::Alignment( + ty_handle, + disalignment.clone(), + )); } - _ => return Err(GlobalVariableError::InvalidType), } ( crate::StorageAccess::all(), - TypeFlags::DATA | TypeFlags::HOST_SHARED, + TypeFlags::DATA | TypeFlags::HOST_SHARED | TypeFlags::BLOCK, true, ) } crate::StorageClass::Uniform => { - match types[var.ty].inner { - crate::TypeInner::Struct { block: true, .. } => { - if let Err((ty_handle, ref disalignment)) = type_info.uniform_layout { - if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { - return Err(GlobalVariableError::Alignment( - ty_handle, - disalignment.clone(), - )); - } - } + if let Err((ty_handle, ref disalignment)) = type_info.uniform_layout { + if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { + return Err(GlobalVariableError::Alignment( + ty_handle, + disalignment.clone(), + )); } - _ => return Err(GlobalVariableError::InvalidType), } ( crate::StorageAccess::empty(), - TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED, + TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED | TypeFlags::BLOCK, true, ) } diff --git a/src/valid/type.rs b/src/valid/type.rs index 508666722..c3622f289 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -14,6 +14,8 @@ bitflags::bitflags! { const INTERFACE = 0x4; /// Can be used for host-shareable structures. const HOST_SHARED = 0x8; + /// This is a top-level host-shareable type. + const BLOCK = 0x10; } } @@ -61,6 +63,8 @@ pub enum TypeError { size: u32, base_size: u32, }, + #[error("The composite type contains a block structure")] + NestedBlock, } // Only makes sense if `flags.contains(HOST_SHARED)` @@ -163,6 +167,9 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { return Err(TypeError::InvalidArrayBaseType(base)); } + if base_info.flags.contains(TypeFlags::BLOCK) { + return Err(TypeError::NestedBlock); + } let base_layout = &layouter[base]; if let Some(stride) = stride { @@ -239,7 +246,10 @@ impl super::Validator { } } Ti::Struct { block, ref members } => { - let mut flags = TypeFlags::all(); + let mut flags = TypeFlags::DATA + | TypeFlags::SIZED + | TypeFlags::HOST_SHARED + | TypeFlags::INTERFACE; let mut uniform_layout = Ok(()); let mut storage_layout = Ok(()); let mut offset = 0; @@ -248,13 +258,16 @@ impl super::Validator { return Err(TypeError::UnresolvedBase(member.ty)); } let base_info = &self.types[member.ty.index()]; - flags &= base_info.flags; if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); } if block && !base_info.flags.contains(TypeFlags::INTERFACE) { return Err(TypeError::InvalidBlockType(member.ty)); } + if base_info.flags.contains(TypeFlags::BLOCK) { + return Err(TypeError::NestedBlock); + } + flags &= base_info.flags; let base_layout = &layouter[member.ty]; let (range, _alignment) = layouter.member_placement(offset, member); @@ -294,6 +307,9 @@ impl super::Validator { uniform_layout = uniform_layout.or_else(|_| base_info.uniform_layout.clone()); storage_layout = storage_layout.or_else(|_| base_info.storage_layout.clone()); } + if block { + flags |= TypeFlags::BLOCK; + } // disabled temporarily, see https://github.com/gpuweb/gpuweb/issues/1558 const CHECK_STRUCT_SIZE: bool = false; diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index f41a6ffa0..935d8ee08 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -1,6 +1,5 @@ const NUM_PARTICLES: u32 = 1500u; -[[block]] struct Particle { pos : vec2; vel : vec2; diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 8ccea6700..f40802cb4 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -6,7 +6,6 @@ struct Globals { [[group(0), binding(0)]] var u_globals: Globals; -[[block]] struct Light { proj: mat4x4; pos: vec4; diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index 0df16acec..41e343a60 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -7,6 +7,7 @@ expression: dis ; Generator: rspirv ; Bound: 221 OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %43 "main" %40 @@ -53,7 +54,7 @@ OpMemberDecorate %17 4 Offset 16 OpMemberDecorate %17 5 Offset 20 OpMemberDecorate %17 6 Offset 24 OpDecorate %18 ArrayStride 16 -OpDecorate %19 BufferBlock +OpDecorate %19 Block OpMemberDecorate %19 0 Offset 0 OpDecorate %21 DescriptorSet 0 OpDecorate %21 Binding 0 @@ -84,9 +85,9 @@ OpDecorate %40 BuiltIn GlobalInvocationId %20 = OpTypeVector %4 3 %22 = OpTypePointer Uniform %17 %21 = OpVariable %22 Uniform -%24 = OpTypePointer Uniform %19 -%23 = OpVariable %24 Uniform -%25 = OpVariable %24 Uniform +%24 = OpTypePointer StorageBuffer %19 +%23 = OpVariable %24 StorageBuffer +%25 = OpVariable %24 StorageBuffer %27 = OpTypePointer Function %15 %33 = OpTypePointer Function %8 %38 = OpTypePointer Function %4 @@ -94,9 +95,9 @@ OpDecorate %40 BuiltIn GlobalInvocationId %40 = OpVariable %41 Input %44 = OpTypeFunction %2 %47 = OpTypeBool -%51 = OpTypePointer Uniform %18 -%52 = OpTypePointer Uniform %16 -%53 = OpTypePointer Uniform %15 +%51 = OpTypePointer StorageBuffer %18 +%52 = OpTypePointer StorageBuffer %16 +%53 = OpTypePointer StorageBuffer %15 %54 = OpConstant %8 0 %55 = OpConstant %8 0 %58 = OpConstant %8 1 diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index 379b5a3f0..472cebff2 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -7,6 +7,7 @@ expression: dis ; Generator: rspirv ; Bound: 62 OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %48 "main" %45 @@ -22,7 +23,7 @@ OpName %45 "global_id" OpName %48 "main" OpName %48 "main" OpDecorate %8 ArrayStride 4 -OpDecorate %9 BufferBlock +OpDecorate %9 Block OpMemberDecorate %9 0 Offset 0 OpDecorate %11 DescriptorSet 0 OpDecorate %11 Binding 0 @@ -36,16 +37,16 @@ OpDecorate %45 BuiltIn GlobalInvocationId %8 = OpTypeRuntimeArray %4 %9 = OpTypeStruct %8 %10 = OpTypeVector %4 3 -%12 = OpTypePointer Uniform %9 -%11 = OpVariable %12 Uniform +%12 = OpTypePointer StorageBuffer %9 +%11 = OpVariable %12 StorageBuffer %14 = OpTypePointer Function %4 %19 = OpTypeFunction %4 %4 %26 = OpTypeBool %46 = OpTypePointer Input %10 %45 = OpVariable %46 Input %49 = OpTypeFunction %2 -%51 = OpTypePointer Uniform %8 -%53 = OpTypePointer Uniform %4 +%51 = OpTypePointer StorageBuffer %8 +%53 = OpTypePointer StorageBuffer %4 %55 = OpTypeInt 32 1 %56 = OpConstant %55 0 %60 = OpConstant %55 0 diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index 62a1dd336..425fdedd5 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -15,6 +15,8 @@ OpExecutionMode %47 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" OpName %9 "VertexOutput" +OpMemberName %9 0 "uv" +OpMemberName %9 1 "position" OpName %12 "u_texture" OpName %14 "u_sampler" OpName %16 "out" @@ -27,6 +29,8 @@ OpName %28 "main" OpName %44 "uv" OpName %47 "main" OpName %47 "main" +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 8 OpDecorate %12 DescriptorSet 0 OpDecorate %12 Binding 0 OpDecorate %14 DescriptorSet 0 diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index 8ba659a14..055887ff1 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -150,7 +150,7 @@ expression: output ( name: Some("Light"), inner: Struct( - block: true, + block: false, members: [ ( name: Some("proj"), diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index 23bee506c..cf78faaed 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -7,6 +7,7 @@ expression: dis ; Generator: rspirv ; Bound: 137 OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %81 "fs_main" %73 %76 %79 @@ -41,7 +42,7 @@ OpMemberDecorate %17 0 MatrixStride 16 OpMemberDecorate %17 1 Offset 64 OpMemberDecorate %17 2 Offset 80 OpDecorate %18 ArrayStride 96 -OpDecorate %19 BufferBlock +OpDecorate %19 Block OpMemberDecorate %19 0 Offset 0 OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 0 @@ -80,8 +81,8 @@ OpDecorate %79 Location 0 %24 = OpConstantComposite %23 %8 %8 %8 %26 = OpTypePointer Uniform %14 %25 = OpVariable %26 Uniform -%28 = OpTypePointer Uniform %19 -%27 = OpVariable %28 Uniform +%28 = OpTypePointer StorageBuffer %19 +%27 = OpVariable %28 StorageBuffer %30 = OpTypePointer UniformConstant %20 %29 = OpVariable %30 UniformConstant %32 = OpTypePointer UniformConstant %21 @@ -102,8 +103,8 @@ OpDecorate %79 Location 0 %82 = OpTypeFunction %2 %92 = OpTypePointer Uniform %13 %93 = OpConstant %56 0 -%101 = OpTypePointer Uniform %18 -%103 = OpTypePointer Uniform %17 +%101 = OpTypePointer StorageBuffer %18 +%103 = OpTypePointer StorageBuffer %17 %104 = OpConstant %56 0 %36 = OpFunction %4 None %37 %34 = OpFunctionParameter %10 diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index 3f544eae7..112aacac5 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -14,6 +14,8 @@ OpEntryPoint Fragment %108 "fs_main" %101 %104 %107 OpExecutionMode %108 OriginUpperLeft OpSource GLSL 450 OpName %12 "VertexOutput" +OpMemberName %12 0 "position" +OpMemberName %12 1 "uv" OpName %14 "Data" OpMemberName %14 0 "proj_inv" OpMemberName %14 1 "view" @@ -32,6 +34,8 @@ OpName %101 "position" OpName %104 "uv" OpName %108 "fs_main" OpName %108 "fs_main" +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 16 OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %14 0 ColMajor From 372b2d314ebcb69ca212e3314c05257119dae413 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Mar 2021 12:26:35 -0400 Subject: [PATCH 0623/2212] Adjust lints for Rust clippy 1.51 --- src/front/glsl/parser.rs | 2 +- src/lib.rs | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 4255ec495..0d255d6d5 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,4 +1,4 @@ -#![allow(clippy::panic, clippy::needless_lifetimes)] +#![allow(clippy::panic, clippy::needless_lifetimes, clippy::upper_case_acronyms)] use pomelo::pomelo; pomelo! { //%verbose; diff --git a/src/lib.rs b/src/lib.rs index ee1ca0869..d48db7ef9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,13 +20,16 @@ emitted in order to take effect. This happens in one of the following ways: !*/ +// TODO: use `strip_prefix` instead when Rust 1.45 <= MSRV #![allow( + renamed_and_removed_lints, + unknown_lints, // requires Rust 1.51 clippy::new_without_default, clippy::unneeded_field_pattern, - clippy::match_like_matches_macro + clippy::match_like_matches_macro, + clippy::manual_strip, + clippy::unknown_clippy_lints, )] -// TODO: use `strip_prefix` instead when Rust 1.45 <= MSRV -#![allow(clippy::manual_strip, clippy::unknown_clippy_lints)] #![warn( trivial_casts, trivial_numeric_casts, From 2b163dc2a17579cdabe43fb6dcced463ccaf6f0f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 25 Mar 2021 23:49:30 -0400 Subject: [PATCH 0624/2212] [msl] fix pointer address spaces, private forwarding and initialization --- src/back/msl/writer.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 060f1a9cd..c0d581693 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -109,6 +109,7 @@ impl crate::StorageClass { match *self { crate::StorageClass::Uniform | crate::StorageClass::Storage + | crate::StorageClass::Private | crate::StorageClass::Handle => true, _ => false, } @@ -117,14 +118,15 @@ impl crate::StorageClass { fn get_name(&self, global_use: GlobalUse) -> Option<&'static str> { match *self { Self::Handle => None, - Self::Uniform => Some("constant"), + Self::Uniform | Self::PushConstant => Some("constant"), //TODO: should still be "constant" for read-only buffers Self::Storage => Some(if global_use.contains(GlobalUse::WRITE) { "device" } else { - "storage " + "storage" }), - Self::Private | Self::Function | Self::WorkGroup | Self::PushConstant => Some(""), + Self::Private | Self::Function => Some("thread"), + Self::WorkGroup => Some("threadgroup"), } } } @@ -1386,11 +1388,11 @@ impl Writer { }; write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; - if let Some(value) = var.init { - let value_str = &self.names[&NameKey::Constant(value)]; - write!(self.out, " = {}", value_str)?; - } - writeln!(self.out, ";")?; + let value_str = match var.init { + Some(value) => &self.names[&NameKey::Constant(value)], + None => "{}", + }; + writeln!(self.out, " = {};", value_str)?; } // Now refactor the inputs in a way that the rest of the code expects From bf193bb535517e821b0b5938554fac4ae8fba610 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 26 Mar 2021 00:14:01 -0400 Subject: [PATCH 0625/2212] [msl] don't put expressions in double scopes --- src/back/msl/writer.rs | 113 ++++++++++++++++++++----------------- tests/out/boids.msl.snap | 46 +++++++-------- tests/out/collatz.msl.snap | 10 ++-- tests/out/quad.msl.snap | 6 +- tests/out/shadow.msl.snap | 14 ++--- tests/out/skybox.msl.snap | 10 ++-- 6 files changed, 104 insertions(+), 95 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c0d581693..61bc1d433 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -183,7 +183,7 @@ impl Writer { if i != 0 { write!(self.out, ", ")?; } - self.put_expression(handle, context)?; + self.put_expression(handle, context, true)?; } write!(self.out, ")")?; Ok(()) @@ -196,10 +196,10 @@ impl Writer { level: Option>, context: &ExpressionContext, ) -> Result<(), Error> { - self.put_expression(image, context)?; + self.put_expression(image, context, false)?; write!(self.out, ".get_{}(", query)?; if let Some(expr) = level { - self.put_expression(expr, context)?; + self.put_expression(expr, context, true)?; } write!(self.out, ")")?; Ok(()) @@ -209,6 +209,7 @@ impl Writer { &mut self, expr_handle: Handle, context: &ExpressionContext, + is_scoped: bool, ) -> Result<(), Error> { // Add to the set in order to track the stack size. #[cfg(test)] @@ -225,13 +226,13 @@ impl Writer { log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { crate::Expression::Access { base, index } => { - self.put_expression(base, context)?; + self.put_expression(base, context, false)?; write!(self.out, "[")?; - self.put_expression(index, context)?; + self.put_expression(index, context, true)?; write!(self.out, "]")?; } crate::Expression::AccessIndex { base, index } => { - self.put_expression(base, context)?; + self.put_expression(base, context, false)?; let base_res = &context.info[base].ty; let mut resolved = base_res.inner_with(&context.module.types); let base_ty_handle = match *resolved { @@ -300,7 +301,7 @@ impl Writer { if i != 0 { write!(self.out, ", ")?; } - self.put_expression(component, context)?; + self.put_expression(component, context, true)?; } write!(self.out, "}}")?; } @@ -335,7 +336,7 @@ impl Writer { } crate::Expression::Load { pointer } => { //write!(self.out, "*")?; - self.put_expression(pointer, context)?; + self.put_expression(pointer, context, is_scoped)?; } crate::Expression::ImageSample { image, @@ -350,18 +351,18 @@ impl Writer { Some(_) => "sample_compare", None => "sample", }; - self.put_expression(image, context)?; + self.put_expression(image, context, false)?; write!(self.out, ".{}(", op)?; - self.put_expression(sampler, context)?; + self.put_expression(sampler, context, true)?; write!(self.out, ", ")?; - self.put_expression(coordinate, context)?; + self.put_expression(coordinate, context, true)?; if let Some(expr) = array_index { write!(self.out, ", ")?; - self.put_expression(expr, context)?; + self.put_expression(expr, context, true)?; } if let Some(dref) = depth_ref { write!(self.out, ", ")?; - self.put_expression(dref, context)?; + self.put_expression(dref, context, true)?; } match level { crate::SampleLevel::Auto => {} @@ -370,19 +371,19 @@ impl Writer { } crate::SampleLevel::Exact(h) => { write!(self.out, ", level(")?; - self.put_expression(h, context)?; + self.put_expression(h, context, true)?; write!(self.out, ")")?; } crate::SampleLevel::Bias(h) => { write!(self.out, ", bias(")?; - self.put_expression(h, context)?; + self.put_expression(h, context, true)?; write!(self.out, ")")?; } crate::SampleLevel::Gradient { x, y } => { write!(self.out, ", gradient(")?; - self.put_expression(x, context)?; + self.put_expression(x, context, true)?; write!(self.out, ", ")?; - self.put_expression(y, context)?; + self.put_expression(y, context, true)?; write!(self.out, ")")?; } } @@ -398,16 +399,16 @@ impl Writer { array_index, index, } => { - self.put_expression(image, context)?; + self.put_expression(image, context, false)?; write!(self.out, ".read(")?; - self.put_expression(coordinate, context)?; + self.put_expression(coordinate, context, true)?; if let Some(expr) = array_index { write!(self.out, ", ")?; - self.put_expression(expr, context)?; + self.put_expression(expr, context, true)?; } if let Some(index) = index { write!(self.out, ", ")?; - self.put_expression(index, context)?; + self.put_expression(index, context, true)?; } write!(self.out, ")")?; } @@ -452,17 +453,17 @@ impl Writer { } crate::ImageQuery::NumLevels => { write!(self.out, "int(")?; - self.put_expression(image, context)?; + self.put_expression(image, context, false)?; write!(self.out, ".get_num_mip_levels())")?; } crate::ImageQuery::NumLayers => { write!(self.out, "int(")?; - self.put_expression(image, context)?; + self.put_expression(image, context, false)?; write!(self.out, ".get_array_size())")?; } crate::ImageQuery::NumSamples => { write!(self.out, "int(")?; - self.put_expression(image, context)?; + self.put_expression(image, context, false)?; write!(self.out, ".get_num_samples())")?; } }, @@ -472,7 +473,7 @@ impl Writer { crate::UnaryOperator::Not => "!", }; write!(self.out, "{}", op_str)?; - self.put_expression(expr, context)?; + self.put_expression(expr, context, false)?; } crate::Expression::Binary { op, left, right } => { let op_str = match op { @@ -501,16 +502,20 @@ impl Writer { .ok_or(Error::UnsupportedBinaryOp(op))?; if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float { write!(self.out, "fmod(")?; - self.put_expression(left, context)?; + self.put_expression(left, context, true)?; write!(self.out, ", ")?; - self.put_expression(right, context)?; + self.put_expression(right, context, true)?; write!(self.out, ")")?; } else { - write!(self.out, "(")?; - self.put_expression(left, context)?; + if !is_scoped { + write!(self.out, "(")?; + } + self.put_expression(left, context, false)?; write!(self.out, " {} ", op_str)?; - self.put_expression(right, context)?; - write!(self.out, ")")?; + self.put_expression(right, context, false)?; + if !is_scoped { + write!(self.out, ")")?; + } } } crate::Expression::Select { @@ -518,13 +523,17 @@ impl Writer { accept, reject, } => { - write!(self.out, "(")?; - self.put_expression(condition, context)?; + if !is_scoped { + write!(self.out, "(")?; + } + self.put_expression(condition, context, false)?; write!(self.out, " ? ")?; - self.put_expression(accept, context)?; + self.put_expression(accept, context, false)?; write!(self.out, " : ")?; - self.put_expression(reject, context)?; - write!(self.out, ")")?; + self.put_expression(reject, context, false)?; + if !is_scoped { + write!(self.out, ")")?; + } } crate::Expression::Derivative { axis, expr } => { let op = match axis { @@ -628,7 +637,7 @@ impl Writer { }; let op = if convert { "static_cast" } else { "as_type" }; write!(self.out, "{}<{}{}>(", op, scalar, size)?; - self.put_expression(expr, context)?; + self.put_expression(expr, context, true)?; write!(self.out, ")")?; } // has to be a named expression @@ -701,7 +710,7 @@ impl Writer { if min_ref_count <= context.expression.info[handle].ref_count { write!(self.out, "{}", level)?; self.start_baking_expression(handle, &context.expression)?; - self.put_expression(handle, &context.expression)?; + self.put_expression(handle, &context.expression, true)?; writeln!(self.out, ";")?; self.named_expressions.insert(handle.index()); } @@ -720,7 +729,7 @@ impl Writer { ref reject, } => { write!(self.out, "{}if (", level)?; - self.put_expression(condition, &context.expression)?; + self.put_expression(condition, &context.expression, true)?; writeln!(self.out, ") {{")?; self.put_block(level.next(), accept, context)?; if !reject.is_empty() { @@ -735,7 +744,7 @@ impl Writer { ref default, } => { write!(self.out, "{}switch(", level)?; - self.put_expression(selector, &context.expression)?; + self.put_expression(selector, &context.expression, true)?; writeln!(self.out, ") {{")?; let lcase = level.next(); for case in cases.iter() { @@ -789,7 +798,7 @@ impl Writer { } => { let tmp = "_tmp"; write!(self.out, "{}const auto {} = ", level, tmp)?; - self.put_expression(expr_handle, &context.expression)?; + self.put_expression(expr_handle, &context.expression, true)?; writeln!(self.out, ";")?; write!(self.out, "{}return {} {{", level, struct_name)?; for index in 0..members.len() as u32 { @@ -801,14 +810,14 @@ impl Writer { } _ => { write!(self.out, "{}return {} {{ ", level, struct_name)?; - self.put_expression(expr_handle, &context.expression)?; + self.put_expression(expr_handle, &context.expression, true)?; } } write!(self.out, " }}")?; } None => { write!(self.out, "{}return ", level)?; - self.put_expression(expr_handle, &context.expression)?; + self.put_expression(expr_handle, &context.expression, true)?; } } writeln!(self.out, ";")?; @@ -821,9 +830,9 @@ impl Writer { } crate::Statement::Store { pointer, value } => { write!(self.out, "{}", level)?; - self.put_expression(pointer, &context.expression)?; + self.put_expression(pointer, &context.expression, true)?; write!(self.out, " = ")?; - self.put_expression(value, &context.expression)?; + self.put_expression(value, &context.expression, true)?; writeln!(self.out, ";")?; } crate::Statement::ImageStore { @@ -833,14 +842,14 @@ impl Writer { value, } => { write!(self.out, "{}", level)?; - self.put_expression(image, &context.expression)?; + self.put_expression(image, &context.expression, false)?; write!(self.out, ".write(")?; - self.put_expression(value, &context.expression)?; + self.put_expression(value, &context.expression, true)?; write!(self.out, ", ")?; - self.put_expression(coordinate, &context.expression)?; + self.put_expression(coordinate, &context.expression, true)?; if let Some(expr) = array_index { write!(self.out, ", ")?; - self.put_expression(expr, &context.expression)?; + self.put_expression(expr, &context.expression, true)?; } writeln!(self.out, ");")?; } @@ -861,7 +870,7 @@ impl Writer { if i != 0 { write!(self.out, ", ")?; } - self.put_expression(handle, &context.expression)?; + self.put_expression(handle, &context.expression, true)?; } // follow-up with any global resources used let mut separate = !arguments.is_empty(); @@ -1513,8 +1522,8 @@ fn test_stack_size() { } let stack_size = max_addr - min_addr; // check the size (in debug only) - // last observed macOS value: 20672 - if stack_size > 21000 { + // last observed macOS value: 21920 + if stack_size > 22000 { panic!("`put_expression` stack size {} is too large!", stack_size); } } diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index 816ad79a4..a7d810241 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -54,7 +54,7 @@ kernel void main1( type1 pos1; type1 vel1; type i = const_0u; - if ((global_invocation_id.x >= NUM_PARTICLES)) { + if (global_invocation_id.x >= NUM_PARTICLES) { return; } vPos = particlesSrc.particles[global_invocation_id.x].pos; @@ -65,48 +65,48 @@ kernel void main1( bool loop_init = true; while(true) { if (!loop_init) { - i = (i + const_1u); + i = i + const_1u; } loop_init = false; - if ((i >= NUM_PARTICLES)) { + if (i >= NUM_PARTICLES) { break; } - if ((i == global_invocation_id.x)) { + if (i == global_invocation_id.x) { continue; } pos1 = particlesSrc.particles[i].pos; vel1 = particlesSrc.particles[i].vel; - if ((metal::distance(pos1, vPos) < params.rule1Distance)) { - cMass = (cMass + pos1); - cMassCount = (cMassCount + const_1i); + if (metal::distance(pos1, vPos) < params.rule1Distance) { + cMass = cMass + pos1; + cMassCount = cMassCount + const_1i; } - if ((metal::distance(pos1, vPos) < params.rule2Distance)) { - colVel = (colVel - (pos1 - vPos)); + if (metal::distance(pos1, vPos) < params.rule2Distance) { + colVel = colVel - (pos1 - vPos); } - if ((metal::distance(pos1, vPos) < params.rule3Distance)) { - cVel = (cVel + vel1); - cVelCount = (cVelCount + const_1i); + if (metal::distance(pos1, vPos) < params.rule3Distance) { + cVel = cVel + vel1; + cVelCount = cVelCount + const_1i; } } - if ((cMassCount > const_0i)) { - cMass = ((cMass * (const_1f / static_cast(cMassCount))) - vPos); + if (cMassCount > const_0i) { + cMass = (cMass * (const_1f / static_cast(cMassCount))) - vPos; } - if ((cVelCount > const_0i)) { - cVel = (cVel * (const_1f / static_cast(cVelCount))); + if (cVelCount > const_0i) { + cVel = cVel * (const_1f / static_cast(cVelCount)); } - vVel = (((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale)); - vVel = (metal::normalize(vVel) * metal::clamp(metal::length(vVel), const_0f, const_0_10f)); - vPos = (vPos + (vVel * params.deltaT)); - if ((vPos.x < const_n1f)) { + vVel = ((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale); + vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), const_0f, const_0_10f); + vPos = vPos + (vVel * params.deltaT); + if (vPos.x < const_n1f) { vPos.x = const_1f; } - if ((vPos.x > const_1f)) { + if (vPos.x > const_1f) { vPos.x = const_n1f; } - if ((vPos.y < const_n1f)) { + if (vPos.y < const_n1f) { vPos.y = const_1f; } - if ((vPos.y > const_1f)) { + if (vPos.y > const_1f) { vPos.y = const_n1f; } particlesDst.particles[global_invocation_id.x].pos = vPos; diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index 6c9e2f0a6..b7d56f09c 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -22,15 +22,15 @@ type collatz_iterations( type i = const_0u; n = n_base; while(true) { - if ((n <= const_1u)) { + if (n <= const_1u) { break; } - if (((n % const_2u) == const_0u)) { - n = (n / const_2u); + if ((n % const_2u) == const_0u) { + n = n / const_2u; } else { - n = ((const_3u * n) + const_1u); + n = (const_3u * n) + const_1u; } - i = (i + const_1u); + i = i + const_1u; } return i; } diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index ebea304a2..0a01f1484 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -32,7 +32,7 @@ vertex main1Output main1( const auto uv1 = varyings.uv1; VertexOutput out; out.uv = uv1; - out.position = metal::float4((c_scale * pos), const_0f, const_1f); + out.position = metal::float4(c_scale * pos, const_0f, const_1f); const auto _tmp = out; return main1Output { _tmp.uv, _tmp.position }; } @@ -50,9 +50,9 @@ fragment main2Output main2( ) { const auto uv2 = varyings1.uv2; metal::float4 _expr4 = u_texture.sample(u_sampler, uv2); - if ((_expr4.w == const_0f)) { + if (_expr4.w == const_0f) { metal::discard_fragment(); } - return main2Output { (_expr4.w * _expr4) }; + return main2Output { _expr4.w * _expr4 }; } diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 0e2e67067..b2eae0b4c 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -41,11 +41,11 @@ type7 fetch_shadow( type4 t_shadow, type5 sampler_shadow ) { - if ((homogeneous_coords.w <= const_0f)) { + if (homogeneous_coords.w <= const_0f) { return const_1f; } - float _expr15 = (const_1f / homogeneous_coords.w); - float _expr28 = t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * _expr15) + metal::float2(const_0_50f, const_0_50f)), static_cast(light_id), (homogeneous_coords.z * _expr15)); + float _expr15 = const_1f / homogeneous_coords.w; + float _expr28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * _expr15) + metal::float2(const_0_50f, const_0_50f), static_cast(light_id), homogeneous_coords.z * _expr15); return _expr28; } @@ -70,15 +70,15 @@ fragment fs_mainOutput fs_main( bool loop_init = true; while(true) { if (!loop_init) { - i = (i + const_1u); + i = i + const_1u; } loop_init = false; - if ((i >= metal::min(u_globals.num_lights.x, c_max_lights))) { + if (i >= metal::min(u_globals.num_lights.x, c_max_lights)) { break; } Light _expr21 = s_lights.data[i]; - type7 _expr25 = fetch_shadow(i, (_expr21.proj * position), t_shadow, sampler_shadow); - color1 = (color1 + ((_expr25 * metal::max(const_0f, metal::dot(metal::normalize(raw_normal), metal::normalize((metal::float3(_expr21.pos.x, _expr21.pos.y, _expr21.pos.z) - metal::float3(position.x, position.y, position.z)))))) * metal::float3(_expr21.color.x, _expr21.color.y, _expr21.color.z))); + type7 _expr25 = fetch_shadow(i, _expr21.proj * position, t_shadow, sampler_shadow); + color1 = color1 + ((_expr25 * metal::max(const_0f, metal::dot(metal::normalize(raw_normal), metal::normalize(metal::float3(_expr21.pos.x, _expr21.pos.y, _expr21.pos.z) - metal::float3(position.x, position.y, position.z))))) * metal::float3(_expr21.color.x, _expr21.color.y, _expr21.color.z)); } return fs_mainOutput { metal::float4(color1, const_1f) }; } diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 83ce8194a..eb27b7cfe 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -39,11 +39,11 @@ vertex vs_mainOutput vs_main( type4 tmp1_; type4 tmp2_; VertexOutput out; - tmp1_ = (static_cast(vertex_index) / const_2i); - tmp2_ = (static_cast(vertex_index) & const_1i); - type _expr24 = metal::float4(((static_cast(tmp1_) * const_4f) - const_1f), ((static_cast(tmp2_) * const_4f) - const_1f), const_0f, const_1f); - metal::float4 _expr50 = (r_data.proj_inv * _expr24); - out.uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr50.x, _expr50.y, _expr50.z)); + tmp1_ = static_cast(vertex_index) / const_2i; + tmp2_ = static_cast(vertex_index) & const_1i; + type _expr24 = metal::float4((static_cast(tmp1_) * const_4f) - const_1f, (static_cast(tmp2_) * const_4f) - const_1f, const_0f, const_1f); + metal::float4 _expr50 = r_data.proj_inv * _expr24; + out.uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr50.x, _expr50.y, _expr50.z); out.position = _expr24; const auto _tmp = out; return vs_mainOutput { _tmp.position, _tmp.uv }; From a090afa3f5f733c8cb47ad61b199bf5532a0740d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 26 Mar 2021 00:21:17 -0400 Subject: [PATCH 0626/2212] [msl] write scalar constants before the types --- src/back/msl/writer.rs | 64 ++++++++++++++++++++++++-------------- tests/out/boids.msl.snap | 18 +++++------ tests/out/collatz.msl.snap | 8 ++--- tests/out/quad.msl.snap | 6 ++-- tests/out/shadow.msl.snap | 16 +++++----- tests/out/skybox.msl.snap | 10 +++--- 6 files changed, 70 insertions(+), 52 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 61bc1d433..ba0f1403b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -501,7 +501,7 @@ impl Writer { .scalar_kind() .ok_or(Error::UnsupportedBinaryOp(op))?; if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float { - write!(self.out, "fmod(")?; + write!(self.out, "{}::fmod(", NAMESPACE)?; self.put_expression(left, context, true)?; write!(self.out, ", ")?; self.put_expression(right, context, true)?; @@ -907,8 +907,9 @@ impl Writer { writeln!(self.out, "#include ")?; writeln!(self.out)?; + self.write_scalar_constants(module)?; self.write_type_defs(module)?; - self.write_constants(module)?; + self.write_composite_constants(module)?; self.write_functions(module, info, options) } @@ -1076,43 +1077,60 @@ impl Writer { Ok(()) } - fn write_constants(&mut self, module: &crate::Module) -> Result<(), Error> { + fn write_scalar_constants(&mut self, module: &crate::Module) -> Result<(), Error> { for (handle, constant) in module.constants.iter() { - write!(self.out, "constexpr constant ")?; - let name = &self.names[&NameKey::Constant(handle)]; match constant.inner { crate::ConstantInner::Scalar { width: _, ref value, - } => match *value { - crate::ScalarValue::Sint(value) => { - write!(self.out, "int {} = {}", name, value)?; - } - crate::ScalarValue::Uint(value) => { - write!(self.out, "unsigned {} = {}u", name, value)?; - } - crate::ScalarValue::Float(value) => { - write!(self.out, "float {} = {}", name, value)?; - if value.fract() == 0.0 { - write!(self.out, ".0")?; + } => { + let name = &self.names[&NameKey::Constant(handle)]; + write!(self.out, "constexpr constant ")?; + match *value { + crate::ScalarValue::Sint(value) => { + write!(self.out, "int {} = {}", name, value)?; + } + crate::ScalarValue::Uint(value) => { + write!(self.out, "unsigned {} = {}u", name, value)?; + } + crate::ScalarValue::Float(value) => { + write!(self.out, "float {} = {}", name, value)?; + if value.fract() == 0.0 { + write!(self.out, ".0")?; + } + } + crate::ScalarValue::Bool(value) => { + write!(self.out, "bool {} = {}", name, value)?; } } - crate::ScalarValue::Bool(value) => { - write!(self.out, "bool {} = {}", name, value)?; - } - }, + writeln!(self.out, ";")?; + } + crate::ConstantInner::Composite { .. } => {} + } + } + Ok(()) + } + + fn write_composite_constants(&mut self, module: &crate::Module) -> Result<(), Error> { + for (handle, constant) in module.constants.iter() { + match constant.inner { + crate::ConstantInner::Scalar { .. } => {} crate::ConstantInner::Composite { ty, ref components } => { + let name = &self.names[&NameKey::Constant(handle)]; let ty_name = &self.names[&NameKey::Type(ty)]; - write!(self.out, "{} {} = {}(", ty_name, name, ty_name)?; + write!( + self.out, + "constexpr constant {} {} = {}(", + ty_name, name, ty_name + )?; for (i, &sub_handle) in components.iter().enumerate() { let separator = if i != 0 { ", " } else { "" }; let sub_name = &self.names[&NameKey::Constant(sub_handle)]; write!(self.out, "{}{}", separator, sub_name)?; } - write!(self.out, ")")?; + writeln!(self.out, ");")?; } } - writeln!(self.out, ";")?; } Ok(()) } diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index a7d810241..82bcf12b2 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -5,6 +5,15 @@ expression: msl #include #include +constexpr constant unsigned NUM_PARTICLES = 1500u; +constexpr constant float const_0f = 0.0; +constexpr constant int const_0i = 0; +constexpr constant unsigned const_0u = 0u; +constexpr constant int const_1i = 1; +constexpr constant unsigned const_1u = 1u; +constexpr constant float const_1f = 1.0; +constexpr constant float const_0_10f = 0.1; +constexpr constant float const_n1f = -1.0; typedef uint type; typedef metal::float2 type1; struct Particle { @@ -27,15 +36,6 @@ struct Particles { }; typedef metal::uint3 type4; typedef int type5; -constexpr constant unsigned NUM_PARTICLES = 1500u; -constexpr constant float const_0f = 0.0; -constexpr constant int const_0i = 0; -constexpr constant unsigned const_0u = 0u; -constexpr constant int const_1i = 1; -constexpr constant unsigned const_1u = 1u; -constexpr constant float const_1f = 1.0; -constexpr constant float const_0_10f = 0.1; -constexpr constant float const_n1f = -1.0; struct main1Input { }; kernel void main1( diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index b7d56f09c..561440471 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -5,16 +5,16 @@ expression: msl #include #include +constexpr constant unsigned const_0u = 0u; +constexpr constant unsigned const_1u = 1u; +constexpr constant unsigned const_2u = 2u; +constexpr constant unsigned const_3u = 3u; typedef uint type; typedef type type1[1]; struct PrimeIndices { type1 data; }; typedef metal::uint3 type2; -constexpr constant unsigned const_0u = 0u; -constexpr constant unsigned const_1u = 1u; -constexpr constant unsigned const_2u = 2u; -constexpr constant unsigned const_3u = 3u; type collatz_iterations( type n_base ) { diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index 0a01f1484..084d7fb87 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -5,6 +5,9 @@ expression: msl #include #include +constexpr constant float c_scale = 1.2; +constexpr constant float const_0f = 0.0; +constexpr constant float const_1f = 1.0; typedef float type; typedef metal::float2 type1; typedef metal::float4 type2; @@ -14,9 +17,6 @@ struct VertexOutput { }; typedef metal::texture2d type3; typedef metal::sampler type4; -constexpr constant float c_scale = 1.2; -constexpr constant float const_0f = 0.0; -constexpr constant float const_1f = 1.0; struct main1Input { type1 pos [[attribute(0)]]; type1 uv1 [[attribute(1)]]; diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index b2eae0b4c..906e53bfd 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -5,6 +5,14 @@ expression: msl #include #include +constexpr constant float const_0f = 0.0; +constexpr constant float const_1f = 1.0; +constexpr constant float const_0_50f = 0.5; +constexpr constant float const_n0_50f = -0.5; +constexpr constant float const_0_05f = 0.05; +constexpr constant unsigned c_max_lights = 10u; +constexpr constant unsigned const_0u = 0u; +constexpr constant unsigned const_1u = 1u; typedef metal::uint4 type; struct Globals { type num_lights; @@ -26,15 +34,7 @@ typedef uint type6; typedef float type7; typedef metal::float2 type8; typedef metal::float3 type9; -constexpr constant float const_0f = 0.0; -constexpr constant float const_1f = 1.0; -constexpr constant float const_0_50f = 0.5; -constexpr constant float const_n0_50f = -0.5; -constexpr constant float const_0_05f = 0.05; constexpr constant type9 c_ambient = type9(const_0_05f, const_0_05f, const_0_05f); -constexpr constant unsigned c_max_lights = 10u; -constexpr constant unsigned const_0u = 0u; -constexpr constant unsigned const_1u = 1u; type7 fetch_shadow( type6 light_id, type2 homogeneous_coords, diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index eb27b7cfe..7b22fd95f 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -5,6 +5,11 @@ expression: msl #include #include +constexpr constant int const_2i = 2; +constexpr constant int const_1i = 1; +constexpr constant float const_4f = 4.0; +constexpr constant float const_1f = 1.0; +constexpr constant float const_0f = 0.0; typedef metal::float4 type; typedef metal::float3 type1; struct VertexOutput { @@ -21,11 +26,6 @@ typedef int type4; typedef metal::float3x3 type5; typedef metal::texturecube type6; typedef metal::sampler type7; -constexpr constant int const_2i = 2; -constexpr constant int const_1i = 1; -constexpr constant float const_4f = 4.0; -constexpr constant float const_1f = 1.0; -constexpr constant float const_0f = 0.0; struct vs_mainInput { }; struct vs_mainOutput { From 00f4c0760957e7793aae981c2149c5d5ee5a8cbd Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 26 Mar 2021 01:02:07 -0400 Subject: [PATCH 0627/2212] [msl] fix Select on vectors --- src/back/msl/writer.rs | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ba0f1403b..c73f67c8b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -522,19 +522,37 @@ impl Writer { condition, accept, reject, - } => { - if !is_scoped { - write!(self.out, "(")?; + } => match *context.resolve_type(condition) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + .. + } => { + if !is_scoped { + write!(self.out, "(")?; + } + self.put_expression(condition, context, false)?; + write!(self.out, " ? ")?; + self.put_expression(accept, context, false)?; + write!(self.out, " : ")?; + self.put_expression(reject, context, false)?; + if !is_scoped { + write!(self.out, ")")?; + } } - self.put_expression(condition, context, false)?; - write!(self.out, " ? ")?; - self.put_expression(accept, context, false)?; - write!(self.out, " : ")?; - self.put_expression(reject, context, false)?; - if !is_scoped { + crate::TypeInner::Vector { + kind: crate::ScalarKind::Bool, + .. + } => { + write!(self.out, "{}::select(", NAMESPACE)?; + self.put_expression(accept, context, true)?; + write!(self.out, ", ")?; + self.put_expression(reject, context, true)?; + write!(self.out, ", ")?; + self.put_expression(condition, context, true)?; write!(self.out, ")")?; } - } + _ => return Err(Error::Validation), + }, crate::Expression::Derivative { axis, expr } => { let op = match axis { crate::DerivativeAxis::X => "dfdx", From ba055bfbada4806e16776f686edbe3539453e645 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 27 Mar 2021 00:05:41 -0400 Subject: [PATCH 0628/2212] Fix validation of constant offset expression --- src/valid/expression.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 7128a0c23..5a5ea2456 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -440,7 +440,7 @@ impl super::Validator { match module.types[ty].inner { Ti::Vector { size, - kind: crate::ScalarKind::Float, + kind: crate::ScalarKind::Sint, .. } => size as u32 == num_components, _ => false, From c55bdf57bf9bc190ab4863b831547250e82cc9a6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 27 Mar 2021 00:24:42 -0400 Subject: [PATCH 0629/2212] [wgsl] don't clone statements --- src/front/wgsl/mod.rs | 15 +++++---------- src/lib.rs | 1 + 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 8bae91cff..09bc350cf 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -75,8 +75,8 @@ pub enum Error<'a> { BadTypeCast(&'a str), #[error(transparent)] InvalidResolve(ResolveError), - #[error("invalid statement {0:?}, expected {1}")] - InvalidStatement(crate::Statement, &'a str), + #[error("for(;;) initializer is not an assignment or a function call")] + InvalidForInitializer, #[error("resource type {0:?} is invalid")] InvalidResourceType(Handle), #[error("unknown import: `{0}`")] @@ -2232,14 +2232,9 @@ impl Parser { is_uniform_control_flow, )?; if block.len() != num_statements { - match block.last().unwrap() { - &crate::Statement::Store { .. } | &crate::Statement::Call { .. } => {} - other => { - return Err(Error::InvalidStatement( - other.clone(), - "variable, assignment or function call", - )) - } + match *block.last().unwrap() { + crate::Statement::Store { .. } | crate::Statement::Call { .. } => {} + _ => return Err(Error::InvalidForInitializer), } } }; diff --git a/src/lib.rs b/src/lib.rs index d48db7ef9..10cbdc1c8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -779,6 +779,7 @@ pub struct SwitchCase { pub fall_through: bool, } +//TODO: consider removing `Clone`. It's not valid to clone `Statement::Emit` anyway. /// Instructions which make up an executable block. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug)] From e47ff2dc26a049bc2830f468f0acf6d0214ff8a2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 26 Mar 2021 22:07:40 -0400 Subject: [PATCH 0630/2212] [spv-in] support output interface block --- src/front/spv/function.rs | 55 ++++++++++++++++++++++++++++---------- src/front/spv/mod.rs | 8 +++--- tests/in/quad-vert.spv | Bin 0 -> 968 bytes tests/snapshots.rs | 6 +++++ 4 files changed, 52 insertions(+), 17 deletions(-) create mode 100644 tests/in/quad-vert.spv diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 8bd683a1b..082c9ff17 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -235,20 +235,47 @@ impl> super::Parser { for &v_id in ep.variable_ids.iter() { let lvar = self.lookup_variable.lookup(v_id)?; if let super::Variable::Output(ref result) = lvar.inner { - members.push(crate::StructMember { - name: None, - ty: result.ty, - binding: result.binding.clone(), - size: None, - align: None, - }); - // populate just the globals first, then do `Load` in a - // separate step, so that we can get a range. - components.push( - function - .expressions - .append(crate::Expression::GlobalVariable(lvar.handle)), - ); + let expr_handle = function + .expressions + .append(crate::Expression::GlobalVariable(lvar.handle)); + match module.types[result.ty].inner { + crate::TypeInner::Struct { + members: ref sub_members, + .. + } => { + for (index, sm) in sub_members.iter().enumerate() { + if sm.binding.is_none() { + // unrecognized binding, skip + continue; + } + members.push(crate::StructMember { + name: sm.name.clone(), + ty: sm.ty, + binding: sm.binding.clone(), + size: None, + align: None, + }); + components.push(function.expressions.append( + crate::Expression::AccessIndex { + base: expr_handle, + index: index as u32, + }, + )); + } + } + _ => { + members.push(crate::StructMember { + name: None, + ty: result.ty, + binding: result.binding.clone(), + size: None, + align: None, + }); + // populate just the globals first, then do `Load` in a + // separate step, so that we can get a range. + components.push(expr_handle); + } + } } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 46e1453ff..6bcab546a 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2414,10 +2414,11 @@ impl> Parser { .future_member_decor .remove(&(id, i)) .unwrap_or_default(); + let binding = decor.io_binding().ok(); members.push(crate::StructMember { name: decor.name, ty, - binding: None, + binding, size: None, //TODO align: None, }); @@ -2871,7 +2872,8 @@ impl> Parser { (inner, var) } ExtendedClass::Output => { - let binding = dec.io_binding()?; + // For output interface blocks. this would be a structure. + let binding = dec.io_binding().ok(); let var = crate::GlobalVariable { name: dec.name, class: crate::StorageClass::Private, @@ -2882,7 +2884,7 @@ impl> Parser { }; let inner = Variable::Output(crate::FunctionResult { ty: effective_ty, - binding: Some(binding), + binding, }); (inner, var) } diff --git a/tests/in/quad-vert.spv b/tests/in/quad-vert.spv new file mode 100644 index 0000000000000000000000000000000000000000..eaf03d2fbe057ec0046f3fcaf1f351eec0d6f569 GIT binary patch literal 968 zcmYk3%}c{T5XIMiq_tIRt!@3NHR4ey9#jNT5rul_p;GW#f(8l1v@~fEPyT`aL0$yk zFLtXFCbRF&?9AKUZ04|F%#taYqS-gURy7$h#*~ed#%^!W>%_@(=j8O5iZzo>3#qA? z<#e6X|J4g308Ck4lQ-m9eHq11ZOEIPzQ0;9^|Rr0rjX{@>n*Tjs=_bfubvB0<6!t7d`ol948|;4Z}q)Fa4Ya zLoa9YhT~DJ*q!Tdlaztc4@Seic37S8nB~aB{jWnC96D?rYdG$$s|@|9V-{NM?3!5k z1J$sHbwevh(Umt zqBT8Q!t09E!?m^IEVc(ZoVgo{XdsU+FmC|IoJ~bnPG9DL>vD{GbaFQ~&&(}3Mm=~t zMIYD9+tZrfXgSlHaX*|1gZ~nfSG*L Date: Fri, 26 Mar 2021 23:52:55 -0400 Subject: [PATCH 0631/2212] [msl] fix initialization of arrayed members, enable METAL snapshot of quad-vert --- src/back/msl/writer.rs | 63 +++++++++++++++++++++++++++--- tests/out/quad-vert.msl.snap | 75 ++++++++++++++++++++++++++++++++++++ tests/snapshots.rs | 2 +- 3 files changed, 134 insertions(+), 6 deletions(-) create mode 100644 tests/out/quad-vert.msl.snap diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c73f67c8b..e045c9a24 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -205,6 +205,39 @@ impl Writer { Ok(()) } + fn put_initialization_component( + &mut self, + component: Handle, + context: &ExpressionContext, + ) -> Result<(), Error> { + // we can't initialize the array members just like other members, + // we have to unwrap them one level deeper... + let component_res = &context.info[component].ty; + if let crate::TypeInner::Array { + size: crate::ArraySize::Constant(const_handle), + .. + } = *component_res.inner_with(&context.module.types) + { + //HACK: we are forcefully duplicating the expression here, + // it would be nice to find a more C++ idiomatic solution for initializing array members + let size = context.module.constants[const_handle] + .to_array_length() + .unwrap(); + write!(self.out, "{{")?; + for j in 0..size { + if j != 0 { + write!(self.out, ",")?; + } + self.put_expression(component, context, false)?; + write!(self.out, "[{}]", j)?; + } + write!(self.out, "}}")?; + } else { + self.put_expression(component, context, true)?; + } + Ok(()) + } + fn put_expression( &mut self, expr_handle: Handle, @@ -301,7 +334,7 @@ impl Writer { if i != 0 { write!(self.out, ", ")?; } - self.put_expression(component, context, true)?; + self.put_initialization_component(component, context)?; } write!(self.out, "}}")?; } @@ -819,11 +852,31 @@ impl Writer { self.put_expression(expr_handle, &context.expression, true)?; writeln!(self.out, ";")?; write!(self.out, "{}return {} {{", level, struct_name)?; - for index in 0..members.len() as u32 { + for (index, member) in members.iter().enumerate() { let comma = if index == 0 { "" } else { "," }; - let name = - &self.names[&NameKey::StructMember(result_ty, index)]; - write!(self.out, "{} {}.{}", comma, tmp, name)?; + let name = &self.names + [&NameKey::StructMember(result_ty, index as u32)]; + // logic similar to `put_initialization_component` + if let crate::TypeInner::Array { + size: crate::ArraySize::Constant(const_handle), + .. + } = context.expression.module.types[member.ty].inner + { + let size = context.expression.module.constants + [const_handle] + .to_array_length() + .unwrap(); + write!(self.out, "{} {{", comma)?; + for j in 0..size { + if j != 0 { + write!(self.out, ",")?; + } + write!(self.out, "{}.{}[{}]", tmp, name, j)?; + } + write!(self.out, "}}")?; + } else { + write!(self.out, "{} {}.{}", comma, tmp, name)?; + } } } _ => { diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap new file mode 100644 index 000000000..80b811141 --- /dev/null +++ b/tests/out/quad-vert.msl.snap @@ -0,0 +1,75 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +constexpr constant unsigned const_0u = 0u; +constexpr constant unsigned const_1u = 1u; +constexpr constant unsigned const_2u = 2u; +constexpr constant unsigned const_3u = 3u; +constexpr constant unsigned const_1u1 = 1u; +constexpr constant int const_0i = 0; +constexpr constant float const_0f = 0.0; +constexpr constant float const_1f = 1.0; +typedef float type; +typedef metal::float2 type1; +typedef thread type1 *type2; +typedef thread type1 *type3; +typedef metal::float4 type4; +typedef uint type5; +typedef type type6[const_1u1]; +struct gl_PerVertex { + type4 gl_Position; + type gl_PointSize; + type6 gl_ClipDistance; + type6 gl_CullDistance; +}; +typedef thread gl_PerVertex *type7; +typedef int type8; +typedef thread type4 *type9; +struct type10 { + type1 member; + type4 gl_Position1; + type gl_PointSize1; + type6 gl_ClipDistance1; +}; +void main1( + type1 v_uv, + type1 a_uv, + gl_PerVertex _, + type1 a_pos +) { + v_uv = a_uv; + type1 _expr9 = a_pos; + _.gl_Position = metal::float4(_expr9.x, _expr9.y, const_0f, const_1f); + return; +} + +struct main2Input { + type1 a_uv1 [[attribute(1)]]; + type1 a_pos1 [[attribute(0)]]; +}; +struct main2Output { + type1 member [[user(loc0)]]; + type4 gl_Position1 [[position]]; + type gl_PointSize1 [[point_size]]; + type6 gl_ClipDistance1 [[clip_distance]]; +}; +vertex main2Output main2( + main2Input varyings [[stage_in]] +) { + type1 v_uv = {}; + type1 a_uv = {}; + gl_PerVertex _ = {}; + type1 a_pos = {}; + const auto a_uv1 = varyings.a_uv1; + const auto a_pos1 = varyings.a_pos1; + a_uv = a_uv1; + a_pos = a_pos1; + main1(v_uv, a_uv, _, a_pos); + const auto _tmp = type10 {v_uv, _.gl_Position, _.gl_PointSize, {_.gl_ClipDistance[0]}}; + return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1[0]} }; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d94f1f052..30def8d2c 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -286,7 +286,7 @@ fn convert_spv(name: &str, targets: Targets) { #[cfg(feature = "spv-in")] #[test] fn convert_spv_quad_vert() { - convert_spv("quad-vert", Targets::empty()); + convert_spv("quad-vert", Targets::METAL); } #[cfg(feature = "spv-in")] From 50059740f7e100fb698a3ba8fced233d6d58f1df Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 27 Mar 2021 00:40:25 -0400 Subject: [PATCH 0632/2212] [msl] prefix lod options with metal namespace --- src/back/msl/writer.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e045c9a24..ee5b9522c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -403,17 +403,17 @@ impl Writer { //TODO: do we support Zero on `Sampled` image classes? } crate::SampleLevel::Exact(h) => { - write!(self.out, ", level(")?; + write!(self.out, ", {}::level(", NAMESPACE)?; self.put_expression(h, context, true)?; write!(self.out, ")")?; } crate::SampleLevel::Bias(h) => { - write!(self.out, ", bias(")?; + write!(self.out, ", {}::bias(", NAMESPACE)?; self.put_expression(h, context, true)?; write!(self.out, ")")?; } crate::SampleLevel::Gradient { x, y } => { - write!(self.out, ", gradient(")?; + write!(self.out, ", {}::gradient(", NAMESPACE)?; self.put_expression(x, context, true)?; write!(self.out, ", ")?; self.put_expression(y, context, true)?; @@ -1611,8 +1611,8 @@ fn test_stack_size() { } let stack_size = max_addr - min_addr; // check the size (in debug only) - // last observed macOS value: 21920 - if stack_size > 22000 { + // last observed macOS value: 22112 + if stack_size > 22200 { panic!("`put_expression` stack size {} is too large!", stack_size); } } From ca6876b7a0be2597136564b6bbafb9260d627083 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 28 Mar 2021 23:33:29 -0400 Subject: [PATCH 0633/2212] Validate math functions --- src/front/wgsl/tests.rs | 13 ++ src/valid/expression.rs | 301 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 286 insertions(+), 28 deletions(-) diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index fbad55201..b439a26b8 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -226,6 +226,19 @@ fn parse_texture_load() { .unwrap(); } +#[test] +fn parse_texture_store() { + parse_str( + " + var t: [[access(write)]] texture_storage_2d; + fn foo() { + textureStore(t, vec2(10, 20), vec4(0.0, 1.0, 2.0, 3.0)); + } + ", + ) + .unwrap(); +} + #[test] fn parse_texture_query() { parse_str( diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 5a5ea2456..b21f53488 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -97,6 +97,10 @@ pub enum ExpressionError { InvalidSampleLevelGradientType(crate::ImageDimension, Handle), #[error("Unable to cast")] InvalidCastArgument, + #[error("Invalid argument count for {0:?}")] + WrongArgumentCount(crate::MathFunction), + #[error("Argument [{1}] to {0:?} as expression {2:?} has an invalid type.")] + InvalidArgumentType(crate::MathFunction, u32, Handle), } struct ExpressionTypeResolver<'a> { @@ -401,7 +405,7 @@ impl super::Validator { if let Some(expr) = array_index { match *resolver.resolve(expr)? { Ti::Scalar { - kind: crate::ScalarKind::Sint, + kind: Sk::Sint, width: _, } => {} _ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)), @@ -419,12 +423,11 @@ impl super::Validator { }; match *resolver.resolve(coordinate)? { Ti::Scalar { - kind: crate::ScalarKind::Float, - .. + kind: Sk::Float, .. } if num_components == 1 => {} Ti::Vector { size, - kind: crate::ScalarKind::Float, + kind: Sk::Float, .. } if size as u32 == num_components => {} _ => return Err(ExpressionError::InvalidImageCoordinateType(dim, coordinate)), @@ -440,7 +443,7 @@ impl super::Validator { match module.types[ty].inner { Ti::Vector { size, - kind: crate::ScalarKind::Sint, + kind: Sk::Sint, .. } => size as u32 == num_components, _ => false, @@ -455,8 +458,7 @@ impl super::Validator { if let Some(expr) = depth_ref { match *resolver.resolve(expr)? { Ti::Scalar { - kind: crate::ScalarKind::Float, - .. + kind: Sk::Float, .. } => {} _ => return Err(ExpressionError::InvalidDepthReference(expr)), } @@ -474,8 +476,7 @@ impl super::Validator { crate::SampleLevel::Exact(expr) if can_level => { match *resolver.resolve(expr)? { Ti::Scalar { - kind: crate::ScalarKind::Float, - .. + kind: Sk::Float, .. } => {} _ => return Err(ExpressionError::InvalidSampleLevelExactType(expr)), } @@ -484,8 +485,7 @@ impl super::Validator { crate::SampleLevel::Bias(expr) => { match *resolver.resolve(expr)? { Ti::Scalar { - kind: crate::ScalarKind::Float, - .. + kind: Sk::Float, .. } => {} _ => return Err(ExpressionError::InvalidSampleLevelBiasType(expr)), } @@ -494,12 +494,11 @@ impl super::Validator { crate::SampleLevel::Gradient { x, y } => { match *resolver.resolve(x)? { Ti::Scalar { - kind: crate::ScalarKind::Float, - .. + kind: Sk::Float, .. } if num_components == 1 => {} Ti::Vector { size, - kind: crate::ScalarKind::Float, + kind: Sk::Float, .. } if size as u32 == num_components => {} _ => { @@ -508,12 +507,11 @@ impl super::Validator { } match *resolver.resolve(y)? { Ti::Scalar { - kind: crate::ScalarKind::Float, - .. + kind: Sk::Float, .. } if num_components == 1 => {} Ti::Vector { size, - kind: crate::ScalarKind::Float, + kind: Sk::Float, .. } if size as u32 == num_components => {} _ => { @@ -564,7 +562,7 @@ impl super::Validator { if let Some(expr) = array_index { match *resolver.resolve(expr)? { Ti::Scalar { - kind: crate::ScalarKind::Sint, + kind: Sk::Sint, width: _, } => {} _ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)), @@ -573,7 +571,7 @@ impl super::Validator { if let Some(expr) = index { match *resolver.resolve(expr)? { Ti::Scalar { - kind: crate::ScalarKind::Sint, + kind: Sk::Sint, width: _, } => {} _ => return Err(ExpressionError::InvalidImageOtherIndexType(expr)), @@ -807,12 +805,10 @@ impl super::Validator { E::Derivative { axis: _, expr } => { match *resolver.resolve(expr)? { Ti::Scalar { - kind: crate::ScalarKind::Float, - .. + kind: Sk::Float, .. } | Ti::Vector { - kind: crate::ScalarKind::Float, - .. + kind: Sk::Float, .. } => {} _ => return Err(ExpressionError::InvalidDerivative), } @@ -844,13 +840,264 @@ impl super::Validator { } ShaderStages::all() } - #[allow(unused)] E::Math { fun, arg, arg1, arg2, - } => ShaderStages::all(), + } => { + use crate::MathFunction as Mf; + + let arg_ty = resolver.resolve(arg)?; + let arg1_ty = arg1.map(|expr| resolver.resolve(expr)).transpose()?; + let arg2_ty = arg2.map(|expr| resolver.resolve(expr)).transpose()?; + match fun { + Mf::Abs => { + if arg1_ty.is_some() | arg2_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + let good = match *arg_ty { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => kind != Sk::Bool, + _ => false, + }; + if !good { + return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)); + } + } + Mf::Min | Mf::Max => { + let arg1_ty = match (arg1_ty, arg2_ty) { + (Some(ty1), None) => ty1, + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + let good = match *arg_ty { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => kind != Sk::Bool, + _ => false, + }; + if !good { + return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)); + } + if arg1_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + } + Mf::Clamp => { + let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty) { + (Some(ty1), Some(ty2)) => (ty1, ty2), + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + let good = match *arg_ty { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => kind != Sk::Bool, + _ => false, + }; + if !good { + return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)); + } + if arg1_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + if arg2_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 2, + arg2.unwrap(), + )); + } + } + Mf::Cos + | Mf::Cosh + | Mf::Sin + | Mf::Sinh + | Mf::Tan + | Mf::Tanh + | Mf::Acos + | Mf::Asin + | Mf::Atan + | Mf::Ceil + | Mf::Floor + | Mf::Round + | Mf::Fract + | Mf::Trunc + | Mf::Exp + | Mf::Exp2 + | Mf::Log + | Mf::Log2 + | Mf::Length + | Mf::Sign + | Mf::Sqrt + | Mf::InverseSqrt => { + if arg1_ty.is_some() | arg2_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + match *arg_ty { + Ti::Scalar { + kind: Sk::Float, .. + } + | Ti::Vector { + kind: Sk::Float, .. + } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + } + Mf::Atan2 | Mf::Pow | Mf::Distance => { + let arg1_ty = match (arg1_ty, arg2_ty) { + (Some(ty1), None) => ty1, + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + match *arg_ty { + Ti::Scalar { + kind: Sk::Float, .. + } + | Ti::Vector { + kind: Sk::Float, .. + } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + if arg1_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + } + Mf::Modf | Mf::Frexp | Mf::Ldexp => { + let arg1_ty = match (arg1_ty, arg2_ty) { + (Some(ty1), None) => ty1, + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + let (size0, width0) = match *arg_ty { + Ti::Scalar { + kind: Sk::Float, + width, + } => (None, width), + Ti::Vector { + kind: Sk::Float, + size, + width, + } => (Some(size), width), + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + }; + let good = match *arg1_ty { + Ti::Pointer { base, class: _ } => module.types[base].inner == *arg_ty, + Ti::ValuePointer { + size, + kind: Sk::Float, + width, + class: _, + } => size == size0 && width == width0, + _ => false, + }; + if !good { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + } + Mf::Dot | Mf::Outer | Mf::Cross | Mf::Step | Mf::Reflect => { + let arg1_ty = match (arg1_ty, arg2_ty) { + (Some(ty1), None) => ty1, + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + match *arg_ty { + Ti::Vector { + kind: Sk::Float, .. + } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + if arg1_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + } + Mf::Normalize => { + if arg1_ty.is_some() | arg2_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + match *arg_ty { + Ti::Vector { + kind: Sk::Float, .. + } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + } + Mf::FaceForward | Mf::Fma | Mf::Mix | Mf::SmoothStep => { + let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty) { + (Some(ty1), Some(ty2)) => (ty1, ty2), + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + match *arg_ty { + Ti::Scalar { + kind: Sk::Float, .. + } + | Ti::Vector { + kind: Sk::Float, .. + } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + if arg1_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + if arg2_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 2, + arg2.unwrap(), + )); + } + } + Mf::Inverse | Mf::Determinant => { + if arg1_ty.is_some() | arg2_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + let good = match *arg_ty { + Ti::Matrix { columns, rows, .. } => columns == rows, + _ => false, + }; + if !good { + return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)); + } + } + Mf::Transpose => { + if arg1_ty.is_some() | arg2_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + match *arg_ty { + Ti::Matrix { .. } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + } + Mf::CountOneBits | Mf::ReverseBits => { + if arg1_ty.is_some() | arg2_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + match *arg_ty { + Ti::Scalar { kind: Sk::Sint, .. } + | Ti::Scalar { kind: Sk::Uint, .. } + | Ti::Vector { kind: Sk::Sint, .. } + | Ti::Vector { kind: Sk::Uint, .. } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + } + } + ShaderStages::all() + } E::As { expr, kind, @@ -860,9 +1107,7 @@ impl super::Validator { .resolve(expr)? .scalar_kind() .ok_or(ExpressionError::InvalidCastArgument)?; - if !convert && prev_kind == crate::ScalarKind::Bool - || kind == crate::ScalarKind::Bool - { + if !convert && prev_kind == Sk::Bool || kind == Sk::Bool { return Err(ExpressionError::InvalidCastArgument); } ShaderStages::all() From f06583ca7d6e69be3aea9939ebe52cfe74ce76e1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 29 Mar 2021 00:37:29 -0400 Subject: [PATCH 0634/2212] [spv-in] change const indexes to signed int --- src/front/spv/mod.rs | 32 +++++++++++++++++++++++++++----- tests/out/quad-vert.msl.snap | 12 ++++++------ tests/out/shadow.ron.snap | 8 ++++---- 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 6bcab546a..324255813 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1503,11 +1503,33 @@ impl> Parser { inst.expect(5)?; self.parse_expr_binary_op(expressions, crate::BinaryOperator::LogicalAnd)?; } - op if inst.op >= Op::IEqual && inst.op <= Op::FUnordGreaterThanEqual => { + Op::IEqual + | Op::INotEqual + | Op::UGreaterThan + | Op::SGreaterThan + | Op::UGreaterThanEqual + | Op::SGreaterThanEqual + | Op::ULessThan + | Op::SLessThan + | Op::ULessThanEqual + | Op::SLessThanEqual + | Op::FOrdEqual + | Op::FUnordEqual + | Op::FOrdNotEqual + | Op::FUnordNotEqual + | Op::FOrdLessThan + | Op::FUnordLessThan + | Op::FOrdGreaterThan + | Op::FUnordGreaterThan + | Op::FOrdLessThanEqual + | Op::FUnordLessThanEqual + | Op::FOrdGreaterThanEqual + | Op::FUnordGreaterThanEqual => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, map_binary_operator(op)?)?; + let operator = map_binary_operator(inst.op)?; + self.parse_expr_binary_op(expressions, operator)?; } - op if inst.op >= Op::Any && inst.op <= Op::IsNormal => { + Op::Any | Op::All | Op::IsNan | Op::IsInf | Op::IsFinite | Op::IsNormal => { inst.expect(4)?; let result_type_id = self.next()?; let result_id = self.next()?; @@ -1516,7 +1538,7 @@ impl> Parser { let arg_lexp = self.lookup_expression.lookup(arg_id)?; let expr = crate::Expression::Relational { - fun: map_relational_fun(op)?, + fun: map_relational_fun(inst.op)?, argument: arg_lexp.handle, }; self.lookup_expression.insert( @@ -1772,7 +1794,7 @@ impl> Parser { specialization: None, inner: crate::ConstantInner::Scalar { width: 4, - value: crate::ScalarValue::Uint(i), + value: crate::ScalarValue::Sint(i), }, }); self.index_constants.push(handle); diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap index 80b811141..716b77bbb 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl.snap @@ -5,12 +5,12 @@ expression: msl #include #include -constexpr constant unsigned const_0u = 0u; -constexpr constant unsigned const_1u = 1u; -constexpr constant unsigned const_2u = 2u; -constexpr constant unsigned const_3u = 3u; -constexpr constant unsigned const_1u1 = 1u; constexpr constant int const_0i = 0; +constexpr constant int const_1i = 1; +constexpr constant int const_2i = 2; +constexpr constant int const_3i = 3; +constexpr constant unsigned const_1u = 1u; +constexpr constant int const_0i1 = 0; constexpr constant float const_0f = 0.0; constexpr constant float const_1f = 1.0; typedef float type; @@ -19,7 +19,7 @@ typedef thread type1 *type2; typedef thread type1 *type3; typedef metal::float4 type4; typedef uint type5; -typedef type type6[const_1u1]; +typedef type type6[const_1u]; struct gl_PerVertex { type4 gl_Position; type gl_PointSize; diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index 055887ff1..7c05bcee1 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -458,7 +458,7 @@ expression: output specialization: None, inner: Scalar( width: 4, - value: Uint(0), + value: Sint(0), ), ), ( @@ -466,7 +466,7 @@ expression: output specialization: None, inner: Scalar( width: 4, - value: Uint(1), + value: Sint(1), ), ), ( @@ -474,7 +474,7 @@ expression: output specialization: None, inner: Scalar( width: 4, - value: Uint(2), + value: Sint(2), ), ), ( @@ -482,7 +482,7 @@ expression: output specialization: None, inner: Scalar( width: 4, - value: Uint(3), + value: Sint(3), ), ), ( From 057fa336a8ae3e2006717460307fd6f8a7026bcb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 29 Mar 2021 00:43:46 -0400 Subject: [PATCH 0635/2212] [spv-in] derivative ops --- src/front/spv/mod.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 324255813..8d7442b31 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -580,6 +580,31 @@ impl> Parser { Ok(()) } + fn parse_expr_derivative( + &mut self, + expressions: &mut Arena, + axis: crate::DerivativeAxis, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let arg_id = self.next()?; + + let arg_lexp = self.lookup_expression.lookup(arg_id)?; + + let expr = crate::Expression::Derivative { + axis, + expr: arg_lexp.handle, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } + fn insert_composite( &self, root_expr: Handle, @@ -1654,6 +1679,15 @@ impl> Parser { continue_block_id, }); } + Op::DPdx | Op::DPdxFine | Op::DPdxCoarse => { + self.parse_expr_derivative(expressions, crate::DerivativeAxis::X)?; + } + Op::DPdy | Op::DPdyFine | Op::DPdyCoarse => { + self.parse_expr_derivative(expressions, crate::DerivativeAxis::Y)?; + } + Op::Fwidth | Op::FwidthFine | Op::FwidthCoarse => { + self.parse_expr_derivative(expressions, crate::DerivativeAxis::Width)?; + } _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } }; From baccfc68f551adeb4ad01e132834bd857f66b2ad Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 30 Mar 2021 00:30:42 -0400 Subject: [PATCH 0636/2212] [msl] fix constant array initialization --- src/back/msl/writer.rs | 8 ++------ tests/out/shadow.msl.snap | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ee5b9522c..2964a9244 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1189,17 +1189,13 @@ impl Writer { crate::ConstantInner::Composite { ty, ref components } => { let name = &self.names[&NameKey::Constant(handle)]; let ty_name = &self.names[&NameKey::Type(ty)]; - write!( - self.out, - "constexpr constant {} {} = {}(", - ty_name, name, ty_name - )?; + write!(self.out, "constexpr constant {} {} = {{", ty_name, name,)?; for (i, &sub_handle) in components.iter().enumerate() { let separator = if i != 0 { ", " } else { "" }; let sub_name = &self.names[&NameKey::Constant(sub_handle)]; write!(self.out, "{}{}", separator, sub_name)?; } - writeln!(self.out, ");")?; + writeln!(self.out, "}};")?; } } } diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 906e53bfd..c03bf1cda 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -34,7 +34,7 @@ typedef uint type6; typedef float type7; typedef metal::float2 type8; typedef metal::float3 type9; -constexpr constant type9 c_ambient = type9(const_0_05f, const_0_05f, const_0_05f); +constexpr constant type9 c_ambient = {const_0_05f, const_0_05f, const_0_05f}; type7 fetch_shadow( type6 light_id, type2 homogeneous_coords, From c41f0503121521b22b83f0aff8fc87f81d580810 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 30 Mar 2021 00:40:38 -0400 Subject: [PATCH 0637/2212] [wgsl-in] ability to take a pointer to something --- src/front/wgsl/mod.rs | 20 +++++++++++++------- src/front/wgsl/tests.rs | 12 ++++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 09bc350cf..9eb8c4f96 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1271,37 +1271,43 @@ impl Parser { self.scopes.push(Scope::SingularExpr); //TODO: refactor this to avoid backing up let backup = lexer.clone(); - let handle = match lexer.next().0 { + let (allow_deref, handle) = match lexer.next().0 { Token::Operation('-') => { let expr = crate::Expression::Unary { op: crate::UnaryOperator::Negate, expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }; - ctx.expressions.append(expr) + (true, ctx.expressions.append(expr)) } Token::Operation('!') => { let expr = crate::Expression::Unary { op: crate::UnaryOperator::Not, expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }; - ctx.expressions.append(expr) + (true, ctx.expressions.append(expr)) + } + Token::Operation('&') => { + let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; + (false, handle) } Token::Word(word) => { - match self.parse_function_call_inner(lexer, word, ctx.reborrow())? { + let handle = match self.parse_function_call_inner(lexer, word, ctx.reborrow())? { Some(handle) => handle, None => { *lexer = backup; self.parse_primary_expression(lexer, ctx.reborrow())? } - } + }; + (true, handle) } _ => { *lexer = backup; - self.parse_primary_expression(lexer, ctx.reborrow())? + let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; + (true, handle) } }; - let post_handle = self.parse_postfix(lexer, ctx, handle, true)?; + let post_handle = self.parse_postfix(lexer, ctx, handle, allow_deref)?; self.scopes.pop(); Ok(post_handle) } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index b439a26b8..64da1fbd4 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -274,3 +274,15 @@ fn parse_expressions() { const z: bool = !(0.0 == 1.0); }").unwrap(); } + +#[test] +fn parse_pointers() { + parse_str( + "fn foo() { + var x: f32 = 1.0; + const px = &x; + const py = frexp(0.5, px); + }", + ) + .unwrap(); +} From fc7b79ddff3c549496b1c311f81eb87589edf455 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 30 Mar 2021 09:38:57 -0400 Subject: [PATCH 0638/2212] [msl-out] make EntryPointError cloneable --- src/back/msl/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 120e8532a..0b067a329 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -76,9 +76,9 @@ pub enum Error { Validation, } -#[derive(Debug, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum EntryPointError { - #[error("bind source for {0:?} is missing from the map")] + #[error("mapping of {0:?} is missing")] MissingBinding(BindSource), } From 7be524592aa66aaaf00926519c093a694bdb98e2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 30 Mar 2021 15:18:06 -0400 Subject: [PATCH 0639/2212] [msl] fix mutability of function parameters --- src/back/msl/writer.rs | 44 ++++++++++++++++++++++-------------- tests/out/quad-vert.msl.snap | 8 +++---- 2 files changed, 31 insertions(+), 21 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 2964a9244..83090a30b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -33,33 +33,40 @@ struct TypedGlobalVariable<'a> { names: &'a FastHashMap, handle: Handle, usage: GlobalUse, + reference: bool, } impl<'a> TypedGlobalVariable<'a> { fn try_fmt(&self, out: &mut W) -> Result<(), Error> { let var = &self.module.global_variables[self.handle]; let name = &self.names[&NameKey::GlobalVariable(self.handle)]; - let ty = &self.module.types[var.ty]; let ty_name = &self.names[&NameKey::Type(var.ty)]; - let (space_qualifier, reference) = match ty.inner { - crate::TypeInner::Struct { .. } => match var.class { - crate::StorageClass::Uniform | crate::StorageClass::Storage => { - let space = if self.usage.contains(GlobalUse::WRITE) { - "device " - } else { - "constant " - }; - (space, "&") - } - _ => ("", ""), - }, - _ => ("", ""), + let (space, access, reference) = match var.class.get_name(self.usage) { + Some(space) if self.reference => { + let access = match var.class { + crate::StorageClass::Private | crate::StorageClass::WorkGroup + if !self.usage.contains(GlobalUse::WRITE) => + { + "const" + } + _ => "", + }; + (space, access, "&") + } + _ => ("", "", ""), }; + Ok(write!( out, - "{}{}{} {}", - space_qualifier, ty_name, reference, name + "{}{}{}{}{}{} {}", + space, + if space.is_empty() { "" } else { " " }, + ty_name, + if access.is_empty() { "" } else { " " }, + access, + reference, + name, )?) } } @@ -123,7 +130,7 @@ impl crate::StorageClass { Self::Storage => Some(if global_use.contains(GlobalUse::WRITE) { "device" } else { - "storage" + "constant" }), Self::Private | Self::Function => Some("thread"), Self::WorkGroup => Some("threadgroup"), @@ -1243,6 +1250,7 @@ impl Writer { names: &self.names, handle, usage: fun_info[handle], + reference: true, }; let separator = separate(index + 1 != pass_through_globals.len()); write!(self.out, "{}", INDENT)?; @@ -1444,6 +1452,7 @@ impl Writer { names: &self.names, handle, usage, + reference: true, }; let separator = if is_first_argument { is_first_argument = false; @@ -1479,6 +1488,7 @@ impl Writer { names: &self.names, handle, usage, + reference: false, }; write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap index 716b77bbb..a3677ef4c 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl.snap @@ -36,10 +36,10 @@ struct type10 { type6 gl_ClipDistance1; }; void main1( - type1 v_uv, - type1 a_uv, - gl_PerVertex _, - type1 a_pos + thread type1& v_uv, + thread type1 const& a_uv, + thread gl_PerVertex& _, + thread type1 const& a_pos ) { v_uv = a_uv; type1 _expr9 = a_pos; From 80a8243953f93c5265ed20cd2bca85bc336fe355 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 31 Mar 2021 01:06:45 +0300 Subject: [PATCH 0640/2212] Fix Uint/Sint type conversion --- src/back/glsl/mod.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index cbc367cd8..b27b6468b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1962,7 +1962,7 @@ impl<'a, W: Write> Writer<'a, W> { // Else the function name is one of the glsl provided bitcast functions Expression::As { expr, - kind, + kind: target_kind, convert, } => { let inner = ctx.info[expr].ty.inner_with(&self.module.types); @@ -1970,7 +1970,7 @@ impl<'a, W: Write> Writer<'a, W> { // this is similar to `write_type`, but with the target kind match *inner { TypeInner::Scalar { kind: _, width } => { - write!(self.out, "{}", glsl_scalar(kind, width)?.full)? + write!(self.out, "{}", glsl_scalar(target_kind, width)?.full)? } TypeInner::Vector { size, @@ -1979,7 +1979,7 @@ impl<'a, W: Write> Writer<'a, W> { } => write!( self.out, "{}vec{}", - glsl_scalar(kind, width)?.prefix, + glsl_scalar(target_kind, width)?.prefix, size as u8 )?, ref other => unreachable!("unexpected cast of {:?}", other), @@ -1989,15 +1989,18 @@ impl<'a, W: Write> Writer<'a, W> { write!( self.out, "{}", - match (source_kind, kind) { + match (source_kind, target_kind) { (ScalarKind::Float, ScalarKind::Sint) => "floatBitsToInt", (ScalarKind::Float, ScalarKind::Uint) => "floatBitsToUInt", (ScalarKind::Sint, ScalarKind::Float) => "intBitsToFloat", (ScalarKind::Uint, ScalarKind::Float) => "uintBitsToFloat", + // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion + (ScalarKind::Uint, ScalarKind::Sint) => "int", + (ScalarKind::Sint, ScalarKind::Uint) => "uint", _ => { return Err(Error::Custom(format!( "Cannot bitcast {:?} to {:?}", - source_kind, kind + source_kind, target_kind ))); } } From 7a17da195c7b460e38ba6e46f0c6f96af1f9ae16 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 31 Mar 2021 22:27:41 -0400 Subject: [PATCH 0641/2212] [msl] use uint behind metal namespace only --- src/back/msl/writer.rs | 7 +++++++ tests/out/boids.msl.snap | 2 +- tests/out/collatz.msl.snap | 2 +- tests/out/quad-vert.msl.snap | 2 +- tests/out/shadow.msl.snap | 2 +- tests/out/skybox.msl.snap | 2 +- 6 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 83090a30b..a82c45661 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -996,6 +996,13 @@ impl Writer { let name = &self.names[&NameKey::Type(handle)]; let global_use = GlobalUse::all(); //TODO match ty.inner { + // work around Metal toolchain bug with `uint` typedef + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } => { + writeln!(self.out, "typedef metal::uint {};", name)?; + } crate::TypeInner::Scalar { kind, .. } => { writeln!(self.out, "typedef {} {};", scalar_kind_string(kind), name)?; } diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index 82bcf12b2..e690e2ccd 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -14,7 +14,7 @@ constexpr constant unsigned const_1u = 1u; constexpr constant float const_1f = 1.0; constexpr constant float const_0_10f = 0.1; constexpr constant float const_n1f = -1.0; -typedef uint type; +typedef metal::uint type; typedef metal::float2 type1; struct Particle { type1 pos; diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index 561440471..f921cb575 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -9,7 +9,7 @@ constexpr constant unsigned const_0u = 0u; constexpr constant unsigned const_1u = 1u; constexpr constant unsigned const_2u = 2u; constexpr constant unsigned const_3u = 3u; -typedef uint type; +typedef metal::uint type; typedef type type1[1]; struct PrimeIndices { type1 data; diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap index a3677ef4c..5ab8150a2 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl.snap @@ -18,7 +18,7 @@ typedef metal::float2 type1; typedef thread type1 *type2; typedef thread type1 *type3; typedef metal::float4 type4; -typedef uint type5; +typedef metal::uint type5; typedef type type6[const_1u]; struct gl_PerVertex { type4 gl_Position; diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index c03bf1cda..e2a9c1c86 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -30,7 +30,7 @@ struct Lights { }; typedef metal::depth2d_array type4; typedef metal::sampler type5; -typedef uint type6; +typedef metal::uint type6; typedef float type7; typedef metal::float2 type8; typedef metal::float3 type9; diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 7b22fd95f..1fbf706d9 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -21,7 +21,7 @@ struct Data { type2 proj_inv; type2 view; }; -typedef uint type3; +typedef metal::uint type3; typedef int type4; typedef metal::float3x3 type5; typedef metal::texturecube type6; From 427d8dc1ebb04317a025f62438905a72a9842fdf Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 31 Mar 2021 22:37:45 -0400 Subject: [PATCH 0642/2212] [spv-in] pre-emit constant expressions --- src/front/spv/mod.rs | 18 +- tests/out/quad-vert.msl.snap | 4 +- tests/out/shadow.info.ron.snap | 278 +++++++++++++++------- tests/out/shadow.ron.snap | 406 +++++++++++++++++---------------- 4 files changed, 415 insertions(+), 291 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 8d7442b31..651fc11a6 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -347,6 +347,7 @@ pub struct Parser { function_call_graph: GraphMap, options: Options, index_constants: Vec>, + index_constant_expressions: Vec>, } impl> Parser { @@ -375,6 +376,7 @@ impl> Parser { function_call_graph: GraphMap::new(), options: options.clone(), index_constants: Vec::new(), + index_constant_expressions: Vec::new(), } } @@ -891,14 +893,11 @@ impl> Parser { _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), }; - let mut index_expr = - expressions.append(crate::Expression::Constant(self.index_constants[0])); let mut handle = expressions.append(crate::Expression::Access { base: root_lexp.handle, - index: index_expr, + index: self.index_constant_expressions[0], }); - for &index in self.index_constants[1..num_components].iter() { - index_expr = expressions.append(crate::Expression::Constant(index)); + for &index_expr in self.index_constant_expressions[1..num_components].iter() { let access_expr = expressions.append(crate::Expression::Access { base: root_lexp.handle, index: index_expr, @@ -942,8 +941,7 @@ impl> Parser { _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), }; let mut components = Vec::with_capacity(num_components); - for &index in self.index_constants[..num_components].iter() { - let index_expr = expressions.append(crate::Expression::Constant(index)); + for &index_expr in self.index_constant_expressions[..num_components].iter() { let access_expr = expressions.append(crate::Expression::Access { base: root_lexp.handle, index: index_expr, @@ -1720,6 +1718,12 @@ impl> Parser { }, ); } + // register special constants + self.index_constant_expressions.clear(); + for &con_handle in self.index_constants.iter() { + let handle = expressions.append(crate::Expression::Constant(con_handle)); + self.index_constant_expressions.push(handle); + } // register constants for (&id, con) in self.lookup_constant.iter() { let handle = expressions.append(crate::Expression::Constant(con.handle)); diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap index 5ab8150a2..16b352977 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl.snap @@ -42,8 +42,8 @@ void main1( thread type1 const& a_pos ) { v_uv = a_uv; - type1 _expr9 = a_pos; - _.gl_Position = metal::float4(_expr9.x, _expr9.y, const_0f, const_1f); + type1 _expr13 = a_pos; + _.gl_Position = metal::float4(_expr13.x, _expr13.y, const_0f, const_1f); return; } diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index ee2b1c2c8..cac191bf1 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -12,7 +12,7 @@ expression: output bits: 7, ), uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -154,6 +154,62 @@ expression: output width: 4, )), ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), ( uniformity: ( non_uniform_result: None, @@ -629,7 +685,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(47), requirements: ( bits: 0, ), @@ -640,7 +696,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -651,7 +707,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -665,7 +721,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -679,7 +735,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -693,7 +749,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -707,7 +763,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -729,7 +785,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -740,7 +796,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -754,7 +810,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -768,7 +824,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -790,7 +846,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -801,7 +857,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -815,7 +871,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -829,7 +885,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(47), requirements: ( bits: 0, ), @@ -843,7 +899,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(47), requirements: ( bits: 0, ), @@ -857,7 +913,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -868,7 +924,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -882,7 +938,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -896,7 +952,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -910,7 +966,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -924,7 +980,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -938,7 +994,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -952,7 +1008,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -963,7 +1019,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -977,7 +1033,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -991,7 +1047,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1013,7 +1069,7 @@ expression: output bits: 7, ), uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1155,6 +1211,62 @@ expression: output width: 4, )), ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), ( uniformity: ( non_uniform_result: None, @@ -1630,7 +1742,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(47), requirements: ( bits: 0, ), @@ -1644,7 +1756,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1658,7 +1770,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1727,7 +1839,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1741,7 +1853,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(47), requirements: ( bits: 0, ), @@ -1752,7 +1864,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1777,7 +1889,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1788,7 +1900,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1802,7 +1914,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1816,7 +1928,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1838,7 +1950,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1853,7 +1965,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1900,7 +2012,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1911,7 +2023,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1925,7 +2037,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1939,7 +2051,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1955,7 +2067,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1983,7 +2095,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1994,7 +2106,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2008,7 +2120,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2022,7 +2134,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2038,7 +2150,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2066,7 +2178,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2077,7 +2189,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2091,7 +2203,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2105,7 +2217,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2121,7 +2233,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2135,7 +2247,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2247,7 +2359,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2258,7 +2370,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2297,7 +2409,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2322,7 +2434,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2333,7 +2445,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2347,7 +2459,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2361,7 +2473,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2377,7 +2489,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2405,7 +2517,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2416,7 +2528,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2430,7 +2542,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2444,7 +2556,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2460,7 +2572,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2488,7 +2600,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2499,7 +2611,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2513,7 +2625,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2527,7 +2639,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2543,7 +2655,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2557,7 +2669,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2568,7 +2680,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2579,7 +2691,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(47), requirements: ( bits: 0, ), @@ -2590,7 +2702,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2601,7 +2713,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2612,7 +2724,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(47), requirements: ( bits: 0, ), @@ -2623,7 +2735,7 @@ expression: output ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(47), requirements: ( bits: 0, ), @@ -2644,7 +2756,7 @@ expression: output bits: 7, ), uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(48), requirements: ( bits: 0, ), diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index 7c05bcee1..cb7c0d81e 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -882,6 +882,10 @@ expression: output GlobalVariable(2), GlobalVariable(4), GlobalVariable(7), + Constant(1), + Constant(2), + Constant(3), + Constant(4), Constant(20), Constant(7), Constant(33), @@ -920,165 +924,165 @@ expression: output FunctionArgument(0), FunctionArgument(1), AccessIndex( - base: 44, + base: 48, index: 3, ), Binary( op: LessEqual, - left: 45, - right: 42, + left: 49, + right: 46, ), AccessIndex( - base: 44, + base: 48, index: 0, ), AccessIndex( - base: 44, + base: 48, index: 1, ), Compose( ty: 9, components: [ - 47, - 48, + 51, + 52, ], ), Compose( ty: 9, components: [ - 9, - 18, + 13, + 22, ], ), Binary( op: Multiply, - left: 49, - right: 50, + left: 53, + right: 54, ), AccessIndex( - base: 44, + base: 48, index: 3, ), Binary( op: Divide, - left: 30, - right: 52, + left: 34, + right: 56, ), Binary( op: Multiply, - left: 51, - right: 53, + left: 55, + right: 57, ), Compose( ty: 9, components: [ - 9, - 9, + 13, + 13, ], ), Binary( op: Add, - left: 54, - right: 55, + left: 58, + right: 59, ), AccessIndex( - base: 56, + base: 60, index: 0, ), AccessIndex( - base: 56, + base: 60, index: 1, ), As( - expr: 43, + expr: 47, kind: Sint, convert: false, ), As( - expr: 59, + expr: 63, kind: Float, convert: true, ), Compose( ty: 2, components: [ - 57, - 58, - 60, + 61, + 62, + 64, ], ), AccessIndex( - base: 44, + base: 48, index: 2, ), AccessIndex( - base: 44, + base: 48, index: 3, ), Binary( op: Divide, - left: 30, - right: 63, + left: 34, + right: 67, ), Binary( op: Multiply, - left: 62, - right: 64, + left: 66, + right: 68, ), AccessIndex( - base: 61, + base: 65, index: 0, ), AccessIndex( - base: 61, + base: 65, index: 1, ), Compose( ty: 6, components: [ - 66, - 67, + 70, + 71, ], ), AccessIndex( - base: 61, + base: 65, index: 2, ), As( - expr: 69, + expr: 73, kind: Sint, convert: true, ), ImageSample( image: 4, sampler: 5, - coordinate: 68, - array_index: Some(70), + coordinate: 72, + array_index: Some(74), offset: None, - level: Exact(21), - depth_ref: Some(65), + level: Exact(25), + depth_ref: Some(69), ), ], body: [ Emit(( - start: 44, - end: 46, + start: 48, + end: 50, )), If( - condition: 46, + condition: 50, accept: [ Return( - value: Some(30), + value: Some(34), ), ], reject: [], ), Emit(( - start: 46, - end: 71, + start: 50, + end: 75, )), Return( - value: Some(71), + value: Some(75), ), ], ), @@ -1106,6 +1110,10 @@ expression: output GlobalVariable(2), GlobalVariable(4), GlobalVariable(7), + Constant(1), + Constant(2), + Constant(3), + Constant(4), Constant(20), Constant(7), Constant(33), @@ -1144,61 +1152,61 @@ expression: output LocalVariable(1), LocalVariable(2), Load( - pointer: 44, + pointer: 48, ), AccessIndex( base: 1, index: 0, ), Access( - base: 46, - index: 37, + base: 50, + index: 41, ), Load( - pointer: 47, + pointer: 51, ), Math( fun: Min, - arg: 48, - arg1: Some(28), + arg: 52, + arg1: Some(32), arg2: None, ), Binary( op: GreaterEqual, - left: 45, - right: 49, + left: 49, + right: 53, ), Load( - pointer: 43, + pointer: 47, ), Load( - pointer: 44, + pointer: 48, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 48, ), Access( - base: 53, - index: 54, + base: 57, + index: 58, ), AccessIndex( - base: 55, + base: 59, index: 0, ), Load( - pointer: 56, + pointer: 60, ), Load( pointer: 3, ), Binary( op: Multiply, - left: 57, - right: 58, + left: 61, + right: 62, ), Call(1), Load( @@ -1206,7 +1214,7 @@ expression: output ), Math( fun: Normalize, - arg: 61, + arg: 65, arg1: None, arg2: None, ), @@ -1215,232 +1223,232 @@ expression: output index: 0, ), Load( - pointer: 44, + pointer: 48, ), Access( - base: 63, - index: 64, + base: 67, + index: 68, ), AccessIndex( - base: 65, - index: 1, - ), - Access( - base: 66, - index: 31, - ), - Load( - pointer: 67, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 44, - ), - Access( base: 69, - index: 70, - ), - AccessIndex( - base: 71, index: 1, ), Access( - base: 72, - index: 38, + base: 70, + index: 35, ), Load( - pointer: 73, + pointer: 71, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 48, ), Access( - base: 75, - index: 76, + base: 73, + index: 74, ), AccessIndex( - base: 77, + base: 75, index: 1, ), Access( - base: 78, - index: 13, + base: 76, + index: 42, ), Load( - pointer: 79, + pointer: 77, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 48, + ), + Access( + base: 79, + index: 80, + ), + AccessIndex( + base: 81, + index: 1, + ), + Access( + base: 82, + index: 17, + ), + Load( + pointer: 83, ), Compose( ty: 2, components: [ - 68, - 74, - 80, + 72, + 78, + 84, ], ), Access( base: 3, - index: 36, - ), - Load( - pointer: 82, - ), - Access( - base: 3, - index: 12, - ), - Load( - pointer: 84, - ), - Access( - base: 3, - index: 23, + index: 40, ), Load( pointer: 86, ), + Access( + base: 3, + index: 16, + ), + Load( + pointer: 88, + ), + Access( + base: 3, + index: 27, + ), + Load( + pointer: 90, + ), Compose( ty: 2, components: [ - 83, - 85, 87, + 89, + 91, ], ), Binary( op: Subtract, - left: 81, - right: 88, + left: 85, + right: 92, ), Math( fun: Normalize, - arg: 89, + arg: 93, arg1: None, arg2: None, ), Math( fun: Dot, - arg: 62, - arg1: Some(90), + arg: 66, + arg1: Some(94), arg2: None, ), Math( fun: Max, - arg: 42, - arg1: Some(91), + arg: 46, + arg1: Some(95), arg2: None, ), Binary( op: Multiply, - left: 60, - right: 92, + left: 64, + right: 96, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 48, ), Access( - base: 94, - index: 95, + base: 98, + index: 99, ), AccessIndex( - base: 96, - index: 2, - ), - Access( - base: 97, - index: 10, - ), - Load( - pointer: 98, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 44, - ), - Access( base: 100, - index: 101, - ), - AccessIndex( - base: 102, index: 2, ), Access( - base: 103, - index: 19, + base: 101, + index: 14, ), Load( - pointer: 104, + pointer: 102, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 48, ), Access( - base: 106, - index: 107, + base: 104, + index: 105, ), AccessIndex( - base: 108, + base: 106, index: 2, ), Access( - base: 109, - index: 26, + base: 107, + index: 23, ), Load( - pointer: 110, + pointer: 108, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 48, + ), + Access( + base: 110, + index: 111, + ), + AccessIndex( + base: 112, + index: 2, + ), + Access( + base: 113, + index: 30, + ), + Load( + pointer: 114, ), Compose( ty: 2, components: [ - 99, - 105, - 111, + 103, + 109, + 115, ], ), Binary( op: Multiply, - left: 112, - right: 93, + left: 116, + right: 97, ), Binary( op: Add, - left: 51, - right: 113, + left: 55, + right: 117, ), Load( - pointer: 44, + pointer: 48, ), Binary( op: Add, - left: 115, - right: 27, + left: 119, + right: 31, ), Load( - pointer: 43, + pointer: 47, ), Compose( ty: 4, components: [ - 117, - 30, + 121, + 34, ], ), ], @@ -1448,55 +1456,55 @@ expression: output Loop( body: [ Emit(( - start: 44, - end: 50, + start: 48, + end: 54, )), If( - condition: 50, + condition: 54, accept: [ Break, ], reject: [], ), Emit(( - start: 50, - end: 59, + start: 54, + end: 63, )), Call( function: 1, arguments: [ - 52, - 59, + 56, + 63, ], - result: Some(60), + result: Some(64), ), Emit(( - start: 60, - end: 114, + start: 64, + end: 118, )), Store( - pointer: 43, - value: 114, + pointer: 47, + value: 118, ), ], continuing: [ Emit(( - start: 114, - end: 116, + start: 118, + end: 120, )), Store( - pointer: 44, - value: 116, + pointer: 48, + value: 120, ), ], ), Emit(( - start: 116, - end: 118, + start: 120, + end: 122, )), Store( pointer: 7, - value: 118, + value: 122, ), Return( value: None, From 62fe72be2e788e00aa607010e471c64b02888893 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 09:34:07 -0400 Subject: [PATCH 0643/2212] Enable all features for the docs --- Cargo.toml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 2607cf33e..7f3ef3efd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,9 +6,12 @@ edition = "2018" description = "Shader translation infrastructure" homepage = "https://github.com/gfx-rs/naga" repository = "https://github.com/gfx-rs/naga" -keywords = ["shader", "SPIR-V"] +keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" +[package.metadata.docs.rs] +all-features = true + [dependencies] bitflags = "1" bit-set = "0.5" From cf3a6da3ce643e1d602ecac57c69c0d69a8bb481 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 31 Mar 2021 23:18:33 -0400 Subject: [PATCH 0644/2212] [msl] clean up emitted expressions at the end of a block --- src/back/msl/writer.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a82c45661..f748b5a7b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -969,6 +969,16 @@ impl Writer { } } } + + // un-emit expressions + //TODO: take care of loop/continuing? + for statement in statements { + if let crate::Statement::Emit(ref range) = *statement { + for handle in range.clone() { + self.named_expressions.remove(handle.index()); + } + } + } Ok(()) } From af4d989f556fc810afcf4af1dfd5080ddcb3dbb5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 31 Mar 2021 23:48:21 -0400 Subject: [PATCH 0645/2212] [msl-out] copy array elements one by one --- src/back/msl/writer.rs | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index f748b5a7b..549a683b0 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -907,11 +907,40 @@ impl Writer { writeln!(self.out, "{}{}::discard_fragment();", level, NAMESPACE)?; } crate::Statement::Store { pointer, value } => { - write!(self.out, "{}", level)?; - self.put_expression(pointer, &context.expression, true)?; - write!(self.out, " = ")?; - self.put_expression(value, &context.expression, true)?; - writeln!(self.out, ";")?; + // we can't assign fixed-size arrays + let pointer_info = &context.expression.info[pointer]; + let array_size = + match *pointer_info.ty.inner_with(&context.expression.module.types) { + crate::TypeInner::Pointer { base, .. } => { + match context.expression.module.types[base].inner { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(ch), + .. + } => Some(ch), + _ => None, + } + } + _ => None, + }; + match array_size { + Some(const_handle) => { + let size = context.expression.module.constants[const_handle] + .to_array_length() + .unwrap(); + write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?; + self.put_expression(pointer, &context.expression, true)?; + write!(self.out, "[_i] = ")?; + self.put_expression(value, &context.expression, true)?; + writeln!(self.out, "[_i];")?; + } + None => { + write!(self.out, "{}", level)?; + self.put_expression(pointer, &context.expression, true)?; + write!(self.out, " = ")?; + self.put_expression(value, &context.expression, true)?; + writeln!(self.out, ";")?; + } + } } crate::Statement::ImageStore { image, From 6a5c7f10ad86e4952cf2ae2f2edfd9ce6c783777 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 09:52:23 -0400 Subject: [PATCH 0646/2212] [msl-out] cast image load/store coordinates to unsigned --- src/back/msl/writer.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 549a683b0..bb029876e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -212,6 +212,23 @@ impl Writer { Ok(()) } + fn put_storage_image_coordinate( + &mut self, + expr: Handle, + context: &ExpressionContext, + ) -> Result<(), Error> { + // coordinates in IR are int, but Metal expects uint + let size_str = match *context.info[expr].ty.inner_with(&context.module.types) { + crate::TypeInner::Scalar { .. } => "", + crate::TypeInner::Vector { size, .. } => vector_size_string(size), + _ => return Err(Error::Validation), + }; + write!(self.out, "{}::uint{}(", NAMESPACE, size_str)?; + self.put_expression(expr, context, true)?; + write!(self.out, ")")?; + Ok(()) + } + fn put_initialization_component( &mut self, component: Handle, @@ -441,7 +458,7 @@ impl Writer { } => { self.put_expression(image, context, false)?; write!(self.out, ".read(")?; - self.put_expression(coordinate, context, true)?; + self.put_storage_image_coordinate(coordinate, context)?; if let Some(expr) = array_index { write!(self.out, ", ")?; self.put_expression(expr, context, true)?; @@ -953,7 +970,7 @@ impl Writer { write!(self.out, ".write(")?; self.put_expression(value, &context.expression, true)?; write!(self.out, ", ")?; - self.put_expression(coordinate, &context.expression, true)?; + self.put_storage_image_coordinate(coordinate, &context.expression)?; if let Some(expr) = array_index { write!(self.out, ", ")?; self.put_expression(expr, &context.expression, true)?; From db455af04ba888e197d5831497f84830914248dd Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 10:25:17 -0400 Subject: [PATCH 0647/2212] Add a snapshot for image load/store ops --- tests/in/image-copy.param.ron | 8 ++++++++ tests/in/image-copy.wgsl | 16 ++++++++++++++++ tests/out/image-copy.msl.snap | 27 +++++++++++++++++++++++++++ tests/snapshots.rs | 7 +++++++ 4 files changed, 58 insertions(+) create mode 100644 tests/in/image-copy.param.ron create mode 100644 tests/in/image-copy.wgsl create mode 100644 tests/out/image-copy.msl.snap diff --git a/tests/in/image-copy.param.ron b/tests/in/image-copy.param.ron new file mode 100644 index 000000000..f4cbc5f0b --- /dev/null +++ b/tests/in/image-copy.param.ron @@ -0,0 +1,8 @@ +( + spv_version: (1, 1), + spv_capabilities: [ Shader, Image1D, Sampled1D ], + mtl_bindings: { + (stage: Compute, group: 0, binding: 1): (texture: Some(0), mutable: false), + (stage: Compute, group: 0, binding: 2): (texture: Some(1), mutable: true), + } +) diff --git a/tests/in/image-copy.wgsl b/tests/in/image-copy.wgsl new file mode 100644 index 000000000..cb09083b9 --- /dev/null +++ b/tests/in/image-copy.wgsl @@ -0,0 +1,16 @@ +[[group(0), binding(1)]] +var image_src: [[access(read)]] texture_storage_2d; +[[group(0), binding(2)]] +var image_dst: [[access(write)]] texture_storage_1d; + +[[stage(compute), workgroup_size(16)]] +fn main( + [[builtin(local_invocation_id)]] local_id: vec3, + //TODO: https://github.com/gpuweb/gpuweb/issues/1590 + //[[builtin(workgroup_size)]] wg_size: vec3 +) { + const dim = textureDimensions(image_src); + const itc = dim * vec2(local_id.xy) % vec2(10, 20); + const value = textureLoad(image_src, itc); + textureStore(image_dst, itc.x, value); +} diff --git a/tests/out/image-copy.msl.snap b/tests/out/image-copy.msl.snap new file mode 100644 index 000000000..81329b6bd --- /dev/null +++ b/tests/out/image-copy.msl.snap @@ -0,0 +1,27 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +constexpr constant int const_10i = 10; +constexpr constant int const_20i = 20; +typedef metal::texture2d type; +typedef metal::texture1d type1; +typedef metal::uint3 type2; +typedef metal::uint2 type3; +typedef metal::int2 type4; +struct main1Input { +}; +kernel void main1( + type2 local_id [[thread_position_in_threadgroup]] +, type image_src [[texture(0)]] +, type1 image_dst [[texture(1)]] +) { + metal::int2 _expr12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(const_10i, const_20i); + metal::uint4 _expr13 = image_src.read(metal::uint2(_expr12)); + image_dst.write(_expr13, metal::uint(_expr12.x)); + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 30def8d2c..9bddce1ca 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -264,6 +264,13 @@ fn convert_wgsl_shadow() { convert_wgsl("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL); } +#[cfg(feature = "wgsl-in")] +#[test] +fn convert_wgsl_image_copy() { + //SPIR-V is blocked by https://github.com/gfx-rs/naga/issues/646 + convert_wgsl("image-copy", Targets::METAL); +} + #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_texture_array() { From f8b3c597ff1fd55bfe14f5cb62aa060173718da2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 10:34:54 -0400 Subject: [PATCH 0648/2212] [msl-out] move image size query into a separate method --- src/back/msl/writer.rs | 84 +++++++++++++++++++++++------------------- 1 file changed, 47 insertions(+), 37 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index bb029876e..8312cc819 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -212,6 +212,49 @@ impl Writer { Ok(()) } + fn put_image_size_query( + &mut self, + image: Handle, + level: Option>, + context: &ExpressionContext, + ) -> Result<(), Error> { + //Note: MSL only has separate width/height/depth queries, + // so compose the result of them. + let dim = match *context.resolve_type(image) { + crate::TypeInner::Image { dim, .. } => dim, + ref other => unreachable!("Unexpected type {:?}", other), + }; + match dim { + crate::ImageDimension::D1 => { + write!(self.out, "int(")?; + self.put_image_query(image, "width", level, context)?; + write!(self.out, ")")?; + } + crate::ImageDimension::D2 => { + write!(self.out, "int2(")?; + self.put_image_query(image, "width", level, context)?; + write!(self.out, ", ")?; + self.put_image_query(image, "height", level, context)?; + write!(self.out, ")")?; + } + crate::ImageDimension::D3 => { + write!(self.out, "int3(")?; + self.put_image_query(image, "width", level, context)?; + write!(self.out, ", ")?; + self.put_image_query(image, "height", level, context)?; + write!(self.out, ", ")?; + self.put_image_query(image, "depth", level, context)?; + write!(self.out, ")")?; + } + crate::ImageDimension::Cube => { + write!(self.out, "int(")?; + self.put_image_query(image, "width", level, context)?; + write!(self.out, ").xxx")?; + } + } + Ok(()) + } + fn put_storage_image_coordinate( &mut self, expr: Handle, @@ -473,40 +516,7 @@ impl Writer { // so a conversion is needed. crate::Expression::ImageQuery { image, query } => match query { crate::ImageQuery::Size { level } => { - //Note: MSL only has separate width/height/depth queries, - // so compose the result of them. - let dim = match *context.resolve_type(image) { - crate::TypeInner::Image { dim, .. } => dim, - ref other => unreachable!("Unexpected type {:?}", other), - }; - match dim { - crate::ImageDimension::D1 => { - write!(self.out, "int(")?; - self.put_image_query(image, "width", level, context)?; - write!(self.out, ")")?; - } - crate::ImageDimension::D2 => { - write!(self.out, "int2(")?; - self.put_image_query(image, "width", level, context)?; - write!(self.out, ", ")?; - self.put_image_query(image, "height", level, context)?; - write!(self.out, ")")?; - } - crate::ImageDimension::D3 => { - write!(self.out, "int3(")?; - self.put_image_query(image, "width", level, context)?; - write!(self.out, ", ")?; - self.put_image_query(image, "height", level, context)?; - write!(self.out, ", ")?; - self.put_image_query(image, "depth", level, context)?; - write!(self.out, ")")?; - } - crate::ImageDimension::Cube => { - write!(self.out, "int(")?; - self.put_image_query(image, "width", level, context)?; - write!(self.out, ").xxx")?; - } - } + self.put_image_size_query(image, level, context)?; } crate::ImageQuery::NumLevels => { write!(self.out, "int(")?; @@ -1680,8 +1690,8 @@ fn test_stack_size() { } let stack_size = max_addr - min_addr; // check the size (in debug only) - // last observed macOS value: 22112 - if stack_size > 22200 { - panic!("`put_expression` stack size {} is too large!", stack_size); + // last observed macOS value: 18768 + if stack_size < 18000 || stack_size > 19500 { + panic!("`put_expression` stack size {} has changed!", stack_size); } } From 13c93568735d49890d0010c7975ba9bc0d9ab51f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 10:44:15 -0400 Subject: [PATCH 0649/2212] [msl-out] track put_block stack sizes --- src/back/msl/writer.rs | 47 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 9 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8312cc819..b16d044ac 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -78,6 +78,8 @@ pub struct Writer { namer: Namer, #[cfg(test)] put_expression_stack_pointers: crate::FastHashSet<*const ()>, + #[cfg(test)] + put_block_stack_pointers: crate::FastHashSet<*const ()>, } fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { @@ -172,6 +174,8 @@ impl Writer { namer: Namer::default(), #[cfg(test)] put_expression_stack_pointers: Default::default(), + #[cfg(test)] + put_block_stack_pointers: Default::default(), } } @@ -785,6 +789,12 @@ impl Writer { statements: &[crate::Statement], context: &StatementContext, ) -> Result<(), Error> { + // Add to the set in order to track the stack size. + #[cfg(test)] + #[allow(trivial_casts)] + self.put_block_stack_pointers + .insert(&level as *const _ as *const ()); + for statement in statements { log::trace!("statement[{}] {:?}", level.0, statement); match *statement { @@ -1683,15 +1693,34 @@ fn test_stack_size() { // process the module let mut writer = Writer::new(String::new()); writer.write(&module, &info, &Default::default()).unwrap(); - let (mut min_addr, mut max_addr) = (!0usize, 0usize); - for pointer in writer.put_expression_stack_pointers { - min_addr = min_addr.min(pointer as usize); - max_addr = max_addr.max(pointer as usize); + + { + // check expression stack + let mut addresses = !0usize..0usize; + for pointer in writer.put_expression_stack_pointers { + addresses.start = addresses.start.min(pointer as usize); + addresses.end = addresses.end.max(pointer as usize); + } + let stack_size = addresses.end - addresses.start; + // check the size (in debug only) + // last observed macOS value: 18768 + if stack_size < 18000 || stack_size > 19500 { + panic!("`put_expression` stack size {} has changed!", stack_size); + } } - let stack_size = max_addr - min_addr; - // check the size (in debug only) - // last observed macOS value: 18768 - if stack_size < 18000 || stack_size > 19500 { - panic!("`put_expression` stack size {} has changed!", stack_size); + + { + // check block stack + let mut addresses = !0usize..0usize; + for pointer in writer.put_block_stack_pointers { + addresses.start = addresses.start.min(pointer as usize); + addresses.end = addresses.end.max(pointer as usize); + } + let stack_size = addresses.end - addresses.start; + // check the size (in debug only) + // last observed macOS value: 15616 + if stack_size < 15000 || stack_size > 16200 { + panic!("`put_block` stack size {} has changed!", stack_size); + } } } From cbdfbed32ed9c58eed688fd0a361e35470746579 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 10:52:07 -0400 Subject: [PATCH 0650/2212] [msl-out] move return value statement into a function --- src/back/msl/writer.rs | 126 +++++++++++++++++++++++------------------ 1 file changed, 70 insertions(+), 56 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index b16d044ac..08aa6cbd9 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -750,6 +750,67 @@ impl Writer { Ok(()) } + fn put_return_value( + &mut self, + level: Level, + expr_handle: Handle, + result_struct: Option<&str>, + context: &ExpressionContext, + ) -> Result<(), Error> { + match result_struct { + Some(struct_name) => { + let result_ty = context.function.result.as_ref().unwrap().ty; + match context.module.types[result_ty].inner { + crate::TypeInner::Struct { + block: _, + ref members, + } => { + let tmp = "_tmp"; + write!(self.out, "{}const auto {} = ", level, tmp)?; + self.put_expression(expr_handle, context, true)?; + writeln!(self.out, ";")?; + write!(self.out, "{}return {} {{", level, struct_name)?; + for (index, member) in members.iter().enumerate() { + let comma = if index == 0 { "" } else { "," }; + let name = &self.names[&NameKey::StructMember(result_ty, index as u32)]; + // logic similar to `put_initialization_component` + if let crate::TypeInner::Array { + size: crate::ArraySize::Constant(const_handle), + .. + } = context.module.types[member.ty].inner + { + let size = context.module.constants[const_handle] + .to_array_length() + .unwrap(); + write!(self.out, "{} {{", comma)?; + for j in 0..size { + if j != 0 { + write!(self.out, ",")?; + } + write!(self.out, "{}.{}[{}]", tmp, name, j)?; + } + write!(self.out, "}}")?; + } else { + write!(self.out, "{} {}.{}", comma, tmp, name)?; + } + } + } + _ => { + write!(self.out, "{}return {} {{ ", level, struct_name)?; + self.put_expression(expr_handle, context, true)?; + } + } + write!(self.out, " }}")?; + } + None => { + write!(self.out, "{}return ", level)?; + self.put_expression(expr_handle, context, true)?; + } + } + writeln!(self.out, ";")?; + Ok(()) + } + fn start_baking_expression( &mut self, handle: Handle, @@ -883,59 +944,12 @@ impl Writer { crate::Statement::Return { value: Some(expr_handle), } => { - match context.result_struct { - Some(struct_name) => { - let result_ty = context.expression.function.result.as_ref().unwrap().ty; - match context.expression.module.types[result_ty].inner { - crate::TypeInner::Struct { - block: _, - ref members, - } => { - let tmp = "_tmp"; - write!(self.out, "{}const auto {} = ", level, tmp)?; - self.put_expression(expr_handle, &context.expression, true)?; - writeln!(self.out, ";")?; - write!(self.out, "{}return {} {{", level, struct_name)?; - for (index, member) in members.iter().enumerate() { - let comma = if index == 0 { "" } else { "," }; - let name = &self.names - [&NameKey::StructMember(result_ty, index as u32)]; - // logic similar to `put_initialization_component` - if let crate::TypeInner::Array { - size: crate::ArraySize::Constant(const_handle), - .. - } = context.expression.module.types[member.ty].inner - { - let size = context.expression.module.constants - [const_handle] - .to_array_length() - .unwrap(); - write!(self.out, "{} {{", comma)?; - for j in 0..size { - if j != 0 { - write!(self.out, ",")?; - } - write!(self.out, "{}.{}[{}]", tmp, name, j)?; - } - write!(self.out, "}}")?; - } else { - write!(self.out, "{} {}.{}", comma, tmp, name)?; - } - } - } - _ => { - write!(self.out, "{}return {} {{ ", level, struct_name)?; - self.put_expression(expr_handle, &context.expression, true)?; - } - } - write!(self.out, " }}")?; - } - None => { - write!(self.out, "{}return ", level)?; - self.put_expression(expr_handle, &context.expression, true)?; - } - } - writeln!(self.out, ";")?; + self.put_return_value( + level.clone(), + expr_handle, + context.result_struct, + &context.expression, + )?; } crate::Statement::Return { value: None } => { writeln!(self.out, "{}return;", level)?; @@ -1704,7 +1718,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 18768 - if stack_size < 18000 || stack_size > 19500 { + if stack_size < 18000 || stack_size > 20000 { panic!("`put_expression` stack size {} has changed!", stack_size); } } @@ -1718,8 +1732,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 15616 - if stack_size < 15000 || stack_size > 16200 { + // last observed macOS value: 12736 + if stack_size < 12000 || stack_size > 13500 { panic!("`put_block` stack size {} has changed!", stack_size); } } From 8ff27187d1e1bb15c4147694052e1a796d5e59ad Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 15:43:33 -0400 Subject: [PATCH 0651/2212] Fix matrix multiplication types --- src/proc/typifier.rs | 72 +++++++++++++++++++-------------- tests/out/collatz.info.ron.snap | 10 +---- tests/out/shadow.info.ron.snap | 5 ++- 3 files changed, 47 insertions(+), 40 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 0bf23993c..3183c5bd9 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -369,43 +369,53 @@ impl<'a> ResolveContext<'a> { | crate::BinaryOperator::Divide | crate::BinaryOperator::Modulo => past(left).clone(), crate::BinaryOperator::Multiply => { - let res_left = past(left); - let ty_left = res_left.inner_with(types); - let res_right = past(right); - let ty_right = res_right.inner_with(types); - if ty_left == ty_right { - res_left.clone() - } else if let Ti::Scalar { .. } = *ty_left { - res_right.clone() - } else if let Ti::Scalar { .. } = *ty_right { - res_left.clone() - } else if let Ti::Matrix { - columns: _, - rows, - width, - } = *ty_left - { - TypeResolution::Value(Ti::Vector { + let (res_left, res_right) = (past(left), past(right)); + match (res_left.inner_with(types), res_right.inner_with(types)) { + ( + &Ti::Matrix { + columns: _, + rows, + width, + }, + &Ti::Matrix { columns, .. }, + ) => TypeResolution::Value(Ti::Matrix { + columns, + rows, + width, + }), + ( + &Ti::Matrix { + columns: _, + rows, + width, + }, + &Ti::Vector { .. }, + ) => TypeResolution::Value(Ti::Vector { size: rows, kind: crate::ScalarKind::Float, width, - }) - } else if let Ti::Matrix { - columns, - rows: _, - width, - } = *ty_right - { - TypeResolution::Value(Ti::Vector { + }), + ( + &Ti::Vector { .. }, + &Ti::Matrix { + columns, + rows: _, + width, + }, + ) => TypeResolution::Value(Ti::Vector { size: columns, kind: crate::ScalarKind::Float, width, - }) - } else { - return Err(ResolveError::IncompatibleOperands(format!( - "{:?} * {:?}", - ty_left, ty_right - ))); + }), + (&Ti::Scalar { .. }, _) => res_right.clone(), + (_, &Ti::Scalar { .. }) => res_left.clone(), + (&Ti::Vector { .. }, &Ti::Vector { .. }) => res_left.clone(), + (tl, tr) => { + return Err(ResolveError::IncompatibleOperands(format!( + "{:?} * {:?}", + tl, tr + ))) + } } } crate::BinaryOperator::Equal diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index 517e4c545..aff136329 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -265,10 +265,7 @@ expression: output ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Uint, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -293,10 +290,7 @@ expression: output ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Uint, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index cac191bf1..0881409f0 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -2416,7 +2416,10 @@ expression: output ), ref_count: 1, assignable_global: None, - ty: Handle(1), + ty: Value(Scalar( + kind: Float, + width: 4, + )), ), ( uniformity: ( From d4d9d7814f1bdea228bc6f5e00576e71ea836677 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 23:49:17 -0400 Subject: [PATCH 0652/2212] [msl-out] option to omit point size output --- src/back/msl/mod.rs | 4 ++++ src/back/msl/writer.rs | 18 +++++++++++++++++- tests/snapshots.rs | 1 + 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 0b067a329..23b63794c 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -100,6 +100,9 @@ pub struct Options { pub spirv_cross_compatibility: bool, /// Don't panic on missing bindings, instead generate invalid MSL. pub fake_missing_bindings: bool, + /// Allow `BuiltIn::PointSize` in the vertex shader. + /// Metal doesn't like this for non-point primitive topologies. + pub allow_point_size: bool, } impl Default for Options { @@ -109,6 +112,7 @@ impl Default for Options { binding_map: BindingMap::default(), spirv_cross_compatibility: false, fake_missing_bindings: true, + allow_point_size: true, } } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 08aa6cbd9..5d3f76119 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -150,6 +150,7 @@ struct ExpressionContext<'a> { origin: FunctionOrigin, info: &'a FunctionInfo, module: &'a crate::Module, + options: &'a Options, } impl<'a> ExpressionContext<'a> { @@ -770,8 +771,16 @@ impl Writer { self.put_expression(expr_handle, context, true)?; writeln!(self.out, ";")?; write!(self.out, "{}return {} {{", level, struct_name)?; + let mut is_first = true; for (index, member) in members.iter().enumerate() { - let comma = if index == 0 { "" } else { "," }; + if !context.options.allow_point_size + && member.binding + == Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) + { + continue; + } + let comma = if is_first { "" } else { "," }; + is_first = false; let name = &self.names[&NameKey::StructMember(result_ty, index as u32)]; // logic similar to `put_initialization_component` if let crate::TypeInner::Array { @@ -1373,6 +1382,7 @@ impl Writer { origin: FunctionOrigin::Handle(fun_handle), info: fun_info, module, + options, }, mod_info, result_struct: None, @@ -1501,6 +1511,11 @@ impl Writer { for (name, ty, binding) in result_members { let type_name = &self.names[&NameKey::Type(ty)]; let binding = binding.ok_or(Error::Validation)?; + if !options.allow_point_size + && *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize) + { + continue; + } let resolved = options.resolve_local_binding(binding, out_mode)?; write!(self.out, "{}{} {}", INDENT, type_name, name)?; resolved.try_fmt_decorated(&mut self.out, "")?; @@ -1655,6 +1670,7 @@ impl Writer { origin: FunctionOrigin::EntryPoint(ep_index as _), info: fun_info, module, + options, }, mod_info, result_struct: Some(&stage_out_name), diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 9bddce1ca..d6bd5e887 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -176,6 +176,7 @@ fn check_output_msl( binding_map, spirv_cross_compatibility: false, fake_missing_bindings: false, + allow_point_size: true, }; let (msl, _) = msl::write_string(module, info, &options).unwrap(); From 4389a86787bd205363b82098c242ba0bbdf04bfb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 3 Apr 2021 00:36:32 -0400 Subject: [PATCH 0653/2212] Fix layout roundup --- bin/convert.rs | 1 + src/proc/layouter.rs | 2 +- src/valid/analyzer.rs | 3 ++- src/valid/mod.rs | 1 + tests/out/quad.spvasm.snap | 2 +- tests/out/shadow.info.ron.snap | 2 +- 6 files changed, 7 insertions(+), 4 deletions(-) diff --git a/bin/convert.rs b/bin/convert.rs index aab31be55..402b21e34 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -185,6 +185,7 @@ fn main() { Some(ref string) => string, None => { println!("{:#?}", module); + println!("{:#?}", info); return; } }; diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 8a90cc8f4..d8674f846 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -30,7 +30,7 @@ impl Layouter { } pub fn round_up(alignment: NonZeroU32, offset: u32) -> u32 { - match offset & alignment.get() { + match offset & (alignment.get() - 1) { 0 => offset, other => offset + alignment.get() - other, } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 9e8e81c91..94d7fecc9 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -134,7 +134,7 @@ pub struct SamplingKey { pub sampler: Handle, } -#[derive(Clone)] +#[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ExpressionInfo { @@ -159,6 +159,7 @@ impl ExpressionInfo { } } +#[derive(Debug)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct FunctionInfo { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 5ed602521..0ecf12e33 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -48,6 +48,7 @@ bitflags::bitflags! { } } +#[derive(Debug)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ModuleInfo { diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index 425fdedd5..ef0b768a0 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -30,7 +30,7 @@ OpName %44 "uv" OpName %47 "main" OpName %47 "main" OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 8 +OpMemberDecorate %9 1 Offset 16 OpDecorate %12 DescriptorSet 0 OpDecorate %12 Binding 0 OpDecorate %14 DescriptorSet 0 diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 0881409f0..928083055 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -2956,7 +2956,7 @@ expression: output alignment: 96, ), ( - size: 96, + size: 128, alignment: 96, ), ( From ab54f683bee5d0480e6c7830cb0e3b683f6a2ff6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 01:25:34 -0400 Subject: [PATCH 0654/2212] [spv-in] flip Y axis --- src/front/spv/function.rs | 37 ++++++++++++++++++++++++++++++++---- src/front/spv/mod.rs | 1 + tests/out/quad-vert.msl.snap | 1 + 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 082c9ff17..8a71b4037 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -279,12 +279,41 @@ impl> super::Parser { } } - let old_len = function.expressions.len(); - for component in components.iter_mut() { - *component = function.expressions.append(crate::Expression::Load { - pointer: *component, + let position_index = members.iter().position(|member| match member.binding { + Some(crate::Binding::BuiltIn(crate::BuiltIn::Position)) => true, + _ => false, + }); + if let Some(component_index) = position_index { + let old_len = function.expressions.len(); + let global_expr = components[component_index]; + let access_expr = function.expressions.append(crate::Expression::AccessIndex { + base: global_expr, + index: 1, + }); + let load_expr = function.expressions.append(crate::Expression::Load { + pointer: access_expr, + }); + let neg_expr = function.expressions.append(crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr: load_expr, + }); + function.body.push(crate::Statement::Emit( + function.expressions.range_from(old_len), + )); + function.body.push(crate::Statement::Store { + pointer: access_expr, + value: neg_expr, }); } + + let old_len = function.expressions.len(); + for component in components.iter_mut() { + let load_expr = crate::Expression::Load { + pointer: *component, + }; + *component = function.expressions.append(load_expr); + } + match members.len() { 0 => {} 1 => { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 651fc11a6..1fe4e51da 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1825,6 +1825,7 @@ impl> Parser { crate::Module::default() }; + // register indexing constants self.index_constants.clear(); for i in 0..4 { let handle = module.constants.append(crate::Constant { diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap index 16b352977..79d91a3cd 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl.snap @@ -69,6 +69,7 @@ vertex main2Output main2( a_uv = a_uv1; a_pos = a_pos1; main1(v_uv, a_uv, _, a_pos); + _.gl_Position.y = -_.gl_Position.y; const auto _tmp = type10 {v_uv, _.gl_Position, _.gl_PointSize, {_.gl_ClipDistance[0]}}; return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1[0]} }; } From 5673603bab90fda79172bc5eb9ad2e177577a67b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 23:00:55 -0400 Subject: [PATCH 0655/2212] [spv-out] flip position Y --- src/back/spv/writer.rs | 157 ++++++++++++++++++++++++++--------- src/proc/mod.rs | 9 ++ tests/out/quad.spvasm.snap | 66 ++++++++------- tests/out/skybox.spvasm.snap | 68 ++++++++------- 4 files changed, 200 insertions(+), 100 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 91fcada40..94b7ab2e1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -53,10 +53,15 @@ struct LocalVariable { instruction: Instruction, } -#[derive(Default)] +struct ResultMember { + id: Word, + type_id: Word, + built_in: Option, +} + struct EntryPointContext { argument_ids: Vec, - result_ids_typed: Vec<(Word, Word)>, + results: Vec, } #[derive(Default)] @@ -362,6 +367,24 @@ impl Writer { id } + fn get_index_constant( + &mut self, + index: Word, + types: &Arena, + ) -> Result { + let type_id = self.get_type_id( + types, + LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + }), + )?; + //TODO: cache this + Ok(self.create_constant(type_id, &[index])) + } + fn write_function( &mut self, ir_function: &crate::Function, @@ -398,7 +421,10 @@ impl Writer { let prelude_id = self.id_gen.next(); let mut prelude = Block::new(prelude_id); - let mut ep_context = EntryPointContext::default(); + let mut ep_context = EntryPointContext { + argument_ids: Vec::new(), + results: Vec::new(), + }; let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); for argument in ir_function.arguments.iter() { @@ -465,7 +491,11 @@ impl Writer { let varying_id = self.write_varying(ir_module, class, None, result.ty, binding)?; list.push(varying_id); - ep_context.result_ids_typed.push((varying_id, type_id)); + ep_context.results.push(ResultMember { + id: varying_id, + type_id, + built_in: binding.to_built_in(), + }); } else if let crate::TypeInner::Struct { block: _, ref members, @@ -479,7 +509,11 @@ impl Writer { let varying_id = self.write_varying(ir_module, class, name, member.ty, binding)?; list.push(varying_id); - ep_context.result_ids_typed.push((varying_id, type_id)); + ep_context.results.push(ResultMember { + id: varying_id, + type_id, + built_in: binding.to_built_in(), + }); } } else { unreachable!("Missing result binding on an entry point"); @@ -1900,16 +1934,7 @@ impl Writer { base } crate::Expression::AccessIndex { base, index } => { - let const_ty_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Sint, - width: 4, - pointer_class: None, - }), - )?; - let const_id = self.create_constant(const_ty_id, &[index]); + let const_id = self.get_index_constant(index, &ir_module.types)?; self.temp_chain.push(const_id); base } @@ -1958,6 +1983,77 @@ impl Writer { } } + fn write_entry_point_return( + &mut self, + value_id: Word, + ir_result: &crate::FunctionResult, + type_arena: &Arena, + result_members: &[ResultMember], + body: &mut Vec, + ) -> Result<(), Error> { + for (index, res_member) in result_members.iter().enumerate() { + let member_value_id = match ir_result.binding { + Some(_) => value_id, + None => { + let member_value_id = self.id_gen.next(); + body.push(Instruction::composite_extract( + res_member.type_id, + member_value_id, + value_id, + &[index as u32], + )); + member_value_id + } + }; + + body.push(Instruction::store(res_member.id, member_value_id, None)); + + // Flip Y coordinate to adjust for coordinate space difference + // between SPIR-V and our IR. + if res_member.built_in == Some(crate::BuiltIn::Position) { + let access_id = self.id_gen.next(); + let float_ptr_type_id = self.get_type_id( + type_arena, + LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: Some(spirv::StorageClass::Output), + }), + )?; + let index_y_id = self.get_index_constant(1, type_arena)?; + body.push(Instruction::access_chain( + float_ptr_type_id, + access_id, + res_member.id, + &[index_y_id], + )); + + let load_id = self.id_gen.next(); + let float_type_id = self.get_type_id( + type_arena, + LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }), + )?; + body.push(Instruction::load(float_type_id, load_id, access_id, None)); + + let neg_id = self.id_gen.next(); + body.push(Instruction::unary( + spirv::Op::FNegate, + float_type_id, + neg_id, + load_id, + )); + body.push(Instruction::store(access_id, neg_id, None)); + } + } + Ok(()) + } + //TODO: put most of these into a `BlockContext` structure! #[allow(clippy::too_many_arguments)] fn write_block( @@ -2193,30 +2289,13 @@ impl Writer { // If this is an entry point, and we need to return anything, // let's instead store the output variables and return `void`. Some(ref context) => { - let result = ir_function.result.as_ref().unwrap(); - if result.binding.is_none() { - for (index, &(varying_id, type_id)) in - context.result_ids_typed.iter().enumerate() - { - let member_value_id = self.id_gen.next(); - block.body.push(Instruction::composite_extract( - type_id, - member_value_id, - value_id, - &[index as u32], - )); - block.body.push(Instruction::store( - varying_id, - member_value_id, - None, - )); - } - } else { - let (varying_id, _) = context.result_ids_typed[0]; - block - .body - .push(Instruction::store(varying_id, value_id, None)); - }; + self.write_entry_point_return( + value_id, + ir_function.result.as_ref().unwrap(), + &ir_module.types, + &context.results, + &mut block.body, + )?; Instruction::return_void() } None => Instruction::return_value(value_id), diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c0d1e74a2..2bb277c70 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -174,3 +174,12 @@ impl crate::Constant { } } } + +impl crate::Binding { + pub fn to_built_in(&self) -> Option { + match *self { + Self::BuiltIn(bi) => Some(bi), + Self::Location(..) => None, + } + } +} diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index ef0b768a0..f6c3487d2 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -5,13 +5,13 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 61 +; Bound: 66 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %28 "main" %19 %22 %24 %26 -OpEntryPoint Fragment %47 "main" %44 %46 -OpExecutionMode %47 OriginUpperLeft +OpEntryPoint Fragment %52 "main" %49 %51 +OpExecutionMode %52 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" OpName %9 "VertexOutput" @@ -26,9 +26,9 @@ OpName %24 "uv" OpName %26 "position" OpName %28 "main" OpName %28 "main" -OpName %44 "uv" -OpName %47 "main" -OpName %47 "main" +OpName %49 "uv" +OpName %52 "main" +OpName %52 "main" OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 16 OpDecorate %12 DescriptorSet 0 @@ -39,8 +39,8 @@ OpDecorate %19 Location 0 OpDecorate %22 Location 1 OpDecorate %24 Location 0 OpDecorate %26 BuiltIn Position -OpDecorate %44 Location 0 -OpDecorate %46 Location 0 +OpDecorate %49 Location 0 +OpDecorate %51 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.2 @@ -69,10 +69,12 @@ OpDecorate %46 Location 0 %33 = OpConstant %32 0 %35 = OpTypePointer Function %8 %38 = OpConstant %32 1 -%44 = OpVariable %20 Input -%46 = OpVariable %27 Output -%51 = OpTypeSampledImage %10 -%55 = OpTypeBool +%44 = OpTypePointer Output %4 +%45 = OpConstant %32 1 +%49 = OpVariable %20 Input +%51 = OpVariable %27 Output +%56 = OpTypeSampledImage %10 +%60 = OpTypeBool %28 = OpFunction %2 None %29 %18 = OpLabel %16 = OpVariable %17 Function @@ -91,26 +93,30 @@ OpStore %39 %37 OpStore %24 %41 %42 = OpCompositeExtract %8 %40 1 OpStore %26 %42 +%43 = OpAccessChain %44 %26 %45 +%46 = OpLoad %4 %43 +%47 = OpFNegate %4 %46 +OpStore %43 %47 OpReturn OpFunctionEnd -%47 = OpFunction %2 None %29 -%43 = OpLabel -%45 = OpLoad %7 %44 -%48 = OpLoad %10 %12 -%49 = OpLoad %11 %14 -OpBranch %50 -%50 = OpLabel -%52 = OpSampledImage %51 %48 %49 -%53 = OpImageSampleImplicitLod %8 %52 %45 -%54 = OpCompositeExtract %4 %53 3 -%56 = OpFOrdEqual %55 %54 %5 -OpSelectionMerge %57 None -OpBranchConditional %56 %58 %57 -%58 = OpLabel +%52 = OpFunction %2 None %29 +%48 = OpLabel +%50 = OpLoad %7 %49 +%53 = OpLoad %10 %12 +%54 = OpLoad %11 %14 +OpBranch %55 +%55 = OpLabel +%57 = OpSampledImage %56 %53 %54 +%58 = OpImageSampleImplicitLod %8 %57 %50 +%59 = OpCompositeExtract %4 %58 3 +%61 = OpFOrdEqual %60 %59 %5 +OpSelectionMerge %62 None +OpBranchConditional %61 %63 %62 +%63 = OpLabel OpKill -%57 = OpLabel -%59 = OpCompositeExtract %4 %53 3 -%60 = OpVectorTimesScalar %8 %53 %59 -OpStore %46 %60 +%62 = OpLabel +%64 = OpCompositeExtract %4 %58 3 +%65 = OpVectorTimesScalar %8 %58 %64 +OpStore %51 %65 OpReturn OpFunctionEnd diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index 112aacac5..c7b1d7d25 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -5,13 +5,13 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 116 +; Bound: 121 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %38 "vs_main" %31 %34 %36 -OpEntryPoint Fragment %108 "fs_main" %101 %104 %107 -OpExecutionMode %108 OriginUpperLeft +OpEntryPoint Fragment %113 "fs_main" %106 %109 %112 +OpExecutionMode %113 OriginUpperLeft OpSource GLSL 450 OpName %12 "VertexOutput" OpMemberName %12 0 "position" @@ -30,10 +30,10 @@ OpName %34 "position" OpName %36 "uv" OpName %38 "vs_main" OpName %38 "vs_main" -OpName %101 "position" -OpName %104 "uv" -OpName %108 "fs_main" -OpName %108 "fs_main" +OpName %106 "position" +OpName %109 "uv" +OpName %113 "fs_main" +OpName %113 "fs_main" OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpDecorate %14 Block @@ -52,9 +52,9 @@ OpDecorate %23 Binding 2 OpDecorate %31 BuiltIn VertexIndex OpDecorate %34 BuiltIn Position OpDecorate %36 Location 0 -OpDecorate %101 BuiltIn FragCoord -OpDecorate %104 Location 0 -OpDecorate %107 Location 0 +OpDecorate %106 BuiltIn FragCoord +OpDecorate %109 Location 0 +OpDecorate %112 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -96,12 +96,14 @@ OpDecorate %107 Location 0 %91 = OpConstant %4 1 %93 = OpTypePointer Function %10 %94 = OpConstant %4 0 -%102 = OpTypePointer Input %10 -%101 = OpVariable %102 Input -%105 = OpTypePointer Input %11 -%104 = OpVariable %105 Input -%107 = OpVariable %35 Output -%113 = OpTypeSampledImage %17 +%99 = OpTypePointer Output %7 +%100 = OpConstant %4 1 +%107 = OpTypePointer Input %10 +%106 = OpVariable %107 Input +%110 = OpTypePointer Input %11 +%109 = OpVariable %110 Input +%112 = OpVariable %35 Output +%118 = OpTypeSampledImage %17 %38 = OpFunction %2 None %39 %30 = OpLabel %25 = OpVariable %26 Function @@ -163,22 +165,26 @@ OpStore %95 %53 %96 = OpLoad %12 %28 %97 = OpCompositeExtract %10 %96 0 OpStore %34 %97 -%98 = OpCompositeExtract %11 %96 1 -OpStore %36 %98 +%98 = OpAccessChain %99 %34 %100 +%101 = OpLoad %7 %98 +%102 = OpFNegate %7 %101 +OpStore %98 %102 +%103 = OpCompositeExtract %11 %96 1 +OpStore %36 %103 OpReturn OpFunctionEnd -%108 = OpFunction %2 None %39 -%99 = OpLabel -%103 = OpLoad %10 %101 -%106 = OpLoad %11 %104 -%100 = OpCompositeConstruct %12 %103 %106 -%109 = OpLoad %17 %21 -%110 = OpLoad %18 %23 -OpBranch %111 -%111 = OpLabel -%112 = OpCompositeExtract %11 %100 1 -%114 = OpSampledImage %113 %109 %110 -%115 = OpImageSampleImplicitLod %10 %114 %112 -OpStore %107 %115 +%113 = OpFunction %2 None %39 +%104 = OpLabel +%108 = OpLoad %10 %106 +%111 = OpLoad %11 %109 +%105 = OpCompositeConstruct %12 %108 %111 +%114 = OpLoad %17 %21 +%115 = OpLoad %18 %23 +OpBranch %116 +%116 = OpLabel +%117 = OpCompositeExtract %11 %105 1 +%119 = OpSampledImage %118 %114 %115 +%120 = OpImageSampleImplicitLod %10 %119 %117 +OpStore %112 %120 OpReturn OpFunctionEnd From 100c2f42ed47906153c91c05086f29c92a6de646 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Apr 2021 23:21:46 -0400 Subject: [PATCH 0656/2212] [spv-out] cache access index constants --- src/back/spv/writer.rs | 71 ++++-- tests/out/boids.spvasm.snap | 422 ++++++++++++++++------------------ tests/out/collatz.spvasm.snap | 7 +- tests/out/quad.spvasm.snap | 69 +++--- tests/out/shadow.spvasm.snap | 73 +++--- tests/out/skybox.spvasm.snap | 160 +++++++------ 6 files changed, 405 insertions(+), 397 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 94b7ab2e1..f4c7d404a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -11,6 +11,7 @@ use std::{collections::hash_map::Entry, ops}; use thiserror::Error; const BITS_PER_BYTE: crate::Bytes = 8; +const CACHED_CONSTANT_INDICES: usize = 8; #[derive(Clone, Debug, Error)] pub enum Error { @@ -269,7 +270,8 @@ pub struct Writer { lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, lookup_function_call: crate::FastHashMap, Word>, - lookup_constant: crate::FastHashMap, Word>, + constant_ids: Vec, + index_constant_ids: Vec, global_variables: Vec, cached: CachedExpressions, gl450_ext_inst_id: Word, @@ -300,7 +302,8 @@ impl Writer { lookup_function: crate::FastHashMap::default(), lookup_function_type: crate::FastHashMap::default(), lookup_function_call: crate::FastHashMap::default(), - lookup_constant: crate::FastHashMap::default(), + constant_ids: Vec::new(), + index_constant_ids: Vec::new(), global_variables: Vec::new(), cached: CachedExpressions::default(), gl450_ext_inst_id, @@ -372,6 +375,14 @@ impl Writer { index: Word, types: &Arena, ) -> Result { + while self.index_constant_ids.len() <= index as usize { + self.index_constant_ids.push(0); + } + let cached = self.index_constant_ids[index as usize]; + if cached != 0 { + return Ok(cached); + } + let type_id = self.get_type_id( types, LookupType::Local(LocalType::Value { @@ -381,8 +392,10 @@ impl Writer { pointer_class: None, }), )?; - //TODO: cache this - Ok(self.create_constant(type_id, &[index])) + + let id = self.create_constant(type_id, &[index]); + self.index_constant_ids[index as usize] = id; + Ok(id) } fn write_function( @@ -405,7 +418,7 @@ impl Writer { let init_word = variable .init - .map(|constant| self.lookup_constant[&constant]); + .map(|constant| self.constant_ids[constant.index()]); let pointer_type_id = self.get_pointer_id(&ir_module.types, variable.ty, spirv::StorageClass::Function)?; let instruction = Instruction::variable( @@ -841,7 +854,7 @@ impl Writer { let type_id = self.get_type_id(arena, LookupType::Handle(base))?; match size { crate::ArraySize::Constant(const_handle) => { - let length_id = self.lookup_constant[&const_handle]; + let length_id = self.constant_ids[const_handle.index()]; Instruction::type_array(id, type_id, length_id) } crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), @@ -935,8 +948,14 @@ impl Writer { id: Word, value: &crate::ScalarValue, width: crate::Bytes, + debug_name: Option<&String>, types: &Arena, ) -> Result<(), Error> { + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(name) = debug_name { + self.debugs.push(Instruction::name(id, name)); + } + } let type_id = self.get_type_id( types, LookupType::Local(LocalType::Value { @@ -951,6 +970,17 @@ impl Writer { crate::ScalarValue::Sint(val) => { let words = match width { 4 => { + if debug_name.is_none() + && 0 <= val + && val < CACHED_CONSTANT_INDICES as i64 + && self.index_constant_ids.get(val as usize).unwrap_or(&0) == &0 + { + // cache this as an indexing constant + while self.index_constant_ids.len() <= val as usize { + self.index_constant_ids.push(0); + } + self.index_constant_ids[val as usize] = id; + } solo = [val as u32]; &solo[..] } @@ -1008,7 +1038,7 @@ impl Writer { ) -> Result<(), Error> { let mut constituent_ids = Vec::with_capacity(components.len()); for constituent in components.iter() { - let constituent_id = self.lookup_constant[constituent]; + let constituent_id = self.constant_ids[constituent.index()]; constituent_ids.push(constituent_id); } @@ -1109,7 +1139,7 @@ impl Writer { let init_word = global_variable .init - .map(|constant| self.lookup_constant[&constant]); + .map(|constant| self.constant_ids[constant.index()]); let pointer_type_id = self.get_pointer_id(&ir_module.types, global_variable.ty, class)?; let instruction = Instruction::variable(pointer_type_id, id, class, init_word); @@ -1345,7 +1375,7 @@ impl Writer { } } crate::Expression::GlobalVariable(handle) => self.global_variables[handle.index()].id, - crate::Expression::Constant(handle) => self.lookup_constant[&handle], + crate::Expression::Constant(handle) => self.constant_ids[handle.index()], crate::Expression::Compose { ty: _, ref components, @@ -1794,6 +1824,7 @@ impl Writer { zero_id, &crate::ScalarValue::Float(0.0), 4, + None, &ir_module.types, )?; inst.add_operand(spirv::ImageOperands::LOD.bits()); @@ -1862,7 +1893,7 @@ impl Writer { }; if let Some(offset_const) = offset { - let offset_id = self.lookup_constant[&offset_const]; + let offset_id = self.constant_ids[offset_const.index()]; main_instruction.add_operand(spirv::ImageOperands::CONST_OFFSET.bits()); main_instruction.add_operand(offset_id); } @@ -2419,19 +2450,22 @@ impl Writer { .push(Instruction::source(spirv::SourceLanguage::GLSL, 450)); } + self.constant_ids.clear(); + self.constant_ids.resize(ir_module.constants.len(), 0); // first, output all the scalar constants for (handle, constant) in ir_module.constants.iter() { match constant.inner { crate::ConstantInner::Composite { .. } => continue, crate::ConstantInner::Scalar { width, ref value } => { let id = self.id_gen.next(); - self.lookup_constant.insert(handle, id); - if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = constant.name { - self.debugs.push(Instruction::name(id, name)); - } - } - self.write_constant_scalar(id, value, width, &ir_module.types)?; + self.constant_ids[handle.index()] = id; + self.write_constant_scalar( + id, + value, + width, + constant.name.as_ref(), + &ir_module.types, + )?; } } } @@ -2447,7 +2481,7 @@ impl Writer { crate::ConstantInner::Scalar { .. } => continue, crate::ConstantInner::Composite { ty, ref components } => { let id = self.id_gen.next(); - self.lookup_constant.insert(handle, id); + self.constant_ids[handle.index()] = id; if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = constant.name { self.debugs.push(Instruction::name(id, name)); @@ -2457,6 +2491,7 @@ impl Writer { } } } + debug_assert_eq!(self.constant_ids.iter().position(|&id| id == 0), None); // now write all globals self.global_variables.clear(); diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap index 41e343a60..ded452eae 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm.snap @@ -5,7 +5,7 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 221 +; Bound: 203 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" @@ -98,31 +98,13 @@ OpDecorate %40 BuiltIn GlobalInvocationId %51 = OpTypePointer StorageBuffer %18 %52 = OpTypePointer StorageBuffer %16 %53 = OpTypePointer StorageBuffer %15 -%54 = OpConstant %8 0 -%55 = OpConstant %8 0 -%58 = OpConstant %8 1 -%59 = OpConstant %8 0 -%78 = OpConstant %8 0 -%79 = OpConstant %8 0 -%83 = OpConstant %8 1 -%84 = OpConstant %8 0 -%90 = OpTypePointer Uniform %6 -%91 = OpConstant %8 1 -%105 = OpConstant %8 2 -%119 = OpConstant %8 3 -%154 = OpConstant %8 4 -%160 = OpConstant %8 5 -%166 = OpConstant %8 6 -%179 = OpConstant %8 0 -%189 = OpTypePointer Function %6 -%190 = OpConstant %8 0 -%197 = OpConstant %8 0 -%204 = OpConstant %8 1 -%211 = OpConstant %8 1 -%214 = OpConstant %8 0 -%215 = OpConstant %8 0 -%218 = OpConstant %8 1 -%219 = OpConstant %8 0 +%82 = OpTypePointer Uniform %6 +%96 = OpConstant %8 2 +%110 = OpConstant %8 3 +%145 = OpConstant %8 4 +%151 = OpConstant %8 5 +%157 = OpConstant %8 6 +%179 = OpTypePointer Function %6 %43 = OpFunction %2 None %44 %39 = OpLabel %37 = OpVariable %38 Function %9 @@ -145,209 +127,209 @@ OpBranchConditional %48 %50 %49 %50 = OpLabel OpReturn %49 = OpLabel -%56 = OpAccessChain %53 %23 %55 %46 %54 +%54 = OpAccessChain %53 %23 %7 %46 %7 +%55 = OpLoad %15 %54 +OpStore %26 %55 +%56 = OpAccessChain %53 %23 %7 %46 %10 %57 = OpLoad %15 %56 -OpStore %26 %57 -%60 = OpAccessChain %53 %23 %59 %46 %58 -%61 = OpLoad %15 %60 -OpStore %28 %61 -%62 = OpCompositeConstruct %15 %5 %5 -OpStore %29 %62 -%63 = OpCompositeConstruct %15 %5 %5 -OpStore %30 %63 -%64 = OpCompositeConstruct %15 %5 %5 -OpStore %31 %64 -OpBranch %65 -%65 = OpLabel -OpLoopMerge %66 %68 None -OpBranch %67 +OpStore %28 %57 +%58 = OpCompositeConstruct %15 %5 %5 +OpStore %29 %58 +%59 = OpCompositeConstruct %15 %5 %5 +OpStore %30 %59 +%60 = OpCompositeConstruct %15 %5 %5 +OpStore %31 %60 +OpBranch %61 +%61 = OpLabel +OpLoopMerge %62 %64 None +OpBranch %63 +%63 = OpLabel +%65 = OpLoad %4 %37 +%66 = OpUGreaterThanEqual %47 %65 %3 +OpSelectionMerge %67 None +OpBranchConditional %66 %68 %67 +%68 = OpLabel +OpBranch %62 %67 = OpLabel %69 = OpLoad %4 %37 -%70 = OpUGreaterThanEqual %47 %69 %3 +%70 = OpIEqual %47 %69 %46 OpSelectionMerge %71 None OpBranchConditional %70 %72 %71 %72 = OpLabel -OpBranch %66 +OpBranch %64 %71 = OpLabel %73 = OpLoad %4 %37 -%74 = OpIEqual %47 %73 %46 -OpSelectionMerge %75 None -OpBranchConditional %74 %76 %75 -%76 = OpLabel -OpBranch %68 -%75 = OpLabel -%77 = OpLoad %4 %37 -%80 = OpAccessChain %53 %23 %79 %77 %78 -%81 = OpLoad %15 %80 -OpStore %35 %81 -%82 = OpLoad %4 %37 -%85 = OpAccessChain %53 %23 %84 %82 %83 -%86 = OpLoad %15 %85 -OpStore %36 %86 -%87 = OpLoad %15 %35 -%88 = OpLoad %15 %26 -%89 = OpExtInst %6 %1 Distance %87 %88 -%92 = OpAccessChain %90 %21 %91 -%93 = OpLoad %6 %92 -%94 = OpFOrdLessThan %47 %89 %93 -OpSelectionMerge %95 None -OpBranchConditional %94 %96 %95 -%96 = OpLabel -%97 = OpLoad %15 %29 -%98 = OpLoad %15 %35 -%99 = OpFAdd %15 %97 %98 -OpStore %29 %99 -%100 = OpLoad %8 %32 -%101 = OpIAdd %8 %100 %10 -OpStore %32 %101 -OpBranch %95 -%95 = OpLabel -%102 = OpLoad %15 %35 -%103 = OpLoad %15 %26 -%104 = OpExtInst %6 %1 Distance %102 %103 -%106 = OpAccessChain %90 %21 %105 -%107 = OpLoad %6 %106 -%108 = OpFOrdLessThan %47 %104 %107 -OpSelectionMerge %109 None -OpBranchConditional %108 %110 %109 -%110 = OpLabel -%111 = OpLoad %15 %31 -%112 = OpLoad %15 %35 -%113 = OpLoad %15 %26 -%114 = OpFSub %15 %112 %113 -%115 = OpFSub %15 %111 %114 -OpStore %31 %115 -OpBranch %109 -%109 = OpLabel -%116 = OpLoad %15 %35 -%117 = OpLoad %15 %26 -%118 = OpExtInst %6 %1 Distance %116 %117 -%120 = OpAccessChain %90 %21 %119 -%121 = OpLoad %6 %120 -%122 = OpFOrdLessThan %47 %118 %121 -OpSelectionMerge %123 None -OpBranchConditional %122 %124 %123 -%124 = OpLabel -%125 = OpLoad %15 %30 -%126 = OpLoad %15 %36 -%127 = OpFAdd %15 %125 %126 -OpStore %30 %127 -%128 = OpLoad %8 %34 -%129 = OpIAdd %8 %128 %10 -OpStore %34 %129 -OpBranch %123 -%123 = OpLabel -OpBranch %68 -%68 = OpLabel -%130 = OpLoad %4 %37 -%131 = OpIAdd %4 %130 %11 -OpStore %37 %131 -OpBranch %65 -%66 = OpLabel -%132 = OpLoad %8 %32 -%133 = OpSGreaterThan %47 %132 %7 -OpSelectionMerge %134 None -OpBranchConditional %133 %135 %134 -%135 = OpLabel -%136 = OpLoad %15 %29 -%137 = OpLoad %8 %32 -%138 = OpConvertSToF %6 %137 -%139 = OpFDiv %6 %12 %138 -%140 = OpVectorTimesScalar %15 %136 %139 -%141 = OpLoad %15 %26 -%142 = OpFSub %15 %140 %141 -OpStore %29 %142 -OpBranch %134 -%134 = OpLabel -%143 = OpLoad %8 %34 -%144 = OpSGreaterThan %47 %143 %7 -OpSelectionMerge %145 None -OpBranchConditional %144 %146 %145 -%146 = OpLabel -%147 = OpLoad %15 %30 -%148 = OpLoad %8 %34 -%149 = OpConvertSToF %6 %148 -%150 = OpFDiv %6 %12 %149 -%151 = OpVectorTimesScalar %15 %147 %150 -OpStore %30 %151 -OpBranch %145 -%145 = OpLabel -%152 = OpLoad %15 %28 -%153 = OpLoad %15 %29 -%155 = OpAccessChain %90 %21 %154 -%156 = OpLoad %6 %155 -%157 = OpVectorTimesScalar %15 %153 %156 -%158 = OpFAdd %15 %152 %157 -%159 = OpLoad %15 %31 -%161 = OpAccessChain %90 %21 %160 -%162 = OpLoad %6 %161 -%163 = OpVectorTimesScalar %15 %159 %162 -%164 = OpFAdd %15 %158 %163 -%165 = OpLoad %15 %30 -%167 = OpAccessChain %90 %21 %166 -%168 = OpLoad %6 %167 -%169 = OpVectorTimesScalar %15 %165 %168 -%170 = OpFAdd %15 %164 %169 -OpStore %28 %170 -%171 = OpLoad %15 %28 -%172 = OpExtInst %15 %1 Normalize %171 -%173 = OpLoad %15 %28 -%174 = OpExtInst %6 %1 Length %173 -%175 = OpExtInst %6 %1 FClamp %174 %5 %13 -%176 = OpVectorTimesScalar %15 %172 %175 -OpStore %28 %176 -%177 = OpLoad %15 %26 -%178 = OpLoad %15 %28 -%180 = OpAccessChain %90 %21 %179 -%181 = OpLoad %6 %180 -%182 = OpVectorTimesScalar %15 %178 %181 -%183 = OpFAdd %15 %177 %182 -OpStore %26 %183 -%184 = OpLoad %15 %26 -%185 = OpCompositeExtract %6 %184 0 -%186 = OpFOrdLessThan %47 %185 %14 -OpSelectionMerge %187 None -OpBranchConditional %186 %188 %187 -%188 = OpLabel -%191 = OpAccessChain %189 %26 %190 -OpStore %191 %12 -OpBranch %187 -%187 = OpLabel -%192 = OpLoad %15 %26 -%193 = OpCompositeExtract %6 %192 0 -%194 = OpFOrdGreaterThan %47 %193 %12 -OpSelectionMerge %195 None -OpBranchConditional %194 %196 %195 -%196 = OpLabel -%198 = OpAccessChain %189 %26 %197 +%74 = OpAccessChain %53 %23 %7 %73 %7 +%75 = OpLoad %15 %74 +OpStore %35 %75 +%76 = OpLoad %4 %37 +%77 = OpAccessChain %53 %23 %7 %76 %10 +%78 = OpLoad %15 %77 +OpStore %36 %78 +%79 = OpLoad %15 %35 +%80 = OpLoad %15 %26 +%81 = OpExtInst %6 %1 Distance %79 %80 +%83 = OpAccessChain %82 %21 %10 +%84 = OpLoad %6 %83 +%85 = OpFOrdLessThan %47 %81 %84 +OpSelectionMerge %86 None +OpBranchConditional %85 %87 %86 +%87 = OpLabel +%88 = OpLoad %15 %29 +%89 = OpLoad %15 %35 +%90 = OpFAdd %15 %88 %89 +OpStore %29 %90 +%91 = OpLoad %8 %32 +%92 = OpIAdd %8 %91 %10 +OpStore %32 %92 +OpBranch %86 +%86 = OpLabel +%93 = OpLoad %15 %35 +%94 = OpLoad %15 %26 +%95 = OpExtInst %6 %1 Distance %93 %94 +%97 = OpAccessChain %82 %21 %96 +%98 = OpLoad %6 %97 +%99 = OpFOrdLessThan %47 %95 %98 +OpSelectionMerge %100 None +OpBranchConditional %99 %101 %100 +%101 = OpLabel +%102 = OpLoad %15 %31 +%103 = OpLoad %15 %35 +%104 = OpLoad %15 %26 +%105 = OpFSub %15 %103 %104 +%106 = OpFSub %15 %102 %105 +OpStore %31 %106 +OpBranch %100 +%100 = OpLabel +%107 = OpLoad %15 %35 +%108 = OpLoad %15 %26 +%109 = OpExtInst %6 %1 Distance %107 %108 +%111 = OpAccessChain %82 %21 %110 +%112 = OpLoad %6 %111 +%113 = OpFOrdLessThan %47 %109 %112 +OpSelectionMerge %114 None +OpBranchConditional %113 %115 %114 +%115 = OpLabel +%116 = OpLoad %15 %30 +%117 = OpLoad %15 %36 +%118 = OpFAdd %15 %116 %117 +OpStore %30 %118 +%119 = OpLoad %8 %34 +%120 = OpIAdd %8 %119 %10 +OpStore %34 %120 +OpBranch %114 +%114 = OpLabel +OpBranch %64 +%64 = OpLabel +%121 = OpLoad %4 %37 +%122 = OpIAdd %4 %121 %11 +OpStore %37 %122 +OpBranch %61 +%62 = OpLabel +%123 = OpLoad %8 %32 +%124 = OpSGreaterThan %47 %123 %7 +OpSelectionMerge %125 None +OpBranchConditional %124 %126 %125 +%126 = OpLabel +%127 = OpLoad %15 %29 +%128 = OpLoad %8 %32 +%129 = OpConvertSToF %6 %128 +%130 = OpFDiv %6 %12 %129 +%131 = OpVectorTimesScalar %15 %127 %130 +%132 = OpLoad %15 %26 +%133 = OpFSub %15 %131 %132 +OpStore %29 %133 +OpBranch %125 +%125 = OpLabel +%134 = OpLoad %8 %34 +%135 = OpSGreaterThan %47 %134 %7 +OpSelectionMerge %136 None +OpBranchConditional %135 %137 %136 +%137 = OpLabel +%138 = OpLoad %15 %30 +%139 = OpLoad %8 %34 +%140 = OpConvertSToF %6 %139 +%141 = OpFDiv %6 %12 %140 +%142 = OpVectorTimesScalar %15 %138 %141 +OpStore %30 %142 +OpBranch %136 +%136 = OpLabel +%143 = OpLoad %15 %28 +%144 = OpLoad %15 %29 +%146 = OpAccessChain %82 %21 %145 +%147 = OpLoad %6 %146 +%148 = OpVectorTimesScalar %15 %144 %147 +%149 = OpFAdd %15 %143 %148 +%150 = OpLoad %15 %31 +%152 = OpAccessChain %82 %21 %151 +%153 = OpLoad %6 %152 +%154 = OpVectorTimesScalar %15 %150 %153 +%155 = OpFAdd %15 %149 %154 +%156 = OpLoad %15 %30 +%158 = OpAccessChain %82 %21 %157 +%159 = OpLoad %6 %158 +%160 = OpVectorTimesScalar %15 %156 %159 +%161 = OpFAdd %15 %155 %160 +OpStore %28 %161 +%162 = OpLoad %15 %28 +%163 = OpExtInst %15 %1 Normalize %162 +%164 = OpLoad %15 %28 +%165 = OpExtInst %6 %1 Length %164 +%166 = OpExtInst %6 %1 FClamp %165 %5 %13 +%167 = OpVectorTimesScalar %15 %163 %166 +OpStore %28 %167 +%168 = OpLoad %15 %26 +%169 = OpLoad %15 %28 +%170 = OpAccessChain %82 %21 %7 +%171 = OpLoad %6 %170 +%172 = OpVectorTimesScalar %15 %169 %171 +%173 = OpFAdd %15 %168 %172 +OpStore %26 %173 +%174 = OpLoad %15 %26 +%175 = OpCompositeExtract %6 %174 0 +%176 = OpFOrdLessThan %47 %175 %14 +OpSelectionMerge %177 None +OpBranchConditional %176 %178 %177 +%178 = OpLabel +%180 = OpAccessChain %179 %26 %7 +OpStore %180 %12 +OpBranch %177 +%177 = OpLabel +%181 = OpLoad %15 %26 +%182 = OpCompositeExtract %6 %181 0 +%183 = OpFOrdGreaterThan %47 %182 %12 +OpSelectionMerge %184 None +OpBranchConditional %183 %185 %184 +%185 = OpLabel +%186 = OpAccessChain %179 %26 %7 +OpStore %186 %14 +OpBranch %184 +%184 = OpLabel +%187 = OpLoad %15 %26 +%188 = OpCompositeExtract %6 %187 1 +%189 = OpFOrdLessThan %47 %188 %14 +OpSelectionMerge %190 None +OpBranchConditional %189 %191 %190 +%191 = OpLabel +%192 = OpAccessChain %179 %26 %10 +OpStore %192 %12 +OpBranch %190 +%190 = OpLabel +%193 = OpLoad %15 %26 +%194 = OpCompositeExtract %6 %193 1 +%195 = OpFOrdGreaterThan %47 %194 %12 +OpSelectionMerge %196 None +OpBranchConditional %195 %197 %196 +%197 = OpLabel +%198 = OpAccessChain %179 %26 %10 OpStore %198 %14 -OpBranch %195 -%195 = OpLabel +OpBranch %196 +%196 = OpLabel %199 = OpLoad %15 %26 -%200 = OpCompositeExtract %6 %199 1 -%201 = OpFOrdLessThan %47 %200 %14 -OpSelectionMerge %202 None -OpBranchConditional %201 %203 %202 -%203 = OpLabel -%205 = OpAccessChain %189 %26 %204 -OpStore %205 %12 -OpBranch %202 -%202 = OpLabel -%206 = OpLoad %15 %26 -%207 = OpCompositeExtract %6 %206 1 -%208 = OpFOrdGreaterThan %47 %207 %12 -OpSelectionMerge %209 None -OpBranchConditional %208 %210 %209 -%210 = OpLabel -%212 = OpAccessChain %189 %26 %211 -OpStore %212 %14 -OpBranch %209 -%209 = OpLabel -%213 = OpLoad %15 %26 -%216 = OpAccessChain %53 %25 %215 %46 %214 -OpStore %216 %213 -%217 = OpLoad %15 %28 -%220 = OpAccessChain %53 %25 %219 %46 %218 -OpStore %220 %217 +%200 = OpAccessChain %53 %25 %7 %46 %7 +OpStore %200 %199 +%201 = OpLoad %15 %28 +%202 = OpAccessChain %53 %25 %7 %46 %10 +OpStore %202 %201 OpReturn OpFunctionEnd diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap index 472cebff2..9d56582b9 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm.snap @@ -5,7 +5,7 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 62 +; Bound: 61 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" @@ -49,7 +49,6 @@ OpDecorate %45 BuiltIn GlobalInvocationId %53 = OpTypePointer StorageBuffer %4 %55 = OpTypeInt 32 1 %56 = OpConstant %55 0 -%60 = OpConstant %55 0 %18 = OpFunction %4 None %19 %17 = OpFunctionParameter %4 %16 = OpLabel @@ -107,7 +106,7 @@ OpBranch %50 %57 = OpAccessChain %53 %11 %56 %54 %58 = OpLoad %4 %57 %59 = OpFunctionCall %4 %18 %58 -%61 = OpAccessChain %53 %11 %60 %52 -OpStore %61 %59 +%60 = OpAccessChain %53 %11 %56 %52 +OpStore %60 %59 OpReturn OpFunctionEnd diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap index f6c3487d2..800c4f612 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm.snap @@ -5,13 +5,13 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 66 +; Bound: 65 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %28 "main" %19 %22 %24 %26 -OpEntryPoint Fragment %52 "main" %49 %51 -OpExecutionMode %52 OriginUpperLeft +OpEntryPoint Fragment %51 "main" %48 %50 +OpExecutionMode %51 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" OpName %9 "VertexOutput" @@ -26,9 +26,9 @@ OpName %24 "uv" OpName %26 "position" OpName %28 "main" OpName %28 "main" -OpName %49 "uv" -OpName %52 "main" -OpName %52 "main" +OpName %48 "uv" +OpName %51 "main" +OpName %51 "main" OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 16 OpDecorate %12 DescriptorSet 0 @@ -39,8 +39,8 @@ OpDecorate %19 Location 0 OpDecorate %22 Location 1 OpDecorate %24 Location 0 OpDecorate %26 BuiltIn Position -OpDecorate %49 Location 0 -OpDecorate %51 Location 0 +OpDecorate %48 Location 0 +OpDecorate %50 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.2 @@ -70,11 +70,10 @@ OpDecorate %51 Location 0 %35 = OpTypePointer Function %8 %38 = OpConstant %32 1 %44 = OpTypePointer Output %4 -%45 = OpConstant %32 1 -%49 = OpVariable %20 Input -%51 = OpVariable %27 Output -%56 = OpTypeSampledImage %10 -%60 = OpTypeBool +%48 = OpVariable %20 Input +%50 = OpVariable %27 Output +%55 = OpTypeSampledImage %10 +%59 = OpTypeBool %28 = OpFunction %2 None %29 %18 = OpLabel %16 = OpVariable %17 Function @@ -93,30 +92,30 @@ OpStore %39 %37 OpStore %24 %41 %42 = OpCompositeExtract %8 %40 1 OpStore %26 %42 -%43 = OpAccessChain %44 %26 %45 -%46 = OpLoad %4 %43 -%47 = OpFNegate %4 %46 -OpStore %43 %47 +%43 = OpAccessChain %44 %26 %38 +%45 = OpLoad %4 %43 +%46 = OpFNegate %4 %45 +OpStore %43 %46 OpReturn OpFunctionEnd -%52 = OpFunction %2 None %29 -%48 = OpLabel -%50 = OpLoad %7 %49 -%53 = OpLoad %10 %12 -%54 = OpLoad %11 %14 -OpBranch %55 -%55 = OpLabel -%57 = OpSampledImage %56 %53 %54 -%58 = OpImageSampleImplicitLod %8 %57 %50 -%59 = OpCompositeExtract %4 %58 3 -%61 = OpFOrdEqual %60 %59 %5 -OpSelectionMerge %62 None -OpBranchConditional %61 %63 %62 -%63 = OpLabel -OpKill +%51 = OpFunction %2 None %29 +%47 = OpLabel +%49 = OpLoad %7 %48 +%52 = OpLoad %10 %12 +%53 = OpLoad %11 %14 +OpBranch %54 +%54 = OpLabel +%56 = OpSampledImage %55 %52 %53 +%57 = OpImageSampleImplicitLod %8 %56 %49 +%58 = OpCompositeExtract %4 %57 3 +%60 = OpFOrdEqual %59 %58 %5 +OpSelectionMerge %61 None +OpBranchConditional %60 %62 %61 %62 = OpLabel -%64 = OpCompositeExtract %4 %58 3 -%65 = OpVectorTimesScalar %8 %58 %64 -OpStore %51 %65 +OpKill +%61 = OpLabel +%63 = OpCompositeExtract %4 %57 3 +%64 = OpVectorTimesScalar %8 %57 %63 +OpStore %50 %64 OpReturn OpFunctionEnd diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap index cf78faaed..e478f288e 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm.snap @@ -5,7 +5,7 @@ expression: dis ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 137 +; Bound: 136 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" @@ -105,7 +105,6 @@ OpDecorate %79 Location 0 %93 = OpConstant %56 0 %101 = OpTypePointer StorageBuffer %18 %103 = OpTypePointer StorageBuffer %17 -%104 = OpConstant %56 0 %36 = OpFunction %4 None %37 %34 = OpFunctionParameter %10 %35 = OpFunctionParameter %16 @@ -170,44 +169,44 @@ OpBranchConditional %98 %100 %99 OpBranch %88 %99 = OpLabel %102 = OpLoad %10 %70 -%105 = OpAccessChain %103 %27 %104 %102 -%106 = OpLoad %17 %105 -%107 = OpLoad %10 %70 -%108 = OpCompositeExtract %15 %106 0 -%109 = OpMatrixTimesVector %16 %108 %78 -%110 = OpFunctionCall %4 %36 %107 %109 -%111 = OpCompositeExtract %16 %106 1 -%112 = OpCompositeExtract %4 %111 0 -%113 = OpCompositeExtract %4 %111 1 -%114 = OpCompositeExtract %4 %111 2 -%115 = OpCompositeConstruct %23 %112 %113 %114 -%116 = OpCompositeExtract %4 %78 0 -%117 = OpCompositeExtract %4 %78 1 -%118 = OpCompositeExtract %4 %78 2 -%119 = OpCompositeConstruct %23 %116 %117 %118 -%120 = OpFSub %23 %115 %119 -%121 = OpExtInst %23 %1 Normalize %120 -%122 = OpDot %4 %86 %121 -%123 = OpExtInst %4 %1 FMax %3 %122 -%124 = OpLoad %23 %68 -%125 = OpFMul %4 %110 %123 -%126 = OpCompositeExtract %16 %106 2 -%127 = OpCompositeExtract %4 %126 0 -%128 = OpCompositeExtract %4 %126 1 -%129 = OpCompositeExtract %4 %126 2 -%130 = OpCompositeConstruct %23 %127 %128 %129 -%131 = OpVectorTimesScalar %23 %130 %125 -%132 = OpFAdd %23 %124 %131 -OpStore %68 %132 +%104 = OpAccessChain %103 %27 %93 %102 +%105 = OpLoad %17 %104 +%106 = OpLoad %10 %70 +%107 = OpCompositeExtract %15 %105 0 +%108 = OpMatrixTimesVector %16 %107 %78 +%109 = OpFunctionCall %4 %36 %106 %108 +%110 = OpCompositeExtract %16 %105 1 +%111 = OpCompositeExtract %4 %110 0 +%112 = OpCompositeExtract %4 %110 1 +%113 = OpCompositeExtract %4 %110 2 +%114 = OpCompositeConstruct %23 %111 %112 %113 +%115 = OpCompositeExtract %4 %78 0 +%116 = OpCompositeExtract %4 %78 1 +%117 = OpCompositeExtract %4 %78 2 +%118 = OpCompositeConstruct %23 %115 %116 %117 +%119 = OpFSub %23 %114 %118 +%120 = OpExtInst %23 %1 Normalize %119 +%121 = OpDot %4 %86 %120 +%122 = OpExtInst %4 %1 FMax %3 %121 +%123 = OpLoad %23 %68 +%124 = OpFMul %4 %109 %122 +%125 = OpCompositeExtract %16 %105 2 +%126 = OpCompositeExtract %4 %125 0 +%127 = OpCompositeExtract %4 %125 1 +%128 = OpCompositeExtract %4 %125 2 +%129 = OpCompositeConstruct %23 %126 %127 %128 +%130 = OpVectorTimesScalar %23 %129 %124 +%131 = OpFAdd %23 %123 %130 +OpStore %68 %131 OpBranch %90 %90 = OpLabel -%133 = OpLoad %10 %70 -%134 = OpIAdd %10 %133 %12 -OpStore %70 %134 +%132 = OpLoad %10 %70 +%133 = OpIAdd %10 %132 %12 +OpStore %70 %133 OpBranch %87 %88 = OpLabel -%135 = OpLoad %23 %68 -%136 = OpCompositeConstruct %16 %135 %5 -OpStore %79 %136 +%134 = OpLoad %23 %68 +%135 = OpCompositeConstruct %16 %134 %5 +OpStore %79 %135 OpReturn OpFunctionEnd diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index c7b1d7d25..f05b6c18b 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -5,13 +5,13 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 121 +; Bound: 115 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %38 "vs_main" %31 %34 %36 -OpEntryPoint Fragment %113 "fs_main" %106 %109 %112 -OpExecutionMode %113 OriginUpperLeft +OpEntryPoint Fragment %107 "fs_main" %100 %103 %106 +OpExecutionMode %107 OriginUpperLeft OpSource GLSL 450 OpName %12 "VertexOutput" OpMemberName %12 0 "position" @@ -30,10 +30,10 @@ OpName %34 "position" OpName %36 "uv" OpName %38 "vs_main" OpName %38 "vs_main" -OpName %106 "position" -OpName %109 "uv" -OpName %113 "fs_main" -OpName %113 "fs_main" +OpName %100 "position" +OpName %103 "uv" +OpName %107 "fs_main" +OpName %107 "fs_main" OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpDecorate %14 Block @@ -52,9 +52,9 @@ OpDecorate %23 Binding 2 OpDecorate %31 BuiltIn VertexIndex OpDecorate %34 BuiltIn Position OpDecorate %36 Location 0 -OpDecorate %106 BuiltIn FragCoord -OpDecorate %109 Location 0 -OpDecorate %112 Location 0 +OpDecorate %100 BuiltIn FragCoord +OpDecorate %103 Location 0 +OpDecorate %106 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -88,22 +88,16 @@ OpDecorate %112 Location 0 %36 = OpVariable %37 Output %39 = OpTypeFunction %2 %54 = OpTypePointer Uniform %13 -%55 = OpConstant %4 1 -%63 = OpConstant %4 1 -%71 = OpConstant %4 1 -%81 = OpConstant %4 0 -%85 = OpTypePointer Function %11 -%91 = OpConstant %4 1 -%93 = OpTypePointer Function %10 -%94 = OpConstant %4 0 -%99 = OpTypePointer Output %7 -%100 = OpConstant %4 1 -%107 = OpTypePointer Input %10 -%106 = OpVariable %107 Input -%110 = OpTypePointer Input %11 -%109 = OpVariable %110 Input -%112 = OpVariable %35 Output -%118 = OpTypeSampledImage %17 +%78 = OpConstant %4 0 +%82 = OpTypePointer Function %11 +%89 = OpTypePointer Function %10 +%94 = OpTypePointer Output %7 +%101 = OpTypePointer Input %10 +%100 = OpVariable %101 Input +%104 = OpTypePointer Input %11 +%103 = OpVariable %104 Input +%106 = OpVariable %35 Output +%112 = OpTypeSampledImage %17 %38 = OpFunction %2 None %39 %30 = OpLabel %25 = OpVariable %26 Function @@ -127,64 +121,64 @@ OpStore %27 %44 %51 = OpFMul %7 %50 %6 %52 = OpFSub %7 %51 %8 %53 = OpCompositeConstruct %10 %48 %52 %9 %8 -%56 = OpAccessChain %54 %19 %55 -%57 = OpLoad %13 %56 -%58 = OpCompositeExtract %10 %57 0 -%59 = OpCompositeExtract %7 %58 0 -%60 = OpCompositeExtract %7 %58 1 -%61 = OpCompositeExtract %7 %58 2 -%62 = OpCompositeConstruct %11 %59 %60 %61 -%64 = OpAccessChain %54 %19 %63 -%65 = OpLoad %13 %64 -%66 = OpCompositeExtract %10 %65 1 -%67 = OpCompositeExtract %7 %66 0 -%68 = OpCompositeExtract %7 %66 1 -%69 = OpCompositeExtract %7 %66 2 -%70 = OpCompositeConstruct %11 %67 %68 %69 -%72 = OpAccessChain %54 %19 %71 -%73 = OpLoad %13 %72 -%74 = OpCompositeExtract %10 %73 2 -%75 = OpCompositeExtract %7 %74 0 -%76 = OpCompositeExtract %7 %74 1 -%77 = OpCompositeExtract %7 %74 2 -%78 = OpCompositeConstruct %11 %75 %76 %77 -%79 = OpCompositeConstruct %16 %62 %70 %78 -%80 = OpTranspose %16 %79 -%82 = OpAccessChain %54 %19 %81 -%83 = OpLoad %13 %82 -%84 = OpMatrixTimesVector %10 %83 %53 -%86 = OpCompositeExtract %7 %84 0 -%87 = OpCompositeExtract %7 %84 1 -%88 = OpCompositeExtract %7 %84 2 -%89 = OpCompositeConstruct %11 %86 %87 %88 -%90 = OpMatrixTimesVector %11 %80 %89 -%92 = OpAccessChain %85 %28 %91 -OpStore %92 %90 -%95 = OpAccessChain %93 %28 %94 -OpStore %95 %53 -%96 = OpLoad %12 %28 -%97 = OpCompositeExtract %10 %96 0 -OpStore %34 %97 -%98 = OpAccessChain %99 %34 %100 -%101 = OpLoad %7 %98 -%102 = OpFNegate %7 %101 -OpStore %98 %102 -%103 = OpCompositeExtract %11 %96 1 -OpStore %36 %103 +%55 = OpAccessChain %54 %19 %5 +%56 = OpLoad %13 %55 +%57 = OpCompositeExtract %10 %56 0 +%58 = OpCompositeExtract %7 %57 0 +%59 = OpCompositeExtract %7 %57 1 +%60 = OpCompositeExtract %7 %57 2 +%61 = OpCompositeConstruct %11 %58 %59 %60 +%62 = OpAccessChain %54 %19 %5 +%63 = OpLoad %13 %62 +%64 = OpCompositeExtract %10 %63 1 +%65 = OpCompositeExtract %7 %64 0 +%66 = OpCompositeExtract %7 %64 1 +%67 = OpCompositeExtract %7 %64 2 +%68 = OpCompositeConstruct %11 %65 %66 %67 +%69 = OpAccessChain %54 %19 %5 +%70 = OpLoad %13 %69 +%71 = OpCompositeExtract %10 %70 2 +%72 = OpCompositeExtract %7 %71 0 +%73 = OpCompositeExtract %7 %71 1 +%74 = OpCompositeExtract %7 %71 2 +%75 = OpCompositeConstruct %11 %72 %73 %74 +%76 = OpCompositeConstruct %16 %61 %68 %75 +%77 = OpTranspose %16 %76 +%79 = OpAccessChain %54 %19 %78 +%80 = OpLoad %13 %79 +%81 = OpMatrixTimesVector %10 %80 %53 +%83 = OpCompositeExtract %7 %81 0 +%84 = OpCompositeExtract %7 %81 1 +%85 = OpCompositeExtract %7 %81 2 +%86 = OpCompositeConstruct %11 %83 %84 %85 +%87 = OpMatrixTimesVector %11 %77 %86 +%88 = OpAccessChain %82 %28 %5 +OpStore %88 %87 +%90 = OpAccessChain %89 %28 %78 +OpStore %90 %53 +%91 = OpLoad %12 %28 +%92 = OpCompositeExtract %10 %91 0 +OpStore %34 %92 +%93 = OpAccessChain %94 %34 %5 +%95 = OpLoad %7 %93 +%96 = OpFNegate %7 %95 +OpStore %93 %96 +%97 = OpCompositeExtract %11 %91 1 +OpStore %36 %97 OpReturn OpFunctionEnd -%113 = OpFunction %2 None %39 -%104 = OpLabel -%108 = OpLoad %10 %106 -%111 = OpLoad %11 %109 -%105 = OpCompositeConstruct %12 %108 %111 -%114 = OpLoad %17 %21 -%115 = OpLoad %18 %23 -OpBranch %116 -%116 = OpLabel -%117 = OpCompositeExtract %11 %105 1 -%119 = OpSampledImage %118 %114 %115 -%120 = OpImageSampleImplicitLod %10 %119 %117 -OpStore %112 %120 +%107 = OpFunction %2 None %39 +%98 = OpLabel +%102 = OpLoad %10 %100 +%105 = OpLoad %11 %103 +%99 = OpCompositeConstruct %12 %102 %105 +%108 = OpLoad %17 %21 +%109 = OpLoad %18 %23 +OpBranch %110 +%110 = OpLabel +%111 = OpCompositeExtract %11 %99 1 +%113 = OpSampledImage %112 %108 %109 +%114 = OpImageSampleImplicitLod %10 %113 %111 +OpStore %106 %114 OpReturn OpFunctionEnd From ead052b7734b767ef358b2f1d7e573968039cd13 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 2 Apr 2021 00:16:11 -0400 Subject: [PATCH 0657/2212] [spv-in] add a flag to adjust the coordinate space --- bin/convert.rs | 3 +++ src/front/spv/function.rs | 51 +++++++++++++++++++----------------- src/front/spv/mod.rs | 15 ++++++++++- tests/out/quad-vert.msl.snap | 1 - tests/snapshots.rs | 11 +++++--- 5 files changed, 51 insertions(+), 30 deletions(-) diff --git a/bin/convert.rs b/bin/convert.rs index 402b21e34..d52468110 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -5,6 +5,8 @@ use std::{env, error::Error, path::Path}; #[derive(Default)] struct Parameters { + #[cfg(feature = "spv-in")] + spv_adjust_coordinate_space: bool, #[cfg(feature = "spv-in")] spv_flow_dump_prefix: Option, #[cfg(feature = "spv-out")] @@ -102,6 +104,7 @@ fn main() { #[cfg(feature = "spv-in")] "spv" => { let options = naga::front::spv::Options { + adjust_coordinate_space: params.spv_adjust_coordinate_space, flow_graph_dump_prefix: params.spv_flow_dump_prefix.map(std::path::PathBuf::from), }; let input = fs::read(input_path).unwrap(); diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 8a71b4037..ba38cea69 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -279,31 +279,34 @@ impl> super::Parser { } } - let position_index = members.iter().position(|member| match member.binding { - Some(crate::Binding::BuiltIn(crate::BuiltIn::Position)) => true, - _ => false, - }); - if let Some(component_index) = position_index { - let old_len = function.expressions.len(); - let global_expr = components[component_index]; - let access_expr = function.expressions.append(crate::Expression::AccessIndex { - base: global_expr, - index: 1, - }); - let load_expr = function.expressions.append(crate::Expression::Load { - pointer: access_expr, - }); - let neg_expr = function.expressions.append(crate::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr: load_expr, - }); - function.body.push(crate::Statement::Emit( - function.expressions.range_from(old_len), - )); - function.body.push(crate::Statement::Store { - pointer: access_expr, - value: neg_expr, + if self.options.adjust_coordinate_space { + let position_index = members.iter().position(|member| match member.binding { + Some(crate::Binding::BuiltIn(crate::BuiltIn::Position)) => true, + _ => false, }); + if let Some(component_index) = position_index { + // The IR is Y-up, while SPIR-V is Y-down. + let old_len = function.expressions.len(); + let global_expr = components[component_index]; + let access_expr = function.expressions.append(crate::Expression::AccessIndex { + base: global_expr, + index: 1, + }); + let load_expr = function.expressions.append(crate::Expression::Load { + pointer: access_expr, + }); + let neg_expr = function.expressions.append(crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr: load_expr, + }); + function.body.push(crate::Statement::Emit( + function.expressions.range_from(old_len), + )); + function.body.push(crate::Statement::Store { + pointer: access_expr, + value: neg_expr, + }); + } } let old_len = function.expressions.len(); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 1fe4e51da..0d13d9714 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -312,11 +312,24 @@ enum ExtendedClass { Output, } -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug)] pub struct Options { + /// The IR coordinate space matches all the APIs except SPIR-V, + /// so by default we flip the Y coordinate of the `BuiltIn::Position`. + /// This flag can be used to avoid this. + pub adjust_coordinate_space: bool, pub flow_graph_dump_prefix: Option, } +impl Default for Options { + fn default() -> Self { + Options { + adjust_coordinate_space: true, + flow_graph_dump_prefix: None, + } + } +} + pub struct Parser { data: I, state: ModuleState, diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap index 79d91a3cd..16b352977 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl.snap @@ -69,7 +69,6 @@ vertex main2Output main2( a_uv = a_uv1; a_pos = a_pos1; main1(v_uv, a_uv, _, a_pos); - _.gl_Position.y = -_.gl_Position.y; const auto _tmp = type10 {v_uv, _.gl_Position, _.gl_PointSize, {_.gl_ClipDistance[0]}}; return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1[0]} }; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d6bd5e887..c4c86398b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -279,10 +279,13 @@ fn convert_wgsl_texture_array() { } #[cfg(feature = "spv-in")] -fn convert_spv(name: &str, targets: Targets) { +fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { let module = naga::front::spv::parse_u8_slice( &std::fs::read(format!("tests/in/{}{}", name, ".spv")).expect("Couldn't find spv file"), - &Default::default(), + &naga::front::spv::Options { + adjust_coordinate_space, + flow_graph_dump_prefix: None, + }, ) .unwrap(); check_targets(&module, name, targets); @@ -294,13 +297,13 @@ fn convert_spv(name: &str, targets: Targets) { #[cfg(feature = "spv-in")] #[test] fn convert_spv_quad_vert() { - convert_spv("quad-vert", Targets::METAL); + convert_spv("quad-vert", false, Targets::METAL); } #[cfg(feature = "spv-in")] #[test] fn convert_spv_shadow() { - convert_spv("shadow", Targets::IR | Targets::ANALYSIS); + convert_spv("shadow", true, Targets::IR | Targets::ANALYSIS); } #[cfg(feature = "glsl-in")] From 410c242daf764c6dc0cc1352470760525ce6e652 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 2 Apr 2021 01:12:36 -0400 Subject: [PATCH 0658/2212] [spv-out] add a flag to adjust the coordinate space --- src/back/spv/mod.rs | 5 +- src/back/spv/writer.rs | 4 +- tests/in/boids.param.ron | 2 + tests/in/collatz.param.ron | 2 + tests/in/empty.param.ron | 2 + tests/in/image-copy.param.ron | 2 + tests/in/quad-glsl.param.ron | 2 + tests/in/quad.param.ron | 2 + tests/in/shadow.param.ron | 2 + tests/in/skybox.param.ron | 2 + tests/in/texture-array.param.ron | 2 + tests/out/empty.spvasm.snap | 3 -- tests/out/skybox.spvasm.snap | 81 +++++++++++--------------------- tests/snapshots.rs | 13 ++++- 14 files changed, 64 insertions(+), 60 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index e4fa14019..55d8abf96 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -13,7 +13,10 @@ use spirv::Word; bitflags::bitflags! { pub struct WriterFlags: u32 { + /// Include debug labels for everything. const DEBUG = 0x1; + /// Flip Y coordinate of `BuiltIn::Position` output. + const ADJUST_COORDINATE_SPACE = 0x2; } } @@ -60,7 +63,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { - let mut flags = WriterFlags::empty(); + let mut flags = WriterFlags::ADJUST_COORDINATE_SPACE; if cfg!(debug_assertions) { flags |= WriterFlags::DEBUG; } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f4c7d404a..5ee3d6324 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2041,7 +2041,9 @@ impl Writer { // Flip Y coordinate to adjust for coordinate space difference // between SPIR-V and our IR. - if res_member.built_in == Some(crate::BuiltIn::Position) { + if self.flags.contains(WriterFlags::ADJUST_COORDINATE_SPACE) + && res_member.built_in == Some(crate::BuiltIn::Position) + { let access_id = self.id_gen.next(); let float_ptr_type_id = self.get_type_id( type_arena, diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index ba48f483f..16eca7eba 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -2,6 +2,8 @@ spv_flow_dump_prefix: "", spv_version: (1, 0), spv_capabilities: [ Shader ], + spv_debug: true, + spv_adjust_coordinate_space: false, mtl_bindings: { (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: false), (stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true), diff --git a/tests/in/collatz.param.ron b/tests/in/collatz.param.ron index 5e2b5adaa..e27b19568 100644 --- a/tests/in/collatz.param.ron +++ b/tests/in/collatz.param.ron @@ -2,6 +2,8 @@ spv_flow_dump_prefix: "", spv_version: (1, 0), spv_capabilities: [ Shader ], + spv_debug: true, + spv_adjust_coordinate_space: false, mtl_bindings: { (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: true), } diff --git a/tests/in/empty.param.ron b/tests/in/empty.param.ron index 18fffb565..cd1d89ab8 100644 --- a/tests/in/empty.param.ron +++ b/tests/in/empty.param.ron @@ -1,6 +1,8 @@ ( spv_version: (1, 1), spv_capabilities: [ Shader ], + spv_debug: false, + spv_adjust_coordinate_space: false, mtl_bindings: { } ) diff --git a/tests/in/image-copy.param.ron b/tests/in/image-copy.param.ron index f4cbc5f0b..297ffec8d 100644 --- a/tests/in/image-copy.param.ron +++ b/tests/in/image-copy.param.ron @@ -1,6 +1,8 @@ ( spv_version: (1, 1), spv_capabilities: [ Shader, Image1D, Sampled1D ], + spv_debug: true, + spv_adjust_coordinate_space: false, mtl_bindings: { (stage: Compute, group: 0, binding: 1): (texture: Some(0), mutable: false), (stage: Compute, group: 0, binding: 2): (texture: Some(1), mutable: true), diff --git a/tests/in/quad-glsl.param.ron b/tests/in/quad-glsl.param.ron index 9f7b9d587..3fe357ca6 100644 --- a/tests/in/quad-glsl.param.ron +++ b/tests/in/quad-glsl.param.ron @@ -1,5 +1,7 @@ ( spv_version: (1, 0), spv_capabilities: [ Shader ], + spv_debug: true, + spv_adjust_coordinate_space: true, mtl_bindings: {} ) diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index 74dd08590..fcddac8b5 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -1,6 +1,8 @@ ( spv_version: (1, 0), spv_capabilities: [ Shader ], + spv_debug: true, + spv_adjust_coordinate_space: true, mtl_bindings: { (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), (stage: Fragment, group: 0, binding: 1): (sampler: Some(0)), diff --git a/tests/in/shadow.param.ron b/tests/in/shadow.param.ron index 0af3dcbba..643ac437b 100644 --- a/tests/in/shadow.param.ron +++ b/tests/in/shadow.param.ron @@ -2,6 +2,8 @@ spv_flow_dump_prefix: "", spv_version: (1, 2), spv_capabilities: [ Shader ], + spv_debug: true, + spv_adjust_coordinate_space: true, mtl_bindings: { (stage: Fragment, group: 0, binding: 0): (buffer: Some(0), mutable: false), (stage: Fragment, group: 0, binding: 1): (buffer: Some(1), mutable: false), diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index f7e3b4f2e..237356912 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -2,6 +2,8 @@ spv_flow_dump_prefix: "", spv_version: (1, 0), spv_capabilities: [ Shader ], + spv_debug: false, + spv_adjust_coordinate_space: false, mtl_bindings: { (stage: Vertex, group: 0, binding: 0): (buffer: Some(0)), (stage: Fragment, group: 0, binding: 1): (texture: Some(0)), diff --git a/tests/in/texture-array.param.ron b/tests/in/texture-array.param.ron index 12ca44909..6e3432a8a 100644 --- a/tests/in/texture-array.param.ron +++ b/tests/in/texture-array.param.ron @@ -2,6 +2,8 @@ spv_flow_dump_prefix: "", spv_version: (1, 5), spv_capabilities: [ Shader ], + spv_debug: true, + spv_adjust_coordinate_space: false, mtl_bindings: { (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), (stage: Fragment, group: 0, binding: 1): (texture: Some(1)), diff --git a/tests/out/empty.spvasm.snap b/tests/out/empty.spvasm.snap index dabf551e5..bd9279de9 100644 --- a/tests/out/empty.spvasm.snap +++ b/tests/out/empty.spvasm.snap @@ -11,9 +11,6 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %4 "main" OpExecutionMode %4 LocalSize 1 1 1 -OpSource GLSL 450 -OpName %4 "main" -OpName %4 "main" %2 = OpTypeVoid %5 = OpTypeFunction %2 %4 = OpFunction %2 None %5 diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap index f05b6c18b..d41aa067b 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm.snap @@ -5,35 +5,13 @@ expression: dis ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 115 +; Bound: 111 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %38 "vs_main" %31 %34 %36 -OpEntryPoint Fragment %107 "fs_main" %100 %103 %106 -OpExecutionMode %107 OriginUpperLeft -OpSource GLSL 450 -OpName %12 "VertexOutput" -OpMemberName %12 0 "position" -OpMemberName %12 1 "uv" -OpName %14 "Data" -OpMemberName %14 0 "proj_inv" -OpMemberName %14 1 "view" -OpName %19 "r_data" -OpName %21 "r_texture" -OpName %23 "r_sampler" -OpName %25 "tmp1" -OpName %27 "tmp2" -OpName %28 "out" -OpName %31 "vertex_index" -OpName %34 "position" -OpName %36 "uv" -OpName %38 "vs_main" -OpName %38 "vs_main" -OpName %100 "position" -OpName %103 "uv" -OpName %107 "fs_main" -OpName %107 "fs_main" +OpEntryPoint Fragment %103 "fs_main" %96 %99 %102 +OpExecutionMode %103 OriginUpperLeft OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpDecorate %14 Block @@ -52,9 +30,9 @@ OpDecorate %23 Binding 2 OpDecorate %31 BuiltIn VertexIndex OpDecorate %34 BuiltIn Position OpDecorate %36 Location 0 -OpDecorate %100 BuiltIn FragCoord -OpDecorate %103 Location 0 -OpDecorate %106 Location 0 +OpDecorate %96 BuiltIn FragCoord +OpDecorate %99 Location 0 +OpDecorate %102 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -91,13 +69,12 @@ OpDecorate %106 Location 0 %78 = OpConstant %4 0 %82 = OpTypePointer Function %11 %89 = OpTypePointer Function %10 -%94 = OpTypePointer Output %7 -%101 = OpTypePointer Input %10 -%100 = OpVariable %101 Input -%104 = OpTypePointer Input %11 -%103 = OpVariable %104 Input -%106 = OpVariable %35 Output -%112 = OpTypeSampledImage %17 +%97 = OpTypePointer Input %10 +%96 = OpVariable %97 Input +%100 = OpTypePointer Input %11 +%99 = OpVariable %100 Input +%102 = OpVariable %35 Output +%108 = OpTypeSampledImage %17 %38 = OpFunction %2 None %39 %30 = OpLabel %25 = OpVariable %26 Function @@ -159,26 +136,22 @@ OpStore %90 %53 %91 = OpLoad %12 %28 %92 = OpCompositeExtract %10 %91 0 OpStore %34 %92 -%93 = OpAccessChain %94 %34 %5 -%95 = OpLoad %7 %93 -%96 = OpFNegate %7 %95 -OpStore %93 %96 -%97 = OpCompositeExtract %11 %91 1 -OpStore %36 %97 +%93 = OpCompositeExtract %11 %91 1 +OpStore %36 %93 OpReturn OpFunctionEnd -%107 = OpFunction %2 None %39 -%98 = OpLabel -%102 = OpLoad %10 %100 -%105 = OpLoad %11 %103 -%99 = OpCompositeConstruct %12 %102 %105 -%108 = OpLoad %17 %21 -%109 = OpLoad %18 %23 -OpBranch %110 -%110 = OpLabel -%111 = OpCompositeExtract %11 %99 1 -%113 = OpSampledImage %112 %108 %109 -%114 = OpImageSampleImplicitLod %10 %113 %111 -OpStore %106 %114 +%103 = OpFunction %2 None %39 +%94 = OpLabel +%98 = OpLoad %10 %96 +%101 = OpLoad %11 %99 +%95 = OpCompositeConstruct %12 %98 %101 +%104 = OpLoad %17 %21 +%105 = OpLoad %18 %23 +OpBranch %106 +%106 = OpLabel +%107 = OpCompositeExtract %11 %95 1 +%109 = OpSampledImage %108 %104 %105 +%110 = OpImageSampleImplicitLod %10 %109 %107 +OpStore %102 %110 OpReturn OpFunctionEnd diff --git a/tests/snapshots.rs b/tests/snapshots.rs index c4c86398b..e978a0051 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -45,6 +45,10 @@ struct Parameters { spv_version: (u8, u8), #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_capabilities: naga::FastHashSet, + #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + spv_debug: bool, + #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + spv_adjust_coordinate_space: bool, #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] mtl_bindings: naga::FastHashMap, } @@ -126,9 +130,16 @@ fn check_output_spv( use naga::back::spv; use rspirv::binary::Disassemble; + let mut flags = spv::WriterFlags::empty(); + if params.spv_debug { + flags |= spv::WriterFlags::DEBUG; + } + if params.spv_adjust_coordinate_space { + flags |= spv::WriterFlags::ADJUST_COORDINATE_SPACE; + } let options = spv::Options { lang_version: params.spv_version, - flags: spv::WriterFlags::DEBUG, + flags, capabilities: params.spv_capabilities.clone(), }; From a9bde2678568ff8a395b89a40cfd42af95bd1b4d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 4 Apr 2021 01:01:57 -0400 Subject: [PATCH 0659/2212] [spv-out] fix incorrect dummy result --- src/back/spv/writer.rs | 5 ++++- tests/out/texture-array.spvasm.snap | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 5ee3d6324..5359109fc 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2417,7 +2417,10 @@ impl Writer { if block.termination.is_none() { block.termination = Some(match exit_id { Some(id) => Instruction::branch(id), - None => Instruction::return_void(), + // This can happen if the last branch had all the paths + // leading out of the graph (i.e. returning). + // So it doesn't matter what we do here, but it has to be valid. + None => Instruction::branch(label_id), }); } diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap index 6023540f9..2a5b56ef9 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm.snap @@ -81,5 +81,5 @@ OpReturn OpStore %22 %44 OpReturn %37 = OpLabel -OpReturn +OpBranch %29 OpFunctionEnd From 0369ee181ed9cd315635fc0e3d99deecdbc72246 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 4 Apr 2021 01:32:42 -0400 Subject: [PATCH 0660/2212] [spv-out] fix sampling from depth textures --- src/back/spv/writer.rs | 73 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 65 insertions(+), 8 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 5359109fc..8a375cfd7 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1748,6 +1748,23 @@ impl Writer { class: crate::ImageClass::Storage { .. }, .. } => Instruction::image_read(result_type_id, id, image_id, coordinate_id), + crate::TypeInner::Image { + class: crate::ImageClass::Depth, + .. + } => { + // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, + // so we need to grab the first component out of it. + let load_result_type_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Quad), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }), + )?; + Instruction::image_fetch(load_result_type_id, id, image_id, coordinate_id) + } _ => Instruction::image_fetch(result_type_id, id, image_id, coordinate_id), }; @@ -1764,8 +1781,16 @@ impl Writer { instruction.add_operand(index_id); } - block.body.push(instruction); - id + if instruction.type_id != Some(result_type_id) { + let sub_id = self.id_gen.next(); + let index_id = self.get_index_constant(0, &ir_module.types)?; + let sub_instruction = + Instruction::vector_extract_dynamic(result_type_id, sub_id, id, index_id); + block.body.push(sub_instruction); + sub_id + } else { + id + } } crate::Expression::ImageSample { image, @@ -1780,6 +1805,28 @@ impl Writer { // image let image_id = self.get_expression_global(ir_function, image); let image_type = fun_info[image].ty.handle().unwrap(); + // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, + // so we need to grab the first component out of it. + let needs_sub_access = match ir_module.types[image_type].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Depth, + .. + } => depth_ref.is_none(), + _ => false, + }; + let sample_result_type_id = if needs_sub_access { + self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Quad), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }), + )? + } else { + result_type_id + }; // OpTypeSampledImage let sampled_image_type_id = self.get_type_id( @@ -1810,7 +1857,7 @@ impl Writer { let mut main_instruction = match level { crate::SampleLevel::Zero => { let mut inst = Instruction::image_sample( - result_type_id, + sample_result_type_id, id, SampleLod::Explicit, sampled_image_id, @@ -1833,7 +1880,7 @@ impl Writer { inst } crate::SampleLevel::Auto => Instruction::image_sample( - result_type_id, + sample_result_type_id, id, SampleLod::Implicit, sampled_image_id, @@ -1842,7 +1889,7 @@ impl Writer { ), crate::SampleLevel::Exact(lod_handle) => { let mut inst = Instruction::image_sample( - result_type_id, + sample_result_type_id, id, SampleLod::Explicit, sampled_image_id, @@ -1858,7 +1905,7 @@ impl Writer { } crate::SampleLevel::Bias(bias_handle) => { let mut inst = Instruction::image_sample( - result_type_id, + sample_result_type_id, id, SampleLod::Implicit, sampled_image_id, @@ -1874,7 +1921,7 @@ impl Writer { } crate::SampleLevel::Gradient { x, y } => { let mut inst = Instruction::image_sample( - result_type_id, + sample_result_type_id, id, SampleLod::Explicit, sampled_image_id, @@ -1899,7 +1946,17 @@ impl Writer { } block.body.push(main_instruction); - id + + if needs_sub_access { + let sub_id = self.id_gen.next(); + let index_id = self.get_index_constant(0, &ir_module.types)?; + let sub_instruction = + Instruction::vector_extract_dynamic(result_type_id, sub_id, id, index_id); + block.body.push(sub_instruction); + sub_id + } else { + id + } } crate::Expression::Select { condition, From 0058ce5a7d06885ddd4581a5a8b62fde0a7fdd5f Mon Sep 17 00:00:00 2001 From: adamnemecek Date: Sun, 4 Apr 2021 08:56:48 -0700 Subject: [PATCH 0661/2212] fixed bug where metal backend would make all switch cases fallthrough --- src/back/msl/writer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 5d3f76119..14699dfa5 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -915,7 +915,7 @@ impl Writer { for case in cases.iter() { writeln!(self.out, "{}case {}: {{", lcase, case.value)?; self.put_block(lcase.next(), &case.body, context)?; - if case.fall_through { + if !case.fall_through { writeln!(self.out, "{}break;", lcase.next())?; } writeln!(self.out, "{}}}", lcase)?; From ccb6dc90883e10fea556546a4b40332943bb3e87 Mon Sep 17 00:00:00 2001 From: Zakarum Date: Wed, 7 Apr 2021 21:00:40 +0300 Subject: [PATCH 0662/2212] Panic to prevent arena Handle overflow (#667) * Panic to prevent arena Handle overflow * Use `NonZeroU32::new` to detect overflow --- src/arena.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/arena.rs b/src/arena.rs index af3fba55d..174c79b54 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -189,7 +189,8 @@ impl Arena { /// Adds a new value to the arena, returning a typed handle. pub fn append(&mut self, value: T) -> Handle { let position = self.data.len() + 1; - let index = unsafe { Index::new_unchecked(position as u32) }; + let index = + Index::new(position as u32).expect("Failed to append to Arena. Handle overflows"); self.data.push(value); Handle::new(index) } From 2da7477322354d916882144dffccff99607dea7e Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 7 Apr 2021 19:45:38 -0700 Subject: [PATCH 0663/2212] [wgsl-in] Decorations are now called attributes. (#671) Renames: Error::UnknownDecoration => Error::UnknownAttribute TypeDecoration => TypeAttributes Scope::Decoration => Scope::Attribute various argument names, string literals, comments --- src/front/wgsl/conv.rs | 2 +- src/front/wgsl/mod.rs | 56 +++++++++++++++++++++--------------------- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 396dbd24a..cd84c0b57 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -47,7 +47,7 @@ pub fn map_interpolation(word: &str) -> Result> "centroid" => Ok(crate::Interpolation::Centroid), "sample" => Ok(crate::Interpolation::Sample), "perspective" => Ok(crate::Interpolation::Perspective), - _ => Err(Error::UnknownDecoration(word)), + _ => Err(Error::UnknownAttribute(word)), } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 9eb8c4f96..0434f8589 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -83,8 +83,8 @@ pub enum Error<'a> { UnknownImport(&'a str), #[error("unknown storage class: `{0}`")] UnknownStorageClass(&'a str), - #[error("unknown decoration: `{0}`")] - UnknownDecoration(&'a str), + #[error("unknown attribute: `{0}`")] + UnknownAttribute(&'a str), #[error("unknown scalar kind: `{0}`")] UnknownScalarKind(&'a str), #[error("unknown builtin: `{0}`")] @@ -404,14 +404,14 @@ impl Composition { } #[derive(Default)] -struct TypeDecoration { +struct TypeAttributes { stride: Option, access: crate::StorageAccess, } #[derive(Clone, Debug, PartialEq)] pub enum Scope { - Decoration, + Attribute, ImportDecl, VariableDecl, TypeDecl, @@ -453,7 +453,7 @@ impl BindingParser { self.interpolation = Some(conv::map_interpolation(raw)?); lexer.expect(Token::Paren(')'))?; } - _ => return Err(Error::UnknownDecoration(name)), + _ => return Err(Error::UnknownAttribute(name)), } Ok(()) } @@ -988,7 +988,7 @@ impl Parser { lexer, name, None, - TypeDecoration::default(), + TypeAttributes::default(), type_arena, const_arena, )?; @@ -1072,7 +1072,7 @@ impl Parser { } else { let inner = self.parse_type_decl_impl( lexer, - TypeDecoration::default(), + TypeAttributes::default(), word, ctx.types, ctx.constants, @@ -1513,7 +1513,7 @@ impl Parser { let (mut size, mut align) = (None, None); let mut bind_parser = BindingParser::default(); if lexer.skip(Token::DoubleParen('[')) { - self.scopes.push(Scope::Decoration); + self.scopes.push(Scope::Attribute); let mut ready = true; loop { match lexer.next() { @@ -1543,7 +1543,7 @@ impl Parser { } ready = false; } - other => return Err(Error::Unexpected(other, "decoration separator")), + other => return Err(Error::Unexpected(other, "attribute separator")), } } self.scopes.pop(); @@ -1571,7 +1571,7 @@ impl Parser { fn parse_type_decl_impl<'a>( &mut self, lexer: &mut Lexer<'a>, - decoration: TypeDecoration, + attribute: TypeAttributes, word: &'a str, type_arena: &mut Arena, const_arena: &mut Arena, @@ -1712,7 +1712,7 @@ impl Parser { crate::TypeInner::Array { base, size, - stride: decoration.stride, + stride: attribute.stride, } } "sampler" => crate::TypeInner::Sampler { comparison: false }, @@ -1853,13 +1853,13 @@ impl Parser { }) } - /// Parse type declaration of a given name and decoration. + /// Parse type declaration of a given name and attribute. fn parse_type_decl_name<'a>( &mut self, lexer: &mut Lexer<'a>, name: &'a str, debug_name: Option<&'a str>, - decoration: TypeDecoration, + attribute: TypeAttributes, type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result, Error<'a>> { @@ -1867,7 +1867,7 @@ impl Parser { Some(&handle) => handle, None => { let inner = - self.parse_type_decl_impl(lexer, decoration, name, type_arena, const_arena)?; + self.parse_type_decl_impl(lexer, attribute, name, type_arena, const_arena)?; type_arena.fetch_or_append(crate::Type { name: debug_name.map(|s| s.to_string()), inner, @@ -1884,15 +1884,15 @@ impl Parser { const_arena: &mut Arena, ) -> Result<(Handle, crate::StorageAccess), Error<'a>> { self.scopes.push(Scope::TypeDecl); - let mut decoration = TypeDecoration::default(); + let mut attribute = TypeAttributes::default(); if lexer.skip(Token::DoubleParen('[')) { - self.scopes.push(Scope::Decoration); + self.scopes.push(Scope::Attribute); loop { match lexer.next() { (Token::Word("access"), _) => { lexer.expect(Token::Paren('('))?; - decoration.access = match lexer.next_ident()? { + attribute.access = match lexer.next_ident()? { "read" => crate::StorageAccess::LOAD, "write" => crate::StorageAccess::STORE, "read_write" => crate::StorageAccess::all(), @@ -1902,25 +1902,25 @@ impl Parser { } (Token::Word("stride"), _) => { lexer.expect(Token::Paren('('))?; - decoration.stride = Some( + attribute.stride = Some( NonZeroU32::new(lexer.next_uint_literal()?).ok_or(Error::ZeroStride)?, ); lexer.expect(Token::Paren(')'))?; } (Token::DoubleParen(']'), _) => break, - other => return Err(Error::Unexpected(other, "type decoration")), + other => return Err(Error::Unexpected(other, "type attribute")), } } self.scopes.pop(); } - let storage_access = decoration.access; + let storage_access = attribute.access; let name = lexer.next_ident()?; let handle = self.parse_type_decl_name( lexer, name, debug_name, - decoration, + attribute, type_arena, const_arena, )?; @@ -2361,7 +2361,7 @@ impl Parser { } let mut bind_parser = BindingParser::default(); - self.scopes.push(Scope::Decoration); + self.scopes.push(Scope::Attribute); loop { let word = lexer.next_ident()?; bind_parser.parse(lexer, word)?; @@ -2370,7 +2370,7 @@ impl Parser { break; } (Token::Separator(','), _) => {} - other => return Err(Error::Unexpected(other, "decoration separator")), + other => return Err(Error::Unexpected(other, "attribute separator")), } } self.scopes.pop(); @@ -2465,7 +2465,7 @@ impl Parser { module: &mut crate::Module, lookup_global_expression: &mut FastHashMap<&'a str, crate::Expression>, ) -> Result> { - // read decorations + // read attributes let mut binding = None; // Perspective is the default qualifier. let mut stage = None; @@ -2475,7 +2475,7 @@ impl Parser { if lexer.skip(Token::DoubleParen('[')) { let (mut bind_index, mut bind_group) = (None, None); - self.scopes.push(Scope::Decoration); + self.scopes.push(Scope::Attribute); loop { match lexer.next_ident()? { "binding" => { @@ -2527,14 +2527,14 @@ impl Parser { }; early_depth_test = Some(crate::EarlyDepthTest { conservative }); } - word => return Err(Error::UnknownDecoration(word)), + word => return Err(Error::UnknownAttribute(word)), } match lexer.next() { (Token::DoubleParen(']'), _) => { break; } (Token::Separator(','), _) => {} - other => return Err(Error::Unexpected(other, "decoration separator")), + other => return Err(Error::Unexpected(other, "attribute separator")), } } if let (Some(group), Some(index)) = (bind_group, bind_index) { @@ -2663,7 +2663,7 @@ impl Parser { match binding { None => Ok(true), - // we had the decoration but no var? + // we had the attribute but no var? Some(_) => Err(Error::Other), } } From dcbedd17d075a654f1b35b47e2636517b2275089 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 7 Apr 2021 01:06:51 -0400 Subject: [PATCH 0664/2212] [msl] basic infrastructure for inline samplers Also move out "allow_point_size" into SubOptions to allow main Options to not be cloned. --- bin/convert.rs | 4 ++- src/back/msl/mod.rs | 65 +++++++++++++++++++++++++-------- src/back/msl/sampler.rs | 80 +++++++++++++++++++++++++++++++++++++++++ src/back/msl/writer.rs | 20 ++++++----- tests/snapshots.rs | 7 ++-- 5 files changed, 150 insertions(+), 26 deletions(-) create mode 100644 src/back/msl/sampler.rs diff --git a/bin/convert.rs b/bin/convert.rs index d52468110..b6aaba122 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -202,8 +202,10 @@ fn main() { #[cfg(feature = "msl-out")] "metal" => { use naga::back::msl; + let sub_options = msl::SubOptions::default(); let (msl, _) = - msl::write_string(&module, info.as_ref().unwrap(), ¶ms.msl).unwrap_pretty(); + msl::write_string(&module, info.as_ref().unwrap(), ¶ms.msl, &sub_options) + .unwrap_pretty(); fs::write(output_path, msl).unwrap(); } #[cfg(feature = "spv-out")] diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 23b63794c..024995cf1 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -23,19 +23,30 @@ For the result type, if it's a structure, we re-compose it with a temporary valu holding the result. !*/ -use crate::{arena::Handle, valid::ModuleInfo, FastHashMap}; +use crate::{ + arena::{Arena, Handle}, + valid::ModuleInfo, + FastHashMap, +}; use std::fmt::{Error as FmtError, Write}; mod keywords; +mod sampler; mod writer; pub use writer::Writer; +#[derive(Clone, Debug, PartialEq)] +pub enum BindSamplerTarget { + Resource(u8), + Inline(Handle), +} + #[derive(Clone, Debug, Default, PartialEq)] pub struct BindTarget { pub buffer: Option, pub texture: Option, - pub sampler: Option, + pub sampler: Option, pub mutable: bool, } @@ -90,19 +101,18 @@ enum LocationMode { Uniform, } -#[derive(Debug, Clone)] +#[derive(Debug)] pub struct Options { /// (Major, Minor) target version of the Metal Shading Language. pub lang_version: (u8, u8), /// Binding model mapping to Metal. pub binding_map: BindingMap, + /// Samplers to be inlined into the code. + pub inline_samplers: Arena, /// Make it possible to link different stages via SPIRV-Cross. pub spirv_cross_compatibility: bool, /// Don't panic on missing bindings, instead generate invalid MSL. pub fake_missing_bindings: bool, - /// Allow `BuiltIn::PointSize` in the vertex shader. - /// Metal doesn't like this for non-point primitive topologies. - pub allow_point_size: bool, } impl Default for Options { @@ -110,8 +120,24 @@ impl Default for Options { Options { lang_version: (1, 0), binding_map: BindingMap::default(), + inline_samplers: Arena::new(), spirv_cross_compatibility: false, fake_missing_bindings: true, + } + } +} + +// A subset of options that are meant to be changed per pipeline. +#[derive(Debug, Clone)] +pub struct SubOptions { + /// Allow `BuiltIn::PointSize` in the vertex shader. + /// Metal doesn't like this for non-point primitive topologies. + pub allow_point_size: bool, +} + +impl Default for SubOptions { + fn default() -> Self { + SubOptions { allow_point_size: true, } } @@ -169,9 +195,19 @@ impl Options { } impl ResolvedBinding { + fn _as_inline_sampler<'a>(&self, options: &'a Options) -> Option<&'a sampler::InlineSampler> { + match *self { + Self::Resource(BindTarget { + sampler: Some(BindSamplerTarget::Inline(handle)), + .. + }) => Some(&options.inline_samplers[handle]), + _ => None, + } + } + fn try_fmt(&self, out: &mut W) -> Result<(), Error> { match *self { - ResolvedBinding::BuiltIn(built_in) => { + Self::BuiltIn(built_in) => { use crate::BuiltIn as Bi; let name = match built_in { Bi::Position => "position", @@ -196,17 +232,15 @@ impl ResolvedBinding { }; Ok(write!(out, "{}", name)?) } - ResolvedBinding::Attribute(index) => Ok(write!(out, "attribute({})", index)?), - ResolvedBinding::Color(index) => Ok(write!(out, "color({})", index)?), - ResolvedBinding::User { prefix, index } => { - Ok(write!(out, "user({}{})", prefix, index)?) - } - ResolvedBinding::Resource(ref target) => { + Self::Attribute(index) => Ok(write!(out, "attribute({})", index)?), + Self::Color(index) => Ok(write!(out, "color({})", index)?), + Self::User { prefix, index } => Ok(write!(out, "user({}{})", prefix, index)?), + Self::Resource(ref target) => { if let Some(id) = target.buffer { Ok(write!(out, "buffer({})", id)?) } else if let Some(id) = target.texture { Ok(write!(out, "texture({})", id)?) - } else if let Some(id) = target.sampler { + } else if let Some(BindSamplerTarget::Resource(id)) = target.sampler { Ok(write!(out, "sampler({})", id)?) } else { Err(Error::UnimplementedBindTarget(target.clone())) @@ -238,9 +272,10 @@ pub fn write_string( module: &crate::Module, info: &ModuleInfo, options: &Options, + sub_options: &SubOptions, ) -> Result<(String, TranslationInfo), Error> { let mut w = writer::Writer::new(String::new()); - let info = w.write(module, info, options)?; + let info = w.write(module, info, options, sub_options)?; Ok((w.finish(), info)) } diff --git a/src/back/msl/sampler.rs b/src/back/msl/sampler.rs new file mode 100644 index 000000000..4d5539be8 --- /dev/null +++ b/src/back/msl/sampler.rs @@ -0,0 +1,80 @@ +#[derive(Clone, Debug, PartialEq)] +pub enum Coord { + Normalized, + Pixel, +} + +impl Default for Coord { + fn default() -> Self { + Self::Normalized + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Address { + Repeat, + MirroredRepeat, + ClampToEdge, + ClampToZero, + ClampToBorder, +} + +impl Default for Address { + fn default() -> Self { + Self::ClampToEdge + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum BorderColor { + TransparentBlack, + OpaqueBlack, + OpaqueWhite, +} + +impl Default for BorderColor { + fn default() -> Self { + Self::TransparentBlack + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Filter { + Nearest, + Linear, +} + +impl Default for Filter { + fn default() -> Self { + Self::Nearest + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum CompareFunc { + Never, + Less, + LessEqual, + Greater, + GreaterEqual, + Equal, + NotEqual, + Always, +} + +impl Default for CompareFunc { + fn default() -> Self { + Self::Never + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct InlineSampler { + pub coord: Coord, + pub address: [Address; 3], + pub border_color: BorderColor, + pub mag_filter: Filter, + pub min_filter: Filter, + pub mip_filter: Option, + pub compare_func: CompareFunc, +} diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 14699dfa5..6225809a7 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,4 +1,4 @@ -use super::{keywords::RESERVED, Error, LocationMode, Options, TranslationInfo}; +use super::{keywords::RESERVED, Error, LocationMode, Options, SubOptions, TranslationInfo}; use crate::{ arena::Handle, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, @@ -150,7 +150,7 @@ struct ExpressionContext<'a> { origin: FunctionOrigin, info: &'a FunctionInfo, module: &'a crate::Module, - options: &'a Options, + sub_options: &'a SubOptions, } impl<'a> ExpressionContext<'a> { @@ -773,7 +773,7 @@ impl Writer { write!(self.out, "{}return {} {{", level, struct_name)?; let mut is_first = true; for (index, member) in members.iter().enumerate() { - if !context.options.allow_point_size + if !context.sub_options.allow_point_size && member.binding == Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) { @@ -1076,6 +1076,7 @@ impl Writer { module: &crate::Module, info: &ModuleInfo, options: &Options, + sub_options: &SubOptions, ) -> Result { self.names.clear(); self.namer.reset(module, RESERVED, &mut self.names); @@ -1087,7 +1088,7 @@ impl Writer { self.write_scalar_constants(module)?; self.write_type_defs(module)?; self.write_composite_constants(module)?; - self.write_functions(module, info, options) + self.write_functions(module, info, options, sub_options) } fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { @@ -1321,6 +1322,7 @@ impl Writer { module: &crate::Module, mod_info: &ModuleInfo, options: &Options, + sub_options: &SubOptions, ) -> Result { let mut pass_through_globals = Vec::new(); for (fun_handle, fun) in module.functions.iter() { @@ -1382,7 +1384,7 @@ impl Writer { origin: FunctionOrigin::Handle(fun_handle), info: fun_info, module, - options, + sub_options, }, mod_info, result_struct: None, @@ -1511,7 +1513,7 @@ impl Writer { for (name, ty, binding) in result_members { let type_name = &self.names[&NameKey::Type(ty)]; let binding = binding.ok_or(Error::Validation)?; - if !options.allow_point_size + if !sub_options.allow_point_size && *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize) { continue; @@ -1670,7 +1672,7 @@ impl Writer { origin: FunctionOrigin::EntryPoint(ep_index as _), info: fun_info, module, - options, + sub_options, }, mod_info, result_struct: Some(&stage_out_name), @@ -1722,7 +1724,9 @@ fn test_stack_size() { .unwrap(); // process the module let mut writer = Writer::new(String::new()); - writer.write(&module, &info, &Default::default()).unwrap(); + writer + .write(&module, &info, &Default::default(), &Default::default()) + .unwrap(); { // check expression stack diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e978a0051..a42e7470f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -177,7 +177,7 @@ fn check_output_msl( msl::BindTarget { buffer: value.buffer, texture: value.texture, - sampler: value.sampler, + sampler: value.sampler.map(msl::BindSamplerTarget::Resource), mutable: value.mutable, }, ); @@ -185,12 +185,15 @@ fn check_output_msl( let options = msl::Options { lang_version: (1, 0), binding_map, + inline_samplers: naga::Arena::new(), spirv_cross_compatibility: false, fake_missing_bindings: false, + }; + let sub_options = msl::SubOptions { allow_point_size: true, }; - let (msl, _) = msl::write_string(module, info, &options).unwrap(); + let (msl, _) = msl::write_string(module, info, &options, &sub_options).unwrap(); with_snapshot_settings(|| { insta::assert_snapshot!(format!("{}.msl", name), msl); From 9e09c792dcd55f441a6e646758af88b02511c5f7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 7 Apr 2021 01:38:22 -0400 Subject: [PATCH 0665/2212] [msl] write down inline samplers --- src/back/msl/mod.rs | 2 +- src/back/msl/sampler.rs | 56 ++++++++++++++++++++-- src/back/msl/writer.rs | 102 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 150 insertions(+), 10 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 024995cf1..f9ddf51c7 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -195,7 +195,7 @@ impl Options { } impl ResolvedBinding { - fn _as_inline_sampler<'a>(&self, options: &'a Options) -> Option<&'a sampler::InlineSampler> { + fn as_inline_sampler<'a>(&self, options: &'a Options) -> Option<&'a sampler::InlineSampler> { match *self { Self::Resource(BindTarget { sampler: Some(BindSamplerTarget::Inline(handle)), diff --git a/src/back/msl/sampler.rs b/src/back/msl/sampler.rs index 4d5539be8..f9b57e4b5 100644 --- a/src/back/msl/sampler.rs +++ b/src/back/msl/sampler.rs @@ -1,4 +1,4 @@ -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum Coord { Normalized, Pixel, @@ -10,7 +10,7 @@ impl Default for Coord { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum Address { Repeat, MirroredRepeat, @@ -25,7 +25,19 @@ impl Default for Address { } } -#[derive(Clone, Debug, PartialEq)] +impl Address { + pub fn as_str(&self) -> &'static str { + match *self { + Self::Repeat => "repeat", + Self::MirroredRepeat => "mirrored_repeat", + Self::ClampToEdge => "clamp_to_edge", + Self::ClampToZero => "clamp_to_zero", + Self::ClampToBorder => "clamp_to_border", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] pub enum BorderColor { TransparentBlack, OpaqueBlack, @@ -38,19 +50,38 @@ impl Default for BorderColor { } } -#[derive(Clone, Debug, PartialEq)] +impl BorderColor { + pub fn as_str(&self) -> &'static str { + match *self { + Self::TransparentBlack => "transparent_black", + Self::OpaqueBlack => "opaque_black", + Self::OpaqueWhite => "opaque_white", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] pub enum Filter { Nearest, Linear, } +impl Filter { + pub fn as_str(&self) -> &'static str { + match *self { + Self::Nearest => "nearest", + Self::Linear => "linear", + } + } +} + impl Default for Filter { fn default() -> Self { Self::Nearest } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum CompareFunc { Never, Less, @@ -68,6 +99,21 @@ impl Default for CompareFunc { } } +impl CompareFunc { + pub fn as_str(&self) -> &'static str { + match *self { + Self::Never => "never", + Self::Less => "less", + Self::LessEqual => "less_equal", + Self::Greater => "greater", + Self::GreaterEqual => "greater_equal", + Self::Equal => "equal", + Self::NotEqual => "not_equal", + Self::Always => "always", + } + } +} + #[derive(Clone, Debug, Default, PartialEq)] pub struct InlineSampler { pub coord: Coord, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 6225809a7..5054c1f56 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,4 +1,6 @@ -use super::{keywords::RESERVED, Error, LocationMode, Options, SubOptions, TranslationInfo}; +use super::{ + keywords::RESERVED, sampler as sm, Error, LocationMode, Options, SubOptions, TranslationInfo, +}; use crate::{ arena::Handle, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, @@ -163,6 +165,7 @@ struct StatementContext<'a> { expression: ExpressionContext<'a>, mod_info: &'a ModuleInfo, result_struct: Option<&'a str>, + inline_global_handles: &'a BitSet, } impl Writer { @@ -1043,7 +1046,10 @@ impl Writer { let mut separate = !arguments.is_empty(); let fun_info = &context.mod_info[function]; for (handle, var) in context.expression.module.global_variables.iter() { - if !fun_info[handle].is_empty() && var.class.needs_pass_through() { + if !fun_info[handle].is_empty() + && !context.inline_global_handles.contains(handle.index()) + && var.class.needs_pass_through() + { let name = &self.names[&NameKey::GlobalVariable(handle)]; if separate { write!(self.out, ", ")?; @@ -1316,6 +1322,63 @@ impl Writer { Ok(()) } + fn write_inline_sampler( + &mut self, + sampler: &sm::InlineSampler, + stage: crate::ShaderStage, + handle: Handle, + ) -> Result<(), Error> { + write!( + self.out, + "constexpr sampler ism_{}_{:?}(", + handle.index(), + stage + )?; + for (&letter, address) in ['s', 't', 'r'].iter().zip(sampler.address.iter()) { + write!( + self.out, + "{}{}_address::{},", + INDENT, + letter, + address.as_str() + )?; + } + write!( + self.out, + "{}mag_filter::{},", + INDENT, + sampler.mag_filter.as_str() + )?; + write!( + self.out, + "{}min_filter::{},", + INDENT, + sampler.min_filter.as_str() + )?; + if let Some(filter) = sampler.mip_filter { + write!(self.out, "{}mip_filter::{},", INDENT, filter.as_str())?; + } + // avoid setting it on platforms that don't support it + if sampler.border_color != sm::BorderColor::TransparentBlack { + write!( + self.out, + "{}border_color::{},", + INDENT, + sampler.border_color.as_str() + )?; + } + if sampler.compare_func != sm::CompareFunc::Never { + write!( + self.out, + "{}compare_func::{},", + INDENT, + sampler.compare_func.as_str() + )?; + } + writeln!(self.out, "{}coord::normalized);", INDENT)?; + Ok(()) + } + // Returns the array of mapped entry point names. fn write_functions( &mut self, @@ -1324,12 +1387,38 @@ impl Writer { options: &Options, sub_options: &SubOptions, ) -> Result { + // first, write down immutable samplers as const expressions + let mut inline_global_handles = BitSet::new(); + for (handle, var) in module.global_variables.iter() { + let binding = match var.binding { + Some(ref binding) => binding, + None => continue, + }; + for &stage in [ + crate::ShaderStage::Vertex, + crate::ShaderStage::Fragment, + crate::ShaderStage::Compute, + ] + .iter() + { + if let Ok(resolved) = options.resolve_global_binding(stage, binding) { + if let Some(sampler) = resolved.as_inline_sampler(options) { + inline_global_handles.insert(handle.index()); + self.write_inline_sampler(sampler, stage, handle)?; + } + } + } + } + let mut pass_through_globals = Vec::new(); for (fun_handle, fun) in module.functions.iter() { let fun_info = &mod_info[fun_handle]; pass_through_globals.clear(); for (handle, var) in module.global_variables.iter() { - if !fun_info[handle].is_empty() && var.class.needs_pass_through() { + if !fun_info[handle].is_empty() + && !inline_global_handles.contains(handle.index()) + && var.class.needs_pass_through() + { pass_through_globals.push(handle); } } @@ -1388,6 +1477,7 @@ impl Writer { }, mod_info, result_struct: None, + inline_global_handles: &inline_global_handles, }; self.named_expressions.clear(); self.put_block(Level(1), &fun.body, &context)?; @@ -1558,7 +1648,10 @@ impl Writer { } for (handle, var) in module.global_variables.iter() { let usage = fun_info[handle]; - if usage.is_empty() || var.class == crate::StorageClass::Private { + if usage.is_empty() + || var.class == crate::StorageClass::Private + || inline_global_handles.contains(handle.index()) + { continue; } let tyvar = TypedGlobalVariable { @@ -1676,6 +1769,7 @@ impl Writer { }, mod_info, result_struct: Some(&stage_out_name), + inline_global_handles: &inline_global_handles, }; self.named_expressions.clear(); self.put_block(Level(1), &fun.body, &context)?; From 7c11759041081cf2caaba3035ce94fc418d22e0a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 7 Apr 2021 10:29:35 -0400 Subject: [PATCH 0666/2212] Re-use the MSL types in snapshot code --- src/back/msl/mod.rs | 9 ++++ src/back/msl/sampler.rs | 9 ++++ tests/in/boids.param.ron | 17 ++++--- tests/in/collatz.param.ron | 4 +- tests/in/empty.param.ron | 3 +- tests/in/image-copy.param.ron | 5 +-- tests/in/quad-glsl.param.ron | 2 +- tests/in/quad.param.ron | 5 +-- tests/in/shadow.param.ron | 7 +-- tests/in/skybox.param.ron | 17 ++++--- tests/in/texture-array.param.ron | 6 +-- tests/out/collatz.msl.snap | 2 +- tests/out/image-copy.msl.snap | 4 +- tests/out/quad.msl.snap | 4 +- tests/out/shadow.msl.snap | 8 ++-- tests/snapshots.rs | 76 +++++++------------------------- 16 files changed, 75 insertions(+), 103 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index f9ddf51c7..234aaf284 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -37,20 +37,27 @@ mod writer; pub use writer::Writer; #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum BindSamplerTarget { Resource(u8), Inline(Handle), } #[derive(Clone, Debug, Default, PartialEq)] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct BindTarget { + #[cfg_attr(feature = "deserialize", serde(default))] pub buffer: Option, + #[cfg_attr(feature = "deserialize", serde(default))] pub texture: Option, + #[cfg_attr(feature = "deserialize", serde(default))] pub sampler: Option, + #[cfg_attr(feature = "deserialize", serde(default))] pub mutable: bool, } #[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct BindSource { pub stage: crate::ShaderStage, pub group: u32, @@ -102,6 +109,7 @@ enum LocationMode { } #[derive(Debug)] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Options { /// (Major, Minor) target version of the Metal Shading Language. pub lang_version: (u8, u8), @@ -129,6 +137,7 @@ impl Default for Options { // A subset of options that are meant to be changed per pipeline. #[derive(Debug, Clone)] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct SubOptions { /// Allow `BuiltIn::PointSize` in the vertex shader. /// Metal doesn't like this for non-point primitive topologies. diff --git a/src/back/msl/sampler.rs b/src/back/msl/sampler.rs index f9b57e4b5..be44045c7 100644 --- a/src/back/msl/sampler.rs +++ b/src/back/msl/sampler.rs @@ -1,4 +1,8 @@ +#[cfg(feature = "deserialize")] +use serde::Deserialize; + #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Coord { Normalized, Pixel, @@ -11,6 +15,7 @@ impl Default for Coord { } #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Address { Repeat, MirroredRepeat, @@ -38,6 +43,7 @@ impl Address { } #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum BorderColor { TransparentBlack, OpaqueBlack, @@ -61,6 +67,7 @@ impl BorderColor { } #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Filter { Nearest, Linear, @@ -82,6 +89,7 @@ impl Default for Filter { } #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum CompareFunc { Never, Less, @@ -115,6 +123,7 @@ impl CompareFunc { } #[derive(Clone, Debug, Default, PartialEq)] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct InlineSampler { pub coord: Coord, pub address: [Address; 3], diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index 16eca7eba..06a8df2da 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -4,9 +4,16 @@ spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: false, - mtl_bindings: { - (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: false), - (stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true), - (stage: Compute, group: 0, binding: 2): (buffer: Some(2), mutable: true), - } + msl_custom: true, + msl: ( + lang_version: (2, 0), + binding_map: { + (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: false), + (stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true), + (stage: Compute, group: 0, binding: 2): (buffer: Some(2), mutable: true), + }, + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + ), ) diff --git a/tests/in/collatz.param.ron b/tests/in/collatz.param.ron index e27b19568..984ca763e 100644 --- a/tests/in/collatz.param.ron +++ b/tests/in/collatz.param.ron @@ -4,7 +4,5 @@ spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: false, - mtl_bindings: { - (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: true), - } + msl_custom: false, ) diff --git a/tests/in/empty.param.ron b/tests/in/empty.param.ron index cd1d89ab8..6de22960d 100644 --- a/tests/in/empty.param.ron +++ b/tests/in/empty.param.ron @@ -3,6 +3,5 @@ spv_capabilities: [ Shader ], spv_debug: false, spv_adjust_coordinate_space: false, - mtl_bindings: { - } + msl_custom: false, ) diff --git a/tests/in/image-copy.param.ron b/tests/in/image-copy.param.ron index 297ffec8d..52f49f360 100644 --- a/tests/in/image-copy.param.ron +++ b/tests/in/image-copy.param.ron @@ -3,8 +3,5 @@ spv_capabilities: [ Shader, Image1D, Sampled1D ], spv_debug: true, spv_adjust_coordinate_space: false, - mtl_bindings: { - (stage: Compute, group: 0, binding: 1): (texture: Some(0), mutable: false), - (stage: Compute, group: 0, binding: 2): (texture: Some(1), mutable: true), - } + msl_custom: false, ) diff --git a/tests/in/quad-glsl.param.ron b/tests/in/quad-glsl.param.ron index 3fe357ca6..efded54c2 100644 --- a/tests/in/quad-glsl.param.ron +++ b/tests/in/quad-glsl.param.ron @@ -3,5 +3,5 @@ spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: true, - mtl_bindings: {} + msl_custom: false, ) diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index fcddac8b5..efded54c2 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -3,8 +3,5 @@ spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: true, - mtl_bindings: { - (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), - (stage: Fragment, group: 0, binding: 1): (sampler: Some(0)), - } + msl_custom: false, ) diff --git a/tests/in/shadow.param.ron b/tests/in/shadow.param.ron index 643ac437b..dc51d3ff4 100644 --- a/tests/in/shadow.param.ron +++ b/tests/in/shadow.param.ron @@ -4,10 +4,5 @@ spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: true, - mtl_bindings: { - (stage: Fragment, group: 0, binding: 0): (buffer: Some(0), mutable: false), - (stage: Fragment, group: 0, binding: 1): (buffer: Some(1), mutable: false), - (stage: Fragment, group: 0, binding: 2): (texture: Some(0), mutable: false), - (stage: Fragment, group: 0, binding: 3): (sampler: Some(0), mutable: false), - } + msl_custom: false, ) diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 237356912..30aded535 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -4,9 +4,16 @@ spv_capabilities: [ Shader ], spv_debug: false, spv_adjust_coordinate_space: false, - mtl_bindings: { - (stage: Vertex, group: 0, binding: 0): (buffer: Some(0)), - (stage: Fragment, group: 0, binding: 1): (texture: Some(0)), - (stage: Fragment, group: 0, binding: 2): (sampler: Some(1)), - } + msl_custom: true, + msl: ( + lang_version: (2, 1), + binding_map: { + (stage: Vertex, group: 0, binding: 0): (buffer: Some(0)), + (stage: Fragment, group: 0, binding: 1): (texture: Some(0)), + (stage: Fragment, group: 0, binding: 2): (sampler: Some(Resource(1))), + }, + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + ) ) diff --git a/tests/in/texture-array.param.ron b/tests/in/texture-array.param.ron index 6e3432a8a..b46594e31 100644 --- a/tests/in/texture-array.param.ron +++ b/tests/in/texture-array.param.ron @@ -4,9 +4,5 @@ spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: false, - mtl_bindings: { - (stage: Fragment, group: 0, binding: 0): (texture: Some(0)), - (stage: Fragment, group: 0, binding: 1): (texture: Some(1)), - (stage: Fragment, group: 0, binding: 2): (sampler: Some(0)), - } + msl_custom: false, ) diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index f921cb575..1a0e7d95d 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -39,7 +39,7 @@ struct main1Input { }; kernel void main1( type2 global_id [[thread_position_in_grid]] -, device PrimeIndices& v_indices [[buffer(0)]] +, device PrimeIndices& v_indices [[user(fake0)]] ) { type _expr9 = collatz_iterations(v_indices.data[global_id.x]); v_indices.data[global_id.x] = _expr9; diff --git a/tests/out/image-copy.msl.snap b/tests/out/image-copy.msl.snap index 81329b6bd..6584e9463 100644 --- a/tests/out/image-copy.msl.snap +++ b/tests/out/image-copy.msl.snap @@ -16,8 +16,8 @@ struct main1Input { }; kernel void main1( type2 local_id [[thread_position_in_threadgroup]] -, type image_src [[texture(0)]] -, type1 image_dst [[texture(1)]] +, type image_src [[user(fake0)]] +, type1 image_dst [[user(fake0)]] ) { metal::int2 _expr12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(const_10i, const_20i); metal::uint4 _expr13 = image_src.read(metal::uint2(_expr12)); diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index 084d7fb87..47a48a2d1 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -45,8 +45,8 @@ struct main2Output { }; fragment main2Output main2( main2Input varyings1 [[stage_in]] -, type3 u_texture [[texture(0)]] -, type4 u_sampler [[sampler(0)]] +, type3 u_texture [[user(fake0)]] +, type4 u_sampler [[user(fake0)]] ) { const auto uv2 = varyings1.uv2; metal::float4 _expr4 = u_texture.sample(u_sampler, uv2); diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index e2a9c1c86..94cd7982e 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -58,10 +58,10 @@ struct fs_mainOutput { }; fragment fs_mainOutput fs_main( fs_mainInput varyings [[stage_in]] -, constant Globals& u_globals [[buffer(0)]] -, constant Lights& s_lights [[buffer(1)]] -, type4 t_shadow [[texture(0)]] -, type5 sampler_shadow [[sampler(0)]] +, constant Globals& u_globals [[user(fake0)]] +, constant Lights& s_lights [[user(fake0)]] +, type4 t_shadow [[user(fake0)]] +, type5 sampler_shadow [[user(fake0)]] ) { const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index a42e7470f..e0c343c74 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -9,36 +9,6 @@ bitflags::bitflags! { } } -#[derive(Hash, PartialEq, Eq, serde::Deserialize)] -enum Stage { - Vertex, - Fragment, - Compute, -} - -#[derive(Hash, PartialEq, Eq, serde::Deserialize)] -struct BindSource { - stage: Stage, - group: u32, - binding: u32, -} - -#[derive(serde::Deserialize)] -struct BindTarget { - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - #[serde(default)] - buffer: Option, - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - #[serde(default)] - texture: Option, - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - #[serde(default)] - sampler: Option, - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - #[serde(default)] - mutable: bool, -} - #[derive(Default, serde::Deserialize)] struct Parameters { #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] @@ -49,8 +19,11 @@ struct Parameters { spv_debug: bool, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_adjust_coordinate_space: bool, - #[cfg_attr(not(feature = "msl-out"), allow(dead_code))] - mtl_bindings: naga::FastHashMap, + #[cfg(all(feature = "deserialize", feature = "msl-out"))] + #[serde(default)] + msl: naga::back::msl::Options, + #[cfg(all(not(feature = "deserialize"), feature = "msl-out"))] + msl_custom: bool, } #[allow(dead_code)] @@ -162,38 +135,23 @@ fn check_output_msl( ) { use naga::back::msl; - let mut binding_map = msl::BindingMap::default(); - for (key, value) in params.mtl_bindings.iter() { - binding_map.insert( - msl::BindSource { - stage: match key.stage { - Stage::Vertex => naga::ShaderStage::Vertex, - Stage::Fragment => naga::ShaderStage::Fragment, - Stage::Compute => naga::ShaderStage::Compute, - }, - group: key.group, - binding: key.binding, - }, - msl::BindTarget { - buffer: value.buffer, - texture: value.texture, - sampler: value.sampler.map(msl::BindSamplerTarget::Resource), - mutable: value.mutable, - }, - ); - } - let options = msl::Options { - lang_version: (1, 0), - binding_map, - inline_samplers: naga::Arena::new(), - spirv_cross_compatibility: false, - fake_missing_bindings: false, + #[cfg_attr(feature = "deserialize", allow(unused_variables))] + let default_options = msl::Options::default(); + #[cfg(feature = "deserialize")] + let options = ¶ms.msl; + #[cfg(not(feature = "deserialize"))] + let options = if params.msl_custom { + println!("Skipping {}", name); + return; + } else { + &default_options }; + let sub_options = msl::SubOptions { allow_point_size: true, }; - let (msl, _) = msl::write_string(module, info, &options, &sub_options).unwrap(); + let (msl, _) = msl::write_string(module, info, options, &sub_options).unwrap(); with_snapshot_settings(|| { insta::assert_snapshot!(format!("{}.msl", name), msl); From 499f2e3cbe6e8ab3e385a893d96cd29508a1b936 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 7 Apr 2021 10:50:34 -0400 Subject: [PATCH 0667/2212] [msl] add a snapshot test for inline sampler --- src/back/msl/writer.rs | 166 ++++++++++++++++++-------------------- tests/in/skybox.param.ron | 14 +++- tests/out/skybox.msl.snap | 9 ++- 3 files changed, 100 insertions(+), 89 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 5054c1f56..af5ba4c9c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -165,7 +165,6 @@ struct StatementContext<'a> { expression: ExpressionContext<'a>, mod_info: &'a ModuleInfo, result_struct: Option<&'a str>, - inline_global_handles: &'a BitSet, } impl Writer { @@ -1046,10 +1045,7 @@ impl Writer { let mut separate = !arguments.is_empty(); let fun_info = &context.mod_info[function]; for (handle, var) in context.expression.module.global_variables.iter() { - if !fun_info[handle].is_empty() - && !context.inline_global_handles.contains(handle.index()) - && var.class.needs_pass_through() - { + if !fun_info[handle].is_empty() && var.class.needs_pass_through() { let name = &self.names[&NameKey::GlobalVariable(handle)]; if separate { write!(self.out, ", ")?; @@ -1322,60 +1318,64 @@ impl Writer { Ok(()) } - fn write_inline_sampler( + fn put_inline_sampler_properties( &mut self, + level: Level, sampler: &sm::InlineSampler, - stage: crate::ShaderStage, - handle: Handle, ) -> Result<(), Error> { - write!( - self.out, - "constexpr sampler ism_{}_{:?}(", - handle.index(), - stage - )?; for (&letter, address) in ['s', 't', 'r'].iter().zip(sampler.address.iter()) { - write!( + writeln!( self.out, - "{}{}_address::{},", - INDENT, + "{}{}::{}_address::{},", + level, + NAMESPACE, letter, - address.as_str() + address.as_str(), )?; } - write!( + writeln!( self.out, - "{}mag_filter::{},", - INDENT, - sampler.mag_filter.as_str() + "{}{}::mag_filter::{},", + level, + NAMESPACE, + sampler.mag_filter.as_str(), )?; - write!( + writeln!( self.out, - "{}min_filter::{},", - INDENT, - sampler.min_filter.as_str() + "{}{}::min_filter::{},", + level, + NAMESPACE, + sampler.min_filter.as_str(), )?; if let Some(filter) = sampler.mip_filter { - write!(self.out, "{}mip_filter::{},", INDENT, filter.as_str())?; + writeln!( + self.out, + "{}{}::mip_filter::{},", + level, + NAMESPACE, + filter.as_str(), + )?; } // avoid setting it on platforms that don't support it if sampler.border_color != sm::BorderColor::TransparentBlack { - write!( + writeln!( self.out, - "{}border_color::{},", - INDENT, - sampler.border_color.as_str() + "{}{}::border_color::{},", + level, + NAMESPACE, + sampler.border_color.as_str(), )?; } if sampler.compare_func != sm::CompareFunc::Never { - write!( + writeln!( self.out, - "{}compare_func::{},", - INDENT, - sampler.compare_func.as_str() + "{}{}::compare_func::{},", + level, + NAMESPACE, + sampler.compare_func.as_str(), )?; } - writeln!(self.out, "{}coord::normalized);", INDENT)?; + writeln!(self.out, "{}{}::coord::normalized", NAMESPACE, level)?; Ok(()) } @@ -1387,38 +1387,12 @@ impl Writer { options: &Options, sub_options: &SubOptions, ) -> Result { - // first, write down immutable samplers as const expressions - let mut inline_global_handles = BitSet::new(); - for (handle, var) in module.global_variables.iter() { - let binding = match var.binding { - Some(ref binding) => binding, - None => continue, - }; - for &stage in [ - crate::ShaderStage::Vertex, - crate::ShaderStage::Fragment, - crate::ShaderStage::Compute, - ] - .iter() - { - if let Ok(resolved) = options.resolve_global_binding(stage, binding) { - if let Some(sampler) = resolved.as_inline_sampler(options) { - inline_global_handles.insert(handle.index()); - self.write_inline_sampler(sampler, stage, handle)?; - } - } - } - } - let mut pass_through_globals = Vec::new(); for (fun_handle, fun) in module.functions.iter() { let fun_info = &mod_info[fun_handle]; pass_through_globals.clear(); for (handle, var) in module.global_variables.iter() { - if !fun_info[handle].is_empty() - && !inline_global_handles.contains(handle.index()) - && var.class.needs_pass_through() - { + if !fun_info[handle].is_empty() && var.class.needs_pass_through() { pass_through_globals.push(handle); } } @@ -1477,7 +1451,6 @@ impl Writer { }, mod_info, result_struct: None, - inline_global_handles: &inline_global_handles, }; self.named_expressions.clear(); self.put_block(Level(1), &fun.body, &context)?; @@ -1648,12 +1621,20 @@ impl Writer { } for (handle, var) in module.global_variables.iter() { let usage = fun_info[handle]; - if usage.is_empty() - || var.class == crate::StorageClass::Private - || inline_global_handles.contains(handle.index()) - { + if usage.is_empty() || var.class == crate::StorageClass::Private { continue; } + let resolved = var + .binding + .as_ref() + .map(|binding| options.resolve_global_binding(ep.stage, binding).unwrap()); + if let Some(ref resolved) = resolved { + // Inline samplers are be defined in the EP body + if resolved.as_inline_sampler(options).is_some() { + continue; + } + } + let tyvar = TypedGlobalVariable { module, names: &self.names, @@ -1669,8 +1650,7 @@ impl Writer { }; write!(self.out, "{} ", separator)?; tyvar.try_fmt(&mut self.out)?; - if let Some(ref binding) = var.binding { - let resolved = options.resolve_global_binding(ep.stage, binding).unwrap(); + if let Some(resolved) = resolved { resolved.try_fmt_decorated(&mut self.out, "")?; } if let Some(value) = var.init { @@ -1687,23 +1667,38 @@ impl Writer { // so we put them here, just like the locals. for (handle, var) in module.global_variables.iter() { let usage = fun_info[handle]; - if usage.is_empty() || var.class != crate::StorageClass::Private { + if usage.is_empty() { continue; } - let tyvar = TypedGlobalVariable { - module, - names: &self.names, - handle, - usage, - reference: false, - }; - write!(self.out, "{}", INDENT)?; - tyvar.try_fmt(&mut self.out)?; - let value_str = match var.init { - Some(value) => &self.names[&NameKey::Constant(value)], - None => "{}", - }; - writeln!(self.out, " = {};", value_str)?; + if var.class == crate::StorageClass::Private { + let tyvar = TypedGlobalVariable { + module, + names: &self.names, + handle, + usage, + reference: false, + }; + write!(self.out, "{}", INDENT)?; + tyvar.try_fmt(&mut self.out)?; + let value_str = match var.init { + Some(value) => &self.names[&NameKey::Constant(value)], + None => "{}", + }; + writeln!(self.out, " = {};", value_str)?; + } else if let Some(ref binding) = var.binding { + // write an inline sampler + let resolved = options.resolve_global_binding(ep.stage, binding).unwrap(); + if let Some(sampler) = resolved.as_inline_sampler(options) { + let name = &self.names[&NameKey::GlobalVariable(handle)]; + writeln!( + self.out, + "{}constexpr {}::sampler {}(", + INDENT, NAMESPACE, name + )?; + self.put_inline_sampler_properties(Level(2), sampler)?; + writeln!(self.out, "{});", INDENT)?; + } + } } // Now refactor the inputs in a way that the rest of the code expects @@ -1769,7 +1764,6 @@ impl Writer { }, mod_info, result_struct: Some(&stage_out_name), - inline_global_handles: &inline_global_handles, }; self.named_expressions.clear(); self.put_block(Level(1), &fun.body, &context)?; diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 30aded535..6e23a1118 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -10,9 +10,19 @@ binding_map: { (stage: Vertex, group: 0, binding: 0): (buffer: Some(0)), (stage: Fragment, group: 0, binding: 1): (texture: Some(0)), - (stage: Fragment, group: 0, binding: 2): (sampler: Some(Resource(1))), + (stage: Fragment, group: 0, binding: 2): (sampler: Some(Inline(1))), }, - inline_samplers: [], + inline_samplers: [ + ( + coord: Normalized, + address: (ClampToEdge, ClampToEdge, ClampToEdge), + mag_filter: Linear, + min_filter: Linear, + mip_filter: None, + border_color: TransparentBlack, + compare_func: Never, + ), + ], spirv_cross_compatibility: false, fake_missing_bindings: false, ) diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 1fbf706d9..5c5448e78 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -59,8 +59,15 @@ fragment fs_mainOutput fs_main( fs_mainInput varyings1 [[stage_in]] , type position [[position]] , type6 r_texture [[texture(0)]] -, type7 r_sampler [[sampler(1)]] ) { + constexpr metal::sampler r_sampler( + metal::s_address::clamp_to_edge, + metal::t_address::clamp_to_edge, + metal::r_address::clamp_to_edge, + metal::mag_filter::linear, + metal::min_filter::linear, +metal ::coord::normalized + ); const VertexOutput in = { position, varyings1.uv }; metal::float4 _expr5 = r_texture.sample(r_sampler, in.uv); return fs_mainOutput { _expr5 }; From e06451777e88d6b006e8f5fac2dd165e4a071bb1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 7 Apr 2021 22:44:41 -0400 Subject: [PATCH 0668/2212] [msl] address review comments, rename SubOptions to PipelineOptions, add more inlined states --- bin/convert.rs | 12 ++++++++---- src/back/msl/mod.rs | 12 ++++++------ src/back/msl/sampler.rs | 12 ++++++++++++ src/back/msl/writer.rs | 38 ++++++++++++++++++++++++++++---------- tests/in/skybox.param.ron | 2 ++ tests/out/skybox.msl.snap | 2 +- tests/snapshots.rs | 4 ++-- 7 files changed, 59 insertions(+), 23 deletions(-) diff --git a/bin/convert.rs b/bin/convert.rs index b6aaba122..343155326 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -202,10 +202,14 @@ fn main() { #[cfg(feature = "msl-out")] "metal" => { use naga::back::msl; - let sub_options = msl::SubOptions::default(); - let (msl, _) = - msl::write_string(&module, info.as_ref().unwrap(), ¶ms.msl, &sub_options) - .unwrap_pretty(); + let pipeline_options = msl::PipelineOptions::default(); + let (msl, _) = msl::write_string( + &module, + info.as_ref().unwrap(), + ¶ms.msl, + &pipeline_options, + ) + .unwrap_pretty(); fs::write(output_path, msl).unwrap(); } #[cfg(feature = "spv-out")] diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 234aaf284..ad78a5bd0 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -31,7 +31,7 @@ use crate::{ use std::fmt::{Error as FmtError, Write}; mod keywords; -mod sampler; +pub mod sampler; mod writer; pub use writer::Writer; @@ -138,15 +138,15 @@ impl Default for Options { // A subset of options that are meant to be changed per pipeline. #[derive(Debug, Clone)] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] -pub struct SubOptions { +pub struct PipelineOptions { /// Allow `BuiltIn::PointSize` in the vertex shader. /// Metal doesn't like this for non-point primitive topologies. pub allow_point_size: bool, } -impl Default for SubOptions { +impl Default for PipelineOptions { fn default() -> Self { - SubOptions { + PipelineOptions { allow_point_size: true, } } @@ -281,10 +281,10 @@ pub fn write_string( module: &crate::Module, info: &ModuleInfo, options: &Options, - sub_options: &SubOptions, + pipeline_options: &PipelineOptions, ) -> Result<(String, TranslationInfo), Error> { let mut w = writer::Writer::new(String::new()); - let info = w.write(module, info, options, sub_options)?; + let info = w.write(module, info, options, pipeline_options)?; Ok((w.finish(), info)) } diff --git a/src/back/msl/sampler.rs b/src/back/msl/sampler.rs index be44045c7..7d76aac92 100644 --- a/src/back/msl/sampler.rs +++ b/src/back/msl/sampler.rs @@ -1,5 +1,6 @@ #[cfg(feature = "deserialize")] use serde::Deserialize; +use std::{num::NonZeroU32, ops::Range}; #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "deserialize", derive(Deserialize))] @@ -14,6 +15,15 @@ impl Default for Coord { } } +impl Coord { + pub fn as_str(&self) -> &'static str { + match *self { + Self::Normalized => "normalized", + Self::Pixel => "pixel", + } + } +} + #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Address { @@ -131,5 +141,7 @@ pub struct InlineSampler { pub mag_filter: Filter, pub min_filter: Filter, pub mip_filter: Option, + pub lod_clamp: Option>, + pub max_anisotropy: Option, pub compare_func: CompareFunc, } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index af5ba4c9c..5d62e7907 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,5 +1,6 @@ use super::{ - keywords::RESERVED, sampler as sm, Error, LocationMode, Options, SubOptions, TranslationInfo, + keywords::RESERVED, sampler as sm, Error, LocationMode, Options, PipelineOptions, + TranslationInfo, }; use crate::{ arena::Handle, @@ -152,7 +153,7 @@ struct ExpressionContext<'a> { origin: FunctionOrigin, info: &'a FunctionInfo, module: &'a crate::Module, - sub_options: &'a SubOptions, + pipeline_options: &'a PipelineOptions, } impl<'a> ExpressionContext<'a> { @@ -775,7 +776,7 @@ impl Writer { write!(self.out, "{}return {} {{", level, struct_name)?; let mut is_first = true; for (index, member) in members.iter().enumerate() { - if !context.sub_options.allow_point_size + if !context.pipeline_options.allow_point_size && member.binding == Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) { @@ -1078,7 +1079,7 @@ impl Writer { module: &crate::Module, info: &ModuleInfo, options: &Options, - sub_options: &SubOptions, + pipeline_options: &PipelineOptions, ) -> Result { self.names.clear(); self.namer.reset(module, RESERVED, &mut self.names); @@ -1090,7 +1091,7 @@ impl Writer { self.write_scalar_constants(module)?; self.write_type_defs(module)?; self.write_composite_constants(module)?; - self.write_functions(module, info, options, sub_options) + self.write_functions(module, info, options, pipeline_options) } fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { @@ -1366,6 +1367,17 @@ impl Writer { sampler.border_color.as_str(), )?; } + //TODO: I'm not able to feed this in a way that MSL likes: + //>error: use of undeclared identifier 'lod_clamp' + //>error: no member named 'max_anisotropy' in namespace 'metal' + if false { + if let Some(ref lod) = sampler.lod_clamp { + writeln!(self.out, "{}lod_clamp({},{}),", level, lod.start, lod.end,)?; + } + if let Some(aniso) = sampler.max_anisotropy { + writeln!(self.out, "{}max_anisotropy({}),", level, aniso.get(),)?; + } + } if sampler.compare_func != sm::CompareFunc::Never { writeln!( self.out, @@ -1375,7 +1387,13 @@ impl Writer { sampler.compare_func.as_str(), )?; } - writeln!(self.out, "{}{}::coord::normalized", NAMESPACE, level)?; + writeln!( + self.out, + "{}{}::coord::{}", + level, + NAMESPACE, + sampler.coord.as_str() + )?; Ok(()) } @@ -1385,7 +1403,7 @@ impl Writer { module: &crate::Module, mod_info: &ModuleInfo, options: &Options, - sub_options: &SubOptions, + pipeline_options: &PipelineOptions, ) -> Result { let mut pass_through_globals = Vec::new(); for (fun_handle, fun) in module.functions.iter() { @@ -1447,7 +1465,7 @@ impl Writer { origin: FunctionOrigin::Handle(fun_handle), info: fun_info, module, - sub_options, + pipeline_options, }, mod_info, result_struct: None, @@ -1576,7 +1594,7 @@ impl Writer { for (name, ty, binding) in result_members { let type_name = &self.names[&NameKey::Type(ty)]; let binding = binding.ok_or(Error::Validation)?; - if !sub_options.allow_point_size + if !pipeline_options.allow_point_size && *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize) { continue; @@ -1760,7 +1778,7 @@ impl Writer { origin: FunctionOrigin::EntryPoint(ep_index as _), info: fun_info, module, - sub_options, + pipeline_options, }, mod_info, result_struct: Some(&stage_out_name), diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 6e23a1118..9a85ec2d0 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -21,6 +21,8 @@ mip_filter: None, border_color: TransparentBlack, compare_func: Never, + lod_clamp: Some((start: 0.5, end: 10.0)), + max_anisotropy: Some(8), ), ], spirv_cross_compatibility: false, diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 5c5448e78..5fde02477 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -66,7 +66,7 @@ fragment fs_mainOutput fs_main( metal::r_address::clamp_to_edge, metal::mag_filter::linear, metal::min_filter::linear, -metal ::coord::normalized + metal::coord::normalized ); const VertexOutput in = { position, varyings1.uv }; metal::float4 _expr5 = r_texture.sample(r_sampler, in.uv); diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e0c343c74..6cb1d3846 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -147,11 +147,11 @@ fn check_output_msl( &default_options }; - let sub_options = msl::SubOptions { + let pipeline_options = msl::PipelineOptions { allow_point_size: true, }; - let (msl, _) = msl::write_string(module, info, options, &sub_options).unwrap(); + let (msl, _) = msl::write_string(module, info, options, &pipeline_options).unwrap(); with_snapshot_settings(|| { insta::assert_snapshot!(format!("{}.msl", name), msl); From f1c5e04b89c2bd783d34fae66fc66c5d03b2f202 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 7 Apr 2021 23:42:23 -0400 Subject: [PATCH 0669/2212] [msl] fix select() arguments --- src/back/msl/writer.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 5d62e7907..bea412cda 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -619,10 +619,10 @@ impl Writer { .. } => { write!(self.out, "{}::select(", NAMESPACE)?; - self.put_expression(accept, context, true)?; - write!(self.out, ", ")?; self.put_expression(reject, context, true)?; write!(self.out, ", ")?; + self.put_expression(accept, context, true)?; + write!(self.out, ", ")?; self.put_expression(condition, context, true)?; write!(self.out, ")")?; } From 2774dcb40359349753a8825eca947508e770aa1f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 8 Apr 2021 11:00:11 -0400 Subject: [PATCH 0670/2212] [msl] inline some of the types --- src/back/msl/writer.rs | 444 ++++++++++++++++++++++------------ tests/out/boids.msl.snap | 46 ++-- tests/out/collatz.msl.snap | 17 +- tests/out/empty.msl.snap | 1 + tests/out/image-copy.msl.snap | 12 +- tests/out/quad-vert.msl.snap | 46 ++-- tests/out/quad.msl.snap | 27 +-- tests/out/shadow.msl.snap | 46 ++-- tests/out/skybox.msl.snap | 38 ++- 9 files changed, 390 insertions(+), 287 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index bea412cda..0c4979a89 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3,7 +3,7 @@ use super::{ TranslationInfo, }; use crate::{ - arena::Handle, + arena::{Arena, Handle}, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, GlobalUse, ModuleInfo}, FastHashMap, @@ -31,6 +31,154 @@ impl Display for Level { } } +struct TypeContext<'a> { + handle: Handle, + arena: &'a Arena, + names: &'a FastHashMap, + usage: GlobalUse, + access: crate::StorageAccess, + first_time: bool, +} + +impl<'a> Display for TypeContext<'a> { + fn fmt(&self, out: &mut Formatter<'_>) -> Result<(), FmtError> { + let ty = &self.arena[self.handle]; + if ty.needs_alias() && !self.first_time { + let name = &self.names[&NameKey::Type(self.handle)]; + return write!(out, "{}", name); + } + + match ty.inner { + // work around Metal toolchain bug with `uint` typedef + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } => { + write!(out, "metal::uint") + } + crate::TypeInner::Scalar { kind, .. } => { + write!(out, "{}", scalar_kind_string(kind)) + } + crate::TypeInner::Vector { size, kind, .. } => { + write!( + out, + "{}::{}{}", + NAMESPACE, + scalar_kind_string(kind), + vector_size_string(size), + ) + } + crate::TypeInner::Matrix { columns, rows, .. } => { + write!( + out, + "{}::{}{}x{}", + NAMESPACE, + scalar_kind_string(crate::ScalarKind::Float), + vector_size_string(columns), + vector_size_string(rows), + ) + } + crate::TypeInner::Pointer { base, class } => { + let sub = Self { + arena: self.arena, + names: self.names, + handle: base, + usage: self.usage, + access: self.access, + first_time: false, + }; + let class_name = match class.get_name(self.usage) { + Some(name) => name, + None => return Ok(()), + }; + write!(out, "{} {}*", class_name, sub) + } + crate::TypeInner::ValuePointer { + size: None, + kind, + width: _, + class, + } => { + let class_name = match class.get_name(self.usage) { + Some(name) => name, + None => return Ok(()), + }; + write!(out, "{} {}*", class_name, scalar_kind_string(kind),) + } + crate::TypeInner::ValuePointer { + size: Some(size), + kind, + width: _, + class, + } => { + let class_name = match class.get_name(self.usage) { + Some(name) => name, + None => return Ok(()), + }; + write!( + out, + "{} {}::{}{}*", + class_name, + NAMESPACE, + scalar_kind_string(kind), + vector_size_string(size), + ) + } + crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => unreachable!(), + crate::TypeInner::Image { + dim, + arrayed, + class, + } => { + let dim_str = match dim { + crate::ImageDimension::D1 => "1d", + crate::ImageDimension::D2 => "2d", + crate::ImageDimension::D3 => "3d", + crate::ImageDimension::Cube => "cube", + }; + let (texture_str, msaa_str, kind, access) = match class { + crate::ImageClass::Sampled { kind, multi } => { + ("texture", if multi { "_ms" } else { "" }, kind, "sample") + } + crate::ImageClass::Depth => ("depth", "", crate::ScalarKind::Float, "sample"), + crate::ImageClass::Storage(format) => { + let access = if self + .access + .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) + { + "read_write" + } else if self.access.contains(crate::StorageAccess::STORE) { + "write" + } else if self.access.contains(crate::StorageAccess::LOAD) { + "read" + } else { + unreachable!("module is not valid") + }; + ("texture", "", format.into(), access) + } + }; + let base_name = scalar_kind_string(kind); + let array_str = if arrayed { "_array" } else { "" }; + write!( + out, + "{}::{}{}{}{}<{}, {}::access::{}>", + NAMESPACE, + texture_str, + dim_str, + msaa_str, + array_str, + base_name, + NAMESPACE, + access, + ) + } + crate::TypeInner::Sampler { comparison: _ } => { + write!(out, "{}::sampler", NAMESPACE) + } + } + } +} + struct TypedGlobalVariable<'a> { module: &'a crate::Module, names: &'a FastHashMap, @@ -43,7 +191,14 @@ impl<'a> TypedGlobalVariable<'a> { fn try_fmt(&self, out: &mut W) -> Result<(), Error> { let var = &self.module.global_variables[self.handle]; let name = &self.names[&NameKey::GlobalVariable(self.handle)]; - let ty_name = &self.names[&NameKey::Type(var.ty)]; + let ty_name = TypeContext { + handle: var.ty, + arena: &self.module.types, + names: self.names, + usage: self.usage, + access: var.storage_access, + first_time: false, + }; let (space, access, reference) = match var.class.get_name(self.usage) { Some(space) if self.reference => { @@ -143,6 +298,25 @@ impl crate::StorageClass { } } +impl crate::Type { + // Returns `true` if we need to emit a type alias for this type. + fn needs_alias(&self) -> bool { + use crate::TypeInner as Ti; + match self.inner { + // value types are concise enough, we only alias them if they are named + Ti::Scalar { .. } + | Ti::Vector { .. } + | Ti::Matrix { .. } + | Ti::Pointer { .. } + | Ti::ValuePointer { .. } => self.name.is_some(), + // composite types are better to be aliased, regardless of the name + Ti::Struct { .. } | Ti::Array { .. } => true, + // handle types may be different, depending on the global var access, so we always inline them + Ti::Image { .. } | Ti::Sampler { .. } => false, + } + } +} + enum FunctionOrigin { Handle(Handle), EntryPoint(EntryPointIndex), @@ -830,7 +1004,14 @@ impl Writer { ) -> Result<(), Error> { match context.info[handle].ty { TypeResolution::Handle(ty_handle) => { - let ty_name = &self.names[&NameKey::Type(ty_handle)]; + let ty_name = TypeContext { + handle: ty_handle, + arena: &context.module.types, + names: &self.names, + usage: GlobalUse::all(), + access: crate::StorageAccess::empty(), + first_time: false, + }; write!(self.out, "{}", ty_name)?; } TypeResolution::Value(crate::TypeInner::Scalar { kind, .. }) => { @@ -1096,92 +1277,25 @@ impl Writer { fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { for (handle, ty) in module.types.iter() { + if !ty.needs_alias() { + continue; + } let name = &self.names[&NameKey::Type(handle)]; let global_use = GlobalUse::all(); //TODO match ty.inner { - // work around Metal toolchain bug with `uint` typedef - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - .. - } => { - writeln!(self.out, "typedef metal::uint {};", name)?; - } - crate::TypeInner::Scalar { kind, .. } => { - writeln!(self.out, "typedef {} {};", scalar_kind_string(kind), name)?; - } - crate::TypeInner::Vector { size, kind, .. } => { - writeln!( - self.out, - "typedef {}::{}{} {};", - NAMESPACE, - scalar_kind_string(kind), - vector_size_string(size), - name - )?; - } - crate::TypeInner::Matrix { columns, rows, .. } => { - writeln!( - self.out, - "typedef {}::{}{}x{} {};", - NAMESPACE, - scalar_kind_string(crate::ScalarKind::Float), - vector_size_string(columns), - vector_size_string(rows), - name - )?; - } - crate::TypeInner::Pointer { base, class } => { - let base_name = &self.names[&NameKey::Type(base)]; - let class_name = match class.get_name(global_use) { - Some(name) => name, - None => continue, - }; - writeln!(self.out, "typedef {} {} *{};", class_name, base_name, name)?; - } - crate::TypeInner::ValuePointer { - size: None, - kind, - width: _, - class, - } => { - let class_name = match class.get_name(global_use) { - Some(name) => name, - None => continue, - }; - writeln!( - self.out, - "typedef {} {} *{};", - class_name, - scalar_kind_string(kind), - name - )?; - } - crate::TypeInner::ValuePointer { - size: Some(size), - kind, - width: _, - class, - } => { - let class_name = match class.get_name(global_use) { - Some(name) => name, - None => continue, - }; - writeln!( - self.out, - "typedef {} {}::{}{} {};", - class_name, - NAMESPACE, - scalar_kind_string(kind), - vector_size_string(size), - name - )?; - } crate::TypeInner::Array { base, size, stride: _, } => { - let base_name = &self.names[&NameKey::Type(base)]; + let base_name = TypeContext { + handle: base, + arena: &module.types, + names: &self.names, + usage: global_use, + access: crate::StorageAccess::empty(), + first_time: false, + }; let size_str = match size { crate::ArraySize::Constant(const_handle) => { &self.names[&NameKey::Constant(const_handle)] @@ -1197,68 +1311,28 @@ impl Writer { writeln!(self.out, "struct {} {{", name)?; for (index, member) in members.iter().enumerate() { let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; - let base_name = &self.names[&NameKey::Type(member.ty)]; + let base_name = TypeContext { + handle: member.ty, + arena: &module.types, + names: &self.names, + usage: global_use, + access: crate::StorageAccess::empty(), + first_time: false, + }; writeln!(self.out, "{}{} {};", INDENT, base_name, member_name)?; } writeln!(self.out, "}};")?; } - crate::TypeInner::Image { - dim, - arrayed, - class, - } => { - let dim_str = match dim { - crate::ImageDimension::D1 => "1d", - crate::ImageDimension::D2 => "2d", - crate::ImageDimension::D3 => "3d", - crate::ImageDimension::Cube => "cube", + _ => { + let ty_name = TypeContext { + handle, + arena: &module.types, + names: &self.names, + usage: global_use, + access: crate::StorageAccess::empty(), + first_time: true, }; - let (texture_str, msaa_str, kind, access) = match class { - crate::ImageClass::Sampled { kind, multi } => { - ("texture", if multi { "_ms" } else { "" }, kind, "sample") - } - crate::ImageClass::Depth => { - ("depth", "", crate::ScalarKind::Float, "sample") - } - crate::ImageClass::Storage(format) => { - let (_, global) = module - .global_variables - .iter() - .find(|&(_, ref var)| var.ty == handle) - .expect("Unable to find a global variable using the image type"); - let access = if global - .storage_access - .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) - { - "read_write" - } else if global.storage_access.contains(crate::StorageAccess::STORE) { - "write" - } else if global.storage_access.contains(crate::StorageAccess::LOAD) { - "read" - } else { - return Err(Error::Validation); - }; - ("texture", "", format.into(), access) - } - }; - let base_name = scalar_kind_string(kind); - let array_str = if arrayed { "_array" } else { "" }; - writeln!( - self.out, - "typedef {}::{}{}{}{}<{}, {}::access::{}> {};", - NAMESPACE, - texture_str, - dim_str, - msaa_str, - array_str, - base_name, - NAMESPACE, - access, - name - )?; - } - crate::TypeInner::Sampler { comparison: _ } => { - writeln!(self.out, "typedef {}::sampler {};", NAMESPACE, name)?; + writeln!(self.out, "typedef {} {};", ty_name, name)?; } } } @@ -1305,7 +1379,14 @@ impl Writer { crate::ConstantInner::Scalar { .. } => {} crate::ConstantInner::Composite { ty, ref components } => { let name = &self.names[&NameKey::Constant(handle)]; - let ty_name = &self.names[&NameKey::Type(ty)]; + let ty_name = TypeContext { + handle: ty, + arena: &module.types, + names: &self.names, + usage: GlobalUse::empty(), + access: crate::StorageAccess::empty(), + first_time: false, + }; write!(self.out, "constexpr constant {} {} = {{", ty_name, name,)?; for (i, &sub_handle) in components.iter().enumerate() { let separator = if i != 0 { ", " } else { "" }; @@ -1415,16 +1496,36 @@ impl Writer { } } + writeln!(self.out)?; let fun_name = &self.names[&NameKey::Function(fun_handle)]; - let result_type_name = match fun.result { - Some(ref result) => &self.names[&NameKey::Type(result.ty)], - None => "void", - }; - writeln!(self.out, "{} {}(", result_type_name, fun_name)?; + match fun.result { + Some(ref result) => { + let ty_name = TypeContext { + handle: result.ty, + arena: &module.types, + names: &self.names, + usage: GlobalUse::empty(), + access: crate::StorageAccess::empty(), + first_time: false, + }; + write!(self.out, "{}", ty_name)?; + } + None => { + write!(self.out, "void")?; + } + } + writeln!(self.out, " {}(", fun_name)?; for (index, arg) in fun.arguments.iter().enumerate() { let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; - let param_type_name = &self.names[&NameKey::Type(arg.ty)]; + let param_type_name = TypeContext { + handle: arg.ty, + arena: &module.types, + names: &self.names, + usage: GlobalUse::empty(), + access: crate::StorageAccess::empty(), + first_time: false, + }; let separator = separate(!pass_through_globals.is_empty() || index + 1 != fun.arguments.len()); writeln!( @@ -1449,7 +1550,14 @@ impl Writer { writeln!(self.out, ") {{")?; for (local_handle, local) in fun.local_variables.iter() { - let ty_name = &self.names[&NameKey::Type(local.ty)]; + let ty_name = TypeContext { + handle: local.ty, + arena: &module.types, + names: &self.names, + usage: GlobalUse::empty(), + access: crate::StorageAccess::empty(), + first_time: false, + }; let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; write!(self.out, "{}{} {}", INDENT, ty_name, local_name)?; if let Some(value) = local.init { @@ -1473,7 +1581,6 @@ impl Writer { self.named_expressions.clear(); self.put_block(Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; - writeln!(self.out)?; } let mut info = TranslationInfo { @@ -1503,6 +1610,7 @@ impl Writer { } } + writeln!(self.out)?; let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; info.entry_point_names.push(Ok(fun_name.clone())); @@ -1558,9 +1666,16 @@ impl Writer { }; varying_count += 1; let name = &self.names[&name_key]; - let type_name = &self.names[&NameKey::Type(ty)]; + let ty_name = TypeContext { + handle: ty, + arena: &module.types, + names: &self.names, + usage: GlobalUse::empty(), + access: crate::StorageAccess::empty(), + first_time: false, + }; let resolved = options.resolve_local_binding(binding, in_mode)?; - write!(self.out, "{}{} {}", INDENT, type_name, name)?; + write!(self.out, "{}{} {}", INDENT, ty_name, name)?; resolved.try_fmt_decorated(&mut self.out, "")?; writeln!(self.out, ";")?; } @@ -1592,7 +1707,14 @@ impl Writer { } writeln!(self.out, "struct {} {{", stage_out_name)?; for (name, ty, binding) in result_members { - let type_name = &self.names[&NameKey::Type(ty)]; + let ty_name = TypeContext { + handle: ty, + arena: &module.types, + names: &self.names, + usage: GlobalUse::empty(), + access: crate::StorageAccess::empty(), + first_time: false, + }; let binding = binding.ok_or(Error::Validation)?; if !pipeline_options.allow_point_size && *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize) @@ -1600,7 +1722,7 @@ impl Writer { continue; } let resolved = options.resolve_local_binding(binding, out_mode)?; - write!(self.out, "{}{} {}", INDENT, type_name, name)?; + write!(self.out, "{}{} {}", INDENT, ty_name, name)?; resolved.try_fmt_decorated(&mut self.out, "")?; writeln!(self.out, ";")?; } @@ -1626,7 +1748,14 @@ impl Writer { _ => continue, }; let name = &self.names[&name_key]; - let type_name = &self.names[&NameKey::Type(ty)]; + let ty_name = TypeContext { + handle: ty, + arena: &module.types, + names: &self.names, + usage: GlobalUse::empty(), + access: crate::StorageAccess::empty(), + first_time: false, + }; let resolved = options.resolve_local_binding(binding, in_mode)?; let separator = if is_first_argument { is_first_argument = false; @@ -1634,7 +1763,7 @@ impl Writer { } else { ',' }; - write!(self.out, "{} {} {}", separator, type_name, name)?; + write!(self.out, "{} {} {}", separator, ty_name, name)?; resolved.try_fmt_decorated(&mut self.out, "\n")?; } for (handle, var) in module.global_variables.iter() { @@ -1763,7 +1892,14 @@ impl Writer { //TODO: we can postpone this till the relevant expressions are emitted for (local_handle, local) in fun.local_variables.iter() { let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; - let ty_name = &self.names[&NameKey::Type(local.ty)]; + let ty_name = TypeContext { + handle: local.ty, + arena: &module.types, + names: &self.names, + usage: GlobalUse::empty(), + access: crate::StorageAccess::empty(), + first_time: false, + }; write!(self.out, "{}{} {}", INDENT, ty_name, name)?; if let Some(value) = local.init { let value_str = &self.names[&NameKey::Constant(value)]; diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index e690e2ccd..9f302992a 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -14,46 +14,42 @@ constexpr constant unsigned const_1u = 1u; constexpr constant float const_1f = 1.0; constexpr constant float const_0_10f = 0.1; constexpr constant float const_n1f = -1.0; -typedef metal::uint type; -typedef metal::float2 type1; struct Particle { - type1 pos; - type1 vel; + metal::float2 pos; + metal::float2 vel; }; -typedef float type2; struct SimParams { - type2 deltaT; - type2 rule1Distance; - type2 rule2Distance; - type2 rule3Distance; - type2 rule1Scale; - type2 rule2Scale; - type2 rule3Scale; + float deltaT; + float rule1Distance; + float rule2Distance; + float rule3Distance; + float rule1Scale; + float rule2Scale; + float rule3Scale; }; typedef Particle type3[1]; struct Particles { type3 particles; }; -typedef metal::uint3 type4; -typedef int type5; + struct main1Input { }; kernel void main1( - type4 global_invocation_id [[thread_position_in_grid]] + metal::uint3 global_invocation_id [[thread_position_in_grid]] , constant SimParams& params [[buffer(0)]] , constant Particles& particlesSrc [[buffer(1)]] , device Particles& particlesDst [[buffer(2)]] ) { - type1 vPos; - type1 vVel; - type1 cMass; - type1 cVel; - type1 colVel; - type5 cMassCount = const_0i; - type5 cVelCount = const_0i; - type1 pos1; - type1 vel1; - type i = const_0u; + metal::float2 vPos; + metal::float2 vVel; + metal::float2 cMass; + metal::float2 cVel; + metal::float2 colVel; + int cMassCount = const_0i; + int cVelCount = const_0i; + metal::float2 pos1; + metal::float2 vel1; + metal::uint i = const_0u; if (global_invocation_id.x >= NUM_PARTICLES) { return; } diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index 1a0e7d95d..2aa4fe344 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -9,17 +9,16 @@ constexpr constant unsigned const_0u = 0u; constexpr constant unsigned const_1u = 1u; constexpr constant unsigned const_2u = 2u; constexpr constant unsigned const_3u = 3u; -typedef metal::uint type; -typedef type type1[1]; +typedef metal::uint type1[1]; struct PrimeIndices { type1 data; }; -typedef metal::uint3 type2; -type collatz_iterations( - type n_base + +metal::uint collatz_iterations( + metal::uint n_base ) { - type n; - type i = const_0u; + metal::uint n; + metal::uint i = const_0u; n = n_base; while(true) { if (n <= const_1u) { @@ -38,10 +37,10 @@ type collatz_iterations( struct main1Input { }; kernel void main1( - type2 global_id [[thread_position_in_grid]] + metal::uint3 global_id [[thread_position_in_grid]] , device PrimeIndices& v_indices [[user(fake0)]] ) { - type _expr9 = collatz_iterations(v_indices.data[global_id.x]); + metal::uint _expr9 = collatz_iterations(v_indices.data[global_id.x]); v_indices.data[global_id.x] = _expr9; return; } diff --git a/tests/out/empty.msl.snap b/tests/out/empty.msl.snap index 6cbbbb4bd..9d081189a 100644 --- a/tests/out/empty.msl.snap +++ b/tests/out/empty.msl.snap @@ -5,6 +5,7 @@ expression: msl #include #include + kernel void main1( ) { return; diff --git a/tests/out/image-copy.msl.snap b/tests/out/image-copy.msl.snap index 6584e9463..3b9ca6f74 100644 --- a/tests/out/image-copy.msl.snap +++ b/tests/out/image-copy.msl.snap @@ -7,17 +7,13 @@ expression: msl constexpr constant int const_10i = 10; constexpr constant int const_20i = 20; -typedef metal::texture2d type; -typedef metal::texture1d type1; -typedef metal::uint3 type2; -typedef metal::uint2 type3; -typedef metal::int2 type4; + struct main1Input { }; kernel void main1( - type2 local_id [[thread_position_in_threadgroup]] -, type image_src [[user(fake0)]] -, type1 image_dst [[user(fake0)]] + metal::uint3 local_id [[thread_position_in_threadgroup]] +, metal::texture2d image_src [[user(fake0)]] +, metal::texture1d image_dst [[user(fake0)]] ) { metal::int2 _expr12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(const_10i, const_20i); metal::uint4 _expr13 = image_src.read(metal::uint2(_expr12)); diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap index 16b352977..a87182075 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl.snap @@ -13,57 +13,49 @@ constexpr constant unsigned const_1u = 1u; constexpr constant int const_0i1 = 0; constexpr constant float const_0f = 0.0; constexpr constant float const_1f = 1.0; -typedef float type; -typedef metal::float2 type1; -typedef thread type1 *type2; -typedef thread type1 *type3; -typedef metal::float4 type4; -typedef metal::uint type5; -typedef type type6[const_1u]; +typedef float type6[const_1u]; struct gl_PerVertex { - type4 gl_Position; - type gl_PointSize; + metal::float4 gl_Position; + float gl_PointSize; type6 gl_ClipDistance; type6 gl_CullDistance; }; -typedef thread gl_PerVertex *type7; -typedef int type8; -typedef thread type4 *type9; struct type10 { - type1 member; - type4 gl_Position1; - type gl_PointSize1; + metal::float2 member; + metal::float4 gl_Position1; + float gl_PointSize1; type6 gl_ClipDistance1; }; + void main1( - thread type1& v_uv, - thread type1 const& a_uv, + thread metal::float2& v_uv, + thread metal::float2 const& a_uv, thread gl_PerVertex& _, - thread type1 const& a_pos + thread metal::float2 const& a_pos ) { v_uv = a_uv; - type1 _expr13 = a_pos; + metal::float2 _expr13 = a_pos; _.gl_Position = metal::float4(_expr13.x, _expr13.y, const_0f, const_1f); return; } struct main2Input { - type1 a_uv1 [[attribute(1)]]; - type1 a_pos1 [[attribute(0)]]; + metal::float2 a_uv1 [[attribute(1)]]; + metal::float2 a_pos1 [[attribute(0)]]; }; struct main2Output { - type1 member [[user(loc0)]]; - type4 gl_Position1 [[position]]; - type gl_PointSize1 [[point_size]]; + metal::float2 member [[user(loc0)]]; + metal::float4 gl_Position1 [[position]]; + float gl_PointSize1 [[point_size]]; type6 gl_ClipDistance1 [[clip_distance]]; }; vertex main2Output main2( main2Input varyings [[stage_in]] ) { - type1 v_uv = {}; - type1 a_uv = {}; + metal::float2 v_uv = {}; + metal::float2 a_uv = {}; gl_PerVertex _ = {}; - type1 a_pos = {}; + metal::float2 a_pos = {}; const auto a_uv1 = varyings.a_uv1; const auto a_pos1 = varyings.a_pos1; a_uv = a_uv1; diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index 47a48a2d1..434a62aa6 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -8,22 +8,18 @@ expression: msl constexpr constant float c_scale = 1.2; constexpr constant float const_0f = 0.0; constexpr constant float const_1f = 1.0; -typedef float type; -typedef metal::float2 type1; -typedef metal::float4 type2; struct VertexOutput { - type1 uv; - type2 position; + metal::float2 uv; + metal::float4 position; }; -typedef metal::texture2d type3; -typedef metal::sampler type4; + struct main1Input { - type1 pos [[attribute(0)]]; - type1 uv1 [[attribute(1)]]; + metal::float2 pos [[attribute(0)]]; + metal::float2 uv1 [[attribute(1)]]; }; struct main1Output { - type1 uv [[user(loc0)]]; - type2 position [[position]]; + metal::float2 uv [[user(loc0)]]; + metal::float4 position [[position]]; }; vertex main1Output main1( main1Input varyings [[stage_in]] @@ -37,16 +33,17 @@ vertex main1Output main1( return main1Output { _tmp.uv, _tmp.position }; } + struct main2Input { - type1 uv2 [[user(loc0)]]; + metal::float2 uv2 [[user(loc0)]]; }; struct main2Output { - type2 member1 [[color(0)]]; + metal::float4 member1 [[color(0)]]; }; fragment main2Output main2( main2Input varyings1 [[stage_in]] -, type3 u_texture [[user(fake0)]] -, type4 u_sampler [[user(fake0)]] +, metal::texture2d u_texture [[user(fake0)]] +, metal::sampler u_sampler [[user(fake0)]] ) { const auto uv2 = varyings1.uv2; metal::float4 _expr4 = u_texture.sample(u_sampler, uv2); diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 94cd7982e..057daff8e 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -13,33 +13,25 @@ constexpr constant float const_0_05f = 0.05; constexpr constant unsigned c_max_lights = 10u; constexpr constant unsigned const_0u = 0u; constexpr constant unsigned const_1u = 1u; -typedef metal::uint4 type; struct Globals { - type num_lights; + metal::uint4 num_lights; }; -typedef metal::float4x4 type1; -typedef metal::float4 type2; struct Light { - type1 proj; - type2 pos; - type2 color; + metal::float4x4 proj; + metal::float4 pos; + metal::float4 color; }; typedef Light type3[1]; struct Lights { type3 data; }; -typedef metal::depth2d_array type4; -typedef metal::sampler type5; -typedef metal::uint type6; -typedef float type7; -typedef metal::float2 type8; -typedef metal::float3 type9; -constexpr constant type9 c_ambient = {const_0_05f, const_0_05f, const_0_05f}; -type7 fetch_shadow( - type6 light_id, - type2 homogeneous_coords, - type4 t_shadow, - type5 sampler_shadow +constexpr constant metal::float3 c_ambient = {const_0_05f, const_0_05f, const_0_05f}; + +float fetch_shadow( + metal::uint light_id, + metal::float4 homogeneous_coords, + metal::depth2d_array t_shadow, + metal::sampler sampler_shadow ) { if (homogeneous_coords.w <= const_0f) { return const_1f; @@ -50,23 +42,23 @@ type7 fetch_shadow( } struct fs_mainInput { - type9 raw_normal [[user(loc0)]]; - type2 position [[user(loc1)]]; + metal::float3 raw_normal [[user(loc0)]]; + metal::float4 position [[user(loc1)]]; }; struct fs_mainOutput { - type2 member [[color(0)]]; + metal::float4 member [[color(0)]]; }; fragment fs_mainOutput fs_main( fs_mainInput varyings [[stage_in]] , constant Globals& u_globals [[user(fake0)]] , constant Lights& s_lights [[user(fake0)]] -, type4 t_shadow [[user(fake0)]] -, type5 sampler_shadow [[user(fake0)]] +, metal::depth2d_array t_shadow [[user(fake0)]] +, metal::sampler sampler_shadow [[user(fake0)]] ) { const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; - type9 color1 = c_ambient; - type6 i = const_0u; + metal::float3 color1 = c_ambient; + metal::uint i = const_0u; bool loop_init = true; while(true) { if (!loop_init) { @@ -77,7 +69,7 @@ fragment fs_mainOutput fs_main( break; } Light _expr21 = s_lights.data[i]; - type7 _expr25 = fetch_shadow(i, _expr21.proj * position, t_shadow, sampler_shadow); + float _expr25 = fetch_shadow(i, _expr21.proj * position, t_shadow, sampler_shadow); color1 = color1 + ((_expr25 * metal::max(const_0f, metal::dot(metal::normalize(raw_normal), metal::normalize(metal::float3(_expr21.pos.x, _expr21.pos.y, _expr21.pos.z) - metal::float3(position.x, position.y, position.z))))) * metal::float3(_expr21.color.x, _expr21.color.y, _expr21.color.z)); } return fs_mainOutput { metal::float4(color1, const_1f) }; diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 5fde02477..96bbabe89 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -10,38 +10,31 @@ constexpr constant int const_1i = 1; constexpr constant float const_4f = 4.0; constexpr constant float const_1f = 1.0; constexpr constant float const_0f = 0.0; -typedef metal::float4 type; -typedef metal::float3 type1; struct VertexOutput { - type position; - type1 uv; + metal::float4 position; + metal::float3 uv; }; -typedef metal::float4x4 type2; struct Data { - type2 proj_inv; - type2 view; + metal::float4x4 proj_inv; + metal::float4x4 view; }; -typedef metal::uint type3; -typedef int type4; -typedef metal::float3x3 type5; -typedef metal::texturecube type6; -typedef metal::sampler type7; + struct vs_mainInput { }; struct vs_mainOutput { - type position [[position]]; - type1 uv [[user(loc0)]]; + metal::float4 position [[position]]; + metal::float3 uv [[user(loc0)]]; }; vertex vs_mainOutput vs_main( - type3 vertex_index [[vertex_id]] + metal::uint vertex_index [[vertex_id]] , constant Data& r_data [[buffer(0)]] ) { - type4 tmp1_; - type4 tmp2_; + int tmp1_; + int tmp2_; VertexOutput out; tmp1_ = static_cast(vertex_index) / const_2i; tmp2_ = static_cast(vertex_index) & const_1i; - type _expr24 = metal::float4((static_cast(tmp1_) * const_4f) - const_1f, (static_cast(tmp2_) * const_4f) - const_1f, const_0f, const_1f); + metal::float4 _expr24 = metal::float4((static_cast(tmp1_) * const_4f) - const_1f, (static_cast(tmp2_) * const_4f) - const_1f, const_0f, const_1f); metal::float4 _expr50 = r_data.proj_inv * _expr24; out.uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr50.x, _expr50.y, _expr50.z); out.position = _expr24; @@ -49,16 +42,17 @@ vertex vs_mainOutput vs_main( return vs_mainOutput { _tmp.position, _tmp.uv }; } + struct fs_mainInput { - type1 uv [[user(loc0)]]; + metal::float3 uv [[user(loc0)]]; }; struct fs_mainOutput { - type member1 [[color(0)]]; + metal::float4 member1 [[color(0)]]; }; fragment fs_mainOutput fs_main( fs_mainInput varyings1 [[stage_in]] -, type position [[position]] -, type6 r_texture [[texture(0)]] +, metal::float4 position [[position]] +, metal::texturecube r_texture [[texture(0)]] ) { constexpr metal::sampler r_sampler( metal::s_address::clamp_to_edge, From 6166b95b6a1ca37564bbe0e8b1e7cd1f4aedaa12 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 8 Apr 2021 12:29:26 -0400 Subject: [PATCH 0671/2212] [msl] inline some of the constants --- src/back/msl/writer.rs | 181 ++++++++++++++++++++++++++-------- tests/out/boids.msl.snap | 52 +++++----- tests/out/collatz.msl.snap | 16 ++- tests/out/image-copy.msl.snap | 4 +- tests/out/quad-vert.msl.snap | 12 +-- tests/out/quad.msl.snap | 6 +- tests/out/shadow.msl.snap | 25 ++--- tests/out/skybox.msl.snap | 11 +-- 8 files changed, 187 insertions(+), 120 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0c4979a89..e06d72791 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -229,6 +229,42 @@ impl<'a> TypedGlobalVariable<'a> { } } +struct ConstantContext<'a> { + handle: Handle, + arena: &'a Arena, + names: &'a FastHashMap, + first_time: bool, +} + +impl<'a> Display for ConstantContext<'a> { + fn fmt(&self, out: &mut Formatter<'_>) -> Result<(), FmtError> { + let con = &self.arena[self.handle]; + if con.needs_alias() && !self.first_time { + let name = &self.names[&NameKey::Constant(self.handle)]; + return write!(out, "{}", name); + } + + match con.inner { + crate::ConstantInner::Scalar { value, width: _ } => match value { + crate::ScalarValue::Sint(value) => { + write!(out, "{}", value) + } + crate::ScalarValue::Uint(value) => { + write!(out, "{}u", value) + } + crate::ScalarValue::Float(value) => { + let suffix = if value.fract() == 0.0 { ".0" } else { "" }; + write!(out, "{}{}", value, suffix) + } + crate::ScalarValue::Bool(value) => { + write!(out, "{}", value) + } + }, + crate::ConstantInner::Composite { .. } => unreachable!("should be aliased"), + } + } +} + pub struct Writer { out: W, names: FastHashMap, @@ -299,7 +335,7 @@ impl crate::StorageClass { } impl crate::Type { - // Returns `true` if we need to emit a type alias for this type. + // Returns `true` if we need to emit an alias for this type. fn needs_alias(&self) -> bool { use crate::TypeInner as Ti; match self.inner { @@ -317,6 +353,16 @@ impl crate::Type { } } +impl crate::Constant { + // Returns `true` if we need to emit an alias for this constant. + fn needs_alias(&self) -> bool { + match self.inner { + crate::ConstantInner::Scalar { .. } => self.name.is_some(), + crate::ConstantInner::Composite { .. } => true, + } + } +} + enum FunctionOrigin { Handle(Handle), EntryPoint(EntryPointIndex), @@ -545,8 +591,13 @@ impl Writer { } } crate::Expression::Constant(handle) => { - let handle_name = &self.names[&NameKey::Constant(handle)]; - write!(self.out, "{}", handle_name)?; + let coco = ConstantContext { + handle, + arena: &context.module.constants, + names: &self.names, + first_time: false, + }; + write!(self.out, "{}", coco)?; } crate::Expression::Compose { ty, ref components } => { let inner = &context.module.types[ty].inner; @@ -670,8 +721,13 @@ impl Writer { } } if let Some(constant) = offset { - let offset_str = &self.names[&NameKey::Constant(constant)]; - write!(self.out, ", {}", offset_str)?; + let coco = ConstantContext { + handle: constant, + arena: &context.module.constants, + names: &self.names, + first_time: false, + }; + write!(self.out, ", {}", coco)?; } write!(self.out, ")")?; } @@ -914,8 +970,13 @@ impl Writer { size: crate::ArraySize::Constant(const_handle), .. } => { - let size_str = &self.names[&NameKey::Constant(const_handle)]; - write!(self.out, "{}", size_str)?; + let coco = ConstantContext { + handle: const_handle, + arena: &context.module.constants, + names: &self.names, + first_time: false, + }; + write!(self.out, "{}", coco)?; } crate::TypeInner::Array { .. } => { return Err(Error::FeatureNotImplemented( @@ -1296,13 +1357,21 @@ impl Writer { access: crate::StorageAccess::empty(), first_time: false, }; - let size_str = match size { + write!(self.out, "typedef {} {}", base_name, name)?; + match size { crate::ArraySize::Constant(const_handle) => { - &self.names[&NameKey::Constant(const_handle)] + let coco = ConstantContext { + handle: const_handle, + arena: &module.constants, + names: &self.names, + first_time: false, + }; + writeln!(self.out, "[{}];", coco)?; } - crate::ArraySize::Dynamic => "1", - }; - writeln!(self.out, "typedef {} {}[{}];", base_name, name, size_str)?; + crate::ArraySize::Dynamic => { + writeln!(self.out, "[1];")?; + } + } } crate::TypeInner::Struct { block: _, @@ -1345,29 +1414,33 @@ impl Writer { crate::ConstantInner::Scalar { width: _, ref value, - } => { - let name = &self.names[&NameKey::Constant(handle)]; + } if constant.name.is_some() => { + debug_assert!(constant.needs_alias()); write!(self.out, "constexpr constant ")?; match *value { - crate::ScalarValue::Sint(value) => { - write!(self.out, "int {} = {}", name, value)?; + crate::ScalarValue::Sint(_) => { + write!(self.out, "int")?; } - crate::ScalarValue::Uint(value) => { - write!(self.out, "unsigned {} = {}u", name, value)?; + crate::ScalarValue::Uint(_) => { + write!(self.out, "unsigned")?; } - crate::ScalarValue::Float(value) => { - write!(self.out, "float {} = {}", name, value)?; - if value.fract() == 0.0 { - write!(self.out, ".0")?; - } + crate::ScalarValue::Float(_) => { + write!(self.out, "float")?; } - crate::ScalarValue::Bool(value) => { - write!(self.out, "bool {} = {}", name, value)?; + crate::ScalarValue::Bool(_) => { + write!(self.out, "bool")?; } } - writeln!(self.out, ";")?; + let name = &self.names[&NameKey::Constant(handle)]; + let coco = ConstantContext { + handle, + arena: &module.constants, + names: &self.names, + first_time: true, + }; + writeln!(self.out, " {} = {};", name, coco)?; } - crate::ConstantInner::Composite { .. } => {} + _ => {} } } Ok(()) @@ -1378,6 +1451,7 @@ impl Writer { match constant.inner { crate::ConstantInner::Scalar { .. } => {} crate::ConstantInner::Composite { ty, ref components } => { + debug_assert!(constant.needs_alias()); let name = &self.names[&NameKey::Constant(handle)]; let ty_name = TypeContext { handle: ty, @@ -1390,8 +1464,13 @@ impl Writer { write!(self.out, "constexpr constant {} {} = {{", ty_name, name,)?; for (i, &sub_handle) in components.iter().enumerate() { let separator = if i != 0 { ", " } else { "" }; - let sub_name = &self.names[&NameKey::Constant(sub_handle)]; - write!(self.out, "{}{}", separator, sub_name)?; + let coco = ConstantContext { + handle: sub_handle, + arena: &module.constants, + names: &self.names, + first_time: false, + }; + write!(self.out, "{}{}", separator, coco)?; } writeln!(self.out, "}};")?; } @@ -1561,8 +1640,13 @@ impl Writer { let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; write!(self.out, "{}{} {}", INDENT, ty_name, local_name)?; if let Some(value) = local.init { - let value_str = &self.names[&NameKey::Constant(value)]; - write!(self.out, " = {}", value_str)?; + let coco = ConstantContext { + handle: value, + arena: &module.constants, + names: &self.names, + first_time: false, + }; + write!(self.out, " = {}", coco)?; } writeln!(self.out, ";")?; } @@ -1801,8 +1885,13 @@ impl Writer { resolved.try_fmt_decorated(&mut self.out, "")?; } if let Some(value) = var.init { - let value_str = &self.names[&NameKey::Constant(value)]; - write!(self.out, " = {}", value_str)?; + let coco = ConstantContext { + handle: value, + arena: &module.constants, + names: &self.names, + first_time: false, + }; + write!(self.out, " = {}", coco)?; } writeln!(self.out)?; } @@ -1827,11 +1916,20 @@ impl Writer { }; write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; - let value_str = match var.init { - Some(value) => &self.names[&NameKey::Constant(value)], - None => "{}", + match var.init { + Some(value) => { + let coco = ConstantContext { + handle: value, + arena: &module.constants, + names: &self.names, + first_time: false, + }; + writeln!(self.out, " = {};", coco)?; + } + None => { + writeln!(self.out, " = {{}};")?; + } }; - writeln!(self.out, " = {};", value_str)?; } else if let Some(ref binding) = var.binding { // write an inline sampler let resolved = options.resolve_global_binding(ep.stage, binding).unwrap(); @@ -1902,8 +2000,13 @@ impl Writer { }; write!(self.out, "{}{} {}", INDENT, ty_name, name)?; if let Some(value) = local.init { - let value_str = &self.names[&NameKey::Constant(value)]; - write!(self.out, " = {}", value_str)?; + let coco = ConstantContext { + handle: value, + arena: &module.constants, + names: &self.names, + first_time: false, + }; + write!(self.out, " = {}", coco)?; } writeln!(self.out, ";")?; } diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap index 9f302992a..d59f82aea 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl.snap @@ -6,14 +6,6 @@ expression: msl #include constexpr constant unsigned NUM_PARTICLES = 1500u; -constexpr constant float const_0f = 0.0; -constexpr constant int const_0i = 0; -constexpr constant unsigned const_0u = 0u; -constexpr constant int const_1i = 1; -constexpr constant unsigned const_1u = 1u; -constexpr constant float const_1f = 1.0; -constexpr constant float const_0_10f = 0.1; -constexpr constant float const_n1f = -1.0; struct Particle { metal::float2 pos; metal::float2 vel; @@ -45,23 +37,23 @@ kernel void main1( metal::float2 cMass; metal::float2 cVel; metal::float2 colVel; - int cMassCount = const_0i; - int cVelCount = const_0i; + int cMassCount = 0; + int cVelCount = 0; metal::float2 pos1; metal::float2 vel1; - metal::uint i = const_0u; + metal::uint i = 0u; if (global_invocation_id.x >= NUM_PARTICLES) { return; } vPos = particlesSrc.particles[global_invocation_id.x].pos; vVel = particlesSrc.particles[global_invocation_id.x].vel; - cMass = metal::float2(const_0f, const_0f); - cVel = metal::float2(const_0f, const_0f); - colVel = metal::float2(const_0f, const_0f); + cMass = metal::float2(0.0, 0.0); + cVel = metal::float2(0.0, 0.0); + colVel = metal::float2(0.0, 0.0); bool loop_init = true; while(true) { if (!loop_init) { - i = i + const_1u; + i = i + 1u; } loop_init = false; if (i >= NUM_PARTICLES) { @@ -74,36 +66,36 @@ kernel void main1( vel1 = particlesSrc.particles[i].vel; if (metal::distance(pos1, vPos) < params.rule1Distance) { cMass = cMass + pos1; - cMassCount = cMassCount + const_1i; + cMassCount = cMassCount + 1; } if (metal::distance(pos1, vPos) < params.rule2Distance) { colVel = colVel - (pos1 - vPos); } if (metal::distance(pos1, vPos) < params.rule3Distance) { cVel = cVel + vel1; - cVelCount = cVelCount + const_1i; + cVelCount = cVelCount + 1; } } - if (cMassCount > const_0i) { - cMass = (cMass * (const_1f / static_cast(cMassCount))) - vPos; + if (cMassCount > 0) { + cMass = (cMass * (1.0 / static_cast(cMassCount))) - vPos; } - if (cVelCount > const_0i) { - cVel = cVel * (const_1f / static_cast(cVelCount)); + if (cVelCount > 0) { + cVel = cVel * (1.0 / static_cast(cVelCount)); } vVel = ((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale); - vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), const_0f, const_0_10f); + vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); vPos = vPos + (vVel * params.deltaT); - if (vPos.x < const_n1f) { - vPos.x = const_1f; + if (vPos.x < -1.0) { + vPos.x = 1.0; } - if (vPos.x > const_1f) { - vPos.x = const_n1f; + if (vPos.x > 1.0) { + vPos.x = -1.0; } - if (vPos.y < const_n1f) { - vPos.y = const_1f; + if (vPos.y < -1.0) { + vPos.y = 1.0; } - if (vPos.y > const_1f) { - vPos.y = const_n1f; + if (vPos.y > 1.0) { + vPos.y = -1.0; } particlesDst.particles[global_invocation_id.x].pos = vPos; particlesDst.particles[global_invocation_id.x].vel = vVel; diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index 2aa4fe344..f86b138a7 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -5,10 +5,6 @@ expression: msl #include #include -constexpr constant unsigned const_0u = 0u; -constexpr constant unsigned const_1u = 1u; -constexpr constant unsigned const_2u = 2u; -constexpr constant unsigned const_3u = 3u; typedef metal::uint type1[1]; struct PrimeIndices { type1 data; @@ -18,18 +14,18 @@ metal::uint collatz_iterations( metal::uint n_base ) { metal::uint n; - metal::uint i = const_0u; + metal::uint i = 0u; n = n_base; while(true) { - if (n <= const_1u) { + if (n <= 1u) { break; } - if ((n % const_2u) == const_0u) { - n = n / const_2u; + if ((n % 2u) == 0u) { + n = n / 2u; } else { - n = (const_3u * n) + const_1u; + n = (3u * n) + 1u; } - i = i + const_1u; + i = i + 1u; } return i; } diff --git a/tests/out/image-copy.msl.snap b/tests/out/image-copy.msl.snap index 3b9ca6f74..da5c6b155 100644 --- a/tests/out/image-copy.msl.snap +++ b/tests/out/image-copy.msl.snap @@ -5,8 +5,6 @@ expression: msl #include #include -constexpr constant int const_10i = 10; -constexpr constant int const_20i = 20; struct main1Input { }; @@ -15,7 +13,7 @@ kernel void main1( , metal::texture2d image_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 _expr12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(const_10i, const_20i); + metal::int2 _expr12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(10, 20); metal::uint4 _expr13 = image_src.read(metal::uint2(_expr12)); image_dst.write(_expr13, metal::uint(_expr12.x)); return; diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap index a87182075..245ffea21 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl.snap @@ -5,15 +5,7 @@ expression: msl #include #include -constexpr constant int const_0i = 0; -constexpr constant int const_1i = 1; -constexpr constant int const_2i = 2; -constexpr constant int const_3i = 3; -constexpr constant unsigned const_1u = 1u; -constexpr constant int const_0i1 = 0; -constexpr constant float const_0f = 0.0; -constexpr constant float const_1f = 1.0; -typedef float type6[const_1u]; +typedef float type6[1u]; struct gl_PerVertex { metal::float4 gl_Position; float gl_PointSize; @@ -35,7 +27,7 @@ void main1( ) { v_uv = a_uv; metal::float2 _expr13 = a_pos; - _.gl_Position = metal::float4(_expr13.x, _expr13.y, const_0f, const_1f); + _.gl_Position = metal::float4(_expr13.x, _expr13.y, 0.0, 1.0); return; } diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index 434a62aa6..b45e13d33 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -6,8 +6,6 @@ expression: msl #include constexpr constant float c_scale = 1.2; -constexpr constant float const_0f = 0.0; -constexpr constant float const_1f = 1.0; struct VertexOutput { metal::float2 uv; metal::float4 position; @@ -28,7 +26,7 @@ vertex main1Output main1( const auto uv1 = varyings.uv1; VertexOutput out; out.uv = uv1; - out.position = metal::float4(c_scale * pos, const_0f, const_1f); + out.position = metal::float4(c_scale * pos, 0.0, 1.0); const auto _tmp = out; return main1Output { _tmp.uv, _tmp.position }; } @@ -47,7 +45,7 @@ fragment main2Output main2( ) { const auto uv2 = varyings1.uv2; metal::float4 _expr4 = u_texture.sample(u_sampler, uv2); - if (_expr4.w == const_0f) { + if (_expr4.w == 0.0) { metal::discard_fragment(); } return main2Output { _expr4.w * _expr4 }; diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 057daff8e..9ac8176a1 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -5,14 +5,7 @@ expression: msl #include #include -constexpr constant float const_0f = 0.0; -constexpr constant float const_1f = 1.0; -constexpr constant float const_0_50f = 0.5; -constexpr constant float const_n0_50f = -0.5; -constexpr constant float const_0_05f = 0.05; constexpr constant unsigned c_max_lights = 10u; -constexpr constant unsigned const_0u = 0u; -constexpr constant unsigned const_1u = 1u; struct Globals { metal::uint4 num_lights; }; @@ -25,7 +18,7 @@ typedef Light type3[1]; struct Lights { type3 data; }; -constexpr constant metal::float3 c_ambient = {const_0_05f, const_0_05f, const_0_05f}; +constexpr constant metal::float3 c_ambient = {0.05, 0.05, 0.05}; float fetch_shadow( metal::uint light_id, @@ -33,11 +26,11 @@ float fetch_shadow( metal::depth2d_array t_shadow, metal::sampler sampler_shadow ) { - if (homogeneous_coords.w <= const_0f) { - return const_1f; + if (homogeneous_coords.w <= 0.0) { + return 1.0; } - float _expr15 = const_1f / homogeneous_coords.w; - float _expr28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * _expr15) + metal::float2(const_0_50f, const_0_50f), static_cast(light_id), homogeneous_coords.z * _expr15); + float _expr15 = 1.0 / homogeneous_coords.w; + float _expr28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) * _expr15) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z * _expr15); return _expr28; } @@ -58,11 +51,11 @@ fragment fs_mainOutput fs_main( const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; metal::float3 color1 = c_ambient; - metal::uint i = const_0u; + metal::uint i = 0u; bool loop_init = true; while(true) { if (!loop_init) { - i = i + const_1u; + i = i + 1u; } loop_init = false; if (i >= metal::min(u_globals.num_lights.x, c_max_lights)) { @@ -70,8 +63,8 @@ fragment fs_mainOutput fs_main( } Light _expr21 = s_lights.data[i]; float _expr25 = fetch_shadow(i, _expr21.proj * position, t_shadow, sampler_shadow); - color1 = color1 + ((_expr25 * metal::max(const_0f, metal::dot(metal::normalize(raw_normal), metal::normalize(metal::float3(_expr21.pos.x, _expr21.pos.y, _expr21.pos.z) - metal::float3(position.x, position.y, position.z))))) * metal::float3(_expr21.color.x, _expr21.color.y, _expr21.color.z)); + color1 = color1 + ((_expr25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(metal::float3(_expr21.pos.x, _expr21.pos.y, _expr21.pos.z) - metal::float3(position.x, position.y, position.z))))) * metal::float3(_expr21.color.x, _expr21.color.y, _expr21.color.z)); } - return fs_mainOutput { metal::float4(color1, const_1f) }; + return fs_mainOutput { metal::float4(color1, 1.0) }; } diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 96bbabe89..67988bf82 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -5,11 +5,6 @@ expression: msl #include #include -constexpr constant int const_2i = 2; -constexpr constant int const_1i = 1; -constexpr constant float const_4f = 4.0; -constexpr constant float const_1f = 1.0; -constexpr constant float const_0f = 0.0; struct VertexOutput { metal::float4 position; metal::float3 uv; @@ -32,9 +27,9 @@ vertex vs_mainOutput vs_main( int tmp1_; int tmp2_; VertexOutput out; - tmp1_ = static_cast(vertex_index) / const_2i; - tmp2_ = static_cast(vertex_index) & const_1i; - metal::float4 _expr24 = metal::float4((static_cast(tmp1_) * const_4f) - const_1f, (static_cast(tmp2_) * const_4f) - const_1f, const_0f, const_1f); + tmp1_ = static_cast(vertex_index) / 2; + tmp2_ = static_cast(vertex_index) & 1; + metal::float4 _expr24 = metal::float4((static_cast(tmp1_) * 4.0) - 1.0, (static_cast(tmp2_) * 4.0) - 1.0, 0.0, 1.0); metal::float4 _expr50 = r_data.proj_inv * _expr24; out.uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr50.x, _expr50.y, _expr50.z); out.position = _expr24; From d0d9e09cdbb03715296073b18c602ba33263434a Mon Sep 17 00:00:00 2001 From: LaughingMan Date: Thu, 8 Apr 2021 14:58:22 +0200 Subject: [PATCH 0672/2212] [spv-in] Copy less bytes in `parse_function` The initial intention was to make the code a little more elegant and match on the Vec itself instead of its length, however there's also a - probably minuscule - performance advantage: `Vec::remove` internally copies the removed element onto the stack. In this case that's a `StructMember` weighting 48 bytes. The `Binding` we are actually interested in is only 8 bytes tough. Cloning just the `Binding` saves us from copying 40 bytes for nothing. --- src/front/spv/function.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index ba38cea69..bb9fe9660 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -317,10 +317,9 @@ impl> super::Parser { *component = function.expressions.append(load_expr); } - match members.len() { - 0 => {} - 1 => { - let member = members.remove(0); + match &members[..] { + [] => {} + [member] => { function.body.push(crate::Statement::Emit( function.expressions.range_from(old_len), )); @@ -329,7 +328,7 @@ impl> super::Parser { }); function.result = Some(crate::FunctionResult { ty: member.ty, - binding: member.binding, + binding: member.binding.clone(), }); } _ => { From 5a0e3ad5ff9e8fb939ba3bb8e0a7cdf61092d3e4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 8 Apr 2021 17:14:05 -0700 Subject: [PATCH 0673/2212] [spv-out]: Add some local `use` declarations to the SPIR-V writer. This adds `use` declarations for `spirv::Decoration` and `spirv::BuiltIn` local to functions where those are used repeatedly. --- src/back/spv/writer.rs | 70 +++++++++++++++++++++++------------------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 8a375cfd7..57e22d1c8 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -790,6 +790,8 @@ impl Writer { } } + use spirv::Decoration; + let instruction = match ty.inner { crate::TypeInner::Scalar { kind, width } => self.write_scalar(id, kind, width), crate::TypeInner::Vector { size, kind, width } => { @@ -846,7 +848,7 @@ impl Writer { if let Some(array_stride) = stride { self.annotations.push(Instruction::decorate( id, - spirv::Decoration::ArrayStride, + Decoration::ArrayStride, &[array_stride.get()], )); } @@ -863,7 +865,7 @@ impl Writer { crate::TypeInner::Struct { block, ref members } => { if block { self.annotations - .push(Instruction::decorate(id, spirv::Decoration::Block, &[])); + .push(Instruction::decorate(id, Decoration::Block, &[])); } let mut current_offset = 0; @@ -873,7 +875,7 @@ impl Writer { self.annotations.push(Instruction::member_decorate( id, index as u32, - spirv::Decoration::Offset, + Decoration::Offset, &[placement.start], )); current_offset = placement.end; @@ -898,13 +900,13 @@ impl Writer { self.annotations.push(Instruction::member_decorate( id, index as u32, - spirv::Decoration::ColMajor, + Decoration::ColMajor, &[], )); self.annotations.push(Instruction::member_decorate( id, index as u32, - spirv::Decoration::MatrixStride, + Decoration::MatrixStride, &[byte_stride as u32], )); } @@ -1067,18 +1069,20 @@ impl Writer { } } + use spirv::{BuiltIn, Decoration}; + match *binding { crate::Binding::Location(location, interpolation) => { self.annotations.push(Instruction::decorate( id, - spirv::Decoration::Location, + Decoration::Location, &[location], )); let interp_decoration = match interpolation { - Some(crate::Interpolation::Linear) => Some(spirv::Decoration::NoPerspective), - Some(crate::Interpolation::Flat) => Some(spirv::Decoration::Flat), - Some(crate::Interpolation::Centroid) => Some(spirv::Decoration::Centroid), - Some(crate::Interpolation::Sample) => Some(spirv::Decoration::Sample), + Some(crate::Interpolation::Linear) => Some(Decoration::NoPerspective), + Some(crate::Interpolation::Flat) => Some(Decoration::Flat), + Some(crate::Interpolation::Centroid) => Some(Decoration::Centroid), + Some(crate::Interpolation::Sample) => Some(Decoration::Sample), Some(crate::Interpolation::Perspective) | None => None, }; if let Some(decoration) = interp_decoration { @@ -1091,34 +1095,34 @@ impl Writer { let built_in = match built_in { Bi::Position => { if class == spirv::StorageClass::Output { - spirv::BuiltIn::Position + BuiltIn::Position } else { - spirv::BuiltIn::FragCoord + BuiltIn::FragCoord } } // vertex - Bi::BaseInstance => spirv::BuiltIn::BaseInstance, - Bi::BaseVertex => spirv::BuiltIn::BaseVertex, - Bi::ClipDistance => spirv::BuiltIn::ClipDistance, - Bi::InstanceIndex => spirv::BuiltIn::InstanceIndex, - Bi::PointSize => spirv::BuiltIn::PointSize, - Bi::VertexIndex => spirv::BuiltIn::VertexIndex, + Bi::BaseInstance => BuiltIn::BaseInstance, + Bi::BaseVertex => BuiltIn::BaseVertex, + Bi::ClipDistance => BuiltIn::ClipDistance, + Bi::InstanceIndex => BuiltIn::InstanceIndex, + Bi::PointSize => BuiltIn::PointSize, + Bi::VertexIndex => BuiltIn::VertexIndex, // fragment - Bi::FragDepth => spirv::BuiltIn::FragDepth, - Bi::FrontFacing => spirv::BuiltIn::FrontFacing, - Bi::SampleIndex => spirv::BuiltIn::SampleId, - Bi::SampleMask => spirv::BuiltIn::SampleMask, + Bi::FragDepth => BuiltIn::FragDepth, + Bi::FrontFacing => BuiltIn::FrontFacing, + Bi::SampleIndex => BuiltIn::SampleId, + Bi::SampleMask => BuiltIn::SampleMask, // compute - Bi::GlobalInvocationId => spirv::BuiltIn::GlobalInvocationId, - Bi::LocalInvocationId => spirv::BuiltIn::LocalInvocationId, - Bi::LocalInvocationIndex => spirv::BuiltIn::LocalInvocationIndex, - Bi::WorkGroupId => spirv::BuiltIn::WorkgroupId, - Bi::WorkGroupSize => spirv::BuiltIn::WorkgroupSize, + Bi::GlobalInvocationId => BuiltIn::GlobalInvocationId, + Bi::LocalInvocationId => BuiltIn::LocalInvocationId, + Bi::LocalInvocationIndex => BuiltIn::LocalInvocationIndex, + Bi::WorkGroupId => BuiltIn::WorkgroupId, + Bi::WorkGroupSize => BuiltIn::WorkgroupSize, }; self.annotations.push(Instruction::decorate( id, - spirv::Decoration::BuiltIn, + Decoration::BuiltIn, &[built_in as u32], )); } @@ -1149,9 +1153,11 @@ impl Writer { } } + use spirv::Decoration; + let access_decoration = match global_variable.storage_access { - crate::StorageAccess::LOAD => Some(spirv::Decoration::NonWritable), - crate::StorageAccess::STORE => Some(spirv::Decoration::NonReadable), + crate::StorageAccess::LOAD => Some(Decoration::NonWritable), + crate::StorageAccess::STORE => Some(Decoration::NonReadable), _ => None, }; if let Some(decoration) = access_decoration { @@ -1162,12 +1168,12 @@ impl Writer { if let Some(ref res_binding) = global_variable.binding { self.annotations.push(Instruction::decorate( id, - spirv::Decoration::DescriptorSet, + Decoration::DescriptorSet, &[res_binding.group], )); self.annotations.push(Instruction::decorate( id, - spirv::Decoration::Binding, + Decoration::Binding, &[res_binding.binding], )); } From 7326ba6ddb479a351742c3020c0926f7f0f61335 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 4 Apr 2021 10:26:28 -0400 Subject: [PATCH 0674/2212] New struct layout IR --- src/back/msl/writer.rs | 8 + src/back/spv/writer.rs | 34 ++- src/front/glsl/parser.rs | 3 +- src/front/spv/function.rs | 11 +- src/front/spv/mod.rs | 41 +++- .../layouter.rs => front/wgsl/layout.rs} | 116 ++++----- src/front/wgsl/mod.rs | 36 +-- src/lib.rs | 13 +- src/proc/mod.rs | 48 +++- src/valid/interface.rs | 14 +- src/valid/mod.rs | 7 +- src/valid/type.rs | 201 ++++++++------- tests/out/collatz.info.ron.snap | 20 -- tests/out/collatz.ron.snap | 5 +- tests/out/shadow.info.ron.snap | 232 ------------------ tests/out/shadow.ron.snap | 17 +- 16 files changed, 312 insertions(+), 494 deletions(-) rename src/{proc/layouter.rs => front/wgsl/layout.rs} (50%) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e06d72791..c71f23af3 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1389,6 +1389,14 @@ impl Writer { first_time: false, }; writeln!(self.out, "{}{} {};", INDENT, base_name, member_name)?; + // quick and dirty way to figure out if we need this... + if member.binding.is_none() { + let pad = + member.span - module.types[member.ty].inner.span(&module.constants); + if pad != 0 { + writeln!(self.out, "{}char _pad{}[{}];", INDENT, index, pad)?; + } + } } writeln!(self.out, "}};")?; } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 57e22d1c8..d82a5059e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -3,7 +3,7 @@ use super::{ }; use crate::{ arena::{Arena, Handle}, - proc::{Layouter, TypeResolution}, + proc::TypeResolution, valid::{FunctionInfo, ModuleInfo}, }; use spirv::Word; @@ -760,10 +760,10 @@ impl Writer { fn write_type_declaration_arena( &mut self, arena: &Arena, - layouter: &Layouter, handle: Handle, ) -> Result { let ty = &arena[handle]; + let decorate_layout = true; //TODO? let id = if let Some(local) = self.physical_layout.make_local(&ty.inner) { match self.lookup_type.entry(LookupType::Local(local)) { @@ -845,11 +845,11 @@ impl Writer { } crate::TypeInner::Sampler { comparison: _ } => Instruction::type_sampler(id), crate::TypeInner::Array { base, size, stride } => { - if let Some(array_stride) = stride { + if decorate_layout { self.annotations.push(Instruction::decorate( id, Decoration::ArrayStride, - &[array_stride.get()], + &[stride], )); } @@ -871,14 +871,15 @@ impl Writer { let mut current_offset = 0; let mut member_ids = Vec::with_capacity(members.len()); for (index, member) in members.iter().enumerate() { - let (placement, _) = layouter.member_placement(current_offset, member); - self.annotations.push(Instruction::member_decorate( - id, - index as u32, - Decoration::Offset, - &[placement.start], - )); - current_offset = placement.end; + if decorate_layout { + self.annotations.push(Instruction::member_decorate( + id, + index as u32, + Decoration::Offset, + &[current_offset], + )); + current_offset += member.span; + } if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = member.name { @@ -1073,11 +1074,8 @@ impl Writer { match *binding { crate::Binding::Location(location, interpolation) => { - self.annotations.push(Instruction::decorate( - id, - Decoration::Location, - &[location], - )); + self.annotations + .push(Instruction::decorate(id, Decoration::Location, &[location])); let interp_decoration = match interpolation { Some(crate::Interpolation::Linear) => Some(Decoration::NoPerspective), Some(crate::Interpolation::Flat) => Some(Decoration::Flat), @@ -2540,7 +2538,7 @@ impl Writer { // then all types, some of them may rely on constants and struct type set for (handle, _) in ir_module.types.iter() { - self.write_type_declaration_arena(&ir_module.types, &mod_info.layouter, handle)?; + self.write_type_declaration_arena(&ir_module.types, handle)?; } // the all the composite constants, they rely on types diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0d255d6d5..9f09b27e9 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -729,8 +729,7 @@ pomelo! { binding: None, //TODO //TODO: if the struct is a uniform struct, these values have to reflect // std140 layout. Otherwise, std430. - size: None, - align: None, + span: extra.module.types[ty].inner.span(&extra.module.constants), }).collect() } else { return Err(ErrorKind::SemanticError("Struct member can't be void".into())) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index bb9fe9660..82f74f16a 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -248,13 +248,7 @@ impl> super::Parser { // unrecognized binding, skip continue; } - members.push(crate::StructMember { - name: sm.name.clone(), - ty: sm.ty, - binding: sm.binding.clone(), - size: None, - align: None, - }); + members.push(sm.clone()); components.push(function.expressions.append( crate::Expression::AccessIndex { base: expr_handle, @@ -268,8 +262,7 @@ impl> super::Parser { name: None, ty: result.ty, binding: result.binding.clone(), - size: None, - align: None, + span: module.types[result.ty].inner.span(&module.constants), }); // populate just the globals first, then do `Load` in a // separate step, so that we can get a range. diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 0d13d9714..8baf6834a 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2419,17 +2419,21 @@ impl> Parser { let length_id = self.next()?; let length_const = self.lookup_constant.lookup(length_id)?; - let decor = self.future_decor.remove(&id); + let decor = self.future_decor.remove(&id).unwrap_or_default(); + let base = self.lookup_type.lookup(type_id)?.handle; let inner = crate::TypeInner::Array { - base: self.lookup_type.lookup(type_id)?.handle, + base, size: crate::ArraySize::Constant(length_const.handle), - stride: decor.as_ref().and_then(|dec| dec.array_stride), + stride: match decor.array_stride { + Some(stride) => stride.get(), + None => module.types[base].inner.span(&module.constants), + }, }; self.lookup_type.insert( id, LookupType { handle: module.types.append(crate::Type { - name: decor.and_then(|dec| dec.name), + name: decor.name, inner, }), base_id: Some(type_id), @@ -2448,17 +2452,21 @@ impl> Parser { let id = self.next()?; let type_id = self.next()?; - let decor = self.future_decor.remove(&id); + let decor = self.future_decor.remove(&id).unwrap_or_default(); + let base = self.lookup_type.lookup(type_id)?.handle; let inner = crate::TypeInner::Array { base: self.lookup_type.lookup(type_id)?.handle, size: crate::ArraySize::Dynamic, - stride: decor.as_ref().and_then(|dec| dec.array_stride), + stride: match decor.array_stride { + Some(stride) => stride.get(), + None => module.types[base].inner.span(&module.constants), + }, }; self.lookup_type.insert( id, LookupType { handle: module.types.append(crate::Type { - name: decor.and_then(|dec| dec.name), + name: decor.name, inner, }), base_id: Some(type_id), @@ -2478,8 +2486,9 @@ impl> Parser { let parent_decor = self.future_decor.remove(&id); let block_decor = parent_decor.as_ref().and_then(|decor| decor.block.clone()); - let mut members = Vec::with_capacity(inst.wc as usize - 2); + let mut members = Vec::::with_capacity(inst.wc as usize - 2); let mut member_type_ids = Vec::with_capacity(members.capacity()); + let mut last_offset = 0; for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; member_type_ids.push(type_id); @@ -2489,12 +2498,24 @@ impl> Parser { .remove(&(id, i)) .unwrap_or_default(); let binding = decor.io_binding().ok(); + + if let Some(offset) = decor.offset { + if offset != last_offset { + if let Some(member) = members.last_mut() { + // add padding, if necessary + member.span = offset - (last_offset - member.span); + } + last_offset = offset; + } + } + let span = module.types[ty].inner.span(&module.constants); + last_offset += span; + members.push(crate::StructMember { name: decor.name, ty, binding, - size: None, //TODO - align: None, + span, }); } diff --git a/src/proc/layouter.rs b/src/front/wgsl/layout.rs similarity index 50% rename from src/proc/layouter.rs rename to src/front/wgsl/layout.rs index d8674f846..91734067f 100644 --- a/src/proc/layouter.rs +++ b/src/front/wgsl/layout.rs @@ -1,5 +1,5 @@ use crate::arena::{Arena, Handle}; -use std::{num::NonZeroU32, ops}; +use std::num::NonZeroU32; pub type Alignment = NonZeroU32; @@ -22,14 +22,17 @@ pub struct Layouter { layouts: Vec, } +pub struct Placement { + pub pad: crate::Span, + pub span: crate::Span, +} + impl Layouter { - pub fn new(types: &Arena, constants: &Arena) -> Self { - let mut this = Layouter::default(); - this.initialize(types, constants); - this + pub fn clear(&mut self) { + self.layouts.clear(); } - pub fn round_up(alignment: NonZeroU32, offset: u32) -> u32 { + pub fn round_up(alignment: Alignment, offset: u32) -> u32 { match offset & (alignment.get() - 1) { 0 => offset, other => offset + alignment.get() - other, @@ -39,78 +42,66 @@ impl Layouter { pub fn member_placement( &self, offset: u32, - member: &crate::StructMember, - ) -> (ops::Range, NonZeroU32) { - let layout = self.layouts[member.ty.index()]; - let alignment = member.align.unwrap_or(layout.alignment); + ty: Handle, + align: Option, + size: Option, + ) -> Placement { + let layout = self.layouts[ty.index()]; + let alignment = align.unwrap_or(layout.alignment); let start = Self::round_up(alignment, offset); - let end = start - + match member.size { - Some(size) => size.get(), - None => layout.size, - }; - (start..end, alignment) + let span = match size { + Some(size) => size.get(), + None => layout.size, + }; + Placement { + pad: start - offset, + span, + } } - pub fn initialize(&mut self, types: &Arena, constants: &Arena) { + pub fn update(&mut self, types: &Arena, constants: &Arena) { use crate::TypeInner as Ti; - - self.layouts.clear(); - self.layouts.reserve(types.len()); - - for (_, ty) in types.iter() { - self.layouts.push(match ty.inner { - Ti::Scalar { kind: _, width } => TypeLayout { - size: width as u32, + for (_, ty) in types.iter().skip(self.layouts.len()) { + let size = ty.inner.span(constants); + let layout = match ty.inner { + Ti::Scalar { width, .. } => TypeLayout { + size, alignment: Alignment::new(width as u32).unwrap(), }, Ti::Vector { - size, - kind: _, + size: vec_size, width, + .. } => TypeLayout { - size: (size as u8 * width) as u32, + size, alignment: { - let count = if size >= crate::VectorSize::Tri { 4 } else { 2 }; + let count = if vec_size >= crate::VectorSize::Tri { + 4 + } else { + 2 + }; Alignment::new((count * width) as u32).unwrap() }, }, Ti::Matrix { - columns, + columns: _, rows, width, } => TypeLayout { - size: (columns as u8 * rows as u8 * width) as u32, + size, alignment: { let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; Alignment::new((count * width) as u32).unwrap() }, }, Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { - size: 4, + size, alignment: Alignment::new(1).unwrap(), }, - Ti::Array { base, size, stride } => { - let count = match size { - crate::ArraySize::Constant(handle) => { - constants[handle].to_array_length().unwrap() - } - // A dynamically-sized array has to have at least one element - crate::ArraySize::Dynamic => 1, - }; - let stride = match stride { - Some(value) => value, - None => { - let layout = &self.layouts[base.index()]; - let stride = Self::round_up(layout.alignment, layout.size); - Alignment::new(stride).unwrap() - } - }; - TypeLayout { - size: count * stride.get(), - alignment: stride, - } - } + Ti::Array { stride, .. } => TypeLayout { + size, + alignment: Alignment::new(stride).unwrap(), + }, Ti::Struct { block: _, ref members, @@ -118,9 +109,9 @@ impl Layouter { let mut total = 0; let mut biggest_alignment = Alignment::new(1).unwrap(); for member in members { - let (placement, alignment) = self.member_placement(total, member); - biggest_alignment = biggest_alignment.max(alignment); - total = placement.end; + let layout = self.layouts[member.ty.index()]; + biggest_alignment = biggest_alignment.max(layout.alignment); + total += member.span; } TypeLayout { size: Self::round_up(biggest_alignment, total), @@ -128,17 +119,12 @@ impl Layouter { } } Ti::Image { .. } | Ti::Sampler { .. } => TypeLayout { - size: 0, + size, alignment: Alignment::new(1).unwrap(), }, - }); + }; + debug_assert!(ty.inner.span(constants) <= layout.size); + self.layouts.push(layout); } } } - -impl ops::Index> for Layouter { - type Output = TypeLayout; - fn index(&self, handle: Handle) -> &TypeLayout { - &self.layouts[handle.index()] - } -} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 0434f8589..f4c19e00f 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3,6 +3,7 @@ //! [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html mod conv; +mod layout; mod lexer; #[cfg(test)] mod tests; @@ -560,6 +561,7 @@ impl<'a> std::error::Error for ParseError<'a> { pub struct Parser { scopes: Vec, lookup_type: FastHashMap>, + layouter: layout::Layouter, } impl Parser { @@ -567,6 +569,7 @@ impl Parser { Parser { scopes: Vec::new(), lookup_type: FastHashMap::default(), + layouter: Default::default(), } } @@ -1507,7 +1510,9 @@ impl Parser { type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result, Error<'a>> { + let mut offset = 0; let mut members = Vec::new(); + lexer.expect(Token::Paren('{'))?; loop { let (mut size, mut align) = (None, None); @@ -1558,12 +1563,18 @@ impl Parser { let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Separator(';'))?; + self.layouter.update(type_arena, const_arena); + let placement = self.layouter.member_placement(offset, ty, align, size); + if placement.pad != 0 { + members.last_mut().unwrap().span += placement.pad; + } + offset += placement.pad + placement.span; + members.push(crate::StructMember { name: Some(name.to_owned()), ty, binding: bind_parser.finish()?, - size, - align, + span: placement.span, }); } } @@ -1708,12 +1719,12 @@ impl Parser { crate::ArraySize::Dynamic }; lexer.expect_generic_paren('>')?; + let stride = match attribute.stride { + Some(stride) => stride.get(), + None => type_arena[base].inner.span(const_arena), + }; - crate::TypeInner::Array { - base, - size, - stride: attribute.stride, - } + crate::TypeInner::Array { base, size, stride } } "sampler" => crate::TypeInner::Sampler { comparison: false }, "sampler_comparison" => crate::TypeInner::Sampler { comparison: true }, @@ -1916,14 +1927,8 @@ impl Parser { let storage_access = attribute.access; let name = lexer.next_ident()?; - let handle = self.parse_type_decl_name( - lexer, - name, - debug_name, - attribute, - type_arena, - const_arena, - )?; + let handle = + self.parse_type_decl_name(lexer, name, debug_name, attribute, type_arena, const_arena)?; self.scopes.pop(); Ok((handle, storage_access)) } @@ -2671,6 +2676,7 @@ impl Parser { pub fn parse<'a>(&mut self, source: &'a str) -> Result> { self.scopes.clear(); self.lookup_type.clear(); + self.layouter.clear(); let mut module = crate::Module::default(); let mut lexer = Lexer::new(source); diff --git a/src/lib.rs b/src/lib.rs index 10cbdc1c8..d8ab525e4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,7 +50,6 @@ pub use crate::arena::{Arena, Handle, Range}; use std::{ collections::{HashMap, HashSet}, hash::BuildHasherDefault, - num::NonZeroU32, }; #[cfg(feature = "deserialize")] @@ -166,8 +165,10 @@ pub enum BuiltIn { WorkGroupSize, } -/// Number of bytes. +/// Number of bytes per scalar. pub type Bytes = u8; +/// Number of bytes per complex type. +pub type Span = u32; /// Number of components in a vector. #[repr(u8)] @@ -244,10 +245,8 @@ pub struct StructMember { pub ty: Handle, /// For I/O structs, defines the binding. pub binding: Option, - /// Overrides the size computed off the type. - pub size: Option, - /// Overrides the alignment computed off the type. - pub align: Option, + /// Size occupied by the member. + pub span: Span, } /// The number of dimensions an image has. @@ -392,7 +391,7 @@ pub enum TypeInner { Array { base: Handle, size: ArraySize, - stride: Option, + stride: Span, }, /// User-defined structure. Struct { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 2bb277c70..1d9e7d878 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,11 +1,9 @@ //! Module processing functionality. -mod layouter; mod namer; mod terminator; mod typifier; -pub use layouter::{Alignment, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, TypeResolution}; @@ -61,6 +59,8 @@ impl super::ScalarValue { } } +pub const POINTER_SPAN: u32 = 4; + impl super::TypeInner { pub fn scalar_kind(&self) -> Option { match *self { @@ -71,6 +71,50 @@ impl super::TypeInner { _ => None, } } + + pub fn span(&self, constants: &super::Arena) -> u32 { + match *self { + Self::Scalar { kind: _, width } => width as u32, + Self::Vector { + size, + kind: _, + width, + } => { + //let count = if size >= super::VectorSize::Tri { 4 } else { 2 }; + let count = size as u8; //TEMP + (count * width) as u32 + } + Self::Matrix { + columns, + rows, + width, + } => { + //let count = if rows >= super::VectorSize::Tri { 4 } else { 2 }; + let count = rows as u8; //TEMP + (columns as u8 * count * width) as u32 + } + Self::Pointer { .. } | Self::ValuePointer { .. } => POINTER_SPAN, + Self::Array { + base: _, + size, + stride, + } => { + let count = match size { + super::ArraySize::Constant(handle) => { + constants[handle].to_array_length().unwrap() + } + // A dynamically-sized array has to have at least one element + super::ArraySize::Dynamic => 1, + }; + count * stride + } + Self::Struct { + block: _, + ref members, + } => members.iter().map(|m| m.span).sum(), + Self::Image { .. } | Self::Sampler { .. } => 0, + } + } } impl super::MathFunction { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 576f4448c..0d144150c 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -272,12 +272,9 @@ impl super::Validator { let (allowed_storage_access, required_type_flags, is_resource) = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), crate::StorageClass::Storage => { - if let Err((ty_handle, ref disalignment)) = type_info.storage_layout { + if let Err((ty_handle, disalignment)) = type_info.storage_layout { if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { - return Err(GlobalVariableError::Alignment( - ty_handle, - disalignment.clone(), - )); + return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); } } ( @@ -287,12 +284,9 @@ impl super::Validator { ) } crate::StorageClass::Uniform => { - if let Err((ty_handle, ref disalignment)) = type_info.uniform_layout { + if let Err((ty_handle, disalignment)) = type_info.uniform_layout { if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { - return Err(GlobalVariableError::Alignment( - ty_handle, - disalignment.clone(), - )); + return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); } } ( diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 0ecf12e33..87bfd2088 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -6,7 +6,6 @@ mod r#type; use crate::{ arena::{Arena, Handle}, - proc::Layouter, FastHashSet, }; use bit_set::BitSet; @@ -54,7 +53,6 @@ bitflags::bitflags! { pub struct ModuleInfo { functions: Vec, entry_points: Vec, - pub layouter: Layouter, } impl ops::Index> for ModuleInfo { @@ -221,8 +219,6 @@ impl Validator { pub fn validate(&mut self, module: &crate::Module) -> Result { self.reset_types(module.types.len()); - let layouter = Layouter::new(&module.types, &module.constants); - for (handle, constant) in module.constants.iter() { self.validate_constant(handle, &module.constants, &module.types) .map_err(|error| ValidationError::Constant { @@ -235,7 +231,7 @@ impl Validator { // doing after the globals, so that `type_flags` is ready for (handle, ty) in module.types.iter() { let ty_info = self - .validate_type(ty, handle, &module.constants, &layouter) + .validate_type(handle, &module.types, &module.constants) .map_err(|error| ValidationError::Type { handle, name: ty.name.clone().unwrap_or_default(), @@ -256,7 +252,6 @@ impl Validator { let mut mod_info = ModuleInfo { functions: Vec::with_capacity(module.functions.len()), entry_points: Vec::with_capacity(module.entry_points.len()), - layouter, }; for (handle, fun) in module.functions.iter() { diff --git a/src/valid/type.rs b/src/valid/type.rs index c3622f289..d2cad1f86 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -1,7 +1,6 @@ -use crate::{ - arena::{Arena, Handle}, - proc::Layouter, -}; +use crate::arena::{Arena, Handle}; + +pub type Alignment = u32; bitflags::bitflags! { #[repr(transparent)] @@ -19,7 +18,7 @@ bitflags::bitflags! { } } -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Copy, Debug, thiserror::Error)] pub enum Disalignment { #[error("The array stride {stride} is not a multiple of the required alignment {alignment}")] ArrayStride { stride: u32, alignment: u32 }, @@ -49,10 +48,6 @@ pub enum TypeError { InvalidArrayBaseType(Handle), #[error("The constant {0:?} can not be used for an array size")] InvalidArraySizeConstant(Handle), - #[error( - "Array stride {stride} is not a multiple of the base element alignment {base_alignment}" - )] - UnalignedArrayStride { stride: u32, base_alignment: u32 }, #[error("Array stride {stride} is smaller than the base element size {base_size}")] InsufficientArrayStride { stride: u32, base_size: u32 }, #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] @@ -68,7 +63,7 @@ pub enum TypeError { } // Only makes sense if `flags.contains(HOST_SHARED)` -type LayoutCompatibility = Result<(), (Handle, Disalignment)>; +type LayoutCompatibility = Result, Disalignment)>; // For the uniform buffer alignment, array strides and struct sizes must be multiples of 16. const UNIFORM_LAYOUT_ALIGNMENT_MASK: u32 = 0xF; @@ -81,19 +76,19 @@ pub(super) struct TypeInfo { } impl TypeInfo { - fn new() -> Self { + fn dummy() -> Self { TypeInfo { flags: TypeFlags::empty(), - uniform_layout: Ok(()), - storage_layout: Ok(()), + uniform_layout: Ok(0), + storage_layout: Ok(0), } } - fn from_flags(flags: TypeFlags) -> Self { + fn new(flags: TypeFlags, alignment: crate::Span) -> Self { TypeInfo { flags, - uniform_layout: Ok(()), - storage_layout: Ok(()), + uniform_layout: Ok(alignment), + storage_layout: Ok(alignment), } } } @@ -108,45 +103,64 @@ impl super::Validator { pub(super) fn reset_types(&mut self, size: usize) { self.types.clear(); - self.types.resize(size, TypeInfo::new()); + self.types.resize(size, TypeInfo::dummy()); } pub(super) fn validate_type( &self, - ty: &crate::Type, handle: Handle, + types: &Arena, constants: &Arena, - layouter: &Layouter, ) -> Result { use crate::TypeInner as Ti; - Ok(match ty.inner { - Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => { + Ok(match types[handle].inner { + Ti::Scalar { kind, width } => { if !Self::check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } - TypeInfo::from_flags( + TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED, + width as u32, ) } - Ti::Matrix { width, .. } => { + Ti::Vector { size, kind, width } => { + if !Self::check_width(kind, width) { + return Err(TypeError::InvalidWidth(kind, width)); + } + let count = if size >= crate::VectorSize::Tri { 4 } else { 2 }; + TypeInfo::new( + TypeFlags::DATA + | TypeFlags::SIZED + | TypeFlags::INTERFACE + | TypeFlags::HOST_SHARED, + count * (width as u32), + ) + } + Ti::Matrix { + columns: _, + rows, + width, + } => { if !Self::check_width(crate::ScalarKind::Float, width) { return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); } - TypeInfo::from_flags( + let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; + TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED, + count * (width as u32), ) } Ti::Pointer { base, class: _ } => { if base >= handle { return Err(TypeError::UnresolvedBase(base)); } - TypeInfo::from_flags(TypeFlags::DATA | TypeFlags::SIZED) + TypeInfo::new(TypeFlags::DATA | TypeFlags::SIZED, 0) } Ti::ValuePointer { size: _, @@ -157,7 +171,7 @@ impl super::Validator { if !Self::check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } - TypeInfo::from_flags(TypeFlags::SIZED) + TypeInfo::new(TypeFlags::SIZED, 0) } Ti::Array { base, size, stride } => { if base >= handle { @@ -171,23 +185,35 @@ impl super::Validator { return Err(TypeError::NestedBlock); } - let base_layout = &layouter[base]; - if let Some(stride) = stride { - if stride.get() % base_layout.alignment.get() != 0 { - return Err(TypeError::UnalignedArrayStride { - stride: stride.get(), - base_alignment: base_layout.alignment.get(), - }); - } - if stride.get() < base_layout.size { - return Err(TypeError::InsufficientArrayStride { - stride: stride.get(), - base_size: base_layout.size, - }); - } + let base_size = types[base].inner.span(constants); + if stride < base_size { + return Err(TypeError::InsufficientArrayStride { stride, base_size }); } - let (sized_flag, uniform_layout) = match size { + let uniform_layout = match base_info.uniform_layout { + Ok(base_alignment) => { + // combine the alignment requirements + let alignment = ((base_alignment - 1) | UNIFORM_LAYOUT_ALIGNMENT_MASK) + 1; + if stride % alignment != 0 { + Err((handle, Disalignment::ArrayStride { stride, alignment })) + } else { + Ok(alignment) + } + } + Err(e) => Err(e), + }; + let storage_layout = match base_info.storage_layout { + Ok(alignment) => { + if stride % alignment != 0 { + Err((handle, Disalignment::ArrayStride { stride, alignment })) + } else { + Ok(alignment) + } + } + Err(e) => Err(e), + }; + + let sized_flag = match size { crate::ArraySize::Constant(const_handle) => { match constants.try_get(const_handle) { Some(&crate::Constant { @@ -216,33 +242,17 @@ impl super::Validator { } } - let effective_stride = match stride { - Some(stride) => stride.get(), - None => base_layout.size, - }; - let uniform_layout = - if effective_stride & UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 { - base_info.uniform_layout.clone() - } else { - Err(( - handle, - Disalignment::ArrayStride { - stride: effective_stride, - alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK + 1, - }, - )) - }; - (TypeFlags::SIZED, uniform_layout) + TypeFlags::SIZED } //Note: this will be detected at the struct level - crate::ArraySize::Dynamic => (TypeFlags::empty(), Ok(())), + crate::ArraySize::Dynamic => TypeFlags::empty(), }; let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; TypeInfo { flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag, uniform_layout, - storage_layout: base_info.storage_layout.clone(), + storage_layout, } } Ti::Struct { block, ref members } => { @@ -250,8 +260,8 @@ impl super::Validator { | TypeFlags::SIZED | TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; - let mut uniform_layout = Ok(()); - let mut storage_layout = Ok(()); + let mut uniform_layout = Ok(1); + let mut storage_layout = Ok(1); let mut offset = 0; for (i, member) in members.iter().enumerate() { if member.ty >= handle { @@ -269,28 +279,54 @@ impl super::Validator { } flags &= base_info.flags; - let base_layout = &layouter[member.ty]; - let (range, _alignment) = layouter.member_placement(offset, member); - if range.end - range.start < base_layout.size { + let base_size = types[member.ty].inner.span(constants); + if member.span < base_size { return Err(TypeError::InsufficientMemberSize { index: i as u32, - size: range.end - range.start, - base_size: base_layout.size, + size: member.span, + base_size, }); } - if range.start % base_layout.alignment.get() != 0 { - let result = Err(( - handle, - Disalignment::Member { - index: i as u32, - offset: range.start, - alignment: base_layout.alignment.get(), - }, - )); - uniform_layout = uniform_layout.or_else(|_| result.clone()); - storage_layout = storage_layout.or(result); - } - offset = range.end; + + uniform_layout = match (uniform_layout, base_info.uniform_layout) { + (Ok(cur_alignment), Ok(alignment)) => { + if offset % alignment != 0 { + Err(( + handle, + Disalignment::Member { + index: i as u32, + offset, + alignment, + }, + )) + } else { + let combined_alignment = + ((cur_alignment - 1) | (alignment - 1)) + 1; + Ok(combined_alignment) + } + } + (Err(e), _) | (_, Err(e)) => Err(e), + }; + storage_layout = match (storage_layout, base_info.storage_layout) { + (Ok(cur_alignment), Ok(alignment)) => { + if offset % alignment != 0 { + Err(( + handle, + Disalignment::Member { + index: i as u32, + offset, + alignment, + }, + )) + } else { + let combined_alignment = + ((cur_alignment - 1) | (alignment - 1)) + 1; + Ok(combined_alignment) + } + } + (Err(e), _) | (_, Err(e)) => Err(e), + }; + offset += member.span; // only the last field can be unsized if !base_info.flags.contains(TypeFlags::SIZED) { @@ -303,9 +339,6 @@ impl super::Validator { Err((handle, Disalignment::UnsizedMember { index: i as u32 })); } } - - uniform_layout = uniform_layout.or_else(|_| base_info.uniform_layout.clone()); - storage_layout = storage_layout.or_else(|_| base_info.storage_layout.clone()); } if block { flags |= TypeFlags::BLOCK; @@ -331,7 +364,7 @@ impl super::Validator { storage_layout, } } - Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::from_flags(TypeFlags::empty()), + Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::new(TypeFlags::empty(), 0), }) } } diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap index aff136329..4f5c1ef92 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron.snap @@ -498,24 +498,4 @@ expression: output ], ), ], - layouter: ( - layouts: [ - ( - size: 4, - alignment: 4, - ), - ( - size: 4, - alignment: 4, - ), - ( - size: 4, - alignment: 4, - ), - ( - size: 12, - alignment: 16, - ), - ], - ), ) diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap index e4e9224c7..52b22cebe 100644 --- a/tests/out/collatz.ron.snap +++ b/tests/out/collatz.ron.snap @@ -16,7 +16,7 @@ expression: output inner: Array( base: 1, size: Dynamic, - stride: Some(4), + stride: 4, ), ), ( @@ -28,8 +28,7 @@ expression: output name: Some("data"), ty: 2, binding: None, - size: None, - align: None, + span: 4, ), ], ), diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap index 928083055..3260f6134 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron.snap @@ -2873,236 +2873,4 @@ expression: output ], ), ], - layouter: ( - layouts: [ - ( - size: 4, - alignment: 4, - ), - ( - size: 12, - alignment: 16, - ), - ( - size: 4, - alignment: 4, - ), - ( - size: 16, - alignment: 16, - ), - ( - size: 1, - alignment: 1, - ), - ( - size: 8, - alignment: 8, - ), - ( - size: 0, - alignment: 1, - ), - ( - size: 0, - alignment: 1, - ), - ( - size: 8, - alignment: 8, - ), - ( - size: 4, - alignment: 4, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 16, - alignment: 16, - ), - ( - size: 16, - alignment: 16, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 64, - alignment: 16, - ), - ( - size: 96, - alignment: 16, - ), - ( - size: 96, - alignment: 96, - ), - ( - size: 128, - alignment: 96, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 4, - alignment: 1, - ), - ( - size: 0, - alignment: 1, - ), - ( - size: 0, - alignment: 1, - ), - ], - ), ) diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index cb7c0d81e..1f73006de 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -112,8 +112,7 @@ expression: output name: Some("num_lights"), ty: 13, binding: None, - size: None, - align: None, + span: 16, ), ], ), @@ -156,22 +155,19 @@ expression: output name: Some("proj"), ty: 18, binding: None, - size: None, - align: None, + span: 64, ), ( name: Some("pos"), ty: 4, binding: None, - size: None, - align: None, + span: 16, ), ( name: Some("color"), ty: 4, binding: None, - size: None, - align: None, + span: 16, ), ], ), @@ -181,7 +177,7 @@ expression: output inner: Array( base: 19, size: Dynamic, - stride: Some(96), + stride: 96, ), ), ( @@ -193,8 +189,7 @@ expression: output name: Some("data"), ty: 20, binding: None, - size: None, - align: None, + span: 96, ), ], ), From 604e10e19b1f8ce284b5da14ce72d47b670f8832 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 6 Apr 2021 23:40:11 -0400 Subject: [PATCH 0675/2212] Rewrite IR to have member offsets, full structure span and alignment --- src/back/glsl/mod.rs | 26 ++-- src/back/msl/writer.rs | 50 ++++---- src/back/spv/writer.rs | 24 ++-- src/front/glsl/functions.rs | 6 +- src/front/glsl/parser.rs | 25 +++- src/front/glsl/variables.rs | 5 +- src/front/spv/function.rs | 7 +- src/front/spv/mod.rs | 39 +++--- src/front/wgsl/layout.rs | 59 ++++----- src/front/wgsl/mod.rs | 24 ++-- src/lib.rs | 26 ++-- src/proc/mod.rs | 17 +-- src/proc/namer.rs | 6 +- src/proc/typifier.rs | 10 +- src/valid/expression.rs | 10 +- src/valid/interface.rs | 3 +- src/valid/type.rs | 238 ++++++++++++++++++++++-------------- tests/out/collatz.ron.snap | 5 +- tests/out/shadow.ron.snap | 21 ++-- 19 files changed, 321 insertions(+), 280 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b27b6468b..3674a2076 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -448,11 +448,7 @@ impl<'a, W: Write> Writer<'a, W> { // This are always ordered because of the IR is structured in a way that you can't make a // struct without adding all of it's members first for (handle, ty) in self.module.types.iter() { - if let TypeInner::Struct { - block: _, - ref members, - } = ty.inner - { + if let TypeInner::Struct { ref members, .. } = ty.inner { // No needed to write a struct that also should be written as a global variable let is_global_struct = self .module @@ -670,11 +666,12 @@ impl<'a, W: Write> Writer<'a, W> { // glsl has no pointer types so just write types as normal and loads are skipped TypeInner::Pointer { base, .. } => self.write_type(base), TypeInner::Struct { - block: true, + level: crate::StructLevel::Root, ref members, + span: _, } => self.write_struct(true, ty, members), // glsl structs are written as just the struct name if it isn't a block - TypeInner::Struct { block: false, .. } => { + TypeInner::Struct { .. } => { // Get the struct name let name = &self.names[&NameKey::Type(ty)]; write!(self.out, "{}", name)?; @@ -790,10 +787,7 @@ impl<'a, W: Write> Writer<'a, W> { output: bool, ) -> Result<(), Error> { match self.module.types[ty].inner { - crate::TypeInner::Struct { - block: _, - ref members, - } => { + crate::TypeInner::Struct { ref members, .. } => { for member in members { self.write_varying(member.binding.as_ref(), member.ty, output)?; } @@ -918,10 +912,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, " {}", name)?; write!(self.out, " = ")?; match self.module.types[arg.ty].inner { - crate::TypeInner::Struct { - block: _, - ref members, - } => { + crate::TypeInner::Struct { ref members, .. } => { self.write_type(arg.ty)?; write!(self.out, "(")?; for (index, member) in members.iter().enumerate() { @@ -1338,10 +1329,7 @@ impl<'a, W: Write> Writer<'a, W> { if let Some(ref result) = ep.function.result { let value = value.unwrap(); match self.module.types[result.ty].inner { - crate::TypeInner::Struct { - block: _, - ref members, - } => { + crate::TypeInner::Struct { ref members, .. } => { for (index, member) in members.iter().enumerate() { let varying_name = VaryingName { binding: member.binding.as_ref().unwrap(), diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c71f23af3..74d2637c9 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1000,10 +1000,7 @@ impl Writer { Some(struct_name) => { let result_ty = context.function.result.as_ref().unwrap().ty; match context.module.types[result_ty].inner { - crate::TypeInner::Struct { - block: _, - ref members, - } => { + crate::TypeInner::Struct { ref members, .. } => { let tmp = "_tmp"; write!(self.out, "{}const auto {} = ", level, tmp)?; self.put_expression(expr_handle, context, true)?; @@ -1373,12 +1370,16 @@ impl Writer { } } } - crate::TypeInner::Struct { - block: _, - ref members, - } => { + crate::TypeInner::Struct { ref members, .. } => { writeln!(self.out, "struct {} {{", name)?; + let mut last_offset = 0; for (index, member) in members.iter().enumerate() { + // quick and dirty way to figure out if we need this... + if member.binding.is_none() && member.offset > last_offset { + let pad = member.offset - last_offset; + //TODO: adjust the struct initializers + writeln!(self.out, "{}char _pad{}[{}];", INDENT, index, pad)?; + } let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; let base_name = TypeContext { handle: member.ty, @@ -1389,13 +1390,16 @@ impl Writer { first_time: false, }; writeln!(self.out, "{}{} {};", INDENT, base_name, member_name)?; - // quick and dirty way to figure out if we need this... - if member.binding.is_none() { - let pad = - member.span - module.types[member.ty].inner.span(&module.constants); - if pad != 0 { - writeln!(self.out, "{}char _pad{}[{}];", INDENT, index, pad)?; - } + let ty_inner = &module.types[member.ty].inner; + last_offset = member.offset + ty_inner.span(&module.constants); + // for 3-component vectors, add one component + if let crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + kind: _, + width, + } = *ty_inner + { + last_offset += width as u32; } } writeln!(self.out, "}};")?; @@ -1728,10 +1732,7 @@ impl Writer { let mut argument_members = Vec::new(); for (arg_index, arg) in fun.arguments.iter().enumerate() { match module.types[arg.ty].inner { - crate::TypeInner::Struct { - block: _, - ref members, - } => { + crate::TypeInner::Struct { ref members, .. } => { for (member_index, member) in members.iter().enumerate() { argument_members.push(( NameKey::StructMember(arg.ty, member_index as u32), @@ -1778,10 +1779,8 @@ impl Writer { let result_type_name = match fun.result { Some(ref result) => { let mut result_members = Vec::new(); - if let crate::TypeInner::Struct { - block: _, - ref members, - } = module.types[result.ty].inner + if let crate::TypeInner::Struct { ref members, .. } = + module.types[result.ty].inner { for (member_index, member) in members.iter().enumerate() { result_members.push(( @@ -1959,10 +1958,7 @@ impl Writer { let arg_name = &self.names[&NameKey::EntryPointArgument(ep_index as _, arg_index as u32)]; match module.types[arg.ty].inner { - crate::TypeInner::Struct { - block: _, - ref members, - } => { + crate::TypeInner::Struct { ref members, .. } => { let struct_name = &self.names[&NameKey::Type(arg.ty)]; write!( self.out, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d82a5059e..aa720a554 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -455,10 +455,8 @@ impl Writer { .body .push(Instruction::load(argument_type_id, id, varying_id, None)); id - } else if let crate::TypeInner::Struct { - block: _, - ref members, - } = ir_module.types[argument.ty].inner + } else if let crate::TypeInner::Struct { ref members, .. } = + ir_module.types[argument.ty].inner { let struct_id = self.id_gen.next(); let mut constituent_ids = Vec::with_capacity(members.len()); @@ -509,10 +507,8 @@ impl Writer { type_id, built_in: binding.to_built_in(), }); - } else if let crate::TypeInner::Struct { - block: _, - ref members, - } = ir_module.types[result.ty].inner + } else if let crate::TypeInner::Struct { ref members, .. } = + ir_module.types[result.ty].inner { for member in members { let type_id = @@ -862,13 +858,16 @@ impl Writer { crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), } } - crate::TypeInner::Struct { block, ref members } => { - if block { + crate::TypeInner::Struct { + ref level, + ref members, + span: _, + } => { + if let crate::StructLevel::Root = *level { self.annotations .push(Instruction::decorate(id, Decoration::Block, &[])); } - let mut current_offset = 0; let mut member_ids = Vec::with_capacity(members.len()); for (index, member) in members.iter().enumerate() { if decorate_layout { @@ -876,9 +875,8 @@ impl Writer { id, index as u32, Decoration::Offset, - &[current_offset], + &[member.offset], )); - current_offset += member.span; } if self.flags.contains(WriterFlags::DEBUG) { diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index e1492e84b..ed3908fca 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -241,11 +241,7 @@ impl Program<'_> { } else { let ty = &self.module.types[var.ty]; // anonymous structs - if let TypeInner::Struct { - block: _, - ref members, - } = ty.inner - { + if let TypeInner::Struct { ref members, .. } = ty.inner { let base = self .context .expressions diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 9f09b27e9..10eacb5e3 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -514,15 +514,21 @@ pomelo! { if i.1 == "gl_PerVertex" { None } else { - let block = !t.is_empty(); + let level = if t.is_empty() { + //TODO + crate::StructLevel::Normal { alignment: crate::Alignment::new(1).unwrap() } + } else { + crate::StructLevel::Root + }; Some(VarDeclaration { type_qualifiers: t, ids_initializers: vec![(None, None)], ty: extra.module.types.fetch_or_append(Type{ name: Some(i.1), inner: TypeInner::Struct { - block, + level, members: sdl, + span: 0, //TODO }, }), }) @@ -531,15 +537,21 @@ pomelo! { declaration ::= type_qualifier(t) Identifier(i1) LeftBrace struct_declaration_list(sdl) RightBrace Identifier(i2) Semicolon { - let block = !t.is_empty(); + let level = if t.is_empty() { + //TODO + crate::StructLevel::Normal { alignment: crate::Alignment::new(1).unwrap() } + } else { + crate::StructLevel::Root + }; Some(VarDeclaration { type_qualifiers: t, ids_initializers: vec![(Some(i2.1), None)], ty: extra.module.types.fetch_or_append(Type{ name: Some(i1.1), inner: TypeInner::Struct { - block, + level, members: sdl, + span: 0, //TODO }, }), }) @@ -706,8 +718,9 @@ pomelo! { Type{ name: Some(i.1), inner: TypeInner::Struct { - block: false, + level: crate::StructLevel::Normal { alignment: crate::Alignment::new(1).unwrap() }, members: vec![], + span: 0, } } } @@ -729,7 +742,7 @@ pomelo! { binding: None, //TODO //TODO: if the struct is a uniform struct, these values have to reflect // std140 layout. Otherwise, std430. - span: extra.module.types[ty].inner.span(&extra.module.constants), + offset: 0, }).collect() } else { return Err(ErrorKind::SemanticError("Struct member can't be void".into())) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index d08c59347..1adf25964 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -133,10 +133,7 @@ impl Program<'_> { meta: TokenMetadata, ) -> Result, ErrorKind> { match *self.resolve_type(expression)? { - TypeInner::Struct { - block: _, - ref members, - } => { + TypeInner::Struct { ref members, .. } => { let index = members .iter() .position(|m| m.name == Some(name.into())) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 82f74f16a..2a6f83bad 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -262,7 +262,7 @@ impl> super::Parser { name: None, ty: result.ty, binding: result.binding.clone(), - span: module.types[result.ty].inner.span(&module.constants), + offset: 0, }); // populate just the globals first, then do `Load` in a // separate step, so that we can get a range. @@ -328,8 +328,11 @@ impl> super::Parser { let ty = module.types.append(crate::Type { name: None, inner: crate::TypeInner::Struct { - block: false, + level: crate::StructLevel::Normal { + alignment: crate::Alignment::new(1).unwrap(), + }, members, + span: 0xFFFF, // shouldn't matter }, }); let result_expr = function diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 8baf6834a..6a4164665 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2488,7 +2488,6 @@ impl> Parser { let mut members = Vec::::with_capacity(inst.wc as usize - 2); let mut member_type_ids = Vec::with_capacity(members.capacity()); - let mut last_offset = 0; for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; member_type_ids.push(type_id); @@ -2499,28 +2498,40 @@ impl> Parser { .unwrap_or_default(); let binding = decor.io_binding().ok(); - if let Some(offset) = decor.offset { - if offset != last_offset { - if let Some(member) = members.last_mut() { - // add padding, if necessary - member.span = offset - (last_offset - member.span); + let offset = match decor.offset { + Some(offset) => offset, + None => match members.last() { + Some(member) => { + member.offset + module.types[member.ty].inner.span(&module.constants) } - last_offset = offset; - } - } - let span = module.types[ty].inner.span(&module.constants); - last_offset += span; - + None => 0, + }, + }; members.push(crate::StructMember { name: decor.name, ty, binding, - span, + offset, }); } + //TODO: we should be able to do better than this. + const STRUCT_ALIGNMENT: u32 = 16; + let inner = crate::TypeInner::Struct { - block: block_decor.is_some(), + level: match block_decor { + Some(_) => crate::StructLevel::Root, + None => crate::StructLevel::Normal { + alignment: crate::Alignment::new(STRUCT_ALIGNMENT).unwrap(), + }, + }, + span: match members.last() { + Some(member) => { + let end = member.offset + module.types[member.ty].inner.span(&module.constants); + ((end - 1) | (STRUCT_ALIGNMENT - 1)) + 1 + } + None => STRUCT_ALIGNMENT, + }, members, }; let ty_handle = module.types.append(crate::Type { diff --git a/src/front/wgsl/layout.rs b/src/front/wgsl/layout.rs index 91734067f..e17d5548e 100644 --- a/src/front/wgsl/layout.rs +++ b/src/front/wgsl/layout.rs @@ -1,7 +1,5 @@ use crate::arena::{Arena, Handle}; -use std::num::NonZeroU32; - -pub type Alignment = NonZeroU32; +use std::{num::NonZeroU32, ops}; /// Alignment information for a type. #[derive(Clone, Copy, Debug, Hash, PartialEq)] @@ -9,7 +7,7 @@ pub type Alignment = NonZeroU32; #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct TypeLayout { pub size: u32, - pub alignment: Alignment, + pub alignment: crate::Alignment, } /// Helper processor that derives the sizes of all types. @@ -22,17 +20,12 @@ pub struct Layouter { layouts: Vec, } -pub struct Placement { - pub pad: crate::Span, - pub span: crate::Span, -} - impl Layouter { pub fn clear(&mut self) { self.layouts.clear(); } - pub fn round_up(alignment: Alignment, offset: u32) -> u32 { + pub fn round_up(alignment: crate::Alignment, offset: u32) -> u32 { match offset & (alignment.get() - 1) { 0 => offset, other => offset + alignment.get() - other, @@ -43,9 +36,9 @@ impl Layouter { &self, offset: u32, ty: Handle, - align: Option, + align: Option, size: Option, - ) -> Placement { + ) -> (ops::Range, crate::Alignment) { let layout = self.layouts[ty.index()]; let alignment = align.unwrap_or(layout.alignment); let start = Self::round_up(alignment, offset); @@ -53,10 +46,7 @@ impl Layouter { Some(size) => size.get(), None => layout.size, }; - Placement { - pad: start - offset, - span, - } + (start..start + span, alignment) } pub fn update(&mut self, types: &Arena, constants: &Arena) { @@ -66,7 +56,7 @@ impl Layouter { let layout = match ty.inner { Ti::Scalar { width, .. } => TypeLayout { size, - alignment: Alignment::new(width as u32).unwrap(), + alignment: crate::Alignment::new(width as u32).unwrap(), }, Ti::Vector { size: vec_size, @@ -80,7 +70,7 @@ impl Layouter { } else { 2 }; - Alignment::new((count * width) as u32).unwrap() + crate::Alignment::new((count * width) as u32).unwrap() }, }, Ti::Matrix { @@ -91,36 +81,31 @@ impl Layouter { size, alignment: { let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; - Alignment::new((count * width) as u32).unwrap() + crate::Alignment::new((count * width) as u32).unwrap() }, }, Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { size, - alignment: Alignment::new(1).unwrap(), + alignment: crate::Alignment::new(1).unwrap(), }, Ti::Array { stride, .. } => TypeLayout { size, - alignment: Alignment::new(stride).unwrap(), + alignment: crate::Alignment::new(stride).unwrap(), }, Ti::Struct { - block: _, - ref members, - } => { - let mut total = 0; - let mut biggest_alignment = Alignment::new(1).unwrap(); - for member in members { - let layout = self.layouts[member.ty.index()]; - biggest_alignment = biggest_alignment.max(layout.alignment); - total += member.span; - } - TypeLayout { - size: Self::round_up(biggest_alignment, total), - alignment: biggest_alignment, - } - } + ref level, + members: _, + span, + } => TypeLayout { + size: span, + alignment: match *level { + crate::StructLevel::Root => crate::Alignment::new(1).unwrap(), + crate::StructLevel::Normal { alignment } => alignment, + }, + }, Ti::Image { .. } | Ti::Sampler { .. } => TypeLayout { size, - alignment: Alignment::new(1).unwrap(), + alignment: crate::Alignment::new(1).unwrap(), }, }; debug_assert!(ty.inner.span(constants) <= layout.size); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f4c19e00f..e618d6812 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1509,8 +1509,9 @@ impl Parser { lexer: &mut Lexer<'a>, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result, Error<'a>> { + ) -> Result<(Vec, u32, crate::Alignment), Error<'a>> { let mut offset = 0; + let mut alignment = crate::Alignment::new(1).unwrap(); let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; @@ -1556,7 +1557,7 @@ impl Parser { let name = match lexer.next() { (Token::Word(word), _) => word, - (Token::Paren('}'), _) => return Ok(members), + (Token::Paren('}'), _) => return Ok((members, offset, alignment)), other => return Err(Error::Unexpected(other, "field name")), }; lexer.expect(Token::Separator(':'))?; @@ -1564,17 +1565,15 @@ impl Parser { lexer.expect(Token::Separator(';'))?; self.layouter.update(type_arena, const_arena); - let placement = self.layouter.member_placement(offset, ty, align, size); - if placement.pad != 0 { - members.last_mut().unwrap().span += placement.pad; - } - offset += placement.pad + placement.span; + let (range, align) = self.layouter.member_placement(offset, ty, align, size); + alignment = alignment.max(align); + offset = range.end; members.push(crate::StructMember { name: Some(name.to_owned()), ty, binding: bind_parser.finish()?, - span: placement.span, + offset: range.start, }); } } @@ -2556,13 +2555,18 @@ impl Parser { (Token::Separator(';'), _) => {} (Token::Word("struct"), _) => { let name = lexer.next_ident()?; - let members = + let (members, span, alignment) = self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?; let ty = module.types.fetch_or_append(crate::Type { name: Some(name.to_string()), inner: crate::TypeInner::Struct { - block: is_block, + level: if is_block { + crate::StructLevel::Root + } else { + crate::StructLevel::Normal { alignment } + }, members, + span, }, }); self.lookup_type.insert(name.to_owned(), ty); diff --git a/src/lib.rs b/src/lib.rs index d8ab525e4..fa12613fb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,6 +50,7 @@ pub use crate::arena::{Arena, Handle, Range}; use std::{ collections::{HashMap, HashSet}, hash::BuildHasherDefault, + num::NonZeroU32, }; #[cfg(feature = "deserialize")] @@ -167,8 +168,7 @@ pub enum BuiltIn { /// Number of bytes per scalar. pub type Bytes = u8; -/// Number of bytes per complex type. -pub type Span = u32; +pub type Alignment = NonZeroU32; /// Number of components in a vector. #[repr(u8)] @@ -245,8 +245,8 @@ pub struct StructMember { pub ty: Handle, /// For I/O structs, defines the binding. pub binding: Option, - /// Size occupied by the member. - pub span: Span, + /// Offset from the beginning from the struct. + pub offset: u32, } /// The number of dimensions an image has. @@ -345,6 +345,18 @@ pub enum ImageClass { Storage(StorageFormat), } +/// Qualifier of the type level, at which a struct can be used. +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum StructLevel { + /// This is a root level struct, it can't be nested inside + /// other composite types. + Root, + /// This is a normal struct, and it has to be aligned for nesting. + Normal { alignment: Alignment }, +} + /// A data type declared in the module. #[derive(Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -391,13 +403,13 @@ pub enum TypeInner { Array { base: Handle, size: ArraySize, - stride: Span, + stride: u32, }, /// User-defined structure. Struct { - /// This is a top-level host-shareable structure. - block: bool, + level: StructLevel, members: Vec, + span: u32, }, /// Possibly multidimensional array of texels. Image { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 1d9e7d878..55266d2bd 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -79,20 +79,12 @@ impl super::TypeInner { size, kind: _, width, - } => { - //let count = if size >= super::VectorSize::Tri { 4 } else { 2 }; - let count = size as u8; //TEMP - (count * width) as u32 - } + } => (size as u8 * width) as u32, Self::Matrix { columns, rows, width, - } => { - //let count = if rows >= super::VectorSize::Tri { 4 } else { 2 }; - let count = rows as u8; //TEMP - (columns as u8 * count * width) as u32 - } + } => (columns as u8 * rows as u8 * width) as u32, Self::Pointer { .. } | Self::ValuePointer { .. } => POINTER_SPAN, Self::Array { base: _, @@ -108,10 +100,7 @@ impl super::TypeInner { }; count * stride } - Self::Struct { - block: _, - ref members, - } => members.iter().map(|m| m.span).sum(), + Self::Struct { span, .. } => span, Self::Image { .. } | Self::Sampler { .. } => 0, } } diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 87ef357ac..7f62ff170 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -77,11 +77,7 @@ impl Namer { let ty_name = self.call_or(&ty.name, "type"); output.insert(NameKey::Type(ty_handle), ty_name); - if let crate::TypeInner::Struct { - block: _, - ref members, - } = ty.inner - { + if let crate::TypeInner::Struct { ref members, .. } = ty.inner { for (index, member) in members.iter().enumerate() { let name = self.call_or(&member.name, "member"); output.insert(NameKey::StructMember(ty_handle, index as u32), name); diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 3183c5bd9..50455defc 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -178,10 +178,7 @@ impl<'a> ResolveContext<'a> { }) } Ti::Array { base, .. } => TypeResolution::Handle(base), - Ti::Struct { - block: _, - ref members, - } => { + Ti::Struct { ref members, .. } => { let member = members .get(index as usize) .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; @@ -234,10 +231,7 @@ impl<'a> ResolveContext<'a> { class, } } - Ti::Struct { - block: _, - ref members, - } => { + Ti::Struct { ref members, .. } => { let member = members .get(index as usize) .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; diff --git a/src/valid/expression.rs b/src/valid/expression.rs index b21f53488..23e6c9546 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -179,10 +179,7 @@ impl super::Validator { } => module.constants[handle].to_array_length().unwrap(), Ti::Array { .. } => !0, // can't statically know, but need run-time checks Ti::Pointer { .. } => !0, //TODO - Ti::Struct { - ref members, - block: _, - } => members.len() as u32, + Ti::Struct { ref members, .. } => members.len() as u32, ref other => { log::error!("Indexing of {:?}", other); return Err(ExpressionError::InvalidBaseType(base)); @@ -289,10 +286,7 @@ impl super::Validator { } } } - Ti::Struct { - block: _, - ref members, - } => { + Ti::Struct { ref members, .. } => { for (index, (member, &comp)) in members.iter().zip(components).enumerate() { let tin = resolver.resolve(comp)?; if tin != &module.types[member.ty].inner { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 0d144150c..17629d1e0 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -239,8 +239,9 @@ impl VaryingContext<'_> { match self.types[self.ty].inner { //TODO: check the member types crate::TypeInner::Struct { - block: false, + level: crate::StructLevel::Normal { .. }, ref members, + .. } => { for (index, member) in members.iter().enumerate() { self.ty = member.ty; diff --git a/src/valid/type.rs b/src/valid/type.rs index d2cad1f86..ff34e81fe 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -1,7 +1,5 @@ use crate::arena::{Arena, Handle}; -pub type Alignment = u32; - bitflags::bitflags! { #[repr(transparent)] pub struct TypeFlags: u8 { @@ -22,10 +20,16 @@ bitflags::bitflags! { pub enum Disalignment { #[error("The array stride {stride} is not a multiple of the required alignment {alignment}")] ArrayStride { stride: u32, alignment: u32 }, - #[error("The struct size {size}, is not a multiple of the required alignment {alignment}")] - StructSize { size: u32, alignment: u32 }, + #[error("The struct span {span}, is not a multiple of the required alignment {alignment}")] + StructSpan { span: u32, alignment: u32 }, + #[error("The struct span {alignment}, is not a multiple of the member[{member_index}] alignment {member_alignment}")] + StructAlignment { + alignment: u32, + member_index: u32, + member_alignment: u32, + }, #[error("The struct member[{index}] offset {offset} is not a multiple of the required alignment {alignment}")] - Member { + MemberOffset { index: u32, offset: u32, alignment: u32, @@ -52,18 +56,62 @@ pub enum TypeError { InsufficientArrayStride { stride: u32, base_size: u32 }, #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] InvalidDynamicArray(String, Handle), - #[error("Structure member[{index}] size {size} is not a sufficient to hold {base_size}")] - InsufficientMemberSize { - index: u32, - size: u32, - base_size: u32, - }, + #[error("Structure member[{index}] at {offset} overlaps the previous member")] + MemberOverlap { index: u32, offset: u32 }, + #[error( + "Structure member[{index}] at {offset} and size {size} crosses the structure boundary" + )] + MemberOutOfBounds { index: u32, offset: u32, size: u32 }, #[error("The composite type contains a block structure")] NestedBlock, } // Only makes sense if `flags.contains(HOST_SHARED)` -type LayoutCompatibility = Result, Disalignment)>; +type LayoutCompatibility = Result, (Handle, Disalignment)>; + +fn check_member_layout( + accum: &mut LayoutCompatibility, + member: &crate::StructMember, + member_index: u32, + member_layout: LayoutCompatibility, + struct_level: crate::StructLevel, + ty_handle: Handle, +) { + *accum = match (*accum, member_layout) { + (Ok(cur_alignment), Ok(align)) => { + let align = align.unwrap().get(); + if member.offset % align != 0 { + Err(( + ty_handle, + Disalignment::MemberOffset { + index: member_index, + offset: member.offset, + alignment: align, + }, + )) + } else { + match struct_level { + crate::StructLevel::Normal { alignment } if alignment.get() % align != 0 => { + Err(( + ty_handle, + Disalignment::StructAlignment { + alignment: alignment.get(), + member_index, + member_alignment: align, + }, + )) + } + _ => { + let combined_alignment = + ((cur_alignment.unwrap().get() - 1) | (align - 1)) + 1; + Ok(crate::Alignment::new(combined_alignment)) + } + } + } + } + (Err(e), _) | (_, Err(e)) => Err(e), + }; +} // For the uniform buffer alignment, array strides and struct sizes must be multiples of 16. const UNIFORM_LAYOUT_ALIGNMENT_MASK: u32 = 0xF; @@ -79,12 +127,13 @@ impl TypeInfo { fn dummy() -> Self { TypeInfo { flags: TypeFlags::empty(), - uniform_layout: Ok(0), - storage_layout: Ok(0), + uniform_layout: Ok(None), + storage_layout: Ok(None), } } - fn new(flags: TypeFlags, alignment: crate::Span) -> Self { + fn new(flags: TypeFlags, align: u32) -> Self { + let alignment = crate::Alignment::new(align); TypeInfo { flags, uniform_layout: Ok(alignment), @@ -193,21 +242,36 @@ impl super::Validator { let uniform_layout = match base_info.uniform_layout { Ok(base_alignment) => { // combine the alignment requirements - let alignment = ((base_alignment - 1) | UNIFORM_LAYOUT_ALIGNMENT_MASK) + 1; - if stride % alignment != 0 { - Err((handle, Disalignment::ArrayStride { stride, alignment })) + let align = ((base_alignment.unwrap().get() - 1) + | UNIFORM_LAYOUT_ALIGNMENT_MASK) + + 1; + if stride % align != 0 { + Err(( + handle, + Disalignment::ArrayStride { + stride, + alignment: align, + }, + )) } else { - Ok(alignment) + Ok(crate::Alignment::new(align)) } } Err(e) => Err(e), }; let storage_layout = match base_info.storage_layout { - Ok(alignment) => { - if stride % alignment != 0 { - Err((handle, Disalignment::ArrayStride { stride, alignment })) + Ok(base_alignment) => { + let align = base_alignment.unwrap().get(); + if stride % align != 0 { + Err(( + handle, + Disalignment::ArrayStride { + stride, + alignment: align, + }, + )) } else { - Ok(alignment) + Ok(base_alignment) } } Err(e) => Err(e), @@ -255,14 +319,19 @@ impl super::Validator { storage_layout, } } - Ti::Struct { block, ref members } => { - let mut flags = TypeFlags::DATA - | TypeFlags::SIZED - | TypeFlags::HOST_SHARED - | TypeFlags::INTERFACE; - let mut uniform_layout = Ok(1); - let mut storage_layout = Ok(1); - let mut offset = 0; + Ti::Struct { + level, + ref members, + span, + } => { + let mut ti = TypeInfo::new( + TypeFlags::DATA + | TypeFlags::SIZED + | TypeFlags::HOST_SHARED + | TypeFlags::INTERFACE, + 1, + ); + let mut min_offset = 0; for (i, member) in members.iter().enumerate() { if member.ty >= handle { return Err(TypeError::UnresolvedBase(member.ty)); @@ -271,62 +340,55 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); } - if block && !base_info.flags.contains(TypeFlags::INTERFACE) { + if level == crate::StructLevel::Root + && !base_info.flags.contains(TypeFlags::INTERFACE) + { return Err(TypeError::InvalidBlockType(member.ty)); } if base_info.flags.contains(TypeFlags::BLOCK) { return Err(TypeError::NestedBlock); } - flags &= base_info.flags; + ti.flags &= base_info.flags; + if member.offset < min_offset { + //HACK: this could be nicer. We want to allow some structures + // to not bother with offsets/alignments if they are never + // used for host sharing. + if member.offset == 0 { + ti.flags.set(TypeFlags::HOST_SHARED, false); + } else { + return Err(TypeError::MemberOverlap { + index: i as u32, + offset: member.offset, + }); + } + } let base_size = types[member.ty].inner.span(constants); - if member.span < base_size { - return Err(TypeError::InsufficientMemberSize { + min_offset = member.offset + base_size; + if min_offset > span { + return Err(TypeError::MemberOutOfBounds { index: i as u32, - size: member.span, - base_size, + offset: member.offset, + size: base_size, }); } - uniform_layout = match (uniform_layout, base_info.uniform_layout) { - (Ok(cur_alignment), Ok(alignment)) => { - if offset % alignment != 0 { - Err(( - handle, - Disalignment::Member { - index: i as u32, - offset, - alignment, - }, - )) - } else { - let combined_alignment = - ((cur_alignment - 1) | (alignment - 1)) + 1; - Ok(combined_alignment) - } - } - (Err(e), _) | (_, Err(e)) => Err(e), - }; - storage_layout = match (storage_layout, base_info.storage_layout) { - (Ok(cur_alignment), Ok(alignment)) => { - if offset % alignment != 0 { - Err(( - handle, - Disalignment::Member { - index: i as u32, - offset, - alignment, - }, - )) - } else { - let combined_alignment = - ((cur_alignment - 1) | (alignment - 1)) + 1; - Ok(combined_alignment) - } - } - (Err(e), _) | (_, Err(e)) => Err(e), - }; - offset += member.span; + check_member_layout( + &mut ti.uniform_layout, + member, + i as u32, + base_info.uniform_layout, + level, + handle, + ); + check_member_layout( + &mut ti.storage_layout, + member, + i as u32, + base_info.storage_layout, + level, + handle, + ); // only the last field can be unsized if !base_info.flags.contains(TypeFlags::SIZED) { @@ -334,35 +396,31 @@ impl super::Validator { let name = member.name.clone().unwrap_or_default(); return Err(TypeError::InvalidDynamicArray(name, member.ty)); } - if uniform_layout.is_ok() { - uniform_layout = + if ti.uniform_layout.is_ok() { + ti.uniform_layout = Err((handle, Disalignment::UnsizedMember { index: i as u32 })); } } } - if block { - flags |= TypeFlags::BLOCK; + if let crate::StructLevel::Root = level { + ti.flags |= TypeFlags::BLOCK; } // disabled temporarily, see https://github.com/gpuweb/gpuweb/issues/1558 const CHECK_STRUCT_SIZE: bool = false; if CHECK_STRUCT_SIZE - && uniform_layout.is_ok() - && offset & UNIFORM_LAYOUT_ALIGNMENT_MASK != 0 + && ti.uniform_layout.is_ok() + && span & UNIFORM_LAYOUT_ALIGNMENT_MASK != 0 { - uniform_layout = Err(( + ti.uniform_layout = Err(( handle, - Disalignment::StructSize { - size: offset, + Disalignment::StructSpan { + span, alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK + 1, }, )); } - TypeInfo { - flags, - uniform_layout, - storage_layout, - } + ti } Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::new(TypeFlags::empty(), 0), }) diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap index 52b22cebe..b86183c22 100644 --- a/tests/out/collatz.ron.snap +++ b/tests/out/collatz.ron.snap @@ -22,15 +22,16 @@ expression: output ( name: Some("PrimeIndices"), inner: Struct( - block: true, + level: Root, members: [ ( name: Some("data"), ty: 2, binding: None, - span: 4, + offset: 0, ), ], + span: 4, ), ), ( diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap index 1f73006de..0d57ef42e 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron.snap @@ -106,15 +106,16 @@ expression: output ( name: Some("Globals"), inner: Struct( - block: true, + level: Root, members: [ ( name: Some("num_lights"), ty: 13, binding: None, - span: 16, + offset: 0, ), ], + span: 16, ), ), ( @@ -149,27 +150,30 @@ expression: output ( name: Some("Light"), inner: Struct( - block: false, + level: Normal( + alignment: 16, + ), members: [ ( name: Some("proj"), ty: 18, binding: None, - span: 64, + offset: 0, ), ( name: Some("pos"), ty: 4, binding: None, - span: 16, + offset: 64, ), ( name: Some("color"), ty: 4, binding: None, - span: 16, + offset: 80, ), ], + span: 96, ), ), ( @@ -183,15 +187,16 @@ expression: output ( name: Some("Lights"), inner: Struct( - block: true, + level: Root, members: [ ( name: Some("data"), ty: 20, binding: None, - span: 96, + offset: 0, ), ], + span: 96, ), ), ( From 4ff5fa4568309a15ff80bec9a3ae973efb52483d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 8 Apr 2021 23:03:30 -0400 Subject: [PATCH 0676/2212] [msl-out] add support for matrix value types --- src/back/msl/writer.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 74d2637c9..7cad22b9a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1084,6 +1084,16 @@ impl Writer { vector_size_string(size) )?; } + TypeResolution::Value(crate::TypeInner::Matrix { columns, rows, .. }) => { + write!( + self.out, + "{}::{}{}x{}", + NAMESPACE, + scalar_kind_string(crate::ScalarKind::Float), + vector_size_string(columns), + vector_size_string(rows), + )?; + } TypeResolution::Value(ref other) => { log::error!("Type {:?} isn't a known local", other); return Err(Error::FeatureNotImplemented("weird local type".to_string())); From f3ba6e91c27be6dfc8015a2dc1b9125505afa316 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 8 Apr 2021 23:59:47 -0400 Subject: [PATCH 0677/2212] [msl-out] shorten the expression name --- src/back/msl/writer.rs | 2 +- tests/out/collatz.msl.snap | 4 ++-- tests/out/image-copy.msl.snap | 6 +++--- tests/out/quad-vert.msl.snap | 4 ++-- tests/out/quad.msl.snap | 6 +++--- tests/out/shadow.msl.snap | 12 ++++++------ tests/out/skybox.msl.snap | 12 ++++++------ 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7cad22b9a..fc2fc4942 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -16,7 +16,7 @@ use std::{ const NAMESPACE: &str = "metal"; const INDENT: &str = " "; -const BAKE_PREFIX: &str = "_expr"; +const BAKE_PREFIX: &str = "_e"; #[derive(Clone)] struct Level(usize); diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap index f86b138a7..efded439e 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl.snap @@ -36,8 +36,8 @@ kernel void main1( metal::uint3 global_id [[thread_position_in_grid]] , device PrimeIndices& v_indices [[user(fake0)]] ) { - metal::uint _expr9 = collatz_iterations(v_indices.data[global_id.x]); - v_indices.data[global_id.x] = _expr9; + metal::uint _e9 = collatz_iterations(v_indices.data[global_id.x]); + v_indices.data[global_id.x] = _e9; return; } diff --git a/tests/out/image-copy.msl.snap b/tests/out/image-copy.msl.snap index da5c6b155..893768a9b 100644 --- a/tests/out/image-copy.msl.snap +++ b/tests/out/image-copy.msl.snap @@ -13,9 +13,9 @@ kernel void main1( , metal::texture2d image_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 _expr12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(10, 20); - metal::uint4 _expr13 = image_src.read(metal::uint2(_expr12)); - image_dst.write(_expr13, metal::uint(_expr12.x)); + metal::int2 _e12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(10, 20); + metal::uint4 _e13 = image_src.read(metal::uint2(_e12)); + image_dst.write(_e13, metal::uint(_e12.x)); return; } diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl.snap index 245ffea21..bc5e83c4a 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl.snap @@ -26,8 +26,8 @@ void main1( thread metal::float2 const& a_pos ) { v_uv = a_uv; - metal::float2 _expr13 = a_pos; - _.gl_Position = metal::float4(_expr13.x, _expr13.y, 0.0, 1.0); + metal::float2 _e13 = a_pos; + _.gl_Position = metal::float4(_e13.x, _e13.y, 0.0, 1.0); return; } diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap index b45e13d33..fb4f8421a 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl.snap @@ -44,10 +44,10 @@ fragment main2Output main2( , metal::sampler u_sampler [[user(fake0)]] ) { const auto uv2 = varyings1.uv2; - metal::float4 _expr4 = u_texture.sample(u_sampler, uv2); - if (_expr4.w == 0.0) { + metal::float4 _e4 = u_texture.sample(u_sampler, uv2); + if (_e4.w == 0.0) { metal::discard_fragment(); } - return main2Output { _expr4.w * _expr4 }; + return main2Output { _e4.w * _e4 }; } diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 9ac8176a1..9d4e2b3af 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -29,9 +29,9 @@ float fetch_shadow( if (homogeneous_coords.w <= 0.0) { return 1.0; } - float _expr15 = 1.0 / homogeneous_coords.w; - float _expr28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) * _expr15) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z * _expr15); - return _expr28; + float _e15 = 1.0 / homogeneous_coords.w; + float _e28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) * _e15) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z * _e15); + return _e28; } struct fs_mainInput { @@ -61,9 +61,9 @@ fragment fs_mainOutput fs_main( if (i >= metal::min(u_globals.num_lights.x, c_max_lights)) { break; } - Light _expr21 = s_lights.data[i]; - float _expr25 = fetch_shadow(i, _expr21.proj * position, t_shadow, sampler_shadow); - color1 = color1 + ((_expr25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(metal::float3(_expr21.pos.x, _expr21.pos.y, _expr21.pos.z) - metal::float3(position.x, position.y, position.z))))) * metal::float3(_expr21.color.x, _expr21.color.y, _expr21.color.z)); + Light _e21 = s_lights.data[i]; + float _e25 = fetch_shadow(i, _e21.proj * position, t_shadow, sampler_shadow); + color1 = color1 + ((_e25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(metal::float3(_e21.pos.x, _e21.pos.y, _e21.pos.z) - metal::float3(position.x, position.y, position.z))))) * metal::float3(_e21.color.x, _e21.color.y, _e21.color.z)); } return fs_mainOutput { metal::float4(color1, 1.0) }; } diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap index 67988bf82..5be5f5459 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl.snap @@ -29,10 +29,10 @@ vertex vs_mainOutput vs_main( VertexOutput out; tmp1_ = static_cast(vertex_index) / 2; tmp2_ = static_cast(vertex_index) & 1; - metal::float4 _expr24 = metal::float4((static_cast(tmp1_) * 4.0) - 1.0, (static_cast(tmp2_) * 4.0) - 1.0, 0.0, 1.0); - metal::float4 _expr50 = r_data.proj_inv * _expr24; - out.uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr50.x, _expr50.y, _expr50.z); - out.position = _expr24; + metal::float4 _e24 = metal::float4((static_cast(tmp1_) * 4.0) - 1.0, (static_cast(tmp2_) * 4.0) - 1.0, 0.0, 1.0); + metal::float4 _e50 = r_data.proj_inv * _e24; + out.uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_e50.x, _e50.y, _e50.z); + out.position = _e24; const auto _tmp = out; return vs_mainOutput { _tmp.position, _tmp.uv }; } @@ -58,7 +58,7 @@ fragment fs_mainOutput fs_main( metal::coord::normalized ); const VertexOutput in = { position, varyings1.uv }; - metal::float4 _expr5 = r_texture.sample(r_sampler, in.uv); - return fs_mainOutput { _expr5 }; + metal::float4 _e5 = r_texture.sample(r_sampler, in.uv); + return fs_mainOutput { _e5 }; } From 425c75eb3fdfe2009e9ed26cf87e09b410c860e4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 9 Apr 2021 00:15:47 -0400 Subject: [PATCH 0678/2212] [msl-out] emit packed vectors if necessary --- src/back/msl/writer.rs | 60 +++++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 18 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index fc2fc4942..788e56ff5 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1390,26 +1390,50 @@ impl Writer { //TODO: adjust the struct initializers writeln!(self.out, "{}char _pad{}[{}];", INDENT, index, pad)?; } - let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; - let base_name = TypeContext { - handle: member.ty, - arena: &module.types, - names: &self.names, - usage: global_use, - access: crate::StorageAccess::empty(), - first_time: false, - }; - writeln!(self.out, "{}{} {};", INDENT, base_name, member_name)?; let ty_inner = &module.types[member.ty].inner; last_offset = member.offset + ty_inner.span(&module.constants); - // for 3-component vectors, add one component - if let crate::TypeInner::Vector { - size: crate::VectorSize::Tri, - kind: _, - width, - } = *ty_inner - { - last_offset += width as u32; + let is_tight = match members.get(index + 1) { + Some(next) => next.offset == last_offset, + None => false, + }; + let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; + + match *ty_inner { + // for a misaligned vec3, issue a packed vector + crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + kind, + width: 4, + } if member.offset & 0xF != 0 || is_tight => { + writeln!( + self.out, + "{}packed_{}3 {};", + INDENT, + scalar_kind_string(kind), + member_name + )?; + } + _ => { + let base_name = TypeContext { + handle: member.ty, + arena: &module.types, + names: &self.names, + usage: global_use, + access: crate::StorageAccess::empty(), + first_time: false, + }; + writeln!(self.out, "{}{} {};", INDENT, base_name, member_name)?; + + // for 3-component vectors, add one component + if let crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + kind: _, + width, + } = *ty_inner + { + last_offset += width as u32; + } + } } } writeln!(self.out, "}};")?; From 0cc22c8c657e3cd7bac683e566ea21bbba7cc358 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 8 Apr 2021 20:20:17 -0400 Subject: [PATCH 0679/2212] [spv-in] move the matrix decoration handling to structure parsing --- src/front/spv/mod.rs | 54 +++++++++++++++++++++----------------------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 6a4164665..c3df4a8af 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2301,36 +2301,14 @@ impl> Parser { let vector_type_lookup = self.lookup_type.lookup(vector_type_id)?; let inner = match module.types[vector_type_lookup.handle].inner { - crate::TypeInner::Vector { size, width, .. } => { - if let Some(Decoration { - matrix_stride: Some(stride), - .. - }) = decor - { - if stride.get() != (size as u32) * (width as u32) { - return Err(Error::UnsupportedMatrixStride(stride.get())); - } - } - crate::TypeInner::Matrix { - columns: map_vector_size(num_columns)?, - rows: size, - width, - } - } + crate::TypeInner::Vector { size, width, .. } => crate::TypeInner::Matrix { + columns: map_vector_size(num_columns)?, + rows: size, + width, + }, _ => return Err(Error::InvalidInnerType(vector_type_id)), }; - if let Some(Decoration { - matrix_major: Some(ref major), - .. - }) = decor - { - match *major { - Majority::Column => (), - Majority::Row => return Err(Error::UnsupportedRowMajorMatrix), - } - } - self.lookup_type.insert( id, LookupType { @@ -2496,17 +2474,37 @@ impl> Parser { .future_member_decor .remove(&(id, i)) .unwrap_or_default(); - let binding = decor.io_binding().ok(); + let binding = decor.io_binding().ok(); let offset = match decor.offset { Some(offset) => offset, None => match members.last() { Some(member) => { + //TODO: is this needed? + // If offsets are required, we can just put 0 here member.offset + module.types[member.ty].inner.span(&module.constants) } None => 0, }, }; + + if let crate::TypeInner::Matrix { + columns: _, + rows, + width, + } = module.types[ty].inner + { + if let Some(stride) = decor.matrix_stride { + if stride.get() != (rows as u32) * (width as u32) { + return Err(Error::UnsupportedMatrixStride(stride.get())); + } + } + match decor.matrix_major { + None | Some(Majority::Column) => (), + Some(Majority::Row) => return Err(Error::UnsupportedRowMajorMatrix), + } + } + members.push(crate::StructMember { name: decor.name, ty, From 67e3e0a697dde1968aa427dc183a647023fa2c0f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 8 Apr 2021 23:02:51 -0400 Subject: [PATCH 0680/2212] [spv-in] work around row-major matrices --- src/front/spv/error.rs | 1 - src/front/spv/function.rs | 3 + src/front/spv/mod.rs | 242 ++++++++++++++++++++++++++++---------- 3 files changed, 182 insertions(+), 64 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 0893f9cd3..ea5bbb377 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -54,6 +54,5 @@ pub enum Error { InvalidEdgeClassification, FunctionCallCycle(spirv::Word), // incomplete implementation error - UnsupportedRowMajorMatrix, UnsupportedMatrixStride(spirv::Word), } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 2a6f83bad..5a5725632 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -63,6 +63,9 @@ impl> super::Parser { } pub(super) fn parse_function(&mut self, module: &mut crate::Module) -> Result<(), Error> { + self.lookup_expression.clear(); + self.lookup_load_override.clear(); + let result_type_id = self.next()?; let fun_id = self.next()?; let _fun_control = self.next()?; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index c3df4a8af..6589d1bb7 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -16,6 +16,13 @@ populated at the start of an entry point. The outputs are saved at the end. The function associated with an entry point is wrapped in another function, such that we can handle any `Return` statements without problems. +## Row-major matrices + +We don't handle them natively, since the IR only expects column majority. +Instead, we detect when such matrix is accessed in the `OpAccessChain`, +and we generate a parallel expression that loads the value, but transposed. +This value then gets used instead of `OpLoad` result later on. + !*/ #![allow(dead_code)] @@ -192,7 +199,7 @@ bitflags::bitflags! { } } -#[derive(Debug)] +#[derive(Debug, PartialEq)] enum Majority { Column, Row, @@ -300,6 +307,21 @@ struct LookupExpression { type_id: spirv::Word, } +#[derive(Debug)] +struct LookupMember { + type_id: spirv::Word, + // This is true for either matrices, or arrays of matrices (yikes). + row_major: bool, +} + +#[derive(Clone, Debug)] +enum LookupLoadOverride { + /// For arrays of matrices, we track them but not loading yet. + Pending, + /// For matrices, vectors, and scalars, we pre-load the data. + Loaded(Handle), +} + #[derive(Clone, Debug)] struct Assignment { to: Handle, @@ -337,7 +359,7 @@ pub struct Parser { ext_glsl_id: Option, future_decor: FastHashMap, future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>, - lookup_member_type_id: FastHashMap<(Handle, MemberIndex), spirv::Word>, + lookup_member: FastHashMap<(Handle, MemberIndex), LookupMember>, handle_sampling: FastHashMap, image::SamplingFlags>, lookup_type: FastHashMap, lookup_void_type: Option, @@ -346,6 +368,8 @@ pub struct Parser { lookup_constant: FastHashMap, lookup_variable: FastHashMap, lookup_expression: FastHashMap, + // Load overrides are used to work around row-major matrices + lookup_load_override: FastHashMap, lookup_sampled_image: FastHashMap, lookup_function_type: FastHashMap, lookup_function: FastHashMap>, @@ -373,13 +397,14 @@ impl> Parser { future_decor: FastHashMap::default(), future_member_decor: FastHashMap::default(), handle_sampling: FastHashMap::default(), - lookup_member_type_id: FastHashMap::default(), + lookup_member: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_void_type: None, lookup_storage_buffer_types: FastHashSet::default(), lookup_constant: FastHashMap::default(), lookup_variable: FastHashMap::default(), lookup_expression: FastHashMap::default(), + lookup_load_override: FastHashMap::default(), lookup_sampled_image: FastHashMap::default(), lookup_function_type: FastHashMap::default(), lookup_function: FastHashMap::default(), @@ -636,11 +661,11 @@ impl> Parser { let root_lookup = self.lookup_type.lookup(root_type_id)?; let (count, child_type_id) = match type_arena[root_lookup.handle].inner { crate::TypeInner::Struct { ref members, .. } => { - let child_type_id = *self - .lookup_member_type_id + let child_member = self + .lookup_member .get(&(root_lookup.handle, selection)) .ok_or(Error::InvalidAccessType(root_type_id))?; - (members.len(), child_type_id) + (members.len(), child_member.type_id) } // crate::TypeInner::Array //TODO? crate::TypeInner::Vector { size, .. } @@ -797,6 +822,7 @@ impl> Parser { struct AccessExpression { base_handle: Handle, type_id: spirv::Word, + load_override: Option, } inst.expect_at_least(4)?; @@ -813,50 +839,96 @@ impl> Parser { AccessExpression { base_handle: lexp.handle, type_id: lty.base_id.ok_or(Error::InvalidAccessType(lexp.type_id))?, + load_override: self.lookup_load_override.get(&base_id).cloned(), } }; for _ in 4..inst.wc { let access_id = self.next()?; log::trace!("\t\t\tlooking up index expr {:?}", access_id); let index_expr = self.lookup_expression.lookup(access_id)?.clone(); - let index_type_handle = self.lookup_type.lookup(index_expr.type_id)?.handle; - match type_arena[index_type_handle].inner { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - .. + let index_expr_data = &expressions[index_expr.handle]; + let index_maybe = match *index_expr_data { + crate::Expression::Constant(const_handle) => { + match const_arena[const_handle].inner { + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(v), + } => Some(v as u32), + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Sint(v), + } => Some(v as u32), + _ => { + return Err(Error::InvalidAccess( + crate::Expression::Constant(const_handle), + )) + } + } } - | crate::TypeInner::Scalar { - kind: crate::ScalarKind::Sint, - .. - } => (), - ref other => { - log::warn!("access index type {:?}", other); - return Err(Error::UnsupportedType(index_type_handle)); - } - } + _ => None, + }; + log::trace!("\t\t\tlooking up type {:?}", acex.type_id); let type_lookup = self.lookup_type.lookup(acex.type_id)?; acex = match type_arena[type_lookup.handle].inner { + // can only index a struct with a constant crate::TypeInner::Struct { .. } => { - let index = match expressions[index_expr.handle] { - crate::Expression::Constant(const_handle) => { - match const_arena[const_handle].inner { - crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(v), - } => v as u32, - crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Sint(v), - } => v as u32, - _ => { - return Err(Error::InvalidAccess( - crate::Expression::Constant(const_handle), - )) + let index = index_maybe + .ok_or_else(|| Error::InvalidAccess(index_expr_data.clone()))?; + let lookup_member = self + .lookup_member + .get(&(type_lookup.handle, index)) + .ok_or(Error::InvalidAccessType(acex.type_id))?; + let base_handle = + expressions.append(crate::Expression::AccessIndex { + base: acex.base_handle, + index, + }); + AccessExpression { + base_handle, + type_id: lookup_member.type_id, + load_override: if lookup_member.row_major { + debug_assert!(acex.load_override.is_none()); + let sub_type_lookup = + self.lookup_type.lookup(lookup_member.type_id)?; + Some(match type_arena[sub_type_lookup.handle].inner { + // load it transposed, to match column major expectations + crate::TypeInner::Matrix { .. } => { + let loaded = + expressions.append(crate::Expression::Load { + pointer: base_handle, + }); + let transposed = + expressions.append(crate::Expression::Math { + fun: crate::MathFunction::Transpose, + arg: loaded, + arg1: None, + arg2: None, + }); + LookupLoadOverride::Loaded(transposed) } - } + _ => LookupLoadOverride::Pending, + }) + } else { + None + }, + } + } + // we can't dynamically index matrices, so expecting constant index here + crate::TypeInner::Matrix { .. } => { + let index = index_maybe + .ok_or_else(|| Error::InvalidAccess(index_expr_data.clone()))?; + let load_override = match acex.load_override { + // We are indexing inside a row-major matrix + Some(LookupLoadOverride::Loaded(load_expr)) => { + let sub_expr = + expressions.append(crate::Expression::AccessIndex { + base: load_expr, + index, + }); + Some(LookupLoadOverride::Loaded(sub_expr)) } - ref other => return Err(Error::InvalidAccess(other.clone())), + _ => None, }; AccessExpression { base_handle: expressions.append( @@ -865,24 +937,62 @@ impl> Parser { index, }, ), - type_id: *self - .lookup_member_type_id - .get(&(type_lookup.handle, index)) + type_id: type_lookup + .base_id .ok_or(Error::InvalidAccessType(acex.type_id))?, + load_override, } } - _ => AccessExpression { - base_handle: expressions.append(crate::Expression::Access { + // This must be a vector or an array. + _ => { + let base_handle = expressions.append(crate::Expression::Access { base: acex.base_handle, index: index_expr.handle, - }), - type_id: type_lookup - .base_id - .ok_or(Error::InvalidAccessType(acex.type_id))?, - }, + }); + let load_override = match acex.load_override { + // If there is a load override in place, then we always end up + // with a side-loaded value here. + Some(lookup_load_override) => { + let sub_expr = match lookup_load_override { + // We must be indexing into the array of row-major matrices. + // Let's load the result of indexing and transpose it. + LookupLoadOverride::Pending => { + let loaded = + expressions.append(crate::Expression::Load { + pointer: base_handle, + }); + expressions.append(crate::Expression::Math { + fun: crate::MathFunction::Transpose, + arg: loaded, + arg1: None, + arg2: None, + }) + } + // We are indexing inside a row-major matrix. + LookupLoadOverride::Loaded(load_expr) => expressions + .append(crate::Expression::Access { + base: load_expr, + index: index_expr.handle, + }), + }; + Some(LookupLoadOverride::Loaded(sub_expr)) + } + None => None, + }; + AccessExpression { + base_handle, + type_id: type_lookup + .base_id + .ok_or(Error::InvalidAccessType(acex.type_id))?, + load_override, + } + } }; } + if let Some(load_expr) = acex.load_override { + self.lookup_load_override.insert(result_id, load_expr); + } let lookup_expression = LookupExpression { handle: acex.base_handle, type_id: result_type_id, @@ -997,10 +1107,12 @@ impl> Parser { log::trace!("\t\t\tlooking up type {:?}", lexp.type_id); let type_lookup = self.lookup_type.lookup(lexp.type_id)?; let type_id = match type_arena[type_lookup.handle].inner { - crate::TypeInner::Struct { .. } => *self - .lookup_member_type_id - .get(&(type_lookup.handle, index)) - .ok_or(Error::InvalidAccessType(lexp.type_id))?, + crate::TypeInner::Struct { .. } => { + self.lookup_member + .get(&(type_lookup.handle, index)) + .ok_or(Error::InvalidAccessType(lexp.type_id))? + .type_id + } crate::TypeInner::Array { .. } | crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => type_lookup @@ -1100,9 +1212,13 @@ impl> Parser { crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { base_lexp.handle } - _ => expressions.append(crate::Expression::Load { - pointer: base_lexp.handle, - }), + _ => match self.lookup_load_override.get(&pointer_id) { + Some(&LookupLoadOverride::Loaded(handle)) => handle, + //Note: we aren't handling `LookupLoadOverride::Pending` properly here + _ => expressions.append(crate::Expression::Load { + pointer: base_lexp.handle, + }), + }, }; self.lookup_expression.insert( @@ -2465,16 +2581,20 @@ impl> Parser { let block_decor = parent_decor.as_ref().and_then(|decor| decor.block.clone()); let mut members = Vec::::with_capacity(inst.wc as usize - 2); - let mut member_type_ids = Vec::with_capacity(members.capacity()); + let mut member_lookups = Vec::with_capacity(members.capacity()); for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; - member_type_ids.push(type_id); let ty = self.lookup_type.lookup(type_id)?.handle; let decor = self .future_member_decor .remove(&(id, i)) .unwrap_or_default(); + member_lookups.push(LookupMember { + type_id, + row_major: decor.matrix_major == Some(Majority::Row), + }); + let binding = decor.io_binding().ok(); let offset = match decor.offset { Some(offset) => offset, @@ -2499,10 +2619,6 @@ impl> Parser { return Err(Error::UnsupportedMatrixStride(stride.get())); } } - match decor.matrix_major { - None | Some(Majority::Column) => (), - Some(Majority::Row) => return Err(Error::UnsupportedRowMajorMatrix), - } } members.push(crate::StructMember { @@ -2540,9 +2656,9 @@ impl> Parser { if block_decor == Some(Block { buffer: true }) { self.lookup_storage_buffer_types.insert(ty_handle); } - for (i, type_id) in member_type_ids.into_iter().enumerate() { - self.lookup_member_type_id - .insert((ty_handle, i as u32), type_id); + for (i, member_lookup) in member_lookups.into_iter().enumerate() { + self.lookup_member + .insert((ty_handle, i as u32), member_lookup); } self.lookup_type.insert( id, From 44a6c02cdac28a56dea287c3fdee9a2662543544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Tal=C4=8D=C3=ADk?= Date: Fri, 9 Apr 2021 23:11:32 +0200 Subject: [PATCH 0681/2212] spv-in: special-case a loop with true/false node == merge node beautify beautify #2 --- src/front/spv/flow.rs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 3a96b5405..5dd0c3b7c 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -338,13 +338,24 @@ impl FlowGraph { condition, true_id, false_id, - } => body.push(crate::Statement::If { - condition, - accept: self - .naga_traverse(self.block_to_node[&true_id], Some(merge_node_index))?, - reject: self - .naga_traverse(self.block_to_node[&false_id], Some(merge_node_index))?, - }), + } => { + let true_node_index = self.block_to_node[&true_id]; + let false_node_index = self.block_to_node[&false_id]; + + body.push(crate::Statement::If { + condition, + accept: if true_node_index == merge_node_index { + vec![crate::Statement::Break] + } else { + self.naga_traverse(true_node_index, Some(merge_node_index))? + }, + reject: if false_node_index == merge_node_index { + vec![crate::Statement::Break] + } else { + self.naga_traverse(false_node_index, Some(merge_node_index))? + }, + }); + } Terminator::Branch { target_id } => body.extend( self.naga_traverse(self.block_to_node[&target_id], Some(merge_node_index))?, ), From 1fc88319e811629698310ca6cf12011b47edd56c Mon Sep 17 00:00:00 2001 From: Ashley Ruglys Date: Fri, 9 Apr 2021 19:53:09 +0200 Subject: [PATCH 0682/2212] Serialize mtl EntryPointError --- src/back/msl/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index ad78a5bd0..bff1556e0 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -57,6 +57,7 @@ pub struct BindTarget { } #[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct BindSource { pub stage: crate::ShaderStage, @@ -95,6 +96,8 @@ pub enum Error { } #[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum EntryPointError { #[error("mapping of {0:?} is missing")] MissingBinding(BindSource), From 98252cf5d29790f85cc4397e0cf7a5b6cfaac614 Mon Sep 17 00:00:00 2001 From: Simas Toleikis Date: Sat, 10 Apr 2021 21:38:35 +0300 Subject: [PATCH 0683/2212] Fix validation for textureDimensions(t) call. --- src/valid/expression.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 23e6c9546..9df4daae1 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -592,10 +592,10 @@ impl super::Validator { }; let good = match query { crate::ImageQuery::NumLayers => arrayed, + crate::ImageQuery::Size { level: None } => true, crate::ImageQuery::Size { level: Some(_) } | crate::ImageQuery::NumLevels => can_level, - crate::ImageQuery::Size { level: None } - | crate::ImageQuery::NumSamples => !can_level, + crate::ImageQuery::NumSamples => !can_level, }; if !good { return Err(ExpressionError::InvalidImageClass(class)); From 142038c85bdcb8acd391e8cb2bf9f0dca5679631 Mon Sep 17 00:00:00 2001 From: Mehmet Oguz Derin Date: Sun, 11 Apr 2021 07:35:03 +0300 Subject: [PATCH 0684/2212] WGSL: `const` to `let` --- src/front/wgsl/mod.rs | 10 +++++----- src/front/wgsl/tests.rs | 40 ++++++++++++++++++++-------------------- tests/errors.rs | 16 ++++++++-------- tests/in/boids.wgsl | 4 ++-- tests/in/image-copy.wgsl | 6 +++--- tests/in/quad.wgsl | 6 +++--- tests/in/shadow.wgsl | 20 ++++++++++---------- tests/in/skybox.wgsl | 6 +++--- 8 files changed, 54 insertions(+), 54 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e618d6812..5f791a37a 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -123,7 +123,7 @@ pub enum Error<'a> { #[error("builtin {0:?} is not implemented")] UnimplementedBuiltin(crate::BuiltIn), #[error("expression {0} doesn't match its given type {1:?}")] - ConstTypeMismatch(&'a str, Handle), + LetTypeMismatch(&'a str, Handle), #[error("other error")] Other, } @@ -1999,7 +1999,7 @@ impl Parser { self.scopes.push(Scope::Statement); let mut emitter = super::Emitter::default(); match word { - "const" => { + "let" => { emitter.start(context.expressions); let name = lexer.next_ident()?; let given_ty = if lexer.skip(Token::Separator(':')) { @@ -2026,7 +2026,7 @@ impl Parser { given_inner, expr_inner ); - return Err(Error::ConstTypeMismatch(name, ty)); + return Err(Error::LetTypeMismatch(name, ty)); } } block.extend(emitter.finish(context.expressions)); @@ -2584,7 +2584,7 @@ impl Parser { self.lookup_type.insert(name.to_owned(), ty); lexer.expect(Token::Separator(';'))?; } - (Token::Word("const"), _) => { + (Token::Word("let"), _) => { let (name, explicit_ty, _access) = self.parse_variable_ident_decl( lexer, &mut module.types, @@ -2611,7 +2611,7 @@ impl Parser { crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty, }; if !type_match { - return Err(Error::ConstTypeMismatch(name, explicit_ty)); + return Err(Error::LetTypeMismatch(name, explicit_ty)); } //TODO: check `ty` against `const_handle`. lexer.expect(Token::Separator(';'))?; diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 64da1fbd4..96b96a718 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -16,8 +16,8 @@ fn parse_comment() { #[test] fn parse_types() { - parse_str("const a : i32 = 2;").unwrap(); - assert!(parse_str("const a : x32 = 2;").is_err()); + parse_str("let a : i32 = 2;").unwrap(); + assert!(parse_str("let a : x32 = 2;").is_err()); parse_str("var t: texture_2d;").unwrap(); parse_str("var t: texture_cube_array;").unwrap(); parse_str("var t: texture_multisampled_2d;").unwrap(); @@ -30,14 +30,14 @@ fn parse_type_inference() { parse_str( " fn foo() { - const a = 2u; - const b: u32 = a; + let a = 2u; + let b: u32 = a; }", ) .unwrap(); assert!(parse_str( " - fn foo() { const c : i32 = 2.0; }", + fn foo() { let c : i32 = 2.0; }", ) .is_err()); } @@ -46,7 +46,7 @@ fn parse_type_inference() { fn parse_type_cast() { parse_str( " - const a : i32 = 2; + let a : i32 = 2; fn main() { var x: f32 = f32(a); x = f32(i32(a + 1) / 2); @@ -57,8 +57,8 @@ fn parse_type_cast() { parse_str( " fn main() { - const x: vec2 = vec2(1.0, 2.0); - const y: vec2 = vec2(x); + let x: vec2 = vec2(1.0, 2.0); + let y: vec2 = vec2(x); } ", ) @@ -201,7 +201,7 @@ fn parse_texture_load() { " var t: texture_3d; fn foo() { - const r: vec4 = textureLoad(t, vec3(0.0, 1.0, 2.0), 1); + let r: vec4 = textureLoad(t, vec3(0.0, 1.0, 2.0), 1); } ", ) @@ -210,7 +210,7 @@ fn parse_texture_load() { " var t: texture_multisampled_2d_array; fn foo() { - const r: vec4 = textureLoad(t, vec2(10, 20), 2, 3); + let r: vec4 = textureLoad(t, vec2(10, 20), 2, 3); } ", ) @@ -219,7 +219,7 @@ fn parse_texture_load() { " var t: [[access(read)]] texture_storage_1d_array; fn foo() { - const r: vec4 = textureLoad(t, 10, 2); + let r: vec4 = textureLoad(t, 10, 2); } ", ) @@ -247,8 +247,8 @@ fn parse_texture_query() { fn foo() { var dim: vec2 = textureDimensions(t); dim = textureDimensions(t, 0); - const layers: i32 = textureNumLayers(t); - const samples: i32 = textureNumSamples(t); + let layers: i32 = textureNumLayers(t); + let samples: i32 = textureNumSamples(t); } ", ) @@ -259,8 +259,8 @@ fn parse_texture_query() { fn parse_postfix() { parse_str( "fn foo() { - const x: f32 = vec4(1.0, 2.0, 3.0, 4.0).xyz.rgbr.aaaa.wz.g; - const y: f32 = fract(vec2(0.5, x)).x; + let x: f32 = vec4(1.0, 2.0, 3.0, 4.0).xyz.rgbr.aaaa.wz.g; + let y: f32 = fract(vec2(0.5, x)).x; }", ) .unwrap(); @@ -269,9 +269,9 @@ fn parse_postfix() { #[test] fn parse_expressions() { parse_str("fn foo() { - const x: f32 = select(0.0, 1.0, true); - const y: vec2 = select(vec2(1.0, 1.0), vec2(x, x), vec2(x < 0.5, x > 0.5)); - const z: bool = !(0.0 == 1.0); + let x: f32 = select(0.0, 1.0, true); + let y: vec2 = select(vec2(1.0, 1.0), vec2(x, x), vec2(x < 0.5, x > 0.5)); + let z: bool = !(0.0 == 1.0); }").unwrap(); } @@ -280,8 +280,8 @@ fn parse_pointers() { parse_str( "fn foo() { var x: f32 = 1.0; - const px = &x; - const py = frexp(0.5, px); + let px = &x; + let py = frexp(0.5, px); }", ) .unwrap(); diff --git a/tests/errors.rs b/tests/errors.rs index 2f159c744..437288ab5 100644 --- a/tests/errors.rs +++ b/tests/errors.rs @@ -46,13 +46,13 @@ fn invalid_integer() { #[test] fn invalid_float() { err!( - "const scale: f32 = 1.1.;", + "let scale: f32 = 1.1.;", @r###" error: expected floating-point literal, found `1.1.` - ┌─ wgsl:1:20 + ┌─ wgsl:1:18 │ - 1 │ const scale: f32 = 1.1.; - │ ^^^^ expected floating-point literal + 1 │ let scale: f32 = 1.1.; + │ ^^^^ expected floating-point literal "### ); @@ -62,13 +62,13 @@ fn invalid_float() { #[test] fn invalid_scalar_width() { err!( - "const scale: f32 = 1.1f1000;", + "let scale: f32 = 1.1f1000;", @r###" error: invalid width of `1000` for literal - ┌─ wgsl:1:20 + ┌─ wgsl:1:18 │ - 1 │ const scale: f32 = 1.1f1000; - │ ^^^^^^^^ invalid width + 1 │ let scale: f32 = 1.1f1000; + │ ^^^^^^^^ invalid width │ = note: valid width is 32 diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 935d8ee08..3db45e1cb 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -1,4 +1,4 @@ -const NUM_PARTICLES: u32 = 1500u; +let NUM_PARTICLES: u32 = 1500u; struct Particle { pos : vec2; @@ -28,7 +28,7 @@ struct Particles { // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp [[stage(compute), workgroup_size(64)]] fn main([[builtin(global_invocation_id)]] global_invocation_id : vec3) { - const index : u32 = global_invocation_id.x; + let index : u32 = global_invocation_id.x; if (index >= NUM_PARTICLES) { return; } diff --git a/tests/in/image-copy.wgsl b/tests/in/image-copy.wgsl index cb09083b9..157d08146 100644 --- a/tests/in/image-copy.wgsl +++ b/tests/in/image-copy.wgsl @@ -9,8 +9,8 @@ fn main( //TODO: https://github.com/gpuweb/gpuweb/issues/1590 //[[builtin(workgroup_size)]] wg_size: vec3 ) { - const dim = textureDimensions(image_src); - const itc = dim * vec2(local_id.xy) % vec2(10, 20); - const value = textureLoad(image_src, itc); + let dim = textureDimensions(image_src); + let itc = dim * vec2(local_id.xy) % vec2(10, 20); + let value = textureLoad(image_src, itc); textureStore(image_dst, itc.x, value); } diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 6283687ef..fdaa9600c 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -1,5 +1,5 @@ // vertex -const c_scale: f32 = 1.2; +let c_scale: f32 = 1.2; struct VertexOutput { [[location(0)]] uv : vec2; @@ -20,12 +20,12 @@ fn main([[location(0)]] pos : vec2, [[location(1)]] uv : vec2) -> Vert [[stage(fragment)]] fn main([[location(0)]] uv : vec2) -> [[location(0)]] vec4 { - const color = textureSample(u_texture, u_sampler, uv); + let color = textureSample(u_texture, u_sampler, uv); if (color.a == 0.0) { discard; } // forcing the expression here to be emitted in order to check the // uniformity of the control flow a bit more strongly. - const premultiplied = color.a * color; + let premultiplied = color.a * color; return premultiplied; } diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index f40802cb4..16d2e79d0 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -28,21 +28,21 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { if (homogeneous_coords.w <= 0.0) { return 1.0; } - const flip_correction = vec2(0.5, -0.5); - const proj_correction = 1.0 / homogeneous_coords.w; - const light_local = homogeneous_coords.xy * flip_correction * proj_correction + vec2(0.5, 0.5); + let flip_correction = vec2(0.5, -0.5); + let proj_correction = 1.0 / homogeneous_coords.w; + let light_local = homogeneous_coords.xy * flip_correction * proj_correction + vec2(0.5, 0.5); return textureSampleCompare(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z * proj_correction); } -const c_ambient: vec3 = vec3(0.05, 0.05, 0.05); -const c_max_lights: u32 = 10u; +let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); +let c_max_lights: u32 = 10u; [[stage(fragment)]] fn fs_main( [[location(0)]] raw_normal: vec3, [[location(1)]] position: vec4 ) -> [[location(0)]] vec4 { - const normal: vec3 = normalize(raw_normal); + let normal: vec3 = normalize(raw_normal); // accumulate color var color: vec3 = c_ambient; var i: u32 = 0u; @@ -50,10 +50,10 @@ fn fs_main( if (i >= min(u_globals.num_lights.x, c_max_lights)) { break; } - const light = s_lights.data[i]; - const shadow = fetch_shadow(i, light.proj * position); - const light_dir = normalize(light.pos.xyz - position.xyz); - const diffuse = max(0.0, dot(normal, light_dir)); + let light = s_lights.data[i]; + let shadow = fetch_shadow(i, light.proj * position); + let light_dir = normalize(light.pos.xyz - position.xyz); + let diffuse = max(0.0, dot(normal, light_dir)); color = color + shadow * diffuse * light.color.xyz; continuing { i = i + 1u; diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index 32ad80ca1..812373792 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -16,15 +16,15 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { // hacky way to draw a large triangle var tmp1: i32 = i32(vertex_index) / 2; var tmp2: i32 = i32(vertex_index) & 1; - const pos = vec4( + let pos = vec4( f32(tmp1) * 4.0 - 1.0, f32(tmp2) * 4.0 - 1.0, 0.0, 1.0 ); - const inv_model_view = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); - const unprojected = r_data.proj_inv * pos; + let inv_model_view = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); + let unprojected = r_data.proj_inv * pos; var out: VertexOutput; out.uv = inv_model_view * unprojected.xyz; out.position = pos; From a8f1022b125712a09f713f8dad0bd089b054013f Mon Sep 17 00:00:00 2001 From: Ashley Date: Sun, 11 Apr 2021 17:06:23 +0200 Subject: [PATCH 0685/2212] [Metal] Handle `NaN` and `inf` correctly in constants (#704) * Handle NaN and inf * Handle negative infinity --- src/back/msl/writer.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 788e56ff5..2e7800298 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -253,8 +253,16 @@ impl<'a> Display for ConstantContext<'a> { write!(out, "{}u", value) } crate::ScalarValue::Float(value) => { - let suffix = if value.fract() == 0.0 { ".0" } else { "" }; - write!(out, "{}{}", value, suffix) + if value.is_infinite() { + let sign = if value.is_sign_negative() { "-" } else { "" }; + write!(out, "{}INFINITY", sign) + } else if value.is_nan() { + write!(out, "NAN") + } else { + let suffix = if value.fract() == 0.0 { ".0" } else { "" }; + + write!(out, "{}{}", value, suffix) + } } crate::ScalarValue::Bool(value) => { write!(out, "{}", value) From 5d487941b22a496edf79957cac1c23077e4a5134 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sun, 11 Apr 2021 17:36:26 +0200 Subject: [PATCH 0686/2212] Start hlsl-out (#408) * Add hlsl-out feature * Integrate hlsl-out with snapshots * Add snapshot --- Cargo.toml | 1 + bin/convert.rs | 7 ++++ src/back/hlsl/keywords.rs | 1 + src/back/hlsl/mod.rs | 23 +++++++++++++ src/back/hlsl/writer.rs | 69 +++++++++++++++++++++++++++++++++++++++ src/back/mod.rs | 2 ++ tests/out/empty.hlsl.snap | 11 +++++++ tests/snapshots.rs | 22 ++++++++++++- 8 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 src/back/hlsl/keywords.rs create mode 100644 src/back/hlsl/mod.rs create mode 100644 src/back/hlsl/writer.rs create mode 100644 tests/out/empty.hlsl.snap diff --git a/Cargo.toml b/Cargo.toml index 7f3ef3efd..c96aa733f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ deserialize = ["serde"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] wgsl-in = ["codespan-reporting"] +hlsl-out = [] [[bin]] name = "convert" diff --git a/bin/convert.rs b/bin/convert.rs index 343155326..492fa783c 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -261,6 +261,13 @@ fn main() { let output = dot::write(&module, info.as_ref()).unwrap(); fs::write(output_path, output).unwrap(); } + #[cfg(feature = "hlsl-out")] + "hlsl" => { + use naga::back::hlsl; + + let hlsl = hlsl::write_string(&module).unwrap_pretty(); + fs::write(output_path, hlsl).unwrap(); + } other => { let _ = params; panic!( diff --git a/src/back/hlsl/keywords.rs b/src/back/hlsl/keywords.rs new file mode 100644 index 000000000..e4ce79f36 --- /dev/null +++ b/src/back/hlsl/keywords.rs @@ -0,0 +1 @@ +pub const RESERVED: &[&str] = &[]; diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs new file mode 100644 index 000000000..e785b57a1 --- /dev/null +++ b/src/back/hlsl/mod.rs @@ -0,0 +1,23 @@ +mod keywords; +mod writer; + +use std::io::Error as IoError; +use std::string::FromUtf8Error; +use thiserror::Error; + +pub use writer::Writer; + +#[derive(Error, Debug)] +pub enum Error { + #[error(transparent)] + IoError(#[from] IoError), + #[error(transparent)] + Utf8(#[from] FromUtf8Error), +} + +pub fn write_string(module: &crate::Module) -> Result { + let mut w = Writer::new(Vec::new()); + w.write(module)?; + let output = String::from_utf8(w.finish())?; + Ok(output) +} diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs new file mode 100644 index 000000000..121d4506c --- /dev/null +++ b/src/back/hlsl/writer.rs @@ -0,0 +1,69 @@ +use super::Error; +use crate::back::hlsl::keywords::RESERVED; +use crate::proc::{NameKey, Namer}; +use crate::FastHashMap; +use std::io::Write; + +const INDENT: &str = " "; + +pub struct Writer { + out: W, + names: FastHashMap, + namer: Namer, +} + +impl Writer { + pub fn new(out: W) -> Self { + Writer { + out, + names: FastHashMap::default(), + namer: Namer::default(), + } + } + + pub fn write(&mut self, module: &crate::Module) -> Result<(), Error> { + self.names.clear(); + self.namer.reset(module, RESERVED, &mut self.names); + + for (ep_index, ep) in module.entry_points.iter().enumerate() { + let fun = &ep.function; + let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; + writeln!(self.out)?; + + let return_type_name = match fun.result { + None => "void", + _ => "", + }; + + writeln!( + self.out, + "{} {}({}", + return_type_name, + fun_name, + if fun.arguments.is_empty() { ")" } else { "" } + )?; + + // TODO Support arguments + self.write_block(&ep.function.body)?; + } + Ok(()) + } + + fn write_block(&mut self, statements: &[crate::Statement]) -> Result<(), Error> { + writeln!(self.out, "{{")?; + + for statement in statements { + if let crate::Statement::Return { value: None } = *statement { + writeln!(self.out, "{}return;", INDENT)?; + } + } + + writeln!(self.out, "}}")?; + + Ok(()) + } + + pub fn finish(self) -> W { + self.out + } +} diff --git a/src/back/mod.rs b/src/back/mod.rs index c7d513a66..efffb40a4 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -4,6 +4,8 @@ pub mod dot; #[cfg(feature = "glsl-out")] pub mod glsl; +#[cfg(feature = "hlsl-out")] +pub mod hlsl; #[cfg(feature = "msl-out")] pub mod msl; #[cfg(feature = "spv-out")] diff --git a/tests/out/empty.hlsl.snap b/tests/out/empty.hlsl.snap new file mode 100644 index 000000000..2cfc16ce6 --- /dev/null +++ b/tests/out/empty.hlsl.snap @@ -0,0 +1,11 @@ +--- +source: tests/snapshots.rs +expression: hlsl + +--- + +void main() +{ + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 6cb1d3846..d2ec5d824 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -6,6 +6,7 @@ bitflags::bitflags! { const METAL = 0x8; const GLSL = 0x10; const DOT = 0x20; + const HLSL = 0x40; } } @@ -91,6 +92,12 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { }); } } + #[cfg(feature = "hlsl-out")] + { + if targets.contains(Targets::HLSL) { + check_output_hlsl(module, name); + } + } } #[cfg(feature = "spv-out")] @@ -185,6 +192,16 @@ fn check_output_glsl( }); } +#[cfg(feature = "hlsl-out")] +fn check_output_hlsl(module: &naga::Module, name: &str) { + use naga::back::hlsl; + + let hlsl = hlsl::write_string(module).unwrap(); + with_snapshot_settings(|| { + insta::assert_snapshot!(format!("{}.hlsl", name), hlsl); + }); +} + #[cfg(feature = "wgsl-in")] fn convert_wgsl(name: &str, targets: Targets) { let module = naga::front::wgsl::parse_str( @@ -207,7 +224,10 @@ fn convert_wgsl_quad() { #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_empty() { - convert_wgsl("empty", Targets::SPIRV | Targets::METAL | Targets::GLSL); + convert_wgsl( + "empty", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL, + ); } #[cfg(feature = "wgsl-in")] From 9549b26a903da882bd79a01dfe983cd0edb70097 Mon Sep 17 00:00:00 2001 From: Ashley Date: Sun, 11 Apr 2021 18:32:01 +0200 Subject: [PATCH 0687/2212] Add the reserved types in metal_types to metal keywords (#705) --- src/back/msl/keywords.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs index cd074ab43..7df404da8 100644 --- a/src/back/msl/keywords.rs +++ b/src/back/msl/keywords.rs @@ -99,4 +99,10 @@ pub const RESERVED: &[&str] = &[ "read_only", "write_only", "read_write", + // Metal reserved types + "llong", + "ullong", + "quad", + "complex", + "imaginary", ]; From 30180c008bd7d001915d25d35c9eca085384177a Mon Sep 17 00:00:00 2001 From: Ashley Date: Sun, 11 Apr 2021 18:48:22 +0200 Subject: [PATCH 0688/2212] [Metal] Change the function argument pointer type to use `&` instead of `*` (#693) * Take references in function calls if thats what the funciton wants * Use references instead of pointers the function argument list --- src/back/msl/writer.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 2e7800298..158122825 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -91,7 +91,7 @@ impl<'a> Display for TypeContext<'a> { Some(name) => name, None => return Ok(()), }; - write!(out, "{} {}*", class_name, sub) + write!(out, "{} {}&", class_name, sub) } crate::TypeInner::ValuePointer { size: None, @@ -103,7 +103,7 @@ impl<'a> Display for TypeContext<'a> { Some(name) => name, None => return Ok(()), }; - write!(out, "{} {}*", class_name, scalar_kind_string(kind),) + write!(out, "{} {}&", class_name, scalar_kind_string(kind),) } crate::TypeInner::ValuePointer { size: Some(size), @@ -117,7 +117,7 @@ impl<'a> Display for TypeContext<'a> { }; write!( out, - "{} {}::{}{}*", + "{} {}::{}{}&", class_name, NAMESPACE, scalar_kind_string(kind), From 3b4acc53006d953eb740664a4e273da17757009f Mon Sep 17 00:00:00 2001 From: Ashley Date: Sun, 11 Apr 2021 19:01:31 +0200 Subject: [PATCH 0689/2212] [Metal] Handle `length(float)` and `distance(float, float)` (#706) * Handle length(float x) * Handle length(float) and distance(float, float) * Apply suggestions * Apply suggestions * Move stack size range up by 1000 --- src/back/msl/writer.rs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 158122825..d24bad6c9 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -895,6 +895,11 @@ impl Writer { } => { use crate::MathFunction as Mf; + let scalar_argument = match *context.resolve_type(arg) { + crate::TypeInner::Scalar { .. } => true, + _ => false, + }; + let fun_name = match fun { // comparison Mf::Abs => "abs", @@ -932,6 +937,7 @@ impl Writer { Mf::Outer => return Err(Error::UnsupportedCall(format!("{:?}", fun))), Mf::Cross => "cross", Mf::Distance => "distance", + Mf::Length if scalar_argument => "abs", Mf::Length => "length", Mf::Normalize => "normalize", Mf::FaceForward => "faceforward", @@ -952,8 +958,16 @@ impl Writer { Mf::ReverseBits => "reverse_bits", }; - write!(self.out, "{}::{}", NAMESPACE, fun_name)?; - self.put_call_parameters(iter::once(arg).chain(arg1).chain(arg2), context)?; + if fun == Mf::Distance && scalar_argument { + write!(self.out, "{}::abs(", NAMESPACE)?; + self.put_expression(arg, context, false)?; + write!(self.out, " - ")?; + self.put_expression(arg1.unwrap(), context, false)?; + write!(self.out, ")")?; + } else { + write!(self.out, "{}::{}", NAMESPACE, fun_name)?; + self.put_call_parameters(iter::once(arg).chain(arg1).chain(arg2), context)?; + } } crate::Expression::As { expr, @@ -2128,8 +2142,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 18768 - if stack_size < 18000 || stack_size > 20000 { + // last observed macOS value: 20336 + if stack_size < 19000 || stack_size > 21000 { panic!("`put_expression` stack size {} has changed!", stack_size); } } From 98db1dedcd6082219e188c1d341869d24f07b7da Mon Sep 17 00:00:00 2001 From: Ashley Date: Sun, 11 Apr 2021 20:21:02 +0200 Subject: [PATCH 0690/2212] Add a note about references and pointers to `Expression::Load` (#708) * Add a note about references and pointers to Expression::Load * Formatting * Remove comma * Clearer English --- src/back/msl/writer.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index d24bad6c9..1ad74a0fe 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -676,7 +676,9 @@ impl Writer { write!(self.out, "{}", name)?; } crate::Expression::Load { pointer } => { - //write!(self.out, "*")?; + // We don't do any dereferencing with `*` here as pointer arguments to functions + // are done by `&` references and not `*` pointers. These do not need to be + // dereferenced. self.put_expression(pointer, context, is_scoped)?; } crate::Expression::ImageSample { From 640bfb1f269f43eac7d899376137d422bd8cda0e Mon Sep 17 00:00:00 2001 From: Ashley Date: Sun, 11 Apr 2021 20:21:47 +0200 Subject: [PATCH 0691/2212] [Metal] Make constant composites non-`constexpr` (#707) * Make constant composites non-constexpr * Update shadow test --- src/back/msl/writer.rs | 2 +- tests/out/shadow.msl.snap | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 1ad74a0fe..a2648165e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1531,7 +1531,7 @@ impl Writer { access: crate::StorageAccess::empty(), first_time: false, }; - write!(self.out, "constexpr constant {} {} = {{", ty_name, name,)?; + write!(self.out, "constant {} {} = {{", ty_name, name,)?; for (i, &sub_handle) in components.iter().enumerate() { let separator = if i != 0 { ", " } else { "" }; let coco = ConstantContext { diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap index 9d4e2b3af..92cd9e83d 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl.snap @@ -18,7 +18,7 @@ typedef Light type3[1]; struct Lights { type3 data; }; -constexpr constant metal::float3 c_ambient = {0.05, 0.05, 0.05}; +constant metal::float3 c_ambient = {0.05, 0.05, 0.05}; float fetch_shadow( metal::uint light_id, From 202d3a6912b9dd4f8c701451480d151744b033ff Mon Sep 17 00:00:00 2001 From: Ashley Date: Sun, 11 Apr 2021 20:36:29 +0200 Subject: [PATCH 0692/2212] Add metal constants to keywords (#709) --- src/back/msl/keywords.rs | 104 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs index 7df404da8..bb4338560 100644 --- a/src/back/msl/keywords.rs +++ b/src/back/msl/keywords.rs @@ -99,10 +99,114 @@ pub const RESERVED: &[&str] = &[ "read_only", "write_only", "read_write", + "auto", // Metal reserved types "llong", "ullong", "quad", "complex", "imaginary", + // Metal constants + "CHAR_BIT", + "SCHAR_MAX", + "SCHAR_MIN", + "UCHAR_MAX", + "CHAR_MAX", + "CHAR_MIN", + "USHRT_MAX", + "SHRT_MAX", + "SHRT_MIN", + "UINT_MAX", + "INT_MAX", + "INT_MIN", + "ULONG_MAX", + "LONG_MAX", + "LONG_MIN", + "ULLONG_MAX", + "LLONG_MAX", + "LLONG_MIN", + "FLT_DIG", + "FLT_MANT_DIG", + "FLT_MAX_10_EXP", + "FLT_MAX_EXP", + "FLT_MIN_10_EXP", + "FLT_MIN_EXP", + "FLT_RADIX", + "FLT_MAX", + "FLT_MIN", + "FLT_EPSILON", + "FLT_DECIMAL_DIG", + "FP_ILOGB0", + "FP_ILOGB0", + "FP_ILOGBNAN", + "FP_ILOGBNAN", + "MAXFLOAT", + "HUGE_VALF", + "INFINITY", + "NAN", + "M_E_F", + "M_LOG2E_F", + "M_LOG10E_F", + "M_LN2_F", + "M_LN10_F", + "M_PI_F", + "M_PI_2_F", + "M_PI_4_F", + "M_1_PI_F", + "M_2_PI_F", + "M_2_SQRTPI_F", + "M_SQRT2_F", + "M_SQRT1_2_F", + "HALF_DIG", + "HALF_MANT_DIG", + "HALF_MAX_10_EXP", + "HALF_MAX_EXP", + "HALF_MIN_10_EXP", + "HALF_MIN_EXP", + "HALF_RADIX", + "HALF_MAX", + "HALF_MIN", + "HALF_EPSILON", + "HALF_DECIMAL_DIG", + "MAXHALF", + "HUGE_VALH", + "M_E_H", + "M_LOG2E_H", + "M_LOG10E_H", + "M_LN2_H", + "M_LN10_H", + "M_PI_H", + "M_PI_2_H", + "M_PI_4_H", + "M_1_PI_H", + "M_2_PI_H", + "M_2_SQRTPI_H", + "M_SQRT2_H", + "M_SQRT1_2_H", + "DBL_DIG", + "DBL_MANT_DIG", + "DBL_MAX_10_EXP", + "DBL_MAX_EXP", + "DBL_MIN_10_EXP", + "DBL_MIN_EXP", + "DBL_RADIX", + "DBL_MAX", + "DBL_MIN", + "DBL_EPSILON", + "DBL_DECIMAL_DIG", + "MAXDOUBLE", + "HUGE_VAL", + "M_E", + "M_LOG2E", + "M_LOG10E", + "M_LN2", + "M_LN10", + "M_PI", + "M_PI_2", + "M_PI_4", + "M_1_PI", + "M_2_PI", + "M_2_SQRTPI", + "M_SQRT2", + "M_SQRT1_2", ]; From 9cd2b04c04c9211488dbd7850ceb394c40599c3c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 12 Apr 2021 12:12:19 -0400 Subject: [PATCH 0693/2212] [spv-out] put matrix decorations on arrays of matrices (#712) --- src/back/spv/writer.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index aa720a554..1a6e7a611 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -886,11 +886,17 @@ impl Writer { } } + // The matrix decorations also go on arrays of matrices, + // so lets check this first. + let member_array_subty_inner = match arena[member.ty].inner { + crate::TypeInner::Array { base, .. } => &arena[base].inner, + ref other => other, + }; if let crate::TypeInner::Matrix { columns, rows: _, width, - } = arena[member.ty].inner + } = *member_array_subty_inner { let byte_stride = match columns { crate::VectorSize::Bi => 2 * width, From 270feb3c0f233d17fa070568f8ae2e490ea8c13b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 13 Apr 2021 01:22:00 -0400 Subject: [PATCH 0694/2212] [msl] map push constants to buffers --- src/back/msl/mod.rs | 51 ++++++++++++++++++++++++++++++++++++--- src/back/msl/writer.rs | 24 +++++++++++++----- tests/in/boids.param.ron | 2 ++ tests/in/skybox.param.ron | 2 ++ 4 files changed, 69 insertions(+), 10 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index bff1556e0..db1fcedf0 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -36,10 +36,12 @@ mod writer; pub use writer::Writer; +pub type Slot = u8; + #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum BindSamplerTarget { - Resource(u8), + Resource(Slot), Inline(Handle), } @@ -47,9 +49,9 @@ pub enum BindSamplerTarget { #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct BindTarget { #[cfg_attr(feature = "deserialize", serde(default))] - pub buffer: Option, + pub buffer: Option, #[cfg_attr(feature = "deserialize", serde(default))] - pub texture: Option, + pub texture: Option, #[cfg_attr(feature = "deserialize", serde(default))] pub sampler: Option, #[cfg_attr(feature = "deserialize", serde(default))] @@ -67,6 +69,18 @@ pub struct BindSource { pub type BindingMap = FastHashMap; +#[derive(Clone, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct PushConstantsMap { + #[cfg_attr(feature = "deserialize", serde(default))] + pub vs_buffer: Option, + #[cfg_attr(feature = "deserialize", serde(default))] + pub fs_buffer: Option, + #[cfg_attr(feature = "deserialize", serde(default))] + pub cs_buffer: Option, +} + enum ResolvedBinding { BuiltIn(crate::BuiltIn), Attribute(u32), @@ -101,6 +115,8 @@ pub enum Error { pub enum EntryPointError { #[error("mapping of {0:?} is missing")] MissingBinding(BindSource), + #[error("mapping for push constants at stage {0:?} is missing")] + MissingPushConstants(crate::ShaderStage), } #[derive(Clone, Copy, Debug)] @@ -118,6 +134,8 @@ pub struct Options { pub lang_version: (u8, u8), /// Binding model mapping to Metal. pub binding_map: BindingMap, + /// Push constants mapping to Metal. + pub push_constants_map: PushConstantsMap, /// Samplers to be inlined into the code. pub inline_samplers: Arena, /// Make it possible to link different stages via SPIRV-Cross. @@ -131,6 +149,7 @@ impl Default for Options { Options { lang_version: (1, 0), binding_map: BindingMap::default(), + push_constants_map: PushConstantsMap::default(), inline_samplers: Arena::new(), spirv_cross_compatibility: false, fake_missing_bindings: true, @@ -185,7 +204,7 @@ impl Options { } } - fn resolve_global_binding( + fn resolve_resource_binding( &self, stage: crate::ShaderStage, res_binding: &crate::ResourceBinding, @@ -204,6 +223,30 @@ impl Options { None => Err(EntryPointError::MissingBinding(source)), } } + + fn resolve_push_constants( + &self, + stage: crate::ShaderStage, + ) -> Result { + let slot = match stage { + crate::ShaderStage::Vertex => self.push_constants_map.vs_buffer, + crate::ShaderStage::Fragment => self.push_constants_map.fs_buffer, + crate::ShaderStage::Compute => self.push_constants_map.cs_buffer, + }; + match slot { + Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { + buffer: Some(slot), + texture: None, + sampler: None, + mutable: false, + })), + None if self.fake_missing_bindings => Ok(ResolvedBinding::User { + prefix: "fake", + index: 0, + }), + None => Err(EntryPointError::MissingPushConstants(stage)), + } + } } impl ResolvedBinding { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a2648165e..da43c71ee 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -321,6 +321,7 @@ impl crate::StorageClass { crate::StorageClass::Uniform | crate::StorageClass::Storage | crate::StorageClass::Private + | crate::StorageClass::PushConstant | crate::StorageClass::Handle => true, _ => false, } @@ -1751,7 +1752,12 @@ impl Writer { .find_map(|(var_handle, var)| { if !fun_info[var_handle].is_empty() { if let Some(ref br) = var.binding { - if let Err(e) = options.resolve_global_binding(ep.stage, br) { + if let Err(e) = options.resolve_resource_binding(ep.stage, br) { + return Some(e); + } + } + if var.class == crate::StorageClass::PushConstant { + if let Err(e) = options.resolve_push_constants(ep.stage) { return Some(e); } } @@ -1920,10 +1926,16 @@ impl Writer { if usage.is_empty() || var.class == crate::StorageClass::Private { continue; } - let resolved = var - .binding - .as_ref() - .map(|binding| options.resolve_global_binding(ep.stage, binding).unwrap()); + // the resolves have already been checked for `!fake_missing_bindings` case + let resolved = match var.class { + crate::StorageClass::PushConstant => { + options.resolve_push_constants(ep.stage).ok() + } + crate::StorageClass::WorkGroup => None, + _ => options + .resolve_resource_binding(ep.stage, var.binding.as_ref().unwrap()) + .ok(), + }; if let Some(ref resolved) = resolved { // Inline samplers are be defined in the EP body if resolved.as_inline_sampler(options).is_some() { @@ -1997,7 +2009,7 @@ impl Writer { }; } else if let Some(ref binding) = var.binding { // write an inline sampler - let resolved = options.resolve_global_binding(ep.stage, binding).unwrap(); + let resolved = options.resolve_resource_binding(ep.stage, binding).unwrap(); if let Some(sampler) = resolved.as_inline_sampler(options) { let name = &self.names[&NameKey::GlobalVariable(handle)]; writeln!( diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index 06a8df2da..551fecede 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -12,6 +12,8 @@ (stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true), (stage: Compute, group: 0, binding: 2): (buffer: Some(2), mutable: true), }, + push_constants_map: ( + ), inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 9a85ec2d0..dec89803e 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -12,6 +12,8 @@ (stage: Fragment, group: 0, binding: 1): (texture: Some(0)), (stage: Fragment, group: 0, binding: 2): (sampler: Some(Inline(1))), }, + push_constants_map: ( + ), inline_samplers: [ ( coord: Normalized, From 2923cfb3aa804bc009cb9619b4119773d0f4577b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 13 Apr 2021 01:22:20 -0400 Subject: [PATCH 0695/2212] [spv-in] claim Vulkan Memory Model support --- src/front/spv/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 6589d1bb7..6a2fdd18a 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -48,6 +48,7 @@ use std::{convert::TryInto, num::NonZeroU32, path::PathBuf}; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, + spirv::Capability::VulkanMemoryModel, spirv::Capability::ClipDistance, spirv::Capability::CullDistance, spirv::Capability::SampleRateShading, @@ -67,7 +68,7 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::UniformBufferArrayDynamicIndexing, spirv::Capability::StorageBufferArrayDynamicIndexing, ]; -pub const SUPPORTED_EXTENSIONS: &[&str] = &[]; +pub const SUPPORTED_EXTENSIONS: &[&str] = &["SPV_KHR_vulkan_memory_model"]; pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"]; #[derive(Copy, Clone)] From 3f57e4db5adfd794d170843d7f1b8845dac1609c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 13 Apr 2021 01:27:28 -0400 Subject: [PATCH 0696/2212] Enable texture-array snapshot on Metal --- tests/out/texture-array.msl.snap | 34 ++++++++++++++++++++++++++++++++ tests/snapshots.rs | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 tests/out/texture-array.msl.snap diff --git a/tests/out/texture-array.msl.snap b/tests/out/texture-array.msl.snap new file mode 100644 index 000000000..3e98f7a0c --- /dev/null +++ b/tests/out/texture-array.msl.snap @@ -0,0 +1,34 @@ +--- +source: tests/snapshots.rs +expression: msl +--- +#include +#include + +struct PushConstants { + metal::uint index; +}; + +struct main1Input { + metal::float2 tex_coord [[user(loc0)]]; +}; +struct main1Output { + metal::float4 member [[color(1)]]; +}; +fragment main1Output main1( + main1Input varyings [[stage_in]] +, metal::texture2d texture0_ [[user(fake0)]] +, metal::texture2d texture1_ [[user(fake0)]] +, metal::sampler sampler [[user(fake0)]] +, constant PushConstants& pc [[user(fake0)]] +) { + const auto tex_coord = varyings.tex_coord; + if (pc.index == 0u) { + metal::float4 _e9 = texture0_.sample(sampler, tex_coord); + return main1Output { _e9 }; + } else { + metal::float4 _e10 = texture1_.sample(sampler, tex_coord); + return main1Output { _e10 }; + } +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d2ec5d824..472505678 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -267,7 +267,7 @@ fn convert_wgsl_image_copy() { #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl_texture_array() { - convert_wgsl("texture-array", Targets::SPIRV); + convert_wgsl("texture-array", Targets::SPIRV | Targets::METAL); } #[cfg(feature = "spv-in")] From f7fdf6b560577d7fdf2921934f6236c83bcb1e32 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 13 Apr 2021 14:36:38 -0700 Subject: [PATCH 0697/2212] Makefile: Be more flexible in removing YAML headers from snapshots. The snapshot files in tests/out start with headers like this: --- source: tests/snapshots.rs expression: dis --- ; SPIR-V ; Version: 1.0 ; Generator: rspirv ... The Makefile's `validate-foo` targets trim off those lines with `tail -n +5` before submitting their test to the validators. However, some versions of the `insta` crate seem to generate headers with an extra blank line, like this: --- source: tests/snapshots.rs expression: dis --- This makes the `validate-foo` targets unhappy. This commit changes the `validate-foo` targets to use `sed` to cope with both kinds of headers. --- Makefile | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 8f3883419..94e512e84 100644 --- a/Makefile +++ b/Makefile @@ -26,34 +26,38 @@ clean: %.png: %.dot dot -Tpng $< -o $@ +# A command to remove the '---' YAML document start markers from the snapshots +# before passing their contents to a validator. +TRIM=sed -e '1d' -e '2,/---/d' + validate-spv: $(SNAPSHOTS_OUT)/*.spvasm.snap @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ - tail -n +5 $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ + $(TRIM) $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ done validate-msl: $(SNAPSHOTS_OUT)/*.msl.snap @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ - tail -n +5 $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ + $(TRIM) $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ done validate-glsl: $(SNAPSHOTS_OUT)/*.glsl.snap @set -e && for file in $(SNAPSHOTS_OUT)/*-Vertex.glsl.snap ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ - tail -n +5 $${file} | glslangValidator --stdin -S vert; \ + $(TRIM) $${file} | glslangValidator --stdin -S vert; \ done @set -e && for file in $(SNAPSHOTS_OUT)/*-Fragment.glsl.snap ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ - tail -n +5 $${file} | glslangValidator --stdin -S frag; \ + $(TRIM) $${file} | glslangValidator --stdin -S frag; \ done @set -e && for file in $(SNAPSHOTS_OUT)/*-Compute.glsl.snap ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ - tail -n +5 $${file} | glslangValidator --stdin -S comp; \ + $(TRIM) $${file} | glslangValidator --stdin -S comp; \ done validate-dot: $(SNAPSHOTS_OUT)/*.dot.snap @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ - tail -n +5 $${file} | dot -o /dev/null; \ + $(TRIM) $${file} | dot -o /dev/null; \ done From c2c93e4ecd891c5d930f4b52a6ef2c60843012fc Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 14 Apr 2021 14:20:48 -0400 Subject: [PATCH 0698/2212] Remove cargo-insta --- .github/workflows/pipeline.yml | 2 + Cargo.toml | 3 +- Makefile | 42 ++-- README.md | 6 +- tests/errors.rs | 114 ++++----- tests/out/{boids.msl.snap => boids.msl} | 5 - tests/out/{boids.spvasm.snap => boids.spvasm} | 6 +- ...collatz.info.ron.snap => collatz.info.ron} | 6 +- tests/out/{collatz.msl.snap => collatz.msl} | 5 - tests/out/{collatz.ron.snap => collatz.ron} | 6 +- .../{collatz.spvasm.snap => collatz.spvasm} | 6 +- ...y-Compute.glsl.snap => empty.Compute.glsl} | 5 - tests/out/empty.hlsl | 5 + tests/out/empty.hlsl.snap | 11 - tests/out/{empty.msl.snap => empty.msl} | 5 - tests/out/{empty.spvasm.snap => empty.spvasm} | 6 +- .../{image-copy.msl.snap => image-copy.msl} | 5 - tests/out/quad-glsl.ron.snap | 224 ------------------ tests/out/quad-glsl.spvasm.snap | 63 ----- .../out/{quad-vert.msl.snap => quad-vert.msl} | 5 - ...-Fragment.glsl.snap => quad.Fragment.glsl} | 5 - ...quad-Vertex.glsl.snap => quad.Vertex.glsl} | 5 - tests/out/{quad.dot.snap => quad.dot} | 5 - tests/out/{quad.msl.snap => quad.msl} | 5 - tests/out/{quad.spvasm.snap => quad.spvasm} | 6 +- ...ragment.glsl.snap => shadow.Fragment.glsl} | 5 - .../{shadow.info.ron.snap => shadow.info.ron} | 6 +- tests/out/{shadow.msl.snap => shadow.msl} | 5 - tests/out/{shadow.ron.snap => shadow.ron} | 6 +- .../out/{shadow.spvasm.snap => shadow.spvasm} | 6 +- ...ragment.glsl.snap => skybox.Fragment.glsl} | 5 - ...ox-Vertex.glsl.snap => skybox.Vertex.glsl} | 5 - tests/out/{skybox.msl.snap => skybox.msl} | 5 - .../out/{skybox.spvasm.snap => skybox.spvasm} | 6 +- ...xture-array.msl.snap => texture-array.msl} | 5 - ...array.spvasm.snap => texture-array.spvasm} | 6 +- tests/snapshots.rs | 87 ++++--- 37 files changed, 139 insertions(+), 564 deletions(-) rename tests/out/{boids.msl.snap => boids.msl} (98%) rename tests/out/{boids.spvasm.snap => boids.spvasm} (99%) rename tests/out/{collatz.info.ron.snap => collatz.info.ron} (99%) rename tests/out/{collatz.msl.snap => collatz.msl} (93%) rename tests/out/{collatz.ron.snap => collatz.ron} (99%) rename tests/out/{collatz.spvasm.snap => collatz.spvasm} (97%) rename tests/out/{empty-Compute.glsl.snap => empty.Compute.glsl} (71%) create mode 100644 tests/out/empty.hlsl delete mode 100644 tests/out/empty.hlsl.snap rename tests/out/{empty.msl.snap => empty.msl} (62%) rename tests/out/{empty.spvasm.snap => empty.spvasm} (83%) rename tests/out/{image-copy.msl.snap => image-copy.msl} (91%) delete mode 100644 tests/out/quad-glsl.ron.snap delete mode 100644 tests/out/quad-glsl.spvasm.snap rename tests/out/{quad-vert.msl.snap => quad-vert.msl} (96%) rename tests/out/{quad-Fragment.glsl.snap => quad.Fragment.glsl} (89%) rename tests/out/{quad-Vertex.glsl.snap => quad.Vertex.glsl} (89%) rename tests/out/{quad.dot.snap => quad.dot} (98%) rename tests/out/{quad.msl.snap => quad.msl} (95%) rename tests/out/{quad.spvasm.snap => quad.spvasm} (97%) rename tests/out/{shadow-Fragment.glsl.snap => shadow.Fragment.glsl} (96%) rename tests/out/{shadow.info.ron.snap => shadow.info.ron} (99%) rename tests/out/{shadow.msl.snap => shadow.msl} (97%) rename tests/out/{shadow.ron.snap => shadow.ron} (99%) rename tests/out/{shadow.spvasm.snap => shadow.spvasm} (98%) rename tests/out/{skybox-Fragment.glsl.snap => skybox.Fragment.glsl} (88%) rename tests/out/{skybox-Vertex.glsl.snap => skybox.Vertex.glsl} (95%) rename tests/out/{skybox.msl.snap => skybox.msl} (97%) rename tests/out/{skybox.spvasm.snap => skybox.spvasm} (98%) rename tests/out/{texture-array.msl.snap => texture-array.msl} (94%) rename tests/out/{texture-array.spvasm.snap => texture-array.spvasm} (96%) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 5ee486280..3d9ca0f6a 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -24,6 +24,8 @@ jobs: with: command: test args: --all-features + - name: Check snapshots + run: git diff --exit-code -- tests/out clippy: name: Clippy runs-on: ubuntu-latest diff --git a/Cargo.toml b/Cargo.toml index c96aa733f..ca412e4e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,9 +46,8 @@ name = "convert" path = "bin/convert.rs" [dev-dependencies] -difference = "2.0" +diff = "0.1" ron = "0.6" serde = { version = "1.0", features = ["derive"] } spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } -insta = { version = "1.6", features = ["glob"] } rspirv = "0.7" diff --git a/Makefile b/Makefile index 94e512e84..2eeec5eb0 100644 --- a/Makefile +++ b/Makefile @@ -26,38 +26,34 @@ clean: %.png: %.dot dot -Tpng $< -o $@ -# A command to remove the '---' YAML document start markers from the snapshots -# before passing their contents to a validator. -TRIM=sed -e '1d' -e '2,/---/d' - -validate-spv: $(SNAPSHOTS_OUT)/*.spvasm.snap +validate-spv: $(SNAPSHOTS_OUT)/*.spvasm @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ - $(TRIM) $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)"}; \ + cat $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ done -validate-msl: $(SNAPSHOTS_OUT)/*.msl.snap +validate-msl: $(SNAPSHOTS_OUT)/*.msl @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ - $(TRIM) $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)"}; \ + cat $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ done -validate-glsl: $(SNAPSHOTS_OUT)/*.glsl.snap - @set -e && for file in $(SNAPSHOTS_OUT)/*-Vertex.glsl.snap ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ - $(TRIM) $${file} | glslangValidator --stdin -S vert; \ +validate-glsl: $(SNAPSHOTS_OUT)/*.glsl + @set -e && for file in $(SNAPSHOTS_OUT)/*.Vertex.glsl ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)"};\ + cat $${file} | glslangValidator --stdin -S vert; \ done - @set -e && for file in $(SNAPSHOTS_OUT)/*-Fragment.glsl.snap ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ - $(TRIM) $${file} | glslangValidator --stdin -S frag; \ + @set -e && for file in $(SNAPSHOTS_OUT)/*.Fragment.glsl ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)"};\ + cat $${file} | glslangValidator --stdin -S frag; \ done - @set -e && for file in $(SNAPSHOTS_OUT)/*-Compute.glsl.snap ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"};\ - $(TRIM) $${file} | glslangValidator --stdin -S comp; \ + @set -e && for file in $(SNAPSHOTS_OUT)/*.Compute.glsl ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)"};\ + cat $${file} | glslangValidator --stdin -S comp; \ done -validate-dot: $(SNAPSHOTS_OUT)/*.dot.snap +validate-dot: $(SNAPSHOTS_OUT)/*.dot @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/snapshots__"}; \ - $(TRIM) $${file} | dot -o /dev/null; \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)"}; \ + cat $${file} | dot -o /dev/null; \ done diff --git a/README.md b/README.md index 9a83e18d8..5873d8eff 100644 --- a/README.md +++ b/README.md @@ -44,9 +44,8 @@ cargo run --features wgsl-in,glsl-out -- my_shader.wgsl my_shader.vert --profile ## Development workflow The main instrument aiding the development is the good old `cargo test --all-features`, -which will run the snapshot tests as well as the unit tests. -Any changes in the snapshots would then have to be reviewed with `cargo insta review` -before being accepted into the code. +which will run the unit tests, and also update all the snapshots. You'll see these +changes in git before committing the code. If working on a particular front-end or back-end, it may be convenient to enable the relevant features in `Cargo.toml`, e.g. @@ -61,4 +60,5 @@ are indeed valid for the target platforms they are compiled for. We automate thi make validate-spv # for Vulkan shaders, requires SPIRV-Tools installed make validate-msl # for Metal shaders, requires XCode command-line tools installed make validate-glsl # for OpenGL shaders, requires GLSLang installed +make validate-dot # for dot files, requires GraphViz installed ``` diff --git a/tests/errors.rs b/tests/errors.rs index 437288ab5..7567b203b 100644 --- a/tests/errors.rs +++ b/tests/errors.rs @@ -1,99 +1,99 @@ #[cfg(feature = "wgsl-in")] -macro_rules! err { - ($value:expr, @$snapshot:literal) => { - ::insta::assert_snapshot!( - naga::front::wgsl::parse_str($value) - .expect_err("expected parser error") - .emit_to_string(), - @$snapshot - ); - }; +fn check(input: &str, snapshot: &str) { + let output = naga::front::wgsl::parse_str(input) + .expect_err("expected parser error") + .emit_to_string(); + if output != snapshot { + for diff in diff::lines(&output, snapshot) { + match diff { + diff::Result::Left(l) => println!("-{}", l), + diff::Result::Both(l, _) => println!(" {}", l), + diff::Result::Right(r) => println!("+{}", r), + } + } + panic!("Error snapshot failed"); + } } #[cfg(feature = "wgsl-in")] #[test] fn function_without_identifier() { - err!( + check( "fn () {}", - @r###" - error: expected identifier, found '(' - ┌─ wgsl:1:4 - │ - 1 │ fn () {} - │ ^ expected identifier +r###"error: expected identifier, found '(' + ┌─ wgsl:1:4 + │ +1 │ fn () {} + │ ^ expected identifier - "### +"###, ); } #[cfg(feature = "wgsl-in")] #[test] fn invalid_integer() { - err!( + check( "fn foo([location(1.)] x: i32) {}", - @r###" - error: expected identifier, found '[' - ┌─ wgsl:1:8 - │ - 1 │ fn foo([location(1.)] x: i32) {} - │ ^ expected identifier +r###"error: expected identifier, found '[' + ┌─ wgsl:1:8 + │ +1 │ fn foo([location(1.)] x: i32) {} + │ ^ expected identifier - "### +"###, ); } #[cfg(feature = "wgsl-in")] #[test] fn invalid_float() { - err!( + check( "let scale: f32 = 1.1.;", - @r###" - error: expected floating-point literal, found `1.1.` - ┌─ wgsl:1:18 - │ - 1 │ let scale: f32 = 1.1.; - │ ^^^^ expected floating-point literal +r###"error: expected floating-point literal, found `1.1.` + ┌─ wgsl:1:18 + │ +1 │ let scale: f32 = 1.1.; + │ ^^^^ expected floating-point literal - "### +"###, ); } #[cfg(feature = "wgsl-in")] #[test] fn invalid_scalar_width() { - err!( + check( "let scale: f32 = 1.1f1000;", - @r###" - error: invalid width of `1000` for literal - ┌─ wgsl:1:18 - │ - 1 │ let scale: f32 = 1.1f1000; - │ ^^^^^^^^ invalid width - │ - = note: valid width is 32 +r###"error: invalid width of `1000` for literal + ┌─ wgsl:1:18 + │ +1 │ let scale: f32 = 1.1f1000; + │ ^^^^^^^^ invalid width + │ + = note: valid width is 32 - "### +"###, ); } #[cfg(feature = "wgsl-in")] #[test] fn invalid_accessor() { - err!( + check( r###" - [[stage(vertex)]] - fn vs_main() { - var color: vec3 = vec3(1.0, 2.0, 3.0); - var i: f32 = color.a; - } - "###, - @r###" - error: invalid field accessor `a` - ┌─ wgsl:5:32 - │ - 5 │ var i: f32 = color.a; - │ ^ invalid accessor +[[stage(vertex)]] +fn vs_main() { + var color: vec3 = vec3(1.0, 2.0, 3.0); + var i: f32 = color.a; +} +"###, +r###"error: invalid field accessor `a` + ┌─ wgsl:5:24 + │ +5 │ var i: f32 = color.a; + │ ^ invalid accessor - "### +"###, ); } diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl similarity index 98% rename from tests/out/boids.msl.snap rename to tests/out/boids.msl index d59f82aea..24e7d2ca0 100644 --- a/tests/out/boids.msl.snap +++ b/tests/out/boids.msl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: msl ---- #include #include @@ -101,4 +97,3 @@ kernel void main1( particlesDst.particles[global_invocation_id.x].vel = vVel; return; } - diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm similarity index 99% rename from tests/out/boids.spvasm.snap rename to tests/out/boids.spvasm index ded452eae..7df829a38 100644 --- a/tests/out/boids.spvasm.snap +++ b/tests/out/boids.spvasm @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: dis ---- ; SPIR-V ; Version: 1.0 ; Generator: rspirv @@ -332,4 +328,4 @@ OpStore %200 %199 %202 = OpAccessChain %53 %25 %7 %46 %10 OpStore %202 %201 OpReturn -OpFunctionEnd +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron similarity index 99% rename from tests/out/collatz.info.ron.snap rename to tests/out/collatz.info.ron index 4f5c1ef92..6bea48630 100644 --- a/tests/out/collatz.info.ron.snap +++ b/tests/out/collatz.info.ron @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: output ---- ( functions: [ ( @@ -498,4 +494,4 @@ expression: output ], ), ], -) +) \ No newline at end of file diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl similarity index 93% rename from tests/out/collatz.msl.snap rename to tests/out/collatz.msl index efded439e..403789659 100644 --- a/tests/out/collatz.msl.snap +++ b/tests/out/collatz.msl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: msl ---- #include #include @@ -40,4 +36,3 @@ kernel void main1( v_indices.data[global_id.x] = _e9; return; } - diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron similarity index 99% rename from tests/out/collatz.ron.snap rename to tests/out/collatz.ron index b86183c22..65f98a6e8 100644 --- a/tests/out/collatz.ron.snap +++ b/tests/out/collatz.ron @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: output ---- ( types: [ ( @@ -347,4 +343,4 @@ expression: output ), ), ], -) +) \ No newline at end of file diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm similarity index 97% rename from tests/out/collatz.spvasm.snap rename to tests/out/collatz.spvasm index 9d56582b9..cc4698fa4 100644 --- a/tests/out/collatz.spvasm.snap +++ b/tests/out/collatz.spvasm @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: dis ---- ; SPIR-V ; Version: 1.0 ; Generator: rspirv @@ -109,4 +105,4 @@ OpBranch %50 %60 = OpAccessChain %53 %11 %56 %52 OpStore %60 %59 OpReturn -OpFunctionEnd +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/empty-Compute.glsl.snap b/tests/out/empty.Compute.glsl similarity index 71% rename from tests/out/empty-Compute.glsl.snap rename to tests/out/empty.Compute.glsl index 4fbc229db..63328eab1 100644 --- a/tests/out/empty-Compute.glsl.snap +++ b/tests/out/empty.Compute.glsl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: string ---- #version 310 es precision highp float; @@ -13,4 +9,3 @@ void main() { return; } - diff --git a/tests/out/empty.hlsl b/tests/out/empty.hlsl new file mode 100644 index 000000000..d1d3c9cb2 --- /dev/null +++ b/tests/out/empty.hlsl @@ -0,0 +1,5 @@ + +void main() +{ + return; +} diff --git a/tests/out/empty.hlsl.snap b/tests/out/empty.hlsl.snap deleted file mode 100644 index 2cfc16ce6..000000000 --- a/tests/out/empty.hlsl.snap +++ /dev/null @@ -1,11 +0,0 @@ ---- -source: tests/snapshots.rs -expression: hlsl - ---- - -void main() -{ - return; -} - diff --git a/tests/out/empty.msl.snap b/tests/out/empty.msl similarity index 62% rename from tests/out/empty.msl.snap rename to tests/out/empty.msl index 9d081189a..9b4ad4862 100644 --- a/tests/out/empty.msl.snap +++ b/tests/out/empty.msl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: msl ---- #include #include @@ -10,4 +6,3 @@ kernel void main1( ) { return; } - diff --git a/tests/out/empty.spvasm.snap b/tests/out/empty.spvasm similarity index 83% rename from tests/out/empty.spvasm.snap rename to tests/out/empty.spvasm index bd9279de9..47d3c1756 100644 --- a/tests/out/empty.spvasm.snap +++ b/tests/out/empty.spvasm @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: dis ---- ; SPIR-V ; Version: 1.1 ; Generator: rspirv @@ -18,4 +14,4 @@ OpExecutionMode %4 LocalSize 1 1 1 OpBranch %6 %6 = OpLabel OpReturn -OpFunctionEnd +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/image-copy.msl.snap b/tests/out/image-copy.msl similarity index 91% rename from tests/out/image-copy.msl.snap rename to tests/out/image-copy.msl index 893768a9b..73407ceef 100644 --- a/tests/out/image-copy.msl.snap +++ b/tests/out/image-copy.msl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: msl ---- #include #include @@ -18,4 +14,3 @@ kernel void main1( image_dst.write(_e13, metal::uint(_e12.x)); return; } - diff --git a/tests/out/quad-glsl.ron.snap b/tests/out/quad-glsl.ron.snap deleted file mode 100644 index 2b8256eee..000000000 --- a/tests/out/quad-glsl.ron.snap +++ /dev/null @@ -1,224 +0,0 @@ ---- -source: tests/snapshots.rs -expression: output ---- -( - types: [ - ( - name: None, - inner: Scalar( - kind: Float, - width: 4, - ), - ), - ( - name: None, - inner: Vector( - size: Bi, - kind: Float, - width: 4, - ), - ), - ( - name: None, - inner: Vector( - size: Quad, - kind: Float, - width: 4, - ), - ), - ], - constants: [ - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(1.2000000476837158), - ), - ), - ( - name: Some("c_scale"), - specialization: None, - inner: Scalar( - width: 4, - value: Float(1.2000000476837158), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(1), - ), - ), - ], - global_variables: [ - ( - name: Some("a_pos"), - class: Input, - binding: Some(Location(0)), - ty: 2, - init: None, - interpolation: None, - storage_access: ( - bits: 0, - ), - ), - ( - name: Some("a_uv"), - class: Input, - binding: Some(Location(1)), - ty: 2, - init: None, - interpolation: None, - storage_access: ( - bits: 0, - ), - ), - ( - name: Some("v_uv"), - class: Output, - binding: Some(Location(0)), - ty: 2, - init: None, - interpolation: None, - storage_access: ( - bits: 0, - ), - ), - ( - name: Some("gl_Position"), - class: Output, - binding: Some(BuiltIn(Position)), - ty: 3, - init: None, - interpolation: None, - storage_access: ( - bits: 0, - ), - ), - ( - name: Some("v_uv"), - class: Input, - binding: Some(Location(0)), - ty: 2, - init: None, - interpolation: None, - storage_access: ( - bits: 0, - ), - ), - ( - name: Some("o_color"), - class: Output, - binding: Some(Location(0)), - ty: 3, - init: None, - interpolation: None, - storage_access: ( - bits: 0, - ), - ), - ], - functions: [], - entry_points: { - (Fragment, "frag_main"): ( - early_depth_test: None, - workgroup_size: (0, 0, 0), - function: ( - name: Some("frag_main"), - arguments: [], - return_type: None, - local_variables: [], - expressions: [ - GlobalVariable(1), - GlobalVariable(2), - GlobalVariable(3), - GlobalVariable(4), - GlobalVariable(5), - GlobalVariable(6), - Constant(2), - Constant(4), - Constant(4), - Constant(4), - Constant(4), - Compose( - ty: 3, - components: [ - 8, - 9, - 10, - 11, - ], - ), - ], - body: [ - Store( - pointer: 6, - value: 12, - ), - Return( - value: None, - ), - ], - ), - ), - (Vertex, "vert_main"): ( - early_depth_test: None, - workgroup_size: (0, 0, 0), - function: ( - name: Some("vert_main"), - arguments: [], - return_type: None, - local_variables: [], - expressions: [ - Constant(1), - Constant(2), - GlobalVariable(1), - GlobalVariable(2), - GlobalVariable(3), - Constant(2), - GlobalVariable(4), - Binary( - op: Multiply, - left: 6, - right: 3, - ), - Constant(3), - Constant(4), - Compose( - ty: 3, - components: [ - 8, - 9, - 10, - ], - ), - ], - body: [ - Store( - pointer: 5, - value: 4, - ), - Store( - pointer: 7, - value: 11, - ), - Return( - value: None, - ), - ], - ), - ), - }, -) diff --git a/tests/out/quad-glsl.spvasm.snap b/tests/out/quad-glsl.spvasm.snap deleted file mode 100644 index 1c68ac044..000000000 --- a/tests/out/quad-glsl.spvasm.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: tests/snapshots.rs -expression: dis ---- -; SPIR-V -; Version: 1.0 -; Generator: rspirv -; Bound: 28 -OpCapability Shader -%1 = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %8 "frag_main" %12 -OpEntryPoint Vertex %15 "vert_main" %25 %20 %18 %23 -OpExecutionMode %8 OriginUpperLeft -OpSource GLSL 450 -OpName %5 "c_scale" -OpName %8 "frag_main" -OpName %12 "o_color" -OpName %8 "frag_main" -OpName %15 "vert_main" -OpName %18 "v_uv" -OpName %20 "a_uv" -OpName %23 "gl_Position" -OpName %25 "a_pos" -OpName %15 "vert_main" -OpDecorate %12 Location 0 -OpDecorate %18 Location 0 -OpDecorate %20 Location 1 -OpDecorate %23 BuiltIn Position -OpDecorate %25 Location 0 -%2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 1.2 -%5 = OpConstant %4 1.2 -%6 = OpConstant %4 0.0 -%7 = OpConstant %4 1.0 -%9 = OpTypeFunction %2 -%11 = OpTypeVector %4 4 -%13 = OpTypePointer Output %11 -%12 = OpVariable %13 Output -%17 = OpTypeVector %4 2 -%19 = OpTypePointer Output %17 -%18 = OpVariable %19 Output -%21 = OpTypePointer Input %17 -%20 = OpVariable %21 Input -%23 = OpVariable %13 Output -%25 = OpVariable %21 Input -%8 = OpFunction %2 None %9 -%10 = OpLabel -%14 = OpCompositeConstruct %11 %7 %7 %7 %7 -OpStore %12 %14 -OpReturn -OpFunctionEnd -%15 = OpFunction %2 None %9 -%16 = OpLabel -%22 = OpLoad %17 %20 -OpStore %18 %22 -%26 = OpLoad %17 %25 -%24 = OpVectorTimesScalar %17 %26 %5 -%27 = OpCompositeConstruct %11 %24 %6 %7 -OpStore %23 %27 -OpReturn -OpFunctionEnd diff --git a/tests/out/quad-vert.msl.snap b/tests/out/quad-vert.msl similarity index 96% rename from tests/out/quad-vert.msl.snap rename to tests/out/quad-vert.msl index bc5e83c4a..f616b1526 100644 --- a/tests/out/quad-vert.msl.snap +++ b/tests/out/quad-vert.msl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: msl ---- #include #include @@ -56,4 +52,3 @@ vertex main2Output main2( const auto _tmp = type10 {v_uv, _.gl_Position, _.gl_PointSize, {_.gl_ClipDistance[0]}}; return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1[0]} }; } - diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad.Fragment.glsl similarity index 89% rename from tests/out/quad-Fragment.glsl.snap rename to tests/out/quad.Fragment.glsl index 7d873bc76..7122843b3 100644 --- a/tests/out/quad-Fragment.glsl.snap +++ b/tests/out/quad.Fragment.glsl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: string ---- #version 310 es precision highp float; @@ -26,4 +22,3 @@ void main() { return; } - diff --git a/tests/out/quad-Vertex.glsl.snap b/tests/out/quad.Vertex.glsl similarity index 89% rename from tests/out/quad-Vertex.glsl.snap rename to tests/out/quad.Vertex.glsl index 99ff87ef1..b35cf16eb 100644 --- a/tests/out/quad-Vertex.glsl.snap +++ b/tests/out/quad.Vertex.glsl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: string ---- #version 310 es precision highp float; @@ -26,4 +22,3 @@ void main() { return; } - diff --git a/tests/out/quad.dot.snap b/tests/out/quad.dot similarity index 98% rename from tests/out/quad.dot.snap rename to tests/out/quad.dot index b839e856d..6e8c54164 100644 --- a/tests/out/quad.dot.snap +++ b/tests/out/quad.dot @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: string ---- digraph Module { subgraph cluster_globals { label="Globals" @@ -108,4 +104,3 @@ digraph Module { ep1_s8 -> ep1_e9 [ style=dotted ] } } - diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl similarity index 95% rename from tests/out/quad.msl.snap rename to tests/out/quad.msl index fb4f8421a..17f225b0d 100644 --- a/tests/out/quad.msl.snap +++ b/tests/out/quad.msl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: msl ---- #include #include @@ -50,4 +46,3 @@ fragment main2Output main2( } return main2Output { _e4.w * _e4 }; } - diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm similarity index 97% rename from tests/out/quad.spvasm.snap rename to tests/out/quad.spvasm index 800c4f612..676aee116 100644 --- a/tests/out/quad.spvasm.snap +++ b/tests/out/quad.spvasm @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: dis ---- ; SPIR-V ; Version: 1.0 ; Generator: rspirv @@ -118,4 +114,4 @@ OpKill %64 = OpVectorTimesScalar %8 %57 %63 OpStore %50 %64 OpReturn -OpFunctionEnd +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/shadow-Fragment.glsl.snap b/tests/out/shadow.Fragment.glsl similarity index 96% rename from tests/out/shadow-Fragment.glsl.snap rename to tests/out/shadow.Fragment.glsl index 14501be8d..6178ae100 100644 --- a/tests/out/shadow-Fragment.glsl.snap +++ b/tests/out/shadow.Fragment.glsl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: string ---- #version 310 es precision highp float; @@ -53,4 +49,3 @@ void main() { return; } - diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron similarity index 99% rename from tests/out/shadow.info.ron.snap rename to tests/out/shadow.info.ron index 3260f6134..661a8655b 100644 --- a/tests/out/shadow.info.ron.snap +++ b/tests/out/shadow.info.ron @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: output ---- ( functions: [ ( @@ -2873,4 +2869,4 @@ expression: output ], ), ], -) +) \ No newline at end of file diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl similarity index 97% rename from tests/out/shadow.msl.snap rename to tests/out/shadow.msl index 92cd9e83d..2cb78ff8d 100644 --- a/tests/out/shadow.msl.snap +++ b/tests/out/shadow.msl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: msl ---- #include #include @@ -67,4 +63,3 @@ fragment fs_mainOutput fs_main( } return fs_mainOutput { metal::float4(color1, 1.0) }; } - diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron similarity index 99% rename from tests/out/shadow.ron.snap rename to tests/out/shadow.ron index 0d57ef42e..4d1e38a3b 100644 --- a/tests/out/shadow.ron.snap +++ b/tests/out/shadow.ron @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: output ---- ( types: [ ( @@ -1572,4 +1568,4 @@ expression: output ), ), ], -) +) \ No newline at end of file diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm similarity index 98% rename from tests/out/shadow.spvasm.snap rename to tests/out/shadow.spvasm index e478f288e..1f6f80039 100644 --- a/tests/out/shadow.spvasm.snap +++ b/tests/out/shadow.spvasm @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: dis ---- ; SPIR-V ; Version: 1.2 ; Generator: rspirv @@ -209,4 +205,4 @@ OpBranch %87 %135 = OpCompositeConstruct %16 %134 %5 OpStore %79 %135 OpReturn -OpFunctionEnd +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox.Fragment.glsl similarity index 88% rename from tests/out/skybox-Fragment.glsl.snap rename to tests/out/skybox.Fragment.glsl index 2975a920b..11f715ee7 100644 --- a/tests/out/skybox-Fragment.glsl.snap +++ b/tests/out/skybox.Fragment.glsl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: string ---- #version 310 es precision highp float; @@ -23,4 +19,3 @@ void main() { return; } - diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox.Vertex.glsl similarity index 95% rename from tests/out/skybox-Vertex.glsl.snap rename to tests/out/skybox.Vertex.glsl index 8c27eed33..b30eced32 100644 --- a/tests/out/skybox-Vertex.glsl.snap +++ b/tests/out/skybox.Vertex.glsl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: string ---- #version 310 es precision highp float; @@ -34,4 +30,3 @@ void main() { return; } - diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl similarity index 97% rename from tests/out/skybox.msl.snap rename to tests/out/skybox.msl index 5be5f5459..bd43ac6f6 100644 --- a/tests/out/skybox.msl.snap +++ b/tests/out/skybox.msl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: msl ---- #include #include @@ -61,4 +57,3 @@ fragment fs_mainOutput fs_main( metal::float4 _e5 = r_texture.sample(r_sampler, in.uv); return fs_mainOutput { _e5 }; } - diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm similarity index 98% rename from tests/out/skybox.spvasm.snap rename to tests/out/skybox.spvasm index d41aa067b..7455b1294 100644 --- a/tests/out/skybox.spvasm.snap +++ b/tests/out/skybox.spvasm @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: dis ---- ; SPIR-V ; Version: 1.0 ; Generator: rspirv @@ -154,4 +150,4 @@ OpBranch %106 %110 = OpImageSampleImplicitLod %10 %109 %107 OpStore %102 %110 OpReturn -OpFunctionEnd +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/texture-array.msl.snap b/tests/out/texture-array.msl similarity index 94% rename from tests/out/texture-array.msl.snap rename to tests/out/texture-array.msl index 3e98f7a0c..06c758842 100644 --- a/tests/out/texture-array.msl.snap +++ b/tests/out/texture-array.msl @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: msl ---- #include #include @@ -31,4 +27,3 @@ fragment main1Output main1( return main1Output { _e10 }; } } - diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm similarity index 96% rename from tests/out/texture-array.spvasm.snap rename to tests/out/texture-array.spvasm index 2a5b56ef9..dfc2b1f4d 100644 --- a/tests/out/texture-array.spvasm.snap +++ b/tests/out/texture-array.spvasm @@ -1,7 +1,3 @@ ---- -source: tests/snapshots.rs -expression: dis ---- ; SPIR-V ; Version: 1.5 ; Generator: rspirv @@ -82,4 +78,4 @@ OpStore %22 %44 OpReturn %37 = OpLabel OpBranch %29 -OpFunctionEnd +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 472505678..e54f389c3 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -1,3 +1,11 @@ +//TODO: move this to a binary target once Rust supports +// binary-specific dependencies. + +use std::{fs, path::PathBuf}; + +const DIR_IN: &str = "tests/in"; +const DIR_OUT: &str = "tests/out"; + bitflags::bitflags! { struct Targets: u32 { const IR = 0x1; @@ -27,17 +35,10 @@ struct Parameters { msl_custom: bool, } -#[allow(dead_code)] -fn with_snapshot_settings ()>(snapshot_assertion: F) { - let mut settings = insta::Settings::new(); - settings.set_snapshot_path("out"); - settings.set_prepend_module_to_snapshot(false); - settings.bind(|| snapshot_assertion()); -} - #[allow(dead_code, unused_variables)] fn check_targets(module: &naga::Module, name: &str, targets: Targets) { - let params = match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) { + let root = env!("CARGO_MANIFEST_DIR"); + let params = match fs::read_to_string(format!("{}/{}/{}.param.ron", root, DIR_IN, name)) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), }; @@ -45,41 +46,39 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { .validate(module) .unwrap(); + let dest = PathBuf::from(root).join(DIR_OUT).join(name); + #[cfg(feature = "serialize")] { if targets.contains(Targets::IR) { let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); - let output = ron::ser::to_string_pretty(module, config).unwrap(); - with_snapshot_settings(|| { - insta::assert_snapshot!(format!("{}.ron", name), output); - }); + let string = ron::ser::to_string_pretty(module, config).unwrap(); + fs::write(dest.with_extension("ron"), string).unwrap(); } if targets.contains(Targets::ANALYSIS) { let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); - let output = ron::ser::to_string_pretty(&info, config).unwrap(); - with_snapshot_settings(|| { - insta::assert_snapshot!(format!("{}.info.ron", name), output); - }); + let string = ron::ser::to_string_pretty(&info, config).unwrap(); + fs::write(dest.with_extension("info.ron"), string).unwrap(); } } #[cfg(feature = "spv-out")] { if targets.contains(Targets::SPIRV) { - check_output_spv(module, &info, name, ¶ms); + check_output_spv(module, &info, &dest, ¶ms); } } #[cfg(feature = "msl-out")] { if targets.contains(Targets::METAL) { - check_output_msl(module, &info, name, ¶ms); + check_output_msl(module, &info, &dest, ¶ms); } } #[cfg(feature = "glsl-out")] { if targets.contains(Targets::GLSL) { for ep in module.entry_points.iter() { - check_output_glsl(module, &info, name, ep.stage, &ep.name); + check_output_glsl(module, &info, &dest, ep.stage, &ep.name); } } } @@ -87,15 +86,13 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { { if targets.contains(Targets::DOT) { let string = naga::back::dot::write(module, Some(&info)).unwrap(); - with_snapshot_settings(|| { - insta::assert_snapshot!(format!("{}.dot", name), string); - }); + fs::write(dest.with_extension("dot"), string).unwrap(); } } #[cfg(feature = "hlsl-out")] { if targets.contains(Targets::HLSL) { - check_output_hlsl(module, name); + check_output_hlsl(module, &dest); } } } @@ -104,7 +101,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { fn check_output_spv( module: &naga::Module, info: &naga::valid::ModuleInfo, - name: &str, + destination: &PathBuf, params: &Parameters, ) { use naga::back::spv; @@ -128,16 +125,15 @@ fn check_output_spv( let dis = rspirv::dr::load_words(spv) .expect("Produced invalid SPIR-V") .disassemble(); - with_snapshot_settings(|| { - insta::assert_snapshot!(format!("{}.spvasm", name), dis); - }); + + fs::write(destination.with_extension("spvasm"), dis).unwrap(); } #[cfg(feature = "msl-out")] fn check_output_msl( module: &naga::Module, info: &naga::valid::ModuleInfo, - name: &str, + destination: &PathBuf, params: &Parameters, ) { use naga::back::msl; @@ -148,7 +144,7 @@ fn check_output_msl( let options = ¶ms.msl; #[cfg(not(feature = "deserialize"))] let options = if params.msl_custom { - println!("Skipping {}", name); + println!("Skipping {}", destination); return; } else { &default_options @@ -158,18 +154,16 @@ fn check_output_msl( allow_point_size: true, }; - let (msl, _) = msl::write_string(module, info, options, &pipeline_options).unwrap(); + let (string, _) = msl::write_string(module, info, options, &pipeline_options).unwrap(); - with_snapshot_settings(|| { - insta::assert_snapshot!(format!("{}.msl", name), msl); - }); + fs::write(destination.with_extension("msl"), string).unwrap(); } #[cfg(feature = "glsl-out")] fn check_output_glsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - name: &str, + destination: &PathBuf, stage: naga::ShaderStage, ep_name: &str, ) { @@ -187,25 +181,24 @@ fn check_output_glsl( let string = String::from_utf8(buffer).unwrap(); - with_snapshot_settings(|| { - insta::assert_snapshot!(format!("{}-{:?}.glsl", name, stage), string); - }); + let ext = format!("{:?}.glsl", stage); + fs::write(destination.with_extension(&ext), string).unwrap(); } #[cfg(feature = "hlsl-out")] -fn check_output_hlsl(module: &naga::Module, name: &str) { +fn check_output_hlsl(module: &naga::Module, destination: &PathBuf) { use naga::back::hlsl; - let hlsl = hlsl::write_string(module).unwrap(); - with_snapshot_settings(|| { - insta::assert_snapshot!(format!("{}.hlsl", name), hlsl); - }); + let string = hlsl::write_string(module).unwrap(); + + fs::write(destination.with_extension("hlsl"), string).unwrap(); } #[cfg(feature = "wgsl-in")] fn convert_wgsl(name: &str, targets: Targets) { + let root = env!("CARGO_MANIFEST_DIR"); let module = naga::front::wgsl::parse_str( - &std::fs::read_to_string(format!("tests/in/{}{}", name, ".wgsl")) + &fs::read_to_string(format!("{}/{}/{}.wgsl", root, DIR_IN, name)) .expect("Couldn't find wgsl file"), ) .unwrap(); @@ -272,8 +265,9 @@ fn convert_wgsl_texture_array() { #[cfg(feature = "spv-in")] fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { + let root = env!("CARGO_MANIFEST_DIR"); let module = naga::front::spv::parse_u8_slice( - &std::fs::read(format!("tests/in/{}{}", name, ".spv")).expect("Couldn't find spv file"), + &fs::read(format!("{}/{}/{}.spv", root, DIR_IN, name)).expect("Couldn't find spv file"), &naga::front::spv::Options { adjust_coordinate_space, flow_graph_dump_prefix: None, @@ -304,8 +298,9 @@ fn convert_glsl( entry_points: naga::FastHashMap, _targets: Targets, ) { + let root = env!("CARGO_MANIFEST_DIR"); let _module = naga::front::glsl::parse_str( - &std::fs::read_to_string(format!("tests/in/{}{}", name, ".glsl")) + &fs::read_to_string(format!("{}/{}/{}.glsl", root, DIR_IN, name)) .expect("Couldn't find glsl file"), &naga::front::glsl::Options { entry_points, From 6701e2bf9663f4de21f7211dbeb3df588eb707c1 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 14 Apr 2021 11:58:52 -0700 Subject: [PATCH 0699/2212] Avoid non-exhaustive matches on Expression. Non-exhaustive matches on `Expression` make it harder to review changes that add new enum variants, because the compiler can't tell you that you've missed a case. Although I believe Clippy is able to do so, I don't think we should make a blanket rule of forbidding wildcard match arms against `Expression`. There are a few matches that are only concerned with a handful of variants, or a single variant. For example, variant, naga::front::spv::Parser::next_block is only concerned with whether an expression is a constant or not. In principle, these sites should also be checked when adding a new variant, but it seems too burdensome to require them to list all the `Expression` variants they don't care about. The principle should be applied only to matches that are already handling most variants. At the moment, there is only one such match on `Expression` in the code base, and it's only missing a few variants, so this is quick to fix. --- src/back/spv/writer.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 1a6e7a611..129529f3f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1993,8 +1993,10 @@ impl Writer { }); id } - ref other => { - log::error!("unimplemented {:?}", other); + crate::Expression::ImageQuery { .. } | + crate::Expression::Relational { .. } | + crate::Expression::ArrayLength(_) => { + log::error!("unimplemented {:?}", ir_function.expressions[expr_handle]); return Err(Error::FeatureNotImplemented("expression")); } }; From d3b39d9e587218ff451fbdc754dd33d6d65d3c18 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 14 Apr 2021 01:03:25 -0400 Subject: [PATCH 0700/2212] Splat expression in the IR --- src/back/dot/mod.rs | 4 ++++ src/back/glsl/mod.rs | 4 ++++ src/back/msl/writer.rs | 3 +++ src/front/glsl/constants.rs | 24 ++++++++++++++++++++++++ src/lib.rs | 5 +++++ src/proc/typifier.rs | 11 +++++++++++ src/valid/analyzer.rs | 4 ++++ src/valid/expression.rs | 9 +++++++++ 8 files changed, 64 insertions(+) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 8296e0ba2..d1df17517 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -183,6 +183,10 @@ fn write_fun( (Cow::Owned(format!("AccessIndex[{}]", index)), 1) } E::Constant(_) => (Cow::Borrowed("Constant"), 2), + E::Splat { size, value } => { + edges.insert("value", value); + (Cow::Owned(format!("Splat{:?}", size)), 3) + } E::Compose { ref components, .. } => { payload = Some(Payload::Arguments(components)); (Cow::Borrowed("Compose"), 3) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 3674a2076..fb686d5b0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1477,6 +1477,10 @@ impl<'a, W: Write> Writer<'a, W> { Expression::Constant(constant) => { self.write_constant(&self.module.constants[constant])? } + // `Splat` is just writing `value` + Expression::Splat { size: _, value } => { + self.write_expr(value, ctx)?; + } // `Compose` is pretty simple we just write `type(components)` where `components` is a // comma separated list of expressions Expression::Compose { ty, ref components } => { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index da43c71ee..086f23768 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -608,6 +608,9 @@ impl Writer { }; write!(self.out, "{}", coco)?; } + crate::Expression::Splat { size: _, value } => { + self.put_expression(value, context, is_scoped)?; + } crate::Expression::Compose { ty, ref components } => { let inner = &context.module.types[ty].inner; match *inner { diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index c68d2b5f7..372ff1704 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -49,6 +49,8 @@ pub enum ConstantSolvingError { InvalidUnaryOpArg, #[error("Cannot apply the binary op to the arguments")] InvalidBinaryOpArgs, + #[error("Splat type is not registered")] + SplatType, } impl<'a> ConstantSolver<'a> { @@ -64,6 +66,28 @@ impl<'a> ConstantSolver<'a> { self.access(base, self.constant_index(index)?) } + Expression::Splat { + size, + value: splat_value, + } => { + let tgt = self.solve(splat_value)?; + let ty = match self.constants[tgt].inner { + ConstantInner::Scalar { ref value, width } => { + let kind = value.scalar_kind(); + self.types + .fetch_if(|t| t.inner == crate::TypeInner::Vector { size, kind, width }) + } + ConstantInner::Composite { .. } => None, + }; + Ok(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: ty.ok_or(ConstantSolvingError::SplatType)?, + components: vec![tgt; size as usize], + }, + })) + } Expression::Compose { ty, ref components } => { let components = components .iter() diff --git a/src/lib.rs b/src/lib.rs index fa12613fb..151591dc4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -683,6 +683,11 @@ pub enum Expression { }, /// Constant value. Constant(Handle), + /// Splat scalar into a vector. + Splat { + size: VectorSize, + value: Handle, + }, /// Composite expression. Compose { ty: Handle, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 50455defc..ce62a5b21 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -79,6 +79,8 @@ pub enum ResolveError { ty: Handle, indexed: bool, }, + #[error("Invalid scalar {0:?}")] + InvalidScalar(Handle), #[error("Invalid pointer {0:?}")] InvalidPointer(Handle), #[error("Invalid image {0:?}")] @@ -265,6 +267,15 @@ impl<'a> ResolveContext<'a> { } crate::ConstantInner::Composite { ty, components: _ } => TypeResolution::Handle(ty), }, + crate::Expression::Splat { size, value } => match *past(value).inner_with(types) { + Ti::Scalar { kind, width } => { + TypeResolution::Value(Ti::Vector { size, kind, width }) + } + ref other => { + log::error!("Scalar type {:?}", other); + return Err(ResolveError::InvalidScalar(value)); + } + }, crate::Expression::Compose { ty, .. } => TypeResolution::Handle(ty), crate::Expression::FunctionArgument(index) => { TypeResolution::Handle(self.arguments[index as usize].ty) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 94d7fecc9..52e00818f 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -318,6 +318,10 @@ impl FunctionInfo { }, // always uniform E::Constant(_) => Uniformity::new(), + E::Splat { size: _, value } => Uniformity { + non_uniform_result: self.add_ref(value), + requirements: UniformityRequirements::empty(), + }, E::Compose { ref components, .. } => { let non_uniform_result = components .iter() diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 9df4daae1..0ab075af1 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -31,6 +31,8 @@ pub enum ExpressionError { InvalidPointerType(Handle), #[error("Array length of {0:?} can't be done")] InvalidArrayType(Handle), + #[error("Splatting {0:?} can't be done")] + InvalidSplatType(Handle), #[error("Compose type {0:?} doesn't exist")] ComposeTypeDoesntExist(Handle), #[error("Composing of type {0:?} can't be done")] @@ -197,6 +199,13 @@ impl super::Validator { .ok_or(ExpressionError::ConstantDoesntExist(handle))?; ShaderStages::all() } + E::Splat { size: _, value } => match *resolver.resolve(value)? { + Ti::Scalar { .. } => ShaderStages::all(), + ref other => { + log::error!("Splat scalar type {:?}", other); + return Err(ExpressionError::InvalidSplatType(value)); + } + }, E::Compose { ref components, ty } => { match module .types From c8d26a1f474f60fcc0b57d1212f6ccf20c251a34 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 14 Apr 2021 01:23:38 -0400 Subject: [PATCH 0701/2212] Splat support for WGSL and SPV in/out, updated snapshots --- src/back/spv/writer.rs | 57 +++++---- src/front/spv/mod.rs | 14 ++- src/front/wgsl/mod.rs | 54 +++++++-- tests/in/boids.wgsl | 4 +- tests/in/shadow.wgsl | 5 +- tests/out/boids.msl | 4 +- tests/out/boids.spvasm | 32 ++--- tests/out/shadow.Fragment.glsl | 3 +- tests/out/shadow.info.ron | 8 +- tests/out/shadow.msl | 3 +- tests/out/shadow.ron | 9 +- tests/out/shadow.spvasm | 213 +++++++++++++++++---------------- 12 files changed, 228 insertions(+), 178 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 129529f3f..094bb07ae 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1204,21 +1204,6 @@ impl Writer { } } - fn write_composite_construct( - &mut self, - base_type_id: Word, - constituent_ids: &[Word], - block: &mut Block, - ) -> Word { - let id = self.id_gen.next(); - block.body.push(Instruction::composite_construct( - base_type_id, - id, - constituent_ids, - )); - id - } - fn write_texture_coordinates( &mut self, ir_module: &crate::Module, @@ -1290,11 +1275,13 @@ impl Writer { }), )?; - self.write_composite_construct( + let id = self.id_gen.next(); + block.body.push(Instruction::composite_construct( extended_coordinate_type_id, + id, &constituent_ids[..size as usize], - block, - ) + )); + id } else { coordinate_id }) @@ -1384,17 +1371,36 @@ impl Writer { } crate::Expression::GlobalVariable(handle) => self.global_variables[handle.index()].id, crate::Expression::Constant(handle) => self.constant_ids[handle.index()], + crate::Expression::Splat { size, value } => { + let value_id = self.cached[value]; + self.temp_chain.clear(); + self.temp_chain.resize(size as usize, value_id); + + let id = self.id_gen.next(); + block.body.push(Instruction::composite_construct( + result_type_id, + id, + &self.temp_chain, + )); + id + } crate::Expression::Compose { ty: _, ref components, } => { - //TODO: avoid allocation - let mut constituent_ids = Vec::with_capacity(components.len()); + self.temp_chain.clear(); for &component in components { let component_id = self.cached[component]; - constituent_ids.push(component_id); + self.temp_chain.push(component_id); } - self.write_composite_construct(result_type_id, &constituent_ids, block) + + let id = self.id_gen.next(); + block.body.push(Instruction::composite_construct( + result_type_id, + id, + &self.temp_chain, + )); + id } crate::Expression::Unary { op, expr } => { let id = self.id_gen.next(); @@ -2449,12 +2455,11 @@ impl Writer { result, } => { let id = self.id_gen.next(); - //TODO: avoid heap allocation - let mut argument_ids = vec![]; + self.temp_chain.clear(); for &argument in arguments { let arg_id = self.cached[argument]; - argument_ids.push(arg_id); + self.temp_chain.push(arg_id); } let type_id = match result { @@ -2475,7 +2480,7 @@ impl Writer { type_id, id, self.lookup_function[&local_function], - argument_ids.as_slice(), + &self.temp_chain, )); } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 6a2fdd18a..d6cedea18 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1184,9 +1184,17 @@ impl> Parser { let lexp = self.lookup_expression.lookup(comp_id)?; components.push(lexp.handle); } - let expr = crate::Expression::Compose { - ty: self.lookup_type.lookup(result_type_id)?.handle, - components, + let ty = self.lookup_type.lookup(result_type_id)?.handle; + let first = components[0]; + let expr = match type_arena[ty].inner { + // this is an optimization to detect the splat + crate::TypeInner::Vector { size, .. } + if components.len() == size as usize + && components[1..].iter().all(|&c| c == first) => + { + crate::Expression::Splat { size, value: first } + } + _ => crate::Expression::Compose { ty, components }, }; self.lookup_expression.insert( id, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5f791a37a..dfde4f273 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -328,12 +328,50 @@ impl<'a> ExpressionContext<'a, '_, '_> { let mut left = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); - let expression = crate::Expression::Binary { - op, - left, - right: parser(lexer, self.reborrow())?, - }; - left = self.expressions.append(expression); + let right = parser(lexer, self.reborrow())?; + left = self + .expressions + .append(crate::Expression::Binary { op, left, right }); + } + Ok(left) + } + + fn parse_binary_splat_op( + &mut self, + lexer: &mut Lexer<'a>, + classifier: impl Fn(Token<'a>) -> Option, + mut parser: impl FnMut( + &mut Lexer<'a>, + ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>>, + ) -> Result, Error<'a>> { + let mut left = parser(lexer, self.reborrow())?; + while let Some(op) = classifier(lexer.peek().0) { + let _ = lexer.next(); + let mut right = parser(lexer, self.reborrow())?; + // insert splats, if needed by the non-'*' operations + if op != crate::BinaryOperator::Multiply { + let left_size = match *self.resolve_type(left)? { + crate::TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + match (left_size, self.resolve_type(right)?) { + (Some(size), &crate::TypeInner::Scalar { .. }) => { + right = self + .expressions + .append(crate::Expression::Splat { size, value: right }); + } + (None, &crate::TypeInner::Vector { size, .. }) => { + left = self + .expressions + .append(crate::Expression::Splat { size, value: left }); + } + _ => {} + } + } + left = self + .expressions + .append(crate::Expression::Binary { op, left, right }); } Ok(left) } @@ -1354,7 +1392,7 @@ impl Parser { }, // additive_expression |lexer, mut context| { - context.parse_binary_op( + context.parse_binary_splat_op( lexer, |token| match token { Token::Operation('+') => Some(crate::BinaryOperator::Add), @@ -1365,7 +1403,7 @@ impl Parser { }, // multiplicative_expression |lexer, mut context| { - context.parse_binary_op( + context.parse_binary_splat_op( lexer, |token| match token { Token::Operation('*') => { diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 3db45e1cb..dc5bd7ea3 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -73,10 +73,10 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id : vec3) { } } if (cMassCount > 0) { - cMass = cMass * (1.0 / f32(cMassCount)) - vPos; + cMass = cMass / f32(cMassCount) - vPos; } if (cVelCount > 0) { - cVel = cVel * (1.0 / f32(cVelCount)); + cVel = cVel / f32(cVelCount); } vVel = vVel + (cMass * params.rule1Scale) + diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 16d2e79d0..9cd5253bc 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -29,9 +29,8 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { return 1.0; } let flip_correction = vec2(0.5, -0.5); - let proj_correction = 1.0 / homogeneous_coords.w; - let light_local = homogeneous_coords.xy * flip_correction * proj_correction + vec2(0.5, 0.5); - return textureSampleCompare(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z * proj_correction); + let light_local = homogeneous_coords.xy * flip_correction / homogeneous_coords.w + vec2(0.5, 0.5); + return textureSampleCompare(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z / homogeneous_coords.w); } let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); diff --git a/tests/out/boids.msl b/tests/out/boids.msl index 24e7d2ca0..f8aa78780 100644 --- a/tests/out/boids.msl +++ b/tests/out/boids.msl @@ -73,10 +73,10 @@ kernel void main1( } } if (cMassCount > 0) { - cMass = (cMass * (1.0 / static_cast(cMassCount))) - vPos; + cMass = (cMass / static_cast(cMassCount)) - vPos; } if (cVelCount > 0) { - cVel = cVel * (1.0 / static_cast(cVelCount)); + cVel = cVel / static_cast(cVelCount); } vVel = ((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale); vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm index 7df829a38..3f28ef288 100644 --- a/tests/out/boids.spvasm +++ b/tests/out/boids.spvasm @@ -70,9 +70,9 @@ OpDecorate %40 BuiltIn GlobalInvocationId %9 = OpConstant %4 0 %10 = OpConstant %8 1 %11 = OpConstant %4 1 -%12 = OpConstant %6 1.0 -%13 = OpConstant %6 0.1 -%14 = OpConstant %6 -1.0 +%12 = OpConstant %6 0.1 +%13 = OpConstant %6 -1.0 +%14 = OpConstant %6 1.0 %15 = OpTypeVector %6 2 %16 = OpTypeStruct %15 %15 %17 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 @@ -230,8 +230,8 @@ OpBranchConditional %124 %126 %125 %127 = OpLoad %15 %29 %128 = OpLoad %8 %32 %129 = OpConvertSToF %6 %128 -%130 = OpFDiv %6 %12 %129 -%131 = OpVectorTimesScalar %15 %127 %130 +%130 = OpCompositeConstruct %15 %129 %129 +%131 = OpFDiv %15 %127 %130 %132 = OpLoad %15 %26 %133 = OpFSub %15 %131 %132 OpStore %29 %133 @@ -245,8 +245,8 @@ OpBranchConditional %135 %137 %136 %138 = OpLoad %15 %30 %139 = OpLoad %8 %34 %140 = OpConvertSToF %6 %139 -%141 = OpFDiv %6 %12 %140 -%142 = OpVectorTimesScalar %15 %138 %141 +%141 = OpCompositeConstruct %15 %140 %140 +%142 = OpFDiv %15 %138 %141 OpStore %30 %142 OpBranch %136 %136 = OpLabel @@ -271,7 +271,7 @@ OpStore %28 %161 %163 = OpExtInst %15 %1 Normalize %162 %164 = OpLoad %15 %28 %165 = OpExtInst %6 %1 Length %164 -%166 = OpExtInst %6 %1 FClamp %165 %5 %13 +%166 = OpExtInst %6 %1 FClamp %165 %5 %12 %167 = OpVectorTimesScalar %15 %163 %166 OpStore %28 %167 %168 = OpLoad %15 %26 @@ -283,42 +283,42 @@ OpStore %28 %167 OpStore %26 %173 %174 = OpLoad %15 %26 %175 = OpCompositeExtract %6 %174 0 -%176 = OpFOrdLessThan %47 %175 %14 +%176 = OpFOrdLessThan %47 %175 %13 OpSelectionMerge %177 None OpBranchConditional %176 %178 %177 %178 = OpLabel %180 = OpAccessChain %179 %26 %7 -OpStore %180 %12 +OpStore %180 %14 OpBranch %177 %177 = OpLabel %181 = OpLoad %15 %26 %182 = OpCompositeExtract %6 %181 0 -%183 = OpFOrdGreaterThan %47 %182 %12 +%183 = OpFOrdGreaterThan %47 %182 %14 OpSelectionMerge %184 None OpBranchConditional %183 %185 %184 %185 = OpLabel %186 = OpAccessChain %179 %26 %7 -OpStore %186 %14 +OpStore %186 %13 OpBranch %184 %184 = OpLabel %187 = OpLoad %15 %26 %188 = OpCompositeExtract %6 %187 1 -%189 = OpFOrdLessThan %47 %188 %14 +%189 = OpFOrdLessThan %47 %188 %13 OpSelectionMerge %190 None OpBranchConditional %189 %191 %190 %191 = OpLabel %192 = OpAccessChain %179 %26 %10 -OpStore %192 %12 +OpStore %192 %14 OpBranch %190 %190 = OpLabel %193 = OpLoad %15 %26 %194 = OpCompositeExtract %6 %193 1 -%195 = OpFOrdGreaterThan %47 %194 %12 +%195 = OpFOrdGreaterThan %47 %194 %14 OpSelectionMerge %196 None OpBranchConditional %195 %197 %196 %197 = OpLabel %198 = OpAccessChain %179 %26 %10 -OpStore %198 %14 +OpStore %198 %13 OpBranch %196 %196 = OpLabel %199 = OpLoad %15 %26 diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index 6178ae100..25087bcff 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -26,8 +26,7 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { if((homogeneous_coords[3] <= 0.0)) { return 1.0; } - float _expr15 = (1.0 / homogeneous_coords[3]); - float _expr28 = textureGrad(_group_0_binding_2, vec4((((vec2(homogeneous_coords[0], homogeneous_coords[1]) * vec2(0.5, -0.5)) * _expr15) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] * _expr15)), vec2(0, 0), vec2(0,0)); + float _expr28 = textureGrad(_group_0_binding_2, vec4((((vec2(homogeneous_coords[0], homogeneous_coords[1]) * vec2(0.5, -0.5)) / homogeneous_coords[3]) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] / homogeneous_coords[3])), vec2(0, 0), vec2(0,0)); return _expr28; } diff --git a/tests/out/shadow.info.ron b/tests/out/shadow.info.ron index 661a8655b..6e11adbc9 100644 --- a/tests/out/shadow.info.ron +++ b/tests/out/shadow.info.ron @@ -213,7 +213,7 @@ bits: 0, ), ), - ref_count: 3, + ref_count: 2, assignable_global: None, ty: Value(Scalar( kind: Float, @@ -838,7 +838,11 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), ), ( uniformity: ( diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index 2cb78ff8d..47ef39e1c 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -25,8 +25,7 @@ float fetch_shadow( if (homogeneous_coords.w <= 0.0) { return 1.0; } - float _e15 = 1.0 / homogeneous_coords.w; - float _e28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) * _e15) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z * _e15); + float _e28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) / homogeneous_coords.w) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); return _e28; } diff --git a/tests/out/shadow.ron b/tests/out/shadow.ron index 4d1e38a3b..8f603ad07 100644 --- a/tests/out/shadow.ron +++ b/tests/out/shadow.ron @@ -969,12 +969,9 @@ left: 55, right: 57, ), - Compose( - ty: 9, - components: [ - 13, - 13, - ], + Splat( + size: Bi, + value: 13, ), Binary( op: Add, diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm index 1f6f80039..8189e93ee 100644 --- a/tests/out/shadow.spvasm +++ b/tests/out/shadow.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 136 +; Bound: 137 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %81 "fs_main" %73 %76 %79 -OpExecutionMode %81 OriginUpperLeft +OpEntryPoint Fragment %82 "fs_main" %74 %77 %80 +OpExecutionMode %82 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_max_lights" OpName %14 "Globals" @@ -24,12 +24,12 @@ OpName %27 "s_lights" OpName %29 "t_shadow" OpName %31 "sampler_shadow" OpName %36 "fetch_shadow" -OpName %68 "color" -OpName %70 "i" -OpName %73 "raw_normal" -OpName %76 "position" -OpName %81 "fs_main" -OpName %81 "fs_main" +OpName %69 "color" +OpName %71 "i" +OpName %74 "raw_normal" +OpName %77 "position" +OpName %82 "fs_main" +OpName %82 "fs_main" OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %17 0 Offset 0 @@ -49,9 +49,9 @@ OpDecorate %29 DescriptorSet 0 OpDecorate %29 Binding 2 OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 3 -OpDecorate %73 Location 0 -OpDecorate %76 Location 1 -OpDecorate %79 Location 0 +OpDecorate %74 Location 0 +OpDecorate %77 Location 1 +OpDecorate %80 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 @@ -86,21 +86,21 @@ OpDecorate %79 Location 0 %37 = OpTypeFunction %4 %10 %16 %42 = OpTypeBool %56 = OpTypeInt 32 1 -%60 = OpTypeSampledImage %20 -%67 = OpConstant %4 0.0 -%69 = OpTypePointer Function %23 -%71 = OpTypePointer Function %10 -%74 = OpTypePointer Input %23 -%73 = OpVariable %74 Input -%77 = OpTypePointer Input %16 -%76 = OpVariable %77 Input -%80 = OpTypePointer Output %16 -%79 = OpVariable %80 Output -%82 = OpTypeFunction %2 -%92 = OpTypePointer Uniform %13 -%93 = OpConstant %56 0 -%101 = OpTypePointer StorageBuffer %18 -%103 = OpTypePointer StorageBuffer %17 +%61 = OpTypeSampledImage %20 +%68 = OpConstant %4 0.0 +%70 = OpTypePointer Function %23 +%72 = OpTypePointer Function %10 +%75 = OpTypePointer Input %23 +%74 = OpVariable %75 Input +%78 = OpTypePointer Input %16 +%77 = OpVariable %78 Input +%81 = OpTypePointer Output %16 +%80 = OpVariable %81 Output +%83 = OpTypeFunction %2 +%93 = OpTypePointer Uniform %13 +%94 = OpConstant %56 0 +%102 = OpTypePointer StorageBuffer %18 +%104 = OpTypePointer StorageBuffer %17 %36 = OpFunction %4 None %37 %34 = OpFunctionParameter %10 %35 = OpFunctionParameter %16 @@ -117,92 +117,93 @@ OpBranchConditional %43 %45 %44 OpReturnValue %5 %44 = OpLabel %46 = OpCompositeConstruct %22 %6 %7 -%47 = OpCompositeExtract %4 %35 3 -%48 = OpFDiv %4 %5 %47 -%49 = OpCompositeExtract %4 %35 0 -%50 = OpCompositeExtract %4 %35 1 -%51 = OpCompositeConstruct %22 %49 %50 -%52 = OpFMul %22 %51 %46 -%53 = OpVectorTimesScalar %22 %52 %48 +%47 = OpCompositeExtract %4 %35 0 +%48 = OpCompositeExtract %4 %35 1 +%49 = OpCompositeConstruct %22 %47 %48 +%50 = OpFMul %22 %49 %46 +%51 = OpCompositeExtract %4 %35 3 +%52 = OpCompositeConstruct %22 %51 %51 +%53 = OpFDiv %22 %50 %52 %54 = OpCompositeConstruct %22 %6 %6 %55 = OpFAdd %22 %53 %54 %57 = OpBitcast %56 %34 %58 = OpCompositeExtract %4 %35 2 -%59 = OpFMul %4 %58 %48 -%61 = OpCompositeExtract %4 %55 0 -%62 = OpCompositeExtract %4 %55 1 -%63 = OpConvertUToF %4 %57 -%64 = OpCompositeConstruct %23 %61 %62 %63 -%65 = OpSampledImage %60 %38 %39 -%66 = OpImageSampleDrefExplicitLod %4 %65 %64 %59 Lod %67 -OpReturnValue %66 +%59 = OpCompositeExtract %4 %35 3 +%60 = OpFDiv %4 %58 %59 +%62 = OpCompositeExtract %4 %55 0 +%63 = OpCompositeExtract %4 %55 1 +%64 = OpConvertUToF %4 %57 +%65 = OpCompositeConstruct %23 %62 %63 %64 +%66 = OpSampledImage %61 %38 %39 +%67 = OpImageSampleDrefExplicitLod %4 %66 %65 %60 Lod %68 +OpReturnValue %67 OpFunctionEnd -%81 = OpFunction %2 None %82 -%72 = OpLabel -%68 = OpVariable %69 Function %24 -%70 = OpVariable %71 Function %11 -%75 = OpLoad %23 %73 -%78 = OpLoad %16 %76 -%83 = OpLoad %20 %29 -%84 = OpLoad %21 %31 -OpBranch %85 -%85 = OpLabel -%86 = OpExtInst %23 %1 Normalize %75 -OpBranch %87 -%87 = OpLabel -OpLoopMerge %88 %90 None -OpBranch %89 -%89 = OpLabel -%91 = OpLoad %10 %70 -%94 = OpAccessChain %92 %25 %93 -%95 = OpLoad %13 %94 -%96 = OpCompositeExtract %10 %95 0 -%97 = OpExtInst %10 %1 UMin %96 %9 -%98 = OpUGreaterThanEqual %42 %91 %97 -OpSelectionMerge %99 None -OpBranchConditional %98 %100 %99 -%100 = OpLabel +%82 = OpFunction %2 None %83 +%73 = OpLabel +%69 = OpVariable %70 Function %24 +%71 = OpVariable %72 Function %11 +%76 = OpLoad %23 %74 +%79 = OpLoad %16 %77 +%84 = OpLoad %20 %29 +%85 = OpLoad %21 %31 +OpBranch %86 +%86 = OpLabel +%87 = OpExtInst %23 %1 Normalize %76 OpBranch %88 -%99 = OpLabel -%102 = OpLoad %10 %70 -%104 = OpAccessChain %103 %27 %93 %102 -%105 = OpLoad %17 %104 -%106 = OpLoad %10 %70 -%107 = OpCompositeExtract %15 %105 0 -%108 = OpMatrixTimesVector %16 %107 %78 -%109 = OpFunctionCall %4 %36 %106 %108 -%110 = OpCompositeExtract %16 %105 1 -%111 = OpCompositeExtract %4 %110 0 -%112 = OpCompositeExtract %4 %110 1 -%113 = OpCompositeExtract %4 %110 2 -%114 = OpCompositeConstruct %23 %111 %112 %113 -%115 = OpCompositeExtract %4 %78 0 -%116 = OpCompositeExtract %4 %78 1 -%117 = OpCompositeExtract %4 %78 2 -%118 = OpCompositeConstruct %23 %115 %116 %117 -%119 = OpFSub %23 %114 %118 -%120 = OpExtInst %23 %1 Normalize %119 -%121 = OpDot %4 %86 %120 -%122 = OpExtInst %4 %1 FMax %3 %121 -%123 = OpLoad %23 %68 -%124 = OpFMul %4 %109 %122 -%125 = OpCompositeExtract %16 %105 2 -%126 = OpCompositeExtract %4 %125 0 -%127 = OpCompositeExtract %4 %125 1 -%128 = OpCompositeExtract %4 %125 2 -%129 = OpCompositeConstruct %23 %126 %127 %128 -%130 = OpVectorTimesScalar %23 %129 %124 -%131 = OpFAdd %23 %123 %130 -OpStore %68 %131 +%88 = OpLabel +OpLoopMerge %89 %91 None OpBranch %90 %90 = OpLabel -%132 = OpLoad %10 %70 -%133 = OpIAdd %10 %132 %12 -OpStore %70 %133 -OpBranch %87 -%88 = OpLabel -%134 = OpLoad %23 %68 -%135 = OpCompositeConstruct %16 %134 %5 -OpStore %79 %135 +%92 = OpLoad %10 %71 +%95 = OpAccessChain %93 %25 %94 +%96 = OpLoad %13 %95 +%97 = OpCompositeExtract %10 %96 0 +%98 = OpExtInst %10 %1 UMin %97 %9 +%99 = OpUGreaterThanEqual %42 %92 %98 +OpSelectionMerge %100 None +OpBranchConditional %99 %101 %100 +%101 = OpLabel +OpBranch %89 +%100 = OpLabel +%103 = OpLoad %10 %71 +%105 = OpAccessChain %104 %27 %94 %103 +%106 = OpLoad %17 %105 +%107 = OpLoad %10 %71 +%108 = OpCompositeExtract %15 %106 0 +%109 = OpMatrixTimesVector %16 %108 %79 +%110 = OpFunctionCall %4 %36 %107 %109 +%111 = OpCompositeExtract %16 %106 1 +%112 = OpCompositeExtract %4 %111 0 +%113 = OpCompositeExtract %4 %111 1 +%114 = OpCompositeExtract %4 %111 2 +%115 = OpCompositeConstruct %23 %112 %113 %114 +%116 = OpCompositeExtract %4 %79 0 +%117 = OpCompositeExtract %4 %79 1 +%118 = OpCompositeExtract %4 %79 2 +%119 = OpCompositeConstruct %23 %116 %117 %118 +%120 = OpFSub %23 %115 %119 +%121 = OpExtInst %23 %1 Normalize %120 +%122 = OpDot %4 %87 %121 +%123 = OpExtInst %4 %1 FMax %3 %122 +%124 = OpLoad %23 %69 +%125 = OpFMul %4 %110 %123 +%126 = OpCompositeExtract %16 %106 2 +%127 = OpCompositeExtract %4 %126 0 +%128 = OpCompositeExtract %4 %126 1 +%129 = OpCompositeExtract %4 %126 2 +%130 = OpCompositeConstruct %23 %127 %128 %129 +%131 = OpVectorTimesScalar %23 %130 %125 +%132 = OpFAdd %23 %124 %131 +OpStore %69 %132 +OpBranch %91 +%91 = OpLabel +%133 = OpLoad %10 %71 +%134 = OpIAdd %10 %133 %12 +OpStore %71 %134 +OpBranch %88 +%89 = OpLabel +%135 = OpLoad %23 %69 +%136 = OpCompositeConstruct %16 %135 %5 +OpStore %80 %136 OpReturn OpFunctionEnd \ No newline at end of file From 96f9cb4ce1941e89cc0f6e4adbd9c62dd1ceef65 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 14 Apr 2021 10:05:48 -0400 Subject: [PATCH 0702/2212] [wgsl] Add support for simplified vector construction, add a snapshot test --- src/back/glsl/mod.rs | 6 ++- src/front/wgsl/mod.rs | 9 ++++ tests/in/operators.param.ron | 7 +++ tests/in/operators.wgsl | 6 +++ tests/out/operators.Vertex.glsl | 11 ++++ tests/out/operators.msl | 12 +++++ tests/out/operators.spvasm | 48 +++++++++++++++++ tests/out/shadow.Fragment.glsl | 2 +- tests/snapshots.rs | 96 +++++++++++---------------------- 9 files changed, 131 insertions(+), 66 deletions(-) create mode 100644 tests/in/operators.param.ron create mode 100644 tests/in/operators.wgsl create mode 100644 tests/out/operators.Vertex.glsl create mode 100644 tests/out/operators.msl create mode 100644 tests/out/operators.spvasm diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index fb686d5b0..97b40f546 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1477,9 +1477,13 @@ impl<'a, W: Write> Writer<'a, W> { Expression::Constant(constant) => { self.write_constant(&self.module.constants[constant])? } - // `Splat` is just writing `value` + // `Splat` needs to actually write down a vector, it's not always inferred in GLSL. Expression::Splat { size: _, value } => { + let resolved = ctx.info[expr].ty.inner_with(&self.module.types); + self.write_value_type(resolved)?; + write!(self.out, "(")?; self.write_expr(value, ctx)?; + write!(self.out, ")")? } // `Compose` is pretty simple we just write `type(components)` where `components` is a // comma separated list of expressions diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index dfde4f273..e9f21a291 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1132,6 +1132,13 @@ impl Parser { let expr = if components.is_empty() { let last_component_inner = ctx.resolve_type(last_component)?; match (&inner, last_component_inner) { + ( + &crate::TypeInner::Vector { size, .. }, + &crate::TypeInner::Scalar { .. }, + ) => crate::Expression::Splat { + size, + value: last_component, + }, ( &crate::TypeInner::Scalar { .. }, &crate::TypeInner::Scalar { .. }, @@ -1215,6 +1222,7 @@ impl Parser { crate::TypeInner::Vector { size, kind, width } => { match Composition::make(handle, size, name, name_span, ctx.expressions)? { + //TODO: Swizzling in IR Composition::Multi(size, components) => { let inner = crate::TypeInner::Vector { size, kind, width }; crate::Expression::Compose { @@ -1238,6 +1246,7 @@ impl Parser { name_span, ctx.expressions, )? { + //TODO: is this really supported? Composition::Multi(columns, components) => { let inner = crate::TypeInner::Matrix { columns, diff --git a/tests/in/operators.param.ron b/tests/in/operators.param.ron new file mode 100644 index 000000000..bd5e5acc2 --- /dev/null +++ b/tests/in/operators.param.ron @@ -0,0 +1,7 @@ +( + spv_version: (1, 0), + spv_capabilities: [ Shader ], + spv_debug: false, + spv_adjust_coordinate_space: false, + msl_custom: false, +) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl new file mode 100644 index 000000000..958924c3e --- /dev/null +++ b/tests/in/operators.wgsl @@ -0,0 +1,6 @@ +[[stage(vertex)]] +fn splat() -> [[builtin(position)]] vec4 { + let a = (1.0 + vec2(2.0) - 3.0) / 4.0; + let b = vec4(5) % 2; + return a.xyxy + vec4(b); +} diff --git a/tests/out/operators.Vertex.glsl b/tests/out/operators.Vertex.glsl new file mode 100644 index 000000000..97d6d3c20 --- /dev/null +++ b/tests/out/operators.Vertex.glsl @@ -0,0 +1,11 @@ +#version 310 es + +precision highp float; + + +void main() { + vec2 _expr10 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + gl_Position = (vec4(_expr10[0], _expr10[1], _expr10[0], _expr10[1]) + vec4((ivec4(5) % ivec4(2)))); + return; +} + diff --git a/tests/out/operators.msl b/tests/out/operators.msl new file mode 100644 index 000000000..2b21eab62 --- /dev/null +++ b/tests/out/operators.msl @@ -0,0 +1,12 @@ +#include +#include + + +struct splatOutput { + metal::float4 member [[position]]; +}; +vertex splatOutput splat( +) { + metal::float2 _e10 = ((1.0 + 2.0) - 3.0) / 4.0; + return splatOutput { metal::float4(_e10.x, _e10.y, _e10.x, _e10.y) + static_cast(5 % 2) }; +} diff --git a/tests/out/operators.spvasm b/tests/out/operators.spvasm new file mode 100644 index 000000000..6ee2477c3 --- /dev/null +++ b/tests/out/operators.spvasm @@ -0,0 +1,48 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 37 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %15 "splat" %13 +OpDecorate %13 BuiltIn Position +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.0 +%5 = OpConstant %4 2.0 +%6 = OpConstant %4 3.0 +%7 = OpConstant %4 4.0 +%9 = OpTypeInt 32 1 +%8 = OpConstant %9 5 +%10 = OpConstant %9 2 +%11 = OpTypeVector %4 4 +%14 = OpTypePointer Output %11 +%13 = OpVariable %14 Output +%16 = OpTypeFunction %2 +%18 = OpTypeVector %4 2 +%26 = OpTypeVector %9 4 +%15 = OpFunction %2 None %16 +%12 = OpLabel +OpBranch %17 +%17 = OpLabel +%19 = OpCompositeConstruct %18 %5 %5 +%20 = OpCompositeConstruct %18 %3 %3 +%21 = OpFAdd %18 %20 %19 +%22 = OpCompositeConstruct %18 %6 %6 +%23 = OpFSub %18 %21 %22 +%24 = OpCompositeConstruct %18 %7 %7 +%25 = OpFDiv %18 %23 %24 +%27 = OpCompositeConstruct %26 %8 %8 %8 %8 +%28 = OpCompositeConstruct %26 %10 %10 %10 %10 +%29 = OpSMod %26 %27 %28 +%30 = OpCompositeExtract %4 %25 0 +%31 = OpCompositeExtract %4 %25 1 +%32 = OpCompositeExtract %4 %25 0 +%33 = OpCompositeExtract %4 %25 1 +%34 = OpCompositeConstruct %11 %30 %31 %32 %33 +%35 = OpConvertSToF %11 %29 +%36 = OpFAdd %11 %34 %35 +OpStore %13 %36 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index 25087bcff..be7f69466 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -26,7 +26,7 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { if((homogeneous_coords[3] <= 0.0)) { return 1.0; } - float _expr28 = textureGrad(_group_0_binding_2, vec4((((vec2(homogeneous_coords[0], homogeneous_coords[1]) * vec2(0.5, -0.5)) / homogeneous_coords[3]) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] / homogeneous_coords[3])), vec2(0, 0), vec2(0,0)); + float _expr28 = textureGrad(_group_0_binding_2, vec4((((vec2(homogeneous_coords[0], homogeneous_coords[1]) * vec2(0.5, -0.5)) / vec2(homogeneous_coords[3])) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] / homogeneous_coords[3])), vec2(0, 0), vec2(0,0)); return _expr28; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e54f389c3..1a24b9151 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -195,72 +195,40 @@ fn check_output_hlsl(module: &naga::Module, destination: &PathBuf) { } #[cfg(feature = "wgsl-in")] -fn convert_wgsl(name: &str, targets: Targets) { +#[test] +fn convert_wgsl() { let root = env!("CARGO_MANIFEST_DIR"); - let module = naga::front::wgsl::parse_str( - &fs::read_to_string(format!("{}/{}/{}.wgsl", root, DIR_IN, name)) - .expect("Couldn't find wgsl file"), - ) - .unwrap(); - check_targets(&module, name, targets); -} + let inputs = [ + ( + "empty", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL, + ), + ( + "quad", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::DOT, + ), + ("boids", Targets::SPIRV | Targets::METAL), + ("skybox", Targets::SPIRV | Targets::METAL | Targets::GLSL), + ( + "collatz", + Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS, + ), + ("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL), + //SPIR-V is blocked by https://github.com/gfx-rs/naga/issues/646 + ("image-copy", Targets::METAL), + ("texture-array", Targets::SPIRV | Targets::METAL), + ("operators", Targets::SPIRV | Targets::METAL | Targets::GLSL), + ]; -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_wgsl_quad() { - convert_wgsl( - "quad", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::DOT, - ); -} - -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_wgsl_empty() { - convert_wgsl( - "empty", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL, - ); -} - -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_wgsl_boids() { - convert_wgsl("boids", Targets::SPIRV | Targets::METAL); -} - -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_wgsl_skybox() { - convert_wgsl("skybox", Targets::SPIRV | Targets::METAL | Targets::GLSL); -} - -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_wgsl_collatz() { - convert_wgsl( - "collatz", - Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS, - ); -} - -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_wgsl_shadow() { - convert_wgsl("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL); -} - -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_wgsl_image_copy() { - //SPIR-V is blocked by https://github.com/gfx-rs/naga/issues/646 - convert_wgsl("image-copy", Targets::METAL); -} - -#[cfg(feature = "wgsl-in")] -#[test] -fn convert_wgsl_texture_array() { - convert_wgsl("texture-array", Targets::SPIRV | Targets::METAL); + for &(name, targets) in inputs.iter() { + println!("Processing '{}'", name); + let file = fs::read_to_string(format!("{}/{}/{}.wgsl", root, DIR_IN, name)) + .expect("Couldn't find wgsl file"); + match naga::front::wgsl::parse_str(&file) { + Ok(module) => check_targets(&module, name, targets), + Err(e) => panic!("{}", e), + } + } } #[cfg(feature = "spv-in")] From 2eae37f7e5b89051680b17b4926d497e0bf335ad Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 14 Apr 2021 19:22:40 -0400 Subject: [PATCH 0703/2212] [spv-out] rename temp_chain to temp_list, run a cargo fmt pass --- src/back/spv/writer.rs | 44 ++++++++++++++++++++---------------------- tests/errors.rs | 10 +++++----- 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 094bb07ae..2b467bc3d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -275,7 +275,8 @@ pub struct Writer { global_variables: Vec, cached: CachedExpressions, gl450_ext_inst_id: Word, - temp_chain: Vec, + // Just a temporary list of SPIR-V ids + temp_list: Vec, } impl Writer { @@ -307,7 +308,7 @@ impl Writer { global_variables: Vec::new(), cached: CachedExpressions::default(), gl450_ext_inst_id, - temp_chain: Vec::new(), + temp_list: Vec::new(), }) } @@ -1373,14 +1374,14 @@ impl Writer { crate::Expression::Constant(handle) => self.constant_ids[handle.index()], crate::Expression::Splat { size, value } => { let value_id = self.cached[value]; - self.temp_chain.clear(); - self.temp_chain.resize(size as usize, value_id); + self.temp_list.clear(); + self.temp_list.resize(size as usize, value_id); let id = self.id_gen.next(); block.body.push(Instruction::composite_construct( result_type_id, id, - &self.temp_chain, + &self.temp_list, )); id } @@ -1388,17 +1389,16 @@ impl Writer { ty: _, ref components, } => { - self.temp_chain.clear(); + self.temp_list.clear(); for &component in components { - let component_id = self.cached[component]; - self.temp_chain.push(component_id); + self.temp_list.push(self.cached[component]); } let id = self.id_gen.next(); block.body.push(Instruction::composite_construct( result_type_id, id, - &self.temp_chain, + &self.temp_list, )); id } @@ -1999,9 +1999,9 @@ impl Writer { }); id } - crate::Expression::ImageQuery { .. } | - crate::Expression::Relational { .. } | - crate::Expression::ArrayLength(_) => { + crate::Expression::ImageQuery { .. } + | crate::Expression::Relational { .. } + | crate::Expression::ArrayLength(_) => { log::error!("unimplemented {:?}", ir_function.expressions[expr_handle]); return Err(Error::FeatureNotImplemented("expression")); } @@ -2029,17 +2029,17 @@ impl Writer { }; let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; - self.temp_chain.clear(); + self.temp_list.clear(); let (root_id, class) = loop { expr_handle = match ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { let index_id = self.cached[index]; - self.temp_chain.push(index_id); + self.temp_list.push(index_id); base } crate::Expression::AccessIndex { base, index } => { let const_id = self.get_index_constant(index, &ir_module.types)?; - self.temp_chain.push(const_id); + self.temp_list.push(const_id); base } crate::Expression::GlobalVariable(handle) => { @@ -2054,16 +2054,16 @@ impl Writer { } }; - let id = if self.temp_chain.is_empty() { + let id = if self.temp_list.is_empty() { root_id } else { - self.temp_chain.reverse(); + self.temp_list.reverse(); let id = self.id_gen.next(); block.body.push(Instruction::access_chain( result_type_id, id, root_id, - &self.temp_chain, + &self.temp_list, )); id }; @@ -2455,11 +2455,9 @@ impl Writer { result, } => { let id = self.id_gen.next(); - self.temp_chain.clear(); - + self.temp_list.clear(); for &argument in arguments { - let arg_id = self.cached[argument]; - self.temp_chain.push(arg_id); + self.temp_list.push(self.cached[argument]); } let type_id = match result { @@ -2480,7 +2478,7 @@ impl Writer { type_id, id, self.lookup_function[&local_function], - &self.temp_chain, + &self.temp_list, )); } } diff --git a/tests/errors.rs b/tests/errors.rs index 7567b203b..e9077220d 100644 --- a/tests/errors.rs +++ b/tests/errors.rs @@ -20,7 +20,7 @@ fn check(input: &str, snapshot: &str) { fn function_without_identifier() { check( "fn () {}", -r###"error: expected identifier, found '(' + r###"error: expected identifier, found '(' ┌─ wgsl:1:4 │ 1 │ fn () {} @@ -35,7 +35,7 @@ r###"error: expected identifier, found '(' fn invalid_integer() { check( "fn foo([location(1.)] x: i32) {}", -r###"error: expected identifier, found '[' + r###"error: expected identifier, found '[' ┌─ wgsl:1:8 │ 1 │ fn foo([location(1.)] x: i32) {} @@ -50,7 +50,7 @@ r###"error: expected identifier, found '[' fn invalid_float() { check( "let scale: f32 = 1.1.;", -r###"error: expected floating-point literal, found `1.1.` + r###"error: expected floating-point literal, found `1.1.` ┌─ wgsl:1:18 │ 1 │ let scale: f32 = 1.1.; @@ -65,7 +65,7 @@ r###"error: expected floating-point literal, found `1.1.` fn invalid_scalar_width() { check( "let scale: f32 = 1.1f1000;", -r###"error: invalid width of `1000` for literal + r###"error: invalid width of `1000` for literal ┌─ wgsl:1:18 │ 1 │ let scale: f32 = 1.1f1000; @@ -88,7 +88,7 @@ fn vs_main() { var i: f32 = color.a; } "###, -r###"error: invalid field accessor `a` + r###"error: invalid field accessor `a` ┌─ wgsl:5:24 │ 5 │ var i: f32 = color.a; From ec6ef38dac02399077411e38a3f9b1569a0f0783 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 15 Apr 2021 09:06:21 -0700 Subject: [PATCH 0704/2212] Makefile: Omit misleading slashes. --- Makefile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 2eeec5eb0..cc70da265 100644 --- a/Makefile +++ b/Makefile @@ -28,32 +28,32 @@ clean: validate-spv: $(SNAPSHOTS_OUT)/*.spvasm @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ cat $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ done validate-msl: $(SNAPSHOTS_OUT)/*.msl @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ cat $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ done validate-glsl: $(SNAPSHOTS_OUT)/*.glsl @set -e && for file in $(SNAPSHOTS_OUT)/*.Vertex.glsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)"};\ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ cat $${file} | glslangValidator --stdin -S vert; \ done @set -e && for file in $(SNAPSHOTS_OUT)/*.Fragment.glsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)"};\ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ cat $${file} | glslangValidator --stdin -S frag; \ done @set -e && for file in $(SNAPSHOTS_OUT)/*.Compute.glsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)"};\ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ cat $${file} | glslangValidator --stdin -S comp; \ done validate-dot: $(SNAPSHOTS_OUT)/*.dot @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ cat $${file} | dot -o /dev/null; \ done From 7fda34c4fda408b777364cffcd8047c7f4338b51 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 15 Apr 2021 10:06:57 -0700 Subject: [PATCH 0705/2212] [glsl-out] Add version checks for qualifiers. Use `back::glsl::features::FeaturesManager` to detect which qualifiers the given module actually uses, and check them against the requested GLSL version. The `linear` and `sample` qualifiers for fragment shader inputs are not supported in all versions of GLSL that Naga can generate. --- src/back/glsl/features.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 283c2ac7d..1e6a6ade0 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -1,7 +1,7 @@ use super::{BackendResult, Error, Version, Writer}; use crate::{ - Bytes, ImageClass, ImageDimension, ScalarKind, ShaderStage, StorageClass, StorageFormat, - TypeInner, + Binding, Bytes, Handle, ImageClass, ImageDimension, Interpolation, ScalarKind, ShaderStage, + StorageClass, StorageFormat, Type, TypeInner, }; use std::io::Write; @@ -24,6 +24,10 @@ bitflags::bitflags! { const CONSERVATIVE_DEPTH = 1 << 9; /// Isn't supported in ES const TEXTURE_1D = 1 << 10; + /// Interpolation and auxiliary qualifiers. Perspective, Flat, and + /// Centroid are available in all GLSL versions we support. + const LINEAR_QUALIFIER = 1 << 11; + const SAMPLE_QUALIFIER = 1 << 12; } } @@ -84,6 +88,8 @@ impl FeaturesManager { // 1D textures are supported by all core versions and aren't supported by an es versions // so use 0 that way the check will always be false and can be optimized away check_feature!(TEXTURE_1D, 0); + check_feature!(LINEAR_QUALIFIER, 130); + check_feature!(SAMPLE_QUALIFIER, 400, 320); // Return an error if there are missing features if missing.is_empty() { @@ -183,6 +189,13 @@ impl<'a, W> Writer<'a, W> { } } + for arg in self.entry_point.function.arguments.iter() { + self.varying_required_features(arg.binding.as_ref(), arg.ty); + } + if let Some(ref result) = self.entry_point.function.result { + self.varying_required_features(result.binding.as_ref(), result.ty); + } + if let ShaderStage::Compute = self.options.shader_stage { self.features.request(Features::COMPUTE_SHADER) } @@ -266,4 +279,23 @@ impl<'a, W> Writer<'a, W> { self.features.request(Features::DOUBLE_TYPE); } } + + fn varying_required_features(&mut self, binding: Option<&Binding>, ty: Handle) { + match self.module.types[ty].inner { + crate::TypeInner::Struct { ref members, .. } => { + for member in members { + self.varying_required_features(member.binding.as_ref(), member.ty); + } + } + _ => { + if let Some(&Binding::Location(_, Some(interpolation))) = binding { + match interpolation { + Interpolation::Linear => self.features.request(Features::LINEAR_QUALIFIER), + Interpolation::Sample => self.features.request(Features::SAMPLE_QUALIFIER), + _ => () + }; + } + } + } + } } From 576723960e482c81bb710de7b3604890fe6d0c47 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 15 Apr 2021 12:14:48 -0700 Subject: [PATCH 0706/2212] Permit interpolation qualifiers on both vertex outputs and fragment inputs. --- src/valid/interface.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 17629d1e0..1299b3821 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -210,8 +210,11 @@ impl VaryingContext<'_> { if !self.location_mask.insert(location as usize) { return Err(VaryingError::BindingCollision { location }); } - let needs_interpolation = - self.stage == crate::ShaderStage::Fragment && !self.output; + let needs_interpolation = match self.stage { + crate::ShaderStage::Vertex => self.output, + crate::ShaderStage::Fragment => !self.output, + _ => false, + }; if !needs_interpolation && interpolation.is_some() { return Err(VaryingError::InvalidInterpolation); } From 3f958f618bf2a5f474a180ee64b32124f6d475e6 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 15 Apr 2021 11:53:41 -0700 Subject: [PATCH 0707/2212] [glsl-out] Let snapshot tests request a specific GLSL desktop version. Add a Option to the snapshot `Params` to let snapshots request specific Desktop GLSL versions. The default is GLSL ES 3.10. It would be more general to let the params select any GLSL version, but that would entail making glsl::Version implement Deserialize and all that, which seems like overkill. --- tests/snapshots.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1a24b9151..587bef439 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -33,6 +33,9 @@ struct Parameters { msl: naga::back::msl::Options, #[cfg(all(not(feature = "deserialize"), feature = "msl-out"))] msl_custom: bool, + #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] + #[serde(default)] + glsl_desktop_version: Option } #[allow(dead_code, unused_variables)] @@ -78,7 +81,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { { if targets.contains(Targets::GLSL) { for ep in module.entry_points.iter() { - check_output_glsl(module, &info, &dest, ep.stage, &ep.name); + check_output_glsl(module, &info, &dest, ep.stage, &ep.name, ¶ms); } } } @@ -166,11 +169,15 @@ fn check_output_glsl( destination: &PathBuf, stage: naga::ShaderStage, ep_name: &str, + params: &Parameters, ) { use naga::back::glsl; let options = glsl::Options { - version: glsl::Version::Embedded(310), + version: match params.glsl_desktop_version { + Some(v) => glsl::Version::Desktop(v), + None => glsl::Version::Embedded(310), + }, shader_stage: stage, entry_point: ep_name.to_string(), }; From 2eb3e81e19630410caa10821fcfcaba4f98602ce Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 9 Apr 2021 14:58:14 -0700 Subject: [PATCH 0708/2212] [wgsl-in] Add basic test for `interpolate` attribute. --- src/back/glsl/features.rs | 6 +- tests/in/interpolate.param.ron | 8 ++ tests/in/interpolate.wgsl | 25 ++++ tests/out/interpolate.Fragment.glsl | 21 ++++ tests/out/interpolate.Vertex.glsl | 33 ++++++ tests/out/interpolate.msl | 48 ++++++++ tests/out/interpolate.spvasm | 174 ++++++++++++++++++++++++++++ tests/snapshots.rs | 1 + 8 files changed, 313 insertions(+), 3 deletions(-) create mode 100644 tests/in/interpolate.param.ron create mode 100644 tests/in/interpolate.wgsl create mode 100644 tests/out/interpolate.Fragment.glsl create mode 100644 tests/out/interpolate.Vertex.glsl create mode 100644 tests/out/interpolate.msl create mode 100644 tests/out/interpolate.spvasm diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 1e6a6ade0..e76003f21 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -26,7 +26,7 @@ bitflags::bitflags! { const TEXTURE_1D = 1 << 10; /// Interpolation and auxiliary qualifiers. Perspective, Flat, and /// Centroid are available in all GLSL versions we support. - const LINEAR_QUALIFIER = 1 << 11; + const NOPERSPECTIVE_QUALIFIER = 1 << 11; const SAMPLE_QUALIFIER = 1 << 12; } } @@ -88,7 +88,7 @@ impl FeaturesManager { // 1D textures are supported by all core versions and aren't supported by an es versions // so use 0 that way the check will always be false and can be optimized away check_feature!(TEXTURE_1D, 0); - check_feature!(LINEAR_QUALIFIER, 130); + check_feature!(NOPERSPECTIVE_QUALIFIER, 130); check_feature!(SAMPLE_QUALIFIER, 400, 320); // Return an error if there are missing features @@ -290,7 +290,7 @@ impl<'a, W> Writer<'a, W> { _ => { if let Some(&Binding::Location(_, Some(interpolation))) = binding { match interpolation { - Interpolation::Linear => self.features.request(Features::LINEAR_QUALIFIER), + Interpolation::Linear => self.features.request(Features::NOPERSPECTIVE_QUALIFIER), Interpolation::Sample => self.features.request(Features::SAMPLE_QUALIFIER), _ => () }; diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron new file mode 100644 index 000000000..dfd15dc16 --- /dev/null +++ b/tests/in/interpolate.param.ron @@ -0,0 +1,8 @@ +( + spv_version: (1, 0), + spv_capabilities: [ Shader, SampleRateShading ], + spv_debug: true, + spv_adjust_coordinate_space: true, + msl_custom: false, + glsl_desktop_version: Some(400) +) diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl new file mode 100644 index 000000000..0bdad9692 --- /dev/null +++ b/tests/in/interpolate.wgsl @@ -0,0 +1,25 @@ +struct FragmentInput { + [[builtin(position)]] position: vec4; + [[location(0), interpolate(flat)]] flat : u32; + [[location(1), interpolate(linear)]] linear: f32; + [[location(2), interpolate(centroid)]] centroid: vec2; + [[location(3), interpolate(sample)]] sample: vec3; + [[location(4), interpolate(perspective)]] perspective: vec4; +}; + +[[stage(vertex)]] +fn main() -> FragmentInput { + var out: FragmentInput; + + out.position = vec4(2.0, 4.0, 5.0, 6.0); + out.flat = 8u32; + out.linear = 27.0; + out.centroid = vec2(64.0, 125.0); + out.sample = vec3(216.0, 343.0, 512.0); + out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + + return out; +} + +[[stage(fragment)]] +fn main(val : FragmentInput) { } diff --git a/tests/out/interpolate.Fragment.glsl b/tests/out/interpolate.Fragment.glsl new file mode 100644 index 000000000..6ec1a66ad --- /dev/null +++ b/tests/out/interpolate.Fragment.glsl @@ -0,0 +1,21 @@ +#version 400 core +struct FragmentInput { + vec4 position; + uint flat1; + float linear; + vec2 centroid1; + vec3 sample1; + vec4 perspective; +}; + +flat in uint _vs2fs_location0; +noperspective in float _vs2fs_location1; +centroid in vec2 _vs2fs_location2; +sample in vec3 _vs2fs_location3; +smooth in vec4 _vs2fs_location4; + +void main() { + FragmentInput val = FragmentInput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1, _vs2fs_location2, _vs2fs_location3, _vs2fs_location4); + return; +} + diff --git a/tests/out/interpolate.Vertex.glsl b/tests/out/interpolate.Vertex.glsl new file mode 100644 index 000000000..3f105dccf --- /dev/null +++ b/tests/out/interpolate.Vertex.glsl @@ -0,0 +1,33 @@ +#version 400 core +struct FragmentInput { + vec4 position; + uint flat1; + float linear; + vec2 centroid1; + vec3 sample1; + vec4 perspective; +}; + +out uint _vs2fs_location0; +out float _vs2fs_location1; +out vec2 _vs2fs_location2; +out vec3 _vs2fs_location3; +out vec4 _vs2fs_location4; + +void main() { + FragmentInput out1; + out1.position = vec4(2.0, 4.0, 5.0, 6.0); + out1.flat1 = 8u; + out1.linear = 27.0; + out1.centroid1 = vec2(64.0, 125.0); + out1.sample1 = vec3(216.0, 343.0, 512.0); + out1.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + gl_Position = out1.position; + _vs2fs_location0 = out1.flat1; + _vs2fs_location1 = out1.linear; + _vs2fs_location2 = out1.centroid1; + _vs2fs_location3 = out1.sample1; + _vs2fs_location4 = out1.perspective; + return; +} + diff --git a/tests/out/interpolate.msl b/tests/out/interpolate.msl new file mode 100644 index 000000000..713dc4ef9 --- /dev/null +++ b/tests/out/interpolate.msl @@ -0,0 +1,48 @@ +#include +#include + +struct FragmentInput { + metal::float4 position; + metal::uint flat; + float linear; + metal::float2 centroid; + metal::float3 sample; + metal::float4 perspective; +}; + +struct main1Output { + metal::float4 position [[position]]; + metal::uint flat [[user(loc0)]]; + float linear [[user(loc1)]]; + metal::float2 centroid [[user(loc2)]]; + metal::float3 sample [[user(loc3)]]; + metal::float4 perspective [[user(loc4)]]; +}; +vertex main1Output main1( +) { + FragmentInput out; + out.position = metal::float4(2.0, 4.0, 5.0, 6.0); + out.flat = 8u; + out.linear = 27.0; + out.centroid = metal::float2(64.0, 125.0); + out.sample = metal::float3(216.0, 343.0, 512.0); + out.perspective = metal::float4(729.0, 1000.0, 1331.0, 1728.0); + const auto _tmp = out; + return main1Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.centroid, _tmp.sample, _tmp.perspective }; +} + + +struct main2Input { + metal::uint flat [[user(loc0)]]; + float linear [[user(loc1)]]; + metal::float2 centroid [[user(loc2)]]; + metal::float3 sample [[user(loc3)]]; + metal::float4 perspective [[user(loc4)]]; +}; +fragment void main2( + main2Input varyings1 [[stage_in]] +, metal::float4 position [[position]] +) { + const FragmentInput val = { position, varyings1.flat, varyings1.linear, varyings1.centroid, varyings1.sample, varyings1.perspective }; + return; +} diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm new file mode 100644 index 000000000..063b86f7f --- /dev/null +++ b/tests/out/interpolate.spvasm @@ -0,0 +1,174 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 95 +OpCapability Shader +OpCapability SampleRateShading +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %38 "main" %27 %29 %31 %33 %35 %37 +OpEntryPoint Fragment %93 "main" %76 %79 %82 %85 %88 %91 +OpExecutionMode %93 OriginUpperLeft +OpSource GLSL 450 +OpName %23 "FragmentInput" +OpMemberName %23 0 "position" +OpMemberName %23 1 "flat" +OpMemberName %23 2 "linear" +OpMemberName %23 3 "centroid" +OpMemberName %23 4 "sample" +OpMemberName %23 5 "perspective" +OpName %24 "out" +OpName %27 "position" +OpName %29 "flat" +OpName %31 "linear" +OpName %33 "centroid" +OpName %35 "sample" +OpName %37 "perspective" +OpName %38 "main" +OpName %38 "main" +OpName %76 "position" +OpName %79 "flat" +OpName %82 "linear" +OpName %85 "centroid" +OpName %88 "sample" +OpName %91 "perspective" +OpName %93 "main" +OpName %93 "main" +OpMemberDecorate %23 0 Offset 0 +OpMemberDecorate %23 1 Offset 16 +OpMemberDecorate %23 2 Offset 20 +OpMemberDecorate %23 3 Offset 24 +OpMemberDecorate %23 4 Offset 32 +OpMemberDecorate %23 5 Offset 48 +OpDecorate %27 BuiltIn Position +OpDecorate %29 Location 0 +OpDecorate %29 Flat +OpDecorate %31 Location 1 +OpDecorate %31 NoPerspective +OpDecorate %33 Location 2 +OpDecorate %33 Centroid +OpDecorate %35 Location 3 +OpDecorate %35 Sample +OpDecorate %37 Location 4 +OpDecorate %76 BuiltIn FragCoord +OpDecorate %79 Location 0 +OpDecorate %79 Flat +OpDecorate %82 Location 1 +OpDecorate %82 NoPerspective +OpDecorate %85 Location 2 +OpDecorate %85 Centroid +OpDecorate %88 Location 3 +OpDecorate %88 Sample +OpDecorate %91 Location 4 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 2.0 +%5 = OpConstant %4 4.0 +%6 = OpConstant %4 5.0 +%7 = OpConstant %4 6.0 +%9 = OpTypeInt 32 0 +%8 = OpConstant %9 8 +%10 = OpConstant %4 27.0 +%11 = OpConstant %4 64.0 +%12 = OpConstant %4 125.0 +%13 = OpConstant %4 216.0 +%14 = OpConstant %4 343.0 +%15 = OpConstant %4 512.0 +%16 = OpConstant %4 729.0 +%17 = OpConstant %4 1000.0 +%18 = OpConstant %4 1331.0 +%19 = OpConstant %4 1728.0 +%20 = OpTypeVector %4 4 +%21 = OpTypeVector %4 2 +%22 = OpTypeVector %4 3 +%23 = OpTypeStruct %20 %9 %4 %21 %22 %20 +%25 = OpTypePointer Function %23 +%28 = OpTypePointer Output %20 +%27 = OpVariable %28 Output +%30 = OpTypePointer Output %9 +%29 = OpVariable %30 Output +%32 = OpTypePointer Output %4 +%31 = OpVariable %32 Output +%34 = OpTypePointer Output %21 +%33 = OpVariable %34 Output +%36 = OpTypePointer Output %22 +%35 = OpVariable %36 Output +%37 = OpVariable %28 Output +%39 = OpTypeFunction %2 +%41 = OpTypePointer Function %20 +%43 = OpTypeInt 32 1 +%44 = OpConstant %43 0 +%46 = OpTypePointer Function %9 +%47 = OpConstant %43 1 +%49 = OpTypePointer Function %4 +%50 = OpConstant %43 2 +%52 = OpTypePointer Function %21 +%54 = OpConstant %43 3 +%56 = OpTypePointer Function %22 +%58 = OpConstant %43 4 +%61 = OpConstant %43 5 +%66 = OpTypePointer Output %4 +%77 = OpTypePointer Input %20 +%76 = OpVariable %77 Input +%80 = OpTypePointer Input %9 +%79 = OpVariable %80 Input +%83 = OpTypePointer Input %4 +%82 = OpVariable %83 Input +%86 = OpTypePointer Input %21 +%85 = OpVariable %86 Input +%89 = OpTypePointer Input %22 +%88 = OpVariable %89 Input +%91 = OpVariable %77 Input +%38 = OpFunction %2 None %39 +%26 = OpLabel +%24 = OpVariable %25 Function +OpBranch %40 +%40 = OpLabel +%42 = OpCompositeConstruct %20 %3 %5 %6 %7 +%45 = OpAccessChain %41 %24 %44 +OpStore %45 %42 +%48 = OpAccessChain %46 %24 %47 +OpStore %48 %8 +%51 = OpAccessChain %49 %24 %50 +OpStore %51 %10 +%53 = OpCompositeConstruct %21 %11 %12 +%55 = OpAccessChain %52 %24 %54 +OpStore %55 %53 +%57 = OpCompositeConstruct %22 %13 %14 %15 +%59 = OpAccessChain %56 %24 %58 +OpStore %59 %57 +%60 = OpCompositeConstruct %20 %16 %17 %18 %19 +%62 = OpAccessChain %41 %24 %61 +OpStore %62 %60 +%63 = OpLoad %23 %24 +%64 = OpCompositeExtract %20 %63 0 +OpStore %27 %64 +%65 = OpAccessChain %66 %27 %47 +%67 = OpLoad %4 %65 +%68 = OpFNegate %4 %67 +OpStore %65 %68 +%69 = OpCompositeExtract %9 %63 1 +OpStore %29 %69 +%70 = OpCompositeExtract %4 %63 2 +OpStore %31 %70 +%71 = OpCompositeExtract %21 %63 3 +OpStore %33 %71 +%72 = OpCompositeExtract %22 %63 4 +OpStore %35 %72 +%73 = OpCompositeExtract %20 %63 5 +OpStore %37 %73 +OpReturn +OpFunctionEnd +%93 = OpFunction %2 None %39 +%74 = OpLabel +%78 = OpLoad %20 %76 +%81 = OpLoad %9 %79 +%84 = OpLoad %4 %82 +%87 = OpLoad %21 %85 +%90 = OpLoad %22 %88 +%92 = OpLoad %20 %91 +%75 = OpCompositeConstruct %23 %78 %81 %84 %87 %90 %92 +OpBranch %94 +%94 = OpLabel +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 587bef439..bc5b56614 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -225,6 +225,7 @@ fn convert_wgsl() { ("image-copy", Targets::METAL), ("texture-array", Targets::SPIRV | Targets::METAL), ("operators", Targets::SPIRV | Targets::METAL | Targets::GLSL), + ("interpolate", Targets::SPIRV | Targets::METAL | Targets::GLSL), ]; for &(name, targets) in inputs.iter() { From 285a855e199221878ec3afb894faff1dec2dd8ee Mon Sep 17 00:00:00 2001 From: Ashley Date: Fri, 16 Apr 2021 20:11:26 +0200 Subject: [PATCH 0709/2212] Impl `Hash` for `msl::Options` (#716) * Impl `Hash` for `msl::Options` * Remove ordered float * [msl] derive everything on Options manually * [msl] switch from Arena to Vec for the options * Fix the clippy error by allowing derive_hash_xor_eq * Fix skybox test Co-authored-by: Dzmitry Malyshau --- src/back/msl/mod.rs | 31 ++++++++++++++++--------------- src/back/msl/sampler.rs | 38 +++++++++++++++++++++++++++++++++----- tests/in/skybox.param.ron | 2 +- 3 files changed, 50 insertions(+), 21 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index db1fcedf0..59b5097c6 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -23,11 +23,7 @@ For the result type, if it's a structure, we re-compose it with a temporary valu holding the result. !*/ -use crate::{ - arena::{Arena, Handle}, - valid::ModuleInfo, - FastHashMap, -}; +use crate::{arena::Handle, valid::ModuleInfo}; use std::fmt::{Error as FmtError, Write}; mod keywords; @@ -37,15 +33,18 @@ mod writer; pub use writer::Writer; pub type Slot = u8; +pub type InlineSamplerIndex = u8; -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum BindSamplerTarget { Resource(Slot), - Inline(Handle), + Inline(InlineSamplerIndex), } -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct BindTarget { #[cfg_attr(feature = "deserialize", serde(default))] @@ -67,7 +66,7 @@ pub struct BindSource { pub binding: u32, } -pub type BindingMap = FastHashMap; +pub type BindingMap = std::collections::BTreeMap; #[derive(Clone, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -127,7 +126,8 @@ enum LocationMode { Uniform, } -#[derive(Debug)] +#[derive(Clone, Debug, Hash, PartialEq)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Options { /// (Major, Minor) target version of the Metal Shading Language. @@ -137,7 +137,7 @@ pub struct Options { /// Push constants mapping to Metal. pub push_constants_map: PushConstantsMap, /// Samplers to be inlined into the code. - pub inline_samplers: Arena, + pub inline_samplers: Vec, /// Make it possible to link different stages via SPIRV-Cross. pub spirv_cross_compatibility: bool, /// Don't panic on missing bindings, instead generate invalid MSL. @@ -150,7 +150,7 @@ impl Default for Options { lang_version: (1, 0), binding_map: BindingMap::default(), push_constants_map: PushConstantsMap::default(), - inline_samplers: Arena::new(), + inline_samplers: Vec::new(), spirv_cross_compatibility: false, fake_missing_bindings: true, } @@ -158,7 +158,8 @@ impl Default for Options { } // A subset of options that are meant to be changed per pipeline. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct PipelineOptions { /// Allow `BuiltIn::PointSize` in the vertex shader. @@ -253,9 +254,9 @@ impl ResolvedBinding { fn as_inline_sampler<'a>(&self, options: &'a Options) -> Option<&'a sampler::InlineSampler> { match *self { Self::Resource(BindTarget { - sampler: Some(BindSamplerTarget::Inline(handle)), + sampler: Some(BindSamplerTarget::Inline(index)), .. - }) => Some(&options.inline_samplers[handle]), + }) => Some(&options.inline_samplers[index as usize]), _ => None, } } diff --git a/src/back/msl/sampler.rs b/src/back/msl/sampler.rs index 7d76aac92..c603fac1b 100644 --- a/src/back/msl/sampler.rs +++ b/src/back/msl/sampler.rs @@ -1,8 +1,11 @@ #[cfg(feature = "deserialize")] use serde::Deserialize; +#[cfg(feature = "serialize")] +use serde::Serialize; use std::{num::NonZeroU32, ops::Range}; -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Coord { Normalized, @@ -24,7 +27,8 @@ impl Coord { } } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Address { Repeat, @@ -52,7 +56,8 @@ impl Address { } } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum BorderColor { TransparentBlack, @@ -76,7 +81,8 @@ impl BorderColor { } } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Filter { Nearest, @@ -98,7 +104,8 @@ impl Default for Filter { } } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum CompareFunc { Never, @@ -133,6 +140,7 @@ impl CompareFunc { } #[derive(Clone, Debug, Default, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct InlineSampler { pub coord: Coord, @@ -145,3 +153,23 @@ pub struct InlineSampler { pub max_anisotropy: Option, pub compare_func: CompareFunc, } + +impl Eq for InlineSampler {} + +#[allow(clippy::derive_hash_xor_eq)] +impl std::hash::Hash for InlineSampler { + fn hash(&self, hasher: &mut H) { + self.coord.hash(hasher); + self.address.hash(hasher); + self.border_color.hash(hasher); + self.mag_filter.hash(hasher); + self.min_filter.hash(hasher); + self.mip_filter.hash(hasher); + self.lod_clamp + .as_ref() + .map(|range| (range.start.to_bits(), range.end.to_bits())) + .hash(hasher); + self.max_anisotropy.hash(hasher); + self.compare_func.hash(hasher); + } +} diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index dec89803e..aae6af7ca 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -10,7 +10,7 @@ binding_map: { (stage: Vertex, group: 0, binding: 0): (buffer: Some(0)), (stage: Fragment, group: 0, binding: 1): (texture: Some(0)), - (stage: Fragment, group: 0, binding: 2): (sampler: Some(Inline(1))), + (stage: Fragment, group: 0, binding: 2): (sampler: Some(Inline(0))), }, push_constants_map: ( ), From daf4c82376e10d03488d7c71773b2acc1b9f7de4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 16 Apr 2021 16:16:15 -0400 Subject: [PATCH 0710/2212] Allow stepping on floats in the validator (#724) --- src/back/glsl/features.rs | 8 +++++--- src/valid/expression.rs | 4 ++-- tests/snapshots.rs | 7 +++++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index e76003f21..9699f98e1 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -280,7 +280,7 @@ impl<'a, W> Writer<'a, W> { } } - fn varying_required_features(&mut self, binding: Option<&Binding>, ty: Handle) { + fn varying_required_features(&mut self, binding: Option<&Binding>, ty: Handle) { match self.module.types[ty].inner { crate::TypeInner::Struct { ref members, .. } => { for member in members { @@ -290,9 +290,11 @@ impl<'a, W> Writer<'a, W> { _ => { if let Some(&Binding::Location(_, Some(interpolation))) = binding { match interpolation { - Interpolation::Linear => self.features.request(Features::NOPERSPECTIVE_QUALIFIER), + Interpolation::Linear => { + self.features.request(Features::NOPERSPECTIVE_QUALIFIER) + } Interpolation::Sample => self.features.request(Features::SAMPLE_QUALIFIER), - _ => () + _ => (), }; } } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 0ab075af1..9a1872d13 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -949,7 +949,7 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } } - Mf::Atan2 | Mf::Pow | Mf::Distance => { + Mf::Atan2 | Mf::Pow | Mf::Distance | Mf::Step => { let arg1_ty = match (arg1_ty, arg2_ty) { (Some(ty1), None) => ty1, _ => return Err(ExpressionError::WrongArgumentCount(fun)), @@ -1006,7 +1006,7 @@ impl super::Validator { )); } } - Mf::Dot | Mf::Outer | Mf::Cross | Mf::Step | Mf::Reflect => { + Mf::Dot | Mf::Outer | Mf::Cross | Mf::Reflect => { let arg1_ty = match (arg1_ty, arg2_ty) { (Some(ty1), None) => ty1, _ => return Err(ExpressionError::WrongArgumentCount(fun)), diff --git a/tests/snapshots.rs b/tests/snapshots.rs index bc5b56614..80b7ecf21 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -35,7 +35,7 @@ struct Parameters { msl_custom: bool, #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] #[serde(default)] - glsl_desktop_version: Option + glsl_desktop_version: Option, } #[allow(dead_code, unused_variables)] @@ -225,7 +225,10 @@ fn convert_wgsl() { ("image-copy", Targets::METAL), ("texture-array", Targets::SPIRV | Targets::METAL), ("operators", Targets::SPIRV | Targets::METAL | Targets::GLSL), - ("interpolate", Targets::SPIRV | Targets::METAL | Targets::GLSL), + ( + "interpolate", + Targets::SPIRV | Targets::METAL | Targets::GLSL, + ), ]; for &(name, targets) in inputs.iter() { From bb716f9c10f8dd766c97135e01d705ccaae959fa Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 16 Apr 2021 17:11:18 -0400 Subject: [PATCH 0711/2212] [spv-out] implement array value indexing (#723) --- src/back/spv/instructions.rs | 4 +- src/back/spv/writer.rs | 112 ++++++++++++++++++++++++++++----- tests/in/access.param.ron | 7 +++ tests/in/access.wgsl | 8 +++ tests/in/interpolate.param.ron | 2 +- tests/in/operators.wgsl | 6 +- tests/in/shadow.param.ron | 12 ++-- tests/out/access.msl | 15 +++++ tests/out/access.spvasm | 50 +++++++++++++++ tests/out/boids.spvasm | 1 - tests/out/collatz.spvasm | 1 - tests/out/interpolate.spvasm | 2 - tests/out/quad.spvasm | 2 - tests/out/shadow.spvasm | 1 - tests/out/texture-array.spvasm | 1 - tests/snapshots.rs | 1 + 16 files changed, 188 insertions(+), 37 deletions(-) create mode 100644 tests/in/access.param.ron create mode 100644 tests/in/access.wgsl create mode 100644 tests/out/access.msl create mode 100644 tests/out/access.spvasm diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 18de62be0..90f8b0128 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -433,12 +433,12 @@ impl super::Instruction { } pub(super) fn store( - pointer_type_id: Word, + pointer_id: Word, object_id: Word, memory_access: Option, ) -> Self { let mut instruction = Self::new(Op::Store); - instruction.add_operand(pointer_type_id); + instruction.add_operand(pointer_id); instruction.add_operand(object_id); if let Some(memory_access) = memory_access { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 2b467bc3d..e35a91ca5 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -70,6 +70,7 @@ struct Function { signature: Option, parameters: Vec, variables: crate::FastHashMap, LocalVariable>, + internal_variables: Vec, blocks: Vec, entry_point_context: Option, } @@ -86,6 +87,9 @@ impl Function { for local_var in self.variables.values() { local_var.instruction.to_words(sink); } + for internal_var in self.internal_variables.iter() { + internal_var.instruction.to_words(sink); + } } for instruction in block.body.iter() { instruction.to_words(sink); @@ -339,6 +343,20 @@ impl Writer { } } + fn get_expression_type_id( + &mut self, + arena: &Arena, + tr: &TypeResolution, + ) -> Result { + let lookup_ty = match *tr { + TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), + TypeResolution::Value(ref inner) => { + LookupType::Local(self.physical_layout.make_local(inner).unwrap()) + } + }; + self.get_type_id(arena, lookup_ty) + } + fn get_pointer_id( &mut self, arena: &Arena, @@ -649,11 +667,6 @@ impl Writer { }; self.check(exec_model.required_capabilities())?; - if self.flags.contains(WriterFlags::DEBUG) { - self.debugs - .push(Instruction::name(function_id, &entry_point.name)); - } - Ok(Instruction::entry_point( exec_model, function_id, @@ -1288,23 +1301,74 @@ impl Writer { }) } - /// Cache an expression for a value. - fn cache_expression_value<'a>( + #[allow(clippy::too_many_arguments)] + fn promote_access_expression_to_variable( &mut self, - ir_module: &'a crate::Module, + ir_types: &Arena, + result_type_id: Word, + container_id: Word, + container_resolution: &TypeResolution, + index_id: Word, + element_ty: Handle, + block: &mut Block, + ) -> Result<(Word, LocalVariable), Error> { + let container_type_id = self.get_expression_type_id(ir_types, container_resolution)?; + let pointer_type_id = self.id_gen.next(); + Instruction::type_pointer( + pointer_type_id, + spirv::StorageClass::Function, + container_type_id, + ) + .to_words(&mut self.logical_layout.declarations); + + let variable = { + let id = self.id_gen.next(); + LocalVariable { + id, + instruction: Instruction::variable( + pointer_type_id, + id, + spirv::StorageClass::Function, + None, + ), + } + }; + block + .body + .push(Instruction::store(variable.id, container_id, None)); + + let element_pointer_id = self.id_gen.next(); + let element_pointer_type_id = + self.get_pointer_id(ir_types, element_ty, spirv::StorageClass::Function)?; + block.body.push(Instruction::access_chain( + element_pointer_type_id, + element_pointer_id, + variable.id, + &[index_id], + )); + let id = self.id_gen.next(); + block.body.push(Instruction::load( + result_type_id, + id, + element_pointer_id, + None, + )); + + Ok((id, variable)) + } + + /// Cache an expression for a value. + fn cache_expression_value( + &mut self, + ir_module: &crate::Module, ir_function: &crate::Function, fun_info: &FunctionInfo, expr_handle: Handle, block: &mut Block, function: &mut Function, ) -> Result<(), Error> { - let result_lookup_ty = match fun_info[expr_handle].ty { - TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), - TypeResolution::Value(ref inner) => { - LookupType::Local(self.physical_layout.make_local(inner).unwrap()) - } - }; - let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; + let result_type_id = + self.get_expression_type_id(&ir_module.types, &fun_info[expr_handle].ty)?; let id = match ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { @@ -1318,10 +1382,10 @@ impl Writer { 0 } else { let index_id = self.cached[index]; + let base_id = self.cached[base]; match *fun_info[base].ty.inner_with(&ir_module.types) { crate::TypeInner::Vector { .. } => { let id = self.id_gen.next(); - let base_id = self.cached[base]; block.body.push(Instruction::vector_extract_dynamic( result_type_id, id, @@ -1330,7 +1394,21 @@ impl Writer { )); id } - //TODO: support `crate::TypeInner::Array { .. }` ? + crate::TypeInner::Array { + base: ty_element, .. + } => { + let (id, variable) = self.promote_access_expression_to_variable( + &ir_module.types, + result_type_id, + base_id, + &fun_info[base].ty, + index_id, + ty_element, + block, + )?; + function.internal_variables.push(variable); + id + } ref other => { log::error!("Unable to access {:?}", other); return Err(Error::FeatureNotImplemented("access for type")); diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron new file mode 100644 index 000000000..52f49f360 --- /dev/null +++ b/tests/in/access.param.ron @@ -0,0 +1,7 @@ +( + spv_version: (1, 1), + spv_capabilities: [ Shader, Image1D, Sampled1D ], + spv_debug: true, + spv_adjust_coordinate_space: false, + msl_custom: false, +) diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl new file mode 100644 index 000000000..c5f6c27e7 --- /dev/null +++ b/tests/in/access.wgsl @@ -0,0 +1,8 @@ +// This snapshot tests accessing various containers, dereferencing pointers. + +[[stage(vertex)]] +fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { + let array = array(1, 2, 3, 4, 5); + let value = array[vi]; + return vec4(vec4(value)); +} diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index dfd15dc16..804665025 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -4,5 +4,5 @@ spv_debug: true, spv_adjust_coordinate_space: true, msl_custom: false, - glsl_desktop_version: Some(400) + glsl_desktop_version: Some(400) ) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 958924c3e..7808e6e7c 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -1,6 +1,6 @@ [[stage(vertex)]] fn splat() -> [[builtin(position)]] vec4 { - let a = (1.0 + vec2(2.0) - 3.0) / 4.0; - let b = vec4(5) % 2; - return a.xyxy + vec4(b); + let a = (1.0 + vec2(2.0) - 3.0) / 4.0; + let b = vec4(5) % 2; + return a.xyxy + vec4(b); } diff --git a/tests/in/shadow.param.ron b/tests/in/shadow.param.ron index dc51d3ff4..dfa9978c3 100644 --- a/tests/in/shadow.param.ron +++ b/tests/in/shadow.param.ron @@ -1,8 +1,8 @@ ( - spv_flow_dump_prefix: "", - spv_version: (1, 2), - spv_capabilities: [ Shader ], - spv_debug: true, - spv_adjust_coordinate_space: true, - msl_custom: false, + spv_flow_dump_prefix: "", + spv_version: (1, 2), + spv_capabilities: [ Shader ], + spv_debug: true, + spv_adjust_coordinate_space: true, + msl_custom: false, ) diff --git a/tests/out/access.msl b/tests/out/access.msl new file mode 100644 index 000000000..8c9d1c226 --- /dev/null +++ b/tests/out/access.msl @@ -0,0 +1,15 @@ +#include +#include + +typedef int type3[5]; + +struct fooInput { +}; +struct fooOutput { + metal::float4 member [[position]]; +}; +vertex fooOutput foo( + metal::uint vi [[vertex_id]] +) { + return fooOutput { static_cast(type3 {1, 2, 3, 4, 5}[vi]) }; +} diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm new file mode 100644 index 000000000..985b9a840 --- /dev/null +++ b/tests/out/access.spvasm @@ -0,0 +1,50 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 31 +OpCapability Image1D +OpCapability Shader +OpCapability Sampled1D +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %19 "foo" %14 %17 +OpSource GLSL 450 +OpName %14 "vi" +OpName %19 "foo" +OpDecorate %12 ArrayStride 4 +OpDecorate %14 BuiltIn VertexIndex +OpDecorate %17 BuiltIn Position +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 5 +%5 = OpConstant %4 1 +%6 = OpConstant %4 2 +%7 = OpConstant %4 3 +%8 = OpConstant %4 4 +%9 = OpTypeInt 32 0 +%11 = OpTypeFloat 32 +%10 = OpTypeVector %11 4 +%12 = OpTypeArray %4 %3 +%15 = OpTypePointer Input %9 +%14 = OpVariable %15 Input +%18 = OpTypePointer Output %10 +%17 = OpVariable %18 Output +%20 = OpTypeFunction %2 +%23 = OpTypePointer Function %12 +%26 = OpTypePointer Function %4 +%28 = OpTypeVector %4 4 +%19 = OpFunction %2 None %20 +%13 = OpLabel +%24 = OpVariable %23 Function +%16 = OpLoad %9 %14 +OpBranch %21 +%21 = OpLabel +%22 = OpCompositeConstruct %12 %5 %6 %7 %8 %3 +OpStore %24 %22 +%25 = OpAccessChain %26 %24 %16 +%27 = OpLoad %4 %25 +%29 = OpCompositeConstruct %28 %27 %27 %27 %27 +%30 = OpConvertSToF %10 %29 +OpStore %17 %30 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm index 3f28ef288..c9a05f398 100644 --- a/tests/out/boids.spvasm +++ b/tests/out/boids.spvasm @@ -38,7 +38,6 @@ OpName %36 "vel" OpName %37 "i" OpName %40 "global_invocation_id" OpName %43 "main" -OpName %43 "main" OpMemberDecorate %16 0 Offset 0 OpMemberDecorate %16 1 Offset 8 OpDecorate %17 Block diff --git a/tests/out/collatz.spvasm b/tests/out/collatz.spvasm index cc4698fa4..929a4343d 100644 --- a/tests/out/collatz.spvasm +++ b/tests/out/collatz.spvasm @@ -17,7 +17,6 @@ OpName %15 "i" OpName %18 "collatz_iterations" OpName %45 "global_id" OpName %48 "main" -OpName %48 "main" OpDecorate %8 ArrayStride 4 OpDecorate %9 Block OpMemberDecorate %9 0 Offset 0 diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm index 063b86f7f..112bd1f0f 100644 --- a/tests/out/interpolate.spvasm +++ b/tests/out/interpolate.spvasm @@ -25,7 +25,6 @@ OpName %33 "centroid" OpName %35 "sample" OpName %37 "perspective" OpName %38 "main" -OpName %38 "main" OpName %76 "position" OpName %79 "flat" OpName %82 "linear" @@ -33,7 +32,6 @@ OpName %85 "centroid" OpName %88 "sample" OpName %91 "perspective" OpName %93 "main" -OpName %93 "main" OpMemberDecorate %23 0 Offset 0 OpMemberDecorate %23 1 Offset 16 OpMemberDecorate %23 2 Offset 20 diff --git a/tests/out/quad.spvasm b/tests/out/quad.spvasm index 676aee116..7f5af3c54 100644 --- a/tests/out/quad.spvasm +++ b/tests/out/quad.spvasm @@ -21,10 +21,8 @@ OpName %22 "uv" OpName %24 "uv" OpName %26 "position" OpName %28 "main" -OpName %28 "main" OpName %48 "uv" OpName %51 "main" -OpName %51 "main" OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 16 OpDecorate %12 DescriptorSet 0 diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm index 8189e93ee..1016e2060 100644 --- a/tests/out/shadow.spvasm +++ b/tests/out/shadow.spvasm @@ -29,7 +29,6 @@ OpName %71 "i" OpName %74 "raw_normal" OpName %77 "position" OpName %82 "fs_main" -OpName %82 "fs_main" OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %17 0 Offset 0 diff --git a/tests/out/texture-array.spvasm b/tests/out/texture-array.spvasm index dfc2b1f4d..1f4ba03f4 100644 --- a/tests/out/texture-array.spvasm +++ b/tests/out/texture-array.spvasm @@ -16,7 +16,6 @@ OpName %14 "sampler" OpName %16 "pc" OpName %19 "tex_coord" OpName %24 "main" -OpName %24 "main" OpDecorate %8 Block OpMemberDecorate %8 0 Offset 0 OpDecorate %11 DescriptorSet 0 diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 80b7ecf21..f90272620 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -229,6 +229,7 @@ fn convert_wgsl() { "interpolate", Targets::SPIRV | Targets::METAL | Targets::GLSL, ), + ("access", Targets::SPIRV | Targets::METAL), ]; for &(name, targets) in inputs.iter() { From 4cbef59dd60c21deb463a2275466734dd428df48 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Sat, 17 Apr 2021 01:14:07 -0400 Subject: [PATCH 0712/2212] Add struct instantiation support to wgsl-in (#507) * Add struct instantiation support to wgsl-in * Readd type matching and move struct test * rebase onto master and update tests * Update tests to upstream * Fix merge errors * Rebase onto master * [wgsl-in] delay composite type creation * Use the new WGSL construction syntax in the tests Co-authored-by: Dzmitry Malyshau --- src/front/wgsl/mod.rs | 59 +++++++---- src/front/wgsl/tests.rs | 18 ++++ tests/in/quad.wgsl | 5 +- tests/in/skybox.wgsl | 5 +- tests/out/quad.Vertex.glsl | 7 +- tests/out/quad.dot | 51 +++------ tests/out/quad.msl | 5 +- tests/out/quad.spvasm | 138 ++++++++++++------------- tests/out/skybox.Vertex.glsl | 7 +- tests/out/skybox.msl | 5 +- tests/out/skybox.spvasm | 194 +++++++++++++++++------------------ 11 files changed, 238 insertions(+), 256 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e9f21a291..8b4853406 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -10,7 +10,7 @@ mod tests; use crate::{ arena::{Arena, Handle}, - proc::{ensure_block_returns, ResolveContext, ResolveError}, + proc::{ensure_block_returns, ResolveContext, ResolveError, TypeResolution}, FastHashMap, }; @@ -1111,14 +1111,19 @@ impl Parser { //TODO: resolve the duplicate call in `parse_singular_expression` expr } else { - let inner = self.parse_type_decl_impl( - lexer, - TypeAttributes::default(), - word, - ctx.types, - ctx.constants, - )?; - let kind = inner.scalar_kind(); + let ty_resolution = match self.lookup_type.get(word) { + Some(&handle) => TypeResolution::Handle(handle), + None => { + let inner = self.parse_type_decl_impl( + lexer, + TypeAttributes::default(), + word, + ctx.types, + ctx.constants, + )?; + TypeResolution::Value(inner) + } + }; lexer.expect(Token::Paren('('))?; let mut components = Vec::new(); @@ -1130,8 +1135,15 @@ impl Parser { } lexer.expect(Token::Paren(')'))?; let expr = if components.is_empty() { - let last_component_inner = ctx.resolve_type(last_component)?; - match (&inner, last_component_inner) { + // We can't use the `TypeInner` returned by this because + // `resolve_type` borrows context mutably. + // Use it to insert into the right maps, + // and then grab it again immutably. + ctx.resolve_type(last_component)?; + match ( + ty_resolution.inner_with(ctx.types), + ctx.typifier.get(last_component, ctx.types), + ) { ( &crate::TypeInner::Vector { size, .. }, &crate::TypeInner::Scalar { .. }, @@ -1140,19 +1152,23 @@ impl Parser { value: last_component, }, ( - &crate::TypeInner::Scalar { .. }, + &crate::TypeInner::Scalar { kind, .. }, &crate::TypeInner::Scalar { .. }, ) | ( - &crate::TypeInner::Matrix { .. }, - &crate::TypeInner::Matrix { .. }, - ) - | ( - &crate::TypeInner::Vector { .. }, + &crate::TypeInner::Vector { kind, .. }, &crate::TypeInner::Vector { .. }, ) => crate::Expression::As { expr: last_component, - kind: kind.ok_or(Error::BadTypeCast(word))?, + kind, + convert: true, + }, + ( + &crate::TypeInner::Matrix { .. }, + &crate::TypeInner::Matrix { .. }, + ) => crate::Expression::As { + expr: last_component, + kind: crate::ScalarKind::Float, convert: true, }, _ => { @@ -1160,8 +1176,13 @@ impl Parser { } } } else { + let ty = match ty_resolution { + TypeResolution::Handle(handle) => handle, + TypeResolution::Value(inner) => { + ctx.types.fetch_or_append(crate::Type { name: None, inner }) + } + }; components.push(last_component); - let ty = ctx.types.fetch_or_append(crate::Type { name: None, inner }); crate::Expression::Compose { ty, components } }; ctx.expressions.append(expr) diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 96b96a718..d7428b65b 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -286,3 +286,21 @@ fn parse_pointers() { ) .unwrap(); } + +#[test] +fn parse_struct_instantiation() { + parse_str( + " + struct Foo { + a: f32; + b: vec3; + }; + + [[stage(fragment)]] + fn fs_main() { + var foo: Foo = Foo(0.0, vec3(0.0, 1.0, 42.0)); + } + ", + ) + .unwrap(); +} diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index fdaa9600c..0cd0187a8 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -8,10 +8,7 @@ struct VertexOutput { [[stage(vertex)]] fn main([[location(0)]] pos : vec2, [[location(1)]] uv : vec2) -> VertexOutput { - var out: VertexOutput; - out.uv = uv; - out.position = vec4(c_scale * pos, 0.0, 1.0); - return out; + return VertexOutput(uv, vec4(c_scale * pos, 0.0, 1.0)); } // fragment diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index 812373792..d5cb05126 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -25,10 +25,7 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { let inv_model_view = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); let unprojected = r_data.proj_inv * pos; - var out: VertexOutput; - out.uv = inv_model_view * unprojected.xyz; - out.position = pos; - return out; + return VertexOutput(pos, inv_model_view * unprojected.xyz); } [[group(0), binding(1)]] diff --git a/tests/out/quad.Vertex.glsl b/tests/out/quad.Vertex.glsl index b35cf16eb..ccd93c498 100644 --- a/tests/out/quad.Vertex.glsl +++ b/tests/out/quad.Vertex.glsl @@ -14,11 +14,8 @@ layout(location = 0) out vec2 _vs2fs_location0; void main() { vec2 pos = _p2vs_location0; vec2 uv1 = _p2vs_location1; - VertexOutput out1; - out1.uv = uv1; - out1.position = vec4((1.2 * pos), 0.0, 1.0); - _vs2fs_location0 = out1.uv; - gl_Position = out1.position; + _vs2fs_location0 = VertexOutput(uv1, vec4((1.2 * pos), 0.0, 1.0)).uv; + gl_Position = VertexOutput(uv1, vec4((1.2 * pos), 0.0, 1.0)).position; return; } diff --git a/tests/out/quad.dot b/tests/out/quad.dot index 6e8c54164..60587fc8b 100644 --- a/tests/out/quad.dot +++ b/tests/out/quad.dot @@ -7,50 +7,29 @@ digraph Module { subgraph cluster_ep0 { label="Vertex/'main'" node [ style=filled ] - ep0_l0 [ shape=hexagon label="[1] 'out'" ] ep0_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] ep0_e1 [ color="#8dd3c7" label="[2] Argument[0]" ] ep0_e2 [ color="#8dd3c7" label="[3] Argument[1]" ] - ep0_e3 [ color="#8dd3c7" label="[4] Local" ] - ep0_l0 -> ep0_e3 - ep0_e4 [ color="#8dd3c7" label="[5] AccessIndex[0]" ] - ep0_e3 -> ep0_e4 [ label="base" ] - ep0_e5 [ color="#8dd3c7" label="[6] AccessIndex[1]" ] - ep0_e3 -> ep0_e5 [ label="base" ] - ep0_e6 [ color="#fdb462" label="[7] Multiply" ] - ep0_e1 -> ep0_e6 [ label="right" ] - ep0_e0 -> ep0_e6 [ label="left" ] - ep0_e7 [ fillcolor="#ffffb3" label="[8] Constant" ] - ep0_e8 [ fillcolor="#ffffb3" label="[9] Constant" ] - ep0_e9 [ color="#bebada" label="[10] Compose" ] - { ep0_e6 ep0_e7 ep0_e8 } -> ep0_e9 - ep0_e10 [ color="#fb8072" label="[11] Load" ] - ep0_e3 -> ep0_e10 [ label="pointer" ] + ep0_e3 [ color="#fdb462" label="[4] Multiply" ] + ep0_e1 -> ep0_e3 [ label="right" ] + ep0_e0 -> ep0_e3 [ label="left" ] + ep0_e4 [ fillcolor="#ffffb3" label="[5] Constant" ] + ep0_e5 [ fillcolor="#ffffb3" label="[6] Constant" ] + ep0_e6 [ color="#bebada" label="[7] Compose" ] + { ep0_e3 ep0_e4 ep0_e5 } -> ep0_e6 + ep0_e7 [ color="#bebada" label="[8] Compose" ] + { ep0_e2 ep0_e6 } -> ep0_e7 ep0_s0 [ shape=square label="Root" ] ep0_s1 [ shape=square label="Emit" ] - ep0_s2 [ shape=square label="Store" ] - ep0_s3 [ shape=square label="Emit" ] - ep0_s4 [ shape=square label="Emit" ] - ep0_s5 [ shape=square label="Store" ] - ep0_s6 [ shape=square label="Emit" ] - ep0_s7 [ shape=square label="Return" ] + ep0_s2 [ shape=square label="Emit" ] + ep0_s3 [ shape=square label="Return" ] ep0_s0 -> ep0_s1 [ arrowhead=tee label="" ] ep0_s1 -> ep0_s2 [ arrowhead=tee label="" ] ep0_s2 -> ep0_s3 [ arrowhead=tee label="" ] - ep0_s3 -> ep0_s4 [ arrowhead=tee label="" ] - ep0_s4 -> ep0_s5 [ arrowhead=tee label="" ] - ep0_s5 -> ep0_s6 [ arrowhead=tee label="" ] - ep0_s6 -> ep0_s7 [ arrowhead=tee label="" ] - ep0_e2 -> ep0_s2 [ label="value" ] - ep0_e9 -> ep0_s5 [ label="value" ] - ep0_e10 -> ep0_s7 [ label="value" ] - ep0_s1 -> ep0_e4 [ style=dotted ] - ep0_s2 -> ep0_e4 [ style=dotted ] - ep0_s3 -> ep0_e5 [ style=dotted ] - ep0_s3 -> ep0_e6 [ style=dotted ] - ep0_s4 -> ep0_e9 [ style=dotted ] - ep0_s5 -> ep0_e5 [ style=dotted ] - ep0_s6 -> ep0_e10 [ style=dotted ] + ep0_e7 -> ep0_s3 [ label="value" ] + ep0_s1 -> ep0_e3 [ style=dotted ] + ep0_s2 -> ep0_e6 [ style=dotted ] + ep0_s2 -> ep0_e7 [ style=dotted ] } subgraph cluster_ep1 { label="Fragment/'main'" diff --git a/tests/out/quad.msl b/tests/out/quad.msl index 17f225b0d..e4ea4e40b 100644 --- a/tests/out/quad.msl +++ b/tests/out/quad.msl @@ -20,10 +20,7 @@ vertex main1Output main1( ) { const auto pos = varyings.pos; const auto uv1 = varyings.uv1; - VertexOutput out; - out.uv = uv1; - out.position = metal::float4(c_scale * pos, 0.0, 1.0); - const auto _tmp = out; + const auto _tmp = VertexOutput {uv1, metal::float4(c_scale * pos, 0.0, 1.0)}; return main1Output { _tmp.uv, _tmp.position }; } diff --git a/tests/out/quad.spvasm b/tests/out/quad.spvasm index 7f5af3c54..d15def3de 100644 --- a/tests/out/quad.spvasm +++ b/tests/out/quad.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 65 +; Bound: 58 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %28 "main" %19 %22 %24 %26 -OpEntryPoint Fragment %51 "main" %48 %50 -OpExecutionMode %51 OriginUpperLeft +OpEntryPoint Vertex %26 "main" %17 %20 %22 %24 +OpEntryPoint Fragment %44 "main" %41 %43 +OpExecutionMode %44 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" OpName %9 "VertexOutput" @@ -15,26 +15,25 @@ OpMemberName %9 0 "uv" OpMemberName %9 1 "position" OpName %12 "u_texture" OpName %14 "u_sampler" -OpName %16 "out" -OpName %19 "pos" +OpName %17 "pos" +OpName %20 "uv" OpName %22 "uv" -OpName %24 "uv" -OpName %26 "position" -OpName %28 "main" -OpName %48 "uv" -OpName %51 "main" +OpName %24 "position" +OpName %26 "main" +OpName %41 "uv" +OpName %44 "main" OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 16 OpDecorate %12 DescriptorSet 0 OpDecorate %12 Binding 0 OpDecorate %14 DescriptorSet 0 OpDecorate %14 Binding 1 -OpDecorate %19 Location 0 -OpDecorate %22 Location 1 -OpDecorate %24 Location 0 -OpDecorate %26 BuiltIn Position -OpDecorate %48 Location 0 -OpDecorate %50 Location 0 +OpDecorate %17 Location 0 +OpDecorate %20 Location 1 +OpDecorate %22 Location 0 +OpDecorate %24 BuiltIn Position +OpDecorate %41 Location 0 +OpDecorate %43 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.2 @@ -49,67 +48,58 @@ OpDecorate %50 Location 0 %12 = OpVariable %13 UniformConstant %15 = OpTypePointer UniformConstant %11 %14 = OpVariable %15 UniformConstant -%17 = OpTypePointer Function %9 -%20 = OpTypePointer Input %7 -%19 = OpVariable %20 Input -%22 = OpVariable %20 Input -%25 = OpTypePointer Output %7 +%18 = OpTypePointer Input %7 +%17 = OpVariable %18 Input +%20 = OpVariable %18 Input +%23 = OpTypePointer Output %7 +%22 = OpVariable %23 Output +%25 = OpTypePointer Output %8 %24 = OpVariable %25 Output -%27 = OpTypePointer Output %8 -%26 = OpVariable %27 Output -%29 = OpTypeFunction %2 -%31 = OpTypePointer Function %7 -%32 = OpTypeInt 32 1 -%33 = OpConstant %32 0 -%35 = OpTypePointer Function %8 -%38 = OpConstant %32 1 -%44 = OpTypePointer Output %4 -%48 = OpVariable %20 Input -%50 = OpVariable %27 Output -%55 = OpTypeSampledImage %10 -%59 = OpTypeBool -%28 = OpFunction %2 None %29 -%18 = OpLabel -%16 = OpVariable %17 Function -%21 = OpLoad %7 %19 -%23 = OpLoad %7 %22 -OpBranch %30 -%30 = OpLabel -%34 = OpAccessChain %31 %16 %33 -OpStore %34 %23 -%36 = OpVectorTimesScalar %7 %21 %3 -%37 = OpCompositeConstruct %8 %36 %5 %6 -%39 = OpAccessChain %35 %16 %38 -OpStore %39 %37 -%40 = OpLoad %9 %16 -%41 = OpCompositeExtract %7 %40 0 -OpStore %24 %41 -%42 = OpCompositeExtract %8 %40 1 -OpStore %26 %42 -%43 = OpAccessChain %44 %26 %38 -%45 = OpLoad %4 %43 -%46 = OpFNegate %4 %45 -OpStore %43 %46 +%27 = OpTypeFunction %2 +%35 = OpTypePointer Output %4 +%36 = OpTypeInt 32 1 +%37 = OpConstant %36 1 +%41 = OpVariable %18 Input +%43 = OpVariable %25 Output +%48 = OpTypeSampledImage %10 +%52 = OpTypeBool +%26 = OpFunction %2 None %27 +%16 = OpLabel +%19 = OpLoad %7 %17 +%21 = OpLoad %7 %20 +OpBranch %28 +%28 = OpLabel +%29 = OpVectorTimesScalar %7 %19 %3 +%30 = OpCompositeConstruct %8 %29 %5 %6 +%31 = OpCompositeConstruct %9 %21 %30 +%32 = OpCompositeExtract %7 %31 0 +OpStore %22 %32 +%33 = OpCompositeExtract %8 %31 1 +OpStore %24 %33 +%34 = OpAccessChain %35 %24 %37 +%38 = OpLoad %4 %34 +%39 = OpFNegate %4 %38 +OpStore %34 %39 OpReturn OpFunctionEnd -%51 = OpFunction %2 None %29 +%44 = OpFunction %2 None %27 +%40 = OpLabel +%42 = OpLoad %7 %41 +%45 = OpLoad %10 %12 +%46 = OpLoad %11 %14 +OpBranch %47 %47 = OpLabel -%49 = OpLoad %7 %48 -%52 = OpLoad %10 %12 -%53 = OpLoad %11 %14 -OpBranch %54 -%54 = OpLabel -%56 = OpSampledImage %55 %52 %53 -%57 = OpImageSampleImplicitLod %8 %56 %49 -%58 = OpCompositeExtract %4 %57 3 -%60 = OpFOrdEqual %59 %58 %5 -OpSelectionMerge %61 None -OpBranchConditional %60 %62 %61 -%62 = OpLabel +%49 = OpSampledImage %48 %45 %46 +%50 = OpImageSampleImplicitLod %8 %49 %42 +%51 = OpCompositeExtract %4 %50 3 +%53 = OpFOrdEqual %52 %51 %5 +OpSelectionMerge %54 None +OpBranchConditional %53 %55 %54 +%55 = OpLabel OpKill -%61 = OpLabel -%63 = OpCompositeExtract %4 %57 3 -%64 = OpVectorTimesScalar %8 %57 %63 -OpStore %50 %64 +%54 = OpLabel +%56 = OpCompositeExtract %4 %50 3 +%57 = OpVectorTimesScalar %8 %50 %56 +OpStore %43 %57 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/skybox.Vertex.glsl b/tests/out/skybox.Vertex.glsl index b30eced32..cc327f6a3 100644 --- a/tests/out/skybox.Vertex.glsl +++ b/tests/out/skybox.Vertex.glsl @@ -18,15 +18,12 @@ void main() { uint vertex_index = uint(gl_VertexID); int tmp1_; int tmp2_; - VertexOutput out1; tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); vec4 _expr24 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); vec4 _expr50 = (_group_0_binding_0.proj_inv * _expr24); - out1.uv = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr50[0], _expr50[1], _expr50[2])); - out1.position = _expr24; - gl_Position = out1.position; - _vs2fs_location0 = out1.uv; + gl_Position = VertexOutput(_expr24, (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr50[0], _expr50[1], _expr50[2]))).position; + _vs2fs_location0 = VertexOutput(_expr24, (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr50[0], _expr50[1], _expr50[2]))).uv; return; } diff --git a/tests/out/skybox.msl b/tests/out/skybox.msl index bd43ac6f6..efdff96d5 100644 --- a/tests/out/skybox.msl +++ b/tests/out/skybox.msl @@ -22,14 +22,11 @@ vertex vs_mainOutput vs_main( ) { int tmp1_; int tmp2_; - VertexOutput out; tmp1_ = static_cast(vertex_index) / 2; tmp2_ = static_cast(vertex_index) & 1; metal::float4 _e24 = metal::float4((static_cast(tmp1_) * 4.0) - 1.0, (static_cast(tmp2_) * 4.0) - 1.0, 0.0, 1.0); metal::float4 _e50 = r_data.proj_inv * _e24; - out.uv = metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_e50.x, _e50.y, _e50.z); - out.position = _e24; - const auto _tmp = out; + const auto _tmp = VertexOutput {_e24, metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_e50.x, _e50.y, _e50.z)}; return vs_mainOutput { _tmp.position, _tmp.uv }; } diff --git a/tests/out/skybox.spvasm b/tests/out/skybox.spvasm index 7455b1294..c51900db3 100644 --- a/tests/out/skybox.spvasm +++ b/tests/out/skybox.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 111 +; Bound: 105 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %38 "vs_main" %31 %34 %36 -OpEntryPoint Fragment %103 "fs_main" %96 %99 %102 -OpExecutionMode %103 OriginUpperLeft +OpEntryPoint Vertex %36 "vs_main" %29 %32 %34 +OpEntryPoint Fragment %97 "fs_main" %90 %93 %96 +OpExecutionMode %97 OriginUpperLeft OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpDecorate %14 Block @@ -23,12 +23,12 @@ OpDecorate %21 DescriptorSet 0 OpDecorate %21 Binding 1 OpDecorate %23 DescriptorSet 0 OpDecorate %23 Binding 2 -OpDecorate %31 BuiltIn VertexIndex -OpDecorate %34 BuiltIn Position -OpDecorate %36 Location 0 -OpDecorate %96 BuiltIn FragCoord -OpDecorate %99 Location 0 -OpDecorate %102 Location 0 +OpDecorate %29 BuiltIn VertexIndex +OpDecorate %32 BuiltIn Position +OpDecorate %34 Location 0 +OpDecorate %90 BuiltIn FragCoord +OpDecorate %93 Location 0 +OpDecorate %96 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -53,101 +53,93 @@ OpDecorate %102 Location 0 %24 = OpTypePointer UniformConstant %18 %23 = OpVariable %24 UniformConstant %26 = OpTypePointer Function %4 -%29 = OpTypePointer Function %12 -%32 = OpTypePointer Input %15 -%31 = OpVariable %32 Input -%35 = OpTypePointer Output %10 +%30 = OpTypePointer Input %15 +%29 = OpVariable %30 Input +%33 = OpTypePointer Output %10 +%32 = OpVariable %33 Output +%35 = OpTypePointer Output %11 %34 = OpVariable %35 Output -%37 = OpTypePointer Output %11 -%36 = OpVariable %37 Output -%39 = OpTypeFunction %2 -%54 = OpTypePointer Uniform %13 -%78 = OpConstant %4 0 -%82 = OpTypePointer Function %11 -%89 = OpTypePointer Function %10 -%97 = OpTypePointer Input %10 -%96 = OpVariable %97 Input -%100 = OpTypePointer Input %11 -%99 = OpVariable %100 Input -%102 = OpVariable %35 Output -%108 = OpTypeSampledImage %17 -%38 = OpFunction %2 None %39 -%30 = OpLabel +%37 = OpTypeFunction %2 +%52 = OpTypePointer Uniform %13 +%76 = OpConstant %4 0 +%91 = OpTypePointer Input %10 +%90 = OpVariable %91 Input +%94 = OpTypePointer Input %11 +%93 = OpVariable %94 Input +%96 = OpVariable %33 Output +%102 = OpTypeSampledImage %17 +%36 = OpFunction %2 None %37 +%28 = OpLabel %25 = OpVariable %26 Function %27 = OpVariable %26 Function -%28 = OpVariable %29 Function -%33 = OpLoad %15 %31 -OpBranch %40 -%40 = OpLabel -%41 = OpBitcast %4 %33 -%42 = OpSDiv %4 %41 %3 -OpStore %25 %42 -%43 = OpBitcast %4 %33 -%44 = OpBitwiseAnd %4 %43 %5 -OpStore %27 %44 -%45 = OpLoad %4 %25 -%46 = OpConvertSToF %7 %45 -%47 = OpFMul %7 %46 %6 -%48 = OpFSub %7 %47 %8 -%49 = OpLoad %4 %27 -%50 = OpConvertSToF %7 %49 -%51 = OpFMul %7 %50 %6 -%52 = OpFSub %7 %51 %8 -%53 = OpCompositeConstruct %10 %48 %52 %9 %8 -%55 = OpAccessChain %54 %19 %5 -%56 = OpLoad %13 %55 -%57 = OpCompositeExtract %10 %56 0 -%58 = OpCompositeExtract %7 %57 0 -%59 = OpCompositeExtract %7 %57 1 -%60 = OpCompositeExtract %7 %57 2 -%61 = OpCompositeConstruct %11 %58 %59 %60 -%62 = OpAccessChain %54 %19 %5 -%63 = OpLoad %13 %62 -%64 = OpCompositeExtract %10 %63 1 -%65 = OpCompositeExtract %7 %64 0 -%66 = OpCompositeExtract %7 %64 1 -%67 = OpCompositeExtract %7 %64 2 -%68 = OpCompositeConstruct %11 %65 %66 %67 -%69 = OpAccessChain %54 %19 %5 -%70 = OpLoad %13 %69 -%71 = OpCompositeExtract %10 %70 2 -%72 = OpCompositeExtract %7 %71 0 -%73 = OpCompositeExtract %7 %71 1 -%74 = OpCompositeExtract %7 %71 2 -%75 = OpCompositeConstruct %11 %72 %73 %74 -%76 = OpCompositeConstruct %16 %61 %68 %75 -%77 = OpTranspose %16 %76 -%79 = OpAccessChain %54 %19 %78 -%80 = OpLoad %13 %79 -%81 = OpMatrixTimesVector %10 %80 %53 -%83 = OpCompositeExtract %7 %81 0 -%84 = OpCompositeExtract %7 %81 1 -%85 = OpCompositeExtract %7 %81 2 -%86 = OpCompositeConstruct %11 %83 %84 %85 -%87 = OpMatrixTimesVector %11 %77 %86 -%88 = OpAccessChain %82 %28 %5 -OpStore %88 %87 -%90 = OpAccessChain %89 %28 %78 -OpStore %90 %53 -%91 = OpLoad %12 %28 -%92 = OpCompositeExtract %10 %91 0 -OpStore %34 %92 -%93 = OpCompositeExtract %11 %91 1 -OpStore %36 %93 +%31 = OpLoad %15 %29 +OpBranch %38 +%38 = OpLabel +%39 = OpBitcast %4 %31 +%40 = OpSDiv %4 %39 %3 +OpStore %25 %40 +%41 = OpBitcast %4 %31 +%42 = OpBitwiseAnd %4 %41 %5 +OpStore %27 %42 +%43 = OpLoad %4 %25 +%44 = OpConvertSToF %7 %43 +%45 = OpFMul %7 %44 %6 +%46 = OpFSub %7 %45 %8 +%47 = OpLoad %4 %27 +%48 = OpConvertSToF %7 %47 +%49 = OpFMul %7 %48 %6 +%50 = OpFSub %7 %49 %8 +%51 = OpCompositeConstruct %10 %46 %50 %9 %8 +%53 = OpAccessChain %52 %19 %5 +%54 = OpLoad %13 %53 +%55 = OpCompositeExtract %10 %54 0 +%56 = OpCompositeExtract %7 %55 0 +%57 = OpCompositeExtract %7 %55 1 +%58 = OpCompositeExtract %7 %55 2 +%59 = OpCompositeConstruct %11 %56 %57 %58 +%60 = OpAccessChain %52 %19 %5 +%61 = OpLoad %13 %60 +%62 = OpCompositeExtract %10 %61 1 +%63 = OpCompositeExtract %7 %62 0 +%64 = OpCompositeExtract %7 %62 1 +%65 = OpCompositeExtract %7 %62 2 +%66 = OpCompositeConstruct %11 %63 %64 %65 +%67 = OpAccessChain %52 %19 %5 +%68 = OpLoad %13 %67 +%69 = OpCompositeExtract %10 %68 2 +%70 = OpCompositeExtract %7 %69 0 +%71 = OpCompositeExtract %7 %69 1 +%72 = OpCompositeExtract %7 %69 2 +%73 = OpCompositeConstruct %11 %70 %71 %72 +%74 = OpCompositeConstruct %16 %59 %66 %73 +%75 = OpTranspose %16 %74 +%77 = OpAccessChain %52 %19 %76 +%78 = OpLoad %13 %77 +%79 = OpMatrixTimesVector %10 %78 %51 +%80 = OpCompositeExtract %7 %79 0 +%81 = OpCompositeExtract %7 %79 1 +%82 = OpCompositeExtract %7 %79 2 +%83 = OpCompositeConstruct %11 %80 %81 %82 +%84 = OpMatrixTimesVector %11 %75 %83 +%85 = OpCompositeConstruct %12 %51 %84 +%86 = OpCompositeExtract %10 %85 0 +OpStore %32 %86 +%87 = OpCompositeExtract %11 %85 1 +OpStore %34 %87 OpReturn OpFunctionEnd -%103 = OpFunction %2 None %39 -%94 = OpLabel -%98 = OpLoad %10 %96 -%101 = OpLoad %11 %99 -%95 = OpCompositeConstruct %12 %98 %101 -%104 = OpLoad %17 %21 -%105 = OpLoad %18 %23 -OpBranch %106 -%106 = OpLabel -%107 = OpCompositeExtract %11 %95 1 -%109 = OpSampledImage %108 %104 %105 -%110 = OpImageSampleImplicitLod %10 %109 %107 -OpStore %102 %110 +%97 = OpFunction %2 None %37 +%88 = OpLabel +%92 = OpLoad %10 %90 +%95 = OpLoad %11 %93 +%89 = OpCompositeConstruct %12 %92 %95 +%98 = OpLoad %17 %21 +%99 = OpLoad %18 %23 +OpBranch %100 +%100 = OpLabel +%101 = OpCompositeExtract %11 %89 1 +%103 = OpSampledImage %102 %98 %99 +%104 = OpImageSampleImplicitLod %10 %103 %101 +OpStore %96 %104 OpReturn OpFunctionEnd \ No newline at end of file From a584ec8185c40145fcf290c958a4f109316edb5a Mon Sep 17 00:00:00 2001 From: Ashley Date: Sun, 18 Apr 2021 07:19:12 +0200 Subject: [PATCH 0713/2212] Impl `Eq` for `msl::Options` (#725) --- src/back/msl/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 59b5097c6..0e402e2dd 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -126,7 +126,7 @@ enum LocationMode { Uniform, } -#[derive(Clone, Debug, Hash, PartialEq)] +#[derive(Clone, Debug, Hash, PartialEq, Eq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Options { From 62c2cf733235334c8f51c62af5a2cc8ba6ea3f9b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 18 Apr 2021 23:19:09 -0400 Subject: [PATCH 0714/2212] Validate composite constants (#729) --- src/front/spv/mod.rs | 18 +---- src/proc/typifier.rs | 12 ++++ src/valid/compose.rs | 131 +++++++++++++++++++++++++++++++++++++ src/valid/expression.rs | 130 ++++-------------------------------- src/valid/mod.rs | 44 ++++++++----- tests/out/collatz.info.ron | 4 +- tests/out/shadow.info.ron | 6 +- 7 files changed, 189 insertions(+), 156 deletions(-) create mode 100644 src/valid/compose.rs diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d6cedea18..e76b86c74 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -850,21 +850,9 @@ impl> Parser { let index_expr_data = &expressions[index_expr.handle]; let index_maybe = match *index_expr_data { crate::Expression::Constant(const_handle) => { - match const_arena[const_handle].inner { - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(v), - } => Some(v as u32), - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Sint(v), - } => Some(v as u32), - _ => { - return Err(Error::InvalidAccess( - crate::Expression::Constant(const_handle), - )) - } - } + Some(const_arena[const_handle].to_array_length().ok_or( + Error::InvalidAccess(crate::Expression::Constant(const_handle)), + )?) } _ => None, }; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index ce62a5b21..1af4cf8b5 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -62,6 +62,18 @@ impl Clone for TypeResolution { } } +impl crate::ConstantInner { + pub fn resolve_type(&self) -> TypeResolution { + match *self { + Self::Scalar { width, ref value } => TypeResolution::Value(crate::TypeInner::Scalar { + kind: value.scalar_kind(), + width, + }), + Self::Composite { ty, components: _ } => TypeResolution::Handle(ty), + } + } +} + #[derive(Clone, Debug, Error, PartialEq)] pub enum ResolveError { #[error("Index {index} is out of bounds for expression {expr:?}")] diff --git a/src/valid/compose.rs b/src/valid/compose.rs new file mode 100644 index 000000000..e25a7379d --- /dev/null +++ b/src/valid/compose.rs @@ -0,0 +1,131 @@ +use crate::{ + arena::{Arena, Handle}, + proc::TypeResolution, +}; + +#[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] +pub enum ComposeError { + #[error("Compose type {0:?} doesn't exist")] + TypeDoesntExist(Handle), + #[error("Composing of type {0:?} can't be done")] + Type(Handle), + #[error("Composing expects {expected} components but {given} were given")] + ComponentCount { given: u32, expected: u32 }, + #[error("Composing {index}'s component type is not expected")] + ComponentType { index: u32 }, +} + +pub fn validate_compose( + self_ty_handle: Handle, + constant_arena: &Arena, + type_arena: &Arena, + component_resolutions: impl ExactSizeIterator, +) -> Result<(), ComposeError> { + use crate::TypeInner as Ti; + + let self_ty = type_arena + .try_get(self_ty_handle) + .ok_or(ComposeError::TypeDoesntExist(self_ty_handle))?; + match self_ty.inner { + // vectors are composed from scalars or other vectors + Ti::Vector { size, kind, width } => { + let mut total = 0; + for (index, comp_res) in component_resolutions.enumerate() { + total += match *comp_res.inner_with(type_arena) { + Ti::Scalar { + kind: comp_kind, + width: comp_width, + } if comp_kind == kind && comp_width == width => 1, + Ti::Vector { + size: comp_size, + kind: comp_kind, + width: comp_width, + } if comp_kind == kind && comp_width == width => comp_size as u32, + ref other => { + log::error!("Vector component[{}] type {:?}", index, other); + return Err(ComposeError::ComponentType { + index: index as u32, + }); + } + }; + } + if size as u32 != total { + return Err(ComposeError::ComponentCount { + expected: size as u32, + given: total, + }); + } + } + // matrix are composed from column vectors + Ti::Matrix { + columns, + rows, + width, + } => { + let inner = Ti::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }; + if columns as usize != component_resolutions.len() { + return Err(ComposeError::ComponentCount { + expected: columns as u32, + given: component_resolutions.len() as u32, + }); + } + for (index, comp_res) in component_resolutions.enumerate() { + if comp_res.inner_with(type_arena) != &inner { + log::error!("Matrix component[{}] type {:?}", index, comp_res); + return Err(ComposeError::ComponentType { + index: index as u32, + }); + } + } + } + Ti::Array { + base, + size: crate::ArraySize::Constant(handle), + stride: _, + } => { + let count = constant_arena[handle].to_array_length().unwrap(); + if count as usize != component_resolutions.len() { + return Err(ComposeError::ComponentCount { + expected: count, + given: component_resolutions.len() as u32, + }); + } + for (index, comp_res) in component_resolutions.enumerate() { + if comp_res.inner_with(type_arena) != &type_arena[base].inner { + log::error!("Array component[{}] type {:?}", index, comp_res); + return Err(ComposeError::ComponentType { + index: index as u32, + }); + } + } + } + Ti::Struct { ref members, .. } => { + if members.len() != component_resolutions.len() { + return Err(ComposeError::ComponentCount { + given: component_resolutions.len() as u32, + expected: members.len() as u32, + }); + } + for (index, (member, comp_res)) in members.iter().zip(component_resolutions).enumerate() + { + if comp_res.inner_with(type_arena) != &type_arena[member.ty].inner { + log::error!("Struct component[{}] type {:?}", index, comp_res); + return Err(ComposeError::ComponentType { + index: index as u32, + }); + } + } + } + ref other => { + log::error!("Composing of {:?}", other); + return Err(ComposeError::Type(self_ty_handle)); + } + } + + Ok(()) +} diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 9a1872d13..1ec603ce7 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,4 +1,4 @@ -use super::{FunctionInfo, ShaderStages, TypeFlags}; +use super::{compose::validate_compose, ComposeError, FunctionInfo, ShaderStages, TypeFlags}; use crate::{ arena::{Arena, Handle}, proc::ResolveError, @@ -33,14 +33,8 @@ pub enum ExpressionError { InvalidArrayType(Handle), #[error("Splatting {0:?} can't be done")] InvalidSplatType(Handle), - #[error("Compose type {0:?} doesn't exist")] - ComposeTypeDoesntExist(Handle), - #[error("Composing of type {0:?} can't be done")] - InvalidComposeType(Handle), - #[error("Composing expects {expected} components but {given} were given")] - InvalidComposeCount { given: u32, expected: u32 }, - #[error("Composing {0}'s component {1:?} is not expected")] - InvalidComponentType(u32, Handle), + #[error(transparent)] + Compose(#[from] ComposeError), #[error("Operation {0:?} can't work with {1:?}")] InvalidUnaryOperandType(crate::UnaryOperator, Handle), #[error("Operation {0:?} can't work with {1:?} and {2:?}")] @@ -207,117 +201,17 @@ impl super::Validator { } }, E::Compose { ref components, ty } => { - match module - .types - .try_get(ty) - .ok_or(ExpressionError::ComposeTypeDoesntExist(ty))? - .inner - { - // vectors are composed from scalars or other vectors - Ti::Vector { size, kind, width } => { - let mut total = 0; - for (index, &comp) in components.iter().enumerate() { - total += match *resolver.resolve(comp)? { - Ti::Scalar { - kind: comp_kind, - width: comp_width, - } if comp_kind == kind && comp_width == width => 1, - Ti::Vector { - size: comp_size, - kind: comp_kind, - width: comp_width, - } if comp_kind == kind && comp_width == width => comp_size as u32, - ref other => { - log::error!("Vector component[{}] type {:?}", index, other); - return Err(ExpressionError::InvalidComponentType( - index as u32, - comp, - )); - } - }; - } - if size as u32 != total { - return Err(ExpressionError::InvalidComposeCount { - expected: size as u32, - given: total, - }); - } - } - // matrix are composed from column vectors - Ti::Matrix { - columns, - rows, - width, - } => { - let inner = Ti::Vector { - size: rows, - kind: Sk::Float, - width, - }; - if columns as usize != components.len() { - return Err(ExpressionError::InvalidComposeCount { - expected: columns as u32, - given: components.len() as u32, - }); - } - for (index, &comp) in components.iter().enumerate() { - let tin = resolver.resolve(comp)?; - if tin != &inner { - log::error!("Matrix component[{}] type {:?}", index, tin); - return Err(ExpressionError::InvalidComponentType( - index as u32, - comp, - )); - } - } - } - Ti::Array { - base, - size: crate::ArraySize::Constant(handle), - stride: _, - } => { - let count = module.constants[handle].to_array_length().unwrap(); - if count as usize != components.len() { - return Err(ExpressionError::InvalidComposeCount { - expected: count, - given: components.len() as u32, - }); - } - let base_inner = &module.types[base].inner; - for (index, &comp) in components.iter().enumerate() { - let tin = resolver.resolve(comp)?; - if tin != base_inner { - log::error!("Array component[{}] type {:?}", index, tin); - return Err(ExpressionError::InvalidComponentType( - index as u32, - comp, - )); - } - } - } - Ti::Struct { ref members, .. } => { - for (index, (member, &comp)) in members.iter().zip(components).enumerate() { - let tin = resolver.resolve(comp)?; - if tin != &module.types[member.ty].inner { - log::error!("Struct component[{}] type {:?}", index, tin); - return Err(ExpressionError::InvalidComponentType( - index as u32, - comp, - )); - } - } - if members.len() != components.len() { - return Err(ExpressionError::InvalidComposeCount { - given: components.len() as u32, - expected: members.len() as u32, - }); - } - } - ref other => { - log::error!("Composing of {:?}", other); - return Err(ExpressionError::InvalidComposeType(ty)); + for &handle in components { + if handle >= root { + return Err(ExpressionError::ForwardDependency(handle)); } } + validate_compose( + ty, + &module.constants, + &module.types, + components.iter().map(|&handle| info[handle].ty.clone()), + )?; ShaderStages::all() } E::FunctionArgument(index) => { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 87bfd2088..9ef3bb312 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -1,4 +1,5 @@ mod analyzer; +mod compose; mod expression; mod function; mod interface; @@ -15,6 +16,7 @@ use std::ops; // merge the corresponding matches over expressions and statements. pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements}; +pub use compose::ComposeError; pub use expression::ExpressionError; pub use function::{CallError, FunctionError, LocalVariableError}; pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; @@ -33,6 +35,8 @@ bitflags::bitflags! { const CONTROL_FLOW_UNIFORMITY = 0x4; /// Host-shareable structure layouts. const STRUCT_LAYOUTS = 0x8; + /// Constants. + const CONSTANTS = 0x10; } } @@ -81,6 +85,8 @@ pub enum ConstantError { UnresolvedComponent(Handle), #[error("The array size handle {0:?} can not be resolved")] UnresolvedSize(Handle), + #[error(transparent)] + Compose(#[from] ComposeError), } #[derive(Clone, Debug, thiserror::Error)] @@ -191,25 +197,25 @@ impl Validator { } crate::ConstantInner::Composite { ty, ref components } => { match types[ty].inner { - crate::TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } => { - return Err(ConstantError::InvalidType); - } crate::TypeInner::Array { size: crate::ArraySize::Constant(size_handle), .. - } => { - if handle <= size_handle { - return Err(ConstantError::UnresolvedSize(size_handle)); - } + } if handle <= size_handle => { + return Err(ConstantError::UnresolvedSize(size_handle)); } - _ => {} //TODO + _ => {} } if let Some(&comp) = components.iter().find(|&&comp| handle <= comp) { return Err(ConstantError::UnresolvedComponent(comp)); } + compose::validate_compose( + ty, + constants, + types, + components + .iter() + .map(|&component| constants[component].inner.resolve_type()), + )?; } } Ok(()) @@ -219,13 +225,15 @@ impl Validator { pub fn validate(&mut self, module: &crate::Module) -> Result { self.reset_types(module.types.len()); - for (handle, constant) in module.constants.iter() { - self.validate_constant(handle, &module.constants, &module.types) - .map_err(|error| ValidationError::Constant { - handle, - name: constant.name.clone().unwrap_or_default(), - error, - })?; + if self.flags.contains(ValidationFlags::CONSTANTS) { + for (handle, constant) in module.constants.iter() { + self.validate_constant(handle, &module.constants, &module.types) + .map_err(|error| ValidationError::Constant { + handle, + name: constant.name.clone().unwrap_or_default(), + error, + })?; + } } // doing after the globals, so that `type_flags` is ready diff --git a/tests/out/collatz.info.ron b/tests/out/collatz.info.ron index 6bea48630..edf6a5a5a 100644 --- a/tests/out/collatz.info.ron +++ b/tests/out/collatz.info.ron @@ -2,7 +2,7 @@ functions: [ ( flags: ( - bits: 15, + bits: 31, ), available_stages: ( bits: 7, @@ -341,7 +341,7 @@ entry_points: [ ( flags: ( - bits: 15, + bits: 31, ), available_stages: ( bits: 7, diff --git a/tests/out/shadow.info.ron b/tests/out/shadow.info.ron index 6e11adbc9..d1491f6c8 100644 --- a/tests/out/shadow.info.ron +++ b/tests/out/shadow.info.ron @@ -2,7 +2,7 @@ functions: [ ( flags: ( - bits: 15, + bits: 31, ), available_stages: ( bits: 7, @@ -1063,7 +1063,7 @@ ), ( flags: ( - bits: 15, + bits: 31, ), available_stages: ( bits: 7, @@ -2753,7 +2753,7 @@ entry_points: [ ( flags: ( - bits: 15, + bits: 31, ), available_stages: ( bits: 7, From c1675d06f9032d6cca57431f94bf7ffdb4c52f2f Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 19 Apr 2021 07:23:27 +0300 Subject: [PATCH 0715/2212] Start wgsl-out (#727) --- Cargo.toml | 1 + README.md | 2 +- bin/convert.rs | 7 ++ src/back/mod.rs | 2 + src/back/wgsl/keywords.rs | 126 +++++++++++++++++++++++++++++++++ src/back/wgsl/mod.rs | 23 ++++++ src/back/wgsl/writer.rs | 144 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 304 insertions(+), 1 deletion(-) create mode 100644 src/back/wgsl/keywords.rs create mode 100644 src/back/wgsl/mod.rs create mode 100644 src/back/wgsl/writer.rs diff --git a/Cargo.toml b/Cargo.toml index ca412e4e9..90b3dedd1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ deserialize = ["serde"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] wgsl-in = ["codespan-reporting"] +wgsl-out = [] hlsl-out = [] [[bin]] diff --git a/README.md b/README.md index 5873d8eff..3ca6c920f 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Rust | | | | Back-end | Status | Feature | Notes | --------------- | ------------------ | -------- | ----- | SPIR-V | :white_check_mark: | spv-out | | -WGSL | | | | +WGSL | :construction: | wgsl-out | | Metal | :white_check_mark: | msl-out | | HLSL | :construction: | hlsl-out | | GLSL | :ok: | glsl-out | | diff --git a/bin/convert.rs b/bin/convert.rs index 492fa783c..151fc2967 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -268,6 +268,13 @@ fn main() { let hlsl = hlsl::write_string(&module).unwrap_pretty(); fs::write(output_path, hlsl).unwrap(); } + #[cfg(feature = "wgsl-out")] + "wgsl" => { + use naga::back::wgsl; + + let wgsl = wgsl::write_string(&module).unwrap_pretty(); + fs::write(output_path, wgsl).unwrap(); + } other => { let _ = params; panic!( diff --git a/src/back/mod.rs b/src/back/mod.rs index efffb40a4..a478d971d 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -10,6 +10,8 @@ pub mod hlsl; pub mod msl; #[cfg(feature = "spv-out")] pub mod spv; +#[cfg(feature = "wgsl-out")] +pub mod wgsl; impl crate::Expression { /// Returns the ref count, upon reaching which this expression diff --git a/src/back/wgsl/keywords.rs b/src/back/wgsl/keywords.rs new file mode 100644 index 000000000..a0ec86810 --- /dev/null +++ b/src/back/wgsl/keywords.rs @@ -0,0 +1,126 @@ +// https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary +pub const RESERVED: &[&str] = &[ + // Type-defining keywords + "ARRAY", + "BOOL", + "FLOAT32", + "INT32", + "MAT2x2", + "MAT2x3", + "MAT2x4", + "MAT3x2", + "MAT3x3", + "MAT3x4", + "MAT4x2", + "MAT4x3", + "MAT4x4", + "POINTER", + "SAMPLER", + "SAMPLER_COMPARISON", + "STRUCT", + "TEXTURE_1D", + "TEXTURE_2D", + "TEXTURE_2D_ARRAY", + "TEXTURE_3D", + "TEXTURE_CUBE", + "TEXTURE_CUBE_ARRAY", + "TEXTURE_MULTISAMPLED_2D", + "TEXTURE_STORAGE_1D", + "TEXTURE_STORAGE_2D", + "TEXTURE_STORAGE_2D_ARRAY", + "TEXTURE_STORAGE_3D", + "TEXTURE_DEPTH_2D", + "TEXTURE_DEPTH_2D_ARRAY", + "TEXTURE_DEPTH_CUBE", + "TEXTURE_DEPTH_CUBE_ARRAY", + "UINT32", + "VEC2", + "VEC3", + "VEC4", + // Other keywords + "BITCAST", + "BLOCK", + "BREAK", + "CASE", + "CONTINUE", + "CONTINUING", + "DEFAULT", + "DISCARD", + "ELSE", + "ELSE_IF", + "ENABLE", + "FALLTHROUGH", + "FALSE", + "FN", + "FOR", + "FUNCTION", + "IF", + "LET", + "LOOP", + "PRIVATE", + "RETURN", + "STORAGE", + "SWITCH", + "TRUE", + "TYPE", + "UNIFORM", + "VAR", + "WORKGROUP", + // Image format keywords + "R8UNORM", + "R8SNORM", + "R8UINT", + "R8SINT", + "R16UINT", + "R16SINT", + "R16FLOAT", + "RG8UNORM", + "RG8SNORM", + "RG8UINT", + "RG8SINT", + "R32UINT", + "R32SINT", + "R32FLOAT", + "RG16UINT", + "RG16SINT", + "RG16FLOAT", + "RGBA8UNORM", + "RGBA8UNORM-SRGB", + "RGBA8SNORM", + "RGBA8UINT", + "RGBA8SINT", + "BGRA8UNORM", + "BGRA8UNORM-SRGB", + "RGB10A2UNORM", + "RG11B10FLOAT", + "RG32UINT", + "RG32SINT", + "RG32FLOAT", + "RGBA16UINT", + "RGBA16SINT", + "RGBA16FLOAT", + "RGBA32UINT", + "RGBA32SINT", + "RGBA32FLOAT", + // Reserved Keywords + "asm", + "bf16", + "do", + "enum", + "f16", + "f64", + "i8", + "i16", + "i64", + "const", + "typedef", + "u8", + "u16", + "u64", + "unless", + "using", + "while", + "regardless", + "premerge", + "handle", +]; diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs new file mode 100644 index 000000000..e785b57a1 --- /dev/null +++ b/src/back/wgsl/mod.rs @@ -0,0 +1,23 @@ +mod keywords; +mod writer; + +use std::io::Error as IoError; +use std::string::FromUtf8Error; +use thiserror::Error; + +pub use writer::Writer; + +#[derive(Error, Debug)] +pub enum Error { + #[error(transparent)] + IoError(#[from] IoError), + #[error(transparent)] + Utf8(#[from] FromUtf8Error), +} + +pub fn write_string(module: &crate::Module) -> Result { + let mut w = Writer::new(Vec::new()); + w.write(module)?; + let output = String::from_utf8(w.finish())?; + Ok(output) +} diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs new file mode 100644 index 000000000..206e96d11 --- /dev/null +++ b/src/back/wgsl/writer.rs @@ -0,0 +1,144 @@ +use super::Error; +use crate::FastHashMap; +use crate::{ + back::wgsl::keywords::RESERVED, Function, Module, ShaderStage, StructLevel, TypeInner, +}; +use crate::{ + proc::{NameKey, Namer}, + StructMember, +}; +use std::io::Write; + +const _INDENT: &str = " "; + +/// Shorthand result used internally by the backend +type BackendResult = Result<(), Error>; + +enum Decoration { + VertexStage, + FragmentStage, + ComputeStage { workgroup_size: [u32; 3] }, + Block, +} + +pub struct Writer { + out: W, + names: FastHashMap, + namer: Namer, +} + +impl Writer { + pub fn new(out: W) -> Self { + Writer { + out, + names: FastHashMap::default(), + namer: Namer::default(), + } + } + + pub fn write(&mut self, module: &Module) -> BackendResult { + self.names.clear(); + self.namer.reset(module, RESERVED, &mut self.names); + + // Write all structs + for (handle, ty) in module.types.iter() { + if let TypeInner::Struct { + level, ref members, .. + } = ty.inner + { + let name = &self.names[&NameKey::Type(handle)].clone(); + let block = level == StructLevel::Root; + self.write_struct(name, block, members)?; + writeln!(self.out)?; + } + } + + for (_, ep) in module.entry_points.iter().enumerate() { + let decoration = match ep.stage { + ShaderStage::Vertex => Decoration::VertexStage, + ShaderStage::Fragment => Decoration::FragmentStage, + ShaderStage::Compute => Decoration::ComputeStage { + workgroup_size: ep.workgroup_size, + }, + }; + + self.write_decoration(decoration)?; + // Add a newline after decoration + writeln!(self.out)?; + self.write_function(&ep.function)?; + } + + // Add a newline at the end of file + writeln!(self.out)?; + + Ok(()) + } + + /// Helper method used to write structs + /// https://gpuweb.github.io/gpuweb/wgsl/#functions + /// + /// # Notes + /// Ends in a newline + fn write_function(&mut self, func: &Function) -> BackendResult { + write!(self.out, "fn {}(", func.name.as_ref().unwrap())?; // TODO: unnamed function? + write!(self.out, ")")?; + + write!(self.out, "{{")?; + write!(self.out, "}}")?; + Ok(()) + } + + /// Helper method to write a decoration + /// + /// # Notes + /// Adds no leading or trailing whitespace + fn write_decoration(&mut self, decoration: Decoration) -> BackendResult { + write!(self.out, "[[")?; + match decoration { + Decoration::VertexStage => write!(self.out, "stage(vertex)")?, + Decoration::FragmentStage => write!(self.out, "stage(fragment)")?, + Decoration::ComputeStage { workgroup_size } => { + write!( + self.out, + "{}", + format!( + "stage(compute), workgroup_size({}, {}, {})", + workgroup_size[0], workgroup_size[1], workgroup_size[2] + ) + )?; + } + Decoration::Block => { + write!(self.out, "block")?; + } + }; + write!(self.out, "]]")?; + + Ok(()) + } + + /// Helper method used to write structs + /// + /// # Notes + /// Ends in a newline + fn write_struct( + &mut self, + name: &str, + block: bool, + _members: &[StructMember], + ) -> BackendResult { + if block { + self.write_decoration(Decoration::Block)?; + writeln!(self.out)?; + } + write!(self.out, "struct {} {{", name)?; + write!(self.out, "}}")?; + + writeln!(self.out)?; + + Ok(()) + } + + pub fn finish(self) -> W { + self.out + } +} From ce0720ac61706af54130ea1eee6a49f9990f9008 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 19 Apr 2021 16:19:03 +0300 Subject: [PATCH 0716/2212] Add wgsl-out into test infrastructure (#730) --- .github/workflows/validation-linux.yml | 8 +++++--- .github/workflows/validation-macos.yml | 2 +- Makefile | 8 +++++++- README.md | 1 + tests/out/empty.wgsl | 2 ++ tests/snapshots.rs | 18 +++++++++++++++++- 6 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 tests/out/empty.wgsl diff --git a/.github/workflows/validation-linux.yml b/.github/workflows/validation-linux.yml index 870299b4b..997b80783 100644 --- a/.github/workflows/validation-linux.yml +++ b/.github/workflows/validation-linux.yml @@ -2,9 +2,10 @@ name: validation-linux on: pull_request: paths: - - 'tests/out/*.spvasm.snap' - - 'tests/out/*.glsl.snap' - - 'tests/out/*.dot.snap' + - 'tests/out/*.spvasm' + - 'tests/out/*.glsl' + - 'tests/out/*.dot' + - 'tests/out/*.wgsl' jobs: validate-linux: @@ -17,3 +18,4 @@ jobs: - run: make validate-spv - run: make validate-glsl - run: make validate-dot + - run: make validate-wgsl diff --git a/.github/workflows/validation-macos.yml b/.github/workflows/validation-macos.yml index 850e9f08c..89a3b13f5 100644 --- a/.github/workflows/validation-macos.yml +++ b/.github/workflows/validation-macos.yml @@ -2,7 +2,7 @@ name: validation-macos on: pull_request: paths: - - 'tests/out/*.msl.snap' + - 'tests/out/*.msl' jobs: validate-macos: diff --git a/Makefile b/Makefile index cc70da265..ea631e499 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all clean validate-spv validate-msl validate-glsl validate-dot +.PHONY: all clean validate-spv validate-msl validate-glsl validate-dot validate-wgsl .SECONDARY: boids.metal quad.metal SNAPSHOTS_IN=tests/in SNAPSHOTS_OUT=tests/out @@ -57,3 +57,9 @@ validate-dot: $(SNAPSHOTS_OUT)/*.dot echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ cat $${file} | dot -o /dev/null; \ done + +validate-wgsl: $(SNAPSHOTS_OUT)/*.wgsl + @set -e && for file in $^ ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ + cargo run --bin convert --features wgsl-in $${file} >/dev/null; \ + done diff --git a/README.md b/README.md index 3ca6c920f..2224fab6e 100644 --- a/README.md +++ b/README.md @@ -61,4 +61,5 @@ make validate-spv # for Vulkan shaders, requires SPIRV-Tools installed make validate-msl # for Metal shaders, requires XCode command-line tools installed make validate-glsl # for OpenGL shaders, requires GLSLang installed make validate-dot # for dot files, requires GraphViz installed +make validate-wgsl # for WGSL shaders ``` diff --git a/tests/out/empty.wgsl b/tests/out/empty.wgsl new file mode 100644 index 000000000..e89004345 --- /dev/null +++ b/tests/out/empty.wgsl @@ -0,0 +1,2 @@ +[[stage(compute), workgroup_size(1, 1, 1)]] +fn main(){} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index f90272620..a52b8b6f5 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -15,6 +15,7 @@ bitflags::bitflags! { const GLSL = 0x10; const DOT = 0x20; const HLSL = 0x40; + const WGSL = 0x80; } } @@ -98,6 +99,12 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { check_output_hlsl(module, &dest); } } + #[cfg(feature = "wgsl-out")] + { + if targets.contains(Targets::WGSL) { + check_output_wgsl(module, &dest); + } + } } #[cfg(feature = "spv-out")] @@ -201,6 +208,15 @@ fn check_output_hlsl(module: &naga::Module, destination: &PathBuf) { fs::write(destination.with_extension("hlsl"), string).unwrap(); } +#[cfg(feature = "wgsl-out")] +fn check_output_wgsl(module: &naga::Module, destination: &PathBuf) { + use naga::back::wgsl; + + let string = wgsl::write_string(module).unwrap(); + + fs::write(destination.with_extension("wgsl"), string).unwrap(); +} + #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl() { @@ -208,7 +224,7 @@ fn convert_wgsl() { let inputs = [ ( "empty", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "quad", From 45ee5f51131d951abe39a22f5b2b9efe5a780e63 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 8 Apr 2021 15:01:03 -0700 Subject: [PATCH 0717/2212] [spv-out] Writer: Introduce `decorate` helper method. The `Writer::decorate` private method neatens up eight call sites. --- src/back/spv/writer.rs | 40 ++++++++++++---------------------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e35a91ca5..4b1502a8b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -417,6 +417,10 @@ impl Writer { Ok(id) } + fn decorate(&mut self, id: Word, decoration: spirv::Decoration, operands: &[Word]) { + self.annotations.push(Instruction::decorate(id, decoration, operands)); + } + fn write_function( &mut self, ir_function: &crate::Function, @@ -856,11 +860,7 @@ impl Writer { crate::TypeInner::Sampler { comparison: _ } => Instruction::type_sampler(id), crate::TypeInner::Array { base, size, stride } => { if decorate_layout { - self.annotations.push(Instruction::decorate( - id, - Decoration::ArrayStride, - &[stride], - )); + self.decorate(id, Decoration::ArrayStride, &[stride]); } let type_id = self.get_type_id(arena, LookupType::Handle(base))?; @@ -878,8 +878,7 @@ impl Writer { span: _, } => { if let crate::StructLevel::Root = *level { - self.annotations - .push(Instruction::decorate(id, Decoration::Block, &[])); + self.decorate(id, Decoration::Block, &[]); } let mut member_ids = Vec::with_capacity(members.len()); @@ -1092,8 +1091,7 @@ impl Writer { match *binding { crate::Binding::Location(location, interpolation) => { - self.annotations - .push(Instruction::decorate(id, Decoration::Location, &[location])); + self.decorate(id, Decoration::Location, &[location]); let interp_decoration = match interpolation { Some(crate::Interpolation::Linear) => Some(Decoration::NoPerspective), Some(crate::Interpolation::Flat) => Some(Decoration::Flat), @@ -1102,8 +1100,7 @@ impl Writer { Some(crate::Interpolation::Perspective) | None => None, }; if let Some(decoration) = interp_decoration { - self.annotations - .push(Instruction::decorate(id, decoration, &[])); + self.decorate(id, decoration, &[]); } } crate::Binding::BuiltIn(built_in) => { @@ -1136,11 +1133,7 @@ impl Writer { Bi::WorkGroupSize => BuiltIn::WorkgroupSize, }; - self.annotations.push(Instruction::decorate( - id, - Decoration::BuiltIn, - &[built_in as u32], - )); + self.decorate(id, Decoration::BuiltIn, &[built_in as u32]); } } @@ -1177,21 +1170,12 @@ impl Writer { _ => None, }; if let Some(decoration) = access_decoration { - self.annotations - .push(Instruction::decorate(id, decoration, &[])); + self.decorate(id, decoration, &[]); } if let Some(ref res_binding) = global_variable.binding { - self.annotations.push(Instruction::decorate( - id, - Decoration::DescriptorSet, - &[res_binding.group], - )); - self.annotations.push(Instruction::decorate( - id, - Decoration::Binding, - &[res_binding.binding], - )); + self.decorate(id, Decoration::DescriptorSet, &[res_binding.group]); + self.decorate(id, Decoration::Binding, &[res_binding.binding]); } // TODO Initializer is optional and not (yet) included in the IR From 99a9e1e78e3ecee63baa670a71fd5f5a21e9e8d4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 8 Apr 2021 20:23:40 -0700 Subject: [PATCH 0718/2212] Change Binding::Location to a struct-style enum variant. This commit makes no other changes. This is in preparation for adding a third field, at which point tuple variants start to get obscure. --- src/back/glsl/features.rs | 5 ++++- src/back/glsl/mod.rs | 6 +++--- src/back/msl/mod.rs | 10 +++++----- src/back/msl/writer.rs | 6 +++--- src/back/spv/writer.rs | 2 +- src/front/glsl/parser.rs | 6 +++--- src/front/spv/function.rs | 7 ++++--- src/front/spv/mod.rs | 4 ++-- src/front/wgsl/mod.rs | 4 ++-- src/lib.rs | 2 +- src/proc/mod.rs | 2 +- src/valid/analyzer.rs | 5 ++++- src/valid/interface.rs | 2 +- tests/out/shadow.ron | 15 ++++++++++++--- 14 files changed, 46 insertions(+), 30 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 9699f98e1..0404ee03f 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -288,7 +288,10 @@ impl<'a, W> Writer<'a, W> { } } _ => { - if let Some(&Binding::Location(_, Some(interpolation))) = binding { + if let Some(&Binding::Location { + interpolation: Some(interpolation), + .. + }) = binding { match interpolation { Interpolation::Linear => { self.features.request(Features::NOPERSPECTIVE_QUALIFIER) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 97b40f546..f58e6a728 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -242,7 +242,7 @@ struct VaryingName<'a> { impl fmt::Display for VaryingName<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self.binding { - Binding::Location(location, _) => { + Binding::Location { location, .. } => { let prefix = match (self.stage, self.output) { (ShaderStage::Compute, _) => unreachable!(), // pipeline to vertex @@ -794,7 +794,7 @@ impl<'a, W: Write> Writer<'a, W> { } _ => { let (location, interpolation) = match binding { - Some(&Binding::Location(location, interpolation)) => (location, interpolation), + Some(&Binding::Location { location, interpolation }) => (location, interpolation), _ => return Ok(()), }; // Write the interpolation modifier if needed @@ -825,7 +825,7 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important let vname = VaryingName { - binding: &Binding::Location(location, None), + binding: &Binding::Location { location, interpolation: None }, stage: self.entry_point.stage, output, }; diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 0e402e2dd..385e7460c 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -183,21 +183,21 @@ impl Options { ) -> Result { match *binding { crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), - crate::Binding::Location(index, _) => match mode { - LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(index)), - LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(index)), + crate::Binding::Location { location, .. } => match mode { + LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(location)), + LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(location)), LocationMode::Intermediate => Ok(ResolvedBinding::User { prefix: if self.spirv_cross_compatibility { "locn" } else { "loc" }, - index, + index: location, }), LocationMode::Uniform => { log::error!( "Unexpected Binding::Location({}) for the Uniform mode", - index + location ); Err(Error::Validation) } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 086f23768..79a811482 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1821,7 +1821,7 @@ impl Writer { writeln!(self.out, "struct {} {{", stage_in_name)?; for &(ref name_key, ty, binding) in argument_members.iter() { let binding = match binding { - Some(ref binding @ &crate::Binding::Location(..)) => binding, + Some(ref binding @ &crate::Binding::Location { .. }) => binding, _ => continue, }; varying_count += 1; @@ -2044,7 +2044,7 @@ impl Writer { if member_index != 0 { write!(self.out, ", ")?; } - if let Some(crate::Binding::Location(..)) = member.binding { + if let Some(crate::Binding::Location { .. }) = member.binding { write!(self.out, "{}.", varyings_member_name)?; } write!(self.out, "{}", name)?; @@ -2052,7 +2052,7 @@ impl Writer { writeln!(self.out, " }};")?; } _ => { - if let Some(crate::Binding::Location(..)) = arg.binding { + if let Some(crate::Binding::Location { .. }) = arg.binding { writeln!( self.out, "{}const auto {} = {}.{};", diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4b1502a8b..123c0d36c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1090,7 +1090,7 @@ impl Writer { use spirv::{BuiltIn, Decoration}; match *binding { - crate::Binding::Location(location, interpolation) => { + crate::Binding::Location { location, interpolation } => { self.decorate(id, Decoration::Location, &[location]); let interp_decoration = match interpolation { Some(crate::Interpolation::Linear) => Some(Decoration::NoPerspective), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 10eacb5e3..d20a9302f 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -614,9 +614,9 @@ pomelo! { } layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen { - if let Some(&(_, loc)) = l.iter().find(|&q| q.0.as_str() == "location") { + if let Some(&(_, location)) = l.iter().find(|&q| q.0.as_str() == "location") { let interpolation = None; //TODO - StructLayout::Binding(Binding::Location(loc, interpolation)) + StructLayout::Binding(Binding::Location { location, interpolation }) } else if let Some(&(_, binding)) = l.iter().find(|&q| q.0.as_str() == "binding") { let group = if let Some(&(_, set)) = l.iter().find(|&q| q.0.as_str() == "set") { set @@ -1133,7 +1133,7 @@ pomelo! { let interpolation = d.type_qualifiers.iter().find_map(|tq| { if let TypeQualifier::Interpolation(interp) = *tq { Some(interp) } else { None } }); - if let Some(Binding::Location(_, ref mut interp)) = binding { + if let Some(Binding::Location { interpolation: ref mut interp, .. }) = binding { *interp = interpolation; } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 5a5725632..fef875d56 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -213,9 +213,10 @@ impl> super::Parser { }); let mut arg = arg.clone(); if ep.stage == crate::ShaderStage::Fragment { - if let Some(crate::Binding::Location(_, ref mut interpolation @ None)) = - arg.binding - { + if let Some(crate::Binding::Location { + interpolation: ref mut interpolation @ None, + .. + }) = arg.binding { *interpolation = Some(crate::Interpolation::Perspective); // default } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e76b86c74..a0943eed5 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -251,10 +251,10 @@ impl Decoration { } => map_builtin(built_in).map(crate::Binding::BuiltIn), Decoration { built_in: None, - location: Some(loc), + location: Some(location), interpolation, .. - } => Ok(crate::Binding::Location(loc, interpolation)), + } => Ok(crate::Binding::Location { location, interpolation }), _ => Err(Error::MissingDecoration(spirv::Decoration::Location)), } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 8b4853406..2bd5497fd 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -500,8 +500,8 @@ impl BindingParser { fn finish<'a>(self) -> Result, Error<'a>> { match (self.location, self.built_in, self.interpolation) { (None, None, None) => Ok(None), - (Some(loc), None, interpolation) => { - Ok(Some(crate::Binding::Location(loc, interpolation))) + (Some(location), None, interpolation) => { + Ok(Some(crate::Binding::Location { location, interpolation })) } (None, Some(bi), None) => Ok(Some(crate::Binding::BuiltIn(bi))), (location, built_in, interpolation) => Err(Error::InconsistentBinding( diff --git a/src/lib.rs b/src/lib.rs index 151591dc4..918f285ce 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -465,7 +465,7 @@ pub enum Binding { /// Built-in shader variable. BuiltIn(BuiltIn), /// Indexed location. - Location(u32, Option), + Location { location: u32, interpolation: Option }, } /// Pipeline binding information for global resources. diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 55266d2bd..a6d6809a4 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -212,7 +212,7 @@ impl crate::Binding { pub fn to_built_in(&self) -> Option { match *self { Self::BuiltIn(bi) => Some(bi), - Self::Location(..) => None, + Self::Location { .. } => None, } } } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 52e00818f..7b0fff4df 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -344,7 +344,10 @@ impl FunctionInfo { _ => false, }, // only flat inputs are uniform - Some(crate::Binding::Location(_, Some(crate::Interpolation::Flat))) => true, + Some(crate::Binding::Location { + interpolation: Some(crate::Interpolation::Flat), + .. + }) => true, _ => false, }; Uniformity { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 1299b3821..350939a07 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -206,7 +206,7 @@ impl VaryingContext<'_> { return Err(VaryingError::InvalidBuiltInType(built_in)); } } - crate::Binding::Location(location, interpolation) => { + crate::Binding::Location { location, interpolation } => { if !self.location_mask.insert(location as usize) { return Err(VaryingError::BindingCollision { location }); } diff --git a/tests/out/shadow.ron b/tests/out/shadow.ron index 8f603ad07..fe4976907 100644 --- a/tests/out/shadow.ron +++ b/tests/out/shadow.ron @@ -1517,17 +1517,26 @@ ( name: Some("in_normal_fs"), ty: 2, - binding: Some(Location(0, Some(Perspective))), + binding: Some(Location( + location: 0, + interpolation: Some(Perspective), + )), ), ( name: Some("in_position_fs"), ty: 4, - binding: Some(Location(1, Some(Perspective))), + binding: Some(Location( + location: 1, + interpolation: Some(Perspective), + )), ), ], result: Some(( ty: 4, - binding: Some(Location(0, None)), + binding: Some(Location( + location: 0, + interpolation: None, + )), )), local_variables: [], expressions: [ From 0910af2718808e5b3461cf16ae7e296019b20cf9 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 16 Apr 2021 18:26:16 -0700 Subject: [PATCH 0719/2212] [wgsl-in] Implement WGSL `interpolate` syntax from gpuweb PR #1605. Fixes: #670 --- src/back/glsl/features.rs | 20 +- src/back/glsl/mod.rs | 65 ++++-- src/back/spv/writer.rs | 32 ++- src/front/glsl/ast.rs | 4 +- src/front/glsl/lex.rs | 4 +- src/front/glsl/parser.rs | 24 ++- src/front/spv/mod.rs | 8 +- src/front/wgsl/conv.rs | 10 +- src/front/wgsl/mod.rs | 21 +- src/lib.rs | 26 ++- src/valid/interface.rs | 7 +- tests/in/interpolate.wgsl | 16 +- tests/out/interpolate.Fragment.glsl | 14 +- tests/out/interpolate.Vertex.glsl | 30 ++- tests/out/interpolate.msl | 28 ++- tests/out/interpolate.spvasm | 312 ++++++++++++++++------------ tests/out/shadow.ron | 3 + 17 files changed, 392 insertions(+), 232 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 0404ee03f..d5c835f9d 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -1,7 +1,7 @@ use super::{BackendResult, Error, Version, Writer}; use crate::{ - Binding, Bytes, Handle, ImageClass, ImageDimension, Interpolation, ScalarKind, ShaderStage, - StorageClass, StorageFormat, Type, TypeInner, + Binding, Bytes, Handle, ImageClass, ImageDimension, Interpolation, Sampling, ScalarKind, + ShaderStage, StorageClass, StorageFormat, Type, TypeInner, }; use std::io::Write; @@ -289,16 +289,16 @@ impl<'a, W> Writer<'a, W> { } _ => { if let Some(&Binding::Location { - interpolation: Some(interpolation), + interpolation, + sampling, .. }) = binding { - match interpolation { - Interpolation::Linear => { - self.features.request(Features::NOPERSPECTIVE_QUALIFIER) - } - Interpolation::Sample => self.features.request(Features::SAMPLE_QUALIFIER), - _ => (), - }; + if interpolation == Some(Interpolation::Linear) { + self.features.request(Features::NOPERSPECTIVE_QUALIFIER); + } + if sampling == Some(Sampling::Sample) { + self.features.request(Features::SAMPLE_QUALIFIER); + } } } } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index f58e6a728..b8541e0d4 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -48,9 +48,10 @@ use crate::{ valid::{FunctionInfo, ModuleInfo}, Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, - ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ScalarValue, - ShaderStage, Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, - TypeInner, UnaryOperator, + ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, Sampling, ScalarKind, + ScalarValue, ShaderStage, Statement, StorageAccess, StorageClass, StorageFormat, StructMember, + Type, TypeInner, UnaryOperator, + }; use features::FeaturesManager; use std::{ @@ -232,8 +233,10 @@ impl IdGenerator { /// Helper wrapper used to get a name for a varying /// /// Varying have different naming schemes depending on their binding: -/// - Varyings with builtin bindings get the from [`glsl_built_in`](glsl_built_in) -/// - Varyings with location bindings are named `_location_X` where `X` is the location +/// - Varyings with builtin bindings get the from [`glsl_built_in`](glsl_built_in). +/// - Varyings with location bindings are named `_S_location_X` where `S` is a +/// prefix identifying which pipeline stage the varying connects, and `X` is +/// the location. struct VaryingName<'a> { binding: &'a Binding, stage: ShaderStage, @@ -793,16 +796,22 @@ impl<'a, W: Write> Writer<'a, W> { } } _ => { - let (location, interpolation) = match binding { - Some(&Binding::Location { location, interpolation }) => (location, interpolation), + let (location, interpolation, sampling) = match binding { + Some(&Binding::Location { location, interpolation, sampling }) => (location, interpolation, sampling), _ => return Ok(()), }; + // Write the interpolation modifier if needed // - // We ignore all interpolation modifiers that aren't used in input globals in fragment - // shaders or output globals in vertex shaders + // We ignore all interpolation and auxiliary modifiers that aren't used in fragment + // shaders' input globals or vertex shaders' output globals. + let emit_interpolation_and_auxiliary = match self.options.shader_stage { + ShaderStage::Vertex => output, + ShaderStage::Fragment => !output, + _ => false, + }; if let Some(interp) = interpolation { - if self.options.shader_stage == ShaderStage::Fragment { + if emit_interpolation_and_auxiliary { write!(self.out, "{} ", glsl_interpolation(interp))?; } } @@ -811,13 +820,24 @@ impl<'a, W: Write> Writer<'a, W> { if self.options.version.supports_explicit_locations() { write!( self.out, - "layout(location = {}) {} ", - location, - if output { "out" } else { "in" } - )?; - } else { - write!(self.out, "{} ", if output { "out" } else { "in" })?; + "layout(location = {}) ", + location)?; } + + // Write the sampling auxiliary qualifier. + // + // Before GLSL 4.2, the `centroid` and `sample` qualifiers were required to appear + // immediately before the `in` / `out` qualifier, so we'll just follow that rule + // here, regardless of the version. + if let Some(sampling) = sampling { + if emit_interpolation_and_auxiliary { + write!(self.out, "{} ", glsl_sampling(sampling))?; + } + } + + // Write the input/output qualifier. + write!(self.out, "{} ", if output { "out" } else { "in" })?; + // Write the type // `write_type` adds no leading or trailing spaces self.write_type(ty)?; @@ -825,7 +845,7 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important let vname = VaryingName { - binding: &Binding::Location { location, interpolation: None }, + binding: &Binding::Location { location, interpolation: None, sampling: None }, stage: self.entry_point.stage, output, }; @@ -2201,8 +2221,15 @@ fn glsl_interpolation(interpolation: Interpolation) -> &'static str { Interpolation::Perspective => "smooth", Interpolation::Linear => "noperspective", Interpolation::Flat => "flat", - Interpolation::Centroid => "centroid", - Interpolation::Sample => "sample", + } +} + +/// Return the GLSL auxiliary qualifier for the given sampling value. +fn glsl_sampling(sampling: Sampling) -> &'static str { + match sampling { + Sampling::Center => "", + Sampling::Centroid => "centroid", + Sampling::Sample => "sample", } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 123c0d36c..39df6f223 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1090,17 +1090,29 @@ impl Writer { use spirv::{BuiltIn, Decoration}; match *binding { - crate::Binding::Location { location, interpolation } => { + crate::Binding::Location { location, interpolation, sampling } => { self.decorate(id, Decoration::Location, &[location]); - let interp_decoration = match interpolation { - Some(crate::Interpolation::Linear) => Some(Decoration::NoPerspective), - Some(crate::Interpolation::Flat) => Some(Decoration::Flat), - Some(crate::Interpolation::Centroid) => Some(Decoration::Centroid), - Some(crate::Interpolation::Sample) => Some(Decoration::Sample), - Some(crate::Interpolation::Perspective) | None => None, - }; - if let Some(decoration) = interp_decoration { - self.decorate(id, decoration, &[]); + + match interpolation { + // Perspective-correct interpolation is the default in SPIR-V. + None | Some(crate::Interpolation::Perspective) => (), + Some(crate::Interpolation::Flat) => { + self.decorate(id, Decoration::Flat, &[]); + } + Some(crate::Interpolation::Linear) => { + self.decorate(id, Decoration::NoPerspective, &[]); + } + } + + match sampling { + // Center sampling is the default in SPIR-V. + None | Some(crate::Sampling::Center) => (), + Some(crate::Sampling::Centroid) => { + self.decorate(id, Decoration::Centroid, &[]); + } + Some(crate::Sampling::Sample) => { + self.decorate(id, Decoration::Sample, &[]); + } } } crate::Binding::BuiltIn(built_in) => { diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 78f914af5..a832a6fde 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -2,7 +2,8 @@ use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind}; use crate::{ proc::ResolveContext, Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, - RelationalFunction, ResourceBinding, ShaderStage, Statement, StorageClass, Type, UnaryOperator, + RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, + UnaryOperator, }; #[derive(Debug)] @@ -226,6 +227,7 @@ pub enum TypeQualifier { ResourceBinding(ResourceBinding), Binding(Binding), Interpolation(Interpolation), + Sampling(Sampling), } #[derive(Debug)] diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 6f72c5c80..08874dfee 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -66,8 +66,8 @@ impl<'a> Iterator for Lexer<'a> { "flat" => Token::Interpolation((meta, crate::Interpolation::Flat)), "noperspective" => Token::Interpolation((meta, crate::Interpolation::Linear)), "smooth" => Token::Interpolation((meta, crate::Interpolation::Perspective)), - "centroid" => Token::Interpolation((meta, crate::Interpolation::Centroid)), - "sample" => Token::Interpolation((meta, crate::Interpolation::Sample)), + "centroid" => Token::Sampling((meta, crate::Sampling::Centroid)), + "sample" => Token::Sampling((meta, crate::Sampling::Sample)), // values "true" => Token::BoolConstant((meta, true)), "false" => Token::BoolConstant((meta, false)), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index d20a9302f..276529b0b 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -10,7 +10,7 @@ pomelo! { ConstantInner, Expression, Function, FunctionArgument, FunctionResult, GlobalVariable, Handle, Interpolation, - LocalVariable, ResourceBinding, ScalarValue, ScalarKind, + LocalVariable, ResourceBinding, Sampling, ScalarValue, ScalarKind, Statement, StorageAccess, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, }; @@ -120,6 +120,8 @@ pomelo! { %type storage_qualifier StorageQualifier; %type interpolation_qualifier Interpolation; %type Interpolation Interpolation; + %type sampling_qualifier Sampling; + %type Sampling Sampling; // types %type fully_specified_type (Vec, Option>); @@ -613,10 +615,15 @@ pomelo! { i } + sampling_qualifier ::= Sampling((_, s)) { + s + } + layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen { if let Some(&(_, location)) = l.iter().find(|&q| q.0.as_str() == "location") { let interpolation = None; //TODO - StructLayout::Binding(Binding::Location { location, interpolation }) + let sampling = None; //TODO + StructLayout::Binding(Binding::Location { location, interpolation, sampling }) } else if let Some(&(_, binding)) = l.iter().find(|&q| q.0.as_str() == "binding") { let group = if let Some(&(_, set)) = l.iter().find(|&q| q.0.as_str() == "set") { set @@ -670,6 +677,9 @@ pomelo! { single_type_qualifier ::= interpolation_qualifier(i) { TypeQualifier::Interpolation(i) } + single_type_qualifier ::= sampling_qualifier(i) { + TypeQualifier::Sampling(i) + } // single_type_qualifier ::= invariant_qualifier; // single_type_qualifier ::= precise_qualifier; @@ -1133,8 +1143,16 @@ pomelo! { let interpolation = d.type_qualifiers.iter().find_map(|tq| { if let TypeQualifier::Interpolation(interp) = *tq { Some(interp) } else { None } }); - if let Some(Binding::Location { interpolation: ref mut interp, .. }) = binding { + let sampling = d.type_qualifiers.iter().find_map(|tq| { + if let TypeQualifier::Sampling(samp) = *tq { Some(samp) } else { None } + }); + if let Some(Binding::Location { + interpolation: ref mut interp, + sampling: ref mut samp, + .. + }) = binding { *interp = interpolation; + *samp = sampling; } for (id, _initializer) in d.ids_initializers { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a0943eed5..e4d7a1c71 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -220,6 +220,7 @@ struct Decoration { matrix_stride: Option, matrix_major: Option, interpolation: Option, + sampling: Option, flags: DecorationFlags, } @@ -253,8 +254,9 @@ impl Decoration { built_in: None, location: Some(location), interpolation, + sampling, .. - } => Ok(crate::Binding::Location { location, interpolation }), + } => Ok(crate::Binding::Location { location, interpolation, sampling }), _ => Err(Error::MissingDecoration(spirv::Decoration::Location)), } } @@ -504,10 +506,10 @@ impl> Parser { dec.interpolation = Some(crate::Interpolation::Flat); } spirv::Decoration::Centroid => { - dec.interpolation = Some(crate::Interpolation::Centroid); + dec.sampling = Some(crate::Sampling::Centroid); } spirv::Decoration::Sample => { - dec.interpolation = Some(crate::Interpolation::Sample); + dec.sampling = Some(crate::Sampling::Sample); } spirv::Decoration::NonReadable => { dec.flags |= DecorationFlags::NON_READABLE; diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index cd84c0b57..227327ad5 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -44,13 +44,19 @@ pub fn map_interpolation(word: &str) -> Result> match word { "linear" => Ok(crate::Interpolation::Linear), "flat" => Ok(crate::Interpolation::Flat), - "centroid" => Ok(crate::Interpolation::Centroid), - "sample" => Ok(crate::Interpolation::Sample), "perspective" => Ok(crate::Interpolation::Perspective), _ => Err(Error::UnknownAttribute(word)), } } +pub fn map_sampling(word: &str) -> Result> { + match word { + "centroid" => Ok(crate::Sampling::Centroid), + "sample" => Ok(crate::Sampling::Sample), + _ => Err(Error::UnknownAttribute(word)), + } +} + pub fn map_storage_format(word: &str) -> Result> { use crate::StorageFormat as Sf; Ok(match word { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2bd5497fd..cea66700c 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -112,11 +112,12 @@ pub enum Error<'a> { ZeroSizeOrAlign, #[error("not a composite type: {0:?}")] NotCompositeType(Handle), - #[error("Input/output binding is not consistent: location {0:?}, built-in {1:?} and interpolation {2:?}")] + #[error("Input/output binding is not consistent: location {0:?}, built-in {1:?}, interpolation {2:?}, and sampling {3:?}")] InconsistentBinding( Option, Option, Option, + Option, ), #[error("call to local `{0}(..)` can't be resolved")] UnknownLocalFunction(&'a str), @@ -470,6 +471,7 @@ struct BindingParser { location: Option, built_in: Option, interpolation: Option, + sampling: Option, } impl BindingParser { @@ -490,6 +492,10 @@ impl BindingParser { lexer.expect(Token::Paren('('))?; let raw = lexer.next_ident()?; self.interpolation = Some(conv::map_interpolation(raw)?); + if lexer.skip(Token::Separator(',')) { + let raw = lexer.next_ident()?; + self.sampling = Some(conv::map_sampling(raw)?); + } lexer.expect(Token::Paren(')'))?; } _ => return Err(Error::UnknownAttribute(name)), @@ -498,16 +504,17 @@ impl BindingParser { } fn finish<'a>(self) -> Result, Error<'a>> { - match (self.location, self.built_in, self.interpolation) { - (None, None, None) => Ok(None), - (Some(location), None, interpolation) => { - Ok(Some(crate::Binding::Location { location, interpolation })) + match (self.location, self.built_in, self.interpolation, self.sampling) { + (None, None, None, None) => Ok(None), + (Some(location), None, interpolation, sampling) => { + Ok(Some(crate::Binding::Location { location, interpolation, sampling })) } - (None, Some(bi), None) => Ok(Some(crate::Binding::BuiltIn(bi))), - (location, built_in, interpolation) => Err(Error::InconsistentBinding( + (None, Some(bi), None, None) => Ok(Some(crate::Binding::BuiltIn(bi))), + (location, built_in, interpolation, sampling) => Err(Error::InconsistentBinding( location, built_in, interpolation, + sampling, )), } } diff --git a/src/lib.rs b/src/lib.rs index 918f285ce..b95fe251b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -226,11 +226,23 @@ pub enum Interpolation { Linear, /// Indicates that no interpolation will be performed. Flat, - /// When used with multi-sampling rasterization, allow - /// a single interpolation location for an entire pixel. +} + +/// The sampling qualifiers of a binding or struct field. +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum Sampling { + /// Interpolate the value at the center of the pixel. + Center, + + /// Interpolate the value at a point that lies within all samples covered by + /// the fragment within the current primitive. In multisampling, use a + /// single value for all samples in the primitive. Centroid, - /// When used with multi-sampling rasterization, require - /// per-sample interpolation. + + /// Interpolate the value at each sample location. In multisampling, invoke + /// the fragment shader once per sample. Sample, } @@ -465,7 +477,11 @@ pub enum Binding { /// Built-in shader variable. BuiltIn(BuiltIn), /// Indexed location. - Location { location: u32, interpolation: Option }, + Location { + location: u32, + interpolation: Option, + sampling: Option + }, } /// Pipeline binding information for global resources. diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 350939a07..c04116995 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -206,7 +206,7 @@ impl VaryingContext<'_> { return Err(VaryingError::InvalidBuiltInType(built_in)); } } - crate::Binding::Location { location, interpolation } => { + crate::Binding::Location { location, interpolation, sampling } => { if !self.location_mask.insert(location as usize) { return Err(VaryingError::BindingCollision { location }); } @@ -218,6 +218,11 @@ impl VaryingContext<'_> { if !needs_interpolation && interpolation.is_some() { return Err(VaryingError::InvalidInterpolation); } + // It doesn't make sense to specify a sampling when + // `interpolation` is `Flat`, but SPIR-V and GLSL both + // explicitly tolerate such combinations of decorators / + // qualifiers, so we won't complain about that here. + let _ = sampling; match ty_inner.scalar_kind() { Some(crate::ScalarKind::Float) => {} Some(_) diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index 0bdad9692..51eb4fde7 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -1,10 +1,12 @@ struct FragmentInput { [[builtin(position)]] position: vec4; [[location(0), interpolate(flat)]] flat : u32; - [[location(1), interpolate(linear)]] linear: f32; - [[location(2), interpolate(centroid)]] centroid: vec2; - [[location(3), interpolate(sample)]] sample: vec3; - [[location(4), interpolate(perspective)]] perspective: vec4; + [[location(1), interpolate(linear)]] linear : f32; + [[location(2), interpolate(linear,centroid)]] linear_centroid : vec2; + [[location(3), interpolate(linear,sample)]] linear_sample : vec3; + [[location(4), interpolate(perspective)]] perspective : vec4; + [[location(5), interpolate(perspective,centroid)]] perspective_centroid : f32; + [[location(6), interpolate(perspective,sample)]] perspective_sample : f32; }; [[stage(vertex)]] @@ -14,9 +16,11 @@ fn main() -> FragmentInput { out.position = vec4(2.0, 4.0, 5.0, 6.0); out.flat = 8u32; out.linear = 27.0; - out.centroid = vec2(64.0, 125.0); - out.sample = vec3(216.0, 343.0, 512.0); + out.linear_centroid = vec2(64.0, 125.0); + out.linear_sample = vec3(216.0, 343.0, 512.0); out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + out.perspective_centroid = 2197.0; + out.perspective_sample = 2744.0; return out; } diff --git a/tests/out/interpolate.Fragment.glsl b/tests/out/interpolate.Fragment.glsl index 6ec1a66ad..b41599730 100644 --- a/tests/out/interpolate.Fragment.glsl +++ b/tests/out/interpolate.Fragment.glsl @@ -3,19 +3,23 @@ struct FragmentInput { vec4 position; uint flat1; float linear; - vec2 centroid1; - vec3 sample1; + vec2 linear_centroid; + vec3 linear_sample; vec4 perspective; + float perspective_centroid; + float perspective_sample; }; flat in uint _vs2fs_location0; noperspective in float _vs2fs_location1; -centroid in vec2 _vs2fs_location2; -sample in vec3 _vs2fs_location3; +noperspective centroid in vec2 _vs2fs_location2; +noperspective sample in vec3 _vs2fs_location3; smooth in vec4 _vs2fs_location4; +smooth centroid in float _vs2fs_location5; +smooth sample in float _vs2fs_location6; void main() { - FragmentInput val = FragmentInput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1, _vs2fs_location2, _vs2fs_location3, _vs2fs_location4); + FragmentInput val = FragmentInput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1, _vs2fs_location2, _vs2fs_location3, _vs2fs_location4, _vs2fs_location5, _vs2fs_location6); return; } diff --git a/tests/out/interpolate.Vertex.glsl b/tests/out/interpolate.Vertex.glsl index 3f105dccf..e287089a1 100644 --- a/tests/out/interpolate.Vertex.glsl +++ b/tests/out/interpolate.Vertex.glsl @@ -3,31 +3,39 @@ struct FragmentInput { vec4 position; uint flat1; float linear; - vec2 centroid1; - vec3 sample1; + vec2 linear_centroid; + vec3 linear_sample; vec4 perspective; + float perspective_centroid; + float perspective_sample; }; -out uint _vs2fs_location0; -out float _vs2fs_location1; -out vec2 _vs2fs_location2; -out vec3 _vs2fs_location3; -out vec4 _vs2fs_location4; +flat out uint _vs2fs_location0; +noperspective out float _vs2fs_location1; +noperspective centroid out vec2 _vs2fs_location2; +noperspective sample out vec3 _vs2fs_location3; +smooth out vec4 _vs2fs_location4; +smooth centroid out float _vs2fs_location5; +smooth sample out float _vs2fs_location6; void main() { FragmentInput out1; out1.position = vec4(2.0, 4.0, 5.0, 6.0); out1.flat1 = 8u; out1.linear = 27.0; - out1.centroid1 = vec2(64.0, 125.0); - out1.sample1 = vec3(216.0, 343.0, 512.0); + out1.linear_centroid = vec2(64.0, 125.0); + out1.linear_sample = vec3(216.0, 343.0, 512.0); out1.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + out1.perspective_centroid = 2197.0; + out1.perspective_sample = 2744.0; gl_Position = out1.position; _vs2fs_location0 = out1.flat1; _vs2fs_location1 = out1.linear; - _vs2fs_location2 = out1.centroid1; - _vs2fs_location3 = out1.sample1; + _vs2fs_location2 = out1.linear_centroid; + _vs2fs_location3 = out1.linear_sample; _vs2fs_location4 = out1.perspective; + _vs2fs_location5 = out1.perspective_centroid; + _vs2fs_location6 = out1.perspective_sample; return; } diff --git a/tests/out/interpolate.msl b/tests/out/interpolate.msl index 713dc4ef9..d1f7514a4 100644 --- a/tests/out/interpolate.msl +++ b/tests/out/interpolate.msl @@ -5,18 +5,22 @@ struct FragmentInput { metal::float4 position; metal::uint flat; float linear; - metal::float2 centroid; - metal::float3 sample; + metal::float2 linear_centroid; + metal::float3 linear_sample; metal::float4 perspective; + float perspective_centroid; + float perspective_sample; }; struct main1Output { metal::float4 position [[position]]; metal::uint flat [[user(loc0)]]; float linear [[user(loc1)]]; - metal::float2 centroid [[user(loc2)]]; - metal::float3 sample [[user(loc3)]]; + metal::float2 linear_centroid [[user(loc2)]]; + metal::float3 linear_sample [[user(loc3)]]; metal::float4 perspective [[user(loc4)]]; + float perspective_centroid [[user(loc5)]]; + float perspective_sample [[user(loc6)]]; }; vertex main1Output main1( ) { @@ -24,25 +28,29 @@ vertex main1Output main1( out.position = metal::float4(2.0, 4.0, 5.0, 6.0); out.flat = 8u; out.linear = 27.0; - out.centroid = metal::float2(64.0, 125.0); - out.sample = metal::float3(216.0, 343.0, 512.0); + out.linear_centroid = metal::float2(64.0, 125.0); + out.linear_sample = metal::float3(216.0, 343.0, 512.0); out.perspective = metal::float4(729.0, 1000.0, 1331.0, 1728.0); + out.perspective_centroid = 2197.0; + out.perspective_sample = 2744.0; const auto _tmp = out; - return main1Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.centroid, _tmp.sample, _tmp.perspective }; + return main1Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample }; } struct main2Input { metal::uint flat [[user(loc0)]]; float linear [[user(loc1)]]; - metal::float2 centroid [[user(loc2)]]; - metal::float3 sample [[user(loc3)]]; + metal::float2 linear_centroid [[user(loc2)]]; + metal::float3 linear_sample [[user(loc3)]]; metal::float4 perspective [[user(loc4)]]; + float perspective_centroid [[user(loc5)]]; + float perspective_sample [[user(loc6)]]; }; fragment void main2( main2Input varyings1 [[stage_in]] , metal::float4 position [[position]] ) { - const FragmentInput val = { position, varyings1.flat, varyings1.linear, varyings1.centroid, varyings1.sample, varyings1.perspective }; + const FragmentInput val = { position, varyings1.flat, varyings1.linear, varyings1.linear_centroid, varyings1.linear_sample, varyings1.perspective, varyings1.perspective_centroid, varyings1.perspective_sample }; return; } diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm index 112bd1f0f..1fa0dfbd4 100644 --- a/tests/out/interpolate.spvasm +++ b/tests/out/interpolate.spvasm @@ -1,63 +1,83 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 95 +; Bound: 109 OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %38 "main" %27 %29 %31 %33 %35 %37 -OpEntryPoint Fragment %93 "main" %76 %79 %82 %85 %88 %91 -OpExecutionMode %93 OriginUpperLeft +OpEntryPoint Vertex %42 "main" %29 %31 %33 %35 %37 %39 %40 %41 +OpEntryPoint Fragment %107 "main" %86 %89 %92 %95 %98 %101 %103 %105 +OpExecutionMode %107 OriginUpperLeft OpSource GLSL 450 -OpName %23 "FragmentInput" -OpMemberName %23 0 "position" -OpMemberName %23 1 "flat" -OpMemberName %23 2 "linear" -OpMemberName %23 3 "centroid" -OpMemberName %23 4 "sample" -OpMemberName %23 5 "perspective" -OpName %24 "out" -OpName %27 "position" -OpName %29 "flat" -OpName %31 "linear" -OpName %33 "centroid" -OpName %35 "sample" -OpName %37 "perspective" -OpName %38 "main" -OpName %76 "position" -OpName %79 "flat" -OpName %82 "linear" -OpName %85 "centroid" -OpName %88 "sample" -OpName %91 "perspective" -OpName %93 "main" -OpMemberDecorate %23 0 Offset 0 -OpMemberDecorate %23 1 Offset 16 -OpMemberDecorate %23 2 Offset 20 -OpMemberDecorate %23 3 Offset 24 -OpMemberDecorate %23 4 Offset 32 -OpMemberDecorate %23 5 Offset 48 -OpDecorate %27 BuiltIn Position -OpDecorate %29 Location 0 -OpDecorate %29 Flat -OpDecorate %31 Location 1 -OpDecorate %31 NoPerspective -OpDecorate %33 Location 2 -OpDecorate %33 Centroid -OpDecorate %35 Location 3 -OpDecorate %35 Sample -OpDecorate %37 Location 4 -OpDecorate %76 BuiltIn FragCoord -OpDecorate %79 Location 0 -OpDecorate %79 Flat -OpDecorate %82 Location 1 -OpDecorate %82 NoPerspective -OpDecorate %85 Location 2 -OpDecorate %85 Centroid -OpDecorate %88 Location 3 -OpDecorate %88 Sample -OpDecorate %91 Location 4 +OpName %25 "FragmentInput" +OpMemberName %25 0 "position" +OpMemberName %25 1 "flat" +OpMemberName %25 2 "linear" +OpMemberName %25 3 "linear_centroid" +OpMemberName %25 4 "linear_sample" +OpMemberName %25 5 "perspective" +OpMemberName %25 6 "perspective_centroid" +OpMemberName %25 7 "perspective_sample" +OpName %26 "out" +OpName %29 "position" +OpName %31 "flat" +OpName %33 "linear" +OpName %35 "linear_centroid" +OpName %37 "linear_sample" +OpName %39 "perspective" +OpName %40 "perspective_centroid" +OpName %41 "perspective_sample" +OpName %42 "main" +OpName %86 "position" +OpName %89 "flat" +OpName %92 "linear" +OpName %95 "linear_centroid" +OpName %98 "linear_sample" +OpName %101 "perspective" +OpName %103 "perspective_centroid" +OpName %105 "perspective_sample" +OpName %107 "main" +OpMemberDecorate %25 0 Offset 0 +OpMemberDecorate %25 1 Offset 16 +OpMemberDecorate %25 2 Offset 20 +OpMemberDecorate %25 3 Offset 24 +OpMemberDecorate %25 4 Offset 32 +OpMemberDecorate %25 5 Offset 48 +OpMemberDecorate %25 6 Offset 64 +OpMemberDecorate %25 7 Offset 68 +OpDecorate %29 BuiltIn Position +OpDecorate %31 Location 0 +OpDecorate %31 Flat +OpDecorate %33 Location 1 +OpDecorate %33 NoPerspective +OpDecorate %35 Location 2 +OpDecorate %35 NoPerspective +OpDecorate %35 Centroid +OpDecorate %37 Location 3 +OpDecorate %37 NoPerspective +OpDecorate %37 Sample +OpDecorate %39 Location 4 +OpDecorate %40 Location 5 +OpDecorate %40 Centroid +OpDecorate %41 Location 6 +OpDecorate %41 Sample +OpDecorate %86 BuiltIn FragCoord +OpDecorate %89 Location 0 +OpDecorate %89 Flat +OpDecorate %92 Location 1 +OpDecorate %92 NoPerspective +OpDecorate %95 Location 2 +OpDecorate %95 NoPerspective +OpDecorate %95 Centroid +OpDecorate %98 Location 3 +OpDecorate %98 NoPerspective +OpDecorate %98 Sample +OpDecorate %101 Location 4 +OpDecorate %103 Location 5 +OpDecorate %103 Centroid +OpDecorate %105 Location 6 +OpDecorate %105 Sample %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 2.0 @@ -76,97 +96,115 @@ OpDecorate %91 Location 4 %17 = OpConstant %4 1000.0 %18 = OpConstant %4 1331.0 %19 = OpConstant %4 1728.0 -%20 = OpTypeVector %4 4 -%21 = OpTypeVector %4 2 -%22 = OpTypeVector %4 3 -%23 = OpTypeStruct %20 %9 %4 %21 %22 %20 -%25 = OpTypePointer Function %23 -%28 = OpTypePointer Output %20 -%27 = OpVariable %28 Output -%30 = OpTypePointer Output %9 +%20 = OpConstant %4 2197.0 +%21 = OpConstant %4 2744.0 +%22 = OpTypeVector %4 4 +%23 = OpTypeVector %4 2 +%24 = OpTypeVector %4 3 +%25 = OpTypeStruct %22 %9 %4 %23 %24 %22 %4 %4 +%27 = OpTypePointer Function %25 +%30 = OpTypePointer Output %22 %29 = OpVariable %30 Output -%32 = OpTypePointer Output %4 +%32 = OpTypePointer Output %9 %31 = OpVariable %32 Output -%34 = OpTypePointer Output %21 +%34 = OpTypePointer Output %4 %33 = OpVariable %34 Output -%36 = OpTypePointer Output %22 +%36 = OpTypePointer Output %23 %35 = OpVariable %36 Output -%37 = OpVariable %28 Output -%39 = OpTypeFunction %2 -%41 = OpTypePointer Function %20 -%43 = OpTypeInt 32 1 -%44 = OpConstant %43 0 -%46 = OpTypePointer Function %9 -%47 = OpConstant %43 1 -%49 = OpTypePointer Function %4 -%50 = OpConstant %43 2 -%52 = OpTypePointer Function %21 -%54 = OpConstant %43 3 -%56 = OpTypePointer Function %22 -%58 = OpConstant %43 4 -%61 = OpConstant %43 5 -%66 = OpTypePointer Output %4 -%77 = OpTypePointer Input %20 -%76 = OpVariable %77 Input -%80 = OpTypePointer Input %9 -%79 = OpVariable %80 Input -%83 = OpTypePointer Input %4 -%82 = OpVariable %83 Input -%86 = OpTypePointer Input %21 -%85 = OpVariable %86 Input -%89 = OpTypePointer Input %22 -%88 = OpVariable %89 Input -%91 = OpVariable %77 Input -%38 = OpFunction %2 None %39 -%26 = OpLabel -%24 = OpVariable %25 Function -OpBranch %40 -%40 = OpLabel -%42 = OpCompositeConstruct %20 %3 %5 %6 %7 -%45 = OpAccessChain %41 %24 %44 -OpStore %45 %42 -%48 = OpAccessChain %46 %24 %47 -OpStore %48 %8 -%51 = OpAccessChain %49 %24 %50 -OpStore %51 %10 -%53 = OpCompositeConstruct %21 %11 %12 -%55 = OpAccessChain %52 %24 %54 -OpStore %55 %53 -%57 = OpCompositeConstruct %22 %13 %14 %15 -%59 = OpAccessChain %56 %24 %58 +%38 = OpTypePointer Output %24 +%37 = OpVariable %38 Output +%39 = OpVariable %30 Output +%40 = OpVariable %34 Output +%41 = OpVariable %34 Output +%43 = OpTypeFunction %2 +%45 = OpTypePointer Function %22 +%47 = OpTypeInt 32 1 +%48 = OpConstant %47 0 +%50 = OpTypePointer Function %9 +%51 = OpConstant %47 1 +%53 = OpTypePointer Function %4 +%54 = OpConstant %47 2 +%56 = OpTypePointer Function %23 +%58 = OpConstant %47 3 +%60 = OpTypePointer Function %24 +%62 = OpConstant %47 4 +%65 = OpConstant %47 5 +%67 = OpConstant %47 6 +%69 = OpConstant %47 7 +%74 = OpTypePointer Output %4 +%87 = OpTypePointer Input %22 +%86 = OpVariable %87 Input +%90 = OpTypePointer Input %9 +%89 = OpVariable %90 Input +%93 = OpTypePointer Input %4 +%92 = OpVariable %93 Input +%96 = OpTypePointer Input %23 +%95 = OpVariable %96 Input +%99 = OpTypePointer Input %24 +%98 = OpVariable %99 Input +%101 = OpVariable %87 Input +%103 = OpVariable %93 Input +%105 = OpVariable %93 Input +%42 = OpFunction %2 None %43 +%28 = OpLabel +%26 = OpVariable %27 Function +OpBranch %44 +%44 = OpLabel +%46 = OpCompositeConstruct %22 %3 %5 %6 %7 +%49 = OpAccessChain %45 %26 %48 +OpStore %49 %46 +%52 = OpAccessChain %50 %26 %51 +OpStore %52 %8 +%55 = OpAccessChain %53 %26 %54 +OpStore %55 %10 +%57 = OpCompositeConstruct %23 %11 %12 +%59 = OpAccessChain %56 %26 %58 OpStore %59 %57 -%60 = OpCompositeConstruct %20 %16 %17 %18 %19 -%62 = OpAccessChain %41 %24 %61 -OpStore %62 %60 -%63 = OpLoad %23 %24 -%64 = OpCompositeExtract %20 %63 0 -OpStore %27 %64 -%65 = OpAccessChain %66 %27 %47 -%67 = OpLoad %4 %65 -%68 = OpFNegate %4 %67 -OpStore %65 %68 -%69 = OpCompositeExtract %9 %63 1 -OpStore %29 %69 -%70 = OpCompositeExtract %4 %63 2 -OpStore %31 %70 -%71 = OpCompositeExtract %21 %63 3 -OpStore %33 %71 -%72 = OpCompositeExtract %22 %63 4 -OpStore %35 %72 -%73 = OpCompositeExtract %20 %63 5 -OpStore %37 %73 +%61 = OpCompositeConstruct %24 %13 %14 %15 +%63 = OpAccessChain %60 %26 %62 +OpStore %63 %61 +%64 = OpCompositeConstruct %22 %16 %17 %18 %19 +%66 = OpAccessChain %45 %26 %65 +OpStore %66 %64 +%68 = OpAccessChain %53 %26 %67 +OpStore %68 %20 +%70 = OpAccessChain %53 %26 %69 +OpStore %70 %21 +%71 = OpLoad %25 %26 +%72 = OpCompositeExtract %22 %71 0 +OpStore %29 %72 +%73 = OpAccessChain %74 %29 %51 +%75 = OpLoad %4 %73 +%76 = OpFNegate %4 %75 +OpStore %73 %76 +%77 = OpCompositeExtract %9 %71 1 +OpStore %31 %77 +%78 = OpCompositeExtract %4 %71 2 +OpStore %33 %78 +%79 = OpCompositeExtract %23 %71 3 +OpStore %35 %79 +%80 = OpCompositeExtract %24 %71 4 +OpStore %37 %80 +%81 = OpCompositeExtract %22 %71 5 +OpStore %39 %81 +%82 = OpCompositeExtract %4 %71 6 +OpStore %40 %82 +%83 = OpCompositeExtract %4 %71 7 +OpStore %41 %83 OpReturn OpFunctionEnd -%93 = OpFunction %2 None %39 -%74 = OpLabel -%78 = OpLoad %20 %76 -%81 = OpLoad %9 %79 -%84 = OpLoad %4 %82 -%87 = OpLoad %21 %85 -%90 = OpLoad %22 %88 -%92 = OpLoad %20 %91 -%75 = OpCompositeConstruct %23 %78 %81 %84 %87 %90 %92 -OpBranch %94 -%94 = OpLabel +%107 = OpFunction %2 None %43 +%84 = OpLabel +%88 = OpLoad %22 %86 +%91 = OpLoad %9 %89 +%94 = OpLoad %4 %92 +%97 = OpLoad %23 %95 +%100 = OpLoad %24 %98 +%102 = OpLoad %22 %101 +%104 = OpLoad %4 %103 +%106 = OpLoad %4 %105 +%85 = OpCompositeConstruct %25 %88 %91 %94 %97 %100 %102 %104 %106 +OpBranch %108 +%108 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/shadow.ron b/tests/out/shadow.ron index fe4976907..8a4a26774 100644 --- a/tests/out/shadow.ron +++ b/tests/out/shadow.ron @@ -1520,6 +1520,7 @@ binding: Some(Location( location: 0, interpolation: Some(Perspective), + sampling: None, )), ), ( @@ -1528,6 +1529,7 @@ binding: Some(Location( location: 1, interpolation: Some(Perspective), + sampling: None, )), ), ], @@ -1536,6 +1538,7 @@ binding: Some(Location( location: 0, interpolation: None, + sampling: None, )), )), local_variables: [], From 4f442ff8ccedbfb745c47f8006f035b83943fbcf Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 16 Apr 2021 18:06:28 -0700 Subject: [PATCH 0720/2212] Require binding interpolation to be resolved by the front end. When validating IR, verify that all `Binding`s for vertex shader outputs and fragment shader inputs, whether directly in the argument or result, or applied to a struct member, has specified an interpolation and sampling, not `None`. This ensures that front ends explicitly state their policies, rather than coasting through on back ends' default behavior. In practice, all our front ends have very similar defaults, so provide a utility function on `Module` to apply these rules. Use this utility function in the SPIR-V and WGSL front ends; GLSL seems to already fill in interpolation as required. --- src/back/glsl/mod.rs | 12 ++-- src/front/spv/function.rs | 2 + src/front/wgsl/mod.rs | 5 ++ src/proc/interpolator.rs | 119 +++++++++++++++++++++++++++++++++ src/proc/mod.rs | 1 + src/valid/interface.rs | 33 +++++---- tests/out/quad.Fragment.glsl | 2 +- tests/out/quad.Vertex.glsl | 2 +- tests/out/shadow.Fragment.glsl | 4 +- tests/out/shadow.ron | 4 +- tests/out/skybox.Fragment.glsl | 2 +- tests/out/skybox.Vertex.glsl | 2 +- 12 files changed, 162 insertions(+), 26 deletions(-) create mode 100644 src/proc/interpolator.rs diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b8541e0d4..11b4c2fd0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -831,7 +831,9 @@ impl<'a, W: Write> Writer<'a, W> { // here, regardless of the version. if let Some(sampling) = sampling { if emit_interpolation_and_auxiliary { - write!(self.out, "{} ", glsl_sampling(sampling))?; + if let Some(qualifier) = glsl_sampling(sampling) { + write!(self.out, "{} ", qualifier)?; + } } } @@ -2225,11 +2227,11 @@ fn glsl_interpolation(interpolation: Interpolation) -> &'static str { } /// Return the GLSL auxiliary qualifier for the given sampling value. -fn glsl_sampling(sampling: Sampling) -> &'static str { +fn glsl_sampling(sampling: Sampling) -> Option<&'static str> { match sampling { - Sampling::Center => "", - Sampling::Centroid => "centroid", - Sampling::Sample => "sample", + Sampling::Center => None, + Sampling::Centroid => Some("centroid"), + Sampling::Sample => Some("sample"), } } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index fef875d56..15e969d5d 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -361,6 +361,8 @@ impl> super::Parser { }); } + module.apply_common_default_interpolation(); + self.lookup_expression.clear(); self.lookup_sampled_image.clear(); Ok(()) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index cea66700c..8d4baa4c4 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -507,6 +507,10 @@ impl BindingParser { match (self.location, self.built_in, self.interpolation, self.sampling) { (None, None, None, None) => Ok(None), (Some(location), None, interpolation, sampling) => { + // Before handing over the completed `Module`, we call + // `apply_common_default_interpolation` to ensure that the interpolation and + // sampling have been explicitly specified on all vertex shader output and fragment + // shader input user bindings, so leaving them potentially `None` here is fine. Ok(Some(crate::Binding::Location { location, interpolation, sampling })) } (None, Some(bi), None, None) => Ok(Some(crate::Binding::BuiltIn(bi))), @@ -2769,6 +2773,7 @@ impl Parser { log::error!("Reached the end of file, but scopes are not closed"); return Err(Error::Other.as_parse_error(lexer.source)); }; + module.apply_common_default_interpolation(); return Ok(module); } } diff --git a/src/proc/interpolator.rs b/src/proc/interpolator.rs new file mode 100644 index 000000000..3a5e7e8cb --- /dev/null +++ b/src/proc/interpolator.rs @@ -0,0 +1,119 @@ +pub use crate::{Arena, Handle}; + +impl crate::Module { + /// Apply the usual default interpolation for vertex shader outputs and fragment shader inputs. + /// + /// For every [`Binding`] that is a vertex shader output or a fragment shader + /// input, and that has an `interpolation` or `sampling` of `None`, assign a + /// default interpolation and sampling as follows: + /// + /// - If the `Binding`'s type contains only 32-bit floating-point values or + /// vectors of such, default its interpolation to `Perspective` and its + /// sampling to `Center`. + /// + /// - Otherwise, mark its interpolation as `Flat`. + /// + /// When struct appear in input or output types, apply these rules to their + /// leaves, since those are the things that actually get assigned locations. + /// + /// This function is a utility front ends may use to satisfy the Naga IR's + /// requirement that all I/O `Binding`s from the vertex shader to the + /// fragment shader must have non-`None` `interpolation` values. This + /// requirement is meant to ensure that input languages' policies have been + /// applied appropriately. + /// + /// All the shader languages Naga supports have similar rules: + /// perspective-correct, center-sampled interpolation is the default for any + /// binding that can vary, and everything else either defaults to flat, or + /// requires an explicit flat qualifier/attribute/what-have-you. + /// + /// [`Binding`]: super::Binding + pub fn apply_common_default_interpolation(&mut self) { + use crate::{Binding, ScalarKind, Type, TypeInner}; + + /// Choose a default interpolation for a function argument or result. + /// + /// `binding` refers to the `Binding` whose type is `ty`. If `ty` is a struct, then it's the + /// bindings of the struct's members that we care about, and the binding of the struct + /// itself is meaningless, so `binding` should be `None`. + fn default_binding_or_struct(binding: &mut Option, + ty: Handle, + types: &mut Arena) + { + match types.get_mut(ty).inner { + // A struct. It's the individual members we care about, so recurse. + TypeInner::Struct { members: ref mut m, .. } => { + // To choose the right interpolations for `members`, we must consult other + // elements of `types`. But both `members` and the types it refers to are stored + // in `types`, and Rust won't let us mutate one element of the `Arena`'s `Vec` + // while reading others. + // + // So, temporarily swap the member list out its type, assign appropriate + // interpolations to its members, and then swap the list back in. + use std::mem::replace; + let mut members = replace(m, vec![]); + + for member in &mut members { + default_binding_or_struct(&mut member.binding, member.ty, types); + } + + // Swap the member list back in. It's essential that we call `types.get_mut` + // afresh here, rather than just using `m`: it's only because `m` was dead that + // we were able to pass `types` to the recursive call. + match types.get_mut(ty).inner { + TypeInner::Struct { members: ref mut m, .. } => replace(m, members), + _ => unreachable!("ty must be a struct"), + }; + } + + // Some interpolatable type. + // + // GLSL has 64-bit floats, but it won't interpolate them. WGSL and MSL only have + // 32-bit floats. SPIR-V has 16- and 64-bit float capabilities, but Vulkan is vague + // about what can and cannot be interpolated. + TypeInner::Scalar { kind: ScalarKind::Float, width: 4 } | + TypeInner::Vector { kind: ScalarKind::Float, width: 4, .. } => { + // unwrap: all `EntryPoint` arguments or return values must either be structures + // or have a `Binding`. + let binding = binding.as_mut().unwrap(); + if let Binding::Location { ref mut interpolation, ref mut sampling, .. } = *binding { + if interpolation.is_none() { + *interpolation = Some(crate::Interpolation::Perspective); + } + if sampling.is_none() && *interpolation != Some(crate::Interpolation::Flat) { + *sampling = Some(crate::Sampling::Center); + } + } + } + + // Some type that can't be interpolated. + _ => { + // unwrap: all `EntryPoint` arguments or return values must either be structures + // or have a `Binding`. + let binding = binding.as_mut().unwrap(); + if let Binding::Location { ref mut interpolation, ref mut sampling, .. } = *binding { + *interpolation = Some(crate::Interpolation::Flat); + *sampling = None; + } + } + } + } + + for ep in &mut self.entry_points { + let function = &mut ep.function; + match ep.stage { + crate::ShaderStage::Fragment => { + for arg in &mut function.arguments { + default_binding_or_struct(&mut arg.binding, arg.ty, &mut self.types); + } + } + crate::ShaderStage::Vertex => { + if let Some(result) = function.result.as_mut() { + default_binding_or_struct(&mut result.binding, result.ty, &mut self.types); + } + } + _ => (), + } + } + } +} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index a6d6809a4..27f5039f4 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,5 +1,6 @@ //! Module processing functionality. +mod interpolator; mod namer; mod terminator; mod typifier; diff --git a/src/valid/interface.rs b/src/valid/interface.rs index c04116995..63541895b 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -36,6 +36,8 @@ pub enum VaryingError { InvalidType(Handle), #[error("Interpolation is not valid")] InvalidInterpolation, + #[error("Interpolation must be specified on vertex shader outputs and fragment shader inputs")] + MissingInterpolation, #[error("BuiltIn {0:?} is not available at this stage")] InvalidBuiltInStage(crate::BuiltIn), #[error("BuiltIn type for {0:?} is invalid")] @@ -210,28 +212,33 @@ impl VaryingContext<'_> { if !self.location_mask.insert(location as usize) { return Err(VaryingError::BindingCollision { location }); } + + // Values passed from the vertex shader to the fragment shader must have their + // interpolation defaulted (i.e. not `None`) by the front end, as appropriate for + // that language. For anything other than floating-point scalars and vectors, the + // interpolation must be `Flat`. let needs_interpolation = match self.stage { crate::ShaderStage::Vertex => self.output, crate::ShaderStage::Fragment => !self.output, _ => false, }; - if !needs_interpolation && interpolation.is_some() { - return Err(VaryingError::InvalidInterpolation); - } - // It doesn't make sense to specify a sampling when - // `interpolation` is `Flat`, but SPIR-V and GLSL both - // explicitly tolerate such combinations of decorators / + + // It doesn't make sense to specify a sampling when `interpolation` is `Flat`, but + // SPIR-V and GLSL both explicitly tolerate such combinations of decorators / // qualifiers, so we won't complain about that here. let _ = sampling; + match ty_inner.scalar_kind() { - Some(crate::ScalarKind::Float) => {} - Some(_) - if needs_interpolation - && interpolation != Some(crate::Interpolation::Flat) => - { - return Err(VaryingError::InvalidInterpolation); + Some(crate::ScalarKind::Float) => { + if needs_interpolation && interpolation.is_none() { + return Err(VaryingError::MissingInterpolation); + } + } + Some(_) => { + if needs_interpolation && interpolation != Some(crate::Interpolation::Flat) { + return Err(VaryingError::InvalidInterpolation); + } } - Some(_) => {} None => return Err(VaryingError::InvalidType(self.ty)), } } diff --git a/tests/out/quad.Fragment.glsl b/tests/out/quad.Fragment.glsl index 7122843b3..8062e3d20 100644 --- a/tests/out/quad.Fragment.glsl +++ b/tests/out/quad.Fragment.glsl @@ -9,7 +9,7 @@ struct VertexOutput { uniform highp sampler2D _group_0_binding_0; -layout(location = 0) in vec2 _vs2fs_location0; +smooth layout(location = 0) in vec2 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { diff --git a/tests/out/quad.Vertex.glsl b/tests/out/quad.Vertex.glsl index ccd93c498..751d8c592 100644 --- a/tests/out/quad.Vertex.glsl +++ b/tests/out/quad.Vertex.glsl @@ -9,7 +9,7 @@ struct VertexOutput { layout(location = 0) in vec2 _p2vs_location0; layout(location = 1) in vec2 _p2vs_location1; -layout(location = 0) out vec2 _vs2fs_location0; +smooth layout(location = 0) out vec2 _vs2fs_location0; void main() { vec2 pos = _p2vs_location0; diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index be7f69466..b045c7250 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -18,8 +18,8 @@ readonly buffer Lights_block_1 { uniform highp sampler2DArrayShadow _group_0_binding_2; -layout(location = 0) in vec3 _vs2fs_location0; -layout(location = 1) in vec4 _vs2fs_location1; +smooth layout(location = 0) in vec3 _vs2fs_location0; +smooth layout(location = 1) in vec4 _vs2fs_location1; layout(location = 0) out vec4 _fs2p_location0; float fetch_shadow(uint light_id, vec4 homogeneous_coords) { diff --git a/tests/out/shadow.ron b/tests/out/shadow.ron index 8a4a26774..e99b3c012 100644 --- a/tests/out/shadow.ron +++ b/tests/out/shadow.ron @@ -1520,7 +1520,7 @@ binding: Some(Location( location: 0, interpolation: Some(Perspective), - sampling: None, + sampling: Some(Center), )), ), ( @@ -1529,7 +1529,7 @@ binding: Some(Location( location: 1, interpolation: Some(Perspective), - sampling: None, + sampling: Some(Center), )), ), ], diff --git a/tests/out/skybox.Fragment.glsl b/tests/out/skybox.Fragment.glsl index 11f715ee7..c8a25b448 100644 --- a/tests/out/skybox.Fragment.glsl +++ b/tests/out/skybox.Fragment.glsl @@ -9,7 +9,7 @@ struct VertexOutput { uniform highp samplerCube _group_0_binding_1; -layout(location = 0) in vec3 _vs2fs_location0; +smooth layout(location = 0) in vec3 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { diff --git a/tests/out/skybox.Vertex.glsl b/tests/out/skybox.Vertex.glsl index cc327f6a3..e76121da3 100644 --- a/tests/out/skybox.Vertex.glsl +++ b/tests/out/skybox.Vertex.glsl @@ -12,7 +12,7 @@ uniform Data_block_0 { mat4x4 view; } _group_0_binding_0; -layout(location = 0) out vec3 _vs2fs_location0; +smooth layout(location = 0) out vec3 _vs2fs_location0; void main() { uint vertex_index = uint(gl_VertexID); From fc39ea8877a585f3aae12c9776032cfada789547 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 18 Apr 2021 17:45:51 -0700 Subject: [PATCH 0721/2212] [msl-out]: ResolvedBinding::try_fmt: Simplify error handling. --- src/back/msl/mod.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 385e7460c..4181e8200 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -286,23 +286,24 @@ impl ResolvedBinding { Bi::WorkGroupId => "threadgroup_position_in_grid", Bi::WorkGroupSize => "dispatch_threads_per_threadgroup", }; - Ok(write!(out, "{}", name)?) + write!(out, "{}", name)?; } - Self::Attribute(index) => Ok(write!(out, "attribute({})", index)?), - Self::Color(index) => Ok(write!(out, "color({})", index)?), - Self::User { prefix, index } => Ok(write!(out, "user({}{})", prefix, index)?), + Self::Attribute(index) => write!(out, "attribute({})", index)?, + Self::Color(index) => write!(out, "color({})", index)?, + Self::User { prefix, index } => write!(out, "user({}{})", prefix, index)?, Self::Resource(ref target) => { if let Some(id) = target.buffer { - Ok(write!(out, "buffer({})", id)?) + write!(out, "buffer({})", id)?; } else if let Some(id) = target.texture { - Ok(write!(out, "texture({})", id)?) + write!(out, "texture({})", id)?; } else if let Some(BindSamplerTarget::Resource(id)) = target.sampler { - Ok(write!(out, "sampler({})", id)?) + write!(out, "sampler({})", id)?; } else { - Err(Error::UnimplementedBindTarget(target.clone())) + return Err(Error::UnimplementedBindTarget(target.clone())); } } } + Ok(()) } fn try_fmt_decorated(&self, out: &mut W, terminator: &str) -> Result<(), Error> { From 9cd6fd9c205a57824644d0baedc6c15997be1e36 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 18 Apr 2021 22:11:00 -0700 Subject: [PATCH 0722/2212] [msl-out]: Generate interpolation qualifiers. --- src/back/msl/mod.rs | 68 +++++++++++++++++++++++++++++++++++-- tests/out/collatz.msl | 2 +- tests/out/image-copy.msl | 4 +-- tests/out/interpolate.msl | 28 +++++++-------- tests/out/quad-vert.msl | 2 +- tests/out/quad.msl | 8 ++--- tests/out/shadow.msl | 12 +++---- tests/out/skybox.msl | 4 +-- tests/out/texture-array.msl | 10 +++--- 9 files changed, 100 insertions(+), 38 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 4181e8200..92b80ffa0 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -84,10 +84,25 @@ enum ResolvedBinding { BuiltIn(crate::BuiltIn), Attribute(u32), Color(u32), - User { prefix: &'static str, index: u32 }, + User { + prefix: &'static str, + index: u32, + interpolation: ResolvedInterpolation + }, Resource(BindTarget), } +#[derive(Copy, Clone)] +enum ResolvedInterpolation { + CenterPerspective, + CenterNoPerspective, + CentroidPerspective, + CentroidNoPerspective, + SamplePerspective, + SampleNoPerspective, + Flat, +} + // Note: some of these should be removed in favor of proper IR validation. #[derive(Debug, thiserror::Error)] @@ -183,7 +198,7 @@ impl Options { ) -> Result { match *binding { crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), - crate::Binding::Location { location, .. } => match mode { + crate::Binding::Location { location, interpolation, sampling } => match mode { LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(location)), LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(location)), LocationMode::Intermediate => Ok(ResolvedBinding::User { @@ -193,6 +208,14 @@ impl Options { "loc" }, index: location, + interpolation: { + // unwrap: The verifier ensures that vertex shader outputs and fragment + // shader inputs always have fully specified interpolation, and that + // sampling is `None` only for Flat interpolation. + let interpolation = interpolation.unwrap(); + let sampling = sampling.unwrap_or(crate::Sampling::Center); + ResolvedInterpolation::from_binding(interpolation, sampling) + } }), LocationMode::Uniform => { log::error!( @@ -220,6 +243,7 @@ impl Options { None if self.fake_missing_bindings => Ok(ResolvedBinding::User { prefix: "fake", index: 0, + interpolation: ResolvedInterpolation::CenterPerspective, }), None => Err(EntryPointError::MissingBinding(source)), } @@ -244,6 +268,7 @@ impl Options { None if self.fake_missing_bindings => Ok(ResolvedBinding::User { prefix: "fake", index: 0, + interpolation: ResolvedInterpolation::CenterPerspective, }), None => Err(EntryPointError::MissingPushConstants(stage)), } @@ -290,7 +315,10 @@ impl ResolvedBinding { } Self::Attribute(index) => write!(out, "attribute({})", index)?, Self::Color(index) => write!(out, "color({})", index)?, - Self::User { prefix, index } => write!(out, "user({}{})", prefix, index)?, + Self::User { prefix, index, interpolation } => { + write!(out, "user({}{}), ", prefix, index)?; + interpolation.try_fmt(out)?; + } Self::Resource(ref target) => { if let Some(id) = target.buffer { write!(out, "buffer({})", id)?; @@ -315,6 +343,40 @@ impl ResolvedBinding { } } +impl ResolvedInterpolation { + fn from_binding(interpolation: crate::Interpolation, + sampling: crate::Sampling) + -> Self +{ + use crate::Interpolation as I; + use crate::Sampling as S; + + match (interpolation, sampling) { + (I::Perspective, S::Center) => Self::CenterPerspective, + (I::Perspective, S::Centroid) => Self::CentroidPerspective, + (I::Perspective, S::Sample) => Self::SamplePerspective, + (I::Linear, S::Center) => Self::CenterNoPerspective, + (I::Linear, S::Centroid) => Self::CentroidNoPerspective, + (I::Linear, S::Sample) => Self::SampleNoPerspective, + (I::Flat, _) => Self::Flat, + } + } + + fn try_fmt(self, out: &mut W) -> Result<(), Error> { + let identifier = match self { + Self::CenterPerspective => "center_perspective", + Self::CenterNoPerspective => "center_no_perspective", + Self::CentroidPerspective => "centroid_perspective", + Self::CentroidNoPerspective => "centroid_no_perspective", + Self::SamplePerspective => "sample_perspective", + Self::SampleNoPerspective => "sample_no_perspective", + Self::Flat => "flat", + }; + out.write_str(identifier)?; + Ok(()) + } +} + /// Information about a translated module that is required /// for the use of the result. pub struct TranslationInfo { diff --git a/tests/out/collatz.msl b/tests/out/collatz.msl index 403789659..02a976116 100644 --- a/tests/out/collatz.msl +++ b/tests/out/collatz.msl @@ -30,7 +30,7 @@ struct main1Input { }; kernel void main1( metal::uint3 global_id [[thread_position_in_grid]] -, device PrimeIndices& v_indices [[user(fake0)]] +, device PrimeIndices& v_indices [[user(fake0), center_perspective]] ) { metal::uint _e9 = collatz_iterations(v_indices.data[global_id.x]); v_indices.data[global_id.x] = _e9; diff --git a/tests/out/image-copy.msl b/tests/out/image-copy.msl index 73407ceef..5d2134dbf 100644 --- a/tests/out/image-copy.msl +++ b/tests/out/image-copy.msl @@ -6,8 +6,8 @@ struct main1Input { }; kernel void main1( metal::uint3 local_id [[thread_position_in_threadgroup]] -, metal::texture2d image_src [[user(fake0)]] -, metal::texture1d image_dst [[user(fake0)]] +, metal::texture2d image_src [[user(fake0), center_perspective]] +, metal::texture1d image_dst [[user(fake0), center_perspective]] ) { metal::int2 _e12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(10, 20); metal::uint4 _e13 = image_src.read(metal::uint2(_e12)); diff --git a/tests/out/interpolate.msl b/tests/out/interpolate.msl index d1f7514a4..963e78b95 100644 --- a/tests/out/interpolate.msl +++ b/tests/out/interpolate.msl @@ -14,13 +14,13 @@ struct FragmentInput { struct main1Output { metal::float4 position [[position]]; - metal::uint flat [[user(loc0)]]; - float linear [[user(loc1)]]; - metal::float2 linear_centroid [[user(loc2)]]; - metal::float3 linear_sample [[user(loc3)]]; - metal::float4 perspective [[user(loc4)]]; - float perspective_centroid [[user(loc5)]]; - float perspective_sample [[user(loc6)]]; + metal::uint flat [[user(loc0), flat]]; + float linear [[user(loc1), center_no_perspective]]; + metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]]; + metal::float3 linear_sample [[user(loc3), sample_no_perspective]]; + metal::float4 perspective [[user(loc4), center_perspective]]; + float perspective_centroid [[user(loc5), centroid_perspective]]; + float perspective_sample [[user(loc6), sample_perspective]]; }; vertex main1Output main1( ) { @@ -39,13 +39,13 @@ vertex main1Output main1( struct main2Input { - metal::uint flat [[user(loc0)]]; - float linear [[user(loc1)]]; - metal::float2 linear_centroid [[user(loc2)]]; - metal::float3 linear_sample [[user(loc3)]]; - metal::float4 perspective [[user(loc4)]]; - float perspective_centroid [[user(loc5)]]; - float perspective_sample [[user(loc6)]]; + metal::uint flat [[user(loc0), flat]]; + float linear [[user(loc1), center_no_perspective]]; + metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]]; + metal::float3 linear_sample [[user(loc3), sample_no_perspective]]; + metal::float4 perspective [[user(loc4), center_perspective]]; + float perspective_centroid [[user(loc5), centroid_perspective]]; + float perspective_sample [[user(loc6), sample_perspective]]; }; fragment void main2( main2Input varyings1 [[stage_in]] diff --git a/tests/out/quad-vert.msl b/tests/out/quad-vert.msl index f616b1526..9e0ff87e4 100644 --- a/tests/out/quad-vert.msl +++ b/tests/out/quad-vert.msl @@ -32,7 +32,7 @@ struct main2Input { metal::float2 a_pos1 [[attribute(0)]]; }; struct main2Output { - metal::float2 member [[user(loc0)]]; + metal::float2 member [[user(loc0), center_perspective]]; metal::float4 gl_Position1 [[position]]; float gl_PointSize1 [[point_size]]; type6 gl_ClipDistance1 [[clip_distance]]; diff --git a/tests/out/quad.msl b/tests/out/quad.msl index e4ea4e40b..b3fd9acaa 100644 --- a/tests/out/quad.msl +++ b/tests/out/quad.msl @@ -12,7 +12,7 @@ struct main1Input { metal::float2 uv1 [[attribute(1)]]; }; struct main1Output { - metal::float2 uv [[user(loc0)]]; + metal::float2 uv [[user(loc0), center_perspective]]; metal::float4 position [[position]]; }; vertex main1Output main1( @@ -26,15 +26,15 @@ vertex main1Output main1( struct main2Input { - metal::float2 uv2 [[user(loc0)]]; + metal::float2 uv2 [[user(loc0), center_perspective]]; }; struct main2Output { metal::float4 member1 [[color(0)]]; }; fragment main2Output main2( main2Input varyings1 [[stage_in]] -, metal::texture2d u_texture [[user(fake0)]] -, metal::sampler u_sampler [[user(fake0)]] +, metal::texture2d u_texture [[user(fake0), center_perspective]] +, metal::sampler u_sampler [[user(fake0), center_perspective]] ) { const auto uv2 = varyings1.uv2; metal::float4 _e4 = u_texture.sample(u_sampler, uv2); diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index 47ef39e1c..68f2b8bfa 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -30,18 +30,18 @@ float fetch_shadow( } struct fs_mainInput { - metal::float3 raw_normal [[user(loc0)]]; - metal::float4 position [[user(loc1)]]; + metal::float3 raw_normal [[user(loc0), center_perspective]]; + metal::float4 position [[user(loc1), center_perspective]]; }; struct fs_mainOutput { metal::float4 member [[color(0)]]; }; fragment fs_mainOutput fs_main( fs_mainInput varyings [[stage_in]] -, constant Globals& u_globals [[user(fake0)]] -, constant Lights& s_lights [[user(fake0)]] -, metal::depth2d_array t_shadow [[user(fake0)]] -, metal::sampler sampler_shadow [[user(fake0)]] +, constant Globals& u_globals [[user(fake0), center_perspective]] +, constant Lights& s_lights [[user(fake0), center_perspective]] +, metal::depth2d_array t_shadow [[user(fake0), center_perspective]] +, metal::sampler sampler_shadow [[user(fake0), center_perspective]] ) { const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; diff --git a/tests/out/skybox.msl b/tests/out/skybox.msl index efdff96d5..bd3763713 100644 --- a/tests/out/skybox.msl +++ b/tests/out/skybox.msl @@ -14,7 +14,7 @@ struct vs_mainInput { }; struct vs_mainOutput { metal::float4 position [[position]]; - metal::float3 uv [[user(loc0)]]; + metal::float3 uv [[user(loc0), center_perspective]]; }; vertex vs_mainOutput vs_main( metal::uint vertex_index [[vertex_id]] @@ -32,7 +32,7 @@ vertex vs_mainOutput vs_main( struct fs_mainInput { - metal::float3 uv [[user(loc0)]]; + metal::float3 uv [[user(loc0), center_perspective]]; }; struct fs_mainOutput { metal::float4 member1 [[color(0)]]; diff --git a/tests/out/texture-array.msl b/tests/out/texture-array.msl index 06c758842..98f5d22d0 100644 --- a/tests/out/texture-array.msl +++ b/tests/out/texture-array.msl @@ -6,17 +6,17 @@ struct PushConstants { }; struct main1Input { - metal::float2 tex_coord [[user(loc0)]]; + metal::float2 tex_coord [[user(loc0), center_perspective]]; }; struct main1Output { metal::float4 member [[color(1)]]; }; fragment main1Output main1( main1Input varyings [[stage_in]] -, metal::texture2d texture0_ [[user(fake0)]] -, metal::texture2d texture1_ [[user(fake0)]] -, metal::sampler sampler [[user(fake0)]] -, constant PushConstants& pc [[user(fake0)]] +, metal::texture2d texture0_ [[user(fake0), center_perspective]] +, metal::texture2d texture1_ [[user(fake0), center_perspective]] +, metal::sampler sampler [[user(fake0), center_perspective]] +, constant PushConstants& pc [[user(fake0), center_perspective]] ) { const auto tex_coord = varyings.tex_coord; if (pc.index == 0u) { From 79bcfb12065b9c2ff906612f35edd75e97217fda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois?= Date: Mon, 19 Apr 2021 19:37:25 +0200 Subject: [PATCH 0723/2212] [glsl-in] add support for array variables (#731) * [glsl-in] add support for array variables * clippy * more clippy --- src/front/glsl/ast.rs | 53 +++++++++++++++++++++++++++++++++++++--- src/front/glsl/parser.rs | 30 ++++++++++++++++++++++- 2 files changed, 78 insertions(+), 5 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index a832a6fde..b85a7f8e8 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,9 +1,9 @@ use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind}; use crate::{ - proc::ResolveContext, Arena, BinaryOperator, Binding, Constant, Expression, FastHashMap, - Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, - RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, - UnaryOperator, + proc::ResolveContext, Arena, ArraySize, BinaryOperator, Binding, Constant, Expression, + FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, + Module, RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, + Type, UnaryOperator, }; #[derive(Debug)] @@ -144,6 +144,51 @@ impl<'a> Program<'a> { .solve(root) .map_err(|_| ErrorKind::SemanticError("Can't solve constant".into())) } + + pub fn type_size(&self, ty: Handle) -> Result { + Ok(match self.module.types[ty].inner { + crate::TypeInner::Scalar { width, .. } => width, + crate::TypeInner::Vector { size, width, .. } => size as u8 * width, + crate::TypeInner::Matrix { + columns, + rows, + width, + } => columns as u8 * rows as u8 * width, + crate::TypeInner::Pointer { .. } => { + return Err(ErrorKind::NotImplemented("type size of pointer")) + } + crate::TypeInner::ValuePointer { .. } => { + return Err(ErrorKind::NotImplemented("type size of value pointer")) + } + crate::TypeInner::Array { size, stride, .. } => { + stride as u8 + * match size { + ArraySize::Dynamic => { + return Err(ErrorKind::NotImplemented("type size of dynamic array")) + } + ArraySize::Constant(constant) => { + match self.module.constants[constant].inner { + crate::ConstantInner::Scalar { width, .. } => width, + crate::ConstantInner::Composite { .. } => { + return Err(ErrorKind::NotImplemented( + "type size of array with composite item size", + )) + } + } + } + } + } + crate::TypeInner::Struct { .. } => { + return Err(ErrorKind::NotImplemented("type size of struct")) + } + crate::TypeInner::Image { .. } => { + return Err(ErrorKind::NotImplemented("type size of image")) + } + crate::TypeInner::Sampler { .. } => { + return Err(ErrorKind::NotImplemented("type size of sampler")) + } + }) + } } #[derive(Debug)] diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 276529b0b..20a9716e1 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -6,7 +6,7 @@ pomelo! { use super::super::{error::ErrorKind, token::*, ast::*}; use crate::{ BOOL_WIDTH, - Arena, BinaryOperator, Binding, Block, Constant, + Arena, ArraySize, BinaryOperator, Binding, Block, Constant, ConstantInner, Expression, Function, FunctionArgument, FunctionResult, GlobalVariable, Handle, Interpolation, @@ -592,6 +592,34 @@ pomelo! { ty, } } + + single_declaration ::= fully_specified_type(t) Identifier(i) LeftBracket additive_expression(exp) RightBracket { + let ty_item = t.1.ok_or_else(|| ErrorKind::SemanticError("Empty type for declaration".into()))?; + + let array_size = if let Ok(constant) = extra.solve_constant(exp.expression) { + ArraySize::Constant(constant) + } else { + ArraySize::Dynamic + }; + + let item_size = extra.type_size(ty_item)?; + + let ty = extra.module.types.fetch_or_append(Type { + inner: TypeInner::Array { + base: ty_item, + size: array_size, + stride: item_size as u32, + }, + name: None, + }); + + VarDeclaration { + type_qualifiers: t.0, + ids_initializers: vec![(Some(i.1), None)], + ty, + } + } + // single_declaration ::= fully_specified_type Identifier array_specifier; // single_declaration ::= fully_specified_type Identifier array_specifier Equal initializer; single_declaration ::= fully_specified_type(t) Identifier(i) Equal initializer(init) { From 446f5dad6f660acf02c7dc5e4d6c54165133d735 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 20 Apr 2021 14:51:32 +0300 Subject: [PATCH 0724/2212] [hlsl-out] Use fmt::Writer instead of io::Writer --- src/back/hlsl/mod.rs | 11 ++++------- src/back/hlsl/writer.rs | 2 +- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index e785b57a1..9cc22d9d1 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -1,8 +1,7 @@ mod keywords; mod writer; -use std::io::Error as IoError; -use std::string::FromUtf8Error; +use std::fmt::Error as FmtError; use thiserror::Error; pub use writer::Writer; @@ -10,14 +9,12 @@ pub use writer::Writer; #[derive(Error, Debug)] pub enum Error { #[error(transparent)] - IoError(#[from] IoError), - #[error(transparent)] - Utf8(#[from] FromUtf8Error), + IoError(#[from] FmtError), } pub fn write_string(module: &crate::Module) -> Result { - let mut w = Writer::new(Vec::new()); + let mut w = Writer::new(String::new()); w.write(module)?; - let output = String::from_utf8(w.finish())?; + let output = w.finish(); Ok(output) } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 121d4506c..67a34f7ca 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2,7 +2,7 @@ use super::Error; use crate::back::hlsl::keywords::RESERVED; use crate::proc::{NameKey, Namer}; use crate::FastHashMap; -use std::io::Write; +use std::fmt::Write; const INDENT: &str = " "; From c37ae5e2a089b89c5608325adeebda4e26baea85 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 20 Apr 2021 14:52:06 +0300 Subject: [PATCH 0725/2212] [glsl-out] Use fmt::Writer instead of io::Writer --- bin/convert.rs | 23 ++++++----------------- src/back/glsl/features.rs | 2 +- src/back/glsl/mod.rs | 6 +++--- tests/snapshots.rs | 6 ++---- 4 files changed, 12 insertions(+), 25 deletions(-) diff --git a/bin/convert.rs b/bin/convert.rs index 151fc2967..978756cff 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -237,23 +237,12 @@ fn main() { _ => unreachable!(), }; - let file = fs::OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(output_path) - .unwrap(); - - let mut writer = glsl::Writer::new(file, &module, info.as_ref().unwrap(), ¶ms.glsl) - .unwrap_pretty(); - - writer - .write() - .map_err(|e| { - fs::remove_file(output_path).unwrap(); - e - }) - .unwrap(); + let mut buffer = String::new(); + let mut writer = + glsl::Writer::new(&mut buffer, &module, info.as_ref().unwrap(), ¶ms.glsl) + .unwrap_pretty(); + writer.write().unwrap(); + fs::write(output_path, buffer).unwrap(); } #[cfg(feature = "dot-out")] "dot" => { diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index d5c835f9d..5ae44b71d 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -3,7 +3,7 @@ use crate::{ Binding, Bytes, Handle, ImageClass, ImageDimension, Interpolation, Sampling, ScalarKind, ShaderStage, StorageClass, StorageFormat, Type, TypeInner, }; -use std::io::Write; +use std::fmt::Write; bitflags::bitflags! { /// Structure used to encode a set of additions to glsl that aren't supported by all versions diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 11b4c2fd0..4a5f5d643 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -57,7 +57,7 @@ use features::FeaturesManager; use std::{ cmp::Ordering, fmt, - io::{Error as IoError, Write}, + fmt::{Error as FmtError, Write}, }; use thiserror::Error; @@ -271,8 +271,8 @@ type BackendResult = Result<(), Error>; #[derive(Debug, Error)] pub enum Error { /// A error occurred while writing to the output - #[error("I/O error")] - IoError(#[from] IoError), + #[error("Format error")] + FmtError(#[from] FmtError), /// The specified [`Version`](Version) doesn't have all required [`Features`](super) /// /// Contains the missing [`Features`](Features) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index a52b8b6f5..bbb92b3b4 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -189,14 +189,12 @@ fn check_output_glsl( entry_point: ep_name.to_string(), }; - let mut buffer = Vec::new(); + let mut buffer = String::new(); let mut writer = glsl::Writer::new(&mut buffer, module, info, &options).unwrap(); writer.write().unwrap(); - let string = String::from_utf8(buffer).unwrap(); - let ext = format!("{:?}.glsl", stage); - fs::write(destination.with_extension(&ext), string).unwrap(); + fs::write(destination.with_extension(&ext), buffer).unwrap(); } #[cfg(feature = "hlsl-out")] From a4ac7b38b28d99e69b64e6e3b35fe7388e02f1d9 Mon Sep 17 00:00:00 2001 From: Ashley Ruglys Date: Tue, 20 Apr 2021 16:01:32 +0200 Subject: [PATCH 0726/2212] Don't use an interpolation on fake bindings --- src/back/msl/mod.rs | 23 +++++++++++++++-------- tests/out/collatz.msl | 2 +- tests/out/image-copy.msl | 4 ++-- tests/out/quad.msl | 4 ++-- tests/out/shadow.msl | 8 ++++---- tests/out/texture-array.msl | 8 ++++---- 6 files changed, 28 insertions(+), 21 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 92b80ffa0..e5652f232 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -87,7 +87,7 @@ enum ResolvedBinding { User { prefix: &'static str, index: u32, - interpolation: ResolvedInterpolation + interpolation: Option, }, Resource(BindTarget), } @@ -214,8 +214,8 @@ impl Options { // sampling is `None` only for Flat interpolation. let interpolation = interpolation.unwrap(); let sampling = sampling.unwrap_or(crate::Sampling::Center); - ResolvedInterpolation::from_binding(interpolation, sampling) - } + Some(ResolvedInterpolation::from_binding(interpolation, sampling)) + }, }), LocationMode::Uniform => { log::error!( @@ -243,7 +243,7 @@ impl Options { None if self.fake_missing_bindings => Ok(ResolvedBinding::User { prefix: "fake", index: 0, - interpolation: ResolvedInterpolation::CenterPerspective, + interpolation: None, }), None => Err(EntryPointError::MissingBinding(source)), } @@ -268,7 +268,7 @@ impl Options { None if self.fake_missing_bindings => Ok(ResolvedBinding::User { prefix: "fake", index: 0, - interpolation: ResolvedInterpolation::CenterPerspective, + interpolation: None, }), None => Err(EntryPointError::MissingPushConstants(stage)), } @@ -315,9 +315,16 @@ impl ResolvedBinding { } Self::Attribute(index) => write!(out, "attribute({})", index)?, Self::Color(index) => write!(out, "color({})", index)?, - Self::User { prefix, index, interpolation } => { - write!(out, "user({}{}), ", prefix, index)?; - interpolation.try_fmt(out)?; + Self::User { + prefix, + index, + interpolation, + } => { + write!(out, "user({}{})", prefix, index)?; + if let Some(interpolation) = interpolation { + write!(out, ", ")?; + interpolation.try_fmt(out)?; + } } Self::Resource(ref target) => { if let Some(id) = target.buffer { diff --git a/tests/out/collatz.msl b/tests/out/collatz.msl index 02a976116..403789659 100644 --- a/tests/out/collatz.msl +++ b/tests/out/collatz.msl @@ -30,7 +30,7 @@ struct main1Input { }; kernel void main1( metal::uint3 global_id [[thread_position_in_grid]] -, device PrimeIndices& v_indices [[user(fake0), center_perspective]] +, device PrimeIndices& v_indices [[user(fake0)]] ) { metal::uint _e9 = collatz_iterations(v_indices.data[global_id.x]); v_indices.data[global_id.x] = _e9; diff --git a/tests/out/image-copy.msl b/tests/out/image-copy.msl index 5d2134dbf..73407ceef 100644 --- a/tests/out/image-copy.msl +++ b/tests/out/image-copy.msl @@ -6,8 +6,8 @@ struct main1Input { }; kernel void main1( metal::uint3 local_id [[thread_position_in_threadgroup]] -, metal::texture2d image_src [[user(fake0), center_perspective]] -, metal::texture1d image_dst [[user(fake0), center_perspective]] +, metal::texture2d image_src [[user(fake0)]] +, metal::texture1d image_dst [[user(fake0)]] ) { metal::int2 _e12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(10, 20); metal::uint4 _e13 = image_src.read(metal::uint2(_e12)); diff --git a/tests/out/quad.msl b/tests/out/quad.msl index b3fd9acaa..47238348b 100644 --- a/tests/out/quad.msl +++ b/tests/out/quad.msl @@ -33,8 +33,8 @@ struct main2Output { }; fragment main2Output main2( main2Input varyings1 [[stage_in]] -, metal::texture2d u_texture [[user(fake0), center_perspective]] -, metal::sampler u_sampler [[user(fake0), center_perspective]] +, metal::texture2d u_texture [[user(fake0)]] +, metal::sampler u_sampler [[user(fake0)]] ) { const auto uv2 = varyings1.uv2; metal::float4 _e4 = u_texture.sample(u_sampler, uv2); diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index 68f2b8bfa..772a3cf2e 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -38,10 +38,10 @@ struct fs_mainOutput { }; fragment fs_mainOutput fs_main( fs_mainInput varyings [[stage_in]] -, constant Globals& u_globals [[user(fake0), center_perspective]] -, constant Lights& s_lights [[user(fake0), center_perspective]] -, metal::depth2d_array t_shadow [[user(fake0), center_perspective]] -, metal::sampler sampler_shadow [[user(fake0), center_perspective]] +, constant Globals& u_globals [[user(fake0)]] +, constant Lights& s_lights [[user(fake0)]] +, metal::depth2d_array t_shadow [[user(fake0)]] +, metal::sampler sampler_shadow [[user(fake0)]] ) { const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; diff --git a/tests/out/texture-array.msl b/tests/out/texture-array.msl index 98f5d22d0..229d53357 100644 --- a/tests/out/texture-array.msl +++ b/tests/out/texture-array.msl @@ -13,10 +13,10 @@ struct main1Output { }; fragment main1Output main1( main1Input varyings [[stage_in]] -, metal::texture2d texture0_ [[user(fake0), center_perspective]] -, metal::texture2d texture1_ [[user(fake0), center_perspective]] -, metal::sampler sampler [[user(fake0), center_perspective]] -, constant PushConstants& pc [[user(fake0), center_perspective]] +, metal::texture2d texture0_ [[user(fake0)]] +, metal::texture2d texture1_ [[user(fake0)]] +, metal::sampler sampler [[user(fake0)]] +, constant PushConstants& pc [[user(fake0)]] ) { const auto tex_coord = varyings.tex_coord; if (pc.index == 0u) { From b08dfe51469447b6daf86b01ebd56465c8efe9ca Mon Sep 17 00:00:00 2001 From: Ashley Date: Tue, 20 Apr 2021 17:41:13 +0200 Subject: [PATCH 0727/2212] [Metal] Impl `Expression::Splat` (#738) * [Metal] Impl `Expression::Splat` * Add changes to the snapshots * Apply suggestions --- src/back/msl/writer.rs | 13 +++++++++++-- tests/out/access.msl | 2 +- tests/out/boids.msl | 4 ++-- tests/out/operators.msl | 4 ++-- tests/out/shadow.msl | 2 +- 5 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 79a811482..8b2f6901e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -608,8 +608,17 @@ impl Writer { }; write!(self.out, "{}", coco)?; } - crate::Expression::Splat { size: _, value } => { - self.put_expression(value, context, is_scoped)?; + crate::Expression::Splat { size, value } => { + let scalar_kind = match *context.resolve_type(value) { + crate::TypeInner::Scalar { kind, .. } => kind, + _ => return Err(Error::Validation) + }; + let scalar = scalar_kind_string(scalar_kind); + let size = vector_size_string(size); + + write!(self.out, "{}{}(", scalar, size)?; + self.put_expression(value, context, true)?; + write!(self.out, ")")?; } crate::Expression::Compose { ty, ref components } => { let inner = &context.module.types[ty].inner; diff --git a/tests/out/access.msl b/tests/out/access.msl index 8c9d1c226..2c3da3e90 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -11,5 +11,5 @@ struct fooOutput { vertex fooOutput foo( metal::uint vi [[vertex_id]] ) { - return fooOutput { static_cast(type3 {1, 2, 3, 4, 5}[vi]) }; + return fooOutput { static_cast(int4(type3 {1, 2, 3, 4, 5}[vi])) }; } diff --git a/tests/out/boids.msl b/tests/out/boids.msl index f8aa78780..3cabb8e66 100644 --- a/tests/out/boids.msl +++ b/tests/out/boids.msl @@ -73,10 +73,10 @@ kernel void main1( } } if (cMassCount > 0) { - cMass = (cMass / static_cast(cMassCount)) - vPos; + cMass = (cMass / float2(static_cast(cMassCount))) - vPos; } if (cVelCount > 0) { - cVel = cVel / static_cast(cVelCount); + cVel = cVel / float2(static_cast(cVelCount)); } vVel = ((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale); vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); diff --git a/tests/out/operators.msl b/tests/out/operators.msl index 2b21eab62..79d2ced84 100644 --- a/tests/out/operators.msl +++ b/tests/out/operators.msl @@ -7,6 +7,6 @@ struct splatOutput { }; vertex splatOutput splat( ) { - metal::float2 _e10 = ((1.0 + 2.0) - 3.0) / 4.0; - return splatOutput { metal::float4(_e10.x, _e10.y, _e10.x, _e10.y) + static_cast(5 % 2) }; + metal::float2 _e10 = ((float2(1.0) + float2(2.0)) - float2(3.0)) / float2(4.0); + return splatOutput { metal::float4(_e10.x, _e10.y, _e10.x, _e10.y) + static_cast(int4(5) % int4(2)) }; } diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index 772a3cf2e..12a5c43bb 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -25,7 +25,7 @@ float fetch_shadow( if (homogeneous_coords.w <= 0.0) { return 1.0; } - float _e28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) / homogeneous_coords.w) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); + float _e28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) / float2(homogeneous_coords.w)) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); return _e28; } From 5d1746b0b4f253a423e68a083d81b794d385ebbf Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 20 Apr 2021 22:03:54 -0400 Subject: [PATCH 0728/2212] Swizzle expression (#734) --- src/back/dot/mod.rs | 11 ++ src/back/glsl/features.rs | 3 +- src/back/glsl/mod.rs | 35 ++++-- src/back/msl/mod.rs | 23 ++-- src/back/msl/writer.rs | 17 ++- src/back/spv/instructions.rs | 20 ++++ src/back/spv/writer.rs | 29 ++++- src/front/glsl/constants.rs | 47 +++++++- src/front/spv/function.rs | 3 +- src/front/spv/mod.rs | 91 ++++++++++---- src/front/wgsl/mod.rs | 139 +++++++++------------- src/lib.rs | 23 +++- src/proc/interpolator.rs | 45 +++++-- src/proc/typifier.rs | 17 +++ src/valid/analyzer.rs | 4 + src/valid/expression.rs | 23 ++++ src/valid/interface.rs | 9 +- tests/errors.rs | 21 ---- tests/out/image-copy.msl | 6 +- tests/out/operators.Vertex.glsl | 3 +- tests/out/operators.msl | 3 +- tests/out/operators.spvasm | 14 +-- tests/out/shadow.Fragment.glsl | 6 +- tests/out/shadow.msl | 6 +- tests/out/shadow.spvasm | 205 +++++++++++++++----------------- tests/out/skybox.Vertex.glsl | 5 +- tests/out/skybox.msl | 3 +- tests/out/skybox.spvasm | 104 +++++++--------- 28 files changed, 547 insertions(+), 368 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index d1df17517..75c619a38 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -187,6 +187,17 @@ fn write_fun( edges.insert("value", value); (Cow::Owned(format!("Splat{:?}", size)), 3) } + E::Swizzle { + size, + vector, + pattern, + } => { + edges.insert("vector", vector); + ( + Cow::Owned(format!("Swizzle{:?}", &pattern[..size as usize])), + 3, + ) + } E::Compose { ref components, .. } => { payload = Some(Payload::Arguments(components)); (Cow::Borrowed("Compose"), 3) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 5ae44b71d..28501b831 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -292,7 +292,8 @@ impl<'a, W> Writer<'a, W> { interpolation, sampling, .. - }) = binding { + }) = binding + { if interpolation == Some(Interpolation::Linear) { self.features.request(Features::NOPERSPECTIVE_QUALIFIER); } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 4a5f5d643..002777f5e 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -51,7 +51,6 @@ use crate::{ ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, Sampling, ScalarKind, ScalarValue, ShaderStage, Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, UnaryOperator, - }; use features::FeaturesManager; use std::{ @@ -72,6 +71,8 @@ pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450] pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; const INDENT: &str = " "; +const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; + /// glsl version #[derive(Debug, Copy, Clone, PartialEq)] pub enum Version { @@ -797,7 +798,11 @@ impl<'a, W: Write> Writer<'a, W> { } _ => { let (location, interpolation, sampling) = match binding { - Some(&Binding::Location { location, interpolation, sampling }) => (location, interpolation, sampling), + Some(&Binding::Location { + location, + interpolation, + sampling, + }) => (location, interpolation, sampling), _ => return Ok(()), }; @@ -818,10 +823,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the storage class if self.options.version.supports_explicit_locations() { - write!( - self.out, - "layout(location = {}) ", - location)?; + write!(self.out, "layout(location = {}) ", location)?; } // Write the sampling auxiliary qualifier. @@ -847,7 +849,11 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important let vname = VaryingName { - binding: &Binding::Location { location, interpolation: None, sampling: None }, + binding: &Binding::Location { + location, + interpolation: None, + sampling: None, + }, stage: self.entry_point.stage, output, }; @@ -1507,6 +1513,18 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(value, ctx)?; write!(self.out, ")")? } + // `Swizzle` adds a few letters behind the dot. + Expression::Swizzle { + size, + vector, + pattern, + } => { + self.write_expr(vector, ctx)?; + write!(self.out, ".")?; + for &sc in pattern[..size as usize].iter() { + write!(self.out, "{}", COMPONENTS[sc as usize])?; + } + } // `Compose` is pretty simple we just write `type(components)` where `components` is a // comma separated list of expressions Expression::Compose { ty, ref components } => { @@ -1728,14 +1746,13 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")",)?; } crate::ImageQuery::NumLayers => { - let selector = ['x', 'y', 'z', 'w']; let fun_name = match class { ImageClass::Sampled { .. } | ImageClass::Depth => "textureSize", ImageClass::Storage(_) => "imageSize", }; write!(self.out, "{}(", fun_name)?; self.write_expr(image, ctx)?; - write!(self.out, ",0).{}", selector[components])?; + write!(self.out, ",0).{}", COMPONENTS[components])?; } crate::ImageQuery::NumSamples => { // assumes ARB_shader_texture_image_samples diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index e5652f232..e38beed88 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -198,7 +198,11 @@ impl Options { ) -> Result { match *binding { crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), - crate::Binding::Location { location, interpolation, sampling } => match mode { + crate::Binding::Location { + location, + interpolation, + sampling, + } => match mode { LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(location)), LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(location)), LocationMode::Intermediate => Ok(ResolvedBinding::User { @@ -351,21 +355,18 @@ impl ResolvedBinding { } impl ResolvedInterpolation { - fn from_binding(interpolation: crate::Interpolation, - sampling: crate::Sampling) - -> Self -{ + fn from_binding(interpolation: crate::Interpolation, sampling: crate::Sampling) -> Self { use crate::Interpolation as I; use crate::Sampling as S; match (interpolation, sampling) { - (I::Perspective, S::Center) => Self::CenterPerspective, + (I::Perspective, S::Center) => Self::CenterPerspective, (I::Perspective, S::Centroid) => Self::CentroidPerspective, - (I::Perspective, S::Sample) => Self::SamplePerspective, - (I::Linear, S::Center) => Self::CenterNoPerspective, - (I::Linear, S::Centroid) => Self::CentroidNoPerspective, - (I::Linear, S::Sample) => Self::SampleNoPerspective, - (I::Flat, _) => Self::Flat, + (I::Perspective, S::Sample) => Self::SamplePerspective, + (I::Linear, S::Center) => Self::CenterNoPerspective, + (I::Linear, S::Centroid) => Self::CentroidNoPerspective, + (I::Linear, S::Sample) => Self::SampleNoPerspective, + (I::Flat, _) => Self::Flat, } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8b2f6901e..fcf815105 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -611,7 +611,7 @@ impl Writer { crate::Expression::Splat { size, value } => { let scalar_kind = match *context.resolve_type(value) { crate::TypeInner::Scalar { kind, .. } => kind, - _ => return Err(Error::Validation) + _ => return Err(Error::Validation), }; let scalar = scalar_kind_string(scalar_kind); let size = vector_size_string(size); @@ -620,6 +620,17 @@ impl Writer { self.put_expression(value, context, true)?; write!(self.out, ")")?; } + crate::Expression::Swizzle { + size, + vector, + pattern, + } => { + self.put_expression(vector, context, is_scoped)?; + write!(self.out, ".")?; + for &sc in pattern[..size as usize].iter() { + write!(self.out, "{}", COMPONENTS[sc as usize])?; + } + } crate::Expression::Compose { ty, ref components } => { let inner = &context.module.types[ty].inner; match *inner { @@ -2168,8 +2179,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 20336 - if stack_size < 19000 || stack_size > 21000 { + // last observed macOS value: 21584 + if stack_size < 20000 || stack_size > 22000 { panic!("`put_expression` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 90f8b0128..b8855cda1 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -659,6 +659,26 @@ impl super::Instruction { instruction } + pub(super) fn vector_shuffle( + result_type_id: Word, + id: Word, + v1_id: Word, + v2_id: Word, + components: &[Word], + ) -> Self { + let mut instruction = Self::new(Op::VectorShuffle); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(v1_id); + instruction.add_operand(v2_id); + + for &component in components { + instruction.add_operand(component); + } + + instruction + } + // // Arithmetic Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 39df6f223..74a9bade6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -418,7 +418,8 @@ impl Writer { } fn decorate(&mut self, id: Word, decoration: spirv::Decoration, operands: &[Word]) { - self.annotations.push(Instruction::decorate(id, decoration, operands)); + self.annotations + .push(Instruction::decorate(id, decoration, operands)); } fn write_function( @@ -1090,7 +1091,11 @@ impl Writer { use spirv::{BuiltIn, Decoration}; match *binding { - crate::Binding::Location { location, interpolation, sampling } => { + crate::Binding::Location { + location, + interpolation, + sampling, + } => { self.decorate(id, Decoration::Location, &[location]); match interpolation { @@ -1459,6 +1464,26 @@ impl Writer { )); id } + crate::Expression::Swizzle { + size, + vector, + pattern, + } => { + let vector_id = self.cached[vector]; + self.temp_list.clear(); + for &sc in pattern[..size as usize].iter() { + self.temp_list.push(sc as Word); + } + let id = self.id_gen.next(); + block.body.push(Instruction::vector_shuffle( + result_type_id, + id, + vector_id, + vector_id, + &self.temp_list, + )); + id + } crate::Expression::Compose { ty: _, ref components, diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 372ff1704..82221f527 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -49,8 +49,8 @@ pub enum ConstantSolvingError { InvalidUnaryOpArg, #[error("Cannot apply the binary op to the arguments")] InvalidBinaryOpArgs, - #[error("Splat type is not registered")] - SplatType, + #[error("Splat/swizzle type is not registered")] + DestinationTypeNotFound, } impl<'a> ConstantSolver<'a> { @@ -83,11 +83,52 @@ impl<'a> ConstantSolver<'a> { name: None, specialization: None, inner: ConstantInner::Composite { - ty: ty.ok_or(ConstantSolvingError::SplatType)?, + //TODO: register the new type if needed + ty: ty.ok_or(ConstantSolvingError::DestinationTypeNotFound)?, components: vec![tgt; size as usize], }, })) } + Expression::Swizzle { + size, + vector: src_vector, + pattern, + } => { + let tgt = self.solve(src_vector)?; + let (ty, src_components) = match self.constants[tgt].inner { + ConstantInner::Scalar { .. } => (None, &[][..]), + ConstantInner::Composite { + ty, + components: ref src_components, + } => match self.types[ty].inner { + crate::TypeInner::Vector { + size: _, + kind, + width, + } => { + let dst_ty = self.types.fetch_if(|t| { + t.inner == crate::TypeInner::Vector { size, kind, width } + }); + (dst_ty, &src_components[..]) + } + _ => (None, &[][..]), + }, + }; + let components = pattern + .iter() + .map(|&sc| src_components[sc as usize]) + .collect(); + + Ok(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + //TODO: register the new type if needed + ty: ty.ok_or(ConstantSolvingError::DestinationTypeNotFound)?, + components, + }, + })) + } Expression::Compose { ty, ref components } => { let components = components .iter() diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 15e969d5d..1116f0e82 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -216,7 +216,8 @@ impl> super::Parser { if let Some(crate::Binding::Location { interpolation: ref mut interpolation @ None, .. - }) = arg.binding { + }) = arg.binding + { *interpolation = Some(crate::Interpolation::Perspective); // default } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e4d7a1c71..eaf9dbc09 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -256,7 +256,11 @@ impl Decoration { interpolation, sampling, .. - } => Ok(crate::Binding::Location { location, interpolation, sampling }), + } => Ok(crate::Binding::Location { + location, + interpolation, + sampling, + }), _ => Err(Error::MissingDecoration(spirv::Decoration::Location)), } } @@ -1438,41 +1442,78 @@ impl> Parser { let v1_lexp = self.lookup_expression.lookup(v1_id)?; let v1_lty = self.lookup_type.lookup(v1_lexp.type_id)?; + let v1_handle = v1_lexp.handle; let n1 = match type_arena[v1_lty.handle].inner { - crate::TypeInner::Vector { size, .. } => size as u8, + crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidInnerType(v1_lexp.type_id)), }; - let v1_handle = v1_lexp.handle; let v2_lexp = self.lookup_expression.lookup(v2_id)?; let v2_lty = self.lookup_type.lookup(v2_lexp.type_id)?; + let v2_handle = v2_lexp.handle; let n2 = match type_arena[v2_lty.handle].inner { - crate::TypeInner::Vector { size, .. } => size as u8, + crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidInnerType(v2_lexp.type_id)), }; - let v2_handle = v2_lexp.handle; - let mut components = Vec::with_capacity(inst.wc as usize - 5); - for _ in 0..components.capacity() { - let index = self.next()?; - let expr = if index < n1 as u32 { - crate::Expression::AccessIndex { - base: v1_handle, - index, - } - } else if index < n1 as u32 + n2 as u32 { - crate::Expression::AccessIndex { - base: v2_handle, - index: index - n1 as u32, - } - } else { - return Err(Error::InvalidAccessIndex(index)); - }; - components.push(expressions.append(expr)); + self.temp_bytes.clear(); + let mut max_component = 0; + for _ in 5..inst.wc as usize { + let mut index = self.next()?; + if index == !0 { + // treat Undefined as X + index = 0; + } + max_component = max_component.max(index); + self.temp_bytes.push(index as u8); } - let expr = crate::Expression::Compose { - ty: self.lookup_type.lookup(result_type_id)?.handle, - components, + + // Check for swizzle first. + let expr = if max_component < n1 { + use crate::SwizzleComponent as Sc; + let size = match self.temp_bytes.len() { + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + _ => crate::VectorSize::Quad, + }; + let mut pattern = [Sc::X; 4]; + for (pat, index) in pattern.iter_mut().zip(self.temp_bytes.drain(..)) { + *pat = match index { + 0 => Sc::X, + 1 => Sc::Y, + 2 => Sc::Z, + _ => Sc::W, + }; + } + crate::Expression::Swizzle { + size, + vector: v1_handle, + pattern, + } + } else { + // Fall back to access + compose + let mut components = Vec::with_capacity(self.temp_bytes.len()); + for index in self.temp_bytes.drain(..).map(|i| i as u32) { + let expr = if index < n1 { + crate::Expression::AccessIndex { + base: v1_handle, + index, + } + } else if index < n1 + n2 { + crate::Expression::AccessIndex { + base: v2_handle, + index: index - n1, + } + } else { + return Err(Error::InvalidAccessIndex(index)); + }; + components.push(expressions.append(expr)); + } + crate::Expression::Compose { + ty: self.lookup_type.lookup(result_type_id)?.handle, + components, + } }; + self.lookup_expression.insert( result_id, LookupExpression { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 8d4baa4c4..cd96de496 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -379,55 +379,49 @@ impl<'a> ExpressionContext<'a, '_, '_> { } enum Composition { - Single(crate::Expression), - Multi(crate::VectorSize, Vec>), + Single(u32), + Multi(crate::VectorSize, [crate::SwizzleComponent; 4]), } impl Composition { //TODO: could be `const fn` once MSRV allows - fn letter_pos(letter: char) -> u32 { + fn letter_component(letter: char) -> Option { + use crate::SwizzleComponent as Sc; match letter { - 'x' | 'r' => 0, - 'y' | 'g' => 1, - 'z' | 'b' => 2, - 'w' | 'a' => 3, - _ => !0, + 'x' | 'r' => Some(Sc::X), + 'y' | 'g' => Some(Sc::Y), + 'z' | 'b' => Some(Sc::Z), + 'w' | 'a' => Some(Sc::W), + _ => None, + } + } + + fn extract_impl(name: &str, name_span: Range) -> Result { + let ch = name + .chars() + .next() + .ok_or_else(|| Error::BadAccessor(name_span.clone()))?; + match Self::letter_component(ch) { + Some(sc) => Ok(sc as u32), + None => Err(Error::BadAccessor(name_span)), } } fn extract( base: Handle, - base_size: crate::VectorSize, name: &str, name_span: Range, ) -> Result { - let ch = name - .chars() - .next() - .ok_or_else(|| Error::BadAccessor(name_span.clone()))?; - let index = Self::letter_pos(ch); - if index >= base_size as u32 { - return Err(Error::BadAccessor(name_span)); - } - Ok(crate::Expression::AccessIndex { base, index }) + Self::extract_impl(name, name_span) + .map(|index| crate::Expression::AccessIndex { base, index }) } - fn make<'a>( - base: Handle, - base_size: crate::VectorSize, - name: &'a str, - name_span: Range, - expressions: &mut Arena, - ) -> Result> { + fn make(name: &str, name_span: Range) -> Result { if name.len() > 1 { - let mut components = Vec::with_capacity(name.len()); - for ch in name.chars() { - let index = Self::letter_pos(ch); - if index >= base_size as u32 { - return Err(Error::BadAccessor(name_span)); - } - let expr = crate::Expression::AccessIndex { base, index }; - components.push(expressions.append(expr)); + let mut components = [crate::SwizzleComponent::X; 4]; + for (comp, ch) in components.iter_mut().zip(name.chars()) { + *comp = Self::letter_component(ch) + .ok_or_else(|| Error::BadAccessor(name_span.clone()))?; } let size = match name.len() { @@ -438,7 +432,7 @@ impl Composition { }; Ok(Composition::Multi(size, components)) } else { - Self::extract(base, base_size, name, name_span).map(Composition::Single) + Self::extract_impl(name, name_span).map(Composition::Single) } } } @@ -504,14 +498,23 @@ impl BindingParser { } fn finish<'a>(self) -> Result, Error<'a>> { - match (self.location, self.built_in, self.interpolation, self.sampling) { + match ( + self.location, + self.built_in, + self.interpolation, + self.sampling, + ) { (None, None, None, None) => Ok(None), (Some(location), None, interpolation, sampling) => { // Before handing over the completed `Module`, we call // `apply_common_default_interpolation` to ensure that the interpolation and // sampling have been explicitly specified on all vertex shader output and fragment // shader input user bindings, so leaving them potentially `None` here is fine. - Ok(Some(crate::Binding::Location { location, interpolation, sampling })) + Ok(Some(crate::Binding::Location { + location, + interpolation, + sampling, + })) } (None, Some(bi), None, None) => Ok(Some(crate::Binding::BuiltIn(bi))), (location, built_in, interpolation, sampling) => Err(Error::InconsistentBinding( @@ -1251,52 +1254,24 @@ impl Parser { index, } } - crate::TypeInner::Vector { size, kind, width } => { - match Composition::make(handle, size, name, name_span, ctx.expressions)? - { - //TODO: Swizzling in IR - Composition::Multi(size, components) => { - let inner = crate::TypeInner::Vector { size, kind, width }; - crate::Expression::Compose { - ty: ctx - .types - .fetch_or_append(crate::Type { name: None, inner }), - components, + crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { + match Composition::make(name, name_span)? { + Composition::Multi(dst_size, pattern) => { + crate::Expression::Swizzle { + size: dst_size, + vector: handle, + pattern, } } - Composition::Single(expr) => expr, + Composition::Single(index) => crate::Expression::AccessIndex { + base: handle, + index, + }, } } - crate::TypeInner::Matrix { - columns, - rows, - width, - } => match Composition::make( - handle, - columns, - name, - name_span, - ctx.expressions, - )? { - //TODO: is this really supported? - Composition::Multi(columns, components) => { - let inner = crate::TypeInner::Matrix { - columns, - rows, - width, - }; - crate::Expression::Compose { - ty: ctx - .types - .fetch_or_append(crate::Type { name: None, inner }), - components, - } - } - Composition::Single(expr) => expr, - }, - crate::TypeInner::ValuePointer { - size: Some(size), .. - } => Composition::extract(handle, size, name, name_span)?, + crate::TypeInner::ValuePointer { .. } => { + Composition::extract(handle, name, name_span)? + } crate::TypeInner::Pointer { base, class: _ } => match ctx.types[base].inner { crate::TypeInner::Struct { ref members, .. } => { @@ -1310,13 +1285,7 @@ impl Parser { index, } } - crate::TypeInner::Vector { size, .. } => { - Composition::extract(handle, size, name, name_span)? - } - crate::TypeInner::Matrix { columns, .. } => { - Composition::extract(handle, columns, name, name_span)? - } - _ => return Err(Error::BadAccessor(name_span)), + _ => Composition::extract(handle, name, name_span)?, }, _ => return Err(Error::BadAccessor(name_span)), } diff --git a/src/lib.rs b/src/lib.rs index b95fe251b..f6a4b59f0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -480,7 +480,7 @@ pub enum Binding { Location { location: u32, interpolation: Option, - sampling: Option + sampling: Option, }, } @@ -679,6 +679,21 @@ pub enum ImageQuery { NumSamples, } +/// Component selection for a vector swizzle. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum SwizzleComponent { + /// + X, + /// + Y, + /// + Z, + /// + W, +} + /// An expression that can be evaluated to obtain a value. /// /// This is a Single Static Assignment (SSA) scheme similar to SPIR-V. @@ -704,6 +719,12 @@ pub enum Expression { size: VectorSize, value: Handle, }, + /// Vector swizzle. + Swizzle { + size: VectorSize, + vector: Handle, + pattern: [SwizzleComponent; 4], + }, /// Composite expression. Compose { ty: Handle, diff --git a/src/proc/interpolator.rs b/src/proc/interpolator.rs index 3a5e7e8cb..7f7296e50 100644 --- a/src/proc/interpolator.rs +++ b/src/proc/interpolator.rs @@ -36,13 +36,16 @@ impl crate::Module { /// `binding` refers to the `Binding` whose type is `ty`. If `ty` is a struct, then it's the /// bindings of the struct's members that we care about, and the binding of the struct /// itself is meaningless, so `binding` should be `None`. - fn default_binding_or_struct(binding: &mut Option, - ty: Handle, - types: &mut Arena) - { + fn default_binding_or_struct( + binding: &mut Option, + ty: Handle, + types: &mut Arena, + ) { match types.get_mut(ty).inner { // A struct. It's the individual members we care about, so recurse. - TypeInner::Struct { members: ref mut m, .. } => { + TypeInner::Struct { + members: ref mut m, .. + } => { // To choose the right interpolations for `members`, we must consult other // elements of `types`. But both `members` and the types it refers to are stored // in `types`, and Rust won't let us mutate one element of the `Arena`'s `Vec` @@ -61,7 +64,9 @@ impl crate::Module { // afresh here, rather than just using `m`: it's only because `m` was dead that // we were able to pass `types` to the recursive call. match types.get_mut(ty).inner { - TypeInner::Struct { members: ref mut m, .. } => replace(m, members), + TypeInner::Struct { + members: ref mut m, .. + } => replace(m, members), _ => unreachable!("ty must be a struct"), }; } @@ -71,16 +76,29 @@ impl crate::Module { // GLSL has 64-bit floats, but it won't interpolate them. WGSL and MSL only have // 32-bit floats. SPIR-V has 16- and 64-bit float capabilities, but Vulkan is vague // about what can and cannot be interpolated. - TypeInner::Scalar { kind: ScalarKind::Float, width: 4 } | - TypeInner::Vector { kind: ScalarKind::Float, width: 4, .. } => { + TypeInner::Scalar { + kind: ScalarKind::Float, + width: 4, + } + | TypeInner::Vector { + kind: ScalarKind::Float, + width: 4, + .. + } => { // unwrap: all `EntryPoint` arguments or return values must either be structures // or have a `Binding`. let binding = binding.as_mut().unwrap(); - if let Binding::Location { ref mut interpolation, ref mut sampling, .. } = *binding { + if let Binding::Location { + ref mut interpolation, + ref mut sampling, + .. + } = *binding + { if interpolation.is_none() { *interpolation = Some(crate::Interpolation::Perspective); } - if sampling.is_none() && *interpolation != Some(crate::Interpolation::Flat) { + if sampling.is_none() && *interpolation != Some(crate::Interpolation::Flat) + { *sampling = Some(crate::Sampling::Center); } } @@ -91,7 +109,12 @@ impl crate::Module { // unwrap: all `EntryPoint` arguments or return values must either be structures // or have a `Binding`. let binding = binding.as_mut().unwrap(); - if let Binding::Location { ref mut interpolation, ref mut sampling, .. } = *binding { + if let Binding::Location { + ref mut interpolation, + ref mut sampling, + .. + } = *binding + { *interpolation = Some(crate::Interpolation::Flat); *sampling = None; } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 1af4cf8b5..7f9068797 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -93,6 +93,8 @@ pub enum ResolveError { }, #[error("Invalid scalar {0:?}")] InvalidScalar(Handle), + #[error("Invalid vector {0:?}")] + InvalidVector(Handle), #[error("Invalid pointer {0:?}")] InvalidPointer(Handle), #[error("Invalid image {0:?}")] @@ -288,6 +290,21 @@ impl<'a> ResolveContext<'a> { return Err(ResolveError::InvalidScalar(value)); } }, + crate::Expression::Swizzle { + size, + vector, + pattern: _, + } => match *past(vector).inner_with(types) { + Ti::Vector { + size: _, + kind, + width, + } => TypeResolution::Value(Ti::Vector { size, kind, width }), + ref other => { + log::error!("Vector type {:?}", other); + return Err(ResolveError::InvalidVector(vector)); + } + }, crate::Expression::Compose { ty, .. } => TypeResolution::Handle(ty), crate::Expression::FunctionArgument(index) => { TypeResolution::Handle(self.arguments[index as usize].ty) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 7b0fff4df..f206dc3f8 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -322,6 +322,10 @@ impl FunctionInfo { non_uniform_result: self.add_ref(value), requirements: UniformityRequirements::empty(), }, + E::Swizzle { vector, .. } => Uniformity { + non_uniform_result: self.add_ref(vector), + requirements: UniformityRequirements::empty(), + }, E::Compose { ref components, .. } => { let non_uniform_result = components .iter() diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 1ec603ce7..5ed5e3853 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -33,6 +33,10 @@ pub enum ExpressionError { InvalidArrayType(Handle), #[error("Splatting {0:?} can't be done")] InvalidSplatType(Handle), + #[error("Swizzling {0:?} can't be done")] + InvalidVectorType(Handle), + #[error("Swizzle component {0:?} is outside of vector size {1:?}")] + InvalidSwizzleComponent(crate::SwizzleComponent, crate::VectorSize), #[error(transparent)] Compose(#[from] ComposeError), #[error("Operation {0:?} can't work with {1:?}")] @@ -200,6 +204,25 @@ impl super::Validator { return Err(ExpressionError::InvalidSplatType(value)); } }, + E::Swizzle { + size, + vector, + pattern, + } => { + let vec_size = match *resolver.resolve(vector)? { + Ti::Vector { size: vec_size, .. } => vec_size, + ref other => { + log::error!("Swizzle vector type {:?}", other); + return Err(ExpressionError::InvalidVectorType(vector)); + } + }; + for &sc in pattern[..size as usize].iter() { + if sc as u8 >= vec_size as u8 { + return Err(ExpressionError::InvalidSwizzleComponent(sc, vec_size)); + } + } + ShaderStages::all() + } E::Compose { ref components, ty } => { for &handle in components { if handle >= root { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 63541895b..aec49e450 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -208,7 +208,11 @@ impl VaryingContext<'_> { return Err(VaryingError::InvalidBuiltInType(built_in)); } } - crate::Binding::Location { location, interpolation, sampling } => { + crate::Binding::Location { + location, + interpolation, + sampling, + } => { if !self.location_mask.insert(location as usize) { return Err(VaryingError::BindingCollision { location }); } @@ -235,7 +239,8 @@ impl VaryingContext<'_> { } } Some(_) => { - if needs_interpolation && interpolation != Some(crate::Interpolation::Flat) { + if needs_interpolation && interpolation != Some(crate::Interpolation::Flat) + { return Err(VaryingError::InvalidInterpolation); } } diff --git a/tests/errors.rs b/tests/errors.rs index e9077220d..13bf5f1d8 100644 --- a/tests/errors.rs +++ b/tests/errors.rs @@ -76,24 +76,3 @@ fn invalid_scalar_width() { "###, ); } - -#[cfg(feature = "wgsl-in")] -#[test] -fn invalid_accessor() { - check( - r###" -[[stage(vertex)]] -fn vs_main() { - var color: vec3 = vec3(1.0, 2.0, 3.0); - var i: f32 = color.a; -} -"###, - r###"error: invalid field accessor `a` - ┌─ wgsl:5:24 - │ -5 │ var i: f32 = color.a; - │ ^ invalid accessor - -"###, - ); -} diff --git a/tests/out/image-copy.msl b/tests/out/image-copy.msl index 73407ceef..2db875cfc 100644 --- a/tests/out/image-copy.msl +++ b/tests/out/image-copy.msl @@ -9,8 +9,8 @@ kernel void main1( , metal::texture2d image_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 _e12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(metal::uint2(local_id.x, local_id.y))) % metal::int2(10, 20); - metal::uint4 _e13 = image_src.read(metal::uint2(_e12)); - image_dst.write(_e13, metal::uint(_e12.x)); + metal::int2 _e10 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(local_id.xy)) % metal::int2(10, 20); + metal::uint4 _e11 = image_src.read(metal::uint2(_e10)); + image_dst.write(_e11, metal::uint(_e10.x)); return; } diff --git a/tests/out/operators.Vertex.glsl b/tests/out/operators.Vertex.glsl index 97d6d3c20..88898e6ef 100644 --- a/tests/out/operators.Vertex.glsl +++ b/tests/out/operators.Vertex.glsl @@ -4,8 +4,7 @@ precision highp float; void main() { - vec2 _expr10 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); - gl_Position = (vec4(_expr10[0], _expr10[1], _expr10[0], _expr10[1]) + vec4((ivec4(5) % ivec4(2)))); + gl_Position = ((((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)).xyxy + vec4((ivec4(5) % ivec4(2)))); return; } diff --git a/tests/out/operators.msl b/tests/out/operators.msl index 79d2ced84..4d3c3d9f3 100644 --- a/tests/out/operators.msl +++ b/tests/out/operators.msl @@ -7,6 +7,5 @@ struct splatOutput { }; vertex splatOutput splat( ) { - metal::float2 _e10 = ((float2(1.0) + float2(2.0)) - float2(3.0)) / float2(4.0); - return splatOutput { metal::float4(_e10.x, _e10.y, _e10.x, _e10.y) + static_cast(int4(5) % int4(2)) }; + return splatOutput { (((float2(1.0) + float2(2.0)) - float2(3.0)) / float2(4.0)).xyxy + static_cast(int4(5) % int4(2)) }; } diff --git a/tests/out/operators.spvasm b/tests/out/operators.spvasm index 6ee2477c3..cc7c22511 100644 --- a/tests/out/operators.spvasm +++ b/tests/out/operators.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 37 +; Bound: 33 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -36,13 +36,9 @@ OpBranch %17 %27 = OpCompositeConstruct %26 %8 %8 %8 %8 %28 = OpCompositeConstruct %26 %10 %10 %10 %10 %29 = OpSMod %26 %27 %28 -%30 = OpCompositeExtract %4 %25 0 -%31 = OpCompositeExtract %4 %25 1 -%32 = OpCompositeExtract %4 %25 0 -%33 = OpCompositeExtract %4 %25 1 -%34 = OpCompositeConstruct %11 %30 %31 %32 %33 -%35 = OpConvertSToF %11 %29 -%36 = OpFAdd %11 %34 %35 -OpStore %13 %36 +%30 = OpVectorShuffle %11 %25 %25 0 1 0 1 +%31 = OpConvertSToF %11 %29 +%32 = OpFAdd %11 %30 %31 +OpStore %13 %32 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index b045c7250..e1310ca34 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -26,8 +26,8 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { if((homogeneous_coords[3] <= 0.0)) { return 1.0; } - float _expr28 = textureGrad(_group_0_binding_2, vec4((((vec2(homogeneous_coords[0], homogeneous_coords[1]) * vec2(0.5, -0.5)) / vec2(homogeneous_coords[3])) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] / homogeneous_coords[3])), vec2(0, 0), vec2(0,0)); - return _expr28; + float _expr26 = textureGrad(_group_0_binding_2, vec4((((homogeneous_coords.xy * vec2(0.5, -0.5)) / vec2(homogeneous_coords[3])) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] / homogeneous_coords[3])), vec2(0, 0), vec2(0,0)); + return _expr26; } void main() { @@ -41,7 +41,7 @@ void main() { } Light _expr21 = _group_0_binding_1.data[i]; float _expr25 = fetch_shadow(i, (_expr21.proj * position)); - color1 = (color1 + ((_expr25 * max(0.0, dot(normalize(raw_normal), normalize((vec3(_expr21.pos[0], _expr21.pos[1], _expr21.pos[2]) - vec3(position[0], position[1], position[2])))))) * vec3(_expr21.color[0], _expr21.color[1], _expr21.color[2]))); + color1 = (color1 + ((_expr25 * max(0.0, dot(normalize(raw_normal), normalize((_expr21.pos.xyz - position.xyz))))) * _expr21.color.xyz)); i = (i + 1u); } _fs2p_location0 = vec4(color1, 1.0); diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index 12a5c43bb..0ff4e18f4 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -25,8 +25,8 @@ float fetch_shadow( if (homogeneous_coords.w <= 0.0) { return 1.0; } - float _e28 = t_shadow.sample_compare(sampler_shadow, ((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(0.5, -0.5)) / float2(homogeneous_coords.w)) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); - return _e28; + float _e26 = t_shadow.sample_compare(sampler_shadow, ((homogeneous_coords.xy * metal::float2(0.5, -0.5)) / float2(homogeneous_coords.w)) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); + return _e26; } struct fs_mainInput { @@ -58,7 +58,7 @@ fragment fs_mainOutput fs_main( } Light _e21 = s_lights.data[i]; float _e25 = fetch_shadow(i, _e21.proj * position, t_shadow, sampler_shadow); - color1 = color1 + ((_e25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(metal::float3(_e21.pos.x, _e21.pos.y, _e21.pos.z) - metal::float3(position.x, position.y, position.z))))) * metal::float3(_e21.color.x, _e21.color.y, _e21.color.z)); + color1 = color1 + ((_e25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(_e21.pos.xyz - position.xyz)))) * _e21.color.xyz); } return fs_mainOutput { metal::float4(color1, 1.0) }; } diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm index 1016e2060..2fd871667 100644 --- a/tests/out/shadow.spvasm +++ b/tests/out/shadow.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 137 +; Bound: 126 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %82 "fs_main" %74 %77 %80 -OpExecutionMode %82 OriginUpperLeft +OpEntryPoint Fragment %80 "fs_main" %72 %75 %78 +OpExecutionMode %80 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_max_lights" OpName %14 "Globals" @@ -24,11 +24,11 @@ OpName %27 "s_lights" OpName %29 "t_shadow" OpName %31 "sampler_shadow" OpName %36 "fetch_shadow" -OpName %69 "color" -OpName %71 "i" -OpName %74 "raw_normal" -OpName %77 "position" -OpName %82 "fs_main" +OpName %67 "color" +OpName %69 "i" +OpName %72 "raw_normal" +OpName %75 "position" +OpName %80 "fs_main" OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %17 0 Offset 0 @@ -48,9 +48,9 @@ OpDecorate %29 DescriptorSet 0 OpDecorate %29 Binding 2 OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 3 -OpDecorate %74 Location 0 -OpDecorate %77 Location 1 -OpDecorate %80 Location 0 +OpDecorate %72 Location 0 +OpDecorate %75 Location 1 +OpDecorate %78 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 @@ -84,22 +84,22 @@ OpDecorate %80 Location 0 %31 = OpVariable %32 UniformConstant %37 = OpTypeFunction %4 %10 %16 %42 = OpTypeBool -%56 = OpTypeInt 32 1 -%61 = OpTypeSampledImage %20 -%68 = OpConstant %4 0.0 -%70 = OpTypePointer Function %23 -%72 = OpTypePointer Function %10 -%75 = OpTypePointer Input %23 -%74 = OpVariable %75 Input -%78 = OpTypePointer Input %16 -%77 = OpVariable %78 Input -%81 = OpTypePointer Output %16 -%80 = OpVariable %81 Output -%83 = OpTypeFunction %2 -%93 = OpTypePointer Uniform %13 -%94 = OpConstant %56 0 -%102 = OpTypePointer StorageBuffer %18 -%104 = OpTypePointer StorageBuffer %17 +%54 = OpTypeInt 32 1 +%59 = OpTypeSampledImage %20 +%66 = OpConstant %4 0.0 +%68 = OpTypePointer Function %23 +%70 = OpTypePointer Function %10 +%73 = OpTypePointer Input %23 +%72 = OpVariable %73 Input +%76 = OpTypePointer Input %16 +%75 = OpVariable %76 Input +%79 = OpTypePointer Output %16 +%78 = OpVariable %79 Output +%81 = OpTypeFunction %2 +%91 = OpTypePointer Uniform %13 +%92 = OpConstant %54 0 +%100 = OpTypePointer StorageBuffer %18 +%102 = OpTypePointer StorageBuffer %17 %36 = OpFunction %4 None %37 %34 = OpFunctionParameter %10 %35 = OpFunctionParameter %16 @@ -116,93 +116,82 @@ OpBranchConditional %43 %45 %44 OpReturnValue %5 %44 = OpLabel %46 = OpCompositeConstruct %22 %6 %7 -%47 = OpCompositeExtract %4 %35 0 -%48 = OpCompositeExtract %4 %35 1 -%49 = OpCompositeConstruct %22 %47 %48 -%50 = OpFMul %22 %49 %46 -%51 = OpCompositeExtract %4 %35 3 -%52 = OpCompositeConstruct %22 %51 %51 -%53 = OpFDiv %22 %50 %52 -%54 = OpCompositeConstruct %22 %6 %6 -%55 = OpFAdd %22 %53 %54 -%57 = OpBitcast %56 %34 -%58 = OpCompositeExtract %4 %35 2 -%59 = OpCompositeExtract %4 %35 3 -%60 = OpFDiv %4 %58 %59 -%62 = OpCompositeExtract %4 %55 0 -%63 = OpCompositeExtract %4 %55 1 -%64 = OpConvertUToF %4 %57 -%65 = OpCompositeConstruct %23 %62 %63 %64 -%66 = OpSampledImage %61 %38 %39 -%67 = OpImageSampleDrefExplicitLod %4 %66 %65 %60 Lod %68 -OpReturnValue %67 +%47 = OpVectorShuffle %22 %35 %35 0 1 +%48 = OpFMul %22 %47 %46 +%49 = OpCompositeExtract %4 %35 3 +%50 = OpCompositeConstruct %22 %49 %49 +%51 = OpFDiv %22 %48 %50 +%52 = OpCompositeConstruct %22 %6 %6 +%53 = OpFAdd %22 %51 %52 +%55 = OpBitcast %54 %34 +%56 = OpCompositeExtract %4 %35 2 +%57 = OpCompositeExtract %4 %35 3 +%58 = OpFDiv %4 %56 %57 +%60 = OpCompositeExtract %4 %53 0 +%61 = OpCompositeExtract %4 %53 1 +%62 = OpConvertUToF %4 %55 +%63 = OpCompositeConstruct %23 %60 %61 %62 +%64 = OpSampledImage %59 %38 %39 +%65 = OpImageSampleDrefExplicitLod %4 %64 %63 %58 Lod %66 +OpReturnValue %65 OpFunctionEnd -%82 = OpFunction %2 None %83 -%73 = OpLabel -%69 = OpVariable %70 Function %24 -%71 = OpVariable %72 Function %11 -%76 = OpLoad %23 %74 -%79 = OpLoad %16 %77 -%84 = OpLoad %20 %29 -%85 = OpLoad %21 %31 +%80 = OpFunction %2 None %81 +%71 = OpLabel +%67 = OpVariable %68 Function %24 +%69 = OpVariable %70 Function %11 +%74 = OpLoad %23 %72 +%77 = OpLoad %16 %75 +%82 = OpLoad %20 %29 +%83 = OpLoad %21 %31 +OpBranch %84 +%84 = OpLabel +%85 = OpExtInst %23 %1 Normalize %74 OpBranch %86 %86 = OpLabel -%87 = OpExtInst %23 %1 Normalize %76 +OpLoopMerge %87 %89 None OpBranch %88 %88 = OpLabel -OpLoopMerge %89 %91 None -OpBranch %90 -%90 = OpLabel -%92 = OpLoad %10 %71 -%95 = OpAccessChain %93 %25 %94 -%96 = OpLoad %13 %95 -%97 = OpCompositeExtract %10 %96 0 -%98 = OpExtInst %10 %1 UMin %97 %9 -%99 = OpUGreaterThanEqual %42 %92 %98 -OpSelectionMerge %100 None -OpBranchConditional %99 %101 %100 -%101 = OpLabel +%90 = OpLoad %10 %69 +%93 = OpAccessChain %91 %25 %92 +%94 = OpLoad %13 %93 +%95 = OpCompositeExtract %10 %94 0 +%96 = OpExtInst %10 %1 UMin %95 %9 +%97 = OpUGreaterThanEqual %42 %90 %96 +OpSelectionMerge %98 None +OpBranchConditional %97 %99 %98 +%99 = OpLabel +OpBranch %87 +%98 = OpLabel +%101 = OpLoad %10 %69 +%103 = OpAccessChain %102 %27 %92 %101 +%104 = OpLoad %17 %103 +%105 = OpLoad %10 %69 +%106 = OpCompositeExtract %15 %104 0 +%107 = OpMatrixTimesVector %16 %106 %77 +%108 = OpFunctionCall %4 %36 %105 %107 +%109 = OpCompositeExtract %16 %104 1 +%110 = OpVectorShuffle %23 %109 %109 0 1 2 +%111 = OpVectorShuffle %23 %77 %77 0 1 2 +%112 = OpFSub %23 %110 %111 +%113 = OpExtInst %23 %1 Normalize %112 +%114 = OpDot %4 %85 %113 +%115 = OpExtInst %4 %1 FMax %3 %114 +%116 = OpLoad %23 %67 +%117 = OpFMul %4 %108 %115 +%118 = OpCompositeExtract %16 %104 2 +%119 = OpVectorShuffle %23 %118 %118 0 1 2 +%120 = OpVectorTimesScalar %23 %119 %117 +%121 = OpFAdd %23 %116 %120 +OpStore %67 %121 OpBranch %89 -%100 = OpLabel -%103 = OpLoad %10 %71 -%105 = OpAccessChain %104 %27 %94 %103 -%106 = OpLoad %17 %105 -%107 = OpLoad %10 %71 -%108 = OpCompositeExtract %15 %106 0 -%109 = OpMatrixTimesVector %16 %108 %79 -%110 = OpFunctionCall %4 %36 %107 %109 -%111 = OpCompositeExtract %16 %106 1 -%112 = OpCompositeExtract %4 %111 0 -%113 = OpCompositeExtract %4 %111 1 -%114 = OpCompositeExtract %4 %111 2 -%115 = OpCompositeConstruct %23 %112 %113 %114 -%116 = OpCompositeExtract %4 %79 0 -%117 = OpCompositeExtract %4 %79 1 -%118 = OpCompositeExtract %4 %79 2 -%119 = OpCompositeConstruct %23 %116 %117 %118 -%120 = OpFSub %23 %115 %119 -%121 = OpExtInst %23 %1 Normalize %120 -%122 = OpDot %4 %87 %121 -%123 = OpExtInst %4 %1 FMax %3 %122 -%124 = OpLoad %23 %69 -%125 = OpFMul %4 %110 %123 -%126 = OpCompositeExtract %16 %106 2 -%127 = OpCompositeExtract %4 %126 0 -%128 = OpCompositeExtract %4 %126 1 -%129 = OpCompositeExtract %4 %126 2 -%130 = OpCompositeConstruct %23 %127 %128 %129 -%131 = OpVectorTimesScalar %23 %130 %125 -%132 = OpFAdd %23 %124 %131 -OpStore %69 %132 -OpBranch %91 -%91 = OpLabel -%133 = OpLoad %10 %71 -%134 = OpIAdd %10 %133 %12 -OpStore %71 %134 -OpBranch %88 %89 = OpLabel -%135 = OpLoad %23 %69 -%136 = OpCompositeConstruct %16 %135 %5 -OpStore %80 %136 +%122 = OpLoad %10 %69 +%123 = OpIAdd %10 %122 %12 +OpStore %69 %123 +OpBranch %86 +%87 = OpLabel +%124 = OpLoad %23 %67 +%125 = OpCompositeConstruct %16 %124 %5 +OpStore %78 %125 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/skybox.Vertex.glsl b/tests/out/skybox.Vertex.glsl index e76121da3..e543e836b 100644 --- a/tests/out/skybox.Vertex.glsl +++ b/tests/out/skybox.Vertex.glsl @@ -21,9 +21,8 @@ void main() { tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); vec4 _expr24 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - vec4 _expr50 = (_group_0_binding_0.proj_inv * _expr24); - gl_Position = VertexOutput(_expr24, (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr50[0], _expr50[1], _expr50[2]))).position; - _vs2fs_location0 = VertexOutput(_expr24, (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr50[0], _expr50[1], _expr50[2]))).uv; + gl_Position = VertexOutput(_expr24, (transpose(mat3x3(_group_0_binding_0.view[0].xyz, _group_0_binding_0.view[1].xyz, _group_0_binding_0.view[2].xyz)) * (_group_0_binding_0.proj_inv * _expr24).xyz)).position; + _vs2fs_location0 = VertexOutput(_expr24, (transpose(mat3x3(_group_0_binding_0.view[0].xyz, _group_0_binding_0.view[1].xyz, _group_0_binding_0.view[2].xyz)) * (_group_0_binding_0.proj_inv * _expr24).xyz)).uv; return; } diff --git a/tests/out/skybox.msl b/tests/out/skybox.msl index bd3763713..c3ba81213 100644 --- a/tests/out/skybox.msl +++ b/tests/out/skybox.msl @@ -25,8 +25,7 @@ vertex vs_mainOutput vs_main( tmp1_ = static_cast(vertex_index) / 2; tmp2_ = static_cast(vertex_index) & 1; metal::float4 _e24 = metal::float4((static_cast(tmp1_) * 4.0) - 1.0, (static_cast(tmp2_) * 4.0) - 1.0, 0.0, 1.0); - metal::float4 _e50 = r_data.proj_inv * _e24; - const auto _tmp = VertexOutput {_e24, metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_e50.x, _e50.y, _e50.z)}; + const auto _tmp = VertexOutput {_e24, metal::transpose(metal::float3x3(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz)) * (r_data.proj_inv * _e24).xyz}; return vs_mainOutput { _tmp.position, _tmp.uv }; } diff --git a/tests/out/skybox.spvasm b/tests/out/skybox.spvasm index c51900db3..ee13bf6fc 100644 --- a/tests/out/skybox.spvasm +++ b/tests/out/skybox.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 105 +; Bound: 93 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %36 "vs_main" %29 %32 %34 -OpEntryPoint Fragment %97 "fs_main" %90 %93 %96 -OpExecutionMode %97 OriginUpperLeft +OpEntryPoint Fragment %85 "fs_main" %78 %81 %84 +OpExecutionMode %85 OriginUpperLeft OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpDecorate %14 Block @@ -26,9 +26,9 @@ OpDecorate %23 Binding 2 OpDecorate %29 BuiltIn VertexIndex OpDecorate %32 BuiltIn Position OpDecorate %34 Location 0 -OpDecorate %90 BuiltIn FragCoord -OpDecorate %93 Location 0 -OpDecorate %96 Location 0 +OpDecorate %78 BuiltIn FragCoord +OpDecorate %81 Location 0 +OpDecorate %84 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -61,13 +61,13 @@ OpDecorate %96 Location 0 %34 = OpVariable %35 Output %37 = OpTypeFunction %2 %52 = OpTypePointer Uniform %13 -%76 = OpConstant %4 0 -%91 = OpTypePointer Input %10 -%90 = OpVariable %91 Input -%94 = OpTypePointer Input %11 -%93 = OpVariable %94 Input -%96 = OpVariable %33 Output -%102 = OpTypeSampledImage %17 +%67 = OpConstant %4 0 +%79 = OpTypePointer Input %10 +%78 = OpVariable %79 Input +%82 = OpTypePointer Input %11 +%81 = OpVariable %82 Input +%84 = OpVariable %33 Output +%90 = OpTypeSampledImage %17 %36 = OpFunction %2 None %37 %28 = OpLabel %25 = OpVariable %26 Function @@ -93,53 +93,41 @@ OpStore %27 %42 %53 = OpAccessChain %52 %19 %5 %54 = OpLoad %13 %53 %55 = OpCompositeExtract %10 %54 0 -%56 = OpCompositeExtract %7 %55 0 -%57 = OpCompositeExtract %7 %55 1 -%58 = OpCompositeExtract %7 %55 2 -%59 = OpCompositeConstruct %11 %56 %57 %58 -%60 = OpAccessChain %52 %19 %5 -%61 = OpLoad %13 %60 -%62 = OpCompositeExtract %10 %61 1 -%63 = OpCompositeExtract %7 %62 0 -%64 = OpCompositeExtract %7 %62 1 -%65 = OpCompositeExtract %7 %62 2 -%66 = OpCompositeConstruct %11 %63 %64 %65 -%67 = OpAccessChain %52 %19 %5 -%68 = OpLoad %13 %67 -%69 = OpCompositeExtract %10 %68 2 -%70 = OpCompositeExtract %7 %69 0 -%71 = OpCompositeExtract %7 %69 1 -%72 = OpCompositeExtract %7 %69 2 -%73 = OpCompositeConstruct %11 %70 %71 %72 -%74 = OpCompositeConstruct %16 %59 %66 %73 -%75 = OpTranspose %16 %74 -%77 = OpAccessChain %52 %19 %76 -%78 = OpLoad %13 %77 -%79 = OpMatrixTimesVector %10 %78 %51 -%80 = OpCompositeExtract %7 %79 0 -%81 = OpCompositeExtract %7 %79 1 -%82 = OpCompositeExtract %7 %79 2 -%83 = OpCompositeConstruct %11 %80 %81 %82 -%84 = OpMatrixTimesVector %11 %75 %83 -%85 = OpCompositeConstruct %12 %51 %84 -%86 = OpCompositeExtract %10 %85 0 -OpStore %32 %86 -%87 = OpCompositeExtract %11 %85 1 -OpStore %34 %87 +%56 = OpVectorShuffle %11 %55 %55 0 1 2 +%57 = OpAccessChain %52 %19 %5 +%58 = OpLoad %13 %57 +%59 = OpCompositeExtract %10 %58 1 +%60 = OpVectorShuffle %11 %59 %59 0 1 2 +%61 = OpAccessChain %52 %19 %5 +%62 = OpLoad %13 %61 +%63 = OpCompositeExtract %10 %62 2 +%64 = OpVectorShuffle %11 %63 %63 0 1 2 +%65 = OpCompositeConstruct %16 %56 %60 %64 +%66 = OpTranspose %16 %65 +%68 = OpAccessChain %52 %19 %67 +%69 = OpLoad %13 %68 +%70 = OpMatrixTimesVector %10 %69 %51 +%71 = OpVectorShuffle %11 %70 %70 0 1 2 +%72 = OpMatrixTimesVector %11 %66 %71 +%73 = OpCompositeConstruct %12 %51 %72 +%74 = OpCompositeExtract %10 %73 0 +OpStore %32 %74 +%75 = OpCompositeExtract %11 %73 1 +OpStore %34 %75 OpReturn OpFunctionEnd -%97 = OpFunction %2 None %37 +%85 = OpFunction %2 None %37 +%76 = OpLabel +%80 = OpLoad %10 %78 +%83 = OpLoad %11 %81 +%77 = OpCompositeConstruct %12 %80 %83 +%86 = OpLoad %17 %21 +%87 = OpLoad %18 %23 +OpBranch %88 %88 = OpLabel -%92 = OpLoad %10 %90 -%95 = OpLoad %11 %93 -%89 = OpCompositeConstruct %12 %92 %95 -%98 = OpLoad %17 %21 -%99 = OpLoad %18 %23 -OpBranch %100 -%100 = OpLabel -%101 = OpCompositeExtract %11 %89 1 -%103 = OpSampledImage %102 %98 %99 -%104 = OpImageSampleImplicitLod %10 %103 %101 -OpStore %96 %104 +%89 = OpCompositeExtract %11 %77 1 +%91 = OpSampledImage %90 %86 %87 +%92 = OpImageSampleImplicitLod %10 %91 %89 +OpStore %84 %92 OpReturn OpFunctionEnd \ No newline at end of file From 4664cd301aaca7e8f77b15aa5162b3730e255de4 Mon Sep 17 00:00:00 2001 From: Ashley Date: Wed, 21 Apr 2021 15:16:11 +0200 Subject: [PATCH 0729/2212] [Metal] Wrap a `packed_float3` with `float3` when loading from struct (#740) * Implement the wrapping in Expression::Load instead * Add changes to stack size * stable and nightly can't seem to agree on a stack size * Apply suggestions * Add a comment about unexpected path * Update skybox snapshot * should_pack_struct_member returns an Option * Remove accidental file --- src/back/msl/writer.rs | 97 +++++++++++++++++++++++++++++++++--------- tests/out/skybox.msl | 2 +- 2 files changed, 79 insertions(+), 20 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index fcf815105..4bbdf065a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -311,6 +311,32 @@ fn separate(need_separator: bool) -> &'static str { } } +fn should_pack_struct_member( + members: &[crate::StructMember], + span: u32, + index: usize, + module: &crate::Module, +) -> Option { + let member = &members[index]; + let ty_inner = &module.types[member.ty].inner; + + let last_offset = member.offset + ty_inner.span(&module.constants); + let next_offset = match members.get(index + 1) { + Some(next) => next.offset, + None => span, + }; + let is_tight = next_offset == last_offset; + + match *ty_inner { + crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + width: 4, + kind, + } if member.offset & 0xF != 0 || is_tight => Some(kind), + _ => None, + } +} + impl crate::StorageClass { /// Returns true for storage classes, for which the global /// variables are passed in function arguments. @@ -700,10 +726,48 @@ impl Writer { write!(self.out, "{}", name)?; } crate::Expression::Load { pointer } => { - // We don't do any dereferencing with `*` here as pointer arguments to functions - // are done by `&` references and not `*` pointers. These do not need to be - // dereferenced. - self.put_expression(pointer, context, is_scoped)?; + // Because packed vectors such as `packed_float3` cannot be directly multipied by + // matrices, we wrap them with `float3` on load. + let wrap_packed_vec_scalar_kind = match context.function.expressions[pointer] { + crate::Expression::AccessIndex { base, index } => { + let ty = match context.resolve_type(base) { + &crate::TypeInner::Pointer { base, .. } => { + &context.module.types[base].inner + } + // This path is unexpected and shouldn't happen, but it's easier + // to leave in. + ty => ty, + }; + match *ty { + crate::TypeInner::Struct { + ref members, span, .. + } => should_pack_struct_member( + members, + span, + index as usize, + &context.module, + ), + _ => None, + } + } + _ => None, + }; + + if let Some(scalar_kind) = wrap_packed_vec_scalar_kind { + write!( + self.out, + "{}::{}3(", + NAMESPACE, + scalar_kind_string(scalar_kind) + )?; + self.put_expression(pointer, context, true)?; + write!(self.out, ")")?; + } else { + // We don't do any dereferencing with `*` here as pointer arguments to functions + // are done by `&` references and not `*` pointers. These do not need to be + // dereferenced. + self.put_expression(pointer, context, is_scoped)?; + } } crate::Expression::ImageSample { image, @@ -1428,7 +1492,9 @@ impl Writer { } } } - crate::TypeInner::Struct { ref members, .. } => { + crate::TypeInner::Struct { + ref members, span, .. + } => { writeln!(self.out, "struct {} {{", name)?; let mut last_offset = 0; for (index, member) in members.iter().enumerate() { @@ -1440,19 +1506,12 @@ impl Writer { } let ty_inner = &module.types[member.ty].inner; last_offset = member.offset + ty_inner.span(&module.constants); - let is_tight = match members.get(index + 1) { - Some(next) => next.offset == last_offset, - None => false, - }; + let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; - match *ty_inner { - // for a misaligned vec3, issue a packed vector - crate::TypeInner::Vector { - size: crate::VectorSize::Tri, - kind, - width: 4, - } if member.offset & 0xF != 0 || is_tight => { + // If the member should be packed (as is the case for a misaligned vec3) issue a packed vector + match should_pack_struct_member(members, span, index, module) { + Some(kind) => { writeln!( self.out, "{}packed_{}3 {};", @@ -1461,7 +1520,7 @@ impl Writer { member_name )?; } - _ => { + None => { let base_name = TypeContext { handle: member.ty, arena: &module.types, @@ -2179,8 +2238,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 21584 - if stack_size < 20000 || stack_size > 22000 { + // last observed macOS value: 21760 + if stack_size < 21000 || stack_size > 23000 { panic!("`put_expression` stack size {} has changed!", stack_size); } } diff --git a/tests/out/skybox.msl b/tests/out/skybox.msl index c3ba81213..6b5409773 100644 --- a/tests/out/skybox.msl +++ b/tests/out/skybox.msl @@ -3,7 +3,7 @@ struct VertexOutput { metal::float4 position; - metal::float3 uv; + packed_float3 uv; }; struct Data { metal::float4x4 proj_inv; From b86c2fbeebf520a3dcb13c4d22ca4f34b61efdde Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 21 Apr 2021 09:40:29 -0400 Subject: [PATCH 0730/2212] Don't print the module in converter if no output is specified (#744) --- README.md | 5 +++-- bin/convert.rs | 18 +++++++++++++----- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 2224fab6e..6482c9ab4 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Front-end | Status | Feature | Notes | --------------- | ------------------ | ------- | ----- | SPIR-V (binary) | :white_check_mark: | spv-in | | WGSL | :white_check_mark: | wgsl-in | | -GLSL | :ok: | glsl-in | Vulkan flavor is expected | +GLSL | :construction: | glsl-in | Vulkan flavor is expected | Rust | | | | Back-end | Status | Feature | Notes | @@ -36,7 +36,8 @@ DOT (GraphViz) | :ok: | dot-out | Not a shading language | Naga includes a default binary target "convert", which allows to test the conversion of different code paths. ```bash -cargo run --features spv-in -- my_shader.spv # dump the IR module to debug output +cargo run --features wgsl-in -- my_shader.wgsl # validate only +cargo run --features spv-in -- my_shader.spv - # dump the IR module to debug output cargo run --features spv-in,msl-out -- my_shader.spv my_shader.metal --flow-dir flow-dir # convert the SPV to Metal, also dump the SPIR-V flow graph to `flow-dir` cargo run --features wgsl-in,glsl-out -- my_shader.wgsl my_shader.vert --profile es310 # convert the WGSL to GLSL vertex stage under ES 3.20 profile ``` diff --git a/bin/convert.rs b/bin/convert.rs index 978756cff..126c4d7d4 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -23,10 +23,10 @@ trait PrettyResult { } fn print_err(error: impl Error) { - println!("{}:", error); + eprintln!("{}:", error); let mut e = error.source(); while let Some(source) = e { - println!("\t{}", source); + eprintln!("\t{}", source); e = source.source(); } } @@ -174,7 +174,6 @@ fn main() { }; // validate the IR - #[allow(unused_variables)] let info = match naga::valid::Validator::new(naga::valid::ValidationFlags::all()).validate(&module) { Ok(info) => Some(info), @@ -187,11 +186,20 @@ fn main() { let output_path = match output_path { Some(ref string) => string, None => { - println!("{:#?}", module); - println!("{:#?}", info); + if info.is_some() { + println!("Validation successful"); + } return; } }; + if output_path == "-" { + println!("{:#?}", module); + if let Some(info) = info { + println!(); + println!("{:#?}", info); + } + return; + } match Path::new(output_path) .extension() From bc344579e81cae0b85f18a154bffc7c3895e6813 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 21 Apr 2021 11:04:53 -0400 Subject: [PATCH 0731/2212] [spv-in] fix signed/unsigned casting for builtins (#746) --- src/front/spv/function.rs | 24 +++++++++++++++++++----- src/front/spv/mod.rs | 17 ++++++++--------- tests/out/shadow.info.ron | 36 ++++++++++++++++++------------------ tests/out/shadow.ron | 12 ++++++------ 4 files changed, 51 insertions(+), 38 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 1116f0e82..3ab6a9780 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -201,16 +201,30 @@ impl> super::Parser { for &v_id in ep.variable_ids.iter() { let lvar = self.lookup_variable.lookup(v_id)?; if let super::Variable::Input(ref arg) = lvar.inner { + let arg_expr = + function + .expressions + .append(crate::Expression::FunctionArgument( + function.arguments.len() as u32, + )); + let load_expr = if arg.ty == module.global_variables[lvar.handle].ty { + arg_expr + } else { + // The only case where the type is different is if we need to treat + // unsigned integer as signed. + function.expressions.append(crate::Expression::As { + expr: arg_expr, + kind: crate::ScalarKind::Sint, + convert: true, + }) + }; function.body.push(crate::Statement::Store { pointer: function .expressions .append(crate::Expression::GlobalVariable(lvar.handle)), - value: function - .expressions - .append(crate::Expression::FunctionArgument( - function.arguments.len() as u32, - )), + value: load_expr, }); + let mut arg = arg.clone(); if ep.stage == crate::ShaderStage::Fragment { if let Some(crate::Binding::Location { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index eaf9dbc09..4da603895 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3039,17 +3039,16 @@ impl> Parser { }; let dec = self.future_decor.remove(&id).unwrap_or_default(); - let mut effective_ty = self.lookup_type.lookup(type_id)?.handle; - let is_storage = match module.types[effective_ty].inner { + let original_ty = self.lookup_type.lookup(type_id)?.handle; + let (effective_ty, is_storage) = match module.types[original_ty].inner { crate::TypeInner::Pointer { base, class } => { - effective_ty = base; - class == crate::StorageClass::Storage + (base, class == crate::StorageClass::Storage) } crate::TypeInner::Image { class: crate::ImageClass::Storage(_), .. - } => true, - _ => false, + } => (original_ty, true), + _ => (original_ty, false), }; let ext_class = if self.lookup_storage_buffer_types.contains(&effective_ty) { ExtendedClass::Global(crate::StorageClass::Storage) @@ -3084,6 +3083,7 @@ impl> Parser { } ExtendedClass::Input => { let binding = dec.io_binding()?; + let mut unsigned_ty = effective_ty; if let crate::Binding::BuiltIn(built_in) = binding { let needs_inner_uint = match built_in { crate::BuiltIn::BaseInstance @@ -3109,8 +3109,7 @@ impl> Parser { needs_inner_uint, module.types[effective_ty].inner.scalar_kind(), ) { - log::warn!("Treating {:?} as unsigned", built_in); - effective_ty = module + unsigned_ty = module .types .fetch_or_append(crate::Type { name: None, inner }); } @@ -3126,7 +3125,7 @@ impl> Parser { }; let inner = Variable::Input(crate::FunctionArgument { name: dec.name, - ty: effective_ty, + ty: unsigned_ty, binding: Some(binding), }); (inner, var) diff --git a/tests/out/shadow.info.ron b/tests/out/shadow.info.ron index d1491f6c8..6d59c22e6 100644 --- a/tests/out/shadow.info.ron +++ b/tests/out/shadow.info.ron @@ -2803,11 +2803,8 @@ ), ), ref_count: 1, - assignable_global: Some(6), - ty: Value(Pointer( - base: 2, - class: Private, - )), + assignable_global: None, + ty: Handle(2), ), ( uniformity: ( @@ -2817,8 +2814,11 @@ ), ), ref_count: 1, - assignable_global: None, - ty: Handle(2), + assignable_global: Some(6), + ty: Value(Pointer( + base: 2, + class: Private, + )), ), ( uniformity: ( @@ -2828,23 +2828,23 @@ ), ), ref_count: 1, + assignable_global: None, + ty: Handle(4), + ), + ( + uniformity: ( + non_uniform_result: Some(4), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, assignable_global: Some(5), ty: Value(Pointer( base: 4, class: Private, )), ), - ( - uniformity: ( - non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(4), - ), ( uniformity: ( non_uniform_result: Some(5), diff --git a/tests/out/shadow.ron b/tests/out/shadow.ron index e99b3c012..e5d646fa9 100644 --- a/tests/out/shadow.ron +++ b/tests/out/shadow.ron @@ -1543,10 +1543,10 @@ )), local_variables: [], expressions: [ - GlobalVariable(6), FunctionArgument(0), - GlobalVariable(5), + GlobalVariable(6), FunctionArgument(1), + GlobalVariable(5), GlobalVariable(7), Load( pointer: 5, @@ -1554,12 +1554,12 @@ ], body: [ Store( - pointer: 1, - value: 2, + pointer: 2, + value: 1, ), Store( - pointer: 3, - value: 4, + pointer: 4, + value: 3, ), Call( function: 2, From a2e5284f82bacf5476022582a6fb86e63b733e70 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 21 Apr 2021 22:38:26 -0400 Subject: [PATCH 0732/2212] WGSL trailing commas (#743) * [wgsl-in] typedef Span * [wgsl-in] trailing comma for case list * [wgsl-in] trailing comma for constructors * Review fixes --- src/front/wgsl/lexer.rs | 27 +++++++- src/front/wgsl/mod.rs | 140 ++++++++++++++++++++-------------------- tests/in/quad.wgsl | 5 +- tests/in/skybox.wgsl | 2 +- 4 files changed, 98 insertions(+), 76 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 7e7c3019e..a0d1d6496 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -1,5 +1,4 @@ -use super::{conv, Error, Token, TokenSpan}; -use std::ops::Range; +use super::{conv, Error, Span, Token, TokenSpan}; fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { if input.starts_with(what) { @@ -168,6 +167,10 @@ impl<'a> Lexer<'a> { } } + pub(super) fn _leftover_span(&self) -> Span { + self.source.len() - self.input.len()..self.source.len() + } + fn peek_token_and_rest(&mut self) -> (TokenSpan<'a>, &'a str) { let mut cloned = self.clone(); let token = cloned.next(); @@ -256,7 +259,7 @@ impl<'a> Lexer<'a> { } } - pub(super) fn next_ident_with_span(&mut self) -> Result<(&'a str, Range), Error<'a>> { + pub(super) fn next_ident_with_span(&mut self) -> Result<(&'a str, Span), Error<'a>> { match self.next() { (Token::Word(word), span) => Ok((word, span)), other => Err(Error::Unexpected(other, "identifier")), @@ -311,6 +314,24 @@ impl<'a> Lexer<'a> { self.expect(Token::Paren('>'))?; Ok(format) } + + pub(super) fn open_arguments(&mut self) -> Result<(), Error<'a>> { + self.expect(Token::Paren('(')) + } + + pub(super) fn close_arguments(&mut self) -> Result<(), Error<'a>> { + let _ = self.skip(Token::Separator(',')); + self.expect(Token::Paren(')')) + } + + pub(super) fn next_argument(&mut self) -> Result> { + let paren = Token::Paren(')'); + if self.skip(Token::Separator(',')) { + Ok(!self.skip(paren)) + } else { + self.expect(paren).map(|()| false) + } + } } #[cfg(test)] diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index cd96de496..9d30fe1af 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -27,11 +27,12 @@ use std::{ io::{self, Write}, iter, num::NonZeroU32, - ops::Range, + ops, }; use thiserror::Error; -type TokenSpan<'a> = (Token<'a>, Range); +type Span = ops::Range; +type TokenSpan<'a> = (Token<'a>, Span); #[derive(Copy, Clone, Debug, PartialEq)] pub enum Token<'a> { @@ -61,13 +62,13 @@ pub enum Error<'a> { #[error("")] Unexpected(TokenSpan<'a>, &'a str), #[error("")] - BadInteger(Range), + BadInteger(Span), #[error("")] - BadFloat(Range), + BadFloat(Span), #[error("")] - BadScalarWidth(Range, &'a str), + BadScalarWidth(Span, &'a str), #[error("")] - BadAccessor(Range), + BadAccessor(Span), #[error("bad texture {0}`")] BadTexture(&'a str), #[error("bad texture coordinate")] @@ -396,7 +397,7 @@ impl Composition { } } - fn extract_impl(name: &str, name_span: Range) -> Result { + fn extract_impl(name: &str, name_span: Span) -> Result { let ch = name .chars() .next() @@ -410,13 +411,13 @@ impl Composition { fn extract( base: Handle, name: &str, - name_span: Range, + name_span: Span, ) -> Result { Self::extract_impl(name, name_span) .map(|index| crate::Expression::AccessIndex { base, index }) } - fn make(name: &str, name_span: Range) -> Result { + fn make(name: &str, name_span: Span) -> Result { if name.len() > 1 { let mut components = [crate::SwizzleComponent::X; 4]; for (comp, ch) in components.iter_mut().zip(name.chars()) { @@ -538,7 +539,7 @@ struct ParsedVariable<'a> { #[derive(Clone, Debug)] pub struct ParseError<'a> { message: String, - labels: Vec<(Range, String)>, + labels: Vec<(Span, String)>, notes: Vec, source: &'a str, } @@ -674,19 +675,17 @@ impl Parser { None => return Ok(None), }; - let mut arguments = Vec::new(); - lexer.expect(Token::Paren('('))?; - if !lexer.skip(Token::Paren(')')) { - loop { - let arg = self.parse_general_expression(lexer, ctx.reborrow())?; - arguments.push(arg); - match lexer.next() { - (Token::Paren(')'), _) => break, - (Token::Separator(','), _) => (), - other => return Err(Error::Unexpected(other, "argument list separator")), - } + let count = ctx.functions[fun_handle].arguments.len(); + let mut arguments = Vec::with_capacity(count); + lexer.open_arguments()?; + while arguments.len() != count { + if !arguments.is_empty() { + lexer.expect(Token::Separator(','))?; } + let arg = self.parse_general_expression(lexer, ctx.reborrow())?; + arguments.push(arg); } + lexer.close_arguments()?; Ok(Some((fun_handle, arguments))) } @@ -697,17 +696,17 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { let expr = if let Some(fun) = conv::map_relational_fun(name) { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let argument = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::Relational { fun, argument } } else if let Some(axis) = conv::map_derivative_axis(name) { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::Derivative { axis, expr } } else if let Some(fun) = conv::map_standard_fun(name) { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let arg_count = fun.argument_count(); let arg = self.parse_general_expression(lexer, ctx.reborrow())?; let arg1 = if arg_count > 1 { @@ -722,7 +721,7 @@ impl Parser { } else { None }; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::Math { fun, arg, @@ -730,13 +729,13 @@ impl Parser { arg2, } } else if name == "select" { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let accept = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let reject = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let condition = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::Select { condition, accept, @@ -746,7 +745,7 @@ impl Parser { // texture sampling match name { "textureSample" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let sampler_name = lexer.next_ident()?; @@ -764,7 +763,7 @@ impl Parser { } else { None }; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, @@ -776,7 +775,7 @@ impl Parser { } } "textureSampleLevel" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let sampler_name = lexer.next_ident()?; @@ -796,7 +795,7 @@ impl Parser { } else { None }; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, @@ -808,7 +807,7 @@ impl Parser { } } "textureSampleBias" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let sampler_name = lexer.next_ident()?; @@ -828,7 +827,7 @@ impl Parser { } else { None }; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, @@ -840,7 +839,7 @@ impl Parser { } } "textureSampleGrad" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let sampler_name = lexer.next_ident()?; @@ -862,7 +861,7 @@ impl Parser { } else { None }; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, @@ -874,7 +873,7 @@ impl Parser { } } "textureSampleCompare" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; lexer.expect(Token::Separator(','))?; let sampler_name = lexer.next_ident()?; @@ -894,7 +893,7 @@ impl Parser { } else { None }; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name)?, @@ -906,7 +905,7 @@ impl Parser { } } "textureLoad" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; let image = ctx.lookup_ident.lookup(image_name)?; lexer.expect(Token::Separator(','))?; @@ -929,7 +928,7 @@ impl Parser { Some(self.parse_general_expression(lexer, ctx.reborrow())?) } }; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageLoad { image, coordinate, @@ -938,7 +937,7 @@ impl Parser { } } "textureDimensions" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; let image = ctx.lookup_ident.lookup(image_name)?; let level = if lexer.skip(Token::Separator(',')) { @@ -947,37 +946,37 @@ impl Parser { } else { None }; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageQuery { image, query: crate::ImageQuery::Size { level }, } } "textureNumLevels" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; let image = ctx.lookup_ident.lookup(image_name)?; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageQuery { image, query: crate::ImageQuery::NumLevels, } } "textureNumLayers" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; let image = ctx.lookup_ident.lookup(image_name)?; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageQuery { image, query: crate::ImageQuery::NumLayers, } } "textureNumSamples" => { - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; let image = ctx.lookup_ident.lookup(image_name)?; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; crate::Expression::ImageQuery { image, query: crate::ImageQuery::NumSamples, @@ -1047,12 +1046,11 @@ impl Parser { type_arena, const_arena, )?; - lexer.expect(Token::Paren('('))?; + + lexer.open_arguments()?; + //Note: this expects at least one argument let mut components = Vec::new(); - while !lexer.skip(Token::Paren(')')) { - if !components.is_empty() { - lexer.expect(Token::Separator(','))?; - } + while components.is_empty() || lexer.next_argument()? { let component = self.parse_const_expression(lexer, type_arena, const_arena)?; components.push(component); } @@ -1139,15 +1137,15 @@ impl Parser { } }; - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let mut components = Vec::new(); let mut last_component = self.parse_general_expression(lexer, ctx.reborrow())?; - while lexer.skip(Token::Separator(',')) { + while lexer.next_argument()? { components.push(last_component); last_component = self.parse_general_expression(lexer, ctx.reborrow())?; } - lexer.expect(Token::Paren(')'))?; + let expr = if components.is_empty() { // We can't use the `TypeInner` returned by this because // `resolve_type` borrows context mutably. @@ -2206,22 +2204,22 @@ impl Parser { // cases + default match lexer.next() { (Token::Word("case"), _) => { + // parse a list of values let value = loop { - // values let value = lexer.next_sint_literal()?; - match lexer.next() { - (Token::Separator(','), _) => { - cases.push(crate::SwitchCase { - value, - body: Vec::new(), - fall_through: true, - }); - } - (Token::Separator(':'), _) => break value, - other => { - return Err(Error::Unexpected(other, "case separator")) + if lexer.skip(Token::Separator(',')) { + if lexer.skip(Token::Separator(':')) { + break value; } + } else { + lexer.expect(Token::Separator(':'))?; + break value; } + cases.push(crate::SwitchCase { + value, + body: Vec::new(), + fall_through: true, + }); }; let mut body = Vec::new(); @@ -2338,7 +2336,7 @@ impl Parser { "discard" => block.push(crate::Statement::Kill), "textureStore" => { emitter.start(context.expressions); - lexer.expect(Token::Paren('('))?; + lexer.open_arguments()?; let image_name = lexer.next_ident()?; let image = context.lookup_ident.lookup(image_name)?; lexer.expect(Token::Separator(','))?; @@ -2360,7 +2358,7 @@ impl Parser { lexer.expect(Token::Separator(','))?; let value = self .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; - lexer.expect(Token::Paren(')'))?; + lexer.close_arguments()?; block.extend(emitter.finish(context.expressions)); block.push(crate::Statement::ImageStore { image, diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 0cd0187a8..df1786361 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -7,7 +7,10 @@ struct VertexOutput { }; [[stage(vertex)]] -fn main([[location(0)]] pos : vec2, [[location(1)]] uv : vec2) -> VertexOutput { +fn main( + [[location(0)]] pos : vec2, + [[location(1)]] uv : vec2, +) -> VertexOutput { return VertexOutput(uv, vec4(c_scale * pos, 0.0, 1.0)); } diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index d5cb05126..96d0e1cee 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -20,7 +20,7 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { f32(tmp1) * 4.0 - 1.0, f32(tmp2) * 4.0 - 1.0, 0.0, - 1.0 + 1.0, ); let inv_model_view = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); From 24eaad10fc481e4bb0b4438941d40cabffb8c145 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 22 Apr 2021 11:17:44 -0400 Subject: [PATCH 0733/2212] Follow up on the swizzle PR review notes (#750) --- src/back/glsl/mod.rs | 2 +- src/front/glsl/constants.rs | 38 ++++++++++++++++++------------------- src/lib.rs | 9 +++++---- 3 files changed, 25 insertions(+), 24 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 002777f5e..a26865c2c 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1522,7 +1522,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(vector, ctx)?; write!(self.out, ".")?; for &sc in pattern[..size as usize].iter() { - write!(self.out, "{}", COMPONENTS[sc as usize])?; + self.out.write_char(COMPONENTS[sc as usize])?; } } // `Compose` is pretty simple we just write `type(components)` where `components` is a diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 82221f527..848fa40c1 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -70,8 +70,8 @@ impl<'a> ConstantSolver<'a> { size, value: splat_value, } => { - let tgt = self.solve(splat_value)?; - let ty = match self.constants[tgt].inner { + let value_constant = self.solve(splat_value)?; + let ty = match self.constants[value_constant].inner { ConstantInner::Scalar { ref value, width } => { let kind = value.scalar_kind(); self.types @@ -79,13 +79,15 @@ impl<'a> ConstantSolver<'a> { } ConstantInner::Composite { .. } => None, }; + + //TODO: register the new type if needed + let ty = ty.ok_or(ConstantSolvingError::DestinationTypeNotFound)?; Ok(self.constants.fetch_or_append(Constant { name: None, specialization: None, inner: ConstantInner::Composite { - //TODO: register the new type if needed - ty: ty.ok_or(ConstantSolvingError::DestinationTypeNotFound)?, - components: vec![tgt; size as usize], + ty, + components: vec![value_constant; size as usize], }, })) } @@ -94,8 +96,8 @@ impl<'a> ConstantSolver<'a> { vector: src_vector, pattern, } => { - let tgt = self.solve(src_vector)?; - let (ty, src_components) = match self.constants[tgt].inner { + let src_constant = self.solve(src_vector)?; + let (ty, src_components) = match self.constants[src_constant].inner { ConstantInner::Scalar { .. } => (None, &[][..]), ConstantInner::Composite { ty, @@ -114,6 +116,8 @@ impl<'a> ConstantSolver<'a> { _ => (None, &[][..]), }, }; + //TODO: register the new type if needed + let ty = ty.ok_or(ConstantSolvingError::DestinationTypeNotFound)?; let components = pattern .iter() .map(|&sc| src_components[sc as usize]) @@ -122,11 +126,7 @@ impl<'a> ConstantSolver<'a> { Ok(self.constants.fetch_or_append(Constant { name: None, specialization: None, - inner: ConstantInner::Composite { - //TODO: register the new type if needed - ty: ty.ok_or(ConstantSolvingError::DestinationTypeNotFound)?, - components, - }, + inner: ConstantInner::Composite { ty, components }, })) } Expression::Compose { ty, ref components } => { @@ -142,15 +142,15 @@ impl<'a> ConstantSolver<'a> { })) } Expression::Unary { expr, op } => { - let tgt = self.solve(expr)?; + let expr_constant = self.solve(expr)?; - self.unary_op(op, tgt) + self.unary_op(op, expr_constant) } Expression::Binary { left, right, op } => { - let left = self.solve(left)?; - let right = self.solve(right)?; + let left_constant = self.solve(left)?; + let right_constant = self.solve(right)?; - self.binary_op(op, left, right) + self.binary_op(op, left_constant, right_constant) } Expression::Math { .. } => todo!(), Expression::As { @@ -158,10 +158,10 @@ impl<'a> ConstantSolver<'a> { expr, kind, } => { - let tgt = self.solve(expr)?; + let expr_constant = self.solve(expr)?; if convert { - self.cast(tgt, kind) + self.cast(expr_constant, kind) } else { Err(ConstantSolvingError::Bitcast) } diff --git a/src/lib.rs b/src/lib.rs index f6a4b59f0..ce0897ae3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -680,18 +680,19 @@ pub enum ImageQuery { } /// Component selection for a vector swizzle. +#[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum SwizzleComponent { /// - X, + X = 0, /// - Y, + Y = 1, /// - Z, + Z = 2, /// - W, + W = 3, } /// An expression that can be evaluated to obtain a value. From f0cf6a677290ea827e29067e3e30f08b614f1d75 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 22 Apr 2021 14:43:14 -0400 Subject: [PATCH 0734/2212] [spv-in] support OpModuleProcessed (#753) --- src/front/spv/mod.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 4da603895..9011e5f19 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2034,6 +2034,7 @@ impl> Parser { Op::SourceExtension => self.parse_source_extension(inst), Op::Name => self.parse_name(inst), Op::MemberName => self.parse_member_name(inst), + Op::ModuleProcessed => self.parse_module_processed(inst), Op::Decorate => self.parse_decorate(inst), Op::MemberDecorate => self.parse_member_decorate(inst), Op::TypeVoid => self.parse_type_void(inst), @@ -2295,6 +2296,17 @@ impl> Parser { Ok(()) } + fn parse_module_processed(&mut self, inst: Instruction) -> Result<(), Error> { + self.switch(ModuleState::Name, inst.op)?; + inst.expect_at_least(2)?; + let (_info, left) = self.next_string(inst.wc - 1)?; + //Note: string is ignored + if left != 0 { + return Err(Error::InvalidOperand); + } + Ok(()) + } + fn parse_decorate(&mut self, inst: Instruction) -> Result<(), Error> { self.switch(ModuleState::Annotation, inst.op)?; inst.expect_at_least(3)?; From b15a23c61ff72e05ead1ab696922ce1e1825667e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 23 Apr 2021 01:05:10 -0400 Subject: [PATCH 0735/2212] [spv-in] fix integer constants parsing (#756) --- src/front/spv/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 9011e5f19..44cfbb1b0 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2873,7 +2873,7 @@ impl> Parser { crate::ConstantInner::Scalar { width, value: crate::ScalarValue::Sint( - ((u64::from(high) << 32) | u64::from(low)) as i64, + (i64::from(high as i32) << 32) | ((i64::from(low as i32) << 32) >> 32), ), } } From 0917e3740bae19d4f12da24d070d6a474d120f83 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 23 Apr 2021 01:15:04 -0400 Subject: [PATCH 0736/2212] [msl] don't use sample level on 1D textures (#757) --- src/back/msl/writer.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 4bbdf065a..4c71c6317 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -795,11 +795,22 @@ impl Writer { write!(self.out, ", ")?; self.put_expression(dref, context, true)?; } + + let has_levels = match *context.resolve_type(image) { + crate::TypeInner::Image { + dim: crate::ImageDimension::D1, + .. + } => false, + _ => true, + }; match level { crate::SampleLevel::Auto => {} crate::SampleLevel::Zero => { //TODO: do we support Zero on `Sampled` image classes? } + _ if !has_levels => { + log::warn!("1D image can't be sampled with level {:?}", level); + } crate::SampleLevel::Exact(h) => { write!(self.out, ", {}::level(", NAMESPACE)?; self.put_expression(h, context, true)?; @@ -818,6 +829,7 @@ impl Writer { write!(self.out, ")")?; } } + if let Some(constant) = offset { let coco = ConstantContext { handle: constant, From 0725417193a0f6dbb1bfe7fee4981dfc39a438ea Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 23 Apr 2021 01:19:48 -0400 Subject: [PATCH 0737/2212] Allow indexing value pointers (#758) --- src/valid/expression.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 5ed5e3853..863909632 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -146,7 +146,8 @@ impl super::Validator { Ti::Vector { .. } | Ti::Matrix { .. } | Ti::Array { .. } - | Ti::Pointer { .. } => {} + | Ti::Pointer { .. } + | Ti::ValuePointer { size: Some(_), .. } => {} ref other => { log::error!("Indexing of {:?}", other); return Err(ExpressionError::InvalidBaseType(base)); @@ -171,7 +172,10 @@ impl super::Validator { } E::AccessIndex { base, index } => { let limit = match *resolver.resolve(base)? { - Ti::Vector { size, .. } => size as u32, + Ti::Vector { size, .. } + | Ti::ValuePointer { + size: Some(size), .. + } => size as u32, Ti::Matrix { columns, .. } => columns as u32, Ti::Array { size: crate::ArraySize::Constant(handle), From 36bace2b41a776caa12d2e0ecac9991c08204aa6 Mon Sep 17 00:00:00 2001 From: Ashley Date: Fri, 23 Apr 2021 17:53:07 +0200 Subject: [PATCH 0738/2212] Set `is_scoped` to false when evaluating a swizzle subexpression (#761) --- src/back/msl/writer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 4c71c6317..15b5bf55f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -651,7 +651,7 @@ impl Writer { vector, pattern, } => { - self.put_expression(vector, context, is_scoped)?; + self.put_expression(vector, context, false)?; write!(self.out, ".")?; for &sc in pattern[..size as usize].iter() { write!(self.out, "{}", COMPONENTS[sc as usize])?; From 02105db045e0664199e3a6fb4418080ac9fad9b1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 23 Apr 2021 12:31:33 -0400 Subject: [PATCH 0739/2212] [spv-out] image queries (#749) --- src/back/msl/writer.rs | 11 +- src/back/spv/instructions.rs | 8 + src/back/spv/writer.rs | 179 +++++++++++++++-- tests/in/image-copy.wgsl | 16 -- .../{image-copy.param.ron => image.param.ron} | 2 +- tests/in/image.wgsl | 60 ++++++ tests/out/image-copy.msl | 16 -- tests/out/image.msl | 32 ++++ tests/out/image.spvasm | 181 ++++++++++++++++++ tests/snapshots.rs | 3 +- 10 files changed, 455 insertions(+), 53 deletions(-) delete mode 100644 tests/in/image-copy.wgsl rename tests/in/{image-copy.param.ron => image.param.ron} (61%) create mode 100644 tests/in/image.wgsl delete mode 100644 tests/out/image-copy.msl create mode 100644 tests/out/image.msl create mode 100644 tests/out/image.spvasm diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 15b5bf55f..638ec4e8e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -138,7 +138,12 @@ impl<'a> Display for TypeContext<'a> { }; let (texture_str, msaa_str, kind, access) = match class { crate::ImageClass::Sampled { kind, multi } => { - ("texture", if multi { "_ms" } else { "" }, kind, "sample") + let (msaa_str, access) = if multi { + ("_ms", "read") + } else { + ("", "sample") + }; + ("texture", msaa_str, kind, access) } crate::ImageClass::Depth => ("depth", "", crate::ScalarKind::Float, "sample"), crate::ImageClass::Storage(format) => { @@ -510,9 +515,9 @@ impl Writer { write!(self.out, ")")?; } crate::ImageDimension::Cube => { - write!(self.out, "int(")?; + write!(self.out, "int3(")?; self.put_image_query(image, "width", level, context)?; - write!(self.out, ").xxx")?; + write!(self.out, ")")?; } } Ok(()) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index b8855cda1..9bc4f56f9 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -594,6 +594,14 @@ impl super::Instruction { instruction } + pub(super) fn image_query(op: Op, result_type_id: Word, id: Word, image: Word) -> Self { + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(image); + instruction + } + // // Conversion Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 74a9bade6..6bead4dd4 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -21,6 +21,8 @@ pub enum Error { MissingCapabilities(Vec), #[error("unimplemented {0}")] FeatureNotImplemented(&'static str), + #[error("module is not validated properly: {0}")] + Validation(&'static str), } #[derive(Default)] @@ -186,7 +188,7 @@ fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { match dim { crate::ImageDimension::D1 => spirv::Dim::Dim1D, crate::ImageDimension::D2 => spirv::Dim::Dim2D, - crate::ImageDimension::D3 => spirv::Dim::Dim2D, + crate::ImageDimension::D3 => spirv::Dim::Dim3D, crate::ImageDimension::Cube => spirv::Dim::DimCube, } } @@ -1261,11 +1263,14 @@ impl Writer { crate::VectorSize::Bi => crate::VectorSize::Tri, crate::VectorSize::Tri => crate::VectorSize::Quad, crate::VectorSize::Quad => { - unimplemented!("Unable to extend the vec4 coordinate") + return Err(Error::Validation("extending vec4 coordinate")); } } } - ref other => unimplemented!("wrong coordinate type {:?}", other), + ref other => { + log::error!("wrong coordinate type {:?}", other); + return Err(Error::Validation("coordinate type")); + } }; let array_index_f32_id = self.id_gen.next(); @@ -1894,12 +1899,16 @@ impl Writer { instruction.add_operand(index_id); } - if instruction.type_id != Some(result_type_id) { + let inst_type_id = instruction.type_id; + block.body.push(instruction); + if inst_type_id != Some(result_type_id) { let sub_id = self.id_gen.next(); - let index_id = self.get_index_constant(0, &ir_module.types)?; - let sub_instruction = - Instruction::vector_extract_dynamic(result_type_id, sub_id, id, index_id); - block.body.push(sub_instruction); + block.body.push(Instruction::composite_extract( + result_type_id, + sub_id, + id, + &[0], + )); sub_id } else { id @@ -2062,10 +2071,12 @@ impl Writer { if needs_sub_access { let sub_id = self.id_gen.next(); - let index_id = self.get_index_constant(0, &ir_module.types)?; - let sub_instruction = - Instruction::vector_extract_dynamic(result_type_id, sub_id, id, index_id); - block.body.push(sub_instruction); + block.body.push(Instruction::composite_extract( + result_type_id, + sub_id, + id, + &[0], + )); sub_id } else { id @@ -2098,9 +2109,147 @@ impl Writer { }); id } - crate::Expression::ImageQuery { .. } - | crate::Expression::Relational { .. } - | crate::Expression::ArrayLength(_) => { + crate::Expression::ImageQuery { image, query } => { + use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq}; + + let image_id = self.get_expression_global(ir_function, image); + let image_type = fun_info[image].ty.handle().unwrap(); + let (dim, arrayed, class) = match ir_module.types[image_type].inner { + crate::TypeInner::Image { + dim, + arrayed, + class, + } => (dim, arrayed, class), + _ => { + return Err(Error::Validation("image type")); + } + }; + + match query { + Iq::Size { level } => { + let dim_coords = match dim { + Id::D1 => 1, + Id::D2 | Id::Cube => 2, + Id::D3 => 3, + }; + let extended_size_type_id = { + let array_coords = if arrayed { 1 } else { 0 }; + let vector_size = match dim_coords + array_coords { + 2 => Some(crate::VectorSize::Bi), + 3 => Some(crate::VectorSize::Tri), + 4 => Some(crate::VectorSize::Quad), + _ => None, + }; + self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Value { + vector_size, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + }), + )? + }; + + let (query_op, level_id) = match class { + Ic::Storage(_) => (spirv::Op::ImageQuerySize, None), + _ => { + let level_id = match level { + Some(expr) => self.cached[expr], + None => self.get_index_constant(0, &ir_module.types)?, + }; + (spirv::Op::ImageQuerySizeLod, Some(level_id)) + } + }; + // The ID of the vector returned by SPIR-V, which contains the dimensions + // as well as the layer count. + let id_extended = self.id_gen.next(); + let mut inst = Instruction::image_query( + query_op, + extended_size_type_id, + id_extended, + image_id, + ); + if let Some(expr_id) = level_id { + inst.add_operand(expr_id); + } + block.body.push(inst); + + if result_type_id != extended_size_type_id { + let id = self.id_gen.next(); + let components = match dim { + // always pick the first component, and duplicate it for all 3 dimensions + Id::Cube => &[0u32, 0, 0][..], + _ => &[0u32, 1, 2, 3][..dim_coords], + }; + block.body.push(Instruction::vector_shuffle( + result_type_id, + id, + id_extended, + id_extended, + components, + )); + id + } else { + id_extended + } + } + Iq::NumLevels => { + let id = self.id_gen.next(); + block.body.push(Instruction::image_query( + spirv::Op::ImageQueryLevels, + result_type_id, + id, + image_id, + )); + id + } + Iq::NumLayers => { + let vec_size = match dim { + Id::D1 => crate::VectorSize::Bi, + Id::D2 | Id::Cube => crate::VectorSize::Tri, + Id::D3 => crate::VectorSize::Quad, + }; + let extended_size_type_id = self.get_type_id( + &ir_module.types, + LookupType::Local(LocalType::Value { + vector_size: Some(vec_size), + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + }), + )?; + let id_extended = self.id_gen.next(); + let mut inst = Instruction::image_query( + spirv::Op::ImageQuerySizeLod, + extended_size_type_id, + id_extended, + image_id, + ); + inst.add_operand(self.get_index_constant(0, &ir_module.types)?); + block.body.push(inst); + let id = self.id_gen.next(); + block.body.push(Instruction::composite_extract( + result_type_id, + id, + id_extended, + &[vec_size as u32 - 1], + )); + id + } + Iq::NumSamples => { + let id = self.id_gen.next(); + block.body.push(Instruction::image_query( + spirv::Op::ImageQuerySamples, + result_type_id, + id, + image_id, + )); + id + } + } + } + crate::Expression::Relational { .. } | crate::Expression::ArrayLength(_) => { log::error!("unimplemented {:?}", ir_function.expressions[expr_handle]); return Err(Error::FeatureNotImplemented("expression")); } diff --git a/tests/in/image-copy.wgsl b/tests/in/image-copy.wgsl deleted file mode 100644 index 157d08146..000000000 --- a/tests/in/image-copy.wgsl +++ /dev/null @@ -1,16 +0,0 @@ -[[group(0), binding(1)]] -var image_src: [[access(read)]] texture_storage_2d; -[[group(0), binding(2)]] -var image_dst: [[access(write)]] texture_storage_1d; - -[[stage(compute), workgroup_size(16)]] -fn main( - [[builtin(local_invocation_id)]] local_id: vec3, - //TODO: https://github.com/gpuweb/gpuweb/issues/1590 - //[[builtin(workgroup_size)]] wg_size: vec3 -) { - let dim = textureDimensions(image_src); - let itc = dim * vec2(local_id.xy) % vec2(10, 20); - let value = textureLoad(image_src, itc); - textureStore(image_dst, itc.x, value); -} diff --git a/tests/in/image-copy.param.ron b/tests/in/image.param.ron similarity index 61% rename from tests/in/image-copy.param.ron rename to tests/in/image.param.ron index 52f49f360..54df97117 100644 --- a/tests/in/image-copy.param.ron +++ b/tests/in/image.param.ron @@ -1,6 +1,6 @@ ( spv_version: (1, 1), - spv_capabilities: [ Shader, Image1D, Sampled1D ], + spv_capabilities: [ Shader, ImageQuery, Image1D, Sampled1D ], spv_debug: true, spv_adjust_coordinate_space: false, msl_custom: false, diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl new file mode 100644 index 000000000..440cd351d --- /dev/null +++ b/tests/in/image.wgsl @@ -0,0 +1,60 @@ +[[group(0), binding(1)]] +var image_src: [[access(read)]] texture_storage_2d; +[[group(0), binding(2)]] +var image_dst: [[access(write)]] texture_storage_1d; + +[[stage(compute), workgroup_size(16)]] +fn main( + [[builtin(local_invocation_id)]] local_id: vec3, + //TODO: https://github.com/gpuweb/gpuweb/issues/1590 + //[[builtin(workgroup_size)]] wg_size: vec3 +) { + let dim = textureDimensions(image_src); + let itc = dim * vec2(local_id.xy) % vec2(10, 20); + let value = textureLoad(image_src, itc); + textureStore(image_dst, itc.x, value); +} + +[[group(0), binding(0)]] +var image_1d: texture_1d; +[[group(0), binding(1)]] +var image_2d: texture_2d; +[[group(0), binding(2)]] +var image_2d_array: texture_2d_array; +[[group(0), binding(3)]] +var image_cube: texture_cube; +[[group(0), binding(4)]] +var image_cube_array: texture_cube_array; +[[group(0), binding(5)]] +var image_3d: texture_3d; +[[group(0), binding(6)]] +var image_aa: texture_multisampled_2d; + +[[stage(vertex)]] +fn queries() -> [[builtin(position)]] vec4 { + let dim_1d = textureDimensions(image_1d); + let dim_2d = textureDimensions(image_2d); + let num_levels_2d = textureNumLevels(image_2d); + let dim_2d_lod = textureDimensions(image_2d, 1); + let dim_2d_array = textureDimensions(image_2d_array); + let num_levels_2d_array = textureNumLevels(image_2d_array); + let dim_2d_array_lod = textureDimensions(image_2d_array, 1); + let num_layers_2d = textureNumLayers(image_2d_array); + let dim_cube = textureDimensions(image_cube); + let num_levels_cube = textureNumLevels(image_cube); + let dim_cube_lod = textureDimensions(image_cube, 1); + let dim_cube_array = textureDimensions(image_cube_array); + let num_levels_cube_array = textureNumLevels(image_cube_array); + let dim_cube_array_lod = textureDimensions(image_cube_array, 1); + let num_layers_cube = textureNumLayers(image_cube_array); + let dim_3d = textureDimensions(image_3d); + let num_levels_3d = textureNumLevels(image_3d); + let dim_3d_lod = textureDimensions(image_3d, 1); + let num_samples_aa = textureNumSamples(image_aa); + + let sum = dim_1d + dim_2d.y + dim_2d_lod.y + dim_2d_array.y + dim_2d_array_lod.y + + num_layers_2d + dim_cube.y + dim_cube_lod.y + dim_cube_array.y + dim_cube_array_lod.y + + num_layers_cube + dim_3d.z + dim_3d_lod.z + num_samples_aa + + num_levels_2d + num_levels_2d_array + num_levels_3d + num_levels_cube + num_levels_cube_array; + return vec4(f32(sum)); +} diff --git a/tests/out/image-copy.msl b/tests/out/image-copy.msl deleted file mode 100644 index 2db875cfc..000000000 --- a/tests/out/image-copy.msl +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include - - -struct main1Input { -}; -kernel void main1( - metal::uint3 local_id [[thread_position_in_threadgroup]] -, metal::texture2d image_src [[user(fake0)]] -, metal::texture1d image_dst [[user(fake0)]] -) { - metal::int2 _e10 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(local_id.xy)) % metal::int2(10, 20); - metal::uint4 _e11 = image_src.read(metal::uint2(_e10)); - image_dst.write(_e11, metal::uint(_e10.x)); - return; -} diff --git a/tests/out/image.msl b/tests/out/image.msl new file mode 100644 index 000000000..87ccd581a --- /dev/null +++ b/tests/out/image.msl @@ -0,0 +1,32 @@ +#include +#include + + +struct main1Input { +}; +kernel void main1( + metal::uint3 local_id [[thread_position_in_threadgroup]] +, metal::texture2d image_src [[user(fake0)]] +, metal::texture1d image_dst [[user(fake0)]] +) { + metal::int2 _e10 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(local_id.xy)) % metal::int2(10, 20); + metal::uint4 _e11 = image_src.read(metal::uint2(_e10)); + image_dst.write(_e11, metal::uint(_e10.x)); + return; +} + + +struct queriesOutput { + metal::float4 member1 [[position]]; +}; +vertex queriesOutput queries( + metal::texture1d image_1d [[user(fake0)]] +, metal::texture2d image_2d [[user(fake0)]] +, metal::texture2d_array image_2d_array [[user(fake0)]] +, metal::texturecube image_cube [[user(fake0)]] +, metal::texturecube_array image_cube_array [[user(fake0)]] +, metal::texture3d image_3d [[user(fake0)]] +, metal::texture2d_ms image_aa [[user(fake0)]] +) { + return queriesOutput { float4(static_cast((((((((((((((((((int(image_1d.get_width()) + int2(image_2d.get_width(), image_2d.get_height()).y) + int2(image_2d.get_width(1), image_2d.get_height(1)).y) + int2(image_2d_array.get_width(), image_2d_array.get_height()).y) + int2(image_2d_array.get_width(1), image_2d_array.get_height(1)).y) + int(image_2d_array.get_array_size())) + int3(image_cube.get_width()).y) + int3(image_cube.get_width(1)).y) + int3(image_cube_array.get_width()).y) + int3(image_cube_array.get_width(1)).y) + int(image_cube_array.get_array_size())) + int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()).z) + int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)).z) + int(image_aa.get_num_samples())) + int(image_2d.get_num_mip_levels())) + int(image_2d_array.get_num_mip_levels())) + int(image_3d.get_num_mip_levels())) + int(image_cube.get_num_mip_levels())) + int(image_cube_array.get_num_mip_levels()))) }; +} diff --git a/tests/out/image.spvasm b/tests/out/image.spvasm new file mode 100644 index 000000000..b5e39cb9a --- /dev/null +++ b/tests/out/image.spvasm @@ -0,0 +1,181 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 127 +OpCapability ImageQuery +OpCapability Image1D +OpCapability Shader +OpCapability Sampled1D +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %43 "main" %40 +OpEntryPoint Vertex %61 "queries" %59 +OpExecutionMode %43 LocalSize 16 1 1 +OpSource GLSL 450 +OpName %21 "image_src" +OpName %23 "image_dst" +OpName %25 "image_1d" +OpName %27 "image_2d" +OpName %29 "image_2d_array" +OpName %31 "image_cube" +OpName %33 "image_cube_array" +OpName %35 "image_3d" +OpName %37 "image_aa" +OpName %40 "local_id" +OpName %43 "main" +OpName %61 "queries" +OpDecorate %21 NonWritable +OpDecorate %21 DescriptorSet 0 +OpDecorate %21 Binding 1 +OpDecorate %23 NonReadable +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 2 +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 0 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 1 +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 2 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 3 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 4 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 5 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 6 +OpDecorate %40 BuiltIn LocalInvocationId +OpDecorate %59 BuiltIn Position +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 10 +%5 = OpConstant %4 20 +%6 = OpConstant %4 1 +%8 = OpTypeInt 32 0 +%7 = OpTypeImage %8 2D 0 0 0 2 Rgba8ui +%9 = OpTypeImage %8 1D 0 0 0 2 R32ui +%10 = OpTypeVector %8 3 +%11 = OpTypeVector %4 2 +%13 = OpTypeFloat 32 +%12 = OpTypeImage %13 1D 0 0 0 1 Unknown +%14 = OpTypeImage %13 2D 0 0 0 1 Unknown +%15 = OpTypeImage %13 2D 0 1 0 1 Unknown +%16 = OpTypeImage %13 Cube 0 0 0 1 Unknown +%17 = OpTypeImage %13 Cube 0 1 0 1 Unknown +%18 = OpTypeImage %13 3D 0 0 0 1 Unknown +%19 = OpTypeImage %13 2D 0 0 1 1 Unknown +%20 = OpTypeVector %13 4 +%22 = OpTypePointer UniformConstant %7 +%21 = OpVariable %22 UniformConstant +%24 = OpTypePointer UniformConstant %9 +%23 = OpVariable %24 UniformConstant +%26 = OpTypePointer UniformConstant %12 +%25 = OpVariable %26 UniformConstant +%28 = OpTypePointer UniformConstant %14 +%27 = OpVariable %28 UniformConstant +%30 = OpTypePointer UniformConstant %15 +%29 = OpVariable %30 UniformConstant +%32 = OpTypePointer UniformConstant %16 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %17 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %18 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %19 +%37 = OpVariable %38 UniformConstant +%41 = OpTypePointer Input %10 +%40 = OpVariable %41 Input +%44 = OpTypeFunction %2 +%49 = OpTypeVector %8 2 +%55 = OpTypeVector %8 4 +%60 = OpTypePointer Output %20 +%59 = OpVariable %60 Output +%70 = OpConstant %4 0 +%75 = OpTypeVector %4 3 +%43 = OpFunction %2 None %44 +%39 = OpLabel +%42 = OpLoad %10 %40 +%45 = OpLoad %7 %21 +%46 = OpLoad %9 %23 +OpBranch %47 +%47 = OpLabel +%48 = OpImageQuerySize %11 %45 +%50 = OpVectorShuffle %49 %42 %42 0 1 +%51 = OpBitcast %11 %50 +%52 = OpIMul %11 %48 %51 +%53 = OpCompositeConstruct %11 %3 %5 +%54 = OpSMod %11 %52 %53 +%56 = OpImageRead %55 %45 %54 +%57 = OpCompositeExtract %4 %54 0 +OpImageWrite %46 %57 %56 +OpReturn +OpFunctionEnd +%61 = OpFunction %2 None %44 +%58 = OpLabel +%62 = OpLoad %12 %25 +%63 = OpLoad %14 %27 +%64 = OpLoad %15 %29 +%65 = OpLoad %16 %31 +%66 = OpLoad %17 %33 +%67 = OpLoad %18 %35 +%68 = OpLoad %19 %37 +OpBranch %69 +%69 = OpLabel +%71 = OpImageQuerySizeLod %4 %62 %70 +%72 = OpImageQuerySizeLod %11 %63 %70 +%73 = OpImageQueryLevels %4 %63 +%74 = OpImageQuerySizeLod %11 %63 %6 +%76 = OpImageQuerySizeLod %75 %64 %70 +%77 = OpVectorShuffle %11 %76 %76 0 1 +%78 = OpImageQueryLevels %4 %64 +%79 = OpImageQuerySizeLod %75 %64 %6 +%80 = OpVectorShuffle %11 %79 %79 0 1 +%81 = OpImageQuerySizeLod %75 %64 %70 +%82 = OpCompositeExtract %4 %81 2 +%83 = OpImageQuerySizeLod %11 %65 %70 +%84 = OpVectorShuffle %75 %83 %83 0 0 0 +%85 = OpImageQueryLevels %4 %65 +%86 = OpImageQuerySizeLod %11 %65 %6 +%87 = OpVectorShuffle %75 %86 %86 0 0 0 +%88 = OpImageQuerySizeLod %75 %66 %70 +%89 = OpImageQueryLevels %4 %66 +%90 = OpImageQuerySizeLod %75 %66 %6 +%91 = OpImageQuerySizeLod %75 %66 %70 +%92 = OpCompositeExtract %4 %91 2 +%93 = OpImageQuerySizeLod %75 %67 %70 +%94 = OpImageQueryLevels %4 %67 +%95 = OpImageQuerySizeLod %75 %67 %6 +%96 = OpImageQuerySamples %4 %68 +%97 = OpCompositeExtract %4 %72 1 +%98 = OpIAdd %4 %71 %97 +%99 = OpCompositeExtract %4 %74 1 +%100 = OpIAdd %4 %98 %99 +%101 = OpCompositeExtract %4 %77 1 +%102 = OpIAdd %4 %100 %101 +%103 = OpCompositeExtract %4 %80 1 +%104 = OpIAdd %4 %102 %103 +%105 = OpIAdd %4 %104 %82 +%106 = OpCompositeExtract %4 %84 1 +%107 = OpIAdd %4 %105 %106 +%108 = OpCompositeExtract %4 %87 1 +%109 = OpIAdd %4 %107 %108 +%110 = OpCompositeExtract %4 %88 1 +%111 = OpIAdd %4 %109 %110 +%112 = OpCompositeExtract %4 %90 1 +%113 = OpIAdd %4 %111 %112 +%114 = OpIAdd %4 %113 %92 +%115 = OpCompositeExtract %4 %93 2 +%116 = OpIAdd %4 %114 %115 +%117 = OpCompositeExtract %4 %95 2 +%118 = OpIAdd %4 %116 %117 +%119 = OpIAdd %4 %118 %96 +%120 = OpIAdd %4 %119 %73 +%121 = OpIAdd %4 %120 %78 +%122 = OpIAdd %4 %121 %94 +%123 = OpIAdd %4 %122 %85 +%124 = OpIAdd %4 %123 %89 +%125 = OpConvertSToF %13 %124 +%126 = OpCompositeConstruct %20 %125 %125 %125 %125 +OpStore %59 %126 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index bbb92b3b4..2655e7bdd 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -235,8 +235,7 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS, ), ("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL), - //SPIR-V is blocked by https://github.com/gfx-rs/naga/issues/646 - ("image-copy", Targets::METAL), + ("image", Targets::SPIRV | Targets::METAL), ("texture-array", Targets::SPIRV | Targets::METAL), ("operators", Targets::SPIRV | Targets::METAL | Targets::GLSL), ( From 3accf4dc15eff11d64bf2b2ce46f3b89a2e58971 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 20 Apr 2021 13:02:13 +0300 Subject: [PATCH 0740/2212] Improve wgsl-out --- Makefile | 2 +- bin/convert.rs | 2 +- src/back/wgsl/mod.rs | 19 +- src/back/wgsl/writer.rs | 720 +++++++++++++++++++++++++++++++++++++--- tests/out/empty.wgsl | 6 +- tests/snapshots.rs | 6 +- 6 files changed, 695 insertions(+), 60 deletions(-) diff --git a/Makefile b/Makefile index ea631e499..10f9b6f92 100644 --- a/Makefile +++ b/Makefile @@ -61,5 +61,5 @@ validate-dot: $(SNAPSHOTS_OUT)/*.dot validate-wgsl: $(SNAPSHOTS_OUT)/*.wgsl @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ - cargo run --bin convert --features wgsl-in $${file} >/dev/null; \ + cargo run --bin convert --features wgsl-in $${file}; \ done diff --git a/bin/convert.rs b/bin/convert.rs index 126c4d7d4..0a5025cc1 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -269,7 +269,7 @@ fn main() { "wgsl" => { use naga::back::wgsl; - let wgsl = wgsl::write_string(&module).unwrap_pretty(); + let wgsl = wgsl::write_string(&module, info.as_ref().unwrap()).unwrap_pretty(); fs::write(output_path, wgsl).unwrap(); } other => { diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index e785b57a1..f259355d8 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -1,8 +1,6 @@ mod keywords; mod writer; -use std::io::Error as IoError; -use std::string::FromUtf8Error; use thiserror::Error; pub use writer::Writer; @@ -10,14 +8,17 @@ pub use writer::Writer; #[derive(Error, Debug)] pub enum Error { #[error(transparent)] - IoError(#[from] IoError), - #[error(transparent)] - Utf8(#[from] FromUtf8Error), + FmtError(#[from] std::fmt::Error), + #[error("{0}")] + Custom(String), } -pub fn write_string(module: &crate::Module) -> Result { - let mut w = Writer::new(Vec::new()); - w.write(module)?; - let output = String::from_utf8(w.finish())?; +pub fn write_string( + module: &crate::Module, + info: &crate::valid::ModuleInfo, +) -> Result { + let mut w = Writer::new(String::new()); + w.write(module, info)?; + let output = w.finish(); Ok(output) } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 206e96d11..ad3e37c45 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1,24 +1,58 @@ +// TODO: temp +#![allow(dead_code)] use super::Error; -use crate::FastHashMap; use crate::{ - back::wgsl::keywords::RESERVED, Function, Module, ShaderStage, StructLevel, TypeInner, + back::wgsl::keywords::RESERVED, + proc::{EntryPointIndex, TypeResolution}, + valid::{FunctionInfo, ModuleInfo}, + Arena, BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, + ImageClass, ImageDimension, Module, ScalarKind, ShaderStage, Statement, StorageFormat, + StructLevel, Type, TypeInner, }; use crate::{ proc::{NameKey, Namer}, StructMember, }; -use std::io::Write; +use crate::{FastHashMap, VectorSize}; +use std::fmt::Write; -const _INDENT: &str = " "; +const INDENT: &str = " "; /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; -enum Decoration { - VertexStage, - FragmentStage, - ComputeStage { workgroup_size: [u32; 3] }, +/// WGSL attribute +/// https://gpuweb.github.io/gpuweb/wgsl/#attributes +enum Attribute { + Binding(u32), Block, + BuiltIn(crate::BuiltIn), + Group(u32), + Location(u32), + Stage(ShaderStage), + WorkGroupSize([u32; 3]), +} + +/// Stores the current function type (either a regular function or an entry point) +/// +/// Also stores data needed to identify it (handle for a regular function or index for an entry point) +// TODO: copy-paste from glsl-out +enum FunctionType { + /// A regular function and it's handle + Function(Handle), + /// A entry point and it's index + EntryPoint(EntryPointIndex), +} + +/// Helper structure that stores data needed when writing the function +// TODO: copy-paste from glsl-out +struct FunctionCtx<'a> { + /// The current function type being written + ty: FunctionType, + /// Analysis about the function + info: &'a FunctionInfo, + /// The expression arena of the current function being written + expressions: &'a Arena, } pub struct Writer { @@ -36,10 +70,24 @@ impl Writer { } } - pub fn write(&mut self, module: &Module) -> BackendResult { + pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { self.names.clear(); self.namer.reset(module, RESERVED, &mut self.names); + // Write all constants + for (_, constant) in module.constants.iter() { + if constant.name.is_some() { + self.write_constant(&constant, true)?; + } + } + + // Write all globals + for (_, global) in module.global_variables.iter() { + if global.name.is_some() { + self.write_global(&module, &global)?; + } + } + // Write all structs for (handle, ty) in module.types.iter() { if let TypeInner::Struct { @@ -48,24 +96,31 @@ impl Writer { { let name = &self.names[&NameKey::Type(handle)].clone(); let block = level == StructLevel::Root; - self.write_struct(name, block, members)?; + self.write_struct(module, name, block, members)?; writeln!(self.out)?; } } - for (_, ep) in module.entry_points.iter().enumerate() { - let decoration = match ep.stage { - ShaderStage::Vertex => Decoration::VertexStage, - ShaderStage::Fragment => Decoration::FragmentStage, - ShaderStage::Compute => Decoration::ComputeStage { - workgroup_size: ep.workgroup_size, - }, + for (index, ep) in module.entry_points.iter().enumerate() { + let attributes = match ep.stage { + ShaderStage::Vertex | ShaderStage::Fragment => vec![Attribute::Stage(ep.stage)], + ShaderStage::Compute => vec![ + Attribute::Stage(ShaderStage::Compute), + Attribute::WorkGroupSize(ep.workgroup_size), + ], }; - self.write_decoration(decoration)?; - // Add a newline after decoration + self.write_attributes(&attributes)?; + // Add a newline after attribute + writeln!(self.out)?; + + let func_ctx = FunctionCtx { + ty: FunctionType::EntryPoint(index as u16), + info: &info.get_entry_point(index), + expressions: &ep.function.expressions, + }; + self.write_function(&module, &ep.function, &func_ctx)?; writeln!(self.out)?; - self.write_function(&ep.function)?; } // Add a newline at the end of file @@ -79,38 +134,108 @@ impl Writer { /// /// # Notes /// Ends in a newline - fn write_function(&mut self, func: &Function) -> BackendResult { - write!(self.out, "fn {}(", func.name.as_ref().unwrap())?; // TODO: unnamed function? - write!(self.out, ")")?; + fn write_function( + &mut self, + module: &Module, + func: &Function, + func_ctx: &FunctionCtx<'_>, + ) -> BackendResult { + // TODO: unnamed function? + write!(self.out, "fn {}(", func.name.as_ref().unwrap())?; + + // Write function arguments + // TODO: another function type + if let FunctionType::EntryPoint(ep_index) = func_ctx.ty { + for (index, arg) in func.arguments.iter().enumerate() { + // Write argument attribute if a binding is present + if let Some(ref binding) = arg.binding { + self.write_attributes(&[map_binding_to_attribute(binding)])?; + write!(self.out, " ")?; + } + // Write argument name + write!( + self.out, + "{}: ", + &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)] + )?; + // Write argument type + self.write_type(module, arg.ty)?; + if index < func.arguments.len() - 1 { + // Add a separator between args + write!(self.out, ", ")?; + } + } + write!(self.out, ")")?; + } + + // Write function return type + if let Some(ref result) = func.result { + if let Some(ref binding) = result.binding { + write!(self.out, " -> ")?; + self.write_attributes(&[map_binding_to_attribute(binding)])?; + write!(self.out, " ")?; + self.write_type(module, result.ty)?; + // Extra space only for readability + write!(self.out, " ")?; + } else { + let struct_name = &self.names[&NameKey::Type(result.ty)].clone(); + write!(self.out, " -> {} ", struct_name)?; + } + } write!(self.out, "{{")?; - write!(self.out, "}}")?; + writeln!(self.out)?; + + // Write the function body (statement list) + for sta in func.body.iter() { + // The indentation should always be 1 when writing the function body + self.write_stmt(&module, sta, &func_ctx, 1)?; + } + + writeln!(self.out, "}}")?; Ok(()) } - /// Helper method to write a decoration + /// Helper method to write a attribute /// /// # Notes /// Adds no leading or trailing whitespace - fn write_decoration(&mut self, decoration: Decoration) -> BackendResult { + fn write_attributes(&mut self, attributes: &[Attribute]) -> BackendResult { write!(self.out, "[[")?; - match decoration { - Decoration::VertexStage => write!(self.out, "stage(vertex)")?, - Decoration::FragmentStage => write!(self.out, "stage(fragment)")?, - Decoration::ComputeStage { workgroup_size } => { - write!( - self.out, - "{}", - format!( - "stage(compute), workgroup_size({}, {}, {})", - workgroup_size[0], workgroup_size[1], workgroup_size[2] - ) - )?; + for (index, attribute) in attributes.iter().enumerate() { + match *attribute { + Attribute::Block => { + write!(self.out, "block")?; + } + Attribute::Location(id) => write!(self.out, "location({})", id)?, + Attribute::BuiltIn(builtin_attrib) => { + let builtin_str = builtin_str(builtin_attrib); + if let Some(builtin) = builtin_str { + write!(self.out, "builtin({})", builtin)? + } else { + log::warn!("Unsupported builtin attribute: {:?}", builtin_attrib); + } + } + Attribute::Stage(shader_stage) => match shader_stage { + ShaderStage::Vertex => write!(self.out, "stage(vertex)")?, + ShaderStage::Fragment => write!(self.out, "stage(fragment)")?, + ShaderStage::Compute => write!(self.out, "stage(compute)")?, + }, + Attribute::WorkGroupSize(size) => { + write!( + self.out, + "{}", + format!("workgroup_size({}, {}, {})", size[0], size[1], size[2]) + )?; + } + Attribute::Binding(id) => write!(self.out, "binding({})", id)?, + Attribute::Group(id) => write!(self.out, "group({})", id)?, + }; + if index < attributes.len() - 1 { + // Add a separator between args + write!(self.out, ", ")?; } - Decoration::Block => { - write!(self.out, "block")?; - } - }; + } write!(self.out, "]]")?; Ok(()) @@ -122,23 +247,528 @@ impl Writer { /// Ends in a newline fn write_struct( &mut self, + module: &Module, name: &str, block: bool, - _members: &[StructMember], + members: &[StructMember], ) -> BackendResult { if block { - self.write_decoration(Decoration::Block)?; + self.write_attributes(&[Attribute::Block])?; writeln!(self.out)?; } write!(self.out, "struct {} {{", name)?; - write!(self.out, "}}")?; + writeln!(self.out)?; + for (_, member) in members.iter().enumerate() { + // The indentation is only for readability + write!(self.out, "{}", INDENT)?; + if let Some(ref binding) = member.binding { + self.write_attributes(&[map_binding_to_attribute(binding)])?; + write!(self.out, " ")?; + } + // Write struct member name and type + write!(self.out, "{}: ", member.name.as_ref().unwrap())?; + self.write_type(module, member.ty)?; + write!(self.out, ";")?; + writeln!(self.out)?; + } + write!(self.out, "}};")?; writeln!(self.out)?; Ok(()) } + /// Helper method used to write non image/sampler types + /// + /// # Notes + /// Adds no trailing or leading whitespace + fn write_type(&mut self, module: &Module, ty: Handle) -> BackendResult { + let inner = &module.types[ty].inner; + match *inner { + TypeInner::Struct { .. } => { + // Get the struct name + let name = &self.names[&NameKey::Type(ty)]; + write!(self.out, "{}", name)?; + return Ok(()); + } + ref other => self.write_value_type(module, other)?, + } + + Ok(()) + } + + /// Helper method used to write value types + /// + /// # Notes + /// Adds no trailing or leading whitespace + fn write_value_type(&mut self, _module: &Module, inner: &TypeInner) -> BackendResult { + match *inner { + TypeInner::Vector { size, kind, .. } => write!( + self.out, + "{}", + format!("vec{}<{}>", vector_size_str(size), scalar_kind_str(kind),) + )?, + TypeInner::Sampler { comparison: false } => { + write!(self.out, "sampler")?; + } + TypeInner::Sampler { comparison: true } => { + write!(self.out, "sampler_comparison")?; + } + TypeInner::Image { + dim, + arrayed, + class, + } => { + // More about texture types: https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type + let dim_str = image_dimension_str(dim); + let arrayed_str = if arrayed { "_array" } else { "" }; + let (class_str, multisampled_str, scalar_str) = match class { + ImageClass::Sampled { kind, multi } => ( + "", + if multi { "multisampled" } else { "" }, + format!("<{}>", scalar_kind_str(kind)), + ), + ImageClass::Depth => ("depth", "", String::from("")), + ImageClass::Storage(storage_format) => ( + "storage", + "", + format!("<{}>", storage_format_str(storage_format)), + ), + }; + let ty_str = format!( + "texture_{}{}{}{}{}", + class_str, multisampled_str, dim_str, arrayed_str, scalar_str + ); + write!(self.out, "{}", ty_str)?; + } + _ => todo!("write_value_type {:?}", inner), + } + + Ok(()) + } + /// Helper method used to write statements + /// + /// # Notes + /// Always adds a newline + fn write_stmt( + &mut self, + module: &Module, + stmt: &Statement, + func_ctx: &FunctionCtx<'_>, + indent: usize, + ) -> BackendResult { + match *stmt { + Statement::Emit(ref range) => { + for handle in range.clone() { + let min_ref_count = func_ctx.expressions[handle].bake_ref_count(); + if min_ref_count <= func_ctx.info[handle].ref_count { + match func_ctx.info[handle].ty { + TypeResolution::Handle(ty_handle) => { + write!(self.out, "{}", INDENT.repeat(indent))?; + self.write_type(module, ty_handle)? + } + TypeResolution::Value(ref _inner) => { + //TODO: + //write!(self.out, "{}", INDENT.repeat(indent))?; + //self.write_value_type(module, inner)? + } + } + } + } + } + // TODO: copy-paste from glsl-out + Statement::If { + condition, + ref accept, + ref reject, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "if (")?; + self.write_expr(module, condition, func_ctx)?; + writeln!(self.out, ") {{")?; + + for sta in accept { + // Increase indentation to help with readability + self.write_stmt(module, sta, func_ctx, indent + 1)?; + } + + // If there are no statements in the reject block we skip writing it + // This is only for readability + if !reject.is_empty() { + writeln!(self.out, "{}}} else {{", INDENT.repeat(indent))?; + + for sta in reject { + // Increase indentation to help with readability + self.write_stmt(module, sta, func_ctx, indent + 1)?; + } + } + + writeln!(self.out, "{}}}", INDENT.repeat(indent))? + } + Statement::Return { value } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + if let Some(return_value) = value { + write!(self.out, "return ")?; + self.write_expr(module, return_value, &func_ctx)?; + writeln!(self.out, ";")?; + } else { + writeln!(self.out, "return;")?; + } + } + // TODO: copy-paste from glsl-out + Statement::Kill => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "discard;")? + } + _ => todo!("write_stmt {:?}", stmt), + } + + Ok(()) + } + + /// Helper method to write expressions + /// + /// # Notes + /// Doesn't add any newlines or leading/trailing spaces + fn write_expr( + &mut self, + module: &Module, + expr: Handle, + func_ctx: &FunctionCtx<'_>, + ) -> BackendResult { + let expression = &func_ctx.expressions[expr]; + match *expression { + Expression::Constant(constant) => { + self.write_constant(&module.constants[constant], false)? + } + Expression::Compose { ty, ref components } => { + self.write_type(&module, ty)?; + write!(self.out, "(")?; + self.write_slice(components, |this, _, arg| { + this.write_expr(&module, *arg, func_ctx) + })?; + write!(self.out, ")")? + } + Expression::FunctionArgument(pos) => { + let name_key = match func_ctx.ty { + FunctionType::Function(handle) => NameKey::FunctionArgument(handle, pos), + FunctionType::EntryPoint(ep_index) => { + NameKey::EntryPointArgument(ep_index, pos) + } + }; + let name = &self.names[&name_key]; + write!(self.out, "{}", name)?; + } + Expression::Binary { op, left, right } => { + self.write_expr(module, left, func_ctx)?; + + // TODO: glsl-out copy-paste + write!( + self.out, + " {} ", + match op { + BinaryOperator::Add => "+", + BinaryOperator::Subtract => "-", + BinaryOperator::Multiply => "*", + BinaryOperator::Divide => "/", + BinaryOperator::Modulo => "%", + BinaryOperator::Equal => "==", + BinaryOperator::NotEqual => "!=", + BinaryOperator::Less => "<", + BinaryOperator::LessEqual => "<=", + BinaryOperator::Greater => ">", + BinaryOperator::GreaterEqual => ">=", + BinaryOperator::And => "&", + BinaryOperator::ExclusiveOr => "^", + BinaryOperator::InclusiveOr => "|", + BinaryOperator::LogicalAnd => "&&", + BinaryOperator::LogicalOr => "||", + BinaryOperator::ShiftLeft => "<<", + BinaryOperator::ShiftRight => ">>", + } + )?; + + self.write_expr(module, right, func_ctx)?; + } + // TODO: copy-paste from glsl-out + Expression::Access { base, index } => { + self.write_expr(module, base, func_ctx)?; + write!(self.out, "[")?; + self.write_expr(module, index, func_ctx)?; + write!(self.out, "]")? + } + // TODO: copy-paste from glsl-out + Expression::AccessIndex { base, index } => { + self.write_expr(module, base, func_ctx)?; + + let base_ty_res = &func_ctx.info[base].ty; + let mut resolved = base_ty_res.inner_with(&module.types); + let base_ty_handle = match *resolved { + TypeInner::Pointer { base, class: _ } => { + resolved = &module.types[base].inner; + Some(base) + } + _ => base_ty_res.handle(), + }; + + match *resolved { + TypeInner::Vector { .. } + | TypeInner::Matrix { .. } + | TypeInner::Array { .. } + | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, + TypeInner::Struct { .. } => { + // This will never panic in case the type is a `Struct`, this is not true + // for other types so we can only check while inside this match arm + let ty = base_ty_handle.unwrap(); + + write!( + self.out, + ".{}", + &self.names[&NameKey::StructMember(ty, index)] + )? + } + ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), + } + } + Expression::ImageSample { + image, + sampler, + coordinate, + array_index: _, + offset: _, + level, + depth_ref: _, + } => { + // TODO: other texture functions + // TODO: comments + let fun_name = match level { + crate::SampleLevel::Auto => "textureSample", + _ => todo!("expression_imagesample_level {:?}", level), + }; + write!(self.out, "{}(", fun_name)?; + self.write_expr(module, image, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, sampler, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, coordinate, func_ctx)?; + write!(self.out, ")")?; + } + // TODO: copy-paste from msl-out + Expression::GlobalVariable(handle) => { + let name = &self.names[&NameKey::GlobalVariable(handle)]; + write!(self.out, "{}", name)?; + } + _ => todo!("write_expr {:?}", expression), + } + + Ok(()) + } + + /// Helper method that writes a list of comma separated `T` with a writer function `F` + /// + /// The writer function `F` receives a mutable reference to `self` that if needed won't cause + /// borrow checker issues (using for example a closure with `self` will cause issues), the + /// second argument is the 0 based index of the element on the list, and the last element is + /// a reference to the element `T` being written + /// + /// # Notes + /// - Adds no newlines or leading/trailing whitespace + /// - The last element won't have a trailing `,` + // TODO: copy-paste from glsl-out + fn write_slice BackendResult>( + &mut self, + data: &[T], + mut f: F, + ) -> BackendResult { + // Loop trough `data` invoking `f` for each element + for (i, item) in data.iter().enumerate() { + f(self, i as u32, item)?; + + // Only write a comma if isn't the last element + if i != data.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } + + Ok(()) + } + + /// Helper method used to write global variables + fn write_global(&mut self, module: &Module, global: &GlobalVariable) -> BackendResult { + if let Some(ref binding) = global.binding { + self.write_attributes(&[ + Attribute::Group(binding.group), + Attribute::Binding(binding.binding), + ])?; + write!(self.out, " ")?; + } + + if let Some(ref name) = global.name { + // First write only global name + write!(self.out, "var {}: ", name)?; + // Write global type + self.write_type(module, global.ty)?; + // End with semicolon and extra newline for readability + writeln!(self.out, ";")?; + writeln!(self.out)?; + } + + Ok(()) + } + + /// Helper method used to write constants + /// + /// # Notes + /// Adds newlines for global constants + fn write_constant(&mut self, constant: &Constant, global: bool) -> BackendResult { + match constant.inner { + crate::ConstantInner::Scalar { + width: _, + ref value, + } => { + if let Some(ref name) = constant.name { + if global { + // First write only constant name + write!(self.out, "let {}: ", name)?; + // Next write constant type and value + match *value { + crate::ScalarValue::Sint(value) => { + write!(self.out, "i32 = {}", value)?; + } + crate::ScalarValue::Uint(value) => { + write!(self.out, "u32 = {}", value)?; + } + crate::ScalarValue::Float(value) => { + write!(self.out, "f32 = {}", value)?; + } + crate::ScalarValue::Bool(value) => { + write!(self.out, "bool = {}", value)?; + } + }; + // End with semicolon and extra newline for readability + writeln!(self.out, ";")?; + writeln!(self.out)?; + } else { + write!(self.out, "{}", name)?; + } + } else { + match *value { + crate::ScalarValue::Sint(value) => { + write!(self.out, "{}", value)?; + } + crate::ScalarValue::Uint(value) => { + write!(self.out, "{}", value)?; + } + // TODO: fix float + crate::ScalarValue::Float(value) => { + write!(self.out, "{:.1}", value)?; + } + crate::ScalarValue::Bool(value) => { + write!(self.out, "{}", value)?; + } + }; + } + } + _ => todo!("write_constant {:?}", constant.inner), + } + + Ok(()) + } + pub fn finish(self) -> W { self.out } } + +fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { + use crate::BuiltIn; + match built_in { + BuiltIn::VertexIndex => Some("vertex_index"), + BuiltIn::InstanceIndex => Some("instance_index"), + BuiltIn::Position => Some("position"), + BuiltIn::FrontFacing => Some("front_facing"), + BuiltIn::FragDepth => Some("frag_depth"), + BuiltIn::LocalInvocationId => Some("local_invocation_id"), + BuiltIn::LocalInvocationIndex => Some("local_invocation_index"), + BuiltIn::GlobalInvocationId => Some("global_invocation_id"), + BuiltIn::WorkGroupId => Some("workgroup_id"), + BuiltIn::WorkGroupSize => Some("workgroup_size"), + BuiltIn::SampleIndex => Some("sample_index"), + BuiltIn::SampleMask => Some("sample_mask"), + _ => None, + } +} + +//TODO: copy-paste from msl-out +fn vector_size_str(size: VectorSize) -> &'static str { + match size { + VectorSize::Bi => "2", + VectorSize::Tri => "3", + VectorSize::Quad => "4", + } +} + +//TODO: copy-paste from msl-out +fn image_dimension_str(dim: ImageDimension) -> &'static str { + match dim { + ImageDimension::D1 => "1d", + ImageDimension::D2 => "2d", + ImageDimension::D3 => "3d", + ImageDimension::Cube => "cube", + } +} + +fn scalar_kind_str(kind: ScalarKind) -> &'static str { + match kind { + crate::ScalarKind::Float => "f32", + crate::ScalarKind::Sint => "i32", + crate::ScalarKind::Uint => "u32", + crate::ScalarKind::Bool => "bool", + } +} + +fn storage_format_str(format: StorageFormat) -> &'static str { + match format { + StorageFormat::R8Unorm => "r8unorm", + StorageFormat::R8Snorm => "r8snorm", + StorageFormat::R8Uint => "r8uint", + StorageFormat::R8Sint => "r8sint", + StorageFormat::R16Uint => "r16uint", + StorageFormat::R16Sint => "r16sint", + StorageFormat::R16Float => "r16float", + StorageFormat::Rg8Unorm => "rg8unorm", + StorageFormat::Rg8Snorm => "rg8snorm", + StorageFormat::Rg8Uint => "rg8uint", + StorageFormat::Rg8Sint => "rg8sint", + StorageFormat::R32Uint => "r32uint", + StorageFormat::R32Sint => "r32sint", + StorageFormat::R32Float => "r32float", + StorageFormat::Rg16Uint => "rg16uint", + StorageFormat::Rg16Sint => "rg16sint", + StorageFormat::Rg16Float => "rg16float", + StorageFormat::Rgba8Unorm => "rgba8unorm", + StorageFormat::Rgba8Snorm => "rgba8snorm", + StorageFormat::Rgba8Uint => "rgba8uint", + StorageFormat::Rgba8Sint => "rgba8sint", + StorageFormat::Rgb10a2Unorm => "rgb10a2unorm", + StorageFormat::Rg11b10Float => "rg11b10float", + StorageFormat::Rg32Uint => "rg32uint", + StorageFormat::Rg32Sint => "rg32sint", + StorageFormat::Rg32Float => "rg32float", + StorageFormat::Rgba16Uint => "rgba16uint", + StorageFormat::Rgba16Sint => "rgba16sint", + StorageFormat::Rgba16Float => "rgba16float", + StorageFormat::Rgba32Uint => "rgba32uint", + StorageFormat::Rgba32Sint => "rgba32sint", + StorageFormat::Rgba32Float => "rgba32float", + } +} + +fn map_binding_to_attribute(binding: &Binding) -> Attribute { + match *binding { + Binding::BuiltIn(built_in) => Attribute::BuiltIn(built_in), + //TODO: Interpolation + Binding::Location { location, .. } => Attribute::Location(location), + } +} diff --git a/tests/out/empty.wgsl b/tests/out/empty.wgsl index e89004345..31548a146 100644 --- a/tests/out/empty.wgsl +++ b/tests/out/empty.wgsl @@ -1,2 +1,6 @@ [[stage(compute), workgroup_size(1, 1, 1)]] -fn main(){} +fn main(){ + return; +} + + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 2655e7bdd..baf855f14 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -102,7 +102,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "wgsl-out")] { if targets.contains(Targets::WGSL) { - check_output_wgsl(module, &dest); + check_output_wgsl(module, &info, &dest); } } } @@ -207,10 +207,10 @@ fn check_output_hlsl(module: &naga::Module, destination: &PathBuf) { } #[cfg(feature = "wgsl-out")] -fn check_output_wgsl(module: &naga::Module, destination: &PathBuf) { +fn check_output_wgsl(module: &naga::Module, info: &naga::valid::ModuleInfo, destination: &PathBuf) { use naga::back::wgsl; - let string = wgsl::write_string(module).unwrap(); + let string = wgsl::write_string(module, info).unwrap(); fs::write(destination.with_extension("wgsl"), string).unwrap(); } From b6996dbd32896e06c8f48d60f922743695bd5c60 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Fri, 23 Apr 2021 19:25:50 +0300 Subject: [PATCH 0741/2212] Return error exit code if validation fails --- bin/convert.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bin/convert.rs b/bin/convert.rs index 0a5025cc1..bd8100bf5 100644 --- a/bin/convert.rs +++ b/bin/convert.rs @@ -188,8 +188,10 @@ fn main() { None => { if info.is_some() { println!("Validation successful"); + return; + } else { + std::process::exit(!0); } - return; } }; if output_path == "-" { From 74f0a153cb633cb4b93946f4112ff5dbc135a588 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 23 Apr 2021 12:32:28 -0400 Subject: [PATCH 0742/2212] Rename the binary to just naga --- Cargo.toml | 6 +++--- Makefile | 4 ++-- README.md | 2 +- bin/{convert.rs => naga.rs} | 0 4 files changed, 6 insertions(+), 6 deletions(-) rename bin/{convert.rs => naga.rs} (100%) diff --git a/Cargo.toml b/Cargo.toml index 90b3dedd1..b3f3e5dcc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,7 +25,7 @@ thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } pp-rs = { git = "https://github.com/Kangz/glslpp-rs", rev = "4f2f72a", optional = true } -#env_logger = "0.8" # uncomment temporarily for developing with `convert` +#env_logger = "0.8" # uncomment temporarily for developing with the binary target [features] default = [] @@ -43,8 +43,8 @@ wgsl-out = [] hlsl-out = [] [[bin]] -name = "convert" -path = "bin/convert.rs" +name = "naga" +path = "bin/naga.rs" [dev-dependencies] diff = "0.1" diff --git a/Makefile b/Makefile index 10f9b6f92..d52a82ab2 100644 --- a/Makefile +++ b/Makefile @@ -20,7 +20,7 @@ clean: %.metallib: %.air xcrun -sdk macosx metallib $< -o $@ -%.dot: $(SNAPSHOTS_IN)/%.wgsl $(wildcard src/*.rs src/front/wgsl/*.rs src/back/dot/*.rs bin/convert.rs) +%.dot: $(SNAPSHOTS_IN)/%.wgsl $(wildcard src/*.rs src/front/wgsl/*.rs src/back/dot/*.rs bin/naga.rs) cargo run --features wgsl-in,dot-out -- $< $@ %.png: %.dot @@ -61,5 +61,5 @@ validate-dot: $(SNAPSHOTS_OUT)/*.dot validate-wgsl: $(SNAPSHOTS_OUT)/*.wgsl @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ - cargo run --bin convert --features wgsl-in $${file}; \ + cargo run --features wgsl-in $${file}; \ done diff --git a/README.md b/README.md index 6482c9ab4..4087a07d8 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ DOT (GraphViz) | :ok: | dot-out | Not a shading language | ## Conversion tool -Naga includes a default binary target "convert", which allows to test the conversion of different code paths. +Naga includes a default binary target, which allows to test the conversion of different code paths. ```bash cargo run --features wgsl-in -- my_shader.wgsl # validate only cargo run --features spv-in -- my_shader.spv - # dump the IR module to debug output diff --git a/bin/convert.rs b/bin/naga.rs similarity index 100% rename from bin/convert.rs rename to bin/naga.rs From 076349ddf7686e563cd1a0fbd1a58fdf3c7b7df8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 21 Apr 2021 11:35:44 +0100 Subject: [PATCH 0743/2212] [glsl-in] Export types to allow for error handling --- src/front/glsl/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 327b8424c..36b26b907 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,3 +1,7 @@ +pub use error::ErrorKind; +pub use parser::Token; +pub use token::TokenMetadata; + use crate::{FastHashMap, Module, ShaderStage}; mod lex; From 6247f2c822a1cd2508750ce43d1437b1b50531b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 22 Apr 2021 22:20:27 +0100 Subject: [PATCH 0744/2212] [glsl-in] Load local variables --- src/front/glsl/ast.rs | 12 +++++++++++- src/front/glsl/parser.rs | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index b85a7f8e8..aaa8a7d80 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -235,7 +235,17 @@ impl Context { /// Add variable to current scope pub fn add_local_var(&mut self, name: String, handle: Handle) { if let Some(current) = self.scopes.last_mut() { - (*current).insert(name, handle); + let expr = self + .expressions + .append(Expression::Load { pointer: handle }); + (*current).insert(name, expr); + } + } + + /// Add function argument to current scope + pub fn add_function_arg(&mut self, name: String, expr: Handle) { + if let Some(current) = self.scopes.last_mut() { + (*current).insert(name, expr); } } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 20a9716e1..4db6e57c6 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1052,7 +1052,7 @@ pomelo! { for (pos, arg) in args.into_iter().enumerate() { if let Some(name) = arg.name.clone() { let exp = extra.context.expressions.append(Expression::FunctionArgument(pos as u32)); - extra.context.add_local_var(name, exp); + extra.context.add_function_arg(name, exp); } extra.context.arguments.push(arg); } From 62e3ba4bcc8d620eed297f2634fb59a1c5654ed8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 22 Apr 2021 22:28:22 +0100 Subject: [PATCH 0745/2212] [glsl-in] Fix type constructor of vec/matrix --- src/front/glsl/functions.rs | 57 ++++++++++++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index ed3908fca..4b098171b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,7 +1,7 @@ use super::super::Typifier; use crate::{ proc::ensure_block_returns, BinaryOperator, Block, EntryPoint, Expression, Function, - MathFunction, RelationalFunction, SampleLevel, TypeInner, + MathFunction, RelationalFunction, SampleLevel, Type, TypeInner, }; use super::{ast::*, error::ErrorKind}; @@ -11,20 +11,69 @@ impl Program<'_> { match fc.kind { FunctionCallKind::TypeConstructor(ty) => { let h = if fc.args.len() == 1 { - let kind = self.module.types[ty].inner.scalar_kind().ok_or_else(|| { + let is_vec = match *self.resolve_type(fc.args[0].expression)? { + TypeInner::Vector { .. } => true, + _ => false, + }; + let inner = &self.module.types[ty].inner; + let kind = inner.scalar_kind().ok_or_else(|| { ErrorKind::SemanticError("Can only cast to scalar or vector".into()) })?; - self.context.expressions.append(Expression::As { + let val = self.context.expressions.append(Expression::As { kind, expr: fc.args[0].expression, convert: true, - }) + }); + + match *inner { + TypeInner::Vector { size, .. } if !is_vec => { + let components = std::iter::repeat(val).take(size as usize).collect(); + + self.context + .expressions + .append(Expression::Compose { ty, components }) + } + TypeInner::Matrix { + columns, + rows, + width, + } => { + let column = if is_vec { + val + } else { + let vec_ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind, + width, + }, + }); + let rows = std::iter::repeat(val).take(rows as usize).collect(); + + self.context.expressions.append(Expression::Compose { + ty: vec_ty, + components: rows, + }) + }; + + let columns = + std::iter::repeat(column).take(columns as usize).collect(); + + self.context.expressions.append(Expression::Compose { + ty, + components: columns, + }) + } + _ => val, + } } else { self.context.expressions.append(Expression::Compose { ty, components: fc.args.iter().map(|a| a.expression).collect(), }) }; + Ok(ExpressionRule { expression: h, statements: fc From 2b8b5a271d00eaaca7af5e3c3c40d246c5c7d6a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 22 Apr 2021 22:29:02 +0100 Subject: [PATCH 0746/2212] [glsl-in] Implement textureLod --- src/front/glsl/functions.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 4b098171b..2009f127d 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -131,6 +131,35 @@ impl Program<'_> { Err(ErrorKind::SemanticError("Bad call to texture".into())) } } + "textureLod" => { + if fc.args.len() != 3 { + return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); + } + if let Some(sampler) = fc.args[0].sampler { + Ok(ExpressionRule { + expression: self.context.expressions.append( + Expression::ImageSample { + image: fc.args[0].expression, + sampler, + coordinate: fc.args[1].expression, + array_index: None, //TODO + offset: None, //TODO + level: SampleLevel::Exact(fc.args[2].expression), + depth_ref: None, + }, + ), + sampler: None, + statements: fc + .args + .into_iter() + .map(|a| a.statements) + .flatten() + .collect(), + }) + } else { + Err(ErrorKind::SemanticError("Bad call to textureLod".into())) + } + } "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" | "normalize" => { From 7135c051b4363df1d8cb137d42e46c4c115adf83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 23 Apr 2021 14:47:41 +0100 Subject: [PATCH 0747/2212] [glsl-in] Support for function parameters with In --- src/front/glsl/parser.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 4db6e57c6..1b260ea72 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1079,8 +1079,8 @@ pomelo! { FunctionArgument { name: Some(n.1), ty, binding: None } } // parameter_declarator ::= type_specifier(ty) Identifier(ident) array_specifier; - parameter_declaration ::= parameter_declarator; - parameter_declaration ::= parameter_type_specifier(ty) { + parameter_declaration ::= In? parameter_declarator(arg) { arg }; + parameter_declaration ::= In? parameter_type_specifier(ty) { FunctionArgument { name: None, ty, binding: None } } From 64856a808e37d8f241f151071490d898d21ae113 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 24 Apr 2021 00:06:16 -0400 Subject: [PATCH 0748/2212] [spv-in] refactor image coordinate extraction --- src/front/spv/error.rs | 1 - src/front/spv/image.rs | 294 +++++++++++++++++------------------------ src/front/spv/mod.rs | 38 ++++-- 3 files changed, 147 insertions(+), 186 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index ea5bbb377..4f4e6b166 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -41,7 +41,6 @@ pub enum Error { InvalidGlobalVar(crate::Expression), InvalidImageBaseType(Handle), InvalidImage(Handle), - InvalidDepthReference(Handle), InvalidAsType(Handle), InvalidVectorType(Handle), InconsistentComparisonSampling(Handle), diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 1859ecceb..ef8763811 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -30,6 +30,22 @@ impl Arena { } } +/// Options of a sampling operation. +#[derive(Debug)] +pub struct SamplingOptions { + /// Projection sampling: the division by W is expected to happen + /// in the texture unit. + pub project: bool, + /// Depth comparison sampling with a reference value. + pub compare: bool, +} + +enum ExtraCoordinate { + ArrayLayer, + Projection, + Garbage, +} + /// Return the texture coordinates separated from the array layer, /// and/or divided by the projection term. /// @@ -37,7 +53,7 @@ impl Arena { /// The arrayed (can't be Proj!) images expect an extra coordinate for the layer. fn extract_image_coordinates( image_dim: crate::ImageDimension, - image_arrayed: bool, + extra_coordinate: ExtraCoordinate, base: Handle, coordinate_ty: Handle, type_arena: &Arena, @@ -67,62 +83,76 @@ fn extract_image_coordinates( index: required_size.map_or(1, |size| size as u32), }; - if given_size == required_size { - // fast path, no complications - (base, None) - } else if image_arrayed { - // extra coordinate for the array index - let extracted = match required_size { - None => expressions.append(crate::Expression::AccessIndex { base, index: 0 }), - Some(size) => { - let mut components = Vec::with_capacity(size as usize); - for index in 0..size as u32 { - let comp = expressions.append(crate::Expression::AccessIndex { base, index }); - components.push(comp); + match extra_coordinate { + ExtraCoordinate::ArrayLayer => { + let extracted = match required_size { + None => expressions.append(crate::Expression::AccessIndex { base, index: 0 }), + Some(size) => { + let mut components = Vec::with_capacity(size as usize); + for index in 0..size as u32 { + let comp = + expressions.append(crate::Expression::AccessIndex { base, index }); + components.push(comp); + } + expressions.append(crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }) } - expressions.append(crate::Expression::Compose { - ty: required_ty.unwrap(), - components, - }) - } - }; - let array_index_f32 = expressions.append(extra_expr); - let array_index = expressions.append(crate::Expression::As { - kind: crate::ScalarKind::Sint, - expr: array_index_f32, - convert: true, - }); - (extracted, Some(array_index)) - } else { - // extra coordinate for the projection W - let projection = expressions.append(extra_expr); - let divided = match required_size { - None => { - let temp = expressions.append(crate::Expression::AccessIndex { base, index: 0 }); - expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Divide, - left: temp, - right: projection, - }) - } - Some(size) => { - let mut components = Vec::with_capacity(size as usize); - for index in 0..size as u32 { - let temp = expressions.append(crate::Expression::AccessIndex { base, index }); - let comp = expressions.append(crate::Expression::Binary { + }; + let array_index_f32 = expressions.append(extra_expr); + let array_index = expressions.append(crate::Expression::As { + kind: crate::ScalarKind::Sint, + expr: array_index_f32, + convert: true, + }); + (extracted, Some(array_index)) + } + ExtraCoordinate::Projection => { + let projection = expressions.append(extra_expr); + let divided = match required_size { + None => { + let temp = + expressions.append(crate::Expression::AccessIndex { base, index: 0 }); + expressions.append(crate::Expression::Binary { op: crate::BinaryOperator::Divide, left: temp, right: projection, - }); - components.push(comp); + }) } - expressions.append(crate::Expression::Compose { - ty: required_ty.unwrap(), - components, - }) - } - }; - (divided, None) + Some(size) => { + let mut components = Vec::with_capacity(size as usize); + for index in 0..size as u32 { + let temp = + expressions.append(crate::Expression::AccessIndex { base, index }); + let comp = expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: temp, + right: projection, + }); + components.push(comp); + } + expressions.append(crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }) + } + }; + (divided, None) + } + ExtraCoordinate::Garbage if given_size == required_size => (base, None), + ExtraCoordinate::Garbage => { + use crate::SwizzleComponent as Sc; + let cut_expr = match required_size { + None => crate::Expression::AccessIndex { base, index: 0 }, + Some(size) => crate::Expression::Swizzle { + size, + vector: base, + pattern: [Sc::X, Sc::Y, Sc::Z, Sc::W], + }, + }; + (expressions.append(cut_expr), None) + } } } @@ -228,7 +258,11 @@ impl> super::Parser { class: _, } => extract_image_coordinates( dim, - arrayed, + if arrayed { + ExtraCoordinate::ArrayLayer + } else { + ExtraCoordinate::Garbage + }, coord_lexp.handle, coord_type_handle, type_arena, @@ -306,7 +340,11 @@ impl> super::Parser { class: _, } => extract_image_coordinates( dim, - arrayed, + if arrayed { + ExtraCoordinate::ArrayLayer + } else { + ExtraCoordinate::Garbage + }, coord_lexp.handle, coord_type_handle, type_arena, @@ -334,6 +372,7 @@ impl> super::Parser { pub(super) fn parse_image_sample( &mut self, mut words_left: u16, + options: SamplingOptions, type_arena: &Arena, global_arena: &Arena, expressions: &mut Arena, @@ -342,6 +381,11 @@ impl> super::Parser { let result_id = self.next()?; let sampled_image_id = self.next()?; let coordinate_id = self.next()?; + let dref_id = if options.compare { + Some(self.next()?) + } else { + None + }; let mut image_ops = if words_left != 0 { words_left -= 1; @@ -374,7 +418,7 @@ impl> super::Parser { words_left -= 1; } other => { - log::warn!("Unknown image sample op {:?}", other); + log::warn!("Unknown image sample operand {:?}", other); for _ in 0..words_left { self.next()?; } @@ -391,14 +435,20 @@ impl> super::Parser { let image_var_handle = expressions.get_global_var(si_lexp.image)?; let sampler_var_handle = expressions.get_global_var(si_lexp.sampler)?; log::debug!( - "\t\t\tImage {:?} sampled with {:?}", + "\t\t\tImage {:?} sampled with {:?} under {:?}", image_var_handle, - sampler_var_handle + sampler_var_handle, + options, ); + let sampling_bit = if options.compare { + SamplingFlags::COMPARISON + } else { + SamplingFlags::REGULAR + }; if let Some(flags) = self.handle_sampling.get_mut(&image_var_handle) { - *flags |= SamplingFlags::REGULAR; + *flags |= sampling_bit; } - *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= SamplingFlags::REGULAR; + *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= sampling_bit; let image_var = &global_arena[image_var_handle]; let (coordinate, array_index) = match type_arena[image_var.ty].inner { @@ -408,7 +458,13 @@ impl> super::Parser { class: _, } => extract_image_coordinates( dim, - arrayed, + if options.project { + ExtraCoordinate::Projection + } else if arrayed { + ExtraCoordinate::ArrayLayer + } else { + ExtraCoordinate::Garbage + }, coord_lexp.handle, coord_type_handle, type_arena, @@ -424,122 +480,10 @@ impl> super::Parser { array_index, offset, level, - depth_ref: None, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, + depth_ref: match dref_id { + Some(id) => Some(self.lookup_expression.lookup(id)?.handle), + None => None, }, - ); - Ok(()) - } - - pub(super) fn parse_image_sample_dref( - &mut self, - mut words_left: u16, - type_arena: &Arena, - global_arena: &Arena, - expressions: &mut Arena, - ) -> Result<(), Error> { - let result_type_id = self.next()?; - let result_id = self.next()?; - let sampled_image_id = self.next()?; - let coordinate_id = self.next()?; - let dref_id = self.next()?; - - let mut image_ops = if words_left != 0 { - words_left -= 1; - self.next()? - } else { - 0 - }; - - let mut level = crate::SampleLevel::Auto; - let mut offset = None; - while image_ops != 0 { - let bit = 1 << image_ops.trailing_zeros(); - match spirv::ImageOperands::from_bits_truncate(bit) { - spirv::ImageOperands::BIAS => { - let bias_expr = self.next()?; - let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; - level = crate::SampleLevel::Bias(bias_handle); - words_left -= 1; - } - spirv::ImageOperands::LOD => { - let lod_expr = self.next()?; - let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; - level = crate::SampleLevel::Exact(lod_handle); - words_left -= 1; - } - spirv::ImageOperands::CONST_OFFSET => { - let offset_constant = self.next()?; - let offset_handle = self.lookup_constant.lookup(offset_constant)?.handle; - offset = Some(offset_handle); - words_left -= 1; - } - other => { - log::warn!("Unknown image sample dref op {:?}", other); - for _ in 0..words_left { - self.next()?; - } - break; - } - } - image_ops ^= bit; - } - - let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; - let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let image_var_handle = expressions.get_global_var(si_lexp.image)?; - let sampler_var_handle = expressions.get_global_var(si_lexp.sampler)?; - log::debug!( - "\t\t\tImage {:?} sampled with comparison {:?}", - image_var_handle, - sampler_var_handle - ); - if let Some(flags) = self.handle_sampling.get_mut(&image_var_handle) { - *flags |= SamplingFlags::COMPARISON; - } - *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= SamplingFlags::COMPARISON; - - let dref_lexp = self.lookup_expression.lookup(dref_id)?; - let dref_type_handle = self.lookup_type.lookup(dref_lexp.type_id)?.handle; - match type_arena[dref_type_handle].inner { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: _, - } => (), - _ => return Err(Error::InvalidDepthReference(dref_type_handle)), - } - - let image_var = &global_arena[image_var_handle]; - let (coordinate, array_index) = match type_arena[image_var.ty].inner { - crate::TypeInner::Image { - dim, - arrayed, - class: _, - } => extract_image_coordinates( - dim, - arrayed, - coord_lexp.handle, - coord_type_handle, - type_arena, - expressions, - ), - _ => return Err(Error::InvalidImage(image_var.ty)), - }; - - let expr = crate::Expression::ImageSample { - image: si_lexp.image, - sampler: si_lexp.sampler, - coordinate, - array_index, - offset, - level, - depth_ref: Some(dref_lexp.handle), }; self.lookup_expression.insert( result_id, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 44cfbb1b0..444c66f00 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1377,19 +1377,37 @@ impl> Parser { let extra = inst.expect_at_least(5)?; self.parse_image_load(extra, type_arena, global_arena, expressions)?; } - Op::ImageSampleImplicitLod - | Op::ImageSampleExplicitLod - | Op::ImageSampleProjImplicitLod - | Op::ImageSampleProjExplicitLod => { + Op::ImageSampleImplicitLod | Op::ImageSampleExplicitLod => { let extra = inst.expect_at_least(5)?; - self.parse_image_sample(extra, type_arena, global_arena, expressions)?; + let options = image::SamplingOptions { + compare: false, + project: false, + }; + self.parse_image_sample(extra, options, type_arena, global_arena, expressions)?; } - Op::ImageSampleDrefImplicitLod - | Op::ImageSampleDrefExplicitLod - | Op::ImageSampleProjDrefImplicitLod - | Op::ImageSampleProjDrefExplicitLod => { + Op::ImageSampleProjImplicitLod | Op::ImageSampleProjExplicitLod => { + let extra = inst.expect_at_least(5)?; + let options = image::SamplingOptions { + compare: false, + project: true, + }; + self.parse_image_sample(extra, options, type_arena, global_arena, expressions)?; + } + Op::ImageSampleDrefImplicitLod | Op::ImageSampleDrefExplicitLod => { let extra = inst.expect_at_least(6)?; - self.parse_image_sample_dref(extra, type_arena, global_arena, expressions)?; + let options = image::SamplingOptions { + compare: true, + project: false, + }; + self.parse_image_sample(extra, options, type_arena, global_arena, expressions)?; + } + Op::ImageSampleProjDrefImplicitLod | Op::ImageSampleProjDrefExplicitLod => { + let extra = inst.expect_at_least(6)?; + let options = image::SamplingOptions { + compare: true, + project: true, + }; + self.parse_image_sample(extra, options, type_arena, global_arena, expressions)?; } Op::ImageQuerySize => { inst.expect(4)?; From 34b830da17070d6f3913501f5946df5cb0c2f27c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 24 Apr 2021 00:52:44 -0400 Subject: [PATCH 0749/2212] [spv-in] work around sign differences in OpIAdd and OpISubtract --- src/front/spv/mod.rs | 71 +++++++++++++++++++++++++++++++++++++++-- src/valid/expression.rs | 10 ++++++ 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 444c66f00..90f397c4d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -593,6 +593,57 @@ impl> Parser { Ok(()) } + /// A more complicated version of the binary op, + /// where we force the operand to have the same type as the result. + /// This is mostly needed for "i++" and "i--" coming from GLSL. + fn parse_expr_binary_op_sign_adjusted( + &mut self, + expressions: &mut Arena, + op: crate::BinaryOperator, + types: &Arena, + ) -> Result<(), Error> { + let result_type_id = self.next()?; + let result_id = self.next()?; + let p1_id = self.next()?; + let p2_id = self.next()?; + + let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let p2_lexp = self.lookup_expression.lookup(p2_id)?; + let result_lookup_ty = self.lookup_type.lookup(result_type_id)?; + let kind = types[result_lookup_ty.handle].inner.scalar_kind().unwrap(); + + let expr = crate::Expression::Binary { + op, + left: if p1_lexp.type_id == result_type_id { + p1_lexp.handle + } else { + expressions.append(crate::Expression::As { + expr: p1_lexp.handle, + kind, + convert: true, + }) + }, + right: if p2_lexp.type_id == result_type_id { + p2_lexp.handle + } else { + expressions.append(crate::Expression::As { + expr: p2_lexp.handle, + kind, + convert: true, + }) + }, + }; + + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + Ok(()) + } + fn parse_expr_shift_op( &mut self, expressions: &mut Arena, @@ -1255,11 +1306,27 @@ impl> Parser { inst.expect(4)?; self.parse_expr_unary_op(expressions, crate::UnaryOperator::Negate)?; } - Op::IAdd | Op::FAdd => { + Op::IAdd => { + inst.expect(5)?; + self.parse_expr_binary_op_sign_adjusted( + expressions, + crate::BinaryOperator::Add, + type_arena, + )?; + } + Op::FAdd => { inst.expect(5)?; self.parse_expr_binary_op(expressions, crate::BinaryOperator::Add)?; } - Op::ISub | Op::FSub => { + Op::ISub => { + inst.expect(5)?; + self.parse_expr_binary_op_sign_adjusted( + expressions, + crate::BinaryOperator::Subtract, + type_arena, + )?; + } + Op::FSub => { inst.expect(5)?; self.parse_expr_binary_op(expressions, crate::BinaryOperator::Subtract)?; } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 863909632..727e46492 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -693,6 +693,16 @@ impl super::Validator { } }; if !good { + log::error!( + "Left: {:?} of type {:?}", + function.expressions[left], + left_inner + ); + log::error!( + "Right: {:?} of type {:?}", + function.expressions[right], + right_inner + ); return Err(ExpressionError::InvalidBinaryOperandTypes(op, left, right)); } ShaderStages::all() From 77a64da189e6ed2c4631ca03cb01b8d8124c4dad Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 24 Apr 2021 01:29:17 -0400 Subject: [PATCH 0750/2212] [spv-out] support function arguments as pointers --- src/back/spv/writer.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 6bead4dd4..c966ddf1b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2298,6 +2298,10 @@ impl Writer { let local_var = &function.variables[&variable]; break (local_var.id, spirv::StorageClass::Function); } + crate::Expression::FunctionArgument(index) => { + let id = function.parameters[index as usize].result_id.unwrap(); + break (id, spirv::StorageClass::Function); + } ref other => unimplemented!("Unexpected pointer expression {:?}", other), } }; From 1cc770a7d8d0f460bf5a491e53961d8213e7c46b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 24 Apr 2021 23:45:04 -0400 Subject: [PATCH 0751/2212] [spv-out] return Null by default --- src/back/spv/instructions.rs | 7 +++++++ src/back/spv/writer.rs | 15 +++++++++++++-- tests/out/texture-array.spvasm | 2 +- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 9bc4f56f9..828b944a8 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -350,6 +350,13 @@ impl super::Instruction { // Constant-Creation Instructions // + pub(super) fn constant_null(result_type_id: Word, id: Word) -> Self { + let mut instruction = Self::new(Op::ConstantNull); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction + } + pub(super) fn constant_true(result_type_id: Word, id: Word) -> Self { let mut instruction = Self::new(Op::ConstantTrue); instruction.set_type(result_type_id); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index c966ddf1b..e1a7b7d3c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2741,8 +2741,19 @@ impl Writer { Some(id) => Instruction::branch(id), // This can happen if the last branch had all the paths // leading out of the graph (i.e. returning). - // So it doesn't matter what we do here, but it has to be valid. - None => Instruction::branch(label_id), + // Or it may be the end of the function. + None => match ir_function.result { + Some(ref result) if function.entry_point_context.is_none() => { + // create a Null and return it + let null_id = self.id_gen.next(); + let type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(result.ty))?; + Instruction::constant_null(type_id, null_id) + .to_words(&mut self.logical_layout.declarations); + Instruction::return_value(null_id) + } + _ => Instruction::return_void(), + }, }); } diff --git a/tests/out/texture-array.spvasm b/tests/out/texture-array.spvasm index 1f4ba03f4..58a2d5b3e 100644 --- a/tests/out/texture-array.spvasm +++ b/tests/out/texture-array.spvasm @@ -76,5 +76,5 @@ OpReturn OpStore %22 %44 OpReturn %37 = OpLabel -OpBranch %29 +OpReturn OpFunctionEnd \ No newline at end of file From 7ec90512a8dc2ae484c6043b36e68fd47c23e431 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 00:43:05 -0400 Subject: [PATCH 0752/2212] [spv-out] deduplicate image types --- src/back/spv/writer.rs | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e1a7b7d3c..6b2a28f4b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -123,8 +123,13 @@ enum LocalType { base: Handle, class: spirv::StorageClass, }, + Image { + dim: crate::ImageDimension, + arrayed: bool, + class: crate::ImageClass, + }, SampledImage { - image_type: Handle, + image_type_id: Word, }, } @@ -167,6 +172,15 @@ impl PhysicalLayout { width, pointer_class: Some(map_storage_class(class)), }, + crate::TypeInner::Image { + dim, + arrayed, + class, + } => LocalType::Image { + dim, + arrayed, + class, + }, _ => return None, }) } @@ -763,8 +777,9 @@ impl Writer { )?; Instruction::type_pointer(id, class, type_id) } - LocalType::SampledImage { image_type } => { - let image_type_id = self.get_type_id(arena, LookupType::Handle(image_type))?; + // all the image types go through `write_type_declaration_arena` + LocalType::Image { .. } => unreachable!(), + LocalType::SampledImage { image_type_id } => { Instruction::type_sampled_image(id, image_type_id) } }; @@ -1951,9 +1966,11 @@ impl Writer { }; // OpTypeSampledImage + let image_type_id = + self.get_type_id(&ir_module.types, LookupType::Handle(image_type))?; let sampled_image_type_id = self.get_type_id( &ir_module.types, - LookupType::Local(LocalType::SampledImage { image_type }), + LookupType::Local(LocalType::SampledImage { image_type_id }), )?; let sampler_id = self.get_expression_global(ir_function, sampler); From 28cba7945262ef8482985ab463a5cd9fb6da3a35 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 00:58:36 -0400 Subject: [PATCH 0753/2212] [spv-out] deduplicate sampler types --- src/back/spv/writer.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 6b2a28f4b..e8520e3e6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -131,6 +131,7 @@ enum LocalType { SampledImage { image_type_id: Word, }, + Sampler, } impl PhysicalLayout { @@ -181,6 +182,7 @@ impl PhysicalLayout { arrayed, class, }, + crate::TypeInner::Sampler { comparison: _ } => LocalType::Sampler, _ => return None, }) } @@ -777,8 +779,8 @@ impl Writer { )?; Instruction::type_pointer(id, class, type_id) } - // all the image types go through `write_type_declaration_arena` - LocalType::Image { .. } => unreachable!(), + // all the samplers and image types go through `write_type_declaration_arena` + LocalType::Image { .. } | LocalType::Sampler => unreachable!(), LocalType::SampledImage { image_type_id } => { Instruction::type_sampled_image(id, image_type_id) } From ecffe374569a5bd9f701a8be5b518c10f3bc8cd3 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 01:10:57 -0400 Subject: [PATCH 0754/2212] Enforce sampled types to be Float --- src/valid/expression.rs | 44 ++++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 727e46492..dcde1d087 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -284,6 +284,7 @@ impl super::Validator { level, depth_ref, } => { + // check the validity of expressions let image_var = match function.expressions[image] { crate::Expression::GlobalVariable(var_handle) => { &module.global_variables[var_handle] @@ -303,26 +304,11 @@ impl super::Validator { let (class, dim) = match module.types[image_var.ty].inner { Ti::Image { - //TODO: should we check that this is Float-only? class, arrayed, dim, } => { - let image_depth = match class { - crate::ImageClass::Sampled { - kind: _, - multi: false, - } => false, - crate::ImageClass::Depth => true, - _ => return Err(ExpressionError::InvalidImageClass(class)), - }; - if comparison != depth_ref.is_some() || (comparison && !image_depth) { - return Err(ExpressionError::ComparisonSamplingMismatch { - image: class, - sampler: comparison, - has_ref: depth_ref.is_some(), - }); - } + // check the array property if arrayed != array_index.is_some() { return Err(ExpressionError::InvalidImageArrayIndex); } @@ -340,6 +326,24 @@ impl super::Validator { _ => return Err(ExpressionError::ExpectedImageType(image_var.ty)), }; + // check sampling and comparison properties + let image_depth = match class { + crate::ImageClass::Sampled { + kind: crate::ScalarKind::Float, + multi: false, + } => false, + crate::ImageClass::Depth => true, + _ => return Err(ExpressionError::InvalidImageClass(class)), + }; + if comparison != depth_ref.is_some() || (comparison && !image_depth) { + return Err(ExpressionError::ComparisonSamplingMismatch { + image: class, + sampler: comparison, + has_ref: depth_ref.is_some(), + }); + } + + // check texture coordinates type let num_components = match dim { crate::ImageDimension::D1 => 1, crate::ImageDimension::D2 => 2, @@ -356,6 +360,8 @@ impl super::Validator { } if size as u32 == num_components => {} _ => return Err(ExpressionError::InvalidImageCoordinateType(dim, coordinate)), } + + // check constant offset if let Some(const_handle) = offset { let good = match module.constants[const_handle].inner { crate::ConstantInner::Scalar { @@ -379,6 +385,7 @@ impl super::Validator { } } + // check depth reference type if let Some(expr) = depth_ref { match *resolver.resolve(expr)? { Ti::Scalar { @@ -387,12 +394,13 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidDepthReference(expr)), } } + + // check level properties let can_level = match class { crate::ImageClass::Sampled { multi, .. } => !multi, - crate::ImageClass::Storage { .. } => false, + crate::ImageClass::Storage { .. } => unreachable!(), crate::ImageClass::Depth { .. } => true, }; - match level { // require `can_level` here? crate::SampleLevel::Auto => ShaderStages::FRAGMENT, From 41e91739acb1a107899a4dec4958e576458c10d8 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sat, 24 Apr 2021 15:44:28 +0300 Subject: [PATCH 0755/2212] [wgsl-out] Return Err instead of panic for unimplemented cases --- src/back/wgsl/mod.rs | 2 ++ src/back/wgsl/writer.rs | 29 ++++++++++++++++++++++++----- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index f259355d8..1ca762af9 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -11,6 +11,8 @@ pub enum Error { FmtError(#[from] std::fmt::Error), #[error("{0}")] Custom(String), + #[error("{0}")] + Unimplemented(String), // TODO: Error used only during development } pub fn write_string( diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index ad3e37c45..dc20a37e9 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -341,7 +341,12 @@ impl Writer { ); write!(self.out, "{}", ty_str)?; } - _ => todo!("write_value_type {:?}", inner), + _ => { + return Err(Error::Unimplemented(format!( + "write_value_type {:?}", + inner + ))); + } } Ok(()) @@ -420,7 +425,9 @@ impl Writer { write!(self.out, "{}", INDENT.repeat(indent))?; writeln!(self.out, "discard;")? } - _ => todo!("write_stmt {:?}", stmt), + _ => { + return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))); + } } Ok(()) @@ -543,7 +550,12 @@ impl Writer { // TODO: comments let fun_name = match level { crate::SampleLevel::Auto => "textureSample", - _ => todo!("expression_imagesample_level {:?}", level), + _ => { + return Err(Error::Unimplemented(format!( + "expression_imagesample_level {:?}", + level + ))); + } }; write!(self.out, "{}(", fun_name)?; self.write_expr(module, image, func_ctx)?; @@ -558,7 +570,9 @@ impl Writer { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; } - _ => todo!("write_expr {:?}", expression), + _ => { + return Err(Error::Unimplemented(format!("write_expr {:?}", expression))); + } } Ok(()) @@ -670,7 +684,12 @@ impl Writer { }; } } - _ => todo!("write_constant {:?}", constant.inner), + _ => { + return Err(Error::Unimplemented(format!( + "write_constant {:?}", + constant.inner + ))); + } } Ok(()) From 0459470986a7a32d650a7917c90c1cded4851e27 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sat, 24 Apr 2021 17:15:27 +0300 Subject: [PATCH 0756/2212] [wgsl-out] Implement writing for more value types --- src/back/wgsl/writer.rs | 167 +++++++++++++++++++++++++--------------- 1 file changed, 107 insertions(+), 60 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index dc20a37e9..f43e7f3ce 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -5,8 +5,8 @@ use crate::{ back::wgsl::keywords::RESERVED, proc::{EntryPointIndex, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, - Arena, BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, - ImageClass, ImageDimension, Module, ScalarKind, ShaderStage, Statement, StorageFormat, + Arena, ArraySize, BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, + Handle, ImageClass, ImageDimension, Module, ScalarKind, ShaderStage, Statement, StorageFormat, StructLevel, Type, TypeInner, }; use crate::{ @@ -30,6 +30,7 @@ enum Attribute { Group(u32), Location(u32), Stage(ShaderStage), + Stride(u32), WorkGroupSize([u32; 3]), } @@ -140,59 +141,61 @@ impl Writer { func: &Function, func_ctx: &FunctionCtx<'_>, ) -> BackendResult { - // TODO: unnamed function? - write!(self.out, "fn {}(", func.name.as_ref().unwrap())?; + if func.name.is_some() { + write!(self.out, "fn {}(", func.name.as_ref().unwrap())?; - // Write function arguments - // TODO: another function type - if let FunctionType::EntryPoint(ep_index) = func_ctx.ty { - for (index, arg) in func.arguments.iter().enumerate() { - // Write argument attribute if a binding is present - if let Some(ref binding) = arg.binding { + // Write function arguments + // TODO: another function type + if let FunctionType::EntryPoint(ep_index) = func_ctx.ty { + for (index, arg) in func.arguments.iter().enumerate() { + // Write argument attribute if a binding is present + if let Some(ref binding) = arg.binding { + self.write_attributes(&[map_binding_to_attribute(binding)])?; + write!(self.out, " ")?; + } + // Write argument name + write!( + self.out, + "{}: ", + &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)] + )?; + // Write argument type + self.write_type(module, arg.ty)?; + if index < func.arguments.len() - 1 { + // Add a separator between args + write!(self.out, ", ")?; + } + } + write!(self.out, ")")?; + } + + // Write function return type + if let Some(ref result) = func.result { + if let Some(ref binding) = result.binding { + write!(self.out, " -> ")?; self.write_attributes(&[map_binding_to_attribute(binding)])?; write!(self.out, " ")?; - } - // Write argument name - write!( - self.out, - "{}: ", - &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)] - )?; - // Write argument type - self.write_type(module, arg.ty)?; - if index < func.arguments.len() - 1 { - // Add a separator between args - write!(self.out, ", ")?; + self.write_type(module, result.ty)?; + // Extra space only for readability + write!(self.out, " ")?; + } else { + let struct_name = &self.names[&NameKey::Type(result.ty)].clone(); + write!(self.out, " -> {} ", struct_name)?; } } - write!(self.out, ")")?; - } - // Write function return type - if let Some(ref result) = func.result { - if let Some(ref binding) = result.binding { - write!(self.out, " -> ")?; - self.write_attributes(&[map_binding_to_attribute(binding)])?; - write!(self.out, " ")?; - self.write_type(module, result.ty)?; - // Extra space only for readability - write!(self.out, " ")?; - } else { - let struct_name = &self.names[&NameKey::Type(result.ty)].clone(); - write!(self.out, " -> {} ", struct_name)?; + write!(self.out, "{{")?; + writeln!(self.out)?; + + // Write the function body (statement list) + for sta in func.body.iter() { + // The indentation should always be 1 when writing the function body + self.write_stmt(&module, sta, &func_ctx, 1)?; } + + writeln!(self.out, "}}")?; } - write!(self.out, "{{")?; - writeln!(self.out)?; - - // Write the function body (statement list) - for sta in func.body.iter() { - // The indentation should always be 1 when writing the function body - self.write_stmt(&module, sta, &func_ctx, 1)?; - } - - writeln!(self.out, "}}")?; Ok(()) } @@ -221,11 +224,12 @@ impl Writer { ShaderStage::Fragment => write!(self.out, "stage(fragment)")?, ShaderStage::Compute => write!(self.out, "stage(compute)")?, }, + Attribute::Stride(stride) => write!(self.out, "stride({})", stride)?, Attribute::WorkGroupSize(size) => { write!( self.out, - "{}", - format!("workgroup_size({}, {}, {})", size[0], size[1], size[2]) + "workgroup_size({}, {}, {})", + size[0], size[1], size[2] )?; } Attribute::Binding(id) => write!(self.out, "binding({})", id)?, @@ -259,17 +263,19 @@ impl Writer { write!(self.out, "struct {} {{", name)?; writeln!(self.out)?; for (_, member) in members.iter().enumerate() { - // The indentation is only for readability - write!(self.out, "{}", INDENT)?; - if let Some(ref binding) = member.binding { - self.write_attributes(&[map_binding_to_attribute(binding)])?; - write!(self.out, " ")?; + if member.name.is_some() { + // The indentation is only for readability + write!(self.out, "{}", INDENT)?; + if let Some(ref binding) = member.binding { + self.write_attributes(&[map_binding_to_attribute(binding)])?; + write!(self.out, " ")?; + } + // Write struct member name and type + write!(self.out, "{}: ", member.name.as_ref().unwrap())?; + self.write_type(module, member.ty)?; + write!(self.out, ";")?; + writeln!(self.out)?; } - // Write struct member name and type - write!(self.out, "{}: ", member.name.as_ref().unwrap())?; - self.write_type(module, member.ty)?; - write!(self.out, ";")?; - writeln!(self.out)?; } write!(self.out, "}};")?; @@ -301,7 +307,7 @@ impl Writer { /// /// # Notes /// Adds no trailing or leading whitespace - fn write_value_type(&mut self, _module: &Module, inner: &TypeInner) -> BackendResult { + fn write_value_type(&mut self, module: &Module, inner: &TypeInner) -> BackendResult { match *inner { TypeInner::Vector { size, kind, .. } => write!( self.out, @@ -341,6 +347,43 @@ impl Writer { ); write!(self.out, "{}", ty_str)?; } + TypeInner::Scalar { kind, .. } => { + write!(self.out, "{}", scalar_kind_str(kind))?; + } + TypeInner::Array { base, size, stride } => { + // More info https://gpuweb.github.io/gpuweb/wgsl/#array-types + // array -- Constant array + // array -- Dynamic array + if stride > 0 { + self.write_attributes(&[Attribute::Stride(stride)])?; + write!(self.out, " ")?; + } + write!(self.out, "array<")?; + match size { + ArraySize::Constant(handle) => { + self.write_type(module, base)?; + write!(self.out, ",")?; + self.write_constant(&module.constants[handle], false)?; + } + ArraySize::Dynamic => { + self.write_type(module, base)?; + } + } + write!(self.out, ">")?; + } + TypeInner::Matrix { + columns, + rows, + width: _, + } => { + write!( + self.out, + //TODO: Can matrix be other than f32? + "mat{}x{}", + vector_size_str(columns), + vector_size_str(rows), + )?; + } _ => { return Err(Error::Unimplemented(format!( "write_value_type {:?}", @@ -372,10 +415,14 @@ impl Writer { write!(self.out, "{}", INDENT.repeat(indent))?; self.write_type(module, ty_handle)? } - TypeResolution::Value(ref _inner) => { + TypeResolution::Value(ref inner) => { //TODO: //write!(self.out, "{}", INDENT.repeat(indent))?; //self.write_value_type(module, inner)? + return Err(Error::Unimplemented(format!( + "Emit statement TypeResolution::Value {:?}", + inner + ))); } } } From 4f5b6c5270eb40270039a832b36f75e032b5e3fa Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sat, 24 Apr 2021 17:39:18 +0300 Subject: [PATCH 0757/2212] Share some functions between backends --- src/back/glsl/mod.rs | 25 +----------------- src/back/mod.rs | 40 +++++++++++++++++++++++++++++ src/back/msl/writer.rs | 56 +++++++++++------------------------------ src/back/wgsl/writer.rs | 46 +++++---------------------------- 4 files changed, 62 insertions(+), 105 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a26865c2c..a6e117772 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1836,30 +1836,7 @@ impl<'a, W: Write> Writer<'a, W> { if function.is_some() { write!(self.out, ",")? } else { - write!( - self.out, - " {} ", - match op { - BinaryOperator::Add => "+", - BinaryOperator::Subtract => "-", - BinaryOperator::Multiply => "*", - BinaryOperator::Divide => "/", - BinaryOperator::Modulo => "%", - BinaryOperator::Equal => "==", - BinaryOperator::NotEqual => "!=", - BinaryOperator::Less => "<", - BinaryOperator::LessEqual => "<=", - BinaryOperator::Greater => ">", - BinaryOperator::GreaterEqual => ">=", - BinaryOperator::And => "&", - BinaryOperator::ExclusiveOr => "^", - BinaryOperator::InclusiveOr => "|", - BinaryOperator::LogicalAnd => "&&", - BinaryOperator::LogicalOr => "||", - BinaryOperator::ShiftLeft => "<<", - BinaryOperator::ShiftRight => ">>", - } - )?; + write!(self.out, " {} ", super::binary_operation_str(op))?; } self.write_expr(right, ctx)?; diff --git a/src/back/mod.rs b/src/back/mod.rs index a478d971d..336833249 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -33,3 +33,43 @@ impl crate::Expression { } } } + +/// Helper function that returns the string corresponding to the [`BinaryOperator`](crate::BinaryOperator) +/// # Notes +/// Used by `glsl-out`, `msl-out`, `wgsl-out`. +#[allow(dead_code)] +fn binary_operation_str(op: crate::BinaryOperator) -> &'static str { + use crate::BinaryOperator as Bo; + match op { + Bo::Add => "+", + Bo::Subtract => "-", + Bo::Multiply => "*", + Bo::Divide => "/", + Bo::Modulo => "%", + Bo::Equal => "==", + Bo::NotEqual => "!=", + Bo::Less => "<", + Bo::LessEqual => "<=", + Bo::Greater => ">", + Bo::GreaterEqual => ">=", + Bo::And => "&", + Bo::ExclusiveOr => "^", + Bo::InclusiveOr => "|", + Bo::LogicalAnd => "&&", + Bo::LogicalOr => "||", + Bo::ShiftLeft => "<<", + Bo::ShiftRight => ">>", + } +} + +/// Helper function that returns the string corresponding to the [`VectorSize`](crate::VectorSize) +/// # Notes +/// Used by `msl-out`, `wgsl-out`. +#[allow(dead_code)] +fn vector_size_str(size: crate::VectorSize) -> &'static str { + match size { + crate::VectorSize::Bi => "2", + crate::VectorSize::Tri => "3", + crate::VectorSize::Quad => "4", + } +} diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 638ec4e8e..0f9ed3c2b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -4,6 +4,7 @@ use super::{ }; use crate::{ arena::{Arena, Handle}, + back::vector_size_str, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, GlobalUse, ModuleInfo}, FastHashMap, @@ -65,7 +66,7 @@ impl<'a> Display for TypeContext<'a> { "{}::{}{}", NAMESPACE, scalar_kind_string(kind), - vector_size_string(size), + vector_size_str(size), ) } crate::TypeInner::Matrix { columns, rows, .. } => { @@ -74,8 +75,8 @@ impl<'a> Display for TypeContext<'a> { "{}::{}{}x{}", NAMESPACE, scalar_kind_string(crate::ScalarKind::Float), - vector_size_string(columns), - vector_size_string(rows), + vector_size_str(columns), + vector_size_str(rows), ) } crate::TypeInner::Pointer { base, class } => { @@ -121,7 +122,7 @@ impl<'a> Display for TypeContext<'a> { class_name, NAMESPACE, scalar_kind_string(kind), - vector_size_string(size), + vector_size_str(size), ) } crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => unreachable!(), @@ -298,14 +299,6 @@ fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { } } -fn vector_size_string(size: crate::VectorSize) -> &'static str { - match size { - crate::VectorSize::Bi => "2", - crate::VectorSize::Tri => "3", - crate::VectorSize::Quad => "4", - } -} - const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; fn separate(need_separator: bool) -> &'static str { @@ -531,7 +524,7 @@ impl Writer { // coordinates in IR are int, but Metal expects uint let size_str = match *context.info[expr].ty.inner_with(&context.module.types) { crate::TypeInner::Scalar { .. } => "", - crate::TypeInner::Vector { size, .. } => vector_size_string(size), + crate::TypeInner::Vector { size, .. } => vector_size_str(size), _ => return Err(Error::Validation), }; write!(self.out, "{}::uint{}(", NAMESPACE, size_str)?; @@ -645,7 +638,7 @@ impl Writer { _ => return Err(Error::Validation), }; let scalar = scalar_kind_string(scalar_kind); - let size = vector_size_string(size); + let size = vector_size_str(size); write!(self.out, "{}{}(", scalar, size)?; self.put_expression(value, context, true)?; @@ -675,7 +668,7 @@ impl Writer { "{}::{}{}", NAMESPACE, scalar_kind_string(kind), - vector_size_string(size) + vector_size_str(size) )?; self.put_call_parameters(components.iter().cloned(), context)?; } @@ -686,8 +679,8 @@ impl Writer { "{}::{}{}x{}", NAMESPACE, scalar_kind_string(kind), - vector_size_string(columns), - vector_size_string(rows) + vector_size_str(columns), + vector_size_str(rows) )?; self.put_call_parameters(components.iter().cloned(), context)?; } @@ -896,26 +889,7 @@ impl Writer { self.put_expression(expr, context, false)?; } crate::Expression::Binary { op, left, right } => { - let op_str = match op { - crate::BinaryOperator::Add => "+", - crate::BinaryOperator::Subtract => "-", - crate::BinaryOperator::Multiply => "*", - crate::BinaryOperator::Divide => "/", - crate::BinaryOperator::Modulo => "%", - crate::BinaryOperator::Equal => "==", - crate::BinaryOperator::NotEqual => "!=", - crate::BinaryOperator::Less => "<", - crate::BinaryOperator::LessEqual => "<=", - crate::BinaryOperator::Greater => ">", - crate::BinaryOperator::GreaterEqual => ">=", - crate::BinaryOperator::And => "&", - crate::BinaryOperator::ExclusiveOr => "^", - crate::BinaryOperator::InclusiveOr => "|", - crate::BinaryOperator::LogicalAnd => "&&", - crate::BinaryOperator::LogicalOr => "||", - crate::BinaryOperator::ShiftLeft => "<<", - crate::BinaryOperator::ShiftRight => ">>", - }; + let op_str = crate::back::binary_operation_str(op); let kind = context .resolve_type(left) .scalar_kind() @@ -1084,7 +1058,7 @@ impl Writer { let scalar = scalar_kind_string(kind); let size = match *context.resolve_type(expr) { crate::TypeInner::Scalar { .. } => "", - crate::TypeInner::Vector { size, .. } => vector_size_string(size), + crate::TypeInner::Vector { size, .. } => vector_size_str(size), _ => return Err(Error::Validation), }; let op = if convert { "static_cast" } else { "as_type" }; @@ -1210,7 +1184,7 @@ impl Writer { "{}::{}{}", NAMESPACE, scalar_kind_string(kind), - vector_size_string(size) + vector_size_str(size) )?; } TypeResolution::Value(crate::TypeInner::Matrix { columns, rows, .. }) => { @@ -1219,8 +1193,8 @@ impl Writer { "{}::{}{}x{}", NAMESPACE, scalar_kind_string(crate::ScalarKind::Float), - vector_size_string(columns), - vector_size_string(rows), + vector_size_str(columns), + vector_size_str(rows), )?; } TypeResolution::Value(ref other) => { diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index f43e7f3ce..991e8f483 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1,19 +1,19 @@ // TODO: temp #![allow(dead_code)] use super::Error; +use crate::FastHashMap; use crate::{ - back::wgsl::keywords::RESERVED, + back::{binary_operation_str, vector_size_str, wgsl::keywords::RESERVED}, proc::{EntryPointIndex, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, - Arena, ArraySize, BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, - Handle, ImageClass, ImageDimension, Module, ScalarKind, ShaderStage, Statement, StorageFormat, - StructLevel, Type, TypeInner, + Arena, ArraySize, Binding, Constant, Expression, Function, GlobalVariable, Handle, ImageClass, + ImageDimension, Module, ScalarKind, ShaderStage, Statement, StorageFormat, StructLevel, Type, + TypeInner, }; use crate::{ proc::{NameKey, Namer}, StructMember, }; -use crate::{FastHashMap, VectorSize}; use std::fmt::Write; const INDENT: &str = " "; @@ -516,31 +516,7 @@ impl Writer { Expression::Binary { op, left, right } => { self.write_expr(module, left, func_ctx)?; - // TODO: glsl-out copy-paste - write!( - self.out, - " {} ", - match op { - BinaryOperator::Add => "+", - BinaryOperator::Subtract => "-", - BinaryOperator::Multiply => "*", - BinaryOperator::Divide => "/", - BinaryOperator::Modulo => "%", - BinaryOperator::Equal => "==", - BinaryOperator::NotEqual => "!=", - BinaryOperator::Less => "<", - BinaryOperator::LessEqual => "<=", - BinaryOperator::Greater => ">", - BinaryOperator::GreaterEqual => ">=", - BinaryOperator::And => "&", - BinaryOperator::ExclusiveOr => "^", - BinaryOperator::InclusiveOr => "|", - BinaryOperator::LogicalAnd => "&&", - BinaryOperator::LogicalOr => "||", - BinaryOperator::ShiftLeft => "<<", - BinaryOperator::ShiftRight => ">>", - } - )?; + write!(self.out, " {} ", binary_operation_str(op),)?; self.write_expr(module, right, func_ctx)?; } @@ -766,16 +742,6 @@ fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { } } -//TODO: copy-paste from msl-out -fn vector_size_str(size: VectorSize) -> &'static str { - match size { - VectorSize::Bi => "2", - VectorSize::Tri => "3", - VectorSize::Quad => "4", - } -} - -//TODO: copy-paste from msl-out fn image_dimension_str(dim: ImageDimension) -> &'static str { match dim { ImageDimension::D1 => "1d", From 0548437ab9558e9126a933e26d2e24479556a2b7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 02:21:46 -0400 Subject: [PATCH 0758/2212] [spv-out] don't cache pointer function arguments --- src/back/spv/writer.rs | 149 +++++++++++++++++++++++------------------ 1 file changed, 82 insertions(+), 67 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e8520e3e6..4676988ee 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1380,6 +1380,27 @@ impl Writer { Ok((id, variable)) } + fn is_intermediate( + &self, + expr_handle: Handle, + ir_function: &crate::Function, + ir_types: &Arena, + ) -> bool { + match ir_function.expressions[expr_handle] { + crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => true, + crate::Expression::FunctionArgument(index) => { + let arg = &ir_function.arguments[index as usize]; + match ir_types[arg.ty].inner { + crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { + true + } + _ => false, + } + } + _ => self.cached.ids[expr_handle.index()] == 0, + } + } + /// Cache an expression for a value. fn cache_expression_value( &mut self, @@ -1394,80 +1415,74 @@ impl Writer { self.get_expression_type_id(&ir_module.types, &fun_info[expr_handle].ty)?; let id = match ir_function.expressions[expr_handle] { + crate::Expression::Access { base, index: _ } + if self.is_intermediate(base, ir_function, &ir_module.types) => + { + 0 + } crate::Expression::Access { base, index } => { - let base_is_var = match ir_function.expressions[base] { - crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => { - true + let index_id = self.cached[index]; + let base_id = self.cached[base]; + match *fun_info[base].ty.inner_with(&ir_module.types) { + crate::TypeInner::Vector { .. } => { + let id = self.id_gen.next(); + block.body.push(Instruction::vector_extract_dynamic( + result_type_id, + id, + base_id, + index_id, + )); + id } - _ => self.cached.ids[base.index()] == 0, - }; - if base_is_var { - 0 - } else { - let index_id = self.cached[index]; - let base_id = self.cached[base]; - match *fun_info[base].ty.inner_with(&ir_module.types) { - crate::TypeInner::Vector { .. } => { - let id = self.id_gen.next(); - block.body.push(Instruction::vector_extract_dynamic( - result_type_id, - id, - base_id, - index_id, - )); - id - } - crate::TypeInner::Array { - base: ty_element, .. - } => { - let (id, variable) = self.promote_access_expression_to_variable( - &ir_module.types, - result_type_id, - base_id, - &fun_info[base].ty, - index_id, - ty_element, - block, - )?; - function.internal_variables.push(variable); - id - } - ref other => { - log::error!("Unable to access {:?}", other); - return Err(Error::FeatureNotImplemented("access for type")); - } + crate::TypeInner::Array { + base: ty_element, .. + } => { + let (id, variable) = self.promote_access_expression_to_variable( + &ir_module.types, + result_type_id, + base_id, + &fun_info[base].ty, + index_id, + ty_element, + block, + )?; + function.internal_variables.push(variable); + id + } + ref other => { + log::error!( + "Unable to access base {:?} of type {:?}", + ir_function.expressions[base], + other + ); + return Err(Error::FeatureNotImplemented("access for type")); } } } + crate::Expression::AccessIndex { base, index: _ } + if self.is_intermediate(base, ir_function, &ir_module.types) => + { + 0 + } crate::Expression::AccessIndex { base, index } => { - let base_is_var = match ir_function.expressions[base] { - crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => { - true + match *fun_info[base].ty.inner_with(&ir_module.types) { + crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } + | crate::TypeInner::Array { .. } + | crate::TypeInner::Struct { .. } => { + let id = self.id_gen.next(); + let base_id = self.cached[base]; + block.body.push(Instruction::composite_extract( + result_type_id, + id, + base_id, + &[index], + )); + id } - _ => self.cached.ids[base.index()] == 0, - }; - if base_is_var { - 0 - } else { - match *fun_info[base].ty.inner_with(&ir_module.types) { - crate::TypeInner::Vector { .. } - | crate::TypeInner::Matrix { .. } - | crate::TypeInner::Array { .. } - | crate::TypeInner::Struct { .. } => { - let id = self.id_gen.next(); - let base_id = self.cached[base]; - block.body.push(Instruction::composite_extract( - result_type_id, - id, - base_id, - &[index], - )); - id - } - ref other => { - log::error!("Unable to access index of {:?}", other); - return Err(Error::FeatureNotImplemented("access index for type")); - } + ref other => { + log::error!("Unable to access index of {:?}", other); + return Err(Error::FeatureNotImplemented("access index for type")); } } } From e8f6d553562c0258c0c47bf52c6c913c98041781 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 02:32:35 -0400 Subject: [PATCH 0759/2212] [spv-out] implement some of the relational functions --- src/back/spv/instructions.rs | 28 ++++++++++------------------ src/back/spv/writer.rs | 36 +++++++++++++++++++++++++++++------- 2 files changed, 39 insertions(+), 25 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 828b944a8..308d9b6d6 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -712,6 +712,14 @@ impl super::Instruction { instruction } + pub(super) fn relational(op: Op, result_type_id: Word, id: Word, expr_id: Word) -> Self { + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(expr_id); + instruction + } + // // Bit Instructions // @@ -724,24 +732,8 @@ impl super::Instruction { // Derivative Instructions // - pub(super) fn derive_x(result_type_id: Word, id: Word, expr_id: Word) -> Self { - let mut instruction = Self::new(Op::DPdx); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(expr_id); - instruction - } - - pub(super) fn derive_y(result_type_id: Word, id: Word, expr_id: Word) -> Self { - let mut instruction = Self::new(Op::DPdy); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(expr_id); - instruction - } - - pub(super) fn derive_width(result_type_id: Word, id: Word, expr_id: Word) -> Self { - let mut instruction = Self::new(Op::Fwidth); + pub(super) fn derivative(op: Op, result_type_id: Word, id: Word, expr_id: Word) -> Self { + let mut instruction = Self::new(op); instruction.set_type(result_type_id); instruction.set_result(id); instruction.add_operand(expr_id); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4676988ee..775582c86 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2132,15 +2132,18 @@ impl Writer { id } crate::Expression::Derivative { axis, expr } => { - use crate::DerivativeAxis; + use crate::DerivativeAxis as Da; let id = self.id_gen.next(); let expr_id = self.cached[expr]; - block.body.push(match axis { - DerivativeAxis::X => Instruction::derive_x(result_type_id, id, expr_id), - DerivativeAxis::Y => Instruction::derive_y(result_type_id, id, expr_id), - DerivativeAxis::Width => Instruction::derive_width(result_type_id, id, expr_id), - }); + let op = match axis { + Da::X => spirv::Op::DPdx, + Da::Y => spirv::Op::DPdy, + Da::Width => spirv::Op::Fwidth, + }; + block + .body + .push(Instruction::derivative(op, result_type_id, id, expr_id)); id } crate::Expression::ImageQuery { image, query } => { @@ -2283,7 +2286,26 @@ impl Writer { } } } - crate::Expression::Relational { .. } | crate::Expression::ArrayLength(_) => { + crate::Expression::Relational { fun, argument } => { + use crate::RelationalFunction as Rf; + let arg_id = self.cached[argument]; + let op = match fun { + Rf::All => spirv::Op::All, + Rf::Any => spirv::Op::Any, + Rf::IsNan => spirv::Op::IsNan, + Rf::IsInf => spirv::Op::IsInf, + //TODO: these require Kernel capability + Rf::IsFinite | Rf::IsNormal => { + return Err(Error::FeatureNotImplemented("is finite/normal")) + } + }; + let id = self.id_gen.next(); + block + .body + .push(Instruction::relational(op, result_type_id, id, arg_id)); + id + } + crate::Expression::ArrayLength(_) => { log::error!("unimplemented {:?}", ir_function.expressions[expr_handle]); return Err(Error::FeatureNotImplemented("expression")); } From 76685fba698f59fa9dedcf09fddcf453b2a10ef4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 11:37:29 -0400 Subject: [PATCH 0760/2212] [spv-out] issue DepthReplacing execution mode --- src/back/spv/helpers.rs | 18 ++++++++++++++++++ src/back/spv/writer.rs | 32 +++++++++++++++++++++++++++----- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index 35b138959..72be7f7b5 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -1,3 +1,4 @@ +use crate::{Arena, Handle}; use spirv::Word; pub(super) fn bytes_to_words(bytes: &[u8]) -> Vec { @@ -30,3 +31,20 @@ pub(super) fn map_storage_class(class: crate::StorageClass) -> spirv::StorageCla crate::StorageClass::PushConstant => spirv::StorageClass::PushConstant, } } + +pub(super) fn contains_builtin( + binding: Option<&crate::Binding>, + ty: Handle, + arena: &Arena, + built_in: crate::BuiltIn, +) -> bool { + if let Some(&crate::Binding::BuiltIn(bi)) = binding { + bi == built_in + } else if let crate::TypeInner::Struct { ref members, .. } = arena[ty].inner { + members + .iter() + .any(|member| contains_builtin(member.binding.as_ref(), member.ty, arena, built_in)) + } else { + false // unreachable + } +} diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 775582c86..61a15260c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,5 +1,6 @@ use super::{ - helpers::map_storage_class, Instruction, LogicalLayout, Options, PhysicalLayout, WriterFlags, + helpers::{contains_builtin, map_storage_class}, + Instruction, LogicalLayout, Options, PhysicalLayout, WriterFlags, }; use crate::{ arena::{Arena, Handle}, @@ -652,6 +653,17 @@ impl Writer { Ok(function_id) } + fn write_execution_mode( + &mut self, + function_id: Word, + mode: spirv::ExecutionMode, + ) -> Result<(), Error> { + self.check(mode.required_capabilities())?; + Instruction::execution_mode(function_id, mode, &[]) + .to_words(&mut self.logical_layout.execution_modes); + Ok(()) + } + // TODO Move to instructions module fn write_entry_point( &mut self, @@ -670,10 +682,20 @@ impl Writer { let exec_model = match entry_point.stage { crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, crate::ShaderStage::Fragment => { - let execution_mode = spirv::ExecutionMode::OriginUpperLeft; - self.check(execution_mode.required_capabilities())?; - Instruction::execution_mode(function_id, execution_mode, &[]) - .to_words(&mut self.logical_layout.execution_modes); + self.write_execution_mode(function_id, spirv::ExecutionMode::OriginUpperLeft)?; + if let Some(ref result) = entry_point.function.result { + if contains_builtin( + result.binding.as_ref(), + result.ty, + &ir_module.types, + crate::BuiltIn::FragDepth, + ) { + self.write_execution_mode( + function_id, + spirv::ExecutionMode::DepthReplacing, + )?; + } + } spirv::ExecutionModel::Fragment } crate::ShaderStage::Compute => { From 4ab9150411928382e5d053b9aff04e1f4cf74b91 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 12:08:53 -0400 Subject: [PATCH 0761/2212] [spv-out] fix image operands --- src/back/spv/writer.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 61a15260c..e8d788bed 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2031,6 +2031,8 @@ impl Writer { let id = self.id_gen.next(); let depth_id = depth_ref.map(|handle| self.cached[handle]); + let mut mask = spirv::ImageOperands::empty(); + mask.set(spirv::ImageOperands::CONST_OFFSET, offset.is_some()); let mut main_instruction = match level { crate::SampleLevel::Zero => { @@ -2052,7 +2054,9 @@ impl Writer { None, &ir_module.types, )?; - inst.add_operand(spirv::ImageOperands::LOD.bits()); + + mask |= spirv::ImageOperands::LOD; + inst.add_operand(mask.bits()); inst.add_operand(zero_id); inst @@ -2076,7 +2080,8 @@ impl Writer { ); let lod_id = self.cached[lod_handle]; - inst.add_operand(spirv::ImageOperands::LOD.bits()); + mask |= spirv::ImageOperands::LOD; + inst.add_operand(mask.bits()); inst.add_operand(lod_id); inst @@ -2092,7 +2097,7 @@ impl Writer { ); let bias_id = self.cached[bias_handle]; - inst.add_operand(spirv::ImageOperands::BIAS.bits()); + mask |= spirv::ImageOperands::BIAS; inst.add_operand(bias_id); inst @@ -2109,7 +2114,7 @@ impl Writer { let x_id = self.cached[x]; let y_id = self.cached[y]; - inst.add_operand(spirv::ImageOperands::GRAD.bits()); + mask |= spirv::ImageOperands::GRAD; inst.add_operand(x_id); inst.add_operand(y_id); @@ -2119,7 +2124,6 @@ impl Writer { if let Some(offset_const) = offset { let offset_id = self.constant_ids[offset_const.index()]; - main_instruction.add_operand(spirv::ImageOperands::CONST_OFFSET.bits()); main_instruction.add_operand(offset_id); } From e8c5242cc71c296f104bc74ba913281f19f9d060 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 12:24:26 -0400 Subject: [PATCH 0762/2212] Fix relational expression type width --- src/back/spv/writer.rs | 6 +++--- src/proc/typifier.rs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e8d788bed..ffd05a607 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -720,7 +720,7 @@ impl Writer { )) } - fn write_scalar(&self, id: Word, kind: crate::ScalarKind, width: crate::Bytes) -> Instruction { + fn make_scalar(&self, id: Word, kind: crate::ScalarKind, width: crate::Bytes) -> Instruction { let bits = (width * BITS_PER_BYTE) as u32; match kind { crate::ScalarKind::Sint => { @@ -746,7 +746,7 @@ impl Writer { kind, width, pointer_class: None, - } => self.write_scalar(id, kind, width), + } => self.make_scalar(id, kind, width), LocalType::Value { vector_size: Some(size), kind, @@ -849,7 +849,7 @@ impl Writer { use spirv::Decoration; let instruction = match ty.inner { - crate::TypeInner::Scalar { kind, width } => self.write_scalar(id, kind, width), + crate::TypeInner::Scalar { kind, width } => self.make_scalar(id, kind, width), crate::TypeInner::Vector { size, kind, width } => { let scalar_id = self.get_type_id( arena, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 7f9068797..86a85e2b0 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -461,7 +461,7 @@ impl<'a> ResolveContext<'a> { | crate::BinaryOperator::LogicalAnd | crate::BinaryOperator::LogicalOr => { let kind = crate::ScalarKind::Bool; - let width = 1; + let width = crate::BOOL_WIDTH; let inner = match *past(left).inner_with(types) { Ti::Scalar { .. } => Ti::Scalar { kind, width }, Ti::Vector { size, .. } => Ti::Vector { size, kind, width }, @@ -484,7 +484,7 @@ impl<'a> ResolveContext<'a> { crate::Expression::Derivative { axis: _, expr } => past(expr).clone(), crate::Expression::Relational { .. } => TypeResolution::Value(Ti::Scalar { kind: crate::ScalarKind::Bool, - width: 4, + width: crate::BOOL_WIDTH, }), crate::Expression::Math { fun, From f77abdb15691289dd517b2ace2a08c010f578d9d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 12:50:49 -0400 Subject: [PATCH 0763/2212] [spv-out] generate LogicalNot for bools --- src/back/spv/writer.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index ffd05a607..ed81608bb 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1575,7 +1575,10 @@ impl Writer { return Err(Error::FeatureNotImplemented("negation")); } }, - crate::UnaryOperator::Not => spirv::Op::Not, + crate::UnaryOperator::Not => match expr_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNot, + _ => spirv::Op::Not, + }, }; block From 3049e3a4acbd72e8f63e70dae4bff7f093b990be Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 12:58:22 -0400 Subject: [PATCH 0764/2212] [spv-out] allow capabilities to be derived --- src/back/spv/mod.rs | 8 +++----- src/back/spv/writer.rs | 30 ++++++++++++++++++++++-------- tests/snapshots.rs | 2 +- 3 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 55d8abf96..967925142 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -57,8 +57,8 @@ pub struct Options { pub lang_version: (u8, u8), /// Configuration flags for the writer. pub flags: WriterFlags, - /// Set of SPIR-V capabilities. - pub capabilities: crate::FastHashSet, + /// Set of SPIR-V allowed capabilities, if provided. + pub capabilities: Option>, } impl Default for Options { @@ -67,12 +67,10 @@ impl Default for Options { if cfg!(debug_assertions) { flags |= WriterFlags::DEBUG; } - let mut capabilities = crate::FastHashSet::default(); - capabilities.insert(Capability::Shader); Options { lang_version: (1, 0), flags, - capabilities, + capabilities: None, } } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index ed81608bb..42065ae02 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -284,6 +284,7 @@ pub struct Writer { logical_layout: LogicalLayout, id_gen: IdGenerator, capabilities: crate::FastHashSet, + strict_capabilities: bool, debugs: Vec, annotations: Vec, flags: WriterFlags, @@ -317,7 +318,15 @@ impl Writer { physical_layout: PhysicalLayout::new(raw_version), logical_layout: LogicalLayout::default(), id_gen, - capabilities: options.capabilities.clone(), + capabilities: match options.capabilities { + Some(ref caps) => caps.clone(), + None => { + let mut caps = crate::FastHashSet::default(); + caps.insert(spirv::Capability::Shader); + caps + } + }, + strict_capabilities: options.capabilities.is_some(), debugs: vec![], annotations: vec![], flags: options.flags, @@ -336,14 +345,19 @@ impl Writer { } fn check(&mut self, capabilities: &[spirv::Capability]) -> Result<(), Error> { - if capabilities.is_empty() - || capabilities - .iter() - .any(|cap| self.capabilities.contains(cap)) - { - Ok(()) + if self.strict_capabilities { + if capabilities.is_empty() + || capabilities + .iter() + .any(|cap| self.capabilities.contains(cap)) + { + Ok(()) + } else { + Err(Error::MissingCapabilities(capabilities.to_vec())) + } } else { - Err(Error::MissingCapabilities(capabilities.to_vec())) + self.capabilities.extend(capabilities); + Ok(()) } } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index baf855f14..1363d3ef6 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -127,7 +127,7 @@ fn check_output_spv( let options = spv::Options { lang_version: params.spv_version, flags, - capabilities: params.spv_capabilities.clone(), + capabilities: Some(params.spv_capabilities.clone()), }; let spv = spv::write_vec(module, info, &options).unwrap(); From 117d729ff8defd404945c021fc62cf4c8d4862d7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 18:20:04 -0400 Subject: [PATCH 0765/2212] [spv-in] allow non-strict check for capabilities --- bin/naga.rs | 1 + src/front/glsl/parser.rs | 7 ++++++- src/front/spv/mod.rs | 14 ++++++++++++-- tests/snapshots.rs | 1 + 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/bin/naga.rs b/bin/naga.rs index bd8100bf5..a0ab7b675 100644 --- a/bin/naga.rs +++ b/bin/naga.rs @@ -105,6 +105,7 @@ fn main() { "spv" => { let options = naga::front::spv::Options { adjust_coordinate_space: params.spv_adjust_coordinate_space, + strict_capabilities: false, flow_graph_dump_prefix: params.spv_flow_dump_prefix.map(std::path::PathBuf::from), }; let input = fs::read(input_path).unwrap(); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 1b260ea72..3f26863ab 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,4 +1,9 @@ -#![allow(clippy::panic, clippy::needless_lifetimes, clippy::upper_case_acronyms)] +#![allow( + unused_braces, + clippy::panic, + clippy::needless_lifetimes, + clippy::upper_case_acronyms +)] use pomelo::pomelo; pomelo! { //%verbose; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 90f397c4d..b33db1360 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -68,7 +68,10 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::UniformBufferArrayDynamicIndexing, spirv::Capability::StorageBufferArrayDynamicIndexing, ]; -pub const SUPPORTED_EXTENSIONS: &[&str] = &["SPV_KHR_vulkan_memory_model"]; +pub const SUPPORTED_EXTENSIONS: &[&str] = &[ + "SPV_KHR_storage_buffer_storage_class", + "SPV_KHR_vulkan_memory_model", +]; pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"]; #[derive(Copy, Clone)] @@ -347,6 +350,8 @@ pub struct Options { /// so by default we flip the Y coordinate of the `BuiltIn::Position`. /// This flag can be used to avoid this. pub adjust_coordinate_space: bool, + /// Only allow shaders with the known set of capabilities. + pub strict_capabilities: bool, pub flow_graph_dump_prefix: Option, } @@ -354,6 +359,7 @@ impl Default for Options { fn default() -> Self { Options { adjust_coordinate_space: true, + strict_capabilities: false, flow_graph_dump_prefix: None, } } @@ -2208,7 +2214,11 @@ impl> Parser { let cap = spirv::Capability::from_u32(capability).ok_or(Error::UnknownCapability(capability))?; if !SUPPORTED_CAPABILITIES.contains(&cap) { - return Err(Error::UnsupportedCapability(cap)); + if self.options.strict_capabilities { + return Err(Error::UnsupportedCapability(cap)); + } else { + log::warn!("Unknown capability {:?}", cap); + } } Ok(()) } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1363d3ef6..ed46091c0 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -263,6 +263,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { &fs::read(format!("{}/{}/{}.spv", root, DIR_IN, name)).expect("Couldn't find spv file"), &naga::front::spv::Options { adjust_coordinate_space, + strict_capabilities: false, flow_graph_dump_prefix: None, }, ) From dd1d9fe29096d9debcde5b6c0ecad27c01cc552b Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 26 Apr 2021 02:09:29 +0300 Subject: [PATCH 0766/2212] [wgsl-out] More improvements. Enable quad snapshot testing for wgsl backend --- src/back/wgsl/writer.rs | 119 +++++++++++++++++++++++++++++++++------- tests/out/access.wgsl | 6 ++ tests/out/quad.wgsl | 26 +++++++++ tests/snapshots.rs | 4 +- 4 files changed, 133 insertions(+), 22 deletions(-) create mode 100644 tests/out/access.wgsl create mode 100644 tests/out/quad.wgsl diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 991e8f483..f3cbeb80b 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -14,9 +14,11 @@ use crate::{ proc::{NameKey, Namer}, StructMember, }; +use bit_set::BitSet; use std::fmt::Write; const INDENT: &str = " "; +const BAKE_PREFIX: &str = "_e"; /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; @@ -60,6 +62,7 @@ pub struct Writer { out: W, names: FastHashMap, namer: Namer, + named_expressions: BitSet, } impl Writer { @@ -68,6 +71,7 @@ impl Writer { out, names: FastHashMap::default(), namer: Namer::default(), + named_expressions: BitSet::new(), } } @@ -196,6 +200,8 @@ impl Writer { writeln!(self.out, "}}")?; } + self.named_expressions.clear(); + Ok(()) } @@ -272,6 +278,16 @@ impl Writer { } // Write struct member name and type write!(self.out, "{}: ", member.name.as_ref().unwrap())?; + // Write stride attribute for array struct member + if let TypeInner::Array { + base: _, + size: _, + stride, + } = module.types[member.ty].inner + { + self.write_attributes(&[Attribute::Stride(stride)])?; + write!(self.out, " ")?; + } self.write_type(module, member.ty)?; write!(self.out, ";")?; writeln!(self.out)?; @@ -350,14 +366,10 @@ impl Writer { TypeInner::Scalar { kind, .. } => { write!(self.out, "{}", scalar_kind_str(kind))?; } - TypeInner::Array { base, size, stride } => { + TypeInner::Array { base, size, .. } => { // More info https://gpuweb.github.io/gpuweb/wgsl/#array-types // array -- Constant array // array -- Dynamic array - if stride > 0 { - self.write_attributes(&[Attribute::Stride(stride)])?; - write!(self.out, " ")?; - } write!(self.out, "array<")?; match size { ArraySize::Constant(handle) => { @@ -410,21 +422,11 @@ impl Writer { for handle in range.clone() { let min_ref_count = func_ctx.expressions[handle].bake_ref_count(); if min_ref_count <= func_ctx.info[handle].ref_count { - match func_ctx.info[handle].ty { - TypeResolution::Handle(ty_handle) => { - write!(self.out, "{}", INDENT.repeat(indent))?; - self.write_type(module, ty_handle)? - } - TypeResolution::Value(ref inner) => { - //TODO: - //write!(self.out, "{}", INDENT.repeat(indent))?; - //self.write_value_type(module, inner)? - return Err(Error::Unimplemented(format!( - "Emit statement TypeResolution::Value {:?}", - inner - ))); - } - } + write!(self.out, "{}", INDENT.repeat(indent))?; + self.start_baking_expr(handle, &func_ctx)?; + self.write_expr(module, handle, &func_ctx)?; + writeln!(self.out, ";")?; + self.named_expressions.insert(handle.index()); } } } @@ -480,6 +482,36 @@ impl Writer { Ok(()) } + fn start_baking_expr( + &mut self, + handle: Handle, + context: &FunctionCtx, + ) -> BackendResult { + // Write variable name + write!(self.out, "let {}{}: ", BAKE_PREFIX, handle.index())?; + let ty = &context.info[handle].ty; + // Write variable type + match *ty { + TypeResolution::Value(crate::TypeInner::Scalar { kind, .. }) => { + write!(self.out, "{}", scalar_kind_str(kind))?; + } + TypeResolution::Value(crate::TypeInner::Vector { size, kind, .. }) => { + write!( + self.out, + "vec{}<{}>", + vector_size_str(size), + scalar_kind_str(kind), + )?; + } + _ => { + return Err(Error::Unimplemented(format!("start_baking_expr {:?}", ty))); + } + } + + write!(self.out, " = ")?; + Ok(()) + } + /// Helper method to write expressions /// /// # Notes @@ -491,6 +523,12 @@ impl Writer { func_ctx: &FunctionCtx<'_>, ) -> BackendResult { let expression = &func_ctx.expressions[expr]; + + if self.named_expressions.contains(expr.index()) { + write!(self.out, "{}{}", BAKE_PREFIX, expr.index())?; + return Ok(()); + } + match *expression { Expression::Constant(constant) => { self.write_constant(&module.constants[constant], false)? @@ -593,6 +631,47 @@ impl Writer { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; } + Expression::As { + expr, + kind, + convert: _, //TODO: + } => { + let inner = func_ctx.info[expr].ty.inner_with(&module.types); + let op = match *inner { + TypeInner::Matrix { columns, rows, .. } => { + format!("mat{}x{}", vector_size_str(columns), vector_size_str(rows)) + } + TypeInner::Vector { size, .. } => format!("vec{}", vector_size_str(size)), + _ => { + return Err(Error::Unimplemented(format!( + "write_expr expression::as {:?}", + inner + ))); + } + }; + let scalar = scalar_kind_str(kind); + write!(self.out, "{}<{}>(", op, scalar)?; + self.write_expr(module, expr, func_ctx)?; + write!(self.out, ")")?; + } + Expression::Splat { size, value } => { + let inner = func_ctx.info[value].ty.inner_with(&module.types); + let scalar_kind = match *inner { + crate::TypeInner::Scalar { kind, .. } => kind, + _ => { + return Err(Error::Unimplemented(format!( + "write_expr expression::splat {:?}", + inner + ))); + } + }; + let scalar = scalar_kind_str(scalar_kind); + let size = vector_size_str(size); + + write!(self.out, "vec{}<{}>(", size, scalar)?; + self.write_expr(module, value, func_ctx)?; + write!(self.out, ")")?; + } _ => { return Err(Error::Unimplemented(format!("write_expr {:?}", expression))); } diff --git a/tests/out/access.wgsl b/tests/out/access.wgsl new file mode 100644 index 000000000..4b1cbc85e --- /dev/null +++ b/tests/out/access.wgsl @@ -0,0 +1,6 @@ +[[stage(vertex)]] +fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { + return vec4(vec4(array(1, 2, 3, 4, 5)[vi])); +} + + diff --git a/tests/out/quad.wgsl b/tests/out/quad.wgsl new file mode 100644 index 000000000..ba45b48c2 --- /dev/null +++ b/tests/out/quad.wgsl @@ -0,0 +1,26 @@ +let c_scale: f32 = 1.2; + +[[group(0), binding(0)]] var u_texture: texture_2d; + +[[group(0), binding(1)]] var u_sampler: sampler; + +struct VertexOutput { + [[location(0)]] uv: vec2; + [[builtin(position)]] position: vec4; +}; + +[[stage(vertex)]] +fn main([[location(0)]] pos: vec2, [[location(1)]] uv1: vec2) -> VertexOutput { + return VertexOutput(uv1, vec4(c_scale * pos, 0.0, 1.0)); +} + +[[stage(fragment)]] +fn main([[location(0)]] uv2: vec2) -> [[location(0)]] vec4 { + let _e4: vec4 = textureSample(u_texture, u_sampler, uv2); + if (_e4[3] == 0.0) { + discard; + } + return _e4[3] * _e4; +} + + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index ed46091c0..b82e14b71 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -226,7 +226,7 @@ fn convert_wgsl() { ), ( "quad", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::DOT, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::DOT | Targets::WGSL, ), ("boids", Targets::SPIRV | Targets::METAL), ("skybox", Targets::SPIRV | Targets::METAL | Targets::GLSL), @@ -242,7 +242,7 @@ fn convert_wgsl() { "interpolate", Targets::SPIRV | Targets::METAL | Targets::GLSL, ), - ("access", Targets::SPIRV | Targets::METAL), + ("access", Targets::SPIRV | Targets::METAL | Targets::WGSL), ]; for &(name, targets) in inputs.iter() { From bb29f8e1424b390c867c161b1821e35fe2644daa Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 26 Apr 2021 00:10:41 -0400 Subject: [PATCH 0767/2212] [spv-in] emit the cast expression for builtin signness --- src/front/spv/function.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 3ab6a9780..a8e97ba61 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -212,11 +212,16 @@ impl> super::Parser { } else { // The only case where the type is different is if we need to treat // unsigned integer as signed. - function.expressions.append(crate::Expression::As { + let old_len = function.expressions.len(); + let handle = function.expressions.append(crate::Expression::As { expr: arg_expr, kind: crate::ScalarKind::Sint, convert: true, - }) + }); + function.body.push(crate::Statement::Emit( + function.expressions.range_from(old_len), + )); + handle }; function.body.push(crate::Statement::Store { pointer: function From 452db33947d1b75da7a8093ace3740ceb3d1a733 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 26 Apr 2021 10:10:44 +0000 Subject: [PATCH 0768/2212] [glsl-out] Enable boids snapshot test --- tests/out/boids.Compute.glsl | 98 ++++++++++++++++++++++++++++++++++++ tests/snapshots.rs | 2 +- 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 tests/out/boids.Compute.glsl diff --git a/tests/out/boids.Compute.glsl b/tests/out/boids.Compute.glsl new file mode 100644 index 000000000..343e25bc3 --- /dev/null +++ b/tests/out/boids.Compute.glsl @@ -0,0 +1,98 @@ +#version 310 es + +precision highp float; + +layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in; + +struct Particle { + vec2 pos; + vec2 vel; +}; + +uniform SimParams_block_0 { + float deltaT; + float rule1Distance; + float rule2Distance; + float rule3Distance; + float rule1Scale; + float rule2Scale; + float rule3Scale; +} _group_0_binding_0; + +readonly buffer Particles_block_1 { + Particle particles[]; +} _group_0_binding_1; + +buffer Particles_block_2 { + Particle particles[]; +} _group_0_binding_2; + + +void main() { + uvec3 global_invocation_id = gl_GlobalInvocationID; + vec2 vPos; + vec2 vVel; + vec2 cMass; + vec2 cVel; + vec2 colVel; + int cMassCount = 0; + int cVelCount = 0; + vec2 pos1; + vec2 vel1; + uint i = 0u; + if((global_invocation_id[0] >= 1500u)) { + return; + } + vPos = _group_0_binding_1.particles[global_invocation_id[0]].pos; + vVel = _group_0_binding_1.particles[global_invocation_id[0]].vel; + cMass = vec2(0.0, 0.0); + cVel = vec2(0.0, 0.0); + colVel = vec2(0.0, 0.0); + while(true) { + if((i >= 1500u)) { + break; + } + if((i == global_invocation_id[0])) { + continue; + } + pos1 = _group_0_binding_1.particles[i].pos; + vel1 = _group_0_binding_1.particles[i].vel; + if((distance(pos1, vPos) < _group_0_binding_0.rule1Distance)) { + cMass = (cMass + pos1); + cMassCount = (cMassCount + 1); + } + if((distance(pos1, vPos) < _group_0_binding_0.rule2Distance)) { + colVel = (colVel - (pos1 - vPos)); + } + if((distance(pos1, vPos) < _group_0_binding_0.rule3Distance)) { + cVel = (cVel + vel1); + cVelCount = (cVelCount + 1); + } + i = (i + 1u); + } + if((cMassCount > 0)) { + cMass = ((cMass / vec2(float(cMassCount))) - vPos); + } + if((cVelCount > 0)) { + cVel = (cVel / vec2(float(cVelCount))); + } + vVel = (((vVel + (cMass * _group_0_binding_0.rule1Scale)) + (colVel * _group_0_binding_0.rule2Scale)) + (cVel * _group_0_binding_0.rule3Scale)); + vVel = (normalize(vVel) * clamp(length(vVel), 0.0, 0.1)); + vPos = (vPos + (vVel * _group_0_binding_0.deltaT)); + if((vPos[0] < -1.0)) { + vPos[0] = 1.0; + } + if((vPos[0] > 1.0)) { + vPos[0] = -1.0; + } + if((vPos[1] < -1.0)) { + vPos[1] = 1.0; + } + if((vPos[1] > 1.0)) { + vPos[1] = -1.0; + } + _group_0_binding_2.particles[global_invocation_id[0]].pos = vPos; + _group_0_binding_2.particles[global_invocation_id[0]].vel = vVel; + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b82e14b71..86d228959 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -228,7 +228,7 @@ fn convert_wgsl() { "quad", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::DOT | Targets::WGSL, ), - ("boids", Targets::SPIRV | Targets::METAL), + ("boids", Targets::SPIRV | Targets::METAL | Targets::GLSL), ("skybox", Targets::SPIRV | Targets::METAL | Targets::GLSL), ( "collatz", From 4a5ff9a0538510ff3c3efa171941bfb44fc1be9c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Apr 2021 18:51:20 -0400 Subject: [PATCH 0769/2212] Validate that used expressions are emitted --- src/valid/function.rs | 49 ++++++++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index cc67fa68e..4e7b6d569 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -3,6 +3,7 @@ use super::{ ExpressionError, FunctionInfo, ModuleInfo, TypeFlags, ValidationFlags, }; use crate::arena::{Arena, Handle}; +use bit_set::BitSet; #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] @@ -160,21 +161,39 @@ impl<'a> BlockContext<'a> { fn resolve_type_impl( &self, handle: Handle, + valid_expressions: &BitSet, ) -> Result<&crate::TypeInner, ExpressionError> { - if handle.index() < self.expressions.len() { - Ok(self.info[handle].ty.inner_with(self.types)) - } else { + if handle.index() >= self.expressions.len() { Err(ExpressionError::DoesntExist) + } else if !valid_expressions.contains(handle.index()) { + Err(ExpressionError::NotInScope) + } else { + Ok(self.info[handle].ty.inner_with(self.types)) } } fn resolve_type( &self, handle: Handle, + valid_expressions: &BitSet, ) -> Result<&crate::TypeInner, FunctionError> { - self.resolve_type_impl(handle) + self.resolve_type_impl(handle, valid_expressions) .map_err(|error| FunctionError::Expression { handle, error }) } + + fn resolve_pointer_type( + &self, + handle: Handle, + ) -> Result<&crate::TypeInner, FunctionError> { + if handle.index() >= self.expressions.len() { + Err(FunctionError::Expression { + handle, + error: ExpressionError::DoesntExist, + }) + } else { + Ok(self.info[handle].ty.inner_with(self.types)) + } + } } impl super::Validator { @@ -197,7 +216,7 @@ impl super::Validator { } for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { let ty = context - .resolve_type_impl(expr) + .resolve_type_impl(expr, &self.valid_expression_set) .map_err(|error| CallError::Argument { index, error })?; if ty != &context.types[arg.ty].inner { return Err(CallError::ArgumentType { @@ -252,7 +271,7 @@ impl super::Validator { ref accept, ref reject, } => { - match *context.resolve_type(condition)? { + match *context.resolve_type(condition, &self.valid_expression_set)? { Ti::Scalar { kind: crate::ScalarKind::Bool, width: _, @@ -267,7 +286,7 @@ impl super::Validator { ref cases, ref default, } => { - match *context.resolve_type(selector)? { + match *context.resolve_type(selector, &self.valid_expression_set)? { Ti::Scalar { kind: crate::ScalarKind::Sint, width: _, @@ -311,7 +330,9 @@ impl super::Validator { if !context.flags.contains(Flags::CAN_JUMP) { return Err(FunctionError::InvalidReturnSpot); } - let value_ty = value.map(|expr| context.resolve_type(expr)).transpose()?; + let value_ty = value + .map(|expr| context.resolve_type(expr, &self.valid_expression_set)) + .transpose()?; let expected_ty = context.return_type.map(|ty| &context.types[ty].inner); if value_ty != expected_ty { log::error!( @@ -329,7 +350,7 @@ impl super::Validator { S::Store { pointer, value } => { let mut current = pointer; loop { - let _ = context.resolve_type(current)?; + let _ = context.resolve_pointer_type(current)?; match *context.get_expression(current)? { crate::Expression::Access { base, .. } | crate::Expression::AccessIndex { base, .. } => current = base, @@ -340,14 +361,14 @@ impl super::Validator { } } - let value_ty = context.resolve_type(value)?; + let value_ty = context.resolve_type(value, &self.valid_expression_set)?; match *value_ty { Ti::Image { .. } | Ti::Sampler { .. } => { return Err(FunctionError::InvalidStoreValue(value)); } _ => {} } - let good = match *context.resolve_type(pointer)? { + let good = match *context.resolve_pointer_type(pointer)? { Ti::Pointer { base, class: _ } => *value_ty == context.types[base].inner, Ti::ValuePointer { size: Some(size), @@ -393,7 +414,7 @@ impl super::Validator { dim, } => { match context - .resolve_type(coordinate)? + .resolve_type(coordinate, &self.valid_expression_set)? .image_storage_coordinates() { Some(coord_dim) if coord_dim == dim => {} @@ -411,7 +432,7 @@ impl super::Validator { )); } if let Some(expr) = array_index { - match *context.resolve_type(expr)? { + match *context.resolve_type(expr, &self.valid_expression_set)? { Ti::Scalar { kind: crate::ScalarKind::Sint, width: _, @@ -443,7 +464,7 @@ impl super::Validator { } }; - if *context.resolve_type(value)? != value_ty { + if *context.resolve_type(value, &self.valid_expression_set)? != value_ty { return Err(FunctionError::InvalidStoreValue(value)); } } From 33003d8ea2a326072fc0187daaa1de98871d5406 Mon Sep 17 00:00:00 2001 From: Ashley Ruglys Date: Mon, 26 Apr 2021 20:08:02 +0200 Subject: [PATCH 0770/2212] Add `MathFunction::Refract` --- src/back/glsl/mod.rs | 1 + src/back/msl/writer.rs | 1 + src/back/spv/writer.rs | 1 + src/front/spv/mod.rs | 1 + src/lib.rs | 1 + src/proc/mod.rs | 1 + src/proc/typifier.rs | 3 ++- src/valid/expression.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 8 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a6e117772..31533615a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1941,6 +1941,7 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Normalize => "normalize", Mf::FaceForward => "faceforward", Mf::Reflect => "reflect", + Mf::Refract => "refract", // computational Mf::Sign => "sign", Mf::Fma => "fma", diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0f9ed3c2b..eeb4afe0c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1023,6 +1023,7 @@ impl Writer { Mf::Normalize => "normalize", Mf::FaceForward => "faceforward", Mf::Reflect => "reflect", + Mf::Refract => "refract", // computational Mf::Sign => "sign", Mf::Fma => "fma", diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 42065ae02..d20fe48bb 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1821,6 +1821,7 @@ impl Writer { Mf::Normalize => MathOp::Ext(spirv::GLOp::Normalize), Mf::FaceForward => MathOp::Ext(spirv::GLOp::FaceForward), Mf::Reflect => MathOp::Ext(spirv::GLOp::Reflect), + Mf::Refract => MathOp::Ext(spirv::GLOp::Refract), // exponent Mf::Exp => MathOp::Ext(spirv::GLOp::Exp), Mf::Exp2 => MathOp::Ext(spirv::GLOp::Exp2), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index b33db1360..ccea724d5 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1737,6 +1737,7 @@ impl> Parser { Glo::Normalize => Mf::Normalize, Glo::FaceForward => Mf::FaceForward, Glo::Reflect => Mf::Reflect, + Glo::Refract => Mf::Refract, _ => return Err(Error::UnsupportedExtInst(inst_id)), }; diff --git a/src/lib.rs b/src/lib.rs index ce0897ae3..270fbf974 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -630,6 +630,7 @@ pub enum MathFunction { Normalize, FaceForward, Reflect, + Refract, // computational Sign, Fma, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 27f5039f4..14eb33df9 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -150,6 +150,7 @@ impl super::MathFunction { Self::Normalize => 1, Self::FaceForward => 3, Self::Reflect => 2, + Self::Refract => 3, // computational Self::Sign => 1, Self::Fma => 3, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 86a85e2b0..4ba71949b 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -561,7 +561,8 @@ impl<'a> ResolveContext<'a> { }, Mf::Normalize | Mf::FaceForward | - Mf::Reflect => res_arg.clone(), + Mf::Reflect | + Mf::Refract => res_arg.clone(), // computational Mf::Sign | Mf::Fma | diff --git a/src/valid/expression.rs b/src/valid/expression.rs index dcde1d087..60bb16901 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -964,6 +964,47 @@ impl super::Validator { )); } } + Mf::Refract => { + let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty) { + (Some(ty1), Some(ty2)) => (ty1, ty2), + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + + match *arg_ty { + Ti::Vector { + kind: Sk::Float, .. + } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + + if arg1_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + + match (arg_ty, arg2_ty) { + ( + &Ti::Vector { + width: vector_width, + .. + }, + &Ti::Scalar { + width: scalar_width, + kind: Sk::Float, + }, + ) if vector_width == scalar_width => {} + _ => { + return Err(ExpressionError::InvalidArgumentType( + fun, + 2, + arg2.unwrap(), + )) + } + } + } Mf::Normalize => { if arg1_ty.is_some() | arg2_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); From 120fc22e9f9594c259b60ca50435a977f4ab152c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 27 Apr 2021 01:10:02 -0400 Subject: [PATCH 0771/2212] Support unary not in WGSL --- src/back/spv/writer.rs | 5 +++ src/front/wgsl/lexer.rs | 2 +- src/front/wgsl/mod.rs | 2 +- src/valid/expression.rs | 1 + tests/in/operators.wgsl | 8 +++-- tests/out/operators.msl | 16 ++++++--- tests/out/operators.spvasm | 72 +++++++++++++++++++++++--------------- 7 files changed, 69 insertions(+), 37 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d20fe48bb..c370b0aa6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2960,6 +2960,11 @@ impl Writer { for capability in self.capabilities.iter() { Instruction::capability(*capability).to_words(&mut self.logical_layout.capabilities); } + if ir_module.entry_points.is_empty() { + // SPIR-V doesn't like modules without entry points + Instruction::capability(spirv::Capability::Linkage) + .to_words(&mut self.logical_layout.capabilities); + } let addressing_model = spirv::AddressingModel::Logical; let memory_model = spirv::MemoryModel::GLSL450; diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index a0d1d6496..a6a5eead3 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -129,7 +129,7 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { } } '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), - '!' => { + '!' | '~' => { input = chars.as_str(); if chars.next() == Some('=') { (Token::LogicalOperation(cur), chars.as_str()) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 9d30fe1af..372c78fe0 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1328,7 +1328,7 @@ impl Parser { }; (true, ctx.expressions.append(expr)) } - Token::Operation('!') => { + Token::Operation('!') | Token::Operation('~') => { let expr = crate::Expression::Unary { op: crate::UnaryOperator::Not, expr: self.parse_singular_expression(lexer, ctx.reborrow())?, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 60bb16901..46d2099c6 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -549,6 +549,7 @@ impl super::Validator { match (op, inner.scalar_kind()) { (_, Some(Sk::Sint)) | (_, Some(Sk::Bool)) + //TODO: restrict Negate for bools? | (Uo::Negate, Some(Sk::Float)) | (Uo::Not, Some(Sk::Uint)) => {} other => { diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 7808e6e7c..3b7d1f33f 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -1,6 +1,10 @@ -[[stage(vertex)]] -fn splat() -> [[builtin(position)]] vec4 { +fn splat() -> vec4 { let a = (1.0 + vec2(2.0) - 3.0) / 4.0; let b = vec4(5) % 2; return a.xyxy + vec4(b); } + +fn unary() -> i32 { + let a = 1; + if (!true) { return a; } else { return ~a; }; +} diff --git a/tests/out/operators.msl b/tests/out/operators.msl index 4d3c3d9f3..9deefef7a 100644 --- a/tests/out/operators.msl +++ b/tests/out/operators.msl @@ -2,10 +2,16 @@ #include -struct splatOutput { - metal::float4 member [[position]]; -}; -vertex splatOutput splat( +metal::float4 splat( ) { - return splatOutput { (((float2(1.0) + float2(2.0)) - float2(3.0)) / float2(4.0)).xyxy + static_cast(int4(5) % int4(2)) }; + return (((float2(1.0) + float2(2.0)) - float2(3.0)) / float2(4.0)).xyxy + static_cast(int4(5) % int4(2)); +} + +int unary( +) { + if (!true) { + return 1; + } else { + return !1; + } } diff --git a/tests/out/operators.spvasm b/tests/out/operators.spvasm index cc7c22511..a6380e59c 100644 --- a/tests/out/operators.spvasm +++ b/tests/out/operators.spvasm @@ -1,12 +1,11 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 33 +; Bound: 44 OpCapability Shader +OpCapability Linkage %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %15 "splat" %13 -OpDecorate %13 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -16,29 +15,46 @@ OpDecorate %13 BuiltIn Position %9 = OpTypeInt 32 1 %8 = OpConstant %9 5 %10 = OpConstant %9 2 -%11 = OpTypeVector %4 4 -%14 = OpTypePointer Output %11 -%13 = OpVariable %14 Output -%16 = OpTypeFunction %2 -%18 = OpTypeVector %4 2 -%26 = OpTypeVector %9 4 -%15 = OpFunction %2 None %16 -%12 = OpLabel -OpBranch %17 -%17 = OpLabel -%19 = OpCompositeConstruct %18 %5 %5 -%20 = OpCompositeConstruct %18 %3 %3 -%21 = OpFAdd %18 %20 %19 -%22 = OpCompositeConstruct %18 %6 %6 -%23 = OpFSub %18 %21 %22 -%24 = OpCompositeConstruct %18 %7 %7 -%25 = OpFDiv %18 %23 %24 -%27 = OpCompositeConstruct %26 %8 %8 %8 %8 -%28 = OpCompositeConstruct %26 %10 %10 %10 %10 -%29 = OpSMod %26 %27 %28 -%30 = OpVectorShuffle %11 %25 %25 0 1 0 1 -%31 = OpConvertSToF %11 %29 -%32 = OpFAdd %11 %30 %31 -OpStore %13 %32 -OpReturn +%11 = OpConstant %9 1 +%13 = OpTypeBool +%12 = OpConstantTrue %13 +%14 = OpTypeVector %4 4 +%17 = OpTypeFunction %14 +%19 = OpTypeVector %4 2 +%27 = OpTypeVector %9 4 +%36 = OpTypeFunction %9 +%43 = OpConstantNull %9 +%16 = OpFunction %14 None %17 +%15 = OpLabel +OpBranch %18 +%18 = OpLabel +%20 = OpCompositeConstruct %19 %5 %5 +%21 = OpCompositeConstruct %19 %3 %3 +%22 = OpFAdd %19 %21 %20 +%23 = OpCompositeConstruct %19 %6 %6 +%24 = OpFSub %19 %22 %23 +%25 = OpCompositeConstruct %19 %7 %7 +%26 = OpFDiv %19 %24 %25 +%28 = OpCompositeConstruct %27 %8 %8 %8 %8 +%29 = OpCompositeConstruct %27 %10 %10 %10 %10 +%30 = OpSMod %27 %28 %29 +%31 = OpVectorShuffle %14 %26 %26 0 1 0 1 +%32 = OpConvertSToF %14 %30 +%33 = OpFAdd %14 %31 %32 +OpReturnValue %33 +OpFunctionEnd +%35 = OpFunction %9 None %36 +%34 = OpLabel +OpBranch %37 +%37 = OpLabel +%38 = OpLogicalNot %13 %12 +OpSelectionMerge %39 None +OpBranchConditional %38 %40 %41 +%40 = OpLabel +OpReturnValue %11 +%41 = OpLabel +%42 = OpNot %9 %11 +OpReturnValue %42 +%39 = OpLabel +OpReturnValue %43 OpFunctionEnd \ No newline at end of file From d9171dbc6121d30b1b59f664ee7b980539cd2400 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 27 Apr 2021 11:00:13 -0400 Subject: [PATCH 0772/2212] [wgsl-in] fix composition of a single element --- src/front/wgsl/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 372c78fe0..d2ac7a0b1 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1146,7 +1146,9 @@ impl Parser { last_component = self.parse_general_expression(lexer, ctx.reborrow())?; } - let expr = if components.is_empty() { + let expr = if components.is_empty() + && ty_resolution.inner_with(ctx.types).scalar_kind().is_some() + { // We can't use the `TypeInner` returned by this because // `resolve_type` borrows context mutably. // Use it to insert into the right maps, From d21dded649eeee1be209eb88896f90d73621ccdd Mon Sep 17 00:00:00 2001 From: Ashley Date: Wed, 28 Apr 2021 16:26:17 +0200 Subject: [PATCH 0773/2212] [msl-out] wrap arrays in structs so that they can be returned by functions (#764) * [msl-out] wrap arrays in structs so that they can be returned by functions * Fix clippy problems * use a raw array for output fields * Fix clippy problems * Apply suggestions * Remove put_initialization_component * Check if the array is a constant size * Don't use the pointer class --- src/back/msl/writer.rs | 110 +++++++++++++++++++++++----------------- tests/out/access.msl | 6 ++- tests/out/quad-vert.msl | 10 ++-- 3 files changed, 73 insertions(+), 53 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index eeb4afe0c..34e0a02c3 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -18,6 +18,7 @@ use std::{ const NAMESPACE: &str = "metal"; const INDENT: &str = " "; const BAKE_PREFIX: &str = "_e"; +const WRAPPED_ARRAY_FIELD: &str = "inner"; #[derive(Clone)] struct Level(usize); @@ -81,12 +82,9 @@ impl<'a> Display for TypeContext<'a> { } crate::TypeInner::Pointer { base, class } => { let sub = Self { - arena: self.arena, - names: self.names, handle: base, - usage: self.usage, - access: self.access, first_time: false, + ..*self }; let class_name = match class.get_name(self.usage) { Some(name) => name, @@ -125,7 +123,17 @@ impl<'a> Display for TypeContext<'a> { vector_size_str(size), ) } - crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => unreachable!(), + crate::TypeInner::Array { base, .. } => { + let sub = Self { + handle: base, + first_time: false, + ..*self + }; + // Array lengths go at the end of the type definition, + // so just print the element type here. + write!(out, "{}", sub) + } + crate::TypeInner::Struct { .. } => unreachable!(), crate::TypeInner::Image { dim, arrayed, @@ -533,39 +541,6 @@ impl Writer { Ok(()) } - fn put_initialization_component( - &mut self, - component: Handle, - context: &ExpressionContext, - ) -> Result<(), Error> { - // we can't initialize the array members just like other members, - // we have to unwrap them one level deeper... - let component_res = &context.info[component].ty; - if let crate::TypeInner::Array { - size: crate::ArraySize::Constant(const_handle), - .. - } = *component_res.inner_with(&context.module.types) - { - //HACK: we are forcefully duplicating the expression here, - // it would be nice to find a more C++ idiomatic solution for initializing array members - let size = context.module.constants[const_handle] - .to_array_length() - .unwrap(); - write!(self.out, "{{")?; - for j in 0..size { - if j != 0 { - write!(self.out, ",")?; - } - self.put_expression(component, context, false)?; - write!(self.out, "[{}]", j)?; - } - write!(self.out, "}}")?; - } else { - self.put_expression(component, context, true)?; - } - Ok(()) - } - fn put_expression( &mut self, expr_handle: Handle, @@ -587,7 +562,25 @@ impl Writer { log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { crate::Expression::Access { base, index } => { + let accessing_wrapped_array = + match *context.info[base].ty.inner_with(&context.module.types) { + crate::TypeInner::Array { .. } => true, + crate::TypeInner::Pointer { + base: pointer_base, .. + } => match context.module.types[pointer_base].inner { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(_), + .. + } => true, + _ => false, + }, + _ => false, + }; + self.put_expression(base, context, false)?; + if accessing_wrapped_array { + write!(self.out, ".{}", WRAPPED_ARRAY_FIELD)?; + } write!(self.out, "[")?; self.put_expression(index, context, true)?; write!(self.out, "]")?; @@ -690,7 +683,7 @@ impl Writer { if i != 0 { write!(self.out, ", ")?; } - self.put_initialization_component(component, context)?; + self.put_expression(component, context, true)?; } write!(self.out, "}}")?; } @@ -1121,7 +1114,9 @@ impl Writer { let comma = if is_first { "" } else { "," }; is_first = false; let name = &self.names[&NameKey::StructMember(result_ty, index as u32)]; - // logic similar to `put_initialization_component` + // HACK: we are forcefully deduplicating the expression here + // to convert from a wrapped struct to a raw array, e.g. + // `float gl_ClipDistance1 [[clip_distance]] [1];`. if let crate::TypeInner::Array { size: crate::ArraySize::Constant(const_handle), .. @@ -1135,7 +1130,11 @@ impl Writer { if j != 0 { write!(self.out, ",")?; } - write!(self.out, "{}.{}[{}]", tmp, name, j)?; + write!( + self.out, + "{}.{}.{}[{}]", + tmp, name, WRAPPED_ARRAY_FIELD, j + )?; } write!(self.out, "}}")?; } else { @@ -1345,9 +1344,9 @@ impl Writer { .unwrap(); write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?; self.put_expression(pointer, &context.expression, true)?; - write!(self.out, "[_i] = ")?; + write!(self.out, ".{}[_i] = ", WRAPPED_ARRAY_FIELD)?; self.put_expression(value, &context.expression, true)?; - writeln!(self.out, "[_i];")?; + writeln!(self.out, ".{}[_i];", WRAPPED_ARRAY_FIELD)?; } None => { write!(self.out, "{}", level)?; @@ -1468,7 +1467,7 @@ impl Writer { access: crate::StorageAccess::empty(), first_time: false, }; - write!(self.out, "typedef {} {}", base_name, name)?; + match size { crate::ArraySize::Constant(const_handle) => { let coco = ConstantContext { @@ -1477,10 +1476,17 @@ impl Writer { names: &self.names, first_time: false, }; - writeln!(self.out, "[{}];", coco)?; + + writeln!(self.out, "struct {} {{", name)?; + writeln!( + self.out, + "{}{} {}[{}];", + INDENT, base_name, WRAPPED_ARRAY_FIELD, coco + )?; + writeln!(self.out, "}};")?; } crate::ArraySize::Dynamic => { - writeln!(self.out, "[1];")?; + writeln!(self.out, "typedef {} {}[1];", base_name, name)?; } } } @@ -1942,7 +1948,7 @@ impl Writer { names: &self.names, usage: GlobalUse::empty(), access: crate::StorageAccess::empty(), - first_time: false, + first_time: true, }; let binding = binding.ok_or(Error::Validation)?; if !pipeline_options.allow_point_size @@ -1950,9 +1956,19 @@ impl Writer { { continue; } + let array_len = match module.types[ty].inner { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(handle), + .. + } => module.constants[handle].to_array_length(), + _ => None, + }; let resolved = options.resolve_local_binding(binding, out_mode)?; write!(self.out, "{}{} {}", INDENT, ty_name, name)?; resolved.try_fmt_decorated(&mut self.out, "")?; + if let Some(array_len) = array_len { + write!(self.out, " [{}]", array_len)?; + } writeln!(self.out, ";")?; } writeln!(self.out, "}};")?; diff --git a/tests/out/access.msl b/tests/out/access.msl index 2c3da3e90..36ed56482 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -1,7 +1,9 @@ #include #include -typedef int type3[5]; +struct type3 { + int inner[5]; +}; struct fooInput { }; @@ -11,5 +13,5 @@ struct fooOutput { vertex fooOutput foo( metal::uint vi [[vertex_id]] ) { - return fooOutput { static_cast(int4(type3 {1, 2, 3, 4, 5}[vi])) }; + return fooOutput { static_cast(int4(type3 {1, 2, 3, 4, 5}.inner[vi])) }; } diff --git a/tests/out/quad-vert.msl b/tests/out/quad-vert.msl index 9e0ff87e4..584a9a748 100644 --- a/tests/out/quad-vert.msl +++ b/tests/out/quad-vert.msl @@ -1,7 +1,9 @@ #include #include -typedef float type6[1u]; +struct type6 { + float inner[1u]; +}; struct gl_PerVertex { metal::float4 gl_Position; float gl_PointSize; @@ -35,7 +37,7 @@ struct main2Output { metal::float2 member [[user(loc0), center_perspective]]; metal::float4 gl_Position1 [[position]]; float gl_PointSize1 [[point_size]]; - type6 gl_ClipDistance1 [[clip_distance]]; + float gl_ClipDistance1 [[clip_distance]] [1]; }; vertex main2Output main2( main2Input varyings [[stage_in]] @@ -49,6 +51,6 @@ vertex main2Output main2( a_uv = a_uv1; a_pos = a_pos1; main1(v_uv, a_uv, _, a_pos); - const auto _tmp = type10 {v_uv, _.gl_Position, _.gl_PointSize, {_.gl_ClipDistance[0]}}; - return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1[0]} }; + const auto _tmp = type10 {v_uv, _.gl_Position, _.gl_PointSize, _.gl_ClipDistance}; + return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1.inner[0]} }; } From fd561da44cb3fdbe770dc2350cc7118a48a5dc3c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 28 Apr 2021 20:37:42 -0400 Subject: [PATCH 0774/2212] [msl] derive access qualifier based on the global variable flags (#798) --- src/back/msl/writer.rs | 27 ++++++--------------------- 1 file changed, 6 insertions(+), 21 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 34e0a02c3..bfccf1dcd 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -37,7 +37,6 @@ struct TypeContext<'a> { handle: Handle, arena: &'a Arena, names: &'a FastHashMap, - usage: GlobalUse, access: crate::StorageAccess, first_time: bool, } @@ -86,7 +85,7 @@ impl<'a> Display for TypeContext<'a> { first_time: false, ..*self }; - let class_name = match class.get_name(self.usage) { + let class_name = match class.get_name(self.access) { Some(name) => name, None => return Ok(()), }; @@ -98,7 +97,7 @@ impl<'a> Display for TypeContext<'a> { width: _, class, } => { - let class_name = match class.get_name(self.usage) { + let class_name = match class.get_name(self.access) { Some(name) => name, None => return Ok(()), }; @@ -110,7 +109,7 @@ impl<'a> Display for TypeContext<'a> { width: _, class, } => { - let class_name = match class.get_name(self.usage) { + let class_name = match class.get_name(self.access) { Some(name) => name, None => return Ok(()), }; @@ -209,12 +208,11 @@ impl<'a> TypedGlobalVariable<'a> { handle: var.ty, arena: &self.module.types, names: self.names, - usage: self.usage, access: var.storage_access, first_time: false, }; - let (space, access, reference) = match var.class.get_name(self.usage) { + let (space, access, reference) = match var.class.get_name(var.storage_access) { Some(space) if self.reference => { let access = match var.class { crate::StorageClass::Private | crate::StorageClass::WorkGroup @@ -359,12 +357,12 @@ impl crate::StorageClass { } } - fn get_name(&self, global_use: GlobalUse) -> Option<&'static str> { + fn get_name(&self, access: crate::StorageAccess) -> Option<&'static str> { match *self { Self::Handle => None, Self::Uniform | Self::PushConstant => Some("constant"), //TODO: should still be "constant" for read-only buffers - Self::Storage => Some(if global_use.contains(GlobalUse::WRITE) { + Self::Storage => Some(if access.contains(crate::StorageAccess::STORE) { "device" } else { "constant" @@ -1169,7 +1167,6 @@ impl Writer { handle: ty_handle, arena: &context.module.types, names: &self.names, - usage: GlobalUse::all(), access: crate::StorageAccess::empty(), first_time: false, }; @@ -1452,7 +1449,6 @@ impl Writer { continue; } let name = &self.names[&NameKey::Type(handle)]; - let global_use = GlobalUse::all(); //TODO match ty.inner { crate::TypeInner::Array { base, @@ -1463,7 +1459,6 @@ impl Writer { handle: base, arena: &module.types, names: &self.names, - usage: global_use, access: crate::StorageAccess::empty(), first_time: false, }; @@ -1523,7 +1518,6 @@ impl Writer { handle: member.ty, arena: &module.types, names: &self.names, - usage: global_use, access: crate::StorageAccess::empty(), first_time: false, }; @@ -1548,7 +1542,6 @@ impl Writer { handle, arena: &module.types, names: &self.names, - usage: global_use, access: crate::StorageAccess::empty(), first_time: true, }; @@ -1608,7 +1601,6 @@ impl Writer { handle: ty, arena: &module.types, names: &self.names, - usage: GlobalUse::empty(), access: crate::StorageAccess::empty(), first_time: false, }; @@ -1734,7 +1726,6 @@ impl Writer { handle: result.ty, arena: &module.types, names: &self.names, - usage: GlobalUse::empty(), access: crate::StorageAccess::empty(), first_time: false, }; @@ -1752,7 +1743,6 @@ impl Writer { handle: arg.ty, arena: &module.types, names: &self.names, - usage: GlobalUse::empty(), access: crate::StorageAccess::empty(), first_time: false, }; @@ -1784,7 +1774,6 @@ impl Writer { handle: local.ty, arena: &module.types, names: &self.names, - usage: GlobalUse::empty(), access: crate::StorageAccess::empty(), first_time: false, }; @@ -1907,7 +1896,6 @@ impl Writer { handle: ty, arena: &module.types, names: &self.names, - usage: GlobalUse::empty(), access: crate::StorageAccess::empty(), first_time: false, }; @@ -1946,7 +1934,6 @@ impl Writer { handle: ty, arena: &module.types, names: &self.names, - usage: GlobalUse::empty(), access: crate::StorageAccess::empty(), first_time: true, }; @@ -1997,7 +1984,6 @@ impl Writer { handle: ty, arena: &module.types, names: &self.names, - usage: GlobalUse::empty(), access: crate::StorageAccess::empty(), first_time: false, }; @@ -2158,7 +2144,6 @@ impl Writer { handle: local.ty, arena: &module.types, names: &self.names, - usage: GlobalUse::empty(), access: crate::StorageAccess::empty(), first_time: false, }; From 93e57ffcf26160c045dd2ee3ec5d871b0a892c31 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 29 Apr 2021 00:52:43 -0400 Subject: [PATCH 0775/2212] Another CHANGELOG update for v0.4 (#796) --- CHANGELOG.md | 14 +++++++++----- Cargo.toml | 4 ++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c23cb5aae..112921fae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Change Log -## v0.4 (TBD) +## v0.4 (2021-04-29) - development release for wgpu-0.8 - API: - expressions are explicitly emitted with `Statement::Emit` @@ -13,18 +13,22 @@ - new `Statement::ImageStore` - all function calls are `Statement::Call` - `GlobalUse` is moved out into processing - - field layout is controlled by `size` and `alignment` overrides, based on a default layout - `Header` is removed - entry points are an array instead of a map + - new `Swizzle` and `Splat` expressions + - interpolation qualifiers are extended and required + - struct member layout is based on the byte offsets - Infrastructure: - control flow uniformity analysis - texture-sampler combination gathering - `CallGraph` processor is moved out into `glsl` backend - - `Interface` is removed - - statement tree and constants are validated + - `Interface` is removed, instead the analysis produces `ModuleInfo` with all the derived info + - validation of statement tree, expressions, and constants - code linting is more strict for matches - new GraphViz `dot` backend for pretty visualization of the IR - - `convert` is default a binary target, published with the crate + - Metal support for inlined samplers + - `convert` example is transformed into the default binary target named `naga` + - lots of frontend and backend fixes ### v0.3.2 (2021-02-15) - fix logical expression types diff --git a/Cargo.toml b/Cargo.toml index b3f3e5dcc..cbe909dcb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.3.1" +version = "0.4.0" authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" @@ -24,7 +24,7 @@ pomelo = { version = "0.1.4", optional = true } thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } -pp-rs = { git = "https://github.com/Kangz/glslpp-rs", rev = "4f2f72a", optional = true } +pp-rs = { version = "0.1", optional = true } #env_logger = "0.8" # uncomment temporarily for developing with the binary target [features] From 881c8a7abc9bc712f140f224a4ef89b759ce96a2 Mon Sep 17 00:00:00 2001 From: Ashley Date: Thu, 29 Apr 2021 16:19:30 +0200 Subject: [PATCH 0776/2212] [spv-in] Impl `GLOp::Radians` and `GLOp::Degrees` (#797) * Implement GLOp::Radians and GLOp::Degrees * Simplify and inline * Change comment * Generate constant on demand * Fix 180/pi/180 --- src/front/spv/function.rs | 2 +- src/front/spv/mod.rs | 191 +++++++++++++++++++++++--------------- 2 files changed, 115 insertions(+), 78 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index a8e97ba61..c3fae7196 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -149,8 +149,8 @@ impl> super::Parser { fun_id, &mut fun.expressions, &mut fun.local_variables, + &mut module.constants, &module.types, - &module.constants, &module.global_variables, )?; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index ccea724d5..1e4384a83 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -772,8 +772,8 @@ impl> Parser { function_id: spirv::Word, expressions: &mut Arena, local_arena: &mut Arena, + const_arena: &mut Arena, type_arena: &Arena, - const_arena: &Arena, global_arena: &Arena, ) -> Result { let mut block = Vec::new(); @@ -1695,84 +1695,121 @@ impl> Parser { } let inst_id = self.next()?; let gl_op = Glo::from_u32(inst_id).ok_or(Error::UnsupportedExtInst(inst_id))?; - let fun = match gl_op { - Glo::Round => Mf::Round, - Glo::Trunc => Mf::Trunc, - Glo::FAbs | Glo::SAbs => Mf::Abs, - Glo::FSign | Glo::SSign => Mf::Sign, - Glo::Floor => Mf::Floor, - Glo::Ceil => Mf::Ceil, - Glo::Fract => Mf::Fract, - Glo::Sin => Mf::Sin, - Glo::Cos => Mf::Cos, - Glo::Tan => Mf::Tan, - Glo::Asin => Mf::Asin, - Glo::Acos => Mf::Acos, - Glo::Atan => Mf::Atan, - Glo::Sinh => Mf::Sinh, - Glo::Cosh => Mf::Cosh, - Glo::Tanh => Mf::Tanh, - Glo::Atan2 => Mf::Atan2, - Glo::Pow => Mf::Pow, - Glo::Exp => Mf::Exp, - Glo::Log => Mf::Log, - Glo::Exp2 => Mf::Exp2, - Glo::Log2 => Mf::Log2, - Glo::Sqrt => Mf::Sqrt, - Glo::InverseSqrt => Mf::InverseSqrt, - Glo::Determinant => Mf::Determinant, - Glo::Modf => Mf::Modf, - Glo::FMin | Glo::UMin | Glo::SMin | Glo::NMin => Mf::Min, - Glo::FMax | Glo::UMax | Glo::SMax | Glo::NMax => Mf::Max, - Glo::FClamp | Glo::UClamp | Glo::SClamp | Glo::NClamp => Mf::Clamp, - Glo::FMix => Mf::Mix, - Glo::Step => Mf::Step, - Glo::SmoothStep => Mf::SmoothStep, - Glo::Fma => Mf::Fma, - Glo::Frexp => Mf::Frexp, //TODO: FrexpStruct? - Glo::Ldexp => Mf::Ldexp, - Glo::Length => Mf::Length, - Glo::Distance => Mf::Distance, - Glo::Cross => Mf::Cross, - Glo::Normalize => Mf::Normalize, - Glo::FaceForward => Mf::FaceForward, - Glo::Reflect => Mf::Reflect, - Glo::Refract => Mf::Refract, - _ => return Err(Error::UnsupportedExtInst(inst_id)), - }; - let arg_count = fun.argument_count(); - inst.expect(base_wc + arg_count as u16)?; - let arg = { - let arg_id = self.next()?; - self.lookup_expression.lookup(arg_id)?.handle - }; - let arg1 = if arg_count > 1 { - let arg_id = self.next()?; - Some(self.lookup_expression.lookup(arg_id)?.handle) - } else { - None - }; - let arg2 = if arg_count > 2 { - let arg_id = self.next()?; - Some(self.lookup_expression.lookup(arg_id)?.handle) - } else { - None - }; + if gl_op == Glo::Radians || gl_op == Glo::Degrees { + inst.expect(base_wc + 1)?; + let arg = { + let arg_id = self.next()?; + self.lookup_expression.lookup(arg_id)?.handle + }; - let expr = crate::Expression::Math { - fun, - arg, - arg1, - arg2, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: expressions.append(expr), - type_id: result_type_id, - }, - ); + let constant_handle = const_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Float(match gl_op { + Glo::Radians => std::f64::consts::PI / 180.0, + Glo::Degrees => 180.0 / std::f64::consts::PI, + _ => unreachable!(), + }), + }, + }); + + let expr_handle = + expressions.append(crate::Expression::Constant(constant_handle)); + + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(crate::Expression::Binary { + op: crate::BinaryOperator::Multiply, + left: arg, + right: expr_handle, + }), + type_id: result_type_id, + }, + ); + } else { + let fun = match gl_op { + Glo::Round => Mf::Round, + Glo::Trunc => Mf::Trunc, + Glo::FAbs | Glo::SAbs => Mf::Abs, + Glo::FSign | Glo::SSign => Mf::Sign, + Glo::Floor => Mf::Floor, + Glo::Ceil => Mf::Ceil, + Glo::Fract => Mf::Fract, + Glo::Sin => Mf::Sin, + Glo::Cos => Mf::Cos, + Glo::Tan => Mf::Tan, + Glo::Asin => Mf::Asin, + Glo::Acos => Mf::Acos, + Glo::Atan => Mf::Atan, + Glo::Sinh => Mf::Sinh, + Glo::Cosh => Mf::Cosh, + Glo::Tanh => Mf::Tanh, + Glo::Atan2 => Mf::Atan2, + Glo::Pow => Mf::Pow, + Glo::Exp => Mf::Exp, + Glo::Log => Mf::Log, + Glo::Exp2 => Mf::Exp2, + Glo::Log2 => Mf::Log2, + Glo::Sqrt => Mf::Sqrt, + Glo::InverseSqrt => Mf::InverseSqrt, + Glo::Determinant => Mf::Determinant, + Glo::Modf => Mf::Modf, + Glo::FMin | Glo::UMin | Glo::SMin | Glo::NMin => Mf::Min, + Glo::FMax | Glo::UMax | Glo::SMax | Glo::NMax => Mf::Max, + Glo::FClamp | Glo::UClamp | Glo::SClamp | Glo::NClamp => Mf::Clamp, + Glo::FMix => Mf::Mix, + Glo::Step => Mf::Step, + Glo::SmoothStep => Mf::SmoothStep, + Glo::Fma => Mf::Fma, + Glo::Frexp => Mf::Frexp, //TODO: FrexpStruct? + Glo::Ldexp => Mf::Ldexp, + Glo::Length => Mf::Length, + Glo::Distance => Mf::Distance, + Glo::Cross => Mf::Cross, + Glo::Normalize => Mf::Normalize, + Glo::FaceForward => Mf::FaceForward, + Glo::Reflect => Mf::Reflect, + Glo::Refract => Mf::Refract, + _ => return Err(Error::UnsupportedExtInst(inst_id)), + }; + + let arg_count = fun.argument_count(); + inst.expect(base_wc + arg_count as u16)?; + let arg = { + let arg_id = self.next()?; + self.lookup_expression.lookup(arg_id)?.handle + }; + let arg1 = if arg_count > 1 { + let arg_id = self.next()?; + Some(self.lookup_expression.lookup(arg_id)?.handle) + } else { + None + }; + let arg2 = if arg_count > 2 { + let arg_id = self.next()?; + Some(self.lookup_expression.lookup(arg_id)?.handle) + } else { + None + }; + + let expr = crate::Expression::Math { + fun, + arg, + arg1, + arg2, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } } // Relational and Logical Instructions Op::LogicalNot => { From 37a6ff7bfe0de83f537278440b973830e4f4b755 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Thu, 29 Apr 2021 19:45:49 -0400 Subject: [PATCH 0777/2212] Add several additional ops to the spirv frontend. (#803) * Add support for int8, int16, and int64 as well as null constant structs * Add support for OpArrayLength to the spirv frontend * Add hacky OpCopyMemory support to spirv frontend * Add OpInBoundsAccessChain to spirv frontend * Add OpLogical(Not)Equal to spirv frontend * Fix several of the issues raised in the pr * Fix the Op::ArrayLength match * Validate accessing structs through pointers * Remove extraneous type check --- src/front/spv/convert.rs | 8 ++- src/front/spv/mod.rs | 142 ++++++++++++++++++++++++++++++++------- src/lib.rs | 4 ++ src/valid/expression.rs | 48 ++++++++----- 4 files changed, 156 insertions(+), 46 deletions(-) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 76c234e6f..c0f6f3917 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -14,8 +14,12 @@ pub(super) fn map_binary_operator(word: spirv::Op) -> Result Ok(BinaryOperator::Divide), Op::UMod | Op::SMod | Op::FMod => Ok(BinaryOperator::Modulo), // Relational and Logical Instructions - Op::IEqual | Op::FOrdEqual | Op::FUnordEqual => Ok(BinaryOperator::Equal), - Op::INotEqual | Op::FOrdNotEqual | Op::FUnordNotEqual => Ok(BinaryOperator::NotEqual), + Op::IEqual | Op::FOrdEqual | Op::FUnordEqual | Op::LogicalEqual => { + Ok(BinaryOperator::Equal) + } + Op::INotEqual | Op::FOrdNotEqual | Op::FUnordNotEqual | Op::LogicalNotEqual => { + Ok(BinaryOperator::NotEqual) + } Op::ULessThan | Op::SLessThan | Op::FOrdLessThan | Op::FUnordLessThan => { Ok(BinaryOperator::Less) } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 1e4384a83..868b2f45d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -64,6 +64,9 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::StorageImageExtendedFormats, spirv::Capability::Sampled1D, spirv::Capability::SampledCubeArray, + spirv::Capability::Int8, + spirv::Capability::Int16, + spirv::Capability::Int64, // tricky ones spirv::Capability::UniformBufferArrayDynamicIndexing, spirv::Capability::StorageBufferArrayDynamicIndexing, @@ -882,7 +885,7 @@ impl> Parser { }, ); } - Op::AccessChain => { + Op::AccessChain | Op::InBoundsAccessChain => { struct AccessExpression { base_handle: Handle, type_id: spirv::Word, @@ -1617,7 +1620,9 @@ impl> Parser { | Op::ConvertSToF | Op::ConvertUToF | Op::ConvertFToU - | Op::ConvertFToS => { + | Op::ConvertFToS + | Op::UConvert + | Op::SConvert => { inst.expect_at_least(4)?; let result_type_id = self.next()?; let result_id = self.next()?; @@ -1845,7 +1850,8 @@ impl> Parser { | Op::FOrdLessThanEqual | Op::FUnordLessThanEqual | Op::FOrdGreaterThanEqual - | Op::FUnordGreaterThanEqual => { + | Op::FUnordGreaterThanEqual + | Op::LogicalNotEqual => { inst.expect(5)?; let operator = map_binary_operator(inst.op)?; self.parse_expr_binary_op(expressions, operator)?; @@ -1984,6 +1990,62 @@ impl> Parser { Op::Fwidth | Op::FwidthFine | Op::FwidthCoarse => { self.parse_expr_derivative(expressions, crate::DerivativeAxis::Width)?; } + Op::ArrayLength => { + inst.expect(5)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let structure_id = self.next()?; + let member_index = self.next()?; + + // We're assuming that the validation pass, if it's run, will catch if the + // wrong types or parameters are supplied here. + + let structure_ptr = self.lookup_expression.lookup(structure_id)?; + + let member_ptr = expressions.append(crate::Expression::AccessIndex { + base: structure_ptr.handle, + index: member_index, + }); + + let length = expressions.append(crate::Expression::ArrayLength(member_ptr)); + + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: length, + type_id: result_type_id, + }, + ); + } + Op::CopyMemory => { + inst.expect_at_least(3)?; + let target_id = self.next()?; + let source_id = self.next()?; + let _memory_access = if inst.wc != 3 { + inst.expect(4)?; + spirv::MemoryAccess::from_bits(self.next()?) + .ok_or(Error::InvalidParameter(Op::CopyMemory))? + } else { + spirv::MemoryAccess::NONE + }; + + // TODO: check if the source and target types are the same? + let target = self.lookup_expression.lookup(target_id)?; + let source = self.lookup_expression.lookup(source_id)?; + + // This operation is practically the same as loading and then storing, I think. + let value_expr = expressions.append(crate::Expression::Load { + pointer: source.handle, + }); + + block.extend(emitter.finish(expressions)); + block.push(crate::Statement::Store { + pointer: target.handle, + value: value_expr, + }); + + emitter.start(expressions); + } _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } }; @@ -2993,15 +3055,12 @@ impl> Parser { kind: crate::ScalarKind::Sint, width, } => { - use std::cmp::Ordering; let low = self.next()?; - let high = match width.cmp(&4) { - Ordering::Less => return Err(Error::InvalidTypeWidth(u32::from(width))), - Ordering::Greater => { - inst.expect(4)?; - self.next()? - } - Ordering::Equal => 0, + let high = if width > 4 { + inst.expect(4)?; + self.next()? + } else { + 0 }; crate::ConstantInner::Scalar { width, @@ -3081,18 +3140,13 @@ impl> Parser { Ok(()) } - fn parse_null_constant( + fn generate_null_constant( &mut self, - inst: Instruction, - module: &mut crate::Module, - ) -> Result<(), Error> { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(3)?; - let type_id = self.next()?; - let id = self.next()?; - let type_lookup = self.lookup_type.lookup(type_id)?; - let ty = type_lookup.handle; - + constants: &mut Arena, + types: &Arena, + ty: Handle, + inner: &crate::TypeInner, + ) -> Result { fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { crate::ConstantInner::Scalar { width, @@ -3105,12 +3159,12 @@ impl> Parser { } } - let inner = match module.types[ty].inner { + let inner = match *inner { crate::TypeInner::Scalar { kind, width } => make_scalar_inner(kind, width), crate::TypeInner::Vector { size, kind, width } => { let mut components = Vec::with_capacity(size as usize); for _ in 0..size as usize { - components.push(module.constants.fetch_or_append(crate::Constant { + components.push(constants.fetch_or_append(crate::Constant { name: None, specialization: None, inner: make_scalar_inner(kind, width), @@ -3118,12 +3172,48 @@ impl> Parser { } crate::ConstantInner::Composite { ty, components } } - //TODO: handle matrices, arrays, and structures + crate::TypeInner::Struct { ref members, .. } => { + let mut components = Vec::with_capacity(members.len()); + for field in members { + let ty_inner = &types[field.ty].inner; + let inner = + self.generate_null_constant(constants, types, field.ty, ty_inner)?; + components.push(constants.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner, + })); + } + + crate::ConstantInner::Composite { ty, components } + } + //TODO: handle matrices, arrays ref other => { log::warn!("null constant type {:?}", other); - return Err(Error::UnsupportedType(type_lookup.handle)); + return Err(Error::UnsupportedType(ty)); } }; + Ok(inner) + } + + fn parse_null_constant( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(3)?; + let type_id = self.next()?; + let id = self.next()?; + let type_lookup = self.lookup_type.lookup(type_id)?; + let ty = type_lookup.handle; + + let inner = self.generate_null_constant( + &mut module.constants, + &module.types, + ty, + &module.types[ty].inner, + )?; self.lookup_constant.insert( id, diff --git a/src/lib.rs b/src/lib.rs index 270fbf974..d51828e5b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -813,6 +813,10 @@ pub enum Expression { /// Result of calling another function. Call(Handle), /// Get the length of an array. + /// The expression must resolve to a pointer to an array with a dynamic size. + /// + /// This doesn't match the semantics of spirv's `OpArrayLength`, which must be passed + /// a pointer to a structure containing a runtime array in its' last field. ArrayLength(Handle), } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 46d2099c6..df79a3dff 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -171,24 +171,36 @@ impl super::Validator { ShaderStages::all() } E::AccessIndex { base, index } => { - let limit = match *resolver.resolve(base)? { - Ti::Vector { size, .. } - | Ti::ValuePointer { - size: Some(size), .. - } => size as u32, - Ti::Matrix { columns, .. } => columns as u32, - Ti::Array { - size: crate::ArraySize::Constant(handle), - .. - } => module.constants[handle].to_array_length().unwrap(), - Ti::Array { .. } => !0, // can't statically know, but need run-time checks - Ti::Pointer { .. } => !0, //TODO - Ti::Struct { ref members, .. } => members.len() as u32, - ref other => { - log::error!("Indexing of {:?}", other); - return Err(ExpressionError::InvalidBaseType(base)); - } - }; + fn resolve_index_limit( + module: &crate::Module, + top: Handle, + ty: &crate::TypeInner, + top_level: bool, + ) -> Result { + let limit = match *ty { + Ti::Vector { size, .. } + | Ti::ValuePointer { + size: Some(size), .. + } => size as u32, + Ti::Matrix { columns, .. } => columns as u32, + Ti::Array { + size: crate::ArraySize::Constant(handle), + .. + } => module.constants[handle].to_array_length().unwrap(), + Ti::Array { .. } => !0, // can't statically know, but need run-time checks + Ti::Pointer { base, .. } if top_level => { + resolve_index_limit(module, top, &module.types[base].inner, false)? + } + Ti::Struct { ref members, .. } => members.len() as u32, + ref other => { + log::error!("Indexing of {:?}", other); + return Err(ExpressionError::InvalidBaseType(top)); + } + }; + Ok(limit) + } + + let limit = resolve_index_limit(module, base, resolver.resolve(base)?, true)?; if index >= limit { return Err(ExpressionError::IndexOutOfBounds(base, index)); } From 960551f952015cb92c16d6382359252d32cd7bc2 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Fri, 30 Apr 2021 00:20:09 -0400 Subject: [PATCH 0778/2212] Add support for arrayLength to the wgsl frontend (#805) * Add support for arrayLength to the wgsl frontend * Fix clippy warning --- src/front/wgsl/mod.rs | 5 +++++ src/front/wgsl/tests.rs | 24 ++++++++++++++++++++++++ src/valid/expression.rs | 12 +++++++++++- 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index d2ac7a0b1..f24eea8fd 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -741,6 +741,11 @@ impl Parser { accept, reject, } + } else if name == "arrayLength" { + lexer.open_arguments()?; + let array = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + crate::Expression::ArrayLength(array) } else { // texture sampling match name { diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index d7428b65b..a537c62d1 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -304,3 +304,27 @@ fn parse_struct_instantiation() { ) .unwrap(); } + +#[test] +fn parse_array_length() { + parse_str( + " + [[block]] + struct Foo { + data: [[stride(4)]] array; + }; // this is used as both input and output for convenience + + [[group(0), binding(0)]] + var foo: [[access(read_write)]] Foo; + + [[group(0), binding(1)]] + var bar: [[access(read)]] array; + + fn foo() { + var x: u32 = arrayLength(foo.data); + var y: u32 = arrayLength(bar); + } + ", + ) + .unwrap(); +} diff --git a/src/valid/expression.rs b/src/valid/expression.rs index df79a3dff..1089b057e 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1110,7 +1110,17 @@ impl super::Validator { } E::Call(function) => other_infos[function.index()].available_stages, E::ArrayLength(expr) => match *resolver.resolve(expr)? { - Ti::Array { .. } => ShaderStages::all(), + Ti::Pointer { base, .. } => { + if let Some(&Ti::Array { + size: crate::ArraySize::Dynamic, + .. + }) = resolver.types.try_get(base).map(|ty| &ty.inner) + { + ShaderStages::all() + } else { + return Err(ExpressionError::InvalidArrayType(expr)); + } + } ref other => { log::error!("Array length of {:?}", other); return Err(ExpressionError::InvalidArrayType(expr)); From 992bdd83ce53263b26386506465c959485187e78 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 30 Apr 2021 13:38:20 -0400 Subject: [PATCH 0779/2212] Report per-entry point translation errors in the MSL output snapshots (#808) --- tests/snapshots.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 86d228959..cf2ce6a48 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -164,7 +164,13 @@ fn check_output_msl( allow_point_size: true, }; - let (string, _) = msl::write_string(module, info, options, &pipeline_options).unwrap(); + let (string, tr_info) = msl::write_string(module, info, options, &pipeline_options).unwrap(); + + for (ep, result) in module.entry_points.iter().zip(tr_info.entry_point_names) { + if let Err(error) = result { + panic!("Failed to translate '{}': {}", ep.name, error); + } + } fs::write(destination.with_extension("msl"), string).unwrap(); } From 232fd65ec7171672f8d3906e1624bb1fe320f182 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Fri, 30 Apr 2021 22:40:32 -0400 Subject: [PATCH 0780/2212] Add support for retrieving array length in msl backend (#806) * Add support for arrayLength to the wgsl frontend * Fix clippy warning * Add draft support for array length to the msl backend * Finalize support for array length in msl * Convert buffer size to array length in msl backend * Fix clippy warning * Fix misleading documentation * Changes based on review of PR * Use a fake binding for sizes buffer in msl backend if necessary * Only generate the msl buffer size structure if globals are present that have unsized arrays * Make sure to generate separators * Replace uses_unsized_buffers with !self.runtime_sized_buffers.is_empty() * Clear self.runtime_sized_buffers * Run snapshot of shadow.msl * Add Expression::ArrayLength support to the spirv backend * Remove wgsl target from the access snapshot test * Update access.msl snapshot * Update stack size for msl backend * Update stack size again for msl backend --- src/back/msl/mod.rs | 5 ++ src/back/msl/writer.rs | 167 +++++++++++++++++++++++++++++------ src/back/spv/instructions.rs | 14 +++ src/back/spv/writer.rs | 34 ++++++- tests/in/access.param.ron | 14 ++- tests/in/access.wgsl | 12 ++- tests/out/access.msl | 14 ++- tests/out/access.spvasm | 96 ++++++++++++-------- tests/out/boids.msl | 6 ++ tests/out/collatz.msl | 10 ++- tests/out/shadow.msl | 10 ++- tests/snapshots.rs | 4 +- 12 files changed, 307 insertions(+), 79 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index e38beed88..0579dcfec 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -157,6 +157,10 @@ pub struct Options { pub spirv_cross_compatibility: bool, /// Don't panic on missing bindings, instead generate invalid MSL. pub fake_missing_bindings: bool, + /// The slot of a buffer that contains an array of `u32`, + /// one for the size of each bound buffer that contains a runtime array, + /// in order of [`GlobalVariable`] declarations. + pub sizes_buffer_binding: Option, } impl Default for Options { @@ -168,6 +172,7 @@ impl Default for Options { inline_samplers: Vec::new(), spirv_cross_compatibility: false, fake_missing_bindings: true, + sizes_buffer_binding: None, } } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index bfccf1dcd..66951b44b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,6 +1,6 @@ use super::{ - keywords::RESERVED, sampler as sm, Error, LocationMode, Options, PipelineOptions, - TranslationInfo, + keywords::RESERVED, sampler as sm, BindTarget, Error, LocationMode, Options, PipelineOptions, + ResolvedBinding, TranslationInfo, }; use crate::{ arena::{Arena, Handle}, @@ -290,6 +290,7 @@ pub struct Writer { names: FastHashMap, named_expressions: BitSet, namer: Namer, + runtime_sized_buffers: FastHashMap, usize>, #[cfg(test)] put_expression_stack_pointers: crate::FastHashSet<*const ()>, #[cfg(test)] @@ -435,6 +436,7 @@ impl Writer { names: FastHashMap::default(), named_expressions: BitSet::new(), namer: Namer::default(), + runtime_sized_buffers: FastHashMap::default(), #[cfg(test)] put_expression_stack_pointers: Default::default(), #[cfg(test)] @@ -1060,26 +1062,53 @@ impl Writer { } // has to be a named expression crate::Expression::Call(_) => unreachable!(), - crate::Expression::ArrayLength(expr) => match *context.resolve_type(expr) { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(const_handle), - .. - } => { - let coco = ConstantContext { - handle: const_handle, - arena: &context.module.constants, - names: &self.names, - first_time: false, - }; - write!(self.out, "{}", coco)?; + crate::Expression::ArrayLength(expr) => { + let handle = match context.function.expressions[expr] { + crate::Expression::AccessIndex { base, .. } => { + match context.function.expressions[base] { + crate::Expression::GlobalVariable(handle) => handle, + _ => return Err(Error::Validation), + } + } + _ => return Err(Error::Validation), + }; + + let global = &context.module.global_variables[handle]; + if let crate::TypeInner::Struct { ref members, .. } = + context.module.types[global.ty].inner + { + if let Some(&crate::StructMember { + offset, + ty: array_ty, + .. + }) = members.last() + { + let (span, stride) = match context.module.types[array_ty].inner { + crate::TypeInner::Array { base, stride, .. } => ( + context.module.types[base] + .inner + .span(&context.module.constants), + stride, + ), + _ => return Err(Error::Validation), + }; + + let buffer_idx = self.runtime_sized_buffers[&handle]; + write!( + self.out, + "(1 + (_buffer_sizes.size{idx} - {offset} - {span}) / {stride})", + idx = buffer_idx, + offset = offset, + span = span, + stride = stride, + )?; + } else { + return Err(Error::Validation); + } + } else { + return Err(Error::Validation); } - crate::TypeInner::Array { .. } => { - return Err(Error::FeatureNotImplemented( - "dynamic array size".to_string(), - )) - } - _ => return Err(Error::Validation), - }, + } } Ok(()) } @@ -1405,6 +1434,14 @@ impl Writer { write!(self.out, "{}", name)?; } } + if !self.runtime_sized_buffers.is_empty() { + if separate { + write!(self.out, ", ")?; + } + + write!(self.out, "_buffer_sizes")?; + } + // done writeln!(self.out, ");")?; } @@ -1432,11 +1469,42 @@ impl Writer { ) -> Result { self.names.clear(); self.namer.reset(module, RESERVED, &mut self.names); + self.runtime_sized_buffers.clear(); writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; writeln!(self.out)?; + { + let mut indices = vec![]; + for (handle, gv) in module.global_variables.iter() { + if let crate::TypeInner::Struct { ref members, .. } = module.types[gv.ty].inner { + if let Some(member) = members.last() { + if let crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } = module.types[member.ty].inner + { + let idx = handle.index(); + self.runtime_sized_buffers.insert(handle, idx); + indices.push(idx); + } + } + } + } + + if !indices.is_empty() { + writeln!(self.out, "struct _mslBufferSizes {{")?; + + for idx in indices { + writeln!(self.out, "{}{}::uint size{};", INDENT, NAMESPACE, idx)?; + } + + writeln!(self.out, "}};")?; + writeln!(self.out)?; + } + }; + self.write_scalar_constants(module)?; self.write_type_defs(module)?; self.write_composite_constants(module)?; @@ -1746,8 +1814,11 @@ impl Writer { access: crate::StorageAccess::empty(), first_time: false, }; - let separator = - separate(!pass_through_globals.is_empty() || index + 1 != fun.arguments.len()); + let separator = separate( + !pass_through_globals.is_empty() + || index + 1 != fun.arguments.len() + || !self.runtime_sized_buffers.is_empty(), + ); writeln!( self.out, "{}{} {}{}", @@ -1762,11 +1833,23 @@ impl Writer { usage: fun_info[handle], reference: true, }; - let separator = separate(index + 1 != pass_through_globals.len()); + let separator = separate( + index + 1 != pass_through_globals.len() + || !self.runtime_sized_buffers.is_empty(), + ); write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; writeln!(self.out, "{}", separator)?; } + + if !self.runtime_sized_buffers.is_empty() { + writeln!( + self.out, + "{}constant _mslBufferSizes& _buffer_sizes", + INDENT + )?; + } + writeln!(self.out, ") {{")?; for (local_handle, local) in fun.local_variables.iter() { @@ -2049,6 +2132,34 @@ impl Writer { writeln!(self.out)?; } + if !self.runtime_sized_buffers.is_empty() { + let resolved = if let Some(slot) = options.sizes_buffer_binding { + ResolvedBinding::Resource(BindTarget { + buffer: Some(slot), + mutable: false, + ..Default::default() + }) + } else { + ResolvedBinding::User { + prefix: "fake", + index: 0, + interpolation: None, + } + }; + + let separator = if module.global_variables.is_empty() { + ' ' + } else { + ',' + }; + write!( + self.out, + "{} constant _mslBufferSizes& _buffer_sizes", + separator, + )?; + resolved.try_fmt_decorated(&mut self.out, "\n")?; + } + // end of the entry point argument list writeln!(self.out, ") {{")?; @@ -2231,8 +2342,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 21760 - if stack_size < 21000 || stack_size > 23000 { + // last observed macOS value: 23040 + if stack_size < 21000 || stack_size > 25000 { panic!("`put_expression` stack size {} has changed!", stack_size); } } @@ -2246,8 +2357,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 12736 - if stack_size < 12000 || stack_size > 13500 { + // last observed macOS value: 13600 + if stack_size < 12000 || stack_size > 14500 { panic!("`put_block` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 308d9b6d6..0b3b42b42 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -473,6 +473,20 @@ impl super::Instruction { instruction } + pub(super) fn array_length( + result_type_id: Word, + id: Word, + structure_id: Word, + array_member: Word, + ) -> Self { + let mut instruction = Self::new(Op::ArrayLength); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(structure_id); + instruction.add_operand(array_member); + instruction + } + // // Function Instructions // diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index c370b0aa6..d6c1a6cd1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2349,9 +2349,37 @@ impl Writer { .push(Instruction::relational(op, result_type_id, id, arg_id)); id } - crate::Expression::ArrayLength(_) => { - log::error!("unimplemented {:?}", ir_function.expressions[expr_handle]); - return Err(Error::FeatureNotImplemented("expression")); + crate::Expression::ArrayLength(expr) => { + let (structure_id, member_idx) = match ir_function.expressions[expr] { + crate::Expression::AccessIndex { base, .. } => { + match ir_function.expressions[base] { + crate::Expression::GlobalVariable(handle) => { + let global = &ir_module.global_variables[handle]; + let last_idx = match ir_module.types[global.ty].inner { + crate::TypeInner::Struct { ref members, .. } => { + members.len() as u32 - 1 + } + _ => return Err(Error::Validation("array length expression")), + }; + + (self.global_variables[handle.index()].id, last_idx) + } + _ => return Err(Error::Validation("array length expression")), + } + } + _ => return Err(Error::Validation("array length expression")), + }; + + // let structure_id = self.get_expression_global(ir_function, global); + let id = self.id_gen.next(); + + block.body.push(Instruction::array_length( + result_type_id, + id, + structure_id, + member_idx, + )); + id } }; diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 52f49f360..0464ddf32 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -3,5 +3,17 @@ spv_capabilities: [ Shader, Image1D, Sampled1D ], spv_debug: true, spv_adjust_coordinate_space: false, - msl_custom: false, + msl_custom: true, + msl: ( + lang_version: (2, 0), + binding_map: { + (stage: Vertex, group: 0, binding: 0): (buffer: Some(0), mutable: true), + }, + push_constants_map: ( + ), + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + sizes_buffer_binding: Some(24), + ), ) diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index c5f6c27e7..1860ff1c4 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -1,8 +1,18 @@ // This snapshot tests accessing various containers, dereferencing pointers. +[[block]] +struct Bar { + data: [[stride(4)]] array; +}; + +[[group(0), binding(0)]] +var bar: [[access(read_write)]] Bar; + [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { - let array = array(1, 2, 3, 4, 5); + let a = bar.data[arrayLength(&bar.data) - 1u]; + + let array = array(a, 2, 3, 4, 5); let value = array[vi]; return vec4(vec4(value)); } diff --git a/tests/out/access.msl b/tests/out/access.msl index 36ed56482..a87a402ae 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -1,7 +1,15 @@ #include #include -struct type3 { +struct _mslBufferSizes { + metal::uint size0; +}; + +typedef int type1[1]; +struct Bar { + type1 data; +}; +struct type4 { int inner[5]; }; @@ -12,6 +20,8 @@ struct fooOutput { }; vertex fooOutput foo( metal::uint vi [[vertex_id]] +, device Bar& bar [[buffer(0)]] +, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - return fooOutput { static_cast(int4(type3 {1, 2, 3, 4, 5}.inner[vi])) }; + return fooOutput { static_cast(int4(type4 {bar.data[(1 + (_buffer_sizes.size0 - 0 - 4) / 4) - 1u], 2, 3, 4, 5}.inner[vi])) }; } diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm index 985b9a840..307305a9e 100644 --- a/tests/out/access.spvasm +++ b/tests/out/access.spvasm @@ -1,50 +1,70 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 31 +; Bound: 42 OpCapability Image1D OpCapability Shader OpCapability Sampled1D +OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %19 "foo" %14 %17 +OpEntryPoint Vertex %23 "foo" %18 %21 OpSource GLSL 450 -OpName %14 "vi" -OpName %19 "foo" -OpDecorate %12 ArrayStride 4 -OpDecorate %14 BuiltIn VertexIndex -OpDecorate %17 BuiltIn Position +OpName %11 "Bar" +OpMemberName %11 0 "data" +OpName %15 "bar" +OpName %18 "vi" +OpName %23 "foo" +OpDecorate %10 ArrayStride 4 +OpDecorate %11 Block +OpMemberDecorate %11 0 Offset 0 +OpDecorate %14 ArrayStride 4 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 0 +OpDecorate %18 BuiltIn VertexIndex +OpDecorate %21 BuiltIn Position %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 5 -%5 = OpConstant %4 1 -%6 = OpConstant %4 2 -%7 = OpConstant %4 3 -%8 = OpConstant %4 4 -%9 = OpTypeInt 32 0 -%11 = OpTypeFloat 32 -%10 = OpTypeVector %11 4 -%12 = OpTypeArray %4 %3 -%15 = OpTypePointer Input %9 -%14 = OpVariable %15 Input -%18 = OpTypePointer Output %10 -%17 = OpVariable %18 Output -%20 = OpTypeFunction %2 -%23 = OpTypePointer Function %12 -%26 = OpTypePointer Function %4 -%28 = OpTypeVector %4 4 -%19 = OpFunction %2 None %20 -%13 = OpLabel -%24 = OpVariable %23 Function -%16 = OpLoad %9 %14 -OpBranch %21 -%21 = OpLabel -%22 = OpCompositeConstruct %12 %5 %6 %7 %8 %3 -OpStore %24 %22 -%25 = OpAccessChain %26 %24 %16 -%27 = OpLoad %4 %25 -%29 = OpCompositeConstruct %28 %27 %27 %27 %27 -%30 = OpConvertSToF %10 %29 -OpStore %17 %30 +%4 = OpTypeInt 32 0 +%3 = OpConstant %4 1 +%6 = OpTypeInt 32 1 +%5 = OpConstant %6 5 +%7 = OpConstant %6 2 +%8 = OpConstant %6 3 +%9 = OpConstant %6 4 +%10 = OpTypeRuntimeArray %6 +%11 = OpTypeStruct %10 +%13 = OpTypeFloat 32 +%12 = OpTypeVector %13 4 +%14 = OpTypeArray %6 %5 +%16 = OpTypePointer StorageBuffer %11 +%15 = OpVariable %16 StorageBuffer +%19 = OpTypePointer Input %4 +%18 = OpVariable %19 Input +%22 = OpTypePointer Output %12 +%21 = OpVariable %22 Output +%24 = OpTypeFunction %2 +%26 = OpTypePointer StorageBuffer %10 +%29 = OpTypePointer StorageBuffer %6 +%30 = OpConstant %6 0 +%34 = OpTypePointer Function %14 +%37 = OpTypePointer Function %6 +%39 = OpTypeVector %6 4 +%23 = OpFunction %2 None %24 +%17 = OpLabel +%35 = OpVariable %34 Function +%20 = OpLoad %4 %18 +OpBranch %25 +%25 = OpLabel +%27 = OpArrayLength %4 %15 0 +%28 = OpISub %4 %27 %3 +%31 = OpAccessChain %29 %15 %30 %28 +%32 = OpLoad %6 %31 +%33 = OpCompositeConstruct %14 %32 %7 %8 %9 %5 +OpStore %35 %33 +%36 = OpAccessChain %37 %35 %20 +%38 = OpLoad %6 %36 +%40 = OpCompositeConstruct %39 %38 %38 %38 %38 +%41 = OpConvertSToF %12 %40 +OpStore %21 %41 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/boids.msl b/tests/out/boids.msl index 3cabb8e66..1deab9f73 100644 --- a/tests/out/boids.msl +++ b/tests/out/boids.msl @@ -1,6 +1,11 @@ #include #include +struct _mslBufferSizes { + metal::uint size1; + metal::uint size2; +}; + constexpr constant unsigned NUM_PARTICLES = 1500u; struct Particle { metal::float2 pos; @@ -27,6 +32,7 @@ kernel void main1( , constant SimParams& params [[buffer(0)]] , constant Particles& particlesSrc [[buffer(1)]] , device Particles& particlesDst [[buffer(2)]] +, constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { metal::float2 vPos; metal::float2 vVel; diff --git a/tests/out/collatz.msl b/tests/out/collatz.msl index 403789659..7342aa8ec 100644 --- a/tests/out/collatz.msl +++ b/tests/out/collatz.msl @@ -1,13 +1,18 @@ #include #include +struct _mslBufferSizes { + metal::uint size0; +}; + typedef metal::uint type1[1]; struct PrimeIndices { type1 data; }; metal::uint collatz_iterations( - metal::uint n_base + metal::uint n_base, + constant _mslBufferSizes& _buffer_sizes ) { metal::uint n; metal::uint i = 0u; @@ -31,8 +36,9 @@ struct main1Input { kernel void main1( metal::uint3 global_id [[thread_position_in_grid]] , device PrimeIndices& v_indices [[user(fake0)]] +, constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - metal::uint _e9 = collatz_iterations(v_indices.data[global_id.x]); + metal::uint _e9 = collatz_iterations(v_indices.data[global_id.x], _buffer_sizes); v_indices.data[global_id.x] = _e9; return; } diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index 0ff4e18f4..420dfda57 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -1,6 +1,10 @@ #include #include +struct _mslBufferSizes { + metal::uint size1; +}; + constexpr constant unsigned c_max_lights = 10u; struct Globals { metal::uint4 num_lights; @@ -20,7 +24,8 @@ float fetch_shadow( metal::uint light_id, metal::float4 homogeneous_coords, metal::depth2d_array t_shadow, - metal::sampler sampler_shadow + metal::sampler sampler_shadow, + constant _mslBufferSizes& _buffer_sizes ) { if (homogeneous_coords.w <= 0.0) { return 1.0; @@ -42,6 +47,7 @@ fragment fs_mainOutput fs_main( , constant Lights& s_lights [[user(fake0)]] , metal::depth2d_array t_shadow [[user(fake0)]] , metal::sampler sampler_shadow [[user(fake0)]] +, constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; @@ -57,7 +63,7 @@ fragment fs_mainOutput fs_main( break; } Light _e21 = s_lights.data[i]; - float _e25 = fetch_shadow(i, _e21.proj * position, t_shadow, sampler_shadow); + float _e25 = fetch_shadow(i, _e21.proj * position, t_shadow, sampler_shadow, _buffer_sizes); color1 = color1 + ((_e25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(_e21.pos.xyz - position.xyz)))) * _e21.color.xyz); } return fs_mainOutput { metal::float4(color1, 1.0) }; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index cf2ce6a48..dfce79d74 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -154,7 +154,7 @@ fn check_output_msl( let options = ¶ms.msl; #[cfg(not(feature = "deserialize"))] let options = if params.msl_custom { - println!("Skipping {}", destination); + println!("Skipping {}", destination.display()); return; } else { &default_options @@ -248,7 +248,7 @@ fn convert_wgsl() { "interpolate", Targets::SPIRV | Targets::METAL | Targets::GLSL, ), - ("access", Targets::SPIRV | Targets::METAL | Targets::WGSL), + ("access", Targets::SPIRV | Targets::METAL), ]; for &(name, targets) in inputs.iter() { From 05d36087378433c39f8984908d99ed98a01d9ebb Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Sun, 2 May 2021 17:29:35 +0200 Subject: [PATCH 0781/2212] HLSL CI (#788) * Add validation-windows yml for HLSL Add workgroup size to hlsl-out * Update Readme with Make target information * Change runs on to windows-latest * Remove snapshot file --- .github/workflows/validation-windows.yml | 16 ++++++++++++++++ Makefile | 9 ++++++++- README.md | 1 + src/back/hlsl/writer.rs | 12 +++++++++++- tests/out/empty.Compute.hlsl | 6 ++++++ tests/snapshots.rs | 9 ++++++--- 6 files changed, 48 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/validation-windows.yml create mode 100644 tests/out/empty.Compute.hlsl diff --git a/.github/workflows/validation-windows.yml b/.github/workflows/validation-windows.yml new file mode 100644 index 000000000..95ff1c06b --- /dev/null +++ b/.github/workflows/validation-windows.yml @@ -0,0 +1,16 @@ +name: validation-windows +on: + pull_request: + paths: + - 'tests/out/*.hlsl' + +jobs: + validate-windows: + name: HLSL + runs-on: windows-latest + steps: + - uses: actions/checkout@v2 + - name: Add DirectXShaderCompiler + uses: napokue/setup-dxc@v1.0.0 + - run: make validate-hlsl + shell: sh \ No newline at end of file diff --git a/Makefile b/Makefile index d52a82ab2..397cbaf5b 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all clean validate-spv validate-msl validate-glsl validate-dot validate-wgsl +.PHONY: all clean validate-spv validate-msl validate-glsl validate-dot validate-wgsl validate-hlsl .SECONDARY: boids.metal quad.metal SNAPSHOTS_IN=tests/in SNAPSHOTS_OUT=tests/out @@ -63,3 +63,10 @@ validate-wgsl: $(SNAPSHOTS_OUT)/*.wgsl echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ cargo run --features wgsl-in $${file}; \ done + +validate-hlsl: $(SNAPSHOTS_OUT)/*.hlsl + @set -e && for file in $(SNAPSHOTS_OUT)/*.Compute.hlsl ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ + dxc $${file} -T cs_6_0;\ + done + diff --git a/README.md b/README.md index 4087a07d8..5956919fe 100644 --- a/README.md +++ b/README.md @@ -63,4 +63,5 @@ make validate-msl # for Metal shaders, requires XCode command-line tools install make validate-glsl # for OpenGL shaders, requires GLSLang installed make validate-dot # for dot files, requires GraphViz installed make validate-wgsl # for WGSL shaders +make validate-hlsl # for HLSL shaders. Note: this Make target makes use of the "sh" shell. This is not the default shell in Windows. ``` diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 67a34f7ca..61f680ded 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,7 +1,7 @@ use super::Error; use crate::back::hlsl::keywords::RESERVED; use crate::proc::{NameKey, Namer}; -use crate::FastHashMap; +use crate::{FastHashMap, ShaderStage}; use std::fmt::Write; const INDENT: &str = " "; @@ -35,6 +35,16 @@ impl Writer { _ => "", }; + if ep.stage == ShaderStage::Compute { + // HLSL is calling workgroup size, num threads + let num_threads = ep.workgroup_size; + writeln!( + self.out, + "[numthreads({}, {}, {})]", + num_threads[0], num_threads[1], num_threads[2] + )?; + } + writeln!( self.out, "{} {}({}", diff --git a/tests/out/empty.Compute.hlsl b/tests/out/empty.Compute.hlsl new file mode 100644 index 000000000..2b5243867 --- /dev/null +++ b/tests/out/empty.Compute.hlsl @@ -0,0 +1,6 @@ + +[numthreads(1, 1, 1)] +void main() +{ + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index dfce79d74..f105fe012 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -96,7 +96,9 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "hlsl-out")] { if targets.contains(Targets::HLSL) { - check_output_hlsl(module, &dest); + for ep in module.entry_points.iter() { + check_output_hlsl(module, &dest, ep.stage); + } } } #[cfg(feature = "wgsl-out")] @@ -204,12 +206,13 @@ fn check_output_glsl( } #[cfg(feature = "hlsl-out")] -fn check_output_hlsl(module: &naga::Module, destination: &PathBuf) { +fn check_output_hlsl(module: &naga::Module, destination: &PathBuf, stage: naga::ShaderStage) { use naga::back::hlsl; let string = hlsl::write_string(module).unwrap(); - fs::write(destination.with_extension("hlsl"), string).unwrap(); + let ext = format!("{:?}.hlsl", stage); + fs::write(destination.with_extension(&ext), string).unwrap(); } #[cfg(feature = "wgsl-out")] From e78f5e69ceacdd40319263babae644db0c70060f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 2 May 2021 00:40:37 -0400 Subject: [PATCH 0782/2212] [spv-in] derive Error --- src/front/spv/error.rs | 54 +++++++++++++++++++++++++++++++++++++++--- src/front/spv/mod.rs | 2 +- 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 4f4e6b166..b1651e847 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -1,57 +1,105 @@ use super::ModuleState; use crate::arena::Handle; -//TODO: use `thiserror` -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] pub enum Error { + #[error("invalid header")] InvalidHeader, + #[error("invalid word count")] InvalidWordCount, + #[error("unknown instruction {0}")] UnknownInstruction(u16), + #[error("unknown capability {0}")] UnknownCapability(spirv::Word), + #[error("unsupported instruction {1:?} at {0:?}")] UnsupportedInstruction(ModuleState, spirv::Op), + #[error("unsupported capability {0:?}")] UnsupportedCapability(spirv::Capability), + #[error("unsupported extension {0}")] UnsupportedExtension(String), + #[error("unsupported extension set {0}")] UnsupportedExtSet(String), + #[error("unsupported extension instantiation set {0}")] UnsupportedExtInstSet(spirv::Word), + #[error("unsupported extension instantiation {0}")] UnsupportedExtInst(spirv::Word), + #[error("unsupported type {0:?}")] UnsupportedType(Handle), + #[error("unsupported execution model {0}")] UnsupportedExecutionModel(spirv::Word), + #[error("unsupported execution mode {0}")] UnsupportedExecutionMode(spirv::Word), + #[error("unsupported storage class {0}")] UnsupportedStorageClass(spirv::Word), + #[error("unsupported image dimension {0}")] UnsupportedImageDim(spirv::Word), + #[error("unsupported image format {0}")] UnsupportedImageFormat(spirv::Word), + #[error("unsupported builtin {0}")] UnsupportedBuiltIn(spirv::Word), + #[error("unsupported control flow {0}")] UnsupportedControlFlow(spirv::Word), + #[error("unsupported binary operator {0}")] UnsupportedBinaryOperator(spirv::Word), + #[error("unknown binary operator {0:?}")] UnknownBinaryOperator(spirv::Op), + #[error("unknown relational function {0:?}")] UnknownRelationalFunction(spirv::Op), + #[error("invalid parameter {0:?}")] InvalidParameter(spirv::Op), + #[error("invalid operand count {1} for {0:?}")] InvalidOperandCount(spirv::Op, u16), + #[error("invalid operand")] InvalidOperand, + #[error("invalid id {0}")] InvalidId(spirv::Word), + #[error("invalid decoration {0}")] InvalidDecoration(spirv::Word), + #[error("invalid type width {0}")] InvalidTypeWidth(spirv::Word), + #[error("invalid sign {0}")] InvalidSign(spirv::Word), + #[error("invalid inner type {0}")] InvalidInnerType(spirv::Word), + #[error("invalid vector size {0}")] InvalidVectorSize(spirv::Word), + #[error("invalid access type {0}")] InvalidAccessType(spirv::Word), + #[error("invalid access {0:?}")] InvalidAccess(crate::Expression), + #[error("invalid access index {0}")] InvalidAccessIndex(spirv::Word), + #[error("invalid binding {0}")] InvalidBinding(spirv::Word), + #[error("invalid global var {0:?}")] InvalidGlobalVar(crate::Expression), + #[error("invalid image base type {0:?}")] InvalidImageBaseType(Handle), + #[error("invalid image {0:?}")] InvalidImage(Handle), + #[error("invalid as type {0:?}")] InvalidAsType(Handle), + #[error("invalid vector type {0:?}")] InvalidVectorType(Handle), + #[error("inconsistent comparison sampling {0:?}")] InconsistentComparisonSampling(Handle), + #[error("wrong function result type {0}")] WrongFunctionResultType(spirv::Word), + #[error("wrong function argument type {0}")] WrongFunctionArgumentType(spirv::Word), + #[error("missing decoration {0:?}")] MissingDecoration(spirv::Decoration), + #[error("bad string")] BadString, + #[error("incomplete data")] IncompleteData, + #[error("invalid terminator")] InvalidTerminator, + #[error("invalid edge classification")] InvalidEdgeClassification, + #[error("recursive function call {0}")] FunctionCallCycle(spirv::Word), - // incomplete implementation error + // incomplete implementation errors + #[error("unsupported matrix stride {0}")] UnsupportedMatrixStride(spirv::Word), } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 868b2f45d..a4a696acd 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -33,7 +33,7 @@ mod function; mod image; use convert::*; -use error::Error; +pub use error::Error; use flow::*; use function::*; From 46a244fff06a791acd86fdd482fb86bd7446b518 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 2 May 2021 00:49:02 -0400 Subject: [PATCH 0783/2212] [wgsl-in] remove lifetime from ParseError --- bin/naga.rs | 2 +- src/front/wgsl/mod.rs | 31 ++++++++++++------------------- tests/errors.rs | 2 +- 3 files changed, 14 insertions(+), 21 deletions(-) diff --git a/bin/naga.rs b/bin/naga.rs index a0ab7b675..d9b841ebc 100644 --- a/bin/naga.rs +++ b/bin/naga.rs @@ -118,7 +118,7 @@ fn main() { match result { Ok(v) => v, Err(ref e) => { - e.emit_to_stderr(); + e.emit_to_stderr(&input); panic!("unable to parse WGSL"); } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f24eea8fd..201509ff0 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -131,7 +131,7 @@ pub enum Error<'a> { } impl<'a> Error<'a> { - fn as_parse_error(&self, source: &'a str) -> ParseError<'a> { + fn as_parse_error(&self, source: &'a str) -> ParseError { match *self { Error::Unexpected((_, ref unexpected_span), expected) => ParseError { message: format!( @@ -141,7 +141,6 @@ impl<'a> Error<'a> { ), labels: vec![(unexpected_span.clone(), format!("expected {}", expected))], notes: vec![], - source, }, Error::BadInteger(ref bad_span) => ParseError { message: format!( @@ -150,7 +149,6 @@ impl<'a> Error<'a> { ), labels: vec![(bad_span.clone(), "expected integer".to_string())], notes: vec![], - source, }, Error::BadFloat(ref bad_span) => ParseError { message: format!( @@ -162,13 +160,11 @@ impl<'a> Error<'a> { "expected floating-point literal".to_string(), )], notes: vec![], - source, }, Error::BadScalarWidth(ref bad_span, width) => ParseError { message: format!("invalid width of `{}` for literal", width,), labels: vec![(bad_span.clone(), "invalid width".to_string())], notes: vec!["valid width is 32".to_string()], - source, }, Error::BadAccessor(ref accessor_span) => ParseError { message: format!( @@ -177,13 +173,11 @@ impl<'a> Error<'a> { ), labels: vec![(accessor_span.clone(), "invalid accessor".to_string())], notes: vec![], - source, }, ref error => ParseError { message: error.to_string(), labels: vec![], notes: vec![], - source, }, } } @@ -537,14 +531,13 @@ struct ParsedVariable<'a> { } #[derive(Clone, Debug)] -pub struct ParseError<'a> { +pub struct ParseError { message: String, labels: Vec<(Span, String)>, notes: Vec, - source: &'a str, } -impl<'a> ParseError<'a> { +impl ParseError { fn diagnostic(&self) -> Diagnostic<()> { let diagnostic = Diagnostic::error() .with_message(self.message.to_string()) @@ -566,8 +559,8 @@ impl<'a> ParseError<'a> { } /// Emits a summary of the error to standard error stream. - pub fn emit_to_stderr(&self) { - let files = SimpleFile::new("wgsl", self.source); + pub fn emit_to_stderr(&self, source: &str) { + let files = SimpleFile::new("wgsl", source); let config = codespan_reporting::term::Config::default(); let writer = StandardStream::stderr(ColorChoice::Always); term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) @@ -575,8 +568,8 @@ impl<'a> ParseError<'a> { } /// Emits a summary of the error to a string. - pub fn emit_to_string(&self) -> String { - let files = SimpleFile::new("wgsl", self.source); + pub fn emit_to_string(&self, source: &str) -> String { + let files = SimpleFile::new("wgsl", source); let config = codespan_reporting::term::Config::default(); let mut writer = StringErrorBuffer::new(); term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); @@ -585,8 +578,8 @@ impl<'a> ParseError<'a> { /// Returns the 1-based line number and column of the first label in the /// error message. - pub fn location(&self) -> (usize, usize) { - let files = SimpleFile::new("wgsl", self.source); + pub fn location(&self, source: &str) -> (usize, usize) { + let files = SimpleFile::new("wgsl", source); match self.labels.get(0) { Some(label) => { let location = files @@ -599,13 +592,13 @@ impl<'a> ParseError<'a> { } } -impl<'a> std::fmt::Display for ParseError<'a> { +impl std::fmt::Display for ParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.message) } } -impl<'a> std::error::Error for ParseError<'a> { +impl std::error::Error for ParseError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } @@ -2730,7 +2723,7 @@ impl Parser { } } - pub fn parse<'a>(&mut self, source: &'a str) -> Result> { + pub fn parse(&mut self, source: &str) -> Result { self.scopes.clear(); self.lookup_type.clear(); self.layouter.clear(); diff --git a/tests/errors.rs b/tests/errors.rs index 13bf5f1d8..9bfefc407 100644 --- a/tests/errors.rs +++ b/tests/errors.rs @@ -2,7 +2,7 @@ fn check(input: &str, snapshot: &str) { let output = naga::front::wgsl::parse_str(input) .expect_err("expected parser error") - .emit_to_string(); + .emit_to_string(input); if output != snapshot { for diff in diff::lines(&output, snapshot) { match diff { From 3537bffad3e357ea5e4a8ae9b06daac0597ae303 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 3 May 2021 01:38:28 +0300 Subject: [PATCH 0784/2212] [glsl-out] Fix scalar arrays writing --- src/back/glsl/mod.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 31533615a..990f6058f 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1119,8 +1119,14 @@ impl<'a, W: Write> Writer<'a, W> { match self.module.types[member.ty].inner { TypeInner::Array { base, .. } => { // GLSL arrays are written as `type name[size]` + let ty_name = match self.module.types[base].inner { + // Write scalar type by backend so as not to depend on the front-end implementation + // Name returned from frontend can be generated (type1, float1, etc.) + TypeInner::Scalar { kind, width } => glsl_scalar(kind, width)?.full, + _ => &self.names[&NameKey::Type(base)], + }; + // Write `type` and `name` - let ty_name = &self.names[&NameKey::Type(base)]; write!(self.out, "{}", ty_name)?; write!( self.out, From bb7ebed23a0cdd3cf7d62b927f3a4483f90d82d2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 3 May 2021 00:50:00 -0400 Subject: [PATCH 0785/2212] [spv-in] null initialization for matrices --- src/back/glsl/mod.rs | 2 +- src/front/spv/mod.rs | 47 ++++++++++++++++++++++++++++++-------------- 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 990f6058f..4f63ab8e8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1121,7 +1121,7 @@ impl<'a, W: Write> Writer<'a, W> { // GLSL arrays are written as `type name[size]` let ty_name = match self.module.types[base].inner { // Write scalar type by backend so as not to depend on the front-end implementation - // Name returned from frontend can be generated (type1, float1, etc.) + // Name returned from frontend can be generated (type1, float1, etc.) TypeInner::Scalar { kind, width } => glsl_scalar(kind, width)?.full, _ => &self.names[&NameKey::Type(base)], }; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a4a696acd..46ac09ea6 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3143,9 +3143,8 @@ impl> Parser { fn generate_null_constant( &mut self, constants: &mut Arena, - types: &Arena, + types: &mut Arena, ty: Handle, - inner: &crate::TypeInner, ) -> Result { fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { crate::ConstantInner::Scalar { @@ -3159,7 +3158,7 @@ impl> Parser { } } - let inner = match *inner { + let inner = match types[ty].inner { crate::TypeInner::Scalar { kind, width } => make_scalar_inner(kind, width), crate::TypeInner::Vector { size, kind, width } => { let mut components = Vec::with_capacity(size as usize); @@ -3172,22 +3171,45 @@ impl> Parser { } crate::ConstantInner::Composite { ty, components } } + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + let vector_ty = types.fetch_or_append(crate::Type { + name: None, + inner: crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + size: rows, + width, + }, + }); + let vector_inner = self.generate_null_constant(constants, types, vector_ty)?; + let vector_handle = constants.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner: vector_inner, + }); + crate::ConstantInner::Composite { + ty, + components: vec![vector_handle; columns as usize], + } + } crate::TypeInner::Struct { ref members, .. } => { let mut components = Vec::with_capacity(members.len()); - for field in members { - let ty_inner = &types[field.ty].inner; - let inner = - self.generate_null_constant(constants, types, field.ty, ty_inner)?; + // copy out the types to avoid borrowing `members` + let member_tys = members.iter().map(|member| member.ty).collect::>(); + for member_ty in member_tys { + let inner = self.generate_null_constant(constants, types, member_ty)?; components.push(constants.fetch_or_append(crate::Constant { name: None, specialization: None, inner, })); } - crate::ConstantInner::Composite { ty, components } } - //TODO: handle matrices, arrays + //TODO: arrays ref other => { log::warn!("null constant type {:?}", other); return Err(Error::UnsupportedType(ty)); @@ -3208,12 +3230,7 @@ impl> Parser { let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; - let inner = self.generate_null_constant( - &mut module.constants, - &module.types, - ty, - &module.types[ty].inner, - )?; + let inner = self.generate_null_constant(&mut module.constants, &mut module.types, ty)?; self.lookup_constant.insert( id, From b8649b3848c69c1274b629a58cf743040e095fb7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 2 May 2021 21:41:09 -0400 Subject: [PATCH 0786/2212] Fix struct layouts for WGSL and SPIRV --- src/front/spv/mod.rs | 48 ++++++++++++++++++++++++++++--------------- src/front/wgsl/mod.rs | 5 ++++- tests/out/skybox.msl | 2 +- 3 files changed, 36 insertions(+), 19 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 46ac09ea6..052120c81 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -191,6 +191,28 @@ impl crate::ImageDimension { } } +//TODO: should this be shared with `crate::proc::wgsl::layout` logic? +fn get_alignment(ty: Handle, arena: &Arena) -> crate::Alignment { + use crate::TypeInner as Ti; + match arena[ty].inner { + Ti::Scalar { width, .. } => crate::Alignment::new(width as u32).unwrap(), + Ti::Vector { size, width, .. } + | Ti::Matrix { + rows: size, width, .. + } => { + let count = if size >= crate::VectorSize::Tri { 4 } else { 2 }; + crate::Alignment::new((count * width) as u32).unwrap() + } + Ti::Pointer { .. } | Ti::ValuePointer { .. } => crate::Alignment::new(1).unwrap(), + Ti::Array { stride, .. } => crate::Alignment::new(stride).unwrap(), + Ti::Struct { ref level, .. } => match *level { + crate::StructLevel::Root => crate::Alignment::new(1).unwrap(), + crate::StructLevel::Normal { alignment } => alignment, + }, + Ti::Image { .. } | Ti::Sampler { .. } => crate::Alignment::new(1).unwrap(), + } +} + type MemberIndex = u32; #[derive(Clone, Debug, Default, PartialEq)] @@ -2827,6 +2849,7 @@ impl> Parser { let parent_decor = self.future_decor.remove(&id); let block_decor = parent_decor.as_ref().and_then(|decor| decor.block.clone()); + let mut struct_alignment = crate::Alignment::new(1).unwrap(); let mut members = Vec::::with_capacity(inst.wc as usize - 2); let mut member_lookups = Vec::with_capacity(members.capacity()); for i in 0..u32::from(inst.wc) - 2 { @@ -2843,17 +2866,8 @@ impl> Parser { }); let binding = decor.io_binding().ok(); - let offset = match decor.offset { - Some(offset) => offset, - None => match members.last() { - Some(member) => { - //TODO: is this needed? - // If offsets are required, we can just put 0 here - member.offset + module.types[member.ty].inner.span(&module.constants) - } - None => 0, - }, - }; + // I/O structs don't have to have offsets, others do + let offset = decor.offset.unwrap_or(0); if let crate::TypeInner::Matrix { columns: _, @@ -2868,6 +2882,9 @@ impl> Parser { } } + let alignment = get_alignment(ty, &module.types); + struct_alignment = struct_alignment.max(alignment); + members.push(crate::StructMember { name: decor.name, ty, @@ -2876,22 +2893,19 @@ impl> Parser { }); } - //TODO: we should be able to do better than this. - const STRUCT_ALIGNMENT: u32 = 16; - let inner = crate::TypeInner::Struct { level: match block_decor { Some(_) => crate::StructLevel::Root, None => crate::StructLevel::Normal { - alignment: crate::Alignment::new(STRUCT_ALIGNMENT).unwrap(), + alignment: struct_alignment, }, }, span: match members.last() { Some(member) => { let end = member.offset + module.types[member.ty].inner.span(&module.constants); - ((end - 1) | (STRUCT_ALIGNMENT - 1)) + 1 + ((end - 1) | (struct_alignment.get() - 1)) + 1 } - None => STRUCT_ALIGNMENT, + None => 4, //do we support this? }, members, }; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 201509ff0..53a53f51a 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1603,7 +1603,10 @@ impl Parser { let name = match lexer.next() { (Token::Word(word), _) => word, - (Token::Paren('}'), _) => return Ok((members, offset, alignment)), + (Token::Paren('}'), _) => { + let span = layout::Layouter::round_up(alignment, offset); + return Ok((members, span, alignment)); + } other => return Err(Error::Unexpected(other, "field name")), }; lexer.expect(Token::Separator(':'))?; diff --git a/tests/out/skybox.msl b/tests/out/skybox.msl index 6b5409773..c3ba81213 100644 --- a/tests/out/skybox.msl +++ b/tests/out/skybox.msl @@ -3,7 +3,7 @@ struct VertexOutput { metal::float4 position; - packed_float3 uv; + metal::float3 uv; }; struct Data { metal::float4x4 proj_inv; From dbfc11a196348d738d98796563e743738f9d5416 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 3 May 2021 14:07:48 +0300 Subject: [PATCH 0787/2212] [glsl-out] Fix writing identifiers starting with gl_ --- src/back/glsl/mod.rs | 65 +++++++++++++++++++++++------------------ src/back/hlsl/writer.rs | 2 +- src/back/msl/writer.rs | 2 +- src/back/wgsl/writer.rs | 2 +- src/proc/namer.rs | 26 +++++++++++++---- 5 files changed, 61 insertions(+), 36 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 4f63ab8e8..0bb6e3d87 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -363,7 +363,7 @@ impl<'a, W: Write> Writer<'a, W> { // Generate a map with names required to write the module let mut names = FastHashMap::default(); - Namer::default().reset(module, keywords::RESERVED_KEYWORDS, &mut names); + Namer::default().reset(module, keywords::RESERVED_KEYWORDS, &["gl_"], &mut names); // Build the instance let mut this = Self { @@ -495,15 +495,8 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "layout({}) ", glsl_storage_format(format))?; } - // Write the storage access modifier - // - // glsl allows adding both `readonly` and `writeonly` but this means that - // they can only be used to query information about the image which isn't what - // we want here so when storage access is both `LOAD` and `STORE` add no modifiers - if global.storage_access == StorageAccess::LOAD { - write!(self.out, "readonly ")?; - } else if global.storage_access == StorageAccess::STORE { - write!(self.out, "writeonly ")?; + if let Some(storage_access) = glsl_storage_access(global.storage_access) { + write!(self.out, "{} ", storage_access)?; } // All images in glsl are `uniform` @@ -741,20 +734,21 @@ impl<'a, W: Write> Writer<'a, W> { handle: Handle, global: &GlobalVariable, ) -> BackendResult { - // Write the storage access modifier - // - // glsl allows adding both `readonly` and `writeonly` but this means that - // they can only be used to query information about the resource which isn't what - // we want here so when storage access is both `LOAD` and `STORE` add no modifiers - if global.storage_access == StorageAccess::LOAD { - write!(self.out, "readonly ")?; - } else if global.storage_access == StorageAccess::STORE { - write!(self.out, "writeonly ")?; + if let Some(storage_access) = glsl_storage_access(global.storage_access) { + write!(self.out, "{} ", storage_access)?; } // Write the storage class // Trailing space is important - write!(self.out, "{} ", glsl_storage_class(global.class))?; + if let Some(storage_class) = glsl_storage_class(global.class) { + write!(self.out, "{} ", storage_class)?; + } else if let TypeInner::Struct { + level: crate::StructLevel::Root, + .. + } = self.module.types[global.ty].inner + { + write!(self.out, "struct ")?; + } // Write the type // `write_type` adds no leading or trailing spaces @@ -2206,15 +2200,15 @@ fn glsl_built_in(built_in: BuiltIn, output: bool) -> &'static str { } /// Helper function that returns the string corresponding to the storage class -fn glsl_storage_class(class: StorageClass) -> &'static str { +fn glsl_storage_class(class: StorageClass) -> Option<&'static str> { match class { - StorageClass::Function => "", - StorageClass::Private => "", - StorageClass::Storage => "buffer", - StorageClass::Uniform => "uniform", - StorageClass::Handle => "uniform", - StorageClass::WorkGroup => "shared", - StorageClass::PushConstant => "", + StorageClass::Function => None, + StorageClass::Private => None, + StorageClass::Storage => Some("buffer"), + StorageClass::Uniform => Some("uniform"), + StorageClass::Handle => Some("uniform"), + StorageClass::WorkGroup => Some("shared"), + StorageClass::PushConstant => None, } } @@ -2283,3 +2277,18 @@ fn glsl_storage_format(format: StorageFormat) -> &'static str { StorageFormat::Rgba32Float => "rgba32f", } } + +/// Helper function that return the glsl storage access string of [`StorageAccess`](crate::StorageAccess) +/// +/// glsl allows adding both `readonly` and `writeonly` but this means that +/// they can only be used to query information about the resource which isn't what +/// we want here so when storage access is both `LOAD` and `STORE` add no modifiers +fn glsl_storage_access(storage_access: StorageAccess) -> Option<&'static str> { + if storage_access == StorageAccess::LOAD { + Some("readonly") + } else if storage_access == StorageAccess::STORE { + Some("writeonly") + } else { + None + } +} diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 61f680ded..a0030a92b 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -23,7 +23,7 @@ impl Writer { pub fn write(&mut self, module: &crate::Module) -> Result<(), Error> { self.names.clear(); - self.namer.reset(module, RESERVED, &mut self.names); + self.namer.reset(module, RESERVED, &[], &mut self.names); for (ep_index, ep) in module.entry_points.iter().enumerate() { let fun = &ep.function; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 66951b44b..692e5010d 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1468,7 +1468,7 @@ impl Writer { pipeline_options: &PipelineOptions, ) -> Result { self.names.clear(); - self.namer.reset(module, RESERVED, &mut self.names); + self.namer.reset(module, RESERVED, &[], &mut self.names); self.runtime_sized_buffers.clear(); writeln!(self.out, "#include ")?; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index f3cbeb80b..1aa412f64 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -77,7 +77,7 @@ impl Writer { pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { self.names.clear(); - self.namer.reset(module, RESERVED, &mut self.names); + self.namer.reset(module, RESERVED, &[], &mut self.names); // Write all constants for (_, constant) in module.constants.iter() { diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 7f62ff170..5e8ba6132 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -22,10 +22,11 @@ pub enum NameKey { #[derive(Default)] pub struct Namer { unique: FastHashMap, + reserved_prefixes: Vec, } impl Namer { - fn sanitize(string: &str) -> String { + fn sanitize(&self, string: &str) -> String { let mut base = string .chars() .skip_while(|c| c.is_numeric()) @@ -37,11 +38,18 @@ impl Namer { Some(c) if !c.is_numeric() => {} _ => base.push('_'), }; + + for prefix in &self.reserved_prefixes { + if base.starts_with(prefix) { + return format!("gen_{}", base); + } + } + base } pub fn call(&mut self, label_raw: &str) -> String { - let base = Self::sanitize(label_raw); + let base = self.sanitize(label_raw); match self.unique.entry(base) { Entry::Occupied(mut e) => { *e.get_mut() += 1; @@ -65,12 +73,20 @@ impl Namer { pub fn reset( &mut self, module: &crate::Module, - reserved: &[&str], + reserved_keywords: &[&str], + reserved_prefixes: &[&str], output: &mut FastHashMap, ) { + self.reserved_prefixes.clear(); + self.reserved_prefixes + .extend(reserved_prefixes.iter().map(|string| string.to_string())); + self.unique.clear(); - self.unique - .extend(reserved.iter().map(|string| (string.to_string(), 0))); + self.unique.extend( + reserved_keywords + .iter() + .map(|string| (string.to_string(), 0)), + ); let mut temp = String::new(); for (ty_handle, ty) in module.types.iter() { From f6da21f8ddc0fd3cb8851e02cc5901dc43de3da7 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Mon, 3 May 2021 21:51:44 -0400 Subject: [PATCH 0788/2212] Unify back::msl push constants map and sizes buffer (#825) * Unify back::msl push constants map and sizes buffer * Fix clippy warning * Actually remove PushConstantsMap * Update snapshots --- src/back/msl/mod.rs | 67 ++++++++++++++++++++++++++++++--------- src/back/msl/writer.rs | 20 ++++-------- tests/in/access.param.ron | 6 ++-- tests/in/boids.param.ron | 5 ++- tests/in/skybox.param.ron | 2 +- tests/out/boids.msl | 2 +- 6 files changed, 69 insertions(+), 33 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 0579dcfec..a905a3e36 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -71,13 +71,27 @@ pub type BindingMap = std::collections::BTreeMap; #[derive(Clone, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] -pub struct PushConstantsMap { +pub struct PerStageResources { #[cfg_attr(feature = "deserialize", serde(default))] - pub vs_buffer: Option, + pub push_constant_buffer: Option, + + /// The slot of a buffer that contains an array of `u32`, + /// one for the size of each bound buffer that contains a runtime array, + /// in order of [`GlobalVariable`] declarations. #[cfg_attr(feature = "deserialize", serde(default))] - pub fs_buffer: Option, + pub sizes_buffer: Option, +} + +#[derive(Clone, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct PerStageMap { #[cfg_attr(feature = "deserialize", serde(default))] - pub cs_buffer: Option, + pub vs: PerStageResources, + #[cfg_attr(feature = "deserialize", serde(default))] + pub fs: PerStageResources, + #[cfg_attr(feature = "deserialize", serde(default))] + pub cs: PerStageResources, } enum ResolvedBinding { @@ -131,6 +145,8 @@ pub enum EntryPointError { MissingBinding(BindSource), #[error("mapping for push constants at stage {0:?} is missing")] MissingPushConstants(crate::ShaderStage), + #[error("mapping for sizes buffer for stage {0:?} is missing")] + MissingSizesBuffer(crate::ShaderStage), } #[derive(Clone, Copy, Debug)] @@ -149,18 +165,14 @@ pub struct Options { pub lang_version: (u8, u8), /// Binding model mapping to Metal. pub binding_map: BindingMap, - /// Push constants mapping to Metal. - pub push_constants_map: PushConstantsMap, + /// Map of per-stage resources (e.g. push constants) to slots + pub per_stage_map: PerStageMap, /// Samplers to be inlined into the code. pub inline_samplers: Vec, /// Make it possible to link different stages via SPIRV-Cross. pub spirv_cross_compatibility: bool, /// Don't panic on missing bindings, instead generate invalid MSL. pub fake_missing_bindings: bool, - /// The slot of a buffer that contains an array of `u32`, - /// one for the size of each bound buffer that contains a runtime array, - /// in order of [`GlobalVariable`] declarations. - pub sizes_buffer_binding: Option, } impl Default for Options { @@ -168,11 +180,10 @@ impl Default for Options { Options { lang_version: (1, 0), binding_map: BindingMap::default(), - push_constants_map: PushConstantsMap::default(), + per_stage_map: PerStageMap::default(), inline_samplers: Vec::new(), spirv_cross_compatibility: false, fake_missing_bindings: true, - sizes_buffer_binding: None, } } } @@ -263,9 +274,9 @@ impl Options { stage: crate::ShaderStage, ) -> Result { let slot = match stage { - crate::ShaderStage::Vertex => self.push_constants_map.vs_buffer, - crate::ShaderStage::Fragment => self.push_constants_map.fs_buffer, - crate::ShaderStage::Compute => self.push_constants_map.cs_buffer, + crate::ShaderStage::Vertex => self.per_stage_map.vs.push_constant_buffer, + crate::ShaderStage::Fragment => self.per_stage_map.fs.push_constant_buffer, + crate::ShaderStage::Compute => self.per_stage_map.cs.push_constant_buffer, }; match slot { Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { @@ -282,6 +293,32 @@ impl Options { None => Err(EntryPointError::MissingPushConstants(stage)), } } + + fn resolve_sizes_buffer( + &self, + stage: crate::ShaderStage, + ) -> Result { + let slot = match stage { + crate::ShaderStage::Vertex => self.per_stage_map.vs.sizes_buffer, + crate::ShaderStage::Fragment => self.per_stage_map.fs.sizes_buffer, + crate::ShaderStage::Compute => self.per_stage_map.cs.sizes_buffer, + }; + + match slot { + Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { + buffer: Some(slot), + texture: None, + sampler: None, + mutable: false, + })), + None if self.fake_missing_bindings => Ok(ResolvedBinding::User { + prefix: "fake", + index: 0, + interpolation: None, + }), + None => Err(EntryPointError::MissingSizesBuffer(stage)), + } + } } impl ResolvedBinding { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 692e5010d..04c7fb510 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,6 +1,6 @@ use super::{ - keywords::RESERVED, sampler as sm, BindTarget, Error, LocationMode, Options, PipelineOptions, - ResolvedBinding, TranslationInfo, + keywords::RESERVED, sampler as sm, Error, LocationMode, Options, PipelineOptions, + TranslationInfo, }; use crate::{ arena::{Arena, Handle}, @@ -2133,17 +2133,11 @@ impl Writer { } if !self.runtime_sized_buffers.is_empty() { - let resolved = if let Some(slot) = options.sizes_buffer_binding { - ResolvedBinding::Resource(BindTarget { - buffer: Some(slot), - mutable: false, - ..Default::default() - }) - } else { - ResolvedBinding::User { - prefix: "fake", - index: 0, - interpolation: None, + let resolved = match options.resolve_sizes_buffer(ep.stage) { + Ok(resolved) => resolved, + Err(e) => { + info.entry_point_names.push(Err(e)); + continue; } }; diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 0464ddf32..e8c788d60 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -9,11 +9,13 @@ binding_map: { (stage: Vertex, group: 0, binding: 0): (buffer: Some(0), mutable: true), }, - push_constants_map: ( + per_stage_map: ( + vs: ( + sizes_buffer: Some(24), + ), ), inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, - sizes_buffer_binding: Some(24), ), ) diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index 551fecede..450770cac 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -12,7 +12,10 @@ (stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true), (stage: Compute, group: 0, binding: 2): (buffer: Some(2), mutable: true), }, - push_constants_map: ( + per_stage_map: ( + cs: ( + sizes_buffer: Some(3), + ) ), inline_samplers: [], spirv_cross_compatibility: false, diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index aae6af7ca..d4510ffcb 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -12,7 +12,7 @@ (stage: Fragment, group: 0, binding: 1): (texture: Some(0)), (stage: Fragment, group: 0, binding: 2): (sampler: Some(Inline(0))), }, - push_constants_map: ( + per_stage_map: ( ), inline_samplers: [ ( diff --git a/tests/out/boids.msl b/tests/out/boids.msl index 1deab9f73..c49bff960 100644 --- a/tests/out/boids.msl +++ b/tests/out/boids.msl @@ -32,7 +32,7 @@ kernel void main1( , constant SimParams& params [[buffer(0)]] , constant Particles& particlesSrc [[buffer(1)]] , device Particles& particlesDst [[buffer(2)]] -, constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] +, constant _mslBufferSizes& _buffer_sizes [[buffer(3)]] ) { metal::float2 vPos; metal::float2 vVel; From 9fbe68131635793cb0ed79049ec6b87b58d6ea41 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 3 May 2021 23:17:56 +0300 Subject: [PATCH 0789/2212] [spv-in] Give entry point function the same name as entry point itself --- src/front/spv/function.rs | 2 +- tests/out/shadow.ron | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index c3fae7196..856ffc076 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -189,7 +189,7 @@ impl> super::Parser { if let Some(ep) = self.lookup_entry_point.remove(&fun_id) { // create a wrapping function let mut function = crate::Function { - name: None, + name: Some(format!("{}_wrap", ep.name)), arguments: Vec::new(), result: None, local_variables: Arena::new(), diff --git a/tests/out/shadow.ron b/tests/out/shadow.ron index e5d646fa9..91516dd79 100644 --- a/tests/out/shadow.ron +++ b/tests/out/shadow.ron @@ -1512,7 +1512,7 @@ early_depth_test: None, workgroup_size: (0, 0, 0), function: ( - name: None, + name: Some("fs_main_wrap"), arguments: [ ( name: Some("in_normal_fs"), From 1476ef84ffa2b450c2a2630b0afacf5551662847 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 4 May 2021 12:59:27 +0000 Subject: [PATCH 0790/2212] [spv-in] Fix empty gl_PerVertex name --- src/front/spv/mod.rs | 14 +++++++++++++- tests/out/quad-vert.msl | 10 +++++----- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 052120c81..c7b77830d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -363,6 +363,7 @@ struct Assignment { value: Handle, } +#[derive(PartialEq)] enum ExtendedClass { Global(crate::StorageClass), Input, @@ -3303,7 +3304,7 @@ impl> Parser { } else { None }; - let dec = self.future_decor.remove(&id).unwrap_or_default(); + let mut dec = self.future_decor.remove(&id).unwrap_or_default(); let original_ty = self.lookup_type.lookup(type_id)?.handle; let (effective_ty, is_storage) = match module.types[original_ty].inner { @@ -3322,6 +3323,17 @@ impl> Parser { map_storage_class(storage_class)? }; + // Fix empty name for gl_PerVertex struct generated by glslang + if let crate::TypeInner::Pointer { .. } = module.types[original_ty].inner { + if ext_class == ExtendedClass::Input || ext_class == ExtendedClass::Output { + if let Some(ref dec_name) = dec.name { + if dec_name.is_empty() { + dec.name = Some("perVertexStruct".to_string()) + } + } + } + } + let (inner, var) = match ext_class { ExtendedClass::Global(class) => { let storage_access = if is_storage { diff --git a/tests/out/quad-vert.msl b/tests/out/quad-vert.msl index 584a9a748..d7363aad4 100644 --- a/tests/out/quad-vert.msl +++ b/tests/out/quad-vert.msl @@ -20,12 +20,12 @@ struct type10 { void main1( thread metal::float2& v_uv, thread metal::float2 const& a_uv, - thread gl_PerVertex& _, + thread gl_PerVertex& perVertexStruct, thread metal::float2 const& a_pos ) { v_uv = a_uv; metal::float2 _e13 = a_pos; - _.gl_Position = metal::float4(_e13.x, _e13.y, 0.0, 1.0); + perVertexStruct.gl_Position = metal::float4(_e13.x, _e13.y, 0.0, 1.0); return; } @@ -44,13 +44,13 @@ vertex main2Output main2( ) { metal::float2 v_uv = {}; metal::float2 a_uv = {}; - gl_PerVertex _ = {}; + gl_PerVertex perVertexStruct = {}; metal::float2 a_pos = {}; const auto a_uv1 = varyings.a_uv1; const auto a_pos1 = varyings.a_pos1; a_uv = a_uv1; a_pos = a_pos1; - main1(v_uv, a_uv, _, a_pos); - const auto _tmp = type10 {v_uv, _.gl_Position, _.gl_PointSize, _.gl_ClipDistance}; + main1(v_uv, a_uv, perVertexStruct, a_pos); + const auto _tmp = type10 {v_uv, perVertexStruct.gl_Position, perVertexStruct.gl_PointSize, perVertexStruct.gl_ClipDistance}; return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1.inner[0]} }; } From b3c29871a7fc2637e10653d214afbf589f1feedf Mon Sep 17 00:00:00 2001 From: Ashley Date: Tue, 4 May 2021 18:34:50 +0200 Subject: [PATCH 0791/2212] [spv-in] Handle `Op::LogicalEqual` --- src/front/spv/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index c7b77830d..4189405bf 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1874,6 +1874,7 @@ impl> Parser { | Op::FUnordLessThanEqual | Op::FOrdGreaterThanEqual | Op::FUnordGreaterThanEqual + | Op::LogicalEqual | Op::LogicalNotEqual => { inst.expect(5)?; let operator = map_binary_operator(inst.op)?; From 04c639c3f10f3e99084b209897e73672cfd7306c Mon Sep 17 00:00:00 2001 From: Ashley Date: Tue, 4 May 2021 19:07:13 +0200 Subject: [PATCH 0792/2212] [spv-in] Handle `Glo::MatrixInverse` --- src/front/spv/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 4189405bf..ff23afc17 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1784,6 +1784,7 @@ impl> Parser { Glo::Log2 => Mf::Log2, Glo::Sqrt => Mf::Sqrt, Glo::InverseSqrt => Mf::InverseSqrt, + Glo::MatrixInverse => Mf::Inverse, Glo::Determinant => Mf::Determinant, Glo::Modf => Mf::Modf, Glo::FMin | Glo::UMin | Glo::SMin | Glo::NMin => Mf::Min, From 3ffc361724bdfe472227a8f78bde87412faab307 Mon Sep 17 00:00:00 2001 From: Ashley Date: Tue, 4 May 2021 18:50:37 +0200 Subject: [PATCH 0793/2212] [spv-in,spv-out] Handle outer product --- src/back/spv/writer.rs | 9 ++++++++- src/front/spv/mod.rs | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d6c1a6cd1..795c80a08 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1815,6 +1815,13 @@ impl Writer { arg0_id, arg1_id, )), + Mf::Outer => MathOp::Custom(Instruction::binary( + spirv::Op::OuterProduct, + result_type_id, + id, + arg0_id, + arg1_id, + )), Mf::Cross => MathOp::Ext(spirv::GLOp::Cross), Mf::Distance => MathOp::Ext(spirv::GLOp::Distance), Mf::Length => MathOp::Ext(spirv::GLOp::Length), @@ -1848,7 +1855,7 @@ impl Writer { arg0_id, )), Mf::Determinant => MathOp::Ext(spirv::GLOp::Determinant), - Mf::Outer | Mf::ReverseBits | Mf::CountOneBits => { + Mf::ReverseBits | Mf::CountOneBits => { log::error!("unimplemented math function {:?}", fun); return Err(Error::FeatureNotImplemented("math function")); } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index ff23afc17..0d0fbccb7 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1426,6 +1426,29 @@ impl> Parser { }, ); } + Op::OuterProduct => { + inst.expect(5)?; + + let result_type_id = self.next()?; + let result_id = self.next()?; + let left_id = self.next()?; + let right_id = self.next()?; + let left_lexp = self.lookup_expression.lookup(left_id)?; + let right_lexp = self.lookup_expression.lookup(right_id)?; + let expr = crate::Expression::Math { + fun: crate::MathFunction::Outer, + arg: left_lexp.handle, + arg1: Some(right_lexp.handle), + arg2: None, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: expressions.append(expr), + type_id: result_type_id, + }, + ); + } // Bitwise instructions Op::Not => { inst.expect(4)?; From 9fe75ed7f1cf54f52c0b00763039f15712f4f398 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 3 May 2021 00:18:35 -0400 Subject: [PATCH 0794/2212] Barriers --- src/back/dot/mod.rs | 1 + src/back/glsl/mod.rs | 12 +- src/back/msl/writer.rs | 16 +++ src/back/spv/instructions.rs | 14 ++ src/back/spv/writer.rs | 132 ++++++++--------- src/front/spv/error.rs | 50 ++++--- src/front/spv/mod.rs | 37 +++++ src/front/wgsl/mod.rs | 11 ++ src/lib.rs | 17 ++- src/proc/mod.rs | 24 ++++ src/proc/terminator.rs | 1 + src/valid/analyzer.rs | 7 + src/valid/function.rs | 63 +++++--- src/valid/mod.rs | 1 + tests/in/control-flow.param.ron | 7 + tests/in/control-flow.wgsl | 5 + tests/out/access.spvasm | 2 +- tests/out/boids.spvasm | 34 ++--- tests/out/collatz.spvasm | 14 +- tests/out/control-flow.Compute.glsl | 14 ++ tests/out/control-flow.msl | 13 ++ tests/out/control-flow.spvasm | 29 ++++ tests/out/image.spvasm | 2 +- tests/out/interpolate.spvasm | 215 ++++++++++++++-------------- tests/out/quad.spvasm | 6 +- tests/out/shadow.spvasm | 160 ++++++++++----------- tests/out/skybox.spvasm | 101 ++++++------- tests/out/texture-array.spvasm | 34 +++-- tests/snapshots.rs | 4 + 29 files changed, 626 insertions(+), 400 deletions(-) create mode 100644 tests/in/control-flow.param.ron create mode 100644 tests/in/control-flow.wgsl create mode 100644 tests/out/control-flow.Compute.glsl create mode 100644 tests/out/control-flow.msl create mode 100644 tests/out/control-flow.spvasm diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 75c619a38..5d529b2a2 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -42,6 +42,7 @@ impl StatementGraph { S::Break => "Break", //TODO: loop context S::Continue => "Continue", //TODO: loop context S::Kill => "Kill", //TODO: link to the beginning + S::Barrier(_flags) => "Barrier", S::Block(ref b) => { let other = self.add(b); self.flow.push((id, other, "")); diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 0bb6e3d87..a67ddd0e9 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1392,9 +1392,15 @@ impl<'a, W: Write> Writer<'a, W> { // This is one of the places were glsl adds to the syntax of C in this case the discard // keyword which ceases all further processing in a fragment shader, it's called OpKill // in spir-v that's why it's called `Statement::Kill` - Statement::Kill => { - write!(self.out, "{}", INDENT.repeat(indent))?; - writeln!(self.out, "discard;")? + Statement::Kill => writeln!(self.out, "{}discard;", INDENT.repeat(indent))?, + // Just issue a memory barrier, ignoring the flags. + Statement::Barrier(flags) => { + if flags.contains(crate::Barrier::WORK_GROUP) { + writeln!(self.out, "{}barrier();", INDENT.repeat(indent))?; + } + if flags.contains(crate::Barrier::STORAGE) { + writeln!(self.out, "{}groupMemoryBarrier();", INDENT.repeat(indent))?; + } } // Stores in glsl are just variable assignments written as `pointer = value;` Statement::Store { pointer, value } => { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 04c7fb510..d72cd5c61 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1347,6 +1347,22 @@ impl Writer { crate::Statement::Kill => { writeln!(self.out, "{}{}::discard_fragment();", level, NAMESPACE)?; } + crate::Statement::Barrier(flags) => { + if flags.contains(crate::Barrier::STORAGE) { + writeln!( + self.out, + "{}{}::threadgroup_barrier({}::mem_flags::mem_device);", + level, NAMESPACE, NAMESPACE, + )?; + } + if flags.contains(crate::Barrier::WORK_GROUP) { + writeln!( + self.out, + "{}{}::threadgroup_barrier({}::mem_flags::mem_threadgroup);", + level, NAMESPACE, NAMESPACE, + )?; + } + } crate::Statement::Store { pointer, value } => { // we can't assign fixed-size arrays let pointer_info = &context.expression.info[pointer]; diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 0b3b42b42..21948d1bc 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -853,4 +853,18 @@ impl super::Instruction { // // Primitive Instructions // + + // Barriers + + pub(super) fn control_barrier( + exec_scope_id: Word, + mem_scope_id: Word, + semantics_id: Word, + ) -> Self { + let mut instruction = Self::new(Op::ControlBarrier); + instruction.add_operand(exec_scope_id); + instruction.add_operand(mem_scope_id); + instruction.add_operand(semantics_id); + instruction + } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 795c80a08..949b0b826 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -12,7 +12,6 @@ use std::{collections::hash_map::Entry, ops}; use thiserror::Error; const BITS_PER_BYTE: crate::Bytes = 8; -const CACHED_CONSTANT_INDICES: usize = 8; #[derive(Clone, Debug, Error)] pub enum Error { @@ -295,7 +294,7 @@ pub struct Writer { lookup_function_type: crate::FastHashMap, lookup_function_call: crate::FastHashMap, Word>, constant_ids: Vec, - index_constant_ids: Vec, + cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>, global_variables: Vec, cached: CachedExpressions, gl450_ext_inst_id: Word, @@ -336,7 +335,7 @@ impl Writer { lookup_function_type: crate::FastHashMap::default(), lookup_function_call: crate::FastHashMap::default(), constant_ids: Vec::new(), - index_constant_ids: Vec::new(), + cached_constants: crate::FastHashMap::default(), global_variables: Vec::new(), cached: CachedExpressions::default(), gl450_ext_inst_id, @@ -415,41 +414,6 @@ impl Writer { }) } - fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word { - let id = self.id_gen.next(); - let instruction = Instruction::constant(type_id, id, value); - instruction.to_words(&mut self.logical_layout.declarations); - id - } - - fn get_index_constant( - &mut self, - index: Word, - types: &Arena, - ) -> Result { - while self.index_constant_ids.len() <= index as usize { - self.index_constant_ids.push(0); - } - let cached = self.index_constant_ids[index as usize]; - if cached != 0 { - return Ok(cached); - } - - let type_id = self.get_type_id( - types, - LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Sint, - width: 4, - pointer_class: None, - }), - )?; - - let id = self.create_constant(type_id, &[index]); - self.index_constant_ids[index as usize] = id; - Ok(id) - } - fn decorate(&mut self, id: Word, decoration: spirv::Decoration, operands: &[Word]) { self.annotations .push(Instruction::decorate(id, decoration, operands)); @@ -1019,6 +983,29 @@ impl Writer { Ok(id) } + fn get_index_constant( + &mut self, + index: Word, + types: &Arena, + ) -> Result { + self.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4, types) + } + + fn get_constant_scalar( + &mut self, + value: crate::ScalarValue, + width: crate::Bytes, + types: &Arena, + ) -> Result { + if let Some(&id) = self.cached_constants.get(&(value, width)) { + return Ok(id); + } + let id = self.id_gen.next(); + self.write_constant_scalar(id, &value, width, None, types)?; + self.cached_constants.insert((value, width), id); + Ok(id) + } + fn write_constant_scalar( &mut self, id: Word, @@ -1046,17 +1033,6 @@ impl Writer { crate::ScalarValue::Sint(val) => { let words = match width { 4 => { - if debug_name.is_none() - && 0 <= val - && val < CACHED_CONSTANT_INDICES as i64 - && self.index_constant_ids.get(val as usize).unwrap_or(&0) == &0 - { - // cache this as an indexing constant - while self.index_constant_ids.len() <= val as usize { - self.index_constant_ids.push(0); - } - self.index_constant_ids[val as usize] = id; - } solo = [val as u32]; &solo[..] } @@ -2070,13 +2046,9 @@ impl Writer { depth_id, ); - //TODO: cache this! - let zero_id = self.id_gen.next(); - self.write_constant_scalar( - zero_id, - &crate::ScalarValue::Float(0.0), + let zero_id = self.get_constant_scalar( + crate::ScalarValue::Float(0.0), 4, - None, &ir_module.types, )?; @@ -2801,6 +2773,33 @@ impl Writer { crate::Statement::Kill => { block.termination = Some(Instruction::kill()); } + crate::Statement::Barrier(flags) => { + let memory_scope = if flags.contains(crate::Barrier::STORAGE) { + spirv::Scope::Device + } else { + spirv::Scope::Workgroup + }; + let mut semantics = spirv::MemorySemantics::ACQUIRE_RELEASE; + semantics.set( + spirv::MemorySemantics::UNIFORM_MEMORY, + flags.contains(crate::Barrier::STORAGE), + ); + semantics.set( + spirv::MemorySemantics::WORKGROUP_MEMORY, + flags.contains(crate::Barrier::WORK_GROUP), + ); + let exec_scope_id = + self.get_index_constant(spirv::Scope::Workgroup as u32, &ir_module.types)?; + let mem_scope_id = + self.get_index_constant(memory_scope as u32, &ir_module.types)?; + let semantics_id = + self.get_index_constant(semantics.bits(), &ir_module.types)?; + block.body.push(Instruction::control_barrier( + exec_scope_id, + mem_scope_id, + semantics_id, + )); + } crate::Statement::Store { pointer, value } => { let (pointer_id, _) = self.write_expression_pointer( ir_module, @@ -2930,15 +2929,20 @@ impl Writer { match constant.inner { crate::ConstantInner::Composite { .. } => continue, crate::ConstantInner::Scalar { width, ref value } => { - let id = self.id_gen.next(); - self.constant_ids[handle.index()] = id; - self.write_constant_scalar( - id, - value, - width, - constant.name.as_ref(), - &ir_module.types, - )?; + self.constant_ids[handle.index()] = match constant.name { + Some(ref name) => { + let id = self.id_gen.next(); + self.write_constant_scalar( + id, + value, + width, + Some(name), + &ir_module.types, + )?; + id + } + None => self.get_constant_scalar(*value, width, &ir_module.types)?, + }; } } } diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index b1651e847..3a4bc44be 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -9,7 +9,7 @@ pub enum Error { InvalidWordCount, #[error("unknown instruction {0}")] UnknownInstruction(u16), - #[error("unknown capability {0}")] + #[error("unknown capability %{0}")] UnknownCapability(spirv::Word), #[error("unsupported instruction {1:?} at {0:?}")] UnsupportedInstruction(ModuleState, spirv::Op), @@ -19,27 +19,27 @@ pub enum Error { UnsupportedExtension(String), #[error("unsupported extension set {0}")] UnsupportedExtSet(String), - #[error("unsupported extension instantiation set {0}")] + #[error("unsupported extension instantiation set %{0}")] UnsupportedExtInstSet(spirv::Word), - #[error("unsupported extension instantiation {0}")] + #[error("unsupported extension instantiation %{0}")] UnsupportedExtInst(spirv::Word), #[error("unsupported type {0:?}")] UnsupportedType(Handle), - #[error("unsupported execution model {0}")] + #[error("unsupported execution model %{0}")] UnsupportedExecutionModel(spirv::Word), - #[error("unsupported execution mode {0}")] + #[error("unsupported execution mode %{0}")] UnsupportedExecutionMode(spirv::Word), - #[error("unsupported storage class {0}")] + #[error("unsupported storage class %{0}")] UnsupportedStorageClass(spirv::Word), - #[error("unsupported image dimension {0}")] + #[error("unsupported image dimension %{0}")] UnsupportedImageDim(spirv::Word), - #[error("unsupported image format {0}")] + #[error("unsupported image format %{0}")] UnsupportedImageFormat(spirv::Word), - #[error("unsupported builtin {0}")] + #[error("unsupported builtin %{0}")] UnsupportedBuiltIn(spirv::Word), - #[error("unsupported control flow {0}")] + #[error("unsupported control flow %{0}")] UnsupportedControlFlow(spirv::Word), - #[error("unsupported binary operator {0}")] + #[error("unsupported binary operator %{0}")] UnsupportedBinaryOperator(spirv::Word), #[error("unknown binary operator {0:?}")] UnknownBinaryOperator(spirv::Op), @@ -51,25 +51,25 @@ pub enum Error { InvalidOperandCount(spirv::Op, u16), #[error("invalid operand")] InvalidOperand, - #[error("invalid id {0}")] + #[error("invalid id %{0}")] InvalidId(spirv::Word), - #[error("invalid decoration {0}")] + #[error("invalid decoration %{0}")] InvalidDecoration(spirv::Word), - #[error("invalid type width {0}")] + #[error("invalid type width %{0}")] InvalidTypeWidth(spirv::Word), - #[error("invalid sign {0}")] + #[error("invalid sign %{0}")] InvalidSign(spirv::Word), - #[error("invalid inner type {0}")] + #[error("invalid inner type %{0}")] InvalidInnerType(spirv::Word), - #[error("invalid vector size {0}")] + #[error("invalid vector size %{0}")] InvalidVectorSize(spirv::Word), - #[error("invalid access type {0}")] + #[error("invalid access type %{0}")] InvalidAccessType(spirv::Word), #[error("invalid access {0:?}")] InvalidAccess(crate::Expression), - #[error("invalid access index {0}")] + #[error("invalid access index %{0}")] InvalidAccessIndex(spirv::Word), - #[error("invalid binding {0}")] + #[error("invalid binding %{0}")] InvalidBinding(spirv::Word), #[error("invalid global var {0:?}")] InvalidGlobalVar(crate::Expression), @@ -83,9 +83,9 @@ pub enum Error { InvalidVectorType(Handle), #[error("inconsistent comparison sampling {0:?}")] InconsistentComparisonSampling(Handle), - #[error("wrong function result type {0}")] + #[error("wrong function result type %{0}")] WrongFunctionResultType(spirv::Word), - #[error("wrong function argument type {0}")] + #[error("wrong function argument type %{0}")] WrongFunctionArgumentType(spirv::Word), #[error("missing decoration {0:?}")] MissingDecoration(spirv::Decoration), @@ -97,8 +97,12 @@ pub enum Error { InvalidTerminator, #[error("invalid edge classification")] InvalidEdgeClassification, - #[error("recursive function call {0}")] + #[error("recursive function call %{0}")] FunctionCallCycle(spirv::Word), + #[error("invalid barrier scope %{0}")] + InvalidBarrierScope(spirv::Word), + #[error("invalid barrier memory semantics %{0}")] + InvalidBarrierMemorySemantics(spirv::Word), // incomplete implementation errors #[error("unsupported matrix stride {0}")] UnsupportedMatrixStride(spirv::Word), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 0d0fbccb7..5603a53c9 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2094,6 +2094,42 @@ impl> Parser { emitter.start(expressions); } + Op::ControlBarrier => { + inst.expect(4)?; + let exec_scope_id = self.next()?; + let _mem_scope_raw = self.next()?; + let semantics_id = self.next()?; + let exec_scope_const = self.lookup_constant.lookup(exec_scope_id)?; + let semantics_const = self.lookup_constant.lookup(semantics_id)?; + let exec_scope = match const_arena[exec_scope_const.handle].inner { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(raw), + width: _, + } => raw as u32, + _ => return Err(Error::InvalidBarrierScope(exec_scope_id)), + }; + let semantics = match const_arena[semantics_const.handle].inner { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(raw), + width: _, + } => raw as u32, + _ => return Err(Error::InvalidBarrierMemorySemantics(semantics_id)), + }; + if exec_scope == spirv::Scope::Workgroup as u32 { + let mut flags = crate::Barrier::empty(); + flags.set( + crate::Barrier::STORAGE, + semantics & spirv::MemorySemantics::UNIFORM_MEMORY.bits() != 0, + ); + flags.set( + crate::Barrier::WORK_GROUP, + semantics & spirv::MemorySemantics::WORKGROUP_MEMORY.bits() != 0, + ); + block.push(crate::Statement::Barrier(flags)); + } else { + log::warn!("Unsupported barrier execution scope: {}", exec_scope); + } + } _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } }; @@ -2196,6 +2232,7 @@ impl> Parser { | S::Continue | S::Return { .. } | S::Kill + | S::Barrier(_) | S::Store { .. } | S::ImageStore { .. } => {} S::Call { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 53a53f51a..fd22ea52e 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -980,6 +980,7 @@ impl Parser { query: crate::ImageQuery::NumSamples, } } + // other _ => { let handle = match self.parse_local_function_call(lexer, name, ctx.reborrow())? { @@ -2337,6 +2338,16 @@ impl Parser { "break" => block.push(crate::Statement::Break), "continue" => block.push(crate::Statement::Continue), "discard" => block.push(crate::Statement::Kill), + "storageBarrier" => { + lexer.expect(Token::Paren('('))?; + lexer.expect(Token::Paren(')'))?; + block.push(crate::Statement::Barrier(crate::Barrier::STORAGE)); + } + "workgroupBarrier" => { + lexer.expect(Token::Paren('('))?; + lexer.expect(Token::Paren(')'))?; + block.push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP)); + } "textureStore" => { emitter.start(context.expressions); lexer.open_arguments()?; diff --git a/src/lib.rs b/src/lib.rs index d51828e5b..40027b4cf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -444,7 +444,7 @@ pub struct Constant { } /// A literal scalar value, used in constants. -#[derive(Debug, PartialEq, Clone, Copy, PartialOrd)] +#[derive(Debug, Clone, Copy, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum ScalarValue { @@ -696,6 +696,19 @@ pub enum SwizzleComponent { W = 3, } +bitflags::bitflags! { + /// Control barrier flags. + #[cfg_attr(feature = "serialize", derive(Serialize))] + #[cfg_attr(feature = "deserialize", derive(Deserialize))] + #[derive(Default)] + pub struct Barrier: u32 { + /// Barrier affects all `StorageClass::Storage` accesses. + const STORAGE = 0x1; + /// Barrier affects all `StorageClass::WorkGroup` accesses. + const WORK_GROUP = 0x2; + } +} + /// An expression that can be evaluated to obtain a value. /// /// This is a Single Static Assignment (SSA) scheme similar to SPIR-V. @@ -871,6 +884,8 @@ pub enum Statement { Return { value: Option> }, /// Aborts the current shader execution. Kill, + /// Synchronize accesses within the work group. + Barrier(Barrier), /// Stores a value at an address. /// /// This statement is a barrier for any operations on the diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 14eb33df9..69b59c171 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -218,3 +218,27 @@ impl crate::Binding { } } } + +//TODO: should we use an existing crate for hashable floats? +impl PartialEq for crate::ScalarValue { + fn eq(&self, other: &Self) -> bool { + match (*self, *other) { + (Self::Uint(a), Self::Uint(b)) => a == b, + (Self::Sint(a), Self::Sint(b)) => a == b, + (Self::Float(a), Self::Float(b)) => a.to_bits() == b.to_bits(), + (Self::Bool(a), Self::Bool(b)) => a == b, + _ => false, + } + } +} +impl Eq for crate::ScalarValue {} +impl std::hash::Hash for crate::ScalarValue { + fn hash(&self, hasher: &mut H) { + match *self { + Self::Sint(v) => v.hash(hasher), + Self::Uint(v) => v.hash(hasher), + Self::Float(v) => v.to_bits().hash(hasher), + Self::Bool(v) => v.hash(hasher), + } + } +} diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index 96822e579..131b62333 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -39,6 +39,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) { | Some(&mut S::Store { .. }) | Some(&mut S::ImageStore { .. }) | Some(&mut S::Call { .. }) + | Some(&mut S::Barrier(_)) | None => block.push(S::Return { value: None }), } } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index f206dc3f8..494aabf9e 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -573,6 +573,13 @@ impl FunctionInfo { result: Uniformity::new(), exit: ExitFlags::MAY_KILL, }, + S::Barrier(_) => FunctionUniformity { + result: Uniformity { + non_uniform_result: None, + requirements: UniformityRequirements::WORK_GROUP_BARRIER, + }, + exit: ExitFlags::empty(), + }, S::Block(ref b) => self.process_block(b, other_functions, disruptor)?, S::If { condition, diff --git a/src/valid/function.rs b/src/valid/function.rs index 4e7b6d569..f49bb70a1 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -1,6 +1,6 @@ use super::{ analyzer::{UniformityDisruptor, UniformityRequirements}, - ExpressionError, FunctionInfo, ModuleInfo, TypeFlags, ValidationFlags, + ExpressionError, FunctionInfo, ModuleInfo, ShaderStages, TypeFlags, ValidationFlags, }; use crate::arena::{Arena, Handle}; use bit_set::BitSet; @@ -121,11 +121,17 @@ struct BlockContext<'a> { types: &'a Arena, global_vars: &'a Arena, functions: &'a Arena, + prev_infos: &'a [FunctionInfo], return_type: Option>, } impl<'a> BlockContext<'a> { - fn new(fun: &'a crate::Function, module: &'a crate::Module, info: &'a FunctionInfo) -> Self { + fn new( + fun: &'a crate::Function, + module: &'a crate::Module, + info: &'a FunctionInfo, + prev_infos: &'a [FunctionInfo], + ) -> Self { Self { flags: Flags::CAN_JUMP, info, @@ -133,6 +139,7 @@ impl<'a> BlockContext<'a> { types: &module.types, global_vars: &module.global_variables, functions: &module.functions, + prev_infos, return_type: fun.result.as_ref().map(|fr| fr.ty), } } @@ -145,6 +152,7 @@ impl<'a> BlockContext<'a> { types: self.types, global_vars: self.global_vars, functions: self.functions, + prev_infos: self.prev_infos, return_type: self.return_type, } } @@ -203,7 +211,7 @@ impl super::Validator { arguments: &[Handle], result: Option>, context: &BlockContext, - ) -> Result<(), CallError> { + ) -> Result { let fun = context .functions .try_get(function) @@ -241,16 +249,18 @@ impl super::Validator { return Err(CallError::ExpressionMismatch(result)); } - Ok(()) + let callee_info = &context.prev_infos[function.index()]; + Ok(callee_info.available_stages) } fn validate_block_impl( &mut self, statements: &[crate::Statement], context: &BlockContext, - ) -> Result<(), FunctionError> { + ) -> Result { use crate::{Statement as S, TypeInner as Ti}; let mut finished = false; + let mut stages = ShaderStages::all(); for statement in statements { if finished { return Err(FunctionError::InstructionsAfterReturn); @@ -265,7 +275,9 @@ impl super::Validator { } } } - S::Block(ref block) => self.validate_block(block, context)?, + S::Block(ref block) => { + stages &= self.validate_block(block, context)?; + } S::If { condition, ref accept, @@ -278,8 +290,8 @@ impl super::Validator { } => {} _ => return Err(FunctionError::InvalidIfType(condition)), } - self.validate_block(accept, context)?; - self.validate_block(reject, context)?; + stages &= self.validate_block(accept, context)?; + stages &= self.validate_block(reject, context)?; } S::Switch { selector, @@ -300,9 +312,9 @@ impl super::Validator { } } for case in cases { - self.validate_block(&case.body, context)?; + stages &= self.validate_block(&case.body, context)?; } - self.validate_block(default, context)?; + stages &= self.validate_block(default, context)?; } S::Loop { ref body, @@ -311,11 +323,12 @@ impl super::Validator { // special handling for block scoping is needed here, // because the continuing{} block inherits the scope let base_expression_count = self.valid_expression_list.len(); - self.validate_block_impl( + stages &= self.validate_block_impl( body, &context.with_flags(Flags::CAN_JUMP | Flags::IN_LOOP), )?; - self.validate_block_impl(continuing, &context.with_flags(Flags::empty()))?; + stages &= + self.validate_block_impl(continuing, &context.with_flags(Flags::empty()))?; for handle in self.valid_expression_list.drain(base_expression_count..) { self.valid_expression_set.remove(handle.index()); } @@ -347,6 +360,9 @@ impl super::Validator { S::Kill => { finished = true; } + S::Barrier(_) => { + stages &= ShaderStages::COMPUTE; + } S::Store { pointer, value } => { let mut current = pointer; loop { @@ -472,27 +488,26 @@ impl super::Validator { function, ref arguments, result, - } => { - if let Err(error) = self.validate_call(function, arguments, result, context) { - return Err(FunctionError::InvalidCall { function, error }); - } - } + } => match self.validate_call(function, arguments, result, context) { + Ok(callee_stages) => stages &= callee_stages, + Err(error) => return Err(FunctionError::InvalidCall { function, error }), + }, } } - Ok(()) + Ok(stages) } fn validate_block( &mut self, statements: &[crate::Statement], context: &BlockContext, - ) -> Result<(), FunctionError> { + ) -> Result { let base_expression_count = self.valid_expression_list.len(); - self.validate_block_impl(statements, context)?; + let stages = self.validate_block_impl(statements, context)?; for handle in self.valid_expression_list.drain(base_expression_count..) { self.valid_expression_set.remove(handle.index()); } - Ok(()) + Ok(stages) } fn validate_local_var( @@ -573,7 +588,11 @@ impl super::Validator { } if self.flags.contains(ValidationFlags::BLOCKS) { - self.validate_block(&fun.body, &BlockContext::new(fun, module, &info))?; + let stages = self.validate_block( + &fun.body, + &BlockContext::new(fun, module, &info, &mod_info.functions), + )?; + info.available_stages &= stages; } Ok(info) } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 9ef3bb312..1191e77b8 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -40,6 +40,7 @@ bitflags::bitflags! { } } +#[must_use] bitflags::bitflags! { /// Validation flags. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] diff --git a/tests/in/control-flow.param.ron b/tests/in/control-flow.param.ron new file mode 100644 index 000000000..6de22960d --- /dev/null +++ b/tests/in/control-flow.param.ron @@ -0,0 +1,7 @@ +( + spv_version: (1, 1), + spv_capabilities: [ Shader ], + spv_debug: false, + spv_adjust_coordinate_space: false, + msl_custom: false, +) diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl new file mode 100644 index 000000000..4411d179a --- /dev/null +++ b/tests/in/control-flow.wgsl @@ -0,0 +1,5 @@ +[[stage(compute), workgroup_size(1)]] +fn main([[builtin(global_invocation_id)]] global_id: vec3) { + storageBarrier(); + workgroupBarrier(); +} diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm index 307305a9e..d7f3c4082 100644 --- a/tests/out/access.spvasm +++ b/tests/out/access.spvasm @@ -45,7 +45,7 @@ OpDecorate %21 BuiltIn Position %24 = OpTypeFunction %2 %26 = OpTypePointer StorageBuffer %10 %29 = OpTypePointer StorageBuffer %6 -%30 = OpConstant %6 0 +%30 = OpConstant %4 0 %34 = OpTypePointer Function %14 %37 = OpTypePointer Function %6 %39 = OpTypeVector %6 4 diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm index c9a05f398..a40311f79 100644 --- a/tests/out/boids.spvasm +++ b/tests/out/boids.spvasm @@ -94,11 +94,11 @@ OpDecorate %40 BuiltIn GlobalInvocationId %52 = OpTypePointer StorageBuffer %16 %53 = OpTypePointer StorageBuffer %15 %82 = OpTypePointer Uniform %6 -%96 = OpConstant %8 2 -%110 = OpConstant %8 3 -%145 = OpConstant %8 4 -%151 = OpConstant %8 5 -%157 = OpConstant %8 6 +%96 = OpConstant %4 2 +%110 = OpConstant %4 3 +%145 = OpConstant %4 4 +%151 = OpConstant %4 5 +%157 = OpConstant %4 6 %179 = OpTypePointer Function %6 %43 = OpFunction %2 None %44 %39 = OpLabel @@ -122,10 +122,10 @@ OpBranchConditional %48 %50 %49 %50 = OpLabel OpReturn %49 = OpLabel -%54 = OpAccessChain %53 %23 %7 %46 %7 +%54 = OpAccessChain %53 %23 %9 %46 %9 %55 = OpLoad %15 %54 OpStore %26 %55 -%56 = OpAccessChain %53 %23 %7 %46 %10 +%56 = OpAccessChain %53 %23 %9 %46 %11 %57 = OpLoad %15 %56 OpStore %28 %57 %58 = OpCompositeConstruct %15 %5 %5 @@ -154,17 +154,17 @@ OpBranchConditional %70 %72 %71 OpBranch %64 %71 = OpLabel %73 = OpLoad %4 %37 -%74 = OpAccessChain %53 %23 %7 %73 %7 +%74 = OpAccessChain %53 %23 %9 %73 %9 %75 = OpLoad %15 %74 OpStore %35 %75 %76 = OpLoad %4 %37 -%77 = OpAccessChain %53 %23 %7 %76 %10 +%77 = OpAccessChain %53 %23 %9 %76 %11 %78 = OpLoad %15 %77 OpStore %36 %78 %79 = OpLoad %15 %35 %80 = OpLoad %15 %26 %81 = OpExtInst %6 %1 Distance %79 %80 -%83 = OpAccessChain %82 %21 %10 +%83 = OpAccessChain %82 %21 %11 %84 = OpLoad %6 %83 %85 = OpFOrdLessThan %47 %81 %84 OpSelectionMerge %86 None @@ -275,7 +275,7 @@ OpStore %28 %161 OpStore %28 %167 %168 = OpLoad %15 %26 %169 = OpLoad %15 %28 -%170 = OpAccessChain %82 %21 %7 +%170 = OpAccessChain %82 %21 %9 %171 = OpLoad %6 %170 %172 = OpVectorTimesScalar %15 %169 %171 %173 = OpFAdd %15 %168 %172 @@ -286,7 +286,7 @@ OpStore %26 %173 OpSelectionMerge %177 None OpBranchConditional %176 %178 %177 %178 = OpLabel -%180 = OpAccessChain %179 %26 %7 +%180 = OpAccessChain %179 %26 %9 OpStore %180 %14 OpBranch %177 %177 = OpLabel @@ -296,7 +296,7 @@ OpBranch %177 OpSelectionMerge %184 None OpBranchConditional %183 %185 %184 %185 = OpLabel -%186 = OpAccessChain %179 %26 %7 +%186 = OpAccessChain %179 %26 %9 OpStore %186 %13 OpBranch %184 %184 = OpLabel @@ -306,7 +306,7 @@ OpBranch %184 OpSelectionMerge %190 None OpBranchConditional %189 %191 %190 %191 = OpLabel -%192 = OpAccessChain %179 %26 %10 +%192 = OpAccessChain %179 %26 %11 OpStore %192 %14 OpBranch %190 %190 = OpLabel @@ -316,15 +316,15 @@ OpBranch %190 OpSelectionMerge %196 None OpBranchConditional %195 %197 %196 %197 = OpLabel -%198 = OpAccessChain %179 %26 %10 +%198 = OpAccessChain %179 %26 %11 OpStore %198 %13 OpBranch %196 %196 = OpLabel %199 = OpLoad %15 %26 -%200 = OpAccessChain %53 %25 %7 %46 %7 +%200 = OpAccessChain %53 %25 %9 %46 %9 OpStore %200 %199 %201 = OpLoad %15 %28 -%202 = OpAccessChain %53 %25 %7 %46 %10 +%202 = OpAccessChain %53 %25 %9 %46 %11 OpStore %202 %201 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/collatz.spvasm b/tests/out/collatz.spvasm index 929a4343d..ce1b3e5e2 100644 --- a/tests/out/collatz.spvasm +++ b/tests/out/collatz.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 61 +; Bound: 59 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" @@ -42,8 +42,6 @@ OpDecorate %45 BuiltIn GlobalInvocationId %49 = OpTypeFunction %2 %51 = OpTypePointer StorageBuffer %8 %53 = OpTypePointer StorageBuffer %4 -%55 = OpTypeInt 32 1 -%56 = OpConstant %55 0 %18 = OpFunction %4 None %19 %17 = OpFunctionParameter %4 %16 = OpLabel @@ -98,10 +96,10 @@ OpBranch %50 %50 = OpLabel %52 = OpCompositeExtract %4 %47 0 %54 = OpCompositeExtract %4 %47 0 -%57 = OpAccessChain %53 %11 %56 %54 -%58 = OpLoad %4 %57 -%59 = OpFunctionCall %4 %18 %58 -%60 = OpAccessChain %53 %11 %56 %52 -OpStore %60 %59 +%55 = OpAccessChain %53 %11 %3 %54 +%56 = OpLoad %4 %55 +%57 = OpFunctionCall %4 %18 %56 +%58 = OpAccessChain %53 %11 %3 %52 +OpStore %58 %57 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/control-flow.Compute.glsl b/tests/out/control-flow.Compute.glsl new file mode 100644 index 000000000..15390223c --- /dev/null +++ b/tests/out/control-flow.Compute.glsl @@ -0,0 +1,14 @@ +#version 310 es + +precision highp float; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + + +void main() { + uvec3 global_id = gl_GlobalInvocationID; + groupMemoryBarrier(); + barrier(); + return; +} + diff --git a/tests/out/control-flow.msl b/tests/out/control-flow.msl new file mode 100644 index 000000000..d7afd08cf --- /dev/null +++ b/tests/out/control-flow.msl @@ -0,0 +1,13 @@ +#include +#include + + +struct main1Input { +}; +kernel void main1( + metal::uint3 global_id [[thread_position_in_grid]] +) { + metal::threadgroup_barrier(metal::mem_flags::mem_device); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + return; +} diff --git a/tests/out/control-flow.spvasm b/tests/out/control-flow.spvasm new file mode 100644 index 000000000..b46424b80 --- /dev/null +++ b/tests/out/control-flow.spvasm @@ -0,0 +1,29 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 16 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %9 "main" %6 +OpExecutionMode %9 LocalSize 1 1 1 +OpDecorate %6 BuiltIn GlobalInvocationId +%2 = OpTypeVoid +%4 = OpTypeInt 32 0 +%3 = OpTypeVector %4 3 +%7 = OpTypePointer Input %3 +%6 = OpVariable %7 Input +%10 = OpTypeFunction %2 +%12 = OpConstant %4 2 +%13 = OpConstant %4 1 +%14 = OpConstant %4 72 +%15 = OpConstant %4 264 +%9 = OpFunction %2 None %10 +%5 = OpLabel +%8 = OpLoad %3 %6 +OpBranch %11 +%11 = OpLabel +OpControlBarrier %12 %13 %14 +OpControlBarrier %12 %12 %15 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/image.spvasm b/tests/out/image.spvasm index b5e39cb9a..e0cac29d4 100644 --- a/tests/out/image.spvasm +++ b/tests/out/image.spvasm @@ -90,7 +90,7 @@ OpDecorate %59 BuiltIn Position %55 = OpTypeVector %8 4 %60 = OpTypePointer Output %20 %59 = OpVariable %60 Output -%70 = OpConstant %4 0 +%70 = OpConstant %8 0 %75 = OpTypeVector %4 3 %43 = OpFunction %2 None %44 %39 = OpLabel diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm index 1fa0dfbd4..80f62b6a4 100644 --- a/tests/out/interpolate.spvasm +++ b/tests/out/interpolate.spvasm @@ -1,14 +1,14 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 109 +; Bound: 108 OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %42 "main" %29 %31 %33 %35 %37 %39 %40 %41 -OpEntryPoint Fragment %107 "main" %86 %89 %92 %95 %98 %101 %103 %105 -OpExecutionMode %107 OriginUpperLeft +OpEntryPoint Fragment %106 "main" %85 %88 %91 %94 %97 %100 %102 %104 +OpExecutionMode %106 OriginUpperLeft OpSource GLSL 450 OpName %25 "FragmentInput" OpMemberName %25 0 "position" @@ -29,15 +29,15 @@ OpName %39 "perspective" OpName %40 "perspective_centroid" OpName %41 "perspective_sample" OpName %42 "main" -OpName %86 "position" -OpName %89 "flat" -OpName %92 "linear" -OpName %95 "linear_centroid" -OpName %98 "linear_sample" -OpName %101 "perspective" -OpName %103 "perspective_centroid" -OpName %105 "perspective_sample" -OpName %107 "main" +OpName %85 "position" +OpName %88 "flat" +OpName %91 "linear" +OpName %94 "linear_centroid" +OpName %97 "linear_sample" +OpName %100 "perspective" +OpName %102 "perspective_centroid" +OpName %104 "perspective_sample" +OpName %106 "main" OpMemberDecorate %25 0 Offset 0 OpMemberDecorate %25 1 Offset 16 OpMemberDecorate %25 2 Offset 20 @@ -62,22 +62,22 @@ OpDecorate %40 Location 5 OpDecorate %40 Centroid OpDecorate %41 Location 6 OpDecorate %41 Sample -OpDecorate %86 BuiltIn FragCoord -OpDecorate %89 Location 0 -OpDecorate %89 Flat -OpDecorate %92 Location 1 -OpDecorate %92 NoPerspective -OpDecorate %95 Location 2 -OpDecorate %95 NoPerspective -OpDecorate %95 Centroid -OpDecorate %98 Location 3 -OpDecorate %98 NoPerspective -OpDecorate %98 Sample -OpDecorate %101 Location 4 -OpDecorate %103 Location 5 -OpDecorate %103 Centroid -OpDecorate %105 Location 6 -OpDecorate %105 Sample +OpDecorate %85 BuiltIn FragCoord +OpDecorate %88 Location 0 +OpDecorate %88 Flat +OpDecorate %91 Location 1 +OpDecorate %91 NoPerspective +OpDecorate %94 Location 2 +OpDecorate %94 NoPerspective +OpDecorate %94 Centroid +OpDecorate %97 Location 3 +OpDecorate %97 NoPerspective +OpDecorate %97 Sample +OpDecorate %100 Location 4 +OpDecorate %102 Location 5 +OpDecorate %102 Centroid +OpDecorate %104 Location 6 +OpDecorate %104 Sample %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 2.0 @@ -118,93 +118,92 @@ OpDecorate %105 Sample %41 = OpVariable %34 Output %43 = OpTypeFunction %2 %45 = OpTypePointer Function %22 -%47 = OpTypeInt 32 1 -%48 = OpConstant %47 0 -%50 = OpTypePointer Function %9 -%51 = OpConstant %47 1 -%53 = OpTypePointer Function %4 -%54 = OpConstant %47 2 -%56 = OpTypePointer Function %23 -%58 = OpConstant %47 3 -%60 = OpTypePointer Function %24 -%62 = OpConstant %47 4 -%65 = OpConstant %47 5 -%67 = OpConstant %47 6 -%69 = OpConstant %47 7 -%74 = OpTypePointer Output %4 -%87 = OpTypePointer Input %22 -%86 = OpVariable %87 Input -%90 = OpTypePointer Input %9 -%89 = OpVariable %90 Input -%93 = OpTypePointer Input %4 -%92 = OpVariable %93 Input -%96 = OpTypePointer Input %23 -%95 = OpVariable %96 Input -%99 = OpTypePointer Input %24 -%98 = OpVariable %99 Input -%101 = OpVariable %87 Input -%103 = OpVariable %93 Input -%105 = OpVariable %93 Input +%47 = OpConstant %9 0 +%49 = OpTypePointer Function %9 +%50 = OpConstant %9 1 +%52 = OpTypePointer Function %4 +%53 = OpConstant %9 2 +%55 = OpTypePointer Function %23 +%57 = OpConstant %9 3 +%59 = OpTypePointer Function %24 +%61 = OpConstant %9 4 +%64 = OpConstant %9 5 +%66 = OpConstant %9 6 +%68 = OpConstant %9 7 +%73 = OpTypePointer Output %4 +%86 = OpTypePointer Input %22 +%85 = OpVariable %86 Input +%89 = OpTypePointer Input %9 +%88 = OpVariable %89 Input +%92 = OpTypePointer Input %4 +%91 = OpVariable %92 Input +%95 = OpTypePointer Input %23 +%94 = OpVariable %95 Input +%98 = OpTypePointer Input %24 +%97 = OpVariable %98 Input +%100 = OpVariable %86 Input +%102 = OpVariable %92 Input +%104 = OpVariable %92 Input %42 = OpFunction %2 None %43 %28 = OpLabel %26 = OpVariable %27 Function OpBranch %44 %44 = OpLabel %46 = OpCompositeConstruct %22 %3 %5 %6 %7 -%49 = OpAccessChain %45 %26 %48 -OpStore %49 %46 -%52 = OpAccessChain %50 %26 %51 -OpStore %52 %8 -%55 = OpAccessChain %53 %26 %54 -OpStore %55 %10 -%57 = OpCompositeConstruct %23 %11 %12 -%59 = OpAccessChain %56 %26 %58 -OpStore %59 %57 -%61 = OpCompositeConstruct %24 %13 %14 %15 -%63 = OpAccessChain %60 %26 %62 -OpStore %63 %61 -%64 = OpCompositeConstruct %22 %16 %17 %18 %19 -%66 = OpAccessChain %45 %26 %65 -OpStore %66 %64 -%68 = OpAccessChain %53 %26 %67 -OpStore %68 %20 -%70 = OpAccessChain %53 %26 %69 -OpStore %70 %21 -%71 = OpLoad %25 %26 -%72 = OpCompositeExtract %22 %71 0 -OpStore %29 %72 -%73 = OpAccessChain %74 %29 %51 -%75 = OpLoad %4 %73 -%76 = OpFNegate %4 %75 -OpStore %73 %76 -%77 = OpCompositeExtract %9 %71 1 -OpStore %31 %77 -%78 = OpCompositeExtract %4 %71 2 -OpStore %33 %78 -%79 = OpCompositeExtract %23 %71 3 -OpStore %35 %79 -%80 = OpCompositeExtract %24 %71 4 -OpStore %37 %80 -%81 = OpCompositeExtract %22 %71 5 -OpStore %39 %81 -%82 = OpCompositeExtract %4 %71 6 -OpStore %40 %82 -%83 = OpCompositeExtract %4 %71 7 -OpStore %41 %83 +%48 = OpAccessChain %45 %26 %47 +OpStore %48 %46 +%51 = OpAccessChain %49 %26 %50 +OpStore %51 %8 +%54 = OpAccessChain %52 %26 %53 +OpStore %54 %10 +%56 = OpCompositeConstruct %23 %11 %12 +%58 = OpAccessChain %55 %26 %57 +OpStore %58 %56 +%60 = OpCompositeConstruct %24 %13 %14 %15 +%62 = OpAccessChain %59 %26 %61 +OpStore %62 %60 +%63 = OpCompositeConstruct %22 %16 %17 %18 %19 +%65 = OpAccessChain %45 %26 %64 +OpStore %65 %63 +%67 = OpAccessChain %52 %26 %66 +OpStore %67 %20 +%69 = OpAccessChain %52 %26 %68 +OpStore %69 %21 +%70 = OpLoad %25 %26 +%71 = OpCompositeExtract %22 %70 0 +OpStore %29 %71 +%72 = OpAccessChain %73 %29 %50 +%74 = OpLoad %4 %72 +%75 = OpFNegate %4 %74 +OpStore %72 %75 +%76 = OpCompositeExtract %9 %70 1 +OpStore %31 %76 +%77 = OpCompositeExtract %4 %70 2 +OpStore %33 %77 +%78 = OpCompositeExtract %23 %70 3 +OpStore %35 %78 +%79 = OpCompositeExtract %24 %70 4 +OpStore %37 %79 +%80 = OpCompositeExtract %22 %70 5 +OpStore %39 %80 +%81 = OpCompositeExtract %4 %70 6 +OpStore %40 %81 +%82 = OpCompositeExtract %4 %70 7 +OpStore %41 %82 OpReturn OpFunctionEnd -%107 = OpFunction %2 None %43 -%84 = OpLabel -%88 = OpLoad %22 %86 -%91 = OpLoad %9 %89 -%94 = OpLoad %4 %92 -%97 = OpLoad %23 %95 -%100 = OpLoad %24 %98 -%102 = OpLoad %22 %101 -%104 = OpLoad %4 %103 -%106 = OpLoad %4 %105 -%85 = OpCompositeConstruct %25 %88 %91 %94 %97 %100 %102 %104 %106 -OpBranch %108 -%108 = OpLabel +%106 = OpFunction %2 None %43 +%83 = OpLabel +%87 = OpLoad %22 %85 +%90 = OpLoad %9 %88 +%93 = OpLoad %4 %91 +%96 = OpLoad %23 %94 +%99 = OpLoad %24 %97 +%101 = OpLoad %22 %100 +%103 = OpLoad %4 %102 +%105 = OpLoad %4 %104 +%84 = OpCompositeConstruct %25 %87 %90 %93 %96 %99 %101 %103 %105 +OpBranch %107 +%107 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/quad.spvasm b/tests/out/quad.spvasm index d15def3de..02c31384b 100644 --- a/tests/out/quad.spvasm +++ b/tests/out/quad.spvasm @@ -57,8 +57,8 @@ OpDecorate %43 Location 0 %24 = OpVariable %25 Output %27 = OpTypeFunction %2 %35 = OpTypePointer Output %4 -%36 = OpTypeInt 32 1 -%37 = OpConstant %36 1 +%37 = OpTypeInt 32 0 +%36 = OpConstant %37 1 %41 = OpVariable %18 Input %43 = OpVariable %25 Output %48 = OpTypeSampledImage %10 @@ -76,7 +76,7 @@ OpBranch %28 OpStore %22 %32 %33 = OpCompositeExtract %8 %31 1 OpStore %24 %33 -%34 = OpAccessChain %35 %24 %37 +%34 = OpAccessChain %35 %24 %36 %38 = OpLoad %4 %34 %39 = OpFNegate %4 %38 OpStore %34 %39 diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm index 2fd871667..6f3697e3a 100644 --- a/tests/out/shadow.spvasm +++ b/tests/out/shadow.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 126 +; Bound: 124 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %80 "fs_main" %72 %75 %78 -OpExecutionMode %80 OriginUpperLeft +OpEntryPoint Fragment %79 "fs_main" %71 %74 %77 +OpExecutionMode %79 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_max_lights" OpName %14 "Globals" @@ -24,11 +24,11 @@ OpName %27 "s_lights" OpName %29 "t_shadow" OpName %31 "sampler_shadow" OpName %36 "fetch_shadow" -OpName %67 "color" -OpName %69 "i" -OpName %72 "raw_normal" -OpName %75 "position" -OpName %80 "fs_main" +OpName %66 "color" +OpName %68 "i" +OpName %71 "raw_normal" +OpName %74 "position" +OpName %79 "fs_main" OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %17 0 Offset 0 @@ -48,9 +48,9 @@ OpDecorate %29 DescriptorSet 0 OpDecorate %29 Binding 2 OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 3 -OpDecorate %72 Location 0 -OpDecorate %75 Location 1 -OpDecorate %78 Location 0 +OpDecorate %71 Location 0 +OpDecorate %74 Location 1 +OpDecorate %77 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 @@ -86,20 +86,18 @@ OpDecorate %78 Location 0 %42 = OpTypeBool %54 = OpTypeInt 32 1 %59 = OpTypeSampledImage %20 -%66 = OpConstant %4 0.0 -%68 = OpTypePointer Function %23 -%70 = OpTypePointer Function %10 -%73 = OpTypePointer Input %23 -%72 = OpVariable %73 Input -%76 = OpTypePointer Input %16 -%75 = OpVariable %76 Input -%79 = OpTypePointer Output %16 -%78 = OpVariable %79 Output -%81 = OpTypeFunction %2 -%91 = OpTypePointer Uniform %13 -%92 = OpConstant %54 0 -%100 = OpTypePointer StorageBuffer %18 -%102 = OpTypePointer StorageBuffer %17 +%67 = OpTypePointer Function %23 +%69 = OpTypePointer Function %10 +%72 = OpTypePointer Input %23 +%71 = OpVariable %72 Input +%75 = OpTypePointer Input %16 +%74 = OpVariable %75 Input +%78 = OpTypePointer Output %16 +%77 = OpVariable %78 Output +%80 = OpTypeFunction %2 +%90 = OpTypePointer Uniform %13 +%98 = OpTypePointer StorageBuffer %18 +%100 = OpTypePointer StorageBuffer %17 %36 = OpFunction %4 None %37 %34 = OpFunctionParameter %10 %35 = OpFunctionParameter %16 @@ -132,66 +130,66 @@ OpReturnValue %5 %62 = OpConvertUToF %4 %55 %63 = OpCompositeConstruct %23 %60 %61 %62 %64 = OpSampledImage %59 %38 %39 -%65 = OpImageSampleDrefExplicitLod %4 %64 %63 %58 Lod %66 +%65 = OpImageSampleDrefExplicitLod %4 %64 %63 %58 Lod %3 OpReturnValue %65 OpFunctionEnd -%80 = OpFunction %2 None %81 -%71 = OpLabel -%67 = OpVariable %68 Function %24 -%69 = OpVariable %70 Function %11 -%74 = OpLoad %23 %72 -%77 = OpLoad %16 %75 -%82 = OpLoad %20 %29 -%83 = OpLoad %21 %31 -OpBranch %84 -%84 = OpLabel -%85 = OpExtInst %23 %1 Normalize %74 +%79 = OpFunction %2 None %80 +%70 = OpLabel +%66 = OpVariable %67 Function %24 +%68 = OpVariable %69 Function %11 +%73 = OpLoad %23 %71 +%76 = OpLoad %16 %74 +%81 = OpLoad %20 %29 +%82 = OpLoad %21 %31 +OpBranch %83 +%83 = OpLabel +%84 = OpExtInst %23 %1 Normalize %73 +OpBranch %85 +%85 = OpLabel +OpLoopMerge %86 %88 None +OpBranch %87 +%87 = OpLabel +%89 = OpLoad %10 %68 +%91 = OpAccessChain %90 %25 %11 +%92 = OpLoad %13 %91 +%93 = OpCompositeExtract %10 %92 0 +%94 = OpExtInst %10 %1 UMin %93 %9 +%95 = OpUGreaterThanEqual %42 %89 %94 +OpSelectionMerge %96 None +OpBranchConditional %95 %97 %96 +%97 = OpLabel OpBranch %86 -%86 = OpLabel -OpLoopMerge %87 %89 None +%96 = OpLabel +%99 = OpLoad %10 %68 +%101 = OpAccessChain %100 %27 %11 %99 +%102 = OpLoad %17 %101 +%103 = OpLoad %10 %68 +%104 = OpCompositeExtract %15 %102 0 +%105 = OpMatrixTimesVector %16 %104 %76 +%106 = OpFunctionCall %4 %36 %103 %105 +%107 = OpCompositeExtract %16 %102 1 +%108 = OpVectorShuffle %23 %107 %107 0 1 2 +%109 = OpVectorShuffle %23 %76 %76 0 1 2 +%110 = OpFSub %23 %108 %109 +%111 = OpExtInst %23 %1 Normalize %110 +%112 = OpDot %4 %84 %111 +%113 = OpExtInst %4 %1 FMax %3 %112 +%114 = OpLoad %23 %66 +%115 = OpFMul %4 %106 %113 +%116 = OpCompositeExtract %16 %102 2 +%117 = OpVectorShuffle %23 %116 %116 0 1 2 +%118 = OpVectorTimesScalar %23 %117 %115 +%119 = OpFAdd %23 %114 %118 +OpStore %66 %119 OpBranch %88 %88 = OpLabel -%90 = OpLoad %10 %69 -%93 = OpAccessChain %91 %25 %92 -%94 = OpLoad %13 %93 -%95 = OpCompositeExtract %10 %94 0 -%96 = OpExtInst %10 %1 UMin %95 %9 -%97 = OpUGreaterThanEqual %42 %90 %96 -OpSelectionMerge %98 None -OpBranchConditional %97 %99 %98 -%99 = OpLabel -OpBranch %87 -%98 = OpLabel -%101 = OpLoad %10 %69 -%103 = OpAccessChain %102 %27 %92 %101 -%104 = OpLoad %17 %103 -%105 = OpLoad %10 %69 -%106 = OpCompositeExtract %15 %104 0 -%107 = OpMatrixTimesVector %16 %106 %77 -%108 = OpFunctionCall %4 %36 %105 %107 -%109 = OpCompositeExtract %16 %104 1 -%110 = OpVectorShuffle %23 %109 %109 0 1 2 -%111 = OpVectorShuffle %23 %77 %77 0 1 2 -%112 = OpFSub %23 %110 %111 -%113 = OpExtInst %23 %1 Normalize %112 -%114 = OpDot %4 %85 %113 -%115 = OpExtInst %4 %1 FMax %3 %114 -%116 = OpLoad %23 %67 -%117 = OpFMul %4 %108 %115 -%118 = OpCompositeExtract %16 %104 2 -%119 = OpVectorShuffle %23 %118 %118 0 1 2 -%120 = OpVectorTimesScalar %23 %119 %117 -%121 = OpFAdd %23 %116 %120 -OpStore %67 %121 -OpBranch %89 -%89 = OpLabel -%122 = OpLoad %10 %69 -%123 = OpIAdd %10 %122 %12 -OpStore %69 %123 -OpBranch %86 -%87 = OpLabel -%124 = OpLoad %23 %67 -%125 = OpCompositeConstruct %16 %124 %5 -OpStore %78 %125 +%120 = OpLoad %10 %68 +%121 = OpIAdd %10 %120 %12 +OpStore %68 %121 +OpBranch %85 +%86 = OpLabel +%122 = OpLoad %23 %66 +%123 = OpCompositeConstruct %16 %122 %5 +OpStore %77 %123 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/skybox.spvasm b/tests/out/skybox.spvasm index ee13bf6fc..6cd768731 100644 --- a/tests/out/skybox.spvasm +++ b/tests/out/skybox.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 93 +; Bound: 94 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %36 "vs_main" %29 %32 %34 -OpEntryPoint Fragment %85 "fs_main" %78 %81 %84 -OpExecutionMode %85 OriginUpperLeft +OpEntryPoint Fragment %86 "fs_main" %79 %82 %85 +OpExecutionMode %86 OriginUpperLeft OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpDecorate %14 Block @@ -26,9 +26,9 @@ OpDecorate %23 Binding 2 OpDecorate %29 BuiltIn VertexIndex OpDecorate %32 BuiltIn Position OpDecorate %34 Location 0 -OpDecorate %78 BuiltIn FragCoord -OpDecorate %81 Location 0 -OpDecorate %84 Location 0 +OpDecorate %79 BuiltIn FragCoord +OpDecorate %82 Location 0 +OpDecorate %85 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -61,13 +61,14 @@ OpDecorate %84 Location 0 %34 = OpVariable %35 Output %37 = OpTypeFunction %2 %52 = OpTypePointer Uniform %13 -%67 = OpConstant %4 0 -%79 = OpTypePointer Input %10 -%78 = OpVariable %79 Input -%82 = OpTypePointer Input %11 -%81 = OpVariable %82 Input -%84 = OpVariable %33 Output -%90 = OpTypeSampledImage %17 +%53 = OpConstant %15 1 +%68 = OpConstant %15 0 +%80 = OpTypePointer Input %10 +%79 = OpVariable %80 Input +%83 = OpTypePointer Input %11 +%82 = OpVariable %83 Input +%85 = OpVariable %33 Output +%91 = OpTypeSampledImage %17 %36 = OpFunction %2 None %37 %28 = OpLabel %25 = OpVariable %26 Function @@ -90,44 +91,44 @@ OpStore %27 %42 %49 = OpFMul %7 %48 %6 %50 = OpFSub %7 %49 %8 %51 = OpCompositeConstruct %10 %46 %50 %9 %8 -%53 = OpAccessChain %52 %19 %5 -%54 = OpLoad %13 %53 -%55 = OpCompositeExtract %10 %54 0 -%56 = OpVectorShuffle %11 %55 %55 0 1 2 -%57 = OpAccessChain %52 %19 %5 -%58 = OpLoad %13 %57 -%59 = OpCompositeExtract %10 %58 1 -%60 = OpVectorShuffle %11 %59 %59 0 1 2 -%61 = OpAccessChain %52 %19 %5 -%62 = OpLoad %13 %61 -%63 = OpCompositeExtract %10 %62 2 -%64 = OpVectorShuffle %11 %63 %63 0 1 2 -%65 = OpCompositeConstruct %16 %56 %60 %64 -%66 = OpTranspose %16 %65 -%68 = OpAccessChain %52 %19 %67 -%69 = OpLoad %13 %68 -%70 = OpMatrixTimesVector %10 %69 %51 -%71 = OpVectorShuffle %11 %70 %70 0 1 2 -%72 = OpMatrixTimesVector %11 %66 %71 -%73 = OpCompositeConstruct %12 %51 %72 -%74 = OpCompositeExtract %10 %73 0 -OpStore %32 %74 -%75 = OpCompositeExtract %11 %73 1 -OpStore %34 %75 +%54 = OpAccessChain %52 %19 %53 +%55 = OpLoad %13 %54 +%56 = OpCompositeExtract %10 %55 0 +%57 = OpVectorShuffle %11 %56 %56 0 1 2 +%58 = OpAccessChain %52 %19 %53 +%59 = OpLoad %13 %58 +%60 = OpCompositeExtract %10 %59 1 +%61 = OpVectorShuffle %11 %60 %60 0 1 2 +%62 = OpAccessChain %52 %19 %53 +%63 = OpLoad %13 %62 +%64 = OpCompositeExtract %10 %63 2 +%65 = OpVectorShuffle %11 %64 %64 0 1 2 +%66 = OpCompositeConstruct %16 %57 %61 %65 +%67 = OpTranspose %16 %66 +%69 = OpAccessChain %52 %19 %68 +%70 = OpLoad %13 %69 +%71 = OpMatrixTimesVector %10 %70 %51 +%72 = OpVectorShuffle %11 %71 %71 0 1 2 +%73 = OpMatrixTimesVector %11 %67 %72 +%74 = OpCompositeConstruct %12 %51 %73 +%75 = OpCompositeExtract %10 %74 0 +OpStore %32 %75 +%76 = OpCompositeExtract %11 %74 1 +OpStore %34 %76 OpReturn OpFunctionEnd -%85 = OpFunction %2 None %37 -%76 = OpLabel -%80 = OpLoad %10 %78 -%83 = OpLoad %11 %81 -%77 = OpCompositeConstruct %12 %80 %83 -%86 = OpLoad %17 %21 -%87 = OpLoad %18 %23 -OpBranch %88 -%88 = OpLabel -%89 = OpCompositeExtract %11 %77 1 -%91 = OpSampledImage %90 %86 %87 -%92 = OpImageSampleImplicitLod %10 %91 %89 -OpStore %84 %92 +%86 = OpFunction %2 None %37 +%77 = OpLabel +%81 = OpLoad %10 %79 +%84 = OpLoad %11 %82 +%78 = OpCompositeConstruct %12 %81 %84 +%87 = OpLoad %17 %21 +%88 = OpLoad %18 %23 +OpBranch %89 +%89 = OpLabel +%90 = OpCompositeExtract %11 %78 1 +%92 = OpSampledImage %91 %87 %88 +%93 = OpImageSampleImplicitLod %10 %92 %90 +OpStore %85 %93 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/texture-array.spvasm b/tests/out/texture-array.spvasm index 58a2d5b3e..faefb5f6e 100644 --- a/tests/out/texture-array.spvasm +++ b/tests/out/texture-array.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.5 ; Generator: rspirv -; Bound: 45 +; Bound: 43 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -48,10 +48,8 @@ OpDecorate %22 Location 1 %22 = OpVariable %23 Output %25 = OpTypeFunction %2 %30 = OpTypePointer PushConstant %4 -%31 = OpTypeInt 32 1 -%32 = OpConstant %31 0 -%35 = OpTypeBool -%40 = OpTypeSampledImage %5 +%33 = OpTypeBool +%38 = OpTypeSampledImage %5 %24 = OpFunction %2 None %25 %18 = OpLabel %21 = OpLoad %9 %19 @@ -60,21 +58,21 @@ OpDecorate %22 Location 1 %28 = OpLoad %7 %14 OpBranch %29 %29 = OpLabel -%33 = OpAccessChain %30 %16 %32 -%34 = OpLoad %4 %33 -%36 = OpIEqual %35 %34 %3 -OpSelectionMerge %37 None -OpBranchConditional %36 %38 %39 -%38 = OpLabel -%41 = OpSampledImage %40 %26 %28 +%31 = OpAccessChain %30 %16 %3 +%32 = OpLoad %4 %31 +%34 = OpIEqual %33 %32 %3 +OpSelectionMerge %35 None +OpBranchConditional %34 %36 %37 +%36 = OpLabel +%39 = OpSampledImage %38 %26 %28 +%40 = OpImageSampleImplicitLod %10 %39 %21 +OpStore %22 %40 +OpReturn +%37 = OpLabel +%41 = OpSampledImage %38 %27 %28 %42 = OpImageSampleImplicitLod %10 %41 %21 OpStore %22 %42 OpReturn -%39 = OpLabel -%43 = OpSampledImage %40 %27 %28 -%44 = OpImageSampleImplicitLod %10 %43 %21 -OpStore %22 %44 -OpReturn -%37 = OpLabel +%35 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index f105fe012..034f91093 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -252,6 +252,10 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::GLSL, ), ("access", Targets::SPIRV | Targets::METAL), + ( + "control-flow", + Targets::SPIRV | Targets::METAL | Targets::GLSL, + ), ]; for &(name, targets) in inputs.iter() { From be00a05fa5feee1527569f5b1da143c0f15a7be6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 3 May 2021 13:47:51 -0400 Subject: [PATCH 0795/2212] [spv-in] default output builtins --- src/back/msl/writer.rs | 1 + src/front/spv/error.rs | 2 + src/front/spv/function.rs | 55 +++++++------- src/front/spv/mod.rs | 138 +++++++++++++++-------------------- src/front/spv/null.rs | 149 ++++++++++++++++++++++++++++++++++++++ tests/out/quad-vert.msl | 5 +- 6 files changed, 241 insertions(+), 109 deletions(-) create mode 100644 src/front/spv/null.rs diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index d72cd5c61..e08f0d61d 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2027,6 +2027,7 @@ impl Writer { result.binding.as_ref(), )); } + writeln!(self.out, "struct {} {{", stage_out_name)?; for (name, ty, binding) in result_members { let ty_name = TypeContext { diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 3a4bc44be..3f0ae9559 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -99,6 +99,8 @@ pub enum Error { InvalidEdgeClassification, #[error("recursive function call %{0}")] FunctionCallCycle(spirv::Word), + #[error("invalid array size {0:?}")] + InvalidArraySize(Handle), #[error("invalid barrier scope %{0}")] InvalidBarrierScope(spirv::Word), #[error("invalid barrier memory semantics %{0}")] diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 856ffc076..a01ed51d6 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -296,33 +296,34 @@ impl> super::Parser { } } - if self.options.adjust_coordinate_space { - let position_index = members.iter().position(|member| match member.binding { - Some(crate::Binding::BuiltIn(crate::BuiltIn::Position)) => true, - _ => false, - }); - if let Some(component_index) = position_index { - // The IR is Y-up, while SPIR-V is Y-down. - let old_len = function.expressions.len(); - let global_expr = components[component_index]; - let access_expr = function.expressions.append(crate::Expression::AccessIndex { - base: global_expr, - index: 1, - }); - let load_expr = function.expressions.append(crate::Expression::Load { - pointer: access_expr, - }); - let neg_expr = function.expressions.append(crate::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr: load_expr, - }); - function.body.push(crate::Statement::Emit( - function.expressions.range_from(old_len), - )); - function.body.push(crate::Statement::Store { - pointer: access_expr, - value: neg_expr, - }); + for (member_index, member) in members.iter().enumerate() { + match member.binding { + Some(crate::Binding::BuiltIn(crate::BuiltIn::Position)) + if self.options.adjust_coordinate_space => + { + let old_len = function.expressions.len(); + let global_expr = components[member_index]; + let access_expr = + function.expressions.append(crate::Expression::AccessIndex { + base: global_expr, + index: 1, + }); + let load_expr = function.expressions.append(crate::Expression::Load { + pointer: access_expr, + }); + let neg_expr = function.expressions.append(crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr: load_expr, + }); + function.body.push(crate::Statement::Emit( + function.expressions.range_from(old_len), + )); + function.body.push(crate::Statement::Store { + pointer: access_expr, + value: neg_expr, + }); + } + _ => {} } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 5603a53c9..3750bd238 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -31,6 +31,7 @@ mod error; mod flow; mod function; mod image; +mod null; use convert::*; pub use error::Error; @@ -3217,84 +3218,6 @@ impl> Parser { Ok(()) } - fn generate_null_constant( - &mut self, - constants: &mut Arena, - types: &mut Arena, - ty: Handle, - ) -> Result { - fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { - crate::ConstantInner::Scalar { - width, - value: match kind { - crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), - crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), - crate::ScalarKind::Float => crate::ScalarValue::Float(0.0), - crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), - }, - } - } - - let inner = match types[ty].inner { - crate::TypeInner::Scalar { kind, width } => make_scalar_inner(kind, width), - crate::TypeInner::Vector { size, kind, width } => { - let mut components = Vec::with_capacity(size as usize); - for _ in 0..size as usize { - components.push(constants.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: make_scalar_inner(kind, width), - })); - } - crate::ConstantInner::Composite { ty, components } - } - crate::TypeInner::Matrix { - columns, - rows, - width, - } => { - let vector_ty = types.fetch_or_append(crate::Type { - name: None, - inner: crate::TypeInner::Vector { - kind: crate::ScalarKind::Float, - size: rows, - width, - }, - }); - let vector_inner = self.generate_null_constant(constants, types, vector_ty)?; - let vector_handle = constants.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: vector_inner, - }); - crate::ConstantInner::Composite { - ty, - components: vec![vector_handle; columns as usize], - } - } - crate::TypeInner::Struct { ref members, .. } => { - let mut components = Vec::with_capacity(members.len()); - // copy out the types to avoid borrowing `members` - let member_tys = members.iter().map(|member| member.ty).collect::>(); - for member_ty in member_tys { - let inner = self.generate_null_constant(constants, types, member_ty)?; - components.push(constants.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner, - })); - } - crate::ConstantInner::Composite { ty, components } - } - //TODO: arrays - ref other => { - log::warn!("null constant type {:?}", other); - return Err(Error::UnsupportedType(ty)); - } - }; - Ok(inner) - } - fn parse_null_constant( &mut self, inst: Instruction, @@ -3307,7 +3230,7 @@ impl> Parser { let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; - let inner = self.generate_null_constant(&mut module.constants, &mut module.types, ty)?; + let inner = null::generate_null_constant(ty, &mut module.types, &mut module.constants)?; self.lookup_constant.insert( id, @@ -3471,14 +3394,67 @@ impl> Parser { (inner, var) } ExtendedClass::Output => { - // For output interface blocks. this would be a structure. + // For output interface blocks, this would be a structure. let binding = dec.io_binding().ok(); + let init = match binding { + Some(crate::Binding::BuiltIn(built_in)) => { + match null::generate_default_built_in( + Some(built_in), + effective_ty, + &mut module.types, + &mut module.constants, + ) { + Ok(handle) => Some(handle), + Err(e) => { + log::warn!("Failed to initialize output built-in: {}", e); + None + } + } + } + Some(crate::Binding::Location { .. }) => None, + None => match module.types[effective_ty].inner { + crate::TypeInner::Struct { ref members, .. } => { + // A temporary to avoid borrowing `module.types` + let pairs = members + .iter() + .map(|member| { + let built_in = match member.binding { + Some(crate::Binding::BuiltIn(built_in)) => Some(built_in), + _ => None, + }; + (built_in, member.ty) + }) + .collect::>(); + + let mut components = Vec::with_capacity(members.len()); + for (built_in, member_ty) in pairs { + let handle = null::generate_default_built_in( + built_in, + member_ty, + &mut module.types, + &mut module.constants, + )?; + components.push(handle); + } + Some(module.constants.append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Composite { + ty: effective_ty, + components, + }, + })) + } + _ => None, + }, + }; + let var = crate::GlobalVariable { name: dec.name, class: crate::StorageClass::Private, binding: None, ty: effective_ty, - init: None, + init, storage_access: crate::StorageAccess::empty(), }; let inner = Variable::Output(crate::FunctionResult { diff --git a/src/front/spv/null.rs b/src/front/spv/null.rs new file mode 100644 index 000000000..1fc2b3043 --- /dev/null +++ b/src/front/spv/null.rs @@ -0,0 +1,149 @@ +use super::Error; +use crate::arena::{Arena, Handle}; + +fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { + crate::ConstantInner::Scalar { + width, + value: match kind { + crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), + crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), + crate::ScalarKind::Float => crate::ScalarValue::Float(0.0), + crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), + }, + } +} + +pub fn generate_null_constant( + ty: Handle, + type_arena: &mut Arena, + constant_arena: &mut Arena, +) -> Result { + let inner = match type_arena[ty].inner { + crate::TypeInner::Scalar { kind, width } => make_scalar_inner(kind, width), + crate::TypeInner::Vector { size, kind, width } => { + let mut components = Vec::with_capacity(size as usize); + for _ in 0..size as usize { + components.push(constant_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner: make_scalar_inner(kind, width), + })); + } + crate::ConstantInner::Composite { ty, components } + } + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + let vector_ty = type_arena.fetch_or_append(crate::Type { + name: None, + inner: crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + size: rows, + width, + }, + }); + let vector_inner = generate_null_constant(vector_ty, type_arena, constant_arena)?; + let vector_handle = constant_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner: vector_inner, + }); + crate::ConstantInner::Composite { + ty, + components: vec![vector_handle; columns as usize], + } + } + crate::TypeInner::Struct { ref members, .. } => { + let mut components = Vec::with_capacity(members.len()); + // copy out the types to avoid borrowing `members` + let member_tys = members.iter().map(|member| member.ty).collect::>(); + for member_ty in member_tys { + let inner = generate_null_constant(member_ty, type_arena, constant_arena)?; + components.push(constant_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner, + })); + } + crate::ConstantInner::Composite { ty, components } + } + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(handle), + .. + } => { + let size = constant_arena[handle] + .to_array_length() + .ok_or(Error::InvalidArraySize(handle))?; + let inner = generate_null_constant(base, type_arena, constant_arena)?; + let value = constant_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner, + }); + crate::ConstantInner::Composite { + ty, + components: vec![value; size as usize], + } + } + ref other => { + log::warn!("null constant type {:?}", other); + return Err(Error::UnsupportedType(ty)); + } + }; + Ok(inner) +} + +/// Create a default value for an output built-in. +pub fn generate_default_built_in( + built_in: Option, + ty: Handle, + type_arena: &mut Arena, + constant_arena: &mut Arena, +) -> Result, Error> { + let inner = match built_in { + Some(crate::BuiltIn::Position) => { + let zero = constant_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + value: crate::ScalarValue::Float(0.0), + width: 4, + }, + }); + let one = constant_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + value: crate::ScalarValue::Float(1.0), + width: 4, + }, + }); + crate::ConstantInner::Composite { + ty, + components: vec![zero, zero, zero, one], + } + } + Some(crate::BuiltIn::PointSize) => crate::ConstantInner::Scalar { + value: crate::ScalarValue::Float(1.0), + width: 4, + }, + Some(crate::BuiltIn::FragDepth) => crate::ConstantInner::Scalar { + value: crate::ScalarValue::Float(0.0), + width: 4, + }, + Some(crate::BuiltIn::SampleMask) => crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(!0), + width: 4, + }, + //Note: `crate::BuiltIn::ClipDistance` is intentionally left for the default path + _ => generate_null_constant(ty, type_arena, constant_arena)?, + }; + Ok(constant_arena.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner, + })) +} diff --git a/tests/out/quad-vert.msl b/tests/out/quad-vert.msl index d7363aad4..4c99ca960 100644 --- a/tests/out/quad-vert.msl +++ b/tests/out/quad-vert.msl @@ -16,6 +16,9 @@ struct type10 { float gl_PointSize1; type6 gl_ClipDistance1; }; +constant metal::float4 const_type4_ = {0.0, 0.0, 0.0, 1.0}; +constant type6 const_type6_ = {0.0}; +constant gl_PerVertex const_gl_PerVertex = {const_type4_, 1.0, const_type6_, const_type6_}; void main1( thread metal::float2& v_uv, @@ -44,7 +47,7 @@ vertex main2Output main2( ) { metal::float2 v_uv = {}; metal::float2 a_uv = {}; - gl_PerVertex perVertexStruct = {}; + gl_PerVertex perVertexStruct = const_gl_PerVertex; metal::float2 a_pos = {}; const auto a_uv1 = varyings.a_uv1; const auto a_pos1 = varyings.a_pos1; From 990fd2d3a3c3a4abf33aeb0015e3b3b4829572d9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 3 May 2021 22:47:33 -0400 Subject: [PATCH 0796/2212] Allow matrix indexing behind a pointer --- src/front/spv/mod.rs | 27 +++++---- src/front/wgsl/mod.rs | 7 ++- src/proc/typifier.rs | 11 ++++ tests/in/access.wgsl | 9 ++- tests/out/access.msl | 9 +-- tests/out/access.spvasm | 123 ++++++++++++++++++++++------------------ tests/out/skybox.spvasm | 95 +++++++++++++++---------------- 7 files changed, 157 insertions(+), 124 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3750bd238..dd23f90dc 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -993,29 +993,34 @@ impl> Parser { }, } } - // we can't dynamically index matrices, so expecting constant index here crate::TypeInner::Matrix { .. } => { - let index = index_maybe - .ok_or_else(|| Error::InvalidAccess(index_expr_data.clone()))?; let load_override = match acex.load_override { // We are indexing inside a row-major matrix Some(LookupLoadOverride::Loaded(load_expr)) => { - let sub_expr = + let index = index_maybe.ok_or_else(|| { + Error::InvalidAccess(index_expr_data.clone()) + })?; + let sub_handle = expressions.append(crate::Expression::AccessIndex { base: load_expr, index, }); - Some(LookupLoadOverride::Loaded(sub_expr)) + Some(LookupLoadOverride::Loaded(sub_handle)) } _ => None, }; + let sub_expr = match index_maybe { + Some(index) => crate::Expression::AccessIndex { + base: acex.base_handle, + index, + }, + None => crate::Expression::Access { + base: acex.base_handle, + index: index_expr.handle, + }, + }; AccessExpression { - base_handle: expressions.append( - crate::Expression::AccessIndex { - base: acex.base_handle, - index, - }, - ), + base_handle: expressions.append(sub_expr), type_id: type_lookup .base_id .ok_or(Error::InvalidAccessType(acex.type_id))?, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index fd22ea52e..a2241401e 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1224,9 +1224,10 @@ impl Parser { // insert the E::Load when we reach a value if needs_deref { let now = match *ctx.resolve_type(handle)? { - crate::TypeInner::Pointer { base, class: _ } => { - ctx.types[base].inner.scalar_kind().is_some() - } + crate::TypeInner::Pointer { base, class: _ } => match ctx.types[base].inner { + crate::TypeInner::Scalar { .. } | crate::TypeInner::Vector { .. } => true, + _ => false, + }, crate::TypeInner::ValuePointer { .. } => true, _ => false, }; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 4ba71949b..f402ab2db 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -156,6 +156,17 @@ impl<'a> ResolveContext<'a> { width, class, }, + // Matrices are only dynamically indexed behind a pointer + Ti::Matrix { + columns: _, + rows, + width, + } => Ti::ValuePointer { + kind: crate::ScalarKind::Float, + size: Some(rows), + width, + class, + }, ref other => { log::error!("Access sub-type {:?}", other); return Err(ResolveError::InvalidSubAccess { diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 1860ff1c4..b6ee08355 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -2,7 +2,8 @@ [[block]] struct Bar { - data: [[stride(4)]] array; + matrix: mat4x4; + data: [[stride(4)]] array; }; [[group(0), binding(0)]] @@ -10,9 +11,13 @@ var bar: [[access(read_write)]] Bar; [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { + let index = 3u; + let b = bar.matrix[index].x; + let a = bar.data[arrayLength(&bar.data) - 1u]; - let array = array(a, 2, 3, 4, 5); + let array = array(a, i32(b), 3, 4, 5); let value = array[vi]; + return vec4(vec4(value)); } diff --git a/tests/out/access.msl b/tests/out/access.msl index a87a402ae..8f623b8ab 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -5,11 +5,12 @@ struct _mslBufferSizes { metal::uint size0; }; -typedef int type1[1]; +typedef int type2[1]; struct Bar { - type1 data; + metal::float4x4 matrix; + type2 data; }; -struct type4 { +struct type5 { int inner[5]; }; @@ -23,5 +24,5 @@ vertex fooOutput foo( , device Bar& bar [[buffer(0)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - return fooOutput { static_cast(int4(type4 {bar.data[(1 + (_buffer_sizes.size0 - 0 - 4) / 4) - 1u], 2, 3, 4, 5}.inner[vi])) }; + return fooOutput { static_cast(int4(type5 {bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u], static_cast(bar.matrix[3u].x), 3, 4, 5}.inner[vi])) }; } diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm index d7f3c4082..894968b5f 100644 --- a/tests/out/access.spvasm +++ b/tests/out/access.spvasm @@ -1,70 +1,81 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 42 +; Bound: 49 OpCapability Image1D OpCapability Shader OpCapability Sampled1D OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %23 "foo" %18 %21 +OpEntryPoint Vertex %24 "foo" %19 %22 OpSource GLSL 450 -OpName %11 "Bar" -OpMemberName %11 0 "data" -OpName %15 "bar" -OpName %18 "vi" -OpName %23 "foo" -OpDecorate %10 ArrayStride 4 -OpDecorate %11 Block -OpMemberDecorate %11 0 Offset 0 -OpDecorate %14 ArrayStride 4 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 0 -OpDecorate %18 BuiltIn VertexIndex -OpDecorate %21 BuiltIn Position +OpName %14 "Bar" +OpMemberName %14 0 "matrix" +OpMemberName %14 1 "data" +OpName %16 "bar" +OpName %19 "vi" +OpName %24 "foo" +OpDecorate %13 ArrayStride 4 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 0 ColMajor +OpMemberDecorate %14 0 MatrixStride 16 +OpMemberDecorate %14 1 Offset 64 +OpDecorate %15 ArrayStride 4 +OpDecorate %16 DescriptorSet 0 +OpDecorate %16 Binding 0 +OpDecorate %19 BuiltIn VertexIndex +OpDecorate %22 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeInt 32 0 -%3 = OpConstant %4 1 -%6 = OpTypeInt 32 1 -%5 = OpConstant %6 5 -%7 = OpConstant %6 2 -%8 = OpConstant %6 3 -%9 = OpConstant %6 4 -%10 = OpTypeRuntimeArray %6 -%11 = OpTypeStruct %10 -%13 = OpTypeFloat 32 -%12 = OpTypeVector %13 4 -%14 = OpTypeArray %6 %5 -%16 = OpTypePointer StorageBuffer %11 -%15 = OpVariable %16 StorageBuffer -%19 = OpTypePointer Input %4 -%18 = OpVariable %19 Input -%22 = OpTypePointer Output %12 -%21 = OpVariable %22 Output -%24 = OpTypeFunction %2 -%26 = OpTypePointer StorageBuffer %10 -%29 = OpTypePointer StorageBuffer %6 -%30 = OpConstant %4 0 -%34 = OpTypePointer Function %14 -%37 = OpTypePointer Function %6 -%39 = OpTypeVector %6 4 -%23 = OpFunction %2 None %24 -%17 = OpLabel -%35 = OpVariable %34 Function -%20 = OpLoad %4 %18 -OpBranch %25 -%25 = OpLabel -%27 = OpArrayLength %4 %15 0 -%28 = OpISub %4 %27 %3 -%31 = OpAccessChain %29 %15 %30 %28 -%32 = OpLoad %6 %31 -%33 = OpCompositeConstruct %14 %32 %7 %8 %9 %5 -OpStore %35 %33 -%36 = OpAccessChain %37 %35 %20 -%38 = OpLoad %6 %36 -%40 = OpCompositeConstruct %39 %38 %38 %38 %38 -%41 = OpConvertSToF %12 %40 -OpStore %21 %41 +%3 = OpConstant %4 3 +%5 = OpConstant %4 1 +%7 = OpTypeInt 32 1 +%6 = OpConstant %7 5 +%8 = OpConstant %7 3 +%9 = OpConstant %7 4 +%12 = OpTypeFloat 32 +%11 = OpTypeVector %12 4 +%10 = OpTypeMatrix %11 4 +%13 = OpTypeRuntimeArray %7 +%14 = OpTypeStruct %10 %13 +%15 = OpTypeArray %7 %6 +%17 = OpTypePointer StorageBuffer %14 +%16 = OpVariable %17 StorageBuffer +%20 = OpTypePointer Input %4 +%19 = OpVariable %20 Input +%23 = OpTypePointer Output %11 +%22 = OpVariable %23 Output +%25 = OpTypeFunction %2 +%27 = OpTypePointer StorageBuffer %10 +%28 = OpTypePointer StorageBuffer %11 +%29 = OpConstant %4 0 +%33 = OpTypePointer StorageBuffer %13 +%36 = OpTypePointer StorageBuffer %7 +%41 = OpTypePointer Function %15 +%44 = OpTypePointer Function %7 +%46 = OpTypeVector %7 4 +%24 = OpFunction %2 None %25 +%18 = OpLabel +%42 = OpVariable %41 Function +%21 = OpLoad %4 %19 +OpBranch %26 +%26 = OpLabel +%30 = OpAccessChain %28 %16 %29 %3 +%31 = OpLoad %11 %30 +%32 = OpCompositeExtract %12 %31 0 +%34 = OpArrayLength %4 %16 1 +%35 = OpISub %4 %34 %5 +%37 = OpAccessChain %36 %16 %5 %35 +%38 = OpLoad %7 %37 +%39 = OpConvertFToS %7 %32 +%40 = OpCompositeConstruct %15 %38 %39 %8 %9 %6 +OpStore %42 %40 +%43 = OpAccessChain %44 %42 %21 +%45 = OpLoad %7 %43 +%47 = OpCompositeConstruct %46 %45 %45 %45 %45 +%48 = OpConvertSToF %11 %47 +OpStore %22 %48 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/skybox.spvasm b/tests/out/skybox.spvasm index 6cd768731..16e597cb8 100644 --- a/tests/out/skybox.spvasm +++ b/tests/out/skybox.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 94 +; Bound: 93 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %36 "vs_main" %29 %32 %34 -OpEntryPoint Fragment %86 "fs_main" %79 %82 %85 -OpExecutionMode %86 OriginUpperLeft +OpEntryPoint Fragment %85 "fs_main" %78 %81 %84 +OpExecutionMode %85 OriginUpperLeft OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpDecorate %14 Block @@ -26,9 +26,9 @@ OpDecorate %23 Binding 2 OpDecorate %29 BuiltIn VertexIndex OpDecorate %32 BuiltIn Position OpDecorate %34 Location 0 -OpDecorate %79 BuiltIn FragCoord -OpDecorate %82 Location 0 -OpDecorate %85 Location 0 +OpDecorate %78 BuiltIn FragCoord +OpDecorate %81 Location 0 +OpDecorate %84 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -61,14 +61,16 @@ OpDecorate %85 Location 0 %34 = OpVariable %35 Output %37 = OpTypeFunction %2 %52 = OpTypePointer Uniform %13 -%53 = OpConstant %15 1 -%68 = OpConstant %15 0 -%80 = OpTypePointer Input %10 -%79 = OpVariable %80 Input -%83 = OpTypePointer Input %11 -%82 = OpVariable %83 Input -%85 = OpVariable %33 Output -%91 = OpTypeSampledImage %17 +%53 = OpTypePointer Uniform %10 +%54 = OpConstant %15 0 +%55 = OpConstant %15 1 +%62 = OpConstant %15 2 +%79 = OpTypePointer Input %10 +%78 = OpVariable %79 Input +%82 = OpTypePointer Input %11 +%81 = OpVariable %82 Input +%84 = OpVariable %33 Output +%90 = OpTypeSampledImage %17 %36 = OpFunction %2 None %37 %28 = OpLabel %25 = OpVariable %26 Function @@ -91,44 +93,41 @@ OpStore %27 %42 %49 = OpFMul %7 %48 %6 %50 = OpFSub %7 %49 %8 %51 = OpCompositeConstruct %10 %46 %50 %9 %8 -%54 = OpAccessChain %52 %19 %53 -%55 = OpLoad %13 %54 -%56 = OpCompositeExtract %10 %55 0 -%57 = OpVectorShuffle %11 %56 %56 0 1 2 -%58 = OpAccessChain %52 %19 %53 -%59 = OpLoad %13 %58 -%60 = OpCompositeExtract %10 %59 1 +%56 = OpAccessChain %53 %19 %55 %54 +%57 = OpLoad %10 %56 +%58 = OpVectorShuffle %11 %57 %57 0 1 2 +%59 = OpAccessChain %53 %19 %55 %55 +%60 = OpLoad %10 %59 %61 = OpVectorShuffle %11 %60 %60 0 1 2 -%62 = OpAccessChain %52 %19 %53 -%63 = OpLoad %13 %62 -%64 = OpCompositeExtract %10 %63 2 +%63 = OpAccessChain %53 %19 %55 %62 +%64 = OpLoad %10 %63 %65 = OpVectorShuffle %11 %64 %64 0 1 2 -%66 = OpCompositeConstruct %16 %57 %61 %65 +%66 = OpCompositeConstruct %16 %58 %61 %65 %67 = OpTranspose %16 %66 -%69 = OpAccessChain %52 %19 %68 -%70 = OpLoad %13 %69 -%71 = OpMatrixTimesVector %10 %70 %51 -%72 = OpVectorShuffle %11 %71 %71 0 1 2 -%73 = OpMatrixTimesVector %11 %67 %72 -%74 = OpCompositeConstruct %12 %51 %73 -%75 = OpCompositeExtract %10 %74 0 -OpStore %32 %75 -%76 = OpCompositeExtract %11 %74 1 -OpStore %34 %76 +%68 = OpAccessChain %52 %19 %54 +%69 = OpLoad %13 %68 +%70 = OpMatrixTimesVector %10 %69 %51 +%71 = OpVectorShuffle %11 %70 %70 0 1 2 +%72 = OpMatrixTimesVector %11 %67 %71 +%73 = OpCompositeConstruct %12 %51 %72 +%74 = OpCompositeExtract %10 %73 0 +OpStore %32 %74 +%75 = OpCompositeExtract %11 %73 1 +OpStore %34 %75 OpReturn OpFunctionEnd -%86 = OpFunction %2 None %37 -%77 = OpLabel -%81 = OpLoad %10 %79 -%84 = OpLoad %11 %82 -%78 = OpCompositeConstruct %12 %81 %84 -%87 = OpLoad %17 %21 -%88 = OpLoad %18 %23 -OpBranch %89 -%89 = OpLabel -%90 = OpCompositeExtract %11 %78 1 -%92 = OpSampledImage %91 %87 %88 -%93 = OpImageSampleImplicitLod %10 %92 %90 -OpStore %85 %93 +%85 = OpFunction %2 None %37 +%76 = OpLabel +%80 = OpLoad %10 %78 +%83 = OpLoad %11 %81 +%77 = OpCompositeConstruct %12 %80 %83 +%86 = OpLoad %17 %21 +%87 = OpLoad %18 %23 +OpBranch %88 +%88 = OpLabel +%89 = OpCompositeExtract %11 %77 1 +%91 = OpSampledImage %90 %86 %87 +%92 = OpImageSampleImplicitLod %10 %91 %89 +OpStore %84 %92 OpReturn OpFunctionEnd \ No newline at end of file From 3a0f0144112ff621dd7f731bf455adf6cab19164 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 5 May 2021 17:38:02 +0300 Subject: [PATCH 0797/2212] [glsl-out] Add clip distance feature --- src/back/glsl/features.rs | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 28501b831..9b46d569f 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -28,6 +28,7 @@ bitflags::bitflags! { /// Centroid are available in all GLSL versions we support. const NOPERSPECTIVE_QUALIFIER = 1 << 11; const SAMPLE_QUALIFIER = 1 << 12; + const CLIP_DISTANCE = 1 << 13; } } @@ -90,6 +91,8 @@ impl FeaturesManager { check_feature!(TEXTURE_1D, 0); check_feature!(NOPERSPECTIVE_QUALIFIER, 130); check_feature!(SAMPLE_QUALIFIER, 400, 320); + // gl_ClipDistance is supported by core versions > 1.3 and aren't supported by an es versions without extensions + check_feature!(CLIP_DISTANCE, 130, 300); // Return an error if there are missing features if missing.is_empty() { @@ -170,6 +173,11 @@ impl FeaturesManager { } } + if self.0.contains(Features::CLIP_DISTANCE) && version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_clip_cull_distance.txt + writeln!(out, "#extension GL_EXT_clip_cull_distance : require")?; + } + Ok(()) } } @@ -288,17 +296,25 @@ impl<'a, W> Writer<'a, W> { } } _ => { - if let Some(&Binding::Location { - interpolation, - sampling, - .. - }) = binding - { - if interpolation == Some(Interpolation::Linear) { - self.features.request(Features::NOPERSPECTIVE_QUALIFIER); - } - if sampling == Some(Sampling::Sample) { - self.features.request(Features::SAMPLE_QUALIFIER); + if let Some(binding) = binding { + match *binding { + Binding::BuiltIn(builtin) => { + if builtin == crate::BuiltIn::ClipDistance { + self.features.request(Features::CLIP_DISTANCE); + } + } + Binding::Location { + location: _, + interpolation, + sampling, + } => { + if interpolation == Some(Interpolation::Linear) { + self.features.request(Features::NOPERSPECTIVE_QUALIFIER); + } + if sampling == Some(Sampling::Sample) { + self.features.request(Features::SAMPLE_QUALIFIER); + } + } } } } From 63afb9a215d46d848fe258c2d712ca29487e3438 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 5 May 2021 17:52:50 -0400 Subject: [PATCH 0798/2212] Add Capabilities bitset for validation --- bin/naga.rs | 20 +++++++++++-------- src/back/msl/writer.rs | 4 ++-- src/valid/mod.rs | 16 +++++++++++++-- src/valid/type.rs | 16 +++++++++------ tests/parse.rs | 44 ------------------------------------------ tests/snapshots.rs | 18 +++++++++++------ 6 files changed, 50 insertions(+), 68 deletions(-) delete mode 100644 tests/parse.rs diff --git a/bin/naga.rs b/bin/naga.rs index d9b841ebc..efa7ddd76 100644 --- a/bin/naga.rs +++ b/bin/naga.rs @@ -175,14 +175,18 @@ fn main() { }; // validate the IR - let info = - match naga::valid::Validator::new(naga::valid::ValidationFlags::all()).validate(&module) { - Ok(info) => Some(info), - Err(error) => { - print_err(error); - None - } - }; + let info = match naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + { + Ok(info) => Some(info), + Err(error) => { + print_err(error); + None + } + }; let output_path = match output_path { Some(ref string) => string, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e08f0d61d..3b1f9e3e0 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2307,7 +2307,7 @@ impl Writer { #[test] fn test_stack_size() { - use crate::valid::ValidationFlags; + use crate::valid::{Capabilities, ValidationFlags}; // create a module with at least one expression nested let mut module = crate::Module::default(); let constant = module.constants.append(crate::Constant { @@ -2335,7 +2335,7 @@ fn test_stack_size() { }); let _ = module.functions.append(fun); // analyse the module - let info = crate::valid::Validator::new(ValidationFlags::empty()) + let info = crate::valid::Validator::new(ValidationFlags::empty(), Capabilities::empty()) .validate(&module) .unwrap(); // process the module diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 1191e77b8..8f3ac946b 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -41,6 +41,16 @@ bitflags::bitflags! { } #[must_use] +bitflags::bitflags! { + /// Allowed IR capabilities. + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + pub struct Capabilities: u8 { + /// Float values with width = 8 + const FLOAT64 = 0x1; + } +} + bitflags::bitflags! { /// Validation flags. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -70,6 +80,7 @@ impl ops::Index> for ModuleInfo { #[derive(Debug)] pub struct Validator { flags: ValidationFlags, + capabilities: Capabilities, types: Vec, location_mask: BitSet, bind_group_masks: Vec, @@ -171,9 +182,10 @@ impl crate::TypeInner { impl Validator { /// Construct a new validator instance. - pub fn new(flags: ValidationFlags) -> Self { + pub fn new(flags: ValidationFlags, capabilities: Capabilities) -> Self { Validator { flags, + capabilities, types: Vec::new(), location_mask: BitSet::new(), bind_group_masks: Vec::new(), @@ -192,7 +204,7 @@ impl Validator { let con = &constants[handle]; match con.inner { crate::ConstantInner::Scalar { width, ref value } => { - if !Self::check_width(value.scalar_kind(), width) { + if !self.check_width(value.scalar_kind(), width) { return Err(ConstantError::InvalidType); } } diff --git a/src/valid/type.rs b/src/valid/type.rs index ff34e81fe..056af0508 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -1,3 +1,4 @@ +use super::Capabilities; use crate::arena::{Arena, Handle}; bitflags::bitflags! { @@ -143,10 +144,13 @@ impl TypeInfo { } impl super::Validator { - pub(super) fn check_width(kind: crate::ScalarKind, width: crate::Bytes) -> bool { + pub(super) fn check_width(&self, kind: crate::ScalarKind, width: crate::Bytes) -> bool { match kind { crate::ScalarKind::Bool => width == crate::BOOL_WIDTH, - _ => width == 4, + crate::ScalarKind::Float => { + width == 4 || (width == 8 && self.capabilities.contains(Capabilities::FLOAT64)) + } + crate::ScalarKind::Sint | crate::ScalarKind::Uint => width == 4, } } @@ -164,7 +168,7 @@ impl super::Validator { use crate::TypeInner as Ti; Ok(match types[handle].inner { Ti::Scalar { kind, width } => { - if !Self::check_width(kind, width) { + if !self.check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } TypeInfo::new( @@ -176,7 +180,7 @@ impl super::Validator { ) } Ti::Vector { size, kind, width } => { - if !Self::check_width(kind, width) { + if !self.check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } let count = if size >= crate::VectorSize::Tri { 4 } else { 2 }; @@ -193,7 +197,7 @@ impl super::Validator { rows, width, } => { - if !Self::check_width(crate::ScalarKind::Float, width) { + if !self.check_width(crate::ScalarKind::Float, width) { return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); } let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; @@ -217,7 +221,7 @@ impl super::Validator { width, class: _, } => { - if !Self::check_width(kind, width) { + if !self.check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } TypeInfo::new(TypeFlags::SIZED, 0) diff --git a/tests/parse.rs b/tests/parse.rs deleted file mode 100644 index ff8eacbc9..000000000 --- a/tests/parse.rs +++ /dev/null @@ -1,44 +0,0 @@ -//TODO: consider converting this to snapshots? - -#[cfg(feature = "glsl-in")] -fn _check_glsl(name: &str) { - let path = std::path::PathBuf::from("tests/cases").join(name); - let input = std::fs::read_to_string(path).unwrap(); - let stage = if name.ends_with(".vert") { - naga::ShaderStage::Vertex - } else if name.ends_with(".frag") { - naga::ShaderStage::Fragment - } else if name.ends_with(".comp") { - naga::ShaderStage::Compute - } else { - panic!("Unknown extension in {:?}", name) - }; - - let mut entry_points = naga::FastHashMap::default(); - entry_points.insert("main".to_string(), stage); - match naga::front::glsl::parse_str( - &input, - &naga::front::glsl::Options { - entry_points, - defines: Default::default(), - }, - ) { - Ok(m) => { - match naga::valid::Validator::new(naga::valid::ValidationFlags::all()).validate(&m) { - Ok(_info) => (), - //TODO: panic - Err(e) => log::error!("Unable to validate {}: {:?}", name, e), - } - } - Err(e) => panic!("Unable to parse {}: {:?}", name, e), - }; -} - -#[cfg(feature = "glsl-in")] -#[test] -fn parse_glsl() { - //check_glsl("glsl_constant_expression.vert"); //TODO - //check_glsl("glsl_if_preprocessor.vert"); - //check_glsl("glsl_preprocessor_abuse.vert"); - //check_glsl("glsl_vertex_test_shader.vert"); //TODO -} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 034f91093..90a835db7 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -46,9 +46,12 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), }; - let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all()) - .validate(module) - .unwrap(); + let info = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::empty(), + ) + .validate(module) + .unwrap(); let dest = PathBuf::from(root).join(DIR_OUT).join(name); @@ -282,9 +285,12 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { ) .unwrap(); check_targets(&module, name, targets); - naga::valid::Validator::new(naga::valid::ValidationFlags::all()) - .validate(&module) - .unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::empty(), + ) + .validate(&module) + .unwrap(); } #[cfg(feature = "spv-in")] From 3ffbd50febaae14688b8923346f37c9e0fe8e3ae Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 6 May 2021 01:02:36 -0400 Subject: [PATCH 0799/2212] Minor tweaks to README --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5956919fe..3772b9d2a 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga) [![Build Status](https://github.com/gfx-rs/naga/workflows/pipeline/badge.svg)](https://github.com/gfx-rs/naga/actions) -This is an experimental shader translation library for the needs of gfx-rs project and WebGPU. +The shader translation library for the needs of [wgpu](https://github.com/gfx-rs/wgpu) and [gfx-rs](https://github.com/gfx-rs/gfx) projects. ## Supported end-points @@ -14,9 +14,8 @@ Everything is still work-in-progress, but some end-points are usable: Front-end | Status | Feature | Notes | --------------- | ------------------ | ------- | ----- | SPIR-V (binary) | :white_check_mark: | spv-in | | -WGSL | :white_check_mark: | wgsl-in | | -GLSL | :construction: | glsl-in | Vulkan flavor is expected | -Rust | | | | +WGSL | :white_check_mark: | wgsl-in | Fully validated | +GLSL | :construction: | glsl-in | Temporarily broken | Back-end | Status | Feature | Notes | --------------- | ------------------ | -------- | ----- | From 0960d1162fe924f921d2433287500af7d45b1033 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Tal=C4=8D=C3=ADk?= Date: Thu, 6 May 2021 16:35:29 +0200 Subject: [PATCH 0800/2212] [spv-in] multiple improvements - added constructs - added loop detection - some logic from Tint borrowed for selection constructs --- Cargo.toml | 3 +- src/front/spv/error.rs | 2 + src/front/spv/flow.rs | 647 +++++++++++++++++++++++++++++++++----- src/front/spv/function.rs | 2 +- src/front/spv/mod.rs | 3 + 5 files changed, 579 insertions(+), 78 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index cbe909dcb..c0f34d8bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ pomelo = { version = "0.1.4", optional = true } thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } +rose_tree = { version ="0.2", optional = true } pp-rs = { version = "0.1", optional = true } #env_logger = "0.8" # uncomment temporarily for developing with the binary target @@ -36,7 +37,7 @@ glsl-out = ["petgraph"] msl-out = [] serialize = ["serde"] deserialize = ["serde"] -spv-in = ["petgraph", "spirv"] +spv-in = ["petgraph", "spirv", "rose_tree"] spv-out = ["spirv"] wgsl-in = ["codespan-reporting"] wgsl-out = [] diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 3f0ae9559..1ae8b2313 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -97,6 +97,8 @@ pub enum Error { InvalidTerminator, #[error("invalid edge classification")] InvalidEdgeClassification, + #[error("cycle detected in the CFG during traversal at {0}")] + ControlFlowGraphCycle(crate::front::spv::BlockId), #[error("recursive function call %{0}")] FunctionCallCycle(spirv::Word), #[error("invalid array size {0:?}")] diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 5dd0c3b7c..e8c6a0a85 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -25,13 +25,23 @@ type BlockNodeIndex = NodeIndex; /// Internal representation of a CFG constisting of function's basic blocks. type ControlFlowGraph = petgraph::Graph; +type ConstructNodeIndex = NodeIndex; + +type ConstructsGraph = rose_tree::RoseTree; + /// Control flow graph (CFG) containing relationships between blocks. pub(super) struct FlowGraph { /// flow: ControlFlowGraph, + /// + constructs: ConstructsGraph, + /// Block ID to Node index mapping. Internal helper to speed up the classification. block_to_node: FastHashMap, + + /// Reversed post-order traversal of the `flow` graph. + traversal_order: Vec, } impl FlowGraph { @@ -39,7 +49,13 @@ impl FlowGraph { pub(super) fn new() -> Self { Self { flow: ControlFlowGraph::default(), + constructs: ConstructsGraph::new(ConstructNode { + ty: ConstructType::Function, + ..Default::default() + }) + .0, block_to_node: FastHashMap::default(), + traversal_order: Vec::new(), } } @@ -52,7 +68,9 @@ impl FlowGraph { /// /// 1. Creates edges in the CFG. - /// 2. Classifies types of blocks and edges in the CFG. + /// 2. Computes the traversal order + /// 3. Finds constructs + /// 4. Classifies types of blocks and edges in the CFG. pub(super) fn classify(&mut self) { let block_to_node = &mut self.block_to_node; @@ -156,6 +174,211 @@ impl FlowGraph { }; } + // 2. + self.compute_postorder_traverse(Some(node_index(0))); + self.traversal_order.reverse(); + + for (i, node_index) in self.traversal_order.iter().enumerate() { + self.flow[*node_index].position = i; + } + + for node_index in self.flow.node_indices() { + self.flow[node_index].visited = false; + } + + // 3. + // The stack of enclosing constructs + let mut enclosing = vec![node_index(0)]; + + let postorder_len = self.traversal_order.len(); + let push_construct = |enclosing: &mut Vec, + constructs: &mut ConstructsGraph, + ty: ConstructType, + begin: BlockNodeIndex, + begin_position: usize, + end: BlockNodeIndex, + end_position: usize, + depth: usize| + -> ConstructNodeIndex { + let mut parent_index = *enclosing.last().unwrap_or(&node_index(0)); + + // A loop construct is added right after its associated continue construct. + // In that case, adjust the parent up. + if ty == ConstructType::Loop { + parent_index = constructs.parent(parent_index).unwrap(); + } + + let end_position = if end_position == 0 { + postorder_len + } else { + end_position + }; + + let node_index = constructs.add_child( + parent_index, + ConstructNode { + ty, + begin, + begin_position, + end, + end_position, + ..Default::default() + }, + ); + + let mut construct = constructs[node_index]; + + let parent = { + if let Some(parent) = constructs.parent(parent_index) { + if constructs[parent].depth < depth { + Some(constructs[parent]) + } else { + None + } + } else { + None + } + }; + + construct.enclosing_loop = { + if construct.ty == ConstructType::Loop { + Some(node_index) + } else if let Some(parent) = parent { + parent.enclosing_loop + } else { + None + } + }; + + construct.enclosing_continue = { + if construct.ty == ConstructType::Continue { + Some(node_index) + } else if let Some(parent) = parent { + parent.enclosing_continue + } else { + None + } + }; + + construct.enclosing_loop_or_continue_or_switch = { + if construct.ty == ConstructType::Continue { + Some(node_index) + } else if let Some(parent) = parent { + parent.enclosing_loop_or_continue_or_switch + } else { + None + } + }; + + enclosing.push(node_index); + + node_index + }; + + self.constructs[node_index(0)].begin = self.traversal_order[0]; + + for block_index in self.traversal_order.iter() { + let mut top_construct_index = *enclosing.last().unwrap(); + + if top_construct_index != node_index(0) { + while *block_index == self.constructs[top_construct_index].end { + enclosing.pop().unwrap(); + top_construct_index = *enclosing.last().unwrap(); + } + } + + let depth = self.constructs[top_construct_index].depth; + + if let Some(merge) = self.flow[*block_index].merge { + let merge_index = self.block_to_node[&merge.merge_block_id]; + + match self.flow[*block_index].ty { + Some(ControlFlowNodeType::Loop) => { + let continue_index = self.block_to_node[&merge.continue_block_id.unwrap()]; + + top_construct_index = push_construct( + &mut enclosing, + &mut self.constructs, + ConstructType::Continue, + continue_index, + self.flow[continue_index].position, + merge_index, + self.flow[merge_index].position, + depth, + ); + + // A loop header that is its own continue target will have an + // empty loop construct. Only create a loop construct when + // the continue target is *not* the same as the loop header. + if *block_index != continue_index { + // From the interval rule, the loop construct consists of blocks + // in the block order, starting at the header, until just + // before the continue target. + top_construct_index = push_construct( + &mut enclosing, + &mut self.constructs, + ConstructType::Loop, + *block_index, + self.flow[*block_index].position, + continue_index, + self.flow[continue_index].position, + depth, + ); + + // If the loop header branches to two different blocks inside the loop + // construct, then the loop body should be modeled as an if-selection + // construct + let neighbors: Vec = self + .flow + .neighbors_directed(*block_index, Direction::Outgoing) + .collect(); + if neighbors.len() == 2 && neighbors[0] != neighbors[1] { + let target0_pos = self.flow[neighbors[0]].position; + let target1_pos = self.flow[neighbors[1]].position; + if self.constructs[top_construct_index] + .contains_position(target0_pos) + && self.constructs[top_construct_index] + .contains_position(target1_pos) + { + // Insert a synthetic if-selection + top_construct_index = push_construct( + &mut enclosing, + &mut self.constructs, + ConstructType::Selection, + *block_index, + self.flow[*block_index].position, + continue_index, + self.flow[continue_index].position, + depth + 1, + ); + } + } + } + } + Some(ControlFlowNodeType::Header) => { + let ty = match self.flow[*block_index].terminator { + Terminator::Switch { .. } => ConstructType::Case, + _ => ConstructType::Selection, + }; + + top_construct_index = push_construct( + &mut enclosing, + &mut self.constructs, + ty, + *block_index, + self.flow[*block_index].position, + merge_index, + self.flow[merge_index].position, + depth, + ); + } + _ => {} + } + } + + self.flow[*block_index].construct = top_construct_index; + } + // 2. // Classify Nodes/Edges as one of [Break, Continue, Back] for edge_index in self.flow.edge_indices() { @@ -175,22 +398,101 @@ impl FlowGraph { while let Some((incoming_edge, incoming_source)) = target_incoming_edges.next(&self.flow) { - // Loop continue - if self.flow[incoming_edge] == ControlFlowEdgeType::ForwardContinue { - self.flow[node_source_index].ty = Some(ControlFlowNodeType::Continue); - self.flow[edge_index] = ControlFlowEdgeType::LoopContinue; - } - // Loop break + // Loop break, Switch Break if self.flow[incoming_source].ty == Some(ControlFlowNodeType::Loop) && self.flow[incoming_edge] == ControlFlowEdgeType::ForwardMerge { self.flow[node_source_index].ty = Some(ControlFlowNodeType::Break); self.flow[edge_index] = ControlFlowEdgeType::LoopBreak; } + + // Loop continue + if self.flow[incoming_edge] == ControlFlowEdgeType::ForwardContinue { + self.flow[node_source_index].ty = Some(ControlFlowNodeType::Continue); + self.flow[edge_index] = ControlFlowEdgeType::LoopContinue; + } + } + + // If break + let construct_index = self.flow[node_source_index].construct; + let header_index = self.constructs[construct_index].begin; + if let Some(merge) = self.flow[header_index].merge { + if self.flow[node_target_index].id == merge.merge_block_id { + self.flow[edge_index] = ControlFlowEdgeType::IfBreak; + } } } } + fn header_if_breakable(&self, construct_index: ConstructNodeIndex) -> Option { + match self.constructs[construct_index].ty { + ConstructType::Loop | ConstructType::Case => { + Some(self.constructs[construct_index].begin) + } + ConstructType::Continue => { + let continue_target = self.constructs[construct_index].begin; + Some( + self.flow + .neighbors_directed(continue_target, Direction::Outgoing) + .next() + .unwrap(), + ) + } + _ => None, + } + } + + fn compute_postorder_traverse(&mut self, node_index: Option) { + if node_index.is_none() { + return; + } + let node_index = node_index.unwrap(); + + if self.flow[node_index].visited { + return; + } + self.flow[node_index].visited = true; + + if let Some(merge) = self.flow[node_index].merge { + self.compute_postorder_traverse(Some(self.block_to_node[&merge.merge_block_id])); + } + + let continue_edge = self + .flow + .edges_directed(node_index, Direction::Outgoing) + .find(|&ty| *ty.weight() == ControlFlowEdgeType::ForwardContinue) + .map(|continue_edge| continue_edge.target()); + self.compute_postorder_traverse(continue_edge); + + let terminator = self.flow[node_index].terminator.clone(); + match terminator { + Terminator::BranchConditional { + condition: _, + true_id, + false_id, + } => { + self.compute_postorder_traverse(Some(self.block_to_node[&false_id])); + self.compute_postorder_traverse(Some(self.block_to_node[&true_id])); + } + Terminator::Branch { target_id } => { + self.compute_postorder_traverse(Some(self.block_to_node[&target_id])); + } + Terminator::Switch { + selector: _, + default, + ref targets, + } => { + self.compute_postorder_traverse(Some(self.block_to_node[&default])); + for target in targets.iter() { + self.compute_postorder_traverse(Some(self.block_to_node[&target.1])); + } + } + _ => {} + }; + + self.traversal_order.push(node_index); + } + /// Removes OpPhi instructions from the control flow graph and turns them into ordinary variables. /// /// Phi instructions are not supported inside Naga nor do they exist as instructions on CPUs. It is necessary @@ -217,23 +519,29 @@ impl FlowGraph { } /// Traverses the flow graph and returns a list of Naga's statements. - pub(super) fn to_naga(&self) -> Result { - self.naga_traverse(node_index(0), None) + pub(super) fn convert_to_naga(&mut self) -> Result { + self.convert_to_naga_traverse(node_index(0), std::collections::HashSet::new()) } - fn naga_traverse( - &self, + fn convert_to_naga_traverse( + &mut self, node_index: BlockNodeIndex, - stop_node_index: Option, + stop_nodes: std::collections::HashSet, ) -> Result { - if stop_node_index == Some(node_index) { + if stop_nodes.contains(&node_index) { return Ok(vec![]); } - let node = &self.flow[node_index]; + if self.flow[node_index].visited { + return Err(Error::ControlFlowGraphCycle(self.flow[node_index].id)); + } - match node.ty { - Some(ControlFlowNodeType::Header) => match node.terminator { + self.flow[node_index].visited = true; + + let terminator = self.flow[node_index].terminator.clone(); + + match self.flow[node_index].ty { + Some(ControlFlowNodeType::Header) => match terminator { Terminator::BranchConditional { condition, true_id, @@ -241,37 +549,71 @@ impl FlowGraph { } => { let true_node_index = self.block_to_node[&true_id]; let false_node_index = self.block_to_node[&false_id]; - let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; + let merge_node_index = + self.block_to_node[&self.flow[node_index].merge.unwrap().merge_block_id]; - let mut result = node.block.clone(); + let premerge_index: Option = { + let second_head = self.flow[true_node_index] + .position + .max(self.flow[false_node_index].position); + let end_first_clause = self.traversal_order[second_head - 1]; - if false_node_index != merge_node_index { - result.push(crate::Statement::If { - condition, - accept: self.naga_traverse(true_node_index, Some(merge_node_index))?, - reject: self.naga_traverse(false_node_index, Some(merge_node_index))?, - }); + self.flow + .edges_directed(end_first_clause, Direction::Outgoing) + .find(|e| match *e.weight() { + ControlFlowEdgeType::Forward + | ControlFlowEdgeType::ForwardContinue + | ControlFlowEdgeType::ForwardMerge + | ControlFlowEdgeType::IfFalse + | ControlFlowEdgeType::IfTrue => self.constructs + [self.flow[node_index].construct] + .contains_position(self.flow[e.target()].position), + _ => false, + }) + .map(|e| e.target()) + }; + + let is_false_inside_construct = self.constructs + [self.flow[node_index].construct] + .contains_position(self.flow[false_node_index].position); + + let intended_merge = if let Some(premerge_index) = premerge_index { + premerge_index } else { - let true_merges_to_false = has_path_connecting( - &self.flow, - true_node_index, - false_node_index, - None, - ); - let stop_node_index = if true_merges_to_false { - Some(merge_node_index) - } else { - stop_node_index - }; + merge_node_index + }; + let then_end_index = if is_false_inside_construct { + false_node_index + } else { + intended_merge + }; + let else_end_index = if let Some(premerge_index) = premerge_index { + premerge_index + } else { + intended_merge + }; - result.push(crate::Statement::If { - condition, - accept: self.naga_traverse(true_node_index, stop_node_index)?, - reject: vec![], - }); - } + let mut result: crate::Block = + std::mem::replace(&mut self.flow[node_index].block, Vec::new()); - result.extend(self.naga_traverse(merge_node_index, stop_node_index)?); + let mut accept_stop_nodes = stop_nodes.clone(); + accept_stop_nodes.insert(merge_node_index); + accept_stop_nodes.insert(intended_merge); + accept_stop_nodes.insert(then_end_index); + let mut reject_stop_nodes = stop_nodes.clone(); + reject_stop_nodes.insert(merge_node_index); + reject_stop_nodes.insert(intended_merge); + reject_stop_nodes.insert(else_end_index); + + result.push(crate::Statement::If { + condition, + accept: self + .convert_to_naga_traverse(true_node_index, accept_stop_nodes)?, + reject: self + .convert_to_naga_traverse(false_node_index, reject_stop_nodes)?, + }); + + result.extend(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); Ok(result) } @@ -280,10 +622,15 @@ impl FlowGraph { default, ref targets, } => { - let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; - let mut result = node.block.clone(); + let merge_node_index = + self.block_to_node[&self.flow[node_index].merge.unwrap().merge_block_id]; + let mut result: crate::Block = + std::mem::replace(&mut self.flow[node_index].block, Vec::new()); let mut cases = Vec::with_capacity(targets.len()); + let mut stop_nodes_cases = stop_nodes.clone(); + stop_nodes_cases.insert(merge_node_index); + for i in 0..targets.len() { let left_target_node_index = self.block_to_node[&targets[i].1]; @@ -301,8 +648,10 @@ impl FlowGraph { cases.push(crate::SwitchCase { value: targets[i].0, - body: self - .naga_traverse(left_target_node_index, Some(merge_node_index))?, + body: self.convert_to_naga_traverse( + left_target_node_index, + stop_nodes_cases.clone(), + )?, fall_through, }); } @@ -310,30 +659,38 @@ impl FlowGraph { result.push(crate::Statement::Switch { selector, cases, - default: self - .naga_traverse(self.block_to_node[&default], Some(merge_node_index))?, + default: self.convert_to_naga_traverse( + self.block_to_node[&default], + stop_nodes_cases, + )?, }); - result.extend(self.naga_traverse(merge_node_index, stop_node_index)?); + result.extend(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); Ok(result) } _ => Err(Error::InvalidTerminator), }, Some(ControlFlowNodeType::Loop) => { - let merge_node_index = self.block_to_node[&node.merge.unwrap().merge_block_id]; + let merge_node_index = + self.block_to_node[&self.flow[node_index].merge.unwrap().merge_block_id]; let continuing: crate::Block = { let continue_edge = self .flow .edges_directed(node_index, Direction::Outgoing) .find(|&ty| *ty.weight() == ControlFlowEdgeType::ForwardContinue) - .unwrap(); + .unwrap() + .target(); - self.flow[continue_edge.target()].block.clone() + std::mem::replace(&mut self.flow[continue_edge].block, Vec::new()) }; - let mut body = node.block.clone(); - match node.terminator { + let mut body: crate::Block = + std::mem::replace(&mut self.flow[node_index].block, Vec::new()); + + let mut stop_nodes_merge = stop_nodes.clone(); + stop_nodes_merge.insert(merge_node_index); + match self.flow[node_index].terminator { Terminator::BranchConditional { condition, true_id, @@ -347,29 +704,36 @@ impl FlowGraph { accept: if true_node_index == merge_node_index { vec![crate::Statement::Break] } else { - self.naga_traverse(true_node_index, Some(merge_node_index))? + self.convert_to_naga_traverse( + true_node_index, + stop_nodes_merge.clone(), + )? }, reject: if false_node_index == merge_node_index { vec![crate::Statement::Break] } else { - self.naga_traverse(false_node_index, Some(merge_node_index))? + self.convert_to_naga_traverse(false_node_index, stop_nodes_merge)? }, }); } - Terminator::Branch { target_id } => body.extend( - self.naga_traverse(self.block_to_node[&target_id], Some(merge_node_index))?, - ), + Terminator::Branch { target_id } => { + body.extend(self.convert_to_naga_traverse( + self.block_to_node[&target_id], + stop_nodes_merge, + )?) + } _ => return Err(Error::InvalidTerminator), }; let mut result = vec![crate::Statement::Loop { body, continuing }]; - result.extend(self.naga_traverse(merge_node_index, stop_node_index)?); + result.extend(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); Ok(result) } Some(ControlFlowNodeType::Break) => { - let mut result = node.block.clone(); - match node.terminator { + let mut result: crate::Block = + std::mem::replace(&mut self.flow[node_index].block, Vec::new()); + match self.flow[node_index].terminator { Terminator::BranchConditional { condition, true_id, @@ -387,12 +751,12 @@ impl FlowGraph { result.push(crate::Statement::If { condition, accept: vec![crate::Statement::Break], - reject: self.naga_traverse(false_node_id, stop_node_index)?, + reject: self.convert_to_naga_traverse(false_node_id, stop_nodes)?, }); } else if false_edge == ControlFlowEdgeType::LoopBreak { result.push(crate::Statement::If { condition, - accept: self.naga_traverse(true_node_id, stop_node_index)?, + accept: self.convert_to_naga_traverse(true_node_id, stop_nodes)?, reject: vec![crate::Statement::Break], }); } else { @@ -406,31 +770,38 @@ impl FlowGraph { }; Ok(result) } - Some(ControlFlowNodeType::Continue) => Ok(node.block.clone()), - Some(ControlFlowNodeType::Back) => Ok(node.block.clone()), + Some(ControlFlowNodeType::Continue) | Some(ControlFlowNodeType::Back) => Ok( + std::mem::replace(&mut self.flow[node_index].block, Vec::new()), + ), Some(ControlFlowNodeType::Kill) => { - let mut result = node.block.clone(); + let mut result: crate::Block = + std::mem::replace(&mut self.flow[node_index].block, Vec::new()); result.push(crate::Statement::Kill); Ok(result) } Some(ControlFlowNodeType::Return) => { - let value = match node.terminator { + let value = match self.flow[node_index].terminator { Terminator::Return { value } => value, _ => return Err(Error::InvalidTerminator), }; - let mut result = node.block.clone(); + let mut result: crate::Block = + std::mem::replace(&mut self.flow[node_index].block, Vec::new()); result.push(crate::Statement::Return { value }); Ok(result) } - Some(ControlFlowNodeType::Merge) | None => match node.terminator { + Some(ControlFlowNodeType::Merge) | None => match self.flow[node_index].terminator { Terminator::Branch { target_id } => { - let mut result = node.block.clone(); + let mut result: crate::Block = + std::mem::replace(&mut self.flow[node_index].block, Vec::new()); result.extend( - self.naga_traverse(self.block_to_node[&target_id], stop_node_index)?, + self.convert_to_naga_traverse(self.block_to_node[&target_id], stop_nodes)?, ); Ok(result) } - _ => Ok(node.block.clone()), + _ => Ok(std::mem::replace( + &mut self.flow[node_index].block, + Vec::new(), + )), }, } } @@ -443,15 +814,25 @@ impl FlowGraph { for node_index in self.flow.node_indices() { let node = &self.flow[node_index]; + let shape = if self.constructs[node.construct].ty == ConstructType::Case + && node.ty != Some(ControlFlowNodeType::Header) + { + "point" + } else { + "ellipse" + }; writeln!( output, - "{} [ label = \"%{} {:?}\" ]", + "{} [ label = \"%{} {:?}\" shape={} ]", node_index.index(), node.id, - node.ty + node.ty, + shape )?; } + self.to_graphviz_constructs(&mut output, node_index(0))?; + for edge in self.flow.raw_edges() { let source = edge.source(); let target = edge.target(); @@ -466,6 +847,7 @@ impl FlowGraph { ControlFlowEdgeType::IfTrue => "color=blue", ControlFlowEdgeType::IfFalse => "color=red", ControlFlowEdgeType::SwitchBreak => "color=yellow", + ControlFlowEdgeType::IfBreak => "color=yellow", ControlFlowEdgeType::CaseFallThrough => "style=dotted", }; @@ -482,6 +864,39 @@ impl FlowGraph { Ok(output) } + + fn to_graphviz_constructs( + &self, + output: &mut String, + node_index: ConstructNodeIndex, + ) -> Result<(), std::fmt::Error> { + let construct = self.constructs[node_index]; + + writeln!( + output, + "subgraph cluster_{:?} {{ label = {:?}", + construct.ty, construct.ty + )?; + + let traversal_order_begin = self.flow[construct.begin].position; + let traversal_order_end = if construct.end.index() >= self.traversal_order.len() { + self.traversal_order.len() - 1 + } else { + self.flow[construct.end].position + }; + + for i in traversal_order_begin..=traversal_order_end { + write!(output, "{} ", self.traversal_order[i].index())?; + } + + for child_index in self.constructs.children(node_index) { + self.to_graphviz_constructs(output, child_index)?; + } + + writeln!(output, "}}",)?; + + Ok(()) + } } /// Type of an edge(flow) in the `ControlFlowGraph`. @@ -521,6 +936,12 @@ pub(super) enum ControlFlowEdgeType { /// where there is no intervening loop. SwitchBreak, + // An edge from a node to the merge block of the nearest enclosing structured + // construct, but which is neither a kSwitchBreak or a kLoopBreak. + // This can only occur for an "if" selection, i.e. where the selection + // header ends in OpBranchConditional. + IfBreak, + /// An edge from one switch case to the next sibling switch case. CaseFallThrough, } @@ -568,6 +989,80 @@ pub(super) struct ControlFlowNode { /// Termination instruction of the block. pub terminator: Terminator, - /// Merge Instruction + /// Merge Instruction. pub merge: Option, + + /// Construct that this block belongs to. + pub construct: ConstructNodeIndex, + + /// Position in the postorder traversal. + pub position: usize, + + /// Flag determining whether this node was already visited by the graph traversal while converting a SPIR-V to Naga's IR. + /// This flag serves as a check in case an incorrect SPIR-V is supplied to the front-end. When a SPIR-V is correct there can be no cycles in it and there is no reason + /// to visit any node twice. + pub visited: bool, +} +/// Type of a node(block) in the `ConstructsGraph`. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub(super) enum ConstructType { + /// Includes all the nodes in the `ControlFlowGraph`. + Function, + /// Includes the nodes(blocks) dominated by a `ControlFlowNodeType::Header` node(block), while excluding nodes(blocks) dominated by the selection construct’s `ControlFlowNodeType::Merge` node(block). + Selection, + /// Includes the nodes(blocks) dominated by a `ControlFlowNodeType::Loop` Continue Target and post dominated by the corresponding loop’s `ControlFlowNodeType::Back` block, while excluding blocks dominated by that `ControlFlowNodeType::Merge` node(block). + Continue, + /// Includes the nodes(blocks) dominated by a `ControlFlowNodeType::Loop`, while excluding both that header’s continue construct and the blocks dominated by the loop’s `ControlFlowNodeType::Merge` node(block). + Loop, + /// Includes the nodes(blocks) dominated by an OpSwitch Target or Default (this construct is only defined for those OpSwitch Target or Default that are not equal to the OpSwitch’s corresponding merge block) + Case, +} + +impl Default for ConstructType { + fn default() -> Self { + ConstructType::Function + } +} + +/// ConstructsGraph's construct node that encompasses a series of blocks in `ControlFlowGraph` +#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)] +pub(super) struct ConstructNode { + /// + pub ty: ConstructType, + + /// + pub begin: BlockNodeIndex, + + /// + pub begin_position: usize, + + /// + pub end: BlockNodeIndex, + + /// + pub end_position: usize, + + /// Control flow nesting depth. The entry block is at nesting depth 0. + pub depth: usize, + + /// The nearest enclosing loop construct, if one exists. Points to itself + /// when this is a loop construct. + pub enclosing_loop: Option, + + /// The nearest enclosing continue construct, if one exists. Points to + /// itself when this is a contnue construct. + pub enclosing_continue: Option, + + /// The nearest enclosing loop construct or continue construct or + /// switch-selection construct, if one exists. The signficance is + /// that a high level language "break" will branch to the merge block + /// of such an enclosing construct. Points to itself when this is + /// a loop construct, a continue construct, or a switch-selection construct. + pub enclosing_loop_or_continue_or_switch: Option, +} + +impl ConstructNode { + pub(super) fn contains_position(&self, position: usize) -> bool { + self.begin_position <= position && position < self.end_position + } } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index a01ed51d6..16f30a69b 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -181,7 +181,7 @@ impl> super::Parser { } } - fun.body = flow_graph.to_naga()?; + fun.body = flow_graph.convert_to_naga()?; // done let fun_handle = module.functions.append(fun); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index dd23f90dc..3f8b5031f 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2148,6 +2148,9 @@ impl> Parser { block, terminator, merge, + construct: petgraph::graph::node_index(0), + position: 0, + visited: false, }) } From 84eac75f71519ba8f25422b76c7acf90dc21381f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 6 May 2021 12:34:05 -0400 Subject: [PATCH 0801/2212] Fix new clippy errors --- src/back/spv/writer.rs | 2 +- src/front/spv/function.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 949b0b826..df9a77ba4 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -557,8 +557,8 @@ impl Writer { }; let lookup_function_type = LookupFunctionType { - return_type_id, parameter_type_ids, + return_type_id, }; let function_id = self.id_gen.next(); diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 16f30a69b..952b693e0 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -107,7 +107,7 @@ impl> super::Parser { .expressions .append(crate::Expression::FunctionArgument(i as u32)); self.lookup_expression - .insert(id, LookupExpression { type_id, handle }); + .insert(id, LookupExpression { handle, type_id }); //Note: we redo the lookup in order to work around `self` borrowing if type_id From a37c37b8f5f3a426bcaa2d90ecec353a4ca40f61 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 6 May 2021 12:24:57 -0400 Subject: [PATCH 0802/2212] Integrate codecov on CI --- .github/workflows/lazy.yml | 28 ++++++++++++++++++++++++++++ .github/workflows/pipeline.yml | 1 + README.md | 1 + 3 files changed, 30 insertions(+) create mode 100644 .github/workflows/lazy.yml diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml new file mode 100644 index 000000000..7344fdac0 --- /dev/null +++ b/.github/workflows/lazy.yml @@ -0,0 +1,28 @@ +# Lazy jobs running on master post merges. +name: lazy +on: + push: + branches: [master] + +jobs: + coverage: + name: Coverage + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + - name: Generate report + uses: actions-rs/tarpaulin@v0.1 + with: + args: '--tests --all-features' + - name: Upload to codecov.io + uses: codecov/codecov-action@v1 + with: + token: ${{ secrets.CODECOV_TOKEN }} + - name: Archive code coverage results + uses: actions/upload-artifact@v1 + with: + name: code-coverage-report + path: cobertura.xml diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 3d9ca0f6a..57d80e5a2 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -1,3 +1,4 @@ +# Regular testing. name: pipeline on: [push, pull_request] diff --git a/README.md b/README.md index 3772b9d2a..6b0adf349 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![Crates.io](https://img.shields.io/crates/v/naga.svg?label=naga)](https://crates.io/crates/naga) [![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga) [![Build Status](https://github.com/gfx-rs/naga/workflows/pipeline/badge.svg)](https://github.com/gfx-rs/naga/actions) +[![codecov.io](https://codecov.io/gh/gfx-rs/naga/branch/master/graph/badge.svg?token=9VOKYO8BM2)](https://codecov.io/gh/gfx-rs/naga) The shader translation library for the needs of [wgpu](https://github.com/gfx-rs/wgpu) and [gfx-rs](https://github.com/gfx-rs/gfx) projects. From 09032695b0984ec9621ff3a66e5a4179c23d91f3 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 6 May 2021 14:29:23 -0400 Subject: [PATCH 0803/2212] Barrier follow-up fixes --- src/back/glsl/mod.rs | 7 +++---- src/back/msl/writer.rs | 9 +++++++++ src/front/spv/mod.rs | 6 +++++- src/lib.rs | 6 ++++-- tests/in/control-flow.wgsl | 1 + tests/out/control-flow.Compute.glsl | 2 +- 6 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a67ddd0e9..f433c6bc0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1393,12 +1393,11 @@ impl<'a, W: Write> Writer<'a, W> { // keyword which ceases all further processing in a fragment shader, it's called OpKill // in spir-v that's why it's called `Statement::Kill` Statement::Kill => writeln!(self.out, "{}discard;", INDENT.repeat(indent))?, - // Just issue a memory barrier, ignoring the flags. + // Issue an execution or a memory barrier. Statement::Barrier(flags) => { - if flags.contains(crate::Barrier::WORK_GROUP) { + if flags.is_empty() { writeln!(self.out, "{}barrier();", INDENT.repeat(indent))?; - } - if flags.contains(crate::Barrier::STORAGE) { + } else { writeln!(self.out, "{}groupMemoryBarrier();", INDENT.repeat(indent))?; } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 3b1f9e3e0..ed0076881 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1348,6 +1348,15 @@ impl Writer { writeln!(self.out, "{}{}::discard_fragment();", level, NAMESPACE)?; } crate::Statement::Barrier(flags) => { + //Note: OR-ring bitflags requires `__HAVE_MEMFLAG_OPERATORS__`, + // so we try to avoid it here. + if flags.is_empty() { + writeln!( + self.out, + "{}{}::threadgroup_barrier({}::mem_flags::mem_none);", + level, NAMESPACE, NAMESPACE, + )?; + } if flags.contains(crate::Barrier::STORAGE) { writeln!( self.out, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3f8b5031f..3b9be2606 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2129,7 +2129,11 @@ impl> Parser { ); flags.set( crate::Barrier::WORK_GROUP, - semantics & spirv::MemorySemantics::WORKGROUP_MEMORY.bits() != 0, + semantics + & (spirv::MemorySemantics::SUBGROUP_MEMORY + | spirv::MemorySemantics::WORKGROUP_MEMORY) + .bits() + != 0, ); block.push(crate::Statement::Barrier(flags)); } else { diff --git a/src/lib.rs b/src/lib.rs index 40027b4cf..594cfacfc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -697,7 +697,7 @@ pub enum SwizzleComponent { } bitflags::bitflags! { - /// Control barrier flags. + /// Memory barrier flags. #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[derive(Default)] @@ -884,7 +884,9 @@ pub enum Statement { Return { value: Option> }, /// Aborts the current shader execution. Kill, - /// Synchronize accesses within the work group. + /// Synchronize invocations within the work group. + /// The `Barrier` flags control which memory accesses should be synchronized. + /// If empty, this becomes purely an execution barrier. Barrier(Barrier), /// Stores a value at an address. /// diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index 4411d179a..893546e43 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -1,5 +1,6 @@ [[stage(compute), workgroup_size(1)]] fn main([[builtin(global_invocation_id)]] global_id: vec3) { + //TODO: execution-only barrier? storageBarrier(); workgroupBarrier(); } diff --git a/tests/out/control-flow.Compute.glsl b/tests/out/control-flow.Compute.glsl index 15390223c..259916328 100644 --- a/tests/out/control-flow.Compute.glsl +++ b/tests/out/control-flow.Compute.glsl @@ -8,7 +8,7 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; void main() { uvec3 global_id = gl_GlobalInvocationID; groupMemoryBarrier(); - barrier(); + groupMemoryBarrier(); return; } From f18a97785fbcdf648d24332e77ba36d7df11bd55 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 6 May 2021 23:09:13 -0400 Subject: [PATCH 0804/2212] Expect *.txt instead of - for the debug output of the converter --- README.md | 2 +- bin/naga.rs | 17 +++++++++-------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 6b0adf349..cd8420c72 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ DOT (GraphViz) | :ok: | dot-out | Not a shading language | Naga includes a default binary target, which allows to test the conversion of different code paths. ```bash cargo run --features wgsl-in -- my_shader.wgsl # validate only -cargo run --features spv-in -- my_shader.spv - # dump the IR module to debug output +cargo run --features spv-in -- my_shader.spv my_shader.txt # dump the IR module into a file cargo run --features spv-in,msl-out -- my_shader.spv my_shader.metal --flow-dir flow-dir # convert the SPV to Metal, also dump the SPIR-V flow graph to `flow-dir` cargo run --features wgsl-in,glsl-out -- my_shader.wgsl my_shader.vert --profile es310 # convert the WGSL to GLSL vertex stage under ES 3.20 profile ``` diff --git a/bin/naga.rs b/bin/naga.rs index efa7ddd76..3f640e1d5 100644 --- a/bin/naga.rs +++ b/bin/naga.rs @@ -199,14 +199,6 @@ fn main() { } } }; - if output_path == "-" { - println!("{:#?}", module); - if let Some(info) = info { - println!(); - println!("{:#?}", info); - } - return; - } match Path::new(output_path) .extension() @@ -214,6 +206,15 @@ fn main() { .to_str() .unwrap() { + "txt" => { + use std::io::Write; + let mut file = fs::File::create(output_path).unwrap(); + writeln!(file, "{:#?}", module).unwrap(); + if let Some(info) = info { + writeln!(file).unwrap(); + writeln!(file, "{:#?}", info).unwrap(); + } + } #[cfg(feature = "msl-out")] "metal" => { use naga::back::msl; From 01f4922806ca0aa1222ed7d9524853d86b21f8f8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 7 May 2021 00:15:08 -0400 Subject: [PATCH 0805/2212] Validation parameter for the converter --- bin/naga.rs | 8 +++++++- src/valid/mod.rs | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/bin/naga.rs b/bin/naga.rs index 3f640e1d5..ea1644947 100644 --- a/bin/naga.rs +++ b/bin/naga.rs @@ -5,6 +5,7 @@ use std::{env, error::Error, path::Path}; #[derive(Default)] struct Parameters { + validation_flags: naga::valid::ValidationFlags, #[cfg(feature = "spv-in")] spv_adjust_coordinate_space: bool, #[cfg(feature = "spv-in")] @@ -60,6 +61,11 @@ fn main() { //TODO: use `strip_prefix` when MSRV reaches 1.45.0 if arg.starts_with("--") { match &arg[2..] { + "validate" => { + let value = args.next().unwrap().parse().unwrap(); + params.validation_flags = + naga::valid::ValidationFlags::from_bits(value).unwrap(); + } #[cfg(feature = "spv-in")] "flow-dir" => params.spv_flow_dump_prefix = args.next(), #[cfg(feature = "glsl-out")] @@ -176,7 +182,7 @@ fn main() { // validate the IR let info = match naga::valid::Validator::new( - naga::valid::ValidationFlags::all(), + params.validation_flags, naga::valid::Capabilities::all(), ) .validate(&module) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 8f3ac946b..558b75bd4 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -40,6 +40,12 @@ bitflags::bitflags! { } } +impl Default for ValidationFlags { + fn default() -> Self { + Self::all() + } +} + #[must_use] bitflags::bitflags! { /// Allowed IR capabilities. From 10c4c906da9e19c5f061d04ae0ab6b76a0088f65 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 7 May 2021 00:43:04 -0400 Subject: [PATCH 0806/2212] [msl] move ArrayLength logic out --- src/back/msl/writer.rs | 98 +++++++++++++++++++++++------------------- 1 file changed, 53 insertions(+), 45 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ed0076881..fea678c57 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -541,6 +541,58 @@ impl Writer { Ok(()) } + fn put_array_length( + &mut self, + expr: Handle, + context: &ExpressionContext, + ) -> Result<(), Error> { + let handle = match context.function.expressions[expr] { + crate::Expression::AccessIndex { base, .. } => { + match context.function.expressions[base] { + crate::Expression::GlobalVariable(handle) => handle, + _ => return Err(Error::Validation), + } + } + _ => return Err(Error::Validation), + }; + + let global = &context.module.global_variables[handle]; + if let crate::TypeInner::Struct { ref members, .. } = context.module.types[global.ty].inner + { + if let Some(&crate::StructMember { + offset, + ty: array_ty, + .. + }) = members.last() + { + let (span, stride) = match context.module.types[array_ty].inner { + crate::TypeInner::Array { base, stride, .. } => ( + context.module.types[base] + .inner + .span(&context.module.constants), + stride, + ), + _ => return Err(Error::Validation), + }; + + let buffer_idx = self.runtime_sized_buffers[&handle]; + write!( + self.out, + "(1 + (_buffer_sizes.size{idx} - {offset} - {span}) / {stride})", + idx = buffer_idx, + offset = offset, + span = span, + stride = stride, + )?; + Ok(()) + } else { + Err(Error::Validation) + } + } else { + Err(Error::Validation) + } + } + fn put_expression( &mut self, expr_handle: Handle, @@ -1063,51 +1115,7 @@ impl Writer { // has to be a named expression crate::Expression::Call(_) => unreachable!(), crate::Expression::ArrayLength(expr) => { - let handle = match context.function.expressions[expr] { - crate::Expression::AccessIndex { base, .. } => { - match context.function.expressions[base] { - crate::Expression::GlobalVariable(handle) => handle, - _ => return Err(Error::Validation), - } - } - _ => return Err(Error::Validation), - }; - - let global = &context.module.global_variables[handle]; - if let crate::TypeInner::Struct { ref members, .. } = - context.module.types[global.ty].inner - { - if let Some(&crate::StructMember { - offset, - ty: array_ty, - .. - }) = members.last() - { - let (span, stride) = match context.module.types[array_ty].inner { - crate::TypeInner::Array { base, stride, .. } => ( - context.module.types[base] - .inner - .span(&context.module.constants), - stride, - ), - _ => return Err(Error::Validation), - }; - - let buffer_idx = self.runtime_sized_buffers[&handle]; - write!( - self.out, - "(1 + (_buffer_sizes.size{idx} - {offset} - {span}) / {stride})", - idx = buffer_idx, - offset = offset, - span = span, - stride = stride, - )?; - } else { - return Err(Error::Validation); - } - } else { - return Err(Error::Validation); - } + self.put_array_length(expr, context)?; } } Ok(()) From bbb1b6b366ecb9e3a33199e957baf91c7139aeea Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 7 May 2021 00:52:30 -0400 Subject: [PATCH 0807/2212] [msl] move Compose into a helper method --- src/back/msl/writer.rs | 169 +++++++++++++++++++++++------------------ 1 file changed, 94 insertions(+), 75 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index fea678c57..8510e5ca3 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -541,6 +541,96 @@ impl Writer { Ok(()) } + fn put_image_sample_level( + &mut self, + image: Handle, + level: crate::SampleLevel, + context: &ExpressionContext, + ) -> Result<(), Error> { + let has_levels = match *context.resolve_type(image) { + crate::TypeInner::Image { + dim: crate::ImageDimension::D1, + .. + } => false, + _ => true, + }; + match level { + crate::SampleLevel::Auto => {} + crate::SampleLevel::Zero => { + //TODO: do we support Zero on `Sampled` image classes? + } + _ if !has_levels => { + log::warn!("1D image can't be sampled with level {:?}", level); + } + crate::SampleLevel::Exact(h) => { + write!(self.out, ", {}::level(", NAMESPACE)?; + self.put_expression(h, context, true)?; + write!(self.out, ")")?; + } + crate::SampleLevel::Bias(h) => { + write!(self.out, ", {}::bias(", NAMESPACE)?; + self.put_expression(h, context, true)?; + write!(self.out, ")")?; + } + crate::SampleLevel::Gradient { x, y } => { + write!(self.out, ", {}::gradient(", NAMESPACE)?; + self.put_expression(x, context, true)?; + write!(self.out, ", ")?; + self.put_expression(y, context, true)?; + write!(self.out, ")")?; + } + } + Ok(()) + } + + fn put_compose( + &mut self, + ty: Handle, + components: &[Handle], + context: &ExpressionContext, + ) -> Result<(), Error> { + match context.module.types[ty].inner { + crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { + write!(self.out, "{}", scalar_kind_string(kind))?; + self.put_call_parameters(components.iter().cloned(), context)?; + } + crate::TypeInner::Vector { size, kind, .. } => { + write!( + self.out, + "{}::{}{}", + NAMESPACE, + scalar_kind_string(kind), + vector_size_str(size) + )?; + self.put_call_parameters(components.iter().cloned(), context)?; + } + crate::TypeInner::Matrix { columns, rows, .. } => { + let kind = crate::ScalarKind::Float; + write!( + self.out, + "{}::{}{}x{}", + NAMESPACE, + scalar_kind_string(kind), + vector_size_str(columns), + vector_size_str(rows) + )?; + self.put_call_parameters(components.iter().cloned(), context)?; + } + crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { + write!(self.out, "{} {{", &self.names[&NameKey::Type(ty)])?; + for (i, &component) in components.iter().enumerate() { + if i != 0 { + write!(self.out, ", ")?; + } + self.put_expression(component, context, true)?; + } + write!(self.out, "}}")?; + } + _ => return Err(Error::UnsupportedCompose(ty)), + } + Ok(()) + } + fn put_array_length( &mut self, expr: Handle, @@ -701,46 +791,7 @@ impl Writer { } } crate::Expression::Compose { ty, ref components } => { - let inner = &context.module.types[ty].inner; - match *inner { - crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { - write!(self.out, "{}", scalar_kind_string(kind))?; - self.put_call_parameters(components.iter().cloned(), context)?; - } - crate::TypeInner::Vector { size, kind, .. } => { - write!( - self.out, - "{}::{}{}", - NAMESPACE, - scalar_kind_string(kind), - vector_size_str(size) - )?; - self.put_call_parameters(components.iter().cloned(), context)?; - } - crate::TypeInner::Matrix { columns, rows, .. } => { - let kind = crate::ScalarKind::Float; - write!( - self.out, - "{}::{}{}x{}", - NAMESPACE, - scalar_kind_string(kind), - vector_size_str(columns), - vector_size_str(rows) - )?; - self.put_call_parameters(components.iter().cloned(), context)?; - } - crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { - write!(self.out, "{} {{", &self.names[&NameKey::Type(ty)])?; - for (i, &component) in components.iter().enumerate() { - if i != 0 { - write!(self.out, ", ")?; - } - self.put_expression(component, context, true)?; - } - write!(self.out, "}}")?; - } - _ => return Err(Error::UnsupportedCompose(ty)), - } + self.put_compose(ty, components, context)?; } crate::Expression::FunctionArgument(index) => { let name_key = match context.origin { @@ -839,39 +890,7 @@ impl Writer { self.put_expression(dref, context, true)?; } - let has_levels = match *context.resolve_type(image) { - crate::TypeInner::Image { - dim: crate::ImageDimension::D1, - .. - } => false, - _ => true, - }; - match level { - crate::SampleLevel::Auto => {} - crate::SampleLevel::Zero => { - //TODO: do we support Zero on `Sampled` image classes? - } - _ if !has_levels => { - log::warn!("1D image can't be sampled with level {:?}", level); - } - crate::SampleLevel::Exact(h) => { - write!(self.out, ", {}::level(", NAMESPACE)?; - self.put_expression(h, context, true)?; - write!(self.out, ")")?; - } - crate::SampleLevel::Bias(h) => { - write!(self.out, ", {}::bias(", NAMESPACE)?; - self.put_expression(h, context, true)?; - write!(self.out, ")")?; - } - crate::SampleLevel::Gradient { x, y } => { - write!(self.out, ", {}::gradient(", NAMESPACE)?; - self.put_expression(x, context, true)?; - write!(self.out, ", ")?; - self.put_expression(y, context, true)?; - write!(self.out, ")")?; - } - } + self.put_image_sample_level(image, level, context)?; if let Some(constant) = offset { let coco = ConstantContext { @@ -2370,8 +2389,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 23040 - if stack_size < 21000 || stack_size > 25000 { + // last observed macOS value: 17664 + if stack_size < 17000 || stack_size > 18500 { panic!("`put_expression` stack size {} has changed!", stack_size); } } From 73b20ffa70c69e3af3c67049be906c5b25443014 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sat, 8 May 2021 02:04:25 +0300 Subject: [PATCH 0808/2212] Add CullDistance BuiltIn --- src/back/glsl/mod.rs | 1 + src/back/msl/mod.rs | 3 +++ src/back/msl/writer.rs | 14 ++++++++++++++ src/back/spv/writer.rs | 1 + src/front/spv/convert.rs | 1 + src/lib.rs | 1 + src/valid/interface.rs | 2 +- tests/out/quad-vert.msl | 3 ++- 8 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index f433c6bc0..8870ffb60 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2181,6 +2181,7 @@ fn glsl_built_in(built_in: BuiltIn, output: bool) -> &'static str { BuiltIn::BaseInstance => "uint(gl_BaseInstance)", BuiltIn::BaseVertex => "uint(gl_BaseVertex)", BuiltIn::ClipDistance => "gl_ClipDistance", + BuiltIn::CullDistance => "gl_CullDistance", BuiltIn::InstanceIndex => "uint(gl_InstanceID)", BuiltIn::PointSize => "gl_PointSize", BuiltIn::VertexIndex => "uint(gl_VertexID)", diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index a905a3e36..b465112c5 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -135,6 +135,8 @@ pub enum Error { FeatureNotImplemented(String), #[error("module is not valid")] Validation, + #[error("BuiltIn {0:?} is not supported")] + UnsupportedBuiltIn(crate::BuiltIn), } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -356,6 +358,7 @@ impl ResolvedBinding { Bi::LocalInvocationIndex => "thread_index_in_threadgroup", Bi::WorkGroupId => "threadgroup_position_in_grid", Bi::WorkGroupSize => "dispatch_threads_per_threadgroup", + _ => return Err(Error::UnsupportedBuiltIn(built_in)), }; write!(out, "{}", name)?; } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8510e5ca3..9994b4f69 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1165,6 +1165,12 @@ impl Writer { { continue; } + if member.binding + == Some(crate::Binding::BuiltIn(crate::BuiltIn::CullDistance)) + { + log::warn!("Ignoring CullDistance BuiltIn"); + continue; + } let comma = if is_first { "" } else { "," }; is_first = false; let name = &self.names[&NameKey::StructMember(result_ty, index as u32)]; @@ -2074,6 +2080,14 @@ impl Writer { first_time: true, }; let binding = binding.ok_or(Error::Validation)?; + // Cull Distance is not supported in Metal. + // But we can't return UnsupportedBuiltIn error to user. + // Because otherwise we can't generate msl shader from any glslang SPIR-V shaders. + // glslang generates gl_PerVertex struct with gl_CullDistance builtin inside by default. + if *binding == crate::Binding::BuiltIn(crate::BuiltIn::CullDistance) { + log::warn!("Ignoring CullDistance BuiltIn"); + continue; + } if !pipeline_options.allow_point_size && *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize) { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index df9a77ba4..13e8854c0 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1165,6 +1165,7 @@ impl Writer { Bi::BaseInstance => BuiltIn::BaseInstance, Bi::BaseVertex => BuiltIn::BaseVertex, Bi::ClipDistance => BuiltIn::ClipDistance, + Bi::CullDistance => BuiltIn::CullDistance, Bi::InstanceIndex => BuiltIn::InstanceIndex, Bi::PointSize => BuiltIn::PointSize, Bi::VertexIndex => BuiltIn::VertexIndex, diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index c0f6f3917..dc429c290 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -125,6 +125,7 @@ pub(super) fn map_builtin(word: spirv::Word) -> Result { Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, Some(Bi::BaseVertex) => crate::BuiltIn::BaseVertex, Some(Bi::ClipDistance) => crate::BuiltIn::ClipDistance, + Some(Bi::CullDistance) => crate::BuiltIn::CullDistance, Some(Bi::InstanceIndex) => crate::BuiltIn::InstanceIndex, Some(Bi::PointSize) => crate::BuiltIn::PointSize, Some(Bi::VertexIndex) => crate::BuiltIn::VertexIndex, diff --git a/src/lib.rs b/src/lib.rs index 594cfacfc..7cc5c3b81 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -150,6 +150,7 @@ pub enum BuiltIn { BaseInstance, BaseVertex, ClipDistance, + CullDistance, InstanceIndex, PointSize, VertexIndex, diff --git a/src/valid/interface.rs b/src/valid/interface.rs index aec49e450..711124508 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -112,7 +112,7 @@ impl VaryingContext<'_> { width, }, ), - Bi::ClipDistance => ( + Bi::ClipDistance | Bi::CullDistance => ( self.stage == St::Vertex && self.output, match *ty_inner { Ti::Array { base, .. } => { diff --git a/tests/out/quad-vert.msl b/tests/out/quad-vert.msl index 4c99ca960..16f2fbc83 100644 --- a/tests/out/quad-vert.msl +++ b/tests/out/quad-vert.msl @@ -15,6 +15,7 @@ struct type10 { metal::float4 gl_Position1; float gl_PointSize1; type6 gl_ClipDistance1; + type6 gl_CullDistance1; }; constant metal::float4 const_type4_ = {0.0, 0.0, 0.0, 1.0}; constant type6 const_type6_ = {0.0}; @@ -54,6 +55,6 @@ vertex main2Output main2( a_uv = a_uv1; a_pos = a_pos1; main1(v_uv, a_uv, perVertexStruct, a_pos); - const auto _tmp = type10 {v_uv, perVertexStruct.gl_Position, perVertexStruct.gl_PointSize, perVertexStruct.gl_ClipDistance}; + const auto _tmp = type10 {v_uv, perVertexStruct.gl_Position, perVertexStruct.gl_PointSize, perVertexStruct.gl_ClipDistance, perVertexStruct.gl_CullDistance}; return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1.inner[0]} }; } From e173a514a03b9761825a06b666f13d05bae7f863 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 8 May 2021 10:14:25 -0400 Subject: [PATCH 0809/2212] [spv-in] respect per-member access decorations --- src/front/spv/mod.rs | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3b9be2606..e69f8701c 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -40,7 +40,7 @@ use function::*; use crate::{ arena::{Arena, Handle}, - FastHashMap, FastHashSet, + FastHashMap, }; use num_traits::cast::FromPrimitive; @@ -403,7 +403,7 @@ pub struct Parser { handle_sampling: FastHashMap, image::SamplingFlags>, lookup_type: FastHashMap, lookup_void_type: Option, - lookup_storage_buffer_types: FastHashSet>, + lookup_storage_buffer_types: FastHashMap, crate::StorageAccess>, // Lookup for samplers and sampled images, storing flags on how they are used. lookup_constant: FastHashMap, lookup_variable: FastHashMap, @@ -440,7 +440,7 @@ impl> Parser { lookup_member: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_void_type: None, - lookup_storage_buffer_types: FastHashSet::default(), + lookup_storage_buffer_types: FastHashMap::default(), lookup_constant: FastHashMap::default(), lookup_variable: FastHashMap::default(), lookup_expression: FastHashMap::default(), @@ -2817,7 +2817,7 @@ impl> Parser { | crate::TypeInner::ValuePointer { class, .. } => class, _ if self .lookup_storage_buffer_types - .contains(&base_lookup_ty.handle) => + .contains_key(&base_lookup_ty.handle) => { crate::StorageClass::Storage } @@ -2928,6 +2928,7 @@ impl> Parser { let mut struct_alignment = crate::Alignment::new(1).unwrap(); let mut members = Vec::::with_capacity(inst.wc as usize - 2); let mut member_lookups = Vec::with_capacity(members.capacity()); + let mut storage_access = crate::StorageAccess::empty(); for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; let ty = self.lookup_type.lookup(type_id)?.handle; @@ -2936,6 +2937,15 @@ impl> Parser { .remove(&(id, i)) .unwrap_or_default(); + let mut member_access = crate::StorageAccess::all(); + if decor.flags.contains(DecorationFlags::NON_READABLE) { + member_access &= !crate::StorageAccess::LOAD; + } + if decor.flags.contains(DecorationFlags::NON_WRITABLE) { + member_access &= !crate::StorageAccess::STORE; + } + storage_access |= member_access; + member_lookups.push(LookupMember { type_id, row_major: decor.matrix_major == Some(Majority::Row), @@ -2991,7 +3001,8 @@ impl> Parser { }); if block_decor == Some(Block { buffer: true }) { - self.lookup_storage_buffer_types.insert(ty_handle); + self.lookup_storage_buffer_types + .insert(ty_handle, storage_access); } for (i, member_lookup) in member_lookups.into_iter().enumerate() { self.lookup_member @@ -3314,11 +3325,14 @@ impl> Parser { } => (original_ty, true), _ => (original_ty, false), }; - let ext_class = if self.lookup_storage_buffer_types.contains(&effective_ty) { - ExtendedClass::Global(crate::StorageClass::Storage) - } else { - map_storage_class(storage_class)? - }; + let (ext_class, type_storage_access) = + match self.lookup_storage_buffer_types.get(&effective_ty) { + Some(&access) => (ExtendedClass::Global(crate::StorageClass::Storage), access), + None => ( + map_storage_class(storage_class)?, + crate::StorageAccess::all(), + ), + }; // Fix empty name for gl_PerVertex struct generated by glslang if let crate::TypeInner::Pointer { .. } = module.types[original_ty].inner { @@ -3334,12 +3348,12 @@ impl> Parser { let (inner, var) = match ext_class { ExtendedClass::Global(class) => { let storage_access = if is_storage { - let mut access = crate::StorageAccess::all(); + let mut access = type_storage_access; if dec.flags.contains(DecorationFlags::NON_READABLE) { - access ^= crate::StorageAccess::LOAD; + access &= !crate::StorageAccess::LOAD; } if dec.flags.contains(DecorationFlags::NON_WRITABLE) { - access ^= crate::StorageAccess::STORE; + access &= !crate::StorageAccess::STORE; } access } else { From 1aa57b3f92d068a497cdcd7aba9e3b0c0f80973c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 8 May 2021 10:55:10 -0400 Subject: [PATCH 0810/2212] Support multiple output targets in the converter --- bin/naga.rs | 187 ++++++++++++++++++++++++++-------------------------- 1 file changed, 94 insertions(+), 93 deletions(-) diff --git a/bin/naga.rs b/bin/naga.rs index ea1644947..09c1f64dc 100644 --- a/bin/naga.rs +++ b/bin/naga.rs @@ -49,7 +49,7 @@ fn main() { //env_logger::init(); // uncomment during development let mut input_path = None; - let mut output_path = None; + let mut output_paths = Vec::new(); //TODO: read the parameters from RON? #[allow(unused_mut)] let mut params = Parameters::default(); @@ -87,10 +87,8 @@ fn main() { } } else if input_path.is_none() { input_path = Some(arg); - } else if output_path.is_none() { - output_path = Some(arg); } else { - log::warn!("Extra parameter: {}", arg); + output_paths.push(arg); } } @@ -194,104 +192,107 @@ fn main() { } }; - let output_path = match output_path { - Some(ref string) => string, - None => { - if info.is_some() { - println!("Validation successful"); - return; - } else { - std::process::exit(!0); + if output_paths.is_empty() { + if info.is_some() { + println!("Validation successful"); + return; + } else { + std::process::exit(!0); + } + } + + for output_path in output_paths { + match Path::new(&output_path) + .extension() + .expect("Output has no extension?") + .to_str() + .unwrap() + { + "txt" => { + use std::io::Write; + + let mut file = fs::File::create(output_path).unwrap(); + writeln!(file, "{:#?}", module).unwrap(); + if let Some(ref info) = info { + writeln!(file).unwrap(); + writeln!(file, "{:#?}", info).unwrap(); + } } - } - }; + #[cfg(feature = "msl-out")] + "metal" => { + use naga::back::msl; - match Path::new(output_path) - .extension() - .expect("Output has no extension?") - .to_str() - .unwrap() - { - "txt" => { - use std::io::Write; - let mut file = fs::File::create(output_path).unwrap(); - writeln!(file, "{:#?}", module).unwrap(); - if let Some(info) = info { - writeln!(file).unwrap(); - writeln!(file, "{:#?}", info).unwrap(); + let pipeline_options = msl::PipelineOptions::default(); + let (msl, _) = msl::write_string( + &module, + info.as_ref().unwrap(), + ¶ms.msl, + &pipeline_options, + ) + .unwrap_pretty(); + fs::write(output_path, msl).unwrap(); } - } - #[cfg(feature = "msl-out")] - "metal" => { - use naga::back::msl; - let pipeline_options = msl::PipelineOptions::default(); - let (msl, _) = msl::write_string( - &module, - info.as_ref().unwrap(), - ¶ms.msl, - &pipeline_options, - ) - .unwrap_pretty(); - fs::write(output_path, msl).unwrap(); - } - #[cfg(feature = "spv-out")] - "spv" => { - use naga::back::spv; + #[cfg(feature = "spv-out")] + "spv" => { + use naga::back::spv; - let spv = spv::write_vec(&module, info.as_ref().unwrap(), ¶ms.spv).unwrap_pretty(); - let bytes = spv - .iter() - .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { - v.extend_from_slice(&w.to_le_bytes()); - v - }); + let spv = + spv::write_vec(&module, info.as_ref().unwrap(), ¶ms.spv).unwrap_pretty(); + let bytes = spv + .iter() + .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { + v.extend_from_slice(&w.to_le_bytes()); + v + }); - fs::write(output_path, bytes.as_slice()).unwrap(); - } - #[cfg(feature = "glsl-out")] - stage @ "vert" | stage @ "frag" | stage @ "comp" => { - use naga::back::glsl; + fs::write(output_path, bytes.as_slice()).unwrap(); + } + #[cfg(feature = "glsl-out")] + stage @ "vert" | stage @ "frag" | stage @ "comp" => { + use naga::back::glsl; - params.glsl.shader_stage = match stage { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - _ => unreachable!(), - }; + params.glsl.shader_stage = match stage { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + _ => unreachable!(), + }; - let mut buffer = String::new(); - let mut writer = - glsl::Writer::new(&mut buffer, &module, info.as_ref().unwrap(), ¶ms.glsl) - .unwrap_pretty(); - writer.write().unwrap(); - fs::write(output_path, buffer).unwrap(); - } - #[cfg(feature = "dot-out")] - "dot" => { - use naga::back::dot; - let output = dot::write(&module, info.as_ref()).unwrap(); - fs::write(output_path, output).unwrap(); - } - #[cfg(feature = "hlsl-out")] - "hlsl" => { - use naga::back::hlsl; + let mut buffer = String::new(); + let mut writer = + glsl::Writer::new(&mut buffer, &module, info.as_ref().unwrap(), ¶ms.glsl) + .unwrap_pretty(); + writer.write().unwrap(); + fs::write(output_path, buffer).unwrap(); + } + #[cfg(feature = "dot-out")] + "dot" => { + use naga::back::dot; - let hlsl = hlsl::write_string(&module).unwrap_pretty(); - fs::write(output_path, hlsl).unwrap(); - } - #[cfg(feature = "wgsl-out")] - "wgsl" => { - use naga::back::wgsl; + let output = dot::write(&module, info.as_ref()).unwrap(); + fs::write(output_path, output).unwrap(); + } + #[cfg(feature = "hlsl-out")] + "hlsl" => { + use naga::back::hlsl; - let wgsl = wgsl::write_string(&module, info.as_ref().unwrap()).unwrap_pretty(); - fs::write(output_path, wgsl).unwrap(); - } - other => { - let _ = params; - panic!( - "Unknown output extension: {}, forgot to enable a feature?", - other - ); + let hlsl = hlsl::write_string(&module).unwrap_pretty(); + fs::write(output_path, hlsl).unwrap(); + } + #[cfg(feature = "wgsl-out")] + "wgsl" => { + use naga::back::wgsl; + + let wgsl = wgsl::write_string(&module, info.as_ref().unwrap()).unwrap_pretty(); + fs::write(output_path, wgsl).unwrap(); + } + other => { + let _ = params; + println!( + "Unknown output extension: {}, forgot to enable a feature?", + other + ); + } } } } From 851f504e418c59438876c83315d50a32cdfe1678 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 7 May 2021 00:03:39 -0400 Subject: [PATCH 0811/2212] [spv-in] patch the SPIR-Vs wacky CFG cases by hand --- src/front/spv/flow.rs | 16 +++++----- src/front/spv/function.rs | 2 +- src/front/spv/mod.rs | 64 ++++++++++++++++++++++++--------------- 3 files changed, 48 insertions(+), 34 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index e8c6a0a85..65f8ca4a4 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -143,10 +143,10 @@ impl FlowGraph { } Terminator::Switch { selector: _, - default, + default_id, ref targets, } => { - let default_node_index = block_to_node[&default]; + let default_node_index = block_to_node[&default_id]; self.flow.add_edge( source_node_index, @@ -479,12 +479,12 @@ impl FlowGraph { } Terminator::Switch { selector: _, - default, + default_id, ref targets, } => { - self.compute_postorder_traverse(Some(self.block_to_node[&default])); - for target in targets.iter() { - self.compute_postorder_traverse(Some(self.block_to_node[&target.1])); + self.compute_postorder_traverse(Some(self.block_to_node[&default_id])); + for &(_, target_id) in targets.iter() { + self.compute_postorder_traverse(Some(self.block_to_node[&target_id])); } } _ => {} @@ -619,7 +619,7 @@ impl FlowGraph { } Terminator::Switch { selector, - default, + default_id, ref targets, } => { let merge_node_index = @@ -660,7 +660,7 @@ impl FlowGraph { selector, cases, default: self.convert_to_naga_traverse( - self.block_to_node[&default], + self.block_to_node[&default_id], stop_nodes_cases, )?, }); diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 952b693e0..ab72543d6 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -38,7 +38,7 @@ pub enum Terminator { /// selector: Handle, /// Default block of the switch case. - default: BlockId, + default_id: BlockId, /// Tuples of (literal, target block) targets: Vec<(i32, BlockId)>, }, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e69f8701c..dbe39bc0c 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -45,7 +45,7 @@ use crate::{ use num_traits::cast::FromPrimitive; use petgraph::graphmap::GraphMap; -use std::{convert::TryInto, num::NonZeroU32, path::PathBuf}; +use std::{convert::TryInto, mem, num::NonZeroU32, path::PathBuf}; pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Shader, @@ -1973,7 +1973,7 @@ impl> Parser { Op::Switch => { inst.expect_at_least(3)?; let selector = self.next()?; - let default = self.next()?; + let default_id = self.next()?; let selector_lexp = &self.lookup_expression[&selector]; let selector_lty = self.lookup_type.lookup(selector_lexp.type_id)?; @@ -2005,7 +2005,7 @@ impl> Parser { break Terminator::Switch { selector, - default, + default_id, targets, }; } @@ -2205,41 +2205,55 @@ impl> Parser { } } - fn patch_function_call_statements( - &self, - statements: &mut [crate::Statement], - ) -> Result<(), Error> { + /// Walk the statement tree and patch it in the following cases: + /// 1. Function call targets are replaced by `deferred_function_calls` map + /// 2. Lift the contents of "If" that only breaks on rejection, onto the parent after it. + /// 3. Lift the contents of "Switch" that only has a default, onto the parent after it. + fn patch_statements(&self, statements: &mut crate::Block) -> Result<(), Error> { use crate::Statement as S; - for statement in statements.iter_mut() { - match *statement { + let mut i = 0usize; + while i < statements.len() { + match statements[i] { S::Emit(_) => {} S::Block(ref mut block) => { - self.patch_function_call_statements(block)?; + self.patch_statements(block)?; } S::If { condition: _, ref mut accept, ref mut reject, } => { - self.patch_function_call_statements(accept)?; - self.patch_function_call_statements(reject)?; + if let [S::Break] = reject[..] { + // uplift "accept" into the parent + let extracted = mem::replace(accept, Vec::new()); + statements.splice(i + 1..i + 1, extracted.into_iter()); + } else { + self.patch_statements(reject)?; + self.patch_statements(accept)?; + } } S::Switch { selector: _, ref mut cases, ref mut default, } => { - for case in cases.iter_mut() { - self.patch_function_call_statements(&mut case.body)?; + if cases.is_empty() { + // uplift "default" into the parent + let extracted = mem::replace(default, Vec::new()); + statements.splice(i + 1..i + 1, extracted.into_iter()); + } else { + for case in cases.iter_mut() { + self.patch_statements(&mut case.body)?; + } + self.patch_statements(default)?; } - self.patch_function_call_statements(default)?; } S::Loop { ref mut body, ref mut continuing, } => { - self.patch_function_call_statements(body)?; - self.patch_function_call_statements(continuing)?; + self.patch_statements(body)?; + self.patch_statements(continuing)?; } S::Break | S::Continue @@ -2255,18 +2269,19 @@ impl> Parser { *function = *self.lookup_function.lookup(fun_id)?; } } + i += 1; } Ok(()) } - fn patch_function_calls(&self, fun: &mut crate::Function) -> Result<(), Error> { + fn patch_function(&self, fun: &mut crate::Function) -> Result<(), Error> { for (_, expr) in fun.expressions.iter_mut() { if let crate::Expression::Call(ref mut function) = *expr { let fun_id = self.deferred_function_calls[function.index()]; *function = *self.lookup_function.lookup(fun_id)?; } } - self.patch_function_call_statements(&mut fun.body)?; + self.patch_statements(&mut fun.body)?; Ok(()) } @@ -2357,11 +2372,10 @@ impl> Parser { log::info!("Patching..."); { - use std::mem::take; let mut nodes = petgraph::algo::toposort(&self.function_call_graph, None) .map_err(|cycle| Error::FunctionCallCycle(cycle.node_id()))?; nodes.reverse(); // we need dominated first - let mut functions = take(&mut module.functions).into_inner(); + let mut functions = mem::take(&mut module.functions).into_inner(); for fun_id in nodes { if fun_id > !(functions.len() as u32) { // skip all the fake IDs registered for the entry points @@ -2369,17 +2383,17 @@ impl> Parser { } let handle = self.lookup_function.get_mut(&fun_id).unwrap(); // take out the function from the old array - let fun = take(&mut functions[handle.index()]); + let fun = mem::take(&mut functions[handle.index()]); // add it to the newly formed arena, and adjust the lookup *handle = module.functions.append(fun); } } - // patch all the function calls + // patch all the functions for (_, fun) in module.functions.iter_mut() { - self.patch_function_calls(fun)?; + self.patch_function(fun)?; } for ep in module.entry_points.iter_mut() { - self.patch_function_calls(&mut ep.function)?; + self.patch_function(&mut ep.function)?; } // Check all the images and samplers to have consistent comparison property. From 53fe7a329f029ee09300e3a979e08a01b2e902be Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 6 May 2021 01:44:32 +0300 Subject: [PATCH 0812/2212] [glsl-out] Handle uninitialized global variables --- src/back/glsl/features.rs | 21 ++++++--- src/back/glsl/mod.rs | 75 ++++++++++++++++++++++++++++++--- tests/out/quad-vert.Vertex.glsl | 48 +++++++++++++++++++++ tests/out/quad.Vertex.glsl | 5 ++- tests/out/skybox.Vertex.glsl | 5 ++- tests/snapshots.rs | 2 +- 6 files changed, 139 insertions(+), 17 deletions(-) create mode 100644 tests/out/quad-vert.Vertex.glsl diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 9b46d569f..b78352fde 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -29,6 +29,7 @@ bitflags::bitflags! { const NOPERSPECTIVE_QUALIFIER = 1 << 11; const SAMPLE_QUALIFIER = 1 << 12; const CLIP_DISTANCE = 1 << 13; + const CULL_DISTANCE = 1 << 14; } } @@ -93,6 +94,7 @@ impl FeaturesManager { check_feature!(SAMPLE_QUALIFIER, 400, 320); // gl_ClipDistance is supported by core versions > 1.3 and aren't supported by an es versions without extensions check_feature!(CLIP_DISTANCE, 130, 300); + check_feature!(CULL_DISTANCE, 450, 300); // Return an error if there are missing features if missing.is_empty() { @@ -173,9 +175,12 @@ impl FeaturesManager { } } - if self.0.contains(Features::CLIP_DISTANCE) && version.is_es() { + if (self.0.contains(Features::CLIP_DISTANCE) || self.0.contains(Features::CULL_DISTANCE)) + && version.is_es() + { + // TODO: handle gl_ClipDistance and gl_CullDistance usage in better way // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_clip_cull_distance.txt - writeln!(out, "#extension GL_EXT_clip_cull_distance : require")?; + // writeln!(out, "#extension GL_EXT_clip_cull_distance : require")?; } Ok(()) @@ -298,11 +303,15 @@ impl<'a, W> Writer<'a, W> { _ => { if let Some(binding) = binding { match *binding { - Binding::BuiltIn(builtin) => { - if builtin == crate::BuiltIn::ClipDistance { - self.features.request(Features::CLIP_DISTANCE); + Binding::BuiltIn(builtin) => match builtin { + crate::BuiltIn::ClipDistance => { + self.features.request(Features::CLIP_DISTANCE) } - } + crate::BuiltIn::CullDistance => { + self.features.request(Features::CULL_DISTANCE) + } + _ => {} + }, Binding::Location { location: _, interpolation, diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 8870ffb60..d9e9fde9b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -756,7 +756,14 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important - writeln!(self.out, " {};", self.get_global_name(handle, global))?; + let global_name = self.get_global_name(handle, global); + let global_str = + if let Some(default_value) = zero_init_value_str(&self.module.types[global.ty].inner) { + format!("{} = {}", global_name, default_value) + } else { + global_name + }; + writeln!(self.out, " {};", global_str)?; writeln!(self.out)?; Ok(()) @@ -1290,7 +1297,7 @@ impl<'a, W: Write> Writer<'a, W> { } // Write `break;` if the block isn't fallthrough - if case.fall_through { + if !case.fall_through { writeln!(self.out, "{}break;", INDENT.repeat(indent + 2))?; } } @@ -1358,17 +1365,50 @@ impl<'a, W: Write> Writer<'a, W> { let value = value.unwrap(); match self.module.types[result.ty].inner { crate::TypeInner::Struct { ref members, .. } => { + let (mut is_temp_struct_used, mut return_struct) = (false, ""); + if let Expression::Compose { .. } = ctx.expressions[value] { + is_temp_struct_used = true; + return_struct = "_tmp_return"; + write!( + self.out, + "{} {} = ", + &self.names[&NameKey::Type(result.ty)], + return_struct + )?; + self.write_expr(value, ctx)?; + writeln!(self.out, ";")?; + write!(self.out, "{}", INDENT.repeat(indent))?; + } for (index, member) in members.iter().enumerate() { + // TODO: handle builtin in better way + if let Some(Binding::BuiltIn(builtin)) = member.binding { + match builtin { + crate::BuiltIn::ClipDistance + | crate::BuiltIn::CullDistance + | crate::BuiltIn::PointSize => { + if self.options.version.is_es() { + continue; + } + } + _ => {} + } + } + let varying_name = VaryingName { binding: member.binding.as_ref().unwrap(), stage: ep.stage, output: true, }; + let field_name = self.names + [&NameKey::StructMember(result.ty, index as u32)] + .clone(); write!(self.out, "{} = ", varying_name)?; - self.write_expr(value, ctx)?; - let field_name = &self.names - [&NameKey::StructMember(result.ty, index as u32)]; - writeln!(self.out, ".{};", field_name)?; + + if !is_temp_struct_used { + self.write_expr(value, ctx)?; + } + + writeln!(self.out, "{}.{};", return_struct, &field_name)?; write!(self.out, "{}", INDENT.repeat(indent))?; } } @@ -2298,3 +2338,26 @@ fn glsl_storage_access(storage_access: StorageAccess) -> Option<&'static str> { None } } + +/// Helper function that return string with default zero initialization for supported types +fn zero_init_value_str(inner: &TypeInner) -> Option { + match *inner { + TypeInner::Scalar { kind, .. } => match kind { + ScalarKind::Bool => Some(String::from("false")), + _ => Some(String::from("0")), + }, + TypeInner::Vector { size, kind, width } => { + if let Ok(scalar_string) = glsl_scalar(kind, width) { + let vec_type = format!("{}vec{}", scalar_string.prefix, size as u8); + match size { + crate::VectorSize::Bi => Some(format!("{}(0, 0)", vec_type)), + crate::VectorSize::Tri => Some(format!("{}(0, 0, 0)", vec_type)), + crate::VectorSize::Quad => Some(format!("{}(0, 0, 0, 0)", vec_type)), + } + } else { + None + } + } + _ => None, + } +} diff --git a/tests/out/quad-vert.Vertex.glsl b/tests/out/quad-vert.Vertex.glsl new file mode 100644 index 000000000..3f3bb13ad --- /dev/null +++ b/tests/out/quad-vert.Vertex.glsl @@ -0,0 +1,48 @@ +#version 310 es + +precision highp float; + +struct type10 { + vec2 member; + vec4 gen_gl_Position1; + float gen_gl_PointSize1; + float gen_gl_ClipDistance1[1]; + float gen_gl_CullDistance1[1]; +}; + +vec2 v_uv = vec2(0, 0); + +vec2 a_uv = vec2(0, 0); + +struct gen_gl_PerVertex_block_0 { + vec4 gen_gl_Position; + float gen_gl_PointSize; + float gen_gl_ClipDistance[1]; + float gen_gl_CullDistance[1]; +} perVertexStruct; + +vec2 a_pos = vec2(0, 0); + +layout(location = 1) in vec2 _p2vs_location1; +layout(location = 0) in vec2 _p2vs_location0; +smooth layout(location = 0) out vec2 _vs2fs_location0; + +void main1() { + v_uv = a_uv; + vec2 _expr13 = a_pos; + perVertexStruct.gen_gl_Position = vec4(_expr13[0], _expr13[1], 0.0, 1.0); + return; +} + +void main() { + vec2 a_uv1 = _p2vs_location1; + vec2 a_pos1 = _p2vs_location0; + a_uv = a_uv1; + a_pos = a_pos1; + main1(); + type10 _tmp_return = type10(v_uv, perVertexStruct.gen_gl_Position, perVertexStruct.gen_gl_PointSize, perVertexStruct.gen_gl_ClipDistance, perVertexStruct.gen_gl_CullDistance); + _vs2fs_location0 = _tmp_return.member; + gl_Position = _tmp_return.gen_gl_Position1; + return; +} + diff --git a/tests/out/quad.Vertex.glsl b/tests/out/quad.Vertex.glsl index 751d8c592..95ce41427 100644 --- a/tests/out/quad.Vertex.glsl +++ b/tests/out/quad.Vertex.glsl @@ -14,8 +14,9 @@ smooth layout(location = 0) out vec2 _vs2fs_location0; void main() { vec2 pos = _p2vs_location0; vec2 uv1 = _p2vs_location1; - _vs2fs_location0 = VertexOutput(uv1, vec4((1.2 * pos), 0.0, 1.0)).uv; - gl_Position = VertexOutput(uv1, vec4((1.2 * pos), 0.0, 1.0)).position; + VertexOutput _tmp_return = VertexOutput(uv1, vec4((1.2 * pos), 0.0, 1.0)); + _vs2fs_location0 = _tmp_return.uv; + gl_Position = _tmp_return.position; return; } diff --git a/tests/out/skybox.Vertex.glsl b/tests/out/skybox.Vertex.glsl index e543e836b..870a4ee26 100644 --- a/tests/out/skybox.Vertex.glsl +++ b/tests/out/skybox.Vertex.glsl @@ -21,8 +21,9 @@ void main() { tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); vec4 _expr24 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - gl_Position = VertexOutput(_expr24, (transpose(mat3x3(_group_0_binding_0.view[0].xyz, _group_0_binding_0.view[1].xyz, _group_0_binding_0.view[2].xyz)) * (_group_0_binding_0.proj_inv * _expr24).xyz)).position; - _vs2fs_location0 = VertexOutput(_expr24, (transpose(mat3x3(_group_0_binding_0.view[0].xyz, _group_0_binding_0.view[1].xyz, _group_0_binding_0.view[2].xyz)) * (_group_0_binding_0.proj_inv * _expr24).xyz)).uv; + VertexOutput _tmp_return = VertexOutput(_expr24, (transpose(mat3x3(_group_0_binding_0.view[0].xyz, _group_0_binding_0.view[1].xyz, _group_0_binding_0.view[2].xyz)) * (_group_0_binding_0.proj_inv * _expr24).xyz)); + gl_Position = _tmp_return.position; + _vs2fs_location0 = _tmp_return.uv; return; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 90a835db7..e0aabd8c2 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -296,7 +296,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { #[cfg(feature = "spv-in")] #[test] fn convert_spv_quad_vert() { - convert_spv("quad-vert", false, Targets::METAL); + convert_spv("quad-vert", false, Targets::METAL | Targets::GLSL); } #[cfg(feature = "spv-in")] From c25c06409c29bf35764be551ebd8bccae0ada383 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 5 May 2021 20:11:14 -0400 Subject: [PATCH 0813/2212] [spv-in] fix casting length expectations --- src/front/spv/mod.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index dbe39bc0c..2b2979ce1 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1673,6 +1673,7 @@ impl> Parser { | Op::ConvertUToF | Op::ConvertFToU | Op::ConvertFToS + | Op::FConvert | Op::UConvert | Op::SConvert => { inst.expect_at_least(4)?; @@ -3143,7 +3144,7 @@ impl> Parser { module: &mut crate::Module, ) -> Result<(), Error> { self.switch(ModuleState::Type, inst.op)?; - inst.expect_at_least(3)?; + inst.expect_at_least(4)?; let type_id = self.next()?; let id = self.next()?; let type_lookup = self.lookup_type.lookup(type_id)?; @@ -3156,7 +3157,7 @@ impl> Parser { } => { let low = self.next()?; let high = if width > 4 { - inst.expect(4)?; + inst.expect(5)?; self.next()? } else { 0 @@ -3172,7 +3173,7 @@ impl> Parser { } => { let low = self.next()?; let high = if width > 4 { - inst.expect(4)?; + inst.expect(5)?; self.next()? } else { 0 @@ -3192,11 +3193,11 @@ impl> Parser { let extended = match width { 4 => f64::from(f32::from_bits(low)), 8 => { - inst.expect(4)?; + inst.expect(5)?; let high = self.next()?; f64::from_bits((u64::from(high) << 32) | u64::from(low)) } - _ => return Err(Error::InvalidTypeWidth(u32::from(width))), + _ => return Err(Error::InvalidTypeWidth(width as u32)), }; crate::ConstantInner::Scalar { width, From 59d1dcab5b1f40a4618dd8ac8efb94e242871d08 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 5 May 2021 23:10:23 -0400 Subject: [PATCH 0814/2212] Support width changes in As expression --- src/back/dot/mod.rs | 7 ++-- src/back/glsl/mod.rs | 68 +++++++++++++++++-------------------- src/back/msl/mod.rs | 2 ++ src/back/msl/writer.rs | 19 +++++++---- src/back/spv/writer.rs | 42 ++++++++++++++++++----- src/front/glsl/constants.rs | 20 ++++++----- src/front/glsl/functions.rs | 59 ++++++++++++++------------------ src/front/spv/function.rs | 2 +- src/front/spv/image.rs | 2 +- src/front/spv/mod.rs | 24 ++++++++----- src/front/wgsl/mod.rs | 10 +++--- src/lib.rs | 5 +-- src/proc/typifier.rs | 13 +++++-- src/valid/expression.rs | 10 ++++-- tests/out/shadow.ron | 6 ++-- 15 files changed, 169 insertions(+), 120 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 5d529b2a2..487a5f946 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -326,9 +326,12 @@ fn write_fun( expr, convert, } => { - let fun = if convert { "Convert" } else { "Cast" }; edges.insert("", expr); - (Cow::Owned(format!("{}<{:?}>", fun, kind)), 3) + let string = match convert { + Some(width) => format!("Convert<{:?},{}>", kind, width), + None => format!("Bitcast<{:?}>", kind), + }; + (Cow::Owned(string), 3) } E::Call(_function) => (Cow::Borrowed("Call"), 4), E::ArrayLength(expr) => { diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index d9e9fde9b..0d75c8471 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2024,45 +2024,39 @@ impl<'a, W: Write> Writer<'a, W> { convert, } => { let inner = ctx.info[expr].ty.inner_with(&self.module.types); - if convert { - // this is similar to `write_type`, but with the target kind - match *inner { - TypeInner::Scalar { kind: _, width } => { - write!(self.out, "{}", glsl_scalar(target_kind, width)?.full)? - } - TypeInner::Vector { - size, - kind: _, - width, - } => write!( - self.out, - "{}vec{}", - glsl_scalar(target_kind, width)?.prefix, - size as u8 - )?, - ref other => unreachable!("unexpected cast of {:?}", other), - } - } else { - let source_kind = inner.scalar_kind().unwrap(); - write!( - self.out, - "{}", - match (source_kind, target_kind) { - (ScalarKind::Float, ScalarKind::Sint) => "floatBitsToInt", - (ScalarKind::Float, ScalarKind::Uint) => "floatBitsToUInt", - (ScalarKind::Sint, ScalarKind::Float) => "intBitsToFloat", - (ScalarKind::Uint, ScalarKind::Float) => "uintBitsToFloat", - // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion - (ScalarKind::Uint, ScalarKind::Sint) => "int", - (ScalarKind::Sint, ScalarKind::Uint) => "uint", - _ => { - return Err(Error::Custom(format!( - "Cannot bitcast {:?} to {:?}", - source_kind, target_kind - ))); + match convert { + Some(width) => { + // this is similar to `write_type`, but with the target kind + let scalar = glsl_scalar(target_kind, width)?; + match *inner { + TypeInner::Vector { size, .. } => { + write!(self.out, "{}vec{}", scalar.prefix, size as u8)? } + _ => write!(self.out, "{}", scalar.full)?, } - )?; + } + None => { + let source_kind = inner.scalar_kind().unwrap(); + write!( + self.out, + "{}", + match (source_kind, target_kind) { + (ScalarKind::Float, ScalarKind::Sint) => "floatBitsToInt", + (ScalarKind::Float, ScalarKind::Uint) => "floatBitsToUInt", + (ScalarKind::Sint, ScalarKind::Float) => "intBitsToFloat", + (ScalarKind::Uint, ScalarKind::Float) => "uintBitsToFloat", + // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion + (ScalarKind::Uint, ScalarKind::Sint) => "int", + (ScalarKind::Sint, ScalarKind::Uint) => "uint", + _ => { + return Err(Error::Custom(format!( + "Cannot bitcast {:?} to {:?}", + source_kind, target_kind + ))); + } + } + )?; + } } write!(self.out, "(")?; diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index b465112c5..54cfd91ab 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -137,6 +137,8 @@ pub enum Error { Validation, #[error("BuiltIn {0:?} is not supported")] UnsupportedBuiltIn(crate::BuiltIn), + #[error("capability {0:?} is not supported")] + CapabilityNotSupported(crate::valid::Capabilities), } #[derive(Clone, Debug, PartialEq, thiserror::Error)] diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 9994b4f69..33317004c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -6,7 +6,7 @@ use crate::{ arena::{Arena, Handle}, back::vector_size_str, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, - valid::{FunctionInfo, GlobalUse, ModuleInfo}, + valid::{Capabilities, FunctionInfo, GlobalUse, ModuleInfo}, FastHashMap, }; use bit_set::BitSet; @@ -1121,12 +1121,19 @@ impl Writer { convert, } => { let scalar = scalar_kind_string(kind); - let size = match *context.resolve_type(expr) { - crate::TypeInner::Scalar { .. } => "", - crate::TypeInner::Vector { size, .. } => vector_size_str(size), + let (size, width) = match *context.resolve_type(expr) { + crate::TypeInner::Scalar { width, .. } => ("", width), + crate::TypeInner::Vector { size, width, .. } => (vector_size_str(size), width), _ => return Err(Error::Validation), }; - let op = if convert { "static_cast" } else { "as_type" }; + let op = match convert { + Some(w) if w == width => "static_cast", + Some(8) if kind == crate::ScalarKind::Float => { + return Err(Error::CapabilityNotSupported(Capabilities::FLOAT64)) + } + Some(_) => return Err(Error::Validation), + None => "as_type", + }; write!(self.out, "{}<{}{}>(", op, scalar, size)?; self.put_expression(expr, context, true)?; write!(self.out, ")")?; @@ -2404,7 +2411,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 17664 - if stack_size < 17000 || stack_size > 18500 { + if stack_size < 17000 || stack_size > 19000 { panic!("`put_expression` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 13e8854c0..894466658 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -698,17 +698,40 @@ impl Writer { )) } - fn make_scalar(&self, id: Word, kind: crate::ScalarKind, width: crate::Bytes) -> Instruction { + fn make_scalar( + &mut self, + id: Word, + kind: crate::ScalarKind, + width: crate::Bytes, + ) -> Instruction { + use crate::ScalarKind as Sk; + let bits = (width * BITS_PER_BYTE) as u32; match kind { - crate::ScalarKind::Sint => { - Instruction::type_int(id, bits, super::instructions::Signedness::Signed) + Sk::Sint | Sk::Uint => { + let signedness = if kind == Sk::Sint { + super::instructions::Signedness::Signed + } else { + super::instructions::Signedness::Unsigned + }; + let cap = match bits { + 8 => Some(spirv::Capability::Int8), + 16 => Some(spirv::Capability::Int16), + 64 => Some(spirv::Capability::Int64), + _ => None, + }; + if let Some(cap) = cap { + self.capabilities.insert(cap); + } + Instruction::type_int(id, bits, signedness) } - crate::ScalarKind::Uint => { - Instruction::type_int(id, bits, super::instructions::Signedness::Unsigned) + crate::ScalarKind::Float => { + if bits == 64 { + self.capabilities.insert(spirv::Capability::Float64); + } + Instruction::type_float(id, bits) } - crate::ScalarKind::Float => Instruction::type_float(id, bits), - crate::ScalarKind::Bool => Instruction::type_bool(id), + Sk::Bool => Instruction::type_bool(id), } } @@ -1885,11 +1908,14 @@ impl Writer { .unwrap(); let op = match (expr_kind, kind) { - _ if !convert => spirv::Op::Bitcast, + _ if convert.is_none() => spirv::Op::Bitcast, (crate::ScalarKind::Float, crate::ScalarKind::Uint) => spirv::Op::ConvertFToU, (crate::ScalarKind::Float, crate::ScalarKind::Sint) => spirv::Op::ConvertFToS, + (crate::ScalarKind::Float, crate::ScalarKind::Float) => spirv::Op::FConvert, (crate::ScalarKind::Sint, crate::ScalarKind::Float) => spirv::Op::ConvertSToF, + (crate::ScalarKind::Sint, crate::ScalarKind::Sint) => spirv::Op::SConvert, (crate::ScalarKind::Uint, crate::ScalarKind::Float) => spirv::Op::ConvertUToF, + (crate::ScalarKind::Uint, crate::ScalarKind::Uint) => spirv::Op::UConvert, // We assume it's either an identity cast, or int-uint. _ => spirv::Op::Bitcast, }; diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 848fa40c1..1df4a9576 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -160,10 +160,9 @@ impl<'a> ConstantSolver<'a> { } => { let expr_constant = self.solve(expr)?; - if convert { - self.cast(expr_constant, kind) - } else { - Err(ConstantSolvingError::Bitcast) + match convert { + Some(width) => self.cast(expr_constant, kind, width), + None => Err(ConstantSolvingError::Bitcast), } } Expression::ArrayLength(expr) => { @@ -239,6 +238,7 @@ impl<'a> ConstantSolver<'a> { &mut self, constant: Handle, kind: ScalarKind, + target_width: crate::Bytes, ) -> Result, ConstantSolvingError> { fn inner_cast(value: ScalarValue) -> A { match value { @@ -253,7 +253,11 @@ impl<'a> ConstantSolver<'a> { let mut inner = self.constants[constant].inner.clone(); match inner { - ConstantInner::Scalar { ref mut value, .. } => { + ConstantInner::Scalar { + ref mut value, + ref mut width, + } => { + *width = target_width; *value = match kind { ScalarKind::Sint => ScalarValue::Sint(inner_cast(*value)), ScalarKind::Uint => ScalarValue::Uint(inner_cast(*value)), @@ -271,7 +275,7 @@ impl<'a> ConstantSolver<'a> { } for component in components { - *component = self.cast(*component, kind)?; + *component = self.cast(*component, kind, target_width)?; } } } @@ -561,7 +565,7 @@ mod tests { let root = expressions.append(Expression::As { expr, kind: ScalarKind::Bool, - convert: true, + convert: Some(crate::BOOL_WIDTH), }); let mut solver = ConstantSolver { @@ -575,7 +579,7 @@ mod tests { assert_eq!( constants[res].inner, ConstantInner::Scalar { - width: 4, + width: crate::BOOL_WIDTH, value: ScalarValue::Bool(true), }, ); diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 2009f127d..98033dc9b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,7 +1,7 @@ use super::super::Typifier; use crate::{ proc::ensure_block_returns, BinaryOperator, Block, EntryPoint, Expression, Function, - MathFunction, RelationalFunction, SampleLevel, Type, TypeInner, + MathFunction, RelationalFunction, SampleLevel, ScalarKind, TypeInner, }; use super::{ast::*, error::ErrorKind}; @@ -15,46 +15,39 @@ impl Program<'_> { TypeInner::Vector { .. } => true, _ => false, }; - let inner = &self.module.types[ty].inner; - let kind = inner.scalar_kind().ok_or_else(|| { - ErrorKind::SemanticError("Can only cast to scalar or vector".into()) - })?; - let val = self.context.expressions.append(Expression::As { - kind, - expr: fc.args[0].expression, - convert: true, - }); - match *inner { + match self.module.types[ty].inner { TypeInner::Vector { size, .. } if !is_vec => { - let components = std::iter::repeat(val).take(size as usize).collect(); - - self.context - .expressions - .append(Expression::Compose { ty, components }) + self.context.expressions.append(Expression::Splat { + size, + value: fc.args[0].expression, + }) + } + TypeInner::Scalar { kind, width } + | TypeInner::Vector { kind, width, .. } => { + self.context.expressions.append(Expression::As { + kind, + expr: fc.args[0].expression, + convert: Some(width), + }) } TypeInner::Matrix { columns, rows, width, } => { - let column = if is_vec { - val - } else { - let vec_ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: rows, - kind, - width, - }, - }); - let rows = std::iter::repeat(val).take(rows as usize).collect(); + let value = self.context.expressions.append(Expression::As { + kind: ScalarKind::Float, + expr: fc.args[0].expression, + convert: Some(width), + }); - self.context.expressions.append(Expression::Compose { - ty: vec_ty, - components: rows, - }) + let column = if is_vec { + value + } else { + self.context + .expressions + .append(Expression::Splat { size: rows, value }) }; let columns = @@ -65,7 +58,7 @@ impl Program<'_> { components: columns, }) } - _ => val, + _ => return Err(ErrorKind::SemanticError("Bad cast".into())), } } else { self.context.expressions.append(Expression::Compose { diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index ab72543d6..449146e48 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -216,7 +216,7 @@ impl> super::Parser { let handle = function.expressions.append(crate::Expression::As { expr: arg_expr, kind: crate::ScalarKind::Sint, - convert: true, + convert: Some(4), }); function.body.push(crate::Statement::Emit( function.expressions.range_from(old_len), diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index ef8763811..1fa9e938f 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -104,7 +104,7 @@ fn extract_image_coordinates( let array_index = expressions.append(crate::Expression::As { kind: crate::ScalarKind::Sint, expr: array_index_f32, - convert: true, + convert: Some(4), }); (extracted, Some(array_index)) } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 2b2979ce1..7b62bce56 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -653,7 +653,7 @@ impl> Parser { expressions.append(crate::Expression::As { expr: p1_lexp.handle, kind, - convert: true, + convert: None, }) }, right: if p2_lexp.type_id == result_type_id { @@ -662,7 +662,7 @@ impl> Parser { expressions.append(crate::Expression::As { expr: p2_lexp.handle, kind, - convert: true, + convert: None, }) }, }; @@ -693,7 +693,7 @@ impl> Parser { let p2_handle = expressions.append(crate::Expression::As { expr: p2_lexp.handle, kind: crate::ScalarKind::Uint, - convert: false, + convert: None, }); let expr = crate::Expression::Binary { @@ -1683,15 +1683,21 @@ impl> Parser { let value_lexp = self.lookup_expression.lookup(value_id)?; let ty_lookup = self.lookup_type.lookup(result_type_id)?; - let kind = type_arena[ty_lookup.handle] - .inner - .scalar_kind() - .ok_or(Error::InvalidAsType(ty_lookup.handle))?; + let (kind, width) = match type_arena[ty_lookup.handle].inner { + crate::TypeInner::Scalar { kind, width } + | crate::TypeInner::Vector { kind, width, .. } => (kind, width), + crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), + _ => return Err(Error::InvalidAsType(ty_lookup.handle)), + }; let expr = crate::Expression::As { expr: value_lexp.handle, kind, - convert: inst.op != Op::Bitcast, + convert: if inst.op == Op::Bitcast { + None + } else { + Some(width) + }, }; self.lookup_expression.insert( result_id, @@ -1987,7 +1993,7 @@ impl> Parser { expressions.append(crate::Expression::As { kind: crate::ScalarKind::Sint, expr: selector_lexp.handle, - convert: false, + convert: None, }) } crate::TypeInner::Scalar { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index a2241401e..a9f4f999b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1165,24 +1165,24 @@ impl Parser { value: last_component, }, ( - &crate::TypeInner::Scalar { kind, .. }, + &crate::TypeInner::Scalar { kind, width, .. }, &crate::TypeInner::Scalar { .. }, ) | ( - &crate::TypeInner::Vector { kind, .. }, + &crate::TypeInner::Vector { kind, width, .. }, &crate::TypeInner::Vector { .. }, ) => crate::Expression::As { expr: last_component, kind, - convert: true, + convert: Some(width), }, ( - &crate::TypeInner::Matrix { .. }, + &crate::TypeInner::Matrix { width, .. }, &crate::TypeInner::Matrix { .. }, ) => crate::Expression::As { expr: last_component, kind: crate::ScalarKind::Float, - convert: true, + convert: Some(width), }, _ => { return Err(Error::BadTypeCast(word)); diff --git a/src/lib.rs b/src/lib.rs index 7cc5c3b81..058a5a9e8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -821,8 +821,9 @@ pub enum Expression { expr: Handle, /// Target scalar kind. kind: ScalarKind, - /// True = conversion needs to take place; False = bitcast. - convert: bool, + /// If provided, converts to the specified byte width. + /// Otherwise, bitcast. + convert: Option, }, /// Result of calling another function. Call(Handle), diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index f402ab2db..f39e65f1b 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -627,14 +627,21 @@ impl<'a> ResolveContext<'a> { crate::Expression::As { expr, kind, - convert: _, + convert, } => match *past(expr).inner_with(types) { - Ti::Scalar { kind: _, width } => TypeResolution::Value(Ti::Scalar { kind, width }), + Ti::Scalar { kind: _, width } => TypeResolution::Value(Ti::Scalar { + kind, + width: convert.unwrap_or(width), + }), Ti::Vector { kind: _, size, width, - } => TypeResolution::Value(Ti::Vector { kind, size, width }), + } => TypeResolution::Value(Ti::Vector { + kind, + size, + width: convert.unwrap_or(width), + }), ref other => { return Err(ResolveError::IncompatibleOperands(format!( "{:?} as {:?}", diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 1089b057e..c87dedcc1 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1103,8 +1103,14 @@ impl super::Validator { .resolve(expr)? .scalar_kind() .ok_or(ExpressionError::InvalidCastArgument)?; - if !convert && prev_kind == Sk::Bool || kind == Sk::Bool { - return Err(ExpressionError::InvalidCastArgument); + match convert { + Some(width) if !self.check_width(kind, width) => { + return Err(ExpressionError::InvalidCastArgument) + } + None if prev_kind == Sk::Bool || kind == Sk::Bool => { + return Err(ExpressionError::InvalidCastArgument) + } + _ => {} } ShaderStages::all() } diff --git a/tests/out/shadow.ron b/tests/out/shadow.ron index 91516dd79..6d55e1bd7 100644 --- a/tests/out/shadow.ron +++ b/tests/out/shadow.ron @@ -989,12 +989,12 @@ As( expr: 47, kind: Sint, - convert: false, + convert: None, ), As( expr: 63, kind: Float, - convert: true, + convert: Some(4), ), Compose( ty: 2, @@ -1044,7 +1044,7 @@ As( expr: 73, kind: Sint, - convert: true, + convert: Some(4), ), ImageSample( image: 4, From 350ceb383d4c85e5ae05e5f9bd2b2881917dac2d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 6 May 2021 00:04:43 -0400 Subject: [PATCH 0815/2212] WGSL support for f64, snapshot test for it --- src/back/spv/mod.rs | 2 + src/front/wgsl/conv.rs | 10 +++- src/front/wgsl/mod.rs | 19 ++------ src/valid/interface.rs | 22 ++++++--- src/valid/mod.rs | 7 ++- tests/in/boids.param.ron | 1 - tests/in/collatz.param.ron | 3 -- tests/in/control-flow.param.ron | 3 -- tests/in/empty.param.ron | 3 -- tests/in/extra.param.ron | 5 ++ tests/in/extra.wgsl | 11 +++++ tests/in/image.param.ron | 2 - tests/in/interpolate.param.ron | 1 - tests/in/operators.param.ron | 3 -- tests/in/quad-glsl.param.ron | 1 - tests/in/quad.param.ron | 1 - tests/in/shadow.param.ron | 2 - tests/in/texture-array.param.ron | 8 ---- tests/in/texture-array.wgsl | 18 -------- tests/out/extra.msl | 21 +++++++++ tests/out/extra.spvasm | 37 +++++++++++++++ tests/out/texture-array.msl | 29 ------------ tests/out/texture-array.spvasm | 78 -------------------------------- tests/snapshots.rs | 21 ++++++--- 24 files changed, 123 insertions(+), 185 deletions(-) create mode 100644 tests/in/extra.param.ron create mode 100644 tests/in/extra.wgsl delete mode 100644 tests/in/texture-array.param.ron delete mode 100644 tests/in/texture-array.wgsl create mode 100644 tests/out/extra.msl create mode 100644 tests/out/extra.spvasm delete mode 100644 tests/out/texture-array.msl delete mode 100644 tests/out/texture-array.spvasm diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 967925142..e571c3ba1 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -58,6 +58,8 @@ pub struct Options { /// Configuration flags for the writer. pub flags: WriterFlags, /// Set of SPIR-V allowed capabilities, if provided. + // Note: there is a major bug currently associated with deriving the capabilities. + // We are calling `required_capabilities`, but the semantics of this is broken. pub capabilities: Option>, } diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 227327ad5..f9b79290d 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -98,10 +98,18 @@ pub fn map_storage_format(word: &str) -> Result> pub fn get_scalar_type(word: &str) -> Option<(crate::ScalarKind, crate::Bytes)> { match word { + "f16" => Some((crate::ScalarKind::Float, 2)), "f32" => Some((crate::ScalarKind::Float, 4)), + "f64" => Some((crate::ScalarKind::Float, 8)), + "i8" => Some((crate::ScalarKind::Sint, 1)), + "i16" => Some((crate::ScalarKind::Sint, 2)), "i32" => Some((crate::ScalarKind::Sint, 4)), + "i64" => Some((crate::ScalarKind::Sint, 8)), + "u8" => Some((crate::ScalarKind::Uint, 1)), + "u16" => Some((crate::ScalarKind::Uint, 2)), "u32" => Some((crate::ScalarKind::Uint, 4)), - "bool" => Some((crate::ScalarKind::Bool, 1)), + "u64" => Some((crate::ScalarKind::Uint, 8)), + "bool" => Some((crate::ScalarKind::Bool, crate::BOOL_WIDTH)), _ => None, } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index a9f4f999b..51ebde417 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1637,23 +1637,10 @@ impl Parser { type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result> { + if let Some((kind, width)) = conv::get_scalar_type(word) { + return Ok(crate::TypeInner::Scalar { kind, width }); + } Ok(match word { - "f32" => crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - width: 4, - }, - "i32" => crate::TypeInner::Scalar { - kind: crate::ScalarKind::Sint, - width: 4, - }, - "u32" => crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: 4, - }, - "bool" => crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: crate::BOOL_WIDTH, - }, "vec2" => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 711124508..6a9949a65 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -1,6 +1,7 @@ use super::{ analyzer::{FunctionInfo, GlobalUse}, - Disalignment, FunctionError, ModuleInfo, ShaderStages, TypeFlags, ValidationFlags, + Capabilities, Disalignment, FunctionError, ModuleInfo, ShaderStages, TypeFlags, + ValidationFlags, }; use crate::arena::{Arena, Handle}; @@ -24,6 +25,8 @@ pub enum GlobalVariableError { required: TypeFlags, seen: TypeFlags, }, + #[error("Capability {0:?} is not supported")] + UnsupportedCapability(Capabilities), #[error("Binding decoration is missing or not applicable")] InvalidBinding, #[error("Alignment requirements for this storage class are not met by {0:?}")] @@ -332,11 +335,18 @@ impl super::Validator { crate::StorageClass::Private | crate::StorageClass::WorkGroup => { (crate::StorageAccess::empty(), TypeFlags::DATA, false) } - crate::StorageClass::PushConstant => ( - crate::StorageAccess::LOAD, - TypeFlags::DATA | TypeFlags::HOST_SHARED, - false, - ), + crate::StorageClass::PushConstant => { + if !self.capabilities.contains(Capabilities::PUSH_CONSTANT) { + return Err(GlobalVariableError::UnsupportedCapability( + Capabilities::PUSH_CONSTANT, + )); + } + ( + crate::StorageAccess::LOAD, + TypeFlags::DATA | TypeFlags::HOST_SHARED, + false, + ) + } }; if !allowed_storage_access.contains(var.storage_access) { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 558b75bd4..c34eeebd2 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -49,11 +49,14 @@ impl Default for ValidationFlags { #[must_use] bitflags::bitflags! { /// Allowed IR capabilities. + #[derive(Default)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Capabilities: u8 { - /// Float values with width = 8 - const FLOAT64 = 0x1; + /// Support for `StorageClass:PushConstant`. + const PUSH_CONSTANT = 0x1; + /// Float values with width = 8. + const FLOAT64 = 0x2; } } diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index 450770cac..16021ec3b 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -1,5 +1,4 @@ ( - spv_flow_dump_prefix: "", spv_version: (1, 0), spv_capabilities: [ Shader ], spv_debug: true, diff --git a/tests/in/collatz.param.ron b/tests/in/collatz.param.ron index 984ca763e..42c8480e4 100644 --- a/tests/in/collatz.param.ron +++ b/tests/in/collatz.param.ron @@ -1,8 +1,5 @@ ( - spv_flow_dump_prefix: "", spv_version: (1, 0), spv_capabilities: [ Shader ], spv_debug: true, - spv_adjust_coordinate_space: false, - msl_custom: false, ) diff --git a/tests/in/control-flow.param.ron b/tests/in/control-flow.param.ron index 6de22960d..d6269ab62 100644 --- a/tests/in/control-flow.param.ron +++ b/tests/in/control-flow.param.ron @@ -1,7 +1,4 @@ ( spv_version: (1, 1), spv_capabilities: [ Shader ], - spv_debug: false, - spv_adjust_coordinate_space: false, - msl_custom: false, ) diff --git a/tests/in/empty.param.ron b/tests/in/empty.param.ron index 6de22960d..d6269ab62 100644 --- a/tests/in/empty.param.ron +++ b/tests/in/empty.param.ron @@ -1,7 +1,4 @@ ( spv_version: (1, 1), spv_capabilities: [ Shader ], - spv_debug: false, - spv_adjust_coordinate_space: false, - msl_custom: false, ) diff --git a/tests/in/extra.param.ron b/tests/in/extra.param.ron new file mode 100644 index 000000000..1767cbe3f --- /dev/null +++ b/tests/in/extra.param.ron @@ -0,0 +1,5 @@ +( + god_mode: true, + spv_version: (1, 0), + spv_capabilities: [ Shader ], +) diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl new file mode 100644 index 000000000..11b8a2eb6 --- /dev/null +++ b/tests/in/extra.wgsl @@ -0,0 +1,11 @@ +[[block]] +struct PushConstants { + index: u32; + double: vec2; +}; +var pc: PushConstants; + +[[stage(fragment)]] +fn main([[location(0)]] color: vec4) -> [[location(0)]] vec4 { + return color; +} diff --git a/tests/in/image.param.ron b/tests/in/image.param.ron index 54df97117..703113755 100644 --- a/tests/in/image.param.ron +++ b/tests/in/image.param.ron @@ -2,6 +2,4 @@ spv_version: (1, 1), spv_capabilities: [ Shader, ImageQuery, Image1D, Sampled1D ], spv_debug: true, - spv_adjust_coordinate_space: false, - msl_custom: false, ) diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index 804665025..f0c6a13d5 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -3,6 +3,5 @@ spv_capabilities: [ Shader, SampleRateShading ], spv_debug: true, spv_adjust_coordinate_space: true, - msl_custom: false, glsl_desktop_version: Some(400) ) diff --git a/tests/in/operators.param.ron b/tests/in/operators.param.ron index bd5e5acc2..553f5e75f 100644 --- a/tests/in/operators.param.ron +++ b/tests/in/operators.param.ron @@ -1,7 +1,4 @@ ( spv_version: (1, 0), spv_capabilities: [ Shader ], - spv_debug: false, - spv_adjust_coordinate_space: false, - msl_custom: false, ) diff --git a/tests/in/quad-glsl.param.ron b/tests/in/quad-glsl.param.ron index efded54c2..c073cf1a5 100644 --- a/tests/in/quad-glsl.param.ron +++ b/tests/in/quad-glsl.param.ron @@ -3,5 +3,4 @@ spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: true, - msl_custom: false, ) diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index efded54c2..c073cf1a5 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -3,5 +3,4 @@ spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: true, - msl_custom: false, ) diff --git a/tests/in/shadow.param.ron b/tests/in/shadow.param.ron index dfa9978c3..c6b43089b 100644 --- a/tests/in/shadow.param.ron +++ b/tests/in/shadow.param.ron @@ -1,8 +1,6 @@ ( - spv_flow_dump_prefix: "", spv_version: (1, 2), spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: true, - msl_custom: false, ) diff --git a/tests/in/texture-array.param.ron b/tests/in/texture-array.param.ron deleted file mode 100644 index b46594e31..000000000 --- a/tests/in/texture-array.param.ron +++ /dev/null @@ -1,8 +0,0 @@ -( - spv_flow_dump_prefix: "", - spv_version: (1, 5), - spv_capabilities: [ Shader ], - spv_debug: true, - spv_adjust_coordinate_space: false, - msl_custom: false, -) diff --git a/tests/in/texture-array.wgsl b/tests/in/texture-array.wgsl deleted file mode 100644 index 5f2e09b35..000000000 --- a/tests/in/texture-array.wgsl +++ /dev/null @@ -1,18 +0,0 @@ -[[group(0), binding(0)]] var texture0: texture_2d; -[[group(0), binding(1)]] var texture1: texture_2d; -[[group(0), binding(2)]] var sampler: sampler; - -[[block]] -struct PushConstants { - index: u32; -}; -var pc: PushConstants; - -[[stage(fragment)]] -fn main([[location(0)]] tex_coord: vec2) -> [[location(1)]] vec4 { - if (pc.index == 0u) { - return textureSample(texture0, sampler, tex_coord); - } else { - return textureSample(texture1, sampler, tex_coord); - } -} diff --git a/tests/out/extra.msl b/tests/out/extra.msl new file mode 100644 index 000000000..b2a2363d9 --- /dev/null +++ b/tests/out/extra.msl @@ -0,0 +1,21 @@ +#include +#include + +struct PushConstants { + metal::uint index; + char _pad1[12]; + metal::float2 double1; +}; + +struct main1Input { + metal::float4 color [[user(loc0), center_perspective]]; +}; +struct main1Output { + metal::float4 member [[color(0)]]; +}; +fragment main1Output main1( + main1Input varyings [[stage_in]] +) { + const auto color = varyings.color; + return main1Output { color }; +} diff --git a/tests/out/extra.spvasm b/tests/out/extra.spvasm new file mode 100644 index 000000000..ec05bdbdf --- /dev/null +++ b/tests/out/extra.spvasm @@ -0,0 +1,37 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 20 +OpCapability Shader +OpCapability Float64 +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %17 "main" %12 %15 +OpExecutionMode %17 OriginUpperLeft +OpDecorate %6 Block +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %6 1 Offset 16 +OpDecorate %12 Location 0 +OpDecorate %15 Location 0 +%2 = OpTypeVoid +%3 = OpTypeInt 32 0 +%5 = OpTypeFloat 64 +%4 = OpTypeVector %5 2 +%6 = OpTypeStruct %3 %4 +%8 = OpTypeFloat 32 +%7 = OpTypeVector %8 4 +%10 = OpTypePointer PushConstant %6 +%9 = OpVariable %10 PushConstant +%13 = OpTypePointer Input %7 +%12 = OpVariable %13 Input +%16 = OpTypePointer Output %7 +%15 = OpVariable %16 Output +%18 = OpTypeFunction %2 +%17 = OpFunction %2 None %18 +%11 = OpLabel +%14 = OpLoad %7 %12 +OpBranch %19 +%19 = OpLabel +OpStore %15 %14 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/texture-array.msl b/tests/out/texture-array.msl deleted file mode 100644 index 229d53357..000000000 --- a/tests/out/texture-array.msl +++ /dev/null @@ -1,29 +0,0 @@ -#include -#include - -struct PushConstants { - metal::uint index; -}; - -struct main1Input { - metal::float2 tex_coord [[user(loc0), center_perspective]]; -}; -struct main1Output { - metal::float4 member [[color(1)]]; -}; -fragment main1Output main1( - main1Input varyings [[stage_in]] -, metal::texture2d texture0_ [[user(fake0)]] -, metal::texture2d texture1_ [[user(fake0)]] -, metal::sampler sampler [[user(fake0)]] -, constant PushConstants& pc [[user(fake0)]] -) { - const auto tex_coord = varyings.tex_coord; - if (pc.index == 0u) { - metal::float4 _e9 = texture0_.sample(sampler, tex_coord); - return main1Output { _e9 }; - } else { - metal::float4 _e10 = texture1_.sample(sampler, tex_coord); - return main1Output { _e10 }; - } -} diff --git a/tests/out/texture-array.spvasm b/tests/out/texture-array.spvasm deleted file mode 100644 index faefb5f6e..000000000 --- a/tests/out/texture-array.spvasm +++ /dev/null @@ -1,78 +0,0 @@ -; SPIR-V -; Version: 1.5 -; Generator: rspirv -; Bound: 43 -OpCapability Shader -%1 = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %24 "main" %19 %22 -OpExecutionMode %24 OriginUpperLeft -OpSource GLSL 450 -OpName %8 "PushConstants" -OpMemberName %8 0 "index" -OpName %11 "texture0" -OpName %13 "texture1" -OpName %14 "sampler" -OpName %16 "pc" -OpName %19 "tex_coord" -OpName %24 "main" -OpDecorate %8 Block -OpMemberDecorate %8 0 Offset 0 -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 0 -OpDecorate %13 DescriptorSet 0 -OpDecorate %13 Binding 1 -OpDecorate %14 DescriptorSet 0 -OpDecorate %14 Binding 2 -OpDecorate %19 Location 0 -OpDecorate %22 Location 1 -%2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpConstant %4 0 -%6 = OpTypeFloat 32 -%5 = OpTypeImage %6 2D 0 0 0 1 Unknown -%7 = OpTypeSampler -%8 = OpTypeStruct %4 -%9 = OpTypeVector %6 2 -%10 = OpTypeVector %6 4 -%12 = OpTypePointer UniformConstant %5 -%11 = OpVariable %12 UniformConstant -%13 = OpVariable %12 UniformConstant -%15 = OpTypePointer UniformConstant %7 -%14 = OpVariable %15 UniformConstant -%17 = OpTypePointer PushConstant %8 -%16 = OpVariable %17 PushConstant -%20 = OpTypePointer Input %9 -%19 = OpVariable %20 Input -%23 = OpTypePointer Output %10 -%22 = OpVariable %23 Output -%25 = OpTypeFunction %2 -%30 = OpTypePointer PushConstant %4 -%33 = OpTypeBool -%38 = OpTypeSampledImage %5 -%24 = OpFunction %2 None %25 -%18 = OpLabel -%21 = OpLoad %9 %19 -%26 = OpLoad %5 %11 -%27 = OpLoad %5 %13 -%28 = OpLoad %7 %14 -OpBranch %29 -%29 = OpLabel -%31 = OpAccessChain %30 %16 %3 -%32 = OpLoad %4 %31 -%34 = OpIEqual %33 %32 %3 -OpSelectionMerge %35 None -OpBranchConditional %34 %36 %37 -%36 = OpLabel -%39 = OpSampledImage %38 %26 %28 -%40 = OpImageSampleImplicitLod %10 %39 %21 -OpStore %22 %40 -OpReturn -%37 = OpLabel -%41 = OpSampledImage %38 %27 %28 -%42 = OpImageSampleImplicitLod %10 %41 %21 -OpStore %22 %42 -OpReturn -%35 = OpLabel -OpReturn -OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e0aabd8c2..b628075ce 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -21,18 +21,23 @@ bitflags::bitflags! { #[derive(Default, serde::Deserialize)] struct Parameters { + #[serde(default)] + god_mode: bool, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_version: (u8, u8), #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_capabilities: naga::FastHashSet, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + #[serde(default)] spv_debug: bool, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + #[serde(default)] spv_adjust_coordinate_space: bool, #[cfg(all(feature = "deserialize", feature = "msl-out"))] #[serde(default)] msl: naga::back::msl::Options, #[cfg(all(not(feature = "deserialize"), feature = "msl-out"))] + #[serde(default)] msl_custom: bool, #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] #[serde(default)] @@ -46,12 +51,14 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), }; - let info = naga::valid::Validator::new( - naga::valid::ValidationFlags::all(), - naga::valid::Capabilities::empty(), - ) - .validate(module) - .unwrap(); + let capabilities = if params.god_mode { + naga::valid::Capabilities::all() + } else { + naga::valid::Capabilities::empty() + }; + let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities) + .validate(module) + .unwrap(); let dest = PathBuf::from(root).join(DIR_OUT).join(name); @@ -248,7 +255,7 @@ fn convert_wgsl() { ), ("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL), ("image", Targets::SPIRV | Targets::METAL), - ("texture-array", Targets::SPIRV | Targets::METAL), + ("extra", Targets::SPIRV | Targets::METAL), ("operators", Targets::SPIRV | Targets::METAL | Targets::GLSL), ( "interpolate", From ba422f10f83e7c33cebb9c53a8df2b8e4df4de98 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 8 May 2021 22:07:13 -0400 Subject: [PATCH 0816/2212] [msl] fix splat namespace --- src/back/glsl/mod.rs | 2 +- src/back/msl/writer.rs | 2 +- tests/out/access.msl | 2 +- tests/out/boids.msl | 4 ++-- tests/out/image.msl | 2 +- tests/out/operators.msl | 2 +- tests/out/shadow.msl | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 0d75c8471..ef2f14933 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1380,7 +1380,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}", INDENT.repeat(indent))?; } for (index, member) in members.iter().enumerate() { - // TODO: handle builtin in better way + // TODO: handle builtin in better way if let Some(Binding::BuiltIn(builtin)) = member.binding { match builtin { crate::BuiltIn::ClipDistance diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 33317004c..cde303cb9 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -775,7 +775,7 @@ impl Writer { let scalar = scalar_kind_string(scalar_kind); let size = vector_size_str(size); - write!(self.out, "{}{}(", scalar, size)?; + write!(self.out, "{}::{}{}(", NAMESPACE, scalar, size)?; self.put_expression(value, context, true)?; write!(self.out, ")")?; } diff --git a/tests/out/access.msl b/tests/out/access.msl index 8f623b8ab..36fd35774 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -24,5 +24,5 @@ vertex fooOutput foo( , device Bar& bar [[buffer(0)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - return fooOutput { static_cast(int4(type5 {bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u], static_cast(bar.matrix[3u].x), 3, 4, 5}.inner[vi])) }; + return fooOutput { static_cast(metal::int4(type5 {bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u], static_cast(bar.matrix[3u].x), 3, 4, 5}.inner[vi])) }; } diff --git a/tests/out/boids.msl b/tests/out/boids.msl index c49bff960..05f0760f3 100644 --- a/tests/out/boids.msl +++ b/tests/out/boids.msl @@ -79,10 +79,10 @@ kernel void main1( } } if (cMassCount > 0) { - cMass = (cMass / float2(static_cast(cMassCount))) - vPos; + cMass = (cMass / metal::float2(static_cast(cMassCount))) - vPos; } if (cVelCount > 0) { - cVel = cVel / float2(static_cast(cVelCount)); + cVel = cVel / metal::float2(static_cast(cVelCount)); } vVel = ((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale); vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); diff --git a/tests/out/image.msl b/tests/out/image.msl index 87ccd581a..a8d37578e 100644 --- a/tests/out/image.msl +++ b/tests/out/image.msl @@ -28,5 +28,5 @@ vertex queriesOutput queries( , metal::texture3d image_3d [[user(fake0)]] , metal::texture2d_ms image_aa [[user(fake0)]] ) { - return queriesOutput { float4(static_cast((((((((((((((((((int(image_1d.get_width()) + int2(image_2d.get_width(), image_2d.get_height()).y) + int2(image_2d.get_width(1), image_2d.get_height(1)).y) + int2(image_2d_array.get_width(), image_2d_array.get_height()).y) + int2(image_2d_array.get_width(1), image_2d_array.get_height(1)).y) + int(image_2d_array.get_array_size())) + int3(image_cube.get_width()).y) + int3(image_cube.get_width(1)).y) + int3(image_cube_array.get_width()).y) + int3(image_cube_array.get_width(1)).y) + int(image_cube_array.get_array_size())) + int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()).z) + int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)).z) + int(image_aa.get_num_samples())) + int(image_2d.get_num_mip_levels())) + int(image_2d_array.get_num_mip_levels())) + int(image_3d.get_num_mip_levels())) + int(image_cube.get_num_mip_levels())) + int(image_cube_array.get_num_mip_levels()))) }; + return queriesOutput { metal::float4(static_cast((((((((((((((((((int(image_1d.get_width()) + int2(image_2d.get_width(), image_2d.get_height()).y) + int2(image_2d.get_width(1), image_2d.get_height(1)).y) + int2(image_2d_array.get_width(), image_2d_array.get_height()).y) + int2(image_2d_array.get_width(1), image_2d_array.get_height(1)).y) + int(image_2d_array.get_array_size())) + int3(image_cube.get_width()).y) + int3(image_cube.get_width(1)).y) + int3(image_cube_array.get_width()).y) + int3(image_cube_array.get_width(1)).y) + int(image_cube_array.get_array_size())) + int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()).z) + int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)).z) + int(image_aa.get_num_samples())) + int(image_2d.get_num_mip_levels())) + int(image_2d_array.get_num_mip_levels())) + int(image_3d.get_num_mip_levels())) + int(image_cube.get_num_mip_levels())) + int(image_cube_array.get_num_mip_levels()))) }; } diff --git a/tests/out/operators.msl b/tests/out/operators.msl index 9deefef7a..48c82bbca 100644 --- a/tests/out/operators.msl +++ b/tests/out/operators.msl @@ -4,7 +4,7 @@ metal::float4 splat( ) { - return (((float2(1.0) + float2(2.0)) - float2(3.0)) / float2(4.0)).xyxy + static_cast(int4(5) % int4(2)); + return (((metal::float2(1.0) + metal::float2(2.0)) - metal::float2(3.0)) / metal::float2(4.0)).xyxy + static_cast(metal::int4(5) % metal::int4(2)); } int unary( diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index 420dfda57..17f1c82ea 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -30,7 +30,7 @@ float fetch_shadow( if (homogeneous_coords.w <= 0.0) { return 1.0; } - float _e26 = t_shadow.sample_compare(sampler_shadow, ((homogeneous_coords.xy * metal::float2(0.5, -0.5)) / float2(homogeneous_coords.w)) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); + float _e26 = t_shadow.sample_compare(sampler_shadow, ((homogeneous_coords.xy * metal::float2(0.5, -0.5)) / metal::float2(homogeneous_coords.w)) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); return _e26; } From 6a42e4a0f83add0ff7055d128b99084a82919af5 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 27 Apr 2021 17:29:02 +0300 Subject: [PATCH 0817/2212] [wgsl-out] Enable snapshot testing for spv-in quad shader --- src/back/wgsl/writer.rs | 761 +++++++++++++++++++++++++++------------ tests/out/access.wgsl | 6 - tests/out/empty.wgsl | 4 +- tests/out/quad-vert.wgsl | 29 ++ tests/out/quad.wgsl | 19 +- tests/snapshots.rs | 2 +- 6 files changed, 573 insertions(+), 248 deletions(-) delete mode 100644 tests/out/access.wgsl create mode 100644 tests/out/quad-vert.wgsl diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 1aa412f64..f906d3fba 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1,23 +1,19 @@ // TODO: temp #![allow(dead_code)] use super::Error; -use crate::FastHashMap; use crate::{ back::{binary_operation_str, vector_size_str, wgsl::keywords::RESERVED}, - proc::{EntryPointIndex, TypeResolution}, + proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, - Arena, ArraySize, Binding, Constant, Expression, Function, GlobalVariable, Handle, ImageClass, - ImageDimension, Module, ScalarKind, ShaderStage, Statement, StorageFormat, StructLevel, Type, - TypeInner, -}; -use crate::{ - proc::{NameKey, Namer}, - StructMember, + Arena, ArraySize, Binding, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, + ImageClass, ImageDimension, Interpolation, Module, Sampling, ScalarKind, ScalarValue, + ShaderStage, Statement, StorageFormat, StructLevel, StructMember, Type, TypeInner, }; use bit_set::BitSet; use std::fmt::Write; const INDENT: &str = " "; +const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; const BAKE_PREFIX: &str = "_e"; /// Shorthand result used internally by the backend @@ -26,10 +22,12 @@ type BackendResult = Result<(), Error>; /// WGSL attribute /// https://gpuweb.github.io/gpuweb/wgsl/#attributes enum Attribute { + Access(crate::StorageAccess), Binding(u32), Block, BuiltIn(crate::BuiltIn), Group(u32), + Interpolate(Option, Option), Location(u32), Stage(ShaderStage), Stride(u32), @@ -75,23 +73,14 @@ impl Writer { } } - pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { + fn reset(&mut self, module: &Module) { self.names.clear(); self.namer.reset(module, RESERVED, &[], &mut self.names); + self.named_expressions.clear(); + } - // Write all constants - for (_, constant) in module.constants.iter() { - if constant.name.is_some() { - self.write_constant(&constant, true)?; - } - } - - // Write all globals - for (_, global) in module.global_variables.iter() { - if global.name.is_some() { - self.write_global(&module, &global)?; - } - } + pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { + self.reset(module); // Write all structs for (handle, ty) in module.types.iter() { @@ -99,13 +88,46 @@ impl Writer { level, ref members, .. } = ty.inner { - let name = &self.names[&NameKey::Type(handle)].clone(); let block = level == StructLevel::Root; - self.write_struct(module, name, block, members)?; + self.write_struct(module, handle, block, members)?; writeln!(self.out)?; } } + // Write all constants + for (handle, constant) in module.constants.iter() { + if constant.name.is_some() { + self.write_global_constant(&constant, handle)?; + } + } + + // Write all globals + for (ty, global) in module.global_variables.iter() { + self.write_global(&module, &global, ty)?; + } + + if !module.global_variables.is_empty() { + // Add extra newline for readability + writeln!(self.out)?; + } + + // Write all regular functions + for (handle, function) in module.functions.iter() { + let fun_info = &info[handle]; + + let func_ctx = FunctionCtx { + ty: FunctionType::Function(handle), + info: fun_info, + expressions: &function.expressions, + }; + + // Write the function + self.write_function(&module, &function, &func_ctx)?; + + writeln!(self.out)?; + } + + // Write all entry points for (index, ep) in module.entry_points.iter().enumerate() { let attributes = match ep.stage { ShaderStage::Vertex | ShaderStage::Fragment => vec![Attribute::Stage(ep.stage)], @@ -115,7 +137,7 @@ impl Writer { ], }; - self.write_attributes(&attributes)?; + self.write_attributes(&attributes, false)?; // Add a newline after attribute writeln!(self.out)?; @@ -125,11 +147,28 @@ impl Writer { expressions: &ep.function.expressions, }; self.write_function(&module, &ep.function, &func_ctx)?; - writeln!(self.out)?; + + if index < module.entry_points.len() - 1 { + writeln!(self.out)?; + } } - // Add a newline at the end of file - writeln!(self.out)?; + Ok(()) + } + + /// Helper method used to write [`ScalarValue`](ScalarValue) + /// + /// # Notes + /// Adds no trailing or leading whitespace + fn write_scalar_value(&mut self, value: ScalarValue) -> BackendResult { + match value { + ScalarValue::Sint(value) => write!(self.out, "{}", value)?, + ScalarValue::Uint(value) => write!(self.out, "{}", value)?, + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero + ScalarValue::Float(value) => write!(self.out, "{:?}", value)?, + ScalarValue::Bool(value) => write!(self.out, "{}", value)?, + } Ok(()) } @@ -145,61 +184,100 @@ impl Writer { func: &Function, func_ctx: &FunctionCtx<'_>, ) -> BackendResult { - if func.name.is_some() { - write!(self.out, "fn {}(", func.name.as_ref().unwrap())?; + let func_name = match func_ctx.ty { + FunctionType::EntryPoint(index) => self.names[&NameKey::EntryPoint(index)].clone(), + FunctionType::Function(handle) => self.names[&NameKey::Function(handle)].clone(), + }; - // Write function arguments - // TODO: another function type - if let FunctionType::EntryPoint(ep_index) = func_ctx.ty { - for (index, arg) in func.arguments.iter().enumerate() { - // Write argument attribute if a binding is present - if let Some(ref binding) = arg.binding { - self.write_attributes(&[map_binding_to_attribute(binding)])?; - write!(self.out, " ")?; - } - // Write argument name - write!( - self.out, - "{}: ", - &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)] - )?; - // Write argument type - self.write_type(module, arg.ty)?; - if index < func.arguments.len() - 1 { - // Add a separator between args - write!(self.out, ", ")?; - } + // Write function name + write!(self.out, "fn {}(", func_name)?; + + // Write function arguments + for (index, arg) in func.arguments.iter().enumerate() { + // Write argument attribute if a binding is present + if let Some(ref binding) = arg.binding { + self.write_attributes(&map_binding_to_attribute(binding), false)?; + write!(self.out, " ")?; + } + // Write argument name + let argument_name = match func_ctx.ty { + FunctionType::Function(handle) => { + self.names[&NameKey::FunctionArgument(handle, index as u32)].clone() } - write!(self.out, ")")?; - } - - // Write function return type - if let Some(ref result) = func.result { - if let Some(ref binding) = result.binding { - write!(self.out, " -> ")?; - self.write_attributes(&[map_binding_to_attribute(binding)])?; - write!(self.out, " ")?; - self.write_type(module, result.ty)?; - // Extra space only for readability - write!(self.out, " ")?; - } else { - let struct_name = &self.names[&NameKey::Type(result.ty)].clone(); - write!(self.out, " -> {} ", struct_name)?; + FunctionType::EntryPoint(ep_index) => { + self.names[&NameKey::EntryPointArgument(ep_index, index as u32)].clone() } + }; + + write!(self.out, "{}: ", argument_name)?; + // Write argument type + self.write_type(module, arg.ty)?; + if index < func.arguments.len() - 1 { + // Add a separator between args + write!(self.out, ", ")?; } - - write!(self.out, "{{")?; - writeln!(self.out)?; - - // Write the function body (statement list) - for sta in func.body.iter() { - // The indentation should always be 1 when writing the function body - self.write_stmt(&module, sta, &func_ctx, 1)?; - } - - writeln!(self.out, "}}")?; } + write!(self.out, ")")?; + + // Write function return type + if let Some(ref result) = func.result { + if let Some(ref binding) = result.binding { + write!(self.out, " -> ")?; + self.write_attributes(&map_binding_to_attribute(binding), true)?; + self.write_type(module, result.ty)?; + } else { + let struct_name = &self.names[&NameKey::Type(result.ty)].clone(); + write!(self.out, " -> {}", struct_name)?; + } + } + + write!(self.out, " {{")?; + writeln!(self.out)?; + + // Write function local variables + for (handle, local) in func.local_variables.iter() { + // Write indentation (only for readability) + write!(self.out, "{}", INDENT)?; + + // Write the local name + // The leading space is important + let name_key = match func_ctx.ty { + FunctionType::Function(func_handle) => NameKey::FunctionLocal(func_handle, handle), + FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, handle), + }; + write!(self.out, "var {}: ", self.names[&name_key])?; + + // Write the local type + self.write_type(&module, local.ty)?; + + // Write the local initializer if needed + if let Some(init) = local.init { + // Put the equal signal only if there's a initializer + // The leading and trailing spaces aren't needed but help with readability + write!(self.out, " = ")?; + + // Write the constant + // `write_constant` adds no trailing or leading space/newline + self.write_constant(module, init)?; + } + + // Finish the local with `;` and add a newline (only for readability) + writeln!(self.out, ";")? + } + + if !func.local_variables.is_empty() { + writeln!(self.out)?; + } + + // Write the function body (statement list) + for sta in func.body.iter() { + // The indentation should always be 1 when writing the function body + self.write_stmt(&module, sta, &func_ctx, 1)?; + } + + writeln!(self.out, "}}")?; + self.named_expressions.clear(); Ok(()) @@ -208,45 +286,84 @@ impl Writer { /// Helper method to write a attribute /// /// # Notes - /// Adds no leading or trailing whitespace - fn write_attributes(&mut self, attributes: &[Attribute]) -> BackendResult { - write!(self.out, "[[")?; + /// Adds an extra space if required + fn write_attributes(&mut self, attributes: &[Attribute], extra_space: bool) -> BackendResult { + let mut attributes_str = String::new(); for (index, attribute) in attributes.iter().enumerate() { - match *attribute { - Attribute::Block => { - write!(self.out, "block")?; + let attribute_str = match *attribute { + Attribute::Access(access) => { + let access_str = if access.is_all() { + "read_write" + } else if access.contains(crate::StorageAccess::LOAD) { + "read" + } else { + "write" + }; + format!("access({})", access_str) } - Attribute::Location(id) => write!(self.out, "location({})", id)?, + Attribute::Block => String::from("block"), + Attribute::Location(id) => format!("location({})", id), Attribute::BuiltIn(builtin_attrib) => { let builtin_str = builtin_str(builtin_attrib); if let Some(builtin) = builtin_str { - write!(self.out, "builtin({})", builtin)? + format!("builtin({})", builtin) } else { log::warn!("Unsupported builtin attribute: {:?}", builtin_attrib); + String::from("") } } Attribute::Stage(shader_stage) => match shader_stage { - ShaderStage::Vertex => write!(self.out, "stage(vertex)")?, - ShaderStage::Fragment => write!(self.out, "stage(fragment)")?, - ShaderStage::Compute => write!(self.out, "stage(compute)")?, + ShaderStage::Vertex => String::from("stage(vertex)"), + ShaderStage::Fragment => String::from("stage(fragment)"), + ShaderStage::Compute => String::from("stage(compute)"), }, - Attribute::Stride(stride) => write!(self.out, "stride({})", stride)?, + Attribute::Stride(stride) => format!("stride({})", stride), Attribute::WorkGroupSize(size) => { - write!( - self.out, - "workgroup_size({}, {}, {})", - size[0], size[1], size[2] - )?; + format!("workgroup_size({}, {}, {})", size[0], size[1], size[2]) + } + Attribute::Binding(id) => format!("binding({})", id), + Attribute::Group(id) => format!("group({})", id), + Attribute::Interpolate(interpolation, sampling) => { + if interpolation.is_some() || sampling.is_some() { + let interpolation_str = if let Some(interpolation) = interpolation { + interpolation_str(interpolation) + } else { + "" + }; + let sampling_str = if let Some(sampling) = sampling { + // Center sampling is the default + if sampling == Sampling::Center { + String::from("") + } else { + format!(",{}", sampling_str(sampling)) + } + } else { + String::from("") + }; + format!("interpolate({}{})", interpolation_str, sampling_str) + } else { + String::from("") + } } - Attribute::Binding(id) => write!(self.out, "binding({})", id)?, - Attribute::Group(id) => write!(self.out, "group({})", id)?, }; - if index < attributes.len() - 1 { + if !attribute_str.is_empty() { // Add a separator between args - write!(self.out, ", ")?; + let separator = if index < attributes.len() - 1 { + ", " + } else { + "" + }; + attributes_str = format!("{}{}{}", attributes_str, attribute_str, separator); } } - write!(self.out, "]]")?; + if !attributes_str.is_empty() { + //TODO: looks ugly + if attributes_str.ends_with(", ") { + attributes_str = attributes_str[0..attributes_str.len() - 2].to_string(); + } + let extra_space_str = if extra_space { " " } else { "" }; + write!(self.out, "[[{}]]{}", attributes_str, extra_space_str)?; + } Ok(()) } @@ -258,41 +375,48 @@ impl Writer { fn write_struct( &mut self, module: &Module, - name: &str, + handle: Handle, block: bool, members: &[StructMember], ) -> BackendResult { if block { - self.write_attributes(&[Attribute::Block])?; + self.write_attributes(&[Attribute::Block], false)?; writeln!(self.out)?; } + let name = &self.names[&NameKey::Type(handle)].clone(); write!(self.out, "struct {} {{", name)?; writeln!(self.out)?; - for (_, member) in members.iter().enumerate() { - if member.name.is_some() { - // The indentation is only for readability - write!(self.out, "{}", INDENT)?; - if let Some(ref binding) = member.binding { - self.write_attributes(&[map_binding_to_attribute(binding)])?; - write!(self.out, " ")?; + for (index, member) in members.iter().enumerate() { + // Skip struct member with unsupported built in + if let Some(Binding::BuiltIn(builtin)) = member.binding { + if builtin_str(builtin).is_none() { + log::warn!("Skip member with unsupported builtin {:?}", builtin); + continue; } - // Write struct member name and type - write!(self.out, "{}: ", member.name.as_ref().unwrap())?; - // Write stride attribute for array struct member - if let TypeInner::Array { - base: _, - size: _, - stride, - } = module.types[member.ty].inner - { - self.write_attributes(&[Attribute::Stride(stride)])?; - write!(self.out, " ")?; - } - self.write_type(module, member.ty)?; - write!(self.out, ";")?; - writeln!(self.out)?; } + + // The indentation is only for readability + write!(self.out, "{}", INDENT)?; + if let Some(ref binding) = member.binding { + self.write_attributes(&map_binding_to_attribute(binding), true)?; + } + // Write struct member name and type + let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; + write!(self.out, "{}: ", member_name)?; + // Write stride attribute for array struct member + if let TypeInner::Array { + base: _, + size: _, + stride, + } = module.types[member.ty].inner + { + self.write_attributes(&[Attribute::Stride(stride)], true)?; + } + self.write_type(module, member.ty)?; + write!(self.out, ";")?; + writeln!(self.out)?; } + write!(self.out, "}};")?; writeln!(self.out)?; @@ -352,7 +476,7 @@ impl Writer { ), ImageClass::Depth => ("depth", "", String::from("")), ImageClass::Storage(storage_format) => ( - "storage", + "storage_", "", format!("<{}>", storage_format_str(storage_format)), ), @@ -375,7 +499,7 @@ impl Writer { ArraySize::Constant(handle) => { self.write_type(module, base)?; write!(self.out, ",")?; - self.write_constant(&module.constants[handle], false)?; + self.write_constant(module, handle)?; } ArraySize::Dynamic => { self.write_type(module, base)?; @@ -423,7 +547,7 @@ impl Writer { let min_ref_count = func_ctx.expressions[handle].bake_ref_count(); if min_ref_count <= func_ctx.info[handle].ref_count { write!(self.out, "{}", INDENT.repeat(indent))?; - self.start_baking_expr(handle, &func_ctx)?; + self.start_baking_expr(module, handle, &func_ctx)?; self.write_expr(module, handle, &func_ctx)?; writeln!(self.out, ";")?; self.named_expressions.insert(handle.index()); @@ -461,19 +585,49 @@ impl Writer { } Statement::Return { value } => { write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "return")?; if let Some(return_value) = value { - write!(self.out, "return ")?; + // The leading space is important + write!(self.out, " ")?; self.write_expr(module, return_value, &func_ctx)?; - writeln!(self.out, ";")?; - } else { - writeln!(self.out, "return;")?; } + writeln!(self.out, ";")?; } // TODO: copy-paste from glsl-out Statement::Kill => { write!(self.out, "{}", INDENT.repeat(indent))?; writeln!(self.out, "discard;")? } + // TODO: copy-paste from glsl-out + Statement::Store { pointer, value } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, " = ")?; + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ";")? + } + crate::Statement::Call { + function, + ref arguments, + result, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + if let Some(expr) = result { + self.start_baking_expr(module, expr, &func_ctx)?; + self.named_expressions.insert(expr.index()); + } + let func_name = &self.names[&NameKey::Function(function)]; + write!(self.out, "{}(", func_name)?; + for (index, argument) in arguments.iter().enumerate() { + self.write_expr(module, *argument, func_ctx)?; + // Only write a comma if isn't the last element + if index != arguments.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } + writeln!(self.out, ");")? + } _ => { return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))); } @@ -484,6 +638,7 @@ impl Writer { fn start_baking_expr( &mut self, + module: &Module, handle: Handle, context: &FunctionCtx, ) -> BackendResult { @@ -492,6 +647,9 @@ impl Writer { let ty = &context.info[handle].ty; // Write variable type match *ty { + TypeResolution::Handle(ty_handle) => { + self.write_type(module, ty_handle)?; + } TypeResolution::Value(crate::TypeInner::Scalar { kind, .. }) => { write!(self.out, "{}", scalar_kind_str(kind))?; } @@ -530,15 +688,74 @@ impl Writer { } match *expression { - Expression::Constant(constant) => { - self.write_constant(&module.constants[constant], false)? - } + Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::Compose { ty, ref components } => { self.write_type(&module, ty)?; write!(self.out, "(")?; - self.write_slice(components, |this, _, arg| { - this.write_expr(&module, *arg, func_ctx) - })?; + // !spv-in specific notes! + // WGSL does not support all SPIR-V builtins and we should skip it in generated shaders. + // We already skip them when we generate struct type. + // Now we need to find components that used struct with ignored builtins. + + // So, why we can't just return the error to a user? + // We can, but otherwise, we can't generate WGSL shader from any glslang SPIR-V shaders. + // glslang generates gl_PerVertex struct with gl_CullDistance, gl_ClipDistance and gl_PointSize builtin inside by default. + // All of them are not supported by WGSL. + + // We need to copy components to another vec because we don't know which of them we should write. + let mut components_to_write = Vec::with_capacity(components.len()); + for component in components { + let mut skip_component = false; + if let Expression::Load { pointer } = func_ctx.expressions[*component] { + if let Expression::AccessIndex { + base, + index: access_index, + } = func_ctx.expressions[pointer] + { + let base_ty_res = &func_ctx.info[base].ty; + let resolved = base_ty_res.inner_with(&module.types); + if let TypeInner::Pointer { + base: pointer_base_handle, + .. + } = *resolved + { + // Let's check that we try to access a struct member with unsupported built-in and skip it. + if let TypeInner::Struct { ref members, .. } = + module.types[pointer_base_handle].inner + { + if let Some(Binding::BuiltIn(builtin)) = + members[access_index as usize].binding + { + if builtin_str(builtin).is_none() { + // glslang why you did this with us... + log::warn!( + "Skip component with unsupported builtin {:?}", + builtin + ); + skip_component = true; + } + } + } + } + } + } + if skip_component { + continue; + } else { + components_to_write.push(*component); + } + } + + // non spv-in specific notes! + // Real `Expression::Compose` logic generates here. + for (index, component) in components_to_write.iter().enumerate() { + self.write_expr(module, *component, &func_ctx)?; + // Only write a comma if isn't the last element + if index != components_to_write.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } write!(self.out, ")")? } Expression::FunctionArgument(pos) => { @@ -642,6 +859,7 @@ impl Writer { format!("mat{}x{}", vector_size_str(columns), vector_size_str(rows)) } TypeInner::Vector { size, .. } => format!("vec{}", vector_size_str(size)), + TypeInner::Scalar { kind, .. } => String::from(scalar_kind_str(kind)), _ => { return Err(Error::Unimplemented(format!( "write_expr expression::as {:?}", @@ -672,6 +890,64 @@ impl Writer { self.write_expr(module, value, func_ctx)?; write!(self.out, ")")?; } + //TODO: add pointer logic + Expression::Load { pointer } => self.write_expr(module, pointer, func_ctx)?, + Expression::LocalVariable(handle) => { + let name_key = match func_ctx.ty { + FunctionType::Function(func_handle) => { + NameKey::FunctionLocal(func_handle, handle) + } + FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, handle), + }; + write!(self.out, "{}", self.names[&name_key])? + } + Expression::ArrayLength(expr) => { + write!(self.out, "arrayLength(")?; + self.write_expr(module, expr, func_ctx)?; + write!(self.out, ")")?; + } + Expression::Math { + fun, + arg, + arg1, + arg2, + } => { + use crate::MathFunction as Mf; + + let fun_name = match fun { + Mf::Length => "length", + Mf::Mix => "mix", + _ => { + return Err(Error::Unimplemented(format!( + "write_expr Math func {:?}", + fun + ))); + } + }; + + write!(self.out, "{}(", fun_name)?; + self.write_expr(module, arg, func_ctx)?; + if let Some(arg) = arg1 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } + if let Some(arg) = arg2 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } + write!(self.out, ")")? + } + Expression::Swizzle { + size, + vector, + pattern, + } => { + self.write_expr(module, vector, func_ctx)?; + write!(self.out, ".")?; + for &sc in pattern[..size as usize].iter() { + self.out.write_char(COMPONENTS[sc as usize])?; + } + } _ => { return Err(Error::Unimplemented(format!("write_expr {:?}", expression))); } @@ -680,115 +956,120 @@ impl Writer { Ok(()) } - /// Helper method that writes a list of comma separated `T` with a writer function `F` - /// - /// The writer function `F` receives a mutable reference to `self` that if needed won't cause - /// borrow checker issues (using for example a closure with `self` will cause issues), the - /// second argument is the 0 based index of the element on the list, and the last element is - /// a reference to the element `T` being written - /// - /// # Notes - /// - Adds no newlines or leading/trailing whitespace - /// - The last element won't have a trailing `,` - // TODO: copy-paste from glsl-out - fn write_slice BackendResult>( - &mut self, - data: &[T], - mut f: F, - ) -> BackendResult { - // Loop trough `data` invoking `f` for each element - for (i, item) in data.iter().enumerate() { - f(self, i as u32, item)?; - - // Only write a comma if isn't the last element - if i != data.len().saturating_sub(1) { - // The leading space is for readability only - write!(self.out, ", ")?; - } - } - - Ok(()) - } - /// Helper method used to write global variables - fn write_global(&mut self, module: &Module, global: &GlobalVariable) -> BackendResult { + /// # Notes + /// Always adds a newline + fn write_global( + &mut self, + module: &Module, + global: &GlobalVariable, + handle: Handle, + ) -> BackendResult { + let name = self.names[&NameKey::GlobalVariable(handle)].clone(); + // Write group and dinding attributes if present if let Some(ref binding) = global.binding { - self.write_attributes(&[ - Attribute::Group(binding.group), - Attribute::Binding(binding.binding), - ])?; - write!(self.out, " ")?; - } - - if let Some(ref name) = global.name { - // First write only global name - write!(self.out, "var {}: ", name)?; - // Write global type - self.write_type(module, global.ty)?; - // End with semicolon and extra newline for readability - writeln!(self.out, ";")?; + self.write_attributes( + &[ + Attribute::Group(binding.group), + Attribute::Binding(binding.binding), + ], + false, + )?; writeln!(self.out)?; } + // First write only global name + write!(self.out, "var {}: ", name)?; + // Write access attribute if present + if !global.storage_access.is_empty() { + self.write_attributes(&[Attribute::Access(global.storage_access)], true)?; + } + // Write global type + self.write_type(module, global.ty)?; + // End with semicolon + writeln!(self.out, ";")?; + Ok(()) } /// Helper method used to write constants /// /// # Notes - /// Adds newlines for global constants - fn write_constant(&mut self, constant: &Constant, global: bool) -> BackendResult { + /// Doesn't add any newlines or leading/trailing spaces + fn write_constant(&mut self, module: &Module, handle: Handle) -> BackendResult { + let constant = &module.constants[handle]; match constant.inner { crate::ConstantInner::Scalar { width: _, ref value, } => { if let Some(ref name) = constant.name { - if global { - // First write only constant name - write!(self.out, "let {}: ", name)?; - // Next write constant type and value - match *value { - crate::ScalarValue::Sint(value) => { - write!(self.out, "i32 = {}", value)?; - } - crate::ScalarValue::Uint(value) => { - write!(self.out, "u32 = {}", value)?; - } - crate::ScalarValue::Float(value) => { - write!(self.out, "f32 = {}", value)?; - } - crate::ScalarValue::Bool(value) => { - write!(self.out, "bool = {}", value)?; - } - }; - // End with semicolon and extra newline for readability - writeln!(self.out, ";")?; - writeln!(self.out)?; - } else { - write!(self.out, "{}", name)?; - } + write!(self.out, "{}", name)?; } else { - match *value { - crate::ScalarValue::Sint(value) => { - write!(self.out, "{}", value)?; - } - crate::ScalarValue::Uint(value) => { - write!(self.out, "{}", value)?; - } - // TODO: fix float - crate::ScalarValue::Float(value) => { - write!(self.out, "{:.1}", value)?; - } - crate::ScalarValue::Bool(value) => { - write!(self.out, "{}", value)?; - } - }; + self.write_scalar_value(*value)?; } } + crate::ConstantInner::Composite { ty, ref components } => { + self.write_type(module, ty)?; + write!(self.out, "(")?; + + // Write the comma separated constants + for (index, constant) in components.iter().enumerate() { + self.write_constant(module, *constant)?; + // Only write a comma if isn't the last element + if index != components.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } + write!(self.out, ")")? + } + } + + Ok(()) + } + + /// Helper method used to write global constants + /// + /// # Notes + /// Ends in a newline + fn write_global_constant( + &mut self, + constant: &Constant, + handle: Handle, + ) -> BackendResult { + match constant.inner { + crate::ConstantInner::Scalar { + width: _, + ref value, + } => { + let name = self.names[&NameKey::Constant(handle)].clone(); + // First write only constant name + write!(self.out, "let {}: ", name)?; + // Next write constant type and value + match *value { + crate::ScalarValue::Sint(value) => { + write!(self.out, "i32 = {}", value)?; + } + crate::ScalarValue::Uint(value) => { + write!(self.out, "u32 = {}", value)?; + } + crate::ScalarValue::Float(value) => { + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero + write!(self.out, "f32 = {:?}", value)?; + } + crate::ScalarValue::Bool(value) => { + write!(self.out, "bool = {}", value)?; + } + }; + // End with semicolon and extra newline for readability + writeln!(self.out, ";")?; + writeln!(self.out)?; + } _ => { return Err(Error::Unimplemented(format!( - "write_constant {:?}", + "write_global_constant {:?}", constant.inner ))); } @@ -876,10 +1157,34 @@ fn storage_format_str(format: StorageFormat) -> &'static str { } } -fn map_binding_to_attribute(binding: &Binding) -> Attribute { +/// Helper function that returns the string corresponding to the WGSL interpolation qualifier +fn interpolation_str(interpolation: Interpolation) -> &'static str { + match interpolation { + Interpolation::Perspective => "perspective", + Interpolation::Linear => "linear", + Interpolation::Flat => "flat", + } +} + +/// Return the WGSL auxiliary qualifier for the given sampling value. +fn sampling_str(sampling: Sampling) -> &'static str { + match sampling { + Sampling::Center => "", + Sampling::Centroid => "centroid", + Sampling::Sample => "sample", + } +} + +fn map_binding_to_attribute(binding: &Binding) -> Vec { match *binding { - Binding::BuiltIn(built_in) => Attribute::BuiltIn(built_in), - //TODO: Interpolation - Binding::Location { location, .. } => Attribute::Location(location), + Binding::BuiltIn(built_in) => vec![Attribute::BuiltIn(built_in)], + Binding::Location { + location, + interpolation, + sampling, + } => vec![ + Attribute::Location(location), + Attribute::Interpolate(interpolation, sampling), + ], } } diff --git a/tests/out/access.wgsl b/tests/out/access.wgsl deleted file mode 100644 index 4b1cbc85e..000000000 --- a/tests/out/access.wgsl +++ /dev/null @@ -1,6 +0,0 @@ -[[stage(vertex)]] -fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { - return vec4(vec4(array(1, 2, 3, 4, 5)[vi])); -} - - diff --git a/tests/out/empty.wgsl b/tests/out/empty.wgsl index 31548a146..1ee73b580 100644 --- a/tests/out/empty.wgsl +++ b/tests/out/empty.wgsl @@ -1,6 +1,4 @@ [[stage(compute), workgroup_size(1, 1, 1)]] -fn main(){ +fn main() { return; } - - diff --git a/tests/out/quad-vert.wgsl b/tests/out/quad-vert.wgsl new file mode 100644 index 000000000..66a173b4c --- /dev/null +++ b/tests/out/quad-vert.wgsl @@ -0,0 +1,29 @@ +[[block]] +struct gl_PerVertex { + [[builtin(position)]] gl_Position: vec4; +}; + +struct type10 { + [[location(0), interpolate(perspective)]] member: vec2; + [[builtin(position)]] gl_Position1: vec4; +}; + +var v_uv: vec2; +var a_uv: vec2; +var perVertexStruct: gl_PerVertex; +var a_pos: vec2; + +fn main() { + v_uv = a_uv; + let _e13: vec2 = a_pos; + perVertexStruct.gl_Position = vec4(_e13[0], _e13[1], 0.0, 1.0); + return; +} + +[[stage(vertex)]] +fn main1([[location(1)]] a_uv1: vec2, [[location(0)]] a_pos1: vec2) -> type10 { + a_uv = a_uv1; + a_pos = a_pos1; + main(); + return type10(v_uv, perVertexStruct.gl_Position); +} diff --git a/tests/out/quad.wgsl b/tests/out/quad.wgsl index ba45b48c2..fe924dc76 100644 --- a/tests/out/quad.wgsl +++ b/tests/out/quad.wgsl @@ -1,26 +1,25 @@ -let c_scale: f32 = 1.2; - -[[group(0), binding(0)]] var u_texture: texture_2d; - -[[group(0), binding(1)]] var u_sampler: sampler; - struct VertexOutput { - [[location(0)]] uv: vec2; + [[location(0), interpolate(perspective)]] uv: vec2; [[builtin(position)]] position: vec4; }; +let c_scale: f32 = 1.2; + +[[group(0), binding(0)]] +var u_texture: texture_2d; +[[group(0), binding(1)]] +var u_sampler: sampler; + [[stage(vertex)]] fn main([[location(0)]] pos: vec2, [[location(1)]] uv1: vec2) -> VertexOutput { return VertexOutput(uv1, vec4(c_scale * pos, 0.0, 1.0)); } [[stage(fragment)]] -fn main([[location(0)]] uv2: vec2) -> [[location(0)]] vec4 { +fn main1([[location(0), interpolate(perspective)]] uv2: vec2) -> [[location(0)]] vec4 { let _e4: vec4 = textureSample(u_texture, u_sampler, uv2); if (_e4[3] == 0.0) { discard; } return _e4[3] * _e4; } - - diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b628075ce..5fe0c2b45 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -303,7 +303,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { #[cfg(feature = "spv-in")] #[test] fn convert_spv_quad_vert() { - convert_spv("quad-vert", false, Targets::METAL | Targets::GLSL); + convert_spv("quad-vert", false, Targets::METAL | Targets::GLSL | Targets::WGSL); } #[cfg(feature = "spv-in")] From 0250ffe2fb9b30e24c1f8e54f4c387e53db8fbc6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 9 May 2021 01:27:23 -0400 Subject: [PATCH 0818/2212] [msl] early out if the binding sizes are missing --- src/back/msl/writer.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index cde303cb9..ca4523fd3 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1985,6 +1985,12 @@ impl Writer { info.entry_point_names.push(Err(err)); continue; } + if !self.runtime_sized_buffers.is_empty() { + if let Err(err) = options.resolve_sizes_buffer(ep.stage) { + info.entry_point_names.push(Err(err)); + continue; + } + } } writeln!(self.out)?; @@ -2207,14 +2213,8 @@ impl Writer { } if !self.runtime_sized_buffers.is_empty() { - let resolved = match options.resolve_sizes_buffer(ep.stage) { - Ok(resolved) => resolved, - Err(e) => { - info.entry_point_names.push(Err(e)); - continue; - } - }; - + // this is checked earlier + let resolved = options.resolve_sizes_buffer(ep.stage).unwrap(); let separator = if module.global_variables.is_empty() { ' ' } else { From a8df6a2b343af9d7913dec0f04133f7c1ea5c228 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 May 2021 01:26:08 -0400 Subject: [PATCH 0819/2212] [msl] make sizes buffer local to each function --- src/back/msl/writer.rs | 119 +++++++++++++++++++++++------------------ tests/out/collatz.msl | 6 +-- tests/out/shadow.msl | 6 +-- tests/snapshots.rs | 6 ++- 4 files changed, 77 insertions(+), 60 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ca4523fd3..819a4f15f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -342,6 +342,21 @@ fn should_pack_struct_member( } } +fn needs_array_length(ty: Handle, arena: &Arena) -> bool { + if let crate::TypeInner::Struct { ref members, .. } = arena[ty].inner { + if let Some(member) = members.last() { + if let crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } = arena[member.ty].inner + { + return true; + } + } + } + false +} + impl crate::StorageClass { /// Returns true for storage classes, for which the global /// variables are passed in function arguments. @@ -1488,8 +1503,12 @@ impl Writer { // follow-up with any global resources used let mut separate = !arguments.is_empty(); let fun_info = &context.mod_info[function]; + let mut supports_array_length = false; for (handle, var) in context.expression.module.global_variables.iter() { - if !fun_info[handle].is_empty() && var.class.needs_pass_through() { + if fun_info[handle].is_empty() { + continue; + } + if var.class.needs_pass_through() { let name = &self.names[&NameKey::GlobalVariable(handle)]; if separate { write!(self.out, ", ")?; @@ -1498,12 +1517,13 @@ impl Writer { } write!(self.out, "{}", name)?; } + supports_array_length |= + needs_array_length(var.ty, &context.expression.module.types); } - if !self.runtime_sized_buffers.is_empty() { + if supports_array_length { if separate { write!(self.out, ", ")?; } - write!(self.out, "_buffer_sizes")?; } @@ -1542,19 +1562,11 @@ impl Writer { { let mut indices = vec![]; - for (handle, gv) in module.global_variables.iter() { - if let crate::TypeInner::Struct { ref members, .. } = module.types[gv.ty].inner { - if let Some(member) = members.last() { - if let crate::TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } = module.types[member.ty].inner - { - let idx = handle.index(); - self.runtime_sized_buffers.insert(handle, idx); - indices.push(idx); - } - } + for (handle, var) in module.global_variables.iter() { + if needs_array_length(var.ty, &module.types) { + let idx = handle.index(); + self.runtime_sized_buffers.insert(handle, idx); + indices.push(idx); } } @@ -1845,9 +1857,13 @@ impl Writer { for (fun_handle, fun) in module.functions.iter() { let fun_info = &mod_info[fun_handle]; pass_through_globals.clear(); + let mut supports_array_length = false; for (handle, var) in module.global_variables.iter() { - if !fun_info[handle].is_empty() && var.class.needs_pass_through() { - pass_through_globals.push(handle); + if !fun_info[handle].is_empty() { + if var.class.needs_pass_through() { + pass_through_globals.push(handle); + } + supports_array_length |= needs_array_length(var.ty, &module.types); } } @@ -1882,7 +1898,7 @@ impl Writer { let separator = separate( !pass_through_globals.is_empty() || index + 1 != fun.arguments.len() - || !self.runtime_sized_buffers.is_empty(), + || supports_array_length, ); writeln!( self.out, @@ -1898,16 +1914,14 @@ impl Writer { usage: fun_info[handle], reference: true, }; - let separator = separate( - index + 1 != pass_through_globals.len() - || !self.runtime_sized_buffers.is_empty(), - ); + let separator = + separate(index + 1 != pass_through_globals.len() || supports_array_length); write!(self.out, "{}", INDENT)?; tyvar.try_fmt(&mut self.out)?; writeln!(self.out, "{}", separator)?; } - if !self.runtime_sized_buffers.is_empty() { + if supports_array_length { writeln!( self.out, "{}constant _mslBufferSizes& _buffer_sizes", @@ -1961,42 +1975,45 @@ impl Writer { for (ep_index, ep) in module.entry_points.iter().enumerate() { let fun = &ep.function; let fun_info = mod_info.get_entry_point(ep_index); + let mut ep_error = None; + let mut supports_array_length = false; + // skip this entry point if any global bindings are missing if !options.fake_missing_bindings { - if let Some(err) = module - .global_variables - .iter() - .find_map(|(var_handle, var)| { - if !fun_info[var_handle].is_empty() { - if let Some(ref br) = var.binding { - if let Err(e) = options.resolve_resource_binding(ep.stage, br) { - return Some(e); - } - } - if var.class == crate::StorageClass::PushConstant { - if let Err(e) = options.resolve_push_constants(ep.stage) { - return Some(e); - } - } - } - None - }) - { - info.entry_point_names.push(Err(err)); - continue; - } - if !self.runtime_sized_buffers.is_empty() { - if let Err(err) = options.resolve_sizes_buffer(ep.stage) { - info.entry_point_names.push(Err(err)); + for (var_handle, var) in module.global_variables.iter() { + if fun_info[var_handle].is_empty() { continue; } + if let Some(ref br) = var.binding { + if let Err(e) = options.resolve_resource_binding(ep.stage, br) { + ep_error = Some(e); + break; + } + } + if var.class == crate::StorageClass::PushConstant { + if let Err(e) = options.resolve_push_constants(ep.stage) { + ep_error = Some(e); + break; + } + } + supports_array_length |= needs_array_length(var.ty, &module.types); + } + if supports_array_length { + if let Err(err) = options.resolve_sizes_buffer(ep.stage) { + ep_error = Some(err); + } } } - writeln!(self.out)?; + if let Some(err) = ep_error { + info.entry_point_names.push(Err(err)); + continue; + } let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; info.entry_point_names.push(Ok(fun_name.clone())); + writeln!(self.out)?; + let stage_out_name = format!("{}Output", fun_name); let stage_in_name = format!("{}Input", fun_name); @@ -2212,7 +2229,7 @@ impl Writer { writeln!(self.out)?; } - if !self.runtime_sized_buffers.is_empty() { + if supports_array_length { // this is checked earlier let resolved = options.resolve_sizes_buffer(ep.stage).unwrap(); let separator = if module.global_variables.is_empty() { diff --git a/tests/out/collatz.msl b/tests/out/collatz.msl index 7342aa8ec..b33506022 100644 --- a/tests/out/collatz.msl +++ b/tests/out/collatz.msl @@ -11,8 +11,7 @@ struct PrimeIndices { }; metal::uint collatz_iterations( - metal::uint n_base, - constant _mslBufferSizes& _buffer_sizes + metal::uint n_base ) { metal::uint n; metal::uint i = 0u; @@ -36,9 +35,8 @@ struct main1Input { kernel void main1( metal::uint3 global_id [[thread_position_in_grid]] , device PrimeIndices& v_indices [[user(fake0)]] -, constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - metal::uint _e9 = collatz_iterations(v_indices.data[global_id.x], _buffer_sizes); + metal::uint _e9 = collatz_iterations(v_indices.data[global_id.x]); v_indices.data[global_id.x] = _e9; return; } diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index 17f1c82ea..ed9b5bc55 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -24,8 +24,7 @@ float fetch_shadow( metal::uint light_id, metal::float4 homogeneous_coords, metal::depth2d_array t_shadow, - metal::sampler sampler_shadow, - constant _mslBufferSizes& _buffer_sizes + metal::sampler sampler_shadow ) { if (homogeneous_coords.w <= 0.0) { return 1.0; @@ -47,7 +46,6 @@ fragment fs_mainOutput fs_main( , constant Lights& s_lights [[user(fake0)]] , metal::depth2d_array t_shadow [[user(fake0)]] , metal::sampler sampler_shadow [[user(fake0)]] -, constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; @@ -63,7 +61,7 @@ fragment fs_mainOutput fs_main( break; } Light _e21 = s_lights.data[i]; - float _e25 = fetch_shadow(i, _e21.proj * position, t_shadow, sampler_shadow, _buffer_sizes); + float _e25 = fetch_shadow(i, _e21.proj * position, t_shadow, sampler_shadow); color1 = color1 + ((_e25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(_e21.pos.xyz - position.xyz)))) * _e21.color.xyz); } return fs_mainOutput { metal::float4(color1, 1.0) }; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 5fe0c2b45..8a85ee32c 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -303,7 +303,11 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { #[cfg(feature = "spv-in")] #[test] fn convert_spv_quad_vert() { - convert_spv("quad-vert", false, Targets::METAL | Targets::GLSL | Targets::WGSL); + convert_spv( + "quad-vert", + false, + Targets::METAL | Targets::GLSL | Targets::WGSL, + ); } #[cfg(feature = "spv-in")] From 5e5d64291d056fcd36ddf4fa0093f98b5b5da07c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Tal=C4=8D=C3=ADk?= Date: Thu, 13 May 2021 23:10:43 +0200 Subject: [PATCH 0820/2212] [spv-in] fix handling of break blocks (borrowed from Tint) --- src/front/spv/flow.rs | 144 ++++++++++++++++++++++++++---------------- 1 file changed, 91 insertions(+), 53 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 65f8ca4a4..19db91ffd 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -222,14 +222,13 @@ impl FlowGraph { begin_position, end, end_position, + depth, ..Default::default() }, ); - let mut construct = constructs[node_index]; - let parent = { - if let Some(parent) = constructs.parent(parent_index) { + if let Some(parent) = constructs.parent(node_index) { if constructs[parent].depth < depth { Some(constructs[parent]) } else { @@ -240,8 +239,8 @@ impl FlowGraph { } }; - construct.enclosing_loop = { - if construct.ty == ConstructType::Loop { + constructs[node_index].enclosing_loop = { + if constructs[node_index].ty == ConstructType::Loop { Some(node_index) } else if let Some(parent) = parent { parent.enclosing_loop @@ -250,8 +249,8 @@ impl FlowGraph { } }; - construct.enclosing_continue = { - if construct.ty == ConstructType::Continue { + constructs[node_index].enclosing_continue = { + if constructs[node_index].ty == ConstructType::Continue { Some(node_index) } else if let Some(parent) = parent { parent.enclosing_continue @@ -260,8 +259,11 @@ impl FlowGraph { } }; - construct.enclosing_loop_or_continue_or_switch = { - if construct.ty == ConstructType::Continue { + constructs[node_index].enclosing_loop_or_continue_or_switch = { + if constructs[node_index].ty == ConstructType::Loop + || constructs[node_index].ty == ConstructType::Continue + || constructs[node_index].ty == ConstructType::Case + { Some(node_index) } else if let Some(parent) = parent { parent.enclosing_loop_or_continue_or_switch @@ -287,10 +289,9 @@ impl FlowGraph { } } - let depth = self.constructs[top_construct_index].depth; - if let Some(merge) = self.flow[*block_index].merge { let merge_index = self.block_to_node[&merge.merge_block_id]; + let depth = self.constructs[top_construct_index].depth + 1; match self.flow[*block_index].ty { Some(ControlFlowNodeType::Loop) => { @@ -380,7 +381,7 @@ impl FlowGraph { } // 2. - // Classify Nodes/Edges as one of [Break, Continue, Back] + // Classify Nodes/Edges as one of [Break, Continue] for edge_index in self.flow.edge_indices() { let (node_source_index, node_target_index) = self.flow.edge_endpoints(edge_index).unwrap(); @@ -391,34 +392,52 @@ impl FlowGraph { continue; } - let mut target_incoming_edges = self - .flow - .neighbors_directed(node_target_index, Direction::Incoming) - .detach(); - while let Some((incoming_edge, incoming_source)) = - target_incoming_edges.next(&self.flow) - { - // Loop break, Switch Break - if self.flow[incoming_source].ty == Some(ControlFlowNodeType::Loop) - && self.flow[incoming_edge] == ControlFlowEdgeType::ForwardMerge - { - self.flow[node_source_index].ty = Some(ControlFlowNodeType::Break); - self.flow[edge_index] = ControlFlowEdgeType::LoopBreak; - } + let construct_index = self.flow[node_source_index].construct; + let header_index = self.constructs[construct_index].begin; - // Loop continue - if self.flow[incoming_edge] == ControlFlowEdgeType::ForwardContinue { - self.flow[node_source_index].ty = Some(ControlFlowNodeType::Continue); - self.flow[edge_index] = ControlFlowEdgeType::LoopContinue; + // Loop break/Switch break + if let Some(enclosing_construct_index) = + self.constructs[construct_index].enclosing_loop_or_continue_or_switch + { + let enclosing_construct = self.constructs[enclosing_construct_index]; + let breakable_header = &self.flow[enclosing_construct.begin]; + + if let Some(merge_instruction) = breakable_header.merge { + let merge_node_index = self.block_to_node[&merge_instruction.merge_block_id]; + if node_target_index == merge_node_index { + self.flow[node_source_index].ty = Some(ControlFlowNodeType::Break); + self.flow[edge_index] = if enclosing_construct.ty == ConstructType::Case { + ControlFlowEdgeType::SwitchBreak + } else { + ControlFlowEdgeType::LoopBreak + }; + continue; + } + } + } + + // Continue + if let Some(enclosing_construct_index) = self.constructs[construct_index].enclosing_loop + { + let loop_header = &self.flow[self.constructs[enclosing_construct_index].begin]; + + if let Some(continue_block_id) = + loop_header.merge.and_then(|merge| merge.continue_block_id) + { + if node_target_index == self.block_to_node[&continue_block_id] { + self.flow[node_source_index].ty = Some(ControlFlowNodeType::Continue); + self.flow[edge_index] = ControlFlowEdgeType::LoopContinue; + continue; + } } } // If break - let construct_index = self.flow[node_source_index].construct; - let header_index = self.constructs[construct_index].begin; - if let Some(merge) = self.flow[header_index].merge { - if self.flow[node_target_index].id == merge.merge_block_id { + if let Some(merge_instruction) = self.flow[header_index].merge { + if node_target_index == self.block_to_node[&merge_instruction.merge_block_id] { + self.flow[node_source_index].ty = Some(ControlFlowNodeType::Break); self.flow[edge_index] = ControlFlowEdgeType::IfBreak; + continue; } } } @@ -747,25 +766,43 @@ impl FlowGraph { let false_edge = self.flow[self.flow.find_edge(node_index, false_node_id).unwrap()]; - if true_edge == ControlFlowEdgeType::LoopBreak { + if true_edge == ControlFlowEdgeType::LoopBreak + || true_edge == ControlFlowEdgeType::IfBreak + { result.push(crate::Statement::If { condition, - accept: vec![crate::Statement::Break], + accept: if true_edge == ControlFlowEdgeType::LoopBreak { + vec![crate::Statement::Break] + } else { + vec![] + }, reject: self.convert_to_naga_traverse(false_node_id, stop_nodes)?, }); - } else if false_edge == ControlFlowEdgeType::LoopBreak { + } else if false_edge == ControlFlowEdgeType::LoopBreak + || false_edge == ControlFlowEdgeType::IfBreak + { result.push(crate::Statement::If { condition, accept: self.convert_to_naga_traverse(true_node_id, stop_nodes)?, - reject: vec![crate::Statement::Break], + reject: if false_edge == ControlFlowEdgeType::LoopBreak { + vec![crate::Statement::Break] + } else { + vec![] + }, }); } else { return Err(Error::InvalidEdgeClassification); } } - Terminator::Branch { .. } => { - result.push(crate::Statement::Break); - } + Terminator::Branch { target_id } => { + let target_index = self.block_to_node[&target_id]; + + let edge = self.flow[self.flow.find_edge(node_index, target_index).unwrap()]; + + if edge == ControlFlowEdgeType::LoopBreak { + result.push(crate::Statement::Break); + } + }, _ => return Err(Error::InvalidTerminator), }; Ok(result) @@ -823,9 +860,10 @@ impl FlowGraph { }; writeln!( output, - "{} [ label = \"%{} {:?}\" shape={} ]", + "{} [ label = \"%{}({}) {:?}\" shape={} ]", node_index.index(), node.id, + node_index.index(), node.ty, shape )?; @@ -842,11 +880,11 @@ impl FlowGraph { ControlFlowEdgeType::ForwardMerge => "style=dotted", ControlFlowEdgeType::ForwardContinue => "color=green", ControlFlowEdgeType::Back => "style=dashed", - ControlFlowEdgeType::LoopBreak => "color=yellow", ControlFlowEdgeType::LoopContinue => "color=green", ControlFlowEdgeType::IfTrue => "color=blue", ControlFlowEdgeType::IfFalse => "color=red", - ControlFlowEdgeType::SwitchBreak => "color=yellow", + ControlFlowEdgeType::LoopBreak => "color=orange", + ControlFlowEdgeType::SwitchBreak => "color=tomato", ControlFlowEdgeType::IfBreak => "color=yellow", ControlFlowEdgeType::CaseFallThrough => "style=dotted", }; @@ -916,11 +954,6 @@ pub(super) enum ControlFlowEdgeType { /// Can only be to a ControlFlowNodeType::Loop. Back, - /// An edge from a node to the merge block of the nearest enclosing loop, where - /// there is no intervening switch. - /// The source block is a "break block" as defined by SPIR-V. - LoopBreak, - /// An edge from a node in a loop body to the associated continue target, where /// there are no other intervening loops or switches. /// The source block is a "continue block" as defined by SPIR-V. @@ -932,14 +965,19 @@ pub(super) enum ControlFlowEdgeType { /// An edge from a node with OpBranchConditional to the block of false operand. IfFalse, + /// An edge from a node to the merge block of the nearest enclosing loop, where + /// there is no intervening switch. + /// The source block is a "break block" as defined by SPIR-V. + LoopBreak, + /// An edge from a node to the merge block of the nearest enclosing switch, /// where there is no intervening loop. SwitchBreak, - // An edge from a node to the merge block of the nearest enclosing structured - // construct, but which is neither a kSwitchBreak or a kLoopBreak. - // This can only occur for an "if" selection, i.e. where the selection - // header ends in OpBranchConditional. + /// An edge from a node to the merge block of the nearest enclosing structured + /// construct, but which is neither a SwitchBreak or a LoopBreak. + /// This can only occur for an "if" selection, i.e. where the selection + /// header ends in OpBranchConditional. IfBreak, /// An edge from one switch case to the next sibling switch case. From f45d812266545db12e6ed5191d997d06957c644d Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 13 May 2021 10:21:43 -0700 Subject: [PATCH 0821/2212] [wgsl-in]: Move WGSL front end integration tests into a WGSL-specific file. This lets us reduce noise by removing a bunch of `#[cfg]` attributes. In the future, if we have tests for other front ends, we can create an `errors` subdirectory, but for now, we only have the WGSL tests, so we should keep things flat. --- tests/{errors.rs => wgsl-errors.rs} | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) rename tests/{errors.rs => wgsl-errors.rs} (91%) diff --git a/tests/errors.rs b/tests/wgsl-errors.rs similarity index 91% rename from tests/errors.rs rename to tests/wgsl-errors.rs index 9bfefc407..face95d91 100644 --- a/tests/errors.rs +++ b/tests/wgsl-errors.rs @@ -1,4 +1,6 @@ -#[cfg(feature = "wgsl-in")] +//! Tests for the WGSL front end. +#![cfg(feature = "wgsl-in")] + fn check(input: &str, snapshot: &str) { let output = naga::front::wgsl::parse_str(input) .expect_err("expected parser error") @@ -15,7 +17,6 @@ fn check(input: &str, snapshot: &str) { } } -#[cfg(feature = "wgsl-in")] #[test] fn function_without_identifier() { check( @@ -30,7 +31,6 @@ fn function_without_identifier() { ); } -#[cfg(feature = "wgsl-in")] #[test] fn invalid_integer() { check( @@ -45,7 +45,6 @@ fn invalid_integer() { ); } -#[cfg(feature = "wgsl-in")] #[test] fn invalid_float() { check( @@ -60,7 +59,6 @@ fn invalid_float() { ); } -#[cfg(feature = "wgsl-in")] #[test] fn invalid_scalar_width() { check( From 9c5f324de21867249900821ed6547badefac896e Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 13 May 2021 10:28:22 -0700 Subject: [PATCH 0822/2212] TypeInner::span: Tolerate bad array length constants for now. --- src/proc/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 69b59c171..49bab5528 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -94,7 +94,8 @@ impl super::TypeInner { } => { let count = match size { super::ArraySize::Constant(handle) => { - constants[handle].to_array_length().unwrap() + // Bad array lengths will be caught during validation. + constants[handle].to_array_length().unwrap_or(1) } // A dynamically-sized array has to have at least one element super::ArraySize::Dynamic => 1, From 057d03ad86f18e3bb3866b20901d8d4e892dd3d6 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 13 May 2021 10:29:03 -0700 Subject: [PATCH 0823/2212] [wgsl-in]: Add tests for array and struct validation. --- tests/wgsl-errors.rs | 101 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index face95d91..5a03f4785 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -74,3 +74,104 @@ fn invalid_scalar_width() { "###, ); } + +macro_rules! check_validation_error { + ( $( $source:literal ),* : $pattern:pat ) => { + $( + let error = validation_error($source); + if ! matches!(error, $pattern) { + eprintln!("validation error does not match pattern:\n\ + {:?}\n\ + \n\ + expected match for pattern:\n\ + {}", + error, + stringify!($pattern)); + panic!("validation error does not match pattern"); + } + )* + } +} + +fn validation_error(source: &str) -> Result { + let module = naga::front::wgsl::parse_str(source).expect("expected WGSL parse to succeed"); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::empty(), + ) + .validate(&module) +} + +#[test] +fn invalid_arrays() { + check_validation_error! { + "type Bad = array, 4>;", + "type Bad = array;", + "type Bad = array, 4>;": + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::InvalidArrayBaseType(_), + .. + }) + } + + check_validation_error! { + r#" + [[block]] struct Block { value: f32; }; + type Bad = array; + "#: + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::NestedBlock, + .. + }) + } + + check_validation_error! { + r#" + type Bad = [[stride(2)]] array; + "#: + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::InsufficientArrayStride { stride: 2, base_size: 4 }, + .. + }) + } + + check_validation_error! { + "type Bad = array;", + r#" + let length: f32 = 2.718; + type Bad = array; + "#: + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::InvalidArraySizeConstant(_), + .. + }) + } +} + +#[test] +fn invalid_structs() { + check_validation_error! { + "struct Bad { data: sampler; };", + "struct Bad { data: texture_2d; };": + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::InvalidData(_), + .. + }) + } + + check_validation_error! { + "[[block]] struct Bad { data: ptr; };": + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::InvalidBlockType(_), + .. + }) + } + + check_validation_error! { + "struct Bad { data: array; other: f32; };": + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::InvalidDynamicArray(_, _), + .. + }) + } +} From 418e71281eed883e9bebc49d8cfb371ed897c18a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 14 May 2021 09:45:37 -0400 Subject: [PATCH 0824/2212] Derivative tests --- src/front/spv/flow.rs | 5 +++-- src/front/wgsl/conv.rs | 2 +- tests/in/standard.param.ron | 5 +++++ tests/in/standard.wgsl | 9 +++++++++ tests/out/standard.Fragment.glsl | 15 +++++++++++++++ tests/out/standard.msl | 17 +++++++++++++++++ tests/out/standard.spvasm | 32 ++++++++++++++++++++++++++++++++ tests/snapshots.rs | 1 + 8 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 tests/in/standard.param.ron create mode 100644 tests/in/standard.wgsl create mode 100644 tests/out/standard.Fragment.glsl create mode 100644 tests/out/standard.msl create mode 100644 tests/out/standard.spvasm diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 19db91ffd..e9dd5b835 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -797,12 +797,13 @@ impl FlowGraph { Terminator::Branch { target_id } => { let target_index = self.block_to_node[&target_id]; - let edge = self.flow[self.flow.find_edge(node_index, target_index).unwrap()]; + let edge = + self.flow[self.flow.find_edge(node_index, target_index).unwrap()]; if edge == ControlFlowEdgeType::LoopBreak { result.push(crate::Statement::Break); } - }, + } _ => return Err(Error::InvalidTerminator), }; Ok(result) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index f9b79290d..7187bd560 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -118,7 +118,7 @@ pub fn map_derivative_axis(word: &str) -> Option { match word { "dpdx" => Some(crate::DerivativeAxis::X), "dpdy" => Some(crate::DerivativeAxis::Y), - "dwidth" => Some(crate::DerivativeAxis::Width), + "fwidth" => Some(crate::DerivativeAxis::Width), _ => None, } } diff --git a/tests/in/standard.param.ron b/tests/in/standard.param.ron new file mode 100644 index 000000000..1eb59329e --- /dev/null +++ b/tests/in/standard.param.ron @@ -0,0 +1,5 @@ +( + spv_version: (1, 0), + spv_capabilities: [ Shader ], + spv_adjust_coordinate_space: false, +) diff --git a/tests/in/standard.wgsl b/tests/in/standard.wgsl new file mode 100644 index 000000000..a9db49e78 --- /dev/null +++ b/tests/in/standard.wgsl @@ -0,0 +1,9 @@ +// Standard functions. + +[[stage(fragment)]] +fn derivatives([[builtin(position)]] foo: vec4) -> [[location(0)]] vec4 { + let x = dpdx(foo); + let y = dpdy(foo); + let z = fwidth(foo); + return (x + y) * z; +} diff --git a/tests/out/standard.Fragment.glsl b/tests/out/standard.Fragment.glsl new file mode 100644 index 000000000..d39147bfb --- /dev/null +++ b/tests/out/standard.Fragment.glsl @@ -0,0 +1,15 @@ +#version 310 es + +precision highp float; + +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + vec4 foo = gl_FragCoord; + vec4 _expr1 = dFdx(foo); + vec4 _expr2 = dFdy(foo); + vec4 _expr3 = fwidth(foo); + _fs2p_location0 = ((_expr1 + _expr2) * _expr3); + return; +} + diff --git a/tests/out/standard.msl b/tests/out/standard.msl new file mode 100644 index 000000000..3909bef27 --- /dev/null +++ b/tests/out/standard.msl @@ -0,0 +1,17 @@ +#include +#include + + +struct derivativesInput { +}; +struct derivativesOutput { + metal::float4 member [[color(0)]]; +}; +fragment derivativesOutput derivatives( + metal::float4 foo [[position]] +) { + metal::float4 _e1 = metal::dfdx(foo); + metal::float4 _e2 = metal::dfdy(foo); + metal::float4 _e3 = metal::fwidth(foo); + return derivativesOutput { (_e1 + _e2) * _e3 }; +} diff --git a/tests/out/standard.spvasm b/tests/out/standard.spvasm new file mode 100644 index 000000000..a8c5d0693 --- /dev/null +++ b/tests/out/standard.spvasm @@ -0,0 +1,32 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 19 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %11 "derivatives" %6 %9 +OpExecutionMode %11 OriginUpperLeft +OpDecorate %6 BuiltIn FragCoord +OpDecorate %9 Location 0 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%7 = OpTypePointer Input %3 +%6 = OpVariable %7 Input +%10 = OpTypePointer Output %3 +%9 = OpVariable %10 Output +%12 = OpTypeFunction %2 +%11 = OpFunction %2 None %12 +%5 = OpLabel +%8 = OpLoad %3 %6 +OpBranch %13 +%13 = OpLabel +%14 = OpDPdx %3 %8 +%15 = OpDPdy %3 %8 +%16 = OpFwidth %3 %8 +%17 = OpFAdd %3 %14 %15 +%18 = OpFMul %3 %17 %16 +OpStore %9 %18 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 8a85ee32c..fb4bb824f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -266,6 +266,7 @@ fn convert_wgsl() { "control-flow", Targets::SPIRV | Targets::METAL | Targets::GLSL, ), + ("standard", Targets::SPIRV | Targets::METAL | Targets::GLSL), ]; for &(name, targets) in inputs.iter() { From 77a20d00176cd88fd7508e26a84812dc8dda12f7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 14 May 2021 10:21:55 -0400 Subject: [PATCH 0825/2212] Update CHANGELOG for v0.4.1 --- CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 112921fae..f68bf07e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Change Log +### v0.4.1 (2021-05-14) + - numerous additions and improvements to SPIR-V frontend: + - int8, in16, int64 + - null constant initializers for structs and matrices + - `OpArrayLength`, `OpCopyMemory`, `OpInBoundsAccessChain`, `OpLogicalXxxEqual` + - outer product + - fix struct size alignment + - initialize built-ins with default values + - fix read-only decorations on struct members + - fix struct size alignment in WGSL + - fix `fwidth` in WGSL + - fix scalars arrays in GLSL backend + ## v0.4 (2021-04-29) - development release for wgpu-0.8 - API: From 5958f9848983744681dc4f0cadf204ad531add08 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 13 May 2021 22:35:08 +0300 Subject: [PATCH 0826/2212] [wgsl-out] Enable snapshot testing for wgsl-in image test --- src/back/wgsl/writer.rs | 157 ++++++++++++++++++++++++++++++++-------- tests/out/image.wgsl | 31 ++++++++ tests/out/quad.wgsl | 6 +- tests/snapshots.rs | 2 +- 4 files changed, 161 insertions(+), 35 deletions(-) create mode 100644 tests/out/image.wgsl diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index f906d3fba..5f634badc 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -6,8 +6,8 @@ use crate::{ proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, Arena, ArraySize, Binding, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, - ImageClass, ImageDimension, Interpolation, Module, Sampling, ScalarKind, ScalarValue, - ShaderStage, Statement, StorageFormat, StructLevel, StructMember, Type, TypeInner, + ImageClass, ImageDimension, Interpolation, Module, SampleLevel, Sampling, ScalarKind, + ScalarValue, ShaderStage, Statement, StorageFormat, StructLevel, StructMember, Type, TypeInner, }; use bit_set::BitSet; use std::fmt::Write; @@ -471,7 +471,7 @@ impl Writer { let (class_str, multisampled_str, scalar_str) = match class { ImageClass::Sampled { kind, multi } => ( "", - if multi { "multisampled" } else { "" }, + if multi { "multisampled_" } else { "" }, format!("<{}>", scalar_kind_str(kind)), ), ImageClass::Depth => ("depth", "", String::from("")), @@ -606,7 +606,7 @@ impl Writer { self.write_expr(module, value, func_ctx)?; writeln!(self.out, ";")? } - crate::Statement::Call { + Statement::Call { function, ref arguments, result, @@ -628,6 +628,25 @@ impl Writer { } writeln!(self.out, ");")? } + Statement::ImageStore { + image, + coordinate, + array_index, + value, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "textureStore(")?; + self.write_expr(module, image, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, coordinate, func_ctx)?; + if let Some(array_index_expr) = array_index { + write!(self.out, ", ")?; + self.write_expr(module, array_index_expr, func_ctx)?; + } + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ");")?; + } _ => { return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))); } @@ -769,11 +788,11 @@ impl Writer { write!(self.out, "{}", name)?; } Expression::Binary { op, left, right } => { + write!(self.out, "(")?; self.write_expr(module, left, func_ctx)?; - - write!(self.out, " {} ", binary_operation_str(op),)?; - + write!(self.out, " {} ", binary_operation_str(op))?; self.write_expr(module, right, func_ctx)?; + write!(self.out, ")")?; } // TODO: copy-paste from glsl-out Expression::Access { base, index } => { @@ -819,28 +838,97 @@ impl Writer { image, sampler, coordinate, - array_index: _, - offset: _, + array_index, + offset, level, - depth_ref: _, + depth_ref, } => { - // TODO: other texture functions - // TODO: comments - let fun_name = match level { - crate::SampleLevel::Auto => "textureSample", - _ => { - return Err(Error::Unimplemented(format!( - "expression_imagesample_level {:?}", - level - ))); + let texture_function = if depth_ref.is_some() { + "textureSampleCompare" + } else { + match level { + SampleLevel::Auto | SampleLevel::Zero => "textureSample", + SampleLevel::Exact(_) => "textureSampleLevel", + SampleLevel::Bias(_) => "textureSampleBias", + SampleLevel::Gradient { .. } => "textureSampleGrad", } }; - write!(self.out, "{}(", fun_name)?; + + write!(self.out, "{}(", texture_function)?; self.write_expr(module, image, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, sampler, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, coordinate, func_ctx)?; + + if let Some(array_index) = array_index { + write!(self.out, ", ")?; + self.write_expr(module, array_index, func_ctx)?; + } + + if let SampleLevel::Bias(expr) = level { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + + if let Some(depth_ref) = depth_ref { + write!(self.out, ", ")?; + self.write_expr(module, depth_ref, func_ctx)?; + } + + if let SampleLevel::Gradient { x, y } = level { + write!(self.out, ", ")?; + self.write_expr(module, x, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, y, func_ctx)?; + } + + if let SampleLevel::Exact(expr) = level { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + + if let Some(offset) = offset { + write!(self.out, ", ")?; + self.write_constant(module, offset)?; + } + + write!(self.out, ")")?; + } + Expression::ImageQuery { image, query } => { + let texture_function = match query { + crate::ImageQuery::Size { .. } => "textureDimensions", + crate::ImageQuery::NumLevels => "textureNumLevels", + crate::ImageQuery::NumLayers => "textureNumLayers", + crate::ImageQuery::NumSamples => "textureNumSamples", + }; + + write!(self.out, "{}(", texture_function)?; + self.write_expr(module, image, func_ctx)?; + if let crate::ImageQuery::Size { level: Some(level) } = query { + write!(self.out, ", ")?; + self.write_expr(module, level, func_ctx)?; + }; + write!(self.out, ")")?; + } + Expression::ImageLoad { + image, + coordinate, + array_index, + index, + } => { + write!(self.out, "textureLoad(")?; + self.write_expr(module, image, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, coordinate, func_ctx)?; + if let Some(array_index) = array_index { + write!(self.out, ", ")?; + self.write_expr(module, array_index, func_ctx)?; + } + if let Some(index) = index { + write!(self.out, ", ")?; + self.write_expr(module, index, func_ctx)?; + } write!(self.out, ")")?; } // TODO: copy-paste from msl-out @@ -848,18 +936,26 @@ impl Writer { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; } - Expression::As { - expr, - kind, - convert: _, //TODO: - } => { + Expression::As { expr, kind, .. } => { let inner = func_ctx.info[expr].ty.inner_with(&module.types); - let op = match *inner { + match *inner { TypeInner::Matrix { columns, rows, .. } => { - format!("mat{}x{}", vector_size_str(columns), vector_size_str(rows)) + write!( + self.out, + "mat{}x{}", + vector_size_str(columns), + vector_size_str(rows) + )?; } - TypeInner::Vector { size, .. } => format!("vec{}", vector_size_str(size)), - TypeInner::Scalar { kind, .. } => String::from(scalar_kind_str(kind)), + TypeInner::Vector { size, .. } => { + write!( + self.out, + "vec{}<{}>", + vector_size_str(size), + scalar_kind_str(kind) + )?; + } + TypeInner::Scalar { .. } => write!(self.out, "{}", scalar_kind_str(kind))?, _ => { return Err(Error::Unimplemented(format!( "write_expr expression::as {:?}", @@ -867,8 +963,7 @@ impl Writer { ))); } }; - let scalar = scalar_kind_str(kind); - write!(self.out, "{}<{}>(", op, scalar)?; + write!(self.out, "(")?; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")?; } diff --git a/tests/out/image.wgsl b/tests/out/image.wgsl new file mode 100644 index 000000000..4fd7ef9a3 --- /dev/null +++ b/tests/out/image.wgsl @@ -0,0 +1,31 @@ +[[group(0), binding(1)]] +var image_src: [[access(read)]] texture_storage_2d; +[[group(0), binding(2)]] +var image_dst: [[access(write)]] texture_storage_1d; +[[group(0), binding(0)]] +var image_1d: texture_1d; +[[group(0), binding(1)]] +var image_2d: texture_2d; +[[group(0), binding(2)]] +var image_2d_array: texture_2d_array; +[[group(0), binding(3)]] +var image_cube: texture_cube; +[[group(0), binding(4)]] +var image_cube_array: texture_cube_array; +[[group(0), binding(5)]] +var image_3d: texture_3d; +[[group(0), binding(6)]] +var image_aa: texture_multisampled_2d; + +[[stage(compute), workgroup_size(16, 1, 1)]] +fn main([[builtin(local_invocation_id)]] local_id: vec3) { + let _e10: vec2 = ((textureDimensions(image_src) * vec2(local_id.xy)) % vec2(10, 20)); + let _e11: vec4 = textureLoad(image_src, _e10); + textureStore(image_dst, _e10[0], _e11); + return; +} + +[[stage(vertex)]] +fn queries() -> [[builtin(position)]] vec4 { + return vec4(f32(((((((((((((((((((textureDimensions(image_1d) + textureDimensions(image_2d)[1]) + textureDimensions(image_2d, 1)[1]) + textureDimensions(image_2d_array)[1]) + textureDimensions(image_2d_array, 1)[1]) + textureNumLayers(image_2d_array)) + textureDimensions(image_cube)[1]) + textureDimensions(image_cube, 1)[1]) + textureDimensions(image_cube_array)[1]) + textureDimensions(image_cube_array, 1)[1]) + textureNumLayers(image_cube_array)) + textureDimensions(image_3d)[2]) + textureDimensions(image_3d, 1)[2]) + textureNumSamples(image_aa)) + textureNumLevels(image_2d)) + textureNumLevels(image_2d_array)) + textureNumLevels(image_3d)) + textureNumLevels(image_cube)) + textureNumLevels(image_cube_array)))); +} diff --git a/tests/out/quad.wgsl b/tests/out/quad.wgsl index fe924dc76..43f161438 100644 --- a/tests/out/quad.wgsl +++ b/tests/out/quad.wgsl @@ -12,14 +12,14 @@ var u_sampler: sampler; [[stage(vertex)]] fn main([[location(0)]] pos: vec2, [[location(1)]] uv1: vec2) -> VertexOutput { - return VertexOutput(uv1, vec4(c_scale * pos, 0.0, 1.0)); + return VertexOutput(uv1, vec4((c_scale * pos), 0.0, 1.0)); } [[stage(fragment)]] fn main1([[location(0), interpolate(perspective)]] uv2: vec2) -> [[location(0)]] vec4 { let _e4: vec4 = textureSample(u_texture, u_sampler, uv2); - if (_e4[3] == 0.0) { + if ((_e4[3] == 0.0)) { discard; } - return _e4[3] * _e4; + return (_e4[3] * _e4); } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index fb4bb824f..37a49478f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -254,7 +254,7 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS, ), ("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL), - ("image", Targets::SPIRV | Targets::METAL), + ("image", Targets::SPIRV | Targets::METAL | Targets::WGSL), ("extra", Targets::SPIRV | Targets::METAL), ("operators", Targets::SPIRV | Targets::METAL | Targets::GLSL), ( From 6efe347e9083f215aa6cbdb2aa8839f07d871fc6 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 12 May 2021 21:09:03 +0300 Subject: [PATCH 0827/2212] [wgsl-out] Implement all math functions. Rename entry point function based on stage. Rename entry point output struct. --- src/back/wgsl/mod.rs | 2 + src/back/wgsl/writer.rs | 107 ++++++++++++++++++++++++++++++++------- tests/out/quad-vert.wgsl | 6 +-- 3 files changed, 95 insertions(+), 20 deletions(-) diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index 1ca762af9..6408b5125 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -13,6 +13,8 @@ pub enum Error { Custom(String), #[error("{0}")] Unimplemented(String), // TODO: Error used only during development + #[error("Unsupported math function: {0:?}")] + UnsupportedMathFunction(crate::MathFunction), } pub fn write_string( diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 5f634badc..4d7701d65 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -61,6 +61,7 @@ pub struct Writer { names: FastHashMap, namer: Namer, named_expressions: BitSet, + ep_results: Vec<(ShaderStage, Handle)>, } impl Writer { @@ -70,6 +71,7 @@ impl Writer { names: FastHashMap::default(), namer: Namer::default(), named_expressions: BitSet::new(), + ep_results: vec![], } } @@ -82,6 +84,13 @@ impl Writer { pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { self.reset(module); + // Save all ep result types + for (_, ep) in module.entry_points.iter().enumerate() { + if let Some(ref result) = ep.function.result { + self.ep_results.push((ep.stage, result.ty)); + } + } + // Write all structs for (handle, ty) in module.types.iter() { if let TypeInner::Struct { @@ -173,6 +182,29 @@ impl Writer { Ok(()) } + /// Helper method used to write stuct name + /// + /// # Notes + /// Adds no trailing or leading whitespace + fn write_struct_name(&mut self, module: &Module, handle: Handle) -> BackendResult { + if module.types[handle].name.is_none() { + if let Some(&(stage, _)) = self.ep_results.iter().find(|&&(_, ty)| ty == handle) { + let name = match stage { + ShaderStage::Compute => "ComputeOutput", + ShaderStage::Fragment => "FragmentOutput", + ShaderStage::Vertex => "VertexOutput", + }; + + write!(self.out, "{}", name)?; + return Ok(()); + } + } + + write!(self.out, "{}", self.names[&NameKey::Type(handle)])?; + + Ok(()) + } + /// Helper method used to write structs /// https://gpuweb.github.io/gpuweb/wgsl/#functions /// @@ -222,14 +254,11 @@ impl Writer { // Write function return type if let Some(ref result) = func.result { + write!(self.out, " -> ")?; if let Some(ref binding) = result.binding { - write!(self.out, " -> ")?; self.write_attributes(&map_binding_to_attribute(binding), true)?; - self.write_type(module, result.ty)?; - } else { - let struct_name = &self.names[&NameKey::Type(result.ty)].clone(); - write!(self.out, " -> {}", struct_name)?; } + self.write_type(module, result.ty)?; } write!(self.out, " {{")?; @@ -383,8 +412,10 @@ impl Writer { self.write_attributes(&[Attribute::Block], false)?; writeln!(self.out)?; } - let name = &self.names[&NameKey::Type(handle)].clone(); - write!(self.out, "struct {} {{", name)?; + + write!(self.out, "struct ")?; + self.write_struct_name(module, handle)?; + write!(self.out, " {{")?; writeln!(self.out)?; for (index, member) in members.iter().enumerate() { // Skip struct member with unsupported built in @@ -431,12 +462,7 @@ impl Writer { fn write_type(&mut self, module: &Module, ty: Handle) -> BackendResult { let inner = &module.types[ty].inner; match *inner { - TypeInner::Struct { .. } => { - // Get the struct name - let name = &self.names[&NameKey::Type(ty)]; - write!(self.out, "{}", name)?; - return Ok(()); - } + TypeInner::Struct { .. } => self.write_struct_name(module, ty)?, ref other => self.write_value_type(module, other)?, } @@ -1010,13 +1036,60 @@ impl Writer { use crate::MathFunction as Mf; let fun_name = match fun { + Mf::Abs => "abs", + Mf::Min => "min", + Mf::Max => "max", + Mf::Clamp => "clamp", + // trigonometry + Mf::Cos => "cos", + Mf::Cosh => "cosh", + Mf::Sin => "sin", + Mf::Sinh => "sinh", + Mf::Tan => "tan", + Mf::Tanh => "tanh", + Mf::Acos => "acos", + Mf::Asin => "asin", + Mf::Atan => "atan", + Mf::Atan2 => "atan2", + // decomposition + Mf::Ceil => "ceil", + Mf::Floor => "floor", + Mf::Round => "round", + Mf::Fract => "fract", + Mf::Trunc => "trunc", + Mf::Modf => "modf", + Mf::Frexp => "frexp", + Mf::Ldexp => "ldexp", + // exponent + Mf::Exp => "exp", + Mf::Exp2 => "exp2", + Mf::Log => "log", + Mf::Log2 => "log2", + Mf::Pow => "pow", + // geometry + Mf::Dot => "dot", + Mf::Outer => "outerProduct", + Mf::Cross => "cross", + Mf::Distance => "distance", Mf::Length => "length", + Mf::Normalize => "normalize", + Mf::FaceForward => "faceForward", + Mf::Reflect => "reflect", + // computational + Mf::Sign => "sign", + Mf::Fma => "fma", Mf::Mix => "mix", + Mf::Step => "step", + Mf::SmoothStep => "smoothStep", + Mf::Sqrt => "sqrt", + Mf::InverseSqrt => "inverseSqrt", + Mf::Transpose => "transpose", + Mf::Determinant => "determinant", + // bits + Mf::CountOneBits => "countOneBits", + Mf::ReverseBits => "reverseBits", _ => { - return Err(Error::Unimplemented(format!( - "write_expr Math func {:?}", - fun - ))); + return Err(Error::UnsupportedMathFunction(fun)); } }; diff --git a/tests/out/quad-vert.wgsl b/tests/out/quad-vert.wgsl index 66a173b4c..579fe73e5 100644 --- a/tests/out/quad-vert.wgsl +++ b/tests/out/quad-vert.wgsl @@ -3,7 +3,7 @@ struct gl_PerVertex { [[builtin(position)]] gl_Position: vec4; }; -struct type10 { +struct VertexOutput { [[location(0), interpolate(perspective)]] member: vec2; [[builtin(position)]] gl_Position1: vec4; }; @@ -21,9 +21,9 @@ fn main() { } [[stage(vertex)]] -fn main1([[location(1)]] a_uv1: vec2, [[location(0)]] a_pos1: vec2) -> type10 { +fn main1([[location(1)]] a_uv1: vec2, [[location(0)]] a_pos1: vec2) -> VertexOutput { a_uv = a_uv1; a_pos = a_pos1; main(); - return type10(v_uv, perVertexStruct.gl_Position); + return VertexOutput(v_uv, perVertexStruct.gl_Position); } From b191c982ec146f97d3f495f7a8b7af648c189f0d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 16 May 2021 00:46:46 -0400 Subject: [PATCH 0828/2212] Remove alignment from struct IR --- src/back/glsl/mod.rs | 5 +- src/back/spv/writer.rs | 4 +- src/back/wgsl/writer.rs | 9 +- src/front/glsl/parser.rs | 22 +---- src/front/spv/function.rs | 4 +- src/front/spv/mod.rs | 42 +++----- src/front/wgsl/mod.rs | 26 +++-- src/lib.rs | 17 +--- .../wgsl/layout.rs => proc/layouter.rs} | 81 ++++++++++----- src/proc/mod.rs | 2 + src/valid/interface.rs | 9 +- src/valid/mod.rs | 6 ++ src/valid/type.rs | 99 +++++++------------ tests/out/collatz.ron | 2 +- tests/out/shadow.ron | 8 +- tests/wgsl-errors.rs | 2 +- 16 files changed, 152 insertions(+), 186 deletions(-) rename src/{front/wgsl/layout.rs => proc/layouter.rs} (58%) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ef2f14933..a9fe8ce04 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -663,7 +663,7 @@ impl<'a, W: Write> Writer<'a, W> { // glsl has no pointer types so just write types as normal and loads are skipped TypeInner::Pointer { base, .. } => self.write_type(base), TypeInner::Struct { - level: crate::StructLevel::Root, + top_level: true, ref members, span: _, } => self.write_struct(true, ty, members), @@ -743,8 +743,7 @@ impl<'a, W: Write> Writer<'a, W> { if let Some(storage_class) = glsl_storage_class(global.class) { write!(self.out, "{} ", storage_class)?; } else if let TypeInner::Struct { - level: crate::StructLevel::Root, - .. + top_level: true, .. } = self.module.types[global.ty].inner { write!(self.out, "struct ")?; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 894466658..763cd0a6a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -916,11 +916,11 @@ impl Writer { } } crate::TypeInner::Struct { - ref level, + top_level, ref members, span: _, } => { - if let crate::StructLevel::Root = *level { + if top_level { self.decorate(id, Decoration::Block, &[]); } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 4d7701d65..19ba6df22 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -7,7 +7,7 @@ use crate::{ valid::{FunctionInfo, ModuleInfo}, Arena, ArraySize, Binding, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, ImageDimension, Interpolation, Module, SampleLevel, Sampling, ScalarKind, - ScalarValue, ShaderStage, Statement, StorageFormat, StructLevel, StructMember, Type, TypeInner, + ScalarValue, ShaderStage, Statement, StorageFormat, StructMember, Type, TypeInner, }; use bit_set::BitSet; use std::fmt::Write; @@ -94,11 +94,12 @@ impl Writer { // Write all structs for (handle, ty) in module.types.iter() { if let TypeInner::Struct { - level, ref members, .. + top_level, + ref members, + .. } = ty.inner { - let block = level == StructLevel::Root; - self.write_struct(module, handle, block, members)?; + self.write_struct(module, handle, top_level, members)?; writeln!(self.out)?; } } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 3f26863ab..8b46b7c66 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -521,46 +521,34 @@ pomelo! { if i.1 == "gl_PerVertex" { None } else { - let level = if t.is_empty() { - //TODO - crate::StructLevel::Normal { alignment: crate::Alignment::new(1).unwrap() } - } else { - crate::StructLevel::Root - }; Some(VarDeclaration { - type_qualifiers: t, ids_initializers: vec![(None, None)], ty: extra.module.types.fetch_or_append(Type{ name: Some(i.1), inner: TypeInner::Struct { - level, + top_level: !t.is_empty(), members: sdl, span: 0, //TODO }, }), + type_qualifiers: t, }) } } declaration ::= type_qualifier(t) Identifier(i1) LeftBrace struct_declaration_list(sdl) RightBrace Identifier(i2) Semicolon { - let level = if t.is_empty() { - //TODO - crate::StructLevel::Normal { alignment: crate::Alignment::new(1).unwrap() } - } else { - crate::StructLevel::Root - }; Some(VarDeclaration { - type_qualifiers: t, ids_initializers: vec![(Some(i2.1), None)], ty: extra.module.types.fetch_or_append(Type{ name: Some(i1.1), inner: TypeInner::Struct { - level, + top_level: !t.is_empty(), members: sdl, span: 0, //TODO }, }), + type_qualifiers: t, }) } @@ -761,7 +749,7 @@ pomelo! { Type{ name: Some(i.1), inner: TypeInner::Struct { - level: crate::StructLevel::Normal { alignment: crate::Alignment::new(1).unwrap() }, + top_level: false, members: vec![], span: 0, } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 449146e48..47dd75b19 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -353,9 +353,7 @@ impl> super::Parser { let ty = module.types.append(crate::Type { name: None, inner: crate::TypeInner::Struct { - level: crate::StructLevel::Normal { - alignment: crate::Alignment::new(1).unwrap(), - }, + top_level: false, members, span: 0xFFFF, // shouldn't matter }, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 7b62bce56..0a1e3113d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -40,6 +40,7 @@ use function::*; use crate::{ arena::{Arena, Handle}, + proc::{Alignment, Layouter}, FastHashMap, }; @@ -192,28 +193,6 @@ impl crate::ImageDimension { } } -//TODO: should this be shared with `crate::proc::wgsl::layout` logic? -fn get_alignment(ty: Handle, arena: &Arena) -> crate::Alignment { - use crate::TypeInner as Ti; - match arena[ty].inner { - Ti::Scalar { width, .. } => crate::Alignment::new(width as u32).unwrap(), - Ti::Vector { size, width, .. } - | Ti::Matrix { - rows: size, width, .. - } => { - let count = if size >= crate::VectorSize::Tri { 4 } else { 2 }; - crate::Alignment::new((count * width) as u32).unwrap() - } - Ti::Pointer { .. } | Ti::ValuePointer { .. } => crate::Alignment::new(1).unwrap(), - Ti::Array { stride, .. } => crate::Alignment::new(stride).unwrap(), - Ti::Struct { ref level, .. } => match *level { - crate::StructLevel::Root => crate::Alignment::new(1).unwrap(), - crate::StructLevel::Normal { alignment } => alignment, - }, - Ti::Image { .. } | Ti::Sampler { .. } => crate::Alignment::new(1).unwrap(), - } -} - type MemberIndex = u32; #[derive(Clone, Debug, Default, PartialEq)] @@ -395,6 +374,7 @@ impl Default for Options { pub struct Parser { data: I, state: ModuleState, + layouter: Layouter, temp_bytes: Vec, ext_glsl_id: Option, future_decor: FastHashMap, @@ -432,6 +412,7 @@ impl> Parser { Parser { data, state: ModuleState::Empty, + layouter: Layouter::default(), temp_bytes: Vec::new(), ext_glsl_id: None, future_decor: FastHashMap::default(), @@ -2319,6 +2300,7 @@ impl> Parser { self.index_constants.push(handle); } + self.layouter.clear(); self.dummy_functions = Arena::new(); self.lookup_function.clear(); self.function_call_graph.clear(); @@ -2946,7 +2928,11 @@ impl> Parser { let parent_decor = self.future_decor.remove(&id); let block_decor = parent_decor.as_ref().and_then(|decor| decor.block.clone()); - let mut struct_alignment = crate::Alignment::new(1).unwrap(); + self.layouter + .update(&module.types, &module.constants) + .unwrap(); + + let mut struct_alignment = Alignment::new(1).unwrap(); let mut members = Vec::::with_capacity(inst.wc as usize - 2); let mut member_lookups = Vec::with_capacity(members.capacity()); let mut storage_access = crate::StorageAccess::empty(); @@ -2989,8 +2975,7 @@ impl> Parser { } } - let alignment = get_alignment(ty, &module.types); - struct_alignment = struct_alignment.max(alignment); + struct_alignment = struct_alignment.max(self.layouter[ty].alignment); members.push(crate::StructMember { name: decor.name, @@ -3001,12 +2986,7 @@ impl> Parser { } let inner = crate::TypeInner::Struct { - level: match block_decor { - Some(_) => crate::StructLevel::Root, - None => crate::StructLevel::Normal { - alignment: struct_alignment, - }, - }, + top_level: block_decor.is_some(), span: match members.last() { Some(member) => { let end = member.offset + module.types[member.ty].inner.span(&module.constants); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 51ebde417..0235cb962 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3,14 +3,15 @@ //! [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html mod conv; -mod layout; mod lexer; #[cfg(test)] mod tests; use crate::{ arena::{Arena, Handle}, - proc::{ensure_block_returns, ResolveContext, ResolveError, TypeResolution}, + proc::{ + ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution, + }, FastHashMap, }; @@ -607,7 +608,7 @@ impl std::error::Error for ParseError { pub struct Parser { scopes: Vec, lookup_type: FastHashMap>, - layouter: layout::Layouter, + layouter: Layouter, } impl Parser { @@ -1557,9 +1558,9 @@ impl Parser { lexer: &mut Lexer<'a>, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result<(Vec, u32, crate::Alignment), Error<'a>> { + ) -> Result<(Vec, u32), Error<'a>> { let mut offset = 0; - let mut alignment = crate::Alignment::new(1).unwrap(); + let mut alignment = Alignment::new(1).unwrap(); let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; @@ -1606,8 +1607,8 @@ impl Parser { let name = match lexer.next() { (Token::Word(word), _) => word, (Token::Paren('}'), _) => { - let span = layout::Layouter::round_up(alignment, offset); - return Ok((members, span, alignment)); + let span = Layouter::round_up(alignment, offset); + return Ok((members, span)); } other => return Err(Error::Unexpected(other, "field name")), }; @@ -1615,7 +1616,8 @@ impl Parser { let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Separator(';'))?; - self.layouter.update(type_arena, const_arena); + self.layouter.update(type_arena, const_arena).unwrap(); + let (range, align) = self.layouter.member_placement(offset, ty, align, size); alignment = alignment.max(align); offset = range.end; @@ -2603,16 +2605,12 @@ impl Parser { (Token::Separator(';'), _) => {} (Token::Word("struct"), _) => { let name = lexer.next_ident()?; - let (members, span, alignment) = + let (members, span) = self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?; let ty = module.types.fetch_or_append(crate::Type { name: Some(name.to_string()), inner: crate::TypeInner::Struct { - level: if is_block { - crate::StructLevel::Root - } else { - crate::StructLevel::Normal { alignment } - }, + top_level: is_block, members, span, }, diff --git a/src/lib.rs b/src/lib.rs index 058a5a9e8..8a5ab20b7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,7 +50,6 @@ pub use crate::arena::{Arena, Handle, Range}; use std::{ collections::{HashMap, HashSet}, hash::BuildHasherDefault, - num::NonZeroU32, }; #[cfg(feature = "deserialize")] @@ -169,7 +168,6 @@ pub enum BuiltIn { /// Number of bytes per scalar. pub type Bytes = u8; -pub type Alignment = NonZeroU32; /// Number of components in a vector. #[repr(u8)] @@ -358,18 +356,6 @@ pub enum ImageClass { Storage(StorageFormat), } -/// Qualifier of the type level, at which a struct can be used. -#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] -#[cfg_attr(feature = "serialize", derive(Serialize))] -#[cfg_attr(feature = "deserialize", derive(Deserialize))] -pub enum StructLevel { - /// This is a root level struct, it can't be nested inside - /// other composite types. - Root, - /// This is a normal struct, and it has to be aligned for nesting. - Normal { alignment: Alignment }, -} - /// A data type declared in the module. #[derive(Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -420,8 +406,9 @@ pub enum TypeInner { }, /// User-defined structure. Struct { - level: StructLevel, + top_level: bool, members: Vec, + //TODO: should this be unaligned? span: u32, }, /// Possibly multidimensional array of texels. diff --git a/src/front/wgsl/layout.rs b/src/proc/layouter.rs similarity index 58% rename from src/front/wgsl/layout.rs rename to src/proc/layouter.rs index e17d5548e..d6c67e0aa 100644 --- a/src/front/wgsl/layout.rs +++ b/src/proc/layouter.rs @@ -1,13 +1,15 @@ use crate::arena::{Arena, Handle}; use std::{num::NonZeroU32, ops}; +pub type Alignment = NonZeroU32; + /// Alignment information for a type. #[derive(Clone, Copy, Debug, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct TypeLayout { pub size: u32, - pub alignment: crate::Alignment, + pub alignment: Alignment, } /// Helper processor that derives the sizes of all types. @@ -20,12 +22,23 @@ pub struct Layouter { layouts: Vec, } +impl ops::Index> for Layouter { + type Output = TypeLayout; + fn index(&self, handle: Handle) -> &TypeLayout { + &self.layouts[handle.index()] + } +} + +#[derive(Clone, Copy, Debug, PartialEq, thiserror::Error)] +#[error("Base type {0:?} is out of bounds")] +pub struct InvalidBaseType(pub Handle); + impl Layouter { pub fn clear(&mut self) { self.layouts.clear(); } - pub fn round_up(alignment: crate::Alignment, offset: u32) -> u32 { + pub fn round_up(alignment: Alignment, offset: u32) -> u32 { match offset & (alignment.get() - 1) { 0 => offset, other => offset + alignment.get() - other, @@ -36,9 +49,9 @@ impl Layouter { &self, offset: u32, ty: Handle, - align: Option, + align: Option, size: Option, - ) -> (ops::Range, crate::Alignment) { + ) -> (ops::Range, Alignment) { let layout = self.layouts[ty.index()]; let alignment = align.unwrap_or(layout.alignment); let start = Self::round_up(alignment, offset); @@ -49,14 +62,19 @@ impl Layouter { (start..start + span, alignment) } - pub fn update(&mut self, types: &Arena, constants: &Arena) { + pub fn update( + &mut self, + types: &Arena, + constants: &Arena, + ) -> Result<(), InvalidBaseType> { use crate::TypeInner as Ti; - for (_, ty) in types.iter().skip(self.layouts.len()) { + + for (ty_handle, ty) in types.iter().skip(self.layouts.len()) { let size = ty.inner.span(constants); let layout = match ty.inner { Ti::Scalar { width, .. } => TypeLayout { size, - alignment: crate::Alignment::new(width as u32).unwrap(), + alignment: Alignment::new(width as u32).unwrap(), }, Ti::Vector { size: vec_size, @@ -70,7 +88,7 @@ impl Layouter { } else { 2 }; - crate::Alignment::new((count * width) as u32).unwrap() + Alignment::new((count * width) as u32).unwrap() }, }, Ti::Matrix { @@ -81,35 +99,52 @@ impl Layouter { size, alignment: { let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; - crate::Alignment::new((count * width) as u32).unwrap() + Alignment::new((count * width) as u32).unwrap() }, }, Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { size, - alignment: crate::Alignment::new(1).unwrap(), + alignment: Alignment::new(1).unwrap(), }, - Ti::Array { stride, .. } => TypeLayout { - size, - alignment: crate::Alignment::new(stride).unwrap(), - }, - Ti::Struct { - ref level, - members: _, - span, + Ti::Array { + base, + stride: _, + size: _, } => TypeLayout { - size: span, - alignment: match *level { - crate::StructLevel::Root => crate::Alignment::new(1).unwrap(), - crate::StructLevel::Normal { alignment } => alignment, + size, + alignment: if base < ty_handle { + self[base].alignment + } else { + return Err(InvalidBaseType(base)); }, }, + Ti::Struct { + top_level: _, + span, + ref members, + } => { + let mut alignment = Alignment::new(1).unwrap(); + for member in members { + alignment = if member.ty < ty_handle { + alignment.max(self[member.ty].alignment) + } else { + return Err(InvalidBaseType(member.ty)); + }; + } + TypeLayout { + size: span, + alignment, + } + } Ti::Image { .. } | Ti::Sampler { .. } => TypeLayout { size, - alignment: crate::Alignment::new(1).unwrap(), + alignment: Alignment::new(1).unwrap(), }, }; debug_assert!(ty.inner.span(constants) <= layout.size); self.layouts.push(layout); } + + Ok(()) } } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 49bab5528..58926c1d8 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,10 +1,12 @@ //! Module processing functionality. mod interpolator; +mod layouter; mod namer; mod terminator; mod typifier; +pub use layouter::{Alignment, InvalidBaseType, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, TypeResolution}; diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 6a9949a65..3d7830b8a 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -262,7 +262,7 @@ impl VaryingContext<'_> { match self.types[self.ty].inner { //TODO: check the member types crate::TypeInner::Struct { - level: crate::StructLevel::Normal { .. }, + top_level: false, ref members, .. } => { @@ -303,7 +303,7 @@ impl super::Validator { } ( crate::StorageAccess::all(), - TypeFlags::DATA | TypeFlags::HOST_SHARED | TypeFlags::BLOCK, + TypeFlags::DATA | TypeFlags::HOST_SHARED | TypeFlags::TOP_LEVEL, true, ) } @@ -315,7 +315,10 @@ impl super::Validator { } ( crate::StorageAccess::empty(), - TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED | TypeFlags::BLOCK, + TypeFlags::DATA + | TypeFlags::SIZED + | TypeFlags::HOST_SHARED + | TypeFlags::TOP_LEVEL, true, ) } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index c34eeebd2..3d22cb34e 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -7,6 +7,7 @@ mod r#type; use crate::{ arena::{Arena, Handle}, + proc::{InvalidBaseType, Layouter}, FastHashSet, }; use bit_set::BitSet; @@ -91,6 +92,7 @@ pub struct Validator { flags: ValidationFlags, capabilities: Capabilities, types: Vec, + layouter: Layouter, location_mask: BitSet, bind_group_masks: Vec, select_cases: FastHashSet, @@ -112,6 +114,8 @@ pub enum ConstantError { #[derive(Clone, Debug, thiserror::Error)] pub enum ValidationError { + #[error(transparent)] + Layouter(#[from] InvalidBaseType), #[error("Type {handle:?} '{name}' is invalid")] Type { handle: Handle, @@ -196,6 +200,7 @@ impl Validator { flags, capabilities, types: Vec::new(), + layouter: Layouter::default(), location_mask: BitSet::new(), bind_group_masks: Vec::new(), select_cases: FastHashSet::default(), @@ -246,6 +251,7 @@ impl Validator { /// Check the given module to be valid. pub fn validate(&mut self, module: &crate::Module) -> Result { self.reset_types(module.types.len()); + self.layouter.update(&module.types, &module.constants)?; if self.flags.contains(ValidationFlags::CONSTANTS) { for (handle, constant) in module.constants.iter() { diff --git a/src/valid/type.rs b/src/valid/type.rs index 056af0508..df0a401c0 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -1,5 +1,8 @@ use super::Capabilities; -use crate::arena::{Arena, Handle}; +use crate::{ + arena::{Arena, Handle}, + proc::Alignment, +}; bitflags::bitflags! { #[repr(transparent)] @@ -13,7 +16,7 @@ bitflags::bitflags! { /// Can be used for host-shareable structures. const HOST_SHARED = 0x8; /// This is a top-level host-shareable type. - const BLOCK = 0x10; + const TOP_LEVEL = 0x10; } } @@ -23,12 +26,6 @@ pub enum Disalignment { ArrayStride { stride: u32, alignment: u32 }, #[error("The struct span {span}, is not a multiple of the required alignment {alignment}")] StructSpan { span: u32, alignment: u32 }, - #[error("The struct span {alignment}, is not a multiple of the member[{member_index}] alignment {member_alignment}")] - StructAlignment { - alignment: u32, - member_index: u32, - member_alignment: u32, - }, #[error("The struct member[{index}] offset {offset} is not a multiple of the required alignment {alignment}")] MemberOffset { index: u32, @@ -63,27 +60,26 @@ pub enum TypeError { "Structure member[{index}] at {offset} and size {size} crosses the structure boundary" )] MemberOutOfBounds { index: u32, offset: u32, size: u32 }, - #[error("The composite type contains a block structure")] - NestedBlock, + #[error("The composite type contains a top-level structure")] + NestedTopLevel, } // Only makes sense if `flags.contains(HOST_SHARED)` -type LayoutCompatibility = Result, (Handle, Disalignment)>; +type LayoutCompatibility = Result, (Handle, Disalignment)>; fn check_member_layout( accum: &mut LayoutCompatibility, member: &crate::StructMember, member_index: u32, member_layout: LayoutCompatibility, - struct_level: crate::StructLevel, - ty_handle: Handle, + parent_handle: Handle, ) { *accum = match (*accum, member_layout) { (Ok(cur_alignment), Ok(align)) => { let align = align.unwrap().get(); if member.offset % align != 0 { Err(( - ty_handle, + parent_handle, Disalignment::MemberOffset { index: member_index, offset: member.offset, @@ -91,32 +87,14 @@ fn check_member_layout( }, )) } else { - match struct_level { - crate::StructLevel::Normal { alignment } if alignment.get() % align != 0 => { - Err(( - ty_handle, - Disalignment::StructAlignment { - alignment: alignment.get(), - member_index, - member_alignment: align, - }, - )) - } - _ => { - let combined_alignment = - ((cur_alignment.unwrap().get() - 1) | (align - 1)) + 1; - Ok(crate::Alignment::new(combined_alignment)) - } - } + let combined_alignment = ((cur_alignment.unwrap().get() - 1) | (align - 1)) + 1; + Ok(Alignment::new(combined_alignment)) } } (Err(e), _) | (_, Err(e)) => Err(e), }; } -// For the uniform buffer alignment, array strides and struct sizes must be multiples of 16. -const UNIFORM_LAYOUT_ALIGNMENT_MASK: u32 = 0xF; - #[derive(Clone, Debug)] pub(super) struct TypeInfo { pub flags: TypeFlags, @@ -134,7 +112,7 @@ impl TypeInfo { } fn new(flags: TypeFlags, align: u32) -> Self { - let alignment = crate::Alignment::new(align); + let alignment = Alignment::new(align); TypeInfo { flags, uniform_layout: Ok(alignment), @@ -157,6 +135,7 @@ impl super::Validator { pub(super) fn reset_types(&mut self, size: usize) { self.types.clear(); self.types.resize(size, TypeInfo::dummy()); + self.layouter.clear(); } pub(super) fn validate_type( @@ -234,8 +213,8 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { return Err(TypeError::InvalidArrayBaseType(base)); } - if base_info.flags.contains(TypeFlags::BLOCK) { - return Err(TypeError::NestedBlock); + if base_info.flags.contains(TypeFlags::TOP_LEVEL) { + return Err(TypeError::NestedTopLevel); } let base_size = types[base].inner.span(constants); @@ -243,11 +222,12 @@ impl super::Validator { return Err(TypeError::InsufficientArrayStride { stride, base_size }); } + let general_alignment = self.layouter[base].alignment; let uniform_layout = match base_info.uniform_layout { Ok(base_alignment) => { // combine the alignment requirements let align = ((base_alignment.unwrap().get() - 1) - | UNIFORM_LAYOUT_ALIGNMENT_MASK) + | (general_alignment.get() - 1)) + 1; if stride % align != 0 { Err(( @@ -258,14 +238,16 @@ impl super::Validator { }, )) } else { - Ok(crate::Alignment::new(align)) + Ok(Alignment::new(align)) } } Err(e) => Err(e), }; let storage_layout = match base_info.storage_layout { Ok(base_alignment) => { - let align = base_alignment.unwrap().get(); + let align = ((base_alignment.unwrap().get() - 1) + | (general_alignment.get() - 1)) + + 1; if stride % align != 0 { Err(( handle, @@ -275,7 +257,7 @@ impl super::Validator { }, )) } else { - Ok(base_alignment) + Ok(Alignment::new(align)) } } Err(e) => Err(e), @@ -324,7 +306,7 @@ impl super::Validator { } } Ti::Struct { - level, + top_level, ref members, span, } => { @@ -336,6 +318,7 @@ impl super::Validator { 1, ); let mut min_offset = 0; + for (i, member) in members.iter().enumerate() { if member.ty >= handle { return Err(TypeError::UnresolvedBase(member.ty)); @@ -344,13 +327,11 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); } - if level == crate::StructLevel::Root - && !base_info.flags.contains(TypeFlags::INTERFACE) - { + if top_level && !base_info.flags.contains(TypeFlags::INTERFACE) { return Err(TypeError::InvalidBlockType(member.ty)); } - if base_info.flags.contains(TypeFlags::BLOCK) { - return Err(TypeError::NestedBlock); + if base_info.flags.contains(TypeFlags::TOP_LEVEL) { + return Err(TypeError::NestedTopLevel); } ti.flags &= base_info.flags; @@ -382,7 +363,6 @@ impl super::Validator { member, i as u32, base_info.uniform_layout, - level, handle, ); check_member_layout( @@ -390,7 +370,6 @@ impl super::Validator { member, i as u32, base_info.storage_layout, - level, handle, ); @@ -406,24 +385,16 @@ impl super::Validator { } } } - if let crate::StructLevel::Root = level { - ti.flags |= TypeFlags::BLOCK; + if top_level { + ti.flags |= TypeFlags::TOP_LEVEL; } - // disabled temporarily, see https://github.com/gpuweb/gpuweb/issues/1558 - const CHECK_STRUCT_SIZE: bool = false; - if CHECK_STRUCT_SIZE - && ti.uniform_layout.is_ok() - && span & UNIFORM_LAYOUT_ALIGNMENT_MASK != 0 - { - ti.uniform_layout = Err(( - handle, - Disalignment::StructSpan { - span, - alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK + 1, - }, - )); + let alignment = self.layouter[handle].alignment.get(); + if span % alignment != 0 { + ti.uniform_layout = Err((handle, Disalignment::StructSpan { span, alignment })); + ti.storage_layout = Err((handle, Disalignment::StructSpan { span, alignment })); } + ti } Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::new(TypeFlags::empty(), 0), diff --git a/tests/out/collatz.ron b/tests/out/collatz.ron index 65f98a6e8..7fe6a38ef 100644 --- a/tests/out/collatz.ron +++ b/tests/out/collatz.ron @@ -18,7 +18,7 @@ ( name: Some("PrimeIndices"), inner: Struct( - level: Root, + top_level: true, members: [ ( name: Some("data"), diff --git a/tests/out/shadow.ron b/tests/out/shadow.ron index 6d55e1bd7..fd91f99af 100644 --- a/tests/out/shadow.ron +++ b/tests/out/shadow.ron @@ -102,7 +102,7 @@ ( name: Some("Globals"), inner: Struct( - level: Root, + top_level: true, members: [ ( name: Some("num_lights"), @@ -146,9 +146,7 @@ ( name: Some("Light"), inner: Struct( - level: Normal( - alignment: 16, - ), + top_level: false, members: [ ( name: Some("proj"), @@ -183,7 +181,7 @@ ( name: Some("Lights"), inner: Struct( - level: Root, + top_level: true, members: [ ( name: Some("data"), diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 5a03f4785..cf4a91d81 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -120,7 +120,7 @@ fn invalid_arrays() { type Bad = array; "#: Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::NestedBlock, + error: naga::valid::TypeError::NestedTopLevel, .. }) } From 0e3a7840ffa554cb144233f4fdda9224936d75d9 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 17 May 2021 15:44:58 -0700 Subject: [PATCH 0829/2212] [wgsl-in]: Report unknown identifiers as Error::UnknownIdent. Move the parsing of type construction expressions into a function of its own, which can return `None` when the identifier at hand is not the name of a type. This means that `parse_primary_expression` doesn't have to commit to interpreting the expression as a type construction too early, allowing it to report unknown identifiers as Error::UnknownIdent. --- src/front/wgsl/mod.rs | 186 ++++++++++++++++++++++-------------------- 1 file changed, 98 insertions(+), 88 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 0235cb962..f0c9ccbad 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1007,6 +1007,89 @@ impl Parser { Ok(Some(ctx.expressions.append(expr))) } + fn parse_construction<'a>( + &mut self, + lexer: &mut Lexer<'a>, + type_name: &'a str, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + let ty_resolution = match self.lookup_type.get(type_name) { + Some(&handle) => TypeResolution::Handle(handle), + None => match self.parse_type_decl_impl( + lexer, + TypeAttributes::default(), + type_name, + ctx.types, + ctx.constants, + )? { + Some(inner) => TypeResolution::Value(inner), + None => return Ok(None), + }, + }; + + lexer.open_arguments()?; + let mut components = Vec::new(); + let mut last_component = self.parse_general_expression(lexer, ctx.reborrow())?; + while lexer.next_argument()? { + components.push(last_component); + last_component = self.parse_general_expression(lexer, ctx.reborrow())?; + } + + let expr = if components.is_empty() + && ty_resolution.inner_with(ctx.types).scalar_kind().is_some() + { + // We can't use the `TypeInner` returned by this because + // `resolve_type` borrows context mutably. + // Use it to insert into the right maps, + // and then grab it again immutably. + ctx.resolve_type(last_component)?; + match ( + ty_resolution.inner_with(ctx.types), + ctx.typifier.get(last_component, ctx.types), + ) { + (&crate::TypeInner::Vector { size, .. }, &crate::TypeInner::Scalar { .. }) => { + crate::Expression::Splat { + size, + value: last_component, + } + } + ( + &crate::TypeInner::Scalar { kind, width, .. }, + &crate::TypeInner::Scalar { .. }, + ) + | ( + &crate::TypeInner::Vector { kind, width, .. }, + &crate::TypeInner::Vector { .. }, + ) => crate::Expression::As { + expr: last_component, + kind, + convert: Some(width), + }, + (&crate::TypeInner::Matrix { width, .. }, &crate::TypeInner::Matrix { .. }) => { + crate::Expression::As { + expr: last_component, + kind: crate::ScalarKind::Float, + convert: Some(width), + } + } + _ => { + return Err(Error::BadTypeCast(type_name)); + } + } + } else { + let ty = match ty_resolution { + TypeResolution::Handle(handle) => handle, + TypeResolution::Value(inner) => { + ctx.types.fetch_or_append(crate::Type { name: None, inner }) + } + }; + components.push(last_component); + crate::Expression::Compose { ty, components } + }; + + Ok(Some(ctx.expressions.append(expr))) + } + fn parse_const_expression_impl<'a>( &mut self, first_token_span: TokenSpan<'a>, @@ -1122,84 +1205,10 @@ impl Parser { { //TODO: resolve the duplicate call in `parse_singular_expression` expr + } else if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow())? { + expr } else { - let ty_resolution = match self.lookup_type.get(word) { - Some(&handle) => TypeResolution::Handle(handle), - None => { - let inner = self.parse_type_decl_impl( - lexer, - TypeAttributes::default(), - word, - ctx.types, - ctx.constants, - )?; - TypeResolution::Value(inner) - } - }; - - lexer.open_arguments()?; - let mut components = Vec::new(); - let mut last_component = - self.parse_general_expression(lexer, ctx.reborrow())?; - while lexer.next_argument()? { - components.push(last_component); - last_component = self.parse_general_expression(lexer, ctx.reborrow())?; - } - - let expr = if components.is_empty() - && ty_resolution.inner_with(ctx.types).scalar_kind().is_some() - { - // We can't use the `TypeInner` returned by this because - // `resolve_type` borrows context mutably. - // Use it to insert into the right maps, - // and then grab it again immutably. - ctx.resolve_type(last_component)?; - match ( - ty_resolution.inner_with(ctx.types), - ctx.typifier.get(last_component, ctx.types), - ) { - ( - &crate::TypeInner::Vector { size, .. }, - &crate::TypeInner::Scalar { .. }, - ) => crate::Expression::Splat { - size, - value: last_component, - }, - ( - &crate::TypeInner::Scalar { kind, width, .. }, - &crate::TypeInner::Scalar { .. }, - ) - | ( - &crate::TypeInner::Vector { kind, width, .. }, - &crate::TypeInner::Vector { .. }, - ) => crate::Expression::As { - expr: last_component, - kind, - convert: Some(width), - }, - ( - &crate::TypeInner::Matrix { width, .. }, - &crate::TypeInner::Matrix { .. }, - ) => crate::Expression::As { - expr: last_component, - kind: crate::ScalarKind::Float, - convert: Some(width), - }, - _ => { - return Err(Error::BadTypeCast(word)); - } - } - } else { - let ty = match ty_resolution { - TypeResolution::Handle(handle) => handle, - TypeResolution::Value(inner) => { - ctx.types.fetch_or_append(crate::Type { name: None, inner }) - } - }; - components.push(last_component); - crate::Expression::Compose { ty, components } - }; - ctx.expressions.append(expr) + return Err(Error::UnknownIdent(word)); } } other => return Err(Error::Unexpected(other, "primary expression")), @@ -1638,11 +1647,11 @@ impl Parser { word: &'a str, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result> { + ) -> Result, Error<'a>> { if let Some((kind, width)) = conv::get_scalar_type(word) { - return Ok(crate::TypeInner::Scalar { kind, width }); + return Ok(Some(crate::TypeInner::Scalar { kind, width })); } - Ok(match word { + Ok(Some(match word { "vec2" => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Vector { @@ -1899,8 +1908,8 @@ impl Parser { class: crate::ImageClass::Storage(format), } } - _ => return Err(Error::UnknownType(word)), - }) + _ => return Ok(None), + })) } /// Parse type declaration of a given name and attribute. @@ -1916,12 +1925,13 @@ impl Parser { Ok(match self.lookup_type.get(name) { Some(&handle) => handle, None => { - let inner = - self.parse_type_decl_impl(lexer, attribute, name, type_arena, const_arena)?; - type_arena.fetch_or_append(crate::Type { - name: debug_name.map(|s| s.to_string()), - inner, - }) + match self.parse_type_decl_impl(lexer, attribute, name, type_arena, const_arena)? { + Some(inner) => type_arena.fetch_or_append(crate::Type { + name: debug_name.map(|s| s.to_string()), + inner, + }), + None => return Err(Error::UnknownType(name)), + } } }) } From 0985727710e3fc23c27f2feb07511aa289e5aca8 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 17 May 2021 16:19:33 -0700 Subject: [PATCH 0830/2212] [wgsl-in] Include span information in 'unknown identifier' errors. --- src/front/wgsl/mod.rs | 91 ++++++++++++++++++++++++------------------- tests/wgsl-errors.rs | 18 +++++++++ 2 files changed, 68 insertions(+), 41 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f0c9ccbad..56343335d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -96,8 +96,8 @@ pub enum Error<'a> { UnknownAccess(&'a str), #[error("unknown shader stage: `{0}`")] UnknownShaderStage(&'a str), - #[error("unknown identifier: `{0}`")] - UnknownIdent(&'a str), + #[error("unknown identifier: `{1}`")] + UnknownIdent(Span, &'a str), #[error("unknown scalar type: `{0}`")] UnknownScalarType(&'a str), #[error("unknown type: `{0}`")] @@ -175,6 +175,11 @@ impl<'a> Error<'a> { labels: vec![(accessor_span.clone(), "invalid accessor".to_string())], notes: vec![], }, + Error::UnknownIdent(ref ident_span, ident) => ParseError { + message: format!("unknown identifier: '{}'", ident), + labels: vec![(ident_span.clone(), "unknown identifier".to_string())], + notes: vec![], + }, ref error => ParseError { message: error.to_string(), labels: vec![], @@ -186,12 +191,12 @@ impl<'a> Error<'a> { trait StringValueLookup<'a> { type Value; - fn lookup(&self, key: &'a str) -> Result>; + fn lookup(&self, key: &'a str, span: Span) -> Result>; } impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle> { type Value = Handle; - fn lookup(&self, key: &'a str) -> Result> { - self.get(key).cloned().ok_or(Error::UnknownIdent(key)) + fn lookup(&self, key: &'a str, span: Span) -> Result> { + self.get(key).cloned().ok_or(Error::UnknownIdent(span, key)) } } @@ -302,8 +307,12 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } - fn prepare_sampling(&mut self, image_name: &'a str) -> Result> { - let image = self.lookup_ident.lookup(image_name)?; + fn prepare_sampling( + &mut self, + image_name: &'a str, + span: Span, + ) -> Result> { + let image = self.lookup_ident.lookup(image_name, span)?; Ok(SamplingContext { image, arrayed: match *self.resolve_type(image)? { @@ -745,12 +754,12 @@ impl Parser { match name { "textureSample" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; + let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let sampler_name = lexer.next_ident()?; + let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name)?; + let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -765,7 +774,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, coordinate, array_index, offset, @@ -775,12 +784,12 @@ impl Parser { } "textureSampleLevel" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; + let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let sampler_name = lexer.next_ident()?; + let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name)?; + let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -797,7 +806,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, coordinate, array_index, offset, @@ -807,12 +816,12 @@ impl Parser { } "textureSampleBias" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; + let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let sampler_name = lexer.next_ident()?; + let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name)?; + let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -829,7 +838,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, coordinate, array_index, offset, @@ -839,12 +848,12 @@ impl Parser { } "textureSampleGrad" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; + let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let sampler_name = lexer.next_ident()?; + let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name)?; + let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -863,7 +872,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, coordinate, array_index, offset, @@ -873,12 +882,12 @@ impl Parser { } "textureSampleCompare" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; + let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let sampler_name = lexer.next_ident()?; + let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name)?; + let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -895,7 +904,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, coordinate, array_index, offset, @@ -905,8 +914,8 @@ impl Parser { } "textureLoad" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; - let image = ctx.lookup_ident.lookup(image_name)?; + let (image_name, image_span) = lexer.next_ident_with_span()?; + let image = ctx.lookup_ident.lookup(image_name, image_span)?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let (class, arrayed) = match *ctx.resolve_type(image)? { @@ -937,8 +946,8 @@ impl Parser { } "textureDimensions" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; - let image = ctx.lookup_ident.lookup(image_name)?; + let (image_name, image_span) = lexer.next_ident_with_span()?; + let image = ctx.lookup_ident.lookup(image_name, image_span)?; let level = if lexer.skip(Token::Separator(',')) { let expr = self.parse_general_expression(lexer, ctx.reborrow())?; Some(expr) @@ -953,8 +962,8 @@ impl Parser { } "textureNumLevels" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; - let image = ctx.lookup_ident.lookup(image_name)?; + let (image_name, image_span) = lexer.next_ident_with_span()?; + let image = ctx.lookup_ident.lookup(image_name, image_span)?; lexer.close_arguments()?; crate::Expression::ImageQuery { image, @@ -963,8 +972,8 @@ impl Parser { } "textureNumLayers" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; - let image = ctx.lookup_ident.lookup(image_name)?; + let (image_name, image_span) = lexer.next_ident_with_span()?; + let image = ctx.lookup_ident.lookup(image_name, image_span)?; lexer.close_arguments()?; crate::Expression::ImageQuery { image, @@ -973,8 +982,8 @@ impl Parser { } "textureNumSamples" => { lexer.open_arguments()?; - let image_name = lexer.next_ident()?; - let image = ctx.lookup_ident.lookup(image_name)?; + let (image_name, image_span) = lexer.next_ident_with_span()?; + let image = ctx.lookup_ident.lookup(image_name, image_span)?; lexer.close_arguments()?; crate::Expression::ImageQuery { image, @@ -1197,7 +1206,7 @@ impl Parser { ctx.emitter.start(ctx.expressions); expr } - (Token::Word(word), _) => { + (Token::Word(word), span) => { if let Some(&expr) = ctx.lookup_ident.get(word) { expr } else if let Some(expr) = @@ -1208,7 +1217,7 @@ impl Parser { } else if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow())? { expr } else { - return Err(Error::UnknownIdent(word)); + return Err(Error::UnknownIdent(span, word)); } } other => return Err(Error::Unexpected(other, "primary expression")), @@ -2351,8 +2360,8 @@ impl Parser { "textureStore" => { emitter.start(context.expressions); lexer.open_arguments()?; - let image_name = lexer.next_ident()?; - let image = context.lookup_ident.lookup(image_name)?; + let (image_name, image_span) = lexer.next_ident_with_span()?; + let image = context.lookup_ident.lookup(image_name, image_span)?; lexer.expect(Token::Separator(','))?; let mut expr_context = context.as_expression(block, &mut emitter); let arrayed = match *expr_context.resolve_type(image)? { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index cf4a91d81..87050a6de 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -75,6 +75,24 @@ fn invalid_scalar_width() { ); } +#[test] +fn unknown_identifier() { + check( + r###" + fn f(x: f32) -> f32 { + return x * schmoo; + } + "###, + r###"error: unknown identifier: 'schmoo' + ┌─ wgsl:3:30 + │ +3 │ return x * schmoo; + │ ^^^^^^ unknown identifier + +"###, + ); +} + macro_rules! check_validation_error { ( $( $source:literal ),* : $pattern:pat ) => { $( From 1f53ff1d1e41339716ef5265171e318a728c3f8a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 17 May 2021 21:27:33 -0400 Subject: [PATCH 0831/2212] [spv-in] fix emitted expressions for ImageStore --- src/front/spv/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 0a1e3113d..fa3c7263f 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1478,9 +1478,11 @@ impl> Parser { } Op::ImageWrite => { let extra = inst.expect_at_least(4)?; + block.extend(emitter.finish(expressions)); let stmt = self.parse_image_write(extra, type_arena, global_arena, expressions)?; block.push(stmt); + emitter.start(expressions); } Op::ImageFetch | Op::ImageRead => { let extra = inst.expect_at_least(5)?; From 8b601714035f2cc4925e7f1007c4bfe593c30164 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 17 May 2021 22:00:05 -0400 Subject: [PATCH 0832/2212] [glsl-out] emit sample variables extension --- src/back/glsl/features.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index b78352fde..7b99c9c22 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -30,6 +30,8 @@ bitflags::bitflags! { const SAMPLE_QUALIFIER = 1 << 12; const CLIP_DISTANCE = 1 << 13; const CULL_DISTANCE = 1 << 14; + // Sample ID + const SAMPLE_VARIABLES = 1 << 15; } } @@ -95,6 +97,7 @@ impl FeaturesManager { // gl_ClipDistance is supported by core versions > 1.3 and aren't supported by an es versions without extensions check_feature!(CLIP_DISTANCE, 130, 300); check_feature!(CULL_DISTANCE, 450, 300); + check_feature!(SAMPLE_VARIABLES, 300, 300); // Return an error if there are missing features if missing.is_empty() { @@ -183,6 +186,11 @@ impl FeaturesManager { // writeln!(out, "#extension GL_EXT_clip_cull_distance : require")?; } + if self.0.contains(Features::SAMPLE_VARIABLES) && version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/OES/OES_sample_variables.txt + writeln!(out, "#extension GL_OES_sample_variables : require")?; + } + Ok(()) } } @@ -310,6 +318,9 @@ impl<'a, W> Writer<'a, W> { crate::BuiltIn::CullDistance => { self.features.request(Features::CULL_DISTANCE) } + crate::BuiltIn::SampleIndex => { + self.features.request(Features::SAMPLE_VARIABLES) + } _ => {} }, Binding::Location { From 96ec0b61e783bd2e32ed6cd6c13f9ae7cb1b4d79 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 17 May 2021 22:00:12 -0400 Subject: [PATCH 0833/2212] Snapshot for built-ins --- src/back/glsl/features.rs | 2 +- tests/in/interface.param.ron | 5 ++ tests/in/interface.wgsl | 45 +++++++++++++ tests/out/interface.msl | 62 ++++++++++++++++++ tests/out/interface.spvasm | 124 +++++++++++++++++++++++++++++++++++ tests/snapshots.rs | 2 + 6 files changed, 239 insertions(+), 1 deletion(-) create mode 100644 tests/in/interface.param.ron create mode 100644 tests/in/interface.wgsl create mode 100644 tests/out/interface.msl create mode 100644 tests/out/interface.spvasm diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 7b99c9c22..957b02347 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -97,7 +97,7 @@ impl FeaturesManager { // gl_ClipDistance is supported by core versions > 1.3 and aren't supported by an es versions without extensions check_feature!(CLIP_DISTANCE, 130, 300); check_feature!(CULL_DISTANCE, 450, 300); - check_feature!(SAMPLE_VARIABLES, 300, 300); + check_feature!(SAMPLE_VARIABLES, 400, 300); // Return an error if there are missing features if missing.is_empty() { diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron new file mode 100644 index 000000000..ee3fa36da --- /dev/null +++ b/tests/in/interface.param.ron @@ -0,0 +1,5 @@ +( + spv_version: (1, 0), + spv_capabilities: [ Shader, SampleRateShading ], + spv_adjust_coordinate_space: false, +) diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl new file mode 100644 index 000000000..e56634e67 --- /dev/null +++ b/tests/in/interface.wgsl @@ -0,0 +1,45 @@ +// Testing various parts of the pipeline interface: locations, built-ins, bindings, and entry points + +struct VertexOutput { + [[builtin(position)]] position: vec4; + [[location(1)]] varying: f32; +}; + +[[stage(vertex)]] +fn vertex( + [[builtin(vertex_index)]] vertex_index: u32, + [[builtin(instance_index)]] instance_index: u32, + [[location(10)]] color: u32, +) -> VertexOutput { + let tmp = vertex_index + instance_index + color; + return VertexOutput(vec4(1.0), f32(tmp)); +} + +struct FragmentOutput { + [[builtin(frag_depth)]] depth: f32; + [[builtin(sample_mask)]] sample_mask: u32; + [[location(0)]] color: f32; +}; + +[[stage(fragment)]] +fn fragment( + in: VertexOutput, + [[builtin(front_facing)]] front_facing: bool, + [[builtin(sample_index)]] sample_index: u32, + [[builtin(sample_mask)]] sample_mask: u32, +) -> FragmentOutput { + let mask = sample_mask & (1u << sample_index); + let color = select(0.0, 1.0, front_facing); + return FragmentOutput(in.varying, mask, color); +} + +[[stage(compute), workgroup_size(1)]] +fn compute( + [[builtin(global_invocation_id)]] global_id: vec3, + [[builtin(local_invocation_id)]] local_id: vec3, + [[builtin(local_invocation_index)]] local_index: u32, + [[builtin(workgroup_id)]] wg_id: vec3, + //TODO: https://github.com/gpuweb/gpuweb/issues/1590 + //[[builtin(workgroup_size)]] wg_size: vec3, +) { +} diff --git a/tests/out/interface.msl b/tests/out/interface.msl new file mode 100644 index 000000000..970f81c0c --- /dev/null +++ b/tests/out/interface.msl @@ -0,0 +1,62 @@ +#include +#include + +struct VertexOutput { + metal::float4 position; + float varying; +}; +struct FragmentOutput { + float depth; + metal::uint sample_mask; + float color; +}; + +struct vertex1Input { + metal::uint color1 [[attribute(10)]]; +}; +struct vertex1Output { + metal::float4 position [[position]]; + float varying [[user(loc1), center_perspective]]; +}; +vertex vertex1Output vertex1( + vertex1Input varyings [[stage_in]] +, metal::uint vertex_index [[vertex_id]] +, metal::uint instance_index [[instance_id]] +) { + const auto color1 = varyings.color1; + const auto _tmp = VertexOutput {metal::float4(1.0), static_cast((vertex_index + instance_index) + color1)}; + return vertex1Output { _tmp.position, _tmp.varying }; +} + + +struct fragment1Input { + float varying [[user(loc1), center_perspective]]; +}; +struct fragment1Output { + float depth [[depth(any)]]; + metal::uint sample_mask [[sample_mask]]; + float color [[color(0)]]; +}; +fragment fragment1Output fragment1( + fragment1Input varyings1 [[stage_in]] +, metal::float4 position [[position]] +, bool front_facing [[front_facing]] +, metal::uint sample_index [[sample_id]] +, metal::uint sample_mask1 [[sample_mask]] +) { + const VertexOutput in = { position, varyings1.varying }; + const auto _tmp = FragmentOutput {in.varying, sample_mask1 & (1u << sample_index), front_facing ? 0.0 : 1.0}; + return fragment1Output { _tmp.depth, _tmp.sample_mask, _tmp.color }; +} + + +struct compute1Input { +}; +kernel void compute1( + metal::uint3 global_id [[thread_position_in_grid]] +, metal::uint3 local_id [[thread_position_in_threadgroup]] +, metal::uint local_index [[thread_index_in_threadgroup]] +, metal::uint3 wg_id [[threadgroup_position_in_grid]] +) { + return; +} diff --git a/tests/out/interface.spvasm b/tests/out/interface.spvasm new file mode 100644 index 000000000..3ba43b860 --- /dev/null +++ b/tests/out/interface.spvasm @@ -0,0 +1,124 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 76 +OpCapability Shader +OpCapability SampleRateShading +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %25 "vertex" %14 %17 %19 %21 %23 +OpEntryPoint Fragment %54 "fragment" %37 %40 %43 %46 %48 %50 %51 %53 +OpEntryPoint GLCompute %74 "compute" %65 %68 %70 %72 +OpExecutionMode %54 OriginUpperLeft +OpExecutionMode %54 DepthReplacing +OpExecutionMode %74 LocalSize 1 1 1 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 16 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 4 +OpMemberDecorate %10 2 Offset 8 +OpDecorate %14 BuiltIn VertexIndex +OpDecorate %17 BuiltIn InstanceIndex +OpDecorate %19 Location 10 +OpDecorate %21 BuiltIn Position +OpDecorate %23 Location 1 +OpDecorate %37 BuiltIn FragCoord +OpDecorate %40 Location 1 +OpDecorate %43 BuiltIn FrontFacing +OpDecorate %46 BuiltIn SampleId +OpDecorate %48 BuiltIn SampleMask +OpDecorate %50 BuiltIn FragDepth +OpDecorate %51 BuiltIn SampleMask +OpDecorate %53 Location 0 +OpDecorate %65 BuiltIn GlobalInvocationId +OpDecorate %68 BuiltIn LocalInvocationId +OpDecorate %70 BuiltIn LocalInvocationIndex +OpDecorate %72 BuiltIn WorkgroupId +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.0 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 1 +%7 = OpConstant %4 0.0 +%8 = OpTypeVector %4 4 +%9 = OpTypeStruct %8 %4 +%10 = OpTypeStruct %4 %6 %4 +%11 = OpTypeBool +%12 = OpTypeVector %6 3 +%15 = OpTypePointer Input %6 +%14 = OpVariable %15 Input +%17 = OpVariable %15 Input +%19 = OpVariable %15 Input +%22 = OpTypePointer Output %8 +%21 = OpVariable %22 Output +%24 = OpTypePointer Output %4 +%23 = OpVariable %24 Output +%26 = OpTypeFunction %2 +%38 = OpTypePointer Input %8 +%37 = OpVariable %38 Input +%41 = OpTypePointer Input %4 +%40 = OpVariable %41 Input +%44 = OpTypePointer Input %11 +%43 = OpVariable %44 Input +%46 = OpVariable %15 Input +%48 = OpVariable %15 Input +%50 = OpVariable %24 Output +%52 = OpTypePointer Output %6 +%51 = OpVariable %52 Output +%53 = OpVariable %24 Output +%66 = OpTypePointer Input %12 +%65 = OpVariable %66 Input +%68 = OpVariable %66 Input +%70 = OpVariable %15 Input +%72 = OpVariable %66 Input +%25 = OpFunction %2 None %26 +%13 = OpLabel +%16 = OpLoad %6 %14 +%18 = OpLoad %6 %17 +%20 = OpLoad %6 %19 +OpBranch %27 +%27 = OpLabel +%28 = OpIAdd %6 %16 %18 +%29 = OpIAdd %6 %28 %20 +%30 = OpCompositeConstruct %8 %3 %3 %3 %3 +%31 = OpConvertUToF %4 %29 +%32 = OpCompositeConstruct %9 %30 %31 +%33 = OpCompositeExtract %8 %32 0 +OpStore %21 %33 +%34 = OpCompositeExtract %4 %32 1 +OpStore %23 %34 +OpReturn +OpFunctionEnd +%54 = OpFunction %2 None %26 +%35 = OpLabel +%39 = OpLoad %8 %37 +%42 = OpLoad %4 %40 +%36 = OpCompositeConstruct %9 %39 %42 +%45 = OpLoad %11 %43 +%47 = OpLoad %6 %46 +%49 = OpLoad %6 %48 +OpBranch %55 +%55 = OpLabel +%56 = OpShiftLeftLogical %6 %5 %47 +%57 = OpBitwiseAnd %6 %49 %56 +%58 = OpSelect %4 %45 %7 %3 +%59 = OpCompositeExtract %4 %36 1 +%60 = OpCompositeConstruct %10 %59 %57 %58 +%61 = OpCompositeExtract %4 %60 0 +OpStore %50 %61 +%62 = OpCompositeExtract %6 %60 1 +OpStore %51 %62 +%63 = OpCompositeExtract %4 %60 2 +OpStore %53 %63 +OpReturn +OpFunctionEnd +%74 = OpFunction %2 None %26 +%64 = OpLabel +%67 = OpLoad %12 %65 +%69 = OpLoad %12 %68 +%71 = OpLoad %6 %70 +%73 = OpLoad %12 %72 +OpBranch %75 +%75 = OpLabel +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 37a49478f..8882f9600 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -267,6 +267,8 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::GLSL, ), ("standard", Targets::SPIRV | Targets::METAL | Targets::GLSL), + //TODO: GLSL https://github.com/gfx-rs/naga/issues/874 + ("interface", Targets::SPIRV | Targets::METAL), ]; for &(name, targets) in inputs.iter() { From b4aa96657539d46f6d22387aff7d6b5390602e85 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sun, 16 May 2021 23:06:57 +0300 Subject: [PATCH 0834/2212] [wgsl-out] Create baking expression for texture function --- src/back/wgsl/writer.rs | 19 +++++++++++++++---- tests/out/image.wgsl | 26 +++++++++++++++++++++++--- tests/out/quad-vert.wgsl | 2 +- tests/out/quad.wgsl | 4 ++-- 4 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 19ba6df22..214cdece7 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -571,8 +571,16 @@ impl Writer { match *stmt { Statement::Emit(ref range) => { for handle in range.clone() { - let min_ref_count = func_ctx.expressions[handle].bake_ref_count(); - if min_ref_count <= func_ctx.info[handle].ref_count { + let expr = &func_ctx.expressions[handle]; + let min_ref_count = expr.bake_ref_count(); + // Forcefully creating baking expressions in some cases to help with readability + let required_baking_expr = match *expr { + Expression::ImageLoad { .. } + | Expression::ImageQuery { .. } + | Expression::ImageSample { .. } => true, + _ => false, + }; + if min_ref_count <= func_ctx.info[handle].ref_count || required_baking_expr { write!(self.out, "{}", INDENT.repeat(indent))?; self.start_baking_expr(module, handle, &func_ctx)?; self.write_expr(module, handle, &func_ctx)?; @@ -843,8 +851,11 @@ impl Writer { }; match *resolved { - TypeInner::Vector { .. } - | TypeInner::Matrix { .. } + TypeInner::Vector { .. } => { + // Write vector access as a swizzle + write!(self.out, ".{}", COMPONENTS[index as usize])? + } + TypeInner::Matrix { .. } | TypeInner::Array { .. } | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, TypeInner::Struct { .. } => { diff --git a/tests/out/image.wgsl b/tests/out/image.wgsl index 4fd7ef9a3..f92a356c4 100644 --- a/tests/out/image.wgsl +++ b/tests/out/image.wgsl @@ -19,13 +19,33 @@ var image_aa: texture_multisampled_2d; [[stage(compute), workgroup_size(16, 1, 1)]] fn main([[builtin(local_invocation_id)]] local_id: vec3) { - let _e10: vec2 = ((textureDimensions(image_src) * vec2(local_id.xy)) % vec2(10, 20)); + let _e3: vec2 = textureDimensions(image_src); + let _e10: vec2 = ((_e3 * vec2(local_id.xy)) % vec2(10, 20)); let _e11: vec4 = textureLoad(image_src, _e10); - textureStore(image_dst, _e10[0], _e11); + textureStore(image_dst, _e10.x, _e11); return; } [[stage(vertex)]] fn queries() -> [[builtin(position)]] vec4 { - return vec4(f32(((((((((((((((((((textureDimensions(image_1d) + textureDimensions(image_2d)[1]) + textureDimensions(image_2d, 1)[1]) + textureDimensions(image_2d_array)[1]) + textureDimensions(image_2d_array, 1)[1]) + textureNumLayers(image_2d_array)) + textureDimensions(image_cube)[1]) + textureDimensions(image_cube, 1)[1]) + textureDimensions(image_cube_array)[1]) + textureDimensions(image_cube_array, 1)[1]) + textureNumLayers(image_cube_array)) + textureDimensions(image_3d)[2]) + textureDimensions(image_3d, 1)[2]) + textureNumSamples(image_aa)) + textureNumLevels(image_2d)) + textureNumLevels(image_2d_array)) + textureNumLevels(image_3d)) + textureNumLevels(image_cube)) + textureNumLevels(image_cube_array)))); + let _e9: i32 = textureDimensions(image_1d); + let _e10: vec2 = textureDimensions(image_2d); + let _e11: i32 = textureNumLevels(image_2d); + let _e13: vec2 = textureDimensions(image_2d, 1); + let _e14: vec2 = textureDimensions(image_2d_array); + let _e15: i32 = textureNumLevels(image_2d_array); + let _e17: vec2 = textureDimensions(image_2d_array, 1); + let _e18: i32 = textureNumLayers(image_2d_array); + let _e19: vec3 = textureDimensions(image_cube); + let _e20: i32 = textureNumLevels(image_cube); + let _e22: vec3 = textureDimensions(image_cube, 1); + let _e23: vec3 = textureDimensions(image_cube_array); + let _e24: i32 = textureNumLevels(image_cube_array); + let _e26: vec3 = textureDimensions(image_cube_array, 1); + let _e27: i32 = textureNumLayers(image_cube_array); + let _e28: vec3 = textureDimensions(image_3d); + let _e29: i32 = textureNumLevels(image_3d); + let _e31: vec3 = textureDimensions(image_3d, 1); + let _e32: i32 = textureNumSamples(image_aa); + return vec4(f32(((((((((((((((((((_e9 + _e10.y) + _e13.y) + _e14.y) + _e17.y) + _e18) + _e19.y) + _e22.y) + _e23.y) + _e26.y) + _e27) + _e28.z) + _e31.z) + _e32) + _e11) + _e15) + _e29) + _e20) + _e24))); } diff --git a/tests/out/quad-vert.wgsl b/tests/out/quad-vert.wgsl index 579fe73e5..167778f89 100644 --- a/tests/out/quad-vert.wgsl +++ b/tests/out/quad-vert.wgsl @@ -16,7 +16,7 @@ var a_pos: vec2; fn main() { v_uv = a_uv; let _e13: vec2 = a_pos; - perVertexStruct.gl_Position = vec4(_e13[0], _e13[1], 0.0, 1.0); + perVertexStruct.gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); return; } diff --git a/tests/out/quad.wgsl b/tests/out/quad.wgsl index 43f161438..b853f09e3 100644 --- a/tests/out/quad.wgsl +++ b/tests/out/quad.wgsl @@ -18,8 +18,8 @@ fn main([[location(0)]] pos: vec2, [[location(1)]] uv1: vec2) -> Verte [[stage(fragment)]] fn main1([[location(0), interpolate(perspective)]] uv2: vec2) -> [[location(0)]] vec4 { let _e4: vec4 = textureSample(u_texture, u_sampler, uv2); - if ((_e4[3] == 0.0)) { + if ((_e4.w == 0.0)) { discard; } - return (_e4[3] * _e4); + return (_e4.w * _e4); } From 8246287561708847c4de90015f69bf9a2002f46f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 17 May 2021 20:16:39 -0700 Subject: [PATCH 0835/2212] [dot-out] Take advantage of Cow's implementation of `From`. --- src/back/dot/mod.rs | 54 ++++++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 30 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 487a5f946..2659ddc49 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -9,10 +9,7 @@ use crate::{ valid::{FunctionInfo, ModuleInfo}, }; -use std::{ - borrow::Cow, - fmt::{Error as FmtError, Write as _}, -}; +use std::fmt::{Error as FmtError, Write as _}; #[derive(Default)] struct StatementGraph { @@ -177,16 +174,16 @@ fn write_fun( E::Access { base, index } => { edges.insert("base", base); edges.insert("index", index); - (Cow::Borrowed("Access"), 1) + ("Access".into(), 1) } E::AccessIndex { base, index } => { edges.insert("base", base); - (Cow::Owned(format!("AccessIndex[{}]", index)), 1) + (format!("AccessIndex[{}]", index).into(), 1) } - E::Constant(_) => (Cow::Borrowed("Constant"), 2), + E::Constant(_) => ("Constant".into(), 2), E::Splat { size, value } => { edges.insert("value", value); - (Cow::Owned(format!("Splat{:?}", size)), 3) + (format!("Splat{:?}", size).into(), 3) } E::Swizzle { size, @@ -194,27 +191,24 @@ fn write_fun( pattern, } => { edges.insert("vector", vector); - ( - Cow::Owned(format!("Swizzle{:?}", &pattern[..size as usize])), - 3, - ) + (format!("Swizzle{:?}", &pattern[..size as usize]).into(), 3) } E::Compose { ref components, .. } => { payload = Some(Payload::Arguments(components)); - (Cow::Borrowed("Compose"), 3) + ("Compose".into(), 3) } - E::FunctionArgument(index) => (Cow::Owned(format!("Argument[{}]", index)), 1), + E::FunctionArgument(index) => (format!("Argument[{}]", index).into(), 1), E::GlobalVariable(h) => { payload = Some(Payload::Global(h)); - (Cow::Borrowed("Global"), 2) + ("Global".into(), 2) } E::LocalVariable(h) => { payload = Some(Payload::Local(h)); - (Cow::Borrowed("Local"), 1) + ("Local".into(), 1) } E::Load { pointer } => { edges.insert("pointer", pointer); - (Cow::Borrowed("Load"), 4) + ("Load".into(), 4) } E::ImageSample { image, @@ -248,7 +242,7 @@ fn write_fun( if let Some(expr) = depth_ref { edges.insert("depth_ref", expr); } - (Cow::Borrowed("ImageSample"), 5) + ("ImageSample".into(), 5) } E::ImageLoad { image, @@ -264,7 +258,7 @@ fn write_fun( if let Some(expr) = index { edges.insert("index", expr); } - (Cow::Borrowed("ImageLoad"), 5) + ("ImageLoad".into(), 5) } E::ImageQuery { image, query } => { edges.insert("image", image); @@ -273,20 +267,20 @@ fn write_fun( if let Some(expr) = level { edges.insert("level", expr); } - Cow::Borrowed("ImageSize") + std::borrow::Cow::from("ImageSize") } - _ => Cow::Owned(format!("{:?}", query)), + _ => format!("{:?}", query).into(), }; (args, 7) } E::Unary { op, expr } => { edges.insert("expr", expr); - (Cow::Owned(format!("{:?}", op)), 6) + (format!("{:?}", op).into(), 6) } E::Binary { op, left, right } => { edges.insert("left", left); edges.insert("right", right); - (Cow::Owned(format!("{:?}", op)), 6) + (format!("{:?}", op).into(), 6) } E::Select { condition, @@ -296,15 +290,15 @@ fn write_fun( edges.insert("condition", condition); edges.insert("accept", accept); edges.insert("reject", reject); - (Cow::Borrowed("Select"), 3) + ("Select".into(), 3) } E::Derivative { axis, expr } => { edges.insert("", expr); - (Cow::Owned(format!("d{:?}", axis)), 8) + (format!("d{:?}", axis).into(), 8) } E::Relational { fun, argument } => { edges.insert("arg", argument); - (Cow::Owned(format!("{:?}", fun)), 6) + (format!("{:?}", fun).into(), 6) } E::Math { fun, @@ -319,7 +313,7 @@ fn write_fun( if let Some(expr) = arg2 { edges.insert("arg2", expr); } - (Cow::Owned(format!("{:?}", fun)), 7) + (format!("{:?}", fun).into(), 7) } E::As { kind, @@ -331,12 +325,12 @@ fn write_fun( Some(width) => format!("Convert<{:?},{}>", kind, width), None => format!("Bitcast<{:?}>", kind), }; - (Cow::Owned(string), 3) + (string.into(), 3) } - E::Call(_function) => (Cow::Borrowed("Call"), 4), + E::Call(_function) => ("Call".into(), 4), E::ArrayLength(expr) => { edges.insert("", expr); - (Cow::Borrowed("ArrayLength"), 7) + ("ArrayLength".into(), 7) } }; From 4e3dc41f3f522a3244350b4cb27cad9670541279 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 17 May 2021 20:20:30 -0700 Subject: [PATCH 0836/2212] [wgsl-in] Use Cow in wgsl::ParseError. --- src/front/wgsl/mod.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 56343335d..b557315e2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -25,6 +25,7 @@ use codespan_reporting::{ }, }; use std::{ + borrow::Cow, io::{self, Write}, iter, num::NonZeroU32, @@ -140,7 +141,10 @@ impl<'a> Error<'a> { expected, &source[unexpected_span.clone()], ), - labels: vec![(unexpected_span.clone(), format!("expected {}", expected))], + labels: vec![( + unexpected_span.clone(), + format!("expected {}", expected).into(), + )], notes: vec![], }, Error::BadInteger(ref bad_span) => ParseError { @@ -148,7 +152,7 @@ impl<'a> Error<'a> { "expected integer literal, found `{}`", &source[bad_span.clone()], ), - labels: vec![(bad_span.clone(), "expected integer".to_string())], + labels: vec![(bad_span.clone(), "expected integer".into())], notes: vec![], }, Error::BadFloat(ref bad_span) => ParseError { @@ -156,15 +160,12 @@ impl<'a> Error<'a> { "expected floating-point literal, found `{}`", &source[bad_span.clone()], ), - labels: vec![( - bad_span.clone(), - "expected floating-point literal".to_string(), - )], + labels: vec![(bad_span.clone(), "expected floating-point literal".into())], notes: vec![], }, Error::BadScalarWidth(ref bad_span, width) => ParseError { message: format!("invalid width of `{}` for literal", width,), - labels: vec![(bad_span.clone(), "invalid width".to_string())], + labels: vec![(bad_span.clone(), "invalid width".into())], notes: vec!["valid width is 32".to_string()], }, Error::BadAccessor(ref accessor_span) => ParseError { @@ -172,12 +173,12 @@ impl<'a> Error<'a> { "invalid field accessor `{}`", &source[accessor_span.clone()], ), - labels: vec![(accessor_span.clone(), "invalid accessor".to_string())], + labels: vec![(accessor_span.clone(), "invalid accessor".into())], notes: vec![], }, Error::UnknownIdent(ref ident_span, ident) => ParseError { message: format!("unknown identifier: '{}'", ident), - labels: vec![(ident_span.clone(), "unknown identifier".to_string())], + labels: vec![(ident_span.clone(), "unknown identifier".into())], notes: vec![], }, ref error => ParseError { @@ -543,7 +544,7 @@ struct ParsedVariable<'a> { #[derive(Clone, Debug)] pub struct ParseError { message: String, - labels: Vec<(Span, String)>, + labels: Vec<(Span, Cow<'static, str>)>, notes: Vec, } From 5753f6e1072849c76fc40b6ea85c41e93cac1da3 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 18 May 2021 11:20:25 -0700 Subject: [PATCH 0837/2212] [wgsl-in] Improve error message for UnknownIdent. --- src/front/wgsl/mod.rs | 2 +- tests/wgsl-errors.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b557315e2..66feb04b5 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -177,7 +177,7 @@ impl<'a> Error<'a> { notes: vec![], }, Error::UnknownIdent(ref ident_span, ident) => ParseError { - message: format!("unknown identifier: '{}'", ident), + message: format!("no definition in scope for identifier: '{}'", ident), labels: vec![(ident_span.clone(), "unknown identifier".into())], notes: vec![], }, diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 87050a6de..db70992d2 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -83,7 +83,7 @@ fn unknown_identifier() { return x * schmoo; } "###, - r###"error: unknown identifier: 'schmoo' + r###"error: no definition in scope for identifier: 'schmoo' ┌─ wgsl:3:30 │ 3 │ return x * schmoo; From 6b3db1f487e63e8d5c5f130de965e362e57c1840 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 18 May 2021 21:31:24 +0300 Subject: [PATCH 0838/2212] [glsl-out] Write vector access as a swizzle --- src/back/glsl/mod.rs | 7 +++++-- tests/out/boids.Compute.glsl | 28 ++++++++++++++-------------- tests/out/quad-vert.Vertex.glsl | 2 +- tests/out/quad.Fragment.glsl | 4 ++-- tests/out/shadow.Fragment.glsl | 6 +++--- 5 files changed, 25 insertions(+), 22 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a9fe8ce04..c74011a68 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1527,8 +1527,11 @@ impl<'a, W: Write> Writer<'a, W> { }; match *resolved { - TypeInner::Vector { .. } - | TypeInner::Matrix { .. } + TypeInner::Vector { .. } => { + // Write vector access as a swizzle + write!(self.out, ".{}", COMPONENTS[index as usize])? + } + TypeInner::Matrix { .. } | TypeInner::Array { .. } | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, TypeInner::Struct { .. } => { diff --git a/tests/out/boids.Compute.glsl b/tests/out/boids.Compute.glsl index 343e25bc3..e518b6cc7 100644 --- a/tests/out/boids.Compute.glsl +++ b/tests/out/boids.Compute.glsl @@ -40,11 +40,11 @@ void main() { vec2 pos1; vec2 vel1; uint i = 0u; - if((global_invocation_id[0] >= 1500u)) { + if((global_invocation_id.x >= 1500u)) { return; } - vPos = _group_0_binding_1.particles[global_invocation_id[0]].pos; - vVel = _group_0_binding_1.particles[global_invocation_id[0]].vel; + vPos = _group_0_binding_1.particles[global_invocation_id.x].pos; + vVel = _group_0_binding_1.particles[global_invocation_id.x].vel; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); @@ -52,7 +52,7 @@ void main() { if((i >= 1500u)) { break; } - if((i == global_invocation_id[0])) { + if((i == global_invocation_id.x)) { continue; } pos1 = _group_0_binding_1.particles[i].pos; @@ -79,20 +79,20 @@ void main() { vVel = (((vVel + (cMass * _group_0_binding_0.rule1Scale)) + (colVel * _group_0_binding_0.rule2Scale)) + (cVel * _group_0_binding_0.rule3Scale)); vVel = (normalize(vVel) * clamp(length(vVel), 0.0, 0.1)); vPos = (vPos + (vVel * _group_0_binding_0.deltaT)); - if((vPos[0] < -1.0)) { - vPos[0] = 1.0; + if((vPos.x < -1.0)) { + vPos.x = 1.0; } - if((vPos[0] > 1.0)) { - vPos[0] = -1.0; + if((vPos.x > 1.0)) { + vPos.x = -1.0; } - if((vPos[1] < -1.0)) { - vPos[1] = 1.0; + if((vPos.y < -1.0)) { + vPos.y = 1.0; } - if((vPos[1] > 1.0)) { - vPos[1] = -1.0; + if((vPos.y > 1.0)) { + vPos.y = -1.0; } - _group_0_binding_2.particles[global_invocation_id[0]].pos = vPos; - _group_0_binding_2.particles[global_invocation_id[0]].vel = vVel; + _group_0_binding_2.particles[global_invocation_id.x].pos = vPos; + _group_0_binding_2.particles[global_invocation_id.x].vel = vVel; return; } diff --git a/tests/out/quad-vert.Vertex.glsl b/tests/out/quad-vert.Vertex.glsl index 3f3bb13ad..e1b9853b0 100644 --- a/tests/out/quad-vert.Vertex.glsl +++ b/tests/out/quad-vert.Vertex.glsl @@ -30,7 +30,7 @@ smooth layout(location = 0) out vec2 _vs2fs_location0; void main1() { v_uv = a_uv; vec2 _expr13 = a_pos; - perVertexStruct.gen_gl_Position = vec4(_expr13[0], _expr13[1], 0.0, 1.0); + perVertexStruct.gen_gl_Position = vec4(_expr13.x, _expr13.y, 0.0, 1.0); return; } diff --git a/tests/out/quad.Fragment.glsl b/tests/out/quad.Fragment.glsl index 8062e3d20..825f9bd4d 100644 --- a/tests/out/quad.Fragment.glsl +++ b/tests/out/quad.Fragment.glsl @@ -15,10 +15,10 @@ layout(location = 0) out vec4 _fs2p_location0; void main() { vec2 uv2 = _vs2fs_location0; vec4 _expr4 = texture(_group_0_binding_0, vec2(uv2)); - if((_expr4[3] == 0.0)) { + if((_expr4.w == 0.0)) { discard; } - _fs2p_location0 = (_expr4[3] * _expr4); + _fs2p_location0 = (_expr4.w * _expr4); return; } diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index e1310ca34..2042b5f22 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -23,10 +23,10 @@ smooth layout(location = 1) in vec4 _vs2fs_location1; layout(location = 0) out vec4 _fs2p_location0; float fetch_shadow(uint light_id, vec4 homogeneous_coords) { - if((homogeneous_coords[3] <= 0.0)) { + if((homogeneous_coords.w <= 0.0)) { return 1.0; } - float _expr26 = textureGrad(_group_0_binding_2, vec4((((homogeneous_coords.xy * vec2(0.5, -0.5)) / vec2(homogeneous_coords[3])) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] / homogeneous_coords[3])), vec2(0, 0), vec2(0,0)); + float _expr26 = textureGrad(_group_0_binding_2, vec4((((homogeneous_coords.xy * vec2(0.5, -0.5)) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0, 0), vec2(0,0)); return _expr26; } @@ -36,7 +36,7 @@ void main() { vec3 color1 = vec3(0.05, 0.05, 0.05); uint i = 0u; while(true) { - if((i >= min(_group_0_binding_0.num_lights[0], 10u))) { + if((i >= min(_group_0_binding_0.num_lights.x, 10u))) { break; } Light _expr21 = _group_0_binding_1.data[i]; From 6c1832c8eeeac15f1e85d6279b1c976427a727bc Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 19 May 2021 01:18:27 -0400 Subject: [PATCH 0839/2212] [spv-out] be smarter about deriving capabilities, auto derive them for tests --- src/back/msl/writer.rs | 4 +- src/back/spv/writer.rs | 65 ++++++++++++++++++++------------- tests/in/access.param.ron | 1 - tests/in/boids.param.ron | 1 - tests/in/collatz.param.ron | 1 - tests/in/control-flow.param.ron | 1 - tests/in/empty.param.ron | 1 - tests/in/extra.param.ron | 1 - tests/in/image.param.ron | 1 - tests/in/operators.param.ron | 1 - tests/in/quad-glsl.param.ron | 1 - tests/in/quad.param.ron | 1 - tests/in/shadow.param.ron | 1 - tests/in/skybox.param.ron | 1 - tests/in/standard.param.ron | 1 - tests/out/access.spvasm | 2 - tests/out/image.spvasm | 3 +- tests/snapshots.rs | 7 +++- 18 files changed, 49 insertions(+), 45 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 819a4f15f..97da4de05 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2428,7 +2428,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 17664 - if stack_size < 17000 || stack_size > 19000 { + if stack_size < 14000 || stack_size > 19000 { panic!("`put_expression` stack size {} has changed!", stack_size); } } @@ -2443,7 +2443,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 13600 - if stack_size < 12000 || stack_size > 14500 { + if stack_size < 11000 || stack_size > 14500 { panic!("`put_block` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 763cd0a6a..176f5f491 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -283,7 +283,7 @@ pub struct Writer { logical_layout: LogicalLayout, id_gen: IdGenerator, capabilities: crate::FastHashSet, - strict_capabilities: bool, + forbidden_caps: Option<&'static [spirv::Capability]>, debugs: Vec, annotations: Vec, flags: WriterFlags, @@ -313,19 +313,22 @@ impl Writer { let gl450_ext_inst_id = id_gen.next(); let void_type = id_gen.next(); + let (capabilities, forbidden_caps) = match options.capabilities { + Some(ref caps) => (caps.clone(), None), + None => { + let mut caps = crate::FastHashSet::default(); + caps.insert(spirv::Capability::Shader); + let forbidden: &[_] = &[spirv::Capability::Kernel]; + (caps, Some(forbidden)) + } + }; + Ok(Writer { physical_layout: PhysicalLayout::new(raw_version), logical_layout: LogicalLayout::default(), id_gen, - capabilities: match options.capabilities { - Some(ref caps) => caps.clone(), - None => { - let mut caps = crate::FastHashSet::default(); - caps.insert(spirv::Capability::Shader); - caps - } - }, - strict_capabilities: options.capabilities.is_some(), + capabilities, + forbidden_caps, debugs: vec![], annotations: vec![], flags: options.flags, @@ -344,20 +347,21 @@ impl Writer { } fn check(&mut self, capabilities: &[spirv::Capability]) -> Result<(), Error> { - if self.strict_capabilities { - if capabilities.is_empty() - || capabilities - .iter() - .any(|cap| self.capabilities.contains(cap)) - { - Ok(()) - } else { - Err(Error::MissingCapabilities(capabilities.to_vec())) - } - } else { - self.capabilities.extend(capabilities); - Ok(()) + if capabilities.is_empty() + || capabilities + .iter() + .any(|cap| self.capabilities.contains(cap)) + { + return Ok(()); } + if let Some(forbidden) = self.forbidden_caps { + // take the first allowed capability, blindly + if let Some(&cap) = capabilities.iter().find(|cap| !forbidden.contains(cap)) { + self.capabilities.insert(cap); + return Ok(()); + } + } + Err(Error::MissingCapabilities(capabilities.to_vec())) } fn get_type_id( @@ -887,7 +891,15 @@ impl Writer { let kind = match class { crate::ImageClass::Sampled { kind, multi: _ } => kind, crate::ImageClass::Depth => crate::ScalarKind::Float, - crate::ImageClass::Storage(format) => format.into(), + crate::ImageClass::Storage(format) => { + let required_caps: &[_] = match dim { + crate::ImageDimension::D1 => &[spirv::Capability::Image1D], + crate::ImageDimension::Cube => &[spirv::Capability::ImageCubeArray], + _ => &[], + }; + self.check(required_caps)?; + format.into() + } }; let local_type = LocalType::Value { vector_size: None, @@ -895,9 +907,9 @@ impl Writer { width: 4, pointer_class: None, }; - let type_id = self.get_type_id(arena, LookupType::Local(local_type))?; let dim = map_dim(dim); self.check(dim.required_capabilities())?; + let type_id = self.get_type_id(arena, LookupType::Local(local_type))?; Instruction::type_image(id, type_id, dim, arrayed, class) } crate::TypeInner::Sampler { comparison: _ } => Instruction::type_sampler(id), @@ -2212,6 +2224,8 @@ impl Writer { } }; + self.check(&[spirv::Capability::ImageQuery])?; + match query { Iq::Size { level } => { let dim_coords = match dim { @@ -2248,6 +2262,7 @@ impl Writer { (spirv::Op::ImageQuerySizeLod, Some(level_id)) } }; + // The ID of the vector returned by SPIR-V, which contains the dimensions // as well as the layer count. let id_extended = self.id_gen.next(); diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index e8c788d60..f7084220b 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -1,6 +1,5 @@ ( spv_version: (1, 1), - spv_capabilities: [ Shader, Image1D, Sampled1D ], spv_debug: true, spv_adjust_coordinate_space: false, msl_custom: true, diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index 16021ec3b..25413d0c4 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -1,6 +1,5 @@ ( spv_version: (1, 0), - spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: false, msl_custom: true, diff --git a/tests/in/collatz.param.ron b/tests/in/collatz.param.ron index 42c8480e4..6da4b84fd 100644 --- a/tests/in/collatz.param.ron +++ b/tests/in/collatz.param.ron @@ -1,5 +1,4 @@ ( spv_version: (1, 0), - spv_capabilities: [ Shader ], spv_debug: true, ) diff --git a/tests/in/control-flow.param.ron b/tests/in/control-flow.param.ron index d6269ab62..bd7d7cc3e 100644 --- a/tests/in/control-flow.param.ron +++ b/tests/in/control-flow.param.ron @@ -1,4 +1,3 @@ ( spv_version: (1, 1), - spv_capabilities: [ Shader ], ) diff --git a/tests/in/empty.param.ron b/tests/in/empty.param.ron index d6269ab62..bd7d7cc3e 100644 --- a/tests/in/empty.param.ron +++ b/tests/in/empty.param.ron @@ -1,4 +1,3 @@ ( spv_version: (1, 1), - spv_capabilities: [ Shader ], ) diff --git a/tests/in/extra.param.ron b/tests/in/extra.param.ron index 1767cbe3f..a0c5c775e 100644 --- a/tests/in/extra.param.ron +++ b/tests/in/extra.param.ron @@ -1,5 +1,4 @@ ( god_mode: true, spv_version: (1, 0), - spv_capabilities: [ Shader ], ) diff --git a/tests/in/image.param.ron b/tests/in/image.param.ron index 703113755..aca18ab38 100644 --- a/tests/in/image.param.ron +++ b/tests/in/image.param.ron @@ -1,5 +1,4 @@ ( spv_version: (1, 1), - spv_capabilities: [ Shader, ImageQuery, Image1D, Sampled1D ], spv_debug: true, ) diff --git a/tests/in/operators.param.ron b/tests/in/operators.param.ron index 553f5e75f..8b306e5b7 100644 --- a/tests/in/operators.param.ron +++ b/tests/in/operators.param.ron @@ -1,4 +1,3 @@ ( spv_version: (1, 0), - spv_capabilities: [ Shader ], ) diff --git a/tests/in/quad-glsl.param.ron b/tests/in/quad-glsl.param.ron index c073cf1a5..a049e71aa 100644 --- a/tests/in/quad-glsl.param.ron +++ b/tests/in/quad-glsl.param.ron @@ -1,6 +1,5 @@ ( spv_version: (1, 0), - spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: true, ) diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index c073cf1a5..a049e71aa 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -1,6 +1,5 @@ ( spv_version: (1, 0), - spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: true, ) diff --git a/tests/in/shadow.param.ron b/tests/in/shadow.param.ron index c6b43089b..63926c63c 100644 --- a/tests/in/shadow.param.ron +++ b/tests/in/shadow.param.ron @@ -1,6 +1,5 @@ ( spv_version: (1, 2), - spv_capabilities: [ Shader ], spv_debug: true, spv_adjust_coordinate_space: true, ) diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index d4510ffcb..9a5bf7d2b 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -1,7 +1,6 @@ ( spv_flow_dump_prefix: "", spv_version: (1, 0), - spv_capabilities: [ Shader ], spv_debug: false, spv_adjust_coordinate_space: false, msl_custom: true, diff --git a/tests/in/standard.param.ron b/tests/in/standard.param.ron index 1eb59329e..d6d9d69be 100644 --- a/tests/in/standard.param.ron +++ b/tests/in/standard.param.ron @@ -1,5 +1,4 @@ ( spv_version: (1, 0), - spv_capabilities: [ Shader ], spv_adjust_coordinate_space: false, ) diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm index 894968b5f..2f5c21665 100644 --- a/tests/out/access.spvasm +++ b/tests/out/access.spvasm @@ -2,9 +2,7 @@ ; Version: 1.1 ; Generator: rspirv ; Bound: 49 -OpCapability Image1D OpCapability Shader -OpCapability Sampled1D OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 diff --git a/tests/out/image.spvasm b/tests/out/image.spvasm index e0cac29d4..08d1f5a8e 100644 --- a/tests/out/image.spvasm +++ b/tests/out/image.spvasm @@ -2,10 +2,9 @@ ; Version: 1.1 ; Generator: rspirv ; Bound: 127 -OpCapability ImageQuery OpCapability Image1D OpCapability Shader -OpCapability Sampled1D +OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %43 "main" %40 diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 8882f9600..b7410e416 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -26,6 +26,7 @@ struct Parameters { #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_version: (u8, u8), #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + #[serde(default)] spv_capabilities: naga::FastHashSet, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] #[serde(default)] @@ -139,7 +140,11 @@ fn check_output_spv( let options = spv::Options { lang_version: params.spv_version, flags, - capabilities: Some(params.spv_capabilities.clone()), + capabilities: if params.spv_capabilities.is_empty() { + None + } else { + Some(params.spv_capabilities.clone()) + }, }; let spv = spv::write_vec(module, info, &options).unwrap(); From 12e6dc591792dc549f78e2186c64fa99914d81c4 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sun, 16 May 2021 01:09:58 +0300 Subject: [PATCH 0840/2212] [wgsl-out] Implement all statements and expressions. Enable all wgsl-in tests --- src/back/wgsl/writer.rs | 254 ++++++++++++++++++++++++++++++++---- tests/out/access.wgsl | 13 ++ tests/out/boids.wgsl | 100 ++++++++++++++ tests/out/collatz.wgsl | 33 +++++ tests/out/control-flow.wgsl | 6 + tests/out/extra.wgsl | 12 ++ tests/out/interface.wgsl | 25 ++++ tests/out/interpolate.wgsl | 30 +++++ tests/out/operators.wgsl | 12 ++ tests/out/quad-vert.wgsl | 8 +- tests/out/shadow.wgsl | 54 ++++++++ tests/out/skybox.wgsl | 34 +++++ tests/out/standard.wgsl | 7 + tests/snapshots.rs | 41 ++++-- 14 files changed, 587 insertions(+), 42 deletions(-) create mode 100644 tests/out/access.wgsl create mode 100644 tests/out/boids.wgsl create mode 100644 tests/out/collatz.wgsl create mode 100644 tests/out/control-flow.wgsl create mode 100644 tests/out/extra.wgsl create mode 100644 tests/out/interface.wgsl create mode 100644 tests/out/interpolate.wgsl create mode 100644 tests/out/operators.wgsl create mode 100644 tests/out/shadow.wgsl create mode 100644 tests/out/skybox.wgsl create mode 100644 tests/out/standard.wgsl diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 214cdece7..6bc3d6e09 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1,13 +1,12 @@ -// TODO: temp -#![allow(dead_code)] use super::Error; use crate::{ back::{binary_operation_str, vector_size_str, wgsl::keywords::RESERVED}, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, - Arena, ArraySize, Binding, Constant, Expression, FastHashMap, Function, GlobalVariable, Handle, - ImageClass, ImageDimension, Interpolation, Module, SampleLevel, Sampling, ScalarKind, - ScalarValue, ShaderStage, Statement, StorageFormat, StructMember, Type, TypeInner, + Arena, ArraySize, Binding, Constant, ConstantInner, Expression, FastHashMap, Function, + GlobalVariable, Handle, ImageClass, ImageDimension, Interpolation, Module, SampleLevel, + Sampling, ScalarKind, ScalarValue, ShaderStage, Statement, StorageClass, StorageFormat, + StructMember, Type, TypeInner, }; use bit_set::BitSet; use std::fmt::Write; @@ -107,7 +106,7 @@ impl Writer { // Write all constants for (handle, constant) in module.constants.iter() { if constant.name.is_some() { - self.write_global_constant(&constant, handle)?; + self.write_global_constant(&module, &constant.inner, handle)?; } } @@ -173,7 +172,7 @@ impl Writer { fn write_scalar_value(&mut self, value: ScalarValue) -> BackendResult { match value { ScalarValue::Sint(value) => write!(self.out, "{}", value)?, - ScalarValue::Uint(value) => write!(self.out, "{}", value)?, + ScalarValue::Uint(value) => write!(self.out, "{}u", value)?, // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero ScalarValue::Float(value) => write!(self.out, "{:?}", value)?, @@ -501,7 +500,7 @@ impl Writer { if multi { "multisampled_" } else { "" }, format!("<{}>", scalar_kind_str(kind)), ), - ImageClass::Depth => ("depth", "", String::from("")), + ImageClass::Depth => ("depth_", "", String::from("")), ImageClass::Storage(storage_format) => ( "storage_", "", @@ -682,8 +681,105 @@ impl Writer { self.write_expr(module, value, func_ctx)?; writeln!(self.out, ");")?; } - _ => { - return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))); + // TODO: copy-paste from glsl-out + Statement::Block(ref block) => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "{{")?; + for sta in block.iter() { + // Increase the indentation to help with readability + self.write_stmt(module, sta, func_ctx, indent + 1)? + } + writeln!(self.out, "{}}}", INDENT.repeat(indent))? + } + Statement::Switch { + selector, + ref cases, + ref default, + } => { + // Start the switch + write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "switch(")?; + self.write_expr(module, selector, func_ctx)?; + writeln!(self.out, ") {{")?; + + // Write all cases + let mut write_case = true; + let all_fall_through = cases + .iter() + .all(|case| case.fall_through && case.body.is_empty()); + if !cases.is_empty() { + for case in cases { + if write_case { + write!(self.out, "{}case ", INDENT.repeat(indent + 1))?; + } + if !all_fall_through && case.fall_through && case.body.is_empty() { + write_case = false; + write!(self.out, "{}, ", case.value)?; + continue; + } else { + write_case = true; + writeln!(self.out, "{}: {{", case.value)?; + } + + for sta in case.body.iter() { + self.write_stmt(module, sta, func_ctx, indent + 2)?; + } + + if case.fall_through { + writeln!(self.out, "{}fallthrough;", INDENT.repeat(indent + 2))?; + } + } + + writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; + } + + if !default.is_empty() { + writeln!(self.out, "{}default: {{", INDENT.repeat(indent + 1))?; + + for sta in default { + self.write_stmt(module, sta, func_ctx, indent + 2)?; + } + + writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))? + } + + writeln!(self.out, "{}}}", INDENT.repeat(indent))? + } + Statement::Loop { + ref body, + ref continuing, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "loop {{")?; + + for sta in body.iter() { + self.write_stmt(module, sta, func_ctx, indent + 1)?; + } + + if !continuing.is_empty() { + writeln!(self.out, "{}continuing {{", INDENT.repeat(indent + 1))?; + for sta in continuing.iter() { + self.write_stmt(module, sta, func_ctx, indent + 2)?; + } + writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; + } + + writeln!(self.out, "{}}}", INDENT.repeat(indent))? + } + Statement::Break => { + writeln!(self.out, "{}break;", INDENT.repeat(indent))?; + } + Statement::Continue => { + writeln!(self.out, "{}continue;", INDENT.repeat(indent))?; + } + Statement::Barrier(barrier) => { + if barrier.contains(crate::Barrier::STORAGE) { + writeln!(self.out, "{}storageBarrier();", INDENT.repeat(indent))?; + } + + if barrier.contains(crate::Barrier::WORK_GROUP) { + writeln!(self.out, "{}workgroupBarrier();", INDENT.repeat(indent))?; + } } } @@ -969,7 +1065,6 @@ impl Writer { } write!(self.out, ")")?; } - // TODO: copy-paste from msl-out Expression::GlobalVariable(handle) => { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; @@ -1023,7 +1118,6 @@ impl Writer { self.write_expr(module, value, func_ctx)?; write!(self.out, ")")?; } - //TODO: add pointer logic Expression::Load { pointer } => self.write_expr(module, pointer, func_ctx)?, Expression::LocalVariable(handle) => { let name_key = match func_ctx.ty { @@ -1036,6 +1130,9 @@ impl Writer { } Expression::ArrayLength(expr) => { write!(self.out, "arrayLength(")?; + if is_deref_required(expr, module, func_ctx.info) { + write!(self.out, "&")?; + }; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")?; } @@ -1128,8 +1225,67 @@ impl Writer { self.out.write_char(COMPONENTS[sc as usize])?; } } - _ => { - return Err(Error::Unimplemented(format!("write_expr {:?}", expression))); + Expression::Unary { op, expr } => { + let unary = match op { + crate::UnaryOperator::Negate => "-", + crate::UnaryOperator::Not => { + match *func_ctx.info[expr].ty.inner_with(&module.types) { + TypeInner::Scalar { + kind: ScalarKind::Bool, + .. + } + | TypeInner::Vector { .. } => "!", + _ => "~", + } + } + }; + + write!(self.out, "{}(", unary)?; + self.write_expr(module, expr, func_ctx)?; + + write!(self.out, ")")? + } + Expression::Select { + condition, + accept, + reject, + } => { + write!(self.out, "select(")?; + self.write_expr(module, accept, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, reject, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, condition, func_ctx)?; + write!(self.out, ")")? + } + Expression::Derivative { axis, expr } => { + let op = match axis { + crate::DerivativeAxis::X => "dpdx", + crate::DerivativeAxis::Y => "dpdy", + crate::DerivativeAxis::Width => "fwidth", + }; + write!(self.out, "{}(", op)?; + self.write_expr(module, expr, func_ctx)?; + write!(self.out, ")")? + } + Expression::Relational { fun, argument } => { + let fun_name = match fun { + crate::RelationalFunction::IsFinite => "isFinite", + crate::RelationalFunction::IsInf => "isInf", + crate::RelationalFunction::IsNan => "isNan", + crate::RelationalFunction::IsNormal => "isNormal", + crate::RelationalFunction::All => "all", + crate::RelationalFunction::Any => "any", + }; + write!(self.out, "{}(", fun_name)?; + + self.write_expr(module, argument, func_ctx)?; + + write!(self.out, ")")? + } + Expression::Call(function) => { + let func_name = &self.names[&NameKey::Function(function)]; + write!(self.out, "{}(", func_name)? } } @@ -1158,8 +1314,12 @@ impl Writer { writeln!(self.out)?; } - // First write only global name - write!(self.out, "var {}: ", name)?; + // First write global name and storage class if supported + write!(self.out, "var")?; + if let Some(storage_class) = storage_class_str(global.class) { + write!(self.out, "<{}>", storage_class)?; + } + write!(self.out, " {}: ", name)?; // Write access attribute if present if !global.storage_access.is_empty() { self.write_attributes(&[Attribute::Access(global.storage_access)], true)?; @@ -1215,10 +1375,11 @@ impl Writer { /// Ends in a newline fn write_global_constant( &mut self, - constant: &Constant, + module: &Module, + inner: &ConstantInner, handle: Handle, ) -> BackendResult { - match constant.inner { + match *inner { crate::ConstantInner::Scalar { width: _, ref value, @@ -1232,7 +1393,7 @@ impl Writer { write!(self.out, "i32 = {}", value)?; } crate::ScalarValue::Uint(value) => { - write!(self.out, "u32 = {}", value)?; + write!(self.out, "u32 = {}u", value)?; } crate::ScalarValue::Float(value) => { // Floats are written using `Debug` instead of `Display` because it always appends the @@ -1243,18 +1404,33 @@ impl Writer { write!(self.out, "bool = {}", value)?; } }; - // End with semicolon and extra newline for readability + // End with semicolon writeln!(self.out, ";")?; - writeln!(self.out)?; } - _ => { - return Err(Error::Unimplemented(format!( - "write_global_constant {:?}", - constant.inner - ))); + ConstantInner::Composite { ty, ref components } => { + let name = self.names[&NameKey::Constant(handle)].clone(); + // First write only constant name + write!(self.out, "let {}: ", name)?; + // Next write constant type + self.write_type(module, ty)?; + + write!(self.out, " = ")?; + self.write_type(module, ty)?; + + write!(self.out, "(")?; + for (index, constant) in components.iter().enumerate() { + self.write_constant(module, *constant)?; + // Only write a comma if isn't the last element + if index != components.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } + write!(self.out, ");")?; } } - + // End with extra newline for readability + writeln!(self.out)?; Ok(()) } @@ -1355,6 +1531,17 @@ fn sampling_str(sampling: Sampling) -> &'static str { } } +fn storage_class_str(storage_class: StorageClass) -> Option<&'static str> { + match storage_class { + StorageClass::Private => Some("private"), + StorageClass::Uniform => Some("uniform"), + StorageClass::Storage => Some("storage"), + StorageClass::PushConstant => Some("push_constant"), + StorageClass::WorkGroup => Some("workgroup"), + StorageClass::Function | StorageClass::Handle => None, + } +} + fn map_binding_to_attribute(binding: &Binding) -> Vec { match *binding { Binding::BuiltIn(built_in) => vec![Attribute::BuiltIn(built_in)], @@ -1368,3 +1555,16 @@ fn map_binding_to_attribute(binding: &Binding) -> Vec { ], } } + +fn is_deref_required(expr: Handle, module: &Module, info: &FunctionInfo) -> bool { + let base_ty_res = &info[expr].ty; + let resolved = base_ty_res.inner_with(&module.types); + match *resolved { + TypeInner::Pointer { base, class: _ } => match module.types[base].inner { + TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Array { .. } => true, + _ => false, + }, + TypeInner::ValuePointer { .. } => true, + _ => false, + } +} diff --git a/tests/out/access.wgsl b/tests/out/access.wgsl new file mode 100644 index 000000000..dfbbb1b7d --- /dev/null +++ b/tests/out/access.wgsl @@ -0,0 +1,13 @@ +[[block]] +struct Bar { + matrix: mat4x4; + data: [[stride(4)]] array; +}; + +[[group(0), binding(0)]] +var bar: [[access(read_write)]] Bar; + +[[stage(vertex)]] +fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { + return vec4(vec4(array(bar.data[(arrayLength(&bar.data) - 1u)], i32(bar.matrix[3u].x), 3, 4, 5)[vi])); +} diff --git a/tests/out/boids.wgsl b/tests/out/boids.wgsl new file mode 100644 index 000000000..b1437ab8f --- /dev/null +++ b/tests/out/boids.wgsl @@ -0,0 +1,100 @@ +struct Particle { + pos: vec2; + vel: vec2; +}; + +[[block]] +struct SimParams { + deltaT: f32; + rule1Distance: f32; + rule2Distance: f32; + rule3Distance: f32; + rule1Scale: f32; + rule2Scale: f32; + rule3Scale: f32; +}; + +[[block]] +struct Particles { + particles: [[stride(16)]] array; +}; + +let NUM_PARTICLES: u32 = 1500u; + +[[group(0), binding(0)]] +var params: SimParams; +[[group(0), binding(1)]] +var particlesSrc: [[access(read)]] Particles; +[[group(0), binding(2)]] +var particlesDst: [[access(read_write)]] Particles; + +[[stage(compute), workgroup_size(64, 1, 1)]] +fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { + var vPos: vec2; + var vVel: vec2; + var cMass: vec2; + var cVel: vec2; + var colVel: vec2; + var cMassCount: i32 = 0; + var cVelCount: i32 = 0; + var pos1: vec2; + var vel1: vec2; + var i: u32 = 0u; + + if ((global_invocation_id.x >= NUM_PARTICLES)) { + return; + } + vPos = particlesSrc.particles[global_invocation_id.x].pos; + vVel = particlesSrc.particles[global_invocation_id.x].vel; + cMass = vec2(0.0, 0.0); + cVel = vec2(0.0, 0.0); + colVel = vec2(0.0, 0.0); + loop { + if ((i >= NUM_PARTICLES)) { + break; + } + if ((i == global_invocation_id.x)) { + continue; + } + pos1 = particlesSrc.particles[i].pos; + vel1 = particlesSrc.particles[i].vel; + if ((distance(pos1, vPos) < params.rule1Distance)) { + cMass = (cMass + pos1); + cMassCount = (cMassCount + 1); + } + if ((distance(pos1, vPos) < params.rule2Distance)) { + colVel = (colVel - (pos1 - vPos)); + } + if ((distance(pos1, vPos) < params.rule3Distance)) { + cVel = (cVel + vel1); + cVelCount = (cVelCount + 1); + } + continuing { + i = (i + 1u); + } + } + if ((cMassCount > 0)) { + cMass = ((cMass / vec2(f32(cMassCount))) - vPos); + } + if ((cVelCount > 0)) { + cVel = (cVel / vec2(f32(cVelCount))); + } + vVel = (((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale)); + vVel = (normalize(vVel) * clamp(length(vVel), 0.0, 0.1)); + vPos = (vPos + (vVel * params.deltaT)); + if ((vPos.x < -1.0)) { + vPos.x = 1.0; + } + if ((vPos.x > 1.0)) { + vPos.x = -1.0; + } + if ((vPos.y < -1.0)) { + vPos.y = 1.0; + } + if ((vPos.y > 1.0)) { + vPos.y = -1.0; + } + particlesDst.particles[global_invocation_id.x].pos = vPos; + particlesDst.particles[global_invocation_id.x].vel = vVel; + return; +} diff --git a/tests/out/collatz.wgsl b/tests/out/collatz.wgsl new file mode 100644 index 000000000..e8c09d91c --- /dev/null +++ b/tests/out/collatz.wgsl @@ -0,0 +1,33 @@ +[[block]] +struct PrimeIndices { + data: [[stride(4)]] array; +}; + +[[group(0), binding(0)]] +var v_indices: [[access(read_write)]] PrimeIndices; + +fn collatz_iterations(n_base: u32) -> u32 { + var n: u32; + var i: u32 = 0u; + + n = n_base; + loop { + if ((n <= 1u)) { + break; + } + if (((n % 2u) == 0u)) { + n = (n / 2u); + } else { + n = ((3u * n) + 1u); + } + i = (i + 1u); + } + return i; +} + +[[stage(compute), workgroup_size(1, 1, 1)]] +fn main([[builtin(global_invocation_id)]] global_id: vec3) { + let _e9: u32 = collatz_iterations(v_indices.data[global_id.x]); + v_indices.data[global_id.x] = _e9; + return; +} diff --git a/tests/out/control-flow.wgsl b/tests/out/control-flow.wgsl new file mode 100644 index 000000000..31b2fa2cb --- /dev/null +++ b/tests/out/control-flow.wgsl @@ -0,0 +1,6 @@ +[[stage(compute), workgroup_size(1, 1, 1)]] +fn main([[builtin(global_invocation_id)]] global_id: vec3) { + storageBarrier(); + workgroupBarrier(); + return; +} diff --git a/tests/out/extra.wgsl b/tests/out/extra.wgsl new file mode 100644 index 000000000..8db56b157 --- /dev/null +++ b/tests/out/extra.wgsl @@ -0,0 +1,12 @@ +[[block]] +struct PushConstants { + index: u32; + double: vec2; +}; + +var pc: PushConstants; + +[[stage(fragment)]] +fn main([[location(0), interpolate(perspective)]] color: vec4) -> [[location(0)]] vec4 { + return color; +} diff --git a/tests/out/interface.wgsl b/tests/out/interface.wgsl new file mode 100644 index 000000000..90b76ff7b --- /dev/null +++ b/tests/out/interface.wgsl @@ -0,0 +1,25 @@ +struct VertexOutput { + [[builtin(position)]] position: vec4; + [[location(1), interpolate(perspective)]] varying: f32; +}; + +struct FragmentOutput { + [[builtin(frag_depth)]] depth: f32; + [[builtin(sample_mask)]] sample_mask: u32; + [[location(0)]] color: f32; +}; + +[[stage(vertex)]] +fn vertex([[builtin(vertex_index)]] vertex_index: u32, [[builtin(instance_index)]] instance_index: u32, [[location(10)]] color1: u32) -> VertexOutput { + return VertexOutput(vec4(1.0), f32(((vertex_index + instance_index) + color1))); +} + +[[stage(fragment)]] +fn fragment(in: VertexOutput, [[builtin(front_facing)]] front_facing: bool, [[builtin(sample_index)]] sample_index: u32, [[builtin(sample_mask)]] sample_mask1: u32) -> FragmentOutput { + return FragmentOutput(in.varying, (sample_mask1 & (1u << sample_index)), select(0.0, 1.0, front_facing)); +} + +[[stage(compute), workgroup_size(1, 1, 1)]] +fn compute([[builtin(global_invocation_id)]] global_id: vec3, [[builtin(local_invocation_id)]] local_id: vec3, [[builtin(local_invocation_index)]] local_index: u32, [[builtin(workgroup_id)]] wg_id: vec3) { + return; +} diff --git a/tests/out/interpolate.wgsl b/tests/out/interpolate.wgsl new file mode 100644 index 000000000..ceebf56f2 --- /dev/null +++ b/tests/out/interpolate.wgsl @@ -0,0 +1,30 @@ +struct FragmentInput { + [[builtin(position)]] position: vec4; + [[location(0), interpolate(flat)]] flat: u32; + [[location(1), interpolate(linear)]] linear: f32; + [[location(2), interpolate(linear,centroid)]] linear_centroid: vec2; + [[location(3), interpolate(linear,sample)]] linear_sample: vec3; + [[location(4), interpolate(perspective)]] perspective: vec4; + [[location(5), interpolate(perspective,centroid)]] perspective_centroid: f32; + [[location(6), interpolate(perspective,sample)]] perspective_sample: f32; +}; + +[[stage(vertex)]] +fn main() -> FragmentInput { + var out: FragmentInput; + + out.position = vec4(2.0, 4.0, 5.0, 6.0); + out.flat = 8u; + out.linear = 27.0; + out.linear_centroid = vec2(64.0, 125.0); + out.linear_sample = vec3(216.0, 343.0, 512.0); + out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + out.perspective_centroid = 2197.0; + out.perspective_sample = 2744.0; + return out; +} + +[[stage(fragment)]] +fn main1(val: FragmentInput) { + return; +} diff --git a/tests/out/operators.wgsl b/tests/out/operators.wgsl new file mode 100644 index 000000000..aad7a5c03 --- /dev/null +++ b/tests/out/operators.wgsl @@ -0,0 +1,12 @@ +fn splat() -> vec4 { + return ((((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)).xyxy + vec4((vec4(5) % vec4(2)))); +} + +fn unary() -> i32 { + if (!(true)) { + return 1; + } else { + return ~(1); + } +} + diff --git a/tests/out/quad-vert.wgsl b/tests/out/quad-vert.wgsl index 167778f89..cadca2a4a 100644 --- a/tests/out/quad-vert.wgsl +++ b/tests/out/quad-vert.wgsl @@ -8,10 +8,10 @@ struct VertexOutput { [[builtin(position)]] gl_Position1: vec4; }; -var v_uv: vec2; -var a_uv: vec2; -var perVertexStruct: gl_PerVertex; -var a_pos: vec2; +var v_uv: vec2; +var a_uv: vec2; +var perVertexStruct: gl_PerVertex; +var a_pos: vec2; fn main() { v_uv = a_uv; diff --git a/tests/out/shadow.wgsl b/tests/out/shadow.wgsl new file mode 100644 index 000000000..20731bc10 --- /dev/null +++ b/tests/out/shadow.wgsl @@ -0,0 +1,54 @@ +[[block]] +struct Globals { + num_lights: vec4; +}; + +struct Light { + proj: mat4x4; + pos: vec4; + color: vec4; +}; + +[[block]] +struct Lights { + data: [[stride(96)]] array; +}; + +let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); +let c_max_lights: u32 = 10u; + +[[group(0), binding(0)]] +var u_globals: Globals; +[[group(0), binding(1)]] +var s_lights: [[access(read)]] Lights; +[[group(0), binding(2)]] +var t_shadow: texture_depth_2d_array; +[[group(0), binding(3)]] +var sampler_shadow: sampler_comparison; + +fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { + if ((homogeneous_coords.w <= 0.0)) { + return 1.0; + } + let _e26: f32 = textureSampleCompare(t_shadow, sampler_shadow, (((homogeneous_coords.xy * vec2(0.5, -0.5)) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)), i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); + return _e26; +} + +[[stage(fragment)]] +fn fs_main([[location(0), interpolate(perspective)]] raw_normal: vec3, [[location(1), interpolate(perspective)]] position: vec4) -> [[location(0)]] vec4 { + var color1: vec3 = vec3(0.05, 0.05, 0.05); + var i: u32 = 0u; + + loop { + if ((i >= min(u_globals.num_lights.x, c_max_lights))) { + break; + } + let _e21: Light = s_lights.data[i]; + let _e25: f32 = fetch_shadow(i, (_e21.proj * position)); + color1 = (color1 + ((_e25 * max(0.0, dot(normalize(raw_normal), normalize((_e21.pos.xyz - position.xyz))))) * _e21.color.xyz)); + continuing { + i = (i + 1u); + } + } + return vec4(color1, 1.0); +} diff --git a/tests/out/skybox.wgsl b/tests/out/skybox.wgsl new file mode 100644 index 000000000..a0e0112e9 --- /dev/null +++ b/tests/out/skybox.wgsl @@ -0,0 +1,34 @@ +struct VertexOutput { + [[builtin(position)]] position: vec4; + [[location(0), interpolate(perspective)]] uv: vec3; +}; + +[[block]] +struct Data { + proj_inv: mat4x4; + view: mat4x4; +}; + +[[group(0), binding(0)]] +var r_data: Data; +[[group(0), binding(1)]] +var r_texture: texture_cube; +[[group(0), binding(2)]] +var r_sampler: sampler; + +[[stage(vertex)]] +fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { + var tmp1_: i32; + var tmp2_: i32; + + tmp1_ = (i32(vertex_index) / 2); + tmp2_ = (i32(vertex_index) & 1); + let _e24: vec4 = vec4(((f32(tmp1_) * 4.0) - 1.0), ((f32(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + return VertexOutput(_e24, (transpose(mat3x3(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz)) * (r_data.proj_inv * _e24).xyz)); +} + +[[stage(fragment)]] +fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 { + let _e5: vec4 = textureSample(r_texture, r_sampler, in.uv); + return _e5; +} diff --git a/tests/out/standard.wgsl b/tests/out/standard.wgsl new file mode 100644 index 000000000..90f74e871 --- /dev/null +++ b/tests/out/standard.wgsl @@ -0,0 +1,7 @@ +[[stage(fragment)]] +fn derivatives([[builtin(position)]] foo: vec4) -> [[location(0)]] vec4 { + let _e1: vec4 = dpdx(foo); + let _e2: vec4 = dpdy(foo); + let _e3: vec4 = fwidth(foo); + return ((_e1 + _e2) * _e3); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b7410e416..080eaf129 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -252,28 +252,47 @@ fn convert_wgsl() { "quad", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::DOT | Targets::WGSL, ), - ("boids", Targets::SPIRV | Targets::METAL | Targets::GLSL), - ("skybox", Targets::SPIRV | Targets::METAL | Targets::GLSL), + ( + "boids", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + ), + ( + "skybox", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + ), ( "collatz", - Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS, + Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS | Targets::WGSL, + ), + ( + "shadow", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, ), - ("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL), ("image", Targets::SPIRV | Targets::METAL | Targets::WGSL), - ("extra", Targets::SPIRV | Targets::METAL), - ("operators", Targets::SPIRV | Targets::METAL | Targets::GLSL), + ("extra", Targets::SPIRV | Targets::METAL | Targets::WGSL), + ( + "operators", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + ), ( "interpolate", - Targets::SPIRV | Targets::METAL | Targets::GLSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, ), - ("access", Targets::SPIRV | Targets::METAL), + ("access", Targets::SPIRV | Targets::METAL | Targets::WGSL), ( "control-flow", - Targets::SPIRV | Targets::METAL | Targets::GLSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + ), + ( + "standard", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + ), + ( + "standard", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, ), - ("standard", Targets::SPIRV | Targets::METAL | Targets::GLSL), //TODO: GLSL https://github.com/gfx-rs/naga/issues/874 - ("interface", Targets::SPIRV | Targets::METAL), + ("interface", Targets::SPIRV | Targets::METAL | Targets::WGSL), ]; for &(name, targets) in inputs.iter() { From ff8f15e0342a5729ac935c6c278a16d710cbde39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 25 Apr 2021 16:47:30 +0100 Subject: [PATCH 0841/2212] [glsl-in] Start writting a parser without pomelo --- Cargo.toml | 3 +- src/front/glsl/error.rs | 3 +- src/front/glsl/lex.rs | 270 ++++--- src/front/glsl/mod.rs | 16 +- src/front/glsl/parser.rs | 1313 ++------------------------------ src/front/glsl/parser_tests.rs | 416 +++++----- src/front/glsl/token.rs | 101 +++ tests/snapshots.rs | 11 +- 8 files changed, 560 insertions(+), 1573 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c0f34d8bd..1809e624e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,6 @@ fxhash = "0.2" log = "0.4" num-traits = "0.2" spirv = { package = "spirv_headers", version = "1.5", optional = true } -pomelo = { version = "0.1.4", optional = true } thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } @@ -31,7 +30,7 @@ pp-rs = { version = "0.1", optional = true } [features] default = [] dot-out = [] -glsl-in = ["pomelo", "pp-rs"] +glsl-in = ["pp-rs"] glsl-validate = [] glsl-out = ["petgraph"] msl-out = [] diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index a0daaccf1..87d00075b 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -1,5 +1,4 @@ -use super::parser::Token; -use super::token::TokenMetadata; +use super::token::{Token, TokenMetadata}; use std::{borrow::Cow, fmt, io}; //TODO: use `thiserror` diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 08874dfee..c7c643df3 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -1,8 +1,11 @@ -use super::{parser::Token, token::TokenMetadata, types::parse_type}; +use super::{ + token::{Token, TokenMetadata, TokenValue}, + types::parse_type, +}; use crate::FastHashMap; use pp_rs::{ pp::Preprocessor, - token::{Punct, Token as PPToken, TokenValue}, + token::{Punct, Token as PPToken, TokenValue as PPTokenValue}, }; use std::collections::VecDeque; @@ -40,7 +43,10 @@ impl<'a> Iterator for Lexer<'a> { meta.chars.start = loc.pos as usize; //TODO: proper location end meta.chars.end = loc.pos as usize + 1; - return Some(Token::Unknown((meta, err))); + return Some(Token { + value: TokenValue::Unknown(err), + meta, + }); } }, }; @@ -49,129 +55,131 @@ impl<'a> Iterator for Lexer<'a> { meta.chars.start = pp_token.location.pos as usize; //TODO: proper location end meta.chars.end = pp_token.location.pos as usize + 1; - Some(match pp_token.value { - TokenValue::Extension(extension) => { + let value = match pp_token.value { + PPTokenValue::Extension(extension) => { for t in extension.tokens { self.tokens.push_back(t); } - Token::Extension((meta, ())) + TokenValue::Extension } - TokenValue::Float(float) => Token::FloatConstant((meta, float.value)), - TokenValue::Ident(ident) => { + PPTokenValue::Float(float) => TokenValue::FloatConstant(float.value), + PPTokenValue::Ident(ident) => { match ident.as_str() { - "layout" => Token::Layout(meta), - "in" => Token::In(meta), - "out" => Token::Out(meta), - "uniform" => Token::Uniform(meta), - "flat" => Token::Interpolation((meta, crate::Interpolation::Flat)), - "noperspective" => Token::Interpolation((meta, crate::Interpolation::Linear)), - "smooth" => Token::Interpolation((meta, crate::Interpolation::Perspective)), - "centroid" => Token::Sampling((meta, crate::Sampling::Centroid)), - "sample" => Token::Sampling((meta, crate::Sampling::Sample)), + "layout" => TokenValue::Layout, + "in" => TokenValue::In, + "out" => TokenValue::Out, + "uniform" => TokenValue::Uniform, + "flat" => TokenValue::Interpolation(crate::Interpolation::Flat), + "noperspective" => TokenValue::Interpolation(crate::Interpolation::Linear), + "smooth" => TokenValue::Interpolation(crate::Interpolation::Perspective), + "centroid" => TokenValue::Sampling(crate::Sampling::Centroid), + "sample" => TokenValue::Sampling(crate::Sampling::Sample), + "const" => TokenValue::Const, + "inout" => TokenValue::InOut, // values - "true" => Token::BoolConstant((meta, true)), - "false" => Token::BoolConstant((meta, false)), + "true" => TokenValue::BoolConstant(true), + "false" => TokenValue::BoolConstant(false), // jump statements - "continue" => Token::Continue(meta), - "break" => Token::Break(meta), - "return" => Token::Return(meta), - "discard" => Token::Discard(meta), + "continue" => TokenValue::Continue, + "break" => TokenValue::Break, + "return" => TokenValue::Return, + "discard" => TokenValue::Discard, // selection statements - "if" => Token::If(meta), - "else" => Token::Else(meta), - "switch" => Token::Switch(meta), - "case" => Token::Case(meta), - "default" => Token::Default(meta), + "if" => TokenValue::If, + "else" => TokenValue::Else, + "switch" => TokenValue::Switch, + "case" => TokenValue::Case, + "default" => TokenValue::Default, // iteration statements - "while" => Token::While(meta), - "do" => Token::Do(meta), - "for" => Token::For(meta), + "while" => TokenValue::While, + "do" => TokenValue::Do, + "for" => TokenValue::For, // types - "void" => Token::Void(meta), - "const" => Token::Const(meta), - + "void" => TokenValue::Void, word => match parse_type(word) { - Some(t) => Token::TypeName((meta, t)), - None => Token::Identifier((meta, String::from(word))), + Some(t) => TokenValue::TypeName(t), + None => TokenValue::Identifier(String::from(word)), }, } } //TODO: unsigned etc - TokenValue::Integer(integer) => Token::IntConstant((meta, integer.value as i64)), - TokenValue::Punct(punct) => match punct { + PPTokenValue::Integer(integer) => TokenValue::IntConstant(integer.value as i64), + PPTokenValue::Punct(punct) => match punct { // Compound assignments - Punct::AddAssign => Token::AddAssign(meta), - Punct::SubAssign => Token::SubAssign(meta), - Punct::MulAssign => Token::MulAssign(meta), - Punct::DivAssign => Token::DivAssign(meta), - Punct::ModAssign => Token::ModAssign(meta), - Punct::LeftShiftAssign => Token::LeftAssign(meta), - Punct::RightShiftAssign => Token::RightAssign(meta), - Punct::AndAssign => Token::AndAssign(meta), - Punct::XorAssign => Token::XorAssign(meta), - Punct::OrAssign => Token::OrAssign(meta), + Punct::AddAssign => TokenValue::AddAssign, + Punct::SubAssign => TokenValue::SubAssign, + Punct::MulAssign => TokenValue::MulAssign, + Punct::DivAssign => TokenValue::DivAssign, + Punct::ModAssign => TokenValue::ModAssign, + Punct::LeftShiftAssign => TokenValue::LeftShiftAssign, + Punct::RightShiftAssign => TokenValue::RightShiftAssign, + Punct::AndAssign => TokenValue::AndAssign, + Punct::XorAssign => TokenValue::XorAssign, + Punct::OrAssign => TokenValue::OrAssign, // Two character punctuation - Punct::Increment => Token::IncOp(meta), - Punct::Decrement => Token::DecOp(meta), - Punct::LogicalAnd => Token::AndOp(meta), - Punct::LogicalOr => Token::OrOp(meta), - Punct::LogicalXor => Token::XorOp(meta), - Punct::LessEqual => Token::LeOp(meta), - Punct::GreaterEqual => Token::GeOp(meta), - Punct::EqualEqual => Token::EqOp(meta), - Punct::NotEqual => Token::NeOp(meta), - Punct::LeftShift => Token::LeftOp(meta), - Punct::RightShift => Token::RightOp(meta), + Punct::Increment => TokenValue::Increment, + Punct::Decrement => TokenValue::Decrement, + Punct::LogicalAnd => TokenValue::LogicalAnd, + Punct::LogicalOr => TokenValue::LogicalOr, + Punct::LogicalXor => TokenValue::LogicalXor, + Punct::LessEqual => TokenValue::LessEqual, + Punct::GreaterEqual => TokenValue::GreaterEqual, + Punct::EqualEqual => TokenValue::Equal, + Punct::NotEqual => TokenValue::NotEqual, + Punct::LeftShift => TokenValue::LeftShift, + Punct::RightShift => TokenValue::RightShift, // Parenthesis or similar - Punct::LeftBrace => Token::LeftBrace(meta), - Punct::RightBrace => Token::RightBrace(meta), - Punct::LeftParen => Token::LeftParen(meta), - Punct::RightParen => Token::RightParen(meta), - Punct::LeftBracket => Token::LeftBracket(meta), - Punct::RightBracket => Token::RightBracket(meta), + Punct::LeftBrace => TokenValue::LeftBrace, + Punct::RightBrace => TokenValue::RightBrace, + Punct::LeftParen => TokenValue::LeftParen, + Punct::RightParen => TokenValue::RightParen, + Punct::LeftBracket => TokenValue::LeftBracket, + Punct::RightBracket => TokenValue::RightBracket, // Other one character punctuation - Punct::LeftAngle => Token::LeftAngle(meta), - Punct::RightAngle => Token::RightAngle(meta), - Punct::Semicolon => Token::Semicolon(meta), - Punct::Comma => Token::Comma(meta), - Punct::Colon => Token::Colon(meta), - Punct::Dot => Token::Dot(meta), - Punct::Equal => Token::Equal(meta), - Punct::Bang => Token::Bang(meta), - Punct::Minus => Token::Dash(meta), - Punct::Tilde => Token::Tilde(meta), - Punct::Plus => Token::Plus(meta), - Punct::Star => Token::Star(meta), - Punct::Slash => Token::Slash(meta), - Punct::Percent => Token::Percent(meta), - Punct::Pipe => Token::VerticalBar(meta), - Punct::Caret => Token::Caret(meta), - Punct::Ampersand => Token::Ampersand(meta), - Punct::Question => Token::Question(meta), + Punct::LeftAngle => TokenValue::LeftAngle, + Punct::RightAngle => TokenValue::RightAngle, + Punct::Semicolon => TokenValue::Semicolon, + Punct::Comma => TokenValue::Comma, + Punct::Colon => TokenValue::Colon, + Punct::Dot => TokenValue::Dot, + Punct::Equal => TokenValue::Assign, + Punct::Bang => TokenValue::Bang, + Punct::Minus => TokenValue::Dash, + Punct::Tilde => TokenValue::Tilde, + Punct::Plus => TokenValue::Plus, + Punct::Star => TokenValue::Star, + Punct::Slash => TokenValue::Slash, + Punct::Percent => TokenValue::Percent, + Punct::Pipe => TokenValue::VerticalBar, + Punct::Caret => TokenValue::Caret, + Punct::Ampersand => TokenValue::Ampersand, + Punct::Question => TokenValue::Question, }, - TokenValue::Pragma(pragma) => { + PPTokenValue::Pragma(pragma) => { for t in pragma.tokens { self.tokens.push_back(t); } - Token::Pragma((meta, ())) + TokenValue::Pragma } - TokenValue::Version(version) => { + PPTokenValue::Version(version) => { for t in version.tokens { self.tokens.push_back(t); } - Token::Version(meta) + TokenValue::Version } - }) + }; + + Some(Token { value, meta }) } } #[cfg(test)] mod tests { use super::{ - super::{parser::Token::*, token::TokenMetadata}, + super::token::{Token, TokenMetadata, TokenValue}, Lexer, }; @@ -183,65 +191,83 @@ mod tests { let mut lex = Lexer::new("#version 450\nvoid main () {}", &defines); assert_eq!( lex.next().unwrap(), - Version(TokenMetadata { - line: 1, - chars: 1..2 //TODO - }) + Token { + value: TokenValue::Version, + meta: TokenMetadata { + line: 1, + chars: 1..2 //TODO + } + } ); assert_eq!( lex.next().unwrap(), - IntConstant(( - TokenMetadata { + Token { + value: TokenValue::IntConstant(450), + meta: TokenMetadata { line: 1, chars: 9..10 //TODO }, - 450 - )) + } ); assert_eq!( lex.next().unwrap(), - Void(TokenMetadata { - line: 2, - chars: 0..1 //TODO - }) + Token { + value: TokenValue::Void, + meta: TokenMetadata { + line: 2, + chars: 0..1 //TODO + } + } ); assert_eq!( lex.next().unwrap(), - Identifier(( - TokenMetadata { + Token { + value: TokenValue::Identifier("main".into()), + meta: TokenMetadata { line: 2, chars: 5..6 //TODO - }, - "main".into() - )) + } + } ); assert_eq!( lex.next().unwrap(), - LeftParen(TokenMetadata { - line: 2, - chars: 10..11 //TODO - }) + Token { + value: TokenValue::LeftParen, + meta: TokenMetadata { + line: 2, + chars: 10..11 //TODO + } + } ); assert_eq!( lex.next().unwrap(), - RightParen(TokenMetadata { - line: 2, - chars: 11..12 //TODO - }) + Token { + value: TokenValue::RightParen, + meta: TokenMetadata { + line: 2, + chars: 11..12 //TODO + } + } ); assert_eq!( lex.next().unwrap(), - LeftBrace(TokenMetadata { - line: 2, - chars: 13..14 //TODO - }) + Token { + value: TokenValue::LeftBrace, + meta: TokenMetadata { + line: 2, + chars: 13..14 //TODO + } + } ); assert_eq!( lex.next().unwrap(), - RightBrace(TokenMetadata { - line: 2, - chars: 14..15 //TODO - }) + Token { + value: TokenValue::RightBrace, + meta: TokenMetadata { + line: 2, + chars: 14..15 //TODO + } + } ); assert_eq!(lex.next(), None); } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 36b26b907..7a17300cf 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,23 +1,28 @@ pub use error::ErrorKind; -pub use parser::Token; -pub use token::TokenMetadata; +pub use token::{Token, TokenMetadata}; use crate::{FastHashMap, Module, ShaderStage}; mod lex; +// TODO: Remove later +#[allow(dead_code)] mod ast; use ast::Program; mod error; pub use error::ParseError; mod constants; +// TODO: Remove later +#[allow(dead_code)] mod functions; mod parser; #[cfg(test)] mod parser_tests; mod token; mod types; +// TODO: Remove later +#[allow(dead_code)] mod variables; pub struct Options { @@ -29,11 +34,8 @@ pub fn parse_str(source: &str, options: &Options) -> Result let mut program = Program::new(&options.entry_points); let lex = lex::Lexer::new(source, &options.defines); - let mut parser = parser::Parser::new(&mut program); - for token in lex { - parser.parse(token)?; - } - parser.end_of_input()?; + let mut parser = parser::Parser::new(&mut program, lex); + parser.parse()?; Ok(program.module) } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 8b46b7c66..499c98866 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,1231 +1,86 @@ -#![allow( - unused_braces, - clippy::panic, - clippy::needless_lifetimes, - clippy::upper_case_acronyms -)] -use pomelo::pomelo; -pomelo! { - //%verbose; - %include { - use super::super::{error::ErrorKind, token::*, ast::*}; - use crate::{ - BOOL_WIDTH, - Arena, ArraySize, BinaryOperator, Binding, Block, Constant, - ConstantInner, Expression, - Function, FunctionArgument, FunctionResult, - GlobalVariable, Handle, Interpolation, - LocalVariable, ResourceBinding, Sampling, ScalarValue, ScalarKind, - Statement, StorageAccess, StorageClass, StructMember, - SwitchCase, Type, TypeInner, UnaryOperator, - }; - use pp_rs::token::PreprocessorError; - } - %token #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum Token {}; - %parser pub struct Parser<'a, 'b> {}; - %extra_argument &'a mut Program<'b>; - %extra_token TokenMetadata; - %error ErrorKind; - %syntax_error { - match token { - Some(token) => Err(ErrorKind::InvalidToken(token)), - None => Err(ErrorKind::EndOfFile), - } - } - %parse_fail { - ErrorKind::ParserFail - } - %stack_overflow { - ErrorKind::ParserStackOverflow - } - - %type Unknown PreprocessorError; - %type Pragma (); - %type Extension (); - - %type Identifier String; - // constants - %type IntConstant i64; - %type UintConstant u64; - %type FloatConstant f32; - %type BoolConstant bool; - %type DoubleConstant f64; - %type String String; - // function - %type function_prototype Function; - %type function_declarator Function; - %type function_header Function; - %type function_header_with_parameters (Function, Vec); - %type function_definition Function; - - // statements - %type compound_statement Block; - %type compound_statement_no_new_scope Block; - %type statement_list Block; - %type statement Statement; - %type simple_statement Statement; - %type expression_statement Statement; - %type declaration_statement Statement; - %type jump_statement Statement; - %type iteration_statement Statement; - %type selection_statement Statement; - %type switch_statement_list Vec<(Option, Block, bool)>; - %type switch_statement (Option, Block, bool); - %type for_init_statement Statement; - %type for_rest_statement (Option, Option); - %type condition_opt Option; - - // expressions - %type unary_expression ExpressionRule; - %type postfix_expression ExpressionRule; - %type primary_expression ExpressionRule; - %type variable_identifier ExpressionRule; - - %type function_call ExpressionRule; - %type function_call_or_method FunctionCall; - %type function_call_generic FunctionCall; - %type function_call_header_no_parameters FunctionCall; - %type function_call_header_with_parameters FunctionCall; - %type function_call_header FunctionCall; - %type function_identifier FunctionCallKind; - - %type parameter_declarator FunctionArgument; - %type parameter_declaration FunctionArgument; - %type parameter_type_specifier Handle; - - %type multiplicative_expression ExpressionRule; - %type additive_expression ExpressionRule; - %type shift_expression ExpressionRule; - %type relational_expression ExpressionRule; - %type equality_expression ExpressionRule; - %type and_expression ExpressionRule; - %type exclusive_or_expression ExpressionRule; - %type inclusive_or_expression ExpressionRule; - %type logical_and_expression ExpressionRule; - %type logical_xor_expression ExpressionRule; - %type logical_or_expression ExpressionRule; - %type conditional_expression ExpressionRule; - - %type assignment_expression ExpressionRule; - %type assignment_operator BinaryOperator; - %type expression ExpressionRule; - %type constant_expression Handle; - - %type initializer ExpressionRule; - - // declarations - %type declaration Option; - %type init_declarator_list VarDeclaration; - %type single_declaration VarDeclaration; - %type layout_qualifier StructLayout; - %type layout_qualifier_id_list Vec<(String, u32)>; - %type layout_qualifier_id (String, u32); - %type type_qualifier Vec; - %type single_type_qualifier TypeQualifier; - %type storage_qualifier StorageQualifier; - %type interpolation_qualifier Interpolation; - %type Interpolation Interpolation; - %type sampling_qualifier Sampling; - %type Sampling Sampling; - - // types - %type fully_specified_type (Vec, Option>); - %type type_specifier Option>; - %type type_specifier_nonarray Option; - %type struct_specifier Type; - %type struct_declaration_list Vec; - %type struct_declaration Vec; - %type struct_declarator_list Vec; - %type struct_declarator String; - - %type TypeName Type; - - // precedence - %right Else; - - root ::= version_pragma translation_unit; - version_pragma ::= Version IntConstant(V) Identifier?(P) { - match V.1 { - 440 => (), - 450 => (), - 460 => (), - _ => return Err(ErrorKind::InvalidVersion(V.0, V.1)) - } - extra.version = V.1 as u16; - extra.profile = match P { - Some((meta, profile)) => { - match profile.as_str() { - "core" => Profile::Core, - _ => return Err(ErrorKind::InvalidProfile(meta, profile)) - } - }, - None => Profile::Core, - } - }; - - // expression - variable_identifier ::= Identifier(v) { - let var = extra.lookup_variable(&v.1)?; - match var { - Some(expression) => { - ExpressionRule::from_expression(expression) - }, - None => { - return Err(ErrorKind::UnknownVariable(v.0, v.1)); - } - } - } - - primary_expression ::= variable_identifier; - primary_expression ::= IntConstant(i) { - let ch = extra.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(i.1), - }, - }); - ExpressionRule::from_expression( - extra.context.expressions.append(Expression::Constant(ch)) - ) - } - primary_expression ::= UintConstant(i) { - let ch = extra.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Uint(i.1), - }, - }); - ExpressionRule::from_expression( - extra.context.expressions.append(Expression::Constant(ch)) - ) - } - primary_expression ::= FloatConstant(f) { - let ch = extra.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(f.1 as f64), - }, - }); - ExpressionRule::from_expression( - extra.context.expressions.append(Expression::Constant(ch)) - ) - } - primary_expression ::= BoolConstant(b) { - let ch = extra.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: BOOL_WIDTH, - value: ScalarValue::Bool(b.1) - }, - }); - ExpressionRule::from_expression( - extra.context.expressions.append(Expression::Constant(ch)) - ) - } - primary_expression ::= DoubleConstant(f) { - let ch = extra.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 8, - value: ScalarValue::Float(f.1), - }, - }); - ExpressionRule::from_expression( - extra.context.expressions.append(Expression::Constant(ch)) - ) - } - primary_expression ::= LeftParen expression(e) RightParen { - e - } - - postfix_expression ::= primary_expression; - postfix_expression ::= postfix_expression LeftBracket integer_expression RightBracket { - //TODO - return Err(ErrorKind::NotImplemented("[]")) - } - postfix_expression ::= function_call; - postfix_expression ::= postfix_expression(e) Dot Identifier(i) /* FieldSelection in spec */ { - //TODO: how will this work as l-value? - let expression = extra.field_selection(e.expression, &*i.1, i.0)?; - ExpressionRule { expression, statements: e.statements, sampler: None } - } - postfix_expression ::= postfix_expression(pe) IncOp { - //TODO - return Err(ErrorKind::NotImplemented("post++")) - } - postfix_expression ::= postfix_expression(pe) DecOp { - //TODO - return Err(ErrorKind::NotImplemented("post--")) - } - - integer_expression ::= expression; - - function_call ::= function_call_or_method(fc) { - extra.function_call(fc)? - } - function_call_or_method ::= function_call_generic; - function_call_generic ::= function_call_header_with_parameters(h) RightParen { - h - } - function_call_generic ::= function_call_header_no_parameters(h) RightParen { - h - } - function_call_header_no_parameters ::= function_call_header(h) Void { - h - } - function_call_header_no_parameters ::= function_call_header; - function_call_header_with_parameters ::= function_call_header(mut h) assignment_expression(ae) { - h.args.push(ae); - h - } - function_call_header_with_parameters ::= function_call_header_with_parameters(mut h) Comma assignment_expression(ae) { - h.args.push(ae); - h - } - function_call_header ::= function_identifier(i) LeftParen { - FunctionCall { - kind: i, - args: vec![], - } - } - - // Grammar Note: Constructors look like functions, but lexical analysis recognized most of them as - // keywords. They are now recognized through “type_specifier”. - function_identifier ::= type_specifier(t) { - if let Some(ty) = t { - FunctionCallKind::TypeConstructor(ty) - } else { - return Err(ErrorKind::NotImplemented("bad type ctor")) - } - } - - //TODO - // Methods (.length), subroutine array calls, and identifiers are recognized through postfix_expression. - // function_identifier ::= postfix_expression(e) { - // FunctionCallKind::Function(e.expression) - // } - - // Simplification of above - function_identifier ::= Identifier(i) { - FunctionCallKind::Function(i.1) - } - - - unary_expression ::= postfix_expression; - - unary_expression ::= IncOp unary_expression { - //TODO - return Err(ErrorKind::NotImplemented("++pre")) - } - unary_expression ::= DecOp unary_expression { - //TODO - return Err(ErrorKind::NotImplemented("--pre")) - } - unary_expression ::= Plus unary_expression(tgt) { - tgt - } - unary_expression ::= Dash unary_expression(tgt) { - extra.unary_expr(UnaryOperator::Negate, &tgt) - } - unary_expression ::= Bang unary_expression(tgt) { - if let TypeInner::Scalar { kind: ScalarKind::Bool, .. } = *extra.resolve_type(tgt.expression)? { - extra.unary_expr(UnaryOperator::Not, &tgt) - } else { - return Err(ErrorKind::SemanticError("Cannot apply '!' to non bool type".into())) - } - } - unary_expression ::= Tilde unary_expression(tgt) { - if extra.resolve_type(tgt.expression)?.scalar_kind() != Some(ScalarKind::Bool) { - extra.unary_expr(UnaryOperator::Not, &tgt) - } else { - return Err(ErrorKind::SemanticError("Cannot apply '~' to type".into())) - } - } - - multiplicative_expression ::= unary_expression; - multiplicative_expression ::= multiplicative_expression(left) Star unary_expression(right) { - extra.binary_expr(BinaryOperator::Multiply, &left, &right) - } - multiplicative_expression ::= multiplicative_expression(left) Slash unary_expression(right) { - extra.binary_expr(BinaryOperator::Divide, &left, &right) - } - multiplicative_expression ::= multiplicative_expression(left) Percent unary_expression(right) { - extra.binary_expr(BinaryOperator::Modulo, &left, &right) - } - additive_expression ::= multiplicative_expression; - additive_expression ::= additive_expression(left) Plus multiplicative_expression(right) { - extra.binary_expr(BinaryOperator::Add, &left, &right) - } - additive_expression ::= additive_expression(left) Dash multiplicative_expression(right) { - extra.binary_expr(BinaryOperator::Subtract, &left, &right) - } - shift_expression ::= additive_expression; - shift_expression ::= shift_expression(left) LeftOp additive_expression(right) { - extra.binary_expr(BinaryOperator::ShiftLeft, &left, &right) - } - shift_expression ::= shift_expression(left) RightOp additive_expression(right) { - extra.binary_expr(BinaryOperator::ShiftRight, &left, &right) - } - relational_expression ::= shift_expression; - relational_expression ::= relational_expression(left) LeftAngle shift_expression(right) { - extra.binary_expr(BinaryOperator::Less, &left, &right) - } - relational_expression ::= relational_expression(left) RightAngle shift_expression(right) { - extra.binary_expr(BinaryOperator::Greater, &left, &right) - } - relational_expression ::= relational_expression(left) LeOp shift_expression(right) { - extra.binary_expr(BinaryOperator::LessEqual, &left, &right) - } - relational_expression ::= relational_expression(left) GeOp shift_expression(right) { - extra.binary_expr(BinaryOperator::GreaterEqual, &left, &right) - } - equality_expression ::= relational_expression; - equality_expression ::= equality_expression(left) EqOp relational_expression(right) { - extra.equality_expr(true, &left, &right)? - } - equality_expression ::= equality_expression(left) NeOp relational_expression(right) { - extra.equality_expr(false, &left, &right)? - } - and_expression ::= equality_expression; - and_expression ::= and_expression(left) Ampersand equality_expression(right) { - extra.binary_expr(BinaryOperator::And, &left, &right) - } - exclusive_or_expression ::= and_expression; - exclusive_or_expression ::= exclusive_or_expression(left) Caret and_expression(right) { - extra.binary_expr(BinaryOperator::ExclusiveOr, &left, &right) - } - inclusive_or_expression ::= exclusive_or_expression; - inclusive_or_expression ::= inclusive_or_expression(left) VerticalBar exclusive_or_expression(right) { - extra.binary_expr(BinaryOperator::InclusiveOr, &left, &right) - } - logical_and_expression ::= inclusive_or_expression; - logical_and_expression ::= logical_and_expression(left) AndOp inclusive_or_expression(right) { - extra.binary_expr(BinaryOperator::LogicalAnd, &left, &right) - } - logical_xor_expression ::= logical_and_expression; - logical_xor_expression ::= logical_xor_expression(left) XorOp logical_and_expression(right) { - let exp1 = extra.binary_expr(BinaryOperator::LogicalOr, &left, &right); - let exp2 = { - let tmp = extra.binary_expr(BinaryOperator::LogicalAnd, &left, &right).expression; - ExpressionRule::from_expression(extra.context.expressions.append(Expression::Unary { op: UnaryOperator::Not, expr: tmp })) - }; - extra.binary_expr(BinaryOperator::LogicalAnd, &exp1, &exp2) - } - logical_or_expression ::= logical_xor_expression; - logical_or_expression ::= logical_or_expression(left) OrOp logical_xor_expression(right) { - extra.binary_expr(BinaryOperator::LogicalOr, &left, &right) - } - - conditional_expression ::= logical_or_expression; - conditional_expression ::= logical_or_expression Question expression Colon assignment_expression(ae) { - //TODO: how to do ternary here in naga? - return Err(ErrorKind::NotImplemented("ternary exp")) - } - - assignment_expression ::= conditional_expression; - assignment_expression ::= unary_expression(mut pointer) assignment_operator(op) assignment_expression(value) { - pointer.statements.extend(value.statements); - match op { - BinaryOperator::Equal => { - pointer.statements.push(Statement::Store{ - pointer: pointer.expression, - value: value.expression - }); - pointer - }, - _ => { - let h = extra.context.expressions.append( - Expression::Binary{ - op, - left: pointer.expression, - right: value.expression, - } - ); - pointer.statements.push(Statement::Store{ - pointer: pointer.expression, - value: h, - }); - pointer - } - } - } - - assignment_operator ::= Equal { - BinaryOperator::Equal - } - assignment_operator ::= MulAssign { - BinaryOperator::Multiply - } - assignment_operator ::= DivAssign { - BinaryOperator::Divide - } - assignment_operator ::= ModAssign { - BinaryOperator::Modulo - } - assignment_operator ::= AddAssign { - BinaryOperator::Add - } - assignment_operator ::= SubAssign { - BinaryOperator::Subtract - } - assignment_operator ::= LeftAssign { - BinaryOperator::ShiftLeft - } - assignment_operator ::= RightAssign { - BinaryOperator::ShiftRight - } - assignment_operator ::= AndAssign { - BinaryOperator::And - } - assignment_operator ::= XorAssign { - BinaryOperator::ExclusiveOr - } - assignment_operator ::= OrAssign { - BinaryOperator::InclusiveOr - } - - expression ::= assignment_expression; - expression ::= expression(e) Comma assignment_expression(mut ae) { - ae.statements.extend(e.statements); - ExpressionRule { - expression: e.expression, - statements: ae.statements, - sampler: None, - } - } - - //TODO: properly handle constant expressions - // constant_expression ::= conditional_expression(e) { - // if let Expression::Constant(h) = extra.context.expressions[e] { - // h - // } else { - // return Err(ErrorKind::ExpectedConstant) - // } - // } - - // declaration - declaration ::= init_declarator_list(idl) Semicolon { - Some(idl) - } - - declaration ::= type_qualifier(t) Identifier(i) LeftBrace - struct_declaration_list(sdl) RightBrace Semicolon { - if i.1 == "gl_PerVertex" { - None - } else { - Some(VarDeclaration { - ids_initializers: vec![(None, None)], - ty: extra.module.types.fetch_or_append(Type{ - name: Some(i.1), - inner: TypeInner::Struct { - top_level: !t.is_empty(), - members: sdl, - span: 0, //TODO - }, - }), - type_qualifiers: t, - }) - } - } - - declaration ::= type_qualifier(t) Identifier(i1) LeftBrace - struct_declaration_list(sdl) RightBrace Identifier(i2) Semicolon { - Some(VarDeclaration { - ids_initializers: vec![(Some(i2.1), None)], - ty: extra.module.types.fetch_or_append(Type{ - name: Some(i1.1), - inner: TypeInner::Struct { - top_level: !t.is_empty(), - members: sdl, - span: 0, //TODO - }, - }), - type_qualifiers: t, - }) - } - - // declaration ::= type_qualifier(t) Identifier(i1) LeftBrace - // struct_declaration_list RightBrace Identifier(i2) array_specifier Semicolon; - - init_declarator_list ::= single_declaration; - init_declarator_list ::= init_declarator_list(mut idl) Comma Identifier(i) { - idl.ids_initializers.push((Some(i.1), None)); - idl - } - // init_declarator_list ::= init_declarator_list Comma Identifier array_specifier; - // init_declarator_list ::= init_declarator_list Comma Identifier array_specifier Equal initializer; - init_declarator_list ::= init_declarator_list(mut idl) Comma Identifier(i) Equal initializer(init) { - idl.ids_initializers.push((Some(i.1), Some(init))); - idl - } - - single_declaration ::= fully_specified_type(t) { - let ty = t.1.ok_or_else(||ErrorKind::SemanticError("Empty type for declaration".into()))?; - - VarDeclaration { - type_qualifiers: t.0, - ids_initializers: vec![], - ty, - } - } - single_declaration ::= fully_specified_type(t) Identifier(i) { - let ty = t.1.ok_or_else(|| ErrorKind::SemanticError("Empty type for declaration".into()))?; - - VarDeclaration { - type_qualifiers: t.0, - ids_initializers: vec![(Some(i.1), None)], - ty, - } - } - - single_declaration ::= fully_specified_type(t) Identifier(i) LeftBracket additive_expression(exp) RightBracket { - let ty_item = t.1.ok_or_else(|| ErrorKind::SemanticError("Empty type for declaration".into()))?; - - let array_size = if let Ok(constant) = extra.solve_constant(exp.expression) { - ArraySize::Constant(constant) - } else { - ArraySize::Dynamic - }; - - let item_size = extra.type_size(ty_item)?; - - let ty = extra.module.types.fetch_or_append(Type { - inner: TypeInner::Array { - base: ty_item, - size: array_size, - stride: item_size as u32, - }, - name: None, - }); - - VarDeclaration { - type_qualifiers: t.0, - ids_initializers: vec![(Some(i.1), None)], - ty, - } - } - - // single_declaration ::= fully_specified_type Identifier array_specifier; - // single_declaration ::= fully_specified_type Identifier array_specifier Equal initializer; - single_declaration ::= fully_specified_type(t) Identifier(i) Equal initializer(init) { - let ty = t.1.ok_or_else(|| ErrorKind::SemanticError("Empty type for declaration".into()))?; - - VarDeclaration { - type_qualifiers: t.0, - ids_initializers: vec![(Some(i.1), Some(init))], - ty, - } - } - - fully_specified_type ::= type_specifier(t) { - (vec![], t) - } - fully_specified_type ::= type_qualifier(q) type_specifier(t) { - (q,t) - } - - interpolation_qualifier ::= Interpolation((_, i)) { - i - } - - sampling_qualifier ::= Sampling((_, s)) { - s - } - - layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen { - if let Some(&(_, location)) = l.iter().find(|&q| q.0.as_str() == "location") { - let interpolation = None; //TODO - let sampling = None; //TODO - StructLayout::Binding(Binding::Location { location, interpolation, sampling }) - } else if let Some(&(_, binding)) = l.iter().find(|&q| q.0.as_str() == "binding") { - let group = if let Some(&(_, set)) = l.iter().find(|&q| q.0.as_str() == "set") { - set - } else { - 0 - }; - StructLayout::Resource(ResourceBinding{ group, binding }) - } else if l.iter().any(|q| q.0.as_str() == "push_constant") { - StructLayout::PushConstant - } else { - return Err(ErrorKind::NotImplemented("unsupported layout qualifier(s)")); - } - } - layout_qualifier_id_list ::= layout_qualifier_id(lqi) { - vec![lqi] - } - layout_qualifier_id_list ::= layout_qualifier_id_list(mut l) Comma layout_qualifier_id(lqi) { - l.push(lqi); - l - } - layout_qualifier_id ::= Identifier(i) { - (i.1, 0) - } - //TODO: handle full constant_expression instead of IntConstant - layout_qualifier_id ::= Identifier(i) Equal IntConstant(ic) { - (i.1, ic.1 as u32) - } - // layout_qualifier_id ::= Shared; - - // precise_qualifier ::= Precise; - - type_qualifier ::= single_type_qualifier(t) { - vec![t] - } - type_qualifier ::= type_qualifier(mut l) single_type_qualifier(t) { - l.push(t); - l - } - - single_type_qualifier ::= storage_qualifier(s) { - TypeQualifier::StorageQualifier(s) - } - single_type_qualifier ::= layout_qualifier(l) { - match l { - StructLayout::Binding(b) => TypeQualifier::Binding(b), - StructLayout::Resource(b) => TypeQualifier::ResourceBinding(b), - StructLayout::PushConstant => TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(StorageClass::PushConstant)), - } - } - // single_type_qualifier ::= precision_qualifier; - single_type_qualifier ::= interpolation_qualifier(i) { - TypeQualifier::Interpolation(i) - } - single_type_qualifier ::= sampling_qualifier(i) { - TypeQualifier::Sampling(i) - } - // single_type_qualifier ::= invariant_qualifier; - // single_type_qualifier ::= precise_qualifier; - - storage_qualifier ::= Const { - StorageQualifier::Const - } - // storage_qualifier ::= InOut; - storage_qualifier ::= In { - StorageQualifier::Input - } - storage_qualifier ::= Out { - StorageQualifier::Output - } - // storage_qualifier ::= Centroid; - // storage_qualifier ::= Patch; - // storage_qualifier ::= Sample; - storage_qualifier ::= Uniform { - StorageQualifier::StorageClass(StorageClass::Uniform) - } - //TODO: other storage qualifiers - - type_specifier ::= type_specifier_nonarray(t) { - t.map(|t| { - let name = t.name.clone(); - let handle = extra.module.types.fetch_or_append(t); - if let Some(name) = name { - extra.lookup_type.insert(name, handle); - } - handle - }) - } - //TODO: array - - type_specifier_nonarray ::= Void { - None - } - type_specifier_nonarray ::= TypeName(t) { - Some(t.1) - }; - type_specifier_nonarray ::= struct_specifier(s) { - Some(s) - } - - // struct - struct_specifier ::= Struct Identifier(i) LeftBrace struct_declaration_list RightBrace { - Type{ - name: Some(i.1), - inner: TypeInner::Struct { - top_level: false, - members: vec![], - span: 0, - } - } - } - //struct_specifier ::= Struct LeftBrace struct_declaration_list RightBrace; - - struct_declaration_list ::= struct_declaration(sd) { - sd - } - struct_declaration_list ::= struct_declaration_list(mut sdl) struct_declaration(sd) { - sdl.extend(sd); - sdl - } - - struct_declaration ::= type_specifier(t) struct_declarator_list(sdl) Semicolon { - if let Some(ty) = t { - sdl.iter().map(|name| StructMember { - name: Some(name.clone()), - ty, - binding: None, //TODO - //TODO: if the struct is a uniform struct, these values have to reflect - // std140 layout. Otherwise, std430. - offset: 0, - }).collect() - } else { - return Err(ErrorKind::SemanticError("Struct member can't be void".into())) - } - } - //struct_declaration ::= type_qualifier type_specifier struct_declarator_list Semicolon; - - struct_declarator_list ::= struct_declarator(sd) { - vec![sd] - } - struct_declarator_list ::= struct_declarator_list(mut sdl) Comma struct_declarator(sd) { - sdl.push(sd); - sdl - } - - struct_declarator ::= Identifier(i) { - i.1 - } - //struct_declarator ::= Identifier array_specifier; - - - initializer ::= assignment_expression; - // initializer ::= LeftBrace initializer_list RightBrace; - // initializer ::= LeftBrace initializer_list Comma RightBrace; - - // initializer_list ::= initializer; - // initializer_list ::= initializer_list Comma initializer; - - declaration_statement ::= declaration(d) { - let mut statements = Vec::::new(); - // local variables - if let Some(d) = d { - for (id, initializer) in d.ids_initializers { - let id = id.ok_or_else(|| ErrorKind::SemanticError("Local var must be named".into()))?; - // check if already declared in current scope - #[cfg(feature = "glsl-validate")] - { - if extra.context.lookup_local_var_current_scope(&id).is_some() { - return Err(ErrorKind::VariableAlreadyDeclared(id)) - } - } - let mut init_exp: Option> = None; - let localVar = extra.context.local_variables.append( - LocalVariable { - name: Some(id.clone()), - ty: d.ty, - init: initializer.map(|i| { - statements.extend(i.statements); - if let Expression::Constant(constant) = extra.context.expressions[i.expression] { - Some(constant) - } else { - init_exp = Some(i.expression); - None - } - }).flatten(), - } - ); - let exp = extra.context.expressions.append(Expression::LocalVariable(localVar)); - extra.context.add_local_var(id, exp); - - if let Some(value) = init_exp { - statements.push( - Statement::Store { - pointer: exp, - value, - } - ); - } - } - }; - match statements.len() { - 1 => statements.remove(0), - _ => Statement::Block(statements), - } - } - - // statement - statement ::= compound_statement(cs) { - Statement::Block(cs) - } - statement ::= simple_statement; - - simple_statement ::= declaration_statement; - simple_statement ::= expression_statement; - simple_statement ::= selection_statement; - simple_statement ::= jump_statement; - simple_statement ::= iteration_statement; - - - selection_statement ::= If LeftParen expression(e) RightParen statement(s1) Else statement(s2) { - Statement::If { - condition: e.expression, - accept: vec![s1], - reject: vec![s2], - } - } - - selection_statement ::= If LeftParen expression(e) RightParen statement(s) [Else] { - Statement::If { - condition: e.expression, - accept: vec![s], - reject: vec![], - } - } - - selection_statement ::= Switch LeftParen expression(e) RightParen LeftBrace switch_statement_list(ls) RightBrace { - let mut default = Vec::new(); - let mut cases = Vec::new(); - for (v, body, fall_through) in ls { - if let Some(value) = v { - cases.push(SwitchCase { - value, - body, - fall_through, - }); - } else { - default.extend_from_slice(&body); - } - } - Statement::Switch { - selector: e.expression, - cases, - default, - } - } - - switch_statement_list ::= { - vec![] - } - switch_statement_list ::= switch_statement_list(mut ssl) switch_statement((v, sl, ft)) { - ssl.push((v, sl, ft)); - ssl - } - switch_statement ::= Case IntConstant(v) Colon statement_list(sl) { - let fall_through = match sl.last() { - Some(&Statement::Break) => false, - _ => true, - }; - (Some(v.1 as i32), sl, fall_through) - } - switch_statement ::= Default Colon statement_list(sl) { - let fall_through = match sl.last() { - Some(&Statement::Break) => true, - _ => false, - }; - (None, sl, fall_through) - } - - iteration_statement ::= While LeftParen expression(e) RightParen compound_statement_no_new_scope(sl) { - let mut body = Vec::with_capacity(sl.len() + 1); - body.push( - Statement::If { - condition: e.expression, - accept: vec![Statement::Break], - reject: vec![], - } - ); - body.extend_from_slice(&sl); - Statement::Loop { - body, - continuing: vec![], - } - } - - iteration_statement ::= Do compound_statement(sl) While LeftParen expression(e) RightParen { - let mut body = sl; - body.push( - Statement::If { - condition: e.expression, - accept: vec![Statement::Break], - reject: vec![], - } - ); - Statement::Loop { - body, - continuing: vec![], - } - } - - iteration_statement ::= For LeftParen for_init_statement(s_init) for_rest_statement((cond_e, loop_e)) RightParen compound_statement_no_new_scope(sl) { - let mut body = Vec::with_capacity(sl.len() + 2); - if let Some(cond_e) = cond_e { - body.push( - Statement::If { - condition: cond_e.expression, - accept: vec![Statement::Break], - reject: vec![], - } - ); - } - body.extend_from_slice(&sl); - if let Some(loop_e) = loop_e { - body.extend_from_slice(&loop_e.statements); - } - Statement::Block(vec![ - s_init, - Statement::Loop { - body, - continuing: vec![], - } - ]) - } - - for_init_statement ::= expression_statement; - for_init_statement ::= declaration_statement; - for_rest_statement ::= condition_opt(c) Semicolon { - (c, None) - } - for_rest_statement ::= condition_opt(c) Semicolon expression(e) { - (c, Some(e)) - } - - condition_opt ::= { - None - } - condition_opt ::= conditional_expression(c) { - Some(c) - } - - compound_statement ::= LeftBrace RightBrace { - vec![] - } - compound_statement ::= left_brace_scope statement_list(sl) RightBrace { - extra.context.remove_current_scope(); - sl - } - - // extra rule to add scope before statement_list - left_brace_scope ::= LeftBrace { - extra.context.push_scope(); - } - - - compound_statement_no_new_scope ::= LeftBrace RightBrace { - vec![] - } - compound_statement_no_new_scope ::= LeftBrace statement_list(sl) RightBrace { - sl - } - - statement_list ::= statement(s) { - //TODO: catch this earlier and don't populate the statements - match s { - Statement::Block(ref block) if block.is_empty() => vec![], - _ => vec![s], - } - } - statement_list ::= statement_list(mut ss) statement(s) { ss.push(s); ss } - - expression_statement ::= Semicolon { - Statement::Block(Vec::new()) - } - expression_statement ::= expression(mut e) Semicolon { - match e.statements.len() { - 1 => e.statements.remove(0), - _ => Statement::Block(e.statements), - } - } - - - - // function - function_prototype ::= function_declarator(f) RightParen { - extra.add_function_prelude(); - f - } - function_declarator ::= function_header; - function_declarator ::= function_header_with_parameters((f, args)) { - for (pos, arg) in args.into_iter().enumerate() { - if let Some(name) = arg.name.clone() { - let exp = extra.context.expressions.append(Expression::FunctionArgument(pos as u32)); - extra.context.add_function_arg(name, exp); - } - extra.context.arguments.push(arg); - } - f - } - function_header ::= fully_specified_type(t) Identifier(n) LeftParen { - Function { - name: Some(n.1), - arguments: vec![], - result: t.1.map(|ty| FunctionResult { ty, binding: None }), - local_variables: Arena::::new(), - expressions: Arena::::new(), - body: vec![], - } - } - function_header_with_parameters ::= function_header(h) parameter_declaration(p) { - (h, vec![p]) - } - function_header_with_parameters ::= function_header_with_parameters((h, mut args)) Comma parameter_declaration(p) { - args.push(p); - (h, args) - } - parameter_declarator ::= parameter_type_specifier(ty) Identifier(n) { - FunctionArgument { name: Some(n.1), ty, binding: None } - } - // parameter_declarator ::= type_specifier(ty) Identifier(ident) array_specifier; - parameter_declaration ::= In? parameter_declarator(arg) { arg }; - parameter_declaration ::= In? parameter_type_specifier(ty) { - FunctionArgument { name: None, ty, binding: None } - } - - parameter_type_specifier ::= type_specifier(t) { - if let Some(ty) = t { - ty - } else { - return Err(ErrorKind::SemanticError("Function parameter can't be void".into())) - } - } - - jump_statement ::= Continue Semicolon { - Statement::Continue - } - jump_statement ::= Break Semicolon { - Statement::Break - } - jump_statement ::= Return Semicolon { - Statement::Return { value: None } - } - jump_statement ::= Return expression(mut e) Semicolon { - let ret = Statement::Return{ value: Some(e.expression) }; - if !e.statements.is_empty() { - e.statements.push(ret); - Statement::Block(e.statements) - } else { - ret - } - } - jump_statement ::= Discard Semicolon { - Statement::Kill - } // Fragment shader only - - // Grammar Note: No 'goto'. Gotos are not supported. - - // misc - translation_unit ::= external_declaration; - translation_unit ::= translation_unit external_declaration; - - external_declaration ::= function_definition(f) { - extra.declare_function(f)? - } - external_declaration ::= declaration(d) { - if let Some(d) = d { - // TODO: handle multiple storage qualifiers - let storage = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::StorageQualifier(sc) = *tq { Some(sc) } else { None } - }).unwrap_or(StorageQualifier::StorageClass(StorageClass::Private)); - - match storage { - StorageQualifier::StorageClass(storage_class) => { - // TODO: Check that the storage qualifiers allow for the bindings - let binding = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::ResourceBinding(ref b) = *tq { Some(b.clone()) } else { None } - }); - for (id, initializer) in d.ids_initializers { - let init = initializer.map(|init| extra.solve_constant(init.expression)).transpose()?; - - // use StorageClass::Handle for texture and sampler uniforms - let class = if storage_class == StorageClass::Uniform { - match extra.module.types[d.ty].inner { - TypeInner::Image{..} | TypeInner::Sampler{..} => StorageClass::Handle, - _ => storage_class, - } - } else { - storage_class - }; - - let h = extra.module.global_variables.fetch_or_append( - GlobalVariable { - name: id.clone(), - class, - binding: binding.clone(), - ty: d.ty, - init, - storage_access: StorageAccess::empty(), //TODO - }, - ); - if let Some(id) = id { - extra.lookup_global_variables.insert(id, h); - } - } - } - StorageQualifier::Input => { - let mut binding = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Binding(ref b) = *tq { Some(b.clone()) } else { None } - }); - let interpolation = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Interpolation(interp) = *tq { Some(interp) } else { None } - }); - let sampling = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Sampling(samp) = *tq { Some(samp) } else { None } - }); - if let Some(Binding::Location { - interpolation: ref mut interp, - sampling: ref mut samp, - .. - }) = binding { - *interp = interpolation; - *samp = sampling; - } - - for (id, _initializer) in d.ids_initializers { - if let Some(id) = id { - //TODO! - let expr = extra.context.expressions.append(Expression::FunctionArgument(0)); - extra.context.lookup_global_var_exps.insert(id, expr); - } - } - } - StorageQualifier::Output => { - let _binding = d.type_qualifiers.iter().find_map(|tq| { - if let TypeQualifier::Binding(ref b) = *tq { Some(b.clone()) } else { None } - }); - for (id, _initializer) in d.ids_initializers { - if let Some(id) = id { - //TODO! - let expr = extra.context.expressions.append(Expression::FunctionArgument(0)); - extra.context.lookup_global_var_exps.insert(id, expr); - } - } - } - StorageQualifier::Const => { - for (id, initializer) in d.ids_initializers { - if let Some(init) = initializer { - let constant = extra.solve_constant(init.expression)?; - let inner = extra.module.constants[constant].inner.clone(); - - let h = extra.module.constants.fetch_or_append( - Constant { - name: id.clone(), - specialization: None, // TODO - inner - }, - ); - if let Some(id) = id { - extra.lookup_constants.insert(id.clone(), h); - let expr = extra.context.expressions.append(Expression::Constant(h)); - extra.context.lookup_constant_exps.insert(id, expr); - } - } else { - return Err(ErrorKind::SemanticError("Constants must have an initializer".into())) - } - } - } - } - } - } - - function_definition ::= function_prototype(f) compound_statement_no_new_scope(cs) { - extra.function_definition(f, cs) - }; +use super::{ + ast::Profile, + error::ErrorKind, + lex::Lexer, + token::{Token, TokenMetadata, TokenValue}, + Program, +}; +use std::iter::Peekable; + +pub struct Parser<'source, 'program, 'options> { + program: &'program mut Program<'options>, + lexer: Peekable>, } -pub use parser::*; +impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { + pub fn new(program: &'program mut Program<'options>, lexer: Lexer<'source>) -> Self { + Parser { + program, + lexer: lexer.peekable(), + } + } + + pub fn parse(&mut self) -> Result<(), ErrorKind> { + self.parse_version()?; + + if let Some(token) = self.lexer.next() { + Err(ErrorKind::InvalidToken(token)) + } else { + Ok(()) + } + } + + fn parse_version(&mut self) -> Result<(), ErrorKind> { + self.expect(TokenValue::Version)?; + + let version = self.bump()?; + match version.value { + TokenValue::IntConstant(i) => match i { + 440 | 450 | 460 => self.program.version = i as u16, + _ => return Err(ErrorKind::InvalidVersion(version.meta, i)), + }, + _ => return Err(ErrorKind::InvalidToken(version)), + } + + let profile = self.lexer.peek(); + self.program.profile = match profile { + Some(&Token { + value: TokenValue::Identifier(_), + .. + }) => { + let (name, meta) = self.expect_ident()?; + + match name.as_str() { + "core" => Profile::Core, + _ => return Err(ErrorKind::InvalidProfile(meta, name)), + } + } + _ => Profile::Core, + }; + + Ok(()) + } + + fn expect_ident(&mut self) -> Result<(String, TokenMetadata), ErrorKind> { + let token = self.bump()?; + + match token.value { + TokenValue::Identifier(name) => Ok((name, token.meta)), + _ => Err(ErrorKind::InvalidToken(token)), + } + } + + fn expect(&mut self, value: TokenValue) -> Result { + let token = self.bump()?; + + if token.value != value { + Err(ErrorKind::InvalidToken(token)) + } else { + Ok(token) + } + } + + fn bump(&mut self) -> Result { + self.lexer.next().ok_or(ErrorKind::EndOfFile) + } +} diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index de0b4db41..c9b31ba62 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -11,12 +11,9 @@ fn parse_program<'a>( let mut program = Program::new(entry_points); let defines = crate::FastHashMap::default(); let lex = Lexer::new(source, &defines); - let mut parser = parser::Parser::new(&mut program); + let mut parser = parser::Parser::new(&mut program, lex); - for token in lex { - parser.parse(token)?; - } - parser.end_of_input()?; + parser.parse()?; Ok(program) } @@ -53,148 +50,152 @@ fn version() { "InvalidProfile(TokenMetadata { line: 1, chars: 13..14 }, \"smart\")" //TODO: location ); - assert_eq!( - format!( - "{:?}", - parse_program("#version 450\nvoid f(){} #version 450", &entry_points) - .err() - .unwrap() - ), - "InvalidToken(Unknown((TokenMetadata { line: 2, chars: 11..12 }, UnexpectedHash)))" - ); + // TODO: Reenable tests later + // assert_eq!( + // format!( + // "{:?}", + // parse_program("#version 450\nvoid f(){} #version 450", &entry_points) + // .err() + // .unwrap() + // ), + // "InvalidToken(Unknown((TokenMetadata { line: 2, chars: 11..12 }, UnexpectedHash)))" + // ); - // valid versions - let program = parse_program(" # version 450\nvoid main() {}", &entry_points).unwrap(); - assert_eq!( - format!("{:?}", (program.version, program.profile)), - "(450, Core)" - ); + // // valid versions + // let program = parse_program(" # version 450\nvoid main() {}", &entry_points).unwrap(); + // assert_eq!( + // format!("{:?}", (program.version, program.profile)), + // "(450, Core)" + // ); - let program = parse_program("#version 450\nvoid main() {}", &entry_points).unwrap(); - assert_eq!( - format!("{:?}", (program.version, program.profile)), - "(450, Core)" - ); + // let program = parse_program("#version 450\nvoid main() {}", &entry_points).unwrap(); + // assert_eq!( + // format!("{:?}", (program.version, program.profile)), + // "(450, Core)" + // ); - let program = parse_program("#version 450 core\nvoid main() {}", &entry_points).unwrap(); - assert_eq!( - format!("{:?}", (program.version, program.profile)), - "(450, Core)" - ); + // let program = parse_program("#version 450 core\nvoid main() {}", &entry_points).unwrap(); + // assert_eq!( + // format!("{:?}", (program.version, program.profile)), + // "(450, Core)" + // ); } #[test] fn control_flow() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Vertex); + // TODO: Reenable tests later + // let mut entry_points = crate::FastHashMap::default(); + // entry_points.insert("".to_string(), ShaderStage::Vertex); - let _program = parse_program( - r#" - # version 450 - void main() { - if (true) { - return 1; - } else { - return 2; - } - } - "#, - &entry_points, - ) - .unwrap(); + // let _program = parse_program( + // r#" + // # version 450 + // void main() { + // if (true) { + // return 1; + // } else { + // return 2; + // } + // } + // "#, + // &entry_points, + // ) + // .unwrap(); - let _program = parse_program( - r#" - # version 450 - void main() { - if (true) { - return 1; - } - } - "#, - &entry_points, - ) - .unwrap(); + // let _program = parse_program( + // r#" + // # version 450 + // void main() { + // if (true) { + // return 1; + // } + // } + // "#, + // &entry_points, + // ) + // .unwrap(); - let _program = parse_program( - r#" - # version 450 - void main() { - int x; - int y = 3; - switch (5) { - case 2: - x = 2; - case 5: - x = 5; - y = 2; - break; - default: - x = 0; - } - } - "#, - &entry_points, - ) - .unwrap(); - let _program = parse_program( - r#" - # version 450 - void main() { - int x = 0; - while(x < 5) { - x = x + 1; - } - do { - x = x - 1; - } while(x >= 4) - } - "#, - &entry_points, - ) - .unwrap(); + // let _program = parse_program( + // r#" + // # version 450 + // void main() { + // int x; + // int y = 3; + // switch (5) { + // case 2: + // x = 2; + // case 5: + // x = 5; + // y = 2; + // break; + // default: + // x = 0; + // } + // } + // "#, + // &entry_points, + // ) + // .unwrap(); + // let _program = parse_program( + // r#" + // # version 450 + // void main() { + // int x = 0; + // while(x < 5) { + // x = x + 1; + // } + // do { + // x = x - 1; + // } while(x >= 4) + // } + // "#, + // &entry_points, + // ) + // .unwrap(); - let _program = parse_program( - r#" - # version 450 - void main() { - int x = 0; - for(int i = 0; i < 10;) { - x = x + 2; - } - return x; - } - "#, - &entry_points, - ) - .unwrap(); + // let _program = parse_program( + // r#" + // # version 450 + // void main() { + // int x = 0; + // for(int i = 0; i < 10;) { + // x = x + 2; + // } + // return x; + // } + // "#, + // &entry_points, + // ) + // .unwrap(); } #[test] fn textures() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Fragment); + // TODO: Reenable tests later + // let mut entry_points = crate::FastHashMap::default(); + // entry_points.insert("".to_string(), ShaderStage::Fragment); - let _program = parse_program( - r#" - #version 450 - layout(location = 0) in vec2 v_uv; - layout(location = 0) out vec4 o_color; - layout(set = 1, binding = 1) uniform texture2D tex; - layout(set = 1, binding = 2) uniform sampler tex_sampler; - void main() { - o_color = texture(sampler2D(tex, tex_sampler), v_uv); - } - "#, - &entry_points, - ) - .unwrap(); + // let _program = parse_program( + // r#" + // #version 450 + // layout(location = 0) in vec2 v_uv; + // layout(location = 0) out vec4 o_color; + // layout(set = 1, binding = 1) uniform texture2D tex; + // layout(set = 1, binding = 2) uniform sampler tex_sampler; + // void main() { + // o_color = texture(sampler2D(tex, tex_sampler), v_uv); + // } + // "#, + // &entry_points, + // ) + // .unwrap(); } #[test] fn functions() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Vertex); + // TODO: Reenable tests later + // let mut entry_points = crate::FastHashMap::default(); + // entry_points.insert("".to_string(), ShaderStage::Vertex); // TODO: Add support for function prototypes // parse_program( @@ -209,97 +210,98 @@ fn functions() { // ) // .unwrap(); - parse_program( - r#" - # version 450 - void test2(float a) {} - void test3(float a, float b) {} - void test4(float, float) {} - - void main() {} - "#, - &entry_points, - ) - .unwrap(); + // parse_program( + // r#" + // # version 450 + // void test2(float a) {} + // void test3(float a, float b) {} + // void test4(float, float) {} - parse_program( - r#" - # version 450 - float test(float a) { return a; } - - void main() {} - "#, - &entry_points, - ) - .unwrap(); + // void main() {} + // "#, + // &entry_points, + // ) + // .unwrap(); - parse_program( - r#" - # version 450 - float test(vec4 p) { - return p.x; - } - "#, - &entry_points, - ) - .unwrap(); + // parse_program( + // r#" + // # version 450 + // float test(float a) { return a; } + + // void main() {} + // "#, + // &entry_points, + // ) + // .unwrap(); + + // parse_program( + // r#" + // # version 450 + // float test(vec4 p) { + // return p.x; + // } + // "#, + // &entry_points, + // ) + // .unwrap(); } #[test] fn constants() { - use crate::{Constant, ConstantInner, ScalarValue}; + // TODO: Reenable tests later + // use crate::{Constant, ConstantInner, ScalarValue}; - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Vertex); + // let mut entry_points = crate::FastHashMap::default(); + // entry_points.insert("".to_string(), ShaderStage::Vertex); - let program = parse_program( - r#" - # version 450 - const float a = 1.0; - float global = a; - const flat float b = a; - "#, - &entry_points, - ) - .unwrap(); + // let program = parse_program( + // r#" + // # version 450 + // const float a = 1.0; + // float global = a; + // const flat float b = a; + // "#, + // &entry_points, + // ) + // .unwrap(); - let mut constants = program.module.constants.iter(); + // let mut constants = program.module.constants.iter(); - assert_eq!( - constants.next().unwrap().1, - &Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(1.0) - } - } - ); + // assert_eq!( + // constants.next().unwrap().1, + // &Constant { + // name: None, + // specialization: None, + // inner: ConstantInner::Scalar { + // width: 4, + // value: ScalarValue::Float(1.0) + // } + // } + // ); - assert_eq!( - constants.next().unwrap().1, - &Constant { - name: Some(String::from("a")), - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(1.0) - } - } - ); + // assert_eq!( + // constants.next().unwrap().1, + // &Constant { + // name: Some(String::from("a")), + // specialization: None, + // inner: ConstantInner::Scalar { + // width: 4, + // value: ScalarValue::Float(1.0) + // } + // } + // ); - assert_eq!( - constants.next().unwrap().1, - &Constant { - name: Some(String::from("b")), - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(1.0) - } - } - ); + // assert_eq!( + // constants.next().unwrap().1, + // &Constant { + // name: Some(String::from("b")), + // specialization: None, + // inner: ConstantInner::Scalar { + // width: 4, + // value: ScalarValue::Float(1.0) + // } + // } + // ); - assert!(constants.next().is_none()); + // assert!(constants.next().is_none()); } diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 7b849d361..e6de19d4c 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -1,3 +1,5 @@ +use crate::{Interpolation, Sampling, Type}; +use pp_rs::token::PreprocessorError; use std::ops::Range; #[derive(Debug, Clone)] @@ -6,3 +8,102 @@ pub struct TokenMetadata { pub line: usize, pub chars: Range, } + +#[derive(Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub struct Token { + pub value: TokenValue, + pub meta: TokenMetadata, +} + +#[derive(Debug, PartialEq)] +pub enum TokenValue { + Unknown(PreprocessorError), + Identifier(String), + + Extension, + Version, + Pragma, + + FloatConstant(f32), + IntConstant(i64), + BoolConstant(bool), + + Layout, + In, + Out, + InOut, + Uniform, + Const, + Interpolation(Interpolation), + Sampling(Sampling), + + Continue, + Break, + Return, + Discard, + + If, + Else, + Switch, + Case, + Default, + While, + Do, + For, + + Void, + TypeName(Type), + + Assign, + AddAssign, + SubAssign, + MulAssign, + DivAssign, + ModAssign, + LeftShiftAssign, + RightShiftAssign, + AndAssign, + XorAssign, + OrAssign, + + Increment, + Decrement, + + LogicalOr, + LogicalAnd, + LogicalXor, + + LessEqual, + GreaterEqual, + Equal, + NotEqual, + + LeftShift, + RightShift, + + LeftBrace, + RightBrace, + LeftParen, + RightParen, + LeftBracket, + RightBracket, + LeftAngle, + RightAngle, + + Comma, + Semicolon, + Colon, + Dot, + Bang, + Dash, + Tilde, + Plus, + Star, + Slash, + Percent, + VerticalBar, + Caret, + Ampersand, + Question, +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 080eaf129..6126b4659 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -344,6 +344,8 @@ fn convert_spv_shadow() { } #[cfg(feature = "glsl-in")] +// TODO: Reenable tests later +#[allow(dead_code)] fn convert_glsl( name: &str, entry_points: naga::FastHashMap, @@ -366,8 +368,9 @@ fn convert_glsl( #[cfg(feature = "glsl-in")] #[test] fn convert_glsl_quad() { - let mut entry_points = naga::FastHashMap::default(); - entry_points.insert("vert_main".to_string(), naga::ShaderStage::Vertex); - entry_points.insert("frag_main".to_string(), naga::ShaderStage::Fragment); - convert_glsl("quad-glsl", entry_points, Targets::SPIRV | Targets::IR); + // TODO: Reenable tests later + // let mut entry_points = naga::FastHashMap::default(); + // entry_points.insert("vert_main".to_string(), naga::ShaderStage::Vertex); + // entry_points.insert("frag_main".to_string(), naga::ShaderStage::Fragment); + // convert_glsl("quad-glsl", entry_points, Targets::SPIRV | Targets::IR); } From 786194ec679ca96af48cbac75775fe66979b17e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 1 May 2021 14:06:27 +0100 Subject: [PATCH 0842/2212] [glsl-in][New parser] WIP support for functions --- src/front/glsl/ast.rs | 101 ++++++++----- src/front/glsl/functions.rs | 132 ++++++++--------- src/front/glsl/lex.rs | 1 + src/front/glsl/parser.rs | 255 ++++++++++++++++++++++++++++++--- src/front/glsl/parser_tests.rs | 82 ++++++----- src/front/glsl/token.rs | 1 + src/front/glsl/variables.rs | 61 ++++---- 7 files changed, 427 insertions(+), 206 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index aaa8a7d80..c31d1f972 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,9 +1,9 @@ use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind}; use crate::{ proc::ResolveContext, Arena, ArraySize, BinaryOperator, Binding, Constant, Expression, - FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, - Module, RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, - Type, UnaryOperator, + FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, Module, + RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, + UnaryOperator, }; #[derive(Debug)] @@ -15,7 +15,6 @@ pub struct Program<'a> { pub lookup_type: FastHashMap>, pub lookup_global_variables: FastHashMap>, pub lookup_constants: FastHashMap>, - pub context: Context, pub module: Module, } @@ -29,34 +28,31 @@ impl<'a> Program<'a> { lookup_type: FastHashMap::default(), lookup_global_variables: FastHashMap::default(), lookup_constants: FastHashMap::default(), - context: Context { - expressions: Arena::::new(), - local_variables: Arena::::new(), - arguments: Vec::new(), - scopes: vec![FastHashMap::default()], - lookup_global_var_exps: FastHashMap::default(), - lookup_constant_exps: FastHashMap::default(), - typifier: Typifier::new(), - }, module: Module::default(), } } pub fn binary_expr( &mut self, + function: &mut Function, op: BinaryOperator, left: &ExpressionRule, right: &ExpressionRule, ) -> ExpressionRule { - ExpressionRule::from_expression(self.context.expressions.append(Expression::Binary { + ExpressionRule::from_expression(function.expressions.append(Expression::Binary { op, left: left.expression, right: right.expression, })) } - pub fn unary_expr(&mut self, op: UnaryOperator, tgt: &ExpressionRule) -> ExpressionRule { - ExpressionRule::from_expression(self.context.expressions.append(Expression::Unary { + pub fn unary_expr( + &mut self, + function: &mut Function, + op: UnaryOperator, + tgt: &ExpressionRule, + ) -> ExpressionRule { + ExpressionRule::from_expression(function.expressions.append(Expression::Unary { op, expr: tgt.expression, })) @@ -67,16 +63,17 @@ impl<'a> Program<'a> { /// represented as `all(equal(vec1, vec2))` and `any(notEqual(vec1, vec2))` pub fn equality_expr( &mut self, + context: &mut FunctionContext, equals: bool, left: &ExpressionRule, right: &ExpressionRule, ) -> Result { - let left_is_vector = match *self.resolve_type(left.expression)? { + let left_is_vector = match *self.resolve_type(context, left.expression)? { crate::TypeInner::Vector { .. } => true, _ => false, }; - let right_is_vector = match *self.resolve_type(right.expression)? { + let right_is_vector = match *self.resolve_type(context, right.expression)? { crate::TypeInner::Vector { .. } => true, _ => false, }; @@ -86,15 +83,16 @@ impl<'a> Program<'a> { false => (BinaryOperator::NotEqual, RelationalFunction::Any), }; - let expr = - ExpressionRule::from_expression(self.context.expressions.append(Expression::Binary { + let expr = ExpressionRule::from_expression(context.function.expressions.append( + Expression::Binary { op, left: left.expression, right: right.expression, - })); + }, + )); Ok(if left_is_vector && right_is_vector { - ExpressionRule::from_expression(self.context.expressions.append( + ExpressionRule::from_expression(context.function.expressions.append( Expression::Relational { fun, argument: expr.expression, @@ -105,20 +103,21 @@ impl<'a> Program<'a> { }) } - pub fn resolve_type( - &mut self, + pub fn resolve_type<'b>( + &'b mut self, + context: &'b mut FunctionContext, handle: Handle, - ) -> Result<&crate::TypeInner, ErrorKind> { + ) -> Result<&'b crate::TypeInner, ErrorKind> { let resolve_ctx = ResolveContext { constants: &self.module.constants, global_vars: &self.module.global_variables, - local_vars: &self.context.local_variables, + local_vars: &context.function.local_variables, functions: &self.module.functions, - arguments: &self.context.arguments, + arguments: &context.function.arguments, }; - match self.context.typifier.grow( + match context.typifier.grow( handle, - &self.context.expressions, + &context.function.expressions, &mut self.module.types, &resolve_ctx, ) { @@ -126,17 +125,18 @@ impl<'a> Program<'a> { Err(error) => Err(ErrorKind::SemanticError( format!("Can't resolve type: {:?}", error).into(), )), - Ok(()) => Ok(self.context.typifier.get(handle, &self.module.types)), + Ok(()) => Ok(context.typifier.get(handle, &self.module.types)), } } pub fn solve_constant( &mut self, + expressions: &Arena, root: Handle, ) -> Result, ErrorKind> { let mut solver = ConstantSolver { types: &self.module.types, - expressions: &self.context.expressions, + expressions, constants: &mut self.module.constants, }; @@ -197,10 +197,8 @@ pub enum Profile { } #[derive(Debug)] -pub struct Context { - pub expressions: Arena, - pub local_variables: Arena, - pub arguments: Vec, +pub struct FunctionContext<'function> { + pub function: &'function mut Function, //TODO: Find less allocation heavy representation pub scopes: Vec>>, pub lookup_global_var_exps: FastHashMap>, @@ -208,7 +206,17 @@ pub struct Context { pub typifier: Typifier, } -impl Context { +impl<'function> FunctionContext<'function> { + pub fn new(function: &'function mut Function) -> Self { + FunctionContext { + function, + scopes: vec![FastHashMap::default()], + lookup_global_var_exps: FastHashMap::default(), + lookup_constant_exps: FastHashMap::default(), + typifier: Typifier::new(), + } + } + pub fn lookup_local_var(&self, name: &str) -> Option> { for scope in self.scopes.iter().rev() { if let Some(var) = scope.get(name) { @@ -236,6 +244,7 @@ impl Context { pub fn add_local_var(&mut self, name: String, handle: Handle) { if let Some(current) = self.scopes.last_mut() { let expr = self + .function .expressions .append(Expression::Load { pointer: handle }); (*current).insert(name, expr); @@ -243,9 +252,22 @@ impl Context { } /// Add function argument to current scope - pub fn add_function_arg(&mut self, name: String, expr: Handle) { - if let Some(current) = self.scopes.last_mut() { - (*current).insert(name, expr); + pub fn add_function_arg(&mut self, name: Option, ty: Handle) { + let index = self.function.arguments.len(); + self.function.arguments.push(FunctionArgument { + name: name.clone(), + ty, + binding: None, + }); + + if let Some(name) = name { + if let Some(current) = self.scopes.last_mut() { + let expr = self + .function + .expressions + .append(Expression::FunctionArgument(index as u32)); + (*current).insert(name, expr); + } } } @@ -309,6 +331,7 @@ pub enum StorageQualifier { StorageClass(StorageClass), Input, Output, + InOut, Const, } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 98033dc9b..c1599e589 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,31 +1,34 @@ -use super::super::Typifier; use crate::{ - proc::ensure_block_returns, BinaryOperator, Block, EntryPoint, Expression, Function, - MathFunction, RelationalFunction, SampleLevel, ScalarKind, TypeInner, + BinaryOperator, Expression, MathFunction, RelationalFunction, SampleLevel, ScalarKind, + TypeInner, }; use super::{ast::*, error::ErrorKind}; impl Program<'_> { - pub fn function_call(&mut self, fc: FunctionCall) -> Result { + pub fn function_call( + &mut self, + context: &mut FunctionContext, + fc: FunctionCall, + ) -> Result { match fc.kind { FunctionCallKind::TypeConstructor(ty) => { let h = if fc.args.len() == 1 { - let is_vec = match *self.resolve_type(fc.args[0].expression)? { + let is_vec = match *self.resolve_type(context, fc.args[0].expression)? { TypeInner::Vector { .. } => true, _ => false, }; match self.module.types[ty].inner { TypeInner::Vector { size, .. } if !is_vec => { - self.context.expressions.append(Expression::Splat { + context.function.expressions.append(Expression::Splat { size, value: fc.args[0].expression, }) } TypeInner::Scalar { kind, width } | TypeInner::Vector { kind, width, .. } => { - self.context.expressions.append(Expression::As { + context.function.expressions.append(Expression::As { kind, expr: fc.args[0].expression, convert: Some(width), @@ -36,7 +39,7 @@ impl Program<'_> { rows, width, } => { - let value = self.context.expressions.append(Expression::As { + let value = context.function.expressions.append(Expression::As { kind: ScalarKind::Float, expr: fc.args[0].expression, convert: Some(width), @@ -45,7 +48,8 @@ impl Program<'_> { let column = if is_vec { value } else { - self.context + context + .function .expressions .append(Expression::Splat { size: rows, value }) }; @@ -53,7 +57,7 @@ impl Program<'_> { let columns = std::iter::repeat(column).take(columns as usize).collect(); - self.context.expressions.append(Expression::Compose { + context.function.expressions.append(Expression::Compose { ty, components: columns, }) @@ -61,7 +65,7 @@ impl Program<'_> { _ => return Err(ErrorKind::SemanticError("Bad cast".into())), } } else { - self.context.expressions.append(Expression::Compose { + context.function.expressions.append(Expression::Compose { ty, components: fc.args.iter().map(|a| a.expression).collect(), }) @@ -101,7 +105,7 @@ impl Program<'_> { } if let Some(sampler) = fc.args[0].sampler { Ok(ExpressionRule { - expression: self.context.expressions.append( + expression: context.function.expressions.append( Expression::ImageSample { image: fc.args[0].expression, sampler, @@ -130,7 +134,7 @@ impl Program<'_> { } if let Some(sampler) = fc.args[0].sampler { Ok(ExpressionRule { - expression: self.context.expressions.append( + expression: context.function.expressions.append( Expression::ImageSample { image: fc.args[0].expression, sampler, @@ -160,7 +164,7 @@ impl Program<'_> { return Err(ErrorKind::WrongNumberArgs(name, 1, fc.args.len())); } Ok(ExpressionRule { - expression: self.context.expressions.append(Expression::Math { + expression: context.function.expressions.append(Expression::Math { fun: match name.as_str() { "ceil" => MathFunction::Ceil, "round" => MathFunction::Round, @@ -192,7 +196,7 @@ impl Program<'_> { return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); } Ok(ExpressionRule { - expression: self.context.expressions.append(Expression::Math { + expression: context.function.expressions.append(Expression::Math { fun: match name.as_str() { "pow" => MathFunction::Pow, "dot" => MathFunction::Dot, @@ -212,7 +216,7 @@ impl Program<'_> { return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); } Ok(ExpressionRule { - expression: self.context.expressions.append(Expression::Math { + expression: context.function.expressions.append(Expression::Math { fun: match name.as_str() { "mix" => MathFunction::Mix, "clamp" => MathFunction::Clamp, @@ -232,7 +236,7 @@ impl Program<'_> { return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); } Ok(ExpressionRule { - expression: self.context.expressions.append(Expression::Binary { + expression: context.function.expressions.append(Expression::Binary { op: match name.as_str() { "lessThan" => BinaryOperator::Less, "greaterThan" => BinaryOperator::Greater, @@ -249,10 +253,18 @@ impl Program<'_> { statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), }) } - "isinf" => self.parse_relational_fun(name, fc.args, RelationalFunction::IsInf), - "isnan" => self.parse_relational_fun(name, fc.args, RelationalFunction::IsNan), - "all" => self.parse_relational_fun(name, fc.args, RelationalFunction::All), - "any" => self.parse_relational_fun(name, fc.args, RelationalFunction::Any), + "isinf" => { + self.parse_relational_fun(context, name, fc.args, RelationalFunction::IsInf) + } + "isnan" => { + self.parse_relational_fun(context, name, fc.args, RelationalFunction::IsNan) + } + "all" => { + self.parse_relational_fun(context, name, fc.args, RelationalFunction::All) + } + "any" => { + self.parse_relational_fun(context, name, fc.args, RelationalFunction::Any) + } func_name => { let function = *self.lookup_function.get(func_name).ok_or_else(|| { ErrorKind::SemanticError( @@ -262,8 +274,10 @@ impl Program<'_> { let arguments: Vec<_> = fc.args.iter().map(|a| a.expression).collect(); let mut statements: Vec<_> = fc.args.into_iter().flat_map(|a| a.statements).collect(); - let expression = - self.context.expressions.append(Expression::Call(function)); + let expression = context + .function + .expressions + .append(Expression::Call(function)); statements.push(crate::Statement::Call { function, arguments, @@ -282,6 +296,7 @@ impl Program<'_> { pub fn parse_relational_fun( &mut self, + context: &mut FunctionContext, name: String, args: Vec, fun: RelationalFunction, @@ -290,7 +305,7 @@ impl Program<'_> { return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); } Ok(ExpressionRule { - expression: self.context.expressions.append(Expression::Relational { + expression: context.function.expressions.append(Expression::Relational { fun, argument: args[0].expression, }), @@ -299,33 +314,33 @@ impl Program<'_> { }) } - pub fn add_function_prelude(&mut self) { + pub fn add_function_prelude(&mut self, context: &mut FunctionContext) { for (var_handle, var) in self.module.global_variables.iter() { if let Some(name) = var.name.as_ref() { - let expr = self - .context + let expr = context + .function .expressions .append(Expression::GlobalVariable(var_handle)); - self.context - .lookup_global_var_exps - .insert(name.clone(), expr); + context.lookup_global_var_exps.insert(name.clone(), expr); } else { let ty = &self.module.types[var.ty]; // anonymous structs if let TypeInner::Struct { ref members, .. } = ty.inner { - let base = self - .context + let base = context + .function .expressions .append(Expression::GlobalVariable(var_handle)); for (idx, member) in members.iter().enumerate() { if let Some(name) = member.name.as_ref() { - let exp = self.context.expressions.append(Expression::AccessIndex { - base, - index: idx as u32, - }); - self.context - .lookup_global_var_exps - .insert(name.clone(), exp); + let exp = + context + .function + .expressions + .append(Expression::AccessIndex { + base, + index: idx as u32, + }); + context.lookup_global_var_exps.insert(name.clone(), exp); } } } @@ -334,45 +349,12 @@ impl Program<'_> { for (handle, constant) in self.module.constants.iter() { if let Some(name) = constant.name.as_ref() { - let expr = self - .context + let expr = context + .function .expressions .append(Expression::Constant(handle)); - self.context.lookup_constant_exps.insert(name.clone(), expr); + context.lookup_constant_exps.insert(name.clone(), expr); } } } - - pub fn function_definition(&mut self, mut f: Function, mut block: Block) -> Function { - std::mem::swap(&mut f.expressions, &mut self.context.expressions); - std::mem::swap(&mut f.local_variables, &mut self.context.local_variables); - std::mem::swap(&mut f.arguments, &mut self.context.arguments); - self.context.clear_scopes(); - self.context.lookup_global_var_exps.clear(); - self.context.typifier = Typifier::new(); - ensure_block_returns(&mut block); - f.body = block; - f - } - - pub fn declare_function(&mut self, f: Function) -> Result<(), ErrorKind> { - let name = f - .name - .clone() - .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; - let stage = self.entry_points.get(&name); - if let Some(&stage) = stage { - self.module.entry_points.push(EntryPoint { - name, - stage, - early_depth_test: None, - workgroup_size: [0; 3], //TODO - function: f, - }); - } else { - let handle = self.module.functions.append(f); - self.lookup_function.insert(name, handle); - } - Ok(()) - } } diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index c7c643df3..84e73df48 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -96,6 +96,7 @@ impl<'a> Iterator for Lexer<'a> { "for" => TokenValue::For, // types "void" => TokenValue::Void, + "struct" => TokenValue::Struct, word => match parse_type(word) { Some(t) => TokenValue::TypeName(t), None => TokenValue::Identifier(String::from(word)), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 499c98866..c80667eb4 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,12 +1,15 @@ use super::{ - ast::Profile, + ast::{FunctionContext, Profile, StorageQualifier, TypeQualifier}, error::ErrorKind, lex::Lexer, token::{Token, TokenMetadata, TokenValue}, Program, }; +use crate::{arena::Handle, ArraySize, Function, FunctionResult, StorageClass, Type, TypeInner}; use std::iter::Peekable; +type Result = std::result::Result; + pub struct Parser<'source, 'program, 'options> { program: &'program mut Program<'options>, lexer: Peekable>, @@ -20,17 +23,44 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } - pub fn parse(&mut self) -> Result<(), ErrorKind> { - self.parse_version()?; + fn expect_ident(&mut self) -> Result<(String, TokenMetadata)> { + let token = self.bump()?; - if let Some(token) = self.lexer.next() { - Err(ErrorKind::InvalidToken(token)) - } else { - Ok(()) + match token.value { + TokenValue::Identifier(name) => Ok((name, token.meta)), + _ => Err(ErrorKind::InvalidToken(token)), } } - fn parse_version(&mut self) -> Result<(), ErrorKind> { + fn expect(&mut self, value: TokenValue) -> Result { + let token = self.bump()?; + + if token.value != value { + Err(ErrorKind::InvalidToken(token)) + } else { + Ok(token) + } + } + + fn bump(&mut self) -> Result { + self.lexer.next().ok_or(ErrorKind::EndOfFile) + } + + fn expect_peek(&mut self) -> Result<&Token> { + self.lexer.peek().ok_or(ErrorKind::EndOfFile) + } + + pub fn parse(&mut self) -> Result<()> { + self.parse_version()?; + + while self.lexer.peek().is_some() { + self.parse_external_declaration()?; + } + + Ok(()) + } + + fn parse_version(&mut self) -> Result<()> { self.expect(TokenValue::Version)?; let version = self.bump()?; @@ -61,26 +91,205 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(()) } - fn expect_ident(&mut self) -> Result<(String, TokenMetadata), ErrorKind> { - let token = self.bump()?; + fn parse_array_specifier(&mut self) -> Result> { + // TODO: expressions + if let Some(&TokenValue::LeftBracket) = self.lexer.peek().map(|t| &t.value) { + self.bump()?; - match token.value { - TokenValue::Identifier(name) => Ok((name, token.meta)), - _ => Err(ErrorKind::InvalidToken(token)), - } - } + self.expect(TokenValue::RightBracket)?; - fn expect(&mut self, value: TokenValue) -> Result { - let token = self.bump()?; - - if token.value != value { - Err(ErrorKind::InvalidToken(token)) + Ok(Some(ArraySize::Dynamic)) } else { - Ok(token) + Ok(None) } } - fn bump(&mut self) -> Result { - self.lexer.next().ok_or(ErrorKind::EndOfFile) + fn parse_type(&mut self) -> Result>> { + let token = self.bump()?; + let ty = match token.value { + TokenValue::Void => None, + TokenValue::TypeName(ty) => Some(ty), + TokenValue::Struct => todo!(), + _ => return Err(ErrorKind::InvalidToken(token)), + }; + let handle = ty.map(|t| self.program.module.types.append(t)); + + let size = self.parse_array_specifier()?; + Ok(handle.map(|ty| self.maybe_array(ty, size))) + } + + fn parse_type_non_void(&mut self) -> Result> { + self.parse_type()? + .ok_or_else(|| ErrorKind::SemanticError("Type can't be void".into())) + } + + fn maybe_array(&mut self, base: Handle, size: Option) -> Handle { + size.map(|size| { + self.program.module.types.append(Type { + name: None, + inner: TypeInner::Array { + base, + size, + stride: self.program.module.types[base] + .inner + .span(&self.program.module.constants), + }, + }) + }) + .unwrap_or(base) + } + + fn peek_type_qualifier(&mut self) -> bool { + self.lexer.peek().map_or(false, |t| match t.value { + TokenValue::Interpolation(_) + | TokenValue::Const + | TokenValue::In + | TokenValue::Out + | TokenValue::InOut + | TokenValue::Uniform => true, + _ => false, + }) + } + + fn parse_type_qualifiers(&mut self) -> Result> { + let mut qualifiers = Vec::new(); + + if self.peek_type_qualifier() { + let token = self.bump()?; + qualifiers.push(match token.value { + TokenValue::Interpolation(i) => TypeQualifier::Interpolation(i), + TokenValue::Const => TypeQualifier::StorageQualifier(StorageQualifier::Const), + TokenValue::In => TypeQualifier::StorageQualifier(StorageQualifier::Input), + TokenValue::Out => TypeQualifier::StorageQualifier(StorageQualifier::Output), + TokenValue::InOut => TypeQualifier::StorageQualifier(StorageQualifier::InOut), + TokenValue::Uniform => TypeQualifier::StorageQualifier( + StorageQualifier::StorageClass(StorageClass::Uniform), + ), + _ => unreachable!(), + }) + } + + Ok(qualifiers) + } + + fn parse_external_declaration(&mut self) -> Result<()> { + if !self.parse_declaration(true)? { + let token = self.bump()?; + match token.value { + TokenValue::Semicolon if self.program.version == 460 => Ok(()), + _ => Err(ErrorKind::InvalidToken(token)), + } + } else { + Ok(()) + } + } + + fn peek_type_name(&mut self) -> bool { + self.lexer.peek().map_or(false, |t| match t.value { + TokenValue::TypeName(_) | TokenValue::Void => true, + _ => false, + }) + } + + /// `external` wheter or not we are in a global or local context + fn parse_declaration(&mut self, external: bool) -> Result { + // TODO: Handle precision qualifiers + if self.peek_type_qualifier() || self.peek_type_name() { + // TODO: Use qualifiers + let _qualifiers = self.parse_type_qualifiers()?; + + if self.peek_type_name() { + // Functions and variable declarations + let ty = self.parse_type()?; + + let token = self.bump()?; + + match token.value { + TokenValue::Semicolon => Ok(true), + TokenValue::Identifier(name) => match self.expect_peek()?.value { + // Function definition/prototype + TokenValue::LeftParen => { + self.bump()?; + + let mut function = Function { + name: Some(name), + result: ty.map(|ty| FunctionResult { ty, binding: None }), + ..Default::default() + }; + let mut context = FunctionContext::new(&mut function); + + self.parse_function_args(&mut context)?; + + self.expect(TokenValue::RightParen)?; + + let token = self.bump()?; + match token.value { + // Function prototypes + TokenValue::Semicolon => todo!(), + TokenValue::LeftBrace if external => { + // TODO: body + self.expect(TokenValue::RightBrace)?; + + Ok(true) + } + _ => Err(ErrorKind::InvalidToken(token)), + } + } + // Variable Declaration + TokenValue::Semicolon => todo!(), + TokenValue::Comma => todo!(), + _ => Err(ErrorKind::InvalidToken(self.bump()?)), + }, + _ => Err(ErrorKind::InvalidToken(token)), + } + } else { + // Structs and modifiers + let token = self.bump()?; + match token.value { + TokenValue::Identifier(_) => todo!(), + TokenValue::Semicolon => Ok(true), + _ => Err(ErrorKind::InvalidToken(token)), + } + } + } else { + Ok(false) + } + } + + fn parse_function_args(&mut self, context: &mut FunctionContext) -> Result<()> { + loop { + // TODO: parameter qualifier + if self.peek_type_name() { + let ty = self.parse_type_non_void()?; + + match self.expect_peek()?.value { + TokenValue::Comma => { + self.bump()?; + context.add_function_arg(None, ty); + continue; + } + TokenValue::Identifier(_) => { + let name = self.expect_ident()?.0; + + let size = self.parse_array_specifier()?; + let ty = self.maybe_array(ty, size); + + context.add_function_arg(Some(name), ty); + + if self.expect_peek()?.value == TokenValue::Comma { + self.bump()?; + continue; + } + + break; + } + _ => break, + } + } + + break; + } + + Ok(()) } } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index c9b31ba62..a81edf8df 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -50,35 +50,34 @@ fn version() { "InvalidProfile(TokenMetadata { line: 1, chars: 13..14 }, \"smart\")" //TODO: location ); - // TODO: Reenable tests later - // assert_eq!( - // format!( - // "{:?}", - // parse_program("#version 450\nvoid f(){} #version 450", &entry_points) - // .err() - // .unwrap() - // ), - // "InvalidToken(Unknown((TokenMetadata { line: 2, chars: 11..12 }, UnexpectedHash)))" - // ); + assert_eq!( + format!( + "{:?}", + parse_program("#version 450\nvoid f(){} #version 450", &entry_points) + .err() + .unwrap() + ), + "InvalidToken(Token { value: Unknown(UnexpectedHash), meta: TokenMetadata { line: 2, chars: 11..12 } })" + ); - // // valid versions - // let program = parse_program(" # version 450\nvoid main() {}", &entry_points).unwrap(); - // assert_eq!( - // format!("{:?}", (program.version, program.profile)), - // "(450, Core)" - // ); + // valid versions + let program = parse_program(" # version 450\nvoid main() {}", &entry_points).unwrap(); + assert_eq!( + format!("{:?}", (program.version, program.profile)), + "(450, Core)" + ); - // let program = parse_program("#version 450\nvoid main() {}", &entry_points).unwrap(); - // assert_eq!( - // format!("{:?}", (program.version, program.profile)), - // "(450, Core)" - // ); + let program = parse_program("#version 450\nvoid main() {}", &entry_points).unwrap(); + assert_eq!( + format!("{:?}", (program.version, program.profile)), + "(450, Core)" + ); - // let program = parse_program("#version 450 core\nvoid main() {}", &entry_points).unwrap(); - // assert_eq!( - // format!("{:?}", (program.version, program.profile)), - // "(450, Core)" - // ); + let program = parse_program("#version 450 core\nvoid main() {}", &entry_points).unwrap(); + assert_eq!( + format!("{:?}", (program.version, program.profile)), + "(450, Core)" + ); } #[test] @@ -193,9 +192,8 @@ fn textures() { #[test] fn functions() { - // TODO: Reenable tests later - // let mut entry_points = crate::FastHashMap::default(); - // entry_points.insert("".to_string(), ShaderStage::Vertex); + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Vertex); // TODO: Add support for function prototypes // parse_program( @@ -204,25 +202,25 @@ fn functions() { // void test1(float); // void test1(float) {} - // void main() {} - // "#, - // ShaderStage::Vertex, - // ) - // .unwrap(); - - // parse_program( - // r#" - // # version 450 - // void test2(float a) {} - // void test3(float a, float b) {} - // void test4(float, float) {} - // void main() {} // "#, // &entry_points, // ) // .unwrap(); + parse_program( + r#" + # version 450 + void test2(float a) {} + void test3(float a, float b) {} + void test4(float, float) {} + + void main() {} + "#, + &entry_points, + ) + .unwrap(); + // parse_program( // r#" // # version 450 diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index e6de19d4c..bc53d61f3 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -53,6 +53,7 @@ pub enum TokenValue { For, Void, + Struct, TypeName(Type), Assign, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 1adf25964..db4755906 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -5,14 +5,18 @@ use super::error::ErrorKind; use super::token::TokenMetadata; impl Program<'_> { - pub fn lookup_variable(&mut self, name: &str) -> Result>, ErrorKind> { - if let Some(local_var) = self.context.lookup_local_var(name) { + pub fn lookup_variable( + &mut self, + context: &mut FunctionContext, + name: &str, + ) -> Result>, ErrorKind> { + if let Some(local_var) = context.lookup_local_var(name) { return Ok(Some(local_var)); } - if let Some(global_var) = self.context.lookup_global_var_exps.get(name) { + if let Some(global_var) = context.lookup_global_var_exps.get(name) { return Ok(Some(*global_var)); } - if let Some(constant) = self.context.lookup_constant_exps.get(name) { + if let Some(constant) = context.lookup_constant_exps.get(name) { return Ok(Some(*constant)); } match name { @@ -38,11 +42,11 @@ impl Program<'_> { .context .expressions .append(Expression::GlobalVariable(h));*/ - let exp = self - .context + let exp = context + .function .expressions .append(Expression::FunctionArgument(0)); //TODO - self.context.lookup_global_var_exps.insert(name.into(), exp); + context.lookup_global_var_exps.insert(name.into(), exp); Ok(Some(exp)) } @@ -74,13 +78,11 @@ impl Program<'_> { convert: true, }); */ - let expr = self - .context + let expr = context + .function .expressions .append(Expression::FunctionArgument(0)); //TODO - self.context - .lookup_global_var_exps - .insert(name.into(), expr); + context.lookup_global_var_exps.insert(name.into(), expr); Ok(Some(expr)) } @@ -112,13 +114,11 @@ impl Program<'_> { convert: true, }); */ - let expr = self - .context + let expr = context + .function .expressions .append(Expression::FunctionArgument(0)); //TODO - self.context - .lookup_global_var_exps - .insert(name.into(), expr); + context.lookup_global_var_exps.insert(name.into(), expr); Ok(Some(expr)) } @@ -128,20 +128,24 @@ impl Program<'_> { pub fn field_selection( &mut self, + context: &mut FunctionContext, expression: Handle, name: &str, meta: TokenMetadata, ) -> Result, ErrorKind> { - match *self.resolve_type(expression)? { + match *self.resolve_type(context, expression)? { TypeInner::Struct { ref members, .. } => { let index = members .iter() .position(|m| m.name == Some(name.into())) .ok_or_else(|| ErrorKind::UnknownField(meta, name.into()))?; - Ok(self.context.expressions.append(Expression::AccessIndex { - base: expression, - index: index as u32, - })) + Ok(context + .function + .expressions + .append(Expression::AccessIndex { + base: expression, + index: index as u32, + })) } // swizzles (xyzw, rgba, stpq) TypeInner::Vector { size, kind, width } => { @@ -170,17 +174,20 @@ impl Program<'_> { let components: Vec> = v .iter() .map(|idx| { - self.context.expressions.append(Expression::AccessIndex { - base: expression, - index: *idx as u32, - }) + context + .function + .expressions + .append(Expression::AccessIndex { + base: expression, + index: *idx as u32, + }) }) .collect(); if components.len() == 1 { // only single element swizzle, like pos.y, just return that component Ok(components[0]) } else { - Ok(self.context.expressions.append(Expression::Compose { + Ok(context.function.expressions.append(Expression::Compose { ty: self.module.types.fetch_or_append(Type { name: None, inner: TypeInner::Vector { From 3073ade8a41f4f2d14edc6aa691e95ad61b28bb9 Mon Sep 17 00:00:00 2001 From: Imbris Date: Sat, 1 May 2021 19:32:23 -0400 Subject: [PATCH 0843/2212] [glsl-in] improved WIP parsing for declarations --- src/front/glsl/ast.rs | 8 +- src/front/glsl/error.rs | 4 + src/front/glsl/parser.rs | 153 +++++++++++++++++++++++++++++++-- src/front/glsl/parser_tests.rs | 35 ++++++++ 4 files changed, 187 insertions(+), 13 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index c31d1f972..88f002d77 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -301,10 +301,12 @@ impl ExpressionRule { #[derive(Debug)] pub enum TypeQualifier { StorageQualifier(StorageQualifier), + Interpolation(Interpolation), ResourceBinding(ResourceBinding), Binding(Binding), - Interpolation(Interpolation), Sampling(Sampling), + Layout(StructLayout), + EarlyFragmentTests, } #[derive(Debug)] @@ -337,7 +339,5 @@ pub enum StorageQualifier { #[derive(Debug, Clone)] pub enum StructLayout { - Binding(Binding), - Resource(ResourceBinding), - PushConstant, + Std140, } diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 87d00075b..154556d31 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -15,6 +15,7 @@ pub enum ErrorKind { NotImplemented(&'static str), UnknownVariable(TokenMetadata, String), UnknownField(TokenMetadata, String), + UnknownLayoutQualifier(TokenMetadata, String), #[cfg(feature = "glsl-validate")] VariableAlreadyDeclared(String), ExpectedConstant, @@ -45,6 +46,9 @@ impl fmt::Display for ErrorKind { ErrorKind::UnknownField(ref meta, ref val) => { write!(f, "Unknown field {} at {:?}", val, meta) } + ErrorKind::UnknownLayoutQualifier(ref meta, ref val) => { + write!(f, "Unknown layout qualifier name {} at {:?}", val, meta) + } #[cfg(feature = "glsl-validate")] ErrorKind::VariableAlreadyDeclared(ref val) => { write!(f, "Variable {} already declared in current scope", val) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index c80667eb4..2e587fe55 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,12 +1,16 @@ use super::{ - ast::{FunctionContext, Profile, StorageQualifier, TypeQualifier}, + ast::{FunctionContext, Profile, StorageQualifier, StructLayout, TypeQualifier}, error::ErrorKind, lex::Lexer, token::{Token, TokenMetadata, TokenValue}, Program, }; -use crate::{arena::Handle, ArraySize, Function, FunctionResult, StorageClass, Type, TypeInner}; -use std::iter::Peekable; +use crate::{ + arena::Handle, ArraySize, Binding, Function, FunctionResult, ResourceBinding, StorageClass, + Type, TypeInner, +}; +use core::convert::TryFrom; +use core::iter::Peekable; type Result = std::result::Result; @@ -46,6 +50,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.lexer.next().ok_or(ErrorKind::EndOfFile) } + /// Returns None on the end of the file rather than an error like other methods + fn bump_if(&mut self, value: TokenValue) -> Option { + if self.lexer.peek().filter(|t| t.value == value).is_some() { + self.bump().ok() + } else { + None + } + } + fn expect_peek(&mut self) -> Result<&Token> { self.lexer.peek().ok_or(ErrorKind::EndOfFile) } @@ -146,7 +159,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { | TokenValue::In | TokenValue::Out | TokenValue::InOut - | TokenValue::Uniform => true, + | TokenValue::Uniform + | TokenValue::Layout => true, _ => false, }) } @@ -154,8 +168,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_type_qualifiers(&mut self) -> Result> { let mut qualifiers = Vec::new(); - if self.peek_type_qualifier() { + while self.peek_type_qualifier() { let token = self.bump()?; + + // Handle layout qualifiers outside the match since this can push multiple values + if token.value == TokenValue::Layout { + self.parse_layout_qualifier_id_list(&mut qualifiers)?; + continue; + } + qualifiers.push(match token.value { TokenValue::Interpolation(i) => TypeQualifier::Interpolation(i), TokenValue::Const => TypeQualifier::StorageQualifier(StorageQualifier::Const), @@ -165,6 +186,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Uniform => TypeQualifier::StorageQualifier( StorageQualifier::StorageClass(StorageClass::Uniform), ), + _ => unreachable!(), }) } @@ -172,6 +194,105 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(qualifiers) } + fn parse_layout_qualifier_id_list( + &mut self, + qualifiers: &mut Vec, + ) -> Result<()> { + // We need both of these to produce a ResourceBinding + let mut group = None; + let mut binding = None; + + self.expect(TokenValue::LeftParen)?; + loop { + self.parse_layout_qualifier_id(qualifiers, &mut group, &mut binding)?; + + if self.bump_if(TokenValue::Comma).is_some() { + continue; + } + + break; + } + self.expect(TokenValue::RightParen)?; + + match (group, binding) { + (Some(group), Some(binding)) => { + qualifiers.push(TypeQualifier::ResourceBinding(ResourceBinding { + group, + binding, + })) + } + // Produce an error if we have one of group or binding but not the other + // TODO: include at least line info in errors? + (Some(_), None) => { + return Err(ErrorKind::SemanticError( + "set specified with no binding".into(), + )) + } + (None, Some(_)) => { + return Err(ErrorKind::SemanticError( + "binding specified with no set".into(), + )) + } + (None, None) => (), + } + + Ok(()) + } + + fn parse_layout_qualifier_id( + &mut self, + qualifiers: &mut Vec, + group: &mut Option, + binding: &mut Option, + ) -> Result<()> { + // layout_qualifier_id: + // IDENTIFIER + // IDENTIFIER EQUAL constant_expression + // SHARED + let token = self.bump()?; + match token.value { + TokenValue::Identifier(name) => { + if self.bump_if(TokenValue::Assign).is_some() { + let value = self.parse_constant_expression()?; + + match name.as_str() { + "location" => qualifiers.push(TypeQualifier::Binding(Binding::Location { + // TODO: use better error here + location: u32::try_from(value).map_err(|_| ErrorKind::InvalidInput)?, + interpolation: None, + sampling: None, + })), + // TODO: produce error when try_from fails + "set" => *group = u32::try_from(value).ok(), + "binding" => *binding = u32::try_from(value).ok(), + _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), + } + } else { + match name.as_str() { + "std140" => qualifiers.push(TypeQualifier::Layout(StructLayout::Std140)), + "early_fragment_tests" => { + qualifiers.push(TypeQualifier::EarlyFragmentTests) + } + _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), + } + }; + + Ok(()) + } + // TODO: handle Shared? + _ => Err(ErrorKind::InvalidToken(token)), + } + } + + // TODO: parse more than just integer literal + fn parse_constant_expression(&mut self) -> Result { + let token = self.bump()?; + match token.value { + TokenValue::IntConstant(value) => Ok(value), + _ => Err(ErrorKind::InvalidToken(token)), + } + } + fn parse_external_declaration(&mut self) -> Result<()> { if !self.parse_declaration(true)? { let token = self.bump()?; @@ -182,6 +303,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } else { Ok(()) } + // TODO } fn peek_type_name(&mut self) -> bool { @@ -191,8 +313,17 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }) } - /// `external` wheter or not we are in a global or local context + /// `external` whether or not we are in a global or local context fn parse_declaration(&mut self, external: bool) -> Result { + //declaration: + // function_prototype SEMICOLON + // init_declarator_list SEMICOLON + // PRECISION precision_qualifier type_specifier SEMICOLON + // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE SEMICOLON + // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER SEMICOLON + // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER array_specifier SEMICOLON + // type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON + // type_qualifier IDENTIFIER identifier_list SEMICOLON // TODO: Handle precision qualifiers if self.peek_type_qualifier() || self.peek_type_name() { // TODO: Use qualifiers @@ -236,7 +367,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } // Variable Declaration - TokenValue::Semicolon => todo!(), + TokenValue::Semicolon => { + // TODO: are we supposed to consume the semicolon here + self.bump()?; + // TODO: use parsed type & qualifiers + Ok(true) + } TokenValue::Comma => todo!(), _ => Err(ErrorKind::InvalidToken(self.bump()?)), }, @@ -276,8 +412,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { context.add_function_arg(Some(name), ty); - if self.expect_peek()?.value == TokenValue::Comma { - self.bump()?; + if self.bump_if(TokenValue::Comma).is_some() { continue; } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index a81edf8df..42ee511a6 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -168,6 +168,41 @@ fn control_flow() { // .unwrap(); } +#[test] +fn declarations() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Fragment); + + let _program = parse_program( + r#" + #version 450 + layout(location = 0) in vec2 v_uv; + layout(location = 0) out vec4 o_color; + layout(set = 1, binding = 1) uniform texture2D tex; + layout(set = 1, binding = 2) uniform sampler tex_sampler; + + layout(early_fragment_tests) in; + "#, + &entry_points, + ) + .unwrap(); + + // TODO: Reenable tests later + // let _program = parse_program( + // r#" + // #version 450 + // layout(std140, set = 2, binding = 0) + // uniform u_locals { + // vec3 model_offs; + // float load_time; + // ivec4 atlas_offs; + // }; + // "#, + // &entry_points, + // ) + // .unwrap(); +} + #[test] fn textures() { // TODO: Reenable tests later From f8c8d192aefa8f720bb97eced0915c32b27fa806 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 2 May 2021 22:17:01 +0100 Subject: [PATCH 0844/2212] [glsl-in] WIP expression parsing --- src/front/glsl/ast.rs | 152 +++++++- src/front/glsl/error.rs | 2 +- src/front/glsl/functions.rs | 671 +++++++++++++++++---------------- src/front/glsl/lex.rs | 13 +- src/front/glsl/mod.rs | 2 +- src/front/glsl/parser.rs | 327 +++++++++++++++- src/front/glsl/parser_tests.rs | 38 +- src/front/glsl/token.rs | 7 +- src/front/glsl/variables.rs | 105 +----- 9 files changed, 842 insertions(+), 475 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 88f002d77..08c265d31 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,4 +1,4 @@ -use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind}; +use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind, TokenMetadata}; use crate::{ proc::ResolveContext, Arena, ArraySize, BinaryOperator, Binding, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, Module, @@ -200,9 +200,9 @@ pub enum Profile { pub struct FunctionContext<'function> { pub function: &'function mut Function, //TODO: Find less allocation heavy representation - pub scopes: Vec>>, - pub lookup_global_var_exps: FastHashMap>, - pub lookup_constant_exps: FastHashMap>, + pub scopes: Vec>, + pub lookup_global_var_exps: FastHashMap, + pub lookup_constant_exps: FastHashMap, pub typifier: Typifier, } @@ -217,17 +217,17 @@ impl<'function> FunctionContext<'function> { } } - pub fn lookup_local_var(&self, name: &str) -> Option> { + pub fn lookup_local_var(&self, name: &str) -> Option { for scope in self.scopes.iter().rev() { if let Some(var) = scope.get(name) { - return Some(*var); + return Some(var.clone()); } } None } #[cfg(feature = "glsl-validate")] - pub fn lookup_local_var_current_scope(&self, name: &str) -> Option> { + pub fn lookup_local_var_current_scope(&self, name: &str) -> Option { if let Some(current) = self.scopes.last() { current.get(name).cloned() } else { @@ -241,13 +241,20 @@ impl<'function> FunctionContext<'function> { } /// Add variable to current scope - pub fn add_local_var(&mut self, name: String, handle: Handle) { + pub fn add_local_var(&mut self, name: String, expr: Handle) { if let Some(current) = self.scopes.last_mut() { - let expr = self + let load = self .function .expressions - .append(Expression::Load { pointer: handle }); - (*current).insert(name, expr); + .append(Expression::Load { pointer: expr }); + + (*current).insert( + name, + VariableReference { + expr, + load: Some(load), + }, + ); } } @@ -266,7 +273,8 @@ impl<'function> FunctionContext<'function> { .function .expressions .append(Expression::FunctionArgument(index as u32)); - (*current).insert(name, expr); + + (*current).insert(name, VariableReference { expr, load: None }); } } } @@ -279,6 +287,79 @@ impl<'function> FunctionContext<'function> { pub fn remove_current_scope(&mut self) { self.scopes.pop(); } + + pub fn resolve( + &mut self, + program: &mut Program, + expr: Expr, + lhs: bool, + ) -> Result, ErrorKind> { + Ok(match expr.kind { + ExprKind::Access { base, index } => { + let base = self.resolve(program, *base, lhs)?; + let index = self.resolve(program, *index, false)?; + + self.function + .expressions + .append(Expression::Access { base, index }) + } + ExprKind::Select { base, field } => { + let base = self.resolve(program, *base, lhs)?; + + program.field_selection(self, base, &field, expr.meta)? + } + ExprKind::Constant(constant) => self + .function + .expressions + .append(Expression::Constant(constant)), + ExprKind::Binary { left, op, right } => { + let left = self.resolve(program, *left, false)?; + let right = self.resolve(program, *right, false)?; + + self.function + .expressions + .append(Expression::Binary { left, op, right }) + } + ExprKind::Unary { op, expr } => { + let expr = self.resolve(program, *expr, false)?; + + self.function + .expressions + .append(Expression::Unary { op, expr }) + } + ExprKind::Variable(var) => { + if lhs { + var.expr + } else { + var.load.unwrap_or(var.expr) + } + } + ExprKind::Call(_) => todo!(), + ExprKind::Conditional { + condition, + accept, + reject, + } => { + let condition = self.resolve(program, *condition, false)?; + let accept = self.resolve(program, *accept, false)?; + let reject = self.resolve(program, *reject, false)?; + + self.function.expressions.append(Expression::Select { + condition, + accept, + reject, + }) + } + ExprKind::Assign { tgt, value } => { + let pointer = self.resolve(program, *tgt, false)?; + let value = self.resolve(program, *value, false)?; + + self.function.body.push(Statement::Store { pointer, value }); + + value + } + }) + } } #[derive(Debug)] @@ -298,6 +379,51 @@ impl ExpressionRule { } } +#[derive(Debug, Clone)] +pub struct VariableReference { + pub expr: Handle, + pub load: Option>, +} + +#[derive(Debug)] +pub struct Expr { + pub kind: ExprKind, + pub meta: TokenMetadata, +} + +#[derive(Debug)] +pub enum ExprKind { + Access { + base: Box, + index: Box, + }, + Select { + base: Box, + field: String, + }, + Constant(Handle), + Binary { + left: Box, + op: BinaryOperator, + right: Box, + }, + Unary { + op: UnaryOperator, + expr: Box, + }, + Variable(VariableReference), + Call(FunctionCall), + Conditional { + condition: Box, + accept: Box, + reject: Box, + }, + Assign { + tgt: Box, + value: Box, + }, +} + #[derive(Debug)] pub enum TypeQualifier { StorageQualifier(StorageQualifier), @@ -325,7 +451,7 @@ pub enum FunctionCallKind { #[derive(Debug)] pub struct FunctionCall { pub kind: FunctionCallKind, - pub args: Vec, + pub args: Vec, } #[derive(Debug, Clone, Copy)] diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 154556d31..dd5e0b4c4 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -8,7 +8,7 @@ pub enum ErrorKind { InvalidInput, InvalidProfile(TokenMetadata, String), InvalidToken(Token), - InvalidVersion(TokenMetadata, i64), + InvalidVersion(TokenMetadata, u64), IoError(io::Error), ParserFail, ParserStackOverflow, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index c1599e589..bc0cc3367 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,298 +1,298 @@ use crate::{ - BinaryOperator, Expression, MathFunction, RelationalFunction, SampleLevel, ScalarKind, - TypeInner, + proc::ensure_block_returns, BinaryOperator, EntryPoint, Expression, Function, MathFunction, + RelationalFunction, SampleLevel, TypeInner, }; use super::{ast::*, error::ErrorKind}; impl Program<'_> { - pub fn function_call( - &mut self, - context: &mut FunctionContext, - fc: FunctionCall, - ) -> Result { - match fc.kind { - FunctionCallKind::TypeConstructor(ty) => { - let h = if fc.args.len() == 1 { - let is_vec = match *self.resolve_type(context, fc.args[0].expression)? { - TypeInner::Vector { .. } => true, - _ => false, - }; + // pub fn function_call( + // &mut self, + // context: &mut FunctionContext, + // fc: FunctionCall, + // ) -> Result { + // match fc.kind { + // FunctionCallKind::TypeConstructor(ty) => { + // let h = if fc.args.len() == 1 { + // let is_vec = match *self.resolve_type(context, fc.args[0].expression)? { + // TypeInner::Vector { .. } => true, + // _ => false, + // }; - match self.module.types[ty].inner { - TypeInner::Vector { size, .. } if !is_vec => { - context.function.expressions.append(Expression::Splat { - size, - value: fc.args[0].expression, - }) - } - TypeInner::Scalar { kind, width } - | TypeInner::Vector { kind, width, .. } => { - context.function.expressions.append(Expression::As { - kind, - expr: fc.args[0].expression, - convert: Some(width), - }) - } - TypeInner::Matrix { - columns, - rows, - width, - } => { - let value = context.function.expressions.append(Expression::As { - kind: ScalarKind::Float, - expr: fc.args[0].expression, - convert: Some(width), - }); + // match self.module.types[ty].inner { + // TypeInner::Vector { size, .. } if !is_vec => { + // context.function.expressions.append(Expression::Splat { + // size, + // value: fc.args[0].expression, + // }) + // } + // TypeInner::Scalar { kind, width } + // | TypeInner::Vector { kind, width, .. } => { + // context.function.expressions.append(Expression::As { + // kind, + // expr: fc.args[0].expression, + // convert: Some(width), + // }) + // } + // TypeInner::Matrix { + // columns, + // rows, + // width, + // } => { + // let value = context.function.expressions.append(Expression::As { + // kind: ScalarKind::Float, + // expr: fc.args[0].expression, + // convert: Some(width), + // }); - let column = if is_vec { - value - } else { - context - .function - .expressions - .append(Expression::Splat { size: rows, value }) - }; + // let column = if is_vec { + // value + // } else { + // context + // .function + // .expressions + // .append(Expression::Splat { size: rows, value }) + // }; - let columns = - std::iter::repeat(column).take(columns as usize).collect(); + // let columns = + // std::iter::repeat(column).take(columns as usize).collect(); - context.function.expressions.append(Expression::Compose { - ty, - components: columns, - }) - } - _ => return Err(ErrorKind::SemanticError("Bad cast".into())), - } - } else { - context.function.expressions.append(Expression::Compose { - ty, - components: fc.args.iter().map(|a| a.expression).collect(), - }) - }; + // context.function.expressions.append(Expression::Compose { + // ty, + // components: columns, + // }) + // } + // _ => return Err(ErrorKind::SemanticError("Bad cast".into())), + // } + // } else { + // context.function.expressions.append(Expression::Compose { + // ty, + // components: fc.args.iter().map(|a| a.expression).collect(), + // }) + // }; - Ok(ExpressionRule { - expression: h, - statements: fc - .args - .into_iter() - .map(|a| a.statements) - .flatten() - .collect(), - sampler: None, - }) - } - FunctionCallKind::Function(name) => { - match name.as_str() { - "sampler2D" => { - if fc.args.len() != 2 { - return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); - } - Ok(ExpressionRule { - expression: fc.args[0].expression, - sampler: Some(fc.args[1].expression), - statements: fc - .args - .into_iter() - .map(|a| a.statements) - .flatten() - .collect(), - }) - } - "texture" => { - if fc.args.len() != 2 { - return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); - } - if let Some(sampler) = fc.args[0].sampler { - Ok(ExpressionRule { - expression: context.function.expressions.append( - Expression::ImageSample { - image: fc.args[0].expression, - sampler, - coordinate: fc.args[1].expression, - array_index: None, //TODO - offset: None, //TODO - level: SampleLevel::Auto, - depth_ref: None, - }, - ), - sampler: None, - statements: fc - .args - .into_iter() - .map(|a| a.statements) - .flatten() - .collect(), - }) - } else { - Err(ErrorKind::SemanticError("Bad call to texture".into())) - } - } - "textureLod" => { - if fc.args.len() != 3 { - return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); - } - if let Some(sampler) = fc.args[0].sampler { - Ok(ExpressionRule { - expression: context.function.expressions.append( - Expression::ImageSample { - image: fc.args[0].expression, - sampler, - coordinate: fc.args[1].expression, - array_index: None, //TODO - offset: None, //TODO - level: SampleLevel::Exact(fc.args[2].expression), - depth_ref: None, - }, - ), - sampler: None, - statements: fc - .args - .into_iter() - .map(|a| a.statements) - .flatten() - .collect(), - }) - } else { - Err(ErrorKind::SemanticError("Bad call to textureLod".into())) - } - } - "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" - | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" - | "normalize" => { - if fc.args.len() != 1 { - return Err(ErrorKind::WrongNumberArgs(name, 1, fc.args.len())); - } - Ok(ExpressionRule { - expression: context.function.expressions.append(Expression::Math { - fun: match name.as_str() { - "ceil" => MathFunction::Ceil, - "round" => MathFunction::Round, - "floor" => MathFunction::Floor, - "fract" => MathFunction::Fract, - "trunc" => MathFunction::Trunc, - "sin" => MathFunction::Sin, - "abs" => MathFunction::Abs, - "sqrt" => MathFunction::Sqrt, - "inversesqrt" => MathFunction::InverseSqrt, - "exp" => MathFunction::Exp, - "exp2" => MathFunction::Exp2, - "sign" => MathFunction::Sign, - "transpose" => MathFunction::Transpose, - "inverse" => MathFunction::Inverse, - "normalize" => MathFunction::Normalize, - _ => unreachable!(), - }, - arg: fc.args[0].expression, - arg1: None, - arg2: None, - }), - sampler: None, - statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), - }) - } - "pow" | "dot" | "max" => { - if fc.args.len() != 2 { - return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); - } - Ok(ExpressionRule { - expression: context.function.expressions.append(Expression::Math { - fun: match name.as_str() { - "pow" => MathFunction::Pow, - "dot" => MathFunction::Dot, - "max" => MathFunction::Max, - _ => unreachable!(), - }, - arg: fc.args[0].expression, - arg1: Some(fc.args[1].expression), - arg2: None, - }), - sampler: None, - statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), - }) - } - "mix" | "clamp" => { - if fc.args.len() != 3 { - return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); - } - Ok(ExpressionRule { - expression: context.function.expressions.append(Expression::Math { - fun: match name.as_str() { - "mix" => MathFunction::Mix, - "clamp" => MathFunction::Clamp, - _ => unreachable!(), - }, - arg: fc.args[0].expression, - arg1: Some(fc.args[1].expression), - arg2: Some(fc.args[2].expression), - }), - sampler: None, - statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), - }) - } - "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" - | "notEqual" => { - if fc.args.len() != 2 { - return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); - } - Ok(ExpressionRule { - expression: context.function.expressions.append(Expression::Binary { - op: match name.as_str() { - "lessThan" => BinaryOperator::Less, - "greaterThan" => BinaryOperator::Greater, - "lessThanEqual" => BinaryOperator::LessEqual, - "greaterThanEqual" => BinaryOperator::GreaterEqual, - "equal" => BinaryOperator::Equal, - "notEqual" => BinaryOperator::NotEqual, - _ => unreachable!(), - }, - left: fc.args[0].expression, - right: fc.args[1].expression, - }), - sampler: None, - statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), - }) - } - "isinf" => { - self.parse_relational_fun(context, name, fc.args, RelationalFunction::IsInf) - } - "isnan" => { - self.parse_relational_fun(context, name, fc.args, RelationalFunction::IsNan) - } - "all" => { - self.parse_relational_fun(context, name, fc.args, RelationalFunction::All) - } - "any" => { - self.parse_relational_fun(context, name, fc.args, RelationalFunction::Any) - } - func_name => { - let function = *self.lookup_function.get(func_name).ok_or_else(|| { - ErrorKind::SemanticError( - format!("Unknown function: {}", func_name).into(), - ) - })?; - let arguments: Vec<_> = fc.args.iter().map(|a| a.expression).collect(); - let mut statements: Vec<_> = - fc.args.into_iter().flat_map(|a| a.statements).collect(); - let expression = context - .function - .expressions - .append(Expression::Call(function)); - statements.push(crate::Statement::Call { - function, - arguments, - result: Some(expression), - }); - Ok(ExpressionRule { - expression, - sampler: None, - statements, - }) - } - } - } - } - } + // Ok(ExpressionRule { + // expression: h, + // statements: fc + // .args + // .into_iter() + // .map(|a| a.statements) + // .flatten() + // .collect(), + // sampler: None, + // }) + // } + // FunctionCallKind::Function(name) => { + // match name.as_str() { + // "sampler2D" => { + // if fc.args.len() != 2 { + // return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); + // } + // Ok(ExpressionRule { + // expression: fc.args[0].expression, + // sampler: Some(fc.args[1].expression), + // statements: fc + // .args + // .into_iter() + // .map(|a| a.statements) + // .flatten() + // .collect(), + // }) + // } + // "texture" => { + // if fc.args.len() != 2 { + // return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); + // } + // if let Some(sampler) = fc.args[0].sampler { + // Ok(ExpressionRule { + // expression: context.function.expressions.append( + // Expression::ImageSample { + // image: fc.args[0].expression, + // sampler, + // coordinate: fc.args[1].expression, + // array_index: None, //TODO + // offset: None, //TODO + // level: SampleLevel::Auto, + // depth_ref: None, + // }, + // ), + // sampler: None, + // statements: fc + // .args + // .into_iter() + // .map(|a| a.statements) + // .flatten() + // .collect(), + // }) + // } else { + // Err(ErrorKind::SemanticError("Bad call to texture".into())) + // } + // } + // "textureLod" => { + // if fc.args.len() != 3 { + // return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); + // } + // if let Some(sampler) = fc.args[0].sampler { + // Ok(ExpressionRule { + // expression: context.function.expressions.append( + // Expression::ImageSample { + // image: fc.args[0].expression, + // sampler, + // coordinate: fc.args[1].expression, + // array_index: None, //TODO + // offset: None, //TODO + // level: SampleLevel::Exact(fc.args[2].expression), + // depth_ref: None, + // }, + // ), + // sampler: None, + // statements: fc + // .args + // .into_iter() + // .map(|a| a.statements) + // .flatten() + // .collect(), + // }) + // } else { + // Err(ErrorKind::SemanticError("Bad call to textureLod".into())) + // } + // } + // "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" + // | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" + // | "normalize" => { + // if fc.args.len() != 1 { + // return Err(ErrorKind::WrongNumberArgs(name, 1, fc.args.len())); + // } + // Ok(ExpressionRule { + // expression: context.function.expressions.append(Expression::Math { + // fun: match name.as_str() { + // "ceil" => MathFunction::Ceil, + // "round" => MathFunction::Round, + // "floor" => MathFunction::Floor, + // "fract" => MathFunction::Fract, + // "trunc" => MathFunction::Trunc, + // "sin" => MathFunction::Sin, + // "abs" => MathFunction::Abs, + // "sqrt" => MathFunction::Sqrt, + // "inversesqrt" => MathFunction::InverseSqrt, + // "exp" => MathFunction::Exp, + // "exp2" => MathFunction::Exp2, + // "sign" => MathFunction::Sign, + // "transpose" => MathFunction::Transpose, + // "inverse" => MathFunction::Inverse, + // "normalize" => MathFunction::Normalize, + // _ => unreachable!(), + // }, + // arg: fc.args[0].expression, + // arg1: None, + // arg2: None, + // }), + // sampler: None, + // statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), + // }) + // } + // "pow" | "dot" | "max" => { + // if fc.args.len() != 2 { + // return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); + // } + // Ok(ExpressionRule { + // expression: context.function.expressions.append(Expression::Math { + // fun: match name.as_str() { + // "pow" => MathFunction::Pow, + // "dot" => MathFunction::Dot, + // "max" => MathFunction::Max, + // _ => unreachable!(), + // }, + // arg: fc.args[0].expression, + // arg1: Some(fc.args[1].expression), + // arg2: None, + // }), + // sampler: None, + // statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), + // }) + // } + // "mix" | "clamp" => { + // if fc.args.len() != 3 { + // return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); + // } + // Ok(ExpressionRule { + // expression: context.function.expressions.append(Expression::Math { + // fun: match name.as_str() { + // "mix" => MathFunction::Mix, + // "clamp" => MathFunction::Clamp, + // _ => unreachable!(), + // }, + // arg: fc.args[0].expression, + // arg1: Some(fc.args[1].expression), + // arg2: Some(fc.args[2].expression), + // }), + // sampler: None, + // statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), + // }) + // } + // "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" + // | "notEqual" => { + // if fc.args.len() != 2 { + // return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); + // } + // Ok(ExpressionRule { + // expression: context.function.expressions.append(Expression::Binary { + // op: match name.as_str() { + // "lessThan" => BinaryOperator::Less, + // "greaterThan" => BinaryOperator::Greater, + // "lessThanEqual" => BinaryOperator::LessEqual, + // "greaterThanEqual" => BinaryOperator::GreaterEqual, + // "equal" => BinaryOperator::Equal, + // "notEqual" => BinaryOperator::NotEqual, + // _ => unreachable!(), + // }, + // left: fc.args[0].expression, + // right: fc.args[1].expression, + // }), + // sampler: None, + // statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), + // }) + // } + // "isinf" => { + // self.parse_relational_fun(context, name, fc.args, RelationalFunction::IsInf) + // } + // "isnan" => { + // self.parse_relational_fun(context, name, fc.args, RelationalFunction::IsNan) + // } + // "all" => { + // self.parse_relational_fun(context, name, fc.args, RelationalFunction::All) + // } + // "any" => { + // self.parse_relational_fun(context, name, fc.args, RelationalFunction::Any) + // } + // func_name => { + // let function = *self.lookup_function.get(func_name).ok_or_else(|| { + // ErrorKind::SemanticError( + // format!("Unknown function: {}", func_name).into(), + // ) + // })?; + // let arguments: Vec<_> = fc.args.iter().map(|a| a.expression).collect(); + // let mut statements: Vec<_> = + // fc.args.into_iter().flat_map(|a| a.statements).collect(); + // let expression = context + // .function + // .expressions + // .append(Expression::Call(function)); + // statements.push(crate::Statement::Call { + // function, + // arguments, + // result: Some(expression), + // }); + // Ok(ExpressionRule { + // expression, + // sampler: None, + // statements, + // }) + // } + // } + // } + // } + // } pub fn parse_relational_fun( &mut self, @@ -314,47 +314,70 @@ impl Program<'_> { }) } - pub fn add_function_prelude(&mut self, context: &mut FunctionContext) { - for (var_handle, var) in self.module.global_variables.iter() { - if let Some(name) = var.name.as_ref() { - let expr = context - .function - .expressions - .append(Expression::GlobalVariable(var_handle)); - context.lookup_global_var_exps.insert(name.clone(), expr); - } else { - let ty = &self.module.types[var.ty]; - // anonymous structs - if let TypeInner::Struct { ref members, .. } = ty.inner { - let base = context - .function - .expressions - .append(Expression::GlobalVariable(var_handle)); - for (idx, member) in members.iter().enumerate() { - if let Some(name) = member.name.as_ref() { - let exp = - context - .function - .expressions - .append(Expression::AccessIndex { - base, - index: idx as u32, - }); - context.lookup_global_var_exps.insert(name.clone(), exp); - } - } - } - } - } + // TODO: Reenable later + // pub fn add_function_prelude(&mut self, context: &mut FunctionContext) { + // for (var_handle, var) in self.module.global_variables.iter() { + // if let Some(name) = var.name.as_ref() { + // let expr = context + // .function + // .expressions + // .append(Expression::GlobalVariable(var_handle)); + // context.lookup_global_var_exps.insert(name.clone(), expr); + // } else { + // let ty = &self.module.types[var.ty]; + // // anonymous structs + // if let TypeInner::Struct { ref members, .. } = ty.inner { + // let base = context + // .function + // .expressions + // .append(Expression::GlobalVariable(var_handle)); + // for (idx, member) in members.iter().enumerate() { + // if let Some(name) = member.name.as_ref() { + // let exp = + // context + // .function + // .expressions + // .append(Expression::AccessIndex { + // base, + // index: idx as u32, + // }); + // context.lookup_global_var_exps.insert(name.clone(), exp); + // } + // } + // } + // } + // } - for (handle, constant) in self.module.constants.iter() { - if let Some(name) = constant.name.as_ref() { - let expr = context - .function - .expressions - .append(Expression::Constant(handle)); - context.lookup_constant_exps.insert(name.clone(), expr); - } + // for (handle, constant) in self.module.constants.iter() { + // if let Some(name) = constant.name.as_ref() { + // let expr = context + // .function + // .expressions + // .append(Expression::Constant(handle)); + // context.lookup_constant_exps.insert(name.clone(), expr); + // } + // } + // } + + pub fn add_function(&mut self, mut function: Function) -> Result<(), ErrorKind> { + ensure_block_returns(&mut function.body); + let name = function + .name + .clone() + .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; + let stage = self.entry_points.get(&name); + if let Some(&stage) = stage { + self.module.entry_points.push(EntryPoint { + name, + stage, + early_depth_test: None, + workgroup_size: [0; 3], //TODO + function, + }); + } else { + let handle = self.module.functions.append(function); + self.lookup_function.insert(name, handle); } + Ok(()) } } diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 84e73df48..a07cc4af2 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -62,7 +62,7 @@ impl<'a> Iterator for Lexer<'a> { } TokenValue::Extension } - PPTokenValue::Float(float) => TokenValue::FloatConstant(float.value), + PPTokenValue::Float(float) => TokenValue::FloatConstant(float), PPTokenValue::Ident(ident) => { match ident.as_str() { "layout" => TokenValue::Layout, @@ -103,8 +103,7 @@ impl<'a> Iterator for Lexer<'a> { }, } } - //TODO: unsigned etc - PPTokenValue::Integer(integer) => TokenValue::IntConstant(integer.value as i64), + PPTokenValue::Integer(integer) => TokenValue::IntConstant(integer), PPTokenValue::Punct(punct) => match punct { // Compound assignments Punct::AddAssign => TokenValue::AddAssign, @@ -179,6 +178,8 @@ impl<'a> Iterator for Lexer<'a> { #[cfg(test)] mod tests { + use pp_rs::token::Integer; + use super::{ super::token::{Token, TokenMetadata, TokenValue}, Lexer, @@ -203,7 +204,11 @@ mod tests { assert_eq!( lex.next().unwrap(), Token { - value: TokenValue::IntConstant(450), + value: TokenValue::IntConstant(Integer { + signed: true, + value: 450, + width: 32 + }), meta: TokenMetadata { line: 1, chars: 9..10 //TODO diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 7a17300cf..17b8a5784 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -14,7 +14,7 @@ mod error; pub use error::ParseError; mod constants; // TODO: Remove later -#[allow(dead_code)] +#[allow(dead_code, unused_imports)] mod functions; mod parser; #[cfg(test)] diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2e587fe55..0cc769ccd 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,16 +1,19 @@ use super::{ - ast::{FunctionContext, Profile, StorageQualifier, StructLayout, TypeQualifier}, + ast::{ + Expr, ExprKind, FunctionContext, Profile, StorageQualifier, StructLayout, TypeQualifier, + }, error::ErrorKind, lex::Lexer, token::{Token, TokenMetadata, TokenValue}, Program, }; use crate::{ - arena::Handle, ArraySize, Binding, Function, FunctionResult, ResourceBinding, StorageClass, - Type, TypeInner, + arena::Handle, ArraySize, BinaryOperator, Binding, Constant, ConstantInner, Function, + FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, Type, TypeInner, + UnaryOperator, }; use core::convert::TryFrom; -use core::iter::Peekable; +use std::iter::Peekable; type Result = std::result::Result; @@ -78,9 +81,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let version = self.bump()?; match version.value { - TokenValue::IntConstant(i) => match i { - 440 | 450 | 460 => self.program.version = i as u16, - _ => return Err(ErrorKind::InvalidVersion(version.meta, i)), + TokenValue::IntConstant(i) => match i.value { + 440 | 450 | 460 => self.program.version = i.value as u16, + _ => return Err(ErrorKind::InvalidVersion(version.meta, i.value)), }, _ => return Err(ErrorKind::InvalidToken(version)), } @@ -288,7 +291,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_constant_expression(&mut self) -> Result { let token = self.bump()?; match token.value { - TokenValue::IntConstant(value) => Ok(value), + TokenValue::IntConstant(int) => Ok(int.value as i64), _ => Err(ErrorKind::InvalidToken(token)), } } @@ -355,11 +358,11 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let token = self.bump()?; match token.value { - // Function prototypes + // TODO: Function prototypes TokenValue::Semicolon => todo!(), TokenValue::LeftBrace if external => { - // TODO: body - self.expect(TokenValue::RightBrace)?; + self.parse_compound_statement(&mut context)?; + self.program.add_function(function)?; Ok(true) } @@ -392,6 +395,288 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } + fn parse_primary(&mut self, ctx: &mut FunctionContext) -> Result { + let token = self.bump()?; + + let (width, value) = match token.value { + TokenValue::IntConstant(int) => ( + (int.width / 8) as u8, + if int.signed { + ScalarValue::Sint(int.value as i64) + } else { + ScalarValue::Uint(int.value) + }, + ), + TokenValue::FloatConstant(float) => ( + (float.width / 8) as u8, + ScalarValue::Float(float.value as f64), + ), + TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)), + TokenValue::LeftParen => { + let expr = self.parse_expression(ctx)?; + self.expect(TokenValue::RightParen)?; + + return Ok(expr); + } + _ => return Err(ErrorKind::InvalidToken(token)), + }; + + let handle = self.program.module.constants.append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { width, value }, + }); + + Ok(Expr { + kind: ExprKind::Constant(handle), + meta: token.meta, + }) + } + + fn parse_postfix(&mut self, ctx: &mut FunctionContext) -> Result { + let mut expr = match self.expect_peek()?.value { + TokenValue::Identifier(_) => { + let (name, meta) = self.expect_ident()?; + + // TODO: function calls + // let mut args = Vec::new(); + // while TokenValue::RightBracket != self.bump()?.value { + // args.push(self.parse_expression(ctx)?) + // } + + let var = match self.program.lookup_variable(ctx, &name)? { + Some(var) => var, + None => return Err(ErrorKind::UnknownVariable(meta, name)), + }; + + Expr { + kind: ExprKind::Variable(var), + meta, + } + } + _ => self.parse_primary(ctx)?, + }; + + // TODO: postfix inc/dec + while let TokenValue::LeftBracket | TokenValue::Dot = self.expect_peek()?.value { + let Token { value, meta } = self.bump()?; + + match value { + TokenValue::LeftBracket => { + let index = Box::new(self.parse_expression(ctx)?); + self.expect(TokenValue::RightBracket)?; + + // TODO: metadata unification + expr = Expr { + kind: ExprKind::Access { + base: Box::new(expr), + index, + }, + meta, + } + } + TokenValue::Dot => { + let field = self.expect_ident()?.0; + + // TODO: metadata unification + expr = Expr { + kind: ExprKind::Select { + base: Box::new(expr), + field, + }, + meta, + } + } + _ => unreachable!(), + } + } + + Ok(expr) + } + + fn parse_unary(&mut self, ctx: &mut FunctionContext) -> Result { + // TODO: prefix inc/dec + match self.expect_peek()?.value { + TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { + let Token { value, meta } = self.bump()?; + + let expr = self.parse_unary(ctx)?; + + let kind = match value { + TokenValue::Dash => ExprKind::Unary { + op: UnaryOperator::Negate, + expr: Box::new(expr), + }, + TokenValue::Bang | TokenValue::Tilde => ExprKind::Unary { + op: UnaryOperator::Not, + expr: Box::new(expr), + }, + _ => return Ok(expr), + }; + + // TODO: metadata unification + Ok(Expr { kind, meta }) + } + _ => self.parse_postfix(ctx), + } + } + + fn parse_binary( + &mut self, + ctx: &mut FunctionContext, + passtrough: Option, + min_bp: u8, + ) -> Result { + let mut expr = passtrough + .ok_or(ErrorKind::EndOfFile /* Dummy error */) + .or_else(|_| self.parse_unary(ctx))?; + + while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek()?.value) { + if l_bp < min_bp { + break; + } + + let Token { value, meta } = self.bump()?; + + let right = Box::new(self.parse_binary(ctx, None, r_bp)?); + + expr = Expr { + kind: ExprKind::Binary { + left: Box::new(expr), + op: match value { + TokenValue::LogicalOr => BinaryOperator::LogicalOr, + TokenValue::LogicalXor => BinaryOperator::NotEqual, + TokenValue::LogicalAnd => BinaryOperator::LogicalAnd, + TokenValue::VerticalBar => BinaryOperator::InclusiveOr, + TokenValue::Caret => BinaryOperator::ExclusiveOr, + TokenValue::Ampersand => BinaryOperator::And, + TokenValue::Equal => BinaryOperator::Equal, + TokenValue::NotEqual => BinaryOperator::NotEqual, + TokenValue::GreaterEqual => BinaryOperator::GreaterEqual, + TokenValue::LessEqual => BinaryOperator::LessEqual, + TokenValue::LeftAngle => BinaryOperator::Greater, + TokenValue::RightAngle => BinaryOperator::Less, + TokenValue::LeftShift => BinaryOperator::ShiftLeft, + TokenValue::RightShift => BinaryOperator::ShiftRight, + TokenValue::Plus => BinaryOperator::Add, + TokenValue::Dash => BinaryOperator::Subtract, + TokenValue::Star => BinaryOperator::Multiply, + TokenValue::Slash => BinaryOperator::Divide, + TokenValue::Percent => BinaryOperator::Modulo, + _ => unreachable!(), + }, + right, + }, + meta, + } + } + + Ok(expr) + } + + fn parse_conditional( + &mut self, + ctx: &mut FunctionContext, + passtrough: Option, + ) -> Result { + let mut condition = self.parse_binary(ctx, passtrough, 0)?; + + if let TokenValue::Question = self.expect_peek()?.value { + let meta = self.bump()?.meta; + + let accept = Box::new(self.parse_expression(ctx)?); + self.expect(TokenValue::Colon)?; + let reject = Box::new(self.parse_assignment(ctx)?); + + condition = Expr { + kind: ExprKind::Conditional { + condition: Box::new(condition), + accept, + reject, + }, + meta, + }; + } + + Ok(condition) + } + + fn parse_assignment(&mut self, ctx: &mut FunctionContext) -> Result { + let pointer = self.parse_unary(ctx)?; + + if let TokenValue::Assign = self.expect_peek()?.value { + let meta = self.bump()?.meta; + + let value = Box::new(self.parse_assignment(ctx)?); + + Ok(Expr { + kind: ExprKind::Assign { + tgt: Box::new(pointer), + value, + }, + meta, + }) + } else { + self.parse_conditional(ctx, Some(pointer)) + } + } + + fn parse_expression(&mut self, ctx: &mut FunctionContext) -> Result { + let mut expr = self.parse_assignment(ctx)?; + + while let TokenValue::Comma = self.expect_peek()?.value { + self.bump()?; + expr = self.parse_assignment(ctx)?; + } + + Ok(expr) + } + + fn parse_compound_statement(&mut self, ctx: &mut FunctionContext) -> Result<()> { + loop { + let token = self.bump()?; + + match token.value { + TokenValue::Continue => { + ctx.function.body.push(Statement::Continue); + self.expect(TokenValue::Semicolon)?; + } + TokenValue::Break => { + ctx.function.body.push(Statement::Break); + self.expect(TokenValue::Semicolon)?; + } + TokenValue::Return => { + let value = match self.expect_peek()?.value { + TokenValue::Semicolon => { + self.bump()?; + None + } + _ => { + let expr = self.parse_expression(ctx)?; + self.expect(TokenValue::Semicolon)?; + Some(ctx.resolve(self.program, expr, false)?) + } + }; + + ctx.function.body.push(Statement::Return { value }) + } + TokenValue::Discard => { + ctx.function.body.push(Statement::Kill); + self.expect(TokenValue::Semicolon)?; + } + TokenValue::LeftBrace => { + ctx.push_scope(); + self.parse_compound_statement(ctx)?; + ctx.remove_current_scope(); + } + TokenValue::RightBrace => break, + _ => {} + } + } + + Ok(()) + } + fn parse_function_args(&mut self, context: &mut FunctionContext) -> Result<()> { loop { // TODO: parameter qualifier @@ -428,3 +713,23 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(()) } } + +fn binding_power(value: &TokenValue) -> Option<(u8, u8)> { + Some(match *value { + TokenValue::LogicalOr => (1, 2), + TokenValue::LogicalXor => (3, 4), + TokenValue::LogicalAnd => (5, 6), + TokenValue::VerticalBar => (7, 8), + TokenValue::Caret => (9, 10), + TokenValue::Ampersand => (11, 12), + TokenValue::Equal | TokenValue::NotEqual => (13, 14), + TokenValue::GreaterEqual + | TokenValue::LessEqual + | TokenValue::LeftAngle + | TokenValue::RightAngle => (15, 16), + TokenValue::LeftShift | TokenValue::RightShift => (17, 18), + TokenValue::Plus | TokenValue::Dash => (19, 20), + TokenValue::Star | TokenValue::Slash | TokenValue::Percent => (21, 22), + _ => return None, + }) +} diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 42ee511a6..b02324c04 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -256,27 +256,27 @@ fn functions() { ) .unwrap(); - // parse_program( - // r#" - // # version 450 - // float test(float a) { return a; } + parse_program( + r#" + # version 450 + float test(float a) { return a; } - // void main() {} - // "#, - // &entry_points, - // ) - // .unwrap(); + void main() {} + "#, + &entry_points, + ) + .unwrap(); - // parse_program( - // r#" - // # version 450 - // float test(vec4 p) { - // return p.x; - // } - // "#, - // &entry_points, - // ) - // .unwrap(); + parse_program( + r#" + # version 450 + float test(vec4 p) { + return p.x; + } + "#, + &entry_points, + ) + .unwrap(); } #[test] diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index bc53d61f3..e17ba7d5c 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -1,5 +1,6 @@ +pub use pp_rs::token::{Float, Integer, PreprocessorError}; + use crate::{Interpolation, Sampling, Type}; -use pp_rs::token::PreprocessorError; use std::ops::Range; #[derive(Debug, Clone)] @@ -25,8 +26,8 @@ pub enum TokenValue { Version, Pragma, - FloatConstant(f32), - IntConstant(i64), + FloatConstant(Float), + IntConstant(Integer), BoolConstant(bool), Layout, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index db4755906..b7d32f4de 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -9,118 +9,25 @@ impl Program<'_> { &mut self, context: &mut FunctionContext, name: &str, - ) -> Result>, ErrorKind> { + ) -> Result, ErrorKind> { if let Some(local_var) = context.lookup_local_var(name) { return Ok(Some(local_var)); } if let Some(global_var) = context.lookup_global_var_exps.get(name) { - return Ok(Some(*global_var)); + return Ok(Some(global_var.clone())); } if let Some(constant) = context.lookup_constant_exps.get(name) { - return Ok(Some(*constant)); + return Ok(Some(constant.clone())); } match name { "gl_Position" => { - /*let h = self.module.global_variables.append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Output, - binding: Some(Binding::BuiltIn(BuiltIn::Position)), - ty: self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, - }, - }), - init: None, - interpolation: None, - storage_access: StorageAccess::empty(), - }); - self.lookup_global_variables.insert(name.into(), h); - let exp = self - .context - .expressions - .append(Expression::GlobalVariable(h));*/ - let exp = context - .function - .expressions - .append(Expression::FunctionArgument(0)); //TODO - context.lookup_global_var_exps.insert(name.into(), exp); - - Ok(Some(exp)) + todo!() } "gl_VertexIndex" => { - /* TODO - let h = self.module.global_variables.append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::VertexIndex)), - ty: self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - }), - init: None, - interpolation: None, - storage_access: StorageAccess::empty(), - }); - self.lookup_global_variables.insert(name.into(), h); - let mut expr = self - .context - .expressions - .append(Expression::GlobalVariable(h)); - expr = self.context.expressions.append(Expression::As { - expr, - kind: ScalarKind::Sint, - convert: true, - }); - */ - let expr = context - .function - .expressions - .append(Expression::FunctionArgument(0)); //TODO - context.lookup_global_var_exps.insert(name.into(), expr); - - Ok(Some(expr)) + todo!() } "gl_InstanceIndex" => { - /* TODO - let h = self.module.global_variables.append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Input, - binding: Some(Binding::BuiltIn(BuiltIn::InstanceIndex)), - ty: self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - }), - init: None, - interpolation: None, - storage_access: StorageAccess::empty(), - }); - self.lookup_global_variables.insert(name.into(), h); - let mut expr = self - .context - .expressions - .append(Expression::GlobalVariable(h)); - expr = self.context.expressions.append(Expression::As { - expr, - kind: ScalarKind::Sint, - convert: true, - }); - */ - let expr = context - .function - .expressions - .append(Expression::FunctionArgument(0)); //TODO - context.lookup_global_var_exps.insert(name.into(), expr); - - Ok(Some(expr)) + todo!() } _ => Ok(None), } From 8519095f554bb18d035d62191d4def05398e8fc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 7 May 2021 21:00:16 +0100 Subject: [PATCH 0845/2212] [glsl-in] Handle global declarations parse constant expressions fully --- src/front/glsl/ast.rs | 213 +++++++++++++++++++----------- src/front/glsl/functions.rs | 180 +++++++++++++++---------- src/front/glsl/mod.rs | 4 +- src/front/glsl/parser.rs | 75 +++++++---- src/front/glsl/variables.rs | 257 ++++++++++++++++++++++++++++++++++-- 5 files changed, 543 insertions(+), 186 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 08c265d31..bfd49d6bc 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,113 +1,80 @@ use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind, TokenMetadata}; use crate::{ - proc::ResolveContext, Arena, ArraySize, BinaryOperator, Binding, Constant, Expression, + proc::ResolveContext, Arena, ArraySize, BinaryOperator, BuiltIn, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, Module, RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, - UnaryOperator, + TypeInner, UnaryOperator, }; +#[derive(Debug)] +pub enum GlobalLookup { + Variable(Handle), + Select(u32), +} + #[derive(Debug)] pub struct Program<'a> { pub version: u16, pub profile: Profile, pub entry_points: &'a FastHashMap, + pub lookup_function: FastHashMap>, pub lookup_type: FastHashMap>, - pub lookup_global_variables: FastHashMap>, + pub lookup_global_variables: FastHashMap, pub lookup_constants: FastHashMap>, + + pub built_ins: Vec<(BuiltIn, Handle)>, + pub entries: Vec<(String, ShaderStage, Handle)>, + + pub input_struct: Handle, + pub output_struct: Handle, + pub module: Module, } impl<'a> Program<'a> { pub fn new(entry_points: &'a FastHashMap) -> Program<'a> { + let mut module = Module::default(); + Program { version: 0, profile: Profile::Core, entry_points, + lookup_function: FastHashMap::default(), lookup_type: FastHashMap::default(), lookup_global_variables: FastHashMap::default(), lookup_constants: FastHashMap::default(), - module: Module::default(), - } - } - pub fn binary_expr( - &mut self, - function: &mut Function, - op: BinaryOperator, - left: &ExpressionRule, - right: &ExpressionRule, - ) -> ExpressionRule { - ExpressionRule::from_expression(function.expressions.append(Expression::Binary { - op, - left: left.expression, - right: right.expression, - })) - } + built_ins: Vec::new(), + entries: Vec::new(), - pub fn unary_expr( - &mut self, - function: &mut Function, - op: UnaryOperator, - tgt: &ExpressionRule, - ) -> ExpressionRule { - ExpressionRule::from_expression(function.expressions.append(Expression::Unary { - op, - expr: tgt.expression, - })) - } - - /// Helper function to insert equality expressions, this handles the special - /// case of `vec1 == vec2` and `vec1 != vec2` since in the IR they are - /// represented as `all(equal(vec1, vec2))` and `any(notEqual(vec1, vec2))` - pub fn equality_expr( - &mut self, - context: &mut FunctionContext, - equals: bool, - left: &ExpressionRule, - right: &ExpressionRule, - ) -> Result { - let left_is_vector = match *self.resolve_type(context, left.expression)? { - crate::TypeInner::Vector { .. } => true, - _ => false, - }; - - let right_is_vector = match *self.resolve_type(context, right.expression)? { - crate::TypeInner::Vector { .. } => true, - _ => false, - }; - - let (op, fun) = match equals { - true => (BinaryOperator::Equal, RelationalFunction::All), - false => (BinaryOperator::NotEqual, RelationalFunction::Any), - }; - - let expr = ExpressionRule::from_expression(context.function.expressions.append( - Expression::Binary { - op, - left: left.expression, - right: right.expression, - }, - )); - - Ok(if left_is_vector && right_is_vector { - ExpressionRule::from_expression(context.function.expressions.append( - Expression::Relational { - fun, - argument: expr.expression, + input_struct: module.types.append(Type { + name: None, + inner: TypeInner::Struct { + level: crate::StructLevel::Root, + members: Vec::new(), + span: 0, }, - )) - } else { - expr - }) + }), + output_struct: module.types.append(Type { + name: None, + inner: TypeInner::Struct { + level: crate::StructLevel::Root, + members: Vec::new(), + span: 0, + }, + }), + + module, + } } pub fn resolve_type<'b>( &'b mut self, context: &'b mut FunctionContext, handle: Handle, - ) -> Result<&'b crate::TypeInner, ErrorKind> { + ) -> Result<&'b TypeInner, ErrorKind> { let resolve_ctx = ResolveContext { constants: &self.module.constants, global_vars: &self.module.global_variables, @@ -226,6 +193,61 @@ impl<'function> FunctionContext<'function> { None } + pub fn lookup_global_var( + &mut self, + program: &mut Program, + name: &str, + ) -> Option { + self.lookup_global_var_exps.get(name).cloned().or_else(|| { + let expr = match *program.lookup_global_variables.get(name)? { + GlobalLookup::Variable(v) => Expression::GlobalVariable(v), + GlobalLookup::Select(index) => { + let base = self + .function + .expressions + .append(Expression::FunctionArgument( + self.function.arguments.len() as u32 - 1, + )); + + Expression::AccessIndex { base, index } + } + }; + + let expr = self.function.expressions.append(expr); + let var = VariableReference { + expr, + load: Some( + self.function + .expressions + .append(Expression::Load { pointer: expr }), + ), + }; + + self.lookup_global_var_exps.insert(name.into(), var.clone()); + + Some(var) + }) + } + + pub fn lookup_constants_var( + &mut self, + program: &mut Program, + name: &str, + ) -> Option { + self.lookup_constant_exps.get(name).cloned().or_else(|| { + let expr = self + .function + .expressions + .append(Expression::Constant(*program.lookup_constants.get(name)?)); + + let var = VariableReference { expr, load: None }; + + self.lookup_constant_exps.insert(name.into(), var.clone()); + + Some(var) + }) + } + #[cfg(feature = "glsl-validate")] pub fn lookup_local_var_current_scope(&self, name: &str) -> Option { if let Some(current) = self.scopes.last() { @@ -316,9 +338,41 @@ impl<'function> FunctionContext<'function> { let left = self.resolve(program, *left, false)?; let right = self.resolve(program, *right, false)?; - self.function - .expressions - .append(Expression::Binary { left, op, right }) + if let BinaryOperator::Equal | BinaryOperator::NotEqual = op { + let equals = op == BinaryOperator::Equal; + let left_is_vector = match *program.resolve_type(self, left)? { + crate::TypeInner::Vector { .. } => true, + _ => false, + }; + + let right_is_vector = match *program.resolve_type(self, right)? { + crate::TypeInner::Vector { .. } => true, + _ => false, + }; + + let (op, fun) = match equals { + true => (BinaryOperator::Equal, RelationalFunction::All), + false => (BinaryOperator::NotEqual, RelationalFunction::Any), + }; + + let expr = + self.function + .expressions + .append(Expression::Binary { op, left, right }); + + if left_is_vector && right_is_vector { + self.function.expressions.append(Expression::Relational { + fun, + argument: expr, + }) + } else { + expr + } + } else { + self.function + .expressions + .append(Expression::Binary { left, op, right }) + } } ExprKind::Unary { op, expr } => { let expr = self.resolve(program, *expr, false)?; @@ -429,7 +483,7 @@ pub enum TypeQualifier { StorageQualifier(StorageQualifier), Interpolation(Interpolation), ResourceBinding(ResourceBinding), - Binding(Binding), + Location(u32), Sampling(Sampling), Layout(StructLayout), EarlyFragmentTests, @@ -454,12 +508,11 @@ pub struct FunctionCall { pub args: Vec, } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq)] pub enum StorageQualifier { StorageClass(StorageClass), Input, Output, - InOut, Const, } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index bc0cc3367..8b22ad7ab 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,6 +1,7 @@ use crate::{ - proc::ensure_block_returns, BinaryOperator, EntryPoint, Expression, Function, MathFunction, - RelationalFunction, SampleLevel, TypeInner, + proc::ensure_block_returns, Arena, BinaryOperator, Binding, BuiltIn, EntryPoint, Expression, + Function, FunctionArgument, FunctionResult, MathFunction, RelationalFunction, SampleLevel, + ShaderStage, Statement, TypeInner, }; use super::{ast::*, error::ErrorKind}; @@ -294,69 +295,25 @@ impl Program<'_> { // } // } - pub fn parse_relational_fun( - &mut self, - context: &mut FunctionContext, - name: String, - args: Vec, - fun: RelationalFunction, - ) -> Result { - if args.len() != 1 { - return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); - } - Ok(ExpressionRule { - expression: context.function.expressions.append(Expression::Relational { - fun, - argument: args[0].expression, - }), - sampler: None, - statements: args.into_iter().flat_map(|a| a.statements).collect(), - }) - } - // TODO: Reenable later - // pub fn add_function_prelude(&mut self, context: &mut FunctionContext) { - // for (var_handle, var) in self.module.global_variables.iter() { - // if let Some(name) = var.name.as_ref() { - // let expr = context - // .function - // .expressions - // .append(Expression::GlobalVariable(var_handle)); - // context.lookup_global_var_exps.insert(name.clone(), expr); - // } else { - // let ty = &self.module.types[var.ty]; - // // anonymous structs - // if let TypeInner::Struct { ref members, .. } = ty.inner { - // let base = context - // .function - // .expressions - // .append(Expression::GlobalVariable(var_handle)); - // for (idx, member) in members.iter().enumerate() { - // if let Some(name) = member.name.as_ref() { - // let exp = - // context - // .function - // .expressions - // .append(Expression::AccessIndex { - // base, - // index: idx as u32, - // }); - // context.lookup_global_var_exps.insert(name.clone(), exp); - // } - // } - // } - // } - // } - - // for (handle, constant) in self.module.constants.iter() { - // if let Some(name) = constant.name.as_ref() { - // let expr = context - // .function - // .expressions - // .append(Expression::Constant(handle)); - // context.lookup_constant_exps.insert(name.clone(), expr); - // } + // pub fn parse_relational_fun( + // &mut self, + // context: &mut FunctionContext, + // name: String, + // args: Vec, + // fun: RelationalFunction, + // ) -> Result { + // if args.len() != 1 { + // return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); // } + // Ok(ExpressionRule { + // expression: context.function.expressions.append(Expression::Relational { + // fun, + // argument: args[0].expression, + // }), + // sampler: None, + // statements: args.into_iter().flat_map(|a| a.statements).collect(), + // }) // } pub fn add_function(&mut self, mut function: Function) -> Result<(), ErrorKind> { @@ -366,18 +323,103 @@ impl Program<'_> { .clone() .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; let stage = self.entry_points.get(&name); + + // Add the input variables as a function argument + function.arguments.push(FunctionArgument { + name: None, + ty: self.input_struct, + binding: None, + }); + + let handle = self.module.functions.append(function); + if let Some(&stage) = stage { + self.entries.push((name, stage, handle)); + } else { + self.lookup_function.insert(name, handle); + } + + Ok(()) + } + + pub fn add_entry_points(&mut self) { + for (name, stage, function) in self.entries.iter().cloned() { + let mut arguments = Vec::new(); + let mut expressions = Arena::new(); + let mut body = Vec::new(); + + for (built_in, handle) in self.built_ins.iter().copied() { + let ty = self.module.global_variables[handle].ty; + let arg = arguments.len() as u32; + + arguments.push(FunctionArgument { + name: None, + ty, + binding: Some(Binding::BuiltIn(built_in)), + }); + + let pointer = expressions.append(Expression::GlobalVariable(handle)); + let value = expressions.append(Expression::FunctionArgument(arg)); + + body.push(Statement::Store { pointer, value }); + } + + let i = arguments.len() as u32; + arguments.push(FunctionArgument { + name: None, + ty: self.input_struct, + binding: None, + }); + + let res = expressions.append(Expression::Call(function)); + + body.push(Statement::Call { + function, + arguments: vec![expressions.append(Expression::FunctionArgument(i))], + result: Some(res), + }); + + for (i, (built_in, handle)) in self.built_ins.iter().copied().enumerate() { + if !should_write(built_in, stage) { + continue; + } + + let value = expressions.append(Expression::GlobalVariable(handle)); + let pointer = expressions.append(Expression::FunctionArgument(i as u32)); + + body.push(Statement::Store { pointer, value }); + } + + body.push(Statement::Return { value: Some(res) }); + self.module.entry_points.push(EntryPoint { name, stage, + // TODO early_depth_test: None, - workgroup_size: [0; 3], //TODO - function, + workgroup_size: [0; 3], + function: Function { + arguments, + expressions, + body, + result: Some(FunctionResult { + ty: self.output_struct, + binding: None, + }), + ..Default::default() + }, }); - } else { - let handle = self.module.functions.append(function); - self.lookup_function.insert(name, handle); } - Ok(()) + } +} + +fn should_write(built_in: BuiltIn, stage: ShaderStage) -> bool { + match (built_in, stage) { + (BuiltIn::Position, ShaderStage::Vertex) + | (BuiltIn::ClipDistance, ShaderStage::Vertex) + | (BuiltIn::PointSize, ShaderStage::Vertex) + | (BuiltIn::FragDepth, ShaderStage::Fragment) + | (BuiltIn::SampleMask, ShaderStage::Fragment) => true, + _ => false, } } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 17b8a5784..590ddd717 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -14,15 +14,13 @@ mod error; pub use error::ParseError; mod constants; // TODO: Remove later -#[allow(dead_code, unused_imports)] +#[allow(unused_imports)] mod functions; mod parser; #[cfg(test)] mod parser_tests; mod token; mod types; -// TODO: Remove later -#[allow(dead_code)] mod variables; pub struct Options { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0cc769ccd..8d6a6f4e1 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -8,9 +8,8 @@ use super::{ Program, }; use crate::{ - arena::Handle, ArraySize, BinaryOperator, Binding, Constant, ConstantInner, Function, - FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, Type, TypeInner, - UnaryOperator, + arena::Handle, ArraySize, BinaryOperator, Constant, ConstantInner, Function, FunctionResult, + ResourceBinding, ScalarValue, Statement, StorageClass, Type, TypeInner, UnaryOperator, }; use core::convert::TryFrom; use std::iter::Peekable; @@ -73,6 +72,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.parse_external_declaration()?; } + self.program.add_entry_points(); + Ok(()) } @@ -161,7 +162,6 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { | TokenValue::Const | TokenValue::In | TokenValue::Out - | TokenValue::InOut | TokenValue::Uniform | TokenValue::Layout => true, _ => false, @@ -185,7 +185,6 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Const => TypeQualifier::StorageQualifier(StorageQualifier::Const), TokenValue::In => TypeQualifier::StorageQualifier(StorageQualifier::Input), TokenValue::Out => TypeQualifier::StorageQualifier(StorageQualifier::Output), - TokenValue::InOut => TypeQualifier::StorageQualifier(StorageQualifier::InOut), TokenValue::Uniform => TypeQualifier::StorageQualifier( StorageQualifier::StorageClass(StorageClass::Uniform), ), @@ -242,6 +241,25 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(()) } + fn parse_uint_constant(&mut self) -> Result { + let value = self.parse_constant_expression()?; + + // TODO: better errors + match self.program.module.constants[value].inner { + ConstantInner::Scalar { + value: ScalarValue::Uint(int), + .. + } => u32::try_from(int) + .map_err(|_| ErrorKind::SemanticError("int constant overflows".into())), + ConstantInner::Scalar { + value: ScalarValue::Sint(int), + .. + } => u32::try_from(int) + .map_err(|_| ErrorKind::SemanticError("int constant overflows".into())), + _ => Err(ErrorKind::SemanticError("Expected a uint constant".into())), + } + } + fn parse_layout_qualifier_id( &mut self, qualifiers: &mut Vec, @@ -256,18 +274,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match token.value { TokenValue::Identifier(name) => { if self.bump_if(TokenValue::Assign).is_some() { - let value = self.parse_constant_expression()?; + let value = self.parse_uint_constant()?; match name.as_str() { - "location" => qualifiers.push(TypeQualifier::Binding(Binding::Location { - // TODO: use better error here - location: u32::try_from(value).map_err(|_| ErrorKind::InvalidInput)?, - interpolation: None, - sampling: None, - })), - // TODO: produce error when try_from fails - "set" => *group = u32::try_from(value).ok(), - "binding" => *binding = u32::try_from(value).ok(), + "location" => qualifiers.push(TypeQualifier::Location(value)), + "set" => *group = Some(value), + "binding" => *binding = Some(value), _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), } } else { @@ -287,13 +299,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } - // TODO: parse more than just integer literal - fn parse_constant_expression(&mut self) -> Result { - let token = self.bump()?; - match token.value { - TokenValue::IntConstant(int) => Ok(int.value as i64), - _ => Err(ErrorKind::InvalidToken(token)), - } + fn parse_constant_expression(&mut self) -> Result> { + let mut function = Function::default(); + let mut ctx = FunctionContext::new(&mut function); + + let expr = self.parse_conditional(&mut ctx, None)?; + let root = ctx.resolve(self.program, expr, false)?; + + self.program.solve_constant(&function.expressions, root) } fn parse_external_declaration(&mut self) -> Result<()> { @@ -329,8 +342,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // type_qualifier IDENTIFIER identifier_list SEMICOLON // TODO: Handle precision qualifiers if self.peek_type_qualifier() || self.peek_type_name() { - // TODO: Use qualifiers - let _qualifiers = self.parse_type_qualifiers()?; + let qualifiers = self.parse_type_qualifiers()?; if self.peek_type_name() { // Functions and variable declarations @@ -371,9 +383,20 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } // Variable Declaration TokenValue::Semicolon => { - // TODO: are we supposed to consume the semicolon here self.bump()?; - // TODO: use parsed type & qualifiers + + if let Some(ty) = ty { + if external { + self.program.add_global_var(qualifiers, ty, name, None)?; + } else { + // TODO: local variables + } + } else { + return Err(ErrorKind::SemanticError( + "Declaration cannot have void type".into(), + )); + } + Ok(true) } TokenValue::Comma => todo!(), diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index b7d32f4de..b27fe14fb 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,4 +1,7 @@ -use crate::{Expression, Handle, Type, TypeInner, VectorSize}; +use crate::{ + Binding, BuiltIn, Constant, Expression, GlobalVariable, Handle, ScalarKind, StorageAccess, + StorageClass, StructMember, Type, TypeInner, VectorSize, +}; use super::ast::*; use super::error::ErrorKind; @@ -13,21 +16,88 @@ impl Program<'_> { if let Some(local_var) = context.lookup_local_var(name) { return Ok(Some(local_var)); } - if let Some(global_var) = context.lookup_global_var_exps.get(name) { - return Ok(Some(global_var.clone())); + if let Some(global_var) = context.lookup_global_var(self, name) { + return Ok(Some(global_var)); } - if let Some(constant) = context.lookup_constant_exps.get(name) { - return Ok(Some(constant.clone())); + if let Some(constant) = context.lookup_global_var(self, name) { + return Ok(Some(constant)); } match name { "gl_Position" => { - todo!() + let ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 4, + }, + }); + + let handle = self.module.global_variables.append(GlobalVariable { + name: Some(name.into()), + class: StorageClass::Function, + binding: None, + ty, + init: None, + storage_access: StorageAccess::all(), + }); + + self.built_ins.push((BuiltIn::Position, handle)); + + self.lookup_global_variables + .insert(name.into(), GlobalLookup::Variable(handle)); + + Ok(context.lookup_global_var(self, name)) } "gl_VertexIndex" => { - todo!() + let ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + }); + + let handle = self.module.global_variables.append(GlobalVariable { + name: Some(name.into()), + class: StorageClass::Function, + binding: None, + ty, + init: None, + storage_access: StorageAccess::all(), + }); + + self.built_ins.push((BuiltIn::VertexIndex, handle)); + + self.lookup_global_variables + .insert(name.into(), GlobalLookup::Variable(handle)); + + Ok(context.lookup_global_var(self, name)) } "gl_InstanceIndex" => { - todo!() + let ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + }); + + let handle = self.module.global_variables.append(GlobalVariable { + name: Some(name.into()), + class: StorageClass::Function, + binding: None, + ty, + init: None, + storage_access: StorageAccess::all(), + }); + + self.built_ins.push((BuiltIn::InstanceIndex, handle)); + + self.lookup_global_variables + .insert(name.into(), GlobalLookup::Variable(handle)); + + Ok(context.lookup_global_var(self, name)) } _ => Ok(None), } @@ -130,4 +200,175 @@ impl Program<'_> { )), } } + + // TODO: constants + pub fn add_global_var( + &mut self, + qualifiers: Vec, + ty: Handle, + name: String, + init: Option>, + ) -> Result<(), ErrorKind> { + let mut storage = StorageQualifier::StorageClass(StorageClass::Function); + let mut interpolation = None; + let mut binding = None; + let mut location = None; + let mut sampling = None; + let mut layout = None; + + for qualifier in qualifiers { + match qualifier { + TypeQualifier::StorageQualifier(s) => { + if StorageQualifier::StorageClass(StorageClass::Function) != storage { + return Err(ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + )); + } + + storage = s; + } + TypeQualifier::Interpolation(i) => { + if interpolation.is_some() { + return Err(ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + )); + } + + interpolation = Some(i); + } + TypeQualifier::ResourceBinding(r) => { + if binding.is_some() { + return Err(ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + )); + } + + binding = Some(r); + } + TypeQualifier::Location(l) => { + if location.is_some() { + return Err(ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + )); + } + + location = Some(l); + } + TypeQualifier::Sampling(s) => { + if sampling.is_some() { + return Err(ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + )); + } + + sampling = Some(s); + } + TypeQualifier::Layout(l) => { + if layout.is_some() { + return Err(ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + )); + } + + layout = Some(l); + } + TypeQualifier::EarlyFragmentTests => { + return Err(ErrorKind::SemanticError( + "Cannot set early fragment tests on a declaration".into(), + )); + } + } + } + + if binding.is_some() && storage != StorageQualifier::StorageClass(StorageClass::Uniform) { + return Err(ErrorKind::SemanticError( + "binding requires uniform or buffer storage qualifier".into(), + )); + } + + if (sampling.is_some() || interpolation.is_some()) && location.is_none() { + return Err(ErrorKind::SemanticError( + "Sampling and interpolation qualifiers can only be used in in/out variables".into(), + )); + } + + if let Some(location) = location { + let input = StorageQualifier::Input == storage; + + let index = self.add_member( + input, + Some(name.clone()), + ty, + Some(Binding::Location { + location, + interpolation, + sampling, + }), + ); + + if let Some(i) = index { + self.lookup_global_variables + .insert(name, GlobalLookup::Select(i)); + } + } else if let StorageQualifier::StorageClass(class) = storage { + let handle = self.module.global_variables.append(GlobalVariable { + name: Some(name.clone()), + class, + binding, + ty, + init, + // TODO + storage_access: StorageAccess::all(), + }); + + self.lookup_global_variables + .insert(name, GlobalLookup::Variable(handle)); + } + + Ok(()) + } + + fn add_member( + &mut self, + input: bool, + name: Option, + ty: Handle, + binding: Option, + ) -> Option { + let handle = match input { + true => self.input_struct, + false => self.output_struct, + }; + + let offset = if let TypeInner::Struct { ref members, .. } = self.module.types[handle].inner + { + members + .last() + .map(|member| { + member.offset + + self.module.types[member.ty] + .inner + .span(&self.module.constants) + }) + .unwrap_or(0) + } else { + 0 + }; + + if let TypeInner::Struct { + ref mut members, .. + } = self.module.types.get_mut(handle).inner + { + members.push(StructMember { + name, + ty, + binding, + offset, + }); + + Some(members.len() as u32 - 1) + } else { + None + } + } } From afaf44a75f7f0c5b7ee31c8c463b6d1375b24414 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 7 May 2021 23:01:13 +0100 Subject: [PATCH 0846/2212] [glsl-in] Add function call support --- src/front/glsl/ast.rs | 36 +-- src/front/glsl/functions.rs | 537 ++++++++++++++------------------- src/front/glsl/parser.rs | 54 +++- src/front/glsl/parser_tests.rs | 33 +- 4 files changed, 304 insertions(+), 356 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index bfd49d6bc..072e98f48 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -171,6 +171,8 @@ pub struct FunctionContext<'function> { pub lookup_global_var_exps: FastHashMap, pub lookup_constant_exps: FastHashMap, pub typifier: Typifier, + + pub samplers: FastHashMap, Handle>, } impl<'function> FunctionContext<'function> { @@ -181,6 +183,7 @@ impl<'function> FunctionContext<'function> { lookup_global_var_exps: FastHashMap::default(), lookup_constant_exps: FastHashMap::default(), typifier: Typifier::new(), + samplers: FastHashMap::default(), } } @@ -388,7 +391,14 @@ impl<'function> FunctionContext<'function> { var.load.unwrap_or(var.expr) } } - ExprKind::Call(_) => todo!(), + ExprKind::Call(call) => { + let args: Vec<_> = call + .args + .into_iter() + .map(|e| self.resolve(program, e, false)) + .collect::>()?; + program.function_call(self, call.kind, &args)? + } ExprKind::Conditional { condition, accept, @@ -416,23 +426,6 @@ impl<'function> FunctionContext<'function> { } } -#[derive(Debug)] -pub struct ExpressionRule { - pub expression: Handle, - pub statements: Vec, - pub sampler: Option>, -} - -impl ExpressionRule { - pub fn from_expression(expression: Handle) -> ExpressionRule { - ExpressionRule { - expression, - statements: vec![], - sampler: None, - } - } -} - #[derive(Debug, Clone)] pub struct VariableReference { pub expr: Handle, @@ -489,13 +482,6 @@ pub enum TypeQualifier { EarlyFragmentTests, } -#[derive(Debug)] -pub struct VarDeclaration { - pub type_qualifiers: Vec, - pub ids_initializers: Vec<(Option, Option)>, - pub ty: Handle, -} - #[derive(Debug)] pub enum FunctionCallKind { TypeConstructor(Handle), diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 8b22ad7ab..412136cb2 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,320 +1,249 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Binding, BuiltIn, EntryPoint, Expression, - Function, FunctionArgument, FunctionResult, MathFunction, RelationalFunction, SampleLevel, - ShaderStage, Statement, TypeInner, + Function, FunctionArgument, FunctionResult, Handle, MathFunction, RelationalFunction, + SampleLevel, ScalarKind, ShaderStage, Statement, TypeInner, }; use super::{ast::*, error::ErrorKind}; impl Program<'_> { - // pub fn function_call( - // &mut self, - // context: &mut FunctionContext, - // fc: FunctionCall, - // ) -> Result { - // match fc.kind { - // FunctionCallKind::TypeConstructor(ty) => { - // let h = if fc.args.len() == 1 { - // let is_vec = match *self.resolve_type(context, fc.args[0].expression)? { - // TypeInner::Vector { .. } => true, - // _ => false, - // }; + pub fn function_call( + &mut self, + ctx: &mut FunctionContext, + fc: FunctionCallKind, + args: &[Handle], + ) -> Result, ErrorKind> { + match fc { + FunctionCallKind::TypeConstructor(ty) => { + let h = if args.len() == 1 { + let is_vec = match *self.resolve_type(ctx, args[0])? { + TypeInner::Vector { .. } => true, + _ => false, + }; - // match self.module.types[ty].inner { - // TypeInner::Vector { size, .. } if !is_vec => { - // context.function.expressions.append(Expression::Splat { - // size, - // value: fc.args[0].expression, - // }) - // } - // TypeInner::Scalar { kind, width } - // | TypeInner::Vector { kind, width, .. } => { - // context.function.expressions.append(Expression::As { - // kind, - // expr: fc.args[0].expression, - // convert: Some(width), - // }) - // } - // TypeInner::Matrix { - // columns, - // rows, - // width, - // } => { - // let value = context.function.expressions.append(Expression::As { - // kind: ScalarKind::Float, - // expr: fc.args[0].expression, - // convert: Some(width), - // }); + match self.module.types[ty].inner { + TypeInner::Vector { size, .. } if !is_vec => { + ctx.function.expressions.append(Expression::Splat { + size, + value: args[0], + }) + } + TypeInner::Scalar { kind, width } + | TypeInner::Vector { kind, width, .. } => { + ctx.function.expressions.append(Expression::As { + kind, + expr: args[0], + convert: Some(width), + }) + } + TypeInner::Matrix { + columns, + rows, + width, + } => { + let value = ctx.function.expressions.append(Expression::As { + kind: ScalarKind::Float, + expr: args[0], + convert: Some(width), + }); - // let column = if is_vec { - // value - // } else { - // context - // .function - // .expressions - // .append(Expression::Splat { size: rows, value }) - // }; + let column = if is_vec { + value + } else { + ctx.function + .expressions + .append(Expression::Splat { size: rows, value }) + }; - // let columns = - // std::iter::repeat(column).take(columns as usize).collect(); + let columns = + std::iter::repeat(column).take(columns as usize).collect(); - // context.function.expressions.append(Expression::Compose { - // ty, - // components: columns, - // }) - // } - // _ => return Err(ErrorKind::SemanticError("Bad cast".into())), - // } - // } else { - // context.function.expressions.append(Expression::Compose { - // ty, - // components: fc.args.iter().map(|a| a.expression).collect(), - // }) - // }; + ctx.function.expressions.append(Expression::Compose { + ty, + components: columns, + }) + } + _ => return Err(ErrorKind::SemanticError("Bad cast".into())), + } + } else { + ctx.function.expressions.append(Expression::Compose { + ty, + components: args.to_vec(), + }) + }; - // Ok(ExpressionRule { - // expression: h, - // statements: fc - // .args - // .into_iter() - // .map(|a| a.statements) - // .flatten() - // .collect(), - // sampler: None, - // }) - // } - // FunctionCallKind::Function(name) => { - // match name.as_str() { - // "sampler2D" => { - // if fc.args.len() != 2 { - // return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); - // } - // Ok(ExpressionRule { - // expression: fc.args[0].expression, - // sampler: Some(fc.args[1].expression), - // statements: fc - // .args - // .into_iter() - // .map(|a| a.statements) - // .flatten() - // .collect(), - // }) - // } - // "texture" => { - // if fc.args.len() != 2 { - // return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); - // } - // if let Some(sampler) = fc.args[0].sampler { - // Ok(ExpressionRule { - // expression: context.function.expressions.append( - // Expression::ImageSample { - // image: fc.args[0].expression, - // sampler, - // coordinate: fc.args[1].expression, - // array_index: None, //TODO - // offset: None, //TODO - // level: SampleLevel::Auto, - // depth_ref: None, - // }, - // ), - // sampler: None, - // statements: fc - // .args - // .into_iter() - // .map(|a| a.statements) - // .flatten() - // .collect(), - // }) - // } else { - // Err(ErrorKind::SemanticError("Bad call to texture".into())) - // } - // } - // "textureLod" => { - // if fc.args.len() != 3 { - // return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); - // } - // if let Some(sampler) = fc.args[0].sampler { - // Ok(ExpressionRule { - // expression: context.function.expressions.append( - // Expression::ImageSample { - // image: fc.args[0].expression, - // sampler, - // coordinate: fc.args[1].expression, - // array_index: None, //TODO - // offset: None, //TODO - // level: SampleLevel::Exact(fc.args[2].expression), - // depth_ref: None, - // }, - // ), - // sampler: None, - // statements: fc - // .args - // .into_iter() - // .map(|a| a.statements) - // .flatten() - // .collect(), - // }) - // } else { - // Err(ErrorKind::SemanticError("Bad call to textureLod".into())) - // } - // } - // "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" - // | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" - // | "normalize" => { - // if fc.args.len() != 1 { - // return Err(ErrorKind::WrongNumberArgs(name, 1, fc.args.len())); - // } - // Ok(ExpressionRule { - // expression: context.function.expressions.append(Expression::Math { - // fun: match name.as_str() { - // "ceil" => MathFunction::Ceil, - // "round" => MathFunction::Round, - // "floor" => MathFunction::Floor, - // "fract" => MathFunction::Fract, - // "trunc" => MathFunction::Trunc, - // "sin" => MathFunction::Sin, - // "abs" => MathFunction::Abs, - // "sqrt" => MathFunction::Sqrt, - // "inversesqrt" => MathFunction::InverseSqrt, - // "exp" => MathFunction::Exp, - // "exp2" => MathFunction::Exp2, - // "sign" => MathFunction::Sign, - // "transpose" => MathFunction::Transpose, - // "inverse" => MathFunction::Inverse, - // "normalize" => MathFunction::Normalize, - // _ => unreachable!(), - // }, - // arg: fc.args[0].expression, - // arg1: None, - // arg2: None, - // }), - // sampler: None, - // statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), - // }) - // } - // "pow" | "dot" | "max" => { - // if fc.args.len() != 2 { - // return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); - // } - // Ok(ExpressionRule { - // expression: context.function.expressions.append(Expression::Math { - // fun: match name.as_str() { - // "pow" => MathFunction::Pow, - // "dot" => MathFunction::Dot, - // "max" => MathFunction::Max, - // _ => unreachable!(), - // }, - // arg: fc.args[0].expression, - // arg1: Some(fc.args[1].expression), - // arg2: None, - // }), - // sampler: None, - // statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), - // }) - // } - // "mix" | "clamp" => { - // if fc.args.len() != 3 { - // return Err(ErrorKind::WrongNumberArgs(name, 3, fc.args.len())); - // } - // Ok(ExpressionRule { - // expression: context.function.expressions.append(Expression::Math { - // fun: match name.as_str() { - // "mix" => MathFunction::Mix, - // "clamp" => MathFunction::Clamp, - // _ => unreachable!(), - // }, - // arg: fc.args[0].expression, - // arg1: Some(fc.args[1].expression), - // arg2: Some(fc.args[2].expression), - // }), - // sampler: None, - // statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), - // }) - // } - // "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" - // | "notEqual" => { - // if fc.args.len() != 2 { - // return Err(ErrorKind::WrongNumberArgs(name, 2, fc.args.len())); - // } - // Ok(ExpressionRule { - // expression: context.function.expressions.append(Expression::Binary { - // op: match name.as_str() { - // "lessThan" => BinaryOperator::Less, - // "greaterThan" => BinaryOperator::Greater, - // "lessThanEqual" => BinaryOperator::LessEqual, - // "greaterThanEqual" => BinaryOperator::GreaterEqual, - // "equal" => BinaryOperator::Equal, - // "notEqual" => BinaryOperator::NotEqual, - // _ => unreachable!(), - // }, - // left: fc.args[0].expression, - // right: fc.args[1].expression, - // }), - // sampler: None, - // statements: fc.args.into_iter().flat_map(|a| a.statements).collect(), - // }) - // } - // "isinf" => { - // self.parse_relational_fun(context, name, fc.args, RelationalFunction::IsInf) - // } - // "isnan" => { - // self.parse_relational_fun(context, name, fc.args, RelationalFunction::IsNan) - // } - // "all" => { - // self.parse_relational_fun(context, name, fc.args, RelationalFunction::All) - // } - // "any" => { - // self.parse_relational_fun(context, name, fc.args, RelationalFunction::Any) - // } - // func_name => { - // let function = *self.lookup_function.get(func_name).ok_or_else(|| { - // ErrorKind::SemanticError( - // format!("Unknown function: {}", func_name).into(), - // ) - // })?; - // let arguments: Vec<_> = fc.args.iter().map(|a| a.expression).collect(); - // let mut statements: Vec<_> = - // fc.args.into_iter().flat_map(|a| a.statements).collect(); - // let expression = context - // .function - // .expressions - // .append(Expression::Call(function)); - // statements.push(crate::Statement::Call { - // function, - // arguments, - // result: Some(expression), - // }); - // Ok(ExpressionRule { - // expression, - // sampler: None, - // statements, - // }) - // } - // } - // } - // } - // } + Ok(h) + } + FunctionCallKind::Function(name) => { + match name.as_str() { + "sampler2D" => { + if args.len() != 2 { + return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); + } + ctx.samplers.insert(args[0], args[1]); + Ok(args[0]) + } + "texture" => { + if args.len() != 2 { + return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); + } + if let Some(sampler) = ctx.samplers.get(&args[0]).copied() { + Ok(ctx.function.expressions.append(Expression::ImageSample { + image: args[0], + sampler, + coordinate: args[1], + array_index: None, //TODO + offset: None, //TODO + level: SampleLevel::Auto, + depth_ref: None, + })) + } else { + Err(ErrorKind::SemanticError("Bad call to texture".into())) + } + } + "textureLod" => { + if args.len() != 3 { + return Err(ErrorKind::WrongNumberArgs(name, 3, args.len())); + } + if let Some(sampler) = ctx.samplers.get(&args[0]).copied() { + Ok(ctx.function.expressions.append(Expression::ImageSample { + image: args[0], + sampler, + coordinate: args[1], + array_index: None, //TODO + offset: None, //TODO + level: SampleLevel::Exact(args[2]), + depth_ref: None, + })) + } else { + Err(ErrorKind::SemanticError("Bad call to textureLod".into())) + } + } + "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" + | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" + | "normalize" => { + if args.len() != 1 { + return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); + } + Ok(ctx.function.expressions.append(Expression::Math { + fun: match name.as_str() { + "ceil" => MathFunction::Ceil, + "round" => MathFunction::Round, + "floor" => MathFunction::Floor, + "fract" => MathFunction::Fract, + "trunc" => MathFunction::Trunc, + "sin" => MathFunction::Sin, + "abs" => MathFunction::Abs, + "sqrt" => MathFunction::Sqrt, + "inversesqrt" => MathFunction::InverseSqrt, + "exp" => MathFunction::Exp, + "exp2" => MathFunction::Exp2, + "sign" => MathFunction::Sign, + "transpose" => MathFunction::Transpose, + "inverse" => MathFunction::Inverse, + "normalize" => MathFunction::Normalize, + _ => unreachable!(), + }, + arg: args[0], + arg1: None, + arg2: None, + })) + } + "pow" | "dot" | "max" => { + if args.len() != 2 { + return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); + } + Ok(ctx.function.expressions.append(Expression::Math { + fun: match name.as_str() { + "pow" => MathFunction::Pow, + "dot" => MathFunction::Dot, + "max" => MathFunction::Max, + _ => unreachable!(), + }, + arg: args[0], + arg1: Some(args[1]), + arg2: None, + })) + } + "mix" | "clamp" => { + if args.len() != 3 { + return Err(ErrorKind::WrongNumberArgs(name, 3, args.len())); + } + Ok(ctx.function.expressions.append(Expression::Math { + fun: match name.as_str() { + "mix" => MathFunction::Mix, + "clamp" => MathFunction::Clamp, + _ => unreachable!(), + }, + arg: args[0], + arg1: Some(args[1]), + arg2: Some(args[2]), + })) + } + "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" + | "notEqual" => { + if args.len() != 2 { + return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); + } + Ok(ctx.function.expressions.append(Expression::Binary { + op: match name.as_str() { + "lessThan" => BinaryOperator::Less, + "greaterThan" => BinaryOperator::Greater, + "lessThanEqual" => BinaryOperator::LessEqual, + "greaterThanEqual" => BinaryOperator::GreaterEqual, + "equal" => BinaryOperator::Equal, + "notEqual" => BinaryOperator::NotEqual, + _ => unreachable!(), + }, + left: args[0], + right: args[1], + })) + } + "isinf" => { + self.parse_relational_fun(ctx, name, args, RelationalFunction::IsInf) + } + "isnan" => { + self.parse_relational_fun(ctx, name, args, RelationalFunction::IsNan) + } + "all" => self.parse_relational_fun(ctx, name, args, RelationalFunction::All), + "any" => self.parse_relational_fun(ctx, name, args, RelationalFunction::Any), + func_name => { + let function = *self.lookup_function.get(func_name).ok_or_else(|| { + ErrorKind::SemanticError( + format!("Unknown function: {}", func_name).into(), + ) + })?; + let arguments: Vec<_> = args.to_vec(); + let expression = + ctx.function.expressions.append(Expression::Call(function)); + ctx.function.body.push(crate::Statement::Call { + function, + arguments, + result: Some(expression), + }); + Ok(expression) + } + } + } + } + } - // TODO: Reenable later - // pub fn parse_relational_fun( - // &mut self, - // context: &mut FunctionContext, - // name: String, - // args: Vec, - // fun: RelationalFunction, - // ) -> Result { - // if args.len() != 1 { - // return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); - // } - // Ok(ExpressionRule { - // expression: context.function.expressions.append(Expression::Relational { - // fun, - // argument: args[0].expression, - // }), - // sampler: None, - // statements: args.into_iter().flat_map(|a| a.statements).collect(), - // }) - // } + pub fn parse_relational_fun( + &mut self, + ctx: &mut FunctionContext, + name: String, + args: &[Handle], + fun: RelationalFunction, + ) -> Result, ErrorKind> { + if args.len() != 1 { + return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); + } + + Ok(ctx.function.expressions.append(Expression::Relational { + fun, + argument: args[0], + })) + } pub fn add_function(&mut self, mut function: Function) -> Result<(), ErrorKind> { ensure_block_returns(&mut function.body); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 8d6a6f4e1..4d97b3a7d 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,6 +1,7 @@ use super::{ ast::{ - Expr, ExprKind, FunctionContext, Profile, StorageQualifier, StructLayout, TypeQualifier, + Expr, ExprKind, FunctionCall, FunctionCallKind, FunctionContext, Profile, StorageQualifier, + StructLayout, TypeQualifier, }, error::ErrorKind, lex::Lexer, @@ -461,19 +462,52 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Identifier(_) => { let (name, meta) = self.expect_ident()?; - // TODO: function calls - // let mut args = Vec::new(); - // while TokenValue::RightBracket != self.bump()?.value { - // args.push(self.parse_expression(ctx)?) - // } + if self.bump_if(TokenValue::LeftParen).is_some() { + let mut args = Vec::new(); + while TokenValue::RightParen != self.bump()?.value { + args.push(self.parse_expression(ctx)?) + } - let var = match self.program.lookup_variable(ctx, &name)? { - Some(var) => var, - None => return Err(ErrorKind::UnknownVariable(meta, name)), + Expr { + kind: ExprKind::Call(FunctionCall { + kind: FunctionCallKind::Function(name), + args, + }), + meta, + } + } else { + let var = match self.program.lookup_variable(ctx, &name)? { + Some(var) => var, + None => return Err(ErrorKind::UnknownVariable(meta, name)), + }; + + Expr { + kind: ExprKind::Variable(var), + meta, + } + } + } + TokenValue::TypeName(_) => { + let Token { value, meta } = self.bump()?; + + let handle = if let TokenValue::TypeName(ty) = value { + self.program.module.types.append(ty) + } else { + unreachable!() }; + self.expect(TokenValue::LeftParen)?; + + let mut args = Vec::new(); + while TokenValue::RightParen != self.bump()?.value { + args.push(self.parse_expression(ctx)?) + } + Expr { - kind: ExprKind::Variable(var), + kind: ExprKind::Call(FunctionCall { + kind: FunctionCallKind::TypeConstructor(handle), + args, + }), meta, } } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index b02324c04..b0812ee96 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -205,24 +205,23 @@ fn declarations() { #[test] fn textures() { - // TODO: Reenable tests later - // let mut entry_points = crate::FastHashMap::default(); - // entry_points.insert("".to_string(), ShaderStage::Fragment); + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Fragment); - // let _program = parse_program( - // r#" - // #version 450 - // layout(location = 0) in vec2 v_uv; - // layout(location = 0) out vec4 o_color; - // layout(set = 1, binding = 1) uniform texture2D tex; - // layout(set = 1, binding = 2) uniform sampler tex_sampler; - // void main() { - // o_color = texture(sampler2D(tex, tex_sampler), v_uv); - // } - // "#, - // &entry_points, - // ) - // .unwrap(); + let _program = parse_program( + r#" + #version 450 + layout(location = 0) in vec2 v_uv; + layout(location = 0) out vec4 o_color; + layout(set = 1, binding = 1) uniform texture2D tex; + layout(set = 1, binding = 2) uniform sampler tex_sampler; + void main() { + o_color = texture(sampler2D(tex, tex_sampler), v_uv); + } + "#, + &entry_points, + ) + .unwrap(); } #[test] From 0d98ef4ea9961a6383ef97d8b121437046610648 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 8 May 2021 21:44:56 +0100 Subject: [PATCH 0847/2212] [glsl-in] Add if parsing --- src/front/glsl/ast.rs | 131 +++++++++++----------- src/front/glsl/functions.rs | 67 +++++------ src/front/glsl/parser.rs | 198 ++++++++++++++++++++++----------- src/front/glsl/parser_tests.rs | 58 +++++----- src/front/glsl/variables.rs | 28 ++--- 5 files changed, 264 insertions(+), 218 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 072e98f48..d2879c055 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,9 +1,9 @@ use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind, TokenMetadata}; use crate::{ - proc::ResolveContext, Arena, ArraySize, BinaryOperator, BuiltIn, Constant, Expression, - FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, Module, - RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, - TypeInner, UnaryOperator, + proc::ResolveContext, Arena, ArraySize, BinaryOperator, Block, BuiltIn, Constant, Expression, + FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, + Module, RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, + Type, TypeInner, UnaryOperator, }; #[derive(Debug)] @@ -72,19 +72,19 @@ impl<'a> Program<'a> { pub fn resolve_type<'b>( &'b mut self, - context: &'b mut FunctionContext, + context: &'b mut Context, handle: Handle, ) -> Result<&'b TypeInner, ErrorKind> { let resolve_ctx = ResolveContext { constants: &self.module.constants, global_vars: &self.module.global_variables, - local_vars: &context.function.local_variables, + local_vars: &context.locals, functions: &self.module.functions, - arguments: &context.function.arguments, + arguments: &context.arguments, }; match context.typifier.grow( handle, - &context.function.expressions, + &context.expressions, &mut self.module.types, &resolve_ctx, ) { @@ -112,6 +112,14 @@ impl<'a> Program<'a> { .map_err(|_| ErrorKind::SemanticError("Can't solve constant".into())) } + pub fn function_args_prelude(&self) -> Vec { + vec![FunctionArgument { + name: None, + ty: self.input_struct, + binding: None, + }] + } + pub fn type_size(&self, ty: Handle) -> Result { Ok(match self.module.types[ty].inner { crate::TypeInner::Scalar { width, .. } => width, @@ -164,21 +172,30 @@ pub enum Profile { } #[derive(Debug)] -pub struct FunctionContext<'function> { - pub function: &'function mut Function, +pub struct Context<'function> { + pub expressions: &'function mut Arena, + pub locals: &'function mut Arena, + pub arguments: &'function mut Vec, + //TODO: Find less allocation heavy representation pub scopes: Vec>, pub lookup_global_var_exps: FastHashMap, pub lookup_constant_exps: FastHashMap, pub typifier: Typifier, - pub samplers: FastHashMap, Handle>, } -impl<'function> FunctionContext<'function> { - pub fn new(function: &'function mut Function) -> Self { - FunctionContext { - function, +impl<'function> Context<'function> { + pub fn new( + expressions: &'function mut Arena, + locals: &'function mut Arena, + arguments: &'function mut Vec, + ) -> Self { + Context { + expressions, + locals, + arguments, + scopes: vec![FastHashMap::default()], lookup_global_var_exps: FastHashMap::default(), lookup_constant_exps: FastHashMap::default(), @@ -205,25 +222,16 @@ impl<'function> FunctionContext<'function> { let expr = match *program.lookup_global_variables.get(name)? { GlobalLookup::Variable(v) => Expression::GlobalVariable(v), GlobalLookup::Select(index) => { - let base = self - .function - .expressions - .append(Expression::FunctionArgument( - self.function.arguments.len() as u32 - 1, - )); + let base = self.expressions.append(Expression::FunctionArgument(0)); Expression::AccessIndex { base, index } } }; - let expr = self.function.expressions.append(expr); + let expr = self.expressions.append(expr); let var = VariableReference { expr, - load: Some( - self.function - .expressions - .append(Expression::Load { pointer: expr }), - ), + load: Some(self.expressions.append(Expression::Load { pointer: expr })), }; self.lookup_global_var_exps.insert(name.into(), var.clone()); @@ -239,7 +247,6 @@ impl<'function> FunctionContext<'function> { ) -> Option { self.lookup_constant_exps.get(name).cloned().or_else(|| { let expr = self - .function .expressions .append(Expression::Constant(*program.lookup_constants.get(name)?)); @@ -268,10 +275,7 @@ impl<'function> FunctionContext<'function> { /// Add variable to current scope pub fn add_local_var(&mut self, name: String, expr: Handle) { if let Some(current) = self.scopes.last_mut() { - let load = self - .function - .expressions - .append(Expression::Load { pointer: expr }); + let load = self.expressions.append(Expression::Load { pointer: expr }); (*current).insert( name, @@ -285,8 +289,8 @@ impl<'function> FunctionContext<'function> { /// Add function argument to current scope pub fn add_function_arg(&mut self, name: Option, ty: Handle) { - let index = self.function.arguments.len(); - self.function.arguments.push(FunctionArgument { + let index = self.arguments.len(); + self.arguments.push(FunctionArgument { name: name.clone(), ty, binding: None, @@ -295,7 +299,6 @@ impl<'function> FunctionContext<'function> { if let Some(name) = name { if let Some(current) = self.scopes.last_mut() { let expr = self - .function .expressions .append(Expression::FunctionArgument(index as u32)); @@ -313,33 +316,29 @@ impl<'function> FunctionContext<'function> { self.scopes.pop(); } - pub fn resolve( + pub fn lower( &mut self, program: &mut Program, expr: Expr, lhs: bool, + body: &mut Block, ) -> Result, ErrorKind> { Ok(match expr.kind { ExprKind::Access { base, index } => { - let base = self.resolve(program, *base, lhs)?; - let index = self.resolve(program, *index, false)?; + let base = self.lower(program, *base, lhs, body)?; + let index = self.lower(program, *index, false, body)?; - self.function - .expressions - .append(Expression::Access { base, index }) + self.expressions.append(Expression::Access { base, index }) } ExprKind::Select { base, field } => { - let base = self.resolve(program, *base, lhs)?; + let base = self.lower(program, *base, lhs, body)?; program.field_selection(self, base, &field, expr.meta)? } - ExprKind::Constant(constant) => self - .function - .expressions - .append(Expression::Constant(constant)), + ExprKind::Constant(constant) => self.expressions.append(Expression::Constant(constant)), ExprKind::Binary { left, op, right } => { - let left = self.resolve(program, *left, false)?; - let right = self.resolve(program, *right, false)?; + let left = self.lower(program, *left, false, body)?; + let right = self.lower(program, *right, false, body)?; if let BinaryOperator::Equal | BinaryOperator::NotEqual = op { let equals = op == BinaryOperator::Equal; @@ -358,13 +357,12 @@ impl<'function> FunctionContext<'function> { false => (BinaryOperator::NotEqual, RelationalFunction::Any), }; - let expr = - self.function - .expressions - .append(Expression::Binary { op, left, right }); + let expr = self + .expressions + .append(Expression::Binary { op, left, right }); if left_is_vector && right_is_vector { - self.function.expressions.append(Expression::Relational { + self.expressions.append(Expression::Relational { fun, argument: expr, }) @@ -372,17 +370,14 @@ impl<'function> FunctionContext<'function> { expr } } else { - self.function - .expressions + self.expressions .append(Expression::Binary { left, op, right }) } } ExprKind::Unary { op, expr } => { - let expr = self.resolve(program, *expr, false)?; + let expr = self.lower(program, *expr, false, body)?; - self.function - .expressions - .append(Expression::Unary { op, expr }) + self.expressions.append(Expression::Unary { op, expr }) } ExprKind::Variable(var) => { if lhs { @@ -395,30 +390,30 @@ impl<'function> FunctionContext<'function> { let args: Vec<_> = call .args .into_iter() - .map(|e| self.resolve(program, e, false)) + .map(|e| self.lower(program, e, false, body)) .collect::>()?; - program.function_call(self, call.kind, &args)? + program.function_call(self, call.kind, &args, body)? } ExprKind::Conditional { condition, accept, reject, } => { - let condition = self.resolve(program, *condition, false)?; - let accept = self.resolve(program, *accept, false)?; - let reject = self.resolve(program, *reject, false)?; + let condition = self.lower(program, *condition, false, body)?; + let accept = self.lower(program, *accept, false, body)?; + let reject = self.lower(program, *reject, false, body)?; - self.function.expressions.append(Expression::Select { + self.expressions.append(Expression::Select { condition, accept, reject, }) } ExprKind::Assign { tgt, value } => { - let pointer = self.resolve(program, *tgt, false)?; - let value = self.resolve(program, *value, false)?; + let pointer = self.lower(program, *tgt, false, body)?; + let value = self.lower(program, *value, false, body)?; - self.function.body.push(Statement::Store { pointer, value }); + body.push(Statement::Store { pointer, value }); value } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 412136cb2..cfeb0c010 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,7 +1,7 @@ use crate::{ - proc::ensure_block_returns, Arena, BinaryOperator, Binding, BuiltIn, EntryPoint, Expression, - Function, FunctionArgument, FunctionResult, Handle, MathFunction, RelationalFunction, - SampleLevel, ScalarKind, ShaderStage, Statement, TypeInner, + proc::ensure_block_returns, Arena, BinaryOperator, Binding, Block, BuiltIn, EntryPoint, + Expression, Function, FunctionArgument, FunctionResult, Handle, MathFunction, + RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, Type, TypeInner, }; use super::{ast::*, error::ErrorKind}; @@ -9,9 +9,10 @@ use super::{ast::*, error::ErrorKind}; impl Program<'_> { pub fn function_call( &mut self, - ctx: &mut FunctionContext, + ctx: &mut Context, fc: FunctionCallKind, args: &[Handle], + body: &mut Block, ) -> Result, ErrorKind> { match fc { FunctionCallKind::TypeConstructor(ty) => { @@ -23,14 +24,14 @@ impl Program<'_> { match self.module.types[ty].inner { TypeInner::Vector { size, .. } if !is_vec => { - ctx.function.expressions.append(Expression::Splat { + ctx.expressions.append(Expression::Splat { size, value: args[0], }) } TypeInner::Scalar { kind, width } | TypeInner::Vector { kind, width, .. } => { - ctx.function.expressions.append(Expression::As { + ctx.expressions.append(Expression::As { kind, expr: args[0], convert: Some(width), @@ -41,7 +42,7 @@ impl Program<'_> { rows, width, } => { - let value = ctx.function.expressions.append(Expression::As { + let value = ctx.expressions.append(Expression::As { kind: ScalarKind::Float, expr: args[0], convert: Some(width), @@ -50,15 +51,14 @@ impl Program<'_> { let column = if is_vec { value } else { - ctx.function - .expressions + ctx.expressions .append(Expression::Splat { size: rows, value }) }; let columns = std::iter::repeat(column).take(columns as usize).collect(); - ctx.function.expressions.append(Expression::Compose { + ctx.expressions.append(Expression::Compose { ty, components: columns, }) @@ -66,7 +66,7 @@ impl Program<'_> { _ => return Err(ErrorKind::SemanticError("Bad cast".into())), } } else { - ctx.function.expressions.append(Expression::Compose { + ctx.expressions.append(Expression::Compose { ty, components: args.to_vec(), }) @@ -88,7 +88,7 @@ impl Program<'_> { return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); } if let Some(sampler) = ctx.samplers.get(&args[0]).copied() { - Ok(ctx.function.expressions.append(Expression::ImageSample { + Ok(ctx.expressions.append(Expression::ImageSample { image: args[0], sampler, coordinate: args[1], @@ -106,7 +106,7 @@ impl Program<'_> { return Err(ErrorKind::WrongNumberArgs(name, 3, args.len())); } if let Some(sampler) = ctx.samplers.get(&args[0]).copied() { - Ok(ctx.function.expressions.append(Expression::ImageSample { + Ok(ctx.expressions.append(Expression::ImageSample { image: args[0], sampler, coordinate: args[1], @@ -125,7 +125,7 @@ impl Program<'_> { if args.len() != 1 { return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); } - Ok(ctx.function.expressions.append(Expression::Math { + Ok(ctx.expressions.append(Expression::Math { fun: match name.as_str() { "ceil" => MathFunction::Ceil, "round" => MathFunction::Round, @@ -153,7 +153,7 @@ impl Program<'_> { if args.len() != 2 { return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); } - Ok(ctx.function.expressions.append(Expression::Math { + Ok(ctx.expressions.append(Expression::Math { fun: match name.as_str() { "pow" => MathFunction::Pow, "dot" => MathFunction::Dot, @@ -169,7 +169,7 @@ impl Program<'_> { if args.len() != 3 { return Err(ErrorKind::WrongNumberArgs(name, 3, args.len())); } - Ok(ctx.function.expressions.append(Expression::Math { + Ok(ctx.expressions.append(Expression::Math { fun: match name.as_str() { "mix" => MathFunction::Mix, "clamp" => MathFunction::Clamp, @@ -185,7 +185,7 @@ impl Program<'_> { if args.len() != 2 { return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); } - Ok(ctx.function.expressions.append(Expression::Binary { + Ok(ctx.expressions.append(Expression::Binary { op: match name.as_str() { "lessThan" => BinaryOperator::Less, "greaterThan" => BinaryOperator::Greater, @@ -214,9 +214,8 @@ impl Program<'_> { ) })?; let arguments: Vec<_> = args.to_vec(); - let expression = - ctx.function.expressions.append(Expression::Call(function)); - ctx.function.body.push(crate::Statement::Call { + let expression = ctx.expressions.append(Expression::Call(function)); + body.push(crate::Statement::Call { function, arguments, result: Some(expression), @@ -230,7 +229,7 @@ impl Program<'_> { pub fn parse_relational_fun( &mut self, - ctx: &mut FunctionContext, + ctx: &mut Context, name: String, args: &[Handle], fun: RelationalFunction, @@ -239,7 +238,7 @@ impl Program<'_> { return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); } - Ok(ctx.function.expressions.append(Expression::Relational { + Ok(ctx.expressions.append(Expression::Relational { fun, argument: args[0], })) @@ -253,13 +252,6 @@ impl Program<'_> { .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; let stage = self.entry_points.get(&name); - // Add the input variables as a function argument - function.arguments.push(FunctionArgument { - name: None, - ty: self.input_struct, - binding: None, - }); - let handle = self.module.functions.append(function); if let Some(&stage) = stage { @@ -277,6 +269,12 @@ impl Program<'_> { let mut expressions = Arena::new(); let mut body = Vec::new(); + arguments.push(FunctionArgument { + name: None, + ty: self.input_struct, + binding: None, + }); + for (built_in, handle) in self.built_ins.iter().copied() { let ty = self.module.global_variables[handle].ty; let arg = arguments.len() as u32; @@ -293,18 +291,11 @@ impl Program<'_> { body.push(Statement::Store { pointer, value }); } - let i = arguments.len() as u32; - arguments.push(FunctionArgument { - name: None, - ty: self.input_struct, - binding: None, - }); - let res = expressions.append(Expression::Call(function)); body.push(Statement::Call { function, - arguments: vec![expressions.append(Expression::FunctionArgument(i))], + arguments: vec![expressions.append(Expression::FunctionArgument(0))], result: Some(res), }); @@ -314,7 +305,7 @@ impl Program<'_> { } let value = expressions.append(Expression::GlobalVariable(handle)); - let pointer = expressions.append(Expression::FunctionArgument(i as u32)); + let pointer = expressions.append(Expression::FunctionArgument(i as u32 + 1)); body.push(Statement::Store { pointer, value }); } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 4d97b3a7d..f243ded15 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,6 +1,6 @@ use super::{ ast::{ - Expr, ExprKind, FunctionCall, FunctionCallKind, FunctionContext, Profile, StorageQualifier, + Context, Expr, ExprKind, FunctionCall, FunctionCallKind, Profile, StorageQualifier, StructLayout, TypeQualifier, }, error::ErrorKind, @@ -9,8 +9,9 @@ use super::{ Program, }; use crate::{ - arena::Handle, ArraySize, BinaryOperator, Constant, ConstantInner, Function, FunctionResult, - ResourceBinding, ScalarValue, Statement, StorageClass, Type, TypeInner, UnaryOperator, + arena::Handle, Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Function, + FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, Type, TypeInner, + UnaryOperator, }; use core::convert::TryFrom; use std::iter::Peekable; @@ -301,13 +302,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } fn parse_constant_expression(&mut self) -> Result> { - let mut function = Function::default(); - let mut ctx = FunctionContext::new(&mut function); + let mut expressions = Arena::new(); + let mut locals = Arena::new(); + let mut arguments = Vec::new(); + + let mut ctx = Context::new(&mut expressions, &mut locals, &mut arguments); let expr = self.parse_conditional(&mut ctx, None)?; - let root = ctx.resolve(self.program, expr, false)?; + let root = ctx.lower(self.program, expr, false, &mut Block::new())?; - self.program.solve_constant(&function.expressions, root) + self.program.solve_constant(&expressions, root) } fn parse_external_declaration(&mut self) -> Result<()> { @@ -358,12 +362,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::LeftParen => { self.bump()?; - let mut function = Function { - name: Some(name), - result: ty.map(|ty| FunctionResult { ty, binding: None }), - ..Default::default() - }; - let mut context = FunctionContext::new(&mut function); + let mut expressions = Arena::new(); + let mut local_variables = Arena::new(); + let mut arguments = self.program.function_args_prelude(); + + let mut context = Context::new( + &mut expressions, + &mut local_variables, + &mut arguments, + ); self.parse_function_args(&mut context)?; @@ -374,8 +381,17 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // TODO: Function prototypes TokenValue::Semicolon => todo!(), TokenValue::LeftBrace if external => { - self.parse_compound_statement(&mut context)?; - self.program.add_function(function)?; + let mut body = Block::new(); + + self.parse_compound_statement(&mut context, &mut body)?; + self.program.add_function(Function { + name: Some(name), + result: ty.map(|ty| FunctionResult { ty, binding: None }), + expressions, + local_variables, + arguments, + body, + })?; Ok(true) } @@ -419,7 +435,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } - fn parse_primary(&mut self, ctx: &mut FunctionContext) -> Result { + fn parse_primary(&mut self, ctx: &mut Context) -> Result { let token = self.bump()?; let (width, value) = match token.value { @@ -457,7 +473,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }) } - fn parse_postfix(&mut self, ctx: &mut FunctionContext) -> Result { + fn parse_postfix(&mut self, ctx: &mut Context) -> Result { let mut expr = match self.expect_peek()?.value { TokenValue::Identifier(_) => { let (name, meta) = self.expect_ident()?; @@ -551,7 +567,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(expr) } - fn parse_unary(&mut self, ctx: &mut FunctionContext) -> Result { + fn parse_unary(&mut self, ctx: &mut Context) -> Result { // TODO: prefix inc/dec match self.expect_peek()?.value { TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { @@ -580,7 +596,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_binary( &mut self, - ctx: &mut FunctionContext, + ctx: &mut Context, passtrough: Option, min_bp: u8, ) -> Result { @@ -631,11 +647,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(expr) } - fn parse_conditional( - &mut self, - ctx: &mut FunctionContext, - passtrough: Option, - ) -> Result { + fn parse_conditional(&mut self, ctx: &mut Context, passtrough: Option) -> Result { let mut condition = self.parse_binary(ctx, passtrough, 0)?; if let TokenValue::Question = self.expect_peek()?.value { @@ -658,7 +670,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(condition) } - fn parse_assignment(&mut self, ctx: &mut FunctionContext) -> Result { + fn parse_assignment(&mut self, ctx: &mut Context) -> Result { let pointer = self.parse_unary(ctx)?; if let TokenValue::Assign = self.expect_peek()?.value { @@ -678,7 +690,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } - fn parse_expression(&mut self, ctx: &mut FunctionContext) -> Result { + fn parse_expression(&mut self, ctx: &mut Context) -> Result { let mut expr = self.parse_assignment(ctx)?; while let TokenValue::Comma = self.expect_peek()?.value { @@ -689,52 +701,106 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(expr) } - fn parse_compound_statement(&mut self, ctx: &mut FunctionContext) -> Result<()> { - loop { - let token = self.bump()?; - - match token.value { - TokenValue::Continue => { - ctx.function.body.push(Statement::Continue); - self.expect(TokenValue::Semicolon)?; - } - TokenValue::Break => { - ctx.function.body.push(Statement::Break); - self.expect(TokenValue::Semicolon)?; - } - TokenValue::Return => { - let value = match self.expect_peek()?.value { - TokenValue::Semicolon => { - self.bump()?; - None - } - _ => { - let expr = self.parse_expression(ctx)?; - self.expect(TokenValue::Semicolon)?; - Some(ctx.resolve(self.program, expr, false)?) - } - }; - - ctx.function.body.push(Statement::Return { value }) - } - TokenValue::Discard => { - ctx.function.body.push(Statement::Kill); - self.expect(TokenValue::Semicolon)?; - } - TokenValue::LeftBrace => { - ctx.push_scope(); - self.parse_compound_statement(ctx)?; - ctx.remove_current_scope(); - } - TokenValue::RightBrace => break, - _ => {} + fn parse_statement(&mut self, ctx: &mut Context, body: &mut Block) -> Result<()> { + match self.expect_peek()?.value { + TokenValue::Continue => { + self.bump()?; + body.push(Statement::Continue); + self.expect(TokenValue::Semicolon)?; } + TokenValue::Break => { + self.bump()?; + body.push(Statement::Break); + self.expect(TokenValue::Semicolon)?; + } + TokenValue::Return => { + self.bump()?; + let value = match self.expect_peek()?.value { + TokenValue::Semicolon => { + self.bump()?; + None + } + _ => { + let expr = self.parse_expression(ctx)?; + self.expect(TokenValue::Semicolon)?; + Some(ctx.lower(self.program, expr, false, body)?) + } + }; + + body.push(Statement::Return { value }) + } + TokenValue::Discard => { + self.bump()?; + body.push(Statement::Kill); + self.expect(TokenValue::Semicolon)?; + } + TokenValue::If => { + self.bump()?; + + self.expect(TokenValue::LeftParen)?; + let condition = { + let expr = self.parse_expression(ctx)?; + ctx.lower(self.program, expr, false, body)? + }; + self.expect(TokenValue::RightParen)?; + + let mut accept = Block::new(); + self.parse_statement(ctx, &mut accept)?; + + let mut reject = Block::new(); + if self.bump_if(TokenValue::Else).is_some() { + self.parse_statement(ctx, &mut reject)?; + } + + body.push(Statement::If { + condition, + accept, + reject, + }); + } + TokenValue::LeftBrace => { + self.bump()?; + + let mut block = Block::new(); + ctx.push_scope(); + + self.parse_compound_statement(ctx, &mut block)?; + + ctx.remove_current_scope(); + body.push(Statement::Block(block)); + } + TokenValue::Plus + | TokenValue::Dash + | TokenValue::Bang + | TokenValue::Tilde + | TokenValue::LeftParen + | TokenValue::Identifier(_) + | TokenValue::TypeName(_) + | TokenValue::IntConstant(_) + | TokenValue::BoolConstant(_) + | TokenValue::FloatConstant(_) => { + self.parse_expression(ctx)?; + self.expect(TokenValue::Semicolon)?; + } + _ => {} } Ok(()) } - fn parse_function_args(&mut self, context: &mut FunctionContext) -> Result<()> { + fn parse_compound_statement(&mut self, ctx: &mut Context, body: &mut Block) -> Result<()> { + loop { + if self.bump_if(TokenValue::RightBrace).is_some() { + break; + } + + self.parse_statement(ctx, body)?; + } + + Ok(()) + } + + fn parse_function_args(&mut self, context: &mut Context) -> Result<()> { loop { // TODO: parameter qualifier if self.peek_type_name() { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index b0812ee96..72a9f891d 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -82,38 +82,38 @@ fn version() { #[test] fn control_flow() { - // TODO: Reenable tests later - // let mut entry_points = crate::FastHashMap::default(); - // entry_points.insert("".to_string(), ShaderStage::Vertex); + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Vertex); - // let _program = parse_program( - // r#" - // # version 450 - // void main() { - // if (true) { - // return 1; - // } else { - // return 2; - // } - // } - // "#, - // &entry_points, - // ) - // .unwrap(); + let _program = parse_program( + r#" + # version 450 + void main() { + if (true) { + return 1; + } else { + return 2; + } + } + "#, + &entry_points, + ) + .unwrap(); - // let _program = parse_program( - // r#" - // # version 450 - // void main() { - // if (true) { - // return 1; - // } - // } - // "#, - // &entry_points, - // ) - // .unwrap(); + let _program = parse_program( + r#" + # version 450 + void main() { + if (true) { + return 1; + } + } + "#, + &entry_points, + ) + .unwrap(); + // TODO: Reenable later // let _program = parse_program( // r#" // # version 450 diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index b27fe14fb..6d6ec4b44 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -10,7 +10,7 @@ use super::token::TokenMetadata; impl Program<'_> { pub fn lookup_variable( &mut self, - context: &mut FunctionContext, + context: &mut Context, name: &str, ) -> Result, ErrorKind> { if let Some(local_var) = context.lookup_local_var(name) { @@ -105,7 +105,7 @@ impl Program<'_> { pub fn field_selection( &mut self, - context: &mut FunctionContext, + context: &mut Context, expression: Handle, name: &str, meta: TokenMetadata, @@ -116,13 +116,10 @@ impl Program<'_> { .iter() .position(|m| m.name == Some(name.into())) .ok_or_else(|| ErrorKind::UnknownField(meta, name.into()))?; - Ok(context - .function - .expressions - .append(Expression::AccessIndex { - base: expression, - index: index as u32, - })) + Ok(context.expressions.append(Expression::AccessIndex { + base: expression, + index: index as u32, + })) } // swizzles (xyzw, rgba, stpq) TypeInner::Vector { size, kind, width } => { @@ -151,20 +148,17 @@ impl Program<'_> { let components: Vec> = v .iter() .map(|idx| { - context - .function - .expressions - .append(Expression::AccessIndex { - base: expression, - index: *idx as u32, - }) + context.expressions.append(Expression::AccessIndex { + base: expression, + index: *idx as u32, + }) }) .collect(); if components.len() == 1 { // only single element swizzle, like pos.y, just return that component Ok(components[0]) } else { - Ok(context.function.expressions.append(Expression::Compose { + Ok(context.expressions.append(Expression::Compose { ty: self.module.types.fetch_or_append(Type { name: None, inner: TypeInner::Vector { From 39ccec5e7d41dd4f6a76e07bab2b1eb224b4496f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 9 May 2021 15:48:11 +0100 Subject: [PATCH 0848/2212] [glsl-in] Update pp-rs for location info --- Cargo.toml | 2 +- src/front/glsl/lex.rs | 55 ++++++---------------------- src/front/glsl/parser.rs | 67 ++++++++++++++++++++++------------ src/front/glsl/parser_tests.rs | 8 ++-- src/front/glsl/token.rs | 9 ++++- 5 files changed, 67 insertions(+), 74 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1809e624e..b67f45046 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } rose_tree = { version ="0.2", optional = true } -pp-rs = { version = "0.1", optional = true } +pp-rs = { git = "https://github.com/Kangz/glslpp-rs.git", optional = true, rev = "c02476b" } #env_logger = "0.8" # uncomment temporarily for developing with the binary target [features] diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index a07cc4af2..95cb24094 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -30,19 +30,13 @@ impl<'a> Lexer<'a> { impl<'a> Iterator for Lexer<'a> { type Item = Token; fn next(&mut self) -> Option { - let mut meta = TokenMetadata { - line: 0, - chars: 0..0, - }; + let mut meta = TokenMetadata { chars: 0..0 }; let pp_token = match self.tokens.pop_front() { Some(t) => t, None => match self.pp.next()? { Ok(t) => t, Err((err, loc)) => { - meta.line = loc.line as usize; - meta.chars.start = loc.pos as usize; - //TODO: proper location end - meta.chars.end = loc.pos as usize + 1; + meta.chars = loc.into(); return Some(Token { value: TokenValue::Unknown(err), meta, @@ -51,10 +45,7 @@ impl<'a> Iterator for Lexer<'a> { }, }; - meta.line = pp_token.location.line as usize; - meta.chars.start = pp_token.location.pos as usize; - //TODO: proper location end - meta.chars.end = pp_token.location.pos as usize + 1; + meta.chars = pp_token.location.into(); let value = match pp_token.value { PPTokenValue::Extension(extension) => { for t in extension.tokens { @@ -195,10 +186,7 @@ mod tests { lex.next().unwrap(), Token { value: TokenValue::Version, - meta: TokenMetadata { - line: 1, - chars: 1..2 //TODO - } + meta: TokenMetadata { chars: 1..8 } } ); assert_eq!( @@ -209,70 +197,49 @@ mod tests { value: 450, width: 32 }), - meta: TokenMetadata { - line: 1, - chars: 9..10 //TODO - }, + meta: TokenMetadata { chars: 9..12 }, } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::Void, - meta: TokenMetadata { - line: 2, - chars: 0..1 //TODO - } + meta: TokenMetadata { chars: 13..17 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::Identifier("main".into()), - meta: TokenMetadata { - line: 2, - chars: 5..6 //TODO - } + meta: TokenMetadata { chars: 18..22 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::LeftParen, - meta: TokenMetadata { - line: 2, - chars: 10..11 //TODO - } + meta: TokenMetadata { chars: 23..24 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::RightParen, - meta: TokenMetadata { - line: 2, - chars: 11..12 //TODO - } + meta: TokenMetadata { chars: 24..25 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::LeftBrace, - meta: TokenMetadata { - line: 2, - chars: 13..14 //TODO - } + meta: TokenMetadata { chars: 26..27 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::RightBrace, - meta: TokenMetadata { - line: 2, - chars: 14..15 //TODO - } + meta: TokenMetadata { chars: 27..28 } } ); assert_eq!(lex.next(), None); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index f243ded15..040dbd32e 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -436,7 +436,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } fn parse_primary(&mut self, ctx: &mut Context) -> Result { - let token = self.bump()?; + let mut token = self.bump()?; let (width, value) = match token.value { TokenValue::IntConstant(int) => ( @@ -454,7 +454,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)), TokenValue::LeftParen => { let expr = self.parse_expression(ctx)?; - self.expect(TokenValue::RightParen)?; + let meta = self.expect(TokenValue::RightParen)?.meta; + + token.meta = token.meta.union(&meta); return Ok(expr); } @@ -476,11 +478,18 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_postfix(&mut self, ctx: &mut Context) -> Result { let mut expr = match self.expect_peek()?.value { TokenValue::Identifier(_) => { - let (name, meta) = self.expect_ident()?; + let (name, mut meta) = self.expect_ident()?; if self.bump_if(TokenValue::LeftParen).is_some() { let mut args = Vec::new(); - while TokenValue::RightParen != self.bump()?.value { + loop { + let token = self.bump()?; + + if let TokenValue::RightParen = token.value { + meta = meta.union(&token.meta); + break; + } + args.push(self.parse_expression(ctx)?) } @@ -504,7 +513,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } TokenValue::TypeName(_) => { - let Token { value, meta } = self.bump()?; + let Token { value, mut meta } = self.bump()?; let handle = if let TokenValue::TypeName(ty) = value { self.program.module.types.append(ty) @@ -515,7 +524,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::LeftParen)?; let mut args = Vec::new(); - while TokenValue::RightParen != self.bump()?.value { + loop { + let token = self.bump()?; + + if let TokenValue::RightParen = token.value { + meta = meta.union(&token.meta); + break; + } + args.push(self.parse_expression(ctx)?) } @@ -537,27 +553,25 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match value { TokenValue::LeftBracket => { let index = Box::new(self.parse_expression(ctx)?); - self.expect(TokenValue::RightBracket)?; + let end_meta = self.expect(TokenValue::RightBracket)?.meta; - // TODO: metadata unification expr = Expr { kind: ExprKind::Access { base: Box::new(expr), index, }, - meta, + meta: meta.union(&end_meta), } } TokenValue::Dot => { - let field = self.expect_ident()?.0; + let (field, end_meta) = self.expect_ident()?; - // TODO: metadata unification expr = Expr { kind: ExprKind::Select { base: Box::new(expr), field, }, - meta, + meta: meta.union(&end_meta), } } _ => unreachable!(), @@ -574,6 +588,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let Token { value, meta } = self.bump()?; let expr = self.parse_unary(ctx)?; + let end_meta = expr.meta.clone(); let kind = match value { TokenValue::Dash => ExprKind::Unary { @@ -587,8 +602,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { _ => return Ok(expr), }; - // TODO: metadata unification - Ok(Expr { kind, meta }) + Ok(Expr { + kind, + meta: meta.union(&end_meta), + }) } _ => self.parse_postfix(ctx), } @@ -603,15 +620,17 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut expr = passtrough .ok_or(ErrorKind::EndOfFile /* Dummy error */) .or_else(|_| self.parse_unary(ctx))?; + let start_meta = expr.meta.clone(); while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek()?.value) { if l_bp < min_bp { break; } - let Token { value, meta } = self.bump()?; + let Token { value, .. } = self.bump()?; let right = Box::new(self.parse_binary(ctx, None, r_bp)?); + let end_meta = right.meta.clone(); expr = Expr { kind: ExprKind::Binary { @@ -640,7 +659,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }, right, }, - meta, + meta: start_meta.union(&end_meta), } } @@ -649,13 +668,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_conditional(&mut self, ctx: &mut Context, passtrough: Option) -> Result { let mut condition = self.parse_binary(ctx, passtrough, 0)?; + let start_meta = condition.meta.clone(); - if let TokenValue::Question = self.expect_peek()?.value { - let meta = self.bump()?.meta; - + if self.bump_if(TokenValue::Question).is_some() { let accept = Box::new(self.parse_expression(ctx)?); self.expect(TokenValue::Colon)?; let reject = Box::new(self.parse_assignment(ctx)?); + let end_meta = reject.meta.clone(); condition = Expr { kind: ExprKind::Conditional { @@ -663,7 +682,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { accept, reject, }, - meta, + meta: start_meta.union(&end_meta), }; } @@ -672,18 +691,18 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_assignment(&mut self, ctx: &mut Context) -> Result { let pointer = self.parse_unary(ctx)?; + let start_meta = pointer.meta.clone(); - if let TokenValue::Assign = self.expect_peek()?.value { - let meta = self.bump()?.meta; - + if self.bump_if(TokenValue::Assign).is_some() { let value = Box::new(self.parse_assignment(ctx)?); + let end_meta = value.meta.clone(); Ok(Expr { kind: ExprKind::Assign { tgt: Box::new(pointer), value, }, - meta, + meta: start_meta.union(&end_meta), }) } else { self.parse_conditional(ctx, Some(pointer)) diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 72a9f891d..fc7336209 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -29,7 +29,7 @@ fn version() { .err() .unwrap() ), - "InvalidVersion(TokenMetadata { line: 1, chars: 9..10 }, 99000)" //TODO: location + "InvalidVersion(TokenMetadata { chars: 9..14 }, 99000)" ); assert_eq!( @@ -37,7 +37,7 @@ fn version() { "{:?}", parse_program("#version 449", &entry_points).err().unwrap() ), - "InvalidVersion(TokenMetadata { line: 1, chars: 9..10 }, 449)" //TODO: location + "InvalidVersion(TokenMetadata { chars: 9..12 }, 449)" ); assert_eq!( @@ -47,7 +47,7 @@ fn version() { .err() .unwrap() ), - "InvalidProfile(TokenMetadata { line: 1, chars: 13..14 }, \"smart\")" //TODO: location + "InvalidProfile(TokenMetadata { chars: 13..18 }, \"smart\")" ); assert_eq!( @@ -57,7 +57,7 @@ fn version() { .err() .unwrap() ), - "InvalidToken(Token { value: Unknown(UnexpectedHash), meta: TokenMetadata { line: 2, chars: 11..12 } })" + "InvalidToken(Token { value: Unknown(UnexpectedHash), meta: TokenMetadata { chars: 24..25 } })" ); // valid versions diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index e17ba7d5c..3483f9d27 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -6,10 +6,17 @@ use std::ops::Range; #[derive(Debug, Clone)] #[cfg_attr(test, derive(PartialEq))] pub struct TokenMetadata { - pub line: usize, pub chars: Range, } +impl TokenMetadata { + pub fn union(&self, other: &Self) -> Self { + TokenMetadata { + chars: (self.chars.start.min(other.chars.start))..(self.chars.end.max(self.chars.end)), + } + } +} + #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub struct Token { From 73f928a7c35f6243c70f63f8eb26be984f94a3b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 10 May 2021 11:42:59 +0100 Subject: [PATCH 0849/2212] [glsl-in] Add support for switch statements --- src/front/glsl/parser.rs | 101 ++++++++++++++++++++++++++++++++- src/front/glsl/parser_tests.rs | 43 +++++++------- 2 files changed, 120 insertions(+), 24 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 040dbd32e..264ba6aaa 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -10,11 +10,11 @@ use super::{ }; use crate::{ arena::Handle, Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Function, - FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, Type, TypeInner, - UnaryOperator, + FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, SwitchCase, Type, + TypeInner, UnaryOperator, }; use core::convert::TryFrom; -use std::iter::Peekable; +use std::{iter::Peekable, mem}; type Result = std::result::Result; @@ -777,6 +777,101 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { reject, }); } + TokenValue::Switch => { + self.bump()?; + + self.expect(TokenValue::LeftParen)?; + let selector = { + let expr = self.parse_expression(ctx)?; + ctx.lower(self.program, expr, false, body)? + }; + self.expect(TokenValue::RightParen)?; + + let mut cases = Vec::new(); + let mut default = Block::new(); + + self.expect(TokenValue::LeftBrace)?; + loop { + match self.expect_peek()?.value { + TokenValue::Case => { + self.bump()?; + let value = { + let expr = self.parse_expression(ctx)?; + let root = ctx.lower(self.program, expr, false, body)?; + let constant = + self.program.solve_constant(&ctx.expressions, root)?; + + match self.program.module.constants[constant].inner { + ConstantInner::Scalar { + value: ScalarValue::Sint(int), + .. + } => int as i32, + ConstantInner::Scalar { + value: ScalarValue::Uint(int), + .. + } => int as i32, + _ => { + return Err(ErrorKind::SemanticError( + "Case values can only be integers".into(), + )) + } + } + }; + + self.expect(TokenValue::Colon)?; + + let mut body = Block::new(); + + loop { + match self.expect_peek()?.value { + TokenValue::Case + | TokenValue::Default + | TokenValue::RightBrace => break, + _ => self.parse_statement(ctx, &mut body)?, + } + } + + let fall_through = body.iter().any(|s| { + mem::discriminant(s) == mem::discriminant(&Statement::Break) + }); + + cases.push(SwitchCase { + value, + body, + fall_through, + }) + } + TokenValue::Default => { + self.bump()?; + self.expect(TokenValue::Colon)?; + + if !default.is_empty() { + return Err(ErrorKind::SemanticError( + "Can only have one default case per switch statement".into(), + )); + } + + loop { + match self.expect_peek()?.value { + TokenValue::Case | TokenValue::RightBrace => break, + _ => self.parse_statement(ctx, &mut &mut default)?, + } + } + } + TokenValue::RightBrace => { + self.bump()?; + break; + } + _ => return Err(ErrorKind::InvalidToken(self.bump()?)), + } + } + + body.push(Statement::Switch { + selector, + cases, + default, + }); + } TokenValue::LeftBrace => { self.bump()?; diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index fc7336209..6d97c2661 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -113,32 +113,33 @@ fn control_flow() { ) .unwrap(); + let _program = parse_program( + r#" + # version 450 + int x; + int y; + + void main() { + switch (5) { + case 2: + x = 2; + case 5: + x = 5; + y = 2; + break; + default: + x = 0; + } + } + "#, + &entry_points, + ) + .unwrap(); // TODO: Reenable later // let _program = parse_program( // r#" // # version 450 // void main() { - // int x; - // int y = 3; - // switch (5) { - // case 2: - // x = 2; - // case 5: - // x = 5; - // y = 2; - // break; - // default: - // x = 0; - // } - // } - // "#, - // &entry_points, - // ) - // .unwrap(); - // let _program = parse_program( - // r#" - // # version 450 - // void main() { // int x = 0; // while(x < 5) { // x = x + 1; From cfe41052374f009a1363ebc6f012c0feba3e1251 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 11 May 2021 19:39:17 +0100 Subject: [PATCH 0850/2212] [glsl-in] Add support for while/do statements --- src/front/glsl/parser.rs | 62 ++++++++++++++++++++++++++++++++-- src/front/glsl/parser_tests.rs | 35 +++++++++---------- 2 files changed, 77 insertions(+), 20 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 264ba6aaa..ef2952289 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -9,9 +9,9 @@ use super::{ Program, }; use crate::{ - arena::Handle, Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Function, - FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, SwitchCase, Type, - TypeInner, UnaryOperator, + arena::Handle, Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Expression, + Function, FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, SwitchCase, + Type, TypeInner, UnaryOperator, }; use core::convert::TryFrom; use std::{iter::Peekable, mem}; @@ -872,6 +872,62 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { default, }); } + TokenValue::While => { + self.bump()?; + + self.expect(TokenValue::LeftParen)?; + let root = self.parse_expression(ctx)?; + self.expect(TokenValue::RightParen)?; + + let mut loop_body = Block::new(); + + let expr = ctx.lower(self.program, root, false, &mut loop_body)?; + let condition = ctx.expressions.append(Expression::Unary { + op: UnaryOperator::Not, + expr, + }); + + loop_body.push(Statement::If { + condition, + accept: vec![Statement::Break], + reject: Block::new(), + }); + + self.parse_statement(ctx, &mut loop_body)?; + + body.push(Statement::Loop { + body: loop_body, + continuing: Block::new(), + }) + } + TokenValue::Do => { + self.bump()?; + + let mut loop_body = Block::new(); + self.parse_statement(ctx, &mut loop_body)?; + + self.expect(TokenValue::While)?; + self.expect(TokenValue::LeftParen)?; + let root = self.parse_expression(ctx)?; + self.expect(TokenValue::RightParen)?; + + let expr = ctx.lower(self.program, root, false, &mut loop_body)?; + let condition = ctx.expressions.append(Expression::Unary { + op: UnaryOperator::Not, + expr, + }); + + loop_body.push(Statement::If { + condition, + accept: vec![Statement::Break], + reject: Block::new(), + }); + + body.push(Statement::Loop { + body: loop_body, + continuing: Block::new(), + }) + } TokenValue::LeftBrace => { self.bump()?; diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 6d97c2661..05dc0425f 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -135,24 +135,25 @@ fn control_flow() { &entry_points, ) .unwrap(); - // TODO: Reenable later - // let _program = parse_program( - // r#" - // # version 450 - // void main() { - // int x = 0; - // while(x < 5) { - // x = x + 1; - // } - // do { - // x = x - 1; - // } while(x >= 4) - // } - // "#, - // &entry_points, - // ) - // .unwrap(); + let _program = parse_program( + r#" + # version 450 + int x; + void main() { + while(x < 5) { + x = x + 1; + } + do { + x = x - 1; + } while(x >= 4) + } + "#, + &entry_points, + ) + .unwrap(); + + // TODO: Reenable later // let _program = parse_program( // r#" // # version 450 From 62d3956096e2ceb777ff8fc21b99df51396ee064 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 13 May 2021 16:16:22 +0100 Subject: [PATCH 0851/2212] [glsl-in] function prototypes and overloading --- src/front/glsl/ast.rs | 111 ++++++++++++++++++++------ src/front/glsl/functions.rs | 142 ++++++++++++++++++++++++++++----- src/front/glsl/mod.rs | 2 - src/front/glsl/parser.rs | 82 ++++++++++++++----- src/front/glsl/parser_tests.rs | 67 +++++++++++++--- src/front/mod.rs | 24 ++++++ 6 files changed, 353 insertions(+), 75 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index d2879c055..8d98970c8 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -12,13 +12,27 @@ pub enum GlobalLookup { Select(u32), } +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct FunctionSignature { + pub name: String, + pub parameters: Vec>, +} + +#[derive(Debug, Clone)] +pub struct FunctionDeclaration { + pub parameters: Vec, + pub handle: Handle, + /// Wheter this function was already defined or is just a prototype + pub defined: bool, +} + #[derive(Debug)] pub struct Program<'a> { pub version: u16, pub profile: Profile, pub entry_points: &'a FastHashMap, - pub lookup_function: FastHashMap>, + pub lookup_function: FastHashMap, pub lookup_type: FastHashMap>, pub lookup_global_variables: FastHashMap, pub lookup_constants: FastHashMap>, @@ -96,6 +110,32 @@ impl<'a> Program<'a> { } } + pub fn resolve_handle( + &mut self, + context: &mut Context, + handle: Handle, + ) -> Result, ErrorKind> { + let resolve_ctx = ResolveContext { + constants: &self.module.constants, + global_vars: &self.module.global_variables, + local_vars: &context.locals, + functions: &self.module.functions, + arguments: &context.arguments, + }; + match context.typifier.grow( + handle, + &context.expressions, + &mut self.module.types, + &resolve_ctx, + ) { + //TODO: better error report + Err(error) => Err(ErrorKind::SemanticError( + format!("Can't resolve type: {:?}", error).into(), + )), + Ok(()) => Ok(context.typifier.get_handle(handle, &mut self.module.types)), + } + } + pub fn solve_constant( &mut self, expressions: &Arena, @@ -112,12 +152,15 @@ impl<'a> Program<'a> { .map_err(|_| ErrorKind::SemanticError("Can't solve constant".into())) } - pub fn function_args_prelude(&self) -> Vec { - vec![FunctionArgument { - name: None, - ty: self.input_struct, - binding: None, - }] + pub fn function_args_prelude(&self) -> (Vec, Vec) { + ( + vec![FunctionArgument { + name: None, + ty: self.input_struct, + binding: None, + }], + vec![ParameterQualifier::In], + ) } pub fn type_size(&self, ty: Handle) -> Result { @@ -335,8 +378,10 @@ impl<'function> Context<'function> { program.field_selection(self, base, &field, expr.meta)? } - ExprKind::Constant(constant) => self.expressions.append(Expression::Constant(constant)), - ExprKind::Binary { left, op, right } => { + ExprKind::Constant(constant) if !lhs => { + self.expressions.append(Expression::Constant(constant)) + } + ExprKind::Binary { left, op, right } if !lhs => { let left = self.lower(program, *left, false, body)?; let right = self.lower(program, *right, false, body)?; @@ -374,7 +419,7 @@ impl<'function> Context<'function> { .append(Expression::Binary { left, op, right }) } } - ExprKind::Unary { op, expr } => { + ExprKind::Unary { op, expr } if !lhs => { let expr = self.lower(program, *expr, false, body)?; self.expressions.append(Expression::Unary { op, expr }) @@ -386,19 +431,14 @@ impl<'function> Context<'function> { var.load.unwrap_or(var.expr) } } - ExprKind::Call(call) => { - let args: Vec<_> = call - .args - .into_iter() - .map(|e| self.lower(program, e, false, body)) - .collect::>()?; - program.function_call(self, call.kind, &args, body)? + ExprKind::Call(call) if !lhs => { + program.function_call(self, call.kind, call.args, body)? } ExprKind::Conditional { condition, accept, reject, - } => { + } if !lhs => { let condition = self.lower(program, *condition, false, body)?; let accept = self.lower(program, *accept, false, body)?; let reject = self.lower(program, *reject, false, body)?; @@ -409,14 +449,19 @@ impl<'function> Context<'function> { reject, }) } - ExprKind::Assign { tgt, value } => { - let pointer = self.lower(program, *tgt, false, body)?; + ExprKind::Assign { tgt, value } if !lhs => { + let pointer = self.lower(program, *tgt, true, body)?; let value = self.lower(program, *value, false, body)?; body.push(Statement::Store { pointer, value }); value } + _ => { + return Err(ErrorKind::SemanticError( + format!("{:?} cannot be in the left hand side", expr).into(), + )) + } }) } } @@ -427,13 +472,13 @@ pub struct VariableReference { pub load: Option>, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct Expr { pub kind: ExprKind, pub meta: TokenMetadata, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum ExprKind { Access { base: Box, @@ -477,13 +522,13 @@ pub enum TypeQualifier { EarlyFragmentTests, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum FunctionCallKind { TypeConstructor(Handle), Function(String), } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct FunctionCall { pub kind: FunctionCallKind, pub args: Vec, @@ -501,3 +546,21 @@ pub enum StorageQualifier { pub enum StructLayout { Std140, } + +#[derive(Debug, Clone)] +pub enum ParameterQualifier { + In, + Out, + InOut, + Const, +} + +impl ParameterQualifier { + /// Returns true if the argument should be passed as a lhs expression + pub fn is_lhs(&self) -> bool { + match *self { + ParameterQualifier::Out | ParameterQualifier::InOut => true, + _ => false, + } + } +} diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index cfeb0c010..75ff0535a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,7 +1,8 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Binding, Block, BuiltIn, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, MathFunction, - RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, Type, TypeInner, + RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, StorageClass, Type, + TypeInner, }; use super::{ast::*, error::ErrorKind}; @@ -11,9 +12,15 @@ impl Program<'_> { &mut self, ctx: &mut Context, fc: FunctionCallKind, - args: &[Handle], + raw_args: Vec, body: &mut Block, ) -> Result, ErrorKind> { + let args: Vec<_> = raw_args + .clone() + .into_iter() + .map(|e| ctx.lower(self, e, false, body)) + .collect::>()?; + match fc { FunctionCallKind::TypeConstructor(ty) => { let h = if args.len() == 1 { @@ -200,23 +207,43 @@ impl Program<'_> { })) } "isinf" => { - self.parse_relational_fun(ctx, name, args, RelationalFunction::IsInf) + self.parse_relational_fun(ctx, name, &args, RelationalFunction::IsInf) } "isnan" => { - self.parse_relational_fun(ctx, name, args, RelationalFunction::IsNan) + self.parse_relational_fun(ctx, name, &args, RelationalFunction::IsNan) } - "all" => self.parse_relational_fun(ctx, name, args, RelationalFunction::All), - "any" => self.parse_relational_fun(ctx, name, args, RelationalFunction::Any), - func_name => { - let function = *self.lookup_function.get(func_name).ok_or_else(|| { - ErrorKind::SemanticError( - format!("Unknown function: {}", func_name).into(), - ) - })?; - let arguments: Vec<_> = args.to_vec(); - let expression = ctx.expressions.append(Expression::Call(function)); + "all" => self.parse_relational_fun(ctx, name, &args, RelationalFunction::All), + "any" => self.parse_relational_fun(ctx, name, &args, RelationalFunction::Any), + _ => { + let sig = FunctionSignature { + name, + parameters: args + .iter() + .map(|e| self.resolve_handle(ctx, *e)) + .collect::>()?, + }; + + let function = self + .lookup_function + .get(&sig) + .ok_or_else(|| { + ErrorKind::SemanticError( + format!("Unknown function: {:?}", sig).into(), + ) + })? + .clone(); + + let mut arguments = Vec::with_capacity(raw_args.len()); + for (qualifier, expr) in + function.parameters.iter().zip(raw_args.into_iter()) + { + let handle = ctx.lower(self, expr, qualifier.is_lhs(), body)?; + arguments.push(handle) + } + + let expression = ctx.expressions.append(Expression::Call(function.handle)); body.push(crate::Statement::Call { - function, + function: function.handle, arguments, result: Some(expression), }); @@ -244,7 +271,11 @@ impl Program<'_> { })) } - pub fn add_function(&mut self, mut function: Function) -> Result<(), ErrorKind> { + pub fn add_function( + &mut self, + mut function: Function, + parameters: Vec, + ) -> Result<(), ErrorKind> { ensure_block_returns(&mut function.body); let name = function .name @@ -252,17 +283,90 @@ impl Program<'_> { .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; let stage = self.entry_points.get(&name); - let handle = self.module.functions.append(function); - if let Some(&stage) = stage { + let handle = self.module.functions.append(function); self.entries.push((name, stage, handle)); } else { - self.lookup_function.insert(name, handle); + let sig = FunctionSignature { + name, + parameters: function.arguments.iter().map(|p| p.ty).collect(), + }; + + for (arg, qualifier) in function.arguments.iter_mut().zip(parameters.iter()) { + if qualifier.is_lhs() { + arg.ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Pointer { + base: arg.ty, + class: StorageClass::Function, + }, + }) + } + } + + if let Some(decl) = self.lookup_function.get_mut(&sig) { + if decl.defined { + return Err(ErrorKind::SemanticError("Function already defined".into())); + } + + decl.defined = true; + *self.module.functions.get_mut(decl.handle) = function; + } else { + let handle = self.module.functions.append(function); + self.lookup_function.insert( + sig, + FunctionDeclaration { + parameters, + handle, + defined: true, + }, + ); + } } Ok(()) } + pub fn add_prototype( + &mut self, + mut function: Function, + parameters: Vec, + ) -> Result<(), ErrorKind> { + let name = function + .name + .clone() + .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; + let sig = FunctionSignature { + name, + parameters: function.arguments.iter().map(|p| p.ty).collect(), + }; + + for (arg, qualifier) in function.arguments.iter_mut().zip(parameters.iter()) { + if qualifier.is_lhs() { + arg.ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Pointer { + base: arg.ty, + class: StorageClass::Function, + }, + }) + } + } + + let handle = self.module.functions.append(function); + + self.lookup_function.insert( + sig, + FunctionDeclaration { + parameters, + handle, + defined: false, + }, + ); + + Ok(()) + } + pub fn add_entry_points(&mut self) { for (name, stage, function) in self.entries.iter().cloned() { let mut arguments = Vec::new(); diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 590ddd717..d8d0b27f9 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -13,8 +13,6 @@ use ast::Program; mod error; pub use error::ParseError; mod constants; -// TODO: Remove later -#[allow(unused_imports)] mod functions; mod parser; #[cfg(test)] diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index ef2952289..0330d7a80 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,7 +1,7 @@ use super::{ ast::{ - Context, Expr, ExprKind, FunctionCall, FunctionCallKind, Profile, StorageQualifier, - StructLayout, TypeQualifier, + Context, Expr, ExprKind, FunctionCall, FunctionCallKind, ParameterQualifier, Profile, + StorageQualifier, StructLayout, TypeQualifier, }, error::ErrorKind, lex::Lexer, @@ -131,7 +131,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Struct => todo!(), _ => return Err(ErrorKind::InvalidToken(token)), }; - let handle = ty.map(|t| self.program.module.types.append(t)); + let handle = ty.map(|t| self.program.module.types.fetch_or_append(t)); let size = self.parse_array_specifier()?; Ok(handle.map(|ty| self.maybe_array(ty, size))) @@ -144,7 +144,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn maybe_array(&mut self, base: Handle, size: Option) -> Handle { size.map(|size| { - self.program.module.types.append(Type { + self.program.module.types.fetch_or_append(Type { name: None, inner: TypeInner::Array { base, @@ -334,6 +334,28 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }) } + fn peek_parameter_qualifier(&mut self) -> bool { + self.lexer.peek().map_or(false, |t| match t.value { + TokenValue::In | TokenValue::Out | TokenValue::InOut | TokenValue::Const => true, + _ => false, + }) + } + + /// Returns the parsed `ParameterQualifier` or `ParameterQualifier::In` + fn parse_parameter_qualifier(&mut self) -> ParameterQualifier { + if self.peek_parameter_qualifier() { + match self.bump().unwrap().value { + TokenValue::In => ParameterQualifier::In, + TokenValue::Out => ParameterQualifier::Out, + TokenValue::InOut => ParameterQualifier::InOut, + TokenValue::Const => ParameterQualifier::Const, + _ => unreachable!(), + } + } else { + ParameterQualifier::In + } + } + /// `external` whether or not we are in a global or local context fn parse_declaration(&mut self, external: bool) -> Result { //declaration: @@ -364,7 +386,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut expressions = Arena::new(); let mut local_variables = Arena::new(); - let mut arguments = self.program.function_args_prelude(); + let (mut arguments, mut parameters) = + self.program.function_args_prelude(); let mut context = Context::new( &mut expressions, @@ -372,26 +395,43 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { &mut arguments, ); - self.parse_function_args(&mut context)?; + self.parse_function_args(&mut context, &mut parameters)?; self.expect(TokenValue::RightParen)?; let token = self.bump()?; match token.value { // TODO: Function prototypes - TokenValue::Semicolon => todo!(), + TokenValue::Semicolon => { + self.program.add_prototype( + Function { + name: Some(name), + result: ty + .map(|ty| FunctionResult { ty, binding: None }), + arguments, + ..Default::default() + }, + parameters, + )?; + + Ok(true) + } TokenValue::LeftBrace if external => { let mut body = Block::new(); self.parse_compound_statement(&mut context, &mut body)?; - self.program.add_function(Function { - name: Some(name), - result: ty.map(|ty| FunctionResult { ty, binding: None }), - expressions, - local_variables, - arguments, - body, - })?; + self.program.add_function( + Function { + name: Some(name), + result: ty + .map(|ty| FunctionResult { ty, binding: None }), + expressions, + local_variables, + arguments, + body, + }, + parameters, + )?; Ok(true) } @@ -516,7 +556,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let Token { value, mut meta } = self.bump()?; let handle = if let TokenValue::TypeName(ty) = value { - self.program.module.types.append(ty) + self.program.module.types.fetch_or_append(ty) } else { unreachable!() }; @@ -970,10 +1010,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(()) } - fn parse_function_args(&mut self, context: &mut Context) -> Result<()> { + fn parse_function_args( + &mut self, + context: &mut Context, + parameters: &mut Vec, + ) -> Result<()> { loop { - // TODO: parameter qualifier - if self.peek_type_name() { + if self.peek_type_name() || self.peek_parameter_qualifier() { + parameters.push(self.parse_parameter_qualifier()); let ty = self.parse_type_non_void()?; match self.expect_peek()?.value { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 05dc0425f..b0aff34a5 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -231,18 +231,17 @@ fn functions() { let mut entry_points = crate::FastHashMap::default(); entry_points.insert("".to_string(), ShaderStage::Vertex); - // TODO: Add support for function prototypes - // parse_program( - // r#" - // # version 450 - // void test1(float); - // void test1(float) {} + parse_program( + r#" + # version 450 + void test1(float); + void test1(float) {} - // void main() {} - // "#, - // &entry_points, - // ) - // .unwrap(); + void main() {} + "#, + &entry_points, + ) + .unwrap(); parse_program( r#" @@ -278,6 +277,52 @@ fn functions() { &entry_points, ) .unwrap(); + + // Function overloading + parse_program( + r#" + # version 450 + float test(vec2 p); + float test(vec3 p); + float test(vec4 p); + + float test(vec2 p) { + return p.x; + } + + float test(vec3 p) { + return p.x; + } + + float test(vec4 p) { + return p.x; + } + "#, + &entry_points, + ) + .unwrap(); + + assert_eq!( + format!( + "{:?}", + parse_program( + r#" + # version 450 + int test(vec4 p) { + return p.x; + } + + float test(vec4 p) { + return p.x; + } + "#, + &entry_points + ) + .err() + .unwrap() + ), + "SemanticError(\"Function already defined\")" + ); } #[test] diff --git a/src/front/mod.rs b/src/front/mod.rs index aa39bc259..72242bbc7 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -69,6 +69,30 @@ impl Typifier { self.resolutions[expr_handle.index()].inner_with(types) } + pub fn get_handle( + &mut self, + expr_handle: Handle, + types: &mut Arena, + ) -> Handle { + let mut dummy = TypeResolution::Value(crate::TypeInner::Sampler { comparison: false }); + let res = &mut self.resolutions[expr_handle.index()]; + + std::mem::swap(&mut dummy, res); + + let v = match dummy { + TypeResolution::Handle(h) => h, + TypeResolution::Value(inner) => { + let h = types.fetch_or_append(crate::Type { name: None, inner }); + dummy = TypeResolution::Handle(h); + h + } + }; + + std::mem::swap(&mut dummy, res); + + v + } + pub fn grow( &mut self, expr_handle: Handle, From 168a55396c1a228542501fe3a5d6803d98a93cfe Mon Sep 17 00:00:00 2001 From: Imbris Date: Sun, 9 May 2021 00:59:58 -0400 Subject: [PATCH 0852/2212] [glsl-in] Add full init_declarator_list support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: João Capucho --- src/front/glsl/ast.rs | 2 +- src/front/glsl/parser.rs | 228 +++++++++++++++++++++++++++++---- src/front/glsl/parser_tests.rs | 77 ++++------- src/front/glsl/variables.rs | 112 +++++++++++----- 4 files changed, 310 insertions(+), 109 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 8d98970c8..017690f6f 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -542,7 +542,7 @@ pub enum StorageQualifier { Const, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Copy)] pub enum StructLayout { Std140, } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0330d7a80..4c06dbfb9 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -110,6 +110,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(()) } + /// Parses an optional array_specifier returning `Ok(None)` if there is no + /// LeftBracket fn parse_array_specifier(&mut self) -> Result> { // TODO: expressions if let Some(&TokenValue::LeftBracket) = self.lexer.peek().map(|t| &t.value) { @@ -315,7 +317,20 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } fn parse_external_declaration(&mut self) -> Result<()> { - if !self.parse_declaration(true)? { + // TODO: Create body and expressions arena to be used in all entry + // points to handle this case + // ```glsl + // // This is valid and the body of main will contain the assignment + // float b; + // float a = b = 1; + // + // void main() {} + // ``` + let (mut e, mut l, mut a) = (Arena::new(), Arena::new(), Vec::new()); + let mut ctx = Context::new(&mut e, &mut l, &mut a); + let mut body = Block::new(); + + if !self.parse_declaration(&mut ctx, &mut body, true)? { let token = self.bump()?; match token.value { TokenValue::Semicolon if self.program.version == 460 => Ok(()), @@ -356,12 +371,147 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } + fn parse_initializer( + &mut self, + ty: Handle, + ctx: &mut Context, + body: &mut Block, + ) -> Result> { + // initializer: + // assignment_expression + // LEFT_BRACE initializer_list RIGHT_BRACE + // LEFT_BRACE initializer_list COMMA RIGHT_BRACE + // + // initializer_list: + // initializer + // initializer_list COMMA initializer + if self.bump_if(TokenValue::LeftBrace).is_some() { + // initializer_list + let mut components = Vec::new(); + loop { + // TODO: Change type + components.push(self.parse_initializer(ty, ctx, body)?); + + let token = self.bump()?; + match token.value { + TokenValue::Comma => { + if self.bump_if(TokenValue::RightBrace).is_some() { + break; + } + } + TokenValue::RightBrace => break, + _ => return Err(ErrorKind::InvalidToken(token)), + } + } + + Ok(ctx + .expressions + .append(Expression::Compose { ty, components })) + } else { + let expr = self.parse_assignment(ctx)?; + let root = ctx.lower(self.program, expr, false, body)?; + + Ok(root) + } + } + + // Note: caller preparsed the type and qualifiers + // Note: caller skips this if the fallthrough token is not expected to be consumed here so this + // produced Error::InvalidToken if it isn't consumed + fn parse_init_declarator_list( + &mut self, + ty: Handle, + mut fallthrough: Option, + ctx: &mut DeclarationContext, + ) -> Result<()> { + // init_declarator_list: + // single_declaration + // init_declarator_list COMMA IDENTIFIER + // init_declarator_list COMMA IDENTIFIER array_specifier + // init_declarator_list COMMA IDENTIFIER array_specifier EQUAL initializer + // init_declarator_list COMMA IDENTIFIER EQUAL initializer + // + // single_declaration: + // fully_specified_type + // fully_specified_type IDENTIFIER + // fully_specified_type IDENTIFIER array_specifier + // fully_specified_type IDENTIFIER array_specifier EQUAL initializer + // fully_specified_type IDENTIFIER EQUAL initializer + + // Consume any leading comma, e.g. this is valid: `float, a=1;` + if fallthrough + .as_ref() + .or_else(|| self.lexer.peek()) + .filter(|t| t.value == TokenValue::Comma) + .is_some() + { + fallthrough.take().or_else(|| self.lexer.next()); + } + + loop { + let token = fallthrough + .take() + .ok_or(ErrorKind::EndOfFile) + .or_else(|_| self.bump())?; + let name = match token.value { + TokenValue::Semicolon => break, + TokenValue::Identifier(name) => name, + _ => return Err(ErrorKind::InvalidToken(token)), + }; + + // array_specifier + // array_specifier EQUAL initializer + // EQUAL initializer + + // parse an array specifier if it exists + // NOTE: unlike other parse methods this one doesn't expect an array specifier and + // returns Ok(None) rather than an error if there is not one + let array_specifier = self.parse_array_specifier()?; + let ty = self.maybe_array(ty, array_specifier); + + let init = self + .bump_if(TokenValue::Assign) + .map(|_| self.parse_initializer(ty, ctx.ctx, ctx.body)) + .transpose()?; + + let pointer = ctx.add_var( + ty, + name, + // TODO: Should we try to make constants here? + // This is mostly a hack because we don't yet support adding + // bodies to entry points for variable initialization + init.and_then(|root| self.program.solve_constant(ctx.ctx.expressions, root).ok()), + self.program, + )?; + + if let Some(value) = init { + ctx.body.push(Statement::Store { pointer, value }); + } + + let token = self.bump()?; + match token.value { + TokenValue::Semicolon => break, + TokenValue::Comma => {} + _ => return Err(ErrorKind::InvalidToken(token)), + } + } + + Ok(()) + } + /// `external` whether or not we are in a global or local context - fn parse_declaration(&mut self, external: bool) -> Result { + fn parse_declaration( + &mut self, + ctx: &mut Context, + body: &mut Block, + external: bool, + ) -> Result { //declaration: // function_prototype SEMICOLON + // // init_declarator_list SEMICOLON // PRECISION precision_qualifier type_specifier SEMICOLON + // // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE SEMICOLON // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER array_specifier SEMICOLON @@ -377,8 +527,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let token = self.bump()?; - match token.value { - TokenValue::Semicolon => Ok(true), + let token_fallthrough = match token.value { TokenValue::Identifier(name) => match self.expect_peek()?.value { // Function definition/prototype TokenValue::LeftParen => { @@ -400,7 +549,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::RightParen)?; let token = self.bump()?; - match token.value { + return match token.value { // TODO: Function prototypes TokenValue::Semicolon => { self.program.add_prototype( @@ -436,31 +585,33 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(true) } _ => Err(ErrorKind::InvalidToken(token)), - } + }; } - // Variable Declaration - TokenValue::Semicolon => { - self.bump()?; - - if let Some(ty) = ty { - if external { - self.program.add_global_var(qualifiers, ty, name, None)?; - } else { - // TODO: local variables - } - } else { - return Err(ErrorKind::SemanticError( - "Declaration cannot have void type".into(), - )); - } - - Ok(true) - } - TokenValue::Comma => todo!(), - _ => Err(ErrorKind::InvalidToken(self.bump()?)), + _ => Token { + value: TokenValue::Identifier(name), + meta: token.meta, + }, }, - _ => Err(ErrorKind::InvalidToken(token)), + _ => token, + }; + + // Variable Declaration + if let Some(ty) = ty { + let mut ctx = DeclarationContext { + qualifiers, + external, + ctx, + body, + }; + + self.parse_init_declarator_list(ty, Some(token_fallthrough), &mut ctx)?; + } else { + return Err(ErrorKind::SemanticError( + "Declaration cannot have void type".into(), + )); } + + Ok(true) } else { // Structs and modifiers let token = self.bump()?; @@ -1051,6 +1202,29 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } +struct DeclarationContext<'ctx, 'fun> { + qualifiers: Vec, + external: bool, + + ctx: &'ctx mut Context<'fun>, + body: &'ctx mut Block, +} + +impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { + fn add_var( + &mut self, + ty: Handle, + name: String, + init: Option>, + program: &mut Program, + ) -> Result> { + match self.external { + true => program.add_global_var(self.ctx, &self.qualifiers, ty, name, init), + false => program.add_local_var(self.ctx, &self.qualifiers, ty, name, init), + } + } +} + fn binding_power(value: &TokenValue) -> Option<(u8, u8)> { Some(match *value { TokenValue::LogicalOr => (1, 2), diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index b0aff34a5..b0b6a18b2 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -327,60 +327,35 @@ fn functions() { #[test] fn constants() { - // TODO: Reenable tests later - // use crate::{Constant, ConstantInner, ScalarValue}; + use crate::{Constant, ConstantInner, ScalarValue}; - // let mut entry_points = crate::FastHashMap::default(); - // entry_points.insert("".to_string(), ShaderStage::Vertex); + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Vertex); - // let program = parse_program( - // r#" - // # version 450 - // const float a = 1.0; - // float global = a; - // const flat float b = a; - // "#, - // &entry_points, - // ) - // .unwrap(); + let program = parse_program( + r#" + # version 450 + const float a = 1.0; + float global = a; + const float b = a; + "#, + &entry_points, + ) + .unwrap(); - // let mut constants = program.module.constants.iter(); + let mut constants = program.module.constants.iter(); - // assert_eq!( - // constants.next().unwrap().1, - // &Constant { - // name: None, - // specialization: None, - // inner: ConstantInner::Scalar { - // width: 4, - // value: ScalarValue::Float(1.0) - // } - // } - // ); + assert_eq!( + constants.next().unwrap().1, + &Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(1.0) + } + } + ); - // assert_eq!( - // constants.next().unwrap().1, - // &Constant { - // name: Some(String::from("a")), - // specialization: None, - // inner: ConstantInner::Scalar { - // width: 4, - // value: ScalarValue::Float(1.0) - // } - // } - // ); - - // assert_eq!( - // constants.next().unwrap().1, - // &Constant { - // name: Some(String::from("b")), - // specialization: None, - // inner: ConstantInner::Scalar { - // width: 4, - // value: ScalarValue::Float(1.0) - // } - // } - // ); - - // assert!(constants.next().is_none()); + assert!(constants.next().is_none()); } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 6d6ec4b44..cfbd766e8 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,6 +1,6 @@ use crate::{ - Binding, BuiltIn, Constant, Expression, GlobalVariable, Handle, ScalarKind, StorageAccess, - StorageClass, StructMember, Type, TypeInner, VectorSize, + Binding, BuiltIn, Constant, Expression, GlobalVariable, Handle, LocalVariable, ScalarKind, + StorageAccess, StorageClass, StructMember, Type, TypeInner, VectorSize, }; use super::ast::*; @@ -19,7 +19,7 @@ impl Program<'_> { if let Some(global_var) = context.lookup_global_var(self, name) { return Ok(Some(global_var)); } - if let Some(constant) = context.lookup_global_var(self, name) { + if let Some(constant) = context.lookup_constants_var(self, name) { return Ok(Some(constant)); } match name { @@ -195,14 +195,14 @@ impl Program<'_> { } } - // TODO: constants pub fn add_global_var( &mut self, - qualifiers: Vec, + ctx: &mut Context, + qualifiers: &[TypeQualifier], ty: Handle, name: String, init: Option>, - ) -> Result<(), ErrorKind> { + ) -> Result, ErrorKind> { let mut storage = StorageQualifier::StorageClass(StorageClass::Function); let mut interpolation = None; let mut binding = None; @@ -211,7 +211,7 @@ impl Program<'_> { let mut layout = None; for qualifier in qualifiers { - match qualifier { + match *qualifier { TypeQualifier::StorageQualifier(s) => { if StorageQualifier::StorageClass(StorageClass::Function) != storage { return Err(ErrorKind::SemanticError( @@ -230,14 +230,14 @@ impl Program<'_> { interpolation = Some(i); } - TypeQualifier::ResourceBinding(r) => { + TypeQualifier::ResourceBinding(ref r) => { if binding.is_some() { return Err(ErrorKind::SemanticError( "Cannot use more than one storage qualifier per declaration".into(), )); } - binding = Some(r); + binding = Some(r.clone()); } TypeQualifier::Location(l) => { if location.is_some() { @@ -257,7 +257,7 @@ impl Program<'_> { sampling = Some(s); } - TypeQualifier::Layout(l) => { + TypeQualifier::Layout(ref l) => { if layout.is_some() { return Err(ErrorKind::SemanticError( "Cannot use more than one storage qualifier per declaration".into(), @@ -300,26 +300,78 @@ impl Program<'_> { }), ); - if let Some(i) = index { - self.lookup_global_variables - .insert(name, GlobalLookup::Select(i)); - } - } else if let StorageQualifier::StorageClass(class) = storage { - let handle = self.module.global_variables.append(GlobalVariable { - name: Some(name.clone()), - class, - binding, - ty, - init, - // TODO - storage_access: StorageAccess::all(), - }); - self.lookup_global_variables - .insert(name, GlobalLookup::Variable(handle)); + .insert(name, GlobalLookup::Select(index)); + + let base = ctx.expressions.append(Expression::FunctionArgument(0)); + return Ok(ctx + .expressions + .append(Expression::AccessIndex { base, index })); + } else if let StorageQualifier::Const = storage { + let handle = init.ok_or_else(|| { + ErrorKind::SemanticError("Constant must have a initializer".into()) + })?; + + self.lookup_constants.insert(name, handle); + + return Ok(ctx.expressions.append(Expression::Constant(handle))); } - Ok(()) + let class = match storage { + StorageQualifier::StorageClass(class) => class, + _ => StorageClass::Function, + }; + + let handle = self.module.global_variables.append(GlobalVariable { + name: Some(name.clone()), + class, + binding, + ty, + init, + // TODO + storage_access: StorageAccess::all(), + }); + + self.lookup_global_variables + .insert(name, GlobalLookup::Variable(handle)); + + Ok(ctx.expressions.append(Expression::GlobalVariable(handle))) + } + + pub fn add_local_var( + &mut self, + ctx: &mut Context, + qualifiers: &[TypeQualifier], + ty: Handle, + name: String, + init: Option>, + ) -> Result, ErrorKind> { + // FIXME: this should be removed after + // fixing the lack of constant qualifier support + #[allow(clippy::never_loop)] + for qualifier in qualifiers { + match *qualifier { + TypeQualifier::StorageQualifier(StorageQualifier::Const) => { + return Err(ErrorKind::NotImplemented("const qualifier")); + } + _ => { + return Err(ErrorKind::SemanticError( + "Qualifier not supported in locals".into(), + )); + } + } + } + + let handle = ctx.locals.append(LocalVariable { + name: Some(name.clone()), + ty, + init, + }); + let expr = ctx.expressions.append(Expression::LocalVariable(handle)); + + ctx.add_local_var(name, expr); + + Ok(expr) } fn add_member( @@ -328,7 +380,7 @@ impl Program<'_> { name: Option, ty: Handle, binding: Option, - ) -> Option { + ) -> u32 { let handle = match input { true => self.input_struct, false => self.output_struct, @@ -360,9 +412,9 @@ impl Program<'_> { offset, }); - Some(members.len() as u32 - 1) + members.len() as u32 - 1 } else { - None + unreachable!() } } } From fec67ced8e2b8737f71893669854c5b58160e7d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 14 May 2021 13:19:35 +0100 Subject: [PATCH 0853/2212] [glsl-in] Add support for declaration statements --- src/front/glsl/parser.rs | 14 ++++++++++++-- src/front/glsl/parser_tests.rs | 8 +++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 4c06dbfb9..18c9bfcb8 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1130,20 +1130,30 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ctx.remove_current_scope(); body.push(Statement::Block(block)); } + // TODO: We should also add TypeName here because this is valid + // ```glsl + // vec4(1.0); + // ``` + // But this would require us to add lookahead to also support + // declarations and since this statement is very unlikely and most + // likely an error, for now we don't support it TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde | TokenValue::LeftParen | TokenValue::Identifier(_) - | TokenValue::TypeName(_) | TokenValue::IntConstant(_) | TokenValue::BoolConstant(_) | TokenValue::FloatConstant(_) => { self.parse_expression(ctx)?; self.expect(TokenValue::Semicolon)?; } - _ => {} + _ => { + if self.peek_type_name() || self.peek_type_qualifier() { + self.parse_declaration(ctx, body, false)?; + } + } } Ok(()) diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index b0b6a18b2..b3b1f32e6 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -116,10 +116,9 @@ fn control_flow() { let _program = parse_program( r#" # version 450 - int x; - int y; - void main() { + int x; + int y = 3; switch (5) { case 2: x = 2; @@ -138,9 +137,8 @@ fn control_flow() { let _program = parse_program( r#" # version 450 - int x; - void main() { + int x = 0; while(x < 5) { x = x + 1; } From 565c27292a8d8a89c27575ca26ed2c875053b725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 14 May 2021 13:40:14 +0100 Subject: [PATCH 0854/2212] [glsl-in] Cleanup parse_declaration --- src/front/glsl/parser.rs | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 18c9bfcb8..98a6c8ef3 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -339,7 +339,6 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } else { Ok(()) } - // TODO } fn peek_type_name(&mut self) -> bool { @@ -517,22 +516,23 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER array_specifier SEMICOLON // type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON - // TODO: Handle precision qualifiers + if self.peek_type_qualifier() || self.peek_type_name() { let qualifiers = self.parse_type_qualifiers()?; if self.peek_type_name() { - // Functions and variable declarations + // This branch handles variables and function prototypes and if + // external is true also function definitions let ty = self.parse_type()?; let token = self.bump()?; - let token_fallthrough = match token.value { TokenValue::Identifier(name) => match self.expect_peek()?.value { - // Function definition/prototype TokenValue::LeftParen => { + // This branch handles function definition and prototypes self.bump()?; + let result = ty.map(|ty| FunctionResult { ty, binding: None }); let mut expressions = Arena::new(); let mut local_variables = Arena::new(); let (mut arguments, mut parameters) = @@ -550,13 +550,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let token = self.bump()?; return match token.value { - // TODO: Function prototypes TokenValue::Semicolon => { + // This branch handles function prototypes self.program.add_prototype( Function { name: Some(name), - result: ty - .map(|ty| FunctionResult { ty, binding: None }), + result, arguments, ..Default::default() }, @@ -566,14 +565,17 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(true) } TokenValue::LeftBrace if external => { + // This branch handles function definitions + // as you can see by the guard this branch + // only happens if external is also true let mut body = Block::new(); + // parse the body self.parse_compound_statement(&mut context, &mut body)?; self.program.add_function( Function { name: Some(name), - result: ty - .map(|ty| FunctionResult { ty, binding: None }), + result, expressions, local_variables, arguments, @@ -587,15 +589,19 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { _ => Err(ErrorKind::InvalidToken(token)), }; } + // Pass the token to the init_declator_list parser _ => Token { value: TokenValue::Identifier(name), meta: token.meta, }, }, + // Pass the token to the init_declator_list parser _ => token, }; - // Variable Declaration + // If program execution has reached here then this will be a + // init_declarator_list + // token_falltrough will have a token that was already bumped if let Some(ty) = ty { let mut ctx = DeclarationContext { qualifiers, @@ -613,7 +619,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(true) } else { - // Structs and modifiers + // This branch handles struct definitions and modifiers like + // ```glsl + // layout(early_fragment_tests); + // ``` let token = self.bump()?; match token.value { TokenValue::Identifier(_) => todo!(), @@ -622,6 +631,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } } else { + // TODO: Handle precision qualifiers Ok(false) } } From 7165a06fbfbba9b0b1b2776d8bbb5ee80e9e6d03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 14 May 2021 13:49:56 +0100 Subject: [PATCH 0855/2212] [glsl-in] Add glsl-validate and sampling qualifier --- src/front/glsl/ast.rs | 6 +----- src/front/glsl/mod.rs | 2 -- src/front/glsl/parser.rs | 2 ++ src/front/glsl/variables.rs | 5 +++++ 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 017690f6f..94ef4c173 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -163,6 +163,7 @@ impl<'a> Program<'a> { ) } + #[allow(dead_code)] // FIXME: Remove after implementing structs pub fn type_size(&self, ty: Handle) -> Result { Ok(match self.module.types[ty].inner { crate::TypeInner::Scalar { width, .. } => width, @@ -310,11 +311,6 @@ impl<'function> Context<'function> { } } - pub fn clear_scopes(&mut self) { - self.scopes.clear(); - self.scopes.push(FastHashMap::default()); - } - /// Add variable to current scope pub fn add_local_var(&mut self, name: String, expr: Handle) { if let Some(current) = self.scopes.last_mut() { diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index d8d0b27f9..e03d61109 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -5,8 +5,6 @@ use crate::{FastHashMap, Module, ShaderStage}; mod lex; -// TODO: Remove later -#[allow(dead_code)] mod ast; use ast::Program; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 98a6c8ef3..eabcaaa26 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -163,6 +163,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn peek_type_qualifier(&mut self) -> bool { self.lexer.peek().map_or(false, |t| match t.value { TokenValue::Interpolation(_) + | TokenValue::Sampling(_) | TokenValue::Const | TokenValue::In | TokenValue::Out @@ -192,6 +193,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Uniform => TypeQualifier::StorageQualifier( StorageQualifier::StorageClass(StorageClass::Uniform), ), + TokenValue::Sampling(s) => TypeQualifier::Sampling(s), _ => unreachable!(), }) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index cfbd766e8..6b629aed3 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -346,6 +346,11 @@ impl Program<'_> { name: String, init: Option>, ) -> Result, ErrorKind> { + #[cfg(feature = "glsl-validate")] + if ctx.lookup_local_var_current_scope(&name).is_some() { + return Err(ErrorKind::VariableAlreadyDeclared(name)); + } + // FIXME: this should be removed after // fixing the lack of constant qualifier support #[allow(clippy::never_loop)] From 14f2caf6b02abc4ede2490dabc02b4d82744975a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 14 May 2021 17:18:47 +0100 Subject: [PATCH 0856/2212] [glsl-in] for loops --- src/front/glsl/parser.rs | 74 ++++++++++++++++++++++++++++++++++ src/front/glsl/parser_tests.rs | 30 +++++++------- 2 files changed, 89 insertions(+), 15 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index eabcaaa26..28b1540d2 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -896,6 +896,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let pointer = self.parse_unary(ctx)?; let start_meta = pointer.meta.clone(); + // TODO: More assign symbols if self.bump_if(TokenValue::Assign).is_some() { let value = Box::new(self.parse_assignment(ctx)?); let end_meta = value.meta.clone(); @@ -1131,6 +1132,76 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { continuing: Block::new(), }) } + TokenValue::For => { + self.bump()?; + + ctx.push_scope(); + self.expect(TokenValue::LeftParen)?; + + if self.bump_if(TokenValue::Semicolon).is_none() { + if self.peek_type_name() || self.peek_type_qualifier() { + self.parse_declaration(ctx, body, false)?; + } else { + self.parse_expression(ctx)?; + self.expect(TokenValue::Semicolon)?; + } + } + + let (mut block, mut continuing) = (Block::new(), Block::new()); + + if self.bump_if(TokenValue::Semicolon).is_none() { + let expr = if self.peek_type_name() || self.peek_type_qualifier() { + let qualifiers = self.parse_type_qualifiers()?; + let ty = self.parse_type_non_void()?; + let name = self.expect_ident()?.0; + + self.expect(TokenValue::Assign)?; + + let value = self.parse_initializer(ty, ctx, &mut block)?; + + let pointer = + self.program + .add_local_var(ctx, &qualifiers, ty, name, None)?; + + block.push(Statement::Store { pointer, value }); + + value + } else { + let root = self.parse_expression(ctx)?; + ctx.lower(self.program, root, false, &mut block)? + }; + + body.push(Statement::If { + condition: ctx.expressions.append(Expression::Unary { + op: UnaryOperator::Not, + expr, + }), + accept: vec![Statement::Break], + reject: Block::new(), + }); + + self.expect(TokenValue::Semicolon)?; + } + + match self.expect_peek()?.value { + TokenValue::RightParen => {} + _ => { + let rest = self.parse_expression(ctx)?; + ctx.lower(self.program, rest, false, &mut &mut continuing)?; + } + } + + self.expect(TokenValue::RightParen)?; + + self.parse_statement(ctx, &mut block)?; + + body.push(Statement::Loop { + body: block, + continuing, + }); + + ctx.remove_current_scope(); + } TokenValue::LeftBrace => { self.bump()?; @@ -1161,6 +1232,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.parse_expression(ctx)?; self.expect(TokenValue::Semicolon)?; } + TokenValue::Semicolon => { + self.bump()?; + } _ => { if self.peek_type_name() || self.peek_type_qualifier() { self.parse_declaration(ctx, body, false)?; diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index b3b1f32e6..4f74348bf 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -151,21 +151,21 @@ fn control_flow() { ) .unwrap(); - // TODO: Reenable later - // let _program = parse_program( - // r#" - // # version 450 - // void main() { - // int x = 0; - // for(int i = 0; i < 10;) { - // x = x + 2; - // } - // return x; - // } - // "#, - // &entry_points, - // ) - // .unwrap(); + let _program = parse_program( + r#" + # version 450 + void main() { + int x = 0; + for(int i = 0; i < 10;) { + x = x + 2; + } + for(;;); + return x; + } + "#, + &entry_points, + ) + .unwrap(); } #[test] From 4e40a75843fc1d16d19441b7c53f9619d176dadb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 14 May 2021 19:18:01 +0100 Subject: [PATCH 0857/2212] [glsl-in] block declarations --- src/front/glsl/ast.rs | 64 +++---------- src/front/glsl/parser.rs | 160 +++++++++++++++++++++++++++++++-- src/front/glsl/parser_tests.rs | 45 +++++++--- src/front/glsl/variables.rs | 2 +- 4 files changed, 199 insertions(+), 72 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 94ef4c173..453c31a41 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,15 +1,16 @@ use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind, TokenMetadata}; use crate::{ - proc::ResolveContext, Arena, ArraySize, BinaryOperator, Block, BuiltIn, Constant, Expression, - FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, - Module, RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, - Type, TypeInner, UnaryOperator, + proc::ResolveContext, Arena, BinaryOperator, Block, BuiltIn, Constant, Expression, FastHashMap, + Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, + RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, + TypeInner, UnaryOperator, }; #[derive(Debug)] pub enum GlobalLookup { Variable(Handle), - Select(u32), + InOutSelect(u32), + BlockSelect(Handle, u32), } #[derive(Debug, PartialEq, Eq, Hash)] @@ -162,52 +163,6 @@ impl<'a> Program<'a> { vec![ParameterQualifier::In], ) } - - #[allow(dead_code)] // FIXME: Remove after implementing structs - pub fn type_size(&self, ty: Handle) -> Result { - Ok(match self.module.types[ty].inner { - crate::TypeInner::Scalar { width, .. } => width, - crate::TypeInner::Vector { size, width, .. } => size as u8 * width, - crate::TypeInner::Matrix { - columns, - rows, - width, - } => columns as u8 * rows as u8 * width, - crate::TypeInner::Pointer { .. } => { - return Err(ErrorKind::NotImplemented("type size of pointer")) - } - crate::TypeInner::ValuePointer { .. } => { - return Err(ErrorKind::NotImplemented("type size of value pointer")) - } - crate::TypeInner::Array { size, stride, .. } => { - stride as u8 - * match size { - ArraySize::Dynamic => { - return Err(ErrorKind::NotImplemented("type size of dynamic array")) - } - ArraySize::Constant(constant) => { - match self.module.constants[constant].inner { - crate::ConstantInner::Scalar { width, .. } => width, - crate::ConstantInner::Composite { .. } => { - return Err(ErrorKind::NotImplemented( - "type size of array with composite item size", - )) - } - } - } - } - } - crate::TypeInner::Struct { .. } => { - return Err(ErrorKind::NotImplemented("type size of struct")) - } - crate::TypeInner::Image { .. } => { - return Err(ErrorKind::NotImplemented("type size of image")) - } - crate::TypeInner::Sampler { .. } => { - return Err(ErrorKind::NotImplemented("type size of sampler")) - } - }) - } } #[derive(Debug)] @@ -265,9 +220,14 @@ impl<'function> Context<'function> { self.lookup_global_var_exps.get(name).cloned().or_else(|| { let expr = match *program.lookup_global_variables.get(name)? { GlobalLookup::Variable(v) => Expression::GlobalVariable(v), - GlobalLookup::Select(index) => { + GlobalLookup::InOutSelect(index) => { let base = self.expressions.append(Expression::FunctionArgument(0)); + Expression::AccessIndex { base, index } + } + GlobalLookup::BlockSelect(handle, index) => { + let base = self.expressions.append(Expression::GlobalVariable(handle)); + Expression::AccessIndex { base, index } } }; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 28b1540d2..22275873d 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,7 +1,7 @@ use super::{ ast::{ - Context, Expr, ExprKind, FunctionCall, FunctionCallKind, ParameterQualifier, Profile, - StorageQualifier, StructLayout, TypeQualifier, + Context, Expr, ExprKind, FunctionCall, FunctionCallKind, GlobalLookup, ParameterQualifier, + Profile, StorageQualifier, StructLayout, TypeQualifier, }, error::ErrorKind, lex::Lexer, @@ -10,8 +10,8 @@ use super::{ }; use crate::{ arena::Handle, Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Expression, - Function, FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, SwitchCase, - Type, TypeInner, UnaryOperator, + Function, FunctionResult, GlobalVariable, ResourceBinding, ScalarValue, Statement, + StorageAccess, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, }; use core::convert::TryFrom; use std::{iter::Peekable, mem}; @@ -627,7 +627,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // ``` let token = self.bump()?; match token.value { - TokenValue::Identifier(_) => todo!(), + TokenValue::Identifier(ty_name) => { + if self.bump_if(TokenValue::LeftBrace).is_some() { + self.parse_block_declaration(&qualifiers, ty_name) + } else { + //TODO: declaration + // type_qualifier IDENTIFIER SEMICOLON + // type_qualifier IDENTIFIER identifier_list SEMICOLON + todo!() + } + } TokenValue::Semicolon => Ok(true), _ => Err(ErrorKind::InvalidToken(token)), } @@ -638,6 +647,147 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } + fn parse_block_declaration( + &mut self, + qualifiers: &[TypeQualifier], + ty_name: String, + ) -> Result { + let mut class = StorageClass::Function; + let mut binding = None; + let mut layout = None; + + for qualifier in qualifiers { + match *qualifier { + TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { + if StorageClass::Function != class { + return Err(ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + )); + } + + class = c; + } + TypeQualifier::ResourceBinding(ref r) => { + if binding.is_some() { + return Err(ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + )); + } + + binding = Some(r.clone()); + } + TypeQualifier::Layout(ref l) => { + if layout.is_some() { + return Err(ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + )); + } + + layout = Some(l); + } + _ => { + return Err(ErrorKind::SemanticError( + "Qualifier not supported in block declarations".into(), + )); + } + } + } + + let mut members = Vec::new(); + let span = self.parse_struct_declaration_list(&mut members)?; + self.expect(TokenValue::RightBrace)?; + + let mut ty = self.program.module.types.append(Type { + name: Some(ty_name), + inner: TypeInner::Struct { + top_level: true, + members: members.clone(), + span, + }, + }); + + let token = self.bump()?; + let name = match token.value { + TokenValue::Semicolon => None, + TokenValue::Identifier(name) => { + if let Some(size) = self.parse_array_specifier()? { + ty = self.program.module.types.append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size, + stride: self.program.module.types[ty] + .inner + .span(&self.program.module.constants), + }, + }); + } + + self.expect(TokenValue::Semicolon)?; + + Some(name) + } + _ => return Err(ErrorKind::InvalidToken(token)), + }; + + let handle = self.program.module.global_variables.append(GlobalVariable { + name: name.clone(), + class, + binding, + ty, + init: None, + // TODO + storage_access: StorageAccess::all(), + }); + + if let Some(k) = name { + self.program + .lookup_global_variables + .insert(k, GlobalLookup::Variable(handle)); + } + + for (i, k) in members + .into_iter() + .enumerate() + .filter_map(|(i, m)| m.name.map(|s| (i as u32, s))) + { + self.program + .lookup_global_variables + .insert(k, GlobalLookup::BlockSelect(handle, i)); + } + + Ok(true) + } + + // TODO: Accept layout arguments + fn parse_struct_declaration_list(&mut self, members: &mut Vec) -> Result { + let mut span = 0; + + loop { + // TODO: type_qualifier + if !self.peek_type_name() { + break; + } + + let ty = self.parse_type_non_void()?; + let name = self.expect_ident()?.0; + self.expect(TokenValue::Semicolon)?; + + members.push(StructMember { + name: Some(name), + ty, + binding: None, + offset: span, + }); + + span = self.program.module.types[ty] + .inner + .span(&self.program.module.constants); + } + + Ok(span) + } + fn parse_primary(&mut self, ctx: &mut Context) -> Result { let mut token = self.bump()?; diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 4f74348bf..a9e22fa7c 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -187,20 +187,37 @@ fn declarations() { ) .unwrap(); - // TODO: Reenable tests later - // let _program = parse_program( - // r#" - // #version 450 - // layout(std140, set = 2, binding = 0) - // uniform u_locals { - // vec3 model_offs; - // float load_time; - // ivec4 atlas_offs; - // }; - // "#, - // &entry_points, - // ) - // .unwrap(); + let _program = parse_program( + r#" + #version 450 + layout(std140, set = 2, binding = 0) + uniform u_locals { + vec3 model_offs; + float load_time; + ivec4 atlas_offs; + }; + "#, + &entry_points, + ) + .unwrap(); + + let _program = parse_program( + r#" + #version 450 + layout(std140, set = 2, binding = 0) + uniform u_locals { + vec3 model_offs; + float load_time; + } block_var; + + void main() { + load_time * model_offs; + block_var.load_time * block_var.model_offs; + } + "#, + &entry_points, + ) + .unwrap(); } #[test] diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 6b629aed3..12def0422 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -301,7 +301,7 @@ impl Program<'_> { ); self.lookup_global_variables - .insert(name, GlobalLookup::Select(index)); + .insert(name, GlobalLookup::InOutSelect(index)); let base = ctx.expressions.append(Expression::FunctionArgument(0)); return Ok(ctx From d310cff591e39a209a7ccefa57c0dfbb9c19446d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 14 May 2021 22:19:56 +0100 Subject: [PATCH 0858/2212] [glsl-in] Fix parsing of function calls --- src/front/glsl/parser.rs | 52 +++++++++++++++++++--------------- src/front/glsl/parser_tests.rs | 26 +++++++++++++++++ 2 files changed, 55 insertions(+), 23 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 22275873d..fdebe6e24 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -828,23 +828,40 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }) } + fn parse_function_call_args( + &mut self, + ctx: &mut Context, + meta: &mut TokenMetadata, + ) -> Result> { + let mut args = Vec::new(); + if let Some(token) = self.bump_if(TokenValue::RightParen) { + *meta = meta.union(&token.meta); + } else { + loop { + args.push(self.parse_assignment(ctx)?); + + let token = self.bump()?; + match token.value { + TokenValue::Comma => {} + TokenValue::RightParen => { + *meta = meta.union(&token.meta); + break; + } + _ => return Err(ErrorKind::InvalidToken(token)), + } + } + } + + Ok(args) + } + fn parse_postfix(&mut self, ctx: &mut Context) -> Result { let mut expr = match self.expect_peek()?.value { TokenValue::Identifier(_) => { let (name, mut meta) = self.expect_ident()?; if self.bump_if(TokenValue::LeftParen).is_some() { - let mut args = Vec::new(); - loop { - let token = self.bump()?; - - if let TokenValue::RightParen = token.value { - meta = meta.union(&token.meta); - break; - } - - args.push(self.parse_expression(ctx)?) - } + let args = self.parse_function_call_args(ctx, &mut meta)?; Expr { kind: ExprKind::Call(FunctionCall { @@ -875,18 +892,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }; self.expect(TokenValue::LeftParen)?; - - let mut args = Vec::new(); - loop { - let token = self.bump()?; - - if let TokenValue::RightParen = token.value { - meta = meta.union(&token.meta); - break; - } - - args.push(self.parse_expression(ctx)?) - } + let args = self.parse_function_call_args(ctx, &mut meta)?; Expr { kind: ExprKind::Call(FunctionCall { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index a9e22fa7c..6166c1c9c 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -218,6 +218,15 @@ fn declarations() { &entry_points, ) .unwrap(); + + let _program = parse_program( + r#" + #version 450 + float vector = vec4(1.0 / 17.0, 9.0 / 17.0, 3.0 / 17.0, 11.0 / 17.0); + "#, + &entry_points, + ) + .unwrap(); } #[test] @@ -338,6 +347,23 @@ fn functions() { ), "SemanticError(\"Function already defined\")" ); + + println!(); + + // Nested function call + let _program = parse_program( + r#" + # version 450 + layout(set = 0, binding = 1) uniform texture2D t_noise; + layout(set = 0, binding = 2) uniform sampler s_noise; + + void main() { + textureLod(sampler2D(t_noise, s_noise), vec2(1.0), 0); + } + "#, + &entry_points, + ) + .unwrap(); } #[test] From 474b5918929635746adb556f74850a702ef753a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 12:20:52 +0100 Subject: [PATCH 0859/2212] [glsl-in] Add support for assignment ops --- src/front/glsl/parser.rs | 69 +++++++++++++++++++++++++++++++++------- 1 file changed, 57 insertions(+), 12 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index fdebe6e24..b90f1fc6b 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1053,19 +1053,64 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let start_meta = pointer.meta.clone(); // TODO: More assign symbols - if self.bump_if(TokenValue::Assign).is_some() { - let value = Box::new(self.parse_assignment(ctx)?); - let end_meta = value.meta.clone(); + match self.expect_peek()?.value { + TokenValue::Assign => { + self.bump()?; + let value = Box::new(self.parse_assignment(ctx)?); + let end_meta = value.meta.clone(); - Ok(Expr { - kind: ExprKind::Assign { - tgt: Box::new(pointer), - value, - }, - meta: start_meta.union(&end_meta), - }) - } else { - self.parse_conditional(ctx, Some(pointer)) + Ok(Expr { + kind: ExprKind::Assign { + tgt: Box::new(pointer), + value, + }, + meta: start_meta.union(&end_meta), + }) + } + TokenValue::OrAssign + | TokenValue::AndAssign + | TokenValue::AddAssign + | TokenValue::DivAssign + | TokenValue::ModAssign + | TokenValue::SubAssign + | TokenValue::MulAssign + | TokenValue::LeftShiftAssign + | TokenValue::RightShiftAssign + | TokenValue::XorAssign => { + let token = self.bump()?; + let right = Box::new(self.parse_assignment(ctx)?); + let end_meta = right.meta.clone(); + + let value = Box::new(Expr { + meta: start_meta.union(&end_meta), + kind: ExprKind::Binary { + left: Box::new(pointer.clone()), + op: match token.value { + TokenValue::OrAssign => BinaryOperator::ExclusiveOr, + TokenValue::AndAssign => BinaryOperator::ExclusiveOr, + TokenValue::AddAssign => BinaryOperator::ExclusiveOr, + TokenValue::DivAssign => BinaryOperator::ExclusiveOr, + TokenValue::ModAssign => BinaryOperator::ExclusiveOr, + TokenValue::SubAssign => BinaryOperator::ExclusiveOr, + TokenValue::MulAssign => BinaryOperator::ExclusiveOr, + TokenValue::LeftShiftAssign => BinaryOperator::ExclusiveOr, + TokenValue::RightShiftAssign => BinaryOperator::ExclusiveOr, + TokenValue::XorAssign => BinaryOperator::ExclusiveOr, + _ => unreachable!(), + }, + right, + }, + }); + + Ok(Expr { + kind: ExprKind::Assign { + tgt: Box::new(pointer), + value, + }, + meta: start_meta.union(&end_meta), + }) + } + _ => self.parse_conditional(ctx, Some(pointer)), } } From 95a2baf485dbc1813e1ab20392893a5378c72424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 12:21:48 +0100 Subject: [PATCH 0860/2212] [glsl-in] lower expression statements --- src/front/glsl/parser.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b90f1fc6b..69215881e 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1388,7 +1388,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::RightParen => {} _ => { let rest = self.parse_expression(ctx)?; - ctx.lower(self.program, rest, false, &mut &mut continuing)?; + ctx.lower(self.program, rest, false, &mut continuing)?; } } @@ -1430,7 +1430,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { | TokenValue::IntConstant(_) | TokenValue::BoolConstant(_) | TokenValue::FloatConstant(_) => { - self.parse_expression(ctx)?; + let expr = self.parse_expression(ctx)?; + ctx.lower(self.program, expr, false, body)?; self.expect(TokenValue::Semicolon)?; } TokenValue::Semicolon => { From 375f6fb38dd957d6b4b23f732aa5a7e8b9b392d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 12:49:22 +0100 Subject: [PATCH 0861/2212] [glsl-in] Use typed errors in the parser tests Rename TokenMetadata to SourceMetadata to reflect it's actual use --- src/front/glsl/ast.rs | 6 +-- src/front/glsl/error.rs | 60 +++++++++++++----------- src/front/glsl/lex.rs | 22 ++++----- src/front/glsl/mod.rs | 2 +- src/front/glsl/parser.rs | 6 +-- src/front/glsl/parser_tests.rs | 86 ++++++++++++++-------------------- src/front/glsl/token.rs | 8 ++-- src/front/glsl/variables.rs | 4 +- 8 files changed, 92 insertions(+), 102 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 453c31a41..21ff09d6e 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,4 +1,4 @@ -use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind, TokenMetadata}; +use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind, SourceMetadata}; use crate::{ proc::ResolveContext, Arena, BinaryOperator, Block, BuiltIn, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, @@ -165,7 +165,7 @@ impl<'a> Program<'a> { } } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum Profile { Core, } @@ -431,7 +431,7 @@ pub struct VariableReference { #[derive(Debug, Clone)] pub struct Expr { pub kind: ExprKind, - pub meta: TokenMetadata, + pub meta: SourceMetadata, } #[derive(Debug, Clone)] diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index dd5e0b4c4..b1c953ea7 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -1,21 +1,21 @@ -use super::token::{Token, TokenMetadata}; -use std::{borrow::Cow, fmt, io}; +use super::token::{SourceMetadata, Token}; +use std::{borrow::Cow, fmt}; //TODO: use `thiserror` #[derive(Debug)] +#[cfg_attr(test, derive(PartialEq))] pub enum ErrorKind { EndOfFile, InvalidInput, - InvalidProfile(TokenMetadata, String), + InvalidProfile(SourceMetadata, String), InvalidToken(Token), - InvalidVersion(TokenMetadata, u64), - IoError(io::Error), + InvalidVersion(SourceMetadata, u64), ParserFail, ParserStackOverflow, NotImplemented(&'static str), - UnknownVariable(TokenMetadata, String), - UnknownField(TokenMetadata, String), - UnknownLayoutQualifier(TokenMetadata, String), + UnknownVariable(SourceMetadata, String), + UnknownField(SourceMetadata, String), + UnknownLayoutQualifier(SourceMetadata, String), #[cfg(feature = "glsl-validate")] VariableAlreadyDeclared(String), ExpectedConstant, @@ -24,30 +24,44 @@ pub enum ErrorKind { WrongNumberArgs(String, usize, usize), } +impl ErrorKind { + // Returns the TokenMetadata if available + pub fn metadata(&self) -> Option<&SourceMetadata> { + match *self { + ErrorKind::UnknownVariable(ref metadata, _) + | ErrorKind::InvalidProfile(ref metadata, _) + | ErrorKind::InvalidVersion(ref metadata, _) + | ErrorKind::UnknownLayoutQualifier(ref metadata, _) + | ErrorKind::UnknownField(ref metadata, _) => Some(metadata), + ErrorKind::InvalidToken(ref token) => Some(&token.meta), + _ => None, + } + } +} + impl fmt::Display for ErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ErrorKind::EndOfFile => write!(f, "Unexpected end of file"), ErrorKind::InvalidInput => write!(f, "InvalidInput"), - ErrorKind::InvalidProfile(ref meta, ref val) => { - write!(f, "Invalid profile {} at {:?}", val, meta) + ErrorKind::InvalidProfile(_, ref val) => { + write!(f, "Invalid profile {}", val) } ErrorKind::InvalidToken(ref token) => write!(f, "Invalid Token {:?}", token), - ErrorKind::InvalidVersion(ref meta, ref val) => { - write!(f, "Invalid version {} at {:?}", val, meta) + ErrorKind::InvalidVersion(_, ref val) => { + write!(f, "Invalid version {}", val) } - ErrorKind::IoError(ref error) => write!(f, "IO Error {}", error), ErrorKind::ParserFail => write!(f, "Parser failed"), ErrorKind::ParserStackOverflow => write!(f, "Parser stack overflow"), ErrorKind::NotImplemented(ref msg) => write!(f, "Not implemented: {}", msg), - ErrorKind::UnknownVariable(ref meta, ref val) => { - write!(f, "Unknown variable {} at {:?}", val, meta) + ErrorKind::UnknownVariable(_, ref val) => { + write!(f, "Unknown variable {}", val) } - ErrorKind::UnknownField(ref meta, ref val) => { - write!(f, "Unknown field {} at {:?}", val, meta) + ErrorKind::UnknownField(_, ref val) => { + write!(f, "Unknown field {}", val) } - ErrorKind::UnknownLayoutQualifier(ref meta, ref val) => { - write!(f, "Unknown layout qualifier name {} at {:?}", val, meta) + ErrorKind::UnknownLayoutQualifier(_, ref val) => { + write!(f, "Unknown layout qualifier name {}", val) } #[cfg(feature = "glsl-validate")] ErrorKind::VariableAlreadyDeclared(ref val) => { @@ -74,14 +88,6 @@ impl fmt::Display for ParseError { } } -impl From for ParseError { - fn from(error: io::Error) -> Self { - ParseError { - kind: ErrorKind::IoError(error), - } - } -} - impl From for ParseError { fn from(kind: ErrorKind) -> Self { ParseError { kind } diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 95cb24094..bc6335abf 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -1,5 +1,5 @@ use super::{ - token::{Token, TokenMetadata, TokenValue}, + token::{SourceMetadata, Token, TokenValue}, types::parse_type, }; use crate::FastHashMap; @@ -30,7 +30,7 @@ impl<'a> Lexer<'a> { impl<'a> Iterator for Lexer<'a> { type Item = Token; fn next(&mut self) -> Option { - let mut meta = TokenMetadata { chars: 0..0 }; + let mut meta = SourceMetadata { chars: 0..0 }; let pp_token = match self.tokens.pop_front() { Some(t) => t, None => match self.pp.next()? { @@ -172,7 +172,7 @@ mod tests { use pp_rs::token::Integer; use super::{ - super::token::{Token, TokenMetadata, TokenValue}, + super::token::{SourceMetadata, Token, TokenValue}, Lexer, }; @@ -186,7 +186,7 @@ mod tests { lex.next().unwrap(), Token { value: TokenValue::Version, - meta: TokenMetadata { chars: 1..8 } + meta: SourceMetadata { chars: 1..8 } } ); assert_eq!( @@ -197,49 +197,49 @@ mod tests { value: 450, width: 32 }), - meta: TokenMetadata { chars: 9..12 }, + meta: SourceMetadata { chars: 9..12 }, } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::Void, - meta: TokenMetadata { chars: 13..17 } + meta: SourceMetadata { chars: 13..17 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::Identifier("main".into()), - meta: TokenMetadata { chars: 18..22 } + meta: SourceMetadata { chars: 18..22 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::LeftParen, - meta: TokenMetadata { chars: 23..24 } + meta: SourceMetadata { chars: 23..24 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::RightParen, - meta: TokenMetadata { chars: 24..25 } + meta: SourceMetadata { chars: 24..25 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::LeftBrace, - meta: TokenMetadata { chars: 26..27 } + meta: SourceMetadata { chars: 26..27 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::RightBrace, - meta: TokenMetadata { chars: 27..28 } + meta: SourceMetadata { chars: 27..28 } } ); assert_eq!(lex.next(), None); diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index e03d61109..41e6967db 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,5 +1,5 @@ pub use error::ErrorKind; -pub use token::{Token, TokenMetadata}; +pub use token::{SourceMetadata, Token}; use crate::{FastHashMap, Module, ShaderStage}; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 69215881e..f339a9278 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -5,7 +5,7 @@ use super::{ }, error::ErrorKind, lex::Lexer, - token::{Token, TokenMetadata, TokenValue}, + token::{SourceMetadata, Token, TokenValue}, Program, }; use crate::{ @@ -31,7 +31,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } - fn expect_ident(&mut self) -> Result<(String, TokenMetadata)> { + fn expect_ident(&mut self) -> Result<(String, SourceMetadata)> { let token = self.bump()?; match token.value { @@ -831,7 +831,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_function_call_args( &mut self, ctx: &mut Context, - meta: &mut TokenMetadata, + meta: &mut SourceMetadata, ) -> Result> { let mut args = Vec::new(); if let Some(token) = self.bump_if(TokenValue::RightParen) { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 6166c1c9c..066a3a07c 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -1,8 +1,13 @@ -use super::ast::Program; -use super::error::ErrorKind; +use pp_rs::token::PreprocessorError; + use super::lex::Lexer; use super::parser; -use crate::ShaderStage; +use super::{ast::Profile, error::ErrorKind}; +use super::{ast::Program, SourceMetadata}; +use crate::{ + front::glsl::{token::TokenValue, Token}, + ShaderStage, +}; fn parse_program<'a>( source: &str, @@ -23,61 +28,43 @@ fn version() { entry_points.insert("".to_string(), ShaderStage::Vertex); // invalid versions assert_eq!( - format!( - "{:?}", - parse_program("#version 99000", &entry_points) - .err() - .unwrap() - ), - "InvalidVersion(TokenMetadata { chars: 9..14 }, 99000)" + parse_program("#version 99000", &entry_points) + .err() + .unwrap(), + ErrorKind::InvalidVersion(SourceMetadata { chars: 9..14 }, 99000), ); assert_eq!( - format!( - "{:?}", - parse_program("#version 449", &entry_points).err().unwrap() - ), - "InvalidVersion(TokenMetadata { chars: 9..12 }, 449)" + parse_program("#version 449", &entry_points).err().unwrap(), + ErrorKind::InvalidVersion(SourceMetadata { chars: 9..12 }, 449) ); assert_eq!( - format!( - "{:?}", - parse_program("#version 450 smart", &entry_points) - .err() - .unwrap() - ), - "InvalidProfile(TokenMetadata { chars: 13..18 }, \"smart\")" + parse_program("#version 450 smart", &entry_points) + .err() + .unwrap(), + ErrorKind::InvalidProfile(SourceMetadata { chars: 13..18 }, "smart".into()) ); assert_eq!( - format!( - "{:?}", - parse_program("#version 450\nvoid f(){} #version 450", &entry_points) - .err() - .unwrap() - ), - "InvalidToken(Token { value: Unknown(UnexpectedHash), meta: TokenMetadata { chars: 24..25 } })" + parse_program("#version 450\nvoid f(){} #version 450", &entry_points) + .err() + .unwrap(), + ErrorKind::InvalidToken(Token { + value: TokenValue::Unknown(PreprocessorError::UnexpectedHash), + meta: SourceMetadata { chars: 24..25 } + }) ); // valid versions let program = parse_program(" # version 450\nvoid main() {}", &entry_points).unwrap(); - assert_eq!( - format!("{:?}", (program.version, program.profile)), - "(450, Core)" - ); + assert_eq!((program.version, program.profile), (450, Profile::Core)); let program = parse_program("#version 450\nvoid main() {}", &entry_points).unwrap(); - assert_eq!( - format!("{:?}", (program.version, program.profile)), - "(450, Core)" - ); + assert_eq!((program.version, program.profile), (450, Profile::Core)); let program = parse_program("#version 450 core\nvoid main() {}", &entry_points).unwrap(); - assert_eq!( - format!("{:?}", (program.version, program.profile)), - "(450, Core)" - ); + assert_eq!((program.version, program.profile), (450, Profile::Core)); } #[test] @@ -327,10 +314,8 @@ fn functions() { .unwrap(); assert_eq!( - format!( - "{:?}", - parse_program( - r#" + parse_program( + r#" # version 450 int test(vec4 p) { return p.x; @@ -340,12 +325,11 @@ fn functions() { return p.x; } "#, - &entry_points - ) - .err() - .unwrap() - ), - "SemanticError(\"Function already defined\")" + &entry_points + ) + .err() + .unwrap(), + ErrorKind::SemanticError("Function already defined".into()) ); println!(); diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 3483f9d27..a8710245d 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -5,13 +5,13 @@ use std::ops::Range; #[derive(Debug, Clone)] #[cfg_attr(test, derive(PartialEq))] -pub struct TokenMetadata { +pub struct SourceMetadata { pub chars: Range, } -impl TokenMetadata { +impl SourceMetadata { pub fn union(&self, other: &Self) -> Self { - TokenMetadata { + SourceMetadata { chars: (self.chars.start.min(other.chars.start))..(self.chars.end.max(self.chars.end)), } } @@ -21,7 +21,7 @@ impl TokenMetadata { #[cfg_attr(test, derive(PartialEq))] pub struct Token { pub value: TokenValue, - pub meta: TokenMetadata, + pub meta: SourceMetadata, } #[derive(Debug, PartialEq)] diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 12def0422..b7ff88770 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -5,7 +5,7 @@ use crate::{ use super::ast::*; use super::error::ErrorKind; -use super::token::TokenMetadata; +use super::token::SourceMetadata; impl Program<'_> { pub fn lookup_variable( @@ -108,7 +108,7 @@ impl Program<'_> { context: &mut Context, expression: Handle, name: &str, - meta: TokenMetadata, + meta: SourceMetadata, ) -> Result, ErrorKind> { match *self.resolve_type(context, expression)? { TypeInner::Struct { ref members, .. } => { From a44d40e5ae1a762e3bc111ed5cbc0a1f9ec04685 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 13:53:31 +0100 Subject: [PATCH 0862/2212] [glsl-in] use thiserror for the error --- src/front/glsl/error.rs | 75 ++++++++++------------------------------- src/front/glsl/token.rs | 8 ++++- 2 files changed, 25 insertions(+), 58 deletions(-) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index b1c953ea7..256abc491 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -1,31 +1,37 @@ use super::token::{SourceMetadata, Token}; -use std::{borrow::Cow, fmt}; +use std::borrow::Cow; +use thiserror::Error; -//TODO: use `thiserror` -#[derive(Debug)] +#[derive(Debug, Error)] #[cfg_attr(test, derive(PartialEq))] pub enum ErrorKind { + #[error("Unexpected end of file")] EndOfFile, - InvalidInput, + #[error("Invalid profile: {1}")] InvalidProfile(SourceMetadata, String), - InvalidToken(Token), + #[error("Invalid version: {1}")] InvalidVersion(SourceMetadata, u64), - ParserFail, - ParserStackOverflow, + #[error("Unexpected token: {0}")] + InvalidToken(Token), + #[error("Not implemented {0}")] NotImplemented(&'static str), + #[error("Unknown variable: {1}")] UnknownVariable(SourceMetadata, String), + #[error("Unknown field: {1}")] UnknownField(SourceMetadata, String), + #[error("Unknown layout qualifier: {1}")] UnknownLayoutQualifier(SourceMetadata, String), #[cfg(feature = "glsl-validate")] + #[error("Variable already declared: {0}")] VariableAlreadyDeclared(String), - ExpectedConstant, + #[error("{0}")] SemanticError(Cow<'static, str>), - PreprocessorError(String), + #[error("Function \"{0}\" expects {1} arguments, got {2}")] WrongNumberArgs(String, usize, usize), } impl ErrorKind { - // Returns the TokenMetadata if available + /// Returns the TokenMetadata if available pub fn metadata(&self) -> Option<&SourceMetadata> { match *self { ErrorKind::UnknownVariable(ref metadata, _) @@ -39,59 +45,14 @@ impl ErrorKind { } } -impl fmt::Display for ErrorKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - ErrorKind::EndOfFile => write!(f, "Unexpected end of file"), - ErrorKind::InvalidInput => write!(f, "InvalidInput"), - ErrorKind::InvalidProfile(_, ref val) => { - write!(f, "Invalid profile {}", val) - } - ErrorKind::InvalidToken(ref token) => write!(f, "Invalid Token {:?}", token), - ErrorKind::InvalidVersion(_, ref val) => { - write!(f, "Invalid version {}", val) - } - ErrorKind::ParserFail => write!(f, "Parser failed"), - ErrorKind::ParserStackOverflow => write!(f, "Parser stack overflow"), - ErrorKind::NotImplemented(ref msg) => write!(f, "Not implemented: {}", msg), - ErrorKind::UnknownVariable(_, ref val) => { - write!(f, "Unknown variable {}", val) - } - ErrorKind::UnknownField(_, ref val) => { - write!(f, "Unknown field {}", val) - } - ErrorKind::UnknownLayoutQualifier(_, ref val) => { - write!(f, "Unknown layout qualifier name {}", val) - } - #[cfg(feature = "glsl-validate")] - ErrorKind::VariableAlreadyDeclared(ref val) => { - write!(f, "Variable {} already declared in current scope", val) - } - ErrorKind::ExpectedConstant => write!(f, "Expected constant"), - ErrorKind::SemanticError(ref msg) => write!(f, "Semantic error: {}", msg), - ErrorKind::PreprocessorError(ref val) => write!(f, "Preprocessor error: {}", val), - ErrorKind::WrongNumberArgs(ref fun, expected, actual) => { - write!(f, "{} requires {} args, got {}", fun, expected, actual) - } - } - } -} - -#[derive(Debug)] +#[derive(Debug, Error)] +#[error("{kind}")] pub struct ParseError { pub kind: ErrorKind, } -impl fmt::Display for ParseError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self) - } -} - impl From for ParseError { fn from(kind: ErrorKind) -> Self { ParseError { kind } } } - -impl std::error::Error for ParseError {} diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index a8710245d..c791003c6 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -1,7 +1,7 @@ pub use pp_rs::token::{Float, Integer, PreprocessorError}; use crate::{Interpolation, Sampling, Type}; -use std::ops::Range; +use std::{fmt, ops::Range}; #[derive(Debug, Clone)] #[cfg_attr(test, derive(PartialEq))] @@ -116,3 +116,9 @@ pub enum TokenValue { Ampersand, Question, } + +impl fmt::Display for Token { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self.value) + } +} From 57ab3b3fb4b327c1e45f8b8f93c6f58b2e13fefa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 15:30:43 +0100 Subject: [PATCH 0863/2212] [glsl-in] Add metadata to semantic errors --- src/front/glsl/ast.rs | 15 ++- src/front/glsl/error.rs | 5 +- src/front/glsl/functions.rs | 32 ++++-- src/front/glsl/parser.rs | 189 ++++++++++++++++++++++----------- src/front/glsl/parser_tests.rs | 5 +- src/front/glsl/token.rs | 2 +- src/front/glsl/variables.rs | 47 ++++++-- 7 files changed, 203 insertions(+), 92 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 21ff09d6e..ea0644939 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -89,6 +89,7 @@ impl<'a> Program<'a> { &'b mut self, context: &'b mut Context, handle: Handle, + meta: SourceMetadata, ) -> Result<&'b TypeInner, ErrorKind> { let resolve_ctx = ResolveContext { constants: &self.module.constants, @@ -105,6 +106,7 @@ impl<'a> Program<'a> { ) { //TODO: better error report Err(error) => Err(ErrorKind::SemanticError( + meta, format!("Can't resolve type: {:?}", error).into(), )), Ok(()) => Ok(context.typifier.get(handle, &self.module.types)), @@ -115,6 +117,7 @@ impl<'a> Program<'a> { &mut self, context: &mut Context, handle: Handle, + meta: SourceMetadata, ) -> Result, ErrorKind> { let resolve_ctx = ResolveContext { constants: &self.module.constants, @@ -131,6 +134,7 @@ impl<'a> Program<'a> { ) { //TODO: better error report Err(error) => Err(ErrorKind::SemanticError( + meta, format!("Can't resolve type: {:?}", error).into(), )), Ok(()) => Ok(context.typifier.get_handle(handle, &mut self.module.types)), @@ -141,6 +145,7 @@ impl<'a> Program<'a> { &mut self, expressions: &Arena, root: Handle, + meta: SourceMetadata, ) -> Result, ErrorKind> { let mut solver = ConstantSolver { types: &self.module.types, @@ -150,7 +155,7 @@ impl<'a> Program<'a> { solver .solve(root) - .map_err(|_| ErrorKind::SemanticError("Can't solve constant".into())) + .map_err(|_| ErrorKind::SemanticError(meta, "Can't solve constant".into())) } pub fn function_args_prelude(&self) -> (Vec, Vec) { @@ -338,17 +343,18 @@ impl<'function> Context<'function> { self.expressions.append(Expression::Constant(constant)) } ExprKind::Binary { left, op, right } if !lhs => { + let (left_meta, right_meta) = (left.meta.clone(), right.meta.clone()); let left = self.lower(program, *left, false, body)?; let right = self.lower(program, *right, false, body)?; if let BinaryOperator::Equal | BinaryOperator::NotEqual = op { let equals = op == BinaryOperator::Equal; - let left_is_vector = match *program.resolve_type(self, left)? { + let left_is_vector = match *program.resolve_type(self, left, left_meta)? { crate::TypeInner::Vector { .. } => true, _ => false, }; - let right_is_vector = match *program.resolve_type(self, right)? { + let right_is_vector = match *program.resolve_type(self, right, right_meta)? { crate::TypeInner::Vector { .. } => true, _ => false, }; @@ -388,7 +394,7 @@ impl<'function> Context<'function> { } } ExprKind::Call(call) if !lhs => { - program.function_call(self, call.kind, call.args, body)? + program.function_call(self, body, call.kind, call.args, expr.meta)? } ExprKind::Conditional { condition, @@ -415,6 +421,7 @@ impl<'function> Context<'function> { } _ => { return Err(ErrorKind::SemanticError( + expr.meta.clone(), format!("{:?} cannot be in the left hand side", expr).into(), )) } diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 256abc491..d955f1a82 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -24,8 +24,8 @@ pub enum ErrorKind { #[cfg(feature = "glsl-validate")] #[error("Variable already declared: {0}")] VariableAlreadyDeclared(String), - #[error("{0}")] - SemanticError(Cow<'static, str>), + #[error("{1}")] + SemanticError(SourceMetadata, Cow<'static, str>), #[error("Function \"{0}\" expects {1} arguments, got {2}")] WrongNumberArgs(String, usize, usize), } @@ -38,6 +38,7 @@ impl ErrorKind { | ErrorKind::InvalidProfile(ref metadata, _) | ErrorKind::InvalidVersion(ref metadata, _) | ErrorKind::UnknownLayoutQualifier(ref metadata, _) + | ErrorKind::SemanticError(ref metadata, _) | ErrorKind::UnknownField(ref metadata, _) => Some(metadata), ErrorKind::InvalidToken(ref token) => Some(&token.meta), _ => None, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 75ff0535a..f7766416e 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -5,15 +5,16 @@ use crate::{ TypeInner, }; -use super::{ast::*, error::ErrorKind}; +use super::{ast::*, error::ErrorKind, SourceMetadata}; impl Program<'_> { pub fn function_call( &mut self, ctx: &mut Context, + body: &mut Block, fc: FunctionCallKind, raw_args: Vec, - body: &mut Block, + meta: SourceMetadata, ) -> Result, ErrorKind> { let args: Vec<_> = raw_args .clone() @@ -24,7 +25,7 @@ impl Program<'_> { match fc { FunctionCallKind::TypeConstructor(ty) => { let h = if args.len() == 1 { - let is_vec = match *self.resolve_type(ctx, args[0])? { + let is_vec = match *self.resolve_type(ctx, args[0], raw_args[0].meta.clone())? { TypeInner::Vector { .. } => true, _ => false, }; @@ -70,7 +71,7 @@ impl Program<'_> { components: columns, }) } - _ => return Err(ErrorKind::SemanticError("Bad cast".into())), + _ => return Err(ErrorKind::SemanticError(meta, "Bad cast".into())), } } else { ctx.expressions.append(Expression::Compose { @@ -105,7 +106,7 @@ impl Program<'_> { depth_ref: None, })) } else { - Err(ErrorKind::SemanticError("Bad call to texture".into())) + Err(ErrorKind::SemanticError(meta, "Bad call to texture".into())) } } "textureLod" => { @@ -123,7 +124,10 @@ impl Program<'_> { depth_ref: None, })) } else { - Err(ErrorKind::SemanticError("Bad call to textureLod".into())) + Err(ErrorKind::SemanticError( + meta, + "Bad call to textureLod".into(), + )) } } "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" @@ -219,7 +223,8 @@ impl Program<'_> { name, parameters: args .iter() - .map(|e| self.resolve_handle(ctx, *e)) + .zip(raw_args.iter().map(|e| e.meta.clone())) + .map(|(e, meta)| self.resolve_handle(ctx, *e, meta)) .collect::>()?, }; @@ -228,6 +233,8 @@ impl Program<'_> { .get(&sig) .ok_or_else(|| { ErrorKind::SemanticError( + meta, + // FIXME: Proper signature display format!("Unknown function: {:?}", sig).into(), ) })? @@ -275,12 +282,13 @@ impl Program<'_> { &mut self, mut function: Function, parameters: Vec, + meta: SourceMetadata, ) -> Result<(), ErrorKind> { ensure_block_returns(&mut function.body); let name = function .name .clone() - .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; + .ok_or_else(|| ErrorKind::SemanticError(meta.clone(), "Unnamed function".into()))?; let stage = self.entry_points.get(&name); if let Some(&stage) = stage { @@ -306,7 +314,10 @@ impl Program<'_> { if let Some(decl) = self.lookup_function.get_mut(&sig) { if decl.defined { - return Err(ErrorKind::SemanticError("Function already defined".into())); + return Err(ErrorKind::SemanticError( + meta, + "Function already defined".into(), + )); } decl.defined = true; @@ -331,11 +342,12 @@ impl Program<'_> { &mut self, mut function: Function, parameters: Vec, + meta: SourceMetadata, ) -> Result<(), ErrorKind> { let name = function .name .clone() - .ok_or_else(|| ErrorKind::SemanticError("Unnamed function".into()))?; + .ok_or_else(|| ErrorKind::SemanticError(meta, "Unnamed function".into()))?; let sig = FunctionSignature { name, parameters: function.arguments.iter().map(|p| p.ty).collect(), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index f339a9278..13a82cd97 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -6,6 +6,7 @@ use super::{ error::ErrorKind, lex::Lexer, token::{SourceMetadata, Token, TokenValue}, + variables::VarDeclaration, Program, }; use crate::{ @@ -125,7 +126,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } - fn parse_type(&mut self) -> Result>> { + fn parse_type(&mut self) -> Result<(Option>, SourceMetadata)> { let token = self.bump()?; let ty = match token.value { TokenValue::Void => None, @@ -136,12 +137,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let handle = ty.map(|t| self.program.module.types.fetch_or_append(t)); let size = self.parse_array_specifier()?; - Ok(handle.map(|ty| self.maybe_array(ty, size))) + Ok((handle.map(|ty| self.maybe_array(ty, size)), token.meta)) } - fn parse_type_non_void(&mut self) -> Result> { - self.parse_type()? - .ok_or_else(|| ErrorKind::SemanticError("Type can't be void".into())) + fn parse_type_non_void(&mut self) -> Result<(Handle, SourceMetadata)> { + let (maybe_ty, meta) = self.parse_type()?; + let ty = maybe_ty + .ok_or_else(|| ErrorKind::SemanticError(meta.clone(), "Type can't be void".into()))?; + + Ok((ty, meta)) } fn maybe_array(&mut self, base: Handle, size: Option) -> Handle { @@ -223,21 +227,22 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::RightParen)?; match (group, binding) { - (Some(group), Some(binding)) => { + (Some((group, _)), Some((binding, _))) => { qualifiers.push(TypeQualifier::ResourceBinding(ResourceBinding { group, binding, })) } // Produce an error if we have one of group or binding but not the other - // TODO: include at least line info in errors? - (Some(_), None) => { + (Some((_, meta)), None) => { return Err(ErrorKind::SemanticError( + meta, "set specified with no binding".into(), )) } - (None, Some(_)) => { + (None, Some((_, meta))) => { return Err(ErrorKind::SemanticError( + meta, "binding specified with no set".into(), )) } @@ -247,45 +252,52 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(()) } - fn parse_uint_constant(&mut self) -> Result { - let value = self.parse_constant_expression()?; + fn parse_uint_constant(&mut self) -> Result<(u32, SourceMetadata)> { + let (value, meta) = self.parse_constant_expression()?; - // TODO: better errors - match self.program.module.constants[value].inner { + let int = match self.program.module.constants[value].inner { ConstantInner::Scalar { value: ScalarValue::Uint(int), .. - } => u32::try_from(int) - .map_err(|_| ErrorKind::SemanticError("int constant overflows".into())), + } => u32::try_from(int).map_err(|_| { + ErrorKind::SemanticError(meta.clone(), "int constant overflows".into()) + }), ConstantInner::Scalar { value: ScalarValue::Sint(int), .. - } => u32::try_from(int) - .map_err(|_| ErrorKind::SemanticError("int constant overflows".into())), - _ => Err(ErrorKind::SemanticError("Expected a uint constant".into())), - } + } => u32::try_from(int).map_err(|_| { + ErrorKind::SemanticError(meta.clone(), "int constant overflows".into()) + }), + _ => Err(ErrorKind::SemanticError( + meta.clone(), + "Expected a uint constant".into(), + )), + }?; + + Ok((int, meta)) } fn parse_layout_qualifier_id( &mut self, qualifiers: &mut Vec, - group: &mut Option, - binding: &mut Option, + group: &mut Option<(u32, SourceMetadata)>, + binding: &mut Option<(u32, SourceMetadata)>, ) -> Result<()> { // layout_qualifier_id: // IDENTIFIER // IDENTIFIER EQUAL constant_expression // SHARED - let token = self.bump()?; + let mut token = self.bump()?; match token.value { TokenValue::Identifier(name) => { if self.bump_if(TokenValue::Assign).is_some() { - let value = self.parse_uint_constant()?; + let (value, end_meta) = self.parse_uint_constant()?; + token.meta = token.meta.union(&end_meta); match name.as_str() { "location" => qualifiers.push(TypeQualifier::Location(value)), - "set" => *group = Some(value), - "binding" => *binding = Some(value), + "set" => *group = Some((value, end_meta)), + "binding" => *binding = Some((value, end_meta)), _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), } } else { @@ -305,7 +317,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } - fn parse_constant_expression(&mut self) -> Result> { + fn parse_constant_expression(&mut self) -> Result<(Handle, SourceMetadata)> { let mut expressions = Arena::new(); let mut locals = Arena::new(); let mut arguments = Vec::new(); @@ -313,9 +325,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut ctx = Context::new(&mut expressions, &mut locals, &mut arguments); let expr = self.parse_conditional(&mut ctx, None)?; + let meta = expr.meta.clone(); let root = ctx.lower(self.program, expr, false, &mut Block::new())?; - self.program.solve_constant(&expressions, root) + Ok(( + self.program + .solve_constant(&expressions, root, meta.clone())?, + meta, + )) } fn parse_external_declaration(&mut self) -> Result<()> { @@ -377,7 +394,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ty: Handle, ctx: &mut Context, body: &mut Block, - ) -> Result> { + ) -> Result<(Handle, SourceMetadata)> { // initializer: // assignment_expression // LEFT_BRACE initializer_list RIGHT_BRACE @@ -386,33 +403,42 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // initializer_list: // initializer // initializer_list COMMA initializer - if self.bump_if(TokenValue::LeftBrace).is_some() { + if let Some(Token { mut meta, .. }) = self.bump_if(TokenValue::LeftBrace) { // initializer_list let mut components = Vec::new(); loop { // TODO: Change type - components.push(self.parse_initializer(ty, ctx, body)?); + components.push(self.parse_initializer(ty, ctx, body)?.0); let token = self.bump()?; match token.value { TokenValue::Comma => { - if self.bump_if(TokenValue::RightBrace).is_some() { + if let Some(Token { meta: end_meta, .. }) = + self.bump_if(TokenValue::RightBrace) + { + meta = meta.union(&end_meta); break; } } - TokenValue::RightBrace => break, + TokenValue::RightBrace => { + meta = meta.union(&token.meta); + break; + } _ => return Err(ErrorKind::InvalidToken(token)), } } - Ok(ctx - .expressions - .append(Expression::Compose { ty, components })) + Ok(( + ctx.expressions + .append(Expression::Compose { ty, components }), + meta, + )) } else { let expr = self.parse_assignment(ctx)?; + let meta = expr.meta.clone(); let root = ctx.lower(self.program, expr, false, body)?; - Ok(root) + Ok((root, meta)) } } @@ -459,6 +485,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Identifier(name) => name, _ => return Err(ErrorKind::InvalidToken(token)), }; + let mut meta = token.meta; // array_specifier // array_specifier EQUAL initializer @@ -472,20 +499,25 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let init = self .bump_if(TokenValue::Assign) - .map(|_| self.parse_initializer(ty, ctx.ctx, ctx.body)) + .map(|_| { + let (expr, init_meta) = self.parse_initializer(ty, ctx.ctx, ctx.body)?; + meta = meta.union(&init_meta); + Ok((expr, init_meta)) + }) .transpose()?; - let pointer = ctx.add_var( - ty, - name, - // TODO: Should we try to make constants here? - // This is mostly a hack because we don't yet support adding - // bodies to entry points for variable initialization - init.and_then(|root| self.program.solve_constant(ctx.ctx.expressions, root).ok()), - self.program, - )?; + // TODO: Should we try to make constants here? + // This is mostly a hack because we don't yet support adding + // bodies to entry points for variable initialization + let maybe_constant = init.clone().and_then(|(root, meta)| { + self.program + .solve_constant(ctx.ctx.expressions, root, meta) + .ok() + }); - if let Some(value) = init { + let pointer = ctx.add_var(self.program, ty, name, maybe_constant, meta)?; + + if let Some((value, _)) = init { ctx.body.push(Statement::Store { pointer, value }); } @@ -525,7 +557,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { if self.peek_type_name() { // This branch handles variables and function prototypes and if // external is true also function definitions - let ty = self.parse_type()?; + let (ty, mut meta) = self.parse_type()?; let token = self.bump()?; let token_fallthrough = match token.value { @@ -548,7 +580,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.parse_function_args(&mut context, &mut parameters)?; - self.expect(TokenValue::RightParen)?; + let end_meta = self.expect(TokenValue::RightParen)?.meta; + meta = meta.union(&end_meta); let token = self.bump()?; return match token.value { @@ -562,6 +595,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ..Default::default() }, parameters, + meta, )?; Ok(true) @@ -584,6 +618,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { body, }, parameters, + meta, )?; Ok(true) @@ -615,6 +650,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.parse_init_declarator_list(ty, Some(token_fallthrough), &mut ctx)?; } else { return Err(ErrorKind::SemanticError( + meta, "Declaration cannot have void type".into(), )); } @@ -629,7 +665,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match token.value { TokenValue::Identifier(ty_name) => { if self.bump_if(TokenValue::LeftBrace).is_some() { - self.parse_block_declaration(&qualifiers, ty_name) + self.parse_block_declaration(&qualifiers, ty_name, token.meta) } else { //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON @@ -651,6 +687,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { &mut self, qualifiers: &[TypeQualifier], ty_name: String, + meta: SourceMetadata, ) -> Result { let mut class = StorageClass::Function; let mut binding = None; @@ -661,6 +698,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { if StorageClass::Function != class { return Err(ErrorKind::SemanticError( + meta, "Cannot use more than one storage qualifier per declaration".into(), )); } @@ -670,6 +708,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TypeQualifier::ResourceBinding(ref r) => { if binding.is_some() { return Err(ErrorKind::SemanticError( + meta, "Cannot use more than one storage qualifier per declaration".into(), )); } @@ -679,6 +718,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TypeQualifier::Layout(ref l) => { if layout.is_some() { return Err(ErrorKind::SemanticError( + meta, "Cannot use more than one storage qualifier per declaration".into(), )); } @@ -687,6 +727,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } _ => { return Err(ErrorKind::SemanticError( + meta, "Qualifier not supported in block declarations".into(), )); } @@ -769,7 +810,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { break; } - let ty = self.parse_type_non_void()?; + let ty = self.parse_type_non_void()?.0; let name = self.expect_ident()?.0; self.expect(TokenValue::Semicolon)?; @@ -1052,7 +1093,6 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let pointer = self.parse_unary(ctx)?; let start_meta = pointer.meta.clone(); - // TODO: More assign symbols match self.expect_peek()?.value { TokenValue::Assign => { self.bump()?; @@ -1202,9 +1242,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.bump()?; let value = { let expr = self.parse_expression(ctx)?; + let meta = expr.meta.clone(); let root = ctx.lower(self.program, expr, false, body)?; - let constant = - self.program.solve_constant(&ctx.expressions, root)?; + let constant = self.program.solve_constant( + &ctx.expressions, + root, + meta.clone(), + )?; match self.program.module.constants[constant].inner { ConstantInner::Scalar { @@ -1217,6 +1261,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } => int as i32, _ => { return Err(ErrorKind::SemanticError( + meta, "Case values can only be integers".into(), )) } @@ -1247,11 +1292,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }) } TokenValue::Default => { - self.bump()?; + let Token { meta, .. } = self.bump()?; self.expect(TokenValue::Colon)?; if !default.is_empty() { return Err(ErrorKind::SemanticError( + meta, "Can only have one default case per switch statement".into(), )); } @@ -1353,16 +1399,22 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { if self.bump_if(TokenValue::Semicolon).is_none() { let expr = if self.peek_type_name() || self.peek_type_qualifier() { let qualifiers = self.parse_type_qualifiers()?; - let ty = self.parse_type_non_void()?; + let (ty, meta) = self.parse_type_non_void()?; let name = self.expect_ident()?.0; self.expect(TokenValue::Assign)?; - let value = self.parse_initializer(ty, ctx, &mut block)?; + let (value, end_meta) = self.parse_initializer(ty, ctx, &mut block)?; - let pointer = - self.program - .add_local_var(ctx, &qualifiers, ty, name, None)?; + let decl = VarDeclaration { + qualifiers: &qualifiers, + ty, + name, + init: None, + meta: meta.union(&end_meta), + }; + + let pointer = self.program.add_local_var(ctx, decl)?; block.push(Statement::Store { pointer, value }); @@ -1467,7 +1519,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { loop { if self.peek_type_name() || self.peek_parameter_qualifier() { parameters.push(self.parse_parameter_qualifier()); - let ty = self.parse_type_non_void()?; + let ty = self.parse_type_non_void()?.0; match self.expect_peek()?.value { TokenValue::Comma => { @@ -1511,14 +1563,23 @@ struct DeclarationContext<'ctx, 'fun> { impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { fn add_var( &mut self, + program: &mut Program, ty: Handle, name: String, init: Option>, - program: &mut Program, + meta: SourceMetadata, ) -> Result> { + let decl = VarDeclaration { + qualifiers: &self.qualifiers, + ty, + name, + init, + meta, + }; + match self.external { - true => program.add_global_var(self.ctx, &self.qualifiers, ty, name, init), - false => program.add_local_var(self.ctx, &self.qualifiers, ty, name, init), + true => program.add_global_var(self.ctx, decl), + false => program.add_local_var(self.ctx, decl), } } } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 066a3a07c..cb8844e47 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -329,7 +329,10 @@ fn functions() { ) .err() .unwrap(), - ErrorKind::SemanticError("Function already defined".into()) + ErrorKind::SemanticError( + SourceMetadata { chars: 134..152 }, + "Function already defined".into() + ) ); println!(); diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index c791003c6..8e81de31c 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -12,7 +12,7 @@ pub struct SourceMetadata { impl SourceMetadata { pub fn union(&self, other: &Self) -> Self { SourceMetadata { - chars: (self.chars.start.min(other.chars.start))..(self.chars.end.max(self.chars.end)), + chars: (self.chars.start.min(other.chars.start))..(self.chars.end.max(other.chars.end)), } } } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index b7ff88770..b4dcda53b 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -7,6 +7,14 @@ use super::ast::*; use super::error::ErrorKind; use super::token::SourceMetadata; +pub struct VarDeclaration<'a> { + pub qualifiers: &'a [TypeQualifier], + pub ty: Handle, + pub name: String, + pub init: Option>, + pub meta: SourceMetadata, +} + impl Program<'_> { pub fn lookup_variable( &mut self, @@ -110,7 +118,7 @@ impl Program<'_> { name: &str, meta: SourceMetadata, ) -> Result, ErrorKind> { - match *self.resolve_type(context, expression)? { + match *self.resolve_type(context, expression, meta.clone())? { TypeInner::Struct { ref members, .. } => { let index = members .iter() @@ -170,6 +178,7 @@ impl Program<'_> { 4 => VectorSize::Quad, _ => { return Err(ErrorKind::SemanticError( + meta, format!( "Bad swizzle size for \"{:?}\": {:?}", name, v @@ -185,11 +194,13 @@ impl Program<'_> { } } else { Err(ErrorKind::SemanticError( + meta, format!("Invalid swizzle for vector \"{}\"", name).into(), )) } } _ => Err(ErrorKind::SemanticError( + meta, format!("Can't lookup field on this type \"{}\"", name).into(), )), } @@ -198,10 +209,13 @@ impl Program<'_> { pub fn add_global_var( &mut self, ctx: &mut Context, - qualifiers: &[TypeQualifier], - ty: Handle, - name: String, - init: Option>, + VarDeclaration { + qualifiers, + ty, + name, + init, + meta, + }: VarDeclaration, ) -> Result, ErrorKind> { let mut storage = StorageQualifier::StorageClass(StorageClass::Function); let mut interpolation = None; @@ -215,6 +229,7 @@ impl Program<'_> { TypeQualifier::StorageQualifier(s) => { if StorageQualifier::StorageClass(StorageClass::Function) != storage { return Err(ErrorKind::SemanticError( + meta, "Cannot use more than one storage qualifier per declaration".into(), )); } @@ -224,6 +239,7 @@ impl Program<'_> { TypeQualifier::Interpolation(i) => { if interpolation.is_some() { return Err(ErrorKind::SemanticError( + meta, "Cannot use more than one storage qualifier per declaration".into(), )); } @@ -233,6 +249,7 @@ impl Program<'_> { TypeQualifier::ResourceBinding(ref r) => { if binding.is_some() { return Err(ErrorKind::SemanticError( + meta, "Cannot use more than one storage qualifier per declaration".into(), )); } @@ -242,6 +259,7 @@ impl Program<'_> { TypeQualifier::Location(l) => { if location.is_some() { return Err(ErrorKind::SemanticError( + meta, "Cannot use more than one storage qualifier per declaration".into(), )); } @@ -251,6 +269,7 @@ impl Program<'_> { TypeQualifier::Sampling(s) => { if sampling.is_some() { return Err(ErrorKind::SemanticError( + meta, "Cannot use more than one storage qualifier per declaration".into(), )); } @@ -260,6 +279,7 @@ impl Program<'_> { TypeQualifier::Layout(ref l) => { if layout.is_some() { return Err(ErrorKind::SemanticError( + meta, "Cannot use more than one storage qualifier per declaration".into(), )); } @@ -268,6 +288,7 @@ impl Program<'_> { } TypeQualifier::EarlyFragmentTests => { return Err(ErrorKind::SemanticError( + meta, "Cannot set early fragment tests on a declaration".into(), )); } @@ -276,12 +297,14 @@ impl Program<'_> { if binding.is_some() && storage != StorageQualifier::StorageClass(StorageClass::Uniform) { return Err(ErrorKind::SemanticError( + meta, "binding requires uniform or buffer storage qualifier".into(), )); } if (sampling.is_some() || interpolation.is_some()) && location.is_none() { return Err(ErrorKind::SemanticError( + meta, "Sampling and interpolation qualifiers can only be used in in/out variables".into(), )); } @@ -309,7 +332,7 @@ impl Program<'_> { .append(Expression::AccessIndex { base, index })); } else if let StorageQualifier::Const = storage { let handle = init.ok_or_else(|| { - ErrorKind::SemanticError("Constant must have a initializer".into()) + ErrorKind::SemanticError(meta, "Constant must have a initializer".into()) })?; self.lookup_constants.insert(name, handle); @@ -341,10 +364,13 @@ impl Program<'_> { pub fn add_local_var( &mut self, ctx: &mut Context, - qualifiers: &[TypeQualifier], - ty: Handle, - name: String, - init: Option>, + VarDeclaration { + qualifiers, + ty, + name, + init, + meta, + }: VarDeclaration, ) -> Result, ErrorKind> { #[cfg(feature = "glsl-validate")] if ctx.lookup_local_var_current_scope(&name).is_some() { @@ -361,6 +387,7 @@ impl Program<'_> { } _ => { return Err(ErrorKind::SemanticError( + meta, "Qualifier not supported in locals".into(), )); } From 7ef095881b8e37e94bc513471b750d2cde485366 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 15:53:20 +0100 Subject: [PATCH 0864/2212] [glsl-in]Replace WrongNumberArg with SemanticError --- src/front/glsl/error.rs | 16 ++++++++++++++-- src/front/glsl/functions.rs | 29 +++++++++++++++++------------ 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index d955f1a82..705b4a798 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -26,8 +26,6 @@ pub enum ErrorKind { VariableAlreadyDeclared(String), #[error("{1}")] SemanticError(SourceMetadata, Cow<'static, str>), - #[error("Function \"{0}\" expects {1} arguments, got {2}")] - WrongNumberArgs(String, usize, usize), } impl ErrorKind { @@ -44,6 +42,20 @@ impl ErrorKind { _ => None, } } + + pub(crate) fn wrong_function_args( + name: String, + expected: usize, + got: usize, + meta: SourceMetadata, + ) -> Self { + let msg = format!( + "Function \"{}\" expects {} arguments, got {}", + name, expected, got + ); + + ErrorKind::SemanticError(meta, msg.into()) + } } #[derive(Debug, Error)] diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index f7766416e..d210aa96c 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -86,14 +86,14 @@ impl Program<'_> { match name.as_str() { "sampler2D" => { if args.len() != 2 { - return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } ctx.samplers.insert(args[0], args[1]); Ok(args[0]) } "texture" => { if args.len() != 2 { - return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } if let Some(sampler) = ctx.samplers.get(&args[0]).copied() { Ok(ctx.expressions.append(Expression::ImageSample { @@ -111,7 +111,7 @@ impl Program<'_> { } "textureLod" => { if args.len() != 3 { - return Err(ErrorKind::WrongNumberArgs(name, 3, args.len())); + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } if let Some(sampler) = ctx.samplers.get(&args[0]).copied() { Ok(ctx.expressions.append(Expression::ImageSample { @@ -134,7 +134,7 @@ impl Program<'_> { | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" | "normalize" => { if args.len() != 1 { - return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); + return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); } Ok(ctx.expressions.append(Expression::Math { fun: match name.as_str() { @@ -162,7 +162,7 @@ impl Program<'_> { } "pow" | "dot" | "max" => { if args.len() != 2 { - return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } Ok(ctx.expressions.append(Expression::Math { fun: match name.as_str() { @@ -178,7 +178,7 @@ impl Program<'_> { } "mix" | "clamp" => { if args.len() != 3 { - return Err(ErrorKind::WrongNumberArgs(name, 3, args.len())); + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } Ok(ctx.expressions.append(Expression::Math { fun: match name.as_str() { @@ -194,7 +194,7 @@ impl Program<'_> { "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" | "notEqual" => { if args.len() != 2 { - return Err(ErrorKind::WrongNumberArgs(name, 2, args.len())); + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } Ok(ctx.expressions.append(Expression::Binary { op: match name.as_str() { @@ -211,13 +211,17 @@ impl Program<'_> { })) } "isinf" => { - self.parse_relational_fun(ctx, name, &args, RelationalFunction::IsInf) + self.parse_relational_fun(ctx, name, &args, RelationalFunction::IsInf, meta) } "isnan" => { - self.parse_relational_fun(ctx, name, &args, RelationalFunction::IsNan) + self.parse_relational_fun(ctx, name, &args, RelationalFunction::IsNan, meta) + } + "all" => { + self.parse_relational_fun(ctx, name, &args, RelationalFunction::All, meta) + } + "any" => { + self.parse_relational_fun(ctx, name, &args, RelationalFunction::Any, meta) } - "all" => self.parse_relational_fun(ctx, name, &args, RelationalFunction::All), - "any" => self.parse_relational_fun(ctx, name, &args, RelationalFunction::Any), _ => { let sig = FunctionSignature { name, @@ -267,9 +271,10 @@ impl Program<'_> { name: String, args: &[Handle], fun: RelationalFunction, + meta: SourceMetadata, ) -> Result, ErrorKind> { if args.len() != 1 { - return Err(ErrorKind::WrongNumberArgs(name, 1, args.len())); + return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); } Ok(ctx.expressions.append(Expression::Relational { From e4bc844ba0306cfeb39f6b4aa0916cadd18fa6e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 16:27:09 +0100 Subject: [PATCH 0865/2212] [glsl-in] return error in constant math functions --- src/front/glsl/ast.rs | 4 +--- src/front/glsl/constants.rs | 6 +++++- src/front/glsl/error.rs | 11 ++++++++++- src/front/glsl/parser.rs | 2 +- 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index ea0644939..7c67ddac5 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -153,9 +153,7 @@ impl<'a> Program<'a> { constants: &mut self.module.constants, }; - solver - .solve(root) - .map_err(|_| ErrorKind::SemanticError(meta, "Can't solve constant".into())) + solver.solve(root).map_err(|e| (meta, e).into()) } pub fn function_args_prelude(&self) -> (Vec, Vec) { diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 1df4a9576..1143b90f3 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -51,6 +51,8 @@ pub enum ConstantSolvingError { InvalidBinaryOpArgs, #[error("Splat/swizzle type is not registered")] DestinationTypeNotFound, + #[error("Not implemented: {0}")] + NotImplemented(String), } impl<'a> ConstantSolver<'a> { @@ -152,7 +154,9 @@ impl<'a> ConstantSolver<'a> { self.binary_op(op, left_constant, right_constant) } - Expression::Math { .. } => todo!(), + Expression::Math { fun, .. } => { + Err(ConstantSolvingError::NotImplemented(format!("{:?}", fun))) + } Expression::As { convert, expr, diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 705b4a798..8ae98dd29 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -1,4 +1,7 @@ -use super::token::{SourceMetadata, Token}; +use super::{ + constants::ConstantSolvingError, + token::{SourceMetadata, Token}, +}; use std::borrow::Cow; use thiserror::Error; @@ -58,6 +61,12 @@ impl ErrorKind { } } +impl From<(SourceMetadata, ConstantSolvingError)> for ErrorKind { + fn from((meta, err): (SourceMetadata, ConstantSolvingError)) -> Self { + ErrorKind::SemanticError(meta, err.to_string().into()) + } +} + #[derive(Debug, Error)] #[error("{kind}")] pub struct ParseError { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 13a82cd97..a3debee8c 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -499,7 +499,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let init = self .bump_if(TokenValue::Assign) - .map(|_| { + .map::, _>(|_| { let (expr, init_meta) = self.parse_initializer(ty, ctx.ctx, ctx.body)?; meta = meta.union(&init_meta); Ok((expr, init_meta)) From 9ddca9cef5c1ea480469d20fc16d472182bce1e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 18:42:01 +0100 Subject: [PATCH 0866/2212] [glsl-in] Fix input/output handling Previously we passed a struct with the input bindings and just ignored the outputs. Now we handle them the same way we do with builtins, by creating function local globals that are read and written in a wrapper entry point. --- src/front/glsl/ast.rs | 47 ++----------------- src/front/glsl/functions.rs | 83 +++++++++++++++++++++------------- src/front/glsl/parser.rs | 4 +- src/front/glsl/parser_tests.rs | 15 ++++++ src/front/glsl/variables.rs | 82 ++++++++++----------------------- 5 files changed, 96 insertions(+), 135 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 7c67ddac5..5da25fbf5 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,6 +1,6 @@ use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind, SourceMetadata}; use crate::{ - proc::ResolveContext, Arena, BinaryOperator, Block, BuiltIn, Constant, Expression, FastHashMap, + proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, TypeInner, UnaryOperator, @@ -9,7 +9,6 @@ use crate::{ #[derive(Debug)] pub enum GlobalLookup { Variable(Handle), - InOutSelect(u32), BlockSelect(Handle, u32), } @@ -38,19 +37,14 @@ pub struct Program<'a> { pub lookup_global_variables: FastHashMap, pub lookup_constants: FastHashMap>, - pub built_ins: Vec<(BuiltIn, Handle)>, + pub entry_args: Vec<(Binding, bool, Handle)>, pub entries: Vec<(String, ShaderStage, Handle)>, - pub input_struct: Handle, - pub output_struct: Handle, - pub module: Module, } impl<'a> Program<'a> { pub fn new(entry_points: &'a FastHashMap) -> Program<'a> { - let mut module = Module::default(); - Program { version: 0, profile: Profile::Core, @@ -61,27 +55,10 @@ impl<'a> Program<'a> { lookup_global_variables: FastHashMap::default(), lookup_constants: FastHashMap::default(), - built_ins: Vec::new(), + entry_args: Vec::new(), entries: Vec::new(), - input_struct: module.types.append(Type { - name: None, - inner: TypeInner::Struct { - level: crate::StructLevel::Root, - members: Vec::new(), - span: 0, - }, - }), - output_struct: module.types.append(Type { - name: None, - inner: TypeInner::Struct { - level: crate::StructLevel::Root, - members: Vec::new(), - span: 0, - }, - }), - - module, + module: Module::default(), } } @@ -155,17 +132,6 @@ impl<'a> Program<'a> { solver.solve(root).map_err(|e| (meta, e).into()) } - - pub fn function_args_prelude(&self) -> (Vec, Vec) { - ( - vec![FunctionArgument { - name: None, - ty: self.input_struct, - binding: None, - }], - vec![ParameterQualifier::In], - ) - } } #[derive(Debug, PartialEq)] @@ -223,11 +189,6 @@ impl<'function> Context<'function> { self.lookup_global_var_exps.get(name).cloned().or_else(|| { let expr = match *program.lookup_global_variables.get(name)? { GlobalLookup::Variable(v) => Expression::GlobalVariable(v), - GlobalLookup::InOutSelect(index) => { - let base = self.expressions.append(Expression::FunctionArgument(0)); - - Expression::AccessIndex { base, index } - } GlobalLookup::BlockSelect(handle, index) => { let base = self.expressions.append(Expression::GlobalVariable(handle)); diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index d210aa96c..be4fcfca6 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,8 +1,8 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Binding, Block, BuiltIn, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, MathFunction, - RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, StorageClass, Type, - TypeInner, + RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, StorageClass, + StructMember, Type, TypeInner, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; @@ -223,14 +223,15 @@ impl Program<'_> { self.parse_relational_fun(ctx, name, &args, RelationalFunction::Any, meta) } _ => { - let sig = FunctionSignature { - name, - parameters: args - .iter() - .zip(raw_args.iter().map(|e| e.meta.clone())) - .map(|(e, meta)| self.resolve_handle(ctx, *e, meta)) - .collect::>()?, - }; + let mut parameters = Vec::new(); + + for (e, meta) in args.iter().zip(raw_args.iter().map(|e| e.meta.clone())) { + let handle = self.resolve_handle(ctx, *e, meta)?; + + parameters.push(handle) + } + + let sig = FunctionSignature { name, parameters }; let function = self .lookup_function @@ -390,20 +391,19 @@ impl Program<'_> { let mut expressions = Arena::new(); let mut body = Vec::new(); - arguments.push(FunctionArgument { - name: None, - ty: self.input_struct, - binding: None, - }); + for (binding, input, handle) in self.entry_args.iter().cloned() { + match binding { + Binding::Location { .. } if !input => continue, + _ => {} + } - for (built_in, handle) in self.built_ins.iter().copied() { let ty = self.module.global_variables[handle].ty; let arg = arguments.len() as u32; arguments.push(FunctionArgument { name: None, ty, - binding: Some(Binding::BuiltIn(built_in)), + binding: Some(binding), }); let pointer = expressions.append(Expression::GlobalVariable(handle)); @@ -412,25 +412,49 @@ impl Program<'_> { body.push(Statement::Store { pointer, value }); } - let res = expressions.append(Expression::Call(function)); - body.push(Statement::Call { function, - arguments: vec![expressions.append(Expression::FunctionArgument(0))], - result: Some(res), + arguments: Vec::new(), + result: None, }); - for (i, (built_in, handle)) in self.built_ins.iter().copied().enumerate() { - if !should_write(built_in, stage) { - continue; + let mut span = 0; + let mut members = Vec::new(); + let mut components = Vec::new(); + + for (binding, input, handle) in self.entry_args.iter().cloned() { + match binding { + Binding::Location { .. } if input => continue, + Binding::BuiltIn(builtin) if !should_write(builtin, stage) => continue, + _ => {} } - let value = expressions.append(Expression::GlobalVariable(handle)); - let pointer = expressions.append(Expression::FunctionArgument(i as u32 + 1)); + let ty = self.module.global_variables[handle].ty; - body.push(Statement::Store { pointer, value }); + members.push(StructMember { + name: None, + ty, + binding: Some(binding), + offset: span, + }); + + span += self.module.types[ty].inner.span(&self.module.constants); + + let pointer = expressions.append(Expression::GlobalVariable(handle)); + let load = expressions.append(Expression::Load { pointer }); + components.push(load) } + let ty = self.module.types.append(Type { + name: None, + inner: TypeInner::Struct { + top_level: true, + members, + span, + }, + }); + + let res = expressions.append(Expression::Compose { ty, components }); body.push(Statement::Return { value: Some(res) }); self.module.entry_points.push(EntryPoint { @@ -443,10 +467,7 @@ impl Program<'_> { arguments, expressions, body, - result: Some(FunctionResult { - ty: self.output_struct, - binding: None, - }), + result: Some(FunctionResult { ty, binding: None }), ..Default::default() }, }); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index a3debee8c..bd90a66e3 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -569,8 +569,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let result = ty.map(|ty| FunctionResult { ty, binding: None }); let mut expressions = Arena::new(); let mut local_variables = Arena::new(); - let (mut arguments, mut parameters) = - self.program.function_args_prelude(); + let mut arguments = Vec::new(); + let mut parameters = Vec::new(); let mut context = Context::new( &mut expressions, diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index cb8844e47..3a165ab33 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -337,6 +337,21 @@ fn functions() { println!(); + let _program = parse_program( + r#" + # version 450 + float callee(uint q) { + return float(q); + } + + float caller() { + callee(1u); + } + "#, + &entry_points, + ) + .unwrap(); + // Nested function call let _program = parse_program( r#" diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index b4dcda53b..7985633c2 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,6 +1,6 @@ use crate::{ Binding, BuiltIn, Constant, Expression, GlobalVariable, Handle, LocalVariable, ScalarKind, - StorageAccess, StorageClass, StructMember, Type, TypeInner, VectorSize, + StorageAccess, StorageClass, Type, TypeInner, VectorSize, }; use super::ast::*; @@ -50,7 +50,8 @@ impl Program<'_> { storage_access: StorageAccess::all(), }); - self.built_ins.push((BuiltIn::Position, handle)); + self.entry_args + .push((Binding::BuiltIn(BuiltIn::Position), true, handle)); self.lookup_global_variables .insert(name.into(), GlobalLookup::Variable(handle)); @@ -75,7 +76,8 @@ impl Program<'_> { storage_access: StorageAccess::all(), }); - self.built_ins.push((BuiltIn::VertexIndex, handle)); + self.entry_args + .push((Binding::BuiltIn(BuiltIn::VertexIndex), true, handle)); self.lookup_global_variables .insert(name.into(), GlobalLookup::Variable(handle)); @@ -100,7 +102,8 @@ impl Program<'_> { storage_access: StorageAccess::all(), }); - self.built_ins.push((BuiltIn::InstanceIndex, handle)); + self.entry_args + .push((Binding::BuiltIn(BuiltIn::InstanceIndex), true, handle)); self.lookup_global_variables .insert(name.into(), GlobalLookup::Variable(handle)); @@ -312,24 +315,29 @@ impl Program<'_> { if let Some(location) = location { let input = StorageQualifier::Input == storage; - let index = self.add_member( - input, - Some(name.clone()), + let handle = self.module.global_variables.append(GlobalVariable { + name: Some(name.clone()), + class: StorageClass::Function, + binding: None, ty, - Some(Binding::Location { + init, + storage_access: StorageAccess::all(), + }); + + self.entry_args.push(( + Binding::Location { location, interpolation, sampling, - }), - ); + }, + input, + handle, + )); self.lookup_global_variables - .insert(name, GlobalLookup::InOutSelect(index)); + .insert(name, GlobalLookup::Variable(handle)); - let base = ctx.expressions.append(Expression::FunctionArgument(0)); - return Ok(ctx - .expressions - .append(Expression::AccessIndex { base, index })); + return Ok(ctx.expressions.append(Expression::GlobalVariable(handle))); } else if let StorageQualifier::Const = storage { let handle = init.ok_or_else(|| { ErrorKind::SemanticError(meta, "Constant must have a initializer".into()) @@ -405,48 +413,4 @@ impl Program<'_> { Ok(expr) } - - fn add_member( - &mut self, - input: bool, - name: Option, - ty: Handle, - binding: Option, - ) -> u32 { - let handle = match input { - true => self.input_struct, - false => self.output_struct, - }; - - let offset = if let TypeInner::Struct { ref members, .. } = self.module.types[handle].inner - { - members - .last() - .map(|member| { - member.offset - + self.module.types[member.ty] - .inner - .span(&self.module.constants) - }) - .unwrap_or(0) - } else { - 0 - }; - - if let TypeInner::Struct { - ref mut members, .. - } = self.module.types.get_mut(handle).inner - { - members.push(StructMember { - name, - ty, - binding, - offset, - }); - - members.len() as u32 - 1 - } else { - unreachable!() - } - } } From ea544a388fa8e7a3b8fd2b7c652760bfcdf0e6de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 19:12:24 +0100 Subject: [PATCH 0867/2212] [glsl-in] Handle constant qualifier in declaration --- src/front/glsl/ast.rs | 32 +++++++++++++++++++++++++++----- src/front/glsl/parser.rs | 8 +++++--- src/front/glsl/variables.rs | 16 +++++++++++----- 3 files changed, 43 insertions(+), 13 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 5da25fbf5..c570fd79b 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -200,6 +200,8 @@ impl<'function> Context<'function> { let var = VariableReference { expr, load: Some(self.expressions.append(Expression::Load { pointer: expr })), + // TODO: respect constant qualifier + mutable: true, }; self.lookup_global_var_exps.insert(name.into(), var.clone()); @@ -218,7 +220,11 @@ impl<'function> Context<'function> { .expressions .append(Expression::Constant(*program.lookup_constants.get(name)?)); - let var = VariableReference { expr, load: None }; + let var = VariableReference { + expr, + load: None, + mutable: false, + }; self.lookup_constant_exps.insert(name.into(), var.clone()); @@ -236,7 +242,7 @@ impl<'function> Context<'function> { } /// Add variable to current scope - pub fn add_local_var(&mut self, name: String, expr: Handle) { + pub fn add_local_var(&mut self, name: String, expr: Handle, mutable: bool) { if let Some(current) = self.scopes.last_mut() { let load = self.expressions.append(Expression::Load { pointer: expr }); @@ -245,13 +251,14 @@ impl<'function> Context<'function> { VariableReference { expr, load: Some(load), + mutable, }, ); } } /// Add function argument to current scope - pub fn add_function_arg(&mut self, name: Option, ty: Handle) { + pub fn add_function_arg(&mut self, name: Option, ty: Handle, mutable: bool) { let index = self.arguments.len(); self.arguments.push(FunctionArgument { name: name.clone(), @@ -265,7 +272,14 @@ impl<'function> Context<'function> { .expressions .append(Expression::FunctionArgument(index as u32)); - (*current).insert(name, VariableReference { expr, load: None }); + (*current).insert( + name, + VariableReference { + expr, + load: None, + mutable, + }, + ); } } } @@ -347,6 +361,13 @@ impl<'function> Context<'function> { } ExprKind::Variable(var) => { if lhs { + if !var.mutable { + return Err(ErrorKind::SemanticError( + expr.meta, + "Variable cannot be used in LHS position".into(), + )); + } + var.expr } else { var.load.unwrap_or(var.expr) @@ -392,6 +413,7 @@ impl<'function> Context<'function> { pub struct VariableReference { pub expr: Handle, pub load: Option>, + pub mutable: bool, } #[derive(Debug, Clone)] @@ -469,7 +491,7 @@ pub enum StructLayout { Std140, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq)] pub enum ParameterQualifier { In, Out, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index bd90a66e3..727d010b5 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1518,13 +1518,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ) -> Result<()> { loop { if self.peek_type_name() || self.peek_parameter_qualifier() { - parameters.push(self.parse_parameter_qualifier()); + let qualifier = self.parse_parameter_qualifier(); + let mutable = qualifier != ParameterQualifier::Const; + parameters.push(qualifier); let ty = self.parse_type_non_void()?.0; match self.expect_peek()?.value { TokenValue::Comma => { self.bump()?; - context.add_function_arg(None, ty); + context.add_function_arg(None, ty, mutable); continue; } TokenValue::Identifier(_) => { @@ -1533,7 +1535,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let size = self.parse_array_specifier()?; let ty = self.maybe_array(ty, size); - context.add_function_arg(Some(name), ty); + context.add_function_arg(Some(name), ty, mutable); if self.bump_if(TokenValue::Comma).is_some() { continue; diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 7985633c2..7aaff1d7a 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -385,13 +385,19 @@ impl Program<'_> { return Err(ErrorKind::VariableAlreadyDeclared(name)); } - // FIXME: this should be removed after - // fixing the lack of constant qualifier support - #[allow(clippy::never_loop)] + let mut mutable = true; + for qualifier in qualifiers { match *qualifier { TypeQualifier::StorageQualifier(StorageQualifier::Const) => { - return Err(ErrorKind::NotImplemented("const qualifier")); + if !mutable { + return Err(ErrorKind::SemanticError( + meta, + "Cannot use more than one constant qualifier per declaration".into(), + )); + } + + mutable = false; } _ => { return Err(ErrorKind::SemanticError( @@ -409,7 +415,7 @@ impl Program<'_> { }); let expr = ctx.expressions.append(Expression::LocalVariable(handle)); - ctx.add_local_var(name, expr); + ctx.add_local_var(name, expr, mutable); Ok(expr) } From ba4b7ba3e26506e2305961705c89ad47bc029557 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 May 2021 19:40:54 +0100 Subject: [PATCH 0868/2212] [glsl-in] Restrict comparisons The expressions on both sides must now have the same dimensions otherwise a semantic error is returned. --- src/front/glsl/ast.rs | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index c570fd79b..f18db8a31 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -322,32 +322,36 @@ impl<'function> Context<'function> { if let BinaryOperator::Equal | BinaryOperator::NotEqual = op { let equals = op == BinaryOperator::Equal; - let left_is_vector = match *program.resolve_type(self, left, left_meta)? { - crate::TypeInner::Vector { .. } => true, - _ => false, - }; + let (left_is_vector, left_dims) = + match *program.resolve_type(self, left, left_meta)? { + crate::TypeInner::Vector { .. } => (true, 1), + crate::TypeInner::Matrix { .. } => (false, 2), + _ => (false, 0), + }; - let right_is_vector = match *program.resolve_type(self, right, right_meta)? { - crate::TypeInner::Vector { .. } => true, - _ => false, - }; + let (right_is_vector, right_dims) = + match *program.resolve_type(self, right, right_meta)? { + crate::TypeInner::Vector { .. } => (true, 1), + crate::TypeInner::Matrix { .. } => (false, 2), + _ => (false, 0), + }; let (op, fun) = match equals { true => (BinaryOperator::Equal, RelationalFunction::All), false => (BinaryOperator::NotEqual, RelationalFunction::Any), }; - let expr = self + let argument = self .expressions .append(Expression::Binary { op, left, right }); - if left_is_vector && right_is_vector { - self.expressions.append(Expression::Relational { - fun, - argument: expr, - }) + if left_dims != right_dims { + return Err(ErrorKind::SemanticError(expr.meta, "Cannot compare".into())); + } else if left_is_vector && right_is_vector { + self.expressions + .append(Expression::Relational { fun, argument }) } else { - expr + argument } } else { self.expressions From 9390515595250a354cbe561533975e3c1ec1ff36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 17 May 2021 11:20:29 +0100 Subject: [PATCH 0869/2212] [glsl-in] Use an arena for the HirExprs --- src/front/glsl/ast.rs | 99 ++++++++++--------- src/front/glsl/functions.rs | 71 +++++++------- src/front/glsl/parser.rs | 189 +++++++++++++++++------------------- 3 files changed, 176 insertions(+), 183 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index f18db8a31..845f06ac6 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -151,6 +151,8 @@ pub struct Context<'function> { pub lookup_constant_exps: FastHashMap, pub typifier: Typifier, pub samplers: FastHashMap, Handle>, + + pub hir_exprs: Arena, } impl<'function> Context<'function> { @@ -169,6 +171,8 @@ impl<'function> Context<'function> { lookup_constant_exps: FastHashMap::default(), typifier: Typifier::new(), samplers: FastHashMap::default(), + + hir_exprs: Arena::default(), } } @@ -296,29 +300,30 @@ impl<'function> Context<'function> { pub fn lower( &mut self, program: &mut Program, - expr: Expr, + expr: Handle, lhs: bool, body: &mut Block, - ) -> Result, ErrorKind> { - Ok(match expr.kind { - ExprKind::Access { base, index } => { - let base = self.lower(program, *base, lhs, body)?; - let index = self.lower(program, *index, false, body)?; + ) -> Result<(Handle, SourceMetadata), ErrorKind> { + let HirExpr { kind, meta } = self.hir_exprs[expr].clone(); + + let handle = match kind { + HirExprKind::Access { base, index } => { + let base = self.lower(program, base, lhs, body)?.0; + let index = self.lower(program, index, false, body)?.0; self.expressions.append(Expression::Access { base, index }) } - ExprKind::Select { base, field } => { - let base = self.lower(program, *base, lhs, body)?; + HirExprKind::Select { base, field } => { + let base = self.lower(program, base, lhs, body)?.0; - program.field_selection(self, base, &field, expr.meta)? + program.field_selection(self, base, &field, meta.clone())? } - ExprKind::Constant(constant) if !lhs => { + HirExprKind::Constant(constant) if !lhs => { self.expressions.append(Expression::Constant(constant)) } - ExprKind::Binary { left, op, right } if !lhs => { - let (left_meta, right_meta) = (left.meta.clone(), right.meta.clone()); - let left = self.lower(program, *left, false, body)?; - let right = self.lower(program, *right, false, body)?; + HirExprKind::Binary { left, op, right } if !lhs => { + let (left, left_meta) = self.lower(program, left, false, body)?; + let (right, right_meta) = self.lower(program, right, false, body)?; if let BinaryOperator::Equal | BinaryOperator::NotEqual = op { let equals = op == BinaryOperator::Equal; @@ -346,7 +351,7 @@ impl<'function> Context<'function> { .append(Expression::Binary { op, left, right }); if left_dims != right_dims { - return Err(ErrorKind::SemanticError(expr.meta, "Cannot compare".into())); + return Err(ErrorKind::SemanticError(meta, "Cannot compare".into())); } else if left_is_vector && right_is_vector { self.expressions .append(Expression::Relational { fun, argument }) @@ -358,16 +363,16 @@ impl<'function> Context<'function> { .append(Expression::Binary { left, op, right }) } } - ExprKind::Unary { op, expr } if !lhs => { - let expr = self.lower(program, *expr, false, body)?; + HirExprKind::Unary { op, expr } if !lhs => { + let expr = self.lower(program, expr, false, body)?.0; self.expressions.append(Expression::Unary { op, expr }) } - ExprKind::Variable(var) => { + HirExprKind::Variable(var) => { if lhs { if !var.mutable { return Err(ErrorKind::SemanticError( - expr.meta, + meta, "Variable cannot be used in LHS position".into(), )); } @@ -377,17 +382,17 @@ impl<'function> Context<'function> { var.load.unwrap_or(var.expr) } } - ExprKind::Call(call) if !lhs => { - program.function_call(self, body, call.kind, call.args, expr.meta)? + HirExprKind::Call(call) if !lhs => { + program.function_call(self, body, call.kind, &call.args, meta.clone())? } - ExprKind::Conditional { + HirExprKind::Conditional { condition, accept, reject, } if !lhs => { - let condition = self.lower(program, *condition, false, body)?; - let accept = self.lower(program, *accept, false, body)?; - let reject = self.lower(program, *reject, false, body)?; + let condition = self.lower(program, condition, false, body)?.0; + let accept = self.lower(program, accept, false, body)?.0; + let reject = self.lower(program, reject, false, body)?.0; self.expressions.append(Expression::Select { condition, @@ -395,9 +400,9 @@ impl<'function> Context<'function> { reject, }) } - ExprKind::Assign { tgt, value } if !lhs => { - let pointer = self.lower(program, *tgt, true, body)?; - let value = self.lower(program, *value, false, body)?; + HirExprKind::Assign { tgt, value } if !lhs => { + let pointer = self.lower(program, tgt, true, body)?.0; + let value = self.lower(program, value, false, body)?.0; body.push(Statement::Store { pointer, value }); @@ -405,11 +410,13 @@ impl<'function> Context<'function> { } _ => { return Err(ErrorKind::SemanticError( - expr.meta.clone(), - format!("{:?} cannot be in the left hand side", expr).into(), + meta, + format!("{:?} cannot be in the left hand side", self.hir_exprs[expr]).into(), )) } - }) + }; + + Ok((handle, meta)) } } @@ -421,41 +428,41 @@ pub struct VariableReference { } #[derive(Debug, Clone)] -pub struct Expr { - pub kind: ExprKind, +pub struct HirExpr { + pub kind: HirExprKind, pub meta: SourceMetadata, } #[derive(Debug, Clone)] -pub enum ExprKind { +pub enum HirExprKind { Access { - base: Box, - index: Box, + base: Handle, + index: Handle, }, Select { - base: Box, + base: Handle, field: String, }, Constant(Handle), Binary { - left: Box, + left: Handle, op: BinaryOperator, - right: Box, + right: Handle, }, Unary { op: UnaryOperator, - expr: Box, + expr: Handle, }, Variable(VariableReference), Call(FunctionCall), Conditional { - condition: Box, - accept: Box, - reject: Box, + condition: Handle, + accept: Handle, + reject: Handle, }, Assign { - tgt: Box, - value: Box, + tgt: Handle, + value: Handle, }, } @@ -479,7 +486,7 @@ pub enum FunctionCallKind { #[derive(Debug, Clone)] pub struct FunctionCall { pub kind: FunctionCallKind, - pub args: Vec, + pub args: Vec>, } #[derive(Debug, Clone, Copy, PartialEq)] diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index be4fcfca6..8f9882c3e 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -13,19 +13,18 @@ impl Program<'_> { ctx: &mut Context, body: &mut Block, fc: FunctionCallKind, - raw_args: Vec, + raw_args: &[Handle], meta: SourceMetadata, ) -> Result, ErrorKind> { let args: Vec<_> = raw_args - .clone() - .into_iter() - .map(|e| ctx.lower(self, e, false, body)) + .iter() + .map(|e| ctx.lower(self, *e, false, body)) .collect::>()?; match fc { FunctionCallKind::TypeConstructor(ty) => { let h = if args.len() == 1 { - let is_vec = match *self.resolve_type(ctx, args[0], raw_args[0].meta.clone())? { + let is_vec = match *self.resolve_type(ctx, args[0].0, args[0].1.clone())? { TypeInner::Vector { .. } => true, _ => false, }; @@ -34,14 +33,14 @@ impl Program<'_> { TypeInner::Vector { size, .. } if !is_vec => { ctx.expressions.append(Expression::Splat { size, - value: args[0], + value: args[0].0, }) } TypeInner::Scalar { kind, width } | TypeInner::Vector { kind, width, .. } => { ctx.expressions.append(Expression::As { kind, - expr: args[0], + expr: args[0].0, convert: Some(width), }) } @@ -52,7 +51,7 @@ impl Program<'_> { } => { let value = ctx.expressions.append(Expression::As { kind: ScalarKind::Float, - expr: args[0], + expr: args[0].0, convert: Some(width), }); @@ -76,7 +75,7 @@ impl Program<'_> { } else { ctx.expressions.append(Expression::Compose { ty, - components: args.to_vec(), + components: args.iter().map(|e| e.0).collect(), }) }; @@ -88,18 +87,18 @@ impl Program<'_> { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } - ctx.samplers.insert(args[0], args[1]); - Ok(args[0]) + ctx.samplers.insert(args[0].0, args[1].0); + Ok(args[0].0) } "texture" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } - if let Some(sampler) = ctx.samplers.get(&args[0]).copied() { + if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { Ok(ctx.expressions.append(Expression::ImageSample { - image: args[0], + image: args[0].0, sampler, - coordinate: args[1], + coordinate: args[1].0, array_index: None, //TODO offset: None, //TODO level: SampleLevel::Auto, @@ -113,14 +112,14 @@ impl Program<'_> { if args.len() != 3 { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } - if let Some(sampler) = ctx.samplers.get(&args[0]).copied() { + if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { Ok(ctx.expressions.append(Expression::ImageSample { - image: args[0], + image: args[0].0, sampler, - coordinate: args[1], + coordinate: args[1].0, array_index: None, //TODO offset: None, //TODO - level: SampleLevel::Exact(args[2]), + level: SampleLevel::Exact(args[2].0), depth_ref: None, })) } else { @@ -155,7 +154,7 @@ impl Program<'_> { "normalize" => MathFunction::Normalize, _ => unreachable!(), }, - arg: args[0], + arg: args[0].0, arg1: None, arg2: None, })) @@ -171,8 +170,8 @@ impl Program<'_> { "max" => MathFunction::Max, _ => unreachable!(), }, - arg: args[0], - arg1: Some(args[1]), + arg: args[0].0, + arg1: Some(args[1].0), arg2: None, })) } @@ -186,9 +185,9 @@ impl Program<'_> { "clamp" => MathFunction::Clamp, _ => unreachable!(), }, - arg: args[0], - arg1: Some(args[1]), - arg2: Some(args[2]), + arg: args[0].0, + arg1: Some(args[1].0), + arg2: Some(args[2].0), })) } "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" @@ -206,8 +205,8 @@ impl Program<'_> { "notEqual" => BinaryOperator::NotEqual, _ => unreachable!(), }, - left: args[0], - right: args[1], + left: args[0].0, + right: args[1].0, })) } "isinf" => { @@ -225,15 +224,15 @@ impl Program<'_> { _ => { let mut parameters = Vec::new(); - for (e, meta) in args.iter().zip(raw_args.iter().map(|e| e.meta.clone())) { - let handle = self.resolve_handle(ctx, *e, meta)?; + for (e, meta) in args { + let handle = self.resolve_handle(ctx, e, meta)?; parameters.push(handle) } let sig = FunctionSignature { name, parameters }; - let function = self + let fun = self .lookup_function .get(&sig) .ok_or_else(|| { @@ -246,16 +245,14 @@ impl Program<'_> { .clone(); let mut arguments = Vec::with_capacity(raw_args.len()); - for (qualifier, expr) in - function.parameters.iter().zip(raw_args.into_iter()) - { - let handle = ctx.lower(self, expr, qualifier.is_lhs(), body)?; + for (qualifier, expr) in fun.parameters.iter().zip(raw_args.iter()) { + let handle = ctx.lower(self, *expr, qualifier.is_lhs(), body)?.0; arguments.push(handle) } - let expression = ctx.expressions.append(Expression::Call(function.handle)); + let expression = ctx.expressions.append(Expression::Call(fun.handle)); body.push(crate::Statement::Call { - function: function.handle, + function: fun.handle, arguments, result: Some(expression), }); @@ -270,7 +267,7 @@ impl Program<'_> { &mut self, ctx: &mut Context, name: String, - args: &[Handle], + args: &[(Handle, SourceMetadata)], fun: RelationalFunction, meta: SourceMetadata, ) -> Result, ErrorKind> { @@ -280,7 +277,7 @@ impl Program<'_> { Ok(ctx.expressions.append(Expression::Relational { fun, - argument: args[0], + argument: args[0].0, })) } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 727d010b5..b7448818a 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,7 +1,7 @@ use super::{ ast::{ - Context, Expr, ExprKind, FunctionCall, FunctionCallKind, GlobalLookup, ParameterQualifier, - Profile, StorageQualifier, StructLayout, TypeQualifier, + Context, FunctionCall, FunctionCallKind, GlobalLookup, HirExpr, HirExprKind, + ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier, }, error::ErrorKind, lex::Lexer, @@ -325,8 +325,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut ctx = Context::new(&mut expressions, &mut locals, &mut arguments); let expr = self.parse_conditional(&mut ctx, None)?; - let meta = expr.meta.clone(); - let root = ctx.lower(self.program, expr, false, &mut Block::new())?; + let (root, meta) = ctx.lower(self.program, expr, false, &mut Block::new())?; Ok(( self.program @@ -435,10 +434,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { )) } else { let expr = self.parse_assignment(ctx)?; - let meta = expr.meta.clone(); - let root = ctx.lower(self.program, expr, false, body)?; - - Ok((root, meta)) + Ok(ctx.lower(self.program, expr, false, body)?) } } @@ -829,7 +825,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(span) } - fn parse_primary(&mut self, ctx: &mut Context) -> Result { + fn parse_primary(&mut self, ctx: &mut Context) -> Result> { let mut token = self.bump()?; let (width, value) = match token.value { @@ -863,17 +859,17 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { inner: ConstantInner::Scalar { width, value }, }); - Ok(Expr { - kind: ExprKind::Constant(handle), + Ok(ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Constant(handle), meta: token.meta, - }) + })) } fn parse_function_call_args( &mut self, ctx: &mut Context, meta: &mut SourceMetadata, - ) -> Result> { + ) -> Result>> { let mut args = Vec::new(); if let Some(token) = self.bump_if(TokenValue::RightParen) { *meta = meta.union(&token.meta); @@ -896,16 +892,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(args) } - fn parse_postfix(&mut self, ctx: &mut Context) -> Result { - let mut expr = match self.expect_peek()?.value { + fn parse_postfix(&mut self, ctx: &mut Context) -> Result> { + let mut base = match self.expect_peek()?.value { TokenValue::Identifier(_) => { let (name, mut meta) = self.expect_ident()?; - if self.bump_if(TokenValue::LeftParen).is_some() { + let expr = if self.bump_if(TokenValue::LeftParen).is_some() { let args = self.parse_function_call_args(ctx, &mut meta)?; - Expr { - kind: ExprKind::Call(FunctionCall { + HirExpr { + kind: HirExprKind::Call(FunctionCall { kind: FunctionCallKind::Function(name), args, }), @@ -917,11 +913,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { None => return Err(ErrorKind::UnknownVariable(meta, name)), }; - Expr { - kind: ExprKind::Variable(var), + HirExpr { + kind: HirExprKind::Variable(var), meta, } - } + }; + + ctx.hir_exprs.append(expr) } TokenValue::TypeName(_) => { let Token { value, mut meta } = self.bump()?; @@ -935,13 +933,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::LeftParen)?; let args = self.parse_function_call_args(ctx, &mut meta)?; - Expr { - kind: ExprKind::Call(FunctionCall { + ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Call(FunctionCall { kind: FunctionCallKind::TypeConstructor(handle), args, }), meta, - } + }) } _ => self.parse_primary(ctx)?, }; @@ -952,75 +950,69 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match value { TokenValue::LeftBracket => { - let index = Box::new(self.parse_expression(ctx)?); + let index = self.parse_expression(ctx)?; let end_meta = self.expect(TokenValue::RightBracket)?.meta; - expr = Expr { - kind: ExprKind::Access { - base: Box::new(expr), - index, - }, + base = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Access { base, index }, meta: meta.union(&end_meta), - } + }) } TokenValue::Dot => { let (field, end_meta) = self.expect_ident()?; - expr = Expr { - kind: ExprKind::Select { - base: Box::new(expr), - field, - }, + base = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Select { base, field }, meta: meta.union(&end_meta), - } + }) } _ => unreachable!(), } } - Ok(expr) + Ok(base) } - fn parse_unary(&mut self, ctx: &mut Context) -> Result { + fn parse_unary(&mut self, ctx: &mut Context) -> Result> { // TODO: prefix inc/dec - match self.expect_peek()?.value { + Ok(match self.expect_peek()?.value { TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { let Token { value, meta } = self.bump()?; let expr = self.parse_unary(ctx)?; - let end_meta = expr.meta.clone(); + let end_meta = ctx.hir_exprs[expr].meta.clone(); let kind = match value { - TokenValue::Dash => ExprKind::Unary { + TokenValue::Dash => HirExprKind::Unary { op: UnaryOperator::Negate, - expr: Box::new(expr), + expr, }, - TokenValue::Bang | TokenValue::Tilde => ExprKind::Unary { + TokenValue::Bang | TokenValue::Tilde => HirExprKind::Unary { op: UnaryOperator::Not, - expr: Box::new(expr), + expr, }, _ => return Ok(expr), }; - Ok(Expr { + ctx.hir_exprs.append(HirExpr { kind, meta: meta.union(&end_meta), }) } - _ => self.parse_postfix(ctx), - } + _ => self.parse_postfix(ctx)?, + }) } fn parse_binary( &mut self, ctx: &mut Context, - passtrough: Option, + passtrough: Option>, min_bp: u8, - ) -> Result { - let mut expr = passtrough + ) -> Result> { + let mut left = passtrough .ok_or(ErrorKind::EndOfFile /* Dummy error */) .or_else(|_| self.parse_unary(ctx))?; - let start_meta = expr.meta.clone(); + let start_meta = ctx.hir_exprs[left].meta.clone(); while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek()?.value) { if l_bp < min_bp { @@ -1029,12 +1021,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let Token { value, .. } = self.bump()?; - let right = Box::new(self.parse_binary(ctx, None, r_bp)?); - let end_meta = right.meta.clone(); + let right = self.parse_binary(ctx, None, r_bp)?; + let end_meta = ctx.hir_exprs[right].meta.clone(); - expr = Expr { - kind: ExprKind::Binary { - left: Box::new(expr), + left = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Binary { + left, op: match value { TokenValue::LogicalOr => BinaryOperator::LogicalOr, TokenValue::LogicalXor => BinaryOperator::NotEqual, @@ -1060,50 +1052,51 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { right, }, meta: start_meta.union(&end_meta), - } + }) } - Ok(expr) + Ok(left) } - fn parse_conditional(&mut self, ctx: &mut Context, passtrough: Option) -> Result { + fn parse_conditional( + &mut self, + ctx: &mut Context, + passtrough: Option>, + ) -> Result> { let mut condition = self.parse_binary(ctx, passtrough, 0)?; - let start_meta = condition.meta.clone(); + let start_meta = ctx.hir_exprs[condition].meta.clone(); if self.bump_if(TokenValue::Question).is_some() { - let accept = Box::new(self.parse_expression(ctx)?); + let accept = self.parse_expression(ctx)?; self.expect(TokenValue::Colon)?; - let reject = Box::new(self.parse_assignment(ctx)?); - let end_meta = reject.meta.clone(); + let reject = self.parse_assignment(ctx)?; + let end_meta = ctx.hir_exprs[reject].meta.clone(); - condition = Expr { - kind: ExprKind::Conditional { - condition: Box::new(condition), + condition = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Conditional { + condition, accept, reject, }, meta: start_meta.union(&end_meta), - }; + }) } Ok(condition) } - fn parse_assignment(&mut self, ctx: &mut Context) -> Result { - let pointer = self.parse_unary(ctx)?; - let start_meta = pointer.meta.clone(); + fn parse_assignment(&mut self, ctx: &mut Context) -> Result> { + let tgt = self.parse_unary(ctx)?; + let start_meta = ctx.hir_exprs[tgt].meta.clone(); - match self.expect_peek()?.value { + Ok(match self.expect_peek()?.value { TokenValue::Assign => { self.bump()?; - let value = Box::new(self.parse_assignment(ctx)?); - let end_meta = value.meta.clone(); + let value = self.parse_assignment(ctx)?; + let end_meta = ctx.hir_exprs[value].meta.clone(); - Ok(Expr { - kind: ExprKind::Assign { - tgt: Box::new(pointer), - value, - }, + ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Assign { tgt, value }, meta: start_meta.union(&end_meta), }) } @@ -1118,13 +1111,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { | TokenValue::RightShiftAssign | TokenValue::XorAssign => { let token = self.bump()?; - let right = Box::new(self.parse_assignment(ctx)?); - let end_meta = right.meta.clone(); + let right = self.parse_assignment(ctx)?; + let end_meta = ctx.hir_exprs[right].meta.clone(); - let value = Box::new(Expr { + let value = ctx.hir_exprs.append(HirExpr { meta: start_meta.union(&end_meta), - kind: ExprKind::Binary { - left: Box::new(pointer.clone()), + kind: HirExprKind::Binary { + left: tgt, op: match token.value { TokenValue::OrAssign => BinaryOperator::ExclusiveOr, TokenValue::AndAssign => BinaryOperator::ExclusiveOr, @@ -1142,19 +1135,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }, }); - Ok(Expr { - kind: ExprKind::Assign { - tgt: Box::new(pointer), - value, - }, + ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Assign { tgt, value }, meta: start_meta.union(&end_meta), }) } - _ => self.parse_conditional(ctx, Some(pointer)), - } + _ => self.parse_conditional(ctx, Some(tgt))?, + }) } - fn parse_expression(&mut self, ctx: &mut Context) -> Result { + fn parse_expression(&mut self, ctx: &mut Context) -> Result> { let mut expr = self.parse_assignment(ctx)?; while let TokenValue::Comma = self.expect_peek()?.value { @@ -1187,7 +1177,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { _ => { let expr = self.parse_expression(ctx)?; self.expect(TokenValue::Semicolon)?; - Some(ctx.lower(self.program, expr, false, body)?) + Some(ctx.lower(self.program, expr, false, body)?.0) } }; @@ -1204,7 +1194,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::LeftParen)?; let condition = { let expr = self.parse_expression(ctx)?; - ctx.lower(self.program, expr, false, body)? + ctx.lower(self.program, expr, false, body)?.0 }; self.expect(TokenValue::RightParen)?; @@ -1228,7 +1218,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::LeftParen)?; let selector = { let expr = self.parse_expression(ctx)?; - ctx.lower(self.program, expr, false, body)? + ctx.lower(self.program, expr, false, body)?.0 }; self.expect(TokenValue::RightParen)?; @@ -1242,8 +1232,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.bump()?; let value = { let expr = self.parse_expression(ctx)?; - let meta = expr.meta.clone(); - let root = ctx.lower(self.program, expr, false, body)?; + let (root, meta) = ctx.lower(self.program, expr, false, body)?; let constant = self.program.solve_constant( &ctx.expressions, root, @@ -1332,7 +1321,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut loop_body = Block::new(); - let expr = ctx.lower(self.program, root, false, &mut loop_body)?; + let expr = ctx.lower(self.program, root, false, &mut loop_body)?.0; let condition = ctx.expressions.append(Expression::Unary { op: UnaryOperator::Not, expr, @@ -1362,7 +1351,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let root = self.parse_expression(ctx)?; self.expect(TokenValue::RightParen)?; - let expr = ctx.lower(self.program, root, false, &mut loop_body)?; + let expr = ctx.lower(self.program, root, false, &mut loop_body)?.0; let condition = ctx.expressions.append(Expression::Unary { op: UnaryOperator::Not, expr, @@ -1421,7 +1410,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { value } else { let root = self.parse_expression(ctx)?; - ctx.lower(self.program, root, false, &mut block)? + ctx.lower(self.program, root, false, &mut block)?.0 }; body.push(Statement::If { From a0815679234d324ee6e4f8aacaef3a3aa035e445 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 17 May 2021 11:43:19 +0100 Subject: [PATCH 0870/2212] [glsl-in] Implement Copy on SourceMetadata --- src/front/glsl/ast.rs | 4 ++-- src/front/glsl/error.rs | 16 ++++++++-------- src/front/glsl/functions.rs | 4 ++-- src/front/glsl/lex.rs | 24 +++++++++++++----------- src/front/glsl/parser.rs | 28 ++++++++++++++-------------- src/front/glsl/parser_tests.rs | 13 ++++++++----- src/front/glsl/token.rs | 17 ++++++++++++++--- src/front/glsl/variables.rs | 2 +- 8 files changed, 62 insertions(+), 46 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 845f06ac6..f54abf72e 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -316,7 +316,7 @@ impl<'function> Context<'function> { HirExprKind::Select { base, field } => { let base = self.lower(program, base, lhs, body)?.0; - program.field_selection(self, base, &field, meta.clone())? + program.field_selection(self, base, &field, meta)? } HirExprKind::Constant(constant) if !lhs => { self.expressions.append(Expression::Constant(constant)) @@ -383,7 +383,7 @@ impl<'function> Context<'function> { } } HirExprKind::Call(call) if !lhs => { - program.function_call(self, body, call.kind, &call.args, meta.clone())? + program.function_call(self, body, call.kind, &call.args, meta)? } HirExprKind::Conditional { condition, diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 8ae98dd29..8ad9c16aa 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -33,15 +33,15 @@ pub enum ErrorKind { impl ErrorKind { /// Returns the TokenMetadata if available - pub fn metadata(&self) -> Option<&SourceMetadata> { + pub fn metadata(&self) -> Option { match *self { - ErrorKind::UnknownVariable(ref metadata, _) - | ErrorKind::InvalidProfile(ref metadata, _) - | ErrorKind::InvalidVersion(ref metadata, _) - | ErrorKind::UnknownLayoutQualifier(ref metadata, _) - | ErrorKind::SemanticError(ref metadata, _) - | ErrorKind::UnknownField(ref metadata, _) => Some(metadata), - ErrorKind::InvalidToken(ref token) => Some(&token.meta), + ErrorKind::UnknownVariable(metadata, _) + | ErrorKind::InvalidProfile(metadata, _) + | ErrorKind::InvalidVersion(metadata, _) + | ErrorKind::UnknownLayoutQualifier(metadata, _) + | ErrorKind::SemanticError(metadata, _) + | ErrorKind::UnknownField(metadata, _) => Some(metadata), + ErrorKind::InvalidToken(ref token) => Some(token.meta), _ => None, } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 8f9882c3e..d0128dc81 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -24,7 +24,7 @@ impl Program<'_> { match fc { FunctionCallKind::TypeConstructor(ty) => { let h = if args.len() == 1 { - let is_vec = match *self.resolve_type(ctx, args[0].0, args[0].1.clone())? { + let is_vec = match *self.resolve_type(ctx, args[0].0, args[0].1)? { TypeInner::Vector { .. } => true, _ => false, }; @@ -291,7 +291,7 @@ impl Program<'_> { let name = function .name .clone() - .ok_or_else(|| ErrorKind::SemanticError(meta.clone(), "Unnamed function".into()))?; + .ok_or_else(|| ErrorKind::SemanticError(meta, "Unnamed function".into()))?; let stage = self.entry_points.get(&name); if let Some(&stage) = stage { diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index bc6335abf..b98997242 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -30,13 +30,14 @@ impl<'a> Lexer<'a> { impl<'a> Iterator for Lexer<'a> { type Item = Token; fn next(&mut self) -> Option { - let mut meta = SourceMetadata { chars: 0..0 }; + let mut meta = SourceMetadata::default(); let pp_token = match self.tokens.pop_front() { Some(t) => t, None => match self.pp.next()? { Ok(t) => t, Err((err, loc)) => { - meta.chars = loc.into(); + meta.start = loc.start as usize; + meta.end = loc.end as usize; return Some(Token { value: TokenValue::Unknown(err), meta, @@ -45,7 +46,8 @@ impl<'a> Iterator for Lexer<'a> { }, }; - meta.chars = pp_token.location.into(); + meta.start = pp_token.location.start as usize; + meta.end = pp_token.location.end as usize; let value = match pp_token.value { PPTokenValue::Extension(extension) => { for t in extension.tokens { @@ -186,7 +188,7 @@ mod tests { lex.next().unwrap(), Token { value: TokenValue::Version, - meta: SourceMetadata { chars: 1..8 } + meta: SourceMetadata { start: 1, end: 8 } } ); assert_eq!( @@ -197,49 +199,49 @@ mod tests { value: 450, width: 32 }), - meta: SourceMetadata { chars: 9..12 }, + meta: SourceMetadata { start: 9, end: 12 }, } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::Void, - meta: SourceMetadata { chars: 13..17 } + meta: SourceMetadata { start: 13, end: 17 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::Identifier("main".into()), - meta: SourceMetadata { chars: 18..22 } + meta: SourceMetadata { start: 18, end: 22 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::LeftParen, - meta: SourceMetadata { chars: 23..24 } + meta: SourceMetadata { start: 23, end: 24 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::RightParen, - meta: SourceMetadata { chars: 24..25 } + meta: SourceMetadata { start: 24, end: 25 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::LeftBrace, - meta: SourceMetadata { chars: 26..27 } + meta: SourceMetadata { start: 26, end: 27 } } ); assert_eq!( lex.next().unwrap(), Token { value: TokenValue::RightBrace, - meta: SourceMetadata { chars: 27..28 } + meta: SourceMetadata { start: 27, end: 28 } } ); assert_eq!(lex.next(), None); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b7448818a..580128990 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -143,7 +143,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_type_non_void(&mut self) -> Result<(Handle, SourceMetadata)> { let (maybe_ty, meta) = self.parse_type()?; let ty = maybe_ty - .ok_or_else(|| ErrorKind::SemanticError(meta.clone(), "Type can't be void".into()))?; + .ok_or_else(|| ErrorKind::SemanticError(meta, "Type can't be void".into()))?; Ok((ty, meta)) } @@ -260,16 +260,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { value: ScalarValue::Uint(int), .. } => u32::try_from(int).map_err(|_| { - ErrorKind::SemanticError(meta.clone(), "int constant overflows".into()) + ErrorKind::SemanticError(meta, "int constant overflows".into()) }), ConstantInner::Scalar { value: ScalarValue::Sint(int), .. } => u32::try_from(int).map_err(|_| { - ErrorKind::SemanticError(meta.clone(), "int constant overflows".into()) + ErrorKind::SemanticError(meta, "int constant overflows".into()) }), _ => Err(ErrorKind::SemanticError( - meta.clone(), + meta, "Expected a uint constant".into(), )), }?; @@ -329,7 +329,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(( self.program - .solve_constant(&expressions, root, meta.clone())?, + .solve_constant(&expressions, root, meta)?, meta, )) } @@ -980,7 +980,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let Token { value, meta } = self.bump()?; let expr = self.parse_unary(ctx)?; - let end_meta = ctx.hir_exprs[expr].meta.clone(); + let end_meta = ctx.hir_exprs[expr].meta; let kind = match value { TokenValue::Dash => HirExprKind::Unary { @@ -1012,7 +1012,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut left = passtrough .ok_or(ErrorKind::EndOfFile /* Dummy error */) .or_else(|_| self.parse_unary(ctx))?; - let start_meta = ctx.hir_exprs[left].meta.clone(); + let start_meta = ctx.hir_exprs[left].meta; while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek()?.value) { if l_bp < min_bp { @@ -1022,7 +1022,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let Token { value, .. } = self.bump()?; let right = self.parse_binary(ctx, None, r_bp)?; - let end_meta = ctx.hir_exprs[right].meta.clone(); + let end_meta = ctx.hir_exprs[right].meta; left = ctx.hir_exprs.append(HirExpr { kind: HirExprKind::Binary { @@ -1064,13 +1064,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { passtrough: Option>, ) -> Result> { let mut condition = self.parse_binary(ctx, passtrough, 0)?; - let start_meta = ctx.hir_exprs[condition].meta.clone(); + let start_meta = ctx.hir_exprs[condition].meta; if self.bump_if(TokenValue::Question).is_some() { let accept = self.parse_expression(ctx)?; self.expect(TokenValue::Colon)?; let reject = self.parse_assignment(ctx)?; - let end_meta = ctx.hir_exprs[reject].meta.clone(); + let end_meta = ctx.hir_exprs[reject].meta; condition = ctx.hir_exprs.append(HirExpr { kind: HirExprKind::Conditional { @@ -1087,13 +1087,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_assignment(&mut self, ctx: &mut Context) -> Result> { let tgt = self.parse_unary(ctx)?; - let start_meta = ctx.hir_exprs[tgt].meta.clone(); + let start_meta = ctx.hir_exprs[tgt].meta; Ok(match self.expect_peek()?.value { TokenValue::Assign => { self.bump()?; let value = self.parse_assignment(ctx)?; - let end_meta = ctx.hir_exprs[value].meta.clone(); + let end_meta = ctx.hir_exprs[value].meta; ctx.hir_exprs.append(HirExpr { kind: HirExprKind::Assign { tgt, value }, @@ -1112,7 +1112,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { | TokenValue::XorAssign => { let token = self.bump()?; let right = self.parse_assignment(ctx)?; - let end_meta = ctx.hir_exprs[right].meta.clone(); + let end_meta = ctx.hir_exprs[right].meta; let value = ctx.hir_exprs.append(HirExpr { meta: start_meta.union(&end_meta), @@ -1236,7 +1236,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let constant = self.program.solve_constant( &ctx.expressions, root, - meta.clone(), + meta, )?; match self.program.module.constants[constant].inner { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 3a165ab33..3e3321e4a 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -31,19 +31,19 @@ fn version() { parse_program("#version 99000", &entry_points) .err() .unwrap(), - ErrorKind::InvalidVersion(SourceMetadata { chars: 9..14 }, 99000), + ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 14 }, 99000), ); assert_eq!( parse_program("#version 449", &entry_points).err().unwrap(), - ErrorKind::InvalidVersion(SourceMetadata { chars: 9..12 }, 449) + ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 12 }, 449) ); assert_eq!( parse_program("#version 450 smart", &entry_points) .err() .unwrap(), - ErrorKind::InvalidProfile(SourceMetadata { chars: 13..18 }, "smart".into()) + ErrorKind::InvalidProfile(SourceMetadata { start: 13, end: 18 }, "smart".into()) ); assert_eq!( @@ -52,7 +52,7 @@ fn version() { .unwrap(), ErrorKind::InvalidToken(Token { value: TokenValue::Unknown(PreprocessorError::UnexpectedHash), - meta: SourceMetadata { chars: 24..25 } + meta: SourceMetadata { start: 24, end: 25 } }) ); @@ -330,7 +330,10 @@ fn functions() { .err() .unwrap(), ErrorKind::SemanticError( - SourceMetadata { chars: 134..152 }, + SourceMetadata { + start: 134, + end: 152 + }, "Function already defined".into() ) ); diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 8e81de31c..16a745e35 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -3,20 +3,31 @@ pub use pp_rs::token::{Float, Integer, PreprocessorError}; use crate::{Interpolation, Sampling, Type}; use std::{fmt, ops::Range}; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Copy, Default)] #[cfg_attr(test, derive(PartialEq))] pub struct SourceMetadata { - pub chars: Range, + /// Byte offset into the source where the first char starts + pub start: usize, + /// Byte offset into the source where the first char not belonging to this + /// source metadata starts + pub end: usize, } impl SourceMetadata { pub fn union(&self, other: &Self) -> Self { SourceMetadata { - chars: (self.chars.start.min(other.chars.start))..(self.chars.end.max(other.chars.end)), + start: self.start.min(other.start), + end: self.end.max(other.end), } } } +impl From for Range { + fn from(meta: SourceMetadata) -> Self { + meta.start..meta.end + } +} + #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub struct Token { diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 7aaff1d7a..1e572e171 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -121,7 +121,7 @@ impl Program<'_> { name: &str, meta: SourceMetadata, ) -> Result, ErrorKind> { - match *self.resolve_type(context, expression, meta.clone())? { + match *self.resolve_type(context, expression, meta)? { TypeInner::Struct { ref members, .. } => { let index = members .iter() From db1350ba4facac02159b55cf1672264968db7ab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 19 May 2021 20:38:40 +0100 Subject: [PATCH 0871/2212] [glsl-in] fix global storage class --- src/front/glsl/parser.rs | 31 +++++++++++-------------------- src/front/glsl/variables.rs | 14 +++++++------- 2 files changed, 18 insertions(+), 27 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 580128990..1e7236056 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -142,8 +142,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_type_non_void(&mut self) -> Result<(Handle, SourceMetadata)> { let (maybe_ty, meta) = self.parse_type()?; - let ty = maybe_ty - .ok_or_else(|| ErrorKind::SemanticError(meta, "Type can't be void".into()))?; + let ty = + maybe_ty.ok_or_else(|| ErrorKind::SemanticError(meta, "Type can't be void".into()))?; Ok((ty, meta)) } @@ -259,15 +259,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ConstantInner::Scalar { value: ScalarValue::Uint(int), .. - } => u32::try_from(int).map_err(|_| { - ErrorKind::SemanticError(meta, "int constant overflows".into()) - }), + } => u32::try_from(int) + .map_err(|_| ErrorKind::SemanticError(meta, "int constant overflows".into())), ConstantInner::Scalar { value: ScalarValue::Sint(int), .. - } => u32::try_from(int).map_err(|_| { - ErrorKind::SemanticError(meta, "int constant overflows".into()) - }), + } => u32::try_from(int) + .map_err(|_| ErrorKind::SemanticError(meta, "int constant overflows".into())), _ => Err(ErrorKind::SemanticError( meta, "Expected a uint constant".into(), @@ -327,11 +325,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let expr = self.parse_conditional(&mut ctx, None)?; let (root, meta) = ctx.lower(self.program, expr, false, &mut Block::new())?; - Ok(( - self.program - .solve_constant(&expressions, root, meta)?, - meta, - )) + Ok((self.program.solve_constant(&expressions, root, meta)?, meta)) } fn parse_external_declaration(&mut self) -> Result<()> { @@ -685,14 +679,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ty_name: String, meta: SourceMetadata, ) -> Result { - let mut class = StorageClass::Function; + let mut class = StorageClass::Private; let mut binding = None; let mut layout = None; for qualifier in qualifiers { match *qualifier { TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { - if StorageClass::Function != class { + if StorageClass::Private != class { return Err(ErrorKind::SemanticError( meta, "Cannot use more than one storage qualifier per declaration".into(), @@ -1233,11 +1227,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let value = { let expr = self.parse_expression(ctx)?; let (root, meta) = ctx.lower(self.program, expr, false, body)?; - let constant = self.program.solve_constant( - &ctx.expressions, - root, - meta, - )?; + let constant = + self.program.solve_constant(&ctx.expressions, root, meta)?; match self.program.module.constants[constant].inner { ConstantInner::Scalar { diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 1e572e171..d57ce2a7e 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -43,7 +43,7 @@ impl Program<'_> { let handle = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), - class: StorageClass::Function, + class: StorageClass::Private, binding: None, ty, init: None, @@ -69,7 +69,7 @@ impl Program<'_> { let handle = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), - class: StorageClass::Function, + class: StorageClass::Private, binding: None, ty, init: None, @@ -95,7 +95,7 @@ impl Program<'_> { let handle = self.module.global_variables.append(GlobalVariable { name: Some(name.into()), - class: StorageClass::Function, + class: StorageClass::Private, binding: None, ty, init: None, @@ -220,7 +220,7 @@ impl Program<'_> { meta, }: VarDeclaration, ) -> Result, ErrorKind> { - let mut storage = StorageQualifier::StorageClass(StorageClass::Function); + let mut storage = StorageQualifier::StorageClass(StorageClass::Private); let mut interpolation = None; let mut binding = None; let mut location = None; @@ -230,7 +230,7 @@ impl Program<'_> { for qualifier in qualifiers { match *qualifier { TypeQualifier::StorageQualifier(s) => { - if StorageQualifier::StorageClass(StorageClass::Function) != storage { + if StorageQualifier::StorageClass(StorageClass::Private) != storage { return Err(ErrorKind::SemanticError( meta, "Cannot use more than one storage qualifier per declaration".into(), @@ -317,7 +317,7 @@ impl Program<'_> { let handle = self.module.global_variables.append(GlobalVariable { name: Some(name.clone()), - class: StorageClass::Function, + class: StorageClass::Private, binding: None, ty, init, @@ -350,7 +350,7 @@ impl Program<'_> { let class = match storage { StorageQualifier::StorageClass(class) => class, - _ => StorageClass::Function, + _ => StorageClass::Private, }; let handle = self.module.global_variables.append(GlobalVariable { From 47ada8182b83d43f47435df76d68f7dd278ab57a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 19 May 2021 23:24:09 -0400 Subject: [PATCH 0872/2212] Parse Dota2 shaders on CI in lazy mode --- .github/workflows/lazy.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index 7344fdac0..5d6bc561f 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -26,3 +26,21 @@ jobs: with: name: code-coverage-report path: cobertura.xml + parse-dota2: + name: Parse Dota2 shaders + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + - run: mkdir data + - name: Download shaders + run: curl https://user.fm/files/v2-5573e18b9f03f42c6ae53c392083da35/dota2-shaders.zip -o data/all.zip + - name: Unpack shaders + run: cd data && unzip all.zip + - name: Build Naga + run: cargo build --release --features spv-in,msl-out --bin naga + - name: Convert shaders + run: for file in data/*.spv ; do echo "Translating" ${file} && target/release/naga --validate 27 ${file} ${file}.metal; done From a7100b14eb86302b24faa05960ea3418498069fd Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 19 May 2021 11:21:56 -0700 Subject: [PATCH 0873/2212] Flesh out the Naga module-level documentation. --- src/lib.rs | 123 ++++++++++++++++++++++++++++++++++----- src/proc/interpolator.rs | 2 +- 2 files changed, 109 insertions(+), 16 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 8a5ab20b7..5413b45c0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,22 +1,108 @@ /*! Universal shader translator. -The central structure of the crate is [`Module`]. +The central structure of the crate is [`Module`]. A `Module` contains: -To improve performance and reduce memory usage, most structures are stored -in an [`Arena`], and can be retrieved using the corresponding [`Handle`]. +- [`EntryPoint`]s, the main functions for pipeline stages like vertex shading or + fragment shading, -Functions are described in terms of statement trees. A statement may have -branching control flow, and it may be mutating. Statements refer to expressions. +- [`Function`]s, representing functions used by `EntryPoint`s and other `Function`s, -Expressions form a DAG, without any side effects. Expressions need to be -emitted in order to take effect. This happens in one of the following ways: - 1. Constants and function arguments are implicitly emitted at function start. - This corresponds to `expression.needs_pre_emit()` condition. - 2. Local and global variables are implicitly emitted. However, in order to use parts - of them in right-hand-side expressions, the `Expression::Load` must be explicitly emitted, - with an exception of `StorageClass::Handle` global variables. - 3. Result of `Statement::Call` is automatically emitted. - 4. `Statement::Emit` range is explicitly emitted. +- [`Constant`]s and [`GlobalVariable`]s used by `EntryPoint`s and `Function`s, and + +- [`Type`]s used by the above. + +The body of an `EntryPoint` or `Function` is represented using two types: + +- An [`Expression`] produces a value, but has no side effects or control flow. + `Expressions` include variable references, unary and binary operators, and so + on. + +- A [`Statement`] can have side effects and structured control flow. + `Statement`s do not produce a value, other than by storing one in some + designated place. `Statements` include blocks, conditionals, and loops, but also + operations that have side effects, like stores and function calls. + +`Statement`s form a tree, with pointers into the DAG of `Expression`s. + +Restricting side effects to statements simplifies analysis and code generation. +A Naga backend can generate code to evaluate an `Expression` however and +whenever it pleases, as long as it is certain to observe the side effects of all +previously executed `Statement`s. + +Many `Statement` variants use the [`Block`] type, which is simply `Vec`, +representing a series of statements executed in order. The body of an +`EntryPoint`s or `Function` is a `Block`, and `Statement` has a +[`Block`][Statement::Block] variant. + +To improve translator performance and reduce memory usage, most structures are +stored in an [`Arena`]. An `Arena` stores a series of `T` values, indexed by +[`Handle`](Handle) values, which are just wrappers around integer indexes. +For example, a `Function`'s expressions are stored in an `Arena`, +and compound expressions refer to their sub-expressions via `Handle` +values. (When examining the serialized form of a `Module`, note that the first +element of an `Arena` has an index of 1, not 0.) + +## Function Calls + +The Naga IR's representation of function calls is unusual. Most languages treat +function calls as expressions, but because calls may have side effects, Naga +represents them with [`Statement::Call`]. A call statement may designate a +particular `Expression` to represent its return value, if any, which can be used +by subsequent statements and their expressions. + +## `Expression` evaluation time and scope + +While the order of execution of [`Statement`]s is apparent from their structure, +it is not so obvious exactly when a given [`Expression`] should be evaluated, +since many `Statement`s and `Expression`s may refer to its value. But it is +essential to clearly specify an expression's evaluation time, since that +determines which statements' effects the expression should observe. It is also +helpful to backends to limit the visibility of an `Expression`'s value to a +portion of the statement tree. + +An `Expression` may only be used, whether by a `Statement` or another +`Expression`, if one of the following is true: + +- The expression is an [`Expression::Constant`], [`Expression::FunctionArgument`], or + [`Expression::GlobalVariable`]. + +- The expression is an [`Expression::LocalVariable`] that is either the + `pointer` (destination) of a [`Statement::Store`], or initialized by some + previously executed `Statement::Store`. + +- The expression is the `result` of a [`Statement::Call`], representing the + call's return value. The call must be 'in scope' for the use (see below). + +- The expression is included in the range of some [`Statement::Emit`] that is + 'in scope' for the use (see below). The [`Expression::needs_pre_emit`] method + returns `true` if the given expression does *not* need to be covered by an + `Emit` statement. + +The scope of an expression evaluated by an `Emit` statement covers the +subsequent expressions in that `Emit`, any following statements in the `Block` +to which that `Emit` belongs (if any) and their sub-statements (if any). + +If a `Call` statement has a `result` expression, then it is in scope for any +statements following the `Call` in the `Block` to which that `Call` belongs (if +any) and their sub-statements (if any). + +This means that, for example, an expression evaluated by some statement in a +nested `Block` is not available in the `Block`'s parents. Such a value would +need to be stored in a local variable to be carried upwards in the statement +tree. + +## Variables + +An [`Expression::LocalVariable`] or [`Expression::GlobalVariable`] produces a +pointer value referring to the variable's value. To retrieve the variable's +value, use an [`Expression::Load`], with the variable expression as its +`pointer` operand. To assign to a variable, use a [`Statement::Store`] with the +variable expression as its `pointer` operand. + +As an exception, [`Expression::GlobalVariable`]s referring to +[`GlobalVariable`]s whose `class` is [`StorageClass::Handle`] produce the +variable's value directly; no `Load` is needed. These global variables refer to +opaque values like samplers and images. !*/ @@ -778,6 +864,9 @@ pub enum Expression { right: Handle, }, /// Select between two values based on a condition. + /// + /// Note that, because expressions have no side effects, it is unobservable + /// whether the non-selected branch is evaluated. Select { /// Boolean expression condition: Handle, @@ -848,6 +937,10 @@ pub struct SwitchCase { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Statement { /// Emit a range of expressions, visible to all statements that follow in this block. + /// + /// See the [module-level documentation][emit] for details. + /// + /// [emit]: index.html#expression-evaluation-time-and-scope Emit(Range), /// A block containing more statements, to be executed sequentially. Block(Block), @@ -981,7 +1074,7 @@ pub struct EntryPoint { /// To create a new module, use the `Default` implementation. /// Alternatively, you can load an existing shader using one of the [available front ends][front]. /// -/// When finished, you can export modules using one of the [available back ends][back]. +/// When finished, you can export modules using one of the [available backends][back]. #[derive(Debug, Default)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] diff --git a/src/proc/interpolator.rs b/src/proc/interpolator.rs index 7f7296e50..90e6cb57e 100644 --- a/src/proc/interpolator.rs +++ b/src/proc/interpolator.rs @@ -27,7 +27,7 @@ impl crate::Module { /// binding that can vary, and everything else either defaults to flat, or /// requires an explicit flat qualifier/attribute/what-have-you. /// - /// [`Binding`]: super::Binding + /// [`Binding`]: crate::Binding pub fn apply_common_default_interpolation(&mut self) { use crate::{Binding, ScalarKind, Type, TypeInner}; From c22fa546421c0f6aeffbe34355a43f9e7889287d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 20 May 2021 21:14:49 +0100 Subject: [PATCH 0874/2212] [glsl-in] Expression emitting --- src/front/glsl/ast.rs | 176 +++++++++++++----------- src/front/glsl/functions.rs | 260 +++++++++++++++++++++--------------- src/front/glsl/parser.rs | 190 ++++++++++++++++---------- src/front/glsl/variables.rs | 246 ++++++++++++++++------------------ src/front/mod.rs | 4 +- 5 files changed, 482 insertions(+), 394 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index f54abf72e..0de03552b 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,12 +1,12 @@ use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind, SourceMetadata}; use crate::{ - proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, Expression, FastHashMap, - Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, - RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, - TypeInner, UnaryOperator, + front::Emitter, proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, + Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, + LocalVariable, Module, RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, + StorageClass, Type, TypeInner, UnaryOperator, }; -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] pub enum GlobalLookup { Variable(Handle), BlockSelect(Handle, u32), @@ -34,8 +34,9 @@ pub struct Program<'a> { pub lookup_function: FastHashMap, pub lookup_type: FastHashMap>, - pub lookup_global_variables: FastHashMap, - pub lookup_constants: FastHashMap>, + + pub global_variables: Vec<(String, GlobalLookup)>, + pub constants: Vec<(String, Handle)>, pub entry_args: Vec<(Binding, bool, Handle)>, pub entries: Vec<(String, ShaderStage, Handle)>, @@ -52,8 +53,8 @@ impl<'a> Program<'a> { lookup_function: FastHashMap::default(), lookup_type: FastHashMap::default(), - lookup_global_variables: FastHashMap::default(), - lookup_constants: FastHashMap::default(), + global_variables: Vec::new(), + constants: Vec::new(), entry_args: Vec::new(), entries: Vec::new(), @@ -120,13 +121,13 @@ impl<'a> Program<'a> { pub fn solve_constant( &mut self, - expressions: &Arena, + ctx: &Context, root: Handle, meta: SourceMetadata, ) -> Result, ErrorKind> { let mut solver = ConstantSolver { types: &self.module.types, - expressions, + expressions: ctx.expressions, constants: &mut self.module.constants, }; @@ -141,38 +142,98 @@ pub enum Profile { #[derive(Debug)] pub struct Context<'function> { - pub expressions: &'function mut Arena, + expressions: &'function mut Arena, pub locals: &'function mut Arena, pub arguments: &'function mut Vec, //TODO: Find less allocation heavy representation pub scopes: Vec>, pub lookup_global_var_exps: FastHashMap, - pub lookup_constant_exps: FastHashMap, - pub typifier: Typifier, pub samplers: FastHashMap, Handle>, + pub typifier: Typifier, pub hir_exprs: Arena, + emitter: Emitter, } impl<'function> Context<'function> { pub fn new( + program: &mut Program, + body: &mut Block, expressions: &'function mut Arena, locals: &'function mut Arena, arguments: &'function mut Vec, ) -> Self { - Context { + let mut this = Context { expressions, locals, arguments, scopes: vec![FastHashMap::default()], - lookup_global_var_exps: FastHashMap::default(), - lookup_constant_exps: FastHashMap::default(), + lookup_global_var_exps: FastHashMap::with_capacity_and_hasher( + program.constants.len() + program.global_variables.len(), + Default::default(), + ), typifier: Typifier::new(), samplers: FastHashMap::default(), hir_exprs: Arena::default(), + emitter: Emitter::default(), + }; + + this.emit_start(); + + for &(ref name, lookup) in program.global_variables.iter() { + let expr = match lookup { + GlobalLookup::Variable(v) => Expression::GlobalVariable(v), + GlobalLookup::BlockSelect(handle, index) => { + let base = this.add_expression(Expression::GlobalVariable(handle), body); + + Expression::AccessIndex { base, index } + } + }; + + let expr = this.add_expression(expr, body); + let var = VariableReference { + expr, + load: Some(this.add_expression(Expression::Load { pointer: expr }, body)), + // TODO: respect constant qualifier + mutable: true, + }; + + this.lookup_global_var_exps.insert(name.into(), var); + } + + for &(ref name, handle) in program.constants.iter() { + let expr = this.add_expression(Expression::Constant(handle), body); + let var = VariableReference { + expr, + load: None, + mutable: false, + }; + + this.lookup_global_var_exps.insert(name.into(), var); + } + + this + } + + pub fn emit_start(&mut self) { + self.emitter.start(&self.expressions) + } + + pub fn emit_flush(&mut self, body: &mut Block) { + body.extend(self.emitter.finish(&self.expressions)) + } + + pub fn add_expression(&mut self, expr: Expression, body: &mut Block) -> Handle { + if expr.needs_pre_emit() { + self.emit_flush(body); + let expr = self.expressions.append(expr); + self.emit_start(); + expr + } else { + self.expressions.append(expr) } } @@ -185,55 +246,8 @@ impl<'function> Context<'function> { None } - pub fn lookup_global_var( - &mut self, - program: &mut Program, - name: &str, - ) -> Option { - self.lookup_global_var_exps.get(name).cloned().or_else(|| { - let expr = match *program.lookup_global_variables.get(name)? { - GlobalLookup::Variable(v) => Expression::GlobalVariable(v), - GlobalLookup::BlockSelect(handle, index) => { - let base = self.expressions.append(Expression::GlobalVariable(handle)); - - Expression::AccessIndex { base, index } - } - }; - - let expr = self.expressions.append(expr); - let var = VariableReference { - expr, - load: Some(self.expressions.append(Expression::Load { pointer: expr })), - // TODO: respect constant qualifier - mutable: true, - }; - - self.lookup_global_var_exps.insert(name.into(), var.clone()); - - Some(var) - }) - } - - pub fn lookup_constants_var( - &mut self, - program: &mut Program, - name: &str, - ) -> Option { - self.lookup_constant_exps.get(name).cloned().or_else(|| { - let expr = self - .expressions - .append(Expression::Constant(*program.lookup_constants.get(name)?)); - - let var = VariableReference { - expr, - load: None, - mutable: false, - }; - - self.lookup_constant_exps.insert(name.into(), var.clone()); - - Some(var) - }) + pub fn lookup_global_var(&mut self, name: &str) -> Option { + self.lookup_global_var_exps.get(name).cloned() } #[cfg(feature = "glsl-validate")] @@ -311,15 +325,15 @@ impl<'function> Context<'function> { let base = self.lower(program, base, lhs, body)?.0; let index = self.lower(program, index, false, body)?.0; - self.expressions.append(Expression::Access { base, index }) + self.add_expression(Expression::Access { base, index }, body) } HirExprKind::Select { base, field } => { let base = self.lower(program, base, lhs, body)?.0; - program.field_selection(self, base, &field, meta)? + program.field_selection(self, body, base, &field, meta)? } HirExprKind::Constant(constant) if !lhs => { - self.expressions.append(Expression::Constant(constant)) + self.add_expression(Expression::Constant(constant), body) } HirExprKind::Binary { left, op, right } if !lhs => { let (left, left_meta) = self.lower(program, left, false, body)?; @@ -353,20 +367,18 @@ impl<'function> Context<'function> { if left_dims != right_dims { return Err(ErrorKind::SemanticError(meta, "Cannot compare".into())); } else if left_is_vector && right_is_vector { - self.expressions - .append(Expression::Relational { fun, argument }) + self.add_expression(Expression::Relational { fun, argument }, body) } else { argument } } else { - self.expressions - .append(Expression::Binary { left, op, right }) + self.add_expression(Expression::Binary { left, op, right }, body) } } HirExprKind::Unary { op, expr } if !lhs => { let expr = self.lower(program, expr, false, body)?.0; - self.expressions.append(Expression::Unary { op, expr }) + self.add_expression(Expression::Unary { op, expr }, body) } HirExprKind::Variable(var) => { if lhs { @@ -394,16 +406,22 @@ impl<'function> Context<'function> { let accept = self.lower(program, accept, false, body)?.0; let reject = self.lower(program, reject, false, body)?.0; - self.expressions.append(Expression::Select { - condition, - accept, - reject, - }) + self.add_expression( + Expression::Select { + condition, + accept, + reject, + }, + body, + ) } HirExprKind::Assign { tgt, value } if !lhs => { let pointer = self.lower(program, tgt, true, body)?.0; let value = self.lower(program, value, false, body)?.0; + self.emit_flush(body); + self.emit_start(); + body.push(Statement::Store { pointer, value }); value diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index d0128dc81..766f255e1 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -30,53 +30,63 @@ impl Program<'_> { }; match self.module.types[ty].inner { - TypeInner::Vector { size, .. } if !is_vec => { - ctx.expressions.append(Expression::Splat { + TypeInner::Vector { size, .. } if !is_vec => ctx.add_expression( + Expression::Splat { size, value: args[0].0, - }) - } + }, + body, + ), TypeInner::Scalar { kind, width } - | TypeInner::Vector { kind, width, .. } => { - ctx.expressions.append(Expression::As { + | TypeInner::Vector { kind, width, .. } => ctx.add_expression( + Expression::As { kind, expr: args[0].0, convert: Some(width), - }) - } + }, + body, + ), TypeInner::Matrix { columns, rows, width, } => { - let value = ctx.expressions.append(Expression::As { - kind: ScalarKind::Float, - expr: args[0].0, - convert: Some(width), - }); + let value = ctx.add_expression( + Expression::As { + kind: ScalarKind::Float, + expr: args[0].0, + convert: Some(width), + }, + body, + ); let column = if is_vec { value } else { - ctx.expressions - .append(Expression::Splat { size: rows, value }) + ctx.add_expression(Expression::Splat { size: rows, value }, body) }; let columns = std::iter::repeat(column).take(columns as usize).collect(); - ctx.expressions.append(Expression::Compose { - ty, - components: columns, - }) + ctx.add_expression( + Expression::Compose { + ty, + components: columns, + }, + body, + ) } _ => return Err(ErrorKind::SemanticError(meta, "Bad cast".into())), } } else { - ctx.expressions.append(Expression::Compose { - ty, - components: args.iter().map(|e| e.0).collect(), - }) + ctx.add_expression( + Expression::Compose { + ty, + components: args.iter().map(|e| e.0).collect(), + }, + body, + ) }; Ok(h) @@ -95,15 +105,18 @@ impl Program<'_> { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(ctx.expressions.append(Expression::ImageSample { - image: args[0].0, - sampler, - coordinate: args[1].0, - array_index: None, //TODO - offset: None, //TODO - level: SampleLevel::Auto, - depth_ref: None, - })) + Ok(ctx.add_expression( + Expression::ImageSample { + image: args[0].0, + sampler, + coordinate: args[1].0, + array_index: None, //TODO + offset: None, //TODO + level: SampleLevel::Auto, + depth_ref: None, + }, + body, + )) } else { Err(ErrorKind::SemanticError(meta, "Bad call to texture".into())) } @@ -113,15 +126,18 @@ impl Program<'_> { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(ctx.expressions.append(Expression::ImageSample { - image: args[0].0, - sampler, - coordinate: args[1].0, - array_index: None, //TODO - offset: None, //TODO - level: SampleLevel::Exact(args[2].0), - depth_ref: None, - })) + Ok(ctx.add_expression( + Expression::ImageSample { + image: args[0].0, + sampler, + coordinate: args[1].0, + array_index: None, //TODO + offset: None, //TODO + level: SampleLevel::Exact(args[2].0), + depth_ref: None, + }, + body, + )) } else { Err(ErrorKind::SemanticError( meta, @@ -135,91 +151,102 @@ impl Program<'_> { if args.len() != 1 { return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); } - Ok(ctx.expressions.append(Expression::Math { - fun: match name.as_str() { - "ceil" => MathFunction::Ceil, - "round" => MathFunction::Round, - "floor" => MathFunction::Floor, - "fract" => MathFunction::Fract, - "trunc" => MathFunction::Trunc, - "sin" => MathFunction::Sin, - "abs" => MathFunction::Abs, - "sqrt" => MathFunction::Sqrt, - "inversesqrt" => MathFunction::InverseSqrt, - "exp" => MathFunction::Exp, - "exp2" => MathFunction::Exp2, - "sign" => MathFunction::Sign, - "transpose" => MathFunction::Transpose, - "inverse" => MathFunction::Inverse, - "normalize" => MathFunction::Normalize, - _ => unreachable!(), + Ok(ctx.add_expression( + Expression::Math { + fun: match name.as_str() { + "ceil" => MathFunction::Ceil, + "round" => MathFunction::Round, + "floor" => MathFunction::Floor, + "fract" => MathFunction::Fract, + "trunc" => MathFunction::Trunc, + "sin" => MathFunction::Sin, + "abs" => MathFunction::Abs, + "sqrt" => MathFunction::Sqrt, + "inversesqrt" => MathFunction::InverseSqrt, + "exp" => MathFunction::Exp, + "exp2" => MathFunction::Exp2, + "sign" => MathFunction::Sign, + "transpose" => MathFunction::Transpose, + "inverse" => MathFunction::Inverse, + "normalize" => MathFunction::Normalize, + _ => unreachable!(), + }, + arg: args[0].0, + arg1: None, + arg2: None, }, - arg: args[0].0, - arg1: None, - arg2: None, - })) + body, + )) } "pow" | "dot" | "max" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } - Ok(ctx.expressions.append(Expression::Math { - fun: match name.as_str() { - "pow" => MathFunction::Pow, - "dot" => MathFunction::Dot, - "max" => MathFunction::Max, - _ => unreachable!(), + Ok(ctx.add_expression( + Expression::Math { + fun: match name.as_str() { + "pow" => MathFunction::Pow, + "dot" => MathFunction::Dot, + "max" => MathFunction::Max, + _ => unreachable!(), + }, + arg: args[0].0, + arg1: Some(args[1].0), + arg2: None, }, - arg: args[0].0, - arg1: Some(args[1].0), - arg2: None, - })) + body, + )) } "mix" | "clamp" => { if args.len() != 3 { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } - Ok(ctx.expressions.append(Expression::Math { - fun: match name.as_str() { - "mix" => MathFunction::Mix, - "clamp" => MathFunction::Clamp, - _ => unreachable!(), + Ok(ctx.add_expression( + Expression::Math { + fun: match name.as_str() { + "mix" => MathFunction::Mix, + "clamp" => MathFunction::Clamp, + _ => unreachable!(), + }, + arg: args[0].0, + arg1: Some(args[1].0), + arg2: Some(args[2].0), }, - arg: args[0].0, - arg1: Some(args[1].0), - arg2: Some(args[2].0), - })) + body, + )) } "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" | "notEqual" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } - Ok(ctx.expressions.append(Expression::Binary { - op: match name.as_str() { - "lessThan" => BinaryOperator::Less, - "greaterThan" => BinaryOperator::Greater, - "lessThanEqual" => BinaryOperator::LessEqual, - "greaterThanEqual" => BinaryOperator::GreaterEqual, - "equal" => BinaryOperator::Equal, - "notEqual" => BinaryOperator::NotEqual, - _ => unreachable!(), + Ok(ctx.add_expression( + Expression::Binary { + op: match name.as_str() { + "lessThan" => BinaryOperator::Less, + "greaterThan" => BinaryOperator::Greater, + "lessThanEqual" => BinaryOperator::LessEqual, + "greaterThanEqual" => BinaryOperator::GreaterEqual, + "equal" => BinaryOperator::Equal, + "notEqual" => BinaryOperator::NotEqual, + _ => unreachable!(), + }, + left: args[0].0, + right: args[1].0, }, - left: args[0].0, - right: args[1].0, - })) + body, + )) } - "isinf" => { - self.parse_relational_fun(ctx, name, &args, RelationalFunction::IsInf, meta) - } - "isnan" => { - self.parse_relational_fun(ctx, name, &args, RelationalFunction::IsNan, meta) - } - "all" => { - self.parse_relational_fun(ctx, name, &args, RelationalFunction::All, meta) - } - "any" => { - self.parse_relational_fun(ctx, name, &args, RelationalFunction::Any, meta) + "isinf" | "isnan" | "all" | "any" => { + let fun = match name.as_str() { + "isinf" => RelationalFunction::IsInf, + "isnan" => RelationalFunction::IsNan, + "all" => RelationalFunction::All, + "any" => RelationalFunction::Any, + _ => unreachable!(), + }; + + self.parse_relational_fun(ctx, body, name, &args, fun, meta) } _ => { let mut parameters = Vec::new(); @@ -250,12 +277,17 @@ impl Program<'_> { arguments.push(handle) } - let expression = ctx.expressions.append(Expression::Call(fun.handle)); + ctx.emit_flush(body); + + let expression = ctx.add_expression(Expression::Call(fun.handle), body); body.push(crate::Statement::Call { function: fun.handle, arguments, result: Some(expression), }); + + ctx.emit_start(); + Ok(expression) } } @@ -266,6 +298,7 @@ impl Program<'_> { pub fn parse_relational_fun( &mut self, ctx: &mut Context, + body: &mut Block, name: String, args: &[(Handle, SourceMetadata)], fun: RelationalFunction, @@ -275,10 +308,13 @@ impl Program<'_> { return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); } - Ok(ctx.expressions.append(Expression::Relational { - fun, - argument: args[0].0, - })) + Ok(ctx.add_expression( + Expression::Relational { + fun, + argument: args[0].0, + }, + body, + )) } pub fn add_function( @@ -438,7 +474,9 @@ impl Program<'_> { span += self.module.types[ty].inner.span(&self.module.constants); let pointer = expressions.append(Expression::GlobalVariable(handle)); + let len = expressions.len(); let load = expressions.append(Expression::Load { pointer }); + body.push(Statement::Emit(expressions.range_from(len))); components.push(load) } @@ -451,7 +489,9 @@ impl Program<'_> { }, }); + let len = expressions.len(); let res = expressions.append(Expression::Compose { ty, components }); + body.push(Statement::Emit(expressions.range_from(len))); body.push(Statement::Return { value: Some(res) }); self.module.entry_points.push(EntryPoint { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 1e7236056..0283fb1c5 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -319,13 +319,20 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut expressions = Arena::new(); let mut locals = Arena::new(); let mut arguments = Vec::new(); + let mut block = Block::new(); - let mut ctx = Context::new(&mut expressions, &mut locals, &mut arguments); + let mut ctx = Context::new( + self.program, + &mut block, + &mut expressions, + &mut locals, + &mut arguments, + ); - let expr = self.parse_conditional(&mut ctx, None)?; - let (root, meta) = ctx.lower(self.program, expr, false, &mut Block::new())?; + let expr = self.parse_conditional(&mut ctx, &mut block, None)?; + let (root, meta) = ctx.lower(self.program, expr, false, &mut block)?; - Ok((self.program.solve_constant(&expressions, root, meta)?, meta)) + Ok((self.program.solve_constant(&ctx, root, meta)?, meta)) } fn parse_external_declaration(&mut self) -> Result<()> { @@ -339,8 +346,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // void main() {} // ``` let (mut e, mut l, mut a) = (Arena::new(), Arena::new(), Vec::new()); - let mut ctx = Context::new(&mut e, &mut l, &mut a); let mut body = Block::new(); + let mut ctx = Context::new(self.program, &mut body, &mut e, &mut l, &mut a); if !self.parse_declaration(&mut ctx, &mut body, true)? { let token = self.bump()?; @@ -422,12 +429,11 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } Ok(( - ctx.expressions - .append(Expression::Compose { ty, components }), + ctx.add_expression(Expression::Compose { ty, components }, body), meta, )) } else { - let expr = self.parse_assignment(ctx)?; + let expr = self.parse_assignment(ctx, body)?; Ok(ctx.lower(self.program, expr, false, body)?) } } @@ -499,15 +505,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // TODO: Should we try to make constants here? // This is mostly a hack because we don't yet support adding // bodies to entry points for variable initialization - let maybe_constant = init.clone().and_then(|(root, meta)| { - self.program - .solve_constant(ctx.ctx.expressions, root, meta) - .ok() - }); + let maybe_constant = init + .clone() + .and_then(|(root, meta)| self.program.solve_constant(ctx.ctx, root, meta).ok()); let pointer = ctx.add_var(self.program, ty, name, maybe_constant, meta)?; if let Some((value, _)) = init { + ctx.ctx.emit_flush(ctx.body); + ctx.ctx.emit_start(); ctx.body.push(Statement::Store { pointer, value }); } @@ -561,8 +567,11 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut local_variables = Arena::new(); let mut arguments = Vec::new(); let mut parameters = Vec::new(); + let mut body = Block::new(); let mut context = Context::new( + self.program, + &mut body, &mut expressions, &mut local_variables, &mut arguments, @@ -594,10 +603,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // This branch handles function definitions // as you can see by the guard this branch // only happens if external is also true - let mut body = Block::new(); // parse the body self.parse_compound_statement(&mut context, &mut body)?; + self.program.add_function( Function { name: Some(name), @@ -773,8 +782,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { if let Some(k) = name { self.program - .lookup_global_variables - .insert(k, GlobalLookup::Variable(handle)); + .global_variables + .push((k, GlobalLookup::Variable(handle))); } for (i, k) in members @@ -783,8 +792,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { .filter_map(|(i, m)| m.name.map(|s| (i as u32, s))) { self.program - .lookup_global_variables - .insert(k, GlobalLookup::BlockSelect(handle, i)); + .global_variables + .push((k, GlobalLookup::BlockSelect(handle, i))); } Ok(true) @@ -819,7 +828,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(span) } - fn parse_primary(&mut self, ctx: &mut Context) -> Result> { + fn parse_primary(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { let mut token = self.bump()?; let (width, value) = match token.value { @@ -837,7 +846,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ), TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)), TokenValue::LeftParen => { - let expr = self.parse_expression(ctx)?; + let expr = self.parse_expression(ctx, body)?; let meta = self.expect(TokenValue::RightParen)?.meta; token.meta = token.meta.union(&meta); @@ -862,6 +871,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_function_call_args( &mut self, ctx: &mut Context, + body: &mut Block, meta: &mut SourceMetadata, ) -> Result>> { let mut args = Vec::new(); @@ -869,7 +879,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { *meta = meta.union(&token.meta); } else { loop { - args.push(self.parse_assignment(ctx)?); + args.push(self.parse_assignment(ctx, body)?); let token = self.bump()?; match token.value { @@ -886,13 +896,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(args) } - fn parse_postfix(&mut self, ctx: &mut Context) -> Result> { + fn parse_postfix(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { let mut base = match self.expect_peek()?.value { TokenValue::Identifier(_) => { let (name, mut meta) = self.expect_ident()?; let expr = if self.bump_if(TokenValue::LeftParen).is_some() { - let args = self.parse_function_call_args(ctx, &mut meta)?; + let args = self.parse_function_call_args(ctx, body, &mut meta)?; HirExpr { kind: HirExprKind::Call(FunctionCall { @@ -902,7 +912,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta, } } else { - let var = match self.program.lookup_variable(ctx, &name)? { + let var = match self.program.lookup_variable(ctx, body, &name)? { Some(var) => var, None => return Err(ErrorKind::UnknownVariable(meta, name)), }; @@ -925,7 +935,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }; self.expect(TokenValue::LeftParen)?; - let args = self.parse_function_call_args(ctx, &mut meta)?; + let args = self.parse_function_call_args(ctx, body, &mut meta)?; ctx.hir_exprs.append(HirExpr { kind: HirExprKind::Call(FunctionCall { @@ -935,7 +945,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta, }) } - _ => self.parse_primary(ctx)?, + _ => self.parse_primary(ctx, body)?, }; // TODO: postfix inc/dec @@ -944,7 +954,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match value { TokenValue::LeftBracket => { - let index = self.parse_expression(ctx)?; + let index = self.parse_expression(ctx, body)?; let end_meta = self.expect(TokenValue::RightBracket)?.meta; base = ctx.hir_exprs.append(HirExpr { @@ -967,13 +977,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(base) } - fn parse_unary(&mut self, ctx: &mut Context) -> Result> { + fn parse_unary(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { // TODO: prefix inc/dec Ok(match self.expect_peek()?.value { TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { let Token { value, meta } = self.bump()?; - let expr = self.parse_unary(ctx)?; + let expr = self.parse_unary(ctx, body)?; let end_meta = ctx.hir_exprs[expr].meta; let kind = match value { @@ -993,19 +1003,20 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta: meta.union(&end_meta), }) } - _ => self.parse_postfix(ctx)?, + _ => self.parse_postfix(ctx, body)?, }) } fn parse_binary( &mut self, ctx: &mut Context, + body: &mut Block, passtrough: Option>, min_bp: u8, ) -> Result> { let mut left = passtrough .ok_or(ErrorKind::EndOfFile /* Dummy error */) - .or_else(|_| self.parse_unary(ctx))?; + .or_else(|_| self.parse_unary(ctx, body))?; let start_meta = ctx.hir_exprs[left].meta; while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek()?.value) { @@ -1015,7 +1026,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let Token { value, .. } = self.bump()?; - let right = self.parse_binary(ctx, None, r_bp)?; + let right = self.parse_binary(ctx, body, None, r_bp)?; let end_meta = ctx.hir_exprs[right].meta; left = ctx.hir_exprs.append(HirExpr { @@ -1055,15 +1066,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_conditional( &mut self, ctx: &mut Context, + body: &mut Block, passtrough: Option>, ) -> Result> { - let mut condition = self.parse_binary(ctx, passtrough, 0)?; + let mut condition = self.parse_binary(ctx, body, passtrough, 0)?; let start_meta = ctx.hir_exprs[condition].meta; if self.bump_if(TokenValue::Question).is_some() { - let accept = self.parse_expression(ctx)?; + let accept = self.parse_expression(ctx, body)?; self.expect(TokenValue::Colon)?; - let reject = self.parse_assignment(ctx)?; + let reject = self.parse_assignment(ctx, body)?; let end_meta = ctx.hir_exprs[reject].meta; condition = ctx.hir_exprs.append(HirExpr { @@ -1079,14 +1091,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(condition) } - fn parse_assignment(&mut self, ctx: &mut Context) -> Result> { - let tgt = self.parse_unary(ctx)?; + fn parse_assignment(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { + let tgt = self.parse_unary(ctx, body)?; let start_meta = ctx.hir_exprs[tgt].meta; Ok(match self.expect_peek()?.value { TokenValue::Assign => { self.bump()?; - let value = self.parse_assignment(ctx)?; + let value = self.parse_assignment(ctx, body)?; let end_meta = ctx.hir_exprs[value].meta; ctx.hir_exprs.append(HirExpr { @@ -1105,7 +1117,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { | TokenValue::RightShiftAssign | TokenValue::XorAssign => { let token = self.bump()?; - let right = self.parse_assignment(ctx)?; + let right = self.parse_assignment(ctx, body)?; let end_meta = ctx.hir_exprs[right].meta; let value = ctx.hir_exprs.append(HirExpr { @@ -1134,16 +1146,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta: start_meta.union(&end_meta), }) } - _ => self.parse_conditional(ctx, Some(tgt))?, + _ => self.parse_conditional(ctx, body, Some(tgt))?, }) } - fn parse_expression(&mut self, ctx: &mut Context) -> Result> { - let mut expr = self.parse_assignment(ctx)?; + fn parse_expression(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { + let mut expr = self.parse_assignment(ctx, body)?; while let TokenValue::Comma = self.expect_peek()?.value { self.bump()?; - expr = self.parse_assignment(ctx)?; + expr = self.parse_assignment(ctx, body)?; } Ok(expr) @@ -1169,12 +1181,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { None } _ => { - let expr = self.parse_expression(ctx)?; + let expr = self.parse_expression(ctx, body)?; self.expect(TokenValue::Semicolon)?; Some(ctx.lower(self.program, expr, false, body)?.0) } }; + ctx.emit_flush(body); + ctx.emit_start(); + body.push(Statement::Return { value }) } TokenValue::Discard => { @@ -1187,11 +1202,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::LeftParen)?; let condition = { - let expr = self.parse_expression(ctx)?; + let expr = self.parse_expression(ctx, body)?; ctx.lower(self.program, expr, false, body)?.0 }; self.expect(TokenValue::RightParen)?; + ctx.emit_flush(body); + ctx.emit_start(); + let mut accept = Block::new(); self.parse_statement(ctx, &mut accept)?; @@ -1211,11 +1229,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::LeftParen)?; let selector = { - let expr = self.parse_expression(ctx)?; + let expr = self.parse_expression(ctx, body)?; ctx.lower(self.program, expr, false, body)?.0 }; self.expect(TokenValue::RightParen)?; + ctx.emit_flush(body); + ctx.emit_start(); + let mut cases = Vec::new(); let mut default = Block::new(); @@ -1225,10 +1246,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Case => { self.bump()?; let value = { - let expr = self.parse_expression(ctx)?; + let expr = self.parse_expression(ctx, body)?; let (root, meta) = ctx.lower(self.program, expr, false, body)?; - let constant = - self.program.solve_constant(&ctx.expressions, root, meta)?; + let constant = self.program.solve_constant(&ctx, root, meta)?; match self.program.module.constants[constant].inner { ConstantInner::Scalar { @@ -1306,17 +1326,23 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::While => { self.bump()?; - self.expect(TokenValue::LeftParen)?; - let root = self.parse_expression(ctx)?; - self.expect(TokenValue::RightParen)?; - let mut loop_body = Block::new(); + self.expect(TokenValue::LeftParen)?; + let root = self.parse_expression(ctx, &mut loop_body)?; + self.expect(TokenValue::RightParen)?; + let expr = ctx.lower(self.program, root, false, &mut loop_body)?.0; - let condition = ctx.expressions.append(Expression::Unary { - op: UnaryOperator::Not, - expr, - }); + let condition = ctx.add_expression( + Expression::Unary { + op: UnaryOperator::Not, + expr, + }, + &mut loop_body, + ); + + ctx.emit_flush(&mut loop_body); + ctx.emit_start(); loop_body.push(Statement::If { condition, @@ -1339,14 +1365,20 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::While)?; self.expect(TokenValue::LeftParen)?; - let root = self.parse_expression(ctx)?; + let root = self.parse_expression(ctx, &mut loop_body)?; self.expect(TokenValue::RightParen)?; let expr = ctx.lower(self.program, root, false, &mut loop_body)?.0; - let condition = ctx.expressions.append(Expression::Unary { - op: UnaryOperator::Not, - expr, - }); + let condition = ctx.add_expression( + Expression::Unary { + op: UnaryOperator::Not, + expr, + }, + &mut loop_body, + ); + + ctx.emit_flush(&mut loop_body); + ctx.emit_start(); loop_body.push(Statement::If { condition, @@ -1369,11 +1401,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { if self.peek_type_name() || self.peek_type_qualifier() { self.parse_declaration(ctx, body, false)?; } else { - self.parse_expression(ctx)?; + self.parse_expression(ctx, body)?; self.expect(TokenValue::Semicolon)?; } } + ctx.emit_flush(body); + ctx.emit_start(); + let (mut block, mut continuing) = (Block::new(), Block::new()); if self.bump_if(TokenValue::Semicolon).is_none() { @@ -1394,21 +1429,32 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta: meta.union(&end_meta), }; - let pointer = self.program.add_local_var(ctx, decl)?; + let pointer = self.program.add_local_var(ctx, &mut block, decl)?; + + ctx.emit_flush(&mut block); + ctx.emit_start(); block.push(Statement::Store { pointer, value }); value } else { - let root = self.parse_expression(ctx)?; + let root = self.parse_expression(ctx, &mut block)?; ctx.lower(self.program, root, false, &mut block)?.0 }; - body.push(Statement::If { - condition: ctx.expressions.append(Expression::Unary { + let condition = ctx.add_expression( + Expression::Unary { op: UnaryOperator::Not, expr, - }), + }, + &mut block, + ); + + ctx.emit_flush(&mut block); + ctx.emit_start(); + + body.push(Statement::If { + condition, accept: vec![Statement::Break], reject: Block::new(), }); @@ -1419,7 +1465,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match self.expect_peek()?.value { TokenValue::RightParen => {} _ => { - let rest = self.parse_expression(ctx)?; + let rest = self.parse_expression(ctx, &mut continuing)?; ctx.lower(self.program, rest, false, &mut continuing)?; } } @@ -1462,7 +1508,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { | TokenValue::IntConstant(_) | TokenValue::BoolConstant(_) | TokenValue::FloatConstant(_) => { - let expr = self.parse_expression(ctx)?; + let expr = self.parse_expression(ctx, body)?; ctx.lower(self.program, expr, false, body)?; self.expect(TokenValue::Semicolon)?; } @@ -1560,8 +1606,8 @@ impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { }; match self.external { - true => program.add_global_var(self.ctx, decl), - false => program.add_local_var(self.ctx, decl), + true => program.add_global_var(self.ctx, self.body, decl), + false => program.add_local_var(self.ctx, self.body, decl), } } } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index d57ce2a7e..22201b8d2 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,6 +1,6 @@ use crate::{ - Binding, BuiltIn, Constant, Expression, GlobalVariable, Handle, LocalVariable, ScalarKind, - StorageAccess, StorageClass, Type, TypeInner, VectorSize, + Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, LocalVariable, + ScalarKind, StorageAccess, StorageClass, Type, TypeInner, VectorSize, }; use super::ast::*; @@ -18,119 +18,102 @@ pub struct VarDeclaration<'a> { impl Program<'_> { pub fn lookup_variable( &mut self, - context: &mut Context, + ctx: &mut Context, + body: &mut Block, name: &str, ) -> Result, ErrorKind> { - if let Some(local_var) = context.lookup_local_var(name) { + if let Some(local_var) = ctx.lookup_local_var(name) { return Ok(Some(local_var)); } - if let Some(global_var) = context.lookup_global_var(self, name) { + if let Some(global_var) = ctx.lookup_global_var(name) { return Ok(Some(global_var)); } - if let Some(constant) = context.lookup_constants_var(self, name) { - return Ok(Some(constant)); - } + + let mut add_builtin = |inner, builtin, mutable| { + let ty = self + .module + .types + .fetch_or_append(Type { name: None, inner }); + + let handle = self.module.global_variables.append(GlobalVariable { + name: Some(name.into()), + class: StorageClass::Private, + binding: None, + ty, + init: None, + storage_access: StorageAccess::all(), + }); + + self.entry_args + .push((Binding::BuiltIn(builtin), true, handle)); + + self.global_variables + .push((name.into(), GlobalLookup::Variable(handle))); + + let expr = ctx.add_expression(Expression::GlobalVariable(handle), body); + let load = ctx.add_expression(Expression::Load { pointer: expr }, body); + ctx.lookup_global_var_exps.insert( + name.into(), + VariableReference { + expr, + load: Some(load), + mutable, + }, + ); + + Ok(ctx.lookup_global_var(name)) + }; match name { - "gl_Position" => { - let ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Quad, - kind: ScalarKind::Float, - width: 4, - }, - }); - - let handle = self.module.global_variables.append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Private, - binding: None, - ty, - init: None, - storage_access: StorageAccess::all(), - }); - - self.entry_args - .push((Binding::BuiltIn(BuiltIn::Position), true, handle)); - - self.lookup_global_variables - .insert(name.into(), GlobalLookup::Variable(handle)); - - Ok(context.lookup_global_var(self, name)) - } - "gl_VertexIndex" => { - let ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - }, - }); - - let handle = self.module.global_variables.append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Private, - binding: None, - ty, - init: None, - storage_access: StorageAccess::all(), - }); - - self.entry_args - .push((Binding::BuiltIn(BuiltIn::VertexIndex), true, handle)); - - self.lookup_global_variables - .insert(name.into(), GlobalLookup::Variable(handle)); - - Ok(context.lookup_global_var(self, name)) - } - "gl_InstanceIndex" => { - let ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: ScalarKind::Sint, - width: 4, - }, - }); - - let handle = self.module.global_variables.append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Private, - binding: None, - ty, - init: None, - storage_access: StorageAccess::all(), - }); - - self.entry_args - .push((Binding::BuiltIn(BuiltIn::InstanceIndex), true, handle)); - - self.lookup_global_variables - .insert(name.into(), GlobalLookup::Variable(handle)); - - Ok(context.lookup_global_var(self, name)) - } + "gl_Position" => add_builtin( + TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 4, + }, + BuiltIn::Position, + true, + ), + "gl_VertexIndex" => add_builtin( + TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + BuiltIn::VertexIndex, + false, + ), + "gl_InstanceIndex" => add_builtin( + TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + BuiltIn::InstanceIndex, + false, + ), _ => Ok(None), } } pub fn field_selection( &mut self, - context: &mut Context, + ctx: &mut Context, + body: &mut Block, expression: Handle, name: &str, meta: SourceMetadata, ) -> Result, ErrorKind> { - match *self.resolve_type(context, expression, meta)? { + match *self.resolve_type(ctx, expression, meta)? { TypeInner::Struct { ref members, .. } => { let index = members .iter() .position(|m| m.name == Some(name.into())) .ok_or_else(|| ErrorKind::UnknownField(meta, name.into()))?; - Ok(context.expressions.append(Expression::AccessIndex { - base: expression, - index: index as u32, - })) + Ok(ctx.add_expression( + Expression::AccessIndex { + base: expression, + index: index as u32, + }, + body, + )) } // swizzles (xyzw, rgba, stpq) TypeInner::Vector { size, kind, width } => { @@ -159,41 +142,40 @@ impl Program<'_> { let components: Vec> = v .iter() .map(|idx| { - context.expressions.append(Expression::AccessIndex { - base: expression, - index: *idx as u32, - }) + ctx.add_expression( + Expression::AccessIndex { + base: expression, + index: *idx as u32, + }, + body, + ) }) .collect(); if components.len() == 1 { // only single element swizzle, like pos.y, just return that component Ok(components[0]) } else { - Ok(context.expressions.append(Expression::Compose { - ty: self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - kind, - width, - size: match components.len() { - 2 => VectorSize::Bi, - 3 => VectorSize::Tri, - 4 => VectorSize::Quad, - _ => { - return Err(ErrorKind::SemanticError( - meta, - format!( - "Bad swizzle size for \"{:?}\": {:?}", - name, v - ) - .into(), - )); - } - }, - }, - }), - components, - })) + let size = match components.len() { + 2 => VectorSize::Bi, + 3 => VectorSize::Tri, + 4 => VectorSize::Quad, + _ => { + return Err(ErrorKind::SemanticError( + meta, + format!("Bad swizzle size for \"{:?}\": {:?}", name, v).into(), + )); + } + }; + Ok(ctx.add_expression( + Expression::Compose { + ty: self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { kind, width, size }, + }), + components, + }, + body, + )) } } else { Err(ErrorKind::SemanticError( @@ -212,6 +194,7 @@ impl Program<'_> { pub fn add_global_var( &mut self, ctx: &mut Context, + body: &mut Block, VarDeclaration { qualifiers, ty, @@ -334,18 +317,18 @@ impl Program<'_> { handle, )); - self.lookup_global_variables - .insert(name, GlobalLookup::Variable(handle)); + self.global_variables + .push((name, GlobalLookup::Variable(handle))); - return Ok(ctx.expressions.append(Expression::GlobalVariable(handle))); + return Ok(ctx.add_expression(Expression::GlobalVariable(handle), body)); } else if let StorageQualifier::Const = storage { let handle = init.ok_or_else(|| { ErrorKind::SemanticError(meta, "Constant must have a initializer".into()) })?; - self.lookup_constants.insert(name, handle); + self.constants.push((name, handle)); - return Ok(ctx.expressions.append(Expression::Constant(handle))); + return Ok(ctx.add_expression(Expression::Constant(handle), body)); } let class = match storage { @@ -363,15 +346,16 @@ impl Program<'_> { storage_access: StorageAccess::all(), }); - self.lookup_global_variables - .insert(name, GlobalLookup::Variable(handle)); + self.global_variables + .push((name, GlobalLookup::Variable(handle))); - Ok(ctx.expressions.append(Expression::GlobalVariable(handle))) + Ok(ctx.add_expression(Expression::GlobalVariable(handle), body)) } pub fn add_local_var( &mut self, ctx: &mut Context, + body: &mut Block, VarDeclaration { qualifiers, ty, @@ -413,7 +397,7 @@ impl Program<'_> { ty, init, }); - let expr = ctx.expressions.append(Expression::LocalVariable(handle)); + let expr = ctx.add_expression(Expression::LocalVariable(handle), body); ctx.add_local_var(name, expr, mutable); diff --git a/src/front/mod.rs b/src/front/mod.rs index 72242bbc7..15fcfe494 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -14,8 +14,8 @@ use crate::{ /// Helper class to emit expressions #[allow(dead_code)] -#[derive(Default)] -struct Emitter { +#[derive(Default, Debug)] +pub(crate) struct Emitter { start_len: Option, } From c526c85258ce0ebef38c21f5fd0c6a1e3be434f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 20 May 2021 21:47:04 +0100 Subject: [PATCH 0875/2212] [glsl-in] Fix function argument generation --- src/front/glsl/ast.rs | 24 +++++++++++++++++------- src/front/glsl/parser.rs | 8 ++++---- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 0de03552b..b0781715a 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -276,7 +276,13 @@ impl<'function> Context<'function> { } /// Add function argument to current scope - pub fn add_function_arg(&mut self, name: Option, ty: Handle, mutable: bool) { + pub fn add_function_arg( + &mut self, + body: &mut Block, + name: Option, + ty: Handle, + parameter: ParameterQualifier, + ) { let index = self.arguments.len(); self.arguments.push(FunctionArgument { name: name.clone(), @@ -285,16 +291,20 @@ impl<'function> Context<'function> { }); if let Some(name) = name { - if let Some(current) = self.scopes.last_mut() { - let expr = self - .expressions - .append(Expression::FunctionArgument(index as u32)); + let expr = self.add_expression(Expression::FunctionArgument(index as u32), body); + let mutable = parameter != ParameterQualifier::Const; + let load = if parameter.is_lhs() { + Some(self.add_expression(Expression::Load { pointer: expr }, body)) + } else { + None + }; + if let Some(current) = self.scopes.last_mut() { (*current).insert( name, VariableReference { expr, - load: None, + load, mutable, }, ); @@ -520,7 +530,7 @@ pub enum StructLayout { Std140, } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Copy)] pub enum ParameterQualifier { In, Out, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0283fb1c5..3e9fd25bb 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -577,7 +577,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { &mut arguments, ); - self.parse_function_args(&mut context, &mut parameters)?; + self.parse_function_args(&mut context, &mut body, &mut parameters)?; let end_meta = self.expect(TokenValue::RightParen)?.meta; meta = meta.union(&end_meta); @@ -1540,19 +1540,19 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_function_args( &mut self, context: &mut Context, + body: &mut Block, parameters: &mut Vec, ) -> Result<()> { loop { if self.peek_type_name() || self.peek_parameter_qualifier() { let qualifier = self.parse_parameter_qualifier(); - let mutable = qualifier != ParameterQualifier::Const; parameters.push(qualifier); let ty = self.parse_type_non_void()?.0; match self.expect_peek()?.value { TokenValue::Comma => { self.bump()?; - context.add_function_arg(None, ty, mutable); + context.add_function_arg(body, None, ty, qualifier); continue; } TokenValue::Identifier(_) => { @@ -1561,7 +1561,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let size = self.parse_array_specifier()?; let ty = self.maybe_array(ty, size); - context.add_function_arg(Some(name), ty, mutable); + context.add_function_arg(body, Some(name), ty, qualifier); if self.bump_if(TokenValue::Comma).is_some() { continue; From 4e95c46a9dd8e734e51096677e5fdb6baee4381d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 20 May 2021 22:28:34 +0100 Subject: [PATCH 0876/2212] [glsl-in] Fix void function calls --- src/front/glsl/ast.rs | 53 ++++++++++++++++++++++++++---------- src/front/glsl/functions.rs | 54 ++++++++++++++++++++++--------------- src/front/glsl/parser.rs | 23 +++++++++------- 3 files changed, 86 insertions(+), 44 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index b0781715a..d770efcee 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -24,6 +24,8 @@ pub struct FunctionDeclaration { pub handle: Handle, /// Wheter this function was already defined or is just a prototype pub defined: bool, + /// Wheter or not this function returns void (nothing) + pub void: bool, } #[derive(Debug)] @@ -321,24 +323,46 @@ impl<'function> Context<'function> { self.scopes.pop(); } - pub fn lower( + pub fn lower_expect( &mut self, program: &mut Program, expr: Handle, lhs: bool, body: &mut Block, ) -> Result<(Handle, SourceMetadata), ErrorKind> { + let (maybe_expr, meta) = self.lower(program, expr, lhs, body)?; + + let expr = match maybe_expr { + Some(e) => e, + None => { + return Err(ErrorKind::SemanticError( + meta, + "Expression returns void".into(), + )) + } + }; + + Ok((expr, meta)) + } + + pub fn lower( + &mut self, + program: &mut Program, + expr: Handle, + lhs: bool, + body: &mut Block, + ) -> Result<(Option>, SourceMetadata), ErrorKind> { let HirExpr { kind, meta } = self.hir_exprs[expr].clone(); let handle = match kind { HirExprKind::Access { base, index } => { - let base = self.lower(program, base, lhs, body)?.0; - let index = self.lower(program, index, false, body)?.0; + let base = self.lower_expect(program, base, lhs, body)?.0; + let index = self.lower_expect(program, index, false, body)?.0; self.add_expression(Expression::Access { base, index }, body) } HirExprKind::Select { base, field } => { - let base = self.lower(program, base, lhs, body)?.0; + let base = self.lower_expect(program, base, lhs, body)?.0; program.field_selection(self, body, base, &field, meta)? } @@ -346,8 +370,8 @@ impl<'function> Context<'function> { self.add_expression(Expression::Constant(constant), body) } HirExprKind::Binary { left, op, right } if !lhs => { - let (left, left_meta) = self.lower(program, left, false, body)?; - let (right, right_meta) = self.lower(program, right, false, body)?; + let (left, left_meta) = self.lower_expect(program, left, false, body)?; + let (right, right_meta) = self.lower_expect(program, right, false, body)?; if let BinaryOperator::Equal | BinaryOperator::NotEqual = op { let equals = op == BinaryOperator::Equal; @@ -386,7 +410,7 @@ impl<'function> Context<'function> { } } HirExprKind::Unary { op, expr } if !lhs => { - let expr = self.lower(program, expr, false, body)?.0; + let expr = self.lower_expect(program, expr, false, body)?.0; self.add_expression(Expression::Unary { op, expr }, body) } @@ -405,16 +429,17 @@ impl<'function> Context<'function> { } } HirExprKind::Call(call) if !lhs => { - program.function_call(self, body, call.kind, &call.args, meta)? + let maybe_expr = program.function_call(self, body, call.kind, &call.args, meta)?; + return Ok((maybe_expr, meta)); } HirExprKind::Conditional { condition, accept, reject, } if !lhs => { - let condition = self.lower(program, condition, false, body)?.0; - let accept = self.lower(program, accept, false, body)?.0; - let reject = self.lower(program, reject, false, body)?.0; + let condition = self.lower_expect(program, condition, false, body)?.0; + let accept = self.lower_expect(program, accept, false, body)?.0; + let reject = self.lower_expect(program, reject, false, body)?.0; self.add_expression( Expression::Select { @@ -426,8 +451,8 @@ impl<'function> Context<'function> { ) } HirExprKind::Assign { tgt, value } if !lhs => { - let pointer = self.lower(program, tgt, true, body)?.0; - let value = self.lower(program, value, false, body)?.0; + let pointer = self.lower_expect(program, tgt, true, body)?.0; + let value = self.lower_expect(program, value, false, body)?.0; self.emit_flush(body); self.emit_start(); @@ -444,7 +469,7 @@ impl<'function> Context<'function> { } }; - Ok((handle, meta)) + Ok((Some(handle), meta)) } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 766f255e1..7659d23ea 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -15,10 +15,10 @@ impl Program<'_> { fc: FunctionCallKind, raw_args: &[Handle], meta: SourceMetadata, - ) -> Result, ErrorKind> { + ) -> Result>, ErrorKind> { let args: Vec<_> = raw_args .iter() - .map(|e| ctx.lower(self, *e, false, body)) + .map(|e| ctx.lower_expect(self, *e, false, body)) .collect::>()?; match fc { @@ -89,7 +89,7 @@ impl Program<'_> { ) }; - Ok(h) + Ok(Some(h)) } FunctionCallKind::Function(name) => { match name.as_str() { @@ -98,14 +98,14 @@ impl Program<'_> { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } ctx.samplers.insert(args[0].0, args[1].0); - Ok(args[0].0) + Ok(Some(args[0].0)) } "texture" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(ctx.add_expression( + Ok(Some(ctx.add_expression( Expression::ImageSample { image: args[0].0, sampler, @@ -116,7 +116,7 @@ impl Program<'_> { depth_ref: None, }, body, - )) + ))) } else { Err(ErrorKind::SemanticError(meta, "Bad call to texture".into())) } @@ -126,7 +126,7 @@ impl Program<'_> { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(ctx.add_expression( + Ok(Some(ctx.add_expression( Expression::ImageSample { image: args[0].0, sampler, @@ -137,7 +137,7 @@ impl Program<'_> { depth_ref: None, }, body, - )) + ))) } else { Err(ErrorKind::SemanticError( meta, @@ -151,7 +151,7 @@ impl Program<'_> { if args.len() != 1 { return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); } - Ok(ctx.add_expression( + Ok(Some(ctx.add_expression( Expression::Math { fun: match name.as_str() { "ceil" => MathFunction::Ceil, @@ -176,13 +176,13 @@ impl Program<'_> { arg2: None, }, body, - )) + ))) } "pow" | "dot" | "max" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } - Ok(ctx.add_expression( + Ok(Some(ctx.add_expression( Expression::Math { fun: match name.as_str() { "pow" => MathFunction::Pow, @@ -195,13 +195,13 @@ impl Program<'_> { arg2: None, }, body, - )) + ))) } "mix" | "clamp" => { if args.len() != 3 { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } - Ok(ctx.add_expression( + Ok(Some(ctx.add_expression( Expression::Math { fun: match name.as_str() { "mix" => MathFunction::Mix, @@ -213,14 +213,14 @@ impl Program<'_> { arg2: Some(args[2].0), }, body, - )) + ))) } "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" | "notEqual" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } - Ok(ctx.add_expression( + Ok(Some(ctx.add_expression( Expression::Binary { op: match name.as_str() { "lessThan" => BinaryOperator::Less, @@ -235,7 +235,7 @@ impl Program<'_> { right: args[1].0, }, body, - )) + ))) } "isinf" | "isnan" | "all" | "any" => { let fun = match name.as_str() { @@ -246,7 +246,9 @@ impl Program<'_> { _ => unreachable!(), }; - self.parse_relational_fun(ctx, body, name, &args, fun, meta) + Ok(Some( + self.parse_relational_fun(ctx, body, name, &args, fun, meta)?, + )) } _ => { let mut parameters = Vec::new(); @@ -273,22 +275,27 @@ impl Program<'_> { let mut arguments = Vec::with_capacity(raw_args.len()); for (qualifier, expr) in fun.parameters.iter().zip(raw_args.iter()) { - let handle = ctx.lower(self, *expr, qualifier.is_lhs(), body)?.0; + let handle = ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?.0; arguments.push(handle) } ctx.emit_flush(body); - let expression = ctx.add_expression(Expression::Call(fun.handle), body); + let result = if !fun.void { + Some(ctx.add_expression(Expression::Call(fun.handle), body)) + } else { + None + }; + body.push(crate::Statement::Call { function: fun.handle, arguments, - result: Some(expression), + result, }); ctx.emit_start(); - Ok(expression) + Ok(result) } } } @@ -351,6 +358,8 @@ impl Program<'_> { } } + let void = function.result.is_none(); + if let Some(decl) = self.lookup_function.get_mut(&sig) { if decl.defined { return Err(ErrorKind::SemanticError( @@ -369,6 +378,7 @@ impl Program<'_> { parameters, handle, defined: true, + void, }, ); } @@ -391,6 +401,7 @@ impl Program<'_> { name, parameters: function.arguments.iter().map(|p| p.ty).collect(), }; + let void = function.result.is_none(); for (arg, qualifier) in function.arguments.iter_mut().zip(parameters.iter()) { if qualifier.is_lhs() { @@ -412,6 +423,7 @@ impl Program<'_> { parameters, handle, defined: false, + void, }, ); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 3e9fd25bb..56fc1c32d 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -330,7 +330,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ); let expr = self.parse_conditional(&mut ctx, &mut block, None)?; - let (root, meta) = ctx.lower(self.program, expr, false, &mut block)?; + let (root, meta) = ctx.lower_expect(self.program, expr, false, &mut block)?; Ok((self.program.solve_constant(&ctx, root, meta)?, meta)) } @@ -434,7 +434,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { )) } else { let expr = self.parse_assignment(ctx, body)?; - Ok(ctx.lower(self.program, expr, false, body)?) + Ok(ctx.lower_expect(self.program, expr, false, body)?) } } @@ -1183,7 +1183,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { _ => { let expr = self.parse_expression(ctx, body)?; self.expect(TokenValue::Semicolon)?; - Some(ctx.lower(self.program, expr, false, body)?.0) + Some(ctx.lower_expect(self.program, expr, false, body)?.0) } }; @@ -1203,7 +1203,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::LeftParen)?; let condition = { let expr = self.parse_expression(ctx, body)?; - ctx.lower(self.program, expr, false, body)?.0 + ctx.lower_expect(self.program, expr, false, body)?.0 }; self.expect(TokenValue::RightParen)?; @@ -1230,7 +1230,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::LeftParen)?; let selector = { let expr = self.parse_expression(ctx, body)?; - ctx.lower(self.program, expr, false, body)?.0 + ctx.lower_expect(self.program, expr, false, body)?.0 }; self.expect(TokenValue::RightParen)?; @@ -1247,7 +1247,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.bump()?; let value = { let expr = self.parse_expression(ctx, body)?; - let (root, meta) = ctx.lower(self.program, expr, false, body)?; + let (root, meta) = + ctx.lower_expect(self.program, expr, false, body)?; let constant = self.program.solve_constant(&ctx, root, meta)?; match self.program.module.constants[constant].inner { @@ -1332,7 +1333,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let root = self.parse_expression(ctx, &mut loop_body)?; self.expect(TokenValue::RightParen)?; - let expr = ctx.lower(self.program, root, false, &mut loop_body)?.0; + let expr = ctx + .lower_expect(self.program, root, false, &mut loop_body)? + .0; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -1368,7 +1371,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let root = self.parse_expression(ctx, &mut loop_body)?; self.expect(TokenValue::RightParen)?; - let expr = ctx.lower(self.program, root, false, &mut loop_body)?.0; + let expr = ctx + .lower_expect(self.program, root, false, &mut loop_body)? + .0; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -1439,7 +1444,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { value } else { let root = self.parse_expression(ctx, &mut block)?; - ctx.lower(self.program, root, false, &mut block)?.0 + ctx.lower_expect(self.program, root, false, &mut block)?.0 }; let condition = ctx.add_expression( From 72fca17dbc56a33acdf53ab6eab113386a774731 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 20 May 2021 22:29:12 +0100 Subject: [PATCH 0877/2212] [glsl-in] Cleanup --- src/front/glsl/ast.rs | 58 +++++++++++++++++++++++----------------- src/front/glsl/parser.rs | 8 ++++-- src/front/mod.rs | 2 +- 3 files changed, 40 insertions(+), 28 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index d770efcee..9be082775 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,9 +1,14 @@ -use super::{super::Typifier, constants::ConstantSolver, error::ErrorKind, SourceMetadata}; +use super::{ + super::{Emitter, Typifier}, + constants::ConstantSolver, + error::ErrorKind, + SourceMetadata, +}; use crate::{ - front::Emitter, proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, - Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, - LocalVariable, Module, RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, - StorageClass, Type, TypeInner, UnaryOperator, + proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, Expression, FastHashMap, + Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, + RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, + TypeInner, UnaryOperator, }; #[derive(Debug, Clone, Copy)] @@ -185,33 +190,36 @@ impl<'function> Context<'function> { this.emit_start(); - for &(ref name, lookup) in program.global_variables.iter() { - let expr = match lookup { - GlobalLookup::Variable(v) => Expression::GlobalVariable(v), - GlobalLookup::BlockSelect(handle, index) => { - let base = this.add_expression(Expression::GlobalVariable(handle), body); - - Expression::AccessIndex { base, index } - } - }; - - let expr = this.add_expression(expr, body); + for &(ref name, handle) in program.constants.iter() { + let expr = this.expressions.append(Expression::Constant(handle)); let var = VariableReference { expr, - load: Some(this.add_expression(Expression::Load { pointer: expr }, body)), - // TODO: respect constant qualifier - mutable: true, + load: None, + mutable: false, }; this.lookup_global_var_exps.insert(name.into(), var); } - for &(ref name, handle) in program.constants.iter() { - let expr = this.add_expression(Expression::Constant(handle), body); + for &(ref name, lookup) in program.global_variables.iter() { + this.emit_flush(body); + let expr = match lookup { + GlobalLookup::Variable(v) => Expression::GlobalVariable(v), + GlobalLookup::BlockSelect(handle, index) => { + let base = this.expressions.append(Expression::GlobalVariable(handle)); + + Expression::AccessIndex { base, index } + } + }; + + let expr = this.expressions.append(expr); + this.emit_start(); + let var = VariableReference { expr, - load: None, - mutable: false, + load: Some(this.add_expression(Expression::Load { pointer: expr }, body)), + // TODO: respect constant qualifier + mutable: true, }; this.lookup_global_var_exps.insert(name.into(), var); @@ -231,9 +239,9 @@ impl<'function> Context<'function> { pub fn add_expression(&mut self, expr: Expression, body: &mut Block) -> Handle { if expr.needs_pre_emit() { self.emit_flush(body); - let expr = self.expressions.append(expr); + let handle = self.expressions.append(expr); self.emit_start(); - expr + handle } else { self.expressions.append(expr) } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 56fc1c32d..61ad7cab4 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -512,8 +512,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let pointer = ctx.add_var(self.program, ty, name, maybe_constant, meta)?; if let Some((value, _)) = init { - ctx.ctx.emit_flush(ctx.body); - ctx.ctx.emit_start(); + ctx.flush_expressions(); ctx.body.push(Statement::Store { pointer, value }); } @@ -1615,6 +1614,11 @@ impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { false => program.add_local_var(self.ctx, self.body, decl), } } + + fn flush_expressions(&mut self) { + self.ctx.emit_flush(self.body); + self.ctx.emit_start() + } } fn binding_power(value: &TokenValue) -> Option<(u8, u8)> { diff --git a/src/front/mod.rs b/src/front/mod.rs index 15fcfe494..0509258ce 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -15,7 +15,7 @@ use crate::{ /// Helper class to emit expressions #[allow(dead_code)] #[derive(Default, Debug)] -pub(crate) struct Emitter { +struct Emitter { start_len: Option, } From 6c4012f9c43c2aecc2e78e94db4c98174e418200 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 20 May 2021 15:14:09 +0300 Subject: [PATCH 0878/2212] Add Vulkan tutorial shaders to lazy check --- .github/workflows/lazy.yml | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index 5d6bc561f..aacbfaf33 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -44,3 +44,35 @@ jobs: run: cargo build --release --features spv-in,msl-out --bin naga - name: Convert shaders run: for file in data/*.spv ; do echo "Translating" ${file} && target/release/naga --validate 27 ${file} ${file}.metal; done + parse-vulkan-tutorial-shaders: + name: Parse Sascha Willems Vulkan tutorial shaders + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + - name: Download shaders + run: git clone https://github.com/SaschaWillems/Vulkan.git + - name: Build Naga + run: cargo build --release --features spv-in,msl-out --bin naga + - name: Convert metal shaders + run: | + # No needed to stop workflow if we can't validate one file + set +e + touch counter + SUCCESS_RESULT_COUNT=0 + FILE_COUNT=0 + mkdir -p out + find "Vulkan/data/shaders/glsl/" -name '*.spv' | while read fname; + do + echo "Convert: $fname" + FILE_COUNT=$((FILE_COUNT+1)) + target/release/naga --validate 27 $(realpath ${fname}) out/$(basename ${fname}).metal + if [[ $? -eq 0 ]]; then + SUCCESS_RESULT_COUNT=$((SUCCESS_RESULT_COUNT + 1)) + fi + echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter + done + cat counter From 3dd9cc0c665680b4331d97ee528308e07960f2a1 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 20 May 2021 14:44:10 +0000 Subject: [PATCH 0879/2212] [wgsl-out] Skip access to unsupported builtin inside Store statement --- src/back/wgsl/writer.rs | 69 ++++++++++++++++++++++++----------------- 1 file changed, 40 insertions(+), 29 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 6bc3d6e09..2f774bdea 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -632,8 +632,15 @@ impl Writer { write!(self.out, "{}", INDENT.repeat(indent))?; writeln!(self.out, "discard;")? } - // TODO: copy-paste from glsl-out Statement::Store { pointer, value } => { + // WGSL does not support all SPIR-V builtins and we should skip it in generated shaders. + // We already skip them when we generate struct type. + // Now we need to find expression that used struct with ignored builtins + if let Expression::AccessIndex { base, index } = func_ctx.expressions[pointer] { + if access_to_unsupported_builtin(base, index, module, &func_ctx.info) { + return Ok(()); + } + } write!(self.out, "{}", INDENT.repeat(indent))?; self.write_expr(module, pointer, func_ctx)?; write!(self.out, " = ")?; @@ -857,35 +864,11 @@ impl Writer { for component in components { let mut skip_component = false; if let Expression::Load { pointer } = func_ctx.expressions[*component] { - if let Expression::AccessIndex { - base, - index: access_index, - } = func_ctx.expressions[pointer] + if let Expression::AccessIndex { base, index } = + func_ctx.expressions[pointer] { - let base_ty_res = &func_ctx.info[base].ty; - let resolved = base_ty_res.inner_with(&module.types); - if let TypeInner::Pointer { - base: pointer_base_handle, - .. - } = *resolved - { - // Let's check that we try to access a struct member with unsupported built-in and skip it. - if let TypeInner::Struct { ref members, .. } = - module.types[pointer_base_handle].inner - { - if let Some(Binding::BuiltIn(builtin)) = - members[access_index as usize].binding - { - if builtin_str(builtin).is_none() { - // glslang why you did this with us... - log::warn!( - "Skip component with unsupported builtin {:?}", - builtin - ); - skip_component = true; - } - } - } + if access_to_unsupported_builtin(base, index, module, &func_ctx.info) { + skip_component = true; } } } @@ -1568,3 +1551,31 @@ fn is_deref_required(expr: Handle, module: &Module, info: &FunctionI _ => false, } } + +/// Helper function that check that expression don't access to structure member with unsupported builtin. +fn access_to_unsupported_builtin( + expr: Handle, + index: u32, + module: &Module, + info: &FunctionInfo, +) -> bool { + let base_ty_res = &info[expr].ty; + let resolved = base_ty_res.inner_with(&module.types); + if let TypeInner::Pointer { + base: pointer_base_handle, + .. + } = *resolved + { + // Let's check that we try to access a struct member with unsupported built-in and skip it. + if let TypeInner::Struct { ref members, .. } = module.types[pointer_base_handle].inner { + if let Some(Binding::BuiltIn(builtin)) = members[index as usize].binding { + if builtin_str(builtin).is_none() { + log::warn!("Skip component with unsupported builtin {:?}", builtin); + return true; + } + } + } + } + + false +} From ad550addb89f30fd6bf54838f862637b15341869 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 20 May 2021 14:22:31 -0700 Subject: [PATCH 0880/2212] [spv-out] Take advantage of `use` abbreviation. --- src/back/spv/writer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 176f5f491..d50c28e52 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -729,7 +729,7 @@ impl Writer { } Instruction::type_int(id, bits, signedness) } - crate::ScalarKind::Float => { + Sk::Float => { if bits == 64 { self.capabilities.insert(spirv::Capability::Float64); } From 8bcd2a4a1f942a7a0c934548667f73c4dcd04550 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 21 May 2021 13:11:06 -0700 Subject: [PATCH 0881/2212] [spv-in]: Typo. --- src/front/spv/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index fa3c7263f..86998bbc2 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -905,7 +905,7 @@ impl> Parser { log::trace!("\t\t\tlooking up expr {:?}", base_id); let mut acex = { // the base type has to be a pointer, - // so we derefernce it here for the traversal + // so we dereference it here for the traversal let lexp = self.lookup_expression.lookup(base_id)?; let lty = self.lookup_type.lookup(lexp.type_id)?; AccessExpression { From 652a955e9bd4ad61d0d18feb3568855ceb0332cd Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 21 May 2021 13:11:23 -0700 Subject: [PATCH 0882/2212] Expression::As: Typo. --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 5413b45c0..9dc6c0b22 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -891,7 +891,7 @@ pub enum Expression { arg1: Option>, arg2: Option>, }, - /// Cast a simply type to another kind. + /// Cast a simple type to another kind. As { /// Source expression, which can only be a scalar or a vector. expr: Handle, From 50de6ae9ac81be841266691f1a5ad984b67a82af Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 21 May 2021 13:11:35 -0700 Subject: [PATCH 0883/2212] Improve error messages for missing I/O bindings. The `apply_common_default_interpolation` helper function would panic if bindings were missing, but missing bindings should be something that front ends can count on validation to detect, so the helper should just return silently. The validator returned `InvalidType` errors for missing bindings, apparently because variables without bindings must be structs that do have bindings. But this is unhelpful when you've just forgotten to label an argument. So this patch adds a new, more specific, `VaryingError` variant. --- src/proc/interpolator.rs | 69 +++++++++++++++++++---------------- src/valid/interface.rs | 4 ++- tests/wgsl-errors.rs | 77 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 117 insertions(+), 33 deletions(-) diff --git a/src/proc/interpolator.rs b/src/proc/interpolator.rs index 90e6cb57e..df48c0c3f 100644 --- a/src/proc/interpolator.rs +++ b/src/proc/interpolator.rs @@ -41,36 +41,49 @@ impl crate::Module { ty: Handle, types: &mut Arena, ) { - match types.get_mut(ty).inner { + let inner = &mut types.get_mut(ty).inner; + if let TypeInner::Struct { + members: ref mut m, .. + } = *inner + { // A struct. It's the individual members we care about, so recurse. - TypeInner::Struct { - members: ref mut m, .. - } => { - // To choose the right interpolations for `members`, we must consult other - // elements of `types`. But both `members` and the types it refers to are stored - // in `types`, and Rust won't let us mutate one element of the `Arena`'s `Vec` - // while reading others. - // - // So, temporarily swap the member list out its type, assign appropriate - // interpolations to its members, and then swap the list back in. - use std::mem::replace; - let mut members = replace(m, vec![]); - for member in &mut members { - default_binding_or_struct(&mut member.binding, member.ty, types); - } + // To choose the right interpolations for `members`, we must consult other + // elements of `types`. But both `members` and the types it refers to are stored + // in `types`, and Rust won't let us mutate one element of the `Arena`'s `Vec` + // while reading others. + // + // So, temporarily swap the member list out its type, assign appropriate + // interpolations to its members, and then swap the list back in. + use std::mem::replace; + let mut members = replace(m, vec![]); - // Swap the member list back in. It's essential that we call `types.get_mut` - // afresh here, rather than just using `m`: it's only because `m` was dead that - // we were able to pass `types` to the recursive call. - match types.get_mut(ty).inner { - TypeInner::Struct { - members: ref mut m, .. - } => replace(m, members), - _ => unreachable!("ty must be a struct"), - }; + for member in &mut members { + default_binding_or_struct(&mut member.binding, member.ty, types); } + // Swap the member list back in. It's essential that we call `types.get_mut` + // afresh here, rather than just using `m`: it's only because `m` was dead that + // we were able to pass `types` to the recursive call. + match types.get_mut(ty).inner { + TypeInner::Struct { + members: ref mut m, .. + } => replace(m, members), + _ => unreachable!("ty must be a struct"), + }; + + return; + } + + // For all other types, a binding is required. Missing bindings will + // be caught during validation, but this processor is meant for use + // by front ends before validation, so just return for now. + let binding = match binding.as_mut() { + None => return, + Some(binding) => binding, + }; + + match *inner { // Some interpolatable type. // // GLSL has 64-bit floats, but it won't interpolate them. WGSL and MSL only have @@ -85,9 +98,6 @@ impl crate::Module { width: 4, .. } => { - // unwrap: all `EntryPoint` arguments or return values must either be structures - // or have a `Binding`. - let binding = binding.as_mut().unwrap(); if let Binding::Location { ref mut interpolation, ref mut sampling, @@ -106,9 +116,6 @@ impl crate::Module { // Some type that can't be interpolated. _ => { - // unwrap: all `EntryPoint` arguments or return values must either be structures - // or have a `Binding`. - let binding = binding.as_mut().unwrap(); if let Binding::Location { ref mut interpolation, ref mut sampling, diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 3d7830b8a..a9fbf82b8 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -45,6 +45,8 @@ pub enum VaryingError { InvalidBuiltInStage(crate::BuiltIn), #[error("BuiltIn type for {0:?} is invalid")] InvalidBuiltInType(crate::BuiltIn), + #[error("Entry point arguments and return values must all have bindings")] + MissingBinding, #[error("Struct member {0} is missing a binding")] MemberMissingBinding(u32), #[error("Multiple bindings at location {location} are present")] @@ -276,7 +278,7 @@ impl VaryingContext<'_> { } } } - _ => return Err(VaryingError::InvalidType(self.ty)), + _ => return Err(VaryingError::MissingBinding), } Ok(()) } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index db70992d2..dd0221b65 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -99,7 +99,7 @@ macro_rules! check_validation_error { let error = validation_error($source); if ! matches!(error, $pattern) { eprintln!("validation error does not match pattern:\n\ - {:?}\n\ + {:#?}\n\ \n\ expected match for pattern:\n\ {}", @@ -193,3 +193,78 @@ fn invalid_structs() { }) } } + +#[test] +fn missing_bindings() { + check_validation_error! { + " + [[stage(vertex)]] + fn vertex(input: vec4) -> [[location(0)]] vec4 { + return input; + } + ": + Err(naga::valid::ValidationError::EntryPoint { + stage: naga::ShaderStage::Vertex, + error: naga::valid::EntryPointError::Argument( + 0, + naga::valid::VaryingError::MissingBinding, + ), + .. + }) + } + + check_validation_error! { + " + [[stage(vertex)]] + fn vertex([[location(0)]] input: vec4, more_input: f32) -> [[location(0)]] vec4 { + return input + more_input; + } + ": + Err(naga::valid::ValidationError::EntryPoint { + stage: naga::ShaderStage::Vertex, + error: naga::valid::EntryPointError::Argument( + 1, + naga::valid::VaryingError::MissingBinding, + ), + .. + }) + } + + check_validation_error! { + " + [[stage(vertex)]] + fn vertex([[location(0)]] input: vec4) -> vec4 { + return input; + } + ": + Err(naga::valid::ValidationError::EntryPoint { + stage: naga::ShaderStage::Vertex, + error: naga::valid::EntryPointError::Result( + naga::valid::VaryingError::MissingBinding, + ), + .. + }) + } + + check_validation_error! { + " + struct VertexIn { + [[location(0)]] pos: vec4; + uv: vec2; + }; + + [[stage(vertex)]] + fn vertex(input: VertexIn) -> [[location(0)]] vec4 { + return input.pos; + } + ": + Err(naga::valid::ValidationError::EntryPoint { + stage: naga::ShaderStage::Vertex, + error: naga::valid::EntryPointError::Argument( + 0, + naga::valid::VaryingError::MemberMissingBinding(1), + ), + .. + }) + } +} From 652b65cfa9cff89435526ecbb96702f0b3b9b9e1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 21 May 2021 00:35:45 -0400 Subject: [PATCH 0884/2212] Validate built-ins to not repeat --- src/valid/interface.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index a9fbf82b8..39bf029ff 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -41,9 +41,9 @@ pub enum VaryingError { InvalidInterpolation, #[error("Interpolation must be specified on vertex shader outputs and fragment shader inputs")] MissingInterpolation, - #[error("BuiltIn {0:?} is not available at this stage")] + #[error("Built-in {0:?} is not available at this stage")] InvalidBuiltInStage(crate::BuiltIn), - #[error("BuiltIn type for {0:?} is invalid")] + #[error("Built-in type for {0:?} is invalid")] InvalidBuiltInType(crate::BuiltIn), #[error("Entry point arguments and return values must all have bindings")] MissingBinding, @@ -51,6 +51,8 @@ pub enum VaryingError { MemberMissingBinding(u32), #[error("Multiple bindings at location {location} are present")] BindingCollision { location: u32 }, + #[error("Built-in {0:?} is present more than once")] + DuplicateBuiltIn(crate::BuiltIn), } #[derive(Clone, Debug, thiserror::Error)] @@ -96,6 +98,7 @@ struct VaryingContext<'a> { output: bool, types: &'a Arena, location_mask: &'a mut BitSet, + built_in_mask: u32, } impl VaryingContext<'_> { @@ -107,6 +110,12 @@ impl VaryingContext<'_> { let ty_inner = &self.types[self.ty].inner; match *binding { crate::Binding::BuiltIn(built_in) => { + let bit = 1 << built_in as u32; + if self.built_in_mask & bit != 0 { + return Err(VaryingError::DuplicateBuiltIn(built_in)); + } + self.built_in_mask |= bit; + let width = 4; let (visible, type_good) = match built_in { Bi::BaseInstance | Bi::BaseVertex | Bi::InstanceIndex | Bi::VertexIndex => ( @@ -257,7 +266,7 @@ impl VaryingContext<'_> { Ok(()) } - fn validate(mut self, binding: Option<&crate::Binding>) -> Result<(), VaryingError> { + fn validate(&mut self, binding: Option<&crate::Binding>) -> Result<(), VaryingError> { match binding { Some(binding) => self.validate_impl(binding), None => { @@ -409,26 +418,30 @@ impl super::Validator { } self.location_mask.clear(); + let mut argument_built_ins = 0; for (index, fa) in ep.function.arguments.iter().enumerate() { - let ctx = VaryingContext { + let mut ctx = VaryingContext { ty: fa.ty, stage: ep.stage, output: false, types: &module.types, location_mask: &mut self.location_mask, + built_in_mask: argument_built_ins, }; ctx.validate(fa.binding.as_ref()) .map_err(|e| EntryPointError::Argument(index as u32, e))?; + argument_built_ins = ctx.built_in_mask; } self.location_mask.clear(); if let Some(ref fr) = ep.function.result { - let ctx = VaryingContext { + let mut ctx = VaryingContext { ty: fr.ty, stage: ep.stage, output: true, types: &module.types, location_mask: &mut self.location_mask, + built_in_mask: 0, }; ctx.validate(fr.binding.as_ref()) .map_err(EntryPointError::Result)?; From 813da7a87e1e9404f09b128b0d901f57cc638cb3 Mon Sep 17 00:00:00 2001 From: Jack Foltz Date: Sat, 22 May 2021 13:25:58 -0400 Subject: [PATCH 0885/2212] [glsl-in] Support parsing push_constant and std430 --- src/front/glsl/ast.rs | 1 + src/front/glsl/parser.rs | 12 +++++++++++- src/front/glsl/parser_tests.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 9be082775..1d02b504a 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -561,6 +561,7 @@ pub enum StorageQualifier { #[derive(Debug, Clone, Copy)] pub enum StructLayout { Std140, + Std430, } #[derive(Debug, Clone, PartialEq, Copy)] diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 61ad7cab4..543708dc3 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -300,7 +300,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } else { match name.as_str() { + "push_constant" => { + qualifiers.push(TypeQualifier::StorageQualifier( + StorageQualifier::StorageClass(StorageClass::PushConstant), + )); + qualifiers.push(TypeQualifier::Layout(StructLayout::Std430)); + } "std140" => qualifiers.push(TypeQualifier::Layout(StructLayout::Std140)), + "std430" => qualifiers.push(TypeQualifier::Layout(StructLayout::Std430)), "early_fragment_tests" => { qualifiers.push(TypeQualifier::EarlyFragmentTests) } @@ -694,7 +701,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { for qualifier in qualifiers { match *qualifier { TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { - if StorageClass::Private != class { + if StorageClass::PushConstant == class && c == StorageClass::Uniform { + // Ignore the Uniform qualifier if the class was already set to PushConstant + continue; + } else if StorageClass::Private != class { return Err(ErrorKind::SemanticError( meta, "Cannot use more than one storage qualifier per declaration".into(), diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 3e3321e4a..91c0e22fc 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -188,6 +188,34 @@ fn declarations() { ) .unwrap(); + let _program = parse_program( + r#" + #version 450 + layout(push_constant, set = 2, binding = 0) + uniform u_locals { + vec3 model_offs; + float load_time; + ivec4 atlas_offs; + }; + "#, + &entry_points, + ) + .unwrap(); + + let _program = parse_program( + r#" + #version 450 + layout(std430, set = 2, binding = 0) + uniform u_locals { + vec3 model_offs; + float load_time; + ivec4 atlas_offs; + }; + "#, + &entry_points, + ) + .unwrap(); + let _program = parse_program( r#" #version 450 From 99fbb34bd6b07ca0a0cc2cf01c151d8264789965 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 24 May 2021 12:44:06 -0700 Subject: [PATCH 0886/2212] Require dynamically sized arrays to appear in 'storage' memory. WGSL requires that runtime-sized arrays appear only as the last member of a structure in in the `storage` storage class. It seems to me that Naga should enforce this restriction on its own IR as well. --- src/valid/interface.rs | 10 ++++++---- src/valid/type.rs | 8 ++++++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 39bf029ff..372d3ef0d 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -346,9 +346,11 @@ impl super::Validator { }; (access, TypeFlags::empty(), true) } - crate::StorageClass::Private | crate::StorageClass::WorkGroup => { - (crate::StorageAccess::empty(), TypeFlags::DATA, false) - } + crate::StorageClass::Private | crate::StorageClass::WorkGroup => ( + crate::StorageAccess::empty(), + TypeFlags::DATA | TypeFlags::SIZED, + false, + ), crate::StorageClass::PushConstant => { if !self.capabilities.contains(Capabilities::PUSH_CONSTANT) { return Err(GlobalVariableError::UnsupportedCapability( @@ -357,7 +359,7 @@ impl super::Validator { } ( crate::StorageAccess::LOAD, - TypeFlags::DATA | TypeFlags::HOST_SHARED, + TypeFlags::DATA | TypeFlags::HOST_SHARED | TypeFlags::SIZED, false, ) } diff --git a/src/valid/type.rs b/src/valid/type.rs index df0a401c0..8b5e108ef 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -294,8 +294,12 @@ impl super::Validator { TypeFlags::SIZED } - //Note: this will be detected at the struct level - crate::ArraySize::Dynamic => TypeFlags::empty(), + crate::ArraySize::Dynamic => { + // Non-SIZED types may only appear as the last element of a structure. + // This is enforced by checks for SIZED-ness for all compound types, + // and a special case for structs. + TypeFlags::empty() + } }; let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; From e7308e1903030a56c9bcfc4648e3b1da84e2966c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 21 May 2021 22:44:45 +0100 Subject: [PATCH 0887/2212] [glsl-in] fix validation error of entry result --- src/front/glsl/functions.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 7659d23ea..6da0028a2 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -495,7 +495,7 @@ impl Program<'_> { let ty = self.module.types.append(Type { name: None, inner: TypeInner::Struct { - top_level: true, + top_level: false, members, span, }, From 28a1ee435463c898314a0db0d42a1eacd40e95fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 21 May 2021 22:46:17 +0100 Subject: [PATCH 0888/2212] [glsl-in] Don't read builtin if it isn't available --- src/front/glsl/functions.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 6da0028a2..883856238 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -439,6 +439,7 @@ impl Program<'_> { for (binding, input, handle) in self.entry_args.iter().cloned() { match binding { Binding::Location { .. } if !input => continue, + Binding::BuiltIn(builtin) if !should_read(builtin, stage) => continue, _ => {} } @@ -524,6 +525,32 @@ impl Program<'_> { } } +// FIXME: Both of the functions below should be removed they are a temporary solution +// +// The fix should analyze the entry point and children function calls +// (recursively) and store something like `GlobalUse` and then later only read +// or store the globals that need to be read or written in that stage + +fn should_read(built_in: BuiltIn, stage: ShaderStage) -> bool { + match (built_in, stage) { + (BuiltIn::Position, ShaderStage::Fragment) + | (BuiltIn::BaseInstance, ShaderStage::Vertex) + | (BuiltIn::BaseVertex, ShaderStage::Vertex) + | (BuiltIn::ClipDistance, ShaderStage::Fragment) + | (BuiltIn::InstanceIndex, ShaderStage::Vertex) + | (BuiltIn::VertexIndex, ShaderStage::Vertex) + | (BuiltIn::FrontFacing, ShaderStage::Fragment) + | (BuiltIn::SampleIndex, ShaderStage::Fragment) + | (BuiltIn::SampleMask, ShaderStage::Fragment) + | (BuiltIn::GlobalInvocationId, ShaderStage::Compute) + | (BuiltIn::LocalInvocationId, ShaderStage::Compute) + | (BuiltIn::LocalInvocationIndex, ShaderStage::Compute) + | (BuiltIn::WorkGroupId, ShaderStage::Compute) + | (BuiltIn::WorkGroupSize, ShaderStage::Compute) => true, + _ => false, + } +} + fn should_write(built_in: BuiltIn, stage: ShaderStage) -> bool { match (built_in, stage) { (BuiltIn::Position, ShaderStage::Vertex) From 9868441ebc04ed1366c7a2994d8ee41c90caffb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 21 May 2021 22:47:08 +0100 Subject: [PATCH 0889/2212] [glsl-in] Fix storage access --- src/front/glsl/ast.rs | 15 +++++++++++---- src/front/glsl/parser.rs | 3 +-- src/front/glsl/variables.rs | 33 ++++++++++++++++++++++++--------- 3 files changed, 36 insertions(+), 15 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 1d02b504a..f43f69cfe 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -203,12 +203,15 @@ impl<'function> Context<'function> { for &(ref name, lookup) in program.global_variables.iter() { this.emit_flush(body); - let expr = match lookup { - GlobalLookup::Variable(v) => Expression::GlobalVariable(v), + let (expr, load) = match lookup { + GlobalLookup::Variable(v) => ( + Expression::GlobalVariable(v), + program.module.global_variables[v].class != StorageClass::Handle, + ), GlobalLookup::BlockSelect(handle, index) => { let base = this.expressions.append(Expression::GlobalVariable(handle)); - Expression::AccessIndex { base, index } + (Expression::AccessIndex { base, index }, true) } }; @@ -217,7 +220,11 @@ impl<'function> Context<'function> { let var = VariableReference { expr, - load: Some(this.add_expression(Expression::Load { pointer: expr }, body)), + load: if load { + Some(this.add_expression(Expression::Load { pointer: expr }, body)) + } else { + None + }, // TODO: respect constant qualifier mutable: true, }; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 543708dc3..a3552ea16 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -785,8 +785,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { binding, ty, init: None, - // TODO - storage_access: StorageAccess::all(), + storage_access: StorageAccess::empty(), }); if let Some(k) = name { diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 22201b8d2..ad4677a8b 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,6 +1,6 @@ use crate::{ - Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, LocalVariable, - ScalarKind, StorageAccess, StorageClass, Type, TypeInner, VectorSize, + Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, ImageClass, + LocalVariable, ScalarKind, StorageAccess, StorageClass, Type, TypeInner, VectorSize, }; use super::ast::*; @@ -41,7 +41,7 @@ impl Program<'_> { binding: None, ty, init: None, - storage_access: StorageAccess::all(), + storage_access: StorageAccess::empty(), }); self.entry_args @@ -304,7 +304,7 @@ impl Program<'_> { binding: None, ty, init, - storage_access: StorageAccess::all(), + storage_access: StorageAccess::empty(), }); self.entry_args.push(( @@ -331,9 +331,25 @@ impl Program<'_> { return Ok(ctx.add_expression(Expression::Constant(handle), body)); } - let class = match storage { - StorageQualifier::StorageClass(class) => class, - _ => StorageClass::Private, + let (class, storage_access) = match self.module.types[ty].inner { + TypeInner::Image { class, .. } => ( + StorageClass::Handle, + if let ImageClass::Storage(_) = class { + // TODO: Add support for qualifiers such as readonly, + // writeonly and readwrite + StorageAccess::all() + } else { + StorageAccess::empty() + }, + ), + TypeInner::Sampler { .. } => (StorageClass::Handle, StorageAccess::empty()), + _ => ( + match storage { + StorageQualifier::StorageClass(class) => class, + _ => StorageClass::Private, + }, + StorageAccess::empty(), + ), }; let handle = self.module.global_variables.append(GlobalVariable { @@ -342,8 +358,7 @@ impl Program<'_> { binding, ty, init, - // TODO - storage_access: StorageAccess::all(), + storage_access, }); self.global_variables From 01eb19e29f4d824171879fb297b08210403c27e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 21 May 2021 22:48:57 +0100 Subject: [PATCH 0890/2212] [glsl-in] Fix vector and matrix constructor Matrix and vector constructors expected a vector (in the case of the matrix) or a scalar (in both cases). Now they handle resizing such that the following code now works ```glsl mat3 a; mat4(a); // This would return a validation error because it emitted a cast ``` --- src/front/glsl/functions.rs | 91 +++++++++++++++++++++++++++++-------- 1 file changed, 73 insertions(+), 18 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 883856238..dee3991ad 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,8 +1,8 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Binding, Block, BuiltIn, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, MathFunction, - RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, StorageClass, - StructMember, Type, TypeInner, + RelationalFunction, SampleLevel, ShaderStage, Statement, StorageClass, StructMember, + SwizzleComponent, Type, TypeInner, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; @@ -37,8 +37,7 @@ impl Program<'_> { }, body, ), - TypeInner::Scalar { kind, width } - | TypeInner::Vector { kind, width, .. } => ctx.add_expression( + TypeInner::Scalar { kind, width } => ctx.add_expression( Expression::As { kind, expr: args[0].0, @@ -46,24 +45,80 @@ impl Program<'_> { }, body, ), - TypeInner::Matrix { - columns, - rows, - width, - } => { - let value = ctx.add_expression( - Expression::As { - kind: ScalarKind::Float, - expr: args[0].0, - convert: Some(width), + TypeInner::Vector { size, kind, width } => { + let expr = ctx.add_expression( + Expression::Swizzle { + size, + vector: args[0].0, + pattern: [ + SwizzleComponent::X, + SwizzleComponent::Y, + SwizzleComponent::Z, + SwizzleComponent::W, + ], }, body, ); - let column = if is_vec { - value - } else { - ctx.add_expression(Expression::Splat { size: rows, value }, body) + ctx.add_expression( + Expression::As { + kind, + expr, + convert: Some(width), + }, + body, + ) + } + TypeInner::Matrix { columns, rows, .. } => { + // TODO: casts + // `Expression::As` doesn't support matrix width + // casts so we need to do some extra work for casts + + let column = match *self.resolve_type(ctx, args[0].0, args[0].1)? { + TypeInner::Scalar { .. } => ctx.add_expression( + Expression::Splat { + size: rows, + value: args[0].0, + }, + body, + ), + TypeInner::Matrix { .. } => { + let mut components = Vec::new(); + + for n in 0..columns as u32 { + let vector = ctx.add_expression( + Expression::AccessIndex { + base: args[0].0, + index: n, + }, + body, + ); + + let c = ctx.add_expression( + Expression::Swizzle { + size: rows, + vector, + pattern: [ + SwizzleComponent::X, + SwizzleComponent::Y, + SwizzleComponent::Z, + SwizzleComponent::W, + ], + }, + body, + ); + + components.push(c) + } + + let h = ctx.add_expression( + Expression::Compose { ty, components }, + body, + ); + + return Ok(Some(h)); + } + _ => args[0].0, }; let columns = From 2b263a185160d72da881ba48b8c3f4dea8e63ad0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 22 May 2021 16:58:15 +0100 Subject: [PATCH 0891/2212] [glsl-in] Cast lod value in textureLod --- src/front/glsl/functions.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index dee3991ad..a5ffa082d 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -180,6 +180,14 @@ impl Program<'_> { if args.len() != 3 { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } + let exact = ctx.add_expression( + Expression::As { + kind: crate::ScalarKind::Float, + expr: args[2].0, + convert: Some(4), + }, + body, + ); if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { Ok(Some(ctx.add_expression( Expression::ImageSample { @@ -188,7 +196,7 @@ impl Program<'_> { coordinate: args[1].0, array_index: None, //TODO offset: None, //TODO - level: SampleLevel::Exact(args[2].0), + level: SampleLevel::Exact(exact), depth_ref: None, }, body, From 9464a81ae216a4224bbf52d45e4f119ed2cc7914 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 22 May 2021 20:26:25 +0100 Subject: [PATCH 0892/2212] [glsl-in] Fix parameter qualifiers Previously the types where changed in a later phase now they are changed right when the argument is added, this makes the implementation slightly less spec compliant because the following code will compile whilst it shouldn't ```glsl void test(float a) {} void test(out float b) {} ``` --- src/front/glsl/ast.rs | 27 ++++++++--- src/front/glsl/functions.rs | 88 +++++++++++----------------------- src/front/glsl/parser.rs | 29 +++++++++-- src/front/glsl/parser_tests.rs | 16 +++++++ 4 files changed, 90 insertions(+), 70 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index f43f69cfe..9d8d5217e 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -25,7 +25,7 @@ pub struct FunctionSignature { #[derive(Debug, Clone)] pub struct FunctionDeclaration { - pub parameters: Vec, + pub qualifiers: Vec, pub handle: Handle, /// Wheter this function was already defined or is just a prototype pub defined: bool, @@ -295,22 +295,37 @@ impl<'function> Context<'function> { /// Add function argument to current scope pub fn add_function_arg( &mut self, + program: &mut Program, + sig: &mut FunctionSignature, body: &mut Block, name: Option, ty: Handle, - parameter: ParameterQualifier, + qualifier: ParameterQualifier, ) { let index = self.arguments.len(); - self.arguments.push(FunctionArgument { + let mut arg = FunctionArgument { name: name.clone(), ty, binding: None, - }); + }; + sig.parameters.push(ty); + + if qualifier.is_lhs() { + arg.ty = program.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Pointer { + base: arg.ty, + class: StorageClass::Function, + }, + }) + } + + self.arguments.push(arg); if let Some(name) = name { let expr = self.add_expression(Expression::FunctionArgument(index as u32), body); - let mutable = parameter != ParameterQualifier::Const; - let load = if parameter.is_lhs() { + let mutable = qualifier != ParameterQualifier::Const; + let load = if qualifier.is_lhs() { Some(self.add_expression(Expression::Load { pointer: expr }, body)) } else { None diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index a5ffa082d..8bb5d04a7 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,8 +1,8 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Binding, Block, BuiltIn, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, MathFunction, - RelationalFunction, SampleLevel, ShaderStage, Statement, StorageClass, StructMember, - SwizzleComponent, Type, TypeInner, + RelationalFunction, SampleLevel, ShaderStage, Statement, StructMember, SwizzleComponent, Type, + TypeInner, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; @@ -337,7 +337,7 @@ impl Program<'_> { .clone(); let mut arguments = Vec::with_capacity(raw_args.len()); - for (qualifier, expr) in fun.parameters.iter().zip(raw_args.iter()) { + for (qualifier, expr) in fun.qualifiers.iter().zip(raw_args.iter()) { let handle = ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?.0; arguments.push(handle) } @@ -390,37 +390,17 @@ impl Program<'_> { pub fn add_function( &mut self, mut function: Function, - parameters: Vec, + sig: FunctionSignature, + qualifiers: Vec, meta: SourceMetadata, ) -> Result<(), ErrorKind> { ensure_block_returns(&mut function.body); - let name = function - .name - .clone() - .ok_or_else(|| ErrorKind::SemanticError(meta, "Unnamed function".into()))?; - let stage = self.entry_points.get(&name); + let stage = self.entry_points.get(&sig.name); if let Some(&stage) = stage { let handle = self.module.functions.append(function); - self.entries.push((name, stage, handle)); + self.entries.push((sig.name, stage, handle)); } else { - let sig = FunctionSignature { - name, - parameters: function.arguments.iter().map(|p| p.ty).collect(), - }; - - for (arg, qualifier) in function.arguments.iter_mut().zip(parameters.iter()) { - if qualifier.is_lhs() { - arg.ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Pointer { - base: arg.ty, - class: StorageClass::Function, - }, - }) - } - } - let void = function.result.is_none(); if let Some(decl) = self.lookup_function.get_mut(&sig) { @@ -438,7 +418,7 @@ impl Program<'_> { self.lookup_function.insert( sig, FunctionDeclaration { - parameters, + qualifiers, handle, defined: true, void, @@ -452,43 +432,33 @@ impl Program<'_> { pub fn add_prototype( &mut self, - mut function: Function, - parameters: Vec, + function: Function, + sig: FunctionSignature, + qualifiers: Vec, meta: SourceMetadata, ) -> Result<(), ErrorKind> { - let name = function - .name - .clone() - .ok_or_else(|| ErrorKind::SemanticError(meta, "Unnamed function".into()))?; - let sig = FunctionSignature { - name, - parameters: function.arguments.iter().map(|p| p.ty).collect(), - }; let void = function.result.is_none(); - for (arg, qualifier) in function.arguments.iter_mut().zip(parameters.iter()) { - if qualifier.is_lhs() { - arg.ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Pointer { - base: arg.ty, - class: StorageClass::Function, - }, - }) - } - } - let handle = self.module.functions.append(function); - self.lookup_function.insert( - sig, - FunctionDeclaration { - parameters, - handle, - defined: false, - void, - }, - ); + if self + .lookup_function + .insert( + sig, + FunctionDeclaration { + qualifiers, + handle, + defined: false, + void, + }, + ) + .is_some() + { + return Err(ErrorKind::SemanticError( + meta, + "Prototype already defined".into(), + )); + } Ok(()) } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index a3552ea16..cd7370631 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,7 +1,7 @@ use super::{ ast::{ - Context, FunctionCall, FunctionCallKind, GlobalLookup, HirExpr, HirExprKind, - ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier, + Context, FunctionCall, FunctionCallKind, FunctionSignature, GlobalLookup, HirExpr, + HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier, }, error::ErrorKind, lex::Lexer, @@ -574,6 +574,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut arguments = Vec::new(); let mut parameters = Vec::new(); let mut body = Block::new(); + let mut sig = FunctionSignature { + name: name.clone(), + parameters: Vec::new(), + }; let mut context = Context::new( self.program, @@ -583,7 +587,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { &mut arguments, ); - self.parse_function_args(&mut context, &mut body, &mut parameters)?; + self.parse_function_args( + &mut context, + &mut body, + &mut parameters, + &mut sig, + )?; let end_meta = self.expect(TokenValue::RightParen)?.meta; meta = meta.union(&end_meta); @@ -599,6 +608,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { arguments, ..Default::default() }, + sig, parameters, meta, )?; @@ -622,6 +632,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { arguments, body, }, + sig, parameters, meta, )?; @@ -1555,6 +1566,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { context: &mut Context, body: &mut Block, parameters: &mut Vec, + sig: &mut FunctionSignature, ) -> Result<()> { loop { if self.peek_type_name() || self.peek_parameter_qualifier() { @@ -1565,7 +1577,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match self.expect_peek()?.value { TokenValue::Comma => { self.bump()?; - context.add_function_arg(body, None, ty, qualifier); + context.add_function_arg(&mut self.program, sig, body, None, ty, qualifier); continue; } TokenValue::Identifier(_) => { @@ -1574,7 +1586,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let size = self.parse_array_specifier()?; let ty = self.maybe_array(ty, size); - context.add_function_arg(body, Some(name), ty, qualifier); + context.add_function_arg( + &mut self.program, + sig, + body, + Some(name), + ty, + qualifier, + ); if self.bump_if(TokenValue::Comma).is_some() { continue; diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 91c0e22fc..fda018388 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -397,6 +397,22 @@ fn functions() { &entry_points, ) .unwrap(); + + parse_program( + r#" + # version 450 + void fun(vec2 in_parameter, out float out_parameter) { + ivec2 _ = ivec2(in_parameter); + } + + void main() { + float a; + fun(vec2(1.0), a); + } + "#, + &entry_points, + ) + .unwrap(); } #[test] From f57739d30bf5b1075ba4ab8ed44dfd3dc51259d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 22 May 2021 20:36:17 +0100 Subject: [PATCH 0893/2212] [glsl-in] Provide default interpolation --- src/front/glsl/variables.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index ad4677a8b..8a3bbee5d 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,6 +1,7 @@ use crate::{ Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, ImageClass, - LocalVariable, ScalarKind, StorageAccess, StorageClass, Type, TypeInner, VectorSize, + Interpolation, LocalVariable, ScalarKind, StorageAccess, StorageClass, Type, TypeInner, + VectorSize, }; use super::ast::*; @@ -297,6 +298,13 @@ impl Program<'_> { if let Some(location) = location { let input = StorageQualifier::Input == storage; + let interpolation = self.module.types[ty].inner.scalar_kind().map(|kind| { + if let ScalarKind::Float = kind { + Interpolation::Perspective + } else { + Interpolation::Flat + } + }); let handle = self.module.global_variables.append(GlobalVariable { name: Some(name.clone()), From badf99653a32639826ac322840bdcc99c503da15 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 26 May 2021 00:02:00 -0400 Subject: [PATCH 0894/2212] [spv-in] refactor the matrix stride check --- src/front/spv/error.rs | 2 -- src/front/spv/mod.rs | 17 ++++++++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 1ae8b2313..688127a27 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -108,6 +108,4 @@ pub enum Error { #[error("invalid barrier memory semantics %{0}")] InvalidBarrierMemorySemantics(spirv::Word), // incomplete implementation errors - #[error("unsupported matrix stride {0}")] - UnsupportedMatrixStride(spirv::Word), } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 86998bbc2..78100c067 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2965,14 +2965,25 @@ impl> Parser { let offset = decor.offset.unwrap_or(0); if let crate::TypeInner::Matrix { - columns: _, + columns, rows, width, } = module.types[ty].inner { if let Some(stride) = decor.matrix_stride { - if stride.get() != (rows as u32) * (width as u32) { - return Err(Error::UnsupportedMatrixStride(stride.get())); + let rounded_rows = if rows > crate::VectorSize::Bi { + 4 + } else { + rows as u32 + }; + if stride.get() != rounded_rows * (width as u32) { + log::warn!( + "Unexpected matrix stride {} for an {}x{} matrix with scalar width={}", + stride.get(), + columns as u8, + rows as u8, + width, + ); } } } From 398d3545b324a32a484e094ac1f4da6886e0f86f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 25 May 2021 13:03:27 -0700 Subject: [PATCH 0895/2212] Include the type arena in `ResolveContext`, since it's always needed. --- src/front/glsl/ast.rs | 22 +++++++------- src/front/mod.rs | 3 +- src/front/wgsl/mod.rs | 6 ++-- src/proc/typifier.rs | 67 ++++++++++++++++++++++--------------------- src/valid/analyzer.rs | 18 ++++-------- 5 files changed, 53 insertions(+), 63 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 9d8d5217e..6c86e9d64 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -78,17 +78,16 @@ impl<'a> Program<'a> { ) -> Result<&'b TypeInner, ErrorKind> { let resolve_ctx = ResolveContext { constants: &self.module.constants, + types: &self.module.types, global_vars: &self.module.global_variables, local_vars: &context.locals, functions: &self.module.functions, arguments: &context.arguments, }; - match context.typifier.grow( - handle, - &context.expressions, - &mut self.module.types, - &resolve_ctx, - ) { + match context + .typifier + .grow(handle, &context.expressions, &resolve_ctx) + { //TODO: better error report Err(error) => Err(ErrorKind::SemanticError( meta, @@ -106,17 +105,16 @@ impl<'a> Program<'a> { ) -> Result, ErrorKind> { let resolve_ctx = ResolveContext { constants: &self.module.constants, + types: &self.module.types, global_vars: &self.module.global_variables, local_vars: &context.locals, functions: &self.module.functions, arguments: &context.arguments, }; - match context.typifier.grow( - handle, - &context.expressions, - &mut self.module.types, - &resolve_ctx, - ) { + match context + .typifier + .grow(handle, &context.expressions, &resolve_ctx) + { //TODO: better error report Err(error) => Err(ErrorKind::SemanticError( meta, diff --git a/src/front/mod.rs b/src/front/mod.rs index 0509258ce..45c93143e 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -97,12 +97,11 @@ impl Typifier { &mut self, expr_handle: Handle, expressions: &Arena, - types: &mut Arena, ctx: &ResolveContext, ) -> Result<(), ResolveError> { if self.resolutions.len() <= expr_handle.index() { for (eh, expr) in expressions.iter().skip(self.resolutions.len()) { - let resolution = ctx.resolve(expr, types, |h| &self.resolutions[h.index()])?; + let resolution = ctx.resolve(expr, |h| &self.resolutions[h.index()])?; log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); self.resolutions.push(resolution); } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 66feb04b5..d9bb9ba2d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -294,15 +294,13 @@ impl<'a> ExpressionContext<'a, '_, '_> { ) -> Result<&crate::TypeInner, Error<'a>> { let resolve_ctx = ResolveContext { constants: self.constants, + types: self.types, global_vars: self.global_vars, local_vars: self.local_vars, functions: self.functions, arguments: self.arguments, }; - match self - .typifier - .grow(handle, self.expressions, self.types, &resolve_ctx) - { + match self.typifier.grow(handle, self.expressions, &resolve_ctx) { Err(e) => Err(Error::InvalidResolve(e)), Ok(()) => Ok(self.typifier.get(handle, self.types)), } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index f39e65f1b..a07e3d43a 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -111,6 +111,7 @@ pub enum ResolveError { pub struct ResolveContext<'a> { pub constants: &'a Arena, + pub types: &'a Arena, pub global_vars: &'a Arena, pub local_vars: &'a Arena, pub functions: &'a Arena, @@ -121,10 +122,10 @@ impl<'a> ResolveContext<'a> { pub fn resolve( &self, expr: &crate::Expression, - types: &'a Arena, past: impl Fn(Handle) -> &'a TypeResolution, ) -> Result { use crate::TypeInner as Ti; + let types = self.types; Ok(match *expr { crate::Expression::Access { base, .. } => match *past(base).inner_with(types) { Ti::Array { base, .. } => TypeResolution::Handle(base), @@ -144,37 +145,39 @@ impl<'a> ResolveContext<'a> { width, class, }), - Ti::Pointer { base, class } => TypeResolution::Value(match types[base].inner { - Ti::Array { base, .. } => Ti::Pointer { base, class }, - Ti::Vector { - size: _, - kind, - width, - } => Ti::ValuePointer { - size: None, - kind, - width, - class, - }, - // Matrices are only dynamically indexed behind a pointer - Ti::Matrix { - columns: _, - rows, - width, - } => Ti::ValuePointer { - kind: crate::ScalarKind::Float, - size: Some(rows), - width, - class, - }, - ref other => { - log::error!("Access sub-type {:?}", other); - return Err(ResolveError::InvalidSubAccess { - ty: base, - indexed: false, - }); - } - }), + Ti::Pointer { base, class } => { + TypeResolution::Value(match types[base].inner { + Ti::Array { base, .. } => Ti::Pointer { base, class }, + Ti::Vector { + size: _, + kind, + width, + } => Ti::ValuePointer { + size: None, + kind, + width, + class, + }, + // Matrices are only dynamically indexed behind a pointer + Ti::Matrix { + columns: _, + rows, + width, + } => Ti::ValuePointer { + kind: crate::ScalarKind::Float, + size: Some(rows), + width, + class, + }, + ref other => { + log::error!("Access sub-type {:?}", other); + return Err(ResolveError::InvalidSubAccess { + ty: base, + indexed: false, + }); + } + }) + } ref other => { log::error!("Access type {:?}", other); return Err(ResolveError::InvalidAccess { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 494aabf9e..ecae2232a 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -299,7 +299,6 @@ impl FunctionInfo { expression: &crate::Expression, expression_arena: &Arena, other_functions: &[FunctionInfo], - type_arena: &Arena, resolve_context: &ResolveContext, ) -> Result<(), ExpressionError> { use crate::{Expression as E, SampleLevel as Sl}; @@ -513,8 +512,7 @@ impl FunctionInfo { }, }; - let ty = - resolve_context.resolve(expression, type_arena, |h| &self.expressions[h.index()].ty)?; + let ty = resolve_context.resolve(expression, |h| &self.expressions[h.index()].ty)?; self.expressions[handle.index()] = ExpressionInfo { uniformity, ref_count: 0, @@ -706,6 +704,7 @@ impl ModuleInfo { }; let resolve_context = ResolveContext { constants: &module.constants, + types: &module.types, global_vars: &module.global_variables, local_vars: &fun.local_variables, functions: &module.functions, @@ -718,7 +717,6 @@ impl ModuleInfo { expr, &fun.expressions, &self.functions, - &module.types, &resolve_context, ) { return Err(FunctionError::Expression { handle, error }); @@ -810,21 +808,15 @@ fn uniform_control_flow() { }; let resolve_context = ResolveContext { constants: &constant_arena, + types: &type_arena, global_vars: &global_var_arena, local_vars: &Arena::new(), functions: &Arena::new(), arguments: &[], }; for (handle, expression) in expressions.iter() { - info.process_expression( - handle, - expression, - &expressions, - &[], - &type_arena, - &resolve_context, - ) - .unwrap(); + info.process_expression(handle, expression, &expressions, &[], &resolve_context) + .unwrap(); } assert_eq!(info[non_uniform_global_expr].ref_count, 1); assert_eq!(info[uniform_global_expr].ref_count, 1); From 48363fcef1cb171792d6f69270b9daee42396731 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 26 May 2021 09:11:18 -0700 Subject: [PATCH 0896/2212] Don't accept unsized types as function arguments. --- src/valid/function.rs | 2 +- tests/wgsl-errors.rs | 46 +++++++++++++++++++++++++++++++++++-------- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index f49bb70a1..60b431052 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -558,7 +558,7 @@ impl super::Validator { for (index, argument) in fun.arguments.iter().enumerate() { if !self.types[argument.ty.index()] .flags - .contains(TypeFlags::DATA) + .contains(TypeFlags::DATA | TypeFlags::SIZED) { return Err(FunctionError::InvalidArgumentType { index, diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index dd0221b65..6c03ca7be 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -94,21 +94,35 @@ fn unknown_identifier() { } macro_rules! check_validation_error { + // We want to support an optional guard expression after the pattern, so + // that we can check values we can't match against, like strings. + // Unfortunately, we can't simply include `$( if $guard:expr )?` in the + // pattern, because Rust treats `?` as a repetition operator, and its count + // (0 or 1) will not necessarily match `$source`. ( $( $source:literal ),* : $pattern:pat ) => { + check_validation_error!( @full $( $source ),* : $pattern if true ; ""); + }; + + ( $( $source:literal ),* : $pattern:pat if $guard:expr ) => { + check_validation_error!( @full $( $source ),* : $pattern if $guard ; stringify!( $guard ) ); + }; + + ( @full $( $source:literal ),* : $pattern:pat if $guard:expr ; $guard_string:expr ) => { $( let error = validation_error($source); - if ! matches!(error, $pattern) { + if ! matches!(&error, $pattern if $guard) { eprintln!("validation error does not match pattern:\n\ - {:#?}\n\ - \n\ - expected match for pattern:\n\ - {}", - error, - stringify!($pattern)); + {:#?}\n\ + \n\ + expected match for pattern:\n\ + {}{}", + error, + stringify!($pattern), + $guard_string); panic!("validation error does not match pattern"); } )* - } + }; } fn validation_error(source: &str) -> Result { @@ -194,6 +208,22 @@ fn invalid_structs() { } } +#[test] +fn invalid_functions() { + check_validation_error! { + "fn bogus(data: array) -> f32 { return data[0]; }": + Err(naga::valid::ValidationError::Function { + name: function_name, + error: naga::valid::FunctionError::InvalidArgumentType { + index: 0, + name: argument_name, + }, + .. + }) + if function_name == "bogus" && argument_name == "data" + } +} + #[test] fn missing_bindings() { check_validation_error! { From 14908e512619514acd3414daf0cdf14306254e2a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 27 May 2021 20:23:51 -0700 Subject: [PATCH 0897/2212] [spv-out]: Don't pass in the type arena where it's not needed. --- src/back/spv/writer.rs | 335 +++++++++++++++-------------------------- 1 file changed, 122 insertions(+), 213 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d50c28e52..f3918347a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -364,33 +364,25 @@ impl Writer { Err(Error::MissingCapabilities(capabilities.to_vec())) } - fn get_type_id( - &mut self, - arena: &Arena, - lookup_ty: LookupType, - ) -> Result { + fn get_type_id(&mut self, lookup_ty: LookupType) -> Result { if let Entry::Occupied(e) = self.lookup_type.entry(lookup_ty) { Ok(*e.get()) } else { match lookup_ty { LookupType::Handle(_handle) => unreachable!("Handles are populated at start"), - LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty), + LookupType::Local(local_ty) => self.write_type_declaration_local(local_ty), } } } - fn get_expression_type_id( - &mut self, - arena: &Arena, - tr: &TypeResolution, - ) -> Result { + fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Result { let lookup_ty = match *tr { TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), TypeResolution::Value(ref inner) => { LookupType::Local(self.physical_layout.make_local(inner).unwrap()) } }; - self.get_type_id(arena, lookup_ty) + self.get_type_id(lookup_ty) } fn get_pointer_id( @@ -399,7 +391,7 @@ impl Writer { handle: Handle, class: spirv::StorageClass, ) -> Result { - let ty_id = self.get_type_id(arena, LookupType::Handle(handle))?; + let ty_id = self.get_type_id(LookupType::Handle(handle))?; if let crate::TypeInner::Pointer { .. } = arena[handle].inner { return Ok(ty_id); } @@ -467,8 +459,7 @@ impl Writer { let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); for argument in ir_function.arguments.iter() { let class = spirv::StorageClass::Input; - let argument_type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(argument.ty))?; + let argument_type_id = self.get_type_id(LookupType::Handle(argument.ty))?; if let Some(ref mut list) = varying_ids { let id = if let Some(ref binding) = argument.binding { let name = argument.name.as_ref().map(AsRef::as_ref); @@ -486,8 +477,7 @@ impl Writer { let struct_id = self.id_gen.next(); let mut constituent_ids = Vec::with_capacity(members.len()); for member in members { - let type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(member.ty))?; + let type_id = self.get_type_id(LookupType::Handle(member.ty))?; let name = member.name.as_ref().map(AsRef::as_ref); let binding = member.binding.as_ref().unwrap(); let varying_id = @@ -522,8 +512,7 @@ impl Writer { if let Some(ref mut list) = varying_ids { let class = spirv::StorageClass::Output; if let Some(ref binding) = result.binding { - let type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(result.ty))?; + let type_id = self.get_type_id(LookupType::Handle(result.ty))?; let varying_id = self.write_varying(ir_module, class, None, result.ty, binding)?; list.push(varying_id); @@ -536,8 +525,7 @@ impl Writer { ir_module.types[result.ty].inner { for member in members { - let type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(member.ty))?; + let type_id = self.get_type_id(LookupType::Handle(member.ty))?; let name = member.name.as_ref().map(AsRef::as_ref); let binding = member.binding.as_ref().unwrap(); let varying_id = @@ -554,7 +542,7 @@ impl Writer { } self.void_type } else { - self.get_type_id(&ir_module.types, LookupType::Handle(result.ty))? + self.get_type_id(LookupType::Handle(result.ty))? } } None => self.void_type, @@ -594,7 +582,7 @@ impl Writer { continue; } let id = self.id_gen.next(); - let result_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(var.ty))?; + let result_type_id = self.get_type_id(LookupType::Handle(var.ty))?; let gv = &mut self.global_variables[handle.index()]; prelude .body @@ -739,11 +727,7 @@ impl Writer { } } - fn write_type_declaration_local( - &mut self, - arena: &Arena, - local_ty: LocalType, - ) -> Result { + fn write_type_declaration_local(&mut self, local_ty: LocalType) -> Result { let id = self.id_gen.next(); let instruction = match local_ty { LocalType::Value { @@ -758,15 +742,12 @@ impl Writer { width, pointer_class: None, } => { - let scalar_id = self.get_type_id( - arena, - LookupType::Local(LocalType::Value { - vector_size: None, - kind, - width, - pointer_class: None, - }), - )?; + let scalar_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind, + width, + pointer_class: None, + }))?; Instruction::type_vector(id, scalar_id, size) } LocalType::Matrix { @@ -774,19 +755,16 @@ impl Writer { rows, width, } => { - let vector_id = self.get_type_id( - arena, - LookupType::Local(LocalType::Value { - vector_size: Some(rows), - kind: crate::ScalarKind::Float, - width, - pointer_class: None, - }), - )?; + let vector_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(rows), + kind: crate::ScalarKind::Float, + width, + pointer_class: None, + }))?; Instruction::type_matrix(id, vector_id, columns) } LocalType::Pointer { base, class } => { - let type_id = self.get_type_id(arena, LookupType::Handle(base))?; + let type_id = self.get_type_id(LookupType::Handle(base))?; Instruction::type_pointer(id, class, type_id) } LocalType::Value { @@ -795,15 +773,12 @@ impl Writer { width, pointer_class: Some(class), } => { - let type_id = self.get_type_id( - arena, - LookupType::Local(LocalType::Value { - vector_size, - kind, - width, - pointer_class: None, - }), - )?; + let type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size, + kind, + width, + pointer_class: None, + }))?; Instruction::type_pointer(id, class, type_id) } // all the samplers and image types go through `write_type_declaration_arena` @@ -856,15 +831,12 @@ impl Writer { let instruction = match ty.inner { crate::TypeInner::Scalar { kind, width } => self.make_scalar(id, kind, width), crate::TypeInner::Vector { size, kind, width } => { - let scalar_id = self.get_type_id( - arena, - LookupType::Local(LocalType::Value { - vector_size: None, - kind, - width, - pointer_class: None, - }), - )?; + let scalar_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind, + width, + pointer_class: None, + }))?; Instruction::type_vector(id, scalar_id, size) } crate::TypeInner::Matrix { @@ -872,15 +844,12 @@ impl Writer { rows, width, } => { - let vector_id = self.get_type_id( - arena, - LookupType::Local(LocalType::Value { - vector_size: Some(rows), - kind: crate::ScalarKind::Float, - width, - pointer_class: None, - }), - )?; + let vector_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(rows), + kind: crate::ScalarKind::Float, + width, + pointer_class: None, + }))?; Instruction::type_matrix(id, vector_id, columns) } crate::TypeInner::Image { @@ -909,7 +878,7 @@ impl Writer { }; let dim = map_dim(dim); self.check(dim.required_capabilities())?; - let type_id = self.get_type_id(arena, LookupType::Local(local_type))?; + let type_id = self.get_type_id(LookupType::Local(local_type))?; Instruction::type_image(id, type_id, dim, arrayed, class) } crate::TypeInner::Sampler { comparison: _ } => Instruction::type_sampler(id), @@ -918,7 +887,7 @@ impl Writer { self.decorate(id, Decoration::ArrayStride, &[stride]); } - let type_id = self.get_type_id(arena, LookupType::Handle(base))?; + let type_id = self.get_type_id(LookupType::Handle(base))?; match size { crate::ArraySize::Constant(const_handle) => { let length_id = self.constant_ids[const_handle.index()]; @@ -984,13 +953,13 @@ impl Writer { )); } - let member_id = self.get_type_id(arena, LookupType::Handle(member.ty))?; + let member_id = self.get_type_id(LookupType::Handle(member.ty))?; member_ids.push(member_id); } Instruction::type_struct(id, member_ids.as_slice()) } crate::TypeInner::Pointer { base, class } => { - let type_id = self.get_type_id(arena, LookupType::Handle(base))?; + let type_id = self.get_type_id(LookupType::Handle(base))?; let raw_class = map_storage_class(class); Instruction::type_pointer(id, raw_class, type_id) } @@ -1001,15 +970,12 @@ impl Writer { class, } => { let raw_class = map_storage_class(class); - let type_id = self.get_type_id( - arena, - LookupType::Local(LocalType::Value { - vector_size: size, - kind, - width, - pointer_class: None, - }), - )?; + let type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: size, + kind, + width, + pointer_class: None, + }))?; Instruction::type_pointer(id, raw_class, type_id) } }; @@ -1018,25 +984,20 @@ impl Writer { Ok(id) } - fn get_index_constant( - &mut self, - index: Word, - types: &Arena, - ) -> Result { - self.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4, types) + fn get_index_constant(&mut self, index: Word) -> Result { + self.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) } fn get_constant_scalar( &mut self, value: crate::ScalarValue, width: crate::Bytes, - types: &Arena, ) -> Result { if let Some(&id) = self.cached_constants.get(&(value, width)) { return Ok(id); } let id = self.id_gen.next(); - self.write_constant_scalar(id, &value, width, None, types)?; + self.write_constant_scalar(id, &value, width, None)?; self.cached_constants.insert((value, width), id); Ok(id) } @@ -1047,22 +1008,18 @@ impl Writer { value: &crate::ScalarValue, width: crate::Bytes, debug_name: Option<&String>, - types: &Arena, ) -> Result<(), Error> { if self.flags.contains(WriterFlags::DEBUG) { if let Some(name) = debug_name { self.debugs.push(Instruction::name(id, name)); } } - let type_id = self.get_type_id( - types, - LookupType::Local(LocalType::Value { - vector_size: None, - kind: value.scalar_kind(), - width, - pointer_class: None, - }), - )?; + let type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: value.scalar_kind(), + width, + pointer_class: None, + }))?; let (solo, pair); let instruction = match *value { crate::ScalarValue::Sint(val) => { @@ -1121,7 +1078,6 @@ impl Writer { id: Word, ty: Handle, components: &[Handle], - types: &Arena, ) -> Result<(), Error> { let mut constituent_ids = Vec::with_capacity(components.len()); for constituent in components.iter() { @@ -1129,7 +1085,7 @@ impl Writer { constituent_ids.push(constituent_id); } - let type_id = self.get_type_id(types, LookupType::Handle(ty))?; + let type_id = self.get_type_id(LookupType::Handle(ty))?; Instruction::constant_composite(type_id, id, constituent_ids.as_slice()) .to_words(&mut self.logical_layout.declarations); Ok(()) @@ -1297,15 +1253,13 @@ impl Writer { let coordinate_id = self.cached[coordinates]; Ok(if let Some(array_index) = array_index { - let coordinate_scalar_type_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Value { + let coordinate_scalar_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { vector_size: None, kind: crate::ScalarKind::Float, width: 4, pointer_class: None, - }), - )?; + }))?; let mut constituent_ids = [0u32; 4]; let size = match *fun_info[coordinates].ty.inner_with(&ir_module.types) { @@ -1350,15 +1304,13 @@ impl Writer { ); block.body.push(cast_instruction); - let extended_coordinate_type_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Value { + let extended_coordinate_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { vector_size: Some(size), kind: crate::ScalarKind::Float, width: 4, pointer_class: None, - }), - )?; + }))?; let id = self.id_gen.next(); block.body.push(Instruction::composite_construct( @@ -1383,7 +1335,7 @@ impl Writer { element_ty: Handle, block: &mut Block, ) -> Result<(Word, LocalVariable), Error> { - let container_type_id = self.get_expression_type_id(ir_types, container_resolution)?; + let container_type_id = self.get_expression_type_id(container_resolution)?; let pointer_type_id = self.id_gen.next(); Instruction::type_pointer( pointer_type_id, @@ -1459,8 +1411,7 @@ impl Writer { block: &mut Block, function: &mut Function, ) -> Result<(), Error> { - let result_type_id = - self.get_expression_type_id(&ir_module.types, &fun_info[expr_handle].ty)?; + let result_type_id = self.get_expression_type_id(&fun_info[expr_handle].ty)?; let id = match ir_function.expressions[expr_handle] { crate::Expression::Access { base, index: _ } @@ -1887,14 +1838,8 @@ impl Writer { } crate::Expression::LocalVariable(variable) => function.variables[&variable].id, crate::Expression::Load { pointer } => { - let (pointer_id, _) = self.write_expression_pointer( - ir_module, - ir_function, - fun_info, - pointer, - block, - function, - )?; + let (pointer_id, _) = + self.write_expression_pointer(ir_function, fun_info, pointer, block, function)?; let id = self.id_gen.next(); block @@ -1966,15 +1911,13 @@ impl Writer { } => { // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, // so we need to grab the first component out of it. - let load_result_type_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Value { + let load_result_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { vector_size: Some(crate::VectorSize::Quad), kind: crate::ScalarKind::Float, width: 4, pointer_class: None, - }), - )?; + }))?; Instruction::image_fetch(load_result_type_id, id, image_id, coordinate_id) } _ => Instruction::image_fetch(result_type_id, id, image_id, coordinate_id), @@ -2031,26 +1974,20 @@ impl Writer { _ => false, }; let sample_result_type_id = if needs_sub_access { - self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Value { - vector_size: Some(crate::VectorSize::Quad), - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }), - )? + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Quad), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))? } else { result_type_id }; // OpTypeSampledImage - let image_type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(image_type))?; - let sampled_image_type_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::SampledImage { image_type_id }), - )?; + let image_type_id = self.get_type_id(LookupType::Handle(image_type))?; + let sampled_image_type_id = + self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id }))?; let sampler_id = self.get_expression_global(ir_function, sampler); let coordinate_id = self.write_texture_coordinates( @@ -2085,11 +2022,8 @@ impl Writer { depth_id, ); - let zero_id = self.get_constant_scalar( - crate::ScalarValue::Float(0.0), - 4, - &ir_module.types, - )?; + let zero_id = + self.get_constant_scalar(crate::ScalarValue::Float(0.0), 4)?; mask |= spirv::ImageOperands::LOD; inst.add_operand(mask.bits()); @@ -2241,15 +2175,12 @@ impl Writer { 4 => Some(crate::VectorSize::Quad), _ => None, }; - self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Value { - vector_size, - kind: crate::ScalarKind::Sint, - width: 4, - pointer_class: None, - }), - )? + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + }))? }; let (query_op, level_id) = match class { @@ -2257,7 +2188,7 @@ impl Writer { _ => { let level_id = match level { Some(expr) => self.cached[expr], - None => self.get_index_constant(0, &ir_module.types)?, + None => self.get_index_constant(0)?, }; (spirv::Op::ImageQuerySizeLod, Some(level_id)) } @@ -2312,15 +2243,13 @@ impl Writer { Id::D2 | Id::Cube => crate::VectorSize::Tri, Id::D3 => crate::VectorSize::Quad, }; - let extended_size_type_id = self.get_type_id( - &ir_module.types, - LookupType::Local(LocalType::Value { + let extended_size_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { vector_size: Some(vec_size), kind: crate::ScalarKind::Sint, width: 4, pointer_class: None, - }), - )?; + }))?; let id_extended = self.id_gen.next(); let mut inst = Instruction::image_query( spirv::Op::ImageQuerySizeLod, @@ -2328,7 +2257,7 @@ impl Writer { id_extended, image_id, ); - inst.add_operand(self.get_index_constant(0, &ir_module.types)?); + inst.add_operand(self.get_index_constant(0)?); block.body.push(inst); let id = self.id_gen.next(); block.body.push(Instruction::composite_extract( @@ -2409,9 +2338,8 @@ impl Writer { } /// Write a left-hand-side expression, returning an `id` of the pointer. - fn write_expression_pointer<'a>( + fn write_expression_pointer( &mut self, - ir_module: &'a crate::Module, ir_function: &crate::Function, fun_info: &FunctionInfo, mut expr_handle: Handle, @@ -2424,7 +2352,7 @@ impl Writer { LookupType::Local(self.physical_layout.make_local(inner).unwrap()) } }; - let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?; + let result_type_id = self.get_type_id(result_lookup_ty)?; self.temp_list.clear(); let (root_id, class) = loop { @@ -2435,7 +2363,7 @@ impl Writer { base } crate::Expression::AccessIndex { base, index } => { - let const_id = self.get_index_constant(index, &ir_module.types)?; + let const_id = self.get_index_constant(index)?; self.temp_list.push(const_id); base } @@ -2492,7 +2420,6 @@ impl Writer { &mut self, value_id: Word, ir_result: &crate::FunctionResult, - type_arena: &Arena, result_members: &[ResultMember], body: &mut Vec, ) -> Result<(), Error> { @@ -2519,16 +2446,13 @@ impl Writer { && res_member.built_in == Some(crate::BuiltIn::Position) { let access_id = self.id_gen.next(); - let float_ptr_type_id = self.get_type_id( - type_arena, - LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: Some(spirv::StorageClass::Output), - }), - )?; - let index_y_id = self.get_index_constant(1, type_arena)?; + let float_ptr_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: Some(spirv::StorageClass::Output), + }))?; + let index_y_id = self.get_index_constant(1)?; body.push(Instruction::access_chain( float_ptr_type_id, access_id, @@ -2537,15 +2461,12 @@ impl Writer { )); let load_id = self.id_gen.next(); - let float_type_id = self.get_type_id( - type_arena, - LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }), - )?; + let float_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))?; body.push(Instruction::load(float_type_id, load_id, access_id, None)); let neg_id = self.id_gen.next(); @@ -2799,7 +2720,6 @@ impl Writer { self.write_entry_point_return( value_id, ir_function.result.as_ref().unwrap(), - &ir_module.types, &context.results, &mut block.body, )?; @@ -2830,12 +2750,9 @@ impl Writer { spirv::MemorySemantics::WORKGROUP_MEMORY, flags.contains(crate::Barrier::WORK_GROUP), ); - let exec_scope_id = - self.get_index_constant(spirv::Scope::Workgroup as u32, &ir_module.types)?; - let mem_scope_id = - self.get_index_constant(memory_scope as u32, &ir_module.types)?; - let semantics_id = - self.get_index_constant(semantics.bits(), &ir_module.types)?; + let exec_scope_id = self.get_index_constant(spirv::Scope::Workgroup as u32)?; + let mem_scope_id = self.get_index_constant(memory_scope as u32)?; + let semantics_id = self.get_index_constant(semantics.bits())?; block.body.push(Instruction::control_barrier( exec_scope_id, mem_scope_id, @@ -2844,7 +2761,6 @@ impl Writer { } crate::Statement::Store { pointer, value } => { let (pointer_id, _) = self.write_expression_pointer( - ir_module, ir_function, fun_info, pointer, @@ -2897,7 +2813,7 @@ impl Writer { .as_ref() .unwrap() .ty; - self.get_type_id(&ir_module.types, LookupType::Handle(ty_handle))? + self.get_type_id(LookupType::Handle(ty_handle))? } None => self.void_type, }; @@ -2922,8 +2838,7 @@ impl Writer { Some(ref result) if function.entry_point_context.is_none() => { // create a Null and return it let null_id = self.id_gen.next(); - let type_id = - self.get_type_id(&ir_module.types, LookupType::Handle(result.ty))?; + let type_id = self.get_type_id(LookupType::Handle(result.ty))?; Instruction::constant_null(type_id, null_id) .to_words(&mut self.logical_layout.declarations); Instruction::return_value(null_id) @@ -2974,16 +2889,10 @@ impl Writer { self.constant_ids[handle.index()] = match constant.name { Some(ref name) => { let id = self.id_gen.next(); - self.write_constant_scalar( - id, - value, - width, - Some(name), - &ir_module.types, - )?; + self.write_constant_scalar(id, value, width, Some(name))?; id } - None => self.get_constant_scalar(*value, width, &ir_module.types)?, + None => self.get_constant_scalar(*value, width)?, }; } } @@ -3006,7 +2915,7 @@ impl Writer { self.debugs.push(Instruction::name(id, name)); } } - self.write_constant_composite(id, ty, components, &ir_module.types)?; + self.write_constant_composite(id, ty, components)?; } } } From 0244853d4cf0b44b392a046ce8512acabc175620 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 28 May 2021 21:41:11 -0400 Subject: [PATCH 0898/2212] [wgsl-in] Support workgroup storage class --- src/front/wgsl/conv.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 7187bd560..9259a53ce 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -3,6 +3,7 @@ use super::Error; pub fn map_storage_class(word: &str) -> Result> { match word { "private" => Ok(crate::StorageClass::Private), + "workgroup" => Ok(crate::StorageClass::WorkGroup), "uniform" => Ok(crate::StorageClass::Uniform), "storage" => Ok(crate::StorageClass::Storage), "push_constant" => Ok(crate::StorageClass::PushConstant), From d1e2ac57fe359672e596bb4a3b8674f84d22bd04 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 28 May 2021 21:49:50 -0400 Subject: [PATCH 0899/2212] New snapshot test for global variables --- tests/in/globals.param.ron | 3 +++ tests/in/globals.wgsl | 9 +++++++++ tests/in/interface.wgsl | 2 +- tests/in/interpolate.wgsl | 2 ++ tests/out/globals.Compute.glsl | 11 +++++++++++ tests/out/globals.msl | 12 ++++++++++++ tests/out/globals.spvasm | 26 ++++++++++++++++++++++++++ tests/out/globals.wgsl | 8 ++++++++ tests/snapshots.rs | 4 ++++ 9 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 tests/in/globals.param.ron create mode 100644 tests/in/globals.wgsl create mode 100644 tests/out/globals.Compute.glsl create mode 100644 tests/out/globals.msl create mode 100644 tests/out/globals.spvasm create mode 100644 tests/out/globals.wgsl diff --git a/tests/in/globals.param.ron b/tests/in/globals.param.ron new file mode 100644 index 000000000..8b306e5b7 --- /dev/null +++ b/tests/in/globals.param.ron @@ -0,0 +1,3 @@ +( + spv_version: (1, 0), +) diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl new file mode 100644 index 000000000..3f20e53ef --- /dev/null +++ b/tests/in/globals.wgsl @@ -0,0 +1,9 @@ +// Global variable & constant declarations + +let Foo: bool = true; + +var wg : array; + +[[stage(compute), workgroup_size(1)]] +fn main() { +} diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index e56634e67..18b060702 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -1,4 +1,4 @@ -// Testing various parts of the pipeline interface: locations, built-ins, bindings, and entry points +// Testing various parts of the pipeline interface: locations, built-ins, and entry points struct VertexOutput { [[builtin(position)]] position: vec4; diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index 51eb4fde7..dcb8a66c5 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -1,3 +1,5 @@ +//TODO: mere with "interface"? + struct FragmentInput { [[builtin(position)]] position: vec4; [[location(0), interpolate(flat)]] flat : u32; diff --git a/tests/out/globals.Compute.glsl b/tests/out/globals.Compute.glsl new file mode 100644 index 000000000..63328eab1 --- /dev/null +++ b/tests/out/globals.Compute.glsl @@ -0,0 +1,11 @@ +#version 310 es + +precision highp float; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + + +void main() { + return; +} + diff --git a/tests/out/globals.msl b/tests/out/globals.msl new file mode 100644 index 000000000..638fa22ed --- /dev/null +++ b/tests/out/globals.msl @@ -0,0 +1,12 @@ +#include +#include + +constexpr constant bool Foo = true; +struct type2 { + float inner[10]; +}; + +kernel void main1( +) { + return; +} diff --git a/tests/out/globals.spvasm b/tests/out/globals.spvasm new file mode 100644 index 000000000..0078cf2e8 --- /dev/null +++ b/tests/out/globals.spvasm @@ -0,0 +1,26 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 15 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %12 "main" +OpExecutionMode %12 LocalSize 1 1 1 +OpDecorate %8 ArrayStride 4 +%2 = OpTypeVoid +%4 = OpTypeBool +%3 = OpConstantTrue %4 +%6 = OpTypeInt 32 1 +%5 = OpConstant %6 10 +%7 = OpTypeFloat 32 +%8 = OpTypeArray %7 %5 +%10 = OpTypePointer Workgroup %8 +%9 = OpVariable %10 Workgroup +%13 = OpTypeFunction %2 +%12 = OpFunction %2 None %13 +%11 = OpLabel +OpBranch %14 +%14 = OpLabel +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/globals.wgsl b/tests/out/globals.wgsl new file mode 100644 index 000000000..87ce46054 --- /dev/null +++ b/tests/out/globals.wgsl @@ -0,0 +1,8 @@ +let Foo: bool = true; + +var wg: array; + +[[stage(compute), workgroup_size(1, 1, 1)]] +fn main() { + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 6126b4659..4453309d3 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -293,6 +293,10 @@ fn convert_wgsl() { ), //TODO: GLSL https://github.com/gfx-rs/naga/issues/874 ("interface", Targets::SPIRV | Targets::METAL | Targets::WGSL), + ( + "globals", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + ), ]; for &(name, targets) in inputs.iter() { From 13665466453b457fa4a46eacff0655cd5bd515a2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 28 May 2021 22:11:39 -0400 Subject: [PATCH 0900/2212] [glsl-out] improve array types --- src/back/glsl/mod.rs | 69 ++++++++++++++++++--------------- tests/in/globals.wgsl | 3 +- tests/out/boids.Compute.glsl | 3 -- tests/out/globals.Compute.glsl | 2 + tests/out/globals.msl | 4 +- tests/out/globals.spvasm | 32 ++++++++------- tests/out/globals.wgsl | 3 +- tests/out/quad-vert.Vertex.glsl | 4 -- tests/out/shadow.Fragment.glsl | 2 - tests/out/skybox.Vertex.glsl | 1 - 10 files changed, 66 insertions(+), 57 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c74011a68..985c385c0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -564,6 +564,27 @@ impl<'a, W: Write> Writer<'a, W> { self.collect_reflection_info() } + fn write_array_size(&mut self, size: ArraySize) -> BackendResult { + write!(self.out, "[")?; + + // Write the array size + // Writes nothing if `ArraySize::Dynamic` + // Panics if `ArraySize::Constant` has a constant that isn't an uint + match size { + ArraySize::Constant(const_handle) => match self.module.constants[const_handle].inner { + ConstantInner::Scalar { + width: _, + value: ScalarValue::Uint(size), + } => write!(self.out, "{}", size)?, + _ => unreachable!(), + }, + ArraySize::Dynamic => (), + } + + write!(self.out, "]")?; + Ok(()) + } + /// Helper method used to write value types /// /// # Notes @@ -615,27 +636,7 @@ impl<'a, W: Write> Writer<'a, W> { // GLSL arrays are written as `type name[size]` // Current code is written arrays only as `[size]` // Base `type` and `name` should be written outside - TypeInner::Array { base: _, size, .. } => { - write!(self.out, "[")?; - - // Write the array size - // Writes nothing if `ArraySize::Dynamic` - // Panics if `ArraySize::Constant` has a constant that isn't an uint - match size { - ArraySize::Constant(const_handle) => { - match self.module.constants[const_handle].inner { - ConstantInner::Scalar { - width: _, - value: ScalarValue::Uint(size), - } => write!(self.out, "{}", size)?, - _ => unreachable!(), - } - } - ArraySize::Dynamic => (), - } - - write!(self.out, "]")? - } + TypeInner::Array { size, .. } => self.write_array_size(size)?, // Panic if either Image, Sampler, Pointer, or a Struct is being written // // Write all variants instead of `_` so that if new variants are added a @@ -674,6 +675,8 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}", name)?; Ok(()) } + // glsl array has the size separated from the base type + TypeInner::Array { base, .. } => self.write_type(base), ref other => self.write_value_type(other), } } @@ -756,14 +759,14 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important let global_name = self.get_global_name(handle, global); - let global_str = - if let Some(default_value) = zero_init_value_str(&self.module.types[global.ty].inner) { - format!("{} = {}", global_name, default_value) - } else { - global_name - }; - writeln!(self.out, " {};", global_str)?; - writeln!(self.out)?; + write!(self.out, " {}", global_name)?; + if let TypeInner::Array { size, .. } = self.module.types[global.ty].inner { + self.write_array_size(size)?; + } + if let Some(default_value) = zero_init_value_str(&self.module.types[global.ty].inner) { + write!(self.out, " = {}", default_value)?; + }; + writeln!(self.out, ";")?; Ok(()) } @@ -1117,7 +1120,11 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}", INDENT)?; match self.module.types[member.ty].inner { - TypeInner::Array { base, .. } => { + TypeInner::Array { + base, + size, + stride: _, + } => { // GLSL arrays are written as `type name[size]` let ty_name = match self.module.types[base].inner { // Write scalar type by backend so as not to depend on the front-end implementation @@ -1134,7 +1141,7 @@ impl<'a, W: Write> Writer<'a, W> { &self.names[&NameKey::StructMember(handle, idx as u32)] )?; // Write [size] - self.write_type(member.ty)?; + self.write_array_size(size)?; // Newline is important writeln!(self.out, ";")?; } diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 3f20e53ef..bab28b3fe 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -2,8 +2,9 @@ let Foo: bool = true; -var wg : array; +var wg : array; [[stage(compute), workgroup_size(1)]] fn main() { + wg[3] = 1.0; } diff --git a/tests/out/boids.Compute.glsl b/tests/out/boids.Compute.glsl index e518b6cc7..e54432d5c 100644 --- a/tests/out/boids.Compute.glsl +++ b/tests/out/boids.Compute.glsl @@ -18,16 +18,13 @@ uniform SimParams_block_0 { float rule2Scale; float rule3Scale; } _group_0_binding_0; - readonly buffer Particles_block_1 { Particle particles[]; } _group_0_binding_1; - buffer Particles_block_2 { Particle particles[]; } _group_0_binding_2; - void main() { uvec3 global_invocation_id = gl_GlobalInvocationID; vec2 vPos; diff --git a/tests/out/globals.Compute.glsl b/tests/out/globals.Compute.glsl index 63328eab1..2fba504b7 100644 --- a/tests/out/globals.Compute.glsl +++ b/tests/out/globals.Compute.glsl @@ -4,8 +4,10 @@ precision highp float; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +shared float wg[10]; void main() { + wg[3] = 1.0; return; } diff --git a/tests/out/globals.msl b/tests/out/globals.msl index 638fa22ed..435c090f2 100644 --- a/tests/out/globals.msl +++ b/tests/out/globals.msl @@ -3,10 +3,12 @@ constexpr constant bool Foo = true; struct type2 { - float inner[10]; + float inner[10u]; }; kernel void main1( + threadgroup type2& wg ) { + wg.inner[3] = 1.0; return; } diff --git a/tests/out/globals.spvasm b/tests/out/globals.spvasm index 0078cf2e8..2668d178d 100644 --- a/tests/out/globals.spvasm +++ b/tests/out/globals.spvasm @@ -1,26 +1,32 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 15 +; Bound: 20 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %12 "main" -OpExecutionMode %12 LocalSize 1 1 1 -OpDecorate %8 ArrayStride 4 +OpEntryPoint GLCompute %15 "main" +OpExecutionMode %15 LocalSize 1 1 1 +OpDecorate %11 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 -%6 = OpTypeInt 32 1 +%6 = OpTypeInt 32 0 %5 = OpConstant %6 10 -%7 = OpTypeFloat 32 -%8 = OpTypeArray %7 %5 -%10 = OpTypePointer Workgroup %8 -%9 = OpVariable %10 Workgroup -%13 = OpTypeFunction %2 -%12 = OpFunction %2 None %13 -%11 = OpLabel -OpBranch %14 +%8 = OpTypeInt 32 1 +%7 = OpConstant %8 3 +%10 = OpTypeFloat 32 +%9 = OpConstant %10 1.0 +%11 = OpTypeArray %10 %5 +%13 = OpTypePointer Workgroup %11 +%12 = OpVariable %13 Workgroup +%16 = OpTypeFunction %2 +%18 = OpTypePointer Workgroup %10 +%15 = OpFunction %2 None %16 %14 = OpLabel +OpBranch %17 +%17 = OpLabel +%19 = OpAccessChain %18 %12 %7 +OpStore %19 %9 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/globals.wgsl b/tests/out/globals.wgsl index 87ce46054..36856539f 100644 --- a/tests/out/globals.wgsl +++ b/tests/out/globals.wgsl @@ -1,8 +1,9 @@ let Foo: bool = true; -var wg: array; +var wg: array; [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { + wg[3] = 1.0; return; } diff --git a/tests/out/quad-vert.Vertex.glsl b/tests/out/quad-vert.Vertex.glsl index e1b9853b0..c2f59e712 100644 --- a/tests/out/quad-vert.Vertex.glsl +++ b/tests/out/quad-vert.Vertex.glsl @@ -11,18 +11,14 @@ struct type10 { }; vec2 v_uv = vec2(0, 0); - vec2 a_uv = vec2(0, 0); - struct gen_gl_PerVertex_block_0 { vec4 gen_gl_Position; float gen_gl_PointSize; float gen_gl_ClipDistance[1]; float gen_gl_CullDistance[1]; } perVertexStruct; - vec2 a_pos = vec2(0, 0); - layout(location = 1) in vec2 _p2vs_location1; layout(location = 0) in vec2 _p2vs_location0; smooth layout(location = 0) out vec2 _vs2fs_location0; diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index 2042b5f22..5b9c58de0 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -11,11 +11,9 @@ struct Light { uniform Globals_block_0 { uvec4 num_lights; } _group_0_binding_0; - readonly buffer Lights_block_1 { Light data[]; } _group_0_binding_1; - uniform highp sampler2DArrayShadow _group_0_binding_2; smooth layout(location = 0) in vec3 _vs2fs_location0; diff --git a/tests/out/skybox.Vertex.glsl b/tests/out/skybox.Vertex.glsl index 870a4ee26..2d35107bc 100644 --- a/tests/out/skybox.Vertex.glsl +++ b/tests/out/skybox.Vertex.glsl @@ -11,7 +11,6 @@ uniform Data_block_0 { mat4x4 proj_inv; mat4x4 view; } _group_0_binding_0; - smooth layout(location = 0) out vec3 _vs2fs_location0; void main() { From 8a1d883ba5fd37c9f52e3aa13e08347c32ecc0bd Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 28 May 2021 22:32:35 -0400 Subject: [PATCH 0901/2212] [wgsl-in] support textureSampleCompareLevel --- src/front/wgsl/mod.rs | 32 ++++++++++++++++++++++++++++++++ tests/in/shadow.wgsl | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index d9bb9ba2d..45e19cead 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -880,6 +880,38 @@ impl Parser { } } "textureSampleCompare" => { + lexer.open_arguments()?; + let (image_name, image_span) = lexer.next_ident_with_span()?; + lexer.expect(Token::Separator(','))?; + let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let sc = ctx.prepare_sampling(image_name, image_span)?; + let array_index = if sc.arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; + lexer.expect(Token::Separator(','))?; + let reference = self.parse_general_expression(lexer, ctx.reborrow())?; + let offset = if lexer.skip(Token::Separator(',')) { + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) + } else { + None + }; + lexer.close_arguments()?; + crate::Expression::ImageSample { + image: sc.image, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, + coordinate, + array_index, + offset, + level: crate::SampleLevel::Auto, + depth_ref: Some(reference), + } + } + "textureSampleCompareLevel" => { lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 9cd5253bc..89780ea6e 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -30,7 +30,7 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { } let flip_correction = vec2(0.5, -0.5); let light_local = homogeneous_coords.xy * flip_correction / homogeneous_coords.w + vec2(0.5, 0.5); - return textureSampleCompare(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z / homogeneous_coords.w); + return textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z / homogeneous_coords.w); } let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); From d3fbb30d46ff41e10e7b96d0402416f48877a83c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 28 May 2021 22:32:50 -0400 Subject: [PATCH 0902/2212] [wgsl-out] Improve texture sampling call --- src/back/wgsl/writer.rs | 57 +++++++++++++++++++++++------------------ tests/out/shadow.wgsl | 2 +- 2 files changed, 33 insertions(+), 26 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 2f774bdea..417fbe585 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -960,18 +960,18 @@ impl Writer { level, depth_ref, } => { - let texture_function = if depth_ref.is_some() { - "textureSampleCompare" - } else { - match level { - SampleLevel::Auto | SampleLevel::Zero => "textureSample", - SampleLevel::Exact(_) => "textureSampleLevel", - SampleLevel::Bias(_) => "textureSampleBias", - SampleLevel::Gradient { .. } => "textureSampleGrad", - } + let suffix_cmp = match depth_ref { + Some(_) => "Compare", + None => "", + }; + let suffix_level = match level { + SampleLevel::Auto => "", + SampleLevel::Zero | SampleLevel::Exact(_) => "Level", + SampleLevel::Bias(_) => "Bias", + SampleLevel::Gradient { .. } => "Grad", }; - write!(self.out, "{}(", texture_function)?; + write!(self.out, "textureSample{}{}(", suffix_cmp, suffix_level)?; self.write_expr(module, image, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, sampler, func_ctx)?; @@ -983,26 +983,33 @@ impl Writer { self.write_expr(module, array_index, func_ctx)?; } - if let SampleLevel::Bias(expr) = level { - write!(self.out, ", ")?; - self.write_expr(module, expr, func_ctx)?; - } - if let Some(depth_ref) = depth_ref { write!(self.out, ", ")?; self.write_expr(module, depth_ref, func_ctx)?; } - if let SampleLevel::Gradient { x, y } = level { - write!(self.out, ", ")?; - self.write_expr(module, x, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, y, func_ctx)?; - } - - if let SampleLevel::Exact(expr) = level { - write!(self.out, ", ")?; - self.write_expr(module, expr, func_ctx)?; + match level { + SampleLevel::Auto => {} + SampleLevel::Zero => { + // Level 0 is implied for depth comparison + if depth_ref.is_none() { + write!(self.out, ", 0.0")?; + } + } + SampleLevel::Exact(expr) => { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + SampleLevel::Bias(expr) => { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + SampleLevel::Gradient { x, y } => { + write!(self.out, ", ")?; + self.write_expr(module, x, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, y, func_ctx)?; + } } if let Some(offset) = offset { diff --git a/tests/out/shadow.wgsl b/tests/out/shadow.wgsl index 20731bc10..c5ca9f0a5 100644 --- a/tests/out/shadow.wgsl +++ b/tests/out/shadow.wgsl @@ -30,7 +30,7 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { if ((homogeneous_coords.w <= 0.0)) { return 1.0; } - let _e26: f32 = textureSampleCompare(t_shadow, sampler_shadow, (((homogeneous_coords.xy * vec2(0.5, -0.5)) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)), i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); + let _e26: f32 = textureSampleCompareLevel(t_shadow, sampler_shadow, (((homogeneous_coords.xy * vec2(0.5, -0.5)) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)), i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); return _e26; } From 4b5ab528ac1203a9201230d1c910d1c8f735d906 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 28 May 2021 22:39:18 -0400 Subject: [PATCH 0903/2212] Comparison sampling tests --- tests/in/image.wgsl | 14 ++ tests/out/image.msl | 14 ++ tests/out/image.spvasm | 351 +++++++++++++++++++++++------------------ tests/out/image.wgsl | 12 ++ 4 files changed, 234 insertions(+), 157 deletions(-) diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 440cd351d..05cfe7505 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -58,3 +58,17 @@ fn queries() -> [[builtin(position)]] vec4 { num_levels_2d + num_levels_2d_array + num_levels_3d + num_levels_cube + num_levels_cube_array; return vec4(f32(sum)); } + +[[group(1), binding(0)]] +var sampler_cmp: sampler_comparison; +[[group(1), binding(1)]] +var image_2d_depth: texture_depth_2d; + +[[stage(fragment)]] +fn sample_comparison() -> [[location(0)]] f32 { + let tc = vec2(0.5); + let dref = 0.5; + let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc, dref); + let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc, dref); + return s2d_depth + s2d_depth_level; +} diff --git a/tests/out/image.msl b/tests/out/image.msl index a8d37578e..e569e4504 100644 --- a/tests/out/image.msl +++ b/tests/out/image.msl @@ -30,3 +30,17 @@ vertex queriesOutput queries( ) { return queriesOutput { metal::float4(static_cast((((((((((((((((((int(image_1d.get_width()) + int2(image_2d.get_width(), image_2d.get_height()).y) + int2(image_2d.get_width(1), image_2d.get_height(1)).y) + int2(image_2d_array.get_width(), image_2d_array.get_height()).y) + int2(image_2d_array.get_width(1), image_2d_array.get_height(1)).y) + int(image_2d_array.get_array_size())) + int3(image_cube.get_width()).y) + int3(image_cube.get_width(1)).y) + int3(image_cube_array.get_width()).y) + int3(image_cube_array.get_width(1)).y) + int(image_cube_array.get_array_size())) + int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()).z) + int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)).z) + int(image_aa.get_num_samples())) + int(image_2d.get_num_mip_levels())) + int(image_2d_array.get_num_mip_levels())) + int(image_3d.get_num_mip_levels())) + int(image_cube.get_num_mip_levels())) + int(image_cube_array.get_num_mip_levels()))) }; } + + +struct sample_comparisonOutput { + float member2 [[color(0)]]; +}; +fragment sample_comparisonOutput sample_comparison( + metal::sampler sampler_cmp [[user(fake0)]] +, metal::depth2d image_2d_depth [[user(fake0)]] +) { + metal::float2 _e12 = metal::float2(0.5); + float _e14 = image_2d_depth.sample_compare(sampler_cmp, _e12, 0.5); + float _e15 = image_2d_depth.sample_compare(sampler_cmp, _e12, 0.5); + return sample_comparisonOutput { _e14 + _e15 }; +} diff --git a/tests/out/image.spvasm b/tests/out/image.spvasm index 08d1f5a8e..d3d3b7fde 100644 --- a/tests/out/image.spvasm +++ b/tests/out/image.spvasm @@ -1,180 +1,217 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 127 +; Bound: 150 OpCapability Image1D OpCapability Shader OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %43 "main" %40 -OpEntryPoint Vertex %61 "queries" %59 -OpExecutionMode %43 LocalSize 16 1 1 +OpEntryPoint GLCompute %50 "main" %47 +OpEntryPoint Vertex %68 "queries" %66 +OpEntryPoint Fragment %137 "sample_comparison" %135 +OpExecutionMode %50 LocalSize 16 1 1 +OpExecutionMode %137 OriginUpperLeft OpSource GLSL 450 -OpName %21 "image_src" -OpName %23 "image_dst" -OpName %25 "image_1d" -OpName %27 "image_2d" -OpName %29 "image_2d_array" -OpName %31 "image_cube" -OpName %33 "image_cube_array" -OpName %35 "image_3d" -OpName %37 "image_aa" -OpName %40 "local_id" -OpName %43 "main" -OpName %61 "queries" -OpDecorate %21 NonWritable -OpDecorate %21 DescriptorSet 0 -OpDecorate %21 Binding 1 -OpDecorate %23 NonReadable -OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 2 -OpDecorate %25 DescriptorSet 0 -OpDecorate %25 Binding 0 -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 1 -OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 2 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 3 -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 4 -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 5 -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 6 -OpDecorate %40 BuiltIn LocalInvocationId -OpDecorate %59 BuiltIn Position +OpName %24 "image_src" +OpName %26 "image_dst" +OpName %28 "image_1d" +OpName %30 "image_2d" +OpName %32 "image_2d_array" +OpName %34 "image_cube" +OpName %36 "image_cube_array" +OpName %38 "image_3d" +OpName %40 "image_aa" +OpName %42 "sampler_cmp" +OpName %44 "image_2d_depth" +OpName %47 "local_id" +OpName %50 "main" +OpName %68 "queries" +OpName %137 "sample_comparison" +OpDecorate %24 NonWritable +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 1 +OpDecorate %26 NonReadable +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 2 +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 0 +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 1 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 2 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 3 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 4 +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 5 +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 6 +OpDecorate %42 DescriptorSet 1 +OpDecorate %42 Binding 0 +OpDecorate %44 DescriptorSet 1 +OpDecorate %44 Binding 1 +OpDecorate %47 BuiltIn LocalInvocationId +OpDecorate %66 BuiltIn Position +OpDecorate %135 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 %5 = OpConstant %4 20 %6 = OpConstant %4 1 -%8 = OpTypeInt 32 0 -%7 = OpTypeImage %8 2D 0 0 0 2 Rgba8ui -%9 = OpTypeImage %8 1D 0 0 0 2 R32ui -%10 = OpTypeVector %8 3 -%11 = OpTypeVector %4 2 -%13 = OpTypeFloat 32 -%12 = OpTypeImage %13 1D 0 0 0 1 Unknown -%14 = OpTypeImage %13 2D 0 0 0 1 Unknown -%15 = OpTypeImage %13 2D 0 1 0 1 Unknown -%16 = OpTypeImage %13 Cube 0 0 0 1 Unknown -%17 = OpTypeImage %13 Cube 0 1 0 1 Unknown -%18 = OpTypeImage %13 3D 0 0 0 1 Unknown -%19 = OpTypeImage %13 2D 0 0 1 1 Unknown -%20 = OpTypeVector %13 4 -%22 = OpTypePointer UniformConstant %7 -%21 = OpVariable %22 UniformConstant -%24 = OpTypePointer UniformConstant %9 -%23 = OpVariable %24 UniformConstant -%26 = OpTypePointer UniformConstant %12 -%25 = OpVariable %26 UniformConstant -%28 = OpTypePointer UniformConstant %14 -%27 = OpVariable %28 UniformConstant -%30 = OpTypePointer UniformConstant %15 -%29 = OpVariable %30 UniformConstant -%32 = OpTypePointer UniformConstant %16 -%31 = OpVariable %32 UniformConstant -%34 = OpTypePointer UniformConstant %17 -%33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %18 -%35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %19 -%37 = OpVariable %38 UniformConstant -%41 = OpTypePointer Input %10 -%40 = OpVariable %41 Input -%44 = OpTypeFunction %2 -%49 = OpTypeVector %8 2 -%55 = OpTypeVector %8 4 -%60 = OpTypePointer Output %20 -%59 = OpVariable %60 Output -%70 = OpConstant %8 0 -%75 = OpTypeVector %4 3 -%43 = OpFunction %2 None %44 -%39 = OpLabel -%42 = OpLoad %10 %40 -%45 = OpLoad %7 %21 -%46 = OpLoad %9 %23 -OpBranch %47 -%47 = OpLabel -%48 = OpImageQuerySize %11 %45 -%50 = OpVectorShuffle %49 %42 %42 0 1 -%51 = OpBitcast %11 %50 -%52 = OpIMul %11 %48 %51 -%53 = OpCompositeConstruct %11 %3 %5 -%54 = OpSMod %11 %52 %53 -%56 = OpImageRead %55 %45 %54 -%57 = OpCompositeExtract %4 %54 0 -OpImageWrite %46 %57 %56 +%8 = OpTypeFloat 32 +%7 = OpConstant %8 0.5 +%10 = OpTypeInt 32 0 +%9 = OpTypeImage %10 2D 0 0 0 2 Rgba8ui +%11 = OpTypeImage %10 1D 0 0 0 2 R32ui +%12 = OpTypeVector %10 3 +%13 = OpTypeVector %4 2 +%14 = OpTypeImage %8 1D 0 0 0 1 Unknown +%15 = OpTypeImage %8 2D 0 0 0 1 Unknown +%16 = OpTypeImage %8 2D 0 1 0 1 Unknown +%17 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%18 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%19 = OpTypeImage %8 3D 0 0 0 1 Unknown +%20 = OpTypeImage %8 2D 0 0 1 1 Unknown +%21 = OpTypeVector %8 4 +%22 = OpTypeSampler +%23 = OpTypeImage %8 2D 1 0 0 1 Unknown +%25 = OpTypePointer UniformConstant %9 +%24 = OpVariable %25 UniformConstant +%27 = OpTypePointer UniformConstant %11 +%26 = OpVariable %27 UniformConstant +%29 = OpTypePointer UniformConstant %14 +%28 = OpVariable %29 UniformConstant +%31 = OpTypePointer UniformConstant %15 +%30 = OpVariable %31 UniformConstant +%33 = OpTypePointer UniformConstant %16 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer UniformConstant %17 +%34 = OpVariable %35 UniformConstant +%37 = OpTypePointer UniformConstant %18 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %19 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %20 +%40 = OpVariable %41 UniformConstant +%43 = OpTypePointer UniformConstant %22 +%42 = OpVariable %43 UniformConstant +%45 = OpTypePointer UniformConstant %23 +%44 = OpVariable %45 UniformConstant +%48 = OpTypePointer Input %12 +%47 = OpVariable %48 Input +%51 = OpTypeFunction %2 +%56 = OpTypeVector %10 2 +%62 = OpTypeVector %10 4 +%67 = OpTypePointer Output %21 +%66 = OpVariable %67 Output +%77 = OpConstant %10 0 +%82 = OpTypeVector %4 3 +%136 = OpTypePointer Output %8 +%135 = OpVariable %136 Output +%141 = OpTypeVector %8 2 +%143 = OpTypeSampledImage %23 +%148 = OpConstant %8 0.0 +%50 = OpFunction %2 None %51 +%46 = OpLabel +%49 = OpLoad %12 %47 +%52 = OpLoad %9 %24 +%53 = OpLoad %11 %26 +OpBranch %54 +%54 = OpLabel +%55 = OpImageQuerySize %13 %52 +%57 = OpVectorShuffle %56 %49 %49 0 1 +%58 = OpBitcast %13 %57 +%59 = OpIMul %13 %55 %58 +%60 = OpCompositeConstruct %13 %3 %5 +%61 = OpSMod %13 %59 %60 +%63 = OpImageRead %62 %52 %61 +%64 = OpCompositeExtract %4 %61 0 +OpImageWrite %53 %64 %63 OpReturn OpFunctionEnd -%61 = OpFunction %2 None %44 -%58 = OpLabel -%62 = OpLoad %12 %25 -%63 = OpLoad %14 %27 -%64 = OpLoad %15 %29 -%65 = OpLoad %16 %31 -%66 = OpLoad %17 %33 -%67 = OpLoad %18 %35 -%68 = OpLoad %19 %37 -OpBranch %69 -%69 = OpLabel -%71 = OpImageQuerySizeLod %4 %62 %70 -%72 = OpImageQuerySizeLod %11 %63 %70 -%73 = OpImageQueryLevels %4 %63 -%74 = OpImageQuerySizeLod %11 %63 %6 -%76 = OpImageQuerySizeLod %75 %64 %70 -%77 = OpVectorShuffle %11 %76 %76 0 1 -%78 = OpImageQueryLevels %4 %64 -%79 = OpImageQuerySizeLod %75 %64 %6 -%80 = OpVectorShuffle %11 %79 %79 0 1 -%81 = OpImageQuerySizeLod %75 %64 %70 -%82 = OpCompositeExtract %4 %81 2 -%83 = OpImageQuerySizeLod %11 %65 %70 -%84 = OpVectorShuffle %75 %83 %83 0 0 0 -%85 = OpImageQueryLevels %4 %65 -%86 = OpImageQuerySizeLod %11 %65 %6 -%87 = OpVectorShuffle %75 %86 %86 0 0 0 -%88 = OpImageQuerySizeLod %75 %66 %70 -%89 = OpImageQueryLevels %4 %66 -%90 = OpImageQuerySizeLod %75 %66 %6 -%91 = OpImageQuerySizeLod %75 %66 %70 -%92 = OpCompositeExtract %4 %91 2 -%93 = OpImageQuerySizeLod %75 %67 %70 -%94 = OpImageQueryLevels %4 %67 -%95 = OpImageQuerySizeLod %75 %67 %6 -%96 = OpImageQuerySamples %4 %68 -%97 = OpCompositeExtract %4 %72 1 -%98 = OpIAdd %4 %71 %97 -%99 = OpCompositeExtract %4 %74 1 -%100 = OpIAdd %4 %98 %99 -%101 = OpCompositeExtract %4 %77 1 -%102 = OpIAdd %4 %100 %101 -%103 = OpCompositeExtract %4 %80 1 -%104 = OpIAdd %4 %102 %103 -%105 = OpIAdd %4 %104 %82 -%106 = OpCompositeExtract %4 %84 1 +%68 = OpFunction %2 None %51 +%65 = OpLabel +%69 = OpLoad %14 %28 +%70 = OpLoad %15 %30 +%71 = OpLoad %16 %32 +%72 = OpLoad %17 %34 +%73 = OpLoad %18 %36 +%74 = OpLoad %19 %38 +%75 = OpLoad %20 %40 +OpBranch %76 +%76 = OpLabel +%78 = OpImageQuerySizeLod %4 %69 %77 +%79 = OpImageQuerySizeLod %13 %70 %77 +%80 = OpImageQueryLevels %4 %70 +%81 = OpImageQuerySizeLod %13 %70 %6 +%83 = OpImageQuerySizeLod %82 %71 %77 +%84 = OpVectorShuffle %13 %83 %83 0 1 +%85 = OpImageQueryLevels %4 %71 +%86 = OpImageQuerySizeLod %82 %71 %6 +%87 = OpVectorShuffle %13 %86 %86 0 1 +%88 = OpImageQuerySizeLod %82 %71 %77 +%89 = OpCompositeExtract %4 %88 2 +%90 = OpImageQuerySizeLod %13 %72 %77 +%91 = OpVectorShuffle %82 %90 %90 0 0 0 +%92 = OpImageQueryLevels %4 %72 +%93 = OpImageQuerySizeLod %13 %72 %6 +%94 = OpVectorShuffle %82 %93 %93 0 0 0 +%95 = OpImageQuerySizeLod %82 %73 %77 +%96 = OpImageQueryLevels %4 %73 +%97 = OpImageQuerySizeLod %82 %73 %6 +%98 = OpImageQuerySizeLod %82 %73 %77 +%99 = OpCompositeExtract %4 %98 2 +%100 = OpImageQuerySizeLod %82 %74 %77 +%101 = OpImageQueryLevels %4 %74 +%102 = OpImageQuerySizeLod %82 %74 %6 +%103 = OpImageQuerySamples %4 %75 +%104 = OpCompositeExtract %4 %79 1 +%105 = OpIAdd %4 %78 %104 +%106 = OpCompositeExtract %4 %81 1 %107 = OpIAdd %4 %105 %106 -%108 = OpCompositeExtract %4 %87 1 +%108 = OpCompositeExtract %4 %84 1 %109 = OpIAdd %4 %107 %108 -%110 = OpCompositeExtract %4 %88 1 +%110 = OpCompositeExtract %4 %87 1 %111 = OpIAdd %4 %109 %110 -%112 = OpCompositeExtract %4 %90 1 -%113 = OpIAdd %4 %111 %112 -%114 = OpIAdd %4 %113 %92 -%115 = OpCompositeExtract %4 %93 2 +%112 = OpIAdd %4 %111 %89 +%113 = OpCompositeExtract %4 %91 1 +%114 = OpIAdd %4 %112 %113 +%115 = OpCompositeExtract %4 %94 1 %116 = OpIAdd %4 %114 %115 -%117 = OpCompositeExtract %4 %95 2 +%117 = OpCompositeExtract %4 %95 1 %118 = OpIAdd %4 %116 %117 -%119 = OpIAdd %4 %118 %96 -%120 = OpIAdd %4 %119 %73 -%121 = OpIAdd %4 %120 %78 -%122 = OpIAdd %4 %121 %94 -%123 = OpIAdd %4 %122 %85 -%124 = OpIAdd %4 %123 %89 -%125 = OpConvertSToF %13 %124 -%126 = OpCompositeConstruct %20 %125 %125 %125 %125 -OpStore %59 %126 +%119 = OpCompositeExtract %4 %97 1 +%120 = OpIAdd %4 %118 %119 +%121 = OpIAdd %4 %120 %99 +%122 = OpCompositeExtract %4 %100 2 +%123 = OpIAdd %4 %121 %122 +%124 = OpCompositeExtract %4 %102 2 +%125 = OpIAdd %4 %123 %124 +%126 = OpIAdd %4 %125 %103 +%127 = OpIAdd %4 %126 %80 +%128 = OpIAdd %4 %127 %85 +%129 = OpIAdd %4 %128 %101 +%130 = OpIAdd %4 %129 %92 +%131 = OpIAdd %4 %130 %96 +%132 = OpConvertSToF %8 %131 +%133 = OpCompositeConstruct %21 %132 %132 %132 %132 +OpStore %66 %133 +OpReturn +OpFunctionEnd +%137 = OpFunction %2 None %51 +%134 = OpLabel +%138 = OpLoad %22 %42 +%139 = OpLoad %23 %44 +OpBranch %140 +%140 = OpLabel +%142 = OpCompositeConstruct %141 %7 %7 +%144 = OpSampledImage %143 %139 %138 +%145 = OpImageSampleDrefImplicitLod %8 %144 %142 %7 +%146 = OpSampledImage %143 %139 %138 +%147 = OpImageSampleDrefExplicitLod %8 %146 %142 %7 Lod %148 +%149 = OpFAdd %8 %145 %147 +OpStore %135 %149 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/image.wgsl b/tests/out/image.wgsl index f92a356c4..4d1ead826 100644 --- a/tests/out/image.wgsl +++ b/tests/out/image.wgsl @@ -16,6 +16,10 @@ var image_cube_array: texture_cube_array; var image_3d: texture_3d; [[group(0), binding(6)]] var image_aa: texture_multisampled_2d; +[[group(1), binding(0)]] +var sampler_cmp: sampler_comparison; +[[group(1), binding(1)]] +var image_2d_depth: texture_depth_2d; [[stage(compute), workgroup_size(16, 1, 1)]] fn main([[builtin(local_invocation_id)]] local_id: vec3) { @@ -49,3 +53,11 @@ fn queries() -> [[builtin(position)]] vec4 { let _e32: i32 = textureNumSamples(image_aa); return vec4(f32(((((((((((((((((((_e9 + _e10.y) + _e13.y) + _e14.y) + _e17.y) + _e18) + _e19.y) + _e22.y) + _e23.y) + _e26.y) + _e27) + _e28.z) + _e31.z) + _e32) + _e11) + _e15) + _e29) + _e20) + _e24))); } + +[[stage(fragment)]] +fn sample_comparison() -> [[location(0)]] f32 { + let _e12: vec2 = vec2(0.5); + let _e14: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, _e12, 0.5); + let _e15: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, _e12, 0.5); + return (_e14 + _e15); +} From b9e641c310412cb0af8f922b7cdf3a7950dac085 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 29 May 2021 17:59:08 +0100 Subject: [PATCH 0904/2212] [glsl-in] Expression implicit conversions --- src/front/glsl/ast.rs | 127 +++++++++++++++++++++++++++++++++--- src/front/glsl/functions.rs | 49 +++++++------- src/front/glsl/parser.rs | 2 + 3 files changed, 145 insertions(+), 33 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 6c86e9d64..a32edde14 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -7,8 +7,8 @@ use super::{ use crate::{ proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, - RelationalFunction, ResourceBinding, Sampling, ShaderStage, Statement, StorageClass, Type, - TypeInner, UnaryOperator, + RelationalFunction, ResourceBinding, Sampling, ScalarKind, ShaderStage, Statement, + StorageClass, Type, TypeInner, UnaryOperator, }; #[derive(Debug, Clone, Copy)] @@ -398,8 +398,12 @@ impl<'function> Context<'function> { self.add_expression(Expression::Constant(constant), body) } HirExprKind::Binary { left, op, right } if !lhs => { - let (left, left_meta) = self.lower_expect(program, left, false, body)?; - let (right, right_meta) = self.lower_expect(program, right, false, body)?; + let (mut left, left_meta) = self.lower_expect(program, left, false, body)?; + let (mut right, right_meta) = self.lower_expect(program, right, false, body)?; + + self.binary_implicit_conversion( + program, &mut left, left_meta, &mut right, right_meta, + )?; if let BinaryOperator::Equal | BinaryOperator::NotEqual = op { let equals = op == BinaryOperator::Equal; @@ -466,8 +470,16 @@ impl<'function> Context<'function> { reject, } if !lhs => { let condition = self.lower_expect(program, condition, false, body)?.0; - let accept = self.lower_expect(program, accept, false, body)?.0; - let reject = self.lower_expect(program, reject, false, body)?.0; + let (mut accept, accept_meta) = self.lower_expect(program, accept, false, body)?; + let (mut reject, reject_meta) = self.lower_expect(program, reject, false, body)?; + + self.binary_implicit_conversion( + program, + &mut accept, + accept_meta, + &mut reject, + reject_meta, + )?; self.add_expression( Expression::Select { @@ -479,8 +491,19 @@ impl<'function> Context<'function> { ) } HirExprKind::Assign { tgt, value } if !lhs => { - let pointer = self.lower_expect(program, tgt, true, body)?.0; - let value = self.lower_expect(program, value, false, body)?.0; + let (pointer, ptr_meta) = self.lower_expect(program, tgt, true, body)?; + let (mut value, value_meta) = self.lower_expect(program, value, false, body)?; + + let ptr_kind = match *program.resolve_type(self, pointer, ptr_meta)? { + TypeInner::Pointer { base, .. } => { + program.module.types[base].inner.scalar_kind() + } + ref ty => ty.scalar_kind(), + }; + + if let Some(kind) = ptr_kind { + self.implicit_conversion(program, &mut value, value_meta, kind)?; + } self.emit_flush(body); self.emit_start(); @@ -499,6 +522,94 @@ impl<'function> Context<'function> { Ok((Some(handle), meta)) } + + pub fn expr_scalar_kind( + &mut self, + program: &mut Program, + expr: Handle, + meta: SourceMetadata, + ) -> Result, ErrorKind> { + Ok(program.resolve_type(self, expr, meta)?.scalar_kind()) + } + + pub fn expr_power( + &mut self, + program: &mut Program, + expr: Handle, + meta: SourceMetadata, + ) -> Result, ErrorKind> { + Ok(self + .expr_scalar_kind(program, expr, meta)? + .and_then(type_power)) + } + + pub fn implicit_conversion( + &mut self, + program: &mut Program, + expr: &mut Handle, + meta: SourceMetadata, + kind: ScalarKind, + ) -> Result<(), ErrorKind> { + if let (Some(tgt_power), Some(expr_power)) = + (type_power(kind), self.expr_power(program, *expr, meta)?) + { + if tgt_power > expr_power { + *expr = self.expressions.append(Expression::As { + expr: *expr, + kind, + convert: None, + }) + } + } + + Ok(()) + } + + pub fn binary_implicit_conversion( + &mut self, + program: &mut Program, + left: &mut Handle, + left_meta: SourceMetadata, + right: &mut Handle, + right_meta: SourceMetadata, + ) -> Result<(), ErrorKind> { + let left_kind = self.expr_scalar_kind(program, *left, left_meta)?; + let right_kind = self.expr_scalar_kind(program, *right, right_meta)?; + + if let (Some((left_power, left_kind)), Some((right_power, right_kind))) = ( + left_kind.and_then(|kind| Some((type_power(kind)?, kind))), + right_kind.and_then(|kind| Some((type_power(kind)?, kind))), + ) { + match left_power.cmp(&right_power) { + std::cmp::Ordering::Less => { + *left = self.expressions.append(Expression::As { + expr: *left, + kind: right_kind, + convert: None, + }) + } + std::cmp::Ordering::Equal => {} + std::cmp::Ordering::Greater => { + *right = self.expressions.append(Expression::As { + expr: *right, + kind: left_kind, + convert: None, + }) + } + } + } + + Ok(()) + } +} + +fn type_power(kind: ScalarKind) -> Option { + Some(match kind { + ScalarKind::Sint => 0, + ScalarKind::Uint => 1, + ScalarKind::Float => 2, + ScalarKind::Bool => return None, + }) } #[derive(Debug, Clone)] diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 8bb5d04a7..db6822de4 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,8 +1,8 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Binding, Block, BuiltIn, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, MathFunction, - RelationalFunction, SampleLevel, ShaderStage, Statement, StructMember, SwizzleComponent, Type, - TypeInner, + RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, StructMember, + SwizzleComponent, Type, TypeInner, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; @@ -30,13 +30,12 @@ impl Program<'_> { }; match self.module.types[ty].inner { - TypeInner::Vector { size, .. } if !is_vec => ctx.add_expression( - Expression::Splat { - size, - value: args[0].0, - }, - body, - ), + TypeInner::Vector { size, kind, .. } if !is_vec => { + let (mut value, meta) = args[0]; + ctx.implicit_conversion(self, &mut value, meta, kind)?; + + ctx.add_expression(Expression::Splat { size, value }, body) + } TypeInner::Scalar { kind, width } => ctx.add_expression( Expression::As { kind, @@ -74,21 +73,18 @@ impl Program<'_> { // `Expression::As` doesn't support matrix width // casts so we need to do some extra work for casts + let (mut value, meta) = args[0]; + ctx.implicit_conversion(self, &mut value, meta, ScalarKind::Float)?; let column = match *self.resolve_type(ctx, args[0].0, args[0].1)? { - TypeInner::Scalar { .. } => ctx.add_expression( - Expression::Splat { - size: rows, - value: args[0].0, - }, - body, - ), + TypeInner::Scalar { .. } => ctx + .add_expression(Expression::Splat { size: rows, value }, body), TypeInner::Matrix { .. } => { let mut components = Vec::new(); for n in 0..columns as u32 { let vector = ctx.add_expression( Expression::AccessIndex { - base: args[0].0, + base: value, index: n, }, body, @@ -118,7 +114,7 @@ impl Program<'_> { return Ok(Some(h)); } - _ => args[0].0, + _ => value, }; let columns = @@ -135,13 +131,16 @@ impl Program<'_> { _ => return Err(ErrorKind::SemanticError(meta, "Bad cast".into())), } } else { - ctx.add_expression( - Expression::Compose { - ty, - components: args.iter().map(|e| e.0).collect(), - }, - body, - ) + let mut components = Vec::with_capacity(args.len()); + + for (mut arg, meta) in args.iter().copied() { + if let Some(kind) = self.module.types[ty].inner.scalar_kind() { + ctx.implicit_conversion(self, &mut arg, meta, kind)?; + } + components.push(arg) + } + + ctx.add_expression(Expression::Compose { ty, components }, body) }; Ok(Some(h)) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index cd7370631..b995ea5d6 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1200,6 +1200,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { None } _ => { + // TODO: Implicit conversions let expr = self.parse_expression(ctx, body)?; self.expect(TokenValue::Semicolon)?; Some(ctx.lower_expect(self.program, expr, false, body)?.0) @@ -1247,6 +1248,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.bump()?; self.expect(TokenValue::LeftParen)?; + // TODO: Implicit conversions let selector = { let expr = self.parse_expression(ctx, body)?; ctx.lower_expect(self.program, expr, false, body)?.0 From 589f02fad463d517067cac14782c5a7dc70f65dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 29 May 2021 18:09:07 +0100 Subject: [PATCH 0905/2212] [glsl-in] Add implicit conversions tests --- src/front/glsl/parser_tests.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index fda018388..5a4374a2c 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -449,3 +449,22 @@ fn constants() { assert!(constants.next().is_none()); } + +#[test] +fn implicit_conversions() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Vertex); + + parse_program( + r#" + # version 450 + void main() { + mat4 a = mat4(1); + float b = 1u; + float c = 1 + 2.0; + } + "#, + &entry_points, + ) + .unwrap(); +} From 37724102a38927ad91154c16b6c3dde576221b29 Mon Sep 17 00:00:00 2001 From: Aron Granberg Date: Tue, 25 May 2021 16:58:17 +0200 Subject: [PATCH 0906/2212] Improve wgsl lexer error messages. Better errors for Unexpected, BadInteger, BadFloat, BadTexture, BadTypeCast, UnknownScalarType, UnknownStorageClass, UnknownAttribute, UnknownBuiltin, UnknownShaderStage, UnknownStorageFormat and UnknownConservativeDepth, ZeroStride, ZeroSizeOrAlign and UnknownType. Also adds lexer::capture_span. Also fixes some validation for texture sample types and and issue that cauld cause e.g. the type `f33` to be parsed as `f32`. --- src/front/wgsl/conv.rs | 33 +- src/front/wgsl/lexer.rs | 94 ++++-- src/front/wgsl/mod.rs | 716 ++++++++++++++++++++++++++++++++-------- tests/wgsl-errors.rs | 18 +- 4 files changed, 683 insertions(+), 178 deletions(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 9259a53ce..deb9643df 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -1,17 +1,17 @@ -use super::Error; +use super::{Error, Span}; -pub fn map_storage_class(word: &str) -> Result> { +pub fn map_storage_class(word: &str, span: Span) -> Result> { match word { "private" => Ok(crate::StorageClass::Private), "workgroup" => Ok(crate::StorageClass::WorkGroup), "uniform" => Ok(crate::StorageClass::Uniform), "storage" => Ok(crate::StorageClass::Storage), "push_constant" => Ok(crate::StorageClass::PushConstant), - _ => Err(Error::UnknownStorageClass(word)), + _ => Err(Error::UnknownStorageClass(span)), } } -pub fn map_built_in(word: &str) -> Result> { +pub fn map_built_in(word: &str, span: Span) -> Result> { Ok(match word { "position" => crate::BuiltIn::Position, // vertex @@ -28,37 +28,37 @@ pub fn map_built_in(word: &str) -> Result> { "local_invocation_index" => crate::BuiltIn::LocalInvocationIndex, "workgroup_id" => crate::BuiltIn::WorkGroupId, "workgroup_size" => crate::BuiltIn::WorkGroupSize, - _ => return Err(Error::UnknownBuiltin(word)), + _ => return Err(Error::UnknownBuiltin(span)), }) } -pub fn map_shader_stage(word: &str) -> Result> { +pub fn map_shader_stage(word: &str, span: Span) -> Result> { match word { "vertex" => Ok(crate::ShaderStage::Vertex), "fragment" => Ok(crate::ShaderStage::Fragment), "compute" => Ok(crate::ShaderStage::Compute), - _ => Err(Error::UnknownShaderStage(word)), + _ => Err(Error::UnknownShaderStage(span)), } } -pub fn map_interpolation(word: &str) -> Result> { +pub fn map_interpolation(word: &str, span: Span) -> Result> { match word { "linear" => Ok(crate::Interpolation::Linear), "flat" => Ok(crate::Interpolation::Flat), "perspective" => Ok(crate::Interpolation::Perspective), - _ => Err(Error::UnknownAttribute(word)), + _ => Err(Error::UnknownAttribute(span)), } } -pub fn map_sampling(word: &str) -> Result> { +pub fn map_sampling(word: &str, span: Span) -> Result> { match word { "centroid" => Ok(crate::Sampling::Centroid), "sample" => Ok(crate::Sampling::Sample), - _ => Err(Error::UnknownAttribute(word)), + _ => Err(Error::UnknownAttribute(span)), } } -pub fn map_storage_format(word: &str) -> Result> { +pub fn map_storage_format(word: &str, span: Span) -> Result> { use crate::StorageFormat as Sf; Ok(match word { "r8unorm" => Sf::R8Unorm, @@ -93,7 +93,7 @@ pub fn map_storage_format(word: &str) -> Result> "rgba32uint" => Sf::Rgba32Uint, "rgba32sint" => Sf::Rgba32Sint, "rgba32float" => Sf::Rgba32Float, - _ => return Err(Error::UnknownStorageFormat(word)), + _ => return Err(Error::UnknownStorageFormat(span)), }) } @@ -196,12 +196,15 @@ pub fn map_standard_fun(word: &str) -> Option { }) } -pub fn map_conservative_depth(word: &str) -> Result> { +pub fn map_conservative_depth( + word: &str, + span: Span, +) -> Result> { use crate::ConservativeDepth as Cd; match word { "greater_equal" => Ok(Cd::GreaterEqual), "less_equal" => Ok(Cd::LessEqual), "unchanged" => Ok(Cd::Unchanged), - _ => Err(Error::UnknownConservativeDepth(word)), + _ => Err(Error::UnknownConservativeDepth(span)), } } diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index a6a5eead3..b7b34d231 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -1,4 +1,4 @@ -use super::{conv, Error, Span, Token, TokenSpan}; +use super::{conv, Error, ExpectedToken, Span, Token, TokenSpan}; fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { if input.starts_with(what) { @@ -171,6 +171,25 @@ impl<'a> Lexer<'a> { self.source.len() - self.input.len()..self.source.len() } + /// Calls the function with a lexer and returns the result of the function as well as the span for everything the function parsed + /// + /// # Examples + /// ```ignore + /// let lexer = Lexer::new("5"); + /// let (value, span) = lexer.capture_span(Lexer::next_uint_literal); + /// assert_eq!(value, 5); + /// ``` + #[inline] + pub fn capture_span( + &mut self, + inner: impl FnOnce(&mut Self) -> Result, + ) -> Result<(T, Span), E> { + let start = self.current_byte_offset(); + let res = inner(self)?; + let end = self.current_byte_offset(); + Ok((res, start..end)) + } + fn peek_token_and_rest(&mut self) -> (TokenSpan<'a>, &'a str) { let mut cloned = self.clone(); let token = cloned.next(); @@ -219,24 +238,7 @@ impl<'a> Lexer<'a> { if next.0 == expected { Ok(()) } else { - let description = match expected { - Token::Separator(_) => "separator", - Token::DoubleColon => "::", - Token::Paren(_) => "paren", - Token::DoubleParen(_) => "double paren", - Token::Number { .. } => "number", - Token::String(string) => string, - Token::Word(word) => word, - Token::Operation(_) => "operation", - Token::LogicalOperation(_) => "logical op", - Token::ShiftOperation(_) => "shift op", - Token::Arrow => "->", - Token::Unknown(_) => "unknown", - Token::UnterminatedString => "string", - Token::Trivia => "trivia", - Token::End => "", - }; - Err(Error::Unexpected(next, description)) + Err(Error::Unexpected(next, ExpectedToken::Token(expected))) } } @@ -245,10 +247,14 @@ impl<'a> Lexer<'a> { if next.0 == Token::Paren(expected) { Ok(()) } else { - Err(Error::Unexpected(next, "paren")) + Err(Error::Unexpected( + next, + ExpectedToken::Token(Token::Paren(expected)), + )) } } + /// If the next token matches it is skipped and true is returned pub(super) fn skip(&mut self, what: Token<'_>) -> bool { let (peeked_token, rest) = self.peek_token_and_rest(); if peeked_token.0 == what { @@ -262,55 +268,81 @@ impl<'a> Lexer<'a> { pub(super) fn next_ident_with_span(&mut self) -> Result<(&'a str, Span), Error<'a>> { match self.next() { (Token::Word(word), span) => Ok((word, span)), - other => Err(Error::Unexpected(other, "identifier")), + other => Err(Error::Unexpected(other, ExpectedToken::Identifier)), } } pub(super) fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { match self.next() { (Token::Word(word), _) => Ok(word), - other => Err(Error::Unexpected(other, "identifier")), + other => Err(Error::Unexpected(other, ExpectedToken::Identifier)), } } fn _next_float_literal(&mut self) -> Result> { match self.next() { - (Token::Number { value, .. }, span) => value.parse().map_err(|_| Error::BadFloat(span)), - other => Err(Error::Unexpected(other, "floating-point literal")), + (Token::Number { value, .. }, span) => { + value.parse().map_err(|e| Error::BadFloat(span, e)) + } + other => Err(Error::Unexpected(other, ExpectedToken::Float)), } } pub(super) fn next_uint_literal(&mut self) -> Result> { match self.next() { (Token::Number { value, .. }, span) => { - value.parse().map_err(|_| Error::BadInteger(span)) + let v = value.parse(); + v.map_err(|e| Error::BadU32(span, e)) } - other => Err(Error::Unexpected(other, "unsigned integer literal")), + other => Err(Error::Unexpected(other, ExpectedToken::Uint)), } } pub(super) fn next_sint_literal(&mut self) -> Result> { match self.next() { (Token::Number { value, .. }, span) => { - value.parse().map_err(|_| Error::BadInteger(span)) + value.parse().map_err(|e| Error::BadI32(span, e)) } - other => Err(Error::Unexpected(other, "signed integer literal")), + other => Err(Error::Unexpected(other, ExpectedToken::Sint)), } } + /// Parses a generic scalar type, for example ``. pub(super) fn next_scalar_generic( &mut self, ) -> Result<(crate::ScalarKind, crate::Bytes), Error<'a>> { self.expect_generic_paren('<')?; - let word = self.next_ident()?; - let pair = conv::get_scalar_type(word).ok_or(Error::UnknownScalarType(word))?; + let pair = match self.next() { + (Token::Word(word), span) => { + conv::get_scalar_type(word).ok_or(Error::UnknownScalarType(span)) + } + (_, span) => Err(Error::UnknownScalarType(span)), + }?; + self.expect_generic_paren('>')?; + Ok(pair) + } + + /// Parses a generic scalar type, for example ``. + /// + /// Returns the span covering the inner type, excluding the brackets. + pub(super) fn next_scalar_generic_with_span( + &mut self, + ) -> Result<(crate::ScalarKind, crate::Bytes, Span), Error<'a>> { + self.expect_generic_paren('<')?; + let pair = match self.next() { + (Token::Word(word), span) => conv::get_scalar_type(word) + .map(|(a, b)| (a, b, span.clone())) + .ok_or(Error::UnknownScalarType(span)), + (_, span) => Err(Error::UnknownScalarType(span)), + }?; self.expect_generic_paren('>')?; Ok(pair) } pub(super) fn next_format_generic(&mut self) -> Result> { self.expect(Token::Paren('<'))?; - let format = conv::map_storage_format(self.next_ident()?)?; + let (ident, ident_span) = self.next_ident_with_span()?; + let format = conv::map_storage_format(ident, ident_span)?; self.expect(Token::Paren('>'))?; Ok(format) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 45e19cead..cc522b41f 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -28,7 +28,7 @@ use std::{ borrow::Cow, io::{self, Write}, iter, - num::NonZeroU32, + num::{NonZeroU32, ParseFloatError, ParseIntError}, ops, }; use thiserror::Error; @@ -59,60 +59,100 @@ pub enum Token<'a> { End, } +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum ExpectedToken<'a> { + Token(Token<'a>), + Identifier, + Float, + Uint, + Sint, + Constant, + /// Expected: constant, parenthesized expression, identifier + PrimaryExpression, + /// Expected: ']]', ',' + AttributeSeparator, + /// Expected: '}', identifier + FieldName, + /// Expected: ']]', 'access', 'stride' + TypeAttribute, + /// Expected: ';', '{', word + Statement, + /// Expected: 'case', 'default', '}' + SwitchItem, + /// Expected: ',', ')' + WorkgroupSizeSeparator, + /// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof + GlobalItem, + /// Expected: ']]', 'size', 'align' + StructAttribute, +} + #[derive(Clone, Debug, Error)] pub enum Error<'a> { #[error("")] - Unexpected(TokenSpan<'a>, &'a str), + Unexpected(TokenSpan<'a>, ExpectedToken<'a>), #[error("")] - BadInteger(Span), + BadU32(Span, ParseIntError), #[error("")] - BadFloat(Span), + BadI32(Span, ParseIntError), + #[error("")] + BadFloat(Span, ParseFloatError), #[error("")] BadScalarWidth(Span, &'a str), #[error("")] BadAccessor(Span), - #[error("bad texture {0}`")] - BadTexture(&'a str), + #[error("bad texture`")] + BadTexture(Span), #[error("bad texture coordinate")] BadCoordinate, - #[error("invalid type cast to `{0}`")] - BadTypeCast(&'a str), + #[error("invalid type cast")] + BadTypeCast { + span: Span, + from_type: String, + to_type: String, + }, + #[error("bad texture sample type. Only f32, i32 and u32 are valid")] + BadTextureSampleType { + span: Span, + kind: crate::ScalarKind, + width: u8, + }, #[error(transparent)] InvalidResolve(ResolveError), #[error("for(;;) initializer is not an assignment or a function call")] - InvalidForInitializer, + InvalidForInitializer(Span), #[error("resource type {0:?} is invalid")] InvalidResourceType(Handle), #[error("unknown import: `{0}`")] UnknownImport(&'a str), - #[error("unknown storage class: `{0}`")] - UnknownStorageClass(&'a str), - #[error("unknown attribute: `{0}`")] - UnknownAttribute(&'a str), + #[error("unknown storage class")] + UnknownStorageClass(Span), + #[error("unknown attribute")] + UnknownAttribute(Span), #[error("unknown scalar kind: `{0}`")] UnknownScalarKind(&'a str), - #[error("unknown builtin: `{0}`")] - UnknownBuiltin(&'a str), + #[error("unknown builtin")] + UnknownBuiltin(Span), #[error("unknown access: `{0}`")] UnknownAccess(&'a str), - #[error("unknown shader stage: `{0}`")] - UnknownShaderStage(&'a str), + #[error("unknown shader stage")] + UnknownShaderStage(Span), #[error("unknown identifier: `{1}`")] UnknownIdent(Span, &'a str), - #[error("unknown scalar type: `{0}`")] - UnknownScalarType(&'a str), - #[error("unknown type: `{0}`")] - UnknownType(&'a str), + #[error("unknown scalar type")] + UnknownScalarType(Span), + #[error("unknown type")] + UnknownType(Span), #[error("unknown function: `{0}`")] UnknownFunction(&'a str), - #[error("unknown storage format: `{0}`")] - UnknownStorageFormat(&'a str), - #[error("unknown conservative depth: `{0}`")] - UnknownConservativeDepth(&'a str), + #[error("unknown storage format")] + UnknownStorageFormat(Span), + #[error("unknown conservative depth")] + UnknownConservativeDepth(Span), #[error("array stride must not be 0")] - ZeroStride, - #[error("struct member size or array must not be 0")] - ZeroSizeOrAlign, + ZeroStride(Span), + #[error("struct member size or alignment must not be 0")] + ZeroSizeOrAlign(Span), #[error("not a composite type: {0:?}")] NotCompositeType(Handle), #[error("Input/output binding is not consistent: location {0:?}, built-in {1:?}, interpolation {2:?}, and sampling {3:?}")] @@ -135,38 +175,85 @@ pub enum Error<'a> { impl<'a> Error<'a> { fn as_parse_error(&self, source: &'a str) -> ParseError { match *self { - Error::Unexpected((_, ref unexpected_span), expected) => ParseError { - message: format!( - "expected {}, found '{}'", - expected, - &source[unexpected_span.clone()], - ), - labels: vec![( - unexpected_span.clone(), - format!("expected {}", expected).into(), - )], - notes: vec![], + Error::Unexpected((_, ref unexpected_span), expected) => { + let expected_str = match expected { + ExpectedToken::Token(token) => { + match token { + Token::Separator(c) => format!("'{}'", c), + Token::DoubleColon => "'::'".to_string(), + Token::Paren(c) => format!("'{}'", c), + Token::DoubleParen(c) => format!("'{}{}'", c, c), + Token::Number { value, .. } => { + format!("number ({})", value) + } + Token::String(s) => format!("string literal ('{}')", s.to_string()), + Token::Word(s) => s.to_string(), + Token::Operation(c) => format!("operation ('{}')", c), + Token::LogicalOperation(c) => format!("logical operation ('{}')", c), + Token::ShiftOperation(c) => format!("bitshift ('{}{}')", c, c), + Token::Arrow => "->".to_string(), + Token::Unknown(c) => format!("unkown ('{}')", c), + Token::UnterminatedString => "unterminated string".to_string(), + Token::Trivia => "trivia".to_string(), + Token::End => "end".to_string(), + } + } + ExpectedToken::Identifier => "identifier".to_string(), + ExpectedToken::Float => "floating point literal".to_string(), + ExpectedToken::Uint => "non-negative integer literal".to_string(), + ExpectedToken::Sint => "integer literal".to_string(), + ExpectedToken::Constant => "constant".to_string(), + ExpectedToken::PrimaryExpression => "expression".to_string(), + ExpectedToken::AttributeSeparator => "attribute separator (',') or an end of the attribute list (']]')".to_string(), + ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(), + ExpectedToken::TypeAttribute => "type attribute ('access' or 'stride') or and of the attribute list (']]')".to_string(), + ExpectedToken::Statement => "statement".to_string(), + ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), + ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), + ExpectedToken::GlobalItem => "global item ('struct', 'let', 'var', 'type', ';', 'fn') or the end of the file".to_string(), + ExpectedToken::StructAttribute => "struct attribute ('size' or 'align') or an end of the attribute list (']]')".to_string(), + }; + ParseError { + message: format!( + "expected {}, found '{}'", + expected_str, + &source[unexpected_span.clone()], + ), + labels: vec![( + unexpected_span.clone(), + format!("expected {}", expected_str).into(), + )], + notes: vec![], + } }, - Error::BadInteger(ref bad_span) => ParseError { + Error::BadU32(ref bad_span, ref err) => ParseError { + message: format!( + "expected non-negative integer literal, found `{}`", + &source[bad_span.clone()], + ), + labels: vec![(bad_span.clone(), "expected positive integer".into())], + notes: vec![err.to_string()], + }, + Error::BadI32(ref bad_span, ref err) => ParseError { message: format!( "expected integer literal, found `{}`", &source[bad_span.clone()], ), labels: vec![(bad_span.clone(), "expected integer".into())], - notes: vec![], + notes: vec![err.to_string()], }, - Error::BadFloat(ref bad_span) => ParseError { + Error::BadFloat(ref bad_span, ref err) => ParseError { message: format!( "expected floating-point literal, found `{}`", &source[bad_span.clone()], ), labels: vec![(bad_span.clone(), "expected floating-point literal".into())], - notes: vec![], + notes: vec![err.to_string()], }, Error::BadScalarWidth(ref bad_span, width) => ParseError { message: format!("invalid width of `{}` for literal", width,), labels: vec![(bad_span.clone(), "invalid width".into())], - notes: vec!["valid width is 32".to_string()], + notes: vec!["valid widths are 8, 16, 32, 64".to_string()], }, Error::BadAccessor(ref accessor_span) => ParseError { message: format!( @@ -181,6 +268,80 @@ impl<'a> Error<'a> { labels: vec![(ident_span.clone(), "unknown identifier".into())], notes: vec![], }, + Error::UnknownScalarType(ref bad_span) => ParseError { + message: format!("unknown scalar type: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown scalar type".into())], + notes: vec!["Valid scalar types are f16, f32, f64, i8, i16, i32, i64, u8, u16, u32, u64, bool".into()], + }, + Error::BadTextureSampleType { ref span, kind, width } => ParseError { + message: format!("texture sample type must be one of f32, i32 or u32, but found {}", kind.to_wgsl(width)), + labels: vec![(span.clone(), "must be one of f32, i32 or u32".into())], + notes: vec![], + }, + Error::BadTexture(ref bad_span) => ParseError { + message: format!("expected an image, but found '{}' which is not an image", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "not an image".into())], + notes: vec![], + }, + Error::BadTypeCast { ref span, ref from_type, ref to_type } => { + let msg = format!("cannot cast a {} to a {}", from_type, to_type); + ParseError { + message: msg.clone(), + labels: vec![(span.clone(), msg.into())], + notes: vec![], + } + }, + Error::InvalidForInitializer(ref bad_span) => ParseError { + message: format!("for(;;) initializer is not an assignment or a function call: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "not an assignment or function call".into())], + notes: vec![], + }, + Error::UnknownStorageClass(ref bad_span) => ParseError { + message: format!("unknown storage class: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown storage class".into())], + notes: vec![], + }, + Error::UnknownAttribute(ref bad_span) => ParseError { + message: format!("unknown attribute: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown attribute".into())], + notes: vec![], + }, + Error::UnknownBuiltin(ref bad_span) => ParseError { + message: format!("unknown builtin: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown builtin".into())], + notes: vec![], + }, + Error::UnknownShaderStage(ref bad_span) => ParseError { + message: format!("unknown shader stage: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown shader stage".into())], + notes: vec![], + }, + Error::UnknownStorageFormat(ref bad_span) => ParseError { + message: format!("unknown storage format: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown storage format".into())], + notes: vec![], + }, + Error::UnknownConservativeDepth(ref bad_span) => ParseError { + message: format!("unknown conservative depth: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown conservative depth".into())], + notes: vec![], + }, + Error::UnknownType(ref bad_span) => ParseError { + message: format!("unknown type: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown type".into())], + notes: vec![], + }, + Error::ZeroStride(ref bad_span) => ParseError { + message: "array stride must not be zero".to_string(), + labels: vec![(bad_span.clone(), "array stride must not be zero".into())], + notes: vec![], + }, + Error::ZeroSizeOrAlign(ref bad_span) => ParseError { + message: "struct member size or alignment must not be 0".to_string(), + labels: vec![(bad_span.clone(), "struct member size or alignment must not be 0".into())], + notes: vec![], + }, + ref error => ParseError { message: error.to_string(), labels: vec![], @@ -190,6 +351,228 @@ impl<'a> Error<'a> { } } +impl crate::StorageFormat { + pub fn to_wgsl(&self) -> &str { + use crate::StorageFormat as Sf; + match *self { + Sf::R8Unorm => "r8unorm", + Sf::R8Snorm => "r8snorm", + Sf::R8Uint => "r8uint", + Sf::R8Sint => "r8sint", + Sf::R16Uint => "r16uint", + Sf::R16Sint => "r16sint", + Sf::R16Float => "r16float", + Sf::Rg8Unorm => "rg8unorm", + Sf::Rg8Snorm => "rg8snorm", + Sf::Rg8Uint => "rg8uint", + Sf::Rg8Sint => "rg8sint", + Sf::R32Uint => "r32uint", + Sf::R32Sint => "r32sint", + Sf::R32Float => "r32float", + Sf::Rg16Uint => "rg16uint", + Sf::Rg16Sint => "rg16sint", + Sf::Rg16Float => "rg16float", + Sf::Rgba8Unorm => "rgba8unorm", + Sf::Rgba8Snorm => "rgba8snorm", + Sf::Rgba8Uint => "rgba8uint", + Sf::Rgba8Sint => "rgba8sint", + Sf::Rgb10a2Unorm => "rgb10a2unorm", + Sf::Rg11b10Float => "rg11b10float", + Sf::Rg32Uint => "rg32uint", + Sf::Rg32Sint => "rg32sint", + Sf::Rg32Float => "rg32float", + Sf::Rgba16Uint => "rgba16uint", + Sf::Rgba16Sint => "rgba16sint", + Sf::Rgba16Float => "rgba16float", + Sf::Rgba32Uint => "rgba32uint", + Sf::Rgba32Sint => "rgba32sint", + Sf::Rgba32Float => "rgba32float", + } + } +} + +impl crate::TypeInner { + /// Formats the type as it is written in wgsl. + /// + /// For example `vec3`. + /// + /// Note: The names of a `TypeInner::Struct` is not known. Therefore this method will simply return "struct" for them. + pub fn to_wgsl( + &self, + types: &Arena, + constants: &Arena, + ) -> String { + match *self { + crate::TypeInner::Scalar { kind, width } => kind.to_wgsl(width), + crate::TypeInner::Vector { size, kind, width } => { + format!("vec{}<{}>", size as u32, kind.to_wgsl(width)) + } + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + format!( + "mat{}x{}<{}>", + columns as u32, + rows as u32, + crate::ScalarKind::Float.to_wgsl(width), + ) + } + crate::TypeInner::Pointer { base, .. } => { + let base = &types[base]; + let name = base.name.as_deref().unwrap_or("unknown"); + format!("*{}", name) + } + crate::TypeInner::ValuePointer { kind, width, .. } => { + format!("*{}", kind.to_wgsl(width)) + } + crate::TypeInner::Array { base, size, .. } => { + let member_type = &types[base]; + let base = member_type.name.as_deref().unwrap_or("unknown"); + match size { + crate::ArraySize::Constant(size) => { + let size = constants[size].name.as_deref().unwrap_or("unknown"); + format!("{}[{}]", base, size) + } + crate::ArraySize::Dynamic => format!("{}[]", base), + } + } + crate::TypeInner::Struct { .. } => { + // TODO: Actually output the struct? + "struct".to_string() + } + crate::TypeInner::Image { + dim, + arrayed, + class, + } => { + let dim_suffix = match dim { + crate::ImageDimension::D1 => "_1d", + crate::ImageDimension::D2 => "_2d", + crate::ImageDimension::D3 => "_3d", + crate::ImageDimension::Cube => "_cube", + }; + let array_suffix = if arrayed { "_array" } else { "" }; + + let class_suffix = match class { + crate::ImageClass::Sampled { multi: true, .. } => "_multisampled", + crate::ImageClass::Depth => "_depth", + _ => "", + }; + + let type_in_brackets = match class { + crate::ImageClass::Sampled { kind, .. } => { + // Note: The only valid widths are 4 bytes wide. + // The lexer has already verified this, so we can safely assume it here. + // https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type + let element_type = kind.to_wgsl(4); + format!("<{}>", element_type) + } + crate::ImageClass::Depth => String::new(), + crate::ImageClass::Storage(format) => { + format!("<{}>", format.to_wgsl()) + } + }; + + format!( + "texture{}{}{}{}", + class_suffix, dim_suffix, array_suffix, type_in_brackets + ) + } + crate::TypeInner::Sampler { .. } => "sampler".to_string(), + } + } +} + +mod type_inner_tests { + #[test] + fn to_wgsl() { + let mut types = crate::Arena::new(); + let mut constants = crate::Arena::new(); + let c = constants.append(crate::Constant { + name: Some("C".to_string()), + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(32), + }, + }); + + let mytype1 = types.append(crate::Type { + name: Some("MyType1".to_string()), + inner: crate::TypeInner::Struct { + top_level: true, + members: vec![], + span: 0, + }, + }); + let mytype2 = types.append(crate::Type { + name: Some("MyType2".to_string()), + inner: crate::TypeInner::Struct { + top_level: true, + members: vec![], + span: 0, + }, + }); + + let array = crate::TypeInner::Array { + base: mytype1, + stride: 4, + size: crate::ArraySize::Constant(c), + }; + assert_eq!(array.to_wgsl(&types, &constants), "MyType1[C]"); + + let mat = crate::TypeInner::Matrix { + rows: crate::VectorSize::Quad, + columns: crate::VectorSize::Bi, + width: 8, + }; + assert_eq!(mat.to_wgsl(&types, &constants), "mat2x4"); + + let ptr = crate::TypeInner::Pointer { + base: mytype2, + class: crate::StorageClass::Storage, + }; + assert_eq!(ptr.to_wgsl(&types, &constants), "*MyType2"); + + let img1 = crate::TypeInner::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Sampled { + kind: crate::ScalarKind::Float, + multi: true, + }, + }; + assert_eq!( + img1.to_wgsl(&types, &constants), + "texture_multisampled_2d" + ); + + let img2 = crate::TypeInner::Image { + dim: crate::ImageDimension::Cube, + arrayed: true, + class: crate::ImageClass::Depth, + }; + assert_eq!(img2.to_wgsl(&types, &constants), "texture_depth_cube_array"); + } +} + +impl crate::ScalarKind { + /// Format a scalar kind+width as a type is written in wgsl. + /// + /// Examples: `f32`, `u64`, `bool`. + fn to_wgsl(&self, width: u8) -> String { + let prefix = match *self { + crate::ScalarKind::Sint => "i", + crate::ScalarKind::Uint => "u", + crate::ScalarKind::Float => "f", + crate::ScalarKind::Bool => return "bool".to_string(), + }; + format!("{}{}", prefix, width * 8) + } +} + trait StringValueLookup<'a> { type Value; fn lookup(&self, key: &'a str, span: Span) -> Result>; @@ -311,12 +694,12 @@ impl<'a> ExpressionContext<'a, '_, '_> { image_name: &'a str, span: Span, ) -> Result> { - let image = self.lookup_ident.lookup(image_name, span)?; + let image = self.lookup_ident.lookup(image_name, span.clone())?; Ok(SamplingContext { image, arrayed: match *self.resolve_type(image)? { crate::TypeInner::Image { arrayed, .. } => arrayed, - _ => return Err(Error::BadTexture(image_name)), + _ => return Err(Error::BadTexture(span)), }, }) } @@ -473,7 +856,12 @@ struct BindingParser { } impl BindingParser { - fn parse<'a>(&mut self, lexer: &mut Lexer<'a>, name: &'a str) -> Result<(), Error<'a>> { + fn parse<'a>( + &mut self, + lexer: &mut Lexer<'a>, + name: &'a str, + name_span: Span, + ) -> Result<(), Error<'a>> { match name { "location" => { lexer.expect(Token::Paren('('))?; @@ -482,21 +870,21 @@ impl BindingParser { } "builtin" => { lexer.expect(Token::Paren('('))?; - let raw = lexer.next_ident()?; - self.built_in = Some(conv::map_built_in(raw)?); + let (raw, span) = lexer.next_ident_with_span()?; + self.built_in = Some(conv::map_built_in(raw, span)?); lexer.expect(Token::Paren(')'))?; } "interpolate" => { lexer.expect(Token::Paren('('))?; - let raw = lexer.next_ident()?; - self.interpolation = Some(conv::map_interpolation(raw)?); + let (raw, span) = lexer.next_ident_with_span()?; + self.interpolation = Some(conv::map_interpolation(raw, span)?); if lexer.skip(Token::Separator(',')) { - let raw = lexer.next_ident()?; - self.sampling = Some(conv::map_sampling(raw)?); + let (raw, span) = lexer.next_ident_with_span()?; + self.sampling = Some(conv::map_sampling(raw, span)?); } lexer.expect(Token::Paren(')'))?; } - _ => return Err(Error::UnknownAttribute(name)), + _ => return Err(Error::UnknownAttribute(name_span)), } Ok(()) } @@ -639,15 +1027,15 @@ impl Parser { 'i' => word .parse() .map(crate::ScalarValue::Sint) - .map_err(|_| Error::BadInteger(span.clone()))?, + .map_err(|e| Error::BadI32(span.clone(), e))?, 'u' => word .parse() .map(crate::ScalarValue::Uint) - .map_err(|_| Error::BadInteger(span.clone()))?, + .map_err(|e| Error::BadU32(span.clone(), e))?, 'f' => word .parse() .map(crate::ScalarValue::Float) - .map_err(|_| Error::BadFloat(span.clone()))?, + .map_err(|e| Error::BadFloat(span.clone(), e))?, _ => unreachable!(), }; Ok(crate::ConstantInner::Scalar { @@ -656,9 +1044,9 @@ impl Parser { 4 } else { match width.parse::() { - Ok(bits) => bits / 8, - Err(_) => return Err(Error::BadScalarWidth(span, width)), - } + Ok(bits) if (bits % 8) == 0 => Ok(bits / 8), + _ => Err(Error::BadScalarWidth(span, width)), + }? }, }) } @@ -946,12 +1334,12 @@ impl Parser { "textureLoad" => { lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span)?; + let image = ctx.lookup_ident.lookup(image_name, image_span.clone())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let (class, arrayed) = match *ctx.resolve_type(image)? { crate::TypeInner::Image { class, arrayed, .. } => (class, arrayed), - _ => return Err(Error::BadTexture(image_name)), + _ => return Err(Error::BadTexture(image_span)), }; let array_index = if arrayed { lexer.expect(Token::Separator(','))?; @@ -1067,13 +1455,18 @@ impl Parser { }, }; - lexer.open_arguments()?; let mut components = Vec::new(); - let mut last_component = self.parse_general_expression(lexer, ctx.reborrow())?; - while lexer.next_argument()? { - components.push(last_component); - last_component = self.parse_general_expression(lexer, ctx.reborrow())?; - } + let (last_component, arguments_span) = lexer.capture_span(|lexer| { + lexer.open_arguments()?; + let mut last_component = self.parse_general_expression(lexer, ctx.reborrow())?; + + while lexer.next_argument()? { + components.push(last_component); + last_component = self.parse_general_expression(lexer, ctx.reborrow())?; + } + + Ok(last_component) + })?; let expr = if components.is_empty() && ty_resolution.inner_with(ctx.types).scalar_kind().is_some() @@ -1083,6 +1476,7 @@ impl Parser { // Use it to insert into the right maps, // and then grab it again immutably. ctx.resolve_type(last_component)?; + match ( ty_resolution.inner_with(ctx.types), ctx.typifier.get(last_component, ctx.types), @@ -1112,8 +1506,12 @@ impl Parser { convert: Some(width), } } - _ => { - return Err(Error::BadTypeCast(type_name)); + (to_type, from_type) => { + return Err(Error::BadTypeCast { + span: arguments_span, + from_type: from_type.to_wgsl(&ctx.types, &ctx.constants), + to_type: to_type.to_wgsl(&ctx.types, &ctx.constants), + }); } } } else { @@ -1150,7 +1548,7 @@ impl Parser { }, _, ) => Self::get_constant_inner(*value, *ty, *width, first_token_span)?, - (Token::Word(name), _) => { + (Token::Word(name), name_span) => { // look for an existing constant first for (handle, var) in const_arena.iter() { match var.name { @@ -1164,6 +1562,7 @@ impl Parser { let composite_ty = self.parse_type_decl_name( lexer, name, + name_span, None, TypeAttributes::default(), type_arena, @@ -1182,7 +1581,7 @@ impl Parser { components, } } - other => return Err(Error::Unexpected(other, "constant")), + other => return Err(Error::Unexpected(other, ExpectedToken::Constant)), }; let handle = if let Some(name) = register_name { @@ -1251,7 +1650,7 @@ impl Parser { return Err(Error::UnknownIdent(span, word)); } } - other => return Err(Error::Unexpected(other, "primary expression")), + other => return Err(Error::Unexpected(other, ExpectedToken::PrimaryExpression)), }; self.scopes.pop(); Ok(handle) @@ -1577,8 +1976,8 @@ impl Parser { self.scopes.push(Scope::VariableDecl); let mut class = None; if lexer.skip(Token::Paren('<')) { - let class_str = lexer.next_ident()?; - class = Some(conv::map_storage_class(class_str)?); + let (class_str, span) = lexer.next_ident_with_span()?; + class = Some(conv::map_storage_class(class_str, span)?); lexer.expect(Token::Paren('>'))?; } let name = lexer.next_ident()?; @@ -1627,27 +2026,38 @@ impl Parser { (Token::Separator(','), _) if !ready => { ready = true; } - (Token::Word(word), _) if ready => { + (Token::Word(word), word_span) if ready => { match word { "size" => { lexer.expect(Token::Paren('('))?; - let value = lexer.next_uint_literal()?; + let (value, span) = + lexer.capture_span(Lexer::next_uint_literal)?; lexer.expect(Token::Paren(')'))?; - size = - Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign)?); + size = Some( + NonZeroU32::new(value) + .ok_or(Error::ZeroSizeOrAlign(span))?, + ); } "align" => { lexer.expect(Token::Paren('('))?; - let value = lexer.next_uint_literal()?; + let (value, span) = + lexer.capture_span(Lexer::next_uint_literal)?; lexer.expect(Token::Paren(')'))?; - align = - Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign)?); + align = Some( + NonZeroU32::new(value) + .ok_or(Error::ZeroSizeOrAlign(span))?, + ); } - _ => bind_parser.parse(lexer, word)?, + _ => bind_parser.parse(lexer, word, word_span)?, } ready = false; } - other => return Err(Error::Unexpected(other, "attribute separator")), + other if ready => { + return Err(Error::Unexpected(other, ExpectedToken::StructAttribute)) + } + other => { + return Err(Error::Unexpected(other, ExpectedToken::AttributeSeparator)) + } } } self.scopes.pop(); @@ -1659,7 +2069,7 @@ impl Parser { let span = Layouter::round_up(alignment, offset); return Ok((members, span)); } - other => return Err(Error::Unexpected(other, "field name")), + other => return Err(Error::Unexpected(other, ExpectedToken::FieldName)), }; lexer.expect(Token::Separator(':'))?; let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; @@ -1790,7 +2200,8 @@ impl Parser { } "ptr" => { lexer.expect_generic_paren('<')?; - let class = conv::map_storage_class(lexer.next_ident()?)?; + let (ident, span) = lexer.next_ident_with_span()?; + let class = conv::map_storage_class(ident, span)?; lexer.expect(Token::Separator(','))?; let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect_generic_paren('>')?; @@ -1817,7 +2228,8 @@ impl Parser { "sampler" => crate::TypeInner::Sampler { comparison: false }, "sampler_comparison" => crate::TypeInner::Sampler { comparison: true }, "texture_1d" => { - let (kind, _) = lexer.next_scalar_generic()?; + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, arrayed: false, @@ -1825,7 +2237,8 @@ impl Parser { } } "texture_1d_array" => { - let (kind, _) = lexer.next_scalar_generic()?; + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, arrayed: true, @@ -1833,7 +2246,8 @@ impl Parser { } } "texture_2d" => { - let (kind, _) = lexer.next_scalar_generic()?; + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: false, @@ -1841,7 +2255,8 @@ impl Parser { } } "texture_2d_array" => { - let (kind, _) = lexer.next_scalar_generic()?; + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: true, @@ -1849,7 +2264,8 @@ impl Parser { } } "texture_3d" => { - let (kind, _) = lexer.next_scalar_generic()?; + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; crate::TypeInner::Image { dim: crate::ImageDimension::D3, arrayed: false, @@ -1857,7 +2273,8 @@ impl Parser { } } "texture_cube" => { - let (kind, _) = lexer.next_scalar_generic()?; + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; crate::TypeInner::Image { dim: crate::ImageDimension::Cube, arrayed: false, @@ -1865,7 +2282,8 @@ impl Parser { } } "texture_cube_array" => { - let (kind, _) = lexer.next_scalar_generic()?; + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; crate::TypeInner::Image { dim: crate::ImageDimension::Cube, arrayed: true, @@ -1873,7 +2291,8 @@ impl Parser { } } "texture_multisampled_2d" => { - let (kind, _) = lexer.next_scalar_generic()?; + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: false, @@ -1881,7 +2300,8 @@ impl Parser { } } "texture_multisampled_2d_array" => { - let (kind, _) = lexer.next_scalar_generic()?; + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: true, @@ -1952,11 +2372,26 @@ impl Parser { })) } + fn check_texture_sample_type( + kind: crate::ScalarKind, + width: u8, + span: Span, + ) -> Result<(), Error<'static>> { + use crate::ScalarKind::*; + // Validate according to https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type + match (kind, width) { + (Float, 4) | (Sint, 4) | (Uint, 4) => Ok(()), + _ => Err(Error::BadTextureSampleType { span, kind, width }), + } + } + /// Parse type declaration of a given name and attribute. + #[allow(clippy::too_many_arguments)] fn parse_type_decl_name<'a>( &mut self, lexer: &mut Lexer<'a>, name: &'a str, + name_span: Span, debug_name: Option<&'a str>, attribute: TypeAttributes, type_arena: &mut Arena, @@ -1970,7 +2405,7 @@ impl Parser { name: debug_name.map(|s| s.to_string()), inner, }), - None => return Err(Error::UnknownType(name)), + None => return Err(Error::UnknownType(name_span)), } } }) @@ -2002,22 +2437,29 @@ impl Parser { } (Token::Word("stride"), _) => { lexer.expect(Token::Paren('('))?; - attribute.stride = Some( - NonZeroU32::new(lexer.next_uint_literal()?).ok_or(Error::ZeroStride)?, - ); + let (stride, span) = lexer.capture_span(Lexer::next_uint_literal)?; + attribute.stride = + Some(NonZeroU32::new(stride).ok_or(Error::ZeroStride(span))?); lexer.expect(Token::Paren(')'))?; } (Token::DoubleParen(']'), _) => break, - other => return Err(Error::Unexpected(other, "type attribute")), + other => return Err(Error::Unexpected(other, ExpectedToken::TypeAttribute)), } } self.scopes.pop(); } let storage_access = attribute.access; - let name = lexer.next_ident()?; - let handle = - self.parse_type_decl_name(lexer, name, debug_name, attribute, type_arena, const_arena)?; + let (name, name_span) = lexer.next_ident_with_span()?; + let handle = self.parse_type_decl_name( + lexer, + name, + name_span, + debug_name, + attribute, + type_arena, + const_arena, + )?; self.scopes.pop(); Ok((handle, storage_access)) } @@ -2083,7 +2525,7 @@ impl Parser { return Ok(()); } (Token::Word(word), _) => word, - other => return Err(Error::Unexpected(other, "statement")), + other => return Err(Error::Unexpected(other, ExpectedToken::Statement)), }; self.scopes.push(Scope::Statement); @@ -2292,7 +2734,7 @@ impl Parser { default = self.parse_block(lexer, context.reborrow(), false)?; } (Token::Paren('}'), _) => break, - other => return Err(Error::Unexpected(other, "switch item")), + other => return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)), } } @@ -2325,16 +2767,19 @@ impl Parser { lexer.expect(Token::Paren('('))?; if !lexer.skip(Token::Separator(';')) { let num_statements = block.len(); - self.parse_statement( - lexer, - context.reborrow(), - block, - is_uniform_control_flow, - )?; + let (_, span) = lexer.capture_span(|lexer| { + self.parse_statement( + lexer, + context.reborrow(), + block, + is_uniform_control_flow, + ) + })?; + if block.len() != num_statements { match *block.last().unwrap() { crate::Statement::Store { .. } | crate::Statement::Call { .. } => {} - _ => return Err(Error::InvalidForInitializer), + _ => return Err(Error::InvalidForInitializer(span)), } } }; @@ -2392,12 +2837,14 @@ impl Parser { emitter.start(context.expressions); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = context.lookup_ident.lookup(image_name, image_span)?; + let image = context + .lookup_ident + .lookup(image_name, image_span.clone())?; lexer.expect(Token::Separator(','))?; let mut expr_context = context.as_expression(block, &mut emitter); let arrayed = match *expr_context.resolve_type(image)? { crate::TypeInner::Image { arrayed, .. } => arrayed, - _ => return Err(Error::BadTexture(image_name)), + _ => return Err(Error::BadTexture(image_span)), }; let coordinate = self.parse_general_expression(lexer, expr_context)?; let array_index = if arrayed { @@ -2467,14 +2914,14 @@ impl Parser { let mut bind_parser = BindingParser::default(); self.scopes.push(Scope::Attribute); loop { - let word = lexer.next_ident()?; - bind_parser.parse(lexer, word)?; + let (word, span) = lexer.next_ident_with_span()?; + bind_parser.parse(lexer, word, span)?; match lexer.next() { (Token::DoubleParen(']'), _) => { break; } (Token::Separator(','), _) => {} - other => return Err(Error::Unexpected(other, "attribute separator")), + other => return Err(Error::Unexpected(other, ExpectedToken::AttributeSeparator)), } } self.scopes.pop(); @@ -2503,7 +2950,10 @@ impl Parser { let mut ready = true; while !lexer.skip(Token::Paren(')')) { if !ready { - return Err(Error::Unexpected(lexer.next(), "comma")); + return Err(Error::Unexpected( + lexer.next(), + ExpectedToken::Token(Token::Separator(',')), + )); } let binding = self.parse_varying_binding(lexer)?; let (param_name, param_type, _access) = @@ -2581,26 +3031,27 @@ impl Parser { let (mut bind_index, mut bind_group) = (None, None); self.scopes.push(Scope::Attribute); loop { - match lexer.next_ident()? { - "binding" => { + match lexer.next_ident_with_span()? { + ("binding", _) => { lexer.expect(Token::Paren('('))?; bind_index = Some(lexer.next_uint_literal()?); lexer.expect(Token::Paren(')'))?; } - "block" => { + ("block", _) => { is_block = true; } - "group" => { + ("group", _) => { lexer.expect(Token::Paren('('))?; bind_group = Some(lexer.next_uint_literal()?); lexer.expect(Token::Paren(')'))?; } - "stage" => { + ("stage", _) => { lexer.expect(Token::Paren('('))?; - stage = Some(conv::map_shader_stage(lexer.next_ident()?)?); + let (ident, ident_span) = lexer.next_ident_with_span()?; + stage = Some(conv::map_shader_stage(ident, ident_span)?); lexer.expect(Token::Paren(')'))?; } - "workgroup_size" => { + ("workgroup_size", _) => { lexer.expect(Token::Paren('('))?; for (i, size) in workgroup_size.iter_mut().enumerate() { *size = lexer.next_uint_literal()?; @@ -2610,7 +3061,7 @@ impl Parser { other => { return Err(Error::Unexpected( other, - "workgroup size separator", + ExpectedToken::WorkgroupSizeSeparator, )) } } @@ -2621,9 +3072,10 @@ impl Parser { } } } - "early_depth_test" => { + ("early_depth_test", _) => { let conservative = if lexer.skip(Token::Paren('(')) { - let value = conv::map_conservative_depth(lexer.next_ident()?)?; + let (ident, ident_span) = lexer.next_ident_with_span()?; + let value = conv::map_conservative_depth(ident, ident_span)?; lexer.expect(Token::Paren(')'))?; Some(value) } else { @@ -2631,14 +3083,16 @@ impl Parser { }; early_depth_test = Some(crate::EarlyDepthTest { conservative }); } - word => return Err(Error::UnknownAttribute(word)), + (_, word_span) => return Err(Error::UnknownAttribute(word_span)), } match lexer.next() { (Token::DoubleParen(']'), _) => { break; } (Token::Separator(','), _) => {} - other => return Err(Error::Unexpected(other, "attribute separator")), + other => { + return Err(Error::Unexpected(other, ExpectedToken::AttributeSeparator)) + } } } if let (Some(group), Some(index)) = (bind_group, bind_index) { @@ -2763,7 +3217,7 @@ impl Parser { } } (Token::End, _) => return Ok(false), - other => return Err(Error::Unexpected(other, "global item")), + other => return Err(Error::Unexpected(other, ExpectedToken::GlobalItem)), } match binding { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 6c03ca7be..d11cef3f9 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -54,6 +54,8 @@ fn invalid_float() { │ 1 │ let scale: f32 = 1.1.; │ ^^^^ expected floating-point literal + │ + = note: invalid float literal "###, ); @@ -69,7 +71,21 @@ fn invalid_scalar_width() { 1 │ let scale: f32 = 1.1f1000; │ ^^^^^^^^ invalid width │ - = note: valid width is 32 + = note: valid widths are 8, 16, 32, 64 + +"###, + ); +} + +#[test] +fn invalid_texture_sample_type() { + check( + "let x: texture_2d;", + r###"error: texture sample type must be one of f32, i32 or u32, but found f16 + ┌─ wgsl:1:19 + │ +1 │ let x: texture_2d; + │ ^^^ must be one of f32, i32 or u32 "###, ); From 58e5b2565d98d553548b31fe3818e1178c17df9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fredrik=20Nore=CC=81n?= Date: Sun, 30 May 2021 10:12:29 +0200 Subject: [PATCH 0907/2212] Validate matrix component-wise ops correctly --- src/valid/expression.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index c87dedcc1..69d0d9b9d 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -576,7 +576,15 @@ impl super::Validator { let left_inner = resolver.resolve(left)?; let right_inner = resolver.resolve(right)?; let good = match op { - Bo::Add | Bo::Subtract | Bo::Divide | Bo::Modulo => match *left_inner { + Bo::Add | Bo::Subtract => match *left_inner { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { + Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner, + Sk::Bool => false, + }, + Ti::Matrix { .. } => left_inner == right_inner, + _ => false, + }, + Bo::Divide | Bo::Modulo => match *left_inner { Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner, Sk::Bool => false, From 61bfb29963fba9a7e8807bdd7ca1c5e5a8b76fec Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 31 May 2021 00:04:17 -0400 Subject: [PATCH 0908/2212] Don't consider discard and return inside uniform control flow --- src/valid/analyzer.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index ecae2232a..aae5dcdde 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -569,7 +569,11 @@ impl FunctionInfo { S::Break | S::Continue => FunctionUniformity::new(), S::Kill => FunctionUniformity { result: Uniformity::new(), - exit: ExitFlags::MAY_KILL, + exit: if disruptor.is_some() { + ExitFlags::MAY_KILL + } else { + ExitFlags::empty() + }, }, S::Barrier(_) => FunctionUniformity { result: Uniformity { @@ -633,8 +637,11 @@ impl FunctionInfo { non_uniform_result: value.and_then(|expr| self.add_ref(expr)), requirements: UniformityRequirements::empty(), }, - //TODO: if we are in the uniform control flow, should this still be an exit flag? - exit: ExitFlags::MAY_RETURN, + exit: if disruptor.is_some() { + ExitFlags::MAY_RETURN + } else { + ExitFlags::empty() + }, }, // Here and below, the used expressions are already emitted, // and their results do not affect the function return value, From 027634451de050adf786bb48340742e2c41bd362 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 1 Jun 2021 19:06:14 +0100 Subject: [PATCH 0909/2212] [glsl-in] Collect entry point arguments usage --- src/front/glsl/ast.rs | 42 ++++++++-- src/front/glsl/functions.rs | 148 ++++++++++++++++++++++-------------- src/front/glsl/parser.rs | 30 +++++--- src/front/glsl/variables.rs | 36 ++++++--- 4 files changed, 176 insertions(+), 80 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index a32edde14..491af32c6 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -12,11 +12,17 @@ use crate::{ }; #[derive(Debug, Clone, Copy)] -pub enum GlobalLookup { +pub enum GlobalLookupKind { Variable(Handle), BlockSelect(Handle, u32), } +#[derive(Debug, Clone, Copy)] +pub struct GlobalLookup { + pub kind: GlobalLookupKind, + pub entry_arg: Option, +} + #[derive(Debug, PartialEq, Eq, Hash)] pub struct FunctionSignature { pub name: String, @@ -33,6 +39,13 @@ pub struct FunctionDeclaration { pub void: bool, } +bitflags::bitflags! { + pub struct EntryArgUse: u32 { + const READ = 0x1; + const WRITE = 0x2; + } +} + #[derive(Debug)] pub struct Program<'a> { pub version: u16, @@ -45,8 +58,10 @@ pub struct Program<'a> { pub global_variables: Vec<(String, GlobalLookup)>, pub constants: Vec<(String, Handle)>, - pub entry_args: Vec<(Binding, bool, Handle)>, + pub entry_args: Vec<(Binding, Handle)>, pub entries: Vec<(String, ShaderStage, Handle)>, + // TODO: More efficient representation + pub function_arg_use: Vec>, pub module: Module, } @@ -65,6 +80,7 @@ impl<'a> Program<'a> { entry_args: Vec::new(), entries: Vec::new(), + function_arg_use: Vec::new(), module: Module::default(), } @@ -150,6 +166,7 @@ pub struct Context<'function> { expressions: &'function mut Arena, pub locals: &'function mut Arena, pub arguments: &'function mut Vec, + pub arg_use: Vec, //TODO: Find less allocation heavy representation pub scopes: Vec>, @@ -173,6 +190,7 @@ impl<'function> Context<'function> { expressions, locals, arguments, + arg_use: vec![EntryArgUse::empty(); program.entry_args.len()], scopes: vec![FastHashMap::default()], lookup_global_var_exps: FastHashMap::with_capacity_and_hasher( @@ -194,6 +212,7 @@ impl<'function> Context<'function> { expr, load: None, mutable: false, + entry_arg: None, }; this.lookup_global_var_exps.insert(name.into(), var); @@ -201,12 +220,13 @@ impl<'function> Context<'function> { for &(ref name, lookup) in program.global_variables.iter() { this.emit_flush(body); - let (expr, load) = match lookup { - GlobalLookup::Variable(v) => ( + let GlobalLookup { kind, entry_arg } = lookup; + let (expr, load) = match kind { + GlobalLookupKind::Variable(v) => ( Expression::GlobalVariable(v), program.module.global_variables[v].class != StorageClass::Handle, ), - GlobalLookup::BlockSelect(handle, index) => { + GlobalLookupKind::BlockSelect(handle, index) => { let base = this.expressions.append(Expression::GlobalVariable(handle)); (Expression::AccessIndex { base, index }, true) @@ -225,6 +245,7 @@ impl<'function> Context<'function> { }, // TODO: respect constant qualifier mutable: true, + entry_arg, }; this.lookup_global_var_exps.insert(name.into(), var); @@ -285,6 +306,7 @@ impl<'function> Context<'function> { expr, load: Some(load), mutable, + entry_arg: None, }, ); } @@ -336,6 +358,7 @@ impl<'function> Context<'function> { expr, load, mutable, + entry_arg: None, }, ); } @@ -455,8 +478,16 @@ impl<'function> Context<'function> { )); } + if let Some(idx) = var.entry_arg { + self.arg_use[idx] |= EntryArgUse::WRITE + } + var.expr } else { + if let Some(idx) = var.entry_arg { + self.arg_use[idx] |= EntryArgUse::READ + } + var.load.unwrap_or(var.expr) } } @@ -617,6 +648,7 @@ pub struct VariableReference { pub expr: Handle, pub load: Option>, pub mutable: bool, + pub entry_arg: Option, } #[derive(Debug, Clone)] diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index db6822de4..a70df7e50 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,8 +1,7 @@ use crate::{ - proc::ensure_block_returns, Arena, BinaryOperator, Binding, Block, BuiltIn, EntryPoint, - Expression, Function, FunctionArgument, FunctionResult, Handle, MathFunction, - RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, StructMember, - SwizzleComponent, Type, TypeInner, + proc::ensure_block_returns, Arena, BinaryOperator, Block, EntryPoint, Expression, Function, + FunctionArgument, FunctionResult, Handle, MathFunction, RelationalFunction, SampleLevel, + ScalarKind, Statement, StructMember, SwizzleComponent, Type, TypeInner, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; @@ -392,13 +391,15 @@ impl Program<'_> { sig: FunctionSignature, qualifiers: Vec, meta: SourceMetadata, - ) -> Result<(), ErrorKind> { + ) -> Result, ErrorKind> { ensure_block_returns(&mut function.body); let stage = self.entry_points.get(&sig.name); - if let Some(&stage) = stage { + Ok(if let Some(&stage) = stage { let handle = self.module.functions.append(function); self.entries.push((sig.name, stage, handle)); + self.function_arg_use.push(Vec::new()); + handle } else { let void = function.result.is_none(); @@ -412,7 +413,9 @@ impl Program<'_> { decl.defined = true; *self.module.functions.get_mut(decl.handle) = function; + decl.handle } else { + self.function_arg_use.push(Vec::new()); let handle = self.module.functions.append(function); self.lookup_function.insert( sig, @@ -423,10 +426,9 @@ impl Program<'_> { void, }, ); + handle } - } - - Ok(()) + }) } pub fn add_prototype( @@ -438,6 +440,7 @@ impl Program<'_> { ) -> Result<(), ErrorKind> { let void = function.result.is_none(); + self.function_arg_use.push(Vec::new()); let handle = self.module.functions.append(function); if self @@ -462,17 +465,86 @@ impl Program<'_> { Ok(()) } + fn check_call_global( + &self, + caller: Handle, + function_arg_use: &mut [Vec], + stmt: &Statement, + ) { + match *stmt { + Statement::Block(ref block) => { + for stmt in block { + self.check_call_global(caller, function_arg_use, stmt) + } + } + Statement::If { + ref accept, + ref reject, + .. + } => { + for stmt in accept.iter().chain(reject.iter()) { + self.check_call_global(caller, function_arg_use, stmt) + } + } + Statement::Switch { + ref cases, + ref default, + .. + } => { + for stmt in cases + .iter() + .flat_map(|c| c.body.iter()) + .chain(default.iter()) + { + self.check_call_global(caller, function_arg_use, stmt) + } + } + Statement::Loop { + ref body, + ref continuing, + } => { + for stmt in body.iter().chain(continuing.iter()) { + self.check_call_global(caller, function_arg_use, stmt) + } + } + Statement::Call { function, .. } => { + let callee_len = function_arg_use[function.index()].len(); + let caller_len = function_arg_use[caller.index()].len(); + function_arg_use[caller.index()].extend( + std::iter::repeat(EntryArgUse::empty()) + .take(callee_len.saturating_sub(caller_len)), + ); + + for i in 0..callee_len.max(caller_len) { + let callee_use = function_arg_use[function.index()][i]; + function_arg_use[caller.index()][i] |= callee_use + } + } + _ => {} + } + } + pub fn add_entry_points(&mut self) { + let mut function_arg_use = Vec::new(); + std::mem::swap(&mut self.function_arg_use, &mut function_arg_use); + + for (handle, function) in self.module.functions.iter() { + for stmt in function.body.iter() { + self.check_call_global(handle, &mut function_arg_use, stmt) + } + } + for (name, stage, function) in self.entries.iter().cloned() { let mut arguments = Vec::new(); let mut expressions = Arena::new(); let mut body = Vec::new(); - for (binding, input, handle) in self.entry_args.iter().cloned() { - match binding { - Binding::Location { .. } if !input => continue, - Binding::BuiltIn(builtin) if !should_read(builtin, stage) => continue, - _ => {} + for (i, (binding, handle)) in self.entry_args.iter().cloned().enumerate() { + if function_arg_use[function.index()] + .get(i) + .map_or(true, |u| !u.contains(EntryArgUse::READ)) + { + continue; } let ty = self.module.global_variables[handle].ty; @@ -500,11 +572,12 @@ impl Program<'_> { let mut members = Vec::new(); let mut components = Vec::new(); - for (binding, input, handle) in self.entry_args.iter().cloned() { - match binding { - Binding::Location { .. } if input => continue, - Binding::BuiltIn(builtin) if !should_write(builtin, stage) => continue, - _ => {} + for (i, (binding, handle)) in self.entry_args.iter().cloned().enumerate() { + if function_arg_use[function.index()] + .get(i) + .map_or(true, |u| !u.contains(EntryArgUse::WRITE)) + { + continue; } let ty = self.module.global_variables[handle].ty; @@ -556,40 +629,3 @@ impl Program<'_> { } } } - -// FIXME: Both of the functions below should be removed they are a temporary solution -// -// The fix should analyze the entry point and children function calls -// (recursively) and store something like `GlobalUse` and then later only read -// or store the globals that need to be read or written in that stage - -fn should_read(built_in: BuiltIn, stage: ShaderStage) -> bool { - match (built_in, stage) { - (BuiltIn::Position, ShaderStage::Fragment) - | (BuiltIn::BaseInstance, ShaderStage::Vertex) - | (BuiltIn::BaseVertex, ShaderStage::Vertex) - | (BuiltIn::ClipDistance, ShaderStage::Fragment) - | (BuiltIn::InstanceIndex, ShaderStage::Vertex) - | (BuiltIn::VertexIndex, ShaderStage::Vertex) - | (BuiltIn::FrontFacing, ShaderStage::Fragment) - | (BuiltIn::SampleIndex, ShaderStage::Fragment) - | (BuiltIn::SampleMask, ShaderStage::Fragment) - | (BuiltIn::GlobalInvocationId, ShaderStage::Compute) - | (BuiltIn::LocalInvocationId, ShaderStage::Compute) - | (BuiltIn::LocalInvocationIndex, ShaderStage::Compute) - | (BuiltIn::WorkGroupId, ShaderStage::Compute) - | (BuiltIn::WorkGroupSize, ShaderStage::Compute) => true, - _ => false, - } -} - -fn should_write(built_in: BuiltIn, stage: ShaderStage) -> bool { - match (built_in, stage) { - (BuiltIn::Position, ShaderStage::Vertex) - | (BuiltIn::ClipDistance, ShaderStage::Vertex) - | (BuiltIn::PointSize, ShaderStage::Vertex) - | (BuiltIn::FragDepth, ShaderStage::Fragment) - | (BuiltIn::SampleMask, ShaderStage::Fragment) => true, - _ => false, - } -} diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b995ea5d6..6161f563f 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,7 +1,8 @@ use super::{ ast::{ - Context, FunctionCall, FunctionCallKind, FunctionSignature, GlobalLookup, HirExpr, - HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier, + Context, FunctionCall, FunctionCallKind, FunctionSignature, GlobalLookup, GlobalLookupKind, + HirExpr, HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout, + TypeQualifier, }, error::ErrorKind, lex::Lexer, @@ -623,7 +624,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // parse the body self.parse_compound_statement(&mut context, &mut body)?; - self.program.add_function( + let Context { arg_use, .. } = context; + let handle = self.program.add_function( Function { name: Some(name), result, @@ -637,6 +639,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta, )?; + self.program.function_arg_use[handle.index()] = arg_use; + Ok(true) } _ => Err(ErrorKind::InvalidToken(token)), @@ -800,9 +804,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }); if let Some(k) = name { - self.program - .global_variables - .push((k, GlobalLookup::Variable(handle))); + self.program.global_variables.push(( + k, + GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: None, + }, + )); } for (i, k) in members @@ -810,9 +818,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { .enumerate() .filter_map(|(i, m)| m.name.map(|s| (i as u32, s))) { - self.program - .global_variables - .push((k, GlobalLookup::BlockSelect(handle, i))); + self.program.global_variables.push(( + k, + GlobalLookup { + kind: GlobalLookupKind::BlockSelect(handle, i), + entry_arg: None, + }, + )); } Ok(true) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 8a3bbee5d..966b639ee 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -45,11 +45,17 @@ impl Program<'_> { storage_access: StorageAccess::empty(), }); - self.entry_args - .push((Binding::BuiltIn(builtin), true, handle)); + let idx = self.entry_args.len(); + self.entry_args.push((Binding::BuiltIn(builtin), handle)); - self.global_variables - .push((name.into(), GlobalLookup::Variable(handle))); + self.global_variables.push(( + name.into(), + GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: Some(idx), + }, + )); + ctx.arg_use.push(EntryArgUse::empty()); let expr = ctx.add_expression(Expression::GlobalVariable(handle), body); let load = ctx.add_expression(Expression::Load { pointer: expr }, body); @@ -59,6 +65,7 @@ impl Program<'_> { expr, load: Some(load), mutable, + entry_arg: Some(idx), }, ); @@ -297,7 +304,6 @@ impl Program<'_> { } if let Some(location) = location { - let input = StorageQualifier::Input == storage; let interpolation = self.module.types[ty].inner.scalar_kind().map(|kind| { if let ScalarKind::Float = kind { Interpolation::Perspective @@ -315,18 +321,23 @@ impl Program<'_> { storage_access: StorageAccess::empty(), }); + let idx = self.entry_args.len(); self.entry_args.push(( Binding::Location { location, interpolation, sampling, }, - input, handle, )); - self.global_variables - .push((name, GlobalLookup::Variable(handle))); + self.global_variables.push(( + name, + GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: Some(idx), + }, + )); return Ok(ctx.add_expression(Expression::GlobalVariable(handle), body)); } else if let StorageQualifier::Const = storage { @@ -369,8 +380,13 @@ impl Program<'_> { storage_access, }); - self.global_variables - .push((name, GlobalLookup::Variable(handle))); + self.global_variables.push(( + name, + GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: None, + }, + )); Ok(ctx.add_expression(Expression::GlobalVariable(handle), body)) } From 679b6a308f077121b6f9568aa167d998015049dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 1 Jun 2021 19:21:49 +0100 Subject: [PATCH 0910/2212] [glsl-in] Fix emitting issues --- src/front/glsl/ast.rs | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 491af32c6..ed2eecc8c 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -204,8 +204,6 @@ impl<'function> Context<'function> { emitter: Emitter::default(), }; - this.emit_start(); - for &(ref name, handle) in program.constants.iter() { let expr = this.expressions.append(Expression::Constant(handle)); let var = VariableReference { @@ -218,24 +216,32 @@ impl<'function> Context<'function> { this.lookup_global_var_exps.insert(name.into(), var); } + this.emit_start(); + for &(ref name, lookup) in program.global_variables.iter() { this.emit_flush(body); let GlobalLookup { kind, entry_arg } = lookup; let (expr, load) = match kind { - GlobalLookupKind::Variable(v) => ( - Expression::GlobalVariable(v), - program.module.global_variables[v].class != StorageClass::Handle, - ), + GlobalLookupKind::Variable(v) => { + let res = ( + this.expressions.append(Expression::GlobalVariable(v)), + program.module.global_variables[v].class != StorageClass::Handle, + ); + this.emit_start(); + + res + } GlobalLookupKind::BlockSelect(handle, index) => { let base = this.expressions.append(Expression::GlobalVariable(handle)); + this.emit_start(); + let expr = this + .expressions + .append(Expression::AccessIndex { base, index }); - (Expression::AccessIndex { base, index }, true) + (expr, true) } }; - let expr = this.expressions.append(expr); - this.emit_start(); - let var = VariableReference { expr, load: if load { From 344acc3121dc3b327baecdbc13c8922778ece053 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 1 Jun 2021 19:22:08 +0100 Subject: [PATCH 0911/2212] [glsl-in] Reenable snapshot tests --- tests/snapshots.rs | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 4453309d3..1df7c8bc5 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -348,15 +348,13 @@ fn convert_spv_shadow() { } #[cfg(feature = "glsl-in")] -// TODO: Reenable tests later -#[allow(dead_code)] fn convert_glsl( name: &str, entry_points: naga::FastHashMap, - _targets: Targets, + targets: Targets, ) { let root = env!("CARGO_MANIFEST_DIR"); - let _module = naga::front::glsl::parse_str( + let module = naga::front::glsl::parse_str( &fs::read_to_string(format!("{}/{}/{}.glsl", root, DIR_IN, name)) .expect("Couldn't find glsl file"), &naga::front::glsl::Options { @@ -365,16 +363,16 @@ fn convert_glsl( }, ) .unwrap(); - //TODO - //check_targets(&module, name, targets); + println!("{:#?}", module); + + check_targets(&module, name, targets); } #[cfg(feature = "glsl-in")] #[test] fn convert_glsl_quad() { - // TODO: Reenable tests later - // let mut entry_points = naga::FastHashMap::default(); - // entry_points.insert("vert_main".to_string(), naga::ShaderStage::Vertex); - // entry_points.insert("frag_main".to_string(), naga::ShaderStage::Fragment); - // convert_glsl("quad-glsl", entry_points, Targets::SPIRV | Targets::IR); + let mut entry_points = naga::FastHashMap::default(); + entry_points.insert("vert_main".to_string(), naga::ShaderStage::Vertex); + entry_points.insert("frag_main".to_string(), naga::ShaderStage::Fragment); + convert_glsl("quad-glsl", entry_points, Targets::SPIRV | Targets::IR); } From 4cb036b3359dd72b19bc150bf08500dd04ce28d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 1 Jun 2021 21:25:12 +0100 Subject: [PATCH 0912/2212] [glsl-in] Fix op assignments --- src/front/glsl/parser.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 6161f563f..0f5f0db70 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1156,15 +1156,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { kind: HirExprKind::Binary { left: tgt, op: match token.value { - TokenValue::OrAssign => BinaryOperator::ExclusiveOr, - TokenValue::AndAssign => BinaryOperator::ExclusiveOr, - TokenValue::AddAssign => BinaryOperator::ExclusiveOr, - TokenValue::DivAssign => BinaryOperator::ExclusiveOr, - TokenValue::ModAssign => BinaryOperator::ExclusiveOr, - TokenValue::SubAssign => BinaryOperator::ExclusiveOr, - TokenValue::MulAssign => BinaryOperator::ExclusiveOr, - TokenValue::LeftShiftAssign => BinaryOperator::ExclusiveOr, - TokenValue::RightShiftAssign => BinaryOperator::ExclusiveOr, + TokenValue::OrAssign => BinaryOperator::InclusiveOr, + TokenValue::AndAssign => BinaryOperator::And, + TokenValue::AddAssign => BinaryOperator::Add, + TokenValue::DivAssign => BinaryOperator::Divide, + TokenValue::ModAssign => BinaryOperator::Modulo, + TokenValue::SubAssign => BinaryOperator::Subtract, + TokenValue::MulAssign => BinaryOperator::Multiply, + TokenValue::LeftShiftAssign => BinaryOperator::ShiftLeft, + TokenValue::RightShiftAssign => BinaryOperator::ShiftRight, TokenValue::XorAssign => BinaryOperator::ExclusiveOr, _ => unreachable!(), }, From 3699034cccb71f6928ecfb53d6f8cd17c8dfc8f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 1 Jun 2021 21:25:42 +0100 Subject: [PATCH 0913/2212] [glsl-in] Fix for if being in the wrong body --- src/front/glsl/parser.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0f5f0db70..81439e30e 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1491,7 +1491,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ctx.emit_flush(&mut block); ctx.emit_start(); - body.push(Statement::If { + block.push(Statement::If { condition, accept: vec![Statement::Break], reject: Block::new(), From 2295508f0e0d68e9160501b9a32201dd7a65e810 Mon Sep 17 00:00:00 2001 From: Frizi Date: Wed, 2 Jun 2021 01:46:17 +0200 Subject: [PATCH 0914/2212] Insert attribute glsl location qualifier for opengl ES 3.0 --- src/back/glsl/mod.rs | 6 ++++-- tests/out/quad-vert.Vertex.glsl | 2 +- tests/out/quad.Fragment.glsl | 2 +- tests/out/quad.Vertex.glsl | 2 +- tests/out/shadow.Fragment.glsl | 4 ++-- tests/out/skybox.Fragment.glsl | 2 +- tests/out/skybox.Vertex.glsl | 2 +- 7 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 985c385c0..6a4147149 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -106,7 +106,7 @@ impl Version { /// Checks if the version supports explicit `layout(location=)` qualifiers. fn supports_explicit_locations(&self) -> bool { - *self >= Version::Embedded(310) || *self >= Version::Desktop(410) + *self >= Version::Embedded(300) || *self >= Version::Desktop(410) } } @@ -825,7 +825,9 @@ impl<'a, W: Write> Writer<'a, W> { } // Write the storage class - if self.options.version.supports_explicit_locations() { + if !emit_interpolation_and_auxiliary + && self.options.version.supports_explicit_locations() + { write!(self.out, "layout(location = {}) ", location)?; } diff --git a/tests/out/quad-vert.Vertex.glsl b/tests/out/quad-vert.Vertex.glsl index c2f59e712..40d321619 100644 --- a/tests/out/quad-vert.Vertex.glsl +++ b/tests/out/quad-vert.Vertex.glsl @@ -21,7 +21,7 @@ struct gen_gl_PerVertex_block_0 { vec2 a_pos = vec2(0, 0); layout(location = 1) in vec2 _p2vs_location1; layout(location = 0) in vec2 _p2vs_location0; -smooth layout(location = 0) out vec2 _vs2fs_location0; +smooth out vec2 _vs2fs_location0; void main1() { v_uv = a_uv; diff --git a/tests/out/quad.Fragment.glsl b/tests/out/quad.Fragment.glsl index 825f9bd4d..ff24336cf 100644 --- a/tests/out/quad.Fragment.glsl +++ b/tests/out/quad.Fragment.glsl @@ -9,7 +9,7 @@ struct VertexOutput { uniform highp sampler2D _group_0_binding_0; -smooth layout(location = 0) in vec2 _vs2fs_location0; +smooth in vec2 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { diff --git a/tests/out/quad.Vertex.glsl b/tests/out/quad.Vertex.glsl index 95ce41427..873bbf39b 100644 --- a/tests/out/quad.Vertex.glsl +++ b/tests/out/quad.Vertex.glsl @@ -9,7 +9,7 @@ struct VertexOutput { layout(location = 0) in vec2 _p2vs_location0; layout(location = 1) in vec2 _p2vs_location1; -smooth layout(location = 0) out vec2 _vs2fs_location0; +smooth out vec2 _vs2fs_location0; void main() { vec2 pos = _p2vs_location0; diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index 5b9c58de0..df9f71c64 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -16,8 +16,8 @@ readonly buffer Lights_block_1 { } _group_0_binding_1; uniform highp sampler2DArrayShadow _group_0_binding_2; -smooth layout(location = 0) in vec3 _vs2fs_location0; -smooth layout(location = 1) in vec4 _vs2fs_location1; +smooth in vec3 _vs2fs_location0; +smooth in vec4 _vs2fs_location1; layout(location = 0) out vec4 _fs2p_location0; float fetch_shadow(uint light_id, vec4 homogeneous_coords) { diff --git a/tests/out/skybox.Fragment.glsl b/tests/out/skybox.Fragment.glsl index c8a25b448..1a8488c2a 100644 --- a/tests/out/skybox.Fragment.glsl +++ b/tests/out/skybox.Fragment.glsl @@ -9,7 +9,7 @@ struct VertexOutput { uniform highp samplerCube _group_0_binding_1; -smooth layout(location = 0) in vec3 _vs2fs_location0; +smooth in vec3 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { diff --git a/tests/out/skybox.Vertex.glsl b/tests/out/skybox.Vertex.glsl index 2d35107bc..1b7b6167c 100644 --- a/tests/out/skybox.Vertex.glsl +++ b/tests/out/skybox.Vertex.glsl @@ -11,7 +11,7 @@ uniform Data_block_0 { mat4x4 proj_inv; mat4x4 view; } _group_0_binding_0; -smooth layout(location = 0) out vec3 _vs2fs_location0; +smooth out vec3 _vs2fs_location0; void main() { uint vertex_index = uint(gl_VertexID); From 1a60ba01d9e8cbaafed9de5c34498484b70de0f9 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 2 Jun 2021 22:16:03 +0300 Subject: [PATCH 0915/2212] Add note about MSRV in README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index cd8420c72..8d99c4d93 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![Crates.io](https://img.shields.io/crates/v/naga.svg?label=naga)](https://crates.io/crates/naga) [![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga) [![Build Status](https://github.com/gfx-rs/naga/workflows/pipeline/badge.svg)](https://github.com/gfx-rs/naga/actions) +![MSRV](https://img.shields.io/badge/rustc-1.43+-blue.svg) [![codecov.io](https://codecov.io/gh/gfx-rs/naga/branch/master/graph/badge.svg?token=9VOKYO8BM2)](https://codecov.io/gh/gfx-rs/naga) The shader translation library for the needs of [wgpu](https://github.com/gfx-rs/wgpu) and [gfx-rs](https://github.com/gfx-rs/gfx) projects. From 98769c642d33e9947f3ec36e51115396a547ee3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 3 Jun 2021 14:49:10 +0100 Subject: [PATCH 0916/2212] [glsl-in] read global in prologue only if allowed Adds a check of wether or not a global can be read in the entry point prologue --- src/front/glsl/ast.rs | 27 ++++++++++++++++++++++++++- src/front/glsl/functions.rs | 21 +++++++++++---------- src/front/glsl/variables.rs | 23 ++++++++++++++++++----- 3 files changed, 55 insertions(+), 16 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index ed2eecc8c..aca29951d 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -46,6 +46,31 @@ bitflags::bitflags! { } } +bitflags::bitflags! { + pub struct PrologueStage: u32 { + const VERTEX = 0x1; + const FRAGMENT = 0x2; + const COMPUTE = 0x4; + } +} + +impl From for PrologueStage { + fn from(stage: ShaderStage) -> Self { + match stage { + ShaderStage::Vertex => PrologueStage::VERTEX, + ShaderStage::Fragment => PrologueStage::FRAGMENT, + ShaderStage::Compute => PrologueStage::COMPUTE, + } + } +} + +#[derive(Debug)] +pub struct EntryArg { + pub binding: Binding, + pub handle: Handle, + pub prologue: PrologueStage, +} + #[derive(Debug)] pub struct Program<'a> { pub version: u16, @@ -58,7 +83,7 @@ pub struct Program<'a> { pub global_variables: Vec<(String, GlobalLookup)>, pub constants: Vec<(String, Handle)>, - pub entry_args: Vec<(Binding, Handle)>, + pub entry_args: Vec, pub entries: Vec<(String, ShaderStage, Handle)>, // TODO: More efficient representation pub function_arg_use: Vec>, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index a70df7e50..77bdfb577 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -539,25 +539,26 @@ impl Program<'_> { let mut expressions = Arena::new(); let mut body = Vec::new(); - for (i, (binding, handle)) in self.entry_args.iter().cloned().enumerate() { + for (i, arg) in self.entry_args.iter().enumerate() { if function_arg_use[function.index()] .get(i) .map_or(true, |u| !u.contains(EntryArgUse::READ)) + || !arg.prologue.contains(stage.into()) { continue; } - let ty = self.module.global_variables[handle].ty; - let arg = arguments.len() as u32; + let ty = self.module.global_variables[arg.handle].ty; + let idx = arguments.len() as u32; arguments.push(FunctionArgument { name: None, ty, - binding: Some(binding), + binding: Some(arg.binding.clone()), }); - let pointer = expressions.append(Expression::GlobalVariable(handle)); - let value = expressions.append(Expression::FunctionArgument(arg)); + let pointer = expressions.append(Expression::GlobalVariable(arg.handle)); + let value = expressions.append(Expression::FunctionArgument(idx)); body.push(Statement::Store { pointer, value }); } @@ -572,7 +573,7 @@ impl Program<'_> { let mut members = Vec::new(); let mut components = Vec::new(); - for (i, (binding, handle)) in self.entry_args.iter().cloned().enumerate() { + for (i, arg) in self.entry_args.iter().enumerate() { if function_arg_use[function.index()] .get(i) .map_or(true, |u| !u.contains(EntryArgUse::WRITE)) @@ -580,18 +581,18 @@ impl Program<'_> { continue; } - let ty = self.module.global_variables[handle].ty; + let ty = self.module.global_variables[arg.handle].ty; members.push(StructMember { name: None, ty, - binding: Some(binding), + binding: Some(arg.binding.clone()), offset: span, }); span += self.module.types[ty].inner.span(&self.module.constants); - let pointer = expressions.append(Expression::GlobalVariable(handle)); + let pointer = expressions.append(Expression::GlobalVariable(arg.handle)); let len = expressions.len(); let load = expressions.append(Expression::Load { pointer }); body.push(Statement::Emit(expressions.range_from(len))); diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 966b639ee..399a9249f 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -30,7 +30,7 @@ impl Program<'_> { return Ok(Some(global_var)); } - let mut add_builtin = |inner, builtin, mutable| { + let mut add_builtin = |inner, builtin, mutable, prologue| { let ty = self .module .types @@ -46,7 +46,11 @@ impl Program<'_> { }); let idx = self.entry_args.len(); - self.entry_args.push((Binding::BuiltIn(builtin), handle)); + self.entry_args.push(EntryArg { + binding: Binding::BuiltIn(builtin), + handle, + prologue, + }); self.global_variables.push(( name.into(), @@ -80,6 +84,7 @@ impl Program<'_> { }, BuiltIn::Position, true, + PrologueStage::FRAGMENT, ), "gl_VertexIndex" => add_builtin( TypeInner::Scalar { @@ -88,6 +93,7 @@ impl Program<'_> { }, BuiltIn::VertexIndex, false, + PrologueStage::VERTEX, ), "gl_InstanceIndex" => add_builtin( TypeInner::Scalar { @@ -96,6 +102,7 @@ impl Program<'_> { }, BuiltIn::InstanceIndex, false, + PrologueStage::VERTEX, ), _ => Ok(None), } @@ -304,6 +311,11 @@ impl Program<'_> { } if let Some(location) = location { + let prologue = if let StorageQualifier::Input = storage { + PrologueStage::all() + } else { + PrologueStage::empty() + }; let interpolation = self.module.types[ty].inner.scalar_kind().map(|kind| { if let ScalarKind::Float = kind { Interpolation::Perspective @@ -322,14 +334,15 @@ impl Program<'_> { }); let idx = self.entry_args.len(); - self.entry_args.push(( - Binding::Location { + self.entry_args.push(EntryArg { + binding: Binding::Location { location, interpolation, sampling, }, handle, - )); + prologue, + }); self.global_variables.push(( name, From 90c2cf6aa6ea2b595098a27b148e3ad2f91317cb Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 2 Jun 2021 18:28:41 +0300 Subject: [PATCH 0917/2212] Add ability to generate named expressions --- src/back/glsl/mod.rs | 86 ++++++++++++++-------- src/back/msl/mod.rs | 2 +- src/back/wgsl/writer.rs | 118 ++++++++++++++++++------------- src/front/glsl/parser.rs | 1 + src/front/spv/function.rs | 4 +- src/front/wgsl/mod.rs | 11 +++ src/lib.rs | 5 ++ src/proc/namer.rs | 16 +++++ tests/out/access.wgsl | 6 +- tests/out/boids.Compute.glsl | 13 ++-- tests/out/boids.wgsl | 13 ++-- tests/out/collatz.ron | 2 + tests/out/image.wgsl | 57 +++++++-------- tests/out/interface.wgsl | 7 +- tests/out/operators.wgsl | 4 +- tests/out/quad.Fragment.glsl | 7 +- tests/out/quad.wgsl | 7 +- tests/out/shadow.Fragment.glsl | 13 ++-- tests/out/shadow.ron | 3 + tests/out/shadow.wgsl | 13 ++-- tests/out/skybox.Vertex.glsl | 6 +- tests/out/skybox.wgsl | 6 +- tests/out/standard.Fragment.glsl | 8 +-- tests/out/standard.wgsl | 8 +-- 24 files changed, 263 insertions(+), 153 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 6a4147149..fc7847e77 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -194,9 +194,11 @@ struct FunctionCtx<'a> { info: &'a FunctionInfo, /// The expression arena of the current function being written expressions: &'a Arena, + /// Map of expressions that have associated variable names + named_expressions: &'a crate::NamedExpressions, } -impl<'a> FunctionCtx<'a> { +impl<'a> FunctionCtx<'_> { /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function fn name_key(&self, local: Handle) -> NameKey { match self.func { @@ -295,9 +297,6 @@ pub enum Error { /// A scalar with an unsupported width was requested #[error("A scalar with an unsupported width was requested: {0:?} {1:?}")] UnsupportedScalar(ScalarKind, Bytes), - /// [`Interpolation::Patch`](crate::Interpolation::Patch) isn't supported - #[error("Patch interpolation isn't supported")] - PatchInterpolationNotSupported, /// A image was used with multiple samplers, this isn't supported #[error("A image was used with multiple samplers")] ImageMultipleSamplers, @@ -320,6 +319,7 @@ pub struct Writer<'a, W> { // Internal State /// Features manager used to store all the needed features and write them features: FeaturesManager, + namer: Namer, /// A map with all the names needed for writing the module /// (generated by a [`Namer`](crate::proc::Namer)) names: FastHashMap, @@ -332,7 +332,7 @@ pub struct Writer<'a, W> { /// Used to generate a unique number for blocks block_id: IdGenerator, /// Set of expressions that have associated temporary variables - cached_expressions: FastHashMap, String>, + named_expressions: crate::NamedExpressions, } impl<'a, W: Write> Writer<'a, W> { @@ -363,7 +363,8 @@ impl<'a, W: Write> Writer<'a, W> { // Generate a map with names required to write the module let mut names = FastHashMap::default(); - Namer::default().reset(module, keywords::RESERVED_KEYWORDS, &["gl_"], &mut names); + let mut namer = Namer::default(); + namer.reset(module, keywords::RESERVED_KEYWORDS, &["gl_"], &mut names); // Build the instance let mut this = Self { @@ -371,7 +372,7 @@ impl<'a, W: Write> Writer<'a, W> { info, out, options, - + namer, features: FeaturesManager::new(), names, reflection_names: FastHashMap::default(), @@ -379,7 +380,7 @@ impl<'a, W: Write> Writer<'a, W> { entry_point_idx: ep_idx as u16, block_id: IdGenerator::default(), - cached_expressions: FastHashMap::default(), + named_expressions: crate::NamedExpressions::default(), }; // Find all features required to print this module @@ -884,9 +885,10 @@ impl<'a, W: Write> Writer<'a, W> { func: ty, info, expressions: &func.expressions, + named_expressions: &func.named_expressions, }; - self.cached_expressions.clear(); + self.named_expressions.clear(); // Write the function header // @@ -1189,30 +1191,23 @@ impl<'a, W: Write> Writer<'a, W> { // This is where we can generate intermediate constants for some expression types. Statement::Emit(ref range) => { for handle in range.clone() { + if let Some(name) = ctx.named_expressions.get(&handle) { + write!(self.out, "{}", INDENT.repeat(indent))?; + + // Front end provides names for all variables at the start of writing. + // But we write them to step by step. We need to recache them inside `write_named_expr` + // Otherwise, we could accidentally write variable name instead of full expression. + // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. + let sanitized_name = self.namer.call_unique(name); + self.write_named_expr(handle, sanitized_name, ctx)?; + continue; + } + let min_ref_count = ctx.expressions[handle].bake_ref_count(); if min_ref_count <= ctx.info[handle].ref_count { write!(self.out, "{}", INDENT.repeat(indent))?; - match ctx.info[handle].ty { - TypeResolution::Handle(ty_handle) => { - match self.module.types[ty_handle].inner { - TypeInner::Struct { .. } => { - let ty_name = &self.names[&NameKey::Type(ty_handle)]; - write!(self.out, "{}", ty_name)?; - } - _ => { - self.write_type(ty_handle)?; - } - } - } - TypeResolution::Value(ref inner) => { - self.write_value_type(inner)?; - } - } let name = format!("_expr{}", handle.index()); - write!(self.out, " {} = ", name)?; - self.write_expr(handle, ctx)?; - writeln!(self.out, ";")?; - self.cached_expressions.insert(handle, name); + self.write_named_expr(handle, name, ctx)?; } } } @@ -1491,7 +1486,7 @@ impl<'a, W: Write> Writer<'a, W> { let result = self.module.functions[function].result.as_ref().unwrap(); self.write_type(result.ty)?; write!(self.out, " {} = ", name)?; - self.cached_expressions.insert(expr, name); + self.named_expressions.insert(expr, name); } write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; @@ -1507,10 +1502,11 @@ impl<'a, W: Write> Writer<'a, W> { /// # Notes /// Doesn't add any newlines or leading/trailing spaces fn write_expr(&mut self, expr: Handle, ctx: &FunctionCtx<'_>) -> BackendResult { - if let Some(name) = self.cached_expressions.get(&expr) { + if let Some(name) = self.named_expressions.get(&expr) { write!(self.out, "{}", name)?; return Ok(()); } + match ctx.expressions[expr] { // `Access` is applied to arrays, vectors and matrices and is written as indexing Expression::Access { base, index } => { @@ -2114,6 +2110,34 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + fn write_named_expr( + &mut self, + handle: Handle, + name: String, + ctx: &FunctionCtx, + ) -> BackendResult { + match ctx.info[handle].ty { + TypeResolution::Handle(ty_handle) => match self.module.types[ty_handle].inner { + TypeInner::Struct { .. } => { + let ty_name = &self.names[&NameKey::Type(ty_handle)]; + write!(self.out, "{}", ty_name)?; + } + _ => { + self.write_type(ty_handle)?; + } + }, + TypeResolution::Value(ref inner) => { + self.write_value_type(inner)?; + } + } + write!(self.out, " {} = ", name)?; + self.write_expr(handle, ctx)?; + writeln!(self.out, ";")?; + self.named_expressions.insert(handle, name); + + Ok(()) + } + /// Helper method used to produce the reflection info that's returned to the user /// /// It takes an iterator of [`Function`](crate::Function) references instead of diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 54cfd91ab..738eb9c93 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -77,7 +77,7 @@ pub struct PerStageResources { /// The slot of a buffer that contains an array of `u32`, /// one for the size of each bound buffer that contains a runtime array, - /// in order of [`GlobalVariable`] declarations. + /// in order of [`crate::GlobalVariable`] declarations. #[cfg_attr(feature = "deserialize", serde(default))] pub sizes_buffer: Option, } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 417fbe585..488d0256b 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -4,11 +4,10 @@ use crate::{ proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, Arena, ArraySize, Binding, Constant, ConstantInner, Expression, FastHashMap, Function, - GlobalVariable, Handle, ImageClass, ImageDimension, Interpolation, Module, SampleLevel, - Sampling, ScalarKind, ScalarValue, ShaderStage, Statement, StorageClass, StorageFormat, - StructMember, Type, TypeInner, + GlobalVariable, Handle, ImageClass, ImageDimension, Interpolation, LocalVariable, Module, + SampleLevel, Sampling, ScalarKind, ScalarValue, ShaderStage, Statement, StorageClass, + StorageFormat, StructMember, Type, TypeInner, }; -use bit_set::BitSet; use std::fmt::Write; const INDENT: &str = " "; @@ -53,13 +52,25 @@ struct FunctionCtx<'a> { info: &'a FunctionInfo, /// The expression arena of the current function being written expressions: &'a Arena, + /// Map of expressions that have associated variable names + named_expressions: &'a crate::NamedExpressions, +} + +impl<'a> FunctionCtx<'_> { + /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function + fn name_key(&self, local: Handle) -> NameKey { + match self.ty { + FunctionType::Function(handle) => NameKey::FunctionLocal(handle, local), + FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, local), + } + } } pub struct Writer { out: W, names: FastHashMap, namer: Namer, - named_expressions: BitSet, + named_expressions: crate::NamedExpressions, ep_results: Vec<(ShaderStage, Handle)>, } @@ -69,7 +80,7 @@ impl Writer { out, names: FastHashMap::default(), namer: Namer::default(), - named_expressions: BitSet::new(), + named_expressions: crate::NamedExpressions::default(), ep_results: vec![], } } @@ -78,6 +89,7 @@ impl Writer { self.names.clear(); self.namer.reset(module, RESERVED, &[], &mut self.names); self.named_expressions.clear(); + self.ep_results.clear(); } pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { @@ -128,6 +140,7 @@ impl Writer { ty: FunctionType::Function(handle), info: fun_info, expressions: &function.expressions, + named_expressions: &function.named_expressions, }; // Write the function @@ -154,6 +167,7 @@ impl Writer { ty: FunctionType::EntryPoint(index as u16), info: &info.get_entry_point(index), expressions: &ep.function.expressions, + named_expressions: &ep.function.named_expressions, }; self.write_function(&module, &ep.function, &func_ctx)?; @@ -271,11 +285,7 @@ impl Writer { // Write the local name // The leading space is important - let name_key = match func_ctx.ty { - FunctionType::Function(func_handle) => NameKey::FunctionLocal(func_handle, handle), - FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, handle), - }; - write!(self.out, "var {}: ", self.names[&name_key])?; + write!(self.out, "var {}: ", self.names[&func_ctx.name_key(handle)])?; // Write the local type self.write_type(&module, local.ty)?; @@ -570,6 +580,21 @@ impl Writer { match *stmt { Statement::Emit(ref range) => { for handle in range.clone() { + if let Some(name) = func_ctx.named_expressions.get(&handle) { + write!(self.out, "{}", INDENT.repeat(indent))?; + let sanitized_name = self.namer.call_unique(name); + self.start_named_expr(module, handle, &func_ctx, &sanitized_name)?; + self.write_expr(module, handle, &func_ctx)?; + writeln!(self.out, ";")?; + + // Front end provides names for all variables at the start of writing. + // But we write them to step by step. We need to recache them. + // Otherwise, we could accidentally write variable name instead of full expression. + // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. + self.named_expressions.insert(handle, sanitized_name); + continue; + } + let expr = &func_ctx.expressions[handle]; let min_ref_count = expr.bake_ref_count(); // Forcefully creating baking expressions in some cases to help with readability @@ -581,10 +606,8 @@ impl Writer { }; if min_ref_count <= func_ctx.info[handle].ref_count || required_baking_expr { write!(self.out, "{}", INDENT.repeat(indent))?; - self.start_baking_expr(module, handle, &func_ctx)?; - self.write_expr(module, handle, &func_ctx)?; + self.write_baking_expr(module, handle, &func_ctx)?; writeln!(self.out, ";")?; - self.named_expressions.insert(handle.index()); } } } @@ -654,8 +677,7 @@ impl Writer { } => { write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { - self.start_baking_expr(module, expr, &func_ctx)?; - self.named_expressions.insert(expr.index()); + self.write_baking_expr(module, expr, &func_ctx)?; } let func_name = &self.names[&NameKey::Function(function)]; write!(self.out, "{}(", func_name)?; @@ -793,33 +815,23 @@ impl Writer { Ok(()) } - fn start_baking_expr( + fn start_named_expr( &mut self, module: &Module, handle: Handle, - context: &FunctionCtx, + func_ctx: &FunctionCtx, + name: &str, ) -> BackendResult { // Write variable name - write!(self.out, "let {}{}: ", BAKE_PREFIX, handle.index())?; - let ty = &context.info[handle].ty; + write!(self.out, "let {}: ", name)?; + let ty = &func_ctx.info[handle].ty; // Write variable type match *ty { - TypeResolution::Handle(ty_handle) => { - self.write_type(module, ty_handle)?; + TypeResolution::Handle(handle) => { + self.write_type(module, handle)?; } - TypeResolution::Value(crate::TypeInner::Scalar { kind, .. }) => { - write!(self.out, "{}", scalar_kind_str(kind))?; - } - TypeResolution::Value(crate::TypeInner::Vector { size, kind, .. }) => { - write!( - self.out, - "vec{}<{}>", - vector_size_str(size), - scalar_kind_str(kind), - )?; - } - _ => { - return Err(Error::Unimplemented(format!("start_baking_expr {:?}", ty))); + TypeResolution::Value(ref inner) => { + self.write_value_type(module, inner)?; } } @@ -827,6 +839,20 @@ impl Writer { Ok(()) } + fn write_baking_expr( + &mut self, + module: &Module, + handle: Handle, + func_ctx: &FunctionCtx, + ) -> BackendResult { + let name = format!("{}{}", BAKE_PREFIX, handle.index()); + self.start_named_expr(module, handle, func_ctx, &name)?; + self.write_expr(module, handle, func_ctx)?; + self.named_expressions.insert(handle, name); + + Ok(()) + } + /// Helper method to write expressions /// /// # Notes @@ -837,13 +863,13 @@ impl Writer { expr: Handle, func_ctx: &FunctionCtx<'_>, ) -> BackendResult { - let expression = &func_ctx.expressions[expr]; - - if self.named_expressions.contains(expr.index()) { - write!(self.out, "{}{}", BAKE_PREFIX, expr.index())?; + if let Some(name) = self.named_expressions.get(&expr) { + write!(self.out, "{}", name)?; return Ok(()); } + let expression = &func_ctx.expressions[expr]; + match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::Compose { ty, ref components } => { @@ -1110,13 +1136,7 @@ impl Writer { } Expression::Load { pointer } => self.write_expr(module, pointer, func_ctx)?, Expression::LocalVariable(handle) => { - let name_key = match func_ctx.ty { - FunctionType::Function(func_handle) => { - NameKey::FunctionLocal(func_handle, handle) - } - FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, handle), - }; - write!(self.out, "{}", self.names[&name_key])? + write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])? } Expression::ArrayLength(expr) => { write!(self.out, "arrayLength(")?; @@ -1273,10 +1293,8 @@ impl Writer { write!(self.out, ")")? } - Expression::Call(function) => { - let func_name = &self.names[&NameKey::Function(function)]; - write!(self.out, "{}(", func_name)? - } + // Nothing to do here, since call expression already cached + Expression::Call(_) => {} } Ok(()) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 81439e30e..d97333dab 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -630,6 +630,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { name: Some(name), result, expressions, + named_expressions: crate::FastHashMap::default(), local_variables, arguments, body, diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 47dd75b19..7c0554654 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -28,7 +28,7 @@ pub enum Terminator { /// /// switch(SELECTOR) { /// case TARGET_LITERAL#: { - /// TARGET_BLOCK# + /// TARGET_BLOCK# /// } /// default: { /// DEFAULT @@ -90,6 +90,7 @@ impl> super::Parser { }, local_variables: Arena::new(), expressions: self.make_expression_storage(), + named_expressions: crate::FastHashMap::default(), body: Vec::new(), } }; @@ -194,6 +195,7 @@ impl> super::Parser { result: None, local_variables: Arena::new(), expressions: Arena::new(), + named_expressions: crate::FastHashMap::default(), body: Vec::new(), }; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index cc522b41f..caabe9673 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -589,6 +589,7 @@ struct StatementContext<'input, 'temp, 'out> { typifier: &'temp mut super::Typifier, variables: &'out mut Arena, expressions: &'out mut Arena, + named_expressions: &'out mut FastHashMap, String>, types: &'out mut Arena, constants: &'out mut Arena, global_vars: &'out Arena, @@ -603,6 +604,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { typifier: self.typifier, variables: self.variables, expressions: self.expressions, + named_expressions: self.named_expressions, types: self.types, constants: self.constants, global_vars: self.global_vars, @@ -2563,6 +2565,9 @@ impl Parser { } block.extend(emitter.finish(context.expressions)); context.lookup_ident.insert(name, expr_id); + context + .named_expressions + .insert(expr_id, String::from(name)); } "var" => { enum Init { @@ -2985,11 +2990,13 @@ impl Parser { result, local_variables: Arena::new(), expressions, + named_expressions: crate::NamedExpressions::default(), body: Vec::new(), }; // read body let mut typifier = super::Typifier::new(); + let mut named_expressions = crate::FastHashMap::default(); fun.body = self.parse_block( lexer, StatementContext { @@ -2997,6 +3004,7 @@ impl Parser { typifier: &mut typifier, variables: &mut fun.local_variables, expressions: &mut fun.expressions, + named_expressions: &mut named_expressions, types: &mut module.types, constants: &mut module.constants, global_vars: &module.global_variables, @@ -3010,6 +3018,9 @@ impl Parser { // done self.scopes.pop(); + // Set named expressions after block parsing ends + fun.named_expressions = named_expressions; + Ok((fun, fun_name)) } diff --git a/src/lib.rs b/src/lib.rs index 9dc6c0b22..ad48cd4e7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -151,6 +151,9 @@ pub type FastHashMap = HashMap> /// Hash set that is faster but not resilient to DoS attacks. pub type FastHashSet = HashSet>; +/// Map of expressions that have associated variable names +pub(crate) type NamedExpressions = FastHashMap, String>; + /// Early fragment tests. In a standard situation if a driver determines that it is possible to /// switch on early depth test it will. Typical situations when early depth test is switched off: /// - Calling ```discard``` in a shader. @@ -1043,6 +1046,8 @@ pub struct Function { pub local_variables: Arena, /// Expressions used inside this function. pub expressions: Arena, + /// Map of expressions that have associated variable names + pub named_expressions: NamedExpressions, /// Block of instructions comprising the body of the function. pub body: Block, } diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 5e8ba6132..c339c4cf9 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -48,6 +48,22 @@ impl Namer { base } + /// Helper function that return unique name without cache update. + /// This function should be used **after** [`Namer`](crate::proc::Namer) initialization by [`reset`](Self::reset()) function. + pub fn call_unique(&mut self, string: &str) -> String { + let base = self.sanitize(string); + match self.unique.entry(base) { + Entry::Occupied(mut e) => { + *e.get_mut() += 1; + format!("{}{}", e.key(), e.get()) + } + Entry::Vacant(e) => { + let name = e.key().to_string(); + name + } + } + } + pub fn call(&mut self, label_raw: &str) -> String { let base = self.sanitize(label_raw); match self.unique.entry(base) { diff --git a/tests/out/access.wgsl b/tests/out/access.wgsl index dfbbb1b7d..9a75615ab 100644 --- a/tests/out/access.wgsl +++ b/tests/out/access.wgsl @@ -9,5 +9,9 @@ var bar: [[access(read_write)]] Bar; [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { - return vec4(vec4(array(bar.data[(arrayLength(&bar.data) - 1u)], i32(bar.matrix[3u].x), 3, 4, 5)[vi])); + let b: f32 = bar.matrix[3u].x; + let a: i32 = bar.data[(arrayLength(&bar.data) - 1u)]; + let array: array = array(a, i32(b), 3, 4, 5); + let value: i32 = array[vi]; + return vec4(vec4(value)); } diff --git a/tests/out/boids.Compute.glsl b/tests/out/boids.Compute.glsl index e54432d5c..9f32dbf80 100644 --- a/tests/out/boids.Compute.glsl +++ b/tests/out/boids.Compute.glsl @@ -37,11 +37,12 @@ void main() { vec2 pos1; vec2 vel1; uint i = 0u; - if((global_invocation_id.x >= 1500u)) { + uint index = global_invocation_id.x; + if((index >= 1500u)) { return; } - vPos = _group_0_binding_1.particles[global_invocation_id.x].pos; - vVel = _group_0_binding_1.particles[global_invocation_id.x].vel; + vPos = _group_0_binding_1.particles[index].pos; + vVel = _group_0_binding_1.particles[index].vel; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); @@ -49,7 +50,7 @@ void main() { if((i >= 1500u)) { break; } - if((i == global_invocation_id.x)) { + if((i == index)) { continue; } pos1 = _group_0_binding_1.particles[i].pos; @@ -88,8 +89,8 @@ void main() { if((vPos.y > 1.0)) { vPos.y = -1.0; } - _group_0_binding_2.particles[global_invocation_id.x].pos = vPos; - _group_0_binding_2.particles[global_invocation_id.x].vel = vVel; + _group_0_binding_2.particles[index].pos = vPos; + _group_0_binding_2.particles[index].vel = vVel; return; } diff --git a/tests/out/boids.wgsl b/tests/out/boids.wgsl index b1437ab8f..a3591c6a7 100644 --- a/tests/out/boids.wgsl +++ b/tests/out/boids.wgsl @@ -41,11 +41,12 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { var vel1: vec2; var i: u32 = 0u; - if ((global_invocation_id.x >= NUM_PARTICLES)) { + let index: u32 = global_invocation_id.x; + if ((index >= NUM_PARTICLES)) { return; } - vPos = particlesSrc.particles[global_invocation_id.x].pos; - vVel = particlesSrc.particles[global_invocation_id.x].vel; + vPos = particlesSrc.particles[index].pos; + vVel = particlesSrc.particles[index].vel; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); @@ -53,7 +54,7 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { if ((i >= NUM_PARTICLES)) { break; } - if ((i == global_invocation_id.x)) { + if ((i == index)) { continue; } pos1 = particlesSrc.particles[i].pos; @@ -94,7 +95,7 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { if ((vPos.y > 1.0)) { vPos.y = -1.0; } - particlesDst.particles[global_invocation_id.x].pos = vPos; - particlesDst.particles[global_invocation_id.x].vel = vVel; + particlesDst.particles[index].pos = vPos; + particlesDst.particles[index].vel = vVel; return; } diff --git a/tests/out/collatz.ron b/tests/out/collatz.ron index 7fe6a38ef..df144444c 100644 --- a/tests/out/collatz.ron +++ b/tests/out/collatz.ron @@ -181,6 +181,7 @@ pointer: 5, ), ], + named_expressions: {}, body: [ Store( pointer: 3, @@ -320,6 +321,7 @@ ), Call(1), ], + named_expressions: {}, body: [ Emit(( start: 2, diff --git a/tests/out/image.wgsl b/tests/out/image.wgsl index 4d1ead826..f7e682c93 100644 --- a/tests/out/image.wgsl +++ b/tests/out/image.wgsl @@ -23,41 +23,42 @@ var image_2d_depth: texture_depth_2d; [[stage(compute), workgroup_size(16, 1, 1)]] fn main([[builtin(local_invocation_id)]] local_id: vec3) { - let _e3: vec2 = textureDimensions(image_src); - let _e10: vec2 = ((_e3 * vec2(local_id.xy)) % vec2(10, 20)); - let _e11: vec4 = textureLoad(image_src, _e10); - textureStore(image_dst, _e10.x, _e11); + let dim: vec2 = textureDimensions(image_src); + let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); + let value: vec4 = textureLoad(image_src, itc); + textureStore(image_dst, itc.x, value); return; } [[stage(vertex)]] fn queries() -> [[builtin(position)]] vec4 { - let _e9: i32 = textureDimensions(image_1d); - let _e10: vec2 = textureDimensions(image_2d); - let _e11: i32 = textureNumLevels(image_2d); - let _e13: vec2 = textureDimensions(image_2d, 1); - let _e14: vec2 = textureDimensions(image_2d_array); - let _e15: i32 = textureNumLevels(image_2d_array); - let _e17: vec2 = textureDimensions(image_2d_array, 1); - let _e18: i32 = textureNumLayers(image_2d_array); - let _e19: vec3 = textureDimensions(image_cube); - let _e20: i32 = textureNumLevels(image_cube); - let _e22: vec3 = textureDimensions(image_cube, 1); - let _e23: vec3 = textureDimensions(image_cube_array); - let _e24: i32 = textureNumLevels(image_cube_array); - let _e26: vec3 = textureDimensions(image_cube_array, 1); - let _e27: i32 = textureNumLayers(image_cube_array); - let _e28: vec3 = textureDimensions(image_3d); - let _e29: i32 = textureNumLevels(image_3d); - let _e31: vec3 = textureDimensions(image_3d, 1); - let _e32: i32 = textureNumSamples(image_aa); - return vec4(f32(((((((((((((((((((_e9 + _e10.y) + _e13.y) + _e14.y) + _e17.y) + _e18) + _e19.y) + _e22.y) + _e23.y) + _e26.y) + _e27) + _e28.z) + _e31.z) + _e32) + _e11) + _e15) + _e29) + _e20) + _e24))); + let dim_1d: i32 = textureDimensions(image_1d); + let dim_2d: vec2 = textureDimensions(image_2d); + let num_levels_2d: i32 = textureNumLevels(image_2d); + let dim_2d_lod: vec2 = textureDimensions(image_2d, 1); + let dim_2d_array: vec2 = textureDimensions(image_2d_array); + let num_levels_2d_array: i32 = textureNumLevels(image_2d_array); + let dim_2d_array_lod: vec2 = textureDimensions(image_2d_array, 1); + let num_layers_2d: i32 = textureNumLayers(image_2d_array); + let dim_cube: vec3 = textureDimensions(image_cube); + let num_levels_cube: i32 = textureNumLevels(image_cube); + let dim_cube_lod: vec3 = textureDimensions(image_cube, 1); + let dim_cube_array: vec3 = textureDimensions(image_cube_array); + let num_levels_cube_array: i32 = textureNumLevels(image_cube_array); + let dim_cube_array_lod: vec3 = textureDimensions(image_cube_array, 1); + let num_layers_cube: i32 = textureNumLayers(image_cube_array); + let dim_3d: vec3 = textureDimensions(image_3d); + let num_levels_3d: i32 = textureNumLevels(image_3d); + let dim_3d_lod: vec3 = textureDimensions(image_3d, 1); + let num_samples_aa: i32 = textureNumSamples(image_aa); + let sum: i32 = ((((((((((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + num_layers_2d) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + num_layers_cube) + dim_3d.z) + dim_3d_lod.z) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); + return vec4(f32(sum)); } [[stage(fragment)]] fn sample_comparison() -> [[location(0)]] f32 { - let _e12: vec2 = vec2(0.5); - let _e14: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, _e12, 0.5); - let _e15: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, _e12, 0.5); - return (_e14 + _e15); + let tc: vec2 = vec2(0.5); + let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc, 0.5); + let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc, 0.5); + return (s2d_depth + s2d_depth_level); } diff --git a/tests/out/interface.wgsl b/tests/out/interface.wgsl index 90b76ff7b..74dbe30be 100644 --- a/tests/out/interface.wgsl +++ b/tests/out/interface.wgsl @@ -11,12 +11,15 @@ struct FragmentOutput { [[stage(vertex)]] fn vertex([[builtin(vertex_index)]] vertex_index: u32, [[builtin(instance_index)]] instance_index: u32, [[location(10)]] color1: u32) -> VertexOutput { - return VertexOutput(vec4(1.0), f32(((vertex_index + instance_index) + color1))); + let tmp: u32 = ((vertex_index + instance_index) + color1); + return VertexOutput(vec4(1.0), f32(tmp)); } [[stage(fragment)]] fn fragment(in: VertexOutput, [[builtin(front_facing)]] front_facing: bool, [[builtin(sample_index)]] sample_index: u32, [[builtin(sample_mask)]] sample_mask1: u32) -> FragmentOutput { - return FragmentOutput(in.varying, (sample_mask1 & (1u << sample_index)), select(0.0, 1.0, front_facing)); + let mask: u32 = (sample_mask1 & (1u << sample_index)); + let color2: f32 = select(0.0, 1.0, front_facing); + return FragmentOutput(in.varying, mask, color2); } [[stage(compute), workgroup_size(1, 1, 1)]] diff --git a/tests/out/operators.wgsl b/tests/out/operators.wgsl index aad7a5c03..cacefc724 100644 --- a/tests/out/operators.wgsl +++ b/tests/out/operators.wgsl @@ -1,5 +1,7 @@ fn splat() -> vec4 { - return ((((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)).xyxy + vec4((vec4(5) % vec4(2)))); + let a: vec2 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + let b: vec4 = (vec4(5) % vec4(2)); + return (a.xyxy + vec4(b)); } fn unary() -> i32 { diff --git a/tests/out/quad.Fragment.glsl b/tests/out/quad.Fragment.glsl index ff24336cf..4cb26d2a4 100644 --- a/tests/out/quad.Fragment.glsl +++ b/tests/out/quad.Fragment.glsl @@ -14,11 +14,12 @@ layout(location = 0) out vec4 _fs2p_location0; void main() { vec2 uv2 = _vs2fs_location0; - vec4 _expr4 = texture(_group_0_binding_0, vec2(uv2)); - if((_expr4.w == 0.0)) { + vec4 color = texture(_group_0_binding_0, vec2(uv2)); + if((color.w == 0.0)) { discard; } - _fs2p_location0 = (_expr4.w * _expr4); + vec4 premultiplied = (color.w * color); + _fs2p_location0 = premultiplied; return; } diff --git a/tests/out/quad.wgsl b/tests/out/quad.wgsl index b853f09e3..63d94b5a3 100644 --- a/tests/out/quad.wgsl +++ b/tests/out/quad.wgsl @@ -17,9 +17,10 @@ fn main([[location(0)]] pos: vec2, [[location(1)]] uv1: vec2) -> Verte [[stage(fragment)]] fn main1([[location(0), interpolate(perspective)]] uv2: vec2) -> [[location(0)]] vec4 { - let _e4: vec4 = textureSample(u_texture, u_sampler, uv2); - if ((_e4.w == 0.0)) { + let color: vec4 = textureSample(u_texture, u_sampler, uv2); + if ((color.w == 0.0)) { discard; } - return (_e4.w * _e4); + let premultiplied: vec4 = (color.w * color); + return premultiplied; } diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index df9f71c64..fa7ab0ca3 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -24,7 +24,9 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { if((homogeneous_coords.w <= 0.0)) { return 1.0; } - float _expr26 = textureGrad(_group_0_binding_2, vec4((((homogeneous_coords.xy * vec2(0.5, -0.5)) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0, 0), vec2(0,0)); + vec2 flip_correction = vec2(0.5, -0.5); + vec2 light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); + float _expr26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0, 0), vec2(0,0)); return _expr26; } @@ -33,13 +35,16 @@ void main() { vec4 position = _vs2fs_location1; vec3 color1 = vec3(0.05, 0.05, 0.05); uint i = 0u; + vec3 normal = normalize(raw_normal); while(true) { if((i >= min(_group_0_binding_0.num_lights.x, 10u))) { break; } - Light _expr21 = _group_0_binding_1.data[i]; - float _expr25 = fetch_shadow(i, (_expr21.proj * position)); - color1 = (color1 + ((_expr25 * max(0.0, dot(normalize(raw_normal), normalize((_expr21.pos.xyz - position.xyz))))) * _expr21.color.xyz)); + Light light = _group_0_binding_1.data[i]; + float _expr25 = fetch_shadow(i, (light.proj * position)); + vec3 light_dir = normalize((light.pos.xyz - position.xyz)); + float diffuse = max(0.0, dot(normal, light_dir)); + color1 = (color1 + ((_expr25 * diffuse) * light.color.xyz)); i = (i + 1u); } _fs2p_location0 = vec4(color1, 1.0); diff --git a/tests/out/shadow.ron b/tests/out/shadow.ron index fd91f99af..9ea27083a 100644 --- a/tests/out/shadow.ron +++ b/tests/out/shadow.ron @@ -1054,6 +1054,7 @@ depth_ref: Some(69), ), ], + named_expressions: {}, body: [ Emit(( start: 48, @@ -1443,6 +1444,7 @@ ], ), ], + named_expressions: {}, body: [ Loop( body: [ @@ -1550,6 +1552,7 @@ pointer: 5, ), ], + named_expressions: {}, body: [ Store( pointer: 2, diff --git a/tests/out/shadow.wgsl b/tests/out/shadow.wgsl index c5ca9f0a5..5325cf9fa 100644 --- a/tests/out/shadow.wgsl +++ b/tests/out/shadow.wgsl @@ -30,7 +30,9 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { if ((homogeneous_coords.w <= 0.0)) { return 1.0; } - let _e26: f32 = textureSampleCompareLevel(t_shadow, sampler_shadow, (((homogeneous_coords.xy * vec2(0.5, -0.5)) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)), i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); + let flip_correction: vec2 = vec2(0.5, -0.5); + let light_local: vec2 = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); + let _e26: f32 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); return _e26; } @@ -39,13 +41,16 @@ fn fs_main([[location(0), interpolate(perspective)]] raw_normal: vec3, [[lo var color1: vec3 = vec3(0.05, 0.05, 0.05); var i: u32 = 0u; + let normal: vec3 = normalize(raw_normal); loop { if ((i >= min(u_globals.num_lights.x, c_max_lights))) { break; } - let _e21: Light = s_lights.data[i]; - let _e25: f32 = fetch_shadow(i, (_e21.proj * position)); - color1 = (color1 + ((_e25 * max(0.0, dot(normalize(raw_normal), normalize((_e21.pos.xyz - position.xyz))))) * _e21.color.xyz)); + let light: Light = s_lights.data[i]; + let _e25: f32 = fetch_shadow(i, (light.proj * position)); + let light_dir: vec3 = normalize((light.pos.xyz - position.xyz)); + let diffuse: f32 = max(0.0, dot(normal, light_dir)); + color1 = (color1 + ((_e25 * diffuse) * light.color.xyz)); continuing { i = (i + 1u); } diff --git a/tests/out/skybox.Vertex.glsl b/tests/out/skybox.Vertex.glsl index 1b7b6167c..dd00b450e 100644 --- a/tests/out/skybox.Vertex.glsl +++ b/tests/out/skybox.Vertex.glsl @@ -19,8 +19,10 @@ void main() { int tmp2_; tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); - vec4 _expr24 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - VertexOutput _tmp_return = VertexOutput(_expr24, (transpose(mat3x3(_group_0_binding_0.view[0].xyz, _group_0_binding_0.view[1].xyz, _group_0_binding_0.view[2].xyz)) * (_group_0_binding_0.proj_inv * _expr24).xyz)); + vec4 pos = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + mat3x3 inv_model_view = transpose(mat3x3(_group_0_binding_0.view[0].xyz, _group_0_binding_0.view[1].xyz, _group_0_binding_0.view[2].xyz)); + vec4 unprojected = (_group_0_binding_0.proj_inv * pos); + VertexOutput _tmp_return = VertexOutput(pos, (inv_model_view * unprojected.xyz)); gl_Position = _tmp_return.position; _vs2fs_location0 = _tmp_return.uv; return; diff --git a/tests/out/skybox.wgsl b/tests/out/skybox.wgsl index a0e0112e9..3df95a61c 100644 --- a/tests/out/skybox.wgsl +++ b/tests/out/skybox.wgsl @@ -23,8 +23,10 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { tmp1_ = (i32(vertex_index) / 2); tmp2_ = (i32(vertex_index) & 1); - let _e24: vec4 = vec4(((f32(tmp1_) * 4.0) - 1.0), ((f32(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - return VertexOutput(_e24, (transpose(mat3x3(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz)) * (r_data.proj_inv * _e24).xyz)); + let pos: vec4 = vec4(((f32(tmp1_) * 4.0) - 1.0), ((f32(tmp2_) * 4.0) - 1.0), 0.0, 1.0); + let inv_model_view: mat3x3 = transpose(mat3x3(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz)); + let unprojected: vec4 = (r_data.proj_inv * pos); + return VertexOutput(pos, (inv_model_view * unprojected.xyz)); } [[stage(fragment)]] diff --git a/tests/out/standard.Fragment.glsl b/tests/out/standard.Fragment.glsl index d39147bfb..54d962ce9 100644 --- a/tests/out/standard.Fragment.glsl +++ b/tests/out/standard.Fragment.glsl @@ -6,10 +6,10 @@ layout(location = 0) out vec4 _fs2p_location0; void main() { vec4 foo = gl_FragCoord; - vec4 _expr1 = dFdx(foo); - vec4 _expr2 = dFdy(foo); - vec4 _expr3 = fwidth(foo); - _fs2p_location0 = ((_expr1 + _expr2) * _expr3); + vec4 x = dFdx(foo); + vec4 y = dFdy(foo); + vec4 z = fwidth(foo); + _fs2p_location0 = ((x + y) * z); return; } diff --git a/tests/out/standard.wgsl b/tests/out/standard.wgsl index 90f74e871..3aa0277df 100644 --- a/tests/out/standard.wgsl +++ b/tests/out/standard.wgsl @@ -1,7 +1,7 @@ [[stage(fragment)]] fn derivatives([[builtin(position)]] foo: vec4) -> [[location(0)]] vec4 { - let _e1: vec4 = dpdx(foo); - let _e2: vec4 = dpdy(foo); - let _e3: vec4 = fwidth(foo); - return ((_e1 + _e2) * _e3); + let x: vec4 = dpdx(foo); + let y: vec4 = dpdy(foo); + let z: vec4 = fwidth(foo); + return ((x + y) * z); } From ce88c9d5372ad3807ef9887a92d2602dc63aceb8 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 3 Jun 2021 16:06:42 +0000 Subject: [PATCH 0918/2212] Exclude bin and tests from publishing --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index b67f45046..7acbf4a33 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ homepage = "https://github.com/gfx-rs/naga" repository = "https://github.com/gfx-rs/naga" keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" +exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] [package.metadata.docs.rs] all-features = true From db3dd63bdd57b68d1f3965e3460c5a20ea1fa05a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 3 Jun 2021 19:33:20 +0100 Subject: [PATCH 0919/2212] [glsl-in] Don't output empty struct in entry point --- src/front/glsl/functions.rs | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 77bdfb577..8ccdc8c4a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -599,19 +599,26 @@ impl Program<'_> { components.push(load) } - let ty = self.module.types.append(Type { - name: None, - inner: TypeInner::Struct { - top_level: false, - members, - span, - }, - }); + let (ty, value) = if !components.is_empty() { + let ty = self.module.types.append(Type { + name: None, + inner: TypeInner::Struct { + top_level: false, + members, + span, + }, + }); - let len = expressions.len(); - let res = expressions.append(Expression::Compose { ty, components }); - body.push(Statement::Emit(expressions.range_from(len))); - body.push(Statement::Return { value: Some(res) }); + let len = expressions.len(); + let res = expressions.append(Expression::Compose { ty, components }); + body.push(Statement::Emit(expressions.range_from(len))); + + (Some(ty), Some(res)) + } else { + (None, None) + }; + + body.push(Statement::Return { value }); self.module.entry_points.push(EntryPoint { name, @@ -623,7 +630,7 @@ impl Program<'_> { arguments, expressions, body, - result: Some(FunctionResult { ty, binding: None }), + result: ty.map(|ty| FunctionResult { ty, binding: None }), ..Default::default() }, }); From 87748a2fe3668a5684fdc60da48a3e2973d5a711 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 3 Jun 2021 20:34:54 +0100 Subject: [PATCH 0920/2212] [glsl-in] Add integration tests to CI (#943) * [glsl-in] Add glsl snapshots folder * [glsl-in] Fix incorrect angle brackets parsing * [glsl-in] Temporarily remove wgsl snapshot output --- src/front/glsl/parser.rs | 4 +- tests/in/glsl/210-bevy-2d-shader.frag | 27 ++++++++++++ tests/in/glsl/210-bevy-2d-shader.vert | 27 ++++++++++++ tests/in/glsl/210-bevy-shader.vert | 28 ++++++++++++ tests/in/glsl/277-casting.vert | 8 ++++ tests/in/glsl/280-matrix-cast.vert | 8 ++++ tests/in/glsl/484-preprocessor-if.vert | 10 +++++ tests/in/glsl/800-out-of-bounds-panic.vert | 26 +++++++++++ tests/in/glsl/896-push-constant.vert | 10 +++++ tests/in/glsl/931-constant-emitting.vert | 10 +++++ tests/in/glsl/932-for-loop-if.vert | 8 ++++ tests/out/210-bevy-2d-shader-frag.wgsl | 27 ++++++++++++ tests/out/210-bevy-2d-shader-vert.wgsl | 48 +++++++++++++++++++++ tests/out/800-out-of-bounds-panic-vert.wgsl | 36 ++++++++++++++++ tests/out/931-constant-emitting-vert.wgsl | 4 ++ tests/snapshots.rs | 47 ++++++++++++++++++++ 16 files changed, 326 insertions(+), 2 deletions(-) create mode 100644 tests/in/glsl/210-bevy-2d-shader.frag create mode 100644 tests/in/glsl/210-bevy-2d-shader.vert create mode 100644 tests/in/glsl/210-bevy-shader.vert create mode 100644 tests/in/glsl/277-casting.vert create mode 100644 tests/in/glsl/280-matrix-cast.vert create mode 100644 tests/in/glsl/484-preprocessor-if.vert create mode 100644 tests/in/glsl/800-out-of-bounds-panic.vert create mode 100644 tests/in/glsl/896-push-constant.vert create mode 100644 tests/in/glsl/931-constant-emitting.vert create mode 100644 tests/in/glsl/932-for-loop-if.vert create mode 100644 tests/out/210-bevy-2d-shader-frag.wgsl create mode 100644 tests/out/210-bevy-2d-shader-vert.wgsl create mode 100644 tests/out/800-out-of-bounds-panic-vert.wgsl create mode 100644 tests/out/931-constant-emitting-vert.wgsl diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index d97333dab..cf9eaf16b 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1075,8 +1075,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::NotEqual => BinaryOperator::NotEqual, TokenValue::GreaterEqual => BinaryOperator::GreaterEqual, TokenValue::LessEqual => BinaryOperator::LessEqual, - TokenValue::LeftAngle => BinaryOperator::Greater, - TokenValue::RightAngle => BinaryOperator::Less, + TokenValue::LeftAngle => BinaryOperator::Less, + TokenValue::RightAngle => BinaryOperator::Greater, TokenValue::LeftShift => BinaryOperator::ShiftLeft, TokenValue::RightShift => BinaryOperator::ShiftRight, TokenValue::Plus => BinaryOperator::Add, diff --git a/tests/in/glsl/210-bevy-2d-shader.frag b/tests/in/glsl/210-bevy-2d-shader.frag new file mode 100644 index 000000000..93119ef25 --- /dev/null +++ b/tests/in/glsl/210-bevy-2d-shader.frag @@ -0,0 +1,27 @@ +// AUTHOR: mrk-its +// ISSUE: #210 +// FIX: #898 +#version 450 + +layout(location = 0) in vec2 v_Uv; + +layout(location = 0) out vec4 o_Target; + +layout(set = 1, binding = 0) uniform ColorMaterial_color { + vec4 Color; +}; + +# ifdef COLORMATERIAL_TEXTURE +layout(set = 1, binding = 1) uniform texture2D ColorMaterial_texture; +layout(set = 1, binding = 2) uniform sampler ColorMaterial_texture_sampler; +# endif + +void main() { + vec4 color = Color; +# ifdef COLORMATERIAL_TEXTURE + color *= texture( + sampler2D(ColorMaterial_texture, ColorMaterial_texture_sampler), + v_Uv); +# endif + o_Target = color; +} diff --git a/tests/in/glsl/210-bevy-2d-shader.vert b/tests/in/glsl/210-bevy-2d-shader.vert new file mode 100644 index 000000000..1d99e1b17 --- /dev/null +++ b/tests/in/glsl/210-bevy-2d-shader.vert @@ -0,0 +1,27 @@ +// AUTHOR: mrk-its +// ISSUE: #210 +// FIX: #898 +#version 450 + +layout(location = 0) in vec3 Vertex_Position; +layout(location = 1) in vec3 Vertex_Normal; +layout(location = 2) in vec2 Vertex_Uv; + +layout(location = 0) out vec2 v_Uv; + +layout(set = 0, binding = 0) uniform Camera { + mat4 ViewProj; +}; + +layout(set = 2, binding = 0) uniform Transform { + mat4 Model; +}; +layout(set = 2, binding = 1) uniform Sprite_size { + vec2 size; +}; + +void main() { + v_Uv = Vertex_Uv; + vec3 position = Vertex_Position * vec3(size, 1.0); + gl_Position = ViewProj * Model * vec4(position, 1.0); +} diff --git a/tests/in/glsl/210-bevy-shader.vert b/tests/in/glsl/210-bevy-shader.vert new file mode 100644 index 000000000..64cdca2ce --- /dev/null +++ b/tests/in/glsl/210-bevy-shader.vert @@ -0,0 +1,28 @@ +// AUTHOR: enfipy +// ISSUE: #210 +// FIX: #898 +#version 450 + +layout(location = 0) in vec3 Vertex_Position; +layout(location = 1) in vec3 Vertex_Normal; +layout(location = 2) in vec2 Vertex_Uv; + +layout(location = 0) out vec3 v_Position; +layout(location = 1) out vec3 v_Normal; +layout(location = 2) out vec2 v_Uv; + +layout(set = 0, binding = 0) uniform Camera { + mat4 ViewProj; +}; + +layout(set = 2, binding = 0) uniform Transform { + mat4 Model; +}; + +void main() { + v_Normal = (Model * vec4(Vertex_Normal, 1.0)).xyz; + v_Normal = mat3(Model) * Vertex_Normal; + v_Position = (Model * vec4(Vertex_Position, 1.0)).xyz; + v_Uv = Vertex_Uv; + gl_Position = ViewProj * vec4(v_Position, 1.0); +} diff --git a/tests/in/glsl/277-casting.vert b/tests/in/glsl/277-casting.vert new file mode 100644 index 000000000..939be006b --- /dev/null +++ b/tests/in/glsl/277-casting.vert @@ -0,0 +1,8 @@ +// AUTHOR: Napokue +// ISSUE: #277 +// FIX: #278 +#version 450 + +void main() { + float a = float(1); +} diff --git a/tests/in/glsl/280-matrix-cast.vert b/tests/in/glsl/280-matrix-cast.vert new file mode 100644 index 000000000..560a44260 --- /dev/null +++ b/tests/in/glsl/280-matrix-cast.vert @@ -0,0 +1,8 @@ +// AUTHOR: pjoe +// ISSUE: #280 +// FIX: #898 +#version 450 + +void main() { + mat4 a = mat4(1); +} diff --git a/tests/in/glsl/484-preprocessor-if.vert b/tests/in/glsl/484-preprocessor-if.vert new file mode 100644 index 000000000..d2c92030e --- /dev/null +++ b/tests/in/glsl/484-preprocessor-if.vert @@ -0,0 +1,10 @@ +// AUTHOR: fintelia +// ISSUE: #484 +// FIX: https://github.com/Kangz/glslpp-rs/pull/30 +// NOTE: Shader altered to use correct syntax +#version 450 core + +#if 0 +#endif + +void main() { } diff --git a/tests/in/glsl/800-out-of-bounds-panic.vert b/tests/in/glsl/800-out-of-bounds-panic.vert new file mode 100644 index 000000000..babca1668 --- /dev/null +++ b/tests/in/glsl/800-out-of-bounds-panic.vert @@ -0,0 +1,26 @@ +// AUTHOR: Herschel +// ISSUE: #800 +// FIX: #901 +#version 450 + +// Set 0: globals +layout(set = 0, binding = 0) uniform Globals { + mat4 view_matrix; +}; + +// Push constants: matrix + color +layout(push_constant) uniform VertexPushConstants { + mat4 world_matrix; +}; + +layout(location = 0) in vec2 position; +layout(location = 1) in vec4 color; + +layout(location = 0) out vec4 frag_color; + +void main() { + frag_color = color; + gl_Position = view_matrix * world_matrix * vec4(position, 0.0, 1.0); + // TODO: https://github.com/gfx-rs/naga/issues/901 + // gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0; +} diff --git a/tests/in/glsl/896-push-constant.vert b/tests/in/glsl/896-push-constant.vert new file mode 100644 index 000000000..59ea1e4c4 --- /dev/null +++ b/tests/in/glsl/896-push-constant.vert @@ -0,0 +1,10 @@ +// AUTHOR: Foltik +// ISSUE: #896 +// FIX: #897 +#version 450 + +layout(push_constant) uniform PushConstants { + float example; +} c; + +void main() {} diff --git a/tests/in/glsl/931-constant-emitting.vert b/tests/in/glsl/931-constant-emitting.vert new file mode 100644 index 000000000..b780eb7ac --- /dev/null +++ b/tests/in/glsl/931-constant-emitting.vert @@ -0,0 +1,10 @@ +// AUTHOR: jakobhellermann +// ISSUE: #931 +// FIX: #933 +#version 450 + +const int constant = 10; + +float function() { + return 0.0; +} diff --git a/tests/in/glsl/932-for-loop-if.vert b/tests/in/glsl/932-for-loop-if.vert new file mode 100644 index 000000000..07dbdd751 --- /dev/null +++ b/tests/in/glsl/932-for-loop-if.vert @@ -0,0 +1,8 @@ +// AUTHOR: jakobhellermann +// ISSUE: #932 +// FIX: #935 +#version 450 + +void main() { + for (int i = 0; i < 1; i += 1) {} +} diff --git a/tests/out/210-bevy-2d-shader-frag.wgsl b/tests/out/210-bevy-2d-shader-frag.wgsl new file mode 100644 index 000000000..2185714c4 --- /dev/null +++ b/tests/out/210-bevy-2d-shader-frag.wgsl @@ -0,0 +1,27 @@ +[[block]] +struct ColorMaterial_color { + Color: vec4; +}; + +struct FragmentOutput { + [[location(0), interpolate(perspective)]] member: vec4; +}; + +var v_Uv: vec2; +var o_Target: vec4; +[[group(1), binding(0)]] +var global: ColorMaterial_color; + +fn main() { + var color: vec4; + + color = global.Color; + o_Target = color; + return; +} + +[[stage(fragment)]] +fn main1() -> FragmentOutput { + main(); + return FragmentOutput(o_Target); +} diff --git a/tests/out/210-bevy-2d-shader-vert.wgsl b/tests/out/210-bevy-2d-shader-vert.wgsl new file mode 100644 index 000000000..ce2e4cf1c --- /dev/null +++ b/tests/out/210-bevy-2d-shader-vert.wgsl @@ -0,0 +1,48 @@ +[[block]] +struct Camera { + ViewProj: mat4x4; +}; + +[[block]] +struct Transform { + Model: mat4x4; +}; + +[[block]] +struct Sprite_size { + size: vec2; +}; + +struct VertexOutput { + [[location(0), interpolate(perspective)]] member: vec2; + [[builtin(position)]] member1: vec4; +}; + +var Vertex_Position: vec3; +var Vertex_Normal: vec3; +var Vertex_Uv: vec2; +var v_Uv: vec2; +[[group(0), binding(0)]] +var global: Camera; +[[group(2), binding(0)]] +var global1: Transform; +[[group(2), binding(1)]] +var global2: Sprite_size; +var gl_Position: vec4; + +fn main() { + var position: vec3; + + v_Uv = Vertex_Uv; + position = (Vertex_Position * vec3(global2.size, 1.0)); + gl_Position = ((global.ViewProj * global1.Model) * vec4(position, 1.0)); + return; +} + +[[stage(vertex)]] +fn main1([[location(0), interpolate(perspective)]] param: vec3, [[location(2), interpolate(perspective)]] param1: vec2) -> VertexOutput { + Vertex_Position = param; + Vertex_Uv = param1; + main(); + return VertexOutput(v_Uv, gl_Position); +} diff --git a/tests/out/800-out-of-bounds-panic-vert.wgsl b/tests/out/800-out-of-bounds-panic-vert.wgsl new file mode 100644 index 000000000..175862c52 --- /dev/null +++ b/tests/out/800-out-of-bounds-panic-vert.wgsl @@ -0,0 +1,36 @@ +[[block]] +struct Globals { + view_matrix: mat4x4; +}; + +[[block]] +struct VertexPushConstants { + world_matrix: mat4x4; +}; + +struct VertexOutput { + [[location(0), interpolate(perspective)]] member: vec4; + [[builtin(position)]] member1: vec4; +}; + +[[group(0), binding(0)]] +var global: Globals; +var global1: VertexPushConstants; +var position: vec2; +var color: vec4; +var frag_color: vec4; +var gl_Position: vec4; + +fn main() { + frag_color = color; + gl_Position = ((global.view_matrix * global1.world_matrix) * vec4(position, 0.0, 1.0)); + return; +} + +[[stage(vertex)]] +fn main1([[location(0), interpolate(perspective)]] param: vec2, [[location(1), interpolate(perspective)]] param1: vec4) -> VertexOutput { + position = param; + color = param1; + main(); + return VertexOutput(frag_color, gl_Position); +} diff --git a/tests/out/931-constant-emitting-vert.wgsl b/tests/out/931-constant-emitting-vert.wgsl new file mode 100644 index 000000000..43ccc8800 --- /dev/null +++ b/tests/out/931-constant-emitting-vert.wgsl @@ -0,0 +1,4 @@ +fn function() -> f32 { + return 0.0; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1df7c8bc5..25c6887a6 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -368,6 +368,53 @@ fn convert_glsl( check_targets(&module, name, targets); } +#[cfg(feature = "glsl-in")] +#[allow(unused_variables)] +#[test] +fn convert_glsl_folder() { + let root = env!("CARGO_MANIFEST_DIR"); + + for entry in std::fs::read_dir(format!("{}/{}/glsl", root, DIR_IN)).unwrap() { + let entry = entry.unwrap(); + let file_name = entry.file_name().into_string().unwrap(); + + println!("Processing {}", file_name); + + let mut entry_points = naga::FastHashMap::default(); + let stage = match entry.path().extension().and_then(|s| s.to_str()).unwrap() { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + ext => panic!("Unknown extension for glsl file {}", ext), + }; + entry_points.insert("main".to_string(), stage); + + let module = naga::front::glsl::parse_str( + &fs::read_to_string(entry.path()).expect("Couldn't find glsl file"), + &naga::front::glsl::Options { + entry_points, + defines: Default::default(), + }, + ) + .unwrap(); + + let info = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + + let dest = PathBuf::from(root) + .join(DIR_OUT) + .join(&file_name.replace(".", "-")); + + // FIXME: https://github.com/gfx-rs/naga/issues/945 + // #[cfg(feature = "wgsl-out")] + // check_output_wgsl(&module, &info, &dest); + } +} + #[cfg(feature = "glsl-in")] #[test] fn convert_glsl_quad() { From 1c3baf4557cf9ff5e6b42f61d916285c350e3baf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 3 Jun 2021 21:09:20 +0100 Subject: [PATCH 0921/2212] [glsl-in] Allow field selection behind pointers (#948) --- src/front/glsl/variables.rs | 6 +++++- tests/in/glsl/901-lhs-field-select.vert | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 tests/in/glsl/901-lhs-field-select.vert diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 399a9249f..3b0c6df77 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -116,7 +116,11 @@ impl Program<'_> { name: &str, meta: SourceMetadata, ) -> Result, ErrorKind> { - match *self.resolve_type(ctx, expression, meta)? { + let ty = match *self.resolve_type(ctx, expression, meta)? { + TypeInner::Pointer { base, .. } => &self.module.types[base].inner, + ref ty => ty, + }; + match *ty { TypeInner::Struct { ref members, .. } => { let index = members .iter() diff --git a/tests/in/glsl/901-lhs-field-select.vert b/tests/in/glsl/901-lhs-field-select.vert new file mode 100644 index 000000000..a9b7348fd --- /dev/null +++ b/tests/in/glsl/901-lhs-field-select.vert @@ -0,0 +1,9 @@ +// AUTHOR: JCapucho +// ISSUE: #901 +// FIX: #948 +#version 450 + +void main() { + vec4 a = vec4(1.0); + a.x = 2.0; +} From a2a35f2eb38a5fd413c50fd3f6aff551a1ea5ea0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 4 Jun 2021 09:57:20 -0700 Subject: [PATCH 0922/2212] Permit dynamic indexing of arrays and matrices only behind a pointer. (#949) This makes Naga IR validation impose the restrictions added to WGSL in gpuweb/gpuweb#1801. Remove code in the SPIR-V writer to spill arrays to temporary variables in order to index them dynamically. If such IR is encountered, treat it as a failure of validation. --- src/back/spv/writer.rs | 78 +++-------------------------------------- src/lib.rs | 51 ++++++++++++++++++++++++++- src/proc/mod.rs | 22 ++++++++++++ src/proc/typifier.rs | 8 +++++ src/valid/expression.rs | 20 +++++++---- tests/in/access.wgsl | 6 ++-- tests/out/access.msl | 4 ++- tests/out/access.spvasm | 73 +++++++++++++++++++------------------- tests/out/access.wgsl | 6 ++-- tests/wgsl-errors.rs | 43 +++++++++++++++++++++++ 10 files changed, 187 insertions(+), 124 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f3918347a..57342be2f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -72,7 +72,6 @@ struct Function { signature: Option, parameters: Vec, variables: crate::FastHashMap, LocalVariable>, - internal_variables: Vec, blocks: Vec, entry_point_context: Option, } @@ -89,9 +88,6 @@ impl Function { for local_var in self.variables.values() { local_var.instruction.to_words(sink); } - for internal_var in self.internal_variables.iter() { - internal_var.instruction.to_words(sink); - } } for instruction in block.body.iter() { instruction.to_words(sink); @@ -1324,62 +1320,6 @@ impl Writer { }) } - #[allow(clippy::too_many_arguments)] - fn promote_access_expression_to_variable( - &mut self, - ir_types: &Arena, - result_type_id: Word, - container_id: Word, - container_resolution: &TypeResolution, - index_id: Word, - element_ty: Handle, - block: &mut Block, - ) -> Result<(Word, LocalVariable), Error> { - let container_type_id = self.get_expression_type_id(container_resolution)?; - let pointer_type_id = self.id_gen.next(); - Instruction::type_pointer( - pointer_type_id, - spirv::StorageClass::Function, - container_type_id, - ) - .to_words(&mut self.logical_layout.declarations); - - let variable = { - let id = self.id_gen.next(); - LocalVariable { - id, - instruction: Instruction::variable( - pointer_type_id, - id, - spirv::StorageClass::Function, - None, - ), - } - }; - block - .body - .push(Instruction::store(variable.id, container_id, None)); - - let element_pointer_id = self.id_gen.next(); - let element_pointer_type_id = - self.get_pointer_id(ir_types, element_ty, spirv::StorageClass::Function)?; - block.body.push(Instruction::access_chain( - element_pointer_type_id, - element_pointer_id, - variable.id, - &[index_id], - )); - let id = self.id_gen.next(); - block.body.push(Instruction::load( - result_type_id, - id, - element_pointer_id, - None, - )); - - Ok((id, variable)) - } - fn is_intermediate( &self, expr_handle: Handle, @@ -1433,20 +1373,10 @@ impl Writer { )); id } - crate::TypeInner::Array { - base: ty_element, .. - } => { - let (id, variable) = self.promote_access_expression_to_variable( - &ir_module.types, - result_type_id, - base_id, - &fun_info[base].ty, - index_id, - ty_element, - block, - )?; - function.internal_variables.push(variable); - id + crate::TypeInner::Array { .. } => { + return Err(Error::Validation( + "dynamic indexing of arrays not permitted", + )); } ref other => { log::error!( diff --git a/src/lib.rs b/src/lib.rs index ad48cd4e7..d863ea406 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -795,9 +795,58 @@ bitflags::bitflags! { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Expression { /// Array access with a computed index. + /// + /// ## Typing rules + /// + /// The `base` operand must be some composite type: [`Vector`], [`Matrix`], + /// [`Array`], a [`Pointer`] to one of those, or a [`ValuePointer`] with a + /// `size`. + /// + /// The `index` operand must be an integer, signed or unsigned. + /// + /// Indexing a [`Vector`] or [`Array`] produces a value of its element type. + /// Indexing a [`Matrix`] produces a [`Vector`]. + /// + /// Indexing a [`Pointer`] to an [`Array`] produces a [`Pointer`] to its + /// `base` type, taking on the `Pointer`'s storage class. + /// + /// Indexing a [`Pointer`] to a [`Vector`] produces a [`ValuePointer`] whose + /// size is `None`, taking on the [`Vector`]'s scalar kind and width and the + /// [`Pointer`]'s storage class. + /// + /// Indexing a [`Pointer`] to a [`Matrix`] produces a [`ValuePointer`] for a + /// column of the matrix: its size is the matrix's height, its `kind` is + /// [`Float`], and it inherits the [`Matrix`]'s width and the [`Pointer`]'s + /// storage class. + /// + /// ## Dynamic indexing restrictions + /// + /// To accommodate restrictions in some of the shader languages that Naga + /// targets, it is not permitted to subscript a matrix or array with a + /// dynamically computed index unless that matrix or array appears behind a + /// pointer. In other words, if the inner type of `base` is [`Array`] or + /// [`Matrix`], then `index` must be a constant. But if the type of `base` + /// is a [`Pointer`] to an array or matrix or a [`ValuePointer`] with a + /// `size`, then the index may be any expression of integer type. + /// + /// You can use the [`Expression::is_dynamic_index`] method to determine + /// whether a given index expression requires matrix or array base operands + /// to be behind a pointer. + /// + /// (It would be simpler to always require the use of `AccessIndex` when + /// subscripting arrays and matrices that are not behind pointers, but to + /// accommodate existing front ends, Naga also permits `Access`, with a + /// restricted `index`.) + /// + /// [`Vector`]: TypeInner::Vector + /// [`Matrix`]: TypeInner::Matrix + /// [`Array`]: TypeInner::Array + /// [`Pointer`]: TypeInner::Pointer + /// [`ValuePointer`]: TypeInner::ValuePointer + /// [`Float`]: ScalarKind::Float Access { base: Handle, - index: Handle, //int + index: Handle, }, /// Array access with a known index. AccessIndex { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 58926c1d8..6229f9390 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -183,6 +183,28 @@ impl crate::Expression { _ => false, } } + + /// Return true if this expression is a dynamic array index, for [`Access`]. + /// + /// This method returns true if this expression is a dynamically computed + /// index, and as such can only be used to index matrices and arrays when + /// they appear behind a pointer. See the documentation for [`Access`] for + /// details. + /// + /// Note, this does not check the _type_ of the given expression. It's up to + /// the caller to establish that the `Access` expression is well-typed + /// through other means, like [`ResolveContext`]. + /// + /// [`Access`]: crate::Expression::Access + /// [`ResolveContext`]: crate::proc::ResolveContext + pub fn is_dynamic_index(&self, module: &crate::Module) -> bool { + if let Self::Constant(handle) = *self { + let constant = &module.constants[handle]; + constant.specialization.is_some() + } else { + true + } + } } impl crate::SampleLevel { diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index a07e3d43a..c8d2b02df 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -128,7 +128,15 @@ impl<'a> ResolveContext<'a> { let types = self.types; Ok(match *expr { crate::Expression::Access { base, .. } => match *past(base).inner_with(types) { + // Arrays and matrices can only be indexed dynamically behind a + // pointer, but that's a validation error, not a type error, so + // go ahead provide a type here. Ti::Array { base, .. } => TypeResolution::Handle(base), + Ti::Matrix { rows, width, .. } => TypeResolution::Value(Ti::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }), Ti::Vector { size: _, kind, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 69d0d9b9d..561a088a7 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -19,6 +19,8 @@ pub enum ExpressionError { InvalidIndexType(Handle), #[error("Accessing index {1} is out of {0:?} bounds")] IndexOutOfBounds(Handle, u32), + #[error("The expression {0:?} may only be indexed by a constant")] + IndexMustBeConstant(Handle), #[error("Function argument {0:?} doesn't exist")] FunctionArgumentDoesntExist(u32), #[error("Constant {0:?} doesn't exist")] @@ -142,17 +144,16 @@ impl super::Validator { let stages = match *expression { E::Access { base, index } => { - match *resolver.resolve(base)? { - Ti::Vector { .. } - | Ti::Matrix { .. } - | Ti::Array { .. } - | Ti::Pointer { .. } - | Ti::ValuePointer { size: Some(_), .. } => {} + // See the documentation for `Expression::Access`. + let dynamic_indexing_restricted = match *resolver.resolve(base)? { + Ti::Vector { .. } => false, + Ti::Matrix { .. } | Ti::Array { .. } => true, + Ti::Pointer { .. } | Ti::ValuePointer { size: Some(_), .. } => false, ref other => { log::error!("Indexing of {:?}", other); return Err(ExpressionError::InvalidBaseType(base)); } - } + }; match *resolver.resolve(index)? { //TODO: only allow one of these Ti::Scalar { @@ -168,6 +169,11 @@ impl super::Validator { return Err(ExpressionError::InvalidIndexType(index)); } } + if dynamic_indexing_restricted + && function.expressions[index].is_dynamic_index(module) + { + return Err(ExpressionError::IndexMustBeConstant(base)); + } ShaderStages::all() } E::AccessIndex { base, index } => { diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index b6ee08355..ec963e6df 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -15,9 +15,9 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let b = bar.matrix[index].x; let a = bar.data[arrayLength(&bar.data) - 1u]; - - let array = array(a, i32(b), 3, 4, 5); - let value = array[vi]; + + var c: array = array(a, i32(b), 3, 4, 5); + let value = c[vi]; return vec4(vec4(value)); } diff --git a/tests/out/access.msl b/tests/out/access.msl index 36fd35774..1fcde2582 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -24,5 +24,7 @@ vertex fooOutput foo( , device Bar& bar [[buffer(0)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - return fooOutput { static_cast(metal::int4(type5 {bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u], static_cast(bar.matrix[3u].x), 3, 4, 5}.inner[vi])) }; + type5 c; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type5 {bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u], static_cast(bar.matrix[3u].x), 3, 4, 5}.inner[_i]; + return fooOutput { static_cast(metal::int4(c.inner[vi])) }; } diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm index 2f5c21665..843872137 100644 --- a/tests/out/access.spvasm +++ b/tests/out/access.spvasm @@ -6,14 +6,15 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %24 "foo" %19 %22 +OpEntryPoint Vertex %26 "foo" %21 %24 OpSource GLSL 450 OpName %14 "Bar" OpMemberName %14 0 "matrix" OpMemberName %14 1 "data" OpName %16 "bar" -OpName %19 "vi" -OpName %24 "foo" +OpName %18 "c" +OpName %21 "vi" +OpName %26 "foo" OpDecorate %13 ArrayStride 4 OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 @@ -23,8 +24,8 @@ OpMemberDecorate %14 1 Offset 64 OpDecorate %15 ArrayStride 4 OpDecorate %16 DescriptorSet 0 OpDecorate %16 Binding 0 -OpDecorate %19 BuiltIn VertexIndex -OpDecorate %22 BuiltIn Position +OpDecorate %21 BuiltIn VertexIndex +OpDecorate %24 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 3 @@ -41,39 +42,39 @@ OpDecorate %22 BuiltIn Position %15 = OpTypeArray %7 %6 %17 = OpTypePointer StorageBuffer %14 %16 = OpVariable %17 StorageBuffer -%20 = OpTypePointer Input %4 -%19 = OpVariable %20 Input -%23 = OpTypePointer Output %11 -%22 = OpVariable %23 Output -%25 = OpTypeFunction %2 -%27 = OpTypePointer StorageBuffer %10 -%28 = OpTypePointer StorageBuffer %11 -%29 = OpConstant %4 0 -%33 = OpTypePointer StorageBuffer %13 -%36 = OpTypePointer StorageBuffer %7 -%41 = OpTypePointer Function %15 -%44 = OpTypePointer Function %7 +%19 = OpTypePointer Function %15 +%22 = OpTypePointer Input %4 +%21 = OpVariable %22 Input +%25 = OpTypePointer Output %11 +%24 = OpVariable %25 Output +%27 = OpTypeFunction %2 +%29 = OpTypePointer StorageBuffer %10 +%30 = OpTypePointer StorageBuffer %11 +%31 = OpConstant %4 0 +%35 = OpTypePointer StorageBuffer %13 +%38 = OpTypePointer StorageBuffer %7 +%43 = OpTypePointer Function %7 %46 = OpTypeVector %7 4 -%24 = OpFunction %2 None %25 -%18 = OpLabel -%42 = OpVariable %41 Function -%21 = OpLoad %4 %19 -OpBranch %26 -%26 = OpLabel -%30 = OpAccessChain %28 %16 %29 %3 -%31 = OpLoad %11 %30 -%32 = OpCompositeExtract %12 %31 0 -%34 = OpArrayLength %4 %16 1 -%35 = OpISub %4 %34 %5 -%37 = OpAccessChain %36 %16 %5 %35 -%38 = OpLoad %7 %37 -%39 = OpConvertFToS %7 %32 -%40 = OpCompositeConstruct %15 %38 %39 %8 %9 %6 -OpStore %42 %40 -%43 = OpAccessChain %44 %42 %21 -%45 = OpLoad %7 %43 +%26 = OpFunction %2 None %27 +%20 = OpLabel +%18 = OpVariable %19 Function +%23 = OpLoad %4 %21 +OpBranch %28 +%28 = OpLabel +%32 = OpAccessChain %30 %16 %31 %3 +%33 = OpLoad %11 %32 +%34 = OpCompositeExtract %12 %33 0 +%36 = OpArrayLength %4 %16 1 +%37 = OpISub %4 %36 %5 +%39 = OpAccessChain %38 %16 %5 %37 +%40 = OpLoad %7 %39 +%41 = OpConvertFToS %7 %34 +%42 = OpCompositeConstruct %15 %40 %41 %8 %9 %6 +OpStore %18 %42 +%44 = OpAccessChain %43 %18 %23 +%45 = OpLoad %7 %44 %47 = OpCompositeConstruct %46 %45 %45 %45 %45 %48 = OpConvertSToF %11 %47 -OpStore %22 %48 +OpStore %24 %48 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/access.wgsl b/tests/out/access.wgsl index 9a75615ab..c0926ea80 100644 --- a/tests/out/access.wgsl +++ b/tests/out/access.wgsl @@ -9,9 +9,11 @@ var bar: [[access(read_write)]] Bar; [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { + var c: array; + let b: f32 = bar.matrix[3u].x; let a: i32 = bar.data[(arrayLength(&bar.data) - 1u)]; - let array: array = array(a, i32(b), 3, 4, 5); - let value: i32 = array[vi]; + c = array(a, i32(b), 3, 4, 5); + let value: i32 = c[vi]; return vec4(vec4(value)); } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index d11cef3f9..fb49a4056 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -314,3 +314,46 @@ fn missing_bindings() { }) } } + +#[test] +fn invalid_access() { + check_validation_error! { + " + fn array_by_value(a: array, i: i32) -> i32 { + return a[i]; + } + ", + " + fn matrix_by_value(m: mat4x4, i: i32) -> vec4 { + return m[i]; + } + ": + Err(naga::valid::ValidationError::Function { + error: naga::valid::FunctionError::Expression { + error: naga::valid::ExpressionError::IndexMustBeConstant(_), + .. + }, + .. + }) + } +} + +#[test] +fn valid_access() { + check_validation_error! { + " + fn vector_by_value(v: vec4, i: i32) -> i32 { + return v[i]; + } + ", + " + fn matrix_dynamic(m: mat4x4, i: i32, j: i32) -> f32 { + var temp: mat4x4 = m; + // Dynamically indexing the column vector applies + // `Access` to a `ValuePointer`. + return temp[i][j]; + } + ": + Ok(_) + } +} From 94cdaf685dec30aee9eb3bb73bc842afc09873f7 Mon Sep 17 00:00:00 2001 From: Matus Talcik Date: Sun, 6 Jun 2021 02:09:41 +0200 Subject: [PATCH 0923/2212] [spv-in] CFG: add break statements in switch selections (#951) --- src/front/spv/flow.rs | 67 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 54 insertions(+), 13 deletions(-) diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index e9dd5b835..12e748686 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -619,17 +619,47 @@ impl FlowGraph { accept_stop_nodes.insert(merge_node_index); accept_stop_nodes.insert(intended_merge); accept_stop_nodes.insert(then_end_index); + let mut reject_stop_nodes = stop_nodes.clone(); reject_stop_nodes.insert(merge_node_index); reject_stop_nodes.insert(intended_merge); reject_stop_nodes.insert(else_end_index); + let mut accept = + self.convert_to_naga_traverse(true_node_index, accept_stop_nodes)?; + let mut reject = + self.convert_to_naga_traverse(false_node_index, reject_stop_nodes)?; + + // If the true/false block of a header is breaking from switch or loop we add a break statement after its statements + for &mut (target_index, ref mut statements) in [ + (true_node_index, &mut accept), + (false_node_index, &mut reject), + ] + .iter_mut() + { + if let Some(ControlFlowNodeType::Break) = self.flow[target_index].ty { + let edge = *self + .flow + .edges_directed(target_index, Direction::Outgoing) + .next() + .unwrap() + .weight(); + if edge == ControlFlowEdgeType::SwitchBreak + || edge == ControlFlowEdgeType::LoopBreak + { + // Do not add break if already has one as the last statement + if let Some(&crate::Statement::Break) = statements.last() { + } else { + statements.push(crate::Statement::Break); + } + } + } + } + result.push(crate::Statement::If { condition, - accept: self - .convert_to_naga_traverse(true_node_index, accept_stop_nodes)?, - reject: self - .convert_to_naga_traverse(false_node_index, reject_stop_nodes)?, + accept, + reject, }); result.extend(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); @@ -852,21 +882,32 @@ impl FlowGraph { for node_index in self.flow.node_indices() { let node = &self.flow[node_index]; - let shape = if self.constructs[node.construct].ty == ConstructType::Case - && node.ty != Some(ControlFlowNodeType::Header) - { - "point" - } else { - "ellipse" + + let node_name = match node.ty { + Some(ControlFlowNodeType::Header) => { + if self.constructs[node.construct].ty == ConstructType::Case { + "Switch" + } else { + "If" + } + } + Some(ControlFlowNodeType::Loop) => "Loop", + Some(ControlFlowNodeType::Merge) => "", + Some(ControlFlowNodeType::Break) => "Break", + Some(ControlFlowNodeType::Continue) => "Continue", + Some(ControlFlowNodeType::Back) => "Back", + Some(ControlFlowNodeType::Kill) => "Kill", + Some(ControlFlowNodeType::Return) => "Return", + None => "Unlabeled", }; + writeln!( output, - "{} [ label = \"%{}({}) {:?}\" shape={} ]", + "{} [ label = \"%{}({}) {}\" shape=ellipse ]", node_index.index(), node.id, node_index.index(), - node.ty, - shape + node_name, )?; } From bfa2bbe590d9dad265d45ce9e79eb113f6974db5 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 4 Jun 2021 19:55:15 -0700 Subject: [PATCH 0924/2212] Snapshot quad-glsl to WGSL, not SPIR-V and IR. In tests/out, stop generating the uncommitted files quad-glsl.ron and quad-glsl.spvasm, and add the snapshot quad-glsl.wgsl. --- tests/out/quad-glsl.wgsl | 40 ++++++++++++++++++++++++++++++++++++++++ tests/snapshots.rs | 2 +- 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 tests/out/quad-glsl.wgsl diff --git a/tests/out/quad-glsl.wgsl b/tests/out/quad-glsl.wgsl new file mode 100644 index 000000000..dfadc6ec8 --- /dev/null +++ b/tests/out/quad-glsl.wgsl @@ -0,0 +1,40 @@ +struct VertexOutput { + [[location(0), interpolate(perspective)]] member: vec2; + [[builtin(position)]] member1: vec4; +}; + +struct FragmentOutput { + [[location(0), interpolate(perspective)]] member2: vec4; +}; + +var a_pos: vec2; +var a_uv: vec2; +var v_uv: vec2; +var gl_Position: vec4; +var v_uv1: vec2; +var o_color: vec4; + +fn vert_main() { + v_uv = a_uv; + gl_Position = vec4((1.2000000476837158 * a_pos), 0.0, 1.0); + return; +} + +fn frag_main() { + o_color = vec4(1.0, 1.0, 1.0, 1.0); + return; +} + +[[stage(vertex)]] +fn vert_main1([[location(0), interpolate(perspective)]] param: vec2, [[location(1), interpolate(perspective)]] param1: vec2) -> VertexOutput { + a_pos = param; + a_uv = param1; + vert_main(); + return VertexOutput(v_uv, gl_Position); +} + +[[stage(fragment)]] +fn frag_main1() -> FragmentOutput { + frag_main(); + return FragmentOutput(o_color); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 25c6887a6..a5aebfc69 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -421,5 +421,5 @@ fn convert_glsl_quad() { let mut entry_points = naga::FastHashMap::default(); entry_points.insert("vert_main".to_string(), naga::ShaderStage::Vertex); entry_points.insert("frag_main".to_string(), naga::ShaderStage::Fragment); - convert_glsl("quad-glsl", entry_points, Targets::SPIRV | Targets::IR); + convert_glsl("quad-glsl", entry_points, Targets::WGSL); } From be6a4172c5065a7c6db33c708664ae88a706072e Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 8 Jun 2021 17:15:26 +0300 Subject: [PATCH 0925/2212] Fix `Expression::Load` generating (#925) * [glsl-out] Fix writing named expressions with array types * [wgsl-out] Remove unsupported builtin from baked expression * [glsl-out] Add a newline between globals for readability * Set bake_ref_count to 1 for Expression::Load * Update snapshot data --- src/back/glsl/mod.rs | 19 +++- src/back/mod.rs | 4 + src/back/wgsl/writer.rs | 16 ++++ tests/in/access.wgsl | 5 ++ tests/out/access.msl | 13 ++- tests/out/access.spvasm | 143 ++++++++++++++++-------------- tests/out/access.wgsl | 6 +- tests/out/boids.Compute.glsl | 111 +++++++++++++++++------ tests/out/boids.msl | 108 ++++++++++++++++------ tests/out/boids.wgsl | 108 ++++++++++++++++------ tests/out/collatz.msl | 21 +++-- tests/out/collatz.wgsl | 21 +++-- tests/out/globals.Compute.glsl | 1 + tests/out/interpolate.Vertex.glsl | 17 ++-- tests/out/interpolate.msl | 3 +- tests/out/interpolate.wgsl | 3 +- tests/out/quad-glsl.wgsl | 13 ++- tests/out/quad-vert.Vertex.glsl | 14 ++- tests/out/quad-vert.msl | 10 ++- tests/out/quad-vert.wgsl | 7 +- tests/out/shadow.Fragment.glsl | 21 +++-- tests/out/shadow.msl | 19 ++-- tests/out/shadow.wgsl | 19 ++-- tests/out/skybox.Vertex.glsl | 13 ++- tests/out/skybox.msl | 10 ++- tests/out/skybox.wgsl | 12 ++- 26 files changed, 518 insertions(+), 219 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index fc7847e77..af8132b13 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -521,7 +521,11 @@ impl<'a, W: Write> Writer<'a, W> { // glsl has no concept of samplers so we just ignore it TypeInner::Sampler { .. } => continue, // All other globals are written by `write_global` - _ => self.write_global(handle, global)?, + _ => { + self.write_global(handle, global)?; + // Add a newline (only for readability) + writeln!(self.out)?; + } } } @@ -2130,7 +2134,18 @@ impl<'a, W: Write> Writer<'a, W> { self.write_value_type(inner)?; } } - write!(self.out, " {} = ", name)?; + + let base_ty_res = &ctx.info[handle].ty; + let resolved = base_ty_res.inner_with(&self.module.types); + + // If rhs is a array type, we should write temp variable as a dynamic array + let array_str = if let TypeInner::Array { .. } = *resolved { + "[]" + } else { + "" + }; + + write!(self.out, " {}{} = ", name, array_str)?; self.write_expr(handle, ctx)?; writeln!(self.out, ";")?; self.named_expressions.insert(handle, name); diff --git a/src/back/mod.rs b/src/back/mod.rs index 336833249..63f84d8f0 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -28,6 +28,10 @@ impl crate::Expression { crate::Expression::ImageSample { .. } | crate::Expression::ImageLoad { .. } => 1, // derivatives use the control flow crate::Expression::Derivative { .. } => 1, + // TODO: We need a better fix for named `Load` expressions + // More info - https://github.com/gfx-rs/naga/pull/914 + // And https://github.com/gfx-rs/naga/issues/910 + crate::Expression::Load { .. } => 1, // cache expressions that are referenced multiple times _ => 2, } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 488d0256b..6e996c6f9 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -605,6 +605,22 @@ impl Writer { _ => false, }; if min_ref_count <= func_ctx.info[handle].ref_count || required_baking_expr { + // If expression contains unsupported builtin we should skip it + if let Expression::Load { pointer } = func_ctx.expressions[handle] { + if let Expression::AccessIndex { base, index } = + func_ctx.expressions[pointer] + { + if access_to_unsupported_builtin( + base, + index, + module, + &func_ctx.info, + ) { + return Ok(()); + } + } + } + write!(self.out, "{}", INDENT.repeat(indent))?; self.write_baking_expr(module, handle, &func_ctx)?; writeln!(self.out, ";")?; diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index ec963e6df..dc5fb984f 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -11,6 +11,11 @@ var bar: [[access(read_write)]] Bar; [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { + var foo: f32 = 0.0; + // We should check that backed doesn't skip this expression + let baz: f32 = foo; + foo = 1.0; + let index = 3u; let b = bar.matrix[index].x; diff --git a/tests/out/access.msl b/tests/out/access.msl index 1fcde2582..af4a9feb3 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -10,7 +10,7 @@ struct Bar { metal::float4x4 matrix; type2 data; }; -struct type5 { +struct type6 { int inner[5]; }; @@ -24,7 +24,12 @@ vertex fooOutput foo( , device Bar& bar [[buffer(0)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - type5 c; - for(int _i=0; _i<5; ++_i) c.inner[_i] = type5 {bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u], static_cast(bar.matrix[3u].x), 3, 4, 5}.inner[_i]; - return fooOutput { static_cast(metal::int4(c.inner[vi])) }; + float foo1 = 0.0; + type6 c; + foo1 = 1.0; + metal::float4 _e9 = bar.matrix[3u]; + int _e17 = bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u]; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type6 {_e17, static_cast(_e9.x), 3, 4, 5}.inner[_i]; + int _e25 = c.inner[vi]; + return fooOutput { static_cast(metal::int4(_e25)) }; } diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm index 843872137..297b8a726 100644 --- a/tests/out/access.spvasm +++ b/tests/out/access.spvasm @@ -1,80 +1,87 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 49 +; Bound: 54 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %26 "foo" %21 %24 +OpEntryPoint Vertex %30 "foo" %25 %28 OpSource GLSL 450 -OpName %14 "Bar" -OpMemberName %14 0 "matrix" -OpMemberName %14 1 "data" -OpName %16 "bar" -OpName %18 "c" -OpName %21 "vi" -OpName %26 "foo" -OpDecorate %13 ArrayStride 4 -OpDecorate %14 Block -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 0 ColMajor -OpMemberDecorate %14 0 MatrixStride 16 -OpMemberDecorate %14 1 Offset 64 +OpName %16 "Bar" +OpMemberName %16 0 "matrix" +OpMemberName %16 1 "data" +OpName %18 "bar" +OpName %20 "foo" +OpName %22 "c" +OpName %25 "vi" +OpName %30 "foo" OpDecorate %15 ArrayStride 4 -OpDecorate %16 DescriptorSet 0 -OpDecorate %16 Binding 0 -OpDecorate %21 BuiltIn VertexIndex -OpDecorate %24 BuiltIn Position +OpDecorate %16 Block +OpMemberDecorate %16 0 Offset 0 +OpMemberDecorate %16 0 ColMajor +OpMemberDecorate %16 0 MatrixStride 16 +OpMemberDecorate %16 1 Offset 64 +OpDecorate %17 ArrayStride 4 +OpDecorate %18 DescriptorSet 0 +OpDecorate %18 Binding 0 +OpDecorate %25 BuiltIn VertexIndex +OpDecorate %28 BuiltIn Position %2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpConstant %4 3 -%5 = OpConstant %4 1 -%7 = OpTypeInt 32 1 -%6 = OpConstant %7 5 -%8 = OpConstant %7 3 -%9 = OpConstant %7 4 -%12 = OpTypeFloat 32 -%11 = OpTypeVector %12 4 -%10 = OpTypeMatrix %11 4 -%13 = OpTypeRuntimeArray %7 -%14 = OpTypeStruct %10 %13 -%15 = OpTypeArray %7 %6 -%17 = OpTypePointer StorageBuffer %14 -%16 = OpVariable %17 StorageBuffer -%19 = OpTypePointer Function %15 -%22 = OpTypePointer Input %4 -%21 = OpVariable %22 Input -%25 = OpTypePointer Output %11 -%24 = OpVariable %25 Output -%27 = OpTypeFunction %2 -%29 = OpTypePointer StorageBuffer %10 -%30 = OpTypePointer StorageBuffer %11 -%31 = OpConstant %4 0 -%35 = OpTypePointer StorageBuffer %13 -%38 = OpTypePointer StorageBuffer %7 -%43 = OpTypePointer Function %7 -%46 = OpTypeVector %7 4 -%26 = OpFunction %2 None %27 -%20 = OpLabel -%18 = OpVariable %19 Function -%23 = OpLoad %4 %21 -OpBranch %28 -%28 = OpLabel -%32 = OpAccessChain %30 %16 %31 %3 -%33 = OpLoad %11 %32 -%34 = OpCompositeExtract %12 %33 0 -%36 = OpArrayLength %4 %16 1 -%37 = OpISub %4 %36 %5 -%39 = OpAccessChain %38 %16 %5 %37 -%40 = OpLoad %7 %39 -%41 = OpConvertFToS %7 %34 -%42 = OpCompositeConstruct %15 %40 %41 %8 %9 %6 -OpStore %18 %42 -%44 = OpAccessChain %43 %18 %23 -%45 = OpLoad %7 %44 -%47 = OpCompositeConstruct %46 %45 %45 %45 %45 -%48 = OpConvertSToF %11 %47 -OpStore %24 %48 +%4 = OpTypeFloat 32 +%3 = OpConstant %4 0.0 +%5 = OpConstant %4 1.0 +%7 = OpTypeInt 32 0 +%6 = OpConstant %7 3 +%8 = OpConstant %7 1 +%10 = OpTypeInt 32 1 +%9 = OpConstant %10 5 +%11 = OpConstant %10 3 +%12 = OpConstant %10 4 +%14 = OpTypeVector %4 4 +%13 = OpTypeMatrix %14 4 +%15 = OpTypeRuntimeArray %10 +%16 = OpTypeStruct %13 %15 +%17 = OpTypeArray %10 %9 +%19 = OpTypePointer StorageBuffer %16 +%18 = OpVariable %19 StorageBuffer +%21 = OpTypePointer Function %4 +%23 = OpTypePointer Function %17 +%26 = OpTypePointer Input %7 +%25 = OpVariable %26 Input +%29 = OpTypePointer Output %14 +%28 = OpVariable %29 Output +%31 = OpTypeFunction %2 +%34 = OpTypePointer StorageBuffer %13 +%35 = OpTypePointer StorageBuffer %14 +%36 = OpConstant %7 0 +%40 = OpTypePointer StorageBuffer %15 +%43 = OpTypePointer StorageBuffer %10 +%48 = OpTypePointer Function %10 +%51 = OpTypeVector %10 4 +%30 = OpFunction %2 None %31 +%24 = OpLabel +%20 = OpVariable %21 Function %3 +%22 = OpVariable %23 Function +%27 = OpLoad %7 %25 +OpBranch %32 +%32 = OpLabel +%33 = OpLoad %4 %20 +OpStore %20 %5 +%37 = OpAccessChain %35 %18 %36 %6 +%38 = OpLoad %14 %37 +%39 = OpCompositeExtract %4 %38 0 +%41 = OpArrayLength %7 %18 1 +%42 = OpISub %7 %41 %8 +%44 = OpAccessChain %43 %18 %8 %42 +%45 = OpLoad %10 %44 +%46 = OpConvertFToS %10 %39 +%47 = OpCompositeConstruct %17 %45 %46 %11 %12 %9 +OpStore %22 %47 +%49 = OpAccessChain %48 %22 %27 +%50 = OpLoad %10 %49 +%52 = OpCompositeConstruct %51 %50 %50 %50 %50 +%53 = OpConvertSToF %14 %52 +OpStore %28 %53 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/access.wgsl b/tests/out/access.wgsl index c0926ea80..f05072bd7 100644 --- a/tests/out/access.wgsl +++ b/tests/out/access.wgsl @@ -9,9 +9,13 @@ var bar: [[access(read_write)]] Bar; [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { + var foo1: f32 = 0.0; var c: array; - let b: f32 = bar.matrix[3u].x; + let baz: f32 = foo1; + foo1 = 1.0; + let _e9: vec4 = bar.matrix[3u]; + let b: f32 = _e9.x; let a: i32 = bar.data[(arrayLength(&bar.data) - 1u)]; c = array(a, i32(b), 3, 4, 5); let value: i32 = c[vi]; diff --git a/tests/out/boids.Compute.glsl b/tests/out/boids.Compute.glsl index 9f32dbf80..9af204f3c 100644 --- a/tests/out/boids.Compute.glsl +++ b/tests/out/boids.Compute.glsl @@ -18,13 +18,16 @@ uniform SimParams_block_0 { float rule2Scale; float rule3Scale; } _group_0_binding_0; + readonly buffer Particles_block_1 { Particle particles[]; } _group_0_binding_1; + buffer Particles_block_2 { Particle particles[]; } _group_0_binding_2; + void main() { uvec3 global_invocation_id = gl_GlobalInvocationID; vec2 vPos; @@ -41,56 +44,108 @@ void main() { if((index >= 1500u)) { return; } - vPos = _group_0_binding_1.particles[index].pos; - vVel = _group_0_binding_1.particles[index].vel; + vec2 _expr10 = _group_0_binding_1.particles[index].pos; + vPos = _expr10; + vec2 _expr15 = _group_0_binding_1.particles[index].vel; + vVel = _expr15; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); while(true) { - if((i >= 1500u)) { + uint _expr37 = i; + if((_expr37 >= 1500u)) { break; } - if((i == index)) { + uint _expr39 = i; + if((_expr39 == index)) { continue; } - pos1 = _group_0_binding_1.particles[i].pos; - vel1 = _group_0_binding_1.particles[i].vel; - if((distance(pos1, vPos) < _group_0_binding_0.rule1Distance)) { - cMass = (cMass + pos1); - cMassCount = (cMassCount + 1); + uint _expr42 = i; + vec2 _expr45 = _group_0_binding_1.particles[_expr42].pos; + pos1 = _expr45; + uint _expr47 = i; + vec2 _expr50 = _group_0_binding_1.particles[_expr47].vel; + vel1 = _expr50; + vec2 _expr51 = pos1; + vec2 _expr52 = vPos; + float _expr55 = _group_0_binding_0.rule1Distance; + if((distance(_expr51, _expr52) < _expr55)) { + vec2 _expr57 = cMass; + vec2 _expr58 = pos1; + cMass = (_expr57 + _expr58); + int _expr60 = cMassCount; + cMassCount = (_expr60 + 1); } - if((distance(pos1, vPos) < _group_0_binding_0.rule2Distance)) { - colVel = (colVel - (pos1 - vPos)); + vec2 _expr63 = pos1; + vec2 _expr64 = vPos; + float _expr67 = _group_0_binding_0.rule2Distance; + if((distance(_expr63, _expr64) < _expr67)) { + vec2 _expr69 = colVel; + vec2 _expr70 = pos1; + vec2 _expr71 = vPos; + colVel = (_expr69 - (_expr70 - _expr71)); } - if((distance(pos1, vPos) < _group_0_binding_0.rule3Distance)) { - cVel = (cVel + vel1); - cVelCount = (cVelCount + 1); + vec2 _expr74 = pos1; + vec2 _expr75 = vPos; + float _expr78 = _group_0_binding_0.rule3Distance; + if((distance(_expr74, _expr75) < _expr78)) { + vec2 _expr80 = cVel; + vec2 _expr81 = vel1; + cVel = (_expr80 + _expr81); + int _expr83 = cVelCount; + cVelCount = (_expr83 + 1); } - i = (i + 1u); + uint _expr86 = i; + i = (_expr86 + 1u); } - if((cMassCount > 0)) { - cMass = ((cMass / vec2(float(cMassCount))) - vPos); + int _expr89 = cMassCount; + if((_expr89 > 0)) { + vec2 _expr92 = cMass; + int _expr93 = cMassCount; + vec2 _expr97 = vPos; + cMass = ((_expr92 / vec2(float(_expr93))) - _expr97); } - if((cVelCount > 0)) { - cVel = (cVel / vec2(float(cVelCount))); + int _expr99 = cVelCount; + if((_expr99 > 0)) { + vec2 _expr102 = cVel; + int _expr103 = cVelCount; + cVel = (_expr102 / vec2(float(_expr103))); } - vVel = (((vVel + (cMass * _group_0_binding_0.rule1Scale)) + (colVel * _group_0_binding_0.rule2Scale)) + (cVel * _group_0_binding_0.rule3Scale)); - vVel = (normalize(vVel) * clamp(length(vVel), 0.0, 0.1)); - vPos = (vPos + (vVel * _group_0_binding_0.deltaT)); - if((vPos.x < -1.0)) { + vec2 _expr107 = vVel; + vec2 _expr108 = cMass; + float _expr110 = _group_0_binding_0.rule1Scale; + vec2 _expr113 = colVel; + float _expr115 = _group_0_binding_0.rule2Scale; + vec2 _expr118 = cVel; + float _expr120 = _group_0_binding_0.rule3Scale; + vVel = (((_expr107 + (_expr108 * _expr110)) + (_expr113 * _expr115)) + (_expr118 * _expr120)); + vec2 _expr123 = vVel; + vec2 _expr125 = vVel; + vVel = (normalize(_expr123) * clamp(length(_expr125), 0.0, 0.1)); + vec2 _expr131 = vPos; + vec2 _expr132 = vVel; + float _expr134 = _group_0_binding_0.deltaT; + vPos = (_expr131 + (_expr132 * _expr134)); + vec2 _expr137 = vPos; + if((_expr137.x < -1.0)) { vPos.x = 1.0; } - if((vPos.x > 1.0)) { + vec2 _expr143 = vPos; + if((_expr143.x > 1.0)) { vPos.x = -1.0; } - if((vPos.y < -1.0)) { + vec2 _expr149 = vPos; + if((_expr149.y < -1.0)) { vPos.y = 1.0; } - if((vPos.y > 1.0)) { + vec2 _expr155 = vPos; + if((_expr155.y > 1.0)) { vPos.y = -1.0; } - _group_0_binding_2.particles[index].pos = vPos; - _group_0_binding_2.particles[index].vel = vVel; + vec2 _expr164 = vPos; + _group_0_binding_2.particles[index].pos = _expr164; + vec2 _expr168 = vVel; + _group_0_binding_2.particles[index].vel = _expr168; return; } diff --git a/tests/out/boids.msl b/tests/out/boids.msl index 05f0760f3..3f9f1a6d4 100644 --- a/tests/out/boids.msl +++ b/tests/out/boids.msl @@ -47,59 +47,111 @@ kernel void main1( if (global_invocation_id.x >= NUM_PARTICLES) { return; } - vPos = particlesSrc.particles[global_invocation_id.x].pos; - vVel = particlesSrc.particles[global_invocation_id.x].vel; + metal::float2 _e10 = particlesSrc.particles[global_invocation_id.x].pos; + vPos = _e10; + metal::float2 _e15 = particlesSrc.particles[global_invocation_id.x].vel; + vVel = _e15; cMass = metal::float2(0.0, 0.0); cVel = metal::float2(0.0, 0.0); colVel = metal::float2(0.0, 0.0); bool loop_init = true; while(true) { if (!loop_init) { - i = i + 1u; + metal::uint _e86 = i; + i = _e86 + 1u; } loop_init = false; - if (i >= NUM_PARTICLES) { + metal::uint _e37 = i; + if (_e37 >= NUM_PARTICLES) { break; } - if (i == global_invocation_id.x) { + metal::uint _e39 = i; + if (_e39 == global_invocation_id.x) { continue; } - pos1 = particlesSrc.particles[i].pos; - vel1 = particlesSrc.particles[i].vel; - if (metal::distance(pos1, vPos) < params.rule1Distance) { - cMass = cMass + pos1; - cMassCount = cMassCount + 1; + metal::uint _e42 = i; + metal::float2 _e45 = particlesSrc.particles[_e42].pos; + pos1 = _e45; + metal::uint _e47 = i; + metal::float2 _e50 = particlesSrc.particles[_e47].vel; + vel1 = _e50; + metal::float2 _e51 = pos1; + metal::float2 _e52 = vPos; + float _e55 = params.rule1Distance; + if (metal::distance(_e51, _e52) < _e55) { + metal::float2 _e57 = cMass; + metal::float2 _e58 = pos1; + cMass = _e57 + _e58; + int _e60 = cMassCount; + cMassCount = _e60 + 1; } - if (metal::distance(pos1, vPos) < params.rule2Distance) { - colVel = colVel - (pos1 - vPos); + metal::float2 _e63 = pos1; + metal::float2 _e64 = vPos; + float _e67 = params.rule2Distance; + if (metal::distance(_e63, _e64) < _e67) { + metal::float2 _e69 = colVel; + metal::float2 _e70 = pos1; + metal::float2 _e71 = vPos; + colVel = _e69 - (_e70 - _e71); } - if (metal::distance(pos1, vPos) < params.rule3Distance) { - cVel = cVel + vel1; - cVelCount = cVelCount + 1; + metal::float2 _e74 = pos1; + metal::float2 _e75 = vPos; + float _e78 = params.rule3Distance; + if (metal::distance(_e74, _e75) < _e78) { + metal::float2 _e80 = cVel; + metal::float2 _e81 = vel1; + cVel = _e80 + _e81; + int _e83 = cVelCount; + cVelCount = _e83 + 1; } } - if (cMassCount > 0) { - cMass = (cMass / metal::float2(static_cast(cMassCount))) - vPos; + int _e89 = cMassCount; + if (_e89 > 0) { + metal::float2 _e92 = cMass; + int _e93 = cMassCount; + metal::float2 _e97 = vPos; + cMass = (_e92 / metal::float2(static_cast(_e93))) - _e97; } - if (cVelCount > 0) { - cVel = cVel / metal::float2(static_cast(cVelCount)); + int _e99 = cVelCount; + if (_e99 > 0) { + metal::float2 _e102 = cVel; + int _e103 = cVelCount; + cVel = _e102 / metal::float2(static_cast(_e103)); } - vVel = ((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale); - vVel = metal::normalize(vVel) * metal::clamp(metal::length(vVel), 0.0, 0.1); - vPos = vPos + (vVel * params.deltaT); - if (vPos.x < -1.0) { + metal::float2 _e107 = vVel; + metal::float2 _e108 = cMass; + float _e110 = params.rule1Scale; + metal::float2 _e113 = colVel; + float _e115 = params.rule2Scale; + metal::float2 _e118 = cVel; + float _e120 = params.rule3Scale; + vVel = ((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120); + metal::float2 _e123 = vVel; + metal::float2 _e125 = vVel; + vVel = metal::normalize(_e123) * metal::clamp(metal::length(_e125), 0.0, 0.1); + metal::float2 _e131 = vPos; + metal::float2 _e132 = vVel; + float _e134 = params.deltaT; + vPos = _e131 + (_e132 * _e134); + metal::float2 _e137 = vPos; + if (_e137.x < -1.0) { vPos.x = 1.0; } - if (vPos.x > 1.0) { + metal::float2 _e143 = vPos; + if (_e143.x > 1.0) { vPos.x = -1.0; } - if (vPos.y < -1.0) { + metal::float2 _e149 = vPos; + if (_e149.y < -1.0) { vPos.y = 1.0; } - if (vPos.y > 1.0) { + metal::float2 _e155 = vPos; + if (_e155.y > 1.0) { vPos.y = -1.0; } - particlesDst.particles[global_invocation_id.x].pos = vPos; - particlesDst.particles[global_invocation_id.x].vel = vVel; + metal::float2 _e164 = vPos; + particlesDst.particles[global_invocation_id.x].pos = _e164; + metal::float2 _e168 = vVel; + particlesDst.particles[global_invocation_id.x].vel = _e168; return; } diff --git a/tests/out/boids.wgsl b/tests/out/boids.wgsl index a3591c6a7..e0d326599 100644 --- a/tests/out/boids.wgsl +++ b/tests/out/boids.wgsl @@ -45,57 +45,109 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { if ((index >= NUM_PARTICLES)) { return; } - vPos = particlesSrc.particles[index].pos; - vVel = particlesSrc.particles[index].vel; + let _e10: vec2 = particlesSrc.particles[index].pos; + vPos = _e10; + let _e15: vec2 = particlesSrc.particles[index].vel; + vVel = _e15; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); loop { - if ((i >= NUM_PARTICLES)) { + let _e37: u32 = i; + if ((_e37 >= NUM_PARTICLES)) { break; } - if ((i == index)) { + let _e39: u32 = i; + if ((_e39 == index)) { continue; } - pos1 = particlesSrc.particles[i].pos; - vel1 = particlesSrc.particles[i].vel; - if ((distance(pos1, vPos) < params.rule1Distance)) { - cMass = (cMass + pos1); - cMassCount = (cMassCount + 1); + let _e42: u32 = i; + let _e45: vec2 = particlesSrc.particles[_e42].pos; + pos1 = _e45; + let _e47: u32 = i; + let _e50: vec2 = particlesSrc.particles[_e47].vel; + vel1 = _e50; + let _e51: vec2 = pos1; + let _e52: vec2 = vPos; + let _e55: f32 = params.rule1Distance; + if ((distance(_e51, _e52) < _e55)) { + let _e57: vec2 = cMass; + let _e58: vec2 = pos1; + cMass = (_e57 + _e58); + let _e60: i32 = cMassCount; + cMassCount = (_e60 + 1); } - if ((distance(pos1, vPos) < params.rule2Distance)) { - colVel = (colVel - (pos1 - vPos)); + let _e63: vec2 = pos1; + let _e64: vec2 = vPos; + let _e67: f32 = params.rule2Distance; + if ((distance(_e63, _e64) < _e67)) { + let _e69: vec2 = colVel; + let _e70: vec2 = pos1; + let _e71: vec2 = vPos; + colVel = (_e69 - (_e70 - _e71)); } - if ((distance(pos1, vPos) < params.rule3Distance)) { - cVel = (cVel + vel1); - cVelCount = (cVelCount + 1); + let _e74: vec2 = pos1; + let _e75: vec2 = vPos; + let _e78: f32 = params.rule3Distance; + if ((distance(_e74, _e75) < _e78)) { + let _e80: vec2 = cVel; + let _e81: vec2 = vel1; + cVel = (_e80 + _e81); + let _e83: i32 = cVelCount; + cVelCount = (_e83 + 1); } continuing { - i = (i + 1u); + let _e86: u32 = i; + i = (_e86 + 1u); } } - if ((cMassCount > 0)) { - cMass = ((cMass / vec2(f32(cMassCount))) - vPos); + let _e89: i32 = cMassCount; + if ((_e89 > 0)) { + let _e92: vec2 = cMass; + let _e93: i32 = cMassCount; + let _e97: vec2 = vPos; + cMass = ((_e92 / vec2(f32(_e93))) - _e97); } - if ((cVelCount > 0)) { - cVel = (cVel / vec2(f32(cVelCount))); + let _e99: i32 = cVelCount; + if ((_e99 > 0)) { + let _e102: vec2 = cVel; + let _e103: i32 = cVelCount; + cVel = (_e102 / vec2(f32(_e103))); } - vVel = (((vVel + (cMass * params.rule1Scale)) + (colVel * params.rule2Scale)) + (cVel * params.rule3Scale)); - vVel = (normalize(vVel) * clamp(length(vVel), 0.0, 0.1)); - vPos = (vPos + (vVel * params.deltaT)); - if ((vPos.x < -1.0)) { + let _e107: vec2 = vVel; + let _e108: vec2 = cMass; + let _e110: f32 = params.rule1Scale; + let _e113: vec2 = colVel; + let _e115: f32 = params.rule2Scale; + let _e118: vec2 = cVel; + let _e120: f32 = params.rule3Scale; + vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); + let _e123: vec2 = vVel; + let _e125: vec2 = vVel; + vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.1)); + let _e131: vec2 = vPos; + let _e132: vec2 = vVel; + let _e134: f32 = params.deltaT; + vPos = (_e131 + (_e132 * _e134)); + let _e137: vec2 = vPos; + if ((_e137.x < -1.0)) { vPos.x = 1.0; } - if ((vPos.x > 1.0)) { + let _e143: vec2 = vPos; + if ((_e143.x > 1.0)) { vPos.x = -1.0; } - if ((vPos.y < -1.0)) { + let _e149: vec2 = vPos; + if ((_e149.y < -1.0)) { vPos.y = 1.0; } - if ((vPos.y > 1.0)) { + let _e155: vec2 = vPos; + if ((_e155.y > 1.0)) { vPos.y = -1.0; } - particlesDst.particles[index].pos = vPos; - particlesDst.particles[index].vel = vVel; + let _e164: vec2 = vPos; + particlesDst.particles[index].pos = _e164; + let _e168: vec2 = vVel; + particlesDst.particles[index].vel = _e168; return; } diff --git a/tests/out/collatz.msl b/tests/out/collatz.msl index b33506022..d687ae310 100644 --- a/tests/out/collatz.msl +++ b/tests/out/collatz.msl @@ -17,17 +17,23 @@ metal::uint collatz_iterations( metal::uint i = 0u; n = n_base; while(true) { - if (n <= 1u) { + metal::uint _e5 = n; + if (_e5 <= 1u) { break; } - if ((n % 2u) == 0u) { - n = n / 2u; + metal::uint _e8 = n; + if ((_e8 % 2u) == 0u) { + metal::uint _e13 = n; + n = _e13 / 2u; } else { - n = (3u * n) + 1u; + metal::uint _e17 = n; + n = (3u * _e17) + 1u; } - i = i + 1u; + metal::uint _e21 = i; + i = _e21 + 1u; } - return i; + metal::uint _e24 = i; + return _e24; } struct main1Input { @@ -36,7 +42,8 @@ kernel void main1( metal::uint3 global_id [[thread_position_in_grid]] , device PrimeIndices& v_indices [[user(fake0)]] ) { - metal::uint _e9 = collatz_iterations(v_indices.data[global_id.x]); + metal::uint _e8 = v_indices.data[global_id.x]; + metal::uint _e9 = collatz_iterations(_e8); v_indices.data[global_id.x] = _e9; return; } diff --git a/tests/out/collatz.wgsl b/tests/out/collatz.wgsl index e8c09d91c..b5d1cbbcd 100644 --- a/tests/out/collatz.wgsl +++ b/tests/out/collatz.wgsl @@ -12,22 +12,29 @@ fn collatz_iterations(n_base: u32) -> u32 { n = n_base; loop { - if ((n <= 1u)) { + let _e5: u32 = n; + if ((_e5 <= 1u)) { break; } - if (((n % 2u) == 0u)) { - n = (n / 2u); + let _e8: u32 = n; + if (((_e8 % 2u) == 0u)) { + let _e13: u32 = n; + n = (_e13 / 2u); } else { - n = ((3u * n) + 1u); + let _e17: u32 = n; + n = ((3u * _e17) + 1u); } - i = (i + 1u); + let _e21: u32 = i; + i = (_e21 + 1u); } - return i; + let _e24: u32 = i; + return _e24; } [[stage(compute), workgroup_size(1, 1, 1)]] fn main([[builtin(global_invocation_id)]] global_id: vec3) { - let _e9: u32 = collatz_iterations(v_indices.data[global_id.x]); + let _e8: u32 = v_indices.data[global_id.x]; + let _e9: u32 = collatz_iterations(_e8); v_indices.data[global_id.x] = _e9; return; } diff --git a/tests/out/globals.Compute.glsl b/tests/out/globals.Compute.glsl index 2fba504b7..9c68181b1 100644 --- a/tests/out/globals.Compute.glsl +++ b/tests/out/globals.Compute.glsl @@ -6,6 +6,7 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; shared float wg[10]; + void main() { wg[3] = 1.0; return; diff --git a/tests/out/interpolate.Vertex.glsl b/tests/out/interpolate.Vertex.glsl index e287089a1..5aefc78ed 100644 --- a/tests/out/interpolate.Vertex.glsl +++ b/tests/out/interpolate.Vertex.glsl @@ -28,14 +28,15 @@ void main() { out1.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); out1.perspective_centroid = 2197.0; out1.perspective_sample = 2744.0; - gl_Position = out1.position; - _vs2fs_location0 = out1.flat1; - _vs2fs_location1 = out1.linear; - _vs2fs_location2 = out1.linear_centroid; - _vs2fs_location3 = out1.linear_sample; - _vs2fs_location4 = out1.perspective; - _vs2fs_location5 = out1.perspective_centroid; - _vs2fs_location6 = out1.perspective_sample; + FragmentInput _expr30 = out1; + gl_Position = _expr30.position; + _vs2fs_location0 = _expr30.flat1; + _vs2fs_location1 = _expr30.linear; + _vs2fs_location2 = _expr30.linear_centroid; + _vs2fs_location3 = _expr30.linear_sample; + _vs2fs_location4 = _expr30.perspective; + _vs2fs_location5 = _expr30.perspective_centroid; + _vs2fs_location6 = _expr30.perspective_sample; return; } diff --git a/tests/out/interpolate.msl b/tests/out/interpolate.msl index 963e78b95..baec86cae 100644 --- a/tests/out/interpolate.msl +++ b/tests/out/interpolate.msl @@ -33,7 +33,8 @@ vertex main1Output main1( out.perspective = metal::float4(729.0, 1000.0, 1331.0, 1728.0); out.perspective_centroid = 2197.0; out.perspective_sample = 2744.0; - const auto _tmp = out; + FragmentInput _e30 = out; + const auto _tmp = _e30; return main1Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample }; } diff --git a/tests/out/interpolate.wgsl b/tests/out/interpolate.wgsl index ceebf56f2..45a7d0a4b 100644 --- a/tests/out/interpolate.wgsl +++ b/tests/out/interpolate.wgsl @@ -21,7 +21,8 @@ fn main() -> FragmentInput { out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); out.perspective_centroid = 2197.0; out.perspective_sample = 2744.0; - return out; + let _e30: FragmentInput = out; + return _e30; } [[stage(fragment)]] diff --git a/tests/out/quad-glsl.wgsl b/tests/out/quad-glsl.wgsl index dfadc6ec8..fccd8cc2a 100644 --- a/tests/out/quad-glsl.wgsl +++ b/tests/out/quad-glsl.wgsl @@ -15,8 +15,10 @@ var v_uv1: vec2; var o_color: vec4; fn vert_main() { - v_uv = a_uv; - gl_Position = vec4((1.2000000476837158 * a_pos), 0.0, 1.0); + let _e2: vec2 = a_pos; + let _e4: vec2 = a_uv; + v_uv = _e4; + gl_Position = vec4((1.2000000476837158 * _e2), 0.0, 1.0); return; } @@ -30,11 +32,14 @@ fn vert_main1([[location(0), interpolate(perspective)]] param: vec2, [[loca a_pos = param; a_uv = param1; vert_main(); - return VertexOutput(v_uv, gl_Position); + let _e5: vec2 = v_uv; + let _e7: vec4 = gl_Position; + return VertexOutput(_e5, _e7); } [[stage(fragment)]] fn frag_main1() -> FragmentOutput { frag_main(); - return FragmentOutput(o_color); + let _e1: vec4 = o_color; + return FragmentOutput(_e1); } diff --git a/tests/out/quad-vert.Vertex.glsl b/tests/out/quad-vert.Vertex.glsl index 40d321619..e6cbc6c86 100644 --- a/tests/out/quad-vert.Vertex.glsl +++ b/tests/out/quad-vert.Vertex.glsl @@ -11,20 +11,25 @@ struct type10 { }; vec2 v_uv = vec2(0, 0); + vec2 a_uv = vec2(0, 0); + struct gen_gl_PerVertex_block_0 { vec4 gen_gl_Position; float gen_gl_PointSize; float gen_gl_ClipDistance[1]; float gen_gl_CullDistance[1]; } perVertexStruct; + vec2 a_pos = vec2(0, 0); + layout(location = 1) in vec2 _p2vs_location1; layout(location = 0) in vec2 _p2vs_location0; smooth out vec2 _vs2fs_location0; void main1() { - v_uv = a_uv; + vec2 _expr12 = a_uv; + v_uv = _expr12; vec2 _expr13 = a_pos; perVertexStruct.gen_gl_Position = vec4(_expr13.x, _expr13.y, 0.0, 1.0); return; @@ -36,7 +41,12 @@ void main() { a_uv = a_uv1; a_pos = a_pos1; main1(); - type10 _tmp_return = type10(v_uv, perVertexStruct.gen_gl_Position, perVertexStruct.gen_gl_PointSize, perVertexStruct.gen_gl_ClipDistance, perVertexStruct.gen_gl_CullDistance); + vec2 _expr10 = v_uv; + vec4 _expr11 = perVertexStruct.gen_gl_Position; + float _expr12 = perVertexStruct.gen_gl_PointSize; + float _expr13[] = perVertexStruct.gen_gl_ClipDistance; + float _expr14[] = perVertexStruct.gen_gl_CullDistance; + type10 _tmp_return = type10(_expr10, _expr11, _expr12, _expr13, _expr14); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position1; return; diff --git a/tests/out/quad-vert.msl b/tests/out/quad-vert.msl index 16f2fbc83..d7195a141 100644 --- a/tests/out/quad-vert.msl +++ b/tests/out/quad-vert.msl @@ -27,7 +27,8 @@ void main1( thread gl_PerVertex& perVertexStruct, thread metal::float2 const& a_pos ) { - v_uv = a_uv; + metal::float2 _e12 = a_uv; + v_uv = _e12; metal::float2 _e13 = a_pos; perVertexStruct.gl_Position = metal::float4(_e13.x, _e13.y, 0.0, 1.0); return; @@ -55,6 +56,11 @@ vertex main2Output main2( a_uv = a_uv1; a_pos = a_pos1; main1(v_uv, a_uv, perVertexStruct, a_pos); - const auto _tmp = type10 {v_uv, perVertexStruct.gl_Position, perVertexStruct.gl_PointSize, perVertexStruct.gl_ClipDistance, perVertexStruct.gl_CullDistance}; + metal::float2 _e10 = v_uv; + metal::float4 _e11 = perVertexStruct.gl_Position; + float _e12 = perVertexStruct.gl_PointSize; + type6 _e13 = perVertexStruct.gl_ClipDistance; + type6 _e14 = perVertexStruct.gl_CullDistance; + const auto _tmp = type10 {_e10, _e11, _e12, _e13, _e14}; return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1.inner[0]} }; } diff --git a/tests/out/quad-vert.wgsl b/tests/out/quad-vert.wgsl index cadca2a4a..5ff06e857 100644 --- a/tests/out/quad-vert.wgsl +++ b/tests/out/quad-vert.wgsl @@ -14,7 +14,8 @@ var perVertexStruct: gl_PerVertex; var a_pos: vec2; fn main() { - v_uv = a_uv; + let _e12: vec2 = a_uv; + v_uv = _e12; let _e13: vec2 = a_pos; perVertexStruct.gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); return; @@ -25,5 +26,7 @@ fn main1([[location(1)]] a_uv1: vec2, [[location(0)]] a_pos1: vec2) -> a_uv = a_uv1; a_pos = a_pos1; main(); - return VertexOutput(v_uv, perVertexStruct.gl_Position); + let _e10: vec2 = v_uv; + let _e11: vec4 = perVertexStruct.gl_Position; + return VertexOutput(_e10, _e11); } diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index fa7ab0ca3..90ca7eea8 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -11,9 +11,11 @@ struct Light { uniform Globals_block_0 { uvec4 num_lights; } _group_0_binding_0; + readonly buffer Lights_block_1 { Light data[]; } _group_0_binding_1; + uniform highp sampler2DArrayShadow _group_0_binding_2; smooth in vec3 _vs2fs_location0; @@ -37,17 +39,24 @@ void main() { uint i = 0u; vec3 normal = normalize(raw_normal); while(true) { - if((i >= min(_group_0_binding_0.num_lights.x, 10u))) { + uint _expr12 = i; + uvec4 _expr14 = _group_0_binding_0.num_lights; + if((_expr12 >= min(_expr14.x, 10u))) { break; } - Light light = _group_0_binding_1.data[i]; - float _expr25 = fetch_shadow(i, (light.proj * position)); + uint _expr19 = i; + Light light = _group_0_binding_1.data[_expr19]; + uint _expr22 = i; + float _expr25 = fetch_shadow(_expr22, (light.proj * position)); vec3 light_dir = normalize((light.pos.xyz - position.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); - color1 = (color1 + ((_expr25 * diffuse) * light.color.xyz)); - i = (i + 1u); + vec3 _expr34 = color1; + color1 = (_expr34 + ((_expr25 * diffuse) * light.color.xyz)); + uint _expr40 = i; + i = (_expr40 + 1u); } - _fs2p_location0 = vec4(color1, 1.0); + vec3 _expr43 = color1; + _fs2p_location0 = vec4(_expr43, 1.0); return; } diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index ed9b5bc55..e7d24ea6a 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -54,15 +54,22 @@ fragment fs_mainOutput fs_main( bool loop_init = true; while(true) { if (!loop_init) { - i = i + 1u; + metal::uint _e40 = i; + i = _e40 + 1u; } loop_init = false; - if (i >= metal::min(u_globals.num_lights.x, c_max_lights)) { + metal::uint _e12 = i; + metal::uint4 _e14 = u_globals.num_lights; + if (_e12 >= metal::min(_e14.x, c_max_lights)) { break; } - Light _e21 = s_lights.data[i]; - float _e25 = fetch_shadow(i, _e21.proj * position, t_shadow, sampler_shadow); - color1 = color1 + ((_e25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(_e21.pos.xyz - position.xyz)))) * _e21.color.xyz); + metal::uint _e19 = i; + Light _e21 = s_lights.data[_e19]; + metal::uint _e22 = i; + float _e25 = fetch_shadow(_e22, _e21.proj * position, t_shadow, sampler_shadow); + metal::float3 _e34 = color1; + color1 = _e34 + ((_e25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(_e21.pos.xyz - position.xyz)))) * _e21.color.xyz); } - return fs_mainOutput { metal::float4(color1, 1.0) }; + metal::float3 _e43 = color1; + return fs_mainOutput { metal::float4(_e43, 1.0) }; } diff --git a/tests/out/shadow.wgsl b/tests/out/shadow.wgsl index 5325cf9fa..ef9ba9c37 100644 --- a/tests/out/shadow.wgsl +++ b/tests/out/shadow.wgsl @@ -43,17 +43,24 @@ fn fs_main([[location(0), interpolate(perspective)]] raw_normal: vec3, [[lo let normal: vec3 = normalize(raw_normal); loop { - if ((i >= min(u_globals.num_lights.x, c_max_lights))) { + let _e12: u32 = i; + let _e14: vec4 = u_globals.num_lights; + if ((_e12 >= min(_e14.x, c_max_lights))) { break; } - let light: Light = s_lights.data[i]; - let _e25: f32 = fetch_shadow(i, (light.proj * position)); + let _e19: u32 = i; + let light: Light = s_lights.data[_e19]; + let _e22: u32 = i; + let _e25: f32 = fetch_shadow(_e22, (light.proj * position)); let light_dir: vec3 = normalize((light.pos.xyz - position.xyz)); let diffuse: f32 = max(0.0, dot(normal, light_dir)); - color1 = (color1 + ((_e25 * diffuse) * light.color.xyz)); + let _e34: vec3 = color1; + color1 = (_e34 + ((_e25 * diffuse) * light.color.xyz)); continuing { - i = (i + 1u); + let _e40: u32 = i; + i = (_e40 + 1u); } } - return vec4(color1, 1.0); + let _e43: vec3 = color1; + return vec4(_e43, 1.0); } diff --git a/tests/out/skybox.Vertex.glsl b/tests/out/skybox.Vertex.glsl index dd00b450e..1c81eb42a 100644 --- a/tests/out/skybox.Vertex.glsl +++ b/tests/out/skybox.Vertex.glsl @@ -11,6 +11,7 @@ uniform Data_block_0 { mat4x4 proj_inv; mat4x4 view; } _group_0_binding_0; + smooth out vec3 _vs2fs_location0; void main() { @@ -19,9 +20,15 @@ void main() { int tmp2_; tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); - vec4 pos = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - mat3x3 inv_model_view = transpose(mat3x3(_group_0_binding_0.view[0].xyz, _group_0_binding_0.view[1].xyz, _group_0_binding_0.view[2].xyz)); - vec4 unprojected = (_group_0_binding_0.proj_inv * pos); + int _expr10 = tmp1_; + int _expr16 = tmp2_; + vec4 pos = vec4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); + vec4 _expr27 = _group_0_binding_0.view[0]; + vec4 _expr31 = _group_0_binding_0.view[1]; + vec4 _expr35 = _group_0_binding_0.view[2]; + mat3x3 inv_model_view = transpose(mat3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz)); + mat4x4 _expr40 = _group_0_binding_0.proj_inv; + vec4 unprojected = (_expr40 * pos); VertexOutput _tmp_return = VertexOutput(pos, (inv_model_view * unprojected.xyz)); gl_Position = _tmp_return.position; _vs2fs_location0 = _tmp_return.uv; diff --git a/tests/out/skybox.msl b/tests/out/skybox.msl index c3ba81213..813c3e6d2 100644 --- a/tests/out/skybox.msl +++ b/tests/out/skybox.msl @@ -24,8 +24,14 @@ vertex vs_mainOutput vs_main( int tmp2_; tmp1_ = static_cast(vertex_index) / 2; tmp2_ = static_cast(vertex_index) & 1; - metal::float4 _e24 = metal::float4((static_cast(tmp1_) * 4.0) - 1.0, (static_cast(tmp2_) * 4.0) - 1.0, 0.0, 1.0); - const auto _tmp = VertexOutput {_e24, metal::transpose(metal::float3x3(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz)) * (r_data.proj_inv * _e24).xyz}; + int _e10 = tmp1_; + int _e16 = tmp2_; + metal::float4 _e24 = metal::float4((static_cast(_e10) * 4.0) - 1.0, (static_cast(_e16) * 4.0) - 1.0, 0.0, 1.0); + metal::float4 _e27 = r_data.view[0]; + metal::float4 _e31 = r_data.view[1]; + metal::float4 _e35 = r_data.view[2]; + metal::float4x4 _e40 = r_data.proj_inv; + const auto _tmp = VertexOutput {_e24, metal::transpose(metal::float3x3(_e27.xyz, _e31.xyz, _e35.xyz)) * (_e40 * _e24).xyz}; return vs_mainOutput { _tmp.position, _tmp.uv }; } diff --git a/tests/out/skybox.wgsl b/tests/out/skybox.wgsl index 3df95a61c..83f170f8a 100644 --- a/tests/out/skybox.wgsl +++ b/tests/out/skybox.wgsl @@ -23,9 +23,15 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { tmp1_ = (i32(vertex_index) / 2); tmp2_ = (i32(vertex_index) & 1); - let pos: vec4 = vec4(((f32(tmp1_) * 4.0) - 1.0), ((f32(tmp2_) * 4.0) - 1.0), 0.0, 1.0); - let inv_model_view: mat3x3 = transpose(mat3x3(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz)); - let unprojected: vec4 = (r_data.proj_inv * pos); + let _e10: i32 = tmp1_; + let _e16: i32 = tmp2_; + let pos: vec4 = vec4(((f32(_e10) * 4.0) - 1.0), ((f32(_e16) * 4.0) - 1.0), 0.0, 1.0); + let _e27: vec4 = r_data.view[0]; + let _e31: vec4 = r_data.view[1]; + let _e35: vec4 = r_data.view[2]; + let inv_model_view: mat3x3 = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); + let _e40: mat4x4 = r_data.proj_inv; + let unprojected: vec4 = (_e40 * pos); return VertexOutput(pos, (inv_model_view * unprojected.xyz)); } From 9dcfe8fa4be3468aff44d7c324be3eb53da38741 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 8 Jun 2021 07:16:10 -0700 Subject: [PATCH 0926/2212] [spv-out]: Don't have write_expression_pointer return a storage class. (#958) Nobody uses that value. This lets us simplify `GlobalVariable` and `write_global_variable` as well. --- src/back/spv/writer.rs | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 57342be2f..73bc39d13 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -270,8 +270,6 @@ struct GlobalVariable { /// prelude block (and reset before every function) as `OpLoad` of the variable. /// It is then used for all the global ops, such as `OpImageSample`. handle_id: Word, - /// SPIR-V storage class. - class: spirv::StorageClass, } pub struct Writer { @@ -1180,7 +1178,7 @@ impl Writer { &mut self, ir_module: &crate::Module, global_variable: &crate::GlobalVariable, - ) -> Result<(Instruction, Word, spirv::StorageClass), Error> { + ) -> Result<(Instruction, Word), Error> { let id = self.id_gen.next(); let class = map_storage_class(global_variable.class); @@ -1215,7 +1213,7 @@ impl Writer { } // TODO Initializer is optional and not (yet) included in the IR - Ok((instruction, id, class)) + Ok((instruction, id)) } fn get_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { @@ -1768,7 +1766,7 @@ impl Writer { } crate::Expression::LocalVariable(variable) => function.variables[&variable].id, crate::Expression::Load { pointer } => { - let (pointer_id, _) = + let pointer_id = self.write_expression_pointer(ir_function, fun_info, pointer, block, function)?; let id = self.id_gen.next(); @@ -2275,7 +2273,7 @@ impl Writer { mut expr_handle: Handle, block: &mut Block, function: &mut Function, - ) -> Result<(Word, spirv::StorageClass), Error> { + ) -> Result { let result_lookup_ty = match fun_info[expr_handle].ty { TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), TypeResolution::Value(ref inner) => { @@ -2285,7 +2283,7 @@ impl Writer { let result_type_id = self.get_type_id(result_lookup_ty)?; self.temp_list.clear(); - let (root_id, class) = loop { + let root_id = loop { expr_handle = match ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { let index_id = self.cached[index]; @@ -2299,15 +2297,15 @@ impl Writer { } crate::Expression::GlobalVariable(handle) => { let gv = &self.global_variables[handle.index()]; - break (gv.id, gv.class); + break gv.id; } crate::Expression::LocalVariable(variable) => { let local_var = &function.variables[&variable]; - break (local_var.id, spirv::StorageClass::Function); + break local_var.id; } crate::Expression::FunctionArgument(index) => { let id = function.parameters[index as usize].result_id.unwrap(); - break (id, spirv::StorageClass::Function); + break id; } ref other => unimplemented!("Unexpected pointer expression {:?}", other), } @@ -2326,7 +2324,7 @@ impl Writer { )); id }; - Ok((id, class)) + Ok(id) } fn get_expression_global( @@ -2690,7 +2688,7 @@ impl Writer { )); } crate::Statement::Store { pointer, value } => { - let (pointer_id, _) = self.write_expression_pointer( + let pointer_id = self.write_expression_pointer( ir_function, fun_info, pointer, @@ -2854,13 +2852,10 @@ impl Writer { // now write all globals self.global_variables.clear(); for (_, var) in ir_module.global_variables.iter() { - let (instruction, id, class) = self.write_global_variable(ir_module, var)?; + let (instruction, id) = self.write_global_variable(ir_module, var)?; instruction.to_words(&mut self.logical_layout.declarations); - self.global_variables.push(GlobalVariable { - id, - handle_id: 0, - class, - }); + self.global_variables + .push(GlobalVariable { id, handle_id: 0 }); } // all functions From 575304a50c102f2e2a3a622b4be567c0ccf6e6c0 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 8 Jun 2021 19:09:46 +0300 Subject: [PATCH 0927/2212] [msl-out] Implement named expression generation (#957) --- src/back/msl/writer.rs | 48 ++++++++++++++++++++++++++++------------- tests/out/access.msl | 10 +++++---- tests/out/boids.msl | 13 +++++------ tests/out/image.msl | 37 ++++++++++++++++++++++++------- tests/out/interface.msl | 7 ++++-- tests/out/operators.msl | 4 +++- tests/out/quad.msl | 7 +++--- tests/out/shadow.msl | 13 +++++++---- tests/out/skybox.msl | 6 ++++-- tests/out/standard.msl | 8 +++---- 10 files changed, 104 insertions(+), 49 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 97da4de05..32c61cfd5 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -9,7 +9,6 @@ use crate::{ valid::{Capabilities, FunctionInfo, GlobalUse, ModuleInfo}, FastHashMap, }; -use bit_set::BitSet; use std::{ fmt::{Display, Error as FmtError, Formatter, Write}, iter, @@ -288,7 +287,7 @@ impl<'a> Display for ConstantContext<'a> { pub struct Writer { out: W, names: FastHashMap, - named_expressions: BitSet, + named_expressions: crate::NamedExpressions, namer: Namer, runtime_sized_buffers: FastHashMap, usize>, #[cfg(test)] @@ -449,7 +448,7 @@ impl Writer { Writer { out, names: FastHashMap::default(), - named_expressions: BitSet::new(), + named_expressions: crate::NamedExpressions::default(), namer: Namer::default(), runtime_sized_buffers: FastHashMap::default(), #[cfg(test)] @@ -710,8 +709,8 @@ impl Writer { self.put_expression_stack_pointers .insert(&expr_handle as *const _ as *const ()); - if self.named_expressions.contains(expr_handle.index()) { - write!(self.out, "{}{}", BAKE_PREFIX, expr_handle.index())?; + if let Some(name) = self.named_expressions.get(&expr_handle) { + write!(self.out, "{}", name)?; return Ok(()); } @@ -1244,6 +1243,7 @@ impl Writer { &mut self, handle: Handle, context: &ExpressionContext, + name: &str, ) -> Result<(), Error> { match context.info[handle].ty { TypeResolution::Handle(ty_handle) => { @@ -1285,7 +1285,8 @@ impl Writer { } //TODO: figure out the naming scheme that wouldn't collide with user names. - write!(self.out, " {}{} = ", BAKE_PREFIX, handle.index())?; + write!(self.out, " {} = ", name)?; + Ok(()) } @@ -1306,14 +1307,30 @@ impl Writer { match *statement { crate::Statement::Emit(ref range) => { for handle in range.clone() { - let min_ref_count = - context.expression.function.expressions[handle].bake_ref_count(); - if min_ref_count <= context.expression.info[handle].ref_count { + let expr_name = if let Some(name) = + context.expression.function.named_expressions.get(&handle) + { + // Front end provides names for all variables at the start of writing. + // But we write them to step by step. We need to recache them + // Otherwise, we could accidentally write variable name instead of full expression. + // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. + Some(self.namer.call_unique(name)) + } else { + let min_ref_count = + context.expression.function.expressions[handle].bake_ref_count(); + if min_ref_count <= context.expression.info[handle].ref_count { + Some(format!("{}{}", BAKE_PREFIX, handle.index())) + } else { + None + } + }; + + if let Some(name) = expr_name { write!(self.out, "{}", level)?; - self.start_baking_expression(handle, &context.expression)?; + self.start_baking_expression(handle, &context.expression, &name)?; self.put_expression(handle, &context.expression, true)?; + self.named_expressions.insert(handle, name); writeln!(self.out, ";")?; - self.named_expressions.insert(handle.index()); } } } @@ -1488,8 +1505,9 @@ impl Writer { } => { write!(self.out, "{}", level)?; if let Some(expr) = result { - self.start_baking_expression(expr, &context.expression)?; - self.named_expressions.insert(expr.index()); + let name = format!("{}{}", BAKE_PREFIX, expr.index()); + self.start_baking_expression(expr, &context.expression, &name)?; + self.named_expressions.insert(expr, name); } let fun_name = &self.names[&NameKey::Function(function)]; write!(self.out, "{}(", fun_name)?; @@ -1538,7 +1556,7 @@ impl Writer { for statement in statements { if let crate::Statement::Emit(ref range) = *statement { for handle in range.clone() { - self.named_expressions.remove(handle.index()); + self.named_expressions.remove(&handle); } } } @@ -2443,7 +2461,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 13600 - if stack_size < 11000 || stack_size > 14500 { + if stack_size < 11000 || stack_size > 16000 { panic!("`put_block` stack size {} has changed!", stack_size); } } diff --git a/tests/out/access.msl b/tests/out/access.msl index af4a9feb3..4ce5bb71e 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -26,10 +26,12 @@ vertex fooOutput foo( ) { float foo1 = 0.0; type6 c; + float baz = foo1; foo1 = 1.0; metal::float4 _e9 = bar.matrix[3u]; - int _e17 = bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u]; - for(int _i=0; _i<5; ++_i) c.inner[_i] = type6 {_e17, static_cast(_e9.x), 3, 4, 5}.inner[_i]; - int _e25 = c.inner[vi]; - return fooOutput { static_cast(metal::int4(_e25)) }; + float b = _e9.x; + int a = bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u]; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type6 {a, static_cast(b), 3, 4, 5}.inner[_i]; + int value = c.inner[vi]; + return fooOutput { static_cast(metal::int4(value)) }; } diff --git a/tests/out/boids.msl b/tests/out/boids.msl index 3f9f1a6d4..693d58d87 100644 --- a/tests/out/boids.msl +++ b/tests/out/boids.msl @@ -44,12 +44,13 @@ kernel void main1( metal::float2 pos1; metal::float2 vel1; metal::uint i = 0u; - if (global_invocation_id.x >= NUM_PARTICLES) { + uint index = global_invocation_id.x; + if (index >= NUM_PARTICLES) { return; } - metal::float2 _e10 = particlesSrc.particles[global_invocation_id.x].pos; + metal::float2 _e10 = particlesSrc.particles[index].pos; vPos = _e10; - metal::float2 _e15 = particlesSrc.particles[global_invocation_id.x].vel; + metal::float2 _e15 = particlesSrc.particles[index].vel; vVel = _e15; cMass = metal::float2(0.0, 0.0); cVel = metal::float2(0.0, 0.0); @@ -66,7 +67,7 @@ kernel void main1( break; } metal::uint _e39 = i; - if (_e39 == global_invocation_id.x) { + if (_e39 == index) { continue; } metal::uint _e42 = i; @@ -150,8 +151,8 @@ kernel void main1( vPos.y = -1.0; } metal::float2 _e164 = vPos; - particlesDst.particles[global_invocation_id.x].pos = _e164; + particlesDst.particles[index].pos = _e164; metal::float2 _e168 = vVel; - particlesDst.particles[global_invocation_id.x].vel = _e168; + particlesDst.particles[index].vel = _e168; return; } diff --git a/tests/out/image.msl b/tests/out/image.msl index e569e4504..d2f5bff06 100644 --- a/tests/out/image.msl +++ b/tests/out/image.msl @@ -9,9 +9,10 @@ kernel void main1( , metal::texture2d image_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 _e10 = (int2(image_src.get_width(), image_src.get_height()) * static_cast(local_id.xy)) % metal::int2(10, 20); - metal::uint4 _e11 = image_src.read(metal::uint2(_e10)); - image_dst.write(_e11, metal::uint(_e10.x)); + metal::int2 dim = int2(image_src.get_width(), image_src.get_height()); + metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); + metal::uint4 value = image_src.read(metal::uint2(itc)); + image_dst.write(value, metal::uint(itc.x)); return; } @@ -28,7 +29,27 @@ vertex queriesOutput queries( , metal::texture3d image_3d [[user(fake0)]] , metal::texture2d_ms image_aa [[user(fake0)]] ) { - return queriesOutput { metal::float4(static_cast((((((((((((((((((int(image_1d.get_width()) + int2(image_2d.get_width(), image_2d.get_height()).y) + int2(image_2d.get_width(1), image_2d.get_height(1)).y) + int2(image_2d_array.get_width(), image_2d_array.get_height()).y) + int2(image_2d_array.get_width(1), image_2d_array.get_height(1)).y) + int(image_2d_array.get_array_size())) + int3(image_cube.get_width()).y) + int3(image_cube.get_width(1)).y) + int3(image_cube_array.get_width()).y) + int3(image_cube_array.get_width(1)).y) + int(image_cube_array.get_array_size())) + int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()).z) + int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)).z) + int(image_aa.get_num_samples())) + int(image_2d.get_num_mip_levels())) + int(image_2d_array.get_num_mip_levels())) + int(image_3d.get_num_mip_levels())) + int(image_cube.get_num_mip_levels())) + int(image_cube_array.get_num_mip_levels()))) }; + int dim_1d = int(image_1d.get_width()); + metal::int2 dim_2d = int2(image_2d.get_width(), image_2d.get_height()); + int num_levels_2d = int(image_2d.get_num_mip_levels()); + metal::int2 dim_2d_lod = int2(image_2d.get_width(1), image_2d.get_height(1)); + metal::int2 dim_2d_array = int2(image_2d_array.get_width(), image_2d_array.get_height()); + int num_levels_2d_array = int(image_2d_array.get_num_mip_levels()); + metal::int2 dim_2d_array_lod = int2(image_2d_array.get_width(1), image_2d_array.get_height(1)); + int num_layers_2d = int(image_2d_array.get_array_size()); + metal::int3 dim_cube = int3(image_cube.get_width()); + int num_levels_cube = int(image_cube.get_num_mip_levels()); + metal::int3 dim_cube_lod = int3(image_cube.get_width(1)); + metal::int3 dim_cube_array = int3(image_cube_array.get_width()); + int num_levels_cube_array = int(image_cube_array.get_num_mip_levels()); + metal::int3 dim_cube_array_lod = int3(image_cube_array.get_width(1)); + int num_layers_cube = int(image_cube_array.get_array_size()); + metal::int3 dim_3d = int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()); + int num_levels_3d = int(image_3d.get_num_mip_levels()); + metal::int3 dim_3d_lod = int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)); + int num_samples_aa = int(image_aa.get_num_samples()); + int sum = (((((((((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + num_layers_2d) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + num_layers_cube) + dim_3d.z) + dim_3d_lod.z) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array; + return queriesOutput { metal::float4(static_cast(sum)) }; } @@ -39,8 +60,8 @@ fragment sample_comparisonOutput sample_comparison( metal::sampler sampler_cmp [[user(fake0)]] , metal::depth2d image_2d_depth [[user(fake0)]] ) { - metal::float2 _e12 = metal::float2(0.5); - float _e14 = image_2d_depth.sample_compare(sampler_cmp, _e12, 0.5); - float _e15 = image_2d_depth.sample_compare(sampler_cmp, _e12, 0.5); - return sample_comparisonOutput { _e14 + _e15 }; + metal::float2 tc = metal::float2(0.5); + float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc, 0.5); + float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc, 0.5); + return sample_comparisonOutput { s2d_depth + s2d_depth_level }; } diff --git a/tests/out/interface.msl b/tests/out/interface.msl index 970f81c0c..bd002be08 100644 --- a/tests/out/interface.msl +++ b/tests/out/interface.msl @@ -24,7 +24,8 @@ vertex vertex1Output vertex1( , metal::uint instance_index [[instance_id]] ) { const auto color1 = varyings.color1; - const auto _tmp = VertexOutput {metal::float4(1.0), static_cast((vertex_index + instance_index) + color1)}; + metal::uint tmp = (vertex_index + instance_index) + color1; + const auto _tmp = VertexOutput {metal::float4(1.0), static_cast(tmp)}; return vertex1Output { _tmp.position, _tmp.varying }; } @@ -45,7 +46,9 @@ fragment fragment1Output fragment1( , metal::uint sample_mask1 [[sample_mask]] ) { const VertexOutput in = { position, varyings1.varying }; - const auto _tmp = FragmentOutput {in.varying, sample_mask1 & (1u << sample_index), front_facing ? 0.0 : 1.0}; + metal::uint mask = sample_mask1 & (1u << sample_index); + float color2 = front_facing ? 0.0 : 1.0; + const auto _tmp = FragmentOutput {in.varying, mask, color2}; return fragment1Output { _tmp.depth, _tmp.sample_mask, _tmp.color }; } diff --git a/tests/out/operators.msl b/tests/out/operators.msl index 48c82bbca..4cddb70b5 100644 --- a/tests/out/operators.msl +++ b/tests/out/operators.msl @@ -4,7 +4,9 @@ metal::float4 splat( ) { - return (((metal::float2(1.0) + metal::float2(2.0)) - metal::float2(3.0)) / metal::float2(4.0)).xyxy + static_cast(metal::int4(5) % metal::int4(2)); + metal::float2 a = ((metal::float2(1.0) + metal::float2(2.0)) - metal::float2(3.0)) / metal::float2(4.0); + metal::int4 b = metal::int4(5) % metal::int4(2); + return a.xyxy + static_cast(b); } int unary( diff --git a/tests/out/quad.msl b/tests/out/quad.msl index 47238348b..53a5cb541 100644 --- a/tests/out/quad.msl +++ b/tests/out/quad.msl @@ -37,9 +37,10 @@ fragment main2Output main2( , metal::sampler u_sampler [[user(fake0)]] ) { const auto uv2 = varyings1.uv2; - metal::float4 _e4 = u_texture.sample(u_sampler, uv2); - if (_e4.w == 0.0) { + metal::float4 color = u_texture.sample(u_sampler, uv2); + if (color.w == 0.0) { metal::discard_fragment(); } - return main2Output { _e4.w * _e4 }; + metal::float4 premultiplied = color.w * color; + return main2Output { premultiplied }; } diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index e7d24ea6a..fc22233b7 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -29,7 +29,9 @@ float fetch_shadow( if (homogeneous_coords.w <= 0.0) { return 1.0; } - float _e26 = t_shadow.sample_compare(sampler_shadow, ((homogeneous_coords.xy * metal::float2(0.5, -0.5)) / metal::float2(homogeneous_coords.w)) + metal::float2(0.5, 0.5), static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); + metal::float2 flip_correction = metal::float2(0.5, -0.5); + metal::float2 light_local = ((homogeneous_coords.xy * flip_correction) / metal::float2(homogeneous_coords.w)) + metal::float2(0.5, 0.5); + float _e26 = t_shadow.sample_compare(sampler_shadow, light_local, static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); return _e26; } @@ -51,6 +53,7 @@ fragment fs_mainOutput fs_main( const auto position = varyings.position; metal::float3 color1 = c_ambient; metal::uint i = 0u; + metal::float3 normal = metal::normalize(raw_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -64,11 +67,13 @@ fragment fs_mainOutput fs_main( break; } metal::uint _e19 = i; - Light _e21 = s_lights.data[_e19]; + Light light = s_lights.data[_e19]; metal::uint _e22 = i; - float _e25 = fetch_shadow(_e22, _e21.proj * position, t_shadow, sampler_shadow); + float _e25 = fetch_shadow(_e22, light.proj * position, t_shadow, sampler_shadow); + metal::float3 light_dir = metal::normalize(light.pos.xyz - position.xyz); + float diffuse = metal::max(0.0, metal::dot(normal, light_dir)); metal::float3 _e34 = color1; - color1 = _e34 + ((_e25 * metal::max(0.0, metal::dot(metal::normalize(raw_normal), metal::normalize(_e21.pos.xyz - position.xyz)))) * _e21.color.xyz); + color1 = _e34 + ((_e25 * diffuse) * light.color.xyz); } metal::float3 _e43 = color1; return fs_mainOutput { metal::float4(_e43, 1.0) }; diff --git a/tests/out/skybox.msl b/tests/out/skybox.msl index 813c3e6d2..feec800e7 100644 --- a/tests/out/skybox.msl +++ b/tests/out/skybox.msl @@ -26,12 +26,14 @@ vertex vs_mainOutput vs_main( tmp2_ = static_cast(vertex_index) & 1; int _e10 = tmp1_; int _e16 = tmp2_; - metal::float4 _e24 = metal::float4((static_cast(_e10) * 4.0) - 1.0, (static_cast(_e16) * 4.0) - 1.0, 0.0, 1.0); + metal::float4 pos = metal::float4((static_cast(_e10) * 4.0) - 1.0, (static_cast(_e16) * 4.0) - 1.0, 0.0, 1.0); metal::float4 _e27 = r_data.view[0]; metal::float4 _e31 = r_data.view[1]; metal::float4 _e35 = r_data.view[2]; + metal::float3x3 inv_model_view = metal::transpose(metal::float3x3(_e27.xyz, _e31.xyz, _e35.xyz)); metal::float4x4 _e40 = r_data.proj_inv; - const auto _tmp = VertexOutput {_e24, metal::transpose(metal::float3x3(_e27.xyz, _e31.xyz, _e35.xyz)) * (_e40 * _e24).xyz}; + metal::float4 unprojected = _e40 * pos; + const auto _tmp = VertexOutput {pos, inv_model_view * unprojected.xyz}; return vs_mainOutput { _tmp.position, _tmp.uv }; } diff --git a/tests/out/standard.msl b/tests/out/standard.msl index 3909bef27..c102b47f7 100644 --- a/tests/out/standard.msl +++ b/tests/out/standard.msl @@ -10,8 +10,8 @@ struct derivativesOutput { fragment derivativesOutput derivatives( metal::float4 foo [[position]] ) { - metal::float4 _e1 = metal::dfdx(foo); - metal::float4 _e2 = metal::dfdy(foo); - metal::float4 _e3 = metal::fwidth(foo); - return derivativesOutput { (_e1 + _e2) * _e3 }; + metal::float4 x = metal::dfdx(foo); + metal::float4 y = metal::dfdy(foo); + metal::float4 z = metal::fwidth(foo); + return derivativesOutput { (x + y) * z }; } From 4af035edb797a3cd2d11fe0b86da3c202879e7fd Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 8 Jun 2021 20:21:13 +0300 Subject: [PATCH 0928/2212] [glsl-out] Simplify code for writing named expression --- src/back/glsl/mod.rs | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index af8132b13..68ee1c202 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1195,22 +1195,23 @@ impl<'a, W: Write> Writer<'a, W> { // This is where we can generate intermediate constants for some expression types. Statement::Emit(ref range) => { for handle in range.clone() { - if let Some(name) = ctx.named_expressions.get(&handle) { - write!(self.out, "{}", INDENT.repeat(indent))?; - + let expr_name = if let Some(name) = ctx.named_expressions.get(&handle) { // Front end provides names for all variables at the start of writing. - // But we write them to step by step. We need to recache them inside `write_named_expr` + // But we write them to step by step. We need to recache them // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. - let sanitized_name = self.namer.call_unique(name); - self.write_named_expr(handle, sanitized_name, ctx)?; - continue; - } + Some(self.namer.call_unique(name)) + } else { + let min_ref_count = ctx.expressions[handle].bake_ref_count(); + if min_ref_count <= ctx.info[handle].ref_count { + Some(format!("_expr{}", handle.index())) + } else { + None + } + }; - let min_ref_count = ctx.expressions[handle].bake_ref_count(); - if min_ref_count <= ctx.info[handle].ref_count { + if let Some(name) = expr_name { write!(self.out, "{}", INDENT.repeat(indent))?; - let name = format!("_expr{}", handle.index()); self.write_named_expr(handle, name, ctx)?; } } From b299a59bb5ddad16db938c138e2f1a85158e7021 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 8 Jun 2021 20:21:33 +0300 Subject: [PATCH 0929/2212] [wgsl-out] Simplify code for writing named expression --- src/back/wgsl/writer.rs | 93 +++++++++++++++++++---------------------- 1 file changed, 42 insertions(+), 51 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 6e996c6f9..517251ca4 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -580,49 +580,51 @@ impl Writer { match *stmt { Statement::Emit(ref range) => { for handle in range.clone() { - if let Some(name) = func_ctx.named_expressions.get(&handle) { - write!(self.out, "{}", INDENT.repeat(indent))?; - let sanitized_name = self.namer.call_unique(name); - self.start_named_expr(module, handle, &func_ctx, &sanitized_name)?; - self.write_expr(module, handle, &func_ctx)?; - writeln!(self.out, ";")?; - + let expr_name = if let Some(name) = func_ctx.named_expressions.get(&handle) { // Front end provides names for all variables at the start of writing. - // But we write them to step by step. We need to recache them. + // But we write them to step by step. We need to recache them // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. - self.named_expressions.insert(handle, sanitized_name); - continue; - } - - let expr = &func_ctx.expressions[handle]; - let min_ref_count = expr.bake_ref_count(); - // Forcefully creating baking expressions in some cases to help with readability - let required_baking_expr = match *expr { - Expression::ImageLoad { .. } - | Expression::ImageQuery { .. } - | Expression::ImageSample { .. } => true, - _ => false, - }; - if min_ref_count <= func_ctx.info[handle].ref_count || required_baking_expr { - // If expression contains unsupported builtin we should skip it - if let Expression::Load { pointer } = func_ctx.expressions[handle] { - if let Expression::AccessIndex { base, index } = - func_ctx.expressions[pointer] - { - if access_to_unsupported_builtin( - base, - index, - module, - &func_ctx.info, - ) { - return Ok(()); + Some(self.namer.call_unique(name)) + } else { + let expr = &func_ctx.expressions[handle]; + let min_ref_count = expr.bake_ref_count(); + // Forcefully creating baking expressions in some cases to help with readability + let required_baking_expr = match *expr { + Expression::ImageLoad { .. } + | Expression::ImageQuery { .. } + | Expression::ImageSample { .. } => true, + _ => false, + }; + if min_ref_count <= func_ctx.info[handle].ref_count || required_baking_expr + { + // If expression contains unsupported builtin we should skip it + if let Expression::Load { pointer } = func_ctx.expressions[handle] { + if let Expression::AccessIndex { base, index } = + func_ctx.expressions[pointer] + { + if access_to_unsupported_builtin( + base, + index, + module, + &func_ctx.info, + ) { + return Ok(()); + } } } - } + Some(format!("{}{}", BAKE_PREFIX, handle.index())) + } else { + None + } + }; + + if let Some(name) = expr_name { write!(self.out, "{}", INDENT.repeat(indent))?; - self.write_baking_expr(module, handle, &func_ctx)?; + self.start_named_expr(module, handle, &func_ctx, &name)?; + self.write_expr(module, handle, &func_ctx)?; + self.named_expressions.insert(handle, name); writeln!(self.out, ";")?; } } @@ -693,7 +695,10 @@ impl Writer { } => { write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { - self.write_baking_expr(module, expr, &func_ctx)?; + let name = format!("{}{}", BAKE_PREFIX, expr.index()); + self.start_named_expr(module, expr, func_ctx, &name)?; + self.write_expr(module, expr, func_ctx)?; + self.named_expressions.insert(expr, name); } let func_name = &self.names[&NameKey::Function(function)]; write!(self.out, "{}(", func_name)?; @@ -855,20 +860,6 @@ impl Writer { Ok(()) } - fn write_baking_expr( - &mut self, - module: &Module, - handle: Handle, - func_ctx: &FunctionCtx, - ) -> BackendResult { - let name = format!("{}{}", BAKE_PREFIX, handle.index()); - self.start_named_expr(module, handle, func_ctx, &name)?; - self.write_expr(module, handle, func_ctx)?; - self.named_expressions.insert(handle, name); - - Ok(()) - } - /// Helper method to write expressions /// /// # Notes From 38f6a799171b7ee173cbc5ed79815c40433144f4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 8 Jun 2021 17:35:20 -0400 Subject: [PATCH 0930/2212] [spv-out] fix image sampling ops, add more tests --- src/back/spv/writer.rs | 24 ++- tests/in/image.wgsl | 16 +- tests/out/image.msl | 19 +- tests/out/image.spvasm | 417 ++++++++++++++++++++++------------------- tests/out/image.wgsl | 14 +- 5 files changed, 288 insertions(+), 202 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 73bc39d13..62afb85fd 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1959,14 +1959,20 @@ impl Writer { inst } - crate::SampleLevel::Auto => Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Implicit, - sampled_image_id, - coordinate_id, - depth_id, - ), + crate::SampleLevel::Auto => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Implicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + if !mask.is_empty() { + inst.add_operand(mask.bits()); + } + inst + } crate::SampleLevel::Exact(lod_handle) => { let mut inst = Instruction::image_sample( sample_result_type_id, @@ -1996,6 +2002,7 @@ impl Writer { let bias_id = self.cached[bias_handle]; mask |= spirv::ImageOperands::BIAS; + inst.add_operand(mask.bits()); inst.add_operand(bias_id); inst @@ -2013,6 +2020,7 @@ impl Writer { let x_id = self.cached[x]; let y_id = self.cached[y]; mask |= spirv::ImageOperands::GRAD; + inst.add_operand(mask.bits()); inst.add_operand(x_id); inst.add_operand(y_id); diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 05cfe7505..67cddb4d4 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -60,8 +60,22 @@ fn queries() -> [[builtin(position)]] vec4 { } [[group(1), binding(0)]] -var sampler_cmp: sampler_comparison; +var sampler_reg: sampler; + +[[stage(fragment)]] +fn sample() -> [[location(0)]] vec4 { + let tc = vec2(0.5); + let level = 2.3; + let s2d = textureSample(image_2d, sampler_reg, tc); + let s2d_offset = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); + let s2d_level = textureSampleLevel(image_2d, sampler_reg, tc, level); + let s2d_level_offset = textureSampleLevel(image_2d, sampler_reg, tc, level, vec2(3, 1)); + return s2d + s2d_offset + s2d_level + s2d_level_offset; +} + [[group(1), binding(1)]] +var sampler_cmp: sampler_comparison; +[[group(1), binding(2)]] var image_2d_depth: texture_depth_2d; [[stage(fragment)]] diff --git a/tests/out/image.msl b/tests/out/image.msl index d2f5bff06..64aa1740e 100644 --- a/tests/out/image.msl +++ b/tests/out/image.msl @@ -1,6 +1,7 @@ #include #include +constant metal::int2 const_type3_ = {3, 1}; struct main1Input { }; @@ -53,8 +54,24 @@ vertex queriesOutput queries( } +struct sampleOutput { + metal::float4 member2 [[color(0)]]; +}; +fragment sampleOutput sample( + metal::texture2d image_2d [[user(fake0)]] +, metal::sampler sampler_reg [[user(fake0)]] +) { + metal::float2 tc = metal::float2(0.5); + metal::float4 s2d = image_2d.sample(sampler_reg, tc); + metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type3_); + metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.3)); + metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type3_); + return sampleOutput { ((s2d + s2d_offset) + s2d_level) + s2d_level_offset }; +} + + struct sample_comparisonOutput { - float member2 [[color(0)]]; + float member3 [[color(0)]]; }; fragment sample_comparisonOutput sample_comparison( metal::sampler sampler_cmp [[user(fake0)]] diff --git a/tests/out/image.spvasm b/tests/out/image.spvasm index d3d3b7fde..3e32829f7 100644 --- a/tests/out/image.spvasm +++ b/tests/out/image.spvasm @@ -1,60 +1,67 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 150 +; Bound: 174 OpCapability Image1D OpCapability Shader OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %50 "main" %47 -OpEntryPoint Vertex %68 "queries" %66 -OpEntryPoint Fragment %137 "sample_comparison" %135 -OpExecutionMode %50 LocalSize 16 1 1 -OpExecutionMode %137 OriginUpperLeft +OpEntryPoint GLCompute %55 "main" %52 +OpEntryPoint Vertex %73 "queries" %71 +OpEntryPoint Fragment %141 "sample" %140 +OpEntryPoint Fragment %162 "sample_comparison" %160 +OpExecutionMode %55 LocalSize 16 1 1 +OpExecutionMode %141 OriginUpperLeft +OpExecutionMode %162 OriginUpperLeft OpSource GLSL 450 -OpName %24 "image_src" -OpName %26 "image_dst" -OpName %28 "image_1d" -OpName %30 "image_2d" -OpName %32 "image_2d_array" -OpName %34 "image_cube" -OpName %36 "image_cube_array" -OpName %38 "image_3d" -OpName %40 "image_aa" -OpName %42 "sampler_cmp" -OpName %44 "image_2d_depth" -OpName %47 "local_id" -OpName %50 "main" -OpName %68 "queries" -OpName %137 "sample_comparison" -OpDecorate %24 NonWritable -OpDecorate %24 DescriptorSet 0 -OpDecorate %24 Binding 1 -OpDecorate %26 NonReadable -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 2 -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 0 -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 1 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 2 -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 3 -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 4 -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 5 -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 6 -OpDecorate %42 DescriptorSet 1 -OpDecorate %42 Binding 0 -OpDecorate %44 DescriptorSet 1 -OpDecorate %44 Binding 1 -OpDecorate %47 BuiltIn LocalInvocationId -OpDecorate %66 BuiltIn Position -OpDecorate %135 Location 0 +OpName %27 "image_src" +OpName %29 "image_dst" +OpName %31 "image_1d" +OpName %33 "image_2d" +OpName %35 "image_2d_array" +OpName %37 "image_cube" +OpName %39 "image_cube_array" +OpName %41 "image_3d" +OpName %43 "image_aa" +OpName %45 "sampler_reg" +OpName %47 "sampler_cmp" +OpName %49 "image_2d_depth" +OpName %52 "local_id" +OpName %55 "main" +OpName %73 "queries" +OpName %141 "sample" +OpName %162 "sample_comparison" +OpDecorate %27 NonWritable +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 1 +OpDecorate %29 NonReadable +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 2 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 0 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 1 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 2 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 3 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 4 +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 5 +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 6 +OpDecorate %45 DescriptorSet 1 +OpDecorate %45 Binding 0 +OpDecorate %47 DescriptorSet 1 +OpDecorate %47 Binding 1 +OpDecorate %49 DescriptorSet 1 +OpDecorate %49 Binding 2 +OpDecorate %52 BuiltIn LocalInvocationId +OpDecorate %71 BuiltIn Position +OpDecorate %140 Location 0 +OpDecorate %160 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -62,156 +69,184 @@ OpDecorate %135 Location 0 %6 = OpConstant %4 1 %8 = OpTypeFloat 32 %7 = OpConstant %8 0.5 -%10 = OpTypeInt 32 0 -%9 = OpTypeImage %10 2D 0 0 0 2 Rgba8ui -%11 = OpTypeImage %10 1D 0 0 0 2 R32ui -%12 = OpTypeVector %10 3 -%13 = OpTypeVector %4 2 -%14 = OpTypeImage %8 1D 0 0 0 1 Unknown -%15 = OpTypeImage %8 2D 0 0 0 1 Unknown -%16 = OpTypeImage %8 2D 0 1 0 1 Unknown -%17 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%18 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%19 = OpTypeImage %8 3D 0 0 0 1 Unknown -%20 = OpTypeImage %8 2D 0 0 1 1 Unknown -%21 = OpTypeVector %8 4 -%22 = OpTypeSampler -%23 = OpTypeImage %8 2D 1 0 0 1 Unknown -%25 = OpTypePointer UniformConstant %9 -%24 = OpVariable %25 UniformConstant -%27 = OpTypePointer UniformConstant %11 -%26 = OpVariable %27 UniformConstant -%29 = OpTypePointer UniformConstant %14 -%28 = OpVariable %29 UniformConstant -%31 = OpTypePointer UniformConstant %15 -%30 = OpVariable %31 UniformConstant -%33 = OpTypePointer UniformConstant %16 -%32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %17 -%34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %18 -%36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %19 -%38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %20 -%40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %22 -%42 = OpVariable %43 UniformConstant -%45 = OpTypePointer UniformConstant %23 -%44 = OpVariable %45 UniformConstant -%48 = OpTypePointer Input %12 -%47 = OpVariable %48 Input -%51 = OpTypeFunction %2 -%56 = OpTypeVector %10 2 -%62 = OpTypeVector %10 4 -%67 = OpTypePointer Output %21 -%66 = OpVariable %67 Output -%77 = OpConstant %10 0 -%82 = OpTypeVector %4 3 -%136 = OpTypePointer Output %8 -%135 = OpVariable %136 Output -%141 = OpTypeVector %8 2 -%143 = OpTypeSampledImage %23 -%148 = OpConstant %8 0.0 -%50 = OpFunction %2 None %51 -%46 = OpLabel -%49 = OpLoad %12 %47 -%52 = OpLoad %9 %24 -%53 = OpLoad %11 %26 -OpBranch %54 -%54 = OpLabel -%55 = OpImageQuerySize %13 %52 -%57 = OpVectorShuffle %56 %49 %49 0 1 -%58 = OpBitcast %13 %57 -%59 = OpIMul %13 %55 %58 -%60 = OpCompositeConstruct %13 %3 %5 -%61 = OpSMod %13 %59 %60 -%63 = OpImageRead %62 %52 %61 -%64 = OpCompositeExtract %4 %61 0 -OpImageWrite %53 %64 %63 +%9 = OpConstant %8 2.3 +%10 = OpConstant %4 3 +%12 = OpTypeInt 32 0 +%11 = OpTypeImage %12 2D 0 0 0 2 Rgba8ui +%13 = OpTypeImage %12 1D 0 0 0 2 R32ui +%14 = OpTypeVector %12 3 +%15 = OpTypeVector %4 2 +%16 = OpTypeImage %8 1D 0 0 0 1 Unknown +%17 = OpTypeImage %8 2D 0 0 0 1 Unknown +%18 = OpTypeImage %8 2D 0 1 0 1 Unknown +%19 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%20 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%21 = OpTypeImage %8 3D 0 0 0 1 Unknown +%22 = OpTypeImage %8 2D 0 0 1 1 Unknown +%23 = OpTypeVector %8 4 +%24 = OpTypeSampler +%25 = OpTypeImage %8 2D 1 0 0 1 Unknown +%26 = OpConstantComposite %15 %10 %6 +%28 = OpTypePointer UniformConstant %11 +%27 = OpVariable %28 UniformConstant +%30 = OpTypePointer UniformConstant %13 +%29 = OpVariable %30 UniformConstant +%32 = OpTypePointer UniformConstant %16 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %17 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %18 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %19 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %20 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %21 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %22 +%43 = OpVariable %44 UniformConstant +%46 = OpTypePointer UniformConstant %24 +%45 = OpVariable %46 UniformConstant +%48 = OpTypePointer UniformConstant %24 +%47 = OpVariable %48 UniformConstant +%50 = OpTypePointer UniformConstant %25 +%49 = OpVariable %50 UniformConstant +%53 = OpTypePointer Input %14 +%52 = OpVariable %53 Input +%56 = OpTypeFunction %2 +%61 = OpTypeVector %12 2 +%67 = OpTypeVector %12 4 +%72 = OpTypePointer Output %23 +%71 = OpVariable %72 Output +%82 = OpConstant %12 0 +%87 = OpTypeVector %4 3 +%140 = OpVariable %72 Output +%145 = OpTypeVector %8 2 +%147 = OpTypeSampledImage %17 +%161 = OpTypePointer Output %8 +%160 = OpVariable %161 Output +%167 = OpTypeSampledImage %25 +%172 = OpConstant %8 0.0 +%55 = OpFunction %2 None %56 +%51 = OpLabel +%54 = OpLoad %14 %52 +%57 = OpLoad %11 %27 +%58 = OpLoad %13 %29 +OpBranch %59 +%59 = OpLabel +%60 = OpImageQuerySize %15 %57 +%62 = OpVectorShuffle %61 %54 %54 0 1 +%63 = OpBitcast %15 %62 +%64 = OpIMul %15 %60 %63 +%65 = OpCompositeConstruct %15 %3 %5 +%66 = OpSMod %15 %64 %65 +%68 = OpImageRead %67 %57 %66 +%69 = OpCompositeExtract %4 %66 0 +OpImageWrite %58 %69 %68 OpReturn OpFunctionEnd -%68 = OpFunction %2 None %51 -%65 = OpLabel -%69 = OpLoad %14 %28 -%70 = OpLoad %15 %30 -%71 = OpLoad %16 %32 -%72 = OpLoad %17 %34 -%73 = OpLoad %18 %36 -%74 = OpLoad %19 %38 -%75 = OpLoad %20 %40 -OpBranch %76 -%76 = OpLabel -%78 = OpImageQuerySizeLod %4 %69 %77 -%79 = OpImageQuerySizeLod %13 %70 %77 -%80 = OpImageQueryLevels %4 %70 -%81 = OpImageQuerySizeLod %13 %70 %6 -%83 = OpImageQuerySizeLod %82 %71 %77 -%84 = OpVectorShuffle %13 %83 %83 0 1 -%85 = OpImageQueryLevels %4 %71 -%86 = OpImageQuerySizeLod %82 %71 %6 -%87 = OpVectorShuffle %13 %86 %86 0 1 -%88 = OpImageQuerySizeLod %82 %71 %77 -%89 = OpCompositeExtract %4 %88 2 -%90 = OpImageQuerySizeLod %13 %72 %77 -%91 = OpVectorShuffle %82 %90 %90 0 0 0 -%92 = OpImageQueryLevels %4 %72 -%93 = OpImageQuerySizeLod %13 %72 %6 -%94 = OpVectorShuffle %82 %93 %93 0 0 0 -%95 = OpImageQuerySizeLod %82 %73 %77 -%96 = OpImageQueryLevels %4 %73 -%97 = OpImageQuerySizeLod %82 %73 %6 -%98 = OpImageQuerySizeLod %82 %73 %77 -%99 = OpCompositeExtract %4 %98 2 -%100 = OpImageQuerySizeLod %82 %74 %77 -%101 = OpImageQueryLevels %4 %74 -%102 = OpImageQuerySizeLod %82 %74 %6 -%103 = OpImageQuerySamples %4 %75 -%104 = OpCompositeExtract %4 %79 1 -%105 = OpIAdd %4 %78 %104 -%106 = OpCompositeExtract %4 %81 1 -%107 = OpIAdd %4 %105 %106 -%108 = OpCompositeExtract %4 %84 1 -%109 = OpIAdd %4 %107 %108 -%110 = OpCompositeExtract %4 %87 1 -%111 = OpIAdd %4 %109 %110 -%112 = OpIAdd %4 %111 %89 -%113 = OpCompositeExtract %4 %91 1 +%73 = OpFunction %2 None %56 +%70 = OpLabel +%74 = OpLoad %16 %31 +%75 = OpLoad %17 %33 +%76 = OpLoad %18 %35 +%77 = OpLoad %19 %37 +%78 = OpLoad %20 %39 +%79 = OpLoad %21 %41 +%80 = OpLoad %22 %43 +OpBranch %81 +%81 = OpLabel +%83 = OpImageQuerySizeLod %4 %74 %82 +%84 = OpImageQuerySizeLod %15 %75 %82 +%85 = OpImageQueryLevels %4 %75 +%86 = OpImageQuerySizeLod %15 %75 %6 +%88 = OpImageQuerySizeLod %87 %76 %82 +%89 = OpVectorShuffle %15 %88 %88 0 1 +%90 = OpImageQueryLevels %4 %76 +%91 = OpImageQuerySizeLod %87 %76 %6 +%92 = OpVectorShuffle %15 %91 %91 0 1 +%93 = OpImageQuerySizeLod %87 %76 %82 +%94 = OpCompositeExtract %4 %93 2 +%95 = OpImageQuerySizeLod %15 %77 %82 +%96 = OpVectorShuffle %87 %95 %95 0 0 0 +%97 = OpImageQueryLevels %4 %77 +%98 = OpImageQuerySizeLod %15 %77 %6 +%99 = OpVectorShuffle %87 %98 %98 0 0 0 +%100 = OpImageQuerySizeLod %87 %78 %82 +%101 = OpImageQueryLevels %4 %78 +%102 = OpImageQuerySizeLod %87 %78 %6 +%103 = OpImageQuerySizeLod %87 %78 %82 +%104 = OpCompositeExtract %4 %103 2 +%105 = OpImageQuerySizeLod %87 %79 %82 +%106 = OpImageQueryLevels %4 %79 +%107 = OpImageQuerySizeLod %87 %79 %6 +%108 = OpImageQuerySamples %4 %80 +%109 = OpCompositeExtract %4 %84 1 +%110 = OpIAdd %4 %83 %109 +%111 = OpCompositeExtract %4 %86 1 +%112 = OpIAdd %4 %110 %111 +%113 = OpCompositeExtract %4 %89 1 %114 = OpIAdd %4 %112 %113 -%115 = OpCompositeExtract %4 %94 1 +%115 = OpCompositeExtract %4 %92 1 %116 = OpIAdd %4 %114 %115 -%117 = OpCompositeExtract %4 %95 1 -%118 = OpIAdd %4 %116 %117 -%119 = OpCompositeExtract %4 %97 1 -%120 = OpIAdd %4 %118 %119 -%121 = OpIAdd %4 %120 %99 -%122 = OpCompositeExtract %4 %100 2 +%117 = OpIAdd %4 %116 %94 +%118 = OpCompositeExtract %4 %96 1 +%119 = OpIAdd %4 %117 %118 +%120 = OpCompositeExtract %4 %99 1 +%121 = OpIAdd %4 %119 %120 +%122 = OpCompositeExtract %4 %100 1 %123 = OpIAdd %4 %121 %122 -%124 = OpCompositeExtract %4 %102 2 +%124 = OpCompositeExtract %4 %102 1 %125 = OpIAdd %4 %123 %124 -%126 = OpIAdd %4 %125 %103 -%127 = OpIAdd %4 %126 %80 -%128 = OpIAdd %4 %127 %85 -%129 = OpIAdd %4 %128 %101 -%130 = OpIAdd %4 %129 %92 -%131 = OpIAdd %4 %130 %96 -%132 = OpConvertSToF %8 %131 -%133 = OpCompositeConstruct %21 %132 %132 %132 %132 -OpStore %66 %133 +%126 = OpIAdd %4 %125 %104 +%127 = OpCompositeExtract %4 %105 2 +%128 = OpIAdd %4 %126 %127 +%129 = OpCompositeExtract %4 %107 2 +%130 = OpIAdd %4 %128 %129 +%131 = OpIAdd %4 %130 %108 +%132 = OpIAdd %4 %131 %85 +%133 = OpIAdd %4 %132 %90 +%134 = OpIAdd %4 %133 %106 +%135 = OpIAdd %4 %134 %97 +%136 = OpIAdd %4 %135 %101 +%137 = OpConvertSToF %8 %136 +%138 = OpCompositeConstruct %23 %137 %137 %137 %137 +OpStore %71 %138 OpReturn OpFunctionEnd -%137 = OpFunction %2 None %51 -%134 = OpLabel -%138 = OpLoad %22 %42 -%139 = OpLoad %23 %44 -OpBranch %140 -%140 = OpLabel -%142 = OpCompositeConstruct %141 %7 %7 -%144 = OpSampledImage %143 %139 %138 -%145 = OpImageSampleDrefImplicitLod %8 %144 %142 %7 -%146 = OpSampledImage %143 %139 %138 -%147 = OpImageSampleDrefExplicitLod %8 %146 %142 %7 Lod %148 -%149 = OpFAdd %8 %145 %147 -OpStore %135 %149 +%141 = OpFunction %2 None %56 +%139 = OpLabel +%142 = OpLoad %17 %33 +%143 = OpLoad %24 %45 +OpBranch %144 +%144 = OpLabel +%146 = OpCompositeConstruct %145 %7 %7 +%148 = OpSampledImage %147 %142 %143 +%149 = OpImageSampleImplicitLod %23 %148 %146 +%150 = OpSampledImage %147 %142 %143 +%151 = OpImageSampleImplicitLod %23 %150 %146 ConstOffset %26 +%152 = OpSampledImage %147 %142 %143 +%153 = OpImageSampleExplicitLod %23 %152 %146 Lod %9 +%154 = OpSampledImage %147 %142 %143 +%155 = OpImageSampleExplicitLod %23 %154 %146 Lod|ConstOffset %9 %26 +%156 = OpFAdd %23 %149 %151 +%157 = OpFAdd %23 %156 %153 +%158 = OpFAdd %23 %157 %155 +OpStore %140 %158 +OpReturn +OpFunctionEnd +%162 = OpFunction %2 None %56 +%159 = OpLabel +%163 = OpLoad %24 %47 +%164 = OpLoad %25 %49 +OpBranch %165 +%165 = OpLabel +%166 = OpCompositeConstruct %145 %7 %7 +%168 = OpSampledImage %167 %164 %163 +%169 = OpImageSampleDrefImplicitLod %8 %168 %166 %7 +%170 = OpSampledImage %167 %164 %163 +%171 = OpImageSampleDrefExplicitLod %8 %170 %166 %7 Lod %172 +%173 = OpFAdd %8 %169 %171 +OpStore %160 %173 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/image.wgsl b/tests/out/image.wgsl index f7e682c93..61c9fdfd8 100644 --- a/tests/out/image.wgsl +++ b/tests/out/image.wgsl @@ -17,8 +17,10 @@ var image_3d: texture_3d; [[group(0), binding(6)]] var image_aa: texture_multisampled_2d; [[group(1), binding(0)]] -var sampler_cmp: sampler_comparison; +var sampler_reg: sampler; [[group(1), binding(1)]] +var sampler_cmp: sampler_comparison; +[[group(1), binding(2)]] var image_2d_depth: texture_depth_2d; [[stage(compute), workgroup_size(16, 1, 1)]] @@ -55,6 +57,16 @@ fn queries() -> [[builtin(position)]] vec4 { return vec4(f32(sum)); } +[[stage(fragment)]] +fn sample() -> [[location(0)]] vec4 { + let tc: vec2 = vec2(0.5); + let s2d: vec4 = textureSample(image_2d, sampler_reg, tc); + let s2d_offset: vec4 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); + let s2d_level: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3); + let s2d_level_offset: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3, vec2(3, 1)); + return (((s2d + s2d_offset) + s2d_level) + s2d_level_offset); +} + [[stage(fragment)]] fn sample_comparison() -> [[location(0)]] f32 { let tc: vec2 = vec2(0.5); From be2231f6d959e5a7d906c441d8ddbdd2571efba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 8 Jun 2021 18:59:43 +0100 Subject: [PATCH 0931/2212] [wgsl-out] Write global initializers --- src/back/wgsl/writer.rs | 24 ++++++++++++++++++++++++ tests/out/quad-vert.wgsl | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 517251ca4..2a1c7fb54 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1341,6 +1341,13 @@ impl Writer { } // Write global type self.write_type(module, global.ty)?; + + // Write initializer + if let Some(init) = global.init { + write!(self.out, " = ")?; + self.write_constant(module, init)?; + } + // End with semicolon writeln!(self.out, ";")?; @@ -1368,8 +1375,25 @@ impl Writer { self.write_type(module, ty)?; write!(self.out, "(")?; + let members = match module.types[ty].inner { + TypeInner::Struct { ref members, .. } => Some(members), + _ => None, + }; + // Write the comma separated constants for (index, constant) in components.iter().enumerate() { + if let Some(&Binding::BuiltIn(builtin)) = + members.and_then(|members| members.get(index)?.binding.as_ref()) + { + if builtin_str(builtin).is_none() { + log::warn!( + "Skip constant for struct member with unsupported builtin {:?}", + builtin + ); + continue; + } + } + self.write_constant(module, *constant)?; // Only write a comma if isn't the last element if index != components.len().saturating_sub(1) { diff --git a/tests/out/quad-vert.wgsl b/tests/out/quad-vert.wgsl index 5ff06e857..92fab9dad 100644 --- a/tests/out/quad-vert.wgsl +++ b/tests/out/quad-vert.wgsl @@ -10,7 +10,7 @@ struct VertexOutput { var v_uv: vec2; var a_uv: vec2; -var perVertexStruct: gl_PerVertex; +var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), ); var a_pos: vec2; fn main() { From 54af83085552330b2fb3323971accfbd391da08b Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 8 Jun 2021 20:40:11 +0300 Subject: [PATCH 0932/2212] Fix nightly clippy suggestions --- src/back/msl/writer.rs | 6 +++--- src/back/wgsl/writer.rs | 30 +++++++++++++++--------------- src/front/glsl/ast.rs | 16 ++++++++-------- src/front/glsl/parser.rs | 7 +++---- src/front/spv/flow.rs | 36 +++++++++++++----------------------- src/front/spv/mod.rs | 4 ++-- src/front/wgsl/mod.rs | 17 ++++++----------- src/proc/interpolator.rs | 6 +++--- src/valid/interface.rs | 2 +- 9 files changed, 54 insertions(+), 70 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 32c61cfd5..e2664e13b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -853,7 +853,7 @@ impl Writer { members, span, index as usize, - &context.module, + context.module, ), _ => None, } @@ -2080,7 +2080,7 @@ impl Writer { _ => continue, }; varying_count += 1; - let name = &self.names[&name_key]; + let name = &self.names[name_key]; let ty_name = TypeContext { handle: ty, arena: &module.types, @@ -2177,7 +2177,7 @@ impl Writer { Some(ref binding @ &crate::Binding::BuiltIn(..)) => binding, _ => continue, }; - let name = &self.names[&name_key]; + let name = &self.names[name_key]; let ty_name = TypeContext { handle: ty, arena: &module.types, diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 2a1c7fb54..da7874cc2 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -118,13 +118,13 @@ impl Writer { // Write all constants for (handle, constant) in module.constants.iter() { if constant.name.is_some() { - self.write_global_constant(&module, &constant.inner, handle)?; + self.write_global_constant(module, &constant.inner, handle)?; } } // Write all globals for (ty, global) in module.global_variables.iter() { - self.write_global(&module, &global, ty)?; + self.write_global(module, global, ty)?; } if !module.global_variables.is_empty() { @@ -144,7 +144,7 @@ impl Writer { }; // Write the function - self.write_function(&module, &function, &func_ctx)?; + self.write_function(module, function, &func_ctx)?; writeln!(self.out)?; } @@ -165,11 +165,11 @@ impl Writer { let func_ctx = FunctionCtx { ty: FunctionType::EntryPoint(index as u16), - info: &info.get_entry_point(index), + info: info.get_entry_point(index), expressions: &ep.function.expressions, named_expressions: &ep.function.named_expressions, }; - self.write_function(&module, &ep.function, &func_ctx)?; + self.write_function(module, &ep.function, &func_ctx)?; if index < module.entry_points.len() - 1 { writeln!(self.out)?; @@ -288,7 +288,7 @@ impl Writer { write!(self.out, "var {}: ", self.names[&func_ctx.name_key(handle)])?; // Write the local type - self.write_type(&module, local.ty)?; + self.write_type(module, local.ty)?; // Write the local initializer if needed if let Some(init) = local.init { @@ -312,7 +312,7 @@ impl Writer { // Write the function body (statement list) for sta in func.body.iter() { // The indentation should always be 1 when writing the function body - self.write_stmt(&module, sta, &func_ctx, 1)?; + self.write_stmt(module, sta, func_ctx, 1)?; } writeln!(self.out, "}}")?; @@ -607,7 +607,7 @@ impl Writer { base, index, module, - &func_ctx.info, + func_ctx.info, ) { return Ok(()); } @@ -622,8 +622,8 @@ impl Writer { if let Some(name) = expr_name { write!(self.out, "{}", INDENT.repeat(indent))?; - self.start_named_expr(module, handle, &func_ctx, &name)?; - self.write_expr(module, handle, &func_ctx)?; + self.start_named_expr(module, handle, func_ctx, &name)?; + self.write_expr(module, handle, func_ctx)?; self.named_expressions.insert(handle, name); writeln!(self.out, ";")?; } @@ -664,7 +664,7 @@ impl Writer { if let Some(return_value) = value { // The leading space is important write!(self.out, " ")?; - self.write_expr(module, return_value, &func_ctx)?; + self.write_expr(module, return_value, func_ctx)?; } writeln!(self.out, ";")?; } @@ -678,7 +678,7 @@ impl Writer { // We already skip them when we generate struct type. // Now we need to find expression that used struct with ignored builtins if let Expression::AccessIndex { base, index } = func_ctx.expressions[pointer] { - if access_to_unsupported_builtin(base, index, module, &func_ctx.info) { + if access_to_unsupported_builtin(base, index, module, func_ctx.info) { return Ok(()); } } @@ -880,7 +880,7 @@ impl Writer { match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::Compose { ty, ref components } => { - self.write_type(&module, ty)?; + self.write_type(module, ty)?; write!(self.out, "(")?; // !spv-in specific notes! // WGSL does not support all SPIR-V builtins and we should skip it in generated shaders. @@ -900,7 +900,7 @@ impl Writer { if let Expression::AccessIndex { base, index } = func_ctx.expressions[pointer] { - if access_to_unsupported_builtin(base, index, module, &func_ctx.info) { + if access_to_unsupported_builtin(base, index, module, func_ctx.info) { skip_component = true; } } @@ -915,7 +915,7 @@ impl Writer { // non spv-in specific notes! // Real `Expression::Compose` logic generates here. for (index, component) in components_to_write.iter().enumerate() { - self.write_expr(module, *component, &func_ctx)?; + self.write_expr(module, *component, func_ctx)?; // Only write a comma if isn't the last element if index != components_to_write.len().saturating_sub(1) { // The leading space is for readability only diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index aca29951d..b3f9fbb4c 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -121,13 +121,13 @@ impl<'a> Program<'a> { constants: &self.module.constants, types: &self.module.types, global_vars: &self.module.global_variables, - local_vars: &context.locals, + local_vars: context.locals, functions: &self.module.functions, - arguments: &context.arguments, + arguments: context.arguments, }; match context .typifier - .grow(handle, &context.expressions, &resolve_ctx) + .grow(handle, context.expressions, &resolve_ctx) { //TODO: better error report Err(error) => Err(ErrorKind::SemanticError( @@ -148,13 +148,13 @@ impl<'a> Program<'a> { constants: &self.module.constants, types: &self.module.types, global_vars: &self.module.global_variables, - local_vars: &context.locals, + local_vars: context.locals, functions: &self.module.functions, - arguments: &context.arguments, + arguments: context.arguments, }; match context .typifier - .grow(handle, &context.expressions, &resolve_ctx) + .grow(handle, context.expressions, &resolve_ctx) { //TODO: better error report Err(error) => Err(ErrorKind::SemanticError( @@ -286,11 +286,11 @@ impl<'function> Context<'function> { } pub fn emit_start(&mut self) { - self.emitter.start(&self.expressions) + self.emitter.start(self.expressions) } pub fn emit_flush(&mut self, body: &mut Block) { - body.extend(self.emitter.finish(&self.expressions)) + body.extend(self.emitter.finish(self.expressions)) } pub fn add_expression(&mut self, expr: Expression, body: &mut Block) -> Handle { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index cf9eaf16b..61ad48730 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -513,9 +513,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // TODO: Should we try to make constants here? // This is mostly a hack because we don't yet support adding // bodies to entry points for variable initialization - let maybe_constant = init - .clone() - .and_then(|(root, meta)| self.program.solve_constant(ctx.ctx, root, meta).ok()); + let maybe_constant = + init.and_then(|(root, meta)| self.program.solve_constant(ctx.ctx, root, meta).ok()); let pointer = ctx.add_var(self.program, ty, name, maybe_constant, meta)?; @@ -1283,7 +1282,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let expr = self.parse_expression(ctx, body)?; let (root, meta) = ctx.lower_expect(self.program, expr, false, body)?; - let constant = self.program.solve_constant(&ctx, root, meta)?; + let constant = self.program.solve_constant(ctx, root, meta)?; match self.program.module.constants[constant].inner { ConstantInner::Scalar { diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index 12e748686..c7c8b82af 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -521,7 +521,7 @@ impl FlowGraph { lookup_expression: &FastHashMap, ) { for node_index in self.flow.node_indices() { - let phis = std::mem::replace(&mut self.flow[node_index].phis, Vec::new()); + let phis = std::mem::take(&mut self.flow[node_index].phis); for phi in phis.iter() { for &(variable_id, parent_id) in phi.variables.iter() { let variable = &lookup_expression[&variable_id]; @@ -612,8 +612,7 @@ impl FlowGraph { intended_merge }; - let mut result: crate::Block = - std::mem::replace(&mut self.flow[node_index].block, Vec::new()); + let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); let mut accept_stop_nodes = stop_nodes.clone(); accept_stop_nodes.insert(merge_node_index); @@ -673,8 +672,7 @@ impl FlowGraph { } => { let merge_node_index = self.block_to_node[&self.flow[node_index].merge.unwrap().merge_block_id]; - let mut result: crate::Block = - std::mem::replace(&mut self.flow[node_index].block, Vec::new()); + let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); let mut cases = Vec::with_capacity(targets.len()); let mut stop_nodes_cases = stop_nodes.clone(); @@ -731,11 +729,10 @@ impl FlowGraph { .unwrap() .target(); - std::mem::replace(&mut self.flow[continue_edge].block, Vec::new()) + std::mem::take(&mut self.flow[continue_edge].block) }; - let mut body: crate::Block = - std::mem::replace(&mut self.flow[node_index].block, Vec::new()); + let mut body: crate::Block = std::mem::take(&mut self.flow[node_index].block); let mut stop_nodes_merge = stop_nodes.clone(); stop_nodes_merge.insert(merge_node_index); @@ -780,8 +777,7 @@ impl FlowGraph { Ok(result) } Some(ControlFlowNodeType::Break) => { - let mut result: crate::Block = - std::mem::replace(&mut self.flow[node_index].block, Vec::new()); + let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); match self.flow[node_index].terminator { Terminator::BranchConditional { condition, @@ -838,12 +834,11 @@ impl FlowGraph { }; Ok(result) } - Some(ControlFlowNodeType::Continue) | Some(ControlFlowNodeType::Back) => Ok( - std::mem::replace(&mut self.flow[node_index].block, Vec::new()), - ), + Some(ControlFlowNodeType::Continue) | Some(ControlFlowNodeType::Back) => { + Ok(std::mem::take(&mut self.flow[node_index].block)) + } Some(ControlFlowNodeType::Kill) => { - let mut result: crate::Block = - std::mem::replace(&mut self.flow[node_index].block, Vec::new()); + let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); result.push(crate::Statement::Kill); Ok(result) } @@ -852,24 +847,19 @@ impl FlowGraph { Terminator::Return { value } => value, _ => return Err(Error::InvalidTerminator), }; - let mut result: crate::Block = - std::mem::replace(&mut self.flow[node_index].block, Vec::new()); + let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); result.push(crate::Statement::Return { value }); Ok(result) } Some(ControlFlowNodeType::Merge) | None => match self.flow[node_index].terminator { Terminator::Branch { target_id } => { - let mut result: crate::Block = - std::mem::replace(&mut self.flow[node_index].block, Vec::new()); + let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); result.extend( self.convert_to_naga_traverse(self.block_to_node[&target_id], stop_nodes)?, ); Ok(result) } - _ => Ok(std::mem::replace( - &mut self.flow[node_index].block, - Vec::new(), - )), + _ => Ok(std::mem::take(&mut self.flow[node_index].block)), }, } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 78100c067..0ad9a002e 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2215,7 +2215,7 @@ impl> Parser { } => { if let [S::Break] = reject[..] { // uplift "accept" into the parent - let extracted = mem::replace(accept, Vec::new()); + let extracted = mem::take(accept); statements.splice(i + 1..i + 1, extracted.into_iter()); } else { self.patch_statements(reject)?; @@ -2229,7 +2229,7 @@ impl> Parser { } => { if cases.is_empty() { // uplift "default" into the parent - let extracted = mem::replace(default, Vec::new()); + let extracted = mem::take(default); statements.splice(i + 1..i + 1, extracted.into_iter()); } else { for case in cases.iter_mut() { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index caabe9673..65abcd01d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1511,8 +1511,8 @@ impl Parser { (to_type, from_type) => { return Err(Error::BadTypeCast { span: arguments_span, - from_type: from_type.to_wgsl(&ctx.types, &ctx.constants), - to_type: to_type.to_wgsl(&ctx.types, &ctx.constants), + from_type: from_type.to_wgsl(ctx.types, ctx.constants), + to_type: to_type.to_wgsl(ctx.types, ctx.constants), }); } } @@ -1542,14 +1542,9 @@ impl Parser { let inner = match first_token_span { (Token::Word("true"), _) => crate::ConstantInner::boolean(true), (Token::Word("false"), _) => crate::ConstantInner::boolean(false), - ( - Token::Number { - ref value, - ref ty, - ref width, - }, - _, - ) => Self::get_constant_inner(*value, *ty, *width, first_token_span)?, + (Token::Number { value, ty, width }, _) => { + Self::get_constant_inner(value, ty, width, first_token_span)? + } (Token::Word(name), name_span) => { // look for an existing constant first for (handle, var) in const_arena.iter() { @@ -3213,7 +3208,7 @@ impl Parser { } (Token::Word("fn"), _) => { let (function, name) = - self.parse_function_decl(lexer, module, &lookup_global_expression)?; + self.parse_function_decl(lexer, module, lookup_global_expression)?; match stage { Some(stage) => module.entry_points.push(crate::EntryPoint { name: name.to_string(), diff --git a/src/proc/interpolator.rs b/src/proc/interpolator.rs index df48c0c3f..3b550782c 100644 --- a/src/proc/interpolator.rs +++ b/src/proc/interpolator.rs @@ -55,8 +55,8 @@ impl crate::Module { // // So, temporarily swap the member list out its type, assign appropriate // interpolations to its members, and then swap the list back in. - use std::mem::replace; - let mut members = replace(m, vec![]); + use std::mem; + let mut members = mem::take(m); for member in &mut members { default_binding_or_struct(&mut member.binding, member.ty, types); @@ -68,7 +68,7 @@ impl crate::Module { match types.get_mut(ty).inner { TypeInner::Struct { members: ref mut m, .. - } => replace(m, members), + } => mem::replace(m, members), _ => unreachable!("ty must be a struct"), }; diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 372d3ef0d..d4050aea1 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -413,7 +413,7 @@ impl super::Validator { crate::ShaderStage::Compute => ShaderStages::COMPUTE, }; - let info = self.validate_function(&ep.function, module, &mod_info)?; + let info = self.validate_function(&ep.function, module, mod_info)?; if !info.available_stages.contains(stage_bit) { return Err(EntryPointError::ForbiddenStageOperations); From 0184e1c87554a223420d721805345351c02a10fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 5 Jun 2021 00:27:00 +0100 Subject: [PATCH 0933/2212] [glsl-in] Add parsing for some modifiers Adds support for workgroup size and early fragment tests definitions --- src/front/glsl/ast.rs | 7 +++ src/front/glsl/functions.rs | 10 ++- src/front/glsl/parser.rs | 118 ++++++++++++++++++++++++------------ src/front/glsl/variables.rs | 12 ++-- 4 files changed, 100 insertions(+), 47 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index b3f9fbb4c..06918f76d 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -77,6 +77,9 @@ pub struct Program<'a> { pub profile: Profile, pub entry_points: &'a FastHashMap, + pub workgroup_size: [u32; 3], + pub early_fragment_tests: bool, + pub lookup_function: FastHashMap, pub lookup_type: FastHashMap>, @@ -98,6 +101,9 @@ impl<'a> Program<'a> { profile: Profile::Core, entry_points, + workgroup_size: [1; 3], + early_fragment_tests: false, + lookup_function: FastHashMap::default(), lookup_type: FastHashMap::default(), global_variables: Vec::new(), @@ -727,6 +733,7 @@ pub enum TypeQualifier { Interpolation(Interpolation), ResourceBinding(ResourceBinding), Location(u32), + WorkGroupSize(usize, u32), Sampling(Sampling), Layout(StructLayout), EarlyFragmentTests, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 8ccdc8c4a..6a9ee79c1 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -623,9 +623,13 @@ impl Program<'_> { self.module.entry_points.push(EntryPoint { name, stage, - // TODO - early_depth_test: None, - workgroup_size: [0; 3], + early_depth_test: Some(crate::EarlyDepthTest { conservative: None }) + .filter(|_| self.early_fragment_tests && stage == crate::ShaderStage::Fragment), + workgroup_size: if let crate::ShaderStage::Compute = stage { + self.workgroup_size + } else { + [0; 3] + }, function: Function { arguments, expressions, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 61ad48730..baaf5e6fb 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -178,7 +178,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }) } - fn parse_type_qualifiers(&mut self) -> Result> { + fn parse_type_qualifiers(&mut self) -> Result> { let mut qualifiers = Vec::new(); while self.peek_type_qualifier() { @@ -190,18 +190,21 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { continue; } - qualifiers.push(match token.value { - TokenValue::Interpolation(i) => TypeQualifier::Interpolation(i), - TokenValue::Const => TypeQualifier::StorageQualifier(StorageQualifier::Const), - TokenValue::In => TypeQualifier::StorageQualifier(StorageQualifier::Input), - TokenValue::Out => TypeQualifier::StorageQualifier(StorageQualifier::Output), - TokenValue::Uniform => TypeQualifier::StorageQualifier( - StorageQualifier::StorageClass(StorageClass::Uniform), - ), - TokenValue::Sampling(s) => TypeQualifier::Sampling(s), + qualifiers.push(( + match token.value { + TokenValue::Interpolation(i) => TypeQualifier::Interpolation(i), + TokenValue::Const => TypeQualifier::StorageQualifier(StorageQualifier::Const), + TokenValue::In => TypeQualifier::StorageQualifier(StorageQualifier::Input), + TokenValue::Out => TypeQualifier::StorageQualifier(StorageQualifier::Output), + TokenValue::Uniform => TypeQualifier::StorageQualifier( + StorageQualifier::StorageClass(StorageClass::Uniform), + ), + TokenValue::Sampling(s) => TypeQualifier::Sampling(s), - _ => unreachable!(), - }) + _ => unreachable!(), + }, + token.meta, + )) } Ok(qualifiers) @@ -209,7 +212,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_layout_qualifier_id_list( &mut self, - qualifiers: &mut Vec, + qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, ) -> Result<()> { // We need both of these to produce a ResourceBinding let mut group = None; @@ -228,12 +231,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.expect(TokenValue::RightParen)?; match (group, binding) { - (Some((group, _)), Some((binding, _))) => { - qualifiers.push(TypeQualifier::ResourceBinding(ResourceBinding { - group, - binding, - })) - } + (Some((group, group_meta)), Some((binding, binding_meta))) => qualifiers.push(( + TypeQualifier::ResourceBinding(ResourceBinding { group, binding }), + group_meta.union(&binding_meta), + )), // Produce an error if we have one of group or binding but not the other (Some((_, meta)), None) => { return Err(ErrorKind::SemanticError( @@ -278,7 +279,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_layout_qualifier_id( &mut self, - qualifiers: &mut Vec, + qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, group: &mut Option<(u32, SourceMetadata)>, binding: &mut Option<(u32, SourceMetadata)>, ) -> Result<()> { @@ -293,24 +294,42 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let (value, end_meta) = self.parse_uint_constant()?; token.meta = token.meta.union(&end_meta); - match name.as_str() { - "location" => qualifiers.push(TypeQualifier::Location(value)), - "set" => *group = Some((value, end_meta)), - "binding" => *binding = Some((value, end_meta)), - _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), - } + qualifiers.push(( + match name.as_str() { + "location" => TypeQualifier::Location(value), + "set" => { + *group = Some((value, end_meta)); + return Ok(()); + } + "binding" => { + *binding = Some((value, end_meta)); + return Ok(()); + } + "local_size_x" => TypeQualifier::WorkGroupSize(0, value), + "local_size_y" => TypeQualifier::WorkGroupSize(1, value), + "local_size_z" => TypeQualifier::WorkGroupSize(2, value), + _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), + }, + token.meta, + )) } else { match name.as_str() { "push_constant" => { - qualifiers.push(TypeQualifier::StorageQualifier( - StorageQualifier::StorageClass(StorageClass::PushConstant), + qualifiers.push(( + TypeQualifier::StorageQualifier(StorageQualifier::StorageClass( + StorageClass::PushConstant, + )), + token.meta, )); - qualifiers.push(TypeQualifier::Layout(StructLayout::Std430)); + qualifiers + .push((TypeQualifier::Layout(StructLayout::Std430), token.meta)); } - "std140" => qualifiers.push(TypeQualifier::Layout(StructLayout::Std140)), - "std430" => qualifiers.push(TypeQualifier::Layout(StructLayout::Std430)), + "std140" => qualifiers + .push((TypeQualifier::Layout(StructLayout::Std140), token.meta)), + "std430" => qualifiers + .push((TypeQualifier::Layout(StructLayout::Std430), token.meta)), "early_fragment_tests" => { - qualifiers.push(TypeQualifier::EarlyFragmentTests) + qualifiers.push((TypeQualifier::EarlyFragmentTests, token.meta)) } _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), } @@ -685,7 +704,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match token.value { TokenValue::Identifier(ty_name) => { if self.bump_if(TokenValue::LeftBrace).is_some() { - self.parse_block_declaration(&qualifiers, ty_name, token.meta) + self.parse_block_declaration(&qualifiers, ty_name) } else { //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON @@ -693,7 +712,31 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { todo!() } } - TokenValue::Semicolon => Ok(true), + TokenValue::Semicolon => { + for &(ref qualifier, meta) in qualifiers.iter() { + match *qualifier { + TypeQualifier::WorkGroupSize(i, value) => { + self.program.workgroup_size[i] = value + } + TypeQualifier::EarlyFragmentTests => { + self.program.early_fragment_tests = true; + } + TypeQualifier::StorageQualifier(_) => { + // TODO: Maybe add some checks here + // This is needed because of cases like + // layout(early_fragment_tests) in; + } + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Qualifier not supported as standalone".into(), + )); + } + } + } + + Ok(true) + } _ => Err(ErrorKind::InvalidToken(token)), } } @@ -705,15 +748,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_block_declaration( &mut self, - qualifiers: &[TypeQualifier], + qualifiers: &[(TypeQualifier, SourceMetadata)], ty_name: String, - meta: SourceMetadata, ) -> Result { let mut class = StorageClass::Private; let mut binding = None; let mut layout = None; - for qualifier in qualifiers { + for &(ref qualifier, meta) in qualifiers { match *qualifier { TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { if StorageClass::PushConstant == class && c == StorageClass::Uniform { @@ -1627,7 +1669,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } struct DeclarationContext<'ctx, 'fun> { - qualifiers: Vec, + qualifiers: Vec<(TypeQualifier, SourceMetadata)>, external: bool, ctx: &'ctx mut Context<'fun>, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 3b0c6df77..b0c51e6dd 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -9,7 +9,7 @@ use super::error::ErrorKind; use super::token::SourceMetadata; pub struct VarDeclaration<'a> { - pub qualifiers: &'a [TypeQualifier], + pub qualifiers: &'a [(TypeQualifier, SourceMetadata)], pub ty: Handle, pub name: String, pub init: Option>, @@ -229,7 +229,7 @@ impl Program<'_> { let mut sampling = None; let mut layout = None; - for qualifier in qualifiers { + for &(ref qualifier, meta) in qualifiers { match *qualifier { TypeQualifier::StorageQualifier(s) => { if StorageQualifier::StorageClass(StorageClass::Private) != storage { @@ -291,10 +291,10 @@ impl Program<'_> { layout = Some(l); } - TypeQualifier::EarlyFragmentTests => { + _ => { return Err(ErrorKind::SemanticError( meta, - "Cannot set early fragment tests on a declaration".into(), + "Qualifier not supported in globals".into(), )); } } @@ -417,7 +417,7 @@ impl Program<'_> { ty, name, init, - meta, + .. }: VarDeclaration, ) -> Result, ErrorKind> { #[cfg(feature = "glsl-validate")] @@ -427,7 +427,7 @@ impl Program<'_> { let mut mutable = true; - for qualifier in qualifiers { + for &(ref qualifier, meta) in qualifiers { match *qualifier { TypeQualifier::StorageQualifier(StorageQualifier::Const) => { if !mutable { From 803cb31fb0fff6656b2389c394abcc056739daed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 5 Jun 2021 00:37:51 +0100 Subject: [PATCH 0934/2212] [glsl-in] Add support for buffer class --- src/front/glsl/lex.rs | 1 + src/front/glsl/parser.rs | 4 ++++ src/front/glsl/token.rs | 1 + 3 files changed, 6 insertions(+) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index b98997242..fb203dd6c 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -62,6 +62,7 @@ impl<'a> Iterator for Lexer<'a> { "in" => TokenValue::In, "out" => TokenValue::Out, "uniform" => TokenValue::Uniform, + "buffer" => TokenValue::Buffer, "flat" => TokenValue::Interpolation(crate::Interpolation::Flat), "noperspective" => TokenValue::Interpolation(crate::Interpolation::Linear), "smooth" => TokenValue::Interpolation(crate::Interpolation::Perspective), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index baaf5e6fb..c3bd80733 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -173,6 +173,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { | TokenValue::In | TokenValue::Out | TokenValue::Uniform + | TokenValue::Buffer | TokenValue::Layout => true, _ => false, }) @@ -199,6 +200,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Uniform => TypeQualifier::StorageQualifier( StorageQualifier::StorageClass(StorageClass::Uniform), ), + TokenValue::Buffer => TypeQualifier::StorageQualifier( + StorageQualifier::StorageClass(StorageClass::Storage), + ), TokenValue::Sampling(s) => TypeQualifier::Sampling(s), _ => unreachable!(), diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 16a745e35..7d01ffb77 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -53,6 +53,7 @@ pub enum TokenValue { Out, InOut, Uniform, + Buffer, Const, Interpolation(Interpolation), Sampling(Sampling), From a5b2486a9b44f9b654e60527f1c81586a0ab72bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 5 Jun 2021 00:50:12 +0100 Subject: [PATCH 0935/2212] [glsl-in] Add mod function --- src/front/glsl/functions.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 6a9ee79c1..0c7457341 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -239,6 +239,30 @@ impl Program<'_> { body, ))) } + "mod" => { + if args.len() != 2 { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + + let expr = if let Some(ScalarKind::Float) = + self.resolve_type(ctx, args[0].0, args[1].1)?.scalar_kind() + { + Expression::Math { + fun: MathFunction::Modf, + arg: args[0].0, + arg1: Some(args[1].0), + arg2: None, + } + } else { + Expression::Binary { + op: BinaryOperator::Modulo, + left: args[0].0, + right: args[1].0, + } + }; + + Ok(Some(ctx.add_expression(expr, body))) + } "pow" | "dot" | "max" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); From a9dad25b0f2e00c0c1a8da084f077039916454b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 6 Jun 2021 13:49:27 +0100 Subject: [PATCH 0936/2212] [glsl-in] Implement increment and decrement ops --- src/front/glsl/ast.rs | 94 ++++++++++++++++++++++++++++++++++++++++ src/front/glsl/parser.rs | 45 ++++++++++++++++++- 2 files changed, 137 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 06918f76d..11b0652c2 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -580,6 +580,95 @@ impl<'function> Context<'function> { value } + HirExprKind::IncDec { + increment, + postfix, + expr, + } => { + let op = match increment { + true => BinaryOperator::Add, + false => BinaryOperator::Subtract, + }; + + let pointer = self.lower_expect(program, expr, true, body)?.0; + let left = self.add_expression(Expression::Load { pointer }, body); + + let uint = if let Some(kind) = program.resolve_type(self, left, meta)?.scalar_kind() + { + match kind { + ScalarKind::Sint => false, + ScalarKind::Uint => true, + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Increment/decrement operations must operate in integers".into(), + )) + } + } + } else { + return Err(ErrorKind::SemanticError( + meta, + "Increment/decrement operations must operate in integers".into(), + )); + }; + + let one = program.module.constants.append(Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: match uint { + true => crate::ScalarValue::Uint(1), + false => crate::ScalarValue::Sint(1), + }, + }, + }); + let right = self.add_expression(Expression::Constant(one), body); + + let value = self.add_expression(Expression::Binary { op, left, right }, body); + + if postfix { + let local = self.locals.append(LocalVariable { + name: None, + ty: program.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: match uint { + true => ScalarKind::Uint, + false => ScalarKind::Sint, + }, + width: 4, + }, + }), + init: None, + }); + + let expr = self.add_expression(Expression::LocalVariable(local), body); + let load = self.add_expression(Expression::Load { pointer: expr }, body); + + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { + pointer: expr, + value: left, + }); + + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { pointer, value }); + + load + } else { + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { pointer, value }); + + left + } + } _ => { return Err(ErrorKind::SemanticError( meta, @@ -725,6 +814,11 @@ pub enum HirExprKind { tgt: Handle, value: Handle, }, + IncDec { + increment: bool, + postfix: bool, + expr: Handle, + }, } #[derive(Debug)] diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index c3bd80733..8353f8f74 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1025,8 +1025,11 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { _ => self.parse_primary(ctx, body)?, }; - // TODO: postfix inc/dec - while let TokenValue::LeftBracket | TokenValue::Dot = self.expect_peek()?.value { + while let TokenValue::LeftBracket + | TokenValue::Dot + | TokenValue::Increment + | TokenValue::Decrement = self.expect_peek()?.value + { let Token { value, meta } = self.bump()?; match value { @@ -1047,6 +1050,26 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta: meta.union(&end_meta), }) } + TokenValue::Increment => { + base = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::IncDec { + increment: true, + postfix: true, + expr: base, + }, + meta, + }) + } + TokenValue::Decrement => { + base = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::IncDec { + increment: false, + postfix: true, + expr: base, + }, + meta, + }) + } _ => unreachable!(), } } @@ -1080,6 +1103,24 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta: meta.union(&end_meta), }) } + TokenValue::Increment | TokenValue::Decrement => { + let Token { value, meta } = self.bump()?; + + let expr = self.parse_unary(ctx, body)?; + + ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::IncDec { + increment: match value { + TokenValue::Increment => true, + TokenValue::Decrement => false, + _ => unreachable!(), + }, + postfix: false, + expr, + }, + meta, + }) + } _ => self.parse_postfix(ctx, body)?, }) } From 2023b1a72c77914d7a63e949c28ceedc7a0989bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 6 Jun 2021 14:26:19 +0100 Subject: [PATCH 0937/2212] [glsl-in] Implicit convert initializers --- src/front/glsl/parser.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 8353f8f74..fa50d9941 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -527,8 +527,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let init = self .bump_if(TokenValue::Assign) .map::, _>(|_| { - let (expr, init_meta) = self.parse_initializer(ty, ctx.ctx, ctx.body)?; + let (mut expr, init_meta) = self.parse_initializer(ty, ctx.ctx, ctx.body)?; + + if let Some(kind) = self.program.module.types[ty].inner.scalar_kind() { + ctx.ctx + .implicit_conversion(self.program, &mut expr, init_meta, kind)?; + } + meta = meta.union(&init_meta); + Ok((expr, init_meta)) }) .transpose()?; @@ -541,7 +548,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let pointer = ctx.add_var(self.program, ty, name, maybe_constant, meta)?; - if let Some((value, _)) = init { + if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) { ctx.flush_expressions(); ctx.body.push(Statement::Store { pointer, value }); } From d8dc12e47b4608f05b9fc9e8cad56cd35b400753 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 6 Jun 2021 14:26:51 +0100 Subject: [PATCH 0938/2212] [glsl-in] Add gl_GlobalInvocationID builtin --- src/front/glsl/variables.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index b0c51e6dd..85530b9cb 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -104,6 +104,16 @@ impl Program<'_> { false, PrologueStage::VERTEX, ), + "gl_GlobalInvocationID" => add_builtin( + TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Uint, + width: 4, + }, + BuiltIn::GlobalInvocationId, + false, + PrologueStage::COMPUTE, + ), _ => Ok(None), } } From 15c846cd0ecba15eee22d28a5a6106ec949e64d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 6 Jun 2021 14:28:30 +0100 Subject: [PATCH 0939/2212] [glsl-in] Fix panic when calculating global use --- src/front/glsl/functions.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 0c7457341..e683b952a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -539,7 +539,7 @@ impl Program<'_> { .take(callee_len.saturating_sub(caller_len)), ); - for i in 0..callee_len.max(caller_len) { + for i in 0..callee_len.min(caller_len) { let callee_use = function_arg_use[function.index()][i]; function_arg_use[caller.index()][i] |= callee_use } From a2ecd8ecff40b55d48962a88d886048401ce6510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 6 Jun 2021 18:49:34 +0100 Subject: [PATCH 0940/2212] [glsl-in] Refractor global and blocks handling --- src/front/glsl/ast.rs | 26 ++----- src/front/glsl/parser.rs | 91 +++++------------------ src/front/glsl/variables.rs | 141 +++++++++++++++++++++++------------- 3 files changed, 120 insertions(+), 138 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 11b0652c2..975963561 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -21,6 +21,7 @@ pub enum GlobalLookupKind { pub struct GlobalLookup { pub kind: GlobalLookupKind, pub entry_arg: Option, + pub mutable: bool, } #[derive(Debug, PartialEq, Eq, Hash)] @@ -84,7 +85,6 @@ pub struct Program<'a> { pub lookup_type: FastHashMap>, pub global_variables: Vec<(String, GlobalLookup)>, - pub constants: Vec<(String, Handle)>, pub entry_args: Vec, pub entries: Vec<(String, ShaderStage, Handle)>, @@ -107,7 +107,6 @@ impl<'a> Program<'a> { lookup_function: FastHashMap::default(), lookup_type: FastHashMap::default(), global_variables: Vec::new(), - constants: Vec::new(), entry_args: Vec::new(), entries: Vec::new(), @@ -225,7 +224,7 @@ impl<'function> Context<'function> { scopes: vec![FastHashMap::default()], lookup_global_var_exps: FastHashMap::with_capacity_and_hasher( - program.constants.len() + program.global_variables.len(), + program.global_variables.len(), Default::default(), ), typifier: Typifier::new(), @@ -235,23 +234,15 @@ impl<'function> Context<'function> { emitter: Emitter::default(), }; - for &(ref name, handle) in program.constants.iter() { - let expr = this.expressions.append(Expression::Constant(handle)); - let var = VariableReference { - expr, - load: None, - mutable: false, - entry_arg: None, - }; - - this.lookup_global_var_exps.insert(name.into(), var); - } - this.emit_start(); for &(ref name, lookup) in program.global_variables.iter() { this.emit_flush(body); - let GlobalLookup { kind, entry_arg } = lookup; + let GlobalLookup { + kind, + entry_arg, + mutable, + } = lookup; let (expr, load) = match kind { GlobalLookupKind::Variable(v) => { let res = ( @@ -280,8 +271,7 @@ impl<'function> Context<'function> { } else { None }, - // TODO: respect constant qualifier - mutable: true, + mutable, entry_arg, }; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index fa50d9941..0caa16dd1 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -12,8 +12,8 @@ use super::{ }; use crate::{ arena::Handle, Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Expression, - Function, FunctionResult, GlobalVariable, ResourceBinding, ScalarValue, Statement, - StorageAccess, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, + Function, FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, StructMember, + SwitchCase, Type, TypeInner, UnaryOperator, }; use core::convert::TryFrom; use std::{iter::Peekable, mem}; @@ -715,7 +715,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match token.value { TokenValue::Identifier(ty_name) => { if self.bump_if(TokenValue::LeftBrace).is_some() { - self.parse_block_declaration(&qualifiers, ty_name) + self.parse_block_declaration(&qualifiers, ty_name, token.meta) } else { //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON @@ -761,55 +761,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { &mut self, qualifiers: &[(TypeQualifier, SourceMetadata)], ty_name: String, + mut meta: SourceMetadata, ) -> Result { - let mut class = StorageClass::Private; - let mut binding = None; - let mut layout = None; - - for &(ref qualifier, meta) in qualifiers { - match *qualifier { - TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { - if StorageClass::PushConstant == class && c == StorageClass::Uniform { - // Ignore the Uniform qualifier if the class was already set to PushConstant - continue; - } else if StorageClass::Private != class { - return Err(ErrorKind::SemanticError( - meta, - "Cannot use more than one storage qualifier per declaration".into(), - )); - } - - class = c; - } - TypeQualifier::ResourceBinding(ref r) => { - if binding.is_some() { - return Err(ErrorKind::SemanticError( - meta, - "Cannot use more than one storage qualifier per declaration".into(), - )); - } - - binding = Some(r.clone()); - } - TypeQualifier::Layout(ref l) => { - if layout.is_some() { - return Err(ErrorKind::SemanticError( - meta, - "Cannot use more than one storage qualifier per declaration".into(), - )); - } - - layout = Some(l); - } - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Qualifier not supported in block declarations".into(), - )); - } - } - } - let mut members = Vec::new(); let span = self.parse_struct_declaration_list(&mut members)?; self.expect(TokenValue::RightBrace)?; @@ -828,7 +781,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Semicolon => None, TokenValue::Identifier(name) => { if let Some(size) = self.parse_array_specifier()? { - ty = self.program.module.types.append(Type { + ty = self.program.module.types.fetch_or_append(Type { name: None, inner: TypeInner::Array { base: ty, @@ -846,25 +799,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } _ => return Err(ErrorKind::InvalidToken(token)), }; + meta = meta.union(&token.meta); - let handle = self.program.module.global_variables.append(GlobalVariable { - name: name.clone(), - class, - binding, + let handle = self.program.add_global_var(VarDeclaration { + qualifiers, ty, + name, init: None, - storage_access: StorageAccess::empty(), - }); - - if let Some(k) = name { - self.program.global_variables.push(( - k, - GlobalLookup { - kind: GlobalLookupKind::Variable(handle), - entry_arg: None, - }, - )); - } + meta, + })?; for (i, k) in members .into_iter() @@ -876,6 +819,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { GlobalLookup { kind: GlobalLookupKind::BlockSelect(handle, i), entry_arg: None, + mutable: true, }, )); } @@ -1556,7 +1500,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let decl = VarDeclaration { qualifiers: &qualifiers, ty, - name, + name: Some(name), init: None, meta: meta.union(&end_meta), }; @@ -1740,13 +1684,18 @@ impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { let decl = VarDeclaration { qualifiers: &self.qualifiers, ty, - name, + name: Some(name), init, meta, }; match self.external { - true => program.add_global_var(self.ctx, self.body, decl), + true => { + let handle = program.add_global_var(decl)?; + Ok(self + .ctx + .add_expression(Expression::GlobalVariable(handle), self.body)) + } false => program.add_local_var(self.ctx, self.body, decl), } } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 85530b9cb..03dd2ddfd 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -11,7 +11,7 @@ use super::token::SourceMetadata; pub struct VarDeclaration<'a> { pub qualifiers: &'a [(TypeQualifier, SourceMetadata)], pub ty: Handle, - pub name: String, + pub name: Option, pub init: Option>, pub meta: SourceMetadata, } @@ -57,6 +57,7 @@ impl Program<'_> { GlobalLookup { kind: GlobalLookupKind::Variable(handle), entry_arg: Some(idx), + mutable, }, )); ctx.arg_use.push(EntryArgUse::empty()); @@ -222,8 +223,6 @@ impl Program<'_> { pub fn add_global_var( &mut self, - ctx: &mut Context, - body: &mut Block, VarDeclaration { qualifiers, ty, @@ -231,7 +230,7 @@ impl Program<'_> { init, meta, }: VarDeclaration, - ) -> Result, ErrorKind> { + ) -> Result, ErrorKind> { let mut storage = StorageQualifier::StorageClass(StorageClass::Private); let mut interpolation = None; let mut binding = None; @@ -242,7 +241,12 @@ impl Program<'_> { for &(ref qualifier, meta) in qualifiers { match *qualifier { TypeQualifier::StorageQualifier(s) => { - if StorageQualifier::StorageClass(StorageClass::Private) != storage { + if StorageQualifier::StorageClass(StorageClass::PushConstant) == storage + && s == StorageQualifier::StorageClass(StorageClass::Uniform) + { + // Ignore the Uniform qualifier if the class was already set to PushConstant + continue; + } else if StorageQualifier::StorageClass(StorageClass::Private) != storage { return Err(ErrorKind::SemanticError( meta, "Cannot use more than one storage qualifier per declaration".into(), @@ -255,7 +259,8 @@ impl Program<'_> { if interpolation.is_some() { return Err(ErrorKind::SemanticError( meta, - "Cannot use more than one storage qualifier per declaration".into(), + "Cannot use more than one interpolation qualifier per declaration" + .into(), )); } @@ -265,7 +270,7 @@ impl Program<'_> { if binding.is_some() { return Err(ErrorKind::SemanticError( meta, - "Cannot use more than one storage qualifier per declaration".into(), + "Cannot use more than one binding per declaration".into(), )); } @@ -275,7 +280,7 @@ impl Program<'_> { if location.is_some() { return Err(ErrorKind::SemanticError( meta, - "Cannot use more than one storage qualifier per declaration".into(), + "Cannot use more than one binding per declaration".into(), )); } @@ -285,7 +290,7 @@ impl Program<'_> { if sampling.is_some() { return Err(ErrorKind::SemanticError( meta, - "Cannot use more than one storage qualifier per declaration".into(), + "Cannot use more than one sampling qualifier per declaration".into(), )); } @@ -295,7 +300,7 @@ impl Program<'_> { if layout.is_some() { return Err(ErrorKind::SemanticError( meta, - "Cannot use more than one storage qualifier per declaration".into(), + "Cannot use more than one layout qualifier per declaration".into(), )); } @@ -311,10 +316,17 @@ impl Program<'_> { } if binding.is_some() && storage != StorageQualifier::StorageClass(StorageClass::Uniform) { - return Err(ErrorKind::SemanticError( - meta, - "binding requires uniform or buffer storage qualifier".into(), - )); + match storage { + StorageQualifier::StorageClass(StorageClass::PushConstant) + | StorageQualifier::StorageClass(StorageClass::Uniform) + | StorageQualifier::StorageClass(StorageClass::Storage) => {} + _ => { + return Err(ErrorKind::SemanticError( + meta, + "binding requires uniform or buffer storage qualifier".into(), + )) + } + } } if (sampling.is_some() || interpolation.is_some()) && location.is_none() { @@ -325,7 +337,8 @@ impl Program<'_> { } if let Some(location) = location { - let prologue = if let StorageQualifier::Input = storage { + let input = storage == StorageQualifier::Input; + let prologue = if input { PrologueStage::all() } else { PrologueStage::empty() @@ -339,7 +352,7 @@ impl Program<'_> { }); let handle = self.module.global_variables.append(GlobalVariable { - name: Some(name.clone()), + name: name.clone(), class: StorageClass::Private, binding: None, ty, @@ -358,23 +371,40 @@ impl Program<'_> { prologue, }); - self.global_variables.push(( - name, - GlobalLookup { - kind: GlobalLookupKind::Variable(handle), - entry_arg: Some(idx), - }, - )); + if let Some(name) = name { + self.global_variables.push(( + name, + GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: Some(idx), + mutable: !input, + }, + )); + } - return Ok(ctx.add_expression(Expression::GlobalVariable(handle), body)); + return Ok(handle); } else if let StorageQualifier::Const = storage { - let handle = init.ok_or_else(|| { - ErrorKind::SemanticError(meta, "Constant must have a initializer".into()) - })?; + let handle = self.module.global_variables.append(GlobalVariable { + name: name.clone(), + class: StorageClass::Private, + binding: None, + ty, + init, + storage_access: StorageAccess::empty(), + }); - self.constants.push((name, handle)); + if let Some(name) = name { + self.global_variables.push(( + name, + GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: None, + mutable: false, + }, + )); + } - return Ok(ctx.add_expression(Expression::Constant(handle), body)); + return Ok(handle); } let (class, storage_access) = match self.module.types[ty].inner { @@ -389,17 +419,23 @@ impl Program<'_> { }, ), TypeInner::Sampler { .. } => (StorageClass::Handle, StorageAccess::empty()), - _ => ( - match storage { - StorageQualifier::StorageClass(class) => class, - _ => StorageClass::Private, - }, - StorageAccess::empty(), - ), + _ => { + if let StorageQualifier::StorageClass(StorageClass::Storage) = storage { + (StorageClass::Storage, StorageAccess::all()) + } else { + ( + match storage { + StorageQualifier::StorageClass(class) => class, + _ => StorageClass::Private, + }, + StorageAccess::empty(), + ) + } + } }; let handle = self.module.global_variables.append(GlobalVariable { - name: Some(name.clone()), + name: name.clone(), class, binding, ty, @@ -407,15 +443,18 @@ impl Program<'_> { storage_access, }); - self.global_variables.push(( - name, - GlobalLookup { - kind: GlobalLookupKind::Variable(handle), - entry_arg: None, - }, - )); + if let Some(name) = name { + self.global_variables.push(( + name, + GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: None, + mutable: true, + }, + )); + } - Ok(ctx.add_expression(Expression::GlobalVariable(handle), body)) + Ok(handle) } pub fn add_local_var( @@ -431,8 +470,10 @@ impl Program<'_> { }: VarDeclaration, ) -> Result, ErrorKind> { #[cfg(feature = "glsl-validate")] - if ctx.lookup_local_var_current_scope(&name).is_some() { - return Err(ErrorKind::VariableAlreadyDeclared(name)); + if let Some(ref name) = name { + if ctx.lookup_local_var_current_scope(name).is_some() { + return Err(ErrorKind::VariableAlreadyDeclared(name.clone())); + } } let mut mutable = true; @@ -459,13 +500,15 @@ impl Program<'_> { } let handle = ctx.locals.append(LocalVariable { - name: Some(name.clone()), + name: name.clone(), ty, init, }); let expr = ctx.add_expression(Expression::LocalVariable(handle), body); - ctx.add_local_var(name, expr, mutable); + if let Some(name) = name { + ctx.add_local_var(name, expr, mutable); + } Ok(expr) } From 605bab12e31672cc4523cd11975ebb5bf9bc61c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 6 Jun 2021 18:52:12 +0100 Subject: [PATCH 0941/2212] [glsl-in] Don't load unsized types --- src/front/glsl/ast.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 975963561..3e02c16e3 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -260,7 +260,24 @@ impl<'function> Context<'function> { .expressions .append(Expression::AccessIndex { base, index }); - (expr, true) + (expr, { + let ty = program.module.global_variables[handle].ty; + + match program.module.types[ty].inner { + TypeInner::Struct { ref members, .. } => { + if let TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } = program.module.types[members[index as usize].ty].inner + { + false + } else { + true + } + } + _ => true, + } + }) } }; @@ -437,7 +454,18 @@ impl<'function> Context<'function> { let base = self.lower_expect(program, base, lhs, body)?.0; let index = self.lower_expect(program, index, false, body)?.0; - self.add_expression(Expression::Access { base, index }, body) + let pointer = self.add_expression(Expression::Access { base, index }, body); + + if let TypeInner::Pointer { .. } = *program.resolve_type(self, pointer, meta)? { + if !lhs { + return Ok(( + Some(self.add_expression(Expression::Load { pointer }, body)), + meta, + )); + } + } + + pointer } HirExprKind::Select { base, field } => { let base = self.lower_expect(program, base, lhs, body)?.0; From b15b0b6862dcd93fdc0d74714322152b2b51695a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 6 Jun 2021 18:53:25 +0100 Subject: [PATCH 0942/2212] [glsl-in] Use local for mutable non pointer args --- src/front/glsl/ast.rs | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 3e02c16e3..16dc59708 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -395,7 +395,41 @@ impl<'function> Context<'function> { None }; - if let Some(current) = self.scopes.last_mut() { + if mutable && load.is_none() { + let handle = self.locals.append(LocalVariable { + name: Some(name.clone()), + ty, + init: None, + }); + let local_expr = self.add_expression(Expression::LocalVariable(handle), body); + + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { + pointer: local_expr, + value: expr, + }); + + let local_load = self.add_expression( + Expression::Load { + pointer: local_expr, + }, + body, + ); + + if let Some(current) = self.scopes.last_mut() { + (*current).insert( + name, + VariableReference { + expr: local_expr, + load: Some(local_load), + mutable, + entry_arg: None, + }, + ); + } + } else if let Some(current) = self.scopes.last_mut() { (*current).insert( name, VariableReference { From fb71e49501c4321054d63dcc86c6451619f05ecd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 6 Jun 2021 18:56:36 +0100 Subject: [PATCH 0943/2212] [glsl-in] Implicit cast mod function --- src/front/glsl/functions.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index e683b952a..9e7655e4b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -244,20 +244,27 @@ impl Program<'_> { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } + let (mut left, left_meta) = args[0]; + let (mut right, right_meta) = args[1]; + + ctx.binary_implicit_conversion( + self, &mut left, left_meta, &mut right, right_meta, + )?; + let expr = if let Some(ScalarKind::Float) = self.resolve_type(ctx, args[0].0, args[1].1)?.scalar_kind() { Expression::Math { fun: MathFunction::Modf, - arg: args[0].0, - arg1: Some(args[1].0), + arg: left, + arg1: Some(right), arg2: None, } } else { Expression::Binary { op: BinaryOperator::Modulo, - left: args[0].0, - right: args[1].0, + left, + right, } }; From 06c8588fcd574afab0fc0217b45a2a233d481ee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 9 Jun 2021 11:04:42 +0100 Subject: [PATCH 0944/2212] [glsl-in] Add collatz shader and test quad shader --- tests/in/glsl/246-collatz.comp | 34 ++++++++++++++++++++++++++++++++++ tests/out/quad-glsl.wgsl | 10 ++++++---- 2 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 tests/in/glsl/246-collatz.comp diff --git a/tests/in/glsl/246-collatz.comp b/tests/in/glsl/246-collatz.comp new file mode 100644 index 000000000..274cdca1c --- /dev/null +++ b/tests/in/glsl/246-collatz.comp @@ -0,0 +1,34 @@ +// AUTHOR: Unknown +// ISSUE: #246 +// NOTE: Taken from the wgpu repo +#version 450 +layout(local_size_x = 1) in; + +layout(set = 0, binding = 0) buffer PrimeIndices { + uint[] indices; +}; // this is used as both input and output for convenience + +// The Collatz Conjecture states that for any integer n: +// If n is even, n = n/2 +// If n is odd, n = 3n+1 +// And repeat this process for each new n, you will always eventually reach 1. +// Though the conjecture has not been proven, no counterexample has ever been found. +// This function returns how many times this recurrence needs to be applied to reach 1. +uint collatz_iterations(uint n) { + uint i = 0; + while(n != 1) { + if (mod(n, 2) == 0) { + n = n / 2; + } + else { + n = (3 * n) + 1; + } + i++; + } + return i; +} + +void main() { + uint index = gl_GlobalInvocationID.x; + indices[index] = collatz_iterations(indices[index]); +} diff --git a/tests/out/quad-glsl.wgsl b/tests/out/quad-glsl.wgsl index fccd8cc2a..6be3e0caa 100644 --- a/tests/out/quad-glsl.wgsl +++ b/tests/out/quad-glsl.wgsl @@ -7,6 +7,7 @@ struct FragmentOutput { [[location(0), interpolate(perspective)]] member2: vec4; }; +var c_scale: f32; var a_pos: vec2; var a_uv: vec2; var v_uv: vec2; @@ -15,10 +16,11 @@ var v_uv1: vec2; var o_color: vec4; fn vert_main() { - let _e2: vec2 = a_pos; - let _e4: vec2 = a_uv; - v_uv = _e4; - gl_Position = vec4((1.2000000476837158 * _e2), 0.0, 1.0); + let _e1: f32 = c_scale; + let _e3: vec2 = a_pos; + let _e5: vec2 = a_uv; + v_uv = _e5; + gl_Position = vec4((_e1 * _e3), 0.0, 1.0); return; } From 10422c6b4a88d4ab21216763c57c6fcedfe97a36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 9 Jun 2021 18:01:25 +0100 Subject: [PATCH 0945/2212] Regenerate quad-glsl shader --- tests/out/quad-glsl.wgsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/out/quad-glsl.wgsl b/tests/out/quad-glsl.wgsl index 6be3e0caa..22a9b9b70 100644 --- a/tests/out/quad-glsl.wgsl +++ b/tests/out/quad-glsl.wgsl @@ -7,7 +7,7 @@ struct FragmentOutput { [[location(0), interpolate(perspective)]] member2: vec4; }; -var c_scale: f32; +var c_scale: f32 = 1.2000000476837158; var a_pos: vec2; var a_uv: vec2; var v_uv: vec2; From af022ed21e980a199c7c9bd66e5f5df477a74437 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 10 Jun 2021 14:19:41 -0400 Subject: [PATCH 0946/2212] Add Hash to ResourceBinding --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index d863ea406..b2ab989b9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -562,7 +562,7 @@ pub enum Binding { } /// Pipeline binding information for global resources. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct ResourceBinding { From 4224d14a082043a8bf5101ca3e8de44b5514f581 Mon Sep 17 00:00:00 2001 From: Jakob Hellermann Date: Sun, 13 Jun 2021 01:24:01 +0200 Subject: [PATCH 0947/2212] move bin/naga.rs to a separate crate in workspace (#938) * move bin/naga.rs to a separate crate * enable all shader languages for naga binary * [naga-cli] add env logger * [naga-cli] remove unneccessary code * [naga-cli]enable glsl-validate feature * move naga-cli to cli, add trailing newline * remove commented env_logger dependency --- Cargo.toml | 10 +++++----- cli/Cargo.toml | 20 +++++++++++++++++++ bin/naga.rs => cli/src/main.rs | 35 +++------------------------------- 3 files changed, 28 insertions(+), 37 deletions(-) create mode 100644 cli/Cargo.toml rename bin/naga.rs => cli/src/main.rs (88%) diff --git a/Cargo.toml b/Cargo.toml index 7acbf4a33..55248d678 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ repository = "https://github.com/gfx-rs/naga" keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] +resolver = "2" [package.metadata.docs.rs] all-features = true @@ -26,7 +27,6 @@ serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } rose_tree = { version ="0.2", optional = true } pp-rs = { git = "https://github.com/Kangz/glslpp-rs.git", optional = true, rev = "c02476b" } -#env_logger = "0.8" # uncomment temporarily for developing with the binary target [features] default = [] @@ -43,13 +43,13 @@ wgsl-in = ["codespan-reporting"] wgsl-out = [] hlsl-out = [] -[[bin]] -name = "naga" -path = "bin/naga.rs" - [dev-dependencies] diff = "0.1" ron = "0.6" serde = { version = "1.0", features = ["derive"] } spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } rspirv = "0.7" + +[workspace] +members = [".", "cli"] +default-members = ["cli"] diff --git a/cli/Cargo.toml b/cli/Cargo.toml new file mode 100644 index 000000000..70a274cd8 --- /dev/null +++ b/cli/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "naga-cli" +version = "0.4.0" +authors = ["Naga Developers"] +edition = "2018" +description = "Shader translation command line tool" +homepage = "https://github.com/gfx-rs/naga" +repository = "https://github.com/gfx-rs/naga" +keywords = ["shader", "SPIR-V", "GLSL", "MSL"] +license = "MIT OR Apache-2.0" + +[[bin]] +name = "naga" +path = "src/main.rs" + +[dependencies] +naga = { path = "../", features = ["wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate"] } +log = "0.4" +codespan-reporting = "0.11" +env_logger = "0.8" diff --git a/bin/naga.rs b/cli/src/main.rs similarity index 88% rename from bin/naga.rs rename to cli/src/main.rs index 09c1f64dc..8b2930819 100644 --- a/bin/naga.rs +++ b/cli/src/main.rs @@ -6,15 +6,10 @@ use std::{env, error::Error, path::Path}; #[derive(Default)] struct Parameters { validation_flags: naga::valid::ValidationFlags, - #[cfg(feature = "spv-in")] spv_adjust_coordinate_space: bool, - #[cfg(feature = "spv-in")] spv_flow_dump_prefix: Option, - #[cfg(feature = "spv-out")] spv: naga::back::spv::Options, - #[cfg(feature = "msl-out")] msl: naga::back::msl::Options, - #[cfg(feature = "glsl-out")] glsl: naga::back::glsl::Options, } @@ -46,7 +41,7 @@ impl PrettyResult for Result { } fn main() { - //env_logger::init(); // uncomment during development + env_logger::init(); let mut input_path = None; let mut output_paths = Vec::new(); @@ -66,11 +61,8 @@ fn main() { params.validation_flags = naga::valid::ValidationFlags::from_bits(value).unwrap(); } - #[cfg(feature = "spv-in")] "flow-dir" => params.spv_flow_dump_prefix = args.next(), - #[cfg(feature = "glsl-out")] "entry-point" => params.glsl.entry_point = args.next().unwrap(), - #[cfg(feature = "glsl-out")] "profile" => { use naga::back::glsl::Version; let string = args.next().unwrap(); @@ -105,7 +97,6 @@ fn main() { .to_str() .unwrap() { - #[cfg(feature = "spv-in")] "spv" => { let options = naga::front::spv::Options { adjust_coordinate_space: params.spv_adjust_coordinate_space, @@ -115,7 +106,6 @@ fn main() { let input = fs::read(input_path).unwrap(); naga::front::spv::parse_u8_slice(&input, &options).unwrap() } - #[cfg(feature = "wgsl-in")] "wgsl" => { let input = fs::read_to_string(input_path).unwrap(); let result = naga::front::wgsl::parse_str(&input); @@ -127,7 +117,6 @@ fn main() { } } } - #[cfg(feature = "glsl-in")] "vert" => { let input = fs::read_to_string(input_path).unwrap(); let mut entry_points = naga::FastHashMap::default(); @@ -141,7 +130,6 @@ fn main() { ) .unwrap_pretty() } - #[cfg(feature = "glsl-in")] "frag" => { let input = fs::read_to_string(input_path).unwrap(); let mut entry_points = naga::FastHashMap::default(); @@ -155,7 +143,6 @@ fn main() { ) .unwrap_pretty() } - #[cfg(feature = "glsl-in")] "comp" => { let input = fs::read_to_string(input_path).unwrap(); let mut entry_points = naga::FastHashMap::default(); @@ -169,13 +156,7 @@ fn main() { ) .unwrap_pretty() } - other => { - if true { - // prevent "unreachable_code" warnings - panic!("Unknown input extension: {}", other); - } - naga::Module::default() - } + other => panic!("Unknown input extension: {}", other), }; // validate the IR @@ -218,7 +199,6 @@ fn main() { writeln!(file, "{:#?}", info).unwrap(); } } - #[cfg(feature = "msl-out")] "metal" => { use naga::back::msl; @@ -232,7 +212,6 @@ fn main() { .unwrap_pretty(); fs::write(output_path, msl).unwrap(); } - #[cfg(feature = "spv-out")] "spv" => { use naga::back::spv; @@ -247,7 +226,6 @@ fn main() { fs::write(output_path, bytes.as_slice()).unwrap(); } - #[cfg(feature = "glsl-out")] stage @ "vert" | stage @ "frag" | stage @ "comp" => { use naga::back::glsl; @@ -265,21 +243,18 @@ fn main() { writer.write().unwrap(); fs::write(output_path, buffer).unwrap(); } - #[cfg(feature = "dot-out")] "dot" => { use naga::back::dot; let output = dot::write(&module, info.as_ref()).unwrap(); fs::write(output_path, output).unwrap(); } - #[cfg(feature = "hlsl-out")] "hlsl" => { use naga::back::hlsl; let hlsl = hlsl::write_string(&module).unwrap_pretty(); fs::write(output_path, hlsl).unwrap(); } - #[cfg(feature = "wgsl-out")] "wgsl" => { use naga::back::wgsl; @@ -287,11 +262,7 @@ fn main() { fs::write(output_path, wgsl).unwrap(); } other => { - let _ = params; - println!( - "Unknown output extension: {}, forgot to enable a feature?", - other - ); + println!("Unknown output extension: {}", other); } } } From 753e9608d3798c8b3fe30191198db2de3676d150 Mon Sep 17 00:00:00 2001 From: Evgeny Proydakov Date: Sun, 13 Jun 2021 02:46:33 +0300 Subject: [PATCH 0948/2212] Fixed compile-time error in spv fuzzer test. (#967) * Fixed compile-time error in spv fuzzer test. error[E0061]: this function takes 2 arguments but 1 argument was supplied --> fuzz_targets/spv_parser.rs:7:19 | 7 | let _result = Parser::new(data.into_iter()).parse(); | ^^^^^^^^^^^ ---------------- supplied 1 argument | | | expected 2 arguments | note: associated function defined here --> /Users/evgeny.proydakov/repository/naga/src/front/spv/mod.rs:411:12 | 411 | pub fn new(data: I, options: &Options) -> Self { | ^^^ error: aborting due to previous error * Code review. Group imports --- fuzz/fuzz_targets/spv_parser.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/fuzz/fuzz_targets/spv_parser.rs b/fuzz/fuzz_targets/spv_parser.rs index dca86b8fa..3b8af0fbb 100644 --- a/fuzz/fuzz_targets/spv_parser.rs +++ b/fuzz/fuzz_targets/spv_parser.rs @@ -1,8 +1,9 @@ #![no_main] use libfuzzer_sys::fuzz_target; -use naga::front::spv::Parser; +use naga::front::spv::{Parser, Options}; fuzz_target!(|data: Vec| { // Ensure the parser can handle potentially malformed data without crashing. - let _result = Parser::new(data.into_iter()).parse(); + let options = Options::default(); + let _result = Parser::new(data.into_iter(), &options).parse(); }); From 54d7d7d2a348412222d483731580d74499f03f53 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sat, 12 Jun 2021 01:12:01 +0300 Subject: [PATCH 0949/2212] Improve hlsl-out --- Makefile | 2 +- README.md | 2 +- cli/src/main.rs | 9 +- src/back/hlsl/keywords.rs | 164 ++++++++++++++++- src/back/hlsl/mod.rs | 27 ++- src/back/hlsl/writer.rs | 339 ++++++++++++++++++++++++++++++++--- tests/out/empty.Compute.hlsl | 1 - tests/snapshots.rs | 11 +- 8 files changed, 515 insertions(+), 40 deletions(-) diff --git a/Makefile b/Makefile index 397cbaf5b..bf0bfbb1e 100644 --- a/Makefile +++ b/Makefile @@ -67,6 +67,6 @@ validate-wgsl: $(SNAPSHOTS_OUT)/*.wgsl validate-hlsl: $(SNAPSHOTS_OUT)/*.hlsl @set -e && for file in $(SNAPSHOTS_OUT)/*.Compute.hlsl ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ - dxc $${file} -T cs_6_0;\ + dxc $${file} -T cs_5_0;\ done diff --git a/README.md b/README.md index 8d99c4d93..2984a6037 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Back-end | Status | Feature | Notes | SPIR-V | :white_check_mark: | spv-out | | WGSL | :construction: | wgsl-out | | Metal | :white_check_mark: | msl-out | | -HLSL | :construction: | hlsl-out | | +HLSL | :construction: | hlsl-out | Shader Model 5.0+ (DirectX 11+) | GLSL | :ok: | glsl-out | | AIR | | | | DXIL/DXIR | | | | diff --git a/cli/src/main.rs b/cli/src/main.rs index 8b2930819..393595020 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -251,8 +251,13 @@ fn main() { } "hlsl" => { use naga::back::hlsl; - - let hlsl = hlsl::write_string(&module).unwrap_pretty(); + // TODO: Get `ShaderModel` from user + let hlsl = hlsl::write_string( + &module, + info.as_ref().unwrap(), + hlsl::ShaderModel::default(), + ) + .unwrap_pretty(); fs::write(output_path, hlsl).unwrap(); } "wgsl" => { diff --git a/src/back/hlsl/keywords.rs b/src/back/hlsl/keywords.rs index e4ce79f36..1c19c5112 100644 --- a/src/back/hlsl/keywords.rs +++ b/src/back/hlsl/keywords.rs @@ -1 +1,163 @@ -pub const RESERVED: &[&str] = &[]; +/// HLSL Reserved Words +/// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-appendix-keywords +/// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-appendix-reserved-words +pub const RESERVED: &[&str] = &[ + "AppendStructuredBuffer", + "asm", + "asm_fragment", + "BlendState", + "bool", + "break", + "Buffer", + "ByteAddressBuffer", + "case", + "cbuffer", + "centroid", + "class", + "column_major", + "compile", + "compile_fragment", + "CompileShader", + "const", + "continue", + "ComputeShader", + "ConsumeStructuredBuffer", + "default", + "DepthStencilState", + "DepthStencilView", + "discard", + "do", + "double", + "DomainShader", + "dword", + "else", + "export", + "extern", + "false", + "float", + "for", + "fxgroup", + "GeometryShader", + "groupshared", + "half", + "Hullshader", + "if", + "in", + "inline", + "inout", + "InputPatch", + "int", + "interface", + "line", + "lineadj", + "linear", + "LineStream", + "matrix", + "min16float", + "min10float", + "min16int", + "min12int", + "min16uint", + "namespace", + "nointerpolation", + "noperspective", + "NULL", + "out", + "OutputPatch", + "packoffset", + "pass", + "pixelfragment", + "PixelShader", + "point", + "PointStream", + "precise", + "RasterizerState", + "RenderTargetView", + "return", + "register", + "row_major", + "RWBuffer", + "RWByteAddressBuffer", + "RWStructuredBuffer", + "RWTexture1D", + "RWTexture1DArray", + "RWTexture2D", + "RWTexture2DArray", + "RWTexture3D", + "sample", + "sampler", + "SamplerState", + "SamplerComparisonState", + "shared", + "snorm", + "stateblock", + "stateblock_state", + "static", + "string", + "struct", + "switch", + "StructuredBuffer", + "tbuffer", + "technique", + "technique10", + "technique11", + "texture", + "Texture1D", + "Texture1DArray", + "Texture2D", + "Texture2DArray", + "Texture2DMS", + "Texture2DMSArray", + "Texture3D", + "TextureCube", + "TextureCubeArray", + "true", + "typedef", + "triangle", + "triangleadj", + "TriangleStream", + "uint", + "uniform", + "unorm", + "unsigned", + "vector", + "vertexfragment", + "VertexShader", + "void", + "volatile", + "while", + "auto", + "case", + "catch", + "char", + "class", + "const_cast", + "default", + "delete", + "dynamic_cast", + "enum", + "explicit", + "friend", + "goto", + "long", + "mutable", + "new", + "operator", + "private", + "protected", + "public", + "reinterpret_cast", + "short", + "signed", + "sizeof", + "static_cast", + "template", + "this", + "throw", + "try", + "typename", + "union", + "unsigned", + "using", + "virtual", +]; diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 9cc22d9d1..5f049a4a9 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -6,15 +6,36 @@ use thiserror::Error; pub use writer::Writer; +#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] +pub struct ShaderModel(u16); + +impl Default for ShaderModel { + fn default() -> Self { + ShaderModel(50) + } +} + #[derive(Error, Debug)] pub enum Error { #[error(transparent)] IoError(#[from] FmtError), + #[error("BuiltIn {0:?} is not supported")] + UnsupportedShaderModel(ShaderModel), + #[error("A scalar with an unsupported width was requested: {0:?} {1:?}")] + UnsupportedScalar(crate::ScalarKind, crate::Bytes), + #[error("BuiltIn {0:?} is not supported")] + UnsupportedBuiltIn(crate::BuiltIn), + #[error("{0}")] + Unimplemented(String), // TODO: Error used only during development } -pub fn write_string(module: &crate::Module) -> Result { - let mut w = Writer::new(String::new()); - w.write(module)?; +pub fn write_string( + module: &crate::Module, + info: &crate::valid::ModuleInfo, + shader_model: ShaderModel, +) -> Result { + let mut w = Writer::new(String::new(), shader_model); + w.write(module, info)?; let output = w.finish(); Ok(output) } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index a0030a92b..78e086137 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,40 +1,94 @@ -use super::Error; +//TODO: temp +#![allow(dead_code)] +use super::{Error, ShaderModel}; use crate::back::hlsl::keywords::RESERVED; -use crate::proc::{NameKey, Namer}; -use crate::{FastHashMap, ShaderStage}; +use crate::proc::{EntryPointIndex, NameKey, Namer}; +use crate::valid::{FunctionInfo, ModuleInfo}; +use crate::{ + Arena, Bytes, Constant, Expression, FastHashMap, Function, Handle, ImageDimension, + LocalVariable, Module, ScalarKind, ShaderStage, Statement, Type, TypeInner, +}; use std::fmt::Write; const INDENT: &str = " "; +/// Shorthand result used internally by the backend +type BackendResult = Result<(), Error>; + +/// Stores the current function type (either a regular function or an entry point) +/// +/// Also stores data needed to identify it (handle for a regular function or index for an entry point) +// TODO: copy-paste from glsl-out, wgsl-out +enum FunctionType { + /// A regular function and it's handle + Function(Handle), + /// A entry point and it's index + EntryPoint(EntryPointIndex), +} + +/// Helper structure that stores data needed when writing the function +// TODO: copy-paste from glsl-out, wgsl-out +struct FunctionCtx<'a> { + /// The current function type being written + ty: FunctionType, + /// Analysis about the function + info: &'a FunctionInfo, + /// The expression arena of the current function being written + expressions: &'a Arena, + /// Map of expressions that have associated variable names + named_expressions: &'a crate::NamedExpressions, +} + +impl<'a> FunctionCtx<'_> { + /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function + fn name_key(&self, local: Handle) -> NameKey { + match self.ty { + FunctionType::Function(handle) => NameKey::FunctionLocal(handle, local), + FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, local), + } + } +} + pub struct Writer { out: W, names: FastHashMap, namer: Namer, + shader_model: ShaderModel, + named_expressions: crate::NamedExpressions, } impl Writer { - pub fn new(out: W) -> Self { + pub fn new(out: W, shader_model: ShaderModel) -> Self { Writer { out, names: FastHashMap::default(), namer: Namer::default(), + shader_model, + named_expressions: crate::NamedExpressions::default(), } } - pub fn write(&mut self, module: &crate::Module) -> Result<(), Error> { + fn reset(&mut self, module: &Module) { self.names.clear(); self.namer.reset(module, RESERVED, &[], &mut self.names); + self.named_expressions.clear(); + } - for (ep_index, ep) in module.entry_points.iter().enumerate() { - let fun = &ep.function; - let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)]; - writeln!(self.out)?; + pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { + if self.shader_model < ShaderModel(50) { + return Err(Error::UnsupportedShaderModel(self.shader_model)); + } - let return_type_name = match fun.result { - None => "void", - _ => "", + self.reset(module); + + // Write all entry points + for (index, ep) in module.entry_points.iter().enumerate() { + let func_ctx = FunctionCtx { + ty: FunctionType::EntryPoint(index as u16), + info: info.get_entry_point(index), + expressions: &ep.function.expressions, + named_expressions: &ep.function.named_expressions, }; - if ep.stage == ShaderStage::Compute { // HLSL is calling workgroup size, num threads let num_threads = ep.workgroup_size; @@ -44,36 +98,265 @@ impl Writer { num_threads[0], num_threads[1], num_threads[2] )?; } + self.write_function(module, &ep.function, &func_ctx)?; - writeln!( - self.out, - "{} {}({}", - return_type_name, - fun_name, - if fun.arguments.is_empty() { ")" } else { "" } - )?; - - // TODO Support arguments - self.write_block(&ep.function.body)?; + if index < module.entry_points.len() - 1 { + writeln!(self.out)?; + } } + Ok(()) } - fn write_block(&mut self, statements: &[crate::Statement]) -> Result<(), Error> { - writeln!(self.out, "{{")?; + /// Helper method used to write non image/sampler types + /// + /// # Notes + /// Adds no trailing or leading whitespace + fn write_type(&mut self, module: &Module, ty: Handle) -> BackendResult { + let inner = &module.types[ty].inner; + match *inner { + TypeInner::Struct { .. } => write!(self.out, "{}", self.names[&NameKey::Type(ty)])?, + ref other => self.write_value_type(module, other)?, + } - for statement in statements { - if let crate::Statement::Return { value: None } = *statement { - writeln!(self.out, "{}return;", INDENT)?; + Ok(()) + } + + /// Helper method used to write value types + /// + /// # Notes + /// Adds no trailing or leading whitespace + fn write_value_type(&mut self, _module: &Module, inner: &TypeInner) -> BackendResult { + match *inner { + TypeInner::Scalar { kind, width } => { + write!(self.out, "{}", scalar_kind_str(kind, width)?)?; } + _ => { + return Err(Error::Unimplemented(format!( + "write_value_type {:?}", + inner + ))) + } + } + + Ok(()) + } + + /// Helper method used to write structs + /// # Notes + /// Ends in a newline + fn write_function( + &mut self, + module: &Module, + func: &Function, + func_ctx: &FunctionCtx<'_>, + ) -> BackendResult { + // Function Declaration Syntax - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-function-syntax + if let Some(ref result) = func.result { + self.write_type(module, result.ty)?; + } else { + write!(self.out, "void")?; + } + + let func_name = match func_ctx.ty { + FunctionType::EntryPoint(index) => self.names[&NameKey::EntryPoint(index)].clone(), + FunctionType::Function(handle) => self.names[&NameKey::Function(handle)].clone(), + }; + + // Write function name + write!(self.out, " {}(", func_name)?; + + // Write function arguments + for (index, arg) in func.arguments.iter().enumerate() { + // Write argument type + self.write_type(module, arg.ty)?; + + let argument_name = match func_ctx.ty { + FunctionType::Function(handle) => { + self.names[&NameKey::FunctionArgument(handle, index as u32)].clone() + } + FunctionType::EntryPoint(ep_index) => { + self.names[&NameKey::EntryPointArgument(ep_index, index as u32)].clone() + } + }; + + // Write argument name. Space is important. + write!(self.out, " {}", argument_name)?; + if index < func.arguments.len() - 1 { + // Add a separator between args + write!(self.out, ", ")?; + } + } + // Ends of arguments + write!(self.out, ")")?; + + // Write semantic if it present + if let Some(ref result) = func.result { + if let Some(ref binding) = result.binding { + match *binding { + crate::Binding::BuiltIn(builtin) => { + write!(self.out, " : {}", builtin_str(builtin)?)? + } + // TODO: Is this reachable ? + crate::Binding::Location { .. } => { + return Err(Error::Unimplemented(format!( + "write_function semantic {:?}", + binding + ))) + } + } + } + } + + // Function body start + writeln!(self.out)?; + writeln!(self.out, "{{")?; + // Write function local variables + for (handle, local) in func.local_variables.iter() { + // Write indentation (only for readability) + write!(self.out, "{}", INDENT)?; + + // Write the local name + // The leading space is important + write!(self.out, "var {}: ", self.names[&func_ctx.name_key(handle)])?; + + // Write the local type + self.write_type(module, local.ty)?; + + // Write the local initializer if needed + if let Some(init) = local.init { + // Put the equal signal only if there's a initializer + // The leading and trailing spaces aren't needed but help with readability + write!(self.out, " = ")?; + + // Write the constant + // `write_constant` adds no trailing or leading space/newline + self.write_constant(module, init)?; + } + + // Finish the local with `;` and add a newline (only for readability) + writeln!(self.out, ";")? + } + + if !func.local_variables.is_empty() { + writeln!(self.out)?; + } + + // Write the function body (statement list) + for sta in func.body.iter() { + // The indentation should always be 1 when writing the function body + self.write_stmt(module, sta, func_ctx, 1)?; } writeln!(self.out, "}}")?; + self.named_expressions.clear(); + Ok(()) } + /// Helper method used to write statements + /// + /// # Notes + /// Always adds a newline + fn write_stmt( + &mut self, + module: &Module, + stmt: &Statement, + func_ctx: &FunctionCtx<'_>, + indent: usize, + ) -> BackendResult { + match *stmt { + Statement::Return { value } => { + write!(self.out, "{}return", INDENT.repeat(indent))?; + if let Some(return_value) = value { + // The leading space is important + write!(self.out, " ")?; + self.write_expr(module, return_value, func_ctx)?; + } + writeln!(self.out, ";")?; + } + _ => return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))), + } + + Ok(()) + } + + /// Helper method to write expressions + /// + /// # Notes + /// Doesn't add any newlines or leading/trailing spaces + fn write_expr( + &mut self, + _module: &Module, + expr: Handle, + func_ctx: &FunctionCtx<'_>, + ) -> BackendResult { + if let Some(name) = self.named_expressions.get(&expr) { + write!(self.out, "{}", name)?; + return Ok(()); + } + + let expression = &func_ctx.expressions[expr]; + + #[allow(clippy::match_single_binding)] + match *expression { + _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), + } + } + + /// Helper method used to write constants + /// + /// # Notes + /// Doesn't add any newlines or leading/trailing spaces + fn write_constant(&mut self, module: &Module, handle: Handle) -> BackendResult { + let constant = &module.constants[handle]; + #[allow(clippy::match_single_binding)] + match constant.inner { + _ => { + return Err(Error::Unimplemented(format!( + "write_constant {:?}", + constant + ))) + } + } + } + pub fn finish(self) -> W { self.out } } + +fn image_dimension_str(dim: ImageDimension) -> &'static str { + match dim { + ImageDimension::D1 => "1D", + ImageDimension::D2 => "2D", + ImageDimension::D3 => "3D", + ImageDimension::Cube => "Cube", + } +} + +fn builtin_str(built_in: crate::BuiltIn) -> Result<&'static str, Error> { + use crate::BuiltIn; + match built_in { + BuiltIn::Position => Ok("SV_Position"), + BuiltIn::PointSize => Err(Error::UnsupportedBuiltIn(built_in)), + _ => Err(Error::Unimplemented(format!("builtin_str {:?}", built_in))), + } +} + +/// Helper function that returns scalar related strings +/// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-scalar +fn scalar_kind_str(kind: ScalarKind, width: Bytes) -> Result<&'static str, Error> { + match kind { + ScalarKind::Sint => Ok("int"), + ScalarKind::Uint => Ok("uint"), + ScalarKind::Float => match width { + 2 => Ok("half"), + 4 => Ok("float"), + 8 => Ok("double"), + _ => Err(Error::UnsupportedScalar(kind, width)), + }, + ScalarKind::Bool => Ok("bool"), + } +} diff --git a/tests/out/empty.Compute.hlsl b/tests/out/empty.Compute.hlsl index 2b5243867..e79d36b9c 100644 --- a/tests/out/empty.Compute.hlsl +++ b/tests/out/empty.Compute.hlsl @@ -1,4 +1,3 @@ - [numthreads(1, 1, 1)] void main() { diff --git a/tests/snapshots.rs b/tests/snapshots.rs index a5aebfc69..742bb977e 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -108,7 +108,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { { if targets.contains(Targets::HLSL) { for ep in module.entry_points.iter() { - check_output_hlsl(module, &dest, ep.stage); + check_output_hlsl(module, &info, &dest, ep.stage); } } } @@ -221,10 +221,15 @@ fn check_output_glsl( } #[cfg(feature = "hlsl-out")] -fn check_output_hlsl(module: &naga::Module, destination: &PathBuf, stage: naga::ShaderStage) { +fn check_output_hlsl( + module: &naga::Module, + info: &naga::valid::ModuleInfo, + destination: &PathBuf, + stage: naga::ShaderStage, +) { use naga::back::hlsl; - let string = hlsl::write_string(module).unwrap(); + let string = hlsl::write_string(module, info, hlsl::ShaderModel::default()).unwrap(); let ext = format!("{:?}.hlsl", stage); fs::write(destination.with_extension(&ext), string).unwrap(); From 343f7864922f9912fec065fb3497a83d4099b398 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Sun, 13 Jun 2021 12:38:40 +0000 Subject: [PATCH 0950/2212] Fix testing infrastructure --- .github/workflows/lazy.yml | 2 +- .github/workflows/pipeline.yml | 4 ++-- Makefile | 5 ++--- README.md | 2 +- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index aacbfaf33..14f6005c9 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -16,7 +16,7 @@ jobs: - name: Generate report uses: actions-rs/tarpaulin@v0.1 with: - args: '--tests --all-features' + args: '--tests --all-features --workspace' - name: Upload to codecov.io uses: codecov/codecov-action@v1 with: diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 57d80e5a2..cc0f6bb0e 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -24,7 +24,7 @@ jobs: name: Test all features with: command: test - args: --all-features + args: --all-features --workspace - name: Check snapshots run: git diff --exit-code -- tests/out clippy: @@ -41,4 +41,4 @@ jobs: - uses: actions-rs/cargo@v1 with: command: clippy - args: --all-features -- -D warnings + args: --all-features --workspace -- -D warnings diff --git a/Makefile b/Makefile index bf0bfbb1e..936ef880d 100644 --- a/Makefile +++ b/Makefile @@ -5,8 +5,8 @@ SNAPSHOTS_OUT=tests/out all: cargo fmt - cargo test --all-features - cargo clippy --all-features + cargo test --all-features --workspace + cargo clippy --all-features --workspace -- -D warnings clean: rm *.metal *.air *.metallib *.vert *.frag *.comp *.spv @@ -69,4 +69,3 @@ validate-hlsl: $(SNAPSHOTS_OUT)/*.hlsl echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ dxc $${file} -T cs_5_0;\ done - diff --git a/README.md b/README.md index 2984a6037..aa18f5cb5 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ cargo run --features wgsl-in,glsl-out -- my_shader.wgsl my_shader.vert --profile ## Development workflow -The main instrument aiding the development is the good old `cargo test --all-features`, +The main instrument aiding the development is the good old `cargo test --all-features --workspace`, which will run the unit tests, and also update all the snapshots. You'll see these changes in git before committing the code. From 976ae3a9ff8de52cfd62cd0d71c981839623ba0d Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 14 Jun 2021 09:27:16 -0700 Subject: [PATCH 0951/2212] Makefile: Make validate-wgsl target use new 'cli' sub-package. --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 936ef880d..8452f2ede 100644 --- a/Makefile +++ b/Makefile @@ -61,7 +61,7 @@ validate-dot: $(SNAPSHOTS_OUT)/*.dot validate-wgsl: $(SNAPSHOTS_OUT)/*.wgsl @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ - cargo run --features wgsl-in $${file}; \ + cargo run $${file}; \ done validate-hlsl: $(SNAPSHOTS_OUT)/*.hlsl From d1f9575ed1a8059c26bd7b24fd43a14834747c7e Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sat, 12 Jun 2021 22:03:01 +0300 Subject: [PATCH 0952/2212] [glsl-out] Write space after if keyword --- src/back/glsl/mod.rs | 2 +- tests/out/boids.Compute.glsl | 24 ++++++++++++------------ tests/out/quad.Fragment.glsl | 2 +- tests/out/shadow.Fragment.glsl | 4 ++-- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 68ee1c202..3a85a6c9b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1242,7 +1242,7 @@ impl<'a, W: Write> Writer<'a, W> { ref reject, } => { write!(self.out, "{}", INDENT.repeat(indent))?; - write!(self.out, "if(")?; + write!(self.out, "if (")?; self.write_expr(condition, ctx)?; writeln!(self.out, ") {{")?; diff --git a/tests/out/boids.Compute.glsl b/tests/out/boids.Compute.glsl index 9af204f3c..1d3b29184 100644 --- a/tests/out/boids.Compute.glsl +++ b/tests/out/boids.Compute.glsl @@ -41,7 +41,7 @@ void main() { vec2 vel1; uint i = 0u; uint index = global_invocation_id.x; - if((index >= 1500u)) { + if ((index >= 1500u)) { return; } vec2 _expr10 = _group_0_binding_1.particles[index].pos; @@ -53,11 +53,11 @@ void main() { colVel = vec2(0.0, 0.0); while(true) { uint _expr37 = i; - if((_expr37 >= 1500u)) { + if ((_expr37 >= 1500u)) { break; } uint _expr39 = i; - if((_expr39 == index)) { + if ((_expr39 == index)) { continue; } uint _expr42 = i; @@ -69,7 +69,7 @@ void main() { vec2 _expr51 = pos1; vec2 _expr52 = vPos; float _expr55 = _group_0_binding_0.rule1Distance; - if((distance(_expr51, _expr52) < _expr55)) { + if ((distance(_expr51, _expr52) < _expr55)) { vec2 _expr57 = cMass; vec2 _expr58 = pos1; cMass = (_expr57 + _expr58); @@ -79,7 +79,7 @@ void main() { vec2 _expr63 = pos1; vec2 _expr64 = vPos; float _expr67 = _group_0_binding_0.rule2Distance; - if((distance(_expr63, _expr64) < _expr67)) { + if ((distance(_expr63, _expr64) < _expr67)) { vec2 _expr69 = colVel; vec2 _expr70 = pos1; vec2 _expr71 = vPos; @@ -88,7 +88,7 @@ void main() { vec2 _expr74 = pos1; vec2 _expr75 = vPos; float _expr78 = _group_0_binding_0.rule3Distance; - if((distance(_expr74, _expr75) < _expr78)) { + if ((distance(_expr74, _expr75) < _expr78)) { vec2 _expr80 = cVel; vec2 _expr81 = vel1; cVel = (_expr80 + _expr81); @@ -99,14 +99,14 @@ void main() { i = (_expr86 + 1u); } int _expr89 = cMassCount; - if((_expr89 > 0)) { + if ((_expr89 > 0)) { vec2 _expr92 = cMass; int _expr93 = cMassCount; vec2 _expr97 = vPos; cMass = ((_expr92 / vec2(float(_expr93))) - _expr97); } int _expr99 = cVelCount; - if((_expr99 > 0)) { + if ((_expr99 > 0)) { vec2 _expr102 = cVel; int _expr103 = cVelCount; cVel = (_expr102 / vec2(float(_expr103))); @@ -127,19 +127,19 @@ void main() { float _expr134 = _group_0_binding_0.deltaT; vPos = (_expr131 + (_expr132 * _expr134)); vec2 _expr137 = vPos; - if((_expr137.x < -1.0)) { + if ((_expr137.x < -1.0)) { vPos.x = 1.0; } vec2 _expr143 = vPos; - if((_expr143.x > 1.0)) { + if ((_expr143.x > 1.0)) { vPos.x = -1.0; } vec2 _expr149 = vPos; - if((_expr149.y < -1.0)) { + if ((_expr149.y < -1.0)) { vPos.y = 1.0; } vec2 _expr155 = vPos; - if((_expr155.y > 1.0)) { + if ((_expr155.y > 1.0)) { vPos.y = -1.0; } vec2 _expr164 = vPos; diff --git a/tests/out/quad.Fragment.glsl b/tests/out/quad.Fragment.glsl index 4cb26d2a4..ccb1198be 100644 --- a/tests/out/quad.Fragment.glsl +++ b/tests/out/quad.Fragment.glsl @@ -15,7 +15,7 @@ layout(location = 0) out vec4 _fs2p_location0; void main() { vec2 uv2 = _vs2fs_location0; vec4 color = texture(_group_0_binding_0, vec2(uv2)); - if((color.w == 0.0)) { + if ((color.w == 0.0)) { discard; } vec4 premultiplied = (color.w * color); diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index 90ca7eea8..23e04ef01 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -23,7 +23,7 @@ smooth in vec4 _vs2fs_location1; layout(location = 0) out vec4 _fs2p_location0; float fetch_shadow(uint light_id, vec4 homogeneous_coords) { - if((homogeneous_coords.w <= 0.0)) { + if ((homogeneous_coords.w <= 0.0)) { return 1.0; } vec2 flip_correction = vec2(0.5, -0.5); @@ -41,7 +41,7 @@ void main() { while(true) { uint _expr12 = i; uvec4 _expr14 = _group_0_binding_0.num_lights; - if((_expr12 >= min(_expr14.x, 10u))) { + if ((_expr12 >= min(_expr14.x, 10u))) { break; } uint _expr19 = i; From 7430a43c36cca96b7cbf1348fb840e64b6f171a5 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sat, 12 Jun 2021 22:03:36 +0300 Subject: [PATCH 0953/2212] [wgsl-out] Write constant names with namer --- src/back/wgsl/writer.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index da7874cc2..f37bd202c 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1365,8 +1365,8 @@ impl Writer { width: _, ref value, } => { - if let Some(ref name) = constant.name { - write!(self.out, "{}", name)?; + if constant.name.is_some() { + write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?; } else { self.write_scalar_value(*value)?; } From 92a11d0978a8ab09f41e6cd6314fc27e8dc41d28 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 15 Jun 2021 00:29:20 +0300 Subject: [PATCH 0954/2212] [hlsl-out] More improvements. Enable quad snapshot testing --- Makefile | 14 +- cli/src/main.rs | 16 +- src/back/hlsl/mod.rs | 41 +- src/back/hlsl/writer.rs | 710 ++++++++++++++++++++++++++++++++--- src/back/mod.rs | 4 +- tests/out/empty.Compute.hlsl | 5 - tests/out/empty.hlsl | 4 +- tests/out/empty.hlsl.config | 2 + tests/out/quad.hlsl | 34 ++ tests/out/quad.hlsl.config | 4 + tests/snapshots.rs | 39 +- 11 files changed, 776 insertions(+), 97 deletions(-) delete mode 100644 tests/out/empty.Compute.hlsl create mode 100644 tests/out/empty.hlsl.config create mode 100644 tests/out/quad.hlsl create mode 100644 tests/out/quad.hlsl.config diff --git a/Makefile b/Makefile index 8452f2ede..30da29c4c 100644 --- a/Makefile +++ b/Makefile @@ -65,7 +65,15 @@ validate-wgsl: $(SNAPSHOTS_OUT)/*.wgsl done validate-hlsl: $(SNAPSHOTS_OUT)/*.hlsl - @set -e && for file in $(SNAPSHOTS_OUT)/*.Compute.hlsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ - dxc $${file} -T cs_5_0;\ + @set -e && for file in $^ ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ + config="$$(dirname $${file})/$$(basename $${file}).config"; \ + vertex=""\ + fragment="" \ + compute="" \ + . $${config}; \ + [ ! -z "$${vertex}" ] && echo "Vertex Stage:" && dxc $${file} -T $${vertex} -E $${vertex_name} -Wno-parentheses-equality -Zi -Qembed_debug > /dev/null; \ + [ ! -z "$${fragment}" ] && echo "Fragment Stage:" && dxc $${file} -T $${fragment} -E $${fragment_name} -Wno-parentheses-equality -Zi -Qembed_debug > /dev/null; \ + [ ! -z "$${compute}" ] && echo "Compute Stage:" && dxc $${file} -T $${compute} -E $${compute_name} -Wno-parentheses-equality -Zi -Qembed_debug > /dev/null; \ + echo "======================"; \ done diff --git a/cli/src/main.rs b/cli/src/main.rs index 393595020..14d4c1185 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -11,6 +11,7 @@ struct Parameters { spv: naga::back::spv::Options, msl: naga::back::msl::Options, glsl: naga::back::glsl::Options, + hlsl: naga::back::hlsl::Options, } trait PrettyResult { @@ -75,6 +76,12 @@ fn main() { panic!("Unknown profile: {}", string) }; } + "shader-model" => { + use naga::back::hlsl::{ShaderModel, DEFAULT_SHADER_MODEL}; + let string = args.next().unwrap(); + params.hlsl.shader_model = + ShaderModel::new(string.parse().unwrap_or(DEFAULT_SHADER_MODEL)); + } other => log::warn!("Unknown parameter: {}", other), } } else if input_path.is_none() { @@ -251,13 +258,8 @@ fn main() { } "hlsl" => { use naga::back::hlsl; - // TODO: Get `ShaderModel` from user - let hlsl = hlsl::write_string( - &module, - info.as_ref().unwrap(), - hlsl::ShaderModel::default(), - ) - .unwrap_pretty(); + let hlsl = hlsl::write_string(&module, info.as_ref().unwrap(), ¶ms.hlsl) + .unwrap_pretty(); fs::write(output_path, hlsl).unwrap(); } "wgsl" => { diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 5f049a4a9..3b94239a0 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -6,12 +6,43 @@ use thiserror::Error; pub use writer::Writer; +pub const DEFAULT_SHADER_MODEL: u16 = 50; #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] pub struct ShaderModel(u16); +impl ShaderModel { + pub fn new(shader_model: u16) -> Self { + Self(shader_model) + } +} + impl Default for ShaderModel { fn default() -> Self { - ShaderModel(50) + Self(DEFAULT_SHADER_MODEL) + } +} + +/// Structure that contains the configuration used in the [`Writer`](Writer) +#[derive(Debug, Clone)] +pub struct Options { + /// The hlsl shader model to be used + pub shader_model: ShaderModel, + /// The vertex entry point name in generated shader + pub vertex_entry_point_name: String, + /// The fragment entry point name in generated shader + pub fragment_entry_point_name: String, + /// The comput entry point name in generated shader + pub compute_entry_point_name: String, +} + +impl Default for Options { + fn default() -> Self { + Options { + shader_model: ShaderModel(50), + vertex_entry_point_name: String::from("vert_main"), + fragment_entry_point_name: String::from("frag_main"), + compute_entry_point_name: String::from("comp_main"), + } } } @@ -23,18 +54,18 @@ pub enum Error { UnsupportedShaderModel(ShaderModel), #[error("A scalar with an unsupported width was requested: {0:?} {1:?}")] UnsupportedScalar(crate::ScalarKind, crate::Bytes), - #[error("BuiltIn {0:?} is not supported")] - UnsupportedBuiltIn(crate::BuiltIn), #[error("{0}")] Unimplemented(String), // TODO: Error used only during development + #[error("{0}")] + Custom(String), } pub fn write_string( module: &crate::Module, info: &crate::valid::ModuleInfo, - shader_model: ShaderModel, + options: &Options, ) -> Result { - let mut w = Writer::new(String::new(), shader_model); + let mut w = Writer::new(String::new(), options); w.write(module, info)?; let output = w.finish(); Ok(output) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 78e086137..c2260cf18 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,16 +1,19 @@ //TODO: temp #![allow(dead_code)] -use super::{Error, ShaderModel}; -use crate::back::hlsl::keywords::RESERVED; -use crate::proc::{EntryPointIndex, NameKey, Namer}; -use crate::valid::{FunctionInfo, ModuleInfo}; +use super::{Error, Options, ShaderModel}; use crate::{ - Arena, Bytes, Constant, Expression, FastHashMap, Function, Handle, ImageDimension, - LocalVariable, Module, ScalarKind, ShaderStage, Statement, Type, TypeInner, + back::{hlsl::keywords::RESERVED, vector_size_str}, + proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, + valid::{FunctionInfo, ModuleInfo}, + Arena, BuiltIn, Bytes, Constant, ConstantInner, Expression, FastHashMap, Function, + GlobalVariable, Handle, ImageDimension, LocalVariable, Module, ScalarKind, ScalarValue, + ShaderStage, Statement, StructMember, Type, TypeInner, }; use std::fmt::Write; const INDENT: &str = " "; +const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; +const LOCATION_SEMANTIC: &str = "LOC"; /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; @@ -49,21 +52,35 @@ impl<'a> FunctionCtx<'_> { } } -pub struct Writer { +struct EntryPointBinding { + stage: ShaderStage, + name: String, + members: Vec, +} + +struct EpStructMember { + pub name: String, + pub ty: Handle, + pub binding: Option, +} + +pub struct Writer<'a, W> { out: W, names: FastHashMap, namer: Namer, - shader_model: ShaderModel, + options: &'a Options, + ep_inputs: Vec>, named_expressions: crate::NamedExpressions, } -impl Writer { - pub fn new(out: W, shader_model: ShaderModel) -> Self { - Writer { +impl<'a, W: Write> Writer<'a, W> { + pub fn new(out: W, options: &'a Options) -> Self { + Self { out, names: FastHashMap::default(), namer: Namer::default(), - shader_model, + options, + ep_inputs: Vec::with_capacity(3), named_expressions: crate::NamedExpressions::default(), } } @@ -72,23 +89,76 @@ impl Writer { self.names.clear(); self.namer.reset(module, RESERVED, &[], &mut self.names); self.named_expressions.clear(); + self.ep_inputs.clear(); } pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { - if self.shader_model < ShaderModel(50) { - return Err(Error::UnsupportedShaderModel(self.shader_model)); + if self.options.shader_model < ShaderModel::default() { + return Err(Error::UnsupportedShaderModel(self.options.shader_model)); } self.reset(module); + // Write all constants + for (handle, constant) in module.constants.iter() { + if constant.name.is_some() { + self.write_global_constant(module, &constant.inner, handle)?; + } + } + + // Write all globals + for (ty, _) in module.global_variables.iter() { + self.write_global(module, ty)?; + } + + if !module.global_variables.is_empty() { + // Add extra newline for readability + writeln!(self.out)?; + } + + // Write all structs + for (handle, ty) in module.types.iter() { + if let TypeInner::Struct { + top_level, + ref members, + .. + } = ty.inner + { + self.write_struct(module, handle, top_level, members)?; + writeln!(self.out)?; + } + } + + // Write all entry points wrapped structs + for (index, ep) in module.entry_points.iter().enumerate() { + self.write_ep_input_struct(module, &ep.function, ep.stage, index)?; + } + + // Write all regular functions + for (handle, function) in module.functions.iter() { + let info = &info[handle]; + let ctx = FunctionCtx { + ty: FunctionType::Function(handle), + info, + expressions: &function.expressions, + named_expressions: &function.named_expressions, + }; + let name = self.names[&NameKey::Function(handle)].clone(); + + self.write_function(module, name.as_str(), function, &ctx)?; + + writeln!(self.out)?; + } + // Write all entry points for (index, ep) in module.entry_points.iter().enumerate() { - let func_ctx = FunctionCtx { + let ctx = FunctionCtx { ty: FunctionType::EntryPoint(index as u16), info: info.get_entry_point(index), expressions: &ep.function.expressions, named_expressions: &ep.function.named_expressions, }; + if ep.stage == ShaderStage::Compute { // HLSL is calling workgroup size, num threads let num_threads = ep.workgroup_size; @@ -98,7 +168,14 @@ impl Writer { num_threads[0], num_threads[1], num_threads[2] )?; } - self.write_function(module, &ep.function, &func_ctx)?; + + let name = match ep.stage { + ShaderStage::Vertex => &self.options.vertex_entry_point_name, + ShaderStage::Fragment => &self.options.fragment_entry_point_name, + ShaderStage::Compute => &self.options.compute_entry_point_name, + }; + + self.write_function(module, name, &ep.function, &ctx)?; if index < module.entry_points.len() - 1 { writeln!(self.out)?; @@ -108,6 +185,183 @@ impl Writer { Ok(()) } + fn write_binding(&mut self, binding: &crate::Binding) -> BackendResult { + match *binding { + crate::Binding::BuiltIn(builtin) => { + write!(self.out, " : {}", builtin_str(builtin))?; + } + crate::Binding::Location { location, .. } => { + write!(self.out, " : {}{}", LOCATION_SEMANTIC, location)?; + } + } + + Ok(()) + } + + fn write_ep_input_struct( + &mut self, + module: &Module, + func: &Function, + stage: ShaderStage, + index: usize, + ) -> BackendResult { + if !func.arguments.is_empty() { + let struct_name = self.namer.call_unique(match stage { + ShaderStage::Vertex => "VertexInput", + ShaderStage::Fragment => "FragmentInput", + ShaderStage::Compute => "ComputeInput", + }); + + let mut members = Vec::with_capacity(func.arguments.len()); + + write!(self.out, "struct {}", &struct_name)?; + writeln!(self.out, " {{")?; + + for arg in func.arguments.iter() { + let member_name = if let Some(ref name) = arg.name { + name + } else { + "member" + }; + let member = EpStructMember { + name: self.namer.call_unique(member_name), + ty: arg.ty, + binding: arg.binding.clone(), + }; + + write!(self.out, "{}", INDENT)?; + self.write_type(module, member.ty)?; + write!(self.out, " {}", &member.name)?; + if let Some(ref binding) = member.binding { + self.write_binding(binding)?; + } + write!(self.out, ";")?; + writeln!(self.out)?; + + members.push(member); + } + + writeln!(self.out, "}};")?; + writeln!(self.out)?; + + let ep_input = EntryPointBinding { + stage, + name: struct_name, + members, + }; + + self.ep_inputs.insert(index, Some(ep_input)); + } + + Ok(()) + } + + /// Helper method used to write global variables + /// # Notes + /// Always adds a newline + fn write_global(&mut self, module: &Module, handle: Handle) -> BackendResult { + let global = &module.global_variables[handle]; + let inner = &module.types[global.ty].inner; + + let register_ty = match *inner { + TypeInner::Image { .. } => "t", + TypeInner::Sampler { .. } => "s", + // TODO: other register ty https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register + _ => return Err(Error::Unimplemented(format!("register_ty {:?}", inner))), + }; + + let register = if let Some(ref binding) = global.binding { + format!("register({}{})", register_ty, binding.binding) + } else { + String::from("") + }; + + let name = self.names[&NameKey::GlobalVariable(handle)].clone(); + self.write_type(module, global.ty)?; + write!(self.out, " {}", name)?; + + if register.is_empty() { + writeln!(self.out, ";")?; + } else { + writeln!(self.out, " : {};", register)?; + } + + Ok(()) + } + + /// Helper method used to write global constants + /// + /// # Notes + /// Ends in a newline + fn write_global_constant( + &mut self, + _module: &Module, + inner: &ConstantInner, + handle: Handle, + ) -> BackendResult { + match *inner { + ConstantInner::Scalar { + width: _, + ref value, + } => { + let name = &self.names[&NameKey::Constant(handle)]; + let (ty, value) = match *value { + crate::ScalarValue::Sint(value) => ("int", format!("{}", value)), + crate::ScalarValue::Uint(value) => ("uint", format!("{}", value)), + crate::ScalarValue::Float(value) => { + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero + ("float", format!("{:?}", value)) + } + crate::ScalarValue::Bool(value) => ("bool", format!("{}", value)), + }; + writeln!(self.out, "static const {} {} = {};", ty, name, value)?; + } + ConstantInner::Composite { .. } => { + return Err(Error::Unimplemented(format!( + "write_global_constant Composite {:?}", + inner + ))) + } + } + // End with extra newline for readability + writeln!(self.out)?; + Ok(()) + } + + /// Helper method used to write structs + /// + /// # Notes + /// Ends in a newline + fn write_struct( + &mut self, + module: &Module, + handle: Handle, + _block: bool, + members: &[StructMember], + ) -> BackendResult { + // Write struct name + write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?; + writeln!(self.out, " {{")?; + + for (index, member) in members.iter().enumerate() { + // The indentation is only for readability + write!(self.out, "{}", INDENT)?; + // Write struct member type and name + self.write_type(module, member.ty)?; + let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; + write!(self.out, " {}", member_name)?; + if let Some(ref binding) = member.binding { + self.write_binding(binding)?; + }; + write!(self.out, ";")?; + writeln!(self.out)?; + } + + writeln!(self.out, "}};")?; + Ok(()) + } + /// Helper method used to write non image/sampler types /// /// # Notes @@ -131,6 +385,52 @@ impl Writer { TypeInner::Scalar { kind, width } => { write!(self.out, "{}", scalar_kind_str(kind, width)?)?; } + TypeInner::Vector { size, kind, width } => { + write!( + self.out, + "{}{}", + scalar_kind_str(kind, width)?, + vector_size_str(size) + )?; + } + TypeInner::Matrix { + columns, + rows, + width, + } => { + //TODO: int matrix ? + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-matrix + write!( + self.out, + "{}{}x{}", + scalar_kind_str(ScalarKind::Float, width)?, + vector_size_str(columns), + vector_size_str(rows), + )?; + } + TypeInner::Image { + dim, + arrayed: _, //TODO: + class, + } => { + let dim_str = image_dimension_str(dim); + if let crate::ImageClass::Sampled { kind, multi: false } = class { + write!( + self.out, + "Texture{}<{}4>", + dim_str, + scalar_kind_str(kind, 4)? + )? + } else { + return Err(Error::Unimplemented(format!( + "write_value_type {:?}", + inner + ))); + } + } + TypeInner::Sampler { comparison: false } => { + write!(self.out, "SamplerState")?; + } _ => { return Err(Error::Unimplemented(format!( "write_value_type {:?}", @@ -148,6 +448,7 @@ impl Writer { fn write_function( &mut self, module: &Module, + name: &str, func: &Function, func_ctx: &FunctionCtx<'_>, ) -> BackendResult { @@ -158,51 +459,60 @@ impl Writer { write!(self.out, "void")?; } - let func_name = match func_ctx.ty { - FunctionType::EntryPoint(index) => self.names[&NameKey::EntryPoint(index)].clone(), - FunctionType::Function(handle) => self.names[&NameKey::Function(handle)].clone(), - }; - // Write function name - write!(self.out, " {}(", func_name)?; + write!(self.out, " {}(", name)?; - // Write function arguments - for (index, arg) in func.arguments.iter().enumerate() { - // Write argument type - self.write_type(module, arg.ty)?; + // Write function arguments for non entry point functions + match func_ctx.ty { + FunctionType::Function(handle) => { + for (index, arg) in func.arguments.iter().enumerate() { + // Write argument type + self.write_type(module, arg.ty)?; - let argument_name = match func_ctx.ty { - FunctionType::Function(handle) => { - self.names[&NameKey::FunctionArgument(handle, index as u32)].clone() + let argument_name = + &self.names[&NameKey::FunctionArgument(handle, index as u32)]; + + // Write argument name. Space is important. + write!(self.out, " {}", argument_name)?; + if index < func.arguments.len() - 1 { + // Add a separator between args + write!(self.out, ", ")?; + } } - FunctionType::EntryPoint(ep_index) => { - self.names[&NameKey::EntryPointArgument(ep_index, index as u32)].clone() + } + FunctionType::EntryPoint(index) => { + // EntryPoint arguments wrapped into structure + if !self.ep_inputs.is_empty() { + if let Some(ref ep_input) = self.ep_inputs[index as usize] { + write!( + self.out, + "{} {}", + ep_input.name, + self.namer + .call_unique(ep_input.name.to_lowercase().as_str()) + )?; + } } - }; - - // Write argument name. Space is important. - write!(self.out, " {}", argument_name)?; - if index < func.arguments.len() - 1 { - // Add a separator between args - write!(self.out, ", ")?; } } // Ends of arguments write!(self.out, ")")?; // Write semantic if it present + let stage = match func_ctx.ty { + FunctionType::EntryPoint(index) => Some(module.entry_points[index as usize].stage), + _ => None, + }; if let Some(ref result) = func.result { if let Some(ref binding) = result.binding { match *binding { crate::Binding::BuiltIn(builtin) => { - write!(self.out, " : {}", builtin_str(builtin)?)? + write!(self.out, " : {}", builtin_str(builtin))?; } - // TODO: Is this reachable ? - crate::Binding::Location { .. } => { - return Err(Error::Unimplemented(format!( - "write_function semantic {:?}", - binding - ))) + crate::Binding::Location { location, .. } => { + if stage == Some(ShaderStage::Fragment) { + write!(self.out, " : SV_Target{}", location)?; + } } } } @@ -267,14 +577,105 @@ impl Writer { indent: usize, ) -> BackendResult { match *stmt { - Statement::Return { value } => { - write!(self.out, "{}return", INDENT.repeat(indent))?; - if let Some(return_value) = value { - // The leading space is important - write!(self.out, " ")?; - self.write_expr(module, return_value, func_ctx)?; + Statement::Emit(ref range) => { + for handle in range.clone() { + let expr_name = if let Some(name) = func_ctx.named_expressions.get(&handle) { + // Front end provides names for all variables at the start of writing. + // But we write them to step by step. We need to recache them + // Otherwise, we could accidentally write variable name instead of full expression. + // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. + Some(self.namer.call_unique(name)) + } else { + let min_ref_count = func_ctx.expressions[handle].bake_ref_count(); + if min_ref_count <= func_ctx.info[handle].ref_count { + Some(format!("_expr{}", handle.index())) + } else { + None + } + }; + + if let Some(name) = expr_name { + write!(self.out, "{}", INDENT.repeat(indent))?; + self.write_named_expr(module, handle, name, func_ctx)?; + } + } + } + // TODO: copy-paste from glsl-out + Statement::Block(ref block) => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "{{")?; + for sta in block.iter() { + // Increase the indentation to help with readability + self.write_stmt(module, sta, func_ctx, indent + 1)? + } + writeln!(self.out, "{}}}", INDENT.repeat(indent))? + } + // TODO: copy-paste from glsl-out + Statement::If { + condition, + ref accept, + ref reject, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "if (")?; + self.write_expr(module, condition, func_ctx)?; + writeln!(self.out, ") {{")?; + + for sta in accept { + // Increase indentation to help with readability + self.write_stmt(module, sta, func_ctx, indent + 1)?; + } + + // If there are no statements in the reject block we skip writing it + // This is only for readability + if !reject.is_empty() { + writeln!(self.out, "{}}} else {{", INDENT.repeat(indent))?; + + for sta in reject { + // Increase indentation to help with readability + self.write_stmt(module, sta, func_ctx, indent + 1)?; + } + } + + writeln!(self.out, "{}}}", INDENT.repeat(indent))? + } + // TODO: copy-paste from glsl-out + Statement::Kill => writeln!(self.out, "{}discard;", INDENT.repeat(indent))?, + Statement::Return { value: None } => { + writeln!(self.out, "{}return;", INDENT.repeat(indent))?; + } + Statement::Return { value: Some(expr) } => { + let base_ty_res = &func_ctx.info[expr].ty; + let mut resolved = base_ty_res.inner_with(&module.types); + if let TypeInner::Pointer { base, class: _ } = *resolved { + resolved = &module.types[base].inner; + } + + if let TypeInner::Struct { .. } = *resolved { + // We can safery unwrap here, since we now we working with struct + let ty = base_ty_res.handle().unwrap(); + let struct_name = &self.names[&NameKey::Type(ty)]; + let variable_name = self.namer.call_unique(struct_name.as_str()).to_lowercase(); + write!( + self.out, + "{}const {} {} = ", + INDENT.repeat(indent), + struct_name, + variable_name + )?; + self.write_expr(module, expr, func_ctx)?; + writeln!(self.out)?; + writeln!( + self.out, + "{}return {};", + INDENT.repeat(indent), + variable_name + )?; + } else { + write!(self.out, "{}return ", INDENT.repeat(indent))?; + self.write_expr(module, expr, func_ctx)?; + writeln!(self.out, ";")? } - writeln!(self.out, ";")?; } _ => return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))), } @@ -288,7 +689,7 @@ impl Writer { /// Doesn't add any newlines or leading/trailing spaces fn write_expr( &mut self, - _module: &Module, + module: &Module, expr: Handle, func_ctx: &FunctionCtx<'_>, ) -> BackendResult { @@ -299,10 +700,119 @@ impl Writer { let expression = &func_ctx.expressions[expr]; - #[allow(clippy::match_single_binding)] match *expression { + Expression::Constant(constant) => self.write_constant(module, constant)?, + Expression::Compose { ty, ref components } => { + let is_struct = if let TypeInner::Struct { .. } = module.types[ty].inner { + true + } else { + false + }; + if is_struct { + write!(self.out, "{{ ")?; + } else { + self.write_type(module, ty)?; + write!(self.out, "(")?; + } + for (index, component) in components.iter().enumerate() { + self.write_expr(module, *component, func_ctx)?; + // Only write a comma if isn't the last element + if index != components.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } + if is_struct { + write!(self.out, " }};")? + } else { + write!(self.out, ")")? + } + } + // TODO: copy-paste from wgsl-out + Expression::Binary { op, left, right } => { + write!(self.out, "(")?; + self.write_expr(module, left, func_ctx)?; + write!(self.out, " {} ", crate::back::binary_operation_str(op))?; + self.write_expr(module, right, func_ctx)?; + write!(self.out, ")")?; + } + // TODO: copy-paste from glsl-out + Expression::AccessIndex { base, index } => { + self.write_expr(module, base, func_ctx)?; + + let base_ty_res = &func_ctx.info[base].ty; + let mut resolved = base_ty_res.inner_with(&module.types); + let base_ty_handle = match *resolved { + TypeInner::Pointer { base, class: _ } => { + resolved = &module.types[base].inner; + Some(base) + } + _ => base_ty_res.handle(), + }; + + match *resolved { + TypeInner::Vector { .. } => { + // Write vector access as a swizzle + write!(self.out, ".{}", COMPONENTS[index as usize])? + } + TypeInner::Matrix { .. } + | TypeInner::Array { .. } + | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, + TypeInner::Struct { .. } => { + // This will never panic in case the type is a `Struct`, this is not true + // for other types so we can only check while inside this match arm + let ty = base_ty_handle.unwrap(); + + write!( + self.out, + ".{}", + &self.names[&NameKey::StructMember(ty, index)] + )? + } + ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), + } + } + Expression::FunctionArgument(pos) => { + let name = match func_ctx.ty { + FunctionType::Function(handle) => { + self.names[&NameKey::FunctionArgument(handle, pos)].clone() + } + FunctionType::EntryPoint(index) => { + // EntryPoint arguments wrapped into structure + // We can safery unwrap here, because if we write function arguments it means, that ep_input struct already exists + let ep_input = self.ep_inputs[index as usize].as_ref().unwrap(); + let member_name = &ep_input.members[pos as usize].name; + format!("{}.{}", &ep_input.name.to_lowercase(), member_name) + } + }; + write!(self.out, "{}", name)?; + } + Expression::ImageSample { + image, + sampler, // TODO: + coordinate, // TODO: + array_index: _, // TODO: + offset: _, // TODO: + level: _, // TODO: + depth_ref: _, // TODO: + } => { + // TODO: others + self.write_expr(module, image, func_ctx)?; + write!(self.out, ".Sample(")?; + self.write_expr(module, sampler, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, coordinate, func_ctx)?; + write!(self.out, ")")?; + } + // TODO: copy-paste from wgsl-out + Expression::GlobalVariable(handle) => { + let name = &self.names[&NameKey::GlobalVariable(handle)]; + write!(self.out, "{}", name)?; + } _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } + + Ok(()) } /// Helper method used to write constants @@ -311,8 +821,13 @@ impl Writer { /// Doesn't add any newlines or leading/trailing spaces fn write_constant(&mut self, module: &Module, handle: Handle) -> BackendResult { let constant = &module.constants[handle]; - #[allow(clippy::match_single_binding)] match constant.inner { + crate::ConstantInner::Scalar { + width: _, + ref value, + } => { + self.write_scalar_value(*value)?; + } _ => { return Err(Error::Unimplemented(format!( "write_constant {:?}", @@ -320,6 +835,65 @@ impl Writer { ))) } } + + Ok(()) + } + + /// Helper method used to write [`ScalarValue`](ScalarValue) + /// + /// # Notes + /// Adds no trailing or leading whitespace + fn write_scalar_value(&mut self, value: ScalarValue) -> BackendResult { + match value { + ScalarValue::Sint(value) => write!(self.out, "{}", value)?, + ScalarValue::Uint(value) => write!(self.out, "{}u", value)?, + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero + ScalarValue::Float(value) => write!(self.out, "{:?}", value)?, + ScalarValue::Bool(value) => write!(self.out, "{}", value)?, + } + + Ok(()) + } + + fn write_named_expr( + &mut self, + module: &Module, + handle: Handle, + name: String, + ctx: &FunctionCtx, + ) -> BackendResult { + match ctx.info[handle].ty { + TypeResolution::Handle(ty_handle) => match module.types[ty_handle].inner { + TypeInner::Struct { .. } => { + let ty_name = &self.names[&NameKey::Type(ty_handle)]; + write!(self.out, "{}", ty_name)?; + } + _ => { + self.write_type(module, ty_handle)?; + } + }, + TypeResolution::Value(ref inner) => { + self.write_value_type(module, inner)?; + } + } + + let base_ty_res = &ctx.info[handle].ty; + let resolved = base_ty_res.inner_with(&module.types); + + // If rhs is a array type, we should write temp variable as a dynamic array + let array_str = if let TypeInner::Array { .. } = *resolved { + "[]" + } else { + "" + }; + + write!(self.out, " {}{} = ", name, array_str)?; + self.write_expr(module, handle, ctx)?; + writeln!(self.out, ";")?; + self.named_expressions.insert(handle, name); + + Ok(()) } pub fn finish(self) -> W { @@ -336,12 +910,28 @@ fn image_dimension_str(dim: ImageDimension) -> &'static str { } } -fn builtin_str(built_in: crate::BuiltIn) -> Result<&'static str, Error> { - use crate::BuiltIn; +fn builtin_str(built_in: BuiltIn) -> &'static str { match built_in { - BuiltIn::Position => Ok("SV_Position"), - BuiltIn::PointSize => Err(Error::UnsupportedBuiltIn(built_in)), - _ => Err(Error::Unimplemented(format!("builtin_str {:?}", built_in))), + BuiltIn::Position => "SV_Position", + // vertex + BuiltIn::ClipDistance => "SV_ClipDistance", + BuiltIn::CullDistance => "SV_CullDistance", + BuiltIn::InstanceIndex => "SV_InstanceID", + // based on this page https://docs.microsoft.com/en-us/windows/uwp/gaming/glsl-to-hlsl-reference#comparing-opengl-es-20-with-direct3d-11 + // No meaning unless you target Direct3D 9 + BuiltIn::PointSize => "PSIZE", + BuiltIn::VertexIndex => "SV_VertexID", + // fragment + BuiltIn::FragDepth => "SV_Depth", + BuiltIn::FrontFacing => "SV_IsFrontFace", + BuiltIn::SampleIndex => "SV_SampleIndex", + BuiltIn::SampleMask => "SV_Coverage", + // compute + BuiltIn::GlobalInvocationId => "SV_DispatchThreadID", + BuiltIn::LocalInvocationId => "SV_GroupThreadID", + BuiltIn::LocalInvocationIndex => "SV_GroupIndex", + BuiltIn::WorkGroupId => "SV_GroupID", + _ => todo!("builtin_str {:?}", built_in), } } diff --git a/src/back/mod.rs b/src/back/mod.rs index 63f84d8f0..49c7c5689 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -40,7 +40,7 @@ impl crate::Expression { /// Helper function that returns the string corresponding to the [`BinaryOperator`](crate::BinaryOperator) /// # Notes -/// Used by `glsl-out`, `msl-out`, `wgsl-out`. +/// Used by `glsl-out`, `msl-out`, `wgsl-out`, `hlsl-out`. #[allow(dead_code)] fn binary_operation_str(op: crate::BinaryOperator) -> &'static str { use crate::BinaryOperator as Bo; @@ -68,7 +68,7 @@ fn binary_operation_str(op: crate::BinaryOperator) -> &'static str { /// Helper function that returns the string corresponding to the [`VectorSize`](crate::VectorSize) /// # Notes -/// Used by `msl-out`, `wgsl-out`. +/// Used by `msl-out`, `wgsl-out`, `hlsl-out`. #[allow(dead_code)] fn vector_size_str(size: crate::VectorSize) -> &'static str { match size { diff --git a/tests/out/empty.Compute.hlsl b/tests/out/empty.Compute.hlsl deleted file mode 100644 index e79d36b9c..000000000 --- a/tests/out/empty.Compute.hlsl +++ /dev/null @@ -1,5 +0,0 @@ -[numthreads(1, 1, 1)] -void main() -{ - return; -} diff --git a/tests/out/empty.hlsl b/tests/out/empty.hlsl index d1d3c9cb2..a1b3590ec 100644 --- a/tests/out/empty.hlsl +++ b/tests/out/empty.hlsl @@ -1,5 +1,5 @@ - -void main() +[numthreads(1, 1, 1)] +void comp_main() { return; } diff --git a/tests/out/empty.hlsl.config b/tests/out/empty.hlsl.config new file mode 100644 index 000000000..f20f94588 --- /dev/null +++ b/tests/out/empty.hlsl.config @@ -0,0 +1,2 @@ +compute=cs_5_0 +compute_name=comp_main diff --git a/tests/out/quad.hlsl b/tests/out/quad.hlsl new file mode 100644 index 000000000..c678e3e8f --- /dev/null +++ b/tests/out/quad.hlsl @@ -0,0 +1,34 @@ +static const float c_scale = 1.2; + +Texture2D u_texture : register(t0); +SamplerState u_sampler : register(s1); + +struct VertexOutput { + float2 uv : LOC0; + float4 position : SV_Position; +}; + +struct VertexInput { + float2 pos1 : LOC0; + float2 uv3 : LOC1; +}; + +struct FragmentInput { + float2 uv4 : LOC0; +}; + +VertexOutput vert_main(VertexInput vertexinput) +{ + const VertexOutput vertexoutput1 = { vertexinput.uv3, float4((1.2 * vertexinput.pos1), 0.0, 1.0) }; + return vertexoutput1; +} + +float4 frag_main(FragmentInput fragmentinput) : SV_Target0 +{ + float4 color = u_texture.Sample(u_sampler, fragmentinput.uv4); + if ((color.w == 0.0)) { + discard; + } + float4 premultiplied = (color.w * color); + return premultiplied; +} diff --git a/tests/out/quad.hlsl.config b/tests/out/quad.hlsl.config new file mode 100644 index 000000000..a11240919 --- /dev/null +++ b/tests/out/quad.hlsl.config @@ -0,0 +1,4 @@ +vertex=vs_5_0 +vertex_name=vert_main +fragment=ps_5_0 +fragment_name=frag_main diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 742bb977e..d3076391b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -107,9 +107,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "hlsl-out")] { if targets.contains(Targets::HLSL) { - for ep in module.entry_points.iter() { - check_output_hlsl(module, &info, &dest, ep.stage); - } + check_output_hlsl(module, &info, &dest); } } #[cfg(feature = "wgsl-out")] @@ -221,18 +219,28 @@ fn check_output_glsl( } #[cfg(feature = "hlsl-out")] -fn check_output_hlsl( - module: &naga::Module, - info: &naga::valid::ModuleInfo, - destination: &PathBuf, - stage: naga::ShaderStage, -) { +fn check_output_hlsl(module: &naga::Module, info: &naga::valid::ModuleInfo, destination: &PathBuf) { use naga::back::hlsl; + let options = hlsl::Options::default(); + let string = hlsl::write_string(module, info, &options).unwrap(); - let string = hlsl::write_string(module, info, hlsl::ShaderModel::default()).unwrap(); + fs::write(destination.with_extension("hlsl"), string).unwrap(); - let ext = format!("{:?}.hlsl", stage); - fs::write(destination.with_extension(&ext), string).unwrap(); + // We need a config file for validation script + // This file contains an info about profiles (shader stages) contains inside generated shader + // This info will be passed to dxc + let mut config_str = String::from(""); + for ep in module.entry_points.iter() { + let (stage_str, profile, ep_name) = match ep.stage { + naga::ShaderStage::Vertex => ("vertex", "vs_5_0", &options.vertex_entry_point_name), + naga::ShaderStage::Fragment => { + ("fragment", "ps_5_0", &options.fragment_entry_point_name) + } + naga::ShaderStage::Compute => ("compute", "cs_5_0", &options.compute_entry_point_name), + }; + config_str = format!("{}{}={}\n{}_name={}\n", config_str, stage_str, profile, stage_str, ep_name); + } + fs::write(destination.with_extension("hlsl.config"), config_str).unwrap(); } #[cfg(feature = "wgsl-out")] @@ -255,7 +263,12 @@ fn convert_wgsl() { ), ( "quad", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::DOT | Targets::WGSL, + Targets::SPIRV + | Targets::METAL + | Targets::GLSL + | Targets::DOT + | Targets::HLSL + | Targets::WGSL, ), ( "boids", From 822c68067c26082af3124a7455038cbb613c38f0 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 16 Jun 2021 00:05:36 +0300 Subject: [PATCH 0955/2212] Remove all features from README --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index aa18f5cb5..63bf3a2ed 100644 --- a/README.md +++ b/README.md @@ -37,10 +37,10 @@ DOT (GraphViz) | :ok: | dot-out | Not a shading language | Naga includes a default binary target, which allows to test the conversion of different code paths. ```bash -cargo run --features wgsl-in -- my_shader.wgsl # validate only -cargo run --features spv-in -- my_shader.spv my_shader.txt # dump the IR module into a file -cargo run --features spv-in,msl-out -- my_shader.spv my_shader.metal --flow-dir flow-dir # convert the SPV to Metal, also dump the SPIR-V flow graph to `flow-dir` -cargo run --features wgsl-in,glsl-out -- my_shader.wgsl my_shader.vert --profile es310 # convert the WGSL to GLSL vertex stage under ES 3.20 profile +cargo run my_shader.wgsl # validate only +cargo run my_shader.spv my_shader.txt # dump the IR module into a file +cargo run my_shader.spv my_shader.metal --flow-dir flow-dir # convert the SPV to Metal, also dump the SPIR-V flow graph to `flow-dir` +cargo run my_shader.wgsl my_shader.vert --profile es310 # convert the WGSL to GLSL vertex stage under ES 3.20 profile ``` ## Development workflow From fd838169459b68ab79a744741008818030fcf71c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 16 Jun 2021 09:45:13 -0700 Subject: [PATCH 0956/2212] Add `.` to the workspace's default members. Test with no features. Naga is now a workspace with `naga` and `cli` as its two members. The default package for cargo commands is `cli`, so that `cargo run` will just run the CLI. However, this has a few unexpected consequences: - Now `cargo test` will just try to run `cli`'s tests, of which there are none. Adding `"."` to the `default-members` list in the workspace's `Cargo.toml` seems to fix this, without breaking `cargo run`. - Even with `"."` added to `default-members`, `cargo test` will build `naga` by default with the features requested for it in `cli/Cargo.toml`: all the front and back ends, but no `serialize` or `deserialize`. This means that our CI job meant to verify no-feature builds isn't doing that job any more. We need to pass `--package naga` to `cargo test` to make it test naga directly. --- .github/workflows/pipeline.yml | 6 ++++++ Cargo.toml | 6 +++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index cc0f6bb0e..f13460c7a 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -19,7 +19,13 @@ jobs: - uses: actions-rs/cargo@v1 name: Default test with: + # Our intention here is to test `naga` with no features enabled. But + # since `cli` is the default package, a plain `cargo test` will build + # `naga` with the features requested in `cli/Cargo.toml`. Passing + # `--package naga` causes us to use the default features in the + # top-level `Cargo.toml` instead. command: test + args: --package naga - uses: actions-rs/cargo@v1 name: Test all features with: diff --git a/Cargo.toml b/Cargo.toml index 55248d678..341a6300b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,4 +52,8 @@ rspirv = "0.7" [workspace] members = [".", "cli"] -default-members = ["cli"] + +# Include "cli", so that `cargo run` runs the CLI by default. Include ".", so +# that `cargo test` includes naga's own tests by default (but note, using the +# features that `cli/Cargo.toml` requests). +default-members = [".", "cli"] From b1ce49a217f510faa94e08c934acd9712eeebc54 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 16 Jun 2021 13:41:01 +0000 Subject: [PATCH 0957/2212] Remove features from lazy CI task --- .github/workflows/lazy.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index 14f6005c9..cdfb1cef8 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -41,7 +41,7 @@ jobs: - name: Unpack shaders run: cd data && unzip all.zip - name: Build Naga - run: cargo build --release --features spv-in,msl-out --bin naga + run: cargo build --release --bin naga - name: Convert shaders run: for file in data/*.spv ; do echo "Translating" ${file} && target/release/naga --validate 27 ${file} ${file}.metal; done parse-vulkan-tutorial-shaders: @@ -56,7 +56,7 @@ jobs: - name: Download shaders run: git clone https://github.com/SaschaWillems/Vulkan.git - name: Build Naga - run: cargo build --release --features spv-in,msl-out --bin naga + run: cargo build --release --bin naga - name: Convert metal shaders run: | # No needed to stop workflow if we can't validate one file From 1b468edaa463000a3f33aa7cac1180967d2f236d Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 16 Jun 2021 10:04:03 +0300 Subject: [PATCH 0958/2212] Makefile. Move dxc params into a variable --- Makefile | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 30da29c4c..016f7a37e 100644 --- a/Makefile +++ b/Makefile @@ -72,8 +72,9 @@ validate-hlsl: $(SNAPSHOTS_OUT)/*.hlsl fragment="" \ compute="" \ . $${config}; \ - [ ! -z "$${vertex}" ] && echo "Vertex Stage:" && dxc $${file} -T $${vertex} -E $${vertex_name} -Wno-parentheses-equality -Zi -Qembed_debug > /dev/null; \ - [ ! -z "$${fragment}" ] && echo "Fragment Stage:" && dxc $${file} -T $${fragment} -E $${fragment_name} -Wno-parentheses-equality -Zi -Qembed_debug > /dev/null; \ - [ ! -z "$${compute}" ] && echo "Compute Stage:" && dxc $${file} -T $${compute} -E $${compute_name} -Wno-parentheses-equality -Zi -Qembed_debug > /dev/null; \ + DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug;" \ + [ ! -z "$${vertex}" ] && echo "Vertex Stage:" && dxc $${file} -T $${vertex} -E $${vertex_name} $${DXC_PARAMS} > /dev/null; \ + [ ! -z "$${fragment}" ] && echo "Fragment Stage:" && dxc $${file} -T $${fragment} -E $${fragment_name} $${DXC_PARAMS} > /dev/null; \ + [ ! -z "$${compute}" ] && echo "Compute Stage:" && dxc $${file} -T $${compute} -E $${compute_name} $${DXC_PARAMS} > /dev/null; \ echo "======================"; \ done From 96b37aff1f0377f76eb9ddae55ed46121aac2bb1 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 16 Jun 2021 10:04:40 +0300 Subject: [PATCH 0959/2212] [hlsl-out] Reduce heap allocation --- src/back/hlsl/writer.rs | 55 ++++++++++++++++++++++++++++++++--------- tests/out/quad.hlsl | 2 +- tests/snapshots.rs | 5 +++- 3 files changed, 49 insertions(+), 13 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index c2260cf18..019260339 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -100,6 +100,19 @@ impl<'a, W: Write> Writer<'a, W> { self.reset(module); // Write all constants + // For example, input wgsl shader: + // ```wgsl + // let c_scale: f32 = 1.2; + // return VertexOutput(uv, vec4(c_scale * pos, 0.0, 1.0)); + // ``` + // + // Output shader: + // ```hlsl + // static const float c_scale = 1.2; + // const VertexOutput vertexoutput1 = { vertexinput.uv3, float4((c_scale * vertexinput.pos1), 0.0, 1.0) }; + // ``` + // + // If we remove `write_global_constant` `c_scale` will be inlined. for (handle, constant) in module.constants.iter() { if constant.name.is_some() { self.write_global_constant(module, &constant.inner, handle)?; @@ -304,18 +317,29 @@ impl<'a, W: Write> Writer<'a, W> { width: _, ref value, } => { + write!(self.out, "static const ")?; + // Write type + match *value { + crate::ScalarValue::Sint(_) => write!(self.out, "int")?, + crate::ScalarValue::Uint(_) => write!(self.out, "uint")?, + crate::ScalarValue::Float(_) => write!(self.out, "float")?, + crate::ScalarValue::Bool(_) => write!(self.out, "bool")?, + }; let name = &self.names[&NameKey::Constant(handle)]; - let (ty, value) = match *value { - crate::ScalarValue::Sint(value) => ("int", format!("{}", value)), - crate::ScalarValue::Uint(value) => ("uint", format!("{}", value)), + write!(self.out, " {} = ", name)?; + + // Second match required to avoid heap allocation by `format!()` + match *value { + crate::ScalarValue::Sint(value) => write!(self.out, "{}", value)?, + crate::ScalarValue::Uint(value) => write!(self.out, "{}", value)?, crate::ScalarValue::Float(value) => { // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero - ("float", format!("{:?}", value)) + write!(self.out, "{:?}", value)? } - crate::ScalarValue::Bool(value) => ("bool", format!("{}", value)), + crate::ScalarValue::Bool(value) => write!(self.out, "{}", value)?, }; - writeln!(self.out, "static const {} {} = {};", ty, name, value)?; + writeln!(self.out, ";")?; } ConstantInner::Composite { .. } => { return Err(Error::Unimplemented(format!( @@ -773,19 +797,24 @@ impl<'a, W: Write> Writer<'a, W> { } } Expression::FunctionArgument(pos) => { - let name = match func_ctx.ty { + match func_ctx.ty { FunctionType::Function(handle) => { - self.names[&NameKey::FunctionArgument(handle, pos)].clone() + let name = &self.names[&NameKey::FunctionArgument(handle, pos)]; + write!(self.out, "{}", name)?; } FunctionType::EntryPoint(index) => { // EntryPoint arguments wrapped into structure // We can safery unwrap here, because if we write function arguments it means, that ep_input struct already exists let ep_input = self.ep_inputs[index as usize].as_ref().unwrap(); let member_name = &ep_input.members[pos as usize].name; - format!("{}.{}", &ep_input.name.to_lowercase(), member_name) + write!( + self.out, + "{}.{}", + &ep_input.name.to_lowercase(), + member_name + )? } }; - write!(self.out, "{}", name)?; } Expression::ImageSample { image, @@ -826,7 +855,11 @@ impl<'a, W: Write> Writer<'a, W> { width: _, ref value, } => { - self.write_scalar_value(*value)?; + if constant.name.is_some() { + write!(self.out, "{}", &self.names[&NameKey::Constant(handle)])?; + } else { + self.write_scalar_value(*value)?; + } } _ => { return Err(Error::Unimplemented(format!( diff --git a/tests/out/quad.hlsl b/tests/out/quad.hlsl index c678e3e8f..c9685d234 100644 --- a/tests/out/quad.hlsl +++ b/tests/out/quad.hlsl @@ -19,7 +19,7 @@ struct FragmentInput { VertexOutput vert_main(VertexInput vertexinput) { - const VertexOutput vertexoutput1 = { vertexinput.uv3, float4((1.2 * vertexinput.pos1), 0.0, 1.0) }; + const VertexOutput vertexoutput1 = { vertexinput.uv3, float4((c_scale * vertexinput.pos1), 0.0, 1.0) }; return vertexoutput1; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d3076391b..06c48e218 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -238,7 +238,10 @@ fn check_output_hlsl(module: &naga::Module, info: &naga::valid::ModuleInfo, dest } naga::ShaderStage::Compute => ("compute", "cs_5_0", &options.compute_entry_point_name), }; - config_str = format!("{}{}={}\n{}_name={}\n", config_str, stage_str, profile, stage_str, ep_name); + config_str = format!( + "{}{}={}\n{}_name={}\n", + config_str, stage_str, profile, stage_str, ep_name + ); } fs::write(destination.with_extension("hlsl.config"), config_str).unwrap(); } From b79d4c5d85b4f6b3dbac96b839305ba5fa47e1c4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 16 Jun 2021 14:47:59 -0700 Subject: [PATCH 0960/2212] Validator::validate: Remove bogus comment. This comment claims that the following work is being done after global validation, but it actually appears before global validation. --- src/valid/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 3d22cb34e..a6dc0f2c4 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -264,7 +264,6 @@ impl Validator { } } - // doing after the globals, so that `type_flags` is ready for (handle, ty) in module.types.iter() { let ty_info = self .validate_type(handle, &module.types, &module.constants) From b29e853a862940c3dbc318a9532c864dbdb913e0 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 17 Jun 2021 16:08:17 +0300 Subject: [PATCH 0961/2212] Update `wgsl-out` status in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 63bf3a2ed..a3d880d02 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ GLSL | :construction: | glsl-in | Temporarily broken | Back-end | Status | Feature | Notes | --------------- | ------------------ | -------- | ----- | SPIR-V | :white_check_mark: | spv-out | | -WGSL | :construction: | wgsl-out | | +WGSL | :ok: | wgsl-out | | Metal | :white_check_mark: | msl-out | | HLSL | :construction: | hlsl-out | Shader Model 5.0+ (DirectX 11+) | GLSL | :ok: | glsl-out | | From 337014786ca5a59571e27c1719223fce66dccaca Mon Sep 17 00:00:00 2001 From: Frizi Date: Thu, 17 Jun 2021 17:17:46 +0200 Subject: [PATCH 0962/2212] [wgsl-in] use AccessIndex for accesses using constant index --- src/back/msl/writer.rs | 2 +- src/front/wgsl/lexer.rs | 12 ++++++++-- src/front/wgsl/mod.rs | 48 ++++++++++++++++++++++++++++++++++------ tests/out/access.msl | 2 +- tests/out/access.wgsl | 2 +- tests/out/globals.spvasm | 7 +++--- 6 files changed, 58 insertions(+), 15 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e2664e13b..7301c4f06 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -765,7 +765,7 @@ impl Writer { write!(self.out, "[{}]", index)?; } crate::TypeInner::Array { .. } => { - write!(self.out, "[{}]", index)?; + write!(self.out, ".{}[{}]", WRAPPED_ARRAY_FIELD, index)?; } _ => { // unexpected indexing, should fail validation diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index b7b34d231..015b7b99d 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -233,15 +233,23 @@ impl<'a> Lexer<'a> { token } - pub(super) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { + pub(super) fn expect_span( + &mut self, + expected: Token<'a>, + ) -> Result, Error<'a>> { let next = self.next(); if next.0 == expected { - Ok(()) + Ok(next.1) } else { Err(Error::Unexpected(next, ExpectedToken::Token(expected))) } } + pub(super) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { + self.expect_span(expected)?; + Ok(()) + } + pub(super) fn expect_generic_paren(&mut self, expected: char) -> Result<(), Error<'a>> { let next = self.next_generic(); if next.0 == Token::Paren(expected) { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 65abcd01d..cee4cab0a 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -12,7 +12,7 @@ use crate::{ proc::{ ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution, }, - FastHashMap, + ConstantInner, FastHashMap, ScalarValue, }; use self::lexer::Lexer; @@ -26,6 +26,7 @@ use codespan_reporting::{ }; use std::{ borrow::Cow, + convert::TryFrom, io::{self, Write}, iter, num::{NonZeroU32, ParseFloatError, ParseIntError}, @@ -98,6 +99,8 @@ pub enum Error<'a> { #[error("")] BadFloat(Span, ParseFloatError), #[error("")] + BadU32Constant(Span), + #[error("")] BadScalarWidth(Span, &'a str), #[error("")] BadAccessor(Span), @@ -250,6 +253,15 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "expected floating-point literal".into())], notes: vec![err.to_string()], }, + Error::BadU32Constant(ref bad_span) => ParseError { + message: format!( + "expected non-negative integer constant expression, found `{}`", + &source[bad_span.clone()], + ), + labels: vec![(bad_span.clone(), "expected non-negative integer".into())], + notes: vec![], + }, + Error::BadScalarWidth(ref bad_span, width) => ParseError { message: format!("invalid width of `{}` for literal", width,), labels: vec![(bad_span.clone(), "invalid width".into())], @@ -1023,7 +1035,7 @@ impl Parser { ty: char, width: &'a str, token: TokenSpan<'a>, - ) -> Result> { + ) -> Result> { let span = token.1; let value = match ty { 'i' => word @@ -1737,12 +1749,34 @@ impl Parser { } } Token::Paren('[') => { - let _ = lexer.next(); + let (_, open_brace_span) = lexer.next(); let index = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(']'))?; - crate::Expression::Access { - base: handle, - index, + let close_brace_span = lexer.expect_span(Token::Paren(']'))?; + + if let crate::Expression::Constant(constant) = ctx.expressions[index] { + let expr_span = open_brace_span.end..close_brace_span.start; + + let index = match ctx.constants[constant].inner { + ConstantInner::Scalar { + value: ScalarValue::Uint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(expr_span)), + ConstantInner::Scalar { + value: ScalarValue::Sint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(expr_span)), + _ => Err(Error::BadU32Constant(expr_span)), + }?; + + crate::Expression::AccessIndex { + base: handle, + index, + } + } else { + crate::Expression::Access { + base: handle, + index, + } } } _ => { diff --git a/tests/out/access.msl b/tests/out/access.msl index 4ce5bb71e..54f422f4d 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -28,7 +28,7 @@ vertex fooOutput foo( type6 c; float baz = foo1; foo1 = 1.0; - metal::float4 _e9 = bar.matrix[3u]; + metal::float4 _e9 = bar.matrix[3]; float b = _e9.x; int a = bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u]; for(int _i=0; _i<5; ++_i) c.inner[_i] = type6 {a, static_cast(b), 3, 4, 5}.inner[_i]; diff --git a/tests/out/access.wgsl b/tests/out/access.wgsl index f05072bd7..8bb52234a 100644 --- a/tests/out/access.wgsl +++ b/tests/out/access.wgsl @@ -14,7 +14,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let baz: f32 = foo1; foo1 = 1.0; - let _e9: vec4 = bar.matrix[3u]; + let _e9: vec4 = bar.matrix[3]; let b: f32 = _e9.x; let a: i32 = bar.data[(arrayLength(&bar.data) - 1u)]; c = array(a, i32(b), 3, 4, 5); diff --git a/tests/out/globals.spvasm b/tests/out/globals.spvasm index 2668d178d..0e85aa503 100644 --- a/tests/out/globals.spvasm +++ b/tests/out/globals.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 20 +; Bound: 21 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -22,11 +22,12 @@ OpDecorate %11 ArrayStride 4 %12 = OpVariable %13 Workgroup %16 = OpTypeFunction %2 %18 = OpTypePointer Workgroup %10 +%19 = OpConstant %6 3 %15 = OpFunction %2 None %16 %14 = OpLabel OpBranch %17 %17 = OpLabel -%19 = OpAccessChain %18 %12 %7 -OpStore %19 %9 +%20 = OpAccessChain %18 %12 %19 +OpStore %20 %9 OpReturn OpFunctionEnd \ No newline at end of file From a7d3b604dca515a388f62788de423f3f28025814 Mon Sep 17 00:00:00 2001 From: Frizi Date: Thu, 17 Jun 2021 17:45:26 +0200 Subject: [PATCH 0963/2212] [wgsl-in] fix clippy warnings on `to_wgsl` methods --- src/front/wgsl/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index cee4cab0a..bab096fe3 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -364,9 +364,9 @@ impl<'a> Error<'a> { } impl crate::StorageFormat { - pub fn to_wgsl(&self) -> &str { + pub fn to_wgsl(self) -> &'static str { use crate::StorageFormat as Sf; - match *self { + match self { Sf::R8Unorm => "r8unorm", Sf::R8Snorm => "r8snorm", Sf::R8Uint => "r8uint", @@ -574,8 +574,8 @@ impl crate::ScalarKind { /// Format a scalar kind+width as a type is written in wgsl. /// /// Examples: `f32`, `u64`, `bool`. - fn to_wgsl(&self, width: u8) -> String { - let prefix = match *self { + fn to_wgsl(self, width: u8) -> String { + let prefix = match self { crate::ScalarKind::Sint => "i", crate::ScalarKind::Uint => "u", crate::ScalarKind::Float => "f", From bff8b18a01abd314fd4270a51252e5932007d976 Mon Sep 17 00:00:00 2001 From: Frizi Date: Tue, 15 Jun 2021 12:00:10 +0200 Subject: [PATCH 0964/2212] [glsl-in] lower swizzle store to per-component stores --- src/front/glsl/ast.rs | 54 +++++++++++++++++++-- src/front/glsl/variables.rs | 93 +++++++++++++++++-------------------- src/proc/typifier.rs | 11 +++++ src/valid/expression.rs | 7 +++ 4 files changed, 111 insertions(+), 54 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 16dc59708..5367fc74e 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -8,7 +8,7 @@ use crate::{ proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, RelationalFunction, ResourceBinding, Sampling, ScalarKind, ShaderStage, Statement, - StorageClass, Type, TypeInner, UnaryOperator, + StorageClass, SwizzleComponent, Type, TypeInner, UnaryOperator, VectorSize, }; #[derive(Debug, Clone, Copy)] @@ -625,10 +625,56 @@ impl<'function> Context<'function> { self.implicit_conversion(program, &mut value, value_meta, kind)?; } - self.emit_flush(body); - self.emit_start(); + if let Expression::Swizzle { + size, + vector, + pattern, + } = self.expressions[pointer] + { + // Stores to swizzled values are not directly supported, + // lower them as series of per-component stores. + let size = match size { + VectorSize::Bi => 2, + VectorSize::Tri => 3, + VectorSize::Quad => 4, + }; - body.push(Statement::Store { pointer, value }); + #[allow(clippy::needless_range_loop)] + for index in 0..size { + let dst = self.add_expression( + Expression::AccessIndex { + base: vector, + index: match pattern[index] { + SwizzleComponent::X => 0, + SwizzleComponent::Y => 1, + SwizzleComponent::Z => 2, + SwizzleComponent::W => 3, + }, + }, + body, + ); + let src = self.add_expression( + Expression::AccessIndex { + base: value, + index: index as u32, + }, + body, + ); + + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { + pointer: dst, + value: src, + }); + } + } else { + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { pointer, value }); + } value } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 03dd2ddfd..fc54c5daf 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,7 +1,7 @@ use crate::{ Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, ImageClass, - Interpolation, LocalVariable, ScalarKind, StorageAccess, StorageClass, Type, TypeInner, - VectorSize, + Interpolation, LocalVariable, ScalarKind, StorageAccess, StorageClass, SwizzleComponent, Type, + TypeInner, VectorSize, }; use super::ast::*; @@ -146,67 +146,60 @@ impl Program<'_> { )) } // swizzles (xyzw, rgba, stpq) - TypeInner::Vector { size, kind, width } => { + TypeInner::Vector { size, .. } => { let check_swizzle_components = |comps: &str| { name.chars() - .map(|c| { - comps - .find(c) - .and_then(|i| if i < size as usize { Some(i) } else { None }) - }) - .fold(Some(Vec::::new()), |acc, cur| { - cur.and_then(|i| { - acc.map(|mut v| { - v.push(i); - v - }) - }) - }) + .map(|c| comps.find(c).filter(|i| *i < size as usize)) + .collect::>>() }; let indices = check_swizzle_components("xyzw") .or_else(|| check_swizzle_components("rgba")) .or_else(|| check_swizzle_components("stpq")); - if let Some(v) = indices { - let components: Vec> = v - .iter() - .map(|idx| { - ctx.add_expression( - Expression::AccessIndex { - base: expression, - index: *idx as u32, - }, - body, - ) - }) - .collect(); + if let Some(components) = indices { if components.len() == 1 { // only single element swizzle, like pos.y, just return that component - Ok(components[0]) - } else { - let size = match components.len() { - 2 => VectorSize::Bi, - 3 => VectorSize::Tri, - 4 => VectorSize::Quad, - _ => { - return Err(ErrorKind::SemanticError( - meta, - format!("Bad swizzle size for \"{:?}\": {:?}", name, v).into(), - )); - } - }; - Ok(ctx.add_expression( - Expression::Compose { - ty: self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { kind, width, size }, - }), - components, + return Ok(ctx.add_expression( + Expression::AccessIndex { + base: expression, + index: components[0] as u32, }, body, - )) + )); } + + let size = match components.len() { + 2 => VectorSize::Bi, + 3 => VectorSize::Tri, + 4 => VectorSize::Quad, + _ => { + return Err(ErrorKind::SemanticError( + meta, + format!("Bad swizzle size for \"{:?}\": {:?}", name, components) + .into(), + )); + } + }; + + let mut pattern = [SwizzleComponent::X; 4]; + for (pat, index) in pattern.iter_mut().zip(components) { + *pat = match index { + 0 => SwizzleComponent::X, + 1 => SwizzleComponent::Y, + 2 => SwizzleComponent::Z, + _ => SwizzleComponent::W, + }; + } + + Ok(ctx.add_expression( + Expression::Swizzle { + size, + vector: expression, + pattern, + }, + body, + )) } else { Err(ErrorKind::SemanticError( meta, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index c8d2b02df..47adb4d5d 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -322,6 +322,17 @@ impl<'a> ResolveContext<'a> { kind, width, } => TypeResolution::Value(Ti::Vector { size, kind, width }), + Ti::Pointer { base, .. } => match types[base].inner { + Ti::Vector { + size: _, + kind, + width, + } => TypeResolution::Value(Ti::Vector { size, kind, width }), + ref other => { + log::error!("Vector pointer type {:?}", other); + return Err(ResolveError::InvalidVector(vector)); + } + }, ref other => { log::error!("Vector type {:?}", other); return Err(ResolveError::InvalidVector(vector)); diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 561a088a7..313dfa01b 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -233,6 +233,13 @@ impl super::Validator { } => { let vec_size = match *resolver.resolve(vector)? { Ti::Vector { size: vec_size, .. } => vec_size, + Ti::Pointer { base, .. } => match module.types[base].inner { + Ti::Vector { size: vec_size, .. } => vec_size, + ref other => { + log::error!("Swizzle vector pointer type {:?}", other); + return Err(ExpressionError::InvalidVectorType(vector)); + } + }, ref other => { log::error!("Swizzle vector type {:?}", other); return Err(ExpressionError::InvalidVectorType(vector)); From 7c8fbb43772cc8a5efd2ceca071d553cc55d7e45 Mon Sep 17 00:00:00 2001 From: Frizi Date: Tue, 15 Jun 2021 12:02:31 +0200 Subject: [PATCH 0965/2212] [glsl-in] support more math functions and builitns --- src/front/glsl/functions.rs | 5 ++++- src/front/glsl/variables.rs | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 9e7655e4b..9bddc953d 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -270,7 +270,7 @@ impl Program<'_> { Ok(Some(ctx.add_expression(expr, body))) } - "pow" | "dot" | "max" => { + "pow" | "dot" | "max" | "min" | "reflect" | "cross" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } @@ -280,6 +280,9 @@ impl Program<'_> { "pow" => MathFunction::Pow, "dot" => MathFunction::Dot, "max" => MathFunction::Max, + "min" => MathFunction::Min, + "reflect" => MathFunction::Reflect, + "cross" => MathFunction::Cross, _ => unreachable!(), }, arg: args[0].0, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index fc54c5daf..9636281ce 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -115,6 +115,15 @@ impl Program<'_> { false, PrologueStage::COMPUTE, ), + "gl_FrontFacing" => add_builtin( + TypeInner::Scalar { + kind: ScalarKind::Bool, + width: 1, + }, + BuiltIn::FrontFacing, + false, + PrologueStage::FRAGMENT, + ), _ => Ok(None), } } From e6d142f28f51dfcd3d2ca8a7db458c8d9578f77d Mon Sep 17 00:00:00 2001 From: Frizi Date: Tue, 15 Jun 2021 12:09:35 +0200 Subject: [PATCH 0966/2212] [glsl-in] treat const globals as constants allow them in array size exprs --- src/front/glsl/ast.rs | 8 ++++++- src/front/glsl/parser.rs | 43 ++++++++++++++++++++++------------- src/front/glsl/variables.rs | 45 ++++++++++++++++++++----------------- tests/out/quad-glsl.wgsl | 10 ++++----- 4 files changed, 63 insertions(+), 43 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 5367fc74e..00e72e885 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -14,6 +14,7 @@ use crate::{ #[derive(Debug, Clone, Copy)] pub enum GlobalLookupKind { Variable(Handle), + Constant(Handle), BlockSelect(Handle, u32), } @@ -279,6 +280,11 @@ impl<'function> Context<'function> { } }) } + GlobalLookupKind::Constant(v) => { + let res = (this.expressions.append(Expression::Constant(v)), false); + this.emit_start(); + res + } }; let var = VariableReference { @@ -485,7 +491,7 @@ impl<'function> Context<'function> { let handle = match kind { HirExprKind::Access { base, index } => { - let base = self.lower_expect(program, base, lhs, body)?.0; + let base = self.lower_expect(program, base, true, body)?.0; let index = self.lower_expect(program, index, false, body)?.0; let pointer = self.add_expression(Expression::Access { base, index }, body); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 0caa16dd1..575aa27be 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -7,7 +7,7 @@ use super::{ error::ErrorKind, lex::Lexer, token::{SourceMetadata, Token, TokenValue}, - variables::VarDeclaration, + variables::{GlobalOrConstant, VarDeclaration}, Program, }; use crate::{ @@ -115,13 +115,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { /// Parses an optional array_specifier returning `Ok(None)` if there is no /// LeftBracket fn parse_array_specifier(&mut self) -> Result> { - // TODO: expressions - if let Some(&TokenValue::LeftBracket) = self.lexer.peek().map(|t| &t.value) { - self.bump()?; + if self.bump_if(TokenValue::LeftBracket).is_some() { + if self.bump_if(TokenValue::RightBracket).is_some() { + return Ok(Some(ArraySize::Dynamic)); + } + let (constant, _) = self.parse_constant_expression()?; self.expect(TokenValue::RightBracket)?; - - Ok(Some(ArraySize::Dynamic)) + Ok(Some(ArraySize::Constant(constant))) } else { Ok(None) } @@ -801,7 +802,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }; meta = meta.union(&token.meta); - let handle = self.program.add_global_var(VarDeclaration { + let global = self.program.add_global_var(VarDeclaration { qualifiers, ty, name, @@ -817,7 +818,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.program.global_variables.push(( k, GlobalLookup { - kind: GlobalLookupKind::BlockSelect(handle, i), + kind: match global { + GlobalOrConstant::Global(handle) => { + GlobalLookupKind::BlockSelect(handle, i) + } + GlobalOrConstant::Constant(handle) => GlobalLookupKind::Constant(handle), + }, entry_arg: None, mutable: true, }, @@ -832,13 +838,18 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut span = 0; loop { - // TODO: type_qualifier - if !self.peek_type_name() { + if let TokenValue::RightBrace = self.expect_peek()?.value { break; } + // TODO: type_qualifier + let ty = self.parse_type_non_void()?.0; let name = self.expect_ident()?.0; + + let array_specifier = self.parse_array_specifier()?; + let ty = self.maybe_array(ty, array_specifier); + self.expect(TokenValue::Semicolon)?; members.push(StructMember { @@ -848,7 +859,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { offset: span, }); - span = self.program.module.types[ty] + span += self.program.module.types[ty] .inner .span(&self.program.module.constants); } @@ -1691,10 +1702,12 @@ impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { match self.external { true => { - let handle = program.add_global_var(decl)?; - Ok(self - .ctx - .add_expression(Expression::GlobalVariable(handle), self.body)) + let global = program.add_global_var(decl)?; + let expr = match global { + GlobalOrConstant::Global(handle) => Expression::GlobalVariable(handle), + GlobalOrConstant::Constant(handle) => Expression::Constant(handle), + }; + Ok(self.ctx.add_expression(expr, self.body)) } false => program.add_local_var(self.ctx, self.body, decl), } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 9636281ce..3129081e5 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -16,6 +16,11 @@ pub struct VarDeclaration<'a> { pub meta: SourceMetadata, } +pub enum GlobalOrConstant { + Global(Handle), + Constant(Handle), +} + impl Program<'_> { pub fn lookup_variable( &mut self, @@ -232,7 +237,7 @@ impl Program<'_> { init, meta, }: VarDeclaration, - ) -> Result, ErrorKind> { + ) -> Result { let mut storage = StorageQualifier::StorageClass(StorageClass::Private); let mut interpolation = None; let mut binding = None; @@ -384,29 +389,27 @@ impl Program<'_> { )); } - return Ok(handle); + return Ok(GlobalOrConstant::Global(handle)); } else if let StorageQualifier::Const = storage { - let handle = self.module.global_variables.append(GlobalVariable { - name: name.clone(), - class: StorageClass::Private, - binding: None, - ty, - init, - storage_access: StorageAccess::empty(), - }); + if let Some(init) = init { + if let Some(name) = name { + self.global_variables.push(( + name, + GlobalLookup { + kind: GlobalLookupKind::Constant(init), + entry_arg: None, + mutable: false, + }, + )); + } - if let Some(name) = name { - self.global_variables.push(( - name, - GlobalLookup { - kind: GlobalLookupKind::Variable(handle), - entry_arg: None, - mutable: false, - }, + return Ok(GlobalOrConstant::Constant(init)); + } else { + return Err(ErrorKind::SemanticError( + meta, + "const values must have an initializer".into(), )); } - - return Ok(handle); } let (class, storage_access) = match self.module.types[ty].inner { @@ -456,7 +459,7 @@ impl Program<'_> { )); } - Ok(handle) + Ok(GlobalOrConstant::Global(handle)) } pub fn add_local_var( diff --git a/tests/out/quad-glsl.wgsl b/tests/out/quad-glsl.wgsl index 22a9b9b70..fccd8cc2a 100644 --- a/tests/out/quad-glsl.wgsl +++ b/tests/out/quad-glsl.wgsl @@ -7,7 +7,6 @@ struct FragmentOutput { [[location(0), interpolate(perspective)]] member2: vec4; }; -var c_scale: f32 = 1.2000000476837158; var a_pos: vec2; var a_uv: vec2; var v_uv: vec2; @@ -16,11 +15,10 @@ var v_uv1: vec2; var o_color: vec4; fn vert_main() { - let _e1: f32 = c_scale; - let _e3: vec2 = a_pos; - let _e5: vec2 = a_uv; - v_uv = _e5; - gl_Position = vec4((_e1 * _e3), 0.0, 1.0); + let _e2: vec2 = a_pos; + let _e4: vec2 = a_uv; + v_uv = _e4; + gl_Position = vec4((1.2000000476837158 * _e2), 0.0, 1.0); return; } From c7580f2743801a916b0abcdd715eee784fcd6caf Mon Sep 17 00:00:00 2001 From: Frizi Date: Tue, 15 Jun 2021 12:11:40 +0200 Subject: [PATCH 0967/2212] [glsl-in] preserve entrypoint arg names for reflection --- src/front/glsl/ast.rs | 1 + src/front/glsl/functions.rs | 2 +- src/front/glsl/variables.rs | 4 +++- tests/out/quad-glsl.wgsl | 28 ++++++++++++++-------------- 4 files changed, 19 insertions(+), 16 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 00e72e885..ad59dd52a 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -68,6 +68,7 @@ impl From for PrologueStage { #[derive(Debug)] pub struct EntryArg { + pub name: Option, pub binding: Binding, pub handle: Handle, pub prologue: PrologueStage, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 9bddc953d..aa4e1ba02 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -586,7 +586,7 @@ impl Program<'_> { let idx = arguments.len() as u32; arguments.push(FunctionArgument { - name: None, + name: arg.name.clone(), ty, binding: Some(arg.binding.clone()), }); diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 3129081e5..9eafcf88f 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -52,6 +52,7 @@ impl Program<'_> { let idx = self.entry_args.len(); self.entry_args.push(EntryArg { + name: None, binding: Binding::BuiltIn(builtin), handle, prologue, @@ -359,7 +360,7 @@ impl Program<'_> { }); let handle = self.module.global_variables.append(GlobalVariable { - name: name.clone(), + name: name.as_ref().map(|n| format!("gen_entry_{}", n)), class: StorageClass::Private, binding: None, ty, @@ -369,6 +370,7 @@ impl Program<'_> { let idx = self.entry_args.len(); self.entry_args.push(EntryArg { + name: name.clone(), binding: Binding::Location { location, interpolation, diff --git a/tests/out/quad-glsl.wgsl b/tests/out/quad-glsl.wgsl index fccd8cc2a..6e3cb4120 100644 --- a/tests/out/quad-glsl.wgsl +++ b/tests/out/quad-glsl.wgsl @@ -7,32 +7,32 @@ struct FragmentOutput { [[location(0), interpolate(perspective)]] member2: vec4; }; -var a_pos: vec2; -var a_uv: vec2; -var v_uv: vec2; +var gen_entry_a_pos: vec2; +var gen_entry_a_uv: vec2; +var gen_entry_v_uv: vec2; var gl_Position: vec4; -var v_uv1: vec2; -var o_color: vec4; +var gen_entry_v_uv1: vec2; +var gen_entry_o_color: vec4; fn vert_main() { - let _e2: vec2 = a_pos; - let _e4: vec2 = a_uv; - v_uv = _e4; + let _e2: vec2 = gen_entry_a_pos; + let _e4: vec2 = gen_entry_a_uv; + gen_entry_v_uv = _e4; gl_Position = vec4((1.2000000476837158 * _e2), 0.0, 1.0); return; } fn frag_main() { - o_color = vec4(1.0, 1.0, 1.0, 1.0); + gen_entry_o_color = vec4(1.0, 1.0, 1.0, 1.0); return; } [[stage(vertex)]] -fn vert_main1([[location(0), interpolate(perspective)]] param: vec2, [[location(1), interpolate(perspective)]] param1: vec2) -> VertexOutput { - a_pos = param; - a_uv = param1; +fn vert_main1([[location(0), interpolate(perspective)]] a_pos: vec2, [[location(1), interpolate(perspective)]] a_uv: vec2) -> VertexOutput { + gen_entry_a_pos = a_pos; + gen_entry_a_uv = a_uv; vert_main(); - let _e5: vec2 = v_uv; + let _e5: vec2 = gen_entry_v_uv; let _e7: vec4 = gl_Position; return VertexOutput(_e5, _e7); } @@ -40,6 +40,6 @@ fn vert_main1([[location(0), interpolate(perspective)]] param: vec2, [[loca [[stage(fragment)]] fn frag_main1() -> FragmentOutput { frag_main(); - let _e1: vec4 = o_color; + let _e1: vec4 = gen_entry_o_color; return FragmentOutput(_e1); } From ad260062a019c975539f4ce103dab22966d3f8b3 Mon Sep 17 00:00:00 2001 From: Frizi Date: Tue, 15 Jun 2021 12:18:34 +0200 Subject: [PATCH 0968/2212] [glsl-in] parse structs and resolve user-defined types --- src/front/glsl/error.rs | 2 + src/front/glsl/parser.rs | 326 ++++++++++++++++++--------------- src/front/glsl/parser_tests.rs | 40 ++++ 3 files changed, 216 insertions(+), 152 deletions(-) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 8ad9c16aa..924f411d0 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -20,6 +20,8 @@ pub enum ErrorKind { NotImplemented(&'static str), #[error("Unknown variable: {1}")] UnknownVariable(SourceMetadata, String), + #[error("Unknown type: {1}")] + UnknownType(SourceMetadata, String), #[error("Unknown field: {1}")] UnknownField(SourceMetadata, String), #[error("Unknown layout qualifier: {1}")] diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 575aa27be..471dd3dd1 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -130,13 +130,19 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { fn parse_type(&mut self) -> Result<(Option>, SourceMetadata)> { let token = self.bump()?; - let ty = match token.value { + let handle = match token.value { TokenValue::Void => None, - TokenValue::TypeName(ty) => Some(ty), + TokenValue::TypeName(ty) => Some(self.program.module.types.fetch_or_append(ty)), TokenValue::Struct => todo!(), + TokenValue::Identifier(ident) => { + let ty = self.program.lookup_type.get(&ident).cloned(); + if ty.is_none() { + return Err(ErrorKind::UnknownType(token.meta, ident)); + } + ty + } _ => return Err(ErrorKind::InvalidToken(token)), }; - let handle = ty.map(|t| self.program.module.types.fetch_or_append(t)); let size = self.parse_array_specifier()?; Ok((handle.map(|ty| self.maybe_array(ty, size)), token.meta)) @@ -393,8 +399,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } fn peek_type_name(&mut self) -> bool { + let program = &self.program; self.lexer.peek().map_or(false, |t| match t.value { TokenValue::TypeName(_) | TokenValue::Void => true, + TokenValue::Identifier(ref ident) => program.lookup_type.contains_key(ident), _ => false, }) } @@ -584,177 +592,191 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON - if self.peek_type_qualifier() || self.peek_type_name() { - let qualifiers = self.parse_type_qualifiers()?; + let qualifiers = self.parse_type_qualifiers()?; - if self.peek_type_name() { - // This branch handles variables and function prototypes and if - // external is true also function definitions - let (ty, mut meta) = self.parse_type()?; + if self.peek_type_name() { + // This branch handles variables and function prototypes and if + // external is true also function definitions + let (ty, mut meta) = self.parse_type()?; - let token = self.bump()?; - let token_fallthrough = match token.value { - TokenValue::Identifier(name) => match self.expect_peek()?.value { - TokenValue::LeftParen => { - // This branch handles function definition and prototypes - self.bump()?; + let token = self.bump()?; + let token_fallthrough = match token.value { + TokenValue::Identifier(name) => match self.expect_peek()?.value { + TokenValue::LeftParen => { + // This branch handles function definition and prototypes + self.bump()?; - let result = ty.map(|ty| FunctionResult { ty, binding: None }); - let mut expressions = Arena::new(); - let mut local_variables = Arena::new(); - let mut arguments = Vec::new(); - let mut parameters = Vec::new(); - let mut body = Block::new(); - let mut sig = FunctionSignature { - name: name.clone(), - parameters: Vec::new(), - }; + let result = ty.map(|ty| FunctionResult { ty, binding: None }); + let mut expressions = Arena::new(); + let mut local_variables = Arena::new(); + let mut arguments = Vec::new(); + let mut parameters = Vec::new(); + let mut body = Block::new(); + let mut sig = FunctionSignature { + name: name.clone(), + parameters: Vec::new(), + }; - let mut context = Context::new( - self.program, - &mut body, - &mut expressions, - &mut local_variables, - &mut arguments, - ); + let mut context = Context::new( + self.program, + &mut body, + &mut expressions, + &mut local_variables, + &mut arguments, + ); - self.parse_function_args( - &mut context, - &mut body, - &mut parameters, - &mut sig, - )?; + self.parse_function_args( + &mut context, + &mut body, + &mut parameters, + &mut sig, + )?; - let end_meta = self.expect(TokenValue::RightParen)?.meta; - meta = meta.union(&end_meta); + let end_meta = self.expect(TokenValue::RightParen)?.meta; + meta = meta.union(&end_meta); - let token = self.bump()?; - return match token.value { - TokenValue::Semicolon => { - // This branch handles function prototypes - self.program.add_prototype( - Function { - name: Some(name), - result, - arguments, - ..Default::default() - }, - sig, - parameters, - meta, - )?; + let token = self.bump()?; + return match token.value { + TokenValue::Semicolon => { + // This branch handles function prototypes + self.program.add_prototype( + Function { + name: Some(name), + result, + arguments, + ..Default::default() + }, + sig, + parameters, + meta, + )?; - Ok(true) - } - TokenValue::LeftBrace if external => { - // This branch handles function definitions - // as you can see by the guard this branch - // only happens if external is also true + Ok(true) + } + TokenValue::LeftBrace if external => { + // This branch handles function definitions + // as you can see by the guard this branch + // only happens if external is also true - // parse the body - self.parse_compound_statement(&mut context, &mut body)?; + // parse the body + self.parse_compound_statement(&mut context, &mut body)?; - let Context { arg_use, .. } = context; - let handle = self.program.add_function( - Function { - name: Some(name), - result, - expressions, - named_expressions: crate::FastHashMap::default(), - local_variables, - arguments, - body, - }, - sig, - parameters, - meta, - )?; + let Context { arg_use, .. } = context; + let handle = self.program.add_function( + Function { + name: Some(name), + result, + expressions, + named_expressions: crate::FastHashMap::default(), + local_variables, + arguments, + body, + }, + sig, + parameters, + meta, + )?; - self.program.function_arg_use[handle.index()] = arg_use; + self.program.function_arg_use[handle.index()] = arg_use; - Ok(true) - } - _ => Err(ErrorKind::InvalidToken(token)), - }; - } - // Pass the token to the init_declator_list parser - _ => Token { - value: TokenValue::Identifier(name), - meta: token.meta, - }, - }, + Ok(true) + } + _ => Err(ErrorKind::InvalidToken(token)), + }; + } // Pass the token to the init_declator_list parser - _ => token, + _ => Token { + value: TokenValue::Identifier(name), + meta: token.meta, + }, + }, + // Pass the token to the init_declator_list parser + _ => token, + }; + + // If program execution has reached here then this will be a + // init_declarator_list + // token_falltrough will have a token that was already bumped + if let Some(ty) = ty { + let mut ctx = DeclarationContext { + qualifiers, + external, + ctx, + body, }; - // If program execution has reached here then this will be a - // init_declarator_list - // token_falltrough will have a token that was already bumped - if let Some(ty) = ty { - let mut ctx = DeclarationContext { - qualifiers, - external, - ctx, - body, - }; - - self.parse_init_declarator_list(ty, Some(token_fallthrough), &mut ctx)?; - } else { - return Err(ErrorKind::SemanticError( - meta, - "Declaration cannot have void type".into(), - )); - } - - Ok(true) + self.parse_init_declarator_list(ty, Some(token_fallthrough), &mut ctx)?; } else { - // This branch handles struct definitions and modifiers like - // ```glsl - // layout(early_fragment_tests); - // ``` - let token = self.bump()?; - match token.value { - TokenValue::Identifier(ty_name) => { - if self.bump_if(TokenValue::LeftBrace).is_some() { - self.parse_block_declaration(&qualifiers, ty_name, token.meta) - } else { - //TODO: declaration - // type_qualifier IDENTIFIER SEMICOLON - // type_qualifier IDENTIFIER identifier_list SEMICOLON - todo!() - } + return Err(ErrorKind::SemanticError( + meta, + "Declaration cannot have void type".into(), + )); + } + + Ok(true) + } else { + // This branch handles struct definitions and modifiers like + // ```glsl + // layout(early_fragment_tests); + // ``` + let token = self.bump()?; + match token.value { + TokenValue::Identifier(ty_name) => { + if self.bump_if(TokenValue::LeftBrace).is_some() { + self.parse_block_declaration(&qualifiers, ty_name, token.meta) + } else { + //TODO: declaration + // type_qualifier IDENTIFIER SEMICOLON + // type_qualifier IDENTIFIER identifier_list SEMICOLON + todo!() } - TokenValue::Semicolon => { - for &(ref qualifier, meta) in qualifiers.iter() { - match *qualifier { - TypeQualifier::WorkGroupSize(i, value) => { - self.program.workgroup_size[i] = value - } - TypeQualifier::EarlyFragmentTests => { - self.program.early_fragment_tests = true; - } - TypeQualifier::StorageQualifier(_) => { - // TODO: Maybe add some checks here - // This is needed because of cases like - // layout(early_fragment_tests) in; - } - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Qualifier not supported as standalone".into(), - )); - } + } + TokenValue::Semicolon => { + for &(ref qualifier, meta) in qualifiers.iter() { + match *qualifier { + TypeQualifier::WorkGroupSize(i, value) => { + self.program.workgroup_size[i] = value + } + TypeQualifier::EarlyFragmentTests => { + self.program.early_fragment_tests = true; + } + TypeQualifier::StorageQualifier(_) => { + // TODO: Maybe add some checks here + // This is needed because of cases like + // layout(early_fragment_tests) in; + } + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Qualifier not supported as standalone".into(), + )); } } - - Ok(true) } - _ => Err(ErrorKind::InvalidToken(token)), + + Ok(true) } + TokenValue::Struct => { + let ty_name = self.expect_ident()?.0; + self.expect(TokenValue::LeftBrace)?; + let mut members = Vec::new(); + let span = self.parse_struct_declaration_list(&mut members)?; + self.expect(TokenValue::RightBrace)?; + self.expect(TokenValue::Semicolon)?; + + let ty = self.program.module.types.append(Type { + name: Some(ty_name.clone()), + inner: TypeInner::Struct { + top_level: false, + members, + span, + }, + }); + self.program.lookup_type.insert(ty_name, ty); + Ok(true) + } + _ => Err(ErrorKind::InvalidToken(token)), } - } else { - // TODO: Handle precision qualifiers - Ok(false) } } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 5a4374a2c..947fba1c4 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -468,3 +468,43 @@ fn implicit_conversions() { ) .unwrap(); } + +#[test] +fn structs() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Fragment); + + parse_program( + r#" + # version 450 + Test { + vec4 pos; + } xx; + "#, + &entry_points, + ) + .unwrap_err(); + + parse_program( + r#" + # version 450 + struct Test { + vec4 pos; + }; + "#, + &entry_points, + ) + .unwrap(); + + parse_program( + r#" + # version 450 + const int NUM_VECS = 42; + struct Test { + vec4 vecs[NUM_VECS]; + }; + "#, + &entry_points, + ) + .unwrap(); +} From 378ea9d396558a4f07d20034beefaed2e36df1b4 Mon Sep 17 00:00:00 2001 From: Frizi Date: Tue, 15 Jun 2021 12:22:04 +0200 Subject: [PATCH 0969/2212] add more glsl snapshot tests --- tests/in/glsl/931-constant-emitting.vert | 4 +- tests/in/glsl/bevy-pbr.frag | 368 +++++++++++++++++++++++ tests/in/glsl/bevy-pbr.vert | 31 ++ tests/in/glsl/constant-array-size.vert | 14 + tests/in/glsl/swizzle_write.frag | 7 + 5 files changed, 422 insertions(+), 2 deletions(-) create mode 100644 tests/in/glsl/bevy-pbr.frag create mode 100644 tests/in/glsl/bevy-pbr.vert create mode 100644 tests/in/glsl/constant-array-size.vert create mode 100644 tests/in/glsl/swizzle_write.frag diff --git a/tests/in/glsl/931-constant-emitting.vert b/tests/in/glsl/931-constant-emitting.vert index b780eb7ac..6844a7a7f 100644 --- a/tests/in/glsl/931-constant-emitting.vert +++ b/tests/in/glsl/931-constant-emitting.vert @@ -3,8 +3,8 @@ // FIX: #933 #version 450 -const int constant = 10; +const float constant = 10.0; float function() { - return 0.0; + return constant; } diff --git a/tests/in/glsl/bevy-pbr.frag b/tests/in/glsl/bevy-pbr.frag new file mode 100644 index 000000000..4a796dd94 --- /dev/null +++ b/tests/in/glsl/bevy-pbr.frag @@ -0,0 +1,368 @@ +// NOTE: Taken from the bevy repo +#version 450 + +const int MAX_POINT_LIGHTS = 10; +const int MAX_DIRECTIONAL_LIGHTS = 1; + +struct PointLight { + vec4 pos; + vec4 color; + vec4 lightParams; +}; + +struct DirectionalLight { + vec4 direction; + vec4 color; +}; + +layout(location = 0) in vec3 v_WorldPosition; +layout(location = 1) in vec3 v_WorldNormal; +layout(location = 2) in vec2 v_Uv; +layout(location = 3) in vec4 v_WorldTangent; + +layout(location = 0) out vec4 o_Target; + +layout(set = 0, binding = 0) uniform CameraViewProj { + mat4 ViewProj; +}; +layout(std140, set = 0, binding = 1) uniform CameraPosition { + vec4 CameraPos; +}; + +layout(std140, set = 1, binding = 0) uniform Lights { + vec4 AmbientColor; + uvec4 NumLights; // x = point lights, y = directional lights + PointLight PointLights[MAX_POINT_LIGHTS]; + DirectionalLight DirectionalLights[MAX_DIRECTIONAL_LIGHTS]; +}; + +layout(set = 3, binding = 0) uniform StandardMaterial_base_color { + vec4 base_color; +}; + +layout(set = 3, binding = 1) uniform texture2D StandardMaterial_base_color_texture; +layout(set = 3, + binding = 2) uniform sampler StandardMaterial_base_color_texture_sampler; + +layout(set = 3, binding = 3) uniform StandardMaterial_roughness { + float perceptual_roughness; +}; + +layout(set = 3, binding = 4) uniform StandardMaterial_metallic { + float metallic; +}; + +layout(set = 3, binding = 5) uniform texture2D StandardMaterial_metallic_roughness_texture; +layout(set = 3, + binding = 6) uniform sampler StandardMaterial_metallic_roughness_texture_sampler; + +layout(set = 3, binding = 7) uniform StandardMaterial_reflectance { + float reflectance; +}; + +layout(set = 3, binding = 8) uniform texture2D StandardMaterial_normal_map; +layout(set = 3, + binding = 9) uniform sampler StandardMaterial_normal_map_sampler; + +layout(set = 3, binding = 10) uniform texture2D StandardMaterial_occlusion_texture; +layout(set = 3, + binding = 11) uniform sampler StandardMaterial_occlusion_texture_sampler; + +layout(set = 3, binding = 12) uniform StandardMaterial_emissive { + vec4 emissive; +}; + +layout(set = 3, binding = 13) uniform texture2D StandardMaterial_emissive_texture; +layout(set = 3, + binding = 14) uniform sampler StandardMaterial_emissive_texture_sampler; + +# define saturate(x) clamp(x, 0.0, 1.0) +const float PI = 3.141592653589793; + +float pow5(float x) { + float x2 = x * x; + return x2 * x2 * x; +} + +// distanceAttenuation is simply the square falloff of light intensity +// combined with a smooth attenuation at the edge of the light radius +// +// light radius is a non-physical construct for efficiency purposes, +// because otherwise every light affects every fragment in the scene +float getDistanceAttenuation(float distanceSquare, float inverseRangeSquared) { + float factor = distanceSquare * inverseRangeSquared; + float smoothFactor = saturate(1.0 - factor * factor); + float attenuation = smoothFactor * smoothFactor; + return attenuation * 1.0 / max(distanceSquare, 1e-4); +} + +// Normal distribution function (specular D) +// Based on https://google.github.io/filament/Filament.html#citation-walter07 + +// D_GGX(h,α) = α^2 / { π ((n⋅h)^2 (α2−1) + 1)^2 } + +// Simple implementation, has precision problems when using fp16 instead of fp32 +// see https://google.github.io/filament/Filament.html#listing_speculardfp16 +float D_GGX(float roughness, float NoH, const vec3 h) { + float oneMinusNoHSquared = 1.0 - NoH * NoH; + float a = NoH * roughness; + float k = roughness / (oneMinusNoHSquared + a * a); + float d = k * k * (1.0 / PI); + return d; +} + +// Visibility function (Specular G) +// V(v,l,a) = G(v,l,α) / { 4 (n⋅v) (n⋅l) } +// such that f_r becomes +// f_r(v,l) = D(h,α) V(v,l,α) F(v,h,f0) +// where +// V(v,l,α) = 0.5 / { n⋅l sqrt((n⋅v)^2 (1−α2) + α2) + n⋅v sqrt((n⋅l)^2 (1−α2) + α2) } +// Note the two sqrt's, that may be slow on mobile, see https://google.github.io/filament/Filament.html#listing_approximatedspecularv +float V_SmithGGXCorrelated(float roughness, float NoV, float NoL) { + float a2 = roughness * roughness; + float lambdaV = NoL * sqrt((NoV - a2 * NoV) * NoV + a2); + float lambdaL = NoV * sqrt((NoL - a2 * NoL) * NoL + a2); + float v = 0.5 / (lambdaV + lambdaL); + return v; +} + +// Fresnel function +// see https://google.github.io/filament/Filament.html#citation-schlick94 +// F_Schlick(v,h,f_0,f_90) = f_0 + (f_90 − f_0) (1 − v⋅h)^5 +vec3 F_Schlick(const vec3 f0, float f90, float VoH) { + // not using mix to keep the vec3 and float versions identical + return f0 + (vec3(f90) - f0) * pow5(1.0 - VoH); +} + +float F_Schlick(float f0, float f90, float VoH) { + // not using mix to keep the vec3 and float versions identical + return f0 + (f90 - f0) * pow5(1.0 - VoH); +} + +vec3 fresnel(vec3 f0, float LoH) { + // f_90 suitable for ambient occlusion + // see https://google.github.io/filament/Filament.html#lighting/occlusion + float f90 = saturate(dot(f0, vec3(50.0 * 0.33))); + return F_Schlick(f0, f90, LoH); +} + +// Specular BRDF +// https://google.github.io/filament/Filament.html#materialsystem/specularbrdf + +// Cook-Torrance approximation of the microfacet model integration using Fresnel law F to model f_m +// f_r(v,l) = { D(h,α) G(v,l,α) F(v,h,f0) } / { 4 (n⋅v) (n⋅l) } +vec3 specular(vec3 f0, float roughness, const vec3 h, float NoV, float NoL, + float NoH, float LoH, float specularIntensity) { + float D = D_GGX(roughness, NoH, h); + float V = V_SmithGGXCorrelated(roughness, NoV, NoL); + vec3 F = fresnel(f0, LoH); + + return (specularIntensity * D * V) * F; +} + +// Diffuse BRDF +// https://google.github.io/filament/Filament.html#materialsystem/diffusebrdf +// fd(v,l) = σ/π * 1 / { |n⋅v||n⋅l| } ∫Ω D(m,α) G(v,l,m) (v⋅m) (l⋅m) dm + +// simplest approximation +// float Fd_Lambert() { +// return 1.0 / PI; +// } +// +// vec3 Fd = diffuseColor * Fd_Lambert(); + +// Disney approximation +// See https://google.github.io/filament/Filament.html#citation-burley12 +// minimal quality difference +float Fd_Burley(float roughness, float NoV, float NoL, float LoH) { + float f90 = 0.5 + 2.0 * roughness * LoH * LoH; + float lightScatter = F_Schlick(1.0, f90, NoL); + float viewScatter = F_Schlick(1.0, f90, NoV); + return lightScatter * viewScatter * (1.0 / PI); +} + +// From https://www.unrealengine.com/en-US/blog/physically-based-shading-on-mobile +vec3 EnvBRDFApprox(vec3 f0, float perceptual_roughness, float NoV) { + const vec4 c0 = { -1.0, -0.0275, -0.572, 0.022 }; + const vec4 c1 = { 1.0, 0.0425, 1.04, -0.04 }; + vec4 r = vec4(perceptual_roughness) * c0 + c1; + float a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y; + vec2 AB = vec2(-1.04, 1.04) * vec2(a004) + r.zw; + return f0 * vec3(AB.x) + vec3(AB.y); +} + +float perceptualRoughnessToRoughness(float perceptualRoughness) { + // clamp perceptual roughness to prevent precision problems + // According to Filament design 0.089 is recommended for mobile + // Filament uses 0.045 for non-mobile + float clampedPerceptualRoughness = clamp(perceptualRoughness, 0.089, 1.0); + return clampedPerceptualRoughness * clampedPerceptualRoughness; +} + +// from https://64.github.io/tonemapping/ +// reinhard on RGB oversaturates colors +vec3 reinhard(vec3 color) { + return color / (vec3(1.0) + color); +} + +vec3 reinhard_extended(vec3 color, float max_white) { + vec3 numerator = color * (vec3(1.0) + (color / vec3(max_white * max_white))); + return numerator / (vec3(1.0) + color); +} + +// luminance coefficients from Rec. 709. +// https://en.wikipedia.org/wiki/Rec._709 +float luminance(vec3 v) { + return dot(v, vec3(0.2126, 0.7152, 0.0722)); +} + +vec3 change_luminance(vec3 c_in, float l_out) { + float l_in = luminance(c_in); + return c_in * (l_out / l_in); +} + +vec3 reinhard_luminance(vec3 color) { + float l_old = luminance(color); + float l_new = l_old / (1.0f + l_old); + return change_luminance(color, l_new); +} + +vec3 reinhard_extended_luminance(vec3 color, float max_white_l) { + float l_old = luminance(color); + float numerator = l_old * (1.0f + (l_old / (max_white_l * max_white_l))); + float l_new = numerator / (1.0f + l_old); + return change_luminance(color, l_new); +} + +vec3 point_light(PointLight light, float roughness, float NdotV, vec3 N, vec3 V, vec3 R, vec3 F0, vec3 diffuseColor) { + vec3 light_to_frag = light.pos.xyz - v_WorldPosition.xyz; + float distance_square = dot(light_to_frag, light_to_frag); + float rangeAttenuation = + getDistanceAttenuation(distance_square, light.lightParams.r); + + // Specular. + // Representative Point Area Lights. + // see http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf p14-16 + float a = roughness; + float radius = light.lightParams.g; + vec3 centerToRay = dot(light_to_frag, R) * R - light_to_frag; + vec3 closestPoint = light_to_frag + centerToRay * saturate(radius * inversesqrt(dot(centerToRay, centerToRay))); + float LspecLengthInverse = inversesqrt(dot(closestPoint, closestPoint)); + float normalizationFactor = a / saturate(a + (radius * 0.5 * LspecLengthInverse)); + float specularIntensity = normalizationFactor * normalizationFactor; + + vec3 L = closestPoint * LspecLengthInverse; // normalize() equivalent? + vec3 H = normalize(L + V); + float NoL = saturate(dot(N, L)); + float NoH = saturate(dot(N, H)); + float LoH = saturate(dot(L, H)); + + vec3 specular = specular(F0, roughness, H, NdotV, NoL, NoH, LoH, specularIntensity); + + // Diffuse. + // Comes after specular since its NoL is used in the lighting equation. + L = normalize(light_to_frag); + H = normalize(L + V); + NoL = saturate(dot(N, L)); + NoH = saturate(dot(N, H)); + LoH = saturate(dot(L, H)); + + vec3 diffuse = diffuseColor * Fd_Burley(roughness, NdotV, NoL, LoH); + + // Lout = f(v,l) Φ / { 4 π d^2 }⟨n⋅l⟩ + // where + // f(v,l) = (f_d(v,l) + f_r(v,l)) * light_color + // Φ is light intensity + + // our rangeAttentuation = 1 / d^2 multiplied with an attenuation factor for smoothing at the edge of the non-physical maximum light radius + // It's not 100% clear where the 1/4π goes in the derivation, but we follow the filament shader and leave it out + + // See https://google.github.io/filament/Filament.html#mjx-eqn-pointLightLuminanceEquation + // TODO compensate for energy loss https://google.github.io/filament/Filament.html#materialsystem/improvingthebrdfs/energylossinspecularreflectance + // light.color.rgb is premultiplied with light.intensity on the CPU + return ((diffuse + specular) * light.color.rgb) * (rangeAttenuation * NoL); +} + +vec3 dir_light(DirectionalLight light, float roughness, float NdotV, vec3 normal, vec3 view, vec3 R, vec3 F0, vec3 diffuseColor) { + vec3 incident_light = light.direction.xyz; + + vec3 half_vector = normalize(incident_light + view); + float NoL = saturate(dot(normal, incident_light)); + float NoH = saturate(dot(normal, half_vector)); + float LoH = saturate(dot(incident_light, half_vector)); + + vec3 diffuse = diffuseColor * Fd_Burley(roughness, NdotV, NoL, LoH); + float specularIntensity = 1.0; + vec3 specular = specular(F0, roughness, half_vector, NdotV, NoL, NoH, LoH, specularIntensity); + + return (specular + diffuse) * light.color.rgb * NoL; +} + +void main() { + vec4 output_color = base_color; + output_color *= texture(sampler2D(StandardMaterial_base_color_texture, + StandardMaterial_base_color_texture_sampler), + v_Uv); + + // calculate non-linear roughness from linear perceptualRoughness + vec4 metallic_roughness = texture(sampler2D(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler), v_Uv); + // Sampling from GLTF standard channels for now + float metallic = metallic * metallic_roughness.b; + float perceptual_roughness = perceptual_roughness * metallic_roughness.g; + + float roughness = perceptualRoughnessToRoughness(perceptual_roughness); + + vec3 N = normalize(v_WorldNormal); + + vec3 T = normalize(v_WorldTangent.xyz); + vec3 B = cross(N, T) * v_WorldTangent.w; + + N = gl_FrontFacing ? N : -N; + T = gl_FrontFacing ? T : -T; + B = gl_FrontFacing ? B : -B; + + mat3 TBN = mat3(T, B, N); + N = TBN * normalize(texture(sampler2D(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler), v_Uv).rgb * 2.0 - vec3(1.0)); + + float occlusion = texture(sampler2D(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler), v_Uv).r; + + vec4 emissive = emissive; + // TODO use .a for exposure compensation in HDR + emissive.rgb *= texture(sampler2D(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler), v_Uv).rgb; + vec3 V = normalize(CameraPos.xyz - v_WorldPosition.xyz); + // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886" + float NdotV = max(dot(N, V), 1e-4); + + // Remapping [0,1] reflectance to F0 + // See https://google.github.io/filament/Filament.html#materialsystem/parameterization/remapping + vec3 F0 = vec3(0.16 * reflectance * reflectance * (1.0 - metallic)) + output_color.rgb * vec3(metallic); + + // Diffuse strength inversely related to metallicity + vec3 diffuseColor = output_color.rgb * vec3(1.0 - metallic); + + vec3 R = reflect(-V, N); + + // accumulate color + vec3 light_accum = vec3(0.0); + for (int i = 0; i < int(NumLights.x) && i < MAX_POINT_LIGHTS; ++i) { + light_accum += point_light(PointLights[i], roughness, NdotV, N, V, R, F0, diffuseColor); + } + for (int i = 0; i < int(NumLights.y) && i < MAX_DIRECTIONAL_LIGHTS; ++i) { + light_accum += dir_light(DirectionalLights[i], roughness, NdotV, N, V, R, F0, diffuseColor); + } + + vec3 diffuse_ambient = EnvBRDFApprox(diffuseColor, 1.0, NdotV); + vec3 specular_ambient = EnvBRDFApprox(F0, perceptual_roughness, NdotV); + + output_color.rgb = light_accum; + output_color.rgb += (diffuse_ambient + specular_ambient) * AmbientColor.xyz * occlusion; + output_color.rgb += emissive.rgb * output_color.a; + + // tone_mapping + output_color.rgb = reinhard_luminance(output_color.rgb); + // Gamma correction. + // Not needed with sRGB buffer + // output_color.rgb = pow(output_color.rgb, vec3(1.0 / 2.2)); + + o_Target = output_color; +} diff --git a/tests/in/glsl/bevy-pbr.vert b/tests/in/glsl/bevy-pbr.vert new file mode 100644 index 000000000..21b12106b --- /dev/null +++ b/tests/in/glsl/bevy-pbr.vert @@ -0,0 +1,31 @@ +// NOTE: Taken from the bevy repo +#version 450 + +layout(location = 0) in vec3 Vertex_Position; +layout(location = 1) in vec3 Vertex_Normal; +layout(location = 2) in vec2 Vertex_Uv; + +layout(location = 3) in vec4 Vertex_Tangent; + +layout(location = 0) out vec3 v_WorldPosition; +layout(location = 1) out vec3 v_WorldNormal; +layout(location = 2) out vec2 v_Uv; + +layout(set = 0, binding = 0) uniform CameraViewProj { + mat4 ViewProj; +}; + +layout(location = 3) out vec4 v_WorldTangent; + +layout(set = 2, binding = 0) uniform Transform { + mat4 Model; +}; + +void main() { + vec4 world_position = Model * vec4(Vertex_Position, 1.0); + v_WorldPosition = world_position.xyz; + v_WorldNormal = mat3(Model) * Vertex_Normal; + v_Uv = Vertex_Uv; + v_WorldTangent = vec4(mat3(Model) * Vertex_Tangent.xyz, Vertex_Tangent.w); + gl_Position = ViewProj * world_position; +} diff --git a/tests/in/glsl/constant-array-size.vert b/tests/in/glsl/constant-array-size.vert new file mode 100644 index 000000000..f1c7a500e --- /dev/null +++ b/tests/in/glsl/constant-array-size.vert @@ -0,0 +1,14 @@ +#version 450 + +const int NUM_VECS = 42; +layout(std140, set = 1, binding = 0) uniform Data { + vec4 vecs[NUM_VECS]; +}; + +vec4 function() { + vec4 sum = vec4(0); + for (int i = 0; i < NUM_VECS; i++) { + sum += vecs[i]; + } + return sum; +} diff --git a/tests/in/glsl/swizzle_write.frag b/tests/in/glsl/swizzle_write.frag new file mode 100644 index 000000000..c4e91ed75 --- /dev/null +++ b/tests/in/glsl/swizzle_write.frag @@ -0,0 +1,7 @@ +#version 450 + + +void main() { + vec3 x = vec3(2.0); + x.rg *= 2.0; +} From b261dde77f0168f6519da6ac2680ddfd5754c4d5 Mon Sep 17 00:00:00 2001 From: Frizi Date: Tue, 15 Jun 2021 18:01:28 +0200 Subject: [PATCH 0970/2212] [glsl-in] revert test case change --- tests/in/glsl/931-constant-emitting.vert | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/in/glsl/931-constant-emitting.vert b/tests/in/glsl/931-constant-emitting.vert index 6844a7a7f..b780eb7ac 100644 --- a/tests/in/glsl/931-constant-emitting.vert +++ b/tests/in/glsl/931-constant-emitting.vert @@ -3,8 +3,8 @@ // FIX: #933 #version 450 -const float constant = 10.0; +const int constant = 10; float function() { - return constant; + return 0.0; } From f85c896ddfd13694bc46af8da1bc04034af5c43e Mon Sep 17 00:00:00 2001 From: Frizi Date: Tue, 15 Jun 2021 18:03:32 +0200 Subject: [PATCH 0971/2212] [glsl-in] require at least one item inside struct_declaration_list --- src/front/glsl/parser.rs | 8 ++++---- src/front/glsl/parser_tests.rs | 9 +++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 471dd3dd1..a17d241d9 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -860,10 +860,6 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut span = 0; loop { - if let TokenValue::RightBrace = self.expect_peek()?.value { - break; - } - // TODO: type_qualifier let ty = self.parse_type_non_void()?.0; @@ -884,6 +880,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { span += self.program.module.types[ty] .inner .span(&self.program.module.constants); + + if let TokenValue::RightBrace = self.expect_peek()?.value { + break; + } } Ok(span) diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 947fba1c4..88f252761 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -507,4 +507,13 @@ fn structs() { &entry_points, ) .unwrap(); + + parse_program( + r#" + # version 450 + struct Test {}; + "#, + &entry_points, + ) + .unwrap_err(); } From 25c0dd22ccf337377e766ecc7c534d82ffad7b4f Mon Sep 17 00:00:00 2001 From: Frizi Date: Tue, 15 Jun 2021 18:10:06 +0200 Subject: [PATCH 0972/2212] [glsl-in] simplify parse_type identifier case --- src/front/glsl/parser.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index a17d241d9..f9cdf8a12 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -134,13 +134,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Void => None, TokenValue::TypeName(ty) => Some(self.program.module.types.fetch_or_append(ty)), TokenValue::Struct => todo!(), - TokenValue::Identifier(ident) => { - let ty = self.program.lookup_type.get(&ident).cloned(); - if ty.is_none() { - return Err(ErrorKind::UnknownType(token.meta, ident)); - } - ty - } + TokenValue::Identifier(ident) => match self.program.lookup_type.get(&ident) { + Some(ty) => Some(*ty), + None => return Err(ErrorKind::UnknownType(token.meta, ident)), + }, _ => return Err(ErrorKind::InvalidToken(token)), }; From 60c44b06112c1d8dc006194577f78b4dfec78b1e Mon Sep 17 00:00:00 2001 From: Frizi Date: Wed, 16 Jun 2021 17:28:49 +0200 Subject: [PATCH 0973/2212] [glsl-in] create temp var for swizzles used as out parameters --- src/front/glsl/ast.rs | 7 ++++++ src/front/glsl/functions.rs | 50 ++++++++++++++++++++++++++++++++++--- 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index ad59dd52a..571c5f569 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -805,6 +805,13 @@ impl<'function> Context<'function> { .and_then(type_power)) } + pub fn expr_is_swizzle(&mut self, expr: Handle) -> bool { + match self.expressions[expr] { + Expression::Swizzle { .. } => true, + _ => false, + } + } + pub fn implicit_conversion( &mut self, program: &mut Program, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index aa4e1ba02..ad888467a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,7 +1,7 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Block, EntryPoint, Expression, Function, - FunctionArgument, FunctionResult, Handle, MathFunction, RelationalFunction, SampleLevel, - ScalarKind, Statement, StructMember, SwizzleComponent, Type, TypeInner, + FunctionArgument, FunctionResult, Handle, LocalVariable, MathFunction, RelationalFunction, + SampleLevel, ScalarKind, Statement, StructMember, SwizzleComponent, Type, TypeInner, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; @@ -369,9 +369,30 @@ impl Program<'_> { .clone(); let mut arguments = Vec::with_capacity(raw_args.len()); + let mut proxy_writes = Vec::new(); for (qualifier, expr) in fun.qualifiers.iter().zip(raw_args.iter()) { let handle = ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?.0; - arguments.push(handle) + if qualifier.is_lhs() && ctx.expr_is_swizzle(handle) { + let meta = ctx.hir_exprs[*expr].meta; + let ty = self.resolve_handle(ctx, handle, meta)?; + let temp_var = ctx.locals.append(LocalVariable { + name: None, + ty, + init: None, + }); + let temp_expr = + ctx.add_expression(Expression::LocalVariable(temp_var), body); + + body.push(Statement::Store { + pointer: temp_expr, + value: handle, + }); + + arguments.push(temp_expr); + proxy_writes.push((*expr, temp_expr)); + } else { + arguments.push(handle); + } } ctx.emit_flush(body); @@ -388,6 +409,29 @@ impl Program<'_> { result, }); + ctx.emit_start(); + for (tgt, pointer) in proxy_writes { + let load = ctx.add_expression(Expression::Load { pointer }, body); + let temp_ref = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Variable(VariableReference { + expr: pointer, + load: Some(load), + mutable: true, + entry_arg: None, + }), + meta, + }); + let assign = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Assign { + tgt, + value: temp_ref, + }, + meta, + }); + + let _ = ctx.lower_expect(self, assign, false, body)?; + } + ctx.emit_flush(body); ctx.emit_start(); Ok(result) From 96980727cbb63430f0ebdfe3f73306f8034449ea Mon Sep 17 00:00:00 2001 From: Frizi Date: Wed, 16 Jun 2021 20:24:30 +0200 Subject: [PATCH 0974/2212] [glsl-in] support nested swizzles and prevent l-value repeated components --- src/front/glsl/ast.rs | 18 ++---- src/front/glsl/functions.rs | 18 ++---- src/front/glsl/parser_tests.rs | 44 +++++++++++++ src/front/glsl/variables.rs | 107 +++++++++++++++++++------------ src/lib.rs | 26 ++++++++ tests/in/glsl/swizzle_write.frag | 3 +- 6 files changed, 147 insertions(+), 69 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 571c5f569..d1b6a7f41 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -8,7 +8,7 @@ use crate::{ proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, RelationalFunction, ResourceBinding, Sampling, ScalarKind, ShaderStage, Statement, - StorageClass, SwizzleComponent, Type, TypeInner, UnaryOperator, VectorSize, + StorageClass, Type, TypeInner, UnaryOperator, VectorSize, }; #[derive(Debug, Clone, Copy)] @@ -511,7 +511,7 @@ impl<'function> Context<'function> { HirExprKind::Select { base, field } => { let base = self.lower_expect(program, base, lhs, body)?.0; - program.field_selection(self, body, base, &field, meta)? + program.field_selection(self, lhs, body, base, &field, meta)? } HirExprKind::Constant(constant) if !lhs => { self.add_expression(Expression::Constant(constant), body) @@ -651,12 +651,7 @@ impl<'function> Context<'function> { let dst = self.add_expression( Expression::AccessIndex { base: vector, - index: match pattern[index] { - SwizzleComponent::X => 0, - SwizzleComponent::Y => 1, - SwizzleComponent::Z => 2, - SwizzleComponent::W => 3, - }, + index: pattern[index].index(), }, body, ); @@ -805,11 +800,8 @@ impl<'function> Context<'function> { .and_then(type_power)) } - pub fn expr_is_swizzle(&mut self, expr: Handle) -> bool { - match self.expressions[expr] { - Expression::Swizzle { .. } => true, - _ => false, - } + pub fn expr(&self, expr: Handle) -> &Expression { + &self.expressions[expr] } pub fn implicit_conversion( diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index ad888467a..d63245b0b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -48,12 +48,7 @@ impl Program<'_> { Expression::Swizzle { size, vector: args[0].0, - pattern: [ - SwizzleComponent::X, - SwizzleComponent::Y, - SwizzleComponent::Z, - SwizzleComponent::W, - ], + pattern: SwizzleComponent::XYZW, }, body, ); @@ -93,12 +88,7 @@ impl Program<'_> { Expression::Swizzle { size: rows, vector, - pattern: [ - SwizzleComponent::X, - SwizzleComponent::Y, - SwizzleComponent::Z, - SwizzleComponent::W, - ], + pattern: SwizzleComponent::XYZW, }, body, ); @@ -372,7 +362,9 @@ impl Program<'_> { let mut proxy_writes = Vec::new(); for (qualifier, expr) in fun.qualifiers.iter().zip(raw_args.iter()) { let handle = ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?.0; - if qualifier.is_lhs() && ctx.expr_is_swizzle(handle) { + if qualifier.is_lhs() + && matches! { ctx.expr(handle), &Expression::Swizzle { .. } } + { let meta = ctx.hir_exprs[*expr].meta; let ty = self.resolve_handle(ctx, handle, meta)?; let temp_var = ctx.locals.append(LocalVariable { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 88f252761..9d203e942 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -517,3 +517,47 @@ fn structs() { ) .unwrap_err(); } + +#[test] +fn swizzles() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Fragment); + + parse_program( + r#" + # version 450 + void main() { + vec4 v = vec4(1); + v.xyz = vec3(2); + v.x = 5.0; + v.xyz.zxy.yx.xy = vec2(5.0, 1.0); + } + "#, + &entry_points, + ) + .unwrap(); + + parse_program( + r#" + # version 450 + void main() { + vec4 v = vec4(1); + v.xx = vec2(5.0); + } + "#, + &entry_points, + ) + .unwrap_err(); + + parse_program( + r#" + # version 450 + void main() { + vec3 v = vec3(1); + v.w = 2.0; + } + "#, + &entry_points, + ) + .unwrap_err(); +} diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 9eafcf88f..72fff5e2a 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -137,6 +137,7 @@ impl Program<'_> { pub fn field_selection( &mut self, ctx: &mut Context, + lhs: bool, body: &mut Block, expression: Handle, name: &str, @@ -164,49 +165,76 @@ impl Program<'_> { TypeInner::Vector { size, .. } => { let check_swizzle_components = |comps: &str| { name.chars() - .map(|c| comps.find(c).filter(|i| *i < size as usize)) - .collect::>>() + .map(|c| { + comps + .find(c) + .filter(|i| *i < size as usize) + .map(|i| SwizzleComponent::from_index(i as u32)) + }) + .collect::>>() }; - let indices = check_swizzle_components("xyzw") + let components = check_swizzle_components("xyzw") .or_else(|| check_swizzle_components("rgba")) .or_else(|| check_swizzle_components("stpq")); - if let Some(components) = indices { - if components.len() == 1 { - // only single element swizzle, like pos.y, just return that component - return Ok(ctx.add_expression( - Expression::AccessIndex { - base: expression, - index: components[0] as u32, - }, - body, - )); + if let Some(components) = components { + if lhs { + let not_unique = (1..components.len()) + .any(|i| components[i..].contains(&components[i - 1])); + if not_unique { + return Err(ErrorKind::SemanticError( + meta, + format!( + "swizzle cannot have duplicate components in left-hand-side expression for \"{:?}\"", + name + ) + .into(), + )); + } + } + + let mut pattern = [SwizzleComponent::X; 4]; + for (pat, component) in pattern.iter_mut().zip(&components) { + *pat = *component; + } + + // flatten nested swizzles (vec.zyx.xy.x => vec.z) + let mut expression = expression; + if let Expression::Swizzle { + size: _, + ref vector, + pattern: ref src_pattern, + } = *ctx.expr(expression) + { + expression = *vector; + for pat in &mut pattern { + *pat = src_pattern[pat.index() as usize]; + } } let size = match components.len() { + 1 => { + // only single element swizzle, like pos.y, just return that component + return Ok(ctx.add_expression( + Expression::AccessIndex { + base: expression, + index: pattern[0].index(), + }, + body, + )); + } 2 => VectorSize::Bi, 3 => VectorSize::Tri, 4 => VectorSize::Quad, _ => { return Err(ErrorKind::SemanticError( meta, - format!("Bad swizzle size for \"{:?}\": {:?}", name, components) - .into(), + format!("Bad swizzle size for \"{:?}\"", name).into(), )); } }; - let mut pattern = [SwizzleComponent::X; 4]; - for (pat, index) in pattern.iter_mut().zip(components) { - *pat = match index { - 0 => SwizzleComponent::X, - 1 => SwizzleComponent::Y, - 2 => SwizzleComponent::Z, - _ => SwizzleComponent::W, - }; - } - Ok(ctx.add_expression( Expression::Swizzle { size, @@ -393,25 +421,20 @@ impl Program<'_> { return Ok(GlobalOrConstant::Global(handle)); } else if let StorageQualifier::Const = storage { - if let Some(init) = init { - if let Some(name) = name { - self.global_variables.push(( - name, - GlobalLookup { - kind: GlobalLookupKind::Constant(init), - entry_arg: None, - mutable: false, - }, - )); - } - - return Ok(GlobalOrConstant::Constant(init)); - } else { - return Err(ErrorKind::SemanticError( - meta, - "const values must have an initializer".into(), + let init = init.ok_or_else(|| { + ErrorKind::SemanticError(meta, "const values must have an initializer".into()) + })?; + if let Some(name) = name { + self.global_variables.push(( + name, + GlobalLookup { + kind: GlobalLookupKind::Constant(init), + entry_arg: None, + mutable: false, + }, )); } + return Ok(GlobalOrConstant::Constant(init)); } let (class, storage_access) = match self.module.types[ty].inner { diff --git a/src/lib.rs b/src/lib.rs index b2ab989b9..9942b9983 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -773,6 +773,32 @@ pub enum SwizzleComponent { W = 3, } +impl SwizzleComponent { + pub const XYZW: [SwizzleComponent; 4] = [ + SwizzleComponent::X, + SwizzleComponent::Y, + SwizzleComponent::Z, + SwizzleComponent::W, + ]; + + pub fn index(&self) -> u32 { + match *self { + SwizzleComponent::X => 0, + SwizzleComponent::Y => 1, + SwizzleComponent::Z => 2, + SwizzleComponent::W => 3, + } + } + pub fn from_index(idx: u32) -> Self { + match idx { + 0 => SwizzleComponent::X, + 1 => SwizzleComponent::Y, + 2 => SwizzleComponent::Z, + _ => SwizzleComponent::W, + } + } +} + bitflags::bitflags! { /// Memory barrier flags. #[cfg_attr(feature = "serialize", derive(Serialize))] diff --git a/tests/in/glsl/swizzle_write.frag b/tests/in/glsl/swizzle_write.frag index c4e91ed75..9f11d7e5f 100644 --- a/tests/in/glsl/swizzle_write.frag +++ b/tests/in/glsl/swizzle_write.frag @@ -3,5 +3,6 @@ void main() { vec3 x = vec3(2.0); - x.rg *= 2.0; + x.zxy.xy = vec2(3.0, 4.0); + x.rg *= 5.0; } From 3d5e6d51a0383b25124fca60c048ace28a9f669b Mon Sep 17 00:00:00 2001 From: Frizi Date: Wed, 16 Jun 2021 22:12:25 +0200 Subject: [PATCH 0975/2212] [glsl-in] make sure swizzles never operate on a pointer value --- src/front/glsl/ast.rs | 8 ++++++-- src/front/glsl/functions.rs | 2 +- src/front/glsl/variables.rs | 34 +++++++++++++++++++++++++++------- src/proc/typifier.rs | 11 ----------- src/valid/expression.rs | 7 ------- 5 files changed, 34 insertions(+), 28 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index d1b6a7f41..04b162f27 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -634,7 +634,7 @@ impl<'function> Context<'function> { if let Expression::Swizzle { size, - vector, + mut vector, pattern, } = self.expressions[pointer] { @@ -646,6 +646,10 @@ impl<'function> Context<'function> { VectorSize::Quad => 4, }; + if let Expression::Load { pointer } = self.expressions[vector] { + vector = pointer; + } + #[allow(clippy::needless_range_loop)] for index in 0..size { let dst = self.add_expression( @@ -800,7 +804,7 @@ impl<'function> Context<'function> { .and_then(type_power)) } - pub fn expr(&self, expr: Handle) -> &Expression { + pub fn get_expression(&self, expr: Handle) -> &Expression { &self.expressions[expr] } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index d63245b0b..0b74492e2 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -363,7 +363,7 @@ impl Program<'_> { for (qualifier, expr) in fun.qualifiers.iter().zip(raw_args.iter()) { let handle = ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?.0; if qualifier.is_lhs() - && matches! { ctx.expr(handle), &Expression::Swizzle { .. } } + && matches! { ctx.get_expression(handle), &Expression::Swizzle { .. } } { let meta = ctx.hir_exprs[*expr].meta; let ty = self.resolve_handle(ctx, handle, meta)?; diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 72fff5e2a..1b48c8d0f 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -143,9 +143,9 @@ impl Program<'_> { name: &str, meta: SourceMetadata, ) -> Result, ErrorKind> { - let ty = match *self.resolve_type(ctx, expression, meta)? { - TypeInner::Pointer { base, .. } => &self.module.types[base].inner, - ref ty => ty, + let (ty, is_pointer) = match *self.resolve_type(ctx, expression, meta)? { + TypeInner::Pointer { base, .. } => (&self.module.types[base].inner, true), + ref ty => (ty, false), }; match *ty { TypeInner::Struct { ref members, .. } => { @@ -203,11 +203,11 @@ impl Program<'_> { let mut expression = expression; if let Expression::Swizzle { size: _, - ref vector, + vector, pattern: ref src_pattern, - } = *ctx.expr(expression) + } = *ctx.get_expression(expression) { - expression = *vector; + expression = vector; for pat in &mut pattern { *pat = src_pattern[pat.index() as usize]; } @@ -215,7 +215,15 @@ impl Program<'_> { let size = match components.len() { 1 => { - // only single element swizzle, like pos.y, just return that component + // only single element swizzle, like pos.y, just return that component. + if lhs { + // Because of possible nested swizzles, like pos.xy.x, we have to unwrap the potential load expr. + if let Expression::Load { ref pointer } = + *ctx.get_expression(expression) + { + expression = *pointer; + } + } return Ok(ctx.add_expression( Expression::AccessIndex { base: expression, @@ -235,6 +243,18 @@ impl Program<'_> { } }; + if is_pointer { + // NOTE: for lhs expression, this extra load ends up as an unused expr, because the + // assignment will extract the pointer and use it directly anyway. Unfortunately we + // need it for validation to pass, as swizzles cannot operate on pointer values. + expression = ctx.add_expression( + Expression::Load { + pointer: expression, + }, + body, + ); + } + Ok(ctx.add_expression( Expression::Swizzle { size, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 47adb4d5d..c8d2b02df 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -322,17 +322,6 @@ impl<'a> ResolveContext<'a> { kind, width, } => TypeResolution::Value(Ti::Vector { size, kind, width }), - Ti::Pointer { base, .. } => match types[base].inner { - Ti::Vector { - size: _, - kind, - width, - } => TypeResolution::Value(Ti::Vector { size, kind, width }), - ref other => { - log::error!("Vector pointer type {:?}", other); - return Err(ResolveError::InvalidVector(vector)); - } - }, ref other => { log::error!("Vector type {:?}", other); return Err(ResolveError::InvalidVector(vector)); diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 313dfa01b..561a088a7 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -233,13 +233,6 @@ impl super::Validator { } => { let vec_size = match *resolver.resolve(vector)? { Ti::Vector { size: vec_size, .. } => vec_size, - Ti::Pointer { base, .. } => match module.types[base].inner { - Ti::Vector { size: vec_size, .. } => vec_size, - ref other => { - log::error!("Swizzle vector pointer type {:?}", other); - return Err(ExpressionError::InvalidVectorType(vector)); - } - }, ref other => { log::error!("Swizzle vector type {:?}", other); return Err(ExpressionError::InvalidVectorType(vector)); From 1d39a92c8beff69a9bccf1ad2182be3bdaaa2385 Mon Sep 17 00:00:00 2001 From: Frizi Date: Wed, 16 Jun 2021 23:50:02 +0200 Subject: [PATCH 0976/2212] [glsl-in] parse structs inside parse_type --- src/front/glsl/functions.rs | 7 + src/front/glsl/parser.rs | 341 +++++++++++++++++---------------- src/front/glsl/parser_tests.rs | 24 +++ 3 files changed, 204 insertions(+), 168 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 0b74492e2..27a796aee 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -117,6 +117,13 @@ impl Program<'_> { body, ) } + TypeInner::Struct { .. } => ctx.add_expression( + Expression::Compose { + ty, + components: args.into_iter().map(|arg| arg.0).collect(), + }, + body, + ), _ => return Err(ErrorKind::SemanticError(meta, "Bad cast".into())), } } else { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index f9cdf8a12..ff9b39279 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -133,7 +133,24 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let handle = match token.value { TokenValue::Void => None, TokenValue::TypeName(ty) => Some(self.program.module.types.fetch_or_append(ty)), - TokenValue::Struct => todo!(), + TokenValue::Struct => { + let ty_name = self.expect_ident()?.0; + self.expect(TokenValue::LeftBrace)?; + let mut members = Vec::new(); + let span = self.parse_struct_declaration_list(&mut members)?; + self.expect(TokenValue::RightBrace)?; + + let ty = self.program.module.types.append(Type { + name: Some(ty_name.clone()), + inner: TypeInner::Struct { + top_level: false, + members, + span, + }, + }); + self.program.lookup_type.insert(ty_name, ty); + Some(ty) + } TokenValue::Identifier(ident) => match self.program.lookup_type.get(&ident) { Some(ty) => Some(*ty), None => return Err(ErrorKind::UnknownType(token.meta, ident)), @@ -399,6 +416,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let program = &self.program; self.lexer.peek().map_or(false, |t| match t.value { TokenValue::TypeName(_) | TokenValue::Void => true, + TokenValue::Struct => true, TokenValue::Identifier(ref ident) => program.lookup_type.contains_key(ident), _ => false, }) @@ -589,191 +607,176 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON - let qualifiers = self.parse_type_qualifiers()?; + if self.peek_type_qualifier() || self.peek_type_name() { + let qualifiers = self.parse_type_qualifiers()?; - if self.peek_type_name() { - // This branch handles variables and function prototypes and if - // external is true also function definitions - let (ty, mut meta) = self.parse_type()?; + if self.peek_type_name() { + // This branch handles variables and function prototypes and if + // external is true also function definitions + let (ty, mut meta) = self.parse_type()?; - let token = self.bump()?; - let token_fallthrough = match token.value { - TokenValue::Identifier(name) => match self.expect_peek()?.value { - TokenValue::LeftParen => { - // This branch handles function definition and prototypes - self.bump()?; + let token = self.bump()?; + let token_fallthrough = match token.value { + TokenValue::Identifier(name) => match self.expect_peek()?.value { + TokenValue::LeftParen => { + // This branch handles function definition and prototypes + self.bump()?; - let result = ty.map(|ty| FunctionResult { ty, binding: None }); - let mut expressions = Arena::new(); - let mut local_variables = Arena::new(); - let mut arguments = Vec::new(); - let mut parameters = Vec::new(); - let mut body = Block::new(); - let mut sig = FunctionSignature { - name: name.clone(), - parameters: Vec::new(), - }; + let result = ty.map(|ty| FunctionResult { ty, binding: None }); + let mut expressions = Arena::new(); + let mut local_variables = Arena::new(); + let mut arguments = Vec::new(); + let mut parameters = Vec::new(); + let mut body = Block::new(); + let mut sig = FunctionSignature { + name: name.clone(), + parameters: Vec::new(), + }; - let mut context = Context::new( - self.program, - &mut body, - &mut expressions, - &mut local_variables, - &mut arguments, - ); + let mut context = Context::new( + self.program, + &mut body, + &mut expressions, + &mut local_variables, + &mut arguments, + ); - self.parse_function_args( - &mut context, - &mut body, - &mut parameters, - &mut sig, - )?; + self.parse_function_args( + &mut context, + &mut body, + &mut parameters, + &mut sig, + )?; - let end_meta = self.expect(TokenValue::RightParen)?.meta; - meta = meta.union(&end_meta); + let end_meta = self.expect(TokenValue::RightParen)?.meta; + meta = meta.union(&end_meta); - let token = self.bump()?; - return match token.value { - TokenValue::Semicolon => { - // This branch handles function prototypes - self.program.add_prototype( - Function { - name: Some(name), - result, - arguments, - ..Default::default() - }, - sig, - parameters, - meta, - )?; + let token = self.bump()?; + return match token.value { + TokenValue::Semicolon => { + // This branch handles function prototypes + self.program.add_prototype( + Function { + name: Some(name), + result, + arguments, + ..Default::default() + }, + sig, + parameters, + meta, + )?; - Ok(true) - } - TokenValue::LeftBrace if external => { - // This branch handles function definitions - // as you can see by the guard this branch - // only happens if external is also true + Ok(true) + } + TokenValue::LeftBrace if external => { + // This branch handles function definitions + // as you can see by the guard this branch + // only happens if external is also true - // parse the body - self.parse_compound_statement(&mut context, &mut body)?; + // parse the body + self.parse_compound_statement(&mut context, &mut body)?; - let Context { arg_use, .. } = context; - let handle = self.program.add_function( - Function { - name: Some(name), - result, - expressions, - named_expressions: crate::FastHashMap::default(), - local_variables, - arguments, - body, - }, - sig, - parameters, - meta, - )?; + let Context { arg_use, .. } = context; + let handle = self.program.add_function( + Function { + name: Some(name), + result, + expressions, + named_expressions: crate::FastHashMap::default(), + local_variables, + arguments, + body, + }, + sig, + parameters, + meta, + )?; - self.program.function_arg_use[handle.index()] = arg_use; + self.program.function_arg_use[handle.index()] = arg_use; - Ok(true) - } - _ => Err(ErrorKind::InvalidToken(token)), - }; - } - // Pass the token to the init_declator_list parser - _ => Token { - value: TokenValue::Identifier(name), - meta: token.meta, + Ok(true) + } + _ => Err(ErrorKind::InvalidToken(token)), + }; + } + // Pass the token to the init_declator_list parser + _ => Token { + value: TokenValue::Identifier(name), + meta: token.meta, + }, }, - }, - // Pass the token to the init_declator_list parser - _ => token, - }; - - // If program execution has reached here then this will be a - // init_declarator_list - // token_falltrough will have a token that was already bumped - if let Some(ty) = ty { - let mut ctx = DeclarationContext { - qualifiers, - external, - ctx, - body, + // Pass the token to the init_declator_list parser + _ => token, }; - self.parse_init_declarator_list(ty, Some(token_fallthrough), &mut ctx)?; - } else { - return Err(ErrorKind::SemanticError( - meta, - "Declaration cannot have void type".into(), - )); - } + // If program execution has reached here then this will be a + // init_declarator_list + // token_falltrough will have a token that was already bumped + if let Some(ty) = ty { + let mut ctx = DeclarationContext { + qualifiers, + external, + ctx, + body, + }; - Ok(true) - } else { - // This branch handles struct definitions and modifiers like - // ```glsl - // layout(early_fragment_tests); - // ``` - let token = self.bump()?; - match token.value { - TokenValue::Identifier(ty_name) => { - if self.bump_if(TokenValue::LeftBrace).is_some() { - self.parse_block_declaration(&qualifiers, ty_name, token.meta) - } else { - //TODO: declaration - // type_qualifier IDENTIFIER SEMICOLON - // type_qualifier IDENTIFIER identifier_list SEMICOLON - todo!() - } + self.parse_init_declarator_list(ty, Some(token_fallthrough), &mut ctx)?; + } else { + return Err(ErrorKind::SemanticError( + meta, + "Declaration cannot have void type".into(), + )); } - TokenValue::Semicolon => { - for &(ref qualifier, meta) in qualifiers.iter() { - match *qualifier { - TypeQualifier::WorkGroupSize(i, value) => { - self.program.workgroup_size[i] = value - } - TypeQualifier::EarlyFragmentTests => { - self.program.early_fragment_tests = true; - } - TypeQualifier::StorageQualifier(_) => { - // TODO: Maybe add some checks here - // This is needed because of cases like - // layout(early_fragment_tests) in; - } - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Qualifier not supported as standalone".into(), - )); - } + + Ok(true) + } else { + // This branch handles struct definitions and modifiers like + // ```glsl + // layout(early_fragment_tests); + // ``` + let token = self.bump()?; + match token.value { + TokenValue::Identifier(ty_name) => { + if self.bump_if(TokenValue::LeftBrace).is_some() { + self.parse_block_declaration(&qualifiers, ty_name, token.meta) + } else { + //TODO: declaration + // type_qualifier IDENTIFIER SEMICOLON + // type_qualifier IDENTIFIER identifier_list SEMICOLON + todo!() } } + TokenValue::Semicolon => { + for &(ref qualifier, meta) in qualifiers.iter() { + match *qualifier { + TypeQualifier::WorkGroupSize(i, value) => { + self.program.workgroup_size[i] = value + } + TypeQualifier::EarlyFragmentTests => { + self.program.early_fragment_tests = true; + } + TypeQualifier::StorageQualifier(_) => { + // TODO: Maybe add some checks here + // This is needed because of cases like + // layout(early_fragment_tests) in; + } + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Qualifier not supported as standalone".into(), + )); + } + } + } - Ok(true) + Ok(true) + } + _ => Err(ErrorKind::InvalidToken(token)), } - TokenValue::Struct => { - let ty_name = self.expect_ident()?.0; - self.expect(TokenValue::LeftBrace)?; - let mut members = Vec::new(); - let span = self.parse_struct_declaration_list(&mut members)?; - self.expect(TokenValue::RightBrace)?; - self.expect(TokenValue::Semicolon)?; - - let ty = self.program.module.types.append(Type { - name: Some(ty_name.clone()), - inner: TypeInner::Struct { - top_level: false, - members, - span, - }, - }); - self.program.lookup_type.insert(ty_name, ty); - Ok(true) - } - _ => Err(ErrorKind::InvalidToken(token)), } + } else { + Ok(false) } } @@ -962,11 +965,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let expr = if self.bump_if(TokenValue::LeftParen).is_some() { let args = self.parse_function_call_args(ctx, body, &mut meta)?; + let kind = match self.program.lookup_type.get(&name) { + Some(ty) => FunctionCallKind::TypeConstructor(*ty), + None => FunctionCallKind::Function(name), + }; + HirExpr { - kind: HirExprKind::Call(FunctionCall { - kind: FunctionCallKind::Function(name), - args, - }), + kind: HirExprKind::Call(FunctionCall { kind, args }), meta, } } else { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 9d203e942..9bed09ffa 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -508,6 +508,19 @@ fn structs() { ) .unwrap(); + parse_program( + r#" + # version 450 + struct Hello { + vec4 test; + } test() { + return Hello( vec4(1.0) ); + } + "#, + &entry_points, + ) + .unwrap(); + parse_program( r#" # version 450 @@ -516,6 +529,17 @@ fn structs() { &entry_points, ) .unwrap_err(); + + parse_program( + r#" + # version 450 + inout struct Test { + vec4 x; + }; + "#, + &entry_points, + ) + .unwrap_err(); } #[test] From 20c6fd18624e765e73d72b6d4941e74056876741 Mon Sep 17 00:00:00 2001 From: Frizi Date: Thu, 17 Jun 2021 00:11:32 +0200 Subject: [PATCH 0977/2212] add license headers to the bevy pbr shaders --- tests/in/glsl/bevy-pbr.frag | 22 ++++++++++++++++++++++ tests/in/glsl/bevy-pbr.vert | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/tests/in/glsl/bevy-pbr.frag b/tests/in/glsl/bevy-pbr.frag index 4a796dd94..1c65f9e96 100644 --- a/tests/in/glsl/bevy-pbr.frag +++ b/tests/in/glsl/bevy-pbr.frag @@ -1,3 +1,25 @@ +// MIT License +// +// Copyright (c) 2020 Carter Anderson +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// // NOTE: Taken from the bevy repo #version 450 diff --git a/tests/in/glsl/bevy-pbr.vert b/tests/in/glsl/bevy-pbr.vert index 21b12106b..0afd3f64c 100644 --- a/tests/in/glsl/bevy-pbr.vert +++ b/tests/in/glsl/bevy-pbr.vert @@ -1,3 +1,25 @@ +// MIT License +// +// Copyright (c) 2020 Carter Anderson +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// // NOTE: Taken from the bevy repo #version 450 From b439868c0055d0efcf26481fc4a46786d34ad822 Mon Sep 17 00:00:00 2001 From: Frizi Date: Thu, 17 Jun 2021 21:18:12 +0200 Subject: [PATCH 0978/2212] move SwizzleComponent impl into proc module --- src/lib.rs | 26 -------------------------- src/proc/mod.rs | 21 +++++++++++++++++++++ 2 files changed, 21 insertions(+), 26 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9942b9983..b2ab989b9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -773,32 +773,6 @@ pub enum SwizzleComponent { W = 3, } -impl SwizzleComponent { - pub const XYZW: [SwizzleComponent; 4] = [ - SwizzleComponent::X, - SwizzleComponent::Y, - SwizzleComponent::Z, - SwizzleComponent::W, - ]; - - pub fn index(&self) -> u32 { - match *self { - SwizzleComponent::X => 0, - SwizzleComponent::Y => 1, - SwizzleComponent::Z => 2, - SwizzleComponent::W => 3, - } - } - pub fn from_index(idx: u32) -> Self { - match idx { - 0 => SwizzleComponent::X, - 1 => SwizzleComponent::Y, - 2 => SwizzleComponent::Z, - _ => SwizzleComponent::W, - } - } -} - bitflags::bitflags! { /// Memory barrier flags. #[cfg_attr(feature = "serialize", derive(Serialize))] diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 6229f9390..a524981f5 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -267,3 +267,24 @@ impl std::hash::Hash for crate::ScalarValue { } } } + +impl super::SwizzleComponent { + pub const XYZW: [Self; 4] = [Self::X, Self::Y, Self::Z, Self::W]; + + pub fn index(&self) -> u32 { + match *self { + Self::X => 0, + Self::Y => 1, + Self::Z => 2, + Self::W => 3, + } + } + pub fn from_index(idx: u32) -> Self { + match idx { + 0 => Self::X, + 1 => Self::Y, + 2 => Self::Z, + _ => Self::W, + } + } +} From b4909021120c46a54a6f39b8a1d7f66f8db0a475 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 17 Jun 2021 20:09:15 +0100 Subject: [PATCH 0979/2212] [glsl-in] Add loads as needed --- src/front/glsl/ast.rs | 35 +++++++++++------------------------ src/front/glsl/functions.rs | 3 +-- src/front/glsl/variables.rs | 3 +-- tests/out/quad-glsl.wgsl | 4 ++-- 4 files changed, 15 insertions(+), 30 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 04b162f27..d5047dada 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -290,11 +290,7 @@ impl<'function> Context<'function> { let var = VariableReference { expr, - load: if load { - Some(this.add_expression(Expression::Load { pointer: expr }, body)) - } else { - None - }, + load, mutable, entry_arg, }; @@ -349,13 +345,11 @@ impl<'function> Context<'function> { /// Add variable to current scope pub fn add_local_var(&mut self, name: String, expr: Handle, mutable: bool) { if let Some(current) = self.scopes.last_mut() { - let load = self.expressions.append(Expression::Load { pointer: expr }); - (*current).insert( name, VariableReference { expr, - load: Some(load), + load: true, mutable, entry_arg: None, }, @@ -396,13 +390,9 @@ impl<'function> Context<'function> { if let Some(name) = name { let expr = self.add_expression(Expression::FunctionArgument(index as u32), body); let mutable = qualifier != ParameterQualifier::Const; - let load = if qualifier.is_lhs() { - Some(self.add_expression(Expression::Load { pointer: expr }, body)) - } else { - None - }; + let load = qualifier.is_lhs(); - if mutable && load.is_none() { + if mutable && !load { let handle = self.locals.append(LocalVariable { name: Some(name.clone()), ty, @@ -418,19 +408,12 @@ impl<'function> Context<'function> { value: expr, }); - let local_load = self.add_expression( - Expression::Load { - pointer: local_expr, - }, - body, - ); - if let Some(current) = self.scopes.last_mut() { (*current).insert( name, VariableReference { expr: local_expr, - load: Some(local_load), + load: true, mutable, entry_arg: None, }, @@ -584,7 +567,11 @@ impl<'function> Context<'function> { self.arg_use[idx] |= EntryArgUse::READ } - var.load.unwrap_or(var.expr) + if var.load { + self.add_expression(Expression::Load { pointer: var.expr }, body) + } else { + var.expr + } } } HirExprKind::Call(call) if !lhs => { @@ -880,7 +867,7 @@ fn type_power(kind: ScalarKind) -> Option { #[derive(Debug, Clone)] pub struct VariableReference { pub expr: Handle, - pub load: Option>, + pub load: bool, pub mutable: bool, pub entry_arg: Option, } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 27a796aee..8965fd08a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -410,11 +410,10 @@ impl Program<'_> { ctx.emit_start(); for (tgt, pointer) in proxy_writes { - let load = ctx.add_expression(Expression::Load { pointer }, body); let temp_ref = ctx.hir_exprs.append(HirExpr { kind: HirExprKind::Variable(VariableReference { expr: pointer, - load: Some(load), + load: true, mutable: true, entry_arg: None, }), diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 1b48c8d0f..0108adf8f 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -69,12 +69,11 @@ impl Program<'_> { ctx.arg_use.push(EntryArgUse::empty()); let expr = ctx.add_expression(Expression::GlobalVariable(handle), body); - let load = ctx.add_expression(Expression::Load { pointer: expr }, body); ctx.lookup_global_var_exps.insert( name.into(), VariableReference { expr, - load: Some(load), + load: true, mutable, entry_arg: Some(idx), }, diff --git a/tests/out/quad-glsl.wgsl b/tests/out/quad-glsl.wgsl index 6e3cb4120..f03522c39 100644 --- a/tests/out/quad-glsl.wgsl +++ b/tests/out/quad-glsl.wgsl @@ -15,10 +15,10 @@ var gen_entry_v_uv1: vec2; var gen_entry_o_color: vec4; fn vert_main() { - let _e2: vec2 = gen_entry_a_pos; let _e4: vec2 = gen_entry_a_uv; gen_entry_v_uv = _e4; - gl_Position = vec4((1.2000000476837158 * _e2), 0.0, 1.0); + let _e6: vec2 = gen_entry_a_pos; + gl_Position = vec4((1.2000000476837158 * _e6), 0.0, 1.0); return; } From 8a4e7b0c93f66c26689b3108bb7cb40f42dcdae0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 17 Jun 2021 20:29:04 +0100 Subject: [PATCH 0980/2212] [glsl-in] Generate AccessIndex for constant access --- src/front/glsl/ast.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index d5047dada..aff74e9f2 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -7,9 +7,10 @@ use super::{ use crate::{ proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, - RelationalFunction, ResourceBinding, Sampling, ScalarKind, ShaderStage, Statement, + RelationalFunction, ResourceBinding, Sampling, ScalarKind, ScalarValue, ShaderStage, Statement, StorageClass, Type, TypeInner, UnaryOperator, VectorSize, }; +use core::convert::TryFrom; #[derive(Debug, Clone, Copy)] pub enum GlobalLookupKind { @@ -476,9 +477,33 @@ impl<'function> Context<'function> { let handle = match kind { HirExprKind::Access { base, index } => { let base = self.lower_expect(program, base, true, body)?.0; - let index = self.lower_expect(program, index, false, body)?.0; + let (index, index_meta) = self.lower_expect(program, index, false, body)?; - let pointer = self.add_expression(Expression::Access { base, index }, body); + let pointer = program + .solve_constant(self, index, index_meta) + .ok() + .and_then(|constant| { + Some(self.add_expression( + Expression::AccessIndex { + base, + index: match program.module.constants[constant].inner { + crate::ConstantInner::Scalar { + value: ScalarValue::Uint(i), + .. + } => u32::try_from(i).ok()?, + crate::ConstantInner::Scalar { + value: ScalarValue::Sint(i), + .. + } => u32::try_from(i).ok()?, + _ => return None, + }, + }, + body, + )) + }) + .unwrap_or_else(|| { + self.add_expression(Expression::Access { base, index }, body) + }); if let TypeInner::Pointer { .. } = *program.resolve_type(self, pointer, meta)? { if !lhs { From a07310536f5a24d146afcae5bff69ed0a0ebc55d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 17 Jun 2021 20:30:47 +0100 Subject: [PATCH 0981/2212] [glsl-in] Build wgsl shaders for glsl test shaders --- tests/out/210-bevy-2d-shader-frag.wgsl | 13 +- tests/out/210-bevy-2d-shader-vert.wgsl | 30 +- tests/out/210-bevy-shader-vert.wgsl | 59 ++ tests/out/246-collatz-comp.wgsl | 63 ++ tests/out/277-casting-vert.wgsl | 10 + tests/out/280-matrix-cast-vert.wgsl | 13 + tests/out/484-preprocessor-if-vert.wgsl | 9 + tests/out/800-out-of-bounds-panic-vert.wgsl | 24 +- tests/out/896-push-constant-vert.wgsl | 16 + tests/out/901-lhs-field-select-vert.wgsl | 12 + tests/out/932-for-loop-if-vert.wgsl | 23 + tests/out/bevy-pbr-frag.wgsl | 854 ++++++++++++++++++++ tests/out/bevy-pbr-vert.wgsl | 69 ++ tests/out/constant-array-size-vert.wgsl | 35 + tests/out/swizzle_write-frag.wgsl | 20 + tests/snapshots.rs | 5 +- 16 files changed, 1227 insertions(+), 28 deletions(-) create mode 100644 tests/out/210-bevy-shader-vert.wgsl create mode 100644 tests/out/246-collatz-comp.wgsl create mode 100644 tests/out/277-casting-vert.wgsl create mode 100644 tests/out/280-matrix-cast-vert.wgsl create mode 100644 tests/out/484-preprocessor-if-vert.wgsl create mode 100644 tests/out/896-push-constant-vert.wgsl create mode 100644 tests/out/901-lhs-field-select-vert.wgsl create mode 100644 tests/out/932-for-loop-if-vert.wgsl create mode 100644 tests/out/bevy-pbr-frag.wgsl create mode 100644 tests/out/bevy-pbr-vert.wgsl create mode 100644 tests/out/constant-array-size-vert.wgsl create mode 100644 tests/out/swizzle_write-frag.wgsl diff --git a/tests/out/210-bevy-2d-shader-frag.wgsl b/tests/out/210-bevy-2d-shader-frag.wgsl index 2185714c4..078da3536 100644 --- a/tests/out/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/210-bevy-2d-shader-frag.wgsl @@ -7,21 +7,24 @@ struct FragmentOutput { [[location(0), interpolate(perspective)]] member: vec4; }; -var v_Uv: vec2; -var o_Target: vec4; +var gen_entry_v_Uv: vec2; +var gen_entry_o_Target: vec4; [[group(1), binding(0)]] var global: ColorMaterial_color; fn main() { var color: vec4; - color = global.Color; - o_Target = color; + let _e4: vec4 = global.Color; + color = _e4; + let _e6: vec4 = color; + gen_entry_o_Target = _e6; return; } [[stage(fragment)]] fn main1() -> FragmentOutput { main(); - return FragmentOutput(o_Target); + let _e1: vec4 = gen_entry_o_Target; + return FragmentOutput(_e1); } diff --git a/tests/out/210-bevy-2d-shader-vert.wgsl b/tests/out/210-bevy-2d-shader-vert.wgsl index ce2e4cf1c..07be5beea 100644 --- a/tests/out/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/210-bevy-2d-shader-vert.wgsl @@ -18,10 +18,10 @@ struct VertexOutput { [[builtin(position)]] member1: vec4; }; -var Vertex_Position: vec3; -var Vertex_Normal: vec3; -var Vertex_Uv: vec2; -var v_Uv: vec2; +var gen_entry_Vertex_Position: vec3; +var gen_entry_Vertex_Normal: vec3; +var gen_entry_Vertex_Uv: vec2; +var gen_entry_v_Uv: vec2; [[group(0), binding(0)]] var global: Camera; [[group(2), binding(0)]] @@ -33,16 +33,24 @@ var gl_Position: vec4; fn main() { var position: vec3; - v_Uv = Vertex_Uv; - position = (Vertex_Position * vec3(global2.size, 1.0)); - gl_Position = ((global.ViewProj * global1.Model) * vec4(position, 1.0)); + let _e10: vec2 = gen_entry_Vertex_Uv; + gen_entry_v_Uv = _e10; + let _e11: vec3 = gen_entry_Vertex_Position; + let _e12: vec2 = global2.size; + position = (_e11 * vec3(_e12, 1.0)); + let _e18: mat4x4 = global.ViewProj; + let _e19: mat4x4 = global1.Model; + let _e21: vec3 = position; + gl_Position = ((_e18 * _e19) * vec4(_e21, 1.0)); return; } [[stage(vertex)]] -fn main1([[location(0), interpolate(perspective)]] param: vec3, [[location(2), interpolate(perspective)]] param1: vec2) -> VertexOutput { - Vertex_Position = param; - Vertex_Uv = param1; +fn main1([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2) -> VertexOutput { + gen_entry_Vertex_Position = Vertex_Position; + gen_entry_Vertex_Uv = Vertex_Uv; main(); - return VertexOutput(v_Uv, gl_Position); + let _e5: vec2 = gen_entry_v_Uv; + let _e7: vec4 = gl_Position; + return VertexOutput(_e5, _e7); } diff --git a/tests/out/210-bevy-shader-vert.wgsl b/tests/out/210-bevy-shader-vert.wgsl new file mode 100644 index 000000000..8e82a0cf4 --- /dev/null +++ b/tests/out/210-bevy-shader-vert.wgsl @@ -0,0 +1,59 @@ +[[block]] +struct Camera { + ViewProj: mat4x4; +}; + +[[block]] +struct Transform { + Model: mat4x4; +}; + +struct VertexOutput { + [[location(0), interpolate(perspective)]] member: vec3; + [[location(1), interpolate(perspective)]] member1: vec3; + [[location(2), interpolate(perspective)]] member2: vec2; + [[builtin(position)]] member3: vec4; +}; + +var gen_entry_Vertex_Position: vec3; +var gen_entry_Vertex_Normal: vec3; +var gen_entry_Vertex_Uv: vec2; +var gen_entry_v_Position: vec3; +var gen_entry_v_Normal: vec3; +var gen_entry_v_Uv: vec2; +[[group(0), binding(0)]] +var global: Camera; +[[group(2), binding(0)]] +var global1: Transform; +var gl_Position: vec4; + +fn main() { + let _e10: mat4x4 = global1.Model; + let _e11: vec3 = gen_entry_Vertex_Normal; + gen_entry_v_Normal = (_e10 * vec4(_e11, 1.0)).xyz; + let _e16: mat4x4 = global1.Model; + let _e24: vec3 = gen_entry_Vertex_Normal; + gen_entry_v_Normal = (mat3x3(_e16[0].xyz, _e16[1].xyz, _e16[2].xyz) * _e24); + let _e26: mat4x4 = global1.Model; + let _e27: vec3 = gen_entry_Vertex_Position; + gen_entry_v_Position = (_e26 * vec4(_e27, 1.0)).xyz; + let _e32: vec2 = gen_entry_Vertex_Uv; + gen_entry_v_Uv = _e32; + let _e34: mat4x4 = global.ViewProj; + let _e35: vec3 = gen_entry_v_Position; + gl_Position = (_e34 * vec4(_e35, 1.0)); + return; +} + +[[stage(vertex)]] +fn main1([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(1), interpolate(perspective)]] Vertex_Normal: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2) -> VertexOutput { + gen_entry_Vertex_Position = Vertex_Position; + gen_entry_Vertex_Normal = Vertex_Normal; + gen_entry_Vertex_Uv = Vertex_Uv; + main(); + let _e7: vec3 = gen_entry_v_Position; + let _e9: vec3 = gen_entry_v_Normal; + let _e11: vec2 = gen_entry_v_Uv; + let _e13: vec4 = gl_Position; + return VertexOutput(_e7, _e9, _e11, _e13); +} diff --git a/tests/out/246-collatz-comp.wgsl b/tests/out/246-collatz-comp.wgsl new file mode 100644 index 000000000..fee36a78c --- /dev/null +++ b/tests/out/246-collatz-comp.wgsl @@ -0,0 +1,63 @@ +[[block]] +struct PrimeIndices { + indices: [[stride(4)]] array; +}; + +[[group(0), binding(0)]] +var global: [[access(read_write)]] PrimeIndices; +var gl_GlobalInvocationID: vec3; + +fn collatz_iterations(n: u32) -> u32 { + var n1: u32; + var i: u32; + var local: u32; + + n1 = n; + i = u32(0); + loop { + let _e7: u32 = n1; + if (!((_e7 != u32(1)))) { + break; + } + { + let _e12: u32 = n1; + if (((_e12 % u32(2)) == u32(0))) { + { + let _e19: u32 = n1; + n1 = (_e19 / u32(2)); + } + } else { + { + let _e24: u32 = n1; + n1 = ((u32(3) * _e24) + u32(1)); + } + } + let _e30: u32 = i; + local = _e30; + i = (_e30 + 1u); + } + } + let _e35: u32 = i; + return _e35; +} + +fn main() { + var index: u32; + + let _e3: vec3 = gl_GlobalInvocationID; + index = _e3.x; + let _e6: u32 = index; + let _e8: u32 = index; + let _e11: u32 = index; + let _e13: u32 = global.indices[_e11]; + let _e14: u32 = collatz_iterations(_e13); + global.indices[_e6] = _e14; + return; +} + +[[stage(compute), workgroup_size(1, 1, 1)]] +fn main1([[builtin(global_invocation_id)]] param: vec3) { + gl_GlobalInvocationID = param; + main(); + return; +} diff --git a/tests/out/277-casting-vert.wgsl b/tests/out/277-casting-vert.wgsl new file mode 100644 index 000000000..605c86529 --- /dev/null +++ b/tests/out/277-casting-vert.wgsl @@ -0,0 +1,10 @@ +fn main() { + var a: f32 = 1.0; + +} + +[[stage(vertex)]] +fn main1() { + main(); + return; +} diff --git a/tests/out/280-matrix-cast-vert.wgsl b/tests/out/280-matrix-cast-vert.wgsl new file mode 100644 index 000000000..915109d08 --- /dev/null +++ b/tests/out/280-matrix-cast-vert.wgsl @@ -0,0 +1,13 @@ +fn main() { + var a: mat4x4; + + let _e2: vec4 = vec4(f32(1)); + a = mat4x4(_e2, _e2, _e2, _e2); + return; +} + +[[stage(vertex)]] +fn main1() { + main(); + return; +} diff --git a/tests/out/484-preprocessor-if-vert.wgsl b/tests/out/484-preprocessor-if-vert.wgsl new file mode 100644 index 000000000..0c58b561b --- /dev/null +++ b/tests/out/484-preprocessor-if-vert.wgsl @@ -0,0 +1,9 @@ +fn main() { + return; +} + +[[stage(vertex)]] +fn main1() { + main(); + return; +} diff --git a/tests/out/800-out-of-bounds-panic-vert.wgsl b/tests/out/800-out-of-bounds-panic-vert.wgsl index 175862c52..c3b90b08b 100644 --- a/tests/out/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/800-out-of-bounds-panic-vert.wgsl @@ -16,21 +16,27 @@ struct VertexOutput { [[group(0), binding(0)]] var global: Globals; var global1: VertexPushConstants; -var position: vec2; -var color: vec4; -var frag_color: vec4; +var gen_entry_position: vec2; +var gen_entry_color: vec4; +var gen_entry_frag_color: vec4; var gl_Position: vec4; fn main() { - frag_color = color; - gl_Position = ((global.view_matrix * global1.world_matrix) * vec4(position, 0.0, 1.0)); + let _e7: vec4 = gen_entry_color; + gen_entry_frag_color = _e7; + let _e9: mat4x4 = global.view_matrix; + let _e10: mat4x4 = global1.world_matrix; + let _e12: vec2 = gen_entry_position; + gl_Position = ((_e9 * _e10) * vec4(_e12, 0.0, 1.0)); return; } [[stage(vertex)]] -fn main1([[location(0), interpolate(perspective)]] param: vec2, [[location(1), interpolate(perspective)]] param1: vec4) -> VertexOutput { - position = param; - color = param1; +fn main1([[location(0), interpolate(perspective)]] position: vec2, [[location(1), interpolate(perspective)]] color: vec4) -> VertexOutput { + gen_entry_position = position; + gen_entry_color = color; main(); - return VertexOutput(frag_color, gl_Position); + let _e5: vec4 = gen_entry_frag_color; + let _e7: vec4 = gl_Position; + return VertexOutput(_e5, _e7); } diff --git a/tests/out/896-push-constant-vert.wgsl b/tests/out/896-push-constant-vert.wgsl new file mode 100644 index 000000000..40c33ac0c --- /dev/null +++ b/tests/out/896-push-constant-vert.wgsl @@ -0,0 +1,16 @@ +[[block]] +struct PushConstants { + example: f32; +}; + +var c: PushConstants; + +fn main() { + return; +} + +[[stage(vertex)]] +fn main1() { + main(); + return; +} diff --git a/tests/out/901-lhs-field-select-vert.wgsl b/tests/out/901-lhs-field-select-vert.wgsl new file mode 100644 index 000000000..2c1b07895 --- /dev/null +++ b/tests/out/901-lhs-field-select-vert.wgsl @@ -0,0 +1,12 @@ +fn main() { + var a: vec4 = vec4(1.0, 1.0, 1.0, 1.0); + + a.x = 2.0; + return; +} + +[[stage(vertex)]] +fn main1() { + main(); + return; +} diff --git a/tests/out/932-for-loop-if-vert.wgsl b/tests/out/932-for-loop-if-vert.wgsl new file mode 100644 index 000000000..0bf744473 --- /dev/null +++ b/tests/out/932-for-loop-if-vert.wgsl @@ -0,0 +1,23 @@ +fn main() { + var i: i32 = 0; + + loop { + let _e2: i32 = i; + if (!((_e2 < 1))) { + break; + } + { + } + continuing { + let _e6: i32 = i; + i = (_e6 + 1); + } + } + return; +} + +[[stage(vertex)]] +fn main1() { + main(); + return; +} diff --git a/tests/out/bevy-pbr-frag.wgsl b/tests/out/bevy-pbr-frag.wgsl new file mode 100644 index 000000000..612de68a3 --- /dev/null +++ b/tests/out/bevy-pbr-frag.wgsl @@ -0,0 +1,854 @@ +struct PointLight { + pos: vec4; + color: vec4; + lightParams: vec4; +}; + +struct DirectionalLight { + direction: vec4; + color1: vec4; +}; + +[[block]] +struct CameraViewProj { + ViewProj: mat4x4; +}; + +[[block]] +struct CameraPosition { + CameraPos: vec4; +}; + +[[block]] +struct Lights { + AmbientColor: vec4; + NumLights: vec4; + PointLights: [[stride(48)]] array; + DirectionalLights: [[stride(32)]] array; +}; + +[[block]] +struct StandardMaterial_base_color { + base_color: vec4; +}; + +[[block]] +struct StandardMaterial_roughness { + perceptual_roughness: f32; +}; + +[[block]] +struct StandardMaterial_metallic { + metallic: f32; +}; + +[[block]] +struct StandardMaterial_reflectance { + reflectance: f32; +}; + +[[block]] +struct StandardMaterial_emissive { + emissive: vec4; +}; + +struct FragmentOutput { + [[location(0), interpolate(perspective)]] member: vec4; +}; + +var gen_entry_v_WorldPosition: vec3; +var gen_entry_v_WorldNormal: vec3; +var gen_entry_v_Uv: vec2; +var gen_entry_v_WorldTangent: vec4; +var gen_entry_o_Target: vec4; +[[group(0), binding(0)]] +var global: CameraViewProj; +[[group(0), binding(1)]] +var global1: CameraPosition; +[[group(1), binding(0)]] +var global2: Lights; +[[group(3), binding(0)]] +var global3: StandardMaterial_base_color; +[[group(3), binding(1)]] +var StandardMaterial_base_color_texture: texture_2d; +[[group(3), binding(2)]] +var StandardMaterial_base_color_texture_sampler: sampler; +[[group(3), binding(3)]] +var global4: StandardMaterial_roughness; +[[group(3), binding(4)]] +var global5: StandardMaterial_metallic; +[[group(3), binding(5)]] +var StandardMaterial_metallic_roughness_texture: texture_2d; +[[group(3), binding(6)]] +var StandardMaterial_metallic_roughness_texture_sampler: sampler; +[[group(3), binding(7)]] +var global6: StandardMaterial_reflectance; +[[group(3), binding(8)]] +var StandardMaterial_normal_map: texture_2d; +[[group(3), binding(9)]] +var StandardMaterial_normal_map_sampler: sampler; +[[group(3), binding(10)]] +var StandardMaterial_occlusion_texture: texture_2d; +[[group(3), binding(11)]] +var StandardMaterial_occlusion_texture_sampler: sampler; +[[group(3), binding(12)]] +var global7: StandardMaterial_emissive; +[[group(3), binding(13)]] +var StandardMaterial_emissive_texture: texture_2d; +[[group(3), binding(14)]] +var StandardMaterial_emissive_texture_sampler: sampler; +var gl_FrontFacing: bool; + +fn pow5_(x: f32) -> f32 { + var x1: f32; + var x2_: f32; + + x1 = x; + let _e42: f32 = x1; + let _e43: f32 = x1; + x2_ = (_e42 * _e43); + let _e46: f32 = x2_; + let _e47: f32 = x2_; + let _e49: f32 = x1; + return ((_e46 * _e47) * _e49); +} + +fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 { + var distanceSquare1: f32; + var inverseRangeSquared1: f32; + var factor: f32; + var smoothFactor: f32; + var attenuation: f32; + + distanceSquare1 = distanceSquare; + inverseRangeSquared1 = inverseRangeSquared; + let _e44: f32 = distanceSquare1; + let _e45: f32 = inverseRangeSquared1; + factor = (_e44 * _e45); + let _e49: f32 = factor; + let _e50: f32 = factor; + smoothFactor = clamp((1.0 - (_e49 * _e50)), 0.0, 1.0); + let _e57: f32 = smoothFactor; + let _e58: f32 = smoothFactor; + attenuation = (_e57 * _e58); + let _e61: f32 = attenuation; + let _e64: f32 = distanceSquare1; + return ((_e61 * 1.0) / max(_e64, 0.00009999999747378752)); +} + +fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { + var roughness1: f32; + var NoH1: f32; + var oneMinusNoHSquared: f32; + var a: f32; + var k: f32; + var d: f32; + + roughness1 = roughness; + NoH1 = NoH; + let _e46: f32 = NoH1; + let _e47: f32 = NoH1; + oneMinusNoHSquared = (1.0 - (_e46 * _e47)); + let _e51: f32 = NoH1; + let _e52: f32 = roughness1; + a = (_e51 * _e52); + let _e55: f32 = roughness1; + let _e56: f32 = oneMinusNoHSquared; + let _e57: f32 = a; + let _e58: f32 = a; + k = (_e55 / (_e56 + (_e57 * _e58))); + let _e63: f32 = k; + let _e64: f32 = k; + d = ((_e63 * _e64) * (1.0 / 3.1415927410125732)); + let _e70: f32 = d; + return _e70; +} + +fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 { + var roughness3: f32; + var NoV1: f32; + var NoL1: f32; + var a2_: f32; + var lambdaV: f32; + var lambdaL: f32; + var v: f32; + + roughness3 = roughness2; + NoV1 = NoV; + NoL1 = NoL; + let _e46: f32 = roughness3; + let _e47: f32 = roughness3; + a2_ = (_e46 * _e47); + let _e50: f32 = NoL1; + let _e51: f32 = NoV1; + let _e52: f32 = a2_; + let _e53: f32 = NoV1; + let _e56: f32 = NoV1; + let _e58: f32 = a2_; + lambdaV = (_e50 * sqrt((((_e51 - (_e52 * _e53)) * _e56) + _e58))); + let _e63: f32 = NoV1; + let _e64: f32 = NoL1; + let _e65: f32 = a2_; + let _e66: f32 = NoL1; + let _e69: f32 = NoL1; + let _e71: f32 = a2_; + lambdaL = (_e63 * sqrt((((_e64 - (_e65 * _e66)) * _e69) + _e71))); + let _e77: f32 = lambdaV; + let _e78: f32 = lambdaL; + v = (0.5 / (_e77 + _e78)); + let _e82: f32 = v; + return _e82; +} + +fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { + var f90_1: f32; + var VoH1: f32; + + f90_1 = f90_; + VoH1 = VoH; + let _e45: f32 = f90_1; + let _e49: f32 = VoH1; + let _e52: f32 = VoH1; + let _e54: f32 = pow5_((1.0 - _e52)); + return (f0_ + ((vec3(_e45) - f0_) * _e54)); +} + +fn F_Schlick1(f0_1: f32, f90_2: f32, VoH2: f32) -> f32 { + var f0_2: f32; + var f90_3: f32; + var VoH3: f32; + + f0_2 = f0_1; + f90_3 = f90_2; + VoH3 = VoH2; + let _e46: f32 = f0_2; + let _e47: f32 = f90_3; + let _e48: f32 = f0_2; + let _e51: f32 = VoH3; + let _e54: f32 = VoH3; + let _e56: f32 = pow5_((1.0 - _e54)); + return (_e46 + ((_e47 - _e48) * _e56)); +} + +fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { + var f0_4: vec3; + var LoH1: f32; + var f90_4: f32; + + f0_4 = f0_3; + LoH1 = LoH; + let _e44: vec3 = f0_4; + f90_4 = clamp(dot(_e44, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); + let _e57: vec3 = f0_4; + let _e58: f32 = f90_4; + let _e59: f32 = LoH1; + let _e60: vec3 = F_Schlick(_e57, _e58, _e59); + return _e60; +} + +fn specular(f0_5: vec3, roughness4: f32, h1: vec3, NoV2: f32, NoL2: f32, NoH2: f32, LoH2: f32, specularIntensity: f32) -> vec3 { + var f0_6: vec3; + var roughness5: f32; + var NoV3: f32; + var NoL3: f32; + var NoH3: f32; + var LoH3: f32; + var specularIntensity1: f32; + var D: f32; + var V: f32; + var F: vec3; + + f0_6 = f0_5; + roughness5 = roughness4; + NoV3 = NoV2; + NoL3 = NoL2; + NoH3 = NoH2; + LoH3 = LoH2; + specularIntensity1 = specularIntensity; + let _e57: f32 = roughness5; + let _e58: f32 = NoH3; + let _e59: f32 = D_GGX(_e57, _e58, h1); + D = _e59; + let _e64: f32 = roughness5; + let _e65: f32 = NoV3; + let _e66: f32 = NoL3; + let _e67: f32 = V_SmithGGXCorrelated(_e64, _e65, _e66); + V = _e67; + let _e71: vec3 = f0_6; + let _e72: f32 = LoH3; + let _e73: vec3 = fresnel(_e71, _e72); + F = _e73; + let _e75: f32 = specularIntensity1; + let _e76: f32 = D; + let _e78: f32 = V; + let _e80: vec3 = F; + return (((_e75 * _e76) * _e78) * _e80); +} + +fn Fd_Burley(roughness6: f32, NoV4: f32, NoL4: f32, LoH4: f32) -> f32 { + var roughness7: f32; + var NoV5: f32; + var NoL5: f32; + var LoH5: f32; + var f90_5: f32; + var lightScatter: f32; + var viewScatter: f32; + + roughness7 = roughness6; + NoV5 = NoV4; + NoL5 = NoL4; + LoH5 = LoH4; + let _e50: f32 = roughness7; + let _e52: f32 = LoH5; + let _e54: f32 = LoH5; + f90_5 = (0.5 + (((2.0 * _e50) * _e52) * _e54)); + let _e62: f32 = f90_5; + let _e63: f32 = NoL5; + let _e64: f32 = F_Schlick1(1.0, _e62, _e63); + lightScatter = _e64; + let _e70: f32 = f90_5; + let _e71: f32 = NoV5; + let _e72: f32 = F_Schlick1(1.0, _e70, _e71); + viewScatter = _e72; + let _e74: f32 = lightScatter; + let _e75: f32 = viewScatter; + return ((_e74 * _e75) * (1.0 / 3.1415927410125732)); +} + +fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness1: f32, NoV6: f32) -> vec3 { + var f0_8: vec3; + var perceptual_roughness2: f32; + var NoV7: f32; + var c0_: vec4 = vec4(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071); + var c1_: vec4 = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033); + var r: vec4; + var a004_: f32; + var AB: vec2; + + f0_8 = f0_7; + perceptual_roughness2 = perceptual_roughness1; + NoV7 = NoV6; + let _e62: f32 = perceptual_roughness2; + let _e64: vec4 = c0_; + let _e66: vec4 = c1_; + r = ((vec4(_e62) * _e64) + _e66); + let _e69: vec4 = r; + let _e71: vec4 = r; + let _e76: f32 = NoV7; + let _e80: vec4 = r; + let _e83: vec4 = r; + a004_ = ((min((_e69.x * _e71.x), exp2((-(9.279999732971191) * _e76))) * _e80.x) + _e83.y); + let _e91: f32 = a004_; + let _e94: vec4 = r; + AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(_e91)) + _e94.zw); + let _e98: vec3 = f0_8; + let _e99: vec2 = AB; + let _e103: vec2 = AB; + return ((_e98 * vec3(_e99.x)) + vec3(_e103.y)); +} + +fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { + var perceptualRoughness1: f32; + var clampedPerceptualRoughness: f32; + + perceptualRoughness1 = perceptualRoughness; + let _e42: f32 = perceptualRoughness1; + clampedPerceptualRoughness = clamp(_e42, 0.08900000154972076, 1.0); + let _e47: f32 = clampedPerceptualRoughness; + let _e48: f32 = clampedPerceptualRoughness; + return (_e47 * _e48); +} + +fn reinhard(color2: vec3) -> vec3 { + var color3: vec3; + + color3 = color2; + let _e42: vec3 = color3; + let _e45: vec3 = color3; + return (_e42 / (vec3(1.0) + _e45)); +} + +fn reinhard_extended(color4: vec3, max_white: f32) -> vec3 { + var color5: vec3; + var max_white1: f32; + var numerator: vec3; + + color5 = color4; + max_white1 = max_white; + let _e44: vec3 = color5; + let _e47: vec3 = color5; + let _e48: f32 = max_white1; + let _e49: f32 = max_white1; + numerator = (_e44 * (vec3(1.0) + (_e47 / vec3((_e48 * _e49))))); + let _e56: vec3 = numerator; + let _e59: vec3 = color5; + return (_e56 / (vec3(1.0) + _e59)); +} + +fn luminance(v1: vec3) -> f32 { + var v2: vec3; + + v2 = v1; + let _e42: vec3 = v2; + return dot(_e42, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); +} + +fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { + var c_in1: vec3; + var l_out1: f32; + var l_in: f32; + + c_in1 = c_in; + l_out1 = l_out; + let _e45: vec3 = c_in1; + let _e46: f32 = luminance(_e45); + l_in = _e46; + let _e48: vec3 = c_in1; + let _e49: f32 = l_out1; + let _e50: f32 = l_in; + return (_e48 * (_e49 / _e50)); +} + +fn reinhard_luminance(color6: vec3) -> vec3 { + var color7: vec3; + var l_old: f32; + var l_new: f32; + + color7 = color6; + let _e43: vec3 = color7; + let _e44: f32 = luminance(_e43); + l_old = _e44; + let _e46: f32 = l_old; + let _e48: f32 = l_old; + l_new = (_e46 / (1.0 + _e48)); + let _e54: vec3 = color7; + let _e55: f32 = l_new; + let _e56: vec3 = change_luminance(_e54, _e55); + return _e56; +} + +fn reinhard_extended_luminance(color8: vec3, max_white_l: f32) -> vec3 { + var color9: vec3; + var max_white_l1: f32; + var l_old1: f32; + var numerator1: f32; + var l_new1: f32; + + color9 = color8; + max_white_l1 = max_white_l; + let _e45: vec3 = color9; + let _e46: f32 = luminance(_e45); + l_old1 = _e46; + let _e48: f32 = l_old1; + let _e50: f32 = l_old1; + let _e51: f32 = max_white_l1; + let _e52: f32 = max_white_l1; + numerator1 = (_e48 * (1.0 + (_e50 / (_e51 * _e52)))); + let _e58: f32 = numerator1; + let _e60: f32 = l_old1; + l_new1 = (_e58 / (1.0 + _e60)); + let _e66: vec3 = color9; + let _e67: f32 = l_new1; + let _e68: vec3 = change_luminance(_e66, _e67); + return _e68; +} + +fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: vec3, R: vec3, F0_: vec3, diffuseColor: vec3) -> vec3 { + var light1: PointLight; + var roughness9: f32; + var NdotV1: f32; + var N1: vec3; + var V2: vec3; + var R1: vec3; + var F0_1: vec3; + var diffuseColor1: vec3; + var light_to_frag: vec3; + var distance_square: f32; + var rangeAttenuation: f32; + var a1: f32; + var radius: f32; + var centerToRay: vec3; + var closestPoint: vec3; + var LspecLengthInverse: f32; + var normalizationFactor: f32; + var specularIntensity2: f32; + var L: vec3; + var H: vec3; + var NoL6: f32; + var NoH4: f32; + var LoH6: f32; + var specular1: vec3; + var diffuse: vec3; + + light1 = light; + roughness9 = roughness8; + NdotV1 = NdotV; + N1 = N; + V2 = V1; + R1 = R; + F0_1 = F0_; + diffuseColor1 = diffuseColor; + let _e56: PointLight = light1; + let _e59: vec3 = gen_entry_v_WorldPosition; + light_to_frag = (_e56.pos.xyz - _e59.xyz); + let _e63: vec3 = light_to_frag; + let _e64: vec3 = light_to_frag; + distance_square = dot(_e63, _e64); + let _e68: PointLight = light1; + let _e71: f32 = distance_square; + let _e72: PointLight = light1; + let _e75: f32 = getDistanceAttenuation(_e71, _e72.lightParams.x); + rangeAttenuation = _e75; + let _e77: f32 = roughness9; + a1 = _e77; + let _e79: PointLight = light1; + radius = _e79.lightParams.y; + let _e83: vec3 = light_to_frag; + let _e84: vec3 = R1; + let _e86: vec3 = R1; + let _e88: vec3 = light_to_frag; + centerToRay = ((dot(_e83, _e84) * _e86) - _e88); + let _e91: vec3 = light_to_frag; + let _e92: vec3 = centerToRay; + let _e93: f32 = radius; + let _e94: vec3 = centerToRay; + let _e95: vec3 = centerToRay; + closestPoint = (_e91 + (_e92 * clamp((_e93 * inverseSqrt(dot(_e94, _e95))), 0.0, 1.0))); + let _e105: vec3 = closestPoint; + let _e106: vec3 = closestPoint; + LspecLengthInverse = inverseSqrt(dot(_e105, _e106)); + let _e110: f32 = a1; + let _e111: f32 = a1; + let _e112: f32 = radius; + let _e115: f32 = LspecLengthInverse; + normalizationFactor = (_e110 / clamp((_e111 + ((_e112 * 0.5) * _e115)), 0.0, 1.0)); + let _e123: f32 = normalizationFactor; + let _e124: f32 = normalizationFactor; + specularIntensity2 = (_e123 * _e124); + let _e127: vec3 = closestPoint; + let _e128: f32 = LspecLengthInverse; + L = (_e127 * _e128); + let _e131: vec3 = L; + let _e132: vec3 = V2; + H = normalize((_e131 + _e132)); + let _e136: vec3 = N1; + let _e137: vec3 = L; + NoL6 = clamp(dot(_e136, _e137), 0.0, 1.0); + let _e143: vec3 = N1; + let _e144: vec3 = H; + NoH4 = clamp(dot(_e143, _e144), 0.0, 1.0); + let _e150: vec3 = L; + let _e151: vec3 = H; + LoH6 = clamp(dot(_e150, _e151), 0.0, 1.0); + let _e165: vec3 = F0_1; + let _e166: f32 = roughness9; + let _e167: vec3 = H; + let _e168: f32 = NdotV1; + let _e169: f32 = NoL6; + let _e170: f32 = NoH4; + let _e171: f32 = LoH6; + let _e172: f32 = specularIntensity2; + let _e173: vec3 = specular(_e165, _e166, _e167, _e168, _e169, _e170, _e171, _e172); + specular1 = _e173; + let _e175: vec3 = light_to_frag; + L = normalize(_e175); + let _e177: vec3 = L; + let _e178: vec3 = V2; + H = normalize((_e177 + _e178)); + let _e181: vec3 = N1; + let _e182: vec3 = L; + NoL6 = clamp(dot(_e181, _e182), 0.0, 1.0); + let _e187: vec3 = N1; + let _e188: vec3 = H; + NoH4 = clamp(dot(_e187, _e188), 0.0, 1.0); + let _e193: vec3 = L; + let _e194: vec3 = H; + LoH6 = clamp(dot(_e193, _e194), 0.0, 1.0); + let _e199: vec3 = diffuseColor1; + let _e204: f32 = roughness9; + let _e205: f32 = NdotV1; + let _e206: f32 = NoL6; + let _e207: f32 = LoH6; + let _e208: f32 = Fd_Burley(_e204, _e205, _e206, _e207); + diffuse = (_e199 * _e208); + let _e211: vec3 = diffuse; + let _e212: vec3 = specular1; + let _e214: PointLight = light1; + let _e218: f32 = rangeAttenuation; + let _e219: f32 = NoL6; + return (((_e211 + _e212) * _e214.color.xyz) * (_e218 * _e219)); +} + +fn dir_light(light2: DirectionalLight, roughness10: f32, NdotV2: f32, normal: vec3, view: vec3, R2: vec3, F0_2: vec3, diffuseColor2: vec3) -> vec3 { + var light3: DirectionalLight; + var roughness11: f32; + var NdotV3: f32; + var normal1: vec3; + var view1: vec3; + var R3: vec3; + var F0_3: vec3; + var diffuseColor3: vec3; + var incident_light: vec3; + var half_vector: vec3; + var NoL7: f32; + var NoH5: f32; + var LoH7: f32; + var diffuse1: vec3; + var specularIntensity3: f32 = 1.0; + var specular2: vec3; + + light3 = light2; + roughness11 = roughness10; + NdotV3 = NdotV2; + normal1 = normal; + view1 = view; + R3 = R2; + F0_3 = F0_2; + diffuseColor3 = diffuseColor2; + let _e56: DirectionalLight = light3; + incident_light = _e56.direction.xyz; + let _e60: vec3 = incident_light; + let _e61: vec3 = view1; + half_vector = normalize((_e60 + _e61)); + let _e65: vec3 = normal1; + let _e66: vec3 = incident_light; + NoL7 = clamp(dot(_e65, _e66), 0.0, 1.0); + let _e72: vec3 = normal1; + let _e73: vec3 = half_vector; + NoH5 = clamp(dot(_e72, _e73), 0.0, 1.0); + let _e79: vec3 = incident_light; + let _e80: vec3 = half_vector; + LoH7 = clamp(dot(_e79, _e80), 0.0, 1.0); + let _e86: vec3 = diffuseColor3; + let _e91: f32 = roughness11; + let _e92: f32 = NdotV3; + let _e93: f32 = NoL7; + let _e94: f32 = LoH7; + let _e95: f32 = Fd_Burley(_e91, _e92, _e93, _e94); + diffuse1 = (_e86 * _e95); + let _e108: vec3 = F0_3; + let _e109: f32 = roughness11; + let _e110: vec3 = half_vector; + let _e111: f32 = NdotV3; + let _e112: f32 = NoL7; + let _e113: f32 = NoH5; + let _e114: f32 = LoH7; + let _e115: f32 = specularIntensity3; + let _e116: vec3 = specular(_e108, _e109, _e110, _e111, _e112, _e113, _e114, _e115); + specular2 = _e116; + let _e118: vec3 = specular2; + let _e119: vec3 = diffuse1; + let _e121: DirectionalLight = light3; + let _e125: f32 = NoL7; + return (((_e118 + _e119) * _e121.color1.xyz) * _e125); +} + +fn main() { + var output_color: vec4; + var metallic_roughness: vec4; + var metallic1: f32; + var perceptual_roughness3: f32; + var roughness12: f32; + var N2: vec3; + var T: vec3; + var B: vec3; + var TBN: mat3x3; + var occlusion: f32; + var emissive1: vec4; + var V3: vec3; + var NdotV4: f32; + var F0_4: vec3; + var diffuseColor4: vec3; + var R4: vec3; + var light_accum: vec3 = vec3(0.0, 0.0, 0.0); + var i: i32 = 0; + var i1: i32 = 0; + var diffuse_ambient: vec3; + var specular_ambient: vec3; + + let _e40: vec4 = global3.base_color; + output_color = _e40; + let _e42: vec4 = output_color; + let _e43: vec2 = gen_entry_v_Uv; + let _e44: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e43); + output_color = (_e42 * _e44); + let _e46: vec2 = gen_entry_v_Uv; + let _e47: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e46); + metallic_roughness = _e47; + let _e49: f32 = global5.metallic; + let _e50: vec4 = metallic_roughness; + metallic1 = (_e49 * _e50.z); + let _e54: f32 = global4.perceptual_roughness; + let _e55: vec4 = metallic_roughness; + perceptual_roughness3 = (_e54 * _e55.y); + let _e60: f32 = perceptual_roughness3; + let _e61: f32 = perceptualRoughnessToRoughness(_e60); + roughness12 = _e61; + let _e63: vec3 = gen_entry_v_WorldNormal; + N2 = normalize(_e63); + let _e66: vec4 = gen_entry_v_WorldTangent; + T = normalize(_e66.xyz); + let _e70: vec3 = N2; + let _e71: vec3 = T; + let _e73: vec4 = gen_entry_v_WorldTangent; + B = (cross(_e70, _e71) * _e73.w); + let _e78: bool = gl_FrontFacing; + let _e79: vec3 = N2; + let _e80: vec3 = N2; + N2 = select(_e79, -(_e80), _e78); + let _e83: bool = gl_FrontFacing; + let _e84: vec3 = T; + let _e85: vec3 = T; + T = select(_e84, -(_e85), _e83); + let _e88: bool = gl_FrontFacing; + let _e89: vec3 = B; + let _e90: vec3 = B; + B = select(_e89, -(_e90), _e88); + let _e93: vec3 = T; + let _e94: vec3 = B; + let _e95: vec3 = N2; + TBN = mat3x3(_e93, _e94, _e95); + let _e98: mat3x3 = TBN; + let _e99: vec2 = gen_entry_v_Uv; + let _e100: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e99); + N2 = (_e98 * normalize(((_e100.xyz * 2.0) - vec3(1.0)))); + let _e109: vec2 = gen_entry_v_Uv; + let _e110: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e109); + occlusion = _e110.x; + let _e113: vec4 = global7.emissive; + emissive1 = _e113; + let _e115: vec4 = emissive1; + let _e117: vec4 = emissive1; + let _e119: vec2 = gen_entry_v_Uv; + let _e120: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e119); + let _e122: vec3 = (_e117.xyz * _e120.xyz); + emissive1.x = _e122.x; + emissive1.y = _e122.y; + emissive1.z = _e122.z; + let _e129: vec4 = global1.CameraPos; + let _e131: vec3 = gen_entry_v_WorldPosition; + V3 = normalize((_e129.xyz - _e131.xyz)); + let _e136: vec3 = N2; + let _e137: vec3 = V3; + NdotV4 = max(dot(_e136, _e137), 0.00009999999747378752); + let _e143: f32 = global6.reflectance; + let _e145: f32 = global6.reflectance; + let _e148: f32 = metallic1; + let _e152: vec4 = output_color; + let _e154: f32 = metallic1; + F0_4 = (vec3((((0.1599999964237213 * _e143) * _e145) * (1.0 - _e148))) + (_e152.xyz * vec3(_e154))); + let _e159: vec4 = output_color; + let _e162: f32 = metallic1; + diffuseColor4 = (_e159.xyz * vec3((1.0 - _e162))); + let _e167: vec3 = V3; + let _e169: vec3 = N2; + R4 = reflect(-(_e167), _e169); + loop { + let _e177: i32 = i; + let _e178: vec4 = global2.NumLights; + let _e182: i32 = i; + if (!(((_e177 < i32(_e178.x)) && (_e182 < 10)))) { + break; + } + { + let _e189: vec3 = light_accum; + let _e190: i32 = i; + let _e200: i32 = i; + let _e202: PointLight = global2.PointLights[_e200]; + let _e203: f32 = roughness12; + let _e204: f32 = NdotV4; + let _e205: vec3 = N2; + let _e206: vec3 = V3; + let _e207: vec3 = R4; + let _e208: vec3 = F0_4; + let _e209: vec3 = diffuseColor4; + let _e210: vec3 = point_light(_e202, _e203, _e204, _e205, _e206, _e207, _e208, _e209); + light_accum = (_e189 + _e210); + } + continuing { + let _e186: i32 = i; + i = (_e186 + 1); + } + } + loop { + let _e214: i32 = i1; + let _e215: vec4 = global2.NumLights; + let _e219: i32 = i1; + if (!(((_e214 < i32(_e215.y)) && (_e219 < 1)))) { + break; + } + { + let _e226: vec3 = light_accum; + let _e227: i32 = i1; + let _e237: i32 = i1; + let _e239: DirectionalLight = global2.DirectionalLights[_e237]; + let _e240: f32 = roughness12; + let _e241: f32 = NdotV4; + let _e242: vec3 = N2; + let _e243: vec3 = V3; + let _e244: vec3 = R4; + let _e245: vec3 = F0_4; + let _e246: vec3 = diffuseColor4; + let _e247: vec3 = dir_light(_e239, _e240, _e241, _e242, _e243, _e244, _e245, _e246); + light_accum = (_e226 + _e247); + } + continuing { + let _e223: i32 = i1; + i1 = (_e223 + 1); + } + } + let _e252: vec3 = diffuseColor4; + let _e254: f32 = NdotV4; + let _e255: vec3 = EnvBRDFApprox(_e252, 1.0, _e254); + diffuse_ambient = _e255; + let _e260: vec3 = F0_4; + let _e261: f32 = perceptual_roughness3; + let _e262: f32 = NdotV4; + let _e263: vec3 = EnvBRDFApprox(_e260, _e261, _e262); + specular_ambient = _e263; + let _e265: vec4 = output_color; + let _e267: vec3 = light_accum; + output_color.x = _e267.x; + output_color.y = _e267.y; + output_color.z = _e267.z; + let _e274: vec4 = output_color; + let _e276: vec4 = output_color; + let _e278: vec3 = diffuse_ambient; + let _e279: vec3 = specular_ambient; + let _e281: vec4 = global2.AmbientColor; + let _e284: f32 = occlusion; + let _e286: vec3 = (_e276.xyz + (((_e278 + _e279) * _e281.xyz) * _e284)); + output_color.x = _e286.x; + output_color.y = _e286.y; + output_color.z = _e286.z; + let _e293: vec4 = output_color; + let _e295: vec4 = output_color; + let _e297: vec4 = emissive1; + let _e299: vec4 = output_color; + let _e302: vec3 = (_e295.xyz + (_e297.xyz * _e299.w)); + output_color.x = _e302.x; + output_color.y = _e302.y; + output_color.z = _e302.z; + let _e309: vec4 = output_color; + let _e311: vec4 = output_color; + let _e313: vec4 = output_color; + let _e315: vec3 = reinhard_luminance(_e313.xyz); + output_color.x = _e315.x; + output_color.y = _e315.y; + output_color.z = _e315.z; + let _e322: vec4 = output_color; + gen_entry_o_Target = _e322; + return; +} + +[[stage(fragment)]] +fn main1([[location(0), interpolate(perspective)]] v_WorldPosition: vec3, [[location(1), interpolate(perspective)]] v_WorldNormal: vec3, [[location(2), interpolate(perspective)]] v_Uv: vec2, [[location(3), interpolate(perspective)]] v_WorldTangent: vec4, [[builtin(front_facing)]] param: bool) -> FragmentOutput { + gen_entry_v_WorldPosition = v_WorldPosition; + gen_entry_v_WorldNormal = v_WorldNormal; + gen_entry_v_Uv = v_Uv; + gen_entry_v_WorldTangent = v_WorldTangent; + gl_FrontFacing = param; + main(); + let _e11: vec4 = gen_entry_o_Target; + return FragmentOutput(_e11); +} diff --git a/tests/out/bevy-pbr-vert.wgsl b/tests/out/bevy-pbr-vert.wgsl new file mode 100644 index 000000000..0d1f1d0fd --- /dev/null +++ b/tests/out/bevy-pbr-vert.wgsl @@ -0,0 +1,69 @@ +[[block]] +struct CameraViewProj { + ViewProj: mat4x4; +}; + +[[block]] +struct Transform { + Model: mat4x4; +}; + +struct VertexOutput { + [[location(0), interpolate(perspective)]] member: vec3; + [[location(1), interpolate(perspective)]] member1: vec3; + [[location(2), interpolate(perspective)]] member2: vec2; + [[location(3), interpolate(perspective)]] member3: vec4; + [[builtin(position)]] member4: vec4; +}; + +var gen_entry_Vertex_Position: vec3; +var gen_entry_Vertex_Normal: vec3; +var gen_entry_Vertex_Uv: vec2; +var gen_entry_Vertex_Tangent: vec4; +var gen_entry_v_WorldPosition: vec3; +var gen_entry_v_WorldNormal: vec3; +var gen_entry_v_Uv: vec2; +[[group(0), binding(0)]] +var global: CameraViewProj; +var gen_entry_v_WorldTangent: vec4; +[[group(2), binding(0)]] +var global1: Transform; +var gl_Position: vec4; + +fn main() { + var world_position: vec4; + + let _e12: mat4x4 = global1.Model; + let _e13: vec3 = gen_entry_Vertex_Position; + world_position = (_e12 * vec4(_e13, 1.0)); + let _e18: vec4 = world_position; + gen_entry_v_WorldPosition = _e18.xyz; + let _e20: mat4x4 = global1.Model; + let _e28: vec3 = gen_entry_Vertex_Normal; + gen_entry_v_WorldNormal = (mat3x3(_e20[0].xyz, _e20[1].xyz, _e20[2].xyz) * _e28); + let _e30: vec2 = gen_entry_Vertex_Uv; + gen_entry_v_Uv = _e30; + let _e31: mat4x4 = global1.Model; + let _e39: vec4 = gen_entry_Vertex_Tangent; + let _e42: vec4 = gen_entry_Vertex_Tangent; + gen_entry_v_WorldTangent = vec4((mat3x3(_e31[0].xyz, _e31[1].xyz, _e31[2].xyz) * _e39.xyz), _e42.w); + let _e46: mat4x4 = global.ViewProj; + let _e47: vec4 = world_position; + gl_Position = (_e46 * _e47); + return; +} + +[[stage(vertex)]] +fn main1([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(1), interpolate(perspective)]] Vertex_Normal: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2, [[location(3), interpolate(perspective)]] Vertex_Tangent: vec4) -> VertexOutput { + gen_entry_Vertex_Position = Vertex_Position; + gen_entry_Vertex_Normal = Vertex_Normal; + gen_entry_Vertex_Uv = Vertex_Uv; + gen_entry_Vertex_Tangent = Vertex_Tangent; + main(); + let _e9: vec3 = gen_entry_v_WorldPosition; + let _e11: vec3 = gen_entry_v_WorldNormal; + let _e13: vec2 = gen_entry_v_Uv; + let _e15: vec4 = gen_entry_v_WorldTangent; + let _e17: vec4 = gl_Position; + return VertexOutput(_e9, _e11, _e13, _e15, _e17); +} diff --git a/tests/out/constant-array-size-vert.wgsl b/tests/out/constant-array-size-vert.wgsl new file mode 100644 index 000000000..96c2472e1 --- /dev/null +++ b/tests/out/constant-array-size-vert.wgsl @@ -0,0 +1,35 @@ +[[block]] +struct Data { + vecs: [[stride(16)]] array,42>; +}; + +[[group(1), binding(0)]] +var global: Data; + +fn function() -> vec4 { + var sum: vec4; + var i: i32 = 0; + var local: i32; + + sum = vec4(f32(0)); + loop { + let _e9: i32 = i; + if (!((_e9 < 42))) { + break; + } + { + let _e17: vec4 = sum; + let _e18: i32 = i; + let _e20: vec4 = global.vecs[_e18]; + sum = (_e17 + _e20); + } + continuing { + let _e12: i32 = i; + local = _e12; + i = (_e12 + 1); + } + } + let _e22: vec4 = sum; + return _e22; +} + diff --git a/tests/out/swizzle_write-frag.wgsl b/tests/out/swizzle_write-frag.wgsl new file mode 100644 index 000000000..082c1c642 --- /dev/null +++ b/tests/out/swizzle_write-frag.wgsl @@ -0,0 +1,20 @@ +fn main() { + var x: vec3 = vec3(2.0, 2.0, 2.0); + + let _e3: vec3 = x; + let _e8: vec2 = vec2(3.0, 4.0); + x.z = _e8.x; + x.x = _e8.y; + let _e13: vec3 = x; + let _e15: vec3 = x; + let _e18: vec2 = (_e15.xy * 5.0); + x.x = _e18.x; + x.y = _e18.y; + return; +} + +[[stage(fragment)]] +fn main1() { + main(); + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 06c48e218..9505f2f87 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -430,9 +430,8 @@ fn convert_glsl_folder() { .join(DIR_OUT) .join(&file_name.replace(".", "-")); - // FIXME: https://github.com/gfx-rs/naga/issues/945 - // #[cfg(feature = "wgsl-out")] - // check_output_wgsl(&module, &info, &dest); + #[cfg(feature = "wgsl-out")] + check_output_wgsl(&module, &info, &dest); } } From efd416d96448d0c749d332b857b67bed3b7fc66e Mon Sep 17 00:00:00 2001 From: Frizi Date: Thu, 17 Jun 2021 21:24:50 +0200 Subject: [PATCH 0982/2212] [glsl-in] parse all math functions --- src/front/glsl/functions.rs | 75 +++++++++++---- tests/in/glsl/math-functions.vert | 55 +++++++++++ tests/out/math-functions-vert.wgsl | 147 +++++++++++++++++++++++++++++ 3 files changed, 260 insertions(+), 17 deletions(-) create mode 100644 tests/in/glsl/math-functions.vert create mode 100644 tests/out/math-functions-vert.wgsl diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 8965fd08a..3e25a0d84 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -205,7 +205,9 @@ impl Program<'_> { } "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" - | "normalize" => { + | "normalize" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" + | "log" | "log2" | "length" | "determinant" | "bitCount" + | "bitfieldReverse" => { if args.len() != 1 { return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); } @@ -227,6 +229,19 @@ impl Program<'_> { "transpose" => MathFunction::Transpose, "inverse" => MathFunction::Inverse, "normalize" => MathFunction::Normalize, + "sinh" => MathFunction::Sinh, + "cos" => MathFunction::Cos, + "cosh" => MathFunction::Cosh, + "tan" => MathFunction::Tan, + "tanh" => MathFunction::Tanh, + "acos" => MathFunction::Acos, + "asin" => MathFunction::Asin, + "log" => MathFunction::Log, + "log2" => MathFunction::Log2, + "length" => MathFunction::Length, + "determinant" => MathFunction::Determinant, + "bitCount" => MathFunction::CountOneBits, + "bitfieldReverse" => MathFunction::ReverseBits, _ => unreachable!(), }, arg: args[0].0, @@ -236,6 +251,31 @@ impl Program<'_> { body, ))) } + "atan" => { + let expr = match args.len() { + 1 => Expression::Math { + fun: MathFunction::Atan, + arg: args[0].0, + arg1: None, + arg2: None, + }, + 2 => Expression::Math { + fun: MathFunction::Atan2, + arg: args[0].0, + arg1: Some(args[1].0), + arg2: None, + }, + _ => { + return Err(ErrorKind::wrong_function_args( + name, + 2, + args.len(), + meta, + )) + } + }; + Ok(Some(ctx.add_expression(expr, body))) + } "mod" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); @@ -248,26 +288,17 @@ impl Program<'_> { self, &mut left, left_meta, &mut right, right_meta, )?; - let expr = if let Some(ScalarKind::Float) = - self.resolve_type(ctx, args[0].0, args[1].1)?.scalar_kind() - { - Expression::Math { - fun: MathFunction::Modf, - arg: left, - arg1: Some(right), - arg2: None, - } - } else { + Ok(Some(ctx.add_expression( Expression::Binary { op: BinaryOperator::Modulo, left, right, - } - }; - - Ok(Some(ctx.add_expression(expr, body))) + }, + body, + ))) } - "pow" | "dot" | "max" | "min" | "reflect" | "cross" => { + "pow" | "dot" | "max" | "min" | "reflect" | "cross" | "outerProduct" + | "distance" | "step" | "modf" | "frexp" | "ldexp" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } @@ -280,6 +311,12 @@ impl Program<'_> { "min" => MathFunction::Min, "reflect" => MathFunction::Reflect, "cross" => MathFunction::Cross, + "outerProduct" => MathFunction::Outer, + "distance" => MathFunction::Distance, + "step" => MathFunction::Step, + "modf" => MathFunction::Modf, + "frexp" => MathFunction::Frexp, + "ldexp" => MathFunction::Ldexp, _ => unreachable!(), }, arg: args[0].0, @@ -289,7 +326,7 @@ impl Program<'_> { body, ))) } - "mix" | "clamp" => { + "mix" | "clamp" | "faceforward" | "refract" | "fma" | "smoothstep" => { if args.len() != 3 { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } @@ -298,6 +335,10 @@ impl Program<'_> { fun: match name.as_str() { "mix" => MathFunction::Mix, "clamp" => MathFunction::Clamp, + "faceforward" => MathFunction::FaceForward, + "refract" => MathFunction::Refract, + "fma" => MathFunction::Fma, + "smoothstep" => MathFunction::SmoothStep, _ => unreachable!(), }, arg: args[0].0, diff --git a/tests/in/glsl/math-functions.vert b/tests/in/glsl/math-functions.vert new file mode 100644 index 000000000..ff1851a69 --- /dev/null +++ b/tests/in/glsl/math-functions.vert @@ -0,0 +1,55 @@ +#version 450 + +void main() { + vec4 a = vec4(1.0); + vec4 b = vec4(2.0); + mat4 m = mat4(a, b, a, b); + int i = 5; + + vec4 ceilOut = ceil(a); + vec4 roundOut = round(a); + vec4 floorOut = floor(a); + vec4 fractOut = fract(a); + vec4 truncOut = trunc(a); + vec4 sinOut = sin(a); + vec4 absOut = abs(a); + vec4 sqrtOut = sqrt(a); + vec4 inversesqrtOut = inversesqrt(a); + vec4 expOut = exp(a); + vec4 exp2Out = exp2(a); + vec4 signOut = sign(a); + mat4 transposeOut = transpose(m); + // TODO: support inverse function in wgsl output + // mat4 inverseOut = inverse(m); + vec4 normalizeOut = normalize(a); + vec4 sinhOut = sinh(a); + vec4 cosOut = cos(a); + vec4 coshOut = cosh(a); + vec4 tanOut = tan(a); + vec4 tanhOut = tanh(a); + vec4 acosOut = acos(a); + vec4 asinOut = asin(a); + vec4 logOut = log(a); + vec4 log2Out = log2(a); + float lengthOut = length(a); + float determinantOut = determinant(m); + int bitCountOut = bitCount(i); + int bitfieldReverseOut = bitfieldReverse(i); + float atanOut = atan(a.x); + float atan2Out = atan(a.x, a.y); + float modOut = mod(a.x, b.x); + vec4 powOut = pow(a, b); + float dotOut = dot(a, b); + vec4 maxOut = max(a, b); + vec4 minOut = min(a, b); + vec4 reflectOut = reflect(a, b); + vec3 crossOut = cross(a.xyz, b.xyz); + mat4 outerProductOut = outerProduct(a, b); + float distanceOut = distance(a, b); + vec4 stepOut = step(a, b); + // TODO: support out params in wgsl output + // vec4 modfOut = modf(a, b); + // vec4 frexpOut = frexp(a, b); + // float ldexpOut = ldexp(a.x, i); + +} \ No newline at end of file diff --git a/tests/out/math-functions-vert.wgsl b/tests/out/math-functions-vert.wgsl new file mode 100644 index 000000000..8cb0af35e --- /dev/null +++ b/tests/out/math-functions-vert.wgsl @@ -0,0 +1,147 @@ +fn main() { + var a: vec4 = vec4(1.0, 1.0, 1.0, 1.0); + var b: vec4 = vec4(2.0, 2.0, 2.0, 2.0); + var m: mat4x4; + var i: i32 = 5; + var ceilOut: vec4; + var roundOut: vec4; + var floorOut: vec4; + var fractOut: vec4; + var truncOut: vec4; + var sinOut: vec4; + var absOut: vec4; + var sqrtOut: vec4; + var inversesqrtOut: vec4; + var expOut: vec4; + var exp2Out: vec4; + var signOut: vec4; + var transposeOut: mat4x4; + var normalizeOut: vec4; + var sinhOut: vec4; + var cosOut: vec4; + var coshOut: vec4; + var tanOut: vec4; + var tanhOut: vec4; + var acosOut: vec4; + var asinOut: vec4; + var logOut: vec4; + var log2Out: vec4; + var lengthOut: f32; + var determinantOut: f32; + var bitCountOut: i32; + var bitfieldReverseOut: i32; + var atanOut: f32; + var atan2Out: f32; + var modOut: f32; + var powOut: vec4; + var dotOut: f32; + var maxOut: vec4; + var minOut: vec4; + var reflectOut: vec4; + var crossOut: vec3; + var outerProductOut: mat4x4; + var distanceOut: f32; + var stepOut: vec4; + + let _e6: vec4 = a; + let _e7: vec4 = b; + let _e8: vec4 = a; + let _e9: vec4 = b; + m = mat4x4(_e6, _e7, _e8, _e9); + let _e14: vec4 = a; + ceilOut = ceil(_e14); + let _e17: vec4 = a; + roundOut = round(_e17); + let _e20: vec4 = a; + floorOut = floor(_e20); + let _e23: vec4 = a; + fractOut = fract(_e23); + let _e26: vec4 = a; + truncOut = trunc(_e26); + let _e29: vec4 = a; + sinOut = sin(_e29); + let _e32: vec4 = a; + absOut = abs(_e32); + let _e35: vec4 = a; + sqrtOut = sqrt(_e35); + let _e38: vec4 = a; + inversesqrtOut = inverseSqrt(_e38); + let _e41: vec4 = a; + expOut = exp(_e41); + let _e44: vec4 = a; + exp2Out = exp2(_e44); + let _e47: vec4 = a; + signOut = sign(_e47); + let _e50: mat4x4 = m; + transposeOut = transpose(_e50); + let _e53: vec4 = a; + normalizeOut = normalize(_e53); + let _e56: vec4 = a; + sinhOut = sinh(_e56); + let _e59: vec4 = a; + cosOut = cos(_e59); + let _e62: vec4 = a; + coshOut = cosh(_e62); + let _e65: vec4 = a; + tanOut = tan(_e65); + let _e68: vec4 = a; + tanhOut = tanh(_e68); + let _e71: vec4 = a; + acosOut = acos(_e71); + let _e74: vec4 = a; + asinOut = asin(_e74); + let _e77: vec4 = a; + logOut = log(_e77); + let _e80: vec4 = a; + log2Out = log2(_e80); + let _e83: vec4 = a; + lengthOut = length(_e83); + let _e86: mat4x4 = m; + determinantOut = determinant(_e86); + let _e89: i32 = i; + bitCountOut = countOneBits(_e89); + let _e92: i32 = i; + bitfieldReverseOut = reverseBits(_e92); + let _e95: vec4 = a; + atanOut = atan(_e95.x); + let _e99: vec4 = a; + let _e101: vec4 = a; + atan2Out = atan2(_e99.x, _e101.y); + let _e105: vec4 = a; + let _e107: vec4 = b; + modOut = (_e105.x % _e107.x); + let _e111: vec4 = a; + let _e112: vec4 = b; + powOut = pow(_e111, _e112); + let _e115: vec4 = a; + let _e116: vec4 = b; + dotOut = dot(_e115, _e116); + let _e119: vec4 = a; + let _e120: vec4 = b; + maxOut = max(_e119, _e120); + let _e123: vec4 = a; + let _e124: vec4 = b; + minOut = min(_e123, _e124); + let _e127: vec4 = a; + let _e128: vec4 = b; + reflectOut = reflect(_e127, _e128); + let _e131: vec4 = a; + let _e133: vec4 = b; + crossOut = cross(_e131.xyz, _e133.xyz); + let _e137: vec4 = a; + let _e138: vec4 = b; + outerProductOut = outerProduct(_e137, _e138); + let _e141: vec4 = a; + let _e142: vec4 = b; + distanceOut = distance(_e141, _e142); + let _e145: vec4 = a; + let _e146: vec4 = b; + stepOut = step(_e145, _e146); + return; +} + +[[stage(vertex)]] +fn main1() { + main(); + return; +} From e3827f8e0899377c0177faa1f106ec2f3f8a9e3e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Jun 2021 00:10:35 -0400 Subject: [PATCH 0983/2212] Improve the MemberOutOfBounds error --- src/valid/type.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/valid/type.rs b/src/valid/type.rs index 8b5e108ef..e9f888a63 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -57,9 +57,14 @@ pub enum TypeError { #[error("Structure member[{index}] at {offset} overlaps the previous member")] MemberOverlap { index: u32, offset: u32 }, #[error( - "Structure member[{index}] at {offset} and size {size} crosses the structure boundary" + "Structure member[{index}] at {offset} and size {size} crosses the structure boundary of size {span}" )] - MemberOutOfBounds { index: u32, offset: u32, size: u32 }, + MemberOutOfBounds { + index: u32, + offset: u32, + size: u32, + span: u32, + }, #[error("The composite type contains a top-level structure")] NestedTopLevel, } @@ -359,6 +364,7 @@ impl super::Validator { index: i as u32, offset: member.offset, size: base_size, + span, }); } From c2cfcbf84b3c84cd8354661135f41a46e837f01d Mon Sep 17 00:00:00 2001 From: Jakob Hellermann Date: Tue, 1 Jun 2021 20:19:23 +0200 Subject: [PATCH 0984/2212] [glsl-in] include information on what was expected in `InvalidToken` --- src/front/glsl/error.rs | 50 ++++++++++++-- src/front/glsl/parser.rs | 119 ++++++++++++++++++++++++++++----- src/front/glsl/parser_tests.rs | 12 ++-- 3 files changed, 155 insertions(+), 26 deletions(-) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 924f411d0..bb2baa972 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -1,10 +1,52 @@ use super::{ constants::ConstantSolvingError, - token::{SourceMetadata, Token}, + token::{SourceMetadata, Token, TokenValue}, }; use std::borrow::Cow; use thiserror::Error; +fn join_with_comma(list: &[ExpectedToken]) -> String { + let mut string = "".to_string(); + for (i, val) in list.iter().enumerate() { + string.push_str(&val.to_string()); + match i { + i if i == list.len() - 1 => {} + i if i == list.len() - 2 => string.push_str(" or "), + _ => string.push_str(", "), + } + } + string +} + +#[derive(Debug, PartialEq)] +pub enum ExpectedToken { + Token(TokenValue), + TypeName, + Identifier, + IntLiteral, + FloatLiteral, + BoolLiteral, + EOF, +} +impl From for ExpectedToken { + fn from(token: TokenValue) -> Self { + ExpectedToken::Token(token) + } +} +impl std::fmt::Display for ExpectedToken { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + ExpectedToken::Token(ref token) => write!(f, "{:?}", token), + ExpectedToken::TypeName => write!(f, "a type"), + ExpectedToken::Identifier => write!(f, "identifier"), + ExpectedToken::IntLiteral => write!(f, "integer literal"), + ExpectedToken::FloatLiteral => write!(f, "float literal"), + ExpectedToken::BoolLiteral => write!(f, "bool literal"), + ExpectedToken::EOF => write!(f, "end of file"), + } + } +} + #[derive(Debug, Error)] #[cfg_attr(test, derive(PartialEq))] pub enum ErrorKind { @@ -14,8 +56,8 @@ pub enum ErrorKind { InvalidProfile(SourceMetadata, String), #[error("Invalid version: {1}")] InvalidVersion(SourceMetadata, u64), - #[error("Unexpected token: {0}")] - InvalidToken(Token), + #[error("Expected {}, found {0}", join_with_comma(.1))] + InvalidToken(Token, Vec), #[error("Not implemented {0}")] NotImplemented(&'static str), #[error("Unknown variable: {1}")] @@ -43,7 +85,7 @@ impl ErrorKind { | ErrorKind::UnknownLayoutQualifier(metadata, _) | ErrorKind::SemanticError(metadata, _) | ErrorKind::UnknownField(metadata, _) => Some(metadata), - ErrorKind::InvalidToken(ref token) => Some(token.meta), + ErrorKind::InvalidToken(ref token, _) => Some(token.meta), _ => None, } } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index ff9b39279..237a8c792 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -11,9 +11,9 @@ use super::{ Program, }; use crate::{ - arena::Handle, Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Expression, - Function, FunctionResult, ResourceBinding, ScalarValue, Statement, StorageClass, StructMember, - SwitchCase, Type, TypeInner, UnaryOperator, + arena::Handle, front::glsl::error::ExpectedToken, Arena, ArraySize, BinaryOperator, Block, + Constant, ConstantInner, Expression, Function, FunctionResult, ResourceBinding, ScalarValue, + Statement, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, }; use core::convert::TryFrom; use std::{iter::Peekable, mem}; @@ -38,7 +38,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match token.value { TokenValue::Identifier(name) => Ok((name, token.meta)), - _ => Err(ErrorKind::InvalidToken(token)), + _ => Err(ErrorKind::InvalidToken( + token, + vec![ExpectedToken::Identifier], + )), } } @@ -46,7 +49,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let token = self.bump()?; if token.value != value { - Err(ErrorKind::InvalidToken(token)) + Err(ErrorKind::InvalidToken(token, vec![value.into()])) } else { Ok(token) } @@ -90,7 +93,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { 440 | 450 | 460 => self.program.version = i.value as u16, _ => return Err(ErrorKind::InvalidVersion(version.meta, i.value)), }, - _ => return Err(ErrorKind::InvalidToken(version)), + _ => { + return Err(ErrorKind::InvalidToken( + version, + vec![ExpectedToken::IntLiteral], + )) + } } let profile = self.lexer.peek(); @@ -155,7 +163,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Some(ty) => Some(*ty), None => return Err(ErrorKind::UnknownType(token.meta, ident)), }, - _ => return Err(ErrorKind::InvalidToken(token)), + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ + TokenValue::Void.into(), + TokenValue::Struct.into(), + ExpectedToken::TypeName, + ], + )) + } }; let size = self.parse_array_specifier()?; @@ -363,7 +380,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(()) } // TODO: handle Shared? - _ => Err(ErrorKind::InvalidToken(token)), + _ => Err(ErrorKind::InvalidToken( + token, + vec![ExpectedToken::Identifier], + )), } } @@ -405,7 +425,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let token = self.bump()?; match token.value { TokenValue::Semicolon if self.program.version == 460 => Ok(()), - _ => Err(ErrorKind::InvalidToken(token)), + _ => { + let expected = match self.program.version { + 460 => vec![TokenValue::Semicolon.into(), ExpectedToken::EOF], + _ => vec![ExpectedToken::EOF], + }; + Err(ErrorKind::InvalidToken(token, expected)) + } } } else { Ok(()) @@ -479,7 +505,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta = meta.union(&token.meta); break; } - _ => return Err(ErrorKind::InvalidToken(token)), + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![TokenValue::Comma.into(), TokenValue::RightBrace.into()], + )) + } } } @@ -534,7 +565,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let name = match token.value { TokenValue::Semicolon => break, TokenValue::Identifier(name) => name, - _ => return Err(ErrorKind::InvalidToken(token)), + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], + )) + } }; let mut meta = token.meta; @@ -581,7 +617,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { match token.value { TokenValue::Semicolon => break, TokenValue::Comma => {} - _ => return Err(ErrorKind::InvalidToken(token)), + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![TokenValue::Comma.into(), TokenValue::Semicolon.into()], + )) + } } } @@ -697,7 +738,17 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(true) } - _ => Err(ErrorKind::InvalidToken(token)), + _ if external => Err(ErrorKind::InvalidToken( + token, + vec![ + TokenValue::LeftBrace.into(), + TokenValue::Semicolon.into(), + ], + )), + _ => Err(ErrorKind::InvalidToken( + token, + vec![TokenValue::Semicolon.into()], + )), }; } // Pass the token to the init_declator_list parser @@ -772,7 +823,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Ok(true) } - _ => Err(ErrorKind::InvalidToken(token)), + _ => Err(ErrorKind::InvalidToken( + token, + vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], + )), } } } else { @@ -820,7 +874,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { Some(name) } - _ => return Err(ErrorKind::InvalidToken(token)), + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], + )) + } }; meta = meta.union(&token.meta); @@ -914,7 +973,17 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { return Ok(expr); } - _ => return Err(ErrorKind::InvalidToken(token)), + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ + TokenValue::LeftParen.into(), + ExpectedToken::IntLiteral, + ExpectedToken::FloatLiteral, + ExpectedToken::BoolLiteral, + ], + )) + } }; let handle = self.program.module.constants.append(Constant { @@ -949,7 +1018,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { *meta = meta.union(&token.meta); break; } - _ => return Err(ErrorKind::InvalidToken(token)), + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![TokenValue::Comma.into(), TokenValue::RightParen.into()], + )) + } } } } @@ -1420,7 +1494,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.bump()?; break; } - _ => return Err(ErrorKind::InvalidToken(self.bump()?)), + _ => { + return Err(ErrorKind::InvalidToken( + self.bump()?, + vec![ + TokenValue::Case.into(), + TokenValue::Default.into(), + TokenValue::RightBrace.into(), + ], + )) + } } } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 9bed09ffa..81107171e 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -4,6 +4,7 @@ use super::lex::Lexer; use super::parser; use super::{ast::Profile, error::ErrorKind}; use super::{ast::Program, SourceMetadata}; +use crate::front::glsl::error::ExpectedToken; use crate::{ front::glsl::{token::TokenValue, Token}, ShaderStage, @@ -50,10 +51,13 @@ fn version() { parse_program("#version 450\nvoid f(){} #version 450", &entry_points) .err() .unwrap(), - ErrorKind::InvalidToken(Token { - value: TokenValue::Unknown(PreprocessorError::UnexpectedHash), - meta: SourceMetadata { start: 24, end: 25 } - }) + ErrorKind::InvalidToken( + Token { + value: TokenValue::Unknown(PreprocessorError::UnexpectedHash), + meta: SourceMetadata { start: 24, end: 25 } + }, + vec![ExpectedToken::EOF] + ) ); // valid versions From 8f410d5ca8fd495cb8c851c2a5fe30153adab161 Mon Sep 17 00:00:00 2001 From: Jakob Hellermann Date: Tue, 1 Jun 2021 21:03:40 +0200 Subject: [PATCH 0985/2212] [glsl-in] add source metadata to VariableAlreadyDeclared error --- src/front/glsl/error.rs | 6 ++++-- src/front/glsl/variables.rs | 5 +++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index bb2baa972..420f6a2e9 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -69,8 +69,8 @@ pub enum ErrorKind { #[error("Unknown layout qualifier: {1}")] UnknownLayoutQualifier(SourceMetadata, String), #[cfg(feature = "glsl-validate")] - #[error("Variable already declared: {0}")] - VariableAlreadyDeclared(String), + #[error("Variable already declared: {1}")] + VariableAlreadyDeclared(SourceMetadata, String), #[error("{1}")] SemanticError(SourceMetadata, Cow<'static, str>), } @@ -85,6 +85,8 @@ impl ErrorKind { | ErrorKind::UnknownLayoutQualifier(metadata, _) | ErrorKind::SemanticError(metadata, _) | ErrorKind::UnknownField(metadata, _) => Some(metadata), + #[cfg(feature = "glsl-validate")] + ErrorKind::VariableAlreadyDeclared(metadata, _) => Some(metadata), ErrorKind::InvalidToken(ref token, _) => Some(token.meta), _ => None, } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 0108adf8f..205514f03 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -510,18 +510,19 @@ impl Program<'_> { &mut self, ctx: &mut Context, body: &mut Block, + #[cfg_attr(not(feature = "glsl-validate"), allow(unused_variables))] VarDeclaration { qualifiers, ty, name, init, - .. + meta, }: VarDeclaration, ) -> Result, ErrorKind> { #[cfg(feature = "glsl-validate")] if let Some(ref name) = name { if ctx.lookup_local_var_current_scope(name).is_some() { - return Err(ErrorKind::VariableAlreadyDeclared(name.clone())); + return Err(ErrorKind::VariableAlreadyDeclared(meta, name.clone())); } } From 9d7e5cf0b5331fac5ecbe824db897988e6f0c405 Mon Sep 17 00:00:00 2001 From: Jakob Hellermann Date: Sun, 13 Jun 2021 10:54:03 +0200 Subject: [PATCH 0986/2212] [cli] add codespan_reporting to glsl error --- cli/src/main.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 47 insertions(+), 5 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 14d4c1185..3e04b055b 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -20,8 +20,15 @@ trait PrettyResult { } fn print_err(error: impl Error) { - eprintln!("{}:", error); + eprint!("{}", error); + let mut e = error.source(); + if e.is_some() { + eprintln!(": "); + } else { + eprintln!(); + } + while let Some(source) = e { eprintln!("\t{}", source); e = source.source(); @@ -92,7 +99,7 @@ fn main() { } let input_path = match input_path { - Some(ref string) => string, + Some(ref string) => Path::new(string), None => { println!("Call with []"); return; @@ -135,7 +142,11 @@ fn main() { defines: Default::default(), }, ) - .unwrap_pretty() + .unwrap_or_else(|err| { + let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); + emit_glsl_parser_error(err, filename.unwrap_or("glsl"), &input); + std::process::exit(1); + }) } "frag" => { let input = fs::read_to_string(input_path).unwrap(); @@ -148,7 +159,11 @@ fn main() { defines: Default::default(), }, ) - .unwrap_pretty() + .unwrap_or_else(|err| { + let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); + emit_glsl_parser_error(err, filename.unwrap_or("glsl"), &input); + std::process::exit(1); + }) } "comp" => { let input = fs::read_to_string(input_path).unwrap(); @@ -161,7 +176,11 @@ fn main() { defines: Default::default(), }, ) - .unwrap_pretty() + .unwrap_or_else(|err| { + let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); + emit_glsl_parser_error(err, filename.unwrap_or("glsl"), &input); + std::process::exit(1); + }) } other => panic!("Unknown input extension: {}", other), }; @@ -274,3 +293,26 @@ fn main() { } } } + +use codespan_reporting::{ + diagnostic::{Diagnostic, Label}, + files::SimpleFile, + term::{ + self, + termcolor::{ColorChoice, StandardStream}, + }, +}; + +pub fn emit_glsl_parser_error(err: naga::front::glsl::ParseError, filename: &str, source: &str) { + let diagnostic = match err.kind.metadata() { + Some(metadata) => Diagnostic::error() + .with_message(err.kind.to_string()) + .with_labels(vec![Label::primary((), metadata.start..metadata.end)]), + None => Diagnostic::error().with_message(err.kind.to_string()), + }; + + let files = SimpleFile::new(filename, source); + let config = codespan_reporting::term::Config::default(); + let writer = StandardStream::stderr(ColorChoice::Auto); + term::emit(&mut writer.lock(), &config, &files, &diagnostic).expect("cannot write error"); +} From b89da31cc718fc2bba8a7e25bc9c99ac7a9fa12b Mon Sep 17 00:00:00 2001 From: Frizi Date: Fri, 18 Jun 2021 02:21:42 +0200 Subject: [PATCH 0987/2212] reorder namer assignment order to preserve names for reflection --- src/front/glsl/functions.rs | 2 +- src/front/glsl/variables.rs | 2 +- src/proc/namer.rs | 81 +++++++----- tests/out/210-bevy-2d-shader-frag.wgsl | 16 +-- tests/out/210-bevy-2d-shader-vert.wgsl | 30 ++--- tests/out/210-bevy-shader-vert.wgsl | 56 ++++---- tests/out/246-collatz-comp.wgsl | 6 +- tests/out/277-casting-vert.wgsl | 6 +- tests/out/280-matrix-cast-vert.wgsl | 6 +- tests/out/484-preprocessor-if-vert.wgsl | 6 +- tests/out/800-out-of-bounds-panic-vert.wgsl | 28 ++-- tests/out/896-push-constant-vert.wgsl | 6 +- tests/out/901-lhs-field-select-vert.wgsl | 6 +- tests/out/932-for-loop-if-vert.wgsl | 6 +- tests/out/bevy-pbr-frag.wgsl | 138 ++++++++++---------- tests/out/bevy-pbr-vert.wgsl | 66 +++++----- tests/out/boids.Compute.glsl | 20 +-- tests/out/boids.msl | 20 +-- tests/out/boids.wgsl | 20 +-- tests/out/interface.msl | 14 +- tests/out/interface.wgsl | 12 +- tests/out/math-functions-vert.wgsl | 6 +- tests/out/quad-glsl.wgsl | 44 +++---- tests/out/quad-vert.Vertex.glsl | 30 ++--- tests/out/quad-vert.msl | 52 ++++---- tests/out/quad-vert.wgsl | 20 +-- tests/out/quad.Fragment.glsl | 4 +- tests/out/quad.Vertex.glsl | 4 +- tests/out/quad.hlsl | 8 +- tests/out/quad.msl | 12 +- tests/out/quad.wgsl | 8 +- tests/out/shadow.Fragment.glsl | 8 +- tests/out/shadow.msl | 8 +- tests/out/shadow.wgsl | 8 +- tests/out/swizzle_write-frag.wgsl | 6 +- 35 files changed, 390 insertions(+), 375 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 3e25a0d84..9095f4c4b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -701,7 +701,7 @@ impl Program<'_> { let ty = self.module.global_variables[arg.handle].ty; members.push(StructMember { - name: None, + name: arg.name.clone(), ty, binding: Some(arg.binding.clone()), offset: span, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 205514f03..c3fb8c766 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -407,7 +407,7 @@ impl Program<'_> { }); let handle = self.module.global_variables.append(GlobalVariable { - name: name.as_ref().map(|n| format!("gen_entry_{}", n)), + name: name.clone(), class: StorageClass::Private, binding: None, ty, diff --git a/src/proc/namer.rs b/src/proc/namer.rs index c339c4cf9..2936a9ae5 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -86,6 +86,18 @@ impl Namer { }) } + fn namespace(&mut self, reserved_keywords: &[&str], f: impl FnOnce(&mut Self)) { + let parent_unique = std::mem::take(&mut self.unique); + self.unique.extend( + reserved_keywords + .iter() + .map(|string| (string.to_string(), 0)), + ); + + f(self); + self.unique = parent_unique; + } + pub fn reset( &mut self, module: &crate::Module, @@ -110,10 +122,42 @@ impl Namer { output.insert(NameKey::Type(ty_handle), ty_name); if let crate::TypeInner::Struct { ref members, .. } = ty.inner { - for (index, member) in members.iter().enumerate() { - let name = self.call_or(&member.name, "member"); - output.insert(NameKey::StructMember(ty_handle, index as u32), name); - } + // struct members have their own namespace, because access is always prefixed + self.namespace(reserved_keywords, |namer| { + for (index, member) in members.iter().enumerate() { + let name = namer.call_or(&member.name, "member"); + output.insert(NameKey::StructMember(ty_handle, index as u32), name); + } + }) + } + } + + for (ep_index, ep) in module.entry_points.iter().enumerate() { + let ep_name = self.call(&ep.name); + output.insert(NameKey::EntryPoint(ep_index as _), ep_name); + for (index, arg) in ep.function.arguments.iter().enumerate() { + let name = self.call_or(&arg.name, "param"); + output.insert( + NameKey::EntryPointArgument(ep_index as _, index as u32), + name, + ); + } + for (handle, var) in ep.function.local_variables.iter() { + let name = self.call_or(&var.name, "local"); + output.insert(NameKey::EntryPointLocal(ep_index as _, handle), name); + } + } + + for (fun_handle, fun) in module.functions.iter() { + let fun_name = self.call_or(&fun.name, "function"); + output.insert(NameKey::Function(fun_handle), fun_name); + for (index, arg) in fun.arguments.iter().enumerate() { + let name = self.call_or(&arg.name, "param"); + output.insert(NameKey::FunctionArgument(fun_handle, index as u32), name); + } + for (handle, var) in fun.local_variables.iter() { + let name = self.call_or(&var.name, "local"); + output.insert(NameKey::FunctionLocal(fun_handle, handle), name); } } @@ -172,34 +216,5 @@ impl Namer { let name = self.call(label); output.insert(NameKey::Constant(handle), name); } - - for (fun_handle, fun) in module.functions.iter() { - let fun_name = self.call_or(&fun.name, "function"); - output.insert(NameKey::Function(fun_handle), fun_name); - for (index, arg) in fun.arguments.iter().enumerate() { - let name = self.call_or(&arg.name, "param"); - output.insert(NameKey::FunctionArgument(fun_handle, index as u32), name); - } - for (handle, var) in fun.local_variables.iter() { - let name = self.call_or(&var.name, "local"); - output.insert(NameKey::FunctionLocal(fun_handle, handle), name); - } - } - - for (ep_index, ep) in module.entry_points.iter().enumerate() { - let ep_name = self.call(&ep.name); - output.insert(NameKey::EntryPoint(ep_index as _), ep_name); - for (index, arg) in ep.function.arguments.iter().enumerate() { - let name = self.call_or(&arg.name, "param"); - output.insert( - NameKey::EntryPointArgument(ep_index as _, index as u32), - name, - ); - } - for (handle, var) in ep.function.local_variables.iter() { - let name = self.call_or(&var.name, "local"); - output.insert(NameKey::EntryPointLocal(ep_index as _, handle), name); - } - } } } diff --git a/tests/out/210-bevy-2d-shader-frag.wgsl b/tests/out/210-bevy-2d-shader-frag.wgsl index 078da3536..59986e986 100644 --- a/tests/out/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/210-bevy-2d-shader-frag.wgsl @@ -4,27 +4,27 @@ struct ColorMaterial_color { }; struct FragmentOutput { - [[location(0), interpolate(perspective)]] member: vec4; + [[location(0), interpolate(perspective)]] o_Target: vec4; }; -var gen_entry_v_Uv: vec2; -var gen_entry_o_Target: vec4; +var v_Uv: vec2; +var o_Target: vec4; [[group(1), binding(0)]] var global: ColorMaterial_color; -fn main() { +fn main1() { var color: vec4; let _e4: vec4 = global.Color; color = _e4; let _e6: vec4 = color; - gen_entry_o_Target = _e6; + o_Target = _e6; return; } [[stage(fragment)]] -fn main1() -> FragmentOutput { - main(); - let _e1: vec4 = gen_entry_o_Target; +fn main() -> FragmentOutput { + main1(); + let _e1: vec4 = o_Target; return FragmentOutput(_e1); } diff --git a/tests/out/210-bevy-2d-shader-vert.wgsl b/tests/out/210-bevy-2d-shader-vert.wgsl index 07be5beea..45b32f351 100644 --- a/tests/out/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/210-bevy-2d-shader-vert.wgsl @@ -14,14 +14,14 @@ struct Sprite_size { }; struct VertexOutput { - [[location(0), interpolate(perspective)]] member: vec2; - [[builtin(position)]] member1: vec4; + [[location(0), interpolate(perspective)]] v_Uv: vec2; + [[builtin(position)]] member: vec4; }; -var gen_entry_Vertex_Position: vec3; -var gen_entry_Vertex_Normal: vec3; -var gen_entry_Vertex_Uv: vec2; -var gen_entry_v_Uv: vec2; +var Vertex_Position1: vec3; +var Vertex_Normal: vec3; +var Vertex_Uv1: vec2; +var v_Uv: vec2; [[group(0), binding(0)]] var global: Camera; [[group(2), binding(0)]] @@ -30,12 +30,12 @@ var global1: Transform; var global2: Sprite_size; var gl_Position: vec4; -fn main() { +fn main1() { var position: vec3; - let _e10: vec2 = gen_entry_Vertex_Uv; - gen_entry_v_Uv = _e10; - let _e11: vec3 = gen_entry_Vertex_Position; + let _e10: vec2 = Vertex_Uv1; + v_Uv = _e10; + let _e11: vec3 = Vertex_Position1; let _e12: vec2 = global2.size; position = (_e11 * vec3(_e12, 1.0)); let _e18: mat4x4 = global.ViewProj; @@ -46,11 +46,11 @@ fn main() { } [[stage(vertex)]] -fn main1([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2) -> VertexOutput { - gen_entry_Vertex_Position = Vertex_Position; - gen_entry_Vertex_Uv = Vertex_Uv; - main(); - let _e5: vec2 = gen_entry_v_Uv; +fn main([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2) -> VertexOutput { + Vertex_Position1 = Vertex_Position; + Vertex_Uv1 = Vertex_Uv; + main1(); + let _e5: vec2 = v_Uv; let _e7: vec4 = gl_Position; return VertexOutput(_e5, _e7); } diff --git a/tests/out/210-bevy-shader-vert.wgsl b/tests/out/210-bevy-shader-vert.wgsl index 8e82a0cf4..2cdca5706 100644 --- a/tests/out/210-bevy-shader-vert.wgsl +++ b/tests/out/210-bevy-shader-vert.wgsl @@ -9,51 +9,51 @@ struct Transform { }; struct VertexOutput { - [[location(0), interpolate(perspective)]] member: vec3; - [[location(1), interpolate(perspective)]] member1: vec3; - [[location(2), interpolate(perspective)]] member2: vec2; - [[builtin(position)]] member3: vec4; + [[location(0), interpolate(perspective)]] v_Position: vec3; + [[location(1), interpolate(perspective)]] v_Normal: vec3; + [[location(2), interpolate(perspective)]] v_Uv: vec2; + [[builtin(position)]] member: vec4; }; -var gen_entry_Vertex_Position: vec3; -var gen_entry_Vertex_Normal: vec3; -var gen_entry_Vertex_Uv: vec2; -var gen_entry_v_Position: vec3; -var gen_entry_v_Normal: vec3; -var gen_entry_v_Uv: vec2; +var Vertex_Position1: vec3; +var Vertex_Normal1: vec3; +var Vertex_Uv1: vec2; +var v_Position: vec3; +var v_Normal: vec3; +var v_Uv: vec2; [[group(0), binding(0)]] var global: Camera; [[group(2), binding(0)]] var global1: Transform; var gl_Position: vec4; -fn main() { +fn main1() { let _e10: mat4x4 = global1.Model; - let _e11: vec3 = gen_entry_Vertex_Normal; - gen_entry_v_Normal = (_e10 * vec4(_e11, 1.0)).xyz; + let _e11: vec3 = Vertex_Normal1; + v_Normal = (_e10 * vec4(_e11, 1.0)).xyz; let _e16: mat4x4 = global1.Model; - let _e24: vec3 = gen_entry_Vertex_Normal; - gen_entry_v_Normal = (mat3x3(_e16[0].xyz, _e16[1].xyz, _e16[2].xyz) * _e24); + let _e24: vec3 = Vertex_Normal1; + v_Normal = (mat3x3(_e16[0].xyz, _e16[1].xyz, _e16[2].xyz) * _e24); let _e26: mat4x4 = global1.Model; - let _e27: vec3 = gen_entry_Vertex_Position; - gen_entry_v_Position = (_e26 * vec4(_e27, 1.0)).xyz; - let _e32: vec2 = gen_entry_Vertex_Uv; - gen_entry_v_Uv = _e32; + let _e27: vec3 = Vertex_Position1; + v_Position = (_e26 * vec4(_e27, 1.0)).xyz; + let _e32: vec2 = Vertex_Uv1; + v_Uv = _e32; let _e34: mat4x4 = global.ViewProj; - let _e35: vec3 = gen_entry_v_Position; + let _e35: vec3 = v_Position; gl_Position = (_e34 * vec4(_e35, 1.0)); return; } [[stage(vertex)]] -fn main1([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(1), interpolate(perspective)]] Vertex_Normal: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2) -> VertexOutput { - gen_entry_Vertex_Position = Vertex_Position; - gen_entry_Vertex_Normal = Vertex_Normal; - gen_entry_Vertex_Uv = Vertex_Uv; - main(); - let _e7: vec3 = gen_entry_v_Position; - let _e9: vec3 = gen_entry_v_Normal; - let _e11: vec2 = gen_entry_v_Uv; +fn main([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(1), interpolate(perspective)]] Vertex_Normal: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2) -> VertexOutput { + Vertex_Position1 = Vertex_Position; + Vertex_Normal1 = Vertex_Normal; + Vertex_Uv1 = Vertex_Uv; + main1(); + let _e7: vec3 = v_Position; + let _e9: vec3 = v_Normal; + let _e11: vec2 = v_Uv; let _e13: vec4 = gl_Position; return VertexOutput(_e7, _e9, _e11, _e13); } diff --git a/tests/out/246-collatz-comp.wgsl b/tests/out/246-collatz-comp.wgsl index fee36a78c..08d58c28a 100644 --- a/tests/out/246-collatz-comp.wgsl +++ b/tests/out/246-collatz-comp.wgsl @@ -41,7 +41,7 @@ fn collatz_iterations(n: u32) -> u32 { return _e35; } -fn main() { +fn main1() { var index: u32; let _e3: vec3 = gl_GlobalInvocationID; @@ -56,8 +56,8 @@ fn main() { } [[stage(compute), workgroup_size(1, 1, 1)]] -fn main1([[builtin(global_invocation_id)]] param: vec3) { +fn main([[builtin(global_invocation_id)]] param: vec3) { gl_GlobalInvocationID = param; - main(); + main1(); return; } diff --git a/tests/out/277-casting-vert.wgsl b/tests/out/277-casting-vert.wgsl index 605c86529..673f8443d 100644 --- a/tests/out/277-casting-vert.wgsl +++ b/tests/out/277-casting-vert.wgsl @@ -1,10 +1,10 @@ -fn main() { +fn main1() { var a: f32 = 1.0; } [[stage(vertex)]] -fn main1() { - main(); +fn main() { + main1(); return; } diff --git a/tests/out/280-matrix-cast-vert.wgsl b/tests/out/280-matrix-cast-vert.wgsl index 915109d08..3416dfc75 100644 --- a/tests/out/280-matrix-cast-vert.wgsl +++ b/tests/out/280-matrix-cast-vert.wgsl @@ -1,4 +1,4 @@ -fn main() { +fn main1() { var a: mat4x4; let _e2: vec4 = vec4(f32(1)); @@ -7,7 +7,7 @@ fn main() { } [[stage(vertex)]] -fn main1() { - main(); +fn main() { + main1(); return; } diff --git a/tests/out/484-preprocessor-if-vert.wgsl b/tests/out/484-preprocessor-if-vert.wgsl index 0c58b561b..a5c402fad 100644 --- a/tests/out/484-preprocessor-if-vert.wgsl +++ b/tests/out/484-preprocessor-if-vert.wgsl @@ -1,9 +1,9 @@ -fn main() { +fn main1() { return; } [[stage(vertex)]] -fn main1() { - main(); +fn main() { + main1(); return; } diff --git a/tests/out/800-out-of-bounds-panic-vert.wgsl b/tests/out/800-out-of-bounds-panic-vert.wgsl index c3b90b08b..80198bf1a 100644 --- a/tests/out/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/800-out-of-bounds-panic-vert.wgsl @@ -9,34 +9,34 @@ struct VertexPushConstants { }; struct VertexOutput { - [[location(0), interpolate(perspective)]] member: vec4; - [[builtin(position)]] member1: vec4; + [[location(0), interpolate(perspective)]] frag_color: vec4; + [[builtin(position)]] member: vec4; }; [[group(0), binding(0)]] var global: Globals; var global1: VertexPushConstants; -var gen_entry_position: vec2; -var gen_entry_color: vec4; -var gen_entry_frag_color: vec4; +var position1: vec2; +var color1: vec4; +var frag_color: vec4; var gl_Position: vec4; -fn main() { - let _e7: vec4 = gen_entry_color; - gen_entry_frag_color = _e7; +fn main1() { + let _e7: vec4 = color1; + frag_color = _e7; let _e9: mat4x4 = global.view_matrix; let _e10: mat4x4 = global1.world_matrix; - let _e12: vec2 = gen_entry_position; + let _e12: vec2 = position1; gl_Position = ((_e9 * _e10) * vec4(_e12, 0.0, 1.0)); return; } [[stage(vertex)]] -fn main1([[location(0), interpolate(perspective)]] position: vec2, [[location(1), interpolate(perspective)]] color: vec4) -> VertexOutput { - gen_entry_position = position; - gen_entry_color = color; - main(); - let _e5: vec4 = gen_entry_frag_color; +fn main([[location(0), interpolate(perspective)]] position: vec2, [[location(1), interpolate(perspective)]] color: vec4) -> VertexOutput { + position1 = position; + color1 = color; + main1(); + let _e5: vec4 = frag_color; let _e7: vec4 = gl_Position; return VertexOutput(_e5, _e7); } diff --git a/tests/out/896-push-constant-vert.wgsl b/tests/out/896-push-constant-vert.wgsl index 40c33ac0c..a8f7df78f 100644 --- a/tests/out/896-push-constant-vert.wgsl +++ b/tests/out/896-push-constant-vert.wgsl @@ -5,12 +5,12 @@ struct PushConstants { var c: PushConstants; -fn main() { +fn main1() { return; } [[stage(vertex)]] -fn main1() { - main(); +fn main() { + main1(); return; } diff --git a/tests/out/901-lhs-field-select-vert.wgsl b/tests/out/901-lhs-field-select-vert.wgsl index 2c1b07895..aa791b917 100644 --- a/tests/out/901-lhs-field-select-vert.wgsl +++ b/tests/out/901-lhs-field-select-vert.wgsl @@ -1,4 +1,4 @@ -fn main() { +fn main1() { var a: vec4 = vec4(1.0, 1.0, 1.0, 1.0); a.x = 2.0; @@ -6,7 +6,7 @@ fn main() { } [[stage(vertex)]] -fn main1() { - main(); +fn main() { + main1(); return; } diff --git a/tests/out/932-for-loop-if-vert.wgsl b/tests/out/932-for-loop-if-vert.wgsl index 0bf744473..a9fc14ab3 100644 --- a/tests/out/932-for-loop-if-vert.wgsl +++ b/tests/out/932-for-loop-if-vert.wgsl @@ -1,4 +1,4 @@ -fn main() { +fn main1() { var i: i32 = 0; loop { @@ -17,7 +17,7 @@ fn main() { } [[stage(vertex)]] -fn main1() { - main(); +fn main() { + main1(); return; } diff --git a/tests/out/bevy-pbr-frag.wgsl b/tests/out/bevy-pbr-frag.wgsl index 612de68a3..948b2cfb9 100644 --- a/tests/out/bevy-pbr-frag.wgsl +++ b/tests/out/bevy-pbr-frag.wgsl @@ -6,7 +6,7 @@ struct PointLight { struct DirectionalLight { direction: vec4; - color1: vec4; + color: vec4; }; [[block]] @@ -53,14 +53,14 @@ struct StandardMaterial_emissive { }; struct FragmentOutput { - [[location(0), interpolate(perspective)]] member: vec4; + [[location(0), interpolate(perspective)]] o_Target: vec4; }; -var gen_entry_v_WorldPosition: vec3; -var gen_entry_v_WorldNormal: vec3; -var gen_entry_v_Uv: vec2; -var gen_entry_v_WorldTangent: vec4; -var gen_entry_o_Target: vec4; +var v_WorldPosition1: vec3; +var v_WorldNormal1: vec3; +var v_Uv1: vec2; +var v_WorldTangent1: vec4; +var o_Target: vec4; [[group(0), binding(0)]] var global: CameraViewProj; [[group(0), binding(1)]] @@ -315,9 +315,9 @@ fn Fd_Burley(roughness6: f32, NoV4: f32, NoL4: f32, LoH4: f32) -> f32 { return ((_e74 * _e75) * (1.0 / 3.1415927410125732)); } -fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness1: f32, NoV6: f32) -> vec3 { +fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV6: f32) -> vec3 { var f0_8: vec3; - var perceptual_roughness2: f32; + var perceptual_roughness1: f32; var NoV7: f32; var c0_: vec4 = vec4(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071); var c1_: vec4 = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033); @@ -326,9 +326,9 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness1: f32, NoV6: f32) -> vec3 var AB: vec2; f0_8 = f0_7; - perceptual_roughness2 = perceptual_roughness1; + perceptual_roughness1 = perceptual_roughness; NoV7 = NoV6; - let _e62: f32 = perceptual_roughness2; + let _e62: f32 = perceptual_roughness1; let _e64: vec4 = c0_; let _e66: vec4 = c1_; r = ((vec4(_e62) * _e64) + _e66); @@ -359,29 +359,29 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { return (_e47 * _e48); } -fn reinhard(color2: vec3) -> vec3 { - var color3: vec3; +fn reinhard(color: vec3) -> vec3 { + var color1: vec3; - color3 = color2; - let _e42: vec3 = color3; - let _e45: vec3 = color3; + color1 = color; + let _e42: vec3 = color1; + let _e45: vec3 = color1; return (_e42 / (vec3(1.0) + _e45)); } -fn reinhard_extended(color4: vec3, max_white: f32) -> vec3 { - var color5: vec3; +fn reinhard_extended(color2: vec3, max_white: f32) -> vec3 { + var color3: vec3; var max_white1: f32; var numerator: vec3; - color5 = color4; + color3 = color2; max_white1 = max_white; - let _e44: vec3 = color5; - let _e47: vec3 = color5; + let _e44: vec3 = color3; + let _e47: vec3 = color3; let _e48: f32 = max_white1; let _e49: f32 = max_white1; numerator = (_e44 * (vec3(1.0) + (_e47 / vec3((_e48 * _e49))))); let _e56: vec3 = numerator; - let _e59: vec3 = color5; + let _e59: vec3 = color3; return (_e56 / (vec3(1.0) + _e59)); } @@ -409,34 +409,34 @@ fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { return (_e48 * (_e49 / _e50)); } -fn reinhard_luminance(color6: vec3) -> vec3 { - var color7: vec3; +fn reinhard_luminance(color4: vec3) -> vec3 { + var color5: vec3; var l_old: f32; var l_new: f32; - color7 = color6; - let _e43: vec3 = color7; + color5 = color4; + let _e43: vec3 = color5; let _e44: f32 = luminance(_e43); l_old = _e44; let _e46: f32 = l_old; let _e48: f32 = l_old; l_new = (_e46 / (1.0 + _e48)); - let _e54: vec3 = color7; + let _e54: vec3 = color5; let _e55: f32 = l_new; let _e56: vec3 = change_luminance(_e54, _e55); return _e56; } -fn reinhard_extended_luminance(color8: vec3, max_white_l: f32) -> vec3 { - var color9: vec3; +fn reinhard_extended_luminance(color6: vec3, max_white_l: f32) -> vec3 { + var color7: vec3; var max_white_l1: f32; var l_old1: f32; var numerator1: f32; var l_new1: f32; - color9 = color8; + color7 = color6; max_white_l1 = max_white_l; - let _e45: vec3 = color9; + let _e45: vec3 = color7; let _e46: f32 = luminance(_e45); l_old1 = _e46; let _e48: f32 = l_old1; @@ -447,7 +447,7 @@ fn reinhard_extended_luminance(color8: vec3, max_white_l: f32) -> vec3 let _e58: f32 = numerator1; let _e60: f32 = l_old1; l_new1 = (_e58 / (1.0 + _e60)); - let _e66: vec3 = color9; + let _e66: vec3 = color7; let _e67: f32 = l_new1; let _e68: vec3 = change_luminance(_e66, _e67); return _e68; @@ -489,7 +489,7 @@ fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: F0_1 = F0_; diffuseColor1 = diffuseColor; let _e56: PointLight = light1; - let _e59: vec3 = gen_entry_v_WorldPosition; + let _e59: vec3 = v_WorldPosition1; light_to_frag = (_e56.pos.xyz - _e59.xyz); let _e63: vec3 = light_to_frag; let _e64: vec3 = light_to_frag; @@ -640,21 +640,21 @@ fn dir_light(light2: DirectionalLight, roughness10: f32, NdotV2: f32, normal: ve let _e119: vec3 = diffuse1; let _e121: DirectionalLight = light3; let _e125: f32 = NoL7; - return (((_e118 + _e119) * _e121.color1.xyz) * _e125); + return (((_e118 + _e119) * _e121.color.xyz) * _e125); } -fn main() { +fn main1() { var output_color: vec4; var metallic_roughness: vec4; - var metallic1: f32; - var perceptual_roughness3: f32; + var metallic: f32; + var perceptual_roughness2: f32; var roughness12: f32; var N2: vec3; var T: vec3; var B: vec3; var TBN: mat3x3; var occlusion: f32; - var emissive1: vec4; + var emissive: vec4; var V3: vec3; var NdotV4: f32; var F0_4: vec3; @@ -669,28 +669,28 @@ fn main() { let _e40: vec4 = global3.base_color; output_color = _e40; let _e42: vec4 = output_color; - let _e43: vec2 = gen_entry_v_Uv; + let _e43: vec2 = v_Uv1; let _e44: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e43); output_color = (_e42 * _e44); - let _e46: vec2 = gen_entry_v_Uv; + let _e46: vec2 = v_Uv1; let _e47: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e46); metallic_roughness = _e47; let _e49: f32 = global5.metallic; let _e50: vec4 = metallic_roughness; - metallic1 = (_e49 * _e50.z); + metallic = (_e49 * _e50.z); let _e54: f32 = global4.perceptual_roughness; let _e55: vec4 = metallic_roughness; - perceptual_roughness3 = (_e54 * _e55.y); - let _e60: f32 = perceptual_roughness3; + perceptual_roughness2 = (_e54 * _e55.y); + let _e60: f32 = perceptual_roughness2; let _e61: f32 = perceptualRoughnessToRoughness(_e60); roughness12 = _e61; - let _e63: vec3 = gen_entry_v_WorldNormal; + let _e63: vec3 = v_WorldNormal1; N2 = normalize(_e63); - let _e66: vec4 = gen_entry_v_WorldTangent; + let _e66: vec4 = v_WorldTangent1; T = normalize(_e66.xyz); let _e70: vec3 = N2; let _e71: vec3 = T; - let _e73: vec4 = gen_entry_v_WorldTangent; + let _e73: vec4 = v_WorldTangent1; B = (cross(_e70, _e71) * _e73.w); let _e78: bool = gl_FrontFacing; let _e79: vec3 = N2; @@ -709,36 +709,36 @@ fn main() { let _e95: vec3 = N2; TBN = mat3x3(_e93, _e94, _e95); let _e98: mat3x3 = TBN; - let _e99: vec2 = gen_entry_v_Uv; + let _e99: vec2 = v_Uv1; let _e100: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e99); N2 = (_e98 * normalize(((_e100.xyz * 2.0) - vec3(1.0)))); - let _e109: vec2 = gen_entry_v_Uv; + let _e109: vec2 = v_Uv1; let _e110: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e109); occlusion = _e110.x; let _e113: vec4 = global7.emissive; - emissive1 = _e113; - let _e115: vec4 = emissive1; - let _e117: vec4 = emissive1; - let _e119: vec2 = gen_entry_v_Uv; + emissive = _e113; + let _e115: vec4 = emissive; + let _e117: vec4 = emissive; + let _e119: vec2 = v_Uv1; let _e120: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e119); let _e122: vec3 = (_e117.xyz * _e120.xyz); - emissive1.x = _e122.x; - emissive1.y = _e122.y; - emissive1.z = _e122.z; + emissive.x = _e122.x; + emissive.y = _e122.y; + emissive.z = _e122.z; let _e129: vec4 = global1.CameraPos; - let _e131: vec3 = gen_entry_v_WorldPosition; + let _e131: vec3 = v_WorldPosition1; V3 = normalize((_e129.xyz - _e131.xyz)); let _e136: vec3 = N2; let _e137: vec3 = V3; NdotV4 = max(dot(_e136, _e137), 0.00009999999747378752); let _e143: f32 = global6.reflectance; let _e145: f32 = global6.reflectance; - let _e148: f32 = metallic1; + let _e148: f32 = metallic; let _e152: vec4 = output_color; - let _e154: f32 = metallic1; + let _e154: f32 = metallic; F0_4 = (vec3((((0.1599999964237213 * _e143) * _e145) * (1.0 - _e148))) + (_e152.xyz * vec3(_e154))); let _e159: vec4 = output_color; - let _e162: f32 = metallic1; + let _e162: f32 = metallic; diffuseColor4 = (_e159.xyz * vec3((1.0 - _e162))); let _e167: vec3 = V3; let _e169: vec3 = N2; @@ -802,7 +802,7 @@ fn main() { let _e255: vec3 = EnvBRDFApprox(_e252, 1.0, _e254); diffuse_ambient = _e255; let _e260: vec3 = F0_4; - let _e261: f32 = perceptual_roughness3; + let _e261: f32 = perceptual_roughness2; let _e262: f32 = NdotV4; let _e263: vec3 = EnvBRDFApprox(_e260, _e261, _e262); specular_ambient = _e263; @@ -823,7 +823,7 @@ fn main() { output_color.z = _e286.z; let _e293: vec4 = output_color; let _e295: vec4 = output_color; - let _e297: vec4 = emissive1; + let _e297: vec4 = emissive; let _e299: vec4 = output_color; let _e302: vec3 = (_e295.xyz + (_e297.xyz * _e299.w)); output_color.x = _e302.x; @@ -837,18 +837,18 @@ fn main() { output_color.y = _e315.y; output_color.z = _e315.z; let _e322: vec4 = output_color; - gen_entry_o_Target = _e322; + o_Target = _e322; return; } [[stage(fragment)]] -fn main1([[location(0), interpolate(perspective)]] v_WorldPosition: vec3, [[location(1), interpolate(perspective)]] v_WorldNormal: vec3, [[location(2), interpolate(perspective)]] v_Uv: vec2, [[location(3), interpolate(perspective)]] v_WorldTangent: vec4, [[builtin(front_facing)]] param: bool) -> FragmentOutput { - gen_entry_v_WorldPosition = v_WorldPosition; - gen_entry_v_WorldNormal = v_WorldNormal; - gen_entry_v_Uv = v_Uv; - gen_entry_v_WorldTangent = v_WorldTangent; +fn main([[location(0), interpolate(perspective)]] v_WorldPosition: vec3, [[location(1), interpolate(perspective)]] v_WorldNormal: vec3, [[location(2), interpolate(perspective)]] v_Uv: vec2, [[location(3), interpolate(perspective)]] v_WorldTangent: vec4, [[builtin(front_facing)]] param: bool) -> FragmentOutput { + v_WorldPosition1 = v_WorldPosition; + v_WorldNormal1 = v_WorldNormal; + v_Uv1 = v_Uv; + v_WorldTangent1 = v_WorldTangent; gl_FrontFacing = param; - main(); - let _e11: vec4 = gen_entry_o_Target; + main1(); + let _e11: vec4 = o_Target; return FragmentOutput(_e11); } diff --git a/tests/out/bevy-pbr-vert.wgsl b/tests/out/bevy-pbr-vert.wgsl index 0d1f1d0fd..63001d808 100644 --- a/tests/out/bevy-pbr-vert.wgsl +++ b/tests/out/bevy-pbr-vert.wgsl @@ -9,44 +9,44 @@ struct Transform { }; struct VertexOutput { - [[location(0), interpolate(perspective)]] member: vec3; - [[location(1), interpolate(perspective)]] member1: vec3; - [[location(2), interpolate(perspective)]] member2: vec2; - [[location(3), interpolate(perspective)]] member3: vec4; - [[builtin(position)]] member4: vec4; + [[location(0), interpolate(perspective)]] v_WorldPosition: vec3; + [[location(1), interpolate(perspective)]] v_WorldNormal: vec3; + [[location(2), interpolate(perspective)]] v_Uv: vec2; + [[location(3), interpolate(perspective)]] v_WorldTangent: vec4; + [[builtin(position)]] member: vec4; }; -var gen_entry_Vertex_Position: vec3; -var gen_entry_Vertex_Normal: vec3; -var gen_entry_Vertex_Uv: vec2; -var gen_entry_Vertex_Tangent: vec4; -var gen_entry_v_WorldPosition: vec3; -var gen_entry_v_WorldNormal: vec3; -var gen_entry_v_Uv: vec2; +var Vertex_Position1: vec3; +var Vertex_Normal1: vec3; +var Vertex_Uv1: vec2; +var Vertex_Tangent1: vec4; +var v_WorldPosition: vec3; +var v_WorldNormal: vec3; +var v_Uv: vec2; [[group(0), binding(0)]] var global: CameraViewProj; -var gen_entry_v_WorldTangent: vec4; +var v_WorldTangent: vec4; [[group(2), binding(0)]] var global1: Transform; var gl_Position: vec4; -fn main() { +fn main1() { var world_position: vec4; let _e12: mat4x4 = global1.Model; - let _e13: vec3 = gen_entry_Vertex_Position; + let _e13: vec3 = Vertex_Position1; world_position = (_e12 * vec4(_e13, 1.0)); let _e18: vec4 = world_position; - gen_entry_v_WorldPosition = _e18.xyz; + v_WorldPosition = _e18.xyz; let _e20: mat4x4 = global1.Model; - let _e28: vec3 = gen_entry_Vertex_Normal; - gen_entry_v_WorldNormal = (mat3x3(_e20[0].xyz, _e20[1].xyz, _e20[2].xyz) * _e28); - let _e30: vec2 = gen_entry_Vertex_Uv; - gen_entry_v_Uv = _e30; + let _e28: vec3 = Vertex_Normal1; + v_WorldNormal = (mat3x3(_e20[0].xyz, _e20[1].xyz, _e20[2].xyz) * _e28); + let _e30: vec2 = Vertex_Uv1; + v_Uv = _e30; let _e31: mat4x4 = global1.Model; - let _e39: vec4 = gen_entry_Vertex_Tangent; - let _e42: vec4 = gen_entry_Vertex_Tangent; - gen_entry_v_WorldTangent = vec4((mat3x3(_e31[0].xyz, _e31[1].xyz, _e31[2].xyz) * _e39.xyz), _e42.w); + let _e39: vec4 = Vertex_Tangent1; + let _e42: vec4 = Vertex_Tangent1; + v_WorldTangent = vec4((mat3x3(_e31[0].xyz, _e31[1].xyz, _e31[2].xyz) * _e39.xyz), _e42.w); let _e46: mat4x4 = global.ViewProj; let _e47: vec4 = world_position; gl_Position = (_e46 * _e47); @@ -54,16 +54,16 @@ fn main() { } [[stage(vertex)]] -fn main1([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(1), interpolate(perspective)]] Vertex_Normal: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2, [[location(3), interpolate(perspective)]] Vertex_Tangent: vec4) -> VertexOutput { - gen_entry_Vertex_Position = Vertex_Position; - gen_entry_Vertex_Normal = Vertex_Normal; - gen_entry_Vertex_Uv = Vertex_Uv; - gen_entry_Vertex_Tangent = Vertex_Tangent; - main(); - let _e9: vec3 = gen_entry_v_WorldPosition; - let _e11: vec3 = gen_entry_v_WorldNormal; - let _e13: vec2 = gen_entry_v_Uv; - let _e15: vec4 = gen_entry_v_WorldTangent; +fn main([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(1), interpolate(perspective)]] Vertex_Normal: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2, [[location(3), interpolate(perspective)]] Vertex_Tangent: vec4) -> VertexOutput { + Vertex_Position1 = Vertex_Position; + Vertex_Normal1 = Vertex_Normal; + Vertex_Uv1 = Vertex_Uv; + Vertex_Tangent1 = Vertex_Tangent; + main1(); + let _e9: vec3 = v_WorldPosition; + let _e11: vec3 = v_WorldNormal; + let _e13: vec2 = v_Uv; + let _e15: vec4 = v_WorldTangent; let _e17: vec4 = gl_Position; return VertexOutput(_e9, _e11, _e13, _e15, _e17); } diff --git a/tests/out/boids.Compute.glsl b/tests/out/boids.Compute.glsl index 1d3b29184..2996c3435 100644 --- a/tests/out/boids.Compute.glsl +++ b/tests/out/boids.Compute.glsl @@ -37,8 +37,8 @@ void main() { vec2 colVel; int cMassCount = 0; int cVelCount = 0; - vec2 pos1; - vec2 vel1; + vec2 pos; + vec2 vel; uint i = 0u; uint index = global_invocation_id.x; if ((index >= 1500u)) { @@ -62,35 +62,35 @@ void main() { } uint _expr42 = i; vec2 _expr45 = _group_0_binding_1.particles[_expr42].pos; - pos1 = _expr45; + pos = _expr45; uint _expr47 = i; vec2 _expr50 = _group_0_binding_1.particles[_expr47].vel; - vel1 = _expr50; - vec2 _expr51 = pos1; + vel = _expr50; + vec2 _expr51 = pos; vec2 _expr52 = vPos; float _expr55 = _group_0_binding_0.rule1Distance; if ((distance(_expr51, _expr52) < _expr55)) { vec2 _expr57 = cMass; - vec2 _expr58 = pos1; + vec2 _expr58 = pos; cMass = (_expr57 + _expr58); int _expr60 = cMassCount; cMassCount = (_expr60 + 1); } - vec2 _expr63 = pos1; + vec2 _expr63 = pos; vec2 _expr64 = vPos; float _expr67 = _group_0_binding_0.rule2Distance; if ((distance(_expr63, _expr64) < _expr67)) { vec2 _expr69 = colVel; - vec2 _expr70 = pos1; + vec2 _expr70 = pos; vec2 _expr71 = vPos; colVel = (_expr69 - (_expr70 - _expr71)); } - vec2 _expr74 = pos1; + vec2 _expr74 = pos; vec2 _expr75 = vPos; float _expr78 = _group_0_binding_0.rule3Distance; if ((distance(_expr74, _expr75) < _expr78)) { vec2 _expr80 = cVel; - vec2 _expr81 = vel1; + vec2 _expr81 = vel; cVel = (_expr80 + _expr81); int _expr83 = cVelCount; cVelCount = (_expr83 + 1); diff --git a/tests/out/boids.msl b/tests/out/boids.msl index 693d58d87..e51ac6309 100644 --- a/tests/out/boids.msl +++ b/tests/out/boids.msl @@ -41,8 +41,8 @@ kernel void main1( metal::float2 colVel; int cMassCount = 0; int cVelCount = 0; - metal::float2 pos1; - metal::float2 vel1; + metal::float2 pos; + metal::float2 vel; metal::uint i = 0u; uint index = global_invocation_id.x; if (index >= NUM_PARTICLES) { @@ -72,35 +72,35 @@ kernel void main1( } metal::uint _e42 = i; metal::float2 _e45 = particlesSrc.particles[_e42].pos; - pos1 = _e45; + pos = _e45; metal::uint _e47 = i; metal::float2 _e50 = particlesSrc.particles[_e47].vel; - vel1 = _e50; - metal::float2 _e51 = pos1; + vel = _e50; + metal::float2 _e51 = pos; metal::float2 _e52 = vPos; float _e55 = params.rule1Distance; if (metal::distance(_e51, _e52) < _e55) { metal::float2 _e57 = cMass; - metal::float2 _e58 = pos1; + metal::float2 _e58 = pos; cMass = _e57 + _e58; int _e60 = cMassCount; cMassCount = _e60 + 1; } - metal::float2 _e63 = pos1; + metal::float2 _e63 = pos; metal::float2 _e64 = vPos; float _e67 = params.rule2Distance; if (metal::distance(_e63, _e64) < _e67) { metal::float2 _e69 = colVel; - metal::float2 _e70 = pos1; + metal::float2 _e70 = pos; metal::float2 _e71 = vPos; colVel = _e69 - (_e70 - _e71); } - metal::float2 _e74 = pos1; + metal::float2 _e74 = pos; metal::float2 _e75 = vPos; float _e78 = params.rule3Distance; if (metal::distance(_e74, _e75) < _e78) { metal::float2 _e80 = cVel; - metal::float2 _e81 = vel1; + metal::float2 _e81 = vel; cVel = _e80 + _e81; int _e83 = cVelCount; cVelCount = _e83 + 1; diff --git a/tests/out/boids.wgsl b/tests/out/boids.wgsl index e0d326599..81aba559c 100644 --- a/tests/out/boids.wgsl +++ b/tests/out/boids.wgsl @@ -37,8 +37,8 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { var colVel: vec2; var cMassCount: i32 = 0; var cVelCount: i32 = 0; - var pos1: vec2; - var vel1: vec2; + var pos: vec2; + var vel: vec2; var i: u32 = 0u; let index: u32 = global_invocation_id.x; @@ -63,35 +63,35 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { } let _e42: u32 = i; let _e45: vec2 = particlesSrc.particles[_e42].pos; - pos1 = _e45; + pos = _e45; let _e47: u32 = i; let _e50: vec2 = particlesSrc.particles[_e47].vel; - vel1 = _e50; - let _e51: vec2 = pos1; + vel = _e50; + let _e51: vec2 = pos; let _e52: vec2 = vPos; let _e55: f32 = params.rule1Distance; if ((distance(_e51, _e52) < _e55)) { let _e57: vec2 = cMass; - let _e58: vec2 = pos1; + let _e58: vec2 = pos; cMass = (_e57 + _e58); let _e60: i32 = cMassCount; cMassCount = (_e60 + 1); } - let _e63: vec2 = pos1; + let _e63: vec2 = pos; let _e64: vec2 = vPos; let _e67: f32 = params.rule2Distance; if ((distance(_e63, _e64) < _e67)) { let _e69: vec2 = colVel; - let _e70: vec2 = pos1; + let _e70: vec2 = pos; let _e71: vec2 = vPos; colVel = (_e69 - (_e70 - _e71)); } - let _e74: vec2 = pos1; + let _e74: vec2 = pos; let _e75: vec2 = vPos; let _e78: f32 = params.rule3Distance; if ((distance(_e74, _e75) < _e78)) { let _e80: vec2 = cVel; - let _e81: vec2 = vel1; + let _e81: vec2 = vel; cVel = (_e80 + _e81); let _e83: i32 = cVelCount; cVelCount = (_e83 + 1); diff --git a/tests/out/interface.msl b/tests/out/interface.msl index bd002be08..67ef0290d 100644 --- a/tests/out/interface.msl +++ b/tests/out/interface.msl @@ -12,7 +12,7 @@ struct FragmentOutput { }; struct vertex1Input { - metal::uint color1 [[attribute(10)]]; + metal::uint color [[attribute(10)]]; }; struct vertex1Output { metal::float4 position [[position]]; @@ -23,8 +23,8 @@ vertex vertex1Output vertex1( , metal::uint vertex_index [[vertex_id]] , metal::uint instance_index [[instance_id]] ) { - const auto color1 = varyings.color1; - metal::uint tmp = (vertex_index + instance_index) + color1; + const auto color = varyings.color; + metal::uint tmp = (vertex_index + instance_index) + color; const auto _tmp = VertexOutput {metal::float4(1.0), static_cast(tmp)}; return vertex1Output { _tmp.position, _tmp.varying }; } @@ -43,12 +43,12 @@ fragment fragment1Output fragment1( , metal::float4 position [[position]] , bool front_facing [[front_facing]] , metal::uint sample_index [[sample_id]] -, metal::uint sample_mask1 [[sample_mask]] +, metal::uint sample_mask [[sample_mask]] ) { const VertexOutput in = { position, varyings1.varying }; - metal::uint mask = sample_mask1 & (1u << sample_index); - float color2 = front_facing ? 0.0 : 1.0; - const auto _tmp = FragmentOutput {in.varying, mask, color2}; + metal::uint mask = sample_mask & (1u << sample_index); + float color1 = front_facing ? 0.0 : 1.0; + const auto _tmp = FragmentOutput {in.varying, mask, color1}; return fragment1Output { _tmp.depth, _tmp.sample_mask, _tmp.color }; } diff --git a/tests/out/interface.wgsl b/tests/out/interface.wgsl index 74dbe30be..e574da5c9 100644 --- a/tests/out/interface.wgsl +++ b/tests/out/interface.wgsl @@ -10,16 +10,16 @@ struct FragmentOutput { }; [[stage(vertex)]] -fn vertex([[builtin(vertex_index)]] vertex_index: u32, [[builtin(instance_index)]] instance_index: u32, [[location(10)]] color1: u32) -> VertexOutput { - let tmp: u32 = ((vertex_index + instance_index) + color1); +fn vertex([[builtin(vertex_index)]] vertex_index: u32, [[builtin(instance_index)]] instance_index: u32, [[location(10)]] color: u32) -> VertexOutput { + let tmp: u32 = ((vertex_index + instance_index) + color); return VertexOutput(vec4(1.0), f32(tmp)); } [[stage(fragment)]] -fn fragment(in: VertexOutput, [[builtin(front_facing)]] front_facing: bool, [[builtin(sample_index)]] sample_index: u32, [[builtin(sample_mask)]] sample_mask1: u32) -> FragmentOutput { - let mask: u32 = (sample_mask1 & (1u << sample_index)); - let color2: f32 = select(0.0, 1.0, front_facing); - return FragmentOutput(in.varying, mask, color2); +fn fragment(in: VertexOutput, [[builtin(front_facing)]] front_facing: bool, [[builtin(sample_index)]] sample_index: u32, [[builtin(sample_mask)]] sample_mask: u32) -> FragmentOutput { + let mask: u32 = (sample_mask & (1u << sample_index)); + let color1: f32 = select(0.0, 1.0, front_facing); + return FragmentOutput(in.varying, mask, color1); } [[stage(compute), workgroup_size(1, 1, 1)]] diff --git a/tests/out/math-functions-vert.wgsl b/tests/out/math-functions-vert.wgsl index 8cb0af35e..6042118a8 100644 --- a/tests/out/math-functions-vert.wgsl +++ b/tests/out/math-functions-vert.wgsl @@ -1,4 +1,4 @@ -fn main() { +fn main1() { var a: vec4 = vec4(1.0, 1.0, 1.0, 1.0); var b: vec4 = vec4(2.0, 2.0, 2.0, 2.0); var m: mat4x4; @@ -141,7 +141,7 @@ fn main() { } [[stage(vertex)]] -fn main1() { - main(); +fn main() { + main1(); return; } diff --git a/tests/out/quad-glsl.wgsl b/tests/out/quad-glsl.wgsl index f03522c39..c43c872cb 100644 --- a/tests/out/quad-glsl.wgsl +++ b/tests/out/quad-glsl.wgsl @@ -1,45 +1,45 @@ struct VertexOutput { - [[location(0), interpolate(perspective)]] member: vec2; - [[builtin(position)]] member1: vec4; + [[location(0), interpolate(perspective)]] v_uv: vec2; + [[builtin(position)]] member: vec4; }; struct FragmentOutput { - [[location(0), interpolate(perspective)]] member2: vec4; + [[location(0), interpolate(perspective)]] o_color: vec4; }; -var gen_entry_a_pos: vec2; -var gen_entry_a_uv: vec2; -var gen_entry_v_uv: vec2; +var a_pos1: vec2; +var a_uv1: vec2; +var v_uv: vec2; var gl_Position: vec4; -var gen_entry_v_uv1: vec2; -var gen_entry_o_color: vec4; +var v_uv1: vec2; +var o_color: vec4; -fn vert_main() { - let _e4: vec2 = gen_entry_a_uv; - gen_entry_v_uv = _e4; - let _e6: vec2 = gen_entry_a_pos; +fn vert_main1() { + let _e4: vec2 = a_uv1; + v_uv = _e4; + let _e6: vec2 = a_pos1; gl_Position = vec4((1.2000000476837158 * _e6), 0.0, 1.0); return; } -fn frag_main() { - gen_entry_o_color = vec4(1.0, 1.0, 1.0, 1.0); +fn frag_main1() { + o_color = vec4(1.0, 1.0, 1.0, 1.0); return; } [[stage(vertex)]] -fn vert_main1([[location(0), interpolate(perspective)]] a_pos: vec2, [[location(1), interpolate(perspective)]] a_uv: vec2) -> VertexOutput { - gen_entry_a_pos = a_pos; - gen_entry_a_uv = a_uv; - vert_main(); - let _e5: vec2 = gen_entry_v_uv; +fn vert_main([[location(0), interpolate(perspective)]] a_pos: vec2, [[location(1), interpolate(perspective)]] a_uv: vec2) -> VertexOutput { + a_pos1 = a_pos; + a_uv1 = a_uv; + vert_main1(); + let _e5: vec2 = v_uv; let _e7: vec4 = gl_Position; return VertexOutput(_e5, _e7); } [[stage(fragment)]] -fn frag_main1() -> FragmentOutput { - frag_main(); - let _e1: vec4 = gen_entry_o_color; +fn frag_main() -> FragmentOutput { + frag_main1(); + let _e1: vec4 = o_color; return FragmentOutput(_e1); } diff --git a/tests/out/quad-vert.Vertex.glsl b/tests/out/quad-vert.Vertex.glsl index e6cbc6c86..94094f6ce 100644 --- a/tests/out/quad-vert.Vertex.glsl +++ b/tests/out/quad-vert.Vertex.glsl @@ -4,15 +4,15 @@ precision highp float; struct type10 { vec2 member; - vec4 gen_gl_Position1; - float gen_gl_PointSize1; - float gen_gl_ClipDistance1[1]; - float gen_gl_CullDistance1[1]; + vec4 gen_gl_Position; + float gen_gl_PointSize; + float gen_gl_ClipDistance[1]; + float gen_gl_CullDistance[1]; }; vec2 v_uv = vec2(0, 0); -vec2 a_uv = vec2(0, 0); +vec2 a_uv1 = vec2(0, 0); struct gen_gl_PerVertex_block_0 { vec4 gen_gl_Position; @@ -21,26 +21,26 @@ struct gen_gl_PerVertex_block_0 { float gen_gl_CullDistance[1]; } perVertexStruct; -vec2 a_pos = vec2(0, 0); +vec2 a_pos1 = vec2(0, 0); layout(location = 1) in vec2 _p2vs_location1; layout(location = 0) in vec2 _p2vs_location0; smooth out vec2 _vs2fs_location0; -void main1() { - vec2 _expr12 = a_uv; +void main2() { + vec2 _expr12 = a_uv1; v_uv = _expr12; - vec2 _expr13 = a_pos; + vec2 _expr13 = a_pos1; perVertexStruct.gen_gl_Position = vec4(_expr13.x, _expr13.y, 0.0, 1.0); return; } void main() { - vec2 a_uv1 = _p2vs_location1; - vec2 a_pos1 = _p2vs_location0; - a_uv = a_uv1; - a_pos = a_pos1; - main1(); + vec2 a_uv = _p2vs_location1; + vec2 a_pos = _p2vs_location0; + a_uv1 = a_uv; + a_pos1 = a_pos; + main2(); vec2 _expr10 = v_uv; vec4 _expr11 = perVertexStruct.gen_gl_Position; float _expr12 = perVertexStruct.gen_gl_PointSize; @@ -48,7 +48,7 @@ void main() { float _expr14[] = perVertexStruct.gen_gl_CullDistance; type10 _tmp_return = type10(_expr10, _expr11, _expr12, _expr13, _expr14); _vs2fs_location0 = _tmp_return.member; - gl_Position = _tmp_return.gen_gl_Position1; + gl_Position = _tmp_return.gen_gl_Position; return; } diff --git a/tests/out/quad-vert.msl b/tests/out/quad-vert.msl index d7195a141..6a3039ed2 100644 --- a/tests/out/quad-vert.msl +++ b/tests/out/quad-vert.msl @@ -12,55 +12,55 @@ struct gl_PerVertex { }; struct type10 { metal::float2 member; - metal::float4 gl_Position1; - float gl_PointSize1; - type6 gl_ClipDistance1; - type6 gl_CullDistance1; + metal::float4 gl_Position; + float gl_PointSize; + type6 gl_ClipDistance; + type6 gl_CullDistance; }; constant metal::float4 const_type4_ = {0.0, 0.0, 0.0, 1.0}; constant type6 const_type6_ = {0.0}; constant gl_PerVertex const_gl_PerVertex = {const_type4_, 1.0, const_type6_, const_type6_}; -void main1( +void main2( thread metal::float2& v_uv, - thread metal::float2 const& a_uv, + thread metal::float2 const& a_uv1, thread gl_PerVertex& perVertexStruct, - thread metal::float2 const& a_pos + thread metal::float2 const& a_pos1 ) { - metal::float2 _e12 = a_uv; + metal::float2 _e12 = a_uv1; v_uv = _e12; - metal::float2 _e13 = a_pos; + metal::float2 _e13 = a_pos1; perVertexStruct.gl_Position = metal::float4(_e13.x, _e13.y, 0.0, 1.0); return; } -struct main2Input { - metal::float2 a_uv1 [[attribute(1)]]; - metal::float2 a_pos1 [[attribute(0)]]; +struct main1Input { + metal::float2 a_uv [[attribute(1)]]; + metal::float2 a_pos [[attribute(0)]]; }; -struct main2Output { +struct main1Output { metal::float2 member [[user(loc0), center_perspective]]; - metal::float4 gl_Position1 [[position]]; - float gl_PointSize1 [[point_size]]; - float gl_ClipDistance1 [[clip_distance]] [1]; + metal::float4 gl_Position [[position]]; + float gl_PointSize [[point_size]]; + float gl_ClipDistance [[clip_distance]] [1]; }; -vertex main2Output main2( - main2Input varyings [[stage_in]] +vertex main1Output main1( + main1Input varyings [[stage_in]] ) { metal::float2 v_uv = {}; - metal::float2 a_uv = {}; + metal::float2 a_uv1 = {}; gl_PerVertex perVertexStruct = const_gl_PerVertex; - metal::float2 a_pos = {}; - const auto a_uv1 = varyings.a_uv1; - const auto a_pos1 = varyings.a_pos1; - a_uv = a_uv1; - a_pos = a_pos1; - main1(v_uv, a_uv, perVertexStruct, a_pos); + metal::float2 a_pos1 = {}; + const auto a_uv = varyings.a_uv; + const auto a_pos = varyings.a_pos; + a_uv1 = a_uv; + a_pos1 = a_pos; + main2(v_uv, a_uv1, perVertexStruct, a_pos1); metal::float2 _e10 = v_uv; metal::float4 _e11 = perVertexStruct.gl_Position; float _e12 = perVertexStruct.gl_PointSize; type6 _e13 = perVertexStruct.gl_ClipDistance; type6 _e14 = perVertexStruct.gl_CullDistance; const auto _tmp = type10 {_e10, _e11, _e12, _e13, _e14}; - return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1.inner[0]} }; + return main1Output { _tmp.member, _tmp.gl_Position, _tmp.gl_PointSize, {_tmp.gl_ClipDistance.inner[0]} }; } diff --git a/tests/out/quad-vert.wgsl b/tests/out/quad-vert.wgsl index 92fab9dad..683007815 100644 --- a/tests/out/quad-vert.wgsl +++ b/tests/out/quad-vert.wgsl @@ -5,27 +5,27 @@ struct gl_PerVertex { struct VertexOutput { [[location(0), interpolate(perspective)]] member: vec2; - [[builtin(position)]] gl_Position1: vec4; + [[builtin(position)]] gl_Position: vec4; }; var v_uv: vec2; -var a_uv: vec2; +var a_uv1: vec2; var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), ); -var a_pos: vec2; +var a_pos1: vec2; -fn main() { - let _e12: vec2 = a_uv; +fn main1() { + let _e12: vec2 = a_uv1; v_uv = _e12; - let _e13: vec2 = a_pos; + let _e13: vec2 = a_pos1; perVertexStruct.gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); return; } [[stage(vertex)]] -fn main1([[location(1)]] a_uv1: vec2, [[location(0)]] a_pos1: vec2) -> VertexOutput { - a_uv = a_uv1; - a_pos = a_pos1; - main(); +fn main([[location(1)]] a_uv: vec2, [[location(0)]] a_pos: vec2) -> VertexOutput { + a_uv1 = a_uv; + a_pos1 = a_pos; + main1(); let _e10: vec2 = v_uv; let _e11: vec4 = perVertexStruct.gl_Position; return VertexOutput(_e10, _e11); diff --git a/tests/out/quad.Fragment.glsl b/tests/out/quad.Fragment.glsl index ccb1198be..4ad470b3e 100644 --- a/tests/out/quad.Fragment.glsl +++ b/tests/out/quad.Fragment.glsl @@ -13,8 +13,8 @@ smooth in vec2 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { - vec2 uv2 = _vs2fs_location0; - vec4 color = texture(_group_0_binding_0, vec2(uv2)); + vec2 uv1 = _vs2fs_location0; + vec4 color = texture(_group_0_binding_0, vec2(uv1)); if ((color.w == 0.0)) { discard; } diff --git a/tests/out/quad.Vertex.glsl b/tests/out/quad.Vertex.glsl index 873bbf39b..873d01103 100644 --- a/tests/out/quad.Vertex.glsl +++ b/tests/out/quad.Vertex.glsl @@ -13,8 +13,8 @@ smooth out vec2 _vs2fs_location0; void main() { vec2 pos = _p2vs_location0; - vec2 uv1 = _p2vs_location1; - VertexOutput _tmp_return = VertexOutput(uv1, vec4((1.2 * pos), 0.0, 1.0)); + vec2 uv = _p2vs_location1; + VertexOutput _tmp_return = VertexOutput(uv, vec4((1.2 * pos), 0.0, 1.0)); _vs2fs_location0 = _tmp_return.uv; gl_Position = _tmp_return.position; return; diff --git a/tests/out/quad.hlsl b/tests/out/quad.hlsl index c9685d234..81f661fc7 100644 --- a/tests/out/quad.hlsl +++ b/tests/out/quad.hlsl @@ -10,22 +10,22 @@ struct VertexOutput { struct VertexInput { float2 pos1 : LOC0; - float2 uv3 : LOC1; + float2 uv2 : LOC1; }; struct FragmentInput { - float2 uv4 : LOC0; + float2 uv3 : LOC0; }; VertexOutput vert_main(VertexInput vertexinput) { - const VertexOutput vertexoutput1 = { vertexinput.uv3, float4((c_scale * vertexinput.pos1), 0.0, 1.0) }; + const VertexOutput vertexoutput1 = { vertexinput.uv2, float4((c_scale * vertexinput.pos1), 0.0, 1.0) }; return vertexoutput1; } float4 frag_main(FragmentInput fragmentinput) : SV_Target0 { - float4 color = u_texture.Sample(u_sampler, fragmentinput.uv4); + float4 color = u_texture.Sample(u_sampler, fragmentinput.uv3); if ((color.w == 0.0)) { discard; } diff --git a/tests/out/quad.msl b/tests/out/quad.msl index 53a5cb541..af6e515f9 100644 --- a/tests/out/quad.msl +++ b/tests/out/quad.msl @@ -9,7 +9,7 @@ struct VertexOutput { struct main1Input { metal::float2 pos [[attribute(0)]]; - metal::float2 uv1 [[attribute(1)]]; + metal::float2 uv [[attribute(1)]]; }; struct main1Output { metal::float2 uv [[user(loc0), center_perspective]]; @@ -19,14 +19,14 @@ vertex main1Output main1( main1Input varyings [[stage_in]] ) { const auto pos = varyings.pos; - const auto uv1 = varyings.uv1; - const auto _tmp = VertexOutput {uv1, metal::float4(c_scale * pos, 0.0, 1.0)}; + const auto uv = varyings.uv; + const auto _tmp = VertexOutput {uv, metal::float4(c_scale * pos, 0.0, 1.0)}; return main1Output { _tmp.uv, _tmp.position }; } struct main2Input { - metal::float2 uv2 [[user(loc0), center_perspective]]; + metal::float2 uv1 [[user(loc0), center_perspective]]; }; struct main2Output { metal::float4 member1 [[color(0)]]; @@ -36,8 +36,8 @@ fragment main2Output main2( , metal::texture2d u_texture [[user(fake0)]] , metal::sampler u_sampler [[user(fake0)]] ) { - const auto uv2 = varyings1.uv2; - metal::float4 color = u_texture.sample(u_sampler, uv2); + const auto uv1 = varyings1.uv1; + metal::float4 color = u_texture.sample(u_sampler, uv1); if (color.w == 0.0) { metal::discard_fragment(); } diff --git a/tests/out/quad.wgsl b/tests/out/quad.wgsl index 63d94b5a3..e6890b1d8 100644 --- a/tests/out/quad.wgsl +++ b/tests/out/quad.wgsl @@ -11,13 +11,13 @@ var u_texture: texture_2d; var u_sampler: sampler; [[stage(vertex)]] -fn main([[location(0)]] pos: vec2, [[location(1)]] uv1: vec2) -> VertexOutput { - return VertexOutput(uv1, vec4((c_scale * pos), 0.0, 1.0)); +fn main([[location(0)]] pos: vec2, [[location(1)]] uv: vec2) -> VertexOutput { + return VertexOutput(uv, vec4((c_scale * pos), 0.0, 1.0)); } [[stage(fragment)]] -fn main1([[location(0), interpolate(perspective)]] uv2: vec2) -> [[location(0)]] vec4 { - let color: vec4 = textureSample(u_texture, u_sampler, uv2); +fn main1([[location(0), interpolate(perspective)]] uv1: vec2) -> [[location(0)]] vec4 { + let color: vec4 = textureSample(u_texture, u_sampler, uv1); if ((color.w == 0.0)) { discard; } diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/shadow.Fragment.glsl index 23e04ef01..b49523b98 100644 --- a/tests/out/shadow.Fragment.glsl +++ b/tests/out/shadow.Fragment.glsl @@ -35,7 +35,7 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { void main() { vec3 raw_normal = _vs2fs_location0; vec4 position = _vs2fs_location1; - vec3 color1 = vec3(0.05, 0.05, 0.05); + vec3 color = vec3(0.05, 0.05, 0.05); uint i = 0u; vec3 normal = normalize(raw_normal); while(true) { @@ -50,12 +50,12 @@ void main() { float _expr25 = fetch_shadow(_expr22, (light.proj * position)); vec3 light_dir = normalize((light.pos.xyz - position.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); - vec3 _expr34 = color1; - color1 = (_expr34 + ((_expr25 * diffuse) * light.color.xyz)); + vec3 _expr34 = color; + color = (_expr34 + ((_expr25 * diffuse) * light.color.xyz)); uint _expr40 = i; i = (_expr40 + 1u); } - vec3 _expr43 = color1; + vec3 _expr43 = color; _fs2p_location0 = vec4(_expr43, 1.0); return; } diff --git a/tests/out/shadow.msl b/tests/out/shadow.msl index fc22233b7..30c4754a7 100644 --- a/tests/out/shadow.msl +++ b/tests/out/shadow.msl @@ -51,7 +51,7 @@ fragment fs_mainOutput fs_main( ) { const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; - metal::float3 color1 = c_ambient; + metal::float3 color = c_ambient; metal::uint i = 0u; metal::float3 normal = metal::normalize(raw_normal); bool loop_init = true; @@ -72,9 +72,9 @@ fragment fs_mainOutput fs_main( float _e25 = fetch_shadow(_e22, light.proj * position, t_shadow, sampler_shadow); metal::float3 light_dir = metal::normalize(light.pos.xyz - position.xyz); float diffuse = metal::max(0.0, metal::dot(normal, light_dir)); - metal::float3 _e34 = color1; - color1 = _e34 + ((_e25 * diffuse) * light.color.xyz); + metal::float3 _e34 = color; + color = _e34 + ((_e25 * diffuse) * light.color.xyz); } - metal::float3 _e43 = color1; + metal::float3 _e43 = color; return fs_mainOutput { metal::float4(_e43, 1.0) }; } diff --git a/tests/out/shadow.wgsl b/tests/out/shadow.wgsl index ef9ba9c37..26993e5e2 100644 --- a/tests/out/shadow.wgsl +++ b/tests/out/shadow.wgsl @@ -38,7 +38,7 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { [[stage(fragment)]] fn fs_main([[location(0), interpolate(perspective)]] raw_normal: vec3, [[location(1), interpolate(perspective)]] position: vec4) -> [[location(0)]] vec4 { - var color1: vec3 = vec3(0.05, 0.05, 0.05); + var color: vec3 = vec3(0.05, 0.05, 0.05); var i: u32 = 0u; let normal: vec3 = normalize(raw_normal); @@ -54,13 +54,13 @@ fn fs_main([[location(0), interpolate(perspective)]] raw_normal: vec3, [[lo let _e25: f32 = fetch_shadow(_e22, (light.proj * position)); let light_dir: vec3 = normalize((light.pos.xyz - position.xyz)); let diffuse: f32 = max(0.0, dot(normal, light_dir)); - let _e34: vec3 = color1; - color1 = (_e34 + ((_e25 * diffuse) * light.color.xyz)); + let _e34: vec3 = color; + color = (_e34 + ((_e25 * diffuse) * light.color.xyz)); continuing { let _e40: u32 = i; i = (_e40 + 1u); } } - let _e43: vec3 = color1; + let _e43: vec3 = color; return vec4(_e43, 1.0); } diff --git a/tests/out/swizzle_write-frag.wgsl b/tests/out/swizzle_write-frag.wgsl index 082c1c642..63c0696f8 100644 --- a/tests/out/swizzle_write-frag.wgsl +++ b/tests/out/swizzle_write-frag.wgsl @@ -1,4 +1,4 @@ -fn main() { +fn main1() { var x: vec3 = vec3(2.0, 2.0, 2.0); let _e3: vec3 = x; @@ -14,7 +14,7 @@ fn main() { } [[stage(fragment)]] -fn main1() { - main(); +fn main() { + main1(); return; } From 5242d4f5a9e2de0ac317bdd0ec83be94c460fedc Mon Sep 17 00:00:00 2001 From: Frizi Date: Fri, 18 Jun 2021 19:30:47 +0200 Subject: [PATCH 0988/2212] avoid hashmap allocation when entering namer namespace --- src/proc/namer.rs | 62 +++++++++++++++++++++++++++-------------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 2936a9ae5..b8f03b25c 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -1,4 +1,4 @@ -use crate::{arena::Handle, FastHashMap}; +use crate::{arena::Handle, FastHashMap, FastHashSet}; use std::collections::hash_map::Entry; pub type EntryPointIndex = u16; @@ -21,7 +21,10 @@ pub enum NameKey { /// that may need identifiers in a textual backend. #[derive(Default)] pub struct Namer { - unique: FastHashMap, + unique: FastHashMap<(String, u32), u32>, + keywords: FastHashSet, + /// Currently active namespace. + namespace_index: u32, reserved_prefixes: Vec, } @@ -52,29 +55,42 @@ impl Namer { /// This function should be used **after** [`Namer`](crate::proc::Namer) initialization by [`reset`](Self::reset()) function. pub fn call_unique(&mut self, string: &str) -> String { let base = self.sanitize(string); - match self.unique.entry(base) { + match self.unique.entry((base, self.namespace_index)) { Entry::Occupied(mut e) => { *e.get_mut() += 1; - format!("{}{}", e.key(), e.get()) + format!("{}{}", e.key().0, e.get()) } Entry::Vacant(e) => { - let name = e.key().to_string(); - name + let name = &e.key().0; + if self.keywords.contains(&e.key().0) { + let name = format!("{}1", name); + e.insert(1); + name + } else { + name.to_string() + } } } } pub fn call(&mut self, label_raw: &str) -> String { let base = self.sanitize(label_raw); - match self.unique.entry(base) { + match self.unique.entry((base, self.namespace_index)) { Entry::Occupied(mut e) => { *e.get_mut() += 1; - format!("{}{}", e.key(), e.get()) + format!("{}{}", e.key().0, e.get()) } Entry::Vacant(e) => { - let name = e.key().to_string(); - e.insert(0); - name + let name = &e.key().0; + if self.keywords.contains(&e.key().0) { + let name = format!("{}1", name); + e.insert(1); + name + } else { + let name = name.to_string(); + e.insert(0); + name + } } } } @@ -86,16 +102,12 @@ impl Namer { }) } - fn namespace(&mut self, reserved_keywords: &[&str], f: impl FnOnce(&mut Self)) { - let parent_unique = std::mem::take(&mut self.unique); - self.unique.extend( - reserved_keywords - .iter() - .map(|string| (string.to_string(), 0)), - ); - + fn namespace(&mut self, f: impl FnOnce(&mut Self)) { + self.namespace_index += 1; f(self); - self.unique = parent_unique; + let current_ns = self.namespace_index; + self.unique.retain(|&(_, ns), _| ns != current_ns); + self.namespace_index -= 1; } pub fn reset( @@ -110,11 +122,9 @@ impl Namer { .extend(reserved_prefixes.iter().map(|string| string.to_string())); self.unique.clear(); - self.unique.extend( - reserved_keywords - .iter() - .map(|string| (string.to_string(), 0)), - ); + self.keywords.clear(); + self.keywords + .extend(reserved_keywords.iter().map(|string| (string.to_string()))); let mut temp = String::new(); for (ty_handle, ty) in module.types.iter() { @@ -123,7 +133,7 @@ impl Namer { if let crate::TypeInner::Struct { ref members, .. } = ty.inner { // struct members have their own namespace, because access is always prefixed - self.namespace(reserved_keywords, |namer| { + self.namespace(|namer| { for (index, member) in members.iter().enumerate() { let name = namer.call_or(&member.name, "member"); output.insert(NameKey::StructMember(ty_handle, index as u32), name); From 46be75fb379f07e19b1733b28bb8f95e75d71083 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Fri, 18 Jun 2021 00:41:13 +0300 Subject: [PATCH 0989/2212] [hlsl-out] Implement all parts required by quad-spv snaphost test --- src/back/hlsl/writer.rs | 202 +++++++++++++++++++++++++------- tests/out/quad-vert.hlsl | 47 ++++++++ tests/out/quad-vert.hlsl.config | 2 + tests/out/quad.hlsl | 6 +- tests/snapshots.rs | 2 +- 5 files changed, 211 insertions(+), 48 deletions(-) create mode 100644 tests/out/quad-vert.hlsl create mode 100644 tests/out/quad-vert.hlsl.config diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 019260339..9dc899277 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -5,7 +5,7 @@ use crate::{ back::{hlsl::keywords::RESERVED, vector_size_str}, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, - Arena, BuiltIn, Bytes, Constant, ConstantInner, Expression, FastHashMap, Function, + Arena, ArraySize, BuiltIn, Bytes, Constant, ConstantInner, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageDimension, LocalVariable, Module, ScalarKind, ScalarValue, ShaderStage, Statement, StructMember, Type, TypeInner, }; @@ -14,6 +14,7 @@ use std::fmt::Write; const INDENT: &str = " "; const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; const LOCATION_SEMANTIC: &str = "LOC"; +const BAKE_PREFIX: &str = "_e"; /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; @@ -119,16 +120,6 @@ impl<'a, W: Write> Writer<'a, W> { } } - // Write all globals - for (ty, _) in module.global_variables.iter() { - self.write_global(module, ty)?; - } - - if !module.global_variables.is_empty() { - // Add extra newline for readability - writeln!(self.out)?; - } - // Write all structs for (handle, ty) in module.types.iter() { if let TypeInner::Struct { @@ -142,6 +133,16 @@ impl<'a, W: Write> Writer<'a, W> { } } + // Write all globals + for (ty, _) in module.global_variables.iter() { + self.write_global(module, ty)?; + } + + if !module.global_variables.is_empty() { + // Add extra newline for readability + writeln!(self.out)?; + } + // Write all entry points wrapped structs for (index, ep) in module.entry_points.iter().enumerate() { self.write_ep_input_struct(module, &ep.function, ep.stage, index)?; @@ -276,27 +277,33 @@ impl<'a, W: Write> Writer<'a, W> { let global = &module.global_variables[handle]; let inner = &module.types[global.ty].inner; - let register_ty = match *inner { - TypeInner::Image { .. } => "t", - TypeInner::Sampler { .. } => "s", + let (storage_class, register_ty) = match *inner { + TypeInner::Image { .. } => ("", "t"), + TypeInner::Sampler { .. } => ("", "s"), + TypeInner::Struct { .. } | TypeInner::Vector { .. } => ("static ", ""), // TODO: other register ty https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register _ => return Err(Error::Unimplemented(format!("register_ty {:?}", inner))), }; - let register = if let Some(ref binding) = global.binding { - format!("register({}{})", register_ty, binding.binding) - } else { - String::from("") - }; - - let name = self.names[&NameKey::GlobalVariable(handle)].clone(); + write!(self.out, "{}", storage_class)?; self.write_type(module, global.ty)?; - write!(self.out, " {}", name)?; + if let TypeInner::Array { size, .. } = module.types[global.ty].inner { + self.write_array_size(module, size)?; + } + write!( + self.out, + " {}", + &self.names[&NameKey::GlobalVariable(handle)] + )?; - if register.is_empty() { - writeln!(self.out, ";")?; + if let Some(ref binding) = global.binding { + writeln!(self.out, " : register({}{});", register_ty, binding.binding)?; } else { - writeln!(self.out, " : {};", register)?; + if let Some(init) = global.init { + write!(self.out, " = ")?; + self.write_constant(module, init)?; + } + writeln!(self.out, ";")?; } Ok(()) @@ -353,6 +360,28 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + // copy-paste from glsl-out + fn write_array_size(&mut self, module: &Module, size: ArraySize) -> BackendResult { + write!(self.out, "[")?; + + // Write the array size + // Writes nothing if `ArraySize::Dynamic` + // Panics if `ArraySize::Constant` has a constant that isn't an uint + match size { + ArraySize::Constant(const_handle) => match module.constants[const_handle].inner { + ConstantInner::Scalar { + width: _, + value: ScalarValue::Uint(size), + } => write!(self.out, "{}", size)?, + _ => unreachable!(), + }, + ArraySize::Dynamic => (), + } + + write!(self.out, "]")?; + Ok(()) + } + /// Helper method used to write structs /// /// # Notes @@ -371,10 +400,42 @@ impl<'a, W: Write> Writer<'a, W> { for (index, member) in members.iter().enumerate() { // The indentation is only for readability write!(self.out, "{}", INDENT)?; - // Write struct member type and name - self.write_type(module, member.ty)?; - let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; - write!(self.out, " {}", member_name)?; + + match module.types[member.ty].inner { + TypeInner::Array { + base, + size, + stride: _, + } => { + // HLSL arrays are written as `type name[size]` + let ty_name = match module.types[base].inner { + // Write scalar type by backend so as not to depend on the front-end implementation + // Name returned from frontend can be generated (type1, float1, etc.) + TypeInner::Scalar { kind, width } => scalar_kind_str(kind, width)?, + _ => &self.names[&NameKey::Type(base)], + }; + + // Write `type` and `name` + write!(self.out, "{}", ty_name)?; + write!( + self.out, + " {}", + &self.names[&NameKey::StructMember(handle, index as u32)] + )?; + // Write [size] + self.write_array_size(module, size)?; + } + _ => { + // Write the member type and name + self.write_type(module, member.ty)?; + write!( + self.out, + " {}", + &self.names[&NameKey::StructMember(handle, index as u32)] + )?; + } + } + if let Some(ref binding) = member.binding { self.write_binding(binding)?; }; @@ -394,6 +455,8 @@ impl<'a, W: Write> Writer<'a, W> { let inner = &module.types[ty].inner; match *inner { TypeInner::Struct { .. } => write!(self.out, "{}", self.names[&NameKey::Type(ty)])?, + // hlsl array has the size separated from the base type + TypeInner::Array { base, .. } => self.write_type(module, base)?, ref other => self.write_value_type(module, other)?, } @@ -404,7 +467,7 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Adds no trailing or leading whitespace - fn write_value_type(&mut self, _module: &Module, inner: &TypeInner) -> BackendResult { + fn write_value_type(&mut self, module: &Module, inner: &TypeInner) -> BackendResult { match *inner { TypeInner::Scalar { kind, width } => { write!(self.out, "{}", scalar_kind_str(kind, width)?)?; @@ -422,7 +485,7 @@ impl<'a, W: Write> Writer<'a, W> { rows, width, } => { - //TODO: int matrix ? + // The IR supports only float matrix // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-matrix write!( self.out, @@ -455,6 +518,12 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Sampler { comparison: false } => { write!(self.out, "SamplerState")?; } + // HLSL arrays are written as `type name[size]` + // Current code is written arrays only as `[size]` + // Base `type` and `name` should be written outside + TypeInner::Array { size, .. } => { + self.write_array_size(module, size)?; + } _ => { return Err(Error::Unimplemented(format!( "write_value_type {:?}", @@ -701,6 +770,38 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ";")? } } + Statement::Store { pointer, value } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, " = ")?; + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ";")? + } + Statement::Call { + function, + ref arguments, + result, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + if let Some(expr) = result { + let name = format!("{}{}", BAKE_PREFIX, expr.index()); + write!(self.out, "const {} = ", name)?; + self.write_expr(module, expr, func_ctx)?; + self.named_expressions.insert(expr, name); + writeln!(self.out, ";")? + } + let func_name = &self.names[&NameKey::Function(function)]; + write!(self.out, "{}(", func_name)?; + for (index, argument) in arguments.iter().enumerate() { + self.write_expr(module, *argument, func_ctx)?; + // Only write a comma if isn't the last element + if index != arguments.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } + writeln!(self.out, ");")? + } _ => return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))), } @@ -838,6 +939,7 @@ impl<'a, W: Write> Writer<'a, W> { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; } + Expression::Load { pointer } => self.write_expr(module, pointer, func_ctx)?, _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } @@ -861,11 +963,25 @@ impl<'a, W: Write> Writer<'a, W> { self.write_scalar_value(*value)?; } } - _ => { - return Err(Error::Unimplemented(format!( - "write_constant {:?}", - constant - ))) + crate::ConstantInner::Composite { ty, ref components } => { + let (open_b, close_b) = match module.types[ty].inner { + TypeInner::Struct { .. } => ("{ ", " }"), + _ => { + // We should write type only for non struct constants + self.write_type(module, ty)?; + ("(", ")") + } + }; + write!(self.out, "{}", open_b)?; + for (index, constant) in components.iter().enumerate() { + self.write_constant(module, *constant)?; + // Only write a comma if isn't the last element + if index != components.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } + write!(self.out, "{}", close_b)?; } } @@ -914,14 +1030,12 @@ impl<'a, W: Write> Writer<'a, W> { let base_ty_res = &ctx.info[handle].ty; let resolved = base_ty_res.inner_with(&module.types); - // If rhs is a array type, we should write temp variable as a dynamic array - let array_str = if let TypeInner::Array { .. } = *resolved { - "[]" - } else { - "" - }; - - write!(self.out, " {}{} = ", name, array_str)?; + write!(self.out, " {}", name)?; + // If rhs is a array type, we should write array size + if let TypeInner::Array { size, .. } = *resolved { + self.write_array_size(module, size)?; + } + write!(self.out, " = ")?; self.write_expr(module, handle, ctx)?; writeln!(self.out, ";")?; self.named_expressions.insert(handle, name); diff --git a/tests/out/quad-vert.hlsl b/tests/out/quad-vert.hlsl new file mode 100644 index 000000000..4c28ecfb6 --- /dev/null +++ b/tests/out/quad-vert.hlsl @@ -0,0 +1,47 @@ +struct gl_PerVertex { + float4 gl_Position : SV_Position; + float gl_PointSize : PSIZE; + float gl_ClipDistance[1] : SV_ClipDistance; + float gl_CullDistance[1] : SV_CullDistance; +}; + +struct type10 { + float2 member : LOC0; + float4 gl_Position : SV_Position; + float gl_PointSize : PSIZE; + float gl_ClipDistance[1] : SV_ClipDistance; + float gl_CullDistance[1] : SV_CullDistance; +}; + +static float2 v_uv; +static float2 a_uv1; +static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, float(0.0), float(0.0) }; +static float2 a_pos1; + +struct VertexInput { + float2 a_uv2 : LOC1; + float2 a_pos2 : LOC0; +}; + +void main1() +{ + float2 _expr12 = a_uv1; + v_uv = _expr12; + float2 _expr13 = a_pos1; + perVertexStruct.gl_Position = float4(_expr13.x, _expr13.y, 0.0, 1.0); + return; +} + +type10 vert_main(VertexInput vertexinput) +{ + a_uv1 = vertexinput.a_uv2; + a_pos1 = vertexinput.a_pos2; + main1(); + float2 _expr10 = v_uv; + float4 _expr11 = perVertexStruct.gl_Position; + float _expr12 = perVertexStruct.gl_PointSize; + float _expr13[1] = perVertexStruct.gl_ClipDistance; + float _expr14[1] = perVertexStruct.gl_CullDistance; + const type10 type10_ = { _expr10, _expr11, _expr12, _expr13, _expr14 }; + return type10_; +} diff --git a/tests/out/quad-vert.hlsl.config b/tests/out/quad-vert.hlsl.config new file mode 100644 index 000000000..c01697983 --- /dev/null +++ b/tests/out/quad-vert.hlsl.config @@ -0,0 +1,2 @@ +vertex=vs_5_0 +vertex_name=vert_main diff --git a/tests/out/quad.hlsl b/tests/out/quad.hlsl index 81f661fc7..bb524e835 100644 --- a/tests/out/quad.hlsl +++ b/tests/out/quad.hlsl @@ -1,13 +1,13 @@ static const float c_scale = 1.2; -Texture2D u_texture : register(t0); -SamplerState u_sampler : register(s1); - struct VertexOutput { float2 uv : LOC0; float4 position : SV_Position; }; +Texture2D u_texture : register(t0); +SamplerState u_sampler : register(s1); + struct VertexInput { float2 pos1 : LOC0; float2 uv2 : LOC1; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 9505f2f87..c6ebaab81 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -358,7 +358,7 @@ fn convert_spv_quad_vert() { convert_spv( "quad-vert", false, - Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ); } From a1bd4a8053a23873b05fbd744c158bf961102733 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 18 Jun 2021 21:46:18 +0100 Subject: [PATCH 0990/2212] [glsl-in] Allow structs as local type --- src/front/glsl/parser.rs | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 237a8c792..2b8239152 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1340,6 +1340,18 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } fn parse_statement(&mut self, ctx: &mut Context, body: &mut Block) -> Result<()> { + // TODO: This prevents snippets like the following from working + // ```glsl + // vec4(1.0); + // ``` + // But this would require us to add lookahead to also support + // declarations and since this statement is very unlikely and most + // likely an error, for now we don't support it + if self.peek_type_name() || self.peek_type_qualifier() { + self.parse_declaration(ctx, body, false)?; + return Ok(()); + } + match self.expect_peek()?.value { TokenValue::Continue => { self.bump()?; @@ -1686,19 +1698,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ctx.remove_current_scope(); body.push(Statement::Block(block)); } - // TODO: We should also add TypeName here because this is valid - // ```glsl - // vec4(1.0); - // ``` - // But this would require us to add lookahead to also support - // declarations and since this statement is very unlikely and most - // likely an error, for now we don't support it TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde | TokenValue::LeftParen | TokenValue::Identifier(_) + | TokenValue::TypeName(_) | TokenValue::IntConstant(_) | TokenValue::BoolConstant(_) | TokenValue::FloatConstant(_) => { @@ -1709,11 +1715,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Semicolon => { self.bump()?; } - _ => { - if self.peek_type_name() || self.peek_type_qualifier() { - self.parse_declaration(ctx, body, false)?; - } - } + _ => {} } Ok(()) From bfeab40c8dfdd10109a23c3081b510628801b7b7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Jun 2021 12:06:42 -0400 Subject: [PATCH 0991/2212] Changelog for v0.5 release --- CHANGELOG.md | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f68bf07e9..51c9655d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,43 @@ # Change Log +## v0.5 (2021-06-18) + - development release for wgpu-0.9 + - API: + - barriers + - dynamic indexing of matrices and arrays is only allowed on variables + - validator now accepts a list of IR capabilities to allow + - improved documentation + - Infrastructure: + - much richer test suite, focused around consuming or emitting WGSL + - lazy testing on large shader corpuses + - the binary is moved to a sub-crate "naga-cli" + - Frontends: + - GLSL frontend: + - rewritten from scratch and effectively revived, no longer depends on `pomelo` + - only supports 440/450/460 versions for now + - has optional support for codespan messages + - SPIRV frontend has improved CFG resolution (still with issues unresolved) + - WGSL got better error messages, workgroup memory support + - Backends: + - general: better expression naming and emitting + - new HLSL backend (in progress) + - MSL: + - support `ArraySize` expression + - better texture sampling instructions + - GLSL: + - multisampling on GLES + - WGSL is vastly improved and now usable + +### v0.4.2 (2021-05-28) + - SPIR-V frontend: + - fix image stores + - fix matrix stride check + - SPIR-V backend: + - fix auto-deriving the capabilities + - GLSL backend: + - support sample interpolation + - write out swizzled vector accesses + ### v0.4.1 (2021-05-14) - numerous additions and improvements to SPIR-V frontend: - int8, in16, int64 diff --git a/README.md b/README.md index a3d880d02..044d4d99a 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Front-end | Status | Feature | Notes | --------------- | ------------------ | ------- | ----- | SPIR-V (binary) | :white_check_mark: | spv-in | | WGSL | :white_check_mark: | wgsl-in | Fully validated | -GLSL | :construction: | glsl-in | Temporarily broken | +GLSL | :ok: | glsl-in | | Back-end | Status | Feature | Notes | --------------- | ------------------ | -------- | ----- | From f0f8a5f3ba228cfa78db1cfc6b2d235f02156cb4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Jun 2021 20:11:42 -0400 Subject: [PATCH 0992/2212] Fix GLSL frontend clippy error --- src/front/glsl/error.rs | 4 ++-- src/front/glsl/parser.rs | 4 ++-- src/front/glsl/parser_tests.rs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 420f6a2e9..004439142 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -26,7 +26,7 @@ pub enum ExpectedToken { IntLiteral, FloatLiteral, BoolLiteral, - EOF, + Eof, } impl From for ExpectedToken { fn from(token: TokenValue) -> Self { @@ -42,7 +42,7 @@ impl std::fmt::Display for ExpectedToken { ExpectedToken::IntLiteral => write!(f, "integer literal"), ExpectedToken::FloatLiteral => write!(f, "float literal"), ExpectedToken::BoolLiteral => write!(f, "bool literal"), - ExpectedToken::EOF => write!(f, "end of file"), + ExpectedToken::Eof => write!(f, "end of file"), } } } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2b8239152..9cc881cb1 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -427,8 +427,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::Semicolon if self.program.version == 460 => Ok(()), _ => { let expected = match self.program.version { - 460 => vec![TokenValue::Semicolon.into(), ExpectedToken::EOF], - _ => vec![ExpectedToken::EOF], + 460 => vec![TokenValue::Semicolon.into(), ExpectedToken::Eof], + _ => vec![ExpectedToken::Eof], }; Err(ErrorKind::InvalidToken(token, expected)) } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 81107171e..40281ed36 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -56,7 +56,7 @@ fn version() { value: TokenValue::Unknown(PreprocessorError::UnexpectedHash), meta: SourceMetadata { start: 24, end: 25 } }, - vec![ExpectedToken::EOF] + vec![ExpectedToken::Eof] ) ); From 8376bab5622f89ed9689cd0c3aedfd97c333c5bf Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Jun 2021 20:11:49 -0400 Subject: [PATCH 0993/2212] Bump version to 0.5 --- Cargo.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 341a6300b..09d2b43a9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,11 +1,11 @@ [package] name = "naga" -version = "0.4.0" +version = "0.5.0" authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" homepage = "https://github.com/gfx-rs/naga" -repository = "https://github.com/gfx-rs/naga" +repository = "https://github.com/gfx-rs/naga/tree/v0.5" keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] @@ -26,7 +26,7 @@ thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } rose_tree = { version ="0.2", optional = true } -pp-rs = { git = "https://github.com/Kangz/glslpp-rs.git", optional = true, rev = "c02476b" } +pp-rs = { version = "0.2.1", optional = true } [features] default = [] From b8724eb1fd2871dbf6e05c1cfc2248368f11a792 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 27 May 2021 21:52:31 -0700 Subject: [PATCH 0994/2212] Tweak access.wgsl to avoid #913 and make SPIR-V more distinctive. --- tests/in/access.wgsl | 2 +- tests/out/access.msl | 2 +- tests/out/access.spvasm | 29 +++++++++++++++-------------- tests/out/access.wgsl | 2 +- 4 files changed, 18 insertions(+), 17 deletions(-) diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index dc5fb984f..9257cd75f 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -19,7 +19,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let index = 3u; let b = bar.matrix[index].x; - let a = bar.data[arrayLength(&bar.data) - 1u]; + let a = bar.data[arrayLength(&bar.data) - 2u]; var c: array = array(a, i32(b), 3, 4, 5); let value = c[vi]; diff --git a/tests/out/access.msl b/tests/out/access.msl index 54f422f4d..31106f896 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -30,7 +30,7 @@ vertex fooOutput foo( foo1 = 1.0; metal::float4 _e9 = bar.matrix[3]; float b = _e9.x; - int a = bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 1u]; + int a = bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 2u]; for(int _i=0; _i<5; ++_i) c.inner[_i] = type6 {a, static_cast(b), 3, 4, 5}.inner[_i]; int value = c.inner[vi]; return fooOutput { static_cast(metal::int4(value)) }; diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm index 297b8a726..96a5a22c4 100644 --- a/tests/out/access.spvasm +++ b/tests/out/access.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 54 +; Bound: 55 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" @@ -33,7 +33,7 @@ OpDecorate %28 BuiltIn Position %5 = OpConstant %4 1.0 %7 = OpTypeInt 32 0 %6 = OpConstant %7 3 -%8 = OpConstant %7 1 +%8 = OpConstant %7 2 %10 = OpTypeInt 32 1 %9 = OpConstant %10 5 %11 = OpConstant %10 3 @@ -57,8 +57,9 @@ OpDecorate %28 BuiltIn Position %36 = OpConstant %7 0 %40 = OpTypePointer StorageBuffer %15 %43 = OpTypePointer StorageBuffer %10 -%48 = OpTypePointer Function %10 -%51 = OpTypeVector %10 4 +%44 = OpConstant %7 1 +%49 = OpTypePointer Function %10 +%52 = OpTypeVector %10 4 %30 = OpFunction %2 None %31 %24 = OpLabel %20 = OpVariable %21 Function %3 @@ -73,15 +74,15 @@ OpStore %20 %5 %39 = OpCompositeExtract %4 %38 0 %41 = OpArrayLength %7 %18 1 %42 = OpISub %7 %41 %8 -%44 = OpAccessChain %43 %18 %8 %42 -%45 = OpLoad %10 %44 -%46 = OpConvertFToS %10 %39 -%47 = OpCompositeConstruct %17 %45 %46 %11 %12 %9 -OpStore %22 %47 -%49 = OpAccessChain %48 %22 %27 -%50 = OpLoad %10 %49 -%52 = OpCompositeConstruct %51 %50 %50 %50 %50 -%53 = OpConvertSToF %14 %52 -OpStore %28 %53 +%45 = OpAccessChain %43 %18 %44 %42 +%46 = OpLoad %10 %45 +%47 = OpConvertFToS %10 %39 +%48 = OpCompositeConstruct %17 %46 %47 %11 %12 %9 +OpStore %22 %48 +%50 = OpAccessChain %49 %22 %27 +%51 = OpLoad %10 %50 +%53 = OpCompositeConstruct %52 %51 %51 %51 %51 +%54 = OpConvertSToF %14 %53 +OpStore %28 %54 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/access.wgsl b/tests/out/access.wgsl index 8bb52234a..66a799199 100644 --- a/tests/out/access.wgsl +++ b/tests/out/access.wgsl @@ -16,7 +16,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { foo1 = 1.0; let _e9: vec4 = bar.matrix[3]; let b: f32 = _e9.x; - let a: i32 = bar.data[(arrayLength(&bar.data) - 1u)]; + let a: i32 = bar.data[(arrayLength(&bar.data) - 2u)]; c = array(a, i32(b), 3, 4, 5); let value: i32 = c[vi]; return vec4(vec4(value)); From fd3b2a93d4ba74bc3a6b658393234c085000b3fb Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 13 May 2021 11:01:32 -0700 Subject: [PATCH 0995/2212] access.wgsl: Make array mutable, and assign to an element. --- tests/in/access.wgsl | 1 + tests/out/access.msl | 1 + tests/out/access.spvasm | 136 +++++++++++++++++++++------------------- tests/out/access.wgsl | 1 + 4 files changed, 73 insertions(+), 66 deletions(-) diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 9257cd75f..551812d1d 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -22,6 +22,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let a = bar.data[arrayLength(&bar.data) - 2u]; var c: array = array(a, i32(b), 3, 4, 5); + c[vi + 1u] = 42; let value = c[vi]; return vec4(vec4(value)); diff --git a/tests/out/access.msl b/tests/out/access.msl index 31106f896..a7abce8b4 100644 --- a/tests/out/access.msl +++ b/tests/out/access.msl @@ -32,6 +32,7 @@ vertex fooOutput foo( float b = _e9.x; int a = bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 2u]; for(int _i=0; _i<5; ++_i) c.inner[_i] = type6 {a, static_cast(b), 3, 4, 5}.inner[_i]; + c.inner[vi + 1u] = 42; int value = c.inner[vi]; return fooOutput { static_cast(metal::int4(value)) }; } diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm index 96a5a22c4..f6f2f8c8a 100644 --- a/tests/out/access.spvasm +++ b/tests/out/access.spvasm @@ -1,32 +1,32 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 55 +; Bound: 58 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %30 "foo" %25 %28 +OpEntryPoint Vertex %32 "foo" %27 %30 OpSource GLSL 450 -OpName %16 "Bar" -OpMemberName %16 0 "matrix" -OpMemberName %16 1 "data" -OpName %18 "bar" -OpName %20 "foo" -OpName %22 "c" -OpName %25 "vi" -OpName %30 "foo" -OpDecorate %15 ArrayStride 4 -OpDecorate %16 Block -OpMemberDecorate %16 0 Offset 0 -OpMemberDecorate %16 0 ColMajor -OpMemberDecorate %16 0 MatrixStride 16 -OpMemberDecorate %16 1 Offset 64 +OpName %18 "Bar" +OpMemberName %18 0 "matrix" +OpMemberName %18 1 "data" +OpName %20 "bar" +OpName %22 "foo" +OpName %24 "c" +OpName %27 "vi" +OpName %32 "foo" OpDecorate %17 ArrayStride 4 -OpDecorate %18 DescriptorSet 0 -OpDecorate %18 Binding 0 -OpDecorate %25 BuiltIn VertexIndex -OpDecorate %28 BuiltIn Position +OpDecorate %18 Block +OpMemberDecorate %18 0 Offset 0 +OpMemberDecorate %18 0 ColMajor +OpMemberDecorate %18 0 MatrixStride 16 +OpMemberDecorate %18 1 Offset 64 +OpDecorate %19 ArrayStride 4 +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 0 +OpDecorate %27 BuiltIn VertexIndex +OpDecorate %30 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 @@ -38,51 +38,55 @@ OpDecorate %28 BuiltIn Position %9 = OpConstant %10 5 %11 = OpConstant %10 3 %12 = OpConstant %10 4 -%14 = OpTypeVector %4 4 -%13 = OpTypeMatrix %14 4 -%15 = OpTypeRuntimeArray %10 -%16 = OpTypeStruct %13 %15 -%17 = OpTypeArray %10 %9 -%19 = OpTypePointer StorageBuffer %16 -%18 = OpVariable %19 StorageBuffer -%21 = OpTypePointer Function %4 -%23 = OpTypePointer Function %17 -%26 = OpTypePointer Input %7 -%25 = OpVariable %26 Input -%29 = OpTypePointer Output %14 -%28 = OpVariable %29 Output -%31 = OpTypeFunction %2 -%34 = OpTypePointer StorageBuffer %13 -%35 = OpTypePointer StorageBuffer %14 -%36 = OpConstant %7 0 -%40 = OpTypePointer StorageBuffer %15 -%43 = OpTypePointer StorageBuffer %10 -%44 = OpConstant %7 1 -%49 = OpTypePointer Function %10 -%52 = OpTypeVector %10 4 -%30 = OpFunction %2 None %31 -%24 = OpLabel -%20 = OpVariable %21 Function %3 -%22 = OpVariable %23 Function -%27 = OpLoad %7 %25 -OpBranch %32 -%32 = OpLabel -%33 = OpLoad %4 %20 -OpStore %20 %5 -%37 = OpAccessChain %35 %18 %36 %6 -%38 = OpLoad %14 %37 -%39 = OpCompositeExtract %4 %38 0 -%41 = OpArrayLength %7 %18 1 -%42 = OpISub %7 %41 %8 -%45 = OpAccessChain %43 %18 %44 %42 -%46 = OpLoad %10 %45 -%47 = OpConvertFToS %10 %39 -%48 = OpCompositeConstruct %17 %46 %47 %11 %12 %9 -OpStore %22 %48 -%50 = OpAccessChain %49 %22 %27 -%51 = OpLoad %10 %50 -%53 = OpCompositeConstruct %52 %51 %51 %51 %51 -%54 = OpConvertSToF %14 %53 -OpStore %28 %54 +%13 = OpConstant %7 1 +%14 = OpConstant %10 42 +%16 = OpTypeVector %4 4 +%15 = OpTypeMatrix %16 4 +%17 = OpTypeRuntimeArray %10 +%18 = OpTypeStruct %15 %17 +%19 = OpTypeArray %10 %9 +%21 = OpTypePointer StorageBuffer %18 +%20 = OpVariable %21 StorageBuffer +%23 = OpTypePointer Function %4 +%25 = OpTypePointer Function %19 +%28 = OpTypePointer Input %7 +%27 = OpVariable %28 Input +%31 = OpTypePointer Output %16 +%30 = OpVariable %31 Output +%33 = OpTypeFunction %2 +%36 = OpTypePointer StorageBuffer %15 +%37 = OpTypePointer StorageBuffer %16 +%38 = OpConstant %7 0 +%42 = OpTypePointer StorageBuffer %17 +%45 = OpTypePointer StorageBuffer %10 +%51 = OpTypePointer Function %10 +%55 = OpTypeVector %10 4 +%32 = OpFunction %2 None %33 +%26 = OpLabel +%22 = OpVariable %23 Function %3 +%24 = OpVariable %25 Function +%29 = OpLoad %7 %27 +OpBranch %34 +%34 = OpLabel +%35 = OpLoad %4 %22 +OpStore %22 %5 +%39 = OpAccessChain %37 %20 %38 %6 +%40 = OpLoad %16 %39 +%41 = OpCompositeExtract %4 %40 0 +%43 = OpArrayLength %7 %20 1 +%44 = OpISub %7 %43 %8 +%46 = OpAccessChain %45 %20 %13 %44 +%47 = OpLoad %10 %46 +%48 = OpConvertFToS %10 %41 +%49 = OpCompositeConstruct %19 %47 %48 %11 %12 %9 +OpStore %24 %49 +%50 = OpIAdd %7 %29 %13 +%52 = OpAccessChain %51 %24 %50 +OpStore %52 %14 +%53 = OpAccessChain %51 %24 %29 +%54 = OpLoad %10 %53 +%56 = OpCompositeConstruct %55 %54 %54 %54 %54 +%57 = OpConvertSToF %16 %56 +OpStore %30 %57 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/access.wgsl b/tests/out/access.wgsl index 66a799199..041d52839 100644 --- a/tests/out/access.wgsl +++ b/tests/out/access.wgsl @@ -18,6 +18,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let b: f32 = _e9.x; let a: i32 = bar.data[(arrayLength(&bar.data) - 2u)]; c = array(a, i32(b), 3, 4, 5); + c[(vi + 1u)] = 42; let value: i32 = c[vi]; return vec4(vec4(value)); } From 1d0b3f3a752347ecbc37fa50abbfea170972caa1 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 27 May 2021 14:01:40 -0700 Subject: [PATCH 0996/2212] Functions can take pointers to unsized structs, but no other unsized types. --- src/valid/function.rs | 8 ++++++++ src/valid/type.rs | 20 +++++++++++++++++++- tests/wgsl-errors.rs | 43 +++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 68 insertions(+), 3 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 60b431052..0c68d8e04 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -37,6 +37,8 @@ pub enum CallError { #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum LocalVariableError { + #[error("Local variable has a type {0:?} that can't be stored in a local variable.")] + InvalidType(Handle), #[error("Initializer doesn't match the variable type")] InitializerType, } @@ -517,6 +519,12 @@ impl super::Validator { constants: &Arena, ) -> Result<(), LocalVariableError> { log::debug!("var {:?}", var); + if !self.types[var.ty.index()] + .flags + .contains(TypeFlags::DATA | TypeFlags::SIZED) + { + return Err(LocalVariableError::InvalidType(var.ty)); + } if let Some(const_handle) = var.init { match constants[const_handle].inner { crate::ConstantInner::Scalar { width, ref value } => { diff --git a/src/valid/type.rs b/src/valid/type.rs index e9f888a63..abcd268c1 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -42,6 +42,8 @@ pub enum TypeError { InvalidWidth(crate::ScalarKind, crate::Bytes), #[error("The base handle {0:?} can not be resolved")] UnresolvedBase(Handle), + #[error("Invalid type for pointer target {0:?}")] + InvalidPointerBase(Handle), #[error("Expected data type, found {0:?}")] InvalidData(Handle), #[error("Structure type {0:?} can not be a block structure")] @@ -197,7 +199,23 @@ impl super::Validator { if base >= handle { return Err(TypeError::UnresolvedBase(base)); } - TypeInfo::new(TypeFlags::DATA | TypeFlags::SIZED, 0) + + // Pointers to dynamically-sized arrays are needed, to serve as + // the type of an `AccessIndex` expression referring to a + // dynamically sized array appearing as the final member of a + // top-level `Struct`. But such pointers cannot be passed to + // functions, stored in varibles, etc. So, we mark them as not + // `DATA`. + let base_info = &self.types[base.index()]; + let data_flag = if base_info.flags.contains(TypeFlags::SIZED) { + TypeFlags::DATA + } else if let crate::TypeInner::Struct { .. } = types[base].inner { + TypeFlags::DATA + } else { + TypeFlags::empty() + }; + + TypeInfo::new(data_flag | TypeFlags::SIZED, 0) } Ti::ValuePointer { size: _, diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index fb49a4056..c1acad6ab 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -128,10 +128,14 @@ macro_rules! check_validation_error { let error = validation_error($source); if ! matches!(&error, $pattern if $guard) { eprintln!("validation error does not match pattern:\n\ + source code: {}\n\ + \n\ + actual result:\n\ {:#?}\n\ \n\ expected match for pattern:\n\ {}{}", + stringify!($source), error, stringify!($pattern), $guard_string); @@ -227,7 +231,12 @@ fn invalid_structs() { #[test] fn invalid_functions() { check_validation_error! { - "fn bogus(data: array) -> f32 { return data[0]; }": + "fn unacceptable_unsized(arg: array) { }", + "fn unacceptable_unsized(arg: ptr>) { }", + " + struct Unsized { data: array; }; + fn unacceptable_unsized(arg: Unsized) { } + ": Err(naga::valid::ValidationError::Function { name: function_name, error: naga::valid::FunctionError::InvalidArgumentType { @@ -236,7 +245,16 @@ fn invalid_functions() { }, .. }) - if function_name == "bogus" && argument_name == "data" + if function_name == "unacceptable_unsized" && argument_name == "arg" + } + + // A *valid* way to pass an unsized value. + check_validation_error! { + " + struct Unsized { data: array; }; + fn acceptable_ptr_to_unsized(okay: ptr) { } + ": + Ok(_) } } @@ -357,3 +375,24 @@ fn valid_access() { Ok(_) } } + +#[test] +fn invalid_local_vars() { + check_validation_error! { + " + struct Unsized { data: array; }; + fn local_ptr_dynamic_array(okay: ptr) { + var not_okay: ptr> = okay.data; + } + ": + Err(naga::valid::ValidationError::Function { + error: naga::valid::FunctionError::LocalVariable { + name: local_var_name, + error: naga::valid::LocalVariableError::InvalidType(_), + .. + }, + .. + }) + if local_var_name == "not_okay" + } +} From ac92f09a485a619f382bcfbecb981f8682976962 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 4 Jun 2021 11:34:48 -0700 Subject: [PATCH 0997/2212] [spv-out] Document `is_intermediate`. --- src/back/spv/writer.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 62afb85fd..4ba24c3f8 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1318,6 +1318,15 @@ impl Writer { }) } + /// Decide whether to put off emitting instructions for `expr_handle`. + /// + /// We would like to gather together chains of `Access` and `AccessIndex` + /// Naga expressions into a single `OpAccessChain` SPIR-V instruction. To do + /// this, we don't generate instructions for these exprs when we first + /// encounter them. Their ids in `self.cached.ids` are left as zero. Then, + /// once we encounter a `Load` or `Store` expression that actually needs the + /// chain's value, we call `write_expression_pointer` to handle the whole + /// thing in one fell swoop. fn is_intermediate( &self, expr_handle: Handle, @@ -1335,6 +1344,9 @@ impl Writer { _ => false, } } + + // The chain rule: if this `Access...`'s `base` operand was + // previously omitted, then omit this one, too. _ => self.cached.ids[expr_handle.index()] == 0, } } @@ -1355,6 +1367,8 @@ impl Writer { crate::Expression::Access { base, index: _ } if self.is_intermediate(base, ir_function, &ir_module.types) => { + // See `is_intermediate`; we'll handle this later in + // `write_expression_pointer`. 0 } crate::Expression::Access { base, index } => { @@ -1389,6 +1403,8 @@ impl Writer { crate::Expression::AccessIndex { base, index: _ } if self.is_intermediate(base, ir_function, &ir_module.types) => { + // See `is_intermediate`; we'll handle this later in + // `write_expression_pointer`. 0 } crate::Expression::AccessIndex { base, index } => { From 9146942412a4124953881f477736bbdc4e72c925 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 7 Jun 2021 15:14:49 -0700 Subject: [PATCH 0998/2212] [spv-out]: Abstract out null constant creation. --- src/back/spv/writer.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4ba24c3f8..a6927d2d7 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1085,6 +1085,13 @@ impl Writer { Ok(()) } + fn write_constant_null(&mut self, type_id: Word) -> Word { + let null_id = self.id_gen.next(); + Instruction::constant_null(type_id, null_id) + .to_words(&mut self.logical_layout.declarations); + null_id + } + fn write_varying( &mut self, ir_module: &crate::Module, @@ -2788,11 +2795,8 @@ impl Writer { // Or it may be the end of the function. None => match ir_function.result { Some(ref result) if function.entry_point_context.is_none() => { - // create a Null and return it - let null_id = self.id_gen.next(); let type_id = self.get_type_id(LookupType::Handle(result.ty))?; - Instruction::constant_null(type_id, null_id) - .to_words(&mut self.logical_layout.declarations); + let null_id = self.write_constant_null(type_id); Instruction::return_value(null_id) } _ => Instruction::return_void(), From a7cacab27671db53eae01229eab1ea0158b306d8 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 18 Jun 2021 09:14:19 -0700 Subject: [PATCH 0999/2212] [spv-out] Move Writer type to back/spv/mod.rs. The `impl` blocks for `Writer` and its associated types remain in spv/writer.rs. There should be no substantive code changes in this commit, only moving code around and adjusting `use` declarations to match. --- src/back/spv/mod.rs | 204 +++++++++++++++++++++++++++++++++++++-- src/back/spv/writer.rs | 212 ++++------------------------------------- 2 files changed, 210 insertions(+), 206 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index e571c3ba1..c579f0546 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -7,18 +7,12 @@ mod layout; mod writer; pub use spirv::Capability; -pub use writer::{Error, Writer}; + +use crate::arena::Handle; use spirv::Word; - -bitflags::bitflags! { - pub struct WriterFlags: u32 { - /// Include debug labels for everything. - const DEBUG = 0x1; - /// Flip Y coordinate of `BuiltIn::Position` output. - const ADJUST_COORDINATE_SPACE = 0x2; - } -} +use std::ops; +use thiserror::Error; struct PhysicalLayout { magic_number: Word, @@ -51,6 +45,196 @@ struct Instruction { operands: Vec, } +const BITS_PER_BYTE: crate::Bytes = 8; + +#[derive(Clone, Debug, Error)] +pub enum Error { + #[error("target SPIRV-{0}.{1} is not supported")] + UnsupportedVersion(u8, u8), + #[error("one of the required capabilities {0:?} is missing")] + MissingCapabilities(Vec), + #[error("unimplemented {0}")] + FeatureNotImplemented(&'static str), + #[error("module is not validated properly: {0}")] + Validation(&'static str), +} + +#[derive(Default)] +struct IdGenerator(Word); + +impl IdGenerator { + fn next(&mut self) -> Word { + self.0 += 1; + self.0 + } +} + +struct Block { + label_id: Word, + body: Vec, + termination: Option, +} + +impl Block { + fn new(label_id: Word) -> Self { + Block { + label_id, + body: Vec::new(), + termination: None, + } + } +} + +struct LocalVariable { + id: Word, + instruction: Instruction, +} + +struct ResultMember { + id: Word, + type_id: Word, + built_in: Option, +} + +struct EntryPointContext { + argument_ids: Vec, + results: Vec, +} + +#[derive(Default)] +struct Function { + signature: Option, + parameters: Vec, + variables: crate::FastHashMap, LocalVariable>, + blocks: Vec, + entry_point_context: Option, +} + +#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] +enum LocalType { + Value { + vector_size: Option, + kind: crate::ScalarKind, + width: crate::Bytes, + pointer_class: Option, + }, + Matrix { + columns: crate::VectorSize, + rows: crate::VectorSize, + width: crate::Bytes, + }, + Pointer { + base: Handle, + class: spirv::StorageClass, + }, + Image { + dim: crate::ImageDimension, + arrayed: bool, + class: crate::ImageClass, + }, + SampledImage { + image_type_id: Word, + }, + Sampler, +} + +#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] +enum LookupType { + Handle(Handle), + Local(LocalType), +} + +impl From for LookupType { + fn from(local: LocalType) -> Self { + Self::Local(local) + } +} + +#[derive(Debug, PartialEq, Clone, Hash, Eq)] +struct LookupFunctionType { + parameter_type_ids: Vec, + return_type_id: Word, +} + +#[derive(Debug)] +enum Dimension { + Scalar, + Vector, + Matrix, +} + +#[derive(Default)] +struct CachedExpressions { + ids: Vec, +} +impl CachedExpressions { + fn reset(&mut self, length: usize) { + self.ids.clear(); + self.ids.resize(length, 0); + } +} +impl ops::Index> for CachedExpressions { + type Output = Word; + fn index(&self, h: Handle) -> &Word { + let id = &self.ids[h.index()]; + if *id == 0 { + unreachable!("Expression {:?} is not cached!", h); + } + id + } +} +impl ops::IndexMut> for CachedExpressions { + fn index_mut(&mut self, h: Handle) -> &mut Word { + let id = &mut self.ids[h.index()]; + if *id != 0 { + unreachable!("Expression {:?} is already cached!", h); + } + id + } +} + +struct GlobalVariable { + /// Actual ID of the variable. + id: Word, + /// For `StorageClass::Handle` variables, this ID is recorded in the function + /// prelude block (and reset before every function) as `OpLoad` of the variable. + /// It is then used for all the global ops, such as `OpImageSample`. + handle_id: Word, +} + +pub struct Writer { + physical_layout: PhysicalLayout, + logical_layout: LogicalLayout, + id_gen: IdGenerator, + capabilities: crate::FastHashSet, + forbidden_caps: Option<&'static [Capability]>, + debugs: Vec, + annotations: Vec, + flags: WriterFlags, + void_type: u32, + //TODO: convert most of these into vectors, addressable by handle indices + lookup_type: crate::FastHashMap, + lookup_function: crate::FastHashMap, Word>, + lookup_function_type: crate::FastHashMap, + lookup_function_call: crate::FastHashMap, Word>, + constant_ids: Vec, + cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>, + global_variables: Vec, + cached: CachedExpressions, + gl450_ext_inst_id: Word, + // Just a temporary list of SPIR-V ids + temp_list: Vec, +} + +bitflags::bitflags! { + pub struct WriterFlags: u32 { + /// Include debug labels for everything. + const DEBUG = 0x1; + /// Flip Y coordinate of `BuiltIn::Position` output. + const ADJUST_COORDINATE_SPACE = 0x2; + } +} + #[derive(Debug, Clone)] pub struct Options { /// (Major, Minor) target version of the SPIR-V. diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a6927d2d7..abcce32e2 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,6 +1,8 @@ use super::{ helpers::{contains_builtin, map_storage_class}, - Instruction, LogicalLayout, Options, PhysicalLayout, WriterFlags, + Block, CachedExpressions, Dimension, EntryPointContext, Error, Function, GlobalVariable, + IdGenerator, Instruction, LocalType, LocalVariable, LogicalLayout, LookupFunctionType, + LookupType, Options, PhysicalLayout, ResultMember, Writer, WriterFlags, BITS_PER_BYTE, }; use crate::{ arena::{Arena, Handle}, @@ -8,74 +10,26 @@ use crate::{ valid::{FunctionInfo, ModuleInfo}, }; use spirv::Word; -use std::{collections::hash_map::Entry, ops}; -use thiserror::Error; +use std::collections::hash_map::Entry; -const BITS_PER_BYTE: crate::Bytes = 8; - -#[derive(Clone, Debug, Error)] -pub enum Error { - #[error("target SPIRV-{0}.{1} is not supported")] - UnsupportedVersion(u8, u8), - #[error("one of the required capabilities {0:?} is missing")] - MissingCapabilities(Vec), - #[error("unimplemented {0}")] - FeatureNotImplemented(&'static str), - #[error("module is not validated properly: {0}")] - Validation(&'static str), -} - -#[derive(Default)] -struct IdGenerator(Word); - -impl IdGenerator { - fn next(&mut self) -> Word { - self.0 += 1; - self.0 +fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { + match dim { + crate::ImageDimension::D1 => spirv::Dim::Dim1D, + crate::ImageDimension::D2 => spirv::Dim::Dim2D, + crate::ImageDimension::D3 => spirv::Dim::Dim3D, + crate::ImageDimension::Cube => spirv::Dim::DimCube, } } -struct Block { - label_id: Word, - body: Vec, - termination: Option, -} - -impl Block { - fn new(label_id: Word) -> Self { - Block { - label_id, - body: Vec::new(), - termination: None, - } +fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { + match *type_inner { + crate::TypeInner::Scalar { .. } => Dimension::Scalar, + crate::TypeInner::Vector { .. } => Dimension::Vector, + crate::TypeInner::Matrix { .. } => Dimension::Matrix, + _ => unreachable!(), } } -struct LocalVariable { - id: Word, - instruction: Instruction, -} - -struct ResultMember { - id: Word, - type_id: Word, - built_in: Option, -} - -struct EntryPointContext { - argument_ids: Vec, - results: Vec, -} - -#[derive(Default)] -struct Function { - signature: Option, - parameters: Vec, - variables: crate::FastHashMap, LocalVariable>, - blocks: Vec, - entry_point_context: Option, -} - impl Function { fn to_words(&self, sink: &mut impl Extend) { self.signature.as_ref().unwrap().to_words(sink); @@ -102,34 +56,6 @@ impl Function { } } -#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] -enum LocalType { - Value { - vector_size: Option, - kind: crate::ScalarKind, - width: crate::Bytes, - pointer_class: Option, - }, - Matrix { - columns: crate::VectorSize, - rows: crate::VectorSize, - width: crate::Bytes, - }, - Pointer { - base: Handle, - class: spirv::StorageClass, - }, - Image { - dim: crate::ImageDimension, - arrayed: bool, - class: crate::ImageClass, - }, - SampledImage { - image_type_id: Word, - }, - Sampler, -} - impl PhysicalLayout { fn make_local(&self, inner: &crate::TypeInner) -> Option { Some(match *inner { @@ -184,118 +110,12 @@ impl PhysicalLayout { } } -#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] -enum LookupType { - Handle(Handle), - Local(LocalType), -} - -impl From for LookupType { - fn from(local: LocalType) -> Self { - Self::Local(local) - } -} - -fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { - match dim { - crate::ImageDimension::D1 => spirv::Dim::Dim1D, - crate::ImageDimension::D2 => spirv::Dim::Dim2D, - crate::ImageDimension::D3 => spirv::Dim::Dim3D, - crate::ImageDimension::Cube => spirv::Dim::DimCube, - } -} - -#[derive(Debug, PartialEq, Clone, Hash, Eq)] -struct LookupFunctionType { - parameter_type_ids: Vec, - return_type_id: Word, -} - -#[derive(Debug)] -enum Dimension { - Scalar, - Vector, - Matrix, -} - -fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { - match *type_inner { - crate::TypeInner::Scalar { .. } => Dimension::Scalar, - crate::TypeInner::Vector { .. } => Dimension::Vector, - crate::TypeInner::Matrix { .. } => Dimension::Matrix, - _ => unreachable!(), - } -} - #[derive(Clone, Copy, Default)] struct LoopContext { continuing_id: Option, break_id: Option, } -#[derive(Default)] -struct CachedExpressions { - ids: Vec, -} -impl CachedExpressions { - fn reset(&mut self, length: usize) { - self.ids.clear(); - self.ids.resize(length, 0); - } -} -impl ops::Index> for CachedExpressions { - type Output = Word; - fn index(&self, h: Handle) -> &Word { - let id = &self.ids[h.index()]; - if *id == 0 { - unreachable!("Expression {:?} is not cached!", h); - } - id - } -} -impl ops::IndexMut> for CachedExpressions { - fn index_mut(&mut self, h: Handle) -> &mut Word { - let id = &mut self.ids[h.index()]; - if *id != 0 { - unreachable!("Expression {:?} is already cached!", h); - } - id - } -} - -struct GlobalVariable { - /// Actual ID of the variable. - id: Word, - /// For `StorageClass::Handle` variables, this ID is recorded in the function - /// prelude block (and reset before every function) as `OpLoad` of the variable. - /// It is then used for all the global ops, such as `OpImageSample`. - handle_id: Word, -} - -pub struct Writer { - physical_layout: PhysicalLayout, - logical_layout: LogicalLayout, - id_gen: IdGenerator, - capabilities: crate::FastHashSet, - forbidden_caps: Option<&'static [spirv::Capability]>, - debugs: Vec, - annotations: Vec, - flags: WriterFlags, - void_type: u32, - //TODO: convert most of these into vectors, addressable by handle indices - lookup_type: crate::FastHashMap, - lookup_function: crate::FastHashMap, Word>, - lookup_function_type: crate::FastHashMap, - lookup_function_call: crate::FastHashMap, Word>, - constant_ids: Vec, - cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>, - global_variables: Vec, - cached: CachedExpressions, - gl450_ext_inst_id: Word, - // Just a temporary list of SPIR-V ids - temp_list: Vec, -} - impl Writer { pub fn new(options: &Options) -> Result { let (major, minor) = options.lang_version; From c16f2097add7705f2439d45fa4334efbf495ff14 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 27 May 2021 15:02:38 -0700 Subject: [PATCH 1000/2212] [spv-out]: Ensure array subscripts are in bounds. --- cli/src/main.rs | 21 ++ src/back/mod.rs | 43 +++ src/back/spv/index.rs | 509 +++++++++++++++++++++++++++ src/back/spv/instructions.rs | 15 + src/back/spv/mod.rs | 26 +- src/back/spv/writer.rs | 291 ++++++++++----- src/proc/index.rs | 79 +++++ src/proc/mod.rs | 24 +- src/valid/expression.rs | 46 ++- src/valid/type.rs | 16 +- tests/in/bounds-check-zero.param.ron | 4 + tests/in/bounds-check-zero.wgsl | 46 +++ tests/in/pointer-access.param.ron | 5 + tests/in/pointer-access.spv | Bin 0 -> 664 bytes tests/in/pointer-access.spvasm | 57 +++ tests/out/bounds-check-zero.spvasm | 212 +++++++++++ tests/out/pointer-access.spvasm | 55 +++ tests/snapshots.rs | 27 ++ tests/wgsl-errors.rs | 43 ++- 19 files changed, 1415 insertions(+), 104 deletions(-) create mode 100644 src/back/spv/index.rs create mode 100644 src/proc/index.rs create mode 100644 tests/in/bounds-check-zero.param.ron create mode 100644 tests/in/bounds-check-zero.wgsl create mode 100644 tests/in/pointer-access.param.ron create mode 100644 tests/in/pointer-access.spv create mode 100644 tests/in/pointer-access.spvasm create mode 100644 tests/out/bounds-check-zero.spvasm create mode 100644 tests/out/pointer-access.spvasm diff --git a/cli/src/main.rs b/cli/src/main.rs index 3e04b055b..edf8f3e98 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -6,6 +6,7 @@ use std::{env, error::Error, path::Path}; #[derive(Default)] struct Parameters { validation_flags: naga::valid::ValidationFlags, + index_bounds_check_policy: naga::back::IndexBoundsCheckPolicy, spv_adjust_coordinate_space: bool, spv_flow_dump_prefix: Option, spv: naga::back::spv::Options, @@ -69,6 +70,24 @@ fn main() { params.validation_flags = naga::valid::ValidationFlags::from_bits(value).unwrap(); } + "index-bounds-check-policy" => { + let value = args.next().unwrap(); + params.index_bounds_check_policy = match value.as_str() { + "Restrict" => naga::back::IndexBoundsCheckPolicy::Restrict, + "ReadZeroSkipWrite" => { + naga::back::IndexBoundsCheckPolicy::ReadZeroSkipWrite + } + "UndefinedBehavior" => { + naga::back::IndexBoundsCheckPolicy::UndefinedBehavior + } + other => { + panic!( + "Unrecognized '--index-bounds-check-policy' value: {:?}", + other + ); + } + }; + } "flow-dir" => params.spv_flow_dump_prefix = args.next(), "entry-point" => params.glsl.entry_point = args.next().unwrap(), "profile" => { @@ -241,6 +260,8 @@ fn main() { "spv" => { use naga::back::spv; + params.spv.index_bounds_check_policy = params.index_bounds_check_policy; + let spv = spv::write_vec(&module, info.as_ref().unwrap(), ¶ms.spv).unwrap_pretty(); let bytes = spv diff --git a/src/back/mod.rs b/src/back/mod.rs index 49c7c5689..4874cadde 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -13,6 +13,49 @@ pub mod spv; #[cfg(feature = "wgsl-out")] pub mod wgsl; +/// How should code generated by Naga do indexing bounds checks? +/// +/// When a vector, matrix, or array index is out of bounds—either negative, or +/// greater than or equal to the number of elements in the type—WGSL requires +/// that some other index of the implementation's choice that is in bounds is +/// used instead. (There are no types with zero elements.) +/// +/// Different users of Naga will prefer different defaults: +/// +/// - When used as part of a WebGPU implementation, the WGSL specification +/// requires the `Restrict` behavior. +/// +/// - When used by the `wgpu` crate for native development, `wgpu` selects +/// `ReadZeroSkipWrite` as its default. +/// +/// - Naga's own default is `UndefinedBehavior`, so that shader translations +/// are as faithful to the original as possible. +#[derive(Clone, Copy, Debug)] +pub enum IndexBoundsCheckPolicy { + /// Replace out-of-bounds indexes with some arbitrary in-bounds index. + /// + /// (This does not necessarily mean clamping. For example, interpreting the + /// index as unsigned and taking the minimum with the largest valid index + /// would also be a valid implementation. That would map negative indices to + /// the last element, not the first.) + Restrict, + + /// Out-of-bounds reads return zero, and writes have no effect. + ReadZeroSkipWrite, + + /// Out-of-bounds indexes are undefined behavior. Generate the fastest code + /// possible. This is the default for Naga, as a translator, but consumers + /// should consider defaulting to a safer behavior. + UndefinedBehavior, +} + +/// The default `IndexBoundsCheckPolicy` is `UndefinedBehavior`. +impl Default for IndexBoundsCheckPolicy { + fn default() -> Self { + IndexBoundsCheckPolicy::UndefinedBehavior + } +} + impl crate::Expression { /// Returns the ref count, upon reaching which this expression /// should be considered for baking. diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs new file mode 100644 index 000000000..02495bbef --- /dev/null +++ b/src/back/spv/index.rs @@ -0,0 +1,509 @@ +//! Bounds-checking for SPIR-V output. + +use super::{Block, Error, Function, IdGenerator, Instruction, Word, Writer}; +use crate::{arena::Handle, back::IndexBoundsCheckPolicy, valid::FunctionInfo}; + +/// The results of emitting code for a left-hand-side expression. +/// +/// On success, `write_expression_pointer` returns one of these. +pub(super) enum ExpressionPointer { + /// The pointer to the expression's value is available, as the value of the + /// expression with the given id. + Ready { pointer_id: Word }, + + /// The access expression must be conditional on the value of `condition`, a boolean + /// expression that is true if all indices are in bounds. If `condition` is true, then + /// `access` is an `OpAccessChain` instruction that will compute a pointer to the + /// expression's value. If `condition` is false, then executing `access` would be + /// undefined behavior. + Conditional { + condition: Word, + access: Instruction, + }, +} + +/// The results of performing a bounds check. +/// +/// On success, `write_bounds_check` returns a value of this type. +pub enum BoundsCheckResult { + /// The index is statically known and in bounds, with the given value. + KnownInBounds(u32), + + /// The given instruction computes the index to be used. + Computed(Word), + + /// The given instruction computes a boolean condition which is true + /// if the index is in bounds. + Conditional(Word), +} + +/// A value that we either know at translation time, or need to compute at runtime. +pub enum MaybeKnown { + /// The value is known at shader translation time. + Known(T), + + /// The value is computed by the instruction with the given id. + Computed(Word), +} + +impl Writer { + /// Emit code to compute the length of a run-time array. + /// + /// Given `array`, an expression referring to the final member of a struct, + /// where the member in question is a runtime-sized array, return the + /// instruction id for the array's length. + pub(super) fn write_runtime_array_length( + &mut self, + array: Handle, + ir_function: &crate::Function, + function: &Function, + block: &mut Block, + ) -> Result { + // Look into the expression to find the value and type of the struct + // holding the dynamically-sized array. + let (structure_id, last_member_index) = match ir_function.expressions[array] { + crate::Expression::AccessIndex { base, index } => match ir_function.expressions[base] { + crate::Expression::GlobalVariable(handle) => { + (self.global_variables[handle.index()].id, index) + } + crate::Expression::FunctionArgument(index) => { + let parameter_id = function.parameter_id(index); + (parameter_id, index) + } + _ => return Err(Error::Validation("array length expression")), + }, + _ => return Err(Error::Validation("array length expression")), + }; + + let length_id = self.id_gen.next(); + block.body.push(Instruction::array_length( + self.get_uint_type_id()?, + length_id, + structure_id, + last_member_index, + )); + + Ok(length_id) + } + + /// Compute the length of a subscriptable value. + /// + /// Given `sequence`, an expression referring to some indexable type, return + /// its length. The result may either be computed by SPIR-V instructions, or + /// known at shader translation time. + /// + /// `sequence` may be a `Vector`, `Matrix`, or `Array`, a `Pointer` to any + /// of those, or a `ValuePointer`. An array may be fixed-size, dynamically + /// sized, or use a specializable constant as its length. + fn write_sequence_length( + &mut self, + sequence: Handle, + ir_module: &crate::Module, + ir_function: &crate::Function, + fun_info: &FunctionInfo, + function: &Function, + block: &mut Block, + ) -> Result, Error> { + let sequence_ty = fun_info[sequence].ty.inner_with(&ir_module.types); + match sequence_ty.indexable_length(ir_module)? { + crate::proc::IndexableLength::Known(known_length) => { + Ok(MaybeKnown::Known(known_length)) + } + crate::proc::IndexableLength::Dynamic => { + let length_id = + self.write_runtime_array_length(sequence, ir_function, function, block)?; + Ok(MaybeKnown::Computed(length_id)) + } + crate::proc::IndexableLength::Specializable(constant) => { + let length_id = self.constant_ids[constant.index()]; + Ok(MaybeKnown::Computed(length_id)) + } + } + } + + /// Compute the maximum valid index of a subscriptable value. + /// + /// Given `sequence`, an expression referring to some indexable type, return + /// its maximum valid index - one less than its length. The result may + /// either be computed, or known at shader translation time. + /// + /// `sequence` may be a `Vector`, `Matrix`, or `Array`, a `Pointer` to any + /// of those, or a `ValuePointer`. An array may be fixed-size, dynamically + /// sized, or use a specializable constant as its length. + fn write_sequence_max_index( + &mut self, + sequence: Handle, + ir_module: &crate::Module, + ir_function: &crate::Function, + fun_info: &FunctionInfo, + function: &Function, + block: &mut Block, + ) -> Result, Error> { + match self.write_sequence_length( + sequence, + ir_module, + ir_function, + fun_info, + function, + block, + )? { + MaybeKnown::Known(known_length) => { + // We should have thrown out all attempts to subscript zero-length + // sequences during validation, so the following subtraction should never + // underflow. + assert!(known_length > 0); + // Compute the max index from the length now. + Ok(MaybeKnown::Known(known_length - 1)) + } + MaybeKnown::Computed(length_id) => { + // Emit code to compute the max index from the length. + let const_one_id = self.get_index_constant(1)?; + let max_index_id = self.id_gen.next(); + block.body.push(Instruction::binary( + spirv::Op::ISub, + self.get_uint_type_id()?, + max_index_id, + length_id, + const_one_id, + )); + Ok(MaybeKnown::Computed(max_index_id)) + } + } + } + + /// Restrict an index to be in range for a vector, matrix, or array. + /// + /// This is used to implement `IndexBoundsCheckPolicy::Restrict`. An + /// in-bounds index is left unchanged. An out-of-bounds index is replaced + /// with some arbitrary in-bounds index. Note,this is not necessarily + /// clamping; for example, negative indices might be changed to refer to the + /// last element of the sequence, not the first, as clamping would do. + /// + /// Either return the restricted index value, if known, or add instructions + /// to `block` to compute it, and return the id of the result. See the + /// documentation for `BoundsCheckResult` for details. + /// + /// The `sequence` expression may be a `Vector`, `Matrix`, or `Array`, a + /// `Pointer` to any of those, or a `ValuePointer`. An array may be + /// fixed-size, dynamically sized, or use a specializable constant as its + /// length. + #[allow(clippy::too_many_arguments)] + pub(super) fn write_restricted_index( + &mut self, + sequence: Handle, + index: Handle, + ir_module: &crate::Module, + ir_function: &crate::Function, + fun_info: &FunctionInfo, + function: &Function, + block: &mut Block, + ) -> Result { + let index_id = self.cached[index]; + + // Get the sequence's maximum valid index. Return early if we've already + // done the bounds check. + let max_index_id = match self.write_sequence_max_index( + sequence, + ir_module, + ir_function, + fun_info, + function, + block, + )? { + MaybeKnown::Known(known_max_index) => { + if let crate::Expression::Constant(index_k) = ir_function.expressions[index] { + if let Some(known_index) = ir_module.constants[index_k].to_array_length() { + // Both the index and length are known at compile time. + // + // In strict WGSL compliance mode, out-of-bounds indices cannot be + // reported at shader translation time, and must be replaced with + // in-bounds indices at run time. So we cannot assume that + // validation ensured the index was in bounds. Restrict now. + let restricted = std::cmp::min(known_index, known_max_index); + return Ok(BoundsCheckResult::KnownInBounds(restricted)); + } + } + + self.get_index_constant(known_max_index)? + } + MaybeKnown::Computed(max_index_id) => max_index_id, + }; + + // One or the other of the index or length is dynamic, so emit code for + // IndexBoundsCheckPolicy::Restrict. + let restricted_index_id = self.id_gen.next(); + block.body.push(Instruction::ext_inst( + self.gl450_ext_inst_id, + spirv::GLOp::UMin, + self.get_uint_type_id()?, + restricted_index_id, + &[index_id, max_index_id], + )); + Ok(BoundsCheckResult::Computed(restricted_index_id)) + } + + /// Write an index bounds comparison to `block`, if needed. + /// + /// If we're able to determine statically that `index` is in bounds for + /// `sequence`, return `KnownInBounds(value)`, where `value` is the actual + /// value of the index. (In principle, one could know that the index is in + /// bounds without knowing its specific value, but in our simple-minded + /// situation, we always know it.) + /// + /// If instead we must generate code to perform the comparison at run time, + /// return `Conditional(comparison_id)`, where `comparison_id` is an + /// instruction producing a boolean value that is true if `index` is in + /// bounds for `sequence`. + /// + /// The `sequence` expression may be a `Vector`, `Matrix`, or `Array`, a + /// `Pointer` to any of those, or a `ValuePointer`. An array may be + /// fixed-size, dynamically sized, or use a specializable constant as its + /// length. + #[allow(clippy::too_many_arguments)] + fn write_index_comparison( + &mut self, + sequence: Handle, + index: Handle, + ir_module: &crate::Module, + ir_function: &crate::Function, + fun_info: &FunctionInfo, + function: &mut Function, + block: &mut Block, + ) -> Result { + let index_id = self.cached[index]; + + // Get the sequence's length. Return early if we've already done the + // bounds check. + let length_id = match self.write_sequence_length( + sequence, + ir_module, + ir_function, + fun_info, + function, + block, + )? { + MaybeKnown::Known(known_length) => { + if let crate::Expression::Constant(index_k) = ir_function.expressions[index] { + if let Some(known_index) = ir_module.constants[index_k].to_array_length() { + // Both the index and length are known at compile time. + // + // It would be nice to assume that, since we are using the + // `ReadZeroSkipWrite` policy, we are not in strict WGSL + // compliance mode, and thus we can count on the validator to have + // rejected any programs with known out-of-bounds indices, and + // thus just return `KnownInBounds` here without actually + // checking. + // + // But it's also reasonable to expect that bounds check policies + // and error reporting policies should be able to vary + // independently without introducing security holes. So, we should + // support the case where bad indices do not cause validation + // errors, and are handled via `ReadZeroSkipWrite`. + // + // In theory, when `known_index` is bad, we could return a new + // `KnownOutOfBounds` variant here. But it's simpler just to fall + // through and let the bounds check take place. The shader is + // broken anyway, so it doesn't make sense to invest in emitting + // the ideal code for it. + if known_index < known_length { + return Ok(BoundsCheckResult::KnownInBounds(known_index)); + } + } + } + + self.get_index_constant(known_length)? + } + MaybeKnown::Computed(length_id) => length_id, + }; + + // Compare the index against the length. + let condition_id = self.id_gen.next(); + block.body.push(Instruction::binary( + spirv::Op::ULessThan, + self.get_bool_type_id()?, + condition_id, + index_id, + length_id, + )); + + // Indicate that we did generate the check. + Ok(BoundsCheckResult::Conditional(condition_id)) + } + + /// Emit a conditional load for `IndexBoundsCheckPolicy::ReadZeroSkipWrite`. + /// + /// Generate code to load a value of `result_type` if `condition` is true, + /// and generate a null value of that type if it is false. Call `emit_load` + /// to emit the instructions to perform the load. Return the id of the + /// merged value of the two branches. + pub(super) fn write_conditional_indexed_load( + &mut self, + result_type: Word, + condition: Word, + function: &mut Function, + block: &mut Block, + emit_load: F, + ) -> Word + where + F: FnOnce(&mut IdGenerator, &mut Block) -> Word, + { + let header_block = block.label_id; + let merge_block = self.id_gen.next(); + let in_bounds_block = self.id_gen.next(); + + // Branch based on whether the index was in bounds. + // + // As it turns out, our out-of-bounds branch block would contain no + // instructions: it just produces a constant zero, whose instruction is + // in the module's declarations section at the front. In this case, + // SPIR-V lets us omit the empty 'else' block, and branch directly to + // the merge block. The phi instruction in the merge block can cite the + // header block as its CFG predecessor. + block.body.push(Instruction::selection_merge( + merge_block, + spirv::SelectionControl::NONE, + )); + function.consume( + std::mem::replace(block, Block::new(in_bounds_block)), + Instruction::branch_conditional(condition, in_bounds_block, merge_block), + ); + + // The in-bounds path. Perform the access and the load. + let value_id = emit_load(&mut self.id_gen, block); + + // Finish the in-bounds block and start the merge block. This + // is the block we'll leave current on return. + function.consume( + std::mem::replace(block, Block::new(merge_block)), + Instruction::branch(merge_block), + ); + + // For the out-of-bounds case, produce a zero value. + let null_id = self.write_constant_null(result_type); + + // Merge the results from the two paths. + let result_id = self.id_gen.next(); + block.body.push(Instruction::phi( + result_type, + result_id, + &[(value_id, in_bounds_block), (null_id, header_block)], + )); + + result_id + } + + /// Emit code for bounds checks, per self.index_bounds_check_policy. + /// + /// Return a `BoundsCheckResult` indicating how the index should be + /// consumed. See that type's documentation for details. + #[allow(clippy::too_many_arguments)] + pub(super) fn write_bounds_check( + &mut self, + ir_module: &crate::Module, + ir_function: &crate::Function, + fun_info: &FunctionInfo, + function: &mut Function, + base: Handle, + index: Handle, + block: &mut Block, + ) -> Result { + Ok(match self.index_bounds_check_policy { + IndexBoundsCheckPolicy::Restrict => self.write_restricted_index( + base, + index, + ir_module, + ir_function, + fun_info, + function, + block, + )?, + IndexBoundsCheckPolicy::ReadZeroSkipWrite => self.write_index_comparison( + base, + index, + ir_module, + ir_function, + fun_info, + function, + block, + )?, + IndexBoundsCheckPolicy::UndefinedBehavior => { + BoundsCheckResult::Computed(self.cached[index]) + } + }) + } + + /// Emit code to subscript a vector by value with a computed index. + /// + /// Return the id of the element value. + #[allow(clippy::too_many_arguments)] + pub(super) fn write_vector_access( + &mut self, + ir_module: &crate::Module, + ir_function: &crate::Function, + fun_info: &FunctionInfo, + function: &mut Function, + expr_handle: Handle, + base: Handle, + index: Handle, + block: &mut Block, + ) -> Result { + let result_type_id = self.get_expression_type_id(&fun_info[expr_handle].ty)?; + + let base_id = self.cached[base]; + let index_id = self.cached[index]; + + let result_id = match self.write_bounds_check( + ir_module, + ir_function, + fun_info, + function, + base, + index, + block, + )? { + BoundsCheckResult::KnownInBounds(known_index) => { + let result_id = self.id_gen.next(); + block.body.push(Instruction::composite_extract( + result_type_id, + result_id, + base_id, + &[known_index], + )); + result_id + } + BoundsCheckResult::Computed(computed_index_id) => { + let result_id = self.id_gen.next(); + block.body.push(Instruction::vector_extract_dynamic( + result_type_id, + result_id, + base_id, + computed_index_id, + )); + result_id + } + BoundsCheckResult::Conditional(comparison_id) => { + // Run-time bounds checks were required. Emit + // conditional load. + self.write_conditional_indexed_load( + result_type_id, + comparison_id, + function, + block, + |id_gen, block| { + // The in-bounds path. Generate the access. + let element_id = id_gen.next(); + block.body.push(Instruction::vector_extract_dynamic( + result_type_id, + element_id, + base_id, + index_id, + )); + element_id + }, + ) + } + }; + + Ok(result_id) + } +} diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 21948d1bc..97fe602dd 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -758,6 +758,21 @@ impl super::Instruction { // Control-Flow Instructions // + pub(super) fn phi( + result_type_id: Word, + result_id: Word, + var_parent_pairs: &[(Word, Word)], + ) -> Self { + let mut instruction = Self::new(Op::Phi); + instruction.add_operand(result_type_id); + instruction.add_operand(result_id); + for &(variable, parent) in var_parent_pairs { + instruction.add_operand(variable); + instruction.add_operand(parent); + } + instruction + } + pub(super) fn selection_merge( merge_id: Word, selection_control: spirv::SelectionControl, diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index c579f0546..daabc4c4e 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -2,13 +2,14 @@ !*/ mod helpers; +mod index; mod instructions; mod layout; mod writer; pub use spirv::Capability; -use crate::arena::Handle; +use crate::{arena::Handle, back::IndexBoundsCheckPolicy}; use spirv::Word; use std::ops; @@ -57,6 +58,8 @@ pub enum Error { FeatureNotImplemented(&'static str), #[error("module is not validated properly: {0}")] Validation(&'static str), + #[error(transparent)] + Proc(#[from] crate::proc::ProcError), } #[derive(Default)] @@ -110,6 +113,20 @@ struct Function { entry_point_context: Option, } +impl Function { + fn consume(&mut self, mut block: Block, termination: Instruction) { + block.termination = Some(termination); + self.blocks.push(block); + } + + fn parameter_id(&self, index: u32) -> Word { + match self.entry_point_context { + Some(ref context) => context.argument_ids[index as usize], + None => self.parameters[index as usize].result_id.unwrap(), + } + } +} + #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LocalType { Value { @@ -211,7 +228,8 @@ pub struct Writer { debugs: Vec, annotations: Vec, flags: WriterFlags, - void_type: u32, + index_bounds_check_policy: IndexBoundsCheckPolicy, + void_type: Word, //TODO: convert most of these into vectors, addressable by handle indices lookup_type: crate::FastHashMap, lookup_function: crate::FastHashMap, Word>, @@ -245,6 +263,9 @@ pub struct Options { // Note: there is a major bug currently associated with deriving the capabilities. // We are calling `required_capabilities`, but the semantics of this is broken. pub capabilities: Option>, + /// How should the generated code handle array, vector, or matrix indices + /// that are out of range? + pub index_bounds_check_policy: IndexBoundsCheckPolicy, } impl Default for Options { @@ -257,6 +278,7 @@ impl Default for Options { lang_version: (1, 0), flags, capabilities: None, + index_bounds_check_policy: super::IndexBoundsCheckPolicy::default(), } } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index abcce32e2..1053fb94e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,5 +1,6 @@ use super::{ helpers::{contains_builtin, map_storage_class}, + index::{BoundsCheckResult, ExpressionPointer}, Block, CachedExpressions, Dimension, EntryPointContext, Error, Function, GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, LogicalLayout, LookupFunctionType, LookupType, Options, PhysicalLayout, ResultMember, Writer, WriterFlags, BITS_PER_BYTE, @@ -49,11 +50,6 @@ impl Function { block.termination.as_ref().unwrap().to_words(sink); } } - - fn consume(&mut self, mut block: Block, termination: Instruction) { - block.termination = Some(termination); - self.blocks.push(block); - } } impl PhysicalLayout { @@ -146,6 +142,7 @@ impl Writer { debugs: vec![], annotations: vec![], flags: options.flags, + index_bounds_check_policy: options.index_bounds_check_policy, void_type, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), @@ -189,7 +186,7 @@ impl Writer { } } - fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Result { + pub(super) fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Result { let lookup_ty = match *tr { TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), TypeResolution::Value(ref inner) => { @@ -224,6 +221,26 @@ impl Writer { }) } + pub(super) fn get_uint_type_id(&mut self) -> Result { + let local_type = LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Uint, + width: 4, + pointer_class: None, + }; + self.get_type_id(local_type.into()) + } + + pub(super) fn get_bool_type_id(&mut self) -> Result { + let local_type = LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Bool, + width: 1, + pointer_class: None, + }; + self.get_type_id(local_type.into()) + } + fn decorate(&mut self, id: Word, decoration: spirv::Decoration, operands: &[Word]) { self.annotations .push(Instruction::decorate(id, decoration, operands)); @@ -798,7 +815,7 @@ impl Writer { Ok(id) } - fn get_index_constant(&mut self, index: Word) -> Result { + pub(super) fn get_index_constant(&mut self, index: Word) -> Result { self.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) } @@ -905,7 +922,7 @@ impl Writer { Ok(()) } - fn write_constant_null(&mut self, type_id: Word) -> Word { + pub(super) fn write_constant_null(&mut self, type_id: Word) -> Word { let null_id = self.id_gen.next(); Instruction::constant_null(type_id, null_id) .to_words(&mut self.logical_layout.declarations); @@ -1199,33 +1216,31 @@ impl Writer { 0 } crate::Expression::Access { base, index } => { - let index_id = self.cached[index]; - let base_id = self.cached[base]; - match *fun_info[base].ty.inner_with(&ir_module.types) { - crate::TypeInner::Vector { .. } => { - let id = self.id_gen.next(); - block.body.push(Instruction::vector_extract_dynamic( - result_type_id, - id, - base_id, - index_id, - )); - id - } - crate::TypeInner::Array { .. } => { - return Err(Error::Validation( - "dynamic indexing of arrays not permitted", - )); - } + let base_ty = fun_info[base].ty.inner_with(&ir_module.types); + match *base_ty { + crate::TypeInner::Vector { .. } => (), ref other => { log::error!( "Unable to access base {:?} of type {:?}", ir_function.expressions[base], other ); - return Err(Error::FeatureNotImplemented("access for type")); + return Err(Error::Validation( + "only vectors may be dynamically indexed by value", + )); } - } + }; + + self.write_vector_access( + ir_module, + ir_function, + fun_info, + function, + expr_handle, + base, + index, + block, + )? } crate::Expression::AccessIndex { base, index: _ } if self.is_intermediate(base, ir_function, &ir_module.types) => @@ -1609,19 +1624,45 @@ impl Writer { } crate::Expression::LocalVariable(variable) => function.variables[&variable].id, crate::Expression::Load { pointer } => { - let pointer_id = - self.write_expression_pointer(ir_function, fun_info, pointer, block, function)?; - - let id = self.id_gen.next(); - block - .body - .push(Instruction::load(result_type_id, id, pointer_id, None)); - id + match self.write_expression_pointer( + ir_module, + ir_function, + fun_info, + pointer, + block, + function, + )? { + ExpressionPointer::Ready { pointer_id } => { + let id = self.id_gen.next(); + block + .body + .push(Instruction::load(result_type_id, id, pointer_id, None)); + id + } + ExpressionPointer::Conditional { condition, access } => { + self.write_conditional_indexed_load( + result_type_id, + condition, + function, + block, + move |id_gen, block| { + // The in-bounds path. Perform the access and the load. + let pointer_id = access.result_id.unwrap(); + let value_id = id_gen.next(); + block.body.push(access); + block.body.push(Instruction::load( + result_type_id, + value_id, + pointer_id, + None, + )); + value_id + }, + ) + } + } } - crate::Expression::FunctionArgument(index) => match function.entry_point_context { - Some(ref context) => context.argument_ids[index as usize], - None => function.parameters[index as usize].result_id.unwrap(), - }, + crate::Expression::FunctionArgument(index) => function.parameter_id(index), crate::Expression::Call(_function) => self.lookup_function_call[&expr_handle], crate::Expression::As { expr, @@ -2079,36 +2120,7 @@ impl Writer { id } crate::Expression::ArrayLength(expr) => { - let (structure_id, member_idx) = match ir_function.expressions[expr] { - crate::Expression::AccessIndex { base, .. } => { - match ir_function.expressions[base] { - crate::Expression::GlobalVariable(handle) => { - let global = &ir_module.global_variables[handle]; - let last_idx = match ir_module.types[global.ty].inner { - crate::TypeInner::Struct { ref members, .. } => { - members.len() as u32 - 1 - } - _ => return Err(Error::Validation("array length expression")), - }; - - (self.global_variables[handle.index()].id, last_idx) - } - _ => return Err(Error::Validation("array length expression")), - } - } - _ => return Err(Error::Validation("array length expression")), - }; - - // let structure_id = self.get_expression_global(ir_function, global); - let id = self.id_gen.next(); - - block.body.push(Instruction::array_length( - result_type_id, - id, - structure_id, - member_idx, - )); - id + self.write_runtime_array_length(expr, ir_function, function, block)? } }; @@ -2116,15 +2128,21 @@ impl Writer { Ok(()) } - /// Write a left-hand-side expression, returning an `id` of the pointer. + /// Build an `OpAccessChain` instruction for a left-hand-side expression. + /// + /// Emit any needed bounds-checking expressions to `block`. + /// + /// On success, the return value is an [`ExpressionPointer`] value; see the + /// documentation for that type. fn write_expression_pointer( &mut self, + ir_module: &crate::Module, ir_function: &crate::Function, fun_info: &FunctionInfo, mut expr_handle: Handle, block: &mut Block, function: &mut Function, - ) -> Result { + ) -> Result { let result_lookup_ty = match fun_info[expr_handle].ty { TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), TypeResolution::Value(ref inner) => { @@ -2133,12 +2151,60 @@ impl Writer { }; let result_type_id = self.get_type_id(result_lookup_ty)?; + // The id of the boolean `and` of all dynamic bounds checks up to this point. If + // `None`, then we haven't done any dynamic bounds checks yet. + // + // When we have a chain of bounds checks, we combine them with `OpLogicalAnd`, not + // a short-circuit branch. This means we might do comparisons we don't need to, + // but we expect these checks to almost always succeed, and keeping branches to a + // minimum is essential. + let mut accumulated_checks = None; + self.temp_list.clear(); let root_id = loop { expr_handle = match ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { - let index_id = self.cached[index]; + let index_id = match self.write_bounds_check( + ir_module, + ir_function, + fun_info, + function, + base, + index, + block, + )? { + BoundsCheckResult::KnownInBounds(known_index) => { + // Even if the index is known, `OpAccessIndex` + // requires expression operands, not literals. + let scalar = crate::ScalarValue::Uint(known_index as u64); + self.get_constant_scalar(scalar, 4)? + } + BoundsCheckResult::Computed(computed_index_id) => computed_index_id, + BoundsCheckResult::Conditional(comparison_id) => { + match accumulated_checks { + Some(prior_checks) => { + let combined = self.id_gen.next(); + block.body.push(Instruction::binary( + spirv::Op::LogicalAnd, + self.get_bool_type_id()?, + combined, + prior_checks, + comparison_id, + )); + accumulated_checks = Some(combined); + } + None => { + // Start a fresh chain of checks. + accumulated_checks = Some(comparison_id); + } + } + + // Either way, the index to use is unchanged. + self.cached[index] + } + }; self.temp_list.push(index_id); + base } crate::Expression::AccessIndex { base, index } => { @@ -2162,20 +2228,30 @@ impl Writer { } }; - let id = if self.temp_list.is_empty() { - root_id + let pointer = if self.temp_list.is_empty() { + ExpressionPointer::Ready { + pointer_id: root_id, + } } else { self.temp_list.reverse(); - let id = self.id_gen.next(); - block.body.push(Instruction::access_chain( - result_type_id, - id, - root_id, - &self.temp_list, - )); - id + let pointer_id = self.id_gen.next(); + let access = + Instruction::access_chain(result_type_id, pointer_id, root_id, &self.temp_list); + + // If we generated some bounds checks, we need to leave it to our + // caller to generate the branch, the access, the load or store, and + // the zero value (for loads). Otherwise, we can emit the access + // ourselves, and just hand them the id of the pointer. + match accumulated_checks { + Some(condition) => ExpressionPointer::Conditional { condition, access }, + None => { + block.body.push(access); + ExpressionPointer::Ready { pointer_id } + } + } }; - Ok(id) + + Ok(pointer) } fn get_expression_global( @@ -2539,18 +2615,53 @@ impl Writer { )); } crate::Statement::Store { pointer, value } => { - let pointer_id = self.write_expression_pointer( + let value_id = self.cached[value]; + match self.write_expression_pointer( + ir_module, ir_function, fun_info, pointer, &mut block, function, - )?; - let value_id = self.cached[value]; + )? { + ExpressionPointer::Ready { pointer_id } => { + block + .body + .push(Instruction::store(pointer_id, value_id, None)); + } + ExpressionPointer::Conditional { condition, access } => { + let merge_block = self.id_gen.next(); + let in_bounds_block = self.id_gen.next(); - block - .body - .push(Instruction::store(pointer_id, value_id, None)); + // Emit the conditional branch. + block.body.push(Instruction::selection_merge( + merge_block, + spirv::SelectionControl::NONE, + )); + function.consume( + std::mem::replace(&mut block, Block::new(in_bounds_block)), + Instruction::branch_conditional( + condition, + in_bounds_block, + merge_block, + ), + ); + + // The in-bounds path. Perform the access and the store. + let pointer_id = access.result_id.unwrap(); + block.body.push(access); + block + .body + .push(Instruction::store(pointer_id, value_id, None)); + + // Finish the in-bounds block and start the merge block. This + // is the block we'll leave current on return. + function.consume( + std::mem::replace(&mut block, Block::new(merge_block)), + Instruction::branch(merge_block), + ); + } + }; } crate::Statement::ImageStore { image, diff --git a/src/proc/index.rs b/src/proc/index.rs new file mode 100644 index 000000000..69dd6c2bb --- /dev/null +++ b/src/proc/index.rs @@ -0,0 +1,79 @@ +//! Definitions for index bounds checking. + +use super::ProcError; + +impl crate::TypeInner { + /// Return the length of a subscriptable type. + /// + /// The `self` parameter should be a handle to a vector, matrix, or array + /// type, a pointer to one of those, or a value pointer. Arrays may be + /// fixed-size, dynamically sized, or sized by a specializable constant. + /// + /// The value returned is appropriate for bounds checks on subscripting. + /// + /// Return an error if `self` does not describe a subscriptable type at all. + pub fn indexable_length(&self, module: &crate::Module) -> Result { + use crate::TypeInner as Ti; + let known_length = match *self { + Ti::Vector { size, .. } => size as _, + Ti::Matrix { columns, .. } => columns as _, + Ti::Array { size, .. } => { + return size.to_indexable_length(module); + } + Ti::ValuePointer { + size: Some(size), .. + } => size as _, + Ti::Pointer { base, .. } => { + // When assigning types to expressions, ResolveContext::Resolve + // does a separate sub-match here instead of a full recursion, + // so we'll do the same. + let base_inner = &module.types[base].inner; + match *base_inner { + Ti::Vector { size, .. } => size as _, + Ti::Matrix { columns, .. } => columns as _, + Ti::Array { size, .. } => return size.to_indexable_length(module), + _ => return Err(ProcError::TypeNotIndexable), + } + } + _ => return Err(ProcError::TypeNotIndexable), + }; + Ok(IndexableLength::Known(known_length)) + } +} + +/// The number of elements in an indexable type. +/// +/// This summarizes the length of vectors, matrices, and arrays in a way that is +/// convenient for indexing and bounds-checking code. +pub enum IndexableLength { + /// Values of this type always have the given number of elements. + Known(u32), + + /// The value of the given specializable constant is the number of elements. + /// (Non-specializable constants are reported as `Known`.) + Specializable(crate::Handle), + + /// The number of elements is determined at runtime. + Dynamic, +} + +impl crate::ArraySize { + pub fn to_indexable_length(self, module: &crate::Module) -> Result { + use crate::Constant as K; + Ok(match self { + Self::Constant(k) => match module.constants[k] { + K { + specialization: Some(_), + .. + } => IndexableLength::Specializable(k), + ref unspecialized => { + let length = unspecialized + .to_array_length() + .ok_or(ProcError::InvalidArraySizeConstant(k))?; + IndexableLength::Known(length) + } + }, + Self::Dynamic => IndexableLength::Dynamic, + }) + } +} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index a524981f5..b19fe6a47 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,16 +1,26 @@ //! Module processing functionality. +mod index; mod interpolator; mod layouter; mod namer; mod terminator; mod typifier; +pub use index::IndexableLength; pub use layouter::{Alignment, InvalidBaseType, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, TypeResolution}; +#[derive(Clone, Debug, thiserror::Error, PartialEq)] +pub enum ProcError { + #[error("type is not indexable, and has no length (validation error)")] + TypeNotIndexable, + #[error("array length is wrong kind of constant (validation error)")] + InvalidArraySizeConstant(crate::Handle), +} + impl From for super::ScalarKind { fn from(format: super::StorageFormat) -> Self { use super::{ScalarKind as Sk, StorageFormat as Sf}; @@ -217,7 +227,19 @@ impl crate::SampleLevel { } impl crate::Constant { - pub fn to_array_length(&self) -> Option { + /// Interpret this constant as an array length, and return it as a `u32`. + /// + /// Ignore any specialization available for this constant; return its + /// unspecialized value. + /// + /// If the constant has an inappropriate kind (non-scalar or non-integer) or + /// value (negative, out of range for u32), return `None`. This usually + /// indicates an error, but only the caller has enough information to report + /// the error helpfully: in back ends, it's a validation error, but in front + /// ends, it may indicate ill-formed input (for example, a SPIR-V + /// `OpArrayType` referring to an inappropriate `OpConstant`). So we return + /// `Option` and let the caller sort things out. + pub(crate) fn to_array_length(&self) -> Option { use std::convert::TryInto; match self.inner { crate::ConstantInner::Scalar { value, width: _ } => match value { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 561a088a7..a4035fede 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,7 +1,7 @@ use super::{compose::validate_compose, ComposeError, FunctionInfo, ShaderStages, TypeFlags}; use crate::{ arena::{Arena, Handle}, - proc::ResolveError, + proc::{ProcError, ResolveError}, }; #[derive(Clone, Debug, thiserror::Error)] @@ -17,8 +17,8 @@ pub enum ExpressionError { InvalidBaseType(Handle), #[error("Accessing with index {0:?} can't be done")] InvalidIndexType(Handle), - #[error("Accessing index {1} is out of {0:?} bounds")] - IndexOutOfBounds(Handle, u32), + #[error("Accessing index {1:?} is out of {0:?} bounds")] + IndexOutOfBounds(Handle, crate::ScalarValue), #[error("The expression {0:?} may only be indexed by a constant")] IndexMustBeConstant(Handle), #[error("Function argument {0:?} doesn't exist")] @@ -41,6 +41,8 @@ pub enum ExpressionError { InvalidSwizzleComponent(crate::SwizzleComponent, crate::VectorSize), #[error(transparent)] Compose(#[from] ComposeError), + #[error(transparent)] + Proc(#[from] ProcError), #[error("Operation {0:?} can't work with {1:?}")] InvalidUnaryOperandType(crate::UnaryOperator, Handle), #[error("Operation {0:?} can't work with {1:?} and {2:?}")] @@ -144,8 +146,9 @@ impl super::Validator { let stages = match *expression { E::Access { base, index } => { + let base_type = resolver.resolve(base)?; // See the documentation for `Expression::Access`. - let dynamic_indexing_restricted = match *resolver.resolve(base)? { + let dynamic_indexing_restricted = match *base_type { Ti::Vector { .. } => false, Ti::Matrix { .. } | Ti::Array { .. } => true, Ti::Pointer { .. } | Ti::ValuePointer { size: Some(_), .. } => false, @@ -174,6 +177,36 @@ impl super::Validator { { return Err(ExpressionError::IndexMustBeConstant(base)); } + + // If we know both the length and the index, we can do the + // bounds check now. + if let crate::proc::IndexableLength::Known(known_length) = + base_type.indexable_length(module)? + { + if let E::Constant(k) = function.expressions[index] { + if let crate::Constant { + // We must treat specializable constants as unknown. + specialization: None, + // Non-scalar indices should have been caught above. + inner: crate::ConstantInner::Scalar { value, .. }, + .. + } = module.constants[k] + { + match value { + crate::ScalarValue::Uint(u) if u >= known_length as u64 => { + return Err(ExpressionError::IndexOutOfBounds(base, value)); + } + crate::ScalarValue::Sint(s) + if s < 0 || s >= known_length as i64 => + { + return Err(ExpressionError::IndexOutOfBounds(base, value)); + } + _ => (), + } + } + } + } + ShaderStages::all() } E::AccessIndex { base, index } => { @@ -208,7 +241,10 @@ impl super::Validator { let limit = resolve_index_limit(module, base, resolver.resolve(base)?, true)?; if index >= limit { - return Err(ExpressionError::IndexOutOfBounds(base, index)); + return Err(ExpressionError::IndexOutOfBounds( + base, + crate::ScalarValue::Uint(limit as _), + )); } ShaderStages::all() } diff --git a/src/valid/type.rs b/src/valid/type.rs index abcd268c1..7ddc0f6aa 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -52,6 +52,8 @@ pub enum TypeError { InvalidArrayBaseType(Handle), #[error("The constant {0:?} can not be used for an array size")] InvalidArraySizeConstant(Handle), + #[error("Array type {0:?} must have a length of one or more")] + NonPositiveArrayLength(Handle), #[error("Array stride {stride} is smaller than the base element size {base_size}")] InsufficientArrayStride { stride: u32, base_size: u32 }, #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] @@ -288,15 +290,15 @@ impl super::Validator { let sized_flag = match size { crate::ArraySize::Constant(const_handle) => { - match constants.try_get(const_handle) { + let length_is_positive = match constants.try_get(const_handle) { Some(&crate::Constant { inner: crate::ConstantInner::Scalar { width: _, - value: crate::ScalarValue::Uint(_), + value: crate::ScalarValue::Uint(length), }, .. - }) => {} + }) => length > 0, // Accept a signed integer size to avoid // requiring an explicit uint // literal. Type inference should make @@ -305,14 +307,18 @@ impl super::Validator { inner: crate::ConstantInner::Scalar { width: _, - value: crate::ScalarValue::Sint(_), + value: crate::ScalarValue::Sint(length), }, .. - }) => {} + }) => length > 0, other => { log::warn!("Array size {:?}", other); return Err(TypeError::InvalidArraySizeConstant(const_handle)); } + }; + + if !length_is_positive { + return Err(TypeError::NonPositiveArrayLength(const_handle)); } TypeFlags::SIZED diff --git a/tests/in/bounds-check-zero.param.ron b/tests/in/bounds-check-zero.param.ron new file mode 100644 index 000000000..e6fc09bf4 --- /dev/null +++ b/tests/in/bounds-check-zero.param.ron @@ -0,0 +1,4 @@ +( + bounds_check_read_zero_skip_write: true, + spv_version: (1, 1), +) diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl new file mode 100644 index 000000000..773a1788f --- /dev/null +++ b/tests/in/bounds-check-zero.wgsl @@ -0,0 +1,46 @@ +// Tests for `naga::back::IndexBoundsCheckPolicy::ReadZeroSkipWrite`. + +[[block]] +struct Globals { + a: array; + v: vec4; + m: mat3x4; +}; + +[[group(0), binding(0)]] var globals: Globals; + +fn index_array(i: i32) -> f32 { + return globals.a[i]; +} + +fn index_vector(i: i32) -> f32 { + return globals.v[i]; +} + +fn index_vector_by_value(v: vec4, i: i32) -> f32 { + return v[i]; +} + +fn index_matrix(i: i32) -> vec4 { + return globals.m[i]; +} + +fn index_twice(i: i32, j: i32) -> f32 { + return globals.m[i][j]; +} + +fn set_array(i: i32, v: f32) { + globals.a[i] = v; +} + +fn set_vector(i: i32, v: f32) { + globals.v[i] = v; +} + +fn set_matrix(i: i32, v: vec4) { + globals.m[i] = v; +} + +fn set_index_twice(i: i32, j: i32, v: f32) { + globals.m[i][j] = v; +} diff --git a/tests/in/pointer-access.param.ron b/tests/in/pointer-access.param.ron new file mode 100644 index 000000000..a049e71aa --- /dev/null +++ b/tests/in/pointer-access.param.ron @@ -0,0 +1,5 @@ +( + spv_version: (1, 0), + spv_debug: true, + spv_adjust_coordinate_space: true, +) diff --git a/tests/in/pointer-access.spv b/tests/in/pointer-access.spv new file mode 100644 index 0000000000000000000000000000000000000000..ba5664c3a7ad4b4d88069e858c69699126167a69 GIT binary patch literal 664 zcmYk3%}c{T5XGly(`c*Js`Ud@T6^@af_Uhu1uvrDHN++@f@s;Kp#Qli@%@sGxG;G$ zZ|3dW-86%7WMRY1B0JHS)wjT4z);w+u01_G$M>_xI4?e2vdrR_^|G?u=IMEI8I8rdf`_Zp` Lj+N8Hha8_@_)arN literal 0 HcmV?d00001 diff --git a/tests/in/pointer-access.spvasm b/tests/in/pointer-access.spvasm new file mode 100644 index 000000000..bdf572c78 --- /dev/null +++ b/tests/in/pointer-access.spvasm @@ -0,0 +1,57 @@ +;;; Indexing into composite values passed by pointer. + +OpCapability Shader +OpCapability Linkage +OpExtension "SPV_KHR_storage_buffer_storage_class" +OpMemoryModel Logical GLSL450 +OpName %dpa_arg_array "dpa_arg_array" +OpName %dpa_arg_index "dpa_arg_index" +OpName %dpra_arg_struct "dpra_arg_struct" +OpName %dpra_arg_index "dpra_arg_index" +OpDecorate %run_array ArrayStride 4 +OpDecorate %run_struct Block +OpDecorate %dummy_var DescriptorSet 0 +OpDecorate %dummy_var Binding 0 +OpMemberDecorate %run_struct 0 Offset 0 + +%uint = OpTypeInt 32 0 +%uint_ptr = OpTypePointer StorageBuffer %uint +%const_0 = OpConstant %uint 0 +%const_7 = OpConstant %uint 7 + +%array = OpTypeArray %uint %const_7 +%array_ptr = OpTypePointer StorageBuffer %array +%dpa_type = OpTypeFunction %uint %array_ptr %uint + +%run_array = OpTypeRuntimeArray %uint +%run_struct = OpTypeStruct %run_array +%run_struct_ptr = OpTypePointer StorageBuffer %run_struct +%dpra_type = OpTypeFunction %uint %run_struct_ptr %uint + +;;; This makes Naga request SPV_KHR_storage_buffer_storage_class in the output, +;;; too. +%dummy_var = OpVariable %run_struct_ptr StorageBuffer + +;;; Take a pointer to an array of unsigned integers, and an index, +;;; and return the given element of the array. +%dpa = OpFunction %uint None %dpa_type +%dpa_arg_array = OpFunctionParameter %array_ptr +%dpa_arg_index = OpFunctionParameter %uint + + %dpa_label = OpLabel + %elt_ptr = OpAccessChain %uint_ptr %dpa_arg_array %dpa_arg_index + %elt_value = OpLoad %uint %elt_ptr + OpReturnValue %elt_value + OpFunctionEnd + +;;; Take a pointer to a struct containing a run-time array, and an index, and +;;; return the given element of the array. +%dpra = OpFunction %uint None %dpra_type +%dpra_arg_struct = OpFunctionParameter %run_struct_ptr +%dpra_arg_index = OpFunctionParameter %uint + + %dpra_label = OpLabel + %elt_ptr2 = OpAccessChain %uint_ptr %dpra_arg_struct %const_0 %dpra_arg_index + %elt_value2 = OpLoad %uint %elt_ptr2 + OpReturnValue %elt_value2 + OpFunctionEnd diff --git a/tests/out/bounds-check-zero.spvasm b/tests/out/bounds-check-zero.spvasm new file mode 100644 index 000000000..da2a09ec6 --- /dev/null +++ b/tests/out/bounds-check-zero.spvasm @@ -0,0 +1,212 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 135 +OpCapability Shader +OpCapability Linkage +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpDecorate %6 ArrayStride 4 +OpDecorate %9 Block +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 48 +OpMemberDecorate %9 2 Offset 64 +OpMemberDecorate %9 2 ColMajor +OpMemberDecorate %9 2 MatrixStride 16 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 0 +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 10 +%5 = OpTypeFloat 32 +%6 = OpTypeArray %5 %3 +%7 = OpTypeVector %5 4 +%8 = OpTypeMatrix %7 3 +%9 = OpTypeStruct %6 %7 %8 +%11 = OpTypePointer StorageBuffer %9 +%10 = OpVariable %11 StorageBuffer +%15 = OpTypeFunction %5 %4 +%17 = OpTypePointer StorageBuffer %6 +%18 = OpTypePointer StorageBuffer %5 +%20 = OpTypeInt 32 0 +%19 = OpConstant %20 10 +%22 = OpTypeBool +%23 = OpConstant %20 0 +%28 = OpConstantNull %5 +%34 = OpTypePointer StorageBuffer %7 +%35 = OpConstant %20 1 +%38 = OpConstant %20 4 +%43 = OpConstantNull %5 +%49 = OpTypeFunction %5 %7 %4 +%55 = OpConstantNull %5 +%60 = OpTypeFunction %7 %4 +%62 = OpTypePointer StorageBuffer %8 +%63 = OpTypePointer StorageBuffer %7 +%64 = OpConstant %20 3 +%66 = OpConstant %20 2 +%71 = OpConstantNull %7 +%77 = OpTypeFunction %5 %4 %4 +%84 = OpConstantNull %7 +%90 = OpConstantNull %5 +%96 = OpTypeFunction %2 %4 %5 +%107 = OpTypePointer StorageBuffer %5 +%116 = OpTypeFunction %2 %4 %7 +%127 = OpTypeFunction %2 %4 %4 %5 +%14 = OpFunction %5 None %15 +%13 = OpFunctionParameter %4 +%12 = OpLabel +OpBranch %16 +%16 = OpLabel +%21 = OpULessThan %22 %13 %19 +OpSelectionMerge %25 None +OpBranchConditional %21 %26 %25 +%26 = OpLabel +%24 = OpAccessChain %18 %10 %23 %13 +%27 = OpLoad %5 %24 +OpBranch %25 +%25 = OpLabel +%29 = OpPhi %5 %27 %26 %28 %16 +OpReturnValue %29 +OpFunctionEnd +%32 = OpFunction %5 None %15 +%31 = OpFunctionParameter %4 +%30 = OpLabel +OpBranch %33 +%33 = OpLabel +%36 = OpAccessChain %34 %10 %35 +%37 = OpLoad %7 %36 +%39 = OpULessThan %22 %31 %38 +OpSelectionMerge %40 None +OpBranchConditional %39 %41 %40 +%41 = OpLabel +%42 = OpVectorExtractDynamic %5 %37 %31 +OpBranch %40 +%40 = OpLabel +%44 = OpPhi %5 %42 %41 %43 %33 +OpReturnValue %44 +OpFunctionEnd +%48 = OpFunction %5 None %49 +%46 = OpFunctionParameter %7 +%47 = OpFunctionParameter %4 +%45 = OpLabel +OpBranch %50 +%50 = OpLabel +%51 = OpULessThan %22 %47 %38 +OpSelectionMerge %52 None +OpBranchConditional %51 %53 %52 +%53 = OpLabel +%54 = OpVectorExtractDynamic %5 %46 %47 +OpBranch %52 +%52 = OpLabel +%56 = OpPhi %5 %54 %53 %55 %50 +OpReturnValue %56 +OpFunctionEnd +%59 = OpFunction %7 None %60 +%58 = OpFunctionParameter %4 +%57 = OpLabel +OpBranch %61 +%61 = OpLabel +%65 = OpULessThan %22 %58 %64 +OpSelectionMerge %68 None +OpBranchConditional %65 %69 %68 +%69 = OpLabel +%67 = OpAccessChain %63 %10 %66 %58 +%70 = OpLoad %7 %67 +OpBranch %68 +%68 = OpLabel +%72 = OpPhi %7 %70 %69 %71 %61 +OpReturnValue %72 +OpFunctionEnd +%76 = OpFunction %5 None %77 +%74 = OpFunctionParameter %4 +%75 = OpFunctionParameter %4 +%73 = OpLabel +OpBranch %78 +%78 = OpLabel +%79 = OpULessThan %22 %74 %64 +OpSelectionMerge %81 None +OpBranchConditional %79 %82 %81 +%82 = OpLabel +%80 = OpAccessChain %63 %10 %66 %74 +%83 = OpLoad %7 %80 +OpBranch %81 +%81 = OpLabel +%85 = OpPhi %7 %83 %82 %84 %78 +%86 = OpULessThan %22 %75 %38 +OpSelectionMerge %87 None +OpBranchConditional %86 %88 %87 +%88 = OpLabel +%89 = OpVectorExtractDynamic %5 %85 %75 +OpBranch %87 +%87 = OpLabel +%91 = OpPhi %5 %89 %88 %90 %81 +OpReturnValue %91 +OpFunctionEnd +%95 = OpFunction %2 None %96 +%93 = OpFunctionParameter %4 +%94 = OpFunctionParameter %5 +%92 = OpLabel +OpBranch %97 +%97 = OpLabel +%98 = OpULessThan %22 %93 %19 +OpSelectionMerge %100 None +OpBranchConditional %98 %101 %100 +%101 = OpLabel +%99 = OpAccessChain %18 %10 %23 %93 +OpStore %99 %94 +OpBranch %100 +%100 = OpLabel +OpReturn +OpFunctionEnd +%105 = OpFunction %2 None %96 +%103 = OpFunctionParameter %4 +%104 = OpFunctionParameter %5 +%102 = OpLabel +OpBranch %106 +%106 = OpLabel +%108 = OpULessThan %22 %103 %38 +OpSelectionMerge %110 None +OpBranchConditional %108 %111 %110 +%111 = OpLabel +%109 = OpAccessChain %107 %10 %35 %103 +OpStore %109 %104 +OpBranch %110 +%110 = OpLabel +OpReturn +OpFunctionEnd +%115 = OpFunction %2 None %116 +%113 = OpFunctionParameter %4 +%114 = OpFunctionParameter %7 +%112 = OpLabel +OpBranch %117 +%117 = OpLabel +%118 = OpULessThan %22 %113 %64 +OpSelectionMerge %120 None +OpBranchConditional %118 %121 %120 +%121 = OpLabel +%119 = OpAccessChain %63 %10 %66 %113 +OpStore %119 %114 +OpBranch %120 +%120 = OpLabel +OpReturn +OpFunctionEnd +%126 = OpFunction %2 None %127 +%123 = OpFunctionParameter %4 +%124 = OpFunctionParameter %4 +%125 = OpFunctionParameter %5 +%122 = OpLabel +OpBranch %128 +%128 = OpLabel +%129 = OpULessThan %22 %124 %38 +%130 = OpULessThan %22 %123 %64 +%131 = OpLogicalAnd %22 %129 %130 +OpSelectionMerge %133 None +OpBranchConditional %131 %134 %133 +%134 = OpLabel +%132 = OpAccessChain %107 %10 %66 %123 %124 +OpStore %132 %125 +OpBranch %133 +%133 = OpLabel +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/pointer-access.spvasm b/tests/out/pointer-access.spvasm new file mode 100644 index 000000000..ef4b7bbce --- /dev/null +++ b/tests/out/pointer-access.spvasm @@ -0,0 +1,55 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 35 +OpCapability Shader +OpCapability Linkage +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpSource GLSL 450 +OpDecorate %12 ArrayStride 4 +OpDecorate %14 ArrayStride 4 +OpDecorate %15 Block +OpMemberDecorate %15 0 Offset 0 +OpDecorate %17 DescriptorSet 0 +OpDecorate %17 Binding 0 +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 0 +%5 = OpConstant %4 1 +%6 = OpConstant %4 2 +%7 = OpConstant %4 3 +%9 = OpTypeInt 32 0 +%8 = OpConstant %9 0 +%10 = OpConstant %9 7 +%11 = OpTypePointer StorageBuffer %9 +%12 = OpTypeArray %9 %10 +%13 = OpTypePointer StorageBuffer %12 +%14 = OpTypeRuntimeArray %9 +%15 = OpTypeStruct %14 +%16 = OpTypePointer StorageBuffer %15 +%17 = OpVariable %16 StorageBuffer +%22 = OpTypeFunction %9 %13 %9 +%30 = OpTypeFunction %9 %16 %9 +%32 = OpTypePointer StorageBuffer %14 +%21 = OpFunction %9 None %22 +%19 = OpFunctionParameter %13 +%20 = OpFunctionParameter %9 +%18 = OpLabel +OpBranch %23 +%23 = OpLabel +%24 = OpAccessChain %11 %19 %20 +%25 = OpLoad %9 %24 +OpReturnValue %25 +OpFunctionEnd +%29 = OpFunction %9 None %30 +%27 = OpFunctionParameter %16 +%28 = OpFunctionParameter %9 +%26 = OpLabel +OpBranch %31 +%31 = OpLabel +%33 = OpAccessChain %11 %27 %8 %28 +%34 = OpLoad %9 %33 +OpReturnValue %34 +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index c6ebaab81..e009f5696 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -23,6 +23,15 @@ bitflags::bitflags! { struct Parameters { #[serde(default)] god_mode: bool, + + // We can only deserialize `IndexBoundsCheckPolicy` values if `deserialize` + // feature was enabled, but features should not affect snapshot contents, so + // just take the policy as booleans instead. + #[serde(default)] + bounds_check_read_zero_skip_write: bool, + #[serde(default)] + bounds_check_restrict: bool, + #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_version: (u8, u8), #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] @@ -52,6 +61,9 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), }; + if params.bounds_check_restrict && params.bounds_check_read_zero_skip_write { + panic!("select only one bounds check policy"); + } let capabilities = if params.god_mode { naga::valid::Capabilities::all() } else { @@ -143,6 +155,14 @@ fn check_output_spv( } else { Some(params.spv_capabilities.clone()) }, + index_bounds_check_policy: if params.bounds_check_restrict { + naga::back::IndexBoundsCheckPolicy::Restrict + } else if params.bounds_check_read_zero_skip_write { + naga::back::IndexBoundsCheckPolicy::ReadZeroSkipWrite + } else { + naga::back::IndexBoundsCheckPolicy::UndefinedBehavior + }, + ..spv::Options::default() }; let spv = spv::write_vec(module, info, &options).unwrap(); @@ -318,6 +338,7 @@ fn convert_wgsl() { "globals", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, ), + ("bounds-check-zero", Targets::SPIRV), ]; for &(name, targets) in inputs.iter() { @@ -368,6 +389,12 @@ fn convert_spv_shadow() { convert_spv("shadow", true, Targets::IR | Targets::ANALYSIS); } +#[cfg(all(feature = "spv-in", feature = "spv-out"))] +#[test] +fn convert_spv_pointer_access() { + convert_spv("pointer-access", true, Targets::SPIRV); +} + #[cfg(feature = "glsl-in")] fn convert_glsl( name: &str, diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index c1acad6ab..c33000403 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -109,6 +109,25 @@ fn unknown_identifier() { ); } +#[test] +fn negative_index() { + check( + r#" + fn main() -> f32 { + let a = array(0., 1., 2.); + return a[-1]; + } + "#, + r#"error: expected non-negative integer constant expression, found `-1` + ┌─ wgsl:4:26 + │ +4 │ return a[-1]; + │ ^^ expected non-negative integer + +"#, + ); +} + macro_rules! check_validation_error { // We want to support an optional guard expression after the pattern, so // that we can check values we can't match against, like strings. @@ -146,7 +165,13 @@ macro_rules! check_validation_error { } fn validation_error(source: &str) -> Result { - let module = naga::front::wgsl::parse_str(source).expect("expected WGSL parse to succeed"); + let module = match naga::front::wgsl::parse_str(source) { + Ok(module) => module, + Err(err) => { + eprintln!("WGSL parse failed:"); + panic!("{}", err.emit_to_string(source)); + } + }; naga::valid::Validator::new( naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty(), @@ -354,6 +379,22 @@ fn invalid_access() { .. }) } + + check_validation_error! { + r#" + fn main() -> f32 { + let a = array(0., 1., 2.); + return a[3]; + } + "#: + Err(naga::valid::ValidationError::Function { + error: naga::valid::FunctionError::Expression { + error: naga::valid::ExpressionError::IndexOutOfBounds(_, _), + .. + }, + .. + }) + } } #[test] From 6cdd332cef6a069acc050d6c2f857b9a56dd9f5e Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Sat, 19 Jun 2021 01:38:47 +0300 Subject: [PATCH 1001/2212] Reorganize test snapshot folder --- Makefile | 42 ++--- tests/cases/glsl_constant_expression.vert | 9 - tests/cases/glsl_if_preprocessor.vert | 14 -- tests/cases/glsl_phong_lighting.frag | 56 ------ tests/cases/glsl_preprocessor_abuse.vert | 11 -- tests/cases/glsl_vertex_test_shader.vert | 29 --- tests/in/glsl/multiple_entry_points.glsl | 19 ++ .../in/glsl/multiple_entry_points.params.ron | 6 + .../{quad-glsl.glsl => glsl/quad_glsl.frag} | 15 +- tests/in/glsl/quad_glsl.vert | 11 ++ tests/in/pointer-access.spvasm | 57 ------ tests/in/quad-glsl.param.ron | 5 - tests/in/{ => spv}/pointer-access.spv | Bin tests/in/{ => spv}/quad-vert.spv | Bin tests/in/{ => spv}/shadow.spv | Bin tests/out/{ => analysis}/collatz.info.ron | 0 tests/out/{ => analysis}/shadow.info.ron | 0 tests/out/{ => dot}/quad.dot | 0 tests/out/{ => glsl}/boids.Compute.glsl | 0 .../out/{ => glsl}/control-flow.Compute.glsl | 0 tests/out/{ => glsl}/empty.Compute.glsl | 0 tests/out/{ => glsl}/globals.Compute.glsl | 0 .../out/{ => glsl}/interpolate.Fragment.glsl | 0 tests/out/{ => glsl}/interpolate.Vertex.glsl | 0 tests/out/{ => glsl}/quad-vert.Vertex.glsl | 0 tests/out/{ => glsl}/quad.Fragment.glsl | 0 tests/out/{ => glsl}/quad.Vertex.glsl | 0 tests/out/{ => glsl}/shadow.Fragment.glsl | 0 tests/out/{ => glsl}/skybox.Fragment.glsl | 0 tests/out/{ => glsl}/skybox.Vertex.glsl | 0 tests/out/{ => glsl}/standard.Fragment.glsl | 0 tests/out/{ => hlsl}/empty.hlsl | 0 tests/out/{ => hlsl}/empty.hlsl.config | 0 tests/out/{ => hlsl}/quad-vert.hlsl | 0 tests/out/{ => hlsl}/quad-vert.hlsl.config | 0 tests/out/{ => hlsl}/quad.hlsl | 0 tests/out/{ => hlsl}/quad.hlsl.config | 0 tests/out/{ => ir}/collatz.ron | 0 tests/out/{ => ir}/shadow.ron | 0 tests/out/{ => msl}/access.msl | 0 tests/out/{ => msl}/boids.msl | 0 tests/out/{ => msl}/collatz.msl | 0 tests/out/{ => msl}/control-flow.msl | 0 tests/out/{ => msl}/empty.msl | 0 tests/out/{ => msl}/extra.msl | 0 tests/out/{ => msl}/globals.msl | 0 tests/out/{ => msl}/image.msl | 0 tests/out/{ => msl}/interface.msl | 0 tests/out/{ => msl}/interpolate.msl | 0 tests/out/{ => msl}/operators.msl | 0 tests/out/{ => msl}/quad-vert.msl | 0 tests/out/{ => msl}/quad.msl | 0 tests/out/{ => msl}/shadow.msl | 0 tests/out/{ => msl}/skybox.msl | 0 tests/out/{ => msl}/standard.msl | 0 tests/out/operators.Vertex.glsl | 10 -- tests/out/{ => spv}/access.spvasm | 0 tests/out/{ => spv}/boids.spvasm | 0 tests/out/{ => spv}/bounds-check-zero.spvasm | 0 tests/out/{ => spv}/collatz.spvasm | 0 tests/out/{ => spv}/control-flow.spvasm | 0 tests/out/{ => spv}/empty.spvasm | 0 tests/out/{ => spv}/extra.spvasm | 0 tests/out/{ => spv}/globals.spvasm | 0 tests/out/{ => spv}/image.spvasm | 0 tests/out/{ => spv}/interface.spvasm | 0 tests/out/{ => spv}/interpolate.spvasm | 0 tests/out/{ => spv}/operators.spvasm | 0 tests/out/{ => spv}/pointer-access.spvasm | 0 tests/out/{ => spv}/quad.spvasm | 0 tests/out/{ => spv}/shadow.spvasm | 0 tests/out/{ => spv}/skybox.spvasm | 0 tests/out/{ => spv}/standard.spvasm | 0 .../{ => wgsl}/210-bevy-2d-shader-frag.wgsl | 0 .../{ => wgsl}/210-bevy-2d-shader-vert.wgsl | 0 .../out/{ => wgsl}/210-bevy-shader-vert.wgsl | 0 tests/out/{ => wgsl}/246-collatz-comp.wgsl | 0 tests/out/{ => wgsl}/277-casting-vert.wgsl | 0 .../out/{ => wgsl}/280-matrix-cast-vert.wgsl | 0 .../{ => wgsl}/484-preprocessor-if-vert.wgsl | 0 .../800-out-of-bounds-panic-vert.wgsl | 0 .../{ => wgsl}/896-push-constant-vert.wgsl | 0 .../{ => wgsl}/901-lhs-field-select-vert.wgsl | 0 .../931-constant-emitting-vert.wgsl | 0 .../out/{ => wgsl}/932-for-loop-if-vert.wgsl | 0 tests/out/{ => wgsl}/access.wgsl | 0 tests/out/{ => wgsl}/bevy-pbr-frag.wgsl | 0 tests/out/{ => wgsl}/bevy-pbr-vert.wgsl | 0 tests/out/{ => wgsl}/boids.wgsl | 0 tests/out/{ => wgsl}/collatz.wgsl | 0 .../{ => wgsl}/constant-array-size-vert.wgsl | 0 tests/out/{ => wgsl}/control-flow.wgsl | 0 tests/out/{ => wgsl}/empty.wgsl | 0 tests/out/{ => wgsl}/extra.wgsl | 0 tests/out/{ => wgsl}/globals.wgsl | 0 tests/out/{ => wgsl}/image.wgsl | 0 tests/out/{ => wgsl}/interface.wgsl | 0 tests/out/{ => wgsl}/interpolate.wgsl | 0 tests/out/{ => wgsl}/math-functions-vert.wgsl | 0 .../out/wgsl/multiple_entry_points-glsl.wgsl | 53 ++++++ tests/out/{ => wgsl}/operators.wgsl | 0 tests/out/{ => wgsl}/quad-vert.wgsl | 0 tests/out/{ => wgsl}/quad.wgsl | 0 tests/out/wgsl/quad_glsl-frag.wgsl | 18 ++ .../quad_glsl-vert.wgsl} | 24 +-- tests/out/{ => wgsl}/shadow.wgsl | 0 tests/out/{ => wgsl}/skybox.wgsl | 0 tests/out/{ => wgsl}/standard.wgsl | 0 tests/out/{ => wgsl}/swizzle_write-frag.wgsl | 0 tests/snapshots.rs | 169 ++++++++++-------- 110 files changed, 231 insertions(+), 317 deletions(-) delete mode 100644 tests/cases/glsl_constant_expression.vert delete mode 100644 tests/cases/glsl_if_preprocessor.vert delete mode 100644 tests/cases/glsl_phong_lighting.frag delete mode 100644 tests/cases/glsl_preprocessor_abuse.vert delete mode 100644 tests/cases/glsl_vertex_test_shader.vert create mode 100644 tests/in/glsl/multiple_entry_points.glsl create mode 100644 tests/in/glsl/multiple_entry_points.params.ron rename tests/in/{quad-glsl.glsl => glsl/quad_glsl.frag} (57%) create mode 100644 tests/in/glsl/quad_glsl.vert delete mode 100644 tests/in/pointer-access.spvasm delete mode 100644 tests/in/quad-glsl.param.ron rename tests/in/{ => spv}/pointer-access.spv (100%) rename tests/in/{ => spv}/quad-vert.spv (100%) rename tests/in/{ => spv}/shadow.spv (100%) rename tests/out/{ => analysis}/collatz.info.ron (100%) rename tests/out/{ => analysis}/shadow.info.ron (100%) rename tests/out/{ => dot}/quad.dot (100%) rename tests/out/{ => glsl}/boids.Compute.glsl (100%) rename tests/out/{ => glsl}/control-flow.Compute.glsl (100%) rename tests/out/{ => glsl}/empty.Compute.glsl (100%) rename tests/out/{ => glsl}/globals.Compute.glsl (100%) rename tests/out/{ => glsl}/interpolate.Fragment.glsl (100%) rename tests/out/{ => glsl}/interpolate.Vertex.glsl (100%) rename tests/out/{ => glsl}/quad-vert.Vertex.glsl (100%) rename tests/out/{ => glsl}/quad.Fragment.glsl (100%) rename tests/out/{ => glsl}/quad.Vertex.glsl (100%) rename tests/out/{ => glsl}/shadow.Fragment.glsl (100%) rename tests/out/{ => glsl}/skybox.Fragment.glsl (100%) rename tests/out/{ => glsl}/skybox.Vertex.glsl (100%) rename tests/out/{ => glsl}/standard.Fragment.glsl (100%) rename tests/out/{ => hlsl}/empty.hlsl (100%) rename tests/out/{ => hlsl}/empty.hlsl.config (100%) rename tests/out/{ => hlsl}/quad-vert.hlsl (100%) rename tests/out/{ => hlsl}/quad-vert.hlsl.config (100%) rename tests/out/{ => hlsl}/quad.hlsl (100%) rename tests/out/{ => hlsl}/quad.hlsl.config (100%) rename tests/out/{ => ir}/collatz.ron (100%) rename tests/out/{ => ir}/shadow.ron (100%) rename tests/out/{ => msl}/access.msl (100%) rename tests/out/{ => msl}/boids.msl (100%) rename tests/out/{ => msl}/collatz.msl (100%) rename tests/out/{ => msl}/control-flow.msl (100%) rename tests/out/{ => msl}/empty.msl (100%) rename tests/out/{ => msl}/extra.msl (100%) rename tests/out/{ => msl}/globals.msl (100%) rename tests/out/{ => msl}/image.msl (100%) rename tests/out/{ => msl}/interface.msl (100%) rename tests/out/{ => msl}/interpolate.msl (100%) rename tests/out/{ => msl}/operators.msl (100%) rename tests/out/{ => msl}/quad-vert.msl (100%) rename tests/out/{ => msl}/quad.msl (100%) rename tests/out/{ => msl}/shadow.msl (100%) rename tests/out/{ => msl}/skybox.msl (100%) rename tests/out/{ => msl}/standard.msl (100%) delete mode 100644 tests/out/operators.Vertex.glsl rename tests/out/{ => spv}/access.spvasm (100%) rename tests/out/{ => spv}/boids.spvasm (100%) rename tests/out/{ => spv}/bounds-check-zero.spvasm (100%) rename tests/out/{ => spv}/collatz.spvasm (100%) rename tests/out/{ => spv}/control-flow.spvasm (100%) rename tests/out/{ => spv}/empty.spvasm (100%) rename tests/out/{ => spv}/extra.spvasm (100%) rename tests/out/{ => spv}/globals.spvasm (100%) rename tests/out/{ => spv}/image.spvasm (100%) rename tests/out/{ => spv}/interface.spvasm (100%) rename tests/out/{ => spv}/interpolate.spvasm (100%) rename tests/out/{ => spv}/operators.spvasm (100%) rename tests/out/{ => spv}/pointer-access.spvasm (100%) rename tests/out/{ => spv}/quad.spvasm (100%) rename tests/out/{ => spv}/shadow.spvasm (100%) rename tests/out/{ => spv}/skybox.spvasm (100%) rename tests/out/{ => spv}/standard.spvasm (100%) rename tests/out/{ => wgsl}/210-bevy-2d-shader-frag.wgsl (100%) rename tests/out/{ => wgsl}/210-bevy-2d-shader-vert.wgsl (100%) rename tests/out/{ => wgsl}/210-bevy-shader-vert.wgsl (100%) rename tests/out/{ => wgsl}/246-collatz-comp.wgsl (100%) rename tests/out/{ => wgsl}/277-casting-vert.wgsl (100%) rename tests/out/{ => wgsl}/280-matrix-cast-vert.wgsl (100%) rename tests/out/{ => wgsl}/484-preprocessor-if-vert.wgsl (100%) rename tests/out/{ => wgsl}/800-out-of-bounds-panic-vert.wgsl (100%) rename tests/out/{ => wgsl}/896-push-constant-vert.wgsl (100%) rename tests/out/{ => wgsl}/901-lhs-field-select-vert.wgsl (100%) rename tests/out/{ => wgsl}/931-constant-emitting-vert.wgsl (100%) rename tests/out/{ => wgsl}/932-for-loop-if-vert.wgsl (100%) rename tests/out/{ => wgsl}/access.wgsl (100%) rename tests/out/{ => wgsl}/bevy-pbr-frag.wgsl (100%) rename tests/out/{ => wgsl}/bevy-pbr-vert.wgsl (100%) rename tests/out/{ => wgsl}/boids.wgsl (100%) rename tests/out/{ => wgsl}/collatz.wgsl (100%) rename tests/out/{ => wgsl}/constant-array-size-vert.wgsl (100%) rename tests/out/{ => wgsl}/control-flow.wgsl (100%) rename tests/out/{ => wgsl}/empty.wgsl (100%) rename tests/out/{ => wgsl}/extra.wgsl (100%) rename tests/out/{ => wgsl}/globals.wgsl (100%) rename tests/out/{ => wgsl}/image.wgsl (100%) rename tests/out/{ => wgsl}/interface.wgsl (100%) rename tests/out/{ => wgsl}/interpolate.wgsl (100%) rename tests/out/{ => wgsl}/math-functions-vert.wgsl (100%) create mode 100644 tests/out/wgsl/multiple_entry_points-glsl.wgsl rename tests/out/{ => wgsl}/operators.wgsl (100%) rename tests/out/{ => wgsl}/quad-vert.wgsl (100%) rename tests/out/{ => wgsl}/quad.wgsl (100%) create mode 100644 tests/out/wgsl/quad_glsl-frag.wgsl rename tests/out/{quad-glsl.wgsl => wgsl/quad_glsl-vert.wgsl} (51%) rename tests/out/{ => wgsl}/shadow.wgsl (100%) rename tests/out/{ => wgsl}/skybox.wgsl (100%) rename tests/out/{ => wgsl}/standard.wgsl (100%) rename tests/out/{ => wgsl}/swizzle_write-frag.wgsl (100%) diff --git a/Makefile b/Makefile index 016f7a37e..3320d785c 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: all clean validate-spv validate-msl validate-glsl validate-dot validate-wgsl validate-hlsl .SECONDARY: boids.metal quad.metal -SNAPSHOTS_IN=tests/in -SNAPSHOTS_OUT=tests/out +SNAPSHOTS_BASE_IN=tests/in +SNAPSHOTS_BASE_OUT=tests/out all: cargo fmt @@ -11,7 +11,7 @@ all: clean: rm *.metal *.air *.metallib *.vert *.frag *.comp *.spv -%.metal: $(SNAPSHOTS_IN)/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) +%.metal: $(SNAPSHOTS_BASE_IN)/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) cargo run --features wgsl-in,msl-out -- $< $@ %.air: %.metal @@ -20,53 +20,53 @@ clean: %.metallib: %.air xcrun -sdk macosx metallib $< -o $@ -%.dot: $(SNAPSHOTS_IN)/%.wgsl $(wildcard src/*.rs src/front/wgsl/*.rs src/back/dot/*.rs bin/naga.rs) +%.dot: $(SNAPSHOTS_BASE_IN)/%.wgsl $(wildcard src/*.rs src/front/wgsl/*.rs src/back/dot/*.rs bin/naga.rs) cargo run --features wgsl-in,dot-out -- $< $@ %.png: %.dot dot -Tpng $< -o $@ -validate-spv: $(SNAPSHOTS_OUT)/*.spvasm +validate-spv: $(SNAPSHOTS_BASE_OUT)/spv/*.spvasm @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ cat $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ done -validate-msl: $(SNAPSHOTS_OUT)/*.msl +validate-msl: $(SNAPSHOTS_BASE_OUT)/msl/*.msl @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ cat $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ done -validate-glsl: $(SNAPSHOTS_OUT)/*.glsl - @set -e && for file in $(SNAPSHOTS_OUT)/*.Vertex.glsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ +validate-glsl: $(SNAPSHOTS_BASE_OUT)/glsl/*.glsl + @set -e && for file in $(SNAPSHOTS_BASE_OUT)/glsl/*.Vertex.glsl ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"};\ cat $${file} | glslangValidator --stdin -S vert; \ done - @set -e && for file in $(SNAPSHOTS_OUT)/*.Fragment.glsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ + @set -e && for file in $(SNAPSHOTS_BASE_OUT)/glsl/*.Fragment.glsl ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"};\ cat $${file} | glslangValidator --stdin -S frag; \ done - @set -e && for file in $(SNAPSHOTS_OUT)/*.Compute.glsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"};\ + @set -e && for file in $(SNAPSHOTS_BASE_OUT)/glsl/*.Compute.glsl ; do \ + echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"};\ cat $${file} | glslangValidator --stdin -S comp; \ done -validate-dot: $(SNAPSHOTS_OUT)/*.dot +validate-dot: $(SNAPSHOTS_BASE_OUT)/dot/*.dot @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ cat $${file} | dot -o /dev/null; \ done -validate-wgsl: $(SNAPSHOTS_OUT)/*.wgsl +validate-wgsl: $(SNAPSHOTS_BASE_OUT)/wgsl/*.wgsl @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ cargo run $${file}; \ done -validate-hlsl: $(SNAPSHOTS_OUT)/*.hlsl +validate-hlsl: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_OUT)/"}; \ + echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ config="$$(dirname $${file})/$$(basename $${file}).config"; \ vertex=""\ fragment="" \ diff --git a/tests/cases/glsl_constant_expression.vert b/tests/cases/glsl_constant_expression.vert deleted file mode 100644 index 3edd419c1..000000000 --- a/tests/cases/glsl_constant_expression.vert +++ /dev/null @@ -1,9 +0,0 @@ -#version 450 core - -const int N = 5; - -float foo[2+N]; - -void main() { - gl_Position = vec4(1); -} \ No newline at end of file diff --git a/tests/cases/glsl_if_preprocessor.vert b/tests/cases/glsl_if_preprocessor.vert deleted file mode 100644 index 752dde308..000000000 --- a/tests/cases/glsl_if_preprocessor.vert +++ /dev/null @@ -1,14 +0,0 @@ -#version 460 core - -#define TEST 3 -#define TEST_EXPR 2 && 2 - -#if TEST_EXPR - 2 == 0 -#error 0 -#elif TEST_EXPR - 2 == 1 -#error 1 -#elif TEST_EXPR - 2 == 2 -#error 2 -#else -#error You shouldn't do that -#endif diff --git a/tests/cases/glsl_phong_lighting.frag b/tests/cases/glsl_phong_lighting.frag deleted file mode 100644 index 6153f2caf..000000000 --- a/tests/cases/glsl_phong_lighting.frag +++ /dev/null @@ -1,56 +0,0 @@ -#version 450 core - -layout(location=0) in vec3 v_position; -layout(location=1) in vec3 v_color; -layout(location=2) in vec3 v_normal; - -layout(location=0) out vec4 f_color; - -layout(set=0, binding=0) -uniform Globals { - mat4 u_view_proj; - vec3 u_view_position; -}; - -layout(set = 1, binding = 0) uniform Light { - vec3 u_position; - vec3 u_color; -}; - -layout(set=2, binding=0) -uniform Locals { - mat4 u_transform; - vec2 u_min_max; -}; - -layout (set = 2, binding = 1) uniform texture2D t_color; -layout (set = 2, binding = 2) uniform sampler s_color; - -float invLerp(float from, float to, float value){ - return (value - from) / (to - from); -} - -void main() { - vec3 object_color = - texture(sampler2D(t_color,s_color), vec2(invLerp(u_min_max.x,u_min_max.y,length(v_position)),0.0)).xyz; - - float ambient_strength = 0.1; - vec3 ambient_color = u_color * ambient_strength; - - vec3 normal = normalize(v_normal); - vec3 light_dir = normalize(u_position - v_position); - - float diffuse_strength = max(dot(normal, light_dir), 0.0); - vec3 diffuse_color = u_color * diffuse_strength; - - vec3 view_dir = normalize(u_view_position - v_position); - vec3 half_dir = normalize(view_dir + light_dir); - - float specular_strength = pow(max(dot(normal, half_dir), 0.0), 32); - - vec3 specular_color = specular_strength * u_color; - - vec3 result = (ambient_color + diffuse_color + specular_color) * object_color; - - f_color = vec4(result, 1.0); -} diff --git a/tests/cases/glsl_preprocessor_abuse.vert b/tests/cases/glsl_preprocessor_abuse.vert deleted file mode 100644 index f83cc74c4..000000000 --- a/tests/cases/glsl_preprocessor_abuse.vert +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 core - -#define MAIN void main() { -#define V_POSITION layout(location=0) in vec4 a_position; -#define ASSIGN_POSITION gl_Position = a_position; - -V_POSITION - -MAIN - ASSIGN_POSITION -} \ No newline at end of file diff --git a/tests/cases/glsl_vertex_test_shader.vert b/tests/cases/glsl_vertex_test_shader.vert deleted file mode 100644 index b82d34f81..000000000 --- a/tests/cases/glsl_vertex_test_shader.vert +++ /dev/null @@ -1,29 +0,0 @@ -#version 450 core - -layout(location=0) in vec3 a_position; -layout(location=1) in vec3 a_color; -layout(location=2) in vec3 a_normal; - -layout(location=0) out vec3 v_position; -layout(location=1) out vec3 v_color; -layout(location=2) out vec3 v_normal; - -layout(set=0, binding=0) -uniform Globals { - mat4 u_view_proj; - vec3 u_view_position; -}; - -layout(set=2, binding=0) -uniform Locals { - mat4 u_transform; - vec2 U_min_max; -}; - -void main() { - v_color = a_color; - v_normal = a_normal; - - v_position = (u_transform * vec4(a_position, 1.0)).xyz; - gl_Position = u_view_proj * u_transform * vec4(a_position, 1.0); -} diff --git a/tests/in/glsl/multiple_entry_points.glsl b/tests/in/glsl/multiple_entry_points.glsl new file mode 100644 index 000000000..94f6c24be --- /dev/null +++ b/tests/in/glsl/multiple_entry_points.glsl @@ -0,0 +1,19 @@ +#version 450 +// vertex +void vert_main() { + gl_Position = vec4(1.0, 1.0, 1.0, 1.0); +} + +// fragment +layout(location = 0) out vec4 o_color; +void frag_main() { + o_color = vec4(1.0, 1.0, 1.0, 1.0); +} + +//compute +// layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in; +void comp_main() { + if (gl_GlobalInvocationID.x > 1) { + return; + } +} diff --git a/tests/in/glsl/multiple_entry_points.params.ron b/tests/in/glsl/multiple_entry_points.params.ron new file mode 100644 index 000000000..f199d9836 --- /dev/null +++ b/tests/in/glsl/multiple_entry_points.params.ron @@ -0,0 +1,6 @@ +( + spv_version: (1, 0), + glsl_vert_ep_name: Some("vert_main"), + glsl_frag_ep_name: Some("frag_main"), + glsl_comp_ep_name: Some("comp_main"), +) diff --git a/tests/in/quad-glsl.glsl b/tests/in/glsl/quad_glsl.frag similarity index 57% rename from tests/in/quad-glsl.glsl rename to tests/in/glsl/quad_glsl.frag index b8d653206..7c0ebf673 100644 --- a/tests/in/quad-glsl.glsl +++ b/tests/in/glsl/quad_glsl.frag @@ -1,17 +1,4 @@ #version 450 -// vertex -const float c_scale = 1.2; - -layout(location = 0) in vec2 a_pos; -layout(location = 1) in vec2 a_uv; -layout(location = 0) out vec2 v_uv; - -void vert_main() { - v_uv = a_uv; - gl_Position = vec4(c_scale * a_pos, 0.0, 1.0); -} - -// fragment layout(location = 0) in vec2 v_uv; #ifdef TEXTURE layout(set = 0, binding = 0) uniform texture2D u_texture; @@ -19,7 +6,7 @@ layout(set = 0, binding = 1) uniform sampler u_sampler; #endif layout(location = 0) out vec4 o_color; -void frag_main() { +void main() { #ifdef TEXTURE o_color = texture(sampler2D(u_texture, u_sampler), v_uv); #else diff --git a/tests/in/glsl/quad_glsl.vert b/tests/in/glsl/quad_glsl.vert new file mode 100644 index 000000000..aa72a833a --- /dev/null +++ b/tests/in/glsl/quad_glsl.vert @@ -0,0 +1,11 @@ +#version 450 +const float c_scale = 1.2; + +layout(location = 0) in vec2 a_pos; +layout(location = 1) in vec2 a_uv; +layout(location = 0) out vec2 v_uv; + +void main() { + v_uv = a_uv; + gl_Position = vec4(c_scale * a_pos, 0.0, 1.0); +} diff --git a/tests/in/pointer-access.spvasm b/tests/in/pointer-access.spvasm deleted file mode 100644 index bdf572c78..000000000 --- a/tests/in/pointer-access.spvasm +++ /dev/null @@ -1,57 +0,0 @@ -;;; Indexing into composite values passed by pointer. - -OpCapability Shader -OpCapability Linkage -OpExtension "SPV_KHR_storage_buffer_storage_class" -OpMemoryModel Logical GLSL450 -OpName %dpa_arg_array "dpa_arg_array" -OpName %dpa_arg_index "dpa_arg_index" -OpName %dpra_arg_struct "dpra_arg_struct" -OpName %dpra_arg_index "dpra_arg_index" -OpDecorate %run_array ArrayStride 4 -OpDecorate %run_struct Block -OpDecorate %dummy_var DescriptorSet 0 -OpDecorate %dummy_var Binding 0 -OpMemberDecorate %run_struct 0 Offset 0 - -%uint = OpTypeInt 32 0 -%uint_ptr = OpTypePointer StorageBuffer %uint -%const_0 = OpConstant %uint 0 -%const_7 = OpConstant %uint 7 - -%array = OpTypeArray %uint %const_7 -%array_ptr = OpTypePointer StorageBuffer %array -%dpa_type = OpTypeFunction %uint %array_ptr %uint - -%run_array = OpTypeRuntimeArray %uint -%run_struct = OpTypeStruct %run_array -%run_struct_ptr = OpTypePointer StorageBuffer %run_struct -%dpra_type = OpTypeFunction %uint %run_struct_ptr %uint - -;;; This makes Naga request SPV_KHR_storage_buffer_storage_class in the output, -;;; too. -%dummy_var = OpVariable %run_struct_ptr StorageBuffer - -;;; Take a pointer to an array of unsigned integers, and an index, -;;; and return the given element of the array. -%dpa = OpFunction %uint None %dpa_type -%dpa_arg_array = OpFunctionParameter %array_ptr -%dpa_arg_index = OpFunctionParameter %uint - - %dpa_label = OpLabel - %elt_ptr = OpAccessChain %uint_ptr %dpa_arg_array %dpa_arg_index - %elt_value = OpLoad %uint %elt_ptr - OpReturnValue %elt_value - OpFunctionEnd - -;;; Take a pointer to a struct containing a run-time array, and an index, and -;;; return the given element of the array. -%dpra = OpFunction %uint None %dpra_type -%dpra_arg_struct = OpFunctionParameter %run_struct_ptr -%dpra_arg_index = OpFunctionParameter %uint - - %dpra_label = OpLabel - %elt_ptr2 = OpAccessChain %uint_ptr %dpra_arg_struct %const_0 %dpra_arg_index - %elt_value2 = OpLoad %uint %elt_ptr2 - OpReturnValue %elt_value2 - OpFunctionEnd diff --git a/tests/in/quad-glsl.param.ron b/tests/in/quad-glsl.param.ron deleted file mode 100644 index a049e71aa..000000000 --- a/tests/in/quad-glsl.param.ron +++ /dev/null @@ -1,5 +0,0 @@ -( - spv_version: (1, 0), - spv_debug: true, - spv_adjust_coordinate_space: true, -) diff --git a/tests/in/pointer-access.spv b/tests/in/spv/pointer-access.spv similarity index 100% rename from tests/in/pointer-access.spv rename to tests/in/spv/pointer-access.spv diff --git a/tests/in/quad-vert.spv b/tests/in/spv/quad-vert.spv similarity index 100% rename from tests/in/quad-vert.spv rename to tests/in/spv/quad-vert.spv diff --git a/tests/in/shadow.spv b/tests/in/spv/shadow.spv similarity index 100% rename from tests/in/shadow.spv rename to tests/in/spv/shadow.spv diff --git a/tests/out/collatz.info.ron b/tests/out/analysis/collatz.info.ron similarity index 100% rename from tests/out/collatz.info.ron rename to tests/out/analysis/collatz.info.ron diff --git a/tests/out/shadow.info.ron b/tests/out/analysis/shadow.info.ron similarity index 100% rename from tests/out/shadow.info.ron rename to tests/out/analysis/shadow.info.ron diff --git a/tests/out/quad.dot b/tests/out/dot/quad.dot similarity index 100% rename from tests/out/quad.dot rename to tests/out/dot/quad.dot diff --git a/tests/out/boids.Compute.glsl b/tests/out/glsl/boids.Compute.glsl similarity index 100% rename from tests/out/boids.Compute.glsl rename to tests/out/glsl/boids.Compute.glsl diff --git a/tests/out/control-flow.Compute.glsl b/tests/out/glsl/control-flow.Compute.glsl similarity index 100% rename from tests/out/control-flow.Compute.glsl rename to tests/out/glsl/control-flow.Compute.glsl diff --git a/tests/out/empty.Compute.glsl b/tests/out/glsl/empty.Compute.glsl similarity index 100% rename from tests/out/empty.Compute.glsl rename to tests/out/glsl/empty.Compute.glsl diff --git a/tests/out/globals.Compute.glsl b/tests/out/glsl/globals.Compute.glsl similarity index 100% rename from tests/out/globals.Compute.glsl rename to tests/out/glsl/globals.Compute.glsl diff --git a/tests/out/interpolate.Fragment.glsl b/tests/out/glsl/interpolate.Fragment.glsl similarity index 100% rename from tests/out/interpolate.Fragment.glsl rename to tests/out/glsl/interpolate.Fragment.glsl diff --git a/tests/out/interpolate.Vertex.glsl b/tests/out/glsl/interpolate.Vertex.glsl similarity index 100% rename from tests/out/interpolate.Vertex.glsl rename to tests/out/glsl/interpolate.Vertex.glsl diff --git a/tests/out/quad-vert.Vertex.glsl b/tests/out/glsl/quad-vert.Vertex.glsl similarity index 100% rename from tests/out/quad-vert.Vertex.glsl rename to tests/out/glsl/quad-vert.Vertex.glsl diff --git a/tests/out/quad.Fragment.glsl b/tests/out/glsl/quad.Fragment.glsl similarity index 100% rename from tests/out/quad.Fragment.glsl rename to tests/out/glsl/quad.Fragment.glsl diff --git a/tests/out/quad.Vertex.glsl b/tests/out/glsl/quad.Vertex.glsl similarity index 100% rename from tests/out/quad.Vertex.glsl rename to tests/out/glsl/quad.Vertex.glsl diff --git a/tests/out/shadow.Fragment.glsl b/tests/out/glsl/shadow.Fragment.glsl similarity index 100% rename from tests/out/shadow.Fragment.glsl rename to tests/out/glsl/shadow.Fragment.glsl diff --git a/tests/out/skybox.Fragment.glsl b/tests/out/glsl/skybox.Fragment.glsl similarity index 100% rename from tests/out/skybox.Fragment.glsl rename to tests/out/glsl/skybox.Fragment.glsl diff --git a/tests/out/skybox.Vertex.glsl b/tests/out/glsl/skybox.Vertex.glsl similarity index 100% rename from tests/out/skybox.Vertex.glsl rename to tests/out/glsl/skybox.Vertex.glsl diff --git a/tests/out/standard.Fragment.glsl b/tests/out/glsl/standard.Fragment.glsl similarity index 100% rename from tests/out/standard.Fragment.glsl rename to tests/out/glsl/standard.Fragment.glsl diff --git a/tests/out/empty.hlsl b/tests/out/hlsl/empty.hlsl similarity index 100% rename from tests/out/empty.hlsl rename to tests/out/hlsl/empty.hlsl diff --git a/tests/out/empty.hlsl.config b/tests/out/hlsl/empty.hlsl.config similarity index 100% rename from tests/out/empty.hlsl.config rename to tests/out/hlsl/empty.hlsl.config diff --git a/tests/out/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl similarity index 100% rename from tests/out/quad-vert.hlsl rename to tests/out/hlsl/quad-vert.hlsl diff --git a/tests/out/quad-vert.hlsl.config b/tests/out/hlsl/quad-vert.hlsl.config similarity index 100% rename from tests/out/quad-vert.hlsl.config rename to tests/out/hlsl/quad-vert.hlsl.config diff --git a/tests/out/quad.hlsl b/tests/out/hlsl/quad.hlsl similarity index 100% rename from tests/out/quad.hlsl rename to tests/out/hlsl/quad.hlsl diff --git a/tests/out/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config similarity index 100% rename from tests/out/quad.hlsl.config rename to tests/out/hlsl/quad.hlsl.config diff --git a/tests/out/collatz.ron b/tests/out/ir/collatz.ron similarity index 100% rename from tests/out/collatz.ron rename to tests/out/ir/collatz.ron diff --git a/tests/out/shadow.ron b/tests/out/ir/shadow.ron similarity index 100% rename from tests/out/shadow.ron rename to tests/out/ir/shadow.ron diff --git a/tests/out/access.msl b/tests/out/msl/access.msl similarity index 100% rename from tests/out/access.msl rename to tests/out/msl/access.msl diff --git a/tests/out/boids.msl b/tests/out/msl/boids.msl similarity index 100% rename from tests/out/boids.msl rename to tests/out/msl/boids.msl diff --git a/tests/out/collatz.msl b/tests/out/msl/collatz.msl similarity index 100% rename from tests/out/collatz.msl rename to tests/out/msl/collatz.msl diff --git a/tests/out/control-flow.msl b/tests/out/msl/control-flow.msl similarity index 100% rename from tests/out/control-flow.msl rename to tests/out/msl/control-flow.msl diff --git a/tests/out/empty.msl b/tests/out/msl/empty.msl similarity index 100% rename from tests/out/empty.msl rename to tests/out/msl/empty.msl diff --git a/tests/out/extra.msl b/tests/out/msl/extra.msl similarity index 100% rename from tests/out/extra.msl rename to tests/out/msl/extra.msl diff --git a/tests/out/globals.msl b/tests/out/msl/globals.msl similarity index 100% rename from tests/out/globals.msl rename to tests/out/msl/globals.msl diff --git a/tests/out/image.msl b/tests/out/msl/image.msl similarity index 100% rename from tests/out/image.msl rename to tests/out/msl/image.msl diff --git a/tests/out/interface.msl b/tests/out/msl/interface.msl similarity index 100% rename from tests/out/interface.msl rename to tests/out/msl/interface.msl diff --git a/tests/out/interpolate.msl b/tests/out/msl/interpolate.msl similarity index 100% rename from tests/out/interpolate.msl rename to tests/out/msl/interpolate.msl diff --git a/tests/out/operators.msl b/tests/out/msl/operators.msl similarity index 100% rename from tests/out/operators.msl rename to tests/out/msl/operators.msl diff --git a/tests/out/quad-vert.msl b/tests/out/msl/quad-vert.msl similarity index 100% rename from tests/out/quad-vert.msl rename to tests/out/msl/quad-vert.msl diff --git a/tests/out/quad.msl b/tests/out/msl/quad.msl similarity index 100% rename from tests/out/quad.msl rename to tests/out/msl/quad.msl diff --git a/tests/out/shadow.msl b/tests/out/msl/shadow.msl similarity index 100% rename from tests/out/shadow.msl rename to tests/out/msl/shadow.msl diff --git a/tests/out/skybox.msl b/tests/out/msl/skybox.msl similarity index 100% rename from tests/out/skybox.msl rename to tests/out/msl/skybox.msl diff --git a/tests/out/standard.msl b/tests/out/msl/standard.msl similarity index 100% rename from tests/out/standard.msl rename to tests/out/msl/standard.msl diff --git a/tests/out/operators.Vertex.glsl b/tests/out/operators.Vertex.glsl deleted file mode 100644 index 88898e6ef..000000000 --- a/tests/out/operators.Vertex.glsl +++ /dev/null @@ -1,10 +0,0 @@ -#version 310 es - -precision highp float; - - -void main() { - gl_Position = ((((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)).xyxy + vec4((ivec4(5) % ivec4(2)))); - return; -} - diff --git a/tests/out/access.spvasm b/tests/out/spv/access.spvasm similarity index 100% rename from tests/out/access.spvasm rename to tests/out/spv/access.spvasm diff --git a/tests/out/boids.spvasm b/tests/out/spv/boids.spvasm similarity index 100% rename from tests/out/boids.spvasm rename to tests/out/spv/boids.spvasm diff --git a/tests/out/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm similarity index 100% rename from tests/out/bounds-check-zero.spvasm rename to tests/out/spv/bounds-check-zero.spvasm diff --git a/tests/out/collatz.spvasm b/tests/out/spv/collatz.spvasm similarity index 100% rename from tests/out/collatz.spvasm rename to tests/out/spv/collatz.spvasm diff --git a/tests/out/control-flow.spvasm b/tests/out/spv/control-flow.spvasm similarity index 100% rename from tests/out/control-flow.spvasm rename to tests/out/spv/control-flow.spvasm diff --git a/tests/out/empty.spvasm b/tests/out/spv/empty.spvasm similarity index 100% rename from tests/out/empty.spvasm rename to tests/out/spv/empty.spvasm diff --git a/tests/out/extra.spvasm b/tests/out/spv/extra.spvasm similarity index 100% rename from tests/out/extra.spvasm rename to tests/out/spv/extra.spvasm diff --git a/tests/out/globals.spvasm b/tests/out/spv/globals.spvasm similarity index 100% rename from tests/out/globals.spvasm rename to tests/out/spv/globals.spvasm diff --git a/tests/out/image.spvasm b/tests/out/spv/image.spvasm similarity index 100% rename from tests/out/image.spvasm rename to tests/out/spv/image.spvasm diff --git a/tests/out/interface.spvasm b/tests/out/spv/interface.spvasm similarity index 100% rename from tests/out/interface.spvasm rename to tests/out/spv/interface.spvasm diff --git a/tests/out/interpolate.spvasm b/tests/out/spv/interpolate.spvasm similarity index 100% rename from tests/out/interpolate.spvasm rename to tests/out/spv/interpolate.spvasm diff --git a/tests/out/operators.spvasm b/tests/out/spv/operators.spvasm similarity index 100% rename from tests/out/operators.spvasm rename to tests/out/spv/operators.spvasm diff --git a/tests/out/pointer-access.spvasm b/tests/out/spv/pointer-access.spvasm similarity index 100% rename from tests/out/pointer-access.spvasm rename to tests/out/spv/pointer-access.spvasm diff --git a/tests/out/quad.spvasm b/tests/out/spv/quad.spvasm similarity index 100% rename from tests/out/quad.spvasm rename to tests/out/spv/quad.spvasm diff --git a/tests/out/shadow.spvasm b/tests/out/spv/shadow.spvasm similarity index 100% rename from tests/out/shadow.spvasm rename to tests/out/spv/shadow.spvasm diff --git a/tests/out/skybox.spvasm b/tests/out/spv/skybox.spvasm similarity index 100% rename from tests/out/skybox.spvasm rename to tests/out/spv/skybox.spvasm diff --git a/tests/out/standard.spvasm b/tests/out/spv/standard.spvasm similarity index 100% rename from tests/out/standard.spvasm rename to tests/out/spv/standard.spvasm diff --git a/tests/out/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl similarity index 100% rename from tests/out/210-bevy-2d-shader-frag.wgsl rename to tests/out/wgsl/210-bevy-2d-shader-frag.wgsl diff --git a/tests/out/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl similarity index 100% rename from tests/out/210-bevy-2d-shader-vert.wgsl rename to tests/out/wgsl/210-bevy-2d-shader-vert.wgsl diff --git a/tests/out/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl similarity index 100% rename from tests/out/210-bevy-shader-vert.wgsl rename to tests/out/wgsl/210-bevy-shader-vert.wgsl diff --git a/tests/out/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl similarity index 100% rename from tests/out/246-collatz-comp.wgsl rename to tests/out/wgsl/246-collatz-comp.wgsl diff --git a/tests/out/277-casting-vert.wgsl b/tests/out/wgsl/277-casting-vert.wgsl similarity index 100% rename from tests/out/277-casting-vert.wgsl rename to tests/out/wgsl/277-casting-vert.wgsl diff --git a/tests/out/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl similarity index 100% rename from tests/out/280-matrix-cast-vert.wgsl rename to tests/out/wgsl/280-matrix-cast-vert.wgsl diff --git a/tests/out/484-preprocessor-if-vert.wgsl b/tests/out/wgsl/484-preprocessor-if-vert.wgsl similarity index 100% rename from tests/out/484-preprocessor-if-vert.wgsl rename to tests/out/wgsl/484-preprocessor-if-vert.wgsl diff --git a/tests/out/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl similarity index 100% rename from tests/out/800-out-of-bounds-panic-vert.wgsl rename to tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl diff --git a/tests/out/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-vert.wgsl similarity index 100% rename from tests/out/896-push-constant-vert.wgsl rename to tests/out/wgsl/896-push-constant-vert.wgsl diff --git a/tests/out/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl similarity index 100% rename from tests/out/901-lhs-field-select-vert.wgsl rename to tests/out/wgsl/901-lhs-field-select-vert.wgsl diff --git a/tests/out/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl similarity index 100% rename from tests/out/931-constant-emitting-vert.wgsl rename to tests/out/wgsl/931-constant-emitting-vert.wgsl diff --git a/tests/out/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl similarity index 100% rename from tests/out/932-for-loop-if-vert.wgsl rename to tests/out/wgsl/932-for-loop-if-vert.wgsl diff --git a/tests/out/access.wgsl b/tests/out/wgsl/access.wgsl similarity index 100% rename from tests/out/access.wgsl rename to tests/out/wgsl/access.wgsl diff --git a/tests/out/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl similarity index 100% rename from tests/out/bevy-pbr-frag.wgsl rename to tests/out/wgsl/bevy-pbr-frag.wgsl diff --git a/tests/out/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl similarity index 100% rename from tests/out/bevy-pbr-vert.wgsl rename to tests/out/wgsl/bevy-pbr-vert.wgsl diff --git a/tests/out/boids.wgsl b/tests/out/wgsl/boids.wgsl similarity index 100% rename from tests/out/boids.wgsl rename to tests/out/wgsl/boids.wgsl diff --git a/tests/out/collatz.wgsl b/tests/out/wgsl/collatz.wgsl similarity index 100% rename from tests/out/collatz.wgsl rename to tests/out/wgsl/collatz.wgsl diff --git a/tests/out/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl similarity index 100% rename from tests/out/constant-array-size-vert.wgsl rename to tests/out/wgsl/constant-array-size-vert.wgsl diff --git a/tests/out/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl similarity index 100% rename from tests/out/control-flow.wgsl rename to tests/out/wgsl/control-flow.wgsl diff --git a/tests/out/empty.wgsl b/tests/out/wgsl/empty.wgsl similarity index 100% rename from tests/out/empty.wgsl rename to tests/out/wgsl/empty.wgsl diff --git a/tests/out/extra.wgsl b/tests/out/wgsl/extra.wgsl similarity index 100% rename from tests/out/extra.wgsl rename to tests/out/wgsl/extra.wgsl diff --git a/tests/out/globals.wgsl b/tests/out/wgsl/globals.wgsl similarity index 100% rename from tests/out/globals.wgsl rename to tests/out/wgsl/globals.wgsl diff --git a/tests/out/image.wgsl b/tests/out/wgsl/image.wgsl similarity index 100% rename from tests/out/image.wgsl rename to tests/out/wgsl/image.wgsl diff --git a/tests/out/interface.wgsl b/tests/out/wgsl/interface.wgsl similarity index 100% rename from tests/out/interface.wgsl rename to tests/out/wgsl/interface.wgsl diff --git a/tests/out/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl similarity index 100% rename from tests/out/interpolate.wgsl rename to tests/out/wgsl/interpolate.wgsl diff --git a/tests/out/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl similarity index 100% rename from tests/out/math-functions-vert.wgsl rename to tests/out/wgsl/math-functions-vert.wgsl diff --git a/tests/out/wgsl/multiple_entry_points-glsl.wgsl b/tests/out/wgsl/multiple_entry_points-glsl.wgsl new file mode 100644 index 000000000..2b8844526 --- /dev/null +++ b/tests/out/wgsl/multiple_entry_points-glsl.wgsl @@ -0,0 +1,53 @@ +struct VertexOutput { + [[builtin(position)]] member: vec4; +}; + +struct FragmentOutput { + [[location(0), interpolate(perspective)]] o_color: vec4; +}; + +var gl_Position: vec4; +var o_color: vec4; +var gl_GlobalInvocationID: vec3; + +fn vert_main1() { + gl_Position = vec4(1.0, 1.0, 1.0, 1.0); + return; +} + +fn frag_main1() { + o_color = vec4(1.0, 1.0, 1.0, 1.0); + return; +} + +fn comp_main1() { + let _e3: vec3 = gl_GlobalInvocationID; + if ((_e3.x > u32(1))) { + { + return; + } + } else { + return; + } +} + +[[stage(vertex)]] +fn vert_main() -> VertexOutput { + vert_main1(); + let _e1: vec4 = gl_Position; + return VertexOutput(_e1); +} + +[[stage(fragment)]] +fn frag_main() -> FragmentOutput { + frag_main1(); + let _e1: vec4 = o_color; + return FragmentOutput(_e1); +} + +[[stage(compute), workgroup_size(1, 1, 1)]] +fn comp_main([[builtin(global_invocation_id)]] param: vec3) { + gl_GlobalInvocationID = param; + comp_main1(); + return; +} diff --git a/tests/out/operators.wgsl b/tests/out/wgsl/operators.wgsl similarity index 100% rename from tests/out/operators.wgsl rename to tests/out/wgsl/operators.wgsl diff --git a/tests/out/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl similarity index 100% rename from tests/out/quad-vert.wgsl rename to tests/out/wgsl/quad-vert.wgsl diff --git a/tests/out/quad.wgsl b/tests/out/wgsl/quad.wgsl similarity index 100% rename from tests/out/quad.wgsl rename to tests/out/wgsl/quad.wgsl diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl new file mode 100644 index 000000000..ea2f651ab --- /dev/null +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -0,0 +1,18 @@ +struct FragmentOutput { + [[location(0), interpolate(perspective)]] o_color: vec4; +}; + +var v_uv: vec2; +var o_color: vec4; + +fn main1() { + o_color = vec4(1.0, 1.0, 1.0, 1.0); + return; +} + +[[stage(fragment)]] +fn main() -> FragmentOutput { + main1(); + let _e1: vec4 = o_color; + return FragmentOutput(_e1); +} diff --git a/tests/out/quad-glsl.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl similarity index 51% rename from tests/out/quad-glsl.wgsl rename to tests/out/wgsl/quad_glsl-vert.wgsl index c43c872cb..fe5aa367a 100644 --- a/tests/out/quad-glsl.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -3,18 +3,12 @@ struct VertexOutput { [[builtin(position)]] member: vec4; }; -struct FragmentOutput { - [[location(0), interpolate(perspective)]] o_color: vec4; -}; - var a_pos1: vec2; var a_uv1: vec2; var v_uv: vec2; var gl_Position: vec4; -var v_uv1: vec2; -var o_color: vec4; -fn vert_main1() { +fn main1() { let _e4: vec2 = a_uv1; v_uv = _e4; let _e6: vec2 = a_pos1; @@ -22,24 +16,12 @@ fn vert_main1() { return; } -fn frag_main1() { - o_color = vec4(1.0, 1.0, 1.0, 1.0); - return; -} - [[stage(vertex)]] -fn vert_main([[location(0), interpolate(perspective)]] a_pos: vec2, [[location(1), interpolate(perspective)]] a_uv: vec2) -> VertexOutput { +fn main([[location(0), interpolate(perspective)]] a_pos: vec2, [[location(1), interpolate(perspective)]] a_uv: vec2) -> VertexOutput { a_pos1 = a_pos; a_uv1 = a_uv; - vert_main1(); + main1(); let _e5: vec2 = v_uv; let _e7: vec4 = gl_Position; return VertexOutput(_e5, _e7); } - -[[stage(fragment)]] -fn frag_main() -> FragmentOutput { - frag_main1(); - let _e1: vec4 = o_color; - return FragmentOutput(_e1); -} diff --git a/tests/out/shadow.wgsl b/tests/out/wgsl/shadow.wgsl similarity index 100% rename from tests/out/shadow.wgsl rename to tests/out/wgsl/shadow.wgsl diff --git a/tests/out/skybox.wgsl b/tests/out/wgsl/skybox.wgsl similarity index 100% rename from tests/out/skybox.wgsl rename to tests/out/wgsl/skybox.wgsl diff --git a/tests/out/standard.wgsl b/tests/out/wgsl/standard.wgsl similarity index 100% rename from tests/out/standard.wgsl rename to tests/out/wgsl/standard.wgsl diff --git a/tests/out/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl similarity index 100% rename from tests/out/swizzle_write-frag.wgsl rename to tests/out/wgsl/swizzle_write-frag.wgsl diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e009f5696..0b8f67eba 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -3,8 +3,8 @@ use std::{fs, path::PathBuf}; -const DIR_IN: &str = "tests/in"; -const DIR_OUT: &str = "tests/out"; +const BASE_DIR_IN: &str = "tests/in"; +const BASE_DIR_OUT: &str = "tests/out"; bitflags::bitflags! { struct Targets: u32 { @@ -52,12 +52,21 @@ struct Parameters { #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] #[serde(default)] glsl_desktop_version: Option, + #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] + #[serde(default)] + glsl_vert_ep_name: Option, + #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] + #[serde(default)] + glsl_frag_ep_name: Option, + #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] + #[serde(default)] + glsl_comp_ep_name: Option, } #[allow(dead_code, unused_variables)] fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let root = env!("CARGO_MANIFEST_DIR"); - let params = match fs::read_to_string(format!("{}/{}/{}.param.ron", root, DIR_IN, name)) { + let params = match fs::read_to_string(format!("{}/{}/{}.param.ron", root, BASE_DIR_IN, name)) { Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), Err(_) => Parameters::default(), }; @@ -73,39 +82,39 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { .validate(module) .unwrap(); - let dest = PathBuf::from(root).join(DIR_OUT).join(name); + let dest = PathBuf::from(root).join(BASE_DIR_OUT); #[cfg(feature = "serialize")] { if targets.contains(Targets::IR) { let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); let string = ron::ser::to_string_pretty(module, config).unwrap(); - fs::write(dest.with_extension("ron"), string).unwrap(); + fs::write(dest.join(format!("ir/{}.ron", name)), string).unwrap(); } if targets.contains(Targets::ANALYSIS) { let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); let string = ron::ser::to_string_pretty(&info, config).unwrap(); - fs::write(dest.with_extension("info.ron"), string).unwrap(); + fs::write(dest.join(format!("analysis/{}.info.ron", name)), string).unwrap(); } } #[cfg(feature = "spv-out")] { if targets.contains(Targets::SPIRV) { - check_output_spv(module, &info, &dest, ¶ms); + write_output_spv(module, &info, &dest, name, ¶ms); } } #[cfg(feature = "msl-out")] { if targets.contains(Targets::METAL) { - check_output_msl(module, &info, &dest, ¶ms); + write_output_msl(module, &info, &dest, name, ¶ms); } } #[cfg(feature = "glsl-out")] { if targets.contains(Targets::GLSL) { for ep in module.entry_points.iter() { - check_output_glsl(module, &info, &dest, ep.stage, &ep.name, ¶ms); + write_output_glsl(module, &info, &dest, name, ep.stage, &ep.name, ¶ms); } } } @@ -113,28 +122,29 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { { if targets.contains(Targets::DOT) { let string = naga::back::dot::write(module, Some(&info)).unwrap(); - fs::write(dest.with_extension("dot"), string).unwrap(); + fs::write(dest.join(format!("dot/{}.dot", name)), string).unwrap(); } } #[cfg(feature = "hlsl-out")] { if targets.contains(Targets::HLSL) { - check_output_hlsl(module, &info, &dest); + write_output_hlsl(module, &info, &dest, name); } } #[cfg(feature = "wgsl-out")] { if targets.contains(Targets::WGSL) { - check_output_wgsl(module, &info, &dest); + write_output_wgsl(module, &info, &dest, name); } } } #[cfg(feature = "spv-out")] -fn check_output_spv( +fn write_output_spv( module: &naga::Module, info: &naga::valid::ModuleInfo, destination: &PathBuf, + file_name: &str, params: &Parameters, ) { use naga::back::spv; @@ -171,14 +181,15 @@ fn check_output_spv( .expect("Produced invalid SPIR-V") .disassemble(); - fs::write(destination.with_extension("spvasm"), dis).unwrap(); + fs::write(destination.join(format!("spv/{}.spvasm", file_name)), dis).unwrap(); } #[cfg(feature = "msl-out")] -fn check_output_msl( +fn write_output_msl( module: &naga::Module, info: &naga::valid::ModuleInfo, destination: &PathBuf, + file_name: &str, params: &Parameters, ) { use naga::back::msl; @@ -207,14 +218,15 @@ fn check_output_msl( } } - fs::write(destination.with_extension("msl"), string).unwrap(); + fs::write(destination.join(format!("msl/{}.msl", file_name)), string).unwrap(); } #[cfg(feature = "glsl-out")] -fn check_output_glsl( +fn write_output_glsl( module: &naga::Module, info: &naga::valid::ModuleInfo, destination: &PathBuf, + file_name: &str, stage: naga::ShaderStage, ep_name: &str, params: &Parameters, @@ -234,17 +246,25 @@ fn check_output_glsl( let mut writer = glsl::Writer::new(&mut buffer, module, info, &options).unwrap(); writer.write().unwrap(); - let ext = format!("{:?}.glsl", stage); - fs::write(destination.with_extension(&ext), buffer).unwrap(); + fs::write( + destination.join(format!("glsl/{}.{:?}.glsl", file_name, stage)), + buffer, + ) + .unwrap(); } #[cfg(feature = "hlsl-out")] -fn check_output_hlsl(module: &naga::Module, info: &naga::valid::ModuleInfo, destination: &PathBuf) { +fn write_output_hlsl( + module: &naga::Module, + info: &naga::valid::ModuleInfo, + destination: &PathBuf, + file_name: &str, +) { use naga::back::hlsl; let options = hlsl::Options::default(); let string = hlsl::write_string(module, info, &options).unwrap(); - fs::write(destination.with_extension("hlsl"), string).unwrap(); + fs::write(destination.join(format!("hlsl/{}.hlsl", file_name)), string).unwrap(); // We need a config file for validation script // This file contains an info about profiles (shader stages) contains inside generated shader @@ -263,16 +283,25 @@ fn check_output_hlsl(module: &naga::Module, info: &naga::valid::ModuleInfo, dest config_str, stage_str, profile, stage_str, ep_name ); } - fs::write(destination.with_extension("hlsl.config"), config_str).unwrap(); + fs::write( + destination.join(format!("hlsl/{}.hlsl.config", file_name)), + config_str, + ) + .unwrap(); } #[cfg(feature = "wgsl-out")] -fn check_output_wgsl(module: &naga::Module, info: &naga::valid::ModuleInfo, destination: &PathBuf) { +fn write_output_wgsl( + module: &naga::Module, + info: &naga::valid::ModuleInfo, + destination: &PathBuf, + file_name: &str, +) { use naga::back::wgsl; let string = wgsl::write_string(module, info).unwrap(); - fs::write(destination.with_extension("wgsl"), string).unwrap(); + fs::write(destination.join(format!("wgsl/{}.wgsl", file_name)), string).unwrap(); } #[cfg(feature = "wgsl-in")] @@ -343,7 +372,8 @@ fn convert_wgsl() { for &(name, targets) in inputs.iter() { println!("Processing '{}'", name); - let file = fs::read_to_string(format!("{}/{}/{}.wgsl", root, DIR_IN, name)) + // WGSL shaders lives in root dir as a privileged. + let file = fs::read_to_string(format!("{}/{}/{}.wgsl", root, BASE_DIR_IN, name)) .expect("Couldn't find wgsl file"); match naga::front::wgsl::parse_str(&file) { Ok(module) => check_targets(&module, name, targets), @@ -356,7 +386,8 @@ fn convert_wgsl() { fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { let root = env!("CARGO_MANIFEST_DIR"); let module = naga::front::spv::parse_u8_slice( - &fs::read(format!("{}/{}/{}.spv", root, DIR_IN, name)).expect("Couldn't find spv file"), + &fs::read(format!("{}/{}/spv/{}.spv", root, BASE_DIR_IN, name)) + .expect("Couldn't find spv file"), &naga::front::spv::Options { adjust_coordinate_space, strict_capabilities: false, @@ -395,47 +426,55 @@ fn convert_spv_pointer_access() { convert_spv("pointer-access", true, Targets::SPIRV); } -#[cfg(feature = "glsl-in")] -fn convert_glsl( - name: &str, - entry_points: naga::FastHashMap, - targets: Targets, -) { - let root = env!("CARGO_MANIFEST_DIR"); - let module = naga::front::glsl::parse_str( - &fs::read_to_string(format!("{}/{}/{}.glsl", root, DIR_IN, name)) - .expect("Couldn't find glsl file"), - &naga::front::glsl::Options { - entry_points, - defines: Default::default(), - }, - ) - .unwrap(); - println!("{:#?}", module); - - check_targets(&module, name, targets); -} - #[cfg(feature = "glsl-in")] #[allow(unused_variables)] #[test] fn convert_glsl_folder() { let root = env!("CARGO_MANIFEST_DIR"); - for entry in std::fs::read_dir(format!("{}/{}/glsl", root, DIR_IN)).unwrap() { + for entry in std::fs::read_dir(format!("{}/{}/glsl", root, BASE_DIR_IN)).unwrap() { let entry = entry.unwrap(); let file_name = entry.file_name().into_string().unwrap(); - + if file_name.ends_with(".ron") { + // No needed to validate ron files + continue; + } + let params_path = format!( + "{}/{}/glsl/{}.params.ron", + root, + BASE_DIR_IN, + PathBuf::from(&file_name).with_extension("").display() + ); + let is_params_used = PathBuf::from(¶ms_path).exists(); println!("Processing {}", file_name); let mut entry_points = naga::FastHashMap::default(); - let stage = match entry.path().extension().and_then(|s| s.to_str()).unwrap() { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - ext => panic!("Unknown extension for glsl file {}", ext), - }; - entry_points.insert("main".to_string(), stage); + if is_params_used { + let params: Parameters = match fs::read_to_string(¶ms_path) { + Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), + Err(_) => panic!("Can't parse glsl params ron file: {:?}", ¶ms_path), + }; + + if let Some(vert) = params.glsl_vert_ep_name { + entry_points.insert(vert, naga::ShaderStage::Vertex); + }; + + if let Some(frag) = params.glsl_frag_ep_name { + entry_points.insert(frag, naga::ShaderStage::Fragment); + }; + + if let Some(comp) = params.glsl_comp_ep_name { + entry_points.insert(comp, naga::ShaderStage::Compute); + }; + } else { + let stage = match entry.path().extension().and_then(|s| s.to_str()).unwrap() { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + ext => panic!("Unknown extension for glsl file {}", ext), + }; + entry_points.insert("main".to_string(), stage); + } let module = naga::front::glsl::parse_str( &fs::read_to_string(entry.path()).expect("Couldn't find glsl file"), @@ -453,20 +492,10 @@ fn convert_glsl_folder() { .validate(&module) .unwrap(); - let dest = PathBuf::from(root) - .join(DIR_OUT) - .join(&file_name.replace(".", "-")); - #[cfg(feature = "wgsl-out")] - check_output_wgsl(&module, &info, &dest); + { + let dest = PathBuf::from(root).join(BASE_DIR_OUT); + write_output_wgsl(&module, &info, &dest, &file_name.replace(".", "-")); + } } } - -#[cfg(feature = "glsl-in")] -#[test] -fn convert_glsl_quad() { - let mut entry_points = naga::FastHashMap::default(); - entry_points.insert("vert_main".to_string(), naga::ShaderStage::Vertex); - entry_points.insert("frag_main".to_string(), naga::ShaderStage::Fragment); - convert_glsl("quad-glsl", entry_points, Targets::WGSL); -} From 4bc4c60663a7ef68711cbf1f1536bb2b2857e7bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 19 Jun 2021 15:50:28 +0100 Subject: [PATCH 1002/2212] [glsl-in] Implicit casts for function calls --- src/front/glsl/ast.rs | 45 +--- src/front/glsl/functions.rs | 250 ++++++++++++------ src/front/glsl/parser.rs | 40 +-- src/front/glsl/parser_tests.rs | 48 ++++ src/front/mod.rs | 24 -- tests/in/glsl/900-implicit-conversions.vert | 15 ++ .../wgsl/900-implicit-conversions-vert.wgsl | 39 +++ 7 files changed, 307 insertions(+), 154 deletions(-) create mode 100644 tests/in/glsl/900-implicit-conversions.vert create mode 100644 tests/out/wgsl/900-implicit-conversions-vert.wgsl diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index aff74e9f2..f7e920888 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -26,14 +26,10 @@ pub struct GlobalLookup { pub mutable: bool, } -#[derive(Debug, PartialEq, Eq, Hash)] -pub struct FunctionSignature { - pub name: String, - pub parameters: Vec>, -} - #[derive(Debug, Clone)] pub struct FunctionDeclaration { + /// Normalized function parameters, modifiers are not applied + pub parameters: Vec>, pub qualifiers: Vec, pub handle: Handle, /// Wheter this function was already defined or is just a prototype @@ -84,7 +80,7 @@ pub struct Program<'a> { pub workgroup_size: [u32; 3], pub early_fragment_tests: bool, - pub lookup_function: FastHashMap, + pub lookup_function: FastHashMap>, pub lookup_type: FastHashMap>, pub global_variables: Vec<(String, GlobalLookup)>, @@ -120,7 +116,7 @@ impl<'a> Program<'a> { } pub fn resolve_type<'b>( - &'b mut self, + &'b self, context: &'b mut Context, handle: Handle, meta: SourceMetadata, @@ -146,33 +142,6 @@ impl<'a> Program<'a> { } } - pub fn resolve_handle( - &mut self, - context: &mut Context, - handle: Handle, - meta: SourceMetadata, - ) -> Result, ErrorKind> { - let resolve_ctx = ResolveContext { - constants: &self.module.constants, - types: &self.module.types, - global_vars: &self.module.global_variables, - local_vars: context.locals, - functions: &self.module.functions, - arguments: context.arguments, - }; - match context - .typifier - .grow(handle, context.expressions, &resolve_ctx) - { - //TODO: better error report - Err(error) => Err(ErrorKind::SemanticError( - meta, - format!("Can't resolve type: {:?}", error).into(), - )), - Ok(()) => Ok(context.typifier.get_handle(handle, &mut self.module.types)), - } - } - pub fn solve_constant( &mut self, ctx: &Context, @@ -362,7 +331,7 @@ impl<'function> Context<'function> { pub fn add_function_arg( &mut self, program: &mut Program, - sig: &mut FunctionSignature, + parameters: &mut Vec>, body: &mut Block, name: Option, ty: Handle, @@ -374,7 +343,7 @@ impl<'function> Context<'function> { ty, binding: None, }; - sig.parameters.push(ty); + parameters.push(ty); if qualifier.is_lhs() { arg.ty = program.module.types.fetch_or_append(Type { @@ -880,7 +849,7 @@ impl<'function> Context<'function> { } } -fn type_power(kind: ScalarKind) -> Option { +pub fn type_power(kind: ScalarKind) -> Option { Some(match kind { ScalarKind::Sint => 0, ScalarKind::Uint => 1, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 9095f4c4b..ecadf0ac0 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -384,67 +384,126 @@ impl Program<'_> { )) } _ => { - let mut parameters = Vec::new(); + let declarations = self.lookup_function.get(&name).ok_or_else(|| { + ErrorKind::SemanticError( + meta, + format!("Unknown function '{}'", name).into(), + ) + })?; - for (e, meta) in args { - let handle = self.resolve_handle(ctx, e, meta)?; + let mut maybe_decl = None; - parameters.push(handle) + 'outer: for decl in declarations { + if args.len() != decl.parameters.len() { + continue; + } + + let mut exact = true; + + for (decl_arg, call_arg) in decl.parameters.iter().zip(args.iter()) { + let decl_inner = &self.module.types[*decl_arg].inner; + let call_inner = self.resolve_type(ctx, call_arg.0, call_arg.1)?; + + if decl_inner != call_inner { + exact = false; + + match ( + decl_inner.scalar_kind().and_then(type_power), + call_inner.scalar_kind().and_then(type_power), + ) { + (Some(decl_power), Some(call_power)) => { + if decl_power < call_power { + continue 'outer; + } + } + _ => continue 'outer, + } + } + } + + if exact { + maybe_decl = Some(decl); + break; + } else if maybe_decl.is_some() { + return Err(ErrorKind::SemanticError( + meta, + format!("Ambiguous best function for '{}'", name).into(), + )); + } else { + maybe_decl = Some(decl) + } } - let sig = FunctionSignature { name, parameters }; + let decl = maybe_decl.ok_or_else(|| { + ErrorKind::SemanticError( + meta, + format!("Unknown function '{}'", name).into(), + ) + })?; - let fun = self - .lookup_function - .get(&sig) - .ok_or_else(|| { - ErrorKind::SemanticError( - meta, - // FIXME: Proper signature display - format!("Unknown function: {:?}", sig).into(), - ) - })? - .clone(); + let qualifiers = decl.qualifiers.clone(); + let parameters = decl.parameters.clone(); + let function = decl.handle; + let is_void = decl.void; - let mut arguments = Vec::with_capacity(raw_args.len()); + let mut arguments = Vec::with_capacity(args.len()); let mut proxy_writes = Vec::new(); - for (qualifier, expr) in fun.qualifiers.iter().zip(raw_args.iter()) { - let handle = ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?.0; - if qualifier.is_lhs() - && matches! { ctx.get_expression(handle), &Expression::Swizzle { .. } } + for (qualifier, (expr, parameter)) in qualifiers + .iter() + .zip(raw_args.iter().zip(parameters.iter())) + { + let (mut handle, meta) = + ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?; + + if let TypeInner::Vector { size, kind, width } = + *self.resolve_type(ctx, handle, meta)? { - let meta = ctx.hir_exprs[*expr].meta; - let ty = self.resolve_handle(ctx, handle, meta)?; - let temp_var = ctx.locals.append(LocalVariable { - name: None, - ty, - init: None, - }); - let temp_expr = - ctx.add_expression(Expression::LocalVariable(temp_var), body); + if qualifier.is_lhs() + && matches!( + *ctx.get_expression(handle), + Expression::Swizzle { .. } + ) + { + let ty = self.module.types.append(Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }); + let temp_var = ctx.locals.append(LocalVariable { + name: None, + ty, + init: None, + }); + let temp_expr = ctx + .add_expression(Expression::LocalVariable(temp_var), body); - body.push(Statement::Store { - pointer: temp_expr, - value: handle, - }); + body.push(Statement::Store { + pointer: temp_expr, + value: handle, + }); - arguments.push(temp_expr); - proxy_writes.push((*expr, temp_expr)); - } else { - arguments.push(handle); + arguments.push(temp_expr); + proxy_writes.push((*expr, temp_expr)); + continue; + } } + + if let Some(kind) = self.module.types[*parameter].inner.scalar_kind() { + ctx.implicit_conversion(self, &mut handle, meta, kind)?; + } + + arguments.push(handle) } ctx.emit_flush(body); - let result = if !fun.void { - Some(ctx.add_expression(Expression::Call(fun.handle), body)) + let result = if !is_void { + Some(ctx.add_expression(Expression::Call(function), body)) } else { None }; body.push(crate::Statement::Call { - function: fun.handle, + function, arguments, result, }); @@ -505,22 +564,46 @@ impl Program<'_> { pub fn add_function( &mut self, mut function: Function, - sig: FunctionSignature, + name: String, + // Normalized function parameters, modifiers are not applied + parameters: Vec>, qualifiers: Vec, meta: SourceMetadata, ) -> Result, ErrorKind> { ensure_block_returns(&mut function.body); - let stage = self.entry_points.get(&sig.name); + let stage = self.entry_points.get(&name); Ok(if let Some(&stage) = stage { let handle = self.module.functions.append(function); - self.entries.push((sig.name, stage, handle)); + self.entries.push((name, stage, handle)); self.function_arg_use.push(Vec::new()); handle } else { let void = function.result.is_none(); - if let Some(decl) = self.lookup_function.get_mut(&sig) { + let &mut Program { + ref mut lookup_function, + ref mut module, + .. + } = self; + + let declarations = lookup_function.entry(name).or_default(); + + 'outer: for decl in declarations.iter_mut() { + if parameters.len() != decl.parameters.len() { + continue; + } + + for (new_parameter, old_parameter) in parameters.iter().zip(decl.parameters.iter()) + { + let new_inner = &module.types[*new_parameter].inner; + let old_inner = &module.types[*old_parameter].inner; + + if new_inner != old_inner { + continue 'outer; + } + } + if decl.defined { return Err(ErrorKind::SemanticError( meta, @@ -529,56 +612,73 @@ impl Program<'_> { } decl.defined = true; + decl.qualifiers = qualifiers; *self.module.functions.get_mut(decl.handle) = function; - decl.handle - } else { - self.function_arg_use.push(Vec::new()); - let handle = self.module.functions.append(function); - self.lookup_function.insert( - sig, - FunctionDeclaration { - qualifiers, - handle, - defined: true, - void, - }, - ); - handle + return Ok(decl.handle); } + + self.function_arg_use.push(Vec::new()); + let handle = module.functions.append(function); + declarations.push(FunctionDeclaration { + parameters, + qualifiers, + handle, + defined: true, + void, + }); + handle }) } pub fn add_prototype( &mut self, function: Function, - sig: FunctionSignature, + name: String, + // Normalized function parameters, modifiers are not applied + parameters: Vec>, qualifiers: Vec, meta: SourceMetadata, ) -> Result<(), ErrorKind> { let void = function.result.is_none(); - self.function_arg_use.push(Vec::new()); - let handle = self.module.functions.append(function); + let &mut Program { + ref mut lookup_function, + ref mut module, + .. + } = self; + + let declarations = lookup_function.entry(name).or_default(); + + 'outer: for decl in declarations.iter_mut() { + if parameters.len() != decl.parameters.len() { + continue; + } + + for (new_parameter, old_parameter) in parameters.iter().zip(decl.parameters.iter()) { + let new_inner = &module.types[*new_parameter].inner; + let old_inner = &module.types[*old_parameter].inner; + + if new_inner != old_inner { + continue 'outer; + } + } - if self - .lookup_function - .insert( - sig, - FunctionDeclaration { - qualifiers, - handle, - defined: false, - void, - }, - ) - .is_some() - { return Err(ErrorKind::SemanticError( meta, "Prototype already defined".into(), )); } + self.function_arg_use.push(Vec::new()); + let handle = module.functions.append(function); + declarations.push(FunctionDeclaration { + parameters, + qualifiers, + handle, + defined: false, + void, + }); + Ok(()) } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 9cc881cb1..b1f933e10 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,8 +1,7 @@ use super::{ ast::{ - Context, FunctionCall, FunctionCallKind, FunctionSignature, GlobalLookup, GlobalLookupKind, - HirExpr, HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout, - TypeQualifier, + Context, FunctionCall, FunctionCallKind, GlobalLookup, GlobalLookupKind, HirExpr, + HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier, }, error::ErrorKind, lex::Lexer, @@ -667,12 +666,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut expressions = Arena::new(); let mut local_variables = Arena::new(); let mut arguments = Vec::new(); + // Normalized function parameters, modifiers are not applied let mut parameters = Vec::new(); + let mut qualifiers = Vec::new(); let mut body = Block::new(); - let mut sig = FunctionSignature { - name: name.clone(), - parameters: Vec::new(), - }; let mut context = Context::new( self.program, @@ -685,8 +682,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.parse_function_args( &mut context, &mut body, + &mut qualifiers, &mut parameters, - &mut sig, )?; let end_meta = self.expect(TokenValue::RightParen)?.meta; @@ -698,13 +695,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // This branch handles function prototypes self.program.add_prototype( Function { - name: Some(name), + name: Some(name.clone()), result, arguments, ..Default::default() }, - sig, + name, parameters, + qualifiers, meta, )?; @@ -721,7 +719,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let Context { arg_use, .. } = context; let handle = self.program.add_function( Function { - name: Some(name), + name: Some(name.clone()), result, expressions, named_expressions: crate::FastHashMap::default(), @@ -729,8 +727,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { arguments, body, }, - sig, + name, parameters, + qualifiers, meta, )?; @@ -1737,19 +1736,26 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { &mut self, context: &mut Context, body: &mut Block, - parameters: &mut Vec, - sig: &mut FunctionSignature, + qualifiers: &mut Vec, + parameters: &mut Vec>, ) -> Result<()> { loop { if self.peek_type_name() || self.peek_parameter_qualifier() { let qualifier = self.parse_parameter_qualifier(); - parameters.push(qualifier); + qualifiers.push(qualifier); let ty = self.parse_type_non_void()?.0; match self.expect_peek()?.value { TokenValue::Comma => { self.bump()?; - context.add_function_arg(&mut self.program, sig, body, None, ty, qualifier); + context.add_function_arg( + &mut self.program, + parameters, + body, + None, + ty, + qualifier, + ); continue; } TokenValue::Identifier(_) => { @@ -1760,7 +1766,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { context.add_function_arg( &mut self.program, - sig, + parameters, body, Some(name), ty, diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 40281ed36..8ff6aa1fe 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -471,6 +471,54 @@ fn implicit_conversions() { &entry_points, ) .unwrap(); + + assert_eq!( + parse_program( + r#" + # version 450 + void test(int a) {} + void test(uint a) {} + + void main() { + test(1.0); + } + "#, + &entry_points + ) + .err() + .unwrap(), + ErrorKind::SemanticError( + SourceMetadata { + start: 156, + end: 165 + }, + "Unknown function \'test\'".into() + ) + ); + + assert_eq!( + parse_program( + r#" + # version 450 + void test(float a) {} + void test(uint a) {} + + void main() { + test(1); + } + "#, + &entry_points + ) + .err() + .unwrap(), + ErrorKind::SemanticError( + SourceMetadata { + start: 158, + end: 165 + }, + "Ambiguous best function for \'test\'".into() + ) + ); } #[test] diff --git a/src/front/mod.rs b/src/front/mod.rs index 45c93143e..818159292 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -69,30 +69,6 @@ impl Typifier { self.resolutions[expr_handle.index()].inner_with(types) } - pub fn get_handle( - &mut self, - expr_handle: Handle, - types: &mut Arena, - ) -> Handle { - let mut dummy = TypeResolution::Value(crate::TypeInner::Sampler { comparison: false }); - let res = &mut self.resolutions[expr_handle.index()]; - - std::mem::swap(&mut dummy, res); - - let v = match dummy { - TypeResolution::Handle(h) => h, - TypeResolution::Value(inner) => { - let h = types.fetch_or_append(crate::Type { name: None, inner }); - dummy = TypeResolution::Handle(h); - h - } - }; - - std::mem::swap(&mut dummy, res); - - v - } - pub fn grow( &mut self, expr_handle: Handle, diff --git a/tests/in/glsl/900-implicit-conversions.vert b/tests/in/glsl/900-implicit-conversions.vert new file mode 100644 index 000000000..d3908bb11 --- /dev/null +++ b/tests/in/glsl/900-implicit-conversions.vert @@ -0,0 +1,15 @@ +// ISSUE: #900 +#version 450 + +// Signature match call the second overload +void exact(float a) {} +void exact(int a) {} + +// No signature match but one overload satisfies the cast rules +void implicit(float a) {} +void implicit(int a) {} + +void main() { + exact(1); + implicit(1u); +} diff --git a/tests/out/wgsl/900-implicit-conversions-vert.wgsl b/tests/out/wgsl/900-implicit-conversions-vert.wgsl new file mode 100644 index 000000000..49e4a5704 --- /dev/null +++ b/tests/out/wgsl/900-implicit-conversions-vert.wgsl @@ -0,0 +1,39 @@ +fn exact(a: f32) { + var a1: f32; + + a1 = a; + return; +} + +fn exact1(a2: i32) { + var a3: i32; + + a3 = a2; + return; +} + +fn implicit(a4: f32) { + var a5: f32; + + a5 = a4; + return; +} + +fn implicit1(a6: i32) { + var a7: i32; + + a7 = a6; + return; +} + +fn main1() { + exact1(1); + implicit(f32(1u)); + return; +} + +[[stage(vertex)]] +fn main() { + main1(); + return; +} From 70071228a3937ca82c9fda13d14197d199a2f0ec Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 20 Jun 2021 01:18:36 -0400 Subject: [PATCH 1003/2212] [spv-out] don't OpConvert the same width --- src/back/spv/writer.rs | 46 ++++++++++++++++++++++++++++-------------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 1053fb94e..223960b0e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1669,22 +1669,38 @@ impl Writer { kind, convert, } => { - let expr_id = self.cached[expr]; - let expr_kind = fun_info[expr] - .ty - .inner_with(&ir_module.types) - .scalar_kind() - .unwrap(); + use crate::ScalarKind as Sk; - let op = match (expr_kind, kind) { - _ if convert.is_none() => spirv::Op::Bitcast, - (crate::ScalarKind::Float, crate::ScalarKind::Uint) => spirv::Op::ConvertFToU, - (crate::ScalarKind::Float, crate::ScalarKind::Sint) => spirv::Op::ConvertFToS, - (crate::ScalarKind::Float, crate::ScalarKind::Float) => spirv::Op::FConvert, - (crate::ScalarKind::Sint, crate::ScalarKind::Float) => spirv::Op::ConvertSToF, - (crate::ScalarKind::Sint, crate::ScalarKind::Sint) => spirv::Op::SConvert, - (crate::ScalarKind::Uint, crate::ScalarKind::Float) => spirv::Op::ConvertUToF, - (crate::ScalarKind::Uint, crate::ScalarKind::Uint) => spirv::Op::UConvert, + let expr_id = self.cached[expr]; + let (src_kind, src_width) = match *fun_info[expr].ty.inner_with(&ir_module.types) { + crate::TypeInner::Scalar { kind, width } + | crate::TypeInner::Vector { + kind, + width, + size: _, + } => (kind, width), + crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), + ref other => { + log::error!("As source {:?}", other); + return Err(Error::Validation("Unexpected Expression::As source")); + } + }; + + let op = match (src_kind, kind, convert) { + (_, _, None) => spirv::Op::Bitcast, + (Sk::Float, Sk::Uint, Some(_)) => spirv::Op::ConvertFToU, + (Sk::Float, Sk::Sint, Some(_)) => spirv::Op::ConvertFToS, + (Sk::Float, Sk::Float, Some(dst_width)) if src_width != dst_width => { + spirv::Op::FConvert + } + (Sk::Sint, Sk::Float, Some(_)) => spirv::Op::ConvertSToF, + (Sk::Sint, Sk::Sint, Some(dst_width)) if src_width != dst_width => { + spirv::Op::SConvert + } + (Sk::Uint, Sk::Float, Some(_)) => spirv::Op::ConvertUToF, + (Sk::Uint, Sk::Uint, Some(dst_width)) if src_width != dst_width => { + spirv::Op::UConvert + } // We assume it's either an identity cast, or int-uint. _ => spirv::Op::Bitcast, }; From 70016ce6e3739b74848d1b965782bd6afd453ad5 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 19 Jun 2021 22:42:39 -0700 Subject: [PATCH 1004/2212] Address warnings about links from `cargo doc --package naga`. --- src/lib.rs | 8 ++++---- src/proc/layouter.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index b2ab989b9..f109e2e3e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -164,8 +164,8 @@ pub(crate) type NamedExpressions = FastHashMap, String>; /// HLSL: Attribute earlydepthstencil /// /// For more, see: -/// - https://www.khronos.org/opengl/wiki/Early_Fragment_Test#Explicit_specification -/// - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-earlydepthstencil +/// - +/// - #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] @@ -180,8 +180,8 @@ pub struct EarlyDepthTest { /// HLSL: SV_Depth/SV_DepthGreaterEqual/SV_DepthLessEqual /// /// For more, see: -/// - https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_conservative_depth.txt -/// - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics#system-value-semantics +/// - +/// - #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index d6c67e0aa..03ca28698 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -14,7 +14,7 @@ pub struct TypeLayout { /// Helper processor that derives the sizes of all types. /// It uses the default layout algorithm/table, described in -/// https://github.com/gpuweb/gpuweb/issues/1393 +/// #[derive(Debug, Default)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] From 696ca340e00490ad0435009226f7279bb6f8d68b Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 16 Jun 2021 16:54:55 -0700 Subject: [PATCH 1005/2212] Improve docs for `TypeInner`, `valid::TypeFlags`, and some internal types. --- src/back/spv/mod.rs | 12 +++++++++ src/lib.rs | 63 +++++++++++++++++++++++++++++++++++++++++++++ src/valid/type.rs | 31 +++++++++++++++++++++- 3 files changed, 105 insertions(+), 1 deletion(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index daabc4c4e..f1522a5c4 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -127,14 +127,26 @@ impl Function { } } +/// A SPIR-V type constructed during code generation. +/// +/// In the process of writing SPIR-V, we need to synthesize various types for +/// intermediate results and such. However, it's inconvenient to use +/// `crate::Type` or `crate::TypeInner` for these, as the IR module is immutable +/// so we can't ever create a `Handle` to refer to them. So for local use +/// in the SPIR-V writer, we have this home-grown type enum that covers only the +/// cases we need (for example, it doesn't cover structs). #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LocalType { + /// A scalar, vector, or pointer to one of those. Value { + /// If `None`, this represents a scalar type. If `Some`, this represents + /// a vector type of the given size. vector_size: Option, kind: crate::ScalarKind, width: crate::Bytes, pointer_class: Option, }, + /// A matrix of floating-point values. Matrix { columns: crate::VectorSize, rows: crate::VectorSize, diff --git a/src/lib.rs b/src/lib.rs index f109e2e3e..361c08069 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -476,6 +476,26 @@ pub enum TypeInner { width: Bytes, }, /// Pointer to another type. + /// + /// ## Pointers to non-`SIZED` types + /// + /// The `base` type of a pointer may be a non-[`SIZED`] type like a + /// dynamically-sized [`Array`], or a [`Struct`] whose last member is a + /// dynamically sized array. Such pointers occur as the types of + /// [`GlobalVariable`] or [`AccessIndex`] expressions referring to + /// dynamically-sized arrays. + /// + /// However, among pointers to non-`SIZED` types, only pointers to `Struct`s + /// are [`DATA`]. Pointers to dynamically sized `Array`s cannot be passed as + /// arguments, stored in variables, or held in arrays or structures. Their + /// only use is as the types of `AccessIndex` expressions. + /// + /// [`SIZED`]: valid::TypeFlags::SIZED + /// [`DATA`]: valid::TypeFlags::DATA + /// [`Array`]: TypeInner::Array + /// [`Struct`]: TypeInner::Struct + /// [`GlobalVariable`]: Expression::GlobalVariable + /// [`AccessIndex`]: Expression::AccessIndex Pointer { base: Handle, class: StorageClass, @@ -487,14 +507,57 @@ pub enum TypeInner { width: Bytes, class: StorageClass, }, + /// Homogenous list of elements. + /// + /// The `base` type must be a [`SIZED`], [`DATA`] type. + /// + /// ## Dynamically sized arrays + /// + /// An `Array` is [`SIZED`] unless its `size` is [`Dynamic`]. + /// Dynamically-sized arrays may only appear in a few situations: + /// + /// - They may appear as the last member of a [`Struct`] whose `top_level` + /// flag is set. + /// + /// - They may appear as the base type of a [`Pointer`]. An + /// [`AccessIndex`] expression referring to a top-level struct's final + /// unsized array member would have such a pointer type. However, such + /// pointer types may only appear as the types of such intermediate + /// expressions. They are not [`DATA`], and cannot be stored in + /// variables, held in arrays or structs, or passed as parameters. + /// + /// [`SIZED`]: crate::valid::TypeFlags::SIZED + /// [`DATA`]: crate::valid::TypeFlags::DATA + /// [`Dynamic`]: ArraySize::Dynamic + /// [`Struct`]: TypeInner::Struct + /// [`Pointer`]: TypeInner::Pointer + /// [`AccessIndex`]: Expression::AccessIndex Array { base: Handle, size: ArraySize, stride: u32, }, + /// User-defined structure. + /// + /// A `Struct` type is [`DATA`], and the types of its members must be + /// `DATA` as well. + /// + /// Member types must be [`SIZED`], except for the final member of a + /// top-level struct, which may be a dynamically sized [`Array`]. The + /// `Struct` type itself is `SIZED` when all its members are `SIZED`. + /// + /// When `top_level` is true, this `Struct` represents the contents of a + /// buffer resource occupying a single binding slot in a shader's resource + /// interface. Top-level `Struct`s may not be used as members of any other + /// struct, or as array elements. + /// + /// [`DATA`]: crate::valid::TypeFlags::DATA + /// [`SIZED`]: crate::valid::TypeFlags::SIZED + /// [`Array`]: TypeInner::Array Struct { + /// This struct serves as the type of a binding slot in a shader's resource interface. top_level: bool, members: Vec, //TODO: should this be unaligned? diff --git a/src/valid/type.rs b/src/valid/type.rs index 7ddc0f6aa..474c5dc0a 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -5,16 +5,45 @@ use crate::{ }; bitflags::bitflags! { + /// Flags associated with [`Type`]s by [`Validator`]. + /// + /// [`Type`]: crate::Type + /// [`Validator`]: crate::valid::Validator #[repr(transparent)] pub struct TypeFlags: u8 { /// Can be used for data variables. + /// + /// This flag is required on types of local variables, function + /// arguments, array elements, and struct members. + /// + /// This includes all types except `Image`, `Sampler`, `ValuePointer`, + /// and some `Pointer` types. const DATA = 0x1; - /// The data type has known size. + + /// The data type has a size known by pipeline creation time. + /// + /// Unsized types are quite restricted. The only unsized types permitted + /// by Naga, other than the non-[`DATA`] types like [`Image`] and + /// [`Sampler`], are dynamically-sized [`Array`s], and [`Struct`s] whose + /// last members are such arrays. See the documentation for those types + /// for details. + /// + /// [`DATA`]: TypeFlags::DATA + /// [`Image`]: crate::Type::Image + /// [`Sampler`]: crate::Type::Sampler + /// [`Array`]: crate::Type::Array + /// [`Struct`]: crate::Type::struct const SIZED = 0x2; + /// Can be be used for interfacing between pipeline stages. + /// + /// This includes non-bool scalars and vectors, matrices, and structs + /// and arrays containing only interface types. const INTERFACE = 0x4; + /// Can be used for host-shareable structures. const HOST_SHARED = 0x8; + /// This is a top-level host-shareable type. const TOP_LEVEL = 0x10; } From 16d7c0e42864ce89a3cf505934f5847979606519 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 19 Jun 2021 21:50:12 +0100 Subject: [PATCH 1006/2212] [glsl-in] Implement texelFetch --- src/front/glsl/functions.rs | 72 +++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index ecadf0ac0..ee0697684 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -2,6 +2,7 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Block, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, LocalVariable, MathFunction, RelationalFunction, SampleLevel, ScalarKind, Statement, StructMember, SwizzleComponent, Type, TypeInner, + VectorSize, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; @@ -203,6 +204,77 @@ impl Program<'_> { )) } } + "texelFetch" => { + if args.len() != 3 { + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + } + if ctx.samplers.get(&args[0].0).is_some() { + let (arrayed, dims) = + match *self.resolve_type(ctx, args[0].0, args[0].1)? { + TypeInner::Image { arrayed, dim, .. } => (arrayed, dim), + _ => (false, crate::ImageDimension::D1), + }; + + let (coordinate, array_index) = if arrayed { + ( + match dims { + crate::ImageDimension::D1 => ctx.add_expression( + Expression::AccessIndex { + base: args[1].0, + index: 0, + }, + body, + ), + crate::ImageDimension::D2 => ctx.add_expression( + Expression::Swizzle { + size: VectorSize::Bi, + vector: args[1].0, + pattern: SwizzleComponent::XYZW, + }, + body, + ), + _ => ctx.add_expression( + Expression::Swizzle { + size: VectorSize::Tri, + vector: args[1].0, + pattern: SwizzleComponent::XYZW, + }, + body, + ), + }, + Some(ctx.add_expression( + Expression::AccessIndex { + base: args[1].0, + index: match dims { + crate::ImageDimension::D1 => 1, + crate::ImageDimension::D2 => 2, + crate::ImageDimension::D3 => 3, + crate::ImageDimension::Cube => 2, + }, + }, + body, + )), + ) + } else { + (args[1].0, None) + }; + + Ok(Some(ctx.add_expression( + Expression::ImageLoad { + image: args[0].0, + coordinate, + array_index, + index: Some(args[2].0), + }, + body, + ))) + } else { + Err(ErrorKind::SemanticError( + meta, + "Bad call to texelFetch".into(), + )) + } + } "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" | "normalize" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" From fd042e6f31b6103e6b537c04b3d3ccd1e6ea8e17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 19 Jun 2021 21:50:42 +0100 Subject: [PATCH 1007/2212] [glsl-in] Implement default for options --- src/front/glsl/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 41e6967db..1db77c271 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -19,6 +19,7 @@ mod token; mod types; mod variables; +#[derive(Default)] pub struct Options { pub entry_points: FastHashMap, pub defines: FastHashMap, From 68609cdff88733007539268d9e2d76f8f5730dcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 20 Jun 2021 10:44:10 +0100 Subject: [PATCH 1008/2212] [glsl-in] Implement textureSize --- src/front/glsl/functions.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index ee0697684..8dd0c0d36 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,8 +1,8 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Block, EntryPoint, Expression, Function, - FunctionArgument, FunctionResult, Handle, LocalVariable, MathFunction, RelationalFunction, - SampleLevel, ScalarKind, Statement, StructMember, SwizzleComponent, Type, TypeInner, - VectorSize, + FunctionArgument, FunctionResult, Handle, ImageQuery, LocalVariable, MathFunction, + RelationalFunction, SampleLevel, ScalarKind, Statement, StructMember, SwizzleComponent, Type, + TypeInner, VectorSize, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; @@ -204,6 +204,21 @@ impl Program<'_> { )) } } + "textureSize" => { + if !(1..=2).contains(&args.len()) { + return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); + } + + Ok(Some(ctx.add_expression( + Expression::ImageQuery { + image: args[0].0, + query: ImageQuery::Size { + level: args.get(1).map(|e| e.0), + }, + }, + body, + ))) + } "texelFetch" => { if args.len() != 3 { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); From 60644504d8e7a79791f998fc98e540475cc40639 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 20 Jun 2021 10:44:29 +0100 Subject: [PATCH 1009/2212] [glsl-in] Implicit cast stores with ValuePointer --- src/front/glsl/ast.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index f7e920888..574213b28 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -606,6 +606,7 @@ impl<'function> Context<'function> { TypeInner::Pointer { base, .. } => { program.module.types[base].inner.scalar_kind() } + TypeInner::ValuePointer { kind, .. } => Some(kind), ref ty => ty.scalar_kind(), }; From e7d712e608c8aa415d6fe0e3c9785d26ac8cfb9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 20 Jun 2021 11:00:31 +0100 Subject: [PATCH 1010/2212] [glsl-in] Apply constant binary ops to composites --- src/front/glsl/constants.rs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 1143b90f3..9f5036aa8 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -340,10 +340,10 @@ impl<'a> ConstantSolver<'a> { left: Handle, right: Handle, ) -> Result, ConstantSolvingError> { - let left = &self.constants[left].inner; - let right = &self.constants[right].inner; + let left_inner = &self.constants[left].inner; + let right_inner = &self.constants[right].inner; - let inner = match (left, right) { + let inner = match (left_inner, right_inner) { ( &ConstantInner::Scalar { value: left_value, @@ -416,6 +416,20 @@ impl<'a> ConstantSolver<'a> { ConstantInner::Scalar { value, width } } + (&ConstantInner::Composite { ref components, ty }, &ConstantInner::Scalar { .. }) => { + let mut components = components.clone(); + for comp in components.iter_mut() { + *comp = self.binary_op(op, *comp, right)?; + } + ConstantInner::Composite { ty, components } + } + (&ConstantInner::Scalar { .. }, &ConstantInner::Composite { ref components, ty }) => { + let mut components = components.clone(); + for comp in components.iter_mut() { + *comp = self.binary_op(op, left, *comp)?; + } + ConstantInner::Composite { ty, components } + } _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), }; From 01036e8f4213b9dbd6cf7db5e9256e7400957474 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 20 Jun 2021 11:01:33 +0100 Subject: [PATCH 1011/2212] [glsl-in] Use crate::BOOL_WIDTH for booleans width --- src/front/glsl/types.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 715c0c743..ed3ec3649 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -6,7 +6,7 @@ pub fn parse_type(type_name: &str) -> Option { name: None, inner: TypeInner::Scalar { kind: ScalarKind::Bool, - width: 4, // https://stackoverflow.com/questions/9419781/what-is-the-size-of-glsl-boolean + width: crate::BOOL_WIDTH, }, }), "float" => Some(Type { @@ -56,7 +56,7 @@ pub fn parse_type(type_name: &str) -> Option { fn kind_width_parse(ty: &str) -> Option<(ScalarKind, u8)> { Some(match ty { "" => (ScalarKind::Float, 4), - "b" => (ScalarKind::Bool, 4), + "b" => (ScalarKind::Bool, crate::BOOL_WIDTH), "i" => (ScalarKind::Sint, 4), "u" => (ScalarKind::Uint, 4), "d" => (ScalarKind::Float, 8), From c152205c8723ab95ea4b95cf01c25a60a6c49770 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 20 Jun 2021 20:15:41 +0100 Subject: [PATCH 1012/2212] [glsl-in] arguments of opaque types are constant --- src/front/glsl/ast.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 574213b28..c468a905f 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -345,6 +345,11 @@ impl<'function> Context<'function> { }; parameters.push(ty); + let opaque = match program.module.types[ty].inner { + TypeInner::Image { .. } | TypeInner::Sampler { .. } => true, + _ => false, + }; + if qualifier.is_lhs() { arg.ty = program.module.types.fetch_or_append(Type { name: None, @@ -359,7 +364,7 @@ impl<'function> Context<'function> { if let Some(name) = name { let expr = self.add_expression(Expression::FunctionArgument(index as u32), body); - let mutable = qualifier != ParameterQualifier::Const; + let mutable = qualifier != ParameterQualifier::Const && !opaque; let load = qualifier.is_lhs(); if mutable && !load { From ffe67139cdaa5c3fecaa3c965609d77ea24a4358 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 20 Jun 2021 20:16:55 +0100 Subject: [PATCH 1013/2212] [glsl-in] Add support for mix with bool selectors --- src/front/glsl/functions.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 8dd0c0d36..bd9b443fa 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -413,14 +413,42 @@ impl Program<'_> { body, ))) } - "mix" | "clamp" | "faceforward" | "refract" | "fma" | "smoothstep" => { + "mix" => { + if args.len() != 3 { + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + } + Ok(Some( + if let Some(ScalarKind::Bool) = + self.resolve_type(ctx, args[2].0, args[2].1)?.scalar_kind() + { + ctx.add_expression( + Expression::Select { + condition: args[2].0, + accept: args[0].0, + reject: args[1].0, + }, + body, + ) + } else { + ctx.add_expression( + Expression::Math { + fun: MathFunction::Mix, + arg: args[0].0, + arg1: Some(args[1].0), + arg2: Some(args[2].0), + }, + body, + ) + }, + )) + } + "clamp" | "faceforward" | "refract" | "fma" | "smoothstep" => { if args.len() != 3 { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } Ok(Some(ctx.add_expression( Expression::Math { fun: match name.as_str() { - "mix" => MathFunction::Mix, "clamp" => MathFunction::Clamp, "faceforward" => MathFunction::FaceForward, "refract" => MathFunction::Refract, From cae71a788a7c5b0d68af64f517341d066aa6a274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 21 Jun 2021 11:26:47 +0100 Subject: [PATCH 1014/2212] [glsl-in] Support for vector scalar operations --- src/front/glsl/ast.rs | 116 ++++++++++++++++++++++++++---------------- 1 file changed, 73 insertions(+), 43 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index c468a905f..91c62f7a6 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -115,12 +115,12 @@ impl<'a> Program<'a> { } } - pub fn resolve_type<'b>( - &'b self, - context: &'b mut Context, + pub fn typifier_grow( + &self, + context: &mut Context, handle: Handle, meta: SourceMetadata, - ) -> Result<&'b TypeInner, ErrorKind> { + ) -> Result<(), ErrorKind> { let resolve_ctx = ResolveContext { constants: &self.module.constants, types: &self.module.types, @@ -129,17 +129,23 @@ impl<'a> Program<'a> { functions: &self.module.functions, arguments: context.arguments, }; - match context + + context .typifier .grow(handle, context.expressions, &resolve_ctx) - { - //TODO: better error report - Err(error) => Err(ErrorKind::SemanticError( - meta, - format!("Can't resolve type: {:?}", error).into(), - )), - Ok(()) => Ok(context.typifier.get(handle, &self.module.types)), - } + .map_err(|error| { + ErrorKind::SemanticError(meta, format!("Can't resolve type: {:?}", error).into()) + }) + } + + pub fn resolve_type<'b>( + &'b self, + context: &'b mut Context, + handle: Handle, + meta: SourceMetadata, + ) -> Result<&'b TypeInner, ErrorKind> { + self.typifier_grow(context, handle, meta)?; + Ok(context.typifier.get(handle, &self.module.types)) } pub fn solve_constant( @@ -506,40 +512,64 @@ impl<'function> Context<'function> { program, &mut left, left_meta, &mut right, right_meta, )?; - if let BinaryOperator::Equal | BinaryOperator::NotEqual = op { - let equals = op == BinaryOperator::Equal; - let (left_is_vector, left_dims) = - match *program.resolve_type(self, left, left_meta)? { - crate::TypeInner::Vector { .. } => (true, 1), - crate::TypeInner::Matrix { .. } => (false, 2), - _ => (false, 0), - }; + program.typifier_grow(self, left, left_meta)?; + program.typifier_grow(self, right, right_meta)?; - let (right_is_vector, right_dims) = - match *program.resolve_type(self, right, right_meta)? { - crate::TypeInner::Vector { .. } => (true, 1), - crate::TypeInner::Matrix { .. } => (false, 2), - _ => (false, 0), - }; + let left_inner = self.typifier.get(left, &program.module.types); + let right_inner = self.typifier.get(right, &program.module.types); - let (op, fun) = match equals { - true => (BinaryOperator::Equal, RelationalFunction::All), - false => (BinaryOperator::NotEqual, RelationalFunction::Any), - }; + match (left_inner, right_inner) { + (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) + | (&TypeInner::Matrix { .. }, &TypeInner::Matrix { .. }) => match op { + BinaryOperator::Equal | BinaryOperator::NotEqual => { + let equals = op == BinaryOperator::Equal; - let argument = self - .expressions - .append(Expression::Binary { op, left, right }); + let (op, fun) = match equals { + true => (BinaryOperator::Equal, RelationalFunction::All), + false => (BinaryOperator::NotEqual, RelationalFunction::Any), + }; - if left_dims != right_dims { - return Err(ErrorKind::SemanticError(meta, "Cannot compare".into())); - } else if left_is_vector && right_is_vector { - self.add_expression(Expression::Relational { fun, argument }, body) - } else { - argument - } - } else { - self.add_expression(Expression::Binary { left, op, right }, body) + let argument = + self.expressions + .append(Expression::Binary { op, left, right }); + + self.add_expression(Expression::Relational { fun, argument }, body) + } + _ => self.add_expression(Expression::Binary { left, op, right }, body), + }, + (&TypeInner::Vector { size, .. }, &TypeInner::Scalar { .. }) => match op { + BinaryOperator::Add | BinaryOperator::Subtract | BinaryOperator::Divide => { + let scalar_vector = + self.add_expression(Expression::Splat { size, value: right }, body); + + self.add_expression( + Expression::Binary { + op, + left, + right: scalar_vector, + }, + body, + ) + } + _ => self.add_expression(Expression::Binary { left, op, right }, body), + }, + (&TypeInner::Scalar { .. }, &TypeInner::Vector { size, .. }) => match op { + BinaryOperator::Add | BinaryOperator::Subtract | BinaryOperator::Divide => { + let scalar_vector = + self.add_expression(Expression::Splat { size, value: left }, body); + + self.add_expression( + Expression::Binary { + op, + left: scalar_vector, + right, + }, + body, + ) + } + _ => self.add_expression(Expression::Binary { left, op, right }, body), + }, + _ => self.add_expression(Expression::Binary { left, op, right }, body), } } HirExprKind::Unary { op, expr } if !lhs => { From 548cde4701510ea66f14de338046034550700d70 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 21 Jun 2021 10:55:49 -0700 Subject: [PATCH 1015/2212] Clear Validator::valid_expression_list before validating each function. If validation fails, `Validator` may be left with entries in `valid_expression_list` and `valid_expression_set`. The validator does clear the set before examining a function's body, but not the list, which means a long-lived `Validator` could accumulate an unbounded amount of garbage in the list. (Minor cleanup: use structural update syntax where appropriate.) --- src/valid/function.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 0c68d8e04..caac37e48 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -147,16 +147,7 @@ impl<'a> BlockContext<'a> { } fn with_flags(&self, flags: Flags) -> Self { - BlockContext { - flags, - info: self.info, - expressions: self.expressions, - types: self.types, - global_vars: self.global_vars, - functions: self.functions, - prev_infos: self.prev_infos, - return_type: self.return_type, - } + BlockContext { flags, ..*self } } fn get_expression( @@ -576,6 +567,7 @@ impl super::Validator { } self.valid_expression_set.clear(); + self.valid_expression_list.clear(); for (handle, expr) in fun.expressions.iter() { if expr.needs_pre_emit() { self.valid_expression_set.insert(handle.index()); From 3a4d6fa29584228e206ecb1d0eeac6dd565cdb1c Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 21 Jun 2021 19:14:03 +0000 Subject: [PATCH 1016/2212] Reduce code duplication between backends --- src/back/glsl/mod.rs | 4 +--- src/back/hlsl/writer.rs | 5 +---- src/back/mod.rs | 7 +++++++ src/back/msl/writer.rs | 6 +----- src/back/wgsl/writer.rs | 9 ++++----- 5 files changed, 14 insertions(+), 17 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 3a85a6c9b..462e88031 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -44,6 +44,7 @@ pub use features::Features; use crate::{ + back::{COMPONENTS, INDENT}, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, @@ -69,9 +70,6 @@ mod keywords; pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; /// List of supported es glsl versions pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; -const INDENT: &str = " "; - -const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; /// glsl version #[derive(Debug, Copy, Clone, PartialEq)] diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 9dc899277..e2af05f64 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2,7 +2,7 @@ #![allow(dead_code)] use super::{Error, Options, ShaderModel}; use crate::{ - back::{hlsl::keywords::RESERVED, vector_size_str}, + back::{hlsl::keywords::RESERVED, vector_size_str, BAKE_PREFIX, COMPONENTS, INDENT}, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, Arena, ArraySize, BuiltIn, Bytes, Constant, ConstantInner, Expression, FastHashMap, Function, @@ -11,10 +11,7 @@ use crate::{ }; use std::fmt::Write; -const INDENT: &str = " "; -const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; const LOCATION_SEMANTIC: &str = "LOC"; -const BAKE_PREFIX: &str = "_e"; /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; diff --git a/src/back/mod.rs b/src/back/mod.rs index 4874cadde..c312c0317 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -13,6 +13,13 @@ pub mod spv; #[cfg(feature = "wgsl-out")] pub mod wgsl; +#[allow(dead_code)] +const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; +#[allow(dead_code)] +const INDENT: &str = " "; +#[allow(dead_code)] +const BAKE_PREFIX: &str = "_e"; + /// How should code generated by Naga do indexing bounds checks? /// /// When a vector, matrix, or array index is out of bounds—either negative, or diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7301c4f06..ace3af23f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -4,7 +4,7 @@ use super::{ }; use crate::{ arena::{Arena, Handle}, - back::vector_size_str, + back::{vector_size_str, BAKE_PREFIX, COMPONENTS, INDENT}, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{Capabilities, FunctionInfo, GlobalUse, ModuleInfo}, FastHashMap, @@ -15,8 +15,6 @@ use std::{ }; const NAMESPACE: &str = "metal"; -const INDENT: &str = " "; -const BAKE_PREFIX: &str = "_e"; const WRAPPED_ARRAY_FIELD: &str = "inner"; #[derive(Clone)] @@ -305,8 +303,6 @@ fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { } } -const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; - fn separate(need_separator: bool) -> &'static str { if need_separator { "," diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index f37bd202c..03b9a050e 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1,6 +1,9 @@ use super::Error; use crate::{ - back::{binary_operation_str, vector_size_str, wgsl::keywords::RESERVED}, + back::{ + binary_operation_str, vector_size_str, wgsl::keywords::RESERVED, BAKE_PREFIX, COMPONENTS, + INDENT, + }, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, Arena, ArraySize, Binding, Constant, ConstantInner, Expression, FastHashMap, Function, @@ -10,10 +13,6 @@ use crate::{ }; use std::fmt::Write; -const INDENT: &str = " "; -const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; -const BAKE_PREFIX: &str = "_e"; - /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; From 93436047f3d1f6fc957c2bb993338be7d8d5c03d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 21 Jun 2021 19:22:51 +0100 Subject: [PATCH 1017/2212] [glsl-in] Fix builtin types --- src/front/glsl/variables.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index c3fb8c766..32cb0eff9 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -94,7 +94,7 @@ impl Program<'_> { ), "gl_VertexIndex" => add_builtin( TypeInner::Scalar { - kind: ScalarKind::Sint, + kind: ScalarKind::Uint, width: 4, }, BuiltIn::VertexIndex, @@ -103,7 +103,7 @@ impl Program<'_> { ), "gl_InstanceIndex" => add_builtin( TypeInner::Scalar { - kind: ScalarKind::Sint, + kind: ScalarKind::Uint, width: 4, }, BuiltIn::InstanceIndex, @@ -123,7 +123,7 @@ impl Program<'_> { "gl_FrontFacing" => add_builtin( TypeInner::Scalar { kind: ScalarKind::Bool, - width: 1, + width: crate::BOOL_WIDTH, }, BuiltIn::FrontFacing, false, From 898c2e7c68e7ddf652f403e17205e8b1cdf1c2b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 21 Jun 2021 20:36:15 +0100 Subject: [PATCH 1018/2212] [glsl-in] Use macro for qualifier match --- src/front/glsl/variables.rs | 90 +++++++++++++++++-------------------- 1 file changed, 40 insertions(+), 50 deletions(-) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 32cb0eff9..effad7b18 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -8,6 +8,16 @@ use super::ast::*; use super::error::ErrorKind; use super::token::SourceMetadata; +macro_rules! qualifier_arm { + ($src:expr, $tgt:expr, $meta:expr, $msg:literal $(,)?) => {{ + if $tgt.is_some() { + return Err(ErrorKind::SemanticError($meta, $msg.into())); + } + + $tgt = Some($src); + }}; +} + pub struct VarDeclaration<'a> { pub qualifiers: &'a [(TypeQualifier, SourceMetadata)], pub ty: Handle, @@ -310,57 +320,37 @@ impl Program<'_> { storage = s; } - TypeQualifier::Interpolation(i) => { - if interpolation.is_some() { - return Err(ErrorKind::SemanticError( - meta, - "Cannot use more than one interpolation qualifier per declaration" - .into(), - )); - } + TypeQualifier::Interpolation(i) => qualifier_arm!( + i, + interpolation, + meta, + "Cannot use more than one interpolation qualifier per declaration" + ), + TypeQualifier::ResourceBinding(ref r) => qualifier_arm!( + r.clone(), + binding, + meta, + "Cannot use more than one binding per declaration" + ), + TypeQualifier::Location(l) => qualifier_arm!( + l, + location, + meta, + "Cannot use more than one binding per declaration" + ), + TypeQualifier::Sampling(s) => qualifier_arm!( + s, + sampling, + meta, + "Cannot use more than one sampling qualifier per declaration" + ), + TypeQualifier::Layout(ref l) => qualifier_arm!( + l, + layout, + meta, + "Cannot use more than one layout qualifier per declaration" + ), - interpolation = Some(i); - } - TypeQualifier::ResourceBinding(ref r) => { - if binding.is_some() { - return Err(ErrorKind::SemanticError( - meta, - "Cannot use more than one binding per declaration".into(), - )); - } - - binding = Some(r.clone()); - } - TypeQualifier::Location(l) => { - if location.is_some() { - return Err(ErrorKind::SemanticError( - meta, - "Cannot use more than one binding per declaration".into(), - )); - } - - location = Some(l); - } - TypeQualifier::Sampling(s) => { - if sampling.is_some() { - return Err(ErrorKind::SemanticError( - meta, - "Cannot use more than one sampling qualifier per declaration".into(), - )); - } - - sampling = Some(s); - } - TypeQualifier::Layout(ref l) => { - if layout.is_some() { - return Err(ErrorKind::SemanticError( - meta, - "Cannot use more than one layout qualifier per declaration".into(), - )); - } - - layout = Some(l); - } _ => { return Err(ErrorKind::SemanticError( meta, From d3fe1c978b155dcbc83d1127cee5a93b88e2e145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 21 Jun 2021 21:27:55 +0100 Subject: [PATCH 1019/2212] [glsl-in] Add support for precision qualifiers --- src/front/glsl/ast.rs | 9 ++++++ src/front/glsl/lex.rs | 6 ++++ src/front/glsl/parser.rs | 57 +++++++++++++++++++++++++++++++--- src/front/glsl/parser_tests.rs | 9 ++++++ src/front/glsl/token.rs | 3 ++ src/front/glsl/variables.rs | 8 ++++- 6 files changed, 86 insertions(+), 6 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 91c62f7a6..d1ba273d3 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -955,6 +955,7 @@ pub enum TypeQualifier { WorkGroupSize(usize, u32), Sampling(Sampling), Layout(StructLayout), + Precision(Precision), EarlyFragmentTests, } @@ -984,6 +985,14 @@ pub enum StructLayout { Std430, } +// TODO: Encode precision hints in the IR +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum Precision { + Low, + Medium, + High, +} + #[derive(Debug, Clone, PartialEq, Copy)] pub enum ParameterQualifier { In, diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index fb203dd6c..e12cb5e3e 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -1,4 +1,5 @@ use super::{ + ast::Precision, token::{SourceMetadata, Token, TokenValue}, types::parse_type, }; @@ -58,6 +59,7 @@ impl<'a> Iterator for Lexer<'a> { PPTokenValue::Float(float) => TokenValue::FloatConstant(float), PPTokenValue::Ident(ident) => { match ident.as_str() { + // Qualifiers "layout" => TokenValue::Layout, "in" => TokenValue::In, "out" => TokenValue::Out, @@ -70,6 +72,10 @@ impl<'a> Iterator for Lexer<'a> { "sample" => TokenValue::Sampling(crate::Sampling::Sample), "const" => TokenValue::Const, "inout" => TokenValue::InOut, + "precision" => TokenValue::Precision, + "highp" => TokenValue::PrecisionQualifier(Precision::High), + "mediump" => TokenValue::PrecisionQualifier(Precision::Medium), + "lowp" => TokenValue::PrecisionQualifier(Precision::Low), // values "true" => TokenValue::BoolConstant(true), "false" => TokenValue::BoolConstant(false), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b1f933e10..9d0700780 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -10,9 +10,11 @@ use super::{ Program, }; use crate::{ - arena::Handle, front::glsl::error::ExpectedToken, Arena, ArraySize, BinaryOperator, Block, - Constant, ConstantInner, Expression, Function, FunctionResult, ResourceBinding, ScalarValue, - Statement, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator, + arena::Handle, + front::glsl::{ast::Precision, error::ExpectedToken}, + Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Expression, Function, + FunctionResult, ResourceBinding, ScalarKind, ScalarValue, Statement, StorageClass, + StructMember, SwitchCase, Type, TypeInner, UnaryOperator, }; use core::convert::TryFrom; use std::{iter::Peekable, mem}; @@ -206,6 +208,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.lexer.peek().map_or(false, |t| match t.value { TokenValue::Interpolation(_) | TokenValue::Sampling(_) + | TokenValue::PrecisionQualifier(_) | TokenValue::Const | TokenValue::In | TokenValue::Out @@ -241,7 +244,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { StorageQualifier::StorageClass(StorageClass::Storage), ), TokenValue::Sampling(s) => TypeQualifier::Sampling(s), - + TokenValue::PrecisionQualifier(p) => TypeQualifier::Precision(p), _ => unreachable!(), }, token.meta, @@ -829,7 +832,51 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } } else { - Ok(false) + match self.lexer.peek().map(|t| &t.value) { + Some(&TokenValue::Precision) => { + // PRECISION precision_qualifier type_specifier SEMICOLON + self.bump()?; + + let token = self.bump()?; + let _ = match token.value { + TokenValue::PrecisionQualifier(p) => p, + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ + TokenValue::PrecisionQualifier(Precision::High).into(), + TokenValue::PrecisionQualifier(Precision::Medium).into(), + TokenValue::PrecisionQualifier(Precision::Low).into(), + ], + )) + } + }; + + let (ty, meta) = self.parse_type_non_void()?; + + match self.program.module.types[ty].inner { + TypeInner::Scalar { + kind: ScalarKind::Float, + .. + } + | TypeInner::Scalar { + kind: ScalarKind::Sint, + .. + } => {} + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Precision statement can only work on floats and ints".into(), + )) + } + } + + self.expect(TokenValue::Semicolon)?; + + Ok(true) + } + _ => Ok(false), + } } } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 8ff6aa1fe..4b1b9ae32 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -246,6 +246,15 @@ fn declarations() { &entry_points, ) .unwrap(); + + let _program = parse_program( + r#" + #version 450 + precision highp float; + "#, + &entry_points, + ) + .unwrap(); } #[test] diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 7d01ffb77..b1f147ab7 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -1,5 +1,6 @@ pub use pp_rs::token::{Float, Integer, PreprocessorError}; +use super::ast::Precision; use crate::{Interpolation, Sampling, Type}; use std::{fmt, ops::Range}; @@ -57,6 +58,8 @@ pub enum TokenValue { Const, Interpolation(Interpolation), Sampling(Sampling), + Precision, + PrecisionQualifier(Precision), Continue, Break, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index effad7b18..529036caa 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -302,6 +302,7 @@ impl Program<'_> { let mut location = None; let mut sampling = None; let mut layout = None; + let mut precision = None; for &(ref qualifier, meta) in qualifiers { match *qualifier { @@ -350,7 +351,12 @@ impl Program<'_> { meta, "Cannot use more than one layout qualifier per declaration" ), - + TypeQualifier::Precision(ref p) => qualifier_arm!( + p, + precision, + meta, + "Cannot use more than one precision qualifier per declaration" + ), _ => { return Err(ErrorKind::SemanticError( meta, From 9b823c1b60c6df40cc0b2fecada891b1c209bea5 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 21 Jun 2021 23:32:32 +0300 Subject: [PATCH 1020/2212] [hlsl-out] Implement Access and Unary expressions --- src/back/hlsl/mod.rs | 2 +- src/back/hlsl/writer.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 3b94239a0..5825f5990 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -50,7 +50,7 @@ impl Default for Options { pub enum Error { #[error(transparent)] IoError(#[from] FmtError), - #[error("BuiltIn {0:?} is not supported")] + #[error("Shader model {0:?} is not supported")] UnsupportedShaderModel(ShaderModel), #[error("A scalar with an unsupported width was requested: {0:?} {1:?}")] UnsupportedScalar(crate::ScalarKind, crate::Bytes), diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index e2af05f64..aa81c9d6d 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -937,6 +937,38 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}", name)?; } Expression::Load { pointer } => self.write_expr(module, pointer, func_ctx)?, + Expression::Access { base, index } => { + self.write_expr(module, base, func_ctx)?; + write!(self.out, "[")?; + self.write_expr(module, index, func_ctx)?; + write!(self.out, "]")? + } + Expression::Unary { op, expr } => { + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators + write!( + self.out, + "({} ", + match op { + crate::UnaryOperator::Negate => "-", + crate::UnaryOperator::Not => + match *func_ctx.info[expr].ty.inner_with(&module.types) { + TypeInner::Scalar { + kind: ScalarKind::Bool, + .. + } => "!", + ref other => + return Err(Error::Custom(format!( + "Cannot apply not to type {:?}", + other + ))), + }, + } + )?; + + self.write_expr(module, expr, func_ctx)?; + + write!(self.out, ")")? + } _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } From 064263272ccc3e4d7e2d1627b3d8ac549775e659 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 18 Jun 2021 23:04:49 -0400 Subject: [PATCH 1021/2212] Refactor control flow validation, allow break in switches --- src/valid/function.rs | 61 +++++++++++++++++++++++++++++-------------- 1 file changed, 41 insertions(+), 20 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index caac37e48..bb5d49c97 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -65,8 +65,10 @@ pub enum FunctionError { InvalidArgumentType { index: usize, name: String }, #[error("There are instructions after `return`/`break`/`continue`")] InstructionsAfterReturn, - #[error("The `break`/`continue` is used outside of a loop context")] - BreakContinueOutsideOfLoop, + #[error("The `break` is used outside of a `loop` or `switch` context")] + BreakOutsideOfLoopOrSwitch, + #[error("The `continue` is used outside of a `loop` context")] + ContinueOutsideOfLoop, #[error("The `return` is called within a `continuing` block")] InvalidReturnSpot, #[error("The `return` value {0:?} does not match the function return value")] @@ -108,16 +110,18 @@ pub enum FunctionError { bitflags::bitflags! { #[repr(transparent)] - struct Flags: u8 { - /// The control can jump out of this block. - const CAN_JUMP = 0x1; - /// The control is in a loop, can break and continue. - const IN_LOOP = 0x2; + struct ControlFlowAbility: u8 { + /// The control can return out of this block. + const RETURN = 0x1; + /// The control can break. + const BREAK = 0x2; + /// The control can continue. + const CONTINUE = 0x4; } } struct BlockContext<'a> { - flags: Flags, + abilities: ControlFlowAbility, info: &'a FunctionInfo, expressions: &'a Arena, types: &'a Arena, @@ -135,7 +139,7 @@ impl<'a> BlockContext<'a> { prev_infos: &'a [FunctionInfo], ) -> Self { Self { - flags: Flags::CAN_JUMP, + abilities: ControlFlowAbility::RETURN, info, expressions: &fun.expressions, types: &module.types, @@ -146,8 +150,8 @@ impl<'a> BlockContext<'a> { } } - fn with_flags(&self, flags: Flags) -> Self { - BlockContext { flags, ..*self } + fn with_abilities(&self, abilities: ControlFlowAbility) -> Self { + BlockContext { abilities, ..*self } } fn get_expression( @@ -304,10 +308,14 @@ impl super::Validator { return Err(FunctionError::ConflictingSwitchCase(case.value)); } } + let pass_through_abilities = context.abilities + & (ControlFlowAbility::RETURN | ControlFlowAbility::CONTINUE); + let sub_context = + context.with_abilities(pass_through_abilities | ControlFlowAbility::BREAK); for case in cases { - stages &= self.validate_block(&case.body, context)?; + stages &= self.validate_block(&case.body, &sub_context)?; } - stages &= self.validate_block(default, context)?; + stages &= self.validate_block(default, &sub_context)?; } S::Loop { ref body, @@ -316,24 +324,37 @@ impl super::Validator { // special handling for block scoping is needed here, // because the continuing{} block inherits the scope let base_expression_count = self.valid_expression_list.len(); + let pass_through_abilities = context.abilities & ControlFlowAbility::RETURN; stages &= self.validate_block_impl( body, - &context.with_flags(Flags::CAN_JUMP | Flags::IN_LOOP), + &context.with_abilities( + pass_through_abilities + | ControlFlowAbility::BREAK + | ControlFlowAbility::CONTINUE, + ), + )?; + stages &= self.validate_block_impl( + continuing, + &context.with_abilities(ControlFlowAbility::empty()), )?; - stages &= - self.validate_block_impl(continuing, &context.with_flags(Flags::empty()))?; for handle in self.valid_expression_list.drain(base_expression_count..) { self.valid_expression_set.remove(handle.index()); } } - S::Break | S::Continue => { - if !context.flags.contains(Flags::IN_LOOP) { - return Err(FunctionError::BreakContinueOutsideOfLoop); + S::Break => { + if !context.abilities.contains(ControlFlowAbility::BREAK) { + return Err(FunctionError::BreakOutsideOfLoopOrSwitch); + } + finished = true; + } + S::Continue => { + if !context.abilities.contains(ControlFlowAbility::CONTINUE) { + return Err(FunctionError::ContinueOutsideOfLoop); } finished = true; } S::Return { value } => { - if !context.flags.contains(Flags::CAN_JUMP) { + if !context.abilities.contains(ControlFlowAbility::RETURN) { return Err(FunctionError::InvalidReturnSpot); } let value_ty = value From ec6b18a7827af222f402701fa13d3a6e053112e4 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 22 Jun 2021 12:09:33 +0300 Subject: [PATCH 1022/2212] [glsl-out] Refactor FunctionCtx --- src/back/glsl/mod.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 462e88031..821dd63a3 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -187,7 +187,7 @@ enum FunctionType { /// Helper structure that stores data needed when writing the function struct FunctionCtx<'a> { /// The current function being written - func: FunctionType, + ty: FunctionType, /// Analysis about the function info: &'a FunctionInfo, /// The expression arena of the current function being written @@ -199,7 +199,7 @@ struct FunctionCtx<'a> { impl<'a> FunctionCtx<'_> { /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function fn name_key(&self, local: Handle) -> NameKey { - match self.func { + match self.ty { FunctionType::Function(handle) => NameKey::FunctionLocal(handle, local), FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, local), } @@ -210,7 +210,7 @@ impl<'a> FunctionCtx<'_> { /// # Panics /// - If the function arguments are less or equal to `arg` fn argument_key(&self, arg: u32) -> NameKey { - match self.func { + match self.ty { FunctionType::Function(handle) => NameKey::FunctionArgument(handle, arg), FunctionType::EntryPoint(ep_index) => NameKey::EntryPointArgument(ep_index, arg), } @@ -884,7 +884,7 @@ impl<'a, W: Write> Writer<'a, W> { ) -> BackendResult { // Create a function context for the function being written let ctx = FunctionCtx { - func: ty, + ty, info, expressions: &func.expressions, named_expressions: &func.named_expressions, @@ -905,7 +905,7 @@ impl<'a, W: Write> Writer<'a, W> { // Start by writing the return type if any otherwise write void // This is the only place where `void` is a valid type // (though it's more a keyword than a type) - if let FunctionType::EntryPoint(_) = ctx.func { + if let FunctionType::EntryPoint(_) = ctx.ty { write!(self.out, "void")?; } else if let Some(ref result) = func.result { self.write_type(result.ty)?; @@ -920,7 +920,7 @@ impl<'a, W: Write> Writer<'a, W> { // // We need access to `Self` here so we use the reference passed to the closure as an // argument instead of capturing as that would cause a borrow checker error - let arguments = match ctx.func { + let arguments = match ctx.ty { FunctionType::EntryPoint(_) => &[][..], FunctionType::Function(_) => &func.arguments, }; @@ -940,7 +940,7 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ") {{")?; // Compose the function arguments from globals, in case of an entry point. - if let FunctionType::EntryPoint(ep_index) = ctx.func { + if let FunctionType::EntryPoint(ep_index) = ctx.ty { let stage = self.module.entry_points[ep_index as usize].stage; for (index, arg) in func.arguments.iter().enumerate() { write!(self.out, "{}", INDENT)?; @@ -1355,7 +1355,7 @@ impl<'a, W: Write> Writer<'a, W> { // `return expr;`, `expr` is optional Statement::Return { value } => { write!(self.out, "{}", INDENT.repeat(indent))?; - match ctx.func { + match ctx.ty { FunctionType::Function(_) => { write!(self.out, "return")?; // Write the expression to be returned if needed From 0292a2897a85c9b668459f242469167c3bf1b914 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 22 Jun 2021 12:29:33 +0300 Subject: [PATCH 1023/2212] Move FunctionCtx into back module --- src/back/glsl/mod.rs | 55 +++++------------------------------------ src/back/hlsl/writer.rs | 49 +++++++----------------------------- src/back/mod.rs | 48 +++++++++++++++++++++++++++++++++++ src/back/wgsl/writer.rs | 48 ++++++----------------------------- 4 files changed, 70 insertions(+), 130 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 821dd63a3..0e04093bb 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -44,14 +44,14 @@ pub use features::Features; use crate::{ - back::{COMPONENTS, INDENT}, + back::{FunctionCtx, FunctionType, COMPONENTS, INDENT}, proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, - Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, - ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, - ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, Sampling, ScalarKind, - ScalarValue, ShaderStage, Statement, StorageAccess, StorageClass, StorageFormat, StructMember, - Type, TypeInner, UnaryOperator, + ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, + DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, + Interpolation, Module, RelationalFunction, Sampling, ScalarKind, ScalarValue, ShaderStage, + Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, + UnaryOperator, }; use features::FeaturesManager; use std::{ @@ -174,49 +174,6 @@ pub struct TextureMapping { pub sampler: Option>, } -/// Stores the current function type (either a regular function or an entry point) -/// -/// Also stores data needed to identify it (handle for a regular function or index for an entry point) -enum FunctionType { - /// A regular function and it's handle - Function(Handle), - /// A entry point and it's index - EntryPoint(EntryPointIndex), -} - -/// Helper structure that stores data needed when writing the function -struct FunctionCtx<'a> { - /// The current function being written - ty: FunctionType, - /// Analysis about the function - info: &'a FunctionInfo, - /// The expression arena of the current function being written - expressions: &'a Arena, - /// Map of expressions that have associated variable names - named_expressions: &'a crate::NamedExpressions, -} - -impl<'a> FunctionCtx<'_> { - /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function - fn name_key(&self, local: Handle) -> NameKey { - match self.ty { - FunctionType::Function(handle) => NameKey::FunctionLocal(handle, local), - FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, local), - } - } - - /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a function argument. - /// - /// # Panics - /// - If the function arguments are less or equal to `arg` - fn argument_key(&self, arg: u32) -> NameKey { - match self.ty { - FunctionType::Function(handle) => NameKey::FunctionArgument(handle, arg), - FunctionType::EntryPoint(ep_index) => NameKey::EntryPointArgument(ep_index, arg), - } - } -} - /// Helper structure that generates a number #[derive(Default)] struct IdGenerator(u32); diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index aa81c9d6d..6f0d3eb29 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2,12 +2,15 @@ #![allow(dead_code)] use super::{Error, Options, ShaderModel}; use crate::{ - back::{hlsl::keywords::RESERVED, vector_size_str, BAKE_PREFIX, COMPONENTS, INDENT}, - proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, - valid::{FunctionInfo, ModuleInfo}, - Arena, ArraySize, BuiltIn, Bytes, Constant, ConstantInner, Expression, FastHashMap, Function, - GlobalVariable, Handle, ImageDimension, LocalVariable, Module, ScalarKind, ScalarValue, - ShaderStage, Statement, StructMember, Type, TypeInner, + back::{ + hlsl::keywords::RESERVED, vector_size_str, FunctionCtx, FunctionType, BAKE_PREFIX, + COMPONENTS, INDENT, + }, + proc::{NameKey, Namer, TypeResolution}, + valid::ModuleInfo, + ArraySize, BuiltIn, Bytes, Constant, ConstantInner, Expression, FastHashMap, Function, + GlobalVariable, Handle, ImageDimension, Module, ScalarKind, ScalarValue, ShaderStage, + Statement, StructMember, Type, TypeInner, }; use std::fmt::Write; @@ -16,40 +19,6 @@ const LOCATION_SEMANTIC: &str = "LOC"; /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; -/// Stores the current function type (either a regular function or an entry point) -/// -/// Also stores data needed to identify it (handle for a regular function or index for an entry point) -// TODO: copy-paste from glsl-out, wgsl-out -enum FunctionType { - /// A regular function and it's handle - Function(Handle), - /// A entry point and it's index - EntryPoint(EntryPointIndex), -} - -/// Helper structure that stores data needed when writing the function -// TODO: copy-paste from glsl-out, wgsl-out -struct FunctionCtx<'a> { - /// The current function type being written - ty: FunctionType, - /// Analysis about the function - info: &'a FunctionInfo, - /// The expression arena of the current function being written - expressions: &'a Arena, - /// Map of expressions that have associated variable names - named_expressions: &'a crate::NamedExpressions, -} - -impl<'a> FunctionCtx<'_> { - /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function - fn name_key(&self, local: Handle) -> NameKey { - match self.ty { - FunctionType::Function(handle) => NameKey::FunctionLocal(handle, local), - FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, local), - } - } -} - struct EntryPointBinding { stage: ShaderStage, name: String, diff --git a/src/back/mod.rs b/src/back/mod.rs index c312c0317..09a18303f 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -20,6 +20,54 @@ const INDENT: &str = " "; #[allow(dead_code)] const BAKE_PREFIX: &str = "_e"; +/// Stores the current function type (either a regular function or an entry point) +/// +/// Also stores data needed to identify it (handle for a regular function or index for an entry point) +#[allow(dead_code)] +enum FunctionType { + /// A regular function and it's handle + Function(crate::Handle), + /// A entry point and it's index + EntryPoint(crate::proc::EntryPointIndex), +} + +/// Helper structure that stores data needed when writing the function +#[allow(dead_code)] +struct FunctionCtx<'a> { + /// The current function being written + ty: FunctionType, + /// Analysis about the function + info: &'a crate::valid::FunctionInfo, + /// The expression arena of the current function being written + expressions: &'a crate::Arena, + /// Map of expressions that have associated variable names + named_expressions: &'a crate::NamedExpressions, +} + +#[allow(dead_code)] +impl<'a> FunctionCtx<'_> { + /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function + fn name_key(&self, local: crate::Handle) -> crate::proc::NameKey { + match self.ty { + FunctionType::Function(handle) => crate::proc::NameKey::FunctionLocal(handle, local), + FunctionType::EntryPoint(idx) => crate::proc::NameKey::EntryPointLocal(idx, local), + } + } + + /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a function argument. + /// + /// # Panics + /// - If the function arguments are less or equal to `arg` + fn argument_key(&self, arg: u32) -> crate::proc::NameKey { + match self.ty { + FunctionType::Function(handle) => crate::proc::NameKey::FunctionArgument(handle, arg), + FunctionType::EntryPoint(ep_index) => { + crate::proc::NameKey::EntryPointArgument(ep_index, arg) + } + } + } +} + /// How should code generated by Naga do indexing bounds checks? /// /// When a vector, matrix, or array index is out of bounds—either negative, or diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 03b9a050e..188b18c62 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1,15 +1,15 @@ use super::Error; use crate::{ back::{ - binary_operation_str, vector_size_str, wgsl::keywords::RESERVED, BAKE_PREFIX, COMPONENTS, - INDENT, + binary_operation_str, vector_size_str, wgsl::keywords::RESERVED, FunctionCtx, FunctionType, + BAKE_PREFIX, COMPONENTS, INDENT, }, - proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, + proc::{NameKey, Namer, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, - Arena, ArraySize, Binding, Constant, ConstantInner, Expression, FastHashMap, Function, - GlobalVariable, Handle, ImageClass, ImageDimension, Interpolation, LocalVariable, Module, - SampleLevel, Sampling, ScalarKind, ScalarValue, ShaderStage, Statement, StorageClass, - StorageFormat, StructMember, Type, TypeInner, + ArraySize, Binding, Constant, ConstantInner, Expression, FastHashMap, Function, GlobalVariable, + Handle, ImageClass, ImageDimension, Interpolation, Module, SampleLevel, Sampling, ScalarKind, + ScalarValue, ShaderStage, Statement, StorageClass, StorageFormat, StructMember, Type, + TypeInner, }; use std::fmt::Write; @@ -31,40 +31,6 @@ enum Attribute { WorkGroupSize([u32; 3]), } -/// Stores the current function type (either a regular function or an entry point) -/// -/// Also stores data needed to identify it (handle for a regular function or index for an entry point) -// TODO: copy-paste from glsl-out -enum FunctionType { - /// A regular function and it's handle - Function(Handle), - /// A entry point and it's index - EntryPoint(EntryPointIndex), -} - -/// Helper structure that stores data needed when writing the function -// TODO: copy-paste from glsl-out -struct FunctionCtx<'a> { - /// The current function type being written - ty: FunctionType, - /// Analysis about the function - info: &'a FunctionInfo, - /// The expression arena of the current function being written - expressions: &'a Arena, - /// Map of expressions that have associated variable names - named_expressions: &'a crate::NamedExpressions, -} - -impl<'a> FunctionCtx<'_> { - /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function - fn name_key(&self, local: Handle) -> NameKey { - match self.ty { - FunctionType::Function(handle) => NameKey::FunctionLocal(handle, local), - FunctionType::EntryPoint(idx) => NameKey::EntryPointLocal(idx, local), - } - } -} - pub struct Writer { out: W, names: FastHashMap, From a5874eb0cfab4592323e6071d76eab81bceda556 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 22 Jun 2021 16:18:24 +0000 Subject: [PATCH 1024/2212] [wgsl-out] Fix Pointer writing --- src/back/wgsl/writer.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 188b18c62..bba0df446 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -521,6 +521,12 @@ impl Writer { vector_size_str(rows), )?; } + TypeInner::Pointer { base, class } => { + self.write_type(module, base)?; + if let Some(storage_class) = storage_class_str(class) { + write!(self.out, "<{}>", storage_class)?; + } + }, _ => { return Err(Error::Unimplemented(format!( "write_value_type {:?}", From 7eeab393b278696f785e2bbec1e636a94fc4c6db Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 23 Jun 2021 13:30:54 +0300 Subject: [PATCH 1025/2212] [glsl-out] Reduce global import usage --- src/back/glsl/mod.rs | 495 +++++++++++++++++++++++-------------------- 1 file changed, 270 insertions(+), 225 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 0e04093bb..f45c93a49 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -44,14 +44,9 @@ pub use features::Features; use crate::{ - back::{FunctionCtx, FunctionType, COMPONENTS, INDENT}, - proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, - valid::{FunctionInfo, ModuleInfo}, - ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant, ConstantInner, - DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle, ImageClass, - Interpolation, Module, RelationalFunction, Sampling, ScalarKind, ScalarValue, ShaderStage, - Statement, StorageAccess, StorageClass, StorageFormat, StructMember, Type, TypeInner, - UnaryOperator, + back, + proc::{self, NameKey}, + valid, Handle, ShaderStage, TypeInner, }; use features::FeaturesManager; use std::{ @@ -153,8 +148,8 @@ impl Default for Options { /// Structure that contains a reflection info pub struct ReflectionInfo { - pub texture_mapping: FastHashMap, - pub uniforms: FastHashMap, String>, + pub texture_mapping: crate::FastHashMap, + pub uniforms: crate::FastHashMap, String>, } /// Structure that connects a texture to a sampler or not @@ -169,9 +164,9 @@ pub struct ReflectionInfo { #[derive(Debug, Clone)] pub struct TextureMapping { /// Handle to the image global variable - pub texture: Handle, + pub texture: Handle, /// Handle to the associated sampler global variable if it exists - pub sampler: Option>, + pub sampler: Option>, } /// Helper structure that generates a number @@ -196,14 +191,14 @@ impl IdGenerator { /// prefix identifying which pipeline stage the varying connects, and `X` is /// the location. struct VaryingName<'a> { - binding: &'a Binding, + binding: &'a crate::Binding, stage: ShaderStage, output: bool, } impl fmt::Display for VaryingName<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self.binding { - Binding::Location { location, .. } => { + crate::Binding::Location { location, .. } => { let prefix = match (self.stage, self.output) { (ShaderStage::Compute, _) => unreachable!(), // pipeline to vertex @@ -215,7 +210,7 @@ impl fmt::Display for VaryingName<'_> { }; write!(f, "_{}_location{}", prefix, location,) } - Binding::BuiltIn(built_in) => { + crate::Binding::BuiltIn(built_in) => { write!(f, "{}", glsl_built_in(built_in, self.output)) } } @@ -251,7 +246,7 @@ pub enum Error { UnsupportedExternal(String), /// A scalar with an unsupported width was requested #[error("A scalar with an unsupported width was requested: {0:?} {1:?}")] - UnsupportedScalar(ScalarKind, Bytes), + UnsupportedScalar(crate::ScalarKind, crate::Bytes), /// A image was used with multiple samplers, this isn't supported #[error("A image was used with multiple samplers")] ImageMultipleSamplers, @@ -263,9 +258,9 @@ pub enum Error { pub struct Writer<'a, W> { // Inputs /// The module being written - module: &'a Module, + module: &'a crate::Module, /// The module analysis. - info: &'a ModuleInfo, + info: &'a valid::ModuleInfo, /// The output writer out: W, /// User defined configuration to be used @@ -274,16 +269,16 @@ pub struct Writer<'a, W> { // Internal State /// Features manager used to store all the needed features and write them features: FeaturesManager, - namer: Namer, + namer: proc::Namer, /// A map with all the names needed for writing the module /// (generated by a [`Namer`](crate::proc::Namer)) - names: FastHashMap, + names: crate::FastHashMap, /// A map with all the names needed for reflections - reflection_names: FastHashMap, String>, + reflection_names: crate::FastHashMap, String>, /// The selected entry point entry_point: &'a crate::EntryPoint, /// The index of the selected entry point - entry_point_idx: EntryPointIndex, + entry_point_idx: proc::EntryPointIndex, /// Used to generate a unique number for blocks block_id: IdGenerator, /// Set of expressions that have associated temporary variables @@ -299,8 +294,8 @@ impl<'a, W: Write> Writer<'a, W> { /// - If the version specified doesn't support some used features pub fn new( out: W, - module: &'a Module, - info: &'a ModuleInfo, + module: &'a crate::Module, + info: &'a valid::ModuleInfo, options: &'a Options, ) -> Result { // Check if the requested version is supported @@ -317,8 +312,8 @@ impl<'a, W: Write> Writer<'a, W> { .ok_or(Error::EntryPointNotFound)?; // Generate a map with names required to write the module - let mut names = FastHashMap::default(); - let mut namer = Namer::default(); + let mut names = crate::FastHashMap::default(); + let mut namer = proc::Namer::default(); namer.reset(module, keywords::RESERVED_KEYWORDS, &["gl_"], &mut names); // Build the instance @@ -330,7 +325,7 @@ impl<'a, W: Write> Writer<'a, W> { namer, features: FeaturesManager::new(), names, - reflection_names: FastHashMap::default(), + reflection_names: crate::FastHashMap::default(), entry_point: &module.entry_points[ep_idx], entry_point_idx: ep_idx as u16, @@ -390,13 +385,15 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, "layout(early_fragment_tests) in;")?; if let Some(conservative) = depth_test.conservative { + use crate::ConservativeDepth as Cd; + writeln!( self.out, "layout (depth_{}) out float gl_FragDepth;", match conservative { - ConservativeDepth::GreaterEqual => "greater", - ConservativeDepth::LessEqual => "less", - ConservativeDepth::Unchanged => "unchanged", + Cd::GreaterEqual => "greater", + Cd::LessEqual => "less", + Cd::Unchanged => "unchanged", } )?; } @@ -444,7 +441,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { // Write the storage format if needed if let TypeInner::Image { - class: ImageClass::Storage(format), + class: crate::ImageClass::Storage(format), .. } = self.module.types[global.ty].inner { @@ -505,13 +502,18 @@ impl<'a, W: Write> Writer<'a, W> { let fun_info = &self.info[handle]; // Write the function - self.write_function(FunctionType::Function(handle), function, fun_info, &name)?; + self.write_function( + back::FunctionType::Function(handle), + function, + fun_info, + &name, + )?; writeln!(self.out)?; } self.write_function( - FunctionType::EntryPoint(self.entry_point_idx), + back::FunctionType::EntryPoint(self.entry_point_idx), &self.entry_point.function, ep_info, "main", @@ -524,21 +526,23 @@ impl<'a, W: Write> Writer<'a, W> { self.collect_reflection_info() } - fn write_array_size(&mut self, size: ArraySize) -> BackendResult { + fn write_array_size(&mut self, size: crate::ArraySize) -> BackendResult { write!(self.out, "[")?; // Write the array size // Writes nothing if `ArraySize::Dynamic` // Panics if `ArraySize::Constant` has a constant that isn't an uint match size { - ArraySize::Constant(const_handle) => match self.module.constants[const_handle].inner { - ConstantInner::Scalar { - width: _, - value: ScalarValue::Uint(size), - } => write!(self.out, "{}", size)?, - _ => unreachable!(), - }, - ArraySize::Dynamic => (), + crate::ArraySize::Constant(const_handle) => { + match self.module.constants[const_handle].inner { + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(size), + } => write!(self.out, "{}", size)?, + _ => unreachable!(), + } + } + crate::ArraySize::Dynamic => (), } write!(self.out, "]")?; @@ -589,7 +593,7 @@ impl<'a, W: Write> Writer<'a, W> { } => write!( self.out, "{}mat{}x{}", - glsl_scalar(ScalarKind::Float, width)?.prefix, + glsl_scalar(crate::ScalarKind::Float, width)?.prefix, columns as u8, rows as u8 )?, @@ -619,7 +623,7 @@ impl<'a, W: Write> Writer<'a, W> { /// - If type is either a image or sampler /// - If it's an Array with a [`ArraySize::Constant`](crate::ArraySize::Constant) with a /// constant that isn't [`Uint`](crate::ConstantInner::Uint) - fn write_type(&mut self, ty: Handle) -> BackendResult { + fn write_type(&mut self, ty: Handle) -> BackendResult { match self.module.types[ty].inner { // glsl has no pointer types so just write types as normal and loads are skipped TypeInner::Pointer { base, .. } => self.write_type(base), @@ -649,7 +653,7 @@ impl<'a, W: Write> Writer<'a, W> { &mut self, dim: crate::ImageDimension, arrayed: bool, - class: ImageClass, + class: crate::ImageClass, ) -> BackendResult { // glsl images consist of four parts the scalar prefix, the image "type", the dimensions // and modifiers @@ -663,12 +667,13 @@ impl<'a, W: Write> Writer<'a, W> { // - MS - used if it's a multisampled image // - Array - used if it's an image array // - Shadow - used if it's a depth image + use crate::ImageClass as Ic; let (base, kind, ms, comparison) = match class { - ImageClass::Sampled { kind, multi: true } => ("sampler", kind, "MS", ""), - ImageClass::Sampled { kind, multi: false } => ("sampler", kind, "", ""), - ImageClass::Depth => ("sampler", crate::ScalarKind::Float, "", "Shadow"), - ImageClass::Storage(format) => ("image", format.into(), "", ""), + Ic::Sampled { kind, multi: true } => ("sampler", kind, "MS", ""), + Ic::Sampled { kind, multi: false } => ("sampler", kind, "", ""), + Ic::Depth => ("sampler", crate::ScalarKind::Float, "", "Shadow"), + Ic::Storage(format) => ("image", format.into(), "", ""), }; write!( @@ -694,8 +699,8 @@ impl<'a, W: Write> Writer<'a, W> { /// If the global has type sampler fn write_global( &mut self, - handle: Handle, - global: &GlobalVariable, + handle: Handle, + global: &crate::GlobalVariable, ) -> BackendResult { if let Some(storage_access) = glsl_storage_access(global.storage_access) { write!(self.out, "{} ", storage_access)?; @@ -737,7 +742,11 @@ impl<'a, W: Write> Writer<'a, W> { /// - Globals without bindings use the name from the [`Namer`](crate::proc::Namer) /// - Globals with resource binding are named `_group_X_binding_Y` where `X` /// is the group and `Y` is the binding - fn get_global_name(&self, handle: Handle, global: &GlobalVariable) -> String { + fn get_global_name( + &self, + handle: Handle, + global: &crate::GlobalVariable, + ) -> String { match global.binding { Some(ref br) => { format!("_group_{}_binding_{}", br.group, br.binding) @@ -749,8 +758,8 @@ impl<'a, W: Write> Writer<'a, W> { /// Writes the varying declaration. fn write_varying( &mut self, - binding: Option<&Binding>, - ty: Handle, + binding: Option<&crate::Binding>, + ty: Handle, output: bool, ) -> Result<(), Error> { match self.module.types[ty].inner { @@ -761,7 +770,7 @@ impl<'a, W: Write> Writer<'a, W> { } _ => { let (location, interpolation, sampling) = match binding { - Some(&Binding::Location { + Some(&crate::Binding::Location { location, interpolation, sampling, @@ -814,7 +823,7 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important let vname = VaryingName { - binding: &Binding::Location { + binding: &crate::Binding::Location { location, interpolation: None, sampling: None, @@ -834,13 +843,13 @@ impl<'a, W: Write> Writer<'a, W> { /// Adds a newline fn write_function( &mut self, - ty: FunctionType, - func: &Function, - info: &FunctionInfo, + ty: back::FunctionType, + func: &crate::Function, + info: &valid::FunctionInfo, name: &str, ) -> BackendResult { // Create a function context for the function being written - let ctx = FunctionCtx { + let ctx = back::FunctionCtx { ty, info, expressions: &func.expressions, @@ -862,7 +871,7 @@ impl<'a, W: Write> Writer<'a, W> { // Start by writing the return type if any otherwise write void // This is the only place where `void` is a valid type // (though it's more a keyword than a type) - if let FunctionType::EntryPoint(_) = ctx.ty { + if let back::FunctionType::EntryPoint(_) = ctx.ty { write!(self.out, "void")?; } else if let Some(ref result) = func.result { self.write_type(result.ty)?; @@ -878,8 +887,8 @@ impl<'a, W: Write> Writer<'a, W> { // We need access to `Self` here so we use the reference passed to the closure as an // argument instead of capturing as that would cause a borrow checker error let arguments = match ctx.ty { - FunctionType::EntryPoint(_) => &[][..], - FunctionType::Function(_) => &func.arguments, + back::FunctionType::EntryPoint(_) => &[][..], + back::FunctionType::Function(_) => &func.arguments, }; self.write_slice(arguments, |this, i, arg| { // Write the argument type @@ -897,10 +906,10 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ") {{")?; // Compose the function arguments from globals, in case of an entry point. - if let FunctionType::EntryPoint(ep_index) = ctx.ty { + if let back::FunctionType::EntryPoint(ep_index) = ctx.ty { let stage = self.module.entry_points[ep_index as usize].stage; for (index, arg) in func.arguments.iter().enumerate() { - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; self.write_type(arg.ty)?; let name = &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)]; write!(self.out, " {}", name)?; @@ -941,7 +950,7 @@ impl<'a, W: Write> Writer<'a, W> { for (handle, local) in func.local_variables.iter() { // Write indentation (only for readability) and the type // `write_type` adds no trailing space - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; self.write_type(local.ty)?; // Write the local name @@ -1009,28 +1018,30 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Adds no newlines or leading/trailing whitespace - fn write_constant(&mut self, constant: &Constant) -> BackendResult { + fn write_constant(&mut self, constant: &crate::Constant) -> BackendResult { + use crate::ScalarValue as Sv; + match constant.inner { - ConstantInner::Scalar { + crate::ConstantInner::Scalar { width: _, ref value, } => match *value { // Signed integers don't need anything special - ScalarValue::Sint(int) => write!(self.out, "{}", int)?, + Sv::Sint(int) => write!(self.out, "{}", int)?, // Unsigned integers need a `u` at the end // // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we // always write it as the extra branch wouldn't have any benefit in readability - ScalarValue::Uint(int) => write!(self.out, "{}u", int)?, + Sv::Uint(int) => write!(self.out, "{}u", int)?, // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero which is needed for a valid glsl float constant - ScalarValue::Float(float) => write!(self.out, "{:?}", float)?, + Sv::Float(float) => write!(self.out, "{:?}", float)?, // Booleans are either `true` or `false` so nothing special needs to be done - ScalarValue::Bool(boolean) => write!(self.out, "{}", boolean)?, + Sv::Bool(boolean) => write!(self.out, "{}", boolean)?, }, // Composite constant are created using the same syntax as compose // `type(components)` where `components` is a comma separated list of constants - ConstantInner::Composite { ty, ref components } => { + crate::ConstantInner::Composite { ty, ref components } => { self.write_type(ty)?; write!(self.out, "(")?; @@ -1053,8 +1064,8 @@ impl<'a, W: Write> Writer<'a, W> { fn write_struct( &mut self, block: bool, - handle: Handle, - members: &[StructMember], + handle: Handle, + members: &[crate::StructMember], ) -> BackendResult { // glsl structs are written as in C // `struct name() { members };` @@ -1080,7 +1091,7 @@ impl<'a, W: Write> Writer<'a, W> { for (idx, member) in members.iter().enumerate() { // The indentation is only for readability - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; match self.module.types[member.ty].inner { TypeInner::Array { @@ -1142,10 +1153,13 @@ impl<'a, W: Write> Writer<'a, W> { /// Always adds a newline fn write_stmt( &mut self, - sta: &Statement, - ctx: &FunctionCtx<'_>, + sta: &crate::Statement, + ctx: &back::FunctionCtx<'_>, indent: usize, ) -> BackendResult { + use crate::Statement; + use back::INDENT; + match *sta { // This is where we can generate intermediate constants for some expression types. Statement::Emit(ref range) => { @@ -1313,7 +1327,7 @@ impl<'a, W: Write> Writer<'a, W> { Statement::Return { value } => { write!(self.out, "{}", INDENT.repeat(indent))?; match ctx.ty { - FunctionType::Function(_) => { + back::FunctionType::Function(_) => { write!(self.out, "return")?; // Write the expression to be returned if needed if let Some(expr) = value { @@ -1322,14 +1336,16 @@ impl<'a, W: Write> Writer<'a, W> { } writeln!(self.out, ";")?; } - FunctionType::EntryPoint(ep_index) => { + back::FunctionType::EntryPoint(ep_index) => { let ep = &self.module.entry_points[ep_index as usize]; if let Some(ref result) = ep.function.result { let value = value.unwrap(); match self.module.types[result.ty].inner { crate::TypeInner::Struct { ref members, .. } => { let (mut is_temp_struct_used, mut return_struct) = (false, ""); - if let Expression::Compose { .. } = ctx.expressions[value] { + if let crate::Expression::Compose { .. } = + ctx.expressions[value] + { is_temp_struct_used = true; return_struct = "_tmp_return"; write!( @@ -1344,7 +1360,9 @@ impl<'a, W: Write> Writer<'a, W> { } for (index, member) in members.iter().enumerate() { // TODO: handle builtin in better way - if let Some(Binding::BuiltIn(builtin)) = member.binding { + if let Some(crate::Binding::BuiltIn(builtin)) = + member.binding + { match builtin { crate::BuiltIn::ClipDistance | crate::BuiltIn::CullDistance @@ -1461,7 +1479,13 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Doesn't add any newlines or leading/trailing spaces - fn write_expr(&mut self, expr: Handle, ctx: &FunctionCtx<'_>) -> BackendResult { + fn write_expr( + &mut self, + expr: Handle, + ctx: &back::FunctionCtx<'_>, + ) -> BackendResult { + use crate::Expression; + if let Some(name) = self.named_expressions.get(&expr) { write!(self.out, "{}", name)?; return Ok(()); @@ -1494,7 +1518,7 @@ impl<'a, W: Write> Writer<'a, W> { match *resolved { TypeInner::Vector { .. } => { // Write vector access as a swizzle - write!(self.out, ".{}", COMPONENTS[index as usize])? + write!(self.out, ".{}", back::COMPONENTS[index as usize])? } TypeInner::Matrix { .. } | TypeInner::Array { .. } @@ -1534,7 +1558,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(vector, ctx)?; write!(self.out, ".")?; for &sc in pattern[..size as usize].iter() { - self.out.write_char(COMPONENTS[sc as usize])?; + self.out.write_char(back::COMPONENTS[sc as usize])?; } } // `Compose` is pretty simple we just write `type(components)` where `components` is a @@ -1695,10 +1719,10 @@ impl<'a, W: Write> Writer<'a, W> { }; let fun_name = match class { - ImageClass::Sampled { .. } => "texelFetch", - ImageClass::Storage(_) => "imageLoad", + crate::ImageClass::Sampled { .. } => "texelFetch", + crate::ImageClass::Storage(_) => "imageLoad", // TODO: Is there even a function for this? - ImageClass::Depth => todo!(), + crate::ImageClass::Depth => todo!(), }; write!(self.out, "{}(", fun_name)?; @@ -1717,6 +1741,8 @@ impl<'a, W: Write> Writer<'a, W> { // - textureQueryLevels // - textureSamples/imageSamples Expression::ImageQuery { image, query } => { + use crate::ImageClass; + // This will only panic if the module is invalid let (dim, class) = match *ctx.info[image].ty.inner_with(&self.module.types) { TypeInner::Image { @@ -1764,7 +1790,7 @@ impl<'a, W: Write> Writer<'a, W> { }; write!(self.out, "{}(", fun_name)?; self.write_expr(image, ctx)?; - write!(self.out, ",0).{}", COMPONENTS[components])?; + write!(self.out, ",0).{}", back::COMPONENTS[components])?; } crate::ImageQuery::NumSamples => { // assumes ARB_shader_texture_image_samples @@ -1786,31 +1812,23 @@ impl<'a, W: Write> Writer<'a, W> { // // We also wrap the everything in parentheses to avoid precedence issues Expression::Unary { op, expr } => { + use crate::{ScalarKind as Sk, UnaryOperator as Uo}; + write!( self.out, "({} ", match op { - UnaryOperator::Negate => "-", - UnaryOperator::Not => - match *ctx.info[expr].ty.inner_with(&self.module.types) { - TypeInner::Scalar { - kind: ScalarKind::Sint, - .. - } => "~", - TypeInner::Scalar { - kind: ScalarKind::Uint, - .. - } => "~", - TypeInner::Scalar { - kind: ScalarKind::Bool, - .. - } => "!", - ref other => - return Err(Error::Custom(format!( - "Cannot apply not to type {:?}", - other - ))), - }, + Uo::Negate => "-", + Uo::Not => match *ctx.info[expr].ty.inner_with(&self.module.types) { + TypeInner::Scalar { kind: Sk::Sint, .. } => "~", + TypeInner::Scalar { kind: Sk::Uint, .. } => "~", + TypeInner::Scalar { kind: Sk::Bool, .. } => "!", + ref other => + return Err(Error::Custom(format!( + "Cannot apply not to type {:?}", + other + ))), + }, } )?; @@ -1825,17 +1843,19 @@ impl<'a, W: Write> Writer<'a, W> { Expression::Binary { op, left, right } => { // Holds `Some(function_name)` if the binary operation is // implemented as a function call + use crate::BinaryOperator as Bo; + let function = if let (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) = ( ctx.info[left].ty.inner_with(&self.module.types), ctx.info[right].ty.inner_with(&self.module.types), ) { match op { - BinaryOperator::Less => Some("lessThan"), - BinaryOperator::LessEqual => Some("lessThanEqual"), - BinaryOperator::Greater => Some("greaterThan"), - BinaryOperator::GreaterEqual => Some("greaterThanEqual"), - BinaryOperator::Equal => Some("equal"), - BinaryOperator::NotEqual => Some("notEqual"), + Bo::Less => Some("lessThan"), + Bo::LessEqual => Some("lessThanEqual"), + Bo::Greater => Some("greaterThan"), + Bo::GreaterEqual => Some("greaterThanEqual"), + Bo::Equal => Some("equal"), + Bo::NotEqual => Some("notEqual"), _ => None, } } else { @@ -1872,13 +1892,15 @@ impl<'a, W: Write> Writer<'a, W> { } // `Derivative` is a function call to a glsl provided function Expression::Derivative { axis, expr } => { + use crate::DerivativeAxis as Da; + write!( self.out, "{}(", match axis { - DerivativeAxis::X => "dFdx", - DerivativeAxis::Y => "dFdy", - DerivativeAxis::Width => "fwidth", + Da::X => "dFdx", + Da::Y => "dFdy", + Da::Width => "fwidth", } )?; self.write_expr(expr, ctx)?; @@ -1886,15 +1908,17 @@ impl<'a, W: Write> Writer<'a, W> { } // `Relational` is a normal function call to some glsl provided functions Expression::Relational { fun, argument } => { + use crate::RelationalFunction as Rf; + let fun_name = match fun { // There's no specific function for this but we can invert the result of `isinf` - RelationalFunction::IsFinite => "!isinf", - RelationalFunction::IsInf => "isinf", - RelationalFunction::IsNan => "isnan", + Rf::IsFinite => "!isinf", + Rf::IsInf => "isinf", + Rf::IsNan => "isnan", // There's also no function for this but we can invert `isnan` - RelationalFunction::IsNormal => "!isnan", - RelationalFunction::All => "all", - RelationalFunction::Any => "any", + Rf::IsNormal => "!isnan", + Rf::All => "all", + Rf::Any => "any", }; write!(self.out, "{}(", fun_name)?; @@ -2003,18 +2027,20 @@ impl<'a, W: Write> Writer<'a, W> { } } None => { + use crate::ScalarKind as Sk; + let source_kind = inner.scalar_kind().unwrap(); write!( self.out, "{}", match (source_kind, target_kind) { - (ScalarKind::Float, ScalarKind::Sint) => "floatBitsToInt", - (ScalarKind::Float, ScalarKind::Uint) => "floatBitsToUInt", - (ScalarKind::Sint, ScalarKind::Float) => "intBitsToFloat", - (ScalarKind::Uint, ScalarKind::Float) => "uintBitsToFloat", + (Sk::Float, Sk::Sint) => "floatBitsToInt", + (Sk::Float, Sk::Uint) => "floatBitsToUInt", + (Sk::Sint, Sk::Float) => "intBitsToFloat", + (Sk::Uint, Sk::Float) => "uintBitsToFloat", // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion - (ScalarKind::Uint, ScalarKind::Sint) => "int", - (ScalarKind::Sint, ScalarKind::Uint) => "uint", + (Sk::Uint, Sk::Sint) => "int", + (Sk::Sint, Sk::Uint) => "uint", _ => { return Err(Error::Custom(format!( "Cannot bitcast {:?} to {:?}", @@ -2044,18 +2070,20 @@ impl<'a, W: Write> Writer<'a, W> { fn write_texture_coordinates( &mut self, - coordinate: Handle, - array_index: Option>, + coordinate: Handle, + array_index: Option>, dim: crate::ImageDimension, - ctx: &FunctionCtx, + ctx: &back::FunctionCtx, ) -> Result<(), Error> { + use crate::ImageDimension as IDim; + match array_index { Some(layer_expr) => { let tex_coord_type = match dim { - crate::ImageDimension::D1 => "ivec2", - crate::ImageDimension::D2 => "ivec3", - crate::ImageDimension::D3 => "ivec4", - crate::ImageDimension::Cube => "ivec4", + IDim::D1 => "ivec2", + IDim::D2 => "ivec3", + IDim::D3 => "ivec4", + IDim::Cube => "ivec4", }; write!(self.out, "{}(", tex_coord_type)?; self.write_expr(coordinate, ctx)?; @@ -2072,12 +2100,12 @@ impl<'a, W: Write> Writer<'a, W> { fn write_named_expr( &mut self, - handle: Handle, + handle: Handle, name: String, - ctx: &FunctionCtx, + ctx: &back::FunctionCtx, ) -> BackendResult { match ctx.info[handle].ty { - TypeResolution::Handle(ty_handle) => match self.module.types[ty_handle].inner { + proc::TypeResolution::Handle(ty_handle) => match self.module.types[ty_handle].inner { TypeInner::Struct { .. } => { let ty_name = &self.names[&NameKey::Type(ty_handle)]; write!(self.out, "{}", ty_name)?; @@ -2086,7 +2114,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(ty_handle)?; } }, - TypeResolution::Value(ref inner) => { + proc::TypeResolution::Value(ref inner) => { self.write_value_type(inner)?; } } @@ -2117,8 +2145,8 @@ impl<'a, W: Write> Writer<'a, W> { fn collect_reflection_info(&self) -> Result { use std::collections::hash_map::Entry; let info = self.info.get_entry_point(self.entry_point_idx as usize); - let mut mappings = FastHashMap::default(); - let mut uniforms = FastHashMap::default(); + let mut mappings = crate::FastHashMap::default(); + let mut uniforms = crate::FastHashMap::default(); for sampling in info.sampling_set.iter() { let global = self.module.global_variables[sampling.image].clone(); @@ -2146,7 +2174,7 @@ impl<'a, W: Write> Writer<'a, W> { } match self.module.types[var.ty].inner { crate::TypeInner::Struct { .. } => match var.class { - StorageClass::Uniform | StorageClass::Storage => { + crate::StorageClass::Uniform | crate::StorageClass::Storage => { let name = self.reflection_names[&var.ty].clone(); uniforms.insert(handle, name); } @@ -2179,17 +2207,22 @@ struct ScalarString<'a> { /// /// # Errors /// If a [`Float`](crate::ScalarKind::Float) with an width that isn't 4 or 8 -fn glsl_scalar(kind: ScalarKind, width: Bytes) -> Result, Error> { +fn glsl_scalar( + kind: crate::ScalarKind, + width: crate::Bytes, +) -> Result, Error> { + use crate::ScalarKind as Sk; + Ok(match kind { - ScalarKind::Sint => ScalarString { + Sk::Sint => ScalarString { prefix: "i", full: "int", }, - ScalarKind::Uint => ScalarString { + Sk::Uint => ScalarString { prefix: "u", full: "uint", }, - ScalarKind::Float => match width { + Sk::Float => match width { 4 => ScalarString { prefix: "", full: "float", @@ -2200,7 +2233,7 @@ fn glsl_scalar(kind: ScalarKind, width: Bytes) -> Result, }, _ => return Err(Error::UnsupportedScalar(kind, width)), }, - ScalarKind::Bool => ScalarString { + Sk::Bool => ScalarString { prefix: "b", full: "bool", }, @@ -2208,9 +2241,11 @@ fn glsl_scalar(kind: ScalarKind, width: Bytes) -> Result, } /// Helper function that returns the glsl variable name for a builtin -fn glsl_built_in(built_in: BuiltIn, output: bool) -> &'static str { +fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { + use crate::BuiltIn as Bi; + match built_in { - BuiltIn::Position => { + Bi::Position => { if output { "gl_Position" } else { @@ -2218,18 +2253,18 @@ fn glsl_built_in(built_in: BuiltIn, output: bool) -> &'static str { } } // vertex - BuiltIn::BaseInstance => "uint(gl_BaseInstance)", - BuiltIn::BaseVertex => "uint(gl_BaseVertex)", - BuiltIn::ClipDistance => "gl_ClipDistance", - BuiltIn::CullDistance => "gl_CullDistance", - BuiltIn::InstanceIndex => "uint(gl_InstanceID)", - BuiltIn::PointSize => "gl_PointSize", - BuiltIn::VertexIndex => "uint(gl_VertexID)", + Bi::BaseInstance => "uint(gl_BaseInstance)", + Bi::BaseVertex => "uint(gl_BaseVertex)", + Bi::ClipDistance => "gl_ClipDistance", + Bi::CullDistance => "gl_CullDistance", + Bi::InstanceIndex => "uint(gl_InstanceID)", + Bi::PointSize => "gl_PointSize", + Bi::VertexIndex => "uint(gl_VertexID)", // fragment - BuiltIn::FragDepth => "gl_FragDepth", - BuiltIn::FrontFacing => "gl_FrontFacing", - BuiltIn::SampleIndex => "gl_SampleID", - BuiltIn::SampleMask => { + Bi::FragDepth => "gl_FragDepth", + Bi::FrontFacing => "gl_FrontFacing", + Bi::SampleIndex => "gl_SampleID", + Bi::SampleMask => { if output { "gl_SampleMask" } else { @@ -2237,90 +2272,100 @@ fn glsl_built_in(built_in: BuiltIn, output: bool) -> &'static str { } } // compute - BuiltIn::GlobalInvocationId => "gl_GlobalInvocationID", - BuiltIn::LocalInvocationId => "gl_LocalInvocationID", - BuiltIn::LocalInvocationIndex => "gl_LocalInvocationIndex", - BuiltIn::WorkGroupId => "gl_WorkGroupID", - BuiltIn::WorkGroupSize => "gl_WorkGroupSize", + Bi::GlobalInvocationId => "gl_GlobalInvocationID", + Bi::LocalInvocationId => "gl_LocalInvocationID", + Bi::LocalInvocationIndex => "gl_LocalInvocationIndex", + Bi::WorkGroupId => "gl_WorkGroupID", + Bi::WorkGroupSize => "gl_WorkGroupSize", } } /// Helper function that returns the string corresponding to the storage class -fn glsl_storage_class(class: StorageClass) -> Option<&'static str> { +fn glsl_storage_class(class: crate::StorageClass) -> Option<&'static str> { + use crate::StorageClass as Sc; + match class { - StorageClass::Function => None, - StorageClass::Private => None, - StorageClass::Storage => Some("buffer"), - StorageClass::Uniform => Some("uniform"), - StorageClass::Handle => Some("uniform"), - StorageClass::WorkGroup => Some("shared"), - StorageClass::PushConstant => None, + Sc::Function => None, + Sc::Private => None, + Sc::Storage => Some("buffer"), + Sc::Uniform => Some("uniform"), + Sc::Handle => Some("uniform"), + Sc::WorkGroup => Some("shared"), + Sc::PushConstant => None, } } /// Helper function that returns the string corresponding to the glsl interpolation qualifier -fn glsl_interpolation(interpolation: Interpolation) -> &'static str { +fn glsl_interpolation(interpolation: crate::Interpolation) -> &'static str { + use crate::Interpolation as I; + match interpolation { - Interpolation::Perspective => "smooth", - Interpolation::Linear => "noperspective", - Interpolation::Flat => "flat", + I::Perspective => "smooth", + I::Linear => "noperspective", + I::Flat => "flat", } } /// Return the GLSL auxiliary qualifier for the given sampling value. -fn glsl_sampling(sampling: Sampling) -> Option<&'static str> { +fn glsl_sampling(sampling: crate::Sampling) -> Option<&'static str> { + use crate::Sampling as S; + match sampling { - Sampling::Center => None, - Sampling::Centroid => Some("centroid"), - Sampling::Sample => Some("sample"), + S::Center => None, + S::Centroid => Some("centroid"), + S::Sample => Some("sample"), } } /// Helper function that returns the glsl dimension string of [`ImageDimension`](crate::ImageDimension) fn glsl_dimension(dim: crate::ImageDimension) -> &'static str { + use crate::ImageDimension as IDim; + match dim { - crate::ImageDimension::D1 => "1D", - crate::ImageDimension::D2 => "2D", - crate::ImageDimension::D3 => "3D", - crate::ImageDimension::Cube => "Cube", + IDim::D1 => "1D", + IDim::D2 => "2D", + IDim::D3 => "3D", + IDim::Cube => "Cube", } } /// Helper function that returns the glsl storage format string of [`StorageFormat`](crate::StorageFormat) -fn glsl_storage_format(format: StorageFormat) -> &'static str { +fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { + use crate::StorageFormat as Sf; + match format { - StorageFormat::R8Unorm => "r8", - StorageFormat::R8Snorm => "r8_snorm", - StorageFormat::R8Uint => "r8ui", - StorageFormat::R8Sint => "r8i", - StorageFormat::R16Uint => "r16ui", - StorageFormat::R16Sint => "r16i", - StorageFormat::R16Float => "r16f", - StorageFormat::Rg8Unorm => "rg8", - StorageFormat::Rg8Snorm => "rg8_snorm", - StorageFormat::Rg8Uint => "rg8ui", - StorageFormat::Rg8Sint => "rg8i", - StorageFormat::R32Uint => "r32ui", - StorageFormat::R32Sint => "r32i", - StorageFormat::R32Float => "r32f", - StorageFormat::Rg16Uint => "rg16ui", - StorageFormat::Rg16Sint => "rg16i", - StorageFormat::Rg16Float => "rg16f", - StorageFormat::Rgba8Unorm => "rgba8ui", - StorageFormat::Rgba8Snorm => "rgba8_snorm", - StorageFormat::Rgba8Uint => "rgba8ui", - StorageFormat::Rgba8Sint => "rgba8i", - StorageFormat::Rgb10a2Unorm => "rgb10_a2ui", - StorageFormat::Rg11b10Float => "r11f_g11f_b10f", - StorageFormat::Rg32Uint => "rg32ui", - StorageFormat::Rg32Sint => "rg32i", - StorageFormat::Rg32Float => "rg32f", - StorageFormat::Rgba16Uint => "rgba16ui", - StorageFormat::Rgba16Sint => "rgba16i", - StorageFormat::Rgba16Float => "rgba16f", - StorageFormat::Rgba32Uint => "rgba32ui", - StorageFormat::Rgba32Sint => "rgba32i", - StorageFormat::Rgba32Float => "rgba32f", + Sf::R8Unorm => "r8", + Sf::R8Snorm => "r8_snorm", + Sf::R8Uint => "r8ui", + Sf::R8Sint => "r8i", + Sf::R16Uint => "r16ui", + Sf::R16Sint => "r16i", + Sf::R16Float => "r16f", + Sf::Rg8Unorm => "rg8", + Sf::Rg8Snorm => "rg8_snorm", + Sf::Rg8Uint => "rg8ui", + Sf::Rg8Sint => "rg8i", + Sf::R32Uint => "r32ui", + Sf::R32Sint => "r32i", + Sf::R32Float => "r32f", + Sf::Rg16Uint => "rg16ui", + Sf::Rg16Sint => "rg16i", + Sf::Rg16Float => "rg16f", + Sf::Rgba8Unorm => "rgba8ui", + Sf::Rgba8Snorm => "rgba8_snorm", + Sf::Rgba8Uint => "rgba8ui", + Sf::Rgba8Sint => "rgba8i", + Sf::Rgb10a2Unorm => "rgb10_a2ui", + Sf::Rg11b10Float => "r11f_g11f_b10f", + Sf::Rg32Uint => "rg32ui", + Sf::Rg32Sint => "rg32i", + Sf::Rg32Float => "rg32f", + Sf::Rgba16Uint => "rgba16ui", + Sf::Rgba16Sint => "rgba16i", + Sf::Rgba16Float => "rgba16f", + Sf::Rgba32Uint => "rgba32ui", + Sf::Rgba32Sint => "rgba32i", + Sf::Rgba32Float => "rgba32f", } } @@ -2329,10 +2374,10 @@ fn glsl_storage_format(format: StorageFormat) -> &'static str { /// glsl allows adding both `readonly` and `writeonly` but this means that /// they can only be used to query information about the resource which isn't what /// we want here so when storage access is both `LOAD` and `STORE` add no modifiers -fn glsl_storage_access(storage_access: StorageAccess) -> Option<&'static str> { - if storage_access == StorageAccess::LOAD { +fn glsl_storage_access(storage_access: crate::StorageAccess) -> Option<&'static str> { + if storage_access == crate::StorageAccess::LOAD { Some("readonly") - } else if storage_access == StorageAccess::STORE { + } else if storage_access == crate::StorageAccess::STORE { Some("writeonly") } else { None @@ -2343,7 +2388,7 @@ fn glsl_storage_access(storage_access: StorageAccess) -> Option<&'static str> { fn zero_init_value_str(inner: &TypeInner) -> Option { match *inner { TypeInner::Scalar { kind, .. } => match kind { - ScalarKind::Bool => Some(String::from("false")), + crate::ScalarKind::Bool => Some(String::from("false")), _ => Some(String::from("0")), }, TypeInner::Vector { size, kind, width } => { From 9e245d1fdea1e828a2528442dcb8fae29ff392b1 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 23 Jun 2021 13:31:06 +0300 Subject: [PATCH 1026/2212] [hlsl-out] Reduce global import usage --- src/back/hlsl/writer.rs | 210 ++++++++++++++++++++++------------------ 1 file changed, 115 insertions(+), 95 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 6f0d3eb29..f924435ec 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2,15 +2,9 @@ #![allow(dead_code)] use super::{Error, Options, ShaderModel}; use crate::{ - back::{ - hlsl::keywords::RESERVED, vector_size_str, FunctionCtx, FunctionType, BAKE_PREFIX, - COMPONENTS, INDENT, - }, - proc::{NameKey, Namer, TypeResolution}, - valid::ModuleInfo, - ArraySize, BuiltIn, Bytes, Constant, ConstantInner, Expression, FastHashMap, Function, - GlobalVariable, Handle, ImageDimension, Module, ScalarKind, ScalarValue, ShaderStage, - Statement, StructMember, Type, TypeInner, + back, + proc::{self, NameKey}, + valid, Handle, Module, ShaderStage, TypeInner, }; use std::fmt::Write; @@ -27,14 +21,14 @@ struct EntryPointBinding { struct EpStructMember { pub name: String, - pub ty: Handle, + pub ty: Handle, pub binding: Option, } pub struct Writer<'a, W> { out: W, - names: FastHashMap, - namer: Namer, + names: crate::FastHashMap, + namer: proc::Namer, options: &'a Options, ep_inputs: Vec>, named_expressions: crate::NamedExpressions, @@ -44,8 +38,8 @@ impl<'a, W: Write> Writer<'a, W> { pub fn new(out: W, options: &'a Options) -> Self { Self { out, - names: FastHashMap::default(), - namer: Namer::default(), + names: crate::FastHashMap::default(), + namer: proc::Namer::default(), options, ep_inputs: Vec::with_capacity(3), named_expressions: crate::NamedExpressions::default(), @@ -54,12 +48,13 @@ impl<'a, W: Write> Writer<'a, W> { fn reset(&mut self, module: &Module) { self.names.clear(); - self.namer.reset(module, RESERVED, &[], &mut self.names); + self.namer + .reset(module, super::keywords::RESERVED, &[], &mut self.names); self.named_expressions.clear(); self.ep_inputs.clear(); } - pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { + pub fn write(&mut self, module: &Module, info: &valid::ModuleInfo) -> BackendResult { if self.options.shader_model < ShaderModel::default() { return Err(Error::UnsupportedShaderModel(self.options.shader_model)); } @@ -88,7 +83,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write all structs for (handle, ty) in module.types.iter() { - if let TypeInner::Struct { + if let crate::TypeInner::Struct { top_level, ref members, .. @@ -117,8 +112,8 @@ impl<'a, W: Write> Writer<'a, W> { // Write all regular functions for (handle, function) in module.functions.iter() { let info = &info[handle]; - let ctx = FunctionCtx { - ty: FunctionType::Function(handle), + let ctx = back::FunctionCtx { + ty: back::FunctionType::Function(handle), info, expressions: &function.expressions, named_expressions: &function.named_expressions, @@ -132,8 +127,8 @@ impl<'a, W: Write> Writer<'a, W> { // Write all entry points for (index, ep) in module.entry_points.iter().enumerate() { - let ctx = FunctionCtx { - ty: FunctionType::EntryPoint(index as u16), + let ctx = back::FunctionCtx { + ty: back::FunctionType::EntryPoint(index as u16), info: info.get_entry_point(index), expressions: &ep.function.expressions, named_expressions: &ep.function.named_expressions, @@ -181,7 +176,7 @@ impl<'a, W: Write> Writer<'a, W> { fn write_ep_input_struct( &mut self, module: &Module, - func: &Function, + func: &crate::Function, stage: ShaderStage, index: usize, ) -> BackendResult { @@ -209,7 +204,7 @@ impl<'a, W: Write> Writer<'a, W> { binding: arg.binding.clone(), }; - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; self.write_type(module, member.ty)?; write!(self.out, " {}", &member.name)?; if let Some(ref binding) = member.binding { @@ -239,7 +234,11 @@ impl<'a, W: Write> Writer<'a, W> { /// Helper method used to write global variables /// # Notes /// Always adds a newline - fn write_global(&mut self, module: &Module, handle: Handle) -> BackendResult { + fn write_global( + &mut self, + module: &Module, + handle: Handle, + ) -> BackendResult { let global = &module.global_variables[handle]; let inner = &module.types[global.ty].inner; @@ -282,11 +281,11 @@ impl<'a, W: Write> Writer<'a, W> { fn write_global_constant( &mut self, _module: &Module, - inner: &ConstantInner, - handle: Handle, + inner: &crate::ConstantInner, + handle: Handle, ) -> BackendResult { match *inner { - ConstantInner::Scalar { + crate::ConstantInner::Scalar { width: _, ref value, } => { @@ -314,7 +313,7 @@ impl<'a, W: Write> Writer<'a, W> { }; writeln!(self.out, ";")?; } - ConstantInner::Composite { .. } => { + crate::ConstantInner::Composite { .. } => { return Err(Error::Unimplemented(format!( "write_global_constant Composite {:?}", inner @@ -327,21 +326,23 @@ impl<'a, W: Write> Writer<'a, W> { } // copy-paste from glsl-out - fn write_array_size(&mut self, module: &Module, size: ArraySize) -> BackendResult { + fn write_array_size(&mut self, module: &Module, size: crate::ArraySize) -> BackendResult { write!(self.out, "[")?; // Write the array size // Writes nothing if `ArraySize::Dynamic` // Panics if `ArraySize::Constant` has a constant that isn't an uint match size { - ArraySize::Constant(const_handle) => match module.constants[const_handle].inner { - ConstantInner::Scalar { - width: _, - value: ScalarValue::Uint(size), - } => write!(self.out, "{}", size)?, - _ => unreachable!(), - }, - ArraySize::Dynamic => (), + crate::ArraySize::Constant(const_handle) => { + match module.constants[const_handle].inner { + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Uint(size), + } => write!(self.out, "{}", size)?, + _ => unreachable!(), + } + } + crate::ArraySize::Dynamic => (), } write!(self.out, "]")?; @@ -355,9 +356,9 @@ impl<'a, W: Write> Writer<'a, W> { fn write_struct( &mut self, module: &Module, - handle: Handle, + handle: Handle, _block: bool, - members: &[StructMember], + members: &[crate::StructMember], ) -> BackendResult { // Write struct name write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?; @@ -365,7 +366,7 @@ impl<'a, W: Write> Writer<'a, W> { for (index, member) in members.iter().enumerate() { // The indentation is only for readability - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; match module.types[member.ty].inner { TypeInner::Array { @@ -417,7 +418,7 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Adds no trailing or leading whitespace - fn write_type(&mut self, module: &Module, ty: Handle) -> BackendResult { + fn write_type(&mut self, module: &Module, ty: Handle) -> BackendResult { let inner = &module.types[ty].inner; match *inner { TypeInner::Struct { .. } => write!(self.out, "{}", self.names[&NameKey::Type(ty)])?, @@ -443,7 +444,7 @@ impl<'a, W: Write> Writer<'a, W> { self.out, "{}{}", scalar_kind_str(kind, width)?, - vector_size_str(size) + back::vector_size_str(size) )?; } TypeInner::Matrix { @@ -456,9 +457,9 @@ impl<'a, W: Write> Writer<'a, W> { write!( self.out, "{}{}x{}", - scalar_kind_str(ScalarKind::Float, width)?, - vector_size_str(columns), - vector_size_str(rows), + scalar_kind_str(crate::ScalarKind::Float, width)?, + back::vector_size_str(columns), + back::vector_size_str(rows), )?; } TypeInner::Image { @@ -508,8 +509,8 @@ impl<'a, W: Write> Writer<'a, W> { &mut self, module: &Module, name: &str, - func: &Function, - func_ctx: &FunctionCtx<'_>, + func: &crate::Function, + func_ctx: &back::FunctionCtx<'_>, ) -> BackendResult { // Function Declaration Syntax - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-function-syntax if let Some(ref result) = func.result { @@ -523,7 +524,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write function arguments for non entry point functions match func_ctx.ty { - FunctionType::Function(handle) => { + back::FunctionType::Function(handle) => { for (index, arg) in func.arguments.iter().enumerate() { // Write argument type self.write_type(module, arg.ty)?; @@ -539,7 +540,7 @@ impl<'a, W: Write> Writer<'a, W> { } } } - FunctionType::EntryPoint(index) => { + back::FunctionType::EntryPoint(index) => { // EntryPoint arguments wrapped into structure if !self.ep_inputs.is_empty() { if let Some(ref ep_input) = self.ep_inputs[index as usize] { @@ -559,7 +560,9 @@ impl<'a, W: Write> Writer<'a, W> { // Write semantic if it present let stage = match func_ctx.ty { - FunctionType::EntryPoint(index) => Some(module.entry_points[index as usize].stage), + back::FunctionType::EntryPoint(index) => { + Some(module.entry_points[index as usize].stage) + } _ => None, }; if let Some(ref result) = func.result { @@ -583,7 +586,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write function local variables for (handle, local) in func.local_variables.iter() { // Write indentation (only for readability) - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; // Write the local name // The leading space is important @@ -631,10 +634,13 @@ impl<'a, W: Write> Writer<'a, W> { fn write_stmt( &mut self, module: &Module, - stmt: &Statement, - func_ctx: &FunctionCtx<'_>, + stmt: &crate::Statement, + func_ctx: &back::FunctionCtx<'_>, indent: usize, ) -> BackendResult { + use crate::Statement; + use back::INDENT; + match *stmt { Statement::Emit(ref range) => { for handle in range.clone() { @@ -750,7 +756,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { - let name = format!("{}{}", BAKE_PREFIX, expr.index()); + let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); write!(self.out, "const {} = ", name)?; self.write_expr(module, expr, func_ctx)?; self.named_expressions.insert(expr, name); @@ -781,9 +787,11 @@ impl<'a, W: Write> Writer<'a, W> { fn write_expr( &mut self, module: &Module, - expr: Handle, - func_ctx: &FunctionCtx<'_>, + expr: Handle, + func_ctx: &back::FunctionCtx<'_>, ) -> BackendResult { + use crate::Expression; + if let Some(name) = self.named_expressions.get(&expr) { write!(self.out, "{}", name)?; return Ok(()); @@ -844,7 +852,7 @@ impl<'a, W: Write> Writer<'a, W> { match *resolved { TypeInner::Vector { .. } => { // Write vector access as a swizzle - write!(self.out, ".{}", COMPONENTS[index as usize])? + write!(self.out, ".{}", back::COMPONENTS[index as usize])? } TypeInner::Matrix { .. } | TypeInner::Array { .. } @@ -865,11 +873,11 @@ impl<'a, W: Write> Writer<'a, W> { } Expression::FunctionArgument(pos) => { match func_ctx.ty { - FunctionType::Function(handle) => { + back::FunctionType::Function(handle) => { let name = &self.names[&NameKey::FunctionArgument(handle, pos)]; write!(self.out, "{}", name)?; } - FunctionType::EntryPoint(index) => { + back::FunctionType::EntryPoint(index) => { // EntryPoint arguments wrapped into structure // We can safery unwrap here, because if we write function arguments it means, that ep_input struct already exists let ep_input = self.ep_inputs[index as usize].as_ref().unwrap(); @@ -922,7 +930,7 @@ impl<'a, W: Write> Writer<'a, W> { crate::UnaryOperator::Not => match *func_ctx.info[expr].ty.inner_with(&module.types) { TypeInner::Scalar { - kind: ScalarKind::Bool, + kind: crate::ScalarKind::Bool, .. } => "!", ref other => @@ -948,7 +956,11 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Doesn't add any newlines or leading/trailing spaces - fn write_constant(&mut self, module: &Module, handle: Handle) -> BackendResult { + fn write_constant( + &mut self, + module: &Module, + handle: Handle, + ) -> BackendResult { let constant = &module.constants[handle]; match constant.inner { crate::ConstantInner::Scalar { @@ -990,14 +1002,16 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Adds no trailing or leading whitespace - fn write_scalar_value(&mut self, value: ScalarValue) -> BackendResult { + fn write_scalar_value(&mut self, value: crate::ScalarValue) -> BackendResult { + use crate::ScalarValue as Sv; + match value { - ScalarValue::Sint(value) => write!(self.out, "{}", value)?, - ScalarValue::Uint(value) => write!(self.out, "{}u", value)?, + Sv::Sint(value) => write!(self.out, "{}", value)?, + Sv::Uint(value) => write!(self.out, "{}u", value)?, // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero - ScalarValue::Float(value) => write!(self.out, "{:?}", value)?, - ScalarValue::Bool(value) => write!(self.out, "{}", value)?, + Sv::Float(value) => write!(self.out, "{:?}", value)?, + Sv::Bool(value) => write!(self.out, "{}", value)?, } Ok(()) @@ -1006,12 +1020,12 @@ impl<'a, W: Write> Writer<'a, W> { fn write_named_expr( &mut self, module: &Module, - handle: Handle, + handle: Handle, name: String, - ctx: &FunctionCtx, + ctx: &back::FunctionCtx, ) -> BackendResult { match ctx.info[handle].ty { - TypeResolution::Handle(ty_handle) => match module.types[ty_handle].inner { + proc::TypeResolution::Handle(ty_handle) => match module.types[ty_handle].inner { TypeInner::Struct { .. } => { let ty_name = &self.names[&NameKey::Type(ty_handle)]; write!(self.out, "{}", ty_name)?; @@ -1020,7 +1034,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(module, ty_handle)?; } }, - TypeResolution::Value(ref inner) => { + proc::TypeResolution::Value(ref inner) => { self.write_value_type(module, inner)?; } } @@ -1046,52 +1060,58 @@ impl<'a, W: Write> Writer<'a, W> { } } -fn image_dimension_str(dim: ImageDimension) -> &'static str { +fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { + use crate::ImageDimension as IDim; + match dim { - ImageDimension::D1 => "1D", - ImageDimension::D2 => "2D", - ImageDimension::D3 => "3D", - ImageDimension::Cube => "Cube", + IDim::D1 => "1D", + IDim::D2 => "2D", + IDim::D3 => "3D", + IDim::Cube => "Cube", } } -fn builtin_str(built_in: BuiltIn) -> &'static str { +fn builtin_str(built_in: crate::BuiltIn) -> &'static str { + use crate::BuiltIn as Bi; + match built_in { - BuiltIn::Position => "SV_Position", + Bi::Position => "SV_Position", // vertex - BuiltIn::ClipDistance => "SV_ClipDistance", - BuiltIn::CullDistance => "SV_CullDistance", - BuiltIn::InstanceIndex => "SV_InstanceID", + Bi::ClipDistance => "SV_ClipDistance", + Bi::CullDistance => "SV_CullDistance", + Bi::InstanceIndex => "SV_InstanceID", // based on this page https://docs.microsoft.com/en-us/windows/uwp/gaming/glsl-to-hlsl-reference#comparing-opengl-es-20-with-direct3d-11 // No meaning unless you target Direct3D 9 - BuiltIn::PointSize => "PSIZE", - BuiltIn::VertexIndex => "SV_VertexID", + Bi::PointSize => "PSIZE", + Bi::VertexIndex => "SV_VertexID", // fragment - BuiltIn::FragDepth => "SV_Depth", - BuiltIn::FrontFacing => "SV_IsFrontFace", - BuiltIn::SampleIndex => "SV_SampleIndex", - BuiltIn::SampleMask => "SV_Coverage", + Bi::FragDepth => "SV_Depth", + Bi::FrontFacing => "SV_IsFrontFace", + Bi::SampleIndex => "SV_SampleIndex", + Bi::SampleMask => "SV_Coverage", // compute - BuiltIn::GlobalInvocationId => "SV_DispatchThreadID", - BuiltIn::LocalInvocationId => "SV_GroupThreadID", - BuiltIn::LocalInvocationIndex => "SV_GroupIndex", - BuiltIn::WorkGroupId => "SV_GroupID", + Bi::GlobalInvocationId => "SV_DispatchThreadID", + Bi::LocalInvocationId => "SV_GroupThreadID", + Bi::LocalInvocationIndex => "SV_GroupIndex", + Bi::WorkGroupId => "SV_GroupID", _ => todo!("builtin_str {:?}", built_in), } } /// Helper function that returns scalar related strings /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-scalar -fn scalar_kind_str(kind: ScalarKind, width: Bytes) -> Result<&'static str, Error> { +fn scalar_kind_str(kind: crate::ScalarKind, width: crate::Bytes) -> Result<&'static str, Error> { + use crate::ScalarKind as Sk; + match kind { - ScalarKind::Sint => Ok("int"), - ScalarKind::Uint => Ok("uint"), - ScalarKind::Float => match width { + Sk::Sint => Ok("int"), + Sk::Uint => Ok("uint"), + Sk::Float => match width { 2 => Ok("half"), 4 => Ok("float"), 8 => Ok("double"), _ => Err(Error::UnsupportedScalar(kind, width)), }, - ScalarKind::Bool => Ok("bool"), + Sk::Bool => Ok("bool"), } } From 1d4f2305b0d985d02cac524df2a873596a81b374 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 23 Jun 2021 13:31:18 +0300 Subject: [PATCH 1027/2212] [msl-out] Reduce global import usage --- src/back/msl/writer.rs | 135 +++++++++++++++++++++++------------------ 1 file changed, 77 insertions(+), 58 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ace3af23f..3331c415c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1,13 +1,9 @@ -use super::{ - keywords::RESERVED, sampler as sm, Error, LocationMode, Options, PipelineOptions, - TranslationInfo, -}; +use super::{sampler as sm, Error, LocationMode, Options, PipelineOptions, TranslationInfo}; use crate::{ - arena::{Arena, Handle}, - back::{vector_size_str, BAKE_PREFIX, COMPONENTS, INDENT}, - proc::{EntryPointIndex, NameKey, Namer, TypeResolution}, - valid::{Capabilities, FunctionInfo, GlobalUse, ModuleInfo}, - FastHashMap, + arena::Handle, + back, + proc::{self, NameKey, TypeResolution}, + valid, FastHashMap, }; use std::{ fmt::{Display, Error as FmtError, Formatter, Write}, @@ -26,13 +22,13 @@ impl Level { } impl Display for Level { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - (0..self.0).try_for_each(|_| formatter.write_str(INDENT)) + (0..self.0).try_for_each(|_| formatter.write_str(back::INDENT)) } } struct TypeContext<'a> { handle: Handle, - arena: &'a Arena, + arena: &'a crate::Arena, names: &'a FastHashMap, access: crate::StorageAccess, first_time: bool, @@ -63,7 +59,7 @@ impl<'a> Display for TypeContext<'a> { "{}::{}{}", NAMESPACE, scalar_kind_string(kind), - vector_size_str(size), + back::vector_size_str(size), ) } crate::TypeInner::Matrix { columns, rows, .. } => { @@ -72,8 +68,8 @@ impl<'a> Display for TypeContext<'a> { "{}::{}{}x{}", NAMESPACE, scalar_kind_string(crate::ScalarKind::Float), - vector_size_str(columns), - vector_size_str(rows), + back::vector_size_str(columns), + back::vector_size_str(rows), ) } crate::TypeInner::Pointer { base, class } => { @@ -116,7 +112,7 @@ impl<'a> Display for TypeContext<'a> { class_name, NAMESPACE, scalar_kind_string(kind), - vector_size_str(size), + back::vector_size_str(size), ) } crate::TypeInner::Array { base, .. } => { @@ -193,7 +189,7 @@ struct TypedGlobalVariable<'a> { module: &'a crate::Module, names: &'a FastHashMap, handle: Handle, - usage: GlobalUse, + usage: valid::GlobalUse, reference: bool, } @@ -213,7 +209,7 @@ impl<'a> TypedGlobalVariable<'a> { Some(space) if self.reference => { let access = match var.class { crate::StorageClass::Private | crate::StorageClass::WorkGroup - if !self.usage.contains(GlobalUse::WRITE) => + if !self.usage.contains(valid::GlobalUse::WRITE) => { "const" } @@ -240,7 +236,7 @@ impl<'a> TypedGlobalVariable<'a> { struct ConstantContext<'a> { handle: Handle, - arena: &'a Arena, + arena: &'a crate::Arena, names: &'a FastHashMap, first_time: bool, } @@ -286,7 +282,7 @@ pub struct Writer { out: W, names: FastHashMap, named_expressions: crate::NamedExpressions, - namer: Namer, + namer: proc::Namer, runtime_sized_buffers: FastHashMap, usize>, #[cfg(test)] put_expression_stack_pointers: crate::FastHashSet<*const ()>, @@ -337,7 +333,7 @@ fn should_pack_struct_member( } } -fn needs_array_length(ty: Handle, arena: &Arena) -> bool { +fn needs_array_length(ty: Handle, arena: &crate::Arena) -> bool { if let crate::TypeInner::Struct { ref members, .. } = arena[ty].inner { if let Some(member) = members.last() { if let crate::TypeInner::Array { @@ -388,6 +384,7 @@ impl crate::Type { // Returns `true` if we need to emit an alias for this type. fn needs_alias(&self) -> bool { use crate::TypeInner as Ti; + match self.inner { // value types are concise enough, we only alias them if they are named Ti::Scalar { .. } @@ -415,13 +412,13 @@ impl crate::Constant { enum FunctionOrigin { Handle(Handle), - EntryPoint(EntryPointIndex), + EntryPoint(proc::EntryPointIndex), } struct ExpressionContext<'a> { function: &'a crate::Function, origin: FunctionOrigin, - info: &'a FunctionInfo, + info: &'a valid::FunctionInfo, module: &'a crate::Module, pipeline_options: &'a PipelineOptions, } @@ -434,7 +431,7 @@ impl<'a> ExpressionContext<'a> { struct StatementContext<'a> { expression: ExpressionContext<'a>, - mod_info: &'a ModuleInfo, + mod_info: &'a valid::ModuleInfo, result_struct: Option<&'a str>, } @@ -445,7 +442,7 @@ impl Writer { out, names: FastHashMap::default(), named_expressions: crate::NamedExpressions::default(), - namer: Namer::default(), + namer: proc::Namer::default(), runtime_sized_buffers: FastHashMap::default(), #[cfg(test)] put_expression_stack_pointers: Default::default(), @@ -542,7 +539,7 @@ impl Writer { // coordinates in IR are int, but Metal expects uint let size_str = match *context.info[expr].ty.inner_with(&context.module.types) { crate::TypeInner::Scalar { .. } => "", - crate::TypeInner::Vector { size, .. } => vector_size_str(size), + crate::TypeInner::Vector { size, .. } => back::vector_size_str(size), _ => return Err(Error::Validation), }; write!(self.out, "{}::uint{}(", NAMESPACE, size_str)?; @@ -610,7 +607,7 @@ impl Writer { "{}::{}{}", NAMESPACE, scalar_kind_string(kind), - vector_size_str(size) + back::vector_size_str(size) )?; self.put_call_parameters(components.iter().cloned(), context)?; } @@ -621,8 +618,8 @@ impl Writer { "{}::{}{}x{}", NAMESPACE, scalar_kind_string(kind), - vector_size_str(columns), - vector_size_str(rows) + back::vector_size_str(columns), + back::vector_size_str(rows) )?; self.put_call_parameters(components.iter().cloned(), context)?; } @@ -755,7 +752,7 @@ impl Writer { write!(self.out, ".{}", name)?; } crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => { - write!(self.out, ".{}", COMPONENTS[index as usize])?; + write!(self.out, ".{}", back::COMPONENTS[index as usize])?; } crate::TypeInner::Matrix { .. } => { write!(self.out, "[{}]", index)?; @@ -783,7 +780,7 @@ impl Writer { _ => return Err(Error::Validation), }; let scalar = scalar_kind_string(scalar_kind); - let size = vector_size_str(size); + let size = back::vector_size_str(size); write!(self.out, "{}::{}{}(", NAMESPACE, scalar, size)?; self.put_expression(value, context, true)?; @@ -797,7 +794,7 @@ impl Writer { self.put_expression(vector, context, false)?; write!(self.out, ".")?; for &sc in pattern[..size as usize].iter() { - write!(self.out, "{}", COMPONENTS[sc as usize])?; + write!(self.out, "{}", back::COMPONENTS[sc as usize])?; } } crate::Expression::Compose { ty, ref components } => { @@ -1133,13 +1130,15 @@ impl Writer { let scalar = scalar_kind_string(kind); let (size, width) = match *context.resolve_type(expr) { crate::TypeInner::Scalar { width, .. } => ("", width), - crate::TypeInner::Vector { size, width, .. } => (vector_size_str(size), width), + crate::TypeInner::Vector { size, width, .. } => { + (back::vector_size_str(size), width) + } _ => return Err(Error::Validation), }; let op = match convert { Some(w) if w == width => "static_cast", Some(8) if kind == crate::ScalarKind::Float => { - return Err(Error::CapabilityNotSupported(Capabilities::FLOAT64)) + return Err(Error::CapabilityNotSupported(valid::Capabilities::FLOAT64)) } Some(_) => return Err(Error::Validation), None => "as_type", @@ -1261,7 +1260,7 @@ impl Writer { "{}::{}{}", NAMESPACE, scalar_kind_string(kind), - vector_size_str(size) + back::vector_size_str(size) )?; } TypeResolution::Value(crate::TypeInner::Matrix { columns, rows, .. }) => { @@ -1270,8 +1269,8 @@ impl Writer { "{}::{}{}x{}", NAMESPACE, scalar_kind_string(crate::ScalarKind::Float), - vector_size_str(columns), - vector_size_str(rows), + back::vector_size_str(columns), + back::vector_size_str(rows), )?; } TypeResolution::Value(ref other) => { @@ -1315,7 +1314,7 @@ impl Writer { let min_ref_count = context.expression.function.expressions[handle].bake_ref_count(); if min_ref_count <= context.expression.info[handle].ref_count { - Some(format!("{}{}", BAKE_PREFIX, handle.index())) + Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) } else { None } @@ -1501,7 +1500,7 @@ impl Writer { } => { write!(self.out, "{}", level)?; if let Some(expr) = result { - let name = format!("{}{}", BAKE_PREFIX, expr.index()); + let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); self.start_baking_expression(expr, &context.expression, &name)?; self.named_expressions.insert(expr, name); } @@ -1562,12 +1561,13 @@ impl Writer { pub fn write( &mut self, module: &crate::Module, - info: &ModuleInfo, + info: &valid::ModuleInfo, options: &Options, pipeline_options: &PipelineOptions, ) -> Result { self.names.clear(); - self.namer.reset(module, RESERVED, &[], &mut self.names); + self.namer + .reset(module, super::keywords::RESERVED, &[], &mut self.names); self.runtime_sized_buffers.clear(); writeln!(self.out, "#include ")?; @@ -1588,7 +1588,7 @@ impl Writer { writeln!(self.out, "struct _mslBufferSizes {{")?; for idx in indices { - writeln!(self.out, "{}{}::uint size{};", INDENT, NAMESPACE, idx)?; + writeln!(self.out, "{}{}::uint size{};", back::INDENT, NAMESPACE, idx)?; } writeln!(self.out, "}};")?; @@ -1635,7 +1635,10 @@ impl Writer { writeln!( self.out, "{}{} {}[{}];", - INDENT, base_name, WRAPPED_ARRAY_FIELD, coco + back::INDENT, + base_name, + WRAPPED_ARRAY_FIELD, + coco )?; writeln!(self.out, "}};")?; } @@ -1654,7 +1657,7 @@ impl Writer { if member.binding.is_none() && member.offset > last_offset { let pad = member.offset - last_offset; //TODO: adjust the struct initializers - writeln!(self.out, "{}char _pad{}[{}];", INDENT, index, pad)?; + writeln!(self.out, "{}char _pad{}[{}];", back::INDENT, index, pad)?; } let ty_inner = &module.types[member.ty].inner; last_offset = member.offset + ty_inner.span(&module.constants); @@ -1667,7 +1670,7 @@ impl Writer { writeln!( self.out, "{}packed_{}3 {};", - INDENT, + back::INDENT, scalar_kind_string(kind), member_name )?; @@ -1680,7 +1683,13 @@ impl Writer { access: crate::StorageAccess::empty(), first_time: false, }; - writeln!(self.out, "{}{} {};", INDENT, base_name, member_name)?; + writeln!( + self.out, + "{}{} {};", + back::INDENT, + base_name, + member_name + )?; // for 3-component vectors, add one component if let crate::TypeInner::Vector { @@ -1863,7 +1872,7 @@ impl Writer { fn write_functions( &mut self, module: &crate::Module, - mod_info: &ModuleInfo, + mod_info: &valid::ModuleInfo, options: &Options, pipeline_options: &PipelineOptions, ) -> Result { @@ -1917,7 +1926,10 @@ impl Writer { writeln!( self.out, "{}{} {}{}", - INDENT, param_type_name, name, separator + back::INDENT, + param_type_name, + name, + separator )?; } for (index, &handle) in pass_through_globals.iter().enumerate() { @@ -1930,7 +1942,7 @@ impl Writer { }; let separator = separate(index + 1 != pass_through_globals.len() || supports_array_length); - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; tyvar.try_fmt(&mut self.out)?; writeln!(self.out, "{}", separator)?; } @@ -1939,7 +1951,7 @@ impl Writer { writeln!( self.out, "{}constant _mslBufferSizes& _buffer_sizes", - INDENT + back::INDENT )?; } @@ -1954,7 +1966,7 @@ impl Writer { first_time: false, }; let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; - write!(self.out, "{}{} {}", INDENT, ty_name, local_name)?; + write!(self.out, "{}{} {}", back::INDENT, ty_name, local_name)?; if let Some(value) = local.init { let coco = ConstantContext { handle: value, @@ -2085,7 +2097,7 @@ impl Writer { first_time: false, }; let resolved = options.resolve_local_binding(binding, in_mode)?; - write!(self.out, "{}{} {}", INDENT, ty_name, name)?; + write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; resolved.try_fmt_decorated(&mut self.out, "")?; writeln!(self.out, ";")?; } @@ -2145,7 +2157,7 @@ impl Writer { _ => None, }; let resolved = options.resolve_local_binding(binding, out_mode)?; - write!(self.out, "{}{} {}", INDENT, ty_name, name)?; + write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; resolved.try_fmt_decorated(&mut self.out, "")?; if let Some(array_len) = array_len { write!(self.out, " [{}]", array_len)?; @@ -2277,7 +2289,7 @@ impl Writer { usage, reference: false, }; - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; tyvar.try_fmt(&mut self.out)?; match var.init { Some(value) => { @@ -2301,10 +2313,12 @@ impl Writer { writeln!( self.out, "{}constexpr {}::sampler {}(", - INDENT, NAMESPACE, name + back::INDENT, + NAMESPACE, + name )?; self.put_inline_sampler_properties(Level(2), sampler)?; - writeln!(self.out, "{});", INDENT)?; + writeln!(self.out, "{});", back::INDENT)?; } } } @@ -2319,7 +2333,9 @@ impl Writer { write!( self.out, "{}const {} {} = {{ ", - INDENT, struct_name, arg_name + back::INDENT, + struct_name, + arg_name )?; for (member_index, member) in members.iter().enumerate() { let name = @@ -2339,7 +2355,10 @@ impl Writer { writeln!( self.out, "{}const auto {} = {}.{};", - INDENT, arg_name, varyings_member_name, arg_name + back::INDENT, + arg_name, + varyings_member_name, + arg_name )?; } } @@ -2357,7 +2376,7 @@ impl Writer { access: crate::StorageAccess::empty(), first_time: false, }; - write!(self.out, "{}{} {}", INDENT, ty_name, name)?; + write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; if let Some(value) = local.init { let coco = ConstantContext { handle: value, From 0a957f9427e7e9bb303c1e158641a2932eb093ad Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 23 Jun 2021 13:31:30 +0300 Subject: [PATCH 1028/2212] [wgsl-out] Reduce global import usage --- src/back/wgsl/writer.rs | 397 ++++++++++++++++++++++------------------ 1 file changed, 214 insertions(+), 183 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index bba0df446..713bb3b8e 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1,15 +1,8 @@ use super::Error; use crate::{ - back::{ - binary_operation_str, vector_size_str, wgsl::keywords::RESERVED, FunctionCtx, FunctionType, - BAKE_PREFIX, COMPONENTS, INDENT, - }, - proc::{NameKey, Namer, TypeResolution}, - valid::{FunctionInfo, ModuleInfo}, - ArraySize, Binding, Constant, ConstantInner, Expression, FastHashMap, Function, GlobalVariable, - Handle, ImageClass, ImageDimension, Interpolation, Module, SampleLevel, Sampling, ScalarKind, - ScalarValue, ShaderStage, Statement, StorageClass, StorageFormat, StructMember, Type, - TypeInner, + back, + proc::{self, NameKey}, + valid, Handle, Module, ShaderStage, TypeInner, }; use std::fmt::Write; @@ -24,7 +17,7 @@ enum Attribute { Block, BuiltIn(crate::BuiltIn), Group(u32), - Interpolate(Option, Option), + Interpolate(Option, Option), Location(u32), Stage(ShaderStage), Stride(u32), @@ -33,18 +26,18 @@ enum Attribute { pub struct Writer { out: W, - names: FastHashMap, - namer: Namer, + names: crate::FastHashMap, + namer: proc::Namer, named_expressions: crate::NamedExpressions, - ep_results: Vec<(ShaderStage, Handle)>, + ep_results: Vec<(ShaderStage, Handle)>, } impl Writer { pub fn new(out: W) -> Self { Writer { out, - names: FastHashMap::default(), - namer: Namer::default(), + names: crate::FastHashMap::default(), + namer: proc::Namer::default(), named_expressions: crate::NamedExpressions::default(), ep_results: vec![], } @@ -52,12 +45,13 @@ impl Writer { fn reset(&mut self, module: &Module) { self.names.clear(); - self.namer.reset(module, RESERVED, &[], &mut self.names); + self.namer + .reset(module, super::keywords::RESERVED, &[], &mut self.names); self.named_expressions.clear(); self.ep_results.clear(); } - pub fn write(&mut self, module: &Module, info: &ModuleInfo) -> BackendResult { + pub fn write(&mut self, module: &Module, info: &valid::ModuleInfo) -> BackendResult { self.reset(module); // Save all ep result types @@ -101,8 +95,8 @@ impl Writer { for (handle, function) in module.functions.iter() { let fun_info = &info[handle]; - let func_ctx = FunctionCtx { - ty: FunctionType::Function(handle), + let func_ctx = back::FunctionCtx { + ty: back::FunctionType::Function(handle), info: fun_info, expressions: &function.expressions, named_expressions: &function.named_expressions, @@ -128,8 +122,8 @@ impl Writer { // Add a newline after attribute writeln!(self.out)?; - let func_ctx = FunctionCtx { - ty: FunctionType::EntryPoint(index as u16), + let func_ctx = back::FunctionCtx { + ty: back::FunctionType::EntryPoint(index as u16), info: info.get_entry_point(index), expressions: &ep.function.expressions, named_expressions: &ep.function.named_expressions, @@ -148,14 +142,16 @@ impl Writer { /// /// # Notes /// Adds no trailing or leading whitespace - fn write_scalar_value(&mut self, value: ScalarValue) -> BackendResult { + fn write_scalar_value(&mut self, value: crate::ScalarValue) -> BackendResult { + use crate::ScalarValue as Sv; + match value { - ScalarValue::Sint(value) => write!(self.out, "{}", value)?, - ScalarValue::Uint(value) => write!(self.out, "{}u", value)?, + Sv::Sint(value) => write!(self.out, "{}", value)?, + Sv::Uint(value) => write!(self.out, "{}u", value)?, // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero - ScalarValue::Float(value) => write!(self.out, "{:?}", value)?, - ScalarValue::Bool(value) => write!(self.out, "{}", value)?, + Sv::Float(value) => write!(self.out, "{:?}", value)?, + Sv::Bool(value) => write!(self.out, "{}", value)?, } Ok(()) @@ -165,7 +161,7 @@ impl Writer { /// /// # Notes /// Adds no trailing or leading whitespace - fn write_struct_name(&mut self, module: &Module, handle: Handle) -> BackendResult { + fn write_struct_name(&mut self, module: &Module, handle: Handle) -> BackendResult { if module.types[handle].name.is_none() { if let Some(&(stage, _)) = self.ep_results.iter().find(|&&(_, ty)| ty == handle) { let name = match stage { @@ -192,12 +188,12 @@ impl Writer { fn write_function( &mut self, module: &Module, - func: &Function, - func_ctx: &FunctionCtx<'_>, + func: &crate::Function, + func_ctx: &back::FunctionCtx<'_>, ) -> BackendResult { let func_name = match func_ctx.ty { - FunctionType::EntryPoint(index) => self.names[&NameKey::EntryPoint(index)].clone(), - FunctionType::Function(handle) => self.names[&NameKey::Function(handle)].clone(), + back::FunctionType::EntryPoint(index) => &self.names[&NameKey::EntryPoint(index)], + back::FunctionType::Function(handle) => &self.names[&NameKey::Function(handle)], }; // Write function name @@ -212,11 +208,11 @@ impl Writer { } // Write argument name let argument_name = match func_ctx.ty { - FunctionType::Function(handle) => { - self.names[&NameKey::FunctionArgument(handle, index as u32)].clone() + back::FunctionType::Function(handle) => { + &self.names[&NameKey::FunctionArgument(handle, index as u32)] } - FunctionType::EntryPoint(ep_index) => { - self.names[&NameKey::EntryPointArgument(ep_index, index as u32)].clone() + back::FunctionType::EntryPoint(ep_index) => { + &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)] } }; @@ -246,7 +242,7 @@ impl Writer { // Write function local variables for (handle, local) in func.local_variables.iter() { // Write indentation (only for readability) - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; // Write the local name // The leading space is important @@ -336,7 +332,7 @@ impl Writer { }; let sampling_str = if let Some(sampling) = sampling { // Center sampling is the default - if sampling == Sampling::Center { + if sampling == crate::Sampling::Center { String::from("") } else { format!(",{}", sampling_str(sampling)) @@ -379,9 +375,9 @@ impl Writer { fn write_struct( &mut self, module: &Module, - handle: Handle, + handle: Handle, block: bool, - members: &[StructMember], + members: &[crate::StructMember], ) -> BackendResult { if block { self.write_attributes(&[Attribute::Block], false)?; @@ -394,7 +390,7 @@ impl Writer { writeln!(self.out)?; for (index, member) in members.iter().enumerate() { // Skip struct member with unsupported built in - if let Some(Binding::BuiltIn(builtin)) = member.binding { + if let Some(crate::Binding::BuiltIn(builtin)) = member.binding { if builtin_str(builtin).is_none() { log::warn!("Skip member with unsupported builtin {:?}", builtin); continue; @@ -402,7 +398,7 @@ impl Writer { } // The indentation is only for readability - write!(self.out, "{}", INDENT)?; + write!(self.out, "{}", back::INDENT)?; if let Some(ref binding) = member.binding { self.write_attributes(&map_binding_to_attribute(binding), true)?; } @@ -434,7 +430,7 @@ impl Writer { /// /// # Notes /// Adds no trailing or leading whitespace - fn write_type(&mut self, module: &Module, ty: Handle) -> BackendResult { + fn write_type(&mut self, module: &Module, ty: Handle) -> BackendResult { let inner = &module.types[ty].inner; match *inner { TypeInner::Struct { .. } => self.write_struct_name(module, ty)?, @@ -453,7 +449,11 @@ impl Writer { TypeInner::Vector { size, kind, .. } => write!( self.out, "{}", - format!("vec{}<{}>", vector_size_str(size), scalar_kind_str(kind),) + format!( + "vec{}<{}>", + back::vector_size_str(size), + scalar_kind_str(kind), + ) )?, TypeInner::Sampler { comparison: false } => { write!(self.out, "sampler")?; @@ -467,16 +467,18 @@ impl Writer { class, } => { // More about texture types: https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type + use crate::ImageClass as Ic; + let dim_str = image_dimension_str(dim); let arrayed_str = if arrayed { "_array" } else { "" }; let (class_str, multisampled_str, scalar_str) = match class { - ImageClass::Sampled { kind, multi } => ( + Ic::Sampled { kind, multi } => ( "", if multi { "multisampled_" } else { "" }, format!("<{}>", scalar_kind_str(kind)), ), - ImageClass::Depth => ("depth_", "", String::from("")), - ImageClass::Storage(storage_format) => ( + Ic::Depth => ("depth_", "", String::from("")), + Ic::Storage(storage_format) => ( "storage_", "", format!("<{}>", storage_format_str(storage_format)), @@ -497,12 +499,12 @@ impl Writer { // array -- Dynamic array write!(self.out, "array<")?; match size { - ArraySize::Constant(handle) => { + crate::ArraySize::Constant(handle) => { self.write_type(module, base)?; write!(self.out, ",")?; self.write_constant(module, handle)?; } - ArraySize::Dynamic => { + crate::ArraySize::Dynamic => { self.write_type(module, base)?; } } @@ -517,8 +519,8 @@ impl Writer { self.out, //TODO: Can matrix be other than f32? "mat{}x{}", - vector_size_str(columns), - vector_size_str(rows), + back::vector_size_str(columns), + back::vector_size_str(rows), )?; } TypeInner::Pointer { base, class } => { @@ -544,10 +546,13 @@ impl Writer { fn write_stmt( &mut self, module: &Module, - stmt: &Statement, - func_ctx: &FunctionCtx<'_>, + stmt: &crate::Statement, + func_ctx: &back::FunctionCtx<'_>, indent: usize, ) -> BackendResult { + use crate::{Expression, Statement}; + use back::INDENT; + match *stmt { Statement::Emit(ref range) => { for handle in range.clone() { @@ -585,7 +590,7 @@ impl Writer { } } - Some(format!("{}{}", BAKE_PREFIX, handle.index())) + Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) } else { None } @@ -666,7 +671,7 @@ impl Writer { } => { write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { - let name = format!("{}{}", BAKE_PREFIX, expr.index()); + let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); self.start_named_expr(module, expr, func_ctx, &name)?; self.write_expr(module, expr, func_ctx)?; self.named_expressions.insert(expr, name); @@ -810,8 +815,8 @@ impl Writer { fn start_named_expr( &mut self, module: &Module, - handle: Handle, - func_ctx: &FunctionCtx, + handle: Handle, + func_ctx: &back::FunctionCtx, name: &str, ) -> BackendResult { // Write variable name @@ -819,10 +824,10 @@ impl Writer { let ty = &func_ctx.info[handle].ty; // Write variable type match *ty { - TypeResolution::Handle(handle) => { + proc::TypeResolution::Handle(handle) => { self.write_type(module, handle)?; } - TypeResolution::Value(ref inner) => { + proc::TypeResolution::Value(ref inner) => { self.write_value_type(module, inner)?; } } @@ -838,9 +843,11 @@ impl Writer { fn write_expr( &mut self, module: &Module, - expr: Handle, - func_ctx: &FunctionCtx<'_>, + expr: Handle, + func_ctx: &back::FunctionCtx<'_>, ) -> BackendResult { + use crate::Expression; + if let Some(name) = self.named_expressions.get(&expr) { write!(self.out, "{}", name)?; return Ok(()); @@ -896,19 +903,14 @@ impl Writer { write!(self.out, ")")? } Expression::FunctionArgument(pos) => { - let name_key = match func_ctx.ty { - FunctionType::Function(handle) => NameKey::FunctionArgument(handle, pos), - FunctionType::EntryPoint(ep_index) => { - NameKey::EntryPointArgument(ep_index, pos) - } - }; + let name_key = func_ctx.argument_key(pos); let name = &self.names[&name_key]; write!(self.out, "{}", name)?; } Expression::Binary { op, left, right } => { write!(self.out, "(")?; self.write_expr(module, left, func_ctx)?; - write!(self.out, " {} ", binary_operation_str(op))?; + write!(self.out, " {} ", back::binary_operation_str(op))?; self.write_expr(module, right, func_ctx)?; write!(self.out, ")")?; } @@ -936,7 +938,7 @@ impl Writer { match *resolved { TypeInner::Vector { .. } => { // Write vector access as a swizzle - write!(self.out, ".{}", COMPONENTS[index as usize])? + write!(self.out, ".{}", back::COMPONENTS[index as usize])? } TypeInner::Matrix { .. } | TypeInner::Array { .. } @@ -964,15 +966,17 @@ impl Writer { level, depth_ref, } => { + use crate::SampleLevel as Sl; + let suffix_cmp = match depth_ref { Some(_) => "Compare", None => "", }; let suffix_level = match level { - SampleLevel::Auto => "", - SampleLevel::Zero | SampleLevel::Exact(_) => "Level", - SampleLevel::Bias(_) => "Bias", - SampleLevel::Gradient { .. } => "Grad", + Sl::Auto => "", + Sl::Zero | Sl::Exact(_) => "Level", + Sl::Bias(_) => "Bias", + Sl::Gradient { .. } => "Grad", }; write!(self.out, "textureSample{}{}(", suffix_cmp, suffix_level)?; @@ -993,22 +997,22 @@ impl Writer { } match level { - SampleLevel::Auto => {} - SampleLevel::Zero => { + Sl::Auto => {} + Sl::Zero => { // Level 0 is implied for depth comparison if depth_ref.is_none() { write!(self.out, ", 0.0")?; } } - SampleLevel::Exact(expr) => { + Sl::Exact(expr) => { write!(self.out, ", ")?; self.write_expr(module, expr, func_ctx)?; } - SampleLevel::Bias(expr) => { + Sl::Bias(expr) => { write!(self.out, ", ")?; self.write_expr(module, expr, func_ctx)?; } - SampleLevel::Gradient { x, y } => { + Sl::Gradient { x, y } => { write!(self.out, ", ")?; self.write_expr(module, x, func_ctx)?; write!(self.out, ", ")?; @@ -1024,16 +1028,18 @@ impl Writer { write!(self.out, ")")?; } Expression::ImageQuery { image, query } => { + use crate::ImageQuery as Iq; + let texture_function = match query { - crate::ImageQuery::Size { .. } => "textureDimensions", - crate::ImageQuery::NumLevels => "textureNumLevels", - crate::ImageQuery::NumLayers => "textureNumLayers", - crate::ImageQuery::NumSamples => "textureNumSamples", + Iq::Size { .. } => "textureDimensions", + Iq::NumLevels => "textureNumLevels", + Iq::NumLayers => "textureNumLayers", + Iq::NumSamples => "textureNumSamples", }; write!(self.out, "{}(", texture_function)?; self.write_expr(module, image, func_ctx)?; - if let crate::ImageQuery::Size { level: Some(level) } = query { + if let Iq::Size { level: Some(level) } = query { write!(self.out, ", ")?; self.write_expr(module, level, func_ctx)?; }; @@ -1070,15 +1076,15 @@ impl Writer { write!( self.out, "mat{}x{}", - vector_size_str(columns), - vector_size_str(rows) + back::vector_size_str(columns), + back::vector_size_str(rows) )?; } TypeInner::Vector { size, .. } => { write!( self.out, "vec{}<{}>", - vector_size_str(size), + back::vector_size_str(size), scalar_kind_str(kind) )?; } @@ -1106,7 +1112,7 @@ impl Writer { } }; let scalar = scalar_kind_str(scalar_kind); - let size = vector_size_str(size); + let size = back::vector_size_str(size); write!(self.out, "vec{}<{}>(", size, scalar)?; self.write_expr(module, value, func_ctx)?; @@ -1210,7 +1216,7 @@ impl Writer { self.write_expr(module, vector, func_ctx)?; write!(self.out, ".")?; for &sc in pattern[..size as usize].iter() { - self.out.write_char(COMPONENTS[sc as usize])?; + self.out.write_char(back::COMPONENTS[sc as usize])?; } } Expression::Unary { op, expr } => { @@ -1219,7 +1225,7 @@ impl Writer { crate::UnaryOperator::Not => { match *func_ctx.info[expr].ty.inner_with(&module.types) { TypeInner::Scalar { - kind: ScalarKind::Bool, + kind: crate::ScalarKind::Bool, .. } | TypeInner::Vector { .. } => "!", @@ -1247,23 +1253,27 @@ impl Writer { write!(self.out, ")")? } Expression::Derivative { axis, expr } => { + use crate::DerivativeAxis as Da; + let op = match axis { - crate::DerivativeAxis::X => "dpdx", - crate::DerivativeAxis::Y => "dpdy", - crate::DerivativeAxis::Width => "fwidth", + Da::X => "dpdx", + Da::Y => "dpdy", + Da::Width => "fwidth", }; write!(self.out, "{}(", op)?; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")? } Expression::Relational { fun, argument } => { + use crate::RelationalFunction as Rf; + let fun_name = match fun { - crate::RelationalFunction::IsFinite => "isFinite", - crate::RelationalFunction::IsInf => "isInf", - crate::RelationalFunction::IsNan => "isNan", - crate::RelationalFunction::IsNormal => "isNormal", - crate::RelationalFunction::All => "all", - crate::RelationalFunction::Any => "any", + Rf::IsFinite => "isFinite", + Rf::IsInf => "isInf", + Rf::IsNan => "isNan", + Rf::IsNormal => "isNormal", + Rf::All => "all", + Rf::Any => "any", }; write!(self.out, "{}(", fun_name)?; @@ -1284,8 +1294,8 @@ impl Writer { fn write_global( &mut self, module: &Module, - global: &GlobalVariable, - handle: Handle, + global: &crate::GlobalVariable, + handle: Handle, ) -> BackendResult { let name = self.names[&NameKey::GlobalVariable(handle)].clone(); // Write group and dinding attributes if present @@ -1329,7 +1339,11 @@ impl Writer { /// /// # Notes /// Doesn't add any newlines or leading/trailing spaces - fn write_constant(&mut self, module: &Module, handle: Handle) -> BackendResult { + fn write_constant( + &mut self, + module: &Module, + handle: Handle, + ) -> BackendResult { let constant = &module.constants[handle]; match constant.inner { crate::ConstantInner::Scalar { @@ -1353,7 +1367,7 @@ impl Writer { // Write the comma separated constants for (index, constant) in components.iter().enumerate() { - if let Some(&Binding::BuiltIn(builtin)) = + if let Some(&crate::Binding::BuiltIn(builtin)) = members.and_then(|members| members.get(index)?.binding.as_ref()) { if builtin_str(builtin).is_none() { @@ -1386,8 +1400,8 @@ impl Writer { fn write_global_constant( &mut self, module: &Module, - inner: &ConstantInner, - handle: Handle, + inner: &crate::ConstantInner, + handle: Handle, ) -> BackendResult { match *inner { crate::ConstantInner::Scalar { @@ -1417,7 +1431,7 @@ impl Writer { // End with semicolon writeln!(self.out, ";")?; } - ConstantInner::Composite { ty, ref components } => { + crate::ConstantInner::Composite { ty, ref components } => { let name = self.names[&NameKey::Constant(handle)].clone(); // First write only constant name write!(self.out, "let {}: ", name)?; @@ -1450,112 +1464,125 @@ impl Writer { } fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { - use crate::BuiltIn; + use crate::BuiltIn as Bi; + match built_in { - BuiltIn::VertexIndex => Some("vertex_index"), - BuiltIn::InstanceIndex => Some("instance_index"), - BuiltIn::Position => Some("position"), - BuiltIn::FrontFacing => Some("front_facing"), - BuiltIn::FragDepth => Some("frag_depth"), - BuiltIn::LocalInvocationId => Some("local_invocation_id"), - BuiltIn::LocalInvocationIndex => Some("local_invocation_index"), - BuiltIn::GlobalInvocationId => Some("global_invocation_id"), - BuiltIn::WorkGroupId => Some("workgroup_id"), - BuiltIn::WorkGroupSize => Some("workgroup_size"), - BuiltIn::SampleIndex => Some("sample_index"), - BuiltIn::SampleMask => Some("sample_mask"), + Bi::VertexIndex => Some("vertex_index"), + Bi::InstanceIndex => Some("instance_index"), + Bi::Position => Some("position"), + Bi::FrontFacing => Some("front_facing"), + Bi::FragDepth => Some("frag_depth"), + Bi::LocalInvocationId => Some("local_invocation_id"), + Bi::LocalInvocationIndex => Some("local_invocation_index"), + Bi::GlobalInvocationId => Some("global_invocation_id"), + Bi::WorkGroupId => Some("workgroup_id"), + Bi::WorkGroupSize => Some("workgroup_size"), + Bi::SampleIndex => Some("sample_index"), + Bi::SampleMask => Some("sample_mask"), _ => None, } } -fn image_dimension_str(dim: ImageDimension) -> &'static str { +fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { + use crate::ImageDimension as IDim; + match dim { - ImageDimension::D1 => "1d", - ImageDimension::D2 => "2d", - ImageDimension::D3 => "3d", - ImageDimension::Cube => "cube", + IDim::D1 => "1d", + IDim::D2 => "2d", + IDim::D3 => "3d", + IDim::Cube => "cube", } } -fn scalar_kind_str(kind: ScalarKind) -> &'static str { +fn scalar_kind_str(kind: crate::ScalarKind) -> &'static str { + use crate::ScalarKind as Sk; + match kind { - crate::ScalarKind::Float => "f32", - crate::ScalarKind::Sint => "i32", - crate::ScalarKind::Uint => "u32", - crate::ScalarKind::Bool => "bool", + Sk::Float => "f32", + Sk::Sint => "i32", + Sk::Uint => "u32", + Sk::Bool => "bool", } } -fn storage_format_str(format: StorageFormat) -> &'static str { +fn storage_format_str(format: crate::StorageFormat) -> &'static str { + use crate::StorageFormat as Sf; + match format { - StorageFormat::R8Unorm => "r8unorm", - StorageFormat::R8Snorm => "r8snorm", - StorageFormat::R8Uint => "r8uint", - StorageFormat::R8Sint => "r8sint", - StorageFormat::R16Uint => "r16uint", - StorageFormat::R16Sint => "r16sint", - StorageFormat::R16Float => "r16float", - StorageFormat::Rg8Unorm => "rg8unorm", - StorageFormat::Rg8Snorm => "rg8snorm", - StorageFormat::Rg8Uint => "rg8uint", - StorageFormat::Rg8Sint => "rg8sint", - StorageFormat::R32Uint => "r32uint", - StorageFormat::R32Sint => "r32sint", - StorageFormat::R32Float => "r32float", - StorageFormat::Rg16Uint => "rg16uint", - StorageFormat::Rg16Sint => "rg16sint", - StorageFormat::Rg16Float => "rg16float", - StorageFormat::Rgba8Unorm => "rgba8unorm", - StorageFormat::Rgba8Snorm => "rgba8snorm", - StorageFormat::Rgba8Uint => "rgba8uint", - StorageFormat::Rgba8Sint => "rgba8sint", - StorageFormat::Rgb10a2Unorm => "rgb10a2unorm", - StorageFormat::Rg11b10Float => "rg11b10float", - StorageFormat::Rg32Uint => "rg32uint", - StorageFormat::Rg32Sint => "rg32sint", - StorageFormat::Rg32Float => "rg32float", - StorageFormat::Rgba16Uint => "rgba16uint", - StorageFormat::Rgba16Sint => "rgba16sint", - StorageFormat::Rgba16Float => "rgba16float", - StorageFormat::Rgba32Uint => "rgba32uint", - StorageFormat::Rgba32Sint => "rgba32sint", - StorageFormat::Rgba32Float => "rgba32float", + Sf::R8Unorm => "r8unorm", + Sf::R8Snorm => "r8snorm", + Sf::R8Uint => "r8uint", + Sf::R8Sint => "r8sint", + Sf::R16Uint => "r16uint", + Sf::R16Sint => "r16sint", + Sf::R16Float => "r16float", + Sf::Rg8Unorm => "rg8unorm", + Sf::Rg8Snorm => "rg8snorm", + Sf::Rg8Uint => "rg8uint", + Sf::Rg8Sint => "rg8sint", + Sf::R32Uint => "r32uint", + Sf::R32Sint => "r32sint", + Sf::R32Float => "r32float", + Sf::Rg16Uint => "rg16uint", + Sf::Rg16Sint => "rg16sint", + Sf::Rg16Float => "rg16float", + Sf::Rgba8Unorm => "rgba8unorm", + Sf::Rgba8Snorm => "rgba8snorm", + Sf::Rgba8Uint => "rgba8uint", + Sf::Rgba8Sint => "rgba8sint", + Sf::Rgb10a2Unorm => "rgb10a2unorm", + Sf::Rg11b10Float => "rg11b10float", + Sf::Rg32Uint => "rg32uint", + Sf::Rg32Sint => "rg32sint", + Sf::Rg32Float => "rg32float", + Sf::Rgba16Uint => "rgba16uint", + Sf::Rgba16Sint => "rgba16sint", + Sf::Rgba16Float => "rgba16float", + Sf::Rgba32Uint => "rgba32uint", + Sf::Rgba32Sint => "rgba32sint", + Sf::Rgba32Float => "rgba32float", } } /// Helper function that returns the string corresponding to the WGSL interpolation qualifier -fn interpolation_str(interpolation: Interpolation) -> &'static str { +fn interpolation_str(interpolation: crate::Interpolation) -> &'static str { + use crate::Interpolation as I; + match interpolation { - Interpolation::Perspective => "perspective", - Interpolation::Linear => "linear", - Interpolation::Flat => "flat", + I::Perspective => "perspective", + I::Linear => "linear", + I::Flat => "flat", } } /// Return the WGSL auxiliary qualifier for the given sampling value. -fn sampling_str(sampling: Sampling) -> &'static str { +fn sampling_str(sampling: crate::Sampling) -> &'static str { + use crate::Sampling as S; + match sampling { - Sampling::Center => "", - Sampling::Centroid => "centroid", - Sampling::Sample => "sample", + S::Center => "", + S::Centroid => "centroid", + S::Sample => "sample", } } -fn storage_class_str(storage_class: StorageClass) -> Option<&'static str> { +fn storage_class_str(storage_class: crate::StorageClass) -> Option<&'static str> { + use crate::StorageClass as Sc; + match storage_class { - StorageClass::Private => Some("private"), - StorageClass::Uniform => Some("uniform"), - StorageClass::Storage => Some("storage"), - StorageClass::PushConstant => Some("push_constant"), - StorageClass::WorkGroup => Some("workgroup"), - StorageClass::Function | StorageClass::Handle => None, + Sc::Private => Some("private"), + Sc::Uniform => Some("uniform"), + Sc::Storage => Some("storage"), + Sc::PushConstant => Some("push_constant"), + Sc::WorkGroup => Some("workgroup"), + Sc::Function | Sc::Handle => None, } } -fn map_binding_to_attribute(binding: &Binding) -> Vec { +fn map_binding_to_attribute(binding: &crate::Binding) -> Vec { match *binding { - Binding::BuiltIn(built_in) => vec![Attribute::BuiltIn(built_in)], - Binding::Location { + crate::Binding::BuiltIn(built_in) => vec![Attribute::BuiltIn(built_in)], + crate::Binding::Location { location, interpolation, sampling, @@ -1566,7 +1593,11 @@ fn map_binding_to_attribute(binding: &Binding) -> Vec { } } -fn is_deref_required(expr: Handle, module: &Module, info: &FunctionInfo) -> bool { +fn is_deref_required( + expr: Handle, + module: &Module, + info: &valid::FunctionInfo, +) -> bool { let base_ty_res = &info[expr].ty; let resolved = base_ty_res.inner_with(&module.types); match *resolved { @@ -1581,10 +1612,10 @@ fn is_deref_required(expr: Handle, module: &Module, info: &FunctionI /// Helper function that check that expression don't access to structure member with unsupported builtin. fn access_to_unsupported_builtin( - expr: Handle, + expr: Handle, index: u32, module: &Module, - info: &FunctionInfo, + info: &valid::FunctionInfo, ) -> bool { let base_ty_res = &info[expr].ty; let resolved = base_ty_res.inner_with(&module.types); @@ -1595,7 +1626,7 @@ fn access_to_unsupported_builtin( { // Let's check that we try to access a struct member with unsupported built-in and skip it. if let TypeInner::Struct { ref members, .. } = module.types[pointer_base_handle].inner { - if let Some(Binding::BuiltIn(builtin)) = members[index as usize].binding { + if let Some(crate::Binding::BuiltIn(builtin)) = members[index as usize].binding { if builtin_str(builtin).is_none() { log::warn!("Skip component with unsupported builtin {:?}", builtin); return true; From 42f1f37741c9ce8cc5f74dc858d77dc1bc0c0731 Mon Sep 17 00:00:00 2001 From: Jonathan Behrens Date: Tue, 22 Jun 2021 14:38:10 -0400 Subject: [PATCH 1029/2212] [glsl-in] Deduplicate constants so array types match --- src/front/glsl/parser.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 9d0700780..c68454b28 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1032,7 +1032,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } }; - let handle = self.program.module.constants.append(Constant { + let handle = self.program.module.constants.fetch_or_append(Constant { name: None, specialization: None, inner: ConstantInner::Scalar { width, value }, From 64b9e4501576bf5fecdb60c6375b191becbaa992 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 23 Jun 2021 08:00:15 +0300 Subject: [PATCH 1030/2212] [msl-out] Add type for backend result --- src/back/msl/writer.rs | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 3331c415c..2d2d715ca 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -10,6 +10,9 @@ use std::{ iter, }; +/// Shorthand result used internally by the backend +type BackendResult = Result<(), Error>; + const NAMESPACE: &str = "metal"; const WRAPPED_ARRAY_FIELD: &str = "inner"; @@ -194,7 +197,7 @@ struct TypedGlobalVariable<'a> { } impl<'a> TypedGlobalVariable<'a> { - fn try_fmt(&self, out: &mut W) -> Result<(), Error> { + fn try_fmt(&self, out: &mut W) -> BackendResult { let var = &self.module.global_variables[self.handle]; let name = &self.names[&NameKey::GlobalVariable(self.handle)]; let ty_name = TypeContext { @@ -460,7 +463,7 @@ impl Writer { &mut self, parameters: impl Iterator>, context: &ExpressionContext, - ) -> Result<(), Error> { + ) -> BackendResult { write!(self.out, "(")?; for (i, handle) in parameters.enumerate() { if i != 0 { @@ -478,7 +481,7 @@ impl Writer { query: &str, level: Option>, context: &ExpressionContext, - ) -> Result<(), Error> { + ) -> BackendResult { self.put_expression(image, context, false)?; write!(self.out, ".get_{}(", query)?; if let Some(expr) = level { @@ -493,7 +496,7 @@ impl Writer { image: Handle, level: Option>, context: &ExpressionContext, - ) -> Result<(), Error> { + ) -> BackendResult { //Note: MSL only has separate width/height/depth queries, // so compose the result of them. let dim = match *context.resolve_type(image) { @@ -535,7 +538,7 @@ impl Writer { &mut self, expr: Handle, context: &ExpressionContext, - ) -> Result<(), Error> { + ) -> BackendResult { // coordinates in IR are int, but Metal expects uint let size_str = match *context.info[expr].ty.inner_with(&context.module.types) { crate::TypeInner::Scalar { .. } => "", @@ -553,7 +556,7 @@ impl Writer { image: Handle, level: crate::SampleLevel, context: &ExpressionContext, - ) -> Result<(), Error> { + ) -> BackendResult { let has_levels = match *context.resolve_type(image) { crate::TypeInner::Image { dim: crate::ImageDimension::D1, @@ -595,7 +598,7 @@ impl Writer { ty: Handle, components: &[Handle], context: &ExpressionContext, - ) -> Result<(), Error> { + ) -> BackendResult { match context.module.types[ty].inner { crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { write!(self.out, "{}", scalar_kind_string(kind))?; @@ -642,7 +645,7 @@ impl Writer { &mut self, expr: Handle, context: &ExpressionContext, - ) -> Result<(), Error> { + ) -> BackendResult { let handle = match context.function.expressions[expr] { crate::Expression::AccessIndex { base, .. } => { match context.function.expressions[base] { @@ -695,7 +698,7 @@ impl Writer { expr_handle: Handle, context: &ExpressionContext, is_scoped: bool, - ) -> Result<(), Error> { + ) -> BackendResult { // Add to the set in order to track the stack size. #[cfg(test)] #[allow(trivial_casts)] @@ -1162,7 +1165,7 @@ impl Writer { expr_handle: Handle, result_struct: Option<&str>, context: &ExpressionContext, - ) -> Result<(), Error> { + ) -> BackendResult { match result_struct { Some(struct_name) => { let result_ty = context.function.result.as_ref().unwrap().ty; @@ -1239,7 +1242,7 @@ impl Writer { handle: Handle, context: &ExpressionContext, name: &str, - ) -> Result<(), Error> { + ) -> BackendResult { match context.info[handle].ty { TypeResolution::Handle(ty_handle) => { let ty_name = TypeContext { @@ -1290,7 +1293,7 @@ impl Writer { level: Level, statements: &[crate::Statement], context: &StatementContext, - ) -> Result<(), Error> { + ) -> BackendResult { // Add to the set in order to track the stack size. #[cfg(test)] #[allow(trivial_casts)] @@ -1602,7 +1605,7 @@ impl Writer { self.write_functions(module, info, options, pipeline_options) } - fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> { + fn write_type_defs(&mut self, module: &crate::Module) -> BackendResult { for (handle, ty) in module.types.iter() { if !ty.needs_alias() { continue; @@ -1720,7 +1723,7 @@ impl Writer { Ok(()) } - fn write_scalar_constants(&mut self, module: &crate::Module) -> Result<(), Error> { + fn write_scalar_constants(&mut self, module: &crate::Module) -> BackendResult { for (handle, constant) in module.constants.iter() { match constant.inner { crate::ConstantInner::Scalar { @@ -1758,7 +1761,7 @@ impl Writer { Ok(()) } - fn write_composite_constants(&mut self, module: &crate::Module) -> Result<(), Error> { + fn write_composite_constants(&mut self, module: &crate::Module) -> BackendResult { for (handle, constant) in module.constants.iter() { match constant.inner { crate::ConstantInner::Scalar { .. } => {} @@ -1794,7 +1797,7 @@ impl Writer { &mut self, level: Level, sampler: &sm::InlineSampler, - ) -> Result<(), Error> { + ) -> BackendResult { for (&letter, address) in ['s', 't', 'r'].iter().zip(sampler.address.iter()) { writeln!( self.out, From 1c5d538ab41256a50df569c5e59d3cd9840e5f29 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 23 Jun 2021 19:47:49 +0300 Subject: [PATCH 1031/2212] [glsl-out] Add entry point name to snapshot file name --- tests/out/glsl/{boids.Compute.glsl => boids.main.Compute.glsl} | 0 ...control-flow.Compute.glsl => control-flow.main.Compute.glsl} | 0 tests/out/glsl/{empty.Compute.glsl => empty.main.Compute.glsl} | 0 .../glsl/{globals.Compute.glsl => globals.main.Compute.glsl} | 0 ...interpolate.Fragment.glsl => interpolate.main.Fragment.glsl} | 0 .../{interpolate.Vertex.glsl => interpolate.main.Vertex.glsl} | 0 .../glsl/{quad-vert.Vertex.glsl => quad-vert.main.Vertex.glsl} | 0 tests/out/glsl/{quad.Fragment.glsl => quad.main.Fragment.glsl} | 0 tests/out/glsl/{quad.Vertex.glsl => quad.main.Vertex.glsl} | 0 .../glsl/{shadow.Fragment.glsl => shadow.fs_main.Fragment.glsl} | 0 .../glsl/{skybox.Fragment.glsl => skybox.fs_main.Fragment.glsl} | 0 .../out/glsl/{skybox.Vertex.glsl => skybox.vs_main.Vertex.glsl} | 0 ...tandard.Fragment.glsl => standard.derivatives.Fragment.glsl} | 0 tests/snapshots.rs | 2 +- 14 files changed, 1 insertion(+), 1 deletion(-) rename tests/out/glsl/{boids.Compute.glsl => boids.main.Compute.glsl} (100%) rename tests/out/glsl/{control-flow.Compute.glsl => control-flow.main.Compute.glsl} (100%) rename tests/out/glsl/{empty.Compute.glsl => empty.main.Compute.glsl} (100%) rename tests/out/glsl/{globals.Compute.glsl => globals.main.Compute.glsl} (100%) rename tests/out/glsl/{interpolate.Fragment.glsl => interpolate.main.Fragment.glsl} (100%) rename tests/out/glsl/{interpolate.Vertex.glsl => interpolate.main.Vertex.glsl} (100%) rename tests/out/glsl/{quad-vert.Vertex.glsl => quad-vert.main.Vertex.glsl} (100%) rename tests/out/glsl/{quad.Fragment.glsl => quad.main.Fragment.glsl} (100%) rename tests/out/glsl/{quad.Vertex.glsl => quad.main.Vertex.glsl} (100%) rename tests/out/glsl/{shadow.Fragment.glsl => shadow.fs_main.Fragment.glsl} (100%) rename tests/out/glsl/{skybox.Fragment.glsl => skybox.fs_main.Fragment.glsl} (100%) rename tests/out/glsl/{skybox.Vertex.glsl => skybox.vs_main.Vertex.glsl} (100%) rename tests/out/glsl/{standard.Fragment.glsl => standard.derivatives.Fragment.glsl} (100%) diff --git a/tests/out/glsl/boids.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl similarity index 100% rename from tests/out/glsl/boids.Compute.glsl rename to tests/out/glsl/boids.main.Compute.glsl diff --git a/tests/out/glsl/control-flow.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl similarity index 100% rename from tests/out/glsl/control-flow.Compute.glsl rename to tests/out/glsl/control-flow.main.Compute.glsl diff --git a/tests/out/glsl/empty.Compute.glsl b/tests/out/glsl/empty.main.Compute.glsl similarity index 100% rename from tests/out/glsl/empty.Compute.glsl rename to tests/out/glsl/empty.main.Compute.glsl diff --git a/tests/out/glsl/globals.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl similarity index 100% rename from tests/out/glsl/globals.Compute.glsl rename to tests/out/glsl/globals.main.Compute.glsl diff --git a/tests/out/glsl/interpolate.Fragment.glsl b/tests/out/glsl/interpolate.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/interpolate.Fragment.glsl rename to tests/out/glsl/interpolate.main.Fragment.glsl diff --git a/tests/out/glsl/interpolate.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl similarity index 100% rename from tests/out/glsl/interpolate.Vertex.glsl rename to tests/out/glsl/interpolate.main.Vertex.glsl diff --git a/tests/out/glsl/quad-vert.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl similarity index 100% rename from tests/out/glsl/quad-vert.Vertex.glsl rename to tests/out/glsl/quad-vert.main.Vertex.glsl diff --git a/tests/out/glsl/quad.Fragment.glsl b/tests/out/glsl/quad.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/quad.Fragment.glsl rename to tests/out/glsl/quad.main.Fragment.glsl diff --git a/tests/out/glsl/quad.Vertex.glsl b/tests/out/glsl/quad.main.Vertex.glsl similarity index 100% rename from tests/out/glsl/quad.Vertex.glsl rename to tests/out/glsl/quad.main.Vertex.glsl diff --git a/tests/out/glsl/shadow.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl similarity index 100% rename from tests/out/glsl/shadow.Fragment.glsl rename to tests/out/glsl/shadow.fs_main.Fragment.glsl diff --git a/tests/out/glsl/skybox.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl similarity index 100% rename from tests/out/glsl/skybox.Fragment.glsl rename to tests/out/glsl/skybox.fs_main.Fragment.glsl diff --git a/tests/out/glsl/skybox.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl similarity index 100% rename from tests/out/glsl/skybox.Vertex.glsl rename to tests/out/glsl/skybox.vs_main.Vertex.glsl diff --git a/tests/out/glsl/standard.Fragment.glsl b/tests/out/glsl/standard.derivatives.Fragment.glsl similarity index 100% rename from tests/out/glsl/standard.Fragment.glsl rename to tests/out/glsl/standard.derivatives.Fragment.glsl diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 0b8f67eba..d906b9894 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -247,7 +247,7 @@ fn write_output_glsl( writer.write().unwrap(); fs::write( - destination.join(format!("glsl/{}.{:?}.glsl", file_name, stage)), + destination.join(format!("glsl/{}.{}.{:?}.glsl", file_name, ep_name, stage)), buffer, ) .unwrap(); From c9a782f8d65cc8009ede36153bda33274d42167d Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 23 Jun 2021 20:09:48 +0300 Subject: [PATCH 1032/2212] [hlsl-out] Fix panic with shader with multiple entry points without argument --- src/back/hlsl/writer.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index f924435ec..c452542e4 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -542,7 +542,15 @@ impl<'a, W: Write> Writer<'a, W> { } back::FunctionType::EntryPoint(index) => { // EntryPoint arguments wrapped into structure - if !self.ep_inputs.is_empty() { + // We need to ensure that entry points have arguments too. + // For the case when we working with multiple entry points + // for example vertex shader with arguments and fragment shader without arguments. + if !self.ep_inputs.is_empty() + && !module.entry_points[index as usize] + .function + .arguments + .is_empty() + { if let Some(ref ep_input) = self.ep_inputs[index as usize] { write!( self.out, From 391983459a8197e59ca8301af1ee5c3c5077ca50 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 23 Jun 2021 20:55:24 +0300 Subject: [PATCH 1033/2212] [hlsl-out] Add enum with supported shader models --- cli/src/main.rs | 12 +++++++++--- src/back/hlsl/mod.rs | 25 ++++++++----------------- src/back/hlsl/writer.rs | 6 +----- 3 files changed, 18 insertions(+), 25 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index edf8f3e98..afc1d6f04 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -103,10 +103,16 @@ fn main() { }; } "shader-model" => { - use naga::back::hlsl::{ShaderModel, DEFAULT_SHADER_MODEL}; + use naga::back::hlsl::ShaderModel; let string = args.next().unwrap(); - params.hlsl.shader_model = - ShaderModel::new(string.parse().unwrap_or(DEFAULT_SHADER_MODEL)); + let sm_numb = string.parse::().unwrap(); + let sm = match string.parse().unwrap() { + 50 => ShaderModel::V5_0, + 51 => ShaderModel::V5_1, + 60 => ShaderModel::V6_0, + _ => panic!("Unsupported shader model: {}", sm_numb), + }; + params.hlsl.shader_model = sm; } other => log::warn!("Unknown parameter: {}", other), } diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 5825f5990..f42f5e01d 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -6,20 +6,13 @@ use thiserror::Error; pub use writer::Writer; -pub const DEFAULT_SHADER_MODEL: u16 = 50; -#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] -pub struct ShaderModel(u16); - -impl ShaderModel { - pub fn new(shader_model: u16) -> Self { - Self(shader_model) - } -} - -impl Default for ShaderModel { - fn default() -> Self { - Self(DEFAULT_SHADER_MODEL) - } +/// A HLSL shader model version. +#[allow(non_snake_case, non_camel_case_types)] +#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] +pub enum ShaderModel { + V5_0, + V5_1, + V6_0, } /// Structure that contains the configuration used in the [`Writer`](Writer) @@ -38,7 +31,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { Options { - shader_model: ShaderModel(50), + shader_model: ShaderModel::V5_0, vertex_entry_point_name: String::from("vert_main"), fragment_entry_point_name: String::from("frag_main"), compute_entry_point_name: String::from("comp_main"), @@ -50,8 +43,6 @@ impl Default for Options { pub enum Error { #[error(transparent)] IoError(#[from] FmtError), - #[error("Shader model {0:?} is not supported")] - UnsupportedShaderModel(ShaderModel), #[error("A scalar with an unsupported width was requested: {0:?} {1:?}")] UnsupportedScalar(crate::ScalarKind, crate::Bytes), #[error("{0}")] diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index c452542e4..e46ae1bc2 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,6 +1,6 @@ //TODO: temp #![allow(dead_code)] -use super::{Error, Options, ShaderModel}; +use super::{Error, Options}; use crate::{ back, proc::{self, NameKey}, @@ -55,10 +55,6 @@ impl<'a, W: Write> Writer<'a, W> { } pub fn write(&mut self, module: &Module, info: &valid::ModuleInfo) -> BackendResult { - if self.options.shader_model < ShaderModel::default() { - return Err(Error::UnsupportedShaderModel(self.options.shader_model)); - } - self.reset(module); // Write all constants From e28344edbb87cae7d6596d69838cca9fa3dd57e7 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 24 Jun 2021 13:59:35 +0300 Subject: [PATCH 1034/2212] [hlsl-out] Return entry points name to users --- cli/src/main.rs | 7 +++-- src/back/hlsl/mod.rs | 44 +++++++++++++++------------- src/back/hlsl/writer.rs | 42 ++++++++++++++++---------- tests/in/quad.wgsl | 7 +++++ tests/out/hlsl/empty.hlsl | 2 +- tests/out/hlsl/empty.hlsl.config | 2 +- tests/out/hlsl/quad-vert.hlsl | 8 ++--- tests/out/hlsl/quad-vert.hlsl.config | 2 +- tests/out/hlsl/quad.hlsl | 12 ++++---- tests/out/hlsl/quad.hlsl.config | 4 +-- tests/snapshots.rs | 24 ++++++++------- 11 files changed, 92 insertions(+), 62 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index afc1d6f04..0a2c22b89 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -304,9 +304,12 @@ fn main() { } "hlsl" => { use naga::back::hlsl; - let hlsl = hlsl::write_string(&module, info.as_ref().unwrap(), ¶ms.hlsl) + let mut buffer = String::new(); + let mut writer = hlsl::Writer::new(&mut buffer, ¶ms.hlsl); + writer + .write(&module, info.as_ref().unwrap()) .unwrap_pretty(); - fs::write(output_path, hlsl).unwrap(); + fs::write(output_path, buffer).unwrap(); } "wgsl" => { use naga::back::wgsl; diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index f42f5e01d..0631952c6 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -15,30 +15,45 @@ pub enum ShaderModel { V6_0, } +impl ShaderModel { + pub fn to_profile_string(self, stage: crate::ShaderStage) -> String { + let stage_prefix = match stage { + crate::ShaderStage::Vertex => "vs_", + crate::ShaderStage::Fragment => "ps_", + crate::ShaderStage::Compute => "cs_", + }; + + let version = match self { + Self::V5_0 => "5_0", + Self::V5_1 => "5_1", + Self::V6_0 => "6_0", + }; + + format!("{}{}", stage_prefix, version) + } +} + /// Structure that contains the configuration used in the [`Writer`](Writer) #[derive(Debug, Clone)] pub struct Options { /// The hlsl shader model to be used pub shader_model: ShaderModel, - /// The vertex entry point name in generated shader - pub vertex_entry_point_name: String, - /// The fragment entry point name in generated shader - pub fragment_entry_point_name: String, - /// The comput entry point name in generated shader - pub compute_entry_point_name: String, } impl Default for Options { fn default() -> Self { Options { shader_model: ShaderModel::V5_0, - vertex_entry_point_name: String::from("vert_main"), - fragment_entry_point_name: String::from("frag_main"), - compute_entry_point_name: String::from("comp_main"), } } } +pub struct ReflectionInfo { + /// Information about all entry points (stage, name). + pub entry_points: Vec<(crate::ShaderStage, String)>, + // TODO: locations +} + #[derive(Error, Debug)] pub enum Error { #[error(transparent)] @@ -50,14 +65,3 @@ pub enum Error { #[error("{0}")] Custom(String), } - -pub fn write_string( - module: &crate::Module, - info: &crate::valid::ModuleInfo, - options: &Options, -) -> Result { - let mut w = Writer::new(String::new(), options); - w.write(module, info)?; - let output = w.finish(); - Ok(output) -} diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index e46ae1bc2..4c27dccfa 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -13,9 +13,14 @@ const LOCATION_SEMANTIC: &str = "LOC"; /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; +/// Structure contains information required for generating +/// wrapped structure of all entry points arguments struct EntryPointBinding { + /// Associated shader stage stage: ShaderStage, + /// Generated structure name name: String, + /// Members of generated structure members: Vec, } @@ -29,8 +34,11 @@ pub struct Writer<'a, W> { out: W, names: crate::FastHashMap, namer: proc::Namer, + /// HLSL backend options options: &'a Options, + /// Information about entry point arguments wrapped into structure ep_inputs: Vec>, + /// Set of expressions that have associated temporary variables named_expressions: crate::NamedExpressions, } @@ -54,7 +62,11 @@ impl<'a, W: Write> Writer<'a, W> { self.ep_inputs.clear(); } - pub fn write(&mut self, module: &Module, info: &valid::ModuleInfo) -> BackendResult { + pub fn write( + &mut self, + module: &Module, + info: &valid::ModuleInfo, + ) -> Result { self.reset(module); // Write all constants @@ -102,7 +114,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write all entry points wrapped structs for (index, ep) in module.entry_points.iter().enumerate() { - self.write_ep_input_struct(module, &ep.function, ep.stage, index)?; + self.write_ep_input_struct(module, &ep.function, ep.stage, &ep.name, index)?; } // Write all regular functions @@ -121,6 +133,8 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out)?; } + let mut entry_points_info = Vec::with_capacity(module.entry_points.len()); + // Write all entry points for (index, ep) in module.entry_points.iter().enumerate() { let ctx = back::FunctionCtx { @@ -140,20 +154,20 @@ impl<'a, W: Write> Writer<'a, W> { )?; } - let name = match ep.stage { - ShaderStage::Vertex => &self.options.vertex_entry_point_name, - ShaderStage::Fragment => &self.options.fragment_entry_point_name, - ShaderStage::Compute => &self.options.compute_entry_point_name, - }; + let name = self.names[&NameKey::EntryPoint(index as u16)].clone(); - self.write_function(module, name, &ep.function, &ctx)?; + self.write_function(module, &name, &ep.function, &ctx)?; if index < module.entry_points.len() - 1 { writeln!(self.out)?; } + + entry_points_info.push((ep.stage, name)) } - Ok(()) + Ok(super::ReflectionInfo { + entry_points: entry_points_info, + }) } fn write_binding(&mut self, binding: &crate::Binding) -> BackendResult { @@ -174,14 +188,16 @@ impl<'a, W: Write> Writer<'a, W> { module: &Module, func: &crate::Function, stage: ShaderStage, + entry_point_name: &str, index: usize, ) -> BackendResult { if !func.arguments.is_empty() { - let struct_name = self.namer.call_unique(match stage { + let struct_name_prefix = match stage { ShaderStage::Vertex => "VertexInput", ShaderStage::Fragment => "FragmentInput", ShaderStage::Compute => "ComputeInput", - }); + }; + let struct_name = format!("{}_{}", struct_name_prefix, entry_point_name); let mut members = Vec::with_capacity(func.arguments.len()); @@ -1058,10 +1074,6 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } - - pub fn finish(self) -> W { - self.out - } } fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index df1786361..ca1655400 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -29,3 +29,10 @@ fn main([[location(0)]] uv : vec2) -> [[location(0)]] vec4 { let premultiplied = color.a * color; return premultiplied; } + + +// We need to make sure that backends are successfully handling multiple entry points for the same shader stage. +//[[stage(fragment)]] +//fn fs_extra() -> [[location(0)]] vec4 { +// return vec4(0.0, 0.5, 0.0, 0.5); +//} diff --git a/tests/out/hlsl/empty.hlsl b/tests/out/hlsl/empty.hlsl index a1b3590ec..e79d36b9c 100644 --- a/tests/out/hlsl/empty.hlsl +++ b/tests/out/hlsl/empty.hlsl @@ -1,5 +1,5 @@ [numthreads(1, 1, 1)] -void comp_main() +void main() { return; } diff --git a/tests/out/hlsl/empty.hlsl.config b/tests/out/hlsl/empty.hlsl.config index f20f94588..71412ac2d 100644 --- a/tests/out/hlsl/empty.hlsl.config +++ b/tests/out/hlsl/empty.hlsl.config @@ -1,2 +1,2 @@ compute=cs_5_0 -compute_name=comp_main +compute_name=main diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 4c28ecfb6..06a1a2fcd 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -18,7 +18,7 @@ static float2 a_uv1; static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, float(0.0), float(0.0) }; static float2 a_pos1; -struct VertexInput { +struct VertexInput_main { float2 a_uv2 : LOC1; float2 a_pos2 : LOC0; }; @@ -32,10 +32,10 @@ void main1() return; } -type10 vert_main(VertexInput vertexinput) +type10 main(VertexInput_main vertexinput_main) { - a_uv1 = vertexinput.a_uv2; - a_pos1 = vertexinput.a_pos2; + a_uv1 = vertexinput_main.a_uv2; + a_pos1 = vertexinput_main.a_pos2; main1(); float2 _expr10 = v_uv; float4 _expr11 = perVertexStruct.gl_Position; diff --git a/tests/out/hlsl/quad-vert.hlsl.config b/tests/out/hlsl/quad-vert.hlsl.config index c01697983..49efa2b9a 100644 --- a/tests/out/hlsl/quad-vert.hlsl.config +++ b/tests/out/hlsl/quad-vert.hlsl.config @@ -1,2 +1,2 @@ vertex=vs_5_0 -vertex_name=vert_main +vertex_name=main diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index bb524e835..6e616106d 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -8,24 +8,24 @@ struct VertexOutput { Texture2D u_texture : register(t0); SamplerState u_sampler : register(s1); -struct VertexInput { +struct VertexInput_main { float2 pos1 : LOC0; float2 uv2 : LOC1; }; -struct FragmentInput { +struct FragmentInput_main { float2 uv3 : LOC0; }; -VertexOutput vert_main(VertexInput vertexinput) +VertexOutput main(VertexInput_main vertexinput_main) { - const VertexOutput vertexoutput1 = { vertexinput.uv2, float4((c_scale * vertexinput.pos1), 0.0, 1.0) }; + const VertexOutput vertexoutput1 = { vertexinput_main.uv2, float4((c_scale * vertexinput_main.pos1), 0.0, 1.0) }; return vertexoutput1; } -float4 frag_main(FragmentInput fragmentinput) : SV_Target0 +float4 main1(FragmentInput_main fragmentinput_main) : SV_Target0 { - float4 color = u_texture.Sample(u_sampler, fragmentinput.uv3); + float4 color = u_texture.Sample(u_sampler, fragmentinput_main.uv3); if ((color.w == 0.0)) { discard; } diff --git a/tests/out/hlsl/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config index a11240919..bae3c1cc6 100644 --- a/tests/out/hlsl/quad.hlsl.config +++ b/tests/out/hlsl/quad.hlsl.config @@ -1,4 +1,4 @@ vertex=vs_5_0 -vertex_name=vert_main +vertex_name=main fragment=ps_5_0 -fragment_name=frag_main +fragment_name=main1 diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d906b9894..7ea614461 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -261,26 +261,30 @@ fn write_output_hlsl( file_name: &str, ) { use naga::back::hlsl; + let mut buffer = String::new(); let options = hlsl::Options::default(); - let string = hlsl::write_string(module, info, &options).unwrap(); + let mut writer = hlsl::Writer::new(&mut buffer, &options); + let reflection_info = writer.write(module, info).unwrap(); - fs::write(destination.join(format!("hlsl/{}.hlsl", file_name)), string).unwrap(); + fs::write(destination.join(format!("hlsl/{}.hlsl", file_name)), buffer).unwrap(); // We need a config file for validation script // This file contains an info about profiles (shader stages) contains inside generated shader // This info will be passed to dxc let mut config_str = String::from(""); - for ep in module.entry_points.iter() { - let (stage_str, profile, ep_name) = match ep.stage { - naga::ShaderStage::Vertex => ("vertex", "vs_5_0", &options.vertex_entry_point_name), - naga::ShaderStage::Fragment => { - ("fragment", "ps_5_0", &options.fragment_entry_point_name) - } - naga::ShaderStage::Compute => ("compute", "cs_5_0", &options.compute_entry_point_name), + for (stage, name) in reflection_info.entry_points.iter() { + let stage_str = match stage { + naga::ShaderStage::Vertex => "vertex", + naga::ShaderStage::Fragment => "fragment", + naga::ShaderStage::Compute => "compute", }; config_str = format!( "{}{}={}\n{}_name={}\n", - config_str, stage_str, profile, stage_str, ep_name + config_str, + stage_str, + options.shader_model.to_profile_string(*stage), + stage_str, + name ); } fs::write( From a8119f005e1eadc2a067f6b5f249753bb5cf3f31 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 24 Jun 2021 14:01:41 +0300 Subject: [PATCH 1035/2212] Add extra fragment entry point to wgsl quad snapshot --- tests/in/quad.wgsl | 8 +- tests/out/dot/quad.dot | 22 +++ tests/out/glsl/quad.fs_extra.Fragment.glsl | 16 ++ tests/out/hlsl/quad.hlsl | 5 + tests/out/hlsl/quad.hlsl.config | 2 + tests/out/msl/quad.msl | 9 + tests/out/spv/quad.spvasm | 188 +++++++++++---------- tests/out/wgsl/quad.wgsl | 5 + 8 files changed, 164 insertions(+), 91 deletions(-) create mode 100644 tests/out/glsl/quad.fs_extra.Fragment.glsl diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index ca1655400..546622f39 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -32,7 +32,7 @@ fn main([[location(0)]] uv : vec2) -> [[location(0)]] vec4 { // We need to make sure that backends are successfully handling multiple entry points for the same shader stage. -//[[stage(fragment)]] -//fn fs_extra() -> [[location(0)]] vec4 { -// return vec4(0.0, 0.5, 0.0, 0.5); -//} +[[stage(fragment)]] +fn fs_extra() -> [[location(0)]] vec4 { + return vec4(0.0, 0.5, 0.0, 0.5); +} diff --git a/tests/out/dot/quad.dot b/tests/out/dot/quad.dot index 60587fc8b..618a76cfc 100644 --- a/tests/out/dot/quad.dot +++ b/tests/out/dot/quad.dot @@ -82,4 +82,26 @@ digraph Module { ep1_s8 -> ep1_e8 [ style=dotted ] ep1_s8 -> ep1_e9 [ style=dotted ] } + subgraph cluster_ep2 { + label="Fragment/'fs_extra'" + node [ style=filled ] + ep2_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] + ep2_e1 [ fillcolor="#ffffb3" label="[2] Global" ] + g1 -> ep2_e1 [fillcolor=gray] + ep2_e2 [ fillcolor="#ffffb3" label="[3] Global" ] + g0 -> ep2_e2 [fillcolor=gray] + ep2_e3 [ fillcolor="#ffffb3" label="[4] Constant" ] + ep2_e4 [ fillcolor="#ffffb3" label="[5] Constant" ] + ep2_e5 [ fillcolor="#ffffb3" label="[6] Constant" ] + ep2_e6 [ fillcolor="#ffffb3" label="[7] Constant" ] + ep2_e7 [ fillcolor="#bebada" label="[8] Compose" ] + { ep2_e3 ep2_e4 ep2_e5 ep2_e6 } -> ep2_e7 + ep2_s0 [ shape=square label="Root" ] + ep2_s1 [ shape=square label="Emit" ] + ep2_s2 [ shape=square label="Return" ] + ep2_s0 -> ep2_s1 [ arrowhead=tee label="" ] + ep2_s1 -> ep2_s2 [ arrowhead=tee label="" ] + ep2_e7 -> ep2_s2 [ label="value" ] + ep2_s1 -> ep2_e7 [ style=dotted ] + } } diff --git a/tests/out/glsl/quad.fs_extra.Fragment.glsl b/tests/out/glsl/quad.fs_extra.Fragment.glsl new file mode 100644 index 000000000..2556b28d8 --- /dev/null +++ b/tests/out/glsl/quad.fs_extra.Fragment.glsl @@ -0,0 +1,16 @@ +#version 310 es + +precision highp float; + +struct VertexOutput { + vec2 uv; + vec4 position; +}; + +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + _fs2p_location0 = vec4(0.0, 0.5, 0.0, 0.5); + return; +} + diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index 6e616106d..b22a0ef38 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -32,3 +32,8 @@ float4 main1(FragmentInput_main fragmentinput_main) : SV_Target0 float4 premultiplied = (color.w * color); return premultiplied; } + +float4 fs_extra() : SV_Target0 +{ + return float4(0.0, 0.5, 0.0, 0.5); +} diff --git a/tests/out/hlsl/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config index bae3c1cc6..18bfb0bd5 100644 --- a/tests/out/hlsl/quad.hlsl.config +++ b/tests/out/hlsl/quad.hlsl.config @@ -2,3 +2,5 @@ vertex=vs_5_0 vertex_name=main fragment=ps_5_0 fragment_name=main1 +fragment=ps_5_0 +fragment_name=fs_extra diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl index af6e515f9..f0fa35dab 100644 --- a/tests/out/msl/quad.msl +++ b/tests/out/msl/quad.msl @@ -44,3 +44,12 @@ fragment main2Output main2( metal::float4 premultiplied = color.w * color; return main2Output { premultiplied }; } + + +struct fs_extraOutput { + metal::float4 member2 [[color(0)]]; +}; +fragment fs_extraOutput fs_extra( +) { + return fs_extraOutput { metal::float4(0.0, 0.5, 0.0, 0.5) }; +} diff --git a/tests/out/spv/quad.spvasm b/tests/out/spv/quad.spvasm index 02c31384b..51b6b61e4 100644 --- a/tests/out/spv/quad.spvasm +++ b/tests/out/spv/quad.spvasm @@ -1,105 +1,119 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 58 +; Bound: 64 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %26 "main" %17 %20 %22 %24 -OpEntryPoint Fragment %44 "main" %41 %43 -OpExecutionMode %44 OriginUpperLeft +OpEntryPoint Vertex %27 "main" %18 %21 %23 %25 +OpEntryPoint Fragment %45 "main" %42 %44 +OpEntryPoint Fragment %61 "fs_extra" %60 +OpExecutionMode %45 OriginUpperLeft +OpExecutionMode %61 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" -OpName %9 "VertexOutput" -OpMemberName %9 0 "uv" -OpMemberName %9 1 "position" -OpName %12 "u_texture" -OpName %14 "u_sampler" -OpName %17 "pos" -OpName %20 "uv" -OpName %22 "uv" -OpName %24 "position" -OpName %26 "main" -OpName %41 "uv" -OpName %44 "main" -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 16 -OpDecorate %12 DescriptorSet 0 -OpDecorate %12 Binding 0 -OpDecorate %14 DescriptorSet 0 -OpDecorate %14 Binding 1 -OpDecorate %17 Location 0 -OpDecorate %20 Location 1 -OpDecorate %22 Location 0 -OpDecorate %24 BuiltIn Position -OpDecorate %41 Location 0 -OpDecorate %43 Location 0 +OpName %10 "VertexOutput" +OpMemberName %10 0 "uv" +OpMemberName %10 1 "position" +OpName %13 "u_texture" +OpName %15 "u_sampler" +OpName %18 "pos" +OpName %21 "uv" +OpName %23 "uv" +OpName %25 "position" +OpName %27 "main" +OpName %42 "uv" +OpName %45 "main" +OpName %61 "fs_extra" +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 16 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 0 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 1 +OpDecorate %18 Location 0 +OpDecorate %21 Location 1 +OpDecorate %23 Location 0 +OpDecorate %25 BuiltIn Position +OpDecorate %42 Location 0 +OpDecorate %44 Location 0 +OpDecorate %60 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.2 %5 = OpConstant %4 0.0 %6 = OpConstant %4 1.0 -%7 = OpTypeVector %4 2 -%8 = OpTypeVector %4 4 -%9 = OpTypeStruct %7 %8 -%10 = OpTypeImage %4 2D 0 0 0 1 Unknown -%11 = OpTypeSampler -%13 = OpTypePointer UniformConstant %10 -%12 = OpVariable %13 UniformConstant -%15 = OpTypePointer UniformConstant %11 -%14 = OpVariable %15 UniformConstant -%18 = OpTypePointer Input %7 -%17 = OpVariable %18 Input -%20 = OpVariable %18 Input -%23 = OpTypePointer Output %7 -%22 = OpVariable %23 Output -%25 = OpTypePointer Output %8 -%24 = OpVariable %25 Output -%27 = OpTypeFunction %2 -%35 = OpTypePointer Output %4 -%37 = OpTypeInt 32 0 -%36 = OpConstant %37 1 -%41 = OpVariable %18 Input -%43 = OpVariable %25 Output -%48 = OpTypeSampledImage %10 -%52 = OpTypeBool -%26 = OpFunction %2 None %27 -%16 = OpLabel -%19 = OpLoad %7 %17 -%21 = OpLoad %7 %20 -OpBranch %28 -%28 = OpLabel -%29 = OpVectorTimesScalar %7 %19 %3 -%30 = OpCompositeConstruct %8 %29 %5 %6 -%31 = OpCompositeConstruct %9 %21 %30 -%32 = OpCompositeExtract %7 %31 0 -OpStore %22 %32 -%33 = OpCompositeExtract %8 %31 1 -OpStore %24 %33 -%34 = OpAccessChain %35 %24 %36 -%38 = OpLoad %4 %34 -%39 = OpFNegate %4 %38 -OpStore %34 %39 +%7 = OpConstant %4 0.5 +%8 = OpTypeVector %4 2 +%9 = OpTypeVector %4 4 +%10 = OpTypeStruct %8 %9 +%11 = OpTypeImage %4 2D 0 0 0 1 Unknown +%12 = OpTypeSampler +%14 = OpTypePointer UniformConstant %11 +%13 = OpVariable %14 UniformConstant +%16 = OpTypePointer UniformConstant %12 +%15 = OpVariable %16 UniformConstant +%19 = OpTypePointer Input %8 +%18 = OpVariable %19 Input +%21 = OpVariable %19 Input +%24 = OpTypePointer Output %8 +%23 = OpVariable %24 Output +%26 = OpTypePointer Output %9 +%25 = OpVariable %26 Output +%28 = OpTypeFunction %2 +%36 = OpTypePointer Output %4 +%38 = OpTypeInt 32 0 +%37 = OpConstant %38 1 +%42 = OpVariable %19 Input +%44 = OpVariable %26 Output +%49 = OpTypeSampledImage %11 +%53 = OpTypeBool +%60 = OpVariable %26 Output +%27 = OpFunction %2 None %28 +%17 = OpLabel +%20 = OpLoad %8 %18 +%22 = OpLoad %8 %21 +OpBranch %29 +%29 = OpLabel +%30 = OpVectorTimesScalar %8 %20 %3 +%31 = OpCompositeConstruct %9 %30 %5 %6 +%32 = OpCompositeConstruct %10 %22 %31 +%33 = OpCompositeExtract %8 %32 0 +OpStore %23 %33 +%34 = OpCompositeExtract %9 %32 1 +OpStore %25 %34 +%35 = OpAccessChain %36 %25 %37 +%39 = OpLoad %4 %35 +%40 = OpFNegate %4 %39 +OpStore %35 %40 OpReturn OpFunctionEnd -%44 = OpFunction %2 None %27 -%40 = OpLabel -%42 = OpLoad %7 %41 -%45 = OpLoad %10 %12 -%46 = OpLoad %11 %14 -OpBranch %47 -%47 = OpLabel -%49 = OpSampledImage %48 %45 %46 -%50 = OpImageSampleImplicitLod %8 %49 %42 -%51 = OpCompositeExtract %4 %50 3 -%53 = OpFOrdEqual %52 %51 %5 -OpSelectionMerge %54 None -OpBranchConditional %53 %55 %54 -%55 = OpLabel +%45 = OpFunction %2 None %28 +%41 = OpLabel +%43 = OpLoad %8 %42 +%46 = OpLoad %11 %13 +%47 = OpLoad %12 %15 +OpBranch %48 +%48 = OpLabel +%50 = OpSampledImage %49 %46 %47 +%51 = OpImageSampleImplicitLod %9 %50 %43 +%52 = OpCompositeExtract %4 %51 3 +%54 = OpFOrdEqual %53 %52 %5 +OpSelectionMerge %55 None +OpBranchConditional %54 %56 %55 +%56 = OpLabel OpKill -%54 = OpLabel -%56 = OpCompositeExtract %4 %50 3 -%57 = OpVectorTimesScalar %8 %50 %56 -OpStore %43 %57 +%55 = OpLabel +%57 = OpCompositeExtract %4 %51 3 +%58 = OpVectorTimesScalar %9 %51 %57 +OpStore %44 %58 +OpReturn +OpFunctionEnd +%61 = OpFunction %2 None %28 +%59 = OpLabel +OpBranch %62 +%62 = OpLabel +%63 = OpCompositeConstruct %9 %5 %7 %5 %7 +OpStore %60 %63 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index e6890b1d8..5c14f1ee4 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -24,3 +24,8 @@ fn main1([[location(0), interpolate(perspective)]] uv1: vec2) -> [[location let premultiplied: vec4 = (color.w * color); return premultiplied; } + +[[stage(fragment)]] +fn fs_extra() -> [[location(0)]] vec4 { + return vec4(0.0, 0.5, 0.0, 0.5); +} From 1f42d4f2271adfa6a99427fde84cd2b13dbaa215 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 24 Jun 2021 21:20:00 +0000 Subject: [PATCH 1036/2212] Fix CI validation tasks --- .github/workflows/validation-linux.yml | 8 ++++---- .github/workflows/validation-macos.yml | 2 +- .github/workflows/validation-windows.yml | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/validation-linux.yml b/.github/workflows/validation-linux.yml index 997b80783..9bc653d39 100644 --- a/.github/workflows/validation-linux.yml +++ b/.github/workflows/validation-linux.yml @@ -2,10 +2,10 @@ name: validation-linux on: pull_request: paths: - - 'tests/out/*.spvasm' - - 'tests/out/*.glsl' - - 'tests/out/*.dot' - - 'tests/out/*.wgsl' + - 'tests/out/spv/*.spvasm' + - 'tests/out/glsl/*.glsl' + - 'tests/out/dot/*.dot' + - 'tests/out/wgsl/*.wgsl' jobs: validate-linux: diff --git a/.github/workflows/validation-macos.yml b/.github/workflows/validation-macos.yml index 89a3b13f5..300d77803 100644 --- a/.github/workflows/validation-macos.yml +++ b/.github/workflows/validation-macos.yml @@ -2,7 +2,7 @@ name: validation-macos on: pull_request: paths: - - 'tests/out/*.msl' + - 'tests/out/msl/*.msl' jobs: validate-macos: diff --git a/.github/workflows/validation-windows.yml b/.github/workflows/validation-windows.yml index 95ff1c06b..c9bd5ae1f 100644 --- a/.github/workflows/validation-windows.yml +++ b/.github/workflows/validation-windows.yml @@ -2,7 +2,7 @@ name: validation-windows on: pull_request: paths: - - 'tests/out/*.hlsl' + - 'tests/out/hlsl/*.hlsl' jobs: validate-windows: @@ -13,4 +13,4 @@ jobs: - name: Add DirectXShaderCompiler uses: napokue/setup-dxc@v1.0.0 - run: make validate-hlsl - shell: sh \ No newline at end of file + shell: sh From f0d41c3fd64098cefece52ece783d1fcef6ab720 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 25 Jun 2021 11:44:32 -0700 Subject: [PATCH 1037/2212] [spv-out] Track block termination statically. Rather than giving `Block` an optional `terminator` field in addition to its `body`, track block termination statically, with two types: - `Block` is a block without a termination instruction. This is what most code generation functions operate on. - `TerminatedBlock` is a block with a termination instruction. This is what `Function::blocks` holds. The `Function::consume` method takes a `Block` by value, together with a termination instruction, and turns it into a `TerminatedBlock`. This lets us remove some unwraps and awkward conditions. As part of this change, `Writer::write_block` no longer hits an `unimplemented!` for Naga statements following `Break`, `Return`, and so on. Instead, it simply doesn't emit code for them, which is a correct translation. If we want to forbid these, we should handle that in validation instead. --- src/back/spv/mod.rs | 28 +++++++++++++++++---- src/back/spv/writer.rs | 55 +++++++++++++++++++++-------------------- src/back/wgsl/writer.rs | 2 +- 3 files changed, 52 insertions(+), 33 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index f1522a5c4..0c3db44b2 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -72,10 +72,26 @@ impl IdGenerator { } } +/// A SPIR-V block to which we are still adding instructions. +/// +/// A `Block` represents a SPIR-V block that does not yet have a termination +/// instruction like `OpBranch` or `OpReturn`. +/// +/// The `OpLabel` that starts the block is implicit. It will be emitted based on +/// `label_id` when we write the block to a `LogicalLayout`. +/// +/// To terminate a `Block`, pass the block and the termination instruction to +/// `Function::consume`. This takes ownership of the `Block` and transforms it +/// into a `TerminatedBlock`. struct Block { label_id: Word, body: Vec, - termination: Option, +} + +/// A SPIR-V block that ends with a termination instruction. +struct TerminatedBlock { + label_id: Word, + body: Vec, } impl Block { @@ -83,7 +99,6 @@ impl Block { Block { label_id, body: Vec::new(), - termination: None, } } } @@ -109,14 +124,17 @@ struct Function { signature: Option, parameters: Vec, variables: crate::FastHashMap, LocalVariable>, - blocks: Vec, + blocks: Vec, entry_point_context: Option, } impl Function { fn consume(&mut self, mut block: Block, termination: Instruction) { - block.termination = Some(termination); - self.blocks.push(block); + block.body.push(termination); + self.blocks.push(TerminatedBlock { + label_id: block.label_id, + body: block.body, + }) } fn parameter_id(&self, index: u32) -> Word { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 223960b0e..09f8fff8e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -47,7 +47,6 @@ impl Function { for instruction in block.body.iter() { instruction.to_words(sink); } - block.termination.as_ref().unwrap().to_words(sink); } } } @@ -2369,9 +2368,6 @@ impl Writer { let mut block = Block::new(label_id); for statement in statements { - if block.termination.is_some() { - unimplemented!("No statements are expected after block termination"); - } match *statement { crate::Statement::Emit(ref range) => { for handle in range.clone() { @@ -2576,11 +2572,15 @@ impl Writer { block = Block::new(merge_id); } crate::Statement::Break => { - block.termination = Some(Instruction::branch(loop_context.break_id.unwrap())); + function.consume(block, Instruction::branch(loop_context.break_id.unwrap())); + return Ok(()); } crate::Statement::Continue => { - block.termination = - Some(Instruction::branch(loop_context.continuing_id.unwrap())); + function.consume( + block, + Instruction::branch(loop_context.continuing_id.unwrap()), + ); + return Ok(()); } crate::Statement::Return { value: Some(value) } => { let value_id = self.cached[value]; @@ -2598,13 +2598,16 @@ impl Writer { } None => Instruction::return_value(value_id), }; - block.termination = Some(instruction); + function.consume(block, instruction); + return Ok(()); } crate::Statement::Return { value: None } => { - block.termination = Some(Instruction::return_void()); + function.consume(block, Instruction::return_void()); + return Ok(()); } crate::Statement::Kill => { - block.termination = Some(Instruction::kill()); + function.consume(block, Instruction::kill()); + return Ok(()); } crate::Statement::Barrier(flags) => { let memory_scope = if flags.contains(crate::Barrier::STORAGE) { @@ -2734,24 +2737,22 @@ impl Writer { } } - if block.termination.is_none() { - block.termination = Some(match exit_id { - Some(id) => Instruction::branch(id), - // This can happen if the last branch had all the paths - // leading out of the graph (i.e. returning). - // Or it may be the end of the function. - None => match ir_function.result { - Some(ref result) if function.entry_point_context.is_none() => { - let type_id = self.get_type_id(LookupType::Handle(result.ty))?; - let null_id = self.write_constant_null(type_id); - Instruction::return_value(null_id) - } - _ => Instruction::return_void(), - }, - }); - } + let termination = match exit_id { + Some(id) => Instruction::branch(id), + // This can happen if the last branch had all the paths + // leading out of the graph (i.e. returning). + // Or it may be the end of the function. + None => match ir_function.result { + Some(ref result) if function.entry_point_context.is_none() => { + let type_id = self.get_type_id(LookupType::Handle(result.ty))?; + let null_id = self.write_constant_null(type_id); + Instruction::return_value(null_id) + } + _ => Instruction::return_void(), + }, + }; - function.blocks.push(block); + function.consume(block, termination); Ok(()) } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 713bb3b8e..354acd191 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -528,7 +528,7 @@ impl Writer { if let Some(storage_class) = storage_class_str(class) { write!(self.out, "<{}>", storage_class)?; } - }, + } _ => { return Err(Error::Unimplemented(format!( "write_value_type {:?}", From c156fa9ad3fb454923d4e8fb0d4e66162d984bf3 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 24 Jun 2021 17:40:51 -0700 Subject: [PATCH 1038/2212] [spv-out] Properly reset `Writer`s between module writes. A single `Writer` can be reused to convert any number of Naga IR modules to SPIR-V. This lets us reuse the heap allocations, but makes us responsible for resetting the state of the `Writer` fully between modules. The old code neglected to clear several different fields: logical_layout (all fields), lookup_type, and cached_constants. This commit uses Rust struct literal expressions to construct the re-initialized `Writer`, which makes the compiler check that each field has been handled. It also introduces a policy limiting how much storage will be retained, so that processing the occasional whale doesn't leave us with leviathan buffers permanently. --- src/back/spv/layout.rs | 30 ++++++++++++++++ src/back/spv/mod.rs | 9 +++++ src/back/spv/recyclable.rs | 74 ++++++++++++++++++++++++++++++++++++++ src/back/spv/writer.rs | 63 +++++++++++++++++++++++++++----- 4 files changed, 168 insertions(+), 8 deletions(-) create mode 100644 src/back/spv/recyclable.rs diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index 5708157ba..492ec0f74 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -25,6 +25,18 @@ impl PhysicalLayout { } } +impl super::recyclable::Recyclable for PhysicalLayout { + fn recycle(self) -> Self { + PhysicalLayout { + magic_number: self.magic_number, + version: self.version, + generator: self.generator, + instruction_schema: self.instruction_schema, + bound: 0, + } + } +} + impl LogicalLayout { pub(super) fn in_words(&self, sink: &mut impl Extend) { sink.extend(self.capabilities.iter().cloned()); @@ -41,6 +53,24 @@ impl LogicalLayout { } } +impl super::recyclable::Recyclable for LogicalLayout { + fn recycle(self) -> Self { + Self { + capabilities: self.capabilities.recycle(), + extensions: self.extensions.recycle(), + ext_inst_imports: self.ext_inst_imports.recycle(), + memory_model: self.memory_model.recycle(), + entry_points: self.entry_points.recycle(), + execution_modes: self.execution_modes.recycle(), + debugs: self.debugs.recycle(), + annotations: self.annotations.recycle(), + declarations: self.declarations.recycle(), + function_declarations: self.function_declarations.recycle(), + function_definitions: self.function_definitions.recycle(), + } + } +} + impl Instruction { pub(super) fn new(op: Op) -> Self { Instruction { diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 0c3db44b2..8445b22a8 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -5,6 +5,7 @@ mod helpers; mod index; mod instructions; mod layout; +mod recyclable; mod writer; pub use spirv::Capability; @@ -15,6 +16,7 @@ use spirv::Word; use std::ops; use thiserror::Error; +#[derive(Clone)] struct PhysicalLayout { magic_number: Word, version: Word, @@ -239,6 +241,13 @@ impl ops::IndexMut> for CachedExpressions { id } } +impl recyclable::Recyclable for CachedExpressions { + fn recycle(self) -> Self { + CachedExpressions { + ids: self.ids.recycle(), + } + } +} struct GlobalVariable { /// Actual ID of the variable. diff --git a/src/back/spv/recyclable.rs b/src/back/spv/recyclable.rs new file mode 100644 index 000000000..54ac91215 --- /dev/null +++ b/src/back/spv/recyclable.rs @@ -0,0 +1,74 @@ +//! Reusing collections' previous allocations. + +/// A value that can be reset to its initial state, retaining its current allocations. +/// +/// Naga attempts to lower the cost of SPIR-V generation by allowing clients to +/// reuse the same `Writer` for multiple Module translations. Reusing a `Writer` +/// means that the `Vec`s, `HashMap`s, and other heap-allocated structures the +/// `Writer` uses internally begin the translation with heap-allocated buffers +/// ready to use. +/// +/// But this approach introduces the risk of `Writer` state leaking from one +/// module to the next. When a developer adds fields to `Writer` or its internal +/// types, they must remember to reset their contents between modules. +/// +/// One trick to ensure that every field has been accounted for is to use Rust's +/// struct literal syntax to construct a new, reset value. If a developer adds a +/// field, but neglects to update the reset code, the compiler will complain +/// that a field is missing from the literal. This trait's `recycle` method +/// takes `self` by value, and returns `Self` by value, encouraging the use of +/// struct literal expressions in its implementation. +pub trait Recyclable { + /// Clear `self`, retaining its current memory allocations. + /// + /// Shrink the buffer if it's currently much larger than was actually used. + /// This prevents a module with exceptionally large allocations from causing + /// the `Writer` to retain more memory than it needs indefinitely. + fn recycle(self) -> Self; +} + +// Stock values for various collections. + +/// Maximum extra capacity that a recycled vector is allowed to have. If the +/// actual capacity is larger, we re-allocate the vector storage with lower +/// capacity. +const MAX_EXTRA_CAPACITY_PERCENT: usize = 200; + +/// Minimum extra capacity to keep when re-allocating the vector storage. +const MIN_EXTRA_CAPACITY_PERCENT: usize = 20; + +/// Minimum sensible length to consider for re-allocation. +const MIN_LENGTH: usize = 16; + +impl Recyclable for Vec { + fn recycle(mut self) -> Self { + let extra_capacity = (self.capacity() - self.len()) * 100 / self.len().max(MIN_LENGTH); + + if extra_capacity > MAX_EXTRA_CAPACITY_PERCENT { + //TODO: use `shrink_to` when it's stable + self = Vec::with_capacity(self.len() + self.len() * MIN_EXTRA_CAPACITY_PERCENT / 100); + } else { + self.clear(); + } + + self + } +} + +impl Recyclable for std::collections::HashMap { + fn recycle(mut self) -> Self { + let extra_capacity = (self.capacity() - self.len()) * 100 / self.len().max(MIN_LENGTH); + + if extra_capacity > MAX_EXTRA_CAPACITY_PERCENT { + //TODO: use `shrink_to` when it's stable + self = Self::with_capacity_and_hasher( + self.len() + self.len() * MIN_EXTRA_CAPACITY_PERCENT / 100, + self.hasher().clone(), + ); + } else { + self.clear(); + } + + self + } +} diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 09f8fff8e..5852da565 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -118,9 +118,6 @@ impl Writer { return Err(Error::UnsupportedVersion(major, minor)); } let raw_version = ((major as u32) << 16) | ((minor as u32) << 8); - let mut id_gen = IdGenerator::default(); - let gl450_ext_inst_id = id_gen.next(); - let void_type = id_gen.next(); let (capabilities, forbidden_caps) = match options.capabilities { Some(ref caps) => (caps.clone(), None), @@ -132,6 +129,10 @@ impl Writer { } }; + let mut id_gen = IdGenerator::default(); + let gl450_ext_inst_id = id_gen.next(); + let void_type = id_gen.next(); + Ok(Writer { physical_layout: PhysicalLayout::new(raw_version), logical_layout: LogicalLayout::default(), @@ -156,6 +157,56 @@ impl Writer { }) } + /// Reset `Writer` to its initial state, retaining any allocations. + /// + /// Why not just implement `Recyclable` for `Writer`? By design, + /// `Recyclable::recycle` requires ownership of the value, not just + /// `&mut`; see the trait documentation. But we need to use this method + /// from functions like `Writer::write`, which only have `&mut Writer`. + /// Workarounds include unsafe code (`std::ptr::read`, then `write`, ugh) + /// or something like a `Default` impl that returns an oddly-initialized + /// `Writer`, which is worse. + fn reset(&mut self) { + use super::recyclable::Recyclable; + use std::mem::take; + + let mut id_gen = IdGenerator::default(); + let gl450_ext_inst_id = id_gen.next(); + let void_type = id_gen.next(); + + // Every field of the old writer that is not determined by the `Options` + // passed to `Writer::new` should be reset somehow. + let fresh = Writer { + // Copied from the old Writer: + flags: self.flags, + index_bounds_check_policy: self.index_bounds_check_policy, + capabilities: take(&mut self.capabilities), + forbidden_caps: take(&mut self.forbidden_caps), + + // Initialized afresh: + id_gen, + void_type, + gl450_ext_inst_id, + + // Recycled: + physical_layout: self.physical_layout.clone().recycle(), + logical_layout: take(&mut self.logical_layout).recycle(), + debugs: take(&mut self.debugs).recycle(), + annotations: take(&mut self.annotations).recycle(), + lookup_type: take(&mut self.lookup_type).recycle(), + lookup_function: take(&mut self.lookup_function).recycle(), + lookup_function_type: take(&mut self.lookup_function_type).recycle(), + lookup_function_call: take(&mut self.lookup_function_call).recycle(), + constant_ids: take(&mut self.constant_ids).recycle(), + cached_constants: take(&mut self.cached_constants).recycle(), + global_variables: take(&mut self.global_variables).recycle(), + cached: take(&mut self.cached).recycle(), + temp_list: take(&mut self.temp_list).recycle(), + }; + + *self = fresh; + } + fn check(&mut self, capabilities: &[spirv::Capability]) -> Result<(), Error> { if capabilities.is_empty() || capabilities @@ -2783,7 +2834,6 @@ impl Writer { .push(Instruction::source(spirv::SourceLanguage::GLSL, 450)); } - self.constant_ids.clear(); self.constant_ids.resize(ir_module.constants.len(), 0); // first, output all the scalar constants for (handle, constant) in ir_module.constants.iter() { @@ -2826,7 +2876,6 @@ impl Writer { debug_assert_eq!(self.constant_ids.iter().position(|&id| id == 0), None); // now write all globals - self.global_variables.clear(); for (_, var) in ir_module.global_variables.iter() { let (instruction, id) = self.write_global_variable(ir_module, var)?; instruction.to_words(&mut self.logical_layout.declarations); @@ -2884,9 +2933,7 @@ impl Writer { info: &ModuleInfo, words: &mut Vec, ) -> Result<(), Error> { - self.lookup_function.clear(); - self.lookup_function_type.clear(); - self.lookup_function_call.clear(); + self.reset(); self.write_logical_layout(ir_module, info)?; self.write_physical_layout(); From 24b2c548bd7854e09c33340973261965d41786ee Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 24 Jun 2021 23:49:40 +0300 Subject: [PATCH 1039/2212] [hlsl-out] Add note about entry points in ReflectionInfo --- src/back/hlsl/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 0631952c6..84802a4bd 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -48,8 +48,12 @@ impl Default for Options { } } +/// Structure that contains a reflection info pub struct ReflectionInfo { /// Information about all entry points (stage, name). + /// HLSL backend returns information about all entry points in shaders that will be allowed by the `hlsl` compiler. + /// For example: + /// the entry point with the name `line` is valid for `wgsl`, but not valid for `hlsl`, because `line` is a reserved keyword. pub entry_points: Vec<(crate::ShaderStage, String)>, // TODO: locations } From 19de60f6e41c6f36af20220f5d6a0c06e234e438 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 24 Jun 2021 23:52:37 +0300 Subject: [PATCH 1040/2212] [hlsl-out] Implement more expressions --- src/back/hlsl/writer.rs | 135 ++++++++++++++++++++++++++++++++++++++- tests/out/hlsl/quad.hlsl | 4 +- 2 files changed, 135 insertions(+), 4 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 4c27dccfa..293e49aa6 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -847,6 +847,17 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } } + Expression::Binary { + op: crate::BinaryOperator::Multiply, + left, + right, + } => { + write!(self.out, "mul(")?; + self.write_expr(module, left, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, right, func_ctx)?; + write!(self.out, ")")?; + } // TODO: copy-paste from wgsl-out Expression::Binary { op, left, right } => { write!(self.out, "(")?; @@ -933,12 +944,17 @@ impl<'a, W: Write> Writer<'a, W> { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; } - Expression::Load { pointer } => self.write_expr(module, pointer, func_ctx)?, + Expression::LocalVariable(handle) => { + write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])? + } + Expression::Load { pointer } => { + self.write_expr(module, pointer, func_ctx)?; + } Expression::Access { base, index } => { self.write_expr(module, base, func_ctx)?; write!(self.out, "[")?; self.write_expr(module, index, func_ctx)?; - write!(self.out, "]")? + write!(self.out, "]")?; } Expression::Unary { op, expr } => { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators @@ -966,6 +982,121 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } + Expression::As { expr, kind, .. } => { + let inner = func_ctx.info[expr].ty.inner_with(&module.types); + match *inner { + TypeInner::Vector { size, width, .. } => { + write!( + self.out, + "{}{}", + scalar_kind_str(kind, width)?, + back::vector_size_str(size), + )?; + } + TypeInner::Scalar { width, .. } => { + write!(self.out, "{}", scalar_kind_str(kind, width)?)? + } + _ => { + return Err(Error::Unimplemented(format!( + "write_expr expression::as {:?}", + inner + ))); + } + }; + write!(self.out, "(")?; + self.write_expr(module, expr, func_ctx)?; + write!(self.out, ")")?; + } + Expression::Math { + fun, + arg, + arg1, + arg2, + } => { + use crate::MathFunction as Mf; + + let fun_name = match fun { + // comparison + Mf::Abs => "abs", + Mf::Min => "min", + Mf::Max => "max", + Mf::Clamp => "clamp", + // trigonometry + Mf::Cos => "cos", + Mf::Cosh => "cosh", + Mf::Sin => "sin", + Mf::Sinh => "sinh", + Mf::Tan => "tan", + Mf::Tanh => "tanh", + Mf::Acos => "acos", + Mf::Asin => "asin", + Mf::Atan => "atan", + Mf::Atan2 => "atan2", + // decomposition + Mf::Ceil => "ceil", + Mf::Floor => "floor", + Mf::Round => "round", + Mf::Fract => "frac", + Mf::Trunc => "trunc", + Mf::Modf => "modf", + Mf::Frexp => "frexp", + Mf::Ldexp => "ldexp", + // exponent + Mf::Exp => "exp", + Mf::Exp2 => "exp2", + Mf::Log => "log", + Mf::Log2 => "log2", + Mf::Pow => "pow", + // geometry + Mf::Dot => "dot", + //Mf::Outer => , + Mf::Cross => "cross", + Mf::Distance => "distance", + Mf::Length => "length", + Mf::Normalize => "normalize", + Mf::FaceForward => "faceforward", + Mf::Reflect => "reflect", + Mf::Refract => "refract", + // computational + Mf::Sign => "sign", + Mf::Fma => "fma", + Mf::Mix => "lerp", + Mf::Step => "step", + Mf::SmoothStep => "smoothstep", + Mf::Sqrt => "sqrt", + Mf::InverseSqrt => "rsqrt", + //Mf::Inverse =>, + Mf::Transpose => "transpose", + Mf::Determinant => "determinant", + // bits + Mf::CountOneBits => "countbits", + Mf::ReverseBits => "reversebits", + _ => return Err(Error::Unimplemented(format!("write_expr_math {:?}", fun))), + }; + + write!(self.out, "{}(", fun_name)?; + self.write_expr(module, arg, func_ctx)?; + if let Some(arg) = arg1 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } + if let Some(arg) = arg2 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } + write!(self.out, ")")? + } + Expression::Swizzle { + size, + vector, + pattern, + } => { + self.write_expr(module, vector, func_ctx)?; + write!(self.out, ".")?; + for &sc in pattern[..size as usize].iter() { + self.out.write_char(back::COMPONENTS[sc as usize])?; + } + } _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index b22a0ef38..eb619b7d0 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -19,7 +19,7 @@ struct FragmentInput_main { VertexOutput main(VertexInput_main vertexinput_main) { - const VertexOutput vertexoutput1 = { vertexinput_main.uv2, float4((c_scale * vertexinput_main.pos1), 0.0, 1.0) }; + const VertexOutput vertexoutput1 = { vertexinput_main.uv2, float4(mul(c_scale, vertexinput_main.pos1), 0.0, 1.0) }; return vertexoutput1; } @@ -29,7 +29,7 @@ float4 main1(FragmentInput_main fragmentinput_main) : SV_Target0 if ((color.w == 0.0)) { discard; } - float4 premultiplied = (color.w * color); + float4 premultiplied = mul(color.w, color); return premultiplied; } From 57b325602015ce6445749a4d8ee5d491edc818d7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 27 Jun 2021 00:26:12 -0400 Subject: [PATCH 1041/2212] [glsl-out] binding location mapping --- cli/src/main.rs | 30 ++++--- src/back/glsl/features.rs | 2 +- src/back/glsl/mod.rs | 89 ++++++++++++++++----- src/back/msl/mod.rs | 70 ++++++++-------- src/lib.rs | 2 +- tests/in/access.param.ron | 6 +- tests/in/boids.param.ron | 10 +-- tests/in/interpolate.param.ron | 6 +- tests/in/skybox.param.ron | 26 ++++-- tests/out/glsl/skybox.fs_main.Fragment.glsl | 4 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 4 +- tests/snapshots.rs | 28 +++++-- 12 files changed, 182 insertions(+), 95 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 0a2c22b89..0415ddc4f 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -7,6 +7,7 @@ use std::{env, error::Error, path::Path}; struct Parameters { validation_flags: naga::valid::ValidationFlags, index_bounds_check_policy: naga::back::IndexBoundsCheckPolicy, + entry_point: Option, spv_adjust_coordinate_space: bool, spv_flow_dump_prefix: Option, spv: naga::back::spv::Options, @@ -89,7 +90,7 @@ fn main() { }; } "flow-dir" => params.spv_flow_dump_prefix = args.next(), - "entry-point" => params.glsl.entry_point = args.next().unwrap(), + "entry-point" => params.entry_point = Some(args.next().unwrap()), "profile" => { use naga::back::glsl::Version; let string = args.next().unwrap(); @@ -282,17 +283,28 @@ fn main() { stage @ "vert" | stage @ "frag" | stage @ "comp" => { use naga::back::glsl; - params.glsl.shader_stage = match stage { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - _ => unreachable!(), + let pipeline_options = glsl::PipelineOptions { + entry_point: match params.entry_point { + Some(ref name) => name.clone(), + None => "main".to_string(), + }, + shader_stage: match stage { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + _ => unreachable!(), + }, }; let mut buffer = String::new(); - let mut writer = - glsl::Writer::new(&mut buffer, &module, info.as_ref().unwrap(), ¶ms.glsl) - .unwrap_pretty(); + let mut writer = glsl::Writer::new( + &mut buffer, + &module, + info.as_ref().unwrap(), + ¶ms.glsl, + &pipeline_options, + ) + .unwrap_pretty(); writer.write().unwrap(); fs::write(output_path, buffer).unwrap(); } diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 957b02347..118840dc2 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -217,7 +217,7 @@ impl<'a, W> Writer<'a, W> { self.varying_required_features(result.binding.as_ref(), result.ty); } - if let ShaderStage::Compute = self.options.shader_stage { + if let ShaderStage::Compute = self.entry_point.stage { self.features.request(Features::COMPUTE_SHADER) } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index f45c93a49..9391c7ffe 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -66,8 +66,12 @@ pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450] /// List of supported es glsl versions pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; +pub type BindingMap = std::collections::BTreeMap; + /// glsl version #[derive(Debug, Copy, Clone, PartialEq)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum Version { /// `core` glsl Desktop(u16), @@ -124,9 +128,29 @@ impl fmt::Display for Version { /// Structure that contains the configuration used in the [`Writer`](Writer) #[derive(Debug, Clone)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Options { /// The glsl version to be used pub version: Version, + /// Map of resources association to binding locations. + pub binding_map: BindingMap, +} + +impl Default for Options { + fn default() -> Self { + Options { + version: Version::Embedded(310), + binding_map: BindingMap::default(), + } + } +} + +// A subset of options that are meant to be changed per pipeline. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct PipelineOptions { /// The stage of the entry point pub shader_stage: ShaderStage, /// The name of the entry point @@ -136,16 +160,6 @@ pub struct Options { pub entry_point: String, } -impl Default for Options { - fn default() -> Self { - Options { - version: Version::Embedded(320), - shader_stage: ShaderStage::Compute, - entry_point: "main".to_string(), - } - } -} - /// Structure that contains a reflection info pub struct ReflectionInfo { pub texture_mapping: crate::FastHashMap, @@ -297,6 +311,7 @@ impl<'a, W: Write> Writer<'a, W> { module: &'a crate::Module, info: &'a valid::ModuleInfo, options: &'a Options, + pipeline_options: &'a PipelineOptions, ) -> Result { // Check if the requested version is supported if !options.version.is_supported() { @@ -308,7 +323,9 @@ impl<'a, W: Write> Writer<'a, W> { let ep_idx = module .entry_points .iter() - .position(|ep| options.shader_stage == ep.stage && options.entry_point == ep.name) + .position(|ep| { + pipeline_options.shader_stage == ep.stage && pipeline_options.entry_point == ep.name + }) .ok_or(Error::EntryPointNotFound)?; // Generate a map with names required to write the module @@ -370,7 +387,7 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out)?; } - if self.options.shader_stage == ShaderStage::Compute { + if self.entry_point.stage == ShaderStage::Compute { let workgroup_size = self.entry_point.workgroup_size; writeln!( self.out, @@ -439,13 +456,36 @@ impl<'a, W: Write> Writer<'a, W> { arrayed, class, } => { - // Write the storage format if needed - if let TypeInner::Image { - class: crate::ImageClass::Storage(format), - .. - } = self.module.types[global.ty].inner - { - write!(self.out, "layout({}) ", glsl_storage_format(format))?; + // Gather the storage format if needed + let layout_storage_format = match self.module.types[global.ty].inner { + TypeInner::Image { + class: crate::ImageClass::Storage(format), + .. + } => Some(glsl_storage_format(format)), + _ => None, + }; + // Gether the location if needed + let layout_binding = if self.options.version.supports_explicit_locations() { + let br = global.binding.as_ref().unwrap(); + self.options.binding_map.get(br).cloned() + } else { + None + }; + + // Write all the layout qualifiers + if layout_binding.is_some() || layout_storage_format.is_some() { + write!(self.out, "layout(")?; + if let Some(binding) = layout_binding { + write!(self.out, "binding = {}", binding)?; + } + if let Some(format) = layout_storage_format { + let separator = match layout_binding { + Some(_) => ",", + None => "", + }; + write!(self.out, "{}{}", separator, format)?; + } + write!(self.out, ") ")?; } if let Some(storage_access) = glsl_storage_access(global.storage_access) { @@ -702,6 +742,15 @@ impl<'a, W: Write> Writer<'a, W> { handle: Handle, global: &crate::GlobalVariable, ) -> BackendResult { + if self.options.version.supports_explicit_locations() { + if let Some(ref br) = global.binding { + match self.options.binding_map.get(br) { + Some(binding) => write!(self.out, "layout(binding = {}) ", binding)?, + None => log::debug!("unassigned binding for {:?}", global.name), + } + } + } + if let Some(storage_access) = glsl_storage_access(global.storage_access) { write!(self.out, "{} ", storage_access)?; } @@ -782,7 +831,7 @@ impl<'a, W: Write> Writer<'a, W> { // // We ignore all interpolation and auxiliary modifiers that aren't used in fragment // shaders' input globals or vertex shaders' output globals. - let emit_interpolation_and_auxiliary = match self.options.shader_stage { + let emit_interpolation_and_auxiliary = match self.entry_point.stage { ShaderStage::Vertex => output, ShaderStage::Fragment => !output, _ => false, diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 738eb9c93..6a46bedaa 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -24,7 +24,10 @@ holding the result. !*/ use crate::{arena::Handle, valid::ModuleInfo}; -use std::fmt::{Error as FmtError, Write}; +use std::{ + fmt::{Error as FmtError, Write}, + ops, +}; mod keywords; pub mod sampler; @@ -57,21 +60,16 @@ pub struct BindTarget { pub mutable: bool, } -#[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] -#[cfg_attr(feature = "serialize", derive(serde::Serialize))] -#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] -pub struct BindSource { - pub stage: crate::ShaderStage, - pub group: u32, - pub binding: u32, -} +// Using `BTreeMap` instead of `HashMap` so that we can hash itself. +pub type BindingMap = std::collections::BTreeMap; -pub type BindingMap = std::collections::BTreeMap; - -#[derive(Clone, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[derive(Clone, Debug, Default, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct PerStageResources { + #[cfg_attr(feature = "deserialize", serde(default))] + pub resources: BindingMap, + #[cfg_attr(feature = "deserialize", serde(default))] pub push_constant_buffer: Option, @@ -82,7 +80,7 @@ pub struct PerStageResources { pub sizes_buffer: Option, } -#[derive(Clone, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[derive(Clone, Debug, Default, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct PerStageMap { @@ -94,6 +92,17 @@ pub struct PerStageMap { pub cs: PerStageResources, } +impl ops::Index for PerStageMap { + type Output = PerStageResources; + fn index(&self, stage: crate::ShaderStage) -> &PerStageResources { + match stage { + crate::ShaderStage::Vertex => &self.vs, + crate::ShaderStage::Fragment => &self.fs, + crate::ShaderStage::Compute => &self.cs, + } + } +} + enum ResolvedBinding { BuiltIn(crate::BuiltIn), Attribute(u32), @@ -146,11 +155,11 @@ pub enum Error { #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum EntryPointError { #[error("mapping of {0:?} is missing")] - MissingBinding(BindSource), - #[error("mapping for push constants at stage {0:?} is missing")] - MissingPushConstants(crate::ShaderStage), - #[error("mapping for sizes buffer for stage {0:?} is missing")] - MissingSizesBuffer(crate::ShaderStage), + MissingBinding(crate::ResourceBinding), + #[error("mapping for push constants is missing")] + MissingPushConstants, + #[error("mapping for sizes buffer is missing")] + MissingSizesBuffer, } #[derive(Clone, Copy, Debug)] @@ -167,9 +176,7 @@ enum LocationMode { pub struct Options { /// (Major, Minor) target version of the Metal Shading Language. pub lang_version: (u8, u8), - /// Binding model mapping to Metal. - pub binding_map: BindingMap, - /// Map of per-stage resources (e.g. push constants) to slots + /// Map of per-stage resources to slots. pub per_stage_map: PerStageMap, /// Samplers to be inlined into the code. pub inline_samplers: Vec, @@ -183,7 +190,6 @@ impl Default for Options { fn default() -> Self { Options { lang_version: (1, 0), - binding_map: BindingMap::default(), per_stage_map: PerStageMap::default(), inline_samplers: Vec::new(), spirv_cross_compatibility: false, @@ -257,19 +263,14 @@ impl Options { stage: crate::ShaderStage, res_binding: &crate::ResourceBinding, ) -> Result { - let source = BindSource { - stage, - group: res_binding.group, - binding: res_binding.binding, - }; - match self.binding_map.get(&source) { + match self.per_stage_map[stage].resources.get(&res_binding) { Some(target) => Ok(ResolvedBinding::Resource(target.clone())), None if self.fake_missing_bindings => Ok(ResolvedBinding::User { prefix: "fake", index: 0, interpolation: None, }), - None => Err(EntryPointError::MissingBinding(source)), + None => Err(EntryPointError::MissingBinding(res_binding.clone())), } } @@ -294,7 +295,7 @@ impl Options { index: 0, interpolation: None, }), - None => Err(EntryPointError::MissingPushConstants(stage)), + None => Err(EntryPointError::MissingPushConstants), } } @@ -302,12 +303,7 @@ impl Options { &self, stage: crate::ShaderStage, ) -> Result { - let slot = match stage { - crate::ShaderStage::Vertex => self.per_stage_map.vs.sizes_buffer, - crate::ShaderStage::Fragment => self.per_stage_map.fs.sizes_buffer, - crate::ShaderStage::Compute => self.per_stage_map.cs.sizes_buffer, - }; - + let slot = self.per_stage_map[stage].sizes_buffer; match slot { Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { buffer: Some(slot), @@ -320,7 +316,7 @@ impl Options { index: 0, interpolation: None, }), - None => Err(EntryPointError::MissingSizesBuffer(stage)), + None => Err(EntryPointError::MissingSizesBuffer), } } } diff --git a/src/lib.rs b/src/lib.rs index 361c08069..6b86d64e5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -625,7 +625,7 @@ pub enum Binding { } /// Pipeline binding information for global resources. -#[derive(Clone, Debug, Hash, PartialEq)] +#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct ResourceBinding { diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index f7084220b..675006b01 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -5,11 +5,11 @@ msl_custom: true, msl: ( lang_version: (2, 0), - binding_map: { - (stage: Vertex, group: 0, binding: 0): (buffer: Some(0), mutable: true), - }, per_stage_map: ( vs: ( + resources: { + (group: 0, binding: 0): (buffer: Some(0), mutable: true), + }, sizes_buffer: Some(24), ), ), diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index 25413d0c4..8f304e5c2 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -5,13 +5,13 @@ msl_custom: true, msl: ( lang_version: (2, 0), - binding_map: { - (stage: Compute, group: 0, binding: 0): (buffer: Some(0), mutable: false), - (stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true), - (stage: Compute, group: 0, binding: 2): (buffer: Some(2), mutable: true), - }, per_stage_map: ( cs: ( + resources: { + (group: 0, binding: 0): (buffer: Some(0), mutable: false), + (group: 0, binding: 1): (buffer: Some(1), mutable: true), + (group: 0, binding: 2): (buffer: Some(2), mutable: true), + }, sizes_buffer: Some(3), ) ), diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index f0c6a13d5..39fdcf20d 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -3,5 +3,9 @@ spv_capabilities: [ Shader, SampleRateShading ], spv_debug: true, spv_adjust_coordinate_space: true, - glsl_desktop_version: Some(400) + glsl: ( + version: Desktop(400), + binding_map: {}, + ), + glsl_custom: true, ) diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 9a5bf7d2b..9d0ad493d 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -6,12 +6,18 @@ msl_custom: true, msl: ( lang_version: (2, 1), - binding_map: { - (stage: Vertex, group: 0, binding: 0): (buffer: Some(0)), - (stage: Fragment, group: 0, binding: 1): (texture: Some(0)), - (stage: Fragment, group: 0, binding: 2): (sampler: Some(Inline(0))), - }, per_stage_map: ( + vs: ( + resources: { + (group: 0, binding: 0): (buffer: Some(0)), + }, + ), + fs: ( + resources: { + (group: 0, binding: 1): (texture: Some(0)), + (group: 0, binding: 2): (sampler: Some(Inline(0))), + }, + ), ), inline_samplers: [ ( @@ -28,5 +34,13 @@ ], spirv_cross_compatibility: false, fake_missing_bindings: false, - ) + ), + glsl_custom: true, + glsl: ( + version: Embedded(320), + binding_map: { + (group: 0, binding: 0): 0, + (group: 0, binding: 1): 0, + }, + ), ) diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index 1a8488c2a..c75b0abb0 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -1,4 +1,4 @@ -#version 310 es +#version 320 es precision highp float; @@ -7,7 +7,7 @@ struct VertexOutput { vec3 uv; }; -uniform highp samplerCube _group_0_binding_1; +layout(binding = 0) uniform highp samplerCube _group_0_binding_1; smooth in vec3 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index 1c81eb42a..c1b423fc6 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -1,4 +1,4 @@ -#version 310 es +#version 320 es precision highp float; @@ -7,7 +7,7 @@ struct VertexOutput { vec3 uv; }; -uniform Data_block_0 { +layout(binding = 0) uniform Data_block_0 { mat4x4 proj_inv; mat4x4 view; } _group_0_binding_0; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 7ea614461..bfcb897d0 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -49,9 +49,12 @@ struct Parameters { #[cfg(all(not(feature = "deserialize"), feature = "msl-out"))] #[serde(default)] msl_custom: bool, - #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] + #[cfg(all(feature = "deserialize", feature = "glsl-out"))] #[serde(default)] - glsl_desktop_version: Option, + glsl: naga::back::glsl::Options, + #[cfg(all(not(feature = "deserialize"), feature = "glsl-out"))] + #[serde(default)] + glsl_custom: bool, #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] #[serde(default)] glsl_vert_ep_name: Option, @@ -233,17 +236,26 @@ fn write_output_glsl( ) { use naga::back::glsl; - let options = glsl::Options { - version: match params.glsl_desktop_version { - Some(v) => glsl::Version::Desktop(v), - None => glsl::Version::Embedded(310), - }, + #[cfg_attr(feature = "deserialize", allow(unused_variables))] + let default_options = glsl::Options::default(); + #[cfg(feature = "deserialize")] + let options = ¶ms.glsl; + #[cfg(not(feature = "deserialize"))] + let options = if params.glsl_custom { + println!("Skipping {}", destination.display()); + return; + } else { + &default_options + }; + + let pipeline_options = glsl::PipelineOptions { shader_stage: stage, entry_point: ep_name.to_string(), }; let mut buffer = String::new(); - let mut writer = glsl::Writer::new(&mut buffer, module, info, &options).unwrap(); + let mut writer = + glsl::Writer::new(&mut buffer, module, info, &options, &pipeline_options).unwrap(); writer.write().unwrap(); fs::write( From 8729391e5363af33111fb646cb3d87b7e1d1650b Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Sat, 26 Jun 2021 10:46:23 -0700 Subject: [PATCH 1042/2212] [glsl-in] Fix function lookup First look for exact matches before trying the implicit lookup. Otherwise, finding two wrong matches first will result in an ambiguous function error. This logic could use with a bit of a cleanup, keeping track of a closer score and doing more exact matching on types, but this might be good enough for now. --- src/front/glsl/functions.rs | 14 ++++++++++---- src/front/glsl/parser_tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index bd9b443fa..36cf73985 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -507,6 +507,7 @@ impl Program<'_> { })?; let mut maybe_decl = None; + let mut ambiguous = false; 'outer: for decl in declarations { if args.len() != decl.parameters.len() { @@ -538,17 +539,22 @@ impl Program<'_> { if exact { maybe_decl = Some(decl); + ambiguous = false; break; } else if maybe_decl.is_some() { - return Err(ErrorKind::SemanticError( - meta, - format!("Ambiguous best function for '{}'", name).into(), - )); + ambiguous = true; } else { maybe_decl = Some(decl) } } + if ambiguous { + return Err(ErrorKind::SemanticError( + meta, + format!("Ambiguous best function for '{}'", name).into(), + )); + } + let decl = maybe_decl.ok_or_else(|| { ErrorKind::SemanticError( meta, diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 4b1b9ae32..f555ec2dc 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -463,6 +463,32 @@ fn constants() { assert!(constants.next().is_none()); } +#[test] +fn function_overloading() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Vertex); + + parse_program( + r#" + # version 450 + + float saturate(float v) { return clamp(v, 0.0, 1.0); } + vec2 saturate(vec2 v) { return clamp(v, vec2(0.0), vec2(1.0)); } + vec3 saturate(vec3 v) { return clamp(v, vec3(0.0), vec3(1.0)); } + vec4 saturate(vec4 v) { return clamp(v, vec4(0.0), vec4(1.0)); } + + void main() { + float v1 = saturate(1.5); + vec2 v2 = saturate(vec2(0.5, 1.5)); + vec3 v3 = saturate(vec3(0.5, 1.5, 2.5)); + vec3 v4 = saturate(vec4(0.5, 1.5, 2.5, 3.5)); + } + "#, + &entry_points, + ) + .unwrap(); +} + #[test] fn implicit_conversions() { let mut entry_points = crate::FastHashMap::default(); From dd791a26aefdf138e5024387eb960ca5fb1e5ae3 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Tue, 22 Jun 2021 13:39:47 -0700 Subject: [PATCH 1043/2212] glsl: Replace todo!() with a NotImplemented error So we can get a source location rather than a panic. --- src/front/glsl/error.rs | 5 +++-- src/front/glsl/parser.rs | 5 ++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 004439142..5d2c62681 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -58,8 +58,8 @@ pub enum ErrorKind { InvalidVersion(SourceMetadata, u64), #[error("Expected {}, found {0}", join_with_comma(.1))] InvalidToken(Token, Vec), - #[error("Not implemented {0}")] - NotImplemented(&'static str), + #[error("Not implemented: {1}")] + NotImplemented(SourceMetadata, &'static str), #[error("Unknown variable: {1}")] UnknownVariable(SourceMetadata, String), #[error("Unknown type: {1}")] @@ -82,6 +82,7 @@ impl ErrorKind { ErrorKind::UnknownVariable(metadata, _) | ErrorKind::InvalidProfile(metadata, _) | ErrorKind::InvalidVersion(metadata, _) + | ErrorKind::NotImplemented(metadata, _) | ErrorKind::UnknownLayoutQualifier(metadata, _) | ErrorKind::SemanticError(metadata, _) | ErrorKind::UnknownField(metadata, _) => Some(metadata), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index c68454b28..16a3f4a19 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -797,7 +797,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON - todo!() + Err(ErrorKind::NotImplemented( + token.meta, + "variable qualifier", + )) } } TokenValue::Semicolon => { From 06cfbbde4e68f375abf5c6ee1f654113c048952a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 19 May 2021 11:21:56 -0700 Subject: [PATCH 1044/2212] Flesh out the Naga module-level documentation. --- src/lib.rs | 146 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 100 insertions(+), 46 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 6b86d64e5..3705ea5cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,10 +2,10 @@ The central structure of the crate is [`Module`]. A `Module` contains: -- [`EntryPoint`]s, the main functions for pipeline stages like vertex shading or - fragment shading, +- [`Function`]s, which have arguments, a return type, local variables, and a body, -- [`Function`]s, representing functions used by `EntryPoint`s and other `Function`s, +- [`EntryPoint`]s, which are specialized functions that can serve as the entry + point for pipeline stages like vertex shading or fragment shading, - [`Constant`]s and [`GlobalVariable`]s used by `EntryPoint`s and `Function`s, and @@ -34,6 +34,8 @@ representing a series of statements executed in order. The body of an `EntryPoint`s or `Function` is a `Block`, and `Statement` has a [`Block`][Statement::Block] variant. +## Arenas + To improve translator performance and reduce memory usage, most structures are stored in an [`Arena`]. An `Arena` stores a series of `T` values, indexed by [`Handle`](Handle) values, which are just wrappers around integer indexes. @@ -44,65 +46,87 @@ element of an `Arena` has an index of 1, not 0.) ## Function Calls -The Naga IR's representation of function calls is unusual. Most languages treat +Naga's representation of function calls is unusual. Most languages treat function calls as expressions, but because calls may have side effects, Naga -represents them with [`Statement::Call`]. A call statement may designate a -particular `Expression` to represent its return value, if any, which can be used -by subsequent statements and their expressions. +represents them as a kind of statement, [`Statement::Call`]. If the function +returns a value, a call statement designates a particular [`Expression::Call`] +expression to represent its return value, for use by subsequent statements and +expressions. ## `Expression` evaluation time and scope -While the order of execution of [`Statement`]s is apparent from their structure, -it is not so obvious exactly when a given [`Expression`] should be evaluated, -since many `Statement`s and `Expression`s may refer to its value. But it is -essential to clearly specify an expression's evaluation time, since that -determines which statements' effects the expression should observe. It is also -helpful to backends to limit the visibility of an `Expression`'s value to a -portion of the statement tree. +It is essential to know when an [`Expression`] should be evaluated, because its +value may depend on previous [`Statement`]s' effects. But whereas the order of +execution for a tree of `Statement`s is apparent from its structure, it is not +so clear for `Expressions`, since an expression may be referred to by any number +of `Statement`s and other `Expression`s. -An `Expression` may only be used, whether by a `Statement` or another -`Expression`, if one of the following is true: +Naga's rules for when `Expression`s are evaluated are as follows: -- The expression is an [`Expression::Constant`], [`Expression::FunctionArgument`], or - [`Expression::GlobalVariable`]. +- [`Constant`](Expression::Constant) expressions are considered to be + implicitly evaluated before execution begins. -- The expression is an [`Expression::LocalVariable`] that is either the - `pointer` (destination) of a [`Statement::Store`], or initialized by some - previously executed `Statement::Store`. +- [`FunctionArgument`] and [`LocalVariable`] expressions are considered + implicitly evaluated upon entry to the function to which they belong. + Function arguments cannot be assigned to, and `LocalVariable` expressions + produce a *pointer to* the variable's value (for use with [`Load`] and + [`Store`]). Neither varies while the function executes, so it suffices to + consider these expressions evaluated once on entry. -- The expression is the `result` of a [`Statement::Call`], representing the - call's return value. The call must be 'in scope' for the use (see below). +- Similarly, [`GlobalVariable`] expressions are considered implicitly + evaluated before execution begins, since their value does not change while + code executes, for one of two reasons: -- The expression is included in the range of some [`Statement::Emit`] that is - 'in scope' for the use (see below). The [`Expression::needs_pre_emit`] method - returns `true` if the given expression does *not* need to be covered by an - `Emit` statement. + - Most `GlobalVariable` expressions produce a pointer to the variable's + value, for use with [`Load`] and [`Store`], as `LocalVariable` + expressions do. Although the variable's value may change, its address + does not. -The scope of an expression evaluated by an `Emit` statement covers the -subsequent expressions in that `Emit`, any following statements in the `Block` -to which that `Emit` belongs (if any) and their sub-statements (if any). + - A `GlobalVariable` expression referring to a global in the + [`StorageClass::Handle`] storage class produces the value directly, not + a pointer. Such global variables hold opaque types like shaders or + images, and cannot be assigned to. -If a `Call` statement has a `result` expression, then it is in scope for any -statements following the `Call` in the `Block` to which that `Call` belongs (if -any) and their sub-statements (if any). +- A [`Call`](Expression::Call) expression that is the `result` of a + [`Statement::Call`], representing the call's return value, is evaluated when + the `Call` statement is executed. -This means that, for example, an expression evaluated by some statement in a +- All other expressions are evaluated when the (unique) [`Statement::Emit`] + statement that covers them is executed. The [`Expression::needs_pre_emit`] + method returns `true` if the given expression is one of those variants that + does *not* need to be covered by an `Emit` statement. + +Each `Expression` has a *scope*, which is the region of the function within +which it can be used by `Statement`s and other `Expression`s. It is a validation +error to use an `Expression` outside its scope. + +An expression's scope is defined as follows: + +- The scope of a [`Constant`], [`GlobalVariable`], [`FunctionArgument`] or + [`LocalVariable`] expression covers the entire `Function` in which it + occurs. + +- The scope of an expression evaluated by an [`Emit`] statement covers the + subsequent expressions in that `Emit`, the subsequent statements in the `Block` + to which that `Emit` belongs (if any) and their sub-statements (if any). + +- If a [`Call`] statement has a `result` expression, then that expression's + scope covers the subsequent statements in the `Block` to which that `Call` + belongs (if any) and their sub-statements (if any). + +For example, this implies that an expression evaluated by some statement in a nested `Block` is not available in the `Block`'s parents. Such a value would need to be stored in a local variable to be carried upwards in the statement tree. -## Variables - -An [`Expression::LocalVariable`] or [`Expression::GlobalVariable`] produces a -pointer value referring to the variable's value. To retrieve the variable's -value, use an [`Expression::Load`], with the variable expression as its -`pointer` operand. To assign to a variable, use a [`Statement::Store`] with the -variable expression as its `pointer` operand. - -As an exception, [`Expression::GlobalVariable`]s referring to -[`GlobalVariable`]s whose `class` is [`StorageClass::Handle`] produce the -variable's value directly; no `Load` is needed. These global variables refer to -opaque values like samplers and images. +[`Call`]: Statement::Call +[`Constant`]: Expression::Constant +[`Emit`]: Statement::Emit +[`FunctionArgument`]: Expression::FunctionArgument +[`GlobalVariable`]: Expression::GlobalVariable +[`Load`]: Expression::Load +[`LocalVariable`]: Expression::LocalVariable +[`Store`]: Statement::Store !*/ @@ -917,6 +941,8 @@ pub enum Expression { index: u32, }, /// Constant value. + /// + /// Every `Constant` expression Constant(Handle), /// Splat scalar into a vector. Splat { @@ -934,12 +960,40 @@ pub enum Expression { ty: Handle, components: Vec>, }, + /// Reference a function parameter, by its index. + /// + /// A `FunctionArgument` expression evaluates to a pointer to the argument's + /// value. You must use a [`Load`] expression to retrieve its value, or a + /// [`Store`] statement to assign it a new value. + /// + /// [`Load`]: Expression::Load + /// [`Store`]: Statement::Store FunctionArgument(u32), + /// Reference a global variable. + /// + /// If the given `GlobalVariable`'s [`class`] is [`StorageClass::Handle`], + /// then the variable stores some opaque type like a sampler or an image, + /// and a `GlobalVariable` expression referring to it produces the + /// variable's value directly. + /// + /// For any other storage class, a `GlobalVariable` expression produces a + /// pointer to the variable's value. You must use a [`Load`] expression to + /// retrieve its value, or a [`Store`] statement to assign it a new value. + /// + /// [`class`]: GlobalVariable::class + /// [`Load`]: Expression::Load + /// [`Store`]: Statement::Store GlobalVariable(Handle), + /// Reference a local variable. + /// + /// A `LocalVariable` expression evaluates to a pointer to the variable's value. + /// You must use a [`Load`](Expression::Load) expression to retrieve its value, + /// or a [`Store`](Statement::Store) statement to assign it a new value. LocalVariable(Handle), + /// Load a value indirectly. Load { pointer: Handle }, /// Sample a point from a sampled or a depth image. From 0cf5484bba530f1134badbd2a1c1a8e9daf2e9c3 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Sun, 27 Jun 2021 19:30:01 +0000 Subject: [PATCH 1045/2212] [hlsl-out] Implement loop statement and composite constants --- src/back/hlsl/writer.rs | 92 ++++++++++++++++++++++++++++------------- 1 file changed, 63 insertions(+), 29 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 293e49aa6..ea5f2e409 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -292,16 +292,17 @@ impl<'a, W: Write> Writer<'a, W> { /// Ends in a newline fn write_global_constant( &mut self, - _module: &Module, + module: &Module, inner: &crate::ConstantInner, handle: Handle, ) -> BackendResult { + write!(self.out, "static const ")?; + match *inner { crate::ConstantInner::Scalar { width: _, ref value, } => { - write!(self.out, "static const ")?; // Write type match *value { crate::ScalarValue::Sint(_) => write!(self.out, "int")?, @@ -323,15 +324,13 @@ impl<'a, W: Write> Writer<'a, W> { } crate::ScalarValue::Bool(value) => write!(self.out, "{}", value)?, }; - writeln!(self.out, ";")?; } - crate::ConstantInner::Composite { .. } => { - return Err(Error::Unimplemented(format!( - "write_global_constant Composite {:?}", - inner - ))) + crate::ConstantInner::Composite { ty, ref components } => { + self.write_type(module, ty)?; + self.write_composite_constant(module, ty, components)?; } } + writeln!(self.out, ";")?; // End with extra newline for readability writeln!(self.out)?; Ok(()) @@ -610,10 +609,8 @@ impl<'a, W: Write> Writer<'a, W> { // Write the local name // The leading space is important - write!(self.out, "var {}: ", self.names[&func_ctx.name_key(handle)])?; - - // Write the local type self.write_type(module, local.ty)?; + write!(self.out, " {}", self.names[&func_ctx.name_key(handle)])?; // Write the local initializer if needed if let Some(init) = local.init { @@ -794,6 +791,27 @@ impl<'a, W: Write> Writer<'a, W> { } writeln!(self.out, ");")? } + Statement::Loop { + ref body, + ref continuing, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "while(true) {{")?; + + for sta in body.iter().chain(continuing.iter()) { + self.write_stmt(module, sta, func_ctx, indent + 1)?; + } + + writeln!(self.out, "{}}}", INDENT.repeat(indent))? + } + Statement::Break => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "break;")? + } + Statement::Continue => { + write!(self.out, "{}", INDENT.repeat(indent))?; + writeln!(self.out, "continue;")? + } _ => return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))), } @@ -1097,6 +1115,11 @@ impl<'a, W: Write> Writer<'a, W> { self.out.write_char(back::COMPONENTS[sc as usize])?; } } + // `ArrayLength` is written as `expr.length()` + Expression::ArrayLength(expr) => { + self.write_expr(module, expr, func_ctx)?; + write!(self.out, ".length()")? + } _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } @@ -1125,30 +1148,41 @@ impl<'a, W: Write> Writer<'a, W> { } } crate::ConstantInner::Composite { ty, ref components } => { - let (open_b, close_b) = match module.types[ty].inner { - TypeInner::Struct { .. } => ("{ ", " }"), - _ => { - // We should write type only for non struct constants - self.write_type(module, ty)?; - ("(", ")") - } - }; - write!(self.out, "{}", open_b)?; - for (index, constant) in components.iter().enumerate() { - self.write_constant(module, *constant)?; - // Only write a comma if isn't the last element - if index != components.len().saturating_sub(1) { - // The leading space is for readability only - write!(self.out, ", ")?; - } - } - write!(self.out, "{}", close_b)?; + self.write_composite_constant(module, ty, components)?; } } Ok(()) } + fn write_composite_constant( + &mut self, + module: &Module, + ty: Handle, + components: &[Handle], + ) -> BackendResult { + let (open_b, close_b) = match module.types[ty].inner { + TypeInner::Struct { .. } => ("{ ", " }"), + _ => { + // We should write type only for non struct constants + self.write_type(module, ty)?; + ("(", ")") + } + }; + write!(self.out, "{}", open_b)?; + for (index, constant) in components.iter().enumerate() { + self.write_constant(module, *constant)?; + // Only write a comma if isn't the last element + if index != components.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } + write!(self.out, "{}", close_b)?; + + Ok(()) + } + /// Helper method used to write [`ScalarValue`](ScalarValue) /// /// # Notes From cfbe83e3846ad8799b48786346ffc305a3d9c77e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 28 Jun 2021 01:40:45 -0400 Subject: [PATCH 1046/2212] glsl-out: adjust coordinate space --- src/back/glsl/mod.rs | 69 ++++++++++++++++------- src/front/glsl/parser.rs | 5 +- src/lib.rs | 2 +- tests/in/interpolate.param.ron | 1 + tests/in/skybox.param.ron | 1 + tests/out/glsl/quad-vert.main.Vertex.glsl | 1 + tests/out/glsl/quad.main.Vertex.glsl | 1 + 7 files changed, 56 insertions(+), 24 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9391c7ffe..2366fe81d 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -126,6 +126,15 @@ impl fmt::Display for Version { } } +bitflags::bitflags! { + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + pub struct WriterFlags: u32 { + /// Extend output Z from (0,1) to (-1,1). + const ADJUST_COORDINATE_SPACE = 0x1; + } +} + /// Structure that contains the configuration used in the [`Writer`](Writer) #[derive(Debug, Clone)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -133,6 +142,8 @@ impl fmt::Display for Version { pub struct Options { /// The glsl version to be used pub version: Version, + /// Configuration flags for the writer. + pub writer_flags: WriterFlags, /// Map of resources association to binding locations. pub binding_map: BindingMap, } @@ -141,6 +152,7 @@ impl Default for Options { fn default() -> Self { Options { version: Version::Embedded(310), + writer_flags: WriterFlags::ADJUST_COORDINATE_SPACE, binding_map: BindingMap::default(), } } @@ -1203,7 +1215,7 @@ impl<'a, W: Write> Writer<'a, W> { fn write_stmt( &mut self, sta: &crate::Statement, - ctx: &back::FunctionCtx<'_>, + ctx: &back::FunctionCtx, indent: usize, ) -> BackendResult { use crate::Statement; @@ -1391,22 +1403,23 @@ impl<'a, W: Write> Writer<'a, W> { let value = value.unwrap(); match self.module.types[result.ty].inner { crate::TypeInner::Struct { ref members, .. } => { - let (mut is_temp_struct_used, mut return_struct) = (false, ""); - if let crate::Expression::Compose { .. } = - ctx.expressions[value] - { - is_temp_struct_used = true; - return_struct = "_tmp_return"; - write!( - self.out, - "{} {} = ", - &self.names[&NameKey::Type(result.ty)], - return_struct - )?; - self.write_expr(value, ctx)?; - writeln!(self.out, ";")?; - write!(self.out, "{}", INDENT.repeat(indent))?; - } + let temp_struct_name = match ctx.expressions[value] { + crate::Expression::Compose { .. } => { + let return_struct = "_tmp_return"; + write!( + self.out, + "{} {} = ", + &self.names[&NameKey::Type(result.ty)], + return_struct + )?; + self.write_expr(value, ctx)?; + writeln!(self.out, ";")?; + write!(self.out, "{}", INDENT.repeat(indent))?; + Some(return_struct) + } + _ => None, + }; + for (index, member) in members.iter().enumerate() { // TODO: handle builtin in better way if let Some(crate::Binding::BuiltIn(builtin)) = @@ -1434,11 +1447,13 @@ impl<'a, W: Write> Writer<'a, W> { .clone(); write!(self.out, "{} = ", varying_name)?; - if !is_temp_struct_used { + if let Some(struct_name) = temp_struct_name { + write!(self.out, "{}", struct_name)?; + } else { self.write_expr(value, ctx)?; } - writeln!(self.out, "{}.{};", return_struct, &field_name)?; + writeln!(self.out, ".{};", field_name)?; write!(self.out, "{}", INDENT.repeat(indent))?; } } @@ -1455,6 +1470,22 @@ impl<'a, W: Write> Writer<'a, W> { } } } + + if let back::FunctionType::EntryPoint(ep_index) = ctx.ty { + if self.module.entry_points[ep_index as usize].stage + == crate::ShaderStage::Vertex + && self + .options + .writer_flags + .contains(WriterFlags::ADJUST_COORDINATE_SPACE) + { + writeln!( + self.out, + "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;", + )?; + write!(self.out, "{}", INDENT.repeat(indent))?; + } + } writeln!(self.out, "return;")?; } } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 16a3f4a19..bb30e9bb2 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -797,10 +797,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON - Err(ErrorKind::NotImplemented( - token.meta, - "variable qualifier", - )) + Err(ErrorKind::NotImplemented(token.meta, "variable qualifier")) } } TokenValue::Semicolon => { diff --git a/src/lib.rs b/src/lib.rs index 3705ea5cc..1efbfeaa0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -942,7 +942,7 @@ pub enum Expression { }, /// Constant value. /// - /// Every `Constant` expression + /// Every `Constant` expression Constant(Handle), /// Splat scalar into a vector. Splat { diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index 39fdcf20d..6a2a10266 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -5,6 +5,7 @@ spv_adjust_coordinate_space: true, glsl: ( version: Desktop(400), + writer_flags: (bits: 0), binding_map: {}, ), glsl_custom: true, diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 9d0ad493d..66899e280 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -38,6 +38,7 @@ glsl_custom: true, glsl: ( version: Embedded(320), + writer_flags: (bits: 0), binding_map: { (group: 0, binding: 0): 0, (group: 0, binding: 1): 0, diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index 94094f6ce..fb0a07283 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -49,6 +49,7 @@ void main() { type10 _tmp_return = type10(_expr10, _expr11, _expr12, _expr13, _expr14); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; + gl_Position.z = gl_Position.z * 2.0 - gl_Position.w; return; } diff --git a/tests/out/glsl/quad.main.Vertex.glsl b/tests/out/glsl/quad.main.Vertex.glsl index 873d01103..e32509b95 100644 --- a/tests/out/glsl/quad.main.Vertex.glsl +++ b/tests/out/glsl/quad.main.Vertex.glsl @@ -17,6 +17,7 @@ void main() { VertexOutput _tmp_return = VertexOutput(uv, vec4((1.2 * pos), 0.0, 1.0)); _vs2fs_location0 = _tmp_return.uv; gl_Position = _tmp_return.position; + gl_Position.z = gl_Position.z * 2.0 - gl_Position.w; return; } From e8b71b8dc5cd70535308591f1dd2dba5f92f44eb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 28 Jun 2021 12:38:11 -0400 Subject: [PATCH 1047/2212] [glsl-out] Support extended shadow sampling instructions, and the offset --- src/back/glsl/mod.rs | 49 +++++++++++++++++---- tests/out/glsl/shadow.fs_main.Fragment.glsl | 2 +- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 2366fe81d..877995b77 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -132,6 +132,9 @@ bitflags::bitflags! { pub struct WriterFlags: u32 { /// Extend output Z from (0,1) to (-1,1). const ADJUST_COORDINATE_SPACE = 0x1; + /// Supports GL_EXT_texture_shadow_lod on the host, which provides + /// additional functions on shadows and arrays of shadows. + const TEXTURE_SHADOW_LOD = 0x2; } } @@ -391,6 +394,16 @@ impl<'a, W: Write> Writer<'a, W> { // preprocessor not the processor ¯\_(ツ)_/¯ self.features.write(self.options.version, &mut self.out)?; + // Write the additional extensions + if self + .options + .writer_flags + .contains(WriterFlags::TEXTURE_SHADOW_LOD) + { + // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_shadow_lod.txt + writeln!(self.out, "#extension GL_EXT_texture_shadow_lod : require")?; + } + // glsl es requires a precision to be specified for floats // TODO: Should this be user configurable? if es { @@ -1677,19 +1690,27 @@ impl<'a, W: Write> Writer<'a, W> { // Furthermore if `depth_ref` is some we need to append it to the coordinate vector Expression::ImageSample { image, - sampler: _, //TODO + sampler: _, //TODO? coordinate, array_index, - offset: _, //TODO + offset, level, depth_ref, } => { - //TODO: handle MS + let dim = match *ctx.info[image].ty.inner_with(&self.module.types) { + TypeInner::Image { dim, .. } => dim, + _ => unreachable!(), + }; // textureLod on sampler2DArrayShadow and samplerCubeShadow does not exist in GLSL. // To emulate this, we will have to use textureGrad with a constant gradient of 0. - let workaround_lod_array_shadow_as_grad = - array_index.is_some() && depth_ref.is_some(); + let workaround_lod_array_shadow_as_grad = (array_index.is_some() + || dim == crate::ImageDimension::Cube) + && depth_ref.is_some() + && !self + .options + .writer_flags + .contains(WriterFlags::TEXTURE_SHADOW_LOD); //Write the function to be used depending on the sample level let fun_name = match level { @@ -1703,8 +1724,12 @@ impl<'a, W: Write> Writer<'a, W> { } crate::SampleLevel::Gradient { .. } => "textureGrad", }; + let offset_name = match offset { + Some(_) => "Offset", + None => "", + }; - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{}{}(", fun_name, offset_name)?; // Write the image that will be used self.write_expr(image, ctx)?; @@ -1745,15 +1770,16 @@ impl<'a, W: Write> Writer<'a, W> { // Zero needs level set to 0 crate::SampleLevel::Zero => { if workaround_lod_array_shadow_as_grad { - write!(self.out, ", vec2(0, 0), vec2(0,0)")?; + write!(self.out, ", vec2(0,0), vec2(0,0)")?; } else { - write!(self.out, ", 0")?; + write!(self.out, ", 0.0")?; } } // Exact and bias require another argument crate::SampleLevel::Exact(expr) => { if workaround_lod_array_shadow_as_grad { - write!(self.out, ", vec2(0, 0), vec2(0,0)")?; + log::warn!("Unable to `textureLod` a shadow array, ignoring the LOD"); + write!(self.out, ", vec2(0,0), vec2(0,0)")?; } else { write!(self.out, ", ")?; self.write_expr(expr, ctx)?; @@ -1771,6 +1797,11 @@ impl<'a, W: Write> Writer<'a, W> { } } + if let Some(constant) = offset { + write!(self.out, ", ")?; + self.write_constant(&self.module.constants[constant])?; + } + // End the function write!(self.out, ")")? } diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index b49523b98..6446c5644 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -28,7 +28,7 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } vec2 flip_correction = vec2(0.5, -0.5); vec2 light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - float _expr26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0, 0), vec2(0,0)); + float _expr26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); return _expr26; } From ba066c83e76a507898941ed897a47b5f93b217ee Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 29 Jun 2021 01:44:49 -0400 Subject: [PATCH 1048/2212] glsl-out: proper continuing block --- src/back/glsl/mod.rs | 40 +++++++++++++++++---- tests/out/glsl/boids.main.Compute.glsl | 8 +++-- tests/out/glsl/shadow.fs_main.Fragment.glsl | 8 +++-- 3 files changed, 45 insertions(+), 11 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 877995b77..9090aba39 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1368,22 +1368,48 @@ impl<'a, W: Write> Writer<'a, W> { // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a // while true loop and appending the continuing block to the body resulting on: // ``` + // bool loop_init = true; // while(true) { - // body - // continuing + // if (!loop_init) { } + // loop_init = false; + // // } // ``` Statement::Loop { ref body, ref continuing, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; - writeln!(self.out, "while(true) {{")?; - - for sta in body.iter().chain(continuing.iter()) { + if !continuing.is_empty() { + let gate_name = self.namer.call("loop_init"); + writeln!( + self.out, + "{}bool {} = true;", + INDENT.repeat(indent), + gate_name + )?; + writeln!(self.out, "{}while(true) {{", INDENT.repeat(indent))?; + writeln!( + self.out, + "{}if (!{}) {{", + INDENT.repeat(indent + 1), + gate_name + )?; + for sta in continuing { + self.write_stmt(sta, ctx, indent + 1)?; + } + writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; + writeln!( + self.out, + "{}{} = false;", + INDENT.repeat(indent + 1), + gate_name + )?; + } else { + writeln!(self.out, "{}while(true) {{", INDENT.repeat(indent))?; + } + for sta in body { self.write_stmt(sta, ctx, indent + 1)?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? } // Break, continue and return as written as in C diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 2996c3435..14a00bce0 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -51,7 +51,13 @@ void main() { cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); + bool loop_init = true; while(true) { + if (!loop_init) { + uint _expr86 = i; + i = (_expr86 + 1u); + } + loop_init = false; uint _expr37 = i; if ((_expr37 >= 1500u)) { break; @@ -95,8 +101,6 @@ void main() { int _expr83 = cVelCount; cVelCount = (_expr83 + 1); } - uint _expr86 = i; - i = (_expr86 + 1u); } int _expr89 = cMassCount; if ((_expr89 > 0)) { diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 6446c5644..dffc97416 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -38,7 +38,13 @@ void main() { vec3 color = vec3(0.05, 0.05, 0.05); uint i = 0u; vec3 normal = normalize(raw_normal); + bool loop_init = true; while(true) { + if (!loop_init) { + uint _expr40 = i; + i = (_expr40 + 1u); + } + loop_init = false; uint _expr12 = i; uvec4 _expr14 = _group_0_binding_0.num_lights; if ((_expr12 >= min(_expr14.x, 10u))) { @@ -52,8 +58,6 @@ void main() { float diffuse = max(0.0, dot(normal, light_dir)); vec3 _expr34 = color; color = (_expr34 + ((_expr25 * diffuse) * light.color.xyz)); - uint _expr40 = i; - i = (_expr40 + 1u); } vec3 _expr43 = color; _fs2p_location0 = vec4(_expr43, 1.0); From 68a2efd3c5db62c2c011ccbad84f58be5e539fe3 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 29 Jun 2021 02:18:56 -0400 Subject: [PATCH 1049/2212] glsl-out: make the cs adjustment to also flip Y --- src/back/glsl/mod.rs | 4 ++-- tests/out/glsl/quad-vert.main.Vertex.glsl | 2 +- tests/out/glsl/quad.main.Vertex.glsl | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9090aba39..ef1a71cbc 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -130,7 +130,7 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct WriterFlags: u32 { - /// Extend output Z from (0,1) to (-1,1). + /// Flip output Y and extend Z from (0,1) to (-1,1). const ADJUST_COORDINATE_SPACE = 0x1; /// Supports GL_EXT_texture_shadow_lod on the host, which provides /// additional functions on shadows and arrays of shadows. @@ -1520,7 +1520,7 @@ impl<'a, W: Write> Writer<'a, W> { { writeln!( self.out, - "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;", + "gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);", )?; write!(self.out, "{}", INDENT.repeat(indent))?; } diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index fb0a07283..b60099c18 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -49,7 +49,7 @@ void main() { type10 _tmp_return = type10(_expr10, _expr11, _expr12, _expr13, _expr14); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; - gl_Position.z = gl_Position.z * 2.0 - gl_Position.w; + gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; } diff --git a/tests/out/glsl/quad.main.Vertex.glsl b/tests/out/glsl/quad.main.Vertex.glsl index e32509b95..cde8ac8d4 100644 --- a/tests/out/glsl/quad.main.Vertex.glsl +++ b/tests/out/glsl/quad.main.Vertex.glsl @@ -17,7 +17,7 @@ void main() { VertexOutput _tmp_return = VertexOutput(uv, vec4((1.2 * pos), 0.0, 1.0)); _vs2fs_location0 = _tmp_return.uv; gl_Position = _tmp_return.position; - gl_Position.z = gl_Position.z * 2.0 - gl_Position.w; + gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; } From 6723c8f6ae49c1758320f35d9448a0d1bf4097c1 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 28 Jun 2021 20:06:53 +0300 Subject: [PATCH 1050/2212] [hlsl-out] Implement Derivative expression and enable standard snapshot test for HLSL --- src/back/hlsl/writer.rs | 15 +++++++++++++++ src/back/msl/mod.rs | 2 +- tests/out/hlsl/standard.hlsl | 11 +++++++++++ tests/out/hlsl/standard.hlsl.config | 2 ++ tests/snapshots.rs | 6 +----- 5 files changed, 30 insertions(+), 6 deletions(-) create mode 100644 tests/out/hlsl/standard.hlsl create mode 100644 tests/out/hlsl/standard.hlsl.config diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index ea5f2e409..386f2a39e 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1120,6 +1120,21 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(module, expr, func_ctx)?; write!(self.out, ".length()")? } + Expression::Derivative { axis, expr } => { + use crate::DerivativeAxis as Da; + + write!( + self.out, + "{}(", + match axis { + Da::X => "ddx", + Da::Y => "ddy", + Da::Width => "fwidth", + } + )?; + self.write_expr(module, expr, func_ctx)?; + write!(self.out, ")")? + } _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 6a46bedaa..33d2e1a15 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -263,7 +263,7 @@ impl Options { stage: crate::ShaderStage, res_binding: &crate::ResourceBinding, ) -> Result { - match self.per_stage_map[stage].resources.get(&res_binding) { + match self.per_stage_map[stage].resources.get(res_binding) { Some(target) => Ok(ResolvedBinding::Resource(target.clone())), None if self.fake_missing_bindings => Ok(ResolvedBinding::User { prefix: "fake", diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl new file mode 100644 index 000000000..5ec8b8f7d --- /dev/null +++ b/tests/out/hlsl/standard.hlsl @@ -0,0 +1,11 @@ +struct FragmentInput_derivatives { + float4 foo1 : SV_Position; +}; + +float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Target0 +{ + float4 x = ddx(fragmentinput_derivatives.foo1); + float4 y = ddy(fragmentinput_derivatives.foo1); + float4 z = fwidth(fragmentinput_derivatives.foo1); + return mul((x + y), z); +} diff --git a/tests/out/hlsl/standard.hlsl.config b/tests/out/hlsl/standard.hlsl.config new file mode 100644 index 000000000..9ae8c9df7 --- /dev/null +++ b/tests/out/hlsl/standard.hlsl.config @@ -0,0 +1,2 @@ +fragment=ps_5_0 +fragment_name=derivatives diff --git a/tests/snapshots.rs b/tests/snapshots.rs index bfcb897d0..1176b353a 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -371,11 +371,7 @@ fn convert_wgsl() { ), ( "standard", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, - ), - ( - "standard", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), //TODO: GLSL https://github.com/gfx-rs/naga/issues/874 ("interface", Targets::SPIRV | Targets::METAL | Targets::WGSL), From 925c92d12f097e7105048b4879c29255d439086a Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 28 Jun 2021 21:25:30 +0300 Subject: [PATCH 1051/2212] Add entry point to operators wgsl test --- tests/in/operators.wgsl | 6 +++++ tests/out/glsl/operators.main.Compute.glsl | 27 ++++++++++++++++++++++ tests/out/msl/operators.msl | 7 ++++++ tests/out/spv/operators.spvasm | 14 +++++++++-- tests/out/wgsl/operators.wgsl | 6 +++++ 5 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 tests/out/glsl/operators.main.Compute.glsl diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 3b7d1f33f..cb6da5df0 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -8,3 +8,9 @@ fn unary() -> i32 { let a = 1; if (!true) { return a; } else { return ~a; }; } + +[[stage(compute), workgroup_size(1)]] +fn main() { + let a = splat(); + let b = unary(); +} diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl new file mode 100644 index 000000000..caad84e6a --- /dev/null +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -0,0 +1,27 @@ +#version 310 es + +precision highp float; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + + +vec4 splat() { + vec2 a = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + ivec4 b = (ivec4(5) % ivec4(2)); + return (a.xyxy + vec4(b)); +} + +int unary() { + if ((! true)) { + return 1; + } else { + return (~ 1); + } +} + +void main() { + vec4 _expr0 = splat(); + int _expr1 = unary(); + return; +} + diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 4cddb70b5..3749cb47c 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -17,3 +17,10 @@ int unary( return !1; } } + +kernel void main1( +) { + metal::float4 _e0 = splat(); + int _e1 = unary(); + return; +} diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index a6380e59c..aefe1c99f 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,11 +1,12 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 44 +; Bound: 50 OpCapability Shader -OpCapability Linkage %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %45 "main" +OpExecutionMode %45 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -24,6 +25,7 @@ OpMemoryModel Logical GLSL450 %27 = OpTypeVector %9 4 %36 = OpTypeFunction %9 %43 = OpConstantNull %9 +%46 = OpTypeFunction %2 %16 = OpFunction %14 None %17 %15 = OpLabel OpBranch %18 @@ -57,4 +59,12 @@ OpReturnValue %11 OpReturnValue %42 %39 = OpLabel OpReturnValue %43 +OpFunctionEnd +%45 = OpFunction %2 None %46 +%44 = OpLabel +OpBranch %47 +%47 = OpLabel +%48 = OpFunctionCall %14 %16 +%49 = OpFunctionCall %9 %35 +OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index cacefc724..06e3ca1dc 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -12,3 +12,9 @@ fn unary() -> i32 { } } +[[stage(compute), workgroup_size(1, 1, 1)]] +fn main() { + let _e0: vec4 = splat(); + let _e1: i32 = unary(); + return; +} From 607206f9a5cc33a8b1e7cec84663be6390e3be7f Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 28 Jun 2021 22:12:31 +0300 Subject: [PATCH 1052/2212] [hlsl-out] Enable operators snapshot test --- src/back/hlsl/writer.rs | 69 +++++++++++++++++++--------- tests/out/hlsl/operators.hlsl | 23 ++++++++++ tests/out/hlsl/operators.hlsl.config | 2 + tests/snapshots.rs | 2 +- 4 files changed, 74 insertions(+), 22 deletions(-) create mode 100644 tests/out/hlsl/operators.hlsl create mode 100644 tests/out/hlsl/operators.hlsl.config diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 386f2a39e..e55194507 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -773,11 +773,18 @@ impl<'a, W: Write> Writer<'a, W> { } => { write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { + write!(self.out, "const ")?; let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); - write!(self.out, "const {} = ", name)?; + let expr_ty = &func_ctx.info[expr].ty; + match *expr_ty { + proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?, + proc::TypeResolution::Value(ref value) => { + self.write_value_type(module, value)? + } + }; + write!(self.out, " {} = ", name)?; self.write_expr(module, expr, func_ctx)?; self.named_expressions.insert(expr, name); - writeln!(self.out, ";")? } let func_name = &self.names[&NameKey::Function(function)]; write!(self.out, "{}(", func_name)?; @@ -976,28 +983,31 @@ impl<'a, W: Write> Writer<'a, W> { } Expression::Unary { op, expr } => { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators - write!( - self.out, - "({} ", - match op { - crate::UnaryOperator::Negate => "-", - crate::UnaryOperator::Not => - match *func_ctx.info[expr].ty.inner_with(&module.types) { - TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - .. - } => "!", - ref other => - return Err(Error::Custom(format!( - "Cannot apply not to type {:?}", - other - ))), - }, - } - )?; + let convert_to_bool = if let TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + .. + } = *func_ctx.info[expr].ty.inner_with(&module.types) + { + false + } else { + true + }; + let op_str = match op { + crate::UnaryOperator::Negate => "-", + crate::UnaryOperator::Not => "!", + }; + write!(self.out, "({}", op_str)?; + + if convert_to_bool { + write!(self.out, "bool(")?; + } self.write_expr(module, expr, func_ctx)?; + if convert_to_bool { + write!(self.out, ")")?; + } + write!(self.out, ")")? } Expression::As { expr, kind, .. } => { @@ -1135,6 +1145,23 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")? } + Expression::Splat { size, value } => { + // hlsl is not supported one value constructor + // if we write, for example, int4(0), dxc returns error: + // error: too few elements in vector initialization (expected 4 elements, have 1) + let number_of_components = match size { + crate::VectorSize::Bi => "xx", + crate::VectorSize::Tri => "xxx", + crate::VectorSize::Quad => "xxxx", + }; + let resolved = func_ctx.info[expr].ty.inner_with(&module.types); + self.write_value_type(module, resolved)?; + write!(self.out, "(")?; + self.write_expr(module, value, func_ctx)?; + write!(self.out, ".{})", number_of_components)? + } + // Nothing to do here, since call expression already cached + Expression::Call(_) => {} _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl new file mode 100644 index 000000000..2448e11c4 --- /dev/null +++ b/tests/out/hlsl/operators.hlsl @@ -0,0 +1,23 @@ +float4 splat() +{ + float2 a = (((float2(1.0.xx) + float2(2.0.xx)) - float2(3.0.xx)) / float2(4.0.xx)); + int4 b = (int4(5.xxxx) % int4(2.xxxx)); + return (a.xyxy + float4(b)); +} + +int unary() +{ + if ((!true)) { + return 1; + } else { + return (!bool(1)); + } +} + +[numthreads(1, 1, 1)] +void main() +{ + const float4 _e0 = splat(); + const int _e1 = unary(); + return; +} diff --git a/tests/out/hlsl/operators.hlsl.config b/tests/out/hlsl/operators.hlsl.config new file mode 100644 index 000000000..71412ac2d --- /dev/null +++ b/tests/out/hlsl/operators.hlsl.config @@ -0,0 +1,2 @@ +compute=cs_5_0 +compute_name=main diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1176b353a..b9466738d 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -358,7 +358,7 @@ fn convert_wgsl() { ("extra", Targets::SPIRV | Targets::METAL | Targets::WGSL), ( "operators", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "interpolate", From ef1194d69a2cbd18b7da19cefdd7205840ecf9b2 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 29 Jun 2021 18:36:40 +0300 Subject: [PATCH 1053/2212] [CI] Add dneto0 spirv-samples to lazy task --- .github/workflows/lazy.yml | 73 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index cdfb1cef8..2065da0d4 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -76,3 +76,76 @@ jobs: echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter done cat counter + dneto0_spirv-samples: + name: Parse dneto0 spirv-samples + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + - name: Download shaders + run: git clone https://github.com/dneto0/spirv-samples.git + - name: Build Naga + run: cargo build --release --bin naga + - name: Install spirv-tools + run: | + wget -q https://storage.googleapis.com/spirv-tools/artifacts/prod/graphics_shader_compiler/spirv-tools/linux-clang-release/continuous/1489/20210629-121459/install.tgz + tar zxf install.tgz + ./install/bin/spirv-as --version + - name: Compile spv from spvasm + run: | + cd spirv-samples + mkdir -p spv + + find "./spvasm" -name '*.spvasm' | while read fname; + do + echo "Convert to spv with spirv-as: $fname" + ../install/bin/spirv-as --target-env spv1.3 $(realpath ${fname}) -o ./spv/$(basename ${fname}).spv + done; + - name: Validate spv and generate wgsl + run: | + set +e + cd spirv-samples + SUCCESS_RESULT_COUNT=0 + FILE_COUNT=0 + mkdir -p spv + mkdir -p wgsl + + echo "==== Validate spv and generate wgsl ====" + rm -f counter + touch counter + + find "./spv" -name '*.spv' | while read fname; + do + echo "Convert: $fname" + FILE_COUNT=$((FILE_COUNT+1)) + ../target/release/naga --validate 27 $(realpath ${fname}) ./wgsl/$(basename ${fname}).wgsl + if [[ $? -eq 0 ]]; then + SUCCESS_RESULT_COUNT=$((SUCCESS_RESULT_COUNT + 1)) + fi + echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter + done + cat counter + - name: Validate output wgsl + run: | + set +e + cd spirv-samples + SUCCESS_RESULT_COUNT=0 + FILE_COUNT=0 + + rm -f counter + touch counter + + find "./wgsl" -name '*.wgsl' | while read fname; + do + echo "Validate: $fname" + FILE_COUNT=$((FILE_COUNT+1)) + ../target/release/naga --validate 27 $(realpath ${fname}) + if [[ $? -eq 0 ]]; then + SUCCESS_RESULT_COUNT=$((SUCCESS_RESULT_COUNT + 1)) + fi + echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter + done + cat counter From fbab3a3ba52d0764459d890ad69238bc567ef725 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Wed, 30 Jun 2021 09:25:56 -0700 Subject: [PATCH 1054/2212] [glsl-in] Add support for texture function with LOD bias --- src/front/glsl/functions.rs | 4 ++-- src/front/glsl/parser_tests.rs | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 36cf73985..d10796266 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -152,7 +152,7 @@ impl Program<'_> { Ok(Some(args[0].0)) } "texture" => { - if args.len() != 2 { + if !(2..=3).contains(&args.len()) { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { @@ -163,7 +163,7 @@ impl Program<'_> { coordinate: args[1].0, array_index: None, //TODO offset: None, //TODO - level: SampleLevel::Auto, + level: args.get(2).map_or(SampleLevel::Auto, |&(expr, _)| SampleLevel::Bias(expr)), depth_ref: None, }, body, diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index f555ec2dc..6bf6f78bf 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -271,6 +271,7 @@ fn textures() { layout(set = 1, binding = 2) uniform sampler tex_sampler; void main() { o_color = texture(sampler2D(tex, tex_sampler), v_uv); + o_color.a = texture(sampler2D(tex, tex_sampler), v_uv, 2.0).a; } "#, &entry_points, From e0b37667ca2ced107607b7e8735212c99a1bccff Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 25 Jun 2021 14:10:21 -0700 Subject: [PATCH 1055/2212] [spv-out] Move future BlockContext methods into their own impl block. This commit should introduce no meaningful code changes. It's simply isolating the `Writer` methods that should be `BlockContext` methods into their own impl block, to make it easier to see the meaningful changes needed to introduce `BlockContext`. --- src/back/spv/writer.rs | 406 ++++++++++++++++++------------------ src/front/glsl/functions.rs | 4 +- 2 files changed, 207 insertions(+), 203 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 5852da565..67f5501e6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1130,6 +1130,210 @@ impl Writer { } } + fn write_entry_point_return( + &mut self, + value_id: Word, + ir_result: &crate::FunctionResult, + result_members: &[ResultMember], + body: &mut Vec, + ) -> Result<(), Error> { + for (index, res_member) in result_members.iter().enumerate() { + let member_value_id = match ir_result.binding { + Some(_) => value_id, + None => { + let member_value_id = self.id_gen.next(); + body.push(Instruction::composite_extract( + res_member.type_id, + member_value_id, + value_id, + &[index as u32], + )); + member_value_id + } + }; + + body.push(Instruction::store(res_member.id, member_value_id, None)); + + // Flip Y coordinate to adjust for coordinate space difference + // between SPIR-V and our IR. + if self.flags.contains(WriterFlags::ADJUST_COORDINATE_SPACE) + && res_member.built_in == Some(crate::BuiltIn::Position) + { + let access_id = self.id_gen.next(); + let float_ptr_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: Some(spirv::StorageClass::Output), + }))?; + let index_y_id = self.get_index_constant(1)?; + body.push(Instruction::access_chain( + float_ptr_type_id, + access_id, + res_member.id, + &[index_y_id], + )); + + let load_id = self.id_gen.next(); + let float_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))?; + body.push(Instruction::load(float_type_id, load_id, access_id, None)); + + let neg_id = self.id_gen.next(); + body.push(Instruction::unary( + spirv::Op::FNegate, + float_type_id, + neg_id, + load_id, + )); + body.push(Instruction::store(access_id, neg_id, None)); + } + } + Ok(()) + } + + fn write_physical_layout(&mut self) { + self.physical_layout.bound = self.id_gen.0 + 1; + } + + fn write_logical_layout( + &mut self, + ir_module: &crate::Module, + mod_info: &ModuleInfo, + ) -> Result<(), Error> { + let has_storage_buffers = ir_module + .global_variables + .iter() + .any(|(_, var)| var.class == crate::StorageClass::Storage); + if self.physical_layout.version < 0x10300 && has_storage_buffers { + // enable the storage buffer class on < SPV-1.3 + Instruction::extension("SPV_KHR_storage_buffer_storage_class") + .to_words(&mut self.logical_layout.extensions); + } + Instruction::type_void(self.void_type).to_words(&mut self.logical_layout.declarations); + Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") + .to_words(&mut self.logical_layout.ext_inst_imports); + + if self.flags.contains(WriterFlags::DEBUG) { + self.debugs + .push(Instruction::source(spirv::SourceLanguage::GLSL, 450)); + } + + self.constant_ids.resize(ir_module.constants.len(), 0); + // first, output all the scalar constants + for (handle, constant) in ir_module.constants.iter() { + match constant.inner { + crate::ConstantInner::Composite { .. } => continue, + crate::ConstantInner::Scalar { width, ref value } => { + self.constant_ids[handle.index()] = match constant.name { + Some(ref name) => { + let id = self.id_gen.next(); + self.write_constant_scalar(id, value, width, Some(name))?; + id + } + None => self.get_constant_scalar(*value, width)?, + }; + } + } + } + + // then all types, some of them may rely on constants and struct type set + for (handle, _) in ir_module.types.iter() { + self.write_type_declaration_arena(&ir_module.types, handle)?; + } + + // the all the composite constants, they rely on types + for (handle, constant) in ir_module.constants.iter() { + match constant.inner { + crate::ConstantInner::Scalar { .. } => continue, + crate::ConstantInner::Composite { ty, ref components } => { + let id = self.id_gen.next(); + self.constant_ids[handle.index()] = id; + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = constant.name { + self.debugs.push(Instruction::name(id, name)); + } + } + self.write_constant_composite(id, ty, components)?; + } + } + } + debug_assert_eq!(self.constant_ids.iter().position(|&id| id == 0), None); + + // now write all globals + for (_, var) in ir_module.global_variables.iter() { + let (instruction, id) = self.write_global_variable(ir_module, var)?; + instruction.to_words(&mut self.logical_layout.declarations); + self.global_variables + .push(GlobalVariable { id, handle_id: 0 }); + } + + // all functions + for (handle, ir_function) in ir_module.functions.iter() { + let info = &mod_info[handle]; + let id = self.write_function(ir_function, info, ir_module, None)?; + self.lookup_function.insert(handle, id); + } + + // and entry points + for (ep_index, ir_ep) in ir_module.entry_points.iter().enumerate() { + let info = mod_info.get_entry_point(ep_index); + let ep_instruction = self.write_entry_point(ir_ep, info, ir_module)?; + ep_instruction.to_words(&mut self.logical_layout.entry_points); + } + + for capability in self.capabilities.iter() { + Instruction::capability(*capability).to_words(&mut self.logical_layout.capabilities); + } + if ir_module.entry_points.is_empty() { + // SPIR-V doesn't like modules without entry points + Instruction::capability(spirv::Capability::Linkage) + .to_words(&mut self.logical_layout.capabilities); + } + + let addressing_model = spirv::AddressingModel::Logical; + let memory_model = spirv::MemoryModel::GLSL450; + self.check(addressing_model.required_capabilities())?; + self.check(memory_model.required_capabilities())?; + + Instruction::memory_model(addressing_model, memory_model) + .to_words(&mut self.logical_layout.memory_model); + + if self.flags.contains(WriterFlags::DEBUG) { + for debug in self.debugs.iter() { + debug.to_words(&mut self.logical_layout.debugs); + } + } + + for annotation in self.annotations.iter() { + annotation.to_words(&mut self.logical_layout.annotations); + } + + Ok(()) + } + + pub fn write( + &mut self, + ir_module: &crate::Module, + info: &ModuleInfo, + words: &mut Vec, + ) -> Result<(), Error> { + self.reset(); + + self.write_logical_layout(ir_module, info)?; + self.write_physical_layout(); + + self.physical_layout.in_words(words); + self.logical_layout.in_words(words); + Ok(()) + } +} + +impl Writer { fn write_texture_coordinates( &mut self, ir_module: &crate::Module, @@ -2337,72 +2541,6 @@ impl Writer { } } - fn write_entry_point_return( - &mut self, - value_id: Word, - ir_result: &crate::FunctionResult, - result_members: &[ResultMember], - body: &mut Vec, - ) -> Result<(), Error> { - for (index, res_member) in result_members.iter().enumerate() { - let member_value_id = match ir_result.binding { - Some(_) => value_id, - None => { - let member_value_id = self.id_gen.next(); - body.push(Instruction::composite_extract( - res_member.type_id, - member_value_id, - value_id, - &[index as u32], - )); - member_value_id - } - }; - - body.push(Instruction::store(res_member.id, member_value_id, None)); - - // Flip Y coordinate to adjust for coordinate space difference - // between SPIR-V and our IR. - if self.flags.contains(WriterFlags::ADJUST_COORDINATE_SPACE) - && res_member.built_in == Some(crate::BuiltIn::Position) - { - let access_id = self.id_gen.next(); - let float_ptr_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: Some(spirv::StorageClass::Output), - }))?; - let index_y_id = self.get_index_constant(1)?; - body.push(Instruction::access_chain( - float_ptr_type_id, - access_id, - res_member.id, - &[index_y_id], - )); - - let load_id = self.id_gen.next(); - let float_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))?; - body.push(Instruction::load(float_type_id, load_id, access_id, None)); - - let neg_id = self.id_gen.next(); - body.push(Instruction::unary( - spirv::Op::FNegate, - float_type_id, - neg_id, - load_id, - )); - body.push(Instruction::store(access_id, neg_id, None)); - } - } - Ok(()) - } - //TODO: put most of these into a `BlockContext` structure! #[allow(clippy::too_many_arguments)] fn write_block( @@ -2806,142 +2944,6 @@ impl Writer { function.consume(block, termination); Ok(()) } - - fn write_physical_layout(&mut self) { - self.physical_layout.bound = self.id_gen.0 + 1; - } - - fn write_logical_layout( - &mut self, - ir_module: &crate::Module, - mod_info: &ModuleInfo, - ) -> Result<(), Error> { - let has_storage_buffers = ir_module - .global_variables - .iter() - .any(|(_, var)| var.class == crate::StorageClass::Storage); - if self.physical_layout.version < 0x10300 && has_storage_buffers { - // enable the storage buffer class on < SPV-1.3 - Instruction::extension("SPV_KHR_storage_buffer_storage_class") - .to_words(&mut self.logical_layout.extensions); - } - Instruction::type_void(self.void_type).to_words(&mut self.logical_layout.declarations); - Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") - .to_words(&mut self.logical_layout.ext_inst_imports); - - if self.flags.contains(WriterFlags::DEBUG) { - self.debugs - .push(Instruction::source(spirv::SourceLanguage::GLSL, 450)); - } - - self.constant_ids.resize(ir_module.constants.len(), 0); - // first, output all the scalar constants - for (handle, constant) in ir_module.constants.iter() { - match constant.inner { - crate::ConstantInner::Composite { .. } => continue, - crate::ConstantInner::Scalar { width, ref value } => { - self.constant_ids[handle.index()] = match constant.name { - Some(ref name) => { - let id = self.id_gen.next(); - self.write_constant_scalar(id, value, width, Some(name))?; - id - } - None => self.get_constant_scalar(*value, width)?, - }; - } - } - } - - // then all types, some of them may rely on constants and struct type set - for (handle, _) in ir_module.types.iter() { - self.write_type_declaration_arena(&ir_module.types, handle)?; - } - - // the all the composite constants, they rely on types - for (handle, constant) in ir_module.constants.iter() { - match constant.inner { - crate::ConstantInner::Scalar { .. } => continue, - crate::ConstantInner::Composite { ty, ref components } => { - let id = self.id_gen.next(); - self.constant_ids[handle.index()] = id; - if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = constant.name { - self.debugs.push(Instruction::name(id, name)); - } - } - self.write_constant_composite(id, ty, components)?; - } - } - } - debug_assert_eq!(self.constant_ids.iter().position(|&id| id == 0), None); - - // now write all globals - for (_, var) in ir_module.global_variables.iter() { - let (instruction, id) = self.write_global_variable(ir_module, var)?; - instruction.to_words(&mut self.logical_layout.declarations); - self.global_variables - .push(GlobalVariable { id, handle_id: 0 }); - } - - // all functions - for (handle, ir_function) in ir_module.functions.iter() { - let info = &mod_info[handle]; - let id = self.write_function(ir_function, info, ir_module, None)?; - self.lookup_function.insert(handle, id); - } - - // and entry points - for (ep_index, ir_ep) in ir_module.entry_points.iter().enumerate() { - let info = mod_info.get_entry_point(ep_index); - let ep_instruction = self.write_entry_point(ir_ep, info, ir_module)?; - ep_instruction.to_words(&mut self.logical_layout.entry_points); - } - - for capability in self.capabilities.iter() { - Instruction::capability(*capability).to_words(&mut self.logical_layout.capabilities); - } - if ir_module.entry_points.is_empty() { - // SPIR-V doesn't like modules without entry points - Instruction::capability(spirv::Capability::Linkage) - .to_words(&mut self.logical_layout.capabilities); - } - - let addressing_model = spirv::AddressingModel::Logical; - let memory_model = spirv::MemoryModel::GLSL450; - self.check(addressing_model.required_capabilities())?; - self.check(memory_model.required_capabilities())?; - - Instruction::memory_model(addressing_model, memory_model) - .to_words(&mut self.logical_layout.memory_model); - - if self.flags.contains(WriterFlags::DEBUG) { - for debug in self.debugs.iter() { - debug.to_words(&mut self.logical_layout.debugs); - } - } - - for annotation in self.annotations.iter() { - annotation.to_words(&mut self.logical_layout.annotations); - } - - Ok(()) - } - - pub fn write( - &mut self, - ir_module: &crate::Module, - info: &ModuleInfo, - words: &mut Vec, - ) -> Result<(), Error> { - self.reset(); - - self.write_logical_layout(ir_module, info)?; - self.write_physical_layout(); - - self.physical_layout.in_words(words); - self.logical_layout.in_words(words); - Ok(()) - } } #[test] diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index d10796266..f8dfe6f42 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -163,7 +163,9 @@ impl Program<'_> { coordinate: args[1].0, array_index: None, //TODO offset: None, //TODO - level: args.get(2).map_or(SampleLevel::Auto, |&(expr, _)| SampleLevel::Bias(expr)), + level: args.get(2).map_or(SampleLevel::Auto, |&(expr, _)| { + SampleLevel::Bias(expr) + }), depth_ref: None, }, body, From 634632a3821c6de79986f3ac55b21b29f04c87e6 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 25 Jun 2021 14:51:14 -0700 Subject: [PATCH 1056/2212] [spv-out]: Introduce `BlockContext`. This commit should should cause no visible change in behavior. Many `back::spv::Writer` methods take long lists of arguments simply describing the module and function we're generating code for, but these never change while we generate a given function. This commit moves some of those values into a `BlockContext` type, and turns those `Writer` methods into `BlockContext` methods, so that code can access these values through `self`, rather than threading them through everywhere as arguments. Many uses of `self.foo` become `self.writer.foo`. Some of these can be simplified, but to make this commit easier to review, most of those changes are left to later commits. This allows us to remove some `#[allow(clippy::too_many_arguments)]` attributes. --- src/back/spv/index.rs | 182 ++++-------- src/back/spv/mod.rs | 19 ++ src/back/spv/writer.rs | 614 +++++++++++++++++------------------------ 3 files changed, 334 insertions(+), 481 deletions(-) diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 02495bbef..76082ba33 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -1,7 +1,7 @@ //! Bounds-checking for SPIR-V output. -use super::{Block, Error, Function, IdGenerator, Instruction, Word, Writer}; -use crate::{arena::Handle, back::IndexBoundsCheckPolicy, valid::FunctionInfo}; +use super::{Block, BlockContext, Error, IdGenerator, Instruction, Word}; +use crate::{arena::Handle, back::IndexBoundsCheckPolicy}; /// The results of emitting code for a left-hand-side expression. /// @@ -46,7 +46,7 @@ pub enum MaybeKnown { Computed(Word), } -impl Writer { +impl<'w> BlockContext<'w> { /// Emit code to compute the length of a run-time array. /// /// Given `array`, an expression referring to the final member of a struct, @@ -55,29 +55,29 @@ impl Writer { pub(super) fn write_runtime_array_length( &mut self, array: Handle, - ir_function: &crate::Function, - function: &Function, block: &mut Block, ) -> Result { // Look into the expression to find the value and type of the struct // holding the dynamically-sized array. - let (structure_id, last_member_index) = match ir_function.expressions[array] { - crate::Expression::AccessIndex { base, index } => match ir_function.expressions[base] { - crate::Expression::GlobalVariable(handle) => { - (self.global_variables[handle.index()].id, index) + let (structure_id, last_member_index) = match self.ir_function.expressions[array] { + crate::Expression::AccessIndex { base, index } => { + match self.ir_function.expressions[base] { + crate::Expression::GlobalVariable(handle) => { + (self.writer.global_variables[handle.index()].id, index) + } + crate::Expression::FunctionArgument(index) => { + let parameter_id = self.function.parameter_id(index); + (parameter_id, index) + } + _ => return Err(Error::Validation("array length expression")), } - crate::Expression::FunctionArgument(index) => { - let parameter_id = function.parameter_id(index); - (parameter_id, index) - } - _ => return Err(Error::Validation("array length expression")), - }, + } _ => return Err(Error::Validation("array length expression")), }; - let length_id = self.id_gen.next(); + let length_id = self.gen_id(); block.body.push(Instruction::array_length( - self.get_uint_type_id()?, + self.writer.get_uint_type_id()?, length_id, structure_id, last_member_index, @@ -98,24 +98,19 @@ impl Writer { fn write_sequence_length( &mut self, sequence: Handle, - ir_module: &crate::Module, - ir_function: &crate::Function, - fun_info: &FunctionInfo, - function: &Function, block: &mut Block, ) -> Result, Error> { - let sequence_ty = fun_info[sequence].ty.inner_with(&ir_module.types); - match sequence_ty.indexable_length(ir_module)? { + let sequence_ty = self.fun_info[sequence].ty.inner_with(&self.ir_module.types); + match sequence_ty.indexable_length(self.ir_module)? { crate::proc::IndexableLength::Known(known_length) => { Ok(MaybeKnown::Known(known_length)) } crate::proc::IndexableLength::Dynamic => { - let length_id = - self.write_runtime_array_length(sequence, ir_function, function, block)?; + let length_id = self.write_runtime_array_length(sequence, block)?; Ok(MaybeKnown::Computed(length_id)) } crate::proc::IndexableLength::Specializable(constant) => { - let length_id = self.constant_ids[constant.index()]; + let length_id = self.writer.constant_ids[constant.index()]; Ok(MaybeKnown::Computed(length_id)) } } @@ -133,20 +128,9 @@ impl Writer { fn write_sequence_max_index( &mut self, sequence: Handle, - ir_module: &crate::Module, - ir_function: &crate::Function, - fun_info: &FunctionInfo, - function: &Function, block: &mut Block, ) -> Result, Error> { - match self.write_sequence_length( - sequence, - ir_module, - ir_function, - fun_info, - function, - block, - )? { + match self.write_sequence_length(sequence, block)? { MaybeKnown::Known(known_length) => { // We should have thrown out all attempts to subscript zero-length // sequences during validation, so the following subtraction should never @@ -158,10 +142,10 @@ impl Writer { MaybeKnown::Computed(length_id) => { // Emit code to compute the max index from the length. let const_one_id = self.get_index_constant(1)?; - let max_index_id = self.id_gen.next(); + let max_index_id = self.gen_id(); block.body.push(Instruction::binary( spirv::Op::ISub, - self.get_uint_type_id()?, + self.writer.get_uint_type_id()?, max_index_id, length_id, const_one_id, @@ -192,27 +176,16 @@ impl Writer { &mut self, sequence: Handle, index: Handle, - ir_module: &crate::Module, - ir_function: &crate::Function, - fun_info: &FunctionInfo, - function: &Function, block: &mut Block, ) -> Result { - let index_id = self.cached[index]; + let index_id = self.writer.cached[index]; // Get the sequence's maximum valid index. Return early if we've already // done the bounds check. - let max_index_id = match self.write_sequence_max_index( - sequence, - ir_module, - ir_function, - fun_info, - function, - block, - )? { + let max_index_id = match self.write_sequence_max_index(sequence, block)? { MaybeKnown::Known(known_max_index) => { - if let crate::Expression::Constant(index_k) = ir_function.expressions[index] { - if let Some(known_index) = ir_module.constants[index_k].to_array_length() { + if let crate::Expression::Constant(index_k) = self.ir_function.expressions[index] { + if let Some(known_index) = self.ir_module.constants[index_k].to_array_length() { // Both the index and length are known at compile time. // // In strict WGSL compliance mode, out-of-bounds indices cannot be @@ -231,11 +204,11 @@ impl Writer { // One or the other of the index or length is dynamic, so emit code for // IndexBoundsCheckPolicy::Restrict. - let restricted_index_id = self.id_gen.next(); + let restricted_index_id = self.gen_id(); block.body.push(Instruction::ext_inst( - self.gl450_ext_inst_id, + self.writer.gl450_ext_inst_id, spirv::GLOp::UMin, - self.get_uint_type_id()?, + self.writer.get_uint_type_id()?, restricted_index_id, &[index_id, max_index_id], )); @@ -264,27 +237,16 @@ impl Writer { &mut self, sequence: Handle, index: Handle, - ir_module: &crate::Module, - ir_function: &crate::Function, - fun_info: &FunctionInfo, - function: &mut Function, block: &mut Block, ) -> Result { - let index_id = self.cached[index]; + let index_id = self.writer.cached[index]; // Get the sequence's length. Return early if we've already done the // bounds check. - let length_id = match self.write_sequence_length( - sequence, - ir_module, - ir_function, - fun_info, - function, - block, - )? { + let length_id = match self.write_sequence_length(sequence, block)? { MaybeKnown::Known(known_length) => { - if let crate::Expression::Constant(index_k) = ir_function.expressions[index] { - if let Some(known_index) = ir_module.constants[index_k].to_array_length() { + if let crate::Expression::Constant(index_k) = self.ir_function.expressions[index] { + if let Some(known_index) = self.ir_module.constants[index_k].to_array_length() { // Both the index and length are known at compile time. // // It would be nice to assume that, since we are using the @@ -317,10 +279,10 @@ impl Writer { }; // Compare the index against the length. - let condition_id = self.id_gen.next(); + let condition_id = self.gen_id(); block.body.push(Instruction::binary( spirv::Op::ULessThan, - self.get_bool_type_id()?, + self.writer.get_bool_type_id()?, condition_id, index_id, length_id, @@ -340,7 +302,6 @@ impl Writer { &mut self, result_type: Word, condition: Word, - function: &mut Function, block: &mut Block, emit_load: F, ) -> Word @@ -348,8 +309,8 @@ impl Writer { F: FnOnce(&mut IdGenerator, &mut Block) -> Word, { let header_block = block.label_id; - let merge_block = self.id_gen.next(); - let in_bounds_block = self.id_gen.next(); + let merge_block = self.gen_id(); + let in_bounds_block = self.gen_id(); // Branch based on whether the index was in bounds. // @@ -363,26 +324,26 @@ impl Writer { merge_block, spirv::SelectionControl::NONE, )); - function.consume( + self.function.consume( std::mem::replace(block, Block::new(in_bounds_block)), Instruction::branch_conditional(condition, in_bounds_block, merge_block), ); // The in-bounds path. Perform the access and the load. - let value_id = emit_load(&mut self.id_gen, block); + let value_id = emit_load(&mut self.writer.id_gen, block); // Finish the in-bounds block and start the merge block. This // is the block we'll leave current on return. - function.consume( + self.function.consume( std::mem::replace(block, Block::new(merge_block)), Instruction::branch(merge_block), ); // For the out-of-bounds case, produce a zero value. - let null_id = self.write_constant_null(result_type); + let null_id = self.writer.write_constant_null(result_type); // Merge the results from the two paths. - let result_id = self.id_gen.next(); + let result_id = self.gen_id(); block.body.push(Instruction::phi( result_type, result_id, @@ -399,35 +360,17 @@ impl Writer { #[allow(clippy::too_many_arguments)] pub(super) fn write_bounds_check( &mut self, - ir_module: &crate::Module, - ir_function: &crate::Function, - fun_info: &FunctionInfo, - function: &mut Function, base: Handle, index: Handle, block: &mut Block, ) -> Result { - Ok(match self.index_bounds_check_policy { - IndexBoundsCheckPolicy::Restrict => self.write_restricted_index( - base, - index, - ir_module, - ir_function, - fun_info, - function, - block, - )?, - IndexBoundsCheckPolicy::ReadZeroSkipWrite => self.write_index_comparison( - base, - index, - ir_module, - ir_function, - fun_info, - function, - block, - )?, + Ok(match self.writer.index_bounds_check_policy { + IndexBoundsCheckPolicy::Restrict => self.write_restricted_index(base, index, block)?, + IndexBoundsCheckPolicy::ReadZeroSkipWrite => { + self.write_index_comparison(base, index, block)? + } IndexBoundsCheckPolicy::UndefinedBehavior => { - BoundsCheckResult::Computed(self.cached[index]) + BoundsCheckResult::Computed(self.writer.cached[index]) } }) } @@ -438,31 +381,19 @@ impl Writer { #[allow(clippy::too_many_arguments)] pub(super) fn write_vector_access( &mut self, - ir_module: &crate::Module, - ir_function: &crate::Function, - fun_info: &FunctionInfo, - function: &mut Function, expr_handle: Handle, base: Handle, index: Handle, block: &mut Block, ) -> Result { - let result_type_id = self.get_expression_type_id(&fun_info[expr_handle].ty)?; + let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty)?; - let base_id = self.cached[base]; - let index_id = self.cached[index]; + let base_id = self.writer.cached[base]; + let index_id = self.writer.cached[index]; - let result_id = match self.write_bounds_check( - ir_module, - ir_function, - fun_info, - function, - base, - index, - block, - )? { + let result_id = match self.write_bounds_check(base, index, block)? { BoundsCheckResult::KnownInBounds(known_index) => { - let result_id = self.id_gen.next(); + let result_id = self.gen_id(); block.body.push(Instruction::composite_extract( result_type_id, result_id, @@ -472,7 +403,7 @@ impl Writer { result_id } BoundsCheckResult::Computed(computed_index_id) => { - let result_id = self.id_gen.next(); + let result_id = self.gen_id(); block.body.push(Instruction::vector_extract_dynamic( result_type_id, result_id, @@ -487,7 +418,6 @@ impl Writer { self.write_conditional_indexed_load( result_type_id, comparison_id, - function, block, |id_gen, block| { // The in-bounds path. Generate the access. diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 8445b22a8..525dce218 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -258,6 +258,25 @@ struct GlobalVariable { handle_id: Word, } +/// General information needed to emit SPIR-V for Naga statements. +struct BlockContext<'w> { + /// The writer handling the module to which this code belongs. + writer: &'w mut Writer, + + /// The [`Module`](crate::Module) for which we're generating code. + ir_module: &'w crate::Module, + + /// The [`Function`](crate::Function) for which we're generating code. + ir_function: &'w crate::Function, + + /// Information module validation produced about + /// [`ir_function`](BlockContext::ir_function). + fun_info: &'w crate::valid::FunctionInfo, + + /// The [`back::spv::Function`] to which we are contributing SPIR-V instructions. + function: &'w mut Function, +} + pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 67f5501e6..7f66597b4 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,9 +1,10 @@ use super::{ helpers::{contains_builtin, map_storage_class}, index::{BoundsCheckResult, ExpressionPointer}, - Block, CachedExpressions, Dimension, EntryPointContext, Error, Function, GlobalVariable, - IdGenerator, Instruction, LocalType, LocalVariable, LogicalLayout, LookupFunctionType, - LookupType, Options, PhysicalLayout, ResultMember, Writer, WriterFlags, BITS_PER_BYTE, + Block, BlockContext, CachedExpressions, Dimension, EntryPointContext, Error, Function, + GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, LogicalLayout, + LookupFunctionType, LookupType, Options, PhysicalLayout, ResultMember, Writer, WriterFlags, + BITS_PER_BYTE, }; use crate::{ arena::{Arena, Handle}, @@ -470,36 +471,36 @@ impl Writer { .push(Instruction::load(result_type_id, id, gv.id, None)); gv.handle_id = id; } + + // Create a `BlockContext` for generating SPIR-V for the function's + // body. + let mut context = BlockContext { + writer: self, + ir_module, + ir_function, + fun_info: info, + function: &mut function, + }; + // fill up the pre-emitted expressions - self.cached.reset(ir_function.expressions.len()); + context.writer.cached.reset(ir_function.expressions.len()); for (handle, expr) in ir_function.expressions.iter() { if expr.needs_pre_emit() { - self.cache_expression_value( - ir_module, - ir_function, - info, - handle, - &mut prelude, - &mut function, - )?; + context.cache_expression_value(handle, &mut prelude)?; } } - let main_id = self.id_gen.next(); - function.consume(prelude, Instruction::branch(main_id)); - self.write_block( - main_id, - &ir_function.body, - ir_module, - ir_function, - info, - &mut function, - None, - LoopContext::default(), - )?; + let main_id = context.gen_id(); + context + .function + .consume(prelude, Instruction::branch(main_id)); + context.write_block(main_id, &ir_function.body, None, LoopContext::default())?; - function.to_words(&mut self.logical_layout.function_definitions); - Instruction::function_end().to_words(&mut self.logical_layout.function_definitions); + context + .function + .to_words(&mut context.writer.logical_layout.function_definitions); + Instruction::function_end() + .to_words(&mut context.writer.logical_layout.function_definitions); Ok(function_id) } @@ -1333,16 +1334,31 @@ impl Writer { } } -impl Writer { +impl<'w> BlockContext<'w> { + pub(super) fn gen_id(&mut self) -> Word { + self.writer.id_gen.next() + } + + fn get_type_id(&mut self, lookup_type: LookupType) -> Result { + self.writer.get_type_id(lookup_type) + } + + pub(super) fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Result { + self.writer.get_expression_type_id(tr) + } + + pub(super) fn get_index_constant(&mut self, index: Word) -> Result { + self.writer + .get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) + } + fn write_texture_coordinates( &mut self, - ir_module: &crate::Module, - fun_info: &FunctionInfo, coordinates: Handle, array_index: Option>, block: &mut Block, ) -> Result { - let coordinate_id = self.cached[coordinates]; + let coordinate_id = self.writer.cached[coordinates]; Ok(if let Some(array_index) = array_index { let coordinate_scalar_type_id = @@ -1354,14 +1370,17 @@ impl Writer { }))?; let mut constituent_ids = [0u32; 4]; - let size = match *fun_info[coordinates].ty.inner_with(&ir_module.types) { + let size = match *self.fun_info[coordinates] + .ty + .inner_with(&self.ir_module.types) + { crate::TypeInner::Scalar { .. } => { constituent_ids[0] = coordinate_id; crate::VectorSize::Bi } crate::TypeInner::Vector { size, .. } => { for i in 0..size as u32 { - let id = self.id_gen.next(); + let id = self.gen_id(); constituent_ids[i as usize] = id; block.body.push(Instruction::composite_extract( coordinate_scalar_type_id, @@ -1384,10 +1403,10 @@ impl Writer { } }; - let array_index_f32_id = self.id_gen.next(); + let array_index_f32_id = self.gen_id(); constituent_ids[size as usize - 1] = array_index_f32_id; - let array_index_u32_id = self.cached[array_index]; + let array_index_u32_id = self.writer.cached[array_index]; let cast_instruction = Instruction::unary( spirv::Op::ConvertUToF, coordinate_scalar_type_id, @@ -1404,7 +1423,7 @@ impl Writer { pointer_class: None, }))?; - let id = self.id_gen.next(); + let id = self.gen_id(); block.body.push(Instruction::composite_construct( extended_coordinate_type_id, id, @@ -1421,21 +1440,16 @@ impl Writer { /// We would like to gather together chains of `Access` and `AccessIndex` /// Naga expressions into a single `OpAccessChain` SPIR-V instruction. To do /// this, we don't generate instructions for these exprs when we first - /// encounter them. Their ids in `self.cached.ids` are left as zero. Then, + /// encounter them. Their ids in `self.writer.cached.ids` are left as zero. Then, /// once we encounter a `Load` or `Store` expression that actually needs the /// chain's value, we call `write_expression_pointer` to handle the whole /// thing in one fell swoop. - fn is_intermediate( - &self, - expr_handle: Handle, - ir_function: &crate::Function, - ir_types: &Arena, - ) -> bool { - match ir_function.expressions[expr_handle] { + fn is_intermediate(&self, expr_handle: Handle) -> bool { + match self.ir_function.expressions[expr_handle] { crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => true, crate::Expression::FunctionArgument(index) => { - let arg = &ir_function.arguments[index as usize]; - match ir_types[arg.ty].inner { + let arg = &self.ir_function.arguments[index as usize]; + match self.ir_module.types[arg.ty].inner { crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { true } @@ -1445,38 +1459,32 @@ impl Writer { // The chain rule: if this `Access...`'s `base` operand was // previously omitted, then omit this one, too. - _ => self.cached.ids[expr_handle.index()] == 0, + _ => self.writer.cached.ids[expr_handle.index()] == 0, } } /// Cache an expression for a value. fn cache_expression_value( &mut self, - ir_module: &crate::Module, - ir_function: &crate::Function, - fun_info: &FunctionInfo, expr_handle: Handle, block: &mut Block, - function: &mut Function, ) -> Result<(), Error> { - let result_type_id = self.get_expression_type_id(&fun_info[expr_handle].ty)?; + let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty)?; - let id = match ir_function.expressions[expr_handle] { - crate::Expression::Access { base, index: _ } - if self.is_intermediate(base, ir_function, &ir_module.types) => - { + let id = match self.ir_function.expressions[expr_handle] { + crate::Expression::Access { base, index: _ } if self.is_intermediate(base) => { // See `is_intermediate`; we'll handle this later in // `write_expression_pointer`. 0 } crate::Expression::Access { base, index } => { - let base_ty = fun_info[base].ty.inner_with(&ir_module.types); + let base_ty = self.fun_info[base].ty.inner_with(&self.ir_module.types); match *base_ty { crate::TypeInner::Vector { .. } => (), ref other => { log::error!( "Unable to access base {:?} of type {:?}", - ir_function.expressions[base], + self.ir_function.expressions[base], other ); return Err(Error::Validation( @@ -1485,32 +1493,21 @@ impl Writer { } }; - self.write_vector_access( - ir_module, - ir_function, - fun_info, - function, - expr_handle, - base, - index, - block, - )? + self.write_vector_access(expr_handle, base, index, block)? } - crate::Expression::AccessIndex { base, index: _ } - if self.is_intermediate(base, ir_function, &ir_module.types) => - { + crate::Expression::AccessIndex { base, index: _ } if self.is_intermediate(base) => { // See `is_intermediate`; we'll handle this later in // `write_expression_pointer`. 0 } crate::Expression::AccessIndex { base, index } => { - match *fun_info[base].ty.inner_with(&ir_module.types) { + match *self.fun_info[base].ty.inner_with(&self.ir_module.types) { crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } | crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { - let id = self.id_gen.next(); - let base_id = self.cached[base]; + let id = self.gen_id(); + let base_id = self.writer.cached[base]; block.body.push(Instruction::composite_extract( result_type_id, id, @@ -1525,18 +1522,20 @@ impl Writer { } } } - crate::Expression::GlobalVariable(handle) => self.global_variables[handle.index()].id, - crate::Expression::Constant(handle) => self.constant_ids[handle.index()], + crate::Expression::GlobalVariable(handle) => { + self.writer.global_variables[handle.index()].id + } + crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], crate::Expression::Splat { size, value } => { - let value_id = self.cached[value]; - self.temp_list.clear(); - self.temp_list.resize(size as usize, value_id); + let value_id = self.writer.cached[value]; + self.writer.temp_list.clear(); + self.writer.temp_list.resize(size as usize, value_id); - let id = self.id_gen.next(); + let id = self.gen_id(); block.body.push(Instruction::composite_construct( result_type_id, id, - &self.temp_list, + &self.writer.temp_list, )); id } @@ -1545,18 +1544,18 @@ impl Writer { vector, pattern, } => { - let vector_id = self.cached[vector]; - self.temp_list.clear(); + let vector_id = self.writer.cached[vector]; + self.writer.temp_list.clear(); for &sc in pattern[..size as usize].iter() { - self.temp_list.push(sc as Word); + self.writer.temp_list.push(sc as Word); } - let id = self.id_gen.next(); + let id = self.gen_id(); block.body.push(Instruction::vector_shuffle( result_type_id, id, vector_id, vector_id, - &self.temp_list, + &self.writer.temp_list, )); id } @@ -1564,23 +1563,23 @@ impl Writer { ty: _, ref components, } => { - self.temp_list.clear(); + self.writer.temp_list.clear(); for &component in components { - self.temp_list.push(self.cached[component]); + self.writer.temp_list.push(self.writer.cached[component]); } - let id = self.id_gen.next(); + let id = self.gen_id(); block.body.push(Instruction::composite_construct( result_type_id, id, - &self.temp_list, + &self.writer.temp_list, )); id } crate::Expression::Unary { op, expr } => { - let id = self.id_gen.next(); - let expr_id = self.cached[expr]; - let expr_ty_inner = fun_info[expr].ty.inner_with(&ir_module.types); + let id = self.gen_id(); + let expr_id = self.writer.cached[expr]; + let expr_ty_inner = self.fun_info[expr].ty.inner_with(&self.ir_module.types); let spirv_op = match op { crate::UnaryOperator::Negate => match expr_ty_inner.scalar_kind() { @@ -1604,12 +1603,12 @@ impl Writer { id } crate::Expression::Binary { op, left, right } => { - let id = self.id_gen.next(); - let left_id = self.cached[left]; - let right_id = self.cached[right]; + let id = self.gen_id(); + let left_id = self.writer.cached[left]; + let right_id = self.writer.cached[right]; - let left_ty_inner = fun_info[left].ty.inner_with(&ir_module.types); - let right_ty_inner = fun_info[right].ty.inner_with(&ir_module.types); + let left_ty_inner = self.fun_info[left].ty.inner_with(&self.ir_module.types); + let right_ty_inner = self.fun_info[right].ty.inner_with(&self.ir_module.types); let left_dimension = get_dimension(left_ty_inner); let right_dimension = get_dimension(right_ty_inner); @@ -1743,18 +1742,21 @@ impl Writer { Custom(Instruction), } - let arg0_id = self.cached[arg]; - let arg_scalar_kind = fun_info[arg].ty.inner_with(&ir_module.types).scalar_kind(); + let arg0_id = self.writer.cached[arg]; + let arg_scalar_kind = self.fun_info[arg] + .ty + .inner_with(&self.ir_module.types) + .scalar_kind(); let arg1_id = match arg1 { - Some(handle) => self.cached[handle], + Some(handle) => self.writer.cached[handle], None => 0, }; let arg2_id = match arg2 { - Some(handle) => self.cached[handle], + Some(handle) => self.writer.cached[handle], None => 0, }; - let id = self.id_gen.next(); + let id = self.gen_id(); let math_op = match fun { // comparison Mf::Abs => { @@ -1866,7 +1868,7 @@ impl Writer { block.body.push(match math_op { MathOp::Ext(op) => Instruction::ext_inst( - self.gl450_ext_inst_id, + self.writer.gl450_ext_inst_id, op, result_type_id, id, @@ -1876,18 +1878,11 @@ impl Writer { }); id } - crate::Expression::LocalVariable(variable) => function.variables[&variable].id, + crate::Expression::LocalVariable(variable) => self.function.variables[&variable].id, crate::Expression::Load { pointer } => { - match self.write_expression_pointer( - ir_module, - ir_function, - fun_info, - pointer, - block, - function, - )? { + match self.write_expression_pointer(pointer, block)? { ExpressionPointer::Ready { pointer_id } => { - let id = self.id_gen.next(); + let id = self.gen_id(); block .body .push(Instruction::load(result_type_id, id, pointer_id, None)); @@ -1897,7 +1892,6 @@ impl Writer { self.write_conditional_indexed_load( result_type_id, condition, - function, block, move |id_gen, block| { // The in-bounds path. Perform the access and the load. @@ -1916,8 +1910,8 @@ impl Writer { } } } - crate::Expression::FunctionArgument(index) => function.parameter_id(index), - crate::Expression::Call(_function) => self.lookup_function_call[&expr_handle], + crate::Expression::FunctionArgument(index) => self.function.parameter_id(index), + crate::Expression::Call(_function) => self.writer.lookup_function_call[&expr_handle], crate::Expression::As { expr, kind, @@ -1925,20 +1919,21 @@ impl Writer { } => { use crate::ScalarKind as Sk; - let expr_id = self.cached[expr]; - let (src_kind, src_width) = match *fun_info[expr].ty.inner_with(&ir_module.types) { - crate::TypeInner::Scalar { kind, width } - | crate::TypeInner::Vector { - kind, - width, - size: _, - } => (kind, width), - crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), - ref other => { - log::error!("As source {:?}", other); - return Err(Error::Validation("Unexpected Expression::As source")); - } - }; + let expr_id = self.writer.cached[expr]; + let (src_kind, src_width) = + match *self.fun_info[expr].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Scalar { kind, width } + | crate::TypeInner::Vector { + kind, + width, + size: _, + } => (kind, width), + crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), + ref other => { + log::error!("As source {:?}", other); + return Err(Error::Validation("Unexpected Expression::As source")); + } + }; let op = match (src_kind, kind, convert) { (_, _, None) => spirv::Op::Bitcast, @@ -1959,7 +1954,7 @@ impl Writer { _ => spirv::Op::Bitcast, }; - let id = self.id_gen.next(); + let id = self.gen_id(); let instruction = Instruction::unary(op, result_type_id, id, expr_id); block.body.push(instruction); id @@ -1970,18 +1965,13 @@ impl Writer { array_index, index, } => { - let image_id = self.get_expression_global(ir_function, image); - let coordinate_id = self.write_texture_coordinates( - ir_module, - fun_info, - coordinate, - array_index, - block, - )?; + let image_id = self.get_expression_global(image); + let coordinate_id = + self.write_texture_coordinates(coordinate, array_index, block)?; - let id = self.id_gen.next(); + let id = self.gen_id(); - let image_ty = fun_info[image].ty.inner_with(&ir_module.types); + let image_ty = self.fun_info[image].ty.inner_with(&self.ir_module.types); let mut instruction = match *image_ty { crate::TypeInner::Image { class: crate::ImageClass::Storage { .. }, @@ -2006,8 +1996,9 @@ impl Writer { }; if let Some(index) = index { - let index_id = self.cached[index]; - let image_ops = match *fun_info[image].ty.inner_with(&ir_module.types) { + let index_id = self.writer.cached[index]; + let image_ops = match *self.fun_info[image].ty.inner_with(&self.ir_module.types) + { crate::TypeInner::Image { class: crate::ImageClass::Sampled { multi: true, .. }, .. @@ -2021,7 +2012,7 @@ impl Writer { let inst_type_id = instruction.type_id; block.body.push(instruction); if inst_type_id != Some(result_type_id) { - let sub_id = self.id_gen.next(); + let sub_id = self.gen_id(); block.body.push(Instruction::composite_extract( result_type_id, sub_id, @@ -2044,11 +2035,11 @@ impl Writer { } => { use super::instructions::SampleLod; // image - let image_id = self.get_expression_global(ir_function, image); - let image_type = fun_info[image].ty.handle().unwrap(); + let image_id = self.get_expression_global(image); + let image_type = self.fun_info[image].ty.handle().unwrap(); // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, // so we need to grab the first component out of it. - let needs_sub_access = match ir_module.types[image_type].inner { + let needs_sub_access = match self.ir_module.types[image_type].inner { crate::TypeInner::Image { class: crate::ImageClass::Depth, .. @@ -2071,25 +2062,20 @@ impl Writer { let sampled_image_type_id = self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id }))?; - let sampler_id = self.get_expression_global(ir_function, sampler); - let coordinate_id = self.write_texture_coordinates( - ir_module, - fun_info, - coordinate, - array_index, - block, - )?; + let sampler_id = self.get_expression_global(sampler); + let coordinate_id = + self.write_texture_coordinates(coordinate, array_index, block)?; - let sampled_image_id = self.id_gen.next(); + let sampled_image_id = self.gen_id(); block.body.push(Instruction::sampled_image( sampled_image_type_id, sampled_image_id, image_id, sampler_id, )); - let id = self.id_gen.next(); + let id = self.gen_id(); - let depth_id = depth_ref.map(|handle| self.cached[handle]); + let depth_id = depth_ref.map(|handle| self.writer.cached[handle]); let mut mask = spirv::ImageOperands::empty(); mask.set(spirv::ImageOperands::CONST_OFFSET, offset.is_some()); @@ -2104,8 +2090,9 @@ impl Writer { depth_id, ); - let zero_id = - self.get_constant_scalar(crate::ScalarValue::Float(0.0), 4)?; + let zero_id = self + .writer + .get_constant_scalar(crate::ScalarValue::Float(0.0), 4)?; mask |= spirv::ImageOperands::LOD; inst.add_operand(mask.bits()); @@ -2137,7 +2124,7 @@ impl Writer { depth_id, ); - let lod_id = self.cached[lod_handle]; + let lod_id = self.writer.cached[lod_handle]; mask |= spirv::ImageOperands::LOD; inst.add_operand(mask.bits()); inst.add_operand(lod_id); @@ -2154,7 +2141,7 @@ impl Writer { depth_id, ); - let bias_id = self.cached[bias_handle]; + let bias_id = self.writer.cached[bias_handle]; mask |= spirv::ImageOperands::BIAS; inst.add_operand(mask.bits()); inst.add_operand(bias_id); @@ -2171,8 +2158,8 @@ impl Writer { depth_id, ); - let x_id = self.cached[x]; - let y_id = self.cached[y]; + let x_id = self.writer.cached[x]; + let y_id = self.writer.cached[y]; mask |= spirv::ImageOperands::GRAD; inst.add_operand(mask.bits()); inst.add_operand(x_id); @@ -2183,14 +2170,14 @@ impl Writer { }; if let Some(offset_const) = offset { - let offset_id = self.constant_ids[offset_const.index()]; + let offset_id = self.writer.constant_ids[offset_const.index()]; main_instruction.add_operand(offset_id); } block.body.push(main_instruction); if needs_sub_access { - let sub_id = self.id_gen.next(); + let sub_id = self.gen_id(); block.body.push(Instruction::composite_extract( result_type_id, sub_id, @@ -2207,10 +2194,10 @@ impl Writer { accept, reject, } => { - let id = self.id_gen.next(); - let condition_id = self.cached[condition]; - let accept_id = self.cached[accept]; - let reject_id = self.cached[reject]; + let id = self.gen_id(); + let condition_id = self.writer.cached[condition]; + let accept_id = self.writer.cached[accept]; + let reject_id = self.writer.cached[reject]; let instruction = Instruction::select(result_type_id, id, condition_id, accept_id, reject_id); @@ -2220,8 +2207,8 @@ impl Writer { crate::Expression::Derivative { axis, expr } => { use crate::DerivativeAxis as Da; - let id = self.id_gen.next(); - let expr_id = self.cached[expr]; + let id = self.gen_id(); + let expr_id = self.writer.cached[expr]; let op = match axis { Da::X => spirv::Op::DPdx, Da::Y => spirv::Op::DPdy, @@ -2235,9 +2222,9 @@ impl Writer { crate::Expression::ImageQuery { image, query } => { use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq}; - let image_id = self.get_expression_global(ir_function, image); - let image_type = fun_info[image].ty.handle().unwrap(); - let (dim, arrayed, class) = match ir_module.types[image_type].inner { + let image_id = self.get_expression_global(image); + let image_type = self.fun_info[image].ty.handle().unwrap(); + let (dim, arrayed, class) = match self.ir_module.types[image_type].inner { crate::TypeInner::Image { dim, arrayed, @@ -2248,7 +2235,7 @@ impl Writer { } }; - self.check(&[spirv::Capability::ImageQuery])?; + self.writer.check(&[spirv::Capability::ImageQuery])?; match query { Iq::Size { level } => { @@ -2277,7 +2264,7 @@ impl Writer { Ic::Storage(_) => (spirv::Op::ImageQuerySize, None), _ => { let level_id = match level { - Some(expr) => self.cached[expr], + Some(expr) => self.writer.cached[expr], None => self.get_index_constant(0)?, }; (spirv::Op::ImageQuerySizeLod, Some(level_id)) @@ -2286,7 +2273,7 @@ impl Writer { // The ID of the vector returned by SPIR-V, which contains the dimensions // as well as the layer count. - let id_extended = self.id_gen.next(); + let id_extended = self.gen_id(); let mut inst = Instruction::image_query( query_op, extended_size_type_id, @@ -2299,7 +2286,7 @@ impl Writer { block.body.push(inst); if result_type_id != extended_size_type_id { - let id = self.id_gen.next(); + let id = self.gen_id(); let components = match dim { // always pick the first component, and duplicate it for all 3 dimensions Id::Cube => &[0u32, 0, 0][..], @@ -2318,7 +2305,7 @@ impl Writer { } } Iq::NumLevels => { - let id = self.id_gen.next(); + let id = self.gen_id(); block.body.push(Instruction::image_query( spirv::Op::ImageQueryLevels, result_type_id, @@ -2340,7 +2327,7 @@ impl Writer { width: 4, pointer_class: None, }))?; - let id_extended = self.id_gen.next(); + let id_extended = self.gen_id(); let mut inst = Instruction::image_query( spirv::Op::ImageQuerySizeLod, extended_size_type_id, @@ -2349,7 +2336,7 @@ impl Writer { ); inst.add_operand(self.get_index_constant(0)?); block.body.push(inst); - let id = self.id_gen.next(); + let id = self.gen_id(); block.body.push(Instruction::composite_extract( result_type_id, id, @@ -2359,7 +2346,7 @@ impl Writer { id } Iq::NumSamples => { - let id = self.id_gen.next(); + let id = self.gen_id(); block.body.push(Instruction::image_query( spirv::Op::ImageQuerySamples, result_type_id, @@ -2372,7 +2359,7 @@ impl Writer { } crate::Expression::Relational { fun, argument } => { use crate::RelationalFunction as Rf; - let arg_id = self.cached[argument]; + let arg_id = self.writer.cached[argument]; let op = match fun { Rf::All => spirv::Op::All, Rf::Any => spirv::Op::Any, @@ -2383,18 +2370,16 @@ impl Writer { return Err(Error::FeatureNotImplemented("is finite/normal")) } }; - let id = self.id_gen.next(); + let id = self.gen_id(); block .body .push(Instruction::relational(op, result_type_id, id, arg_id)); id } - crate::Expression::ArrayLength(expr) => { - self.write_runtime_array_length(expr, ir_function, function, block)? - } + crate::Expression::ArrayLength(expr) => self.write_runtime_array_length(expr, block)?, }; - self.cached[expr_handle] = id; + self.writer.cached[expr_handle] = id; Ok(()) } @@ -2406,17 +2391,13 @@ impl Writer { /// documentation for that type. fn write_expression_pointer( &mut self, - ir_module: &crate::Module, - ir_function: &crate::Function, - fun_info: &FunctionInfo, mut expr_handle: Handle, block: &mut Block, - function: &mut Function, ) -> Result { - let result_lookup_ty = match fun_info[expr_handle].ty { + let result_lookup_ty = match self.fun_info[expr_handle].ty { TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), TypeResolution::Value(ref inner) => { - LookupType::Local(self.physical_layout.make_local(inner).unwrap()) + LookupType::Local(self.writer.physical_layout.make_local(inner).unwrap()) } }; let result_type_id = self.get_type_id(result_lookup_ty)?; @@ -2430,33 +2411,25 @@ impl Writer { // minimum is essential. let mut accumulated_checks = None; - self.temp_list.clear(); + self.writer.temp_list.clear(); let root_id = loop { - expr_handle = match ir_function.expressions[expr_handle] { + expr_handle = match self.ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { - let index_id = match self.write_bounds_check( - ir_module, - ir_function, - fun_info, - function, - base, - index, - block, - )? { + let index_id = match self.write_bounds_check(base, index, block)? { BoundsCheckResult::KnownInBounds(known_index) => { // Even if the index is known, `OpAccessIndex` // requires expression operands, not literals. let scalar = crate::ScalarValue::Uint(known_index as u64); - self.get_constant_scalar(scalar, 4)? + self.writer.get_constant_scalar(scalar, 4)? } BoundsCheckResult::Computed(computed_index_id) => computed_index_id, BoundsCheckResult::Conditional(comparison_id) => { match accumulated_checks { Some(prior_checks) => { - let combined = self.id_gen.next(); + let combined = self.gen_id(); block.body.push(Instruction::binary( spirv::Op::LogicalAnd, - self.get_bool_type_id()?, + self.writer.get_bool_type_id()?, combined, prior_checks, comparison_id, @@ -2470,43 +2443,47 @@ impl Writer { } // Either way, the index to use is unchanged. - self.cached[index] + self.writer.cached[index] } }; - self.temp_list.push(index_id); + self.writer.temp_list.push(index_id); base } crate::Expression::AccessIndex { base, index } => { let const_id = self.get_index_constant(index)?; - self.temp_list.push(const_id); + self.writer.temp_list.push(const_id); base } crate::Expression::GlobalVariable(handle) => { - let gv = &self.global_variables[handle.index()]; + let gv = &self.writer.global_variables[handle.index()]; break gv.id; } crate::Expression::LocalVariable(variable) => { - let local_var = &function.variables[&variable]; + let local_var = &self.function.variables[&variable]; break local_var.id; } crate::Expression::FunctionArgument(index) => { - let id = function.parameters[index as usize].result_id.unwrap(); + let id = self.function.parameters[index as usize].result_id.unwrap(); break id; } ref other => unimplemented!("Unexpected pointer expression {:?}", other), } }; - let pointer = if self.temp_list.is_empty() { + let pointer = if self.writer.temp_list.is_empty() { ExpressionPointer::Ready { pointer_id: root_id, } } else { - self.temp_list.reverse(); - let pointer_id = self.id_gen.next(); - let access = - Instruction::access_chain(result_type_id, pointer_id, root_id, &self.temp_list); + self.writer.temp_list.reverse(); + let pointer_id = self.gen_id(); + let access = Instruction::access_chain( + result_type_id, + pointer_id, + root_id, + &self.writer.temp_list, + ); // If we generated some bounds checks, we need to leave it to our // caller to generate the branch, the access, the load or store, and @@ -2524,14 +2501,10 @@ impl Writer { Ok(pointer) } - fn get_expression_global( - &self, - ir_function: &crate::Function, - expr_handle: Handle, - ) -> Word { - match ir_function.expressions[expr_handle] { + fn get_expression_global(&self, expr_handle: Handle) -> Word { + match self.ir_function.expressions[expr_handle] { crate::Expression::GlobalVariable(handle) => { - let id = self.global_variables[handle.index()].handle_id; + let id = self.writer.global_variables[handle.index()].handle_id; if id == 0 { unreachable!("Global variable {:?} doesn't have a handle ID", handle); } @@ -2547,10 +2520,6 @@ impl Writer { &mut self, label_id: Word, statements: &[crate::Statement], - ir_module: &crate::Module, - ir_function: &crate::Function, - fun_info: &FunctionInfo, - function: &mut Function, exit_id: Option, loop_context: LoopContext, ) -> Result<(), Error> { @@ -2560,31 +2529,15 @@ impl Writer { match *statement { crate::Statement::Emit(ref range) => { for handle in range.clone() { - self.cache_expression_value( - ir_module, - ir_function, - fun_info, - handle, - &mut block, - function, - )?; + self.cache_expression_value(handle, &mut block)?; } } crate::Statement::Block(ref block_statements) => { - let scope_id = self.id_gen.next(); - function.consume(block, Instruction::branch(scope_id)); + let scope_id = self.gen_id(); + self.function.consume(block, Instruction::branch(scope_id)); - let merge_id = self.id_gen.next(); - self.write_block( - scope_id, - block_statements, - ir_module, - ir_function, - fun_info, - function, - Some(merge_id), - loop_context, - )?; + let merge_id = self.gen_id(); + self.write_block(scope_id, block_statements, Some(merge_id), loop_context)?; block = Block::new(merge_id); } @@ -2593,9 +2546,9 @@ impl Writer { ref accept, ref reject, } => { - let condition_id = self.cached[condition]; + let condition_id = self.writer.cached[condition]; - let merge_id = self.id_gen.next(); + let merge_id = self.gen_id(); block.body.push(Instruction::selection_merge( merge_id, spirv::SelectionControl::NONE, @@ -2604,15 +2557,15 @@ impl Writer { let accept_id = if accept.is_empty() { None } else { - Some(self.id_gen.next()) + Some(self.gen_id()) }; let reject_id = if reject.is_empty() { None } else { - Some(self.id_gen.next()) + Some(self.gen_id()) }; - function.consume( + self.function.consume( block, Instruction::branch_conditional( condition_id, @@ -2622,28 +2575,10 @@ impl Writer { ); if let Some(block_id) = accept_id { - self.write_block( - block_id, - accept, - ir_module, - ir_function, - fun_info, - function, - Some(merge_id), - loop_context, - )?; + self.write_block(block_id, accept, Some(merge_id), loop_context)?; } if let Some(block_id) = reject_id { - self.write_block( - block_id, - reject, - ir_module, - ir_function, - fun_info, - function, - Some(merge_id), - loop_context, - )?; + self.write_block(block_id, reject, Some(merge_id), loop_context)?; } block = Block::new(merge_id); @@ -2653,24 +2588,24 @@ impl Writer { ref cases, ref default, } => { - let selector_id = self.cached[selector]; + let selector_id = self.writer.cached[selector]; - let merge_id = self.id_gen.next(); + let merge_id = self.gen_id(); block.body.push(Instruction::selection_merge( merge_id, spirv::SelectionControl::NONE, )); - let default_id = self.id_gen.next(); + let default_id = self.gen_id(); let raw_cases = cases .iter() .map(|c| super::instructions::Case { value: c.value as Word, - label_id: self.id_gen.next(), + label_id: self.gen_id(), }) .collect::>(); - function.consume( + self.function.consume( block, Instruction::switch(selector_id, default_id, &raw_cases), ); @@ -2687,25 +2622,12 @@ impl Writer { self.write_block( raw_case.label_id, &case.body, - ir_module, - ir_function, - fun_info, - function, Some(case_finish_id), LoopContext::default(), )?; } - self.write_block( - default_id, - default, - ir_module, - ir_function, - fun_info, - function, - Some(merge_id), - LoopContext::default(), - )?; + self.write_block(default_id, default, Some(merge_id), LoopContext::default())?; block = Block::new(merge_id); } @@ -2713,12 +2635,13 @@ impl Writer { ref body, ref continuing, } => { - let preamble_id = self.id_gen.next(); - function.consume(block, Instruction::branch(preamble_id)); + let preamble_id = self.gen_id(); + self.function + .consume(block, Instruction::branch(preamble_id)); - let merge_id = self.id_gen.next(); - let body_id = self.id_gen.next(); - let continuing_id = self.id_gen.next(); + let merge_id = self.gen_id(); + let body_id = self.gen_id(); + let continuing_id = self.gen_id(); // SPIR-V requires the continuing to the `OpLoopMerge`, // so we have to start a new block with it. @@ -2728,15 +2651,11 @@ impl Writer { continuing_id, spirv::SelectionControl::NONE, )); - function.consume(block, Instruction::branch(body_id)); + self.function.consume(block, Instruction::branch(body_id)); self.write_block( body_id, body, - ir_module, - ir_function, - fun_info, - function, Some(continuing_id), LoopContext { continuing_id: Some(continuing_id), @@ -2747,10 +2666,6 @@ impl Writer { self.write_block( continuing_id, continuing, - ir_module, - ir_function, - fun_info, - function, Some(preamble_id), LoopContext { continuing_id: None, @@ -2761,25 +2676,26 @@ impl Writer { block = Block::new(merge_id); } crate::Statement::Break => { - function.consume(block, Instruction::branch(loop_context.break_id.unwrap())); + self.function + .consume(block, Instruction::branch(loop_context.break_id.unwrap())); return Ok(()); } crate::Statement::Continue => { - function.consume( + self.function.consume( block, Instruction::branch(loop_context.continuing_id.unwrap()), ); return Ok(()); } crate::Statement::Return { value: Some(value) } => { - let value_id = self.cached[value]; - let instruction = match function.entry_point_context { + let value_id = self.writer.cached[value]; + let instruction = match self.function.entry_point_context { // If this is an entry point, and we need to return anything, // let's instead store the output variables and return `void`. Some(ref context) => { - self.write_entry_point_return( + self.writer.write_entry_point_return( value_id, - ir_function.result.as_ref().unwrap(), + self.ir_function.result.as_ref().unwrap(), &context.results, &mut block.body, )?; @@ -2787,15 +2703,15 @@ impl Writer { } None => Instruction::return_value(value_id), }; - function.consume(block, instruction); + self.function.consume(block, instruction); return Ok(()); } crate::Statement::Return { value: None } => { - function.consume(block, Instruction::return_void()); + self.function.consume(block, Instruction::return_void()); return Ok(()); } crate::Statement::Kill => { - function.consume(block, Instruction::kill()); + self.function.consume(block, Instruction::kill()); return Ok(()); } crate::Statement::Barrier(flags) => { @@ -2823,30 +2739,23 @@ impl Writer { )); } crate::Statement::Store { pointer, value } => { - let value_id = self.cached[value]; - match self.write_expression_pointer( - ir_module, - ir_function, - fun_info, - pointer, - &mut block, - function, - )? { + let value_id = self.writer.cached[value]; + match self.write_expression_pointer(pointer, &mut block)? { ExpressionPointer::Ready { pointer_id } => { block .body .push(Instruction::store(pointer_id, value_id, None)); } ExpressionPointer::Conditional { condition, access } => { - let merge_block = self.id_gen.next(); - let in_bounds_block = self.id_gen.next(); + let merge_block = self.gen_id(); + let in_bounds_block = self.gen_id(); // Emit the conditional branch. block.body.push(Instruction::selection_merge( merge_block, spirv::SelectionControl::NONE, )); - function.consume( + self.function.consume( std::mem::replace(&mut block, Block::new(in_bounds_block)), Instruction::branch_conditional( condition, @@ -2864,7 +2773,7 @@ impl Writer { // Finish the in-bounds block and start the merge block. This // is the block we'll leave current on return. - function.consume( + self.function.consume( std::mem::replace(&mut block, Block::new(merge_block)), Instruction::branch(merge_block), ); @@ -2877,15 +2786,10 @@ impl Writer { array_index, value, } => { - let image_id = self.get_expression_global(ir_function, image); - let coordinate_id = self.write_texture_coordinates( - ir_module, - fun_info, - coordinate, - array_index, - &mut block, - )?; - let value_id = self.cached[value]; + let image_id = self.get_expression_global(image); + let coordinate_id = + self.write_texture_coordinates(coordinate, array_index, &mut block)?; + let value_id = self.writer.cached[value]; block .body @@ -2896,31 +2800,31 @@ impl Writer { ref arguments, result, } => { - let id = self.id_gen.next(); - self.temp_list.clear(); + let id = self.gen_id(); + self.writer.temp_list.clear(); for &argument in arguments { - self.temp_list.push(self.cached[argument]); + self.writer.temp_list.push(self.writer.cached[argument]); } let type_id = match result { Some(expr) => { - self.cached[expr] = id; - self.lookup_function_call.insert(expr, id); - let ty_handle = ir_module.functions[local_function] + self.writer.cached[expr] = id; + self.writer.lookup_function_call.insert(expr, id); + let ty_handle = self.ir_module.functions[local_function] .result .as_ref() .unwrap() .ty; self.get_type_id(LookupType::Handle(ty_handle))? } - None => self.void_type, + None => self.writer.void_type, }; block.body.push(Instruction::function_call( type_id, id, - self.lookup_function[&local_function], - &self.temp_list, + self.writer.lookup_function[&local_function], + &self.writer.temp_list, )); } } @@ -2930,18 +2834,18 @@ impl Writer { Some(id) => Instruction::branch(id), // This can happen if the last branch had all the paths // leading out of the graph (i.e. returning). - // Or it may be the end of the function. - None => match ir_function.result { - Some(ref result) if function.entry_point_context.is_none() => { + // Or it may be the end of the self.function. + None => match self.ir_function.result { + Some(ref result) if self.function.entry_point_context.is_none() => { let type_id = self.get_type_id(LookupType::Handle(result.ty))?; - let null_id = self.write_constant_null(type_id); + let null_id = self.writer.write_constant_null(type_id); Instruction::return_value(null_id) } _ => Instruction::return_void(), }, }; - function.consume(block, termination); + self.function.consume(block, termination); Ok(()) } } From 9f7424c3af3e4724cef814b39e00d07cb222d859 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 25 Jun 2021 23:09:01 -0700 Subject: [PATCH 1057/2212] [spv-out]: Remove all #[allow(clippy::too_many_arguments)] attrs. --- src/back/spv/index.rs | 4 ---- src/back/spv/writer.rs | 1 - 2 files changed, 5 deletions(-) diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 76082ba33..30d9a51e8 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -171,7 +171,6 @@ impl<'w> BlockContext<'w> { /// `Pointer` to any of those, or a `ValuePointer`. An array may be /// fixed-size, dynamically sized, or use a specializable constant as its /// length. - #[allow(clippy::too_many_arguments)] pub(super) fn write_restricted_index( &mut self, sequence: Handle, @@ -232,7 +231,6 @@ impl<'w> BlockContext<'w> { /// `Pointer` to any of those, or a `ValuePointer`. An array may be /// fixed-size, dynamically sized, or use a specializable constant as its /// length. - #[allow(clippy::too_many_arguments)] fn write_index_comparison( &mut self, sequence: Handle, @@ -357,7 +355,6 @@ impl<'w> BlockContext<'w> { /// /// Return a `BoundsCheckResult` indicating how the index should be /// consumed. See that type's documentation for details. - #[allow(clippy::too_many_arguments)] pub(super) fn write_bounds_check( &mut self, base: Handle, @@ -378,7 +375,6 @@ impl<'w> BlockContext<'w> { /// Emit code to subscript a vector by value with a computed index. /// /// Return the id of the element value. - #[allow(clippy::too_many_arguments)] pub(super) fn write_vector_access( &mut self, expr_handle: Handle, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 7f66597b4..45680945c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -2515,7 +2515,6 @@ impl<'w> BlockContext<'w> { } //TODO: put most of these into a `BlockContext` structure! - #[allow(clippy::too_many_arguments)] fn write_block( &mut self, label_id: Word, From f878a9dcaf4a98486a13ce1c86aabd858e404b61 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 25 Jun 2021 23:30:43 -0700 Subject: [PATCH 1058/2212] [spv-out]: Introduce helpers for BlockContext code. Give `BlockContext` its own `temp_list`, which it steals from `Writer` for a bit. Add `BlockContext::cached`, for getting cached expression ids. --- src/back/spv/index.rs | 10 ++-- src/back/spv/mod.rs | 3 + src/back/spv/writer.rs | 122 +++++++++++++++++++++-------------------- 3 files changed, 71 insertions(+), 64 deletions(-) diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 30d9a51e8..2de9994e5 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -177,7 +177,7 @@ impl<'w> BlockContext<'w> { index: Handle, block: &mut Block, ) -> Result { - let index_id = self.writer.cached[index]; + let index_id = self.cached(index); // Get the sequence's maximum valid index. Return early if we've already // done the bounds check. @@ -237,7 +237,7 @@ impl<'w> BlockContext<'w> { index: Handle, block: &mut Block, ) -> Result { - let index_id = self.writer.cached[index]; + let index_id = self.cached(index); // Get the sequence's length. Return early if we've already done the // bounds check. @@ -367,7 +367,7 @@ impl<'w> BlockContext<'w> { self.write_index_comparison(base, index, block)? } IndexBoundsCheckPolicy::UndefinedBehavior => { - BoundsCheckResult::Computed(self.writer.cached[index]) + BoundsCheckResult::Computed(self.cached(index)) } }) } @@ -384,8 +384,8 @@ impl<'w> BlockContext<'w> { ) -> Result { let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty)?; - let base_id = self.writer.cached[base]; - let index_id = self.writer.cached[index]; + let base_id = self.cached(base); + let index_id = self.cached(index); let result_id = match self.write_bounds_check(base, index, block)? { BoundsCheckResult::KnownInBounds(known_index) => { diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 525dce218..0bf831b34 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -275,6 +275,9 @@ struct BlockContext<'w> { /// The [`back::spv::Function`] to which we are contributing SPIR-V instructions. function: &'w mut Function, + + /// The `Writer`'s temporary vector, for convenience. + temp_list: Vec, } pub struct Writer { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 45680945c..4339adec1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -475,11 +475,13 @@ impl Writer { // Create a `BlockContext` for generating SPIR-V for the function's // body. let mut context = BlockContext { - writer: self, ir_module, ir_function, fun_info: info, function: &mut function, + // Steal the Writer's temp list for a bit. + temp_list: std::mem::take(&mut self.temp_list), + writer: self, }; // fill up the pre-emitted expressions @@ -496,11 +498,13 @@ impl Writer { .consume(prelude, Instruction::branch(main_id)); context.write_block(main_id, &ir_function.body, None, LoopContext::default())?; - context - .function - .to_words(&mut context.writer.logical_layout.function_definitions); - Instruction::function_end() - .to_words(&mut context.writer.logical_layout.function_definitions); + // Consume the `BlockContext`, ending its borrows and letting the + // `Writer` steal back its temp_list. + let BlockContext { temp_list, .. } = context; + self.temp_list = temp_list; + + function.to_words(&mut self.logical_layout.function_definitions); + Instruction::function_end().to_words(&mut self.logical_layout.function_definitions); Ok(function_id) } @@ -1352,13 +1356,17 @@ impl<'w> BlockContext<'w> { .get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) } + pub(super) fn cached(&self, expression: Handle) -> Word { + self.writer.cached[expression] + } + fn write_texture_coordinates( &mut self, coordinates: Handle, array_index: Option>, block: &mut Block, ) -> Result { - let coordinate_id = self.writer.cached[coordinates]; + let coordinate_id = self.cached(coordinates); Ok(if let Some(array_index) = array_index { let coordinate_scalar_type_id = @@ -1406,7 +1414,7 @@ impl<'w> BlockContext<'w> { let array_index_f32_id = self.gen_id(); constituent_ids[size as usize - 1] = array_index_f32_id; - let array_index_u32_id = self.writer.cached[array_index]; + let array_index_u32_id = self.cached(array_index); let cast_instruction = Instruction::unary( spirv::Op::ConvertUToF, coordinate_scalar_type_id, @@ -1507,7 +1515,7 @@ impl<'w> BlockContext<'w> { | crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { let id = self.gen_id(); - let base_id = self.writer.cached[base]; + let base_id = self.cached(base); block.body.push(Instruction::composite_extract( result_type_id, id, @@ -1527,15 +1535,15 @@ impl<'w> BlockContext<'w> { } crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], crate::Expression::Splat { size, value } => { - let value_id = self.writer.cached[value]; - self.writer.temp_list.clear(); - self.writer.temp_list.resize(size as usize, value_id); + let value_id = self.cached(value); + self.temp_list.clear(); + self.temp_list.resize(size as usize, value_id); let id = self.gen_id(); block.body.push(Instruction::composite_construct( result_type_id, id, - &self.writer.temp_list, + &self.temp_list, )); id } @@ -1544,10 +1552,10 @@ impl<'w> BlockContext<'w> { vector, pattern, } => { - let vector_id = self.writer.cached[vector]; - self.writer.temp_list.clear(); + let vector_id = self.cached(vector); + self.temp_list.clear(); for &sc in pattern[..size as usize].iter() { - self.writer.temp_list.push(sc as Word); + self.temp_list.push(sc as Word); } let id = self.gen_id(); block.body.push(Instruction::vector_shuffle( @@ -1555,7 +1563,7 @@ impl<'w> BlockContext<'w> { id, vector_id, vector_id, - &self.writer.temp_list, + &self.temp_list, )); id } @@ -1563,22 +1571,22 @@ impl<'w> BlockContext<'w> { ty: _, ref components, } => { - self.writer.temp_list.clear(); + self.temp_list.clear(); for &component in components { - self.writer.temp_list.push(self.writer.cached[component]); + self.temp_list.push(self.cached(component)); } let id = self.gen_id(); block.body.push(Instruction::composite_construct( result_type_id, id, - &self.writer.temp_list, + &self.temp_list, )); id } crate::Expression::Unary { op, expr } => { let id = self.gen_id(); - let expr_id = self.writer.cached[expr]; + let expr_id = self.cached(expr); let expr_ty_inner = self.fun_info[expr].ty.inner_with(&self.ir_module.types); let spirv_op = match op { @@ -1604,8 +1612,8 @@ impl<'w> BlockContext<'w> { } crate::Expression::Binary { op, left, right } => { let id = self.gen_id(); - let left_id = self.writer.cached[left]; - let right_id = self.writer.cached[right]; + let left_id = self.cached(left); + let right_id = self.cached(right); let left_ty_inner = self.fun_info[left].ty.inner_with(&self.ir_module.types); let right_ty_inner = self.fun_info[right].ty.inner_with(&self.ir_module.types); @@ -1742,17 +1750,17 @@ impl<'w> BlockContext<'w> { Custom(Instruction), } - let arg0_id = self.writer.cached[arg]; + let arg0_id = self.cached(arg); let arg_scalar_kind = self.fun_info[arg] .ty .inner_with(&self.ir_module.types) .scalar_kind(); let arg1_id = match arg1 { - Some(handle) => self.writer.cached[handle], + Some(handle) => self.cached(handle), None => 0, }; let arg2_id = match arg2 { - Some(handle) => self.writer.cached[handle], + Some(handle) => self.cached(handle), None => 0, }; @@ -1919,7 +1927,7 @@ impl<'w> BlockContext<'w> { } => { use crate::ScalarKind as Sk; - let expr_id = self.writer.cached[expr]; + let expr_id = self.cached(expr); let (src_kind, src_width) = match *self.fun_info[expr].ty.inner_with(&self.ir_module.types) { crate::TypeInner::Scalar { kind, width } @@ -1996,7 +2004,7 @@ impl<'w> BlockContext<'w> { }; if let Some(index) = index { - let index_id = self.writer.cached[index]; + let index_id = self.cached(index); let image_ops = match *self.fun_info[image].ty.inner_with(&self.ir_module.types) { crate::TypeInner::Image { @@ -2075,7 +2083,7 @@ impl<'w> BlockContext<'w> { )); let id = self.gen_id(); - let depth_id = depth_ref.map(|handle| self.writer.cached[handle]); + let depth_id = depth_ref.map(|handle| self.cached(handle)); let mut mask = spirv::ImageOperands::empty(); mask.set(spirv::ImageOperands::CONST_OFFSET, offset.is_some()); @@ -2124,7 +2132,7 @@ impl<'w> BlockContext<'w> { depth_id, ); - let lod_id = self.writer.cached[lod_handle]; + let lod_id = self.cached(lod_handle); mask |= spirv::ImageOperands::LOD; inst.add_operand(mask.bits()); inst.add_operand(lod_id); @@ -2141,7 +2149,7 @@ impl<'w> BlockContext<'w> { depth_id, ); - let bias_id = self.writer.cached[bias_handle]; + let bias_id = self.cached(bias_handle); mask |= spirv::ImageOperands::BIAS; inst.add_operand(mask.bits()); inst.add_operand(bias_id); @@ -2158,8 +2166,8 @@ impl<'w> BlockContext<'w> { depth_id, ); - let x_id = self.writer.cached[x]; - let y_id = self.writer.cached[y]; + let x_id = self.cached(x); + let y_id = self.cached(y); mask |= spirv::ImageOperands::GRAD; inst.add_operand(mask.bits()); inst.add_operand(x_id); @@ -2195,9 +2203,9 @@ impl<'w> BlockContext<'w> { reject, } => { let id = self.gen_id(); - let condition_id = self.writer.cached[condition]; - let accept_id = self.writer.cached[accept]; - let reject_id = self.writer.cached[reject]; + let condition_id = self.cached(condition); + let accept_id = self.cached(accept); + let reject_id = self.cached(reject); let instruction = Instruction::select(result_type_id, id, condition_id, accept_id, reject_id); @@ -2208,7 +2216,7 @@ impl<'w> BlockContext<'w> { use crate::DerivativeAxis as Da; let id = self.gen_id(); - let expr_id = self.writer.cached[expr]; + let expr_id = self.cached(expr); let op = match axis { Da::X => spirv::Op::DPdx, Da::Y => spirv::Op::DPdy, @@ -2264,7 +2272,7 @@ impl<'w> BlockContext<'w> { Ic::Storage(_) => (spirv::Op::ImageQuerySize, None), _ => { let level_id = match level { - Some(expr) => self.writer.cached[expr], + Some(expr) => self.cached(expr), None => self.get_index_constant(0)?, }; (spirv::Op::ImageQuerySizeLod, Some(level_id)) @@ -2359,7 +2367,7 @@ impl<'w> BlockContext<'w> { } crate::Expression::Relational { fun, argument } => { use crate::RelationalFunction as Rf; - let arg_id = self.writer.cached[argument]; + let arg_id = self.cached(argument); let op = match fun { Rf::All => spirv::Op::All, Rf::Any => spirv::Op::Any, @@ -2411,7 +2419,7 @@ impl<'w> BlockContext<'w> { // minimum is essential. let mut accumulated_checks = None; - self.writer.temp_list.clear(); + self.temp_list.clear(); let root_id = loop { expr_handle = match self.ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { @@ -2443,16 +2451,16 @@ impl<'w> BlockContext<'w> { } // Either way, the index to use is unchanged. - self.writer.cached[index] + self.cached(index) } }; - self.writer.temp_list.push(index_id); + self.temp_list.push(index_id); base } crate::Expression::AccessIndex { base, index } => { let const_id = self.get_index_constant(index)?; - self.writer.temp_list.push(const_id); + self.temp_list.push(const_id); base } crate::Expression::GlobalVariable(handle) => { @@ -2471,19 +2479,15 @@ impl<'w> BlockContext<'w> { } }; - let pointer = if self.writer.temp_list.is_empty() { + let pointer = if self.temp_list.is_empty() { ExpressionPointer::Ready { pointer_id: root_id, } } else { - self.writer.temp_list.reverse(); + self.temp_list.reverse(); let pointer_id = self.gen_id(); - let access = Instruction::access_chain( - result_type_id, - pointer_id, - root_id, - &self.writer.temp_list, - ); + let access = + Instruction::access_chain(result_type_id, pointer_id, root_id, &self.temp_list); // If we generated some bounds checks, we need to leave it to our // caller to generate the branch, the access, the load or store, and @@ -2545,7 +2549,7 @@ impl<'w> BlockContext<'w> { ref accept, ref reject, } => { - let condition_id = self.writer.cached[condition]; + let condition_id = self.cached(condition); let merge_id = self.gen_id(); block.body.push(Instruction::selection_merge( @@ -2587,7 +2591,7 @@ impl<'w> BlockContext<'w> { ref cases, ref default, } => { - let selector_id = self.writer.cached[selector]; + let selector_id = self.cached(selector); let merge_id = self.gen_id(); block.body.push(Instruction::selection_merge( @@ -2687,7 +2691,7 @@ impl<'w> BlockContext<'w> { return Ok(()); } crate::Statement::Return { value: Some(value) } => { - let value_id = self.writer.cached[value]; + let value_id = self.cached(value); let instruction = match self.function.entry_point_context { // If this is an entry point, and we need to return anything, // let's instead store the output variables and return `void`. @@ -2738,7 +2742,7 @@ impl<'w> BlockContext<'w> { )); } crate::Statement::Store { pointer, value } => { - let value_id = self.writer.cached[value]; + let value_id = self.cached(value); match self.write_expression_pointer(pointer, &mut block)? { ExpressionPointer::Ready { pointer_id } => { block @@ -2788,7 +2792,7 @@ impl<'w> BlockContext<'w> { let image_id = self.get_expression_global(image); let coordinate_id = self.write_texture_coordinates(coordinate, array_index, &mut block)?; - let value_id = self.writer.cached[value]; + let value_id = self.cached(value); block .body @@ -2800,9 +2804,9 @@ impl<'w> BlockContext<'w> { result, } => { let id = self.gen_id(); - self.writer.temp_list.clear(); + self.temp_list.clear(); for &argument in arguments { - self.writer.temp_list.push(self.writer.cached[argument]); + self.temp_list.push(self.cached(argument)); } let type_id = match result { @@ -2823,7 +2827,7 @@ impl<'w> BlockContext<'w> { type_id, id, self.writer.lookup_function[&local_function], - &self.writer.temp_list, + &self.temp_list, )); } } From 3a1a2ed8b3c3fce48d194c282e8e21816baaae26 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 30 Jun 2021 21:25:51 -0700 Subject: [PATCH 1059/2212] [spv-out] Move BlockContext into its own file. Rearrange some code for easier visibility. `make_local` doesn't need a PhysicalLayout `self`; make it a free function. --- src/back/spv/block.rs | 1581 +++++++++++++++++++++++++++++++++++++ src/back/spv/mod.rs | 80 +- src/back/spv/writer.rs | 1669 +--------------------------------------- 3 files changed, 1668 insertions(+), 1662 deletions(-) create mode 100644 src/back/spv/block.rs diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs new file mode 100644 index 000000000..a3ec5ced9 --- /dev/null +++ b/src/back/spv/block.rs @@ -0,0 +1,1581 @@ +//! Implementations for `BlockContext` methods. + +use super::{ + index::{BoundsCheckResult, ExpressionPointer}, + make_local, Block, BlockContext, Dimension, Error, Instruction, LocalType, LookupType, + LoopContext, ResultMember, Writer, WriterFlags, +}; +use crate::{arena::Handle, proc::TypeResolution}; +use spirv::Word; + +fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { + match *type_inner { + crate::TypeInner::Scalar { .. } => Dimension::Scalar, + crate::TypeInner::Vector { .. } => Dimension::Vector, + crate::TypeInner::Matrix { .. } => Dimension::Matrix, + _ => unreachable!(), + } +} + +impl Writer { + fn write_entry_point_return( + &mut self, + value_id: Word, + ir_result: &crate::FunctionResult, + result_members: &[ResultMember], + body: &mut Vec, + ) -> Result<(), Error> { + for (index, res_member) in result_members.iter().enumerate() { + let member_value_id = match ir_result.binding { + Some(_) => value_id, + None => { + let member_value_id = self.id_gen.next(); + body.push(Instruction::composite_extract( + res_member.type_id, + member_value_id, + value_id, + &[index as u32], + )); + member_value_id + } + }; + + body.push(Instruction::store(res_member.id, member_value_id, None)); + + // Flip Y coordinate to adjust for coordinate space difference + // between SPIR-V and our IR. + if self.flags.contains(WriterFlags::ADJUST_COORDINATE_SPACE) + && res_member.built_in == Some(crate::BuiltIn::Position) + { + let access_id = self.id_gen.next(); + let float_ptr_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: Some(spirv::StorageClass::Output), + }))?; + let index_y_id = self.get_index_constant(1)?; + body.push(Instruction::access_chain( + float_ptr_type_id, + access_id, + res_member.id, + &[index_y_id], + )); + + let load_id = self.id_gen.next(); + let float_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))?; + body.push(Instruction::load(float_type_id, load_id, access_id, None)); + + let neg_id = self.id_gen.next(); + body.push(Instruction::unary( + spirv::Op::FNegate, + float_type_id, + neg_id, + load_id, + )); + body.push(Instruction::store(access_id, neg_id, None)); + } + } + Ok(()) + } +} + +impl<'w> BlockContext<'w> { + fn get_type_id(&mut self, lookup_type: LookupType) -> Result { + self.writer.get_type_id(lookup_type) + } + + fn write_texture_coordinates( + &mut self, + coordinates: Handle, + array_index: Option>, + block: &mut Block, + ) -> Result { + let coordinate_id = self.cached(coordinates); + + Ok(if let Some(array_index) = array_index { + let coordinate_scalar_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))?; + + let mut constituent_ids = [0u32; 4]; + let size = match *self.fun_info[coordinates] + .ty + .inner_with(&self.ir_module.types) + { + crate::TypeInner::Scalar { .. } => { + constituent_ids[0] = coordinate_id; + crate::VectorSize::Bi + } + crate::TypeInner::Vector { size, .. } => { + for i in 0..size as u32 { + let id = self.gen_id(); + constituent_ids[i as usize] = id; + block.body.push(Instruction::composite_extract( + coordinate_scalar_type_id, + id, + coordinate_id, + &[i], + )); + } + match size { + crate::VectorSize::Bi => crate::VectorSize::Tri, + crate::VectorSize::Tri => crate::VectorSize::Quad, + crate::VectorSize::Quad => { + return Err(Error::Validation("extending vec4 coordinate")); + } + } + } + ref other => { + log::error!("wrong coordinate type {:?}", other); + return Err(Error::Validation("coordinate type")); + } + }; + + let array_index_f32_id = self.gen_id(); + constituent_ids[size as usize - 1] = array_index_f32_id; + + let array_index_u32_id = self.cached(array_index); + let cast_instruction = Instruction::unary( + spirv::Op::ConvertUToF, + coordinate_scalar_type_id, + array_index_f32_id, + array_index_u32_id, + ); + block.body.push(cast_instruction); + + let extended_coordinate_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))?; + + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + extended_coordinate_type_id, + id, + &constituent_ids[..size as usize], + )); + id + } else { + coordinate_id + }) + } + + /// Decide whether to put off emitting instructions for `expr_handle`. + /// + /// We would like to gather together chains of `Access` and `AccessIndex` + /// Naga expressions into a single `OpAccessChain` SPIR-V instruction. To do + /// this, we don't generate instructions for these exprs when we first + /// encounter them. Their ids in `self.writer.cached.ids` are left as zero. Then, + /// once we encounter a `Load` or `Store` expression that actually needs the + /// chain's value, we call `write_expression_pointer` to handle the whole + /// thing in one fell swoop. + fn is_intermediate(&self, expr_handle: Handle) -> bool { + match self.ir_function.expressions[expr_handle] { + crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => true, + crate::Expression::FunctionArgument(index) => { + let arg = &self.ir_function.arguments[index as usize]; + match self.ir_module.types[arg.ty].inner { + crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { + true + } + _ => false, + } + } + + // The chain rule: if this `Access...`'s `base` operand was + // previously omitted, then omit this one, too. + _ => self.writer.cached.ids[expr_handle.index()] == 0, + } + } + + /// Cache an expression for a value. + pub(super) fn cache_expression_value( + &mut self, + expr_handle: Handle, + block: &mut Block, + ) -> Result<(), Error> { + let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty)?; + + let id = match self.ir_function.expressions[expr_handle] { + crate::Expression::Access { base, index: _ } if self.is_intermediate(base) => { + // See `is_intermediate`; we'll handle this later in + // `write_expression_pointer`. + 0 + } + crate::Expression::Access { base, index } => { + let base_ty = self.fun_info[base].ty.inner_with(&self.ir_module.types); + match *base_ty { + crate::TypeInner::Vector { .. } => (), + ref other => { + log::error!( + "Unable to access base {:?} of type {:?}", + self.ir_function.expressions[base], + other + ); + return Err(Error::Validation( + "only vectors may be dynamically indexed by value", + )); + } + }; + + self.write_vector_access(expr_handle, base, index, block)? + } + crate::Expression::AccessIndex { base, index: _ } if self.is_intermediate(base) => { + // See `is_intermediate`; we'll handle this later in + // `write_expression_pointer`. + 0 + } + crate::Expression::AccessIndex { base, index } => { + match *self.fun_info[base].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } + | crate::TypeInner::Array { .. } + | crate::TypeInner::Struct { .. } => { + let id = self.gen_id(); + let base_id = self.cached(base); + block.body.push(Instruction::composite_extract( + result_type_id, + id, + base_id, + &[index], + )); + id + } + ref other => { + log::error!("Unable to access index of {:?}", other); + return Err(Error::FeatureNotImplemented("access index for type")); + } + } + } + crate::Expression::GlobalVariable(handle) => { + self.writer.global_variables[handle.index()].id + } + crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], + crate::Expression::Splat { size, value } => { + let value_id = self.cached(value); + self.temp_list.clear(); + self.temp_list.resize(size as usize, value_id); + + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + result_type_id, + id, + &self.temp_list, + )); + id + } + crate::Expression::Swizzle { + size, + vector, + pattern, + } => { + let vector_id = self.cached(vector); + self.temp_list.clear(); + for &sc in pattern[..size as usize].iter() { + self.temp_list.push(sc as Word); + } + let id = self.gen_id(); + block.body.push(Instruction::vector_shuffle( + result_type_id, + id, + vector_id, + vector_id, + &self.temp_list, + )); + id + } + crate::Expression::Compose { + ty: _, + ref components, + } => { + self.temp_list.clear(); + for &component in components { + self.temp_list.push(self.cached(component)); + } + + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + result_type_id, + id, + &self.temp_list, + )); + id + } + crate::Expression::Unary { op, expr } => { + let id = self.gen_id(); + let expr_id = self.cached(expr); + let expr_ty_inner = self.fun_info[expr].ty.inner_with(&self.ir_module.types); + + let spirv_op = match op { + crate::UnaryOperator::Negate => match expr_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Float) => spirv::Op::FNegate, + Some(crate::ScalarKind::Sint) => spirv::Op::SNegate, + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNot, + Some(crate::ScalarKind::Uint) | None => { + log::error!("Unable to negate {:?}", expr_ty_inner); + return Err(Error::FeatureNotImplemented("negation")); + } + }, + crate::UnaryOperator::Not => match expr_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNot, + _ => spirv::Op::Not, + }, + }; + + block + .body + .push(Instruction::unary(spirv_op, result_type_id, id, expr_id)); + id + } + crate::Expression::Binary { op, left, right } => { + let id = self.gen_id(); + let left_id = self.cached(left); + let right_id = self.cached(right); + + let left_ty_inner = self.fun_info[left].ty.inner_with(&self.ir_module.types); + let right_ty_inner = self.fun_info[right].ty.inner_with(&self.ir_module.types); + + let left_dimension = get_dimension(left_ty_inner); + let right_dimension = get_dimension(right_ty_inner); + + let mut preserve_order = true; + + let spirv_op = match op { + crate::BinaryOperator::Add => match *left_ty_inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } => match kind { + crate::ScalarKind::Float => spirv::Op::FAdd, + _ => spirv::Op::IAdd, + }, + _ => unimplemented!(), + }, + crate::BinaryOperator::Subtract => match *left_ty_inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } => match kind { + crate::ScalarKind::Float => spirv::Op::FSub, + _ => spirv::Op::ISub, + }, + _ => unimplemented!(), + }, + crate::BinaryOperator::Multiply => match (left_dimension, right_dimension) { + (Dimension::Scalar, Dimension::Vector { .. }) => { + preserve_order = false; + spirv::Op::VectorTimesScalar + } + (Dimension::Vector, Dimension::Scalar { .. }) => { + spirv::Op::VectorTimesScalar + } + (Dimension::Vector, Dimension::Matrix) => spirv::Op::VectorTimesMatrix, + (Dimension::Matrix, Dimension::Scalar { .. }) => { + spirv::Op::MatrixTimesScalar + } + (Dimension::Matrix, Dimension::Vector) => spirv::Op::MatrixTimesVector, + (Dimension::Matrix, Dimension::Matrix) => spirv::Op::MatrixTimesMatrix, + (Dimension::Vector, Dimension::Vector) + | (Dimension::Scalar, Dimension::Scalar) + if left_ty_inner.scalar_kind() == Some(crate::ScalarKind::Float) => + { + spirv::Op::FMul + } + (Dimension::Vector, Dimension::Vector) + | (Dimension::Scalar, Dimension::Scalar) => spirv::Op::IMul, + other => unimplemented!("Mul {:?}", other), + }, + crate::BinaryOperator::Divide => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SDiv, + Some(crate::ScalarKind::Uint) => spirv::Op::UDiv, + Some(crate::ScalarKind::Float) => spirv::Op::FDiv, + _ => unimplemented!(), + }, + crate::BinaryOperator::Modulo => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SMod, + Some(crate::ScalarKind::Uint) => spirv::Op::UMod, + Some(crate::ScalarKind::Float) => spirv::Op::FMod, + _ => unimplemented!(), + }, + crate::BinaryOperator::Equal => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { + spirv::Op::IEqual + } + Some(crate::ScalarKind::Float) => spirv::Op::FOrdEqual, + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalEqual, + _ => unimplemented!(), + }, + crate::BinaryOperator::NotEqual => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { + spirv::Op::INotEqual + } + Some(crate::ScalarKind::Float) => spirv::Op::FOrdNotEqual, + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNotEqual, + _ => unimplemented!(), + }, + crate::BinaryOperator::Less => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SLessThan, + Some(crate::ScalarKind::Uint) => spirv::Op::ULessThan, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThan, + _ => unimplemented!(), + }, + crate::BinaryOperator::LessEqual => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SLessThanEqual, + Some(crate::ScalarKind::Uint) => spirv::Op::ULessThanEqual, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThanEqual, + _ => unimplemented!(), + }, + crate::BinaryOperator::Greater => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThan, + Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThan, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThan, + _ => unimplemented!(), + }, + crate::BinaryOperator::GreaterEqual => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThanEqual, + Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThanEqual, + Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThanEqual, + _ => unimplemented!(), + }, + crate::BinaryOperator::And => spirv::Op::BitwiseAnd, + crate::BinaryOperator::ExclusiveOr => spirv::Op::BitwiseXor, + crate::BinaryOperator::InclusiveOr => spirv::Op::BitwiseOr, + crate::BinaryOperator::LogicalAnd => spirv::Op::LogicalAnd, + crate::BinaryOperator::LogicalOr => spirv::Op::LogicalOr, + crate::BinaryOperator::ShiftLeft => spirv::Op::ShiftLeftLogical, + crate::BinaryOperator::ShiftRight => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Sint) => spirv::Op::ShiftRightArithmetic, + Some(crate::ScalarKind::Uint) => spirv::Op::ShiftRightLogical, + _ => unimplemented!(), + }, + }; + + block.body.push(Instruction::binary( + spirv_op, + result_type_id, + id, + if preserve_order { left_id } else { right_id }, + if preserve_order { right_id } else { left_id }, + )); + id + } + crate::Expression::Math { + fun, + arg, + arg1, + arg2, + } => { + use crate::MathFunction as Mf; + enum MathOp { + Ext(spirv::GLOp), + Custom(Instruction), + } + + let arg0_id = self.cached(arg); + let arg_scalar_kind = self.fun_info[arg] + .ty + .inner_with(&self.ir_module.types) + .scalar_kind(); + let arg1_id = match arg1 { + Some(handle) => self.cached(handle), + None => 0, + }; + let arg2_id = match arg2 { + Some(handle) => self.cached(handle), + None => 0, + }; + + let id = self.gen_id(); + let math_op = match fun { + // comparison + Mf::Abs => { + match arg_scalar_kind { + Some(crate::ScalarKind::Float) => MathOp::Ext(spirv::GLOp::FAbs), + Some(crate::ScalarKind::Sint) => MathOp::Ext(spirv::GLOp::SAbs), + Some(crate::ScalarKind::Uint) => { + MathOp::Custom(Instruction::unary( + spirv::Op::CopyObject, // do nothing + result_type_id, + id, + arg0_id, + )) + } + other => unimplemented!("Unexpected abs({:?})", other), + } + } + Mf::Min => MathOp::Ext(match arg_scalar_kind { + Some(crate::ScalarKind::Float) => spirv::GLOp::FMin, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SMin, + Some(crate::ScalarKind::Uint) => spirv::GLOp::UMin, + other => unimplemented!("Unexpected min({:?})", other), + }), + Mf::Max => MathOp::Ext(match arg_scalar_kind { + Some(crate::ScalarKind::Float) => spirv::GLOp::FMax, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SMax, + Some(crate::ScalarKind::Uint) => spirv::GLOp::UMax, + other => unimplemented!("Unexpected max({:?})", other), + }), + Mf::Clamp => MathOp::Ext(match arg_scalar_kind { + Some(crate::ScalarKind::Float) => spirv::GLOp::FClamp, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SClamp, + Some(crate::ScalarKind::Uint) => spirv::GLOp::UClamp, + other => unimplemented!("Unexpected max({:?})", other), + }), + // trigonometry + Mf::Sin => MathOp::Ext(spirv::GLOp::Sin), + Mf::Sinh => MathOp::Ext(spirv::GLOp::Sinh), + Mf::Asin => MathOp::Ext(spirv::GLOp::Asin), + Mf::Cos => MathOp::Ext(spirv::GLOp::Cos), + Mf::Cosh => MathOp::Ext(spirv::GLOp::Cosh), + Mf::Acos => MathOp::Ext(spirv::GLOp::Acos), + Mf::Tan => MathOp::Ext(spirv::GLOp::Tan), + Mf::Tanh => MathOp::Ext(spirv::GLOp::Tanh), + Mf::Atan => MathOp::Ext(spirv::GLOp::Atan), + Mf::Atan2 => MathOp::Ext(spirv::GLOp::Atan2), + // decomposition + Mf::Ceil => MathOp::Ext(spirv::GLOp::Ceil), + Mf::Round => MathOp::Ext(spirv::GLOp::Round), + Mf::Floor => MathOp::Ext(spirv::GLOp::Floor), + Mf::Fract => MathOp::Ext(spirv::GLOp::Fract), + Mf::Trunc => MathOp::Ext(spirv::GLOp::Trunc), + Mf::Modf => MathOp::Ext(spirv::GLOp::Modf), + Mf::Frexp => MathOp::Ext(spirv::GLOp::Frexp), + Mf::Ldexp => MathOp::Ext(spirv::GLOp::Ldexp), + // geometry + Mf::Dot => MathOp::Custom(Instruction::binary( + spirv::Op::Dot, + result_type_id, + id, + arg0_id, + arg1_id, + )), + Mf::Outer => MathOp::Custom(Instruction::binary( + spirv::Op::OuterProduct, + result_type_id, + id, + arg0_id, + arg1_id, + )), + Mf::Cross => MathOp::Ext(spirv::GLOp::Cross), + Mf::Distance => MathOp::Ext(spirv::GLOp::Distance), + Mf::Length => MathOp::Ext(spirv::GLOp::Length), + Mf::Normalize => MathOp::Ext(spirv::GLOp::Normalize), + Mf::FaceForward => MathOp::Ext(spirv::GLOp::FaceForward), + Mf::Reflect => MathOp::Ext(spirv::GLOp::Reflect), + Mf::Refract => MathOp::Ext(spirv::GLOp::Refract), + // exponent + Mf::Exp => MathOp::Ext(spirv::GLOp::Exp), + Mf::Exp2 => MathOp::Ext(spirv::GLOp::Exp2), + Mf::Log => MathOp::Ext(spirv::GLOp::Log), + Mf::Log2 => MathOp::Ext(spirv::GLOp::Log2), + Mf::Pow => MathOp::Ext(spirv::GLOp::Pow), + // computational + Mf::Sign => MathOp::Ext(match arg_scalar_kind { + Some(crate::ScalarKind::Float) => spirv::GLOp::FSign, + Some(crate::ScalarKind::Sint) => spirv::GLOp::SSign, + other => unimplemented!("Unexpected sign({:?})", other), + }), + Mf::Fma => MathOp::Ext(spirv::GLOp::Fma), + Mf::Mix => MathOp::Ext(spirv::GLOp::FMix), + Mf::Step => MathOp::Ext(spirv::GLOp::Step), + Mf::SmoothStep => MathOp::Ext(spirv::GLOp::SmoothStep), + Mf::Sqrt => MathOp::Ext(spirv::GLOp::Sqrt), + Mf::InverseSqrt => MathOp::Ext(spirv::GLOp::InverseSqrt), + Mf::Inverse => MathOp::Ext(spirv::GLOp::MatrixInverse), + Mf::Transpose => MathOp::Custom(Instruction::unary( + spirv::Op::Transpose, + result_type_id, + id, + arg0_id, + )), + Mf::Determinant => MathOp::Ext(spirv::GLOp::Determinant), + Mf::ReverseBits | Mf::CountOneBits => { + log::error!("unimplemented math function {:?}", fun); + return Err(Error::FeatureNotImplemented("math function")); + } + }; + + block.body.push(match math_op { + MathOp::Ext(op) => Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + op, + result_type_id, + id, + &[arg0_id, arg1_id, arg2_id][..fun.argument_count()], + ), + MathOp::Custom(inst) => inst, + }); + id + } + crate::Expression::LocalVariable(variable) => self.function.variables[&variable].id, + crate::Expression::Load { pointer } => { + match self.write_expression_pointer(pointer, block)? { + ExpressionPointer::Ready { pointer_id } => { + let id = self.gen_id(); + block + .body + .push(Instruction::load(result_type_id, id, pointer_id, None)); + id + } + ExpressionPointer::Conditional { condition, access } => { + self.write_conditional_indexed_load( + result_type_id, + condition, + block, + move |id_gen, block| { + // The in-bounds path. Perform the access and the load. + let pointer_id = access.result_id.unwrap(); + let value_id = id_gen.next(); + block.body.push(access); + block.body.push(Instruction::load( + result_type_id, + value_id, + pointer_id, + None, + )); + value_id + }, + ) + } + } + } + crate::Expression::FunctionArgument(index) => self.function.parameter_id(index), + crate::Expression::Call(_function) => self.writer.lookup_function_call[&expr_handle], + crate::Expression::As { + expr, + kind, + convert, + } => { + use crate::ScalarKind as Sk; + + let expr_id = self.cached(expr); + let (src_kind, src_width) = + match *self.fun_info[expr].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Scalar { kind, width } + | crate::TypeInner::Vector { + kind, + width, + size: _, + } => (kind, width), + crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), + ref other => { + log::error!("As source {:?}", other); + return Err(Error::Validation("Unexpected Expression::As source")); + } + }; + + let op = match (src_kind, kind, convert) { + (_, _, None) => spirv::Op::Bitcast, + (Sk::Float, Sk::Uint, Some(_)) => spirv::Op::ConvertFToU, + (Sk::Float, Sk::Sint, Some(_)) => spirv::Op::ConvertFToS, + (Sk::Float, Sk::Float, Some(dst_width)) if src_width != dst_width => { + spirv::Op::FConvert + } + (Sk::Sint, Sk::Float, Some(_)) => spirv::Op::ConvertSToF, + (Sk::Sint, Sk::Sint, Some(dst_width)) if src_width != dst_width => { + spirv::Op::SConvert + } + (Sk::Uint, Sk::Float, Some(_)) => spirv::Op::ConvertUToF, + (Sk::Uint, Sk::Uint, Some(dst_width)) if src_width != dst_width => { + spirv::Op::UConvert + } + // We assume it's either an identity cast, or int-uint. + _ => spirv::Op::Bitcast, + }; + + let id = self.gen_id(); + let instruction = Instruction::unary(op, result_type_id, id, expr_id); + block.body.push(instruction); + id + } + crate::Expression::ImageLoad { + image, + coordinate, + array_index, + index, + } => { + let image_id = self.get_expression_global(image); + let coordinate_id = + self.write_texture_coordinates(coordinate, array_index, block)?; + + let id = self.gen_id(); + + let image_ty = self.fun_info[image].ty.inner_with(&self.ir_module.types); + let mut instruction = match *image_ty { + crate::TypeInner::Image { + class: crate::ImageClass::Storage { .. }, + .. + } => Instruction::image_read(result_type_id, id, image_id, coordinate_id), + crate::TypeInner::Image { + class: crate::ImageClass::Depth, + .. + } => { + // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, + // so we need to grab the first component out of it. + let load_result_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Quad), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))?; + Instruction::image_fetch(load_result_type_id, id, image_id, coordinate_id) + } + _ => Instruction::image_fetch(result_type_id, id, image_id, coordinate_id), + }; + + if let Some(index) = index { + let index_id = self.cached(index); + let image_ops = match *self.fun_info[image].ty.inner_with(&self.ir_module.types) + { + crate::TypeInner::Image { + class: crate::ImageClass::Sampled { multi: true, .. }, + .. + } => spirv::ImageOperands::SAMPLE, + _ => spirv::ImageOperands::LOD, + }; + instruction.add_operand(image_ops.bits()); + instruction.add_operand(index_id); + } + + let inst_type_id = instruction.type_id; + block.body.push(instruction); + if inst_type_id != Some(result_type_id) { + let sub_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + result_type_id, + sub_id, + id, + &[0], + )); + sub_id + } else { + id + } + } + crate::Expression::ImageSample { + image, + sampler, + coordinate, + array_index, + offset, + level, + depth_ref, + } => { + use super::instructions::SampleLod; + // image + let image_id = self.get_expression_global(image); + let image_type = self.fun_info[image].ty.handle().unwrap(); + // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, + // so we need to grab the first component out of it. + let needs_sub_access = match self.ir_module.types[image_type].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Depth, + .. + } => depth_ref.is_none(), + _ => false, + }; + let sample_result_type_id = if needs_sub_access { + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Quad), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))? + } else { + result_type_id + }; + + // OpTypeSampledImage + let image_type_id = self.get_type_id(LookupType::Handle(image_type))?; + let sampled_image_type_id = + self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id }))?; + + let sampler_id = self.get_expression_global(sampler); + let coordinate_id = + self.write_texture_coordinates(coordinate, array_index, block)?; + + let sampled_image_id = self.gen_id(); + block.body.push(Instruction::sampled_image( + sampled_image_type_id, + sampled_image_id, + image_id, + sampler_id, + )); + let id = self.gen_id(); + + let depth_id = depth_ref.map(|handle| self.cached(handle)); + let mut mask = spirv::ImageOperands::empty(); + mask.set(spirv::ImageOperands::CONST_OFFSET, offset.is_some()); + + let mut main_instruction = match level { + crate::SampleLevel::Zero => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Explicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let zero_id = self + .writer + .get_constant_scalar(crate::ScalarValue::Float(0.0), 4)?; + + mask |= spirv::ImageOperands::LOD; + inst.add_operand(mask.bits()); + inst.add_operand(zero_id); + + inst + } + crate::SampleLevel::Auto => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Implicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + if !mask.is_empty() { + inst.add_operand(mask.bits()); + } + inst + } + crate::SampleLevel::Exact(lod_handle) => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Explicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let lod_id = self.cached(lod_handle); + mask |= spirv::ImageOperands::LOD; + inst.add_operand(mask.bits()); + inst.add_operand(lod_id); + + inst + } + crate::SampleLevel::Bias(bias_handle) => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Implicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let bias_id = self.cached(bias_handle); + mask |= spirv::ImageOperands::BIAS; + inst.add_operand(mask.bits()); + inst.add_operand(bias_id); + + inst + } + crate::SampleLevel::Gradient { x, y } => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Explicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let x_id = self.cached(x); + let y_id = self.cached(y); + mask |= spirv::ImageOperands::GRAD; + inst.add_operand(mask.bits()); + inst.add_operand(x_id); + inst.add_operand(y_id); + + inst + } + }; + + if let Some(offset_const) = offset { + let offset_id = self.writer.constant_ids[offset_const.index()]; + main_instruction.add_operand(offset_id); + } + + block.body.push(main_instruction); + + if needs_sub_access { + let sub_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + result_type_id, + sub_id, + id, + &[0], + )); + sub_id + } else { + id + } + } + crate::Expression::Select { + condition, + accept, + reject, + } => { + let id = self.gen_id(); + let condition_id = self.cached(condition); + let accept_id = self.cached(accept); + let reject_id = self.cached(reject); + + let instruction = + Instruction::select(result_type_id, id, condition_id, accept_id, reject_id); + block.body.push(instruction); + id + } + crate::Expression::Derivative { axis, expr } => { + use crate::DerivativeAxis as Da; + + let id = self.gen_id(); + let expr_id = self.cached(expr); + let op = match axis { + Da::X => spirv::Op::DPdx, + Da::Y => spirv::Op::DPdy, + Da::Width => spirv::Op::Fwidth, + }; + block + .body + .push(Instruction::derivative(op, result_type_id, id, expr_id)); + id + } + crate::Expression::ImageQuery { image, query } => { + use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq}; + + let image_id = self.get_expression_global(image); + let image_type = self.fun_info[image].ty.handle().unwrap(); + let (dim, arrayed, class) = match self.ir_module.types[image_type].inner { + crate::TypeInner::Image { + dim, + arrayed, + class, + } => (dim, arrayed, class), + _ => { + return Err(Error::Validation("image type")); + } + }; + + self.writer.check(&[spirv::Capability::ImageQuery])?; + + match query { + Iq::Size { level } => { + let dim_coords = match dim { + Id::D1 => 1, + Id::D2 | Id::Cube => 2, + Id::D3 => 3, + }; + let extended_size_type_id = { + let array_coords = if arrayed { 1 } else { 0 }; + let vector_size = match dim_coords + array_coords { + 2 => Some(crate::VectorSize::Bi), + 3 => Some(crate::VectorSize::Tri), + 4 => Some(crate::VectorSize::Quad), + _ => None, + }; + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + }))? + }; + + let (query_op, level_id) = match class { + Ic::Storage(_) => (spirv::Op::ImageQuerySize, None), + _ => { + let level_id = match level { + Some(expr) => self.cached(expr), + None => self.get_index_constant(0)?, + }; + (spirv::Op::ImageQuerySizeLod, Some(level_id)) + } + }; + + // The ID of the vector returned by SPIR-V, which contains the dimensions + // as well as the layer count. + let id_extended = self.gen_id(); + let mut inst = Instruction::image_query( + query_op, + extended_size_type_id, + id_extended, + image_id, + ); + if let Some(expr_id) = level_id { + inst.add_operand(expr_id); + } + block.body.push(inst); + + if result_type_id != extended_size_type_id { + let id = self.gen_id(); + let components = match dim { + // always pick the first component, and duplicate it for all 3 dimensions + Id::Cube => &[0u32, 0, 0][..], + _ => &[0u32, 1, 2, 3][..dim_coords], + }; + block.body.push(Instruction::vector_shuffle( + result_type_id, + id, + id_extended, + id_extended, + components, + )); + id + } else { + id_extended + } + } + Iq::NumLevels => { + let id = self.gen_id(); + block.body.push(Instruction::image_query( + spirv::Op::ImageQueryLevels, + result_type_id, + id, + image_id, + )); + id + } + Iq::NumLayers => { + let vec_size = match dim { + Id::D1 => crate::VectorSize::Bi, + Id::D2 | Id::Cube => crate::VectorSize::Tri, + Id::D3 => crate::VectorSize::Quad, + }; + let extended_size_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(vec_size), + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + }))?; + let id_extended = self.gen_id(); + let mut inst = Instruction::image_query( + spirv::Op::ImageQuerySizeLod, + extended_size_type_id, + id_extended, + image_id, + ); + inst.add_operand(self.get_index_constant(0)?); + block.body.push(inst); + let id = self.gen_id(); + block.body.push(Instruction::composite_extract( + result_type_id, + id, + id_extended, + &[vec_size as u32 - 1], + )); + id + } + Iq::NumSamples => { + let id = self.gen_id(); + block.body.push(Instruction::image_query( + spirv::Op::ImageQuerySamples, + result_type_id, + id, + image_id, + )); + id + } + } + } + crate::Expression::Relational { fun, argument } => { + use crate::RelationalFunction as Rf; + let arg_id = self.cached(argument); + let op = match fun { + Rf::All => spirv::Op::All, + Rf::Any => spirv::Op::Any, + Rf::IsNan => spirv::Op::IsNan, + Rf::IsInf => spirv::Op::IsInf, + //TODO: these require Kernel capability + Rf::IsFinite | Rf::IsNormal => { + return Err(Error::FeatureNotImplemented("is finite/normal")) + } + }; + let id = self.gen_id(); + block + .body + .push(Instruction::relational(op, result_type_id, id, arg_id)); + id + } + crate::Expression::ArrayLength(expr) => self.write_runtime_array_length(expr, block)?, + }; + + self.writer.cached[expr_handle] = id; + Ok(()) + } + + /// Build an `OpAccessChain` instruction for a left-hand-side expression. + /// + /// Emit any needed bounds-checking expressions to `block`. + /// + /// On success, the return value is an [`ExpressionPointer`] value; see the + /// documentation for that type. + fn write_expression_pointer( + &mut self, + mut expr_handle: Handle, + block: &mut Block, + ) -> Result { + let result_lookup_ty = match self.fun_info[expr_handle].ty { + TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), + TypeResolution::Value(ref inner) => LookupType::Local(make_local(inner).unwrap()), + }; + let result_type_id = self.get_type_id(result_lookup_ty)?; + + // The id of the boolean `and` of all dynamic bounds checks up to this point. If + // `None`, then we haven't done any dynamic bounds checks yet. + // + // When we have a chain of bounds checks, we combine them with `OpLogicalAnd`, not + // a short-circuit branch. This means we might do comparisons we don't need to, + // but we expect these checks to almost always succeed, and keeping branches to a + // minimum is essential. + let mut accumulated_checks = None; + + self.temp_list.clear(); + let root_id = loop { + expr_handle = match self.ir_function.expressions[expr_handle] { + crate::Expression::Access { base, index } => { + let index_id = match self.write_bounds_check(base, index, block)? { + BoundsCheckResult::KnownInBounds(known_index) => { + // Even if the index is known, `OpAccessIndex` + // requires expression operands, not literals. + let scalar = crate::ScalarValue::Uint(known_index as u64); + self.writer.get_constant_scalar(scalar, 4)? + } + BoundsCheckResult::Computed(computed_index_id) => computed_index_id, + BoundsCheckResult::Conditional(comparison_id) => { + match accumulated_checks { + Some(prior_checks) => { + let combined = self.gen_id(); + block.body.push(Instruction::binary( + spirv::Op::LogicalAnd, + self.writer.get_bool_type_id()?, + combined, + prior_checks, + comparison_id, + )); + accumulated_checks = Some(combined); + } + None => { + // Start a fresh chain of checks. + accumulated_checks = Some(comparison_id); + } + } + + // Either way, the index to use is unchanged. + self.cached(index) + } + }; + self.temp_list.push(index_id); + + base + } + crate::Expression::AccessIndex { base, index } => { + let const_id = self.get_index_constant(index)?; + self.temp_list.push(const_id); + base + } + crate::Expression::GlobalVariable(handle) => { + let gv = &self.writer.global_variables[handle.index()]; + break gv.id; + } + crate::Expression::LocalVariable(variable) => { + let local_var = &self.function.variables[&variable]; + break local_var.id; + } + crate::Expression::FunctionArgument(index) => { + let id = self.function.parameters[index as usize].result_id.unwrap(); + break id; + } + ref other => unimplemented!("Unexpected pointer expression {:?}", other), + } + }; + + let pointer = if self.temp_list.is_empty() { + ExpressionPointer::Ready { + pointer_id: root_id, + } + } else { + self.temp_list.reverse(); + let pointer_id = self.gen_id(); + let access = + Instruction::access_chain(result_type_id, pointer_id, root_id, &self.temp_list); + + // If we generated some bounds checks, we need to leave it to our + // caller to generate the branch, the access, the load or store, and + // the zero value (for loads). Otherwise, we can emit the access + // ourselves, and just hand them the id of the pointer. + match accumulated_checks { + Some(condition) => ExpressionPointer::Conditional { condition, access }, + None => { + block.body.push(access); + ExpressionPointer::Ready { pointer_id } + } + } + }; + + Ok(pointer) + } + + fn get_expression_global(&self, expr_handle: Handle) -> Word { + match self.ir_function.expressions[expr_handle] { + crate::Expression::GlobalVariable(handle) => { + let id = self.writer.global_variables[handle.index()].handle_id; + if id == 0 { + unreachable!("Global variable {:?} doesn't have a handle ID", handle); + } + id + } + ref other => unreachable!("Unexpected global expression {:?}", other), + } + } + + pub(super) fn write_block( + &mut self, + label_id: Word, + statements: &[crate::Statement], + exit_id: Option, + loop_context: LoopContext, + ) -> Result<(), Error> { + let mut block = Block::new(label_id); + + for statement in statements { + match *statement { + crate::Statement::Emit(ref range) => { + for handle in range.clone() { + self.cache_expression_value(handle, &mut block)?; + } + } + crate::Statement::Block(ref block_statements) => { + let scope_id = self.gen_id(); + self.function.consume(block, Instruction::branch(scope_id)); + + let merge_id = self.gen_id(); + self.write_block(scope_id, block_statements, Some(merge_id), loop_context)?; + + block = Block::new(merge_id); + } + crate::Statement::If { + condition, + ref accept, + ref reject, + } => { + let condition_id = self.cached(condition); + + let merge_id = self.gen_id(); + block.body.push(Instruction::selection_merge( + merge_id, + spirv::SelectionControl::NONE, + )); + + let accept_id = if accept.is_empty() { + None + } else { + Some(self.gen_id()) + }; + let reject_id = if reject.is_empty() { + None + } else { + Some(self.gen_id()) + }; + + self.function.consume( + block, + Instruction::branch_conditional( + condition_id, + accept_id.unwrap_or(merge_id), + reject_id.unwrap_or(merge_id), + ), + ); + + if let Some(block_id) = accept_id { + self.write_block(block_id, accept, Some(merge_id), loop_context)?; + } + if let Some(block_id) = reject_id { + self.write_block(block_id, reject, Some(merge_id), loop_context)?; + } + + block = Block::new(merge_id); + } + crate::Statement::Switch { + selector, + ref cases, + ref default, + } => { + let selector_id = self.cached(selector); + + let merge_id = self.gen_id(); + block.body.push(Instruction::selection_merge( + merge_id, + spirv::SelectionControl::NONE, + )); + + let default_id = self.gen_id(); + let raw_cases = cases + .iter() + .map(|c| super::instructions::Case { + value: c.value as Word, + label_id: self.gen_id(), + }) + .collect::>(); + + self.function.consume( + block, + Instruction::switch(selector_id, default_id, &raw_cases), + ); + + for (i, (case, raw_case)) in cases.iter().zip(raw_cases.iter()).enumerate() { + let case_finish_id = if case.fall_through { + match raw_cases.get(i + 1) { + Some(rc) => rc.label_id, + None => default_id, + } + } else { + merge_id + }; + self.write_block( + raw_case.label_id, + &case.body, + Some(case_finish_id), + LoopContext::default(), + )?; + } + + self.write_block(default_id, default, Some(merge_id), LoopContext::default())?; + + block = Block::new(merge_id); + } + crate::Statement::Loop { + ref body, + ref continuing, + } => { + let preamble_id = self.gen_id(); + self.function + .consume(block, Instruction::branch(preamble_id)); + + let merge_id = self.gen_id(); + let body_id = self.gen_id(); + let continuing_id = self.gen_id(); + + // SPIR-V requires the continuing to the `OpLoopMerge`, + // so we have to start a new block with it. + block = Block::new(preamble_id); + block.body.push(Instruction::loop_merge( + merge_id, + continuing_id, + spirv::SelectionControl::NONE, + )); + self.function.consume(block, Instruction::branch(body_id)); + + self.write_block( + body_id, + body, + Some(continuing_id), + LoopContext { + continuing_id: Some(continuing_id), + break_id: Some(merge_id), + }, + )?; + + self.write_block( + continuing_id, + continuing, + Some(preamble_id), + LoopContext { + continuing_id: None, + break_id: Some(merge_id), + }, + )?; + + block = Block::new(merge_id); + } + crate::Statement::Break => { + self.function + .consume(block, Instruction::branch(loop_context.break_id.unwrap())); + return Ok(()); + } + crate::Statement::Continue => { + self.function.consume( + block, + Instruction::branch(loop_context.continuing_id.unwrap()), + ); + return Ok(()); + } + crate::Statement::Return { value: Some(value) } => { + let value_id = self.cached(value); + let instruction = match self.function.entry_point_context { + // If this is an entry point, and we need to return anything, + // let's instead store the output variables and return `void`. + Some(ref context) => { + self.writer.write_entry_point_return( + value_id, + self.ir_function.result.as_ref().unwrap(), + &context.results, + &mut block.body, + )?; + Instruction::return_void() + } + None => Instruction::return_value(value_id), + }; + self.function.consume(block, instruction); + return Ok(()); + } + crate::Statement::Return { value: None } => { + self.function.consume(block, Instruction::return_void()); + return Ok(()); + } + crate::Statement::Kill => { + self.function.consume(block, Instruction::kill()); + return Ok(()); + } + crate::Statement::Barrier(flags) => { + let memory_scope = if flags.contains(crate::Barrier::STORAGE) { + spirv::Scope::Device + } else { + spirv::Scope::Workgroup + }; + let mut semantics = spirv::MemorySemantics::ACQUIRE_RELEASE; + semantics.set( + spirv::MemorySemantics::UNIFORM_MEMORY, + flags.contains(crate::Barrier::STORAGE), + ); + semantics.set( + spirv::MemorySemantics::WORKGROUP_MEMORY, + flags.contains(crate::Barrier::WORK_GROUP), + ); + let exec_scope_id = self.get_index_constant(spirv::Scope::Workgroup as u32)?; + let mem_scope_id = self.get_index_constant(memory_scope as u32)?; + let semantics_id = self.get_index_constant(semantics.bits())?; + block.body.push(Instruction::control_barrier( + exec_scope_id, + mem_scope_id, + semantics_id, + )); + } + crate::Statement::Store { pointer, value } => { + let value_id = self.cached(value); + match self.write_expression_pointer(pointer, &mut block)? { + ExpressionPointer::Ready { pointer_id } => { + block + .body + .push(Instruction::store(pointer_id, value_id, None)); + } + ExpressionPointer::Conditional { condition, access } => { + let merge_block = self.gen_id(); + let in_bounds_block = self.gen_id(); + + // Emit the conditional branch. + block.body.push(Instruction::selection_merge( + merge_block, + spirv::SelectionControl::NONE, + )); + self.function.consume( + std::mem::replace(&mut block, Block::new(in_bounds_block)), + Instruction::branch_conditional( + condition, + in_bounds_block, + merge_block, + ), + ); + + // The in-bounds path. Perform the access and the store. + let pointer_id = access.result_id.unwrap(); + block.body.push(access); + block + .body + .push(Instruction::store(pointer_id, value_id, None)); + + // Finish the in-bounds block and start the merge block. This + // is the block we'll leave current on return. + self.function.consume( + std::mem::replace(&mut block, Block::new(merge_block)), + Instruction::branch(merge_block), + ); + } + }; + } + crate::Statement::ImageStore { + image, + coordinate, + array_index, + value, + } => { + let image_id = self.get_expression_global(image); + let coordinate_id = + self.write_texture_coordinates(coordinate, array_index, &mut block)?; + let value_id = self.cached(value); + + block + .body + .push(Instruction::image_write(image_id, coordinate_id, value_id)); + } + crate::Statement::Call { + function: local_function, + ref arguments, + result, + } => { + let id = self.gen_id(); + self.temp_list.clear(); + for &argument in arguments { + self.temp_list.push(self.cached(argument)); + } + + let type_id = match result { + Some(expr) => { + self.writer.cached[expr] = id; + self.writer.lookup_function_call.insert(expr, id); + let ty_handle = self.ir_module.functions[local_function] + .result + .as_ref() + .unwrap() + .ty; + self.get_type_id(LookupType::Handle(ty_handle))? + } + None => self.writer.void_type, + }; + + block.body.push(Instruction::function_call( + type_id, + id, + self.writer.lookup_function[&local_function], + &self.temp_list, + )); + } + } + } + + let termination = match exit_id { + Some(id) => Instruction::branch(id), + // This can happen if the last branch had all the paths + // leading out of the graph (i.e. returning). + // Or it may be the end of the self.function. + None => match self.ir_function.result { + Some(ref result) if self.function.entry_point_context.is_none() => { + let type_id = self.get_type_id(LookupType::Handle(result.ty))?; + let null_id = self.writer.write_constant_null(type_id); + Instruction::return_value(null_id) + } + _ => Instruction::return_void(), + }, + }; + + self.function.consume(block, termination); + Ok(()) + } +} diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 0bf831b34..98cdbcf0c 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -1,6 +1,7 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ +mod block; mod helpers; mod index; mod instructions; @@ -10,7 +11,7 @@ mod writer; pub use spirv::Capability; -use crate::{arena::Handle, back::IndexBoundsCheckPolicy}; +use crate::{arena::Handle, back::IndexBoundsCheckPolicy, proc::TypeResolution}; use spirv::Word; use std::ops; @@ -205,6 +206,58 @@ struct LookupFunctionType { return_type_id: Word, } +fn make_local(inner: &crate::TypeInner) -> Option { + Some(match *inner { + crate::TypeInner::Scalar { kind, width } => LocalType::Value { + vector_size: None, + kind, + width, + pointer_class: None, + }, + crate::TypeInner::Vector { size, kind, width } => LocalType::Value { + vector_size: Some(size), + kind, + width, + pointer_class: None, + }, + crate::TypeInner::Matrix { + columns, + rows, + width, + } => LocalType::Matrix { + columns, + rows, + width, + }, + crate::TypeInner::Pointer { base, class } => LocalType::Pointer { + base, + class: helpers::map_storage_class(class), + }, + crate::TypeInner::ValuePointer { + size, + kind, + width, + class, + } => LocalType::Value { + vector_size: size, + kind, + width, + pointer_class: Some(helpers::map_storage_class(class)), + }, + crate::TypeInner::Image { + dim, + arrayed, + class, + } => LocalType::Image { + dim, + arrayed, + class, + }, + crate::TypeInner::Sampler { comparison: _ } => LocalType::Sampler, + _ => return None, + }) +} + #[derive(Debug)] enum Dimension { Scalar, @@ -280,6 +333,31 @@ struct BlockContext<'w> { temp_list: Vec, } +impl BlockContext<'_> { + fn gen_id(&mut self) -> Word { + self.writer.id_gen.next() + } + + fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Result { + self.writer.get_expression_type_id(tr) + } + + fn get_index_constant(&mut self, index: Word) -> Result { + self.writer + .get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) + } + + fn cached(&self, expression: Handle) -> Word { + self.writer.cached[expression] + } +} + +#[derive(Clone, Copy, Default)] +struct LoopContext { + continuing_id: Option, + break_id: Option, +} + pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4339adec1..2e7f90169 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,10 +1,9 @@ use super::{ helpers::{contains_builtin, map_storage_class}, - index::{BoundsCheckResult, ExpressionPointer}, - Block, BlockContext, CachedExpressions, Dimension, EntryPointContext, Error, Function, + make_local, Block, BlockContext, CachedExpressions, EntryPointContext, Error, Function, GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, LogicalLayout, - LookupFunctionType, LookupType, Options, PhysicalLayout, ResultMember, Writer, WriterFlags, - BITS_PER_BYTE, + LookupFunctionType, LookupType, LoopContext, Options, PhysicalLayout, ResultMember, Writer, + WriterFlags, BITS_PER_BYTE, }; use crate::{ arena::{Arena, Handle}, @@ -23,15 +22,6 @@ fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { } } -fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { - match *type_inner { - crate::TypeInner::Scalar { .. } => Dimension::Scalar, - crate::TypeInner::Vector { .. } => Dimension::Vector, - crate::TypeInner::Matrix { .. } => Dimension::Matrix, - _ => unreachable!(), - } -} - impl Function { fn to_words(&self, sink: &mut impl Extend) { self.signature.as_ref().unwrap().to_words(sink); @@ -52,66 +42,6 @@ impl Function { } } -impl PhysicalLayout { - fn make_local(&self, inner: &crate::TypeInner) -> Option { - Some(match *inner { - crate::TypeInner::Scalar { kind, width } => LocalType::Value { - vector_size: None, - kind, - width, - pointer_class: None, - }, - crate::TypeInner::Vector { size, kind, width } => LocalType::Value { - vector_size: Some(size), - kind, - width, - pointer_class: None, - }, - crate::TypeInner::Matrix { - columns, - rows, - width, - } => LocalType::Matrix { - columns, - rows, - width, - }, - crate::TypeInner::Pointer { base, class } => LocalType::Pointer { - base, - class: map_storage_class(class), - }, - crate::TypeInner::ValuePointer { - size, - kind, - width, - class, - } => LocalType::Value { - vector_size: size, - kind, - width, - pointer_class: Some(map_storage_class(class)), - }, - crate::TypeInner::Image { - dim, - arrayed, - class, - } => LocalType::Image { - dim, - arrayed, - class, - }, - crate::TypeInner::Sampler { comparison: _ } => LocalType::Sampler, - _ => return None, - }) - } -} - -#[derive(Clone, Copy, Default)] -struct LoopContext { - continuing_id: Option, - break_id: Option, -} - impl Writer { pub fn new(options: &Options) -> Result { let (major, minor) = options.lang_version; @@ -208,7 +138,7 @@ impl Writer { *self = fresh; } - fn check(&mut self, capabilities: &[spirv::Capability]) -> Result<(), Error> { + pub(super) fn check(&mut self, capabilities: &[spirv::Capability]) -> Result<(), Error> { if capabilities.is_empty() || capabilities .iter() @@ -226,7 +156,7 @@ impl Writer { Err(Error::MissingCapabilities(capabilities.to_vec())) } - fn get_type_id(&mut self, lookup_ty: LookupType) -> Result { + pub(super) fn get_type_id(&mut self, lookup_ty: LookupType) -> Result { if let Entry::Occupied(e) = self.lookup_type.entry(lookup_ty) { Ok(*e.get()) } else { @@ -240,9 +170,7 @@ impl Writer { pub(super) fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Result { let lookup_ty = match *tr { TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), - TypeResolution::Value(ref inner) => { - LookupType::Local(self.physical_layout.make_local(inner).unwrap()) - } + TypeResolution::Value(ref inner) => LookupType::Local(make_local(inner).unwrap()), }; self.get_type_id(lookup_ty) } @@ -687,7 +615,7 @@ impl Writer { let ty = &arena[handle]; let decorate_layout = true; //TODO? - let id = if let Some(local) = self.physical_layout.make_local(&ty.inner) { + let id = if let Some(local) = make_local(&ty.inner) { match self.lookup_type.entry(LookupType::Local(local)) { // if it's already known as local, re-use it Entry::Occupied(e) => { @@ -874,7 +802,7 @@ impl Writer { self.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) } - fn get_constant_scalar( + pub(super) fn get_constant_scalar( &mut self, value: crate::ScalarValue, width: crate::Bytes, @@ -1135,72 +1063,6 @@ impl Writer { } } - fn write_entry_point_return( - &mut self, - value_id: Word, - ir_result: &crate::FunctionResult, - result_members: &[ResultMember], - body: &mut Vec, - ) -> Result<(), Error> { - for (index, res_member) in result_members.iter().enumerate() { - let member_value_id = match ir_result.binding { - Some(_) => value_id, - None => { - let member_value_id = self.id_gen.next(); - body.push(Instruction::composite_extract( - res_member.type_id, - member_value_id, - value_id, - &[index as u32], - )); - member_value_id - } - }; - - body.push(Instruction::store(res_member.id, member_value_id, None)); - - // Flip Y coordinate to adjust for coordinate space difference - // between SPIR-V and our IR. - if self.flags.contains(WriterFlags::ADJUST_COORDINATE_SPACE) - && res_member.built_in == Some(crate::BuiltIn::Position) - { - let access_id = self.id_gen.next(); - let float_ptr_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: Some(spirv::StorageClass::Output), - }))?; - let index_y_id = self.get_index_constant(1)?; - body.push(Instruction::access_chain( - float_ptr_type_id, - access_id, - res_member.id, - &[index_y_id], - )); - - let load_id = self.id_gen.next(); - let float_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))?; - body.push(Instruction::load(float_type_id, load_id, access_id, None)); - - let neg_id = self.id_gen.next(); - body.push(Instruction::unary( - spirv::Op::FNegate, - float_type_id, - neg_id, - load_id, - )); - body.push(Instruction::store(access_id, neg_id, None)); - } - } - Ok(()) - } - fn write_physical_layout(&mut self) { self.physical_layout.bound = self.id_gen.0 + 1; } @@ -1338,1521 +1200,6 @@ impl Writer { } } -impl<'w> BlockContext<'w> { - pub(super) fn gen_id(&mut self) -> Word { - self.writer.id_gen.next() - } - - fn get_type_id(&mut self, lookup_type: LookupType) -> Result { - self.writer.get_type_id(lookup_type) - } - - pub(super) fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Result { - self.writer.get_expression_type_id(tr) - } - - pub(super) fn get_index_constant(&mut self, index: Word) -> Result { - self.writer - .get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) - } - - pub(super) fn cached(&self, expression: Handle) -> Word { - self.writer.cached[expression] - } - - fn write_texture_coordinates( - &mut self, - coordinates: Handle, - array_index: Option>, - block: &mut Block, - ) -> Result { - let coordinate_id = self.cached(coordinates); - - Ok(if let Some(array_index) = array_index { - let coordinate_scalar_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))?; - - let mut constituent_ids = [0u32; 4]; - let size = match *self.fun_info[coordinates] - .ty - .inner_with(&self.ir_module.types) - { - crate::TypeInner::Scalar { .. } => { - constituent_ids[0] = coordinate_id; - crate::VectorSize::Bi - } - crate::TypeInner::Vector { size, .. } => { - for i in 0..size as u32 { - let id = self.gen_id(); - constituent_ids[i as usize] = id; - block.body.push(Instruction::composite_extract( - coordinate_scalar_type_id, - id, - coordinate_id, - &[i], - )); - } - match size { - crate::VectorSize::Bi => crate::VectorSize::Tri, - crate::VectorSize::Tri => crate::VectorSize::Quad, - crate::VectorSize::Quad => { - return Err(Error::Validation("extending vec4 coordinate")); - } - } - } - ref other => { - log::error!("wrong coordinate type {:?}", other); - return Err(Error::Validation("coordinate type")); - } - }; - - let array_index_f32_id = self.gen_id(); - constituent_ids[size as usize - 1] = array_index_f32_id; - - let array_index_u32_id = self.cached(array_index); - let cast_instruction = Instruction::unary( - spirv::Op::ConvertUToF, - coordinate_scalar_type_id, - array_index_f32_id, - array_index_u32_id, - ); - block.body.push(cast_instruction); - - let extended_coordinate_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(size), - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))?; - - let id = self.gen_id(); - block.body.push(Instruction::composite_construct( - extended_coordinate_type_id, - id, - &constituent_ids[..size as usize], - )); - id - } else { - coordinate_id - }) - } - - /// Decide whether to put off emitting instructions for `expr_handle`. - /// - /// We would like to gather together chains of `Access` and `AccessIndex` - /// Naga expressions into a single `OpAccessChain` SPIR-V instruction. To do - /// this, we don't generate instructions for these exprs when we first - /// encounter them. Their ids in `self.writer.cached.ids` are left as zero. Then, - /// once we encounter a `Load` or `Store` expression that actually needs the - /// chain's value, we call `write_expression_pointer` to handle the whole - /// thing in one fell swoop. - fn is_intermediate(&self, expr_handle: Handle) -> bool { - match self.ir_function.expressions[expr_handle] { - crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => true, - crate::Expression::FunctionArgument(index) => { - let arg = &self.ir_function.arguments[index as usize]; - match self.ir_module.types[arg.ty].inner { - crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { - true - } - _ => false, - } - } - - // The chain rule: if this `Access...`'s `base` operand was - // previously omitted, then omit this one, too. - _ => self.writer.cached.ids[expr_handle.index()] == 0, - } - } - - /// Cache an expression for a value. - fn cache_expression_value( - &mut self, - expr_handle: Handle, - block: &mut Block, - ) -> Result<(), Error> { - let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty)?; - - let id = match self.ir_function.expressions[expr_handle] { - crate::Expression::Access { base, index: _ } if self.is_intermediate(base) => { - // See `is_intermediate`; we'll handle this later in - // `write_expression_pointer`. - 0 - } - crate::Expression::Access { base, index } => { - let base_ty = self.fun_info[base].ty.inner_with(&self.ir_module.types); - match *base_ty { - crate::TypeInner::Vector { .. } => (), - ref other => { - log::error!( - "Unable to access base {:?} of type {:?}", - self.ir_function.expressions[base], - other - ); - return Err(Error::Validation( - "only vectors may be dynamically indexed by value", - )); - } - }; - - self.write_vector_access(expr_handle, base, index, block)? - } - crate::Expression::AccessIndex { base, index: _ } if self.is_intermediate(base) => { - // See `is_intermediate`; we'll handle this later in - // `write_expression_pointer`. - 0 - } - crate::Expression::AccessIndex { base, index } => { - match *self.fun_info[base].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Vector { .. } - | crate::TypeInner::Matrix { .. } - | crate::TypeInner::Array { .. } - | crate::TypeInner::Struct { .. } => { - let id = self.gen_id(); - let base_id = self.cached(base); - block.body.push(Instruction::composite_extract( - result_type_id, - id, - base_id, - &[index], - )); - id - } - ref other => { - log::error!("Unable to access index of {:?}", other); - return Err(Error::FeatureNotImplemented("access index for type")); - } - } - } - crate::Expression::GlobalVariable(handle) => { - self.writer.global_variables[handle.index()].id - } - crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], - crate::Expression::Splat { size, value } => { - let value_id = self.cached(value); - self.temp_list.clear(); - self.temp_list.resize(size as usize, value_id); - - let id = self.gen_id(); - block.body.push(Instruction::composite_construct( - result_type_id, - id, - &self.temp_list, - )); - id - } - crate::Expression::Swizzle { - size, - vector, - pattern, - } => { - let vector_id = self.cached(vector); - self.temp_list.clear(); - for &sc in pattern[..size as usize].iter() { - self.temp_list.push(sc as Word); - } - let id = self.gen_id(); - block.body.push(Instruction::vector_shuffle( - result_type_id, - id, - vector_id, - vector_id, - &self.temp_list, - )); - id - } - crate::Expression::Compose { - ty: _, - ref components, - } => { - self.temp_list.clear(); - for &component in components { - self.temp_list.push(self.cached(component)); - } - - let id = self.gen_id(); - block.body.push(Instruction::composite_construct( - result_type_id, - id, - &self.temp_list, - )); - id - } - crate::Expression::Unary { op, expr } => { - let id = self.gen_id(); - let expr_id = self.cached(expr); - let expr_ty_inner = self.fun_info[expr].ty.inner_with(&self.ir_module.types); - - let spirv_op = match op { - crate::UnaryOperator::Negate => match expr_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Float) => spirv::Op::FNegate, - Some(crate::ScalarKind::Sint) => spirv::Op::SNegate, - Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNot, - Some(crate::ScalarKind::Uint) | None => { - log::error!("Unable to negate {:?}", expr_ty_inner); - return Err(Error::FeatureNotImplemented("negation")); - } - }, - crate::UnaryOperator::Not => match expr_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNot, - _ => spirv::Op::Not, - }, - }; - - block - .body - .push(Instruction::unary(spirv_op, result_type_id, id, expr_id)); - id - } - crate::Expression::Binary { op, left, right } => { - let id = self.gen_id(); - let left_id = self.cached(left); - let right_id = self.cached(right); - - let left_ty_inner = self.fun_info[left].ty.inner_with(&self.ir_module.types); - let right_ty_inner = self.fun_info[right].ty.inner_with(&self.ir_module.types); - - let left_dimension = get_dimension(left_ty_inner); - let right_dimension = get_dimension(right_ty_inner); - - let mut preserve_order = true; - - let spirv_op = match op { - crate::BinaryOperator::Add => match *left_ty_inner { - crate::TypeInner::Scalar { kind, .. } - | crate::TypeInner::Vector { kind, .. } => match kind { - crate::ScalarKind::Float => spirv::Op::FAdd, - _ => spirv::Op::IAdd, - }, - _ => unimplemented!(), - }, - crate::BinaryOperator::Subtract => match *left_ty_inner { - crate::TypeInner::Scalar { kind, .. } - | crate::TypeInner::Vector { kind, .. } => match kind { - crate::ScalarKind::Float => spirv::Op::FSub, - _ => spirv::Op::ISub, - }, - _ => unimplemented!(), - }, - crate::BinaryOperator::Multiply => match (left_dimension, right_dimension) { - (Dimension::Scalar, Dimension::Vector { .. }) => { - preserve_order = false; - spirv::Op::VectorTimesScalar - } - (Dimension::Vector, Dimension::Scalar { .. }) => { - spirv::Op::VectorTimesScalar - } - (Dimension::Vector, Dimension::Matrix) => spirv::Op::VectorTimesMatrix, - (Dimension::Matrix, Dimension::Scalar { .. }) => { - spirv::Op::MatrixTimesScalar - } - (Dimension::Matrix, Dimension::Vector) => spirv::Op::MatrixTimesVector, - (Dimension::Matrix, Dimension::Matrix) => spirv::Op::MatrixTimesMatrix, - (Dimension::Vector, Dimension::Vector) - | (Dimension::Scalar, Dimension::Scalar) - if left_ty_inner.scalar_kind() == Some(crate::ScalarKind::Float) => - { - spirv::Op::FMul - } - (Dimension::Vector, Dimension::Vector) - | (Dimension::Scalar, Dimension::Scalar) => spirv::Op::IMul, - other => unimplemented!("Mul {:?}", other), - }, - crate::BinaryOperator::Divide => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) => spirv::Op::SDiv, - Some(crate::ScalarKind::Uint) => spirv::Op::UDiv, - Some(crate::ScalarKind::Float) => spirv::Op::FDiv, - _ => unimplemented!(), - }, - crate::BinaryOperator::Modulo => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) => spirv::Op::SMod, - Some(crate::ScalarKind::Uint) => spirv::Op::UMod, - Some(crate::ScalarKind::Float) => spirv::Op::FMod, - _ => unimplemented!(), - }, - crate::BinaryOperator::Equal => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { - spirv::Op::IEqual - } - Some(crate::ScalarKind::Float) => spirv::Op::FOrdEqual, - Some(crate::ScalarKind::Bool) => spirv::Op::LogicalEqual, - _ => unimplemented!(), - }, - crate::BinaryOperator::NotEqual => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { - spirv::Op::INotEqual - } - Some(crate::ScalarKind::Float) => spirv::Op::FOrdNotEqual, - Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNotEqual, - _ => unimplemented!(), - }, - crate::BinaryOperator::Less => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) => spirv::Op::SLessThan, - Some(crate::ScalarKind::Uint) => spirv::Op::ULessThan, - Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThan, - _ => unimplemented!(), - }, - crate::BinaryOperator::LessEqual => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) => spirv::Op::SLessThanEqual, - Some(crate::ScalarKind::Uint) => spirv::Op::ULessThanEqual, - Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThanEqual, - _ => unimplemented!(), - }, - crate::BinaryOperator::Greater => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThan, - Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThan, - Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThan, - _ => unimplemented!(), - }, - crate::BinaryOperator::GreaterEqual => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThanEqual, - Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThanEqual, - Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThanEqual, - _ => unimplemented!(), - }, - crate::BinaryOperator::And => spirv::Op::BitwiseAnd, - crate::BinaryOperator::ExclusiveOr => spirv::Op::BitwiseXor, - crate::BinaryOperator::InclusiveOr => spirv::Op::BitwiseOr, - crate::BinaryOperator::LogicalAnd => spirv::Op::LogicalAnd, - crate::BinaryOperator::LogicalOr => spirv::Op::LogicalOr, - crate::BinaryOperator::ShiftLeft => spirv::Op::ShiftLeftLogical, - crate::BinaryOperator::ShiftRight => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) => spirv::Op::ShiftRightArithmetic, - Some(crate::ScalarKind::Uint) => spirv::Op::ShiftRightLogical, - _ => unimplemented!(), - }, - }; - - block.body.push(Instruction::binary( - spirv_op, - result_type_id, - id, - if preserve_order { left_id } else { right_id }, - if preserve_order { right_id } else { left_id }, - )); - id - } - crate::Expression::Math { - fun, - arg, - arg1, - arg2, - } => { - use crate::MathFunction as Mf; - enum MathOp { - Ext(spirv::GLOp), - Custom(Instruction), - } - - let arg0_id = self.cached(arg); - let arg_scalar_kind = self.fun_info[arg] - .ty - .inner_with(&self.ir_module.types) - .scalar_kind(); - let arg1_id = match arg1 { - Some(handle) => self.cached(handle), - None => 0, - }; - let arg2_id = match arg2 { - Some(handle) => self.cached(handle), - None => 0, - }; - - let id = self.gen_id(); - let math_op = match fun { - // comparison - Mf::Abs => { - match arg_scalar_kind { - Some(crate::ScalarKind::Float) => MathOp::Ext(spirv::GLOp::FAbs), - Some(crate::ScalarKind::Sint) => MathOp::Ext(spirv::GLOp::SAbs), - Some(crate::ScalarKind::Uint) => { - MathOp::Custom(Instruction::unary( - spirv::Op::CopyObject, // do nothing - result_type_id, - id, - arg0_id, - )) - } - other => unimplemented!("Unexpected abs({:?})", other), - } - } - Mf::Min => MathOp::Ext(match arg_scalar_kind { - Some(crate::ScalarKind::Float) => spirv::GLOp::FMin, - Some(crate::ScalarKind::Sint) => spirv::GLOp::SMin, - Some(crate::ScalarKind::Uint) => spirv::GLOp::UMin, - other => unimplemented!("Unexpected min({:?})", other), - }), - Mf::Max => MathOp::Ext(match arg_scalar_kind { - Some(crate::ScalarKind::Float) => spirv::GLOp::FMax, - Some(crate::ScalarKind::Sint) => spirv::GLOp::SMax, - Some(crate::ScalarKind::Uint) => spirv::GLOp::UMax, - other => unimplemented!("Unexpected max({:?})", other), - }), - Mf::Clamp => MathOp::Ext(match arg_scalar_kind { - Some(crate::ScalarKind::Float) => spirv::GLOp::FClamp, - Some(crate::ScalarKind::Sint) => spirv::GLOp::SClamp, - Some(crate::ScalarKind::Uint) => spirv::GLOp::UClamp, - other => unimplemented!("Unexpected max({:?})", other), - }), - // trigonometry - Mf::Sin => MathOp::Ext(spirv::GLOp::Sin), - Mf::Sinh => MathOp::Ext(spirv::GLOp::Sinh), - Mf::Asin => MathOp::Ext(spirv::GLOp::Asin), - Mf::Cos => MathOp::Ext(spirv::GLOp::Cos), - Mf::Cosh => MathOp::Ext(spirv::GLOp::Cosh), - Mf::Acos => MathOp::Ext(spirv::GLOp::Acos), - Mf::Tan => MathOp::Ext(spirv::GLOp::Tan), - Mf::Tanh => MathOp::Ext(spirv::GLOp::Tanh), - Mf::Atan => MathOp::Ext(spirv::GLOp::Atan), - Mf::Atan2 => MathOp::Ext(spirv::GLOp::Atan2), - // decomposition - Mf::Ceil => MathOp::Ext(spirv::GLOp::Ceil), - Mf::Round => MathOp::Ext(spirv::GLOp::Round), - Mf::Floor => MathOp::Ext(spirv::GLOp::Floor), - Mf::Fract => MathOp::Ext(spirv::GLOp::Fract), - Mf::Trunc => MathOp::Ext(spirv::GLOp::Trunc), - Mf::Modf => MathOp::Ext(spirv::GLOp::Modf), - Mf::Frexp => MathOp::Ext(spirv::GLOp::Frexp), - Mf::Ldexp => MathOp::Ext(spirv::GLOp::Ldexp), - // geometry - Mf::Dot => MathOp::Custom(Instruction::binary( - spirv::Op::Dot, - result_type_id, - id, - arg0_id, - arg1_id, - )), - Mf::Outer => MathOp::Custom(Instruction::binary( - spirv::Op::OuterProduct, - result_type_id, - id, - arg0_id, - arg1_id, - )), - Mf::Cross => MathOp::Ext(spirv::GLOp::Cross), - Mf::Distance => MathOp::Ext(spirv::GLOp::Distance), - Mf::Length => MathOp::Ext(spirv::GLOp::Length), - Mf::Normalize => MathOp::Ext(spirv::GLOp::Normalize), - Mf::FaceForward => MathOp::Ext(spirv::GLOp::FaceForward), - Mf::Reflect => MathOp::Ext(spirv::GLOp::Reflect), - Mf::Refract => MathOp::Ext(spirv::GLOp::Refract), - // exponent - Mf::Exp => MathOp::Ext(spirv::GLOp::Exp), - Mf::Exp2 => MathOp::Ext(spirv::GLOp::Exp2), - Mf::Log => MathOp::Ext(spirv::GLOp::Log), - Mf::Log2 => MathOp::Ext(spirv::GLOp::Log2), - Mf::Pow => MathOp::Ext(spirv::GLOp::Pow), - // computational - Mf::Sign => MathOp::Ext(match arg_scalar_kind { - Some(crate::ScalarKind::Float) => spirv::GLOp::FSign, - Some(crate::ScalarKind::Sint) => spirv::GLOp::SSign, - other => unimplemented!("Unexpected sign({:?})", other), - }), - Mf::Fma => MathOp::Ext(spirv::GLOp::Fma), - Mf::Mix => MathOp::Ext(spirv::GLOp::FMix), - Mf::Step => MathOp::Ext(spirv::GLOp::Step), - Mf::SmoothStep => MathOp::Ext(spirv::GLOp::SmoothStep), - Mf::Sqrt => MathOp::Ext(spirv::GLOp::Sqrt), - Mf::InverseSqrt => MathOp::Ext(spirv::GLOp::InverseSqrt), - Mf::Inverse => MathOp::Ext(spirv::GLOp::MatrixInverse), - Mf::Transpose => MathOp::Custom(Instruction::unary( - spirv::Op::Transpose, - result_type_id, - id, - arg0_id, - )), - Mf::Determinant => MathOp::Ext(spirv::GLOp::Determinant), - Mf::ReverseBits | Mf::CountOneBits => { - log::error!("unimplemented math function {:?}", fun); - return Err(Error::FeatureNotImplemented("math function")); - } - }; - - block.body.push(match math_op { - MathOp::Ext(op) => Instruction::ext_inst( - self.writer.gl450_ext_inst_id, - op, - result_type_id, - id, - &[arg0_id, arg1_id, arg2_id][..fun.argument_count()], - ), - MathOp::Custom(inst) => inst, - }); - id - } - crate::Expression::LocalVariable(variable) => self.function.variables[&variable].id, - crate::Expression::Load { pointer } => { - match self.write_expression_pointer(pointer, block)? { - ExpressionPointer::Ready { pointer_id } => { - let id = self.gen_id(); - block - .body - .push(Instruction::load(result_type_id, id, pointer_id, None)); - id - } - ExpressionPointer::Conditional { condition, access } => { - self.write_conditional_indexed_load( - result_type_id, - condition, - block, - move |id_gen, block| { - // The in-bounds path. Perform the access and the load. - let pointer_id = access.result_id.unwrap(); - let value_id = id_gen.next(); - block.body.push(access); - block.body.push(Instruction::load( - result_type_id, - value_id, - pointer_id, - None, - )); - value_id - }, - ) - } - } - } - crate::Expression::FunctionArgument(index) => self.function.parameter_id(index), - crate::Expression::Call(_function) => self.writer.lookup_function_call[&expr_handle], - crate::Expression::As { - expr, - kind, - convert, - } => { - use crate::ScalarKind as Sk; - - let expr_id = self.cached(expr); - let (src_kind, src_width) = - match *self.fun_info[expr].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Scalar { kind, width } - | crate::TypeInner::Vector { - kind, - width, - size: _, - } => (kind, width), - crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), - ref other => { - log::error!("As source {:?}", other); - return Err(Error::Validation("Unexpected Expression::As source")); - } - }; - - let op = match (src_kind, kind, convert) { - (_, _, None) => spirv::Op::Bitcast, - (Sk::Float, Sk::Uint, Some(_)) => spirv::Op::ConvertFToU, - (Sk::Float, Sk::Sint, Some(_)) => spirv::Op::ConvertFToS, - (Sk::Float, Sk::Float, Some(dst_width)) if src_width != dst_width => { - spirv::Op::FConvert - } - (Sk::Sint, Sk::Float, Some(_)) => spirv::Op::ConvertSToF, - (Sk::Sint, Sk::Sint, Some(dst_width)) if src_width != dst_width => { - spirv::Op::SConvert - } - (Sk::Uint, Sk::Float, Some(_)) => spirv::Op::ConvertUToF, - (Sk::Uint, Sk::Uint, Some(dst_width)) if src_width != dst_width => { - spirv::Op::UConvert - } - // We assume it's either an identity cast, or int-uint. - _ => spirv::Op::Bitcast, - }; - - let id = self.gen_id(); - let instruction = Instruction::unary(op, result_type_id, id, expr_id); - block.body.push(instruction); - id - } - crate::Expression::ImageLoad { - image, - coordinate, - array_index, - index, - } => { - let image_id = self.get_expression_global(image); - let coordinate_id = - self.write_texture_coordinates(coordinate, array_index, block)?; - - let id = self.gen_id(); - - let image_ty = self.fun_info[image].ty.inner_with(&self.ir_module.types); - let mut instruction = match *image_ty { - crate::TypeInner::Image { - class: crate::ImageClass::Storage { .. }, - .. - } => Instruction::image_read(result_type_id, id, image_id, coordinate_id), - crate::TypeInner::Image { - class: crate::ImageClass::Depth, - .. - } => { - // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, - // so we need to grab the first component out of it. - let load_result_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(crate::VectorSize::Quad), - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))?; - Instruction::image_fetch(load_result_type_id, id, image_id, coordinate_id) - } - _ => Instruction::image_fetch(result_type_id, id, image_id, coordinate_id), - }; - - if let Some(index) = index { - let index_id = self.cached(index); - let image_ops = match *self.fun_info[image].ty.inner_with(&self.ir_module.types) - { - crate::TypeInner::Image { - class: crate::ImageClass::Sampled { multi: true, .. }, - .. - } => spirv::ImageOperands::SAMPLE, - _ => spirv::ImageOperands::LOD, - }; - instruction.add_operand(image_ops.bits()); - instruction.add_operand(index_id); - } - - let inst_type_id = instruction.type_id; - block.body.push(instruction); - if inst_type_id != Some(result_type_id) { - let sub_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - result_type_id, - sub_id, - id, - &[0], - )); - sub_id - } else { - id - } - } - crate::Expression::ImageSample { - image, - sampler, - coordinate, - array_index, - offset, - level, - depth_ref, - } => { - use super::instructions::SampleLod; - // image - let image_id = self.get_expression_global(image); - let image_type = self.fun_info[image].ty.handle().unwrap(); - // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, - // so we need to grab the first component out of it. - let needs_sub_access = match self.ir_module.types[image_type].inner { - crate::TypeInner::Image { - class: crate::ImageClass::Depth, - .. - } => depth_ref.is_none(), - _ => false, - }; - let sample_result_type_id = if needs_sub_access { - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(crate::VectorSize::Quad), - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))? - } else { - result_type_id - }; - - // OpTypeSampledImage - let image_type_id = self.get_type_id(LookupType::Handle(image_type))?; - let sampled_image_type_id = - self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id }))?; - - let sampler_id = self.get_expression_global(sampler); - let coordinate_id = - self.write_texture_coordinates(coordinate, array_index, block)?; - - let sampled_image_id = self.gen_id(); - block.body.push(Instruction::sampled_image( - sampled_image_type_id, - sampled_image_id, - image_id, - sampler_id, - )); - let id = self.gen_id(); - - let depth_id = depth_ref.map(|handle| self.cached(handle)); - let mut mask = spirv::ImageOperands::empty(); - mask.set(spirv::ImageOperands::CONST_OFFSET, offset.is_some()); - - let mut main_instruction = match level { - crate::SampleLevel::Zero => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Explicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - - let zero_id = self - .writer - .get_constant_scalar(crate::ScalarValue::Float(0.0), 4)?; - - mask |= spirv::ImageOperands::LOD; - inst.add_operand(mask.bits()); - inst.add_operand(zero_id); - - inst - } - crate::SampleLevel::Auto => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Implicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - if !mask.is_empty() { - inst.add_operand(mask.bits()); - } - inst - } - crate::SampleLevel::Exact(lod_handle) => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Explicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - - let lod_id = self.cached(lod_handle); - mask |= spirv::ImageOperands::LOD; - inst.add_operand(mask.bits()); - inst.add_operand(lod_id); - - inst - } - crate::SampleLevel::Bias(bias_handle) => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Implicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - - let bias_id = self.cached(bias_handle); - mask |= spirv::ImageOperands::BIAS; - inst.add_operand(mask.bits()); - inst.add_operand(bias_id); - - inst - } - crate::SampleLevel::Gradient { x, y } => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Explicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - - let x_id = self.cached(x); - let y_id = self.cached(y); - mask |= spirv::ImageOperands::GRAD; - inst.add_operand(mask.bits()); - inst.add_operand(x_id); - inst.add_operand(y_id); - - inst - } - }; - - if let Some(offset_const) = offset { - let offset_id = self.writer.constant_ids[offset_const.index()]; - main_instruction.add_operand(offset_id); - } - - block.body.push(main_instruction); - - if needs_sub_access { - let sub_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - result_type_id, - sub_id, - id, - &[0], - )); - sub_id - } else { - id - } - } - crate::Expression::Select { - condition, - accept, - reject, - } => { - let id = self.gen_id(); - let condition_id = self.cached(condition); - let accept_id = self.cached(accept); - let reject_id = self.cached(reject); - - let instruction = - Instruction::select(result_type_id, id, condition_id, accept_id, reject_id); - block.body.push(instruction); - id - } - crate::Expression::Derivative { axis, expr } => { - use crate::DerivativeAxis as Da; - - let id = self.gen_id(); - let expr_id = self.cached(expr); - let op = match axis { - Da::X => spirv::Op::DPdx, - Da::Y => spirv::Op::DPdy, - Da::Width => spirv::Op::Fwidth, - }; - block - .body - .push(Instruction::derivative(op, result_type_id, id, expr_id)); - id - } - crate::Expression::ImageQuery { image, query } => { - use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq}; - - let image_id = self.get_expression_global(image); - let image_type = self.fun_info[image].ty.handle().unwrap(); - let (dim, arrayed, class) = match self.ir_module.types[image_type].inner { - crate::TypeInner::Image { - dim, - arrayed, - class, - } => (dim, arrayed, class), - _ => { - return Err(Error::Validation("image type")); - } - }; - - self.writer.check(&[spirv::Capability::ImageQuery])?; - - match query { - Iq::Size { level } => { - let dim_coords = match dim { - Id::D1 => 1, - Id::D2 | Id::Cube => 2, - Id::D3 => 3, - }; - let extended_size_type_id = { - let array_coords = if arrayed { 1 } else { 0 }; - let vector_size = match dim_coords + array_coords { - 2 => Some(crate::VectorSize::Bi), - 3 => Some(crate::VectorSize::Tri), - 4 => Some(crate::VectorSize::Quad), - _ => None, - }; - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size, - kind: crate::ScalarKind::Sint, - width: 4, - pointer_class: None, - }))? - }; - - let (query_op, level_id) = match class { - Ic::Storage(_) => (spirv::Op::ImageQuerySize, None), - _ => { - let level_id = match level { - Some(expr) => self.cached(expr), - None => self.get_index_constant(0)?, - }; - (spirv::Op::ImageQuerySizeLod, Some(level_id)) - } - }; - - // The ID of the vector returned by SPIR-V, which contains the dimensions - // as well as the layer count. - let id_extended = self.gen_id(); - let mut inst = Instruction::image_query( - query_op, - extended_size_type_id, - id_extended, - image_id, - ); - if let Some(expr_id) = level_id { - inst.add_operand(expr_id); - } - block.body.push(inst); - - if result_type_id != extended_size_type_id { - let id = self.gen_id(); - let components = match dim { - // always pick the first component, and duplicate it for all 3 dimensions - Id::Cube => &[0u32, 0, 0][..], - _ => &[0u32, 1, 2, 3][..dim_coords], - }; - block.body.push(Instruction::vector_shuffle( - result_type_id, - id, - id_extended, - id_extended, - components, - )); - id - } else { - id_extended - } - } - Iq::NumLevels => { - let id = self.gen_id(); - block.body.push(Instruction::image_query( - spirv::Op::ImageQueryLevels, - result_type_id, - id, - image_id, - )); - id - } - Iq::NumLayers => { - let vec_size = match dim { - Id::D1 => crate::VectorSize::Bi, - Id::D2 | Id::Cube => crate::VectorSize::Tri, - Id::D3 => crate::VectorSize::Quad, - }; - let extended_size_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(vec_size), - kind: crate::ScalarKind::Sint, - width: 4, - pointer_class: None, - }))?; - let id_extended = self.gen_id(); - let mut inst = Instruction::image_query( - spirv::Op::ImageQuerySizeLod, - extended_size_type_id, - id_extended, - image_id, - ); - inst.add_operand(self.get_index_constant(0)?); - block.body.push(inst); - let id = self.gen_id(); - block.body.push(Instruction::composite_extract( - result_type_id, - id, - id_extended, - &[vec_size as u32 - 1], - )); - id - } - Iq::NumSamples => { - let id = self.gen_id(); - block.body.push(Instruction::image_query( - spirv::Op::ImageQuerySamples, - result_type_id, - id, - image_id, - )); - id - } - } - } - crate::Expression::Relational { fun, argument } => { - use crate::RelationalFunction as Rf; - let arg_id = self.cached(argument); - let op = match fun { - Rf::All => spirv::Op::All, - Rf::Any => spirv::Op::Any, - Rf::IsNan => spirv::Op::IsNan, - Rf::IsInf => spirv::Op::IsInf, - //TODO: these require Kernel capability - Rf::IsFinite | Rf::IsNormal => { - return Err(Error::FeatureNotImplemented("is finite/normal")) - } - }; - let id = self.gen_id(); - block - .body - .push(Instruction::relational(op, result_type_id, id, arg_id)); - id - } - crate::Expression::ArrayLength(expr) => self.write_runtime_array_length(expr, block)?, - }; - - self.writer.cached[expr_handle] = id; - Ok(()) - } - - /// Build an `OpAccessChain` instruction for a left-hand-side expression. - /// - /// Emit any needed bounds-checking expressions to `block`. - /// - /// On success, the return value is an [`ExpressionPointer`] value; see the - /// documentation for that type. - fn write_expression_pointer( - &mut self, - mut expr_handle: Handle, - block: &mut Block, - ) -> Result { - let result_lookup_ty = match self.fun_info[expr_handle].ty { - TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), - TypeResolution::Value(ref inner) => { - LookupType::Local(self.writer.physical_layout.make_local(inner).unwrap()) - } - }; - let result_type_id = self.get_type_id(result_lookup_ty)?; - - // The id of the boolean `and` of all dynamic bounds checks up to this point. If - // `None`, then we haven't done any dynamic bounds checks yet. - // - // When we have a chain of bounds checks, we combine them with `OpLogicalAnd`, not - // a short-circuit branch. This means we might do comparisons we don't need to, - // but we expect these checks to almost always succeed, and keeping branches to a - // minimum is essential. - let mut accumulated_checks = None; - - self.temp_list.clear(); - let root_id = loop { - expr_handle = match self.ir_function.expressions[expr_handle] { - crate::Expression::Access { base, index } => { - let index_id = match self.write_bounds_check(base, index, block)? { - BoundsCheckResult::KnownInBounds(known_index) => { - // Even if the index is known, `OpAccessIndex` - // requires expression operands, not literals. - let scalar = crate::ScalarValue::Uint(known_index as u64); - self.writer.get_constant_scalar(scalar, 4)? - } - BoundsCheckResult::Computed(computed_index_id) => computed_index_id, - BoundsCheckResult::Conditional(comparison_id) => { - match accumulated_checks { - Some(prior_checks) => { - let combined = self.gen_id(); - block.body.push(Instruction::binary( - spirv::Op::LogicalAnd, - self.writer.get_bool_type_id()?, - combined, - prior_checks, - comparison_id, - )); - accumulated_checks = Some(combined); - } - None => { - // Start a fresh chain of checks. - accumulated_checks = Some(comparison_id); - } - } - - // Either way, the index to use is unchanged. - self.cached(index) - } - }; - self.temp_list.push(index_id); - - base - } - crate::Expression::AccessIndex { base, index } => { - let const_id = self.get_index_constant(index)?; - self.temp_list.push(const_id); - base - } - crate::Expression::GlobalVariable(handle) => { - let gv = &self.writer.global_variables[handle.index()]; - break gv.id; - } - crate::Expression::LocalVariable(variable) => { - let local_var = &self.function.variables[&variable]; - break local_var.id; - } - crate::Expression::FunctionArgument(index) => { - let id = self.function.parameters[index as usize].result_id.unwrap(); - break id; - } - ref other => unimplemented!("Unexpected pointer expression {:?}", other), - } - }; - - let pointer = if self.temp_list.is_empty() { - ExpressionPointer::Ready { - pointer_id: root_id, - } - } else { - self.temp_list.reverse(); - let pointer_id = self.gen_id(); - let access = - Instruction::access_chain(result_type_id, pointer_id, root_id, &self.temp_list); - - // If we generated some bounds checks, we need to leave it to our - // caller to generate the branch, the access, the load or store, and - // the zero value (for loads). Otherwise, we can emit the access - // ourselves, and just hand them the id of the pointer. - match accumulated_checks { - Some(condition) => ExpressionPointer::Conditional { condition, access }, - None => { - block.body.push(access); - ExpressionPointer::Ready { pointer_id } - } - } - }; - - Ok(pointer) - } - - fn get_expression_global(&self, expr_handle: Handle) -> Word { - match self.ir_function.expressions[expr_handle] { - crate::Expression::GlobalVariable(handle) => { - let id = self.writer.global_variables[handle.index()].handle_id; - if id == 0 { - unreachable!("Global variable {:?} doesn't have a handle ID", handle); - } - id - } - ref other => unreachable!("Unexpected global expression {:?}", other), - } - } - - //TODO: put most of these into a `BlockContext` structure! - fn write_block( - &mut self, - label_id: Word, - statements: &[crate::Statement], - exit_id: Option, - loop_context: LoopContext, - ) -> Result<(), Error> { - let mut block = Block::new(label_id); - - for statement in statements { - match *statement { - crate::Statement::Emit(ref range) => { - for handle in range.clone() { - self.cache_expression_value(handle, &mut block)?; - } - } - crate::Statement::Block(ref block_statements) => { - let scope_id = self.gen_id(); - self.function.consume(block, Instruction::branch(scope_id)); - - let merge_id = self.gen_id(); - self.write_block(scope_id, block_statements, Some(merge_id), loop_context)?; - - block = Block::new(merge_id); - } - crate::Statement::If { - condition, - ref accept, - ref reject, - } => { - let condition_id = self.cached(condition); - - let merge_id = self.gen_id(); - block.body.push(Instruction::selection_merge( - merge_id, - spirv::SelectionControl::NONE, - )); - - let accept_id = if accept.is_empty() { - None - } else { - Some(self.gen_id()) - }; - let reject_id = if reject.is_empty() { - None - } else { - Some(self.gen_id()) - }; - - self.function.consume( - block, - Instruction::branch_conditional( - condition_id, - accept_id.unwrap_or(merge_id), - reject_id.unwrap_or(merge_id), - ), - ); - - if let Some(block_id) = accept_id { - self.write_block(block_id, accept, Some(merge_id), loop_context)?; - } - if let Some(block_id) = reject_id { - self.write_block(block_id, reject, Some(merge_id), loop_context)?; - } - - block = Block::new(merge_id); - } - crate::Statement::Switch { - selector, - ref cases, - ref default, - } => { - let selector_id = self.cached(selector); - - let merge_id = self.gen_id(); - block.body.push(Instruction::selection_merge( - merge_id, - spirv::SelectionControl::NONE, - )); - - let default_id = self.gen_id(); - let raw_cases = cases - .iter() - .map(|c| super::instructions::Case { - value: c.value as Word, - label_id: self.gen_id(), - }) - .collect::>(); - - self.function.consume( - block, - Instruction::switch(selector_id, default_id, &raw_cases), - ); - - for (i, (case, raw_case)) in cases.iter().zip(raw_cases.iter()).enumerate() { - let case_finish_id = if case.fall_through { - match raw_cases.get(i + 1) { - Some(rc) => rc.label_id, - None => default_id, - } - } else { - merge_id - }; - self.write_block( - raw_case.label_id, - &case.body, - Some(case_finish_id), - LoopContext::default(), - )?; - } - - self.write_block(default_id, default, Some(merge_id), LoopContext::default())?; - - block = Block::new(merge_id); - } - crate::Statement::Loop { - ref body, - ref continuing, - } => { - let preamble_id = self.gen_id(); - self.function - .consume(block, Instruction::branch(preamble_id)); - - let merge_id = self.gen_id(); - let body_id = self.gen_id(); - let continuing_id = self.gen_id(); - - // SPIR-V requires the continuing to the `OpLoopMerge`, - // so we have to start a new block with it. - block = Block::new(preamble_id); - block.body.push(Instruction::loop_merge( - merge_id, - continuing_id, - spirv::SelectionControl::NONE, - )); - self.function.consume(block, Instruction::branch(body_id)); - - self.write_block( - body_id, - body, - Some(continuing_id), - LoopContext { - continuing_id: Some(continuing_id), - break_id: Some(merge_id), - }, - )?; - - self.write_block( - continuing_id, - continuing, - Some(preamble_id), - LoopContext { - continuing_id: None, - break_id: Some(merge_id), - }, - )?; - - block = Block::new(merge_id); - } - crate::Statement::Break => { - self.function - .consume(block, Instruction::branch(loop_context.break_id.unwrap())); - return Ok(()); - } - crate::Statement::Continue => { - self.function.consume( - block, - Instruction::branch(loop_context.continuing_id.unwrap()), - ); - return Ok(()); - } - crate::Statement::Return { value: Some(value) } => { - let value_id = self.cached(value); - let instruction = match self.function.entry_point_context { - // If this is an entry point, and we need to return anything, - // let's instead store the output variables and return `void`. - Some(ref context) => { - self.writer.write_entry_point_return( - value_id, - self.ir_function.result.as_ref().unwrap(), - &context.results, - &mut block.body, - )?; - Instruction::return_void() - } - None => Instruction::return_value(value_id), - }; - self.function.consume(block, instruction); - return Ok(()); - } - crate::Statement::Return { value: None } => { - self.function.consume(block, Instruction::return_void()); - return Ok(()); - } - crate::Statement::Kill => { - self.function.consume(block, Instruction::kill()); - return Ok(()); - } - crate::Statement::Barrier(flags) => { - let memory_scope = if flags.contains(crate::Barrier::STORAGE) { - spirv::Scope::Device - } else { - spirv::Scope::Workgroup - }; - let mut semantics = spirv::MemorySemantics::ACQUIRE_RELEASE; - semantics.set( - spirv::MemorySemantics::UNIFORM_MEMORY, - flags.contains(crate::Barrier::STORAGE), - ); - semantics.set( - spirv::MemorySemantics::WORKGROUP_MEMORY, - flags.contains(crate::Barrier::WORK_GROUP), - ); - let exec_scope_id = self.get_index_constant(spirv::Scope::Workgroup as u32)?; - let mem_scope_id = self.get_index_constant(memory_scope as u32)?; - let semantics_id = self.get_index_constant(semantics.bits())?; - block.body.push(Instruction::control_barrier( - exec_scope_id, - mem_scope_id, - semantics_id, - )); - } - crate::Statement::Store { pointer, value } => { - let value_id = self.cached(value); - match self.write_expression_pointer(pointer, &mut block)? { - ExpressionPointer::Ready { pointer_id } => { - block - .body - .push(Instruction::store(pointer_id, value_id, None)); - } - ExpressionPointer::Conditional { condition, access } => { - let merge_block = self.gen_id(); - let in_bounds_block = self.gen_id(); - - // Emit the conditional branch. - block.body.push(Instruction::selection_merge( - merge_block, - spirv::SelectionControl::NONE, - )); - self.function.consume( - std::mem::replace(&mut block, Block::new(in_bounds_block)), - Instruction::branch_conditional( - condition, - in_bounds_block, - merge_block, - ), - ); - - // The in-bounds path. Perform the access and the store. - let pointer_id = access.result_id.unwrap(); - block.body.push(access); - block - .body - .push(Instruction::store(pointer_id, value_id, None)); - - // Finish the in-bounds block and start the merge block. This - // is the block we'll leave current on return. - self.function.consume( - std::mem::replace(&mut block, Block::new(merge_block)), - Instruction::branch(merge_block), - ); - } - }; - } - crate::Statement::ImageStore { - image, - coordinate, - array_index, - value, - } => { - let image_id = self.get_expression_global(image); - let coordinate_id = - self.write_texture_coordinates(coordinate, array_index, &mut block)?; - let value_id = self.cached(value); - - block - .body - .push(Instruction::image_write(image_id, coordinate_id, value_id)); - } - crate::Statement::Call { - function: local_function, - ref arguments, - result, - } => { - let id = self.gen_id(); - self.temp_list.clear(); - for &argument in arguments { - self.temp_list.push(self.cached(argument)); - } - - let type_id = match result { - Some(expr) => { - self.writer.cached[expr] = id; - self.writer.lookup_function_call.insert(expr, id); - let ty_handle = self.ir_module.functions[local_function] - .result - .as_ref() - .unwrap() - .ty; - self.get_type_id(LookupType::Handle(ty_handle))? - } - None => self.writer.void_type, - }; - - block.body.push(Instruction::function_call( - type_id, - id, - self.writer.lookup_function[&local_function], - &self.temp_list, - )); - } - } - } - - let termination = match exit_id { - Some(id) => Instruction::branch(id), - // This can happen if the last branch had all the paths - // leading out of the graph (i.e. returning). - // Or it may be the end of the self.function. - None => match self.ir_function.result { - Some(ref result) if self.function.entry_point_context.is_none() => { - let type_id = self.get_type_id(LookupType::Handle(result.ty))?; - let null_id = self.writer.write_constant_null(type_id); - Instruction::return_value(null_id) - } - _ => Instruction::return_void(), - }, - }; - - self.function.consume(block, termination); - Ok(()) - } -} - #[test] fn test_write_physical_layout() { let mut writer = Writer::new(&Options::default()).unwrap(); From e32f10f940e4f257591eb40430ba8a206696f393 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 30 Jun 2021 20:48:57 -0700 Subject: [PATCH 1060/2212] [spv-out] recyclable: Remove capacity reduction code. --- src/back/spv/recyclable.rs | 34 ++-------------------------------- 1 file changed, 2 insertions(+), 32 deletions(-) diff --git a/src/back/spv/recyclable.rs b/src/back/spv/recyclable.rs index 54ac91215..c1b7fdcc6 100644 --- a/src/back/spv/recyclable.rs +++ b/src/back/spv/recyclable.rs @@ -29,46 +29,16 @@ pub trait Recyclable { // Stock values for various collections. -/// Maximum extra capacity that a recycled vector is allowed to have. If the -/// actual capacity is larger, we re-allocate the vector storage with lower -/// capacity. -const MAX_EXTRA_CAPACITY_PERCENT: usize = 200; - -/// Minimum extra capacity to keep when re-allocating the vector storage. -const MIN_EXTRA_CAPACITY_PERCENT: usize = 20; - -/// Minimum sensible length to consider for re-allocation. -const MIN_LENGTH: usize = 16; - impl Recyclable for Vec { fn recycle(mut self) -> Self { - let extra_capacity = (self.capacity() - self.len()) * 100 / self.len().max(MIN_LENGTH); - - if extra_capacity > MAX_EXTRA_CAPACITY_PERCENT { - //TODO: use `shrink_to` when it's stable - self = Vec::with_capacity(self.len() + self.len() * MIN_EXTRA_CAPACITY_PERCENT / 100); - } else { - self.clear(); - } - + self.clear(); self } } impl Recyclable for std::collections::HashMap { fn recycle(mut self) -> Self { - let extra_capacity = (self.capacity() - self.len()) * 100 / self.len().max(MIN_LENGTH); - - if extra_capacity > MAX_EXTRA_CAPACITY_PERCENT { - //TODO: use `shrink_to` when it's stable - self = Self::with_capacity_and_hasher( - self.len() + self.len() * MIN_EXTRA_CAPACITY_PERCENT / 100, - self.hasher().clone(), - ); - } else { - self.clear(); - } - + self.clear(); self } } From f98b4e2f48f6373cd05854a04e4de04f8928707c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 24 Jun 2021 22:00:52 +0100 Subject: [PATCH 1061/2212] [spv-in] Support texture/sampler function argument --- src/front/spv/function.rs | 9 ++- src/front/spv/image.rs | 81 +++++++++++++++--------- src/front/spv/mod.rs | 129 +++++++++++++++++++++++++++++++------- 3 files changed, 167 insertions(+), 52 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 7c0554654..f124bd1f7 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -1,6 +1,6 @@ use crate::arena::{Arena, Handle}; -use super::{flow::*, Error, Instruction, LookupExpression, LookupHelper as _}; +use super::{flow::*, Error, FunctionInfo, Instruction, LookupExpression, LookupHelper as _}; pub type BlockId = u32; @@ -135,6 +135,10 @@ impl> super::Parser { self.function_call_graph.add_node(fun_id); let mut flow_graph = FlowGraph::new(); + let mut function_info = FunctionInfo { + parameters_sampling: vec![None; fun.arguments.len()], + }; + // Scan the blocks and add them as nodes loop { let fun_inst = self.next_inst()?; @@ -153,6 +157,8 @@ impl> super::Parser { &mut module.constants, &module.types, &module.global_variables, + &fun.arguments, + &mut function_info, )?; flow_graph.add_node(node); @@ -187,6 +193,7 @@ impl> super::Parser { // done let fun_handle = module.functions.append(fun); self.lookup_function.insert(fun_id, fun_handle); + self.function_info.insert(fun_handle, function_info); if let Some(ep) = self.lookup_entry_point.remove(&fun_id) { // create a wrapping function let mut function = crate::Function { diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 1fa9e938f..75736771a 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -1,6 +1,9 @@ -use crate::arena::{Arena, Handle}; +use crate::{ + arena::{Arena, Handle}, + FunctionArgument, +}; -use super::{Error, LookupExpression, LookupHelper as _}; +use super::{Error, FunctionInfo, LookupExpression, LookupHelper as _}; #[derive(Clone, Debug)] pub(super) struct LookupSampledImage { @@ -19,12 +22,15 @@ bitflags::bitflags! { } impl Arena { - fn get_global_var( + fn get_image_expr_ty( &self, handle: Handle, - ) -> Result, Error> { + global_vars: &Arena, + arguments: &[FunctionArgument], + ) -> Result, Error> { match self[handle] { - crate::Expression::GlobalVariable(handle) => Ok(handle), + crate::Expression::GlobalVariable(handle) => Ok(global_vars[handle].ty), + crate::Expression::FunctionArgument(i) => Ok(arguments[i as usize].ty), ref other => Err(Error::InvalidGlobalVar(other.clone())), } } @@ -229,6 +235,7 @@ impl> super::Parser { words_left: u16, type_arena: &Arena, global_arena: &Arena, + arguments: &[FunctionArgument], expressions: &mut Arena, ) -> Result { let image_id = self.next()?; @@ -246,12 +253,11 @@ impl> super::Parser { } let image_lexp = self.lookup_expression.lookup(image_id)?; - let image_var_handle = expressions.get_global_var(image_lexp.handle)?; - let image_var = &global_arena[image_var_handle]; + let image_ty = expressions.get_image_expr_ty(image_lexp.handle, global_arena, arguments)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let (coordinate, array_index) = match type_arena[image_var.ty].inner { + let (coordinate, array_index) = match type_arena[image_ty].inner { crate::TypeInner::Image { dim, arrayed, @@ -268,7 +274,7 @@ impl> super::Parser { type_arena, expressions, ), - _ => return Err(Error::InvalidImage(image_var.ty)), + _ => return Err(Error::InvalidImage(image_ty)), }; let value_lexp = self.lookup_expression.lookup(value_id)?; @@ -286,6 +292,7 @@ impl> super::Parser { mut words_left: u16, type_arena: &Arena, global_arena: &Arena, + arguments: &[FunctionArgument], expressions: &mut Arena, ) -> Result<(), Error> { let result_type_id = self.next()?; @@ -328,12 +335,11 @@ impl> super::Parser { } let image_lexp = self.lookup_expression.lookup(image_id)?; - let image_var_handle = expressions.get_global_var(image_lexp.handle)?; - let image_var = &global_arena[image_var_handle]; + let image_ty = expressions.get_image_expr_ty(image_lexp.handle, global_arena, arguments)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let (coordinate, array_index) = match type_arena[image_var.ty].inner { + let (coordinate, array_index) = match type_arena[image_ty].inner { crate::TypeInner::Image { dim, arrayed, @@ -350,7 +356,7 @@ impl> super::Parser { type_arena, expressions, ), - _ => return Err(Error::InvalidImage(image_var.ty)), + _ => return Err(Error::InvalidImage(image_ty)), }; let expr = crate::Expression::ImageLoad { @@ -369,13 +375,16 @@ impl> super::Parser { Ok(()) } + #[allow(clippy::too_many_arguments)] pub(super) fn parse_image_sample( &mut self, mut words_left: u16, options: SamplingOptions, type_arena: &Arena, global_arena: &Arena, + arguments: &[FunctionArgument], expressions: &mut Arena, + function_info: &mut FunctionInfo, ) -> Result<(), Error> { let result_type_id = self.next()?; let result_id = self.next()?; @@ -432,26 +441,42 @@ impl> super::Parser { let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let image_var_handle = expressions.get_global_var(si_lexp.image)?; - let sampler_var_handle = expressions.get_global_var(si_lexp.sampler)?; - log::debug!( - "\t\t\tImage {:?} sampled with {:?} under {:?}", - image_var_handle, - sampler_var_handle, - options, - ); let sampling_bit = if options.compare { SamplingFlags::COMPARISON } else { SamplingFlags::REGULAR }; - if let Some(flags) = self.handle_sampling.get_mut(&image_var_handle) { - *flags |= sampling_bit; - } - *self.handle_sampling.get_mut(&sampler_var_handle).unwrap() |= sampling_bit; - let image_var = &global_arena[image_var_handle]; - let (coordinate, array_index) = match type_arena[image_var.ty].inner { + let image_ty = match expressions[si_lexp.image] { + crate::Expression::GlobalVariable(handle) => { + if let Some(flags) = self.handle_sampling.get_mut(&handle) { + *flags |= sampling_bit; + } + + global_arena[handle].ty + } + crate::Expression::FunctionArgument(i) => { + let flags = function_info.parameters_sampling[i as usize] + .get_or_insert(SamplingFlags::empty()); + *flags |= sampling_bit; + + arguments[i as usize].ty + } + ref other => return Err(Error::InvalidGlobalVar(other.clone())), + }; + match expressions[si_lexp.sampler] { + crate::Expression::GlobalVariable(handle) => { + *self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit + } + crate::Expression::FunctionArgument(i) => { + let flags = function_info.parameters_sampling[i as usize] + .get_or_insert(SamplingFlags::empty()); + *flags |= sampling_bit; + } + ref other => return Err(Error::InvalidGlobalVar(other.clone())), + } + + let (coordinate, array_index) = match type_arena[image_ty].inner { crate::TypeInner::Image { dim, arrayed, @@ -470,7 +495,7 @@ impl> super::Parser { type_arena, expressions, ), - _ => return Err(Error::InvalidImage(image_var.ty)), + _ => return Err(Error::InvalidImage(image_ty)), }; let expr = crate::Expression::ImageSample { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 0ad9a002e..361be0aa4 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -371,6 +371,10 @@ impl Default for Options { } } +struct FunctionInfo { + parameters_sampling: Vec>, +} + pub struct Parser { data: I, state: ModuleState, @@ -405,6 +409,7 @@ pub struct Parser { options: Options, index_constants: Vec>, index_constant_expressions: Vec>, + function_info: FastHashMap, FunctionInfo>, } impl> Parser { @@ -436,6 +441,7 @@ impl> Parser { options: options.clone(), index_constants: Vec::new(), index_constant_expressions: Vec::new(), + function_info: FastHashMap::default(), } } @@ -783,6 +789,8 @@ impl> Parser { const_arena: &mut Arena, type_arena: &Arena, global_arena: &Arena, + arguments: &[crate::FunctionArgument], + function_info: &mut FunctionInfo, ) -> Result { let mut block = Vec::new(); let mut phis = Vec::new(); @@ -1479,14 +1487,19 @@ impl> Parser { Op::ImageWrite => { let extra = inst.expect_at_least(4)?; block.extend(emitter.finish(expressions)); - let stmt = - self.parse_image_write(extra, type_arena, global_arena, expressions)?; + let stmt = self.parse_image_write( + extra, + type_arena, + global_arena, + arguments, + expressions, + )?; block.push(stmt); emitter.start(expressions); } Op::ImageFetch | Op::ImageRead => { let extra = inst.expect_at_least(5)?; - self.parse_image_load(extra, type_arena, global_arena, expressions)?; + self.parse_image_load(extra, type_arena, global_arena, arguments, expressions)?; } Op::ImageSampleImplicitLod | Op::ImageSampleExplicitLod => { let extra = inst.expect_at_least(5)?; @@ -1494,7 +1507,15 @@ impl> Parser { compare: false, project: false, }; - self.parse_image_sample(extra, options, type_arena, global_arena, expressions)?; + self.parse_image_sample( + extra, + options, + type_arena, + global_arena, + arguments, + expressions, + function_info, + )?; } Op::ImageSampleProjImplicitLod | Op::ImageSampleProjExplicitLod => { let extra = inst.expect_at_least(5)?; @@ -1502,7 +1523,15 @@ impl> Parser { compare: false, project: true, }; - self.parse_image_sample(extra, options, type_arena, global_arena, expressions)?; + self.parse_image_sample( + extra, + options, + type_arena, + global_arena, + arguments, + expressions, + function_info, + )?; } Op::ImageSampleDrefImplicitLod | Op::ImageSampleDrefExplicitLod => { let extra = inst.expect_at_least(6)?; @@ -1510,7 +1539,15 @@ impl> Parser { compare: true, project: false, }; - self.parse_image_sample(extra, options, type_arena, global_arena, expressions)?; + self.parse_image_sample( + extra, + options, + type_arena, + global_arena, + arguments, + expressions, + function_info, + )?; } Op::ImageSampleProjDrefImplicitLod | Op::ImageSampleProjDrefExplicitLod => { let extra = inst.expect_at_least(6)?; @@ -1518,7 +1555,15 @@ impl> Parser { compare: true, project: true, }; - self.parse_image_sample(extra, options, type_arena, global_arena, expressions)?; + self.parse_image_sample( + extra, + options, + type_arena, + global_arena, + arguments, + expressions, + function_info, + )?; } Op::ImageQuerySize => { inst.expect(4)?; @@ -2199,14 +2244,19 @@ impl> Parser { /// 1. Function call targets are replaced by `deferred_function_calls` map /// 2. Lift the contents of "If" that only breaks on rejection, onto the parent after it. /// 3. Lift the contents of "Switch" that only has a default, onto the parent after it. - fn patch_statements(&self, statements: &mut crate::Block) -> Result<(), Error> { + fn patch_statements( + &mut self, + statements: &mut crate::Block, + expressions: &mut Arena, + function: Option>, + ) -> Result<(), Error> { use crate::Statement as S; let mut i = 0usize; while i < statements.len() { match statements[i] { S::Emit(_) => {} S::Block(ref mut block) => { - self.patch_statements(block)?; + self.patch_statements(block, expressions, function)?; } S::If { condition: _, @@ -2218,8 +2268,8 @@ impl> Parser { let extracted = mem::take(accept); statements.splice(i + 1..i + 1, extracted.into_iter()); } else { - self.patch_statements(reject)?; - self.patch_statements(accept)?; + self.patch_statements(reject, expressions, function)?; + self.patch_statements(accept, expressions, function)?; } } S::Switch { @@ -2233,17 +2283,17 @@ impl> Parser { statements.splice(i + 1..i + 1, extracted.into_iter()); } else { for case in cases.iter_mut() { - self.patch_statements(&mut case.body)?; + self.patch_statements(&mut case.body, expressions, function)?; } - self.patch_statements(default)?; + self.patch_statements(default, expressions, function)?; } } S::Loop { ref mut body, ref mut continuing, } => { - self.patch_statements(body)?; - self.patch_statements(continuing)?; + self.patch_statements(body, expressions, function)?; + self.patch_statements(continuing, expressions, function)?; } S::Break | S::Continue @@ -2253,10 +2303,39 @@ impl> Parser { | S::Store { .. } | S::ImageStore { .. } => {} S::Call { - ref mut function, .. + function: ref mut callee, + ref arguments, + .. } => { - let fun_id = self.deferred_function_calls[function.index()]; - *function = *self.lookup_function.lookup(fun_id)?; + let fun_id = self.deferred_function_calls[callee.index()]; + let handle = *self.lookup_function.lookup(fun_id)?; + + // Patch sampling flags + for (i, arg) in arguments.iter().enumerate() { + let callee_info = &self.function_info[&handle]; + + if let Some(flags) = callee_info.parameters_sampling.get(i).and_then(|e| *e) + { + match expressions[*arg] { + crate::Expression::GlobalVariable(handle) => { + *self.handle_sampling.get_mut(&handle).unwrap() |= flags + } + crate::Expression::FunctionArgument(i) => { + if let Some(handle) = function { + let function_info = + self.function_info.get_mut(&handle).unwrap(); + let caller_flags = function_info.parameters_sampling + [i as usize] + .get_or_insert(image::SamplingFlags::empty()); + *caller_flags |= flags; + } + } + ref other => return Err(Error::InvalidGlobalVar(other.clone())), + } + } + } + + *callee = handle; } } i += 1; @@ -2264,14 +2343,18 @@ impl> Parser { Ok(()) } - fn patch_function(&self, fun: &mut crate::Function) -> Result<(), Error> { + fn patch_function( + &mut self, + handle: Option>, + fun: &mut crate::Function, + ) -> Result<(), Error> { for (_, expr) in fun.expressions.iter_mut() { if let crate::Expression::Call(ref mut function) = *expr { let fun_id = self.deferred_function_calls[function.index()]; *function = *self.lookup_function.lookup(fun_id)?; } } - self.patch_statements(&mut fun.body)?; + self.patch_statements(&mut fun.body, &mut fun.expressions, handle)?; Ok(()) } @@ -2380,11 +2463,11 @@ impl> Parser { } } // patch all the functions - for (_, fun) in module.functions.iter_mut() { - self.patch_function(fun)?; + for (handle, fun) in module.functions.iter_mut() { + self.patch_function(Some(handle), fun)?; } for ep in module.entry_points.iter_mut() { - self.patch_function(&mut ep.function)?; + self.patch_function(None, &mut ep.function)?; } // Check all the images and samplers to have consistent comparison property. From 7df4a52af9f57886ed6540f3ad3d7bd44083f4ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 24 Jun 2021 22:01:40 +0100 Subject: [PATCH 1062/2212] [valid] Handle texture/sampler function argument --- src/valid/analyzer.rs | 226 ++++++++++++++++++++++++---- src/valid/expression.rs | 36 +++-- src/valid/function.rs | 2 +- src/valid/type.rs | 23 ++- tests/out/analysis/collatz.info.ron | 6 + tests/out/analysis/shadow.info.ron | 9 ++ 6 files changed, 244 insertions(+), 58 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index aae5dcdde..032c4f37f 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -159,6 +159,24 @@ impl ExpressionInfo { } } +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +enum GlobalOrArgument { + Global(Handle), + Argument(u32), +} + +#[derive(Debug, Clone)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +struct ArgumentSampling { + /// Whether this argument is used as an image or a sampler + image: bool, + /// The other global or argument used in the sampling + uses: Vec, +} + #[derive(Debug)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] @@ -181,6 +199,10 @@ pub struct FunctionInfo { /// /// Each item corresponds to an expression in the function. expressions: Box<[ExpressionInfo]>, + /// Vector with information of wether or not a functin argument is used for sampling + /// + /// Each item corresponds to a function argument + argument_sampling: Box<[Option]>, } impl FunctionInfo { @@ -273,21 +295,101 @@ impl FunctionInfo { } /// Inherit information from a called function. - fn process_call(&mut self, info: &Self) -> FunctionUniformity { + fn process_call( + &mut self, + info: &Self, + arguments: &[Handle], + expression_arena: &Arena, + ) -> Result { for key in info.sampling_set.iter() { self.sampling_set.insert(key.clone()); } + for (i, arg_sampling) in info + .argument_sampling + .iter() + .enumerate() + .filter_map(|(i, s)| Some((i, s.as_ref()?))) + { + let handle = arguments[i]; + let arg_storage = match expression_arena[handle] { + crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), + crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), + _ => { + return Err(FunctionError::Expression { + handle, + error: ExpressionError::ExpectedGlobalVariable, + }) + } + }; + + for other in arg_sampling.uses.iter() { + let other_storage = match *other { + GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var), + GlobalOrArgument::Argument(i) => { + let other_handle = arguments[i as usize]; + match expression_arena[other_handle] { + crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), + crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), + _ => { + return Err(FunctionError::Expression { + handle, + error: ExpressionError::ExpectedGlobalVariable, + }) + } + } + } + }; + + match (arg_storage, other_storage) { + (GlobalOrArgument::Global(arg), GlobalOrArgument::Global(other)) => { + if arg_sampling.image { + self.sampling_set.insert(SamplingKey { + image: arg, + sampler: other, + }); + } else { + self.sampling_set.insert(SamplingKey { + image: other, + sampler: arg, + }); + } + } + (GlobalOrArgument::Argument(i), _) => { + let sampling = + self.argument_sampling[i as usize].get_or_insert_with(|| { + ArgumentSampling { + image: arg_sampling.image, + uses: Vec::with_capacity(1), + } + }); + + sampling.uses.push(other_storage) + } + (_, GlobalOrArgument::Argument(i)) => { + let sampling = + self.argument_sampling[i as usize].get_or_insert_with(|| { + ArgumentSampling { + image: !arg_sampling.image, + uses: Vec::with_capacity(1), + } + }); + + sampling.uses.push(arg_storage) + } + } + } + } for (mine, other) in self.global_uses.iter_mut().zip(info.global_uses.iter()) { *mine |= *other; } - FunctionUniformity { + Ok(FunctionUniformity { result: info.uniformity.clone(), exit: if info.may_kill { ExitFlags::MAY_KILL } else { ExitFlags::empty() }, - } + }) } /// Computes the expression info and stores it in `self.expressions`. @@ -397,16 +499,45 @@ impl FunctionInfo { level, depth_ref, } => { - self.sampling_set.insert(SamplingKey { - image: match expression_arena[image] { - crate::Expression::GlobalVariable(var) => var, - _ => return Err(ExpressionError::ExpectedGlobalVariable), - }, - sampler: match expression_arena[sampler] { - crate::Expression::GlobalVariable(var) => var, - _ => return Err(ExpressionError::ExpectedGlobalVariable), - }, - }); + let image_storage = match expression_arena[image] { + crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), + crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), + _ => return Err(ExpressionError::ExpectedGlobalVariable), + }; + let sampler_storage = match expression_arena[sampler] { + crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), + crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), + _ => return Err(ExpressionError::ExpectedGlobalVariable), + }; + + match (image_storage, sampler_storage) { + (GlobalOrArgument::Global(image), GlobalOrArgument::Global(sampler)) => { + self.sampling_set.insert(SamplingKey { image, sampler }); + } + (GlobalOrArgument::Argument(i), _) => { + let sampling = + self.argument_sampling[i as usize].get_or_insert_with(|| { + ArgumentSampling { + image: true, + uses: Vec::with_capacity(1), + } + }); + + sampling.uses.push(sampler_storage) + } + (_, GlobalOrArgument::Argument(i)) => { + let sampling = + self.argument_sampling[i as usize].get_or_insert_with(|| { + ArgumentSampling { + image: false, + uses: Vec::with_capacity(1), + } + }); + + sampling.uses.push(image_storage) + } + } + // "nur" == "Non-Uniform Result" let array_nur = array_index.and_then(|h| self.add_ref(h)); let level_nur = match level { @@ -501,10 +632,11 @@ impl FunctionInfo { requirements: UniformityRequirements::empty(), }, E::Call(function) => { - let fun = other_functions + let info = other_functions .get(function.index()) .ok_or(ExpressionError::CallToUndeclaredFunction(function))?; - self.process_call(fun).result + + info.uniformity.clone() } E::ArrayLength(expr) => Uniformity { non_uniform_result: self.add_ref_impl(expr, GlobalUse::QUERY), @@ -537,6 +669,7 @@ impl FunctionInfo { statements: &[crate::Statement], other_functions: &[FunctionInfo], mut disruptor: Option, + expression_arena: &Arena, ) -> Result { use crate::Statement as S; @@ -582,7 +715,9 @@ impl FunctionInfo { }, exit: ExitFlags::empty(), }, - S::Block(ref b) => self.process_block(b, other_functions, disruptor)?, + S::Block(ref b) => { + self.process_block(b, other_functions, disruptor, expression_arena)? + } S::If { condition, ref accept, @@ -591,10 +726,18 @@ impl FunctionInfo { let condition_nur = self.add_ref(condition); let branch_disruptor = disruptor.or(condition_nur.map(UniformityDisruptor::Expression)); - let accept_uniformity = - self.process_block(accept, other_functions, branch_disruptor)?; - let reject_uniformity = - self.process_block(reject, other_functions, branch_disruptor)?; + let accept_uniformity = self.process_block( + accept, + other_functions, + branch_disruptor, + expression_arena, + )?; + let reject_uniformity = self.process_block( + reject, + other_functions, + branch_disruptor, + expression_arena, + )?; accept_uniformity | reject_uniformity } S::Switch { @@ -608,8 +751,12 @@ impl FunctionInfo { let mut uniformity = FunctionUniformity::new(); let mut case_disruptor = branch_disruptor; for case in cases.iter() { - let case_uniformity = - self.process_block(&case.body, other_functions, case_disruptor)?; + let case_uniformity = self.process_block( + &case.body, + other_functions, + case_disruptor, + expression_arena, + )?; case_disruptor = if case.fall_through { case_disruptor.or(case_uniformity.exit_disruptor()) } else { @@ -618,18 +765,27 @@ impl FunctionInfo { uniformity = uniformity | case_uniformity; } // using the disruptor inherited from the last fall-through chain - let default_exit = - self.process_block(default, other_functions, case_disruptor)?; + let default_exit = self.process_block( + default, + other_functions, + case_disruptor, + expression_arena, + )?; uniformity | default_exit } S::Loop { ref body, ref continuing, } => { - let body_uniformity = self.process_block(body, other_functions, disruptor)?; + let body_uniformity = + self.process_block(body, other_functions, disruptor, expression_arena)?; let continuing_disruptor = disruptor.or(body_uniformity.exit_disruptor()); - let continuing_uniformity = - self.process_block(continuing, other_functions, continuing_disruptor)?; + let continuing_uniformity = self.process_block( + continuing, + other_functions, + continuing_disruptor, + expression_arena, + )?; body_uniformity | continuing_uniformity } S::Return { value } => FunctionUniformity { @@ -680,7 +836,7 @@ impl FunctionInfo { }, )?; //Note: the result is validated by the Validator, not here - self.process_call(info) + self.process_call(info, arguments, expression_arena)? } }; @@ -708,6 +864,7 @@ impl ModuleInfo { sampling_set: crate::FastHashSet::default(), global_uses: vec![GlobalUse::empty(); module.global_variables.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::new(); fun.expressions.len()].into_boxed_slice(), + argument_sampling: vec![None; fun.arguments.len()].into_boxed_slice(), }; let resolve_context = ResolveContext { constants: &module.constants, @@ -730,7 +887,7 @@ impl ModuleInfo { } } - let uniformity = info.process_block(&fun.body, &self.functions, None)?; + let uniformity = info.process_block(&fun.body, &self.functions, None, &fun.expressions)?; info.uniformity = uniformity.result; info.may_kill = uniformity.exit.contains(ExitFlags::MAY_KILL); @@ -812,6 +969,7 @@ fn uniform_control_flow() { sampling_set: crate::FastHashSet::default(), global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::new(); expressions.len()].into_boxed_slice(), + argument_sampling: vec![None; 0].into_boxed_slice(), }; let resolve_context = ResolveContext { constants: &constant_arena, @@ -845,7 +1003,7 @@ fn uniform_control_flow() { ], }; assert_eq!( - info.process_block(&[stmt_emit1, stmt_if_uniform], &[], None), + info.process_block(&[stmt_emit1, stmt_if_uniform], &[], None, &expressions), Ok(FunctionUniformity { result: Uniformity { non_uniform_result: None, @@ -870,7 +1028,7 @@ fn uniform_control_flow() { reject: Vec::new(), }; assert_eq!( - info.process_block(&[stmt_emit2, stmt_if_non_uniform], &[], None), + info.process_block(&[stmt_emit2, stmt_if_non_uniform], &[], None, &expressions), Err(FunctionError::NonUniformControlFlow( UniformityRequirements::DERIVATIVE, derivative_expr, @@ -888,7 +1046,8 @@ fn uniform_control_flow() { info.process_block( &[stmt_emit3, stmt_return_non_uniform], &[], - Some(UniformityDisruptor::Return) + Some(UniformityDisruptor::Return), + &expressions ), Ok(FunctionUniformity { result: Uniformity { @@ -914,7 +1073,8 @@ fn uniform_control_flow() { info.process_block( &[stmt_emit4, stmt_assign, stmt_kill, stmt_return_pointer], &[], - Some(UniformityDisruptor::Discard) + Some(UniformityDisruptor::Discard), + &expressions ), Ok(FunctionUniformity { result: Uniformity { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index a4035fede..409ca82eb 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -339,24 +339,26 @@ impl super::Validator { depth_ref, } => { // check the validity of expressions - let image_var = match function.expressions[image] { + let image_ty = match function.expressions[image] { crate::Expression::GlobalVariable(var_handle) => { - &module.global_variables[var_handle] + module.global_variables[var_handle].ty } + crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, _ => return Err(ExpressionError::ExpectedGlobalVariable), }; - let sampler_var = match function.expressions[sampler] { + let sampler_ty = match function.expressions[sampler] { crate::Expression::GlobalVariable(var_handle) => { - &module.global_variables[var_handle] + module.global_variables[var_handle].ty } + crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, _ => return Err(ExpressionError::ExpectedGlobalVariable), }; - let comparison = match module.types[sampler_var.ty].inner { + let comparison = match module.types[sampler_ty].inner { Ti::Sampler { comparison } => comparison, - _ => return Err(ExpressionError::ExpectedSamplerType(sampler_var.ty)), + _ => return Err(ExpressionError::ExpectedSamplerType(sampler_ty)), }; - let (class, dim) = match module.types[image_var.ty].inner { + let (class, dim) = match module.types[image_ty].inner { Ti::Image { class, arrayed, @@ -377,7 +379,7 @@ impl super::Validator { } (class, dim) } - _ => return Err(ExpressionError::ExpectedImageType(image_var.ty)), + _ => return Err(ExpressionError::ExpectedImageType(image_ty)), }; // check sampling and comparison properties @@ -515,13 +517,14 @@ impl super::Validator { array_index, index, } => { - let var = match function.expressions[image] { + let ty = match function.expressions[image] { crate::Expression::GlobalVariable(var_handle) => { - &module.global_variables[var_handle] + module.global_variables[var_handle].ty } + crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, _ => return Err(ExpressionError::ExpectedGlobalVariable), }; - match module.types[var.ty].inner { + match module.types[ty].inner { Ti::Image { class, arrayed, @@ -564,18 +567,19 @@ impl super::Validator { } } } - _ => return Err(ExpressionError::ExpectedImageType(var.ty)), + _ => return Err(ExpressionError::ExpectedImageType(ty)), } ShaderStages::all() } E::ImageQuery { image, query } => { - let var = match function.expressions[image] { + let ty = match function.expressions[image] { crate::Expression::GlobalVariable(var_handle) => { - &module.global_variables[var_handle] + module.global_variables[var_handle].ty } + crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, _ => return Err(ExpressionError::ExpectedGlobalVariable), }; - match module.types[var.ty].inner { + match module.types[ty].inner { Ti::Image { class, arrayed, .. } => { let can_level = match class { crate::ImageClass::Sampled { multi, .. } => !multi, @@ -593,7 +597,7 @@ impl super::Validator { return Err(ExpressionError::InvalidImageClass(class)); } } - _ => return Err(ExpressionError::ExpectedImageType(var.ty)), + _ => return Err(ExpressionError::ExpectedImageType(ty)), } ShaderStages::all() } diff --git a/src/valid/function.rs b/src/valid/function.rs index bb5d49c97..b05c0e391 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -578,7 +578,7 @@ impl super::Validator { for (index, argument) in fun.arguments.iter().enumerate() { if !self.types[argument.ty.index()] .flags - .contains(TypeFlags::DATA | TypeFlags::SIZED) + .contains(TypeFlags::ARGUMENT) { return Err(FunctionError::InvalidArgumentType { index, diff --git a/src/valid/type.rs b/src/valid/type.rs index 474c5dc0a..e1f25af7b 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -46,6 +46,9 @@ bitflags::bitflags! { /// This is a top-level host-shareable type. const TOP_LEVEL = 0x10; + + /// This type can be passed as a function argument. + const ARGUMENT = 0x20; } } @@ -192,7 +195,8 @@ impl super::Validator { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE - | TypeFlags::HOST_SHARED, + | TypeFlags::HOST_SHARED + | TypeFlags::ARGUMENT, width as u32, ) } @@ -205,7 +209,8 @@ impl super::Validator { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE - | TypeFlags::HOST_SHARED, + | TypeFlags::HOST_SHARED + | TypeFlags::ARGUMENT, count * (width as u32), ) } @@ -222,7 +227,8 @@ impl super::Validator { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::INTERFACE - | TypeFlags::HOST_SHARED, + | TypeFlags::HOST_SHARED + | TypeFlags::ARGUMENT, count * (width as u32), ) } @@ -239,9 +245,9 @@ impl super::Validator { // `DATA`. let base_info = &self.types[base.index()]; let data_flag = if base_info.flags.contains(TypeFlags::SIZED) { - TypeFlags::DATA + TypeFlags::DATA | TypeFlags::ARGUMENT } else if let crate::TypeInner::Struct { .. } = types[base].inner { - TypeFlags::DATA + TypeFlags::DATA | TypeFlags::ARGUMENT } else { TypeFlags::empty() }; @@ -350,7 +356,7 @@ impl super::Validator { return Err(TypeError::NonPositiveArrayLength(const_handle)); } - TypeFlags::SIZED + TypeFlags::SIZED | TypeFlags::ARGUMENT } crate::ArraySize::Dynamic => { // Non-SIZED types may only appear as the last element of a structure. @@ -376,7 +382,8 @@ impl super::Validator { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED - | TypeFlags::INTERFACE, + | TypeFlags::INTERFACE + | TypeFlags::ARGUMENT, 1, ); let mut min_offset = 0; @@ -460,7 +467,7 @@ impl super::Validator { ti } - Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::new(TypeFlags::empty(), 0), + Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::new(TypeFlags::ARGUMENT, 0), }) } } diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index edf6a5a5a..e46776e9d 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -336,6 +336,9 @@ ty: Handle(1), ), ], + argument_sampling: [ + None, + ], ), ], entry_points: [ @@ -492,6 +495,9 @@ ty: Handle(1), ), ], + argument_sampling: [ + None, + ], ), ], ) \ No newline at end of file diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 6d59c22e6..abaef4336 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -1060,6 +1060,10 @@ )), ), ], + argument_sampling: [ + None, + None, + ], ), ( flags: ( @@ -2748,6 +2752,7 @@ ty: Handle(4), ), ], + argument_sampling: [], ), ], entry_points: [ @@ -2871,6 +2876,10 @@ ty: Handle(4), ), ], + argument_sampling: [ + None, + None, + ], ), ], ) \ No newline at end of file From d0fd0650968a3a35dcc1084cbaadc5fd4c9b0299 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 25 Jun 2021 16:53:59 +0100 Subject: [PATCH 1063/2212] [glsl-out]Handle texture/sampler function argument --- src/back/glsl/mod.rs | 64 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 54 insertions(+), 10 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ef1a71cbc..4a68df9b0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -247,7 +247,7 @@ impl fmt::Display for VaryingName<'_> { } /// Shorthand result used internally by the backend -type BackendResult = Result<(), Error>; +type BackendResult = Result; /// A glsl compilation error. #[derive(Debug, Error)] @@ -966,14 +966,42 @@ impl<'a, W: Write> Writer<'a, W> { }; self.write_slice(arguments, |this, i, arg| { // Write the argument type - // `write_type` adds no trailing spaces - this.write_type(arg.ty)?; + match this.module.types[arg.ty].inner { + // We treat images separately because they might require + // writing the storage format + TypeInner::Image { + dim, + arrayed, + class, + } => { + // Write the storage format if needed + if let TypeInner::Image { + class: crate::ImageClass::Storage(format), + .. + } = this.module.types[arg.ty].inner + { + write!(this.out, "layout({}) ", glsl_storage_format(format))?; + } + + // write the type + // + // This is way we need the leading space because `write_image_type` doesn't add + // any spaces at the beginning or end + this.write_image_type(dim, arrayed, class)?; + } + // glsl has no concept of samplers so we just ignore it + TypeInner::Sampler { .. } => return Ok(false), + // All other types are written by `write_type` + _ => { + this.write_type(arg.ty)?; + } + } // Write the argument name // The leading space is important write!(this.out, " {}", &this.names[&ctx.argument_key(i)])?; - Ok(()) + Ok(true) })?; // Close the parentheses and open braces to start the function body @@ -1069,14 +1097,16 @@ impl<'a, W: Write> Writer<'a, W> { /// # Notes /// - Adds no newlines or leading/trailing whitespace /// - The last element won't have a trailing `,` - fn write_slice BackendResult>( + fn write_slice BackendResult>( &mut self, data: &[T], mut f: F, ) -> BackendResult { // Loop trough `data` invoking `f` for each element for (i, item) in data.iter().enumerate() { - f(self, i as u32, item)?; + if !f(self, i as u32, item)? { + continue; + } // Only write a comma if isn't the last element if i != data.len().saturating_sub(1) { @@ -1121,7 +1151,8 @@ impl<'a, W: Write> Writer<'a, W> { // Write the comma separated constants self.write_slice(components, |this, _, arg| { - this.write_constant(&this.module.constants[*arg]) + this.write_constant(&this.module.constants[*arg])?; + Ok(true) })?; write!(self.out, ")")? @@ -1586,7 +1617,16 @@ impl<'a, W: Write> Writer<'a, W> { self.named_expressions.insert(expr, name); } write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; - self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?; + self.write_slice(arguments, |this, i, arg| { + let arg_ty = this.module.functions[function].arguments[i as usize].ty; + if let TypeInner::Sampler { .. } = this.module.types[arg_ty].inner { + return Ok(false); + } + + this.write_expr(*arg, ctx)?; + + Ok(true) + })?; writeln!(self.out, ");")? } } @@ -1686,7 +1726,10 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(ty)?; write!(self.out, "(")?; - self.write_slice(components, |this, _, arg| this.write_expr(*arg, ctx))?; + self.write_slice(components, |this, _, arg| { + this.write_expr(*arg, ctx)?; + Ok(true) + })?; write!(self.out, ")")? } // Function arguments are written as the argument name @@ -1940,7 +1983,8 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")",)?; } } - return Err(Error::Custom("ImageQuery not implemented".to_string())); + // TODO: Why is this not implemented ??? + // return Err(Error::Custom("ImageQuery not implemented".to_string())); } // `Unary` is pretty straightforward // "-" - for `Negate` From 4da665d3ba5226be48c4fb1dcb5e636cd9ffc331 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 29 Jun 2021 21:26:28 +0100 Subject: [PATCH 1064/2212] Address comments --- src/back/glsl/mod.rs | 2 - src/front/spv/error.rs | 2 + src/front/spv/function.rs | 2 +- src/front/spv/image.rs | 2 +- src/front/spv/mod.rs | 8 +- src/valid/analyzer.rs | 175 ++++++++++------------------ src/valid/expression.rs | 2 + tests/out/analysis/collatz.info.ron | 8 +- tests/out/analysis/shadow.info.ron | 12 +- 9 files changed, 79 insertions(+), 134 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 4a68df9b0..ac087e0e6 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1983,8 +1983,6 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")",)?; } } - // TODO: Why is this not implemented ??? - // return Err(Error::Custom("ImageQuery not implemented".to_string())); } // `Unary` is pretty straightforward // "-" - for `Negate` diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 688127a27..681710690 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -73,6 +73,8 @@ pub enum Error { InvalidBinding(spirv::Word), #[error("invalid global var {0:?}")] InvalidGlobalVar(crate::Expression), + #[error("invalid image/sampler expression {0:?}")] + InvalidImageExpression(crate::Expression), #[error("invalid image base type {0:?}")] InvalidImageBaseType(Handle), #[error("invalid image {0:?}")] diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index f124bd1f7..387b47290 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -193,7 +193,7 @@ impl> super::Parser { // done let fun_handle = module.functions.append(fun); self.lookup_function.insert(fun_id, fun_handle); - self.function_info.insert(fun_handle, function_info); + self.function_info.push(function_info); if let Some(ep) = self.lookup_entry_point.remove(&fun_id) { // create a wrapping function let mut function = crate::Function { diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 75736771a..bd952edaf 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -31,7 +31,7 @@ impl Arena { match self[handle] { crate::Expression::GlobalVariable(handle) => Ok(global_vars[handle].ty), crate::Expression::FunctionArgument(i) => Ok(arguments[i as usize].ty), - ref other => Err(Error::InvalidGlobalVar(other.clone())), + ref other => Err(Error::InvalidImageExpression(other.clone())), } } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 361be0aa4..9dad738ad 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -409,7 +409,7 @@ pub struct Parser { options: Options, index_constants: Vec>, index_constant_expressions: Vec>, - function_info: FastHashMap, FunctionInfo>, + function_info: Vec, } impl> Parser { @@ -441,7 +441,7 @@ impl> Parser { options: options.clone(), index_constants: Vec::new(), index_constant_expressions: Vec::new(), - function_info: FastHashMap::default(), + function_info: Vec::new(), } } @@ -2312,7 +2312,7 @@ impl> Parser { // Patch sampling flags for (i, arg) in arguments.iter().enumerate() { - let callee_info = &self.function_info[&handle]; + let callee_info = &self.function_info[handle.index()]; if let Some(flags) = callee_info.parameters_sampling.get(i).and_then(|e| *e) { @@ -2323,7 +2323,7 @@ impl> Parser { crate::Expression::FunctionArgument(i) => { if let Some(handle) = function { let function_info = - self.function_info.get_mut(&handle).unwrap(); + self.function_info.get_mut(handle.index()).unwrap(); let caller_flags = function_info.parameters_sampling [i as usize] .get_or_insert(image::SamplingFlags::empty()); diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 032c4f37f..2d68d322f 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -159,7 +159,7 @@ impl ExpressionInfo { } } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] enum GlobalOrArgument { @@ -167,14 +167,22 @@ enum GlobalOrArgument { Argument(u32), } -#[derive(Debug, Clone)] +impl crate::Expression { + fn to_global_or_argument(&self) -> Option { + Some(match *self { + crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), + crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), + _ => return None, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] -struct ArgumentSampling { - /// Whether this argument is used as an image or a sampler - image: bool, - /// The other global or argument used in the sampling - uses: Vec, +struct Sampling { + image: GlobalOrArgument, + sampler: GlobalOrArgument, } #[derive(Debug)] @@ -199,10 +207,8 @@ pub struct FunctionInfo { /// /// Each item corresponds to an expression in the function. expressions: Box<[ExpressionInfo]>, - /// Vector with information of wether or not a functin argument is used for sampling - /// - /// Each item corresponds to a function argument - argument_sampling: Box<[Option]>, + /// HashSet with information about sampling realized by the function + sampling: crate::FastHashSet, } impl FunctionInfo { @@ -304,78 +310,39 @@ impl FunctionInfo { for key in info.sampling_set.iter() { self.sampling_set.insert(key.clone()); } - for (i, arg_sampling) in info - .argument_sampling - .iter() - .enumerate() - .filter_map(|(i, s)| Some((i, s.as_ref()?))) - { - let handle = arguments[i]; - let arg_storage = match expression_arena[handle] { - crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), - crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), - _ => { - return Err(FunctionError::Expression { - handle, - error: ExpressionError::ExpectedGlobalVariable, - }) + for sampling in info.sampling.iter() { + let image_storage = match sampling.image { + GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var), + GlobalOrArgument::Argument(i) => { + let handle = arguments[i as usize]; + expression_arena[handle].to_global_or_argument().ok_or( + FunctionError::Expression { + handle, + error: ExpressionError::ExpectedGlobalOrArgument, + }, + )? } }; - for other in arg_sampling.uses.iter() { - let other_storage = match *other { - GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var), - GlobalOrArgument::Argument(i) => { - let other_handle = arguments[i as usize]; - match expression_arena[other_handle] { - crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), - crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), - _ => { - return Err(FunctionError::Expression { - handle, - error: ExpressionError::ExpectedGlobalVariable, - }) - } - } - } - }; + let sampler_storage = match sampling.sampler { + GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var), + GlobalOrArgument::Argument(i) => { + let handle = arguments[i as usize]; + expression_arena[handle].to_global_or_argument().ok_or( + FunctionError::Expression { + handle, + error: ExpressionError::ExpectedGlobalOrArgument, + }, + )? + } + }; - match (arg_storage, other_storage) { - (GlobalOrArgument::Global(arg), GlobalOrArgument::Global(other)) => { - if arg_sampling.image { - self.sampling_set.insert(SamplingKey { - image: arg, - sampler: other, - }); - } else { - self.sampling_set.insert(SamplingKey { - image: other, - sampler: arg, - }); - } - } - (GlobalOrArgument::Argument(i), _) => { - let sampling = - self.argument_sampling[i as usize].get_or_insert_with(|| { - ArgumentSampling { - image: arg_sampling.image, - uses: Vec::with_capacity(1), - } - }); - - sampling.uses.push(other_storage) - } - (_, GlobalOrArgument::Argument(i)) => { - let sampling = - self.argument_sampling[i as usize].get_or_insert_with(|| { - ArgumentSampling { - image: !arg_sampling.image, - uses: Vec::with_capacity(1), - } - }); - - sampling.uses.push(arg_storage) - } + match (image_storage, sampler_storage) { + (GlobalOrArgument::Global(image), GlobalOrArgument::Global(sampler)) => { + self.sampling_set.insert(SamplingKey { image, sampler }); + } + (image, sampler) => { + self.sampling.insert(Sampling { image, sampler }); } } } @@ -499,42 +466,28 @@ impl FunctionInfo { level, depth_ref, } => { - let image_storage = match expression_arena[image] { - crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), - crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), - _ => return Err(ExpressionError::ExpectedGlobalVariable), - }; - let sampler_storage = match expression_arena[sampler] { - crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), - crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), - _ => return Err(ExpressionError::ExpectedGlobalVariable), - }; + let image_storage = expression_arena[image] + .to_global_or_argument() + .ok_or(ExpressionError::ExpectedGlobalOrArgument)?; + let sampler_storage = expression_arena[sampler] + .to_global_or_argument() + .ok_or(ExpressionError::ExpectedGlobalOrArgument)?; match (image_storage, sampler_storage) { (GlobalOrArgument::Global(image), GlobalOrArgument::Global(sampler)) => { self.sampling_set.insert(SamplingKey { image, sampler }); } - (GlobalOrArgument::Argument(i), _) => { - let sampling = - self.argument_sampling[i as usize].get_or_insert_with(|| { - ArgumentSampling { - image: true, - uses: Vec::with_capacity(1), - } - }); - - sampling.uses.push(sampler_storage) + (GlobalOrArgument::Argument(_), _) => { + self.sampling.insert(Sampling { + image: image_storage, + sampler: sampler_storage, + }); } - (_, GlobalOrArgument::Argument(i)) => { - let sampling = - self.argument_sampling[i as usize].get_or_insert_with(|| { - ArgumentSampling { - image: false, - uses: Vec::with_capacity(1), - } - }); - - sampling.uses.push(image_storage) + (_, GlobalOrArgument::Argument(_)) => { + self.sampling.insert(Sampling { + image: image_storage, + sampler: sampler_storage, + }); } } @@ -864,7 +817,7 @@ impl ModuleInfo { sampling_set: crate::FastHashSet::default(), global_uses: vec![GlobalUse::empty(); module.global_variables.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::new(); fun.expressions.len()].into_boxed_slice(), - argument_sampling: vec![None; fun.arguments.len()].into_boxed_slice(), + sampling: crate::FastHashSet::default(), }; let resolve_context = ResolveContext { constants: &module.constants, @@ -969,7 +922,7 @@ fn uniform_control_flow() { sampling_set: crate::FastHashSet::default(), global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::new(); expressions.len()].into_boxed_slice(), - argument_sampling: vec![None; 0].into_boxed_slice(), + sampling: crate::FastHashSet::default(), }; let resolve_context = ResolveContext { constants: &constant_arena, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 409ca82eb..d1bb45f7b 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -61,6 +61,8 @@ pub enum ExpressionError { Type(#[from] ResolveError), #[error("Not a global variable")] ExpectedGlobalVariable, + #[error("Not a global variable or a function argument")] + ExpectedGlobalOrArgument, #[error("Calling an undeclared function {0:?}")] CallToUndeclaredFunction(Handle), #[error("Needs to be an image instead of {0:?}")] diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index e46776e9d..f3b229d32 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -336,9 +336,7 @@ ty: Handle(1), ), ], - argument_sampling: [ - None, - ], + sampling: [], ), ], entry_points: [ @@ -495,9 +493,7 @@ ty: Handle(1), ), ], - argument_sampling: [ - None, - ], + sampling: [], ), ], ) \ No newline at end of file diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index abaef4336..c084ca057 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -1060,10 +1060,7 @@ )), ), ], - argument_sampling: [ - None, - None, - ], + sampling: [], ), ( flags: ( @@ -2752,7 +2749,7 @@ ty: Handle(4), ), ], - argument_sampling: [], + sampling: [], ), ], entry_points: [ @@ -2876,10 +2873,7 @@ ty: Handle(4), ), ], - argument_sampling: [ - None, - None, - ], + sampling: [], ), ], ) \ No newline at end of file From 2bb15eb0a84af63b5319bd5df385d7ce724b44ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 30 Jun 2021 17:15:35 +0100 Subject: [PATCH 1065/2212] [glsl-in] Add support for texture arguments --- src/front/wgsl/mod.rs | 5 +++-- tests/in/texture-arg.wgsl | 13 +++++++++++ tests/out/glsl/texture-arg.main.Fragment.glsl | 19 ++++++++++++++++ tests/out/msl/texture-arg.msl | 22 +++++++++++++++++++ tests/out/wgsl/texture-arg.wgsl | 15 +++++++++++++ tests/snapshots.rs | 4 ++++ 6 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 tests/in/texture-arg.wgsl create mode 100644 tests/out/glsl/texture-arg.main.Fragment.glsl create mode 100644 tests/out/msl/texture-arg.msl create mode 100644 tests/out/wgsl/texture-arg.wgsl diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index bab096fe3..4afa8d4eb 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1673,8 +1673,9 @@ impl Parser { allow_deref: bool, ) -> Result, Error<'a>> { let mut needs_deref = match ctx.expressions[handle] { - crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => { - allow_deref + crate::Expression::LocalVariable(_) => allow_deref, + crate::Expression::GlobalVariable(var) => { + ctx.global_vars[var].class != crate::StorageClass::Handle && allow_deref } _ => false, }; diff --git a/tests/in/texture-arg.wgsl b/tests/in/texture-arg.wgsl new file mode 100644 index 000000000..af4c382be --- /dev/null +++ b/tests/in/texture-arg.wgsl @@ -0,0 +1,13 @@ +[[group(0), binding(0)]] +var Texture: texture_2d; +[[group(0), binding(1)]] +var Sampler: sampler; + +fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { + return textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); +} + +[[stage(fragment)]] +fn main() -> [[location(0)]] vec4 { + return test(Texture, Sampler); +} diff --git a/tests/out/glsl/texture-arg.main.Fragment.glsl b/tests/out/glsl/texture-arg.main.Fragment.glsl new file mode 100644 index 000000000..371949236 --- /dev/null +++ b/tests/out/glsl/texture-arg.main.Fragment.glsl @@ -0,0 +1,19 @@ +#version 310 es + +precision highp float; + +uniform highp sampler2D _group_0_binding_0; + +layout(location = 0) out vec4 _fs2p_location0; + +vec4 test(highp sampler2D Passed_Texture, ) { + vec4 _expr7 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); + return _expr7; +} + +void main() { + vec4 _expr2 = test(_group_0_binding_0, ); + _fs2p_location0 = _expr2; + return; +} + diff --git a/tests/out/msl/texture-arg.msl b/tests/out/msl/texture-arg.msl new file mode 100644 index 000000000..f958f527f --- /dev/null +++ b/tests/out/msl/texture-arg.msl @@ -0,0 +1,22 @@ +#include +#include + + +metal::float4 test( + metal::texture2d Passed_Texture, + metal::sampler Passed_Sampler +) { + metal::float4 _e7 = Passed_Texture.sample(Passed_Sampler, metal::float2(0.0, 0.0)); + return _e7; +} + +struct main1Output { + metal::float4 member [[color(0)]]; +}; +fragment main1Output main1( + metal::texture2d Texture [[user(fake0)]] +, metal::sampler Sampler [[user(fake0)]] +) { + metal::float4 _e2 = test(Texture, Sampler); + return main1Output { _e2 }; +} diff --git a/tests/out/wgsl/texture-arg.wgsl b/tests/out/wgsl/texture-arg.wgsl new file mode 100644 index 000000000..420b43780 --- /dev/null +++ b/tests/out/wgsl/texture-arg.wgsl @@ -0,0 +1,15 @@ +[[group(0), binding(0)]] +var Texture: texture_2d; +[[group(0), binding(1)]] +var Sampler: sampler; + +fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { + let _e7: vec4 = textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); + return _e7; +} + +[[stage(fragment)]] +fn main() -> [[location(0)]] vec4 { + let _e2: vec4 = test(Texture, Sampler); + return _e2; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b9466738d..1f747478c 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -380,6 +380,10 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, ), ("bounds-check-zero", Targets::SPIRV), + ( + "texture-arg", + Targets::METAL | Targets::GLSL | Targets::WGSL, + ), ]; for &(name, targets) in inputs.iter() { From a1749ab9c597436ecd9a84126261d0a8364ce5d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 30 Jun 2021 20:38:40 +0100 Subject: [PATCH 1066/2212] [glsl-out] Fix argument skipping --- src/back/glsl/mod.rs | 49 ++++++++++--------- tests/out/glsl/texture-arg.main.Fragment.glsl | 4 +- 2 files changed, 27 insertions(+), 26 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ac087e0e6..bb6b68f03 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -964,7 +964,14 @@ impl<'a, W: Write> Writer<'a, W> { back::FunctionType::EntryPoint(_) => &[][..], back::FunctionType::Function(_) => &func.arguments, }; - self.write_slice(arguments, |this, i, arg| { + let arguments: Vec<_> = arguments + .iter() + .filter(|arg| match self.module.types[arg.ty].inner { + TypeInner::Sampler { .. } => false, + _ => true, + }) + .collect(); + self.write_slice(&arguments, |this, i, arg| { // Write the argument type match this.module.types[arg.ty].inner { // We treat images separately because they might require @@ -989,8 +996,6 @@ impl<'a, W: Write> Writer<'a, W> { // any spaces at the beginning or end this.write_image_type(dim, arrayed, class)?; } - // glsl has no concept of samplers so we just ignore it - TypeInner::Sampler { .. } => return Ok(false), // All other types are written by `write_type` _ => { this.write_type(arg.ty)?; @@ -1001,7 +1006,7 @@ impl<'a, W: Write> Writer<'a, W> { // The leading space is important write!(this.out, " {}", &this.names[&ctx.argument_key(i)])?; - Ok(true) + Ok(()) })?; // Close the parentheses and open braces to start the function body @@ -1097,16 +1102,14 @@ impl<'a, W: Write> Writer<'a, W> { /// # Notes /// - Adds no newlines or leading/trailing whitespace /// - The last element won't have a trailing `,` - fn write_slice BackendResult>( + fn write_slice BackendResult>( &mut self, data: &[T], mut f: F, ) -> BackendResult { // Loop trough `data` invoking `f` for each element for (i, item) in data.iter().enumerate() { - if !f(self, i as u32, item)? { - continue; - } + f(self, i as u32, item)?; // Only write a comma if isn't the last element if i != data.len().saturating_sub(1) { @@ -1151,8 +1154,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the comma separated constants self.write_slice(components, |this, _, arg| { - this.write_constant(&this.module.constants[*arg])?; - Ok(true) + this.write_constant(&this.module.constants[*arg]) })?; write!(self.out, ")")? @@ -1617,16 +1619,18 @@ impl<'a, W: Write> Writer<'a, W> { self.named_expressions.insert(expr, name); } write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; - self.write_slice(arguments, |this, i, arg| { - let arg_ty = this.module.functions[function].arguments[i as usize].ty; - if let TypeInner::Sampler { .. } = this.module.types[arg_ty].inner { - return Ok(false); - } - - this.write_expr(*arg, ctx)?; - - Ok(true) - })?; + let arguments: Vec<_> = arguments + .iter() + .enumerate() + .filter_map(|(i, arg)| { + let arg_ty = self.module.functions[function].arguments[i].ty; + match self.module.types[arg_ty].inner { + TypeInner::Sampler { .. } => None, + _ => Some(*arg), + } + }) + .collect(); + self.write_slice(&arguments, |this, _, arg| this.write_expr(*arg, ctx))?; writeln!(self.out, ");")? } } @@ -1726,10 +1730,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(ty)?; write!(self.out, "(")?; - self.write_slice(components, |this, _, arg| { - this.write_expr(*arg, ctx)?; - Ok(true) - })?; + self.write_slice(components, |this, _, arg| this.write_expr(*arg, ctx))?; write!(self.out, ")")? } // Function arguments are written as the argument name diff --git a/tests/out/glsl/texture-arg.main.Fragment.glsl b/tests/out/glsl/texture-arg.main.Fragment.glsl index 371949236..df318d15b 100644 --- a/tests/out/glsl/texture-arg.main.Fragment.glsl +++ b/tests/out/glsl/texture-arg.main.Fragment.glsl @@ -6,13 +6,13 @@ uniform highp sampler2D _group_0_binding_0; layout(location = 0) out vec4 _fs2p_location0; -vec4 test(highp sampler2D Passed_Texture, ) { +vec4 test(highp sampler2D Passed_Texture) { vec4 _expr7 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); return _expr7; } void main() { - vec4 _expr2 = test(_group_0_binding_0, ); + vec4 _expr2 = test(_group_0_binding_0); _fs2p_location0 = _expr2; return; } From 8880faf360ef0bfaccc397d6d65ee852c1f7c02a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 1 Jul 2021 13:34:45 +0100 Subject: [PATCH 1067/2212] Address more comments --- src/front/spv/function.rs | 2 +- src/front/spv/image.rs | 6 ++---- src/front/spv/mod.rs | 39 +++++++++++++++++++++----------------- src/valid/analyzer.rs | 40 ++++++++++++--------------------------- 4 files changed, 37 insertions(+), 50 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 387b47290..75ca69588 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -136,7 +136,7 @@ impl> super::Parser { let mut flow_graph = FlowGraph::new(); let mut function_info = FunctionInfo { - parameters_sampling: vec![None; fun.arguments.len()], + parameters_sampling: vec![super::image::SamplingFlags::empty(); fun.arguments.len()], }; // Scan the blocks and add them as nodes diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index bd952edaf..a4b1c9fbd 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -456,8 +456,7 @@ impl> super::Parser { global_arena[handle].ty } crate::Expression::FunctionArgument(i) => { - let flags = function_info.parameters_sampling[i as usize] - .get_or_insert(SamplingFlags::empty()); + let flags = &mut function_info.parameters_sampling[i as usize]; *flags |= sampling_bit; arguments[i as usize].ty @@ -469,8 +468,7 @@ impl> super::Parser { *self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit } crate::Expression::FunctionArgument(i) => { - let flags = function_info.parameters_sampling[i as usize] - .get_or_insert(SamplingFlags::empty()); + let flags = &mut function_info.parameters_sampling[i as usize]; *flags |= sampling_bit; } ref other => return Err(Error::InvalidGlobalVar(other.clone())), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 9dad738ad..d03ea8b33 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -372,7 +372,7 @@ impl Default for Options { } struct FunctionInfo { - parameters_sampling: Vec>, + parameters_sampling: Vec, } pub struct Parser { @@ -2314,24 +2314,29 @@ impl> Parser { for (i, arg) in arguments.iter().enumerate() { let callee_info = &self.function_info[handle.index()]; - if let Some(flags) = callee_info.parameters_sampling.get(i).and_then(|e| *e) - { - match expressions[*arg] { - crate::Expression::GlobalVariable(handle) => { - *self.handle_sampling.get_mut(&handle).unwrap() |= flags + let flags = match callee_info.parameters_sampling.get(i) { + Some(&flags) => flags, + _ => continue, + }; + + if flags.is_empty() { + continue; + } + + match expressions[*arg] { + crate::Expression::GlobalVariable(handle) => { + if let Some(sampling) = self.handle_sampling.get_mut(&handle) { + *sampling |= flags } - crate::Expression::FunctionArgument(i) => { - if let Some(handle) = function { - let function_info = - self.function_info.get_mut(handle.index()).unwrap(); - let caller_flags = function_info.parameters_sampling - [i as usize] - .get_or_insert(image::SamplingFlags::empty()); - *caller_flags |= flags; - } - } - ref other => return Err(Error::InvalidGlobalVar(other.clone())), } + crate::Expression::FunctionArgument(i) => { + if let Some(handle) = function { + let function_info = + self.function_info.get_mut(handle.index()).unwrap(); + function_info.parameters_sampling[i as usize] |= flags; + } + } + ref other => return Err(Error::InvalidGlobalVar(other.clone())), } } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 2d68d322f..2655736cb 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -168,11 +168,11 @@ enum GlobalOrArgument { } impl crate::Expression { - fn to_global_or_argument(&self) -> Option { - Some(match *self { + fn to_global_or_argument(&self) -> Result { + Ok(match *self { crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), - _ => return None, + _ => return Err(ExpressionError::ExpectedGlobalOrArgument), }) } } @@ -315,12 +315,9 @@ impl FunctionInfo { GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var), GlobalOrArgument::Argument(i) => { let handle = arguments[i as usize]; - expression_arena[handle].to_global_or_argument().ok_or( - FunctionError::Expression { - handle, - error: ExpressionError::ExpectedGlobalOrArgument, - }, - )? + expression_arena[handle] + .to_global_or_argument() + .map_err(|error| FunctionError::Expression { handle, error })? } }; @@ -328,12 +325,9 @@ impl FunctionInfo { GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var), GlobalOrArgument::Argument(i) => { let handle = arguments[i as usize]; - expression_arena[handle].to_global_or_argument().ok_or( - FunctionError::Expression { - handle, - error: ExpressionError::ExpectedGlobalOrArgument, - }, - )? + expression_arena[handle] + .to_global_or_argument() + .map_err(|error| FunctionError::Expression { handle, error })? } }; @@ -466,24 +460,14 @@ impl FunctionInfo { level, depth_ref, } => { - let image_storage = expression_arena[image] - .to_global_or_argument() - .ok_or(ExpressionError::ExpectedGlobalOrArgument)?; - let sampler_storage = expression_arena[sampler] - .to_global_or_argument() - .ok_or(ExpressionError::ExpectedGlobalOrArgument)?; + let image_storage = expression_arena[image].to_global_or_argument()?; + let sampler_storage = expression_arena[sampler].to_global_or_argument()?; match (image_storage, sampler_storage) { (GlobalOrArgument::Global(image), GlobalOrArgument::Global(sampler)) => { self.sampling_set.insert(SamplingKey { image, sampler }); } - (GlobalOrArgument::Argument(_), _) => { - self.sampling.insert(Sampling { - image: image_storage, - sampler: sampler_storage, - }); - } - (_, GlobalOrArgument::Argument(_)) => { + _ => { self.sampling.insert(Sampling { image: image_storage, sampler: sampler_storage, From cb8e9f2cade5c702083a8410e997a2f06619d0ee Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Wed, 30 Jun 2021 19:20:11 -0700 Subject: [PATCH 1068/2212] [glsl-in] Implicitly splat the inputs of clamp() --- src/front/glsl/ast.rs | 19 ++++++++++++++++++ src/front/glsl/functions.rs | 30 ++++++++++++++++++++++++++-- tests/in/glsl/clamp-splat.vert | 6 ++++++ tests/out/wgsl/clamp-splat-vert.wgsl | 20 +++++++++++++++++++ 4 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 tests/in/glsl/clamp-splat.vert create mode 100644 tests/out/wgsl/clamp-splat-vert.wgsl diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index d1ba273d3..43d62f901 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -883,6 +883,25 @@ impl<'function> Context<'function> { Ok(()) } + + pub fn implicit_splat( + &mut self, + program: &mut Program, + expr: &mut Handle, + meta: SourceMetadata, + vector_size: Option, + ) -> Result<(), ErrorKind> { + let expr_type = program.resolve_type(self, *expr, meta)?; + + if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { + *expr = self.expressions.append(Expression::Splat { + size, + value: *expr, + }) + } + + Ok(()) + } } pub fn type_power(kind: ScalarKind) -> Option { diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index f8dfe6f42..509e96452 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -444,14 +444,40 @@ impl Program<'_> { }, )) } - "clamp" | "faceforward" | "refract" | "fma" | "smoothstep" => { + "clamp" => { + if args.len() != 3 { + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + } + + let (arg0, arg0_meta) = args[0]; + let vector_size = match *(self.resolve_type(ctx, arg0, arg0_meta)?) { + TypeInner::Vector{ size, .. } => Some(size), + _ => None, + }; + + let (mut arg1, arg1_meta) = args[1]; + ctx.implicit_splat(self, &mut arg1, arg1_meta, vector_size)?; + + let (mut arg2, arg2_meta) = args[2]; + ctx.implicit_splat(self, &mut arg2, arg2_meta, vector_size)?; + + Ok(Some(ctx.add_expression( + Expression::Math { + fun: MathFunction::Clamp, + arg: arg0, + arg1: Some(arg1), + arg2: Some(arg2), + }, + body, + ))) + } + "faceforward" | "refract" | "fma" | "smoothstep" => { if args.len() != 3 { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } Ok(Some(ctx.add_expression( Expression::Math { fun: match name.as_str() { - "clamp" => MathFunction::Clamp, "faceforward" => MathFunction::FaceForward, "refract" => MathFunction::Refract, "fma" => MathFunction::Fma, diff --git a/tests/in/glsl/clamp-splat.vert b/tests/in/glsl/clamp-splat.vert new file mode 100644 index 000000000..70ade6098 --- /dev/null +++ b/tests/in/glsl/clamp-splat.vert @@ -0,0 +1,6 @@ +#version 450 +layout(location = 0) in vec2 a_pos; + +void main() { + gl_Position = vec4(clamp(a_pos, 0.0, 1.0), 0.0, 1.0); +} diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl new file mode 100644 index 000000000..08f00587b --- /dev/null +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -0,0 +1,20 @@ +struct VertexOutput { + [[builtin(position)]] member: vec4; +}; + +var a_pos1: vec2; +var gl_Position: vec4; + +fn main1() { + let _e2: vec2 = a_pos1; + gl_Position = vec4(clamp(_e2, vec2(0.0), vec2(1.0)), 0.0, 1.0); + return; +} + +[[stage(vertex)]] +fn main([[location(0), interpolate(perspective)]] a_pos: vec2) -> VertexOutput { + a_pos1 = a_pos; + main1(); + let _e3: vec4 = gl_Position; + return VertexOutput(_e3); +} From 377941a98feb6e30b6f51e64f852ba13cdb5191b Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Thu, 1 Jul 2021 19:16:39 +0200 Subject: [PATCH 1069/2212] [msl-out] Add 'this' as a reserved keyword --- src/back/msl/keywords.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs index bb4338560..af4be8827 100644 --- a/src/back/msl/keywords.rs +++ b/src/back/msl/keywords.rs @@ -55,6 +55,7 @@ pub const RESERVED: &[&str] = &[ "vec_step", "visible", "as_type", + "this", // qualifiers "mutable", "static", From e277cd1b1296bf4b0e34a59e19f2e5a46d6ab529 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 1 Jul 2021 17:12:42 +0100 Subject: [PATCH 1070/2212] [glsl-in] Fix shifts between vectors and scalars --- src/front/glsl/ast.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 43d62f901..9aae02381 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -538,7 +538,11 @@ impl<'function> Context<'function> { _ => self.add_expression(Expression::Binary { left, op, right }, body), }, (&TypeInner::Vector { size, .. }, &TypeInner::Scalar { .. }) => match op { - BinaryOperator::Add | BinaryOperator::Subtract | BinaryOperator::Divide => { + BinaryOperator::Add + | BinaryOperator::Subtract + | BinaryOperator::Divide + | BinaryOperator::ShiftLeft + | BinaryOperator::ShiftRight => { let scalar_vector = self.add_expression(Expression::Splat { size, value: right }, body); From 1e2aee226365f6a9d981c8f0e9e7aa5a6d4bb744 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 1 Jul 2021 17:13:24 +0100 Subject: [PATCH 1071/2212] [glsl-in] Clamp function fixes Allow vector sources and scalar selector Do implicit conversions --- src/front/glsl/functions.rs | 67 ++++++++++++++++++++++++++----------- 1 file changed, 47 insertions(+), 20 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 509e96452..71ec259e7 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -419,30 +419,57 @@ impl Program<'_> { if args.len() != 3 { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } - Ok(Some( - if let Some(ScalarKind::Bool) = - self.resolve_type(ctx, args[2].0, args[2].1)?.scalar_kind() - { - ctx.add_expression( - Expression::Select { - condition: args[2].0, - accept: args[0].0, - reject: args[1].0, - }, - body, - ) - } else { - ctx.add_expression( - Expression::Math { - fun: MathFunction::Mix, - arg: args[0].0, - arg1: Some(args[1].0), - arg2: Some(args[2].0), + + let (mut arg, arg_meta) = args[0]; + let (mut arg1, arg1_meta) = args[1]; + let (mut selector, selector_meta) = args[2]; + + ctx.binary_implicit_conversion( + self, &mut arg, arg_meta, &mut arg1, arg1_meta, + )?; + ctx.binary_implicit_conversion( + self, + &mut arg, + arg_meta, + &mut selector, + selector_meta, + )?; + + let is_vector = match *self.resolve_type(ctx, selector, selector_meta)? { + TypeInner::Vector { .. } => true, + _ => false, + }; + match *self.resolve_type(ctx, args[0].0, args[0].1)? { + TypeInner::Vector { size, .. } if !is_vector => { + selector = ctx.add_expression( + Expression::Splat { + size, + value: selector, }, body, ) + } + _ => {} + }; + + let expr = match self + .resolve_type(ctx, selector, selector_meta)? + .scalar_kind() + { + Some(ScalarKind::Bool) => Expression::Select { + condition: selector, + accept: arg, + reject: arg1, }, - )) + _ => Expression::Math { + fun: MathFunction::Mix, + arg, + arg1: Some(arg1), + arg2: Some(selector), + }, + }; + + Ok(Some(ctx.add_expression(expr, body))) } "clamp" => { if args.len() != 3 { From 6e9410c05634a9319b2d146855dea68b5d4acb50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 1 Jul 2021 19:57:54 +0100 Subject: [PATCH 1072/2212] [glsl-in] More implicit casts for builtins --- src/front/glsl/functions.rs | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 71ec259e7..fab1f5ae2 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -391,6 +391,14 @@ impl Program<'_> { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } + + let (mut arg0, arg0_meta) = args[0]; + let (mut arg1, arg1_meta) = args[1]; + + ctx.binary_implicit_conversion( + self, &mut arg0, arg0_meta, &mut arg1, arg1_meta, + )?; + Ok(Some(ctx.add_expression( Expression::Math { fun: match name.as_str() { @@ -408,8 +416,8 @@ impl Program<'_> { "ldexp" => MathFunction::Ldexp, _ => unreachable!(), }, - arg: args[0].0, - arg1: Some(args[1].0), + arg: arg0, + arg1: Some(arg1), arg2: None, }, body, @@ -476,16 +484,26 @@ impl Program<'_> { return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); } - let (arg0, arg0_meta) = args[0]; + let (mut arg0, arg0_meta) = args[0]; + let (mut arg1, arg1_meta) = args[1]; + let (mut arg2, arg2_meta) = args[2]; + let vector_size = match *(self.resolve_type(ctx, arg0, arg0_meta)?) { - TypeInner::Vector{ size, .. } => Some(size), + TypeInner::Vector { size, .. } => Some(size), _ => None, }; - let (mut arg1, arg1_meta) = args[1]; - ctx.implicit_splat(self, &mut arg1, arg1_meta, vector_size)?; + ctx.binary_implicit_conversion( + self, &mut arg0, arg0_meta, &mut arg1, arg1_meta, + )?; + ctx.binary_implicit_conversion( + self, &mut arg1, arg1_meta, &mut arg2, arg2_meta, + )?; + ctx.binary_implicit_conversion( + self, &mut arg2, arg2_meta, &mut arg0, arg0_meta, + )?; - let (mut arg2, arg2_meta) = args[2]; + ctx.implicit_splat(self, &mut arg1, arg1_meta, vector_size)?; ctx.implicit_splat(self, &mut arg2, arg2_meta, vector_size)?; Ok(Some(ctx.add_expression( From a92f7689f2dc4b15ffd03726cb5ca24d76e545aa Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 1 Jul 2021 23:52:36 -0400 Subject: [PATCH 1073/2212] [mtl] detect binding incomatibility --- src/back/msl/writer.rs | 18 +++++++++++++++--- src/front/glsl/ast.rs | 7 +++---- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 2d2d715ca..836cc523e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2007,15 +2007,27 @@ impl Writer { let mut ep_error = None; let mut supports_array_length = false; - // skip this entry point if any global bindings are missing + // skip this entry point if any global bindings are missing, + // or their types are incompatible. if !options.fake_missing_bindings { for (var_handle, var) in module.global_variables.iter() { if fun_info[var_handle].is_empty() { continue; } if let Some(ref br) = var.binding { - if let Err(e) = options.resolve_resource_binding(ep.stage, br) { - ep_error = Some(e); + let good = match options.per_stage_map[ep.stage].resources.get(br) { + Some(target) => match module.types[var.ty].inner { + crate::TypeInner::Struct { + top_level: true, .. + } => target.buffer.is_some(), + crate::TypeInner::Image { .. } => target.texture.is_some(), + crate::TypeInner::Sampler { .. } => target.sampler.is_some(), + _ => false, + }, + None => false, + }; + if !good { + ep_error = Some(super::EntryPointError::MissingBinding(br.clone())); break; } } diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 9aae02381..4a55caa43 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -898,10 +898,9 @@ impl<'function> Context<'function> { let expr_type = program.resolve_type(self, *expr, meta)?; if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { - *expr = self.expressions.append(Expression::Splat { - size, - value: *expr, - }) + *expr = self + .expressions + .append(Expression::Splat { size, value: *expr }) } Ok(()) From 78e1304d42eaead59e8c453ff3654b7c2a4fff08 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Thu, 1 Jul 2021 19:57:51 -0700 Subject: [PATCH 1074/2212] [glsl-in] Convert bool -> scalar cast to Select --- src/front/glsl/functions.rs | 61 +++++++++++++++++++++++++--- src/valid/expression.rs | 8 ++-- tests/in/glsl/bool-select.frag | 17 ++++++++ tests/out/wgsl/bool-select-frag.wgsl | 45 ++++++++++++++++++++ 4 files changed, 122 insertions(+), 9 deletions(-) create mode 100644 tests/in/glsl/bool-select.frag create mode 100644 tests/out/wgsl/bool-select-frag.wgsl diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index fab1f5ae2..15d8ba753 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,13 +1,35 @@ use crate::{ - proc::ensure_block_returns, Arena, BinaryOperator, Block, EntryPoint, Expression, Function, + proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, ImageQuery, LocalVariable, MathFunction, - RelationalFunction, SampleLevel, ScalarKind, Statement, StructMember, SwizzleComponent, Type, + RelationalFunction, SampleLevel, ScalarKind, ScalarValue, Statement, StructMember, SwizzleComponent, Type, TypeInner, VectorSize, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; impl Program<'_> { + fn add_constant_value( + &mut self, + scalar_kind: ScalarKind, + value: u64, + ) -> Handle { + let value = match scalar_kind { + ScalarKind::Uint => ScalarValue::Uint(value), + ScalarKind::Sint => ScalarValue::Sint(value as i64), + ScalarKind::Float => ScalarValue::Float(value as f64), + _ => unreachable!(), + }; + + self.module.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value, + }, + }) + } + pub fn function_call( &mut self, ctx: &mut Context, @@ -24,13 +46,40 @@ impl Program<'_> { match fc { FunctionCallKind::TypeConstructor(ty) => { let h = if args.len() == 1 { - let is_vec = match *self.resolve_type(ctx, args[0].0, args[0].1)? { - TypeInner::Vector { .. } => true, - _ => false, + let expr_type = self.resolve_type(ctx, args[0].0, args[0].1)?; + + let vector_size = match *expr_type { + TypeInner::Vector{ size, .. } => Some(size), + _ => None, }; + // Special case: if casting from a bool, we need to use Select and not As. + match self.module.types[ty].inner.scalar_kind() { + Some(result_scalar_kind) if expr_type.scalar_kind() == Some(ScalarKind::Bool) && result_scalar_kind != ScalarKind::Bool => { + let c0 = self.add_constant_value(result_scalar_kind, 0u64); + let c1 = self.add_constant_value(result_scalar_kind, 1u64); + let mut reject = ctx.add_expression(Expression::Constant(c0), body); + let mut accept = ctx.add_expression(Expression::Constant(c1), body); + + ctx.implicit_splat(self, &mut reject, meta, vector_size)?; + ctx.implicit_splat(self, &mut accept, meta, vector_size)?; + + let h = ctx.add_expression( + Expression::Select { + accept, + reject, + condition: args[0].0, + }, + body, + ); + + return Ok(Some(h)); + } + _ => {} + } + match self.module.types[ty].inner { - TypeInner::Vector { size, kind, .. } if !is_vec => { + TypeInner::Vector { size, kind, .. } if vector_size.is_none() => { let (mut value, meta) = args[0]; ctx.implicit_conversion(self, &mut value, meta, kind)?; diff --git a/src/valid/expression.rs b/src/valid/expression.rs index d1bb45f7b..990026d9b 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1159,13 +1159,15 @@ impl super::Validator { .resolve(expr)? .scalar_kind() .ok_or(ExpressionError::InvalidCastArgument)?; + + if prev_kind == Sk::Bool || kind == Sk::Bool { + return Err(ExpressionError::InvalidCastArgument); + } + match convert { Some(width) if !self.check_width(kind, width) => { return Err(ExpressionError::InvalidCastArgument) } - None if prev_kind == Sk::Bool || kind == Sk::Bool => { - return Err(ExpressionError::InvalidCastArgument) - } _ => {} } ShaderStages::all() diff --git a/tests/in/glsl/bool-select.frag b/tests/in/glsl/bool-select.frag new file mode 100644 index 000000000..96cd7d4ae --- /dev/null +++ b/tests/in/glsl/bool-select.frag @@ -0,0 +1,17 @@ +#version 440 core +precision highp float; + +layout(location = 0) out vec4 o_color; + +float TevPerCompGT(float a, float b) { + return float(a > b); +} + +vec3 TevPerCompGT(vec3 a, vec3 b) { + return vec3(greaterThan(a, b)); +} + +void main() { + o_color.rgb = TevPerCompGT(vec3(3.0), vec3(5.0)); + o_color.a = TevPerCompGT(3.0, 5.0); +} diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl new file mode 100644 index 000000000..51524143b --- /dev/null +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -0,0 +1,45 @@ +struct FragmentOutput { + [[location(0), interpolate(perspective)]] o_color: vec4; +}; + +var o_color: vec4; + +fn TevPerCompGT(a: f32, b: f32) -> f32 { + var a1: f32; + var b1: f32; + + a1 = a; + b1 = b; + let _e5: f32 = a1; + let _e6: f32 = b1; + return select(1.0, 0.0, (_e5 > _e6)); +} + +fn TevPerCompGT1(a2: vec3, b2: vec3) -> vec3 { + var a3: vec3; + var b3: vec3; + + a3 = a2; + b3 = b2; + let _e5: vec3 = a3; + let _e6: vec3 = b3; + return select(vec3(1.0), vec3(0.0), (_e5 > _e6)); +} + +fn main1() { + let _e1: vec4 = o_color; + let _e11: vec3 = TevPerCompGT1(vec3(3.0), vec3(5.0)); + o_color.x = _e11.x; + o_color.y = _e11.y; + o_color.z = _e11.z; + let _e23: f32 = TevPerCompGT(3.0, 5.0); + o_color.w = _e23; + return; +} + +[[stage(fragment)]] +fn main() -> FragmentOutput { + main1(); + let _e1: vec4 = o_color; + return FragmentOutput(_e1); +} From 0b9af95793e319817e74a30601cbcd4bad9bb3e6 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Thu, 1 Jul 2021 22:40:53 -0700 Subject: [PATCH 1075/2212] [glsl-in] Make sure to Load on a ValuePointer as well Fixes issues with indexing vectors. --- src/front/glsl/ast.rs | 15 +++++++++------ src/front/glsl/parser_tests.rs | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 4a55caa43..1247adcb1 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -485,12 +485,15 @@ impl<'function> Context<'function> { self.add_expression(Expression::Access { base, index }, body) }); - if let TypeInner::Pointer { .. } = *program.resolve_type(self, pointer, meta)? { - if !lhs { - return Ok(( - Some(self.add_expression(Expression::Load { pointer }, body)), - meta, - )); + if !lhs { + match *program.resolve_type(self, pointer, meta)? { + TypeInner::Pointer { .. } | TypeInner::ValuePointer { .. } => { + return Ok(( + Some(self.add_expression(Expression::Load { pointer }, body)), + meta, + )); + }, + _ => {}, } } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 6bf6f78bf..465163867 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -673,3 +673,21 @@ fn swizzles() { ) .unwrap_err(); } + +#[test] +fn vector_indexing() { + let mut entry_points = crate::FastHashMap::default(); + entry_points.insert("".to_string(), ShaderStage::Fragment); + + parse_program( + r#" + # version 450 + float main(int index) { + vec4 v = vec4(1.0, 2.0, 3.0, 4.0); + return v[index] + 1.0; + } + "#, + &entry_points, + ) + .unwrap(); +} From 7a9fb864ad855f43889d4f203dafe4c80acde9c6 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Fri, 2 Jul 2021 10:36:47 -0700 Subject: [PATCH 1076/2212] [glsl-in] Add support for gl_FragCoord / gl_FragDepth And remove the ability to read gl_Position in fragment. --- src/front/glsl/variables.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 529036caa..cec46cdff 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -100,8 +100,27 @@ impl Program<'_> { }, BuiltIn::Position, true, + PrologueStage::empty(), + ), + "gl_FragCoord" => add_builtin( + TypeInner::Vector { + size: VectorSize::Quad, + kind: ScalarKind::Float, + width: 4, + }, + BuiltIn::Position, + false, PrologueStage::FRAGMENT, ), + "gl_FragDepth" => add_builtin( + TypeInner::Scalar { + kind: ScalarKind::Float, + width: 4, + }, + BuiltIn::FragDepth, + true, + PrologueStage::empty(), + ), "gl_VertexIndex" => add_builtin( TypeInner::Scalar { kind: ScalarKind::Uint, From c5805a9e10bbd8c8a48b9956da332cee19f6995f Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Sun, 4 Jul 2021 00:42:22 -0230 Subject: [PATCH 1077/2212] wgsl-in: add more error tests --- src/front/wgsl/mod.rs | 18 +++---- tests/wgsl-errors.rs | 113 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+), 12 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 4afa8d4eb..7e70a4dbc 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -104,17 +104,15 @@ pub enum Error<'a> { BadScalarWidth(Span, &'a str), #[error("")] BadAccessor(Span), - #[error("bad texture`")] + #[error("")] BadTexture(Span), - #[error("bad texture coordinate")] - BadCoordinate, - #[error("invalid type cast")] + #[error("")] BadTypeCast { span: Span, from_type: String, to_type: String, }, - #[error("bad texture sample type. Only f32, i32 and u32 are valid")] + #[error("")] BadTextureSampleType { span: Span, kind: crate::ScalarKind, @@ -122,15 +120,11 @@ pub enum Error<'a> { }, #[error(transparent)] InvalidResolve(ResolveError), - #[error("for(;;) initializer is not an assignment or a function call")] + #[error("")] InvalidForInitializer(Span), - #[error("resource type {0:?} is invalid")] - InvalidResourceType(Handle), - #[error("unknown import: `{0}`")] - UnknownImport(&'a str), - #[error("unknown storage class")] + #[error("")] UnknownStorageClass(Span), - #[error("unknown attribute")] + #[error("")] UnknownAttribute(Span), #[error("unknown scalar kind: `{0}`")] UnknownScalarKind(&'a str), diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index c33000403..ccb521c00 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -128,6 +128,119 @@ fn negative_index() { ); } +#[test] +fn bad_texture() { + check( + r#" + [[group(0), binding(0)]] var sampler : sampler; + + [[stage(fragment)]] + fn main() -> [[location(0)]] vec4 { + let a = 3; + return textureSample(a, sampler, vec2(0.0)); + } + "#, + r#"error: expected an image, but found 'a' which is not an image + ┌─ wgsl:7:38 + │ +7 │ return textureSample(a, sampler, vec2(0.0)); + │ ^ not an image + +"# + ); +} + +#[test] +fn bad_type_cast() { + check( + r#" + fn x() -> i32 { + return i32(vec2(0.0)); + } + "#, + r#"error: cannot cast a vec2 to a i32 + ┌─ wgsl:3:27 + │ +3 │ return i32(vec2(0.0)); + │ ^^^^^^^^^^^^^^^^ cannot cast a vec2 to a i32 + +"#, + ); +} + +#[test] +fn bad_texture_sample_type() { + check( + r#" + [[group(0), binding(0)]] var sampler : sampler; + [[group(0), binding(1)]] var texture : texture_2d; + + [[stage(fragment)]] + fn main() -> [[location(0)]] vec4 { + return textureSample(texture, sampler, vec2(0.0)); + } + "#, + r#"error: texture sample type must be one of f32, i32 or u32, but found bool + ┌─ wgsl:3:63 + │ +3 │ [[group(0), binding(1)]] var texture : texture_2d; + │ ^^^^ must be one of f32, i32 or u32 + +"# + ); +} + +#[test] +fn bad_for_initializer() { + check( + r#" + fn x() { + for ({};;) {} + } + "#, + r#"error: for(;;) initializer is not an assignment or a function call: '{}' + ┌─ wgsl:3:22 + │ +3 │ for ({};;) {} + │ ^^ not an assignment or function call + +"#, + ); +} + +#[test] +fn unknown_storage_class() { + check( + r#" + [[group(0), binding(0)]] var texture: texture_2d; + "#, + r#"error: unknown storage class: 'bad' + ┌─ wgsl:2:42 + │ +2 │ [[group(0), binding(0)]] var texture: texture_2d; + │ ^^^ unknown storage class + +"#, + ); +} + +#[test] +fn unknown_attribute() { + check( + r#" + [[a]] + fn x() {} + "#, + r#"error: unknown attribute: 'a' + ┌─ wgsl:2:15 + │ +2 │ [[a]] + │ ^ unknown attribute + +"# + ); +} + macro_rules! check_validation_error { // We want to support an optional guard expression after the pattern, so // that we can check values we can't match against, like strings. From c7b98f5ab9b073f49277c4c21d6113629136dec5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 2 Jul 2021 11:43:14 +0100 Subject: [PATCH 1078/2212] [spv-out] accept texture trough function argument --- src/back/spv/block.rs | 31 ++++++++++++----- src/back/spv/writer.rs | 15 +++++++-- tests/in/texture-arg.param.ron | 5 +++ tests/out/spv/texture-arg.spvasm | 58 ++++++++++++++++++++++++++++++++ tests/snapshots.rs | 2 +- 5 files changed, 100 insertions(+), 11 deletions(-) create mode 100644 tests/in/texture-arg.param.ron create mode 100644 tests/out/spv/texture-arg.spvasm diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index a3ec5ced9..90b8c7abe 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -703,7 +703,7 @@ impl<'w> BlockContext<'w> { array_index, index, } => { - let image_id = self.get_expression_global(image); + let image_id = self.get_image_id(block, image)?; let coordinate_id = self.write_texture_coordinates(coordinate, array_index, block)?; @@ -773,7 +773,7 @@ impl<'w> BlockContext<'w> { } => { use super::instructions::SampleLod; // image - let image_id = self.get_expression_global(image); + let image_id = self.get_image_id(block, image)?; let image_type = self.fun_info[image].ty.handle().unwrap(); // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, // so we need to grab the first component out of it. @@ -800,7 +800,7 @@ impl<'w> BlockContext<'w> { let sampled_image_type_id = self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id }))?; - let sampler_id = self.get_expression_global(sampler); + let sampler_id = self.get_image_id(block, sampler)?; let coordinate_id = self.write_texture_coordinates(coordinate, array_index, block)?; @@ -960,7 +960,7 @@ impl<'w> BlockContext<'w> { crate::Expression::ImageQuery { image, query } => { use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq}; - let image_id = self.get_expression_global(image); + let image_id = self.get_image_id(block, image)?; let image_type = self.fun_info[image].ty.handle().unwrap(); let (dim, arrayed, class) = match self.ir_module.types[image_type].inner { crate::TypeInner::Image { @@ -1233,8 +1233,12 @@ impl<'w> BlockContext<'w> { Ok(pointer) } - fn get_expression_global(&self, expr_handle: Handle) -> Word { - match self.ir_function.expressions[expr_handle] { + fn get_image_id( + &mut self, + block: &mut Block, + expr_handle: Handle, + ) -> Result { + Ok(match self.ir_function.expressions[expr_handle] { crate::Expression::GlobalVariable(handle) => { let id = self.writer.global_variables[handle.index()].handle_id; if id == 0 { @@ -1242,8 +1246,19 @@ impl<'w> BlockContext<'w> { } id } + crate::Expression::FunctionArgument(i) => { + let result_type_id = self.get_type_id(LookupType::Handle( + self.ir_function.arguments[i as usize].ty, + ))?; + let pointer_id = self.function.parameter_id(i); + let id = self.gen_id(); + block + .body + .push(Instruction::load(result_type_id, id, pointer_id, None)); + id + } ref other => unreachable!("Unexpected global expression {:?}", other), - } + }) } pub(super) fn write_block( @@ -1516,7 +1531,7 @@ impl<'w> BlockContext<'w> { array_index, value, } => { - let image_id = self.get_expression_global(image); + let image_id = self.get_image_id(&mut block, image)?; let coordinate_id = self.write_texture_coordinates(coordinate, array_index, &mut block)?; let value_id = self.cached(value); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 2e7f90169..e53ec6164 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -175,7 +175,7 @@ impl Writer { self.get_type_id(lookup_ty) } - fn get_pointer_id( + pub(super) fn get_pointer_id( &mut self, arena: &Arena, handle: Handle, @@ -269,7 +269,18 @@ impl Writer { let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); for argument in ir_function.arguments.iter() { let class = spirv::StorageClass::Input; - let argument_type_id = self.get_type_id(LookupType::Handle(argument.ty))?; + let handle_ty = match ir_module.types[argument.ty].inner { + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => true, + _ => false, + }; + let argument_type_id = match handle_ty { + true => self.get_pointer_id( + &ir_module.types, + argument.ty, + spirv::StorageClass::UniformConstant, + )?, + false => self.get_type_id(LookupType::Handle(argument.ty))?, + }; if let Some(ref mut list) = varying_ids { let id = if let Some(ref binding) = argument.binding { let name = argument.name.as_ref().map(AsRef::as_ref); diff --git a/tests/in/texture-arg.param.ron b/tests/in/texture-arg.param.ron new file mode 100644 index 000000000..a049e71aa --- /dev/null +++ b/tests/in/texture-arg.param.ron @@ -0,0 +1,5 @@ +( + spv_version: (1, 0), + spv_debug: true, + spv_adjust_coordinate_space: true, +) diff --git a/tests/out/spv/texture-arg.spvasm b/tests/out/spv/texture-arg.spvasm new file mode 100644 index 000000000..80a87f76f --- /dev/null +++ b/tests/out/spv/texture-arg.spvasm @@ -0,0 +1,58 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 34 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %28 "main" %26 +OpExecutionMode %28 OriginUpperLeft +OpSource GLSL 450 +OpName %9 "Texture" +OpName %11 "Sampler" +OpName %16 "test" +OpName %28 "main" +OpDecorate %9 DescriptorSet 0 +OpDecorate %9 Binding 0 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 1 +OpDecorate %26 Location 0 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 0.0 +%5 = OpTypeImage %4 2D 0 0 0 1 Unknown +%6 = OpTypeSampler +%7 = OpTypeVector %4 4 +%8 = OpTypeVector %4 2 +%10 = OpTypePointer UniformConstant %5 +%9 = OpVariable %10 UniformConstant +%12 = OpTypePointer UniformConstant %6 +%11 = OpVariable %12 UniformConstant +%17 = OpTypeFunction %7 %10 %12 +%21 = OpTypeSampledImage %5 +%27 = OpTypePointer Output %7 +%26 = OpVariable %27 Output +%29 = OpTypeFunction %2 +%16 = OpFunction %7 None %17 +%14 = OpFunctionParameter %10 +%15 = OpFunctionParameter %12 +%13 = OpLabel +OpBranch %18 +%18 = OpLabel +%19 = OpCompositeConstruct %8 %3 %3 +%20 = OpLoad %5 %14 +%22 = OpLoad %6 %15 +%23 = OpSampledImage %21 %20 %22 +%24 = OpImageSampleImplicitLod %7 %23 %19 +OpReturnValue %24 +OpFunctionEnd +%28 = OpFunction %2 None %29 +%25 = OpLabel +%30 = OpLoad %5 %9 +%31 = OpLoad %6 %11 +OpBranch %32 +%32 = OpLabel +%33 = OpFunctionCall %7 %16 %9 %11 +OpStore %26 %33 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1f747478c..b4950547c 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -382,7 +382,7 @@ fn convert_wgsl() { ("bounds-check-zero", Targets::SPIRV), ( "texture-arg", - Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, ), ]; From 2f002a05947b653aa41f1919145095f051df3ddf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 4 Jul 2021 15:20:46 +0100 Subject: [PATCH 1079/2212] [spv-out] Load texture arguments ahead of time --- src/back/mod.rs | 10 +++++++ src/back/spv/block.rs | 50 ++++++++++++++------------------ src/back/spv/mod.rs | 13 +++++++-- src/back/spv/writer.rs | 35 ++++++++++++++-------- tests/out/spv/texture-arg.spvasm | 26 ++++++++--------- 5 files changed, 78 insertions(+), 56 deletions(-) diff --git a/src/back/mod.rs b/src/back/mod.rs index 09a18303f..51243a404 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -175,3 +175,13 @@ fn vector_size_str(size: crate::VectorSize) -> &'static str { crate::VectorSize::Quad => "4", } } + +impl crate::TypeInner { + #[allow(unused)] + fn is_handle(&self) -> bool { + match *self { + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => true, + _ => false, + } + } +} diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 90b8c7abe..7de235936 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -703,7 +703,7 @@ impl<'w> BlockContext<'w> { array_index, index, } => { - let image_id = self.get_image_id(block, image)?; + let image_id = self.get_image_id(image); let coordinate_id = self.write_texture_coordinates(coordinate, array_index, block)?; @@ -773,7 +773,7 @@ impl<'w> BlockContext<'w> { } => { use super::instructions::SampleLod; // image - let image_id = self.get_image_id(block, image)?; + let image_id = self.get_image_id(image); let image_type = self.fun_info[image].ty.handle().unwrap(); // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, // so we need to grab the first component out of it. @@ -800,7 +800,7 @@ impl<'w> BlockContext<'w> { let sampled_image_type_id = self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id }))?; - let sampler_id = self.get_image_id(block, sampler)?; + let sampler_id = self.get_image_id(sampler); let coordinate_id = self.write_texture_coordinates(coordinate, array_index, block)?; @@ -960,7 +960,7 @@ impl<'w> BlockContext<'w> { crate::Expression::ImageQuery { image, query } => { use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq}; - let image_id = self.get_image_id(block, image)?; + let image_id = self.get_image_id(image); let image_type = self.fun_info[image].ty.handle().unwrap(); let (dim, arrayed, class) = match self.ir_module.types[image_type].inner { crate::TypeInner::Image { @@ -1200,8 +1200,7 @@ impl<'w> BlockContext<'w> { break local_var.id; } crate::Expression::FunctionArgument(index) => { - let id = self.function.parameters[index as usize].result_id.unwrap(); - break id; + break self.function.parameter_id(index); } ref other => unimplemented!("Unexpected pointer expression {:?}", other), } @@ -1233,32 +1232,25 @@ impl<'w> BlockContext<'w> { Ok(pointer) } - fn get_image_id( - &mut self, - block: &mut Block, - expr_handle: Handle, - ) -> Result { - Ok(match self.ir_function.expressions[expr_handle] { + fn get_image_id(&mut self, expr_handle: Handle) -> Word { + let id = match self.ir_function.expressions[expr_handle] { crate::Expression::GlobalVariable(handle) => { - let id = self.writer.global_variables[handle.index()].handle_id; - if id == 0 { - unreachable!("Global variable {:?} doesn't have a handle ID", handle); - } - id + self.writer.global_variables[handle.index()].handle_id } crate::Expression::FunctionArgument(i) => { - let result_type_id = self.get_type_id(LookupType::Handle( - self.ir_function.arguments[i as usize].ty, - ))?; - let pointer_id = self.function.parameter_id(i); - let id = self.gen_id(); - block - .body - .push(Instruction::load(result_type_id, id, pointer_id, None)); - id + self.function.parameters[i as usize].handle_id } - ref other => unreachable!("Unexpected global expression {:?}", other), - }) + ref other => unreachable!("Unexpected image expression {:?}", other), + }; + + if id == 0 { + unreachable!( + "Image expression {:?} doesn't have a handle ID", + expr_handle + ); + } + + id } pub(super) fn write_block( @@ -1531,7 +1523,7 @@ impl<'w> BlockContext<'w> { array_index, value, } => { - let image_id = self.get_image_id(&mut block, image)?; + let image_id = self.get_image_id(image); let coordinate_id = self.write_texture_coordinates(coordinate, array_index, &mut block)?; let value_id = self.cached(value); diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 98cdbcf0c..952fb7204 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -125,7 +125,7 @@ struct EntryPointContext { #[derive(Default)] struct Function { signature: Option, - parameters: Vec, + parameters: Vec, variables: crate::FastHashMap, LocalVariable>, blocks: Vec, entry_point_context: Option, @@ -143,7 +143,10 @@ impl Function { fn parameter_id(&self, index: u32) -> Word { match self.entry_point_context { Some(ref context) => context.argument_ids[index as usize], - None => self.parameters[index as usize].result_id.unwrap(), + None => self.parameters[index as usize] + .instruction + .result_id + .unwrap(), } } } @@ -311,6 +314,12 @@ struct GlobalVariable { handle_id: Word, } +struct FunctionArgument { + /// Actual instruction of the argument. + instruction: Instruction, + handle_id: Word, +} + /// General information needed to emit SPIR-V for Naga statements. struct BlockContext<'w> { /// The writer handling the module to which this code belongs. diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e53ec6164..89e714659 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,9 +1,9 @@ use super::{ helpers::{contains_builtin, map_storage_class}, make_local, Block, BlockContext, CachedExpressions, EntryPointContext, Error, Function, - GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, LogicalLayout, - LookupFunctionType, LookupType, LoopContext, Options, PhysicalLayout, ResultMember, Writer, - WriterFlags, BITS_PER_BYTE, + FunctionArgument, GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, + LogicalLayout, LookupFunctionType, LookupType, LoopContext, Options, PhysicalLayout, + ResultMember, Writer, WriterFlags, BITS_PER_BYTE, }; use crate::{ arena::{Arena, Handle}, @@ -25,8 +25,8 @@ fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { impl Function { fn to_words(&self, sink: &mut impl Extend) { self.signature.as_ref().unwrap().to_words(sink); - for instruction in self.parameters.iter() { - instruction.to_words(sink); + for argument in self.parameters.iter() { + argument.instruction.to_words(sink); } for (index, block) in self.blocks.iter().enumerate() { Instruction::label(block.label_id).to_words(sink); @@ -269,10 +269,7 @@ impl Writer { let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); for argument in ir_function.arguments.iter() { let class = spirv::StorageClass::Input; - let handle_ty = match ir_module.types[argument.ty].inner { - crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => true, - _ => false, - }; + let handle_ty = ir_module.types[argument.ty].inner.is_handle(); let argument_type_id = match handle_ty { true => self.get_pointer_id( &ir_module.types, @@ -321,9 +318,23 @@ impl Writer { }; ep_context.argument_ids.push(id); } else { - let id = self.id_gen.next(); - let instruction = Instruction::function_parameter(argument_type_id, id); - function.parameters.push(instruction); + let argument_id = self.id_gen.next(); + let instruction = Instruction::function_parameter(argument_type_id, argument_id); + function.parameters.push(FunctionArgument { + instruction, + handle_id: if handle_ty { + let id = self.id_gen.next(); + prelude.body.push(Instruction::load( + self.get_type_id(LookupType::Handle(argument.ty))?, + id, + argument_id, + None, + )); + id + } else { + 0 + }, + }); parameter_type_ids.push(argument_type_id); }; } diff --git a/tests/out/spv/texture-arg.spvasm b/tests/out/spv/texture-arg.spvasm index 80a87f76f..12fd6965c 100644 --- a/tests/out/spv/texture-arg.spvasm +++ b/tests/out/spv/texture-arg.spvasm @@ -10,7 +10,7 @@ OpExecutionMode %28 OriginUpperLeft OpSource GLSL 450 OpName %9 "Texture" OpName %11 "Sampler" -OpName %16 "test" +OpName %18 "test" OpName %28 "main" OpDecorate %9 DescriptorSet 0 OpDecorate %9 Binding 0 @@ -28,22 +28,22 @@ OpDecorate %26 Location 0 %9 = OpVariable %10 UniformConstant %12 = OpTypePointer UniformConstant %6 %11 = OpVariable %12 UniformConstant -%17 = OpTypeFunction %7 %10 %12 -%21 = OpTypeSampledImage %5 +%19 = OpTypeFunction %7 %10 %12 +%22 = OpTypeSampledImage %5 %27 = OpTypePointer Output %7 %26 = OpVariable %27 Output %29 = OpTypeFunction %2 -%16 = OpFunction %7 None %17 +%18 = OpFunction %7 None %19 %14 = OpFunctionParameter %10 -%15 = OpFunctionParameter %12 +%16 = OpFunctionParameter %12 %13 = OpLabel -OpBranch %18 -%18 = OpLabel -%19 = OpCompositeConstruct %8 %3 %3 -%20 = OpLoad %5 %14 -%22 = OpLoad %6 %15 -%23 = OpSampledImage %21 %20 %22 -%24 = OpImageSampleImplicitLod %7 %23 %19 +%15 = OpLoad %5 %14 +%17 = OpLoad %6 %16 +OpBranch %20 +%20 = OpLabel +%21 = OpCompositeConstruct %8 %3 %3 +%23 = OpSampledImage %22 %15 %17 +%24 = OpImageSampleImplicitLod %7 %23 %21 OpReturnValue %24 OpFunctionEnd %28 = OpFunction %2 None %29 @@ -52,7 +52,7 @@ OpFunctionEnd %31 = OpLoad %6 %11 OpBranch %32 %32 = OpLabel -%33 = OpFunctionCall %7 %16 %9 %11 +%33 = OpFunctionCall %7 %18 %9 %11 OpStore %26 %33 OpReturn OpFunctionEnd \ No newline at end of file From 9192f7b882ab26b651ec2e010329b81d1d119138 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Mon, 5 Jul 2021 00:31:15 -0230 Subject: [PATCH 1080/2212] wgsl-in: add more error tests --- src/front/wgsl/lexer.rs | 2 +- src/front/wgsl/mod.rs | 138 +++++++++++------------- src/valid/type.rs | 2 +- tests/wgsl-errors.rs | 234 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 300 insertions(+), 76 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 015b7b99d..b1c3038c8 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -197,7 +197,7 @@ impl<'a> Lexer<'a> { (token, rest) } - fn current_byte_offset(&self) -> usize { + pub(super) fn current_byte_offset(&self) -> usize { self.source.len() - self.input.len() } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7e70a4dbc..861f1e417 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -88,84 +88,43 @@ pub enum ExpectedToken<'a> { StructAttribute, } -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug)] pub enum Error<'a> { - #[error("")] Unexpected(TokenSpan<'a>, ExpectedToken<'a>), - #[error("")] BadU32(Span, ParseIntError), - #[error("")] BadI32(Span, ParseIntError), - #[error("")] BadFloat(Span, ParseFloatError), - #[error("")] BadU32Constant(Span), - #[error("")] BadScalarWidth(Span, &'a str), - #[error("")] BadAccessor(Span), - #[error("")] BadTexture(Span), - #[error("")] BadTypeCast { span: Span, from_type: String, to_type: String, }, - #[error("")] BadTextureSampleType { span: Span, kind: crate::ScalarKind, width: u8, }, - #[error(transparent)] InvalidResolve(ResolveError), - #[error("")] InvalidForInitializer(Span), - #[error("")] UnknownStorageClass(Span), - #[error("")] UnknownAttribute(Span), - #[error("unknown scalar kind: `{0}`")] - UnknownScalarKind(&'a str), - #[error("unknown builtin")] UnknownBuiltin(Span), - #[error("unknown access: `{0}`")] - UnknownAccess(&'a str), - #[error("unknown shader stage")] + UnknownAccess(Span), UnknownShaderStage(Span), - #[error("unknown identifier: `{1}`")] UnknownIdent(Span, &'a str), - #[error("unknown scalar type")] UnknownScalarType(Span), - #[error("unknown type")] UnknownType(Span), - #[error("unknown function: `{0}`")] - UnknownFunction(&'a str), - #[error("unknown storage format")] UnknownStorageFormat(Span), - #[error("unknown conservative depth")] UnknownConservativeDepth(Span), - #[error("array stride must not be 0")] ZeroStride(Span), - #[error("struct member size or alignment must not be 0")] ZeroSizeOrAlign(Span), - #[error("not a composite type: {0:?}")] - NotCompositeType(Handle), - #[error("Input/output binding is not consistent: location {0:?}, built-in {1:?}, interpolation {2:?}, and sampling {3:?}")] - InconsistentBinding( - Option, - Option, - Option, - Option, - ), - #[error("call to local `{0}(..)` can't be resolved")] - UnknownLocalFunction(&'a str), - #[error("builtin {0:?} is not implemented")] - UnimplementedBuiltin(crate::BuiltIn), - #[error("expression {0} doesn't match its given type {1:?}")] - LetTypeMismatch(&'a str, Handle), - #[error("other error")] + InconsistentBinding(Span), + UnknownLocalFunction(Span), + LetTypeMismatch(Span, Handle), Other, } @@ -189,7 +148,7 @@ impl<'a> Error<'a> { Token::LogicalOperation(c) => format!("logical operation ('{}')", c), Token::ShiftOperation(c) => format!("bitshift ('{}{}')", c, c), Token::Arrow => "->".to_string(), - Token::Unknown(c) => format!("unkown ('{}')", c), + Token::Unknown(c) => format!("unknown ('{}')", c), Token::UnterminatedString => "unterminated string".to_string(), Token::Trivia => "trivia".to_string(), Token::End => "end".to_string(), @@ -297,6 +256,11 @@ impl<'a> Error<'a> { notes: vec![], } }, + Error::InvalidResolve(ref resolve_error) => ParseError { + message: resolve_error.to_string(), + labels: vec![], + notes: vec![], + }, Error::InvalidForInitializer(ref bad_span) => ParseError { message: format!("for(;;) initializer is not an assignment or a function call: '{}'", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "not an assignment or function call".into())], @@ -317,6 +281,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "unknown builtin".into())], notes: vec![], }, + Error::UnknownAccess(ref bad_span) => ParseError { + message: format!("unknown access: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown access".into())], + notes: vec![], + }, Error::UnknownShaderStage(ref bad_span) => ParseError { message: format!("unknown shader stage: '{}'", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "unknown shader stage".into())], @@ -347,9 +316,23 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "struct member size or alignment must not be 0".into())], notes: vec![], }, - - ref error => ParseError { - message: error.to_string(), + Error::InconsistentBinding(ref span) => ParseError { + message: "input/output binding is not consistent".to_string(), + labels: vec![(span.clone(), "input/output binding is not consistent".into())], + notes: vec![], + }, + Error::UnknownLocalFunction(ref span) => ParseError { + message: format!("unknown local function `{}`", &source[span.clone()]), + labels: vec![(span.clone(), "unknown local function".into())], + notes: vec![], + }, + Error::LetTypeMismatch(ref name_span, ref expected_ty) => ParseError { + message: format!("the type of `{}` is expected to be {:?}", &source[name_span.clone()], expected_ty), + labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], + notes: vec![], + }, + Error::Other => ParseError { + message: "other error".to_string(), labels: vec![], notes: vec![], }, @@ -897,7 +880,7 @@ impl BindingParser { Ok(()) } - fn finish<'a>(self) -> Result, Error<'a>> { + fn finish<'a>(self, span: Span) -> Result, Error<'a>> { match ( self.location, self.built_in, @@ -917,12 +900,7 @@ impl BindingParser { })) } (None, Some(bi), None, None) => Ok(Some(crate::Binding::BuiltIn(bi))), - (location, built_in, interpolation, sampling) => Err(Error::InconsistentBinding( - location, - built_in, - interpolation, - sampling, - )), + (_, _, _, _) => Err(Error::InconsistentBinding(span)), } } } @@ -1986,11 +1964,11 @@ impl Parser { lexer: &mut Lexer<'a>, type_arena: &mut Arena, const_arena: &mut Arena, - ) -> Result<(&'a str, Handle, crate::StorageAccess), Error<'a>> { - let name = lexer.next_ident()?; + ) -> Result<(&'a str, Span, Handle, crate::StorageAccess), Error<'a>> { + let (name, name_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(':'))?; let (ty, access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; - Ok((name, ty, access)) + Ok((name, name_span, ty, access)) } fn parse_variable_decl<'a>( @@ -2040,6 +2018,7 @@ impl Parser { lexer.expect(Token::Paren('{'))?; loop { let (mut size, mut align) = (None, None); + let bind_start = lexer.current_byte_offset(); let mut bind_parser = BindingParser::default(); if lexer.skip(Token::DoubleParen('[')) { self.scopes.push(Scope::Attribute); @@ -2089,6 +2068,8 @@ impl Parser { self.scopes.pop(); } + let bind_end = lexer.current_byte_offset(); + let name = match lexer.next() { (Token::Word(word), _) => word, (Token::Paren('}'), _) => { @@ -2110,7 +2091,7 @@ impl Parser { members.push(crate::StructMember { name: Some(name.to_owned()), ty, - binding: bind_parser.finish()?, + binding: bind_parser.finish(bind_start..bind_end)?, offset: range.start, }); } @@ -2453,11 +2434,12 @@ impl Parser { match lexer.next() { (Token::Word("access"), _) => { lexer.expect(Token::Paren('('))?; - attribute.access = match lexer.next_ident()? { + let (ident, span) = lexer.next_ident_with_span()?; + attribute.access = match ident { "read" => crate::StorageAccess::LOAD, "write" => crate::StorageAccess::STORE, "read_write" => crate::StorageAccess::all(), - other => return Err(Error::UnknownAccess(other)), + _ => return Err(Error::UnknownAccess(span)), }; lexer.expect(Token::Paren(')'))?; } @@ -2495,6 +2477,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, ident: &'a str, + ident_span: Span, mut context: ExpressionContext<'a, '_, 'out>, ) -> Result<(), Error<'a>> { context.emitter.start(context.expressions); @@ -2511,7 +2494,7 @@ impl Parser { None => { let (function, arguments) = self .parse_local_function_call(lexer, ident, context.reborrow())? - .ok_or(Error::UnknownLocalFunction(ident))?; + .ok_or(Error::UnknownLocalFunction(ident_span))?; crate::Statement::Call { function, arguments, @@ -2533,7 +2516,7 @@ impl Parser { block: &'out mut crate::Block, is_uniform_control_flow: bool, ) -> Result<(), Error<'a>> { - let word = match lexer.next() { + let (word, word_span) = match lexer.next() { (Token::Separator(';'), _) => return Ok(()), (Token::Paren('{'), _) => { self.scopes.push(Scope::Block); @@ -2550,7 +2533,7 @@ impl Parser { block.push(crate::Statement::Block(statements)); return Ok(()); } - (Token::Word(word), _) => word, + (Token::Word(word), span) => (word, span), other => return Err(Error::Unexpected(other, ExpectedToken::Statement)), }; @@ -2559,7 +2542,7 @@ impl Parser { match word { "let" => { emitter.start(context.expressions); - let name = lexer.next_ident()?; + let (name, name_span) = lexer.next_ident_with_span()?; let given_ty = if lexer.skip(Token::Separator(':')) { let (ty, _access) = self.parse_type_decl(lexer, None, context.types, context.constants)?; @@ -2584,7 +2567,7 @@ impl Parser { given_inner, expr_inner ); - return Err(Error::LetTypeMismatch(name, ty)); + return Err(Error::LetTypeMismatch(name_span, ty)); } } block.extend(emitter.finish(context.expressions)); @@ -2600,7 +2583,7 @@ impl Parser { Variable(Handle), } - let (name, ty, _access) = + let (name, _name_span, ty, _access) = self.parse_variable_ident_decl(lexer, context.types, context.constants)?; let init = if lexer.skip(Token::Operation('=')) { @@ -2833,10 +2816,11 @@ impl Parser { if let Token::Word(ident) = lexer.peek().0 { // manually parse the next statement here instead of calling parse_statement // because the statement is not terminated with a semicolon - let _ = lexer.next(); + let (_, ident_span) = lexer.next(); self.parse_statement_restricted( lexer, ident, + ident_span, context.as_expression(&mut continuing, &mut emitter), )?; } @@ -2902,6 +2886,7 @@ impl Parser { self.parse_statement_restricted( lexer, ident, + word_span, context.as_expression(block, &mut emitter), )?; lexer.expect(Token::Separator(';'))?; @@ -2936,6 +2921,8 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, ) -> Result, Error<'a>> { + let start = lexer.current_byte_offset(); + if !lexer.skip(Token::DoubleParen('[')) { return Ok(None); } @@ -2953,8 +2940,11 @@ impl Parser { other => return Err(Error::Unexpected(other, ExpectedToken::AttributeSeparator)), } } + + let end = lexer.current_byte_offset(); + self.scopes.pop(); - bind_parser.finish() + bind_parser.finish(start..end) } fn parse_function_decl<'a>( @@ -2985,7 +2975,7 @@ impl Parser { )); } let binding = self.parse_varying_binding(lexer)?; - let (param_name, param_type, _access) = + let (param_name, _param_name_span, param_type, _access) = self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; let param_index = arguments.len() as u32; let expression_token = @@ -3170,7 +3160,7 @@ impl Parser { lexer.expect(Token::Separator(';'))?; } (Token::Word("let"), _) => { - let (name, explicit_ty, _access) = self.parse_variable_ident_decl( + let (name, name_span, explicit_ty, _access) = self.parse_variable_ident_decl( lexer, &mut module.types, &mut module.constants, @@ -3196,7 +3186,7 @@ impl Parser { crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty, }; if !type_match { - return Err(Error::LetTypeMismatch(name, explicit_ty)); + return Err(Error::LetTypeMismatch(name_span, explicit_ty)); } //TODO: check `ty` against `const_handle`. lexer.expect(Token::Separator(';'))?; diff --git a/src/valid/type.rs b/src/valid/type.rs index e1f25af7b..f1ce40bce 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -241,7 +241,7 @@ impl super::Validator { // the type of an `AccessIndex` expression referring to a // dynamically sized array appearing as the final member of a // top-level `Struct`. But such pointers cannot be passed to - // functions, stored in varibles, etc. So, we mark them as not + // functions, stored in variables, etc. So, we mark them as not // `DATA`. let base_info = &self.types[base.index()]; let data_flag = if base_info.flags.contains(TypeFlags::SIZED) { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index ccb521c00..2c8086102 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -241,6 +241,240 @@ fn unknown_attribute() { ); } +#[test] +fn unknown_built_in() { + check( + r#" + fn x([[builtin(unknown_built_in)]] y: u32) {} + "#, + r#"error: unknown builtin: 'unknown_built_in' + ┌─ wgsl:2:28 + │ +2 │ fn x([[builtin(unknown_built_in)]] y: u32) {} + │ ^^^^^^^^^^^^^^^^ unknown builtin + +"# + ); +} + +#[test] +fn unknown_access() { + check( + r#" + var x: [[access(unknown_access)]] array; + "#, + r#"error: unknown access: 'unknown_access' + ┌─ wgsl:2:38 + │ +2 │ var x: [[access(unknown_access)]] array; + │ ^^^^^^^^^^^^^^ unknown access + +"# + ); +} + +#[test] +fn unknown_shader_stage() { + check( + r#" + [[stage(geometry)]] fn main() {} + "#, + r#"error: unknown shader stage: 'geometry' + ┌─ wgsl:2:21 + │ +2 │ [[stage(geometry)]] fn main() {} + │ ^^^^^^^^ unknown shader stage + +"# + ); +} + +#[test] +fn unknown_ident() { + check( + r#" + fn main() { + let a = b; + } + "#, + r#"error: no definition in scope for identifier: 'b' + ┌─ wgsl:3:25 + │ +3 │ let a = b; + │ ^ unknown identifier + +"# + ); +} + +#[test] +fn unknown_scalar_type() { + check( + r#" + let a: vec2; + "#, + r#"error: unknown scalar type: 'something' + ┌─ wgsl:2:25 + │ +2 │ let a: vec2; + │ ^^^^^^^^^ unknown scalar type + │ + = note: Valid scalar types are f16, f32, f64, i8, i16, i32, i64, u8, u16, u32, u64, bool + +"# + ); +} + +#[test] +fn unknown_type() { + check( + r#" + let a: Vec; + "#, + r#"error: unknown type: 'Vec' + ┌─ wgsl:2:20 + │ +2 │ let a: Vec; + │ ^^^ unknown type + +"# + ); +} + +#[test] +fn unknown_storage_format() { + check( + r#" + let storage: [[access(read)]] texture_storage_1d; + "#, + r#"error: unknown storage format: 'rgba' + ┌─ wgsl:2:62 + │ +2 │ let storage: [[access(read)]] texture_storage_1d; + │ ^^^^ unknown storage format + +"# + ); +} + +#[test] +fn unknown_conservative_depth() { + check( + r#" + [[early_depth_test(abc)]] fn main() {} + "#, + r#"error: unknown conservative depth: 'abc' + ┌─ wgsl:2:32 + │ +2 │ [[early_depth_test(abc)]] fn main() {} + │ ^^^ unknown conservative depth + +"# + ); +} + +#[test] +fn zero_array_stride() { + check( + r#" + type zero = [[stride(0)]] array; + "#, + r#"error: array stride must not be zero + ┌─ wgsl:2:34 + │ +2 │ type zero = [[stride(0)]] array; + │ ^ array stride must not be zero + +"# + ); +} + +#[test] +fn struct_member_zero_size() { + check( + r#" + struct Bar { + [[size(0)]] data: array; + }; + "#, + r#"error: struct member size or alignment must not be 0 + ┌─ wgsl:3:24 + │ +3 │ [[size(0)]] data: array; + │ ^ struct member size or alignment must not be 0 + +"# + ); +} + +#[test] +fn struct_member_zero_align() { + check( + r#" + struct Bar { + [[align(0)]] data: array; + }; + "#, + r#"error: struct member size or alignment must not be 0 + ┌─ wgsl:3:25 + │ +3 │ [[align(0)]] data: array; + │ ^ struct member size or alignment must not be 0 + +"# + ); +} + +#[test] +fn inconsistent_binding() { + check( + r#" + fn foo([[builtin(vertex_index), location(0)]] x: u32) {} + "#, + r#"error: input/output binding is not consistent + ┌─ wgsl:2:16 + │ +2 │ fn foo([[builtin(vertex_index), location(0)]] x: u32) {} + │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ input/output binding is not consistent + +"# + ); +} + +#[test] +fn unknown_local_function() { + check( + r#" + fn x() { + for (a();;) {} + } + "#, + r#"error: unknown local function `a` + ┌─ wgsl:3:22 + │ +3 │ for (a();;) {} + │ ^ unknown local function + +"#, + ); +} + +#[test] +fn let_type_mismatch() { + check( + r#" + let x: i32 = 1.0; + "#, + r#"error: the type of `x` is expected to be [1] + ┌─ wgsl:2:17 + │ +2 │ let x: i32 = 1.0; + │ ^ definition of `x` + +"#, + ); +} + macro_rules! check_validation_error { // We want to support an optional guard expression after the pattern, so // that we can check values we can't match against, like strings. From 988fc90b83076fdadfdae7d9c9ea5a85a7a1df3b Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Fri, 2 Jul 2021 21:15:44 +0300 Subject: [PATCH 1081/2212] [Makefile] Fix dxc params in validate-hlsl --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 3320d785c..85a139952 100644 --- a/Makefile +++ b/Makefile @@ -72,7 +72,7 @@ validate-hlsl: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl fragment="" \ compute="" \ . $${config}; \ - DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug;" \ + DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug"; \ [ ! -z "$${vertex}" ] && echo "Vertex Stage:" && dxc $${file} -T $${vertex} -E $${vertex_name} $${DXC_PARAMS} > /dev/null; \ [ ! -z "$${fragment}" ] && echo "Fragment Stage:" && dxc $${file} -T $${fragment} -E $${fragment_name} $${DXC_PARAMS} > /dev/null; \ [ ! -z "$${compute}" ] && echo "Compute Stage:" && dxc $${file} -T $${compute} -E $${compute_name} $${DXC_PARAMS} > /dev/null; \ From 2812acf8cda3b36ff6f96978247d60ba1bd9aa84 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 5 Jul 2021 13:53:57 +0300 Subject: [PATCH 1082/2212] [hlsl-out] Handle output semantic for shader stage --- src/back/hlsl/writer.rs | 60 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index e55194507..6da220c71 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -89,6 +89,13 @@ impl<'a, W: Write> Writer<'a, W> { } } + // Save all entry point output types + let ep_results = module + .entry_points + .iter() + .map(|ep| (ep.stage, ep.function.result.clone())) + .collect::)>>(); + // Write all structs for (handle, ty) in module.types.iter() { if let crate::TypeInner::Struct { @@ -97,7 +104,26 @@ impl<'a, W: Write> Writer<'a, W> { .. } = ty.inner { - self.write_struct(module, handle, top_level, members)?; + let ep_result = ep_results.iter().find(|e| { + if let Some(ref result) = e.1 { + result.ty == handle + } else { + false + } + }); + + if let Some(result) = ep_result { + self.write_struct( + module, + handle, + top_level, + members, + Some(result.0), + Some(true), + )?; + } else { + self.write_struct(module, handle, top_level, members, None, None)?; + } writeln!(self.out)?; } } @@ -170,13 +196,22 @@ impl<'a, W: Write> Writer<'a, W> { }) } - fn write_binding(&mut self, binding: &crate::Binding) -> BackendResult { + fn write_binding( + &mut self, + binding: &crate::Binding, + stage: Option, + output: Option, + ) -> BackendResult { match *binding { crate::Binding::BuiltIn(builtin) => { write!(self.out, " : {}", builtin_str(builtin))?; } crate::Binding::Location { location, .. } => { - write!(self.out, " : {}{}", LOCATION_SEMANTIC, location)?; + if stage == Some(crate::ShaderStage::Fragment) && output == Some(true) { + write!(self.out, " : SV_Target{}", location)?; + } else { + write!(self.out, " : {}{}", LOCATION_SEMANTIC, location)?; + } } } @@ -220,7 +255,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(module, member.ty)?; write!(self.out, " {}", &member.name)?; if let Some(ref binding) = member.binding { - self.write_binding(binding)?; + self.write_binding(binding, Some(stage), Some(false))?; } write!(self.out, ";")?; writeln!(self.out)?; @@ -370,6 +405,8 @@ impl<'a, W: Write> Writer<'a, W> { handle: Handle, _block: bool, members: &[crate::StructMember], + shader_stage: Option, + out: Option, ) -> BackendResult { // Write struct name write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?; @@ -415,7 +452,7 @@ impl<'a, W: Write> Writer<'a, W> { } if let Some(ref binding) = member.binding { - self.write_binding(binding)?; + self.write_binding(binding, shader_stage, out)?; }; write!(self.out, ";")?; writeln!(self.out)?; @@ -1160,6 +1197,19 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(module, value, func_ctx)?; write!(self.out, ".{})", number_of_components)? } + Expression::Select { + condition, + accept, + reject, + } => { + write!(self.out, "(")?; + self.write_expr(module, condition, func_ctx)?; + write!(self.out, " ? ")?; + self.write_expr(module, accept, func_ctx)?; + write!(self.out, " : ")?; + self.write_expr(module, reject, func_ctx)?; + write!(self.out, ")")? + } // Nothing to do here, since call expression already cached Expression::Call(_) => {} _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), From d5776879de579d84541316ef975eb2e7348d6cdf Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 5 Jul 2021 13:54:42 +0300 Subject: [PATCH 1083/2212] [hlsl-out] Enable interface snapshot testing --- tests/out/hlsl/interface.hlsl | 51 ++++++++++++++++++++++++++++ tests/out/hlsl/interface.hlsl.config | 6 ++++ tests/snapshots.rs | 5 ++- 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 tests/out/hlsl/interface.hlsl create mode 100644 tests/out/hlsl/interface.hlsl.config diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl new file mode 100644 index 000000000..6dc852d5f --- /dev/null +++ b/tests/out/hlsl/interface.hlsl @@ -0,0 +1,51 @@ +struct VertexOutput { + float4 position : SV_Position; + float varying : LOC1; +}; + +struct FragmentOutput { + float depth : SV_Depth; + uint sample_mask : SV_Coverage; + float color : SV_Target0; +}; + +struct VertexInput_vertex { + uint vertex_index1 : SV_VertexID; + uint instance_index1 : SV_InstanceID; + uint color1 : LOC10; +}; + +struct FragmentInput_fragment { + VertexOutput in2; + bool front_facing1 : SV_IsFrontFace; + uint sample_index1 : SV_SampleIndex; + uint sample_mask1 : SV_Coverage; +}; + +struct ComputeInput_compute { + uint3 global_id1 : SV_DispatchThreadID; + uint3 local_id1 : SV_GroupThreadID; + uint local_index1 : SV_GroupIndex; + uint3 wg_id1 : SV_GroupID; +}; + +VertexOutput vertex(VertexInput_vertex vertexinput_vertex) +{ + uint tmp = ((vertexinput_vertex.vertex_index1 + vertexinput_vertex.instance_index1) + vertexinput_vertex.color1); + const VertexOutput vertexoutput1 = { float4(1.0.xxxx), float(tmp) }; + return vertexoutput1; +} + +FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) +{ + uint mask = (fragmentinput_fragment.sample_mask1 & (1u << fragmentinput_fragment.sample_index1)); + float color2 = (fragmentinput_fragment.front_facing1 ? 0.0 : 1.0); + const FragmentOutput fragmentoutput1 = { fragmentinput_fragment.in2.varying, mask, color2 }; + return fragmentoutput1; +} + +[numthreads(1, 1, 1)] +void compute(ComputeInput_compute computeinput_compute) +{ + return; +} diff --git a/tests/out/hlsl/interface.hlsl.config b/tests/out/hlsl/interface.hlsl.config new file mode 100644 index 000000000..bd33fe9c2 --- /dev/null +++ b/tests/out/hlsl/interface.hlsl.config @@ -0,0 +1,6 @@ +vertex=vs_5_0 +vertex_name=vertex +fragment=ps_5_0 +fragment_name=fragment +compute=cs_5_0 +compute_name=compute diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b4950547c..c886d57ef 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -374,7 +374,10 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), //TODO: GLSL https://github.com/gfx-rs/naga/issues/874 - ("interface", Targets::SPIRV | Targets::METAL | Targets::WGSL), + ( + "interface", + Targets::SPIRV | Targets::METAL | Targets::HLSL | Targets::WGSL, + ), ( "globals", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, From 65fbbf110167cad463ddb1b563335bcb7ac18793 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 5 Jul 2021 16:35:48 +0300 Subject: [PATCH 1084/2212] [hlsl-out] Return only real names on entry point in ReflectionInfo --- src/back/hlsl/mod.rs | 5 ++--- src/back/hlsl/writer.rs | 2 +- tests/snapshots.rs | 8 ++++---- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 84802a4bd..424584442 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -50,11 +50,10 @@ impl Default for Options { /// Structure that contains a reflection info pub struct ReflectionInfo { - /// Information about all entry points (stage, name). - /// HLSL backend returns information about all entry points in shaders that will be allowed by the `hlsl` compiler. + /// Real name of entry point allowed by the `hlsl` compiler. /// For example: /// the entry point with the name `line` is valid for `wgsl`, but not valid for `hlsl`, because `line` is a reserved keyword. - pub entry_points: Vec<(crate::ShaderStage, String)>, + pub entry_points: Vec, // TODO: locations } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 6da220c71..f4c4e71fe 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -188,7 +188,7 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out)?; } - entry_points_info.push((ep.stage, name)) + entry_points_info.push(name); } Ok(super::ReflectionInfo { diff --git a/tests/snapshots.rs b/tests/snapshots.rs index c886d57ef..da2f86629 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -284,8 +284,8 @@ fn write_output_hlsl( // This file contains an info about profiles (shader stages) contains inside generated shader // This info will be passed to dxc let mut config_str = String::from(""); - for (stage, name) in reflection_info.entry_points.iter() { - let stage_str = match stage { + for (index, ep) in module.entry_points.iter().enumerate() { + let stage_str = match ep.stage { naga::ShaderStage::Vertex => "vertex", naga::ShaderStage::Fragment => "fragment", naga::ShaderStage::Compute => "compute", @@ -294,9 +294,9 @@ fn write_output_hlsl( "{}{}={}\n{}_name={}\n", config_str, stage_str, - options.shader_model.to_profile_string(*stage), + options.shader_model.to_profile_string(ep.stage), stage_str, - name + &reflection_info.entry_points[index] ); } fs::write( From beabd62d96f2fadac7ca599a5e76593c47a522eb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 5 Jul 2021 16:06:30 -0400 Subject: [PATCH 1085/2212] wgsl: type inference for local variables --- src/front/glsl/ast.rs | 4 +-- src/front/glsl/functions.rs | 26 ++++++-------- src/front/mod.rs | 8 +++++ src/front/wgsl/mod.rs | 71 +++++++++++++++++++++++++++++++------ src/front/wgsl/tests.rs | 2 ++ tests/wgsl-errors.rs | 30 ++++++++-------- 6 files changed, 99 insertions(+), 42 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 1247adcb1..ddeff5d5c 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -492,8 +492,8 @@ impl<'function> Context<'function> { Some(self.add_expression(Expression::Load { pointer }, body)), meta, )); - }, - _ => {}, + } + _ => {} } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 15d8ba753..a5b9c56c1 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,18 +1,14 @@ use crate::{ - proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, Function, - FunctionArgument, FunctionResult, Handle, ImageQuery, LocalVariable, MathFunction, - RelationalFunction, SampleLevel, ScalarKind, ScalarValue, Statement, StructMember, SwizzleComponent, Type, - TypeInner, VectorSize, + proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, + Expression, Function, FunctionArgument, FunctionResult, Handle, ImageQuery, LocalVariable, + MathFunction, RelationalFunction, SampleLevel, ScalarKind, ScalarValue, Statement, + StructMember, SwizzleComponent, Type, TypeInner, VectorSize, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; impl Program<'_> { - fn add_constant_value( - &mut self, - scalar_kind: ScalarKind, - value: u64, - ) -> Handle { + fn add_constant_value(&mut self, scalar_kind: ScalarKind, value: u64) -> Handle { let value = match scalar_kind { ScalarKind::Uint => ScalarValue::Uint(value), ScalarKind::Sint => ScalarValue::Sint(value as i64), @@ -23,10 +19,7 @@ impl Program<'_> { self.module.constants.fetch_or_append(Constant { name: None, specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value, - }, + inner: ConstantInner::Scalar { width: 4, value }, }) } @@ -49,13 +42,16 @@ impl Program<'_> { let expr_type = self.resolve_type(ctx, args[0].0, args[0].1)?; let vector_size = match *expr_type { - TypeInner::Vector{ size, .. } => Some(size), + TypeInner::Vector { size, .. } => Some(size), _ => None, }; // Special case: if casting from a bool, we need to use Select and not As. match self.module.types[ty].inner.scalar_kind() { - Some(result_scalar_kind) if expr_type.scalar_kind() == Some(ScalarKind::Bool) && result_scalar_kind != ScalarKind::Bool => { + Some(result_scalar_kind) + if expr_type.scalar_kind() == Some(ScalarKind::Bool) + && result_scalar_kind != ScalarKind::Bool => + { let c0 = self.add_constant_value(result_scalar_kind, 0u64); let c1 = self.add_constant_value(result_scalar_kind, 1u64); let mut reject = ctx.add_expression(Expression::Constant(c0), body); diff --git a/src/front/mod.rs b/src/front/mod.rs index 818159292..9989b2132 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -11,6 +11,7 @@ use crate::{ arena::{Arena, Handle}, proc::{ResolveContext, ResolveError, TypeResolution}, }; +use std::ops; /// Helper class to emit expressions #[allow(dead_code)] @@ -85,3 +86,10 @@ impl Typifier { Ok(()) } } + +impl ops::Index> for Typifier { + type Output = TypeResolution; + fn index(&self, handle: Handle) -> &Self::Output { + &self.resolutions[handle.index()] + } +} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 861f1e417..86b29dd0a 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -124,7 +124,8 @@ pub enum Error<'a> { ZeroSizeOrAlign(Span), InconsistentBinding(Span), UnknownLocalFunction(Span), - LetTypeMismatch(Span, Handle), + InitializationTypeMismatch(Span, Handle), + MissingType(Span), Other, } @@ -326,11 +327,16 @@ impl<'a> Error<'a> { labels: vec![(span.clone(), "unknown local function".into())], notes: vec![], }, - Error::LetTypeMismatch(ref name_span, ref expected_ty) => ParseError { + Error::InitializationTypeMismatch(ref name_span, ref expected_ty) => ParseError { message: format!("the type of `{}` is expected to be {:?}", &source[name_span.clone()], expected_ty), labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], notes: vec![], }, + Error::MissingType(ref name_span) => ParseError { + message: format!("variable `{}` needs a type", &source[name_span.clone()]), + labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], + notes: vec![], + }, Error::Other => ParseError { message: "other error".to_string(), labels: vec![], @@ -2567,7 +2573,7 @@ impl Parser { given_inner, expr_inner ); - return Err(Error::LetTypeMismatch(name_span, ty)); + return Err(Error::InitializationTypeMismatch(name_span, ty)); } } block.extend(emitter.finish(context.expressions)); @@ -2583,24 +2589,69 @@ impl Parser { Variable(Handle), } - let (name, _name_span, ty, _access) = - self.parse_variable_ident_decl(lexer, context.types, context.constants)?; + let (name, name_span) = lexer.next_ident_with_span()?; + let given_ty = if lexer.skip(Token::Separator(':')) { + let (ty, _access) = + self.parse_type_decl(lexer, None, context.types, context.constants)?; + Some(ty) + } else { + None + }; - let init = if lexer.skip(Token::Operation('=')) { + let (init, ty) = if lexer.skip(Token::Operation('=')) { emitter.start(context.expressions); let value = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), )?; block.extend(emitter.finish(context.expressions)); - match context.expressions[value] { + + // prepare the typifier, but work around mutable borrowing... + let _ = context + .as_expression(block, &mut emitter) + .resolve_type(value)?; + + //TODO: share more of this code with `let` arm + let ty = match given_ty { + Some(ty) => { + let expr_inner = context.typifier.get(value, context.types); + let given_inner = &context.types[ty].inner; + if given_inner != expr_inner { + log::error!( + "Given type {:?} doesn't match expected {:?}", + given_inner, + expr_inner + ); + return Err(Error::InitializationTypeMismatch(name_span, ty)); + } + ty + } + None => { + // register the type, if needed + match context.typifier[value].clone() { + TypeResolution::Handle(ty) => ty, + TypeResolution::Value(inner) => context + .types + .fetch_or_append(crate::Type { name: None, inner }), + } + } + }; + + let init = match context.expressions[value] { crate::Expression::Constant(handle) if is_uniform_control_flow => { Init::Constant(handle) } _ => Init::Variable(value), - } + }; + (init, ty) } else { - Init::Empty + match given_ty { + Some(ty) => (Init::Empty, ty), + None => { + log::error!("Variable '{}' without an initializer needs a type", name); + return Err(Error::MissingType(name_span)); + } + } }; lexer.expect(Token::Separator(';'))?; @@ -3186,7 +3237,7 @@ impl Parser { crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty, }; if !type_match { - return Err(Error::LetTypeMismatch(name_span, explicit_ty)); + return Err(Error::InitializationTypeMismatch(name_span, explicit_ty)); } //TODO: check `ty` against `const_handle`. lexer.expect(Token::Separator(';'))?; diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index a537c62d1..b1c7a1232 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -32,6 +32,8 @@ fn parse_type_inference() { fn foo() { let a = 2u; let b: u32 = a; + var x = 3f32; + var y = vec2(1, 2); }", ) .unwrap(); diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 2c8086102..0f87c70be 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -146,7 +146,7 @@ fn bad_texture() { 7 │ return textureSample(a, sampler, vec2(0.0)); │ ^ not an image -"# +"#, ); } @@ -186,7 +186,7 @@ fn bad_texture_sample_type() { 3 │ [[group(0), binding(1)]] var texture : texture_2d; │ ^^^^ must be one of f32, i32 or u32 -"# +"#, ); } @@ -237,7 +237,7 @@ fn unknown_attribute() { 2 │ [[a]] │ ^ unknown attribute -"# +"#, ); } @@ -253,7 +253,7 @@ fn unknown_built_in() { 2 │ fn x([[builtin(unknown_built_in)]] y: u32) {} │ ^^^^^^^^^^^^^^^^ unknown builtin -"# +"#, ); } @@ -269,7 +269,7 @@ fn unknown_access() { 2 │ var x: [[access(unknown_access)]] array; │ ^^^^^^^^^^^^^^ unknown access -"# +"#, ); } @@ -285,7 +285,7 @@ fn unknown_shader_stage() { 2 │ [[stage(geometry)]] fn main() {} │ ^^^^^^^^ unknown shader stage -"# +"#, ); } @@ -303,7 +303,7 @@ fn unknown_ident() { 3 │ let a = b; │ ^ unknown identifier -"# +"#, ); } @@ -321,7 +321,7 @@ fn unknown_scalar_type() { │ = note: Valid scalar types are f16, f32, f64, i8, i16, i32, i64, u8, u16, u32, u64, bool -"# +"#, ); } @@ -337,7 +337,7 @@ fn unknown_type() { 2 │ let a: Vec; │ ^^^ unknown type -"# +"#, ); } @@ -353,7 +353,7 @@ fn unknown_storage_format() { 2 │ let storage: [[access(read)]] texture_storage_1d; │ ^^^^ unknown storage format -"# +"#, ); } @@ -369,7 +369,7 @@ fn unknown_conservative_depth() { 2 │ [[early_depth_test(abc)]] fn main() {} │ ^^^ unknown conservative depth -"# +"#, ); } @@ -385,7 +385,7 @@ fn zero_array_stride() { 2 │ type zero = [[stride(0)]] array; │ ^ array stride must not be zero -"# +"#, ); } @@ -403,7 +403,7 @@ fn struct_member_zero_size() { 3 │ [[size(0)]] data: array; │ ^ struct member size or alignment must not be 0 -"# +"#, ); } @@ -421,7 +421,7 @@ fn struct_member_zero_align() { 3 │ [[align(0)]] data: array; │ ^ struct member size or alignment must not be 0 -"# +"#, ); } @@ -437,7 +437,7 @@ fn inconsistent_binding() { 2 │ fn foo([[builtin(vertex_index), location(0)]] x: u32) {} │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ input/output binding is not consistent -"# +"#, ); } From c69736210a2a9692e1924dee49a873a14aa9425a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 6 Jul 2021 01:16:15 -0400 Subject: [PATCH 1086/2212] Snapshot test local variable inference --- tests/in/access.wgsl | 4 ++-- tests/in/boids.wgsl | 10 +++++----- tests/in/collatz.wgsl | 2 +- tests/in/shadow.wgsl | 2 +- tests/in/skybox.wgsl | 4 ++-- tests/wgsl-errors.rs | 36 ++++++++++++++++++++++++++++++++++++ 6 files changed, 47 insertions(+), 11 deletions(-) diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 551812d1d..e6cd5552a 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -21,8 +21,8 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let a = bar.data[arrayLength(&bar.data) - 2u]; - var c: array = array(a, i32(b), 3, 4, 5); - c[vi + 1u] = 42; + var c = array(a, i32(b), 3, 4, 5); + c[vi + 1u] = 42; let value = c[vi]; return vec4(vec4(value)); diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index dc5bd7ea3..baec5dd12 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -33,12 +33,12 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id : vec3) { return; } - var vPos : vec2 = particlesSrc.particles[index].pos; - var vVel : vec2 = particlesSrc.particles[index].vel; + var vPos = particlesSrc.particles[index].pos; + var vVel = particlesSrc.particles[index].vel; - var cMass : vec2 = vec2(0.0, 0.0); - var cVel : vec2 = vec2(0.0, 0.0); - var colVel : vec2 = vec2(0.0, 0.0); + var cMass = vec2(0.0, 0.0); + var cVel = vec2(0.0, 0.0); + var colVel = vec2(0.0, 0.0); var cMassCount : i32 = 0; var cVelCount : i32 = 0; diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index 4d2168f46..b291809df 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -13,7 +13,7 @@ var v_indices: [[access(read_write)]] PrimeIndices; // Though the conjecture has not been proven, no counterexample has ever been found. // This function returns how many times this recurrence needs to be applied to reach 1. fn collatz_iterations(n_base: u32) -> u32 { - var n: u32 = n_base; + var n = n_base; var i: u32 = 0u; loop { if (n <= 1u) { diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 89780ea6e..61fca8578 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -43,7 +43,7 @@ fn fs_main( ) -> [[location(0)]] vec4 { let normal: vec3 = normalize(raw_normal); // accumulate color - var color: vec3 = c_ambient; + var color = c_ambient; var i: u32 = 0u; loop { if (i >= min(u_globals.num_lights.x, c_max_lights)) { diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index 96d0e1cee..0c00ebf72 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -14,8 +14,8 @@ var r_data: Data; [[stage(vertex)]] fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { // hacky way to draw a large triangle - var tmp1: i32 = i32(vertex_index) / 2; - var tmp2: i32 = i32(vertex_index) & 1; + var tmp1 = i32(vertex_index) / 2; + var tmp2 = i32(vertex_index) & 1; let pos = vec4( f32(tmp1) * 4.0 - 1.0, f32(tmp2) * 4.0 - 1.0, diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 0f87c70be..86dfd1c16 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -475,6 +475,42 @@ fn let_type_mismatch() { ); } +#[test] +fn local_var_type_mismatch() { + check( + r#" + fn foo() { + var x: f32 = 1; + } + "#, + r#"error: the type of `x` is expected to be [1] + ┌─ wgsl:3:21 + │ +3 │ var x: f32 = 1; + │ ^ definition of `x` + +"#, + ); +} + +#[test] +fn local_var_missing_type() { + check( + r#" + fn foo() { + var x; + } + "#, + r#"error: variable `x` needs a type + ┌─ wgsl:3:21 + │ +3 │ var x; + │ ^ definition of `x` + +"#, + ); +} + macro_rules! check_validation_error { // We want to support an optional guard expression after the pattern, so // that we can check values we can't match against, like strings. From 9473340c161214fdd6aa363c7e553b6166d62d34 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 6 Jul 2021 02:17:18 -0400 Subject: [PATCH 1087/2212] wgsl-in: fix auto array stride --- src/front/wgsl/mod.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 86b29dd0a..dea23906e 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2233,7 +2233,11 @@ impl Parser { lexer.expect_generic_paren('>')?; let stride = match attribute.stride { Some(stride) => stride.get(), - None => type_arena[base].inner.span(const_arena), + None => { + self.layouter.update(type_arena, const_arena).unwrap(); + let layout = &self.layouter[base]; + Layouter::round_up(layout.alignment, layout.size) + } }; crate::TypeInner::Array { base, size, stride } From 2b475ecc9626107ef9fb4f2acb6d64188407e3fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 6 Jul 2021 10:43:22 +0100 Subject: [PATCH 1088/2212] [spv-out] Support object-wise select --- src/back/spv/block.rs | 35 ++++++- tests/in/operators.wgsl | 9 ++ tests/out/glsl/operators.main.Compute.glsl | 8 ++ tests/out/glsl/operators.main.Fragment.glsl | 35 +++++++ tests/out/hlsl/operators.hlsl | 9 ++ tests/out/msl/operators.msl | 9 ++ tests/out/spv/operators.spvasm | 102 +++++++++++--------- tests/out/wgsl/operators.wgsl | 8 ++ 8 files changed, 170 insertions(+), 45 deletions(-) create mode 100644 tests/out/glsl/operators.main.Fragment.glsl diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 7de235936..f45203076 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -933,10 +933,43 @@ impl<'w> BlockContext<'w> { reject, } => { let id = self.gen_id(); - let condition_id = self.cached(condition); + let mut condition_id = self.cached(condition); let accept_id = self.cached(accept); let reject_id = self.cached(reject); + let condition_ty = self.fun_info[condition] + .ty + .inner_with(&self.ir_module.types); + let object_ty = self.fun_info[accept].ty.inner_with(&self.ir_module.types); + + if let ( + &crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width, + }, + &crate::TypeInner::Vector { size, .. }, + ) = (condition_ty, object_ty) + { + self.temp_list.clear(); + self.temp_list.resize(size as usize, condition_id); + + let bool_vector_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind: crate::ScalarKind::Bool, + width, + pointer_class: None, + }))?; + + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + bool_vector_type_id, + id, + &self.temp_list, + )); + condition_id = id + } + let instruction = Instruction::select(result_type_id, id, condition_id, accept_id, reject_id); block.body.push(instruction); diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index cb6da5df0..9bbf9ba67 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -9,8 +9,17 @@ fn unary() -> i32 { if (!true) { return a; } else { return ~a; }; } +fn selection() -> vec4 { + let vector1 = vec4(1.0); + let vector2 = vec4(1.0); + let condition = true; + let a = select(0, 1, condition); + return select(vector1, vector2, condition); +} + [[stage(compute), workgroup_size(1)]] fn main() { let a = splat(); let b = unary(); + let c = selection(); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index caad84e6a..232cd4c06 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -19,9 +19,17 @@ int unary() { } } +vec4 selection() { + vec4 vector1_ = vec4(1.0); + vec4 vector2_ = vec4(1.0); + int a = (true ? 0 : 1); + return (true ? vector1_ : vector2_); +} + void main() { vec4 _expr0 = splat(); int _expr1 = unary(); + vec4 _expr2 = selection(); return; } diff --git a/tests/out/glsl/operators.main.Fragment.glsl b/tests/out/glsl/operators.main.Fragment.glsl new file mode 100644 index 000000000..0c1eaa482 --- /dev/null +++ b/tests/out/glsl/operators.main.Fragment.glsl @@ -0,0 +1,35 @@ +#version 310 es + +precision highp float; + +layout(location = 0) out vec4 _fs2p_location0; + +vec4 splat() { + vec2 a = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + ivec4 b = (ivec4(5) % ivec4(2)); + return (a.xyxy + vec4(b)); +} + +int unary() { + if ((! true)) { + return 1; + } else { + return (~ 1); + } +} + +int unary1() { + if ((! true)) { + return 1; + } else { + return (~ 1); + } +} + +void main() { + vec4 vector1_ = vec4(1.0); + vec4 vector2_ = vec4(1.0); + _fs2p_location0 = (true ? vector1_ : vector2_); + return; +} + diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 2448e11c4..b582a4452 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -14,10 +14,19 @@ int unary() } } +float4 selection() +{ + float4 vector1_ = float4(1.0.xxxx); + float4 vector2_ = float4(1.0.xxxx); + int a = (true ? 0 : 1); + return (true ? vector1_ : vector2_); +} + [numthreads(1, 1, 1)] void main() { const float4 _e0 = splat(); const int _e1 = unary(); + const float4 _e2 = selection(); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 3749cb47c..9fd7f3b4a 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -18,9 +18,18 @@ int unary( } } +metal::float4 selection( +) { + metal::float4 vector1_ = metal::float4(1.0); + metal::float4 vector2_ = metal::float4(1.0); + int a = true ? 0 : 1; + return true ? vector1_ : vector2_; +} + kernel void main1( ) { metal::float4 _e0 = splat(); int _e1 = unary(); + metal::float4 _e2 = selection(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index aefe1c99f..f84503609 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 50 +; Bound: 61 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %45 "main" -OpExecutionMode %45 LocalSize 1 1 1 +OpEntryPoint GLCompute %55 "main" +OpExecutionMode %55 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -19,52 +19,66 @@ OpExecutionMode %45 LocalSize 1 1 1 %11 = OpConstant %9 1 %13 = OpTypeBool %12 = OpConstantTrue %13 -%14 = OpTypeVector %4 4 -%17 = OpTypeFunction %14 -%19 = OpTypeVector %4 2 -%27 = OpTypeVector %9 4 -%36 = OpTypeFunction %9 -%43 = OpConstantNull %9 -%46 = OpTypeFunction %2 -%16 = OpFunction %14 None %17 -%15 = OpLabel -OpBranch %18 -%18 = OpLabel -%20 = OpCompositeConstruct %19 %5 %5 -%21 = OpCompositeConstruct %19 %3 %3 -%22 = OpFAdd %19 %21 %20 -%23 = OpCompositeConstruct %19 %6 %6 -%24 = OpFSub %19 %22 %23 -%25 = OpCompositeConstruct %19 %7 %7 -%26 = OpFDiv %19 %24 %25 -%28 = OpCompositeConstruct %27 %8 %8 %8 %8 -%29 = OpCompositeConstruct %27 %10 %10 %10 %10 -%30 = OpSMod %27 %28 %29 -%31 = OpVectorShuffle %14 %26 %26 0 1 0 1 -%32 = OpConvertSToF %14 %30 -%33 = OpFAdd %14 %31 %32 -OpReturnValue %33 +%14 = OpConstant %9 0 +%15 = OpTypeVector %4 4 +%18 = OpTypeFunction %15 +%20 = OpTypeVector %4 2 +%28 = OpTypeVector %9 4 +%37 = OpTypeFunction %9 +%44 = OpConstantNull %9 +%52 = OpTypeVector %13 4 +%56 = OpTypeFunction %2 +%17 = OpFunction %15 None %18 +%16 = OpLabel +OpBranch %19 +%19 = OpLabel +%21 = OpCompositeConstruct %20 %5 %5 +%22 = OpCompositeConstruct %20 %3 %3 +%23 = OpFAdd %20 %22 %21 +%24 = OpCompositeConstruct %20 %6 %6 +%25 = OpFSub %20 %23 %24 +%26 = OpCompositeConstruct %20 %7 %7 +%27 = OpFDiv %20 %25 %26 +%29 = OpCompositeConstruct %28 %8 %8 %8 %8 +%30 = OpCompositeConstruct %28 %10 %10 %10 %10 +%31 = OpSMod %28 %29 %30 +%32 = OpVectorShuffle %15 %27 %27 0 1 0 1 +%33 = OpConvertSToF %15 %31 +%34 = OpFAdd %15 %32 %33 +OpReturnValue %34 OpFunctionEnd -%35 = OpFunction %9 None %36 -%34 = OpLabel -OpBranch %37 -%37 = OpLabel -%38 = OpLogicalNot %13 %12 -OpSelectionMerge %39 None -OpBranchConditional %38 %40 %41 -%40 = OpLabel -OpReturnValue %11 +%36 = OpFunction %9 None %37 +%35 = OpLabel +OpBranch %38 +%38 = OpLabel +%39 = OpLogicalNot %13 %12 +OpSelectionMerge %40 None +OpBranchConditional %39 %41 %42 %41 = OpLabel -%42 = OpNot %9 %11 -OpReturnValue %42 -%39 = OpLabel +OpReturnValue %11 +%42 = OpLabel +%43 = OpNot %9 %11 OpReturnValue %43 +%40 = OpLabel +OpReturnValue %44 OpFunctionEnd -%45 = OpFunction %2 None %46 -%44 = OpLabel +%46 = OpFunction %15 None %18 +%45 = OpLabel OpBranch %47 %47 = OpLabel -%48 = OpFunctionCall %14 %16 -%49 = OpFunctionCall %9 %35 +%48 = OpCompositeConstruct %15 %3 %3 %3 %3 +%49 = OpCompositeConstruct %15 %3 %3 %3 %3 +%50 = OpSelect %9 %12 %14 %11 +%53 = OpCompositeConstruct %52 %12 %12 %12 %12 +%51 = OpSelect %15 %53 %48 %49 +OpReturnValue %51 +OpFunctionEnd +%55 = OpFunction %2 None %56 +%54 = OpLabel +OpBranch %57 +%57 = OpLabel +%58 = OpFunctionCall %15 %17 +%59 = OpFunctionCall %9 %36 +%60 = OpFunctionCall %15 %46 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 06e3ca1dc..bbd3c9086 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -12,9 +12,17 @@ fn unary() -> i32 { } } +fn selection() -> vec4 { + let vector1_: vec4 = vec4(1.0); + let vector2_: vec4 = vec4(1.0); + let a: i32 = select(0, 1, true); + return select(vector1_, vector2_, true); +} + [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { let _e0: vec4 = splat(); let _e1: i32 = unary(); + let _e2: vec4 = selection(); return; } From 7bced3f4e8f773d3d953573920e6085077f45f31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 6 Jul 2021 15:58:45 +0100 Subject: [PATCH 1089/2212] [glsl-in] Add support for all texture types --- src/front/glsl/functions.rs | 16 ++++++++- src/front/glsl/types.rs | 68 +++++++++++++++++++++++++++++-------- 2 files changed, 69 insertions(+), 15 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index a5b9c56c1..c2b1036df 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -189,7 +189,21 @@ impl Program<'_> { } FunctionCallKind::Function(name) => { match name.as_str() { - "sampler2D" => { + "sampler1D" + | "sampler1DArray" + | "sampler2D" + | "sampler2DArray" + | "sampler2DMS" + | "sampler2DMSArray" + | "sampler3D" + | "samplerCube" + | "samplerCubeArray" + | "sampler1DShadow" + | "sampler1DArrayShadow" + | "sampler2DShadow" + | "sampler2DArrayShadow" + | "samplerCubeShadow" + | "samplerCubeArrayShadow" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index ed3ec3649..2b038242d 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,4 +1,4 @@ -use crate::{ScalarKind, Type, TypeInner, VectorSize}; +use crate::{ImageClass, ImageDimension, ScalarKind, Type, TypeInner, VectorSize}; pub fn parse_type(type_name: &str) -> Option { match type_name { @@ -37,21 +37,12 @@ pub fn parse_type(type_name: &str) -> Option { width: 4, }, }), - "texture2D" => Some(Type { + "sampler" | "samplerShadow" => Some(Type { name: None, - inner: TypeInner::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Sampled { - kind: ScalarKind::Float, - multi: false, - }, + inner: TypeInner::Sampler { + comparison: type_name == "samplerShadow", }, }), - "sampler" => Some(Type { - name: None, - inner: TypeInner::Sampler { comparison: false }, - }), word => { fn kind_width_parse(ty: &str) -> Option<(ScalarKind, u8)> { Some(match ty { @@ -114,7 +105,56 @@ pub fn parse_type(type_name: &str) -> Option { }) }; - vec_parse(word).or_else(|| mat_parse(word)) + let texture_parse = |word: &str| { + let mut iter = word.split("texture"); + + let texture_kind = |ty| { + Some(match ty { + "" => ScalarKind::Float, + "i" => ScalarKind::Sint, + "u" => ScalarKind::Uint, + _ => return None, + }) + }; + + let kind = iter.next()?; + let size = iter.next()?; + let kind = texture_kind(kind)?; + + let sampled = |multi| ImageClass::Sampled { kind, multi }; + + let (dim, arrayed, class) = match size { + "1D" => (ImageDimension::D1, false, sampled(false)), + "1DArray" => (ImageDimension::D1, false, sampled(false)), + "2D" => (ImageDimension::D2, false, sampled(false)), + "2DArray" => (ImageDimension::D2, false, sampled(false)), + "2DMS" => (ImageDimension::D2, true, sampled(true)), + "2DMSArray" => (ImageDimension::D2, true, sampled(true)), + "3D" => (ImageDimension::D3, false, sampled(false)), + "Cube" => (ImageDimension::Cube, false, sampled(false)), + "CubeArray" => (ImageDimension::D2, false, sampled(false)), + "1DShadow" => (ImageDimension::D1, false, ImageClass::Depth), + "1DArrayShadow" => (ImageDimension::D1, true, ImageClass::Depth), + "2DShadow" => (ImageDimension::D2, false, ImageClass::Depth), + "2DArrayShadow" => (ImageDimension::D2, true, ImageClass::Depth), + "CubeShadow" => (ImageDimension::Cube, false, ImageClass::Depth), + "CubeArrayShadow" => (ImageDimension::Cube, true, ImageClass::Depth), + _ => return None, + }; + + Some(Type { + name: None, + inner: TypeInner::Image { + dim, + arrayed, + class, + }, + }) + }; + + vec_parse(word) + .or_else(|| mat_parse(word)) + .or_else(|| texture_parse(word)) } } } From ee343b30176494215199a0a1310940544fc99b5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 6 Jul 2021 16:04:00 +0100 Subject: [PATCH 1090/2212] [glsl-in] Implicit splat max builtin --- src/front/glsl/functions.rs | 39 ++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index c2b1036df..42ac28a6a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -445,8 +445,42 @@ impl Program<'_> { body, ))) } - "pow" | "dot" | "max" | "min" | "reflect" | "cross" | "outerProduct" - | "distance" | "step" | "modf" | "frexp" | "ldexp" => { + "max" => { + if args.len() != 2 { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + + let (mut arg0, arg0_meta) = args[0]; + let (mut arg1, arg1_meta) = args[1]; + + let arg0_size = match *self.resolve_type(ctx, arg0, arg0_meta)? { + TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + let arg1_size = match *self.resolve_type(ctx, arg1, arg1_meta)? { + TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + + ctx.binary_implicit_conversion( + self, &mut arg0, arg0_meta, &mut arg1, arg1_meta, + )?; + + ctx.implicit_splat(self, &mut arg0, arg0_meta, arg1_size)?; + ctx.implicit_splat(self, &mut arg1, arg1_meta, arg0_size)?; + + Ok(Some(ctx.add_expression( + Expression::Math { + fun: MathFunction::Max, + arg: arg0, + arg1: Some(arg1), + arg2: None, + }, + body, + ))) + } + "pow" | "dot" | "min" | "reflect" | "cross" | "outerProduct" | "distance" + | "step" | "modf" | "frexp" | "ldexp" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } @@ -463,7 +497,6 @@ impl Program<'_> { fun: match name.as_str() { "pow" => MathFunction::Pow, "dot" => MathFunction::Dot, - "max" => MathFunction::Max, "min" => MathFunction::Min, "reflect" => MathFunction::Reflect, "cross" => MathFunction::Cross, From ee1004d4434862e3500122b9b5260d99c8ce7a74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 6 Jul 2021 16:08:13 +0100 Subject: [PATCH 1091/2212] [glsl-in] Use cast for implicit conversion Previously this was a bitcast --- src/front/glsl/ast.rs | 53 ++++++++++++-------- src/front/glsl/functions.rs | 29 ++++++++--- src/front/glsl/parser.rs | 15 ++++-- tests/out/wgsl/246-collatz-comp.wgsl | 3 +- tests/out/wgsl/constant-array-size-vert.wgsl | 3 +- 5 files changed, 65 insertions(+), 38 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index ddeff5d5c..306bf1795 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -644,16 +644,10 @@ impl<'function> Context<'function> { let (pointer, ptr_meta) = self.lower_expect(program, tgt, true, body)?; let (mut value, value_meta) = self.lower_expect(program, value, false, body)?; - let ptr_kind = match *program.resolve_type(self, pointer, ptr_meta)? { - TypeInner::Pointer { base, .. } => { - program.module.types[base].inner.scalar_kind() - } - TypeInner::ValuePointer { kind, .. } => Some(kind), - ref ty => ty.scalar_kind(), - }; + let scalar_components = self.expr_scalar_components(program, pointer, ptr_meta)?; - if let Some(kind) = ptr_kind { - self.implicit_conversion(program, &mut value, value_meta, kind)?; + if let Some((kind, width)) = scalar_components { + self.implicit_conversion(program, &mut value, value_meta, kind, width)?; } if let Expression::Swizzle { @@ -808,13 +802,14 @@ impl<'function> Context<'function> { Ok((Some(handle), meta)) } - pub fn expr_scalar_kind( + pub fn expr_scalar_components( &mut self, program: &mut Program, expr: Handle, meta: SourceMetadata, - ) -> Result, ErrorKind> { - Ok(program.resolve_type(self, expr, meta)?.scalar_kind()) + ) -> Result, ErrorKind> { + let ty = program.resolve_type(self, expr, meta)?; + Ok(scalar_components(ty)) } pub fn expr_power( @@ -824,8 +819,8 @@ impl<'function> Context<'function> { meta: SourceMetadata, ) -> Result, ErrorKind> { Ok(self - .expr_scalar_kind(program, expr, meta)? - .and_then(type_power)) + .expr_scalar_components(program, expr, meta)? + .and_then(|(kind, _)| type_power(kind))) } pub fn get_expression(&self, expr: Handle) -> &Expression { @@ -838,6 +833,7 @@ impl<'function> Context<'function> { expr: &mut Handle, meta: SourceMetadata, kind: ScalarKind, + width: crate::Bytes, ) -> Result<(), ErrorKind> { if let (Some(tgt_power), Some(expr_power)) = (type_power(kind), self.expr_power(program, *expr, meta)?) @@ -846,7 +842,7 @@ impl<'function> Context<'function> { *expr = self.expressions.append(Expression::As { expr: *expr, kind, - convert: None, + convert: Some(width), }) } } @@ -862,19 +858,22 @@ impl<'function> Context<'function> { right: &mut Handle, right_meta: SourceMetadata, ) -> Result<(), ErrorKind> { - let left_kind = self.expr_scalar_kind(program, *left, left_meta)?; - let right_kind = self.expr_scalar_kind(program, *right, right_meta)?; + let left_components = self.expr_scalar_components(program, *left, left_meta)?; + let right_components = self.expr_scalar_components(program, *right, right_meta)?; - if let (Some((left_power, left_kind)), Some((right_power, right_kind))) = ( - left_kind.and_then(|kind| Some((type_power(kind)?, kind))), - right_kind.and_then(|kind| Some((type_power(kind)?, kind))), + if let ( + Some((left_power, left_width, left_kind)), + Some((right_power, right_width, right_kind)), + ) = ( + left_components.and_then(|(kind, width)| Some((type_power(kind)?, width, kind))), + right_components.and_then(|(kind, width)| Some((type_power(kind)?, width, kind))), ) { match left_power.cmp(&right_power) { std::cmp::Ordering::Less => { *left = self.expressions.append(Expression::As { expr: *left, kind: right_kind, - convert: None, + convert: Some(right_width), }) } std::cmp::Ordering::Equal => {} @@ -882,7 +881,7 @@ impl<'function> Context<'function> { *right = self.expressions.append(Expression::As { expr: *right, kind: left_kind, - convert: None, + convert: Some(left_width), }) } } @@ -910,6 +909,16 @@ impl<'function> Context<'function> { } } +pub fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, crate::Bytes)> { + match *ty { + TypeInner::Scalar { kind, width } => Some((kind, width)), + TypeInner::Vector { kind, width, .. } => Some((kind, width)), + TypeInner::Matrix { width, .. } => Some((ScalarKind::Float, width)), + TypeInner::ValuePointer { kind, width, .. } => Some((kind, width)), + _ => None, + } +} + pub fn type_power(kind: ScalarKind) -> Option { Some(match kind { ScalarKind::Sint => 0, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 42ac28a6a..b40a5fd33 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -75,9 +75,9 @@ impl Program<'_> { } match self.module.types[ty].inner { - TypeInner::Vector { size, kind, .. } if vector_size.is_none() => { + TypeInner::Vector { size, kind, width } if vector_size.is_none() => { let (mut value, meta) = args[0]; - ctx.implicit_conversion(self, &mut value, meta, kind)?; + ctx.implicit_conversion(self, &mut value, meta, kind, width)?; ctx.add_expression(Expression::Splat { size, value }, body) } @@ -108,13 +108,23 @@ impl Program<'_> { body, ) } - TypeInner::Matrix { columns, rows, .. } => { + TypeInner::Matrix { + columns, + rows, + width, + } => { // TODO: casts // `Expression::As` doesn't support matrix width // casts so we need to do some extra work for casts let (mut value, meta) = args[0]; - ctx.implicit_conversion(self, &mut value, meta, ScalarKind::Float)?; + ctx.implicit_conversion( + self, + &mut value, + meta, + ScalarKind::Float, + width, + )?; let column = match *self.resolve_type(ctx, args[0].0, args[0].1)? { TypeInner::Scalar { .. } => ctx .add_expression(Expression::Splat { size: rows, value }, body), @@ -176,8 +186,9 @@ impl Program<'_> { let mut components = Vec::with_capacity(args.len()); for (mut arg, meta) in args.iter().copied() { - if let Some(kind) = self.module.types[ty].inner.scalar_kind() { - ctx.implicit_conversion(self, &mut arg, meta, kind)?; + let scalar_components = scalar_components(&self.module.types[ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; } components.push(arg) } @@ -773,8 +784,10 @@ impl Program<'_> { } } - if let Some(kind) = self.module.types[*parameter].inner.scalar_kind() { - ctx.implicit_conversion(self, &mut handle, meta, kind)?; + let scalar_components = + scalar_components(&self.module.types[*parameter].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut handle, meta, kind, width)?; } arguments.push(handle) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index bb30e9bb2..8e0a8d045 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,6 +1,6 @@ use super::{ ast::{ - Context, FunctionCall, FunctionCallKind, GlobalLookup, GlobalLookupKind, HirExpr, + self, Context, FunctionCall, FunctionCallKind, GlobalLookup, GlobalLookupKind, HirExpr, HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier, }, error::ErrorKind, @@ -591,9 +591,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { .map::, _>(|_| { let (mut expr, init_meta) = self.parse_initializer(ty, ctx.ctx, ctx.body)?; - if let Some(kind) = self.program.module.types[ty].inner.scalar_kind() { - ctx.ctx - .implicit_conversion(self.program, &mut expr, init_meta, kind)?; + let scalar_components = + ast::scalar_components(&self.program.module.types[ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.ctx.implicit_conversion( + self.program, + &mut expr, + init_meta, + kind, + width, + )?; } meta = meta.union(&init_meta); diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 08d58c28a..0b1410dc9 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -9,11 +9,10 @@ var gl_GlobalInvocationID: vec3; fn collatz_iterations(n: u32) -> u32 { var n1: u32; - var i: u32; + var i: u32 = 0u; var local: u32; n1 = n; - i = u32(0); loop { let _e7: u32 = n1; if (!((_e7 != u32(1)))) { diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 96c2472e1..5a7aba0ab 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -7,11 +7,10 @@ struct Data { var global: Data; fn function() -> vec4 { - var sum: vec4; + var sum: vec4 = vec4(0.0, 0.0, 0.0, 0.0); var i: i32 = 0; var local: i32; - sum = vec4(f32(0)); loop { let _e9: i32 = i; if (!((_e9 < 42))) { From e8bb7f2503f40f0f892d9973eaf4017746af98f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 6 Jul 2021 16:09:50 +0100 Subject: [PATCH 1092/2212] [glsl-in] Parse array initializers --- src/front/glsl/parser.rs | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 8e0a8d045..4029551fd 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1118,15 +1118,49 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { TokenValue::TypeName(_) => { let Token { value, mut meta } = self.bump()?; - let handle = if let TokenValue::TypeName(ty) = value { + let mut handle = if let TokenValue::TypeName(ty) = value { self.program.module.types.fetch_or_append(ty) } else { unreachable!() }; + let maybe_size = self.parse_array_specifier()?; + self.expect(TokenValue::LeftParen)?; let args = self.parse_function_call_args(ctx, body, &mut meta)?; + if let Some(array_size) = maybe_size { + let stride = self.program.module.types[handle] + .inner + .span(&self.program.module.constants); + + let size = match array_size { + ArraySize::Constant(size) => ArraySize::Constant(size), + ArraySize::Dynamic => { + let constant = + self.program.module.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(args.len() as i64), + }, + }); + + ArraySize::Constant(constant) + } + }; + + handle = self.program.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: handle, + size, + stride, + }, + }) + } + ctx.hir_exprs.append(HirExpr { kind: HirExprKind::Call(FunctionCall { kind: FunctionCallKind::TypeConstructor(handle), From a818b2e0896a00dc021acaad19d3e080dc3eee2f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 21 Jun 2021 21:25:13 -0700 Subject: [PATCH 1093/2212] Document `Loop`, `Break`, and `Continue` statements. --- src/lib.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 1efbfeaa0..67d53cac8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1125,16 +1125,65 @@ pub enum Statement { cases: Vec, default: Block, }, + /// Executes a block repeatedly. + /// + /// Each iteration of the loop executes the `body` block, followed by the + /// `continuing` block. + /// + /// Executing a [`Break`], [`Return`] or [`Kill`] statement exits the loop. + /// + /// A [`Continue`] statement in `body` jumps to the `continuing` block. The + /// `continuing` block is meant to be used to represent structures like the + /// third expression of a C-style `for` loop head, to which `continue` + /// statements in the loop's body jump. + /// + /// The `continuing` block and its substatements must not contain `Return` + /// or `Kill` statements, or any `Break` or `Continue` statements targeting + /// this loop. (It may have `Break` and `Continue` statements targeting + /// loops or switches nested within the `continuing` block.) + /// + /// [`Break`]: Statement::Break + /// [`Continue`]: Statement::Continue + /// [`Kill`]: Statement::Kill + /// [`Return`]: Statement::Return Loop { body: Block, continuing: Block }, - /// Exits the loop. + + /// Exits the innermost enclosing [`Loop`] or [`Switch`]. + /// + /// A `Break` statement may only appear within a [`Loop`] or [`Switch`] + /// statement. It may not break out of a [`Loop`] from within the loop's + /// `continuing` block. + /// + /// [`Loop`]: Statement::Loop + /// [`Switch`]: Statement::Switch Break, - /// Skips execution to the next iteration of the loop. + + /// Skips to the `continuing` block of the innermost enclosing [`Loop`]. + /// + /// A `Continue` statement may only appear within the `body` block of the + /// innermost enclosing [`Loop`] statement. It must not appear within that + /// loop's `continuing` block. + /// + /// [`Loop`]: Statement::Loop Continue, + /// Returns from the function (possibly with a value). + /// + /// `Return` statements are forbidden within the `continuing` block of a + /// [`Loop`] statement. + /// + /// [`Loop`]: Statement::Loop Return { value: Option> }, + /// Aborts the current shader execution. + /// + /// `Kill` statements are forbidden within the `continuing` block of a + /// [`Loop`] statement. + /// + /// [`Loop`]: Statement::Loop Kill, + /// Synchronize invocations within the work group. /// The `Barrier` flags control which memory accesses should be synchronized. /// If empty, this becomes purely an execution barrier. From 562af2877316b5eb4cdb246acdbb5b453b31bb70 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 6 Jul 2021 11:13:28 -0700 Subject: [PATCH 1094/2212] [spv-out] Move cached expression table to BlockContext. Since the table of cached expressions is only meaningful within a single function, it's really something that should only be accessed from `BlockContext`. However, to save heap allocations, it makes sense to retain it in the `Writer` between functions. But the `Writer` field should have a different name, to ensure people don't use it by accident. --- src/back/spv/block.rs | 6 +++--- src/back/spv/mod.rs | 19 +++++++++++++++++-- src/back/spv/writer.rs | 16 +++++++++++----- 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index f45203076..37d5ebfd8 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -197,7 +197,7 @@ impl<'w> BlockContext<'w> { // The chain rule: if this `Access...`'s `base` operand was // previously omitted, then omit this one, too. - _ => self.writer.cached.ids[expr_handle.index()] == 0, + _ => self.cached.ids[expr_handle.index()] == 0, } } @@ -1150,7 +1150,7 @@ impl<'w> BlockContext<'w> { crate::Expression::ArrayLength(expr) => self.write_runtime_array_length(expr, block)?, }; - self.writer.cached[expr_handle] = id; + self.cached[expr_handle] = id; Ok(()) } @@ -1578,7 +1578,7 @@ impl<'w> BlockContext<'w> { let type_id = match result { Some(expr) => { - self.writer.cached[expr] = id; + self.cached[expr] = id; self.writer.lookup_function_call.insert(expr, id); let ty_handle = self.ir_module.functions[local_function] .result diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 952fb7204..ffbbf1000 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -268,6 +268,14 @@ enum Dimension { Matrix, } +/// A map from evaluated [`Expression`s] to their SPIR-V ids. +/// +/// When we emit code to evaluate a given `Expression`, we record the +/// SPIR-V id of its value here, under its `Handle` index. +/// +/// A `CachedExpressions` value can be indexed by a `Handle` value. +/// +/// [emit]: index.html#expression-evaluation-time-and-scope #[derive(Default)] struct CachedExpressions { ids: Vec, @@ -338,6 +346,9 @@ struct BlockContext<'w> { /// The [`back::spv::Function`] to which we are contributing SPIR-V instructions. function: &'w mut Function, + /// SPIR-V ids for expressions we've evaluated. + cached: CachedExpressions, + /// The `Writer`'s temporary vector, for convenience. temp_list: Vec, } @@ -357,7 +368,7 @@ impl BlockContext<'_> { } fn cached(&self, expression: Handle) -> Word { - self.writer.cached[expression] + self.cached[expression] } } @@ -386,7 +397,11 @@ pub struct Writer { constant_ids: Vec, cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>, global_variables: Vec, - cached: CachedExpressions, + + // Cached expressions are only meaningful within a BlockContext, but we + // retain the table here between functions to save heap allocations. + saved_cached: CachedExpressions, + gl450_ext_inst_id: Word, // Just a temporary list of SPIR-V ids temp_list: Vec, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 89e714659..8346e8f42 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -82,7 +82,7 @@ impl Writer { constant_ids: Vec::new(), cached_constants: crate::FastHashMap::default(), global_variables: Vec::new(), - cached: CachedExpressions::default(), + saved_cached: CachedExpressions::default(), gl450_ext_inst_id, temp_list: Vec::new(), }) @@ -131,7 +131,7 @@ impl Writer { constant_ids: take(&mut self.constant_ids).recycle(), cached_constants: take(&mut self.cached_constants).recycle(), global_variables: take(&mut self.global_variables).recycle(), - cached: take(&mut self.cached).recycle(), + saved_cached: take(&mut self.saved_cached).recycle(), temp_list: take(&mut self.temp_list).recycle(), }; @@ -429,13 +429,16 @@ impl Writer { ir_function, fun_info: info, function: &mut function, + // Re-use the cached expression table from prior functions. + cached: std::mem::take(&mut self.saved_cached), + // Steal the Writer's temp list for a bit. temp_list: std::mem::take(&mut self.temp_list), writer: self, }; // fill up the pre-emitted expressions - context.writer.cached.reset(ir_function.expressions.len()); + context.cached.reset(ir_function.expressions.len()); for (handle, expr) in ir_function.expressions.iter() { if expr.needs_pre_emit() { context.cache_expression_value(handle, &mut prelude)?; @@ -449,8 +452,11 @@ impl Writer { context.write_block(main_id, &ir_function.body, None, LoopContext::default())?; // Consume the `BlockContext`, ending its borrows and letting the - // `Writer` steal back its temp_list. - let BlockContext { temp_list, .. } = context; + // `Writer` steal back its cached expression table and temp_list. + let BlockContext { + cached, temp_list, .. + } = context; + self.saved_cached = cached; self.temp_list = temp_list; function.to_words(&mut self.logical_layout.function_definitions); From 918183162ff609ac66f849064c1ed255f3c7687a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 6 Jul 2021 11:18:49 -0700 Subject: [PATCH 1095/2212] [spv-out]: Access `BlockContext::cached` directly. Since `BlockContext` now owns the `cached` table directly, there's no point in going through a helper function. --- src/back/spv/block.rs | 64 +++++++++++++++++++++---------------------- src/back/spv/index.rs | 10 +++---- src/back/spv/mod.rs | 4 --- 3 files changed, 37 insertions(+), 41 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 37d5ebfd8..8cc958557 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -96,7 +96,7 @@ impl<'w> BlockContext<'w> { array_index: Option>, block: &mut Block, ) -> Result { - let coordinate_id = self.cached(coordinates); + let coordinate_id = self.cached[coordinates]; Ok(if let Some(array_index) = array_index { let coordinate_scalar_type_id = @@ -144,7 +144,7 @@ impl<'w> BlockContext<'w> { let array_index_f32_id = self.gen_id(); constituent_ids[size as usize - 1] = array_index_f32_id; - let array_index_u32_id = self.cached(array_index); + let array_index_u32_id = self.cached[array_index]; let cast_instruction = Instruction::unary( spirv::Op::ConvertUToF, coordinate_scalar_type_id, @@ -245,7 +245,7 @@ impl<'w> BlockContext<'w> { | crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { let id = self.gen_id(); - let base_id = self.cached(base); + let base_id = self.cached[base]; block.body.push(Instruction::composite_extract( result_type_id, id, @@ -265,7 +265,7 @@ impl<'w> BlockContext<'w> { } crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], crate::Expression::Splat { size, value } => { - let value_id = self.cached(value); + let value_id = self.cached[value]; self.temp_list.clear(); self.temp_list.resize(size as usize, value_id); @@ -282,7 +282,7 @@ impl<'w> BlockContext<'w> { vector, pattern, } => { - let vector_id = self.cached(vector); + let vector_id = self.cached[vector]; self.temp_list.clear(); for &sc in pattern[..size as usize].iter() { self.temp_list.push(sc as Word); @@ -303,7 +303,7 @@ impl<'w> BlockContext<'w> { } => { self.temp_list.clear(); for &component in components { - self.temp_list.push(self.cached(component)); + self.temp_list.push(self.cached[component]); } let id = self.gen_id(); @@ -316,7 +316,7 @@ impl<'w> BlockContext<'w> { } crate::Expression::Unary { op, expr } => { let id = self.gen_id(); - let expr_id = self.cached(expr); + let expr_id = self.cached[expr]; let expr_ty_inner = self.fun_info[expr].ty.inner_with(&self.ir_module.types); let spirv_op = match op { @@ -342,8 +342,8 @@ impl<'w> BlockContext<'w> { } crate::Expression::Binary { op, left, right } => { let id = self.gen_id(); - let left_id = self.cached(left); - let right_id = self.cached(right); + let left_id = self.cached[left]; + let right_id = self.cached[right]; let left_ty_inner = self.fun_info[left].ty.inner_with(&self.ir_module.types); let right_ty_inner = self.fun_info[right].ty.inner_with(&self.ir_module.types); @@ -480,17 +480,17 @@ impl<'w> BlockContext<'w> { Custom(Instruction), } - let arg0_id = self.cached(arg); + let arg0_id = self.cached[arg]; let arg_scalar_kind = self.fun_info[arg] .ty .inner_with(&self.ir_module.types) .scalar_kind(); let arg1_id = match arg1 { - Some(handle) => self.cached(handle), + Some(handle) => self.cached[handle], None => 0, }; let arg2_id = match arg2 { - Some(handle) => self.cached(handle), + Some(handle) => self.cached[handle], None => 0, }; @@ -657,7 +657,7 @@ impl<'w> BlockContext<'w> { } => { use crate::ScalarKind as Sk; - let expr_id = self.cached(expr); + let expr_id = self.cached[expr]; let (src_kind, src_width) = match *self.fun_info[expr].ty.inner_with(&self.ir_module.types) { crate::TypeInner::Scalar { kind, width } @@ -734,7 +734,7 @@ impl<'w> BlockContext<'w> { }; if let Some(index) = index { - let index_id = self.cached(index); + let index_id = self.cached[index]; let image_ops = match *self.fun_info[image].ty.inner_with(&self.ir_module.types) { crate::TypeInner::Image { @@ -813,7 +813,7 @@ impl<'w> BlockContext<'w> { )); let id = self.gen_id(); - let depth_id = depth_ref.map(|handle| self.cached(handle)); + let depth_id = depth_ref.map(|handle| self.cached[handle]); let mut mask = spirv::ImageOperands::empty(); mask.set(spirv::ImageOperands::CONST_OFFSET, offset.is_some()); @@ -862,7 +862,7 @@ impl<'w> BlockContext<'w> { depth_id, ); - let lod_id = self.cached(lod_handle); + let lod_id = self.cached[lod_handle]; mask |= spirv::ImageOperands::LOD; inst.add_operand(mask.bits()); inst.add_operand(lod_id); @@ -879,7 +879,7 @@ impl<'w> BlockContext<'w> { depth_id, ); - let bias_id = self.cached(bias_handle); + let bias_id = self.cached[bias_handle]; mask |= spirv::ImageOperands::BIAS; inst.add_operand(mask.bits()); inst.add_operand(bias_id); @@ -896,8 +896,8 @@ impl<'w> BlockContext<'w> { depth_id, ); - let x_id = self.cached(x); - let y_id = self.cached(y); + let x_id = self.cached[x]; + let y_id = self.cached[y]; mask |= spirv::ImageOperands::GRAD; inst.add_operand(mask.bits()); inst.add_operand(x_id); @@ -933,9 +933,9 @@ impl<'w> BlockContext<'w> { reject, } => { let id = self.gen_id(); - let mut condition_id = self.cached(condition); - let accept_id = self.cached(accept); - let reject_id = self.cached(reject); + let mut condition_id = self.cached[condition]; + let accept_id = self.cached[accept]; + let reject_id = self.cached[reject]; let condition_ty = self.fun_info[condition] .ty @@ -979,7 +979,7 @@ impl<'w> BlockContext<'w> { use crate::DerivativeAxis as Da; let id = self.gen_id(); - let expr_id = self.cached(expr); + let expr_id = self.cached[expr]; let op = match axis { Da::X => spirv::Op::DPdx, Da::Y => spirv::Op::DPdy, @@ -1035,7 +1035,7 @@ impl<'w> BlockContext<'w> { Ic::Storage(_) => (spirv::Op::ImageQuerySize, None), _ => { let level_id = match level { - Some(expr) => self.cached(expr), + Some(expr) => self.cached[expr], None => self.get_index_constant(0)?, }; (spirv::Op::ImageQuerySizeLod, Some(level_id)) @@ -1130,7 +1130,7 @@ impl<'w> BlockContext<'w> { } crate::Expression::Relational { fun, argument } => { use crate::RelationalFunction as Rf; - let arg_id = self.cached(argument); + let arg_id = self.cached[argument]; let op = match fun { Rf::All => spirv::Op::All, Rf::Any => spirv::Op::Any, @@ -1212,7 +1212,7 @@ impl<'w> BlockContext<'w> { } // Either way, the index to use is unchanged. - self.cached(index) + self.cached[index] } }; self.temp_list.push(index_id); @@ -1316,7 +1316,7 @@ impl<'w> BlockContext<'w> { ref accept, ref reject, } => { - let condition_id = self.cached(condition); + let condition_id = self.cached[condition]; let merge_id = self.gen_id(); block.body.push(Instruction::selection_merge( @@ -1358,7 +1358,7 @@ impl<'w> BlockContext<'w> { ref cases, ref default, } => { - let selector_id = self.cached(selector); + let selector_id = self.cached[selector]; let merge_id = self.gen_id(); block.body.push(Instruction::selection_merge( @@ -1458,7 +1458,7 @@ impl<'w> BlockContext<'w> { return Ok(()); } crate::Statement::Return { value: Some(value) } => { - let value_id = self.cached(value); + let value_id = self.cached[value]; let instruction = match self.function.entry_point_context { // If this is an entry point, and we need to return anything, // let's instead store the output variables and return `void`. @@ -1509,7 +1509,7 @@ impl<'w> BlockContext<'w> { )); } crate::Statement::Store { pointer, value } => { - let value_id = self.cached(value); + let value_id = self.cached[value]; match self.write_expression_pointer(pointer, &mut block)? { ExpressionPointer::Ready { pointer_id } => { block @@ -1559,7 +1559,7 @@ impl<'w> BlockContext<'w> { let image_id = self.get_image_id(image); let coordinate_id = self.write_texture_coordinates(coordinate, array_index, &mut block)?; - let value_id = self.cached(value); + let value_id = self.cached[value]; block .body @@ -1573,7 +1573,7 @@ impl<'w> BlockContext<'w> { let id = self.gen_id(); self.temp_list.clear(); for &argument in arguments { - self.temp_list.push(self.cached(argument)); + self.temp_list.push(self.cached[argument]); } let type_id = match result { diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 2de9994e5..85662136d 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -177,7 +177,7 @@ impl<'w> BlockContext<'w> { index: Handle, block: &mut Block, ) -> Result { - let index_id = self.cached(index); + let index_id = self.cached[index]; // Get the sequence's maximum valid index. Return early if we've already // done the bounds check. @@ -237,7 +237,7 @@ impl<'w> BlockContext<'w> { index: Handle, block: &mut Block, ) -> Result { - let index_id = self.cached(index); + let index_id = self.cached[index]; // Get the sequence's length. Return early if we've already done the // bounds check. @@ -367,7 +367,7 @@ impl<'w> BlockContext<'w> { self.write_index_comparison(base, index, block)? } IndexBoundsCheckPolicy::UndefinedBehavior => { - BoundsCheckResult::Computed(self.cached(index)) + BoundsCheckResult::Computed(self.cached[index]) } }) } @@ -384,8 +384,8 @@ impl<'w> BlockContext<'w> { ) -> Result { let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty)?; - let base_id = self.cached(base); - let index_id = self.cached(index); + let base_id = self.cached[base]; + let index_id = self.cached[index]; let result_id = match self.write_bounds_check(base, index, block)? { BoundsCheckResult::KnownInBounds(known_index) => { diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index ffbbf1000..0dcb97567 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -366,10 +366,6 @@ impl BlockContext<'_> { self.writer .get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) } - - fn cached(&self, expression: Handle) -> Word { - self.cached[expression] - } } #[derive(Clone, Copy, Default)] From 9e613906261c0466fa961efe7600c7e7254ba7b4 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 6 Jul 2021 01:30:04 +0300 Subject: [PATCH 1096/2212] [hlsl-out] Zero initialize variables. Write interpolation and sampling qualifier --- src/back/hlsl/writer.rs | 114 ++++++++++++++++++++----- tests/out/hlsl/interface.hlsl | 2 +- tests/out/hlsl/interpolate.hlsl | 36 ++++++++ tests/out/hlsl/interpolate.hlsl.config | 4 + tests/out/hlsl/quad-vert.hlsl | 8 +- tests/out/hlsl/quad.hlsl | 2 +- tests/snapshots.rs | 2 +- 7 files changed, 138 insertions(+), 30 deletions(-) create mode 100644 tests/out/hlsl/interpolate.hlsl create mode 100644 tests/out/hlsl/interpolate.hlsl.config diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index f4c4e71fe..2e8ca079c 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -49,7 +49,7 @@ impl<'a, W: Write> Writer<'a, W> { names: crate::FastHashMap::default(), namer: proc::Namer::default(), options, - ep_inputs: Vec::with_capacity(3), + ep_inputs: Vec::new(), named_expressions: crate::NamedExpressions::default(), } } @@ -139,8 +139,8 @@ impl<'a, W: Write> Writer<'a, W> { } // Write all entry points wrapped structs - for (index, ep) in module.entry_points.iter().enumerate() { - self.write_ep_input_struct(module, &ep.function, ep.stage, &ep.name, index)?; + for ep in module.entry_points.iter() { + self.write_ep_input_struct(module, &ep.function, ep.stage, &ep.name)?; } // Write all regular functions @@ -196,7 +196,7 @@ impl<'a, W: Write> Writer<'a, W> { }) } - fn write_binding( + fn write_semantic( &mut self, binding: &crate::Binding, stage: Option, @@ -224,7 +224,6 @@ impl<'a, W: Write> Writer<'a, W> { func: &crate::Function, stage: ShaderStage, entry_point_name: &str, - index: usize, ) -> BackendResult { if !func.arguments.is_empty() { let struct_name_prefix = match stage { @@ -255,7 +254,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(module, member.ty)?; write!(self.out, " {}", &member.name)?; if let Some(ref binding) = member.binding { - self.write_binding(binding, Some(stage), Some(false))?; + self.write_semantic(binding, Some(stage), Some(false))?; } write!(self.out, ";")?; writeln!(self.out)?; @@ -272,7 +271,9 @@ impl<'a, W: Write> Writer<'a, W> { members, }; - self.ep_inputs.insert(index, Some(ep_input)); + self.ep_inputs.push(Some(ep_input)); + } else { + self.ep_inputs.push(None); } Ok(()) @@ -289,6 +290,10 @@ impl<'a, W: Write> Writer<'a, W> { let global = &module.global_variables[handle]; let inner = &module.types[global.ty].inner; + if let Some(storage_access) = storage_access(global.storage_access) { + write!(self.out, "{} ", storage_access)?; + } + let (storage_class, register_ty) = match *inner { TypeInner::Image { .. } => ("", "t"), TypeInner::Sampler { .. } => ("", "s"), @@ -311,9 +316,11 @@ impl<'a, W: Write> Writer<'a, W> { if let Some(ref binding) = global.binding { writeln!(self.out, " : register({}{});", register_ty, binding.binding)?; } else { + write!(self.out, " = ")?; if let Some(init) = global.init { - write!(self.out, " = ")?; self.write_constant(module, init)?; + } else { + self.write_default_init(module, global.ty)?; } writeln!(self.out, ";")?; } @@ -441,6 +448,24 @@ impl<'a, W: Write> Writer<'a, W> { self.write_array_size(module, size)?; } _ => { + // Write interpolation modifier before type + if let Some(crate::Binding::Location { + interpolation, + sampling, + .. + }) = member.binding + { + if let Some(interpolation) = interpolation { + write!(self.out, "{} ", interpolation_str(interpolation))? + } + + if let Some(sampling) = sampling { + if let Some(str) = sampling_str(sampling) { + write!(self.out, "{} ", str)? + } + } + } + // Write the member type and name self.write_type(module, member.ty)?; write!( @@ -452,7 +477,7 @@ impl<'a, W: Write> Writer<'a, W> { } if let Some(ref binding) = member.binding { - self.write_binding(binding, shader_stage, out)?; + self.write_semantic(binding, shader_stage, out)?; }; write!(self.out, ";")?; writeln!(self.out)?; @@ -623,16 +648,8 @@ impl<'a, W: Write> Writer<'a, W> { }; if let Some(ref result) = func.result { if let Some(ref binding) = result.binding { - match *binding { - crate::Binding::BuiltIn(builtin) => { - write!(self.out, " : {}", builtin_str(builtin))?; - } - crate::Binding::Location { location, .. } => { - if stage == Some(ShaderStage::Fragment) { - write!(self.out, " : SV_Target{}", location)?; - } - } - } + let output = stage.is_some(); + self.write_semantic(binding, stage, Some(output))?; } } @@ -649,15 +666,18 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(module, local.ty)?; write!(self.out, " {}", self.names[&func_ctx.name_key(handle)])?; + write!(self.out, " = ")?; // Write the local initializer if needed if let Some(init) = local.init { // Put the equal signal only if there's a initializer // The leading and trailing spaces aren't needed but help with readability - write!(self.out, " = ")?; // Write the constant // `write_constant` adds no trailing or leading space/newline self.write_constant(module, init)?; + } else { + // Zero initialize local variables + self.write_default_init(module, local.ty)?; } // Finish the local with `;` and add a newline (only for readability) @@ -783,7 +803,7 @@ impl<'a, W: Write> Writer<'a, W> { variable_name )?; self.write_expr(module, expr, func_ctx)?; - writeln!(self.out)?; + writeln!(self.out, ";")?; writeln!( self.out, "{}return {};", @@ -904,7 +924,7 @@ impl<'a, W: Write> Writer<'a, W> { } } if is_struct { - write!(self.out, " }};")? + write!(self.out, " }}")? } else { write!(self.out, ")")? } @@ -993,7 +1013,6 @@ impl<'a, W: Write> Writer<'a, W> { level: _, // TODO: depth_ref: _, // TODO: } => { - // TODO: others self.write_expr(module, image, func_ctx)?; write!(self.out, ".Sample(")?; self.write_expr(module, sampler, func_ctx)?; @@ -1331,6 +1350,15 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + + /// Helper function that write default zero initialization + fn write_default_init(&mut self, module: &Module, ty: Handle) -> BackendResult { + write!(self.out, "(")?; + self.write_type(module, ty)?; + write!(self.out, ")0")?; + + Ok(()) + } } fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { @@ -1388,3 +1416,43 @@ fn scalar_kind_str(kind: crate::ScalarKind, width: crate::Bytes) -> Result<&'sta Sk::Bool => Ok("bool"), } } + +fn storage_access(storage_access: crate::StorageAccess) -> Option<&'static str> { + if storage_access == crate::StorageAccess::LOAD { + Some("ByteAddressBuffer") + } else if storage_access.is_all() { + Some("RWByteAddressBuffer") + } else { + None + } +} + +fn number_of_components(vector_size: crate::VectorSize) -> usize { + match vector_size { + crate::VectorSize::Bi => 2, + crate::VectorSize::Tri => 3, + crate::VectorSize::Quad => 4, + } +} + +/// Helper function that returns the string corresponding to the HLSL interpolation qualifier +fn interpolation_str(interpolation: crate::Interpolation) -> &'static str { + use crate::Interpolation as I; + + match interpolation { + I::Perspective => "linear", + I::Linear => "noperspective", + I::Flat => "nointerpolation", + } +} + +/// Return the HLSL auxiliary qualifier for the given sampling value. +fn sampling_str(sampling: crate::Sampling) -> Option<&'static str> { + use crate::Sampling as S; + + match sampling { + S::Center => None, + S::Centroid => Some("centroid"), + S::Sample => Some("sample"), + } +} diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 6dc852d5f..8b9571451 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -1,6 +1,6 @@ struct VertexOutput { float4 position : SV_Position; - float varying : LOC1; + linear float varying : LOC1; }; struct FragmentOutput { diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl new file mode 100644 index 000000000..2169938c4 --- /dev/null +++ b/tests/out/hlsl/interpolate.hlsl @@ -0,0 +1,36 @@ +struct FragmentInput { + float4 position : SV_Position; + nointerpolation uint flat : LOC0; + noperspective float linear1 : LOC1; + noperspective centroid float2 linear_centroid : LOC2; + noperspective sample float3 linear_sample : LOC3; + linear float4 perspective : LOC4; + linear centroid float perspective_centroid : LOC5; + linear sample float perspective_sample : LOC6; +}; + +struct FragmentInput_main { + FragmentInput val1; +}; + +FragmentInput main() +{ + FragmentInput out1 = (FragmentInput)0; + + out1.position = float4(2.0, 4.0, 5.0, 6.0); + out1.flat = 8u; + out1.linear1 = 27.0; + out1.linear_centroid = float2(64.0, 125.0); + out1.linear_sample = float3(216.0, 343.0, 512.0); + out1.perspective = float4(729.0, 1000.0, 1331.0, 1728.0); + out1.perspective_centroid = 2197.0; + out1.perspective_sample = 2744.0; + FragmentInput _expr30 = out1; + const FragmentInput fragmentinput1 = _expr30; + return fragmentinput1; +} + +void main1(FragmentInput_main fragmentinput_main) +{ + return; +} diff --git a/tests/out/hlsl/interpolate.hlsl.config b/tests/out/hlsl/interpolate.hlsl.config new file mode 100644 index 000000000..bae3c1cc6 --- /dev/null +++ b/tests/out/hlsl/interpolate.hlsl.config @@ -0,0 +1,4 @@ +vertex=vs_5_0 +vertex_name=main +fragment=ps_5_0 +fragment_name=main1 diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 06a1a2fcd..59957193f 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -6,17 +6,17 @@ struct gl_PerVertex { }; struct type10 { - float2 member : LOC0; + linear float2 member : LOC0; float4 gl_Position : SV_Position; float gl_PointSize : PSIZE; float gl_ClipDistance[1] : SV_ClipDistance; float gl_CullDistance[1] : SV_CullDistance; }; -static float2 v_uv; -static float2 a_uv1; +static float2 v_uv = (float2)0; +static float2 a_uv1 = (float2)0; static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, float(0.0), float(0.0) }; -static float2 a_pos1; +static float2 a_pos1 = (float2)0; struct VertexInput_main { float2 a_uv2 : LOC1; diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index eb619b7d0..f69f51ad5 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -1,7 +1,7 @@ static const float c_scale = 1.2; struct VertexOutput { - float2 uv : LOC0; + linear float2 uv : LOC0; float4 position : SV_Position; }; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index da2f86629..0d61048b5 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -362,7 +362,7 @@ fn convert_wgsl() { ), ( "interpolate", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ("access", Targets::SPIRV | Targets::METAL | Targets::WGSL), ( From 105a2ae5e1e830b2e461b72e313776cf47dc294a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 6 Jul 2021 17:06:51 +0100 Subject: [PATCH 1097/2212] [glsl-in] Check type dimensions in function calls --- src/front/glsl/functions.rs | 58 +++++++++++++++---- tests/in/glsl/900-implicit-conversions.vert | 7 +++ .../wgsl/900-implicit-conversions-vert.wgsl | 29 ++++++++++ 3 files changed, 82 insertions(+), 12 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index b40a5fd33..b99daa85f 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -696,20 +696,54 @@ impl Program<'_> { let decl_inner = &self.module.types[*decl_arg].inner; let call_inner = self.resolve_type(ctx, call_arg.0, call_arg.1)?; - if decl_inner != call_inner { - exact = false; + if decl_inner == call_inner { + continue; + } - match ( - decl_inner.scalar_kind().and_then(type_power), - call_inner.scalar_kind().and_then(type_power), - ) { - (Some(decl_power), Some(call_power)) => { - if decl_power < call_power { - continue 'outer; - } - } - _ => continue 'outer, + exact = false; + + let (decl_kind, call_kind) = match (decl_inner, call_inner) { + ( + &TypeInner::Scalar { + kind: decl_kind, .. + }, + &TypeInner::Scalar { + kind: call_kind, .. + }, + ) => (decl_kind, call_kind), + ( + &TypeInner::Vector { + kind: decl_kind, + size: decl_size, + .. + }, + &TypeInner::Vector { + kind: call_kind, + size: call_size, + .. + }, + ) if decl_size == call_size => (decl_kind, call_kind), + ( + &TypeInner::Matrix { + rows: decl_rows, + columns: decl_columns, + .. + }, + &TypeInner::Matrix { + rows: call_rows, + columns: call_columns, + .. + }, + ) if decl_columns == call_columns && decl_rows == call_rows => { + (ScalarKind::Float, ScalarKind::Float) } + _ => continue 'outer, + }; + + match (type_power(decl_kind), type_power(call_kind)) { + (Some(decl_power), Some(call_power)) + if decl_power > call_power => {} + _ => continue 'outer, } } diff --git a/tests/in/glsl/900-implicit-conversions.vert b/tests/in/glsl/900-implicit-conversions.vert index d3908bb11..c534cfad5 100644 --- a/tests/in/glsl/900-implicit-conversions.vert +++ b/tests/in/glsl/900-implicit-conversions.vert @@ -9,7 +9,14 @@ void exact(int a) {} void implicit(float a) {} void implicit(int a) {} +// All satisfy the kind condition but they have different dimensions +void implicit_dims(float v) { } +void implicit_dims(vec2 v) { } +void implicit_dims(vec3 v) { } +void implicit_dims(vec4 v) { } + void main() { exact(1); implicit(1u); + implicit_dims(ivec3(1)); } diff --git a/tests/out/wgsl/900-implicit-conversions-vert.wgsl b/tests/out/wgsl/900-implicit-conversions-vert.wgsl index 49e4a5704..4704b4419 100644 --- a/tests/out/wgsl/900-implicit-conversions-vert.wgsl +++ b/tests/out/wgsl/900-implicit-conversions-vert.wgsl @@ -26,9 +26,38 @@ fn implicit1(a6: i32) { return; } +fn implicit_dims(v: f32) { + var v1: f32; + + v1 = v; + return; +} + +fn implicit_dims1(v2: vec2) { + var v3: vec2; + + v3 = v2; + return; +} + +fn implicit_dims2(v4: vec3) { + var v5: vec3; + + v5 = v4; + return; +} + +fn implicit_dims3(v6: vec4) { + var v7: vec4; + + v7 = v6; + return; +} + fn main1() { exact1(1); implicit(f32(1u)); + implicit_dims2(vec3(vec3(1))); return; } From ba75ca6efe89b64259c48d7f994d740507e80679 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 6 Jul 2021 17:19:58 +0100 Subject: [PATCH 1098/2212] [glsl-in] Don't implicitly cast shifts --- src/front/glsl/ast.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 306bf1795..8ee5e004b 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -511,9 +511,19 @@ impl<'function> Context<'function> { let (mut left, left_meta) = self.lower_expect(program, left, false, body)?; let (mut right, right_meta) = self.lower_expect(program, right, false, body)?; - self.binary_implicit_conversion( - program, &mut left, left_meta, &mut right, right_meta, - )?; + match op { + BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self + .implicit_conversion( + program, + &mut right, + right_meta, + ScalarKind::Uint, + 4, + )?, + _ => self.binary_implicit_conversion( + program, &mut left, left_meta, &mut right, right_meta, + )?, + } program.typifier_grow(self, left, left_meta)?; program.typifier_grow(self, right, right_meta)?; From 3f2b754c4252ed0bdafd355329855df92c1beecc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 6 Jul 2021 18:10:30 +0100 Subject: [PATCH 1099/2212] [glsl-in] Fix proxy write type mismatch --- src/front/glsl/functions.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index b99daa85f..919876e6a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -795,7 +795,7 @@ impl Program<'_> { Expression::Swizzle { .. } ) { - let ty = self.module.types.append(Type { + let ty = self.module.types.fetch_or_append(Type { name: None, inner: TypeInner::Vector { size, kind, width }, }); From bd339e5f60f5b3c81a247a2077982925fa56fb84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 7 Jul 2021 17:36:33 +0100 Subject: [PATCH 1100/2212] [glsl-in] Add textureProj --- src/front/glsl/functions.rs | 70 +++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 919876e6a..520bdef50 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -276,6 +276,76 @@ impl Program<'_> { )) } } + "textureProj" => { + if !(2..=3).contains(&args.len()) { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + let level = args.get(2).map_or(SampleLevel::Auto, |&(expr, _)| { + let exact = ctx.add_expression( + Expression::As { + kind: ScalarKind::Float, + expr, + convert: Some(4), + }, + body, + ); + SampleLevel::Bias(exact) + }); + let dim = match *self.resolve_type(ctx, args[0].0, args[0].1)? { + TypeInner::Image { dim, .. } => match dim { + crate::ImageDimension::D1 => 1, + crate::ImageDimension::D2 => 2, + crate::ImageDimension::D3 => 3, + crate::ImageDimension::Cube => { + return Err(ErrorKind::SemanticError( + meta, + "textureProj doesn't accept cube texture".into(), + )) + } + }, + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Bad call to textureProj".into(), + )) + } + }; + match *self.resolve_type(ctx, args[1].0, args[1].1)? { + TypeInner::Vector { size, .. } => { + if !(size as usize + 1 == dim || size == VectorSize::Quad) { + return Err(ErrorKind::SemanticError( + meta, + "Bad call to textureProj".into(), + )); + } + } + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Bad call to textureProj".into(), + )) + } + } + if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { + Ok(Some(ctx.add_expression( + Expression::ImageSample { + image: args[0].0, + sampler, + coordinate: args[1].0, + array_index: None, //TODO + offset: None, //TODO + level, + depth_ref: None, + }, + body, + ))) + } else { + Err(ErrorKind::SemanticError( + meta, + "Bad call to textureProj".into(), + )) + } + } "textureSize" => { if !(1..=2).contains(&args.len()) { return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); From 7532c2abaacb035e63e98095686504547d164e33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 7 Jul 2021 17:37:12 +0100 Subject: [PATCH 1101/2212] [glsl-in] Remove wrong texture types Glsl doesn't have depth textures what it has is combined image/samplerShadow --- src/front/glsl/types.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 2b038242d..73812276a 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -133,12 +133,6 @@ pub fn parse_type(type_name: &str) -> Option { "3D" => (ImageDimension::D3, false, sampled(false)), "Cube" => (ImageDimension::Cube, false, sampled(false)), "CubeArray" => (ImageDimension::D2, false, sampled(false)), - "1DShadow" => (ImageDimension::D1, false, ImageClass::Depth), - "1DArrayShadow" => (ImageDimension::D1, true, ImageClass::Depth), - "2DShadow" => (ImageDimension::D2, false, ImageClass::Depth), - "2DArrayShadow" => (ImageDimension::D2, true, ImageClass::Depth), - "CubeShadow" => (ImageDimension::Cube, false, ImageClass::Depth), - "CubeArrayShadow" => (ImageDimension::Cube, true, ImageClass::Depth), _ => return None, }; From 458db0b5228854dc417283f4b9742e03f25bc492 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 11 Jul 2021 23:14:07 -0400 Subject: [PATCH 1102/2212] [hlsl-out] expose profile string conversions --- src/back/hlsl/mod.rs | 22 ++++++++++++---------- tests/snapshots.rs | 5 +++-- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 424584442..27bec76e7 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -16,20 +16,22 @@ pub enum ShaderModel { } impl ShaderModel { - pub fn to_profile_string(self, stage: crate::ShaderStage) -> String { - let stage_prefix = match stage { - crate::ShaderStage::Vertex => "vs_", - crate::ShaderStage::Fragment => "ps_", - crate::ShaderStage::Compute => "cs_", - }; - - let version = match self { + pub fn to_str(self) -> &'static str { + match self { Self::V5_0 => "5_0", Self::V5_1 => "5_1", Self::V6_0 => "6_0", - }; + } + } +} - format!("{}{}", stage_prefix, version) +impl crate::ShaderStage { + pub fn to_hlsl_str(self) -> &'static str { + match self { + Self::Vertex => "vs", + Self::Fragment => "ps", + Self::Compute => "cs", + } } } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 0d61048b5..81bab60a5 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -291,10 +291,11 @@ fn write_output_hlsl( naga::ShaderStage::Compute => "compute", }; config_str = format!( - "{}{}={}\n{}_name={}\n", + "{}{}={}_{}\n{}_name={}\n", config_str, stage_str, - options.shader_model.to_profile_string(ep.stage), + ep.stage.to_hlsl_str(), + options.shader_model.to_str(), stage_str, &reflection_info.entry_points[index] ); From bdf792387a9cf6c4ab4250cf0345fcdba784a672 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 13 Jul 2021 12:18:47 -0700 Subject: [PATCH 1103/2212] Document `ImageLoad`, `ImageStore`, and a few other bits. --- src/lib.rs | 81 +++++++++++++++++++++++++++++++++++++++++++----- src/valid/mod.rs | 1 + 2 files changed, 75 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 67d53cac8..540d6ef5f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -460,7 +460,10 @@ pub enum ImageClass { Sampled { /// Kind of values to sample. kind: ScalarKind, - // Multi-sampled. + /// Multi-sampled image. + /// + /// A multi-sampled image holds several samples per texel. Multi-sampled + /// images cannot have mipmaps. multi: bool, }, /// Depth comparison image. @@ -1008,12 +1011,70 @@ pub enum Expression { }, /// Load a texel from an image. ImageLoad { + /// The image to load a texel from. This must have type [`Image`]. (This + /// will necessarily be a [`GlobalVariable`] or [`FunctionArgument`] + /// expression, since no other expressions are allowed to have that + /// type.) + /// + /// [`Image`]: TypeInner::Image + /// [`GlobalVariable`]: Expression::GlobalVariable + /// [`FunctionArgument`]: Expression::FunctionArgument image: Handle, + + /// The coordinate of the texel we wish to load. This must be a scalar + /// for [`D1`] images, a [`Bi`] vector for [`D2`] images, and a [`Tri`] + /// vector for [`D3`] images. (Array indices, sample indices, and + /// explicit level-of-detail values are supplied separately.) Its + /// component type must be [`Sint`]. + /// + /// [`D1`]: ImageDimension::D1 + /// [`D2`]: ImageDimension::D2 + /// [`D3`]: ImageDimension::D3 + /// [`Bi`]: VectorSize::Bi + /// [`Tri`]: VectorSize::Tri + /// [`Sint`]: ScalarKind::Sint coordinate: Handle, + + /// The index into an arrayed image. If the [`arrayed`] flag in + /// `image`'s type is `true`, then this must be `Some(expr)`, where + /// `expr` is a [`Sint`] scalar. Otherwise, it must be `None`. + /// + /// [`arrayed`]: TypeInner::Image::arrayed + /// [`Sint`]: ScalarKind::Sint array_index: Option>, - /// For storage images, this is None. - /// For sampled images, this is the Some(Level). - /// For multisampled images, this is Some(Sample). + + /// The sample within a particular texel. + /// + /// The meaning of this value depends on the [`class`] of `image`: + /// + /// - [`Storage`] images hold exactly one sample per texel, so `index` must + /// be `None`. + /// + /// - [`Depth`] images may have mipmaps, so `index` must be `Some(level)`, + /// where `level` identifies the level of detail. + /// + /// - [`Sampled`] images may be multisampled or have mipmaps, but not both. + /// Which one is indicated by the `Sampled` variant's [`multi`] field: + /// + /// - If `multi` is `true`, then the image has multiple samples per + /// texel, and `index` must be `Some(sample)`, where `sample` is + /// the index of the sample to retrieve. + /// + /// - If `multi` is `false`, then the image may have mipmaps. In + /// this case, `index` must be `Some(level)`, where `level` + /// identifies the level of detail. Even if the image has only the + /// full-sized version, `level` must still be present; its only + /// in-range value is zero. + /// + /// When `index` is `Some` the value must be a `Sint` scalar value. If + /// it identifes a level of detail, zero represents the full resolution + /// mipmap. + /// + /// [`class`]: TypeInner::Image::class + /// [`Sampled`]: ImageClass::Sampled + /// [`Storage`]: ImageClass::Storage + /// [`Depth`]: ImageClass::Depth + /// [`multi`]: ImageClass::Sampled::multi index: Option>, }, /// Query information from an image. @@ -1198,11 +1259,17 @@ pub enum Statement { pointer: Handle, value: Handle, }, - /// Stores a value to an image. + /// Stores a texel value to an image. + /// + /// The `image`, `coordinate`, and `array_index` fields have the same + /// meanings as the corresponding operands of an [`ImageLoad`] expression; + /// see that documentation for details. Storing into multisampled images or + /// images with mipmaps is not supported, so there is no `index`operand. /// - /// Image has to point into a global variable of type `TypeInner::Image`. /// This statement is a barrier for any operations on the corresponding - /// `Expression::GlobalVariable` for this image. + /// [`Expression::GlobalVariable`] for this image. + /// + /// [`ImageLoad`]: Expression::ImageLoad ImageStore { image: Handle, coordinate: Handle, diff --git a/src/valid/mod.rs b/src/valid/mod.rs index a6dc0f2c4..09a5c0127 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -172,6 +172,7 @@ impl crate::TypeInner { } } + /// Return the `ImageDimension` for which `self` is an appropriate coordinate. fn image_storage_coordinates(&self) -> Option { match *self { Self::Scalar { From caa92ef7b99edaeeebd9b0efdf527135b57c6811 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 19 Jun 2021 22:29:48 -0700 Subject: [PATCH 1104/2212] [spv-out] Documentation for `write_texture_coordinates`. --- src/back/spv/block.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 8cc958557..e5565c6ef 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -90,6 +90,18 @@ impl<'w> BlockContext<'w> { self.writer.get_type_id(lookup_type) } + /// Extend texture coordinates with an array index, if necessary. + /// + /// SPIR-V image read and write instructions take the coordinates of the + /// texel to access as a vector. If the image is arrayed, the array index + /// must be supplied as the final component of the coordinate vector. + /// + /// If `array_index` is `Some(expr)`, then this function constructs a new + /// vector that is `coordinates` with `array_index` concatenated onto the + /// end: a `vec2` becomes a `vec3`, a scalar becomes a `vec2`, and so on. + /// + /// If `array_index` is `None`, this function simply returns the id for + /// `coordinates`. fn write_texture_coordinates( &mut self, coordinates: Handle, From ccf3fe97079395683c756adba4977edb88527439 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 13 Jul 2021 23:53:11 +0300 Subject: [PATCH 1105/2212] Fix type info of texture dimensions function with texture cube parameter --- src/back/msl/writer.rs | 2 +- src/back/spv/block.rs | 2 +- src/proc/typifier.rs | 4 ++-- tests/out/msl/image.msl | 8 ++++---- tests/out/spv/image.spvasm | 24 ++++++++++++------------ tests/out/wgsl/image.wgsl | 8 ++++---- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 836cc523e..cfa034b6d 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -526,7 +526,7 @@ impl Writer { write!(self.out, ")")?; } crate::ImageDimension::Cube => { - write!(self.out, "int3(")?; + write!(self.out, "int2(")?; self.put_image_query(image, "width", level, context)?; write!(self.out, ")")?; } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index e5565c6ef..dbac0b845 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1072,7 +1072,7 @@ impl<'w> BlockContext<'w> { let id = self.gen_id(); let components = match dim { // always pick the first component, and duplicate it for all 3 dimensions - Id::Cube => &[0u32, 0, 0][..], + Id::Cube => &[0u32, 0][..], _ => &[0u32, 1, 2, 3][..dim_coords], }; block.body.push(Instruction::vector_shuffle( diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index c8d2b02df..f25e4ef5c 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -395,12 +395,12 @@ impl<'a> ResolveContext<'a> { kind: crate::ScalarKind::Sint, width: 4, }, - crate::ImageDimension::D2 => Ti::Vector { + crate::ImageDimension::D2 | crate::ImageDimension::Cube => Ti::Vector { size: crate::VectorSize::Bi, kind: crate::ScalarKind::Sint, width: 4, }, - crate::ImageDimension::D3 | crate::ImageDimension::Cube => Ti::Vector { + crate::ImageDimension::D3 => Ti::Vector { size: crate::VectorSize::Tri, kind: crate::ScalarKind::Sint, width: 4, diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 64aa1740e..819818011 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -38,12 +38,12 @@ vertex queriesOutput queries( int num_levels_2d_array = int(image_2d_array.get_num_mip_levels()); metal::int2 dim_2d_array_lod = int2(image_2d_array.get_width(1), image_2d_array.get_height(1)); int num_layers_2d = int(image_2d_array.get_array_size()); - metal::int3 dim_cube = int3(image_cube.get_width()); + metal::int2 dim_cube = int2(image_cube.get_width()); int num_levels_cube = int(image_cube.get_num_mip_levels()); - metal::int3 dim_cube_lod = int3(image_cube.get_width(1)); - metal::int3 dim_cube_array = int3(image_cube_array.get_width()); + metal::int2 dim_cube_lod = int2(image_cube.get_width(1)); + metal::int2 dim_cube_array = int2(image_cube_array.get_width()); int num_levels_cube_array = int(image_cube_array.get_num_mip_levels()); - metal::int3 dim_cube_array_lod = int3(image_cube_array.get_width(1)); + metal::int2 dim_cube_array_lod = int2(image_cube_array.get_width(1)); int num_layers_cube = int(image_cube_array.get_array_size()); metal::int3 dim_3d = int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()); int num_levels_3d = int(image_3d.get_num_mip_levels()); diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 3e32829f7..5e77b27cf 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -168,13 +168,13 @@ OpBranch %81 %93 = OpImageQuerySizeLod %87 %76 %82 %94 = OpCompositeExtract %4 %93 2 %95 = OpImageQuerySizeLod %15 %77 %82 -%96 = OpVectorShuffle %87 %95 %95 0 0 0 -%97 = OpImageQueryLevels %4 %77 -%98 = OpImageQuerySizeLod %15 %77 %6 -%99 = OpVectorShuffle %87 %98 %98 0 0 0 -%100 = OpImageQuerySizeLod %87 %78 %82 -%101 = OpImageQueryLevels %4 %78 -%102 = OpImageQuerySizeLod %87 %78 %6 +%96 = OpImageQueryLevels %4 %77 +%97 = OpImageQuerySizeLod %15 %77 %6 +%98 = OpImageQuerySizeLod %87 %78 %82 +%99 = OpVectorShuffle %15 %98 %98 0 0 +%100 = OpImageQueryLevels %4 %78 +%101 = OpImageQuerySizeLod %87 %78 %6 +%102 = OpVectorShuffle %15 %101 %101 0 0 %103 = OpImageQuerySizeLod %87 %78 %82 %104 = OpCompositeExtract %4 %103 2 %105 = OpImageQuerySizeLod %87 %79 %82 @@ -190,11 +190,11 @@ OpBranch %81 %115 = OpCompositeExtract %4 %92 1 %116 = OpIAdd %4 %114 %115 %117 = OpIAdd %4 %116 %94 -%118 = OpCompositeExtract %4 %96 1 +%118 = OpCompositeExtract %4 %95 1 %119 = OpIAdd %4 %117 %118 -%120 = OpCompositeExtract %4 %99 1 +%120 = OpCompositeExtract %4 %97 1 %121 = OpIAdd %4 %119 %120 -%122 = OpCompositeExtract %4 %100 1 +%122 = OpCompositeExtract %4 %99 1 %123 = OpIAdd %4 %121 %122 %124 = OpCompositeExtract %4 %102 1 %125 = OpIAdd %4 %123 %124 @@ -207,8 +207,8 @@ OpBranch %81 %132 = OpIAdd %4 %131 %85 %133 = OpIAdd %4 %132 %90 %134 = OpIAdd %4 %133 %106 -%135 = OpIAdd %4 %134 %97 -%136 = OpIAdd %4 %135 %101 +%135 = OpIAdd %4 %134 %96 +%136 = OpIAdd %4 %135 %100 %137 = OpConvertSToF %8 %136 %138 = OpCompositeConstruct %23 %137 %137 %137 %137 OpStore %71 %138 diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 61c9fdfd8..e8167cf92 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -42,12 +42,12 @@ fn queries() -> [[builtin(position)]] vec4 { let num_levels_2d_array: i32 = textureNumLevels(image_2d_array); let dim_2d_array_lod: vec2 = textureDimensions(image_2d_array, 1); let num_layers_2d: i32 = textureNumLayers(image_2d_array); - let dim_cube: vec3 = textureDimensions(image_cube); + let dim_cube: vec2 = textureDimensions(image_cube); let num_levels_cube: i32 = textureNumLevels(image_cube); - let dim_cube_lod: vec3 = textureDimensions(image_cube, 1); - let dim_cube_array: vec3 = textureDimensions(image_cube_array); + let dim_cube_lod: vec2 = textureDimensions(image_cube, 1); + let dim_cube_array: vec2 = textureDimensions(image_cube_array); let num_levels_cube_array: i32 = textureNumLevels(image_cube_array); - let dim_cube_array_lod: vec3 = textureDimensions(image_cube_array, 1); + let dim_cube_array_lod: vec2 = textureDimensions(image_cube_array, 1); let num_layers_cube: i32 = textureNumLayers(image_cube_array); let dim_3d: vec3 = textureDimensions(image_3d); let num_levels_3d: i32 = textureNumLevels(image_3d); From 1d1aea243fb2352af0d5f33d33df25ca1cfc1ca6 Mon Sep 17 00:00:00 2001 From: pyrotechnick <13998+pyrotechnick@users.noreply.github.com> Date: Wed, 14 Jul 2021 11:57:52 +1000 Subject: [PATCH 1106/2212] Improve WGSL interpolation attributes (#1083) * [wgsl-in] Map interpolate(..., center) to Sampling::Center * [wgsl-out] Improve interpolation attributes * [wgsl] Fix tests/in/interpolate.wgsl typo/format * [wgsl] Snapshot WGSL artefacts * [wgsl-out] Stack-only writing of interpolation --- src/back/wgsl/writer.rs | 34 +++++++++---------- src/front/wgsl/conv.rs | 1 + tests/in/interpolate.wgsl | 10 +++--- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 2 +- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 4 +-- tests/out/wgsl/210-bevy-shader-vert.wgsl | 8 ++--- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 4 +-- tests/out/wgsl/bevy-pbr-frag.wgsl | 4 +-- tests/out/wgsl/bevy-pbr-vert.wgsl | 10 +++--- tests/out/wgsl/bool-select-frag.wgsl | 2 +- tests/out/wgsl/clamp-splat-vert.wgsl | 2 +- tests/out/wgsl/extra.wgsl | 2 +- tests/out/wgsl/interface.wgsl | 2 +- tests/out/wgsl/interpolate.wgsl | 10 +++--- .../out/wgsl/multiple_entry_points-glsl.wgsl | 2 +- tests/out/wgsl/quad-vert.wgsl | 2 +- tests/out/wgsl/quad.wgsl | 4 +-- tests/out/wgsl/quad_glsl-frag.wgsl | 2 +- tests/out/wgsl/quad_glsl-vert.wgsl | 4 +-- tests/out/wgsl/shadow.wgsl | 2 +- tests/out/wgsl/skybox.wgsl | 2 +- 21 files changed, 57 insertions(+), 56 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 354acd191..53b70df66 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -324,23 +324,23 @@ impl Writer { Attribute::Binding(id) => format!("binding({})", id), Attribute::Group(id) => format!("group({})", id), Attribute::Interpolate(interpolation, sampling) => { - if interpolation.is_some() || sampling.is_some() { - let interpolation_str = if let Some(interpolation) = interpolation { - interpolation_str(interpolation) - } else { - "" - }; - let sampling_str = if let Some(sampling) = sampling { - // Center sampling is the default - if sampling == crate::Sampling::Center { - String::from("") - } else { - format!(",{}", sampling_str(sampling)) - } - } else { - String::from("") - }; - format!("interpolate({}{})", interpolation_str, sampling_str) + if sampling.is_some() && sampling != Some(crate::Sampling::Center) { + format!( + "interpolate({}, {})", + interpolation_str( + interpolation.unwrap_or(crate::Interpolation::Perspective) + ), + sampling_str(sampling.unwrap_or(crate::Sampling::Center)) + ) + } else if interpolation.is_some() + && interpolation != Some(crate::Interpolation::Perspective) + { + format!( + "interpolate({})", + interpolation_str( + interpolation.unwrap_or(crate::Interpolation::Perspective) + ) + ) } else { String::from("") } diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index deb9643df..edd4e3019 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -52,6 +52,7 @@ pub fn map_interpolation(word: &str, span: Span) -> Result Result> { match word { + "center" => Ok(crate::Sampling::Center), "centroid" => Ok(crate::Sampling::Centroid), "sample" => Ok(crate::Sampling::Sample), _ => Err(Error::UnknownAttribute(span)), diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index dcb8a66c5..f95c0b6ca 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -1,14 +1,14 @@ -//TODO: mere with "interface"? +//TODO: merge with "interface"? struct FragmentInput { [[builtin(position)]] position: vec4; [[location(0), interpolate(flat)]] flat : u32; [[location(1), interpolate(linear)]] linear : f32; - [[location(2), interpolate(linear,centroid)]] linear_centroid : vec2; - [[location(3), interpolate(linear,sample)]] linear_sample : vec3; + [[location(2), interpolate(linear, centroid)]] linear_centroid : vec2; + [[location(3), interpolate(linear, sample)]] linear_sample : vec3; [[location(4), interpolate(perspective)]] perspective : vec4; - [[location(5), interpolate(perspective,centroid)]] perspective_centroid : f32; - [[location(6), interpolate(perspective,sample)]] perspective_sample : f32; + [[location(5), interpolate(perspective, centroid)]] perspective_centroid : f32; + [[location(6), interpolate(perspective, sample)]] perspective_sample : f32; }; [[stage(vertex)]] diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index 59986e986..f7eff0a34 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -4,7 +4,7 @@ struct ColorMaterial_color { }; struct FragmentOutput { - [[location(0), interpolate(perspective)]] o_Target: vec4; + [[location(0)]] o_Target: vec4; }; var v_Uv: vec2; diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 45b32f351..4bdf88b0e 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -14,7 +14,7 @@ struct Sprite_size { }; struct VertexOutput { - [[location(0), interpolate(perspective)]] v_Uv: vec2; + [[location(0)]] v_Uv: vec2; [[builtin(position)]] member: vec4; }; @@ -46,7 +46,7 @@ fn main1() { } [[stage(vertex)]] -fn main([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2) -> VertexOutput { +fn main([[location(0)]] Vertex_Position: vec3, [[location(2)]] Vertex_Uv: vec2) -> VertexOutput { Vertex_Position1 = Vertex_Position; Vertex_Uv1 = Vertex_Uv; main1(); diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 2cdca5706..50319b857 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -9,9 +9,9 @@ struct Transform { }; struct VertexOutput { - [[location(0), interpolate(perspective)]] v_Position: vec3; - [[location(1), interpolate(perspective)]] v_Normal: vec3; - [[location(2), interpolate(perspective)]] v_Uv: vec2; + [[location(0)]] v_Position: vec3; + [[location(1)]] v_Normal: vec3; + [[location(2)]] v_Uv: vec2; [[builtin(position)]] member: vec4; }; @@ -46,7 +46,7 @@ fn main1() { } [[stage(vertex)]] -fn main([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(1), interpolate(perspective)]] Vertex_Normal: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2) -> VertexOutput { +fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Normal: vec3, [[location(2)]] Vertex_Uv: vec2) -> VertexOutput { Vertex_Position1 = Vertex_Position; Vertex_Normal1 = Vertex_Normal; Vertex_Uv1 = Vertex_Uv; diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index 80198bf1a..66ba8cc4b 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -9,7 +9,7 @@ struct VertexPushConstants { }; struct VertexOutput { - [[location(0), interpolate(perspective)]] frag_color: vec4; + [[location(0)]] frag_color: vec4; [[builtin(position)]] member: vec4; }; @@ -32,7 +32,7 @@ fn main1() { } [[stage(vertex)]] -fn main([[location(0), interpolate(perspective)]] position: vec2, [[location(1), interpolate(perspective)]] color: vec4) -> VertexOutput { +fn main([[location(0)]] position: vec2, [[location(1)]] color: vec4) -> VertexOutput { position1 = position; color1 = color; main1(); diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 948b2cfb9..dbd65184f 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -53,7 +53,7 @@ struct StandardMaterial_emissive { }; struct FragmentOutput { - [[location(0), interpolate(perspective)]] o_Target: vec4; + [[location(0)]] o_Target: vec4; }; var v_WorldPosition1: vec3; @@ -842,7 +842,7 @@ fn main1() { } [[stage(fragment)]] -fn main([[location(0), interpolate(perspective)]] v_WorldPosition: vec3, [[location(1), interpolate(perspective)]] v_WorldNormal: vec3, [[location(2), interpolate(perspective)]] v_Uv: vec2, [[location(3), interpolate(perspective)]] v_WorldTangent: vec4, [[builtin(front_facing)]] param: bool) -> FragmentOutput { +fn main([[location(0)]] v_WorldPosition: vec3, [[location(1)]] v_WorldNormal: vec3, [[location(2)]] v_Uv: vec2, [[location(3)]] v_WorldTangent: vec4, [[builtin(front_facing)]] param: bool) -> FragmentOutput { v_WorldPosition1 = v_WorldPosition; v_WorldNormal1 = v_WorldNormal; v_Uv1 = v_Uv; diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 63001d808..3acb74420 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -9,10 +9,10 @@ struct Transform { }; struct VertexOutput { - [[location(0), interpolate(perspective)]] v_WorldPosition: vec3; - [[location(1), interpolate(perspective)]] v_WorldNormal: vec3; - [[location(2), interpolate(perspective)]] v_Uv: vec2; - [[location(3), interpolate(perspective)]] v_WorldTangent: vec4; + [[location(0)]] v_WorldPosition: vec3; + [[location(1)]] v_WorldNormal: vec3; + [[location(2)]] v_Uv: vec2; + [[location(3)]] v_WorldTangent: vec4; [[builtin(position)]] member: vec4; }; @@ -54,7 +54,7 @@ fn main1() { } [[stage(vertex)]] -fn main([[location(0), interpolate(perspective)]] Vertex_Position: vec3, [[location(1), interpolate(perspective)]] Vertex_Normal: vec3, [[location(2), interpolate(perspective)]] Vertex_Uv: vec2, [[location(3), interpolate(perspective)]] Vertex_Tangent: vec4) -> VertexOutput { +fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Normal: vec3, [[location(2)]] Vertex_Uv: vec2, [[location(3)]] Vertex_Tangent: vec4) -> VertexOutput { Vertex_Position1 = Vertex_Position; Vertex_Normal1 = Vertex_Normal; Vertex_Uv1 = Vertex_Uv; diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index 51524143b..3702c01c5 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -1,5 +1,5 @@ struct FragmentOutput { - [[location(0), interpolate(perspective)]] o_color: vec4; + [[location(0)]] o_color: vec4; }; var o_color: vec4; diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index 08f00587b..f4afbc77c 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -12,7 +12,7 @@ fn main1() { } [[stage(vertex)]] -fn main([[location(0), interpolate(perspective)]] a_pos: vec2) -> VertexOutput { +fn main([[location(0)]] a_pos: vec2) -> VertexOutput { a_pos1 = a_pos; main1(); let _e3: vec4 = gl_Position; diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index 8db56b157..b68b85568 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -7,6 +7,6 @@ struct PushConstants { var pc: PushConstants; [[stage(fragment)]] -fn main([[location(0), interpolate(perspective)]] color: vec4) -> [[location(0)]] vec4 { +fn main([[location(0)]] color: vec4) -> [[location(0)]] vec4 { return color; } diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index e574da5c9..30875ee8e 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -1,6 +1,6 @@ struct VertexOutput { [[builtin(position)]] position: vec4; - [[location(1), interpolate(perspective)]] varying: f32; + [[location(1)]] varying: f32; }; struct FragmentOutput { diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index 45a7d0a4b..b0b2a9eb1 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -2,11 +2,11 @@ struct FragmentInput { [[builtin(position)]] position: vec4; [[location(0), interpolate(flat)]] flat: u32; [[location(1), interpolate(linear)]] linear: f32; - [[location(2), interpolate(linear,centroid)]] linear_centroid: vec2; - [[location(3), interpolate(linear,sample)]] linear_sample: vec3; - [[location(4), interpolate(perspective)]] perspective: vec4; - [[location(5), interpolate(perspective,centroid)]] perspective_centroid: f32; - [[location(6), interpolate(perspective,sample)]] perspective_sample: f32; + [[location(2), interpolate(linear, centroid)]] linear_centroid: vec2; + [[location(3), interpolate(linear, sample)]] linear_sample: vec3; + [[location(4)]] perspective: vec4; + [[location(5), interpolate(perspective, centroid)]] perspective_centroid: f32; + [[location(6), interpolate(perspective, sample)]] perspective_sample: f32; }; [[stage(vertex)]] diff --git a/tests/out/wgsl/multiple_entry_points-glsl.wgsl b/tests/out/wgsl/multiple_entry_points-glsl.wgsl index 2b8844526..ee890b8be 100644 --- a/tests/out/wgsl/multiple_entry_points-glsl.wgsl +++ b/tests/out/wgsl/multiple_entry_points-glsl.wgsl @@ -3,7 +3,7 @@ struct VertexOutput { }; struct FragmentOutput { - [[location(0), interpolate(perspective)]] o_color: vec4; + [[location(0)]] o_color: vec4; }; var gl_Position: vec4; diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index 683007815..bb6a86a19 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -4,7 +4,7 @@ struct gl_PerVertex { }; struct VertexOutput { - [[location(0), interpolate(perspective)]] member: vec2; + [[location(0)]] member: vec2; [[builtin(position)]] gl_Position: vec4; }; diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 5c14f1ee4..0b2a0c1d8 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -1,5 +1,5 @@ struct VertexOutput { - [[location(0), interpolate(perspective)]] uv: vec2; + [[location(0)]] uv: vec2; [[builtin(position)]] position: vec4; }; @@ -16,7 +16,7 @@ fn main([[location(0)]] pos: vec2, [[location(1)]] uv: vec2) -> Vertex } [[stage(fragment)]] -fn main1([[location(0), interpolate(perspective)]] uv1: vec2) -> [[location(0)]] vec4 { +fn main1([[location(0)]] uv1: vec2) -> [[location(0)]] vec4 { let color: vec4 = textureSample(u_texture, u_sampler, uv1); if ((color.w == 0.0)) { discard; diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index ea2f651ab..9f8f2eaf2 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -1,5 +1,5 @@ struct FragmentOutput { - [[location(0), interpolate(perspective)]] o_color: vec4; + [[location(0)]] o_color: vec4; }; var v_uv: vec2; diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index fe5aa367a..9e659a3b3 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -1,5 +1,5 @@ struct VertexOutput { - [[location(0), interpolate(perspective)]] v_uv: vec2; + [[location(0)]] v_uv: vec2; [[builtin(position)]] member: vec4; }; @@ -17,7 +17,7 @@ fn main1() { } [[stage(vertex)]] -fn main([[location(0), interpolate(perspective)]] a_pos: vec2, [[location(1), interpolate(perspective)]] a_uv: vec2) -> VertexOutput { +fn main([[location(0)]] a_pos: vec2, [[location(1)]] a_uv: vec2) -> VertexOutput { a_pos1 = a_pos; a_uv1 = a_uv; main1(); diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 26993e5e2..f1291003d 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -37,7 +37,7 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { } [[stage(fragment)]] -fn fs_main([[location(0), interpolate(perspective)]] raw_normal: vec3, [[location(1), interpolate(perspective)]] position: vec4) -> [[location(0)]] vec4 { +fn fs_main([[location(0)]] raw_normal: vec3, [[location(1)]] position: vec4) -> [[location(0)]] vec4 { var color: vec3 = vec3(0.05, 0.05, 0.05); var i: u32 = 0u; diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index 83f170f8a..75460c49b 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -1,6 +1,6 @@ struct VertexOutput { [[builtin(position)]] position: vec4; - [[location(0), interpolate(perspective)]] uv: vec3; + [[location(0)]] uv: vec3; }; [[block]] From 0b69aa8b8a3931ef2bcf46d7e06b8342954a43e2 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Wed, 14 Jul 2021 09:42:02 -0700 Subject: [PATCH 1107/2212] Init env_logger in snapshots tests For debugging. Maybe there's a way to do it for all tests, not sure... --- Cargo.toml | 1 + tests/snapshots.rs | 2 ++ 2 files changed, 3 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 09d2b43a9..e27d1705b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,7 @@ ron = "0.6" serde = { version = "1.0", features = ["derive"] } spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } rspirv = "0.7" +env_logger = "0.8" [workspace] members = [".", "cli"] diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 81bab60a5..11dd72e4b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -450,6 +450,8 @@ fn convert_spv_pointer_access() { #[allow(unused_variables)] #[test] fn convert_glsl_folder() { + env_logger::init(); + let root = env!("CARGO_MANIFEST_DIR"); for entry in std::fs::read_dir(format!("{}/{}/glsl", root, BASE_DIR_IN)).unwrap() { From 0995c7161ed50e644c1d902fbf449dcbedbdd1b6 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Wed, 14 Jul 2021 08:55:58 -0700 Subject: [PATCH 1108/2212] [glsl-in] Keep around extra linkage variables WGSL will require this. Note that this still might cause some issues with multi-entry-point GLSL that I didn't know how to handle. That is, we will handle unused builtin inputs but not unused builtin outputs correctly right now. This is an existing issue though, not a regression. This is also provided as an option, but I feel like the more correct approach is to never strip linkage variables. We'll see though. --- cli/src/main.rs | 3 ++ src/front/glsl/ast.rs | 5 +++- src/front/glsl/functions.rs | 32 +++++++++++++++------ src/front/glsl/mod.rs | 3 +- src/front/glsl/parser_tests.rs | 2 +- src/front/glsl/variables.rs | 11 ++++++- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 9 +++--- tests/out/wgsl/quad_glsl-frag.wgsl | 9 +++--- tests/snapshots.rs | 3 ++ 9 files changed, 57 insertions(+), 20 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 0415ddc4f..00e6cf2a6 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -166,6 +166,7 @@ fn main() { &naga::front::glsl::Options { entry_points, defines: Default::default(), + strip_unused_linkages: false, }, ) .unwrap_or_else(|err| { @@ -183,6 +184,7 @@ fn main() { &naga::front::glsl::Options { entry_points, defines: Default::default(), + strip_unused_linkages: false, }, ) .unwrap_or_else(|err| { @@ -200,6 +202,7 @@ fn main() { &naga::front::glsl::Options { entry_points, defines: Default::default(), + strip_unused_linkages: false, }, ) .unwrap_or_else(|err| { diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 8ee5e004b..8008864c7 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -69,6 +69,7 @@ pub struct EntryArg { pub binding: Binding, pub handle: Handle, pub prologue: PrologueStage, + pub storage: StorageQualifier, } #[derive(Debug)] @@ -76,6 +77,7 @@ pub struct Program<'a> { pub version: u16, pub profile: Profile, pub entry_points: &'a FastHashMap, + pub strip_unused_linkages: bool, pub workgroup_size: [u32; 3], pub early_fragment_tests: bool, @@ -94,11 +96,12 @@ pub struct Program<'a> { } impl<'a> Program<'a> { - pub fn new(entry_points: &'a FastHashMap) -> Program<'a> { + pub fn new(entry_points: &'a FastHashMap, strip_unused_linkages: bool) -> Program<'a> { Program { version: 0, profile: Profile::Core, entry_points, + strip_unused_linkages, workgroup_size: [1; 3], early_fragment_tests: false, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 520bdef50..d515bbcc3 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,7 +1,7 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, ImageQuery, LocalVariable, - MathFunction, RelationalFunction, SampleLevel, ScalarKind, ScalarValue, Statement, + MathFunction, RelationalFunction, SampleLevel, ScalarKind, ScalarValue, ShaderStage, Statement, StructMember, SwizzleComponent, Type, TypeInner, VectorSize, }; @@ -1159,12 +1159,23 @@ impl Program<'_> { let mut expressions = Arena::new(); let mut body = Vec::new(); + let can_strip_stage_inputs = self.strip_unused_linkages || stage != ShaderStage::Fragment; + let can_strip_stage_outputs = self.strip_unused_linkages || stage != ShaderStage::Vertex; + for (i, arg) in self.entry_args.iter().enumerate() { - if function_arg_use[function.index()] + if arg.storage != StorageQualifier::Input { + continue; + } + + if !arg.prologue.contains(stage.into()) { + continue; + } + + let is_used = function_arg_use[function.index()] .get(i) - .map_or(true, |u| !u.contains(EntryArgUse::READ)) - || !arg.prologue.contains(stage.into()) - { + .map_or(false, |u| u.contains(EntryArgUse::READ)); + + if can_strip_stage_inputs && !is_used { continue; } @@ -1194,10 +1205,15 @@ impl Program<'_> { let mut components = Vec::new(); for (i, arg) in self.entry_args.iter().enumerate() { - if function_arg_use[function.index()] + if arg.storage != StorageQualifier::Output { + continue; + } + + let is_used = function_arg_use[function.index()] .get(i) - .map_or(true, |u| !u.contains(EntryArgUse::WRITE)) - { + .map_or(false, |u| u.contains(EntryArgUse::WRITE)); + + if can_strip_stage_outputs && !is_used { continue; } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 1db77c271..474ab63f2 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -23,10 +23,11 @@ mod variables; pub struct Options { pub entry_points: FastHashMap, pub defines: FastHashMap, + pub strip_unused_linkages: bool, } pub fn parse_str(source: &str, options: &Options) -> Result { - let mut program = Program::new(&options.entry_points); + let mut program = Program::new(&options.entry_points, options.strip_unused_linkages); let lex = lex::Lexer::new(source, &options.defines); let mut parser = parser::Parser::new(&mut program, lex); diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 465163867..7c8001371 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -14,7 +14,7 @@ fn parse_program<'a>( source: &str, entry_points: &'a crate::FastHashMap, ) -> Result, ErrorKind> { - let mut program = Program::new(entry_points); + let mut program = Program::new(entry_points, true); let defines = crate::FastHashMap::default(); let lex = Lexer::new(source, &defines); let mut parser = parser::Parser::new(&mut program, lex); diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index cec46cdff..98994bed2 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -45,7 +45,7 @@ impl Program<'_> { return Ok(Some(global_var)); } - let mut add_builtin = |inner, builtin, mutable, prologue| { + let mut add_builtin = |inner, builtin, mutable, prologue, storage| { let ty = self .module .types @@ -66,6 +66,7 @@ impl Program<'_> { binding: Binding::BuiltIn(builtin), handle, prologue, + storage, }); self.global_variables.push(( @@ -101,6 +102,7 @@ impl Program<'_> { BuiltIn::Position, true, PrologueStage::empty(), + StorageQualifier::Output, ), "gl_FragCoord" => add_builtin( TypeInner::Vector { @@ -111,6 +113,7 @@ impl Program<'_> { BuiltIn::Position, false, PrologueStage::FRAGMENT, + StorageQualifier::Input, ), "gl_FragDepth" => add_builtin( TypeInner::Scalar { @@ -120,6 +123,7 @@ impl Program<'_> { BuiltIn::FragDepth, true, PrologueStage::empty(), + StorageQualifier::Output, ), "gl_VertexIndex" => add_builtin( TypeInner::Scalar { @@ -129,6 +133,7 @@ impl Program<'_> { BuiltIn::VertexIndex, false, PrologueStage::VERTEX, + StorageQualifier::Input, ), "gl_InstanceIndex" => add_builtin( TypeInner::Scalar { @@ -138,6 +143,7 @@ impl Program<'_> { BuiltIn::InstanceIndex, false, PrologueStage::VERTEX, + StorageQualifier::Input, ), "gl_GlobalInvocationID" => add_builtin( TypeInner::Vector { @@ -148,6 +154,7 @@ impl Program<'_> { BuiltIn::GlobalInvocationId, false, PrologueStage::COMPUTE, + StorageQualifier::Input, ), "gl_FrontFacing" => add_builtin( TypeInner::Scalar { @@ -157,6 +164,7 @@ impl Program<'_> { BuiltIn::FrontFacing, false, PrologueStage::FRAGMENT, + StorageQualifier::Input, ), _ => Ok(None), } @@ -440,6 +448,7 @@ impl Program<'_> { }, handle, prologue, + storage, }); if let Some(name) = name { diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index f7eff0a34..d62e395b1 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -7,7 +7,7 @@ struct FragmentOutput { [[location(0)]] o_Target: vec4; }; -var v_Uv: vec2; +var v_Uv1: vec2; var o_Target: vec4; [[group(1), binding(0)]] var global: ColorMaterial_color; @@ -23,8 +23,9 @@ fn main1() { } [[stage(fragment)]] -fn main() -> FragmentOutput { +fn main([[location(0)]] v_Uv: vec2) -> FragmentOutput { + v_Uv1 = v_Uv; main1(); - let _e1: vec4 = o_Target; - return FragmentOutput(_e1); + let _e3: vec4 = o_Target; + return FragmentOutput(_e3); } diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 9f8f2eaf2..6a52a6c23 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -2,7 +2,7 @@ struct FragmentOutput { [[location(0)]] o_color: vec4; }; -var v_uv: vec2; +var v_uv1: vec2; var o_color: vec4; fn main1() { @@ -11,8 +11,9 @@ fn main1() { } [[stage(fragment)]] -fn main() -> FragmentOutput { +fn main([[location(0)]] v_uv: vec2) -> FragmentOutput { + v_uv1 = v_uv; main1(); - let _e1: vec4 = o_color; - return FragmentOutput(_e1); + let _e3: vec4 = o_color; + return FragmentOutput(_e3); } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 11dd72e4b..dae06f471 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -457,6 +457,7 @@ fn convert_glsl_folder() { for entry in std::fs::read_dir(format!("{}/{}/glsl", root, BASE_DIR_IN)).unwrap() { let entry = entry.unwrap(); let file_name = entry.file_name().into_string().unwrap(); + if file_name.ends_with(".ron") { // No needed to validate ron files continue; @@ -498,11 +499,13 @@ fn convert_glsl_folder() { entry_points.insert("main".to_string(), stage); } + let strip_unused_linkages = entry_points.len() > 1; let module = naga::front::glsl::parse_str( &fs::read_to_string(entry.path()).expect("Couldn't find glsl file"), &naga::front::glsl::Options { entry_points, defines: Default::default(), + strip_unused_linkages: strip_unused_linkages, }, ) .unwrap(); From 2716d368a1da0cbaf6b5d399229921d2215a4bad Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 8 Jul 2021 23:55:14 +0300 Subject: [PATCH 1109/2212] [hlsl-out] Implement barrier statement --- src/back/hlsl/writer.rs | 17 +++++++++++++++++ tests/out/hlsl/control-flow.hlsl | 11 +++++++++++ tests/out/hlsl/control-flow.hlsl.config | 2 ++ tests/snapshots.rs | 2 +- 4 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 tests/out/hlsl/control-flow.hlsl create mode 100644 tests/out/hlsl/control-flow.hlsl.config diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 2e8ca079c..f61fc3750 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -876,6 +876,23 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}", INDENT.repeat(indent))?; writeln!(self.out, "continue;")? } + Statement::Barrier(barrier) => { + if barrier.contains(crate::Barrier::STORAGE) { + writeln!( + self.out, + "{}DeviceMemoryBarrierWithGroupSync();", + INDENT.repeat(indent) + )?; + } + + if barrier.contains(crate::Barrier::WORK_GROUP) { + writeln!( + self.out, + "{}GroupMemoryBarrierWithGroupSync();", + INDENT.repeat(indent) + )?; + } + } _ => return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))), } diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl new file mode 100644 index 000000000..1661ebab9 --- /dev/null +++ b/tests/out/hlsl/control-flow.hlsl @@ -0,0 +1,11 @@ +struct ComputeInput_main { + uint3 global_id1 : SV_DispatchThreadID; +}; + +[numthreads(1, 1, 1)] +void main(ComputeInput_main computeinput_main) +{ + DeviceMemoryBarrierWithGroupSync(); + GroupMemoryBarrierWithGroupSync(); + return; +} diff --git a/tests/out/hlsl/control-flow.hlsl.config b/tests/out/hlsl/control-flow.hlsl.config new file mode 100644 index 000000000..71412ac2d --- /dev/null +++ b/tests/out/hlsl/control-flow.hlsl.config @@ -0,0 +1,2 @@ +compute=cs_5_0 +compute_name=main diff --git a/tests/snapshots.rs b/tests/snapshots.rs index dae06f471..cfcc9c7ef 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -368,7 +368,7 @@ fn convert_wgsl() { ("access", Targets::SPIRV | Targets::METAL | Targets::WGSL), ( "control-flow", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "standard", From c5acef791db06fe8565ac4ca0b53f55c8b94baae Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 14 Jul 2021 13:30:50 +0300 Subject: [PATCH 1110/2212] [hlsl-out] Add module documentation --- src/back/hlsl/mod.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 27bec76e7..31273f682 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -1,3 +1,11 @@ +//! HLSL shading language backend +//! +//! # Supported shader model versions: +//! - 5.0 +//! - 5.1 +//! - 6.0 +//! + mod keywords; mod writer; From 03a5ef3a2f26514ec13c63f4a7ae6f9c62d95da7 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Wed, 14 Jul 2021 19:21:54 +0300 Subject: [PATCH 1111/2212] [hlsl-out] Implement all texture functions --- src/back/hlsl/image.rs | 248 ++++++++++++++++++++++++++++ src/back/hlsl/mod.rs | 3 +- src/back/hlsl/writer.rs | 346 +++++++++++++++++++++++++++++++++------- 3 files changed, 538 insertions(+), 59 deletions(-) create mode 100644 src/back/hlsl/image.rs diff --git a/src/back/hlsl/image.rs b/src/back/hlsl/image.rs new file mode 100644 index 000000000..fe87ac1af --- /dev/null +++ b/src/back/hlsl/image.rs @@ -0,0 +1,248 @@ +// Important note about `Expression::ImageQuery` and hlsl backend: +// Due to implementation of `GetDimensions` function in hlsl (https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions) +// backend can't work with it as an expression. +// Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texure info and query function. +// See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions. +// This allowed to works with `Expression::ImageQuery` as expression and write wrapped function. +// +// For example: +// ```wgsl +// let dim_1d = textureDimensions(image_1d); +// ``` +// +// ```hlsl +// int NagaDimensions1D(Texture1D) +// { +// uint4 ret; +// image_1d.GetDimensions(ret.x); +// return ret.x; +// } +// +// int dim_1d = NagaDimensions1D(image_1d); +// ``` + +use std::fmt::Write; + +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) struct WrappedImageQuery { + pub(super) dim: crate::ImageDimension, + pub(super) arrayed: bool, + pub(super) class: crate::ImageClass, + pub(super) query: ImageQuery, +} + +// HLSL backend requires its own `ImageQuery` enum. +// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function. +// IR version can't be unique per function, because it's store mipmap level as an expression. +// +// For example: +// ```wgsl +// let dim_cube_array_lod = textureDimensions(image_cube_array, 1); +// let dim_cube_array_lod2 = textureDimensions(image_cube_array, 1); +// ``` +// +// ```ir +// ImageQuery { +// image: [1], +// query: Size { +// level: Some( +// [1], +// ), +// }, +// }, +// ImageQuery { +// image: [1], +// query: Size { +// level: Some( +// [2], +// ), +// }, +// }, +// ``` +// +// HLSL should generate only 1 function for this case. +// +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) enum ImageQuery { + Size, + SizeLevel, + NumLevels, + NumLayers, + NumSamples, +} + +impl From for ImageQuery { + fn from(q: crate::ImageQuery) -> Self { + use crate::ImageQuery as Iq; + match q { + Iq::Size { level: Some(_) } => ImageQuery::SizeLevel, + Iq::Size { level: None } => ImageQuery::Size, + Iq::NumLevels => ImageQuery::NumLevels, + Iq::NumLayers => ImageQuery::NumLayers, + Iq::NumSamples => ImageQuery::NumSamples, + } + } +} + +impl<'a, W: Write> super::Writer<'a, W> { + pub(super) fn write_wrapped_image_query_function_name( + &mut self, + query: WrappedImageQuery, + ) -> super::writer::BackendResult { + let dim_str = super::writer::image_dimension_str(query.dim); + let class_str = match query.class { + crate::ImageClass::Sampled { multi: true, .. } => "MS", + crate::ImageClass::Depth => "Depth", + _ => "", + }; + let arrayed_str = if query.arrayed { "Array" } else { "" }; + let query_str = match query.query { + ImageQuery::Size => "Dimensions", + ImageQuery::SizeLevel => "MipDimensions", + ImageQuery::NumLevels => "NumLevels", + ImageQuery::NumLayers => "NumLayers", + ImageQuery::NumSamples => "NumSamples", + }; + + write!( + self.out, + "Naga{}{}{}{}", + class_str, query_str, dim_str, arrayed_str + )?; + + Ok(()) + } + + /// Helper function that write wrapped function for `Expression::ImageQuery` + /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions + pub(super) fn write_wrapped_image_query_functions( + &mut self, + module: &crate::Module, + func_ctx: &crate::back::FunctionCtx<'_>, + ) -> super::writer::BackendResult { + for (handle, _) in func_ctx.expressions.iter() { + if let crate::Expression::ImageQuery { image, query } = func_ctx.expressions[handle] { + let image_ty = func_ctx.info[image].ty.inner_with(&module.types); + match *image_ty { + crate::TypeInner::Image { + dim, + arrayed, + class, + } => { + use crate::back::INDENT; + + let ret_ty = func_ctx.info[handle].ty.inner_with(&module.types); + + let wrapped_image_query = WrappedImageQuery { + dim, + arrayed, + class, + query: query.into(), + }; + + if !self.wrapped_image_queries.contains(&wrapped_image_query) { + // Write function return type and name + self.write_value_type(module, ret_ty)?; + write!(self.out, " ")?; + self.write_wrapped_image_query_function_name(wrapped_image_query)?; + + // Write function parameters + write!(self.out, "(")?; + // Texture always first parameter + self.write_value_type(module, image_ty)?; + // Mipmap is a second parameter if exists + const MIP_LEVEL_PARAM: &str = "MipLevel"; + if let crate::ImageQuery::Size { level: Some(_) } = query { + write!(self.out, ", uint {}", MIP_LEVEL_PARAM)?; + } + writeln!(self.out, ")")?; + + // Write function body + writeln!(self.out, "{{")?; + const RETURN_VARIABLE_NAME: &str = "ret"; + + use crate::ImageDimension as IDim; + use crate::ImageQuery as Iq; + + let array_coords = if arrayed { 1 } else { 0 }; + // GetDimensions Overloaded Methods + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods + let (ret_swizzle, number_of_params) = match query { + Iq::Size { .. } => match dim { + IDim::D1 => ("x", 1 + array_coords), + IDim::D2 => ("xy", 3 + array_coords), + IDim::D3 => ("xyz", 4), + IDim::Cube => ("xy", 3 + array_coords), + }, + Iq::NumLevels | Iq::NumSamples | Iq::NumLayers => { + if arrayed || dim == IDim::D3 { + ("w", 4) + } else { + ("z", 3) + } + } + }; + + // Write `GetDimensions` function. + writeln!(self.out, "{}uint4 {};", INDENT, RETURN_VARIABLE_NAME)?; + write!(self.out, "{}", INDENT)?; + self.write_expr(module, image, func_ctx)?; + write!(self.out, ".GetDimensions(")?; + match query { + Iq::Size { level: Some(_) } => { + write!(self.out, "{}, ", MIP_LEVEL_PARAM)?; + } + _ => + // Write zero mipmap level for supported types + { + if let crate::ImageClass::Sampled { multi: true, .. } = class { + } else { + match dim { + IDim::D2 | IDim::D3 | IDim::Cube => { + write!(self.out, "0, ")?; + } + IDim::D1 => {} + } + } + } + } + + for component in crate::back::COMPONENTS[..number_of_params - 1].iter() + { + write!(self.out, "{}.{}, ", RETURN_VARIABLE_NAME, component)?; + } + + // write last parameter without comma and space for last parameter + write!( + self.out, + "{}.{}", + RETURN_VARIABLE_NAME, + crate::back::COMPONENTS[number_of_params - 1] + )?; + + writeln!(self.out, ");")?; + + // Write return value + writeln!( + self.out, + "{}return {}.{};", + INDENT, RETURN_VARIABLE_NAME, ret_swizzle + )?; + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + + self.wrapped_image_queries.insert(wrapped_image_query); + } + } + // Here we work only with image types + _ => unreachable!(), + } + } + } + + Ok(()) + } +} diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 31273f682..dc98bf85d 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -6,6 +6,7 @@ //! - 6.0 //! +mod image; mod keywords; mod writer; @@ -16,7 +17,7 @@ pub use writer::Writer; /// A HLSL shader model version. #[allow(non_snake_case, non_camel_case_types)] -#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd)] pub enum ShaderModel { V5_0, V5_1, diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index f61fc3750..418e73565 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,5 +1,3 @@ -//TODO: temp -#![allow(dead_code)] use super::{Error, Options}; use crate::{ back, @@ -11,13 +9,11 @@ use std::fmt::Write; const LOCATION_SEMANTIC: &str = "LOC"; /// Shorthand result used internally by the backend -type BackendResult = Result<(), Error>; +pub(super) type BackendResult = Result<(), Error>; /// Structure contains information required for generating /// wrapped structure of all entry points arguments struct EntryPointBinding { - /// Associated shader stage - stage: ShaderStage, /// Generated structure name name: String, /// Members of generated structure @@ -31,7 +27,7 @@ struct EpStructMember { } pub struct Writer<'a, W> { - out: W, + pub(super) out: W, names: crate::FastHashMap, namer: proc::Namer, /// HLSL backend options @@ -40,6 +36,7 @@ pub struct Writer<'a, W> { ep_inputs: Vec>, /// Set of expressions that have associated temporary variables named_expressions: crate::NamedExpressions, + pub(super) wrapped_image_queries: crate::FastHashSet, } impl<'a, W: Write> Writer<'a, W> { @@ -51,6 +48,7 @@ impl<'a, W: Write> Writer<'a, W> { options, ep_inputs: Vec::new(), named_expressions: crate::NamedExpressions::default(), + wrapped_image_queries: crate::FastHashSet::default(), } } @@ -60,6 +58,7 @@ impl<'a, W: Write> Writer<'a, W> { .reset(module, super::keywords::RESERVED, &[], &mut self.names); self.named_expressions.clear(); self.ep_inputs.clear(); + self.wrapped_image_queries.clear(); } pub fn write( @@ -154,6 +153,9 @@ impl<'a, W: Write> Writer<'a, W> { }; let name = self.names[&NameKey::Function(handle)].clone(); + // Write wrapped function for `Expression::ImageQuery` before writing all statements and expressions + self.write_wrapped_image_query_functions(module, &ctx)?; + self.write_function(module, name.as_str(), function, &ctx)?; writeln!(self.out)?; @@ -170,6 +172,9 @@ impl<'a, W: Write> Writer<'a, W> { named_expressions: &ep.function.named_expressions, }; + // Write wrapped function for `Expression::ImageQuery` before writing all statements and expressions + self.write_wrapped_image_query_functions(module, &ctx)?; + if ep.stage == ShaderStage::Compute { // HLSL is calling workgroup size, num threads let num_threads = ep.workgroup_size; @@ -266,7 +271,6 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out)?; let ep_input = EntryPointBinding { - stage, name: struct_name, members, }; @@ -290,19 +294,21 @@ impl<'a, W: Write> Writer<'a, W> { let global = &module.global_variables[handle]; let inner = &module.types[global.ty].inner; - if let Some(storage_access) = storage_access(global.storage_access) { - write!(self.out, "{} ", storage_access)?; - } - - let (storage_class, register_ty) = match *inner { - TypeInner::Image { .. } => ("", "t"), + let (storage, register_ty) = match *inner { + TypeInner::Image { .. } => { + if global.storage_access.contains(crate::StorageAccess::STORE) { + ("RW", "u") + } else { + ("", "t") + } + } TypeInner::Sampler { .. } => ("", "s"), TypeInner::Struct { .. } | TypeInner::Vector { .. } => ("static ", ""), // TODO: other register ty https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register _ => return Err(Error::Unimplemented(format!("register_ty {:?}", inner))), }; - write!(self.out, "{}", storage_class)?; + write!(self.out, "{}", storage)?; self.write_type(module, global.ty)?; if let TypeInner::Array { size, .. } = module.types[global.ty].inner { self.write_array_size(module, size)?; @@ -314,7 +320,11 @@ impl<'a, W: Write> Writer<'a, W> { )?; if let Some(ref binding) = global.binding { - writeln!(self.out, " : register({}{});", register_ty, binding.binding)?; + write!(self.out, " : register({}{}", register_ty, binding.binding)?; + if self.options.shader_model > super::ShaderModel::V5_0 { + write!(self.out, ", space{}", binding.group)?; + } + writeln!(self.out, ");")?; } else { write!(self.out, " = ")?; if let Some(init) = global.init { @@ -507,7 +517,7 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Adds no trailing or leading whitespace - fn write_value_type(&mut self, module: &Module, inner: &TypeInner) -> BackendResult { + pub(super) fn write_value_type(&mut self, module: &Module, inner: &TypeInner) -> BackendResult { match *inner { TypeInner::Scalar { kind, width } => { write!(self.out, "{}", scalar_kind_str(kind, width)?)?; @@ -537,26 +547,34 @@ impl<'a, W: Write> Writer<'a, W> { } TypeInner::Image { dim, - arrayed: _, //TODO: + arrayed, class, } => { + use crate::ImageClass as Ic; + let dim_str = image_dimension_str(dim); - if let crate::ImageClass::Sampled { kind, multi: false } = class { - write!( - self.out, - "Texture{}<{}4>", - dim_str, - scalar_kind_str(kind, 4)? - )? - } else { - return Err(Error::Unimplemented(format!( - "write_value_type {:?}", - inner - ))); + let arrayed_str = if arrayed { "Array" } else { "" }; + write!(self.out, "Texture{}{}", dim_str, arrayed_str)?; + match class { + Ic::Depth => {} + Ic::Sampled { kind, multi } => { + let multi_str = if multi { "MS" } else { "" }; + let scalar_kind_str = scalar_kind_str(kind, 4)?; + write!(self.out, "{}<{}4>", multi_str, scalar_kind_str)? + } + Ic::Storage(format) => { + let storage_format_str = storage_format_to_texture_type(format); + write!(self.out, "<{}>", storage_format_str)? + } } } - TypeInner::Sampler { comparison: false } => { - write!(self.out, "SamplerState")?; + TypeInner::Sampler { comparison } => { + let sampler = if comparison { + "SamplerComparisonState" + } else { + "SamplerState" + }; + write!(self.out, "{}", sampler)?; } // HLSL arrays are written as `type name[size]` // Current code is written arrays only as `[size]` @@ -893,6 +911,32 @@ impl<'a, W: Write> Writer<'a, W> { )?; } } + Statement::ImageStore { + image, + coordinate, + array_index, + value, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + self.write_expr(module, image, func_ctx)?; + + write!(self.out, "[")?; + if let Some(index) = array_index { + // Array index accepted only for texture_storage_2d_array, so we can safety use int3(coordinate, array_index) here + write!(self.out, "int3(")?; + self.write_expr(module, coordinate, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, index, func_ctx)?; + write!(self.out, ")")?; + } else { + self.write_expr(module, coordinate, func_ctx)?; + } + write!(self.out, "]")?; + + write!(self.out, " = ")?; + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ";")?; + } _ => return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))), } @@ -903,7 +947,7 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Doesn't add any newlines or leading/trailing spaces - fn write_expr( + pub(super) fn write_expr( &mut self, module: &Module, expr: Handle, @@ -1023,20 +1067,196 @@ impl<'a, W: Write> Writer<'a, W> { } Expression::ImageSample { image, - sampler, // TODO: - coordinate, // TODO: - array_index: _, // TODO: - offset: _, // TODO: - level: _, // TODO: - depth_ref: _, // TODO: + sampler, + coordinate, + array_index, + offset, + level, + depth_ref, } => { + use crate::SampleLevel as Sl; + + let texture_func = match level { + Sl::Auto => { + if depth_ref.is_some() { + "SampleCmp" + } else { + "Sample" + } + } + Sl::Zero => "SampleCmpLevelZero", + Sl::Exact(_) => "SampleLevel", + Sl::Bias(_) => "SampleBias", + Sl::Gradient { .. } => "SampleGrad", + }; + self.write_expr(module, image, func_ctx)?; - write!(self.out, ".Sample(")?; + write!(self.out, ".{}(", texture_func)?; self.write_expr(module, sampler, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, coordinate, func_ctx)?; + + if let Some(array_index) = array_index { + write!(self.out, ", ")?; + self.write_expr(module, array_index, func_ctx)?; + } + + if let Some(depth_ref) = depth_ref { + write!(self.out, ", ")?; + self.write_expr(module, depth_ref, func_ctx)?; + } + + match level { + Sl::Auto | Sl::Zero => {} + Sl::Exact(expr) => { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + Sl::Bias(expr) => { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + Sl::Gradient { x, y } => { + write!(self.out, ", ")?; + self.write_expr(module, x, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, y, func_ctx)?; + } + } + + if let Some(offset) = offset { + write!(self.out, ", ")?; + self.write_constant(module, offset)?; + } + write!(self.out, ")")?; } + Expression::ImageQuery { image, query } => { + // use wrapped image query function + if let TypeInner::Image { + dim, + arrayed, + class, + } = *func_ctx.info[image].ty.inner_with(&module.types) + { + let wrapped_image_query = super::image::WrappedImageQuery { + dim, + arrayed, + class, + query: query.into(), + }; + + self.write_wrapped_image_query_function_name(wrapped_image_query)?; + write!(self.out, "(")?; + // Image always first param + self.write_expr(module, image, func_ctx)?; + if let crate::ImageQuery::Size { level: Some(level) } = query { + write!(self.out, ", ")?; + self.write_expr(module, level, func_ctx)?; + } + write!(self.out, ")")?; + } + } + Expression::ImageLoad { + image, + coordinate, + array_index, + index, + } => { + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-load + let image_ty = func_ctx.info[image].ty.inner_with(&module.types); + if let crate::TypeInner::Image { + dim, + arrayed, + class, + } = *image_ty + { + use crate::ImageDimension as IDim; + + self.write_expr(module, image, func_ctx)?; + write!(self.out, ".Load(")?; + + let ms = if let crate::ImageClass::Sampled { multi: true, .. } = class { + true + } else { + false + }; + + // Input location type based on texture type + let (load_param_ty, load_components_count) = match dim { + IDim::D1 => { + if arrayed { + ("int3", 3) + } else { + ("int2", 2) + } + } + IDim::D2 => match (ms, arrayed) { + (true, true) => ("int3", 3), + (true, false) => ("int2", 2), + (false, true) => ("int4", 4), + (false, false) => ("int3", 3), + }, + IDim::D3 => ("int4", 4), + _ => unreachable!(), + }; + + let coordinate_expr_components_count = + match *func_ctx.info[coordinate].ty.inner_with(&module.types) { + TypeInner::Vector { size, .. } => size as i32, + TypeInner::Scalar { .. } => 1, + // coordinates can be only vector or scalar + _ => unreachable!(), + }; + + let components_count = { + let array_coords = if arrayed { 1 } else { 0 }; + let array_index_param = if array_index.is_some() { 1 } else { 0 }; + let sampler_index_param = if index.is_some() { 1 } else { 0 }; + + coordinate_expr_components_count + + array_coords + + array_index_param + + sampler_index_param + }; + + let is_ty_cast_required = + load_components_count > coordinate_expr_components_count; + + // cast to another type, if required + if is_ty_cast_required { + write!(self.out, "{}(", load_param_ty)?; + } + self.write_expr(module, coordinate, func_ctx)?; + if let Some(array_index) = array_index { + write!(self.out, ", ")?; + self.write_expr(module, array_index, func_ctx)?; + } + if let Some(index) = index { + write!(self.out, ", ")?; + self.write_expr(module, index, func_ctx)?; + } + if index.is_none() && components_count < load_components_count { + // write zero mipmap level if it's not provided but required + write!(self.out, ", 0")?; + }; + + if is_ty_cast_required { + // close bracket for type + write!(self.out, ")")?; + } + + // close bracket for Load function + write!(self.out, ")")?; + + // return x component if return type is scalar + if let TypeInner::Scalar { .. } = + *func_ctx.info[expr].ty.inner_with(&module.types) + { + write!(self.out, ".x")?; + } + } + } // TODO: copy-paste from wgsl-out Expression::GlobalVariable(handle) => { let name = &self.names[&NameKey::GlobalVariable(handle)]; @@ -1378,7 +1598,7 @@ impl<'a, W: Write> Writer<'a, W> { } } -fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { +pub(super) fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { use crate::ImageDimension as IDim; match dim { @@ -1434,24 +1654,6 @@ fn scalar_kind_str(kind: crate::ScalarKind, width: crate::Bytes) -> Result<&'sta } } -fn storage_access(storage_access: crate::StorageAccess) -> Option<&'static str> { - if storage_access == crate::StorageAccess::LOAD { - Some("ByteAddressBuffer") - } else if storage_access.is_all() { - Some("RWByteAddressBuffer") - } else { - None - } -} - -fn number_of_components(vector_size: crate::VectorSize) -> usize { - match vector_size { - crate::VectorSize::Bi => 2, - crate::VectorSize::Tri => 3, - crate::VectorSize::Quad => 4, - } -} - /// Helper function that returns the string corresponding to the HLSL interpolation qualifier fn interpolation_str(interpolation: crate::Interpolation) -> &'static str { use crate::Interpolation as I; @@ -1473,3 +1675,31 @@ fn sampling_str(sampling: crate::Sampling) -> Option<&'static str> { S::Sample => Some("sample"), } } + +fn storage_format_to_texture_type(format: crate::StorageFormat) -> &'static str { + use crate::StorageFormat as Sf; + + match format { + Sf::R16Float => "float", + Sf::R8Unorm => "unorm float", + Sf::R8Snorm => "snorm float", + Sf::R8Uint | Sf::R16Uint => "uint", + Sf::R8Sint | Sf::R16Sint => "int", + + Sf::Rg16Float => "float2", + Sf::Rg8Unorm => "unorm float2", + Sf::Rg8Snorm => "snorm float2", + + Sf::Rg8Sint | Sf::Rg16Sint => "int2", + Sf::Rg8Uint | Sf::Rg16Uint => "uint2", + + Sf::Rg11b10Float => "float3", + + Sf::Rgba16Float | Sf::R32Float | Sf::Rg32Float | Sf::Rgba32Float => "float4", + Sf::Rgba8Unorm | Sf::Rgb10a2Unorm => "unorm float4", + Sf::Rgba8Snorm => "snorm float4", + + Sf::Rgba8Uint | Sf::Rgba16Uint | Sf::R32Uint | Sf::Rg32Uint | Sf::Rgba32Uint => "uint4", + Sf::Rgba8Sint | Sf::Rgba16Sint | Sf::R32Sint | Sf::Rg32Sint | Sf::Rgba32Sint => "int4", + } +} From 4ef754bb9d30e030d57cbfb6f0e4c86ae0c1908b Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Fri, 16 Jul 2021 13:08:48 +0300 Subject: [PATCH 1112/2212] [hlsl-out] Enable image snapshot --- tests/out/hlsl/image.hlsl | 209 +++++++++++++++++++++++++++++++ tests/out/hlsl/image.hlsl.config | 8 ++ tests/snapshots.rs | 5 +- 3 files changed, 221 insertions(+), 1 deletion(-) create mode 100644 tests/out/hlsl/image.hlsl create mode 100644 tests/out/hlsl/image.hlsl.config diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl new file mode 100644 index 000000000..f5f20b4ba --- /dev/null +++ b/tests/out/hlsl/image.hlsl @@ -0,0 +1,209 @@ +Texture2D image_src : register(t1); +RWTexture1D image_dst : register(u2); +Texture1D image_1d : register(t0); +Texture2D image_2d : register(t1); +Texture2DArray image_2d_array : register(t2); +TextureCube image_cube : register(t3); +TextureCubeArray image_cube_array : register(t4); +Texture3D image_3d : register(t5); +Texture2DMS image_aa : register(t6); +SamplerState sampler_reg : register(s0); +SamplerComparisonState sampler_cmp : register(s1); +Texture2D image_2d_depth : register(t2); + +struct ComputeInput_main { + uint3 local_id1 : SV_GroupThreadID; +}; + +int2 NagaDimensions2D(Texture2D) +{ + uint4 ret; + image_src.GetDimensions(0, ret.x, ret.y, ret.z); + return ret.xy; +} + +[numthreads(16, 1, 1)] +void main(ComputeInput_main computeinput_main) +{ + int2 dim = NagaDimensions2D(image_src); + int2 itc = (mul(dim, int2(computeinput_main.local_id1.xy)) % int2(10, 20)); + uint4 value = image_src.Load(int3(itc, 0)); + image_dst[itc.x] = value; + return; +} + +int NagaDimensions1D(Texture1D) +{ + uint4 ret; + image_1d.GetDimensions(ret.x); + return ret.x; +} + +int2 NagaDimensions2D(Texture2D) +{ + uint4 ret; + image_2d.GetDimensions(0, ret.x, ret.y, ret.z); + return ret.xy; +} + +int NagaNumLevels2D(Texture2D) +{ + uint4 ret; + image_2d.GetDimensions(0, ret.x, ret.y, ret.z); + return ret.z; +} + +int2 NagaMipDimensions2D(Texture2D, uint MipLevel) +{ + uint4 ret; + image_2d.GetDimensions(MipLevel, ret.x, ret.y, ret.z); + return ret.xy; +} + +int2 NagaDimensions2DArray(Texture2DArray) +{ + uint4 ret; + image_2d_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.xy; +} + +int NagaNumLevels2DArray(Texture2DArray) +{ + uint4 ret; + image_2d_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; +} + +int2 NagaMipDimensions2DArray(Texture2DArray, uint MipLevel) +{ + uint4 ret; + image_2d_array.GetDimensions(MipLevel, ret.x, ret.y, ret.z, ret.w); + return ret.xy; +} + +int NagaNumLayers2DArray(Texture2DArray) +{ + uint4 ret; + image_2d_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; +} + +int2 NagaDimensionsCube(TextureCube) +{ + uint4 ret; + image_cube.GetDimensions(0, ret.x, ret.y, ret.z); + return ret.xy; +} + +int NagaNumLevelsCube(TextureCube) +{ + uint4 ret; + image_cube.GetDimensions(0, ret.x, ret.y, ret.z); + return ret.z; +} + +int2 NagaMipDimensionsCube(TextureCube, uint MipLevel) +{ + uint4 ret; + image_cube.GetDimensions(MipLevel, ret.x, ret.y, ret.z); + return ret.xy; +} + +int2 NagaDimensionsCubeArray(TextureCubeArray) +{ + uint4 ret; + image_cube_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.xy; +} + +int NagaNumLevelsCubeArray(TextureCubeArray) +{ + uint4 ret; + image_cube_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; +} + +int2 NagaMipDimensionsCubeArray(TextureCubeArray, uint MipLevel) +{ + uint4 ret; + image_cube_array.GetDimensions(MipLevel, ret.x, ret.y, ret.z, ret.w); + return ret.xy; +} + +int NagaNumLayersCubeArray(TextureCubeArray) +{ + uint4 ret; + image_cube_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; +} + +int3 NagaDimensions3D(Texture3D) +{ + uint4 ret; + image_3d.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.xyz; +} + +int NagaNumLevels3D(Texture3D) +{ + uint4 ret; + image_3d.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; +} + +int3 NagaMipDimensions3D(Texture3D, uint MipLevel) +{ + uint4 ret; + image_3d.GetDimensions(MipLevel, ret.x, ret.y, ret.z, ret.w); + return ret.xyz; +} + +int NagaMSNumSamples2D(Texture2DMS) +{ + uint4 ret; + image_aa.GetDimensions(ret.x, ret.y, ret.z); + return ret.z; +} + +float4 queries() : SV_Position +{ + int dim_1d = NagaDimensions1D(image_1d); + int2 dim_2d = NagaDimensions2D(image_2d); + int num_levels_2d = NagaNumLevels2D(image_2d); + int2 dim_2d_lod = NagaMipDimensions2D(image_2d, 1); + int2 dim_2d_array = NagaDimensions2DArray(image_2d_array); + int num_levels_2d_array = NagaNumLevels2DArray(image_2d_array); + int2 dim_2d_array_lod = NagaMipDimensions2DArray(image_2d_array, 1); + int num_layers_2d = NagaNumLayers2DArray(image_2d_array); + int2 dim_cube = NagaDimensionsCube(image_cube); + int num_levels_cube = NagaNumLevelsCube(image_cube); + int2 dim_cube_lod = NagaMipDimensionsCube(image_cube, 1); + int2 dim_cube_array = NagaDimensionsCubeArray(image_cube_array); + int num_levels_cube_array = NagaNumLevelsCubeArray(image_cube_array); + int2 dim_cube_array_lod = NagaMipDimensionsCubeArray(image_cube_array, 1); + int num_layers_cube = NagaNumLayersCubeArray(image_cube_array); + int3 dim_3d = NagaDimensions3D(image_3d); + int num_levels_3d = NagaNumLevels3D(image_3d); + int3 dim_3d_lod = NagaMipDimensions3D(image_3d, 1); + int num_samples_aa = NagaMSNumSamples2D(image_aa); + int sum = ((((((((((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + num_layers_2d) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + num_layers_cube) + dim_3d.z) + dim_3d_lod.z) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); + return float4(float(sum).xxxx); +} + +float4 sample1() : SV_Target0 +{ + float2 tc = float2(0.5.xx); + float4 s2d = image_2d.Sample(sampler_reg, tc); + float4 s2d_offset = image_2d.Sample(sampler_reg, tc, int2(3, 1)); + float4 s2d_level = image_2d.SampleLevel(sampler_reg, tc, 2.3); + float4 s2d_level_offset = image_2d.SampleLevel(sampler_reg, tc, 2.3, int2(3, 1)); + return (((s2d + s2d_offset) + s2d_level) + s2d_level_offset); +} + +float sample_comparison() : SV_Target0 +{ + float2 tc = float2(0.5.xx); + float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc, 0.5); + float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc, 0.5); + return (s2d_depth + s2d_depth_level); +} diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config new file mode 100644 index 000000000..3e97dafc3 --- /dev/null +++ b/tests/out/hlsl/image.hlsl.config @@ -0,0 +1,8 @@ +compute=cs_5_0 +compute_name=main +vertex=vs_5_0 +vertex_name=queries +fragment=ps_5_0 +fragment_name=sample1 +fragment=ps_5_0 +fragment_name=sample_comparison diff --git a/tests/snapshots.rs b/tests/snapshots.rs index cfcc9c7ef..74de68f34 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -355,7 +355,10 @@ fn convert_wgsl() { "shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, ), - ("image", Targets::SPIRV | Targets::METAL | Targets::WGSL), + ( + "image", + Targets::SPIRV | Targets::METAL | Targets::HLSL | Targets::WGSL, + ), ("extra", Targets::SPIRV | Targets::METAL | Targets::WGSL), ( "operators", From 10a3a6a827018dd53362475c7c593f55b588e13f Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 16 Jul 2021 12:32:09 +0000 Subject: [PATCH 1113/2212] [glsl-out] Write sint array size --- src/back/glsl/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index bb6b68f03..66209e6b3 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -604,6 +604,10 @@ impl<'a, W: Write> Writer<'a, W> { width: _, value: crate::ScalarValue::Uint(size), } => write!(self.out, "{}", size)?, + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Sint(size), + } => write!(self.out, "{}", size)?, _ => unreachable!(), } } From 8eef784416b4609d42db1e8e1e3541dd85de01b6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 16 Jul 2021 11:19:43 -0400 Subject: [PATCH 1114/2212] WGSL: Flip true/false arguments of select() --- CHANGELOG.md | 4 ++++ src/back/wgsl/writer.rs | 4 ++-- src/front/glsl/ast.rs | 5 ++++- src/front/glsl/functions.rs | 6 ++++-- src/front/wgsl/mod.rs | 4 ++-- tests/out/glsl/operators.main.Compute.glsl | 4 ++-- tests/out/hlsl/interface.hlsl | 2 +- tests/out/hlsl/operators.hlsl | 4 ++-- tests/out/msl/interface.msl | 2 +- tests/out/msl/operators.msl | 4 ++-- tests/out/spv/interface.spvasm | 2 +- tests/out/spv/operators.spvasm | 4 ++-- tests/out/wgsl/bevy-pbr-frag.wgsl | 6 +++--- tests/out/wgsl/bool-select-frag.wgsl | 4 ++-- 14 files changed, 32 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51c9655d8..7d095734e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change Log +## TBD + - API: + - WGSL `select()` order of true/false is swapped + ## v0.5 (2021-06-18) - development release for wgpu-0.9 - API: diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 53b70df66..7e7db5f02 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1245,10 +1245,10 @@ impl Writer { reject, } => { write!(self.out, "select(")?; - self.write_expr(module, accept, func_ctx)?; - write!(self.out, ", ")?; self.write_expr(module, reject, func_ctx)?; write!(self.out, ", ")?; + self.write_expr(module, accept, func_ctx)?; + write!(self.out, ", ")?; self.write_expr(module, condition, func_ctx)?; write!(self.out, ")")? } diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 8008864c7..bb1fd41aa 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -96,7 +96,10 @@ pub struct Program<'a> { } impl<'a> Program<'a> { - pub fn new(entry_points: &'a FastHashMap, strip_unused_linkages: bool) -> Program<'a> { + pub fn new( + entry_points: &'a FastHashMap, + strip_unused_linkages: bool, + ) -> Program<'a> { Program { version: 0, profile: Profile::Core, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index d515bbcc3..63be05756 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1159,8 +1159,10 @@ impl Program<'_> { let mut expressions = Arena::new(); let mut body = Vec::new(); - let can_strip_stage_inputs = self.strip_unused_linkages || stage != ShaderStage::Fragment; - let can_strip_stage_outputs = self.strip_unused_linkages || stage != ShaderStage::Vertex; + let can_strip_stage_inputs = + self.strip_unused_linkages || stage != ShaderStage::Fragment; + let can_strip_stage_outputs = + self.strip_unused_linkages || stage != ShaderStage::Vertex; for (i, arg) in self.entry_args.iter().enumerate() { if arg.storage != StorageQualifier::Input { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index dea23906e..bb40deb80 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1112,10 +1112,10 @@ impl Parser { } } else if name == "select" { lexer.open_arguments()?; - let accept = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; let reject = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; + let accept = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; let condition = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::Select { diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 232cd4c06..802ef48da 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -22,8 +22,8 @@ int unary() { vec4 selection() { vec4 vector1_ = vec4(1.0); vec4 vector2_ = vec4(1.0); - int a = (true ? 0 : 1); - return (true ? vector1_ : vector2_); + int a = (true ? 1 : 0); + return (true ? vector2_ : vector1_); } void main() { diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 8b9571451..fc118eea2 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -39,7 +39,7 @@ VertexOutput vertex(VertexInput_vertex vertexinput_vertex) FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) { uint mask = (fragmentinput_fragment.sample_mask1 & (1u << fragmentinput_fragment.sample_index1)); - float color2 = (fragmentinput_fragment.front_facing1 ? 0.0 : 1.0); + float color2 = (fragmentinput_fragment.front_facing1 ? 1.0 : 0.0); const FragmentOutput fragmentoutput1 = { fragmentinput_fragment.in2.varying, mask, color2 }; return fragmentoutput1; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index b582a4452..10621ce05 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -18,8 +18,8 @@ float4 selection() { float4 vector1_ = float4(1.0.xxxx); float4 vector2_ = float4(1.0.xxxx); - int a = (true ? 0 : 1); - return (true ? vector1_ : vector2_); + int a = (true ? 1 : 0); + return (true ? vector2_ : vector1_); } [numthreads(1, 1, 1)] diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 67ef0290d..67b51a83e 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -47,7 +47,7 @@ fragment fragment1Output fragment1( ) { const VertexOutput in = { position, varyings1.varying }; metal::uint mask = sample_mask & (1u << sample_index); - float color1 = front_facing ? 0.0 : 1.0; + float color1 = front_facing ? 1.0 : 0.0; const auto _tmp = FragmentOutput {in.varying, mask, color1}; return fragment1Output { _tmp.depth, _tmp.sample_mask, _tmp.color }; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 9fd7f3b4a..62ca17b3f 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -22,8 +22,8 @@ metal::float4 selection( ) { metal::float4 vector1_ = metal::float4(1.0); metal::float4 vector2_ = metal::float4(1.0); - int a = true ? 0 : 1; - return true ? vector1_ : vector2_; + int a = true ? 1 : 0; + return true ? vector2_ : vector1_; } kernel void main1( diff --git a/tests/out/spv/interface.spvasm b/tests/out/spv/interface.spvasm index 3ba43b860..6f4b5d1d1 100644 --- a/tests/out/spv/interface.spvasm +++ b/tests/out/spv/interface.spvasm @@ -101,7 +101,7 @@ OpBranch %55 %55 = OpLabel %56 = OpShiftLeftLogical %6 %5 %47 %57 = OpBitwiseAnd %6 %49 %56 -%58 = OpSelect %4 %45 %7 %3 +%58 = OpSelect %4 %45 %3 %7 %59 = OpCompositeExtract %4 %36 1 %60 = OpCompositeConstruct %10 %59 %57 %58 %61 = OpCompositeExtract %4 %60 0 diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index f84503609..48bef9319 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -68,9 +68,9 @@ OpBranch %47 %47 = OpLabel %48 = OpCompositeConstruct %15 %3 %3 %3 %3 %49 = OpCompositeConstruct %15 %3 %3 %3 %3 -%50 = OpSelect %9 %12 %14 %11 +%50 = OpSelect %9 %12 %11 %14 %53 = OpCompositeConstruct %52 %12 %12 %12 %12 -%51 = OpSelect %15 %53 %48 %49 +%51 = OpSelect %15 %53 %49 %48 OpReturnValue %51 OpFunctionEnd %55 = OpFunction %2 None %56 diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index dbd65184f..075be30c1 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -695,15 +695,15 @@ fn main1() { let _e78: bool = gl_FrontFacing; let _e79: vec3 = N2; let _e80: vec3 = N2; - N2 = select(_e79, -(_e80), _e78); + N2 = select(-(_e80), _e79, _e78); let _e83: bool = gl_FrontFacing; let _e84: vec3 = T; let _e85: vec3 = T; - T = select(_e84, -(_e85), _e83); + T = select(-(_e85), _e84, _e83); let _e88: bool = gl_FrontFacing; let _e89: vec3 = B; let _e90: vec3 = B; - B = select(_e89, -(_e90), _e88); + B = select(-(_e90), _e89, _e88); let _e93: vec3 = T; let _e94: vec3 = B; let _e95: vec3 = N2; diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index 3702c01c5..d7d0e7173 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -12,7 +12,7 @@ fn TevPerCompGT(a: f32, b: f32) -> f32 { b1 = b; let _e5: f32 = a1; let _e6: f32 = b1; - return select(1.0, 0.0, (_e5 > _e6)); + return select(0.0, 1.0, (_e5 > _e6)); } fn TevPerCompGT1(a2: vec3, b2: vec3) -> vec3 { @@ -23,7 +23,7 @@ fn TevPerCompGT1(a2: vec3, b2: vec3) -> vec3 { b3 = b2; let _e5: vec3 = a3; let _e6: vec3 = b3; - return select(vec3(1.0), vec3(0.0), (_e5 > _e6)); + return select(vec3(0.0), vec3(1.0), (_e5 > _e6)); } fn main1() { From 602368d9f0d2dff768bdb682373e8af4d5c31b7e Mon Sep 17 00:00:00 2001 From: initial-algebra <67286231+initial-algebra@users.noreply.github.com> Date: Fri, 16 Jul 2021 23:18:20 -0300 Subject: [PATCH 1115/2212] Support `builtin(primitive_index)` (#1097) * Hack in support for PrimitiveID on Vulkan * Rename to PrimitiveIndex and add preliminary support for GLSL, HLSL and MSL * Implement as an extra WGSL built-in * Update extra.wgsl outputs * Run rustfmt; fix WGSL writer * Add rustfmt changes I forgot * Update extra.wgsl test output for WGSL fix * Bump macOS version to 10.15 in validate-msl to support primitive_index --- Makefile | 2 +- src/back/glsl/mod.rs | 1 + src/back/hlsl/writer.rs | 1 + src/back/msl/mod.rs | 1 + src/back/spv/writer.rs | 4 ++ src/back/wgsl/writer.rs | 1 + src/front/glsl/variables.rs | 10 +++++ src/front/spv/convert.rs | 1 + src/front/spv/mod.rs | 2 + src/front/wgsl/conv.rs | 1 + src/lib.rs | 1 + src/valid/interface.rs | 20 +++++++++ src/valid/mod.rs | 2 + tests/in/extra.wgsl | 13 +++++- tests/out/msl/extra.msl | 13 +++++- tests/out/spv/extra.spvasm | 87 +++++++++++++++++++++++++------------ tests/out/wgsl/extra.wgsl | 13 +++++- 17 files changed, 139 insertions(+), 34 deletions(-) diff --git a/Makefile b/Makefile index 85a139952..380bca01f 100644 --- a/Makefile +++ b/Makefile @@ -35,7 +35,7 @@ validate-spv: $(SNAPSHOTS_BASE_OUT)/spv/*.spvasm validate-msl: $(SNAPSHOTS_BASE_OUT)/msl/*.msl @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ - cat $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -x metal - -o /dev/null; \ + cat $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.15 -x metal - -o /dev/null; \ done validate-glsl: $(SNAPSHOTS_BASE_OUT)/glsl/*.glsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 66209e6b3..5a5b879da 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2447,6 +2447,7 @@ fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { // fragment Bi::FragDepth => "gl_FragDepth", Bi::FrontFacing => "gl_FrontFacing", + Bi::PrimitiveIndex => "uint(gl_PrimitiveID)", Bi::SampleIndex => "gl_SampleID", Bi::SampleMask => { if output { diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 418e73565..2e80a0803 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1625,6 +1625,7 @@ fn builtin_str(built_in: crate::BuiltIn) -> &'static str { // fragment Bi::FragDepth => "SV_Depth", Bi::FrontFacing => "SV_IsFrontFace", + Bi::PrimitiveIndex => "SV_PrimitiveID", Bi::SampleIndex => "SV_SampleIndex", Bi::SampleMask => "SV_Coverage", // compute diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 33d2e1a15..3277991b3 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -348,6 +348,7 @@ impl ResolvedBinding { // fragment Bi::FragDepth => "depth(any)", Bi::FrontFacing => "front_facing", + Bi::PrimitiveIndex => "primitive_id", Bi::SampleIndex => "sample_id", Bi::SampleMask => "sample_mask", // compute diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 8346e8f42..7fd292129 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1012,6 +1012,10 @@ impl Writer { // fragment Bi::FragDepth => BuiltIn::FragDepth, Bi::FrontFacing => BuiltIn::FrontFacing, + Bi::PrimitiveIndex => { + self.capabilities.insert(spirv::Capability::Geometry); + BuiltIn::PrimitiveId + } Bi::SampleIndex => BuiltIn::SampleId, Bi::SampleMask => BuiltIn::SampleMask, // compute diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 7e7db5f02..8cfafd122 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1479,6 +1479,7 @@ fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { Bi::WorkGroupSize => Some("workgroup_size"), Bi::SampleIndex => Some("sample_index"), Bi::SampleMask => Some("sample_mask"), + Bi::PrimitiveIndex => Some("primitive_index"), _ => None, } } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 98994bed2..c0aae1876 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -166,6 +166,16 @@ impl Program<'_> { PrologueStage::FRAGMENT, StorageQualifier::Input, ), + "gl_PrimitiveID" => add_builtin( + TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + }, + BuiltIn::PrimitiveIndex, + false, + PrologueStage::FRAGMENT, + StorageQualifier::Input, + ), _ => Ok(None), } } diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index dc429c290..3bb35249a 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -132,6 +132,7 @@ pub(super) fn map_builtin(word: spirv::Word) -> Result { // fragment Some(Bi::FragDepth) => crate::BuiltIn::FragDepth, Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing, + Some(Bi::PrimitiveId) => crate::BuiltIn::PrimitiveIndex, Some(Bi::SampleId) => crate::BuiltIn::SampleIndex, Some(Bi::SampleMask) => crate::BuiltIn::SampleMask, // compute diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d03ea8b33..01ecda65d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -69,6 +69,7 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Int8, spirv::Capability::Int16, spirv::Capability::Int64, + spirv::Capability::Geometry, // tricky ones spirv::Capability::UniformBufferArrayDynamicIndexing, spirv::Capability::StorageBufferArrayDynamicIndexing, @@ -3482,6 +3483,7 @@ impl> Parser { | crate::BuiltIn::InstanceIndex | crate::BuiltIn::SampleIndex | crate::BuiltIn::VertexIndex + | crate::BuiltIn::PrimitiveIndex | crate::BuiltIn::LocalInvocationIndex => Some(crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width: 4, diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index edd4e3019..6f7d1565b 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -20,6 +20,7 @@ pub fn map_built_in(word: &str, span: Span) -> Result> // fragment "front_facing" => crate::BuiltIn::FrontFacing, "frag_depth" => crate::BuiltIn::FragDepth, + "primitive_index" => crate::BuiltIn::PrimitiveIndex, "sample_index" => crate::BuiltIn::SampleIndex, "sample_mask" => crate::BuiltIn::SampleMask, // compute diff --git a/src/lib.rs b/src/lib.rs index 540d6ef5f..14997a734 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -269,6 +269,7 @@ pub enum BuiltIn { // fragment FragDepth, FrontFacing, + PrimitiveIndex, SampleIndex, SampleMask, // compute diff --git a/src/valid/interface.rs b/src/valid/interface.rs index d4050aea1..c4b4f83ae 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -53,6 +53,8 @@ pub enum VaryingError { BindingCollision { location: u32 }, #[error("Built-in {0:?} is present more than once")] DuplicateBuiltIn(crate::BuiltIn), + #[error("Capability {0:?} is not supported")] + UnsupportedCapability(Capabilities), } #[derive(Clone, Debug, thiserror::Error)] @@ -99,6 +101,7 @@ struct VaryingContext<'a> { types: &'a Arena, location_mask: &'a mut BitSet, built_in_mask: u32, + capabilities: Capabilities, } impl VaryingContext<'_> { @@ -176,6 +179,21 @@ impl VaryingContext<'_> { width: crate::BOOL_WIDTH, }, ), + Bi::PrimitiveIndex => { + if !self.capabilities.contains(Capabilities::PRIMITIVE_INDEX) { + return Err(VaryingError::UnsupportedCapability( + Capabilities::PRIMITIVE_INDEX, + )); + } + ( + self.stage == St::Fragment && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ) + } Bi::SampleIndex => ( self.stage == St::Fragment && !self.output, *ty_inner @@ -429,6 +447,7 @@ impl super::Validator { types: &module.types, location_mask: &mut self.location_mask, built_in_mask: argument_built_ins, + capabilities: self.capabilities, }; ctx.validate(fa.binding.as_ref()) .map_err(|e| EntryPointError::Argument(index as u32, e))?; @@ -444,6 +463,7 @@ impl super::Validator { types: &module.types, location_mask: &mut self.location_mask, built_in_mask: 0, + capabilities: self.capabilities, }; ctx.validate(fr.binding.as_ref()) .map_err(EntryPointError::Result)?; diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 09a5c0127..d8b0be0d1 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -58,6 +58,8 @@ bitflags::bitflags! { const PUSH_CONSTANT = 0x1; /// Float values with width = 8. const FLOAT64 = 0x2; + /// Support for `Builtin:PrimitiveIndex`. + const PRIMITIVE_INDEX = 0x4; } } diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index 11b8a2eb6..9f9acb033 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -5,7 +5,16 @@ struct PushConstants { }; var pc: PushConstants; +struct FragmentIn { + [[location(0)]] color: vec4; + [[builtin(primitive_index)]] primitive_index: u32; +}; + [[stage(fragment)]] -fn main([[location(0)]] color: vec4) -> [[location(0)]] vec4 { - return color; +fn main(in: FragmentIn) -> [[location(0)]] vec4 { + if (in.primitive_index % 2u == 0u) { + return in.color; + } else { + return vec4(vec3(1.0) - in.color.rgb, in.color.a); + } } diff --git a/tests/out/msl/extra.msl b/tests/out/msl/extra.msl index b2a2363d9..a568e14fa 100644 --- a/tests/out/msl/extra.msl +++ b/tests/out/msl/extra.msl @@ -6,6 +6,10 @@ struct PushConstants { char _pad1[12]; metal::float2 double1; }; +struct FragmentIn { + metal::float4 color; + metal::uint primitive_index; +}; struct main1Input { metal::float4 color [[user(loc0), center_perspective]]; @@ -15,7 +19,12 @@ struct main1Output { }; fragment main1Output main1( main1Input varyings [[stage_in]] +, metal::uint primitive_index [[primitive_id]] ) { - const auto color = varyings.color; - return main1Output { color }; + const FragmentIn in = { varyings.color, primitive_index }; + if ((in.primitive_index % 2u) == 0u) { + return main1Output { in.color }; + } else { + return main1Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) }; + } } diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index ec05bdbdf..1131df183 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -1,37 +1,70 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 20 +; Bound: 44 OpCapability Shader OpCapability Float64 +OpCapability Geometry %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %17 "main" %12 %15 -OpExecutionMode %17 OriginUpperLeft -OpDecorate %6 Block -OpMemberDecorate %6 0 Offset 0 -OpMemberDecorate %6 1 Offset 16 -OpDecorate %12 Location 0 -OpDecorate %15 Location 0 +OpEntryPoint Fragment %25 "main" %17 %20 %23 +OpExecutionMode %25 OriginUpperLeft +OpDecorate %10 Block +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 16 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 16 +OpDecorate %17 Location 0 +OpDecorate %20 BuiltIn PrimitiveId +OpDecorate %23 Location 0 %2 = OpTypeVoid -%3 = OpTypeInt 32 0 -%5 = OpTypeFloat 64 -%4 = OpTypeVector %5 2 -%6 = OpTypeStruct %3 %4 -%8 = OpTypeFloat 32 -%7 = OpTypeVector %8 4 -%10 = OpTypePointer PushConstant %6 -%9 = OpVariable %10 PushConstant -%13 = OpTypePointer Input %7 -%12 = OpVariable %13 Input -%16 = OpTypePointer Output %7 -%15 = OpVariable %16 Output -%18 = OpTypeFunction %2 -%17 = OpFunction %2 None %18 -%11 = OpLabel -%14 = OpLoad %7 %12 -OpBranch %19 -%19 = OpLabel -OpStore %15 %14 +%4 = OpTypeInt 32 0 +%3 = OpConstant %4 2 +%5 = OpConstant %4 0 +%7 = OpTypeFloat 32 +%6 = OpConstant %7 1.0 +%9 = OpTypeFloat 64 +%8 = OpTypeVector %9 2 +%10 = OpTypeStruct %4 %8 +%11 = OpTypeVector %7 4 +%12 = OpTypeStruct %11 %4 +%14 = OpTypePointer PushConstant %10 +%13 = OpVariable %14 PushConstant +%18 = OpTypePointer Input %11 +%17 = OpVariable %18 Input +%21 = OpTypePointer Input %4 +%20 = OpVariable %21 Input +%24 = OpTypePointer Output %11 +%23 = OpVariable %24 Output +%26 = OpTypeFunction %2 +%30 = OpTypeBool +%36 = OpTypeVector %7 3 +%25 = OpFunction %2 None %26 +%15 = OpLabel +%19 = OpLoad %11 %17 +%22 = OpLoad %4 %20 +%16 = OpCompositeConstruct %12 %19 %22 +OpBranch %27 +%27 = OpLabel +%28 = OpCompositeExtract %4 %16 1 +%29 = OpUMod %4 %28 %3 +%31 = OpIEqual %30 %29 %5 +OpSelectionMerge %32 None +OpBranchConditional %31 %33 %34 +%33 = OpLabel +%35 = OpCompositeExtract %11 %16 0 +OpStore %23 %35 +OpReturn +%34 = OpLabel +%37 = OpCompositeConstruct %36 %6 %6 %6 +%38 = OpCompositeExtract %11 %16 0 +%39 = OpVectorShuffle %36 %38 %38 0 1 2 +%40 = OpFSub %36 %37 %39 +%41 = OpCompositeExtract %11 %16 0 +%42 = OpCompositeExtract %7 %41 3 +%43 = OpCompositeConstruct %11 %40 %42 +OpStore %23 %43 +OpReturn +%32 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index b68b85568..710519b8e 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -4,9 +4,18 @@ struct PushConstants { double: vec2; }; +struct FragmentIn { + [[location(0)]] color: vec4; + [[builtin(primitive_index)]] primitive_index: u32; +}; + var pc: PushConstants; [[stage(fragment)]] -fn main([[location(0)]] color: vec4) -> [[location(0)]] vec4 { - return color; +fn main(in: FragmentIn) -> [[location(0)]] vec4 { + if (((in.primitive_index % 2u) == 0u)) { + return in.color; + } else { + return vec4((vec3(1.0) - in.color.xyz), in.color.w); + } } From e76824aba3583b4a509454aa0605f930c0469285 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 16 Jul 2021 23:04:55 -0400 Subject: [PATCH 1116/2212] glsl-out: fix emission of location/binding attributes (#1100) --- src/back/glsl/mod.rs | 25 +++++++++++++-------- tests/in/quad.param.ron | 5 +++++ tests/out/glsl/quad-vert.main.Vertex.glsl | 2 +- tests/out/glsl/quad.fs_extra.Fragment.glsl | 2 +- tests/out/glsl/quad.main.Fragment.glsl | 2 +- tests/out/glsl/quad.main.Vertex.glsl | 3 +-- tests/out/glsl/shadow.fs_main.Fragment.glsl | 4 ++-- tests/out/glsl/skybox.fs_main.Fragment.glsl | 2 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 2 +- 9 files changed, 29 insertions(+), 18 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5a5b879da..ffb0c2b36 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -101,9 +101,14 @@ impl Version { } } - /// Checks if the version supports explicit `layout(location=)` qualifiers. + /// Checks if the version supports all of the explicit layouts: + /// - `location=` qualifiers for bindings + /// - `binding=` qualifiers for resources + /// + /// Note: `location=` for vertex inputs and fragment outputs is supported + /// unconditionally for GLES 300. fn supports_explicit_locations(&self) -> bool { - *self >= Version::Embedded(300) || *self >= Version::Desktop(410) + *self >= Version::Embedded(310) || *self >= Version::Desktop(410) } } @@ -865,19 +870,21 @@ impl<'a, W: Write> Writer<'a, W> { ShaderStage::Fragment => !output, _ => false, }; + + // Write the I/O locations, if allowed + if self.options.version.supports_explicit_locations() + || !emit_interpolation_and_auxiliary + { + write!(self.out, "layout(location = {}) ", location)?; + } + + // Write the interpolation qualifier. if let Some(interp) = interpolation { if emit_interpolation_and_auxiliary { write!(self.out, "{} ", glsl_interpolation(interp))?; } } - // Write the storage class - if !emit_interpolation_and_auxiliary - && self.options.version.supports_explicit_locations() - { - write!(self.out, "layout(location = {}) ", location)?; - } - // Write the sampling auxiliary qualifier. // // Before GLSL 4.2, the `centroid` and `sample` qualifiers were required to appear diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index a049e71aa..aca1da9b9 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -2,4 +2,9 @@ spv_version: (1, 0), spv_debug: true, spv_adjust_coordinate_space: true, + glsl: ( + version: Embedded(300), + writer_flags: (bits: 0), + binding_map: {}, + ), ) diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index b60099c18..b1b05b722 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -25,7 +25,7 @@ vec2 a_pos1 = vec2(0, 0); layout(location = 1) in vec2 _p2vs_location1; layout(location = 0) in vec2 _p2vs_location0; -smooth out vec2 _vs2fs_location0; +layout(location = 0) smooth out vec2 _vs2fs_location0; void main2() { vec2 _expr12 = a_uv1; diff --git a/tests/out/glsl/quad.fs_extra.Fragment.glsl b/tests/out/glsl/quad.fs_extra.Fragment.glsl index 2556b28d8..b5f2bea37 100644 --- a/tests/out/glsl/quad.fs_extra.Fragment.glsl +++ b/tests/out/glsl/quad.fs_extra.Fragment.glsl @@ -1,4 +1,4 @@ -#version 310 es +#version 300 es precision highp float; diff --git a/tests/out/glsl/quad.main.Fragment.glsl b/tests/out/glsl/quad.main.Fragment.glsl index 4ad470b3e..7f1fda42e 100644 --- a/tests/out/glsl/quad.main.Fragment.glsl +++ b/tests/out/glsl/quad.main.Fragment.glsl @@ -1,4 +1,4 @@ -#version 310 es +#version 300 es precision highp float; diff --git a/tests/out/glsl/quad.main.Vertex.glsl b/tests/out/glsl/quad.main.Vertex.glsl index cde8ac8d4..e6935cfa6 100644 --- a/tests/out/glsl/quad.main.Vertex.glsl +++ b/tests/out/glsl/quad.main.Vertex.glsl @@ -1,4 +1,4 @@ -#version 310 es +#version 300 es precision highp float; @@ -17,7 +17,6 @@ void main() { VertexOutput _tmp_return = VertexOutput(uv, vec4((1.2 * pos), 0.0, 1.0)); _vs2fs_location0 = _tmp_return.uv; gl_Position = _tmp_return.position; - gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; } diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index dffc97416..2f63f6c6f 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -18,8 +18,8 @@ readonly buffer Lights_block_1 { uniform highp sampler2DArrayShadow _group_0_binding_2; -smooth in vec3 _vs2fs_location0; -smooth in vec4 _vs2fs_location1; +layout(location = 0) smooth in vec3 _vs2fs_location0; +layout(location = 1) smooth in vec4 _vs2fs_location1; layout(location = 0) out vec4 _fs2p_location0; float fetch_shadow(uint light_id, vec4 homogeneous_coords) { diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index c75b0abb0..4495eb478 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -9,7 +9,7 @@ struct VertexOutput { layout(binding = 0) uniform highp samplerCube _group_0_binding_1; -smooth in vec3 _vs2fs_location0; +layout(location = 0) smooth in vec3 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index c1b423fc6..ccdac1e4d 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -12,7 +12,7 @@ layout(binding = 0) uniform Data_block_0 { mat4x4 view; } _group_0_binding_0; -smooth out vec3 _vs2fs_location0; +layout(location = 0) smooth out vec3 _vs2fs_location0; void main() { uint vertex_index = uint(gl_VertexID); From 337e40a2bea4f5d9ab3f4faae639877f3c396f24 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 16 Jul 2021 20:09:48 -0700 Subject: [PATCH 1117/2212] Enable logging in WGSL and SPIR-V tests. (#1098) Use env_logger::try_init to avoid complaints about repeated initialization. This function is thread-safe. --- tests/snapshots.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 74de68f34..932ebb35e 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -324,6 +324,8 @@ fn write_output_wgsl( #[cfg(feature = "wgsl-in")] #[test] fn convert_wgsl() { + let _ = env_logger::try_init(); + let root = env!("CARGO_MANIFEST_DIR"); let inputs = [ ( @@ -407,6 +409,8 @@ fn convert_wgsl() { #[cfg(feature = "spv-in")] fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { + let _ = env_logger::try_init(); + let root = env!("CARGO_MANIFEST_DIR"); let module = naga::front::spv::parse_u8_slice( &fs::read(format!("{}/{}/spv/{}.spv", root, BASE_DIR_IN, name)) @@ -453,7 +457,7 @@ fn convert_spv_pointer_access() { #[allow(unused_variables)] #[test] fn convert_glsl_folder() { - env_logger::init(); + let _ = env_logger::try_init(); let root = env!("CARGO_MANIFEST_DIR"); From 8f71a368eff3a18fd348ab6193cb183df0f49f95 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 16 Jul 2021 23:56:15 -0400 Subject: [PATCH 1118/2212] Validate the exact MSL version (#1101) --- Makefile | 3 ++- src/back/msl/mod.rs | 2 +- src/back/msl/writer.rs | 5 +++++ tests/in/extra.param.ron | 8 ++++++++ tests/out/msl/access.msl | 1 + tests/out/msl/boids.msl | 1 + tests/out/msl/collatz.msl | 1 + tests/out/msl/control-flow.msl | 1 + tests/out/msl/empty.msl | 1 + tests/out/msl/extra.msl | 1 + tests/out/msl/globals.msl | 1 + tests/out/msl/image.msl | 1 + tests/out/msl/interface.msl | 1 + tests/out/msl/interpolate.msl | 1 + tests/out/msl/operators.msl | 1 + tests/out/msl/quad-vert.msl | 1 + tests/out/msl/quad.msl | 1 + tests/out/msl/shadow.msl | 1 + tests/out/msl/skybox.msl | 1 + tests/out/msl/standard.msl | 1 + tests/out/msl/texture-arg.msl | 1 + 21 files changed, 33 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 380bca01f..3d8946235 100644 --- a/Makefile +++ b/Makefile @@ -35,7 +35,8 @@ validate-spv: $(SNAPSHOTS_BASE_OUT)/spv/*.spvasm validate-msl: $(SNAPSHOTS_BASE_OUT)/msl/*.msl @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ - cat $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.15 -x metal - -o /dev/null; \ + header=$$(head -n1 $${file}); \ + cat $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -std=macos-$${header:13:8} -x metal - -o /dev/null; \ done validate-glsl: $(SNAPSHOTS_BASE_OUT)/glsl/*.glsl diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 3277991b3..6bc2b4052 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -189,7 +189,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { Options { - lang_version: (1, 0), + lang_version: (1, 1), per_stage_map: PerStageMap::default(), inline_samplers: Vec::new(), spirv_cross_compatibility: false, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index cfa034b6d..5634b60a6 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1573,6 +1573,11 @@ impl Writer { .reset(module, super::keywords::RESERVED, &[], &mut self.names); self.runtime_sized_buffers.clear(); + writeln!( + self.out, + "// language: metal{}.{}", + options.lang_version.0, options.lang_version.1 + )?; writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; writeln!(self.out)?; diff --git a/tests/in/extra.param.ron b/tests/in/extra.param.ron index a0c5c775e..653d7f035 100644 --- a/tests/in/extra.param.ron +++ b/tests/in/extra.param.ron @@ -1,4 +1,12 @@ ( god_mode: true, spv_version: (1, 0), + msl_custom: true, + msl: ( + lang_version: (2, 2), + per_stage_map: (), + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + ), ) diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index a7abce8b4..fbde9f3d7 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -1,3 +1,4 @@ +// language: metal2.0 #include #include diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index e51ac6309..ef9d6d710 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -1,3 +1,4 @@ +// language: metal2.0 #include #include diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index d687ae310..b3053e6c5 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index d7afd08cf..ef3b1eee2 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/empty.msl b/tests/out/msl/empty.msl index 9b4ad4862..b918cf431 100644 --- a/tests/out/msl/empty.msl +++ b/tests/out/msl/empty.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/extra.msl b/tests/out/msl/extra.msl index a568e14fa..a2613a6e0 100644 --- a/tests/out/msl/extra.msl +++ b/tests/out/msl/extra.msl @@ -1,3 +1,4 @@ +// language: metal2.2 #include #include diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 435c090f2..7fcd970bb 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 819818011..6d21aa989 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 67b51a83e..efa936167 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl index baec86cae..f2600ba13 100644 --- a/tests/out/msl/interpolate.msl +++ b/tests/out/msl/interpolate.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 62ca17b3f..a7e691d5a 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index 6a3039ed2..ef2264a13 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl index f0fa35dab..9811ae517 100644 --- a/tests/out/msl/quad.msl +++ b/tests/out/msl/quad.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 30c4754a7..60a9a023d 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index feec800e7..1a479a89e 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -1,3 +1,4 @@ +// language: metal2.1 #include #include diff --git a/tests/out/msl/standard.msl b/tests/out/msl/standard.msl index c102b47f7..cf7adc7d6 100644 --- a/tests/out/msl/standard.msl +++ b/tests/out/msl/standard.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include diff --git a/tests/out/msl/texture-arg.msl b/tests/out/msl/texture-arg.msl index f958f527f..39919e06d 100644 --- a/tests/out/msl/texture-arg.msl +++ b/tests/out/msl/texture-arg.msl @@ -1,3 +1,4 @@ +// language: metal1.1 #include #include From c7dd717b4c34c1794aa545643e1c7b03d494de67 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Fri, 16 Jul 2021 22:19:11 -0700 Subject: [PATCH 1119/2212] wgsl: Don't output interpolate(flat) for non-float arguments (#1103) --- src/back/wgsl/writer.rs | 21 +++++++++++++-------- tests/out/wgsl/interpolate.wgsl | 2 +- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 8cfafd122..41039a609 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -203,7 +203,7 @@ impl Writer { for (index, arg) in func.arguments.iter().enumerate() { // Write argument attribute if a binding is present if let Some(ref binding) = arg.binding { - self.write_attributes(&map_binding_to_attribute(binding), false)?; + self.write_attributes(&map_binding_to_attribute(binding, module.types[arg.ty].inner.scalar_kind()), false)?; write!(self.out, " ")?; } // Write argument name @@ -231,7 +231,7 @@ impl Writer { if let Some(ref result) = func.result { write!(self.out, " -> ")?; if let Some(ref binding) = result.binding { - self.write_attributes(&map_binding_to_attribute(binding), true)?; + self.write_attributes(&map_binding_to_attribute(binding, module.types[result.ty].inner.scalar_kind()), true)?; } self.write_type(module, result.ty)?; } @@ -400,7 +400,7 @@ impl Writer { // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; if let Some(ref binding) = member.binding { - self.write_attributes(&map_binding_to_attribute(binding), true)?; + self.write_attributes(&map_binding_to_attribute(binding, module.types[member.ty].inner.scalar_kind()), true)?; } // Write struct member name and type let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; @@ -1580,17 +1580,22 @@ fn storage_class_str(storage_class: crate::StorageClass) -> Option<&'static str> } } -fn map_binding_to_attribute(binding: &crate::Binding) -> Vec { +fn map_binding_to_attribute(binding: &crate::Binding, scalar_kind: Option) -> Vec { match *binding { crate::Binding::BuiltIn(built_in) => vec![Attribute::BuiltIn(built_in)], crate::Binding::Location { location, interpolation, sampling, - } => vec![ - Attribute::Location(location), - Attribute::Interpolate(interpolation, sampling), - ], + } => match scalar_kind { + Some(crate::ScalarKind::Float) => vec![ + Attribute::Location(location), + Attribute::Interpolate(interpolation, sampling), + ], + _ => vec![ + Attribute::Location(location), + ], + }, } } diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index b0b2a9eb1..cf1a3824c 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -1,6 +1,6 @@ struct FragmentInput { [[builtin(position)]] position: vec4; - [[location(0), interpolate(flat)]] flat: u32; + [[location(0)]] flat: u32; [[location(1), interpolate(linear)]] linear: f32; [[location(2), interpolate(linear, centroid)]] linear_centroid: vec2; [[location(3), interpolate(linear, sample)]] linear_sample: vec3; From 2a253ab8382864ecb81ac7e0d394fa74e1318be8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 17 Jul 2021 22:38:04 -0400 Subject: [PATCH 1120/2212] hlsl-out: derive register based on storage class --- src/back/hlsl/writer.rs | 20 +++++++------ src/back/wgsl/writer.rs | 24 +++++++++++----- tests/out/hlsl/skybox.hlsl | 47 +++++++++++++++++++++++++++++++ tests/out/hlsl/skybox.hlsl.config | 4 +++ tests/snapshots.rs | 2 +- 5 files changed, 81 insertions(+), 16 deletions(-) create mode 100644 tests/out/hlsl/skybox.hlsl create mode 100644 tests/out/hlsl/skybox.hlsl.config diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 2e80a0803..5b1697c63 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -294,18 +294,22 @@ impl<'a, W: Write> Writer<'a, W> { let global = &module.global_variables[handle]; let inner = &module.types[global.ty].inner; - let (storage, register_ty) = match *inner { - TypeInner::Image { .. } => { - if global.storage_access.contains(crate::StorageAccess::STORE) { + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register + let (storage, register_ty) = match global.class { + crate::StorageClass::Function => unreachable!("Function storage class"), + crate::StorageClass::Private => ("static ", ""), + crate::StorageClass::WorkGroup => ("shared ", ""), + crate::StorageClass::Uniform => ("", "b"), + crate::StorageClass::Storage | crate::StorageClass::Handle => { + if let TypeInner::Sampler { .. } = *inner { + ("", "s") + } else if global.storage_access.contains(crate::StorageAccess::STORE) { ("RW", "u") } else { ("", "t") } } - TypeInner::Sampler { .. } => ("", "s"), - TypeInner::Struct { .. } | TypeInner::Vector { .. } => ("static ", ""), - // TODO: other register ty https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register - _ => return Err(Error::Unimplemented(format!("register_ty {:?}", inner))), + crate::StorageClass::PushConstant => unimplemented!("Push constants"), }; write!(self.out, "{}", storage)?; @@ -405,7 +409,7 @@ impl<'a, W: Write> Writer<'a, W> { _ => unreachable!(), } } - crate::ArraySize::Dynamic => (), + crate::ArraySize::Dynamic => write!(self.out, "1")?, } write!(self.out, "]")?; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 41039a609..8922f9358 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -203,7 +203,10 @@ impl Writer { for (index, arg) in func.arguments.iter().enumerate() { // Write argument attribute if a binding is present if let Some(ref binding) = arg.binding { - self.write_attributes(&map_binding_to_attribute(binding, module.types[arg.ty].inner.scalar_kind()), false)?; + self.write_attributes( + &map_binding_to_attribute(binding, module.types[arg.ty].inner.scalar_kind()), + false, + )?; write!(self.out, " ")?; } // Write argument name @@ -231,7 +234,10 @@ impl Writer { if let Some(ref result) = func.result { write!(self.out, " -> ")?; if let Some(ref binding) = result.binding { - self.write_attributes(&map_binding_to_attribute(binding, module.types[result.ty].inner.scalar_kind()), true)?; + self.write_attributes( + &map_binding_to_attribute(binding, module.types[result.ty].inner.scalar_kind()), + true, + )?; } self.write_type(module, result.ty)?; } @@ -400,7 +406,10 @@ impl Writer { // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; if let Some(ref binding) = member.binding { - self.write_attributes(&map_binding_to_attribute(binding, module.types[member.ty].inner.scalar_kind()), true)?; + self.write_attributes( + &map_binding_to_attribute(binding, module.types[member.ty].inner.scalar_kind()), + true, + )?; } // Write struct member name and type let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; @@ -1580,7 +1589,10 @@ fn storage_class_str(storage_class: crate::StorageClass) -> Option<&'static str> } } -fn map_binding_to_attribute(binding: &crate::Binding, scalar_kind: Option) -> Vec { +fn map_binding_to_attribute( + binding: &crate::Binding, + scalar_kind: Option, +) -> Vec { match *binding { crate::Binding::BuiltIn(built_in) => vec![Attribute::BuiltIn(built_in)], crate::Binding::Location { @@ -1592,9 +1604,7 @@ fn map_binding_to_attribute(binding: &crate::Binding, scalar_kind: Option vec![ - Attribute::Location(location), - ], + _ => vec![Attribute::Location(location)], }, } } diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl new file mode 100644 index 000000000..2d2220a09 --- /dev/null +++ b/tests/out/hlsl/skybox.hlsl @@ -0,0 +1,47 @@ +struct VertexOutput { + float4 position : SV_Position; + linear float3 uv : LOC0; +}; + +struct Data { + float4x4 proj_inv; + float4x4 view; +}; + +Data r_data : register(b0); +TextureCube r_texture : register(t1); +SamplerState r_sampler : register(s2); + +struct VertexInput_vs_main { + uint vertex_index1 : SV_VertexID; +}; + +struct FragmentInput_fs_main { + VertexOutput in2; +}; + +VertexOutput vs_main(VertexInput_vs_main vertexinput_vs_main) +{ + int tmp1_ = (int)0; + int tmp2_ = (int)0; + + tmp1_ = (int(vertexinput_vs_main.vertex_index1) / 2); + tmp2_ = (int(vertexinput_vs_main.vertex_index1) & 1); + int _expr10 = tmp1_; + int _expr16 = tmp2_; + float4 pos = float4((mul(float(_expr10), 4.0) - 1.0), (mul(float(_expr16), 4.0) - 1.0), 0.0, 1.0); + float4 _expr27 = r_data.view[0]; + float4 _expr31 = r_data.view[1]; + float4 _expr35 = r_data.view[2]; + float3x3 inv_model_view = transpose(float3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz)); + float4x4 _expr40 = r_data.proj_inv; + float4 unprojected = mul(_expr40, pos); + const VertexOutput vertexoutput1 = { pos, mul(inv_model_view, unprojected.xyz) }; + return vertexoutput1; +} + +float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 +{ + float4 _expr5 = r_texture.Sample(r_sampler, fragmentinput_fs_main.in2.uv); + return _expr5; +} diff --git a/tests/out/hlsl/skybox.hlsl.config b/tests/out/hlsl/skybox.hlsl.config new file mode 100644 index 000000000..43702adbc --- /dev/null +++ b/tests/out/hlsl/skybox.hlsl.config @@ -0,0 +1,4 @@ +vertex=vs_5_0 +vertex_name=vs_main +fragment=ps_5_0 +fragment_name=fs_main diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 932ebb35e..e634ee851 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -347,7 +347,7 @@ fn convert_wgsl() { ), ( "skybox", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "collatz", From 51fb9bb77afb919ac712eef566537453fe3877e1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 18 Jul 2021 00:10:19 -0400 Subject: [PATCH 1121/2212] hlsl-out: remap bindings --- src/back/hlsl/mod.rs | 58 +++++++++++++++++++++++++++++---- src/back/hlsl/writer.rs | 68 ++++++++++++++++++++++++++++++++------- tests/in/skybox.param.ron | 1 + tests/snapshots.rs | 41 ++++++++++++++++++----- 4 files changed, 142 insertions(+), 26 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index dc98bf85d..f6ab3450d 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -15,9 +15,22 @@ use thiserror::Error; pub use writer::Writer; +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct BindTarget { + pub space: u8, + pub register: u8, +} + +// Using `BTreeMap` instead of `HashMap` so that we can hash itself. +pub type BindingMap = std::collections::BTreeMap; + /// A HLSL shader model version. #[allow(non_snake_case, non_camel_case_types)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum ShaderModel { V5_0, V5_1, @@ -44,28 +57,61 @@ impl crate::ShaderStage { } } +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub enum EntryPointError { + #[error("mapping of {0:?} is missing")] + MissingBinding(crate::ResourceBinding), +} + /// Structure that contains the configuration used in the [`Writer`](Writer) -#[derive(Debug, Clone)] +#[derive(Clone, Debug, Hash, PartialEq, Eq)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Options { /// The hlsl shader model to be used pub shader_model: ShaderModel, + /// Map of resources association to binding locations. + pub binding_map: BindingMap, + /// Don't panic on missing bindings, instead generate any HLSL. + pub fake_missing_bindings: bool, } impl Default for Options { fn default() -> Self { Options { shader_model: ShaderModel::V5_0, + binding_map: BindingMap::default(), + fake_missing_bindings: true, + } + } +} + +impl Options { + fn resolve_resource_binding( + &self, + res_binding: &crate::ResourceBinding, + ) -> Result { + match self.binding_map.get(res_binding) { + Some(target) => Ok(target.clone()), + None if self.fake_missing_bindings => Ok(BindTarget { + space: res_binding.group as u8, + register: res_binding.binding as u8, + }), + None => Err(EntryPointError::MissingBinding(res_binding.clone())), } } } /// Structure that contains a reflection info pub struct ReflectionInfo { - /// Real name of entry point allowed by the `hlsl` compiler. - /// For example: - /// the entry point with the name `line` is valid for `wgsl`, but not valid for `hlsl`, because `line` is a reserved keyword. - pub entry_points: Vec, - // TODO: locations + /// Mapping of the entry point names. Each item in the array + /// corresponds to an entry point index. The real entry point name may be different if one of the + /// reserved words are used. + /// + ///Note: Some entry points may fail translation because of missing bindings. + pub entry_point_names: Vec>, } #[derive(Error, Debug)] diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 5b1697c63..6949b5aef 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -64,7 +64,7 @@ impl<'a, W: Write> Writer<'a, W> { pub fn write( &mut self, module: &Module, - info: &valid::ModuleInfo, + module_info: &valid::ModuleInfo, ) -> Result { self.reset(module); @@ -144,7 +144,31 @@ impl<'a, W: Write> Writer<'a, W> { // Write all regular functions for (handle, function) in module.functions.iter() { - let info = &info[handle]; + let info = &module_info[handle]; + + // Check if all of the globals are accessible + if !self.options.fake_missing_bindings { + if let Some((var_handle, _)) = + module + .global_variables + .iter() + .find(|&(var_handle, var)| match var.binding { + Some(ref binding) if !info[var_handle].is_empty() => { + self.options.resolve_resource_binding(binding).is_err() + } + _ => false, + }) + { + log::info!( + "Skipping function {:?} (name {:?}) because global {:?} is inaccessible", + handle, + function.name, + var_handle + ); + continue; + } + } + let ctx = back::FunctionCtx { ty: back::FunctionType::Function(handle), info, @@ -161,13 +185,34 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out)?; } - let mut entry_points_info = Vec::with_capacity(module.entry_points.len()); + let mut entry_point_names = Vec::with_capacity(module.entry_points.len()); // Write all entry points for (index, ep) in module.entry_points.iter().enumerate() { + let info = module_info.get_entry_point(index); + + if !self.options.fake_missing_bindings { + let mut ep_error = None; + for (var_handle, var) in module.global_variables.iter() { + match var.binding { + Some(ref binding) if !info[var_handle].is_empty() => { + if let Err(err) = self.options.resolve_resource_binding(binding) { + ep_error = Some(err); + break; + } + } + _ => {} + } + } + if let Some(err) = ep_error { + entry_point_names.push(Err(err)); + continue; + } + } + let ctx = back::FunctionCtx { ty: back::FunctionType::EntryPoint(index as u16), - info: info.get_entry_point(index), + info, expressions: &ep.function.expressions, named_expressions: &ep.function.named_expressions, }; @@ -176,7 +221,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_wrapped_image_query_functions(module, &ctx)?; if ep.stage == ShaderStage::Compute { - // HLSL is calling workgroup size, num threads + // HLSL is calling workgroup size "num threads" let num_threads = ep.workgroup_size; writeln!( self.out, @@ -186,19 +231,16 @@ impl<'a, W: Write> Writer<'a, W> { } let name = self.names[&NameKey::EntryPoint(index as u16)].clone(); - self.write_function(module, &name, &ep.function, &ctx)?; if index < module.entry_points.len() - 1 { writeln!(self.out)?; } - entry_points_info.push(name); + entry_point_names.push(Ok(name)); } - Ok(super::ReflectionInfo { - entry_points: entry_points_info, - }) + Ok(super::ReflectionInfo { entry_point_names }) } fn write_semantic( @@ -324,9 +366,11 @@ impl<'a, W: Write> Writer<'a, W> { )?; if let Some(ref binding) = global.binding { - write!(self.out, " : register({}{}", register_ty, binding.binding)?; + // this was already resolved earlier when we started evaluating an entry point. + let bt = self.options.resolve_resource_binding(binding).unwrap(); + write!(self.out, " : register({}{}", register_ty, bt.register)?; if self.options.shader_model > super::ShaderModel::V5_0 { - write!(self.out, ", space{}", binding.group)?; + write!(self.out, ", space{}", bt.space)?; } writeln!(self.out, ");")?; } else { diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 66899e280..03e56dde9 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -44,4 +44,5 @@ (group: 0, binding: 1): 0, }, ), + hlsl_custom: true, ) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e634ee851..da5bd5047 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -64,6 +64,12 @@ struct Parameters { #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] #[serde(default)] glsl_comp_ep_name: Option, + #[cfg(all(feature = "deserialize", feature = "hlsl-out"))] + #[serde(default)] + hlsl: naga::back::hlsl::Options, + #[cfg(all(not(feature = "deserialize"), feature = "hlsl-out"))] + #[serde(default)] + hlsl_custom: bool, } #[allow(dead_code, unused_variables)] @@ -131,7 +137,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "hlsl-out")] { if targets.contains(Targets::HLSL) { - write_output_hlsl(module, &info, &dest, name); + write_output_hlsl(module, &info, &dest, name, ¶ms); } } #[cfg(feature = "wgsl-out")] @@ -271,11 +277,25 @@ fn write_output_hlsl( info: &naga::valid::ModuleInfo, destination: &PathBuf, file_name: &str, + params: &Parameters, ) { use naga::back::hlsl; + use std::fmt::Write; + + #[cfg_attr(feature = "deserialize", allow(unused_variables))] + let default_options = hlsl::Options::default(); + #[cfg(feature = "deserialize")] + let options = ¶ms.hlsl; + #[cfg(not(feature = "deserialize"))] + let options = if params.hlsl_custom { + println!("Skipping {}", destination.display()); + return; + } else { + &default_options + }; + let mut buffer = String::new(); - let options = hlsl::Options::default(); - let mut writer = hlsl::Writer::new(&mut buffer, &options); + let mut writer = hlsl::Writer::new(&mut buffer, options); let reflection_info = writer.write(module, info).unwrap(); fs::write(destination.join(format!("hlsl/{}.hlsl", file_name)), buffer).unwrap(); @@ -283,22 +303,27 @@ fn write_output_hlsl( // We need a config file for validation script // This file contains an info about profiles (shader stages) contains inside generated shader // This info will be passed to dxc - let mut config_str = String::from(""); + let mut config_str = String::new(); for (index, ep) in module.entry_points.iter().enumerate() { + let name = match reflection_info.entry_point_names[index] { + Ok(ref name) => name, + Err(_) => continue, + }; let stage_str = match ep.stage { naga::ShaderStage::Vertex => "vertex", naga::ShaderStage::Fragment => "fragment", naga::ShaderStage::Compute => "compute", }; - config_str = format!( - "{}{}={}_{}\n{}_name={}\n", + writeln!( config_str, + "{}={}_{}\n{}_name={}", stage_str, ep.stage.to_hlsl_str(), options.shader_model.to_str(), stage_str, - &reflection_info.entry_points[index] - ); + name, + ) + .unwrap(); } fs::write( destination.join(format!("hlsl/{}.hlsl.config", file_name)), From 0d94b76d1ebe8cbd5cc22f93c38332629863c7d8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 18 Jul 2021 01:29:41 -0400 Subject: [PATCH 1122/2212] hlsl-out: rewrite texture coordinate construction --- src/back/hlsl/image.rs | 56 +++++++++- src/back/hlsl/writer.rs | 168 +++++++++++------------------- tests/out/hlsl/shadow.hlsl | 65 ++++++++++++ tests/out/hlsl/shadow.hlsl.config | 2 + tests/snapshots.rs | 2 +- 5 files changed, 183 insertions(+), 110 deletions(-) create mode 100644 tests/out/hlsl/shadow.hlsl create mode 100644 tests/out/hlsl/shadow.hlsl.config diff --git a/src/back/hlsl/image.rs b/src/back/hlsl/image.rs index fe87ac1af..85d5791da 100644 --- a/src/back/hlsl/image.rs +++ b/src/back/hlsl/image.rs @@ -21,6 +21,8 @@ // int dim_1d = NagaDimensions1D(image_1d); // ``` +use super::{super::FunctionCtx, writer::BackendResult}; +use crate::arena::Handle; use std::fmt::Write; #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] @@ -84,11 +86,18 @@ impl From for ImageQuery { } } +#[derive(Clone, Copy, PartialEq)] +pub(super) enum MipLevelCoordinate { + NotApplicable, + Zero, + Expression(Handle), +} + impl<'a, W: Write> super::Writer<'a, W> { pub(super) fn write_wrapped_image_query_function_name( &mut self, query: WrappedImageQuery, - ) -> super::writer::BackendResult { + ) -> BackendResult { let dim_str = super::writer::image_dimension_str(query.dim); let class_str = match query.class { crate::ImageClass::Sampled { multi: true, .. } => "MS", @@ -118,8 +127,8 @@ impl<'a, W: Write> super::Writer<'a, W> { pub(super) fn write_wrapped_image_query_functions( &mut self, module: &crate::Module, - func_ctx: &crate::back::FunctionCtx<'_>, - ) -> super::writer::BackendResult { + func_ctx: &FunctionCtx, + ) -> BackendResult { for (handle, _) in func_ctx.expressions.iter() { if let crate::Expression::ImageQuery { image, query } = func_ctx.expressions[handle] { let image_ty = func_ctx.info[image].ty.inner_with(&module.types); @@ -245,4 +254,45 @@ impl<'a, W: Write> super::Writer<'a, W> { Ok(()) } + + pub(super) fn write_texture_coordinates( + &mut self, + kind: &str, + coordinate: Handle, + array_index: Option>, + mip_level: MipLevelCoordinate, + module: &crate::Module, + func_ctx: &FunctionCtx, + ) -> BackendResult { + // HLSL expects the array index to be merged with the coordinate + let extra = array_index.is_some() as usize + + (mip_level != MipLevelCoordinate::NotApplicable) as usize; + if extra == 0 { + self.write_expr(module, coordinate, func_ctx)?; + } else { + let num_coords = match *func_ctx.info[coordinate].ty.inner_with(&module.types) { + crate::TypeInner::Scalar { .. } => 1, + crate::TypeInner::Vector { size, .. } => size as usize, + _ => unreachable!(), + }; + write!(self.out, "{}{}(", kind, num_coords + extra)?; + self.write_expr(module, coordinate, func_ctx)?; + if let Some(expr) = array_index { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + match mip_level { + MipLevelCoordinate::NotApplicable => {} + MipLevelCoordinate::Zero => { + write!(self.out, ", 0")?; + } + MipLevelCoordinate::Expression(expr) => { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + } + write!(self.out, ")")?; + } + Ok(()) + } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 6949b5aef..45d2ac7be 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,4 +1,7 @@ -use super::{Error, Options}; +use super::{ + image::{MipLevelCoordinate, WrappedImageQuery}, + Error, Options, +}; use crate::{ back, proc::{self, NameKey}, @@ -36,7 +39,7 @@ pub struct Writer<'a, W> { ep_inputs: Vec>, /// Set of expressions that have associated temporary variables named_expressions: crate::NamedExpressions, - pub(super) wrapped_image_queries: crate::FastHashSet, + pub(super) wrapped_image_queries: crate::FastHashSet, } impl<'a, W: Write> Writer<'a, W> { @@ -397,21 +400,20 @@ impl<'a, W: Write> Writer<'a, W> { handle: Handle, ) -> BackendResult { write!(self.out, "static const ")?; - match *inner { crate::ConstantInner::Scalar { width: _, ref value, } => { // Write type - match *value { - crate::ScalarValue::Sint(_) => write!(self.out, "int")?, - crate::ScalarValue::Uint(_) => write!(self.out, "uint")?, - crate::ScalarValue::Float(_) => write!(self.out, "float")?, - crate::ScalarValue::Bool(_) => write!(self.out, "bool")?, + let ty_str = match *value { + crate::ScalarValue::Sint(_) => "int", + crate::ScalarValue::Uint(_) => "uint", + crate::ScalarValue::Float(_) => "float", + crate::ScalarValue::Bool(_) => "bool", }; let name = &self.names[&NameKey::Constant(handle)]; - write!(self.out, " {} = ", name)?; + write!(self.out, "{} {} = ", ty_str, name)?; // Second match required to avoid heap allocation by `format!()` match *value { @@ -427,6 +429,8 @@ impl<'a, W: Write> Writer<'a, W> { } crate::ConstantInner::Composite { ty, ref components } => { self.write_type(module, ty)?; + let name = &self.names[&NameKey::Constant(handle)]; + write!(self.out, " {} = ", name)?; self.write_composite_constant(module, ty, components)?; } } @@ -1142,12 +1146,14 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ".{}(", texture_func)?; self.write_expr(module, sampler, func_ctx)?; write!(self.out, ", ")?; - self.write_expr(module, coordinate, func_ctx)?; - - if let Some(array_index) = array_index { - write!(self.out, ", ")?; - self.write_expr(module, array_index, func_ctx)?; - } + self.write_texture_coordinates( + "float", + coordinate, + array_index, + MipLevelCoordinate::NotApplicable, + module, + func_ctx, + )?; if let Some(depth_ref) = depth_ref { write!(self.out, ", ")?; @@ -1187,7 +1193,7 @@ impl<'a, W: Write> Writer<'a, W> { class, } = *func_ctx.info[image].ty.inner_with(&module.types) { - let wrapped_image_query = super::image::WrappedImageQuery { + let wrapped_image_query = WrappedImageQuery { dim, arrayed, class, @@ -1212,97 +1218,47 @@ impl<'a, W: Write> Writer<'a, W> { index, } => { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-load - let image_ty = func_ctx.info[image].ty.inner_with(&module.types); - if let crate::TypeInner::Image { - dim, - arrayed, - class, - } = *image_ty + let ms = match *func_ctx.info[image].ty.inner_with(&module.types) { + crate::TypeInner::Image { + class: crate::ImageClass::Sampled { multi, .. }, + .. + } => multi, + _ => false, + }; + + self.write_expr(module, image, func_ctx)?; + write!(self.out, ".Load(")?; + + let mip_level = if ms { + MipLevelCoordinate::NotApplicable + } else { + match index { + Some(expr) => MipLevelCoordinate::Expression(expr), + None => MipLevelCoordinate::Zero, + } + }; + + self.write_texture_coordinates( + "int", + coordinate, + array_index, + mip_level, + module, + func_ctx, + )?; + + if ms { + write!(self.out, ", ")?; + self.write_expr(module, index.unwrap(), func_ctx)?; + } + + // close bracket for Load function + write!(self.out, ")")?; + + // return x component if return type is scalar + if let TypeInner::Scalar { .. } = *func_ctx.info[expr].ty.inner_with(&module.types) { - use crate::ImageDimension as IDim; - - self.write_expr(module, image, func_ctx)?; - write!(self.out, ".Load(")?; - - let ms = if let crate::ImageClass::Sampled { multi: true, .. } = class { - true - } else { - false - }; - - // Input location type based on texture type - let (load_param_ty, load_components_count) = match dim { - IDim::D1 => { - if arrayed { - ("int3", 3) - } else { - ("int2", 2) - } - } - IDim::D2 => match (ms, arrayed) { - (true, true) => ("int3", 3), - (true, false) => ("int2", 2), - (false, true) => ("int4", 4), - (false, false) => ("int3", 3), - }, - IDim::D3 => ("int4", 4), - _ => unreachable!(), - }; - - let coordinate_expr_components_count = - match *func_ctx.info[coordinate].ty.inner_with(&module.types) { - TypeInner::Vector { size, .. } => size as i32, - TypeInner::Scalar { .. } => 1, - // coordinates can be only vector or scalar - _ => unreachable!(), - }; - - let components_count = { - let array_coords = if arrayed { 1 } else { 0 }; - let array_index_param = if array_index.is_some() { 1 } else { 0 }; - let sampler_index_param = if index.is_some() { 1 } else { 0 }; - - coordinate_expr_components_count - + array_coords - + array_index_param - + sampler_index_param - }; - - let is_ty_cast_required = - load_components_count > coordinate_expr_components_count; - - // cast to another type, if required - if is_ty_cast_required { - write!(self.out, "{}(", load_param_ty)?; - } - self.write_expr(module, coordinate, func_ctx)?; - if let Some(array_index) = array_index { - write!(self.out, ", ")?; - self.write_expr(module, array_index, func_ctx)?; - } - if let Some(index) = index { - write!(self.out, ", ")?; - self.write_expr(module, index, func_ctx)?; - } - if index.is_none() && components_count < load_components_count { - // write zero mipmap level if it's not provided but required - write!(self.out, ", 0")?; - }; - - if is_ty_cast_required { - // close bracket for type - write!(self.out, ")")?; - } - - // close bracket for Load function - write!(self.out, ")")?; - - // return x component if return type is scalar - if let TypeInner::Scalar { .. } = - *func_ctx.info[expr].ty.inner_with(&module.types) - { - write!(self.out, ".x")?; - } + write!(self.out, ".x")?; } } // TODO: copy-paste from wgsl-out diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl new file mode 100644 index 000000000..e123bebdd --- /dev/null +++ b/tests/out/hlsl/shadow.hlsl @@ -0,0 +1,65 @@ +static const float3 c_ambient = float3(0.05, 0.05, 0.05); + +static const uint c_max_lights = 10; + +struct Globals { + uint4 num_lights; +}; + +struct Light { + float4x4 proj; + float4 pos; + float4 color; +}; + +struct Lights { + Light data[1]; +}; + +Globals u_globals : register(b0); +Lights s_lights : register(t1); +Texture2DArray t_shadow : register(t2); +SamplerComparisonState sampler_shadow : register(s3); + +struct FragmentInput_fs_main { + float3 raw_normal1 : LOC0; + float4 position1 : LOC1; +}; + +float fetch_shadow(uint light_id, float4 homogeneous_coords) +{ + if ((homogeneous_coords.w <= 0.0)) { + return 1.0; + } + float2 flip_correction = float2(0.5, -0.5); + float2 light_local = ((mul(homogeneous_coords.xy, flip_correction) / float2(homogeneous_coords.w.xx)) + float2(0.5, 0.5)); + float _expr26 = t_shadow.SampleCmpLevelZero(sampler_shadow, float3(light_local, int(light_id)), (homogeneous_coords.z / homogeneous_coords.w)); + return _expr26; +} + +float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 +{ + float3 color = float3(0.05, 0.05, 0.05); + uint i = 0u; + + float3 normal = normalize(fragmentinput_fs_main.raw_normal1); + while(true) { + uint _expr12 = i; + uint4 _expr14 = u_globals.num_lights; + if ((_expr12 >= min(_expr14.x, c_max_lights))) { + break; + } + uint _expr19 = i; + Light light = s_lights.data[_expr19]; + uint _expr22 = i; + const float _e25 = fetch_shadow(_expr22, mul(light.proj, fragmentinput_fs_main.position1)); + float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz)); + float diffuse = max(0.0, dot(normal, light_dir)); + float3 _expr34 = color; + color = (_expr34 + mul(mul(_e25, diffuse), light.color.xyz)); + uint _expr40 = i; + i = (_expr40 + 1u); + } + float3 _expr43 = color; + return float4(_expr43, 1.0); +} diff --git a/tests/out/hlsl/shadow.hlsl.config b/tests/out/hlsl/shadow.hlsl.config new file mode 100644 index 000000000..5d17f4305 --- /dev/null +++ b/tests/out/hlsl/shadow.hlsl.config @@ -0,0 +1,2 @@ +fragment=ps_5_0 +fragment_name=fs_main diff --git a/tests/snapshots.rs b/tests/snapshots.rs index da5bd5047..cd2d317fc 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -380,7 +380,7 @@ fn convert_wgsl() { ), ( "shadow", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "image", From 16206f2eb27baf15963de9e1c75792f210033e23 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 18 Jul 2021 01:32:10 -0400 Subject: [PATCH 1123/2212] hlsl-out: unlock globals.wgsl test, override skybox bindings --- src/back/hlsl/image.rs | 2 +- src/back/hlsl/mod.rs | 11 +++++++++++ src/back/hlsl/writer.rs | 24 ++++++++---------------- tests/in/skybox.param.ron | 9 +++++++++ tests/out/hlsl/globals.hlsl | 10 ++++++++++ tests/out/hlsl/globals.hlsl.config | 2 ++ tests/out/hlsl/skybox.hlsl | 6 +++--- tests/out/hlsl/skybox.hlsl.config | 4 ++-- tests/snapshots.rs | 2 +- 9 files changed, 47 insertions(+), 23 deletions(-) create mode 100644 tests/out/hlsl/globals.hlsl create mode 100644 tests/out/hlsl/globals.hlsl.config diff --git a/src/back/hlsl/image.rs b/src/back/hlsl/image.rs index 85d5791da..67e940d2d 100644 --- a/src/back/hlsl/image.rs +++ b/src/back/hlsl/image.rs @@ -98,7 +98,7 @@ impl<'a, W: Write> super::Writer<'a, W> { &mut self, query: WrappedImageQuery, ) -> BackendResult { - let dim_str = super::writer::image_dimension_str(query.dim); + let dim_str = query.dim.to_hlsl_str(); let class_str = match query.class { crate::ImageClass::Sampled { multi: true, .. } => "MS", crate::ImageClass::Depth => "Depth", diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index f6ab3450d..e9f103036 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -57,6 +57,17 @@ impl crate::ShaderStage { } } +impl crate::ImageDimension { + fn to_hlsl_str(self) -> &'static str { + match self { + Self::D1 => "1D", + Self::D2 => "2D", + Self::D3 => "3D", + Self::Cube => "Cube", + } + } +} + #[derive(Clone, Debug, PartialEq, thiserror::Error)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 45d2ac7be..245fb78e7 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -343,7 +343,7 @@ impl<'a, W: Write> Writer<'a, W> { let (storage, register_ty) = match global.class { crate::StorageClass::Function => unreachable!("Function storage class"), crate::StorageClass::Private => ("static ", ""), - crate::StorageClass::WorkGroup => ("shared ", ""), + crate::StorageClass::WorkGroup => ("groupshared ", ""), crate::StorageClass::Uniform => ("", "b"), crate::StorageClass::Storage | crate::StorageClass::Handle => { if let TypeInner::Sampler { .. } = *inner { @@ -359,14 +359,14 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}", storage)?; self.write_type(module, global.ty)?; - if let TypeInner::Array { size, .. } = module.types[global.ty].inner { - self.write_array_size(module, size)?; - } write!( self.out, " {}", &self.names[&NameKey::GlobalVariable(handle)] )?; + if let TypeInner::Array { size, .. } = module.types[global.ty].inner { + self.write_array_size(module, size)?; + } if let Some(ref binding) = global.binding { // this was already resolved earlier when we started evaluating an entry point. @@ -604,7 +604,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { use crate::ImageClass as Ic; - let dim_str = image_dimension_str(dim); + let dim_str = dim.to_hlsl_str(); let arrayed_str = if arrayed { "Array" } else { "" }; write!(self.out, "Texture{}{}", dim_str, arrayed_str)?; match class { @@ -1596,23 +1596,15 @@ impl<'a, W: Write> Writer<'a, W> { fn write_default_init(&mut self, module: &Module, ty: Handle) -> BackendResult { write!(self.out, "(")?; self.write_type(module, ty)?; + if let TypeInner::Array { size, .. } = module.types[ty].inner { + self.write_array_size(module, size)?; + } write!(self.out, ")0")?; Ok(()) } } -pub(super) fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { - use crate::ImageDimension as IDim; - - match dim { - IDim::D1 => "1D", - IDim::D2 => "2D", - IDim::D3 => "3D", - IDim::Cube => "Cube", - } -} - fn builtin_str(built_in: crate::BuiltIn) -> &'static str { use crate::BuiltIn as Bi; diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 03e56dde9..d21b3b852 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -45,4 +45,13 @@ }, ), hlsl_custom: true, + hlsl: ( + shader_model: V5_1, + binding_map: { + (group: 0, binding: 0): (space: 0, register: 0), + (group: 0, binding: 1): (space: 0, register: 0), + (group: 0, binding: 2): (space: 1, register: 0), + }, + fake_missing_bindings: false, + ), ) diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl new file mode 100644 index 000000000..9ae432588 --- /dev/null +++ b/tests/out/hlsl/globals.hlsl @@ -0,0 +1,10 @@ +static const bool Foo = true; + +groupshared float wg[10] = (float[10])0; + +[numthreads(1, 1, 1)] +void main() +{ + wg[3] = 1.0; + return; +} diff --git a/tests/out/hlsl/globals.hlsl.config b/tests/out/hlsl/globals.hlsl.config new file mode 100644 index 000000000..71412ac2d --- /dev/null +++ b/tests/out/hlsl/globals.hlsl.config @@ -0,0 +1,2 @@ +compute=cs_5_0 +compute_name=main diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 2d2220a09..283ab73b8 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -8,9 +8,9 @@ struct Data { float4x4 view; }; -Data r_data : register(b0); -TextureCube r_texture : register(t1); -SamplerState r_sampler : register(s2); +Data r_data : register(b0, space0); +TextureCube r_texture : register(t0, space0); +SamplerState r_sampler : register(s0, space1); struct VertexInput_vs_main { uint vertex_index1 : SV_VertexID; diff --git a/tests/out/hlsl/skybox.hlsl.config b/tests/out/hlsl/skybox.hlsl.config index 43702adbc..41df29cb7 100644 --- a/tests/out/hlsl/skybox.hlsl.config +++ b/tests/out/hlsl/skybox.hlsl.config @@ -1,4 +1,4 @@ -vertex=vs_5_0 +vertex=vs_5_1 vertex_name=vs_main -fragment=ps_5_0 +fragment=ps_5_1 fragment_name=fs_main diff --git a/tests/snapshots.rs b/tests/snapshots.rs index cd2d317fc..fb3369728 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -411,7 +411,7 @@ fn convert_wgsl() { ), ( "globals", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ("bounds-check-zero", Targets::SPIRV), ( From 39eaa57a77f64b7433df476abff3ce038224e54c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 18 Jul 2021 02:15:02 -0400 Subject: [PATCH 1124/2212] hlsl-out: implement constant buffer support --- src/back/hlsl/writer.rs | 27 ++++++++++++++++++--------- tests/out/hlsl/globals.hlsl | 2 +- tests/out/hlsl/shadow.hlsl | 2 +- tests/out/hlsl/skybox.hlsl | 2 +- 4 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 245fb78e7..64055a698 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -344,7 +344,7 @@ impl<'a, W: Write> Writer<'a, W> { crate::StorageClass::Function => unreachable!("Function storage class"), crate::StorageClass::Private => ("static ", ""), crate::StorageClass::WorkGroup => ("groupshared ", ""), - crate::StorageClass::Uniform => ("", "b"), + crate::StorageClass::Uniform => ("cbuffer", "b"), crate::StorageClass::Storage | crate::StorageClass::Handle => { if let TypeInner::Sampler { .. } = *inner { ("", "s") @@ -358,12 +358,13 @@ impl<'a, W: Write> Writer<'a, W> { }; write!(self.out, "{}", storage)?; - self.write_type(module, global.ty)?; - write!( - self.out, - " {}", - &self.names[&NameKey::GlobalVariable(handle)] - )?; + // constant buffer declarations are expected to be inlined, e.g. + // cbuffer foo: register(b0) { field1: type1; }; + if global.class != crate::StorageClass::Uniform { + self.write_type(module, global.ty)?; + } + let name = &self.names[&NameKey::GlobalVariable(handle)]; + write!(self.out, " {}", name)?; if let TypeInner::Array { size, .. } = module.types[global.ty].inner { self.write_array_size(module, size)?; } @@ -375,14 +376,22 @@ impl<'a, W: Write> Writer<'a, W> { if self.options.shader_model > super::ShaderModel::V5_0 { write!(self.out, ", space{}", bt.space)?; } - writeln!(self.out, ");")?; - } else { + write!(self.out, ")")?; + } else if global.class == crate::StorageClass::Private { write!(self.out, " = ")?; if let Some(init) = global.init { self.write_constant(module, init)?; } else { self.write_default_init(module, global.ty)?; } + } + + if global.class == crate::StorageClass::Uniform { + write!(self.out, " {{ ")?; + self.write_type(module, global.ty)?; + let name = &self.names[&NameKey::GlobalVariable(handle)]; + writeln!(self.out, " {}; }}", name)?; + } else { writeln!(self.out, ";")?; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 9ae432588..0236e1827 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -1,6 +1,6 @@ static const bool Foo = true; -groupshared float wg[10] = (float[10])0; +groupshared float wg[10]; [numthreads(1, 1, 1)] void main() diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index e123bebdd..bcce7a0fd 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -16,7 +16,7 @@ struct Lights { Light data[1]; }; -Globals u_globals : register(b0); +cbuffer u_globals : register(b0) { Globals u_globals; } Lights s_lights : register(t1); Texture2DArray t_shadow : register(t2); SamplerComparisonState sampler_shadow : register(s3); diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 283ab73b8..6886185b6 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -8,7 +8,7 @@ struct Data { float4x4 view; }; -Data r_data : register(b0, space0); +cbuffer r_data : register(b0, space0) { Data r_data; } TextureCube r_texture : register(t0, space0); SamplerState r_sampler : register(s0, space1); From feee1a2edbcae2a9ad7d9cb39a71ae4e0a5578e9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 18 Jul 2021 11:33:36 -0400 Subject: [PATCH 1125/2212] hlsl-out: switch register to u32 --- src/back/hlsl/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index e9f103036..12bb8670d 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -20,7 +20,7 @@ pub use writer::Writer; #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct BindTarget { pub space: u8, - pub register: u8, + pub register: u32, } // Using `BTreeMap` instead of `HashMap` so that we can hash itself. @@ -108,7 +108,7 @@ impl Options { Some(target) => Ok(target.clone()), None if self.fake_missing_bindings => Ok(BindTarget { space: res_binding.group as u8, - register: res_binding.binding as u8, + register: res_binding.binding, }), None => Err(EntryPointError::MissingBinding(res_binding.clone())), } @@ -116,6 +116,7 @@ impl Options { } /// Structure that contains a reflection info +#[derive(Default)] pub struct ReflectionInfo { /// Mapping of the entry point names. Each item in the array /// corresponds to an entry point index. The real entry point name may be different if one of the From f3c753760974a31a4cdb257f91c73eecaa25147b Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 19 Jul 2021 12:47:22 -0700 Subject: [PATCH 1126/2212] Add tests for sampling mipmapped and multisampled images. Prior to this change, nothing in the test suite exercised the SPIR-V backend code for generating LOD or Sample arguments to OpImageFetch instructions. --- tests/in/image.wgsl | 14 +- tests/out/hlsl/image.hlsl | 14 +- tests/out/msl/image.msl | 18 +- tests/out/spv/image.spvasm | 426 +++++++++++++++++++------------------ tests/out/wgsl/image.wgsl | 14 +- 5 files changed, 264 insertions(+), 222 deletions(-) diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 67cddb4d4..5f1da997b 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -1,5 +1,9 @@ +[[group(0), binding(0)]] +var image_mipmapped_src: texture_2d; +[[group(0), binding(3)]] +var image_multisampled_src: texture_multisampled_2d; [[group(0), binding(1)]] -var image_src: [[access(read)]] texture_storage_2d; +var image_storage_src: [[access(read)]] texture_storage_2d; [[group(0), binding(2)]] var image_dst: [[access(write)]] texture_storage_1d; @@ -9,10 +13,12 @@ fn main( //TODO: https://github.com/gpuweb/gpuweb/issues/1590 //[[builtin(workgroup_size)]] wg_size: vec3 ) { - let dim = textureDimensions(image_src); + let dim = textureDimensions(image_storage_src); let itc = dim * vec2(local_id.xy) % vec2(10, 20); - let value = textureLoad(image_src, itc); - textureStore(image_dst, itc.x, value); + let value1 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); + let value2 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); + let value3 = textureLoad(image_storage_src, itc); + textureStore(image_dst, itc.x, value1 + value2 + value3); } [[group(0), binding(0)]] diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index f5f20b4ba..da460e4f8 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -1,4 +1,6 @@ -Texture2D image_src : register(t1); +Texture2D image_mipmapped_src : register(t0); +Texture2DMS image_multisampled_src : register(t3); +Texture2D image_storage_src : register(t1); RWTexture1D image_dst : register(u2); Texture1D image_1d : register(t0); Texture2D image_2d : register(t1); @@ -18,17 +20,19 @@ struct ComputeInput_main { int2 NagaDimensions2D(Texture2D) { uint4 ret; - image_src.GetDimensions(0, ret.x, ret.y, ret.z); + image_storage_src.GetDimensions(0, ret.x, ret.y, ret.z); return ret.xy; } [numthreads(16, 1, 1)] void main(ComputeInput_main computeinput_main) { - int2 dim = NagaDimensions2D(image_src); + int2 dim = NagaDimensions2D(image_storage_src); int2 itc = (mul(dim, int2(computeinput_main.local_id1.xy)) % int2(10, 20)); - uint4 value = image_src.Load(int3(itc, 0)); - image_dst[itc.x] = value; + uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(computeinput_main.local_id1.z))); + uint4 value2_ = image_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)); + uint4 value3_ = image_storage_src.Load(int3(itc, 0)); + image_dst[itc.x] = ((value1_ + value2_) + value3_); return; } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 6d21aa989..a480db346 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -2,19 +2,23 @@ #include #include -constant metal::int2 const_type3_ = {3, 1}; +constant metal::int2 const_type5_ = {3, 1}; struct main1Input { }; kernel void main1( metal::uint3 local_id [[thread_position_in_threadgroup]] -, metal::texture2d image_src [[user(fake0)]] +, metal::texture2d image_mipmapped_src [[user(fake0)]] +, metal::texture2d_ms image_multisampled_src [[user(fake0)]] +, metal::texture2d image_storage_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 dim = int2(image_src.get_width(), image_src.get_height()); + metal::int2 dim = int2(image_storage_src.get_width(), image_storage_src.get_height()); metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); - metal::uint4 value = image_src.read(metal::uint2(itc)); - image_dst.write(value, metal::uint(itc.x)); + metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); + metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); + metal::uint4 value3_ = image_storage_src.read(metal::uint2(itc)); + image_dst.write((value1_ + value2_) + value3_, metal::uint(itc.x)); return; } @@ -64,9 +68,9 @@ fragment sampleOutput sample( ) { metal::float2 tc = metal::float2(0.5); metal::float4 s2d = image_2d.sample(sampler_reg, tc); - metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type3_); + metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type5_); metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.3)); - metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type3_); + metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type5_); return sampleOutput { ((s2d + s2d_offset) + s2d_level) + s2d_level_offset }; } diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 5e77b27cf..6b788edd7 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,67 +1,73 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 174 +; Bound: 190 OpCapability Image1D OpCapability Shader OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %55 "main" %52 -OpEntryPoint Vertex %73 "queries" %71 -OpEntryPoint Fragment %141 "sample" %140 -OpEntryPoint Fragment %162 "sample_comparison" %160 -OpExecutionMode %55 LocalSize 16 1 1 -OpExecutionMode %141 OriginUpperLeft -OpExecutionMode %162 OriginUpperLeft +OpEntryPoint GLCompute %61 "main" %58 +OpEntryPoint Vertex %89 "queries" %87 +OpEntryPoint Fragment %157 "sample" %156 +OpEntryPoint Fragment %178 "sample_comparison" %176 +OpExecutionMode %61 LocalSize 16 1 1 +OpExecutionMode %157 OriginUpperLeft +OpExecutionMode %178 OriginUpperLeft OpSource GLSL 450 -OpName %27 "image_src" -OpName %29 "image_dst" -OpName %31 "image_1d" -OpName %33 "image_2d" -OpName %35 "image_2d_array" -OpName %37 "image_cube" -OpName %39 "image_cube_array" -OpName %41 "image_3d" -OpName %43 "image_aa" -OpName %45 "sampler_reg" -OpName %47 "sampler_cmp" -OpName %49 "image_2d_depth" -OpName %52 "local_id" -OpName %55 "main" -OpName %73 "queries" -OpName %141 "sample" -OpName %162 "sample_comparison" -OpDecorate %27 NonWritable -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 1 -OpDecorate %29 NonReadable +OpName %29 "image_mipmapped_src" +OpName %31 "image_multisampled_src" +OpName %33 "image_storage_src" +OpName %35 "image_dst" +OpName %37 "image_1d" +OpName %39 "image_2d" +OpName %41 "image_2d_array" +OpName %43 "image_cube" +OpName %45 "image_cube_array" +OpName %47 "image_3d" +OpName %49 "image_aa" +OpName %51 "sampler_reg" +OpName %53 "sampler_cmp" +OpName %55 "image_2d_depth" +OpName %58 "local_id" +OpName %61 "main" +OpName %89 "queries" +OpName %157 "sample" +OpName %178 "sample_comparison" OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 2 +OpDecorate %29 Binding 0 OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 0 +OpDecorate %31 Binding 3 +OpDecorate %33 NonWritable OpDecorate %33 DescriptorSet 0 OpDecorate %33 Binding 1 +OpDecorate %35 NonReadable OpDecorate %35 DescriptorSet 0 OpDecorate %35 Binding 2 OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 3 +OpDecorate %37 Binding 0 OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 4 +OpDecorate %39 Binding 1 OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 5 +OpDecorate %41 Binding 2 OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 6 -OpDecorate %45 DescriptorSet 1 -OpDecorate %45 Binding 0 -OpDecorate %47 DescriptorSet 1 -OpDecorate %47 Binding 1 -OpDecorate %49 DescriptorSet 1 -OpDecorate %49 Binding 2 -OpDecorate %52 BuiltIn LocalInvocationId -OpDecorate %71 BuiltIn Position -OpDecorate %140 Location 0 -OpDecorate %160 Location 0 +OpDecorate %43 Binding 3 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 4 +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 5 +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 6 +OpDecorate %51 DescriptorSet 1 +OpDecorate %51 Binding 0 +OpDecorate %53 DescriptorSet 1 +OpDecorate %53 Binding 1 +OpDecorate %55 DescriptorSet 1 +OpDecorate %55 Binding 2 +OpDecorate %58 BuiltIn LocalInvocationId +OpDecorate %87 BuiltIn Position +OpDecorate %156 Location 0 +OpDecorate %176 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -72,181 +78,197 @@ OpDecorate %160 Location 0 %9 = OpConstant %8 2.3 %10 = OpConstant %4 3 %12 = OpTypeInt 32 0 -%11 = OpTypeImage %12 2D 0 0 0 2 Rgba8ui -%13 = OpTypeImage %12 1D 0 0 0 2 R32ui -%14 = OpTypeVector %12 3 -%15 = OpTypeVector %4 2 -%16 = OpTypeImage %8 1D 0 0 0 1 Unknown -%17 = OpTypeImage %8 2D 0 0 0 1 Unknown -%18 = OpTypeImage %8 2D 0 1 0 1 Unknown -%19 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%20 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%21 = OpTypeImage %8 3D 0 0 0 1 Unknown -%22 = OpTypeImage %8 2D 0 0 1 1 Unknown -%23 = OpTypeVector %8 4 -%24 = OpTypeSampler -%25 = OpTypeImage %8 2D 1 0 0 1 Unknown -%26 = OpConstantComposite %15 %10 %6 -%28 = OpTypePointer UniformConstant %11 -%27 = OpVariable %28 UniformConstant -%30 = OpTypePointer UniformConstant %13 +%11 = OpTypeImage %12 2D 0 0 0 1 Unknown +%13 = OpTypeImage %12 2D 0 0 1 1 Unknown +%14 = OpTypeImage %12 2D 0 0 0 2 Rgba8ui +%15 = OpTypeImage %12 1D 0 0 0 2 R32ui +%16 = OpTypeVector %12 3 +%17 = OpTypeVector %4 2 +%18 = OpTypeImage %8 1D 0 0 0 1 Unknown +%19 = OpTypeImage %8 2D 0 0 0 1 Unknown +%20 = OpTypeImage %8 2D 0 1 0 1 Unknown +%21 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%22 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%23 = OpTypeImage %8 3D 0 0 0 1 Unknown +%24 = OpTypeImage %8 2D 0 0 1 1 Unknown +%25 = OpTypeVector %8 4 +%26 = OpTypeSampler +%27 = OpTypeImage %8 2D 1 0 0 1 Unknown +%28 = OpConstantComposite %17 %10 %6 +%30 = OpTypePointer UniformConstant %11 %29 = OpVariable %30 UniformConstant -%32 = OpTypePointer UniformConstant %16 +%32 = OpTypePointer UniformConstant %13 %31 = OpVariable %32 UniformConstant -%34 = OpTypePointer UniformConstant %17 +%34 = OpTypePointer UniformConstant %14 %33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %18 +%36 = OpTypePointer UniformConstant %15 %35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %19 +%38 = OpTypePointer UniformConstant %18 %37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %20 +%40 = OpTypePointer UniformConstant %19 %39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %21 +%42 = OpTypePointer UniformConstant %20 %41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %22 +%44 = OpTypePointer UniformConstant %21 %43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %24 +%46 = OpTypePointer UniformConstant %22 %45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %24 +%48 = OpTypePointer UniformConstant %23 %47 = OpVariable %48 UniformConstant -%50 = OpTypePointer UniformConstant %25 +%50 = OpTypePointer UniformConstant %24 %49 = OpVariable %50 UniformConstant -%53 = OpTypePointer Input %14 -%52 = OpVariable %53 Input -%56 = OpTypeFunction %2 -%61 = OpTypeVector %12 2 -%67 = OpTypeVector %12 4 -%72 = OpTypePointer Output %23 -%71 = OpVariable %72 Output -%82 = OpConstant %12 0 -%87 = OpTypeVector %4 3 -%140 = OpVariable %72 Output -%145 = OpTypeVector %8 2 -%147 = OpTypeSampledImage %17 -%161 = OpTypePointer Output %8 -%160 = OpVariable %161 Output -%167 = OpTypeSampledImage %25 -%172 = OpConstant %8 0.0 -%55 = OpFunction %2 None %56 -%51 = OpLabel -%54 = OpLoad %14 %52 -%57 = OpLoad %11 %27 -%58 = OpLoad %13 %29 -OpBranch %59 -%59 = OpLabel -%60 = OpImageQuerySize %15 %57 -%62 = OpVectorShuffle %61 %54 %54 0 1 -%63 = OpBitcast %15 %62 -%64 = OpIMul %15 %60 %63 -%65 = OpCompositeConstruct %15 %3 %5 -%66 = OpSMod %15 %64 %65 -%68 = OpImageRead %67 %57 %66 -%69 = OpCompositeExtract %4 %66 0 -OpImageWrite %58 %69 %68 +%52 = OpTypePointer UniformConstant %26 +%51 = OpVariable %52 UniformConstant +%54 = OpTypePointer UniformConstant %26 +%53 = OpVariable %54 UniformConstant +%56 = OpTypePointer UniformConstant %27 +%55 = OpVariable %56 UniformConstant +%59 = OpTypePointer Input %16 +%58 = OpVariable %59 Input +%62 = OpTypeFunction %2 +%69 = OpTypeVector %12 2 +%77 = OpTypeVector %12 4 +%88 = OpTypePointer Output %25 +%87 = OpVariable %88 Output +%98 = OpConstant %12 0 +%103 = OpTypeVector %4 3 +%156 = OpVariable %88 Output +%161 = OpTypeVector %8 2 +%163 = OpTypeSampledImage %19 +%177 = OpTypePointer Output %8 +%176 = OpVariable %177 Output +%183 = OpTypeSampledImage %27 +%188 = OpConstant %8 0.0 +%61 = OpFunction %2 None %62 +%57 = OpLabel +%60 = OpLoad %16 %58 +%63 = OpLoad %11 %29 +%64 = OpLoad %13 %31 +%65 = OpLoad %14 %33 +%66 = OpLoad %15 %35 +OpBranch %67 +%67 = OpLabel +%68 = OpImageQuerySize %17 %65 +%70 = OpVectorShuffle %69 %60 %60 0 1 +%71 = OpBitcast %17 %70 +%72 = OpIMul %17 %68 %71 +%73 = OpCompositeConstruct %17 %3 %5 +%74 = OpSMod %17 %72 %73 +%75 = OpCompositeExtract %12 %60 2 +%76 = OpBitcast %4 %75 +%78 = OpImageFetch %77 %63 %74 Lod %76 +%79 = OpCompositeExtract %12 %60 2 +%80 = OpBitcast %4 %79 +%81 = OpImageFetch %77 %64 %74 Sample %80 +%82 = OpImageRead %77 %65 %74 +%83 = OpCompositeExtract %4 %74 0 +%84 = OpIAdd %77 %78 %81 +%85 = OpIAdd %77 %84 %82 +OpImageWrite %66 %83 %85 OpReturn OpFunctionEnd -%73 = OpFunction %2 None %56 -%70 = OpLabel -%74 = OpLoad %16 %31 -%75 = OpLoad %17 %33 -%76 = OpLoad %18 %35 -%77 = OpLoad %19 %37 -%78 = OpLoad %20 %39 -%79 = OpLoad %21 %41 -%80 = OpLoad %22 %43 -OpBranch %81 -%81 = OpLabel -%83 = OpImageQuerySizeLod %4 %74 %82 -%84 = OpImageQuerySizeLod %15 %75 %82 -%85 = OpImageQueryLevels %4 %75 -%86 = OpImageQuerySizeLod %15 %75 %6 -%88 = OpImageQuerySizeLod %87 %76 %82 -%89 = OpVectorShuffle %15 %88 %88 0 1 -%90 = OpImageQueryLevels %4 %76 -%91 = OpImageQuerySizeLod %87 %76 %6 -%92 = OpVectorShuffle %15 %91 %91 0 1 -%93 = OpImageQuerySizeLod %87 %76 %82 -%94 = OpCompositeExtract %4 %93 2 -%95 = OpImageQuerySizeLod %15 %77 %82 -%96 = OpImageQueryLevels %4 %77 -%97 = OpImageQuerySizeLod %15 %77 %6 -%98 = OpImageQuerySizeLod %87 %78 %82 -%99 = OpVectorShuffle %15 %98 %98 0 0 -%100 = OpImageQueryLevels %4 %78 -%101 = OpImageQuerySizeLod %87 %78 %6 -%102 = OpVectorShuffle %15 %101 %101 0 0 -%103 = OpImageQuerySizeLod %87 %78 %82 -%104 = OpCompositeExtract %4 %103 2 -%105 = OpImageQuerySizeLod %87 %79 %82 -%106 = OpImageQueryLevels %4 %79 -%107 = OpImageQuerySizeLod %87 %79 %6 -%108 = OpImageQuerySamples %4 %80 -%109 = OpCompositeExtract %4 %84 1 -%110 = OpIAdd %4 %83 %109 -%111 = OpCompositeExtract %4 %86 1 -%112 = OpIAdd %4 %110 %111 -%113 = OpCompositeExtract %4 %89 1 -%114 = OpIAdd %4 %112 %113 -%115 = OpCompositeExtract %4 %92 1 -%116 = OpIAdd %4 %114 %115 -%117 = OpIAdd %4 %116 %94 -%118 = OpCompositeExtract %4 %95 1 -%119 = OpIAdd %4 %117 %118 -%120 = OpCompositeExtract %4 %97 1 -%121 = OpIAdd %4 %119 %120 -%122 = OpCompositeExtract %4 %99 1 -%123 = OpIAdd %4 %121 %122 -%124 = OpCompositeExtract %4 %102 1 -%125 = OpIAdd %4 %123 %124 -%126 = OpIAdd %4 %125 %104 -%127 = OpCompositeExtract %4 %105 2 +%89 = OpFunction %2 None %62 +%86 = OpLabel +%90 = OpLoad %18 %37 +%91 = OpLoad %19 %39 +%92 = OpLoad %20 %41 +%93 = OpLoad %21 %43 +%94 = OpLoad %22 %45 +%95 = OpLoad %23 %47 +%96 = OpLoad %24 %49 +OpBranch %97 +%97 = OpLabel +%99 = OpImageQuerySizeLod %4 %90 %98 +%100 = OpImageQuerySizeLod %17 %91 %98 +%101 = OpImageQueryLevels %4 %91 +%102 = OpImageQuerySizeLod %17 %91 %6 +%104 = OpImageQuerySizeLod %103 %92 %98 +%105 = OpVectorShuffle %17 %104 %104 0 1 +%106 = OpImageQueryLevels %4 %92 +%107 = OpImageQuerySizeLod %103 %92 %6 +%108 = OpVectorShuffle %17 %107 %107 0 1 +%109 = OpImageQuerySizeLod %103 %92 %98 +%110 = OpCompositeExtract %4 %109 2 +%111 = OpImageQuerySizeLod %17 %93 %98 +%112 = OpImageQueryLevels %4 %93 +%113 = OpImageQuerySizeLod %17 %93 %6 +%114 = OpImageQuerySizeLod %103 %94 %98 +%115 = OpVectorShuffle %17 %114 %114 0 0 +%116 = OpImageQueryLevels %4 %94 +%117 = OpImageQuerySizeLod %103 %94 %6 +%118 = OpVectorShuffle %17 %117 %117 0 0 +%119 = OpImageQuerySizeLod %103 %94 %98 +%120 = OpCompositeExtract %4 %119 2 +%121 = OpImageQuerySizeLod %103 %95 %98 +%122 = OpImageQueryLevels %4 %95 +%123 = OpImageQuerySizeLod %103 %95 %6 +%124 = OpImageQuerySamples %4 %96 +%125 = OpCompositeExtract %4 %100 1 +%126 = OpIAdd %4 %99 %125 +%127 = OpCompositeExtract %4 %102 1 %128 = OpIAdd %4 %126 %127 -%129 = OpCompositeExtract %4 %107 2 +%129 = OpCompositeExtract %4 %105 1 %130 = OpIAdd %4 %128 %129 -%131 = OpIAdd %4 %130 %108 -%132 = OpIAdd %4 %131 %85 -%133 = OpIAdd %4 %132 %90 -%134 = OpIAdd %4 %133 %106 -%135 = OpIAdd %4 %134 %96 -%136 = OpIAdd %4 %135 %100 -%137 = OpConvertSToF %8 %136 -%138 = OpCompositeConstruct %23 %137 %137 %137 %137 -OpStore %71 %138 +%131 = OpCompositeExtract %4 %108 1 +%132 = OpIAdd %4 %130 %131 +%133 = OpIAdd %4 %132 %110 +%134 = OpCompositeExtract %4 %111 1 +%135 = OpIAdd %4 %133 %134 +%136 = OpCompositeExtract %4 %113 1 +%137 = OpIAdd %4 %135 %136 +%138 = OpCompositeExtract %4 %115 1 +%139 = OpIAdd %4 %137 %138 +%140 = OpCompositeExtract %4 %118 1 +%141 = OpIAdd %4 %139 %140 +%142 = OpIAdd %4 %141 %120 +%143 = OpCompositeExtract %4 %121 2 +%144 = OpIAdd %4 %142 %143 +%145 = OpCompositeExtract %4 %123 2 +%146 = OpIAdd %4 %144 %145 +%147 = OpIAdd %4 %146 %124 +%148 = OpIAdd %4 %147 %101 +%149 = OpIAdd %4 %148 %106 +%150 = OpIAdd %4 %149 %122 +%151 = OpIAdd %4 %150 %112 +%152 = OpIAdd %4 %151 %116 +%153 = OpConvertSToF %8 %152 +%154 = OpCompositeConstruct %25 %153 %153 %153 %153 +OpStore %87 %154 OpReturn OpFunctionEnd -%141 = OpFunction %2 None %56 -%139 = OpLabel -%142 = OpLoad %17 %33 -%143 = OpLoad %24 %45 -OpBranch %144 -%144 = OpLabel -%146 = OpCompositeConstruct %145 %7 %7 -%148 = OpSampledImage %147 %142 %143 -%149 = OpImageSampleImplicitLod %23 %148 %146 -%150 = OpSampledImage %147 %142 %143 -%151 = OpImageSampleImplicitLod %23 %150 %146 ConstOffset %26 -%152 = OpSampledImage %147 %142 %143 -%153 = OpImageSampleExplicitLod %23 %152 %146 Lod %9 -%154 = OpSampledImage %147 %142 %143 -%155 = OpImageSampleExplicitLod %23 %154 %146 Lod|ConstOffset %9 %26 -%156 = OpFAdd %23 %149 %151 -%157 = OpFAdd %23 %156 %153 -%158 = OpFAdd %23 %157 %155 -OpStore %140 %158 +%157 = OpFunction %2 None %62 +%155 = OpLabel +%158 = OpLoad %19 %39 +%159 = OpLoad %26 %51 +OpBranch %160 +%160 = OpLabel +%162 = OpCompositeConstruct %161 %7 %7 +%164 = OpSampledImage %163 %158 %159 +%165 = OpImageSampleImplicitLod %25 %164 %162 +%166 = OpSampledImage %163 %158 %159 +%167 = OpImageSampleImplicitLod %25 %166 %162 ConstOffset %28 +%168 = OpSampledImage %163 %158 %159 +%169 = OpImageSampleExplicitLod %25 %168 %162 Lod %9 +%170 = OpSampledImage %163 %158 %159 +%171 = OpImageSampleExplicitLod %25 %170 %162 Lod|ConstOffset %9 %28 +%172 = OpFAdd %25 %165 %167 +%173 = OpFAdd %25 %172 %169 +%174 = OpFAdd %25 %173 %171 +OpStore %156 %174 OpReturn OpFunctionEnd -%162 = OpFunction %2 None %56 -%159 = OpLabel -%163 = OpLoad %24 %47 -%164 = OpLoad %25 %49 -OpBranch %165 -%165 = OpLabel -%166 = OpCompositeConstruct %145 %7 %7 -%168 = OpSampledImage %167 %164 %163 -%169 = OpImageSampleDrefImplicitLod %8 %168 %166 %7 -%170 = OpSampledImage %167 %164 %163 -%171 = OpImageSampleDrefExplicitLod %8 %170 %166 %7 Lod %172 -%173 = OpFAdd %8 %169 %171 -OpStore %160 %173 +%178 = OpFunction %2 None %62 +%175 = OpLabel +%179 = OpLoad %26 %53 +%180 = OpLoad %27 %55 +OpBranch %181 +%181 = OpLabel +%182 = OpCompositeConstruct %161 %7 %7 +%184 = OpSampledImage %183 %180 %179 +%185 = OpImageSampleDrefImplicitLod %8 %184 %182 %7 +%186 = OpSampledImage %183 %180 %179 +%187 = OpImageSampleDrefExplicitLod %8 %186 %182 %7 Lod %188 +%189 = OpFAdd %8 %185 %187 +OpStore %176 %189 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index e8167cf92..5c9247173 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -1,5 +1,9 @@ +[[group(0), binding(0)]] +var image_mipmapped_src: texture_2d; +[[group(0), binding(3)]] +var image_multisampled_src: texture_multisampled_2d; [[group(0), binding(1)]] -var image_src: [[access(read)]] texture_storage_2d; +var image_storage_src: [[access(read)]] texture_storage_2d; [[group(0), binding(2)]] var image_dst: [[access(write)]] texture_storage_1d; [[group(0), binding(0)]] @@ -25,10 +29,12 @@ var image_2d_depth: texture_depth_2d; [[stage(compute), workgroup_size(16, 1, 1)]] fn main([[builtin(local_invocation_id)]] local_id: vec3) { - let dim: vec2 = textureDimensions(image_src); + let dim: vec2 = textureDimensions(image_storage_src); let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); - let value: vec4 = textureLoad(image_src, itc); - textureStore(image_dst, itc.x, value); + let value1_: vec4 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); + let value2_: vec4 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); + let value3_: vec4 = textureLoad(image_storage_src, itc); + textureStore(image_dst, itc.x, ((value1_ + value2_) + value3_)); return; } From 3c98cc5ae1e720d1cac07b125390d8e0313576f3 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 19 Jul 2021 00:10:07 +0300 Subject: [PATCH 1127/2212] [hlsl-out] Validate all entry points in Makefile --- Makefile | 24 +++++++--- tests/out/hlsl/control-flow.hlsl.config | 5 ++- tests/out/hlsl/empty.hlsl.config | 5 ++- tests/out/hlsl/globals.hlsl.config | 5 ++- tests/out/hlsl/image.hlsl.config | 11 ++--- tests/out/hlsl/interface.hlsl.config | 9 ++-- tests/out/hlsl/interpolate.hlsl.config | 7 ++- tests/out/hlsl/operators.hlsl.config | 5 ++- tests/out/hlsl/quad-vert.hlsl.config | 5 ++- tests/out/hlsl/quad.hlsl.config | 9 ++-- tests/out/hlsl/shadow.hlsl.config | 5 ++- tests/out/hlsl/skybox.hlsl.config | 7 ++- tests/out/hlsl/standard.hlsl.config | 5 ++- tests/snapshots.rs | 58 ++++++++++++++++++------- 14 files changed, 96 insertions(+), 64 deletions(-) diff --git a/Makefile b/Makefile index 3d8946235..841f077a8 100644 --- a/Makefile +++ b/Makefile @@ -65,17 +65,27 @@ validate-wgsl: $(SNAPSHOTS_BASE_OUT)/wgsl/*.wgsl cargo run $${file}; \ done +validate-hlsl: SHELL:=/bin/bash # required because config files uses arrays validate-hlsl: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl @set -e && for file in $^ ; do \ + DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug"; \ echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ config="$$(dirname $${file})/$$(basename $${file}).config"; \ - vertex=""\ - fragment="" \ - compute="" \ . $${config}; \ - DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug"; \ - [ ! -z "$${vertex}" ] && echo "Vertex Stage:" && dxc $${file} -T $${vertex} -E $${vertex_name} $${DXC_PARAMS} > /dev/null; \ - [ ! -z "$${fragment}" ] && echo "Fragment Stage:" && dxc $${file} -T $${fragment} -E $${fragment_name} $${DXC_PARAMS} > /dev/null; \ - [ ! -z "$${compute}" ] && echo "Compute Stage:" && dxc $${file} -T $${compute} -E $${compute_name} $${DXC_PARAMS} > /dev/null; \ + for (( i=0; i<$${#vertex[@]}; i++ )); do \ + name=`echo $${vertex[i]} | cut -d \: -f 1`; \ + profile=`echo $${vertex[i]} | cut -d \: -f 2`; \ + (set -x; dxc $${file} -T $${profile} -E $${name} $${DXC_PARAMS} > /dev/null); \ + done; \ + for (( i=0; i<$${#fragment[@]}; i++ )); do \ + name=`echo $${fragment[i]} | cut -d \: -f 1`; \ + profile=`echo $${fragment[i]} | cut -d \: -f 2`; \ + (set -x; dxc $${file} -T $${profile} -E $${name} $${DXC_PARAMS} > /dev/null); \ + done; \ + for (( i=0; i<$${#compute[@]}; i++ )); do \ + name=`echo $${compute[i]} | cut -d \: -f 1`; \ + profile=`echo $${compute[i]} | cut -d \: -f 2`; \ + (set -x; dxc $${file} -T $${profile} -E $${name} $${DXC_PARAMS} > /dev/null); \ + done; \ echo "======================"; \ done diff --git a/tests/out/hlsl/control-flow.hlsl.config b/tests/out/hlsl/control-flow.hlsl.config index 71412ac2d..c0d04b8f2 100644 --- a/tests/out/hlsl/control-flow.hlsl.config +++ b/tests/out/hlsl/control-flow.hlsl.config @@ -1,2 +1,3 @@ -compute=cs_5_0 -compute_name=main +vertex=() +fragment=() +compute=(main:cs_5_0 ) diff --git a/tests/out/hlsl/empty.hlsl.config b/tests/out/hlsl/empty.hlsl.config index 71412ac2d..c0d04b8f2 100644 --- a/tests/out/hlsl/empty.hlsl.config +++ b/tests/out/hlsl/empty.hlsl.config @@ -1,2 +1,3 @@ -compute=cs_5_0 -compute_name=main +vertex=() +fragment=() +compute=(main:cs_5_0 ) diff --git a/tests/out/hlsl/globals.hlsl.config b/tests/out/hlsl/globals.hlsl.config index 71412ac2d..c0d04b8f2 100644 --- a/tests/out/hlsl/globals.hlsl.config +++ b/tests/out/hlsl/globals.hlsl.config @@ -1,2 +1,3 @@ -compute=cs_5_0 -compute_name=main +vertex=() +fragment=() +compute=(main:cs_5_0 ) diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config index 3e97dafc3..c182886b7 100644 --- a/tests/out/hlsl/image.hlsl.config +++ b/tests/out/hlsl/image.hlsl.config @@ -1,8 +1,3 @@ -compute=cs_5_0 -compute_name=main -vertex=vs_5_0 -vertex_name=queries -fragment=ps_5_0 -fragment_name=sample1 -fragment=ps_5_0 -fragment_name=sample_comparison +vertex=(queries:vs_5_0 ) +fragment=(sample1:ps_5_0 sample_comparison:ps_5_0 ) +compute=(main:cs_5_0 ) diff --git a/tests/out/hlsl/interface.hlsl.config b/tests/out/hlsl/interface.hlsl.config index bd33fe9c2..4da683e01 100644 --- a/tests/out/hlsl/interface.hlsl.config +++ b/tests/out/hlsl/interface.hlsl.config @@ -1,6 +1,3 @@ -vertex=vs_5_0 -vertex_name=vertex -fragment=ps_5_0 -fragment_name=fragment -compute=cs_5_0 -compute_name=compute +vertex=(vertex:vs_5_0 ) +fragment=(fragment:ps_5_0 ) +compute=(compute:cs_5_0 ) diff --git a/tests/out/hlsl/interpolate.hlsl.config b/tests/out/hlsl/interpolate.hlsl.config index bae3c1cc6..7a83c119f 100644 --- a/tests/out/hlsl/interpolate.hlsl.config +++ b/tests/out/hlsl/interpolate.hlsl.config @@ -1,4 +1,3 @@ -vertex=vs_5_0 -vertex_name=main -fragment=ps_5_0 -fragment_name=main1 +vertex=(main:vs_5_0 ) +fragment=(main1:ps_5_0 ) +compute=() diff --git a/tests/out/hlsl/operators.hlsl.config b/tests/out/hlsl/operators.hlsl.config index 71412ac2d..c0d04b8f2 100644 --- a/tests/out/hlsl/operators.hlsl.config +++ b/tests/out/hlsl/operators.hlsl.config @@ -1,2 +1,3 @@ -compute=cs_5_0 -compute_name=main +vertex=() +fragment=() +compute=(main:cs_5_0 ) diff --git a/tests/out/hlsl/quad-vert.hlsl.config b/tests/out/hlsl/quad-vert.hlsl.config index 49efa2b9a..9f33353d2 100644 --- a/tests/out/hlsl/quad-vert.hlsl.config +++ b/tests/out/hlsl/quad-vert.hlsl.config @@ -1,2 +1,3 @@ -vertex=vs_5_0 -vertex_name=main +vertex=(main:vs_5_0 ) +fragment=() +compute=() diff --git a/tests/out/hlsl/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config index 18bfb0bd5..094d9191f 100644 --- a/tests/out/hlsl/quad.hlsl.config +++ b/tests/out/hlsl/quad.hlsl.config @@ -1,6 +1,3 @@ -vertex=vs_5_0 -vertex_name=main -fragment=ps_5_0 -fragment_name=main1 -fragment=ps_5_0 -fragment_name=fs_extra +vertex=(main:vs_5_0 ) +fragment=(main1:ps_5_0 fs_extra:ps_5_0 ) +compute=() diff --git a/tests/out/hlsl/shadow.hlsl.config b/tests/out/hlsl/shadow.hlsl.config index 5d17f4305..ead2c79fa 100644 --- a/tests/out/hlsl/shadow.hlsl.config +++ b/tests/out/hlsl/shadow.hlsl.config @@ -1,2 +1,3 @@ -fragment=ps_5_0 -fragment_name=fs_main +vertex=() +fragment=(fs_main:ps_5_0 ) +compute=() diff --git a/tests/out/hlsl/skybox.hlsl.config b/tests/out/hlsl/skybox.hlsl.config index 41df29cb7..541ec2175 100644 --- a/tests/out/hlsl/skybox.hlsl.config +++ b/tests/out/hlsl/skybox.hlsl.config @@ -1,4 +1,3 @@ -vertex=vs_5_1 -vertex_name=vs_main -fragment=ps_5_1 -fragment_name=fs_main +vertex=(vs_main:vs_5_1 ) +fragment=(fs_main:ps_5_1 ) +compute=() diff --git a/tests/out/hlsl/standard.hlsl.config b/tests/out/hlsl/standard.hlsl.config index 9ae8c9df7..512971d7c 100644 --- a/tests/out/hlsl/standard.hlsl.config +++ b/tests/out/hlsl/standard.hlsl.config @@ -1,2 +1,3 @@ -fragment=ps_5_0 -fragment_name=derivatives +vertex=() +fragment=(derivatives:ps_5_0 ) +compute=() diff --git a/tests/snapshots.rs b/tests/snapshots.rs index fb3369728..70ab53d71 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -304,27 +304,55 @@ fn write_output_hlsl( // This file contains an info about profiles (shader stages) contains inside generated shader // This info will be passed to dxc let mut config_str = String::new(); + let mut vertex_str = String::from("vertex=("); + let mut fragment_str = String::from("fragment=("); + let mut compute_str = String::from("compute=("); for (index, ep) in module.entry_points.iter().enumerate() { let name = match reflection_info.entry_point_names[index] { Ok(ref name) => name, Err(_) => continue, }; - let stage_str = match ep.stage { - naga::ShaderStage::Vertex => "vertex", - naga::ShaderStage::Fragment => "fragment", - naga::ShaderStage::Compute => "compute", - }; - writeln!( - config_str, - "{}={}_{}\n{}_name={}", - stage_str, - ep.stage.to_hlsl_str(), - options.shader_model.to_str(), - stage_str, - name, - ) - .unwrap(); + match ep.stage { + naga::ShaderStage::Vertex => { + write!( + vertex_str, + "{}:{}_{} ", + name, + ep.stage.to_hlsl_str(), + options.shader_model.to_str(), + ) + .unwrap(); + } + naga::ShaderStage::Fragment => { + write!( + fragment_str, + "{}:{}_{} ", + name, + ep.stage.to_hlsl_str(), + options.shader_model.to_str(), + ) + .unwrap(); + } + naga::ShaderStage::Compute => { + write!( + compute_str, + "{}:{}_{} ", + name, + ep.stage.to_hlsl_str(), + options.shader_model.to_str(), + ) + .unwrap(); + } + } } + + writeln!( + config_str, + "{})\n{})\n{})", + vertex_str, fragment_str, compute_str + ) + .unwrap(); + fs::write( destination.join(format!("hlsl/{}.hlsl.config", file_name)), config_str, From 37d094ca070d63fcc197ce46cbe4f45af558124f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 20 Jul 2021 02:12:55 -0400 Subject: [PATCH 1128/2212] hlsl-out: omit globals that aren't accessible --- src/back/hlsl/writer.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 64055a698..2a6f6342f 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -339,6 +339,18 @@ impl<'a, W: Write> Writer<'a, W> { let global = &module.global_variables[handle]; let inner = &module.types[global.ty].inner; + if let Some(ref binding) = global.binding { + if let Err(err) = self.options.resolve_resource_binding(binding) { + log::info!( + "Skipping global {:?} (name {:?}) for being inaccessible: {}", + handle, + global.name, + err, + ); + return Ok(()); + } + } + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register let (storage, register_ty) = match global.class { crate::StorageClass::Function => unreachable!("Function storage class"), From 7b9b56a6abe153a382e611db293bdf74b391906e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 20 Jul 2021 02:40:14 -0400 Subject: [PATCH 1129/2212] hlsl-out: use * for vector by vector multiplication --- src/back/hlsl/writer.rs | 6 ++++-- tests/out/hlsl/image.hlsl | 2 +- tests/out/hlsl/shadow.hlsl | 4 ++-- tests/out/hlsl/skybox.hlsl | 2 +- tests/out/hlsl/standard.hlsl | 2 +- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 2a6f6342f..4571531ca 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1063,18 +1063,20 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } } + // Matrix * Vector has to be written as `mul(Matrix, Vector)` Expression::Binary { op: crate::BinaryOperator::Multiply, left, right, - } => { + } if func_ctx.info[left].ty.inner_with(&module.types) + != func_ctx.info[right].ty.inner_with(&module.types) => + { write!(self.out, "mul(")?; self.write_expr(module, left, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, right, func_ctx)?; write!(self.out, ")")?; } - // TODO: copy-paste from wgsl-out Expression::Binary { op, left, right } => { write!(self.out, "(")?; self.write_expr(module, left, func_ctx)?; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index da460e4f8..da94245fe 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -28,7 +28,7 @@ int2 NagaDimensions2D(Texture2D) void main(ComputeInput_main computeinput_main) { int2 dim = NagaDimensions2D(image_storage_src); - int2 itc = (mul(dim, int2(computeinput_main.local_id1.xy)) % int2(10, 20)); + int2 itc = ((dim * int2(computeinput_main.local_id1.xy)) % int2(10, 20)); uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(computeinput_main.local_id1.z))); uint4 value2_ = image_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)); uint4 value3_ = image_storage_src.Load(int3(itc, 0)); diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index bcce7a0fd..ebb693ad2 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -32,7 +32,7 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords) return 1.0; } float2 flip_correction = float2(0.5, -0.5); - float2 light_local = ((mul(homogeneous_coords.xy, flip_correction) / float2(homogeneous_coords.w.xx)) + float2(0.5, 0.5)); + float2 light_local = (((homogeneous_coords.xy * flip_correction) / float2(homogeneous_coords.w.xx)) + float2(0.5, 0.5)); float _expr26 = t_shadow.SampleCmpLevelZero(sampler_shadow, float3(light_local, int(light_id)), (homogeneous_coords.z / homogeneous_coords.w)); return _expr26; } @@ -56,7 +56,7 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); float3 _expr34 = color; - color = (_expr34 + mul(mul(_e25, diffuse), light.color.xyz)); + color = (_expr34 + mul((_e25 * diffuse), light.color.xyz)); uint _expr40 = i; i = (_expr40 + 1u); } diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 6886185b6..3add16fa9 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -29,7 +29,7 @@ VertexOutput vs_main(VertexInput_vs_main vertexinput_vs_main) tmp2_ = (int(vertexinput_vs_main.vertex_index1) & 1); int _expr10 = tmp1_; int _expr16 = tmp2_; - float4 pos = float4((mul(float(_expr10), 4.0) - 1.0), (mul(float(_expr16), 4.0) - 1.0), 0.0, 1.0); + float4 pos = float4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); float4 _expr27 = r_data.view[0]; float4 _expr31 = r_data.view[1]; float4 _expr35 = r_data.view[2]; diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl index 5ec8b8f7d..b6a639f26 100644 --- a/tests/out/hlsl/standard.hlsl +++ b/tests/out/hlsl/standard.hlsl @@ -7,5 +7,5 @@ float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Tar float4 x = ddx(fragmentinput_derivatives.foo1); float4 y = ddy(fragmentinput_derivatives.foo1); float4 z = fwidth(fragmentinput_derivatives.foo1); - return mul((x + y), z); + return ((x + y) * z); } From 34b486f74b37d73969b354ec757737383bca6186 Mon Sep 17 00:00:00 2001 From: Zicklag Date: Mon, 19 Jul 2021 17:53:06 -0500 Subject: [PATCH 1130/2212] Add Explicit Int Precision for GLSL ES Backend --- src/back/glsl/mod.rs | 3 ++- tests/out/glsl/boids.main.Compute.glsl | 1 + tests/out/glsl/control-flow.main.Compute.glsl | 1 + tests/out/glsl/empty.main.Compute.glsl | 1 + tests/out/glsl/globals.main.Compute.glsl | 1 + tests/out/glsl/operators.main.Compute.glsl | 1 + tests/out/glsl/quad-vert.main.Vertex.glsl | 1 + tests/out/glsl/quad.fs_extra.Fragment.glsl | 1 + tests/out/glsl/quad.main.Fragment.glsl | 1 + tests/out/glsl/quad.main.Vertex.glsl | 1 + tests/out/glsl/shadow.fs_main.Fragment.glsl | 1 + tests/out/glsl/skybox.fs_main.Fragment.glsl | 1 + tests/out/glsl/skybox.vs_main.Vertex.glsl | 1 + tests/out/glsl/standard.derivatives.Fragment.glsl | 1 + tests/out/glsl/texture-arg.main.Fragment.glsl | 1 + 15 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ffb0c2b36..b3b139af3 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -409,11 +409,12 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, "#extension GL_EXT_texture_shadow_lod : require")?; } - // glsl es requires a precision to be specified for floats + // glsl es requires a precision to be specified for floats and ints // TODO: Should this be user configurable? if es { writeln!(self.out)?; writeln!(self.out, "precision highp float;")?; + writeln!(self.out, "precision highp int;")?; writeln!(self.out)?; } diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 14a00bce0..0893dc810 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -1,6 +1,7 @@ #version 310 es precision highp float; +precision highp int; layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in; diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index 259916328..d2bc4571f 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -1,6 +1,7 @@ #version 310 es precision highp float; +precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; diff --git a/tests/out/glsl/empty.main.Compute.glsl b/tests/out/glsl/empty.main.Compute.glsl index 63328eab1..f6b9108cc 100644 --- a/tests/out/glsl/empty.main.Compute.glsl +++ b/tests/out/glsl/empty.main.Compute.glsl @@ -1,6 +1,7 @@ #version 310 es precision highp float; +precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index 9c68181b1..b498b6f4e 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -1,6 +1,7 @@ #version 310 es precision highp float; +precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 802ef48da..8b55a50e3 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -1,6 +1,7 @@ #version 310 es precision highp float; +precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index b1b05b722..970c26840 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -1,6 +1,7 @@ #version 310 es precision highp float; +precision highp int; struct type10 { vec2 member; diff --git a/tests/out/glsl/quad.fs_extra.Fragment.glsl b/tests/out/glsl/quad.fs_extra.Fragment.glsl index b5f2bea37..9770ffb60 100644 --- a/tests/out/glsl/quad.fs_extra.Fragment.glsl +++ b/tests/out/glsl/quad.fs_extra.Fragment.glsl @@ -1,6 +1,7 @@ #version 300 es precision highp float; +precision highp int; struct VertexOutput { vec2 uv; diff --git a/tests/out/glsl/quad.main.Fragment.glsl b/tests/out/glsl/quad.main.Fragment.glsl index 7f1fda42e..6b03a6515 100644 --- a/tests/out/glsl/quad.main.Fragment.glsl +++ b/tests/out/glsl/quad.main.Fragment.glsl @@ -1,6 +1,7 @@ #version 300 es precision highp float; +precision highp int; struct VertexOutput { vec2 uv; diff --git a/tests/out/glsl/quad.main.Vertex.glsl b/tests/out/glsl/quad.main.Vertex.glsl index e6935cfa6..63a447283 100644 --- a/tests/out/glsl/quad.main.Vertex.glsl +++ b/tests/out/glsl/quad.main.Vertex.glsl @@ -1,6 +1,7 @@ #version 300 es precision highp float; +precision highp int; struct VertexOutput { vec2 uv; diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 2f63f6c6f..af217b631 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -1,6 +1,7 @@ #version 310 es precision highp float; +precision highp int; struct Light { mat4x4 proj; diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index 4495eb478..9cf825635 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -1,6 +1,7 @@ #version 320 es precision highp float; +precision highp int; struct VertexOutput { vec4 position; diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index ccdac1e4d..6d3795565 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -1,6 +1,7 @@ #version 320 es precision highp float; +precision highp int; struct VertexOutput { vec4 position; diff --git a/tests/out/glsl/standard.derivatives.Fragment.glsl b/tests/out/glsl/standard.derivatives.Fragment.glsl index 54d962ce9..4a084add1 100644 --- a/tests/out/glsl/standard.derivatives.Fragment.glsl +++ b/tests/out/glsl/standard.derivatives.Fragment.glsl @@ -1,6 +1,7 @@ #version 310 es precision highp float; +precision highp int; layout(location = 0) out vec4 _fs2p_location0; diff --git a/tests/out/glsl/texture-arg.main.Fragment.glsl b/tests/out/glsl/texture-arg.main.Fragment.glsl index df318d15b..2c71caf43 100644 --- a/tests/out/glsl/texture-arg.main.Fragment.glsl +++ b/tests/out/glsl/texture-arg.main.Fragment.glsl @@ -1,6 +1,7 @@ #version 310 es precision highp float; +precision highp int; uniform highp sampler2D _group_0_binding_0; From c6c799648083ce246f2e3943f0e044492f0d93cc Mon Sep 17 00:00:00 2001 From: Zicklag Date: Tue, 20 Jul 2021 12:43:36 -0500 Subject: [PATCH 1131/2212] Fix Documentation Typo --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 14997a734..70c284349 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,7 +29,7 @@ A Naga backend can generate code to evaluate an `Expression` however and whenever it pleases, as long as it is certain to observe the side effects of all previously executed `Statement`s. -Many `Statement` variants use the [`Block`] type, which is simply `Vec`, +Many `Statement` variants use the [`Block`] type, which is simply `Vec`, representing a series of statements executed in order. The body of an `EntryPoint`s or `Function` is a `Block`, and `Statement` has a [`Block`][Statement::Block] variant. From a0e50e3eacec370ca8afd40d6d306f518e7fc832 Mon Sep 17 00:00:00 2001 From: Zicklag Date: Tue, 20 Jul 2021 10:55:23 -0500 Subject: [PATCH 1132/2212] Improve CLI Argument Doc and Error Handling - Use argh for parsing commandline arguments and generating help message - Remove almost all panics and handle errors by printing them and exiting 1 --- cli/Cargo.toml | 1 + cli/src/main.rs | 315 +++++++++++++++++++++++++++++++----------------- 2 files changed, 207 insertions(+), 109 deletions(-) diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 70a274cd8..98f3eeabc 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -18,3 +18,4 @@ naga = { path = "../", features = ["wgsl-in", "wgsl-out", "glsl-in", "glsl-out", log = "0.4" codespan-reporting = "0.11" env_logger = "0.8" +argh = "0.1.5" diff --git a/cli/src/main.rs b/cli/src/main.rs index 00e6cf2a6..d363359a2 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -1,7 +1,111 @@ #![allow(clippy::manual_strip)] #[allow(unused_imports)] use std::fs; -use std::{env, error::Error, path::Path}; +use std::{error::Error, fmt, path::Path, str::FromStr}; + +/// Translate shaders to different formats +#[derive(argh::FromArgs, Debug, Clone)] +struct Args { + /// validate the shader during translation + #[argh(switch)] + validate: bool, + + /// what policy to use for index bounds checking. + /// + /// May be `Restrict`, `ReadZeroSkipWrite`, or `UndefinedBehavior` + #[argh(option)] + index_bounds_check_policy: Option, + + /// directory to dump the SPIR-V flow dump to + #[argh(option)] + flow_dir: Option, + + /// the shader entrypoint to use when compiling to GLSL + #[argh(option)] + entry_point: Option, + + /// the shader profile to use, for example `es`, `core`, `es330`, if translating to GLSL + #[argh(option)] + profile: Option, + + /// the shader model to use if targeting HSLS + /// + /// May be `50`, 51`, or `60` + #[argh(option)] + shader_model: Option, + + /// the input file + #[argh(positional)] + input: String, + + /// the output file + #[argh(positional)] + output: String, + + /// other output files if there are multiples + #[argh(positional)] + extra_outputs: Vec, +} + +/// Newtype so we can implement [`FromStr`] for `IndexBoundsCheckPolicy`. +#[derive(Debug, Clone)] +struct IndexBoundsCheckPolicyArg(naga::back::IndexBoundsCheckPolicy); + +impl FromStr for IndexBoundsCheckPolicyArg { + type Err = String; + + fn from_str(s: &str) -> Result { + use naga::back::IndexBoundsCheckPolicy; + Ok(Self(match s.to_lowercase().as_str() { + "restrict" => IndexBoundsCheckPolicy::Restrict, + "readzeroskipwrite" => IndexBoundsCheckPolicy::ReadZeroSkipWrite, + "undefinedbehavior" => IndexBoundsCheckPolicy::UndefinedBehavior, + _ => { + return Err(format!( + "Invalid value for --index-bounds-check-policy: {}", + s + )) + } + })) + } +} + +/// Newtype so we can implement [`FromStr`] for `ShaderModel`. +#[derive(Debug, Clone)] +struct ShaderModelArg(naga::back::hlsl::ShaderModel); + +impl FromStr for ShaderModelArg { + type Err = String; + + fn from_str(s: &str) -> Result { + use naga::back::hlsl::ShaderModel; + Ok(Self(match s.to_lowercase().as_str() { + "50" => ShaderModel::V5_0, + "51" => ShaderModel::V5_1, + "60" => ShaderModel::V6_0, + _ => return Err(format!("Invalid value for --shader-model: {}", s)), + })) + } +} + +/// Newtype so we can implement [`FromStr`] for [`naga::back::glsl::Version`]. +#[derive(Clone, Debug)] +struct GlslProfileArg(naga::back::glsl::Version); + +impl FromStr for GlslProfileArg { + type Err = String; + + fn from_str(s: &str) -> Result { + use naga::back::glsl::Version; + Ok(Self(if s.starts_with("core") { + Version::Desktop(s[4..].parse().unwrap_or(330)) + } else if s.starts_with("es") { + Version::Embedded(s[2..].parse().unwrap_or(310)) + } else { + return Err(format!("Unknown profile: {}", s)); + })) + } +} #[derive(Default)] struct Parameters { @@ -21,7 +125,7 @@ trait PrettyResult { fn unwrap_pretty(self) -> Self::Target; } -fn print_err(error: impl Error) { +fn print_err(error: &dyn Error) { eprint!("{}", error); let mut e = error.source(); @@ -43,7 +147,7 @@ impl PrettyResult for Result { match self { Result::Ok(value) => value, Result::Err(error) => { - print_err(error); + print_err(&error); std::process::exit(1); } } @@ -51,91 +155,56 @@ impl PrettyResult for Result { } fn main() { + if let Err(e) = run() { + print_err(e.as_ref()); + std::process::exit(1); + } +} + +/// Error type for the CLI +#[derive(Debug, Clone)] +struct CliError(&'static str); +impl fmt::Display for CliError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} +impl std::error::Error for CliError {} + +fn run() -> Result<(), Box> { env_logger::init(); - let mut input_path = None; - let mut output_paths = Vec::new(); + // Initialize default parameters //TODO: read the parameters from RON? - #[allow(unused_mut)] let mut params = Parameters::default(); - let mut args = env::args(); - let _ = args.next().unwrap(); - #[allow(clippy::while_let_on_iterator)] - while let Some(arg) = args.next() { - //TODO: use `strip_prefix` when MSRV reaches 1.45.0 - if arg.starts_with("--") { - match &arg[2..] { - "validate" => { - let value = args.next().unwrap().parse().unwrap(); - params.validation_flags = - naga::valid::ValidationFlags::from_bits(value).unwrap(); - } - "index-bounds-check-policy" => { - let value = args.next().unwrap(); - params.index_bounds_check_policy = match value.as_str() { - "Restrict" => naga::back::IndexBoundsCheckPolicy::Restrict, - "ReadZeroSkipWrite" => { - naga::back::IndexBoundsCheckPolicy::ReadZeroSkipWrite - } - "UndefinedBehavior" => { - naga::back::IndexBoundsCheckPolicy::UndefinedBehavior - } - other => { - panic!( - "Unrecognized '--index-bounds-check-policy' value: {:?}", - other - ); - } - }; - } - "flow-dir" => params.spv_flow_dump_prefix = args.next(), - "entry-point" => params.entry_point = Some(args.next().unwrap()), - "profile" => { - use naga::back::glsl::Version; - let string = args.next().unwrap(); - //TODO: use `strip_prefix` in 1.45.0 - params.glsl.version = if string.starts_with("core") { - Version::Desktop(string[4..].parse().unwrap_or(330)) - } else if string.starts_with("es") { - Version::Embedded(string[2..].parse().unwrap_or(310)) - } else { - panic!("Unknown profile: {}", string) - }; - } - "shader-model" => { - use naga::back::hlsl::ShaderModel; - let string = args.next().unwrap(); - let sm_numb = string.parse::().unwrap(); - let sm = match string.parse().unwrap() { - 50 => ShaderModel::V5_0, - 51 => ShaderModel::V5_1, - 60 => ShaderModel::V6_0, - _ => panic!("Unsupported shader model: {}", sm_numb), - }; - params.hlsl.shader_model = sm; - } - other => log::warn!("Unknown parameter: {}", other), - } - } else if input_path.is_none() { - input_path = Some(arg); - } else { - output_paths.push(arg); - } + // Parse commandline arguments + let args: Args = argh::from_env(); + let input_path = Path::new(&args.input); + let mut output_paths = vec![args.output]; + output_paths.extend(args.extra_outputs); + + // Update parameters from commandline arguments + if args.validate { + params.validation_flags = naga::valid::ValidationFlags::all(); + } + if let Some(policy) = args.index_bounds_check_policy { + params.index_bounds_check_policy = policy.0; + } + params.spv_flow_dump_prefix = args.flow_dir; + params.entry_point = args.entry_point; + if let Some(version) = args.profile { + params.glsl.version = version.0; + } + if let Some(model) = args.shader_model { + params.hlsl.shader_model = model.0; } - let input_path = match input_path { - Some(ref string) => Path::new(string), - None => { - println!("Call with []"); - return; - } - }; - let module = match Path::new(input_path) + let module = match Path::new(&input_path) .extension() - .expect("Input has no extension?") + .ok_or(CliError("Input filename has no extension"))? .to_str() - .unwrap() + .ok_or(CliError("Input filename not valid unicode"))? { "spv" => { let options = naga::front::spv::Options { @@ -143,22 +212,22 @@ fn main() { strict_capabilities: false, flow_graph_dump_prefix: params.spv_flow_dump_prefix.map(std::path::PathBuf::from), }; - let input = fs::read(input_path).unwrap(); - naga::front::spv::parse_u8_slice(&input, &options).unwrap() + let input = fs::read(input_path)?; + naga::front::spv::parse_u8_slice(&input, &options)? } "wgsl" => { - let input = fs::read_to_string(input_path).unwrap(); + let input = fs::read_to_string(input_path)?; let result = naga::front::wgsl::parse_str(&input); match result { Ok(v) => v, Err(ref e) => { e.emit_to_stderr(&input); - panic!("unable to parse WGSL"); + return Err(CliError("Could not parse WGSL").into()); } } } "vert" => { - let input = fs::read_to_string(input_path).unwrap(); + let input = fs::read_to_string(input_path)?; let mut entry_points = naga::FastHashMap::default(); entry_points.insert("main".to_string(), naga::ShaderStage::Vertex); naga::front::glsl::parse_str( @@ -176,7 +245,7 @@ fn main() { }) } "frag" => { - let input = fs::read_to_string(input_path).unwrap(); + let input = fs::read_to_string(input_path)?; let mut entry_points = naga::FastHashMap::default(); entry_points.insert("main".to_string(), naga::ShaderStage::Fragment); naga::front::glsl::parse_str( @@ -194,7 +263,7 @@ fn main() { }) } "comp" => { - let input = fs::read_to_string(input_path).unwrap(); + let input = fs::read_to_string(input_path)?; let mut entry_points = naga::FastHashMap::default(); entry_points.insert("main".to_string(), naga::ShaderStage::Compute); naga::front::glsl::parse_str( @@ -211,7 +280,7 @@ fn main() { std::process::exit(1); }) } - other => panic!("Unknown input extension: {}", other), + _ => return Err(CliError("Unknown input file extension").into()), }; // validate the IR @@ -223,7 +292,7 @@ fn main() { { Ok(info) => Some(info), Err(error) => { - print_err(error); + print_err(&error); None } }; @@ -231,7 +300,7 @@ fn main() { if output_paths.is_empty() { if info.is_some() { println!("Validation successful"); - return; + return Ok(()); } else { std::process::exit(!0); } @@ -240,18 +309,18 @@ fn main() { for output_path in output_paths { match Path::new(&output_path) .extension() - .expect("Output has no extension?") + .ok_or(CliError("Output filename has no extension"))? .to_str() - .unwrap() + .ok_or(CliError("Output filename not valid unicode"))? { "txt" => { use std::io::Write; - let mut file = fs::File::create(output_path).unwrap(); - writeln!(file, "{:#?}", module).unwrap(); + let mut file = fs::File::create(output_path)?; + writeln!(file, "{:#?}", module)?; if let Some(ref info) = info { - writeln!(file).unwrap(); - writeln!(file, "{:#?}", info).unwrap(); + writeln!(file)?; + writeln!(file, "{:#?}", info)?; } } "metal" => { @@ -260,20 +329,30 @@ fn main() { let pipeline_options = msl::PipelineOptions::default(); let (msl, _) = msl::write_string( &module, - info.as_ref().unwrap(), + info.as_ref().ok_or(CliError( + "Generating metal output requires validation to \ + succeed, and it failed in a previous step", + ))?, ¶ms.msl, &pipeline_options, ) .unwrap_pretty(); - fs::write(output_path, msl).unwrap(); + fs::write(output_path, msl)?; } "spv" => { use naga::back::spv; params.spv.index_bounds_check_policy = params.index_bounds_check_policy; - let spv = - spv::write_vec(&module, info.as_ref().unwrap(), ¶ms.spv).unwrap_pretty(); + let spv = spv::write_vec( + &module, + info.as_ref().ok_or(CliError( + "Generating SPIR-V output requires validation to \ + succeed, and it failed in a previous step", + ))?, + ¶ms.spv, + ) + .unwrap_pretty(); let bytes = spv .iter() .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { @@ -281,7 +360,7 @@ fn main() { v }); - fs::write(output_path, bytes.as_slice()).unwrap(); + fs::write(output_path, bytes.as_slice())?; } stage @ "vert" | stage @ "frag" | stage @ "comp" => { use naga::back::glsl; @@ -303,40 +382,58 @@ fn main() { let mut writer = glsl::Writer::new( &mut buffer, &module, - info.as_ref().unwrap(), + info.as_ref().ok_or(CliError( + "Generating glsl output requires validation to \ + succeed, and it failed in a previous step", + ))?, ¶ms.glsl, &pipeline_options, ) .unwrap_pretty(); - writer.write().unwrap(); - fs::write(output_path, buffer).unwrap(); + writer.write()?; + fs::write(output_path, buffer)?; } "dot" => { use naga::back::dot; - let output = dot::write(&module, info.as_ref()).unwrap(); - fs::write(output_path, output).unwrap(); + let output = dot::write(&module, info.as_ref())?; + fs::write(output_path, output)?; } "hlsl" => { use naga::back::hlsl; let mut buffer = String::new(); let mut writer = hlsl::Writer::new(&mut buffer, ¶ms.hlsl); writer - .write(&module, info.as_ref().unwrap()) + .write( + &module, + info.as_ref().ok_or(CliError( + "Generating hsls output requires validation to \ + succeed, and it failed in a previous step", + ))?, + ) .unwrap_pretty(); - fs::write(output_path, buffer).unwrap(); + fs::write(output_path, buffer)?; } "wgsl" => { use naga::back::wgsl; - let wgsl = wgsl::write_string(&module, info.as_ref().unwrap()).unwrap_pretty(); - fs::write(output_path, wgsl).unwrap(); + let wgsl = wgsl::write_string( + &module, + info.as_ref().ok_or(CliError( + "Generating wgsl output requires validation to \ + succeed, and it failed in a previous step", + ))?, + ) + .unwrap_pretty(); + fs::write(output_path, wgsl)?; } other => { println!("Unknown output extension: {}", other); } } } + + Ok(()) } use codespan_reporting::{ From 80bdc74770d6f2b0b77319a82c72f74d186c5b52 Mon Sep 17 00:00:00 2001 From: Zicklag Date: Tue, 20 Jul 2021 13:28:16 -0500 Subject: [PATCH 1133/2212] Gate GLSL Dynamic Array Size to Supported Versions Will fail with an error when trying to generate a GLSL shader that has dynamically sized arrays in a version of GLSL that does not support dynamically sized arrays. --- src/back/glsl/features.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 118840dc2..95a7787d4 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -32,6 +32,8 @@ bitflags::bitflags! { const CULL_DISTANCE = 1 << 14; // Sample ID const SAMPLE_VARIABLES = 1 << 15; + /// Arrays with a dynamic length + const DYNAMIC_ARRAY_SIZE = 1 << 16; } } @@ -98,6 +100,7 @@ impl FeaturesManager { check_feature!(CLIP_DISTANCE, 130, 300); check_feature!(CULL_DISTANCE, 450, 300); check_feature!(SAMPLE_VARIABLES, 400, 300); + check_feature!(DYNAMIC_ARRAY_SIZE, 430, 310); // Return an error if there are missing features if missing.is_empty() { @@ -228,10 +231,14 @@ impl<'a, W> Writer<'a, W> { TypeInner::Matrix { width, .. } => { self.scalar_required_features(ScalarKind::Float, width) } - TypeInner::Array { base, .. } => { + TypeInner::Array { base, size, .. } => { if let TypeInner::Array { .. } = self.module.types[base].inner { self.features.request(Features::ARRAY_OF_ARRAYS) } + + if size == crate::ArraySize::Dynamic { + self.features.request(Features::DYNAMIC_ARRAY_SIZE); + } } TypeInner::Image { dim, From 140a9bfa8f4a7eaf1bfaa0cdf1742f034e268d81 Mon Sep 17 00:00:00 2001 From: Zicklag Date: Tue, 20 Jul 2021 15:09:23 -0500 Subject: [PATCH 1134/2212] Fix Regression With CLI Not Working for Validation Allows output file to be left empty to perform validation only. --- cli/src/main.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index d363359a2..701e1cad1 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -38,13 +38,9 @@ struct Args { #[argh(positional)] input: String, - /// the output file + /// the output file. If not specified, only validation will be performed #[argh(positional)] - output: String, - - /// other output files if there are multiples - #[argh(positional)] - extra_outputs: Vec, + output: Vec, } /// Newtype so we can implement [`FromStr`] for `IndexBoundsCheckPolicy`. @@ -181,8 +177,7 @@ fn run() -> Result<(), Box> { // Parse commandline arguments let args: Args = argh::from_env(); let input_path = Path::new(&args.input); - let mut output_paths = vec![args.output]; - output_paths.extend(args.extra_outputs); + let output_paths = args.output; // Update parameters from commandline arguments if args.validate { From e017cb402e2e7237ad3cc7ee41eae0c5b3296770 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 20 Jul 2021 21:42:15 +0300 Subject: [PATCH 1135/2212] [glsl-out] Add stage postfix for block structs --- src/back/glsl/mod.rs | 7 ++++++- tests/out/glsl/boids.main.Compute.glsl | 6 +++--- tests/out/glsl/quad-vert.main.Vertex.glsl | 2 +- tests/out/glsl/shadow.fs_main.Fragment.glsl | 4 ++-- tests/out/glsl/skybox.vs_main.Vertex.glsl | 2 +- 5 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b3b139af3..c0d1a6b30 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1200,7 +1200,12 @@ impl<'a, W: Write> Writer<'a, W> { // generated number so it's unique and `members` are the same as in a struct if block { // Write the block name, it's just the struct name appended with `_block_ID` - let block_name = format!("{}_block_{}", name, self.block_id.generate()); + let stage_postfix = match self.entry_point.stage { + ShaderStage::Vertex => "Vs", + ShaderStage::Fragment => "Fs", + ShaderStage::Compute => "Cs", + }; + let block_name = format!("{}_block_{}{}", name, self.block_id.generate(), stage_postfix); writeln!(self.out, "{} {{", block_name)?; self.reflection_names.insert(handle, block_name); diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 0893dc810..4c4cec0a3 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -10,7 +10,7 @@ struct Particle { vec2 vel; }; -uniform SimParams_block_0 { +uniform SimParams_block_0Cs { float deltaT; float rule1Distance; float rule2Distance; @@ -20,11 +20,11 @@ uniform SimParams_block_0 { float rule3Scale; } _group_0_binding_0; -readonly buffer Particles_block_1 { +readonly buffer Particles_block_1Cs { Particle particles[]; } _group_0_binding_1; -buffer Particles_block_2 { +buffer Particles_block_2Cs { Particle particles[]; } _group_0_binding_2; diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index 970c26840..029373548 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -15,7 +15,7 @@ vec2 v_uv = vec2(0, 0); vec2 a_uv1 = vec2(0, 0); -struct gen_gl_PerVertex_block_0 { +struct gen_gl_PerVertex_block_0Vs { vec4 gen_gl_Position; float gen_gl_PointSize; float gen_gl_ClipDistance[1]; diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index af217b631..95466dc3a 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -9,11 +9,11 @@ struct Light { vec4 color; }; -uniform Globals_block_0 { +uniform Globals_block_0Fs { uvec4 num_lights; } _group_0_binding_0; -readonly buffer Lights_block_1 { +readonly buffer Lights_block_1Fs { Light data[]; } _group_0_binding_1; diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index 6d3795565..a49f78a93 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -8,7 +8,7 @@ struct VertexOutput { vec3 uv; }; -layout(binding = 0) uniform Data_block_0 { +layout(binding = 0) uniform Data_block_0Vs { mat4x4 proj_inv; mat4x4 view; } _group_0_binding_0; From 82b2fe441048ea81adbeb5c89e8c9f57cb48cfb2 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Tue, 20 Jul 2021 22:51:34 +0300 Subject: [PATCH 1136/2212] [glsl-out] Fix zero initialization --- src/back/glsl/mod.rs | 93 ++++++++++++++++------- tests/out/glsl/quad-vert.main.Vertex.glsl | 6 +- 2 files changed, 69 insertions(+), 30 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c0d1a6b30..71e7096e7 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -812,9 +812,18 @@ impl<'a, W: Write> Writer<'a, W> { if let TypeInner::Array { size, .. } = self.module.types[global.ty].inner { self.write_array_size(size)?; } - if let Some(default_value) = zero_init_value_str(&self.module.types[global.ty].inner) { - write!(self.out, " = {}", default_value)?; - }; + + match self.module.types[global.ty].inner { + TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => { + write!(self.out, " = ")?; + if let Some(init) = global.init { + self.write_constant(&self.module.constants[init])?; + } else { + self.write_zero_init_value(&self.module.types[global.ty].inner)?; + } + } + _ => {} + } writeln!(self.out, ";")?; Ok(()) @@ -1205,7 +1214,12 @@ impl<'a, W: Write> Writer<'a, W> { ShaderStage::Fragment => "Fs", ShaderStage::Compute => "Cs", }; - let block_name = format!("{}_block_{}{}", name, self.block_id.generate(), stage_postfix); + let block_name = format!( + "{}_block_{}{}", + name, + self.block_id.generate(), + stage_postfix + ); writeln!(self.out, "{} {{", block_name)?; self.reflection_names.insert(handle, block_name); @@ -2334,6 +2348,54 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper function that write string with default zero initialization for supported types + fn write_zero_init_value(&mut self, inner: &TypeInner) -> BackendResult { + match *inner { + TypeInner::Scalar { kind, .. } => { + self.write_zero_init_scalar(kind)?; + } + TypeInner::Vector { size, kind, .. } => { + self.write_value_type(inner)?; + write!(self.out, "(")?; + for _ in 1..(size as usize) { + self.write_zero_init_scalar(kind)?; + write!(self.out, ", ")?; + } + // write last parameter without comma and space + self.write_zero_init_scalar(kind)?; + write!(self.out, ")")?; + } + TypeInner::Matrix { columns, rows, .. } => { + let number_of_components = (columns as usize) * (rows as usize); + self.write_value_type(inner)?; + write!(self.out, "(")?; + for _ in 1..number_of_components { + // IR supports only float matrix + self.write_zero_init_scalar(crate::ScalarKind::Float)?; + write!(self.out, ", ")?; + } + // write last parameter without comma and space + self.write_zero_init_scalar(crate::ScalarKind::Float)?; + write!(self.out, ")")?; + } + _ => {} // TODO: + } + + Ok(()) + } + + /// Helper function that write string with zero initialization for scalar + fn write_zero_init_scalar(&mut self, kind: crate::ScalarKind) -> BackendResult { + match kind { + crate::ScalarKind::Bool => write!(self.out, "false")?, + crate::ScalarKind::Uint => write!(self.out, "0u")?, + crate::ScalarKind::Float => write!(self.out, "0.0")?, + crate::ScalarKind::Sint => write!(self.out, "0")?, + } + + Ok(()) + } + /// Helper method used to produce the reflection info that's returned to the user /// /// It takes an iterator of [`Function`](crate::Function) references instead of @@ -2581,26 +2643,3 @@ fn glsl_storage_access(storage_access: crate::StorageAccess) -> Option<&'static None } } - -/// Helper function that return string with default zero initialization for supported types -fn zero_init_value_str(inner: &TypeInner) -> Option { - match *inner { - TypeInner::Scalar { kind, .. } => match kind { - crate::ScalarKind::Bool => Some(String::from("false")), - _ => Some(String::from("0")), - }, - TypeInner::Vector { size, kind, width } => { - if let Ok(scalar_string) = glsl_scalar(kind, width) { - let vec_type = format!("{}vec{}", scalar_string.prefix, size as u8); - match size { - crate::VectorSize::Bi => Some(format!("{}(0, 0)", vec_type)), - crate::VectorSize::Tri => Some(format!("{}(0, 0, 0)", vec_type)), - crate::VectorSize::Quad => Some(format!("{}(0, 0, 0, 0)", vec_type)), - } - } else { - None - } - } - _ => None, - } -} diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index 029373548..0e746e8f2 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -11,9 +11,9 @@ struct type10 { float gen_gl_CullDistance[1]; }; -vec2 v_uv = vec2(0, 0); +vec2 v_uv = vec2(0.0, 0.0); -vec2 a_uv1 = vec2(0, 0); +vec2 a_uv1 = vec2(0.0, 0.0); struct gen_gl_PerVertex_block_0Vs { vec4 gen_gl_Position; @@ -22,7 +22,7 @@ struct gen_gl_PerVertex_block_0Vs { float gen_gl_CullDistance[1]; } perVertexStruct; -vec2 a_pos1 = vec2(0, 0); +vec2 a_pos1 = vec2(0.0, 0.0); layout(location = 1) in vec2 _p2vs_location1; layout(location = 0) in vec2 _p2vs_location0; From bdcab5323140b15e075f0b89bd905ffa3e649218 Mon Sep 17 00:00:00 2001 From: Zicklag Date: Wed, 21 Jul 2021 16:43:00 -0500 Subject: [PATCH 1137/2212] Skip Early Depth Test When Unsupported in GLSL --- src/back/glsl/features.rs | 5 ++++- src/back/glsl/mod.rs | 29 +++++++++++++++++++---------- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 95a7787d4..ab2182b46 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -206,7 +206,10 @@ impl<'a, W> Writer<'a, W> { /// [`Error::MissingFeatures`](super::Error::MissingFeatures) will be returned pub(super) fn collect_required_features(&mut self) -> BackendResult { if let Some(depth_test) = self.entry_point.early_depth_test { - self.features.request(Features::IMAGE_LOAD_STORE); + // If IMAGE_LOAD_STORE is supported for this version of GLSL + if self.options.version.supports_early_depth_test() { + self.features.request(Features::IMAGE_LOAD_STORE); + } if depth_test.conservative.is_some() { self.features.request(Features::CONSERVATIVE_DEPTH); diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 71e7096e7..fa22ac818 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -110,6 +110,10 @@ impl Version { fn supports_explicit_locations(&self) -> bool { *self >= Version::Embedded(310) || *self >= Version::Desktop(410) } + + fn supports_early_depth_test(&self) -> bool { + *self >= Version::Desktop(130) || *self >= Version::Embedded(310) + } } impl PartialOrd for Version { @@ -430,22 +434,27 @@ impl<'a, W: Write> Writer<'a, W> { // Enable early depth tests if needed if let Some(depth_test) = self.entry_point.early_depth_test { - writeln!(self.out, "layout(early_fragment_tests) in;")?; + // If early depth test is supported for this version of GLSL + if self.options.version.supports_early_depth_test() { + writeln!(self.out, "layout(early_fragment_tests) in;")?; - if let Some(conservative) = depth_test.conservative { - use crate::ConservativeDepth as Cd; + if let Some(conservative) = depth_test.conservative { + use crate::ConservativeDepth as Cd; - writeln!( - self.out, - "layout (depth_{}) out float gl_FragDepth;", - match conservative { + let depth = match conservative { Cd::GreaterEqual => "greater", Cd::LessEqual => "less", Cd::Unchanged => "unchanged", - } - )?; + }; + writeln!(self.out, "layout (depth_{}) out float gl_FragDepth;", depth)?; + } + writeln!(self.out)?; + } else { + log::warn!( + "Early depth testing is not supported for this version of GLSL: {}", + self.options.version + ); } - writeln!(self.out)?; } // Write all structs From 12f25c8ce4dba2461b0eea3b998370b183f28222 Mon Sep 17 00:00:00 2001 From: Zicklag Date: Wed, 21 Jul 2021 12:59:33 -0500 Subject: [PATCH 1138/2212] Prune Unused, Unsized Types From GLSL Output --- src/back/glsl/features.rs | 45 ++++++++++++++++++++++++++++++++++++--- src/back/glsl/mod.rs | 8 ++++--- 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index ab2182b46..70bef0126 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -205,6 +205,8 @@ impl<'a, W> Writer<'a, W> { /// If the version doesn't support any of the needed [`Features`](Features) a /// [`Error::MissingFeatures`](super::Error::MissingFeatures) will be returned pub(super) fn collect_required_features(&mut self) -> BackendResult { + let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); + if let Some(depth_test) = self.entry_point.early_depth_test { // If IMAGE_LOAD_STORE is supported for this version of GLSL if self.options.version.supports_early_depth_test() { @@ -227,7 +229,7 @@ impl<'a, W> Writer<'a, W> { self.features.request(Features::COMPUTE_SHADER) } - for (_, ty) in self.module.types.iter() { + for (ty_handle, ty) in self.module.types.iter() { match ty.inner { TypeInner::Scalar { kind, width } => self.scalar_required_features(kind, width), TypeInner::Vector { kind, width, .. } => self.scalar_required_features(kind, width), @@ -239,8 +241,42 @@ impl<'a, W> Writer<'a, W> { self.features.request(Features::ARRAY_OF_ARRAYS) } + // If the array is dynamically sized if size == crate::ArraySize::Dynamic { - self.features.request(Features::DYNAMIC_ARRAY_SIZE); + let mut is_used = false; + + // Check if this type is used in a global that is needed by the current entrypoint + for (global_handle, global) in self.module.global_variables.iter() { + // Skip unused globals + if ep_info[global_handle].is_empty() { + continue; + } + + // If this array is the type of a global, then this array is used + if global.ty == ty_handle { + is_used = true; + break; + } + + // If the type of this global is a struct + if let crate::TypeInner::Struct { ref members, .. } = + self.module.types[global.ty].inner + { + // Check the last element of the struct to see if it's type uses + // this array + if let Some(last) = members.last() { + if last.ty == ty_handle { + is_used = true; + break; + } + } + } + } + + // If this dynamically size array is used, we need dynamic array size support + if is_used { + self.features.request(Features::DYNAMIC_ARRAY_SIZE); + } } } TypeInner::Image { @@ -292,7 +328,10 @@ impl<'a, W> Writer<'a, W> { } } - for (_, global) in self.module.global_variables.iter() { + for (handle, global) in self.module.global_variables.iter() { + if ep_info[handle].is_empty() { + continue; + } match global.class { StorageClass::WorkGroup => self.features.request(Features::COMPUTE_SHADER), StorageClass::Storage => self.features.request(Features::BUFFER_STORAGE), diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index fa22ac818..46ef88318 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -554,9 +554,11 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Sampler { .. } => continue, // All other globals are written by `write_global` _ => { - self.write_global(handle, global)?; - // Add a newline (only for readability) - writeln!(self.out)?; + if !ep_info[handle].is_empty() { + self.write_global(handle, global)?; + // Add a newline (only for readability) + writeln!(self.out)?; + } } } } From 20c4d2c3d1c8be3c77f60d66606a79d01f750562 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 21 Jul 2021 20:06:56 -0400 Subject: [PATCH 1139/2212] Add MSAA depth texture type --- src/back/glsl/features.rs | 6 +- src/back/glsl/mod.rs | 15 +- src/back/hlsl/image.rs | 237 ++++++++--------- src/back/hlsl/writer.rs | 9 +- src/back/msl/writer.rs | 9 +- src/back/spv/block.rs | 8 +- src/back/spv/instructions.rs | 2 +- src/back/spv/writer.rs | 2 +- src/back/wgsl/writer.rs | 6 +- src/front/spv/image.rs | 4 +- src/front/wgsl/mod.rs | 35 ++- src/lib.rs | 6 +- src/proc/typifier.rs | 2 +- src/valid/expression.rs | 16 +- tests/in/image.wgsl | 7 +- tests/out/hlsl/image.hlsl | 8 +- tests/out/hlsl/shadow.hlsl | 2 +- tests/out/ir/shadow.ron | 4 +- tests/out/msl/image.msl | 12 +- tests/out/spv/image.spvasm | 494 ++++++++++++++++++----------------- tests/out/wgsl/image.wgsl | 7 +- 21 files changed, 480 insertions(+), 411 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 70bef0126..a9eb93fed 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -291,7 +291,8 @@ impl<'a, W> Writer<'a, W> { } match class { - ImageClass::Sampled { multi: true, .. } => { + ImageClass::Sampled { multi: true, .. } + | ImageClass::Depth { multi: true } => { self.features.request(Features::MULTISAMPLED_TEXTURES); if arrayed { self.features.request(Features::MULTISAMPLED_TEXTURE_ARRAYS); @@ -321,7 +322,8 @@ impl<'a, W> Writer<'a, W> { } _ => {} }, - _ => {} + ImageClass::Sampled { multi: false, .. } + | ImageClass::Depth { multi: false } => {} } } _ => {} diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 46ef88318..30105917e 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -758,7 +758,8 @@ impl<'a, W: Write> Writer<'a, W> { let (base, kind, ms, comparison) = match class { Ic::Sampled { kind, multi: true } => ("sampler", kind, "MS", ""), Ic::Sampled { kind, multi: false } => ("sampler", kind, "", ""), - Ic::Depth => ("sampler", crate::ScalarKind::Float, "", "Shadow"), + Ic::Depth { multi: true } => ("sampler", crate::ScalarKind::Float, "MS", ""), + Ic::Depth { multi: false } => ("sampler", crate::ScalarKind::Float, "", "Shadow"), Ic::Storage(format) => ("image", format.into(), "", ""), }; @@ -1945,7 +1946,9 @@ impl<'a, W: Write> Writer<'a, W> { crate::ImageClass::Sampled { .. } => "texelFetch", crate::ImageClass::Storage(_) => "imageLoad", // TODO: Is there even a function for this? - crate::ImageClass::Depth => todo!(), + crate::ImageClass::Depth { multi: _ } => { + return Err(Error::Custom("TODO: depth sample loads".to_string())) + } }; write!(self.out, "{}(", fun_name)?; @@ -1984,7 +1987,7 @@ impl<'a, W: Write> Writer<'a, W> { match query { crate::ImageQuery::Size { level } => { match class { - ImageClass::Sampled { .. } | ImageClass::Depth => { + ImageClass::Sampled { .. } | ImageClass::Depth { .. } => { write!(self.out, "textureSize(")?; self.write_expr(image, ctx)?; write!(self.out, ",")?; @@ -2008,7 +2011,7 @@ impl<'a, W: Write> Writer<'a, W> { } crate::ImageQuery::NumLayers => { let fun_name = match class { - ImageClass::Sampled { .. } | ImageClass::Depth => "textureSize", + ImageClass::Sampled { .. } | ImageClass::Depth { .. } => "textureSize", ImageClass::Storage(_) => "imageSize", }; write!(self.out, "{}(", fun_name)?; @@ -2018,7 +2021,9 @@ impl<'a, W: Write> Writer<'a, W> { crate::ImageQuery::NumSamples => { // assumes ARB_shader_texture_image_samples let fun_name = match class { - ImageClass::Sampled { .. } | ImageClass::Depth => "textureSamples", + ImageClass::Sampled { .. } | ImageClass::Depth { .. } => { + "textureSamples" + } ImageClass::Storage(_) => "imageSamples", }; write!(self.out, "{}(", fun_name)?; diff --git a/src/back/hlsl/image.rs b/src/back/hlsl/image.rs index 67e940d2d..306f35200 100644 --- a/src/back/hlsl/image.rs +++ b/src/back/hlsl/image.rs @@ -101,8 +101,11 @@ impl<'a, W: Write> super::Writer<'a, W> { let dim_str = query.dim.to_hlsl_str(); let class_str = match query.class { crate::ImageClass::Sampled { multi: true, .. } => "MS", - crate::ImageClass::Depth => "Depth", - _ => "", + crate::ImageClass::Depth { multi: true } => "DepthMS", + crate::ImageClass::Depth { multi: false } => "Depth", + crate::ImageClass::Sampled { multi: false, .. } | crate::ImageClass::Storage { .. } => { + "" + } }; let arrayed_str = if query.arrayed { "Array" } else { "" }; let query_str = match query.query { @@ -129,127 +132,125 @@ impl<'a, W: Write> super::Writer<'a, W> { module: &crate::Module, func_ctx: &FunctionCtx, ) -> BackendResult { + use crate::{back::INDENT, ImageDimension as IDim, ImageQuery as Iq}; + + const RETURN_VARIABLE_NAME: &str = "ret"; + const MIP_LEVEL_PARAM: &str = "MipLevel"; + for (handle, _) in func_ctx.expressions.iter() { - if let crate::Expression::ImageQuery { image, query } = func_ctx.expressions[handle] { - let image_ty = func_ctx.info[image].ty.inner_with(&module.types); - match *image_ty { - crate::TypeInner::Image { - dim, - arrayed, - class, - } => { - use crate::back::INDENT; + let (image, query) = match func_ctx.expressions[handle] { + crate::Expression::ImageQuery { image, query } => (image, query), + _ => continue, + }; + let image_ty = func_ctx.info[image].ty.inner_with(&module.types); + let ret_ty = func_ctx.info[handle].ty.inner_with(&module.types); - let ret_ty = func_ctx.info[handle].ty.inner_with(&module.types); + let (dim, arrayed, class) = match *image_ty { + crate::TypeInner::Image { + dim, + arrayed, + class, + } => (dim, arrayed, class), + _ => unreachable!("we only query images"), + }; - let wrapped_image_query = WrappedImageQuery { - dim, - arrayed, - class, - query: query.into(), - }; + let wrapped_image_query = WrappedImageQuery { + dim, + arrayed, + class, + query: query.into(), + }; - if !self.wrapped_image_queries.contains(&wrapped_image_query) { - // Write function return type and name - self.write_value_type(module, ret_ty)?; - write!(self.out, " ")?; - self.write_wrapped_image_query_function_name(wrapped_image_query)?; - - // Write function parameters - write!(self.out, "(")?; - // Texture always first parameter - self.write_value_type(module, image_ty)?; - // Mipmap is a second parameter if exists - const MIP_LEVEL_PARAM: &str = "MipLevel"; - if let crate::ImageQuery::Size { level: Some(_) } = query { - write!(self.out, ", uint {}", MIP_LEVEL_PARAM)?; - } - writeln!(self.out, ")")?; - - // Write function body - writeln!(self.out, "{{")?; - const RETURN_VARIABLE_NAME: &str = "ret"; - - use crate::ImageDimension as IDim; - use crate::ImageQuery as Iq; - - let array_coords = if arrayed { 1 } else { 0 }; - // GetDimensions Overloaded Methods - // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods - let (ret_swizzle, number_of_params) = match query { - Iq::Size { .. } => match dim { - IDim::D1 => ("x", 1 + array_coords), - IDim::D2 => ("xy", 3 + array_coords), - IDim::D3 => ("xyz", 4), - IDim::Cube => ("xy", 3 + array_coords), - }, - Iq::NumLevels | Iq::NumSamples | Iq::NumLayers => { - if arrayed || dim == IDim::D3 { - ("w", 4) - } else { - ("z", 3) - } - } - }; - - // Write `GetDimensions` function. - writeln!(self.out, "{}uint4 {};", INDENT, RETURN_VARIABLE_NAME)?; - write!(self.out, "{}", INDENT)?; - self.write_expr(module, image, func_ctx)?; - write!(self.out, ".GetDimensions(")?; - match query { - Iq::Size { level: Some(_) } => { - write!(self.out, "{}, ", MIP_LEVEL_PARAM)?; - } - _ => - // Write zero mipmap level for supported types - { - if let crate::ImageClass::Sampled { multi: true, .. } = class { - } else { - match dim { - IDim::D2 | IDim::D3 | IDim::Cube => { - write!(self.out, "0, ")?; - } - IDim::D1 => {} - } - } - } - } - - for component in crate::back::COMPONENTS[..number_of_params - 1].iter() - { - write!(self.out, "{}.{}, ", RETURN_VARIABLE_NAME, component)?; - } - - // write last parameter without comma and space for last parameter - write!( - self.out, - "{}.{}", - RETURN_VARIABLE_NAME, - crate::back::COMPONENTS[number_of_params - 1] - )?; - - writeln!(self.out, ");")?; - - // Write return value - writeln!( - self.out, - "{}return {}.{};", - INDENT, RETURN_VARIABLE_NAME, ret_swizzle - )?; - - // End of function body - writeln!(self.out, "}}")?; - // Write extra new line - writeln!(self.out)?; - - self.wrapped_image_queries.insert(wrapped_image_query); - } - } - // Here we work only with image types - _ => unreachable!(), - } + if self.wrapped_image_queries.contains(&wrapped_image_query) { + continue; } + + // Write function return type and name + self.write_value_type(module, ret_ty)?; + write!(self.out, " ")?; + self.write_wrapped_image_query_function_name(wrapped_image_query)?; + + // Write function parameters + write!(self.out, "(")?; + // Texture always first parameter + self.write_value_type(module, image_ty)?; + // Mipmap is a second parameter if exists + if let crate::ImageQuery::Size { level: Some(_) } = query { + write!(self.out, ", uint {}", MIP_LEVEL_PARAM)?; + } + writeln!(self.out, ")")?; + + // Write function body + writeln!(self.out, "{{")?; + + let array_coords = if arrayed { 1 } else { 0 }; + // GetDimensions Overloaded Methods + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods + let (ret_swizzle, number_of_params) = match query { + Iq::Size { .. } => match dim { + IDim::D1 => ("x", 1 + array_coords), + IDim::D2 => ("xy", 3 + array_coords), + IDim::D3 => ("xyz", 4), + IDim::Cube => ("xy", 3 + array_coords), + }, + Iq::NumLevels | Iq::NumSamples | Iq::NumLayers => { + if arrayed || dim == IDim::D3 { + ("w", 4) + } else { + ("z", 3) + } + } + }; + + // Write `GetDimensions` function. + writeln!(self.out, "{}uint4 {};", INDENT, RETURN_VARIABLE_NAME)?; + write!(self.out, "{}", INDENT)?; + self.write_expr(module, image, func_ctx)?; + write!(self.out, ".GetDimensions(")?; + match query { + Iq::Size { level: Some(_) } => { + write!(self.out, "{}, ", MIP_LEVEL_PARAM)?; + } + _ => match class { + crate::ImageClass::Sampled { multi: true, .. } + | crate::ImageClass::Depth { multi: true } => {} + _ => match dim { + // Write zero mipmap level for supported types + IDim::D2 | IDim::D3 | IDim::Cube => { + write!(self.out, "0, ")?; + } + IDim::D1 => {} + }, + }, + } + + for component in crate::back::COMPONENTS[..number_of_params - 1].iter() { + write!(self.out, "{}.{}, ", RETURN_VARIABLE_NAME, component)?; + } + + // write last parameter without comma and space for last parameter + write!( + self.out, + "{}.{}", + RETURN_VARIABLE_NAME, + crate::back::COMPONENTS[number_of_params - 1] + )?; + + writeln!(self.out, ");")?; + + // Write return value + writeln!( + self.out, + "{}return {}.{};", + INDENT, RETURN_VARIABLE_NAME, ret_swizzle + )?; + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + + self.wrapped_image_queries.insert(wrapped_image_query); } Ok(()) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 4571531ca..897ff47f8 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -629,7 +629,10 @@ impl<'a, W: Write> Writer<'a, W> { let arrayed_str = if arrayed { "Array" } else { "" }; write!(self.out, "Texture{}{}", dim_str, arrayed_str)?; match class { - Ic::Depth => {} + Ic::Depth { multi } => { + let multi_str = if multi { "MS" } else { "" }; + write!(self.out, "{}", multi_str)? + } Ic::Sampled { kind, multi } => { let multi_str = if multi { "MS" } else { "" }; let scalar_kind_str = scalar_kind_str(kind, 4)?; @@ -1245,6 +1248,10 @@ impl<'a, W: Write> Writer<'a, W> { crate::TypeInner::Image { class: crate::ImageClass::Sampled { multi, .. }, .. + } + | crate::TypeInner::Image { + class: crate::ImageClass::Depth { multi }, + .. } => multi, _ => false, }; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 5634b60a6..0b5456294 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -149,7 +149,14 @@ impl<'a> Display for TypeContext<'a> { }; ("texture", msaa_str, kind, access) } - crate::ImageClass::Depth => ("depth", "", crate::ScalarKind::Float, "sample"), + crate::ImageClass::Depth { multi } => { + let (msaa_str, access) = if multi { + ("_ms", "read") + } else { + ("", "sample") + }; + ("depth", msaa_str, crate::ScalarKind::Float, access) + } crate::ImageClass::Storage(format) => { let access = if self .access diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index dbac0b845..d6493ac71 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -728,7 +728,7 @@ impl<'w> BlockContext<'w> { .. } => Instruction::image_read(result_type_id, id, image_id, coordinate_id), crate::TypeInner::Image { - class: crate::ImageClass::Depth, + class: crate::ImageClass::Depth { multi: _ }, .. } => { // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, @@ -752,6 +752,10 @@ impl<'w> BlockContext<'w> { crate::TypeInner::Image { class: crate::ImageClass::Sampled { multi: true, .. }, .. + } + | crate::TypeInner::Image { + class: crate::ImageClass::Depth { multi: true }, + .. } => spirv::ImageOperands::SAMPLE, _ => spirv::ImageOperands::LOD, }; @@ -791,7 +795,7 @@ impl<'w> BlockContext<'w> { // so we need to grab the first component out of it. let needs_sub_access = match self.ir_module.types[image_type].inner { crate::TypeInner::Image { - class: crate::ImageClass::Depth, + class: crate::ImageClass::Depth { .. }, .. } => depth_ref.is_none(), _ => false, diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 97fe602dd..851952326 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -233,7 +233,7 @@ impl super::Instruction { let (depth, multi, sampled) = match image_class { crate::ImageClass::Sampled { kind: _, multi } => (false, multi, true), - crate::ImageClass::Depth => (true, false, true), + crate::ImageClass::Depth { multi } => (true, multi, true), crate::ImageClass::Storage(_) => (false, false, false), }; instruction.add_operand(depth as u32); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 7fd292129..d164e6832 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -701,7 +701,7 @@ impl Writer { } => { let kind = match class { crate::ImageClass::Sampled { kind, multi: _ } => kind, - crate::ImageClass::Depth => crate::ScalarKind::Float, + crate::ImageClass::Depth { multi: _ } => crate::ScalarKind::Float, crate::ImageClass::Storage(format) => { let required_caps: &[_] = match dim { crate::ImageDimension::D1 => &[spirv::Capability::Image1D], diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 8922f9358..ae3b548f1 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -486,7 +486,11 @@ impl Writer { if multi { "multisampled_" } else { "" }, format!("<{}>", scalar_kind_str(kind)), ), - Ic::Depth => ("depth_", "", String::from("")), + Ic::Depth { multi } => ( + "depth_", + if multi { "multisampled_" } else { "" }, + String::from(""), + ), Ic::Storage(storage_format) => ( "storage_", "", diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index a4b1c9fbd..aee635999 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -178,11 +178,11 @@ pub(super) fn patch_comparison_type( let original_ty = &arena[var.ty]; let ty_inner = match original_ty.inner { crate::TypeInner::Image { - class: _, + class: crate::ImageClass::Sampled { multi, .. }, dim, arrayed, } => crate::TypeInner::Image { - class: crate::ImageClass::Depth, + class: crate::ImageClass::Depth { multi }, dim, arrayed, }, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index bb40deb80..ba85ede39 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -452,8 +452,10 @@ impl crate::TypeInner { let class_suffix = match class { crate::ImageClass::Sampled { multi: true, .. } => "_multisampled", - crate::ImageClass::Depth => "_depth", - _ => "", + crate::ImageClass::Depth { multi: false } => "_depth", + crate::ImageClass::Depth { multi: true } => "_depth_multisampled", + crate::ImageClass::Sampled { multi: false, .. } + | crate::ImageClass::Storage { .. } => "", }; let type_in_brackets = match class { @@ -464,7 +466,7 @@ impl crate::TypeInner { let element_type = kind.to_wgsl(4); format!("<{}>", element_type) } - crate::ImageClass::Depth => String::new(), + crate::ImageClass::Depth { multi: _ } => String::new(), crate::ImageClass::Storage(format) => { format!("<{}>", format.to_wgsl()) } @@ -547,9 +549,19 @@ mod type_inner_tests { let img2 = crate::TypeInner::Image { dim: crate::ImageDimension::Cube, arrayed: true, - class: crate::ImageClass::Depth, + class: crate::ImageClass::Depth { multi: false }, }; assert_eq!(img2.to_wgsl(&types, &constants), "texture_depth_cube_array"); + + let img3 = crate::TypeInner::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Depth { multi: true }, + }; + assert_eq!( + img3.to_wgsl(&types, &constants), + "texture_depth_multisampled_2d" + ); } } @@ -1342,7 +1354,7 @@ impl Parser { let index = match class { crate::ImageClass::Storage(_) => None, // it's the MSAA index for multi-sampled, and LOD for the others - crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth => { + crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) } @@ -2328,22 +2340,27 @@ impl Parser { "texture_depth_2d" => crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: false, - class: crate::ImageClass::Depth, + class: crate::ImageClass::Depth { multi: false }, }, "texture_depth_2d_array" => crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: true, - class: crate::ImageClass::Depth, + class: crate::ImageClass::Depth { multi: false }, }, "texture_depth_cube" => crate::TypeInner::Image { dim: crate::ImageDimension::Cube, arrayed: false, - class: crate::ImageClass::Depth, + class: crate::ImageClass::Depth { multi: false }, }, "texture_depth_cube_array" => crate::TypeInner::Image { dim: crate::ImageDimension::Cube, arrayed: true, - class: crate::ImageClass::Depth, + class: crate::ImageClass::Depth { multi: false }, + }, + "texture_depth_multisampled_2d" => crate::TypeInner::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Depth { multi: true }, }, "texture_storage_1d" => { let format = lexer.next_format_generic()?; diff --git a/src/lib.rs b/src/lib.rs index 70c284349..ad6821dac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -468,7 +468,10 @@ pub enum ImageClass { multi: bool, }, /// Depth comparison image. - Depth, + Depth { + /// Multi-sampled depth image. + multi: bool, + }, /// Storage image. Storage(StorageFormat), } @@ -595,6 +598,7 @@ pub enum TypeInner { Image { dim: ImageDimension, arrayed: bool, + //TODO: consider moving `multisampled: bool` out class: ImageClass, }, /// Can be used to sample values from images. diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index f25e4ef5c..bb3fa0996 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -368,7 +368,7 @@ impl<'a> ResolveContext<'a> { crate::Expression::ImageSample { image, .. } | crate::Expression::ImageLoad { image, .. } => match *past(image).inner_with(types) { Ti::Image { class, .. } => TypeResolution::Value(match class { - crate::ImageClass::Depth => Ti::Scalar { + crate::ImageClass::Depth { multi: _ } => Ti::Scalar { kind: crate::ScalarKind::Float, width: 4, }, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 990026d9b..01f30e2cd 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -93,8 +93,6 @@ pub enum ExpressionError { InvalidSampleOffset(crate::ImageDimension, Handle), #[error("Depth reference {0:?} is not a scalar float")] InvalidDepthReference(Handle), - #[error("Sample level is not compatible with the image dimension {0:?}")] - InvalidSampleLevel(crate::ImageDimension), #[error("Sample level (exact) type {0:?} is not a scalar float")] InvalidSampleLevelExactType(Handle), #[error("Sample level (bias) type {0:?} is not a scalar float")] @@ -390,7 +388,7 @@ impl super::Validator { kind: crate::ScalarKind::Float, multi: false, } => false, - crate::ImageClass::Depth => true, + crate::ImageClass::Depth { multi: false } => true, _ => return Err(ExpressionError::InvalidImageClass(class)), }; if comparison != depth_ref.is_some() || (comparison && !image_depth) { @@ -454,16 +452,10 @@ impl super::Validator { } // check level properties - let can_level = match class { - crate::ImageClass::Sampled { multi, .. } => !multi, - crate::ImageClass::Storage { .. } => unreachable!(), - crate::ImageClass::Depth { .. } => true, - }; match level { - // require `can_level` here? crate::SampleLevel::Auto => ShaderStages::FRAGMENT, crate::SampleLevel::Zero => ShaderStages::all(), - crate::SampleLevel::Exact(expr) if can_level => { + crate::SampleLevel::Exact(expr) => { match *resolver.resolve(expr)? { Ti::Scalar { kind: Sk::Float, .. @@ -510,7 +502,6 @@ impl super::Validator { } ShaderStages::all() } - _ => return Err(ExpressionError::InvalidSampleLevel(dim)), } } E::ImageLoad { @@ -585,14 +576,15 @@ impl super::Validator { Ti::Image { class, arrayed, .. } => { let can_level = match class { crate::ImageClass::Sampled { multi, .. } => !multi, + crate::ImageClass::Depth { multi } => !multi, crate::ImageClass::Storage { .. } => false, - crate::ImageClass::Depth { .. } => true, }; let good = match query { crate::ImageQuery::NumLayers => arrayed, crate::ImageQuery::Size { level: None } => true, crate::ImageQuery::Size { level: Some(_) } | crate::ImageQuery::NumLevels => can_level, + //TODO: forbid on storage images crate::ImageQuery::NumSamples => !can_level, }; if !good { diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 5f1da997b..603c6d299 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -2,6 +2,8 @@ var image_mipmapped_src: texture_2d; [[group(0), binding(3)]] var image_multisampled_src: texture_multisampled_2d; +[[group(0), binding(4)]] +var image_depth_multisampled_src: texture_depth_multisampled_2d; [[group(0), binding(1)]] var image_storage_src: [[access(read)]] texture_storage_2d; [[group(0), binding(2)]] @@ -17,8 +19,9 @@ fn main( let itc = dim * vec2(local_id.xy) % vec2(10, 20); let value1 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); let value2 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); - let value3 = textureLoad(image_storage_src, itc); - textureStore(image_dst, itc.x, value1 + value2 + value3); + let value3 = textureLoad(image_depth_multisampled_src, itc, i32(local_id.z)); + let value4 = textureLoad(image_storage_src, itc); + textureStore(image_dst, itc.x, value1 + value2 + u32(value3) + value4); } [[group(0), binding(0)]] diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index da94245fe..fb4bd604b 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -1,5 +1,6 @@ Texture2D image_mipmapped_src : register(t0); Texture2DMS image_multisampled_src : register(t3); +Texture2DMS image_depth_multisampled_src : register(t4); Texture2D image_storage_src : register(t1); RWTexture1D image_dst : register(u2); Texture1D image_1d : register(t0); @@ -11,7 +12,7 @@ Texture3D image_3d : register(t5); Texture2DMS image_aa : register(t6); SamplerState sampler_reg : register(s0); SamplerComparisonState sampler_cmp : register(s1); -Texture2D image_2d_depth : register(t2); +Texture2D image_2d_depth : register(t2); struct ComputeInput_main { uint3 local_id1 : SV_GroupThreadID; @@ -31,8 +32,9 @@ void main(ComputeInput_main computeinput_main) int2 itc = ((dim * int2(computeinput_main.local_id1.xy)) % int2(10, 20)); uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(computeinput_main.local_id1.z))); uint4 value2_ = image_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)); - uint4 value3_ = image_storage_src.Load(int3(itc, 0)); - image_dst[itc.x] = ((value1_ + value2_) + value3_); + float value3_ = image_depth_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)).x; + uint4 value4_ = image_storage_src.Load(int3(itc, 0)); + image_dst[itc.x] = (((value1_ + value2_) + uint4(uint(value3_).xxxx)) + value4_); return; } diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index ebb693ad2..8f08d925e 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -18,7 +18,7 @@ struct Lights { cbuffer u_globals : register(b0) { Globals u_globals; } Lights s_lights : register(t1); -Texture2DArray t_shadow : register(t2); +Texture2DArray t_shadow : register(t2); SamplerComparisonState sampler_shadow : register(s3); struct FragmentInput_fs_main { diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 9ea27083a..c4e09a6f2 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -436,7 +436,9 @@ inner: Image( dim: D2, arrayed: true, - class: Depth, + class: Depth( + multi: false, + ), ), ), ( diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index a480db346..64014c8ec 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -2,7 +2,7 @@ #include #include -constant metal::int2 const_type5_ = {3, 1}; +constant metal::int2 const_type6_ = {3, 1}; struct main1Input { }; @@ -10,6 +10,7 @@ kernel void main1( metal::uint3 local_id [[thread_position_in_threadgroup]] , metal::texture2d image_mipmapped_src [[user(fake0)]] , metal::texture2d_ms image_multisampled_src [[user(fake0)]] +, metal::depth2d_ms image_depth_multisampled_src [[user(fake0)]] , metal::texture2d image_storage_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { @@ -17,8 +18,9 @@ kernel void main1( metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); - metal::uint4 value3_ = image_storage_src.read(metal::uint2(itc)); - image_dst.write((value1_ + value2_) + value3_, metal::uint(itc.x)); + float value3_ = image_depth_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); + metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); + image_dst.write(((value1_ + value2_) + metal::uint4(static_cast(value3_))) + value4_, metal::uint(itc.x)); return; } @@ -68,9 +70,9 @@ fragment sampleOutput sample( ) { metal::float2 tc = metal::float2(0.5); metal::float4 s2d = image_2d.sample(sampler_reg, tc); - metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type5_); + metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type6_); metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.3)); - metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type5_); + metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type6_); return sampleOutput { ((s2d + s2d_offset) + s2d_level) + s2d_level_offset }; } diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 6b788edd7..b853a7ddf 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,73 +1,76 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 190 +; Bound: 201 OpCapability Image1D OpCapability Shader OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %61 "main" %58 -OpEntryPoint Vertex %89 "queries" %87 -OpEntryPoint Fragment %157 "sample" %156 -OpEntryPoint Fragment %178 "sample_comparison" %176 -OpExecutionMode %61 LocalSize 16 1 1 -OpExecutionMode %157 OriginUpperLeft -OpExecutionMode %178 OriginUpperLeft +OpEntryPoint GLCompute %64 "main" %61 +OpEntryPoint Vertex %100 "queries" %98 +OpEntryPoint Fragment %168 "sample" %167 +OpEntryPoint Fragment %189 "sample_comparison" %187 +OpExecutionMode %64 LocalSize 16 1 1 +OpExecutionMode %168 OriginUpperLeft +OpExecutionMode %189 OriginUpperLeft OpSource GLSL 450 -OpName %29 "image_mipmapped_src" -OpName %31 "image_multisampled_src" -OpName %33 "image_storage_src" -OpName %35 "image_dst" -OpName %37 "image_1d" -OpName %39 "image_2d" -OpName %41 "image_2d_array" -OpName %43 "image_cube" -OpName %45 "image_cube_array" -OpName %47 "image_3d" -OpName %49 "image_aa" -OpName %51 "sampler_reg" -OpName %53 "sampler_cmp" -OpName %55 "image_2d_depth" -OpName %58 "local_id" -OpName %61 "main" -OpName %89 "queries" -OpName %157 "sample" -OpName %178 "sample_comparison" -OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 0 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 3 -OpDecorate %33 NonWritable -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 1 -OpDecorate %35 NonReadable -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 2 -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 0 -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 1 -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 2 -OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 3 -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 4 -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 5 -OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 6 -OpDecorate %51 DescriptorSet 1 -OpDecorate %51 Binding 0 -OpDecorate %53 DescriptorSet 1 -OpDecorate %53 Binding 1 -OpDecorate %55 DescriptorSet 1 -OpDecorate %55 Binding 2 -OpDecorate %58 BuiltIn LocalInvocationId -OpDecorate %87 BuiltIn Position -OpDecorate %156 Location 0 -OpDecorate %176 Location 0 +OpName %30 "image_mipmapped_src" +OpName %32 "image_multisampled_src" +OpName %34 "image_depth_multisampled_src" +OpName %36 "image_storage_src" +OpName %38 "image_dst" +OpName %40 "image_1d" +OpName %42 "image_2d" +OpName %44 "image_2d_array" +OpName %46 "image_cube" +OpName %48 "image_cube_array" +OpName %50 "image_3d" +OpName %52 "image_aa" +OpName %54 "sampler_reg" +OpName %56 "sampler_cmp" +OpName %58 "image_2d_depth" +OpName %61 "local_id" +OpName %64 "main" +OpName %100 "queries" +OpName %168 "sample" +OpName %189 "sample_comparison" +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 0 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 3 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 4 +OpDecorate %36 NonWritable +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 1 +OpDecorate %38 NonReadable +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 2 +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 0 +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 1 +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 2 +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 3 +OpDecorate %48 DescriptorSet 0 +OpDecorate %48 Binding 4 +OpDecorate %50 DescriptorSet 0 +OpDecorate %50 Binding 5 +OpDecorate %52 DescriptorSet 0 +OpDecorate %52 Binding 6 +OpDecorate %54 DescriptorSet 1 +OpDecorate %54 Binding 0 +OpDecorate %56 DescriptorSet 1 +OpDecorate %56 Binding 1 +OpDecorate %58 DescriptorSet 1 +OpDecorate %58 Binding 2 +OpDecorate %61 BuiltIn LocalInvocationId +OpDecorate %98 BuiltIn Position +OpDecorate %167 Location 0 +OpDecorate %187 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -80,195 +83,206 @@ OpDecorate %176 Location 0 %12 = OpTypeInt 32 0 %11 = OpTypeImage %12 2D 0 0 0 1 Unknown %13 = OpTypeImage %12 2D 0 0 1 1 Unknown -%14 = OpTypeImage %12 2D 0 0 0 2 Rgba8ui -%15 = OpTypeImage %12 1D 0 0 0 2 R32ui -%16 = OpTypeVector %12 3 -%17 = OpTypeVector %4 2 -%18 = OpTypeImage %8 1D 0 0 0 1 Unknown -%19 = OpTypeImage %8 2D 0 0 0 1 Unknown -%20 = OpTypeImage %8 2D 0 1 0 1 Unknown -%21 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%22 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%23 = OpTypeImage %8 3D 0 0 0 1 Unknown -%24 = OpTypeImage %8 2D 0 0 1 1 Unknown -%25 = OpTypeVector %8 4 -%26 = OpTypeSampler -%27 = OpTypeImage %8 2D 1 0 0 1 Unknown -%28 = OpConstantComposite %17 %10 %6 -%30 = OpTypePointer UniformConstant %11 -%29 = OpVariable %30 UniformConstant -%32 = OpTypePointer UniformConstant %13 -%31 = OpVariable %32 UniformConstant -%34 = OpTypePointer UniformConstant %14 -%33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %15 -%35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %18 -%37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %19 -%39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %20 -%41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %21 -%43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %22 -%45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %23 -%47 = OpVariable %48 UniformConstant -%50 = OpTypePointer UniformConstant %24 -%49 = OpVariable %50 UniformConstant -%52 = OpTypePointer UniformConstant %26 -%51 = OpVariable %52 UniformConstant -%54 = OpTypePointer UniformConstant %26 -%53 = OpVariable %54 UniformConstant -%56 = OpTypePointer UniformConstant %27 -%55 = OpVariable %56 UniformConstant -%59 = OpTypePointer Input %16 -%58 = OpVariable %59 Input -%62 = OpTypeFunction %2 -%69 = OpTypeVector %12 2 -%77 = OpTypeVector %12 4 -%88 = OpTypePointer Output %25 -%87 = OpVariable %88 Output -%98 = OpConstant %12 0 -%103 = OpTypeVector %4 3 -%156 = OpVariable %88 Output -%161 = OpTypeVector %8 2 -%163 = OpTypeSampledImage %19 -%177 = OpTypePointer Output %8 -%176 = OpVariable %177 Output -%183 = OpTypeSampledImage %27 -%188 = OpConstant %8 0.0 -%61 = OpFunction %2 None %62 -%57 = OpLabel -%60 = OpLoad %16 %58 -%63 = OpLoad %11 %29 -%64 = OpLoad %13 %31 -%65 = OpLoad %14 %33 -%66 = OpLoad %15 %35 -OpBranch %67 -%67 = OpLabel -%68 = OpImageQuerySize %17 %65 -%70 = OpVectorShuffle %69 %60 %60 0 1 -%71 = OpBitcast %17 %70 -%72 = OpIMul %17 %68 %71 -%73 = OpCompositeConstruct %17 %3 %5 -%74 = OpSMod %17 %72 %73 -%75 = OpCompositeExtract %12 %60 2 -%76 = OpBitcast %4 %75 -%78 = OpImageFetch %77 %63 %74 Lod %76 -%79 = OpCompositeExtract %12 %60 2 +%14 = OpTypeImage %8 2D 1 0 1 1 Unknown +%15 = OpTypeImage %12 2D 0 0 0 2 Rgba8ui +%16 = OpTypeImage %12 1D 0 0 0 2 R32ui +%17 = OpTypeVector %12 3 +%18 = OpTypeVector %4 2 +%19 = OpTypeImage %8 1D 0 0 0 1 Unknown +%20 = OpTypeImage %8 2D 0 0 0 1 Unknown +%21 = OpTypeImage %8 2D 0 1 0 1 Unknown +%22 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%23 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%24 = OpTypeImage %8 3D 0 0 0 1 Unknown +%25 = OpTypeImage %8 2D 0 0 1 1 Unknown +%26 = OpTypeVector %8 4 +%27 = OpTypeSampler +%28 = OpTypeImage %8 2D 1 0 0 1 Unknown +%29 = OpConstantComposite %18 %10 %6 +%31 = OpTypePointer UniformConstant %11 +%30 = OpVariable %31 UniformConstant +%33 = OpTypePointer UniformConstant %13 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer UniformConstant %14 +%34 = OpVariable %35 UniformConstant +%37 = OpTypePointer UniformConstant %15 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %16 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %19 +%40 = OpVariable %41 UniformConstant +%43 = OpTypePointer UniformConstant %20 +%42 = OpVariable %43 UniformConstant +%45 = OpTypePointer UniformConstant %21 +%44 = OpVariable %45 UniformConstant +%47 = OpTypePointer UniformConstant %22 +%46 = OpVariable %47 UniformConstant +%49 = OpTypePointer UniformConstant %23 +%48 = OpVariable %49 UniformConstant +%51 = OpTypePointer UniformConstant %24 +%50 = OpVariable %51 UniformConstant +%53 = OpTypePointer UniformConstant %25 +%52 = OpVariable %53 UniformConstant +%55 = OpTypePointer UniformConstant %27 +%54 = OpVariable %55 UniformConstant +%57 = OpTypePointer UniformConstant %27 +%56 = OpVariable %57 UniformConstant +%59 = OpTypePointer UniformConstant %28 +%58 = OpVariable %59 UniformConstant +%62 = OpTypePointer Input %17 +%61 = OpVariable %62 Input +%65 = OpTypeFunction %2 +%73 = OpTypeVector %12 2 +%81 = OpTypeVector %12 4 +%99 = OpTypePointer Output %26 +%98 = OpVariable %99 Output +%109 = OpConstant %12 0 +%114 = OpTypeVector %4 3 +%167 = OpVariable %99 Output +%172 = OpTypeVector %8 2 +%174 = OpTypeSampledImage %20 +%188 = OpTypePointer Output %8 +%187 = OpVariable %188 Output +%194 = OpTypeSampledImage %28 +%199 = OpConstant %8 0.0 +%64 = OpFunction %2 None %65 +%60 = OpLabel +%63 = OpLoad %17 %61 +%66 = OpLoad %11 %30 +%67 = OpLoad %13 %32 +%68 = OpLoad %14 %34 +%69 = OpLoad %15 %36 +%70 = OpLoad %16 %38 +OpBranch %71 +%71 = OpLabel +%72 = OpImageQuerySize %18 %69 +%74 = OpVectorShuffle %73 %63 %63 0 1 +%75 = OpBitcast %18 %74 +%76 = OpIMul %18 %72 %75 +%77 = OpCompositeConstruct %18 %3 %5 +%78 = OpSMod %18 %76 %77 +%79 = OpCompositeExtract %12 %63 2 %80 = OpBitcast %4 %79 -%81 = OpImageFetch %77 %64 %74 Sample %80 -%82 = OpImageRead %77 %65 %74 -%83 = OpCompositeExtract %4 %74 0 -%84 = OpIAdd %77 %78 %81 -%85 = OpIAdd %77 %84 %82 -OpImageWrite %66 %83 %85 +%82 = OpImageFetch %81 %66 %78 Lod %80 +%83 = OpCompositeExtract %12 %63 2 +%84 = OpBitcast %4 %83 +%85 = OpImageFetch %81 %67 %78 Sample %84 +%86 = OpCompositeExtract %12 %63 2 +%87 = OpBitcast %4 %86 +%88 = OpImageFetch %26 %68 %78 Sample %87 +%89 = OpCompositeExtract %8 %88 0 +%90 = OpImageRead %81 %69 %78 +%91 = OpCompositeExtract %4 %78 0 +%92 = OpIAdd %81 %82 %85 +%93 = OpConvertFToU %12 %89 +%94 = OpCompositeConstruct %81 %93 %93 %93 %93 +%95 = OpIAdd %81 %92 %94 +%96 = OpIAdd %81 %95 %90 +OpImageWrite %70 %91 %96 OpReturn OpFunctionEnd -%89 = OpFunction %2 None %62 -%86 = OpLabel -%90 = OpLoad %18 %37 -%91 = OpLoad %19 %39 -%92 = OpLoad %20 %41 -%93 = OpLoad %21 %43 -%94 = OpLoad %22 %45 -%95 = OpLoad %23 %47 -%96 = OpLoad %24 %49 -OpBranch %97 +%100 = OpFunction %2 None %65 %97 = OpLabel -%99 = OpImageQuerySizeLod %4 %90 %98 -%100 = OpImageQuerySizeLod %17 %91 %98 -%101 = OpImageQueryLevels %4 %91 -%102 = OpImageQuerySizeLod %17 %91 %6 -%104 = OpImageQuerySizeLod %103 %92 %98 -%105 = OpVectorShuffle %17 %104 %104 0 1 -%106 = OpImageQueryLevels %4 %92 -%107 = OpImageQuerySizeLod %103 %92 %6 -%108 = OpVectorShuffle %17 %107 %107 0 1 -%109 = OpImageQuerySizeLod %103 %92 %98 -%110 = OpCompositeExtract %4 %109 2 -%111 = OpImageQuerySizeLod %17 %93 %98 -%112 = OpImageQueryLevels %4 %93 -%113 = OpImageQuerySizeLod %17 %93 %6 -%114 = OpImageQuerySizeLod %103 %94 %98 -%115 = OpVectorShuffle %17 %114 %114 0 0 -%116 = OpImageQueryLevels %4 %94 -%117 = OpImageQuerySizeLod %103 %94 %6 -%118 = OpVectorShuffle %17 %117 %117 0 0 -%119 = OpImageQuerySizeLod %103 %94 %98 -%120 = OpCompositeExtract %4 %119 2 -%121 = OpImageQuerySizeLod %103 %95 %98 -%122 = OpImageQueryLevels %4 %95 -%123 = OpImageQuerySizeLod %103 %95 %6 -%124 = OpImageQuerySamples %4 %96 -%125 = OpCompositeExtract %4 %100 1 -%126 = OpIAdd %4 %99 %125 -%127 = OpCompositeExtract %4 %102 1 -%128 = OpIAdd %4 %126 %127 -%129 = OpCompositeExtract %4 %105 1 -%130 = OpIAdd %4 %128 %129 -%131 = OpCompositeExtract %4 %108 1 -%132 = OpIAdd %4 %130 %131 -%133 = OpIAdd %4 %132 %110 -%134 = OpCompositeExtract %4 %111 1 -%135 = OpIAdd %4 %133 %134 -%136 = OpCompositeExtract %4 %113 1 -%137 = OpIAdd %4 %135 %136 -%138 = OpCompositeExtract %4 %115 1 +%101 = OpLoad %19 %40 +%102 = OpLoad %20 %42 +%103 = OpLoad %21 %44 +%104 = OpLoad %22 %46 +%105 = OpLoad %23 %48 +%106 = OpLoad %24 %50 +%107 = OpLoad %25 %52 +OpBranch %108 +%108 = OpLabel +%110 = OpImageQuerySizeLod %4 %101 %109 +%111 = OpImageQuerySizeLod %18 %102 %109 +%112 = OpImageQueryLevels %4 %102 +%113 = OpImageQuerySizeLod %18 %102 %6 +%115 = OpImageQuerySizeLod %114 %103 %109 +%116 = OpVectorShuffle %18 %115 %115 0 1 +%117 = OpImageQueryLevels %4 %103 +%118 = OpImageQuerySizeLod %114 %103 %6 +%119 = OpVectorShuffle %18 %118 %118 0 1 +%120 = OpImageQuerySizeLod %114 %103 %109 +%121 = OpCompositeExtract %4 %120 2 +%122 = OpImageQuerySizeLod %18 %104 %109 +%123 = OpImageQueryLevels %4 %104 +%124 = OpImageQuerySizeLod %18 %104 %6 +%125 = OpImageQuerySizeLod %114 %105 %109 +%126 = OpVectorShuffle %18 %125 %125 0 0 +%127 = OpImageQueryLevels %4 %105 +%128 = OpImageQuerySizeLod %114 %105 %6 +%129 = OpVectorShuffle %18 %128 %128 0 0 +%130 = OpImageQuerySizeLod %114 %105 %109 +%131 = OpCompositeExtract %4 %130 2 +%132 = OpImageQuerySizeLod %114 %106 %109 +%133 = OpImageQueryLevels %4 %106 +%134 = OpImageQuerySizeLod %114 %106 %6 +%135 = OpImageQuerySamples %4 %107 +%136 = OpCompositeExtract %4 %111 1 +%137 = OpIAdd %4 %110 %136 +%138 = OpCompositeExtract %4 %113 1 %139 = OpIAdd %4 %137 %138 -%140 = OpCompositeExtract %4 %118 1 +%140 = OpCompositeExtract %4 %116 1 %141 = OpIAdd %4 %139 %140 -%142 = OpIAdd %4 %141 %120 -%143 = OpCompositeExtract %4 %121 2 -%144 = OpIAdd %4 %142 %143 -%145 = OpCompositeExtract %4 %123 2 +%142 = OpCompositeExtract %4 %119 1 +%143 = OpIAdd %4 %141 %142 +%144 = OpIAdd %4 %143 %121 +%145 = OpCompositeExtract %4 %122 1 %146 = OpIAdd %4 %144 %145 -%147 = OpIAdd %4 %146 %124 -%148 = OpIAdd %4 %147 %101 -%149 = OpIAdd %4 %148 %106 -%150 = OpIAdd %4 %149 %122 -%151 = OpIAdd %4 %150 %112 -%152 = OpIAdd %4 %151 %116 -%153 = OpConvertSToF %8 %152 -%154 = OpCompositeConstruct %25 %153 %153 %153 %153 -OpStore %87 %154 +%147 = OpCompositeExtract %4 %124 1 +%148 = OpIAdd %4 %146 %147 +%149 = OpCompositeExtract %4 %126 1 +%150 = OpIAdd %4 %148 %149 +%151 = OpCompositeExtract %4 %129 1 +%152 = OpIAdd %4 %150 %151 +%153 = OpIAdd %4 %152 %131 +%154 = OpCompositeExtract %4 %132 2 +%155 = OpIAdd %4 %153 %154 +%156 = OpCompositeExtract %4 %134 2 +%157 = OpIAdd %4 %155 %156 +%158 = OpIAdd %4 %157 %135 +%159 = OpIAdd %4 %158 %112 +%160 = OpIAdd %4 %159 %117 +%161 = OpIAdd %4 %160 %133 +%162 = OpIAdd %4 %161 %123 +%163 = OpIAdd %4 %162 %127 +%164 = OpConvertSToF %8 %163 +%165 = OpCompositeConstruct %26 %164 %164 %164 %164 +OpStore %98 %165 OpReturn OpFunctionEnd -%157 = OpFunction %2 None %62 -%155 = OpLabel -%158 = OpLoad %19 %39 -%159 = OpLoad %26 %51 -OpBranch %160 -%160 = OpLabel -%162 = OpCompositeConstruct %161 %7 %7 -%164 = OpSampledImage %163 %158 %159 -%165 = OpImageSampleImplicitLod %25 %164 %162 -%166 = OpSampledImage %163 %158 %159 -%167 = OpImageSampleImplicitLod %25 %166 %162 ConstOffset %28 -%168 = OpSampledImage %163 %158 %159 -%169 = OpImageSampleExplicitLod %25 %168 %162 Lod %9 -%170 = OpSampledImage %163 %158 %159 -%171 = OpImageSampleExplicitLod %25 %170 %162 Lod|ConstOffset %9 %28 -%172 = OpFAdd %25 %165 %167 -%173 = OpFAdd %25 %172 %169 -%174 = OpFAdd %25 %173 %171 -OpStore %156 %174 +%168 = OpFunction %2 None %65 +%166 = OpLabel +%169 = OpLoad %20 %42 +%170 = OpLoad %27 %54 +OpBranch %171 +%171 = OpLabel +%173 = OpCompositeConstruct %172 %7 %7 +%175 = OpSampledImage %174 %169 %170 +%176 = OpImageSampleImplicitLod %26 %175 %173 +%177 = OpSampledImage %174 %169 %170 +%178 = OpImageSampleImplicitLod %26 %177 %173 ConstOffset %29 +%179 = OpSampledImage %174 %169 %170 +%180 = OpImageSampleExplicitLod %26 %179 %173 Lod %9 +%181 = OpSampledImage %174 %169 %170 +%182 = OpImageSampleExplicitLod %26 %181 %173 Lod|ConstOffset %9 %29 +%183 = OpFAdd %26 %176 %178 +%184 = OpFAdd %26 %183 %180 +%185 = OpFAdd %26 %184 %182 +OpStore %167 %185 OpReturn OpFunctionEnd -%178 = OpFunction %2 None %62 -%175 = OpLabel -%179 = OpLoad %26 %53 -%180 = OpLoad %27 %55 -OpBranch %181 -%181 = OpLabel -%182 = OpCompositeConstruct %161 %7 %7 -%184 = OpSampledImage %183 %180 %179 -%185 = OpImageSampleDrefImplicitLod %8 %184 %182 %7 -%186 = OpSampledImage %183 %180 %179 -%187 = OpImageSampleDrefExplicitLod %8 %186 %182 %7 Lod %188 -%189 = OpFAdd %8 %185 %187 -OpStore %176 %189 +%189 = OpFunction %2 None %65 +%186 = OpLabel +%190 = OpLoad %27 %56 +%191 = OpLoad %28 %58 +OpBranch %192 +%192 = OpLabel +%193 = OpCompositeConstruct %172 %7 %7 +%195 = OpSampledImage %194 %191 %190 +%196 = OpImageSampleDrefImplicitLod %8 %195 %193 %7 +%197 = OpSampledImage %194 %191 %190 +%198 = OpImageSampleDrefExplicitLod %8 %197 %193 %7 Lod %199 +%200 = OpFAdd %8 %196 %198 +OpStore %187 %200 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 5c9247173..73c6f9bee 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -2,6 +2,8 @@ var image_mipmapped_src: texture_2d; [[group(0), binding(3)]] var image_multisampled_src: texture_multisampled_2d; +[[group(0), binding(4)]] +var image_depth_multisampled_src: texture_depth_multisampled_2d; [[group(0), binding(1)]] var image_storage_src: [[access(read)]] texture_storage_2d; [[group(0), binding(2)]] @@ -33,8 +35,9 @@ fn main([[builtin(local_invocation_id)]] local_id: vec3) { let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); let value1_: vec4 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); let value2_: vec4 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); - let value3_: vec4 = textureLoad(image_storage_src, itc); - textureStore(image_dst, itc.x, ((value1_ + value2_) + value3_)); + let value3_: f32 = textureLoad(image_depth_multisampled_src, itc, i32(local_id.z)); + let value4_: vec4 = textureLoad(image_storage_src, itc); + textureStore(image_dst, itc.x, (((value1_ + value2_) + vec4(u32(value3_))) + value4_)); return; } From c526383cf885caa7dc5f8207e1a7c37b086615af Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 22 Jul 2021 00:41:48 -0400 Subject: [PATCH 1140/2212] hlsl-out: write StructuredBuffer --- src/back/hlsl/writer.rs | 61 +++++++++++++++++++++++++++----------- tests/out/hlsl/shadow.hlsl | 4 +-- 2 files changed, 45 insertions(+), 20 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 897ff47f8..3ce01ef48 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -352,29 +352,51 @@ impl<'a, W: Write> Writer<'a, W> { } // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register - let (storage, register_ty) = match global.class { + let register_ty = match global.class { crate::StorageClass::Function => unreachable!("Function storage class"), - crate::StorageClass::Private => ("static ", ""), - crate::StorageClass::WorkGroup => ("groupshared ", ""), - crate::StorageClass::Uniform => ("cbuffer", "b"), - crate::StorageClass::Storage | crate::StorageClass::Handle => { - if let TypeInner::Sampler { .. } = *inner { - ("", "s") + crate::StorageClass::Private => { + write!(self.out, "static ")?; + self.write_type(module, global.ty)?; + "" + } + crate::StorageClass::WorkGroup => { + write!(self.out, "groupshared ")?; + self.write_type(module, global.ty)?; + "" + } + crate::StorageClass::Uniform => { + // constant buffer declarations are expected to be inlined, e.g. + // `cbuffer foo: register(b0) { field1: type1; }` + write!(self.out, "cbuffer")?; + "b" + } + crate::StorageClass::Storage => { + let (prefix, register) = + if global.storage_access.contains(crate::StorageAccess::STORE) { + ("RW", "u") + } else { + ("", "t") + }; + write!(self.out, "{}StructuredBuffer<", prefix)?; + self.write_type(module, global.ty)?; + write!(self.out, ">")?; + register + } + crate::StorageClass::Handle => { + let register = if let TypeInner::Sampler { .. } = *inner { + "s" } else if global.storage_access.contains(crate::StorageAccess::STORE) { - ("RW", "u") + write!(self.out, "RW")?; + "u" } else { - ("", "t") - } + "t" + }; + self.write_type(module, global.ty)?; + register } crate::StorageClass::PushConstant => unimplemented!("Push constants"), }; - write!(self.out, "{}", storage)?; - // constant buffer declarations are expected to be inlined, e.g. - // cbuffer foo: register(b0) { field1: type1; }; - if global.class != crate::StorageClass::Uniform { - self.write_type(module, global.ty)?; - } let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, " {}", name)?; if let TypeInner::Array { size, .. } = module.types[global.ty].inner { @@ -1291,10 +1313,13 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ".x")?; } } - // TODO: copy-paste from wgsl-out Expression::GlobalVariable(handle) => { let name = &self.names[&NameKey::GlobalVariable(handle)]; - write!(self.out, "{}", name)?; + let postfix = match module.global_variables[handle].class { + crate::StorageClass::Storage => "[0]", + _ => "", + }; + write!(self.out, "{}{}", name, postfix)?; } Expression::LocalVariable(handle) => { write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])? diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 8f08d925e..44c002b8f 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -17,7 +17,7 @@ struct Lights { }; cbuffer u_globals : register(b0) { Globals u_globals; } -Lights s_lights : register(t1); +StructuredBuffer s_lights : register(t1); Texture2DArray t_shadow : register(t2); SamplerComparisonState sampler_shadow : register(s3); @@ -50,7 +50,7 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 break; } uint _expr19 = i; - Light light = s_lights.data[_expr19]; + Light light = s_lights[0].data[_expr19]; uint _expr22 = i; const float _e25 = fetch_shadow(_expr22, mul(light.proj, fragmentinput_fs_main.position1)); float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz)); From cc91c77f7ac7e22b615bf2e188f659ce623c1fe9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 23 Jul 2021 02:07:42 -0400 Subject: [PATCH 1141/2212] hlsl: fix vector multiplication --- src/back/hlsl/writer.rs | 31 ++++++++++++++++++++++++------- tests/out/hlsl/quad.hlsl | 4 ++-- tests/out/hlsl/shadow.hlsl | 2 +- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 3ce01ef48..9aa878c26 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -14,6 +14,15 @@ const LOCATION_SEMANTIC: &str = "LOC"; /// Shorthand result used internally by the backend pub(super) type BackendResult = Result<(), Error>; +impl TypeInner { + fn is_matrix(&self) -> bool { + match *self { + Self::Matrix { .. } => true, + _ => false, + } + } +} + /// Structure contains information required for generating /// wrapped structure of all entry points arguments struct EntryPointBinding { @@ -100,7 +109,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write all structs for (handle, ty) in module.types.iter() { - if let crate::TypeInner::Struct { + if let TypeInner::Struct { top_level, ref members, .. @@ -500,7 +509,11 @@ impl<'a, W: Write> Writer<'a, W> { _ => unreachable!(), } } - crate::ArraySize::Dynamic => write!(self.out, "1")?, + crate::ArraySize::Dynamic => { + //TODO: https://github.com/gfx-rs/naga/issues/1127 + log::warn!("Dynamically sized arrays are not properly supported yet"); + write!(self.out, "1")? + } } write!(self.out, "]")?; @@ -1088,13 +1101,17 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } } - // Matrix * Vector has to be written as `mul(Matrix, Vector)` + // All of the multiplication can be expressed as `mul`, + // except vector * vector, which needs to use the "*" operator. Expression::Binary { op: crate::BinaryOperator::Multiply, left, right, - } if func_ctx.info[left].ty.inner_with(&module.types) - != func_ctx.info[right].ty.inner_with(&module.types) => + } if func_ctx.info[left].ty.inner_with(&module.types).is_matrix() + || func_ctx.info[right] + .ty + .inner_with(&module.types) + .is_matrix() => { write!(self.out, "mul(")?; self.write_expr(module, left, func_ctx)?; @@ -1267,11 +1284,11 @@ impl<'a, W: Write> Writer<'a, W> { } => { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-load let ms = match *func_ctx.info[image].ty.inner_with(&module.types) { - crate::TypeInner::Image { + TypeInner::Image { class: crate::ImageClass::Sampled { multi, .. }, .. } - | crate::TypeInner::Image { + | TypeInner::Image { class: crate::ImageClass::Depth { multi }, .. } => multi, diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index f69f51ad5..90cd39274 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -19,7 +19,7 @@ struct FragmentInput_main { VertexOutput main(VertexInput_main vertexinput_main) { - const VertexOutput vertexoutput1 = { vertexinput_main.uv2, float4(mul(c_scale, vertexinput_main.pos1), 0.0, 1.0) }; + const VertexOutput vertexoutput1 = { vertexinput_main.uv2, float4((c_scale * vertexinput_main.pos1), 0.0, 1.0) }; return vertexoutput1; } @@ -29,7 +29,7 @@ float4 main1(FragmentInput_main fragmentinput_main) : SV_Target0 if ((color.w == 0.0)) { discard; } - float4 premultiplied = mul(color.w, color); + float4 premultiplied = (color.w * color); return premultiplied; } diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 44c002b8f..5cd2adc20 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -56,7 +56,7 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); float3 _expr34 = color; - color = (_expr34 + mul((_e25 * diffuse), light.color.xyz)); + color = (_expr34 + ((_e25 * diffuse) * light.color.xyz)); uint _expr40 = i; i = (_expr40 + 1u); } From bbfa9a0f9e0599fe09ad9428bf359e6dea2664c6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 23 Jul 2021 10:35:50 -0400 Subject: [PATCH 1142/2212] hlsl: remove the boolean casts for unary operators --- src/back/hlsl/writer.rs | 27 ++++----------------------- tests/out/hlsl/control-flow.hlsl | 1 + tests/out/hlsl/empty.hlsl | 1 + tests/out/hlsl/image.hlsl | 1 + tests/out/hlsl/interface.hlsl | 1 + tests/out/hlsl/interpolate.hlsl | 1 + tests/out/hlsl/operators.hlsl | 5 +++-- tests/out/hlsl/quad-vert.hlsl | 1 + tests/out/hlsl/shadow.hlsl | 1 - tests/out/hlsl/skybox.hlsl | 1 + tests/out/hlsl/standard.hlsl | 1 + 11 files changed, 15 insertions(+), 26 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 9aa878c26..d85299518 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -100,6 +100,9 @@ impl<'a, W: Write> Writer<'a, W> { } } + // Extra newline for readability + writeln!(self.out)?; + // Save all entry point output types let ep_results = module .entry_points @@ -487,8 +490,6 @@ impl<'a, W: Write> Writer<'a, W> { } } writeln!(self.out, ";")?; - // End with extra newline for readability - writeln!(self.out)?; Ok(()) } @@ -1352,32 +1353,12 @@ impl<'a, W: Write> Writer<'a, W> { } Expression::Unary { op, expr } => { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators - let convert_to_bool = if let TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - .. - } = *func_ctx.info[expr].ty.inner_with(&module.types) - { - false - } else { - true - }; let op_str = match op { crate::UnaryOperator::Negate => "-", crate::UnaryOperator::Not => "!", }; - write!(self.out, "({}", op_str)?; - - if convert_to_bool { - write!(self.out, "bool(")?; - } - + write!(self.out, "{}", op_str)?; self.write_expr(module, expr, func_ctx)?; - - if convert_to_bool { - write!(self.out, ")")?; - } - - write!(self.out, ")")? } Expression::As { expr, kind, .. } => { let inner = func_ctx.info[expr].ty.inner_with(&module.types); diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index 1661ebab9..2d6810aab 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -1,3 +1,4 @@ + struct ComputeInput_main { uint3 global_id1 : SV_DispatchThreadID; }; diff --git a/tests/out/hlsl/empty.hlsl b/tests/out/hlsl/empty.hlsl index e79d36b9c..2b5243867 100644 --- a/tests/out/hlsl/empty.hlsl +++ b/tests/out/hlsl/empty.hlsl @@ -1,3 +1,4 @@ + [numthreads(1, 1, 1)] void main() { diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index fb4bd604b..c85118b76 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -1,3 +1,4 @@ + Texture2D image_mipmapped_src : register(t0); Texture2DMS image_multisampled_src : register(t3); Texture2DMS image_depth_multisampled_src : register(t4); diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index fc118eea2..1d6fc884b 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -1,3 +1,4 @@ + struct VertexOutput { float4 position : SV_Position; linear float varying : LOC1; diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index 2169938c4..555727e2c 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -1,3 +1,4 @@ + struct FragmentInput { float4 position : SV_Position; nointerpolation uint flat : LOC0; diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 10621ce05..8bd764da7 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -1,3 +1,4 @@ + float4 splat() { float2 a = (((float2(1.0.xx) + float2(2.0.xx)) - float2(3.0.xx)) / float2(4.0.xx)); @@ -7,10 +8,10 @@ float4 splat() int unary() { - if ((!true)) { + if (!true) { return 1; } else { - return (!bool(1)); + return !1; } } diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 59957193f..c0f0f1fbf 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -1,3 +1,4 @@ + struct gl_PerVertex { float4 gl_Position : SV_Position; float gl_PointSize : PSIZE; diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 5cd2adc20..bec95958c 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -1,5 +1,4 @@ static const float3 c_ambient = float3(0.05, 0.05, 0.05); - static const uint c_max_lights = 10; struct Globals { diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 3add16fa9..8eba4c4ec 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -1,3 +1,4 @@ + struct VertexOutput { float4 position : SV_Position; linear float3 uv : LOC0; diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl index b6a639f26..7f0bed219 100644 --- a/tests/out/hlsl/standard.hlsl +++ b/tests/out/hlsl/standard.hlsl @@ -1,3 +1,4 @@ + struct FragmentInput_derivatives { float4 foo1 : SV_Position; }; From ff14f04734d4ecb99567577da74613bd9f61b965 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 23 Jul 2021 14:45:45 +0000 Subject: [PATCH 1143/2212] [glsl-out] Fix bitcast operation for the same types --- src/back/glsl/mod.rs | 58 ++++++++++++++++++++++++++------------------ 1 file changed, 35 insertions(+), 23 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 30105917e..5779fdcc6 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2252,36 +2252,48 @@ impl<'a, W: Write> Writer<'a, W> { } _ => write!(self.out, "{}", scalar.full)?, } + + write!(self.out, "(")?; + self.write_expr(expr, ctx)?; + write!(self.out, ")")? } None => { use crate::ScalarKind as Sk; let source_kind = inner.scalar_kind().unwrap(); - write!( - self.out, - "{}", - match (source_kind, target_kind) { - (Sk::Float, Sk::Sint) => "floatBitsToInt", - (Sk::Float, Sk::Uint) => "floatBitsToUInt", - (Sk::Sint, Sk::Float) => "intBitsToFloat", - (Sk::Uint, Sk::Float) => "uintBitsToFloat", - // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion - (Sk::Uint, Sk::Sint) => "int", - (Sk::Sint, Sk::Uint) => "uint", - _ => { - return Err(Error::Custom(format!( - "Cannot bitcast {:?} to {:?}", - source_kind, target_kind - ))); - } - } - )?; + let conv_op = match (source_kind, target_kind) { + (Sk::Float, Sk::Sint) => "floatBitsToInt", + (Sk::Float, Sk::Uint) => "floatBitsToUInt", + (Sk::Sint, Sk::Float) => "intBitsToFloat", + (Sk::Uint, Sk::Float) => "uintBitsToFloat", + // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion + (Sk::Uint, Sk::Sint) => "int", + (Sk::Sint, Sk::Uint) => "uint", + + (Sk::Bool, Sk::Sint) => "int", + (Sk::Bool, Sk::Uint) => "uint", + (Sk::Bool, Sk::Float) => "float", + + (Sk::Sint, Sk::Bool) => "bool", + (Sk::Uint, Sk::Bool) => "bool", + (Sk::Float, Sk::Bool) => "bool", + + // No conversion needed + (Sk::Sint, Sk::Sint) => "", + (Sk::Uint, Sk::Uint) => "", + (Sk::Float, Sk::Float) => "", + (Sk::Bool, Sk::Bool) => "", + }; + write!(self.out, "{}", conv_op)?; + if !conv_op.is_empty() { + write!(self.out, "(")?; + } + self.write_expr(expr, ctx)?; + if !conv_op.is_empty() { + write!(self.out, ")")? + } } } - - write!(self.out, "(")?; - self.write_expr(expr, ctx)?; - write!(self.out, ")")? } Expression::Call(_function) => unreachable!(), // `ArrayLength` is written as `expr.length()` and we convert it to a uint From 3000232844a1a2b42b75d922efbe181a0145c342 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Fri, 23 Jul 2021 20:11:43 +0300 Subject: [PATCH 1144/2212] [hlsl-out] Write sint array size --- src/back/hlsl/writer.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index d85299518..a5d97e881 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -507,6 +507,10 @@ impl<'a, W: Write> Writer<'a, W> { width: _, value: crate::ScalarValue::Uint(size), } => write!(self.out, "{}", size)?, + crate::ConstantInner::Scalar { + width: _, + value: crate::ScalarValue::Sint(size), + } => write!(self.out, "{}", size)?, _ => unreachable!(), } } From 7bb28201dd2cf07b2202b8a36bf38afd4c5d9911 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Fri, 23 Jul 2021 20:12:29 +0300 Subject: [PATCH 1145/2212] Allow to translate from bool to another type in validator --- src/valid/expression.rs | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 01f30e2cd..d9937b894 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1142,20 +1142,7 @@ impl super::Validator { } ShaderStages::all() } - E::As { - expr, - kind, - convert, - } => { - let prev_kind = resolver - .resolve(expr)? - .scalar_kind() - .ok_or(ExpressionError::InvalidCastArgument)?; - - if prev_kind == Sk::Bool || kind == Sk::Bool { - return Err(ExpressionError::InvalidCastArgument); - } - + E::As { kind, convert, .. } => { match convert { Some(width) if !self.check_width(kind, width) => { return Err(ExpressionError::InvalidCastArgument) From 7dd9e14a3ddf0f76ae378d05b5680fc86832f45a Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Fri, 23 Jul 2021 20:18:16 +0300 Subject: [PATCH 1146/2212] Add note about sint array size in comment --- src/back/glsl/mod.rs | 2 +- src/back/hlsl/writer.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5779fdcc6..8b0364484 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -613,7 +613,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the array size // Writes nothing if `ArraySize::Dynamic` - // Panics if `ArraySize::Constant` has a constant that isn't an uint + // Panics if `ArraySize::Constant` has a constant that isn't an sint or uint match size { crate::ArraySize::Constant(const_handle) => { match self.module.constants[const_handle].inner { diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index a5d97e881..09db95b48 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -499,7 +499,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the array size // Writes nothing if `ArraySize::Dynamic` - // Panics if `ArraySize::Constant` has a constant that isn't an uint + // Panics if `ArraySize::Constant` has a constant that isn't an sint or uint match size { crate::ArraySize::Constant(const_handle) => { match module.constants[const_handle].inner { From 9bd0abb9873d51e759df6fa7d16899b5b375b586 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Fri, 23 Jul 2021 20:47:27 +0300 Subject: [PATCH 1147/2212] [hlsl-out] Fix local variable writing with array type --- src/back/hlsl/writer.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 09db95b48..78b87a342 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -799,6 +799,10 @@ impl<'a, W: Write> Writer<'a, W> { // The leading space is important self.write_type(module, local.ty)?; write!(self.out, " {}", self.names[&func_ctx.name_key(handle)])?; + // Write size for array type + if let TypeInner::Array { size, .. } = module.types[local.ty].inner { + self.write_array_size(module, size)?; + } write!(self.out, " = ")?; // Write the local initializer if needed @@ -1081,12 +1085,11 @@ impl<'a, W: Write> Writer<'a, W> { match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::Compose { ty, ref components } => { - let is_struct = if let TypeInner::Struct { .. } = module.types[ty].inner { - true - } else { - false + let braces_init = match module.types[ty].inner { + TypeInner::Struct { .. } | TypeInner::Array { .. } => true, + _ => false, }; - if is_struct { + if braces_init { write!(self.out, "{{ ")?; } else { self.write_type(module, ty)?; @@ -1100,7 +1103,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ", ")?; } } - if is_struct { + if braces_init { write!(self.out, " }}")? } else { write!(self.out, ")")? From 526a29e2b84801cef9d068f9d1d4648336916ea0 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Fri, 23 Jul 2021 21:50:13 +0300 Subject: [PATCH 1148/2212] [glsl-out] Fix array type writing and zero initialization for local variables --- src/back/glsl/mod.rs | 67 +++++++++++++---------- tests/out/glsl/boids.main.Compute.glsl | 14 ++--- tests/out/glsl/quad-vert.main.Vertex.glsl | 4 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 4 +- 4 files changed, 49 insertions(+), 40 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 8b0364484..f109a4800 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -825,16 +825,13 @@ impl<'a, W: Write> Writer<'a, W> { self.write_array_size(size)?; } - match self.module.types[global.ty].inner { - TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => { - write!(self.out, " = ")?; - if let Some(init) = global.init { - self.write_constant(&self.module.constants[init])?; - } else { - self.write_zero_init_value(&self.module.types[global.ty].inner)?; - } + if is_value_init_supported(&self.module, global.ty) { + write!(self.out, " = ")?; + if let Some(init) = global.init { + self.write_constant(init)?; + } else { + self.write_zero_init_value(global.ty)?; } - _ => {} } writeln!(self.out, ";")?; @@ -1096,7 +1093,10 @@ impl<'a, W: Write> Writer<'a, W> { // Write the local name // The leading space is important write!(self.out, " {}", self.names[&ctx.name_key(handle)])?; - + // Write size for array type + if let TypeInner::Array { size, .. } = self.module.types[local.ty].inner { + self.write_array_size(size)?; + } // Write the local initializer if needed if let Some(init) = local.init { // Put the equal signal only if there's a initializer @@ -1105,7 +1105,10 @@ impl<'a, W: Write> Writer<'a, W> { // Write the constant // `write_constant` adds no trailing or leading space/newline - self.write_constant(&self.module.constants[init])?; + self.write_constant(init)?; + } else if is_value_init_supported(&self.module, local.ty) { + write!(self.out, " = ")?; + self.write_zero_init_value(local.ty)?; } // Finish the local with `;` and add a newline (only for readability) @@ -1158,10 +1161,10 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Adds no newlines or leading/trailing whitespace - fn write_constant(&mut self, constant: &crate::Constant) -> BackendResult { + fn write_constant(&mut self, handle: Handle) -> BackendResult { use crate::ScalarValue as Sv; - match constant.inner { + match self.module.constants[handle].inner { crate::ConstantInner::Scalar { width: _, ref value, @@ -1186,9 +1189,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "(")?; // Write the comma separated constants - self.write_slice(components, |this, _, arg| { - this.write_constant(&this.module.constants[*arg]) - })?; + self.write_slice(components, |this, _, arg| this.write_constant(*arg))?; write!(self.out, ")")? } @@ -1744,9 +1745,7 @@ impl<'a, W: Write> Writer<'a, W> { } } // Constants are delegated to `write_constant` - Expression::Constant(constant) => { - self.write_constant(&self.module.constants[constant])? - } + Expression::Constant(constant) => self.write_constant(constant)?, // `Splat` needs to actually write down a vector, it's not always inferred in GLSL. Expression::Splat { size: _, value } => { let resolved = ctx.info[expr].ty.inner_with(&self.module.types); @@ -1772,6 +1771,11 @@ impl<'a, W: Write> Writer<'a, W> { Expression::Compose { ty, ref components } => { self.write_type(ty)?; + let resolved = ctx.info[expr].ty.inner_with(&self.module.types); + if let TypeInner::Array { size, .. } = *resolved { + self.write_array_size(size)?; + } + write!(self.out, "(")?; self.write_slice(components, |this, _, arg| this.write_expr(*arg, ctx))?; write!(self.out, ")")? @@ -1912,7 +1916,7 @@ impl<'a, W: Write> Writer<'a, W> { if let Some(constant) = offset { write!(self.out, ", ")?; - self.write_constant(&self.module.constants[constant])?; + self.write_constant(constant)?; } // End the function @@ -2361,14 +2365,11 @@ impl<'a, W: Write> Writer<'a, W> { let base_ty_res = &ctx.info[handle].ty; let resolved = base_ty_res.inner_with(&self.module.types); - // If rhs is a array type, we should write temp variable as a dynamic array - let array_str = if let TypeInner::Array { .. } = *resolved { - "[]" - } else { - "" - }; - - write!(self.out, " {}{} = ", name, array_str)?; + write!(self.out, " {}", name)?; + if let TypeInner::Array { size, .. } = *resolved { + self.write_array_size(size)?; + } + write!(self.out, " = ")?; self.write_expr(handle, ctx)?; writeln!(self.out, ";")?; self.named_expressions.insert(handle, name); @@ -2377,7 +2378,8 @@ impl<'a, W: Write> Writer<'a, W> { } /// Helper function that write string with default zero initialization for supported types - fn write_zero_init_value(&mut self, inner: &TypeInner) -> BackendResult { + fn write_zero_init_value(&mut self, ty: Handle) -> BackendResult { + let inner = &self.module.types[ty].inner; match *inner { TypeInner::Scalar { kind, .. } => { self.write_zero_init_scalar(kind)?; @@ -2671,3 +2673,10 @@ fn glsl_storage_access(storage_access: crate::StorageAccess) -> Option<&'static None } } + +fn is_value_init_supported(module: &crate::Module, ty: Handle) -> bool { + match module.types[ty].inner { + TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => true, + _ => false, + } +} diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 4c4cec0a3..add4e0f9d 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -31,15 +31,15 @@ buffer Particles_block_2Cs { void main() { uvec3 global_invocation_id = gl_GlobalInvocationID; - vec2 vPos; - vec2 vVel; - vec2 cMass; - vec2 cVel; - vec2 colVel; + vec2 vPos = vec2(0.0, 0.0); + vec2 vVel = vec2(0.0, 0.0); + vec2 cMass = vec2(0.0, 0.0); + vec2 cVel = vec2(0.0, 0.0); + vec2 colVel = vec2(0.0, 0.0); int cMassCount = 0; int cVelCount = 0; - vec2 pos; - vec2 vel; + vec2 pos = vec2(0.0, 0.0); + vec2 vel = vec2(0.0, 0.0); uint i = 0u; uint index = global_invocation_id.x; if ((index >= 1500u)) { diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index 0e746e8f2..60f74cd94 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -45,8 +45,8 @@ void main() { vec2 _expr10 = v_uv; vec4 _expr11 = perVertexStruct.gen_gl_Position; float _expr12 = perVertexStruct.gen_gl_PointSize; - float _expr13[] = perVertexStruct.gen_gl_ClipDistance; - float _expr14[] = perVertexStruct.gen_gl_CullDistance; + float _expr13[1] = perVertexStruct.gen_gl_ClipDistance; + float _expr14[1] = perVertexStruct.gen_gl_CullDistance; type10 _tmp_return = type10(_expr10, _expr11, _expr12, _expr13, _expr14); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index a49f78a93..bae80935e 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -17,8 +17,8 @@ layout(location = 0) smooth out vec3 _vs2fs_location0; void main() { uint vertex_index = uint(gl_VertexID); - int tmp1_; - int tmp2_; + int tmp1_ = 0; + int tmp2_ = 0; tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); int _expr10 = tmp1_; From 4b6846d5da0746c56049c4266db6dd62620397c0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 24 Jul 2021 02:21:54 -0400 Subject: [PATCH 1149/2212] hlsl: storage reads support, array length --- src/back/hlsl/conv.rs | 123 +++++ src/back/hlsl/help.rs | 425 +++++++++++++++++ src/back/hlsl/image.rs | 299 ------------ src/back/hlsl/mod.rs | 3 +- src/back/hlsl/writer.rs | 632 ++++++++++++++++--------- src/back/spv/block.rs | 7 +- src/front/glsl/ast.rs | 14 +- src/front/spv/mod.rs | 21 +- src/proc/mod.rs | 8 + tests/in/access.wgsl | 6 +- tests/out/hlsl/access.hlsl | 34 ++ tests/out/hlsl/access.hlsl.config | 3 + tests/out/hlsl/image.hlsl | 80 ++-- tests/out/hlsl/shadow.hlsl | 8 +- tests/out/hlsl/texture-arg.hlsl | 15 + tests/out/hlsl/texture-arg.hlsl.config | 3 + tests/out/msl/access.msl | 24 +- tests/out/spv/access.spvasm | 174 +++---- tests/out/wgsl/access.wgsl | 9 +- tests/snapshots.rs | 7 +- 20 files changed, 1200 insertions(+), 695 deletions(-) create mode 100644 src/back/hlsl/conv.rs create mode 100644 src/back/hlsl/help.rs delete mode 100644 src/back/hlsl/image.rs create mode 100644 tests/out/hlsl/access.hlsl create mode 100644 tests/out/hlsl/access.hlsl.config create mode 100644 tests/out/hlsl/texture-arg.hlsl create mode 100644 tests/out/hlsl/texture-arg.hlsl.config diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs new file mode 100644 index 000000000..1d56a08d9 --- /dev/null +++ b/src/back/hlsl/conv.rs @@ -0,0 +1,123 @@ +use super::Error; + +impl crate::ScalarKind { + pub(super) fn to_hlsl_cast(self) -> &'static str { + match self { + Self::Float => "asfloat", + Self::Sint => "asint", + Self::Uint => "asuint", + Self::Bool => unreachable!(), + } + } + + /// Helper function that returns scalar related strings + /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-scalar + pub(super) fn to_hlsl_str(self, width: crate::Bytes) -> Result<&'static str, Error> { + match self { + Self::Sint => Ok("int"), + Self::Uint => Ok("uint"), + Self::Float => match width { + 2 => Ok("half"), + 4 => Ok("float"), + 8 => Ok("double"), + _ => Err(Error::UnsupportedScalar(self, width)), + }, + Self::Bool => Ok("bool"), + } + } +} + +impl crate::TypeInner { + pub(super) fn is_matrix(&self) -> bool { + match *self { + Self::Matrix { .. } => true, + _ => false, + } + } +} + +impl crate::StorageFormat { + pub(super) fn to_hlsl_str(self) -> &'static str { + match self { + Self::R16Float => "float", + Self::R8Unorm => "unorm float", + Self::R8Snorm => "snorm float", + Self::R8Uint | Self::R16Uint => "uint", + Self::R8Sint | Self::R16Sint => "int", + + Self::Rg16Float => "float2", + Self::Rg8Unorm => "unorm float2", + Self::Rg8Snorm => "snorm float2", + + Self::Rg8Sint | Self::Rg16Sint => "int2", + Self::Rg8Uint | Self::Rg16Uint => "uint2", + + Self::Rg11b10Float => "float3", + + Self::Rgba16Float | Self::R32Float | Self::Rg32Float | Self::Rgba32Float => "float4", + Self::Rgba8Unorm | Self::Rgb10a2Unorm => "unorm float4", + Self::Rgba8Snorm => "snorm float4", + + Self::Rgba8Uint + | Self::Rgba16Uint + | Self::R32Uint + | Self::Rg32Uint + | Self::Rgba32Uint => "uint4", + Self::Rgba8Sint + | Self::Rgba16Sint + | Self::R32Sint + | Self::Rg32Sint + | Self::Rgba32Sint => "int4", + } + } +} + +impl crate::BuiltIn { + pub(super) fn to_hlsl_str(self) -> Result<&'static str, Error> { + Ok(match self { + Self::Position => "SV_Position", + // vertex + Self::ClipDistance => "SV_ClipDistance", + Self::CullDistance => "SV_CullDistance", + Self::InstanceIndex => "SV_InstanceID", + // based on this page https://docs.microsoft.com/en-us/windows/uwp/gaming/glsl-to-hlsl-reference#comparing-opengl-es-20-with-direct3d-11 + // No meaning unless you target Direct3D 9 + Self::PointSize => "PSIZE", + Self::VertexIndex => "SV_VertexID", + // fragment + Self::FragDepth => "SV_Depth", + Self::FrontFacing => "SV_IsFrontFace", + Self::PrimitiveIndex => "SV_PrimitiveID", + Self::SampleIndex => "SV_SampleIndex", + Self::SampleMask => "SV_Coverage", + // compute + Self::GlobalInvocationId => "SV_DispatchThreadID", + Self::LocalInvocationId => "SV_GroupThreadID", + Self::LocalInvocationIndex => "SV_GroupIndex", + Self::WorkGroupId => "SV_GroupID", + _ => return Err(Error::Unimplemented(format!("builtin {:?}", self))), + }) + } +} + +impl crate::Interpolation { + /// Helper function that returns the string corresponding to the HLSL interpolation qualifier + pub(super) fn to_hlsl_str(self) -> &'static str { + match self { + Self::Perspective => "linear", + Self::Linear => "noperspective", + Self::Flat => "nointerpolation", + } + } +} + +impl crate::Sampling { + /// Return the HLSL auxiliary qualifier for the given sampling value. + pub(super) fn to_hlsl_str(self) -> Option<&'static str> { + match self { + Self::Center => None, + Self::Centroid => Some("centroid"), + Self::Sample => Some("sample"), + } + } +} diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs new file mode 100644 index 000000000..aef71ddb2 --- /dev/null +++ b/src/back/hlsl/help.rs @@ -0,0 +1,425 @@ +// Important note about `Expression::ImageQuery`/`Expression::ArrayLength` and hlsl backend: +// Due to implementation of `GetDimensions` function in hlsl (https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions) +// backend can't work with it as an expression. +// Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texure info and query function. +// See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions. +// This allowed to works with `Expression::ImageQuery` as expression and write wrapped function. +// +// For example: +// ```wgsl +// let dim_1d = textureDimensions(image_1d); +// ``` +// +// ```hlsl +// int NagaDimensions1D(Texture1D) +// { +// uint4 ret; +// image_1d.GetDimensions(ret.x); +// return ret.x; +// } +// +// int dim_1d = NagaDimensions1D(image_1d); +// ``` + +use super::{super::FunctionCtx, writer::BackendResult}; +use crate::arena::Handle; +use std::fmt::Write; + +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) struct WrappedArrayLength { + pub(super) writable: bool, +} + +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) struct WrappedImageQuery { + pub(super) dim: crate::ImageDimension, + pub(super) arrayed: bool, + pub(super) class: crate::ImageClass, + pub(super) query: ImageQuery, +} + +// HLSL backend requires its own `ImageQuery` enum. +// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function. +// IR version can't be unique per function, because it's store mipmap level as an expression. +// +// For example: +// ```wgsl +// let dim_cube_array_lod = textureDimensions(image_cube_array, 1); +// let dim_cube_array_lod2 = textureDimensions(image_cube_array, 1); +// ``` +// +// ```ir +// ImageQuery { +// image: [1], +// query: Size { +// level: Some( +// [1], +// ), +// }, +// }, +// ImageQuery { +// image: [1], +// query: Size { +// level: Some( +// [2], +// ), +// }, +// }, +// ``` +// +// HLSL should generate only 1 function for this case. +// +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) enum ImageQuery { + Size, + SizeLevel, + NumLevels, + NumLayers, + NumSamples, +} + +impl From for ImageQuery { + fn from(q: crate::ImageQuery) -> Self { + use crate::ImageQuery as Iq; + match q { + Iq::Size { level: Some(_) } => ImageQuery::SizeLevel, + Iq::Size { level: None } => ImageQuery::Size, + Iq::NumLevels => ImageQuery::NumLevels, + Iq::NumLayers => ImageQuery::NumLayers, + Iq::NumSamples => ImageQuery::NumSamples, + } + } +} + +#[derive(Clone, Copy, PartialEq)] +pub(super) enum MipLevelCoordinate { + NotApplicable, + Zero, + Expression(Handle), +} + +impl<'a, W: Write> super::Writer<'a, W> { + pub(super) fn write_image_type( + &mut self, + dim: crate::ImageDimension, + arrayed: bool, + class: crate::ImageClass, + ) -> BackendResult { + let dim_str = dim.to_hlsl_str(); + let arrayed_str = if arrayed { "Array" } else { "" }; + write!(self.out, "Texture{}{}", dim_str, arrayed_str)?; + match class { + crate::ImageClass::Depth { multi } => { + let multi_str = if multi { "MS" } else { "" }; + write!(self.out, "{}", multi_str)? + } + crate::ImageClass::Sampled { kind, multi } => { + let multi_str = if multi { "MS" } else { "" }; + let scalar_kind_str = kind.to_hlsl_str(4)?; + write!(self.out, "{}<{}4>", multi_str, scalar_kind_str)? + } + crate::ImageClass::Storage(format) => { + let storage_format_str = format.to_hlsl_str(); + write!(self.out, "<{}>", storage_format_str)? + } + } + Ok(()) + } + + pub(super) fn write_wrapped_array_length_function_name( + &mut self, + query: WrappedArrayLength, + ) -> BackendResult { + let access_str = if query.writable { "RW" } else { "" }; + write!(self.out, "NagaBufferLength{}", access_str,)?; + + Ok(()) + } + + /// Helper function that write wrapped function for `Expression::ArrayLength` + /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-rwbyteaddressbuffer-getdimensions + pub(super) fn write_wrapped_array_length_function( + &mut self, + module: &crate::Module, + wal: WrappedArrayLength, + expr_handle: Handle, + func_ctx: &FunctionCtx, + ) -> BackendResult { + use crate::back::INDENT; + + const ARGUMENT_VARIABLE_NAME: &str = "buffer"; + const RETURN_VARIABLE_NAME: &str = "ret"; + + // Write function return type and name + let ret_ty = func_ctx.info[expr_handle].ty.inner_with(&module.types); + self.write_value_type(module, ret_ty)?; + write!(self.out, " ")?; + self.write_wrapped_array_length_function_name(wal)?; + + // Write function parameters + write!(self.out, "(")?; + let access_str = if wal.writable { "RW" } else { "" }; + writeln!( + self.out, + "{}ByteAddressBuffer {})", + access_str, ARGUMENT_VARIABLE_NAME + )?; + // Write function body + writeln!(self.out, "{{")?; + + // Write `GetDimensions` function. + writeln!(self.out, "{}uint {};", INDENT, RETURN_VARIABLE_NAME)?; + writeln!( + self.out, + "{}{}.GetDimensions({});", + INDENT, ARGUMENT_VARIABLE_NAME, RETURN_VARIABLE_NAME + )?; + + // Write return value + writeln!(self.out, "{}return {};", INDENT, RETURN_VARIABLE_NAME)?; + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + + Ok(()) + } + + pub(super) fn write_wrapped_image_query_function_name( + &mut self, + query: WrappedImageQuery, + ) -> BackendResult { + let dim_str = query.dim.to_hlsl_str(); + let class_str = match query.class { + crate::ImageClass::Sampled { multi: true, .. } => "MS", + crate::ImageClass::Depth { multi: true } => "DepthMS", + crate::ImageClass::Depth { multi: false } => "Depth", + crate::ImageClass::Sampled { multi: false, .. } | crate::ImageClass::Storage { .. } => { + "" + } + }; + let arrayed_str = if query.arrayed { "Array" } else { "" }; + let query_str = match query.query { + ImageQuery::Size => "Dimensions", + ImageQuery::SizeLevel => "MipDimensions", + ImageQuery::NumLevels => "NumLevels", + ImageQuery::NumLayers => "NumLayers", + ImageQuery::NumSamples => "NumSamples", + }; + + write!( + self.out, + "Naga{}{}{}{}", + class_str, query_str, dim_str, arrayed_str + )?; + + Ok(()) + } + + /// Helper function that write wrapped function for `Expression::ImageQuery` + /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions + pub(super) fn write_wrapped_image_query_function( + &mut self, + module: &crate::Module, + wiq: WrappedImageQuery, + expr_handle: Handle, + func_ctx: &FunctionCtx, + ) -> BackendResult { + use crate::{back::INDENT, ImageDimension as IDim}; + + const ARGUMENT_VARIABLE_NAME: &str = "texture"; + const RETURN_VARIABLE_NAME: &str = "ret"; + const MIP_LEVEL_PARAM: &str = "mip_level"; + + // Write function return type and name + let ret_ty = func_ctx.info[expr_handle].ty.inner_with(&module.types); + self.write_value_type(module, ret_ty)?; + write!(self.out, " ")?; + self.write_wrapped_image_query_function_name(wiq)?; + + // Write function parameters + write!(self.out, "(")?; + // Texture always first parameter + self.write_image_type(wiq.dim, wiq.arrayed, wiq.class)?; + write!(self.out, " {}", ARGUMENT_VARIABLE_NAME)?; + // Mipmap is a second parameter if exists + if let ImageQuery::SizeLevel = wiq.query { + write!(self.out, ", uint {}", MIP_LEVEL_PARAM)?; + } + writeln!(self.out, ")")?; + + // Write function body + writeln!(self.out, "{{")?; + + let array_coords = if wiq.arrayed { 1 } else { 0 }; + // GetDimensions Overloaded Methods + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods + let (ret_swizzle, number_of_params) = match wiq.query { + ImageQuery::Size | ImageQuery::SizeLevel => match wiq.dim { + IDim::D1 => ("x", 1 + array_coords), + IDim::D2 => ("xy", 3 + array_coords), + IDim::D3 => ("xyz", 4), + IDim::Cube => ("xy", 3 + array_coords), + }, + ImageQuery::NumLevels | ImageQuery::NumSamples | ImageQuery::NumLayers => { + if wiq.arrayed || wiq.dim == IDim::D3 { + ("w", 4) + } else { + ("z", 3) + } + } + }; + + // Write `GetDimensions` function. + writeln!(self.out, "{}uint4 {};", INDENT, RETURN_VARIABLE_NAME)?; + write!( + self.out, + "{}{}.GetDimensions(", + INDENT, ARGUMENT_VARIABLE_NAME + )?; + match wiq.query { + ImageQuery::SizeLevel => { + write!(self.out, "{}, ", MIP_LEVEL_PARAM)?; + } + _ => match wiq.class { + crate::ImageClass::Sampled { multi: true, .. } + | crate::ImageClass::Depth { multi: true } => {} + _ => match wiq.dim { + // Write zero mipmap level for supported types + IDim::D2 | IDim::D3 | IDim::Cube => { + write!(self.out, "0, ")?; + } + IDim::D1 => {} + }, + }, + } + + for component in crate::back::COMPONENTS[..number_of_params - 1].iter() { + write!(self.out, "{}.{}, ", RETURN_VARIABLE_NAME, component)?; + } + + // write last parameter without comma and space for last parameter + write!( + self.out, + "{}.{}", + RETURN_VARIABLE_NAME, + crate::back::COMPONENTS[number_of_params - 1] + )?; + + writeln!(self.out, ");")?; + + // Write return value + writeln!( + self.out, + "{}return {}.{};", + INDENT, RETURN_VARIABLE_NAME, ret_swizzle + )?; + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + + Ok(()) + } + + /// Helper function that write wrapped function for `Expression::ImageQuery` and `Expression::ArrayLength` + /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions + pub(super) fn write_wrapped_functions( + &mut self, + module: &crate::Module, + func_ctx: &FunctionCtx, + ) -> BackendResult { + for (handle, _) in func_ctx.expressions.iter() { + match func_ctx.expressions[handle] { + crate::Expression::ArrayLength(expr) => { + let global_expr = match func_ctx.expressions[expr] { + crate::Expression::AccessIndex { base, index: _ } => base, + ref other => unreachable!("Array length of {:?}", other), + }; + let global_var = match func_ctx.expressions[global_expr] { + crate::Expression::GlobalVariable(var_handle) => { + &module.global_variables[var_handle] + } + ref other => unreachable!("Array length of base {:?}", other), + }; + let wal = WrappedArrayLength { + writable: global_var + .storage_access + .contains(crate::StorageAccess::STORE), + }; + + if !self.wrapped_array_lengths.contains(&wal) { + self.write_wrapped_array_length_function(module, wal, handle, func_ctx)?; + self.wrapped_array_lengths.insert(wal); + } + } + crate::Expression::ImageQuery { image, query } => { + let wiq = match *func_ctx.info[image].ty.inner_with(&module.types) { + crate::TypeInner::Image { + dim, + arrayed, + class, + } => WrappedImageQuery { + dim, + arrayed, + class, + query: query.into(), + }, + _ => unreachable!("we only query images"), + }; + + if !self.wrapped_image_queries.contains(&wiq) { + self.write_wrapped_image_query_function(module, wiq, handle, func_ctx)?; + self.wrapped_image_queries.insert(wiq); + } + } + _ => {} + }; + } + + Ok(()) + } + + pub(super) fn write_texture_coordinates( + &mut self, + kind: &str, + coordinate: Handle, + array_index: Option>, + mip_level: MipLevelCoordinate, + module: &crate::Module, + func_ctx: &FunctionCtx, + ) -> BackendResult { + // HLSL expects the array index to be merged with the coordinate + let extra = array_index.is_some() as usize + + (mip_level != MipLevelCoordinate::NotApplicable) as usize; + if extra == 0 { + self.write_expr(module, coordinate, func_ctx)?; + } else { + let num_coords = match *func_ctx.info[coordinate].ty.inner_with(&module.types) { + crate::TypeInner::Scalar { .. } => 1, + crate::TypeInner::Vector { size, .. } => size as usize, + _ => unreachable!(), + }; + write!(self.out, "{}{}(", kind, num_coords + extra)?; + self.write_expr(module, coordinate, func_ctx)?; + if let Some(expr) = array_index { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + match mip_level { + MipLevelCoordinate::NotApplicable => {} + MipLevelCoordinate::Zero => { + write!(self.out, ", 0")?; + } + MipLevelCoordinate::Expression(expr) => { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; + } + } + write!(self.out, ")")?; + } + Ok(()) + } +} diff --git a/src/back/hlsl/image.rs b/src/back/hlsl/image.rs deleted file mode 100644 index 306f35200..000000000 --- a/src/back/hlsl/image.rs +++ /dev/null @@ -1,299 +0,0 @@ -// Important note about `Expression::ImageQuery` and hlsl backend: -// Due to implementation of `GetDimensions` function in hlsl (https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions) -// backend can't work with it as an expression. -// Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texure info and query function. -// See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions. -// This allowed to works with `Expression::ImageQuery` as expression and write wrapped function. -// -// For example: -// ```wgsl -// let dim_1d = textureDimensions(image_1d); -// ``` -// -// ```hlsl -// int NagaDimensions1D(Texture1D) -// { -// uint4 ret; -// image_1d.GetDimensions(ret.x); -// return ret.x; -// } -// -// int dim_1d = NagaDimensions1D(image_1d); -// ``` - -use super::{super::FunctionCtx, writer::BackendResult}; -use crate::arena::Handle; -use std::fmt::Write; - -#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] -pub(super) struct WrappedImageQuery { - pub(super) dim: crate::ImageDimension, - pub(super) arrayed: bool, - pub(super) class: crate::ImageClass, - pub(super) query: ImageQuery, -} - -// HLSL backend requires its own `ImageQuery` enum. -// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function. -// IR version can't be unique per function, because it's store mipmap level as an expression. -// -// For example: -// ```wgsl -// let dim_cube_array_lod = textureDimensions(image_cube_array, 1); -// let dim_cube_array_lod2 = textureDimensions(image_cube_array, 1); -// ``` -// -// ```ir -// ImageQuery { -// image: [1], -// query: Size { -// level: Some( -// [1], -// ), -// }, -// }, -// ImageQuery { -// image: [1], -// query: Size { -// level: Some( -// [2], -// ), -// }, -// }, -// ``` -// -// HLSL should generate only 1 function for this case. -// -#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] -pub(super) enum ImageQuery { - Size, - SizeLevel, - NumLevels, - NumLayers, - NumSamples, -} - -impl From for ImageQuery { - fn from(q: crate::ImageQuery) -> Self { - use crate::ImageQuery as Iq; - match q { - Iq::Size { level: Some(_) } => ImageQuery::SizeLevel, - Iq::Size { level: None } => ImageQuery::Size, - Iq::NumLevels => ImageQuery::NumLevels, - Iq::NumLayers => ImageQuery::NumLayers, - Iq::NumSamples => ImageQuery::NumSamples, - } - } -} - -#[derive(Clone, Copy, PartialEq)] -pub(super) enum MipLevelCoordinate { - NotApplicable, - Zero, - Expression(Handle), -} - -impl<'a, W: Write> super::Writer<'a, W> { - pub(super) fn write_wrapped_image_query_function_name( - &mut self, - query: WrappedImageQuery, - ) -> BackendResult { - let dim_str = query.dim.to_hlsl_str(); - let class_str = match query.class { - crate::ImageClass::Sampled { multi: true, .. } => "MS", - crate::ImageClass::Depth { multi: true } => "DepthMS", - crate::ImageClass::Depth { multi: false } => "Depth", - crate::ImageClass::Sampled { multi: false, .. } | crate::ImageClass::Storage { .. } => { - "" - } - }; - let arrayed_str = if query.arrayed { "Array" } else { "" }; - let query_str = match query.query { - ImageQuery::Size => "Dimensions", - ImageQuery::SizeLevel => "MipDimensions", - ImageQuery::NumLevels => "NumLevels", - ImageQuery::NumLayers => "NumLayers", - ImageQuery::NumSamples => "NumSamples", - }; - - write!( - self.out, - "Naga{}{}{}{}", - class_str, query_str, dim_str, arrayed_str - )?; - - Ok(()) - } - - /// Helper function that write wrapped function for `Expression::ImageQuery` - /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions - pub(super) fn write_wrapped_image_query_functions( - &mut self, - module: &crate::Module, - func_ctx: &FunctionCtx, - ) -> BackendResult { - use crate::{back::INDENT, ImageDimension as IDim, ImageQuery as Iq}; - - const RETURN_VARIABLE_NAME: &str = "ret"; - const MIP_LEVEL_PARAM: &str = "MipLevel"; - - for (handle, _) in func_ctx.expressions.iter() { - let (image, query) = match func_ctx.expressions[handle] { - crate::Expression::ImageQuery { image, query } => (image, query), - _ => continue, - }; - let image_ty = func_ctx.info[image].ty.inner_with(&module.types); - let ret_ty = func_ctx.info[handle].ty.inner_with(&module.types); - - let (dim, arrayed, class) = match *image_ty { - crate::TypeInner::Image { - dim, - arrayed, - class, - } => (dim, arrayed, class), - _ => unreachable!("we only query images"), - }; - - let wrapped_image_query = WrappedImageQuery { - dim, - arrayed, - class, - query: query.into(), - }; - - if self.wrapped_image_queries.contains(&wrapped_image_query) { - continue; - } - - // Write function return type and name - self.write_value_type(module, ret_ty)?; - write!(self.out, " ")?; - self.write_wrapped_image_query_function_name(wrapped_image_query)?; - - // Write function parameters - write!(self.out, "(")?; - // Texture always first parameter - self.write_value_type(module, image_ty)?; - // Mipmap is a second parameter if exists - if let crate::ImageQuery::Size { level: Some(_) } = query { - write!(self.out, ", uint {}", MIP_LEVEL_PARAM)?; - } - writeln!(self.out, ")")?; - - // Write function body - writeln!(self.out, "{{")?; - - let array_coords = if arrayed { 1 } else { 0 }; - // GetDimensions Overloaded Methods - // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods - let (ret_swizzle, number_of_params) = match query { - Iq::Size { .. } => match dim { - IDim::D1 => ("x", 1 + array_coords), - IDim::D2 => ("xy", 3 + array_coords), - IDim::D3 => ("xyz", 4), - IDim::Cube => ("xy", 3 + array_coords), - }, - Iq::NumLevels | Iq::NumSamples | Iq::NumLayers => { - if arrayed || dim == IDim::D3 { - ("w", 4) - } else { - ("z", 3) - } - } - }; - - // Write `GetDimensions` function. - writeln!(self.out, "{}uint4 {};", INDENT, RETURN_VARIABLE_NAME)?; - write!(self.out, "{}", INDENT)?; - self.write_expr(module, image, func_ctx)?; - write!(self.out, ".GetDimensions(")?; - match query { - Iq::Size { level: Some(_) } => { - write!(self.out, "{}, ", MIP_LEVEL_PARAM)?; - } - _ => match class { - crate::ImageClass::Sampled { multi: true, .. } - | crate::ImageClass::Depth { multi: true } => {} - _ => match dim { - // Write zero mipmap level for supported types - IDim::D2 | IDim::D3 | IDim::Cube => { - write!(self.out, "0, ")?; - } - IDim::D1 => {} - }, - }, - } - - for component in crate::back::COMPONENTS[..number_of_params - 1].iter() { - write!(self.out, "{}.{}, ", RETURN_VARIABLE_NAME, component)?; - } - - // write last parameter without comma and space for last parameter - write!( - self.out, - "{}.{}", - RETURN_VARIABLE_NAME, - crate::back::COMPONENTS[number_of_params - 1] - )?; - - writeln!(self.out, ");")?; - - // Write return value - writeln!( - self.out, - "{}return {}.{};", - INDENT, RETURN_VARIABLE_NAME, ret_swizzle - )?; - - // End of function body - writeln!(self.out, "}}")?; - // Write extra new line - writeln!(self.out)?; - - self.wrapped_image_queries.insert(wrapped_image_query); - } - - Ok(()) - } - - pub(super) fn write_texture_coordinates( - &mut self, - kind: &str, - coordinate: Handle, - array_index: Option>, - mip_level: MipLevelCoordinate, - module: &crate::Module, - func_ctx: &FunctionCtx, - ) -> BackendResult { - // HLSL expects the array index to be merged with the coordinate - let extra = array_index.is_some() as usize - + (mip_level != MipLevelCoordinate::NotApplicable) as usize; - if extra == 0 { - self.write_expr(module, coordinate, func_ctx)?; - } else { - let num_coords = match *func_ctx.info[coordinate].ty.inner_with(&module.types) { - crate::TypeInner::Scalar { .. } => 1, - crate::TypeInner::Vector { size, .. } => size as usize, - _ => unreachable!(), - }; - write!(self.out, "{}{}(", kind, num_coords + extra)?; - self.write_expr(module, coordinate, func_ctx)?; - if let Some(expr) = array_index { - write!(self.out, ", ")?; - self.write_expr(module, expr, func_ctx)?; - } - match mip_level { - MipLevelCoordinate::NotApplicable => {} - MipLevelCoordinate::Zero => { - write!(self.out, ", 0")?; - } - MipLevelCoordinate::Expression(expr) => { - write!(self.out, ", ")?; - self.write_expr(module, expr, func_ctx)?; - } - } - write!(self.out, ")")?; - } - Ok(()) - } -} diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 12bb8670d..1b5e70b92 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -6,7 +6,8 @@ //! - 6.0 //! -mod image; +mod conv; +mod help; mod keywords; mod writer; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 78b87a342..483d4e689 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,5 +1,5 @@ use super::{ - image::{MipLevelCoordinate, WrappedImageQuery}, + help::{MipLevelCoordinate, WrappedArrayLength, WrappedImageQuery}, Error, Options, }; use crate::{ @@ -7,20 +7,25 @@ use crate::{ proc::{self, NameKey}, valid, Handle, Module, ShaderStage, TypeInner, }; -use std::fmt::Write; +use std::{fmt, mem}; const LOCATION_SEMANTIC: &str = "LOC"; /// Shorthand result used internally by the backend pub(super) type BackendResult = Result<(), Error>; -impl TypeInner { - fn is_matrix(&self) -> bool { - match *self { - Self::Matrix { .. } => true, - _ => false, - } - } +#[derive(Copy, Clone, PartialEq)] +enum Io { + Input, + Output, +} + +enum SubAccess { + Offset(u32), + Index { + value: Handle, + stride: u32, + }, } /// Structure contains information required for generating @@ -48,10 +53,12 @@ pub struct Writer<'a, W> { ep_inputs: Vec>, /// Set of expressions that have associated temporary variables named_expressions: crate::NamedExpressions, + pub(super) wrapped_array_lengths: crate::FastHashSet, pub(super) wrapped_image_queries: crate::FastHashSet, + temp_access_chain: Vec, } -impl<'a, W: Write> Writer<'a, W> { +impl<'a, W: fmt::Write> Writer<'a, W> { pub fn new(out: W, options: &'a Options) -> Self { Self { out, @@ -60,7 +67,9 @@ impl<'a, W: Write> Writer<'a, W> { options, ep_inputs: Vec::new(), named_expressions: crate::NamedExpressions::default(), + wrapped_array_lengths: crate::FastHashSet::default(), wrapped_image_queries: crate::FastHashSet::default(), + temp_access_chain: Vec::new(), } } @@ -68,8 +77,9 @@ impl<'a, W: Write> Writer<'a, W> { self.names.clear(); self.namer .reset(module, super::keywords::RESERVED, &[], &mut self.names); - self.named_expressions.clear(); self.ep_inputs.clear(); + self.named_expressions.clear(); + self.wrapped_array_lengths.clear(); self.wrapped_image_queries.clear(); } @@ -118,6 +128,17 @@ impl<'a, W: Write> Writer<'a, W> { .. } = ty.inner { + if let Some(member) = members.last() { + if let TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } = module.types[member.ty].inner + { + // unsized arrays can only be in storage buffers, for which we use `ByteAddressBuffer` anyway. + continue; + } + } + let ep_result = ep_results.iter().find(|e| { if let Some(ref result) = e.1 { result.ty == handle @@ -126,18 +147,13 @@ impl<'a, W: Write> Writer<'a, W> { } }); - if let Some(result) = ep_result { - self.write_struct( - module, - handle, - top_level, - members, - Some(result.0), - Some(true), - )?; - } else { - self.write_struct(module, handle, top_level, members, None, None)?; - } + self.write_struct( + module, + handle, + top_level, + members, + ep_result.map(|r| (r.0, Io::Output)), + )?; writeln!(self.out)?; } } @@ -192,8 +208,9 @@ impl<'a, W: Write> Writer<'a, W> { }; let name = self.names[&NameKey::Function(handle)].clone(); - // Write wrapped function for `Expression::ImageQuery` before writing all statements and expressions - self.write_wrapped_image_query_functions(module, &ctx)?; + // Write wrapped function for `Expression::ImageQuery` and `Expressions::ArrayLength` + // before writing all statements and expressions. + self.write_wrapped_functions(module, &ctx)?; self.write_function(module, name.as_str(), function, &ctx)?; @@ -232,8 +249,9 @@ impl<'a, W: Write> Writer<'a, W> { named_expressions: &ep.function.named_expressions, }; - // Write wrapped function for `Expression::ImageQuery` before writing all statements and expressions - self.write_wrapped_image_query_functions(module, &ctx)?; + // Write wrapped function for `Expression::ImageQuery` and `Expressions::ArrayLength` + // before writing all statements and expressions. + self.write_wrapped_functions(module, &ctx)?; if ep.stage == ShaderStage::Compute { // HLSL is calling workgroup size "num threads" @@ -261,15 +279,15 @@ impl<'a, W: Write> Writer<'a, W> { fn write_semantic( &mut self, binding: &crate::Binding, - stage: Option, - output: Option, + stage: Option<(ShaderStage, Io)>, ) -> BackendResult { match *binding { crate::Binding::BuiltIn(builtin) => { - write!(self.out, " : {}", builtin_str(builtin))?; + let builtin_str = builtin.to_hlsl_str()?; + write!(self.out, " : {}", builtin_str)?; } crate::Binding::Location { location, .. } => { - if stage == Some(crate::ShaderStage::Fragment) && output == Some(true) { + if stage == Some((crate::ShaderStage::Fragment, Io::Output)) { write!(self.out, " : SV_Target{}", location)?; } else { write!(self.out, " : {}{}", LOCATION_SEMANTIC, location)?; @@ -316,7 +334,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(module, member.ty)?; write!(self.out, " {}", &member.name)?; if let Some(ref binding) = member.binding { - self.write_semantic(binding, Some(stage), Some(false))?; + self.write_semantic(binding, Some((stage, Io::Input)))?; } write!(self.out, ";")?; writeln!(self.out)?; @@ -389,9 +407,7 @@ impl<'a, W: Write> Writer<'a, W> { } else { ("", "t") }; - write!(self.out, "{}StructuredBuffer<", prefix)?; - self.write_type(module, global.ty)?; - write!(self.out, ">")?; + write!(self.out, "{}ByteAddressBuffer", prefix)?; register } crate::StorageClass::Handle => { @@ -502,22 +518,13 @@ impl<'a, W: Write> Writer<'a, W> { // Panics if `ArraySize::Constant` has a constant that isn't an sint or uint match size { crate::ArraySize::Constant(const_handle) => { - match module.constants[const_handle].inner { - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(size), - } => write!(self.out, "{}", size)?, - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Sint(size), - } => write!(self.out, "{}", size)?, - _ => unreachable!(), - } + let size = module.constants[const_handle].to_array_length().unwrap(); + write!(self.out, "{}", size)?; } crate::ArraySize::Dynamic => { //TODO: https://github.com/gfx-rs/naga/issues/1127 log::warn!("Dynamically sized arrays are not properly supported yet"); - write!(self.out, "1")? + write!(self.out, "1")?; } } @@ -535,8 +542,7 @@ impl<'a, W: Write> Writer<'a, W> { handle: Handle, _block: bool, members: &[crate::StructMember], - shader_stage: Option, - out: Option, + shader_stage: Option<(ShaderStage, Io)>, ) -> BackendResult { // Write struct name write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?; @@ -553,15 +559,22 @@ impl<'a, W: Write> Writer<'a, W> { stride: _, } => { // HLSL arrays are written as `type name[size]` - let ty_name = match module.types[base].inner { + let (ty_name, vec_size) = match module.types[base].inner { // Write scalar type by backend so as not to depend on the front-end implementation // Name returned from frontend can be generated (type1, float1, etc.) - TypeInner::Scalar { kind, width } => scalar_kind_str(kind, width)?, - _ => &self.names[&NameKey::Type(base)], + TypeInner::Scalar { kind, width } => (kind.to_hlsl_str(width)?, None), + // Similarly, write vector types directly. + TypeInner::Vector { size, kind, width } => { + (kind.to_hlsl_str(width)?, Some(size)) + } + _ => (self.names[&NameKey::Type(base)].as_str(), None), }; // Write `type` and `name` write!(self.out, "{}", ty_name)?; + if let Some(s) = vec_size { + write!(self.out, "{}", s as usize)?; + } write!( self.out, " {}", @@ -579,12 +592,12 @@ impl<'a, W: Write> Writer<'a, W> { }) = member.binding { if let Some(interpolation) = interpolation { - write!(self.out, "{} ", interpolation_str(interpolation))? + write!(self.out, "{} ", interpolation.to_hlsl_str())? } if let Some(sampling) = sampling { - if let Some(str) = sampling_str(sampling) { - write!(self.out, "{} ", str)? + if let Some(string) = sampling.to_hlsl_str() { + write!(self.out, "{} ", string)? } } } @@ -600,7 +613,7 @@ impl<'a, W: Write> Writer<'a, W> { } if let Some(ref binding) = member.binding { - self.write_semantic(binding, shader_stage, out)?; + self.write_semantic(binding, shader_stage)?; }; write!(self.out, ";")?; writeln!(self.out)?; @@ -633,13 +646,13 @@ impl<'a, W: Write> Writer<'a, W> { pub(super) fn write_value_type(&mut self, module: &Module, inner: &TypeInner) -> BackendResult { match *inner { TypeInner::Scalar { kind, width } => { - write!(self.out, "{}", scalar_kind_str(kind, width)?)?; + write!(self.out, "{}", kind.to_hlsl_str(width)?)?; } TypeInner::Vector { size, kind, width } => { write!( self.out, "{}{}", - scalar_kind_str(kind, width)?, + kind.to_hlsl_str(width)?, back::vector_size_str(size) )?; } @@ -653,7 +666,7 @@ impl<'a, W: Write> Writer<'a, W> { write!( self.out, "{}{}x{}", - scalar_kind_str(crate::ScalarKind::Float, width)?, + crate::ScalarKind::Float.to_hlsl_str(width)?, back::vector_size_str(columns), back::vector_size_str(rows), )?; @@ -663,26 +676,7 @@ impl<'a, W: Write> Writer<'a, W> { arrayed, class, } => { - use crate::ImageClass as Ic; - - let dim_str = dim.to_hlsl_str(); - let arrayed_str = if arrayed { "Array" } else { "" }; - write!(self.out, "Texture{}{}", dim_str, arrayed_str)?; - match class { - Ic::Depth { multi } => { - let multi_str = if multi { "MS" } else { "" }; - write!(self.out, "{}", multi_str)? - } - Ic::Sampled { kind, multi } => { - let multi_str = if multi { "MS" } else { "" }; - let scalar_kind_str = scalar_kind_str(kind, 4)?; - write!(self.out, "{}<{}4>", multi_str, scalar_kind_str)? - } - Ic::Storage(format) => { - let storage_format_str = storage_format_to_texture_type(format); - write!(self.out, "<{}>", storage_format_str)? - } - } + self.write_image_type(dim, arrayed, class)?; } TypeInner::Sampler { comparison } => { let sampler = if comparison { @@ -782,8 +776,7 @@ impl<'a, W: Write> Writer<'a, W> { }; if let Some(ref result) = func.result { if let Some(ref binding) = result.binding { - let output = stage.is_some(); - self.write_semantic(binding, stage, Some(output))?; + self.write_semantic(binding, stage.map(|s| (s, Io::Output)))?; } } @@ -955,11 +948,48 @@ impl<'a, W: Write> Writer<'a, W> { } } Statement::Store { pointer, value } => { - write!(self.out, "{}", INDENT.repeat(indent))?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, " = ")?; - self.write_expr(module, value, func_ctx)?; - writeln!(self.out, ";")? + let array_info = match *func_ctx.info[pointer].ty.inner_with(&module.types) { + TypeInner::Pointer { base, .. } => match module.types[base].inner { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(ch), + .. + } => Some((ch, base)), + _ => None, + }, + _ => None, + }; + + if func_ctx.info[pointer] + .ty + .inner_with(&module.types) + .pointer_class() + == Some(crate::StorageClass::Storage) + { + return Err(Error::Unimplemented("Storage stores".to_string())); + } else if let Some((const_handle, base_ty)) = array_info { + let size = module.constants[const_handle].to_array_length().unwrap(); + writeln!(self.out, "{}{{", INDENT.repeat(indent))?; + write!(self.out, "{}", INDENT.repeat(indent + 1))?; + self.write_type(module, base_ty)?; + write!(self.out, " _result[{}]=", size)?; + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ";")?; + write!( + self.out, + "{}for(int _i=0; _i<{}; ++_i) ", + INDENT.repeat(indent + 1), + size + )?; + self.write_expr(module, pointer, func_ctx)?; + writeln!(self.out, "[_i] = _result[_i];")?; + writeln!(self.out, "{}}}", INDENT.repeat(indent))?; + } else { + write!(self.out, "{}", INDENT.repeat(indent))?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, " = ")?; + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ";")? + } } Statement::Call { function, @@ -1134,40 +1164,65 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(module, right, func_ctx)?; write!(self.out, ")")?; } - // TODO: copy-paste from glsl-out + Expression::Access { base, index } => { + if func_ctx.info[expr] + .ty + .inner_with(&module.types) + .pointer_class() + == Some(crate::StorageClass::Storage) + { + // do nothing, the chain is written on `Load`/`Store` + } else { + self.write_expr(module, base, func_ctx)?; + write!(self.out, "[")?; + self.write_expr(module, index, func_ctx)?; + write!(self.out, "]")?; + } + } Expression::AccessIndex { base, index } => { - self.write_expr(module, base, func_ctx)?; + if func_ctx.info[expr] + .ty + .inner_with(&module.types) + .pointer_class() + == Some(crate::StorageClass::Storage) + { + // do nothing, the chain is written on `Load`/`Store` + } else { + self.write_expr(module, base, func_ctx)?; - let base_ty_res = &func_ctx.info[base].ty; - let mut resolved = base_ty_res.inner_with(&module.types); - let base_ty_handle = match *resolved { - TypeInner::Pointer { base, class: _ } => { - resolved = &module.types[base].inner; - Some(base) - } - _ => base_ty_res.handle(), - }; + let base_ty_res = &func_ctx.info[base].ty; + let mut resolved = base_ty_res.inner_with(&module.types); + let base_ty_handle = match *resolved { + TypeInner::Pointer { base, class: _ } => { + resolved = &module.types[base].inner; + Some(base) + } + _ => base_ty_res.handle(), + }; - match *resolved { - TypeInner::Vector { .. } => { - // Write vector access as a swizzle - write!(self.out, ".{}", back::COMPONENTS[index as usize])? - } - TypeInner::Matrix { .. } - | TypeInner::Array { .. } - | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, - TypeInner::Struct { .. } => { - // This will never panic in case the type is a `Struct`, this is not true - // for other types so we can only check while inside this match arm - let ty = base_ty_handle.unwrap(); + match *resolved { + TypeInner::Vector { .. } => { + // Write vector access as a swizzle + write!(self.out, ".{}", back::COMPONENTS[index as usize])? + } + TypeInner::Matrix { .. } + | TypeInner::Array { .. } + | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, + TypeInner::Struct { .. } => { + // This will never panic in case the type is a `Struct`, this is not true + // for other types so we can only check while inside this match arm + let ty = base_ty_handle.unwrap(); - write!( - self.out, - ".{}", - &self.names[&NameKey::StructMember(ty, index)] - )? + write!( + self.out, + ".{}", + &self.names[&NameKey::StructMember(ty, index)] + )? + } + ref other => { + return Err(Error::Custom(format!("Cannot index {:?}", other))) + } } - ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), } } Expression::FunctionArgument(pos) => { @@ -1339,24 +1394,27 @@ impl<'a, W: Write> Writer<'a, W> { } } Expression::GlobalVariable(handle) => { - let name = &self.names[&NameKey::GlobalVariable(handle)]; - let postfix = match module.global_variables[handle].class { - crate::StorageClass::Storage => "[0]", - _ => "", - }; - write!(self.out, "{}{}", name, postfix)?; + if module.global_variables[handle].class != crate::StorageClass::Storage { + let name = &self.names[&NameKey::GlobalVariable(handle)]; + write!(self.out, "{}", name)?; + } } Expression::LocalVariable(handle) => { write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])? } Expression::Load { pointer } => { - self.write_expr(module, pointer, func_ctx)?; - } - Expression::Access { base, index } => { - self.write_expr(module, base, func_ctx)?; - write!(self.out, "[")?; - self.write_expr(module, index, func_ctx)?; - write!(self.out, "]")?; + if func_ctx.info[pointer] + .ty + .inner_with(&module.types) + .pointer_class() + == Some(crate::StorageClass::Storage) + { + let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; + let result_ty = func_ctx.info[expr].ty.clone(); + self.write_storage_load(module, var_handle, result_ty, func_ctx)?; + } else { + self.write_expr(module, pointer, func_ctx)?; + } } Expression::Unary { op, expr } => { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators @@ -1374,12 +1432,12 @@ impl<'a, W: Write> Writer<'a, W> { write!( self.out, "{}{}", - scalar_kind_str(kind, width)?, + kind.to_hlsl_str(width)?, back::vector_size_str(size), )?; } TypeInner::Scalar { width, .. } => { - write!(self.out, "{}", scalar_kind_str(kind, width)?)? + write!(self.out, "{}", kind.to_hlsl_str(width)?)? } _ => { return Err(Error::Unimplemented(format!( @@ -1482,10 +1540,44 @@ impl<'a, W: Write> Writer<'a, W> { self.out.write_char(back::COMPONENTS[sc as usize])?; } } - // `ArrayLength` is written as `expr.length()` Expression::ArrayLength(expr) => { - self.write_expr(module, expr, func_ctx)?; - write!(self.out, ".length()")? + let var_handle = match func_ctx.expressions[expr] { + Expression::AccessIndex { base, index: _ } => { + match func_ctx.expressions[base] { + Expression::GlobalVariable(handle) => handle, + _ => unreachable!(), + } + } + Expression::GlobalVariable(handle) => handle, + _ => unreachable!(), + }; + + let var = &module.global_variables[var_handle]; + let (offset, stride) = match module.types[var.ty].inner { + TypeInner::Array { stride, .. } => (0, stride), + TypeInner::Struct { + top_level: true, + ref members, + .. + } => { + let last = members.last().unwrap(); + let stride = match module.types[last.ty].inner { + TypeInner::Array { stride, .. } => stride, + _ => unreachable!(), + }; + (last.offset, stride) + } + _ => unreachable!(), + }; + + let wrapped_array_length = WrappedArrayLength { + writable: var.storage_access.contains(crate::StorageAccess::STORE), + }; + + write!(self.out, "((")?; + self.write_wrapped_array_length_function_name(wrapped_array_length)?; + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + write!(self.out, "({}) - {}) / {})", var_name, offset, stride)? } Expression::Derivative { axis, expr } => { use crate::DerivativeAxis as Da; @@ -1654,109 +1746,193 @@ impl<'a, W: Write> Writer<'a, W> { /// Helper function that write default zero initialization fn write_default_init(&mut self, module: &Module, ty: Handle) -> BackendResult { - write!(self.out, "(")?; - self.write_type(module, ty)?; - if let TypeInner::Array { size, .. } = module.types[ty].inner { - self.write_array_size(module, size)?; + match module.types[ty].inner { + TypeInner::Array { + size: crate::ArraySize::Constant(const_handle), + base, + .. + } => { + write!(self.out, "{{")?; + let count = module.constants[const_handle].to_array_length().unwrap(); + for i in 0..count { + if i != 0 { + write!(self.out, ",")?; + } + self.write_default_init(module, base)?; + } + write!(self.out, "}}")?; + } + _ => { + write!(self.out, "(")?; + self.write_type(module, ty)?; + write!(self.out, ")0")?; + } } - write!(self.out, ")0")?; - Ok(()) } -} -fn builtin_str(built_in: crate::BuiltIn) -> &'static str { - use crate::BuiltIn as Bi; + fn write_storage_address( + &mut self, + module: &Module, + chain: &[SubAccess], + func_ctx: &back::FunctionCtx<'_>, + ) -> BackendResult { + for (i, access) in chain.iter().enumerate() { + if i != 0 { + write!(self.out, "+")?; + } + match *access { + SubAccess::Offset(offset) => { + write!(self.out, "{}", offset)?; + } + SubAccess::Index { value, stride } => { + self.write_expr(module, value, func_ctx)?; + write!(self.out, "*{}", stride)?; + } + } + } + Ok(()) + } - match built_in { - Bi::Position => "SV_Position", - // vertex - Bi::ClipDistance => "SV_ClipDistance", - Bi::CullDistance => "SV_CullDistance", - Bi::InstanceIndex => "SV_InstanceID", - // based on this page https://docs.microsoft.com/en-us/windows/uwp/gaming/glsl-to-hlsl-reference#comparing-opengl-es-20-with-direct3d-11 - // No meaning unless you target Direct3D 9 - Bi::PointSize => "PSIZE", - Bi::VertexIndex => "SV_VertexID", - // fragment - Bi::FragDepth => "SV_Depth", - Bi::FrontFacing => "SV_IsFrontFace", - Bi::PrimitiveIndex => "SV_PrimitiveID", - Bi::SampleIndex => "SV_SampleIndex", - Bi::SampleMask => "SV_Coverage", - // compute - Bi::GlobalInvocationId => "SV_DispatchThreadID", - Bi::LocalInvocationId => "SV_GroupThreadID", - Bi::LocalInvocationIndex => "SV_GroupIndex", - Bi::WorkGroupId => "SV_GroupID", - _ => todo!("builtin_str {:?}", built_in), + fn write_storage_load_sequence>( + &mut self, + module: &Module, + var_handle: Handle, + sequence: I, + func_ctx: &back::FunctionCtx<'_>, + ) -> BackendResult { + for (i, (ty_resolution, offset)) in sequence.enumerate() { + // add the index temporarily + self.temp_access_chain.push(SubAccess::Offset(offset)); + if i != 0 { + write!(self.out, ", ")?; + }; + self.write_storage_load(module, var_handle, ty_resolution, func_ctx)?; + self.temp_access_chain.pop(); + } + Ok(()) } -} -/// Helper function that returns scalar related strings -/// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-scalar -fn scalar_kind_str(kind: crate::ScalarKind, width: crate::Bytes) -> Result<&'static str, Error> { - use crate::ScalarKind as Sk; - - match kind { - Sk::Sint => Ok("int"), - Sk::Uint => Ok("uint"), - Sk::Float => match width { - 2 => Ok("half"), - 4 => Ok("float"), - 8 => Ok("double"), - _ => Err(Error::UnsupportedScalar(kind, width)), - }, - Sk::Bool => Ok("bool"), - } -} - -/// Helper function that returns the string corresponding to the HLSL interpolation qualifier -fn interpolation_str(interpolation: crate::Interpolation) -> &'static str { - use crate::Interpolation as I; - - match interpolation { - I::Perspective => "linear", - I::Linear => "noperspective", - I::Flat => "nointerpolation", - } -} - -/// Return the HLSL auxiliary qualifier for the given sampling value. -fn sampling_str(sampling: crate::Sampling) -> Option<&'static str> { - use crate::Sampling as S; - - match sampling { - S::Center => None, - S::Centroid => Some("centroid"), - S::Sample => Some("sample"), + /// Helper function to write down the load operation on a `ByteAddressBuffer`. + fn write_storage_load( + &mut self, + module: &Module, + var_handle: Handle, + result_ty: proc::TypeResolution, + func_ctx: &back::FunctionCtx<'_>, + ) -> BackendResult { + match *result_ty.inner_with(&module.types) { + TypeInner::Scalar { kind, width: _ } => { + // working around the borrow checker in `self.write_expr` + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + let cast = kind.to_hlsl_cast(); + write!(self.out, "{}({}.Load(", cast, var_name)?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, "))")?; + self.temp_access_chain = chain; + } + TypeInner::Vector { + size, + kind, + width: _, + } => { + // working around the borrow checker in `self.write_expr` + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + let cast = kind.to_hlsl_cast(); + write!(self.out, "{}({}.Load{}(", cast, var_name, size as u8)?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, "))")?; + self.temp_access_chain = chain; + } + TypeInner::Matrix { + columns, + rows, + width, + } => { + write!( + self.out, + "{}{}x{}(", + crate::ScalarKind::Float.to_hlsl_str(width)?, + columns as u8, + rows as u8, + )?; + let row_stride = width as u32 * rows as u32; + let iter = (0..columns as u32).map(|i| { + let ty_inner = TypeInner::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }; + (proc::TypeResolution::Value(ty_inner), i * row_stride) + }); + self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; + write!(self.out, ")")?; + } + TypeInner::Array { + base, + size: crate::ArraySize::Constant(const_handle), + .. + } => { + write!(self.out, "{{")?; + let count = module.constants[const_handle].to_array_length().unwrap(); + let stride = module.types[base].inner.span(&module.constants); + let iter = (0..count).map(|i| (proc::TypeResolution::Handle(base), stride * i)); + self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; + write!(self.out, "}}")?; + } + TypeInner::Struct { ref members, .. } => { + write!(self.out, "{{")?; + let iter = members + .iter() + .map(|m| (proc::TypeResolution::Handle(m.ty), m.offset)); + self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; + write!(self.out, "}}")?; + } + _ => unreachable!(), + } + Ok(()) } -} - -fn storage_format_to_texture_type(format: crate::StorageFormat) -> &'static str { - use crate::StorageFormat as Sf; - - match format { - Sf::R16Float => "float", - Sf::R8Unorm => "unorm float", - Sf::R8Snorm => "snorm float", - Sf::R8Uint | Sf::R16Uint => "uint", - Sf::R8Sint | Sf::R16Sint => "int", - - Sf::Rg16Float => "float2", - Sf::Rg8Unorm => "unorm float2", - Sf::Rg8Snorm => "snorm float2", - - Sf::Rg8Sint | Sf::Rg16Sint => "int2", - Sf::Rg8Uint | Sf::Rg16Uint => "uint2", - - Sf::Rg11b10Float => "float3", - - Sf::Rgba16Float | Sf::R32Float | Sf::Rg32Float | Sf::Rgba32Float => "float4", - Sf::Rgba8Unorm | Sf::Rgb10a2Unorm => "unorm float4", - Sf::Rgba8Snorm => "snorm float4", - Sf::Rgba8Uint | Sf::Rgba16Uint | Sf::R32Uint | Sf::Rg32Uint | Sf::Rgba32Uint => "uint4", - Sf::Rgba8Sint | Sf::Rgba16Sint | Sf::R32Sint | Sf::Rg32Sint | Sf::Rgba32Sint => "int4", + fn fill_access_chain( + &mut self, + module: &Module, + mut cur_expr: Handle, + func_ctx: &back::FunctionCtx<'_>, + ) -> Result, Error> { + self.temp_access_chain.clear(); + loop { + let stride = func_ctx.info[cur_expr] + .ty + .inner_with(&module.types) + .span(&module.constants); + let (next_expr, sub) = match func_ctx.expressions[cur_expr] { + crate::Expression::GlobalVariable(handle) => return Ok(handle), + crate::Expression::Access { base, index } => ( + base, + SubAccess::Index { + value: index, + stride, + }, + ), + crate::Expression::AccessIndex { base, index } => { + match *func_ctx.info[base].ty.inner_with(&module.types) { + TypeInner::Struct { ref members, .. } => { + (base, SubAccess::Offset(members[index as usize].offset)) + } + _ => (base, SubAccess::Offset(index * stride)), + } + } + ref other => { + return Err(Error::Unimplemented(format!( + "Pointer access of {:?}", + other + ))) + } + }; + self.temp_access_chain.push(sub); + cur_expr = next_expr; + } } } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index d6493ac71..5cb5d585f 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -199,12 +199,7 @@ impl<'w> BlockContext<'w> { crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => true, crate::Expression::FunctionArgument(index) => { let arg = &self.ir_function.arguments[index as usize]; - match self.ir_module.types[arg.ty].inner { - crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { - true - } - _ => false, - } + self.ir_module.types[arg.ty].inner.pointer_class().is_some() } // The chain rule: if this `Access...`'s `base` operand was diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index bb1fd41aa..9e5ec6781 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -492,14 +492,12 @@ impl<'function> Context<'function> { }); if !lhs { - match *program.resolve_type(self, pointer, meta)? { - TypeInner::Pointer { .. } | TypeInner::ValuePointer { .. } => { - return Ok(( - Some(self.add_expression(Expression::Load { pointer }, body)), - meta, - )); - } - _ => {} + let resolved = program.resolve_type(self, pointer, meta)?; + if resolved.pointer_class().is_some() { + return Ok(( + Some(self.add_expression(Expression::Load { pointer }, body)), + meta, + )); } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 01ecda65d..7cab0a833 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2906,19 +2906,18 @@ impl> Parser { let decor = self.future_decor.remove(&id); let base_lookup_ty = self.lookup_type.lookup(type_id)?; - let class = match module.types[base_lookup_ty.handle].inner { - crate::TypeInner::Pointer { class, .. } - | crate::TypeInner::ValuePointer { class, .. } => class, - _ if self - .lookup_storage_buffer_types - .contains_key(&base_lookup_ty.handle) => - { - crate::StorageClass::Storage - } - _ => match map_storage_class(storage_class)? { + let class = if let Some(class) = module.types[base_lookup_ty.handle].inner.pointer_class() { + class + } else if self + .lookup_storage_buffer_types + .contains_key(&base_lookup_ty.handle) + { + crate::StorageClass::Storage + } else { + match map_storage_class(storage_class)? { ExtendedClass::Global(class) => class, ExtendedClass::Input | ExtendedClass::Output => crate::StorageClass::Private, - }, + } }; // Don't bother with pointer stuff for `Handle` types. diff --git a/src/proc/mod.rs b/src/proc/mod.rs index b19fe6a47..0c51646e4 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -85,6 +85,14 @@ impl super::TypeInner { } } + pub fn pointer_class(&self) -> Option { + match *self { + Self::Pointer { class, .. } => Some(class), + Self::ValuePointer { class, .. } => Some(class), + _ => None, + } + } + pub fn span(&self, constants: &super::Arena) -> u32 { match *self { Self::Scalar { kind: _, width } => width as u32, diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index e6cd5552a..f97d504de 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -3,6 +3,7 @@ [[block]] struct Bar { matrix: mat4x4; + arr: [[stride(8)]] array, 2>; data: [[stride(4)]] array; }; @@ -16,6 +17,9 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let baz: f32 = foo; foo = 1.0; + let matrix = bar.matrix; + let arr = bar.arr; + let index = 3u; let b = bar.matrix[index].x; @@ -25,5 +29,5 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { c[vi + 1u] = 42; let value = c[vi]; - return vec4(vec4(value)); + return matrix * vec4(vec4(value)); } diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl new file mode 100644 index 000000000..8d299c9a8 --- /dev/null +++ b/tests/out/hlsl/access.hlsl @@ -0,0 +1,34 @@ + +RWByteAddressBuffer bar : register(u0); + +struct VertexInput_foo { + uint vi1 : SV_VertexID; +}; + +uint NagaBufferLengthRW(RWByteAddressBuffer buffer) +{ + uint ret; + buffer.GetDimensions(ret); + return ret; +} + +float4 foo(VertexInput_foo vertexinput_foo) : SV_Position +{ + float foo1 = 0.0; + int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; + + float baz = foo1; + foo1 = 1.0; + float4x4 matrix1 = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); + uint2 arr[2] = {asuint(bar.Load2(4+0)), asuint(bar.Load2(4+8))}; + float4 _expr13 = asfloat(bar.Load4(12+0)); + float b = _expr13.x; + int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 80) / 4) - 2u)*4+8)); + { + int _result[5]={ a, int(b), 3, 4, 5 }; + for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; + } + c[(vertexinput_foo.vi1 + 1u)] = 42; + int value = c[vertexinput_foo.vi1]; + return mul(matrix1, float4(int4(value.xxxx))); +} diff --git a/tests/out/hlsl/access.hlsl.config b/tests/out/hlsl/access.hlsl.config new file mode 100644 index 000000000..f684c661e --- /dev/null +++ b/tests/out/hlsl/access.hlsl.config @@ -0,0 +1,3 @@ +vertex=(foo:vs_5_0 ) +fragment=() +compute=() diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index c85118b76..d72239152 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -19,10 +19,10 @@ struct ComputeInput_main { uint3 local_id1 : SV_GroupThreadID; }; -int2 NagaDimensions2D(Texture2D) +int2 NagaDimensions2D(Texture2D texture) { uint4 ret; - image_storage_src.GetDimensions(0, ret.x, ret.y, ret.z); + texture.GetDimensions(0, ret.x, ret.y, ret.z); return ret.xy; } @@ -39,136 +39,136 @@ void main(ComputeInput_main computeinput_main) return; } -int NagaDimensions1D(Texture1D) +int NagaDimensions1D(Texture1D texture) { uint4 ret; - image_1d.GetDimensions(ret.x); + texture.GetDimensions(ret.x); return ret.x; } -int2 NagaDimensions2D(Texture2D) +int2 NagaDimensions2D(Texture2D texture) { uint4 ret; - image_2d.GetDimensions(0, ret.x, ret.y, ret.z); + texture.GetDimensions(0, ret.x, ret.y, ret.z); return ret.xy; } -int NagaNumLevels2D(Texture2D) +int NagaNumLevels2D(Texture2D texture) { uint4 ret; - image_2d.GetDimensions(0, ret.x, ret.y, ret.z); + texture.GetDimensions(0, ret.x, ret.y, ret.z); return ret.z; } -int2 NagaMipDimensions2D(Texture2D, uint MipLevel) +int2 NagaMipDimensions2D(Texture2D texture, uint mip_level) { uint4 ret; - image_2d.GetDimensions(MipLevel, ret.x, ret.y, ret.z); + texture.GetDimensions(mip_level, ret.x, ret.y, ret.z); return ret.xy; } -int2 NagaDimensions2DArray(Texture2DArray) +int2 NagaDimensions2DArray(Texture2DArray texture) { uint4 ret; - image_2d_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int NagaNumLevels2DArray(Texture2DArray) +int NagaNumLevels2DArray(Texture2DArray texture) { uint4 ret; - image_2d_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int2 NagaMipDimensions2DArray(Texture2DArray, uint MipLevel) +int2 NagaMipDimensions2DArray(Texture2DArray texture, uint mip_level) { uint4 ret; - image_2d_array.GetDimensions(MipLevel, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int NagaNumLayers2DArray(Texture2DArray) +int NagaNumLayers2DArray(Texture2DArray texture) { uint4 ret; - image_2d_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int2 NagaDimensionsCube(TextureCube) +int2 NagaDimensionsCube(TextureCube texture) { uint4 ret; - image_cube.GetDimensions(0, ret.x, ret.y, ret.z); + texture.GetDimensions(0, ret.x, ret.y, ret.z); return ret.xy; } -int NagaNumLevelsCube(TextureCube) +int NagaNumLevelsCube(TextureCube texture) { uint4 ret; - image_cube.GetDimensions(0, ret.x, ret.y, ret.z); + texture.GetDimensions(0, ret.x, ret.y, ret.z); return ret.z; } -int2 NagaMipDimensionsCube(TextureCube, uint MipLevel) +int2 NagaMipDimensionsCube(TextureCube texture, uint mip_level) { uint4 ret; - image_cube.GetDimensions(MipLevel, ret.x, ret.y, ret.z); + texture.GetDimensions(mip_level, ret.x, ret.y, ret.z); return ret.xy; } -int2 NagaDimensionsCubeArray(TextureCubeArray) +int2 NagaDimensionsCubeArray(TextureCubeArray texture) { uint4 ret; - image_cube_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int NagaNumLevelsCubeArray(TextureCubeArray) +int NagaNumLevelsCubeArray(TextureCubeArray texture) { uint4 ret; - image_cube_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int2 NagaMipDimensionsCubeArray(TextureCubeArray, uint MipLevel) +int2 NagaMipDimensionsCubeArray(TextureCubeArray texture, uint mip_level) { uint4 ret; - image_cube_array.GetDimensions(MipLevel, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int NagaNumLayersCubeArray(TextureCubeArray) +int NagaNumLayersCubeArray(TextureCubeArray texture) { uint4 ret; - image_cube_array.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int3 NagaDimensions3D(Texture3D) +int3 NagaDimensions3D(Texture3D texture) { uint4 ret; - image_3d.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.xyz; } -int NagaNumLevels3D(Texture3D) +int NagaNumLevels3D(Texture3D texture) { uint4 ret; - image_3d.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int3 NagaMipDimensions3D(Texture3D, uint MipLevel) +int3 NagaMipDimensions3D(Texture3D texture, uint mip_level) { uint4 ret; - image_3d.GetDimensions(MipLevel, ret.x, ret.y, ret.z, ret.w); + texture.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); return ret.xyz; } -int NagaMSNumSamples2D(Texture2DMS) +int NagaMSNumSamples2D(Texture2DMS texture) { uint4 ret; - image_aa.GetDimensions(ret.x, ret.y, ret.z); + texture.GetDimensions(ret.x, ret.y, ret.z); return ret.z; } diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index bec95958c..44efa15af 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -11,12 +11,8 @@ struct Light { float4 color; }; -struct Lights { - Light data[1]; -}; - cbuffer u_globals : register(b0) { Globals u_globals; } -StructuredBuffer s_lights : register(t1); +ByteAddressBuffer s_lights : register(t1); Texture2DArray t_shadow : register(t2); SamplerComparisonState sampler_shadow : register(s3); @@ -49,7 +45,7 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 break; } uint _expr19 = i; - Light light = s_lights[0].data[_expr19]; + Light light = {float4x4(asfloat(s_lights.Load4(_expr19*4+0+0+0)), asfloat(s_lights.Load4(_expr19*4+0+0+16)), asfloat(s_lights.Load4(_expr19*4+0+0+32)), asfloat(s_lights.Load4(_expr19*4+0+0+48))), asfloat(s_lights.Load4(_expr19*4+0+64)), asfloat(s_lights.Load4(_expr19*4+0+80))}; uint _expr22 = i; const float _e25 = fetch_shadow(_expr22, mul(light.proj, fragmentinput_fs_main.position1)); float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz)); diff --git a/tests/out/hlsl/texture-arg.hlsl b/tests/out/hlsl/texture-arg.hlsl new file mode 100644 index 000000000..32f950dff --- /dev/null +++ b/tests/out/hlsl/texture-arg.hlsl @@ -0,0 +1,15 @@ + +Texture2D Texture : register(t0); +SamplerState Sampler : register(s1); + +float4 test(Texture2D Passed_Texture, SamplerState Passed_Sampler) +{ + float4 _expr7 = Passed_Texture.Sample(Passed_Sampler, float2(0.0, 0.0)); + return _expr7; +} + +float4 main() : SV_Target0 +{ + const float4 _e2 = test(Texture, Sampler); + return _e2; +} diff --git a/tests/out/hlsl/texture-arg.hlsl.config b/tests/out/hlsl/texture-arg.hlsl.config new file mode 100644 index 000000000..18ddfc224 --- /dev/null +++ b/tests/out/hlsl/texture-arg.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=(main:ps_5_0 ) +compute=() diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index fbde9f3d7..b04acf40b 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -6,12 +6,16 @@ struct _mslBufferSizes { metal::uint size0; }; -typedef int type2[1]; +struct type2 { + metal::uint2 inner[2]; +}; +typedef int type4[1]; struct Bar { metal::float4x4 matrix; - type2 data; + type2 arr; + type4 data; }; -struct type6 { +struct type8 { int inner[5]; }; @@ -26,14 +30,16 @@ vertex fooOutput foo( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo1 = 0.0; - type6 c; + type8 c; float baz = foo1; foo1 = 1.0; - metal::float4 _e9 = bar.matrix[3]; - float b = _e9.x; - int a = bar.data[(1 + (_buffer_sizes.size0 - 64 - 4) / 4) - 2u]; - for(int _i=0; _i<5; ++_i) c.inner[_i] = type6 {a, static_cast(b), 3, 4, 5}.inner[_i]; + metal::float4x4 matrix = bar.matrix; + type2 arr = bar.arr; + metal::float4 _e13 = bar.matrix[3]; + float b = _e13.x; + int a = bar.data[(1 + (_buffer_sizes.size0 - 80 - 4) / 4) - 2u]; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type8 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; - return fooOutput { static_cast(metal::int4(value)) }; + return fooOutput { matrix * static_cast(metal::int4(value)) }; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index f6f2f8c8a..32c4fc27d 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,92 +1,104 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 58 +; Bound: 67 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %32 "foo" %27 %30 +OpEntryPoint Vertex %35 "foo" %30 %33 OpSource GLSL 450 -OpName %18 "Bar" -OpMemberName %18 0 "matrix" -OpMemberName %18 1 "data" -OpName %20 "bar" -OpName %22 "foo" -OpName %24 "c" -OpName %27 "vi" -OpName %32 "foo" -OpDecorate %17 ArrayStride 4 -OpDecorate %18 Block -OpMemberDecorate %18 0 Offset 0 -OpMemberDecorate %18 0 ColMajor -OpMemberDecorate %18 0 MatrixStride 16 -OpMemberDecorate %18 1 Offset 64 -OpDecorate %19 ArrayStride 4 -OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 0 -OpDecorate %27 BuiltIn VertexIndex -OpDecorate %30 BuiltIn Position +OpName %21 "Bar" +OpMemberName %21 0 "matrix" +OpMemberName %21 1 "arr" +OpMemberName %21 2 "data" +OpName %23 "bar" +OpName %25 "foo" +OpName %27 "c" +OpName %30 "vi" +OpName %35 "foo" +OpDecorate %19 ArrayStride 8 +OpDecorate %20 ArrayStride 4 +OpDecorate %21 Block +OpMemberDecorate %21 0 Offset 0 +OpMemberDecorate %21 0 ColMajor +OpMemberDecorate %21 0 MatrixStride 16 +OpMemberDecorate %21 1 Offset 64 +OpMemberDecorate %21 2 Offset 80 +OpDecorate %22 ArrayStride 4 +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 0 +OpDecorate %30 BuiltIn VertexIndex +OpDecorate %33 BuiltIn Position %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 0.0 -%5 = OpConstant %4 1.0 -%7 = OpTypeInt 32 0 -%6 = OpConstant %7 3 -%8 = OpConstant %7 2 -%10 = OpTypeInt 32 1 -%9 = OpConstant %10 5 -%11 = OpConstant %10 3 -%12 = OpConstant %10 4 -%13 = OpConstant %7 1 -%14 = OpConstant %10 42 -%16 = OpTypeVector %4 4 -%15 = OpTypeMatrix %16 4 -%17 = OpTypeRuntimeArray %10 -%18 = OpTypeStruct %15 %17 -%19 = OpTypeArray %10 %9 -%21 = OpTypePointer StorageBuffer %18 -%20 = OpVariable %21 StorageBuffer -%23 = OpTypePointer Function %4 -%25 = OpTypePointer Function %19 -%28 = OpTypePointer Input %7 -%27 = OpVariable %28 Input -%31 = OpTypePointer Output %16 -%30 = OpVariable %31 Output -%33 = OpTypeFunction %2 -%36 = OpTypePointer StorageBuffer %15 -%37 = OpTypePointer StorageBuffer %16 -%38 = OpConstant %7 0 -%42 = OpTypePointer StorageBuffer %17 -%45 = OpTypePointer StorageBuffer %10 -%51 = OpTypePointer Function %10 -%55 = OpTypeVector %10 4 -%32 = OpFunction %2 None %33 -%26 = OpLabel -%22 = OpVariable %23 Function %3 -%24 = OpVariable %25 Function -%29 = OpLoad %7 %27 -OpBranch %34 -%34 = OpLabel -%35 = OpLoad %4 %22 -OpStore %22 %5 -%39 = OpAccessChain %37 %20 %38 %6 -%40 = OpLoad %16 %39 -%41 = OpCompositeExtract %4 %40 0 -%43 = OpArrayLength %7 %20 1 -%44 = OpISub %7 %43 %8 -%46 = OpAccessChain %45 %20 %13 %44 -%47 = OpLoad %10 %46 -%48 = OpConvertFToS %10 %41 -%49 = OpCompositeConstruct %19 %47 %48 %11 %12 %9 -OpStore %24 %49 -%50 = OpIAdd %7 %29 %13 -%52 = OpAccessChain %51 %24 %50 -OpStore %52 %14 -%53 = OpAccessChain %51 %24 %29 -%54 = OpLoad %10 %53 -%56 = OpCompositeConstruct %55 %54 %54 %54 %54 -%57 = OpConvertSToF %16 %56 -OpStore %30 %57 +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 2 +%6 = OpTypeFloat 32 +%5 = OpConstant %6 0.0 +%7 = OpConstant %6 1.0 +%9 = OpTypeInt 32 0 +%8 = OpConstant %9 3 +%10 = OpConstant %9 2 +%11 = OpConstant %4 5 +%12 = OpConstant %4 3 +%13 = OpConstant %4 4 +%14 = OpConstant %9 1 +%15 = OpConstant %4 42 +%17 = OpTypeVector %6 4 +%16 = OpTypeMatrix %17 4 +%18 = OpTypeVector %9 2 +%19 = OpTypeArray %18 %3 +%20 = OpTypeRuntimeArray %4 +%21 = OpTypeStruct %16 %19 %20 +%22 = OpTypeArray %4 %11 +%24 = OpTypePointer StorageBuffer %21 +%23 = OpVariable %24 StorageBuffer +%26 = OpTypePointer Function %6 +%28 = OpTypePointer Function %22 +%31 = OpTypePointer Input %9 +%30 = OpVariable %31 Input +%34 = OpTypePointer Output %17 +%33 = OpVariable %34 Output +%36 = OpTypeFunction %2 +%39 = OpTypePointer StorageBuffer %16 +%40 = OpConstant %9 0 +%43 = OpTypePointer StorageBuffer %19 +%46 = OpTypePointer StorageBuffer %17 +%50 = OpTypePointer StorageBuffer %20 +%53 = OpTypePointer StorageBuffer %4 +%59 = OpTypePointer Function %4 +%63 = OpTypeVector %4 4 +%35 = OpFunction %2 None %36 +%29 = OpLabel +%25 = OpVariable %26 Function %5 +%27 = OpVariable %28 Function +%32 = OpLoad %9 %30 +OpBranch %37 +%37 = OpLabel +%38 = OpLoad %6 %25 +OpStore %25 %7 +%41 = OpAccessChain %39 %23 %40 +%42 = OpLoad %16 %41 +%44 = OpAccessChain %43 %23 %14 +%45 = OpLoad %19 %44 +%47 = OpAccessChain %46 %23 %40 %8 +%48 = OpLoad %17 %47 +%49 = OpCompositeExtract %6 %48 0 +%51 = OpArrayLength %9 %23 2 +%52 = OpISub %9 %51 %10 +%54 = OpAccessChain %53 %23 %10 %52 +%55 = OpLoad %4 %54 +%56 = OpConvertFToS %4 %49 +%57 = OpCompositeConstruct %22 %55 %56 %12 %13 %11 +OpStore %27 %57 +%58 = OpIAdd %9 %32 %14 +%60 = OpAccessChain %59 %27 %58 +OpStore %60 %15 +%61 = OpAccessChain %59 %27 %32 +%62 = OpLoad %4 %61 +%64 = OpCompositeConstruct %63 %62 %62 %62 %62 +%65 = OpConvertSToF %17 %64 +%66 = OpMatrixTimesVector %17 %42 %65 +OpStore %33 %66 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 041d52839..cecc1e04d 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -1,6 +1,7 @@ [[block]] struct Bar { matrix: mat4x4; + arr: [[stride(8)]] array,2>; data: [[stride(4)]] array; }; @@ -14,11 +15,13 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let baz: f32 = foo1; foo1 = 1.0; - let _e9: vec4 = bar.matrix[3]; - let b: f32 = _e9.x; + let matrix: mat4x4 = bar.matrix; + let arr: array,2> = bar.arr; + let _e13: vec4 = bar.matrix[3]; + let b: f32 = _e13.x; let a: i32 = bar.data[(arrayLength(&bar.data) - 2u)]; c = array(a, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value: i32 = c[vi]; - return vec4(vec4(value)); + return (matrix * vec4(vec4(value))); } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 70ab53d71..03edc5f7a 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -423,7 +423,10 @@ fn convert_wgsl() { "interpolate", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), - ("access", Targets::SPIRV | Targets::METAL | Targets::WGSL), + ( + "access", + Targets::SPIRV | Targets::METAL | Targets::HLSL | Targets::WGSL, + ), ( "control-flow", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, @@ -444,7 +447,7 @@ fn convert_wgsl() { ("bounds-check-zero", Targets::SPIRV), ( "texture-arg", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ]; From 284cfcce471d30fc0b544ff2b0892bf2c743036d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Jul 2021 01:36:38 -0400 Subject: [PATCH 1150/2212] hlsl: storage writes --- README.md | 2 +- src/back/hlsl/writer.rs | 229 ++++++++++++++++++++++++++++- tests/in/access.wgsl | 9 +- tests/out/hlsl/access.hlsl | 13 ++ tests/out/hlsl/boids.hlsl | 147 ++++++++++++++++++ tests/out/hlsl/boids.hlsl.config | 3 + tests/out/hlsl/collatz.hlsl | 41 ++++++ tests/out/hlsl/collatz.hlsl.config | 3 + tests/out/msl/access.msl | 3 + tests/out/spv/access.spvasm | 188 ++++++++++++----------- tests/out/wgsl/access.wgsl | 3 + tests/snapshots.rs | 9 +- 12 files changed, 553 insertions(+), 97 deletions(-) create mode 100644 tests/out/hlsl/boids.hlsl create mode 100644 tests/out/hlsl/boids.hlsl.config create mode 100644 tests/out/hlsl/collatz.hlsl create mode 100644 tests/out/hlsl/collatz.hlsl.config diff --git a/README.md b/README.md index 044d4d99a..13bd5afec 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Back-end | Status | Feature | Notes | SPIR-V | :white_check_mark: | spv-out | | WGSL | :ok: | wgsl-out | | Metal | :white_check_mark: | msl-out | | -HLSL | :construction: | hlsl-out | Shader Model 5.0+ (DirectX 11+) | +HLSL | :ok: | hlsl-out | Shader Model 5.0+ (DirectX 11+) | GLSL | :ok: | glsl-out | | AIR | | | | DXIL/DXIR | | | | diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 483d4e689..68841b547 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -10,6 +10,7 @@ use crate::{ use std::{fmt, mem}; const LOCATION_SEMANTIC: &str = "LOC"; +const STORE_TEMP_NAME: &str = "_value"; /// Shorthand result used internally by the backend pub(super) type BackendResult = Result<(), Error>; @@ -28,6 +29,20 @@ enum SubAccess { }, } +enum StoreValue { + Expression(Handle), + TempIndex { + depth: usize, + index: u32, + ty: proc::TypeResolution, + }, + TempAccess { + depth: usize, + base: Handle, + member_index: u32, + }, +} + /// Structure contains information required for generating /// wrapped structure of all entry points arguments struct EntryPointBinding { @@ -521,11 +536,7 @@ impl<'a, W: fmt::Write> Writer<'a, W> { let size = module.constants[const_handle].to_array_length().unwrap(); write!(self.out, "{}", size)?; } - crate::ArraySize::Dynamic => { - //TODO: https://github.com/gfx-rs/naga/issues/1127 - log::warn!("Dynamically sized arrays are not properly supported yet"); - write!(self.out, "1")?; - } + crate::ArraySize::Dynamic => unreachable!(), } write!(self.out, "]")?; @@ -965,7 +976,14 @@ impl<'a, W: fmt::Write> Writer<'a, W> { .pointer_class() == Some(crate::StorageClass::Storage) { - return Err(Error::Unimplemented("Storage stores".to_string())); + let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; + self.write_storage_store( + module, + var_handle, + StoreValue::Expression(value), + func_ctx, + indent, + )?; } else if let Some((const_handle, base_ty)) = array_info { let size = module.constants[const_handle].to_array_length().unwrap(); writeln!(self.out, "{}{{", INDENT.repeat(indent))?; @@ -1813,7 +1831,7 @@ impl<'a, W: fmt::Write> Writer<'a, W> { Ok(()) } - /// Helper function to write down the load operation on a `ByteAddressBuffer`. + /// Helper function to write down the Load operation on a `ByteAddressBuffer`. fn write_storage_load( &mut self, module: &Module, @@ -1895,6 +1913,203 @@ impl<'a, W: fmt::Write> Writer<'a, W> { Ok(()) } + fn write_store_value( + &mut self, + module: &Module, + value: &StoreValue, + func_ctx: &back::FunctionCtx, + ) -> BackendResult { + match *value { + StoreValue::Expression(expr) => self.write_expr(module, expr, &func_ctx)?, + StoreValue::TempIndex { + depth, + index, + ty: _, + } => write!(self.out, "{}{}[{}]", STORE_TEMP_NAME, depth, index)?, + StoreValue::TempAccess { + depth, + base, + member_index, + } => { + let name = &self.names[&NameKey::StructMember(base, member_index)]; + write!(self.out, "{}{}.{}", STORE_TEMP_NAME, depth, name)? + } + } + Ok(()) + } + + /// Helper function to write down the Store operation on a `ByteAddressBuffer`. + fn write_storage_store( + &mut self, + module: &Module, + var_handle: Handle, + value: StoreValue, + func_ctx: &back::FunctionCtx<'_>, + indent: usize, + ) -> BackendResult { + let temp_resolution; + let ty_resolution = match value { + StoreValue::Expression(expr) => &func_ctx.info[expr].ty, + StoreValue::TempIndex { + depth: _, + index: _, + ref ty, + } => ty, + StoreValue::TempAccess { + depth: _, + base, + member_index, + } => { + let ty_handle = match module.types[base].inner { + TypeInner::Struct { ref members, .. } => members[member_index as usize].ty, + _ => unreachable!(), + }; + temp_resolution = proc::TypeResolution::Handle(ty_handle); + &temp_resolution + } + }; + match *ty_resolution.inner_with(&module.types) { + TypeInner::Scalar { .. } => { + // working around the borrow checker in `self.write_expr` + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + write!( + self.out, + "{}{}.Store(", + back::INDENT.repeat(indent), + var_name + )?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", asuint(")?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, "));")?; + self.temp_access_chain = chain; + } + TypeInner::Vector { size, .. } => { + // working around the borrow checker in `self.write_expr` + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + write!( + self.out, + "{}{}.Store{}(", + back::INDENT.repeat(indent), + var_name, + size as u8 + )?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", asuint(")?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, "));")?; + self.temp_access_chain = chain; + } + TypeInner::Matrix { + columns, + rows, + width, + } => { + // first, assign the value to a temporary + writeln!(self.out, "{}{{", back::INDENT.repeat(indent))?; + let depth = indent + 1; + write!( + self.out, + "{}{}{}x{} {}{} = ", + back::INDENT.repeat(indent + 1), + crate::ScalarKind::Float.to_hlsl_str(width)?, + columns as u8, + rows as u8, + STORE_TEMP_NAME, + depth, + )?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, ";")?; + // then iterate the stores + let row_stride = width as u32 * rows as u32; + for i in 0..columns as u32 { + self.temp_access_chain + .push(SubAccess::Offset(i * row_stride)); + let ty_inner = TypeInner::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }; + let sv = StoreValue::TempIndex { + depth, + index: i, + ty: proc::TypeResolution::Value(ty_inner), + }; + self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; + self.temp_access_chain.pop(); + } + // done + writeln!(self.out, "{}}}", back::INDENT.repeat(indent))?; + } + TypeInner::Array { + base, + size: crate::ArraySize::Constant(const_handle), + .. + } => { + // first, assign the value to a temporary + writeln!(self.out, "{}{{", back::INDENT.repeat(indent))?; + write!(self.out, "{}", back::INDENT.repeat(indent + 1))?; + self.write_value_type(module, &module.types[base].inner)?; + let depth = indent + 1; + write!(self.out, " {}{}", STORE_TEMP_NAME, depth)?; + self.write_array_size(module, crate::ArraySize::Constant(const_handle))?; + write!(self.out, " = ")?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, ";")?; + // then iterate the stores + let count = module.constants[const_handle].to_array_length().unwrap(); + let stride = module.types[base].inner.span(&module.constants); + for i in 0..count { + self.temp_access_chain.push(SubAccess::Offset(i * stride)); + let sv = StoreValue::TempIndex { + depth, + index: i, + ty: proc::TypeResolution::Handle(base), + }; + self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; + self.temp_access_chain.pop(); + } + // done + writeln!(self.out, "{}}}", back::INDENT.repeat(indent))?; + } + TypeInner::Struct { ref members, .. } => { + // first, assign the value to a temporary + writeln!(self.out, "{}{{", back::INDENT.repeat(indent))?; + let depth = indent + 1; + let struct_ty = ty_resolution.handle().unwrap(); + let struct_name = &self.names[&NameKey::Type(struct_ty)]; + write!( + self.out, + "{}{} {}{} = ", + back::INDENT.repeat(indent + 1), + struct_name, + STORE_TEMP_NAME, + depth + )?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, ";")?; + // then iterate the stores + for (i, member) in members.iter().enumerate() { + self.temp_access_chain + .push(SubAccess::Offset(member.offset)); + let sv = StoreValue::TempAccess { + depth, + base: struct_ty, + member_index: i as u32, + }; + self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; + self.temp_access_chain.pop(); + } + // done + writeln!(self.out, "{}}}", back::INDENT.repeat(indent))?; + } + _ => unreachable!(), + } + Ok(()) + } + fn fill_access_chain( &mut self, module: &Module, diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index f97d504de..e6f07a263 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -17,14 +17,19 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let baz: f32 = foo; foo = 1.0; + // test storage loads let matrix = bar.matrix; let arr = bar.arr; - let index = 3u; let b = bar.matrix[index].x; - let a = bar.data[arrayLength(&bar.data) - 2u]; + // test storage stores + bar.matrix[1].z = 1.0; + bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + bar.arr = array, 2>(vec2(0u), vec2(1u)); + + // test array indexing var c = array(a, i32(b), 3, 4, 5); c[vi + 1u] = 42; let value = c[vi]; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 8d299c9a8..0946fb8bf 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -24,6 +24,19 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position float4 _expr13 = asfloat(bar.Load4(12+0)); float b = _expr13.x; int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 80) / 4) - 2u)*4+8)); + bar.Store(8+4+0, asuint(1.0)); + { + float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx)); + bar.Store4(0+0, asuint(_value2[0])); + bar.Store4(0+16, asuint(_value2[1])); + bar.Store4(0+32, asuint(_value2[2])); + bar.Store4(0+48, asuint(_value2[3])); + } + { + uint2 _value2[2] = { uint2(0u.xx), uint2(1u.xx) }; + bar.Store2(4+0, asuint(_value2[0])); + bar.Store2(4+8, asuint(_value2[1])); + } { int _result[5]={ a, int(b), 3, 4, 5 }; for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl new file mode 100644 index 000000000..c3e742ca7 --- /dev/null +++ b/tests/out/hlsl/boids.hlsl @@ -0,0 +1,147 @@ +static const uint NUM_PARTICLES = 1500; + +struct Particle { + float2 pos; + float2 vel; +}; + +struct SimParams { + float deltaT; + float rule1Distance; + float rule2Distance; + float rule3Distance; + float rule1Scale; + float rule2Scale; + float rule3Scale; +}; + +cbuffer params : register(b0) { SimParams params; } +ByteAddressBuffer particlesSrc : register(t1); +RWByteAddressBuffer particlesDst : register(u2); + +struct ComputeInput_main { + uint3 global_invocation_id1 : SV_DispatchThreadID; +}; + +[numthreads(64, 1, 1)] +void main(ComputeInput_main computeinput_main) +{ + float2 vPos = (float2)0; + float2 vVel = (float2)0; + float2 cMass = (float2)0; + float2 cVel = (float2)0; + float2 colVel = (float2)0; + int cMassCount = 0; + int cVelCount = 0; + float2 pos = (float2)0; + float2 vel = (float2)0; + uint i = 0u; + + uint index = computeinput_main.global_invocation_id1.x; + if ((index >= NUM_PARTICLES)) { + return; + } + float2 _expr10 = asfloat(particlesSrc.Load2(0+index*4+0)); + vPos = _expr10; + float2 _expr15 = asfloat(particlesSrc.Load2(4+index*4+0)); + vVel = _expr15; + cMass = float2(0.0, 0.0); + cVel = float2(0.0, 0.0); + colVel = float2(0.0, 0.0); + while(true) { + uint _expr37 = i; + if ((_expr37 >= NUM_PARTICLES)) { + break; + } + uint _expr39 = i; + if ((_expr39 == index)) { + continue; + } + uint _expr42 = i; + float2 _expr45 = asfloat(particlesSrc.Load2(0+_expr42*4+0)); + pos = _expr45; + uint _expr47 = i; + float2 _expr50 = asfloat(particlesSrc.Load2(4+_expr47*4+0)); + vel = _expr50; + float2 _expr51 = pos; + float2 _expr52 = vPos; + float _expr55 = params.rule1Distance; + if ((distance(_expr51, _expr52) < _expr55)) { + float2 _expr57 = cMass; + float2 _expr58 = pos; + cMass = (_expr57 + _expr58); + int _expr60 = cMassCount; + cMassCount = (_expr60 + 1); + } + float2 _expr63 = pos; + float2 _expr64 = vPos; + float _expr67 = params.rule2Distance; + if ((distance(_expr63, _expr64) < _expr67)) { + float2 _expr69 = colVel; + float2 _expr70 = pos; + float2 _expr71 = vPos; + colVel = (_expr69 - (_expr70 - _expr71)); + } + float2 _expr74 = pos; + float2 _expr75 = vPos; + float _expr78 = params.rule3Distance; + if ((distance(_expr74, _expr75) < _expr78)) { + float2 _expr80 = cVel; + float2 _expr81 = vel; + cVel = (_expr80 + _expr81); + int _expr83 = cVelCount; + cVelCount = (_expr83 + 1); + } + uint _expr86 = i; + i = (_expr86 + 1u); + } + int _expr89 = cMassCount; + if ((_expr89 > 0)) { + float2 _expr92 = cMass; + int _expr93 = cMassCount; + float2 _expr97 = vPos; + cMass = ((_expr92 / float2(float(_expr93).xx)) - _expr97); + } + int _expr99 = cVelCount; + if ((_expr99 > 0)) { + float2 _expr102 = cVel; + int _expr103 = cVelCount; + cVel = (_expr102 / float2(float(_expr103).xx)); + } + float2 _expr107 = vVel; + float2 _expr108 = cMass; + float _expr110 = params.rule1Scale; + float2 _expr113 = colVel; + float _expr115 = params.rule2Scale; + float2 _expr118 = cVel; + float _expr120 = params.rule3Scale; + vVel = (((_expr107 + (_expr108 * _expr110)) + (_expr113 * _expr115)) + (_expr118 * _expr120)); + float2 _expr123 = vVel; + float2 _expr125 = vVel; + vVel = (normalize(_expr123) * clamp(length(_expr125), 0.0, 0.1)); + float2 _expr131 = vPos; + float2 _expr132 = vVel; + float _expr134 = params.deltaT; + vPos = (_expr131 + (_expr132 * _expr134)); + float2 _expr137 = vPos; + if ((_expr137.x < -1.0)) { + vPos.x = 1.0; + } + float2 _expr143 = vPos; + if ((_expr143.x > 1.0)) { + vPos.x = -1.0; + } + float2 _expr149 = vPos; + if ((_expr149.y < -1.0)) { + vPos.y = 1.0; + } + float2 _expr155 = vPos; + if ((_expr155.y > 1.0)) { + vPos.y = -1.0; + } + float2 _expr164 = vPos; + particlesDst.Store2(0+index*4+0, asuint(_expr164)); + float2 _expr168 = vVel; + particlesDst.Store2(4+index*4+0, asuint(_expr168)); + return; +} diff --git a/tests/out/hlsl/boids.hlsl.config b/tests/out/hlsl/boids.hlsl.config new file mode 100644 index 000000000..c0d04b8f2 --- /dev/null +++ b/tests/out/hlsl/boids.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(main:cs_5_0 ) diff --git a/tests/out/hlsl/collatz.hlsl b/tests/out/hlsl/collatz.hlsl new file mode 100644 index 000000000..3f85ea87e --- /dev/null +++ b/tests/out/hlsl/collatz.hlsl @@ -0,0 +1,41 @@ + +RWByteAddressBuffer v_indices : register(u0); + +struct ComputeInput_main { + uint3 global_id1 : SV_DispatchThreadID; +}; + +uint collatz_iterations(uint n_base) +{ + uint n = (uint)0; + uint i = 0u; + + n = n_base; + while(true) { + uint _expr5 = n; + if ((_expr5 <= 1u)) { + break; + } + uint _expr8 = n; + if (((_expr8 % 2u) == 0u)) { + uint _expr13 = n; + n = (_expr13 / 2u); + } else { + uint _expr17 = n; + n = ((3u * _expr17) + 1u); + } + uint _expr21 = i; + i = (_expr21 + 1u); + } + uint _expr24 = i; + return _expr24; +} + +[numthreads(1, 1, 1)] +void main(ComputeInput_main computeinput_main) +{ + uint _expr8 = asuint(v_indices.Load(computeinput_main.global_id1.x*4+0)); + const uint _e9 = collatz_iterations(_expr8); + v_indices.Store(computeinput_main.global_id1.x*4+0, asuint(_e9)); + return; +} diff --git a/tests/out/hlsl/collatz.hlsl.config b/tests/out/hlsl/collatz.hlsl.config new file mode 100644 index 000000000..c0d04b8f2 --- /dev/null +++ b/tests/out/hlsl/collatz.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(main:cs_5_0 ) diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index b04acf40b..16bcedf55 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -38,6 +38,9 @@ vertex fooOutput foo( metal::float4 _e13 = bar.matrix[3]; float b = _e13.x; int a = bar.data[(1 + (_buffer_sizes.size0 - 80 - 4) / 4) - 2u]; + bar.matrix[1].z = 1.0; + bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); + for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type2 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; for(int _i=0; _i<5; ++_i) c.inner[_i] = type8 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 32c4fc27d..19727e05f 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,35 +1,35 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 67 +; Bound: 82 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %35 "foo" %30 %33 +OpEntryPoint Vertex %39 "foo" %34 %37 OpSource GLSL 450 -OpName %21 "Bar" -OpMemberName %21 0 "matrix" -OpMemberName %21 1 "arr" -OpMemberName %21 2 "data" -OpName %23 "bar" -OpName %25 "foo" -OpName %27 "c" -OpName %30 "vi" -OpName %35 "foo" -OpDecorate %19 ArrayStride 8 -OpDecorate %20 ArrayStride 4 -OpDecorate %21 Block -OpMemberDecorate %21 0 Offset 0 -OpMemberDecorate %21 0 ColMajor -OpMemberDecorate %21 0 MatrixStride 16 -OpMemberDecorate %21 1 Offset 64 -OpMemberDecorate %21 2 Offset 80 -OpDecorate %22 ArrayStride 4 -OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 0 -OpDecorate %30 BuiltIn VertexIndex -OpDecorate %33 BuiltIn Position +OpName %25 "Bar" +OpMemberName %25 0 "matrix" +OpMemberName %25 1 "arr" +OpMemberName %25 2 "data" +OpName %27 "bar" +OpName %29 "foo" +OpName %31 "c" +OpName %34 "vi" +OpName %39 "foo" +OpDecorate %23 ArrayStride 8 +OpDecorate %24 ArrayStride 4 +OpDecorate %25 Block +OpMemberDecorate %25 0 Offset 0 +OpMemberDecorate %25 0 ColMajor +OpMemberDecorate %25 0 MatrixStride 16 +OpMemberDecorate %25 1 Offset 64 +OpMemberDecorate %25 2 Offset 80 +OpDecorate %26 ArrayStride 4 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 0 +OpDecorate %34 BuiltIn VertexIndex +OpDecorate %37 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -39,66 +39,84 @@ OpDecorate %33 BuiltIn Position %9 = OpTypeInt 32 0 %8 = OpConstant %9 3 %10 = OpConstant %9 2 -%11 = OpConstant %4 5 -%12 = OpConstant %4 3 -%13 = OpConstant %4 4 -%14 = OpConstant %9 1 -%15 = OpConstant %4 42 -%17 = OpTypeVector %6 4 -%16 = OpTypeMatrix %17 4 -%18 = OpTypeVector %9 2 -%19 = OpTypeArray %18 %3 -%20 = OpTypeRuntimeArray %4 -%21 = OpTypeStruct %16 %19 %20 -%22 = OpTypeArray %4 %11 -%24 = OpTypePointer StorageBuffer %21 -%23 = OpVariable %24 StorageBuffer -%26 = OpTypePointer Function %6 -%28 = OpTypePointer Function %22 -%31 = OpTypePointer Input %9 -%30 = OpVariable %31 Input -%34 = OpTypePointer Output %17 -%33 = OpVariable %34 Output -%36 = OpTypeFunction %2 -%39 = OpTypePointer StorageBuffer %16 -%40 = OpConstant %9 0 -%43 = OpTypePointer StorageBuffer %19 -%46 = OpTypePointer StorageBuffer %17 -%50 = OpTypePointer StorageBuffer %20 -%53 = OpTypePointer StorageBuffer %4 -%59 = OpTypePointer Function %4 -%63 = OpTypeVector %4 4 -%35 = OpFunction %2 None %36 -%29 = OpLabel -%25 = OpVariable %26 Function %5 -%27 = OpVariable %28 Function -%32 = OpLoad %9 %30 -OpBranch %37 -%37 = OpLabel -%38 = OpLoad %6 %25 -OpStore %25 %7 -%41 = OpAccessChain %39 %23 %40 -%42 = OpLoad %16 %41 -%44 = OpAccessChain %43 %23 %14 -%45 = OpLoad %19 %44 -%47 = OpAccessChain %46 %23 %40 %8 -%48 = OpLoad %17 %47 -%49 = OpCompositeExtract %6 %48 0 -%51 = OpArrayLength %9 %23 2 -%52 = OpISub %9 %51 %10 -%54 = OpAccessChain %53 %23 %10 %52 -%55 = OpLoad %4 %54 -%56 = OpConvertFToS %4 %49 -%57 = OpCompositeConstruct %22 %55 %56 %12 %13 %11 -OpStore %27 %57 -%58 = OpIAdd %9 %32 %14 -%60 = OpAccessChain %59 %27 %58 -OpStore %60 %15 -%61 = OpAccessChain %59 %27 %32 -%62 = OpLoad %4 %61 -%64 = OpCompositeConstruct %63 %62 %62 %62 %62 -%65 = OpConvertSToF %17 %64 -%66 = OpMatrixTimesVector %17 %42 %65 -OpStore %33 %66 +%11 = OpConstant %4 1 +%12 = OpConstant %6 2.0 +%13 = OpConstant %6 3.0 +%14 = OpConstant %9 0 +%15 = OpConstant %9 1 +%16 = OpConstant %4 5 +%17 = OpConstant %4 3 +%18 = OpConstant %4 4 +%19 = OpConstant %4 42 +%21 = OpTypeVector %6 4 +%20 = OpTypeMatrix %21 4 +%22 = OpTypeVector %9 2 +%23 = OpTypeArray %22 %3 +%24 = OpTypeRuntimeArray %4 +%25 = OpTypeStruct %20 %23 %24 +%26 = OpTypeArray %4 %16 +%28 = OpTypePointer StorageBuffer %25 +%27 = OpVariable %28 StorageBuffer +%30 = OpTypePointer Function %6 +%32 = OpTypePointer Function %26 +%35 = OpTypePointer Input %9 +%34 = OpVariable %35 Input +%38 = OpTypePointer Output %21 +%37 = OpVariable %38 Output +%40 = OpTypeFunction %2 +%43 = OpTypePointer StorageBuffer %20 +%46 = OpTypePointer StorageBuffer %23 +%49 = OpTypePointer StorageBuffer %21 +%53 = OpTypePointer StorageBuffer %24 +%56 = OpTypePointer StorageBuffer %4 +%59 = OpTypePointer StorageBuffer %6 +%74 = OpTypePointer Function %4 +%78 = OpTypeVector %4 4 +%39 = OpFunction %2 None %40 +%33 = OpLabel +%29 = OpVariable %30 Function %5 +%31 = OpVariable %32 Function +%36 = OpLoad %9 %34 +OpBranch %41 +%41 = OpLabel +%42 = OpLoad %6 %29 +OpStore %29 %7 +%44 = OpAccessChain %43 %27 %14 +%45 = OpLoad %20 %44 +%47 = OpAccessChain %46 %27 %15 +%48 = OpLoad %23 %47 +%50 = OpAccessChain %49 %27 %14 %8 +%51 = OpLoad %21 %50 +%52 = OpCompositeExtract %6 %51 0 +%54 = OpArrayLength %9 %27 2 +%55 = OpISub %9 %54 %10 +%57 = OpAccessChain %56 %27 %10 %55 +%58 = OpLoad %4 %57 +%60 = OpAccessChain %59 %27 %14 %15 %10 +OpStore %60 %7 +%61 = OpCompositeConstruct %21 %5 %5 %5 %5 +%62 = OpCompositeConstruct %21 %7 %7 %7 %7 +%63 = OpCompositeConstruct %21 %12 %12 %12 %12 +%64 = OpCompositeConstruct %21 %13 %13 %13 %13 +%65 = OpCompositeConstruct %20 %61 %62 %63 %64 +%66 = OpAccessChain %43 %27 %14 +OpStore %66 %65 +%67 = OpCompositeConstruct %22 %14 %14 +%68 = OpCompositeConstruct %22 %15 %15 +%69 = OpCompositeConstruct %23 %67 %68 +%70 = OpAccessChain %46 %27 %15 +OpStore %70 %69 +%71 = OpConvertFToS %4 %52 +%72 = OpCompositeConstruct %26 %58 %71 %17 %18 %16 +OpStore %31 %72 +%73 = OpIAdd %9 %36 %15 +%75 = OpAccessChain %74 %31 %73 +OpStore %75 %19 +%76 = OpAccessChain %74 %31 %36 +%77 = OpLoad %4 %76 +%79 = OpCompositeConstruct %78 %77 %77 %77 %77 +%80 = OpConvertSToF %21 %79 +%81 = OpMatrixTimesVector %21 %45 %80 +OpStore %37 %81 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index cecc1e04d..05c398dfe 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -20,6 +20,9 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let _e13: vec4 = bar.matrix[3]; let b: f32 = _e13.x; let a: i32 = bar.data[(arrayLength(&bar.data) - 2u)]; + bar.matrix[1][2] = 1.0; + bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + bar.arr = array,2>(vec2(0u), vec2(1u)); c = array(a, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value: i32 = c[vi]; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 03edc5f7a..1e6b6b534 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -396,7 +396,7 @@ fn convert_wgsl() { ), ( "boids", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "skybox", @@ -404,7 +404,12 @@ fn convert_wgsl() { ), ( "collatz", - Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS | Targets::WGSL, + Targets::SPIRV + | Targets::METAL + | Targets::IR + | Targets::ANALYSIS + | Targets::HLSL + | Targets::WGSL, ), ( "shadow", From e7502d0a9be0313227ebdebb462abf2764553b23 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 26 Jul 2021 00:24:05 -0400 Subject: [PATCH 1151/2212] hlsl: factor storage logic into a separate module --- src/back/hlsl/help.rs | 2 +- src/back/hlsl/mod.rs | 21 +- src/back/hlsl/storage.rs | 395 +++++++++++++++++++++++++++++++++++ src/back/hlsl/writer.rs | 433 ++------------------------------------- 4 files changed, 433 insertions(+), 418 deletions(-) create mode 100644 src/back/hlsl/storage.rs diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index aef71ddb2..710231901 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -21,7 +21,7 @@ // int dim_1d = NagaDimensions1D(image_1d); // ``` -use super::{super::FunctionCtx, writer::BackendResult}; +use super::{super::FunctionCtx, BackendResult}; use crate::arena::Handle; use std::fmt::Write; diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 1b5e70b92..72ec44e3a 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -9,12 +9,13 @@ mod conv; mod help; mod keywords; +mod storage; mod writer; use std::fmt::Error as FmtError; use thiserror::Error; -pub use writer::Writer; +use crate::proc; #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -69,6 +70,9 @@ impl crate::ImageDimension { } } +/// Shorthand result used internally by the backend +type BackendResult = Result<(), Error>; + #[derive(Clone, Debug, PartialEq, thiserror::Error)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] @@ -138,3 +142,18 @@ pub enum Error { #[error("{0}")] Custom(String), } + +pub struct Writer<'a, W> { + out: W, + names: crate::FastHashMap, + namer: proc::Namer, + /// HLSL backend options + options: &'a Options, + /// Information about entry point arguments wrapped into structure + ep_inputs: Vec>, + /// Set of expressions that have associated temporary variables + named_expressions: crate::NamedExpressions, + wrapped_array_lengths: crate::FastHashSet, + wrapped_image_queries: crate::FastHashSet, + temp_access_chain: Vec, +} diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs new file mode 100644 index 000000000..033bfcf16 --- /dev/null +++ b/src/back/hlsl/storage.rs @@ -0,0 +1,395 @@ +use super::{ + super::{FunctionCtx, INDENT}, + BackendResult, Error, +}; +use crate::{ + proc::{NameKey, TypeResolution}, + Handle, +}; + +use std::{fmt, mem}; + +const STORE_TEMP_NAME: &str = "_value"; + +pub(super) enum SubAccess { + Offset(u32), + Index { + value: Handle, + stride: u32, + }, +} + +pub(super) enum StoreValue { + Expression(Handle), + TempIndex { + depth: usize, + index: u32, + ty: TypeResolution, + }, + TempAccess { + depth: usize, + base: Handle, + member_index: u32, + }, +} + +impl super::Writer<'_, W> { + fn write_storage_address( + &mut self, + module: &crate::Module, + chain: &[SubAccess], + func_ctx: &FunctionCtx, + ) -> BackendResult { + for (i, access) in chain.iter().enumerate() { + if i != 0 { + write!(self.out, "+")?; + } + match *access { + SubAccess::Offset(offset) => { + write!(self.out, "{}", offset)?; + } + SubAccess::Index { value, stride } => { + self.write_expr(module, value, func_ctx)?; + write!(self.out, "*{}", stride)?; + } + } + } + Ok(()) + } + + fn write_storage_load_sequence>( + &mut self, + module: &crate::Module, + var_handle: Handle, + sequence: I, + func_ctx: &FunctionCtx, + ) -> BackendResult { + for (i, (ty_resolution, offset)) in sequence.enumerate() { + // add the index temporarily + self.temp_access_chain.push(SubAccess::Offset(offset)); + if i != 0 { + write!(self.out, ", ")?; + }; + self.write_storage_load(module, var_handle, ty_resolution, func_ctx)?; + self.temp_access_chain.pop(); + } + Ok(()) + } + + /// Helper function to write down the Load operation on a `ByteAddressBuffer`. + pub(super) fn write_storage_load( + &mut self, + module: &crate::Module, + var_handle: Handle, + result_ty: TypeResolution, + func_ctx: &FunctionCtx, + ) -> BackendResult { + match *result_ty.inner_with(&module.types) { + crate::TypeInner::Scalar { kind, width: _ } => { + // working around the borrow checker in `self.write_expr` + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + let cast = kind.to_hlsl_cast(); + write!(self.out, "{}({}.Load(", cast, var_name)?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, "))")?; + self.temp_access_chain = chain; + } + crate::TypeInner::Vector { + size, + kind, + width: _, + } => { + // working around the borrow checker in `self.write_expr` + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + let cast = kind.to_hlsl_cast(); + write!(self.out, "{}({}.Load{}(", cast, var_name, size as u8)?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, "))")?; + self.temp_access_chain = chain; + } + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + write!( + self.out, + "{}{}x{}(", + crate::ScalarKind::Float.to_hlsl_str(width)?, + columns as u8, + rows as u8, + )?; + let row_stride = width as u32 * rows as u32; + let iter = (0..columns as u32).map(|i| { + let ty_inner = crate::TypeInner::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }; + (TypeResolution::Value(ty_inner), i * row_stride) + }); + self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; + write!(self.out, ")")?; + } + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(const_handle), + .. + } => { + write!(self.out, "{{")?; + let count = module.constants[const_handle].to_array_length().unwrap(); + let stride = module.types[base].inner.span(&module.constants); + let iter = (0..count).map(|i| (TypeResolution::Handle(base), stride * i)); + self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; + write!(self.out, "}}")?; + } + crate::TypeInner::Struct { ref members, .. } => { + write!(self.out, "{{")?; + let iter = members + .iter() + .map(|m| (TypeResolution::Handle(m.ty), m.offset)); + self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; + write!(self.out, "}}")?; + } + _ => unreachable!(), + } + Ok(()) + } + + fn write_store_value( + &mut self, + module: &crate::Module, + value: &StoreValue, + func_ctx: &FunctionCtx, + ) -> BackendResult { + match *value { + StoreValue::Expression(expr) => self.write_expr(module, expr, &func_ctx)?, + StoreValue::TempIndex { + depth, + index, + ty: _, + } => write!(self.out, "{}{}[{}]", STORE_TEMP_NAME, depth, index)?, + StoreValue::TempAccess { + depth, + base, + member_index, + } => { + let name = &self.names[&NameKey::StructMember(base, member_index)]; + write!(self.out, "{}{}.{}", STORE_TEMP_NAME, depth, name)? + } + } + Ok(()) + } + + /// Helper function to write down the Store operation on a `ByteAddressBuffer`. + pub(super) fn write_storage_store( + &mut self, + module: &crate::Module, + var_handle: Handle, + value: StoreValue, + func_ctx: &FunctionCtx, + indent: usize, + ) -> BackendResult { + let temp_resolution; + let ty_resolution = match value { + StoreValue::Expression(expr) => &func_ctx.info[expr].ty, + StoreValue::TempIndex { + depth: _, + index: _, + ref ty, + } => ty, + StoreValue::TempAccess { + depth: _, + base, + member_index, + } => { + let ty_handle = match module.types[base].inner { + crate::TypeInner::Struct { ref members, .. } => { + members[member_index as usize].ty + } + _ => unreachable!(), + }; + temp_resolution = TypeResolution::Handle(ty_handle); + &temp_resolution + } + }; + match *ty_resolution.inner_with(&module.types) { + crate::TypeInner::Scalar { .. } => { + // working around the borrow checker in `self.write_expr` + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + write!(self.out, "{}{}.Store(", INDENT.repeat(indent), var_name)?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", asuint(")?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, "));")?; + self.temp_access_chain = chain; + } + crate::TypeInner::Vector { size, .. } => { + // working around the borrow checker in `self.write_expr` + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + write!( + self.out, + "{}{}.Store{}(", + INDENT.repeat(indent), + var_name, + size as u8 + )?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", asuint(")?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, "));")?; + self.temp_access_chain = chain; + } + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + // first, assign the value to a temporary + writeln!(self.out, "{}{{", INDENT.repeat(indent))?; + let depth = indent + 1; + write!( + self.out, + "{}{}{}x{} {}{} = ", + INDENT.repeat(indent + 1), + crate::ScalarKind::Float.to_hlsl_str(width)?, + columns as u8, + rows as u8, + STORE_TEMP_NAME, + depth, + )?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, ";")?; + // then iterate the stores + let row_stride = width as u32 * rows as u32; + for i in 0..columns as u32 { + self.temp_access_chain + .push(SubAccess::Offset(i * row_stride)); + let ty_inner = crate::TypeInner::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }; + let sv = StoreValue::TempIndex { + depth, + index: i, + ty: TypeResolution::Value(ty_inner), + }; + self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; + self.temp_access_chain.pop(); + } + // done + writeln!(self.out, "{}}}", INDENT.repeat(indent))?; + } + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(const_handle), + .. + } => { + // first, assign the value to a temporary + writeln!(self.out, "{}{{", INDENT.repeat(indent))?; + write!(self.out, "{}", INDENT.repeat(indent + 1))?; + self.write_value_type(module, &module.types[base].inner)?; + let depth = indent + 1; + write!(self.out, " {}{}", STORE_TEMP_NAME, depth)?; + self.write_array_size(module, crate::ArraySize::Constant(const_handle))?; + write!(self.out, " = ")?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, ";")?; + // then iterate the stores + let count = module.constants[const_handle].to_array_length().unwrap(); + let stride = module.types[base].inner.span(&module.constants); + for i in 0..count { + self.temp_access_chain.push(SubAccess::Offset(i * stride)); + let sv = StoreValue::TempIndex { + depth, + index: i, + ty: TypeResolution::Handle(base), + }; + self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; + self.temp_access_chain.pop(); + } + // done + writeln!(self.out, "{}}}", INDENT.repeat(indent))?; + } + crate::TypeInner::Struct { ref members, .. } => { + // first, assign the value to a temporary + writeln!(self.out, "{}{{", INDENT.repeat(indent))?; + let depth = indent + 1; + let struct_ty = ty_resolution.handle().unwrap(); + let struct_name = &self.names[&NameKey::Type(struct_ty)]; + write!( + self.out, + "{}{} {}{} = ", + INDENT.repeat(indent + 1), + struct_name, + STORE_TEMP_NAME, + depth + )?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, ";")?; + // then iterate the stores + for (i, member) in members.iter().enumerate() { + self.temp_access_chain + .push(SubAccess::Offset(member.offset)); + let sv = StoreValue::TempAccess { + depth, + base: struct_ty, + member_index: i as u32, + }; + self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; + self.temp_access_chain.pop(); + } + // done + writeln!(self.out, "{}}}", INDENT.repeat(indent))?; + } + _ => unreachable!(), + } + Ok(()) + } + + pub(super) fn fill_access_chain( + &mut self, + module: &crate::Module, + mut cur_expr: Handle, + func_ctx: &FunctionCtx, + ) -> Result, Error> { + self.temp_access_chain.clear(); + loop { + let stride = func_ctx.info[cur_expr] + .ty + .inner_with(&module.types) + .span(&module.constants); + let (next_expr, sub) = match func_ctx.expressions[cur_expr] { + crate::Expression::GlobalVariable(handle) => return Ok(handle), + crate::Expression::Access { base, index } => ( + base, + SubAccess::Index { + value: index, + stride, + }, + ), + crate::Expression::AccessIndex { base, index } => { + match *func_ctx.info[base].ty.inner_with(&module.types) { + crate::TypeInner::Struct { ref members, .. } => { + (base, SubAccess::Offset(members[index as usize].offset)) + } + _ => (base, SubAccess::Offset(index * stride)), + } + } + ref other => { + return Err(Error::Unimplemented(format!( + "Pointer access of {:?}", + other + ))) + } + }; + self.temp_access_chain.push(sub); + cur_expr = next_expr; + } + } +} diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 68841b547..b331d8c27 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,51 +1,20 @@ use super::{ help::{MipLevelCoordinate, WrappedArrayLength, WrappedImageQuery}, - Error, Options, + storage::StoreValue, + BackendResult, Error, Options, }; use crate::{ back, proc::{self, NameKey}, valid, Handle, Module, ShaderStage, TypeInner, }; -use std::{fmt, mem}; +use std::fmt; const LOCATION_SEMANTIC: &str = "LOC"; -const STORE_TEMP_NAME: &str = "_value"; - -/// Shorthand result used internally by the backend -pub(super) type BackendResult = Result<(), Error>; - -#[derive(Copy, Clone, PartialEq)] -enum Io { - Input, - Output, -} - -enum SubAccess { - Offset(u32), - Index { - value: Handle, - stride: u32, - }, -} - -enum StoreValue { - Expression(Handle), - TempIndex { - depth: usize, - index: u32, - ty: proc::TypeResolution, - }, - TempAccess { - depth: usize, - base: Handle, - member_index: u32, - }, -} /// Structure contains information required for generating /// wrapped structure of all entry points arguments -struct EntryPointBinding { +pub(super) struct EntryPointBinding { /// Generated structure name name: String, /// Members of generated structure @@ -53,27 +22,18 @@ struct EntryPointBinding { } struct EpStructMember { - pub name: String, - pub ty: Handle, - pub binding: Option, + name: String, + ty: Handle, + binding: Option, } -pub struct Writer<'a, W> { - pub(super) out: W, - names: crate::FastHashMap, - namer: proc::Namer, - /// HLSL backend options - options: &'a Options, - /// Information about entry point arguments wrapped into structure - ep_inputs: Vec>, - /// Set of expressions that have associated temporary variables - named_expressions: crate::NamedExpressions, - pub(super) wrapped_array_lengths: crate::FastHashSet, - pub(super) wrapped_image_queries: crate::FastHashSet, - temp_access_chain: Vec, +#[derive(Copy, Clone, PartialEq)] +enum Io { + Input, + Output, } -impl<'a, W: fmt::Write> Writer<'a, W> { +impl<'a, W: fmt::Write> super::Writer<'a, W> { pub fn new(out: W, options: &'a Options) -> Self { Self { out, @@ -524,8 +484,11 @@ impl<'a, W: fmt::Write> Writer<'a, W> { Ok(()) } - // copy-paste from glsl-out - fn write_array_size(&mut self, module: &Module, size: crate::ArraySize) -> BackendResult { + pub(super) fn write_array_size( + &mut self, + module: &Module, + size: crate::ArraySize, + ) -> BackendResult { write!(self.out, "[")?; // Write the array size @@ -1788,366 +1751,4 @@ impl<'a, W: fmt::Write> Writer<'a, W> { } Ok(()) } - - fn write_storage_address( - &mut self, - module: &Module, - chain: &[SubAccess], - func_ctx: &back::FunctionCtx<'_>, - ) -> BackendResult { - for (i, access) in chain.iter().enumerate() { - if i != 0 { - write!(self.out, "+")?; - } - match *access { - SubAccess::Offset(offset) => { - write!(self.out, "{}", offset)?; - } - SubAccess::Index { value, stride } => { - self.write_expr(module, value, func_ctx)?; - write!(self.out, "*{}", stride)?; - } - } - } - Ok(()) - } - - fn write_storage_load_sequence>( - &mut self, - module: &Module, - var_handle: Handle, - sequence: I, - func_ctx: &back::FunctionCtx<'_>, - ) -> BackendResult { - for (i, (ty_resolution, offset)) in sequence.enumerate() { - // add the index temporarily - self.temp_access_chain.push(SubAccess::Offset(offset)); - if i != 0 { - write!(self.out, ", ")?; - }; - self.write_storage_load(module, var_handle, ty_resolution, func_ctx)?; - self.temp_access_chain.pop(); - } - Ok(()) - } - - /// Helper function to write down the Load operation on a `ByteAddressBuffer`. - fn write_storage_load( - &mut self, - module: &Module, - var_handle: Handle, - result_ty: proc::TypeResolution, - func_ctx: &back::FunctionCtx<'_>, - ) -> BackendResult { - match *result_ty.inner_with(&module.types) { - TypeInner::Scalar { kind, width: _ } => { - // working around the borrow checker in `self.write_expr` - let chain = mem::take(&mut self.temp_access_chain); - let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; - let cast = kind.to_hlsl_cast(); - write!(self.out, "{}({}.Load(", cast, var_name)?; - self.write_storage_address(module, &chain, func_ctx)?; - write!(self.out, "))")?; - self.temp_access_chain = chain; - } - TypeInner::Vector { - size, - kind, - width: _, - } => { - // working around the borrow checker in `self.write_expr` - let chain = mem::take(&mut self.temp_access_chain); - let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; - let cast = kind.to_hlsl_cast(); - write!(self.out, "{}({}.Load{}(", cast, var_name, size as u8)?; - self.write_storage_address(module, &chain, func_ctx)?; - write!(self.out, "))")?; - self.temp_access_chain = chain; - } - TypeInner::Matrix { - columns, - rows, - width, - } => { - write!( - self.out, - "{}{}x{}(", - crate::ScalarKind::Float.to_hlsl_str(width)?, - columns as u8, - rows as u8, - )?; - let row_stride = width as u32 * rows as u32; - let iter = (0..columns as u32).map(|i| { - let ty_inner = TypeInner::Vector { - size: rows, - kind: crate::ScalarKind::Float, - width, - }; - (proc::TypeResolution::Value(ty_inner), i * row_stride) - }); - self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; - write!(self.out, ")")?; - } - TypeInner::Array { - base, - size: crate::ArraySize::Constant(const_handle), - .. - } => { - write!(self.out, "{{")?; - let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.span(&module.constants); - let iter = (0..count).map(|i| (proc::TypeResolution::Handle(base), stride * i)); - self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; - write!(self.out, "}}")?; - } - TypeInner::Struct { ref members, .. } => { - write!(self.out, "{{")?; - let iter = members - .iter() - .map(|m| (proc::TypeResolution::Handle(m.ty), m.offset)); - self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; - write!(self.out, "}}")?; - } - _ => unreachable!(), - } - Ok(()) - } - - fn write_store_value( - &mut self, - module: &Module, - value: &StoreValue, - func_ctx: &back::FunctionCtx, - ) -> BackendResult { - match *value { - StoreValue::Expression(expr) => self.write_expr(module, expr, &func_ctx)?, - StoreValue::TempIndex { - depth, - index, - ty: _, - } => write!(self.out, "{}{}[{}]", STORE_TEMP_NAME, depth, index)?, - StoreValue::TempAccess { - depth, - base, - member_index, - } => { - let name = &self.names[&NameKey::StructMember(base, member_index)]; - write!(self.out, "{}{}.{}", STORE_TEMP_NAME, depth, name)? - } - } - Ok(()) - } - - /// Helper function to write down the Store operation on a `ByteAddressBuffer`. - fn write_storage_store( - &mut self, - module: &Module, - var_handle: Handle, - value: StoreValue, - func_ctx: &back::FunctionCtx<'_>, - indent: usize, - ) -> BackendResult { - let temp_resolution; - let ty_resolution = match value { - StoreValue::Expression(expr) => &func_ctx.info[expr].ty, - StoreValue::TempIndex { - depth: _, - index: _, - ref ty, - } => ty, - StoreValue::TempAccess { - depth: _, - base, - member_index, - } => { - let ty_handle = match module.types[base].inner { - TypeInner::Struct { ref members, .. } => members[member_index as usize].ty, - _ => unreachable!(), - }; - temp_resolution = proc::TypeResolution::Handle(ty_handle); - &temp_resolution - } - }; - match *ty_resolution.inner_with(&module.types) { - TypeInner::Scalar { .. } => { - // working around the borrow checker in `self.write_expr` - let chain = mem::take(&mut self.temp_access_chain); - let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; - write!( - self.out, - "{}{}.Store(", - back::INDENT.repeat(indent), - var_name - )?; - self.write_storage_address(module, &chain, func_ctx)?; - write!(self.out, ", asuint(")?; - self.write_store_value(module, &value, func_ctx)?; - writeln!(self.out, "));")?; - self.temp_access_chain = chain; - } - TypeInner::Vector { size, .. } => { - // working around the borrow checker in `self.write_expr` - let chain = mem::take(&mut self.temp_access_chain); - let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; - write!( - self.out, - "{}{}.Store{}(", - back::INDENT.repeat(indent), - var_name, - size as u8 - )?; - self.write_storage_address(module, &chain, func_ctx)?; - write!(self.out, ", asuint(")?; - self.write_store_value(module, &value, func_ctx)?; - writeln!(self.out, "));")?; - self.temp_access_chain = chain; - } - TypeInner::Matrix { - columns, - rows, - width, - } => { - // first, assign the value to a temporary - writeln!(self.out, "{}{{", back::INDENT.repeat(indent))?; - let depth = indent + 1; - write!( - self.out, - "{}{}{}x{} {}{} = ", - back::INDENT.repeat(indent + 1), - crate::ScalarKind::Float.to_hlsl_str(width)?, - columns as u8, - rows as u8, - STORE_TEMP_NAME, - depth, - )?; - self.write_store_value(module, &value, func_ctx)?; - writeln!(self.out, ";")?; - // then iterate the stores - let row_stride = width as u32 * rows as u32; - for i in 0..columns as u32 { - self.temp_access_chain - .push(SubAccess::Offset(i * row_stride)); - let ty_inner = TypeInner::Vector { - size: rows, - kind: crate::ScalarKind::Float, - width, - }; - let sv = StoreValue::TempIndex { - depth, - index: i, - ty: proc::TypeResolution::Value(ty_inner), - }; - self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; - self.temp_access_chain.pop(); - } - // done - writeln!(self.out, "{}}}", back::INDENT.repeat(indent))?; - } - TypeInner::Array { - base, - size: crate::ArraySize::Constant(const_handle), - .. - } => { - // first, assign the value to a temporary - writeln!(self.out, "{}{{", back::INDENT.repeat(indent))?; - write!(self.out, "{}", back::INDENT.repeat(indent + 1))?; - self.write_value_type(module, &module.types[base].inner)?; - let depth = indent + 1; - write!(self.out, " {}{}", STORE_TEMP_NAME, depth)?; - self.write_array_size(module, crate::ArraySize::Constant(const_handle))?; - write!(self.out, " = ")?; - self.write_store_value(module, &value, func_ctx)?; - writeln!(self.out, ";")?; - // then iterate the stores - let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.span(&module.constants); - for i in 0..count { - self.temp_access_chain.push(SubAccess::Offset(i * stride)); - let sv = StoreValue::TempIndex { - depth, - index: i, - ty: proc::TypeResolution::Handle(base), - }; - self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; - self.temp_access_chain.pop(); - } - // done - writeln!(self.out, "{}}}", back::INDENT.repeat(indent))?; - } - TypeInner::Struct { ref members, .. } => { - // first, assign the value to a temporary - writeln!(self.out, "{}{{", back::INDENT.repeat(indent))?; - let depth = indent + 1; - let struct_ty = ty_resolution.handle().unwrap(); - let struct_name = &self.names[&NameKey::Type(struct_ty)]; - write!( - self.out, - "{}{} {}{} = ", - back::INDENT.repeat(indent + 1), - struct_name, - STORE_TEMP_NAME, - depth - )?; - self.write_store_value(module, &value, func_ctx)?; - writeln!(self.out, ";")?; - // then iterate the stores - for (i, member) in members.iter().enumerate() { - self.temp_access_chain - .push(SubAccess::Offset(member.offset)); - let sv = StoreValue::TempAccess { - depth, - base: struct_ty, - member_index: i as u32, - }; - self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; - self.temp_access_chain.pop(); - } - // done - writeln!(self.out, "{}}}", back::INDENT.repeat(indent))?; - } - _ => unreachable!(), - } - Ok(()) - } - - fn fill_access_chain( - &mut self, - module: &Module, - mut cur_expr: Handle, - func_ctx: &back::FunctionCtx<'_>, - ) -> Result, Error> { - self.temp_access_chain.clear(); - loop { - let stride = func_ctx.info[cur_expr] - .ty - .inner_with(&module.types) - .span(&module.constants); - let (next_expr, sub) = match func_ctx.expressions[cur_expr] { - crate::Expression::GlobalVariable(handle) => return Ok(handle), - crate::Expression::Access { base, index } => ( - base, - SubAccess::Index { - value: index, - stride, - }, - ), - crate::Expression::AccessIndex { base, index } => { - match *func_ctx.info[base].ty.inner_with(&module.types) { - TypeInner::Struct { ref members, .. } => { - (base, SubAccess::Offset(members[index as usize].offset)) - } - _ => (base, SubAccess::Offset(index * stride)), - } - } - ref other => { - return Err(Error::Unimplemented(format!( - "Pointer access of {:?}", - other - ))) - } - }; - self.temp_access_chain.push(sub); - cur_expr = next_expr; - } - } } From a5c2cef9ab96dc4df235b9d813416a5ec2f503ee Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 26 Jul 2021 00:36:03 -0400 Subject: [PATCH 1152/2212] hlsl: transpose storage matrices --- src/back/hlsl/storage.rs | 29 +++++++++++++++++------------ tests/out/hlsl/access.hlsl | 4 ++-- tests/out/hlsl/shadow.hlsl | 2 +- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 033bfcf16..3f296fe2a 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -1,3 +1,8 @@ +//! Logic related to `ByteAddressBuffer` operations. +//! +//! HLSL backend uses byte address buffers for all storage buffers in IR. +//! Matrices have to be transposed, because HLSL syntax implies row majority. + use super::{ super::{FunctionCtx, INDENT}, BackendResult, Error, @@ -116,22 +121,22 @@ impl super::Writer<'_, W> { } => { write!( self.out, - "{}{}x{}(", + "transpose({}{}x{}(", crate::ScalarKind::Float.to_hlsl_str(width)?, - columns as u8, rows as u8, + columns as u8, )?; - let row_stride = width as u32 * rows as u32; - let iter = (0..columns as u32).map(|i| { + let row_stride = width as u32 * columns as u32; + let iter = (0..rows as u32).map(|i| { let ty_inner = crate::TypeInner::Vector { - size: rows, + size: columns, kind: crate::ScalarKind::Float, width, }; (TypeResolution::Value(ty_inner), i * row_stride) }); self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; - write!(self.out, ")")?; + write!(self.out, "))")?; } crate::TypeInner::Array { base, @@ -254,23 +259,23 @@ impl super::Writer<'_, W> { let depth = indent + 1; write!( self.out, - "{}{}{}x{} {}{} = ", + "{}{}{}x{} {}{} = transpose(", INDENT.repeat(indent + 1), crate::ScalarKind::Float.to_hlsl_str(width)?, - columns as u8, rows as u8, + columns as u8, STORE_TEMP_NAME, depth, )?; self.write_store_value(module, &value, func_ctx)?; - writeln!(self.out, ";")?; + writeln!(self.out, ");")?; // then iterate the stores - let row_stride = width as u32 * rows as u32; - for i in 0..columns as u32 { + let row_stride = width as u32 * columns as u32; + for i in 0..rows as u32 { self.temp_access_chain .push(SubAccess::Offset(i * row_stride)); let ty_inner = crate::TypeInner::Vector { - size: rows, + size: columns, kind: crate::ScalarKind::Float, width, }; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 0946fb8bf..14201429d 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -19,14 +19,14 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position float baz = foo1; foo1 = 1.0; - float4x4 matrix1 = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); + float4x4 matrix1 = transpose(float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48)))); uint2 arr[2] = {asuint(bar.Load2(4+0)), asuint(bar.Load2(4+8))}; float4 _expr13 = asfloat(bar.Load4(12+0)); float b = _expr13.x; int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 80) / 4) - 2u)*4+8)); bar.Store(8+4+0, asuint(1.0)); { - float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx)); + float4x4 _value2 = transpose(float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx))); bar.Store4(0+0, asuint(_value2[0])); bar.Store4(0+16, asuint(_value2[1])); bar.Store4(0+32, asuint(_value2[2])); diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 44efa15af..4982029a1 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -45,7 +45,7 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 break; } uint _expr19 = i; - Light light = {float4x4(asfloat(s_lights.Load4(_expr19*4+0+0+0)), asfloat(s_lights.Load4(_expr19*4+0+0+16)), asfloat(s_lights.Load4(_expr19*4+0+0+32)), asfloat(s_lights.Load4(_expr19*4+0+0+48))), asfloat(s_lights.Load4(_expr19*4+0+64)), asfloat(s_lights.Load4(_expr19*4+0+80))}; + Light light = {transpose(float4x4(asfloat(s_lights.Load4(_expr19*4+0+0+0)), asfloat(s_lights.Load4(_expr19*4+0+0+16)), asfloat(s_lights.Load4(_expr19*4+0+0+32)), asfloat(s_lights.Load4(_expr19*4+0+0+48)))), asfloat(s_lights.Load4(_expr19*4+0+64)), asfloat(s_lights.Load4(_expr19*4+0+80))}; uint _expr22 = i; const float _e25 = fetch_shadow(_expr22, mul(light.proj, fragmentinput_fs_main.position1)); float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz)); From e97c8f944121a58bbc908ecb64bdf97d4ada039d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 26 Jul 2021 01:21:24 -0400 Subject: [PATCH 1153/2212] hlsl: fix storage offset, continuing statement --- src/back/hlsl/storage.rs | 15 +++++++++---- src/back/hlsl/writer.rs | 45 +++++++++++++++++++++++++++----------- tests/out/hlsl/access.hlsl | 10 ++++----- tests/out/hlsl/boids.hlsl | 20 ++++++++++------- tests/out/hlsl/shadow.hlsl | 10 ++++++--- 5 files changed, 67 insertions(+), 33 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 3f296fe2a..a48507a66 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -365,10 +365,17 @@ impl super::Writer<'_, W> { ) -> Result, Error> { self.temp_access_chain.clear(); loop { - let stride = func_ctx.info[cur_expr] - .ty - .inner_with(&module.types) - .span(&module.constants); + // determine the size of the pontee + let stride = match *func_ctx.info[cur_expr].ty.inner_with(&module.types) { + crate::TypeInner::Pointer { base, class: _ } => { + module.types[base].inner.span(&module.constants) + } + crate::TypeInner::ValuePointer { size, width, .. } => { + size.map_or(1, |s| s as u32) * width as u32 + } + _ => 0, + }; + let (next_expr, sub) = match func_ctx.expressions[cur_expr] { crate::Expression::GlobalVariable(handle) => return Ok(handle), crate::Expression::Access { base, index } => ( diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index b331d8c27..bbecb3edc 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1008,23 +1008,42 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ref body, ref continuing, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; - writeln!(self.out, "while(true) {{")?; - - for sta in body.iter().chain(continuing.iter()) { - self.write_stmt(module, sta, func_ctx, indent + 1)?; + if !continuing.is_empty() { + let gate_name = self.namer.call("loop_init"); + writeln!( + self.out, + "{}bool {} = true;", + INDENT.repeat(indent), + gate_name + )?; + writeln!(self.out, "{}while(true) {{", INDENT.repeat(indent))?; + writeln!( + self.out, + "{}if (!{}) {{", + INDENT.repeat(indent + 1), + gate_name + )?; + for sta in continuing.iter() { + self.write_stmt(module, sta, func_ctx, indent + 1)?; + } + writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; + writeln!( + self.out, + "{}{} = false;", + INDENT.repeat(indent + 1), + gate_name + )?; + } else { + writeln!(self.out, "{}while(true) {{", INDENT.repeat(indent))?; } + for sta in body.iter() { + self.write_stmt(module, sta, func_ctx, indent + 1)?; + } writeln!(self.out, "{}}}", INDENT.repeat(indent))? } - Statement::Break => { - write!(self.out, "{}", INDENT.repeat(indent))?; - writeln!(self.out, "break;")? - } - Statement::Continue => { - write!(self.out, "{}", INDENT.repeat(indent))?; - writeln!(self.out, "continue;")? - } + Statement::Break => writeln!(self.out, "{}break;", INDENT.repeat(indent))?, + Statement::Continue => writeln!(self.out, "{}continue;", INDENT.repeat(indent))?, Statement::Barrier(barrier) => { if barrier.contains(crate::Barrier::STORAGE) { writeln!( diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 14201429d..5ff07ea5f 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -20,11 +20,11 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position float baz = foo1; foo1 = 1.0; float4x4 matrix1 = transpose(float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48)))); - uint2 arr[2] = {asuint(bar.Load2(4+0)), asuint(bar.Load2(4+8))}; - float4 _expr13 = asfloat(bar.Load4(12+0)); + uint2 arr[2] = {asuint(bar.Load2(16+0)), asuint(bar.Load2(16+8))}; + float4 _expr13 = asfloat(bar.Load4(48+0)); float b = _expr13.x; int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 80) / 4) - 2u)*4+8)); - bar.Store(8+4+0, asuint(1.0)); + bar.Store(8+16+0, asuint(1.0)); { float4x4 _value2 = transpose(float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx))); bar.Store4(0+0, asuint(_value2[0])); @@ -34,8 +34,8 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position } { uint2 _value2[2] = { uint2(0u.xx), uint2(1u.xx) }; - bar.Store2(4+0, asuint(_value2[0])); - bar.Store2(4+8, asuint(_value2[1])); + bar.Store2(16+0, asuint(_value2[0])); + bar.Store2(16+8, asuint(_value2[1])); } { int _result[5]={ a, int(b), 3, 4, 5 }; diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index c3e742ca7..03fd86d05 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -41,14 +41,20 @@ void main(ComputeInput_main computeinput_main) if ((index >= NUM_PARTICLES)) { return; } - float2 _expr10 = asfloat(particlesSrc.Load2(0+index*4+0)); + float2 _expr10 = asfloat(particlesSrc.Load2(0+index*16+0)); vPos = _expr10; - float2 _expr15 = asfloat(particlesSrc.Load2(4+index*4+0)); + float2 _expr15 = asfloat(particlesSrc.Load2(8+index*16+0)); vVel = _expr15; cMass = float2(0.0, 0.0); cVel = float2(0.0, 0.0); colVel = float2(0.0, 0.0); + bool loop_init = true; while(true) { + if (!loop_init) { + uint _expr86 = i; + i = (_expr86 + 1u); + } + loop_init = false; uint _expr37 = i; if ((_expr37 >= NUM_PARTICLES)) { break; @@ -58,10 +64,10 @@ void main(ComputeInput_main computeinput_main) continue; } uint _expr42 = i; - float2 _expr45 = asfloat(particlesSrc.Load2(0+_expr42*4+0)); + float2 _expr45 = asfloat(particlesSrc.Load2(0+_expr42*16+0)); pos = _expr45; uint _expr47 = i; - float2 _expr50 = asfloat(particlesSrc.Load2(4+_expr47*4+0)); + float2 _expr50 = asfloat(particlesSrc.Load2(8+_expr47*16+0)); vel = _expr50; float2 _expr51 = pos; float2 _expr52 = vPos; @@ -92,8 +98,6 @@ void main(ComputeInput_main computeinput_main) int _expr83 = cVelCount; cVelCount = (_expr83 + 1); } - uint _expr86 = i; - i = (_expr86 + 1u); } int _expr89 = cMassCount; if ((_expr89 > 0)) { @@ -140,8 +144,8 @@ void main(ComputeInput_main computeinput_main) vPos.y = -1.0; } float2 _expr164 = vPos; - particlesDst.Store2(0+index*4+0, asuint(_expr164)); + particlesDst.Store2(0+index*16+0, asuint(_expr164)); float2 _expr168 = vVel; - particlesDst.Store2(4+index*4+0, asuint(_expr168)); + particlesDst.Store2(8+index*16+0, asuint(_expr168)); return; } diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 4982029a1..32d23dd93 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -38,22 +38,26 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 uint i = 0u; float3 normal = normalize(fragmentinput_fs_main.raw_normal1); + bool loop_init = true; while(true) { + if (!loop_init) { + uint _expr40 = i; + i = (_expr40 + 1u); + } + loop_init = false; uint _expr12 = i; uint4 _expr14 = u_globals.num_lights; if ((_expr12 >= min(_expr14.x, c_max_lights))) { break; } uint _expr19 = i; - Light light = {transpose(float4x4(asfloat(s_lights.Load4(_expr19*4+0+0+0)), asfloat(s_lights.Load4(_expr19*4+0+0+16)), asfloat(s_lights.Load4(_expr19*4+0+0+32)), asfloat(s_lights.Load4(_expr19*4+0+0+48)))), asfloat(s_lights.Load4(_expr19*4+0+64)), asfloat(s_lights.Load4(_expr19*4+0+80))}; + Light light = {transpose(float4x4(asfloat(s_lights.Load4(_expr19*96+0+0+0)), asfloat(s_lights.Load4(_expr19*96+0+0+16)), asfloat(s_lights.Load4(_expr19*96+0+0+32)), asfloat(s_lights.Load4(_expr19*96+0+0+48)))), asfloat(s_lights.Load4(_expr19*96+0+64)), asfloat(s_lights.Load4(_expr19*96+0+80))}; uint _expr22 = i; const float _e25 = fetch_shadow(_expr22, mul(light.proj, fragmentinput_fs_main.position1)); float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); float3 _expr34 = color; color = (_expr34 + ((_e25 * diffuse) * light.color.xyz)); - uint _expr40 = i; - i = (_expr40 + 1u); } float3 _expr43 = color; return float4(_expr43, 1.0); From 46d2d6819e61619a52891038c862c591c546465d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 26 Jul 2021 10:37:30 -0400 Subject: [PATCH 1154/2212] Fix matrix size computation --- src/proc/mod.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 0c51646e4..226780851 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -101,11 +101,15 @@ impl super::TypeInner { kind: _, width, } => (size as u8 * width) as u32, + // matrices are treated as arrays of aligned columns Self::Matrix { columns, rows, width, - } => (columns as u8 * rows as u8 * width) as u32, + } => { + let aligned_rows = if rows > crate::VectorSize::Bi { 4 } else { 2 }; + columns as u32 * aligned_rows * width as u32 + } Self::Pointer { .. } | Self::ValuePointer { .. } => POINTER_SPAN, Self::Array { base: _, @@ -318,3 +322,17 @@ impl super::SwizzleComponent { } } } + +#[test] +fn test_matrix_size() { + let constants = crate::Arena::new(); + assert_eq!( + crate::TypeInner::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Tri, + width: 4 + } + .span(&constants), + 48 + ); +} From d3243bd774c2e5d58429681076cf912a1ad8628c Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Mon, 26 Jul 2021 18:22:32 +0300 Subject: [PATCH 1155/2212] [glsl-out] Enable access snapshot testing --- src/back/glsl/mod.rs | 11 +-------- tests/out/glsl/access.foo.Vertex.glsl | 34 +++++++++++++++++++++++++++ tests/snapshots.rs | 2 +- 3 files changed, 36 insertions(+), 11 deletions(-) create mode 100644 tests/out/glsl/access.foo.Vertex.glsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index f109a4800..573c7aaff 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1250,16 +1250,7 @@ impl<'a, W: Write> Writer<'a, W> { size, stride: _, } => { - // GLSL arrays are written as `type name[size]` - let ty_name = match self.module.types[base].inner { - // Write scalar type by backend so as not to depend on the front-end implementation - // Name returned from frontend can be generated (type1, float1, etc.) - TypeInner::Scalar { kind, width } => glsl_scalar(kind, width)?.full, - _ => &self.names[&NameKey::Type(base)], - }; - - // Write `type` and `name` - write!(self.out, "{}", ty_name)?; + self.write_type(base)?; write!( self.out, " {}", diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl new file mode 100644 index 000000000..f5afcd162 --- /dev/null +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -0,0 +1,34 @@ +#version 310 es + +precision highp float; +precision highp int; + +buffer Bar_block_0Vs { + mat4x4 matrix; + uvec2 arr[2]; + int data[]; +} _group_0_binding_0; + + +void main() { + uint vi = uint(gl_VertexID); + float foo1 = 0.0; + int c[5]; + float baz = foo1; + foo1 = 1.0; + mat4x4 matrix = _group_0_binding_0.matrix; + uvec2 arr[2] = _group_0_binding_0.arr; + vec4 _expr13 = _group_0_binding_0.matrix[3]; + float b = _expr13.x; + int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)]; + _group_0_binding_0.matrix[1][2] = 1.0; + _group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + _group_0_binding_0.arr = uvec2[2](uvec2(0u), uvec2(1u)); + c = int[5](a, int(b), 3, 4, 5); + c[(vi + 1u)] = 42; + int value = c[vi]; + gl_Position = (matrix * vec4(ivec4(value))); + gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1e6b6b534..7cc6a1143 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -430,7 +430,7 @@ fn convert_wgsl() { ), ( "access", - Targets::SPIRV | Targets::METAL | Targets::HLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "control-flow", From a7ac13a61d63620b8a0821db9176ed467fc282f7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 26 Jul 2021 21:05:44 -0400 Subject: [PATCH 1156/2212] hlsl: special constants for base vertex/index --- src/back/hlsl/mod.rs | 6 ++- src/back/hlsl/writer.rs | 50 ++++++++++++++++++++++++- src/back/mod.rs | 37 ++++++++++++++++++ tests/in/skybox.param.ron | 1 + tests/out/hlsl/access.hlsl.config | 2 +- tests/out/hlsl/boids.hlsl.config | 2 +- tests/out/hlsl/collatz.hlsl.config | 2 +- tests/out/hlsl/control-flow.hlsl.config | 2 +- tests/out/hlsl/empty.hlsl.config | 2 +- tests/out/hlsl/globals.hlsl.config | 2 +- tests/out/hlsl/image.hlsl | 6 +-- tests/out/hlsl/image.hlsl.config | 6 +-- tests/out/hlsl/interface.hlsl.config | 6 +-- tests/out/hlsl/interpolate.hlsl.config | 4 +- tests/out/hlsl/operators.hlsl.config | 2 +- tests/out/hlsl/quad-vert.hlsl.config | 2 +- tests/out/hlsl/quad.hlsl.config | 4 +- tests/out/hlsl/shadow.hlsl.config | 2 +- tests/out/hlsl/skybox.hlsl | 13 +++++-- tests/out/hlsl/standard.hlsl.config | 2 +- tests/out/hlsl/texture-arg.hlsl.config | 2 +- 21 files changed, 124 insertions(+), 31 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 72ec44e3a..11e812a15 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -92,14 +92,18 @@ pub struct Options { pub binding_map: BindingMap, /// Don't panic on missing bindings, instead generate any HLSL. pub fake_missing_bindings: bool, + /// Add special constants to `SV_VertexIndex` and `SV_InstanceIndex`, + /// to make them work like in Vulkan/Metal, with help of the host. + pub special_constants_binding: Option, } impl Default for Options { fn default() -> Self { Options { - shader_model: ShaderModel::V5_0, + shader_model: ShaderModel::V5_1, binding_map: BindingMap::default(), fake_missing_bindings: true, + special_constants_binding: None, } } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index bbecb3edc..694297100 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -11,6 +11,10 @@ use crate::{ use std::fmt; const LOCATION_SEMANTIC: &str = "LOC"; +const SPECIAL_CBUF_TYPE: &str = "NagaConstants"; +const SPECIAL_CBUF_VAR: &str = "_NagaConstants"; +const SPECIAL_BASE_VERTEX: &str = "base_vertex"; +const SPECIAL_BASE_INSTANCE: &str = "base_instance"; /// Structure contains information required for generating /// wrapped structure of all entry points arguments @@ -65,6 +69,23 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ) -> Result { self.reset(module); + // Write special constants, if needed + if let Some(ref bt) = self.options.special_constants_binding { + writeln!(self.out, "struct {} {{", SPECIAL_CBUF_TYPE)?; + writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_BASE_VERTEX)?; + writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_BASE_INSTANCE)?; + writeln!(self.out, "}};")?; + write!( + self.out, + "ConstantBuffer<{}> {}: register(b{}", + SPECIAL_CBUF_TYPE, SPECIAL_CBUF_VAR, bt.register + )?; + if bt.space != 0 { + write!(self.out, ", space{}", bt.space)?; + } + writeln!(self.out, ");")?; + } + // Write all constants // For example, input wgsl shader: // ```wgsl @@ -410,7 +431,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // this was already resolved earlier when we started evaluating an entry point. let bt = self.options.resolve_resource_binding(binding).unwrap(); write!(self.out, " : register({}{}", register_ty, bt.register)?; - if self.options.shader_model > super::ShaderModel::V5_0 { + if bt.space != 0 { write!(self.out, ", space{}", bt.space)?; } write!(self.out, ")")?; @@ -1105,8 +1126,30 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ) -> BackendResult { use crate::Expression; + // Handle the special semantics for base vertex/instance + let ff_input = if self.options.special_constants_binding.is_some() { + func_ctx.is_fixed_function_input(expr, module) + } else { + None + }; + let closing_bracket = match ff_input { + Some(crate::BuiltIn::VertexIndex) => { + write!(self.out, "({}.{} + ", SPECIAL_CBUF_VAR, SPECIAL_BASE_VERTEX)?; + ")" + } + Some(crate::BuiltIn::InstanceIndex) => { + write!( + self.out, + "({}.{} + ", + SPECIAL_CBUF_VAR, SPECIAL_BASE_INSTANCE + )?; + ")" + } + _ => "", + }; + if let Some(name) = self.named_expressions.get(&expr) { - write!(self.out, "{}", name)?; + write!(self.out, "{}{}", name, closing_bracket)?; return Ok(()); } @@ -1627,6 +1670,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } + if !closing_bracket.is_empty() { + write!(self.out, "{}", closing_bracket)?; + } Ok(()) } diff --git a/src/back/mod.rs b/src/back/mod.rs index 51243a404..e753e7aa5 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -66,6 +66,43 @@ impl<'a> FunctionCtx<'_> { } } } + + // Returns true if the given expression points to a fixed-function pipeline input. + fn is_fixed_function_input( + &self, + mut expression: crate::Handle, + module: &crate::Module, + ) -> Option { + let ep_function = match self.ty { + FunctionType::Function(_) => return None, + FunctionType::EntryPoint(ep_index) => &module.entry_points[ep_index as usize].function, + }; + let mut built_in = None; + loop { + match self.expressions[expression] { + crate::Expression::FunctionArgument(arg_index) => { + return match ep_function.arguments[arg_index as usize].binding { + Some(crate::Binding::BuiltIn(bi)) => Some(bi), + _ => built_in, + }; + } + crate::Expression::AccessIndex { base, index } => { + match *self.info[base].ty.inner_with(&module.types) { + crate::TypeInner::Struct { ref members, .. } => { + if let Some(crate::Binding::BuiltIn(bi)) = + members[index as usize].binding + { + built_in = Some(bi); + } + } + _ => return None, + } + expression = base; + } + _ => return None, + } + } + } } /// How should code generated by Naga do indexing bounds checks? diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index d21b3b852..951981e72 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -53,5 +53,6 @@ (group: 0, binding: 2): (space: 1, register: 0), }, fake_missing_bindings: false, + special_constants_binding: Some((space: 0, register: 1)), ), ) diff --git a/tests/out/hlsl/access.hlsl.config b/tests/out/hlsl/access.hlsl.config index f684c661e..0f887fb4c 100644 --- a/tests/out/hlsl/access.hlsl.config +++ b/tests/out/hlsl/access.hlsl.config @@ -1,3 +1,3 @@ -vertex=(foo:vs_5_0 ) +vertex=(foo:vs_5_1 ) fragment=() compute=() diff --git a/tests/out/hlsl/boids.hlsl.config b/tests/out/hlsl/boids.hlsl.config index c0d04b8f2..246c485cf 100644 --- a/tests/out/hlsl/boids.hlsl.config +++ b/tests/out/hlsl/boids.hlsl.config @@ -1,3 +1,3 @@ vertex=() fragment=() -compute=(main:cs_5_0 ) +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/collatz.hlsl.config b/tests/out/hlsl/collatz.hlsl.config index c0d04b8f2..246c485cf 100644 --- a/tests/out/hlsl/collatz.hlsl.config +++ b/tests/out/hlsl/collatz.hlsl.config @@ -1,3 +1,3 @@ vertex=() fragment=() -compute=(main:cs_5_0 ) +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/control-flow.hlsl.config b/tests/out/hlsl/control-flow.hlsl.config index c0d04b8f2..246c485cf 100644 --- a/tests/out/hlsl/control-flow.hlsl.config +++ b/tests/out/hlsl/control-flow.hlsl.config @@ -1,3 +1,3 @@ vertex=() fragment=() -compute=(main:cs_5_0 ) +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/empty.hlsl.config b/tests/out/hlsl/empty.hlsl.config index c0d04b8f2..246c485cf 100644 --- a/tests/out/hlsl/empty.hlsl.config +++ b/tests/out/hlsl/empty.hlsl.config @@ -1,3 +1,3 @@ vertex=() fragment=() -compute=(main:cs_5_0 ) +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/globals.hlsl.config b/tests/out/hlsl/globals.hlsl.config index c0d04b8f2..246c485cf 100644 --- a/tests/out/hlsl/globals.hlsl.config +++ b/tests/out/hlsl/globals.hlsl.config @@ -1,3 +1,3 @@ vertex=() fragment=() -compute=(main:cs_5_0 ) +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index d72239152..4ade7db1a 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -11,9 +11,9 @@ TextureCube image_cube : register(t3); TextureCubeArray image_cube_array : register(t4); Texture3D image_3d : register(t5); Texture2DMS image_aa : register(t6); -SamplerState sampler_reg : register(s0); -SamplerComparisonState sampler_cmp : register(s1); -Texture2D image_2d_depth : register(t2); +SamplerState sampler_reg : register(s0, space1); +SamplerComparisonState sampler_cmp : register(s1, space1); +Texture2D image_2d_depth : register(t2, space1); struct ComputeInput_main { uint3 local_id1 : SV_GroupThreadID; diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config index c182886b7..c5d0760d9 100644 --- a/tests/out/hlsl/image.hlsl.config +++ b/tests/out/hlsl/image.hlsl.config @@ -1,3 +1,3 @@ -vertex=(queries:vs_5_0 ) -fragment=(sample1:ps_5_0 sample_comparison:ps_5_0 ) -compute=(main:cs_5_0 ) +vertex=(queries:vs_5_1 ) +fragment=(sample1:ps_5_1 sample_comparison:ps_5_1 ) +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/interface.hlsl.config b/tests/out/hlsl/interface.hlsl.config index 4da683e01..cec1fc2b9 100644 --- a/tests/out/hlsl/interface.hlsl.config +++ b/tests/out/hlsl/interface.hlsl.config @@ -1,3 +1,3 @@ -vertex=(vertex:vs_5_0 ) -fragment=(fragment:ps_5_0 ) -compute=(compute:cs_5_0 ) +vertex=(vertex:vs_5_1 ) +fragment=(fragment:ps_5_1 ) +compute=(compute:cs_5_1 ) diff --git a/tests/out/hlsl/interpolate.hlsl.config b/tests/out/hlsl/interpolate.hlsl.config index 7a83c119f..b0a8e4ba9 100644 --- a/tests/out/hlsl/interpolate.hlsl.config +++ b/tests/out/hlsl/interpolate.hlsl.config @@ -1,3 +1,3 @@ -vertex=(main:vs_5_0 ) -fragment=(main1:ps_5_0 ) +vertex=(main:vs_5_1 ) +fragment=(main1:ps_5_1 ) compute=() diff --git a/tests/out/hlsl/operators.hlsl.config b/tests/out/hlsl/operators.hlsl.config index c0d04b8f2..246c485cf 100644 --- a/tests/out/hlsl/operators.hlsl.config +++ b/tests/out/hlsl/operators.hlsl.config @@ -1,3 +1,3 @@ vertex=() fragment=() -compute=(main:cs_5_0 ) +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/quad-vert.hlsl.config b/tests/out/hlsl/quad-vert.hlsl.config index 9f33353d2..f72fafd91 100644 --- a/tests/out/hlsl/quad-vert.hlsl.config +++ b/tests/out/hlsl/quad-vert.hlsl.config @@ -1,3 +1,3 @@ -vertex=(main:vs_5_0 ) +vertex=(main:vs_5_1 ) fragment=() compute=() diff --git a/tests/out/hlsl/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config index 094d9191f..24b516da9 100644 --- a/tests/out/hlsl/quad.hlsl.config +++ b/tests/out/hlsl/quad.hlsl.config @@ -1,3 +1,3 @@ -vertex=(main:vs_5_0 ) -fragment=(main1:ps_5_0 fs_extra:ps_5_0 ) +vertex=(main:vs_5_1 ) +fragment=(main1:ps_5_1 fs_extra:ps_5_1 ) compute=() diff --git a/tests/out/hlsl/shadow.hlsl.config b/tests/out/hlsl/shadow.hlsl.config index ead2c79fa..b9f047558 100644 --- a/tests/out/hlsl/shadow.hlsl.config +++ b/tests/out/hlsl/shadow.hlsl.config @@ -1,3 +1,3 @@ vertex=() -fragment=(fs_main:ps_5_0 ) +fragment=(fs_main:ps_5_1 ) compute=() diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 8eba4c4ec..058b0cbb6 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -1,3 +1,8 @@ +struct NagaConstants { + int base_vertex; + int base_instance; +}; +ConstantBuffer _NagaConstants: register(b1); struct VertexOutput { float4 position : SV_Position; @@ -9,8 +14,8 @@ struct Data { float4x4 view; }; -cbuffer r_data : register(b0, space0) { Data r_data; } -TextureCube r_texture : register(t0, space0); +cbuffer r_data : register(b0) { Data r_data; } +TextureCube r_texture : register(t0); SamplerState r_sampler : register(s0, space1); struct VertexInput_vs_main { @@ -26,8 +31,8 @@ VertexOutput vs_main(VertexInput_vs_main vertexinput_vs_main) int tmp1_ = (int)0; int tmp2_ = (int)0; - tmp1_ = (int(vertexinput_vs_main.vertex_index1) / 2); - tmp2_ = (int(vertexinput_vs_main.vertex_index1) & 1); + tmp1_ = (int((_NagaConstants.base_vertex + vertexinput_vs_main.vertex_index1)) / 2); + tmp2_ = (int((_NagaConstants.base_vertex + vertexinput_vs_main.vertex_index1)) & 1); int _expr10 = tmp1_; int _expr16 = tmp2_; float4 pos = float4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); diff --git a/tests/out/hlsl/standard.hlsl.config b/tests/out/hlsl/standard.hlsl.config index 512971d7c..a2606f3ab 100644 --- a/tests/out/hlsl/standard.hlsl.config +++ b/tests/out/hlsl/standard.hlsl.config @@ -1,3 +1,3 @@ vertex=() -fragment=(derivatives:ps_5_0 ) +fragment=(derivatives:ps_5_1 ) compute=() diff --git a/tests/out/hlsl/texture-arg.hlsl.config b/tests/out/hlsl/texture-arg.hlsl.config index 18ddfc224..98453a04e 100644 --- a/tests/out/hlsl/texture-arg.hlsl.config +++ b/tests/out/hlsl/texture-arg.hlsl.config @@ -1,3 +1,3 @@ vertex=() -fragment=(main:ps_5_0 ) +fragment=(main:ps_5_1 ) compute=() From 677e040462c2755f534de7c6392cf931b4c06614 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 27 Jul 2021 15:46:19 +0100 Subject: [PATCH 1157/2212] [glsl-in] Long form matrix support --- src/front/glsl/functions.rs | 66 ++++++- tests/in/glsl/long-form-matrix.vert | 24 +++ tests/out/wgsl/bevy-pbr-frag.wgsl | 228 +++++++++++----------- tests/out/wgsl/long-form-matrix-vert.wgsl | 31 +++ tests/out/wgsl/math-functions-vert.wgsl | 174 ++++++++--------- 5 files changed, 317 insertions(+), 206 deletions(-) create mode 100644 tests/in/glsl/long-form-matrix.vert create mode 100644 tests/out/wgsl/long-form-matrix-vert.wgsl diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 63be05756..126b4fadb 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -185,12 +185,68 @@ impl Program<'_> { } else { let mut components = Vec::with_capacity(args.len()); - for (mut arg, meta) in args.iter().copied() { - let scalar_components = scalar_components(&self.module.types[ty].inner); - if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; + match self.module.types[ty].inner { + TypeInner::Matrix { + columns, + rows, + width, + } => { + let mut flattened = + Vec::with_capacity(columns as usize * rows as usize); + + for (mut arg, meta) in args.iter().copied() { + let scalar_components = + scalar_components(&self.module.types[ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; + } + + match *self.resolve_type(ctx, arg, meta)? { + TypeInner::Vector { size, .. } => { + for i in 0..(size as u32) { + flattened.push(ctx.add_expression( + Expression::AccessIndex { + base: arg, + index: i, + }, + body, + )) + } + } + _ => flattened.push(arg), + } + } + + let ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, + }, + }); + + for chunk in flattened.chunks(rows as usize) { + components.push(ctx.add_expression( + Expression::Compose { + ty, + components: Vec::from(chunk), + }, + body, + )) + } + } + _ => { + for (mut arg, meta) in args.iter().copied() { + let scalar_components = + scalar_components(&self.module.types[ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; + } + + components.push(arg) + } } - components.push(arg) } ctx.add_expression(Expression::Compose { ty, components }, body) diff --git a/tests/in/glsl/long-form-matrix.vert b/tests/in/glsl/long-form-matrix.vert new file mode 100644 index 000000000..93a4f2d7f --- /dev/null +++ b/tests/in/glsl/long-form-matrix.vert @@ -0,0 +1,24 @@ +// ISSUE: #1064 +#version 450 + +void main() { + // Sane ways to build a matrix + mat2 splat = mat2(1); + mat2 normal = mat2(vec2(1), vec2(2)); + + // This is a little bit weirder but still makes some sense + // Since this matrix has 2 rows we take two numbers to make a column + // and we do this twice because we 2 columns. + // Final result in wgsl should be: + // mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)) + mat2 a = mat2(1, 2, 3, 4); + + // ??? + // Glsl has decided that for it's matrix constructor arguments it doesn't + // take them as is but instead flattens them so the `b` matrix is + // equivalent to the `a` matrix but in value and semantics + mat2 b = mat2(1, vec2(2, 3), 4); + mat3 c = mat3(1, 2, 3, vec3(1), vec3(1)); + mat3 d = mat3(vec2(2), 1, vec3(1), vec3(1)); + mat4 e = mat4(vec2(2), vec4(1), vec2(2), vec4(1), vec4(1)); +} diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 075be30c1..f323e3075 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -707,137 +707,137 @@ fn main1() { let _e93: vec3 = T; let _e94: vec3 = B; let _e95: vec3 = N2; - TBN = mat3x3(_e93, _e94, _e95); - let _e98: mat3x3 = TBN; - let _e99: vec2 = v_Uv1; - let _e100: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e99); - N2 = (_e98 * normalize(((_e100.xyz * 2.0) - vec3(1.0)))); - let _e109: vec2 = v_Uv1; - let _e110: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e109); - occlusion = _e110.x; - let _e113: vec4 = global7.emissive; - emissive = _e113; - let _e115: vec4 = emissive; - let _e117: vec4 = emissive; - let _e119: vec2 = v_Uv1; - let _e120: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e119); - let _e122: vec3 = (_e117.xyz * _e120.xyz); - emissive.x = _e122.x; - emissive.y = _e122.y; - emissive.z = _e122.z; - let _e129: vec4 = global1.CameraPos; - let _e131: vec3 = v_WorldPosition1; - V3 = normalize((_e129.xyz - _e131.xyz)); - let _e136: vec3 = N2; - let _e137: vec3 = V3; - NdotV4 = max(dot(_e136, _e137), 0.00009999999747378752); - let _e143: f32 = global6.reflectance; - let _e145: f32 = global6.reflectance; - let _e148: f32 = metallic; - let _e152: vec4 = output_color; - let _e154: f32 = metallic; - F0_4 = (vec3((((0.1599999964237213 * _e143) * _e145) * (1.0 - _e148))) + (_e152.xyz * vec3(_e154))); - let _e159: vec4 = output_color; - let _e162: f32 = metallic; - diffuseColor4 = (_e159.xyz * vec3((1.0 - _e162))); - let _e167: vec3 = V3; - let _e169: vec3 = N2; - R4 = reflect(-(_e167), _e169); + TBN = mat3x3(vec3(_e93.x, _e93.y, _e93.z), vec3(_e94.x, _e94.y, _e94.z), vec3(_e95.x, _e95.y, _e95.z)); + let _e110: mat3x3 = TBN; + let _e111: vec2 = v_Uv1; + let _e112: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e111); + N2 = (_e110 * normalize(((_e112.xyz * 2.0) - vec3(1.0)))); + let _e121: vec2 = v_Uv1; + let _e122: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e121); + occlusion = _e122.x; + let _e125: vec4 = global7.emissive; + emissive = _e125; + let _e127: vec4 = emissive; + let _e129: vec4 = emissive; + let _e131: vec2 = v_Uv1; + let _e132: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e131); + let _e134: vec3 = (_e129.xyz * _e132.xyz); + emissive.x = _e134.x; + emissive.y = _e134.y; + emissive.z = _e134.z; + let _e141: vec4 = global1.CameraPos; + let _e143: vec3 = v_WorldPosition1; + V3 = normalize((_e141.xyz - _e143.xyz)); + let _e148: vec3 = N2; + let _e149: vec3 = V3; + NdotV4 = max(dot(_e148, _e149), 0.00009999999747378752); + let _e155: f32 = global6.reflectance; + let _e157: f32 = global6.reflectance; + let _e160: f32 = metallic; + let _e164: vec4 = output_color; + let _e166: f32 = metallic; + F0_4 = (vec3((((0.1599999964237213 * _e155) * _e157) * (1.0 - _e160))) + (_e164.xyz * vec3(_e166))); + let _e171: vec4 = output_color; + let _e174: f32 = metallic; + diffuseColor4 = (_e171.xyz * vec3((1.0 - _e174))); + let _e179: vec3 = V3; + let _e181: vec3 = N2; + R4 = reflect(-(_e179), _e181); loop { - let _e177: i32 = i; - let _e178: vec4 = global2.NumLights; - let _e182: i32 = i; - if (!(((_e177 < i32(_e178.x)) && (_e182 < 10)))) { + let _e189: i32 = i; + let _e190: vec4 = global2.NumLights; + let _e194: i32 = i; + if (!(((_e189 < i32(_e190.x)) && (_e194 < 10)))) { break; } { - let _e189: vec3 = light_accum; - let _e190: i32 = i; - let _e200: i32 = i; - let _e202: PointLight = global2.PointLights[_e200]; - let _e203: f32 = roughness12; - let _e204: f32 = NdotV4; - let _e205: vec3 = N2; - let _e206: vec3 = V3; - let _e207: vec3 = R4; - let _e208: vec3 = F0_4; - let _e209: vec3 = diffuseColor4; - let _e210: vec3 = point_light(_e202, _e203, _e204, _e205, _e206, _e207, _e208, _e209); - light_accum = (_e189 + _e210); + let _e201: vec3 = light_accum; + let _e202: i32 = i; + let _e212: i32 = i; + let _e214: PointLight = global2.PointLights[_e212]; + let _e215: f32 = roughness12; + let _e216: f32 = NdotV4; + let _e217: vec3 = N2; + let _e218: vec3 = V3; + let _e219: vec3 = R4; + let _e220: vec3 = F0_4; + let _e221: vec3 = diffuseColor4; + let _e222: vec3 = point_light(_e214, _e215, _e216, _e217, _e218, _e219, _e220, _e221); + light_accum = (_e201 + _e222); } continuing { - let _e186: i32 = i; - i = (_e186 + 1); + let _e198: i32 = i; + i = (_e198 + 1); } } loop { - let _e214: i32 = i1; - let _e215: vec4 = global2.NumLights; - let _e219: i32 = i1; - if (!(((_e214 < i32(_e215.y)) && (_e219 < 1)))) { + let _e226: i32 = i1; + let _e227: vec4 = global2.NumLights; + let _e231: i32 = i1; + if (!(((_e226 < i32(_e227.y)) && (_e231 < 1)))) { break; } { - let _e226: vec3 = light_accum; - let _e227: i32 = i1; - let _e237: i32 = i1; - let _e239: DirectionalLight = global2.DirectionalLights[_e237]; - let _e240: f32 = roughness12; - let _e241: f32 = NdotV4; - let _e242: vec3 = N2; - let _e243: vec3 = V3; - let _e244: vec3 = R4; - let _e245: vec3 = F0_4; - let _e246: vec3 = diffuseColor4; - let _e247: vec3 = dir_light(_e239, _e240, _e241, _e242, _e243, _e244, _e245, _e246); - light_accum = (_e226 + _e247); + let _e238: vec3 = light_accum; + let _e239: i32 = i1; + let _e249: i32 = i1; + let _e251: DirectionalLight = global2.DirectionalLights[_e249]; + let _e252: f32 = roughness12; + let _e253: f32 = NdotV4; + let _e254: vec3 = N2; + let _e255: vec3 = V3; + let _e256: vec3 = R4; + let _e257: vec3 = F0_4; + let _e258: vec3 = diffuseColor4; + let _e259: vec3 = dir_light(_e251, _e252, _e253, _e254, _e255, _e256, _e257, _e258); + light_accum = (_e238 + _e259); } continuing { - let _e223: i32 = i1; - i1 = (_e223 + 1); + let _e235: i32 = i1; + i1 = (_e235 + 1); } } - let _e252: vec3 = diffuseColor4; - let _e254: f32 = NdotV4; - let _e255: vec3 = EnvBRDFApprox(_e252, 1.0, _e254); - diffuse_ambient = _e255; - let _e260: vec3 = F0_4; - let _e261: f32 = perceptual_roughness2; - let _e262: f32 = NdotV4; - let _e263: vec3 = EnvBRDFApprox(_e260, _e261, _e262); - specular_ambient = _e263; - let _e265: vec4 = output_color; - let _e267: vec3 = light_accum; - output_color.x = _e267.x; - output_color.y = _e267.y; - output_color.z = _e267.z; - let _e274: vec4 = output_color; - let _e276: vec4 = output_color; - let _e278: vec3 = diffuse_ambient; - let _e279: vec3 = specular_ambient; - let _e281: vec4 = global2.AmbientColor; - let _e284: f32 = occlusion; - let _e286: vec3 = (_e276.xyz + (((_e278 + _e279) * _e281.xyz) * _e284)); - output_color.x = _e286.x; - output_color.y = _e286.y; - output_color.z = _e286.z; - let _e293: vec4 = output_color; - let _e295: vec4 = output_color; - let _e297: vec4 = emissive; - let _e299: vec4 = output_color; - let _e302: vec3 = (_e295.xyz + (_e297.xyz * _e299.w)); - output_color.x = _e302.x; - output_color.y = _e302.y; - output_color.z = _e302.z; - let _e309: vec4 = output_color; + let _e264: vec3 = diffuseColor4; + let _e266: f32 = NdotV4; + let _e267: vec3 = EnvBRDFApprox(_e264, 1.0, _e266); + diffuse_ambient = _e267; + let _e272: vec3 = F0_4; + let _e273: f32 = perceptual_roughness2; + let _e274: f32 = NdotV4; + let _e275: vec3 = EnvBRDFApprox(_e272, _e273, _e274); + specular_ambient = _e275; + let _e277: vec4 = output_color; + let _e279: vec3 = light_accum; + output_color.x = _e279.x; + output_color.y = _e279.y; + output_color.z = _e279.z; + let _e286: vec4 = output_color; + let _e288: vec4 = output_color; + let _e290: vec3 = diffuse_ambient; + let _e291: vec3 = specular_ambient; + let _e293: vec4 = global2.AmbientColor; + let _e296: f32 = occlusion; + let _e298: vec3 = (_e288.xyz + (((_e290 + _e291) * _e293.xyz) * _e296)); + output_color.x = _e298.x; + output_color.y = _e298.y; + output_color.z = _e298.z; + let _e305: vec4 = output_color; + let _e307: vec4 = output_color; + let _e309: vec4 = emissive; let _e311: vec4 = output_color; - let _e313: vec4 = output_color; - let _e315: vec3 = reinhard_luminance(_e313.xyz); - output_color.x = _e315.x; - output_color.y = _e315.y; - output_color.z = _e315.z; - let _e322: vec4 = output_color; - o_Target = _e322; + let _e314: vec3 = (_e307.xyz + (_e309.xyz * _e311.w)); + output_color.x = _e314.x; + output_color.y = _e314.y; + output_color.z = _e314.z; + let _e321: vec4 = output_color; + let _e323: vec4 = output_color; + let _e325: vec4 = output_color; + let _e327: vec3 = reinhard_luminance(_e325.xyz); + output_color.x = _e327.x; + output_color.y = _e327.y; + output_color.z = _e327.z; + let _e334: vec4 = output_color; + o_Target = _e334; return; } diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl new file mode 100644 index 000000000..d2c3aa18d --- /dev/null +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -0,0 +1,31 @@ +fn main1() { + var splat: mat2x2; + var normal: mat2x2 = mat2x2(vec2(1.0, 1.0), vec2(2.0, 2.0)); + var a: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); + var b: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); + var c: mat3x3 = mat3x3(vec3(1.0, 2.0, 3.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); + var d: mat3x3 = mat3x3(vec3(2.0, 2.0, 1.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); + var e: mat4x4 = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); + + let _e2: vec2 = vec2(f32(1)); + splat = mat2x2(_e2, _e2); + let _e7: vec2 = vec2(f32(1)); + let _e10: vec2 = vec2(f32(2)); + let _e36: vec2 = vec2(f32(2), f32(3)); + let _e51: vec3 = vec3(f32(1)); + let _e54: vec3 = vec3(f32(1)); + let _e71: vec2 = vec2(f32(2)); + let _e75: vec3 = vec3(f32(1)); + let _e78: vec3 = vec3(f32(1)); + let _e95: vec2 = vec2(f32(2)); + let _e98: vec4 = vec4(f32(1)); + let _e101: vec2 = vec2(f32(2)); + let _e104: vec4 = vec4(f32(1)); + let _e107: vec4 = vec4(f32(1)); +} + +[[stage(vertex)]] +fn main() { + main1(); + return; +} diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 6042118a8..03ec93e05 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -47,96 +47,96 @@ fn main1() { let _e7: vec4 = b; let _e8: vec4 = a; let _e9: vec4 = b; - m = mat4x4(_e6, _e7, _e8, _e9); - let _e14: vec4 = a; - ceilOut = ceil(_e14); - let _e17: vec4 = a; - roundOut = round(_e17); - let _e20: vec4 = a; - floorOut = floor(_e20); - let _e23: vec4 = a; - fractOut = fract(_e23); - let _e26: vec4 = a; - truncOut = trunc(_e26); - let _e29: vec4 = a; - sinOut = sin(_e29); - let _e32: vec4 = a; - absOut = abs(_e32); - let _e35: vec4 = a; - sqrtOut = sqrt(_e35); - let _e38: vec4 = a; - inversesqrtOut = inverseSqrt(_e38); - let _e41: vec4 = a; - expOut = exp(_e41); - let _e44: vec4 = a; - exp2Out = exp2(_e44); - let _e47: vec4 = a; - signOut = sign(_e47); - let _e50: mat4x4 = m; - transposeOut = transpose(_e50); - let _e53: vec4 = a; - normalizeOut = normalize(_e53); - let _e56: vec4 = a; - sinhOut = sinh(_e56); - let _e59: vec4 = a; - cosOut = cos(_e59); - let _e62: vec4 = a; - coshOut = cosh(_e62); - let _e65: vec4 = a; - tanOut = tan(_e65); - let _e68: vec4 = a; - tanhOut = tanh(_e68); - let _e71: vec4 = a; - acosOut = acos(_e71); - let _e74: vec4 = a; - asinOut = asin(_e74); - let _e77: vec4 = a; - logOut = log(_e77); - let _e80: vec4 = a; - log2Out = log2(_e80); - let _e83: vec4 = a; - lengthOut = length(_e83); - let _e86: mat4x4 = m; - determinantOut = determinant(_e86); - let _e89: i32 = i; - bitCountOut = countOneBits(_e89); - let _e92: i32 = i; - bitfieldReverseOut = reverseBits(_e92); - let _e95: vec4 = a; - atanOut = atan(_e95.x); - let _e99: vec4 = a; - let _e101: vec4 = a; - atan2Out = atan2(_e99.x, _e101.y); - let _e105: vec4 = a; - let _e107: vec4 = b; - modOut = (_e105.x % _e107.x); - let _e111: vec4 = a; - let _e112: vec4 = b; - powOut = pow(_e111, _e112); + m = mat4x4(vec4(_e6.x, _e6.y, _e6.z, _e6.w), vec4(_e7.x, _e7.y, _e7.z, _e7.w), vec4(_e8.x, _e8.y, _e8.z, _e8.w), vec4(_e9.x, _e9.y, _e9.z, _e9.w)); + let _e34: vec4 = a; + ceilOut = ceil(_e34); + let _e37: vec4 = a; + roundOut = round(_e37); + let _e40: vec4 = a; + floorOut = floor(_e40); + let _e43: vec4 = a; + fractOut = fract(_e43); + let _e46: vec4 = a; + truncOut = trunc(_e46); + let _e49: vec4 = a; + sinOut = sin(_e49); + let _e52: vec4 = a; + absOut = abs(_e52); + let _e55: vec4 = a; + sqrtOut = sqrt(_e55); + let _e58: vec4 = a; + inversesqrtOut = inverseSqrt(_e58); + let _e61: vec4 = a; + expOut = exp(_e61); + let _e64: vec4 = a; + exp2Out = exp2(_e64); + let _e67: vec4 = a; + signOut = sign(_e67); + let _e70: mat4x4 = m; + transposeOut = transpose(_e70); + let _e73: vec4 = a; + normalizeOut = normalize(_e73); + let _e76: vec4 = a; + sinhOut = sinh(_e76); + let _e79: vec4 = a; + cosOut = cos(_e79); + let _e82: vec4 = a; + coshOut = cosh(_e82); + let _e85: vec4 = a; + tanOut = tan(_e85); + let _e88: vec4 = a; + tanhOut = tanh(_e88); + let _e91: vec4 = a; + acosOut = acos(_e91); + let _e94: vec4 = a; + asinOut = asin(_e94); + let _e97: vec4 = a; + logOut = log(_e97); + let _e100: vec4 = a; + log2Out = log2(_e100); + let _e103: vec4 = a; + lengthOut = length(_e103); + let _e106: mat4x4 = m; + determinantOut = determinant(_e106); + let _e109: i32 = i; + bitCountOut = countOneBits(_e109); + let _e112: i32 = i; + bitfieldReverseOut = reverseBits(_e112); let _e115: vec4 = a; - let _e116: vec4 = b; - dotOut = dot(_e115, _e116); + atanOut = atan(_e115.x); let _e119: vec4 = a; - let _e120: vec4 = b; - maxOut = max(_e119, _e120); - let _e123: vec4 = a; - let _e124: vec4 = b; - minOut = min(_e123, _e124); - let _e127: vec4 = a; - let _e128: vec4 = b; - reflectOut = reflect(_e127, _e128); + let _e121: vec4 = a; + atan2Out = atan2(_e119.x, _e121.y); + let _e125: vec4 = a; + let _e127: vec4 = b; + modOut = (_e125.x % _e127.x); let _e131: vec4 = a; - let _e133: vec4 = b; - crossOut = cross(_e131.xyz, _e133.xyz); - let _e137: vec4 = a; - let _e138: vec4 = b; - outerProductOut = outerProduct(_e137, _e138); - let _e141: vec4 = a; - let _e142: vec4 = b; - distanceOut = distance(_e141, _e142); - let _e145: vec4 = a; - let _e146: vec4 = b; - stepOut = step(_e145, _e146); + let _e132: vec4 = b; + powOut = pow(_e131, _e132); + let _e135: vec4 = a; + let _e136: vec4 = b; + dotOut = dot(_e135, _e136); + let _e139: vec4 = a; + let _e140: vec4 = b; + maxOut = max(_e139, _e140); + let _e143: vec4 = a; + let _e144: vec4 = b; + minOut = min(_e143, _e144); + let _e147: vec4 = a; + let _e148: vec4 = b; + reflectOut = reflect(_e147, _e148); + let _e151: vec4 = a; + let _e153: vec4 = b; + crossOut = cross(_e151.xyz, _e153.xyz); + let _e157: vec4 = a; + let _e158: vec4 = b; + outerProductOut = outerProduct(_e157, _e158); + let _e161: vec4 = a; + let _e162: vec4 = b; + distanceOut = distance(_e161, _e162); + let _e165: vec4 = a; + let _e166: vec4 = b; + stepOut = step(_e165, _e166); return; } From 6303af225fbf93a07415eb6981ea7b0fdc3fa125 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 27 Jul 2021 16:14:57 +0100 Subject: [PATCH 1158/2212] [glsl-in] Add implicit conversion for initializer --- src/front/glsl/parser.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 4029551fd..90c360e84 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -522,7 +522,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { )) } else { let expr = self.parse_assignment(ctx, body)?; - Ok(ctx.lower_expect(self.program, expr, false, body)?) + let (mut init, init_meta) = ctx.lower_expect(self.program, expr, false, body)?; + + let scalar_components = ast::scalar_components(&self.program.module.types[ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self.program, &mut init, init_meta, kind, width)?; + } + + Ok((init, init_meta)) } } From 2f516c0932d1e4684d4f4f38b3941345336751ed Mon Sep 17 00:00:00 2001 From: pyrotechnick <13998+pyrotechnick@users.noreply.github.com> Date: Wed, 28 Jul 2021 15:47:18 +1000 Subject: [PATCH 1159/2212] [wgsl] Storage buffer/texture access (#1142) * Resurrect texture_storage_* tests * Test parsing of `var` * Default storage textures to READ * Restore default features * Fix glsl/hlsl/msl/spv front and back ends * Add missing test outputs * All-around fixes for the storage access Co-authored-by: Dzmitry Malyshau --- src/back/glsl/features.rs | 4 +- src/back/glsl/mod.rs | 67 +++--- src/back/hlsl/help.rs | 63 +++--- src/back/hlsl/writer.rs | 85 ++++---- src/back/msl/writer.rs | 39 ++-- src/back/spv/block.rs | 2 +- src/back/spv/helpers.rs | 2 +- src/back/spv/instructions.rs | 4 +- src/back/spv/writer.rs | 36 +++- src/back/wgsl/writer.rs | 30 ++- src/front/glsl/parser.rs | 4 +- src/front/glsl/variables.rs | 44 ++-- src/front/spv/convert.rs | 4 +- src/front/spv/mod.rs | 32 ++- src/front/wgsl/conv.rs | 4 +- src/front/wgsl/lexer.rs | 38 +++- src/front/wgsl/mod.rs | 83 ++++---- src/front/wgsl/tests.rs | 46 +++- src/lib.rs | 9 +- src/proc/typifier.rs | 2 +- src/valid/analyzer.rs | 7 +- src/valid/function.rs | 12 +- src/valid/interface.rs | 45 +--- tests/in/access.wgsl | 2 +- tests/in/boids.wgsl | 4 +- tests/in/collatz.wgsl | 2 +- tests/in/image.wgsl | 4 +- tests/in/shadow.wgsl | 2 +- tests/out/analysis/collatz.info.ron | 36 +++- tests/out/analysis/shadow.info.ron | 278 ++++++++++++++++++------- tests/out/dot/quad.dot | 8 +- tests/out/hlsl/image.hlsl | 12 +- tests/out/ir/collatz.ron | 9 +- tests/out/ir/shadow.ron | 33 +-- tests/out/spv/bounds-check-zero.spvasm | 1 + tests/out/spv/pointer-access.spvasm | 2 + tests/out/wgsl/246-collatz-comp.wgsl | 2 +- tests/out/wgsl/access.wgsl | 2 +- tests/out/wgsl/boids.wgsl | 4 +- tests/out/wgsl/collatz.wgsl | 2 +- tests/out/wgsl/image.wgsl | 4 +- tests/out/wgsl/shadow.wgsl | 2 +- tests/wgsl-errors.rs | 16 +- 43 files changed, 652 insertions(+), 435 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index a9eb93fed..425361586 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -298,7 +298,7 @@ impl<'a, W> Writer<'a, W> { self.features.request(Features::MULTISAMPLED_TEXTURE_ARRAYS); } } - ImageClass::Storage(format) => match format { + ImageClass::Storage { format, .. } => match format { StorageFormat::R8Unorm | StorageFormat::R8Snorm | StorageFormat::R8Uint @@ -336,7 +336,7 @@ impl<'a, W> Writer<'a, W> { } match global.class { StorageClass::WorkGroup => self.features.request(Features::COMPUTE_SHADER), - StorageClass::Storage => self.features.request(Features::BUFFER_STORAGE), + StorageClass::Storage { .. } => self.features.request(Features::BUFFER_STORAGE), StorageClass::PushConstant => return Err(Error::PushConstantNotSupported), _ => {} } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 573c7aaff..7d15db988 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -497,11 +497,11 @@ impl<'a, W: Write> Writer<'a, W> { class, } => { // Gather the storage format if needed - let layout_storage_format = match self.module.types[global.ty].inner { + let storage_format_access = match self.module.types[global.ty].inner { TypeInner::Image { - class: crate::ImageClass::Storage(format), + class: crate::ImageClass::Storage { format, access }, .. - } => Some(glsl_storage_format(format)), + } => Some((format, access)), _ => None, }; // Gether the location if needed @@ -513,23 +513,24 @@ impl<'a, W: Write> Writer<'a, W> { }; // Write all the layout qualifiers - if layout_binding.is_some() || layout_storage_format.is_some() { + if layout_binding.is_some() || storage_format_access.is_some() { write!(self.out, "layout(")?; if let Some(binding) = layout_binding { write!(self.out, "binding = {}", binding)?; } - if let Some(format) = layout_storage_format { + if let Some((format, _)) = storage_format_access { + let format_str = glsl_storage_format(format); let separator = match layout_binding { Some(_) => ",", None => "", }; - write!(self.out, "{}{}", separator, format)?; + write!(self.out, "{}{}", separator, format_str)?; } write!(self.out, ") ")?; } - if let Some(storage_access) = glsl_storage_access(global.storage_access) { - write!(self.out, "{} ", storage_access)?; + if let Some((_, access)) = storage_format_access { + self.write_storage_access(access)?; } // All images in glsl are `uniform` @@ -760,7 +761,7 @@ impl<'a, W: Write> Writer<'a, W> { Ic::Sampled { kind, multi: false } => ("sampler", kind, "", ""), Ic::Depth { multi: true } => ("sampler", crate::ScalarKind::Float, "MS", ""), Ic::Depth { multi: false } => ("sampler", crate::ScalarKind::Float, "", "Shadow"), - Ic::Storage(format) => ("image", format.into(), "", ""), + Ic::Storage { format, .. } => ("image", format.into(), "", ""), }; write!( @@ -798,8 +799,8 @@ impl<'a, W: Write> Writer<'a, W> { } } - if let Some(storage_access) = glsl_storage_access(global.storage_access) { - write!(self.out, "{} ", storage_access)?; + if let crate::StorageClass::Storage { access } = global.class { + self.write_storage_access(access)?; } // Write the storage class @@ -1013,7 +1014,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { // Write the storage format if needed if let TypeInner::Image { - class: crate::ImageClass::Storage(format), + class: crate::ImageClass::Storage { format, .. }, .. } = this.module.types[arg.ty].inner { @@ -1939,7 +1940,7 @@ impl<'a, W: Write> Writer<'a, W> { let fun_name = match class { crate::ImageClass::Sampled { .. } => "texelFetch", - crate::ImageClass::Storage(_) => "imageLoad", + crate::ImageClass::Storage { .. } => "imageLoad", // TODO: Is there even a function for this? crate::ImageClass::Depth { multi: _ } => { return Err(Error::Custom("TODO: depth sample loads".to_string())) @@ -1992,7 +1993,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "0",)?; } } - ImageClass::Storage(_) => { + ImageClass::Storage { .. } => { write!(self.out, "imageSize(")?; self.write_expr(image, ctx)?; } @@ -2007,7 +2008,7 @@ impl<'a, W: Write> Writer<'a, W> { crate::ImageQuery::NumLayers => { let fun_name = match class { ImageClass::Sampled { .. } | ImageClass::Depth { .. } => "textureSize", - ImageClass::Storage(_) => "imageSize", + ImageClass::Storage { .. } => "imageSize", }; write!(self.out, "{}(", fun_name)?; self.write_expr(image, ctx)?; @@ -2019,7 +2020,7 @@ impl<'a, W: Write> Writer<'a, W> { ImageClass::Sampled { .. } | ImageClass::Depth { .. } => { "textureSamples" } - ImageClass::Storage(_) => "imageSamples", + ImageClass::Storage { .. } => "imageSamples", }; write!(self.out, "{}(", fun_name)?; self.write_expr(image, ctx)?; @@ -2417,6 +2418,21 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper function that return the glsl storage access string of [`StorageAccess`](crate::StorageAccess) + /// + /// glsl allows adding both `readonly` and `writeonly` but this means that + /// they can only be used to query information about the resource which isn't what + /// we want here so when storage access is both `LOAD` and `STORE` add no modifiers + fn write_storage_access(&mut self, storage_access: crate::StorageAccess) -> BackendResult { + if !storage_access.contains(crate::StorageAccess::STORE) { + write!(self.out, "readonly ")?; + } + if !storage_access.contains(crate::StorageAccess::LOAD) { + write!(self.out, "writeonly ")?; + } + Ok(()) + } + /// Helper method used to produce the reflection info that's returned to the user /// /// It takes an iterator of [`Function`](crate::Function) references instead of @@ -2454,7 +2470,7 @@ impl<'a, W: Write> Writer<'a, W> { } match self.module.types[var.ty].inner { crate::TypeInner::Struct { .. } => match var.class { - crate::StorageClass::Uniform | crate::StorageClass::Storage => { + crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => { let name = self.reflection_names[&var.ty].clone(); uniforms.insert(handle, name); } @@ -2568,7 +2584,7 @@ fn glsl_storage_class(class: crate::StorageClass) -> Option<&'static str> { match class { Sc::Function => None, Sc::Private => None, - Sc::Storage => Some("buffer"), + Sc::Storage { .. } => Some("buffer"), Sc::Uniform => Some("uniform"), Sc::Handle => Some("uniform"), Sc::WorkGroup => Some("shared"), @@ -2650,21 +2666,6 @@ fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { } } -/// Helper function that return the glsl storage access string of [`StorageAccess`](crate::StorageAccess) -/// -/// glsl allows adding both `readonly` and `writeonly` but this means that -/// they can only be used to query information about the resource which isn't what -/// we want here so when storage access is both `LOAD` and `STORE` add no modifiers -fn glsl_storage_access(storage_access: crate::StorageAccess) -> Option<&'static str> { - if storage_access == crate::StorageAccess::LOAD { - Some("readonly") - } else if storage_access == crate::StorageAccess::STORE { - Some("writeonly") - } else { - None - } -} - fn is_value_init_supported(module: &crate::Module, ty: Handle) -> bool { match module.types[ty].inner { TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => true, diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 710231901..d72c7a242 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -105,9 +105,13 @@ impl<'a, W: Write> super::Writer<'a, W> { arrayed: bool, class: crate::ImageClass, ) -> BackendResult { + let access_str = match class { + crate::ImageClass::Storage { .. } => "RW", + _ => "", + }; let dim_str = dim.to_hlsl_str(); let arrayed_str = if arrayed { "Array" } else { "" }; - write!(self.out, "Texture{}{}", dim_str, arrayed_str)?; + write!(self.out, "{}Texture{}{}", access_str, dim_str, arrayed_str)?; match class { crate::ImageClass::Depth { multi } => { let multi_str = if multi { "MS" } else { "" }; @@ -118,7 +122,7 @@ impl<'a, W: Write> super::Writer<'a, W> { let scalar_kind_str = kind.to_hlsl_str(4)?; write!(self.out, "{}<{}4>", multi_str, scalar_kind_str)? } - crate::ImageClass::Storage(format) => { + crate::ImageClass::Storage { format, .. } => { let storage_format_str = format.to_hlsl_str(); write!(self.out, "<{}>", storage_format_str)? } @@ -195,9 +199,8 @@ impl<'a, W: Write> super::Writer<'a, W> { crate::ImageClass::Sampled { multi: true, .. } => "MS", crate::ImageClass::Depth { multi: true } => "DepthMS", crate::ImageClass::Depth { multi: false } => "Depth", - crate::ImageClass::Sampled { multi: false, .. } | crate::ImageClass::Storage { .. } => { - "" - } + crate::ImageClass::Sampled { multi: false, .. } => "", + crate::ImageClass::Storage { .. } => "RW", }; let arrayed_str = if query.arrayed { "Array" } else { "" }; let query_str = match query.query { @@ -226,7 +229,10 @@ impl<'a, W: Write> super::Writer<'a, W> { expr_handle: Handle, func_ctx: &FunctionCtx, ) -> BackendResult { - use crate::{back::INDENT, ImageDimension as IDim}; + use crate::{ + back::{COMPONENTS, INDENT}, + ImageDimension as IDim, + }; const ARGUMENT_VARIABLE_NAME: &str = "texture"; const RETURN_VARIABLE_NAME: &str = "ret"; @@ -253,15 +259,24 @@ impl<'a, W: Write> super::Writer<'a, W> { writeln!(self.out, "{{")?; let array_coords = if wiq.arrayed { 1 } else { 0 }; + // extra parameter is the mip level count or the sample count + let extra_coords = match wiq.class { + crate::ImageClass::Storage { .. } => 0, + crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => 1, + }; + // GetDimensions Overloaded Methods // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods let (ret_swizzle, number_of_params) = match wiq.query { - ImageQuery::Size | ImageQuery::SizeLevel => match wiq.dim { - IDim::D1 => ("x", 1 + array_coords), - IDim::D2 => ("xy", 3 + array_coords), - IDim::D3 => ("xyz", 4), - IDim::Cube => ("xy", 3 + array_coords), - }, + ImageQuery::Size | ImageQuery::SizeLevel => { + let ret = match wiq.dim { + IDim::D1 => "x", + IDim::D2 => "xy", + IDim::D3 => "xyz", + IDim::Cube => "xy", + }; + (ret, ret.len() + array_coords + extra_coords) + } ImageQuery::NumLevels | ImageQuery::NumSamples | ImageQuery::NumLayers => { if wiq.arrayed || wiq.dim == IDim::D3 { ("w", 4) @@ -284,18 +299,16 @@ impl<'a, W: Write> super::Writer<'a, W> { } _ => match wiq.class { crate::ImageClass::Sampled { multi: true, .. } - | crate::ImageClass::Depth { multi: true } => {} - _ => match wiq.dim { + | crate::ImageClass::Depth { multi: true } + | crate::ImageClass::Storage { .. } => {} + _ => { // Write zero mipmap level for supported types - IDim::D2 | IDim::D3 | IDim::Cube => { - write!(self.out, "0, ")?; - } - IDim::D1 => {} - }, + write!(self.out, "0, ")?; + } }, } - for component in crate::back::COMPONENTS[..number_of_params - 1].iter() { + for component in COMPONENTS[..number_of_params - 1].iter() { write!(self.out, "{}.{}, ", RETURN_VARIABLE_NAME, component)?; } @@ -304,7 +317,7 @@ impl<'a, W: Write> super::Writer<'a, W> { self.out, "{}.{}", RETURN_VARIABLE_NAME, - crate::back::COMPONENTS[number_of_params - 1] + COMPONENTS[number_of_params - 1] )?; writeln!(self.out, ");")?; @@ -344,10 +357,12 @@ impl<'a, W: Write> super::Writer<'a, W> { } ref other => unreachable!("Array length of base {:?}", other), }; + let storage_access = match global_var.class { + crate::StorageClass::Storage { access } => access, + _ => crate::StorageAccess::default(), + }; let wal = WrappedArrayLength { - writable: global_var - .storage_access - .contains(crate::StorageAccess::STORE), + writable: storage_access.contains(crate::StorageAccess::STORE), }; if !self.wrapped_array_lengths.contains(&wal) { diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 694297100..2ef57b266 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -396,24 +396,24 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "cbuffer")?; "b" } - crate::StorageClass::Storage => { - let (prefix, register) = - if global.storage_access.contains(crate::StorageAccess::STORE) { - ("RW", "u") - } else { - ("", "t") - }; + crate::StorageClass::Storage { access } => { + let (prefix, register) = if access.contains(crate::StorageAccess::STORE) { + ("RW", "u") + } else { + ("", "t") + }; write!(self.out, "{}ByteAddressBuffer", prefix)?; register } crate::StorageClass::Handle => { - let register = if let TypeInner::Sampler { .. } = *inner { - "s" - } else if global.storage_access.contains(crate::StorageAccess::STORE) { - write!(self.out, "RW")?; - "u" - } else { - "t" + let register = match *inner { + TypeInner::Sampler { .. } => "s", + // all storage textures are UAV, unconditionally + TypeInner::Image { + class: crate::ImageClass::Storage { .. }, + .. + } => "u", + _ => "t", }; self.write_type(module, global.ty)?; register @@ -954,11 +954,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { _ => None, }; - if func_ctx.info[pointer] + if let Some(crate::StorageClass::Storage { .. }) = func_ctx.info[pointer] .ty .inner_with(&module.types) .pointer_class() - == Some(crate::StorageClass::Storage) { let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; self.write_storage_store( @@ -1208,11 +1207,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; } Expression::Access { base, index } => { - if func_ctx.info[expr] + if let Some(crate::StorageClass::Storage { .. }) = func_ctx.info[expr] .ty .inner_with(&module.types) .pointer_class() - == Some(crate::StorageClass::Storage) { // do nothing, the chain is written on `Load`/`Store` } else { @@ -1223,11 +1221,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Expression::AccessIndex { base, index } => { - if func_ctx.info[expr] + if let Some(crate::StorageClass::Storage { .. }) = func_ctx.info[expr] .ty .inner_with(&module.types) .pointer_class() - == Some(crate::StorageClass::Storage) { // do nothing, the chain is written on `Load`/`Store` } else { @@ -1389,22 +1386,19 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { index, } => { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-load - let ms = match *func_ctx.info[image].ty.inner_with(&module.types) { - TypeInner::Image { - class: crate::ImageClass::Sampled { multi, .. }, - .. - } - | TypeInner::Image { - class: crate::ImageClass::Depth { multi }, - .. - } => multi, - _ => false, + let (ms, storage) = match *func_ctx.info[image].ty.inner_with(&module.types) { + TypeInner::Image { class, .. } => match class { + crate::ImageClass::Sampled { multi, .. } + | crate::ImageClass::Depth { multi } => (multi, false), + crate::ImageClass::Storage { .. } => (false, true), + }, + _ => (false, false), }; self.write_expr(module, image, func_ctx)?; write!(self.out, ".Load(")?; - let mip_level = if ms { + let mip_level = if ms || storage { MipLevelCoordinate::NotApplicable } else { match index { @@ -1436,27 +1430,30 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ".x")?; } } - Expression::GlobalVariable(handle) => { - if module.global_variables[handle].class != crate::StorageClass::Storage { + Expression::GlobalVariable(handle) => match module.global_variables[handle].class { + crate::StorageClass::Storage { .. } => {} + _ => { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; } - } + }, Expression::LocalVariable(handle) => { write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])? } Expression::Load { pointer } => { - if func_ctx.info[pointer] + match func_ctx.info[pointer] .ty .inner_with(&module.types) .pointer_class() - == Some(crate::StorageClass::Storage) { - let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; - let result_ty = func_ctx.info[expr].ty.clone(); - self.write_storage_load(module, var_handle, result_ty, func_ctx)?; - } else { - self.write_expr(module, pointer, func_ctx)?; + Some(crate::StorageClass::Storage { .. }) => { + let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; + let result_ty = func_ctx.info[expr].ty.clone(); + self.write_storage_load(module, var_handle, result_ty, func_ctx)?; + } + _ => { + self.write_expr(module, pointer, func_ctx)?; + } } } Expression::Unary { op, expr } => { @@ -1613,8 +1610,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { _ => unreachable!(), }; + let storage_access = match var.class { + crate::StorageClass::Storage { access } => access, + _ => crate::StorageAccess::default(), + }; let wrapped_array_length = WrappedArrayLength { - writable: var.storage_access.contains(crate::StorageAccess::STORE), + writable: storage_access.contains(crate::StorageAccess::STORE), }; write!(self.out, "((")?; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0b5456294..ddaaf217a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -81,7 +81,7 @@ impl<'a> Display for TypeContext<'a> { first_time: false, ..*self }; - let class_name = match class.get_name(self.access) { + let class_name = match class.to_msl_name() { Some(name) => name, None => return Ok(()), }; @@ -93,7 +93,7 @@ impl<'a> Display for TypeContext<'a> { width: _, class, } => { - let class_name = match class.get_name(self.access) { + let class_name = match class.to_msl_name() { Some(name) => name, None => return Ok(()), }; @@ -105,7 +105,7 @@ impl<'a> Display for TypeContext<'a> { width: _, class, } => { - let class_name = match class.get_name(self.access) { + let class_name = match class.to_msl_name() { Some(name) => name, None => return Ok(()), }; @@ -157,7 +157,7 @@ impl<'a> Display for TypeContext<'a> { }; ("depth", msaa_str, crate::ScalarKind::Float, access) } - crate::ImageClass::Storage(format) => { + crate::ImageClass::Storage { format, .. } => { let access = if self .access .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) @@ -207,15 +207,26 @@ impl<'a> TypedGlobalVariable<'a> { fn try_fmt(&self, out: &mut W) -> BackendResult { let var = &self.module.global_variables[self.handle]; let name = &self.names[&NameKey::GlobalVariable(self.handle)]; + + let storage_access = match var.class { + crate::StorageClass::Storage { access } => access, + _ => match self.module.types[var.ty].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Storage { access, .. }, + .. + } => access, + _ => crate::StorageAccess::default(), + }, + }; let ty_name = TypeContext { handle: var.ty, arena: &self.module.types, names: self.names, - access: var.storage_access, + access: storage_access, first_time: false, }; - let (space, access, reference) = match var.class.get_name(var.storage_access) { + let (space, access, reference) = match var.class.to_msl_name() { Some(space) if self.reference => { let access = match var.class { crate::StorageClass::Private | crate::StorageClass::WorkGroup @@ -366,7 +377,7 @@ impl crate::StorageClass { fn needs_pass_through(&self) -> bool { match *self { crate::StorageClass::Uniform - | crate::StorageClass::Storage + | crate::StorageClass::Storage { .. } | crate::StorageClass::Private | crate::StorageClass::PushConstant | crate::StorageClass::Handle => true, @@ -374,16 +385,14 @@ impl crate::StorageClass { } } - fn get_name(&self, access: crate::StorageAccess) -> Option<&'static str> { - match *self { + fn to_msl_name(self) -> Option<&'static str> { + match self { Self::Handle => None, Self::Uniform | Self::PushConstant => Some("constant"), - //TODO: should still be "constant" for read-only buffers - Self::Storage => Some(if access.contains(crate::StorageAccess::STORE) { - "device" - } else { - "constant" - }), + Self::Storage { access } if access.contains(crate::StorageAccess::STORE) => { + Some("device") + } + Self::Storage { .. } => Some("constant"), Self::Private | Self::Function => Some("thread"), Self::WorkGroup => Some("threadgroup"), } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 5cb5d585f..aabd132d3 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1043,7 +1043,7 @@ impl<'w> BlockContext<'w> { }; let (query_op, level_id) = match class { - Ic::Storage(_) => (spirv::Op::ImageQuerySize, None), + Ic::Storage { .. } => (spirv::Op::ImageQuerySize, None), _ => { let level_id = match level { Some(expr) => self.cached[expr], diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index 72be7f7b5..2f4de389d 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -25,7 +25,7 @@ pub(super) fn map_storage_class(class: crate::StorageClass) -> spirv::StorageCla crate::StorageClass::Handle => spirv::StorageClass::UniformConstant, crate::StorageClass::Function => spirv::StorageClass::Function, crate::StorageClass::Private => spirv::StorageClass::Private, - crate::StorageClass::Storage => spirv::StorageClass::StorageBuffer, + crate::StorageClass::Storage { .. } => spirv::StorageClass::StorageBuffer, crate::StorageClass::Uniform => spirv::StorageClass::Uniform, crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, crate::StorageClass::PushConstant => spirv::StorageClass::PushConstant, diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 851952326..c20e714d9 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -234,7 +234,7 @@ impl super::Instruction { let (depth, multi, sampled) = match image_class { crate::ImageClass::Sampled { kind: _, multi } => (false, multi, true), crate::ImageClass::Depth { multi } => (true, multi, true), - crate::ImageClass::Storage(_) => (false, false, false), + crate::ImageClass::Storage { .. } => (false, false, false), }; instruction.add_operand(depth as u32); instruction.add_operand(arrayed as u32); @@ -242,7 +242,7 @@ impl super::Instruction { instruction.add_operand(if sampled { 1 } else { 2 }); let format = match image_class { - crate::ImageClass::Storage(format) => match format { + crate::ImageClass::Storage { format, .. } => match format { crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8, crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm, crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d164e6832..fa3a08d06 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -702,7 +702,7 @@ impl Writer { let kind = match class { crate::ImageClass::Sampled { kind, multi: _ } => kind, crate::ImageClass::Depth { multi: _ } => crate::ScalarKind::Float, - crate::ImageClass::Storage(format) => { + crate::ImageClass::Storage { format, .. } => { let required_caps: &[_] = match dim { crate::ImageDimension::D1 => &[spirv::Capability::Image1D], crate::ImageDimension::Cube => &[spirv::Capability::ImageCubeArray], @@ -1057,13 +1057,23 @@ impl Writer { use spirv::Decoration; - let access_decoration = match global_variable.storage_access { - crate::StorageAccess::LOAD => Some(Decoration::NonWritable), - crate::StorageAccess::STORE => Some(Decoration::NonReadable), - _ => None, + let storage_access = match global_variable.class { + crate::StorageClass::Storage { access } => Some(access), + _ => match ir_module.types[global_variable.ty].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Storage { access, .. }, + .. + } => Some(access), + _ => None, + }, }; - if let Some(decoration) = access_decoration { - self.decorate(id, decoration, &[]); + if let Some(storage_access) = storage_access { + if !storage_access.contains(crate::StorageAccess::LOAD) { + self.decorate(id, Decoration::NonReadable, &[]); + } + if !storage_access.contains(crate::StorageAccess::STORE) { + self.decorate(id, Decoration::NonWritable, &[]); + } } if let Some(ref res_binding) = global_variable.binding { @@ -1104,10 +1114,14 @@ impl Writer { ir_module: &crate::Module, mod_info: &ModuleInfo, ) -> Result<(), Error> { - let has_storage_buffers = ir_module - .global_variables - .iter() - .any(|(_, var)| var.class == crate::StorageClass::Storage); + let has_storage_buffers = + ir_module + .global_variables + .iter() + .any(|(_, var)| match var.class { + crate::StorageClass::Storage { .. } => true, + _ => false, + }); if self.physical_layout.version < 0x10300 && has_storage_buffers { // enable the storage buffer class on < SPV-1.3 Instruction::extension("SPV_KHR_storage_buffer_storage_class") diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index ae3b548f1..20d0cce1d 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -12,7 +12,6 @@ type BackendResult = Result<(), Error>; /// WGSL attribute /// https://gpuweb.github.io/gpuweb/wgsl/#attributes enum Attribute { - Access(crate::StorageAccess), Binding(u32), Block, BuiltIn(crate::BuiltIn), @@ -297,16 +296,6 @@ impl Writer { let mut attributes_str = String::new(); for (index, attribute) in attributes.iter().enumerate() { let attribute_str = match *attribute { - Attribute::Access(access) => { - let access_str = if access.is_all() { - "read_write" - } else if access.contains(crate::StorageAccess::LOAD) { - "read" - } else { - "write" - }; - format!("access({})", access_str) - } Attribute::Block => String::from("block"), Attribute::Location(id) => format!("location({})", id), Attribute::BuiltIn(builtin_attrib) => { @@ -491,10 +480,14 @@ impl Writer { if multi { "multisampled_" } else { "" }, String::from(""), ), - Ic::Storage(storage_format) => ( + Ic::Storage { format, access } => ( "storage_", "", - format!("<{}>", storage_format_str(storage_format)), + if access.contains(crate::StorageAccess::STORE) { + format!("<{},write>", storage_format_str(format)) + } else { + format!("<{}>", storage_format_str(format)) + }, ), }; let ty_str = format!( @@ -1329,10 +1322,7 @@ impl Writer { write!(self.out, "<{}>", storage_class)?; } write!(self.out, " {}: ", name)?; - // Write access attribute if present - if !global.storage_access.is_empty() { - self.write_attributes(&[Attribute::Access(global.storage_access)], true)?; - } + // Write global type self.write_type(module, global.ty)?; @@ -1586,7 +1576,11 @@ fn storage_class_str(storage_class: crate::StorageClass) -> Option<&'static str> match storage_class { Sc::Private => Some("private"), Sc::Uniform => Some("uniform"), - Sc::Storage => Some("storage"), + Sc::Storage { access } => Some(if access.contains(crate::StorageAccess::STORE) { + "storage,read_write" + } else { + "storage" + }), Sc::PushConstant => Some("push_constant"), Sc::WorkGroup => Some("workgroup"), Sc::Function | Sc::Handle => None, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 90c360e84..51d358d79 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -241,7 +241,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { StorageQualifier::StorageClass(StorageClass::Uniform), ), TokenValue::Buffer => TypeQualifier::StorageQualifier( - StorageQualifier::StorageClass(StorageClass::Storage), + StorageQualifier::StorageClass(StorageClass::Storage { + access: crate::StorageAccess::default(), + }), ), TokenValue::Sampling(s) => TypeQualifier::Sampling(s), TokenValue::PrecisionQualifier(p) => TypeQualifier::Precision(p), diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index c0aae1876..99a410a57 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,7 +1,7 @@ use crate::{ - Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, ImageClass, - Interpolation, LocalVariable, ScalarKind, StorageAccess, StorageClass, SwizzleComponent, Type, - TypeInner, VectorSize, + Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, Interpolation, + LocalVariable, ScalarKind, StorageAccess, StorageClass, SwizzleComponent, Type, TypeInner, + VectorSize, }; use super::ast::*; @@ -57,7 +57,6 @@ impl Program<'_> { binding: None, ty, init: None, - storage_access: StorageAccess::empty(), }); let idx = self.entry_args.len(); @@ -407,7 +406,7 @@ impl Program<'_> { match storage { StorageQualifier::StorageClass(StorageClass::PushConstant) | StorageQualifier::StorageClass(StorageClass::Uniform) - | StorageQualifier::StorageClass(StorageClass::Storage) => {} + | StorageQualifier::StorageClass(StorageClass::Storage { .. }) => {} _ => { return Err(ErrorKind::SemanticError( meta, @@ -445,7 +444,6 @@ impl Program<'_> { binding: None, ty, init, - storage_access: StorageAccess::empty(), }); let idx = self.entry_args.len(); @@ -490,29 +488,20 @@ impl Program<'_> { return Ok(GlobalOrConstant::Constant(init)); } - let (class, storage_access) = match self.module.types[ty].inner { - TypeInner::Image { class, .. } => ( - StorageClass::Handle, - if let ImageClass::Storage(_) = class { - // TODO: Add support for qualifiers such as readonly, - // writeonly and readwrite - StorageAccess::all() - } else { - StorageAccess::empty() - }, - ), - TypeInner::Sampler { .. } => (StorageClass::Handle, StorageAccess::empty()), + // TODO: Add support for qualifiers such as readonly, writeonly and readwrite + let class = match self.module.types[ty].inner { + TypeInner::Image { .. } => StorageClass::Handle, + TypeInner::Sampler { .. } => StorageClass::Handle, _ => { - if let StorageQualifier::StorageClass(StorageClass::Storage) = storage { - (StorageClass::Storage, StorageAccess::all()) + if let StorageQualifier::StorageClass(StorageClass::Storage { .. }) = storage { + StorageClass::Storage { + access: StorageAccess::all(), + } } else { - ( - match storage { - StorageQualifier::StorageClass(class) => class, - _ => StorageClass::Private, - }, - StorageAccess::empty(), - ) + match storage { + StorageQualifier::StorageClass(class) => class, + _ => StorageClass::Private, + } } } }; @@ -523,7 +512,6 @@ impl Program<'_> { binding, ty, init, - storage_access, }); if let Some(name) = name { diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 3bb35249a..aa2de029d 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -154,7 +154,9 @@ pub(super) fn map_storage_class(word: spirv::Word) -> Result Ec::Output, Some(Sc::Private) => Ec::Global(crate::StorageClass::Private), Some(Sc::UniformConstant) => Ec::Global(crate::StorageClass::Handle), - Some(Sc::StorageBuffer) => Ec::Global(crate::StorageClass::Storage), + Some(Sc::StorageBuffer) => Ec::Global(crate::StorageClass::Storage { + access: crate::StorageAccess::default(), + }), // we expect the `Storage` case to be filtered out before calling this function. Some(Sc::Uniform) => Ec::Global(crate::StorageClass::Uniform), Some(Sc::Workgroup) => Ec::Global(crate::StorageClass::WorkGroup), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 7cab0a833..44126857c 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2912,7 +2912,9 @@ impl> Parser { .lookup_storage_buffer_types .contains_key(&base_lookup_ty.handle) { - crate::StorageClass::Storage + crate::StorageClass::Storage { + access: crate::StorageAccess::default(), + } } else { match map_storage_class(storage_class)? { ExtendedClass::Global(class) => class, @@ -3161,7 +3163,10 @@ impl> Parser { let inner = crate::TypeInner::Image { class: if format != 0 { - crate::ImageClass::Storage(map_image_format(format)?) + crate::ImageClass::Storage { + format: map_image_format(format)?, + access: crate::StorageAccess::default(), + } } else { crate::ImageClass::Sampled { kind, @@ -3418,18 +3423,25 @@ impl> Parser { let original_ty = self.lookup_type.lookup(type_id)?.handle; let (effective_ty, is_storage) = match module.types[original_ty].inner { - crate::TypeInner::Pointer { base, class } => { - (base, class == crate::StorageClass::Storage) - } + crate::TypeInner::Pointer { base, class } => ( + base, + match class { + crate::StorageClass::Storage { .. } => true, + _ => false, + }, + ), crate::TypeInner::Image { - class: crate::ImageClass::Storage(_), + class: crate::ImageClass::Storage { .. }, .. } => (original_ty, true), _ => (original_ty, false), }; let (ext_class, type_storage_access) = match self.lookup_storage_buffer_types.get(&effective_ty) { - Some(&access) => (ExtendedClass::Global(crate::StorageClass::Storage), access), + Some(&access) => ( + ExtendedClass::Global(crate::StorageClass::Storage { access }), + access, + ), None => ( map_storage_class(storage_class)?, crate::StorageAccess::all(), @@ -3449,7 +3461,8 @@ impl> Parser { let (inner, var) = match ext_class { ExtendedClass::Global(class) => { - let storage_access = if is_storage { + // TODO actually apply decorators + let _storage_access = if is_storage { let mut access = type_storage_access; if dec.flags.contains(DecorationFlags::NON_READABLE) { access &= !crate::StorageAccess::LOAD; @@ -3468,7 +3481,6 @@ impl> Parser { class, ty: effective_ty, init, - storage_access, }; (Variable::Global, var) } @@ -3513,7 +3525,6 @@ impl> Parser { binding: None, ty: effective_ty, init: None, - storage_access: crate::StorageAccess::empty(), }; let inner = Variable::Input(crate::FunctionArgument { name: dec.name, @@ -3584,7 +3595,6 @@ impl> Parser { binding: None, ty: effective_ty, init, - storage_access: crate::StorageAccess::empty(), }; let inner = Variable::Output(crate::FunctionResult { ty: effective_ty, diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 6f7d1565b..2e47c0e0d 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -5,7 +5,9 @@ pub fn map_storage_class(word: &str, span: Span) -> Result Ok(crate::StorageClass::Private), "workgroup" => Ok(crate::StorageClass::WorkGroup), "uniform" => Ok(crate::StorageClass::Uniform), - "storage" => Ok(crate::StorageClass::Storage), + "storage" => Ok(crate::StorageClass::Storage { + access: crate::StorageAccess::default(), + }), "push_constant" => Ok(crate::StorageClass::PushConstant), _ => Err(Error::UnknownStorageClass(span)), } diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index b1c3038c8..9c6285524 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -347,12 +347,26 @@ impl<'a> Lexer<'a> { Ok(pair) } - pub(super) fn next_format_generic(&mut self) -> Result> { + // TODO relocate storage texture specifics + pub(super) fn next_format_generic( + &mut self, + ) -> Result<(crate::StorageFormat, crate::StorageAccess), Error<'a>> { self.expect(Token::Paren('<'))?; let (ident, ident_span) = self.next_ident_with_span()?; let format = conv::map_storage_format(ident, ident_span)?; + let access = if self.skip(Token::Separator(',')) { + let (raw, span) = self.next_ident_with_span()?; + match raw { + "read" => crate::StorageAccess::LOAD, + "write" => crate::StorageAccess::STORE, + "read_write" => crate::StorageAccess::all(), + _ => return Err(Error::UnknownAccess(span)), + } + } else { + crate::StorageAccess::LOAD + }; self.expect(Token::Paren('>'))?; - Ok(format) + Ok((format, access)) } pub(super) fn open_arguments(&mut self) -> Result<(), Error<'a>> { @@ -455,5 +469,23 @@ fn test_variable_decl() { Token::Paren('>'), Token::Separator(';'), ], - ) + ); + sub_test( + "var buffer: array;", + &[ + Token::Word("var"), + Token::Paren('<'), + Token::Word("storage"), + Token::Separator(','), + Token::Word("read_write"), + Token::Paren('>'), + Token::Word("buffer"), + Token::Separator(':'), + Token::Word("array"), + Token::Paren('<'), + Token::Word("u32"), + Token::Paren('>'), + Token::Separator(';'), + ], + ); } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index ba85ede39..b2de9644d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -467,8 +467,12 @@ impl crate::TypeInner { format!("<{}>", element_type) } crate::ImageClass::Depth { multi: _ } => String::new(), - crate::ImageClass::Storage(format) => { - format!("<{}>", format.to_wgsl()) + crate::ImageClass::Storage { format, access } => { + if access.contains(crate::StorageAccess::STORE) { + format!("<{},write>", format.to_wgsl()) + } else { + format!("<{}>", format.to_wgsl()) + } } }; @@ -529,7 +533,9 @@ mod type_inner_tests { let ptr = crate::TypeInner::Pointer { base: mytype2, - class: crate::StorageClass::Storage, + class: crate::StorageClass::Storage { + access: crate::StorageAccess::default(), + }, }; assert_eq!(ptr.to_wgsl(&types, &constants), "*MyType2"); @@ -836,7 +842,6 @@ impl Composition { #[derive(Default)] struct TypeAttributes { stride: Option, - access: crate::StorageAccess, } #[derive(Clone, Debug, PartialEq)] @@ -927,7 +932,6 @@ struct ParsedVariable<'a> { name: &'a str, class: Option, ty: Handle, - access: crate::StorageAccess, init: Option>, } @@ -1352,7 +1356,7 @@ impl Parser { None }; let index = match class { - crate::ImageClass::Storage(_) => None, + crate::ImageClass::Storage { .. } => None, // it's the MSAA index for multi-sampled, and LOD for the others crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => { lexer.expect(Token::Separator(','))?; @@ -1997,14 +2001,32 @@ impl Parser { ) -> Result, Error<'a>> { self.scopes.push(Scope::VariableDecl); let mut class = None; + if lexer.skip(Token::Paren('<')) { let (class_str, span) = lexer.next_ident_with_span()?; - class = Some(conv::map_storage_class(class_str, span)?); + class = Some(match class_str { + "storage" => { + let access = if lexer.skip(Token::Separator(',')) { + let (ident, span) = lexer.next_ident_with_span()?; + match ident { + "read" => crate::StorageAccess::LOAD, + "write" => crate::StorageAccess::STORE, + "read_write" => crate::StorageAccess::all(), + _ => return Err(Error::UnknownAccess(span)), + } + } else { + // defaulting to `read` + crate::StorageAccess::LOAD + }; + crate::StorageClass::Storage { access } + } + _ => conv::map_storage_class(class_str, span)?, + }); lexer.expect(Token::Paren('>'))?; } let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let (ty, access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let init = if lexer.skip(Token::Operation('=')) { let handle = self.parse_const_expression(lexer, type_arena, const_arena)?; @@ -2018,7 +2040,6 @@ impl Parser { name, class, ty, - access, init, }) } @@ -2363,43 +2384,43 @@ impl Parser { class: crate::ImageClass::Depth { multi: true }, }, "texture_storage_1d" => { - let format = lexer.next_format_generic()?; + let (format, access) = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, arrayed: false, - class: crate::ImageClass::Storage(format), + class: crate::ImageClass::Storage { format, access }, } } "texture_storage_1d_array" => { - let format = lexer.next_format_generic()?; + let (format, access) = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D1, arrayed: true, - class: crate::ImageClass::Storage(format), + class: crate::ImageClass::Storage { format, access }, } } "texture_storage_2d" => { - let format = lexer.next_format_generic()?; + let (format, access) = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: false, - class: crate::ImageClass::Storage(format), + class: crate::ImageClass::Storage { format, access }, } } "texture_storage_2d_array" => { - let format = lexer.next_format_generic()?; + let (format, access) = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: true, - class: crate::ImageClass::Storage(format), + class: crate::ImageClass::Storage { format, access }, } } "texture_storage_3d" => { - let format = lexer.next_format_generic()?; + let (format, access) = lexer.next_format_generic()?; crate::TypeInner::Image { dim: crate::ImageDimension::D3, arrayed: false, - class: crate::ImageClass::Storage(format), + class: crate::ImageClass::Storage { format, access }, } } _ => return Ok(None), @@ -2459,17 +2480,6 @@ impl Parser { self.scopes.push(Scope::Attribute); loop { match lexer.next() { - (Token::Word("access"), _) => { - lexer.expect(Token::Paren('('))?; - let (ident, span) = lexer.next_ident_with_span()?; - attribute.access = match ident { - "read" => crate::StorageAccess::LOAD, - "write" => crate::StorageAccess::STORE, - "read_write" => crate::StorageAccess::all(), - _ => return Err(Error::UnknownAccess(span)), - }; - lexer.expect(Token::Paren(')'))?; - } (Token::Word("stride"), _) => { lexer.expect(Token::Paren('('))?; let (stride, span) = lexer.capture_span(Lexer::next_uint_literal)?; @@ -2484,7 +2494,7 @@ impl Parser { self.scopes.pop(); } - let storage_access = attribute.access; + let storage_access = crate::StorageAccess::default(); let (name, name_span) = lexer.next_ident_with_span()?; let handle = self.parse_type_decl_name( lexer, @@ -3271,14 +3281,12 @@ impl Parser { Some(c) => c, None => match module.types[pvar.ty].inner { crate::TypeInner::Struct { .. } if binding.is_some() => { - if pvar.access.is_empty() { - crate::StorageClass::Uniform - } else { - crate::StorageClass::Storage - } + crate::StorageClass::Uniform } crate::TypeInner::Array { .. } if binding.is_some() => { - crate::StorageClass::Storage + crate::StorageClass::Storage { + access: crate::StorageAccess::LOAD, + } } crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { crate::StorageClass::Handle @@ -3292,7 +3300,6 @@ impl Parser { binding: binding.take(), ty: pvar.ty, init: pvar.init, - storage_access: pvar.access, }); lookup_global_expression .insert(pvar.name, crate::Expression::GlobalVariable(var_handle)); diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index b1c7a1232..4297eccde 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -21,8 +21,8 @@ fn parse_types() { parse_str("var t: texture_2d;").unwrap(); parse_str("var t: texture_cube_array;").unwrap(); parse_str("var t: texture_multisampled_2d;").unwrap(); - parse_str("var t: [[access(write)]] texture_storage_1d;").unwrap(); - parse_str("var t: [[access(read)]] texture_storage_3d;").unwrap(); + parse_str("var t: texture_storage_1d;").unwrap(); + parse_str("var t: texture_storage_3d;").unwrap(); } #[test] @@ -78,7 +78,7 @@ fn parse_struct() { [[size(32), align(8)]] z: vec3; }; struct Empty {}; - var s: [[access(read_write)]] Foo; + var s: Foo; ", ) .unwrap(); @@ -219,7 +219,7 @@ fn parse_texture_load() { .unwrap(); parse_str( " - var t: [[access(read)]] texture_storage_1d_array; + var t: texture_storage_1d_array; fn foo() { let r: vec4 = textureLoad(t, 10, 2); } @@ -232,7 +232,7 @@ fn parse_texture_load() { fn parse_texture_store() { parse_str( " - var t: [[access(write)]] texture_storage_2d; + var t: texture_storage_2d; fn foo() { textureStore(t, vec2(10, 20), vec4(0.0, 1.0, 2.0, 3.0)); } @@ -317,10 +317,10 @@ fn parse_array_length() { }; // this is used as both input and output for convenience [[group(0), binding(0)]] - var foo: [[access(read_write)]] Foo; + var foo: Foo; [[group(0), binding(1)]] - var bar: [[access(read)]] array; + var bar: array; fn foo() { var x: u32 = arrayLength(foo.data); @@ -330,3 +330,35 @@ fn parse_array_length() { ) .unwrap(); } + +#[test] +fn parse_storage_buffers() { + parse_str( + " + [[group(0), binding(0)]] + var foo: array; + ", + ) + .unwrap(); + parse_str( + " + [[group(0), binding(0)]] + var foo: array; + ", + ) + .unwrap(); + parse_str( + " + [[group(0), binding(0)]] + var foo: array; + ", + ) + .unwrap(); + parse_str( + " + [[group(0), binding(0)]] + var foo: array; + ", + ) + .unwrap(); +} diff --git a/src/lib.rs b/src/lib.rs index ad6821dac..2d8cf707c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -245,7 +245,7 @@ pub enum StorageClass { /// Uniform buffer data. Uniform, /// Storage buffer data, potentially mutable. - Storage, + Storage { access: StorageAccess }, /// Opaque handles, such as samplers and images. Handle, /// Push constants. @@ -473,7 +473,10 @@ pub enum ImageClass { multi: bool, }, /// Storage image. - Storage(StorageFormat), + Storage { + format: StorageFormat, + access: StorageAccess, + }, } /// A data type declared in the module. @@ -682,8 +685,6 @@ pub struct GlobalVariable { pub ty: Handle, /// Initial value for this variable. pub init: Option>, - /// Access bit for storage types of images and buffers. - pub storage_access: StorageAccess, } /// Variable defined at function level. diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index bb3fa0996..30af80d19 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -377,7 +377,7 @@ impl<'a> ResolveContext<'a> { width: 4, size: crate::VectorSize::Quad, }, - crate::ImageClass::Storage(format) => Ti::Vector { + crate::ImageClass::Storage { format, .. } => Ti::Vector { kind: format.into(), width: 4, size: crate::VectorSize::Quad, diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 2655736cb..3aab4fc04 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -434,9 +434,8 @@ impl FunctionInfo { // uniform data Sc::Uniform | Sc::PushConstant => true, // storage data is only uniform when read-only - Sc::Handle | Sc::Storage => { - !var.storage_access.contains(crate::StorageAccess::STORE) - } + Sc::Storage { access } => !access.contains(crate::StorageAccess::STORE), + Sc::Handle => false, }; Uniformity { non_uniform_result: if uniform { None } else { Some(handle) }, @@ -865,7 +864,6 @@ fn uniform_control_flow() { ty, class: crate::StorageClass::Handle, binding: None, - storage_access: crate::StorageAccess::STORE, }); let uniform_global = global_var_arena.append(crate::GlobalVariable { name: None, @@ -873,7 +871,6 @@ fn uniform_control_flow() { ty, binding: None, class: crate::StorageClass::Uniform, - storage_access: crate::StorageAccess::empty(), }); let mut expressions = Arena::new(); diff --git a/src/valid/function.rs b/src/valid/function.rs index b05c0e391..807db554f 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -475,11 +475,13 @@ impl super::Validator { } } match class { - crate::ImageClass::Storage(format) => crate::TypeInner::Vector { - kind: format.into(), - size: crate::VectorSize::Quad, - width: 4, - }, + crate::ImageClass::Storage { format, .. } => { + crate::TypeInner::Vector { + kind: format.into(), + size: crate::VectorSize::Quad, + width: 4, + } + } _ => { return Err(FunctionError::InvalidImageStore( ExpressionError::InvalidImageClass(class), diff --git a/src/valid/interface.rs b/src/valid/interface.rs index c4b4f83ae..22ba9becd 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -15,11 +15,6 @@ pub enum GlobalVariableError { InvalidUsage, #[error("Type isn't compatible with the storage class")] InvalidType, - #[error("Storage access {seen:?} exceeds the allowed {allowed:?}")] - InvalidStorageAccess { - allowed: crate::StorageAccess, - seen: crate::StorageAccess, - }, #[error("Type flags {seen:?} do not meet the required {required:?}")] MissingTypeFlags { required: TypeFlags, @@ -322,16 +317,15 @@ impl super::Validator { log::debug!("var {:?}", var); let type_info = &self.types[var.ty.index()]; - let (allowed_storage_access, required_type_flags, is_resource) = match var.class { + let (required_type_flags, is_resource) = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), - crate::StorageClass::Storage => { + crate::StorageClass::Storage { .. } => { if let Err((ty_handle, disalignment)) = type_info.storage_layout { if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); } } ( - crate::StorageAccess::all(), TypeFlags::DATA | TypeFlags::HOST_SHARED | TypeFlags::TOP_LEVEL, true, ) @@ -343,7 +337,6 @@ impl super::Validator { } } ( - crate::StorageAccess::empty(), TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED @@ -352,23 +345,15 @@ impl super::Validator { ) } crate::StorageClass::Handle => { - let access = match types[var.ty].inner { - crate::TypeInner::Image { - class: crate::ImageClass::Storage(_), - .. - } => crate::StorageAccess::all(), - crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { - crate::StorageAccess::empty() - } + match types[var.ty].inner { + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => {} _ => return Err(GlobalVariableError::InvalidType), }; - (access, TypeFlags::empty(), true) + (TypeFlags::empty(), true) + } + crate::StorageClass::Private | crate::StorageClass::WorkGroup => { + (TypeFlags::DATA | TypeFlags::SIZED, false) } - crate::StorageClass::Private | crate::StorageClass::WorkGroup => ( - crate::StorageAccess::empty(), - TypeFlags::DATA | TypeFlags::SIZED, - false, - ), crate::StorageClass::PushConstant => { if !self.capabilities.contains(Capabilities::PUSH_CONSTANT) { return Err(GlobalVariableError::UnsupportedCapability( @@ -376,20 +361,12 @@ impl super::Validator { )); } ( - crate::StorageAccess::LOAD, TypeFlags::DATA | TypeFlags::HOST_SHARED | TypeFlags::SIZED, false, ) } }; - if !allowed_storage_access.contains(var.storage_access) { - return Err(GlobalVariableError::InvalidStorageAccess { - seen: var.storage_access, - allowed: allowed_storage_access, - }); - } - if !type_info.flags.contains(required_type_flags) { return Err(GlobalVariableError::MissingTypeFlags { seen: type_info.flags, @@ -481,12 +458,12 @@ impl super::Validator { let allowed_usage = match var.class { crate::StorageClass::Function => unreachable!(), crate::StorageClass::Uniform => GlobalUse::READ | GlobalUse::QUERY, - crate::StorageClass::Storage => storage_usage(var.storage_access), + crate::StorageClass::Storage { access } => storage_usage(access), crate::StorageClass::Handle => match module.types[var.ty].inner { crate::TypeInner::Image { - class: crate::ImageClass::Storage(_), + class: crate::ImageClass::Storage { access, .. }, .. - } => storage_usage(var.storage_access), + } => storage_usage(access), _ => GlobalUse::READ | GlobalUse::QUERY, }, crate::StorageClass::Private | crate::StorageClass::WorkGroup => GlobalUse::all(), diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index e6f07a263..784bbea3c 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -8,7 +8,7 @@ struct Bar { }; [[group(0), binding(0)]] -var bar: [[access(read_write)]] Bar; +var bar: Bar; [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index baec5dd12..0f89f9a20 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -22,8 +22,8 @@ struct Particles { }; [[group(0), binding(0)]] var params : SimParams; -[[group(0), binding(1)]] var particlesSrc : [[access(read)]] Particles; -[[group(0), binding(2)]] var particlesDst : [[access(read_write)]] Particles; +[[group(0), binding(1)]] var particlesSrc : Particles; +[[group(0), binding(2)]] var particlesDst : Particles; // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp [[stage(compute), workgroup_size(64)]] diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index b291809df..1db3b9115 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -4,7 +4,7 @@ struct PrimeIndices { }; // this is used as both input and output for convenience [[group(0), binding(0)]] -var v_indices: [[access(read_write)]] PrimeIndices; +var v_indices: PrimeIndices; // The Collatz Conjecture states that for any integer n: // If n is even, n = n/2 diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 603c6d299..1a449d0c3 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -5,9 +5,9 @@ var image_multisampled_src: texture_multisampled_2d; [[group(0), binding(4)]] var image_depth_multisampled_src: texture_depth_multisampled_2d; [[group(0), binding(1)]] -var image_storage_src: [[access(read)]] texture_storage_2d; +var image_storage_src: texture_storage_2d; [[group(0), binding(2)]] -var image_dst: [[access(write)]] texture_storage_1d; +var image_dst: texture_storage_1d; [[stage(compute), workgroup_size(16)]] fn main( diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 61fca8578..d1286273c 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -18,7 +18,7 @@ struct Lights { }; [[group(0), binding(1)]] -var s_lights: [[access(read)]] Lights; +var s_lights: Lights; [[group(0), binding(2)]] var t_shadow: texture_depth_2d_array; [[group(0), binding(3)]] diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index f3b229d32..c802c970c 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -32,7 +32,11 @@ assignable_global: Some(1), ty: Value(Pointer( base: 3, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -372,7 +376,11 @@ assignable_global: Some(1), ty: Value(Pointer( base: 3, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -397,7 +405,11 @@ assignable_global: Some(1), ty: Value(Pointer( base: 2, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -425,7 +437,11 @@ assignable_global: Some(1), ty: Value(Pointer( base: 1, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -439,7 +455,11 @@ assignable_global: Some(1), ty: Value(Pointer( base: 2, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -467,7 +487,11 @@ assignable_global: Some(1), ty: Value(Pointer( base: 1, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index c084ca057..0adb46f2b 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -8,7 +8,7 @@ bits: 7, ), uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -88,7 +88,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -99,7 +99,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(5), requirements: ( bits: 0, ), @@ -110,7 +110,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -119,7 +119,11 @@ assignable_global: Some(4), ty: Value(Pointer( base: 21, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -1047,7 +1051,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -1070,7 +1074,7 @@ bits: 7, ), uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -1150,7 +1154,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -1161,7 +1165,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(5), requirements: ( bits: 0, ), @@ -1172,7 +1176,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -1181,7 +1185,11 @@ assignable_global: Some(4), ty: Value(Pointer( base: 21, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -1876,7 +1884,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -1885,7 +1893,11 @@ assignable_global: Some(4), ty: Value(Pointer( base: 20, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -1901,7 +1913,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -1910,12 +1922,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -1924,12 +1940,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 18, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -1951,7 +1971,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -1966,7 +1986,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -1999,7 +2019,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2008,7 +2028,11 @@ assignable_global: Some(4), ty: Value(Pointer( base: 20, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -2024,7 +2048,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2033,12 +2057,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2047,12 +2075,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2063,12 +2095,16 @@ size: None, kind: Float, width: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2082,7 +2118,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2091,7 +2127,11 @@ assignable_global: Some(4), ty: Value(Pointer( base: 20, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -2107,7 +2147,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2116,12 +2156,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2130,12 +2174,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2146,12 +2194,16 @@ size: None, kind: Float, width: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2165,7 +2217,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2174,7 +2226,11 @@ assignable_global: Some(4), ty: Value(Pointer( base: 20, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -2190,7 +2246,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2199,12 +2255,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2213,12 +2273,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2229,12 +2293,16 @@ size: None, kind: Float, width: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2248,7 +2316,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2360,7 +2428,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2371,7 +2439,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2410,7 +2478,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -2424,7 +2492,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2433,7 +2501,11 @@ assignable_global: Some(4), ty: Value(Pointer( base: 20, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -2449,7 +2521,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2458,12 +2530,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2472,12 +2548,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2488,12 +2568,16 @@ size: None, kind: Float, width: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2507,7 +2591,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2516,7 +2600,11 @@ assignable_global: Some(4), ty: Value(Pointer( base: 20, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -2532,7 +2620,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2541,12 +2629,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2555,12 +2647,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2571,12 +2667,16 @@ size: None, kind: Float, width: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2590,7 +2690,7 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2599,7 +2699,11 @@ assignable_global: Some(4), ty: Value(Pointer( base: 20, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( @@ -2615,7 +2719,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2624,12 +2728,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2638,12 +2746,16 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2654,12 +2766,16 @@ size: None, kind: Float, width: 4, - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), )), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2673,7 +2789,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2684,7 +2800,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -2761,7 +2877,7 @@ bits: 7, ), uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(4), requirements: ( bits: 0, ), diff --git a/tests/out/dot/quad.dot b/tests/out/dot/quad.dot index 618a76cfc..1318d9eb0 100644 --- a/tests/out/dot/quad.dot +++ b/tests/out/dot/quad.dot @@ -35,9 +35,9 @@ digraph Module { label="Fragment/'main'" node [ style=filled ] ep1_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] - ep1_e1 [ fillcolor="#ffffb3" label="[2] Global" ] + ep1_e1 [ color="#ffffb3" label="[2] Global" ] g1 -> ep1_e1 [fillcolor=gray] - ep1_e2 [ fillcolor="#ffffb3" label="[3] Global" ] + ep1_e2 [ color="#ffffb3" label="[3] Global" ] g0 -> ep1_e2 [fillcolor=gray] ep1_e3 [ color="#8dd3c7" label="[4] Argument[0]" ] ep1_e4 [ color="#80b1d3" label="[5] ImageSample" ] @@ -86,9 +86,9 @@ digraph Module { label="Fragment/'fs_extra'" node [ style=filled ] ep2_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] - ep2_e1 [ fillcolor="#ffffb3" label="[2] Global" ] + ep2_e1 [ color="#ffffb3" label="[2] Global" ] g1 -> ep2_e1 [fillcolor=gray] - ep2_e2 [ fillcolor="#ffffb3" label="[3] Global" ] + ep2_e2 [ color="#ffffb3" label="[3] Global" ] g0 -> ep2_e2 [fillcolor=gray] ep2_e3 [ fillcolor="#ffffb3" label="[4] Constant" ] ep2_e4 [ fillcolor="#ffffb3" label="[5] Constant" ] diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 4ade7db1a..9669e8259 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -2,7 +2,7 @@ Texture2D image_mipmapped_src : register(t0); Texture2DMS image_multisampled_src : register(t3); Texture2DMS image_depth_multisampled_src : register(t4); -Texture2D image_storage_src : register(t1); +RWTexture2D image_storage_src : register(u1); RWTexture1D image_dst : register(u2); Texture1D image_1d : register(t0); Texture2D image_2d : register(t1); @@ -19,22 +19,22 @@ struct ComputeInput_main { uint3 local_id1 : SV_GroupThreadID; }; -int2 NagaDimensions2D(Texture2D texture) +int2 NagaRWDimensions2D(RWTexture2D texture) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z); + texture.GetDimensions(ret.x, ret.y); return ret.xy; } [numthreads(16, 1, 1)] void main(ComputeInput_main computeinput_main) { - int2 dim = NagaDimensions2D(image_storage_src); + int2 dim = NagaRWDimensions2D(image_storage_src); int2 itc = ((dim * int2(computeinput_main.local_id1.xy)) % int2(10, 20)); uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(computeinput_main.local_id1.z))); uint4 value2_ = image_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)); float value3_ = image_depth_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)).x; - uint4 value4_ = image_storage_src.Load(int3(itc, 0)); + uint4 value4_ = image_storage_src.Load(itc); image_dst[itc.x] = (((value1_ + value2_) + uint4(uint(value3_).xxxx)) + value4_); return; } @@ -42,7 +42,7 @@ void main(ComputeInput_main computeinput_main) int NagaDimensions1D(Texture1D texture) { uint4 ret; - texture.GetDimensions(ret.x); + texture.GetDimensions(0, ret.x, ret.y); return ret.x; } diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index df144444c..c2e984f9a 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -76,16 +76,17 @@ global_variables: [ ( name: Some("v_indices"), - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), binding: Some(( group: 0, binding: 0, )), ty: 3, init: None, - storage_access: ( - bits: 3, - ), ), ], functions: [ diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index c4e09a6f2..4d5f19d5e 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -197,7 +197,11 @@ name: None, inner: Pointer( base: 21, - class: Storage, + class: Storage( + access: ( + bits: 0, + ), + ), ), ), ( @@ -776,9 +780,6 @@ )), ty: 56, init: None, - storage_access: ( - bits: 0, - ), ), ( name: Some("sampler_shadow"), @@ -789,9 +790,6 @@ )), ty: 57, init: None, - storage_access: ( - bits: 0, - ), ), ( name: Some("u_globals"), @@ -802,22 +800,20 @@ )), ty: 14, init: None, - storage_access: ( - bits: 0, - ), ), ( name: Some("s_lights"), - class: Storage, + class: Storage( + access: ( + bits: 3, + ), + ), binding: Some(( group: 0, binding: 1, )), ty: 21, init: None, - storage_access: ( - bits: 1, - ), ), ( name: Some("in_position_fs"), @@ -825,9 +821,6 @@ binding: None, ty: 4, init: None, - storage_access: ( - bits: 0, - ), ), ( name: Some("in_normal_fs"), @@ -835,9 +828,6 @@ binding: None, ty: 2, init: None, - storage_access: ( - bits: 0, - ), ), ( name: Some("out_color_fs"), @@ -845,9 +835,6 @@ binding: None, ty: 4, init: None, - storage_access: ( - bits: 0, - ), ), ], functions: [ diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index da2a09ec6..7dd458711 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -14,6 +14,7 @@ OpMemberDecorate %9 1 Offset 48 OpMemberDecorate %9 2 Offset 64 OpMemberDecorate %9 2 ColMajor OpMemberDecorate %9 2 MatrixStride 16 +OpDecorate %10 NonWritable OpDecorate %10 DescriptorSet 0 OpDecorate %10 Binding 0 %2 = OpTypeVoid diff --git a/tests/out/spv/pointer-access.spvasm b/tests/out/spv/pointer-access.spvasm index ef4b7bbce..6fc3bcc9a 100644 --- a/tests/out/spv/pointer-access.spvasm +++ b/tests/out/spv/pointer-access.spvasm @@ -12,6 +12,8 @@ OpDecorate %12 ArrayStride 4 OpDecorate %14 ArrayStride 4 OpDecorate %15 Block OpMemberDecorate %15 0 Offset 0 +OpDecorate %17 NonReadable +OpDecorate %17 NonWritable OpDecorate %17 DescriptorSet 0 OpDecorate %17 Binding 0 %2 = OpTypeVoid diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 0b1410dc9..21fde3265 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -4,7 +4,7 @@ struct PrimeIndices { }; [[group(0), binding(0)]] -var global: [[access(read_write)]] PrimeIndices; +var global: PrimeIndices; var gl_GlobalInvocationID: vec3; fn collatz_iterations(n: u32) -> u32 { diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 05c398dfe..5efb6e706 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -6,7 +6,7 @@ struct Bar { }; [[group(0), binding(0)]] -var bar: [[access(read_write)]] Bar; +var bar: Bar; [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 81aba559c..4546f1721 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -24,9 +24,9 @@ let NUM_PARTICLES: u32 = 1500u; [[group(0), binding(0)]] var params: SimParams; [[group(0), binding(1)]] -var particlesSrc: [[access(read)]] Particles; +var particlesSrc: Particles; [[group(0), binding(2)]] -var particlesDst: [[access(read_write)]] Particles; +var particlesDst: Particles; [[stage(compute), workgroup_size(64, 1, 1)]] fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index b5d1cbbcd..7d7a8dedc 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -4,7 +4,7 @@ struct PrimeIndices { }; [[group(0), binding(0)]] -var v_indices: [[access(read_write)]] PrimeIndices; +var v_indices: PrimeIndices; fn collatz_iterations(n_base: u32) -> u32 { var n: u32; diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 73c6f9bee..a888581b1 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -5,9 +5,9 @@ var image_multisampled_src: texture_multisampled_2d; [[group(0), binding(4)]] var image_depth_multisampled_src: texture_depth_multisampled_2d; [[group(0), binding(1)]] -var image_storage_src: [[access(read)]] texture_storage_2d; +var image_storage_src: texture_storage_2d; [[group(0), binding(2)]] -var image_dst: [[access(write)]] texture_storage_1d; +var image_dst: texture_storage_1d; [[group(0), binding(0)]] var image_1d: texture_1d; [[group(0), binding(1)]] diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index f1291003d..a0b5fbd9a 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -20,7 +20,7 @@ let c_max_lights: u32 = 10u; [[group(0), binding(0)]] var u_globals: Globals; [[group(0), binding(1)]] -var s_lights: [[access(read)]] Lights; +var s_lights: Lights; [[group(0), binding(2)]] var t_shadow: texture_depth_2d_array; [[group(0), binding(3)]] diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 86dfd1c16..48b1680f0 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -261,13 +261,13 @@ fn unknown_built_in() { fn unknown_access() { check( r#" - var x: [[access(unknown_access)]] array; + var x: array; "#, r#"error: unknown access: 'unknown_access' - ┌─ wgsl:2:38 + ┌─ wgsl:2:25 │ -2 │ var x: [[access(unknown_access)]] array; - │ ^^^^^^^^^^^^^^ unknown access +2 │ var x: array; + │ ^^^^^^^^^^^^^^ unknown access "#, ); @@ -345,13 +345,13 @@ fn unknown_type() { fn unknown_storage_format() { check( r#" - let storage: [[access(read)]] texture_storage_1d; + let storage: texture_storage_1d; "#, r#"error: unknown storage format: 'rgba' - ┌─ wgsl:2:62 + ┌─ wgsl:2:45 │ -2 │ let storage: [[access(read)]] texture_storage_1d; - │ ^^^^ unknown storage format +2 │ let storage: texture_storage_1d; + │ ^^^^ unknown storage format "#, ); From fa05f0d0d975d3f67f96ab5599965ad0d507a9db Mon Sep 17 00:00:00 2001 From: Jakob Hellermann Date: Thu, 29 Jul 2021 06:17:01 +0200 Subject: [PATCH 1160/2212] [glsl-out] split reflection_names into a map for types and another for globals (#1144) * split reflection_names into a map for types and another for globals * reflection_names_structs -> reflection_names_uniforms --- src/back/glsl/mod.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 7d15db988..fd346c3c9 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -312,7 +312,9 @@ pub struct Writer<'a, W> { /// (generated by a [`Namer`](crate::proc::Namer)) names: crate::FastHashMap, /// A map with all the names needed for reflections - reflection_names: crate::FastHashMap, String>, + reflection_names_uniforms: crate::FastHashMap, String>, + /// A map with the names of global variables needed for reflections + reflection_names_globals: crate::FastHashMap, String>, /// The selected entry point entry_point: &'a crate::EntryPoint, /// The index of the selected entry point @@ -366,7 +368,8 @@ impl<'a, W: Write> Writer<'a, W> { namer, features: FeaturesManager::new(), names, - reflection_names: crate::FastHashMap::default(), + reflection_names_uniforms: crate::FastHashMap::default(), + reflection_names_globals: crate::FastHashMap::default(), entry_point: &module.entry_points[ep_idx], entry_point_idx: ep_idx as u16, @@ -549,7 +552,7 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, " {};", global_name)?; writeln!(self.out)?; - self.reflection_names.insert(global.ty, global_name); + self.reflection_names_globals.insert(handle, global_name); } // glsl has no concept of samplers so we just ignore it TypeInner::Sampler { .. } => continue, @@ -1236,7 +1239,7 @@ impl<'a, W: Write> Writer<'a, W> { ); writeln!(self.out, "{} {{", block_name)?; - self.reflection_names.insert(handle, block_name); + self.reflection_names_uniforms.insert(handle, block_name); } else { writeln!(self.out, "struct {} {{", name)?; } @@ -2445,8 +2448,7 @@ impl<'a, W: Write> Writer<'a, W> { let mut uniforms = crate::FastHashMap::default(); for sampling in info.sampling_set.iter() { - let global = self.module.global_variables[sampling.image].clone(); - let tex_name = self.reflection_names[&global.ty].clone(); + let tex_name = self.reflection_names_globals[&sampling.image].clone(); match mappings.entry(tex_name) { Entry::Vacant(v) => { @@ -2471,7 +2473,7 @@ impl<'a, W: Write> Writer<'a, W> { match self.module.types[var.ty].inner { crate::TypeInner::Struct { .. } => match var.class { crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => { - let name = self.reflection_names[&var.ty].clone(); + let name = self.reflection_names_uniforms[&var.ty].clone(); uniforms.insert(handle, name); } _ => (), From e0efe344020673bd29f4220e770bb54077ede9db Mon Sep 17 00:00:00 2001 From: Arnaud Golfouse <53786772+arnaudgolfouse@users.noreply.github.com> Date: Fri, 30 Jul 2021 04:57:27 +0200 Subject: [PATCH 1161/2212] Fix typo in error message (#1150) --- src/front/wgsl/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b2de9644d..7440e2ca2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -163,7 +163,7 @@ impl<'a> Error<'a> { ExpectedToken::PrimaryExpression => "expression".to_string(), ExpectedToken::AttributeSeparator => "attribute separator (',') or an end of the attribute list (']]')".to_string(), ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(), - ExpectedToken::TypeAttribute => "type attribute ('access' or 'stride') or and of the attribute list (']]')".to_string(), + ExpectedToken::TypeAttribute => "type attribute ('access' or 'stride') or an end of the attribute list (']]')".to_string(), ExpectedToken::Statement => "statement".to_string(), ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), From e0e840b22c9b8a9ecddea7c096fc4b8f0a501c29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 28 Jul 2021 20:16:32 +0100 Subject: [PATCH 1162/2212] [glsl-in] Implement std140 and std430 layouts Structs are not yet implemented --- src/front/glsl/ast.rs | 2 +- src/front/glsl/mod.rs | 1 + src/front/glsl/offset.rs | 145 +++++++++++++++++++++++++++++++++++++++ src/front/glsl/parser.rs | 42 +++++++++--- 4 files changed, 180 insertions(+), 10 deletions(-) create mode 100644 src/front/glsl/offset.rs diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 9e5ec6781..fca6d4498 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1027,7 +1027,7 @@ pub enum StorageQualifier { Const, } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StructLayout { Std140, Std430, diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 474ab63f2..654715654 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -12,6 +12,7 @@ mod error; pub use error::ParseError; mod constants; mod functions; +mod offset; mod parser; #[cfg(test)] mod parser_tests; diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs new file mode 100644 index 000000000..f20c30c28 --- /dev/null +++ b/src/front/glsl/offset.rs @@ -0,0 +1,145 @@ +//! Module responsible for calculating the offset and span for types. +//! +//! There exists two types of layouts std140 and std430 (there's technically +//! two more layouts, shared and packed. Shared is not supported by spirv. Packed is +//! implementation dependent and for now it's just implemented as an alias to +//! std140). +//! +//! The OpenGl spec (the layout rules are defined by the OpenGl spec in section +//! 7.6.2.2 as opposed to the GLSL spec) uses the term basic machine units which are +//! equivalent to bytes. +use super::{ast::StructLayout, error::ErrorKind, SourceMetadata}; +use crate::{Arena, Constant, Handle, Type, TypeInner}; + +/// Struct with information needed for defining a struct member. +/// +/// Returned by [`calculate_offset`](calculate_offset) +#[derive(Debug)] +pub struct TypeAlignSpan { + /// The handle to the type, this might be the same handle passed to + /// [`calculate_offset`](calculate_offset) or a new such a new array type + /// with a different stride set. + pub ty: Handle, + /// The alignment required by the type. + pub align: u32, + /// The size of the type. + pub span: u32, +} + +/// Returns the type, alignment and span of a struct member according to a [`StructLayout`](StructLayout). +/// +/// The functions returns a [`TypeAlignSpan`](TypeAlignSpan) which has a `ty` member +/// this should be used as the struct member type because for example arrays may have to +/// change the stride and as such need to have a different type. +pub fn calculate_offset( + mut ty: Handle, + meta: SourceMetadata, + layout: StructLayout, + types: &mut Arena, + constants: &Arena, +) -> Result { + // When using the std430 storage layout, shader storage blocks will be laid out in buffer storage + // identically to uniform and shader storage blocks using the std140 layout, except + // that the base alignment and stride of arrays of scalars and vectors in rule 4 and of + // structures in rule 9 are not rounded up a multiple of the base alignment of a vec4. + + let (align, span) = match types[ty].inner { + // 1. If the member is a scalar consuming N basic machine units, + // the base alignment is N. + TypeInner::Scalar { width, .. } => (width as u32, width as u32), + // 2. If the member is a two- or four-component vector with components + // consuming N basic machine units, the base alignment is 2N or 4N, respectively. + // 3. If the member is a three-component vector with components consuming N + // basic machine units, the base alignment is 4N. + TypeInner::Vector { size, width, .. } => { + let val = match size { + crate::VectorSize::Tri => 4 * width as u32, + _ => size as u32 * width as u32, + }; + + (val, val) + } + // 4. If the member is an array of scalars or vectors, the base alignment and array + // stride are set to match the base alignment of a single array element, according + // to rules (1), (2), and (3), and rounded up to the base alignment of a vec4. + // TODO: Matrices array + TypeInner::Array { base, size, .. } => { + let info = calculate_offset(base, meta, layout, types, constants)?; + + let name = types[ty].name.clone(); + let mut align = info.align; + let mut stride = (align).max(info.span); + + // See comment at the beginning of the function + if StructLayout::Std430 != layout { + stride = align_up(stride, 16); + align = align_up(align, 16); + } + + let span = match size { + crate::ArraySize::Constant(s) => { + constants[s].to_array_length().unwrap_or(1) * stride + } + crate::ArraySize::Dynamic => stride, + }; + + ty = types.fetch_or_append(Type { + name, + inner: TypeInner::Array { + base: info.ty, + size, + stride, + }, + }); + + (align, span) + } + // 5. If the member is a column-major matrix with C columns and R rows, the + // matrix is stored identically to an array of C column vectors with R + // components each, according to rule (4) + // TODO: Row major matrices + TypeInner::Matrix { + columns, + rows, + width, + } => { + let mut align = match rows { + crate::VectorSize::Tri => (4 * width as u32), + _ => (rows as u32 * width as u32), + }; + + // See comment at the beginning of the function + if StructLayout::Std430 != layout { + align = align_up(align, 16); + } + + (align, align * columns as u32) + } + TypeInner::Struct { .. } => todo!(), + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Invalid struct member type".into(), + )) + } + }; + + Ok(TypeAlignSpan { ty, align, span }) +} + +/// Helper function used for aligning `value` to the next multiple of `align` +/// +/// # Notes: +/// - `align` must be a power of two. +/// - The returned value will be greater or equal to `value`. +/// # Examples: +/// ```ignore +/// assert_eq!(0, align_up(0, 16)); +/// assert_eq!(16, align_up(1, 16)); +/// assert_eq!(16, align_up(16, 16)); +/// assert_eq!(334, align_up(333, 2)); +/// assert_eq!(384, align_up(257, 128)); +/// ``` +pub fn align_up(value: u32, align: u32) -> u32 { + ((value.wrapping_sub(1)) & !(align - 1)).wrapping_add(align) +} diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 51d358d79..8068377f7 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -5,6 +5,7 @@ use super::{ }, error::ErrorKind, lex::Lexer, + offset, token::{SourceMetadata, Token, TokenValue}, variables::{GlobalOrConstant, VarDeclaration}, Program, @@ -146,7 +147,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let ty_name = self.expect_ident()?.0; self.expect(TokenValue::LeftBrace)?; let mut members = Vec::new(); - let span = self.parse_struct_declaration_list(&mut members)?; + let span = + self.parse_struct_declaration_list(&mut members, StructLayout::Std140)?; self.expect(TokenValue::RightBrace)?; let ty = self.program.module.types.append(Type { @@ -902,8 +904,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ty_name: String, mut meta: SourceMetadata, ) -> Result { + let layout = qualifiers + .iter() + .find_map(|&(ref qualifier, _)| match *qualifier { + TypeQualifier::Layout(layout) => Some(layout), + _ => None, + }) + .unwrap_or(StructLayout::Std140); + let mut members = Vec::new(); - let span = self.parse_struct_declaration_list(&mut members)?; + let span = self.parse_struct_declaration_list(&mut members, layout)?; self.expect(TokenValue::RightBrace)?; let mut ty = self.program.module.types.append(Type { @@ -977,30 +987,44 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } // TODO: Accept layout arguments - fn parse_struct_declaration_list(&mut self, members: &mut Vec) -> Result { + fn parse_struct_declaration_list( + &mut self, + members: &mut Vec, + layout: StructLayout, + ) -> Result { let mut span = 0; loop { // TODO: type_qualifier - let ty = self.parse_type_non_void()?.0; - let name = self.expect_ident()?.0; + let (ty, mut meta) = self.parse_type_non_void()?; + let (name, end_meta) = self.expect_ident()?; + + meta = meta.union(&end_meta); let array_specifier = self.parse_array_specifier()?; let ty = self.maybe_array(ty, array_specifier); self.expect(TokenValue::Semicolon)?; + let info = offset::calculate_offset( + ty, + meta, + layout, + &mut self.program.module.types, + &self.program.module.constants, + )?; + + span = offset::align_up(span, info.align); + members.push(StructMember { name: Some(name), - ty, + ty: info.ty, binding: None, offset: span, }); - span += self.program.module.types[ty] - .inner - .span(&self.program.module.constants); + span += info.span; if let TokenValue::RightBrace = self.expect_peek()?.value { break; From 56ce439ff5d6cf9119bfbda56ee7bc28b4a437ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 28 Jul 2021 20:48:34 +0100 Subject: [PATCH 1163/2212] [glsl-in] Implement layouting for composite types --- src/front/glsl/offset.rs | 34 +++++++++++++++++++++++++++- src/front/glsl/parser.rs | 4 ++++ tests/out/wgsl/246-collatz-comp.wgsl | 2 +- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index f20c30c28..6d1dee99c 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -115,7 +115,39 @@ pub fn calculate_offset( (align, align * columns as u32) } - TypeInner::Struct { .. } => todo!(), + TypeInner::Struct { + ref members, + top_level, + .. + } => { + let mut span = 0; + let mut align = 0; + let mut members = members.clone(); + let name = types[ty].name.clone(); + + for member in members.iter_mut() { + let info = calculate_offset(member.ty, meta, layout, types, constants)?; + + span = align_up(span, info.align); + align = align.max(info.align); + + member.ty = info.ty; + member.offset = span; + + span += info.span; + } + + ty = types.fetch_or_append(Type { + name, + inner: TypeInner::Struct { + top_level, + members, + span, + }, + }); + + (align, span) + } _ => { return Err(ErrorKind::SemanticError( meta, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 8068377f7..3f01e926c 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -993,6 +993,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { layout: StructLayout, ) -> Result { let mut span = 0; + let mut align = 0; loop { // TODO: type_qualifier @@ -1016,6 +1017,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { )?; span = offset::align_up(span, info.align); + align = align.max(info.align); members.push(StructMember { name: Some(name), @@ -1031,6 +1033,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } + span = offset::align_up(span, align); + Ok(span) } diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 21fde3265..3ae887639 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -1,6 +1,6 @@ [[block]] struct PrimeIndices { - indices: [[stride(4)]] array; + indices: [[stride(16)]] array; }; [[group(0), binding(0)]] From 65e915f9985e19183ee36d5acf299d35e6d91deb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 29 Jul 2021 22:37:24 +0100 Subject: [PATCH 1164/2212] [glsl-in] Implicit convert texture functions --- src/front/glsl/ast.rs | 3 +- src/front/glsl/functions.rs | 1444 +++++++++++++++++------------------ 2 files changed, 716 insertions(+), 731 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index fca6d4498..3deecf483 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -625,7 +625,8 @@ impl<'function> Context<'function> { } } HirExprKind::Call(call) if !lhs => { - let maybe_expr = program.function_call(self, body, call.kind, &call.args, meta)?; + let maybe_expr = program + .function_or_constructor_call(self, body, call.kind, &call.args, meta)?; return Ok((maybe_expr, meta)); } HirExprKind::Conditional { diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 126b4fadb..f6f6f5ea7 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -23,7 +23,7 @@ impl Program<'_> { }) } - pub fn function_call( + pub fn function_or_constructor_call( &mut self, ctx: &mut Context, body: &mut Block, @@ -255,745 +255,729 @@ impl Program<'_> { Ok(Some(h)) } FunctionCallKind::Function(name) => { - match name.as_str() { - "sampler1D" - | "sampler1DArray" - | "sampler2D" - | "sampler2DArray" - | "sampler2DMS" - | "sampler2DMSArray" - | "sampler3D" - | "samplerCube" - | "samplerCubeArray" - | "sampler1DShadow" - | "sampler1DArrayShadow" - | "sampler2DShadow" - | "sampler2DArrayShadow" - | "samplerCubeShadow" - | "samplerCubeArrayShadow" => { - if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); - } - ctx.samplers.insert(args[0].0, args[1].0); - Ok(Some(args[0].0)) - } - "texture" => { - if !(2..=3).contains(&args.len()) { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); - } - if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(Some(ctx.add_expression( - Expression::ImageSample { - image: args[0].0, - sampler, - coordinate: args[1].0, - array_index: None, //TODO - offset: None, //TODO - level: args.get(2).map_or(SampleLevel::Auto, |&(expr, _)| { - SampleLevel::Bias(expr) - }), - depth_ref: None, - }, - body, - ))) - } else { - Err(ErrorKind::SemanticError(meta, "Bad call to texture".into())) - } - } - "textureLod" => { - if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); - } - let exact = ctx.add_expression( - Expression::As { - kind: crate::ScalarKind::Float, - expr: args[2].0, - convert: Some(4), - }, - body, - ); - if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(Some(ctx.add_expression( - Expression::ImageSample { - image: args[0].0, - sampler, - coordinate: args[1].0, - array_index: None, //TODO - offset: None, //TODO - level: SampleLevel::Exact(exact), - depth_ref: None, - }, - body, - ))) - } else { - Err(ErrorKind::SemanticError( - meta, - "Bad call to textureLod".into(), - )) - } - } - "textureProj" => { - if !(2..=3).contains(&args.len()) { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); - } - let level = args.get(2).map_or(SampleLevel::Auto, |&(expr, _)| { - let exact = ctx.add_expression( - Expression::As { - kind: ScalarKind::Float, - expr, - convert: Some(4), - }, - body, - ); - SampleLevel::Bias(exact) - }); - let dim = match *self.resolve_type(ctx, args[0].0, args[0].1)? { - TypeInner::Image { dim, .. } => match dim { - crate::ImageDimension::D1 => 1, - crate::ImageDimension::D2 => 2, - crate::ImageDimension::D3 => 3, - crate::ImageDimension::Cube => { - return Err(ErrorKind::SemanticError( - meta, - "textureProj doesn't accept cube texture".into(), - )) - } - }, - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Bad call to textureProj".into(), - )) - } - }; - match *self.resolve_type(ctx, args[1].0, args[1].1)? { - TypeInner::Vector { size, .. } => { - if !(size as usize + 1 == dim || size == VectorSize::Quad) { - return Err(ErrorKind::SemanticError( - meta, - "Bad call to textureProj".into(), - )); - } - } - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Bad call to textureProj".into(), - )) - } - } - if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(Some(ctx.add_expression( - Expression::ImageSample { - image: args[0].0, - sampler, - coordinate: args[1].0, - array_index: None, //TODO - offset: None, //TODO - level, - depth_ref: None, - }, - body, - ))) - } else { - Err(ErrorKind::SemanticError( - meta, - "Bad call to textureProj".into(), - )) - } - } - "textureSize" => { - if !(1..=2).contains(&args.len()) { - return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); - } + self.function_call(ctx, body, name, args, raw_args, meta) + } + } + } - Ok(Some(ctx.add_expression( - Expression::ImageQuery { + fn function_call( + &mut self, + ctx: &mut Context, + body: &mut Block, + name: String, + mut args: Vec<(Handle, SourceMetadata)>, + raw_args: &[Handle], + meta: SourceMetadata, + ) -> Result>, ErrorKind> { + match name.as_str() { + "sampler1D" + | "sampler1DArray" + | "sampler2D" + | "sampler2DArray" + | "sampler2DMS" + | "sampler2DMSArray" + | "sampler3D" + | "samplerCube" + | "samplerCubeArray" + | "sampler1DShadow" + | "sampler1DArrayShadow" + | "sampler2DShadow" + | "sampler2DArrayShadow" + | "samplerCubeShadow" + | "samplerCubeArrayShadow" => { + if args.len() != 2 { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + ctx.samplers.insert(args[0].0, args[1].0); + Ok(Some(args[0].0)) + } + "texture" => { + if !(2..=3).contains(&args.len()) { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + let arg_1 = &mut args[1]; + ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; + if let Some(&mut (ref mut expr, meta)) = args.get_mut(2) { + ctx.implicit_conversion(self, expr, meta, ScalarKind::Float, 4)?; + } + if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { + Ok(Some( + ctx.add_expression( + Expression::ImageSample { image: args[0].0, - query: ImageQuery::Size { - level: args.get(1).map(|e| e.0), - }, + sampler, + coordinate: args[1].0, + array_index: None, //TODO + offset: None, + level: args.get(2).map_or(SampleLevel::Auto, |&(expr, _)| { + SampleLevel::Bias(expr) + }), + depth_ref: None, }, body, - ))) - } - "texelFetch" => { - if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); - } - if ctx.samplers.get(&args[0].0).is_some() { - let (arrayed, dims) = - match *self.resolve_type(ctx, args[0].0, args[0].1)? { - TypeInner::Image { arrayed, dim, .. } => (arrayed, dim), - _ => (false, crate::ImageDimension::D1), - }; - - let (coordinate, array_index) = if arrayed { - ( - match dims { - crate::ImageDimension::D1 => ctx.add_expression( - Expression::AccessIndex { - base: args[1].0, - index: 0, - }, - body, - ), - crate::ImageDimension::D2 => ctx.add_expression( - Expression::Swizzle { - size: VectorSize::Bi, - vector: args[1].0, - pattern: SwizzleComponent::XYZW, - }, - body, - ), - _ => ctx.add_expression( - Expression::Swizzle { - size: VectorSize::Tri, - vector: args[1].0, - pattern: SwizzleComponent::XYZW, - }, - body, - ), - }, - Some(ctx.add_expression( - Expression::AccessIndex { - base: args[1].0, - index: match dims { - crate::ImageDimension::D1 => 1, - crate::ImageDimension::D2 => 2, - crate::ImageDimension::D3 => 3, - crate::ImageDimension::Cube => 2, - }, - }, - body, - )), - ) - } else { - (args[1].0, None) - }; - - Ok(Some(ctx.add_expression( - Expression::ImageLoad { - image: args[0].0, - coordinate, - array_index, - index: Some(args[2].0), - }, - body, - ))) - } else { - Err(ErrorKind::SemanticError( - meta, - "Bad call to texelFetch".into(), - )) - } - } - "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" - | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" - | "normalize" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" - | "log" | "log2" | "length" | "determinant" | "bitCount" - | "bitfieldReverse" => { - if args.len() != 1 { - return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); - } - Ok(Some(ctx.add_expression( - Expression::Math { - fun: match name.as_str() { - "ceil" => MathFunction::Ceil, - "round" => MathFunction::Round, - "floor" => MathFunction::Floor, - "fract" => MathFunction::Fract, - "trunc" => MathFunction::Trunc, - "sin" => MathFunction::Sin, - "abs" => MathFunction::Abs, - "sqrt" => MathFunction::Sqrt, - "inversesqrt" => MathFunction::InverseSqrt, - "exp" => MathFunction::Exp, - "exp2" => MathFunction::Exp2, - "sign" => MathFunction::Sign, - "transpose" => MathFunction::Transpose, - "inverse" => MathFunction::Inverse, - "normalize" => MathFunction::Normalize, - "sinh" => MathFunction::Sinh, - "cos" => MathFunction::Cos, - "cosh" => MathFunction::Cosh, - "tan" => MathFunction::Tan, - "tanh" => MathFunction::Tanh, - "acos" => MathFunction::Acos, - "asin" => MathFunction::Asin, - "log" => MathFunction::Log, - "log2" => MathFunction::Log2, - "length" => MathFunction::Length, - "determinant" => MathFunction::Determinant, - "bitCount" => MathFunction::CountOneBits, - "bitfieldReverse" => MathFunction::ReverseBits, - _ => unreachable!(), - }, - arg: args[0].0, - arg1: None, - arg2: None, - }, - body, - ))) - } - "atan" => { - let expr = match args.len() { - 1 => Expression::Math { - fun: MathFunction::Atan, - arg: args[0].0, - arg1: None, - arg2: None, - }, - 2 => Expression::Math { - fun: MathFunction::Atan2, - arg: args[0].0, - arg1: Some(args[1].0), - arg2: None, - }, - _ => { - return Err(ErrorKind::wrong_function_args( - name, - 2, - args.len(), - meta, - )) - } - }; - Ok(Some(ctx.add_expression(expr, body))) - } - "mod" => { - if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); - } - - let (mut left, left_meta) = args[0]; - let (mut right, right_meta) = args[1]; - - ctx.binary_implicit_conversion( - self, &mut left, left_meta, &mut right, right_meta, - )?; - - Ok(Some(ctx.add_expression( - Expression::Binary { - op: BinaryOperator::Modulo, - left, - right, - }, - body, - ))) - } - "max" => { - if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); - } - - let (mut arg0, arg0_meta) = args[0]; - let (mut arg1, arg1_meta) = args[1]; - - let arg0_size = match *self.resolve_type(ctx, arg0, arg0_meta)? { - TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - let arg1_size = match *self.resolve_type(ctx, arg1, arg1_meta)? { - TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - - ctx.binary_implicit_conversion( - self, &mut arg0, arg0_meta, &mut arg1, arg1_meta, - )?; - - ctx.implicit_splat(self, &mut arg0, arg0_meta, arg1_size)?; - ctx.implicit_splat(self, &mut arg1, arg1_meta, arg0_size)?; - - Ok(Some(ctx.add_expression( - Expression::Math { - fun: MathFunction::Max, - arg: arg0, - arg1: Some(arg1), - arg2: None, - }, - body, - ))) - } - "pow" | "dot" | "min" | "reflect" | "cross" | "outerProduct" | "distance" - | "step" | "modf" | "frexp" | "ldexp" => { - if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); - } - - let (mut arg0, arg0_meta) = args[0]; - let (mut arg1, arg1_meta) = args[1]; - - ctx.binary_implicit_conversion( - self, &mut arg0, arg0_meta, &mut arg1, arg1_meta, - )?; - - Ok(Some(ctx.add_expression( - Expression::Math { - fun: match name.as_str() { - "pow" => MathFunction::Pow, - "dot" => MathFunction::Dot, - "min" => MathFunction::Min, - "reflect" => MathFunction::Reflect, - "cross" => MathFunction::Cross, - "outerProduct" => MathFunction::Outer, - "distance" => MathFunction::Distance, - "step" => MathFunction::Step, - "modf" => MathFunction::Modf, - "frexp" => MathFunction::Frexp, - "ldexp" => MathFunction::Ldexp, - _ => unreachable!(), - }, - arg: arg0, - arg1: Some(arg1), - arg2: None, - }, - body, - ))) - } - "mix" => { - if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); - } - - let (mut arg, arg_meta) = args[0]; - let (mut arg1, arg1_meta) = args[1]; - let (mut selector, selector_meta) = args[2]; - - ctx.binary_implicit_conversion( - self, &mut arg, arg_meta, &mut arg1, arg1_meta, - )?; - ctx.binary_implicit_conversion( - self, - &mut arg, - arg_meta, - &mut selector, - selector_meta, - )?; - - let is_vector = match *self.resolve_type(ctx, selector, selector_meta)? { - TypeInner::Vector { .. } => true, - _ => false, - }; - match *self.resolve_type(ctx, args[0].0, args[0].1)? { - TypeInner::Vector { size, .. } if !is_vector => { - selector = ctx.add_expression( - Expression::Splat { - size, - value: selector, - }, - body, - ) - } - _ => {} - }; - - let expr = match self - .resolve_type(ctx, selector, selector_meta)? - .scalar_kind() - { - Some(ScalarKind::Bool) => Expression::Select { - condition: selector, - accept: arg, - reject: arg1, - }, - _ => Expression::Math { - fun: MathFunction::Mix, - arg, - arg1: Some(arg1), - arg2: Some(selector), - }, - }; - - Ok(Some(ctx.add_expression(expr, body))) - } - "clamp" => { - if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); - } - - let (mut arg0, arg0_meta) = args[0]; - let (mut arg1, arg1_meta) = args[1]; - let (mut arg2, arg2_meta) = args[2]; - - let vector_size = match *(self.resolve_type(ctx, arg0, arg0_meta)?) { - TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - - ctx.binary_implicit_conversion( - self, &mut arg0, arg0_meta, &mut arg1, arg1_meta, - )?; - ctx.binary_implicit_conversion( - self, &mut arg1, arg1_meta, &mut arg2, arg2_meta, - )?; - ctx.binary_implicit_conversion( - self, &mut arg2, arg2_meta, &mut arg0, arg0_meta, - )?; - - ctx.implicit_splat(self, &mut arg1, arg1_meta, vector_size)?; - ctx.implicit_splat(self, &mut arg2, arg2_meta, vector_size)?; - - Ok(Some(ctx.add_expression( - Expression::Math { - fun: MathFunction::Clamp, - arg: arg0, - arg1: Some(arg1), - arg2: Some(arg2), - }, - body, - ))) - } - "faceforward" | "refract" | "fma" | "smoothstep" => { - if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); - } - Ok(Some(ctx.add_expression( - Expression::Math { - fun: match name.as_str() { - "faceforward" => MathFunction::FaceForward, - "refract" => MathFunction::Refract, - "fma" => MathFunction::Fma, - "smoothstep" => MathFunction::SmoothStep, - _ => unreachable!(), - }, - arg: args[0].0, - arg1: Some(args[1].0), - arg2: Some(args[2].0), - }, - body, - ))) - } - "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" - | "notEqual" => { - if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); - } - Ok(Some(ctx.add_expression( - Expression::Binary { - op: match name.as_str() { - "lessThan" => BinaryOperator::Less, - "greaterThan" => BinaryOperator::Greater, - "lessThanEqual" => BinaryOperator::LessEqual, - "greaterThanEqual" => BinaryOperator::GreaterEqual, - "equal" => BinaryOperator::Equal, - "notEqual" => BinaryOperator::NotEqual, - _ => unreachable!(), - }, - left: args[0].0, - right: args[1].0, - }, - body, - ))) - } - "isinf" | "isnan" | "all" | "any" => { - let fun = match name.as_str() { - "isinf" => RelationalFunction::IsInf, - "isnan" => RelationalFunction::IsNan, - "all" => RelationalFunction::All, - "any" => RelationalFunction::Any, - _ => unreachable!(), - }; - - Ok(Some( - self.parse_relational_fun(ctx, body, name, &args, fun, meta)?, - )) - } - _ => { - let declarations = self.lookup_function.get(&name).ok_or_else(|| { - ErrorKind::SemanticError( - meta, - format!("Unknown function '{}'", name).into(), - ) - })?; - - let mut maybe_decl = None; - let mut ambiguous = false; - - 'outer: for decl in declarations { - if args.len() != decl.parameters.len() { - continue; - } - - let mut exact = true; - - for (decl_arg, call_arg) in decl.parameters.iter().zip(args.iter()) { - let decl_inner = &self.module.types[*decl_arg].inner; - let call_inner = self.resolve_type(ctx, call_arg.0, call_arg.1)?; - - if decl_inner == call_inner { - continue; - } - - exact = false; - - let (decl_kind, call_kind) = match (decl_inner, call_inner) { - ( - &TypeInner::Scalar { - kind: decl_kind, .. - }, - &TypeInner::Scalar { - kind: call_kind, .. - }, - ) => (decl_kind, call_kind), - ( - &TypeInner::Vector { - kind: decl_kind, - size: decl_size, - .. - }, - &TypeInner::Vector { - kind: call_kind, - size: call_size, - .. - }, - ) if decl_size == call_size => (decl_kind, call_kind), - ( - &TypeInner::Matrix { - rows: decl_rows, - columns: decl_columns, - .. - }, - &TypeInner::Matrix { - rows: call_rows, - columns: call_columns, - .. - }, - ) if decl_columns == call_columns && decl_rows == call_rows => { - (ScalarKind::Float, ScalarKind::Float) - } - _ => continue 'outer, - }; - - match (type_power(decl_kind), type_power(call_kind)) { - (Some(decl_power), Some(call_power)) - if decl_power > call_power => {} - _ => continue 'outer, - } - } - - if exact { - maybe_decl = Some(decl); - ambiguous = false; - break; - } else if maybe_decl.is_some() { - ambiguous = true; - } else { - maybe_decl = Some(decl) - } - } - - if ambiguous { + ), + )) + } else { + Err(ErrorKind::SemanticError(meta, "Bad call to texture".into())) + } + } + "textureLod" => { + if args.len() != 3 { + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + } + let arg_1 = &mut args[1]; + ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; + let arg_2 = &mut args[2]; + ctx.implicit_conversion(self, &mut arg_2.0, arg_2.1, ScalarKind::Float, 4)?; + if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { + Ok(Some(ctx.add_expression( + Expression::ImageSample { + image: args[0].0, + sampler, + coordinate: args[1].0, + array_index: None, //TODO + offset: None, + level: SampleLevel::Exact(args[2].0), + depth_ref: None, + }, + body, + ))) + } else { + Err(ErrorKind::SemanticError( + meta, + "Bad call to textureLod".into(), + )) + } + } + "textureProj" => { + if !(2..=3).contains(&args.len()) { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + let arg_1 = &mut args[1]; + ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; + if let Some(&mut (ref mut expr, meta)) = args.get_mut(2) { + ctx.implicit_conversion(self, expr, meta, ScalarKind::Float, 4)?; + } + let level = args + .get(2) + .map_or(SampleLevel::Auto, |&(expr, _)| SampleLevel::Bias(expr)); + let dim = match *self.resolve_type(ctx, args[0].0, args[0].1)? { + TypeInner::Image { dim, .. } => match dim { + crate::ImageDimension::D1 => 1, + crate::ImageDimension::D2 => 2, + crate::ImageDimension::D3 => 3, + crate::ImageDimension::Cube => { return Err(ErrorKind::SemanticError( meta, - format!("Ambiguous best function for '{}'", name).into(), + "textureProj doesn't accept cube texture".into(), + )) + } + }, + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Bad call to textureProj".into(), + )) + } + }; + match *self.resolve_type(ctx, args[1].0, args[1].1)? { + TypeInner::Vector { size, .. } => { + if !(size as usize + 1 == dim || size == VectorSize::Quad) { + return Err(ErrorKind::SemanticError( + meta, + "Bad call to textureProj".into(), )); } - - let decl = maybe_decl.ok_or_else(|| { - ErrorKind::SemanticError( - meta, - format!("Unknown function '{}'", name).into(), - ) - })?; - - let qualifiers = decl.qualifiers.clone(); - let parameters = decl.parameters.clone(); - let function = decl.handle; - let is_void = decl.void; - - let mut arguments = Vec::with_capacity(args.len()); - let mut proxy_writes = Vec::new(); - for (qualifier, (expr, parameter)) in qualifiers - .iter() - .zip(raw_args.iter().zip(parameters.iter())) - { - let (mut handle, meta) = - ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?; - - if let TypeInner::Vector { size, kind, width } = - *self.resolve_type(ctx, handle, meta)? - { - if qualifier.is_lhs() - && matches!( - *ctx.get_expression(handle), - Expression::Swizzle { .. } - ) - { - let ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { size, kind, width }, - }); - let temp_var = ctx.locals.append(LocalVariable { - name: None, - ty, - init: None, - }); - let temp_expr = ctx - .add_expression(Expression::LocalVariable(temp_var), body); - - body.push(Statement::Store { - pointer: temp_expr, - value: handle, - }); - - arguments.push(temp_expr); - proxy_writes.push((*expr, temp_expr)); - continue; - } - } - - let scalar_components = - scalar_components(&self.module.types[*parameter].inner); - if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut handle, meta, kind, width)?; - } - - arguments.push(handle) - } - - ctx.emit_flush(body); - - let result = if !is_void { - Some(ctx.add_expression(Expression::Call(function), body)) - } else { - None - }; - - body.push(crate::Statement::Call { - function, - arguments, - result, - }); - - ctx.emit_start(); - for (tgt, pointer) in proxy_writes { - let temp_ref = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Variable(VariableReference { - expr: pointer, - load: true, - mutable: true, - entry_arg: None, - }), - meta, - }); - let assign = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Assign { - tgt, - value: temp_ref, - }, - meta, - }); - - let _ = ctx.lower_expect(self, assign, false, body)?; - } - ctx.emit_flush(body); - ctx.emit_start(); - - Ok(result) + } + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Bad call to textureProj".into(), + )) } } + if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { + Ok(Some(ctx.add_expression( + Expression::ImageSample { + image: args[0].0, + sampler, + coordinate: args[1].0, + array_index: None, //TODO + offset: None, + level, + depth_ref: None, + }, + body, + ))) + } else { + Err(ErrorKind::SemanticError( + meta, + "Bad call to textureProj".into(), + )) + } + } + "textureSize" => { + if !(1..=2).contains(&args.len()) { + return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); + } + if let Some(&mut (ref mut expr, meta)) = args.get_mut(1) { + ctx.implicit_conversion(self, expr, meta, ScalarKind::Sint, 4)?; + } + Ok(Some(ctx.add_expression( + Expression::ImageQuery { + image: args[0].0, + query: ImageQuery::Size { + level: args.get(1).map(|e| e.0), + }, + }, + body, + ))) + } + "texelFetch" => { + if args.len() != 3 { + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + } + let arg_1 = &mut args[1]; + ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Sint, 4)?; + let arg_2 = &mut args[2]; + ctx.implicit_conversion(self, &mut arg_2.0, arg_2.1, ScalarKind::Sint, 4)?; + if ctx.samplers.get(&args[0].0).is_some() { + let (arrayed, dims) = match *self.resolve_type(ctx, args[0].0, args[0].1)? { + TypeInner::Image { arrayed, dim, .. } => (arrayed, dim), + _ => (false, crate::ImageDimension::D1), + }; + + let (coordinate, array_index) = if arrayed { + ( + match dims { + crate::ImageDimension::D1 => ctx.add_expression( + Expression::AccessIndex { + base: args[1].0, + index: 0, + }, + body, + ), + crate::ImageDimension::D2 => ctx.add_expression( + Expression::Swizzle { + size: VectorSize::Bi, + vector: args[1].0, + pattern: SwizzleComponent::XYZW, + }, + body, + ), + _ => ctx.add_expression( + Expression::Swizzle { + size: VectorSize::Tri, + vector: args[1].0, + pattern: SwizzleComponent::XYZW, + }, + body, + ), + }, + Some(ctx.add_expression( + Expression::AccessIndex { + base: args[1].0, + index: match dims { + crate::ImageDimension::D1 => 1, + crate::ImageDimension::D2 => 2, + crate::ImageDimension::D3 => 3, + crate::ImageDimension::Cube => 2, + }, + }, + body, + )), + ) + } else { + (args[1].0, None) + }; + + Ok(Some(ctx.add_expression( + Expression::ImageLoad { + image: args[0].0, + coordinate, + array_index, + index: Some(args[2].0), + }, + body, + ))) + } else { + Err(ErrorKind::SemanticError( + meta, + "Bad call to texelFetch".into(), + )) + } + } + "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" + | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" | "normalize" + | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" | "log" | "log2" + | "length" | "determinant" | "bitCount" | "bitfieldReverse" => { + if args.len() != 1 { + return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); + } + Ok(Some(ctx.add_expression( + Expression::Math { + fun: match name.as_str() { + "ceil" => MathFunction::Ceil, + "round" => MathFunction::Round, + "floor" => MathFunction::Floor, + "fract" => MathFunction::Fract, + "trunc" => MathFunction::Trunc, + "sin" => MathFunction::Sin, + "abs" => MathFunction::Abs, + "sqrt" => MathFunction::Sqrt, + "inversesqrt" => MathFunction::InverseSqrt, + "exp" => MathFunction::Exp, + "exp2" => MathFunction::Exp2, + "sign" => MathFunction::Sign, + "transpose" => MathFunction::Transpose, + "inverse" => MathFunction::Inverse, + "normalize" => MathFunction::Normalize, + "sinh" => MathFunction::Sinh, + "cos" => MathFunction::Cos, + "cosh" => MathFunction::Cosh, + "tan" => MathFunction::Tan, + "tanh" => MathFunction::Tanh, + "acos" => MathFunction::Acos, + "asin" => MathFunction::Asin, + "log" => MathFunction::Log, + "log2" => MathFunction::Log2, + "length" => MathFunction::Length, + "determinant" => MathFunction::Determinant, + "bitCount" => MathFunction::CountOneBits, + "bitfieldReverse" => MathFunction::ReverseBits, + _ => unreachable!(), + }, + arg: args[0].0, + arg1: None, + arg2: None, + }, + body, + ))) + } + "atan" => { + let expr = match args.len() { + 1 => Expression::Math { + fun: MathFunction::Atan, + arg: args[0].0, + arg1: None, + arg2: None, + }, + 2 => Expression::Math { + fun: MathFunction::Atan2, + arg: args[0].0, + arg1: Some(args[1].0), + arg2: None, + }, + _ => return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)), + }; + Ok(Some(ctx.add_expression(expr, body))) + } + "mod" => { + if args.len() != 2 { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + + let (mut left, left_meta) = args[0]; + let (mut right, right_meta) = args[1]; + + ctx.binary_implicit_conversion(self, &mut left, left_meta, &mut right, right_meta)?; + + Ok(Some(ctx.add_expression( + Expression::Binary { + op: BinaryOperator::Modulo, + left, + right, + }, + body, + ))) + } + "max" => { + if args.len() != 2 { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + + let (mut arg0, arg0_meta) = args[0]; + let (mut arg1, arg1_meta) = args[1]; + + let arg0_size = match *self.resolve_type(ctx, arg0, arg0_meta)? { + TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + let arg1_size = match *self.resolve_type(ctx, arg1, arg1_meta)? { + TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + + ctx.binary_implicit_conversion(self, &mut arg0, arg0_meta, &mut arg1, arg1_meta)?; + + ctx.implicit_splat(self, &mut arg0, arg0_meta, arg1_size)?; + ctx.implicit_splat(self, &mut arg1, arg1_meta, arg0_size)?; + + Ok(Some(ctx.add_expression( + Expression::Math { + fun: MathFunction::Max, + arg: arg0, + arg1: Some(arg1), + arg2: None, + }, + body, + ))) + } + "pow" | "dot" | "min" | "reflect" | "cross" | "outerProduct" | "distance" | "step" + | "modf" | "frexp" | "ldexp" => { + if args.len() != 2 { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + + let (mut arg0, arg0_meta) = args[0]; + let (mut arg1, arg1_meta) = args[1]; + + ctx.binary_implicit_conversion(self, &mut arg0, arg0_meta, &mut arg1, arg1_meta)?; + + Ok(Some(ctx.add_expression( + Expression::Math { + fun: match name.as_str() { + "pow" => MathFunction::Pow, + "dot" => MathFunction::Dot, + "min" => MathFunction::Min, + "reflect" => MathFunction::Reflect, + "cross" => MathFunction::Cross, + "outerProduct" => MathFunction::Outer, + "distance" => MathFunction::Distance, + "step" => MathFunction::Step, + "modf" => MathFunction::Modf, + "frexp" => MathFunction::Frexp, + "ldexp" => MathFunction::Ldexp, + _ => unreachable!(), + }, + arg: arg0, + arg1: Some(arg1), + arg2: None, + }, + body, + ))) + } + "mix" => { + if args.len() != 3 { + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + } + + let (mut arg, arg_meta) = args[0]; + let (mut arg1, arg1_meta) = args[1]; + let (mut selector, selector_meta) = args[2]; + + ctx.binary_implicit_conversion(self, &mut arg, arg_meta, &mut arg1, arg1_meta)?; + ctx.binary_implicit_conversion( + self, + &mut arg, + arg_meta, + &mut selector, + selector_meta, + )?; + + let is_vector = match *self.resolve_type(ctx, selector, selector_meta)? { + TypeInner::Vector { .. } => true, + _ => false, + }; + match *self.resolve_type(ctx, args[0].0, args[0].1)? { + TypeInner::Vector { size, .. } if !is_vector => { + selector = ctx.add_expression( + Expression::Splat { + size, + value: selector, + }, + body, + ) + } + _ => {} + }; + + let expr = match self + .resolve_type(ctx, selector, selector_meta)? + .scalar_kind() + { + Some(ScalarKind::Bool) => Expression::Select { + condition: selector, + accept: arg, + reject: arg1, + }, + _ => Expression::Math { + fun: MathFunction::Mix, + arg, + arg1: Some(arg1), + arg2: Some(selector), + }, + }; + + Ok(Some(ctx.add_expression(expr, body))) + } + "clamp" => { + if args.len() != 3 { + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + } + + let (mut arg0, arg0_meta) = args[0]; + let (mut arg1, arg1_meta) = args[1]; + let (mut arg2, arg2_meta) = args[2]; + + let vector_size = match *(self.resolve_type(ctx, arg0, arg0_meta)?) { + TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + + ctx.binary_implicit_conversion(self, &mut arg0, arg0_meta, &mut arg1, arg1_meta)?; + ctx.binary_implicit_conversion(self, &mut arg1, arg1_meta, &mut arg2, arg2_meta)?; + ctx.binary_implicit_conversion(self, &mut arg2, arg2_meta, &mut arg0, arg0_meta)?; + + ctx.implicit_splat(self, &mut arg1, arg1_meta, vector_size)?; + ctx.implicit_splat(self, &mut arg2, arg2_meta, vector_size)?; + + Ok(Some(ctx.add_expression( + Expression::Math { + fun: MathFunction::Clamp, + arg: arg0, + arg1: Some(arg1), + arg2: Some(arg2), + }, + body, + ))) + } + "faceforward" | "refract" | "fma" | "smoothstep" => { + if args.len() != 3 { + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + } + Ok(Some(ctx.add_expression( + Expression::Math { + fun: match name.as_str() { + "faceforward" => MathFunction::FaceForward, + "refract" => MathFunction::Refract, + "fma" => MathFunction::Fma, + "smoothstep" => MathFunction::SmoothStep, + _ => unreachable!(), + }, + arg: args[0].0, + arg1: Some(args[1].0), + arg2: Some(args[2].0), + }, + body, + ))) + } + "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" + | "notEqual" => { + if args.len() != 2 { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + Ok(Some(ctx.add_expression( + Expression::Binary { + op: match name.as_str() { + "lessThan" => BinaryOperator::Less, + "greaterThan" => BinaryOperator::Greater, + "lessThanEqual" => BinaryOperator::LessEqual, + "greaterThanEqual" => BinaryOperator::GreaterEqual, + "equal" => BinaryOperator::Equal, + "notEqual" => BinaryOperator::NotEqual, + _ => unreachable!(), + }, + left: args[0].0, + right: args[1].0, + }, + body, + ))) + } + "isinf" | "isnan" | "all" | "any" => { + let fun = match name.as_str() { + "isinf" => RelationalFunction::IsInf, + "isnan" => RelationalFunction::IsNan, + "all" => RelationalFunction::All, + "any" => RelationalFunction::Any, + _ => unreachable!(), + }; + + Ok(Some( + self.parse_relational_fun(ctx, body, name, &args, fun, meta)?, + )) + } + _ => { + let declarations = self.lookup_function.get(&name).ok_or_else(|| { + ErrorKind::SemanticError(meta, format!("Unknown function '{}'", name).into()) + })?; + + let mut maybe_decl = None; + let mut ambiguous = false; + + 'outer: for decl in declarations { + if args.len() != decl.parameters.len() { + continue; + } + + let mut exact = true; + + for (decl_arg, call_arg) in decl.parameters.iter().zip(args.iter()) { + let decl_inner = &self.module.types[*decl_arg].inner; + let call_inner = self.resolve_type(ctx, call_arg.0, call_arg.1)?; + + if decl_inner == call_inner { + continue; + } + + exact = false; + + let (decl_kind, call_kind) = match (decl_inner, call_inner) { + ( + &TypeInner::Scalar { + kind: decl_kind, .. + }, + &TypeInner::Scalar { + kind: call_kind, .. + }, + ) => (decl_kind, call_kind), + ( + &TypeInner::Vector { + kind: decl_kind, + size: decl_size, + .. + }, + &TypeInner::Vector { + kind: call_kind, + size: call_size, + .. + }, + ) if decl_size == call_size => (decl_kind, call_kind), + ( + &TypeInner::Matrix { + rows: decl_rows, + columns: decl_columns, + .. + }, + &TypeInner::Matrix { + rows: call_rows, + columns: call_columns, + .. + }, + ) if decl_columns == call_columns && decl_rows == call_rows => { + (ScalarKind::Float, ScalarKind::Float) + } + _ => continue 'outer, + }; + + match (type_power(decl_kind), type_power(call_kind)) { + (Some(decl_power), Some(call_power)) if decl_power > call_power => {} + _ => continue 'outer, + } + } + + if exact { + maybe_decl = Some(decl); + ambiguous = false; + break; + } else if maybe_decl.is_some() { + ambiguous = true; + } else { + maybe_decl = Some(decl) + } + } + + if ambiguous { + return Err(ErrorKind::SemanticError( + meta, + format!("Ambiguous best function for '{}'", name).into(), + )); + } + + let decl = maybe_decl.ok_or_else(|| { + ErrorKind::SemanticError(meta, format!("Unknown function '{}'", name).into()) + })?; + + let qualifiers = decl.qualifiers.clone(); + let parameters = decl.parameters.clone(); + let function = decl.handle; + let is_void = decl.void; + + let mut arguments = Vec::with_capacity(args.len()); + let mut proxy_writes = Vec::new(); + for (qualifier, (expr, parameter)) in qualifiers + .iter() + .zip(raw_args.iter().zip(parameters.iter())) + { + let (mut handle, meta) = + ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?; + + if let TypeInner::Vector { size, kind, width } = + *self.resolve_type(ctx, handle, meta)? + { + if qualifier.is_lhs() + && matches!(*ctx.get_expression(handle), Expression::Swizzle { .. }) + { + let ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }); + let temp_var = ctx.locals.append(LocalVariable { + name: None, + ty, + init: None, + }); + let temp_expr = + ctx.add_expression(Expression::LocalVariable(temp_var), body); + + body.push(Statement::Store { + pointer: temp_expr, + value: handle, + }); + + arguments.push(temp_expr); + proxy_writes.push((*expr, temp_expr)); + continue; + } + } + + let scalar_components = scalar_components(&self.module.types[*parameter].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut handle, meta, kind, width)?; + } + + arguments.push(handle) + } + + ctx.emit_flush(body); + + let result = if !is_void { + Some(ctx.add_expression(Expression::Call(function), body)) + } else { + None + }; + + body.push(crate::Statement::Call { + function, + arguments, + result, + }); + + ctx.emit_start(); + for (tgt, pointer) in proxy_writes { + let temp_ref = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Variable(VariableReference { + expr: pointer, + load: true, + mutable: true, + entry_arg: None, + }), + meta, + }); + let assign = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Assign { + tgt, + value: temp_ref, + }, + meta, + }); + + let _ = ctx.lower_expect(self, assign, false, body)?; + } + ctx.emit_flush(body); + ctx.emit_start(); + + Ok(result) } } } From 223016a4185138ce834487aef36329055d67e0d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 29 Jul 2021 22:38:21 +0100 Subject: [PATCH 1165/2212] [glsl-in] Implement textureGrad --- src/front/glsl/functions.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index f6f6f5ea7..78afdd180 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -416,6 +416,39 @@ impl Program<'_> { )) } } + "textureGrad" => { + if args.len() != 4 { + return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + } + let arg_1 = &mut args[1]; + ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; + let arg_2 = &mut args[2]; + ctx.implicit_conversion(self, &mut arg_2.0, arg_2.1, ScalarKind::Float, 4)?; + let arg_3 = &mut args[3]; + ctx.implicit_conversion(self, &mut arg_3.0, arg_3.1, ScalarKind::Float, 4)?; + if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { + Ok(Some(ctx.add_expression( + Expression::ImageSample { + image: args[0].0, + sampler, + coordinate: args[1].0, + array_index: None, //TODO + offset: None, + level: SampleLevel::Gradient { + x: args[2].0, + y: args[3].0, + }, + depth_ref: None, + }, + body, + ))) + } else { + Err(ErrorKind::SemanticError( + meta, + "Bad call to textureGrad".into(), + )) + } + } "textureSize" => { if !(1..=2).contains(&args.len()) { return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); From e58d1649c317d5209a21d47cd62b4baab0c47e36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 30 Jul 2021 18:32:09 +0100 Subject: [PATCH 1166/2212] Fix clippy lints --- src/back/glsl/mod.rs | 4 ++-- src/back/hlsl/storage.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index fd346c3c9..062e038f0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -829,7 +829,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_array_size(size)?; } - if is_value_init_supported(&self.module, global.ty) { + if is_value_init_supported(self.module, global.ty) { write!(self.out, " = ")?; if let Some(init) = global.init { self.write_constant(init)?; @@ -1110,7 +1110,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the constant // `write_constant` adds no trailing or leading space/newline self.write_constant(init)?; - } else if is_value_init_supported(&self.module, local.ty) { + } else if is_value_init_supported(self.module, local.ty) { write!(self.out, " = ")?; self.write_zero_init_value(local.ty)?; } diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index a48507a66..91f3ef36c 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -170,7 +170,7 @@ impl super::Writer<'_, W> { func_ctx: &FunctionCtx, ) -> BackendResult { match *value { - StoreValue::Expression(expr) => self.write_expr(module, expr, &func_ctx)?, + StoreValue::Expression(expr) => self.write_expr(module, expr, func_ctx)?, StoreValue::TempIndex { depth, index, From 8e17c296442514ba38967f94f61dcee8e2ae9de3 Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 29 Jul 2021 18:45:12 +0300 Subject: [PATCH 1167/2212] [glsl-out] Add inout qualifier for pointer function arguments --- src/back/glsl/mod.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 062e038f0..5777134c8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1030,6 +1030,11 @@ impl<'a, W: Write> Writer<'a, W> { // any spaces at the beginning or end this.write_image_type(dim, arrayed, class)?; } + TypeInner::Pointer { base, .. } => { + // write parameter qualifiers + write!(this.out, "inout ")?; + this.write_type(base)?; + } // All other types are written by `write_type` _ => { this.write_type(arg.ty)?; From e4931e106d56bdb52555ae69ada907c29b2f76fa Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 2 Aug 2021 11:22:29 -0700 Subject: [PATCH 1168/2212] Document `EntryPoint`. --- src/lib.rs | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 2d8cf707c..469a5f496 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1340,7 +1340,46 @@ pub struct Function { pub body: Block, } -/// Exported function, to be run at a certain stage in the pipeline. +/// The main function for a pipeline stage. +/// +/// An [`EntryPoint`] is a [`Function`] that serves as the main function for a +/// graphics or compute pipeline stage. For example, an `EntryPoint` whose +/// [`stage`] is [`ShaderStage::Vertex`] can serve as a graphics pipeline's +/// vertex shader. +/// +/// Since an entry point is called directly by the graphics or compute pipeline, +/// not by other WGSL functions, you must specify what the pipeline should pass +/// as the entry point's arguments, and what values it will return. For example, +/// a vertex shader needs a vertex's attributes as its arguments, but if it's +/// used for instanced draw calls, it will also want to know the instance id. +/// The vertex shader's return value will usually include an output vertex +/// position, and possibly other attributes to be interpolated and passed along +/// to a fragment shader. +/// +/// To specify this, the arguments and result of an `EntryPoint`'s [`function`] +/// must each have a [`Binding`], or be structs whose members all have +/// `Binding`s. This associates every value passed to or returned from the entry +/// point with either a [`BuiltIn`] or a [`Location`]: +/// +/// - A [`BuiltIn`] has special semantics, usually specific to its pipeline +/// stage. For example, the result of a vertex shader can include a +/// [`BuiltIn::Position`] value, which determines the position of a vertex +/// of a rendered primitive. Or, a compute shader might take an argument +/// whose binding is [`BuiltIn::WorkGroupSize`], through which the compute +/// pipeline would pass the number of invocations in your workgroup. +/// +/// - A [`Location`] indicates user-defined IO to be passed from one pipeline +/// stage to the next. For example, a vertex shader might also produce a +/// `uv` texture location as a user-defined IO value. +/// +/// In other words, the pipeline stage's input and output interface are +/// determined by the bindings of the arguments and result of the `EntryPoint`'s +/// [`function`]. +/// +/// [`Function`]: crate::Function +/// [`Location`]: Binding::Location +/// [`function`]: EntryPoint::function +/// [`stage`]: EntryPoint::stage #[derive(Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] From b7a4ee1d2d9b2b433166aad7a9b20000e1e9ced7 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 2 Aug 2021 11:30:03 -0700 Subject: [PATCH 1169/2212] [spv-out] Document back::spv::Writer::write_varying. --- src/back/spv/writer.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index fa3a08d06..e2ac8768c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -940,6 +940,25 @@ impl Writer { null_id } + /// Generate an `OpVariable` for one value in an [`EntryPoint`]'s IO interface. + /// + /// The [`Binding`]s of the arguments and result of an [`EntryPoint`]'s + /// [`Function`] describe a SPIR-V shader interface. In SPIR-V, the + /// interface is represented by global variables in the `Input` and `Output` + /// storage classes, with decorations indicating which builtin or location + /// each variable corresponds to. + /// + /// This function emits a single global `OpVariable` for a single value from + /// the interface, and adds appropriate decorations to indicate which + /// builtin or location it represents, how it should be interpolated, and so + /// on. The `class` argument gives the variable's SPIR-V storage class, + /// which should be either [`Input`] or [`Output`]. + /// + /// [`Binding`]: crate::Binding + /// [`Function`]: crate::Function + /// [`EntryPoint`]: crate::EntryPoint + /// [`Input`]: spirv::StorageClass::Input + /// [`Output`]: spirv::StorageClass::Output fn write_varying( &mut self, ir_module: &crate::Module, From d39f6780a757074be1ef4acb04ee4155ec13b3d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 30 Jul 2021 19:11:31 +0100 Subject: [PATCH 1170/2212] Documentation fixes --- src/back/dot/mod.rs | 2 +- src/back/glsl/mod.rs | 6 +- src/back/hlsl/conv.rs | 3 +- src/back/hlsl/help.rs | 118 ++++++++++++++++++++------------------ src/back/hlsl/keywords.rs | 6 +- src/back/hlsl/writer.rs | 2 +- src/back/spv/mod.rs | 4 +- src/back/wgsl/writer.rs | 9 ++- 8 files changed, 79 insertions(+), 71 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 2659ddc49..c45e1b309 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -134,7 +134,7 @@ fn name(option: &Option) -> &str { } } -/// set39 color scheme from https://graphviz.org/doc/info/colors.html +/// set39 color scheme from const COLORS: &[&str] = &[ "white", // pattern starts at 1 "#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3", "#fdb462", "#b3de69", "#fccde5", diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5777134c8..e4a2e86e8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -647,7 +647,8 @@ impl<'a, W: Write> Writer<'a, W> { /// # Panics /// - If type is either a image, a sampler, a pointer, or a struct /// - If it's an Array with a [`ArraySize::Constant`](crate::ArraySize::Constant) with a - /// constant that isn't [`Uint`](crate::ConstantInner::Uint) + /// constant that isn't a [`Scalar`](crate::ConstantInner::Scalar) or if the + /// scalar value isn't an [`Sint`](crate::ScalarValue::Sint) or [`Uint`](crate::ScalarValue::Uint) fn write_value_type(&mut self, inner: &TypeInner) -> BackendResult { match *inner { // Scalars are simple we just get the full name from `glsl_scalar` @@ -712,7 +713,8 @@ impl<'a, W: Write> Writer<'a, W> { /// # Panics /// - If type is either a image or sampler /// - If it's an Array with a [`ArraySize::Constant`](crate::ArraySize::Constant) with a - /// constant that isn't [`Uint`](crate::ConstantInner::Uint) + /// constant that isn't a [`Scalar`](crate::ConstantInner::Scalar) or if the + /// scalar value isn't an [`Sint`](crate::ScalarValue::Sint) or [`Uint`](crate::ScalarValue::Uint) fn write_type(&mut self, ty: Handle) -> BackendResult { match self.module.types[ty].inner { // glsl has no pointer types so just write types as normal and loads are skipped diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 1d56a08d9..229158973 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -11,7 +11,8 @@ impl crate::ScalarKind { } /// Helper function that returns scalar related strings - /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-scalar + /// + /// pub(super) fn to_hlsl_str(self, width: crate::Bytes) -> Result<&'static str, Error> { match self { Self::Sint => Ok("int"), diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index d72c7a242..a8147aa5a 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -1,25 +1,28 @@ -// Important note about `Expression::ImageQuery`/`Expression::ArrayLength` and hlsl backend: -// Due to implementation of `GetDimensions` function in hlsl (https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions) -// backend can't work with it as an expression. -// Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texure info and query function. -// See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions. -// This allowed to works with `Expression::ImageQuery` as expression and write wrapped function. -// -// For example: -// ```wgsl -// let dim_1d = textureDimensions(image_1d); -// ``` -// -// ```hlsl -// int NagaDimensions1D(Texture1D) -// { -// uint4 ret; -// image_1d.GetDimensions(ret.x); -// return ret.x; -// } -// -// int dim_1d = NagaDimensions1D(image_1d); -// ``` +//! Helpers for the hlsl backend +//! +//! Important note about `Expression::ImageQuery`/`Expression::ArrayLength` and hlsl backend: +//! +//! Due to implementation of `GetDimensions` function in hlsl () +//! backend can't work with it as an expression. +//! Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texure info and query function. +//! See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions. +//! This allowed to works with `Expression::ImageQuery` as expression and write wrapped function. +//! +//! For example: +//! ```wgsl +//! let dim_1d = textureDimensions(image_1d); +//! ``` +//! +//! ```hlsl +//! int NagaDimensions1D(Texture1D) +//! { +//! uint4 ret; +//! image_1d.GetDimensions(ret.x); +//! return ret.x; +//! } +//! +//! int dim_1d = NagaDimensions1D(image_1d); +//! ``` use super::{super::FunctionCtx, BackendResult}; use crate::arena::Handle; @@ -38,37 +41,37 @@ pub(super) struct WrappedImageQuery { pub(super) query: ImageQuery, } -// HLSL backend requires its own `ImageQuery` enum. -// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function. -// IR version can't be unique per function, because it's store mipmap level as an expression. -// -// For example: -// ```wgsl -// let dim_cube_array_lod = textureDimensions(image_cube_array, 1); -// let dim_cube_array_lod2 = textureDimensions(image_cube_array, 1); -// ``` -// -// ```ir -// ImageQuery { -// image: [1], -// query: Size { -// level: Some( -// [1], -// ), -// }, -// }, -// ImageQuery { -// image: [1], -// query: Size { -// level: Some( -// [2], -// ), -// }, -// }, -// ``` -// -// HLSL should generate only 1 function for this case. -// +/// HLSL backend requires its own `ImageQuery` enum. +/// +/// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function. +/// IR version can't be unique per function, because it's store mipmap level as an expression. +/// +/// For example: +/// ```wgsl +/// let dim_cube_array_lod = textureDimensions(image_cube_array, 1); +/// let dim_cube_array_lod2 = textureDimensions(image_cube_array, 1); +/// ``` +/// +/// ```ir +/// ImageQuery { +/// image: [1], +/// query: Size { +/// level: Some( +/// [1], +/// ), +/// }, +/// }, +/// ImageQuery { +/// image: [1], +/// query: Size { +/// level: Some( +/// [2], +/// ), +/// }, +/// }, +/// ``` +/// +/// HLSL should generate only 1 function for this case. #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub(super) enum ImageQuery { Size, @@ -141,7 +144,8 @@ impl<'a, W: Write> super::Writer<'a, W> { } /// Helper function that write wrapped function for `Expression::ArrayLength` - /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-rwbyteaddressbuffer-getdimensions + /// + /// pub(super) fn write_wrapped_array_length_function( &mut self, module: &crate::Module, @@ -221,7 +225,8 @@ impl<'a, W: Write> super::Writer<'a, W> { } /// Helper function that write wrapped function for `Expression::ImageQuery` - /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions + /// + /// pub(super) fn write_wrapped_image_query_function( &mut self, module: &crate::Module, @@ -338,7 +343,8 @@ impl<'a, W: Write> super::Writer<'a, W> { } /// Helper function that write wrapped function for `Expression::ImageQuery` and `Expression::ArrayLength` - /// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions + /// + /// pub(super) fn write_wrapped_functions( &mut self, module: &crate::Module, diff --git a/src/back/hlsl/keywords.rs b/src/back/hlsl/keywords.rs index 1c19c5112..e322c98af 100644 --- a/src/back/hlsl/keywords.rs +++ b/src/back/hlsl/keywords.rs @@ -1,6 +1,6 @@ -/// HLSL Reserved Words -/// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-appendix-keywords -/// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-appendix-reserved-words +//! HLSL Reserved Words +//! - +//! - pub const RESERVED: &[&str] = &[ "AppendStructuredBuffer", "asm", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 2ef57b266..faa2212b5 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1734,7 +1734,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } - /// Helper method used to write [`ScalarValue`](ScalarValue) + /// Helper method used to write [`ScalarValue`](crate::ScalarValue) /// /// # Notes /// Adds no trailing or leading whitespace diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 0dcb97567..3666211c7 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -268,7 +268,7 @@ enum Dimension { Matrix, } -/// A map from evaluated [`Expression`s] to their SPIR-V ids. +/// A map from evaluated [`Expression`](crate::Expression)s to their SPIR-V ids. /// /// When we emit code to evaluate a given `Expression`, we record the /// SPIR-V id of its value here, under its `Handle` index. @@ -343,7 +343,7 @@ struct BlockContext<'w> { /// [`ir_function`](BlockContext::ir_function). fun_info: &'w crate::valid::FunctionInfo, - /// The [`back::spv::Function`] to which we are contributing SPIR-V instructions. + /// The [`spv::Function`](Function) to which we are contributing SPIR-V instructions. function: &'w mut Function, /// SPIR-V ids for expressions we've evaluated. diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 20d0cce1d..3a343d602 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -9,8 +9,7 @@ use std::fmt::Write; /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; -/// WGSL attribute -/// https://gpuweb.github.io/gpuweb/wgsl/#attributes +/// WGSL [attribute](https://gpuweb.github.io/gpuweb/wgsl/#attributes) enum Attribute { Binding(u32), Block, @@ -137,7 +136,7 @@ impl Writer { Ok(()) } - /// Helper method used to write [`ScalarValue`](ScalarValue) + /// Helper method used to write [`ScalarValue`](crate::ScalarValue) /// /// # Notes /// Adds no trailing or leading whitespace @@ -179,8 +178,8 @@ impl Writer { Ok(()) } - /// Helper method used to write structs - /// https://gpuweb.github.io/gpuweb/wgsl/#functions + /// Helper method used to write + /// [functions](https://gpuweb.github.io/gpuweb/wgsl/#functions) /// /// # Notes /// Ends in a newline From d6643086f3917d99b8a4d6a422c8ce85746a2eb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 30 Jul 2021 19:29:22 +0100 Subject: [PATCH 1171/2212] Check documentation errors in CI --- .github/workflows/pipeline.yml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index f13460c7a..bba081e5f 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -48,3 +48,20 @@ jobs: with: command: clippy args: --all-features --workspace -- -D warnings + documentation: + name: Documentation + runs-on: ubuntu-latest + env: + RUSTDOCFLAGS: -Dwarnings + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + - run: rustup component add clippy + - uses: actions-rs/cargo@v1 + with: + command: doc + args: -p naga --all-features --document-private-items From 717063eb2151bc7a5e7df3731792fbddd34b68de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 31 Jul 2021 16:40:39 +0100 Subject: [PATCH 1172/2212] [glsl-in] Convert Sampled image to depth image --- src/front/glsl/ast.rs | 17 ++++++ src/front/glsl/functions.rs | 119 ++++++++++++++++++++++++++++++++---- src/front/glsl/parser.rs | 5 +- 3 files changed, 129 insertions(+), 12 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 3deecf483..481ff99d8 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,3 +1,5 @@ +use bit_set::BitSet; + use super::{ super::{Emitter, Typifier}, constants::ConstantSolver, @@ -11,6 +13,7 @@ use crate::{ StorageClass, Type, TypeInner, UnaryOperator, VectorSize, }; use core::convert::TryFrom; +use std::ops::Index; #[derive(Debug, Clone, Copy)] pub enum GlobalLookupKind { @@ -36,6 +39,10 @@ pub struct FunctionDeclaration { pub defined: bool, /// Wheter or not this function returns void (nothing) pub void: bool, + /// [`BitSet`](BitSet) where each bit indicates if the argument in the + /// corresponding position should be treated as a depth image instead of a + /// regular image + pub depth_set: BitSet, } bitflags::bitflags! { @@ -180,6 +187,7 @@ pub struct Context<'function> { expressions: &'function mut Arena, pub locals: &'function mut Arena, pub arguments: &'function mut Vec, + pub depth_set: BitSet, pub arg_use: Vec, //TODO: Find less allocation heavy representation @@ -204,6 +212,7 @@ impl<'function> Context<'function> { expressions, locals, arguments, + depth_set: BitSet::new(), arg_use: vec![EntryArgUse::empty(); program.entry_args.len()], scopes: vec![FastHashMap::default()], @@ -924,6 +933,14 @@ impl<'function> Context<'function> { } } +impl<'function> Index> for Context<'function> { + type Output = Expression; + + fn index(&self, index: Handle) -> &Self::Output { + &self.expressions[index] + } +} + pub fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, crate::Bytes)> { match *ty { TypeInner::Scalar { kind, width } => Some((kind, width)), diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 78afdd180..3a438b44d 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,3 +1,5 @@ +use bit_set::BitSet; + use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, ImageQuery, LocalVariable, @@ -270,16 +272,15 @@ impl Program<'_> { meta: SourceMetadata, ) -> Result>, ErrorKind> { match name.as_str() { - "sampler1D" - | "sampler1DArray" - | "sampler2D" - | "sampler2DArray" - | "sampler2DMS" - | "sampler2DMSArray" - | "sampler3D" - | "samplerCube" - | "samplerCubeArray" - | "sampler1DShadow" + "sampler1D" | "sampler1DArray" | "sampler2D" | "sampler2DArray" | "sampler2DMS" + | "sampler2DMSArray" | "sampler3D" | "samplerCube" | "samplerCubeArray" => { + if args.len() != 2 { + return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + } + ctx.samplers.insert(args[0].0, args[1].0); + Ok(Some(args[0].0)) + } + "sampler1DShadow" | "sampler1DArrayShadow" | "sampler2DShadow" | "sampler2DArrayShadow" @@ -288,7 +289,48 @@ impl Program<'_> { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } + + let ty = match ctx[args[0].0] { + crate::Expression::GlobalVariable(handle) => { + &mut self.module.global_variables.get_mut(handle).ty + } + crate::Expression::FunctionArgument(i) => { + ctx.depth_set.insert(i as usize); + &mut ctx.arguments[i as usize].ty + } + _ => { + return Err(ErrorKind::SemanticError( + args[0].1, + "Not a valid texture expression".into(), + )) + } + }; + match self.module.types[*ty].inner { + TypeInner::Image { + class, + dim, + arrayed, + } => match class { + crate::ImageClass::Sampled { multi, .. } => { + *ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Image { + dim, + arrayed, + class: crate::ImageClass::Depth { multi }, + }, + }) + } + crate::ImageClass::Depth { .. } => {} + _ => { + return Err(ErrorKind::SemanticError(args[0].1, "Not a texture".into())) + } + }, + _ => return Err(ErrorKind::SemanticError(args[0].1, "Not a texture".into())), + }; + ctx.samplers.insert(args[0].0, args[1].0); + Ok(Some(args[0].0)) } "texture" => { @@ -845,7 +887,58 @@ impl Program<'_> { let mut exact = true; - for (decl_arg, call_arg) in decl.parameters.iter().zip(args.iter()) { + for ((i, decl_arg), call_arg) in + decl.parameters.iter().enumerate().zip(args.iter()) + { + if decl.depth_set.contains(i) { + let ty = match ctx[args[0].0] { + crate::Expression::GlobalVariable(handle) => { + &mut self.module.global_variables.get_mut(handle).ty + } + crate::Expression::FunctionArgument(i) => { + ctx.depth_set.insert(i as usize); + &mut ctx.arguments[i as usize].ty + } + _ => { + return Err(ErrorKind::SemanticError( + args[0].1, + "Not a valid texture expression".into(), + )) + } + }; + match self.module.types[*ty].inner { + TypeInner::Image { + class, + dim, + arrayed, + } => match class { + crate::ImageClass::Sampled { multi, .. } => { + *ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Image { + dim, + arrayed, + class: crate::ImageClass::Depth { multi }, + }, + }) + } + crate::ImageClass::Depth { .. } => {} + _ => { + return Err(ErrorKind::SemanticError( + args[0].1, + "Not a texture".into(), + )) + } + }, + _ => { + return Err(ErrorKind::SemanticError( + args[0].1, + "Not a texture".into(), + )) + } + }; + } + let decl_inner = &self.module.types[*decl_arg].inner; let call_inner = self.resolve_type(ctx, call_arg.0, call_arg.1)?; @@ -1043,6 +1136,7 @@ impl Program<'_> { name: String, // Normalized function parameters, modifiers are not applied parameters: Vec>, + depth_set: BitSet, qualifiers: Vec, meta: SourceMetadata, ) -> Result, ErrorKind> { @@ -1089,6 +1183,7 @@ impl Program<'_> { decl.defined = true; decl.qualifiers = qualifiers; + decl.depth_set = depth_set; *self.module.functions.get_mut(decl.handle) = function; return Ok(decl.handle); } @@ -1101,6 +1196,7 @@ impl Program<'_> { handle, defined: true, void, + depth_set, }); handle }) @@ -1153,6 +1249,7 @@ impl Program<'_> { handle, defined: false, void, + depth_set: BitSet::new(), }); Ok(()) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 3f01e926c..03f358681 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -737,7 +737,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { // parse the body self.parse_compound_statement(&mut context, &mut body)?; - let Context { arg_use, .. } = context; + let Context { + arg_use, depth_set, .. + } = context; let handle = self.program.add_function( Function { name: Some(name.clone()), @@ -750,6 +752,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }, name, parameters, + depth_set, qualifiers, meta, )?; From 244d58e8ff0e3ceb78e2374fddbb9cb079c4f13d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 1 Aug 2021 17:28:32 +0100 Subject: [PATCH 1173/2212] [glsl-in] Add support for depth_ref --- src/front/glsl/functions.rs | 399 +++++++++++++++++++----------------- 1 file changed, 213 insertions(+), 186 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 3a438b44d..c11c47457 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -2,13 +2,23 @@ use bit_set::BitSet; use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, - Expression, Function, FunctionArgument, FunctionResult, Handle, ImageQuery, LocalVariable, - MathFunction, RelationalFunction, SampleLevel, ScalarKind, ScalarValue, ShaderStage, Statement, - StructMember, SwizzleComponent, Type, TypeInner, VectorSize, + Expression, Function, FunctionArgument, FunctionResult, Handle, ImageClass, ImageDimension, + ImageQuery, LocalVariable, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind, + ScalarValue, ShaderStage, Statement, StructMember, SwizzleComponent, Type, TypeInner, + VectorSize, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; +/// Helper struct for texture calls with the separate components from the vector argument +/// +/// Obtained by calling [`coordinate_components`](Program::coordinate_components) +struct CoordComponents { + coordinate: Handle, + depth_ref: Option>, + array_index: Option>, +} + impl Program<'_> { fn add_constant_value(&mut self, scalar_kind: ScalarKind, value: u64) -> Handle { let value = match scalar_kind { @@ -289,49 +299,9 @@ impl Program<'_> { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } - - let ty = match ctx[args[0].0] { - crate::Expression::GlobalVariable(handle) => { - &mut self.module.global_variables.get_mut(handle).ty - } - crate::Expression::FunctionArgument(i) => { - ctx.depth_set.insert(i as usize); - &mut ctx.arguments[i as usize].ty - } - _ => { - return Err(ErrorKind::SemanticError( - args[0].1, - "Not a valid texture expression".into(), - )) - } - }; - match self.module.types[*ty].inner { - TypeInner::Image { - class, - dim, - arrayed, - } => match class { - crate::ImageClass::Sampled { multi, .. } => { - *ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Image { - dim, - arrayed, - class: crate::ImageClass::Depth { multi }, - }, - }) - } - crate::ImageClass::Depth { .. } => {} - _ => { - return Err(ErrorKind::SemanticError(args[0].1, "Not a texture".into())) - } - }, - _ => return Err(ErrorKind::SemanticError(args[0].1, "Not a texture".into())), - }; - - ctx.samplers.insert(args[0].0, args[1].0); - - Ok(Some(args[0].0)) + let expr = sampled_to_depth(&mut self.module, ctx, args[0], body)?; + ctx.samplers.insert(expr, args[1].0); + Ok(Some(expr)) } "texture" => { if !(2..=3).contains(&args.len()) { @@ -342,19 +312,20 @@ impl Program<'_> { if let Some(&mut (ref mut expr, meta)) = args.get_mut(2) { ctx.implicit_conversion(self, expr, meta, ScalarKind::Float, 4)?; } + let comps = self.coordinate_components(ctx, args[0], args[1], body)?; if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { Ok(Some( ctx.add_expression( Expression::ImageSample { image: args[0].0, sampler, - coordinate: args[1].0, - array_index: None, //TODO + coordinate: comps.coordinate, + array_index: comps.array_index, offset: None, level: args.get(2).map_or(SampleLevel::Auto, |&(expr, _)| { SampleLevel::Bias(expr) }), - depth_ref: None, + depth_ref: comps.depth_ref, }, body, ), @@ -371,16 +342,17 @@ impl Program<'_> { ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; let arg_2 = &mut args[2]; ctx.implicit_conversion(self, &mut arg_2.0, arg_2.1, ScalarKind::Float, 4)?; + let comps = self.coordinate_components(ctx, args[0], args[1], body)?; if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { Ok(Some(ctx.add_expression( Expression::ImageSample { image: args[0].0, sampler, - coordinate: args[1].0, - array_index: None, //TODO + coordinate: comps.coordinate, + array_index: comps.array_index, offset: None, level: SampleLevel::Exact(args[2].0), - depth_ref: None, + depth_ref: comps.depth_ref, }, body, ))) @@ -403,18 +375,8 @@ impl Program<'_> { let level = args .get(2) .map_or(SampleLevel::Auto, |&(expr, _)| SampleLevel::Bias(expr)); - let dim = match *self.resolve_type(ctx, args[0].0, args[0].1)? { - TypeInner::Image { dim, .. } => match dim { - crate::ImageDimension::D1 => 1, - crate::ImageDimension::D2 => 2, - crate::ImageDimension::D3 => 3, - crate::ImageDimension::Cube => { - return Err(ErrorKind::SemanticError( - meta, - "textureProj doesn't accept cube texture".into(), - )) - } - }, + let size = match *self.resolve_type(ctx, args[1].0, args[1].1)? { + TypeInner::Vector { size, .. } => size, _ => { return Err(ErrorKind::SemanticError( meta, @@ -422,32 +384,50 @@ impl Program<'_> { )) } }; - match *self.resolve_type(ctx, args[1].0, args[1].1)? { - TypeInner::Vector { size, .. } => { - if !(size as usize + 1 == dim || size == VectorSize::Quad) { - return Err(ErrorKind::SemanticError( - meta, - "Bad call to textureProj".into(), - )); - } - } - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Bad call to textureProj".into(), - )) - } - } + let (base, base_meta) = args[1]; + let mut right = ctx.add_expression( + Expression::AccessIndex { + base, + index: size as u32 - 1, + }, + body, + ); + let left = if let VectorSize::Bi = size { + ctx.add_expression(Expression::AccessIndex { base, index: 0 }, body) + } else { + let size = match size { + VectorSize::Tri => VectorSize::Bi, + _ => VectorSize::Tri, + }; + right = ctx.add_expression(Expression::Splat { size, value: right }, body); + ctx.add_expression( + Expression::Swizzle { + size, + vector: base, + pattern: SwizzleComponent::XYZW, + }, + body, + ) + }; + let coords = ctx.add_expression( + Expression::Binary { + op: BinaryOperator::Divide, + left, + right, + }, + body, + ); + let comps = self.coordinate_components(ctx, args[0], (coords, base_meta), body)?; if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { Ok(Some(ctx.add_expression( Expression::ImageSample { image: args[0].0, sampler, - coordinate: args[1].0, - array_index: None, //TODO + coordinate: comps.coordinate, + array_index: comps.array_index, offset: None, level, - depth_ref: None, + depth_ref: comps.depth_ref, }, body, ))) @@ -468,19 +448,20 @@ impl Program<'_> { ctx.implicit_conversion(self, &mut arg_2.0, arg_2.1, ScalarKind::Float, 4)?; let arg_3 = &mut args[3]; ctx.implicit_conversion(self, &mut arg_3.0, arg_3.1, ScalarKind::Float, 4)?; + let comps = self.coordinate_components(ctx, args[0], args[1], body)?; if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { Ok(Some(ctx.add_expression( Expression::ImageSample { image: args[0].0, sampler, - coordinate: args[1].0, - array_index: None, //TODO + coordinate: comps.coordinate, + array_index: comps.array_index, offset: None, level: SampleLevel::Gradient { x: args[2].0, y: args[3].0, }, - depth_ref: None, + depth_ref: comps.depth_ref, }, body, ))) @@ -516,61 +497,13 @@ impl Program<'_> { ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Sint, 4)?; let arg_2 = &mut args[2]; ctx.implicit_conversion(self, &mut arg_2.0, arg_2.1, ScalarKind::Sint, 4)?; - if ctx.samplers.get(&args[0].0).is_some() { - let (arrayed, dims) = match *self.resolve_type(ctx, args[0].0, args[0].1)? { - TypeInner::Image { arrayed, dim, .. } => (arrayed, dim), - _ => (false, crate::ImageDimension::D1), - }; - - let (coordinate, array_index) = if arrayed { - ( - match dims { - crate::ImageDimension::D1 => ctx.add_expression( - Expression::AccessIndex { - base: args[1].0, - index: 0, - }, - body, - ), - crate::ImageDimension::D2 => ctx.add_expression( - Expression::Swizzle { - size: VectorSize::Bi, - vector: args[1].0, - pattern: SwizzleComponent::XYZW, - }, - body, - ), - _ => ctx.add_expression( - Expression::Swizzle { - size: VectorSize::Tri, - vector: args[1].0, - pattern: SwizzleComponent::XYZW, - }, - body, - ), - }, - Some(ctx.add_expression( - Expression::AccessIndex { - base: args[1].0, - index: match dims { - crate::ImageDimension::D1 => 1, - crate::ImageDimension::D2 => 2, - crate::ImageDimension::D3 => 3, - crate::ImageDimension::Cube => 2, - }, - }, - body, - )), - ) - } else { - (args[1].0, None) - }; - + let comps = self.coordinate_components(ctx, args[0], args[1], body)?; + if ctx.samplers.get(&args[0].0).is_some() && comps.depth_ref.is_none() { Ok(Some(ctx.add_expression( Expression::ImageLoad { image: args[0].0, - coordinate, - array_index, + coordinate: comps.coordinate, + array_index: comps.array_index, index: Some(args[2].0), }, body, @@ -887,56 +820,11 @@ impl Program<'_> { let mut exact = true; - for ((i, decl_arg), call_arg) in - decl.parameters.iter().enumerate().zip(args.iter()) + for ((i, decl_arg), mut call_arg) in + decl.parameters.iter().enumerate().zip(args.iter().copied()) { if decl.depth_set.contains(i) { - let ty = match ctx[args[0].0] { - crate::Expression::GlobalVariable(handle) => { - &mut self.module.global_variables.get_mut(handle).ty - } - crate::Expression::FunctionArgument(i) => { - ctx.depth_set.insert(i as usize); - &mut ctx.arguments[i as usize].ty - } - _ => { - return Err(ErrorKind::SemanticError( - args[0].1, - "Not a valid texture expression".into(), - )) - } - }; - match self.module.types[*ty].inner { - TypeInner::Image { - class, - dim, - arrayed, - } => match class { - crate::ImageClass::Sampled { multi, .. } => { - *ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Image { - dim, - arrayed, - class: crate::ImageClass::Depth { multi }, - }, - }) - } - crate::ImageClass::Depth { .. } => {} - _ => { - return Err(ErrorKind::SemanticError( - args[0].1, - "Not a texture".into(), - )) - } - }, - _ => { - return Err(ErrorKind::SemanticError( - args[0].1, - "Not a texture".into(), - )) - } - }; + call_arg.0 = sampled_to_depth(&mut self.module, ctx, call_arg, body)?; } let decl_inner = &self.module.types[*decl_arg].inner; @@ -1448,4 +1336,143 @@ impl Program<'_> { }); } } + + /// Helper function for texture calls, splits the vector argument into it's components + fn coordinate_components( + &self, + ctx: &mut Context, + (image, image_meta): (Handle, SourceMetadata), + (coord, coord_meta): (Handle, SourceMetadata), + body: &mut Block, + ) -> Result { + if let TypeInner::Image { + dim, + arrayed, + class, + } = *self.resolve_type(ctx, image, image_meta)? + { + let image_size = match dim { + ImageDimension::D1 => None, + ImageDimension::D2 => Some(VectorSize::Bi), + ImageDimension::D3 => Some(VectorSize::Tri), + ImageDimension::Cube => Some(VectorSize::Tri), + }; + let coord_size = match *self.resolve_type(ctx, coord, coord_meta)? { + TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + let shadow = match class { + ImageClass::Depth { .. } => true, + _ => false, + }; + + let coordinate = match (image_size, coord_size) { + (Some(size), Some(coord_s)) if size != coord_s => ctx.add_expression( + Expression::Swizzle { + size, + vector: coord, + pattern: SwizzleComponent::XYZW, + }, + body, + ), + (None, Some(_)) => ctx.add_expression( + Expression::AccessIndex { + base: coord, + index: 0, + }, + body, + ), + _ => coord, + }; + let array_index = match arrayed { + true => { + let index = match shadow { + true => image_size.map_or(0, |s| s as u32 - 1), + false => image_size.map_or(0, |s| s as u32), + }; + + Some(ctx.add_expression(Expression::AccessIndex { base: coord, index }, body)) + } + _ => None, + }; + let depth_ref = match shadow { + true => { + let index = image_size.map_or(0, |s| s as u32); + + Some(ctx.add_expression(Expression::AccessIndex { base: coord, index }, body)) + } + false => None, + }; + + Ok(CoordComponents { + coordinate, + depth_ref, + array_index, + }) + } else { + Err(ErrorKind::SemanticError( + image_meta, + "Type is not an image".into(), + )) + } + } +} + +/// Helper function to cast a expression holding a sampled a image to a +/// depth one. +/// +/// Creates a new expression to make sure the typifier doesn't return a +/// cached evaluation. +fn sampled_to_depth( + module: &mut Module, + ctx: &mut Context, + (image, meta): (Handle, SourceMetadata), + body: &mut Block, +) -> Result, ErrorKind> { + let ty = match ctx[image] { + Expression::GlobalVariable(handle) => &mut module.global_variables.get_mut(handle).ty, + Expression::FunctionArgument(i) => { + ctx.depth_set.insert(i as usize); + &mut ctx.arguments[i as usize].ty + } + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Not a valid texture expression".into(), + )) + } + }; + match module.types[*ty].inner { + TypeInner::Image { + class, + dim, + arrayed, + } => match class { + ImageClass::Sampled { multi, .. } => { + *ty = module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Image { + dim, + arrayed, + class: ImageClass::Depth { multi }, + }, + }) + } + ImageClass::Depth { .. } => {} + _ => return Err(ErrorKind::SemanticError(meta, "Not a texture".into())), + }, + _ => return Err(ErrorKind::SemanticError(meta, "Not a texture".into())), + }; + + // Add a new expression to not have problems with the Typifier + // caching the old type + Ok(match ctx[image] { + Expression::GlobalVariable(handle) => { + ctx.add_expression(Expression::GlobalVariable(handle), body) + } + Expression::FunctionArgument(i) => { + ctx.add_expression(Expression::FunctionArgument(i), body) + } + _ => unreachable!(), + }) } From bd16bf90d0ac9bac69e06e4e0fc702626f2738e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 3 Aug 2021 17:41:05 +0100 Subject: [PATCH 1174/2212] [glsl-in] Unify depth_set and qualifiers --- src/front/glsl/ast.rs | 25 ++++++++++++++++--------- src/front/glsl/functions.rs | 32 +++++++++++++------------------- src/front/glsl/parser.rs | 24 +++++++++++------------- 3 files changed, 40 insertions(+), 41 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 481ff99d8..f98e2a2c7 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,5 +1,3 @@ -use bit_set::BitSet; - use super::{ super::{Emitter, Typifier}, constants::ConstantSolver, @@ -30,19 +28,23 @@ pub struct GlobalLookup { } #[derive(Debug, Clone)] +pub struct ParameterInfo { + pub qualifier: ParameterQualifier, + /// Wether the parameter should be treated as a depth image instead of a + /// sampled image + pub depth: bool, +} + +#[derive(Debug)] pub struct FunctionDeclaration { /// Normalized function parameters, modifiers are not applied pub parameters: Vec>, - pub qualifiers: Vec, + pub parameters_info: Vec, pub handle: Handle, /// Wheter this function was already defined or is just a prototype pub defined: bool, /// Wheter or not this function returns void (nothing) pub void: bool, - /// [`BitSet`](BitSet) where each bit indicates if the argument in the - /// corresponding position should be treated as a depth image instead of a - /// regular image - pub depth_set: BitSet, } bitflags::bitflags! { @@ -187,7 +189,7 @@ pub struct Context<'function> { expressions: &'function mut Arena, pub locals: &'function mut Arena, pub arguments: &'function mut Vec, - pub depth_set: BitSet, + pub parameters_info: Vec, pub arg_use: Vec, //TODO: Find less allocation heavy representation @@ -212,7 +214,7 @@ impl<'function> Context<'function> { expressions, locals, arguments, - depth_set: BitSet::new(), + parameters_info: Vec::new(), arg_use: vec![EntryArgUse::empty(); program.entry_args.len()], scopes: vec![FastHashMap::default()], @@ -383,6 +385,11 @@ impl<'function> Context<'function> { self.arguments.push(arg); + self.parameters_info.push(ParameterInfo { + qualifier, + depth: false, + }); + if let Some(name) = name { let expr = self.add_expression(Expression::FunctionArgument(index as u32), body); let mutable = qualifier != ParameterQualifier::Const && !opaque; diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index c11c47457..005bcb2a8 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,5 +1,3 @@ -use bit_set::BitSet; - use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, ImageClass, ImageDimension, @@ -823,7 +821,7 @@ impl Program<'_> { for ((i, decl_arg), mut call_arg) in decl.parameters.iter().enumerate().zip(args.iter().copied()) { - if decl.depth_set.contains(i) { + if decl.parameters_info[i].depth { call_arg.0 = sampled_to_depth(&mut self.module, ctx, call_arg, body)?; } @@ -902,24 +900,24 @@ impl Program<'_> { ErrorKind::SemanticError(meta, format!("Unknown function '{}'", name).into()) })?; - let qualifiers = decl.qualifiers.clone(); + let parameters_info = decl.parameters_info.clone(); let parameters = decl.parameters.clone(); let function = decl.handle; let is_void = decl.void; let mut arguments = Vec::with_capacity(args.len()); let mut proxy_writes = Vec::new(); - for (qualifier, (expr, parameter)) in qualifiers + for (parameter_info, (expr, parameter)) in parameters_info .iter() .zip(raw_args.iter().zip(parameters.iter())) { let (mut handle, meta) = - ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?; + ctx.lower_expect(self, *expr, parameter_info.qualifier.is_lhs(), body)?; if let TypeInner::Vector { size, kind, width } = *self.resolve_type(ctx, handle, meta)? { - if qualifier.is_lhs() + if parameter_info.qualifier.is_lhs() && matches!(*ctx.get_expression(handle), Expression::Swizzle { .. }) { let ty = self.module.types.fetch_or_append(Type { @@ -1024,8 +1022,7 @@ impl Program<'_> { name: String, // Normalized function parameters, modifiers are not applied parameters: Vec>, - depth_set: BitSet, - qualifiers: Vec, + parameters_info: Vec, meta: SourceMetadata, ) -> Result, ErrorKind> { ensure_block_returns(&mut function.body); @@ -1070,8 +1067,7 @@ impl Program<'_> { } decl.defined = true; - decl.qualifiers = qualifiers; - decl.depth_set = depth_set; + decl.parameters_info = parameters_info; *self.module.functions.get_mut(decl.handle) = function; return Ok(decl.handle); } @@ -1080,11 +1076,10 @@ impl Program<'_> { let handle = module.functions.append(function); declarations.push(FunctionDeclaration { parameters, - qualifiers, + parameters_info, handle, defined: true, void, - depth_set, }); handle }) @@ -1096,7 +1091,7 @@ impl Program<'_> { name: String, // Normalized function parameters, modifiers are not applied parameters: Vec>, - qualifiers: Vec, + parameters_info: Vec, meta: SourceMetadata, ) -> Result<(), ErrorKind> { let void = function.result.is_none(); @@ -1133,11 +1128,10 @@ impl Program<'_> { let handle = module.functions.append(function); declarations.push(FunctionDeclaration { parameters, - qualifiers, + parameters_info, handle, defined: false, void, - depth_set: BitSet::new(), }); Ok(()) @@ -1418,8 +1412,8 @@ impl Program<'_> { } } -/// Helper function to cast a expression holding a sampled a image to a -/// depth one. +/// Helper function to cast a expression holding a sampled image to a +/// depth image. /// /// Creates a new expression to make sure the typifier doesn't return a /// cached evaluation. @@ -1432,7 +1426,7 @@ fn sampled_to_depth( let ty = match ctx[image] { Expression::GlobalVariable(handle) => &mut module.global_variables.get_mut(handle).ty, Expression::FunctionArgument(i) => { - ctx.depth_set.insert(i as usize); + ctx.parameters_info[i as usize].depth = true; &mut ctx.arguments[i as usize].ty } _ => { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 03f358681..a5b62e8ca 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -689,7 +689,6 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { let mut arguments = Vec::new(); // Normalized function parameters, modifiers are not applied let mut parameters = Vec::new(); - let mut qualifiers = Vec::new(); let mut body = Block::new(); let mut context = Context::new( @@ -700,12 +699,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { &mut arguments, ); - self.parse_function_args( - &mut context, - &mut body, - &mut qualifiers, - &mut parameters, - )?; + self.parse_function_args(&mut context, &mut body, &mut parameters)?; let end_meta = self.expect(TokenValue::RightParen)?.meta; meta = meta.union(&end_meta); @@ -714,6 +708,11 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { return match token.value { TokenValue::Semicolon => { // This branch handles function prototypes + + let Context { + parameters_info, .. + } = context; + self.program.add_prototype( Function { name: Some(name.clone()), @@ -723,7 +722,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }, name, parameters, - qualifiers, + parameters_info, meta, )?; @@ -738,7 +737,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.parse_compound_statement(&mut context, &mut body)?; let Context { - arg_use, depth_set, .. + arg_use, + parameters_info, + .. } = context; let handle = self.program.add_function( Function { @@ -752,8 +753,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { }, name, parameters, - depth_set, - qualifiers, + parameters_info, meta, )?; @@ -1864,13 +1864,11 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { &mut self, context: &mut Context, body: &mut Block, - qualifiers: &mut Vec, parameters: &mut Vec>, ) -> Result<()> { loop { if self.peek_type_name() || self.peek_parameter_qualifier() { let qualifier = self.parse_parameter_qualifier(); - qualifiers.push(qualifier); let ty = self.parse_type_non_void()?.0; match self.expect_peek()?.value { From 9742f6820a7094dcde1875f8de5d95fe9ef5059c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 3 Aug 2021 18:04:09 +0100 Subject: [PATCH 1175/2212] [glsl-in] Invalidate the expression in sampled_to_depth --- src/front/glsl/ast.rs | 24 ++++++++++++++++++++++++ src/front/glsl/functions.rs | 32 ++++++++++---------------------- src/front/mod.rs | 20 ++++++++++++++++++++ 3 files changed, 54 insertions(+), 22 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index f98e2a2c7..be1ebf704 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -163,6 +163,30 @@ impl<'a> Program<'a> { Ok(context.typifier.get(handle, &self.module.types)) } + /// Invalidates the cached type resolution for `handle` forcing a recomputation + pub fn invalidate_expression<'b>( + &'b self, + context: &'b mut Context, + handle: Handle, + meta: SourceMetadata, + ) -> Result<(), ErrorKind> { + let resolve_ctx = ResolveContext { + constants: &self.module.constants, + types: &self.module.types, + global_vars: &self.module.global_variables, + local_vars: context.locals, + functions: &self.module.functions, + arguments: context.arguments, + }; + + context + .typifier + .invalidate(handle, context.expressions, &resolve_ctx) + .map_err(|error| { + ErrorKind::SemanticError(meta, format!("Can't resolve type: {:?}", error).into()) + }) + } + pub fn solve_constant( &mut self, ctx: &Context, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 005bcb2a8..5fad4e7b2 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -297,9 +297,10 @@ impl Program<'_> { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } - let expr = sampled_to_depth(&mut self.module, ctx, args[0], body)?; - ctx.samplers.insert(expr, args[1].0); - Ok(Some(expr)) + sampled_to_depth(&mut self.module, ctx, args[0])?; + self.invalidate_expression(ctx, args[0].0, args[0].1)?; + ctx.samplers.insert(args[0].0, args[1].0); + Ok(Some(args[0].0)) } "texture" => { if !(2..=3).contains(&args.len()) { @@ -818,11 +819,12 @@ impl Program<'_> { let mut exact = true; - for ((i, decl_arg), mut call_arg) in - decl.parameters.iter().enumerate().zip(args.iter().copied()) + for ((i, decl_arg), call_arg) in + decl.parameters.iter().enumerate().zip(args.iter()) { if decl.parameters_info[i].depth { - call_arg.0 = sampled_to_depth(&mut self.module, ctx, call_arg, body)?; + sampled_to_depth(&mut self.module, ctx, *call_arg)?; + self.invalidate_expression(ctx, call_arg.0, call_arg.1)? } let decl_inner = &self.module.types[*decl_arg].inner; @@ -1414,15 +1416,11 @@ impl Program<'_> { /// Helper function to cast a expression holding a sampled image to a /// depth image. -/// -/// Creates a new expression to make sure the typifier doesn't return a -/// cached evaluation. fn sampled_to_depth( module: &mut Module, ctx: &mut Context, (image, meta): (Handle, SourceMetadata), - body: &mut Block, -) -> Result, ErrorKind> { +) -> Result<(), ErrorKind> { let ty = match ctx[image] { Expression::GlobalVariable(handle) => &mut module.global_variables.get_mut(handle).ty, Expression::FunctionArgument(i) => { @@ -1458,15 +1456,5 @@ fn sampled_to_depth( _ => return Err(ErrorKind::SemanticError(meta, "Not a texture".into())), }; - // Add a new expression to not have problems with the Typifier - // caching the old type - Ok(match ctx[image] { - Expression::GlobalVariable(handle) => { - ctx.add_expression(Expression::GlobalVariable(handle), body) - } - Expression::FunctionArgument(i) => { - ctx.add_expression(Expression::FunctionArgument(i), body) - } - _ => unreachable!(), - }) + Ok(()) } diff --git a/src/front/mod.rs b/src/front/mod.rs index 9989b2132..8f620f430 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -85,6 +85,26 @@ impl Typifier { } Ok(()) } + + /// Invalidates the cached type resolution for `epxr_handle` forcing a recomputation + /// + /// If the type of the expression hasn't yet been calculated a + /// [`grow`](Self::grow) is performed instead + pub fn invalidate( + &mut self, + expr_handle: Handle, + expressions: &Arena, + ctx: &ResolveContext, + ) -> Result<(), ResolveError> { + if self.resolutions.len() <= expr_handle.index() { + self.grow(expr_handle, expressions, ctx) + } else { + let expr = &expressions[expr_handle]; + let resolution = ctx.resolve(expr, |h| &self.resolutions[h.index()])?; + self.resolutions[expr_handle.index()] = resolution; + Ok(()) + } + } } impl ops::Index> for Typifier { From fde91c1d9461a1e46c8ef487da0c13c6e51d12a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 1 Aug 2021 18:26:17 +0100 Subject: [PATCH 1176/2212] [glsl-in] Implicit splat min builtin --- src/front/glsl/functions.rs | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 5fad4e7b2..5e9ac872a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -598,7 +598,7 @@ impl Program<'_> { body, ))) } - "max" => { + "min" | "max" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } @@ -606,23 +606,22 @@ impl Program<'_> { let (mut arg0, arg0_meta) = args[0]; let (mut arg1, arg1_meta) = args[1]; - let arg0_size = match *self.resolve_type(ctx, arg0, arg0_meta)? { - TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - let arg1_size = match *self.resolve_type(ctx, arg1, arg1_meta)? { - TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - ctx.binary_implicit_conversion(self, &mut arg0, arg0_meta, &mut arg1, arg1_meta)?; - ctx.implicit_splat(self, &mut arg0, arg0_meta, arg1_size)?; - ctx.implicit_splat(self, &mut arg1, arg1_meta, arg0_size)?; + if let TypeInner::Vector { size, .. } = *self.resolve_type(ctx, arg0, arg0_meta)? { + ctx.implicit_splat(self, &mut arg1, arg1_meta, Some(size))?; + } + if let TypeInner::Vector { size, .. } = *self.resolve_type(ctx, arg1, arg1_meta)? { + ctx.implicit_splat(self, &mut arg0, arg0_meta, Some(size))?; + } Ok(Some(ctx.add_expression( Expression::Math { - fun: MathFunction::Max, + fun: match name.as_str() { + "min" => MathFunction::Min, + "max" => MathFunction::Max, + _ => unreachable!(), + }, arg: arg0, arg1: Some(arg1), arg2: None, @@ -630,8 +629,8 @@ impl Program<'_> { body, ))) } - "pow" | "dot" | "min" | "reflect" | "cross" | "outerProduct" | "distance" | "step" - | "modf" | "frexp" | "ldexp" => { + "pow" | "dot" | "reflect" | "cross" | "outerProduct" | "distance" | "step" | "modf" + | "frexp" | "ldexp" => { if args.len() != 2 { return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); } @@ -646,7 +645,6 @@ impl Program<'_> { fun: match name.as_str() { "pow" => MathFunction::Pow, "dot" => MathFunction::Dot, - "min" => MathFunction::Min, "reflect" => MathFunction::Reflect, "cross" => MathFunction::Cross, "outerProduct" => MathFunction::Outer, From 08302b5078d44f1d4f713fce5095bd0829fcf0ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 1 Aug 2021 18:29:46 +0100 Subject: [PATCH 1177/2212] [glsl-in] Fix missing implicit conversion in mix --- src/front/glsl/functions.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 5e9ac872a..ccbc4f03f 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -679,6 +679,13 @@ impl Program<'_> { &mut selector, selector_meta, )?; + ctx.binary_implicit_conversion( + self, + &mut arg1, + arg1_meta, + &mut selector, + selector_meta, + )?; let is_vector = match *self.resolve_type(ctx, selector, selector_meta)? { TypeInner::Vector { .. } => true, From bcfe1f6f2817639d85e761266afcf0a7a41ebcc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 1 Aug 2021 18:34:32 +0100 Subject: [PATCH 1178/2212] [glsl-in] Parse some more memory qualifiers --- src/front/glsl/ast.rs | 3 ++- src/front/glsl/lex.rs | 5 ++++- src/front/glsl/parser.rs | 27 ++++++++++++++++++++++----- src/front/glsl/token.rs | 4 ++++ src/front/glsl/variables.rs | 7 +++---- 5 files changed, 35 insertions(+), 11 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index be1ebf704..f90e6ebbc 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -8,7 +8,7 @@ use crate::{ proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, Expression, FastHashMap, Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, RelationalFunction, ResourceBinding, Sampling, ScalarKind, ScalarValue, ShaderStage, Statement, - StorageClass, Type, TypeInner, UnaryOperator, VectorSize, + StorageAccess, StorageClass, Type, TypeInner, UnaryOperator, VectorSize, }; use core::convert::TryFrom; use std::ops::Index; @@ -1054,6 +1054,7 @@ pub enum TypeQualifier { Layout(StructLayout), Precision(Precision), EarlyFragmentTests, + StorageAccess(StorageAccess), } #[derive(Debug, Clone)] diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index e12cb5e3e..07c4d4507 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -3,7 +3,7 @@ use super::{ token::{SourceMetadata, Token, TokenValue}, types::parse_type, }; -use crate::FastHashMap; +use crate::{FastHashMap, StorageAccess}; use pp_rs::{ pp::Preprocessor, token::{Punct, Token as PPToken, TokenValue as PPTokenValue}, @@ -76,6 +76,9 @@ impl<'a> Iterator for Lexer<'a> { "highp" => TokenValue::PrecisionQualifier(Precision::High), "mediump" => TokenValue::PrecisionQualifier(Precision::Medium), "lowp" => TokenValue::PrecisionQualifier(Precision::Low), + "restrict" => TokenValue::Restrict, + "readonly" => TokenValue::StorageAccess(StorageAccess::LOAD), + "writeonly" => TokenValue::StorageAccess(StorageAccess::STORE), // values "true" => TokenValue::BoolConstant(true), "false" => TokenValue::BoolConstant(false), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index a5b62e8ca..bb87a620e 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -18,7 +18,7 @@ use crate::{ StructMember, SwitchCase, Type, TypeInner, UnaryOperator, }; use core::convert::TryFrom; -use std::{iter::Peekable, mem}; +use std::iter::Peekable; type Result = std::result::Result; @@ -216,6 +216,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { | TokenValue::Out | TokenValue::Uniform | TokenValue::Buffer + | TokenValue::Restrict + | TokenValue::StorageAccess(_) | TokenValue::Layout => true, _ => false, }) @@ -249,6 +251,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { ), TokenValue::Sampling(s) => TypeQualifier::Sampling(s), TokenValue::PrecisionQualifier(p) => TypeQualifier::Precision(p), + TokenValue::StorageAccess(access) => TypeQualifier::StorageAccess(access), + TokenValue::Restrict => continue, _ => unreachable!(), }, token.meta, @@ -1601,9 +1605,15 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { } } - let fall_through = body.iter().any(|s| { - mem::discriminant(s) == mem::discriminant(&Statement::Break) - }); + let mut fall_through = true; + + for (i, stmt) in body.iter().enumerate() { + if let Statement::Break = *stmt { + fall_through = false; + body.drain(i..); + break; + } + } cases.push(SwitchCase { value, @@ -1625,7 +1635,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { loop { match self.expect_peek()?.value { TokenValue::Case | TokenValue::RightBrace => break, - _ => self.parse_statement(ctx, &mut &mut default)?, + _ => self.parse_statement(ctx, &mut default)?, + } + } + + for (i, stmt) in default.iter().enumerate() { + if let Statement::Break = *stmt { + default.drain(i..); + break; } } } diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index b1f147ab7..616c7d2d3 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -56,6 +56,10 @@ pub enum TokenValue { Uniform, Buffer, Const, + + Restrict, + StorageAccess(crate::StorageAccess), + Interpolation(Interpolation), Sampling(Sampling), Precision, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 99a410a57..da857cd09 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -339,6 +339,7 @@ impl Program<'_> { let mut sampling = None; let mut layout = None; let mut precision = None; + let mut access = StorageAccess::all(); for &(ref qualifier, meta) in qualifiers { match *qualifier { @@ -393,6 +394,7 @@ impl Program<'_> { meta, "Cannot use more than one precision qualifier per declaration" ), + TypeQualifier::StorageAccess(a) => access &= a, _ => { return Err(ErrorKind::SemanticError( meta, @@ -488,15 +490,12 @@ impl Program<'_> { return Ok(GlobalOrConstant::Constant(init)); } - // TODO: Add support for qualifiers such as readonly, writeonly and readwrite let class = match self.module.types[ty].inner { TypeInner::Image { .. } => StorageClass::Handle, TypeInner::Sampler { .. } => StorageClass::Handle, _ => { if let StorageQualifier::StorageClass(StorageClass::Storage { .. }) = storage { - StorageClass::Storage { - access: StorageAccess::all(), - } + StorageClass::Storage { access } } else { match storage { StorageQualifier::StorageClass(class) => class, From da77e1f847b1c5adede50d59f5fdfdf8f3637074 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 1 Aug 2021 18:35:18 +0100 Subject: [PATCH 1179/2212] [glsl-in] Accept precision in local variable --- src/front/glsl/variables.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index da857cd09..143e38fc1 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -548,6 +548,7 @@ impl Program<'_> { } let mut mutable = true; + let mut precision = None; for &(ref qualifier, meta) in qualifiers { match *qualifier { @@ -561,6 +562,12 @@ impl Program<'_> { mutable = false; } + TypeQualifier::Precision(ref p) => qualifier_arm!( + p, + precision, + meta, + "Cannot use more than one precision qualifier per declaration" + ), _ => { return Err(ErrorKind::SemanticError( meta, From c084e2cfa80cefdf672dc138113d346f6999004b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 1 Aug 2021 18:35:46 +0100 Subject: [PATCH 1180/2212] [glsl-in] Handle Pow in constant evaluation --- src/front/glsl/constants.rs | 46 +++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 9f5036aa8..a0811d0c3 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -49,6 +49,8 @@ pub enum ConstantSolvingError { InvalidUnaryOpArg, #[error("Cannot apply the binary op to the arguments")] InvalidBinaryOpArgs, + #[error("Cannot apply math function to type")] + InvalidMathArg, #[error("Splat/swizzle type is not registered")] DestinationTypeNotFound, #[error("Not implemented: {0}")] @@ -154,8 +156,48 @@ impl<'a> ConstantSolver<'a> { self.binary_op(op, left_constant, right_constant) } - Expression::Math { fun, .. } => { - Err(ConstantSolvingError::NotImplemented(format!("{:?}", fun))) + Expression::Math { fun, arg, arg1, .. } => { + let arg = self.solve(arg)?; + let arg1 = arg1.map(|arg| self.solve(arg)).transpose()?; + + let const0 = &self.constants[arg].inner; + let const1 = arg1.map(|arg| &self.constants[arg].inner); + + match fun { + crate::MathFunction::Pow => { + let (value, width) = match (const0, const1.unwrap()) { + ( + &ConstantInner::Scalar { + width, + value: value0, + }, + &ConstantInner::Scalar { value: value1, .. }, + ) => ( + match (value0, value1) { + (ScalarValue::Sint(a), ScalarValue::Sint(b)) => { + ScalarValue::Sint(a.pow(b as u32)) + } + (ScalarValue::Uint(a), ScalarValue::Uint(b)) => { + ScalarValue::Uint(a.pow(b as u32)) + } + (ScalarValue::Float(a), ScalarValue::Float(b)) => { + ScalarValue::Float(a.powf(b)) + } + _ => return Err(ConstantSolvingError::InvalidMathArg), + }, + width, + ), + _ => return Err(ConstantSolvingError::InvalidMathArg), + }; + + Ok(self.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { width, value }, + })) + } + _ => Err(ConstantSolvingError::NotImplemented(format!("{:?}", fun))), + } } Expression::As { convert, From 6f476eeafe3c582b9d91acae01bbe4fc18f02d76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 1 Aug 2021 18:36:37 +0100 Subject: [PATCH 1181/2212] [glsl-in] Fix span of gvec3 in layouter --- src/front/glsl/offset.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 6d1dee99c..72aa9570d 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -51,14 +51,10 @@ pub fn calculate_offset( // consuming N basic machine units, the base alignment is 2N or 4N, respectively. // 3. If the member is a three-component vector with components consuming N // basic machine units, the base alignment is 4N. - TypeInner::Vector { size, width, .. } => { - let val = match size { - crate::VectorSize::Tri => 4 * width as u32, - _ => size as u32 * width as u32, - }; - - (val, val) - } + TypeInner::Vector { size, width, .. } => match size { + crate::VectorSize::Tri => (4 * width as u32, 3 * width as u32), + _ => (size as u32 * width as u32, size as u32 * width as u32), + }, // 4. If the member is an array of scalars or vectors, the base alignment and array // stride are set to match the base alignment of a single array element, according // to rules (1), (2), and (3), and rounded up to the base alignment of a vec4. From 057dc3100d9e7b59e417915eca71cc8d7bff1fc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 4 Aug 2021 00:39:25 +0100 Subject: [PATCH 1182/2212] [glsl-in] Remove support for multiple entry points --- cli/src/main.rs | 15 +- src/front/glsl/ast.rs | 68 +--- src/front/glsl/functions.rs | 359 +++++++----------- src/front/glsl/mod.rs | 6 +- src/front/glsl/parser.rs | 20 +- src/front/glsl/parser_tests.rs | 129 +++---- src/front/glsl/variables.rs | 20 +- tests/in/glsl/multiple_entry_points.glsl | 19 - .../in/glsl/multiple_entry_points.params.ron | 6 - tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 11 +- tests/snapshots.rs | 53 +-- 11 files changed, 217 insertions(+), 489 deletions(-) delete mode 100644 tests/in/glsl/multiple_entry_points.glsl delete mode 100644 tests/in/glsl/multiple_entry_points.params.ron diff --git a/cli/src/main.rs b/cli/src/main.rs index 701e1cad1..7bf013489 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -223,14 +223,11 @@ fn run() -> Result<(), Box> { } "vert" => { let input = fs::read_to_string(input_path)?; - let mut entry_points = naga::FastHashMap::default(); - entry_points.insert("main".to_string(), naga::ShaderStage::Vertex); naga::front::glsl::parse_str( &input, &naga::front::glsl::Options { - entry_points, + stage: naga::ShaderStage::Vertex, defines: Default::default(), - strip_unused_linkages: false, }, ) .unwrap_or_else(|err| { @@ -241,14 +238,11 @@ fn run() -> Result<(), Box> { } "frag" => { let input = fs::read_to_string(input_path)?; - let mut entry_points = naga::FastHashMap::default(); - entry_points.insert("main".to_string(), naga::ShaderStage::Fragment); naga::front::glsl::parse_str( &input, &naga::front::glsl::Options { - entry_points, + stage: naga::ShaderStage::Fragment, defines: Default::default(), - strip_unused_linkages: false, }, ) .unwrap_or_else(|err| { @@ -259,14 +253,11 @@ fn run() -> Result<(), Box> { } "comp" => { let input = fs::read_to_string(input_path)?; - let mut entry_points = naga::FastHashMap::default(); - entry_points.insert("main".to_string(), naga::ShaderStage::Compute); naga::front::glsl::parse_str( &input, &naga::front::glsl::Options { - entry_points, + stage: naga::ShaderStage::Compute, defines: Default::default(), - strip_unused_linkages: false, }, ) .unwrap_or_else(|err| { diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index f90e6ebbc..2655b2b45 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -47,46 +47,19 @@ pub struct FunctionDeclaration { pub void: bool, } -bitflags::bitflags! { - pub struct EntryArgUse: u32 { - const READ = 0x1; - const WRITE = 0x2; - } -} - -bitflags::bitflags! { - pub struct PrologueStage: u32 { - const VERTEX = 0x1; - const FRAGMENT = 0x2; - const COMPUTE = 0x4; - } -} - -impl From for PrologueStage { - fn from(stage: ShaderStage) -> Self { - match stage { - ShaderStage::Vertex => PrologueStage::VERTEX, - ShaderStage::Fragment => PrologueStage::FRAGMENT, - ShaderStage::Compute => PrologueStage::COMPUTE, - } - } -} - #[derive(Debug)] pub struct EntryArg { pub name: Option, pub binding: Binding, pub handle: Handle, - pub prologue: PrologueStage, pub storage: StorageQualifier, } #[derive(Debug)] -pub struct Program<'a> { +pub struct Program { pub version: u16, pub profile: Profile, - pub entry_points: &'a FastHashMap, - pub strip_unused_linkages: bool, + pub stage: ShaderStage, pub workgroup_size: [u32; 3], pub early_fragment_tests: bool, @@ -97,25 +70,19 @@ pub struct Program<'a> { pub global_variables: Vec<(String, GlobalLookup)>, pub entry_args: Vec, - pub entries: Vec<(String, ShaderStage, Handle)>, - // TODO: More efficient representation - pub function_arg_use: Vec>, + pub entry_point: Option>, pub module: Module, } -impl<'a> Program<'a> { - pub fn new( - entry_points: &'a FastHashMap, - strip_unused_linkages: bool, - ) -> Program<'a> { +impl Program { + pub fn new(stage: ShaderStage) -> Program { Program { version: 0, profile: Profile::Core, - entry_points, - strip_unused_linkages, + stage, - workgroup_size: [1; 3], + workgroup_size: [if stage == ShaderStage::Compute { 1 } else { 0 }; 3], early_fragment_tests: false, lookup_function: FastHashMap::default(), @@ -123,8 +90,7 @@ impl<'a> Program<'a> { global_variables: Vec::new(), entry_args: Vec::new(), - entries: Vec::new(), - function_arg_use: Vec::new(), + entry_point: None, module: Module::default(), } @@ -214,7 +180,6 @@ pub struct Context<'function> { pub locals: &'function mut Arena, pub arguments: &'function mut Vec, pub parameters_info: Vec, - pub arg_use: Vec, //TODO: Find less allocation heavy representation pub scopes: Vec>, @@ -239,7 +204,6 @@ impl<'function> Context<'function> { locals, arguments, parameters_info: Vec::new(), - arg_use: vec![EntryArgUse::empty(); program.entry_args.len()], scopes: vec![FastHashMap::default()], lookup_global_var_exps: FastHashMap::with_capacity_and_hasher( @@ -647,21 +611,11 @@ impl<'function> Context<'function> { )); } - if let Some(idx) = var.entry_arg { - self.arg_use[idx] |= EntryArgUse::WRITE - } - var.expr + } else if var.load { + self.add_expression(Expression::Load { pointer: var.expr }, body) } else { - if let Some(idx) = var.entry_arg { - self.arg_use[idx] |= EntryArgUse::READ - } - - if var.load { - self.add_expression(Expression::Load { pointer: var.expr }, body) - } else { - var.expr - } + var.expr } } HirExprKind::Call(call) if !lhs => { diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index ccbc4f03f..e22fe2135 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -2,8 +2,7 @@ use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, ImageClass, ImageDimension, ImageQuery, LocalVariable, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind, - ScalarValue, ShaderStage, Statement, StructMember, SwizzleComponent, Type, TypeInner, - VectorSize, + ScalarValue, Statement, StructMember, SwizzleComponent, Type, TypeInner, VectorSize, }; use super::{ast::*, error::ErrorKind, SourceMetadata}; @@ -17,7 +16,7 @@ struct CoordComponents { array_index: Option>, } -impl Program<'_> { +impl Program { fn add_constant_value(&mut self, scalar_kind: ScalarKind, value: u64) -> Handle { let value = match scalar_kind { ScalarKind::Uint => ScalarValue::Uint(value), @@ -1031,65 +1030,65 @@ impl Program<'_> { parameters: Vec>, parameters_info: Vec, meta: SourceMetadata, - ) -> Result, ErrorKind> { + ) -> Result<(), ErrorKind> { ensure_block_returns(&mut function.body); - let stage = self.entry_points.get(&name); - Ok(if let Some(&stage) = stage { + if name.as_str() == "main" { let handle = self.module.functions.append(function); - self.entries.push((name, stage, handle)); - self.function_arg_use.push(Vec::new()); - handle - } else { - let void = function.result.is_none(); + return if self.entry_point.replace(handle).is_some() { + Err(ErrorKind::SemanticError(meta, "main defined twice".into())) + } else { + Ok(()) + }; + } - let &mut Program { - ref mut lookup_function, - ref mut module, - .. - } = self; + let void = function.result.is_none(); - let declarations = lookup_function.entry(name).or_default(); + let &mut Program { + ref mut lookup_function, + ref mut module, + .. + } = self; - 'outer: for decl in declarations.iter_mut() { - if parameters.len() != decl.parameters.len() { - continue; - } + let declarations = lookup_function.entry(name).or_default(); - for (new_parameter, old_parameter) in parameters.iter().zip(decl.parameters.iter()) - { - let new_inner = &module.types[*new_parameter].inner; - let old_inner = &module.types[*old_parameter].inner; - - if new_inner != old_inner { - continue 'outer; - } - } - - if decl.defined { - return Err(ErrorKind::SemanticError( - meta, - "Function already defined".into(), - )); - } - - decl.defined = true; - decl.parameters_info = parameters_info; - *self.module.functions.get_mut(decl.handle) = function; - return Ok(decl.handle); + 'outer: for decl in declarations.iter_mut() { + if parameters.len() != decl.parameters.len() { + continue; } - self.function_arg_use.push(Vec::new()); - let handle = module.functions.append(function); - declarations.push(FunctionDeclaration { - parameters, - parameters_info, - handle, - defined: true, - void, - }); - handle - }) + for (new_parameter, old_parameter) in parameters.iter().zip(decl.parameters.iter()) { + let new_inner = &module.types[*new_parameter].inner; + let old_inner = &module.types[*old_parameter].inner; + + if new_inner != old_inner { + continue 'outer; + } + } + + if decl.defined { + return Err(ErrorKind::SemanticError( + meta, + "Function already defined".into(), + )); + } + + decl.defined = true; + decl.parameters_info = parameters_info; + *self.module.functions.get_mut(decl.handle) = function; + return Ok(()); + } + + let handle = module.functions.append(function); + declarations.push(FunctionDeclaration { + parameters, + parameters_info, + handle, + defined: true, + void, + }); + + Ok(()) } pub fn add_prototype( @@ -1131,7 +1130,6 @@ impl Program<'_> { )); } - self.function_arg_use.push(Vec::new()); let handle = module.functions.append(function); declarations.push(FunctionDeclaration { parameters, @@ -1144,198 +1142,101 @@ impl Program<'_> { Ok(()) } - fn check_call_global( - &self, - caller: Handle, - function_arg_use: &mut [Vec], - stmt: &Statement, - ) { - match *stmt { - Statement::Block(ref block) => { - for stmt in block { - self.check_call_global(caller, function_arg_use, stmt) - } - } - Statement::If { - ref accept, - ref reject, - .. - } => { - for stmt in accept.iter().chain(reject.iter()) { - self.check_call_global(caller, function_arg_use, stmt) - } - } - Statement::Switch { - ref cases, - ref default, - .. - } => { - for stmt in cases - .iter() - .flat_map(|c| c.body.iter()) - .chain(default.iter()) - { - self.check_call_global(caller, function_arg_use, stmt) - } - } - Statement::Loop { - ref body, - ref continuing, - } => { - for stmt in body.iter().chain(continuing.iter()) { - self.check_call_global(caller, function_arg_use, stmt) - } - } - Statement::Call { function, .. } => { - let callee_len = function_arg_use[function.index()].len(); - let caller_len = function_arg_use[caller.index()].len(); - function_arg_use[caller.index()].extend( - std::iter::repeat(EntryArgUse::empty()) - .take(callee_len.saturating_sub(caller_len)), - ); + pub fn add_entry_point(&mut self, function: Handle) -> Result<(), ErrorKind> { + let mut arguments = Vec::new(); + let mut expressions = Arena::new(); + let mut body = Vec::new(); - for i in 0..callee_len.min(caller_len) { - let callee_use = function_arg_use[function.index()][i]; - function_arg_use[caller.index()][i] |= callee_use - } - } - _ => {} - } - } - - pub fn add_entry_points(&mut self) { - let mut function_arg_use = Vec::new(); - std::mem::swap(&mut self.function_arg_use, &mut function_arg_use); - - for (handle, function) in self.module.functions.iter() { - for stmt in function.body.iter() { - self.check_call_global(handle, &mut function_arg_use, stmt) - } - } - - for (name, stage, function) in self.entries.iter().cloned() { - let mut arguments = Vec::new(); - let mut expressions = Arena::new(); - let mut body = Vec::new(); - - let can_strip_stage_inputs = - self.strip_unused_linkages || stage != ShaderStage::Fragment; - let can_strip_stage_outputs = - self.strip_unused_linkages || stage != ShaderStage::Vertex; - - for (i, arg) in self.entry_args.iter().enumerate() { - if arg.storage != StorageQualifier::Input { - continue; - } - - if !arg.prologue.contains(stage.into()) { - continue; - } - - let is_used = function_arg_use[function.index()] - .get(i) - .map_or(false, |u| u.contains(EntryArgUse::READ)); - - if can_strip_stage_inputs && !is_used { - continue; - } - - let ty = self.module.global_variables[arg.handle].ty; - let idx = arguments.len() as u32; - - arguments.push(FunctionArgument { - name: arg.name.clone(), - ty, - binding: Some(arg.binding.clone()), - }); - - let pointer = expressions.append(Expression::GlobalVariable(arg.handle)); - let value = expressions.append(Expression::FunctionArgument(idx)); - - body.push(Statement::Store { pointer, value }); + for arg in self.entry_args.iter() { + if arg.storage != StorageQualifier::Input { + continue; } - body.push(Statement::Call { - function, - arguments: Vec::new(), - result: None, + let ty = self.module.global_variables[arg.handle].ty; + let idx = arguments.len() as u32; + + arguments.push(FunctionArgument { + name: arg.name.clone(), + ty, + binding: Some(arg.binding.clone()), }); - let mut span = 0; - let mut members = Vec::new(); - let mut components = Vec::new(); + let pointer = expressions.append(Expression::GlobalVariable(arg.handle)); + let value = expressions.append(Expression::FunctionArgument(idx)); - for (i, arg) in self.entry_args.iter().enumerate() { - if arg.storage != StorageQualifier::Output { - continue; - } + body.push(Statement::Store { pointer, value }); + } - let is_used = function_arg_use[function.index()] - .get(i) - .map_or(false, |u| u.contains(EntryArgUse::WRITE)); + body.push(Statement::Call { + function, + arguments: Vec::new(), + result: None, + }); - if can_strip_stage_outputs && !is_used { - continue; - } + let mut span = 0; + let mut members = Vec::new(); + let mut components = Vec::new(); - let ty = self.module.global_variables[arg.handle].ty; - - members.push(StructMember { - name: arg.name.clone(), - ty, - binding: Some(arg.binding.clone()), - offset: span, - }); - - span += self.module.types[ty].inner.span(&self.module.constants); - - let pointer = expressions.append(Expression::GlobalVariable(arg.handle)); - let len = expressions.len(); - let load = expressions.append(Expression::Load { pointer }); - body.push(Statement::Emit(expressions.range_from(len))); - components.push(load) + for arg in self.entry_args.iter() { + if arg.storage != StorageQualifier::Output { + continue; } - let (ty, value) = if !components.is_empty() { - let ty = self.module.types.append(Type { - name: None, - inner: TypeInner::Struct { - top_level: false, - members, - span, - }, - }); + let ty = self.module.global_variables[arg.handle].ty; - let len = expressions.len(); - let res = expressions.append(Expression::Compose { ty, components }); - body.push(Statement::Emit(expressions.range_from(len))); + members.push(StructMember { + name: arg.name.clone(), + ty, + binding: Some(arg.binding.clone()), + offset: span, + }); - (Some(ty), Some(res)) - } else { - (None, None) - }; + span += self.module.types[ty].inner.span(&self.module.constants); - body.push(Statement::Return { value }); + let pointer = expressions.append(Expression::GlobalVariable(arg.handle)); + let len = expressions.len(); + let load = expressions.append(Expression::Load { pointer }); + body.push(Statement::Emit(expressions.range_from(len))); + components.push(load) + } - self.module.entry_points.push(EntryPoint { - name, - stage, - early_depth_test: Some(crate::EarlyDepthTest { conservative: None }) - .filter(|_| self.early_fragment_tests && stage == crate::ShaderStage::Fragment), - workgroup_size: if let crate::ShaderStage::Compute = stage { - self.workgroup_size - } else { - [0; 3] - }, - function: Function { - arguments, - expressions, - body, - result: ty.map(|ty| FunctionResult { ty, binding: None }), - ..Default::default() + let (ty, value) = if !components.is_empty() { + let ty = self.module.types.append(Type { + name: None, + inner: TypeInner::Struct { + top_level: false, + members, + span, }, }); - } + + let len = expressions.len(); + let res = expressions.append(Expression::Compose { ty, components }); + body.push(Statement::Emit(expressions.range_from(len))); + + (Some(ty), Some(res)) + } else { + (None, None) + }; + + body.push(Statement::Return { value }); + + self.module.entry_points.push(EntryPoint { + name: "main".to_string(), + stage: self.stage, + early_depth_test: Some(crate::EarlyDepthTest { conservative: None }) + .filter(|_| self.early_fragment_tests), + workgroup_size: self.workgroup_size, + function: Function { + arguments, + expressions, + body, + result: ty.map(|ty| FunctionResult { ty, binding: None }), + ..Default::default() + }, + }); + + Ok(()) } /// Helper function for texture calls, splits the vector argument into it's components diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 654715654..88966d034 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -20,15 +20,13 @@ mod token; mod types; mod variables; -#[derive(Default)] pub struct Options { - pub entry_points: FastHashMap, + pub stage: ShaderStage, pub defines: FastHashMap, - pub strip_unused_linkages: bool, } pub fn parse_str(source: &str, options: &Options) -> Result { - let mut program = Program::new(&options.entry_points, options.strip_unused_linkages); + let mut program = Program::new(options.stage); let lex = lex::Lexer::new(source, &options.defines); let mut parser = parser::Parser::new(&mut program, lex); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index bb87a620e..dfea73d3b 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -22,13 +22,13 @@ use std::iter::Peekable; type Result = std::result::Result; -pub struct Parser<'source, 'program, 'options> { - program: &'program mut Program<'options>, +pub struct Parser<'source, 'program> { + program: &'program mut Program, lexer: Peekable>, } -impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { - pub fn new(program: &'program mut Program<'options>, lexer: Lexer<'source>) -> Self { +impl<'source, 'program> Parser<'source, 'program> { + pub fn new(program: &'program mut Program, lexer: Lexer<'source>) -> Self { Parser { program, lexer: lexer.peekable(), @@ -81,7 +81,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.parse_external_declaration()?; } - self.program.add_entry_points(); + if let Some(handle) = self.program.entry_point { + self.program.add_entry_point(handle)?; + } Ok(()) } @@ -741,11 +743,9 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { self.parse_compound_statement(&mut context, &mut body)?; let Context { - arg_use, - parameters_info, - .. + parameters_info, .. } = context; - let handle = self.program.add_function( + self.program.add_function( Function { name: Some(name.clone()), result, @@ -761,8 +761,6 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> { meta, )?; - self.program.function_arg_use[handle.index()] = arg_use; - Ok(true) } _ if external => Err(ErrorKind::InvalidToken( diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 7c8001371..72372c987 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -10,11 +10,8 @@ use crate::{ ShaderStage, }; -fn parse_program<'a>( - source: &str, - entry_points: &'a crate::FastHashMap, -) -> Result, ErrorKind> { - let mut program = Program::new(entry_points, true); +fn parse_program(source: &str, stage: ShaderStage) -> Result { + let mut program = Program::new(stage); let defines = crate::FastHashMap::default(); let lex = Lexer::new(source, &defines); let mut parser = parser::Parser::new(&mut program, lex); @@ -25,30 +22,30 @@ fn parse_program<'a>( #[test] fn version() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Vertex); // invalid versions assert_eq!( - parse_program("#version 99000", &entry_points) + parse_program("#version 99000", ShaderStage::Vertex) .err() .unwrap(), ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 14 }, 99000), ); assert_eq!( - parse_program("#version 449", &entry_points).err().unwrap(), + parse_program("#version 449", ShaderStage::Vertex) + .err() + .unwrap(), ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 12 }, 449) ); assert_eq!( - parse_program("#version 450 smart", &entry_points) + parse_program("#version 450 smart", ShaderStage::Vertex) .err() .unwrap(), ErrorKind::InvalidProfile(SourceMetadata { start: 13, end: 18 }, "smart".into()) ); assert_eq!( - parse_program("#version 450\nvoid f(){} #version 450", &entry_points) + parse_program("#version 450\nvoid f(){} #version 450", ShaderStage::Vertex) .err() .unwrap(), ErrorKind::InvalidToken( @@ -61,21 +58,18 @@ fn version() { ); // valid versions - let program = parse_program(" # version 450\nvoid main() {}", &entry_points).unwrap(); + let program = parse_program(" # version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); assert_eq!((program.version, program.profile), (450, Profile::Core)); - let program = parse_program("#version 450\nvoid main() {}", &entry_points).unwrap(); + let program = parse_program("#version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); assert_eq!((program.version, program.profile), (450, Profile::Core)); - let program = parse_program("#version 450 core\nvoid main() {}", &entry_points).unwrap(); + let program = parse_program("#version 450 core\nvoid main() {}", ShaderStage::Vertex).unwrap(); assert_eq!((program.version, program.profile), (450, Profile::Core)); } #[test] fn control_flow() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Vertex); - let _program = parse_program( r#" # version 450 @@ -87,7 +81,7 @@ fn control_flow() { } } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -100,7 +94,7 @@ fn control_flow() { } } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -122,7 +116,7 @@ fn control_flow() { } } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); let _program = parse_program( @@ -138,7 +132,7 @@ fn control_flow() { } while(x >= 4) } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -154,16 +148,13 @@ fn control_flow() { return x; } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); } #[test] fn declarations() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Fragment); - let _program = parse_program( r#" #version 450 @@ -174,7 +165,7 @@ fn declarations() { layout(early_fragment_tests) in; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -188,7 +179,7 @@ fn declarations() { ivec4 atlas_offs; }; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -202,7 +193,7 @@ fn declarations() { ivec4 atlas_offs; }; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -216,7 +207,7 @@ fn declarations() { ivec4 atlas_offs; }; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -234,7 +225,7 @@ fn declarations() { block_var.load_time * block_var.model_offs; } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -243,7 +234,7 @@ fn declarations() { #version 450 float vector = vec4(1.0 / 17.0, 9.0 / 17.0, 3.0 / 17.0, 11.0 / 17.0); "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -252,16 +243,13 @@ fn declarations() { #version 450 precision highp float; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); } #[test] fn textures() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Fragment); - let _program = parse_program( r#" #version 450 @@ -274,16 +262,13 @@ fn textures() { o_color.a = texture(sampler2D(tex, tex_sampler), v_uv, 2.0).a; } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); } #[test] fn functions() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Vertex); - parse_program( r#" # version 450 @@ -292,7 +277,7 @@ fn functions() { void main() {} "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -305,7 +290,7 @@ fn functions() { void main() {} "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -316,7 +301,7 @@ fn functions() { void main() {} "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -327,7 +312,7 @@ fn functions() { return p.x; } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -351,7 +336,7 @@ fn functions() { return p.x; } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -367,7 +352,7 @@ fn functions() { return p.x; } "#, - &entry_points + ShaderStage::Vertex ) .err() .unwrap(), @@ -393,7 +378,7 @@ fn functions() { callee(1u); } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -408,7 +393,7 @@ fn functions() { textureLod(sampler2D(t_noise, s_noise), vec2(1.0), 0); } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -424,7 +409,7 @@ fn functions() { fun(vec2(1.0), a); } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); } @@ -433,9 +418,6 @@ fn functions() { fn constants() { use crate::{Constant, ConstantInner, ScalarValue}; - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Vertex); - let program = parse_program( r#" # version 450 @@ -443,7 +425,7 @@ fn constants() { float global = a; const float b = a; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -466,9 +448,6 @@ fn constants() { #[test] fn function_overloading() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Vertex); - parse_program( r#" # version 450 @@ -485,16 +464,13 @@ fn function_overloading() { vec3 v4 = saturate(vec4(0.5, 1.5, 2.5, 3.5)); } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); } #[test] fn implicit_conversions() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Vertex); - parse_program( r#" # version 450 @@ -504,7 +480,7 @@ fn implicit_conversions() { float c = 1 + 2.0; } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -519,7 +495,7 @@ fn implicit_conversions() { test(1.0); } "#, - &entry_points + ShaderStage::Vertex ) .err() .unwrap(), @@ -543,7 +519,7 @@ fn implicit_conversions() { test(1); } "#, - &entry_points + ShaderStage::Vertex ) .err() .unwrap(), @@ -559,9 +535,6 @@ fn implicit_conversions() { #[test] fn structs() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Fragment); - parse_program( r#" # version 450 @@ -569,7 +542,7 @@ fn structs() { vec4 pos; } xx; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap_err(); @@ -580,7 +553,7 @@ fn structs() { vec4 pos; }; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -592,7 +565,7 @@ fn structs() { vec4 vecs[NUM_VECS]; }; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -605,7 +578,7 @@ fn structs() { return Hello( vec4(1.0) ); } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -614,7 +587,7 @@ fn structs() { # version 450 struct Test {}; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap_err(); @@ -625,16 +598,13 @@ fn structs() { vec4 x; }; "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap_err(); } #[test] fn swizzles() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Fragment); - parse_program( r#" # version 450 @@ -645,7 +615,7 @@ fn swizzles() { v.xyz.zxy.yx.xy = vec2(5.0, 1.0); } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); @@ -657,7 +627,7 @@ fn swizzles() { v.xx = vec2(5.0); } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap_err(); @@ -669,16 +639,13 @@ fn swizzles() { v.w = 2.0; } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap_err(); } #[test] fn vector_indexing() { - let mut entry_points = crate::FastHashMap::default(); - entry_points.insert("".to_string(), ShaderStage::Fragment); - parse_program( r#" # version 450 @@ -687,7 +654,7 @@ fn vector_indexing() { return v[index] + 1.0; } "#, - &entry_points, + ShaderStage::Vertex, ) .unwrap(); } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 143e38fc1..dd66b4a15 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -31,7 +31,7 @@ pub enum GlobalOrConstant { Constant(Handle), } -impl Program<'_> { +impl Program { pub fn lookup_variable( &mut self, ctx: &mut Context, @@ -45,7 +45,7 @@ impl Program<'_> { return Ok(Some(global_var)); } - let mut add_builtin = |inner, builtin, mutable, prologue, storage| { + let mut add_builtin = |inner, builtin, mutable, storage| { let ty = self .module .types @@ -64,7 +64,6 @@ impl Program<'_> { name: None, binding: Binding::BuiltIn(builtin), handle, - prologue, storage, }); @@ -76,7 +75,6 @@ impl Program<'_> { mutable, }, )); - ctx.arg_use.push(EntryArgUse::empty()); let expr = ctx.add_expression(Expression::GlobalVariable(handle), body); ctx.lookup_global_var_exps.insert( @@ -100,7 +98,6 @@ impl Program<'_> { }, BuiltIn::Position, true, - PrologueStage::empty(), StorageQualifier::Output, ), "gl_FragCoord" => add_builtin( @@ -111,7 +108,6 @@ impl Program<'_> { }, BuiltIn::Position, false, - PrologueStage::FRAGMENT, StorageQualifier::Input, ), "gl_FragDepth" => add_builtin( @@ -121,7 +117,6 @@ impl Program<'_> { }, BuiltIn::FragDepth, true, - PrologueStage::empty(), StorageQualifier::Output, ), "gl_VertexIndex" => add_builtin( @@ -131,7 +126,6 @@ impl Program<'_> { }, BuiltIn::VertexIndex, false, - PrologueStage::VERTEX, StorageQualifier::Input, ), "gl_InstanceIndex" => add_builtin( @@ -141,7 +135,6 @@ impl Program<'_> { }, BuiltIn::InstanceIndex, false, - PrologueStage::VERTEX, StorageQualifier::Input, ), "gl_GlobalInvocationID" => add_builtin( @@ -152,7 +145,6 @@ impl Program<'_> { }, BuiltIn::GlobalInvocationId, false, - PrologueStage::COMPUTE, StorageQualifier::Input, ), "gl_FrontFacing" => add_builtin( @@ -162,7 +154,6 @@ impl Program<'_> { }, BuiltIn::FrontFacing, false, - PrologueStage::FRAGMENT, StorageQualifier::Input, ), "gl_PrimitiveID" => add_builtin( @@ -172,7 +163,6 @@ impl Program<'_> { }, BuiltIn::PrimitiveIndex, false, - PrologueStage::FRAGMENT, StorageQualifier::Input, ), _ => Ok(None), @@ -427,11 +417,6 @@ impl Program<'_> { if let Some(location) = location { let input = storage == StorageQualifier::Input; - let prologue = if input { - PrologueStage::all() - } else { - PrologueStage::empty() - }; let interpolation = self.module.types[ty].inner.scalar_kind().map(|kind| { if let ScalarKind::Float = kind { Interpolation::Perspective @@ -457,7 +442,6 @@ impl Program<'_> { sampling, }, handle, - prologue, storage, }); diff --git a/tests/in/glsl/multiple_entry_points.glsl b/tests/in/glsl/multiple_entry_points.glsl deleted file mode 100644 index 94f6c24be..000000000 --- a/tests/in/glsl/multiple_entry_points.glsl +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 -// vertex -void vert_main() { - gl_Position = vec4(1.0, 1.0, 1.0, 1.0); -} - -// fragment -layout(location = 0) out vec4 o_color; -void frag_main() { - o_color = vec4(1.0, 1.0, 1.0, 1.0); -} - -//compute -// layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in; -void comp_main() { - if (gl_GlobalInvocationID.x > 1) { - return; - } -} diff --git a/tests/in/glsl/multiple_entry_points.params.ron b/tests/in/glsl/multiple_entry_points.params.ron deleted file mode 100644 index f199d9836..000000000 --- a/tests/in/glsl/multiple_entry_points.params.ron +++ /dev/null @@ -1,6 +0,0 @@ -( - spv_version: (1, 0), - glsl_vert_ep_name: Some("vert_main"), - glsl_frag_ep_name: Some("frag_main"), - glsl_comp_ep_name: Some("comp_main"), -) diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 4bdf88b0e..d31cab2f3 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -19,7 +19,7 @@ struct VertexOutput { }; var Vertex_Position1: vec3; -var Vertex_Normal: vec3; +var Vertex_Normal1: vec3; var Vertex_Uv1: vec2; var v_Uv: vec2; [[group(0), binding(0)]] @@ -46,11 +46,12 @@ fn main1() { } [[stage(vertex)]] -fn main([[location(0)]] Vertex_Position: vec3, [[location(2)]] Vertex_Uv: vec2) -> VertexOutput { +fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Normal: vec3, [[location(2)]] Vertex_Uv: vec2) -> VertexOutput { Vertex_Position1 = Vertex_Position; + Vertex_Normal1 = Vertex_Normal; Vertex_Uv1 = Vertex_Uv; main1(); - let _e5: vec2 = v_Uv; - let _e7: vec4 = gl_Position; - return VertexOutput(_e5, _e7); + let _e7: vec2 = v_Uv; + let _e9: vec4 = gl_Position; + return VertexOutput(_e7, _e9); } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 7cc6a1143..8b4729968 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -55,15 +55,6 @@ struct Parameters { #[cfg(all(not(feature = "deserialize"), feature = "glsl-out"))] #[serde(default)] glsl_custom: bool, - #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] - #[serde(default)] - glsl_vert_ep_name: Option, - #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] - #[serde(default)] - glsl_frag_ep_name: Option, - #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] - #[serde(default)] - glsl_comp_ep_name: Option, #[cfg(all(feature = "deserialize", feature = "hlsl-out"))] #[serde(default)] hlsl: naga::back::hlsl::Options, @@ -530,50 +521,18 @@ fn convert_glsl_folder() { // No needed to validate ron files continue; } - let params_path = format!( - "{}/{}/glsl/{}.params.ron", - root, - BASE_DIR_IN, - PathBuf::from(&file_name).with_extension("").display() - ); - let is_params_used = PathBuf::from(¶ms_path).exists(); println!("Processing {}", file_name); - let mut entry_points = naga::FastHashMap::default(); - if is_params_used { - let params: Parameters = match fs::read_to_string(¶ms_path) { - Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), - Err(_) => panic!("Can't parse glsl params ron file: {:?}", ¶ms_path), - }; - - if let Some(vert) = params.glsl_vert_ep_name { - entry_points.insert(vert, naga::ShaderStage::Vertex); - }; - - if let Some(frag) = params.glsl_frag_ep_name { - entry_points.insert(frag, naga::ShaderStage::Fragment); - }; - - if let Some(comp) = params.glsl_comp_ep_name { - entry_points.insert(comp, naga::ShaderStage::Compute); - }; - } else { - let stage = match entry.path().extension().and_then(|s| s.to_str()).unwrap() { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - ext => panic!("Unknown extension for glsl file {}", ext), - }; - entry_points.insert("main".to_string(), stage); - } - - let strip_unused_linkages = entry_points.len() > 1; let module = naga::front::glsl::parse_str( &fs::read_to_string(entry.path()).expect("Couldn't find glsl file"), &naga::front::glsl::Options { - entry_points, + stage: match entry.path().extension().and_then(|s| s.to_str()).unwrap() { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + ext => panic!("Unknown extension for glsl file {}", ext), + }, defines: Default::default(), - strip_unused_linkages: strip_unused_linkages, }, ) .unwrap(); From a90aa9817bc9609f0bcf3e6582855033c3e942be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 2 Aug 2021 23:26:15 +0100 Subject: [PATCH 1183/2212] [glsl-in] Add support for non constant global init Glsl allows things such as ```glsl layout (location = 0) in vec4 a; vec4 b = a; ``` In this case `b` depends on `a` which can't be known at compile time, so it's necessary to add a small prologue to the entry point to initialize it. --- src/front/glsl/ast.rs | 123 ++++++++++-------- src/front/glsl/functions.rs | 19 ++- src/front/glsl/parser.rs | 90 +++++++------ src/front/glsl/variables.rs | 50 +++---- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 4 +- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 6 +- tests/out/wgsl/210-bevy-shader-vert.wgsl | 10 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 6 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 4 +- tests/out/wgsl/bevy-pbr-vert.wgsl | 12 +- tests/out/wgsl/bool-select-frag.wgsl | 4 +- tests/out/wgsl/clamp-splat-vert.wgsl | 4 +- .../out/wgsl/multiple_entry_points-glsl.wgsl | 8 +- tests/out/wgsl/quad_glsl-frag.wgsl | 4 +- tests/out/wgsl/quad_glsl-vert.wgsl | 6 +- 15 files changed, 194 insertions(+), 156 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 2655b2b45..2d9ba7bf4 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -220,68 +220,77 @@ impl<'function> Context<'function> { this.emit_start(); for &(ref name, lookup) in program.global_variables.iter() { - this.emit_flush(body); - let GlobalLookup { - kind, - entry_arg, - mutable, - } = lookup; - let (expr, load) = match kind { - GlobalLookupKind::Variable(v) => { - let res = ( - this.expressions.append(Expression::GlobalVariable(v)), - program.module.global_variables[v].class != StorageClass::Handle, - ); - this.emit_start(); - - res - } - GlobalLookupKind::BlockSelect(handle, index) => { - let base = this.expressions.append(Expression::GlobalVariable(handle)); - this.emit_start(); - let expr = this - .expressions - .append(Expression::AccessIndex { base, index }); - - (expr, { - let ty = program.module.global_variables[handle].ty; - - match program.module.types[ty].inner { - TypeInner::Struct { ref members, .. } => { - if let TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } = program.module.types[members[index as usize].ty].inner - { - false - } else { - true - } - } - _ => true, - } - }) - } - GlobalLookupKind::Constant(v) => { - let res = (this.expressions.append(Expression::Constant(v)), false); - this.emit_start(); - res - } - }; - - let var = VariableReference { - expr, - load, - mutable, - entry_arg, - }; - - this.lookup_global_var_exps.insert(name.into(), var); + this.add_global(name, lookup, program, body) } this } + pub fn add_global( + &mut self, + name: &str, + GlobalLookup { + kind, + entry_arg, + mutable, + }: GlobalLookup, + program: &Program, + body: &mut Block, + ) { + self.emit_flush(body); + let (expr, load) = match kind { + GlobalLookupKind::Variable(v) => { + let res = ( + self.expressions.append(Expression::GlobalVariable(v)), + program.module.global_variables[v].class != StorageClass::Handle, + ); + self.emit_start(); + + res + } + GlobalLookupKind::BlockSelect(handle, index) => { + let base = self.expressions.append(Expression::GlobalVariable(handle)); + self.emit_start(); + let expr = self + .expressions + .append(Expression::AccessIndex { base, index }); + + (expr, { + let ty = program.module.global_variables[handle].ty; + + match program.module.types[ty].inner { + TypeInner::Struct { ref members, .. } => { + if let TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } = program.module.types[members[index as usize].ty].inner + { + false + } else { + true + } + } + _ => true, + } + }) + } + GlobalLookupKind::Constant(v) => { + let res = (self.expressions.append(Expression::Constant(v)), false); + self.emit_start(); + res + } + }; + + let var = VariableReference { + expr, + load, + mutable, + entry_arg, + }; + + self.lookup_global_var_exps.insert(name.into(), var); + } + pub fn emit_start(&mut self) { self.emitter.start(self.expressions) } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index e22fe2135..c127805b0 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1142,10 +1142,21 @@ impl Program { Ok(()) } - pub fn add_entry_point(&mut self, function: Handle) -> Result<(), ErrorKind> { + pub fn add_entry_point( + &mut self, + function: Handle, + mut global_init_body: Block, + mut expressions: Arena, + ) -> Result<(), ErrorKind> { let mut arguments = Vec::new(); - let mut expressions = Arena::new(); - let mut body = Vec::new(); + let mut body = Block::with_capacity( + // global init body + global_init_body.len() + + // prologue and epilogue + self.entry_args.len() * 2 + // Call, Emit for composing struct and return + + 3, + ); for arg in self.entry_args.iter() { if arg.storage != StorageQualifier::Input { @@ -1167,6 +1178,8 @@ impl Program { body.push(Statement::Store { pointer, value }); } + body.append(&mut global_init_body); + body.push(Statement::Call { function, arguments: Vec::new(), diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index dfea73d3b..7e5df0ea4 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -77,12 +77,25 @@ impl<'source, 'program> Parser<'source, 'program> { pub fn parse(&mut self) -> Result<()> { self.parse_version()?; + // Body and expression arena for global initialization + let mut body = Block::new(); + let mut expressions = Arena::new(); + let mut arguments = Vec::new(); + let mut locals = Arena::new(); + let mut ctx = Context::new( + self.program, + &mut body, + &mut expressions, + &mut locals, + &mut arguments, + ); + while self.lexer.peek().is_some() { - self.parse_external_declaration()?; + self.parse_external_declaration(&mut ctx, &mut body)?; } if let Some(handle) = self.program.entry_point { - self.program.add_entry_point(handle)?; + self.program.add_entry_point(handle, body, expressions)?; } Ok(()) @@ -419,21 +432,12 @@ impl<'source, 'program> Parser<'source, 'program> { Ok((self.program.solve_constant(&ctx, root, meta)?, meta)) } - fn parse_external_declaration(&mut self) -> Result<()> { - // TODO: Create body and expressions arena to be used in all entry - // points to handle this case - // ```glsl - // // This is valid and the body of main will contain the assignment - // float b; - // float a = b = 1; - // - // void main() {} - // ``` - let (mut e, mut l, mut a) = (Arena::new(), Arena::new(), Vec::new()); - let mut body = Block::new(); - let mut ctx = Context::new(self.program, &mut body, &mut e, &mut l, &mut a); - - if !self.parse_declaration(&mut ctx, &mut body, true)? { + fn parse_external_declaration( + &mut self, + global_ctx: &mut Context, + global_body: &mut Block, + ) -> Result<()> { + if !self.parse_declaration(global_ctx, global_body, true)? { let token = self.bump()?; match token.value { TokenValue::Semicolon if self.program.version == 460 => Ok(()), @@ -815,7 +819,13 @@ impl<'source, 'program> Parser<'source, 'program> { match token.value { TokenValue::Identifier(ty_name) => { if self.bump_if(TokenValue::LeftBrace).is_some() { - self.parse_block_declaration(&qualifiers, ty_name, token.meta) + self.parse_block_declaration( + ctx, + body, + &qualifiers, + ty_name, + token.meta, + ) } else { //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON @@ -905,6 +915,8 @@ impl<'source, 'program> Parser<'source, 'program> { fn parse_block_declaration( &mut self, + ctx: &mut Context, + body: &mut Block, qualifiers: &[(TypeQualifier, SourceMetadata)], ty_name: String, mut meta: SourceMetadata, @@ -960,32 +972,34 @@ impl<'source, 'program> Parser<'source, 'program> { }; meta = meta.union(&token.meta); - let global = self.program.add_global_var(VarDeclaration { - qualifiers, - ty, - name, - init: None, - meta, - })?; + let global = self.program.add_global_var( + ctx, + body, + VarDeclaration { + qualifiers, + ty, + name, + init: None, + meta, + }, + )?; for (i, k) in members .into_iter() .enumerate() .filter_map(|(i, m)| m.name.map(|s| (i as u32, s))) { - self.program.global_variables.push(( - k, - GlobalLookup { - kind: match global { - GlobalOrConstant::Global(handle) => { - GlobalLookupKind::BlockSelect(handle, i) - } - GlobalOrConstant::Constant(handle) => GlobalLookupKind::Constant(handle), - }, - entry_arg: None, - mutable: true, + let lookup = GlobalLookup { + kind: match global { + GlobalOrConstant::Global(handle) => GlobalLookupKind::BlockSelect(handle, i), + GlobalOrConstant::Constant(handle) => GlobalLookupKind::Constant(handle), }, - )); + entry_arg: None, + mutable: true, + }; + ctx.add_global(&k, lookup, self.program, body); + + self.program.global_variables.push((k, lookup)); } Ok(true) @@ -1958,7 +1972,7 @@ impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { match self.external { true => { - let global = program.add_global_var(decl)?; + let global = program.add_global_var(self.ctx, self.body, decl)?; let expr = match global { GlobalOrConstant::Global(handle) => Expression::GlobalVariable(handle), GlobalOrConstant::Constant(handle) => Expression::Constant(handle), diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index dd66b4a15..857c8c0d4 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -314,6 +314,8 @@ impl Program { pub fn add_global_var( &mut self, + ctx: &mut Context, + body: &mut Block, VarDeclaration { qualifiers, ty, @@ -446,14 +448,14 @@ impl Program { }); if let Some(name) = name { - self.global_variables.push(( - name, - GlobalLookup { - kind: GlobalLookupKind::Variable(handle), - entry_arg: Some(idx), - mutable: !input, - }, - )); + let lookup = GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: Some(idx), + mutable: !input, + }; + ctx.add_global(&name, lookup, self, body); + + self.global_variables.push((name, lookup)); } return Ok(GlobalOrConstant::Global(handle)); @@ -462,14 +464,14 @@ impl Program { ErrorKind::SemanticError(meta, "const values must have an initializer".into()) })?; if let Some(name) = name { - self.global_variables.push(( - name, - GlobalLookup { - kind: GlobalLookupKind::Constant(init), - entry_arg: None, - mutable: false, - }, - )); + let lookup = GlobalLookup { + kind: GlobalLookupKind::Constant(init), + entry_arg: None, + mutable: false, + }; + ctx.add_global(&name, lookup, self, body); + + self.global_variables.push((name, lookup)); } return Ok(GlobalOrConstant::Constant(init)); } @@ -498,14 +500,14 @@ impl Program { }); if let Some(name) = name { - self.global_variables.push(( - name, - GlobalLookup { - kind: GlobalLookupKind::Variable(handle), - entry_arg: None, - mutable: true, - }, - )); + let lookup = GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: None, + mutable: true, + }; + ctx.add_global(&name, lookup, self, body); + + self.global_variables.push((name, lookup)); } Ok(GlobalOrConstant::Global(handle)) diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index d62e395b1..950979fdd 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -26,6 +26,6 @@ fn main1() { fn main([[location(0)]] v_Uv: vec2) -> FragmentOutput { v_Uv1 = v_Uv; main1(); - let _e3: vec4 = o_Target; - return FragmentOutput(_e3); + let _e9: vec4 = o_Target; + return FragmentOutput(_e9); } diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index d31cab2f3..c495a7232 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -51,7 +51,7 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Normal1 = Vertex_Normal; Vertex_Uv1 = Vertex_Uv; main1(); - let _e7: vec2 = v_Uv; - let _e9: vec4 = gl_Position; - return VertexOutput(_e7, _e9); + let _e21: vec2 = v_Uv; + let _e23: vec4 = gl_Position; + return VertexOutput(_e21, _e23); } diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 50319b857..7c94a048f 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -51,9 +51,9 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Normal1 = Vertex_Normal; Vertex_Uv1 = Vertex_Uv; main1(); - let _e7: vec3 = v_Position; - let _e9: vec3 = v_Normal; - let _e11: vec2 = v_Uv; - let _e13: vec4 = gl_Position; - return VertexOutput(_e7, _e9, _e11, _e13); + let _e23: vec3 = v_Position; + let _e25: vec3 = v_Normal; + let _e27: vec2 = v_Uv; + let _e29: vec4 = gl_Position; + return VertexOutput(_e23, _e25, _e27, _e29); } diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index 66ba8cc4b..84a5e065d 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -36,7 +36,7 @@ fn main([[location(0)]] position: vec2, [[location(1)]] color: vec4) - position1 = position; color1 = color; main1(); - let _e5: vec4 = frag_color; - let _e7: vec4 = gl_Position; - return VertexOutput(_e5, _e7); + let _e15: vec4 = frag_color; + let _e17: vec4 = gl_Position; + return VertexOutput(_e15, _e17); } diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index f323e3075..ef3344386 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -849,6 +849,6 @@ fn main([[location(0)]] v_WorldPosition: vec3, [[location(1)]] v_WorldNorma v_WorldTangent1 = v_WorldTangent; gl_FrontFacing = param; main1(); - let _e11: vec4 = o_Target; - return FragmentOutput(_e11); + let _e72: vec4 = o_Target; + return FragmentOutput(_e72); } diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 3acb74420..5eb6dc897 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -60,10 +60,10 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Uv1 = Vertex_Uv; Vertex_Tangent1 = Vertex_Tangent; main1(); - let _e9: vec3 = v_WorldPosition; - let _e11: vec3 = v_WorldNormal; - let _e13: vec2 = v_Uv; - let _e15: vec4 = v_WorldTangent; - let _e17: vec4 = gl_Position; - return VertexOutput(_e9, _e11, _e13, _e15, _e17); + let _e29: vec3 = v_WorldPosition; + let _e31: vec3 = v_WorldNormal; + let _e33: vec2 = v_Uv; + let _e35: vec4 = v_WorldTangent; + let _e37: vec4 = gl_Position; + return VertexOutput(_e29, _e31, _e33, _e35, _e37); } diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index d7d0e7173..bf0e64fb4 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -40,6 +40,6 @@ fn main1() { [[stage(fragment)]] fn main() -> FragmentOutput { main1(); - let _e1: vec4 = o_color; - return FragmentOutput(_e1); + let _e3: vec4 = o_color; + return FragmentOutput(_e3); } diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index f4afbc77c..3c9ec4535 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -15,6 +15,6 @@ fn main1() { fn main([[location(0)]] a_pos: vec2) -> VertexOutput { a_pos1 = a_pos; main1(); - let _e3: vec4 = gl_Position; - return VertexOutput(_e3); + let _e5: vec4 = gl_Position; + return VertexOutput(_e5); } diff --git a/tests/out/wgsl/multiple_entry_points-glsl.wgsl b/tests/out/wgsl/multiple_entry_points-glsl.wgsl index ee890b8be..2c10716a5 100644 --- a/tests/out/wgsl/multiple_entry_points-glsl.wgsl +++ b/tests/out/wgsl/multiple_entry_points-glsl.wgsl @@ -34,15 +34,15 @@ fn comp_main1() { [[stage(vertex)]] fn vert_main() -> VertexOutput { vert_main1(); - let _e1: vec4 = gl_Position; - return VertexOutput(_e1); + let _e3: vec4 = gl_Position; + return VertexOutput(_e3); } [[stage(fragment)]] fn frag_main() -> FragmentOutput { frag_main1(); - let _e1: vec4 = o_color; - return FragmentOutput(_e1); + let _e3: vec4 = o_color; + return FragmentOutput(_e3); } [[stage(compute), workgroup_size(1, 1, 1)]] diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 6a52a6c23..18ee145e7 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -14,6 +14,6 @@ fn main1() { fn main([[location(0)]] v_uv: vec2) -> FragmentOutput { v_uv1 = v_uv; main1(); - let _e3: vec4 = o_color; - return FragmentOutput(_e3); + let _e7: vec4 = o_color; + return FragmentOutput(_e7); } diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index 9e659a3b3..c010a38cb 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -21,7 +21,7 @@ fn main([[location(0)]] a_pos: vec2, [[location(1)]] a_uv: vec2) -> Ve a_pos1 = a_pos; a_uv1 = a_uv; main1(); - let _e5: vec2 = v_uv; - let _e7: vec4 = gl_Position; - return VertexOutput(_e5, _e7); + let _e14: vec2 = v_uv; + let _e16: vec4 = gl_Position; + return VertexOutput(_e14, _e16); } From 6f210043691902a8d5aa4d06e2d6178d4cbb4935 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 22 Jul 2021 15:31:05 -0400 Subject: [PATCH 1184/2212] Allow mixing on a scalar selector --- src/back/spv/block.rs | 45 ++++++- src/valid/expression.rs | 42 +++++- tests/in/operators.wgsl | 31 +++-- tests/out/glsl/operators.main.Compute.glsl | 21 +-- tests/out/hlsl/operators.hlsl | 26 ++-- tests/out/msl/operators.msl | 26 ++-- tests/out/spv/operators.spvasm | 150 +++++++++++---------- tests/out/wgsl/operators.wgsl | 24 ++-- 8 files changed, 237 insertions(+), 128 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index aabd132d3..0b7ecc526 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -488,10 +488,8 @@ impl<'w> BlockContext<'w> { } let arg0_id = self.cached[arg]; - let arg_scalar_kind = self.fun_info[arg] - .ty - .inner_with(&self.ir_module.types) - .scalar_kind(); + let arg_ty = self.fun_info[arg].ty.inner_with(&self.ir_module.types); + let arg_scalar_kind = arg_ty.scalar_kind(); let arg1_id = match arg1 { Some(handle) => self.cached[handle], None => 0, @@ -592,7 +590,44 @@ impl<'w> BlockContext<'w> { other => unimplemented!("Unexpected sign({:?})", other), }), Mf::Fma => MathOp::Ext(spirv::GLOp::Fma), - Mf::Mix => MathOp::Ext(spirv::GLOp::FMix), + Mf::Mix => { + let selector = arg2.unwrap(); + let selector_ty = + self.fun_info[selector].ty.inner_with(&self.ir_module.types); + match (arg_ty, selector_ty) { + // if the selector is a scalar, we need to splat it + ( + &crate::TypeInner::Vector { size, .. }, + &crate::TypeInner::Scalar { kind, width }, + ) => { + let selector_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind, + width, + pointer_class: None, + }))?; + self.temp_list.clear(); + self.temp_list.resize(size as usize, arg2_id); + + let selector_id = self.gen_id(); + block.body.push(Instruction::composite_construct( + selector_type_id, + selector_id, + &self.temp_list, + )); + + MathOp::Custom(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + spirv::GLOp::FMix, + result_type_id, + id, + &[arg0_id, arg1_id, selector_id], + )) + } + _ => MathOp::Ext(spirv::GLOp::FMix), + } + } Mf::Step => MathOp::Ext(spirv::GLOp::Step), Mf::SmoothStep => MathOp::Ext(spirv::GLOp::SmoothStep), Mf::Sqrt => MathOp::Ext(spirv::GLOp::Sqrt), diff --git a/src/valid/expression.rs b/src/valid/expression.rs index d9937b894..b63321afd 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1077,7 +1077,7 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } } - Mf::FaceForward | Mf::Fma | Mf::Mix | Mf::SmoothStep => { + Mf::FaceForward | Mf::Fma | Mf::SmoothStep => { let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty) { (Some(ty1), Some(ty2)) => (ty1, ty2), _ => return Err(ExpressionError::WrongArgumentCount(fun)), @@ -1106,6 +1106,46 @@ impl super::Validator { )); } } + Mf::Mix => { + let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty) { + (Some(ty1), Some(ty2)) => (ty1, ty2), + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + let arg_width = match *arg_ty { + Ti::Scalar { + kind: Sk::Float, + width, + } + | Ti::Vector { + kind: Sk::Float, + width, + .. + } => width, + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + }; + if arg1_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + // the last argument can always be a scalar + match *arg2_ty { + Ti::Scalar { + kind: Sk::Float, + width, + } if width == arg_width => {} + _ if arg2_ty == arg_ty => {} + _ => { + return Err(ExpressionError::InvalidArgumentType( + fun, + 2, + arg2.unwrap(), + )); + } + } + } Mf::Inverse | Mf::Determinant => { if arg1_ty.is_some() | arg2_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 9bbf9ba67..270e0a4fe 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -1,3 +1,20 @@ +//TODO: support splatting constructors for globals? +let v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); +let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); +let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); + +fn builtins() -> vec4 { + // select() + let condition = true; + let s1 = select(0, 1, condition); + let s2 = select(v_f32_zero, v_f32_one, condition); + // mix() + let m1 = mix(v_f32_zero, v_f32_one, v_f32_half); + let m2 = mix(v_f32_zero, v_f32_one, 0.1); + // done + return vec4(vec4(s1)) + s2 + m1 + m2; +} + fn splat() -> vec4 { let a = (1.0 + vec2(2.0) - 3.0) / 4.0; let b = vec4(5) % 2; @@ -9,17 +26,9 @@ fn unary() -> i32 { if (!true) { return a; } else { return ~a; }; } -fn selection() -> vec4 { - let vector1 = vec4(1.0); - let vector2 = vec4(1.0); - let condition = true; - let a = select(0, 1, condition); - return select(vector1, vector2, condition); -} - [[stage(compute), workgroup_size(1)]] fn main() { - let a = splat(); - let b = unary(); - let c = selection(); + let a = builtins(); + let b = splat(); + let c = unary(); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 8b55a50e3..10f9f4965 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -6,6 +6,14 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +vec4 builtins() { + int s1_ = (true ? 1 : 0); + vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); + vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); + vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); + return (((vec4(ivec4(s1_)) + s2_) + m1_) + m2_); +} + vec4 splat() { vec2 a = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); ivec4 b = (ivec4(5) % ivec4(2)); @@ -20,17 +28,10 @@ int unary() { } } -vec4 selection() { - vec4 vector1_ = vec4(1.0); - vec4 vector2_ = vec4(1.0); - int a = (true ? 1 : 0); - return (true ? vector2_ : vector1_); -} - void main() { - vec4 _expr0 = splat(); - int _expr1 = unary(); - vec4 _expr2 = selection(); + vec4 _expr3 = builtins(); + vec4 _expr4 = splat(); + int _expr5 = unary(); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 8bd764da7..172eda682 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -1,3 +1,15 @@ +static const float4 v_f32_one = float4(1.0, 1.0, 1.0, 1.0); +static const float4 v_f32_zero = float4(0.0, 0.0, 0.0, 0.0); +static const float4 v_f32_half = float4(0.5, 0.5, 0.5, 0.5); + +float4 builtins() +{ + int s1_ = (true ? 1 : 0); + float4 s2_ = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0)); + float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); + float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.1); + return (((float4(int4(s1_.xxxx)) + s2_) + m1_) + m2_); +} float4 splat() { @@ -15,19 +27,11 @@ int unary() } } -float4 selection() -{ - float4 vector1_ = float4(1.0.xxxx); - float4 vector2_ = float4(1.0.xxxx); - int a = (true ? 1 : 0); - return (true ? vector2_ : vector1_); -} - [numthreads(1, 1, 1)] void main() { - const float4 _e0 = splat(); - const int _e1 = unary(); - const float4 _e2 = selection(); + const float4 _e3 = builtins(); + const float4 _e4 = splat(); + const int _e5 = unary(); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index a7e691d5a..d794df1f9 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -2,6 +2,18 @@ #include #include +constant metal::float4 v_f32_one = {1.0, 1.0, 1.0, 1.0}; +constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0}; +constant metal::float4 v_f32_half = {0.5, 0.5, 0.5, 0.5}; + +metal::float4 builtins( +) { + int s1_ = true ? 1 : 0; + metal::float4 s2_ = true ? v_f32_one : v_f32_zero; + metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half); + metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.1); + return ((static_cast(metal::int4(s1_)) + s2_) + m1_) + m2_; +} metal::float4 splat( ) { @@ -19,18 +31,10 @@ int unary( } } -metal::float4 selection( -) { - metal::float4 vector1_ = metal::float4(1.0); - metal::float4 vector2_ = metal::float4(1.0); - int a = true ? 1 : 0; - return true ? vector2_ : vector1_; -} - kernel void main1( ) { - metal::float4 _e0 = splat(); - int _e1 = unary(); - metal::float4 _e2 = selection(); + metal::float4 _e3 = builtins(); + metal::float4 _e4 = splat(); + int _e5 = unary(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 48bef9319..2e56ba9ba 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,84 +1,96 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 61 +; Bound: 73 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %55 "main" -OpExecutionMode %55 LocalSize 1 1 1 +OpEntryPoint GLCompute %67 "main" +OpExecutionMode %67 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 -%5 = OpConstant %4 2.0 -%6 = OpConstant %4 3.0 -%7 = OpConstant %4 4.0 -%9 = OpTypeInt 32 1 -%8 = OpConstant %9 5 -%10 = OpConstant %9 2 -%11 = OpConstant %9 1 -%13 = OpTypeBool -%12 = OpConstantTrue %13 -%14 = OpConstant %9 0 -%15 = OpTypeVector %4 4 -%18 = OpTypeFunction %15 -%20 = OpTypeVector %4 2 -%28 = OpTypeVector %9 4 -%37 = OpTypeFunction %9 -%44 = OpConstantNull %9 -%52 = OpTypeVector %13 4 -%56 = OpTypeFunction %2 -%17 = OpFunction %15 None %18 -%16 = OpLabel -OpBranch %19 -%19 = OpLabel -%21 = OpCompositeConstruct %20 %5 %5 -%22 = OpCompositeConstruct %20 %3 %3 -%23 = OpFAdd %20 %22 %21 -%24 = OpCompositeConstruct %20 %6 %6 -%25 = OpFSub %20 %23 %24 -%26 = OpCompositeConstruct %20 %7 %7 -%27 = OpFDiv %20 %25 %26 -%29 = OpCompositeConstruct %28 %8 %8 %8 %8 -%30 = OpCompositeConstruct %28 %10 %10 %10 %10 -%31 = OpSMod %28 %29 %30 -%32 = OpVectorShuffle %15 %27 %27 0 1 0 1 -%33 = OpConvertSToF %15 %31 -%34 = OpFAdd %15 %32 %33 -OpReturnValue %34 +%5 = OpConstant %4 0.0 +%6 = OpConstant %4 0.5 +%8 = OpTypeBool +%7 = OpConstantTrue %8 +%10 = OpTypeInt 32 1 +%9 = OpConstant %10 0 +%11 = OpConstant %10 1 +%12 = OpConstant %4 0.1 +%13 = OpConstant %4 2.0 +%14 = OpConstant %4 3.0 +%15 = OpConstant %4 4.0 +%16 = OpConstant %10 5 +%17 = OpConstant %10 2 +%18 = OpTypeVector %4 4 +%19 = OpConstantComposite %18 %3 %3 %3 %3 +%20 = OpConstantComposite %18 %5 %5 %5 %5 +%21 = OpConstantComposite %18 %6 %6 %6 %6 +%24 = OpTypeFunction %18 +%28 = OpTypeVector %8 4 +%33 = OpTypeVector %10 4 +%42 = OpTypeVector %4 2 +%58 = OpTypeFunction %10 +%65 = OpConstantNull %10 +%68 = OpTypeFunction %2 +%23 = OpFunction %18 None %24 +%22 = OpLabel +OpBranch %25 +%25 = OpLabel +%26 = OpSelect %10 %7 %11 %9 +%29 = OpCompositeConstruct %28 %7 %7 %7 %7 +%27 = OpSelect %18 %29 %19 %20 +%30 = OpExtInst %18 %1 FMix %20 %19 %21 +%32 = OpCompositeConstruct %18 %12 %12 %12 %12 +%31 = OpExtInst %18 %1 FMix %20 %19 %32 +%34 = OpCompositeConstruct %33 %26 %26 %26 %26 +%35 = OpConvertSToF %18 %34 +%36 = OpFAdd %18 %35 %27 +%37 = OpFAdd %18 %36 %30 +%38 = OpFAdd %18 %37 %31 +OpReturnValue %38 OpFunctionEnd -%36 = OpFunction %9 None %37 -%35 = OpLabel -OpBranch %38 -%38 = OpLabel -%39 = OpLogicalNot %13 %12 -OpSelectionMerge %40 None -OpBranchConditional %39 %41 %42 +%40 = OpFunction %18 None %24 +%39 = OpLabel +OpBranch %41 %41 = OpLabel +%43 = OpCompositeConstruct %42 %13 %13 +%44 = OpCompositeConstruct %42 %3 %3 +%45 = OpFAdd %42 %44 %43 +%46 = OpCompositeConstruct %42 %14 %14 +%47 = OpFSub %42 %45 %46 +%48 = OpCompositeConstruct %42 %15 %15 +%49 = OpFDiv %42 %47 %48 +%50 = OpCompositeConstruct %33 %16 %16 %16 %16 +%51 = OpCompositeConstruct %33 %17 %17 %17 %17 +%52 = OpSMod %33 %50 %51 +%53 = OpVectorShuffle %18 %49 %49 0 1 0 1 +%54 = OpConvertSToF %18 %52 +%55 = OpFAdd %18 %53 %54 +OpReturnValue %55 +OpFunctionEnd +%57 = OpFunction %10 None %58 +%56 = OpLabel +OpBranch %59 +%59 = OpLabel +%60 = OpLogicalNot %8 %7 +OpSelectionMerge %61 None +OpBranchConditional %60 %62 %63 +%62 = OpLabel OpReturnValue %11 -%42 = OpLabel -%43 = OpNot %9 %11 -OpReturnValue %43 -%40 = OpLabel -OpReturnValue %44 +%63 = OpLabel +%64 = OpNot %10 %11 +OpReturnValue %64 +%61 = OpLabel +OpReturnValue %65 OpFunctionEnd -%46 = OpFunction %15 None %18 -%45 = OpLabel -OpBranch %47 -%47 = OpLabel -%48 = OpCompositeConstruct %15 %3 %3 %3 %3 -%49 = OpCompositeConstruct %15 %3 %3 %3 %3 -%50 = OpSelect %9 %12 %11 %14 -%53 = OpCompositeConstruct %52 %12 %12 %12 %12 -%51 = OpSelect %15 %53 %49 %48 -OpReturnValue %51 -OpFunctionEnd -%55 = OpFunction %2 None %56 -%54 = OpLabel -OpBranch %57 -%57 = OpLabel -%58 = OpFunctionCall %15 %17 -%59 = OpFunctionCall %9 %36 -%60 = OpFunctionCall %15 %46 +%67 = OpFunction %2 None %68 +%66 = OpLabel +OpBranch %69 +%69 = OpLabel +%70 = OpFunctionCall %18 %23 +%71 = OpFunctionCall %18 %40 +%72 = OpFunctionCall %10 %57 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index bbd3c9086..967742898 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -1,3 +1,14 @@ +let v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); +let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); +let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); +fn builtins() -> vec4 { + let s1_: i32 = select(0, 1, true); + let s2_: vec4 = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); + let m1_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); + let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); + return (((vec4(vec4(s1_)) + s2_) + m1_) + m2_); +} + fn splat() -> vec4 { let a: vec2 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); let b: vec4 = (vec4(5) % vec4(2)); @@ -12,17 +23,10 @@ fn unary() -> i32 { } } -fn selection() -> vec4 { - let vector1_: vec4 = vec4(1.0); - let vector2_: vec4 = vec4(1.0); - let a: i32 = select(0, 1, true); - return select(vector1_, vector2_, true); -} - [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { - let _e0: vec4 = splat(); - let _e1: i32 = unary(); - let _e2: vec4 = selection(); + let _e3: vec4 = builtins(); + let _e4: vec4 = splat(); + let _e5: i32 = unary(); return; } From ec0d97d9611e33cd229a1102ff11335daebbae4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 2 Aug 2021 23:57:24 +0100 Subject: [PATCH 1185/2212] [glsl-in] Respect user defined interpolation --- src/front/glsl/variables.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 857c8c0d4..13182ca53 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -419,12 +419,12 @@ impl Program { if let Some(location) = location { let input = storage == StorageQualifier::Input; - let interpolation = self.module.types[ty].inner.scalar_kind().map(|kind| { - if let ScalarKind::Float = kind { - Interpolation::Perspective - } else { - Interpolation::Flat - } + let interpolation = interpolation.or_else(|| { + let kind = self.module.types[ty].inner.scalar_kind()?; + Some(match kind { + ScalarKind::Float => Interpolation::Perspective, + _ => Interpolation::Flat, + }) }); let handle = self.module.global_variables.append(GlobalVariable { From 5ec129bbf0bc57d05f8f6393685b3d2ac1d5653e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 2 Aug 2021 23:57:41 +0100 Subject: [PATCH 1186/2212] [glsl-in] Lower the for loop init expression --- src/front/glsl/parser.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 7e5df0ea4..b644de61a 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1763,14 +1763,12 @@ impl<'source, 'program> Parser<'source, 'program> { if self.peek_type_name() || self.peek_type_qualifier() { self.parse_declaration(ctx, body, false)?; } else { - self.parse_expression(ctx, body)?; + let expr = self.parse_expression(ctx, body)?; + ctx.lower(self.program, expr, false, body)?; self.expect(TokenValue::Semicolon)?; } } - ctx.emit_flush(body); - ctx.emit_start(); - let (mut block, mut continuing) = (Block::new(), Block::new()); if self.bump_if(TokenValue::Semicolon).is_none() { From de6399a9c703305f2cdc5ac4a092b188b59f42c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 2 Aug 2021 23:58:20 +0100 Subject: [PATCH 1187/2212] [glsl-in] Follow spec when choosing default layout --- src/front/glsl/parser.rs | 25 ++++++++++++++++++------- tests/out/wgsl/246-collatz-comp.wgsl | 2 +- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b644de61a..d9bf53f74 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -921,13 +921,24 @@ impl<'source, 'program> Parser<'source, 'program> { ty_name: String, mut meta: SourceMetadata, ) -> Result { - let layout = qualifiers - .iter() - .find_map(|&(ref qualifier, _)| match *qualifier { - TypeQualifier::Layout(layout) => Some(layout), - _ => None, - }) - .unwrap_or(StructLayout::Std140); + let mut storage = None; + let mut layout = None; + + for &(ref qualifier, _) in qualifiers { + match *qualifier { + TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { + storage = Some(c) + } + TypeQualifier::Layout(l) => layout = Some(l), + _ => continue, + } + } + + let layout = match (layout, storage) { + (Some(layout), _) => layout, + (None, Some(StorageClass::Storage { .. })) => StructLayout::Std430, + _ => StructLayout::Std140, + }; let mut members = Vec::new(); let span = self.parse_struct_declaration_list(&mut members, layout)?; diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 3ae887639..21fde3265 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -1,6 +1,6 @@ [[block]] struct PrimeIndices { - indices: [[stride(16)]] array; + indices: [[stride(4)]] array; }; [[group(0), binding(0)]] From 151a36352e70fe61d167df0f57ff47ea0e9fd3d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 3 Aug 2021 00:02:21 +0100 Subject: [PATCH 1188/2212] [glsl-in] Be more conservative with vector resizes --- src/front/glsl/ast.rs | 16 +++++++++++ src/front/glsl/functions.rs | 55 ++++++++++++------------------------- 2 files changed, 33 insertions(+), 38 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 2d9ba7bf4..08e2e6522 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -925,6 +925,22 @@ impl<'function> Context<'function> { Ok(()) } + + pub fn vector_resize( + &mut self, + size: VectorSize, + vector: Handle, + body: &mut Block, + ) -> Handle { + self.add_expression( + Expression::Swizzle { + size, + vector, + pattern: crate::SwizzleComponent::XYZW, + }, + body, + ) + } } impl<'function> Index> for Context<'function> { diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index c127805b0..e9cb3dd58 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,12 +1,11 @@ +use super::{ast::*, error::ErrorKind, SourceMetadata}; use crate::{ proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, ImageClass, ImageDimension, ImageQuery, LocalVariable, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind, - ScalarValue, Statement, StructMember, SwizzleComponent, Type, TypeInner, VectorSize, + ScalarValue, Statement, StructMember, Type, TypeInner, VectorSize, }; -use super::{ast::*, error::ErrorKind, SourceMetadata}; - /// Helper struct for texture calls with the separate components from the vector argument /// /// Obtained by calling [`coordinate_components`](Program::coordinate_components) @@ -99,14 +98,11 @@ impl Program { body, ), TypeInner::Vector { size, kind, width } => { - let expr = ctx.add_expression( - Expression::Swizzle { - size, - vector: args[0].0, - pattern: SwizzleComponent::XYZW, - }, - body, - ); + let mut expr = args[0].0; + + if vector_size.map_or(true, |s| s != size) { + expr = ctx.vector_resize(size, expr, body); + } ctx.add_expression( Expression::As { @@ -137,11 +133,11 @@ impl Program { let column = match *self.resolve_type(ctx, args[0].0, args[0].1)? { TypeInner::Scalar { .. } => ctx .add_expression(Expression::Splat { size: rows, value }, body), - TypeInner::Matrix { .. } => { + TypeInner::Matrix { rows: ori_rows, .. } => { let mut components = Vec::new(); for n in 0..columns as u32 { - let vector = ctx.add_expression( + let mut vector = ctx.add_expression( Expression::AccessIndex { base: value, index: n, @@ -149,16 +145,11 @@ impl Program { body, ); - let c = ctx.add_expression( - Expression::Swizzle { - size: rows, - vector, - pattern: SwizzleComponent::XYZW, - }, - body, - ); + if ori_rows != rows { + vector = ctx.vector_resize(rows, vector, body); + } - components.push(c) + components.push(vector) } let h = ctx.add_expression( @@ -398,14 +389,7 @@ impl Program { _ => VectorSize::Tri, }; right = ctx.add_expression(Expression::Splat { size, value: right }, body); - ctx.add_expression( - Expression::Swizzle { - size, - vector: base, - pattern: SwizzleComponent::XYZW, - }, - body, - ) + ctx.vector_resize(size, base, body) }; let coords = ctx.add_expression( Expression::Binary { @@ -1282,14 +1266,9 @@ impl Program { }; let coordinate = match (image_size, coord_size) { - (Some(size), Some(coord_s)) if size != coord_s => ctx.add_expression( - Expression::Swizzle { - size, - vector: coord, - pattern: SwizzleComponent::XYZW, - }, - body, - ), + (Some(size), Some(coord_s)) if size != coord_s => { + ctx.vector_resize(size, coord, body) + } (None, Some(_)) => ctx.add_expression( Expression::AccessIndex { base: coord, From a1395ddb999abdb141ba4c96603d5b253cc2b99a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 3 Aug 2021 00:17:07 +0100 Subject: [PATCH 1189/2212] [glsl-in] Fix matrix constructor with a scalar Glsl defines that if a matrix constructor is called with only a scalar it's result will be the matrix where the scalar is used if the row and column are equal and everywhere else a zero --- src/front/glsl/functions.rs | 81 +++++++++++++++++------ tests/out/wgsl/280-matrix-cast-vert.wgsl | 6 +- tests/out/wgsl/long-form-matrix-vert.wgsl | 31 +++++---- 3 files changed, 77 insertions(+), 41 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index e9cb3dd58..b6c7189be 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -5,6 +5,7 @@ use crate::{ ImageQuery, LocalVariable, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind, ScalarValue, Statement, StructMember, Type, TypeInner, VectorSize, }; +use std::iter; /// Helper struct for texture calls with the separate components from the vector argument /// @@ -130,9 +131,52 @@ impl Program { ScalarKind::Float, width, )?; - let column = match *self.resolve_type(ctx, args[0].0, args[0].1)? { - TypeInner::Scalar { .. } => ctx - .add_expression(Expression::Splat { size: rows, value }, body), + match *self.resolve_type(ctx, value, meta)? { + TypeInner::Scalar { .. } => { + // If a matrix is constructed with a single scalar value, then that + // value is used to initialize all the values along the diagonal of + // the matrix; the rest are given zeros. + let mut components = Vec::with_capacity(columns as usize); + let vector_ty = self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, + }, + }); + let zero_constant = + self.module.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width, + value: ScalarValue::Float(0.0), + }, + }); + let zero = ctx + .add_expression(Expression::Constant(zero_constant), body); + + for i in 0..columns as u32 { + components.push( + ctx.add_expression( + Expression::Compose { + ty: vector_ty, + components: (0..rows as u32) + .into_iter() + .map(|r| match r == i { + true => value, + false => zero, + }) + .collect(), + }, + body, + ), + ) + } + + ctx.add_expression(Expression::Compose { ty, components }, body) + } TypeInner::Matrix { rows: ori_rows, .. } => { let mut components = Vec::new(); @@ -152,26 +196,21 @@ impl Program { components.push(vector) } - let h = ctx.add_expression( - Expression::Compose { ty, components }, - body, - ); - - return Ok(Some(h)); + ctx.add_expression(Expression::Compose { ty, components }, body) } - _ => value, - }; + _ => { + let columns = + iter::repeat(value).take(columns as usize).collect(); - let columns = - std::iter::repeat(column).take(columns as usize).collect(); - - ctx.add_expression( - Expression::Compose { - ty, - components: columns, - }, - body, - ) + ctx.add_expression( + Expression::Compose { + ty, + components: columns, + }, + body, + ) + } + } } TypeInner::Struct { .. } => ctx.add_expression( Expression::Compose { diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl index 3416dfc75..c5676cd28 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl @@ -1,9 +1,7 @@ fn main1() { - var a: mat4x4; + var a: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let _e2: vec4 = vec4(f32(1)); - a = mat4x4(_e2, _e2, _e2, _e2); - return; + let _e1: f32 = f32(1); } [[stage(vertex)]] diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index d2c3aa18d..dee8738ff 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -1,5 +1,5 @@ fn main1() { - var splat: mat2x2; + var splat: mat2x2 = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); var normal: mat2x2 = mat2x2(vec2(1.0, 1.0), vec2(2.0, 2.0)); var a: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); var b: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); @@ -7,21 +7,20 @@ fn main1() { var d: mat3x3 = mat3x3(vec3(2.0, 2.0, 1.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); var e: mat4x4 = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); - let _e2: vec2 = vec2(f32(1)); - splat = mat2x2(_e2, _e2); - let _e7: vec2 = vec2(f32(1)); - let _e10: vec2 = vec2(f32(2)); - let _e36: vec2 = vec2(f32(2), f32(3)); - let _e51: vec3 = vec3(f32(1)); - let _e54: vec3 = vec3(f32(1)); - let _e71: vec2 = vec2(f32(2)); - let _e75: vec3 = vec3(f32(1)); - let _e78: vec3 = vec3(f32(1)); - let _e95: vec2 = vec2(f32(2)); - let _e98: vec4 = vec4(f32(1)); - let _e101: vec2 = vec2(f32(2)); - let _e104: vec4 = vec4(f32(1)); - let _e107: vec4 = vec4(f32(1)); + let _e1: f32 = f32(1); + let _e9: vec2 = vec2(f32(1)); + let _e12: vec2 = vec2(f32(2)); + let _e38: vec2 = vec2(f32(2), f32(3)); + let _e53: vec3 = vec3(f32(1)); + let _e56: vec3 = vec3(f32(1)); + let _e73: vec2 = vec2(f32(2)); + let _e77: vec3 = vec3(f32(1)); + let _e80: vec3 = vec3(f32(1)); + let _e97: vec2 = vec2(f32(2)); + let _e100: vec4 = vec4(f32(1)); + let _e103: vec2 = vec2(f32(2)); + let _e106: vec4 = vec4(f32(1)); + let _e109: vec4 = vec4(f32(1)); } [[stage(vertex)]] From 2ff7dcb417f47fe80ab8ba87539239fb7ff72fd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 3 Aug 2021 00:19:31 +0100 Subject: [PATCH 1190/2212] [glsl-in] Fix mix ordering for boolean selector The mix builtin is defined with the inverse order for it's arguments compared to the IR when the selector is a boolean vector. --- src/front/glsl/functions.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index b6c7189be..c5309d6b4 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -730,10 +730,19 @@ impl Program { .resolve_type(ctx, selector, selector_meta)? .scalar_kind() { + // When the selector is a boolean vector the result is + // calculated per component, for each component of the + // selector if it's false the respective component from the + // first argument is selected, if it's true the respective + // component from the second argument is selected + // + // Note(jcapucho): yes, it's inverted in comparison with the + // IR and SPIR-V and yes I spent a full debugging a shader + // because of this weird behavior Some(ScalarKind::Bool) => Expression::Select { condition: selector, - accept: arg, - reject: arg1, + accept: arg1, + reject: arg, }, _ => Expression::Math { fun: MathFunction::Mix, From b2e51c97c88645319025beb2e6c96db9024fd99f Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 5 Aug 2021 01:58:54 +0300 Subject: [PATCH 1191/2212] [glsl-out] Handle wgsl vector version of select --- src/back/glsl/mod.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index e4a2e86e8..679a2e3e1 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2115,12 +2115,30 @@ impl<'a, W: Write> Writer<'a, W> { accept, reject, } => { - write!(self.out, "(")?; - self.write_expr(condition, ctx)?; - write!(self.out, " ? ")?; - self.write_expr(accept, ctx)?; - write!(self.out, " : ")?; - self.write_expr(reject, ctx)?; + let cond_ty = ctx.info[condition].ty.inner_with(&self.module.types); + let vec_select = if let TypeInner::Vector { .. } = *cond_ty { + true + } else { + false + }; + + // TODO: Boolean mix on desktop required GL_EXT_shader_integer_mix + if vec_select { + write!(self.out, "mix(")?; + self.write_expr(accept, ctx)?; + write!(self.out, ", ")?; + self.write_expr(reject, ctx)?; + write!(self.out, ", ")?; + self.write_expr(condition, ctx)?; + } else { + write!(self.out, "(")?; + self.write_expr(condition, ctx)?; + write!(self.out, " ? ")?; + self.write_expr(accept, ctx)?; + write!(self.out, " : ")?; + self.write_expr(reject, ctx)?; + } + write!(self.out, ")")? } // `Derivative` is a function call to a glsl provided function From 4080bfe502bdb5f91785363c7dc36a997fc4e78a Mon Sep 17 00:00:00 2001 From: Gordon-F Date: Thu, 5 Aug 2021 01:59:25 +0300 Subject: [PATCH 1192/2212] Add vec select to operators snapshot --- tests/in/operators.wgsl | 1 + tests/out/glsl/operators.main.Compute.glsl | 1 + tests/out/hlsl/operators.hlsl | 1 + tests/out/msl/operators.msl | 1 + tests/out/spv/operators.spvasm | 145 +++++++++++---------- tests/out/wgsl/operators.wgsl | 1 + 6 files changed, 79 insertions(+), 71 deletions(-) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 270e0a4fe..1ab3550d2 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -8,6 +8,7 @@ fn builtins() -> vec4 { let condition = true; let s1 = select(0, 1, condition); let s2 = select(v_f32_zero, v_f32_one, condition); + let s3 = select(v_f32_one, v_f32_zero, vec4(false, false, false, false)); // mix() let m1 = mix(v_f32_zero, v_f32_one, v_f32_half); let m2 = mix(v_f32_zero, v_f32_one, 0.1); diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 10f9f4965..332e991c8 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -9,6 +9,7 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; vec4 builtins() { int s1_ = (true ? 1 : 0); vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); + vec4 s3_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), bvec4(false, false, false, false)); vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); return (((vec4(ivec4(s1_)) + s2_) + m1_) + m2_); diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 172eda682..1ff8d4229 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -6,6 +6,7 @@ float4 builtins() { int s1_ = (true ? 1 : 0); float4 s2_ = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0)); + float4 s3_ = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.1); return (((float4(int4(s1_.xxxx)) + s2_) + m1_) + m2_); diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index d794df1f9..a193bc096 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -10,6 +10,7 @@ metal::float4 builtins( ) { int s1_ = true ? 1 : 0; metal::float4 s2_ = true ? v_f32_one : v_f32_zero; + metal::float4 s3_ = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false)); metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half); metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.1); return ((static_cast(metal::int4(s1_)) + s2_) + m1_) + m2_; diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 2e56ba9ba..7e904842a 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 73 +; Bound: 76 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %67 "main" -OpExecutionMode %67 LocalSize 1 1 1 +OpEntryPoint GLCompute %70 "main" +OpExecutionMode %70 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -17,80 +17,83 @@ OpExecutionMode %67 LocalSize 1 1 1 %10 = OpTypeInt 32 1 %9 = OpConstant %10 0 %11 = OpConstant %10 1 -%12 = OpConstant %4 0.1 -%13 = OpConstant %4 2.0 -%14 = OpConstant %4 3.0 -%15 = OpConstant %4 4.0 -%16 = OpConstant %10 5 -%17 = OpConstant %10 2 -%18 = OpTypeVector %4 4 -%19 = OpConstantComposite %18 %3 %3 %3 %3 -%20 = OpConstantComposite %18 %5 %5 %5 %5 -%21 = OpConstantComposite %18 %6 %6 %6 %6 -%24 = OpTypeFunction %18 -%28 = OpTypeVector %8 4 -%33 = OpTypeVector %10 4 -%42 = OpTypeVector %4 2 -%58 = OpTypeFunction %10 -%65 = OpConstantNull %10 -%68 = OpTypeFunction %2 -%23 = OpFunction %18 None %24 -%22 = OpLabel -OpBranch %25 -%25 = OpLabel -%26 = OpSelect %10 %7 %11 %9 -%29 = OpCompositeConstruct %28 %7 %7 %7 %7 -%27 = OpSelect %18 %29 %19 %20 -%30 = OpExtInst %18 %1 FMix %20 %19 %21 -%32 = OpCompositeConstruct %18 %12 %12 %12 %12 -%31 = OpExtInst %18 %1 FMix %20 %19 %32 -%34 = OpCompositeConstruct %33 %26 %26 %26 %26 -%35 = OpConvertSToF %18 %34 -%36 = OpFAdd %18 %35 %27 -%37 = OpFAdd %18 %36 %30 -%38 = OpFAdd %18 %37 %31 -OpReturnValue %38 +%12 = OpConstantFalse %8 +%13 = OpConstant %4 0.1 +%14 = OpConstant %4 2.0 +%15 = OpConstant %4 3.0 +%16 = OpConstant %4 4.0 +%17 = OpConstant %10 5 +%18 = OpConstant %10 2 +%19 = OpTypeVector %4 4 +%20 = OpTypeVector %8 4 +%21 = OpConstantComposite %19 %3 %3 %3 %3 +%22 = OpConstantComposite %19 %5 %5 %5 %5 +%23 = OpConstantComposite %19 %6 %6 %6 %6 +%26 = OpTypeFunction %19 +%36 = OpTypeVector %10 4 +%45 = OpTypeVector %4 2 +%61 = OpTypeFunction %10 +%68 = OpConstantNull %10 +%71 = OpTypeFunction %2 +%25 = OpFunction %19 None %26 +%24 = OpLabel +OpBranch %27 +%27 = OpLabel +%28 = OpSelect %10 %7 %11 %9 +%30 = OpCompositeConstruct %20 %7 %7 %7 %7 +%29 = OpSelect %19 %30 %21 %22 +%31 = OpCompositeConstruct %20 %12 %12 %12 %12 +%32 = OpSelect %19 %31 %22 %21 +%33 = OpExtInst %19 %1 FMix %22 %21 %23 +%35 = OpCompositeConstruct %19 %13 %13 %13 %13 +%34 = OpExtInst %19 %1 FMix %22 %21 %35 +%37 = OpCompositeConstruct %36 %28 %28 %28 %28 +%38 = OpConvertSToF %19 %37 +%39 = OpFAdd %19 %38 %29 +%40 = OpFAdd %19 %39 %33 +%41 = OpFAdd %19 %40 %34 +OpReturnValue %41 OpFunctionEnd -%40 = OpFunction %18 None %24 -%39 = OpLabel -OpBranch %41 -%41 = OpLabel -%43 = OpCompositeConstruct %42 %13 %13 -%44 = OpCompositeConstruct %42 %3 %3 -%45 = OpFAdd %42 %44 %43 -%46 = OpCompositeConstruct %42 %14 %14 -%47 = OpFSub %42 %45 %46 -%48 = OpCompositeConstruct %42 %15 %15 -%49 = OpFDiv %42 %47 %48 -%50 = OpCompositeConstruct %33 %16 %16 %16 %16 -%51 = OpCompositeConstruct %33 %17 %17 %17 %17 -%52 = OpSMod %33 %50 %51 -%53 = OpVectorShuffle %18 %49 %49 0 1 0 1 -%54 = OpConvertSToF %18 %52 -%55 = OpFAdd %18 %53 %54 -OpReturnValue %55 +%43 = OpFunction %19 None %26 +%42 = OpLabel +OpBranch %44 +%44 = OpLabel +%46 = OpCompositeConstruct %45 %14 %14 +%47 = OpCompositeConstruct %45 %3 %3 +%48 = OpFAdd %45 %47 %46 +%49 = OpCompositeConstruct %45 %15 %15 +%50 = OpFSub %45 %48 %49 +%51 = OpCompositeConstruct %45 %16 %16 +%52 = OpFDiv %45 %50 %51 +%53 = OpCompositeConstruct %36 %17 %17 %17 %17 +%54 = OpCompositeConstruct %36 %18 %18 %18 %18 +%55 = OpSMod %36 %53 %54 +%56 = OpVectorShuffle %19 %52 %52 0 1 0 1 +%57 = OpConvertSToF %19 %55 +%58 = OpFAdd %19 %56 %57 +OpReturnValue %58 OpFunctionEnd -%57 = OpFunction %10 None %58 -%56 = OpLabel -OpBranch %59 +%60 = OpFunction %10 None %61 %59 = OpLabel -%60 = OpLogicalNot %8 %7 -OpSelectionMerge %61 None -OpBranchConditional %60 %62 %63 +OpBranch %62 %62 = OpLabel +%63 = OpLogicalNot %8 %7 +OpSelectionMerge %64 None +OpBranchConditional %63 %65 %66 +%65 = OpLabel OpReturnValue %11 -%63 = OpLabel -%64 = OpNot %10 %11 -OpReturnValue %64 -%61 = OpLabel -OpReturnValue %65 -OpFunctionEnd -%67 = OpFunction %2 None %68 %66 = OpLabel -OpBranch %69 +%67 = OpNot %10 %11 +OpReturnValue %67 +%64 = OpLabel +OpReturnValue %68 +OpFunctionEnd +%70 = OpFunction %2 None %71 %69 = OpLabel -%70 = OpFunctionCall %18 %23 -%71 = OpFunctionCall %18 %40 -%72 = OpFunctionCall %10 %57 +OpBranch %72 +%72 = OpLabel +%73 = OpFunctionCall %19 %25 +%74 = OpFunctionCall %19 %43 +%75 = OpFunctionCall %10 %60 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 967742898..f83e8c28a 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -4,6 +4,7 @@ let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); fn builtins() -> vec4 { let s1_: i32 = select(0, 1, true); let s2_: vec4 = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); + let s3_: vec4 = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); let m1_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); return (((vec4(vec4(s1_)) + s2_) + m1_) + m2_); From 300039e24703bc823cc932985947dfda66616e1e Mon Sep 17 00:00:00 2001 From: Zicklag Date: Wed, 4 Aug 2021 16:29:50 -0500 Subject: [PATCH 1193/2212] Fix Invalid Type Attribute Error Message The message previously made reference to the now-removed `access` attribute. --- src/front/wgsl/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7440e2ca2..54a4df564 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -163,7 +163,7 @@ impl<'a> Error<'a> { ExpectedToken::PrimaryExpression => "expression".to_string(), ExpectedToken::AttributeSeparator => "attribute separator (',') or an end of the attribute list (']]')".to_string(), ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(), - ExpectedToken::TypeAttribute => "type attribute ('access' or 'stride') or an end of the attribute list (']]')".to_string(), + ExpectedToken::TypeAttribute => "type attribute ('stride') or an end of the attribute list (']]')".to_string(), ExpectedToken::Statement => "statement".to_string(), ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), From 7c3cc904a0c69377bfaa1564971c95bf30058624 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 5 Aug 2021 09:56:23 -0400 Subject: [PATCH 1194/2212] [spv-in] fix storage buffer access decorations --- src/front/spv/convert.rs | 3 +- src/front/spv/mod.rs | 47 +++------ tests/out/analysis/shadow.info.ron | 142 ++++++++++++++-------------- tests/out/ir/shadow.ron | 2 +- tests/out/spv/pointer-access.spvasm | 2 - 5 files changed, 86 insertions(+), 110 deletions(-) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index aa2de029d..d4fe91d57 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -155,7 +155,8 @@ pub(super) fn map_storage_class(word: spirv::Word) -> Result Ec::Global(crate::StorageClass::Private), Some(Sc::UniformConstant) => Ec::Global(crate::StorageClass::Handle), Some(Sc::StorageBuffer) => Ec::Global(crate::StorageClass::Storage { - access: crate::StorageAccess::default(), + //Note: this is restricted by decorations later + access: crate::StorageAccess::all(), }), // we expect the `Storage` case to be filtered out before calling this function. Some(Sc::Uniform) => Ec::Global(crate::StorageClass::Uniform), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 44126857c..24feb8860 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3422,31 +3422,14 @@ impl> Parser { let mut dec = self.future_decor.remove(&id).unwrap_or_default(); let original_ty = self.lookup_type.lookup(type_id)?.handle; - let (effective_ty, is_storage) = match module.types[original_ty].inner { - crate::TypeInner::Pointer { base, class } => ( - base, - match class { - crate::StorageClass::Storage { .. } => true, - _ => false, - }, - ), - crate::TypeInner::Image { - class: crate::ImageClass::Storage { .. }, - .. - } => (original_ty, true), - _ => (original_ty, false), + let effective_ty = match module.types[original_ty].inner { + crate::TypeInner::Pointer { base, class: _ } => base, + _ => original_ty, + }; + let ext_class = match self.lookup_storage_buffer_types.get(&effective_ty) { + Some(&access) => ExtendedClass::Global(crate::StorageClass::Storage { access }), + None => map_storage_class(storage_class)?, }; - let (ext_class, type_storage_access) = - match self.lookup_storage_buffer_types.get(&effective_ty) { - Some(&access) => ( - ExtendedClass::Global(crate::StorageClass::Storage { access }), - access, - ), - None => ( - map_storage_class(storage_class)?, - crate::StorageAccess::all(), - ), - }; // Fix empty name for gl_PerVertex struct generated by glslang if let crate::TypeInner::Pointer { .. } = module.types[original_ty].inner { @@ -3460,21 +3443,15 @@ impl> Parser { } let (inner, var) = match ext_class { - ExtendedClass::Global(class) => { - // TODO actually apply decorators - let _storage_access = if is_storage { - let mut access = type_storage_access; + ExtendedClass::Global(mut class) => { + if let crate::StorageClass::Storage { ref mut access } = class { if dec.flags.contains(DecorationFlags::NON_READABLE) { - access &= !crate::StorageAccess::LOAD; + *access &= !crate::StorageAccess::LOAD; } if dec.flags.contains(DecorationFlags::NON_WRITABLE) { - access &= !crate::StorageAccess::STORE; + *access &= !crate::StorageAccess::STORE; } - access - } else { - crate::StorageAccess::empty() - }; - + } let var = crate::GlobalVariable { binding: dec.resource_binding(), name: dec.name, diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 0adb46f2b..142cdb078 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -110,7 +110,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: None, requirements: ( bits: 0, ), @@ -121,7 +121,7 @@ base: 21, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), @@ -1176,7 +1176,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: None, requirements: ( bits: 0, ), @@ -1187,7 +1187,7 @@ base: 21, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), @@ -1884,7 +1884,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: None, requirements: ( bits: 0, ), @@ -1895,7 +1895,7 @@ base: 20, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), @@ -1913,7 +1913,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1924,14 +1924,14 @@ base: 19, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1942,14 +1942,14 @@ base: 18, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -1971,7 +1971,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2019,7 +2019,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: None, requirements: ( bits: 0, ), @@ -2030,7 +2030,7 @@ base: 20, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), @@ -2048,7 +2048,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2059,14 +2059,14 @@ base: 19, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2077,14 +2077,14 @@ base: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2097,14 +2097,14 @@ width: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2118,7 +2118,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: None, requirements: ( bits: 0, ), @@ -2129,7 +2129,7 @@ base: 20, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), @@ -2147,7 +2147,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2158,14 +2158,14 @@ base: 19, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2176,14 +2176,14 @@ base: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2196,14 +2196,14 @@ width: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2217,7 +2217,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: None, requirements: ( bits: 0, ), @@ -2228,7 +2228,7 @@ base: 20, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), @@ -2246,7 +2246,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2257,14 +2257,14 @@ base: 19, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2275,14 +2275,14 @@ base: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2295,14 +2295,14 @@ width: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2316,7 +2316,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2428,7 +2428,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2439,7 +2439,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2492,7 +2492,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: None, requirements: ( bits: 0, ), @@ -2503,7 +2503,7 @@ base: 20, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), @@ -2521,7 +2521,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2532,14 +2532,14 @@ base: 19, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2550,14 +2550,14 @@ base: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2570,14 +2570,14 @@ width: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2591,7 +2591,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: None, requirements: ( bits: 0, ), @@ -2602,7 +2602,7 @@ base: 20, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), @@ -2620,7 +2620,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2631,14 +2631,14 @@ base: 19, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2649,14 +2649,14 @@ base: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2669,14 +2669,14 @@ width: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2690,7 +2690,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: None, requirements: ( bits: 0, ), @@ -2701,7 +2701,7 @@ base: 20, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), @@ -2719,7 +2719,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2730,14 +2730,14 @@ base: 19, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2748,14 +2748,14 @@ base: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2768,14 +2768,14 @@ width: 4, class: Storage( access: ( - bits: 3, + bits: 1, ), ), )), ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2789,7 +2789,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), @@ -2800,7 +2800,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(48), requirements: ( bits: 0, ), diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 4d5f19d5e..91bbd48db 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -805,7 +805,7 @@ name: Some("s_lights"), class: Storage( access: ( - bits: 3, + bits: 1, ), ), binding: Some(( diff --git a/tests/out/spv/pointer-access.spvasm b/tests/out/spv/pointer-access.spvasm index 6fc3bcc9a..ef4b7bbce 100644 --- a/tests/out/spv/pointer-access.spvasm +++ b/tests/out/spv/pointer-access.spvasm @@ -12,8 +12,6 @@ OpDecorate %12 ArrayStride 4 OpDecorate %14 ArrayStride 4 OpDecorate %15 Block OpMemberDecorate %15 0 Offset 0 -OpDecorate %17 NonReadable -OpDecorate %17 NonWritable OpDecorate %17 DescriptorSet 0 OpDecorate %17 Binding 0 %2 = OpTypeVoid From 0bd78ef85e122e950f450f9567876b33e1b1db0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 5 Aug 2021 18:33:12 +0100 Subject: [PATCH 1195/2212] [spv-out] Use NotEqual for boolean casts --- src/back/spv/block.rs | 53 +++++++++++++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 0b7ecc526..721fa52c4 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -715,27 +715,46 @@ impl<'w> BlockContext<'w> { } }; - let op = match (src_kind, kind, convert) { - (_, _, None) => spirv::Op::Bitcast, - (Sk::Float, Sk::Uint, Some(_)) => spirv::Op::ConvertFToU, - (Sk::Float, Sk::Sint, Some(_)) => spirv::Op::ConvertFToS, - (Sk::Float, Sk::Float, Some(dst_width)) if src_width != dst_width => { - spirv::Op::FConvert + let id = self.gen_id(); + + let instruction = match (src_kind, kind, convert) { + (_, Sk::Bool, Some(_)) if src_kind != Sk::Bool => { + let (op, value) = match src_kind { + Sk::Sint => (spirv::Op::INotEqual, crate::ScalarValue::Sint(0)), + Sk::Uint => (spirv::Op::INotEqual, crate::ScalarValue::Uint(0)), + Sk::Float => { + (spirv::Op::FUnordNotEqual, crate::ScalarValue::Float(0.0)) + } + Sk::Bool => unreachable!(), + }; + let zero_id = self.writer.get_constant_scalar(value, 4)?; + + Instruction::binary(op, result_type_id, id, expr_id, zero_id) } - (Sk::Sint, Sk::Float, Some(_)) => spirv::Op::ConvertSToF, - (Sk::Sint, Sk::Sint, Some(dst_width)) if src_width != dst_width => { - spirv::Op::SConvert + _ => { + let op = match (src_kind, kind, convert) { + (_, _, None) => spirv::Op::Bitcast, + (Sk::Float, Sk::Uint, Some(_)) => spirv::Op::ConvertFToU, + (Sk::Float, Sk::Sint, Some(_)) => spirv::Op::ConvertFToS, + (Sk::Float, Sk::Float, Some(dst_width)) if src_width != dst_width => { + spirv::Op::FConvert + } + (Sk::Sint, Sk::Float, Some(_)) => spirv::Op::ConvertSToF, + (Sk::Sint, Sk::Sint, Some(dst_width)) if src_width != dst_width => { + spirv::Op::SConvert + } + (Sk::Uint, Sk::Float, Some(_)) => spirv::Op::ConvertUToF, + (Sk::Uint, Sk::Uint, Some(dst_width)) if src_width != dst_width => { + spirv::Op::UConvert + } + // We assume it's either an identity cast, or int-uint. + _ => spirv::Op::Bitcast, + }; + + Instruction::unary(op, result_type_id, id, expr_id) } - (Sk::Uint, Sk::Float, Some(_)) => spirv::Op::ConvertUToF, - (Sk::Uint, Sk::Uint, Some(dst_width)) if src_width != dst_width => { - spirv::Op::UConvert - } - // We assume it's either an identity cast, or int-uint. - _ => spirv::Op::Bitcast, }; - let id = self.gen_id(); - let instruction = Instruction::unary(op, result_type_id, id, expr_id); block.body.push(instruction); id } From a8a316da15120f8b2ff0743392f8a99bab8bc0b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 6 Aug 2021 16:39:04 +0100 Subject: [PATCH 1196/2212] [glsl-in] API revamp The new api allows for reuse while keeping some allocations and to please the borrow checker in future work, it also splits the parser into logical modules to make it easier to work on. --- cli/src/main.rs | 64 +- src/front/glsl/ast.rs | 935 +------- src/front/glsl/context.rs | 787 +++++++ src/front/glsl/functions.rs | 95 +- src/front/glsl/mod.rs | 106 +- src/front/glsl/parser.rs | 1951 +---------------- src/front/glsl/parser/declarations.rs | 581 +++++ src/front/glsl/parser/expressions.rs | 486 ++++ src/front/glsl/parser/functions.rs | 483 ++++ src/front/glsl/parser/types.rs | 268 +++ src/front/glsl/parser_tests.rs | 246 ++- src/front/glsl/types.rs | 114 +- src/front/glsl/variables.rs | 13 +- src/front/mod.rs | 6 +- tests/in/glsl/931-constant-emitting.vert | 2 + tests/in/glsl/constant-array-size.vert | 2 + .../out/wgsl/931-constant-emitting-vert.wgsl | 9 + tests/out/wgsl/constant-array-size-vert.wgsl | 9 + tests/snapshots.rs | 26 +- 19 files changed, 3206 insertions(+), 2977 deletions(-) create mode 100644 src/front/glsl/context.rs create mode 100644 src/front/glsl/parser/declarations.rs create mode 100644 src/front/glsl/parser/expressions.rs create mode 100644 src/front/glsl/parser/functions.rs create mode 100644 src/front/glsl/parser/types.rs diff --git a/cli/src/main.rs b/cli/src/main.rs index 7bf013489..0339becfb 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -221,50 +221,28 @@ fn run() -> Result<(), Box> { } } } - "vert" => { + ext @ "vert" | ext @ "frag" | ext @ "comp" => { let input = fs::read_to_string(input_path)?; - naga::front::glsl::parse_str( - &input, - &naga::front::glsl::Options { - stage: naga::ShaderStage::Vertex, - defines: Default::default(), - }, - ) - .unwrap_or_else(|err| { - let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); - emit_glsl_parser_error(err, filename.unwrap_or("glsl"), &input); - std::process::exit(1); - }) - } - "frag" => { - let input = fs::read_to_string(input_path)?; - naga::front::glsl::parse_str( - &input, - &naga::front::glsl::Options { - stage: naga::ShaderStage::Fragment, - defines: Default::default(), - }, - ) - .unwrap_or_else(|err| { - let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); - emit_glsl_parser_error(err, filename.unwrap_or("glsl"), &input); - std::process::exit(1); - }) - } - "comp" => { - let input = fs::read_to_string(input_path)?; - naga::front::glsl::parse_str( - &input, - &naga::front::glsl::Options { - stage: naga::ShaderStage::Compute, - defines: Default::default(), - }, - ) - .unwrap_or_else(|err| { - let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); - emit_glsl_parser_error(err, filename.unwrap_or("glsl"), &input); - std::process::exit(1); - }) + let mut parser = naga::front::glsl::Parser::default(); + + parser + .parse( + &naga::front::glsl::Options { + stage: match ext { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + _ => unreachable!(), + }, + defines: Default::default(), + }, + &input, + ) + .unwrap_or_else(|err| { + let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); + emit_glsl_parser_error(err, filename.unwrap_or("glsl"), &input); + std::process::exit(1); + }) } _ => return Err(CliError("Unknown input file extension").into()), }; diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 08e2e6522..751fb4d67 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,17 +1,8 @@ -use super::{ - super::{Emitter, Typifier}, - constants::ConstantSolver, - error::ErrorKind, - SourceMetadata, -}; +use super::SourceMetadata; use crate::{ - proc::ResolveContext, Arena, BinaryOperator, Binding, Block, Constant, Expression, FastHashMap, - Function, FunctionArgument, GlobalVariable, Handle, Interpolation, LocalVariable, Module, - RelationalFunction, ResourceBinding, Sampling, ScalarKind, ScalarValue, ShaderStage, Statement, - StorageAccess, StorageClass, Type, TypeInner, UnaryOperator, VectorSize, + BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, Interpolation, + ResourceBinding, Sampling, StorageAccess, StorageClass, Type, UnaryOperator, }; -use core::convert::TryFrom; -use std::ops::Index; #[derive(Debug, Clone, Copy)] pub enum GlobalLookupKind { @@ -55,921 +46,6 @@ pub struct EntryArg { pub storage: StorageQualifier, } -#[derive(Debug)] -pub struct Program { - pub version: u16, - pub profile: Profile, - pub stage: ShaderStage, - - pub workgroup_size: [u32; 3], - pub early_fragment_tests: bool, - - pub lookup_function: FastHashMap>, - pub lookup_type: FastHashMap>, - - pub global_variables: Vec<(String, GlobalLookup)>, - - pub entry_args: Vec, - pub entry_point: Option>, - - pub module: Module, -} - -impl Program { - pub fn new(stage: ShaderStage) -> Program { - Program { - version: 0, - profile: Profile::Core, - stage, - - workgroup_size: [if stage == ShaderStage::Compute { 1 } else { 0 }; 3], - early_fragment_tests: false, - - lookup_function: FastHashMap::default(), - lookup_type: FastHashMap::default(), - global_variables: Vec::new(), - - entry_args: Vec::new(), - entry_point: None, - - module: Module::default(), - } - } - - pub fn typifier_grow( - &self, - context: &mut Context, - handle: Handle, - meta: SourceMetadata, - ) -> Result<(), ErrorKind> { - let resolve_ctx = ResolveContext { - constants: &self.module.constants, - types: &self.module.types, - global_vars: &self.module.global_variables, - local_vars: context.locals, - functions: &self.module.functions, - arguments: context.arguments, - }; - - context - .typifier - .grow(handle, context.expressions, &resolve_ctx) - .map_err(|error| { - ErrorKind::SemanticError(meta, format!("Can't resolve type: {:?}", error).into()) - }) - } - - pub fn resolve_type<'b>( - &'b self, - context: &'b mut Context, - handle: Handle, - meta: SourceMetadata, - ) -> Result<&'b TypeInner, ErrorKind> { - self.typifier_grow(context, handle, meta)?; - Ok(context.typifier.get(handle, &self.module.types)) - } - - /// Invalidates the cached type resolution for `handle` forcing a recomputation - pub fn invalidate_expression<'b>( - &'b self, - context: &'b mut Context, - handle: Handle, - meta: SourceMetadata, - ) -> Result<(), ErrorKind> { - let resolve_ctx = ResolveContext { - constants: &self.module.constants, - types: &self.module.types, - global_vars: &self.module.global_variables, - local_vars: context.locals, - functions: &self.module.functions, - arguments: context.arguments, - }; - - context - .typifier - .invalidate(handle, context.expressions, &resolve_ctx) - .map_err(|error| { - ErrorKind::SemanticError(meta, format!("Can't resolve type: {:?}", error).into()) - }) - } - - pub fn solve_constant( - &mut self, - ctx: &Context, - root: Handle, - meta: SourceMetadata, - ) -> Result, ErrorKind> { - let mut solver = ConstantSolver { - types: &self.module.types, - expressions: ctx.expressions, - constants: &mut self.module.constants, - }; - - solver.solve(root).map_err(|e| (meta, e).into()) - } -} - -#[derive(Debug, PartialEq)] -pub enum Profile { - Core, -} - -#[derive(Debug)] -pub struct Context<'function> { - expressions: &'function mut Arena, - pub locals: &'function mut Arena, - pub arguments: &'function mut Vec, - pub parameters_info: Vec, - - //TODO: Find less allocation heavy representation - pub scopes: Vec>, - pub lookup_global_var_exps: FastHashMap, - pub samplers: FastHashMap, Handle>, - pub typifier: Typifier, - - pub hir_exprs: Arena, - emitter: Emitter, -} - -impl<'function> Context<'function> { - pub fn new( - program: &mut Program, - body: &mut Block, - expressions: &'function mut Arena, - locals: &'function mut Arena, - arguments: &'function mut Vec, - ) -> Self { - let mut this = Context { - expressions, - locals, - arguments, - parameters_info: Vec::new(), - - scopes: vec![FastHashMap::default()], - lookup_global_var_exps: FastHashMap::with_capacity_and_hasher( - program.global_variables.len(), - Default::default(), - ), - typifier: Typifier::new(), - samplers: FastHashMap::default(), - - hir_exprs: Arena::default(), - emitter: Emitter::default(), - }; - - this.emit_start(); - - for &(ref name, lookup) in program.global_variables.iter() { - this.add_global(name, lookup, program, body) - } - - this - } - - pub fn add_global( - &mut self, - name: &str, - GlobalLookup { - kind, - entry_arg, - mutable, - }: GlobalLookup, - program: &Program, - body: &mut Block, - ) { - self.emit_flush(body); - let (expr, load) = match kind { - GlobalLookupKind::Variable(v) => { - let res = ( - self.expressions.append(Expression::GlobalVariable(v)), - program.module.global_variables[v].class != StorageClass::Handle, - ); - self.emit_start(); - - res - } - GlobalLookupKind::BlockSelect(handle, index) => { - let base = self.expressions.append(Expression::GlobalVariable(handle)); - self.emit_start(); - let expr = self - .expressions - .append(Expression::AccessIndex { base, index }); - - (expr, { - let ty = program.module.global_variables[handle].ty; - - match program.module.types[ty].inner { - TypeInner::Struct { ref members, .. } => { - if let TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } = program.module.types[members[index as usize].ty].inner - { - false - } else { - true - } - } - _ => true, - } - }) - } - GlobalLookupKind::Constant(v) => { - let res = (self.expressions.append(Expression::Constant(v)), false); - self.emit_start(); - res - } - }; - - let var = VariableReference { - expr, - load, - mutable, - entry_arg, - }; - - self.lookup_global_var_exps.insert(name.into(), var); - } - - pub fn emit_start(&mut self) { - self.emitter.start(self.expressions) - } - - pub fn emit_flush(&mut self, body: &mut Block) { - body.extend(self.emitter.finish(self.expressions)) - } - - pub fn add_expression(&mut self, expr: Expression, body: &mut Block) -> Handle { - if expr.needs_pre_emit() { - self.emit_flush(body); - let handle = self.expressions.append(expr); - self.emit_start(); - handle - } else { - self.expressions.append(expr) - } - } - - pub fn lookup_local_var(&self, name: &str) -> Option { - for scope in self.scopes.iter().rev() { - if let Some(var) = scope.get(name) { - return Some(var.clone()); - } - } - None - } - - pub fn lookup_global_var(&mut self, name: &str) -> Option { - self.lookup_global_var_exps.get(name).cloned() - } - - #[cfg(feature = "glsl-validate")] - pub fn lookup_local_var_current_scope(&self, name: &str) -> Option { - if let Some(current) = self.scopes.last() { - current.get(name).cloned() - } else { - None - } - } - - /// Add variable to current scope - pub fn add_local_var(&mut self, name: String, expr: Handle, mutable: bool) { - if let Some(current) = self.scopes.last_mut() { - (*current).insert( - name, - VariableReference { - expr, - load: true, - mutable, - entry_arg: None, - }, - ); - } - } - - /// Add function argument to current scope - pub fn add_function_arg( - &mut self, - program: &mut Program, - parameters: &mut Vec>, - body: &mut Block, - name: Option, - ty: Handle, - qualifier: ParameterQualifier, - ) { - let index = self.arguments.len(); - let mut arg = FunctionArgument { - name: name.clone(), - ty, - binding: None, - }; - parameters.push(ty); - - let opaque = match program.module.types[ty].inner { - TypeInner::Image { .. } | TypeInner::Sampler { .. } => true, - _ => false, - }; - - if qualifier.is_lhs() { - arg.ty = program.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Pointer { - base: arg.ty, - class: StorageClass::Function, - }, - }) - } - - self.arguments.push(arg); - - self.parameters_info.push(ParameterInfo { - qualifier, - depth: false, - }); - - if let Some(name) = name { - let expr = self.add_expression(Expression::FunctionArgument(index as u32), body); - let mutable = qualifier != ParameterQualifier::Const && !opaque; - let load = qualifier.is_lhs(); - - if mutable && !load { - let handle = self.locals.append(LocalVariable { - name: Some(name.clone()), - ty, - init: None, - }); - let local_expr = self.add_expression(Expression::LocalVariable(handle), body); - - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { - pointer: local_expr, - value: expr, - }); - - if let Some(current) = self.scopes.last_mut() { - (*current).insert( - name, - VariableReference { - expr: local_expr, - load: true, - mutable, - entry_arg: None, - }, - ); - } - } else if let Some(current) = self.scopes.last_mut() { - (*current).insert( - name, - VariableReference { - expr, - load, - mutable, - entry_arg: None, - }, - ); - } - } - } - - /// Add new empty scope - pub fn push_scope(&mut self) { - self.scopes.push(FastHashMap::default()); - } - - pub fn remove_current_scope(&mut self) { - self.scopes.pop(); - } - - pub fn lower_expect( - &mut self, - program: &mut Program, - expr: Handle, - lhs: bool, - body: &mut Block, - ) -> Result<(Handle, SourceMetadata), ErrorKind> { - let (maybe_expr, meta) = self.lower(program, expr, lhs, body)?; - - let expr = match maybe_expr { - Some(e) => e, - None => { - return Err(ErrorKind::SemanticError( - meta, - "Expression returns void".into(), - )) - } - }; - - Ok((expr, meta)) - } - - pub fn lower( - &mut self, - program: &mut Program, - expr: Handle, - lhs: bool, - body: &mut Block, - ) -> Result<(Option>, SourceMetadata), ErrorKind> { - let HirExpr { kind, meta } = self.hir_exprs[expr].clone(); - - let handle = match kind { - HirExprKind::Access { base, index } => { - let base = self.lower_expect(program, base, true, body)?.0; - let (index, index_meta) = self.lower_expect(program, index, false, body)?; - - let pointer = program - .solve_constant(self, index, index_meta) - .ok() - .and_then(|constant| { - Some(self.add_expression( - Expression::AccessIndex { - base, - index: match program.module.constants[constant].inner { - crate::ConstantInner::Scalar { - value: ScalarValue::Uint(i), - .. - } => u32::try_from(i).ok()?, - crate::ConstantInner::Scalar { - value: ScalarValue::Sint(i), - .. - } => u32::try_from(i).ok()?, - _ => return None, - }, - }, - body, - )) - }) - .unwrap_or_else(|| { - self.add_expression(Expression::Access { base, index }, body) - }); - - if !lhs { - let resolved = program.resolve_type(self, pointer, meta)?; - if resolved.pointer_class().is_some() { - return Ok(( - Some(self.add_expression(Expression::Load { pointer }, body)), - meta, - )); - } - } - - pointer - } - HirExprKind::Select { base, field } => { - let base = self.lower_expect(program, base, lhs, body)?.0; - - program.field_selection(self, lhs, body, base, &field, meta)? - } - HirExprKind::Constant(constant) if !lhs => { - self.add_expression(Expression::Constant(constant), body) - } - HirExprKind::Binary { left, op, right } if !lhs => { - let (mut left, left_meta) = self.lower_expect(program, left, false, body)?; - let (mut right, right_meta) = self.lower_expect(program, right, false, body)?; - - match op { - BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self - .implicit_conversion( - program, - &mut right, - right_meta, - ScalarKind::Uint, - 4, - )?, - _ => self.binary_implicit_conversion( - program, &mut left, left_meta, &mut right, right_meta, - )?, - } - - program.typifier_grow(self, left, left_meta)?; - program.typifier_grow(self, right, right_meta)?; - - let left_inner = self.typifier.get(left, &program.module.types); - let right_inner = self.typifier.get(right, &program.module.types); - - match (left_inner, right_inner) { - (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) - | (&TypeInner::Matrix { .. }, &TypeInner::Matrix { .. }) => match op { - BinaryOperator::Equal | BinaryOperator::NotEqual => { - let equals = op == BinaryOperator::Equal; - - let (op, fun) = match equals { - true => (BinaryOperator::Equal, RelationalFunction::All), - false => (BinaryOperator::NotEqual, RelationalFunction::Any), - }; - - let argument = - self.expressions - .append(Expression::Binary { op, left, right }); - - self.add_expression(Expression::Relational { fun, argument }, body) - } - _ => self.add_expression(Expression::Binary { left, op, right }, body), - }, - (&TypeInner::Vector { size, .. }, &TypeInner::Scalar { .. }) => match op { - BinaryOperator::Add - | BinaryOperator::Subtract - | BinaryOperator::Divide - | BinaryOperator::ShiftLeft - | BinaryOperator::ShiftRight => { - let scalar_vector = - self.add_expression(Expression::Splat { size, value: right }, body); - - self.add_expression( - Expression::Binary { - op, - left, - right: scalar_vector, - }, - body, - ) - } - _ => self.add_expression(Expression::Binary { left, op, right }, body), - }, - (&TypeInner::Scalar { .. }, &TypeInner::Vector { size, .. }) => match op { - BinaryOperator::Add | BinaryOperator::Subtract | BinaryOperator::Divide => { - let scalar_vector = - self.add_expression(Expression::Splat { size, value: left }, body); - - self.add_expression( - Expression::Binary { - op, - left: scalar_vector, - right, - }, - body, - ) - } - _ => self.add_expression(Expression::Binary { left, op, right }, body), - }, - _ => self.add_expression(Expression::Binary { left, op, right }, body), - } - } - HirExprKind::Unary { op, expr } if !lhs => { - let expr = self.lower_expect(program, expr, false, body)?.0; - - self.add_expression(Expression::Unary { op, expr }, body) - } - HirExprKind::Variable(var) => { - if lhs { - if !var.mutable { - return Err(ErrorKind::SemanticError( - meta, - "Variable cannot be used in LHS position".into(), - )); - } - - var.expr - } else if var.load { - self.add_expression(Expression::Load { pointer: var.expr }, body) - } else { - var.expr - } - } - HirExprKind::Call(call) if !lhs => { - let maybe_expr = program - .function_or_constructor_call(self, body, call.kind, &call.args, meta)?; - return Ok((maybe_expr, meta)); - } - HirExprKind::Conditional { - condition, - accept, - reject, - } if !lhs => { - let condition = self.lower_expect(program, condition, false, body)?.0; - let (mut accept, accept_meta) = self.lower_expect(program, accept, false, body)?; - let (mut reject, reject_meta) = self.lower_expect(program, reject, false, body)?; - - self.binary_implicit_conversion( - program, - &mut accept, - accept_meta, - &mut reject, - reject_meta, - )?; - - self.add_expression( - Expression::Select { - condition, - accept, - reject, - }, - body, - ) - } - HirExprKind::Assign { tgt, value } if !lhs => { - let (pointer, ptr_meta) = self.lower_expect(program, tgt, true, body)?; - let (mut value, value_meta) = self.lower_expect(program, value, false, body)?; - - let scalar_components = self.expr_scalar_components(program, pointer, ptr_meta)?; - - if let Some((kind, width)) = scalar_components { - self.implicit_conversion(program, &mut value, value_meta, kind, width)?; - } - - if let Expression::Swizzle { - size, - mut vector, - pattern, - } = self.expressions[pointer] - { - // Stores to swizzled values are not directly supported, - // lower them as series of per-component stores. - let size = match size { - VectorSize::Bi => 2, - VectorSize::Tri => 3, - VectorSize::Quad => 4, - }; - - if let Expression::Load { pointer } = self.expressions[vector] { - vector = pointer; - } - - #[allow(clippy::needless_range_loop)] - for index in 0..size { - let dst = self.add_expression( - Expression::AccessIndex { - base: vector, - index: pattern[index].index(), - }, - body, - ); - let src = self.add_expression( - Expression::AccessIndex { - base: value, - index: index as u32, - }, - body, - ); - - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { - pointer: dst, - value: src, - }); - } - } else { - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { pointer, value }); - } - - value - } - HirExprKind::IncDec { - increment, - postfix, - expr, - } => { - let op = match increment { - true => BinaryOperator::Add, - false => BinaryOperator::Subtract, - }; - - let pointer = self.lower_expect(program, expr, true, body)?.0; - let left = self.add_expression(Expression::Load { pointer }, body); - - let uint = if let Some(kind) = program.resolve_type(self, left, meta)?.scalar_kind() - { - match kind { - ScalarKind::Sint => false, - ScalarKind::Uint => true, - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Increment/decrement operations must operate in integers".into(), - )) - } - } - } else { - return Err(ErrorKind::SemanticError( - meta, - "Increment/decrement operations must operate in integers".into(), - )); - }; - - let one = program.module.constants.append(Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: match uint { - true => crate::ScalarValue::Uint(1), - false => crate::ScalarValue::Sint(1), - }, - }, - }); - let right = self.add_expression(Expression::Constant(one), body); - - let value = self.add_expression(Expression::Binary { op, left, right }, body); - - if postfix { - let local = self.locals.append(LocalVariable { - name: None, - ty: program.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: match uint { - true => ScalarKind::Uint, - false => ScalarKind::Sint, - }, - width: 4, - }, - }), - init: None, - }); - - let expr = self.add_expression(Expression::LocalVariable(local), body); - let load = self.add_expression(Expression::Load { pointer: expr }, body); - - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { - pointer: expr, - value: left, - }); - - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { pointer, value }); - - load - } else { - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { pointer, value }); - - left - } - } - _ => { - return Err(ErrorKind::SemanticError( - meta, - format!("{:?} cannot be in the left hand side", self.hir_exprs[expr]).into(), - )) - } - }; - - Ok((Some(handle), meta)) - } - - pub fn expr_scalar_components( - &mut self, - program: &mut Program, - expr: Handle, - meta: SourceMetadata, - ) -> Result, ErrorKind> { - let ty = program.resolve_type(self, expr, meta)?; - Ok(scalar_components(ty)) - } - - pub fn expr_power( - &mut self, - program: &mut Program, - expr: Handle, - meta: SourceMetadata, - ) -> Result, ErrorKind> { - Ok(self - .expr_scalar_components(program, expr, meta)? - .and_then(|(kind, _)| type_power(kind))) - } - - pub fn get_expression(&self, expr: Handle) -> &Expression { - &self.expressions[expr] - } - - pub fn implicit_conversion( - &mut self, - program: &mut Program, - expr: &mut Handle, - meta: SourceMetadata, - kind: ScalarKind, - width: crate::Bytes, - ) -> Result<(), ErrorKind> { - if let (Some(tgt_power), Some(expr_power)) = - (type_power(kind), self.expr_power(program, *expr, meta)?) - { - if tgt_power > expr_power { - *expr = self.expressions.append(Expression::As { - expr: *expr, - kind, - convert: Some(width), - }) - } - } - - Ok(()) - } - - pub fn binary_implicit_conversion( - &mut self, - program: &mut Program, - left: &mut Handle, - left_meta: SourceMetadata, - right: &mut Handle, - right_meta: SourceMetadata, - ) -> Result<(), ErrorKind> { - let left_components = self.expr_scalar_components(program, *left, left_meta)?; - let right_components = self.expr_scalar_components(program, *right, right_meta)?; - - if let ( - Some((left_power, left_width, left_kind)), - Some((right_power, right_width, right_kind)), - ) = ( - left_components.and_then(|(kind, width)| Some((type_power(kind)?, width, kind))), - right_components.and_then(|(kind, width)| Some((type_power(kind)?, width, kind))), - ) { - match left_power.cmp(&right_power) { - std::cmp::Ordering::Less => { - *left = self.expressions.append(Expression::As { - expr: *left, - kind: right_kind, - convert: Some(right_width), - }) - } - std::cmp::Ordering::Equal => {} - std::cmp::Ordering::Greater => { - *right = self.expressions.append(Expression::As { - expr: *right, - kind: left_kind, - convert: Some(left_width), - }) - } - } - } - - Ok(()) - } - - pub fn implicit_splat( - &mut self, - program: &mut Program, - expr: &mut Handle, - meta: SourceMetadata, - vector_size: Option, - ) -> Result<(), ErrorKind> { - let expr_type = program.resolve_type(self, *expr, meta)?; - - if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { - *expr = self - .expressions - .append(Expression::Splat { size, value: *expr }) - } - - Ok(()) - } - - pub fn vector_resize( - &mut self, - size: VectorSize, - vector: Handle, - body: &mut Block, - ) -> Handle { - self.add_expression( - Expression::Swizzle { - size, - vector, - pattern: crate::SwizzleComponent::XYZW, - }, - body, - ) - } -} - -impl<'function> Index> for Context<'function> { - type Output = Expression; - - fn index(&self, index: Handle) -> &Self::Output { - &self.expressions[index] - } -} - -pub fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, crate::Bytes)> { - match *ty { - TypeInner::Scalar { kind, width } => Some((kind, width)), - TypeInner::Vector { kind, width, .. } => Some((kind, width)), - TypeInner::Matrix { width, .. } => Some((ScalarKind::Float, width)), - TypeInner::ValuePointer { kind, width, .. } => Some((kind, width)), - _ => None, - } -} - -pub fn type_power(kind: ScalarKind) -> Option { - Some(match kind { - ScalarKind::Sint => 0, - ScalarKind::Uint => 1, - ScalarKind::Float => 2, - ScalarKind::Bool => return None, - }) -} - #[derive(Debug, Clone)] pub struct VariableReference { pub expr: Handle, @@ -1087,3 +163,8 @@ impl ParameterQualifier { } } } + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Profile { + Core, +} diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs new file mode 100644 index 000000000..b756bb08d --- /dev/null +++ b/src/front/glsl/context.rs @@ -0,0 +1,787 @@ +use crate::{ + front::{ + glsl::{ + ast::{ + GlobalLookup, GlobalLookupKind, HirExpr, HirExprKind, ParameterInfo, + ParameterQualifier, VariableReference, + }, + error::ErrorKind, + types::{scalar_components, type_power}, + Parser, SourceMetadata, + }, + Emitter, Typifier, + }, + Arena, BinaryOperator, Block, Constant, Expression, FastHashMap, FunctionArgument, Handle, + LocalVariable, RelationalFunction, ScalarKind, ScalarValue, Statement, StorageClass, Type, + TypeInner, VectorSize, +}; +use std::{convert::TryFrom, ops::Index}; + +#[derive(Debug)] +pub struct Context { + pub expressions: Arena, + pub locals: Arena, + pub arguments: Vec, + + pub parameters: Vec>, + pub parameters_info: Vec, + + //TODO: Find less allocation heavy representation + pub scopes: Vec>, + pub lookup_global_var_exps: FastHashMap, + pub samplers: FastHashMap, Handle>, + + pub hir_exprs: Arena, + pub typifier: Typifier, + emitter: Emitter, +} + +impl Context { + pub fn new(parser: &Parser, body: &mut Block) -> Self { + let mut this = Context { + expressions: Arena::new(), + locals: Arena::new(), + arguments: Vec::new(), + + parameters: Vec::new(), + parameters_info: Vec::new(), + + scopes: vec![FastHashMap::default()], + lookup_global_var_exps: FastHashMap::with_capacity_and_hasher( + parser.global_variables.len(), + Default::default(), + ), + samplers: FastHashMap::default(), + + hir_exprs: Arena::default(), + typifier: Typifier::new(), + emitter: Emitter::default(), + }; + + this.emit_start(); + + for &(ref name, lookup) in parser.global_variables.iter() { + this.add_global(parser, name, lookup, body) + } + + this + } + + pub fn add_global( + &mut self, + parser: &Parser, + name: &str, + GlobalLookup { + kind, + entry_arg, + mutable, + }: GlobalLookup, + body: &mut Block, + ) { + self.emit_flush(body); + let (expr, load) = match kind { + GlobalLookupKind::Variable(v) => { + let res = ( + self.expressions.append(Expression::GlobalVariable(v)), + parser.module.global_variables[v].class != StorageClass::Handle, + ); + self.emit_start(); + + res + } + GlobalLookupKind::BlockSelect(handle, index) => { + let base = self.expressions.append(Expression::GlobalVariable(handle)); + self.emit_start(); + let expr = self + .expressions + .append(Expression::AccessIndex { base, index }); + + (expr, { + let ty = parser.module.global_variables[handle].ty; + + match parser.module.types[ty].inner { + TypeInner::Struct { ref members, .. } => { + if let TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } = parser.module.types[members[index as usize].ty].inner + { + false + } else { + true + } + } + _ => true, + } + }) + } + GlobalLookupKind::Constant(v) => { + let res = (self.expressions.append(Expression::Constant(v)), false); + self.emit_start(); + res + } + }; + + let var = VariableReference { + expr, + load, + mutable, + entry_arg, + }; + + self.lookup_global_var_exps.insert(name.into(), var); + } + + pub fn emit_start(&mut self) { + self.emitter.start(&self.expressions) + } + + pub fn emit_flush(&mut self, body: &mut Block) { + body.extend(self.emitter.finish(&self.expressions)) + } + + pub fn add_expression(&mut self, expr: Expression, body: &mut Block) -> Handle { + if expr.needs_pre_emit() { + self.emit_flush(body); + let handle = self.expressions.append(expr); + self.emit_start(); + handle + } else { + self.expressions.append(expr) + } + } + + pub fn lookup_local_var(&self, name: &str) -> Option { + for scope in self.scopes.iter().rev() { + if let Some(var) = scope.get(name) { + return Some(var.clone()); + } + } + None + } + + pub fn lookup_global_var(&mut self, name: &str) -> Option { + self.lookup_global_var_exps.get(name).cloned() + } + + #[cfg(feature = "glsl-validate")] + pub fn lookup_local_var_current_scope(&self, name: &str) -> Option { + if let Some(current) = self.scopes.last() { + current.get(name).cloned() + } else { + None + } + } + + /// Add variable to current scope + pub fn add_local_var(&mut self, name: String, expr: Handle, mutable: bool) { + if let Some(current) = self.scopes.last_mut() { + (*current).insert( + name, + VariableReference { + expr, + load: true, + mutable, + entry_arg: None, + }, + ); + } + } + + /// Add function argument to current scope + pub fn add_function_arg( + &mut self, + parser: &mut Parser, + body: &mut Block, + name: Option, + ty: Handle, + qualifier: ParameterQualifier, + ) { + let index = self.arguments.len(); + let mut arg = FunctionArgument { + name: name.clone(), + ty, + binding: None, + }; + self.parameters.push(ty); + + let opaque = match parser.module.types[ty].inner { + TypeInner::Image { .. } | TypeInner::Sampler { .. } => true, + _ => false, + }; + + if qualifier.is_lhs() { + arg.ty = parser.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Pointer { + base: arg.ty, + class: StorageClass::Function, + }, + }) + } + + self.arguments.push(arg); + + self.parameters_info.push(ParameterInfo { + qualifier, + depth: false, + }); + + if let Some(name) = name { + let expr = self.add_expression(Expression::FunctionArgument(index as u32), body); + let mutable = qualifier != ParameterQualifier::Const && !opaque; + let load = qualifier.is_lhs(); + + if mutable && !load { + let handle = self.locals.append(LocalVariable { + name: Some(name.clone()), + ty, + init: None, + }); + let local_expr = self.add_expression(Expression::LocalVariable(handle), body); + + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { + pointer: local_expr, + value: expr, + }); + + if let Some(current) = self.scopes.last_mut() { + (*current).insert( + name, + VariableReference { + expr: local_expr, + load: true, + mutable, + entry_arg: None, + }, + ); + } + } else if let Some(current) = self.scopes.last_mut() { + (*current).insert( + name, + VariableReference { + expr, + load, + mutable, + entry_arg: None, + }, + ); + } + } + } + + /// Add new empty scope + pub fn push_scope(&mut self) { + self.scopes.push(FastHashMap::default()); + } + + pub fn remove_current_scope(&mut self) { + self.scopes.pop(); + } + + pub fn lower_expect( + &mut self, + parser: &mut Parser, + expr: Handle, + lhs: bool, + body: &mut Block, + ) -> Result<(Handle, SourceMetadata), ErrorKind> { + let (maybe_expr, meta) = self.lower(parser, expr, lhs, body)?; + + let expr = match maybe_expr { + Some(e) => e, + None => { + return Err(ErrorKind::SemanticError( + meta, + "Expression returns void".into(), + )) + } + }; + + Ok((expr, meta)) + } + + pub fn lower( + &mut self, + parser: &mut Parser, + expr: Handle, + lhs: bool, + body: &mut Block, + ) -> Result<(Option>, SourceMetadata), ErrorKind> { + let HirExpr { kind, meta } = self.hir_exprs[expr].clone(); + + let handle = match kind { + HirExprKind::Access { base, index } => { + let base = self.lower_expect(parser, base, true, body)?.0; + let (index, index_meta) = self.lower_expect(parser, index, false, body)?; + + let pointer = parser + .solve_constant(self, index, index_meta) + .ok() + .and_then(|constant| { + Some(self.add_expression( + Expression::AccessIndex { + base, + index: match parser.module.constants[constant].inner { + crate::ConstantInner::Scalar { + value: ScalarValue::Uint(i), + .. + } => u32::try_from(i).ok()?, + crate::ConstantInner::Scalar { + value: ScalarValue::Sint(i), + .. + } => u32::try_from(i).ok()?, + _ => return None, + }, + }, + body, + )) + }) + .unwrap_or_else(|| { + self.add_expression(Expression::Access { base, index }, body) + }); + + if !lhs { + let resolved = parser.resolve_type(self, pointer, meta)?; + if resolved.pointer_class().is_some() { + return Ok(( + Some(self.add_expression(Expression::Load { pointer }, body)), + meta, + )); + } + } + + pointer + } + HirExprKind::Select { base, field } => { + let base = self.lower_expect(parser, base, lhs, body)?.0; + + parser.field_selection(self, lhs, body, base, &field, meta)? + } + HirExprKind::Constant(constant) if !lhs => { + self.add_expression(Expression::Constant(constant), body) + } + HirExprKind::Binary { left, op, right } if !lhs => { + let (mut left, left_meta) = self.lower_expect(parser, left, false, body)?; + let (mut right, right_meta) = self.lower_expect(parser, right, false, body)?; + + match op { + BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self + .implicit_conversion(parser, &mut right, right_meta, ScalarKind::Uint, 4)?, + _ => self.binary_implicit_conversion( + parser, &mut left, left_meta, &mut right, right_meta, + )?, + } + + parser.typifier_grow(self, left, left_meta)?; + parser.typifier_grow(self, right, right_meta)?; + + let left_inner = self.typifier.get(left, &parser.module.types); + let right_inner = self.typifier.get(right, &parser.module.types); + + match (left_inner, right_inner) { + (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) + | (&TypeInner::Matrix { .. }, &TypeInner::Matrix { .. }) => match op { + BinaryOperator::Equal | BinaryOperator::NotEqual => { + let equals = op == BinaryOperator::Equal; + + let (op, fun) = match equals { + true => (BinaryOperator::Equal, RelationalFunction::All), + false => (BinaryOperator::NotEqual, RelationalFunction::Any), + }; + + let argument = + self.expressions + .append(Expression::Binary { op, left, right }); + + self.add_expression(Expression::Relational { fun, argument }, body) + } + _ => self.add_expression(Expression::Binary { left, op, right }, body), + }, + (&TypeInner::Vector { size, .. }, &TypeInner::Scalar { .. }) => match op { + BinaryOperator::Add + | BinaryOperator::Subtract + | BinaryOperator::Divide + | BinaryOperator::ShiftLeft + | BinaryOperator::ShiftRight => { + let scalar_vector = + self.add_expression(Expression::Splat { size, value: right }, body); + + self.add_expression( + Expression::Binary { + op, + left, + right: scalar_vector, + }, + body, + ) + } + _ => self.add_expression(Expression::Binary { left, op, right }, body), + }, + (&TypeInner::Scalar { .. }, &TypeInner::Vector { size, .. }) => match op { + BinaryOperator::Add | BinaryOperator::Subtract | BinaryOperator::Divide => { + let scalar_vector = + self.add_expression(Expression::Splat { size, value: left }, body); + + self.add_expression( + Expression::Binary { + op, + left: scalar_vector, + right, + }, + body, + ) + } + _ => self.add_expression(Expression::Binary { left, op, right }, body), + }, + _ => self.add_expression(Expression::Binary { left, op, right }, body), + } + } + HirExprKind::Unary { op, expr } if !lhs => { + let expr = self.lower_expect(parser, expr, false, body)?.0; + + self.add_expression(Expression::Unary { op, expr }, body) + } + HirExprKind::Variable(var) => { + if lhs { + if !var.mutable { + return Err(ErrorKind::SemanticError( + meta, + "Variable cannot be used in LHS position".into(), + )); + } + + var.expr + } else if var.load { + self.add_expression(Expression::Load { pointer: var.expr }, body) + } else { + var.expr + } + } + HirExprKind::Call(call) if !lhs => { + let maybe_expr = + parser.function_or_constructor_call(self, body, call.kind, &call.args, meta)?; + return Ok((maybe_expr, meta)); + } + HirExprKind::Conditional { + condition, + accept, + reject, + } if !lhs => { + let condition = self.lower_expect(parser, condition, false, body)?.0; + let (mut accept, accept_meta) = self.lower_expect(parser, accept, false, body)?; + let (mut reject, reject_meta) = self.lower_expect(parser, reject, false, body)?; + + self.binary_implicit_conversion( + parser, + &mut accept, + accept_meta, + &mut reject, + reject_meta, + )?; + + self.add_expression( + Expression::Select { + condition, + accept, + reject, + }, + body, + ) + } + HirExprKind::Assign { tgt, value } if !lhs => { + let (pointer, ptr_meta) = self.lower_expect(parser, tgt, true, body)?; + let (mut value, value_meta) = self.lower_expect(parser, value, false, body)?; + + let scalar_components = self.expr_scalar_components(parser, pointer, ptr_meta)?; + + if let Some((kind, width)) = scalar_components { + self.implicit_conversion(parser, &mut value, value_meta, kind, width)?; + } + + if let Expression::Swizzle { + size, + mut vector, + pattern, + } = self.expressions[pointer] + { + // Stores to swizzled values are not directly supported, + // lower them as series of per-component stores. + let size = match size { + VectorSize::Bi => 2, + VectorSize::Tri => 3, + VectorSize::Quad => 4, + }; + + if let Expression::Load { pointer } = self.expressions[vector] { + vector = pointer; + } + + #[allow(clippy::needless_range_loop)] + for index in 0..size { + let dst = self.add_expression( + Expression::AccessIndex { + base: vector, + index: pattern[index].index(), + }, + body, + ); + let src = self.add_expression( + Expression::AccessIndex { + base: value, + index: index as u32, + }, + body, + ); + + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { + pointer: dst, + value: src, + }); + } + } else { + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { pointer, value }); + } + + value + } + HirExprKind::IncDec { + increment, + postfix, + expr, + } => { + let op = match increment { + true => BinaryOperator::Add, + false => BinaryOperator::Subtract, + }; + + let pointer = self.lower_expect(parser, expr, true, body)?.0; + let left = self.add_expression(Expression::Load { pointer }, body); + + let uint = if let Some(kind) = parser.resolve_type(self, left, meta)?.scalar_kind() + { + match kind { + ScalarKind::Sint => false, + ScalarKind::Uint => true, + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Increment/decrement operations must operate in integers".into(), + )) + } + } + } else { + return Err(ErrorKind::SemanticError( + meta, + "Increment/decrement operations must operate in integers".into(), + )); + }; + + let one = parser.module.constants.append(Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: match uint { + true => crate::ScalarValue::Uint(1), + false => crate::ScalarValue::Sint(1), + }, + }, + }); + let right = self.add_expression(Expression::Constant(one), body); + + let value = self.add_expression(Expression::Binary { op, left, right }, body); + + if postfix { + let local = self.locals.append(LocalVariable { + name: None, + ty: parser.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Scalar { + kind: match uint { + true => ScalarKind::Uint, + false => ScalarKind::Sint, + }, + width: 4, + }, + }), + init: None, + }); + + let expr = self.add_expression(Expression::LocalVariable(local), body); + let load = self.add_expression(Expression::Load { pointer: expr }, body); + + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { + pointer: expr, + value: left, + }); + + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { pointer, value }); + + load + } else { + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { pointer, value }); + + left + } + } + _ => { + return Err(ErrorKind::SemanticError( + meta, + format!("{:?} cannot be in the left hand side", self.hir_exprs[expr]).into(), + )) + } + }; + + Ok((Some(handle), meta)) + } + + pub fn expr_scalar_components( + &mut self, + parser: &mut Parser, + expr: Handle, + meta: SourceMetadata, + ) -> Result, ErrorKind> { + let ty = parser.resolve_type(self, expr, meta)?; + Ok(scalar_components(ty)) + } + + pub fn expr_power( + &mut self, + parser: &mut Parser, + expr: Handle, + meta: SourceMetadata, + ) -> Result, ErrorKind> { + Ok(self + .expr_scalar_components(parser, expr, meta)? + .and_then(|(kind, _)| type_power(kind))) + } + + pub fn get_expression(&self, expr: Handle) -> &Expression { + &self.expressions[expr] + } + + pub fn implicit_conversion( + &mut self, + parser: &mut Parser, + expr: &mut Handle, + meta: SourceMetadata, + kind: ScalarKind, + width: crate::Bytes, + ) -> Result<(), ErrorKind> { + if let (Some(tgt_power), Some(expr_power)) = + (type_power(kind), self.expr_power(parser, *expr, meta)?) + { + if tgt_power > expr_power { + *expr = self.expressions.append(Expression::As { + expr: *expr, + kind, + convert: Some(width), + }) + } + } + + Ok(()) + } + + pub fn binary_implicit_conversion( + &mut self, + parser: &mut Parser, + left: &mut Handle, + left_meta: SourceMetadata, + right: &mut Handle, + right_meta: SourceMetadata, + ) -> Result<(), ErrorKind> { + let left_components = self.expr_scalar_components(parser, *left, left_meta)?; + let right_components = self.expr_scalar_components(parser, *right, right_meta)?; + + if let ( + Some((left_power, left_width, left_kind)), + Some((right_power, right_width, right_kind)), + ) = ( + left_components.and_then(|(kind, width)| Some((type_power(kind)?, width, kind))), + right_components.and_then(|(kind, width)| Some((type_power(kind)?, width, kind))), + ) { + match left_power.cmp(&right_power) { + std::cmp::Ordering::Less => { + *left = self.expressions.append(Expression::As { + expr: *left, + kind: right_kind, + convert: Some(right_width), + }) + } + std::cmp::Ordering::Equal => {} + std::cmp::Ordering::Greater => { + *right = self.expressions.append(Expression::As { + expr: *right, + kind: left_kind, + convert: Some(left_width), + }) + } + } + } + + Ok(()) + } + + pub fn implicit_splat( + &mut self, + parser: &mut Parser, + + expr: &mut Handle, + meta: SourceMetadata, + vector_size: Option, + ) -> Result<(), ErrorKind> { + let expr_type = parser.resolve_type(self, *expr, meta)?; + + if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { + *expr = self + .expressions + .append(Expression::Splat { size, value: *expr }) + } + + Ok(()) + } + + pub fn vector_resize( + &mut self, + size: VectorSize, + vector: Handle, + body: &mut Block, + ) -> Handle { + self.add_expression( + Expression::Swizzle { + size, + vector, + pattern: crate::SwizzleComponent::XYZW, + }, + body, + ) + } +} + +impl Index> for Context { + type Output = Expression; + + fn index(&self, index: Handle) -> &Self::Output { + &self.expressions[index] + } +} diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index c5309d6b4..3d3ab3932 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,22 +1,29 @@ -use super::{ast::*, error::ErrorKind, SourceMetadata}; use crate::{ - proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, - Expression, Function, FunctionArgument, FunctionResult, Handle, ImageClass, ImageDimension, - ImageQuery, LocalVariable, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind, - ScalarValue, Statement, StructMember, Type, TypeInner, VectorSize, + front::glsl::{ + ast::*, + context::Context, + error::ErrorKind, + types::{scalar_components, type_power}, + Parser, SourceMetadata, + }, + proc::ensure_block_returns, + Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, FastHashMap, + Function, FunctionArgument, FunctionResult, Handle, ImageClass, ImageDimension, ImageQuery, + LocalVariable, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind, ScalarValue, + Statement, StructMember, Type, TypeInner, VectorSize, }; use std::iter; /// Helper struct for texture calls with the separate components from the vector argument /// -/// Obtained by calling [`coordinate_components`](Program::coordinate_components) +/// Obtained by calling [`coordinate_components`](Parser::coordinate_components) struct CoordComponents { coordinate: Handle, depth_ref: Option>, array_index: Option>, } -impl Program { +impl Parser { fn add_constant_value(&mut self, scalar_kind: ScalarKind, value: u64) -> Handle { let value = match scalar_kind { ScalarKind::Uint => ScalarValue::Uint(value), @@ -1056,33 +1063,40 @@ impl Program { pub fn add_function( &mut self, - mut function: Function, + ctx: Context, name: String, - // Normalized function parameters, modifiers are not applied - parameters: Vec>, - parameters_info: Vec, + result: Option, + mut body: Block, meta: SourceMetadata, ) -> Result<(), ErrorKind> { - ensure_block_returns(&mut function.body); + ensure_block_returns(&mut body); - if name.as_str() == "main" { - let handle = self.module.functions.append(function); - return if self.entry_point.replace(handle).is_some() { - Err(ErrorKind::SemanticError(meta, "main defined twice".into())) - } else { - Ok(()) - }; - } + let void = result.is_none(); - let void = function.result.is_none(); - - let &mut Program { + let &mut Parser { ref mut lookup_function, ref mut module, .. } = self; - let declarations = lookup_function.entry(name).or_default(); + let declarations = lookup_function.entry(name.clone()).or_default(); + let Context { + expressions, + locals, + arguments, + parameters, + parameters_info, + .. + } = ctx; + let function = Function { + name: Some(name), + arguments, + result, + local_variables: locals, + expressions, + named_expressions: FastHashMap::default(), + body, + }; 'outer: for decl in declarations.iter_mut() { if parameters.len() != decl.parameters.len() { @@ -1125,22 +1139,33 @@ impl Program { pub fn add_prototype( &mut self, - function: Function, + ctx: Context, name: String, - // Normalized function parameters, modifiers are not applied - parameters: Vec>, - parameters_info: Vec, + result: Option, meta: SourceMetadata, ) -> Result<(), ErrorKind> { - let void = function.result.is_none(); + let void = result.is_none(); - let &mut Program { + let &mut Parser { ref mut lookup_function, ref mut module, .. } = self; - let declarations = lookup_function.entry(name).or_default(); + let declarations = lookup_function.entry(name.clone()).or_default(); + + let Context { + arguments, + parameters, + parameters_info, + .. + } = ctx; + let function = Function { + name: Some(name), + arguments, + result, + ..Default::default() + }; 'outer: for decl in declarations.iter_mut() { if parameters.len() != decl.parameters.len() { @@ -1268,10 +1293,10 @@ impl Program { self.module.entry_points.push(EntryPoint { name: "main".to_string(), - stage: self.stage, + stage: self.meta.stage, early_depth_test: Some(crate::EarlyDepthTest { conservative: None }) - .filter(|_| self.early_fragment_tests), - workgroup_size: self.workgroup_size, + .filter(|_| self.meta.early_fragment_tests), + workgroup_size: self.meta.workgroup_size, function: Function { arguments, expressions, @@ -1286,7 +1311,7 @@ impl Program { /// Helper function for texture calls, splits the vector argument into it's components fn coordinate_components( - &self, + &mut self, ctx: &mut Context, (image, image_meta): (Handle, SourceMetadata), (coord, coord_meta): (Handle, SourceMetadata), diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 88966d034..8e487b815 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,17 +1,17 @@ -pub use error::ErrorKind; +pub use ast::Profile; +pub use error::{ErrorKind, ParseError}; pub use token::{SourceMetadata, Token}; -use crate::{FastHashMap, Module, ShaderStage}; - -mod lex; +use crate::{FastHashMap, Handle, Module, ShaderStage, Type}; +use ast::{EntryArg, FunctionDeclaration, GlobalLookup}; +use parser::ParsingContext; mod ast; -use ast::Program; - -mod error; -pub use error::ParseError; mod constants; +mod context; +mod error; mod functions; +mod lex; mod offset; mod parser; #[cfg(test)] @@ -20,17 +20,95 @@ mod token; mod types; mod variables; +type Result = std::result::Result; + pub struct Options { pub stage: ShaderStage, pub defines: FastHashMap, } -pub fn parse_str(source: &str, options: &Options) -> Result { - let mut program = Program::new(options.stage); +#[derive(Debug)] +pub struct ShaderMetadata { + pub version: u16, + pub profile: Profile, + pub stage: ShaderStage, - let lex = lex::Lexer::new(source, &options.defines); - let mut parser = parser::Parser::new(&mut program, lex); - parser.parse()?; + pub workgroup_size: [u32; 3], + pub early_fragment_tests: bool, - Ok(program.module) + pub extensions: FastHashMap, +} + +impl ShaderMetadata { + fn reset(&mut self, stage: ShaderStage) { + self.version = 0; + self.profile = Profile::Core; + self.stage = stage; + self.workgroup_size = [if stage == ShaderStage::Compute { 1 } else { 0 }; 3]; + self.early_fragment_tests = false; + self.extensions.clear(); + } +} + +impl Default for ShaderMetadata { + fn default() -> Self { + ShaderMetadata { + version: 0, + profile: Profile::Core, + stage: ShaderStage::Vertex, + workgroup_size: [0; 3], + early_fragment_tests: false, + extensions: FastHashMap::default(), + } + } +} + +#[derive(Debug, Default)] +pub struct Parser { + meta: ShaderMetadata, + + lookup_function: FastHashMap>, + lookup_type: FastHashMap>, + + global_variables: Vec<(String, GlobalLookup)>, + + entry_args: Vec, + + module: Module, +} + +impl Parser { + fn reset(&mut self, stage: ShaderStage) { + self.meta.reset(stage); + + self.lookup_function.clear(); + self.lookup_type.clear(); + self.global_variables.clear(); + self.entry_args.clear(); + + // This is necessary because if the last parsing errored out, the module + // wouldn't have been swapped + self.module = Module::default(); + } + + pub fn parse( + &mut self, + options: &Options, + source: &str, + ) -> std::result::Result { + self.reset(options.stage); + + let lexer = lex::Lexer::new(source, &options.defines); + let mut ctx = ParsingContext::new(lexer); + + ctx.parse(self).map_err(|kind| ParseError { kind })?; + + let mut module = Module::default(); + std::mem::swap(&mut self.module, &mut module); + Ok(module) + } + + pub fn metadata(&self) -> &ShaderMetadata { + &self.meta + } } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index d9bf53f74..56982391c 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,42 +1,38 @@ -use super::{ - ast::{ - self, Context, FunctionCall, FunctionCallKind, GlobalLookup, GlobalLookupKind, HirExpr, - HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier, - }, - error::ErrorKind, - lex::Lexer, - offset, - token::{SourceMetadata, Token, TokenValue}, - variables::{GlobalOrConstant, VarDeclaration}, - Program, -}; use crate::{ arena::Handle, - front::glsl::{ast::Precision, error::ExpectedToken}, - Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Expression, Function, - FunctionResult, ResourceBinding, ScalarKind, ScalarValue, Statement, StorageClass, - StructMember, SwitchCase, Type, TypeInner, UnaryOperator, + front::glsl::{ + ast::{Profile, TypeQualifier}, + context::Context, + error::ErrorKind, + error::ExpectedToken, + lex::Lexer, + token::{SourceMetadata, Token, TokenValue}, + variables::{GlobalOrConstant, VarDeclaration}, + Parser, Result, + }, + Block, Constant, ConstantInner, Expression, ScalarValue, Type, }; use core::convert::TryFrom; use std::iter::Peekable; -type Result = std::result::Result; +mod declarations; +mod expressions; +mod functions; +mod types; -pub struct Parser<'source, 'program> { - program: &'program mut Program, +pub struct ParsingContext<'source> { lexer: Peekable>, } -impl<'source, 'program> Parser<'source, 'program> { - pub fn new(program: &'program mut Program, lexer: Lexer<'source>) -> Self { - Parser { - program, +impl<'source> ParsingContext<'source> { + pub fn new(lexer: Lexer<'source>) -> Self { + ParsingContext { lexer: lexer.peekable(), } } - fn expect_ident(&mut self) -> Result<(String, SourceMetadata)> { - let token = self.bump()?; + pub fn expect_ident(&mut self, parser: &mut Parser) -> Result<(String, SourceMetadata)> { + let token = self.bump(parser)?; match token.value { TokenValue::Identifier(name) => Ok((name, token.meta)), @@ -47,8 +43,8 @@ impl<'source, 'program> Parser<'source, 'program> { } } - fn expect(&mut self, value: TokenValue) -> Result { - let token = self.bump()?; + pub fn expect(&mut self, parser: &mut Parser, value: TokenValue) -> Result { + let token = self.bump(parser)?; if token.value != value { Err(ErrorKind::InvalidToken(token, vec![value.into()])) @@ -57,57 +53,67 @@ impl<'source, 'program> Parser<'source, 'program> { } } - fn bump(&mut self) -> Result { - self.lexer.next().ok_or(ErrorKind::EndOfFile) + pub fn next(&mut self, _parser: &mut Parser) -> Option { + self.lexer.next() + } + + pub fn bump(&mut self, parser: &mut Parser) -> Result { + self.next(parser).ok_or(ErrorKind::EndOfFile) } /// Returns None on the end of the file rather than an error like other methods - fn bump_if(&mut self, value: TokenValue) -> Option { - if self.lexer.peek().filter(|t| t.value == value).is_some() { - self.bump().ok() + pub fn bump_if(&mut self, parser: &mut Parser, value: TokenValue) -> Option { + if self.peek(parser).filter(|t| t.value == value).is_some() { + self.bump(parser).ok() } else { None } } - fn expect_peek(&mut self) -> Result<&Token> { - self.lexer.peek().ok_or(ErrorKind::EndOfFile) + pub fn peek(&mut self, _parser: &mut Parser) -> Option<&Token> { + self.lexer.peek() } - pub fn parse(&mut self) -> Result<()> { - self.parse_version()?; + pub fn expect_peek(&mut self, parser: &mut Parser) -> Result<&Token> { + self.peek(parser).ok_or(ErrorKind::EndOfFile) + } + + pub fn parse(&mut self, parser: &mut Parser) -> Result<()> { + self.parse_version(parser)?; // Body and expression arena for global initialization let mut body = Block::new(); - let mut expressions = Arena::new(); - let mut arguments = Vec::new(); - let mut locals = Arena::new(); - let mut ctx = Context::new( - self.program, - &mut body, - &mut expressions, - &mut locals, - &mut arguments, - ); + let mut ctx = Context::new(parser, &mut body); - while self.lexer.peek().is_some() { - self.parse_external_declaration(&mut ctx, &mut body)?; + while self.peek(parser).is_some() { + self.parse_external_declaration(parser, &mut ctx, &mut body)?; } - if let Some(handle) = self.program.entry_point { - self.program.add_entry_point(handle, body, expressions)?; - } + let handle = parser + .lookup_function + .get("main") + .and_then(|declarations| { + declarations + .iter() + .find(|decl| decl.defined && decl.parameters.is_empty()) + .map(|decl| decl.handle) + }) + .ok_or_else(|| { + ErrorKind::SemanticError(SourceMetadata::default(), "Missing entry point".into()) + })?; + + parser.add_entry_point(handle, body, ctx.expressions)?; Ok(()) } - fn parse_version(&mut self) -> Result<()> { - self.expect(TokenValue::Version)?; + fn parse_version(&mut self, parser: &mut Parser) -> Result<()> { + self.expect(parser, TokenValue::Version)?; - let version = self.bump()?; + let version = self.bump(parser)?; match version.value { TokenValue::IntConstant(i) => match i.value { - 440 | 450 | 460 => self.program.version = i.value as u16, + 440 | 450 | 460 => parser.meta.version = i.value as u16, _ => return Err(ErrorKind::InvalidVersion(version.meta, i.value)), }, _ => { @@ -119,12 +125,12 @@ impl<'source, 'program> Parser<'source, 'program> { } let profile = self.lexer.peek(); - self.program.profile = match profile { + parser.meta.profile = match profile { Some(&Token { value: TokenValue::Identifier(_), .. }) => { - let (name, meta) = self.expect_ident()?; + let (name, meta) = self.expect_ident(parser)?; match name.as_str() { "core" => Profile::Core, @@ -137,194 +143,10 @@ impl<'source, 'program> Parser<'source, 'program> { Ok(()) } - /// Parses an optional array_specifier returning `Ok(None)` if there is no - /// LeftBracket - fn parse_array_specifier(&mut self) -> Result> { - if self.bump_if(TokenValue::LeftBracket).is_some() { - if self.bump_if(TokenValue::RightBracket).is_some() { - return Ok(Some(ArraySize::Dynamic)); - } + fn parse_uint_constant(&mut self, parser: &mut Parser) -> Result<(u32, SourceMetadata)> { + let (value, meta) = self.parse_constant_expression(parser)?; - let (constant, _) = self.parse_constant_expression()?; - self.expect(TokenValue::RightBracket)?; - Ok(Some(ArraySize::Constant(constant))) - } else { - Ok(None) - } - } - - fn parse_type(&mut self) -> Result<(Option>, SourceMetadata)> { - let token = self.bump()?; - let handle = match token.value { - TokenValue::Void => None, - TokenValue::TypeName(ty) => Some(self.program.module.types.fetch_or_append(ty)), - TokenValue::Struct => { - let ty_name = self.expect_ident()?.0; - self.expect(TokenValue::LeftBrace)?; - let mut members = Vec::new(); - let span = - self.parse_struct_declaration_list(&mut members, StructLayout::Std140)?; - self.expect(TokenValue::RightBrace)?; - - let ty = self.program.module.types.append(Type { - name: Some(ty_name.clone()), - inner: TypeInner::Struct { - top_level: false, - members, - span, - }, - }); - self.program.lookup_type.insert(ty_name, ty); - Some(ty) - } - TokenValue::Identifier(ident) => match self.program.lookup_type.get(&ident) { - Some(ty) => Some(*ty), - None => return Err(ErrorKind::UnknownType(token.meta, ident)), - }, - _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ - TokenValue::Void.into(), - TokenValue::Struct.into(), - ExpectedToken::TypeName, - ], - )) - } - }; - - let size = self.parse_array_specifier()?; - Ok((handle.map(|ty| self.maybe_array(ty, size)), token.meta)) - } - - fn parse_type_non_void(&mut self) -> Result<(Handle, SourceMetadata)> { - let (maybe_ty, meta) = self.parse_type()?; - let ty = - maybe_ty.ok_or_else(|| ErrorKind::SemanticError(meta, "Type can't be void".into()))?; - - Ok((ty, meta)) - } - - fn maybe_array(&mut self, base: Handle, size: Option) -> Handle { - size.map(|size| { - self.program.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base, - size, - stride: self.program.module.types[base] - .inner - .span(&self.program.module.constants), - }, - }) - }) - .unwrap_or(base) - } - - fn peek_type_qualifier(&mut self) -> bool { - self.lexer.peek().map_or(false, |t| match t.value { - TokenValue::Interpolation(_) - | TokenValue::Sampling(_) - | TokenValue::PrecisionQualifier(_) - | TokenValue::Const - | TokenValue::In - | TokenValue::Out - | TokenValue::Uniform - | TokenValue::Buffer - | TokenValue::Restrict - | TokenValue::StorageAccess(_) - | TokenValue::Layout => true, - _ => false, - }) - } - - fn parse_type_qualifiers(&mut self) -> Result> { - let mut qualifiers = Vec::new(); - - while self.peek_type_qualifier() { - let token = self.bump()?; - - // Handle layout qualifiers outside the match since this can push multiple values - if token.value == TokenValue::Layout { - self.parse_layout_qualifier_id_list(&mut qualifiers)?; - continue; - } - - qualifiers.push(( - match token.value { - TokenValue::Interpolation(i) => TypeQualifier::Interpolation(i), - TokenValue::Const => TypeQualifier::StorageQualifier(StorageQualifier::Const), - TokenValue::In => TypeQualifier::StorageQualifier(StorageQualifier::Input), - TokenValue::Out => TypeQualifier::StorageQualifier(StorageQualifier::Output), - TokenValue::Uniform => TypeQualifier::StorageQualifier( - StorageQualifier::StorageClass(StorageClass::Uniform), - ), - TokenValue::Buffer => TypeQualifier::StorageQualifier( - StorageQualifier::StorageClass(StorageClass::Storage { - access: crate::StorageAccess::default(), - }), - ), - TokenValue::Sampling(s) => TypeQualifier::Sampling(s), - TokenValue::PrecisionQualifier(p) => TypeQualifier::Precision(p), - TokenValue::StorageAccess(access) => TypeQualifier::StorageAccess(access), - TokenValue::Restrict => continue, - _ => unreachable!(), - }, - token.meta, - )) - } - - Ok(qualifiers) - } - - fn parse_layout_qualifier_id_list( - &mut self, - qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, - ) -> Result<()> { - // We need both of these to produce a ResourceBinding - let mut group = None; - let mut binding = None; - - self.expect(TokenValue::LeftParen)?; - loop { - self.parse_layout_qualifier_id(qualifiers, &mut group, &mut binding)?; - - if self.bump_if(TokenValue::Comma).is_some() { - continue; - } - - break; - } - self.expect(TokenValue::RightParen)?; - - match (group, binding) { - (Some((group, group_meta)), Some((binding, binding_meta))) => qualifiers.push(( - TypeQualifier::ResourceBinding(ResourceBinding { group, binding }), - group_meta.union(&binding_meta), - )), - // Produce an error if we have one of group or binding but not the other - (Some((_, meta)), None) => { - return Err(ErrorKind::SemanticError( - meta, - "set specified with no binding".into(), - )) - } - (None, Some((_, meta))) => { - return Err(ErrorKind::SemanticError( - meta, - "binding specified with no set".into(), - )) - } - (None, None) => (), - } - - Ok(()) - } - - fn parse_uint_constant(&mut self) -> Result<(u32, SourceMetadata)> { - let (value, meta) = self.parse_constant_expression()?; - - let int = match self.program.module.constants[value].inner { + let int = match parser.module.constants[value].inner { ConstantInner::Scalar { value: ScalarValue::Uint(int), .. @@ -344,1628 +166,33 @@ impl<'source, 'program> Parser<'source, 'program> { Ok((int, meta)) } - fn parse_layout_qualifier_id( + fn parse_constant_expression( &mut self, - qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, - group: &mut Option<(u32, SourceMetadata)>, - binding: &mut Option<(u32, SourceMetadata)>, - ) -> Result<()> { - // layout_qualifier_id: - // IDENTIFIER - // IDENTIFIER EQUAL constant_expression - // SHARED - let mut token = self.bump()?; - match token.value { - TokenValue::Identifier(name) => { - if self.bump_if(TokenValue::Assign).is_some() { - let (value, end_meta) = self.parse_uint_constant()?; - token.meta = token.meta.union(&end_meta); - - qualifiers.push(( - match name.as_str() { - "location" => TypeQualifier::Location(value), - "set" => { - *group = Some((value, end_meta)); - return Ok(()); - } - "binding" => { - *binding = Some((value, end_meta)); - return Ok(()); - } - "local_size_x" => TypeQualifier::WorkGroupSize(0, value), - "local_size_y" => TypeQualifier::WorkGroupSize(1, value), - "local_size_z" => TypeQualifier::WorkGroupSize(2, value), - _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), - }, - token.meta, - )) - } else { - match name.as_str() { - "push_constant" => { - qualifiers.push(( - TypeQualifier::StorageQualifier(StorageQualifier::StorageClass( - StorageClass::PushConstant, - )), - token.meta, - )); - qualifiers - .push((TypeQualifier::Layout(StructLayout::Std430), token.meta)); - } - "std140" => qualifiers - .push((TypeQualifier::Layout(StructLayout::Std140), token.meta)), - "std430" => qualifiers - .push((TypeQualifier::Layout(StructLayout::Std430), token.meta)), - "early_fragment_tests" => { - qualifiers.push((TypeQualifier::EarlyFragmentTests, token.meta)) - } - _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), - } - }; - - Ok(()) - } - // TODO: handle Shared? - _ => Err(ErrorKind::InvalidToken( - token, - vec![ExpectedToken::Identifier], - )), - } - } - - fn parse_constant_expression(&mut self) -> Result<(Handle, SourceMetadata)> { - let mut expressions = Arena::new(); - let mut locals = Arena::new(); - let mut arguments = Vec::new(); + parser: &mut Parser, + ) -> Result<(Handle, SourceMetadata)> { let mut block = Block::new(); - let mut ctx = Context::new( - self.program, - &mut block, - &mut expressions, - &mut locals, - &mut arguments, - ); + let mut ctx = Context::new(parser, &mut block); - let expr = self.parse_conditional(&mut ctx, &mut block, None)?; - let (root, meta) = ctx.lower_expect(self.program, expr, false, &mut block)?; + let expr = self.parse_conditional(parser, &mut ctx, &mut block, None)?; + let (root, meta) = ctx.lower_expect(parser, expr, false, &mut block)?; - Ok((self.program.solve_constant(&ctx, root, meta)?, meta)) - } - - fn parse_external_declaration( - &mut self, - global_ctx: &mut Context, - global_body: &mut Block, - ) -> Result<()> { - if !self.parse_declaration(global_ctx, global_body, true)? { - let token = self.bump()?; - match token.value { - TokenValue::Semicolon if self.program.version == 460 => Ok(()), - _ => { - let expected = match self.program.version { - 460 => vec![TokenValue::Semicolon.into(), ExpectedToken::Eof], - _ => vec![ExpectedToken::Eof], - }; - Err(ErrorKind::InvalidToken(token, expected)) - } - } - } else { - Ok(()) - } - } - - fn peek_type_name(&mut self) -> bool { - let program = &self.program; - self.lexer.peek().map_or(false, |t| match t.value { - TokenValue::TypeName(_) | TokenValue::Void => true, - TokenValue::Struct => true, - TokenValue::Identifier(ref ident) => program.lookup_type.contains_key(ident), - _ => false, - }) - } - - fn peek_parameter_qualifier(&mut self) -> bool { - self.lexer.peek().map_or(false, |t| match t.value { - TokenValue::In | TokenValue::Out | TokenValue::InOut | TokenValue::Const => true, - _ => false, - }) - } - - /// Returns the parsed `ParameterQualifier` or `ParameterQualifier::In` - fn parse_parameter_qualifier(&mut self) -> ParameterQualifier { - if self.peek_parameter_qualifier() { - match self.bump().unwrap().value { - TokenValue::In => ParameterQualifier::In, - TokenValue::Out => ParameterQualifier::Out, - TokenValue::InOut => ParameterQualifier::InOut, - TokenValue::Const => ParameterQualifier::Const, - _ => unreachable!(), - } - } else { - ParameterQualifier::In - } - } - - fn parse_initializer( - &mut self, - ty: Handle, - ctx: &mut Context, - body: &mut Block, - ) -> Result<(Handle, SourceMetadata)> { - // initializer: - // assignment_expression - // LEFT_BRACE initializer_list RIGHT_BRACE - // LEFT_BRACE initializer_list COMMA RIGHT_BRACE - // - // initializer_list: - // initializer - // initializer_list COMMA initializer - if let Some(Token { mut meta, .. }) = self.bump_if(TokenValue::LeftBrace) { - // initializer_list - let mut components = Vec::new(); - loop { - // TODO: Change type - components.push(self.parse_initializer(ty, ctx, body)?.0); - - let token = self.bump()?; - match token.value { - TokenValue::Comma => { - if let Some(Token { meta: end_meta, .. }) = - self.bump_if(TokenValue::RightBrace) - { - meta = meta.union(&end_meta); - break; - } - } - TokenValue::RightBrace => { - meta = meta.union(&token.meta); - break; - } - _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![TokenValue::Comma.into(), TokenValue::RightBrace.into()], - )) - } - } - } - - Ok(( - ctx.add_expression(Expression::Compose { ty, components }, body), - meta, - )) - } else { - let expr = self.parse_assignment(ctx, body)?; - let (mut init, init_meta) = ctx.lower_expect(self.program, expr, false, body)?; - - let scalar_components = ast::scalar_components(&self.program.module.types[ty].inner); - if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self.program, &mut init, init_meta, kind, width)?; - } - - Ok((init, init_meta)) - } - } - - // Note: caller preparsed the type and qualifiers - // Note: caller skips this if the fallthrough token is not expected to be consumed here so this - // produced Error::InvalidToken if it isn't consumed - fn parse_init_declarator_list( - &mut self, - ty: Handle, - mut fallthrough: Option, - ctx: &mut DeclarationContext, - ) -> Result<()> { - // init_declarator_list: - // single_declaration - // init_declarator_list COMMA IDENTIFIER - // init_declarator_list COMMA IDENTIFIER array_specifier - // init_declarator_list COMMA IDENTIFIER array_specifier EQUAL initializer - // init_declarator_list COMMA IDENTIFIER EQUAL initializer - // - // single_declaration: - // fully_specified_type - // fully_specified_type IDENTIFIER - // fully_specified_type IDENTIFIER array_specifier - // fully_specified_type IDENTIFIER array_specifier EQUAL initializer - // fully_specified_type IDENTIFIER EQUAL initializer - - // Consume any leading comma, e.g. this is valid: `float, a=1;` - if fallthrough - .as_ref() - .or_else(|| self.lexer.peek()) - .filter(|t| t.value == TokenValue::Comma) - .is_some() - { - fallthrough.take().or_else(|| self.lexer.next()); - } - - loop { - let token = fallthrough - .take() - .ok_or(ErrorKind::EndOfFile) - .or_else(|_| self.bump())?; - let name = match token.value { - TokenValue::Semicolon => break, - TokenValue::Identifier(name) => name, - _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], - )) - } - }; - let mut meta = token.meta; - - // array_specifier - // array_specifier EQUAL initializer - // EQUAL initializer - - // parse an array specifier if it exists - // NOTE: unlike other parse methods this one doesn't expect an array specifier and - // returns Ok(None) rather than an error if there is not one - let array_specifier = self.parse_array_specifier()?; - let ty = self.maybe_array(ty, array_specifier); - - let init = self - .bump_if(TokenValue::Assign) - .map::, _>(|_| { - let (mut expr, init_meta) = self.parse_initializer(ty, ctx.ctx, ctx.body)?; - - let scalar_components = - ast::scalar_components(&self.program.module.types[ty].inner); - if let Some((kind, width)) = scalar_components { - ctx.ctx.implicit_conversion( - self.program, - &mut expr, - init_meta, - kind, - width, - )?; - } - - meta = meta.union(&init_meta); - - Ok((expr, init_meta)) - }) - .transpose()?; - - // TODO: Should we try to make constants here? - // This is mostly a hack because we don't yet support adding - // bodies to entry points for variable initialization - let maybe_constant = - init.and_then(|(root, meta)| self.program.solve_constant(ctx.ctx, root, meta).ok()); - - let pointer = ctx.add_var(self.program, ty, name, maybe_constant, meta)?; - - if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) { - ctx.flush_expressions(); - ctx.body.push(Statement::Store { pointer, value }); - } - - let token = self.bump()?; - match token.value { - TokenValue::Semicolon => break, - TokenValue::Comma => {} - _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![TokenValue::Comma.into(), TokenValue::Semicolon.into()], - )) - } - } - } - - Ok(()) - } - - /// `external` whether or not we are in a global or local context - fn parse_declaration( - &mut self, - ctx: &mut Context, - body: &mut Block, - external: bool, - ) -> Result { - //declaration: - // function_prototype SEMICOLON - // - // init_declarator_list SEMICOLON - // PRECISION precision_qualifier type_specifier SEMICOLON - // - // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE SEMICOLON - // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER SEMICOLON - // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER array_specifier SEMICOLON - // type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON - // type_qualifier IDENTIFIER identifier_list SEMICOLON - - if self.peek_type_qualifier() || self.peek_type_name() { - let qualifiers = self.parse_type_qualifiers()?; - - if self.peek_type_name() { - // This branch handles variables and function prototypes and if - // external is true also function definitions - let (ty, mut meta) = self.parse_type()?; - - let token = self.bump()?; - let token_fallthrough = match token.value { - TokenValue::Identifier(name) => match self.expect_peek()?.value { - TokenValue::LeftParen => { - // This branch handles function definition and prototypes - self.bump()?; - - let result = ty.map(|ty| FunctionResult { ty, binding: None }); - let mut expressions = Arena::new(); - let mut local_variables = Arena::new(); - let mut arguments = Vec::new(); - // Normalized function parameters, modifiers are not applied - let mut parameters = Vec::new(); - let mut body = Block::new(); - - let mut context = Context::new( - self.program, - &mut body, - &mut expressions, - &mut local_variables, - &mut arguments, - ); - - self.parse_function_args(&mut context, &mut body, &mut parameters)?; - - let end_meta = self.expect(TokenValue::RightParen)?.meta; - meta = meta.union(&end_meta); - - let token = self.bump()?; - return match token.value { - TokenValue::Semicolon => { - // This branch handles function prototypes - - let Context { - parameters_info, .. - } = context; - - self.program.add_prototype( - Function { - name: Some(name.clone()), - result, - arguments, - ..Default::default() - }, - name, - parameters, - parameters_info, - meta, - )?; - - Ok(true) - } - TokenValue::LeftBrace if external => { - // This branch handles function definitions - // as you can see by the guard this branch - // only happens if external is also true - - // parse the body - self.parse_compound_statement(&mut context, &mut body)?; - - let Context { - parameters_info, .. - } = context; - self.program.add_function( - Function { - name: Some(name.clone()), - result, - expressions, - named_expressions: crate::FastHashMap::default(), - local_variables, - arguments, - body, - }, - name, - parameters, - parameters_info, - meta, - )?; - - Ok(true) - } - _ if external => Err(ErrorKind::InvalidToken( - token, - vec![ - TokenValue::LeftBrace.into(), - TokenValue::Semicolon.into(), - ], - )), - _ => Err(ErrorKind::InvalidToken( - token, - vec![TokenValue::Semicolon.into()], - )), - }; - } - // Pass the token to the init_declator_list parser - _ => Token { - value: TokenValue::Identifier(name), - meta: token.meta, - }, - }, - // Pass the token to the init_declator_list parser - _ => token, - }; - - // If program execution has reached here then this will be a - // init_declarator_list - // token_falltrough will have a token that was already bumped - if let Some(ty) = ty { - let mut ctx = DeclarationContext { - qualifiers, - external, - ctx, - body, - }; - - self.parse_init_declarator_list(ty, Some(token_fallthrough), &mut ctx)?; - } else { - return Err(ErrorKind::SemanticError( - meta, - "Declaration cannot have void type".into(), - )); - } - - Ok(true) - } else { - // This branch handles struct definitions and modifiers like - // ```glsl - // layout(early_fragment_tests); - // ``` - let token = self.bump()?; - match token.value { - TokenValue::Identifier(ty_name) => { - if self.bump_if(TokenValue::LeftBrace).is_some() { - self.parse_block_declaration( - ctx, - body, - &qualifiers, - ty_name, - token.meta, - ) - } else { - //TODO: declaration - // type_qualifier IDENTIFIER SEMICOLON - // type_qualifier IDENTIFIER identifier_list SEMICOLON - Err(ErrorKind::NotImplemented(token.meta, "variable qualifier")) - } - } - TokenValue::Semicolon => { - for &(ref qualifier, meta) in qualifiers.iter() { - match *qualifier { - TypeQualifier::WorkGroupSize(i, value) => { - self.program.workgroup_size[i] = value - } - TypeQualifier::EarlyFragmentTests => { - self.program.early_fragment_tests = true; - } - TypeQualifier::StorageQualifier(_) => { - // TODO: Maybe add some checks here - // This is needed because of cases like - // layout(early_fragment_tests) in; - } - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Qualifier not supported as standalone".into(), - )); - } - } - } - - Ok(true) - } - _ => Err(ErrorKind::InvalidToken( - token, - vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], - )), - } - } - } else { - match self.lexer.peek().map(|t| &t.value) { - Some(&TokenValue::Precision) => { - // PRECISION precision_qualifier type_specifier SEMICOLON - self.bump()?; - - let token = self.bump()?; - let _ = match token.value { - TokenValue::PrecisionQualifier(p) => p, - _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ - TokenValue::PrecisionQualifier(Precision::High).into(), - TokenValue::PrecisionQualifier(Precision::Medium).into(), - TokenValue::PrecisionQualifier(Precision::Low).into(), - ], - )) - } - }; - - let (ty, meta) = self.parse_type_non_void()?; - - match self.program.module.types[ty].inner { - TypeInner::Scalar { - kind: ScalarKind::Float, - .. - } - | TypeInner::Scalar { - kind: ScalarKind::Sint, - .. - } => {} - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Precision statement can only work on floats and ints".into(), - )) - } - } - - self.expect(TokenValue::Semicolon)?; - - Ok(true) - } - _ => Ok(false), - } - } - } - - fn parse_block_declaration( - &mut self, - ctx: &mut Context, - body: &mut Block, - qualifiers: &[(TypeQualifier, SourceMetadata)], - ty_name: String, - mut meta: SourceMetadata, - ) -> Result { - let mut storage = None; - let mut layout = None; - - for &(ref qualifier, _) in qualifiers { - match *qualifier { - TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { - storage = Some(c) - } - TypeQualifier::Layout(l) => layout = Some(l), - _ => continue, - } - } - - let layout = match (layout, storage) { - (Some(layout), _) => layout, - (None, Some(StorageClass::Storage { .. })) => StructLayout::Std430, - _ => StructLayout::Std140, - }; - - let mut members = Vec::new(); - let span = self.parse_struct_declaration_list(&mut members, layout)?; - self.expect(TokenValue::RightBrace)?; - - let mut ty = self.program.module.types.append(Type { - name: Some(ty_name), - inner: TypeInner::Struct { - top_level: true, - members: members.clone(), - span, - }, - }); - - let token = self.bump()?; - let name = match token.value { - TokenValue::Semicolon => None, - TokenValue::Identifier(name) => { - if let Some(size) = self.parse_array_specifier()? { - ty = self.program.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size, - stride: self.program.module.types[ty] - .inner - .span(&self.program.module.constants), - }, - }); - } - - self.expect(TokenValue::Semicolon)?; - - Some(name) - } - _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], - )) - } - }; - meta = meta.union(&token.meta); - - let global = self.program.add_global_var( - ctx, - body, - VarDeclaration { - qualifiers, - ty, - name, - init: None, - meta, - }, - )?; - - for (i, k) in members - .into_iter() - .enumerate() - .filter_map(|(i, m)| m.name.map(|s| (i as u32, s))) - { - let lookup = GlobalLookup { - kind: match global { - GlobalOrConstant::Global(handle) => GlobalLookupKind::BlockSelect(handle, i), - GlobalOrConstant::Constant(handle) => GlobalLookupKind::Constant(handle), - }, - entry_arg: None, - mutable: true, - }; - ctx.add_global(&k, lookup, self.program, body); - - self.program.global_variables.push((k, lookup)); - } - - Ok(true) - } - - // TODO: Accept layout arguments - fn parse_struct_declaration_list( - &mut self, - members: &mut Vec, - layout: StructLayout, - ) -> Result { - let mut span = 0; - let mut align = 0; - - loop { - // TODO: type_qualifier - - let (ty, mut meta) = self.parse_type_non_void()?; - let (name, end_meta) = self.expect_ident()?; - - meta = meta.union(&end_meta); - - let array_specifier = self.parse_array_specifier()?; - let ty = self.maybe_array(ty, array_specifier); - - self.expect(TokenValue::Semicolon)?; - - let info = offset::calculate_offset( - ty, - meta, - layout, - &mut self.program.module.types, - &self.program.module.constants, - )?; - - span = offset::align_up(span, info.align); - align = align.max(info.align); - - members.push(StructMember { - name: Some(name), - ty: info.ty, - binding: None, - offset: span, - }); - - span += info.span; - - if let TokenValue::RightBrace = self.expect_peek()?.value { - break; - } - } - - span = offset::align_up(span, align); - - Ok(span) - } - - fn parse_primary(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { - let mut token = self.bump()?; - - let (width, value) = match token.value { - TokenValue::IntConstant(int) => ( - (int.width / 8) as u8, - if int.signed { - ScalarValue::Sint(int.value as i64) - } else { - ScalarValue::Uint(int.value) - }, - ), - TokenValue::FloatConstant(float) => ( - (float.width / 8) as u8, - ScalarValue::Float(float.value as f64), - ), - TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)), - TokenValue::LeftParen => { - let expr = self.parse_expression(ctx, body)?; - let meta = self.expect(TokenValue::RightParen)?.meta; - - token.meta = token.meta.union(&meta); - - return Ok(expr); - } - _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ - TokenValue::LeftParen.into(), - ExpectedToken::IntLiteral, - ExpectedToken::FloatLiteral, - ExpectedToken::BoolLiteral, - ], - )) - } - }; - - let handle = self.program.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { width, value }, - }); - - Ok(ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Constant(handle), - meta: token.meta, - })) - } - - fn parse_function_call_args( - &mut self, - ctx: &mut Context, - body: &mut Block, - meta: &mut SourceMetadata, - ) -> Result>> { - let mut args = Vec::new(); - if let Some(token) = self.bump_if(TokenValue::RightParen) { - *meta = meta.union(&token.meta); - } else { - loop { - args.push(self.parse_assignment(ctx, body)?); - - let token = self.bump()?; - match token.value { - TokenValue::Comma => {} - TokenValue::RightParen => { - *meta = meta.union(&token.meta); - break; - } - _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![TokenValue::Comma.into(), TokenValue::RightParen.into()], - )) - } - } - } - } - - Ok(args) - } - - fn parse_postfix(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { - let mut base = match self.expect_peek()?.value { - TokenValue::Identifier(_) => { - let (name, mut meta) = self.expect_ident()?; - - let expr = if self.bump_if(TokenValue::LeftParen).is_some() { - let args = self.parse_function_call_args(ctx, body, &mut meta)?; - - let kind = match self.program.lookup_type.get(&name) { - Some(ty) => FunctionCallKind::TypeConstructor(*ty), - None => FunctionCallKind::Function(name), - }; - - HirExpr { - kind: HirExprKind::Call(FunctionCall { kind, args }), - meta, - } - } else { - let var = match self.program.lookup_variable(ctx, body, &name)? { - Some(var) => var, - None => return Err(ErrorKind::UnknownVariable(meta, name)), - }; - - HirExpr { - kind: HirExprKind::Variable(var), - meta, - } - }; - - ctx.hir_exprs.append(expr) - } - TokenValue::TypeName(_) => { - let Token { value, mut meta } = self.bump()?; - - let mut handle = if let TokenValue::TypeName(ty) = value { - self.program.module.types.fetch_or_append(ty) - } else { - unreachable!() - }; - - let maybe_size = self.parse_array_specifier()?; - - self.expect(TokenValue::LeftParen)?; - let args = self.parse_function_call_args(ctx, body, &mut meta)?; - - if let Some(array_size) = maybe_size { - let stride = self.program.module.types[handle] - .inner - .span(&self.program.module.constants); - - let size = match array_size { - ArraySize::Constant(size) => ArraySize::Constant(size), - ArraySize::Dynamic => { - let constant = - self.program.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(args.len() as i64), - }, - }); - - ArraySize::Constant(constant) - } - }; - - handle = self.program.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: handle, - size, - stride, - }, - }) - } - - ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Call(FunctionCall { - kind: FunctionCallKind::TypeConstructor(handle), - args, - }), - meta, - }) - } - _ => self.parse_primary(ctx, body)?, - }; - - while let TokenValue::LeftBracket - | TokenValue::Dot - | TokenValue::Increment - | TokenValue::Decrement = self.expect_peek()?.value - { - let Token { value, meta } = self.bump()?; - - match value { - TokenValue::LeftBracket => { - let index = self.parse_expression(ctx, body)?; - let end_meta = self.expect(TokenValue::RightBracket)?.meta; - - base = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Access { base, index }, - meta: meta.union(&end_meta), - }) - } - TokenValue::Dot => { - let (field, end_meta) = self.expect_ident()?; - - base = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Select { base, field }, - meta: meta.union(&end_meta), - }) - } - TokenValue::Increment => { - base = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::IncDec { - increment: true, - postfix: true, - expr: base, - }, - meta, - }) - } - TokenValue::Decrement => { - base = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::IncDec { - increment: false, - postfix: true, - expr: base, - }, - meta, - }) - } - _ => unreachable!(), - } - } - - Ok(base) - } - - fn parse_unary(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { - // TODO: prefix inc/dec - Ok(match self.expect_peek()?.value { - TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { - let Token { value, meta } = self.bump()?; - - let expr = self.parse_unary(ctx, body)?; - let end_meta = ctx.hir_exprs[expr].meta; - - let kind = match value { - TokenValue::Dash => HirExprKind::Unary { - op: UnaryOperator::Negate, - expr, - }, - TokenValue::Bang | TokenValue::Tilde => HirExprKind::Unary { - op: UnaryOperator::Not, - expr, - }, - _ => return Ok(expr), - }; - - ctx.hir_exprs.append(HirExpr { - kind, - meta: meta.union(&end_meta), - }) - } - TokenValue::Increment | TokenValue::Decrement => { - let Token { value, meta } = self.bump()?; - - let expr = self.parse_unary(ctx, body)?; - - ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::IncDec { - increment: match value { - TokenValue::Increment => true, - TokenValue::Decrement => false, - _ => unreachable!(), - }, - postfix: false, - expr, - }, - meta, - }) - } - _ => self.parse_postfix(ctx, body)?, - }) - } - - fn parse_binary( - &mut self, - ctx: &mut Context, - body: &mut Block, - passtrough: Option>, - min_bp: u8, - ) -> Result> { - let mut left = passtrough - .ok_or(ErrorKind::EndOfFile /* Dummy error */) - .or_else(|_| self.parse_unary(ctx, body))?; - let start_meta = ctx.hir_exprs[left].meta; - - while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek()?.value) { - if l_bp < min_bp { - break; - } - - let Token { value, .. } = self.bump()?; - - let right = self.parse_binary(ctx, body, None, r_bp)?; - let end_meta = ctx.hir_exprs[right].meta; - - left = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Binary { - left, - op: match value { - TokenValue::LogicalOr => BinaryOperator::LogicalOr, - TokenValue::LogicalXor => BinaryOperator::NotEqual, - TokenValue::LogicalAnd => BinaryOperator::LogicalAnd, - TokenValue::VerticalBar => BinaryOperator::InclusiveOr, - TokenValue::Caret => BinaryOperator::ExclusiveOr, - TokenValue::Ampersand => BinaryOperator::And, - TokenValue::Equal => BinaryOperator::Equal, - TokenValue::NotEqual => BinaryOperator::NotEqual, - TokenValue::GreaterEqual => BinaryOperator::GreaterEqual, - TokenValue::LessEqual => BinaryOperator::LessEqual, - TokenValue::LeftAngle => BinaryOperator::Less, - TokenValue::RightAngle => BinaryOperator::Greater, - TokenValue::LeftShift => BinaryOperator::ShiftLeft, - TokenValue::RightShift => BinaryOperator::ShiftRight, - TokenValue::Plus => BinaryOperator::Add, - TokenValue::Dash => BinaryOperator::Subtract, - TokenValue::Star => BinaryOperator::Multiply, - TokenValue::Slash => BinaryOperator::Divide, - TokenValue::Percent => BinaryOperator::Modulo, - _ => unreachable!(), - }, - right, - }, - meta: start_meta.union(&end_meta), - }) - } - - Ok(left) - } - - fn parse_conditional( - &mut self, - ctx: &mut Context, - body: &mut Block, - passtrough: Option>, - ) -> Result> { - let mut condition = self.parse_binary(ctx, body, passtrough, 0)?; - let start_meta = ctx.hir_exprs[condition].meta; - - if self.bump_if(TokenValue::Question).is_some() { - let accept = self.parse_expression(ctx, body)?; - self.expect(TokenValue::Colon)?; - let reject = self.parse_assignment(ctx, body)?; - let end_meta = ctx.hir_exprs[reject].meta; - - condition = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Conditional { - condition, - accept, - reject, - }, - meta: start_meta.union(&end_meta), - }) - } - - Ok(condition) - } - - fn parse_assignment(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { - let tgt = self.parse_unary(ctx, body)?; - let start_meta = ctx.hir_exprs[tgt].meta; - - Ok(match self.expect_peek()?.value { - TokenValue::Assign => { - self.bump()?; - let value = self.parse_assignment(ctx, body)?; - let end_meta = ctx.hir_exprs[value].meta; - - ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Assign { tgt, value }, - meta: start_meta.union(&end_meta), - }) - } - TokenValue::OrAssign - | TokenValue::AndAssign - | TokenValue::AddAssign - | TokenValue::DivAssign - | TokenValue::ModAssign - | TokenValue::SubAssign - | TokenValue::MulAssign - | TokenValue::LeftShiftAssign - | TokenValue::RightShiftAssign - | TokenValue::XorAssign => { - let token = self.bump()?; - let right = self.parse_assignment(ctx, body)?; - let end_meta = ctx.hir_exprs[right].meta; - - let value = ctx.hir_exprs.append(HirExpr { - meta: start_meta.union(&end_meta), - kind: HirExprKind::Binary { - left: tgt, - op: match token.value { - TokenValue::OrAssign => BinaryOperator::InclusiveOr, - TokenValue::AndAssign => BinaryOperator::And, - TokenValue::AddAssign => BinaryOperator::Add, - TokenValue::DivAssign => BinaryOperator::Divide, - TokenValue::ModAssign => BinaryOperator::Modulo, - TokenValue::SubAssign => BinaryOperator::Subtract, - TokenValue::MulAssign => BinaryOperator::Multiply, - TokenValue::LeftShiftAssign => BinaryOperator::ShiftLeft, - TokenValue::RightShiftAssign => BinaryOperator::ShiftRight, - TokenValue::XorAssign => BinaryOperator::ExclusiveOr, - _ => unreachable!(), - }, - right, - }, - }); - - ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Assign { tgt, value }, - meta: start_meta.union(&end_meta), - }) - } - _ => self.parse_conditional(ctx, body, Some(tgt))?, - }) - } - - fn parse_expression(&mut self, ctx: &mut Context, body: &mut Block) -> Result> { - let mut expr = self.parse_assignment(ctx, body)?; - - while let TokenValue::Comma = self.expect_peek()?.value { - self.bump()?; - expr = self.parse_assignment(ctx, body)?; - } - - Ok(expr) - } - - fn parse_statement(&mut self, ctx: &mut Context, body: &mut Block) -> Result<()> { - // TODO: This prevents snippets like the following from working - // ```glsl - // vec4(1.0); - // ``` - // But this would require us to add lookahead to also support - // declarations and since this statement is very unlikely and most - // likely an error, for now we don't support it - if self.peek_type_name() || self.peek_type_qualifier() { - self.parse_declaration(ctx, body, false)?; - return Ok(()); - } - - match self.expect_peek()?.value { - TokenValue::Continue => { - self.bump()?; - body.push(Statement::Continue); - self.expect(TokenValue::Semicolon)?; - } - TokenValue::Break => { - self.bump()?; - body.push(Statement::Break); - self.expect(TokenValue::Semicolon)?; - } - TokenValue::Return => { - self.bump()?; - let value = match self.expect_peek()?.value { - TokenValue::Semicolon => { - self.bump()?; - None - } - _ => { - // TODO: Implicit conversions - let expr = self.parse_expression(ctx, body)?; - self.expect(TokenValue::Semicolon)?; - Some(ctx.lower_expect(self.program, expr, false, body)?.0) - } - }; - - ctx.emit_flush(body); - ctx.emit_start(); - - body.push(Statement::Return { value }) - } - TokenValue::Discard => { - self.bump()?; - body.push(Statement::Kill); - self.expect(TokenValue::Semicolon)?; - } - TokenValue::If => { - self.bump()?; - - self.expect(TokenValue::LeftParen)?; - let condition = { - let expr = self.parse_expression(ctx, body)?; - ctx.lower_expect(self.program, expr, false, body)?.0 - }; - self.expect(TokenValue::RightParen)?; - - ctx.emit_flush(body); - ctx.emit_start(); - - let mut accept = Block::new(); - self.parse_statement(ctx, &mut accept)?; - - let mut reject = Block::new(); - if self.bump_if(TokenValue::Else).is_some() { - self.parse_statement(ctx, &mut reject)?; - } - - body.push(Statement::If { - condition, - accept, - reject, - }); - } - TokenValue::Switch => { - self.bump()?; - - self.expect(TokenValue::LeftParen)?; - // TODO: Implicit conversions - let selector = { - let expr = self.parse_expression(ctx, body)?; - ctx.lower_expect(self.program, expr, false, body)?.0 - }; - self.expect(TokenValue::RightParen)?; - - ctx.emit_flush(body); - ctx.emit_start(); - - let mut cases = Vec::new(); - let mut default = Block::new(); - - self.expect(TokenValue::LeftBrace)?; - loop { - match self.expect_peek()?.value { - TokenValue::Case => { - self.bump()?; - let value = { - let expr = self.parse_expression(ctx, body)?; - let (root, meta) = - ctx.lower_expect(self.program, expr, false, body)?; - let constant = self.program.solve_constant(ctx, root, meta)?; - - match self.program.module.constants[constant].inner { - ConstantInner::Scalar { - value: ScalarValue::Sint(int), - .. - } => int as i32, - ConstantInner::Scalar { - value: ScalarValue::Uint(int), - .. - } => int as i32, - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Case values can only be integers".into(), - )) - } - } - }; - - self.expect(TokenValue::Colon)?; - - let mut body = Block::new(); - - loop { - match self.expect_peek()?.value { - TokenValue::Case - | TokenValue::Default - | TokenValue::RightBrace => break, - _ => self.parse_statement(ctx, &mut body)?, - } - } - - let mut fall_through = true; - - for (i, stmt) in body.iter().enumerate() { - if let Statement::Break = *stmt { - fall_through = false; - body.drain(i..); - break; - } - } - - cases.push(SwitchCase { - value, - body, - fall_through, - }) - } - TokenValue::Default => { - let Token { meta, .. } = self.bump()?; - self.expect(TokenValue::Colon)?; - - if !default.is_empty() { - return Err(ErrorKind::SemanticError( - meta, - "Can only have one default case per switch statement".into(), - )); - } - - loop { - match self.expect_peek()?.value { - TokenValue::Case | TokenValue::RightBrace => break, - _ => self.parse_statement(ctx, &mut default)?, - } - } - - for (i, stmt) in default.iter().enumerate() { - if let Statement::Break = *stmt { - default.drain(i..); - break; - } - } - } - TokenValue::RightBrace => { - self.bump()?; - break; - } - _ => { - return Err(ErrorKind::InvalidToken( - self.bump()?, - vec![ - TokenValue::Case.into(), - TokenValue::Default.into(), - TokenValue::RightBrace.into(), - ], - )) - } - } - } - - body.push(Statement::Switch { - selector, - cases, - default, - }); - } - TokenValue::While => { - self.bump()?; - - let mut loop_body = Block::new(); - - self.expect(TokenValue::LeftParen)?; - let root = self.parse_expression(ctx, &mut loop_body)?; - self.expect(TokenValue::RightParen)?; - - let expr = ctx - .lower_expect(self.program, root, false, &mut loop_body)? - .0; - let condition = ctx.add_expression( - Expression::Unary { - op: UnaryOperator::Not, - expr, - }, - &mut loop_body, - ); - - ctx.emit_flush(&mut loop_body); - ctx.emit_start(); - - loop_body.push(Statement::If { - condition, - accept: vec![Statement::Break], - reject: Block::new(), - }); - - self.parse_statement(ctx, &mut loop_body)?; - - body.push(Statement::Loop { - body: loop_body, - continuing: Block::new(), - }) - } - TokenValue::Do => { - self.bump()?; - - let mut loop_body = Block::new(); - self.parse_statement(ctx, &mut loop_body)?; - - self.expect(TokenValue::While)?; - self.expect(TokenValue::LeftParen)?; - let root = self.parse_expression(ctx, &mut loop_body)?; - self.expect(TokenValue::RightParen)?; - - let expr = ctx - .lower_expect(self.program, root, false, &mut loop_body)? - .0; - let condition = ctx.add_expression( - Expression::Unary { - op: UnaryOperator::Not, - expr, - }, - &mut loop_body, - ); - - ctx.emit_flush(&mut loop_body); - ctx.emit_start(); - - loop_body.push(Statement::If { - condition, - accept: vec![Statement::Break], - reject: Block::new(), - }); - - body.push(Statement::Loop { - body: loop_body, - continuing: Block::new(), - }) - } - TokenValue::For => { - self.bump()?; - - ctx.push_scope(); - self.expect(TokenValue::LeftParen)?; - - if self.bump_if(TokenValue::Semicolon).is_none() { - if self.peek_type_name() || self.peek_type_qualifier() { - self.parse_declaration(ctx, body, false)?; - } else { - let expr = self.parse_expression(ctx, body)?; - ctx.lower(self.program, expr, false, body)?; - self.expect(TokenValue::Semicolon)?; - } - } - - let (mut block, mut continuing) = (Block::new(), Block::new()); - - if self.bump_if(TokenValue::Semicolon).is_none() { - let expr = if self.peek_type_name() || self.peek_type_qualifier() { - let qualifiers = self.parse_type_qualifiers()?; - let (ty, meta) = self.parse_type_non_void()?; - let name = self.expect_ident()?.0; - - self.expect(TokenValue::Assign)?; - - let (value, end_meta) = self.parse_initializer(ty, ctx, &mut block)?; - - let decl = VarDeclaration { - qualifiers: &qualifiers, - ty, - name: Some(name), - init: None, - meta: meta.union(&end_meta), - }; - - let pointer = self.program.add_local_var(ctx, &mut block, decl)?; - - ctx.emit_flush(&mut block); - ctx.emit_start(); - - block.push(Statement::Store { pointer, value }); - - value - } else { - let root = self.parse_expression(ctx, &mut block)?; - ctx.lower_expect(self.program, root, false, &mut block)?.0 - }; - - let condition = ctx.add_expression( - Expression::Unary { - op: UnaryOperator::Not, - expr, - }, - &mut block, - ); - - ctx.emit_flush(&mut block); - ctx.emit_start(); - - block.push(Statement::If { - condition, - accept: vec![Statement::Break], - reject: Block::new(), - }); - - self.expect(TokenValue::Semicolon)?; - } - - match self.expect_peek()?.value { - TokenValue::RightParen => {} - _ => { - let rest = self.parse_expression(ctx, &mut continuing)?; - ctx.lower(self.program, rest, false, &mut continuing)?; - } - } - - self.expect(TokenValue::RightParen)?; - - self.parse_statement(ctx, &mut block)?; - - body.push(Statement::Loop { - body: block, - continuing, - }); - - ctx.remove_current_scope(); - } - TokenValue::LeftBrace => { - self.bump()?; - - let mut block = Block::new(); - ctx.push_scope(); - - self.parse_compound_statement(ctx, &mut block)?; - - ctx.remove_current_scope(); - body.push(Statement::Block(block)); - } - TokenValue::Plus - | TokenValue::Dash - | TokenValue::Bang - | TokenValue::Tilde - | TokenValue::LeftParen - | TokenValue::Identifier(_) - | TokenValue::TypeName(_) - | TokenValue::IntConstant(_) - | TokenValue::BoolConstant(_) - | TokenValue::FloatConstant(_) => { - let expr = self.parse_expression(ctx, body)?; - ctx.lower(self.program, expr, false, body)?; - self.expect(TokenValue::Semicolon)?; - } - TokenValue::Semicolon => { - self.bump()?; - } - _ => {} - } - - Ok(()) - } - - fn parse_compound_statement(&mut self, ctx: &mut Context, body: &mut Block) -> Result<()> { - loop { - if self.bump_if(TokenValue::RightBrace).is_some() { - break; - } - - self.parse_statement(ctx, body)?; - } - - Ok(()) - } - - fn parse_function_args( - &mut self, - context: &mut Context, - body: &mut Block, - parameters: &mut Vec>, - ) -> Result<()> { - loop { - if self.peek_type_name() || self.peek_parameter_qualifier() { - let qualifier = self.parse_parameter_qualifier(); - let ty = self.parse_type_non_void()?.0; - - match self.expect_peek()?.value { - TokenValue::Comma => { - self.bump()?; - context.add_function_arg( - &mut self.program, - parameters, - body, - None, - ty, - qualifier, - ); - continue; - } - TokenValue::Identifier(_) => { - let name = self.expect_ident()?.0; - - let size = self.parse_array_specifier()?; - let ty = self.maybe_array(ty, size); - - context.add_function_arg( - &mut self.program, - parameters, - body, - Some(name), - ty, - qualifier, - ); - - if self.bump_if(TokenValue::Comma).is_some() { - continue; - } - - break; - } - _ => break, - } - } - - break; - } - - Ok(()) + Ok((parser.solve_constant(&ctx, root, meta)?, meta)) } } -struct DeclarationContext<'ctx, 'fun> { +pub struct DeclarationContext<'ctx> { qualifiers: Vec<(TypeQualifier, SourceMetadata)>, external: bool, - ctx: &'ctx mut Context<'fun>, + ctx: &'ctx mut Context, body: &'ctx mut Block, } -impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { +impl<'ctx> DeclarationContext<'ctx> { fn add_var( &mut self, - program: &mut Program, + parser: &mut Parser, ty: Handle, name: String, init: Option>, @@ -1981,14 +208,14 @@ impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { match self.external { true => { - let global = program.add_global_var(self.ctx, self.body, decl)?; + let global = parser.add_global_var(self.ctx, self.body, decl)?; let expr = match global { GlobalOrConstant::Global(handle) => Expression::GlobalVariable(handle), GlobalOrConstant::Constant(handle) => Expression::Constant(handle), }; Ok(self.ctx.add_expression(expr, self.body)) } - false => program.add_local_var(self.ctx, self.body, decl), + false => parser.add_local_var(self.ctx, self.body, decl), } } @@ -1997,23 +224,3 @@ impl<'ctx, 'fun> DeclarationContext<'ctx, 'fun> { self.ctx.emit_start() } } - -fn binding_power(value: &TokenValue) -> Option<(u8, u8)> { - Some(match *value { - TokenValue::LogicalOr => (1, 2), - TokenValue::LogicalXor => (3, 4), - TokenValue::LogicalAnd => (5, 6), - TokenValue::VerticalBar => (7, 8), - TokenValue::Caret => (9, 10), - TokenValue::Ampersand => (11, 12), - TokenValue::Equal | TokenValue::NotEqual => (13, 14), - TokenValue::GreaterEqual - | TokenValue::LessEqual - | TokenValue::LeftAngle - | TokenValue::RightAngle => (15, 16), - TokenValue::LeftShift | TokenValue::RightShift => (17, 18), - TokenValue::Plus | TokenValue::Dash => (19, 20), - TokenValue::Star | TokenValue::Slash | TokenValue::Percent => (21, 22), - _ => return None, - }) -} diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs new file mode 100644 index 000000000..f74cd15ae --- /dev/null +++ b/src/front/glsl/parser/declarations.rs @@ -0,0 +1,581 @@ +use crate::{ + front::glsl::{ + ast::{ + GlobalLookup, GlobalLookupKind, Precision, StorageQualifier, StructLayout, + TypeQualifier, + }, + context::Context, + error::ExpectedToken, + offset, + token::TokenValue, + types::scalar_components, + variables::{GlobalOrConstant, VarDeclaration}, + ErrorKind, Parser, SourceMetadata, Token, + }, + Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StorageClass, StructMember, + Type, TypeInner, +}; + +use super::{DeclarationContext, ParsingContext, Result}; + +impl<'source> ParsingContext<'source> { + pub fn parse_external_declaration( + &mut self, + parser: &mut Parser, + global_ctx: &mut Context, + global_body: &mut Block, + ) -> Result<()> { + if !self.parse_declaration(parser, global_ctx, global_body, true)? { + let token = self.bump(parser)?; + match token.value { + TokenValue::Semicolon if parser.meta.version == 460 => Ok(()), + _ => { + let expected = match parser.meta.version { + 460 => vec![TokenValue::Semicolon.into(), ExpectedToken::Eof], + _ => vec![ExpectedToken::Eof], + }; + Err(ErrorKind::InvalidToken(token, expected)) + } + } + } else { + Ok(()) + } + } + + pub fn parse_initializer( + &mut self, + parser: &mut Parser, + ty: Handle, + ctx: &mut Context, + body: &mut Block, + ) -> Result<(Handle, SourceMetadata)> { + // initializer: + // assignment_expression + // LEFT_BRACE initializer_list RIGHT_BRACE + // LEFT_BRACE initializer_list COMMA RIGHT_BRACE + // + // initializer_list: + // initializer + // initializer_list COMMA initializer + if let Some(Token { mut meta, .. }) = self.bump_if(parser, TokenValue::LeftBrace) { + // initializer_list + let mut components = Vec::new(); + loop { + // TODO: Change type + components.push(self.parse_initializer(parser, ty, ctx, body)?.0); + + let token = self.bump(parser)?; + match token.value { + TokenValue::Comma => { + if let Some(Token { meta: end_meta, .. }) = + self.bump_if(parser, TokenValue::RightBrace) + { + meta = meta.union(&end_meta); + break; + } + } + TokenValue::RightBrace => { + meta = meta.union(&token.meta); + break; + } + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![TokenValue::Comma.into(), TokenValue::RightBrace.into()], + )) + } + } + } + + Ok(( + ctx.add_expression(Expression::Compose { ty, components }, body), + meta, + )) + } else { + let expr = self.parse_assignment(parser, ctx, body)?; + let (mut init, init_meta) = ctx.lower_expect(parser, expr, false, body)?; + + let scalar_components = scalar_components(&parser.module.types[ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(parser, &mut init, init_meta, kind, width)?; + } + + Ok((init, init_meta)) + } + } + + // Note: caller preparsed the type and qualifiers + // Note: caller skips this if the fallthrough token is not expected to be consumed here so this + // produced Error::InvalidToken if it isn't consumed + pub fn parse_init_declarator_list( + &mut self, + parser: &mut Parser, + ty: Handle, + mut fallthrough: Option, + ctx: &mut DeclarationContext, + ) -> Result<()> { + // init_declarator_list: + // single_declaration + // init_declarator_list COMMA IDENTIFIER + // init_declarator_list COMMA IDENTIFIER array_specifier + // init_declarator_list COMMA IDENTIFIER array_specifier EQUAL initializer + // init_declarator_list COMMA IDENTIFIER EQUAL initializer + // + // single_declaration: + // fully_specified_type + // fully_specified_type IDENTIFIER + // fully_specified_type IDENTIFIER array_specifier + // fully_specified_type IDENTIFIER array_specifier EQUAL initializer + // fully_specified_type IDENTIFIER EQUAL initializer + + // Consume any leading comma, e.g. this is valid: `float, a=1;` + if fallthrough + .as_ref() + .or_else(|| self.peek(parser)) + .filter(|t| t.value == TokenValue::Comma) + .is_some() + { + fallthrough.take().or_else(|| self.next(parser)); + } + + loop { + let token = fallthrough + .take() + .ok_or(ErrorKind::EndOfFile) + .or_else(|_| self.bump(parser))?; + let name = match token.value { + TokenValue::Semicolon => break, + TokenValue::Identifier(name) => name, + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], + )) + } + }; + let mut meta = token.meta; + + // array_specifier + // array_specifier EQUAL initializer + // EQUAL initializer + + // parse an array specifier if it exists + // NOTE: unlike other parse methods this one doesn't expect an array specifier and + // returns Ok(None) rather than an error if there is not one + let array_specifier = self.parse_array_specifier(parser)?; + let ty = parser.maybe_array(ty, array_specifier); + + let init = self + .bump_if(parser, TokenValue::Assign) + .map::, _>(|_| { + let (mut expr, init_meta) = + self.parse_initializer(parser, ty, ctx.ctx, ctx.body)?; + + let scalar_components = scalar_components(&parser.module.types[ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.ctx + .implicit_conversion(parser, &mut expr, init_meta, kind, width)?; + } + + meta = meta.union(&init_meta); + + Ok((expr, init_meta)) + }) + .transpose()?; + + // TODO: Should we try to make constants here? + // This is mostly a hack because we don't yet support adding + // bodies to entry points for variable initialization + let maybe_constant = + init.and_then(|(root, meta)| parser.solve_constant(ctx.ctx, root, meta).ok()); + + let pointer = ctx.add_var(parser, ty, name, maybe_constant, meta)?; + + if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) { + ctx.flush_expressions(); + ctx.body.push(Statement::Store { pointer, value }); + } + + let token = self.bump(parser)?; + match token.value { + TokenValue::Semicolon => break, + TokenValue::Comma => {} + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![TokenValue::Comma.into(), TokenValue::Semicolon.into()], + )) + } + } + } + + Ok(()) + } + + /// `external` whether or not we are in a global or local context + pub fn parse_declaration( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + external: bool, + ) -> Result { + //declaration: + // function_prototype SEMICOLON + // + // init_declarator_list SEMICOLON + // PRECISION precision_qualifier type_specifier SEMICOLON + // + // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE SEMICOLON + // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER SEMICOLON + // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER array_specifier SEMICOLON + // type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON + // type_qualifier IDENTIFIER identifier_list SEMICOLON + + if self.peek_type_qualifier(parser) || self.peek_type_name(parser) { + let qualifiers = self.parse_type_qualifiers(parser)?; + + if self.peek_type_name(parser) { + // This branch handles variables and function prototypes and if + // external is true also function definitions + let (ty, mut meta) = self.parse_type(parser)?; + + let token = self.bump(parser)?; + let token_fallthrough = match token.value { + TokenValue::Identifier(name) => match self.expect_peek(parser)?.value { + TokenValue::LeftParen => { + // This branch handles function definition and prototypes + self.bump(parser)?; + + let result = ty.map(|ty| FunctionResult { ty, binding: None }); + let mut body = Block::new(); + + let mut context = Context::new(parser, &mut body); + + self.parse_function_args(parser, &mut context, &mut body)?; + + let end_meta = self.expect(parser, TokenValue::RightParen)?.meta; + meta = meta.union(&end_meta); + + let token = self.bump(parser)?; + return match token.value { + TokenValue::Semicolon => { + // This branch handles function prototypes + parser.add_prototype(context, name, result, meta)?; + + Ok(true) + } + TokenValue::LeftBrace if external => { + // This branch handles function definitions + // as you can see by the guard this branch + // only happens if external is also true + + // parse the body + self.parse_compound_statement(parser, &mut context, &mut body)?; + + parser.add_function(context, name, result, body, meta)?; + + Ok(true) + } + _ if external => Err(ErrorKind::InvalidToken( + token, + vec![ + TokenValue::LeftBrace.into(), + TokenValue::Semicolon.into(), + ], + )), + _ => Err(ErrorKind::InvalidToken( + token, + vec![TokenValue::Semicolon.into()], + )), + }; + } + // Pass the token to the init_declator_list parser + _ => Token { + value: TokenValue::Identifier(name), + meta: token.meta, + }, + }, + // Pass the token to the init_declator_list parser + _ => token, + }; + + // If program execution has reached here then this will be a + // init_declarator_list + // token_falltrough will have a token that was already bumped + if let Some(ty) = ty { + let mut ctx = DeclarationContext { + qualifiers, + external, + ctx, + body, + }; + + self.parse_init_declarator_list(parser, ty, Some(token_fallthrough), &mut ctx)?; + } else { + return Err(ErrorKind::SemanticError( + meta, + "Declaration cannot have void type".into(), + )); + } + + Ok(true) + } else { + // This branch handles struct definitions and modifiers like + // ```glsl + // layout(early_fragment_tests); + // ``` + let token = self.bump(parser)?; + match token.value { + TokenValue::Identifier(ty_name) => { + if self.bump_if(parser, TokenValue::LeftBrace).is_some() { + self.parse_block_declaration( + parser, + ctx, + body, + &qualifiers, + ty_name, + token.meta, + ) + } else { + //TODO: declaration + // type_qualifier IDENTIFIER SEMICOLON + // type_qualifier IDENTIFIER identifier_list SEMICOLON + Err(ErrorKind::NotImplemented(token.meta, "variable qualifier")) + } + } + TokenValue::Semicolon => { + for &(ref qualifier, meta) in qualifiers.iter() { + match *qualifier { + TypeQualifier::WorkGroupSize(i, value) => { + parser.meta.workgroup_size[i] = value + } + TypeQualifier::EarlyFragmentTests => { + parser.meta.early_fragment_tests = true; + } + TypeQualifier::StorageQualifier(_) => { + // TODO: Maybe add some checks here + // This is needed because of cases like + // layout(early_fragment_tests) in; + } + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Qualifier not supported as standalone".into(), + )); + } + } + } + + Ok(true) + } + _ => Err(ErrorKind::InvalidToken( + token, + vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], + )), + } + } + } else { + match self.peek(parser).map(|t| &t.value) { + Some(&TokenValue::Precision) => { + // PRECISION precision_qualifier type_specifier SEMICOLON + self.bump(parser)?; + + let token = self.bump(parser)?; + let _ = match token.value { + TokenValue::PrecisionQualifier(p) => p, + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ + TokenValue::PrecisionQualifier(Precision::High).into(), + TokenValue::PrecisionQualifier(Precision::Medium).into(), + TokenValue::PrecisionQualifier(Precision::Low).into(), + ], + )) + } + }; + + let (ty, meta) = self.parse_type_non_void(parser)?; + + match parser.module.types[ty].inner { + TypeInner::Scalar { + kind: ScalarKind::Float, + .. + } + | TypeInner::Scalar { + kind: ScalarKind::Sint, + .. + } => {} + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Precision statement can only work on floats and ints".into(), + )) + } + } + + self.expect(parser, TokenValue::Semicolon)?; + + Ok(true) + } + _ => Ok(false), + } + } + } + + pub fn parse_block_declaration( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + qualifiers: &[(TypeQualifier, SourceMetadata)], + ty_name: String, + mut meta: SourceMetadata, + ) -> Result { + let mut storage = None; + let mut layout = None; + + for &(ref qualifier, _) in qualifiers { + match *qualifier { + TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { + storage = Some(c) + } + TypeQualifier::Layout(l) => layout = Some(l), + _ => continue, + } + } + + let layout = match (layout, storage) { + (Some(layout), _) => layout, + (None, Some(StorageClass::Storage { .. })) => StructLayout::Std430, + _ => StructLayout::Std140, + }; + + let mut members = Vec::new(); + let span = self.parse_struct_declaration_list(parser, &mut members, layout)?; + self.expect(parser, TokenValue::RightBrace)?; + + let mut ty = parser.module.types.append(Type { + name: Some(ty_name), + inner: TypeInner::Struct { + top_level: true, + members: members.clone(), + span, + }, + }); + + let token = self.bump(parser)?; + let name = match token.value { + TokenValue::Semicolon => None, + TokenValue::Identifier(name) => { + if let Some(size) = self.parse_array_specifier(parser)? { + ty = parser.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: ty, + size, + stride: parser.module.types[ty].inner.span(&parser.module.constants), + }, + }); + } + + self.expect(parser, TokenValue::Semicolon)?; + + Some(name) + } + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], + )) + } + }; + meta = meta.union(&token.meta); + + let global = parser.add_global_var( + ctx, + body, + VarDeclaration { + qualifiers, + ty, + name, + init: None, + meta, + }, + )?; + + for (i, k) in members + .into_iter() + .enumerate() + .filter_map(|(i, m)| m.name.map(|s| (i as u32, s))) + { + let lookup = GlobalLookup { + kind: match global { + GlobalOrConstant::Global(handle) => GlobalLookupKind::BlockSelect(handle, i), + GlobalOrConstant::Constant(handle) => GlobalLookupKind::Constant(handle), + }, + entry_arg: None, + mutable: true, + }; + ctx.add_global(parser, &k, lookup, body); + + parser.global_variables.push((k, lookup)); + } + + Ok(true) + } + + // TODO: Accept layout arguments + pub fn parse_struct_declaration_list( + &mut self, + parser: &mut Parser, + members: &mut Vec, + layout: StructLayout, + ) -> Result { + let mut span = 0; + let mut align = 0; + + loop { + // TODO: type_qualifier + + let (ty, mut meta) = self.parse_type_non_void(parser)?; + let (name, end_meta) = self.expect_ident(parser)?; + + meta = meta.union(&end_meta); + + let array_specifier = self.parse_array_specifier(parser)?; + let ty = parser.maybe_array(ty, array_specifier); + + self.expect(parser, TokenValue::Semicolon)?; + + let info = offset::calculate_offset( + ty, + meta, + layout, + &mut parser.module.types, + &parser.module.constants, + )?; + + span = offset::align_up(span, info.align); + align = align.max(info.align); + + members.push(StructMember { + name: Some(name), + ty: info.ty, + binding: None, + offset: span, + }); + + span += info.span; + + if let TokenValue::RightBrace = self.expect_peek(parser)?.value { + break; + } + } + + span = offset::align_up(span, align); + + Ok(span) + } +} diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs new file mode 100644 index 000000000..8f119eaaa --- /dev/null +++ b/src/front/glsl/parser/expressions.rs @@ -0,0 +1,486 @@ +use crate::{ + front::glsl::{ + ast::{FunctionCall, FunctionCallKind, HirExpr, HirExprKind}, + context::Context, + error::{ErrorKind, ExpectedToken}, + parser::ParsingContext, + token::{Token, TokenValue}, + Parser, Result, SourceMetadata, + }, + ArraySize, BinaryOperator, Block, Constant, ConstantInner, Handle, ScalarValue, Type, + TypeInner, UnaryOperator, +}; + +impl<'source> ParsingContext<'source> { + pub fn parse_primary( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + ) -> Result> { + let mut token = self.bump(parser)?; + + let (width, value) = match token.value { + TokenValue::IntConstant(int) => ( + (int.width / 8) as u8, + if int.signed { + ScalarValue::Sint(int.value as i64) + } else { + ScalarValue::Uint(int.value) + }, + ), + TokenValue::FloatConstant(float) => ( + (float.width / 8) as u8, + ScalarValue::Float(float.value as f64), + ), + TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)), + TokenValue::LeftParen => { + let expr = self.parse_expression(parser, ctx, body)?; + let meta = self.expect(parser, TokenValue::RightParen)?.meta; + + token.meta = token.meta.union(&meta); + + return Ok(expr); + } + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ + TokenValue::LeftParen.into(), + ExpectedToken::IntLiteral, + ExpectedToken::FloatLiteral, + ExpectedToken::BoolLiteral, + ], + )) + } + }; + + let handle = parser.module.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { width, value }, + }); + + Ok(ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Constant(handle), + meta: token.meta, + })) + } + + pub fn parse_function_call_args( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + meta: &mut SourceMetadata, + ) -> Result>> { + let mut args = Vec::new(); + if let Some(token) = self.bump_if(parser, TokenValue::RightParen) { + *meta = meta.union(&token.meta); + } else { + loop { + args.push(self.parse_assignment(parser, ctx, body)?); + + let token = self.bump(parser)?; + match token.value { + TokenValue::Comma => {} + TokenValue::RightParen => { + *meta = meta.union(&token.meta); + break; + } + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![TokenValue::Comma.into(), TokenValue::RightParen.into()], + )) + } + } + } + } + + Ok(args) + } + + pub fn parse_postfix( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + ) -> Result> { + let mut base = match self.expect_peek(parser)?.value { + TokenValue::Identifier(_) => { + let (name, mut meta) = self.expect_ident(parser)?; + + let expr = if self.bump_if(parser, TokenValue::LeftParen).is_some() { + let args = self.parse_function_call_args(parser, ctx, body, &mut meta)?; + + let kind = match parser.lookup_type.get(&name) { + Some(ty) => FunctionCallKind::TypeConstructor(*ty), + None => FunctionCallKind::Function(name), + }; + + HirExpr { + kind: HirExprKind::Call(FunctionCall { kind, args }), + meta, + } + } else { + let var = match parser.lookup_variable(ctx, body, &name)? { + Some(var) => var, + None => return Err(ErrorKind::UnknownVariable(meta, name)), + }; + + HirExpr { + kind: HirExprKind::Variable(var), + meta, + } + }; + + ctx.hir_exprs.append(expr) + } + TokenValue::TypeName(_) => { + let Token { value, mut meta } = self.bump(parser)?; + + let mut handle = if let TokenValue::TypeName(ty) = value { + parser.module.types.fetch_or_append(ty) + } else { + unreachable!() + }; + + let maybe_size = self.parse_array_specifier(parser)?; + + self.expect(parser, TokenValue::LeftParen)?; + let args = self.parse_function_call_args(parser, ctx, body, &mut meta)?; + + if let Some(array_size) = maybe_size { + let stride = parser.module.types[handle] + .inner + .span(&parser.module.constants); + + let size = match array_size { + ArraySize::Constant(size) => ArraySize::Constant(size), + ArraySize::Dynamic => { + let constant = parser.module.constants.fetch_or_append(Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(args.len() as i64), + }, + }); + + ArraySize::Constant(constant) + } + }; + + handle = parser.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base: handle, + size, + stride, + }, + }) + } + + ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Call(FunctionCall { + kind: FunctionCallKind::TypeConstructor(handle), + args, + }), + meta, + }) + } + _ => self.parse_primary(parser, ctx, body)?, + }; + + while let TokenValue::LeftBracket + | TokenValue::Dot + | TokenValue::Increment + | TokenValue::Decrement = self.expect_peek(parser)?.value + { + let Token { value, meta } = self.bump(parser)?; + + match value { + TokenValue::LeftBracket => { + let index = self.parse_expression(parser, ctx, body)?; + let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; + + base = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Access { base, index }, + meta: meta.union(&end_meta), + }) + } + TokenValue::Dot => { + let (field, end_meta) = self.expect_ident(parser)?; + + base = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Select { base, field }, + meta: meta.union(&end_meta), + }) + } + TokenValue::Increment => { + base = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::IncDec { + increment: true, + postfix: true, + expr: base, + }, + meta, + }) + } + TokenValue::Decrement => { + base = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::IncDec { + increment: false, + postfix: true, + expr: base, + }, + meta, + }) + } + _ => unreachable!(), + } + } + + Ok(base) + } + + pub fn parse_unary( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + ) -> Result> { + // TODO: prefix inc/dec + Ok(match self.expect_peek(parser)?.value { + TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { + let Token { value, meta } = self.bump(parser)?; + + let expr = self.parse_unary(parser, ctx, body)?; + let end_meta = ctx.hir_exprs[expr].meta; + + let kind = match value { + TokenValue::Dash => HirExprKind::Unary { + op: UnaryOperator::Negate, + expr, + }, + TokenValue::Bang | TokenValue::Tilde => HirExprKind::Unary { + op: UnaryOperator::Not, + expr, + }, + _ => return Ok(expr), + }; + + ctx.hir_exprs.append(HirExpr { + kind, + meta: meta.union(&end_meta), + }) + } + TokenValue::Increment | TokenValue::Decrement => { + let Token { value, meta } = self.bump(parser)?; + + let expr = self.parse_unary(parser, ctx, body)?; + + ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::IncDec { + increment: match value { + TokenValue::Increment => true, + TokenValue::Decrement => false, + _ => unreachable!(), + }, + postfix: false, + expr, + }, + meta, + }) + } + _ => self.parse_postfix(parser, ctx, body)?, + }) + } + + pub fn parse_binary( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + passtrough: Option>, + min_bp: u8, + ) -> Result> { + let mut left = passtrough + .ok_or(ErrorKind::EndOfFile /* Dummy error */) + .or_else(|_| self.parse_unary(parser, ctx, body))?; + let start_meta = ctx.hir_exprs[left].meta; + + while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(parser)?.value) { + if l_bp < min_bp { + break; + } + + let Token { value, .. } = self.bump(parser)?; + + let right = self.parse_binary(parser, ctx, body, None, r_bp)?; + let end_meta = ctx.hir_exprs[right].meta; + + left = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Binary { + left, + op: match value { + TokenValue::LogicalOr => BinaryOperator::LogicalOr, + TokenValue::LogicalXor => BinaryOperator::NotEqual, + TokenValue::LogicalAnd => BinaryOperator::LogicalAnd, + TokenValue::VerticalBar => BinaryOperator::InclusiveOr, + TokenValue::Caret => BinaryOperator::ExclusiveOr, + TokenValue::Ampersand => BinaryOperator::And, + TokenValue::Equal => BinaryOperator::Equal, + TokenValue::NotEqual => BinaryOperator::NotEqual, + TokenValue::GreaterEqual => BinaryOperator::GreaterEqual, + TokenValue::LessEqual => BinaryOperator::LessEqual, + TokenValue::LeftAngle => BinaryOperator::Less, + TokenValue::RightAngle => BinaryOperator::Greater, + TokenValue::LeftShift => BinaryOperator::ShiftLeft, + TokenValue::RightShift => BinaryOperator::ShiftRight, + TokenValue::Plus => BinaryOperator::Add, + TokenValue::Dash => BinaryOperator::Subtract, + TokenValue::Star => BinaryOperator::Multiply, + TokenValue::Slash => BinaryOperator::Divide, + TokenValue::Percent => BinaryOperator::Modulo, + _ => unreachable!(), + }, + right, + }, + meta: start_meta.union(&end_meta), + }) + } + + Ok(left) + } + + pub fn parse_conditional( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + passtrough: Option>, + ) -> Result> { + let mut condition = self.parse_binary(parser, ctx, body, passtrough, 0)?; + let start_meta = ctx.hir_exprs[condition].meta; + + if self.bump_if(parser, TokenValue::Question).is_some() { + let accept = self.parse_expression(parser, ctx, body)?; + self.expect(parser, TokenValue::Colon)?; + let reject = self.parse_assignment(parser, ctx, body)?; + let end_meta = ctx.hir_exprs[reject].meta; + + condition = ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Conditional { + condition, + accept, + reject, + }, + meta: start_meta.union(&end_meta), + }) + } + + Ok(condition) + } + + pub fn parse_assignment( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + ) -> Result> { + let tgt = self.parse_unary(parser, ctx, body)?; + let start_meta = ctx.hir_exprs[tgt].meta; + + Ok(match self.expect_peek(parser)?.value { + TokenValue::Assign => { + self.bump(parser)?; + let value = self.parse_assignment(parser, ctx, body)?; + let end_meta = ctx.hir_exprs[value].meta; + + ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Assign { tgt, value }, + meta: start_meta.union(&end_meta), + }) + } + TokenValue::OrAssign + | TokenValue::AndAssign + | TokenValue::AddAssign + | TokenValue::DivAssign + | TokenValue::ModAssign + | TokenValue::SubAssign + | TokenValue::MulAssign + | TokenValue::LeftShiftAssign + | TokenValue::RightShiftAssign + | TokenValue::XorAssign => { + let token = self.bump(parser)?; + let right = self.parse_assignment(parser, ctx, body)?; + let end_meta = ctx.hir_exprs[right].meta; + + let value = ctx.hir_exprs.append(HirExpr { + meta: start_meta.union(&end_meta), + kind: HirExprKind::Binary { + left: tgt, + op: match token.value { + TokenValue::OrAssign => BinaryOperator::InclusiveOr, + TokenValue::AndAssign => BinaryOperator::And, + TokenValue::AddAssign => BinaryOperator::Add, + TokenValue::DivAssign => BinaryOperator::Divide, + TokenValue::ModAssign => BinaryOperator::Modulo, + TokenValue::SubAssign => BinaryOperator::Subtract, + TokenValue::MulAssign => BinaryOperator::Multiply, + TokenValue::LeftShiftAssign => BinaryOperator::ShiftLeft, + TokenValue::RightShiftAssign => BinaryOperator::ShiftRight, + TokenValue::XorAssign => BinaryOperator::ExclusiveOr, + _ => unreachable!(), + }, + right, + }, + }); + + ctx.hir_exprs.append(HirExpr { + kind: HirExprKind::Assign { tgt, value }, + meta: start_meta.union(&end_meta), + }) + } + _ => self.parse_conditional(parser, ctx, body, Some(tgt))?, + }) + } + + pub fn parse_expression( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + ) -> Result> { + let mut expr = self.parse_assignment(parser, ctx, body)?; + + while let TokenValue::Comma = self.expect_peek(parser)?.value { + self.bump(parser)?; + expr = self.parse_assignment(parser, ctx, body)?; + } + + Ok(expr) + } +} + +fn binding_power(value: &TokenValue) -> Option<(u8, u8)> { + Some(match *value { + TokenValue::LogicalOr => (1, 2), + TokenValue::LogicalXor => (3, 4), + TokenValue::LogicalAnd => (5, 6), + TokenValue::VerticalBar => (7, 8), + TokenValue::Caret => (9, 10), + TokenValue::Ampersand => (11, 12), + TokenValue::Equal | TokenValue::NotEqual => (13, 14), + TokenValue::GreaterEqual + | TokenValue::LessEqual + | TokenValue::LeftAngle + | TokenValue::RightAngle => (15, 16), + TokenValue::LeftShift | TokenValue::RightShift => (17, 18), + TokenValue::Plus | TokenValue::Dash => (19, 20), + TokenValue::Star | TokenValue::Slash | TokenValue::Percent => (21, 22), + _ => return None, + }) +} diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs new file mode 100644 index 000000000..9e1db2b89 --- /dev/null +++ b/src/front/glsl/parser/functions.rs @@ -0,0 +1,483 @@ +use crate::{ + front::glsl::{ + ast::ParameterQualifier, context::Context, parser::ParsingContext, token::TokenValue, + variables::VarDeclaration, ErrorKind, Parser, Result, Token, + }, + Block, ConstantInner, Expression, ScalarValue, Statement, SwitchCase, UnaryOperator, +}; + +impl<'source> ParsingContext<'source> { + pub fn peek_parameter_qualifier(&mut self, parser: &mut Parser) -> bool { + self.peek(parser).map_or(false, |t| match t.value { + TokenValue::In | TokenValue::Out | TokenValue::InOut | TokenValue::Const => true, + _ => false, + }) + } + + /// Returns the parsed `ParameterQualifier` or `ParameterQualifier::In` + pub fn parse_parameter_qualifier(&mut self, parser: &mut Parser) -> ParameterQualifier { + if self.peek_parameter_qualifier(parser) { + match self.bump(parser).unwrap().value { + TokenValue::In => ParameterQualifier::In, + TokenValue::Out => ParameterQualifier::Out, + TokenValue::InOut => ParameterQualifier::InOut, + TokenValue::Const => ParameterQualifier::Const, + _ => unreachable!(), + } + } else { + ParameterQualifier::In + } + } + + pub fn parse_statement( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + ) -> Result<()> { + // TODO: This prevents snippets like the following from working + // ```glsl + // vec4(1.0); + // ``` + // But this would require us to add lookahead to also support + // declarations and since this statement is very unlikely and most + // likely an error, for now we don't support it + if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { + self.parse_declaration(parser, ctx, body, false)?; + return Ok(()); + } + + match self.expect_peek(parser)?.value { + TokenValue::Continue => { + self.bump(parser)?; + body.push(Statement::Continue); + self.expect(parser, TokenValue::Semicolon)?; + } + TokenValue::Break => { + self.bump(parser)?; + body.push(Statement::Break); + self.expect(parser, TokenValue::Semicolon)?; + } + TokenValue::Return => { + self.bump(parser)?; + let value = match self.expect_peek(parser)?.value { + TokenValue::Semicolon => { + self.bump(parser)?; + None + } + _ => { + // TODO: Implicit conversions + let expr = self.parse_expression(parser, ctx, body)?; + self.expect(parser, TokenValue::Semicolon)?; + Some(ctx.lower_expect(parser, expr, false, body)?.0) + } + }; + + ctx.emit_flush(body); + ctx.emit_start(); + + body.push(Statement::Return { value }) + } + TokenValue::Discard => { + self.bump(parser)?; + body.push(Statement::Kill); + self.expect(parser, TokenValue::Semicolon)?; + } + TokenValue::If => { + self.bump(parser)?; + + self.expect(parser, TokenValue::LeftParen)?; + let condition = { + let expr = self.parse_expression(parser, ctx, body)?; + ctx.lower_expect(parser, expr, false, body)?.0 + }; + self.expect(parser, TokenValue::RightParen)?; + + ctx.emit_flush(body); + ctx.emit_start(); + + let mut accept = Block::new(); + self.parse_statement(parser, ctx, &mut accept)?; + + let mut reject = Block::new(); + if self.bump_if(parser, TokenValue::Else).is_some() { + self.parse_statement(parser, ctx, &mut reject)?; + } + + body.push(Statement::If { + condition, + accept, + reject, + }); + } + TokenValue::Switch => { + self.bump(parser)?; + + self.expect(parser, TokenValue::LeftParen)?; + // TODO: Implicit conversions + let selector = { + let expr = self.parse_expression(parser, ctx, body)?; + ctx.lower_expect(parser, expr, false, body)?.0 + }; + self.expect(parser, TokenValue::RightParen)?; + + ctx.emit_flush(body); + ctx.emit_start(); + + let mut cases = Vec::new(); + let mut default = Block::new(); + + self.expect(parser, TokenValue::LeftBrace)?; + loop { + match self.expect_peek(parser)?.value { + TokenValue::Case => { + self.bump(parser)?; + let value = { + let expr = self.parse_expression(parser, ctx, body)?; + let (root, meta) = ctx.lower_expect(parser, expr, false, body)?; + let constant = parser.solve_constant(ctx, root, meta)?; + + match parser.module.constants[constant].inner { + ConstantInner::Scalar { + value: ScalarValue::Sint(int), + .. + } => int as i32, + ConstantInner::Scalar { + value: ScalarValue::Uint(int), + .. + } => int as i32, + _ => { + return Err(ErrorKind::SemanticError( + meta, + "Case values can only be integers".into(), + )) + } + } + }; + + self.expect(parser, TokenValue::Colon)?; + + let mut body = Block::new(); + + loop { + match self.expect_peek(parser)?.value { + TokenValue::Case + | TokenValue::Default + | TokenValue::RightBrace => break, + _ => self.parse_statement(parser, ctx, &mut body)?, + } + } + + let mut fall_through = true; + + for (i, stmt) in body.iter().enumerate() { + if let Statement::Break = *stmt { + fall_through = false; + body.drain(i..); + break; + } + } + + cases.push(SwitchCase { + value, + body, + fall_through, + }) + } + TokenValue::Default => { + let Token { meta, .. } = self.bump(parser)?; + self.expect(parser, TokenValue::Colon)?; + + if !default.is_empty() { + return Err(ErrorKind::SemanticError( + meta, + "Can only have one default case per switch statement".into(), + )); + } + + loop { + match self.expect_peek(parser)?.value { + TokenValue::Case | TokenValue::RightBrace => break, + _ => self.parse_statement(parser, ctx, &mut default)?, + } + } + + for (i, stmt) in default.iter().enumerate() { + if let Statement::Break = *stmt { + default.drain(i..); + break; + } + } + } + TokenValue::RightBrace => { + self.bump(parser)?; + break; + } + _ => { + return Err(ErrorKind::InvalidToken( + self.bump(parser)?, + vec![ + TokenValue::Case.into(), + TokenValue::Default.into(), + TokenValue::RightBrace.into(), + ], + )) + } + } + } + + body.push(Statement::Switch { + selector, + cases, + default, + }); + } + TokenValue::While => { + self.bump(parser)?; + + let mut loop_body = Block::new(); + + self.expect(parser, TokenValue::LeftParen)?; + let root = self.parse_expression(parser, ctx, &mut loop_body)?; + self.expect(parser, TokenValue::RightParen)?; + + let expr = ctx.lower_expect(parser, root, false, &mut loop_body)?.0; + let condition = ctx.add_expression( + Expression::Unary { + op: UnaryOperator::Not, + expr, + }, + &mut loop_body, + ); + + ctx.emit_flush(&mut loop_body); + ctx.emit_start(); + + loop_body.push(Statement::If { + condition, + accept: vec![Statement::Break], + reject: Block::new(), + }); + + self.parse_statement(parser, ctx, &mut loop_body)?; + + body.push(Statement::Loop { + body: loop_body, + continuing: Block::new(), + }) + } + TokenValue::Do => { + self.bump(parser)?; + + let mut loop_body = Block::new(); + self.parse_statement(parser, ctx, &mut loop_body)?; + + self.expect(parser, TokenValue::While)?; + self.expect(parser, TokenValue::LeftParen)?; + let root = self.parse_expression(parser, ctx, &mut loop_body)?; + self.expect(parser, TokenValue::RightParen)?; + + let expr = ctx.lower_expect(parser, root, false, &mut loop_body)?.0; + let condition = ctx.add_expression( + Expression::Unary { + op: UnaryOperator::Not, + expr, + }, + &mut loop_body, + ); + + ctx.emit_flush(&mut loop_body); + ctx.emit_start(); + + loop_body.push(Statement::If { + condition, + accept: vec![Statement::Break], + reject: Block::new(), + }); + + body.push(Statement::Loop { + body: loop_body, + continuing: Block::new(), + }) + } + TokenValue::For => { + self.bump(parser)?; + + ctx.push_scope(); + self.expect(parser, TokenValue::LeftParen)?; + + if self.bump_if(parser, TokenValue::Semicolon).is_none() { + if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { + self.parse_declaration(parser, ctx, body, false)?; + } else { + let expr = self.parse_expression(parser, ctx, body)?; + ctx.lower(parser, expr, false, body)?; + self.expect(parser, TokenValue::Semicolon)?; + } + } + + let (mut block, mut continuing) = (Block::new(), Block::new()); + + if self.bump_if(parser, TokenValue::Semicolon).is_none() { + let expr = if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { + let qualifiers = self.parse_type_qualifiers(parser)?; + let (ty, meta) = self.parse_type_non_void(parser)?; + let name = self.expect_ident(parser)?.0; + + self.expect(parser, TokenValue::Assign)?; + + let (value, end_meta) = + self.parse_initializer(parser, ty, ctx, &mut block)?; + + let decl = VarDeclaration { + qualifiers: &qualifiers, + ty, + name: Some(name), + init: None, + meta: meta.union(&end_meta), + }; + + let pointer = parser.add_local_var(ctx, &mut block, decl)?; + + ctx.emit_flush(&mut block); + ctx.emit_start(); + + block.push(Statement::Store { pointer, value }); + + value + } else { + let root = self.parse_expression(parser, ctx, &mut block)?; + ctx.lower_expect(parser, root, false, &mut block)?.0 + }; + + let condition = ctx.add_expression( + Expression::Unary { + op: UnaryOperator::Not, + expr, + }, + &mut block, + ); + + ctx.emit_flush(&mut block); + ctx.emit_start(); + + block.push(Statement::If { + condition, + accept: vec![Statement::Break], + reject: Block::new(), + }); + + self.expect(parser, TokenValue::Semicolon)?; + } + + match self.expect_peek(parser)?.value { + TokenValue::RightParen => {} + _ => { + let rest = self.parse_expression(parser, ctx, &mut continuing)?; + ctx.lower(parser, rest, false, &mut continuing)?; + } + } + + self.expect(parser, TokenValue::RightParen)?; + + self.parse_statement(parser, ctx, &mut block)?; + + body.push(Statement::Loop { + body: block, + continuing, + }); + + ctx.remove_current_scope(); + } + TokenValue::LeftBrace => { + self.bump(parser)?; + + let mut block = Block::new(); + ctx.push_scope(); + + self.parse_compound_statement(parser, ctx, &mut block)?; + + ctx.remove_current_scope(); + body.push(Statement::Block(block)); + } + TokenValue::Plus + | TokenValue::Dash + | TokenValue::Bang + | TokenValue::Tilde + | TokenValue::LeftParen + | TokenValue::Identifier(_) + | TokenValue::TypeName(_) + | TokenValue::IntConstant(_) + | TokenValue::BoolConstant(_) + | TokenValue::FloatConstant(_) => { + let expr = self.parse_expression(parser, ctx, body)?; + ctx.lower(parser, expr, false, body)?; + self.expect(parser, TokenValue::Semicolon)?; + } + TokenValue::Semicolon => { + self.bump(parser)?; + } + _ => {} + } + + Ok(()) + } + + pub fn parse_compound_statement( + &mut self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + ) -> Result<()> { + loop { + if self.bump_if(parser, TokenValue::RightBrace).is_some() { + break; + } + + self.parse_statement(parser, ctx, body)?; + } + + Ok(()) + } + + pub fn parse_function_args( + &mut self, + parser: &mut Parser, + context: &mut Context, + body: &mut Block, + ) -> Result<()> { + loop { + if self.peek_type_name(parser) || self.peek_parameter_qualifier(parser) { + let qualifier = self.parse_parameter_qualifier(parser); + let ty = self.parse_type_non_void(parser)?.0; + + match self.expect_peek(parser)?.value { + TokenValue::Comma => { + self.bump(parser)?; + context.add_function_arg(parser, body, None, ty, qualifier); + continue; + } + TokenValue::Identifier(_) => { + let name = self.expect_ident(parser)?.0; + + let size = self.parse_array_specifier(parser)?; + let ty = parser.maybe_array(ty, size); + + context.add_function_arg(parser, body, Some(name), ty, qualifier); + + if self.bump_if(parser, TokenValue::Comma).is_some() { + continue; + } + + break; + } + _ => break, + } + } + + break; + } + + Ok(()) + } +} diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs new file mode 100644 index 000000000..9ee12a0f0 --- /dev/null +++ b/src/front/glsl/parser/types.rs @@ -0,0 +1,268 @@ +use crate::{ + front::glsl::{ + ast::{StorageQualifier, StructLayout, TypeQualifier}, + error::ExpectedToken, + parser::ParsingContext, + token::{SourceMetadata, TokenValue}, + ErrorKind, Parser, Result, + }, + ArraySize, Handle, ResourceBinding, StorageClass, Type, TypeInner, +}; + +impl<'source> ParsingContext<'source> { + /// Parses an optional array_specifier returning `Ok(None)` if there is no + /// LeftBracket + pub fn parse_array_specifier(&mut self, parser: &mut Parser) -> Result> { + if self.bump_if(parser, TokenValue::LeftBracket).is_some() { + if self.bump_if(parser, TokenValue::RightBracket).is_some() { + return Ok(Some(ArraySize::Dynamic)); + } + + let (constant, _) = self.parse_constant_expression(parser)?; + self.expect(parser, TokenValue::RightBracket)?; + Ok(Some(ArraySize::Constant(constant))) + } else { + Ok(None) + } + } + + pub fn parse_type( + &mut self, + parser: &mut Parser, + ) -> Result<(Option>, SourceMetadata)> { + let token = self.bump(parser)?; + let handle = match token.value { + TokenValue::Void => None, + TokenValue::TypeName(ty) => Some(parser.module.types.fetch_or_append(ty)), + TokenValue::Struct => { + let ty_name = self.expect_ident(parser)?.0; + self.expect(parser, TokenValue::LeftBrace)?; + let mut members = Vec::new(); + let span = + self.parse_struct_declaration_list(parser, &mut members, StructLayout::Std140)?; + self.expect(parser, TokenValue::RightBrace)?; + + let ty = parser.module.types.append(Type { + name: Some(ty_name.clone()), + inner: TypeInner::Struct { + top_level: false, + members, + span, + }, + }); + parser.lookup_type.insert(ty_name, ty); + Some(ty) + } + TokenValue::Identifier(ident) => match parser.lookup_type.get(&ident) { + Some(ty) => Some(*ty), + None => return Err(ErrorKind::UnknownType(token.meta, ident)), + }, + _ => { + return Err(ErrorKind::InvalidToken( + token, + vec![ + TokenValue::Void.into(), + TokenValue::Struct.into(), + ExpectedToken::TypeName, + ], + )) + } + }; + + let size = self.parse_array_specifier(parser)?; + Ok((handle.map(|ty| parser.maybe_array(ty, size)), token.meta)) + } + + pub fn parse_type_non_void( + &mut self, + parser: &mut Parser, + ) -> Result<(Handle, SourceMetadata)> { + let (maybe_ty, meta) = self.parse_type(parser)?; + let ty = + maybe_ty.ok_or_else(|| ErrorKind::SemanticError(meta, "Type can't be void".into()))?; + + Ok((ty, meta)) + } + + pub fn peek_type_qualifier(&mut self, parser: &mut Parser) -> bool { + self.peek(parser).map_or(false, |t| match t.value { + TokenValue::Interpolation(_) + | TokenValue::Sampling(_) + | TokenValue::PrecisionQualifier(_) + | TokenValue::Const + | TokenValue::In + | TokenValue::Out + | TokenValue::Uniform + | TokenValue::Buffer + | TokenValue::Restrict + | TokenValue::StorageAccess(_) + | TokenValue::Layout => true, + _ => false, + }) + } + + pub fn parse_type_qualifiers( + &mut self, + parser: &mut Parser, + ) -> Result> { + let mut qualifiers = Vec::new(); + + while self.peek_type_qualifier(parser) { + let token = self.bump(parser)?; + + // Handle layout qualifiers outside the match since this can push multiple values + if token.value == TokenValue::Layout { + self.parse_layout_qualifier_id_list(parser, &mut qualifiers)?; + continue; + } + + qualifiers.push(( + match token.value { + TokenValue::Interpolation(i) => TypeQualifier::Interpolation(i), + TokenValue::Const => TypeQualifier::StorageQualifier(StorageQualifier::Const), + TokenValue::In => TypeQualifier::StorageQualifier(StorageQualifier::Input), + TokenValue::Out => TypeQualifier::StorageQualifier(StorageQualifier::Output), + TokenValue::Uniform => TypeQualifier::StorageQualifier( + StorageQualifier::StorageClass(StorageClass::Uniform), + ), + TokenValue::Buffer => TypeQualifier::StorageQualifier( + StorageQualifier::StorageClass(StorageClass::Storage { + access: crate::StorageAccess::default(), + }), + ), + TokenValue::Sampling(s) => TypeQualifier::Sampling(s), + TokenValue::PrecisionQualifier(p) => TypeQualifier::Precision(p), + TokenValue::StorageAccess(access) => TypeQualifier::StorageAccess(access), + TokenValue::Restrict => continue, + _ => unreachable!(), + }, + token.meta, + )) + } + + Ok(qualifiers) + } + + pub fn parse_layout_qualifier_id_list( + &mut self, + parser: &mut Parser, + qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, + ) -> Result<()> { + // We need both of these to produce a ResourceBinding + let mut group = None; + let mut binding = None; + + self.expect(parser, TokenValue::LeftParen)?; + loop { + self.parse_layout_qualifier_id(parser, qualifiers, &mut group, &mut binding)?; + + if self.bump_if(parser, TokenValue::Comma).is_some() { + continue; + } + + break; + } + self.expect(parser, TokenValue::RightParen)?; + + match (group, binding) { + (Some((group, group_meta)), Some((binding, binding_meta))) => qualifiers.push(( + TypeQualifier::ResourceBinding(ResourceBinding { group, binding }), + group_meta.union(&binding_meta), + )), + // Produce an error if we have one of group or binding but not the other + (Some((_, meta)), None) => { + return Err(ErrorKind::SemanticError( + meta, + "set specified with no binding".into(), + )) + } + (None, Some((_, meta))) => { + return Err(ErrorKind::SemanticError( + meta, + "binding specified with no set".into(), + )) + } + (None, None) => (), + } + + Ok(()) + } + + pub fn parse_layout_qualifier_id( + &mut self, + parser: &mut Parser, + qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, + group: &mut Option<(u32, SourceMetadata)>, + binding: &mut Option<(u32, SourceMetadata)>, + ) -> Result<()> { + // layout_qualifier_id: + // IDENTIFIER + // IDENTIFIER EQUAL constant_expression + // SHARED + let mut token = self.bump(parser)?; + match token.value { + TokenValue::Identifier(name) => { + if self.bump_if(parser, TokenValue::Assign).is_some() { + let (value, end_meta) = self.parse_uint_constant(parser)?; + token.meta = token.meta.union(&end_meta); + + qualifiers.push(( + match name.as_str() { + "location" => TypeQualifier::Location(value), + "set" => { + *group = Some((value, end_meta)); + return Ok(()); + } + "binding" => { + *binding = Some((value, end_meta)); + return Ok(()); + } + "local_size_x" => TypeQualifier::WorkGroupSize(0, value), + "local_size_y" => TypeQualifier::WorkGroupSize(1, value), + "local_size_z" => TypeQualifier::WorkGroupSize(2, value), + _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), + }, + token.meta, + )) + } else { + match name.as_str() { + "push_constant" => { + qualifiers.push(( + TypeQualifier::StorageQualifier(StorageQualifier::StorageClass( + StorageClass::PushConstant, + )), + token.meta, + )); + qualifiers + .push((TypeQualifier::Layout(StructLayout::Std430), token.meta)); + } + "std140" => qualifiers + .push((TypeQualifier::Layout(StructLayout::Std140), token.meta)), + "std430" => qualifiers + .push((TypeQualifier::Layout(StructLayout::Std430), token.meta)), + "early_fragment_tests" => { + qualifiers.push((TypeQualifier::EarlyFragmentTests, token.meta)) + } + _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), + } + }; + + Ok(()) + } + // TODO: handle Shared? + _ => Err(ErrorKind::InvalidToken( + token, + vec![ExpectedToken::Identifier], + )), + } + } + + pub fn peek_type_name(&mut self, parser: &mut Parser) -> bool { + self.peek(parser).map_or(false, |t| match t.value { + TokenValue::TypeName(_) | TokenValue::Void => true, + TokenValue::Struct => true, + TokenValue::Identifier(ref ident) => parser.lookup_type.contains_key(ident), + _ => false, + }) + } +} diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 72372c987..aec382480 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -1,53 +1,55 @@ use pp_rs::token::PreprocessorError; -use super::lex::Lexer; -use super::parser; -use super::{ast::Profile, error::ErrorKind}; -use super::{ast::Program, SourceMetadata}; -use crate::front::glsl::error::ExpectedToken; use crate::{ - front::glsl::{token::TokenValue, Token}, - ShaderStage, + front::glsl::{ + ast::Profile, error::ErrorKind, error::ExpectedToken, token::TokenValue, Options, Parser, + SourceMetadata, Token, + }, + Module, ShaderStage, }; -fn parse_program(source: &str, stage: ShaderStage) -> Result { - let mut program = Program::new(stage); +fn parse(parser: &mut Parser, source: &str, stage: ShaderStage) -> Result { let defines = crate::FastHashMap::default(); - let lex = Lexer::new(source, &defines); - let mut parser = parser::Parser::new(&mut program, lex); - parser.parse()?; - Ok(program) + parser + .parse(&Options { stage, defines }, source) + .map_err(|e| e.kind) } #[test] fn version() { + let mut parser = Parser::default(); + // invalid versions assert_eq!( - parse_program("#version 99000", ShaderStage::Vertex) + parse(&mut parser, "#version 99000", ShaderStage::Vertex) .err() .unwrap(), ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 14 }, 99000), ); assert_eq!( - parse_program("#version 449", ShaderStage::Vertex) + parse(&mut parser, "#version 449", ShaderStage::Vertex) .err() .unwrap(), ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 12 }, 449) ); assert_eq!( - parse_program("#version 450 smart", ShaderStage::Vertex) + parse(&mut parser, "#version 450 smart", ShaderStage::Vertex) .err() .unwrap(), ErrorKind::InvalidProfile(SourceMetadata { start: 13, end: 18 }, "smart".into()) ); assert_eq!( - parse_program("#version 450\nvoid f(){} #version 450", ShaderStage::Vertex) - .err() - .unwrap(), + parse( + &mut parser, + "#version 450\nvoid f(){} #version 450", + ShaderStage::Vertex + ) + .err() + .unwrap(), ErrorKind::InvalidToken( Token { value: TokenValue::Unknown(PreprocessorError::UnexpectedHash), @@ -58,19 +60,46 @@ fn version() { ); // valid versions - let program = parse_program(" # version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); - assert_eq!((program.version, program.profile), (450, Profile::Core)); + parse( + &mut parser, + " # version 450\nvoid main() {}", + ShaderStage::Vertex, + ) + .unwrap(); + assert_eq!( + (parser.metadata().version, parser.metadata().profile), + (450, Profile::Core) + ); - let program = parse_program("#version 450\nvoid main() {}", ShaderStage::Vertex).unwrap(); - assert_eq!((program.version, program.profile), (450, Profile::Core)); + parse( + &mut parser, + "#version 450\nvoid main() {}", + ShaderStage::Vertex, + ) + .unwrap(); + assert_eq!( + (parser.metadata().version, parser.metadata().profile), + (450, Profile::Core) + ); - let program = parse_program("#version 450 core\nvoid main() {}", ShaderStage::Vertex).unwrap(); - assert_eq!((program.version, program.profile), (450, Profile::Core)); + parse( + &mut parser, + "#version 450 core\nvoid main() {}", + ShaderStage::Vertex, + ) + .unwrap(); + assert_eq!( + (parser.metadata().version, parser.metadata().profile), + (450, Profile::Core) + ); } #[test] fn control_flow() { - let _program = parse_program( + let mut parser = Parser::default(); + + parse( + &mut parser, r#" # version 450 void main() { @@ -85,7 +114,8 @@ fn control_flow() { ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" # version 450 void main() { @@ -98,7 +128,8 @@ fn control_flow() { ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" # version 450 void main() { @@ -119,7 +150,8 @@ fn control_flow() { ShaderStage::Vertex, ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" # version 450 void main() { @@ -136,7 +168,8 @@ fn control_flow() { ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" # version 450 void main() { @@ -155,7 +188,10 @@ fn control_flow() { #[test] fn declarations() { - let _program = parse_program( + let mut parser = Parser::default(); + + parse( + &mut parser, r#" #version 450 layout(location = 0) in vec2 v_uv; @@ -164,12 +200,15 @@ fn declarations() { layout(set = 1, binding = 2) uniform sampler tex_sampler; layout(early_fragment_tests) in; + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" #version 450 layout(std140, set = 2, binding = 0) @@ -178,12 +217,15 @@ fn declarations() { float load_time; ivec4 atlas_offs; }; + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" #version 450 layout(push_constant, set = 2, binding = 0) @@ -192,12 +234,15 @@ fn declarations() { float load_time; ivec4 atlas_offs; }; + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" #version 450 layout(std430, set = 2, binding = 0) @@ -206,12 +251,15 @@ fn declarations() { float load_time; ivec4 atlas_offs; }; + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" #version 450 layout(std140, set = 2, binding = 0) @@ -229,19 +277,25 @@ fn declarations() { ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" #version 450 float vector = vec4(1.0 / 17.0, 9.0 / 17.0, 3.0 / 17.0, 11.0 / 17.0); + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); - let _program = parse_program( + parse( + &mut parser, r#" #version 450 precision highp float; + + void main() {} "#, ShaderStage::Vertex, ) @@ -250,7 +304,10 @@ fn declarations() { #[test] fn textures() { - let _program = parse_program( + let mut parser = Parser::default(); + + parse( + &mut parser, r#" #version 450 layout(location = 0) in vec2 v_uv; @@ -269,7 +326,10 @@ fn textures() { #[test] fn functions() { - parse_program( + let mut parser = Parser::default(); + + parse( + &mut parser, r#" # version 450 void test1(float); @@ -281,7 +341,8 @@ fn functions() { ) .unwrap(); - parse_program( + parse( + &mut parser, r#" # version 450 void test2(float a) {} @@ -294,7 +355,8 @@ fn functions() { ) .unwrap(); - parse_program( + parse( + &mut parser, r#" # version 450 float test(float a) { return a; } @@ -305,19 +367,23 @@ fn functions() { ) .unwrap(); - parse_program( + parse( + &mut parser, r#" # version 450 float test(vec4 p) { return p.x; } + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); // Function overloading - parse_program( + parse( + &mut parser, r#" # version 450 float test(vec2 p); @@ -335,13 +401,16 @@ fn functions() { float test(vec4 p) { return p.x; } + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); assert_eq!( - parse_program( + parse( + &mut parser, r#" # version 450 int test(vec4 p) { @@ -351,6 +420,8 @@ fn functions() { float test(vec4 p) { return p.x; } + + void main() {} "#, ShaderStage::Vertex ) @@ -367,7 +438,8 @@ fn functions() { println!(); - let _program = parse_program( + parse( + &mut parser, r#" # version 450 float callee(uint q) { @@ -377,13 +449,16 @@ fn functions() { float caller() { callee(1u); } + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); // Nested function call - let _program = parse_program( + parse( + &mut parser, r#" # version 450 layout(set = 0, binding = 1) uniform texture2D t_noise; @@ -397,7 +472,8 @@ fn functions() { ) .unwrap(); - parse_program( + parse( + &mut parser, r#" # version 450 void fun(vec2 in_parameter, out float out_parameter) { @@ -417,19 +493,23 @@ fn functions() { #[test] fn constants() { use crate::{Constant, ConstantInner, ScalarValue}; + let mut parser = Parser::default(); - let program = parse_program( + let module = parse( + &mut parser, r#" # version 450 const float a = 1.0; float global = a; const float b = a; + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); - let mut constants = program.module.constants.iter(); + let mut constants = module.constants.iter(); assert_eq!( constants.next().unwrap().1, @@ -448,7 +528,10 @@ fn constants() { #[test] fn function_overloading() { - parse_program( + let mut parser = Parser::default(); + + parse( + &mut parser, r#" # version 450 @@ -471,7 +554,10 @@ fn function_overloading() { #[test] fn implicit_conversions() { - parse_program( + let mut parser = Parser::default(); + + parse( + &mut parser, r#" # version 450 void main() { @@ -485,7 +571,8 @@ fn implicit_conversions() { .unwrap(); assert_eq!( - parse_program( + parse( + &mut parser, r#" # version 450 void test(int a) {} @@ -509,7 +596,8 @@ fn implicit_conversions() { ); assert_eq!( - parse_program( + parse( + &mut parser, r#" # version 450 void test(float a) {} @@ -535,41 +623,53 @@ fn implicit_conversions() { #[test] fn structs() { - parse_program( + let mut parser = Parser::default(); + + parse( + &mut parser, r#" # version 450 Test { vec4 pos; } xx; + + void main() {} "#, ShaderStage::Vertex, ) .unwrap_err(); - parse_program( + parse( + &mut parser, r#" # version 450 struct Test { vec4 pos; }; + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); - parse_program( + parse( + &mut parser, r#" # version 450 const int NUM_VECS = 42; struct Test { vec4 vecs[NUM_VECS]; }; + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); - parse_program( + parse( + &mut parser, r#" # version 450 struct Hello { @@ -577,26 +677,34 @@ fn structs() { } test() { return Hello( vec4(1.0) ); } + + void main() {} "#, ShaderStage::Vertex, ) .unwrap(); - parse_program( + parse( + &mut parser, r#" # version 450 struct Test {}; + + void main() {} "#, ShaderStage::Vertex, ) .unwrap_err(); - parse_program( + parse( + &mut parser, r#" # version 450 inout struct Test { vec4 x; }; + + void main() {} "#, ShaderStage::Vertex, ) @@ -605,7 +713,10 @@ fn structs() { #[test] fn swizzles() { - parse_program( + let mut parser = Parser::default(); + + parse( + &mut parser, r#" # version 450 void main() { @@ -619,7 +730,8 @@ fn swizzles() { ) .unwrap(); - parse_program( + parse( + &mut parser, r#" # version 450 void main() { @@ -631,7 +743,8 @@ fn swizzles() { ) .unwrap_err(); - parse_program( + parse( + &mut parser, r#" # version 450 void main() { @@ -646,13 +759,18 @@ fn swizzles() { #[test] fn vector_indexing() { - parse_program( + let mut parser = Parser::default(); + + parse( + &mut parser, r#" # version 450 - float main(int index) { + float test(int index) { vec4 v = vec4(1.0, 2.0, 3.0, 4.0); return v[index] + 1.0; } + + void main() {} "#, ShaderStage::Vertex, ) diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 73812276a..cac913792 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,4 +1,11 @@ -use crate::{ImageClass, ImageDimension, ScalarKind, Type, TypeInner, VectorSize}; +use crate::{ + front::glsl::{ + constants::ConstantSolver, context::Context, ErrorKind, Parser, Result, SourceMetadata, + }, + proc::ResolveContext, + ArraySize, Constant, Expression, Handle, ImageClass, ImageDimension, ScalarKind, Type, + TypeInner, VectorSize, +}; pub fn parse_type(type_name: &str) -> Option { match type_name { @@ -152,3 +159,108 @@ pub fn parse_type(type_name: &str) -> Option { } } } + +pub fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, crate::Bytes)> { + match *ty { + TypeInner::Scalar { kind, width } => Some((kind, width)), + TypeInner::Vector { kind, width, .. } => Some((kind, width)), + TypeInner::Matrix { width, .. } => Some((ScalarKind::Float, width)), + TypeInner::ValuePointer { kind, width, .. } => Some((kind, width)), + _ => None, + } +} + +pub fn type_power(kind: ScalarKind) -> Option { + Some(match kind { + ScalarKind::Sint => 0, + ScalarKind::Uint => 1, + ScalarKind::Float => 2, + ScalarKind::Bool => return None, + }) +} + +impl Parser { + pub fn typifier_grow( + &self, + ctx: &mut Context, + handle: Handle, + meta: SourceMetadata, + ) -> Result<()> { + let resolve_ctx = ResolveContext { + constants: &self.module.constants, + types: &self.module.types, + global_vars: &self.module.global_variables, + local_vars: &ctx.locals, + functions: &self.module.functions, + arguments: &ctx.arguments, + }; + + ctx.typifier + .grow(handle, &ctx.expressions, &resolve_ctx) + .map_err(|error| { + ErrorKind::SemanticError(meta, format!("Can't resolve type: {:?}", error).into()) + }) + } + + pub fn resolve_type<'b>( + &'b self, + ctx: &'b mut Context, + handle: Handle, + meta: SourceMetadata, + ) -> Result<&'b TypeInner> { + self.typifier_grow(ctx, handle, meta)?; + Ok(ctx.typifier.get(handle, &self.module.types)) + } + + /// Invalidates the cached type resolution for `handle` forcing a recomputation + pub fn invalidate_expression<'b>( + &'b self, + ctx: &'b mut Context, + handle: Handle, + meta: SourceMetadata, + ) -> Result<()> { + let resolve_ctx = ResolveContext { + constants: &self.module.constants, + types: &self.module.types, + global_vars: &self.module.global_variables, + local_vars: &ctx.locals, + functions: &self.module.functions, + arguments: &ctx.arguments, + }; + + ctx.typifier + .invalidate(handle, &ctx.expressions, &resolve_ctx) + .map_err(|error| { + ErrorKind::SemanticError(meta, format!("Can't resolve type: {:?}", error).into()) + }) + } + + pub fn solve_constant( + &mut self, + ctx: &Context, + root: Handle, + meta: SourceMetadata, + ) -> Result> { + let mut solver = ConstantSolver { + types: &self.module.types, + expressions: &ctx.expressions, + constants: &mut self.module.constants, + }; + + solver.solve(root).map_err(|e| (meta, e).into()) + } + + pub fn maybe_array(&mut self, base: Handle, size: Option) -> Handle { + size.map(|size| { + self.module.types.fetch_or_append(Type { + name: None, + inner: TypeInner::Array { + base, + size, + stride: self.module.types[base].inner.span(&self.module.constants), + }, + }) + }) + .unwrap_or(base) + } +} diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 13182ca53..3057cbd7d 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,13 +1,10 @@ use crate::{ + front::glsl::{ast::*, context::Context, error::ErrorKind, Parser, SourceMetadata}, Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, Interpolation, LocalVariable, ScalarKind, StorageAccess, StorageClass, SwizzleComponent, Type, TypeInner, VectorSize, }; -use super::ast::*; -use super::error::ErrorKind; -use super::token::SourceMetadata; - macro_rules! qualifier_arm { ($src:expr, $tgt:expr, $meta:expr, $msg:literal $(,)?) => {{ if $tgt.is_some() { @@ -31,7 +28,7 @@ pub enum GlobalOrConstant { Constant(Handle), } -impl Program { +impl Parser { pub fn lookup_variable( &mut self, ctx: &mut Context, @@ -453,7 +450,7 @@ impl Program { entry_arg: Some(idx), mutable: !input, }; - ctx.add_global(&name, lookup, self, body); + ctx.add_global(self, &name, lookup, body); self.global_variables.push((name, lookup)); } @@ -469,7 +466,7 @@ impl Program { entry_arg: None, mutable: false, }; - ctx.add_global(&name, lookup, self, body); + ctx.add_global(self, &name, lookup, body); self.global_variables.push((name, lookup)); } @@ -505,7 +502,7 @@ impl Program { entry_arg: None, mutable: true, }; - ctx.add_global(&name, lookup, self, body); + ctx.add_global(self, &name, lookup, body); self.global_variables.push((name, lookup)); } diff --git a/src/front/mod.rs b/src/front/mod.rs index 8f620f430..4bd1294ce 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -50,7 +50,7 @@ impl super::ConstantInner { } /// Helper processor that derives the types of all expressions. -#[derive(Debug)] +#[derive(Debug, Default)] pub struct Typifier { resolutions: Vec, } @@ -62,6 +62,10 @@ impl Typifier { } } + pub fn reset(&mut self) { + self.resolutions.clear() + } + pub fn get<'a>( &'a self, expr_handle: Handle, diff --git a/tests/in/glsl/931-constant-emitting.vert b/tests/in/glsl/931-constant-emitting.vert index b780eb7ac..1a3300bc8 100644 --- a/tests/in/glsl/931-constant-emitting.vert +++ b/tests/in/glsl/931-constant-emitting.vert @@ -8,3 +8,5 @@ const int constant = 10; float function() { return 0.0; } + +void main() {} diff --git a/tests/in/glsl/constant-array-size.vert b/tests/in/glsl/constant-array-size.vert index f1c7a500e..9d0f580b5 100644 --- a/tests/in/glsl/constant-array-size.vert +++ b/tests/in/glsl/constant-array-size.vert @@ -12,3 +12,5 @@ vec4 function() { } return sum; } + +void main() {} diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl index 43ccc8800..db5670f1a 100644 --- a/tests/out/wgsl/931-constant-emitting-vert.wgsl +++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl @@ -2,3 +2,12 @@ fn function() -> f32 { return 0.0; } +fn main1() { + return; +} + +[[stage(vertex)]] +fn main() { + main1(); + return; +} diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 5a7aba0ab..2eaec3086 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -32,3 +32,12 @@ fn function() -> vec4 { return _e22; } +fn main1() { + return; +} + +[[stage(vertex)]] +fn main() { + main1(); + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 8b4729968..191ef8b62 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -523,19 +523,21 @@ fn convert_glsl_folder() { } println!("Processing {}", file_name); - let module = naga::front::glsl::parse_str( - &fs::read_to_string(entry.path()).expect("Couldn't find glsl file"), - &naga::front::glsl::Options { - stage: match entry.path().extension().and_then(|s| s.to_str()).unwrap() { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - ext => panic!("Unknown extension for glsl file {}", ext), + let mut parser = naga::front::glsl::Parser::default(); + let module = parser + .parse( + &naga::front::glsl::Options { + stage: match entry.path().extension().and_then(|s| s.to_str()).unwrap() { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + ext => panic!("Unknown extension for glsl file {}", ext), + }, + defines: Default::default(), }, - defines: Default::default(), - }, - ) - .unwrap(); + &fs::read_to_string(entry.path()).expect("Couldn't find glsl file"), + ) + .unwrap(); let info = naga::valid::Validator::new( naga::valid::ValidationFlags::all(), From f6e35f5b66ed3aaa802cb8c8040653c29f3f5168 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 7 Aug 2021 13:02:10 +0100 Subject: [PATCH 1197/2212] [glsl-in] Improved preprocessor and error handling --- cli/src/main.rs | 29 ++-- src/front/glsl/error.rs | 4 + src/front/glsl/lex.rs | 169 +++++++++++++--------- src/front/glsl/mod.rs | 26 ++-- src/front/glsl/parser.rs | 253 +++++++++++++++++++++++++++------ src/front/glsl/parser_tests.rs | 142 +++++++++++------- src/front/glsl/token.rs | 32 ++++- 7 files changed, 467 insertions(+), 188 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 0339becfb..0aa384c45 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -238,9 +238,9 @@ fn run() -> Result<(), Box> { }, &input, ) - .unwrap_or_else(|err| { + .unwrap_or_else(|errors| { let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); - emit_glsl_parser_error(err, filename.unwrap_or("glsl"), &input); + emit_glsl_parser_error(errors, filename.unwrap_or("glsl"), &input); std::process::exit(1); }) } @@ -409,16 +409,23 @@ use codespan_reporting::{ }, }; -pub fn emit_glsl_parser_error(err: naga::front::glsl::ParseError, filename: &str, source: &str) { - let diagnostic = match err.kind.metadata() { - Some(metadata) => Diagnostic::error() - .with_message(err.kind.to_string()) - .with_labels(vec![Label::primary((), metadata.start..metadata.end)]), - None => Diagnostic::error().with_message(err.kind.to_string()), - }; - +pub fn emit_glsl_parser_error( + errors: Vec, + filename: &str, + source: &str, +) { let files = SimpleFile::new(filename, source); let config = codespan_reporting::term::Config::default(); let writer = StandardStream::stderr(ColorChoice::Auto); - term::emit(&mut writer.lock(), &config, &files, &diagnostic).expect("cannot write error"); + + for err in errors { + let diagnostic = match err.kind.metadata() { + Some(metadata) => Diagnostic::error() + .with_message(err.kind.to_string()) + .with_labels(vec![Label::primary((), metadata.start..metadata.end)]), + None => Diagnostic::error().with_message(err.kind.to_string()), + }; + + term::emit(&mut writer.lock(), &config, &files, &diagnostic).expect("cannot write error"); + } } diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 5d2c62681..eb9f5395e 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -2,6 +2,7 @@ use super::{ constants::ConstantSolvingError, token::{SourceMetadata, Token, TokenValue}, }; +use pp_rs::token::PreprocessorError; use std::borrow::Cow; use thiserror::Error; @@ -73,6 +74,8 @@ pub enum ErrorKind { VariableAlreadyDeclared(SourceMetadata, String), #[error("{1}")] SemanticError(SourceMetadata, Cow<'static, str>), + #[error("{1:?}")] + PreprocessorError(SourceMetadata, PreprocessorError), } impl ErrorKind { @@ -116,6 +119,7 @@ impl From<(SourceMetadata, ConstantSolvingError)> for ErrorKind { #[derive(Debug, Error)] #[error("{kind}")] +#[cfg_attr(test, derive(PartialEq))] pub struct ParseError { pub kind: ErrorKind, } diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 07c4d4507..e054217a7 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -1,18 +1,31 @@ use super::{ ast::Precision, - token::{SourceMetadata, Token, TokenValue}, + token::{Directive, DirectiveKind, SourceMetadata, Token, TokenValue}, types::parse_type, }; use crate::{FastHashMap, StorageAccess}; use pp_rs::{ pp::Preprocessor, - token::{Punct, Token as PPToken, TokenValue as PPTokenValue}, + token::{PreprocessorError, Punct, TokenValue as PPTokenValue}, }; -use std::collections::VecDeque; + +#[derive(Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub struct LexerResult { + pub kind: LexerResultKind, + pub meta: SourceMetadata, +} + +#[derive(Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub enum LexerResultKind { + Token(Token), + Directive(Directive), + Error(PreprocessorError), +} pub struct Lexer<'a> { pp: Preprocessor<'a>, - tokens: VecDeque, } impl<'a> Lexer<'a> { @@ -21,40 +34,33 @@ impl<'a> Lexer<'a> { for (define, value) in defines { pp.add_define(define, value).unwrap(); //TODO: handle error } - Lexer { - pp, - tokens: Default::default(), - } + Lexer { pp } } } impl<'a> Iterator for Lexer<'a> { - type Item = Token; + type Item = LexerResult; fn next(&mut self) -> Option { - let mut meta = SourceMetadata::default(); - let pp_token = match self.tokens.pop_front() { - Some(t) => t, - None => match self.pp.next()? { - Ok(t) => t, - Err((err, loc)) => { - meta.start = loc.start as usize; - meta.end = loc.end as usize; - return Some(Token { - value: TokenValue::Unknown(err), - meta, - }); - } - }, + let pp_token = match self.pp.next()? { + Ok(t) => t, + Err((err, loc)) => { + return Some(LexerResult { + kind: LexerResultKind::Error(err), + meta: loc.into(), + }); + } }; - meta.start = pp_token.location.start as usize; - meta.end = pp_token.location.end as usize; + let meta = pp_token.location.into(); let value = match pp_token.value { PPTokenValue::Extension(extension) => { - for t in extension.tokens { - self.tokens.push_back(t); - } - TokenValue::Extension + return Some(LexerResult { + kind: LexerResultKind::Directive(Directive { + kind: DirectiveKind::Extension, + tokens: extension.tokens, + }), + meta, + }) } PPTokenValue::Float(float) => TokenValue::FloatConstant(float), PPTokenValue::Ident(ident) => { @@ -162,30 +168,41 @@ impl<'a> Iterator for Lexer<'a> { Punct::Question => TokenValue::Question, }, PPTokenValue::Pragma(pragma) => { - for t in pragma.tokens { - self.tokens.push_back(t); - } - TokenValue::Pragma + return Some(LexerResult { + kind: LexerResultKind::Directive(Directive { + kind: DirectiveKind::Pragma, + tokens: pragma.tokens, + }), + meta, + }) } PPTokenValue::Version(version) => { - for t in version.tokens { - self.tokens.push_back(t); - } - TokenValue::Version + return Some(LexerResult { + kind: LexerResultKind::Directive(Directive { + kind: DirectiveKind::Version { + is_first_directive: version.is_first_directive, + }, + tokens: version.tokens, + }), + meta, + }) } }; - Some(Token { value, meta }) + Some(LexerResult { + kind: LexerResultKind::Token(Token { value, meta }), + meta, + }) } } #[cfg(test)] mod tests { - use pp_rs::token::Integer; + use pp_rs::token::{Integer, Location, Token as PPToken, TokenValue as PPTokenValue}; use super::{ - super::token::{SourceMetadata, Token, TokenValue}, - Lexer, + super::token::{Directive, DirectiveKind, SourceMetadata, Token, TokenValue}, + Lexer, LexerResult, LexerResultKind, }; #[test] @@ -194,63 +211,85 @@ mod tests { // line comments let mut lex = Lexer::new("#version 450\nvoid main () {}", &defines); + let mut location = Location::default(); + location.start = 9; + location.end = 12; assert_eq!( lex.next().unwrap(), - Token { - value: TokenValue::Version, + LexerResult { + kind: LexerResultKind::Directive(Directive { + kind: DirectiveKind::Version { + is_first_directive: true + }, + tokens: vec![PPToken { + value: PPTokenValue::Integer(Integer { + signed: true, + value: 450, + width: 32 + }), + location + }] + }), meta: SourceMetadata { start: 1, end: 8 } } ); assert_eq!( lex.next().unwrap(), - Token { - value: TokenValue::IntConstant(Integer { - signed: true, - value: 450, - width: 32 + LexerResult { + kind: LexerResultKind::Token(Token { + value: TokenValue::Void, + meta: SourceMetadata { start: 13, end: 17 } }), - meta: SourceMetadata { start: 9, end: 12 }, - } - ); - assert_eq!( - lex.next().unwrap(), - Token { - value: TokenValue::Void, meta: SourceMetadata { start: 13, end: 17 } } ); assert_eq!( lex.next().unwrap(), - Token { - value: TokenValue::Identifier("main".into()), + LexerResult { + kind: LexerResultKind::Token(Token { + value: TokenValue::Identifier("main".into()), + meta: SourceMetadata { start: 18, end: 22 } + }), meta: SourceMetadata { start: 18, end: 22 } } ); assert_eq!( lex.next().unwrap(), - Token { - value: TokenValue::LeftParen, + LexerResult { + kind: LexerResultKind::Token(Token { + value: TokenValue::LeftParen, + meta: SourceMetadata { start: 23, end: 24 } + }), meta: SourceMetadata { start: 23, end: 24 } } ); assert_eq!( lex.next().unwrap(), - Token { - value: TokenValue::RightParen, + LexerResult { + kind: LexerResultKind::Token(Token { + value: TokenValue::RightParen, + meta: SourceMetadata { start: 24, end: 25 } + }), meta: SourceMetadata { start: 24, end: 25 } } ); assert_eq!( lex.next().unwrap(), - Token { - value: TokenValue::LeftBrace, + LexerResult { + kind: LexerResultKind::Token(Token { + value: TokenValue::LeftBrace, + meta: SourceMetadata { start: 26, end: 27 } + }), meta: SourceMetadata { start: 26, end: 27 } } ); assert_eq!( lex.next().unwrap(), - Token { - value: TokenValue::RightBrace, + LexerResult { + kind: LexerResultKind::Token(Token { + value: TokenValue::RightBrace, + meta: SourceMetadata { start: 27, end: 28 } + }), meta: SourceMetadata { start: 27, end: 28 } } ); diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 8e487b815..2d9f0725d 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -2,7 +2,7 @@ pub use ast::Profile; pub use error::{ErrorKind, ParseError}; pub use token::{SourceMetadata, Token}; -use crate::{FastHashMap, Handle, Module, ShaderStage, Type}; +use crate::{FastHashMap, FastHashSet, Handle, Module, ShaderStage, Type}; use ast::{EntryArg, FunctionDeclaration, GlobalLookup}; use parser::ParsingContext; @@ -36,7 +36,7 @@ pub struct ShaderMetadata { pub workgroup_size: [u32; 3], pub early_fragment_tests: bool, - pub extensions: FastHashMap, + pub extensions: FastHashSet, } impl ShaderMetadata { @@ -58,7 +58,7 @@ impl Default for ShaderMetadata { stage: ShaderStage::Vertex, workgroup_size: [0; 3], early_fragment_tests: false, - extensions: FastHashMap::default(), + extensions: FastHashSet::default(), } } } @@ -74,6 +74,8 @@ pub struct Parser { entry_args: Vec, + errors: Vec, + module: Module, } @@ -95,17 +97,25 @@ impl Parser { &mut self, options: &Options, source: &str, - ) -> std::result::Result { + ) -> std::result::Result> { self.reset(options.stage); let lexer = lex::Lexer::new(source, &options.defines); let mut ctx = ParsingContext::new(lexer); - ctx.parse(self).map_err(|kind| ParseError { kind })?; + if let Err(kind) = ctx.parse(self) { + self.errors.push(ParseError { kind }); + } - let mut module = Module::default(); - std::mem::swap(&mut self.module, &mut module); - Ok(module) + if self.errors.is_empty() { + let mut module = Module::default(); + std::mem::swap(&mut self.module, &mut module); + Ok(module) + } else { + let mut errors = Vec::new(); + std::mem::swap(&mut self.errors, &mut errors); + Err(errors) + } } pub fn metadata(&self) -> &ShaderMetadata { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 56982391c..09752df98 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -5,14 +5,16 @@ use crate::{ context::Context, error::ErrorKind, error::ExpectedToken, - lex::Lexer, + lex::{Lexer, LexerResultKind}, + token::{Directive, DirectiveKind}, token::{SourceMetadata, Token, TokenValue}, variables::{GlobalOrConstant, VarDeclaration}, - Parser, Result, + ParseError, Parser, Result, }, Block, Constant, ConstantInner, Expression, ScalarValue, Type, }; use core::convert::TryFrom; +use pp_rs::token::{PreprocessorError, Token as PPToken, TokenValue as PPTokenValue}; use std::iter::Peekable; mod declarations; @@ -53,8 +55,20 @@ impl<'source> ParsingContext<'source> { } } - pub fn next(&mut self, _parser: &mut Parser) -> Option { - self.lexer.next() + pub fn next(&mut self, parser: &mut Parser) -> Option { + loop { + let res = self.lexer.next()?; + + match res.kind { + LexerResultKind::Token(token) => break Some(token), + LexerResultKind::Directive(directive) => { + parser.handle_directive(directive, res.meta) + } + LexerResultKind::Error(error) => parser.errors.push(ParseError { + kind: ErrorKind::PreprocessorError(res.meta, error), + }), + } + } } pub fn bump(&mut self, parser: &mut Parser) -> Result { @@ -70,8 +84,32 @@ impl<'source> ParsingContext<'source> { } } - pub fn peek(&mut self, _parser: &mut Parser) -> Option<&Token> { - self.lexer.peek() + pub fn peek(&mut self, parser: &mut Parser) -> Option<&Token> { + match self.lexer.peek()?.kind { + LexerResultKind::Token(_) => { + let res = self.lexer.peek()?; + + match res.kind { + LexerResultKind::Token(ref token) => Some(token), + _ => unreachable!(), + } + } + LexerResultKind::Error(_) | LexerResultKind::Directive(_) => { + let res = self.lexer.next()?; + + match res.kind { + LexerResultKind::Directive(directive) => { + parser.handle_directive(directive, res.meta) + } + LexerResultKind::Error(error) => parser.errors.push(ParseError { + kind: ErrorKind::PreprocessorError(res.meta, error), + }), + _ => unreachable!(), + } + + self.peek(parser) + } + } } pub fn expect_peek(&mut self, parser: &mut Parser) -> Result<&Token> { @@ -79,8 +117,6 @@ impl<'source> ParsingContext<'source> { } pub fn parse(&mut self, parser: &mut Parser) -> Result<()> { - self.parse_version(parser)?; - // Body and expression arena for global initialization let mut body = Block::new(); let mut ctx = Context::new(parser, &mut body); @@ -107,42 +143,6 @@ impl<'source> ParsingContext<'source> { Ok(()) } - fn parse_version(&mut self, parser: &mut Parser) -> Result<()> { - self.expect(parser, TokenValue::Version)?; - - let version = self.bump(parser)?; - match version.value { - TokenValue::IntConstant(i) => match i.value { - 440 | 450 | 460 => parser.meta.version = i.value as u16, - _ => return Err(ErrorKind::InvalidVersion(version.meta, i.value)), - }, - _ => { - return Err(ErrorKind::InvalidToken( - version, - vec![ExpectedToken::IntLiteral], - )) - } - } - - let profile = self.lexer.peek(); - parser.meta.profile = match profile { - Some(&Token { - value: TokenValue::Identifier(_), - .. - }) => { - let (name, meta) = self.expect_ident(parser)?; - - match name.as_str() { - "core" => Profile::Core, - _ => return Err(ErrorKind::InvalidProfile(meta, name)), - } - } - _ => Profile::Core, - }; - - Ok(()) - } - fn parse_uint_constant(&mut self, parser: &mut Parser) -> Result<(u32, SourceMetadata)> { let (value, meta) = self.parse_constant_expression(parser)?; @@ -181,6 +181,171 @@ impl<'source> ParsingContext<'source> { } } +impl Parser { + fn handle_directive(&mut self, directive: Directive, meta: SourceMetadata) { + let mut tokens = directive.tokens.into_iter(); + + match directive.kind { + DirectiveKind::Version { is_first_directive } => { + if !is_first_directive { + self.errors.push(ParseError { + kind: ErrorKind::SemanticError( + meta, + "#version must occur first in shader".into(), + ), + }) + } + + match tokens.next() { + Some(PPToken { + value: PPTokenValue::Integer(int), + location, + }) => match int.value { + 440 | 450 | 460 => self.meta.version = int.value as u16, + _ => self.errors.push(ParseError { + kind: ErrorKind::InvalidVersion(location.into(), int.value), + }), + }, + Some(PPToken { value, location }) => self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + location.into(), + PreprocessorError::UnexpectedToken(value), + ), + }), + None => self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + meta, + PreprocessorError::UnexpectedNewLine, + ), + }), + }; + + match tokens.next() { + Some(PPToken { + value: PPTokenValue::Ident(name), + location, + }) => match name.as_str() { + "core" => self.meta.profile = Profile::Core, + _ => self.errors.push(ParseError { + kind: ErrorKind::InvalidProfile(location.into(), name), + }), + }, + Some(PPToken { value, location }) => self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + location.into(), + PreprocessorError::UnexpectedToken(value), + ), + }), + None => {} + }; + + if let Some(PPToken { value, location }) = tokens.next() { + self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + location.into(), + PreprocessorError::UnexpectedToken(value), + ), + }) + } + } + DirectiveKind::Extension => { + // TODO: Proper extension handling + // - Checking for extension support in the compiler + // - Handle behaviors such as warn + // - Handle the all extension + let name = match tokens.next() { + Some(PPToken { + value: PPTokenValue::Ident(name), + .. + }) => Some(name), + Some(PPToken { value, location }) => { + self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + location.into(), + PreprocessorError::UnexpectedToken(value), + ), + }); + + None + } + None => { + self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + meta, + PreprocessorError::UnexpectedNewLine, + ), + }); + + None + } + }; + + match tokens.next() { + Some(PPToken { + value: PPTokenValue::Punct(pp_rs::token::Punct::Colon), + .. + }) => {} + Some(PPToken { value, location }) => self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + location.into(), + PreprocessorError::UnexpectedToken(value), + ), + }), + None => self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + meta, + PreprocessorError::UnexpectedNewLine, + ), + }), + }; + + match tokens.next() { + Some(PPToken { + value: PPTokenValue::Ident(behavior), + location, + }) => match behavior.as_str() { + "require" | "enable" | "warn" | "disable" => { + if let Some(name) = name { + self.meta.extensions.insert(name); + } + } + _ => self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + location.into(), + PreprocessorError::UnexpectedToken(PPTokenValue::Ident(behavior)), + ), + }), + }, + Some(PPToken { value, location }) => self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + location.into(), + PreprocessorError::UnexpectedToken(value), + ), + }), + None => self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + meta, + PreprocessorError::UnexpectedNewLine, + ), + }), + } + + if let Some(PPToken { value, location }) = tokens.next() { + self.errors.push(ParseError { + kind: ErrorKind::PreprocessorError( + location.into(), + PreprocessorError::UnexpectedToken(value), + ), + }) + } + } + DirectiveKind::Pragma => { + // TODO: handle some common pragmas? + } + } + } +} + pub struct DeclarationContext<'ctx> { qualifiers: Vec<(TypeQualifier, SourceMetadata)>, external: bool, diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index aec382480..282f0c042 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -1,19 +1,19 @@ -use pp_rs::token::PreprocessorError; - use crate::{ front::glsl::{ - ast::Profile, error::ErrorKind, error::ExpectedToken, token::TokenValue, Options, Parser, - SourceMetadata, Token, + ast::Profile, + error::ExpectedToken, + error::{ErrorKind, ParseError}, + token::TokenValue, + Options, Parser, SourceMetadata, Token, }, Module, ShaderStage, }; +use pp_rs::token::PreprocessorError; -fn parse(parser: &mut Parser, source: &str, stage: ShaderStage) -> Result { +fn parse(parser: &mut Parser, source: &str, stage: ShaderStage) -> Result> { let defines = crate::FastHashMap::default(); - parser - .parse(&Options { stage, defines }, source) - .map_err(|e| e.kind) + parser.parse(&Options { stage, defines }, source) } #[test] @@ -22,41 +22,69 @@ fn version() { // invalid versions assert_eq!( - parse(&mut parser, "#version 99000", ShaderStage::Vertex) - .err() - .unwrap(), - ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 14 }, 99000), - ); - - assert_eq!( - parse(&mut parser, "#version 449", ShaderStage::Vertex) - .err() - .unwrap(), - ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 12 }, 449) - ); - - assert_eq!( - parse(&mut parser, "#version 450 smart", ShaderStage::Vertex) - .err() - .unwrap(), - ErrorKind::InvalidProfile(SourceMetadata { start: 13, end: 18 }, "smart".into()) + parse( + &mut parser, + "#version 99000\n void main(){}", + ShaderStage::Vertex + ) + .err() + .unwrap(), + vec![ParseError { + kind: ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 14 }, 99000) + }], ); assert_eq!( parse( &mut parser, - "#version 450\nvoid f(){} #version 450", + "#version 449\n void main(){}", ShaderStage::Vertex ) .err() .unwrap(), - ErrorKind::InvalidToken( - Token { - value: TokenValue::Unknown(PreprocessorError::UnexpectedHash), - meta: SourceMetadata { start: 24, end: 25 } - }, - vec![ExpectedToken::Eof] + vec![ParseError { + kind: ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 12 }, 449) + }] + ); + + assert_eq!( + parse( + &mut parser, + "#version 450 smart\n void main(){}", + ShaderStage::Vertex ) + .err() + .unwrap(), + vec![ParseError { + kind: ErrorKind::InvalidProfile(SourceMetadata { start: 13, end: 18 }, "smart".into()) + }] + ); + + assert_eq!( + parse( + &mut parser, + "#version 450\nvoid main(){} #version 450", + ShaderStage::Vertex + ) + .err() + .unwrap(), + vec![ + ParseError { + kind: ErrorKind::PreprocessorError( + SourceMetadata { start: 27, end: 28 }, + PreprocessorError::UnexpectedHash, + ) + }, + ParseError { + kind: ErrorKind::InvalidToken( + Token { + value: TokenValue::Identifier("version".into()), + meta: SourceMetadata { start: 28, end: 35 } + }, + vec![ExpectedToken::Eof] + ) + } + ] ); // valid versions @@ -427,13 +455,15 @@ fn functions() { ) .err() .unwrap(), - ErrorKind::SemanticError( - SourceMetadata { - start: 134, - end: 152 - }, - "Function already defined".into() - ) + vec![ParseError { + kind: ErrorKind::SemanticError( + SourceMetadata { + start: 134, + end: 152 + }, + "Function already defined".into() + ) + }] ); println!(); @@ -586,13 +616,15 @@ fn implicit_conversions() { ) .err() .unwrap(), - ErrorKind::SemanticError( - SourceMetadata { - start: 156, - end: 165 - }, - "Unknown function \'test\'".into() - ) + vec![ParseError { + kind: ErrorKind::SemanticError( + SourceMetadata { + start: 156, + end: 165 + }, + "Unknown function \'test\'".into() + ) + }] ); assert_eq!( @@ -611,13 +643,15 @@ fn implicit_conversions() { ) .err() .unwrap(), - ErrorKind::SemanticError( - SourceMetadata { - start: 158, - end: 165 - }, - "Ambiguous best function for \'test\'".into() - ) + vec![ParseError { + kind: ErrorKind::SemanticError( + SourceMetadata { + start: 158, + end: 165 + }, + "Ambiguous best function for \'test\'".into() + ) + }] ); } diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 616c7d2d3..bcff732f9 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -1,4 +1,5 @@ -pub use pp_rs::token::{Float, Integer, PreprocessorError}; +use pp_rs::token::Location; +pub use pp_rs::token::{Float, Integer, PreprocessorError, Token as PPToken}; use super::ast::Precision; use crate::{Interpolation, Sampling, Type}; @@ -23,6 +24,15 @@ impl SourceMetadata { } } +impl From for SourceMetadata { + fn from(loc: Location) -> Self { + SourceMetadata { + start: loc.start as usize, + end: loc.end as usize, + } + } +} + impl From for Range { fn from(meta: SourceMetadata) -> Self { meta.start..meta.end @@ -38,13 +48,8 @@ pub struct Token { #[derive(Debug, PartialEq)] pub enum TokenValue { - Unknown(PreprocessorError), Identifier(String), - Extension, - Version, - Pragma, - FloatConstant(Float), IntConstant(Integer), BoolConstant(bool), @@ -141,3 +146,18 @@ impl fmt::Display for Token { write!(f, "{:?}", self.value) } } + +#[derive(Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub struct Directive { + pub kind: DirectiveKind, + pub tokens: Vec, +} + +#[derive(Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub enum DirectiveKind { + Version { is_first_directive: bool }, + Extension, + Pragma, +} From 1aaf77489b44bc4b56ea294de0209b8926855c83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 8 Aug 2021 00:10:56 +0100 Subject: [PATCH 1198/2212] [glsl-in] Improve error api and make more errors deferred --- cli/src/main.rs | 15 +- src/front/glsl/ast.rs | 5 +- src/front/glsl/context.rs | 70 +++--- src/front/glsl/error.rs | 99 ++++---- src/front/glsl/functions.rs | 177 ++++++++------- src/front/glsl/mod.rs | 12 +- src/front/glsl/offset.rs | 22 +- src/front/glsl/parser.rs | 213 ++++++++++-------- src/front/glsl/parser/declarations.rs | 145 +++++++----- src/front/glsl/parser/expressions.rs | 43 ++-- src/front/glsl/parser/functions.rs | 41 ++-- src/front/glsl/parser/types.rs | 143 ++++++------ src/front/glsl/parser_tests.rs | 83 ++++--- src/front/glsl/token.rs | 12 +- src/front/glsl/types.rs | 18 +- src/front/glsl/variables.rs | 208 +++++++++++------ tests/in/glsl/800-out-of-bounds-panic.vert | 3 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 3 + 18 files changed, 720 insertions(+), 592 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 0aa384c45..d5ef5ccc4 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -409,22 +409,15 @@ use codespan_reporting::{ }, }; -pub fn emit_glsl_parser_error( - errors: Vec, - filename: &str, - source: &str, -) { +pub fn emit_glsl_parser_error(errors: Vec, filename: &str, source: &str) { let files = SimpleFile::new(filename, source); let config = codespan_reporting::term::Config::default(); let writer = StandardStream::stderr(ColorChoice::Auto); for err in errors { - let diagnostic = match err.kind.metadata() { - Some(metadata) => Diagnostic::error() - .with_message(err.kind.to_string()) - .with_labels(vec![Label::primary((), metadata.start..metadata.end)]), - None => Diagnostic::error().with_message(err.kind.to_string()), - }; + let diagnostic = Diagnostic::error() + .with_message(err.kind.to_string()) + .with_labels(vec![Label::primary((), err.meta.start..err.meta.end)]); term::emit(&mut writer.lock(), &config, &files, &diagnostic).expect("cannot write error"); } diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 751fb4d67..c5e46a96b 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,7 +1,7 @@ use super::SourceMetadata; use crate::{ BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, Interpolation, - ResourceBinding, Sampling, StorageAccess, StorageClass, Type, UnaryOperator, + Sampling, StorageAccess, StorageClass, Type, UnaryOperator, }; #[derive(Debug, Clone, Copy)] @@ -102,7 +102,8 @@ pub enum HirExprKind { pub enum TypeQualifier { StorageQualifier(StorageQualifier), Interpolation(Interpolation), - ResourceBinding(ResourceBinding), + Set(u32), + Binding(u32), Location(u32), WorkGroupSize(usize, u32), Sampling(Sampling), diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index b756bb08d..74053f0fd 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -5,9 +5,9 @@ use crate::{ GlobalLookup, GlobalLookupKind, HirExpr, HirExprKind, ParameterInfo, ParameterQualifier, VariableReference, }, - error::ErrorKind, + error::{Error, ErrorKind}, types::{scalar_components, type_power}, - Parser, SourceMetadata, + Parser, Result, SourceMetadata, }, Emitter, Typifier, }, @@ -288,16 +288,16 @@ impl Context { expr: Handle, lhs: bool, body: &mut Block, - ) -> Result<(Handle, SourceMetadata), ErrorKind> { + ) -> Result<(Handle, SourceMetadata)> { let (maybe_expr, meta) = self.lower(parser, expr, lhs, body)?; let expr = match maybe_expr { Some(e) => e, None => { - return Err(ErrorKind::SemanticError( + return Err(Error { + kind: ErrorKind::SemanticError("Expression returns void".into()), meta, - "Expression returns void".into(), - )) + }) } }; @@ -310,7 +310,7 @@ impl Context { expr: Handle, lhs: bool, body: &mut Block, - ) -> Result<(Option>, SourceMetadata), ErrorKind> { + ) -> Result<(Option>, SourceMetadata)> { let HirExpr { kind, meta } = self.hir_exprs[expr].clone(); let handle = match kind { @@ -448,10 +448,12 @@ impl Context { HirExprKind::Variable(var) => { if lhs { if !var.mutable { - return Err(ErrorKind::SemanticError( + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "Variable cannot be used in LHS position".into(), + ), meta, - "Variable cannot be used in LHS position".into(), - )); + }) } var.expr @@ -567,23 +569,18 @@ impl Context { let pointer = self.lower_expect(parser, expr, true, body)?.0; let left = self.add_expression(Expression::Load { pointer }, body); - let uint = if let Some(kind) = parser.resolve_type(self, left, meta)?.scalar_kind() - { - match kind { - ScalarKind::Sint => false, - ScalarKind::Uint => true, - _ => { - return Err(ErrorKind::SemanticError( - meta, + let uint = match parser.resolve_type(self, left, meta)?.scalar_kind() { + Some(ScalarKind::Sint) => false, + Some(ScalarKind::Uint) => true, + _ => { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( "Increment/decrement operations must operate in integers".into(), - )) - } + ), + meta, + }); + true } - } else { - return Err(ErrorKind::SemanticError( - meta, - "Increment/decrement operations must operate in integers".into(), - )); }; let one = parser.module.constants.append(Constant { @@ -644,10 +641,13 @@ impl Context { } } _ => { - return Err(ErrorKind::SemanticError( + return Err(Error { + kind: ErrorKind::SemanticError( + format!("{:?} cannot be in the left hand side", self.hir_exprs[expr]) + .into(), + ), meta, - format!("{:?} cannot be in the left hand side", self.hir_exprs[expr]).into(), - )) + }) } }; @@ -659,7 +659,7 @@ impl Context { parser: &mut Parser, expr: Handle, meta: SourceMetadata, - ) -> Result, ErrorKind> { + ) -> Result> { let ty = parser.resolve_type(self, expr, meta)?; Ok(scalar_components(ty)) } @@ -669,16 +669,12 @@ impl Context { parser: &mut Parser, expr: Handle, meta: SourceMetadata, - ) -> Result, ErrorKind> { + ) -> Result> { Ok(self .expr_scalar_components(parser, expr, meta)? .and_then(|(kind, _)| type_power(kind))) } - pub fn get_expression(&self, expr: Handle) -> &Expression { - &self.expressions[expr] - } - pub fn implicit_conversion( &mut self, parser: &mut Parser, @@ -686,7 +682,7 @@ impl Context { meta: SourceMetadata, kind: ScalarKind, width: crate::Bytes, - ) -> Result<(), ErrorKind> { + ) -> Result<()> { if let (Some(tgt_power), Some(expr_power)) = (type_power(kind), self.expr_power(parser, *expr, meta)?) { @@ -709,7 +705,7 @@ impl Context { left_meta: SourceMetadata, right: &mut Handle, right_meta: SourceMetadata, - ) -> Result<(), ErrorKind> { + ) -> Result<()> { let left_components = self.expr_scalar_components(parser, *left, left_meta)?; let right_components = self.expr_scalar_components(parser, *right, right_meta)?; @@ -749,7 +745,7 @@ impl Context { expr: &mut Handle, meta: SourceMetadata, vector_size: Option, - ) -> Result<(), ErrorKind> { + ) -> Result<()> { let expr_type = parser.resolve_type(self, *expr, meta)?; if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index eb9f5395e..f6ce38011 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -1,6 +1,6 @@ use super::{ constants::ConstantSolvingError, - token::{SourceMetadata, Token, TokenValue}, + token::{SourceMetadata, TokenValue}, }; use pp_rs::token::PreprocessorError; use std::borrow::Cow; @@ -53,49 +53,46 @@ impl std::fmt::Display for ExpectedToken { pub enum ErrorKind { #[error("Unexpected end of file")] EndOfFile, - #[error("Invalid profile: {1}")] - InvalidProfile(SourceMetadata, String), - #[error("Invalid version: {1}")] - InvalidVersion(SourceMetadata, u64), - #[error("Expected {}, found {0}", join_with_comma(.1))] - InvalidToken(Token, Vec), - #[error("Not implemented: {1}")] - NotImplemented(SourceMetadata, &'static str), - #[error("Unknown variable: {1}")] - UnknownVariable(SourceMetadata, String), - #[error("Unknown type: {1}")] - UnknownType(SourceMetadata, String), - #[error("Unknown field: {1}")] - UnknownField(SourceMetadata, String), - #[error("Unknown layout qualifier: {1}")] - UnknownLayoutQualifier(SourceMetadata, String), + #[error("Invalid profile: {0}")] + InvalidProfile(String), + #[error("Invalid version: {0}")] + InvalidVersion(u64), + #[error("Expected {}, found {0:?}", join_with_comma(.1))] + InvalidToken(TokenValue, Vec), + #[error("Not implemented: {0}")] + NotImplemented(&'static str), + #[error("Unknown variable: {0}")] + UnknownVariable(String), + #[error("Unknown type: {0}")] + UnknownType(String), + #[error("Unknown field: {0}")] + UnknownField(String), + #[error("Unknown layout qualifier: {0}")] + UnknownLayoutQualifier(String), #[cfg(feature = "glsl-validate")] - #[error("Variable already declared: {1}")] - VariableAlreadyDeclared(SourceMetadata, String), - #[error("{1}")] - SemanticError(SourceMetadata, Cow<'static, str>), - #[error("{1:?}")] - PreprocessorError(SourceMetadata, PreprocessorError), + #[error("Variable already declared: {0}")] + VariableAlreadyDeclared(String), + #[error("{0}")] + SemanticError(Cow<'static, str>), + #[error("{0:?}")] + PreprocessorError(PreprocessorError), } -impl ErrorKind { - /// Returns the TokenMetadata if available - pub fn metadata(&self) -> Option { - match *self { - ErrorKind::UnknownVariable(metadata, _) - | ErrorKind::InvalidProfile(metadata, _) - | ErrorKind::InvalidVersion(metadata, _) - | ErrorKind::NotImplemented(metadata, _) - | ErrorKind::UnknownLayoutQualifier(metadata, _) - | ErrorKind::SemanticError(metadata, _) - | ErrorKind::UnknownField(metadata, _) => Some(metadata), - #[cfg(feature = "glsl-validate")] - ErrorKind::VariableAlreadyDeclared(metadata, _) => Some(metadata), - ErrorKind::InvalidToken(ref token, _) => Some(token.meta), - _ => None, - } +impl From for ErrorKind { + fn from(err: ConstantSolvingError) -> Self { + ErrorKind::SemanticError(err.to_string().into()) } +} +#[derive(Debug, Error)] +#[error("{kind}")] +#[cfg_attr(test, derive(PartialEq))] +pub struct Error { + pub kind: ErrorKind, + pub meta: SourceMetadata, +} + +impl Error { pub(crate) fn wrong_function_args( name: String, expected: usize, @@ -107,25 +104,9 @@ impl ErrorKind { name, expected, got ); - ErrorKind::SemanticError(meta, msg.into()) - } -} - -impl From<(SourceMetadata, ConstantSolvingError)> for ErrorKind { - fn from((meta, err): (SourceMetadata, ConstantSolvingError)) -> Self { - ErrorKind::SemanticError(meta, err.to_string().into()) - } -} - -#[derive(Debug, Error)] -#[error("{kind}")] -#[cfg_attr(test, derive(PartialEq))] -pub struct ParseError { - pub kind: ErrorKind, -} - -impl From for ParseError { - fn from(kind: ErrorKind) -> Self { - ParseError { kind } + Error { + kind: ErrorKind::SemanticError(msg.into()), + meta, + } } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 3d3ab3932..bc7ec3b1b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -2,9 +2,9 @@ use crate::{ front::glsl::{ ast::*, context::Context, - error::ErrorKind, + error::{Error, ErrorKind}, types::{scalar_components, type_power}, - Parser, SourceMetadata, + Parser, Result, SourceMetadata, }, proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, FastHashMap, @@ -46,11 +46,11 @@ impl Parser { fc: FunctionCallKind, raw_args: &[Handle], meta: SourceMetadata, - ) -> Result>, ErrorKind> { + ) -> Result>> { let args: Vec<_> = raw_args .iter() .map(|e| ctx.lower_expect(self, *e, false, body)) - .collect::>()?; + .collect::>()?; match fc { FunctionCallKind::TypeConstructor(ty) => { @@ -226,7 +226,14 @@ impl Parser { }, body, ), - _ => return Err(ErrorKind::SemanticError(meta, "Bad cast".into())), + _ => { + self.errors.push(Error { + kind: ErrorKind::SemanticError("Bad cast".into()), + meta, + }); + + args[0].0 + } } } else { let mut components = Vec::with_capacity(args.len()); @@ -314,12 +321,12 @@ impl Parser { mut args: Vec<(Handle, SourceMetadata)>, raw_args: &[Handle], meta: SourceMetadata, - ) -> Result>, ErrorKind> { + ) -> Result>> { match name.as_str() { "sampler1D" | "sampler1DArray" | "sampler2D" | "sampler2DArray" | "sampler2DMS" | "sampler2DMSArray" | "sampler3D" | "samplerCube" | "samplerCubeArray" => { if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + return Err(Error::wrong_function_args(name, 2, args.len(), meta)); } ctx.samplers.insert(args[0].0, args[1].0); Ok(Some(args[0].0)) @@ -331,16 +338,16 @@ impl Parser { | "samplerCubeShadow" | "samplerCubeArrayShadow" => { if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + return Err(Error::wrong_function_args(name, 2, args.len(), meta)); } - sampled_to_depth(&mut self.module, ctx, args[0])?; + sampled_to_depth(&mut self.module, ctx, args[0], &mut self.errors)?; self.invalidate_expression(ctx, args[0].0, args[0].1)?; ctx.samplers.insert(args[0].0, args[1].0); Ok(Some(args[0].0)) } "texture" => { if !(2..=3).contains(&args.len()) { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + return Err(Error::wrong_function_args(name, 2, args.len(), meta)); } let arg_1 = &mut args[1]; ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; @@ -366,12 +373,15 @@ impl Parser { ), )) } else { - Err(ErrorKind::SemanticError(meta, "Bad call to texture".into())) + Err(Error { + kind: ErrorKind::SemanticError("Bad call to texture".into()), + meta, + }) } } "textureLod" => { if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + return Err(Error::wrong_function_args(name, 3, args.len(), meta)); } let arg_1 = &mut args[1]; ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; @@ -392,15 +402,15 @@ impl Parser { body, ))) } else { - Err(ErrorKind::SemanticError( + Err(Error { + kind: ErrorKind::SemanticError("Bad call to textureLod".into()), meta, - "Bad call to textureLod".into(), - )) + }) } } "textureProj" => { if !(2..=3).contains(&args.len()) { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + return Err(Error::wrong_function_args(name, 2, args.len(), meta)); } let arg_1 = &mut args[1]; ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; @@ -413,10 +423,10 @@ impl Parser { let size = match *self.resolve_type(ctx, args[1].0, args[1].1)? { TypeInner::Vector { size, .. } => size, _ => { - return Err(ErrorKind::SemanticError( + return Err(Error { + kind: ErrorKind::SemanticError("Bad call to textureProj".into()), meta, - "Bad call to textureProj".into(), - )) + }) } }; let (base, base_meta) = args[1]; @@ -460,15 +470,15 @@ impl Parser { body, ))) } else { - Err(ErrorKind::SemanticError( + Err(Error { + kind: ErrorKind::SemanticError("Bad call to textureProj".into()), meta, - "Bad call to textureProj".into(), - )) + }) } } "textureGrad" => { if args.len() != 4 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + return Err(Error::wrong_function_args(name, 3, args.len(), meta)); } let arg_1 = &mut args[1]; ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; @@ -494,15 +504,15 @@ impl Parser { body, ))) } else { - Err(ErrorKind::SemanticError( + Err(Error { + kind: ErrorKind::SemanticError("Bad call to textureGrad".into()), meta, - "Bad call to textureGrad".into(), - )) + }) } } "textureSize" => { if !(1..=2).contains(&args.len()) { - return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); + return Err(Error::wrong_function_args(name, 1, args.len(), meta)); } if let Some(&mut (ref mut expr, meta)) = args.get_mut(1) { ctx.implicit_conversion(self, expr, meta, ScalarKind::Sint, 4)?; @@ -519,7 +529,7 @@ impl Parser { } "texelFetch" => { if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + return Err(Error::wrong_function_args(name, 3, args.len(), meta)); } let arg_1 = &mut args[1]; ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Sint, 4)?; @@ -537,10 +547,10 @@ impl Parser { body, ))) } else { - Err(ErrorKind::SemanticError( + Err(Error { + kind: ErrorKind::SemanticError("Bad call to texelFetch".into()), meta, - "Bad call to texelFetch".into(), - )) + }) } } "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" @@ -548,7 +558,7 @@ impl Parser { | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" | "log" | "log2" | "length" | "determinant" | "bitCount" | "bitfieldReverse" => { if args.len() != 1 { - return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); + return Err(Error::wrong_function_args(name, 1, args.len(), meta)); } Ok(Some(ctx.add_expression( Expression::Math { @@ -604,13 +614,13 @@ impl Parser { arg1: Some(args[1].0), arg2: None, }, - _ => return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)), + _ => return Err(Error::wrong_function_args(name, 2, args.len(), meta)), }; Ok(Some(ctx.add_expression(expr, body))) } "mod" => { if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + return Err(Error::wrong_function_args(name, 2, args.len(), meta)); } let (mut left, left_meta) = args[0]; @@ -629,7 +639,7 @@ impl Parser { } "min" | "max" => { if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + return Err(Error::wrong_function_args(name, 2, args.len(), meta)); } let (mut arg0, arg0_meta) = args[0]; @@ -661,7 +671,7 @@ impl Parser { "pow" | "dot" | "reflect" | "cross" | "outerProduct" | "distance" | "step" | "modf" | "frexp" | "ldexp" => { if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + return Err(Error::wrong_function_args(name, 2, args.len(), meta)); } let (mut arg0, arg0_meta) = args[0]; @@ -693,7 +703,7 @@ impl Parser { } "mix" => { if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + return Err(Error::wrong_function_args(name, 3, args.len(), meta)); } let (mut arg, arg_meta) = args[0]; @@ -763,7 +773,7 @@ impl Parser { } "clamp" => { if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + return Err(Error::wrong_function_args(name, 3, args.len(), meta)); } let (mut arg0, arg0_meta) = args[0]; @@ -794,7 +804,7 @@ impl Parser { } "faceforward" | "refract" | "fma" | "smoothstep" => { if args.len() != 3 { - return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta)); + return Err(Error::wrong_function_args(name, 3, args.len(), meta)); } Ok(Some(ctx.add_expression( Expression::Math { @@ -815,7 +825,7 @@ impl Parser { "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" | "notEqual" => { if args.len() != 2 { - return Err(ErrorKind::wrong_function_args(name, 2, args.len(), meta)); + return Err(Error::wrong_function_args(name, 2, args.len(), meta)); } Ok(Some(ctx.add_expression( Expression::Binary { @@ -848,8 +858,9 @@ impl Parser { )) } _ => { - let declarations = self.lookup_function.get(&name).ok_or_else(|| { - ErrorKind::SemanticError(meta, format!("Unknown function '{}'", name).into()) + let declarations = self.lookup_function.get(&name).ok_or_else(|| Error { + kind: ErrorKind::SemanticError(format!("Unknown function '{}'", name).into()), + meta, })?; let mut maybe_decl = None; @@ -866,7 +877,7 @@ impl Parser { decl.parameters.iter().enumerate().zip(args.iter()) { if decl.parameters_info[i].depth { - sampled_to_depth(&mut self.module, ctx, *call_arg)?; + sampled_to_depth(&mut self.module, ctx, *call_arg, &mut self.errors)?; self.invalidate_expression(ctx, call_arg.0, call_arg.1)? } @@ -935,14 +946,17 @@ impl Parser { } if ambiguous { - return Err(ErrorKind::SemanticError( + self.errors.push(Error { + kind: ErrorKind::SemanticError( + format!("Ambiguous best function for '{}'", name).into(), + ), meta, - format!("Ambiguous best function for '{}'", name).into(), - )); + }) } - let decl = maybe_decl.ok_or_else(|| { - ErrorKind::SemanticError(meta, format!("Unknown function '{}'", name).into()) + let decl = maybe_decl.ok_or_else(|| Error { + kind: ErrorKind::SemanticError(format!("Unknown function '{}'", name).into()), + meta, })?; let parameters_info = decl.parameters_info.clone(); @@ -963,7 +977,7 @@ impl Parser { *self.resolve_type(ctx, handle, meta)? { if parameter_info.qualifier.is_lhs() - && matches!(*ctx.get_expression(handle), Expression::Swizzle { .. }) + && matches!(ctx[handle], Expression::Swizzle { .. }) { let ty = self.module.types.fetch_or_append(Type { name: None, @@ -1047,9 +1061,9 @@ impl Parser { args: &[(Handle, SourceMetadata)], fun: RelationalFunction, meta: SourceMetadata, - ) -> Result, ErrorKind> { + ) -> Result> { if args.len() != 1 { - return Err(ErrorKind::wrong_function_args(name, 1, args.len(), meta)); + return Err(Error::wrong_function_args(name, 1, args.len(), meta)); } Ok(ctx.add_expression( @@ -1068,7 +1082,7 @@ impl Parser { result: Option, mut body: Block, meta: SourceMetadata, - ) -> Result<(), ErrorKind> { + ) { ensure_block_returns(&mut body); let void = result.is_none(); @@ -1113,16 +1127,16 @@ impl Parser { } if decl.defined { - return Err(ErrorKind::SemanticError( + return self.errors.push(Error { + kind: ErrorKind::SemanticError("Function already defined".into()), meta, - "Function already defined".into(), - )); + }); } decl.defined = true; decl.parameters_info = parameters_info; *self.module.functions.get_mut(decl.handle) = function; - return Ok(()); + return; } let handle = module.functions.append(function); @@ -1133,8 +1147,6 @@ impl Parser { defined: true, void, }); - - Ok(()) } pub fn add_prototype( @@ -1143,7 +1155,7 @@ impl Parser { name: String, result: Option, meta: SourceMetadata, - ) -> Result<(), ErrorKind> { + ) { let void = result.is_none(); let &mut Parser { @@ -1181,10 +1193,10 @@ impl Parser { } } - return Err(ErrorKind::SemanticError( + return self.errors.push(Error { + kind: ErrorKind::SemanticError("Prototype already defined".into()), meta, - "Prototype already defined".into(), - )); + }); } let handle = module.functions.append(function); @@ -1195,8 +1207,6 @@ impl Parser { defined: false, void, }); - - Ok(()) } pub fn add_entry_point( @@ -1204,7 +1214,7 @@ impl Parser { function: Handle, mut global_init_body: Block, mut expressions: Arena, - ) -> Result<(), ErrorKind> { + ) { let mut arguments = Vec::new(); let mut body = Block::with_capacity( // global init body @@ -1305,8 +1315,6 @@ impl Parser { ..Default::default() }, }); - - Ok(()) } /// Helper function for texture calls, splits the vector argument into it's components @@ -1316,7 +1324,7 @@ impl Parser { (image, image_meta): (Handle, SourceMetadata), (coord, coord_meta): (Handle, SourceMetadata), body: &mut Block, - ) -> Result { + ) -> Result { if let TypeInner::Image { dim, arrayed, @@ -1377,10 +1385,16 @@ impl Parser { array_index, }) } else { - Err(ErrorKind::SemanticError( - image_meta, - "Type is not an image".into(), - )) + self.errors.push(Error { + kind: ErrorKind::SemanticError("Type is not an image".into()), + meta: image_meta, + }); + + Ok(CoordComponents { + coordinate: coord, + depth_ref: None, + array_index: None, + }) } } } @@ -1391,7 +1405,8 @@ fn sampled_to_depth( module: &mut Module, ctx: &mut Context, (image, meta): (Handle, SourceMetadata), -) -> Result<(), ErrorKind> { + errors: &mut Vec, +) -> Result<()> { let ty = match ctx[image] { Expression::GlobalVariable(handle) => &mut module.global_variables.get_mut(handle).ty, Expression::FunctionArgument(i) => { @@ -1399,10 +1414,10 @@ fn sampled_to_depth( &mut ctx.arguments[i as usize].ty } _ => { - return Err(ErrorKind::SemanticError( + return Err(Error { + kind: ErrorKind::SemanticError("Not a valid texture expression".into()), meta, - "Not a valid texture expression".into(), - )) + }) } }; match module.types[*ty].inner { @@ -1422,9 +1437,15 @@ fn sampled_to_depth( }) } ImageClass::Depth { .. } => {} - _ => return Err(ErrorKind::SemanticError(meta, "Not a texture".into())), + _ => errors.push(Error { + kind: ErrorKind::SemanticError("Not a texture".into()), + meta, + }), }, - _ => return Err(ErrorKind::SemanticError(meta, "Not a texture".into())), + _ => errors.push(Error { + kind: ErrorKind::SemanticError("Not a texture".into()), + meta, + }), }; Ok(()) diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 2d9f0725d..9e68f68f6 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,5 +1,5 @@ pub use ast::Profile; -pub use error::{ErrorKind, ParseError}; +pub use error::{Error, ErrorKind}; pub use token::{SourceMetadata, Token}; use crate::{FastHashMap, FastHashSet, Handle, Module, ShaderStage, Type}; @@ -20,7 +20,7 @@ mod token; mod types; mod variables; -type Result = std::result::Result; +type Result = std::result::Result; pub struct Options { pub stage: ShaderStage, @@ -74,7 +74,7 @@ pub struct Parser { entry_args: Vec, - errors: Vec, + errors: Vec, module: Module, } @@ -97,14 +97,14 @@ impl Parser { &mut self, options: &Options, source: &str, - ) -> std::result::Result> { + ) -> std::result::Result> { self.reset(options.stage); let lexer = lex::Lexer::new(source, &options.defines); let mut ctx = ParsingContext::new(lexer); - if let Err(kind) = ctx.parse(self) { - self.errors.push(ParseError { kind }); + if let Err(e) = ctx.parse(self) { + self.errors.push(e); } if self.errors.is_empty() { diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 72aa9570d..698aeab35 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -8,7 +8,11 @@ //! The OpenGl spec (the layout rules are defined by the OpenGl spec in section //! 7.6.2.2 as opposed to the GLSL spec) uses the term basic machine units which are //! equivalent to bytes. -use super::{ast::StructLayout, error::ErrorKind, SourceMetadata}; +use super::{ + ast::StructLayout, + error::{Error, ErrorKind}, + SourceMetadata, +}; use crate::{Arena, Constant, Handle, Type, TypeInner}; /// Struct with information needed for defining a struct member. @@ -37,7 +41,8 @@ pub fn calculate_offset( layout: StructLayout, types: &mut Arena, constants: &Arena, -) -> Result { + errors: &mut Vec, +) -> TypeAlignSpan { // When using the std430 storage layout, shader storage blocks will be laid out in buffer storage // identically to uniform and shader storage blocks using the std140 layout, except // that the base alignment and stride of arrays of scalars and vectors in rule 4 and of @@ -60,7 +65,7 @@ pub fn calculate_offset( // to rules (1), (2), and (3), and rounded up to the base alignment of a vec4. // TODO: Matrices array TypeInner::Array { base, size, .. } => { - let info = calculate_offset(base, meta, layout, types, constants)?; + let info = calculate_offset(base, meta, layout, types, constants, errors); let name = types[ty].name.clone(); let mut align = info.align; @@ -122,7 +127,7 @@ pub fn calculate_offset( let name = types[ty].name.clone(); for member in members.iter_mut() { - let info = calculate_offset(member.ty, meta, layout, types, constants)?; + let info = calculate_offset(member.ty, meta, layout, types, constants, errors); span = align_up(span, info.align); align = align.max(info.align); @@ -145,14 +150,15 @@ pub fn calculate_offset( (align, span) } _ => { - return Err(ErrorKind::SemanticError( + errors.push(Error { + kind: ErrorKind::SemanticError("Invalid struct member type".into()), meta, - "Invalid struct member type".into(), - )) + }); + (0, 0) } }; - Ok(TypeAlignSpan { ty, align, span }) + TypeAlignSpan { ty, align, span } } /// Helper function used for aligning `value` to the next multiple of `align` diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 09752df98..cde62531e 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -9,7 +9,7 @@ use crate::{ token::{Directive, DirectiveKind}, token::{SourceMetadata, Token, TokenValue}, variables::{GlobalOrConstant, VarDeclaration}, - ParseError, Parser, Result, + Error, Parser, Result, }, Block, Constant, ConstantInner, Expression, ScalarValue, Type, }; @@ -24,12 +24,14 @@ mod types; pub struct ParsingContext<'source> { lexer: Peekable>, + last_meta: SourceMetadata, } impl<'source> ParsingContext<'source> { pub fn new(lexer: Lexer<'source>) -> Self { ParsingContext { lexer: lexer.peekable(), + last_meta: SourceMetadata::none(), } } @@ -38,10 +40,10 @@ impl<'source> ParsingContext<'source> { match token.value { TokenValue::Identifier(name) => Ok((name, token.meta)), - _ => Err(ErrorKind::InvalidToken( - token, - vec![ExpectedToken::Identifier], - )), + _ => Err(Error { + kind: ErrorKind::InvalidToken(token.value, vec![ExpectedToken::Identifier]), + meta: token.meta, + }), } } @@ -49,7 +51,10 @@ impl<'source> ParsingContext<'source> { let token = self.bump(parser)?; if token.value != value { - Err(ErrorKind::InvalidToken(token, vec![value.into()])) + Err(Error { + kind: ErrorKind::InvalidToken(token.value, vec![value.into()]), + meta: token.meta, + }) } else { Ok(token) } @@ -60,19 +65,26 @@ impl<'source> ParsingContext<'source> { let res = self.lexer.next()?; match res.kind { - LexerResultKind::Token(token) => break Some(token), + LexerResultKind::Token(token) => { + self.last_meta = token.meta; + break Some(token); + } LexerResultKind::Directive(directive) => { parser.handle_directive(directive, res.meta) } - LexerResultKind::Error(error) => parser.errors.push(ParseError { - kind: ErrorKind::PreprocessorError(res.meta, error), + LexerResultKind::Error(error) => parser.errors.push(Error { + kind: ErrorKind::PreprocessorError(error), + meta: res.meta, }), } } } pub fn bump(&mut self, parser: &mut Parser) -> Result { - self.next(parser).ok_or(ErrorKind::EndOfFile) + self.next(parser).ok_or(Error { + kind: ErrorKind::EndOfFile, + meta: self.last_meta, + }) } /// Returns None on the end of the file rather than an error like other methods @@ -101,8 +113,9 @@ impl<'source> ParsingContext<'source> { LexerResultKind::Directive(directive) => { parser.handle_directive(directive, res.meta) } - LexerResultKind::Error(error) => parser.errors.push(ParseError { - kind: ErrorKind::PreprocessorError(res.meta, error), + LexerResultKind::Error(error) => parser.errors.push(Error { + kind: ErrorKind::PreprocessorError(error), + meta: res.meta, }), _ => unreachable!(), } @@ -113,7 +126,11 @@ impl<'source> ParsingContext<'source> { } pub fn expect_peek(&mut self, parser: &mut Parser) -> Result<&Token> { - self.peek(parser).ok_or(ErrorKind::EndOfFile) + let meta = self.last_meta; + self.peek(parser).ok_or(Error { + kind: ErrorKind::EndOfFile, + meta, + }) } pub fn parse(&mut self, parser: &mut Parser) -> Result<()> { @@ -125,20 +142,18 @@ impl<'source> ParsingContext<'source> { self.parse_external_declaration(parser, &mut ctx, &mut body)?; } - let handle = parser - .lookup_function - .get("main") - .and_then(|declarations| { - declarations - .iter() - .find(|decl| decl.defined && decl.parameters.is_empty()) - .map(|decl| decl.handle) - }) - .ok_or_else(|| { - ErrorKind::SemanticError(SourceMetadata::default(), "Missing entry point".into()) - })?; - - parser.add_entry_point(handle, body, ctx.expressions)?; + match parser.lookup_function.get("main").and_then(|declarations| { + declarations + .iter() + .find(|decl| decl.defined && decl.parameters.is_empty()) + .map(|decl| decl.handle) + }) { + Some(handle) => parser.add_entry_point(handle, body, ctx.expressions), + None => parser.errors.push(Error { + kind: ErrorKind::SemanticError("Missing entry point".into()), + meta: SourceMetadata::none(), + }), + } Ok(()) } @@ -150,18 +165,24 @@ impl<'source> ParsingContext<'source> { ConstantInner::Scalar { value: ScalarValue::Uint(int), .. - } => u32::try_from(int) - .map_err(|_| ErrorKind::SemanticError(meta, "int constant overflows".into())), + } => u32::try_from(int).map_err(|_| Error { + kind: ErrorKind::SemanticError("int constant overflows".into()), + meta, + })?, ConstantInner::Scalar { value: ScalarValue::Sint(int), .. - } => u32::try_from(int) - .map_err(|_| ErrorKind::SemanticError(meta, "int constant overflows".into())), - _ => Err(ErrorKind::SemanticError( + } => u32::try_from(int).map_err(|_| Error { + kind: ErrorKind::SemanticError("int constant overflows".into()), meta, - "Expected a uint constant".into(), - )), - }?; + })?, + _ => { + return Err(Error { + kind: ErrorKind::SemanticError("Expected a uint constant".into()), + meta, + }) + } + }; Ok((int, meta)) } @@ -188,11 +209,11 @@ impl Parser { match directive.kind { DirectiveKind::Version { is_first_directive } => { if !is_first_directive { - self.errors.push(ParseError { + self.errors.push(Error { kind: ErrorKind::SemanticError( - meta, "#version must occur first in shader".into(), ), + meta, }) } @@ -202,21 +223,20 @@ impl Parser { location, }) => match int.value { 440 | 450 | 460 => self.meta.version = int.value as u16, - _ => self.errors.push(ParseError { - kind: ErrorKind::InvalidVersion(location.into(), int.value), + _ => self.errors.push(Error { + kind: ErrorKind::InvalidVersion(int.value), + meta: location.into(), }), }, - Some(PPToken { value, location }) => self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - location.into(), - PreprocessorError::UnexpectedToken(value), - ), + Some(PPToken { value, location }) => self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken( + value, + )), + meta: location.into(), }), - None => self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - meta, - PreprocessorError::UnexpectedNewLine, - ), + None => self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedNewLine), + meta, }), }; @@ -226,25 +246,26 @@ impl Parser { location, }) => match name.as_str() { "core" => self.meta.profile = Profile::Core, - _ => self.errors.push(ParseError { - kind: ErrorKind::InvalidProfile(location.into(), name), + _ => self.errors.push(Error { + kind: ErrorKind::InvalidProfile(name), + meta: location.into(), }), }, - Some(PPToken { value, location }) => self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - location.into(), - PreprocessorError::UnexpectedToken(value), - ), + Some(PPToken { value, location }) => self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken( + value, + )), + meta: location.into(), }), None => {} }; if let Some(PPToken { value, location }) = tokens.next() { - self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - location.into(), - PreprocessorError::UnexpectedToken(value), - ), + self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken( + value, + )), + meta: location.into(), }) } } @@ -259,21 +280,21 @@ impl Parser { .. }) => Some(name), Some(PPToken { value, location }) => { - self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - location.into(), - PreprocessorError::UnexpectedToken(value), - ), + self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken( + value, + )), + meta: location.into(), }); None } None => { - self.errors.push(ParseError { + self.errors.push(Error { kind: ErrorKind::PreprocessorError( - meta, PreprocessorError::UnexpectedNewLine, ), + meta, }); None @@ -285,17 +306,15 @@ impl Parser { value: PPTokenValue::Punct(pp_rs::token::Punct::Colon), .. }) => {} - Some(PPToken { value, location }) => self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - location.into(), - PreprocessorError::UnexpectedToken(value), - ), + Some(PPToken { value, location }) => self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken( + value, + )), + meta: location.into(), }), - None => self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - meta, - PreprocessorError::UnexpectedNewLine, - ), + None => self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedNewLine), + meta, }), }; @@ -309,33 +328,31 @@ impl Parser { self.meta.extensions.insert(name); } } - _ => self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - location.into(), - PreprocessorError::UnexpectedToken(PPTokenValue::Ident(behavior)), - ), + _ => self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken( + PPTokenValue::Ident(behavior), + )), + meta: location.into(), }), }, - Some(PPToken { value, location }) => self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - location.into(), - PreprocessorError::UnexpectedToken(value), - ), + Some(PPToken { value, location }) => self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken( + value, + )), + meta: location.into(), }), - None => self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - meta, - PreprocessorError::UnexpectedNewLine, - ), + None => self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedNewLine), + meta, }), } if let Some(PPToken { value, location }) = tokens.next() { - self.errors.push(ParseError { - kind: ErrorKind::PreprocessorError( - location.into(), - PreprocessorError::UnexpectedToken(value), - ), + self.errors.push(Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken( + value, + )), + meta: location.into(), }) } } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index f74cd15ae..6e543c431 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -10,7 +10,7 @@ use crate::{ token::TokenValue, types::scalar_components, variables::{GlobalOrConstant, VarDeclaration}, - ErrorKind, Parser, SourceMetadata, Token, + Error, ErrorKind, Parser, SourceMetadata, Token, }, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StorageClass, StructMember, Type, TypeInner, @@ -34,7 +34,10 @@ impl<'source> ParsingContext<'source> { 460 => vec![TokenValue::Semicolon.into(), ExpectedToken::Eof], _ => vec![ExpectedToken::Eof], }; - Err(ErrorKind::InvalidToken(token, expected)) + Err(Error { + kind: ErrorKind::InvalidToken(token.value, expected), + meta: token.meta, + }) } } } else { @@ -79,10 +82,13 @@ impl<'source> ParsingContext<'source> { break; } _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![TokenValue::Comma.into(), TokenValue::RightBrace.into()], - )) + return Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![TokenValue::Comma.into(), TokenValue::RightBrace.into()], + ), + meta: token.meta, + }) } } } @@ -147,10 +153,13 @@ impl<'source> ParsingContext<'source> { TokenValue::Semicolon => break, TokenValue::Identifier(name) => name, _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], - )) + return Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], + ), + meta: token.meta, + }) } }; let mut meta = token.meta; @@ -201,10 +210,13 @@ impl<'source> ParsingContext<'source> { TokenValue::Semicolon => break, TokenValue::Comma => {} _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![TokenValue::Comma.into(), TokenValue::Semicolon.into()], - )) + return Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![TokenValue::Comma.into(), TokenValue::Semicolon.into()], + ), + meta: token.meta, + }) } } } @@ -261,7 +273,7 @@ impl<'source> ParsingContext<'source> { return match token.value { TokenValue::Semicolon => { // This branch handles function prototypes - parser.add_prototype(context, name, result, meta)?; + parser.add_prototype(context, name, result, meta); Ok(true) } @@ -273,21 +285,27 @@ impl<'source> ParsingContext<'source> { // parse the body self.parse_compound_statement(parser, &mut context, &mut body)?; - parser.add_function(context, name, result, body, meta)?; + parser.add_function(context, name, result, body, meta); Ok(true) } - _ if external => Err(ErrorKind::InvalidToken( - token, - vec![ - TokenValue::LeftBrace.into(), - TokenValue::Semicolon.into(), - ], - )), - _ => Err(ErrorKind::InvalidToken( - token, - vec![TokenValue::Semicolon.into()], - )), + _ if external => Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![ + TokenValue::LeftBrace.into(), + TokenValue::Semicolon.into(), + ], + ), + meta: token.meta, + }), + _ => Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![TokenValue::Semicolon.into()], + ), + meta: token.meta, + }), }; } // Pass the token to the init_declator_list parser @@ -313,10 +331,10 @@ impl<'source> ParsingContext<'source> { self.parse_init_declarator_list(parser, ty, Some(token_fallthrough), &mut ctx)?; } else { - return Err(ErrorKind::SemanticError( + parser.errors.push(Error { + kind: ErrorKind::SemanticError("Declaration cannot have void type".into()), meta, - "Declaration cannot have void type".into(), - )); + }) } Ok(true) @@ -341,7 +359,10 @@ impl<'source> ParsingContext<'source> { //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON - Err(ErrorKind::NotImplemented(token.meta, "variable qualifier")) + Err(Error { + kind: ErrorKind::NotImplemented("variable qualifier"), + meta: token.meta, + }) } } TokenValue::Semicolon => { @@ -359,20 +380,25 @@ impl<'source> ParsingContext<'source> { // layout(early_fragment_tests) in; } _ => { - return Err(ErrorKind::SemanticError( + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "Qualifier not supported as standalone".into(), + ), meta, - "Qualifier not supported as standalone".into(), - )); + }); } } } Ok(true) } - _ => Err(ErrorKind::InvalidToken( - token, - vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], - )), + _ => Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], + ), + meta: token.meta, + }), } } } else { @@ -385,14 +411,17 @@ impl<'source> ParsingContext<'source> { let _ = match token.value { TokenValue::PrecisionQualifier(p) => p, _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ - TokenValue::PrecisionQualifier(Precision::High).into(), - TokenValue::PrecisionQualifier(Precision::Medium).into(), - TokenValue::PrecisionQualifier(Precision::Low).into(), - ], - )) + return Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![ + TokenValue::PrecisionQualifier(Precision::High).into(), + TokenValue::PrecisionQualifier(Precision::Medium).into(), + TokenValue::PrecisionQualifier(Precision::Low).into(), + ], + ), + meta: token.meta, + }) } }; @@ -407,12 +436,12 @@ impl<'source> ParsingContext<'source> { kind: ScalarKind::Sint, .. } => {} - _ => { - return Err(ErrorKind::SemanticError( - meta, + _ => parser.errors.push(Error { + kind: ErrorKind::SemanticError( "Precision statement can only work on floats and ints".into(), - )) - } + ), + meta, + }), } self.expect(parser, TokenValue::Semicolon)?; @@ -485,10 +514,13 @@ impl<'source> ParsingContext<'source> { Some(name) } _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], - )) + return Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], + ), + meta: token.meta, + }) } }; meta = meta.union(&token.meta); @@ -555,7 +587,8 @@ impl<'source> ParsingContext<'source> { layout, &mut parser.module.types, &parser.module.constants, - )?; + &mut parser.errors, + ); span = offset::align_up(span, info.align); align = align.max(info.align); diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 8f119eaaa..f0d98dd2a 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -5,7 +5,7 @@ use crate::{ error::{ErrorKind, ExpectedToken}, parser::ParsingContext, token::{Token, TokenValue}, - Parser, Result, SourceMetadata, + Error, Parser, Result, SourceMetadata, }, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Handle, ScalarValue, Type, TypeInner, UnaryOperator, @@ -43,15 +43,18 @@ impl<'source> ParsingContext<'source> { return Ok(expr); } _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ - TokenValue::LeftParen.into(), - ExpectedToken::IntLiteral, - ExpectedToken::FloatLiteral, - ExpectedToken::BoolLiteral, - ], - )) + return Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![ + TokenValue::LeftParen.into(), + ExpectedToken::IntLiteral, + ExpectedToken::FloatLiteral, + ExpectedToken::BoolLiteral, + ], + ), + meta: token.meta, + }); } }; @@ -89,10 +92,13 @@ impl<'source> ParsingContext<'source> { break; } _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![TokenValue::Comma.into(), TokenValue::RightParen.into()], - )) + return Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![TokenValue::Comma.into(), TokenValue::RightParen.into()], + ), + meta: token.meta, + }); } } } @@ -124,9 +130,14 @@ impl<'source> ParsingContext<'source> { meta, } } else { - let var = match parser.lookup_variable(ctx, body, &name)? { + let var = match parser.lookup_variable(ctx, body, &name) { Some(var) => var, - None => return Err(ErrorKind::UnknownVariable(meta, name)), + None => { + return Err(Error { + kind: ErrorKind::UnknownVariable(name), + meta, + }) + } }; HirExpr { diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 9e1db2b89..31bd585a1 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -1,7 +1,7 @@ use crate::{ front::glsl::{ ast::ParameterQualifier, context::Context, parser::ParsingContext, token::TokenValue, - variables::VarDeclaration, ErrorKind, Parser, Result, Token, + variables::VarDeclaration, Error, ErrorKind, Parser, Result, Token, }, Block, ConstantInner, Expression, ScalarValue, Statement, SwitchCase, UnaryOperator, }; @@ -147,10 +147,14 @@ impl<'source> ParsingContext<'source> { .. } => int as i32, _ => { - return Err(ErrorKind::SemanticError( + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "Case values can only be integers".into(), + ), meta, - "Case values can only be integers".into(), - )) + }); + + 0 } } }; @@ -189,10 +193,13 @@ impl<'source> ParsingContext<'source> { self.expect(parser, TokenValue::Colon)?; if !default.is_empty() { - return Err(ErrorKind::SemanticError( + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "Can only have one default case per switch statement" + .into(), + ), meta, - "Can only have one default case per switch statement".into(), - )); + }); } loop { @@ -214,14 +221,18 @@ impl<'source> ParsingContext<'source> { break; } _ => { - return Err(ErrorKind::InvalidToken( - self.bump(parser)?, - vec![ - TokenValue::Case.into(), - TokenValue::Default.into(), - TokenValue::RightBrace.into(), - ], - )) + let Token { value, meta } = self.bump(parser)?; + return Err(Error { + kind: ErrorKind::InvalidToken( + value, + vec![ + TokenValue::Case.into(), + TokenValue::Default.into(), + TokenValue::RightBrace.into(), + ], + ), + meta, + }); } } } diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 9ee12a0f0..a575f5cb8 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -4,9 +4,9 @@ use crate::{ error::ExpectedToken, parser::ParsingContext, token::{SourceMetadata, TokenValue}, - ErrorKind, Parser, Result, + Error, ErrorKind, Parser, Result, }, - ArraySize, Handle, ResourceBinding, StorageClass, Type, TypeInner, + ArraySize, Handle, StorageClass, Type, TypeInner, }; impl<'source> ParsingContext<'source> { @@ -55,17 +55,25 @@ impl<'source> ParsingContext<'source> { } TokenValue::Identifier(ident) => match parser.lookup_type.get(&ident) { Some(ty) => Some(*ty), - None => return Err(ErrorKind::UnknownType(token.meta, ident)), + None => { + return Err(Error { + kind: ErrorKind::UnknownType(ident), + meta: token.meta, + }) + } }, _ => { - return Err(ErrorKind::InvalidToken( - token, - vec![ - TokenValue::Void.into(), - TokenValue::Struct.into(), - ExpectedToken::TypeName, - ], - )) + return Err(Error { + kind: ErrorKind::InvalidToken( + token.value, + vec![ + TokenValue::Void.into(), + TokenValue::Struct.into(), + ExpectedToken::TypeName, + ], + ), + meta: token.meta, + }); } }; @@ -78,8 +86,10 @@ impl<'source> ParsingContext<'source> { parser: &mut Parser, ) -> Result<(Handle, SourceMetadata)> { let (maybe_ty, meta) = self.parse_type(parser)?; - let ty = - maybe_ty.ok_or_else(|| ErrorKind::SemanticError(meta, "Type can't be void".into()))?; + let ty = maybe_ty.ok_or_else(|| Error { + kind: ErrorKind::SemanticError("Type can't be void".into()), + meta, + })?; Ok((ty, meta)) } @@ -148,13 +158,9 @@ impl<'source> ParsingContext<'source> { parser: &mut Parser, qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, ) -> Result<()> { - // We need both of these to produce a ResourceBinding - let mut group = None; - let mut binding = None; - self.expect(parser, TokenValue::LeftParen)?; loop { - self.parse_layout_qualifier_id(parser, qualifiers, &mut group, &mut binding)?; + self.parse_layout_qualifier_id(parser, qualifiers)?; if self.bump_if(parser, TokenValue::Comma).is_some() { continue; @@ -164,27 +170,6 @@ impl<'source> ParsingContext<'source> { } self.expect(parser, TokenValue::RightParen)?; - match (group, binding) { - (Some((group, group_meta)), Some((binding, binding_meta))) => qualifiers.push(( - TypeQualifier::ResourceBinding(ResourceBinding { group, binding }), - group_meta.union(&binding_meta), - )), - // Produce an error if we have one of group or binding but not the other - (Some((_, meta)), None) => { - return Err(ErrorKind::SemanticError( - meta, - "set specified with no binding".into(), - )) - } - (None, Some((_, meta))) => { - return Err(ErrorKind::SemanticError( - meta, - "binding specified with no set".into(), - )) - } - (None, None) => (), - } - Ok(()) } @@ -192,8 +177,6 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, - group: &mut Option<(u32, SourceMetadata)>, - binding: &mut Option<(u32, SourceMetadata)>, ) -> Result<()> { // layout_qualifier_id: // IDENTIFIER @@ -209,52 +192,60 @@ impl<'source> ParsingContext<'source> { qualifiers.push(( match name.as_str() { "location" => TypeQualifier::Location(value), - "set" => { - *group = Some((value, end_meta)); - return Ok(()); - } - "binding" => { - *binding = Some((value, end_meta)); - return Ok(()); - } + "set" => TypeQualifier::Set(value), + "binding" => TypeQualifier::Binding(value), "local_size_x" => TypeQualifier::WorkGroupSize(0, value), "local_size_y" => TypeQualifier::WorkGroupSize(1, value), "local_size_z" => TypeQualifier::WorkGroupSize(2, value), - _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), + _ => { + parser.errors.push(Error { + kind: ErrorKind::UnknownLayoutQualifier(name), + meta: token.meta, + }); + return Ok(()); + } }, token.meta, )) } else { - match name.as_str() { - "push_constant" => { - qualifiers.push(( - TypeQualifier::StorageQualifier(StorageQualifier::StorageClass( - StorageClass::PushConstant, - )), - token.meta, - )); - qualifiers - .push((TypeQualifier::Layout(StructLayout::Std430), token.meta)); - } - "std140" => qualifiers - .push((TypeQualifier::Layout(StructLayout::Std140), token.meta)), - "std430" => qualifiers - .push((TypeQualifier::Layout(StructLayout::Std430), token.meta)), - "early_fragment_tests" => { - qualifiers.push((TypeQualifier::EarlyFragmentTests, token.meta)) - } - _ => return Err(ErrorKind::UnknownLayoutQualifier(token.meta, name)), - } + qualifiers.push(( + match name.as_str() { + "push_constant" => { + qualifiers.push(( + TypeQualifier::Layout(StructLayout::Std430), + token.meta, + )); + qualifiers.push(( + TypeQualifier::StorageQualifier( + StorageQualifier::StorageClass(StorageClass::PushConstant), + ), + token.meta, + )); + return Ok(()); + } + "std140" => TypeQualifier::Layout(StructLayout::Std140), + "std430" => TypeQualifier::Layout(StructLayout::Std430), + "early_fragment_tests" => TypeQualifier::EarlyFragmentTests, + _ => { + parser.errors.push(Error { + kind: ErrorKind::UnknownLayoutQualifier(name), + meta: token.meta, + }); + return Ok(()); + } + }, + token.meta, + )); }; - - Ok(()) } // TODO: handle Shared? - _ => Err(ErrorKind::InvalidToken( - token, - vec![ExpectedToken::Identifier], - )), + _ => parser.errors.push(Error { + kind: ErrorKind::InvalidToken(token.value, vec![ExpectedToken::Identifier]), + meta: token.meta, + }), } + + Ok(()) } pub fn peek_type_name(&mut self, parser: &mut Parser) -> bool { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 282f0c042..29ea1900c 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -2,15 +2,15 @@ use crate::{ front::glsl::{ ast::Profile, error::ExpectedToken, - error::{ErrorKind, ParseError}, + error::{Error, ErrorKind}, token::TokenValue, - Options, Parser, SourceMetadata, Token, + Options, Parser, SourceMetadata, }, Module, ShaderStage, }; use pp_rs::token::PreprocessorError; -fn parse(parser: &mut Parser, source: &str, stage: ShaderStage) -> Result> { +fn parse(parser: &mut Parser, source: &str, stage: ShaderStage) -> Result> { let defines = crate::FastHashMap::default(); parser.parse(&Options { stage, defines }, source) @@ -29,8 +29,9 @@ fn version() { ) .err() .unwrap(), - vec![ParseError { - kind: ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 14 }, 99000) + vec![Error { + kind: ErrorKind::InvalidVersion(99000), + meta: SourceMetadata { start: 9, end: 14 } }], ); @@ -42,8 +43,9 @@ fn version() { ) .err() .unwrap(), - vec![ParseError { - kind: ErrorKind::InvalidVersion(SourceMetadata { start: 9, end: 12 }, 449) + vec![Error { + kind: ErrorKind::InvalidVersion(449), + meta: SourceMetadata { start: 9, end: 12 } }] ); @@ -55,8 +57,9 @@ fn version() { ) .err() .unwrap(), - vec![ParseError { - kind: ErrorKind::InvalidProfile(SourceMetadata { start: 13, end: 18 }, "smart".into()) + vec![Error { + kind: ErrorKind::InvalidProfile("smart".into()), + meta: SourceMetadata { start: 13, end: 18 }, }] ); @@ -69,20 +72,16 @@ fn version() { .err() .unwrap(), vec![ - ParseError { - kind: ErrorKind::PreprocessorError( - SourceMetadata { start: 27, end: 28 }, - PreprocessorError::UnexpectedHash, - ) + Error { + kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedHash,), + meta: SourceMetadata { start: 27, end: 28 }, }, - ParseError { + Error { kind: ErrorKind::InvalidToken( - Token { - value: TokenValue::Identifier("version".into()), - meta: SourceMetadata { start: 28, end: 35 } - }, + TokenValue::Identifier("version".into()), vec![ExpectedToken::Eof] - ) + ), + meta: SourceMetadata { start: 28, end: 35 } } ] ); @@ -256,7 +255,7 @@ fn declarations() { &mut parser, r#" #version 450 - layout(push_constant, set = 2, binding = 0) + layout(push_constant) uniform u_locals { vec3 model_offs; float load_time; @@ -455,14 +454,12 @@ fn functions() { ) .err() .unwrap(), - vec![ParseError { - kind: ErrorKind::SemanticError( - SourceMetadata { - start: 134, - end: 152 - }, - "Function already defined".into() - ) + vec![Error { + kind: ErrorKind::SemanticError("Function already defined".into()), + meta: SourceMetadata { + start: 134, + end: 152 + }, }] ); @@ -616,14 +613,12 @@ fn implicit_conversions() { ) .err() .unwrap(), - vec![ParseError { - kind: ErrorKind::SemanticError( - SourceMetadata { - start: 156, - end: 165 - }, - "Unknown function \'test\'".into() - ) + vec![Error { + kind: ErrorKind::SemanticError("Unknown function \'test\'".into()), + meta: SourceMetadata { + start: 156, + end: 165 + }, }] ); @@ -643,14 +638,12 @@ fn implicit_conversions() { ) .err() .unwrap(), - vec![ParseError { - kind: ErrorKind::SemanticError( - SourceMetadata { - start: 158, - end: 165 - }, - "Ambiguous best function for \'test\'".into() - ) + vec![Error { + kind: ErrorKind::SemanticError("Ambiguous best function for \'test\'".into()), + meta: SourceMetadata { + start: 158, + end: 165 + }, }] ); } diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index bcff732f9..23caa4b02 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -3,7 +3,7 @@ pub use pp_rs::token::{Float, Integer, PreprocessorError, Token as PPToken}; use super::ast::Precision; use crate::{Interpolation, Sampling, Type}; -use std::{fmt, ops::Range}; +use std::ops::Range; #[derive(Debug, Clone, Copy, Default)] #[cfg_attr(test, derive(PartialEq))] @@ -22,6 +22,10 @@ impl SourceMetadata { end: self.end.max(other.end), } } + + pub fn none() -> Self { + SourceMetadata::default() + } } impl From for SourceMetadata { @@ -141,12 +145,6 @@ pub enum TokenValue { Question, } -impl fmt::Display for Token { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self.value) - } -} - #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub struct Directive { diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index cac913792..b829b4628 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,6 +1,7 @@ use crate::{ front::glsl::{ - constants::ConstantSolver, context::Context, ErrorKind, Parser, Result, SourceMetadata, + constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, + SourceMetadata, }, proc::ResolveContext, ArraySize, Constant, Expression, Handle, ImageClass, ImageDimension, ScalarKind, Type, @@ -197,8 +198,9 @@ impl Parser { ctx.typifier .grow(handle, &ctx.expressions, &resolve_ctx) - .map_err(|error| { - ErrorKind::SemanticError(meta, format!("Can't resolve type: {:?}", error).into()) + .map_err(|error| Error { + kind: ErrorKind::SemanticError(format!("Can't resolve type: {:?}", error).into()), + meta, }) } @@ -230,8 +232,9 @@ impl Parser { ctx.typifier .invalidate(handle, &ctx.expressions, &resolve_ctx) - .map_err(|error| { - ErrorKind::SemanticError(meta, format!("Can't resolve type: {:?}", error).into()) + .map_err(|error| Error { + kind: ErrorKind::SemanticError(format!("Can't resolve type: {:?}", error).into()), + meta, }) } @@ -247,7 +250,10 @@ impl Parser { constants: &mut self.module.constants, }; - solver.solve(root).map_err(|e| (meta, e).into()) + solver.solve(root).map_err(|e| Error { + kind: e.into(), + meta, + }) } pub fn maybe_array(&mut self, base: Handle, size: Option) -> Handle { diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 3057cbd7d..11df1cd7e 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,14 +1,22 @@ use crate::{ - front::glsl::{ast::*, context::Context, error::ErrorKind, Parser, SourceMetadata}, + front::glsl::{ + ast::*, + context::Context, + error::{Error, ErrorKind}, + Parser, Result, SourceMetadata, + }, Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, Interpolation, - LocalVariable, ScalarKind, StorageAccess, StorageClass, SwizzleComponent, Type, TypeInner, - VectorSize, + LocalVariable, ResourceBinding, ScalarKind, StorageAccess, StorageClass, SwizzleComponent, + Type, TypeInner, VectorSize, }; macro_rules! qualifier_arm { - ($src:expr, $tgt:expr, $meta:expr, $msg:literal $(,)?) => {{ + ($src:expr, $tgt:expr, $meta:expr, $msg:literal, $errors:expr $(,)?) => {{ if $tgt.is_some() { - return Err(ErrorKind::SemanticError($meta, $msg.into())); + $errors.push(Error { + kind: ErrorKind::SemanticError($msg.into()), + meta: $meta, + }) } $tgt = Some($src); @@ -34,12 +42,12 @@ impl Parser { ctx: &mut Context, body: &mut Block, name: &str, - ) -> Result, ErrorKind> { + ) -> Option { if let Some(local_var) = ctx.lookup_local_var(name) { - return Ok(Some(local_var)); + return Some(local_var); } if let Some(global_var) = ctx.lookup_global_var(name) { - return Ok(Some(global_var)); + return Some(global_var); } let mut add_builtin = |inner, builtin, mutable, storage| { @@ -84,7 +92,7 @@ impl Parser { }, ); - Ok(ctx.lookup_global_var(name)) + ctx.lookup_global_var(name) }; match name { "gl_Position" => add_builtin( @@ -162,7 +170,7 @@ impl Parser { false, StorageQualifier::Input, ), - _ => Ok(None), + _ => None, } } @@ -174,7 +182,7 @@ impl Parser { expression: Handle, name: &str, meta: SourceMetadata, - ) -> Result, ErrorKind> { + ) -> Result> { let (ty, is_pointer) = match *self.resolve_type(ctx, expression, meta)? { TypeInner::Pointer { base, .. } => (&self.module.types[base].inner, true), ref ty => (ty, false), @@ -184,7 +192,10 @@ impl Parser { let index = members .iter() .position(|m| m.name == Some(name.into())) - .ok_or_else(|| ErrorKind::UnknownField(meta, name.into()))?; + .ok_or_else(|| Error { + kind: ErrorKind::UnknownField(name.into()), + meta, + })?; Ok(ctx.add_expression( Expression::AccessIndex { base: expression, @@ -215,14 +226,17 @@ impl Parser { let not_unique = (1..components.len()) .any(|i| components[i..].contains(&components[i - 1])); if not_unique { - return Err(ErrorKind::SemanticError( - meta, + self.errors.push(Error { + kind: + ErrorKind::SemanticError( format!( "swizzle cannot have duplicate components in left-hand-side expression for \"{:?}\"", name ) .into(), - )); + ), + meta , + }) } } @@ -237,7 +251,7 @@ impl Parser { size: _, vector, pattern: ref src_pattern, - } = *ctx.get_expression(expression) + } = ctx[expression] { expression = vector; for pat in &mut pattern { @@ -250,9 +264,7 @@ impl Parser { // only single element swizzle, like pos.y, just return that component. if lhs { // Because of possible nested swizzles, like pos.xy.x, we have to unwrap the potential load expr. - if let Expression::Load { ref pointer } = - *ctx.get_expression(expression) - { + if let Expression::Load { ref pointer } = ctx[expression] { expression = *pointer; } } @@ -268,10 +280,14 @@ impl Parser { 3 => VectorSize::Tri, 4 => VectorSize::Quad, _ => { - return Err(ErrorKind::SemanticError( + self.errors.push(Error { + kind: ErrorKind::SemanticError( + format!("Bad swizzle size for \"{:?}\"", name).into(), + ), meta, - format!("Bad swizzle size for \"{:?}\"", name).into(), - )); + }); + + VectorSize::Quad } }; @@ -296,16 +312,20 @@ impl Parser { body, )) } else { - Err(ErrorKind::SemanticError( + Err(Error { + kind: ErrorKind::SemanticError( + format!("Invalid swizzle for vector \"{}\"", name).into(), + ), meta, - format!("Invalid swizzle for vector \"{}\"", name).into(), - )) + }) } } - _ => Err(ErrorKind::SemanticError( + _ => Err(Error { + kind: ErrorKind::SemanticError( + format!("Can't lookup field on this type \"{}\"", name).into(), + ), meta, - format!("Can't lookup field on this type \"{}\"", name).into(), - )), + }), } } @@ -320,9 +340,10 @@ impl Parser { init, meta, }: VarDeclaration, - ) -> Result { + ) -> Result { let mut storage = StorageQualifier::StorageClass(StorageClass::Private); let mut interpolation = None; + let mut set = None; let mut binding = None; let mut location = None; let mut sampling = None; @@ -339,10 +360,12 @@ impl Parser { // Ignore the Uniform qualifier if the class was already set to PushConstant continue; } else if StorageQualifier::StorageClass(StorageClass::Private) != storage { - return Err(ErrorKind::SemanticError( + self.errors.push(Error { + kind: ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + ), meta, - "Cannot use more than one storage qualifier per declaration".into(), - )); + }); } storage = s; @@ -351,67 +374,103 @@ impl Parser { i, interpolation, meta, - "Cannot use more than one interpolation qualifier per declaration" + "Cannot use more than one interpolation qualifier per declaration", + self.errors ), - TypeQualifier::ResourceBinding(ref r) => qualifier_arm!( - r.clone(), + TypeQualifier::Binding(r) => qualifier_arm!( + r, binding, meta, - "Cannot use more than one binding per declaration" + "Cannot use more than one binding per declaration", + self.errors + ), + TypeQualifier::Set(s) => qualifier_arm!( + s, + set, + meta, + "Cannot use more than one binding per declaration", + self.errors ), TypeQualifier::Location(l) => qualifier_arm!( l, location, meta, - "Cannot use more than one binding per declaration" + "Cannot use more than one binding per declaration", + self.errors ), TypeQualifier::Sampling(s) => qualifier_arm!( s, sampling, meta, - "Cannot use more than one sampling qualifier per declaration" + "Cannot use more than one sampling qualifier per declaration", + self.errors ), TypeQualifier::Layout(ref l) => qualifier_arm!( l, layout, meta, - "Cannot use more than one layout qualifier per declaration" + "Cannot use more than one layout qualifier per declaration", + self.errors ), TypeQualifier::Precision(ref p) => qualifier_arm!( p, precision, meta, - "Cannot use more than one precision qualifier per declaration" + "Cannot use more than one precision qualifier per declaration", + self.errors ), TypeQualifier::StorageAccess(a) => access &= a, _ => { - return Err(ErrorKind::SemanticError( + self.errors.push(Error { + kind: ErrorKind::SemanticError("Qualifier not supported in globals".into()), meta, - "Qualifier not supported in globals".into(), - )); + }); } } } - if binding.is_some() && storage != StorageQualifier::StorageClass(StorageClass::Uniform) { - match storage { - StorageQualifier::StorageClass(StorageClass::PushConstant) - | StorageQualifier::StorageClass(StorageClass::Uniform) - | StorageQualifier::StorageClass(StorageClass::Storage { .. }) => {} - _ => { - return Err(ErrorKind::SemanticError( + match storage { + StorageQualifier::StorageClass(StorageClass::PushConstant) => { + if set.is_some() { + self.errors.push(Error { + kind: ErrorKind::SemanticError( + "set cannot be used to decorate push constant".into(), + ), meta, - "binding requires uniform or buffer storage qualifier".into(), - )) + }) + } + } + StorageQualifier::StorageClass(StorageClass::Uniform) + | StorageQualifier::StorageClass(StorageClass::Storage { .. }) => { + if binding.is_none() { + self.errors.push(Error { + kind: ErrorKind::SemanticError( + "uniform/buffer blocks require layout(binding=X)".into(), + ), + meta, + }) + } + } + _ => { + if set.is_some() || binding.is_some() { + self.errors.push(Error { + kind: ErrorKind::SemanticError( + "set/binding can only be applied to uniform/buffer blocks".into(), + ), + meta, + }) } } } if (sampling.is_some() || interpolation.is_some()) && location.is_none() { - return Err(ErrorKind::SemanticError( + return Err(Error { + kind: ErrorKind::SemanticError( + "Sampling and interpolation qualifiers can only be used in in/out variables" + .into(), + ), meta, - "Sampling and interpolation qualifiers can only be used in in/out variables".into(), - )); + }); } if let Some(location) = location { @@ -457,8 +516,9 @@ impl Parser { return Ok(GlobalOrConstant::Global(handle)); } else if let StorageQualifier::Const = storage { - let init = init.ok_or_else(|| { - ErrorKind::SemanticError(meta, "const values must have an initializer".into()) + let init = init.ok_or_else(|| Error { + kind: ErrorKind::SemanticError("const values must have an initializer".into()), + meta, })?; if let Some(name) = name { let lookup = GlobalLookup { @@ -491,7 +551,10 @@ impl Parser { let handle = self.module.global_variables.append(GlobalVariable { name: name.clone(), class, - binding, + binding: binding.map(|binding| ResourceBinding { + group: set.unwrap_or(0), + binding, + }), ty, init, }); @@ -522,11 +585,14 @@ impl Parser { init, meta, }: VarDeclaration, - ) -> Result, ErrorKind> { + ) -> Result> { #[cfg(feature = "glsl-validate")] if let Some(ref name) = name { if ctx.lookup_local_var_current_scope(name).is_some() { - return Err(ErrorKind::VariableAlreadyDeclared(meta, name.clone())); + self.errors.push(Error { + kind: ErrorKind::VariableAlreadyDeclared(name.clone()), + meta, + }) } } @@ -537,10 +603,13 @@ impl Parser { match *qualifier { TypeQualifier::StorageQualifier(StorageQualifier::Const) => { if !mutable { - return Err(ErrorKind::SemanticError( + self.errors.push(Error { + kind: ErrorKind::SemanticError( + "Cannot use more than one constant qualifier per declaration" + .into(), + ), meta, - "Cannot use more than one constant qualifier per declaration".into(), - )); + }) } mutable = false; @@ -549,14 +618,13 @@ impl Parser { p, precision, meta, - "Cannot use more than one precision qualifier per declaration" + "Cannot use more than one precision qualifier per declaration", + self.errors ), - _ => { - return Err(ErrorKind::SemanticError( - meta, - "Qualifier not supported in locals".into(), - )); - } + _ => self.errors.push(Error { + kind: ErrorKind::SemanticError("Qualifier not supported in locals".into()), + meta, + }), } } diff --git a/tests/in/glsl/800-out-of-bounds-panic.vert b/tests/in/glsl/800-out-of-bounds-panic.vert index babca1668..e689d2676 100644 --- a/tests/in/glsl/800-out-of-bounds-panic.vert +++ b/tests/in/glsl/800-out-of-bounds-panic.vert @@ -21,6 +21,5 @@ layout(location = 0) out vec4 frag_color; void main() { frag_color = color; gl_Position = view_matrix * world_matrix * vec4(position, 0.0, 1.0); - // TODO: https://github.com/gfx-rs/naga/issues/901 - // gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0; + gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0; } diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index 84a5e065d..6046dc3f4 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -28,6 +28,9 @@ fn main1() { let _e10: mat4x4 = global1.world_matrix; let _e12: vec2 = position1; gl_Position = ((_e9 * _e10) * vec4(_e12, 0.0, 1.0)); + let _e18: vec4 = gl_Position; + let _e20: vec4 = gl_Position; + gl_Position.z = ((_e18.z + _e20.w) / 2.0); return; } From 48a4a9b9022a4e10543e6762949b6de49795f32d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 8 Aug 2021 00:21:34 +0100 Subject: [PATCH 1199/2212] [glsl-in] Cleanup public api --- src/front/glsl/functions.rs | 10 +++++----- src/front/glsl/mod.rs | 6 +++--- src/front/glsl/parser/declarations.rs | 4 ++-- src/front/glsl/parser/functions.rs | 8 ++++++-- src/front/glsl/token.rs | 4 ++-- src/front/glsl/types.rs | 14 +++++++++----- src/front/glsl/variables.rs | 8 ++++---- 7 files changed, 31 insertions(+), 23 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index bc7ec3b1b..4be7422c9 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -39,7 +39,7 @@ impl Parser { }) } - pub fn function_or_constructor_call( + pub(crate) fn function_or_constructor_call( &mut self, ctx: &mut Context, body: &mut Block, @@ -1053,7 +1053,7 @@ impl Parser { } } - pub fn parse_relational_fun( + pub(crate) fn parse_relational_fun( &mut self, ctx: &mut Context, body: &mut Block, @@ -1075,7 +1075,7 @@ impl Parser { )) } - pub fn add_function( + pub(crate) fn add_function( &mut self, ctx: Context, name: String, @@ -1149,7 +1149,7 @@ impl Parser { }); } - pub fn add_prototype( + pub(crate) fn add_prototype( &mut self, ctx: Context, name: String, @@ -1209,7 +1209,7 @@ impl Parser { }); } - pub fn add_entry_point( + pub(crate) fn add_entry_point( &mut self, function: Handle, mut global_init_body: Block, diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 9e68f68f6..32fdf0898 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,6 +1,6 @@ -pub use ast::Profile; -pub use error::{Error, ErrorKind}; -pub use token::{SourceMetadata, Token}; +pub use ast::{Precision, Profile}; +pub use error::{Error, ErrorKind, ExpectedToken}; +pub use token::{SourceMetadata, TokenValue}; use crate::{FastHashMap, FastHashSet, Handle, Module, ShaderStage, Type}; use ast::{EntryArg, FunctionDeclaration, GlobalLookup}; diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 6e543c431..a12751794 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -7,10 +7,10 @@ use crate::{ context::Context, error::ExpectedToken, offset, - token::TokenValue, + token::{Token, TokenValue}, types::scalar_components, variables::{GlobalOrConstant, VarDeclaration}, - Error, ErrorKind, Parser, SourceMetadata, Token, + Error, ErrorKind, Parser, SourceMetadata, }, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StorageClass, StructMember, Type, TypeInner, diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 31bd585a1..24e1ac987 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -1,7 +1,11 @@ use crate::{ front::glsl::{ - ast::ParameterQualifier, context::Context, parser::ParsingContext, token::TokenValue, - variables::VarDeclaration, Error, ErrorKind, Parser, Result, Token, + ast::ParameterQualifier, + context::Context, + parser::ParsingContext, + token::{Token, TokenValue}, + variables::VarDeclaration, + Error, ErrorKind, Parser, Result, }, Block, ConstantInner, Expression, ScalarValue, Statement, SwitchCase, UnaryOperator, }; diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 23caa4b02..458a32cac 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -16,14 +16,14 @@ pub struct SourceMetadata { } impl SourceMetadata { - pub fn union(&self, other: &Self) -> Self { + pub(crate) fn union(&self, other: &Self) -> Self { SourceMetadata { start: self.start.min(other.start), end: self.end.max(other.end), } } - pub fn none() -> Self { + pub(crate) fn none() -> Self { SourceMetadata::default() } } diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index b829b4628..cc0fb04f8 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -181,7 +181,7 @@ pub fn type_power(kind: ScalarKind) -> Option { } impl Parser { - pub fn typifier_grow( + pub(crate) fn typifier_grow( &self, ctx: &mut Context, handle: Handle, @@ -204,7 +204,7 @@ impl Parser { }) } - pub fn resolve_type<'b>( + pub(crate) fn resolve_type<'b>( &'b self, ctx: &'b mut Context, handle: Handle, @@ -215,7 +215,7 @@ impl Parser { } /// Invalidates the cached type resolution for `handle` forcing a recomputation - pub fn invalidate_expression<'b>( + pub(crate) fn invalidate_expression<'b>( &'b self, ctx: &'b mut Context, handle: Handle, @@ -238,7 +238,7 @@ impl Parser { }) } - pub fn solve_constant( + pub(crate) fn solve_constant( &mut self, ctx: &Context, root: Handle, @@ -256,7 +256,11 @@ impl Parser { }) } - pub fn maybe_array(&mut self, base: Handle, size: Option) -> Handle { + pub(crate) fn maybe_array( + &mut self, + base: Handle, + size: Option, + ) -> Handle { size.map(|size| { self.module.types.fetch_or_append(Type { name: None, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 11df1cd7e..86e4b8322 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -37,7 +37,7 @@ pub enum GlobalOrConstant { } impl Parser { - pub fn lookup_variable( + pub(crate) fn lookup_variable( &mut self, ctx: &mut Context, body: &mut Block, @@ -174,7 +174,7 @@ impl Parser { } } - pub fn field_selection( + pub(crate) fn field_selection( &mut self, ctx: &mut Context, lhs: bool, @@ -329,7 +329,7 @@ impl Parser { } } - pub fn add_global_var( + pub(crate) fn add_global_var( &mut self, ctx: &mut Context, body: &mut Block, @@ -573,7 +573,7 @@ impl Parser { Ok(GlobalOrConstant::Global(handle)) } - pub fn add_local_var( + pub(crate) fn add_local_var( &mut self, ctx: &mut Context, body: &mut Block, From b0b489104508bf4c3a6162041605a6aa81f1a6d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 8 Aug 2021 14:51:37 +0100 Subject: [PATCH 1200/2212] [glsl-in] Document public api --- src/front/glsl/ast.rs | 22 +++++++++ src/front/glsl/error.rs | 33 +++++++++++++ src/front/glsl/mod.rs | 105 ++++++++++++++++++++++++++++++++++++++++ src/front/glsl/token.rs | 37 ++++++++++++++ 4 files changed, 197 insertions(+) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index c5e46a96b..b2e35741c 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -140,10 +140,30 @@ pub enum StructLayout { } // TODO: Encode precision hints in the IR +/// A precision hint used in glsl declarations +/// +/// Precision hints can be used to either speed up shader execution or control +/// the precision of arithmetic operations. +/// +/// To use a precision hint simply add it before the type in the declaration. +/// ```glsl +/// mediump float a; +/// ``` +/// +/// The default when no precision is declared is `highp` which means that all +/// operations operate with the type defined width. +/// +/// For `mediump` and `lowp` operations follow the spir-v +/// [`RelaxedPrecision`][RelaxedPrecision] decoration semantics. +/// +/// [RelaxedPrecision]: https://www.khronos.org/registry/SPIR-V/specs/unified1/SPIRV.html#_a_id_relaxedprecisionsection_a_relaxed_precision #[derive(Debug, Clone, PartialEq, Copy)] pub enum Precision { + /// `lowp` precision Low, + /// `mediump` precision Medium, + /// `highp` precision High, } @@ -165,7 +185,9 @@ impl ParameterQualifier { } } +/// The glsl profile used by a shader #[derive(Debug, Clone, Copy, PartialEq)] pub enum Profile { + /// The `core` profile, default when no profile is specified. Core, } diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index f6ce38011..3bd0c8af2 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -19,14 +19,22 @@ fn join_with_comma(list: &[ExpectedToken]) -> String { string } +/// One of the expected tokens returned in [`InvalidToken`](ErrorKind::InvalidToken) #[derive(Debug, PartialEq)] pub enum ExpectedToken { + /// A specific token was expected Token(TokenValue), + /// A type was expected TypeName, + /// An identifier was expected Identifier, + /// An integer literal was expected IntLiteral, + /// A float literal was expected FloatLiteral, + /// A boolean literal was expected BoolLiteral, + /// The end of file was expected Eof, } impl From for ExpectedToken { @@ -48,32 +56,54 @@ impl std::fmt::Display for ExpectedToken { } } +/// Information about the cause of an error #[derive(Debug, Error)] #[cfg_attr(test, derive(PartialEq))] pub enum ErrorKind { + /// Whilst parsing as encountered an unexpected EOF. #[error("Unexpected end of file")] EndOfFile, + /// The shader specified an unsupported or invalid profile. #[error("Invalid profile: {0}")] InvalidProfile(String), + /// The shader requested an unsupported or invalid version. #[error("Invalid version: {0}")] InvalidVersion(u64), + /// Whilst parsing an unexpected token was encountered. + /// + /// A list of expected tokens is also returned. #[error("Expected {}, found {0:?}", join_with_comma(.1))] InvalidToken(TokenValue, Vec), + /// A specific feature is not yet implemented. + /// + /// To help prioritize work please open an issue in the github issue tracker + /// if none exist already or react to the already existing one. #[error("Not implemented: {0}")] NotImplemented(&'static str), + /// A reference to a variable that wasn't declared was used. #[error("Unknown variable: {0}")] UnknownVariable(String), + /// A reference to a type that wasn't declared was used. #[error("Unknown type: {0}")] UnknownType(String), + /// A reference to a non existant member of a type was made. #[error("Unknown field: {0}")] UnknownField(String), + /// An unknown layout qualifier was used. + /// + /// If the qualifier does exist please open an issue in the github issue tracker + /// if none exist already or react to the already existing one to help + /// prioritize work. #[error("Unknown layout qualifier: {0}")] UnknownLayoutQualifier(String), + /// A variable with the same name already exists in the current scope. #[cfg(feature = "glsl-validate")] #[error("Variable already declared: {0}")] VariableAlreadyDeclared(String), + /// A semantic error was detected in the shader. #[error("{0}")] SemanticError(Cow<'static, str>), + /// An error was returned by the preprocessor. #[error("{0:?}")] PreprocessorError(PreprocessorError), } @@ -84,11 +114,14 @@ impl From for ErrorKind { } } +/// Error returned during shader parsing #[derive(Debug, Error)] #[error("{kind}")] #[cfg_attr(test, derive(PartialEq))] pub struct Error { + /// Holds the information about the error itself. pub kind: ErrorKind, + /// Holds information about the range of the source code where the error happened. pub meta: SourceMetadata, } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 32fdf0898..7f8fba66c 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,3 +1,11 @@ +//! Front end for consuming the OpenGl Shading language (GLSL). +//! +//! To begin take a look at the documentation for the [`Parser`](Parser). +//! +//! # Supported versions +//! Currently only the versions 450 and 460 are supported and 440 is partially +//! supported, furthermore the vulkan flavor is assumed. + pub use ast::{Precision, Profile}; pub use error::{Error, ErrorKind, ExpectedToken}; pub use token::{SourceMetadata, TokenValue}; @@ -22,20 +30,66 @@ mod variables; type Result = std::result::Result; +/// Per shader options passed to [`parse`](Parser::parse) +/// +/// The [`From`](From) trait is implemented for [`ShaderStage`](ShaderStage) to +/// provide a quick way to create a Options instance. +/// ```rust +/// # use naga::ShaderStage; +/// # use naga::front::glsl::Options; +/// Options::from(ShaderStage::Vertex); +/// ``` +#[derive(Debug)] pub struct Options { + /// The shader stage in the pipeline. pub stage: ShaderStage, + /// Preprocesor definitions to be used, akin to having + /// ```glsl + /// #define key value + /// ``` + /// for each key value pair in the map. pub defines: FastHashMap, } +impl From for Options { + fn from(stage: ShaderStage) -> Self { + Options { + stage, + defines: FastHashMap::default(), + } + } +} + +/// Additional information about the glsl shader +/// +/// Stores additional information about the glsl shader which might not be +/// stored in the shader [`Module`](Module). #[derive(Debug)] pub struct ShaderMetadata { + /// The glsl version specified in the shader trought the use of the + /// `#version` preprocessor directive. pub version: u16, + /// The glsl profile specified in the shader trought the use of the + /// `#version` preprocessor directive. pub profile: Profile, + /// The shader stage in the pipeline, passed to the [`parse`](Parser::parse) + /// method via the [`Options`](Options) struct. pub stage: ShaderStage, + /// The workgroup size for compute shaders, defaults to `[1; 3]` for + /// compute shaders and `[0; 3]` for non compute shaders. pub workgroup_size: [u32; 3], + /// Wether or not early fragment tests where requested by the shader, + /// defaults to `false`. pub early_fragment_tests: bool, + /// The shader can request extensions via the + /// `#extension` preprocessor directive, in the directive a behavior + /// parameter is used to control whether the extension should be disabled, + /// warn on usage, enabled if possible or required. + /// + /// This field only stores extensions which were required or requested to + /// be enabled if possible and they are supported. pub extensions: FastHashSet, } @@ -63,6 +117,43 @@ impl Default for ShaderMetadata { } } +/// The `Parser` is the central structure of the glsl frontend. +/// +/// To instantiate a new `Parser` the [`Default`](Default) trait is used, so a +/// call to the associated function [`Parser::default`](Parser::default) will +/// return a new `Parser` instance. +/// +/// To parse a shader simply call the [`parse`](Parser::parse) method with a +/// [`Options`](Options) struct and a [`&str`](str) holding the glsl code. +/// +/// The `Parser` also provides the [`metadata`](Parser::metadata) to get some +/// further information about the previously parsed shader, like version and +/// extensions used (see the documentation for +/// [`ShaderMetadata`](ShaderMetadata) to see all the returned information) +/// +/// # Example usage +/// ```rust +/// use naga::ShaderStage; +/// use naga::front::glsl::{Parser, Options}; +/// +/// let glsl = r#" +/// #version 450 core +/// +/// void main() {} +/// "#; +/// +/// let mut parser = Parser::default(); +/// let options = Options::from(ShaderStage::Vertex); +/// parser.parse(&options, glsl); +/// ``` +/// +/// # Reusability +/// +/// If there's a need to parse more than one shader reusing the same `Parser` +/// instance may be beneficial since internal allocations will be reused. +/// +/// Calling the [`parse`](Parser::parse) method multiple times will reset the +/// `Parser` so no extra care is needed when reusing. #[derive(Debug, Default)] pub struct Parser { meta: ShaderMetadata, @@ -93,6 +184,10 @@ impl Parser { self.module = Module::default(); } + /// Parses a shader either outputting a shader [`Module`](Module) or a list + /// of [`Error`](Error)s. + /// + /// Multiple calls using the same `Parser` and different shaders are supported. pub fn parse( &mut self, options: &Options, @@ -118,6 +213,16 @@ impl Parser { } } + /// Returns additional information about the parsed shader which might not be + /// stored in the [`Module`](Module), see the documentation for + /// [`ShaderMetadata`](ShaderMetadata) for more information about the + /// returned data. + /// + /// # Notes + /// + /// Following an unsuccessful parsing the state of the returned infomration + /// is undefined, it might contain only partial information about the + /// current shader, the previous shader or both. pub fn metadata(&self) -> &ShaderMetadata { &self.meta } diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 458a32cac..cd35391af 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -5,6 +5,39 @@ use super::ast::Precision; use crate::{Interpolation, Sampling, Type}; use std::ops::Range; +/// Represents a range of the source code +/// +/// The `SourceMetadata` is used in error reporting to indicate a range of the +/// original source code where the error happened. +/// +/// For easy interaction with error crates like +/// [`codespan`][codespan] the [`From`](From) trait is +/// implemeted for [`Range`](Range) allowing for conversions from `SourceMetadata`. +/// +/// ```rust +/// # use naga::front::glsl::SourceMetadata; +/// # use std::ops::Range; +/// # let meta = SourceMetadata::default(); +/// let range: Range = meta.into(); +/// ``` +/// +/// Or in the case of [`codespan`][codespan] +/// +/// ```rust +/// # use naga::front::glsl::SourceMetadata; +/// use codespan_reporting::diagnostic::Label; +/// # let file = (); +/// # let meta = SourceMetadata::default(); +/// let label = Label::primary(file, meta); +/// ``` +/// +/// # Notes +/// +/// [`start`](SourceMetadata::start) can be equal to +/// [`end`](SourceMetadata::end) especially when reporting errors which aren't +/// associated with a specific portion of the code. +/// +/// [codespan]: https://docs.rs/codespan-reporting #[derive(Debug, Clone, Copy, Default)] #[cfg_attr(test, derive(PartialEq))] pub struct SourceMetadata { @@ -50,6 +83,10 @@ pub struct Token { pub meta: SourceMetadata, } +/// A token passed from the lexing used in the parsing +/// +/// This type is exported since it's returned in the +/// [`InvalidToken`](super::ErrorKind::InvalidToken) error. #[derive(Debug, PartialEq)] pub enum TokenValue { Identifier(String), From c73c1efe33839aebc84681e46732834794acb6a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 8 Aug 2021 17:25:10 +0100 Subject: [PATCH 1201/2212] [glsl-in] Apply comments --- src/front/glsl/context.rs | 22 +- src/front/glsl/functions.rs | 23 +- src/front/glsl/parser.rs | 25 +- src/front/glsl/parser_tests.rs | 565 ++++++++++++++++----------------- src/front/glsl/types.rs | 12 +- src/front/glsl/variables.rs | 12 +- 6 files changed, 322 insertions(+), 337 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 74053f0fd..33b89410c 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -1,16 +1,14 @@ -use crate::{ - front::{ - glsl::{ - ast::{ - GlobalLookup, GlobalLookupKind, HirExpr, HirExprKind, ParameterInfo, - ParameterQualifier, VariableReference, - }, - error::{Error, ErrorKind}, - types::{scalar_components, type_power}, - Parser, Result, SourceMetadata, - }, - Emitter, Typifier, +use super::{ + ast::{ + GlobalLookup, GlobalLookupKind, HirExpr, HirExprKind, ParameterInfo, ParameterQualifier, + VariableReference, }, + error::{Error, ErrorKind}, + types::{scalar_components, type_power}, + Parser, Result, SourceMetadata, +}; +use crate::{ + front::{Emitter, Typifier}, Arena, BinaryOperator, Block, Constant, Expression, FastHashMap, FunctionArgument, Handle, LocalVariable, RelationalFunction, ScalarKind, ScalarValue, Statement, StorageClass, Type, TypeInner, VectorSize, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 4be7422c9..6475c0aa2 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,16 +1,15 @@ +use super::{ + ast::*, + context::Context, + error::{Error, ErrorKind}, + types::{scalar_components, type_power}, + Parser, Result, SourceMetadata, +}; use crate::{ - front::glsl::{ - ast::*, - context::Context, - error::{Error, ErrorKind}, - types::{scalar_components, type_power}, - Parser, Result, SourceMetadata, - }, - proc::ensure_block_returns, - Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, Expression, FastHashMap, - Function, FunctionArgument, FunctionResult, Handle, ImageClass, ImageDimension, ImageQuery, - LocalVariable, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind, ScalarValue, - Statement, StructMember, Type, TypeInner, VectorSize, + proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, + Expression, FastHashMap, Function, FunctionArgument, FunctionResult, Handle, ImageClass, + ImageDimension, ImageQuery, LocalVariable, MathFunction, Module, RelationalFunction, + SampleLevel, ScalarKind, ScalarValue, Statement, StructMember, Type, TypeInner, VectorSize, }; use std::iter; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index cde62531e..b002f9b16 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,18 +1,15 @@ -use crate::{ - arena::Handle, - front::glsl::{ - ast::{Profile, TypeQualifier}, - context::Context, - error::ErrorKind, - error::ExpectedToken, - lex::{Lexer, LexerResultKind}, - token::{Directive, DirectiveKind}, - token::{SourceMetadata, Token, TokenValue}, - variables::{GlobalOrConstant, VarDeclaration}, - Error, Parser, Result, - }, - Block, Constant, ConstantInner, Expression, ScalarValue, Type, +use super::{ + ast::{Profile, TypeQualifier}, + context::Context, + error::ExpectedToken, + error::{Error, ErrorKind}, + lex::{Lexer, LexerResultKind}, + token::{Directive, DirectiveKind}, + token::{SourceMetadata, Token, TokenValue}, + variables::{GlobalOrConstant, VarDeclaration}, + Parser, Result, }; +use crate::{arena::Handle, Block, Constant, ConstantInner, Expression, ScalarValue, Type}; use core::convert::TryFrom; use pp_rs::token::{PreprocessorError, Token as PPToken, TokenValue as PPTokenValue}; use std::iter::Peekable; diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 29ea1900c..10c4b92c2 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -1,34 +1,26 @@ -use crate::{ - front::glsl::{ - ast::Profile, - error::ExpectedToken, - error::{Error, ErrorKind}, - token::TokenValue, - Options, Parser, SourceMetadata, - }, - Module, ShaderStage, +use super::{ + ast::Profile, + error::ExpectedToken, + error::{Error, ErrorKind}, + token::TokenValue, + Options, Parser, SourceMetadata, }; +use crate::ShaderStage; use pp_rs::token::PreprocessorError; -fn parse(parser: &mut Parser, source: &str, stage: ShaderStage) -> Result> { - let defines = crate::FastHashMap::default(); - - parser.parse(&Options { stage, defines }, source) -} - #[test] fn version() { let mut parser = Parser::default(); // invalid versions assert_eq!( - parse( - &mut parser, - "#version 99000\n void main(){}", - ShaderStage::Vertex - ) - .err() - .unwrap(), + parser + .parse( + &Options::from(ShaderStage::Vertex), + "#version 99000\n void main(){}", + ) + .err() + .unwrap(), vec![Error { kind: ErrorKind::InvalidVersion(99000), meta: SourceMetadata { start: 9, end: 14 } @@ -36,13 +28,13 @@ fn version() { ); assert_eq!( - parse( - &mut parser, - "#version 449\n void main(){}", - ShaderStage::Vertex - ) - .err() - .unwrap(), + parser + .parse( + &Options::from(ShaderStage::Vertex), + "#version 449\n void main(){}", + ) + .err() + .unwrap(), vec![Error { kind: ErrorKind::InvalidVersion(449), meta: SourceMetadata { start: 9, end: 12 } @@ -50,13 +42,13 @@ fn version() { ); assert_eq!( - parse( - &mut parser, - "#version 450 smart\n void main(){}", - ShaderStage::Vertex - ) - .err() - .unwrap(), + parser + .parse( + &Options::from(ShaderStage::Vertex), + "#version 450 smart\n void main(){}", + ) + .err() + .unwrap(), vec![Error { kind: ErrorKind::InvalidProfile("smart".into()), meta: SourceMetadata { start: 13, end: 18 }, @@ -64,13 +56,13 @@ fn version() { ); assert_eq!( - parse( - &mut parser, - "#version 450\nvoid main(){} #version 450", - ShaderStage::Vertex - ) - .err() - .unwrap(), + parser + .parse( + &Options::from(ShaderStage::Vertex), + "#version 450\nvoid main(){} #version 450", + ) + .err() + .unwrap(), vec![ Error { kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedHash,), @@ -87,34 +79,34 @@ fn version() { ); // valid versions - parse( - &mut parser, - " # version 450\nvoid main() {}", - ShaderStage::Vertex, - ) - .unwrap(); + parser + .parse( + &Options::from(ShaderStage::Vertex), + " # version 450\nvoid main() {}", + ) + .unwrap(); assert_eq!( (parser.metadata().version, parser.metadata().profile), (450, Profile::Core) ); - parse( - &mut parser, - "#version 450\nvoid main() {}", - ShaderStage::Vertex, - ) - .unwrap(); + parser + .parse( + &Options::from(ShaderStage::Vertex), + "#version 450\nvoid main() {}", + ) + .unwrap(); assert_eq!( (parser.metadata().version, parser.metadata().profile), (450, Profile::Core) ); - parse( - &mut parser, - "#version 450 core\nvoid main() {}", - ShaderStage::Vertex, - ) - .unwrap(); + parser + .parse( + &Options::from(ShaderStage::Vertex), + "#version 450 core\nvoid main() {}", + ) + .unwrap(); assert_eq!( (parser.metadata().version, parser.metadata().profile), (450, Profile::Core) @@ -125,9 +117,10 @@ fn version() { fn control_flow() { let mut parser = Parser::default(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void main() { if (true) { @@ -137,13 +130,13 @@ fn control_flow() { } } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void main() { if (true) { @@ -151,13 +144,13 @@ fn control_flow() { } } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void main() { int x; @@ -174,12 +167,13 @@ fn control_flow() { } } "#, - ShaderStage::Vertex, - ) - .unwrap(); - parse( - &mut parser, - r#" + ) + .unwrap(); + + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void main() { int x = 0; @@ -191,13 +185,13 @@ fn control_flow() { } while(x >= 4) } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void main() { int x = 0; @@ -208,18 +202,18 @@ fn control_flow() { return x; } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); } #[test] fn declarations() { let mut parser = Parser::default(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" #version 450 layout(location = 0) in vec2 v_uv; layout(location = 0) out vec4 o_color; @@ -230,13 +224,13 @@ fn declarations() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" #version 450 layout(std140, set = 2, binding = 0) uniform u_locals { @@ -247,13 +241,13 @@ fn declarations() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" #version 450 layout(push_constant) uniform u_locals { @@ -264,13 +258,13 @@ fn declarations() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" #version 450 layout(std430, set = 2, binding = 0) uniform u_locals { @@ -281,13 +275,13 @@ fn declarations() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" #version 450 layout(std140, set = 2, binding = 0) uniform u_locals { @@ -300,42 +294,42 @@ fn declarations() { block_var.load_time * block_var.model_offs; } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" #version 450 float vector = vec4(1.0 / 17.0, 9.0 / 17.0, 3.0 / 17.0, 11.0 / 17.0); void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" #version 450 precision highp float; void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); } #[test] fn textures() { let mut parser = Parser::default(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" #version 450 layout(location = 0) in vec2 v_uv; layout(location = 0) out vec4 o_color; @@ -346,31 +340,31 @@ fn textures() { o_color.a = texture(sampler2D(tex, tex_sampler), v_uv, 2.0).a; } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); } #[test] fn functions() { let mut parser = Parser::default(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void test1(float); void test1(float) {} void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void test2(float a) {} void test3(float a, float b) {} @@ -378,25 +372,25 @@ fn functions() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 float test(float a) { return a; } void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 float test(vec4 p) { return p.x; @@ -404,14 +398,14 @@ fn functions() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); // Function overloading - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 float test(vec2 p); float test(vec3 p); @@ -431,14 +425,14 @@ fn functions() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); assert_eq!( - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 int test(vec4 p) { return p.x; @@ -450,10 +444,9 @@ fn functions() { void main() {} "#, - ShaderStage::Vertex - ) - .err() - .unwrap(), + ) + .err() + .unwrap(), vec![Error { kind: ErrorKind::SemanticError("Function already defined".into()), meta: SourceMetadata { @@ -465,9 +458,10 @@ fn functions() { println!(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 float callee(uint q) { return float(q); @@ -479,14 +473,14 @@ fn functions() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); // Nested function call - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 layout(set = 0, binding = 1) uniform texture2D t_noise; layout(set = 0, binding = 2) uniform sampler s_noise; @@ -495,13 +489,13 @@ fn functions() { textureLod(sampler2D(t_noise, s_noise), vec2(1.0), 0); } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void fun(vec2 in_parameter, out float out_parameter) { ivec2 _ = ivec2(in_parameter); @@ -512,9 +506,8 @@ fn functions() { fun(vec2(1.0), a); } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); } #[test] @@ -522,9 +515,10 @@ fn constants() { use crate::{Constant, ConstantInner, ScalarValue}; let mut parser = Parser::default(); - let module = parse( - &mut parser, - r#" + let module = parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 const float a = 1.0; float global = a; @@ -532,9 +526,8 @@ fn constants() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); let mut constants = module.constants.iter(); @@ -557,9 +550,10 @@ fn constants() { fn function_overloading() { let mut parser = Parser::default(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 float saturate(float v) { return clamp(v, 0.0, 1.0); } @@ -574,18 +568,18 @@ fn function_overloading() { vec3 v4 = saturate(vec4(0.5, 1.5, 2.5, 3.5)); } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); } #[test] fn implicit_conversions() { let mut parser = Parser::default(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void main() { mat4 a = mat4(1); @@ -593,14 +587,14 @@ fn implicit_conversions() { float c = 1 + 2.0; } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); assert_eq!( - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void test(int a) {} void test(uint a) {} @@ -609,10 +603,9 @@ fn implicit_conversions() { test(1.0); } "#, - ShaderStage::Vertex - ) - .err() - .unwrap(), + ) + .err() + .unwrap(), vec![Error { kind: ErrorKind::SemanticError("Unknown function \'test\'".into()), meta: SourceMetadata { @@ -623,9 +616,10 @@ fn implicit_conversions() { ); assert_eq!( - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void test(float a) {} void test(uint a) {} @@ -634,10 +628,9 @@ fn implicit_conversions() { test(1); } "#, - ShaderStage::Vertex - ) - .err() - .unwrap(), + ) + .err() + .unwrap(), vec![Error { kind: ErrorKind::SemanticError("Ambiguous best function for \'test\'".into()), meta: SourceMetadata { @@ -652,9 +645,10 @@ fn implicit_conversions() { fn structs() { let mut parser = Parser::default(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 Test { vec4 pos; @@ -662,13 +656,13 @@ fn structs() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap_err(); + ) + .unwrap_err(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 struct Test { vec4 pos; @@ -676,13 +670,13 @@ fn structs() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 const int NUM_VECS = 42; struct Test { @@ -691,13 +685,13 @@ fn structs() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 struct Hello { vec4 test; @@ -707,25 +701,25 @@ fn structs() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 struct Test {}; void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap_err(); + ) + .unwrap_err(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 inout struct Test { vec4 x; @@ -733,18 +727,18 @@ fn structs() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap_err(); + ) + .unwrap_err(); } #[test] fn swizzles() { let mut parser = Parser::default(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void main() { vec4 v = vec4(1); @@ -753,44 +747,44 @@ fn swizzles() { v.xyz.zxy.yx.xy = vec2(5.0, 1.0); } "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void main() { vec4 v = vec4(1); v.xx = vec2(5.0); } "#, - ShaderStage::Vertex, - ) - .unwrap_err(); + ) + .unwrap_err(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 void main() { vec3 v = vec3(1); v.w = 2.0; } "#, - ShaderStage::Vertex, - ) - .unwrap_err(); + ) + .unwrap_err(); } #[test] fn vector_indexing() { let mut parser = Parser::default(); - parse( - &mut parser, - r#" + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" # version 450 float test(int index) { vec4 v = vec4(1.0, 2.0, 3.0, 4.0); @@ -799,7 +793,6 @@ fn vector_indexing() { void main() {} "#, - ShaderStage::Vertex, - ) - .unwrap(); + ) + .unwrap(); } diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index cc0fb04f8..7c8200caf 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,11 +1,9 @@ +use super::{ + constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, SourceMetadata, +}; use crate::{ - front::glsl::{ - constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, - SourceMetadata, - }, - proc::ResolveContext, - ArraySize, Constant, Expression, Handle, ImageClass, ImageDimension, ScalarKind, Type, - TypeInner, VectorSize, + proc::ResolveContext, ArraySize, Constant, Expression, Handle, ImageClass, ImageDimension, + ScalarKind, Type, TypeInner, VectorSize, }; pub fn parse_type(type_name: &str) -> Option { diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 86e4b8322..aa1a60b85 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,10 +1,10 @@ +use super::{ + ast::*, + context::Context, + error::{Error, ErrorKind}, + Parser, Result, SourceMetadata, +}; use crate::{ - front::glsl::{ - ast::*, - context::Context, - error::{Error, ErrorKind}, - Parser, Result, SourceMetadata, - }, Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, Interpolation, LocalVariable, ResourceBinding, ScalarKind, StorageAccess, StorageClass, SwizzleComponent, Type, TypeInner, VectorSize, From 021bfd52893cc9a8b4922b76dc46386b7f4e6dd8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 9 Aug 2021 15:03:35 -0400 Subject: [PATCH 1202/2212] [hlsl-out] fix member offset consideration for storage buffers --- src/back/hlsl/storage.rs | 19 ++++++++++++------- tests/out/hlsl/access.hlsl | 8 ++++---- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 91f3ef36c..d16c17c47 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -16,6 +16,7 @@ use std::{fmt, mem}; const STORE_TEMP_NAME: &str = "_value"; +#[derive(Debug)] pub(super) enum SubAccess { Offset(u32), Index { @@ -365,7 +366,7 @@ impl super::Writer<'_, W> { ) -> Result, Error> { self.temp_access_chain.clear(); loop { - // determine the size of the pontee + // determine the size of the pointee let stride = match *func_ctx.info[cur_expr].ty.inner_with(&module.types) { crate::TypeInner::Pointer { base, class: _ } => { module.types[base].inner.span(&module.constants) @@ -386,12 +387,16 @@ impl super::Writer<'_, W> { }, ), crate::Expression::AccessIndex { base, index } => { - match *func_ctx.info[base].ty.inner_with(&module.types) { - crate::TypeInner::Struct { ref members, .. } => { - (base, SubAccess::Offset(members[index as usize].offset)) - } - _ => (base, SubAccess::Offset(index * stride)), - } + let sub = match *func_ctx.info[base].ty.inner_with(&module.types) { + crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { + crate::TypeInner::Struct { ref members, .. } => { + SubAccess::Offset(members[index as usize].offset) + } + _ => SubAccess::Offset(index * stride), + }, + _ => SubAccess::Offset(index * stride), + }; + (base, sub) } ref other => { return Err(Error::Unimplemented(format!( diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 5ff07ea5f..4e1494a9c 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -20,10 +20,10 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position float baz = foo1; foo1 = 1.0; float4x4 matrix1 = transpose(float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48)))); - uint2 arr[2] = {asuint(bar.Load2(16+0)), asuint(bar.Load2(16+8))}; + uint2 arr[2] = {asuint(bar.Load2(64+0)), asuint(bar.Load2(64+8))}; float4 _expr13 = asfloat(bar.Load4(48+0)); float b = _expr13.x; - int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 80) / 4) - 2u)*4+8)); + int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 80) / 4) - 2u)*4+80)); bar.Store(8+16+0, asuint(1.0)); { float4x4 _value2 = transpose(float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx))); @@ -34,8 +34,8 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position } { uint2 _value2[2] = { uint2(0u.xx), uint2(1u.xx) }; - bar.Store2(16+0, asuint(_value2[0])); - bar.Store2(16+8, asuint(_value2[1])); + bar.Store2(64+0, asuint(_value2[0])); + bar.Store2(64+8, asuint(_value2[1])); } { int _result[5]={ a, int(b), 3, 4, 5 }; From 07c286255dc2b79d206b1a7424a672aed6c19e33 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 9 Aug 2021 21:15:47 -0400 Subject: [PATCH 1203/2212] [spv-in] fix struct spans for layout-less structs --- src/front/spv/mod.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 24feb8860..c1e215017 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3090,15 +3090,17 @@ impl> Parser { let inner = crate::TypeInner::Struct { top_level: block_decor.is_some(), - span: match members.last() { - Some(member) => { + span: members + .iter() + .map(|member| { let end = member.offset + module.types[member.ty].inner.span(&module.constants); ((end - 1) | (struct_alignment.get() - 1)) + 1 - } - None => 4, //do we support this? - }, + }) + .max() + .unwrap_or(4), //do we support this? members, }; + let ty_handle = module.types.append(crate::Type { name: parent_decor.and_then(|dec| dec.name), inner, From e384bce771db1d7dd156e9e29afe9d9235984924 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 10 Aug 2021 14:50:13 +0100 Subject: [PATCH 1204/2212] [glsl-in] Don't clone HirExpr when lowering --- src/arena.rs | 5 + src/front/glsl/context.rs | 142 +++++++++++++++++++++----- src/front/glsl/functions.rs | 45 ++++---- src/front/glsl/parser.rs | 5 +- src/front/glsl/parser/declarations.rs | 5 +- src/front/glsl/parser/expressions.rs | 94 +++++++++-------- src/front/glsl/parser/functions.rs | 57 +++++++---- 7 files changed, 237 insertions(+), 116 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 174c79b54..bd3a3d776 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -240,6 +240,11 @@ impl Arena { marker: PhantomData, } } + + /// Clears the arena keeping all allocations + pub fn clear(&mut self) { + self.data.clear() + } } impl ops::Index> for Arena { diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 33b89410c..8b30a6a2b 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -29,9 +29,9 @@ pub struct Context { pub lookup_global_var_exps: FastHashMap, pub samplers: FastHashMap, Handle>, - pub hir_exprs: Arena, pub typifier: Typifier, emitter: Emitter, + stmt_ctx: Option, } impl Context { @@ -51,9 +51,9 @@ impl Context { ), samplers: FastHashMap::default(), - hir_exprs: Arena::default(), typifier: Typifier::new(), emitter: Emitter::default(), + stmt_ctx: Some(StmtContext::new()), }; this.emit_start(); @@ -280,14 +280,71 @@ impl Context { self.scopes.pop(); } + /// Returns a [`StmtContext`](StmtContext) to be used in parsing and lowering + /// + /// # Panics + /// - If more than one [`StmtContext`](StmtContext) are active at the same + /// time or if the previous call didn't use it in lowering. + #[must_use] + pub fn stmt_ctx(&mut self) -> StmtContext { + self.stmt_ctx.take().unwrap() + } + + /// Lowers a [`HirExpr`](HirExpr) which might produce a [`Expression`](Expression). + /// + /// consumes a [`StmtContext`](StmtContext) returning it to the context so + /// that it can be used again later. + pub fn lower( + &mut self, + mut stmt: StmtContext, + parser: &mut Parser, + expr: Handle, + lhs: bool, + body: &mut Block, + ) -> Result<(Option>, SourceMetadata)> { + let res = self.lower_inner(&stmt, parser, expr, lhs, body); + + stmt.hir_exprs.clear(); + self.stmt_ctx = Some(stmt); + + res + } + + /// Similar to [`lower`](Self::lower) but returns an error if the expression + /// returns void (ie. doesn't produce a [`Expression`](Expression)). + /// + /// consumes a [`StmtContext`](StmtContext) returning it to the context so + /// that it can be used again later. pub fn lower_expect( &mut self, + mut stmt: StmtContext, parser: &mut Parser, expr: Handle, lhs: bool, body: &mut Block, ) -> Result<(Handle, SourceMetadata)> { - let (maybe_expr, meta) = self.lower(parser, expr, lhs, body)?; + let res = self.lower_expect_inner(&stmt, parser, expr, lhs, body); + + stmt.hir_exprs.clear(); + self.stmt_ctx = Some(stmt); + + res + } + + /// internal implementation of [`lower_expect`](Self::lower_expect) + /// + /// this method is only public because it's used in + /// [`function_call`](Parser::function_call), unless you know what + /// you're doing use [`lower_expect`](Self::lower_expect) + pub fn lower_expect_inner( + &mut self, + stmt: &StmtContext, + parser: &mut Parser, + expr: Handle, + lhs: bool, + body: &mut Block, + ) -> Result<(Handle, SourceMetadata)> { + let (maybe_expr, meta) = self.lower_inner(stmt, parser, expr, lhs, body)?; let expr = match maybe_expr { Some(e) => e, @@ -302,19 +359,22 @@ impl Context { Ok((expr, meta)) } - pub fn lower( + /// Internal implementation of [`lower`](Self::lower) + fn lower_inner( &mut self, + stmt: &StmtContext, parser: &mut Parser, expr: Handle, lhs: bool, body: &mut Block, ) -> Result<(Option>, SourceMetadata)> { - let HirExpr { kind, meta } = self.hir_exprs[expr].clone(); + let HirExpr { ref kind, meta } = stmt.hir_exprs[expr]; - let handle = match kind { + let handle = match *kind { HirExprKind::Access { base, index } => { - let base = self.lower_expect(parser, base, true, body)?.0; - let (index, index_meta) = self.lower_expect(parser, index, false, body)?; + let base = self.lower_expect_inner(stmt, parser, base, true, body)?.0; + let (index, index_meta) = + self.lower_expect_inner(stmt, parser, index, false, body)?; let pointer = parser .solve_constant(self, index, index_meta) @@ -354,17 +414,19 @@ impl Context { pointer } - HirExprKind::Select { base, field } => { - let base = self.lower_expect(parser, base, lhs, body)?.0; + HirExprKind::Select { base, ref field } => { + let base = self.lower_expect_inner(stmt, parser, base, lhs, body)?.0; - parser.field_selection(self, lhs, body, base, &field, meta)? + parser.field_selection(self, lhs, body, base, field, meta)? } HirExprKind::Constant(constant) if !lhs => { self.add_expression(Expression::Constant(constant), body) } HirExprKind::Binary { left, op, right } if !lhs => { - let (mut left, left_meta) = self.lower_expect(parser, left, false, body)?; - let (mut right, right_meta) = self.lower_expect(parser, right, false, body)?; + let (mut left, left_meta) = + self.lower_expect_inner(stmt, parser, left, false, body)?; + let (mut right, right_meta) = + self.lower_expect_inner(stmt, parser, right, false, body)?; match op { BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self @@ -439,11 +501,11 @@ impl Context { } } HirExprKind::Unary { op, expr } if !lhs => { - let expr = self.lower_expect(parser, expr, false, body)?.0; + let expr = self.lower_expect_inner(stmt, parser, expr, false, body)?.0; self.add_expression(Expression::Unary { op, expr }, body) } - HirExprKind::Variable(var) => { + HirExprKind::Variable(ref var) => { if lhs { if !var.mutable { parser.errors.push(Error { @@ -461,9 +523,15 @@ impl Context { var.expr } } - HirExprKind::Call(call) if !lhs => { - let maybe_expr = - parser.function_or_constructor_call(self, body, call.kind, &call.args, meta)?; + HirExprKind::Call(ref call) if !lhs => { + let maybe_expr = parser.function_or_constructor_call( + self, + stmt, + body, + call.kind.clone(), + &call.args, + meta, + )?; return Ok((maybe_expr, meta)); } HirExprKind::Conditional { @@ -471,9 +539,13 @@ impl Context { accept, reject, } if !lhs => { - let condition = self.lower_expect(parser, condition, false, body)?.0; - let (mut accept, accept_meta) = self.lower_expect(parser, accept, false, body)?; - let (mut reject, reject_meta) = self.lower_expect(parser, reject, false, body)?; + let condition = self + .lower_expect_inner(stmt, parser, condition, false, body)? + .0; + let (mut accept, accept_meta) = + self.lower_expect_inner(stmt, parser, accept, false, body)?; + let (mut reject, reject_meta) = + self.lower_expect_inner(stmt, parser, reject, false, body)?; self.binary_implicit_conversion( parser, @@ -493,8 +565,9 @@ impl Context { ) } HirExprKind::Assign { tgt, value } if !lhs => { - let (pointer, ptr_meta) = self.lower_expect(parser, tgt, true, body)?; - let (mut value, value_meta) = self.lower_expect(parser, value, false, body)?; + let (pointer, ptr_meta) = self.lower_expect_inner(stmt, parser, tgt, true, body)?; + let (mut value, value_meta) = + self.lower_expect_inner(stmt, parser, value, false, body)?; let scalar_components = self.expr_scalar_components(parser, pointer, ptr_meta)?; @@ -564,7 +637,7 @@ impl Context { false => BinaryOperator::Subtract, }; - let pointer = self.lower_expect(parser, expr, true, body)?.0; + let pointer = self.lower_expect_inner(stmt, parser, expr, true, body)?.0; let left = self.add_expression(Expression::Load { pointer }, body); let uint = match parser.resolve_type(self, left, meta)?.scalar_kind() { @@ -641,7 +714,7 @@ impl Context { _ => { return Err(Error { kind: ErrorKind::SemanticError( - format!("{:?} cannot be in the left hand side", self.hir_exprs[expr]) + format!("{:?} cannot be in the left hand side", stmt.hir_exprs[expr]) .into(), ), meta, @@ -779,3 +852,22 @@ impl Index> for Context { &self.expressions[index] } } + +/// Helper struct passed when parsing expressions +/// +/// This struct should only be obtained trough [`stmt_ctx`](Context::stmt_ctx) +/// and only one of these may be active at any time per context. +#[derive(Debug)] +pub struct StmtContext { + /// A arena of high level expressions which can be lowered trough a + /// [`Context`](Context) to naga's [`Expression`](crate::Expression)s + pub hir_exprs: Arena, +} + +impl StmtContext { + fn new() -> Self { + StmtContext { + hir_exprs: Arena::new(), + } + } +} diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 6475c0aa2..dd2d6d0f7 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,6 +1,6 @@ use super::{ ast::*, - context::Context, + context::{Context, StmtContext}, error::{Error, ErrorKind}, types::{scalar_components, type_power}, Parser, Result, SourceMetadata, @@ -41,6 +41,7 @@ impl Parser { pub(crate) fn function_or_constructor_call( &mut self, ctx: &mut Context, + stmt: &StmtContext, body: &mut Block, fc: FunctionCallKind, raw_args: &[Handle], @@ -48,7 +49,7 @@ impl Parser { ) -> Result>> { let args: Vec<_> = raw_args .iter() - .map(|e| ctx.lower_expect(self, *e, false, body)) + .map(|e| ctx.lower_expect_inner(stmt, self, *e, false, body)) .collect::>()?; match fc { @@ -307,14 +308,16 @@ impl Parser { Ok(Some(h)) } FunctionCallKind::Function(name) => { - self.function_call(ctx, body, name, args, raw_args, meta) + self.function_call(ctx, stmt, body, name, args, raw_args, meta) } } } + #[allow(clippy::too_many_arguments)] fn function_call( &mut self, ctx: &mut Context, + stmt: &StmtContext, body: &mut Block, name: String, mut args: Vec<(Handle, SourceMetadata)>, @@ -969,8 +972,13 @@ impl Parser { .iter() .zip(raw_args.iter().zip(parameters.iter())) { - let (mut handle, meta) = - ctx.lower_expect(self, *expr, parameter_info.qualifier.is_lhs(), body)?; + let (mut handle, meta) = ctx.lower_expect_inner( + stmt, + self, + *expr, + parameter_info.qualifier.is_lhs(), + body, + )?; if let TypeInner::Vector { size, kind, width } = *self.resolve_type(ctx, handle, meta)? @@ -1025,27 +1033,16 @@ impl Parser { ctx.emit_start(); for (tgt, pointer) in proxy_writes { - let temp_ref = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Variable(VariableReference { - expr: pointer, - load: true, - mutable: true, - entry_arg: None, - }), - meta, - }); - let assign = ctx.hir_exprs.append(HirExpr { - kind: HirExprKind::Assign { - tgt, - value: temp_ref, - }, - meta, - }); + let value = ctx.add_expression(Expression::Load { pointer }, body); + let target = ctx.lower_expect_inner(stmt, self, tgt, true, body)?.0; - let _ = ctx.lower_expect(self, assign, false, body)?; + ctx.emit_flush(body); + body.push(Statement::Store { + pointer: target, + value, + }); + ctx.emit_start(); } - ctx.emit_flush(body); - ctx.emit_start(); Ok(result) } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b002f9b16..a5ee5f409 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -192,8 +192,9 @@ impl<'source> ParsingContext<'source> { let mut ctx = Context::new(parser, &mut block); - let expr = self.parse_conditional(parser, &mut ctx, &mut block, None)?; - let (root, meta) = ctx.lower_expect(parser, expr, false, &mut block)?; + let mut stmt_ctx = ctx.stmt_ctx(); + let expr = self.parse_conditional(parser, &mut ctx, &mut stmt_ctx, &mut block, None)?; + let (root, meta) = ctx.lower_expect(stmt_ctx, parser, expr, false, &mut block)?; Ok((parser.solve_constant(&ctx, root, meta)?, meta)) } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index a12751794..d6fbd7c70 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -98,8 +98,9 @@ impl<'source> ParsingContext<'source> { meta, )) } else { - let expr = self.parse_assignment(parser, ctx, body)?; - let (mut init, init_meta) = ctx.lower_expect(parser, expr, false, body)?; + let mut stmt = ctx.stmt_ctx(); + let expr = self.parse_assignment(parser, ctx, &mut stmt, body)?; + let (mut init, init_meta) = ctx.lower_expect(stmt, parser, expr, false, body)?; let scalar_components = scalar_components(&parser.module.types[ty].inner); if let Some((kind, width)) = scalar_components { diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index f0d98dd2a..59eacb9a4 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -1,7 +1,7 @@ use crate::{ front::glsl::{ ast::{FunctionCall, FunctionCallKind, HirExpr, HirExprKind}, - context::Context, + context::{Context, StmtContext}, error::{ErrorKind, ExpectedToken}, parser::ParsingContext, token::{Token, TokenValue}, @@ -16,6 +16,7 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, ctx: &mut Context, + stmt: &mut StmtContext, body: &mut Block, ) -> Result> { let mut token = self.bump(parser)?; @@ -35,7 +36,7 @@ impl<'source> ParsingContext<'source> { ), TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)), TokenValue::LeftParen => { - let expr = self.parse_expression(parser, ctx, body)?; + let expr = self.parse_expression(parser, ctx, stmt, body)?; let meta = self.expect(parser, TokenValue::RightParen)?.meta; token.meta = token.meta.union(&meta); @@ -64,7 +65,7 @@ impl<'source> ParsingContext<'source> { inner: ConstantInner::Scalar { width, value }, }); - Ok(ctx.hir_exprs.append(HirExpr { + Ok(stmt.hir_exprs.append(HirExpr { kind: HirExprKind::Constant(handle), meta: token.meta, })) @@ -74,6 +75,7 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, ctx: &mut Context, + stmt: &mut StmtContext, body: &mut Block, meta: &mut SourceMetadata, ) -> Result>> { @@ -82,7 +84,7 @@ impl<'source> ParsingContext<'source> { *meta = meta.union(&token.meta); } else { loop { - args.push(self.parse_assignment(parser, ctx, body)?); + args.push(self.parse_assignment(parser, ctx, stmt, body)?); let token = self.bump(parser)?; match token.value { @@ -111,6 +113,7 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, ctx: &mut Context, + stmt: &mut StmtContext, body: &mut Block, ) -> Result> { let mut base = match self.expect_peek(parser)?.value { @@ -118,7 +121,7 @@ impl<'source> ParsingContext<'source> { let (name, mut meta) = self.expect_ident(parser)?; let expr = if self.bump_if(parser, TokenValue::LeftParen).is_some() { - let args = self.parse_function_call_args(parser, ctx, body, &mut meta)?; + let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; let kind = match parser.lookup_type.get(&name) { Some(ty) => FunctionCallKind::TypeConstructor(*ty), @@ -146,7 +149,7 @@ impl<'source> ParsingContext<'source> { } }; - ctx.hir_exprs.append(expr) + stmt.hir_exprs.append(expr) } TokenValue::TypeName(_) => { let Token { value, mut meta } = self.bump(parser)?; @@ -160,7 +163,7 @@ impl<'source> ParsingContext<'source> { let maybe_size = self.parse_array_specifier(parser)?; self.expect(parser, TokenValue::LeftParen)?; - let args = self.parse_function_call_args(parser, ctx, body, &mut meta)?; + let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; if let Some(array_size) = maybe_size { let stride = parser.module.types[handle] @@ -193,7 +196,7 @@ impl<'source> ParsingContext<'source> { }) } - ctx.hir_exprs.append(HirExpr { + stmt.hir_exprs.append(HirExpr { kind: HirExprKind::Call(FunctionCall { kind: FunctionCallKind::TypeConstructor(handle), args, @@ -201,7 +204,7 @@ impl<'source> ParsingContext<'source> { meta, }) } - _ => self.parse_primary(parser, ctx, body)?, + _ => self.parse_primary(parser, ctx, stmt, body)?, }; while let TokenValue::LeftBracket @@ -213,10 +216,10 @@ impl<'source> ParsingContext<'source> { match value { TokenValue::LeftBracket => { - let index = self.parse_expression(parser, ctx, body)?; + let index = self.parse_expression(parser, ctx, stmt, body)?; let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; - base = ctx.hir_exprs.append(HirExpr { + base = stmt.hir_exprs.append(HirExpr { kind: HirExprKind::Access { base, index }, meta: meta.union(&end_meta), }) @@ -224,13 +227,13 @@ impl<'source> ParsingContext<'source> { TokenValue::Dot => { let (field, end_meta) = self.expect_ident(parser)?; - base = ctx.hir_exprs.append(HirExpr { + base = stmt.hir_exprs.append(HirExpr { kind: HirExprKind::Select { base, field }, meta: meta.union(&end_meta), }) } TokenValue::Increment => { - base = ctx.hir_exprs.append(HirExpr { + base = stmt.hir_exprs.append(HirExpr { kind: HirExprKind::IncDec { increment: true, postfix: true, @@ -240,7 +243,7 @@ impl<'source> ParsingContext<'source> { }) } TokenValue::Decrement => { - base = ctx.hir_exprs.append(HirExpr { + base = stmt.hir_exprs.append(HirExpr { kind: HirExprKind::IncDec { increment: false, postfix: true, @@ -260,6 +263,7 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, ctx: &mut Context, + stmt: &mut StmtContext, body: &mut Block, ) -> Result> { // TODO: prefix inc/dec @@ -267,8 +271,8 @@ impl<'source> ParsingContext<'source> { TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { let Token { value, meta } = self.bump(parser)?; - let expr = self.parse_unary(parser, ctx, body)?; - let end_meta = ctx.hir_exprs[expr].meta; + let expr = self.parse_unary(parser, ctx, stmt, body)?; + let end_meta = stmt.hir_exprs[expr].meta; let kind = match value { TokenValue::Dash => HirExprKind::Unary { @@ -282,7 +286,7 @@ impl<'source> ParsingContext<'source> { _ => return Ok(expr), }; - ctx.hir_exprs.append(HirExpr { + stmt.hir_exprs.append(HirExpr { kind, meta: meta.union(&end_meta), }) @@ -290,9 +294,9 @@ impl<'source> ParsingContext<'source> { TokenValue::Increment | TokenValue::Decrement => { let Token { value, meta } = self.bump(parser)?; - let expr = self.parse_unary(parser, ctx, body)?; + let expr = self.parse_unary(parser, ctx, stmt, body)?; - ctx.hir_exprs.append(HirExpr { + stmt.hir_exprs.append(HirExpr { kind: HirExprKind::IncDec { increment: match value { TokenValue::Increment => true, @@ -305,7 +309,7 @@ impl<'source> ParsingContext<'source> { meta, }) } - _ => self.parse_postfix(parser, ctx, body)?, + _ => self.parse_postfix(parser, ctx, stmt, body)?, }) } @@ -313,14 +317,15 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, ctx: &mut Context, + stmt: &mut StmtContext, body: &mut Block, passtrough: Option>, min_bp: u8, ) -> Result> { let mut left = passtrough .ok_or(ErrorKind::EndOfFile /* Dummy error */) - .or_else(|_| self.parse_unary(parser, ctx, body))?; - let start_meta = ctx.hir_exprs[left].meta; + .or_else(|_| self.parse_unary(parser, ctx, stmt, body))?; + let start_meta = stmt.hir_exprs[left].meta; while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(parser)?.value) { if l_bp < min_bp { @@ -329,10 +334,10 @@ impl<'source> ParsingContext<'source> { let Token { value, .. } = self.bump(parser)?; - let right = self.parse_binary(parser, ctx, body, None, r_bp)?; - let end_meta = ctx.hir_exprs[right].meta; + let right = self.parse_binary(parser, ctx, stmt, body, None, r_bp)?; + let end_meta = stmt.hir_exprs[right].meta; - left = ctx.hir_exprs.append(HirExpr { + left = stmt.hir_exprs.append(HirExpr { kind: HirExprKind::Binary { left, op: match value { @@ -370,19 +375,20 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, ctx: &mut Context, + stmt: &mut StmtContext, body: &mut Block, passtrough: Option>, ) -> Result> { - let mut condition = self.parse_binary(parser, ctx, body, passtrough, 0)?; - let start_meta = ctx.hir_exprs[condition].meta; + let mut condition = self.parse_binary(parser, ctx, stmt, body, passtrough, 0)?; + let start_meta = stmt.hir_exprs[condition].meta; if self.bump_if(parser, TokenValue::Question).is_some() { - let accept = self.parse_expression(parser, ctx, body)?; + let accept = self.parse_expression(parser, ctx, stmt, body)?; self.expect(parser, TokenValue::Colon)?; - let reject = self.parse_assignment(parser, ctx, body)?; - let end_meta = ctx.hir_exprs[reject].meta; + let reject = self.parse_assignment(parser, ctx, stmt, body)?; + let end_meta = stmt.hir_exprs[reject].meta; - condition = ctx.hir_exprs.append(HirExpr { + condition = stmt.hir_exprs.append(HirExpr { kind: HirExprKind::Conditional { condition, accept, @@ -399,18 +405,19 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, ctx: &mut Context, + stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let tgt = self.parse_unary(parser, ctx, body)?; - let start_meta = ctx.hir_exprs[tgt].meta; + let tgt = self.parse_unary(parser, ctx, stmt, body)?; + let start_meta = stmt.hir_exprs[tgt].meta; Ok(match self.expect_peek(parser)?.value { TokenValue::Assign => { self.bump(parser)?; - let value = self.parse_assignment(parser, ctx, body)?; - let end_meta = ctx.hir_exprs[value].meta; + let value = self.parse_assignment(parser, ctx, stmt, body)?; + let end_meta = stmt.hir_exprs[value].meta; - ctx.hir_exprs.append(HirExpr { + stmt.hir_exprs.append(HirExpr { kind: HirExprKind::Assign { tgt, value }, meta: start_meta.union(&end_meta), }) @@ -426,10 +433,10 @@ impl<'source> ParsingContext<'source> { | TokenValue::RightShiftAssign | TokenValue::XorAssign => { let token = self.bump(parser)?; - let right = self.parse_assignment(parser, ctx, body)?; - let end_meta = ctx.hir_exprs[right].meta; + let right = self.parse_assignment(parser, ctx, stmt, body)?; + let end_meta = stmt.hir_exprs[right].meta; - let value = ctx.hir_exprs.append(HirExpr { + let value = stmt.hir_exprs.append(HirExpr { meta: start_meta.union(&end_meta), kind: HirExprKind::Binary { left: tgt, @@ -450,12 +457,12 @@ impl<'source> ParsingContext<'source> { }, }); - ctx.hir_exprs.append(HirExpr { + stmt.hir_exprs.append(HirExpr { kind: HirExprKind::Assign { tgt, value }, meta: start_meta.union(&end_meta), }) } - _ => self.parse_conditional(parser, ctx, body, Some(tgt))?, + _ => self.parse_conditional(parser, ctx, stmt, body, Some(tgt))?, }) } @@ -463,13 +470,14 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, ctx: &mut Context, + stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let mut expr = self.parse_assignment(parser, ctx, body)?; + let mut expr = self.parse_assignment(parser, ctx, stmt, body)?; while let TokenValue::Comma = self.expect_peek(parser)?.value { self.bump(parser)?; - expr = self.parse_assignment(parser, ctx, body)?; + expr = self.parse_assignment(parser, ctx, stmt, body)?; } Ok(expr) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 24e1ac987..efc72803b 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -71,9 +71,10 @@ impl<'source> ParsingContext<'source> { } _ => { // TODO: Implicit conversions - let expr = self.parse_expression(parser, ctx, body)?; + let mut stmt = ctx.stmt_ctx(); + let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; self.expect(parser, TokenValue::Semicolon)?; - Some(ctx.lower_expect(parser, expr, false, body)?.0) + Some(ctx.lower_expect(stmt, parser, expr, false, body)?.0) } }; @@ -92,8 +93,9 @@ impl<'source> ParsingContext<'source> { self.expect(parser, TokenValue::LeftParen)?; let condition = { - let expr = self.parse_expression(parser, ctx, body)?; - ctx.lower_expect(parser, expr, false, body)?.0 + let mut stmt = ctx.stmt_ctx(); + let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; + ctx.lower_expect(stmt, parser, expr, false, body)?.0 }; self.expect(parser, TokenValue::RightParen)?; @@ -120,8 +122,9 @@ impl<'source> ParsingContext<'source> { self.expect(parser, TokenValue::LeftParen)?; // TODO: Implicit conversions let selector = { - let expr = self.parse_expression(parser, ctx, body)?; - ctx.lower_expect(parser, expr, false, body)?.0 + let mut stmt = ctx.stmt_ctx(); + let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; + ctx.lower_expect(stmt, parser, expr, false, body)?.0 }; self.expect(parser, TokenValue::RightParen)?; @@ -137,8 +140,10 @@ impl<'source> ParsingContext<'source> { TokenValue::Case => { self.bump(parser)?; let value = { - let expr = self.parse_expression(parser, ctx, body)?; - let (root, meta) = ctx.lower_expect(parser, expr, false, body)?; + let mut stmt = ctx.stmt_ctx(); + let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; + let (root, meta) = + ctx.lower_expect(stmt, parser, expr, false, body)?; let constant = parser.solve_constant(ctx, root, meta)?; match parser.module.constants[constant].inner { @@ -252,11 +257,14 @@ impl<'source> ParsingContext<'source> { let mut loop_body = Block::new(); + let mut stmt = ctx.stmt_ctx(); self.expect(parser, TokenValue::LeftParen)?; - let root = self.parse_expression(parser, ctx, &mut loop_body)?; + let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; self.expect(parser, TokenValue::RightParen)?; - let expr = ctx.lower_expect(parser, root, false, &mut loop_body)?.0; + let expr = ctx + .lower_expect(stmt, parser, root, false, &mut loop_body)? + .0; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -287,12 +295,16 @@ impl<'source> ParsingContext<'source> { let mut loop_body = Block::new(); self.parse_statement(parser, ctx, &mut loop_body)?; + let mut stmt = ctx.stmt_ctx(); + self.expect(parser, TokenValue::While)?; self.expect(parser, TokenValue::LeftParen)?; - let root = self.parse_expression(parser, ctx, &mut loop_body)?; + let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; self.expect(parser, TokenValue::RightParen)?; - let expr = ctx.lower_expect(parser, root, false, &mut loop_body)?.0; + let expr = ctx + .lower_expect(stmt, parser, root, false, &mut loop_body)? + .0; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -325,8 +337,9 @@ impl<'source> ParsingContext<'source> { if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { self.parse_declaration(parser, ctx, body, false)?; } else { - let expr = self.parse_expression(parser, ctx, body)?; - ctx.lower(parser, expr, false, body)?; + let mut stmt = ctx.stmt_ctx(); + let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; + ctx.lower(stmt, parser, expr, false, body)?; self.expect(parser, TokenValue::Semicolon)?; } } @@ -361,8 +374,9 @@ impl<'source> ParsingContext<'source> { value } else { - let root = self.parse_expression(parser, ctx, &mut block)?; - ctx.lower_expect(parser, root, false, &mut block)?.0 + let mut stmt = ctx.stmt_ctx(); + let root = self.parse_expression(parser, ctx, &mut stmt, &mut block)?; + ctx.lower_expect(stmt, parser, root, false, &mut block)?.0 }; let condition = ctx.add_expression( @@ -388,8 +402,10 @@ impl<'source> ParsingContext<'source> { match self.expect_peek(parser)?.value { TokenValue::RightParen => {} _ => { - let rest = self.parse_expression(parser, ctx, &mut continuing)?; - ctx.lower(parser, rest, false, &mut continuing)?; + let mut stmt = ctx.stmt_ctx(); + let rest = + self.parse_expression(parser, ctx, &mut stmt, &mut continuing)?; + ctx.lower(stmt, parser, rest, false, &mut continuing)?; } } @@ -425,8 +441,9 @@ impl<'source> ParsingContext<'source> { | TokenValue::IntConstant(_) | TokenValue::BoolConstant(_) | TokenValue::FloatConstant(_) => { - let expr = self.parse_expression(parser, ctx, body)?; - ctx.lower(parser, expr, false, body)?; + let mut stmt = ctx.stmt_ctx(); + let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; + ctx.lower(stmt, parser, expr, false, body)?; self.expect(parser, TokenValue::Semicolon)?; } TokenValue::Semicolon => { From 551b7119432817245f477908279ea2d7aa62a3e1 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Mon, 9 Aug 2021 22:10:08 -0400 Subject: [PATCH 1205/2212] [spv-in] use grad image operand --- src/front/spv/image.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index aee635999..d7fe88cc3 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -420,6 +420,17 @@ impl> super::Parser { level = crate::SampleLevel::Exact(lod_handle); words_left -= 1; } + spirv::ImageOperands::GRAD => { + let grad_x_expr = self.next()?; + let grad_x_handle = self.lookup_expression.lookup(grad_x_expr)?.handle; + let grad_y_expr = self.next()?; + let grad_y_handle = self.lookup_expression.lookup(grad_y_expr)?.handle; + level = crate::SampleLevel::Gradient { + x: grad_x_handle, + y: grad_y_handle, + }; + words_left -= 2; + } spirv::ImageOperands::CONST_OFFSET => { let offset_constant = self.next()?; let offset_handle = self.lookup_constant.lookup(offset_constant)?.handle; From 8cb09c24c5769ea01366a3d342c31485304a4cd0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 1 Jun 2021 02:07:49 -0400 Subject: [PATCH 1206/2212] Atomics in the IR --- src/back/glsl/mod.rs | 1 + src/back/msl/writer.rs | 16 +++++++++------- src/back/spv/writer.rs | 4 +++- src/front/wgsl/mod.rs | 37 +++++++++++++++++++------------------ src/lib.rs | 2 ++ src/proc/layouter.rs | 2 +- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 5 ++++- src/valid/mod.rs | 1 + src/valid/type.rs | 36 +++++++++++++++++++++++++++++------- 10 files changed, 70 insertions(+), 36 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 679a2e3e1..5fab23dce 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -653,6 +653,7 @@ impl<'a, W: Write> Writer<'a, W> { match *inner { // Scalars are simple we just get the full name from `glsl_scalar` TypeInner::Scalar { kind, width } + | TypeInner::Atomic { kind, width } //TODO? | TypeInner::ValuePointer { size: None, kind, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ddaaf217a..fbe59241f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -47,14 +47,15 @@ impl<'a> Display for TypeContext<'a> { match ty.inner { // work around Metal toolchain bug with `uint` typedef - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - .. - } => { - write!(out, "metal::uint") - } crate::TypeInner::Scalar { kind, .. } => { - write!(out, "{}", scalar_kind_string(kind)) + let kind_str = match kind { + crate::ScalarKind::Uint => "metal::uint", + _ => scalar_kind_string(kind), + }; + write!(out, "{}", kind_str) + } + crate::TypeInner::Atomic { kind, .. } => { + write!(out, "atomic_{}", scalar_kind_string(kind)) } crate::TypeInner::Vector { size, kind, .. } => { write!( @@ -409,6 +410,7 @@ impl crate::Type { Ti::Scalar { .. } | Ti::Vector { .. } | Ti::Matrix { .. } + | Ti::Atomic { .. } | Ti::Pointer { .. } | Ti::ValuePointer { .. } => self.name.is_some(), // composite types are better to be aliased, regardless of the name diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e2ac8768c..b390cbb5c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -671,7 +671,9 @@ impl Writer { use spirv::Decoration; let instruction = match ty.inner { - crate::TypeInner::Scalar { kind, width } => self.make_scalar(id, kind, width), + crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Atomic { kind, width } => { + self.make_scalar(id, kind, width) + } crate::TypeInner::Vector { size, kind, width } => { let scalar_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size: None, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 54a4df564..7fa77d0ee 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -347,7 +347,7 @@ impl<'a> Error<'a> { } impl crate::StorageFormat { - pub fn to_wgsl(self) -> &'static str { + fn to_wgsl(self) -> &'static str { use crate::StorageFormat as Sf; match self { Sf::R8Unorm => "r8unorm", @@ -392,17 +392,15 @@ impl crate::TypeInner { /// For example `vec3`. /// /// Note: The names of a `TypeInner::Struct` is not known. Therefore this method will simply return "struct" for them. - pub fn to_wgsl( - &self, - types: &Arena, - constants: &Arena, - ) -> String { + fn to_wgsl(&self, types: &Arena, constants: &Arena) -> String { + use crate::TypeInner as Ti; + match *self { - crate::TypeInner::Scalar { kind, width } => kind.to_wgsl(width), - crate::TypeInner::Vector { size, kind, width } => { + Ti::Scalar { kind, width } => kind.to_wgsl(width), + Ti::Vector { size, kind, width } => { format!("vec{}<{}>", size as u32, kind.to_wgsl(width)) } - crate::TypeInner::Matrix { + Ti::Matrix { columns, rows, width, @@ -414,15 +412,18 @@ impl crate::TypeInner { crate::ScalarKind::Float.to_wgsl(width), ) } - crate::TypeInner::Pointer { base, .. } => { + Ti::Atomic { kind, width } => { + format!("atomic<{}>", kind.to_wgsl(width)) + } + Ti::Pointer { base, .. } => { let base = &types[base]; let name = base.name.as_deref().unwrap_or("unknown"); - format!("*{}", name) + format!("ptr<{}>", name) } - crate::TypeInner::ValuePointer { kind, width, .. } => { - format!("*{}", kind.to_wgsl(width)) + Ti::ValuePointer { kind, width, .. } => { + format!("ptr<{}>", kind.to_wgsl(width)) } - crate::TypeInner::Array { base, size, .. } => { + Ti::Array { base, size, .. } => { let member_type = &types[base]; let base = member_type.name.as_deref().unwrap_or("unknown"); match size { @@ -433,11 +434,11 @@ impl crate::TypeInner { crate::ArraySize::Dynamic => format!("{}[]", base), } } - crate::TypeInner::Struct { .. } => { + Ti::Struct { .. } => { // TODO: Actually output the struct? "struct".to_string() } - crate::TypeInner::Image { + Ti::Image { dim, arrayed, class, @@ -481,7 +482,7 @@ impl crate::TypeInner { class_suffix, dim_suffix, array_suffix, type_in_brackets ) } - crate::TypeInner::Sampler { .. } => "sampler".to_string(), + Ti::Sampler { .. } => "sampler".to_string(), } } } @@ -537,7 +538,7 @@ mod type_inner_tests { access: crate::StorageAccess::default(), }, }; - assert_eq!(ptr.to_wgsl(&types, &constants), "*MyType2"); + assert_eq!(ptr.to_wgsl(&types, &constants), "ptr"); let img1 = crate::TypeInner::Image { dim: crate::ImageDimension::D2, diff --git a/src/lib.rs b/src/lib.rs index 469a5f496..1e578662b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -509,6 +509,8 @@ pub enum TypeInner { rows: VectorSize, width: Bytes, }, + /// Atomic scalar. + Atomic { kind: ScalarKind, width: Bytes }, /// Pointer to another type. /// /// ## Pointers to non-`SIZED` types diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 03ca28698..f2921f15e 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -72,7 +72,7 @@ impl Layouter { for (ty_handle, ty) in types.iter().skip(self.layouts.len()) { let size = ty.inner.span(constants); let layout = match ty.inner { - Ti::Scalar { width, .. } => TypeLayout { + Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => TypeLayout { size, alignment: Alignment::new(width as u32).unwrap(), }, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 226780851..7919c4267 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -95,7 +95,7 @@ impl super::TypeInner { pub fn span(&self, constants: &super::Arena) -> u32 { match *self { - Self::Scalar { kind: _, width } => width as u32, + Self::Scalar { kind: _, width } | Self::Atomic { kind: _, width } => width as u32, Self::Vector { size, kind: _, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 30af80d19..297883498 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -350,7 +350,10 @@ impl<'a> ResolveContext<'a> { }) } crate::Expression::Load { pointer } => match *past(pointer).inner_with(types) { - Ti::Pointer { base, class: _ } => TypeResolution::Handle(base), + Ti::Pointer { base, class: _ } => match types[base].inner { + Ti::Atomic { kind, width } => TypeResolution::Value(Ti::Scalar { kind, width }), + _ => TypeResolution::Handle(base), + }, Ti::ValuePointer { size, kind, diff --git a/src/valid/mod.rs b/src/valid/mod.rs index d8b0be0d1..f6d3d380b 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -167,6 +167,7 @@ impl crate::TypeInner { size: crate::ArraySize::Constant(_), .. } + | Self::Atomic { .. } | Self::Pointer { .. } | Self::ValuePointer { .. } | Self::Struct { .. } => true, diff --git a/src/valid/type.rs b/src/valid/type.rs index f1ce40bce..03869e80c 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -35,20 +35,23 @@ bitflags::bitflags! { /// [`Struct`]: crate::Type::struct const SIZED = 0x2; + /// The data can be copied around. + const COPY = 0x4; + /// Can be be used for interfacing between pipeline stages. /// /// This includes non-bool scalars and vectors, matrices, and structs /// and arrays containing only interface types. - const INTERFACE = 0x4; + const INTERFACE = 0x8; /// Can be used for host-shareable structures. - const HOST_SHARED = 0x8; + const HOST_SHARED = 0x10; /// This is a top-level host-shareable type. - const TOP_LEVEL = 0x10; + const TOP_LEVEL = 0x20; /// This type can be passed as a function argument. - const ARGUMENT = 0x20; + const ARGUMENT = 0x40; } } @@ -72,6 +75,8 @@ pub enum Disalignment { pub enum TypeError { #[error("The {0:?} scalar width {1} is not supported")] InvalidWidth(crate::ScalarKind, crate::Bytes), + #[error("The {0:?} scalar width {1} is not supported for an atomic")] + InvalidAtomicWidth(crate::ScalarKind, crate::Bytes), #[error("The base handle {0:?} can not be resolved")] UnresolvedBase(Handle), #[error("Invalid type for pointer target {0:?}")] @@ -194,6 +199,7 @@ impl super::Validator { TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED + | TypeFlags::COPY | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED | TypeFlags::ARGUMENT, @@ -208,6 +214,7 @@ impl super::Validator { TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED + | TypeFlags::COPY | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED | TypeFlags::ARGUMENT, @@ -226,12 +233,26 @@ impl super::Validator { TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED + | TypeFlags::COPY | TypeFlags::INTERFACE | TypeFlags::HOST_SHARED | TypeFlags::ARGUMENT, count * (width as u32), ) } + Ti::Atomic { kind, width } => { + let good = match kind { + crate::ScalarKind::Bool | crate::ScalarKind::Float => false, + crate::ScalarKind::Sint | crate::ScalarKind::Uint => width == 4, + }; + if !good { + return Err(TypeError::InvalidAtomicWidth(kind, width)); + } + TypeInfo::new( + TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED, + width as u32, + ) + } Ti::Pointer { base, class: _ } => { if base >= handle { return Err(TypeError::UnresolvedBase(base)); @@ -252,7 +273,7 @@ impl super::Validator { TypeFlags::empty() }; - TypeInfo::new(data_flag | TypeFlags::SIZED, 0) + TypeInfo::new(data_flag | TypeFlags::SIZED | TypeFlags::COPY, 0) } Ti::ValuePointer { size: _, @@ -263,7 +284,7 @@ impl super::Validator { if !self.check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } - TypeInfo::new(TypeFlags::SIZED, 0) + TypeInfo::new(TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY, 0) } Ti::Array { base, size, stride } => { if base >= handle { @@ -366,7 +387,7 @@ impl super::Validator { } }; - let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; + let base_mask = TypeFlags::COPY | TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; TypeInfo { flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag, uniform_layout, @@ -381,6 +402,7 @@ impl super::Validator { let mut ti = TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED + | TypeFlags::COPY | TypeFlags::HOST_SHARED | TypeFlags::INTERFACE | TypeFlags::ARGUMENT, From 33db45e681614336c3dc6749de03777c24269ce5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 2 Jun 2021 14:57:05 -0400 Subject: [PATCH 1207/2212] Atomic parsing in WGSL --- src/front/spv/function.rs | 3 +-- src/front/wgsl/mod.rs | 4 ++++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 75ca69588..401c14a60 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -65,6 +65,7 @@ impl> super::Parser { pub(super) fn parse_function(&mut self, module: &mut crate::Module) -> Result<(), Error> { self.lookup_expression.clear(); self.lookup_load_override.clear(); + self.lookup_sampled_image.clear(); let result_type_id = self.next()?; let fun_id = self.next()?; @@ -391,8 +392,6 @@ impl> super::Parser { module.apply_common_default_interpolation(); - self.lookup_expression.clear(); - self.lookup_sampled_image.clear(); Ok(()) } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7fa77d0ee..8a9d9b304 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2245,6 +2245,10 @@ impl Parser { width, } } + "atomic" => { + let (kind, width) = lexer.next_scalar_generic()?; + crate::TypeInner::Atomic { kind, width } + } "ptr" => { lexer.expect_generic_paren('<')?; let (ident, span) = lexer.next_ident_with_span()?; From 8c371e80635ac19a3008d8ce69712a0f065c96b1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 5 Aug 2021 01:21:16 -0400 Subject: [PATCH 1208/2212] Atomic expressions, support in backends except HLSL and the validator. --- src/back/dot/mod.rs | 27 +++- src/back/glsl/mod.rs | 32 ++++- src/back/msl/writer.rs | 142 +++++++++++++----- src/back/spv/block.rs | 158 ++++++++++++++++++++- src/back/spv/helpers.rs | 10 ++ src/back/spv/instructions.rs | 53 ++++++- src/back/spv/mod.rs | 19 ++- src/back/wgsl/mod.rs | 12 ++ src/back/wgsl/writer.rs | 26 ++++ src/front/glsl/constants.rs | 3 + src/front/wgsl/mod.rs | 111 ++++++++++++--- src/lib.rs | 22 +++ src/proc/typifier.rs | 5 + src/valid/analyzer.rs | 11 ++ src/valid/expression.rs | 41 ++++++ src/valid/function.rs | 5 +- src/valid/interface.rs | 3 +- src/valid/type.rs | 9 +- tests/in/access.param.ron | 6 + tests/in/access.wgsl | 14 ++ tests/out/glsl/access.atomics.Compute.glsl | 28 ++++ tests/out/glsl/access.foo.Vertex.glsl | 1 + tests/out/msl/access.msl | 39 +++-- tests/out/spv/access.spvasm | 57 ++++++-- tests/out/wgsl/access.wgsl | 16 +++ tests/snapshots.rs | 3 +- 26 files changed, 756 insertions(+), 97 deletions(-) create mode 100644 tests/out/glsl/access.atomics.Compute.glsl diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index c45e1b309..0e8f47523 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -9,7 +9,10 @@ use crate::{ valid::{FunctionInfo, ModuleInfo}, }; -use std::fmt::{Error as FmtError, Write as _}; +use std::{ + borrow::Cow, + fmt::{Error as FmtError, Write as _}, +}; #[derive(Default)] struct StatementGraph { @@ -267,9 +270,9 @@ fn write_fun( if let Some(expr) = level { edges.insert("level", expr); } - std::borrow::Cow::from("ImageSize") + Cow::from("ImageSize") } - _ => format!("{:?}", query).into(), + _ => Cow::Owned(format!("{:?}", query)), }; (args, 7) } @@ -282,6 +285,24 @@ fn write_fun( edges.insert("right", right); (format!("{:?}", op).into(), 6) } + E::Atomic { pointer, fun } => { + edges.insert("pointer", pointer); + let description = match fun { + crate::AtomicFunction::Binary { op, value } => { + edges.insert("value", value); + Cow::Owned(format!("{:?}", op)) + } + crate::AtomicFunction::Min(value) => { + edges.insert("value", value); + Cow::Borrowed("Min") + } + crate::AtomicFunction::Max(value) => { + edges.insert("value", value); + Cow::Borrowed("Max") + } + }; + (description, 3) + } E::Select { condition, accept, diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5fab23dce..4026178eb 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -653,7 +653,7 @@ impl<'a, W: Write> Writer<'a, W> { match *inner { // Scalars are simple we just get the full name from `glsl_scalar` TypeInner::Scalar { kind, width } - | TypeInner::Atomic { kind, width } //TODO? + | TypeInner::Atomic { kind, width } | TypeInner::ValuePointer { size: None, kind, @@ -2109,6 +2109,36 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } + Expression::Atomic { pointer, fun } => match fun { + crate::AtomicFunction::Binary { op, value } => { + let fun_str = match op { + crate::BinaryOperator::Add => "Add", + crate::BinaryOperator::And => "And", + crate::BinaryOperator::InclusiveOr => "Or", + crate::BinaryOperator::ExclusiveOr => "Xor", + _ => unreachable!(), + }; + write!(self.out, "atomic{}(", fun_str)?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + write!(self.out, ")")?; + } + crate::AtomicFunction::Min(value) => { + write!(self.out, "atomicMin(")?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + write!(self.out, ")")?; + } + crate::AtomicFunction::Max(value) => { + write!(self.out, "atomicMax(")?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + write!(self.out, ")")?; + } + }, // `Select` is written as `condition ? accept : reject` // We wrap everything in parentheses to avoid precedence issues Expression::Select { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index fbe59241f..eeb6fc01e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -15,6 +15,10 @@ type BackendResult = Result<(), Error>; const NAMESPACE: &str = "metal"; const WRAPPED_ARRAY_FIELD: &str = "inner"; +// This is a hack: we need to pass a pointer to an atomic, +// but generally the backend isn't putting "&" in front of every pointer. +// Some more general handling of pointers is needed to be implemented here. +const ATOMIC_REFERENCE: &str = "&"; #[derive(Clone)] struct Level(usize); @@ -29,6 +33,18 @@ impl Display for Level { } } +impl crate::BinaryOperator { + fn to_msl_atomic_str(self) -> &'static str { + match self { + Self::Add => "add", + Self::And => "and", + Self::InclusiveOr => "or", + Self::ExclusiveOr => "xor", + _ => unreachable!(), + } + } +} + struct TypeContext<'a> { handle: Handle, arena: &'a crate::Arena, @@ -46,16 +62,18 @@ impl<'a> Display for TypeContext<'a> { } match ty.inner { - // work around Metal toolchain bug with `uint` typedef crate::TypeInner::Scalar { kind, .. } => { - let kind_str = match kind { - crate::ScalarKind::Uint => "metal::uint", - _ => scalar_kind_string(kind), - }; - write!(out, "{}", kind_str) + match kind { + // work around Metal toolchain bug with `uint` typedef + crate::ScalarKind::Uint => write!(out, "{}::uint", NAMESPACE), + _ => { + let kind_str = scalar_kind_string(kind); + write!(out, "{}", kind_str) + } + } } crate::TypeInner::Atomic { kind, .. } => { - write!(out, "atomic_{}", scalar_kind_string(kind)) + write!(out, "{}::atomic_{}", NAMESPACE, scalar_kind_string(kind)) } crate::TypeInner::Vector { size, kind, .. } => { write!( @@ -711,6 +729,25 @@ impl Writer { } } + fn put_atomic_fetch( + &mut self, + pointer: Handle, + key: &str, + value: Handle, + context: &ExpressionContext, + ) -> BackendResult { + write!( + self.out, + "{}::atomic_fetch_{}_explicit({}", + NAMESPACE, key, ATOMIC_REFERENCE + )?; + self.put_expression(pointer, context, true)?; + write!(self.out, ", ")?; + self.put_expression(value, context, true)?; + write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; + Ok(()) + } + fn put_expression( &mut self, expr_handle: Handle, @@ -852,13 +889,11 @@ impl Writer { // matrices, we wrap them with `float3` on load. let wrap_packed_vec_scalar_kind = match context.function.expressions[pointer] { crate::Expression::AccessIndex { base, index } => { - let ty = match context.resolve_type(base) { - &crate::TypeInner::Pointer { base, .. } => { + let ty = match *context.resolve_type(base) { + crate::TypeInner::Pointer { base, .. } => { &context.module.types[base].inner } - // This path is unexpected and shouldn't happen, but it's easier - // to leave in. - ty => ty, + ref ty => ty, }; match *ty { crate::TypeInner::Struct { @@ -874,6 +909,15 @@ impl Writer { } _ => None, }; + let is_atomic = match *context.resolve_type(pointer) { + crate::TypeInner::Pointer { base, .. } => { + match context.module.types[base].inner { + crate::TypeInner::Atomic { .. } => true, + _ => false, + } + } + _ => false, + }; if let Some(scalar_kind) = wrap_packed_vec_scalar_kind { write!( @@ -884,6 +928,14 @@ impl Writer { )?; self.put_expression(pointer, context, true)?; write!(self.out, ")")?; + } else if is_atomic { + write!( + self.out, + "{}::atomic_load_explicit({}", + NAMESPACE, ATOMIC_REFERENCE + )?; + self.put_expression(pointer, context, true)?; + write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; } else { // We don't do any dereferencing with `*` here as pointer arguments to functions // are done by `&` references and not `*` pointers. These do not need to be @@ -1004,6 +1056,17 @@ impl Writer { } } } + crate::Expression::Atomic { pointer, fun } => match fun { + crate::AtomicFunction::Binary { op, value } => { + self.put_atomic_fetch(pointer, op.to_msl_atomic_str(), value, context)?; + } + crate::AtomicFunction::Min(value) => { + self.put_atomic_fetch(pointer, "min", value, context)?; + } + crate::AtomicFunction::Max(value) => { + self.put_atomic_fetch(pointer, "max", value, context)?; + } + }, crate::Expression::Select { condition, accept, @@ -1461,39 +1524,48 @@ impl Writer { } } crate::Statement::Store { pointer, value } => { - // we can't assign fixed-size arrays let pointer_info = &context.expression.info[pointer]; - let array_size = + let (array_size, is_atomic) = match *pointer_info.ty.inner_with(&context.expression.module.types) { crate::TypeInner::Pointer { base, .. } => { match context.expression.module.types[base].inner { crate::TypeInner::Array { size: crate::ArraySize::Constant(ch), .. - } => Some(ch), - _ => None, + } => (Some(ch), false), + crate::TypeInner::Atomic { .. } => (None, true), + _ => (None, false), } } - _ => None, + _ => (None, false), }; - match array_size { - Some(const_handle) => { - let size = context.expression.module.constants[const_handle] - .to_array_length() - .unwrap(); - write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?; - self.put_expression(pointer, &context.expression, true)?; - write!(self.out, ".{}[_i] = ", WRAPPED_ARRAY_FIELD)?; - self.put_expression(value, &context.expression, true)?; - writeln!(self.out, ".{}[_i];", WRAPPED_ARRAY_FIELD)?; - } - None => { - write!(self.out, "{}", level)?; - self.put_expression(pointer, &context.expression, true)?; - write!(self.out, " = ")?; - self.put_expression(value, &context.expression, true)?; - writeln!(self.out, ";")?; - } + + // we can't assign fixed-size arrays + if let Some(const_handle) = array_size { + let size = context.expression.module.constants[const_handle] + .to_array_length() + .unwrap(); + write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?; + self.put_expression(pointer, &context.expression, true)?; + write!(self.out, ".{}[_i] = ", WRAPPED_ARRAY_FIELD)?; + self.put_expression(value, &context.expression, true)?; + writeln!(self.out, ".{}[_i];", WRAPPED_ARRAY_FIELD)?; + } else if is_atomic { + write!( + self.out, + "{}{}::atomic_store_explicit({}", + level, NAMESPACE, ATOMIC_REFERENCE + )?; + self.put_expression(pointer, &context.expression, true)?; + write!(self.out, ", ")?; + self.put_expression(value, &context.expression, true)?; + writeln!(self.out, ", {}::memory_order_relaxed);", NAMESPACE)?; + } else { + write!(self.out, "{}", level)?; + self.put_expression(pointer, &context.expression, true)?; + write!(self.out, " = ")?; + self.put_expression(value, &context.expression, true)?; + writeln!(self.out, ";")?; } } crate::Statement::ImageStore { diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 721fa52c4..9f93d3efd 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -8,6 +8,9 @@ use super::{ use crate::{arena::Handle, proc::TypeResolution}; use spirv::Word; +//TODO: should this ever be `Workgroup`? +const ATOMIC_SCOPE: spirv::Scope = spirv::Scope::Device; + fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { match *type_inner { crate::TypeInner::Scalar { .. } => Dimension::Scalar, @@ -475,6 +478,100 @@ impl<'w> BlockContext<'w> { )); id } + crate::Expression::Atomic { pointer, fun } => { + let id = self.gen_id(); + + let pointer_id = match self.write_expression_pointer(pointer, block)? { + ExpressionPointer::Ready { pointer_id } => pointer_id, + ExpressionPointer::Conditional { .. } => { + return Err(Error::FeatureNotImplemented( + "Atomics out-of-bounds handling", + )); + } + }; + + let class = match *self.fun_info[pointer].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Pointer { base: _, class } => class, + _ => unimplemented!(), + }; + let semantics = + spirv::MemorySemantics::ACQUIRE_RELEASE | class.to_spirv_semantics(); + let scope_constant_id = self.get_scope_constant(ATOMIC_SCOPE as u32)?; + let semantics_id = self.get_index_constant(semantics.bits())?; + + let instruction = match fun { + crate::AtomicFunction::Binary { op, value } => { + let value_id = self.cached[value]; + let spirv_op = match op { + crate::BinaryOperator::Add => spirv::Op::AtomicIAdd, + crate::BinaryOperator::And => spirv::Op::AtomicAnd, + crate::BinaryOperator::InclusiveOr => spirv::Op::AtomicOr, + crate::BinaryOperator::ExclusiveOr => spirv::Op::AtomicXor, + _ => unimplemented!(), + }; + Instruction::atomic_binary( + spirv_op, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ) + } + crate::AtomicFunction::Min(value) => { + let value_id = self.cached[value]; + let spirv_op = + match *self.fun_info[value].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => spirv::Op::AtomicSMin, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + } => spirv::Op::AtomicUMin, + _ => unimplemented!(), + }; + Instruction::atomic_binary( + spirv_op, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ) + } + crate::AtomicFunction::Max(value) => { + let value_id = self.cached[value]; + let spirv_op = + match *self.fun_info[value].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => spirv::Op::AtomicSMax, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + } => spirv::Op::AtomicUMax, + _ => unimplemented!(), + }; + Instruction::atomic_binary( + spirv_op, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ) + } + }; + + block.body.push(instruction); + id + } crate::Expression::Math { fun, arg, @@ -663,12 +760,36 @@ impl<'w> BlockContext<'w> { match self.write_expression_pointer(pointer, block)? { ExpressionPointer::Ready { pointer_id } => { let id = self.gen_id(); - block - .body - .push(Instruction::load(result_type_id, id, pointer_id, None)); + let atomic_class = + match *self.fun_info[pointer].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Pointer { base, class } => { + match self.ir_module.types[base].inner { + crate::TypeInner::Atomic { .. } => Some(class), + _ => None, + } + } + _ => None, + }; + let instruction = if let Some(class) = atomic_class { + let semantics = + spirv::MemorySemantics::ACQUIRE | class.to_spirv_semantics(); + let scope_constant_id = self.get_scope_constant(ATOMIC_SCOPE as u32)?; + let semantics_id = self.get_index_constant(semantics.bits())?; + Instruction::atomic_load( + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + ) + } else { + Instruction::load(result_type_id, id, pointer_id, None) + }; + block.body.push(instruction); id } ExpressionPointer::Conditional { condition, access } => { + //TODO: support atomics? self.write_conditional_indexed_load( result_type_id, condition, @@ -1577,9 +1698,34 @@ impl<'w> BlockContext<'w> { let value_id = self.cached[value]; match self.write_expression_pointer(pointer, &mut block)? { ExpressionPointer::Ready { pointer_id } => { - block - .body - .push(Instruction::store(pointer_id, value_id, None)); + let atomic_class = match *self.fun_info[pointer] + .ty + .inner_with(&self.ir_module.types) + { + crate::TypeInner::Pointer { base, class } => { + match self.ir_module.types[base].inner { + crate::TypeInner::Atomic { .. } => Some(class), + _ => None, + } + } + _ => None, + }; + let instruction = if let Some(class) = atomic_class { + let semantics = + spirv::MemorySemantics::RELEASE | class.to_spirv_semantics(); + let scope_constant_id = + self.get_scope_constant(ATOMIC_SCOPE as u32)?; + let semantics_id = self.get_index_constant(semantics.bits())?; + Instruction::atomic_store( + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ) + } else { + Instruction::store(pointer_id, value_id, None) + }; + block.body.push(instruction); } ExpressionPointer::Conditional { condition, access } => { let merge_block = self.gen_id(); diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index 2f4de389d..9db704126 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -48,3 +48,13 @@ pub(super) fn contains_builtin( false // unreachable } } + +impl crate::StorageClass { + pub(super) fn to_spirv_semantics(self) -> spirv::MemorySemantics { + match self { + Self::Storage { .. } => spirv::MemorySemantics::UNIFORM_MEMORY, + Self::WorkGroup => spirv::MemorySemantics::WORKGROUP_MEMORY, + _ => spirv::MemorySemantics::empty(), + } + } +} diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index c20e714d9..dd3947175 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -439,14 +439,30 @@ impl super::Instruction { instruction } + pub(super) fn atomic_load( + result_type_id: Word, + id: Word, + pointer_id: Word, + scope_id: Word, + semantics_id: Word, + ) -> Self { + let mut instruction = Self::new(Op::AtomicLoad); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(pointer_id); + instruction.add_operand(scope_id); + instruction.add_operand(semantics_id); + instruction + } + pub(super) fn store( pointer_id: Word, - object_id: Word, + value_id: Word, memory_access: Option, ) -> Self { let mut instruction = Self::new(Op::Store); instruction.add_operand(pointer_id); - instruction.add_operand(object_id); + instruction.add_operand(value_id); if let Some(memory_access) = memory_access { instruction.add_operand(memory_access.bits()); @@ -455,6 +471,20 @@ impl super::Instruction { instruction } + pub(super) fn atomic_store( + pointer_id: Word, + scope_id: Word, + semantics_id: Word, + value_id: Word, + ) -> Self { + let mut instruction = Self::new(Op::AtomicStore); + instruction.add_operand(pointer_id); + instruction.add_operand(scope_id); + instruction.add_operand(semantics_id); + instruction.add_operand(value_id); + instruction + } + pub(super) fn access_chain( result_type_id: Word, id: Word, @@ -734,6 +764,25 @@ impl super::Instruction { instruction } + pub(super) fn atomic_binary( + op: Op, + result_type_id: Word, + id: Word, + pointer: Word, + scope_id: Word, + semantics_id: Word, + operand: Word, + ) -> Self { + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(pointer); + instruction.add_operand(scope_id); + instruction.add_operand(semantics_id); + instruction.add_operand(operand); + instruction + } + // // Bit Instructions // diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 3666211c7..4140180a1 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -211,12 +211,14 @@ struct LookupFunctionType { fn make_local(inner: &crate::TypeInner) -> Option { Some(match *inner { - crate::TypeInner::Scalar { kind, width } => LocalType::Value { - vector_size: None, - kind, - width, - pointer_class: None, - }, + crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Atomic { kind, width } => { + LocalType::Value { + vector_size: None, + kind, + width, + pointer_class: None, + } + } crate::TypeInner::Vector { size, kind, width } => LocalType::Value { vector_size: Some(size), kind, @@ -366,6 +368,11 @@ impl BlockContext<'_> { self.writer .get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) } + + fn get_scope_constant(&mut self, scope: Word) -> Result { + self.writer + .get_constant_scalar(crate::ScalarValue::Sint(scope as _), 4) + } } #[derive(Clone, Copy, Default)] diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index 6408b5125..e8fb1e493 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -26,3 +26,15 @@ pub fn write_string( let output = w.finish(); Ok(output) } + +impl crate::BinaryOperator { + fn to_wgsl_atomic_suffix(self) -> &'static str { + match self { + Self::Add => "Add", + Self::And => "And", + Self::InclusiveOr => "Or", + Self::ExclusiveOr => "Xor", + _ => unreachable!(), + } + } +} diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 3a343d602..334bcd133 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -498,6 +498,9 @@ impl Writer { TypeInner::Scalar { kind, .. } => { write!(self.out, "{}", scalar_kind_str(kind))?; } + TypeInner::Atomic { kind, .. } => { + write!(self.out, "atomic<{}>", scalar_kind_str(kind))?; + } TypeInner::Array { base, size, .. } => { // More info https://gpuweb.github.io/gpuweb/wgsl/#array-types // array -- Constant array @@ -919,6 +922,29 @@ impl Writer { self.write_expr(module, right, func_ctx)?; write!(self.out, ")")?; } + Expression::Atomic { pointer, fun } => match fun { + crate::AtomicFunction::Binary { op, value } => { + write!(self.out, "atomic{}(", op.to_wgsl_atomic_suffix())?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + write!(self.out, ")")?; + } + crate::AtomicFunction::Min(value) => { + write!(self.out, "atomicMin(")?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + write!(self.out, ")")?; + } + crate::AtomicFunction::Max(value) => { + write!(self.out, "atomicMax(")?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + write!(self.out, ")")?; + } + }, // TODO: copy-paste from glsl-out Expression::Access { base, index } => { self.write_expr(module, base, func_ctx)?; diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index a0811d0c3..3d4c3cdbc 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -25,6 +25,8 @@ pub enum ConstantSolvingError { ArrayLengthDynamic, #[error("Constants cannot call functions")] Call, + #[error("Constants don't support atomic functions")] + Atomic, #[error("Constants don't support relational functions")] Relational, #[error("Constants don't support derivative functions")] @@ -231,6 +233,7 @@ impl<'a> ConstantSolver<'a> { } Expression::Load { .. } => Err(ConstantSolvingError::Load), + Expression::Atomic { .. } => Err(ConstantSolvingError::Atomic), Expression::Select { .. } => Err(ConstantSolvingError::Select), Expression::LocalVariable(_) => Err(ConstantSolvingError::LocalVariable), Expression::Derivative { .. } => Err(ConstantSolvingError::Derivative), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 8a9d9b304..7fbda0bf8 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1088,6 +1088,23 @@ impl Parser { Ok(Some((fun_handle, arguments))) } + fn parse_atomic_binary_op<'a>( + &mut self, + lexer: &mut Lexer<'a>, + op: crate::BinaryOperator, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result> { + lexer.open_arguments()?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let value = self.parse_singular_expression(lexer, ctx)?; + lexer.close_arguments()?; + Ok(crate::Expression::Atomic { + pointer, + fun: crate::AtomicFunction::Binary { op, value }, + }) + } + fn parse_function_call_inner<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -1127,27 +1144,74 @@ impl Parser { arg1, arg2, } - } else if name == "select" { - lexer.open_arguments()?; - let reject = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let accept = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let condition = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::Select { - condition, - accept, - reject, - } - } else if name == "arrayLength" { - lexer.open_arguments()?; - let array = self.parse_singular_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::ArrayLength(array) } else { - // texture sampling match name { + "select" => { + lexer.open_arguments()?; + let reject = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let accept = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let condition = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + crate::Expression::Select { + condition, + accept, + reject, + } + } + "arrayLength" => { + lexer.open_arguments()?; + let array = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + crate::Expression::ArrayLength(array) + } + // atomics + "atomicLoad" => { + lexer.open_arguments()?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + crate::Expression::Load { pointer } + } + "atomicAdd" => { + self.parse_atomic_binary_op(lexer, crate::BinaryOperator::Add, ctx.reborrow())? + } + "atomicAnd" => { + self.parse_atomic_binary_op(lexer, crate::BinaryOperator::And, ctx.reborrow())? + } + "atomicOr" => self.parse_atomic_binary_op( + lexer, + crate::BinaryOperator::InclusiveOr, + ctx.reborrow(), + )?, + "atomicXor" => self.parse_atomic_binary_op( + lexer, + crate::BinaryOperator::ExclusiveOr, + ctx.reborrow(), + )?, + "atomicMin" => { + lexer.open_arguments()?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let value = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + crate::Expression::Atomic { + pointer, + fun: crate::AtomicFunction::Min(value), + } + } + "atomicMax" => { + lexer.open_arguments()?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let value = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + crate::Expression::Atomic { + pointer, + fun: crate::AtomicFunction::Max(value), + } + } + // texture sampling "textureSample" => { lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; @@ -2933,6 +2997,15 @@ impl Parser { lexer.expect(Token::Paren(')'))?; block.push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP)); } + "atomicStore" => { + lexer.open_arguments()?; + let mut expression_ctx = context.as_expression(block, &mut emitter); + let pointer = self.parse_general_expression(lexer, expression_ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let value = self.parse_general_expression(lexer, expression_ctx)?; + lexer.close_arguments()?; + block.push(crate::Statement::Store { pointer, value }); + } "textureStore" => { emitter.start(context.expressions); lexer.open_arguments()?; diff --git a/src/lib.rs b/src/lib.rs index 1e578662b..7ca561c5a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -737,6 +737,22 @@ pub enum BinaryOperator { ShiftRight, } +/// Function on an atomic value. +/// +/// Note: these do not include load/store, which use the existing +/// [`Expression::Load`] and [`Statement::Store`]. +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum AtomicFunction { + Binary { + op: BinaryOperator, + value: Handle, + }, + Min(Handle), + Max(Handle), +} + /// Axis on which to compute a derivative. #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -1101,6 +1117,12 @@ pub enum Expression { left: Handle, right: Handle, }, + /// Atomic function. + Atomic { + /// Pointer to an atomic value. + pointer: Handle, + fun: AtomicFunction, + }, /// Select between two values based on a condition. /// /// Note that, because expressions have no side effects, it is unobservable diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 297883498..649a61039 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -505,6 +505,11 @@ impl<'a> ResolveContext<'a> { | crate::BinaryOperator::ShiftLeft | crate::BinaryOperator::ShiftRight => past(left).clone(), }, + crate::Expression::Atomic { pointer: _, fun } => match fun { + crate::AtomicFunction::Binary { op: _, value } + | crate::AtomicFunction::Min(value) + | crate::AtomicFunction::Max(value) => past(value).clone(), + }, crate::Expression::Select { accept, .. } => past(accept).clone(), crate::Expression::Derivative { axis: _, expr } => past(expr).clone(), crate::Expression::Relational { .. } => TypeResolution::Value(Ti::Scalar { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 3aab4fc04..8cfbe48e3 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -532,6 +532,17 @@ impl FunctionInfo { non_uniform_result: self.add_ref(left).or(self.add_ref(right)), requirements: UniformityRequirements::empty(), }, + E::Atomic { pointer, fun } => { + let non_uniform_result = match fun { + crate::AtomicFunction::Binary { op: _, value } + | crate::AtomicFunction::Min(value) + | crate::AtomicFunction::Max(value) => self.add_ref(value), + }; + Uniformity { + non_uniform_result: self.add_ref(pointer).or(non_uniform_result), + requirements: UniformityRequirements::empty(), + } + } E::Select { condition, accept, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index b63321afd..28e5a8897 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -105,6 +105,12 @@ pub enum ExpressionError { WrongArgumentCount(crate::MathFunction), #[error("Argument [{1}] to {0:?} as expression {2:?} has an invalid type.")] InvalidArgumentType(crate::MathFunction, u32, Handle), + #[error("Atomic function doesn't work on pointer to {0:?}.")] + InvalidAtomicPointer(Handle), + #[error("Atomic function doesn't work with operand {0:?}.")] + InvalidAtomicOperand(Handle), + #[error("Atomic binary op {0:?} doesn't work on {1:?}.")] + InvalidAtomicBinaryOp(crate::BinaryOperator, crate::ScalarKind), } struct ExpressionTypeResolver<'a> { @@ -776,6 +782,41 @@ impl super::Validator { } ShaderStages::all() } + E::Atomic { pointer, fun } => { + use crate::BinaryOperator as Bo; + let pointer_inner = resolver.resolve(pointer)?; + let (ptr_kind, ptr_width) = match *pointer_inner { + Ti::Pointer { base, .. } => match module.types[base].inner { + Ti::Atomic { kind, width } => (kind, width), + ref other => { + log::error!("Atomic pointer to type {:?}", other); + return Err(ExpressionError::InvalidAtomicPointer(pointer)); + } + }, + ref other => { + log::error!("Atomic on type {:?}", other); + return Err(ExpressionError::InvalidAtomicPointer(pointer)); + } + }; + let value = match fun { + crate::AtomicFunction::Binary { op, value } => { + match op { + Bo::Add | Bo::And | Bo::InclusiveOr | Bo::ExclusiveOr => {} + _ => return Err(ExpressionError::InvalidAtomicBinaryOp(op, ptr_kind)), + } + value + } + crate::AtomicFunction::Min(value) | crate::AtomicFunction::Max(value) => value, + }; + match *resolver.resolve(value)? { + Ti::Scalar { width, kind } if kind == ptr_kind && width == ptr_width => {} + ref other => { + log::error!("Atomic operand type {:?}", other); + return Err(ExpressionError::InvalidAtomicOperand(value)); + } + } + ShaderStages::all() + } E::Select { condition, accept, diff --git a/src/valid/function.rs b/src/valid/function.rs index 807db554f..178324658 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -399,7 +399,10 @@ impl super::Validator { _ => {} } let good = match *context.resolve_pointer_type(pointer)? { - Ti::Pointer { base, class: _ } => *value_ty == context.types[base].inner, + Ti::Pointer { base, class: _ } => match context.types[base].inner { + Ti::Atomic { kind, width } => *value_ty == Ti::Scalar { kind, width }, + ref other => value_ty == other, + }, Ti::ValuePointer { size: Some(size), kind, diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 22ba9becd..b715cfb2d 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -338,6 +338,7 @@ impl super::Validator { } ( TypeFlags::DATA + | TypeFlags::COPY | TypeFlags::SIZED | TypeFlags::HOST_SHARED | TypeFlags::TOP_LEVEL, @@ -361,7 +362,7 @@ impl super::Validator { )); } ( - TypeFlags::DATA | TypeFlags::HOST_SHARED | TypeFlags::SIZED, + TypeFlags::DATA | TypeFlags::COPY | TypeFlags::HOST_SHARED | TypeFlags::SIZED, false, ) } diff --git a/src/valid/type.rs b/src/valid/type.rs index 03869e80c..faf1e517d 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -16,7 +16,7 @@ bitflags::bitflags! { /// This flag is required on types of local variables, function /// arguments, array elements, and struct members. /// - /// This includes all types except `Image`, `Sampler`, `ValuePointer`, + /// This includes all types except `Image`, `Sampler`, /// and some `Pointer` types. const DATA = 0x1; @@ -258,13 +258,16 @@ impl super::Validator { return Err(TypeError::UnresolvedBase(base)); } + let base_info = &self.types[base.index()]; + if !base_info.flags.contains(TypeFlags::DATA) { + return Err(TypeError::InvalidPointerBase(base)); + } // Pointers to dynamically-sized arrays are needed, to serve as // the type of an `AccessIndex` expression referring to a // dynamically sized array appearing as the final member of a // top-level `Struct`. But such pointers cannot be passed to // functions, stored in variables, etc. So, we mark them as not // `DATA`. - let base_info = &self.types[base.index()]; let data_flag = if base_info.flags.contains(TypeFlags::SIZED) { TypeFlags::DATA | TypeFlags::ARGUMENT } else if let crate::TypeInner::Struct { .. } = types[base].inner { @@ -418,7 +421,7 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); } - if top_level && !base_info.flags.contains(TypeFlags::INTERFACE) { + if top_level && !base_info.flags.contains(TypeFlags::HOST_SHARED) { return Err(TypeError::InvalidBlockType(member.ty)); } if base_info.flags.contains(TypeFlags::TOP_LEVEL) { diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 675006b01..71227754b 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -12,6 +12,12 @@ }, sizes_buffer: Some(24), ), + cs: ( + resources: { + (group: 0, binding: 0): (buffer: Some(0), mutable: true), + }, + sizes_buffer: Some(24), + ), ), inline_samplers: [], spirv_cross_compatibility: false, diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 784bbea3c..64409c3d6 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -3,6 +3,7 @@ [[block]] struct Bar { matrix: mat4x4; + atom: atomic; arr: [[stride(8)]] array, 2>; data: [[stride(4)]] array; }; @@ -36,3 +37,16 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { return matrix * vec4(vec4(value)); } + +[[stage(compute), workgroup_size(1)]] +fn atomics() { + var tmp: i32; + let value = atomicLoad(&bar.atom); + tmp = atomicAdd(&bar.atom, 1); + tmp = atomicAnd(&bar.atom, 1); + tmp = atomicOr(&bar.atom, 1); + tmp = atomicXor(&bar.atom, 1); + tmp = atomicMin(&bar.atom, 1); + tmp = atomicMax(&bar.atom, 1); + atomicStore(&bar.atom, value); +} diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl new file mode 100644 index 000000000..1dd0daac2 --- /dev/null +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -0,0 +1,28 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +buffer Bar_block_0Cs { + mat4x4 matrix; + int atom; + uvec2 arr[2]; + int data[]; +} _group_0_binding_0; + + +void main() { + int tmp = 0; + int value = _group_0_binding_0.atom; + tmp = atomicAdd(_group_0_binding_0.atom, 1); + tmp = atomicAnd(_group_0_binding_0.atom, 1); + tmp = atomicOr(_group_0_binding_0.atom, 1); + tmp = atomicXor(_group_0_binding_0.atom, 1); + tmp = atomicMin(_group_0_binding_0.atom, 1); + tmp = atomicMax(_group_0_binding_0.atom, 1); + _group_0_binding_0.atom = value; + return; +} + diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index f5afcd162..6bd543677 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -5,6 +5,7 @@ precision highp int; buffer Bar_block_0Vs { mat4x4 matrix; + int atom; uvec2 arr[2]; int data[]; } _group_0_binding_0; diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 16bcedf55..58ea44f6c 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -6,16 +6,18 @@ struct _mslBufferSizes { metal::uint size0; }; -struct type2 { +struct type3 { metal::uint2 inner[2]; }; -typedef int type4[1]; +typedef int type5[1]; struct Bar { metal::float4x4 matrix; - type2 arr; - type4 data; + metal::atomic_int atom; + char _pad2[4]; + type3 arr; + type5 data; }; -struct type8 { +struct type9 { int inner[5]; }; @@ -30,19 +32,36 @@ vertex fooOutput foo( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo1 = 0.0; - type8 c; + type9 c; float baz = foo1; foo1 = 1.0; metal::float4x4 matrix = bar.matrix; - type2 arr = bar.arr; + type3 arr = bar.arr; metal::float4 _e13 = bar.matrix[3]; float b = _e13.x; - int a = bar.data[(1 + (_buffer_sizes.size0 - 80 - 4) / 4) - 2u]; + int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 4) - 2u]; bar.matrix[1].z = 1.0; bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); - for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type2 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; - for(int _i=0; _i<5; ++_i) c.inner[_i] = type8 {a, static_cast(b), 3, 4, 5}.inner[_i]; + for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type9 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; return fooOutput { matrix * static_cast(metal::int4(value)) }; } + + +kernel void atomics( + device Bar& bar [[buffer(0)]] +, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] +) { + int tmp; + int value = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_add_explicit(&bar.atom, 1, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_and_explicit(&bar.atom, 1, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_or_explicit(&bar.atom, 1, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_xor_explicit(&bar.atom, 1, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_min_explicit(&bar.atom, 1, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_max_explicit(&bar.atom, 1, metal::memory_order_relaxed); + metal::atomic_store_explicit(&bar.atom, value, metal::memory_order_relaxed); + return; +} diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 19727e05f..57bf3363f 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,22 +1,27 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 82 +; Bound: 105 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %39 "foo" %34 %37 +OpEntryPoint GLCompute %84 "atomics" +OpExecutionMode %84 LocalSize 1 1 1 OpSource GLSL 450 OpName %25 "Bar" OpMemberName %25 0 "matrix" -OpMemberName %25 1 "arr" -OpMemberName %25 2 "data" +OpMemberName %25 1 "atom" +OpMemberName %25 2 "arr" +OpMemberName %25 3 "data" OpName %27 "bar" OpName %29 "foo" OpName %31 "c" OpName %34 "vi" OpName %39 "foo" +OpName %82 "tmp" +OpName %84 "atomics" OpDecorate %23 ArrayStride 8 OpDecorate %24 ArrayStride 4 OpDecorate %25 Block @@ -24,7 +29,8 @@ OpMemberDecorate %25 0 Offset 0 OpMemberDecorate %25 0 ColMajor OpMemberDecorate %25 0 MatrixStride 16 OpMemberDecorate %25 1 Offset 64 -OpMemberDecorate %25 2 Offset 80 +OpMemberDecorate %25 2 Offset 72 +OpMemberDecorate %25 3 Offset 88 OpDecorate %26 ArrayStride 4 OpDecorate %27 DescriptorSet 0 OpDecorate %27 Binding 0 @@ -53,7 +59,7 @@ OpDecorate %37 BuiltIn Position %22 = OpTypeVector %9 2 %23 = OpTypeArray %22 %3 %24 = OpTypeRuntimeArray %4 -%25 = OpTypeStruct %20 %23 %24 +%25 = OpTypeStruct %20 %4 %23 %24 %26 = OpTypeArray %4 %16 %28 = OpTypePointer StorageBuffer %25 %27 = OpVariable %28 StorageBuffer @@ -72,6 +78,10 @@ OpDecorate %37 BuiltIn Position %59 = OpTypePointer StorageBuffer %6 %74 = OpTypePointer Function %4 %78 = OpTypeVector %4 4 +%86 = OpTypePointer StorageBuffer %4 +%89 = OpConstant %9 66 +%92 = OpConstant %9 72 +%104 = OpConstant %9 68 %39 = OpFunction %2 None %40 %33 = OpLabel %29 = OpVariable %30 Function %5 @@ -83,14 +93,14 @@ OpBranch %41 OpStore %29 %7 %44 = OpAccessChain %43 %27 %14 %45 = OpLoad %20 %44 -%47 = OpAccessChain %46 %27 %15 +%47 = OpAccessChain %46 %27 %10 %48 = OpLoad %23 %47 %50 = OpAccessChain %49 %27 %14 %8 %51 = OpLoad %21 %50 %52 = OpCompositeExtract %6 %51 0 -%54 = OpArrayLength %9 %27 2 +%54 = OpArrayLength %9 %27 3 %55 = OpISub %9 %54 %10 -%57 = OpAccessChain %56 %27 %10 %55 +%57 = OpAccessChain %56 %27 %8 %55 %58 = OpLoad %4 %57 %60 = OpAccessChain %59 %27 %14 %15 %10 OpStore %60 %7 @@ -104,7 +114,7 @@ OpStore %66 %65 %67 = OpCompositeConstruct %22 %14 %14 %68 = OpCompositeConstruct %22 %15 %15 %69 = OpCompositeConstruct %23 %67 %68 -%70 = OpAccessChain %46 %27 %15 +%70 = OpAccessChain %46 %27 %10 OpStore %70 %69 %71 = OpConvertFToS %4 %52 %72 = OpCompositeConstruct %26 %58 %71 %17 %18 %16 @@ -119,4 +129,33 @@ OpStore %75 %19 %81 = OpMatrixTimesVector %21 %45 %80 OpStore %37 %81 OpReturn +OpFunctionEnd +%84 = OpFunction %2 None %40 +%83 = OpLabel +%82 = OpVariable %74 Function +OpBranch %85 +%85 = OpLabel +%87 = OpAccessChain %86 %27 %15 +%88 = OpAtomicLoad %4 %87 %11 %89 +%91 = OpAccessChain %86 %27 %15 +%90 = OpAtomicIAdd %4 %91 %11 %92 %11 +OpStore %82 %90 +%94 = OpAccessChain %86 %27 %15 +%93 = OpAtomicAnd %4 %94 %11 %92 %11 +OpStore %82 %93 +%96 = OpAccessChain %86 %27 %15 +%95 = OpAtomicOr %4 %96 %11 %92 %11 +OpStore %82 %95 +%98 = OpAccessChain %86 %27 %15 +%97 = OpAtomicXor %4 %98 %11 %92 %11 +OpStore %82 %97 +%100 = OpAccessChain %86 %27 %15 +%99 = OpAtomicSMin %4 %100 %11 %92 %11 +OpStore %82 %99 +%102 = OpAccessChain %86 %27 %15 +%101 = OpAtomicSMax %4 %102 %11 %92 %11 +OpStore %82 %101 +%103 = OpAccessChain %86 %27 %15 +OpAtomicStore %103 %11 %104 %88 +OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 5efb6e706..854f033ed 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -1,6 +1,7 @@ [[block]] struct Bar { matrix: mat4x4; + atom: atomic; arr: [[stride(8)]] array,2>; data: [[stride(4)]] array; }; @@ -28,3 +29,18 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let value: i32 = c[vi]; return (matrix * vec4(vec4(value))); } + +[[stage(compute), workgroup_size(1, 1, 1)]] +fn atomics() { + var tmp: i32; + + let value: i32 = bar.atom; + tmp = atomicAdd(bar.atom, 1); + tmp = atomicAnd(bar.atom, 1); + tmp = atomicOr(bar.atom, 1); + tmp = atomicXor(bar.atom, 1); + tmp = atomicMin(bar.atom, 1); + tmp = atomicMax(bar.atom, 1); + bar.atom = value; + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 191ef8b62..12574b814 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -421,7 +421,8 @@ fn convert_wgsl() { ), ( "access", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + //TODO: atomics on HLSL + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, ), ( "control-flow", From 88c1c9037dfba40e6634533de0801ab1fc34d5fe Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 5 Aug 2021 15:13:25 -0400 Subject: [PATCH 1209/2212] Add atomic exchange function --- CHANGELOG.md | 1 + src/back/dot/mod.rs | 9 ++++++ src/back/glsl/mod.rs | 13 +++++++++ src/back/msl/writer.rs | 25 ++++++++++++++--- src/back/spv/block.rs | 15 ++++++++++ src/back/wgsl/writer.rs | 32 ++++++++++++++++++++-- src/front/wgsl/mod.rs | 24 ++++++++++++++++ src/lib.rs | 5 ++++ src/proc/typifier.rs | 19 ++++++++++++- src/valid/analyzer.rs | 6 +++- src/valid/expression.rs | 13 ++++++++- tests/in/access.wgsl | 15 ++++++---- tests/out/glsl/access.atomics.Compute.glsl | 13 +++++---- tests/out/msl/access.msl | 13 +++++---- tests/out/spv/access.spvasm | 23 +++++++++------- tests/out/wgsl/access.wgsl | 13 +++++---- 16 files changed, 195 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d095734e..03f7d72bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## TBD - API: + - atomic types and functions - WGSL `select()` order of true/false is swapped ## v0.5 (2021-06-18) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 0e8f47523..b82493328 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -300,6 +300,15 @@ fn write_fun( edges.insert("value", value); Cow::Borrowed("Max") } + crate::AtomicFunction::Exchange(value) => { + edges.insert("value", value); + Cow::Borrowed("Exchange") + } + crate::AtomicFunction::CompareExchange { cmp, value } => { + edges.insert("cmp", cmp); + edges.insert("value", value); + Cow::Borrowed("CompareExchange") + } }; (description, 3) } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 4026178eb..aabe04a3e 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2138,6 +2138,19 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(value, ctx)?; write!(self.out, ")")?; } + crate::AtomicFunction::Exchange(value) => { + write!(self.out, "atomicExchange(")?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + write!(self.out, ")")?; + } + crate::AtomicFunction::CompareExchange { .. } => { + //TODO: write a wrapper function to return vec2 + return Err(Error::Custom( + "atomic CompareExchange is not implemented".to_string(), + )); + } }, // `Select` is written as `condition ? accept : reject` // We wrap everything in parentheses to avoid precedence issues diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index eeb6fc01e..21ad99635 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1066,6 +1066,23 @@ impl Writer { crate::AtomicFunction::Max(value) => { self.put_atomic_fetch(pointer, "max", value, context)?; } + crate::AtomicFunction::Exchange(value) => { + write!( + self.out, + "{}::atomic_exchange_explicit({}", + NAMESPACE, ATOMIC_REFERENCE, + )?; + self.put_expression(pointer, context, true)?; + write!(self.out, ", ")?; + self.put_expression(value, context, true)?; + write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; + } + crate::AtomicFunction::CompareExchange { .. } => { + //TODO: add a wrapper function to return the vector + return Err(Error::FeatureNotImplemented( + "atomic CompareExchange".to_string(), + )); + } }, crate::Expression::Select { condition, @@ -2570,8 +2587,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 17664 - if stack_size < 14000 || stack_size > 19000 { + // last observed macOS value: 20752 (from CI) + if stack_size < 16000 || stack_size > 21000 { panic!("`put_expression` stack size {} has changed!", stack_size); } } @@ -2585,8 +2602,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 13600 - if stack_size < 11000 || stack_size > 16000 { + // last observed macOS value: 16160 (on CI) + if stack_size < 12000 || stack_size > 17000 { panic!("`put_block` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 9f93d3efd..6ce689084 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -567,6 +567,21 @@ impl<'w> BlockContext<'w> { value_id, ) } + crate::AtomicFunction::Exchange(value) => { + let value_id = self.cached[value]; + Instruction::atomic_binary( + spirv::Op::AtomicExchange, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ) + } + crate::AtomicFunction::CompareExchange { .. } => { + return Err(Error::FeatureNotImplemented("atomic CompareExchange")); + } }; block.body.push(instruction); diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 334bcd133..44e8fa95f 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -6,6 +6,11 @@ use crate::{ }; use std::fmt::Write; +// This is a hack: we need to pass a pointer to an atomic, +// but generally the backend isn't putting "&" in front of every pointer. +// Some more general handling of pointers is needed to be implemented here. +const ATOMIC_REFERENCE: &str = "&"; + /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; @@ -924,26 +929,47 @@ impl Writer { } Expression::Atomic { pointer, fun } => match fun { crate::AtomicFunction::Binary { op, value } => { - write!(self.out, "atomic{}(", op.to_wgsl_atomic_suffix())?; + write!( + self.out, + "atomic{}({}", + op.to_wgsl_atomic_suffix(), + ATOMIC_REFERENCE + )?; self.write_expr(module, pointer, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, value, func_ctx)?; write!(self.out, ")")?; } crate::AtomicFunction::Min(value) => { - write!(self.out, "atomicMin(")?; + write!(self.out, "atomicMin({}", ATOMIC_REFERENCE)?; self.write_expr(module, pointer, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, value, func_ctx)?; write!(self.out, ")")?; } crate::AtomicFunction::Max(value) => { - write!(self.out, "atomicMax(")?; + write!(self.out, "atomicMax({}", ATOMIC_REFERENCE)?; self.write_expr(module, pointer, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, value, func_ctx)?; write!(self.out, ")")?; } + crate::AtomicFunction::Exchange(value) => { + write!(self.out, "atomicExchange({}", ATOMIC_REFERENCE)?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + write!(self.out, ")")?; + } + crate::AtomicFunction::CompareExchange { cmp, value } => { + write!(self.out, "atomicCompareExchangeWeak({}", ATOMIC_REFERENCE)?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, cmp, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + write!(self.out, ")")?; + } }, // TODO: copy-paste from glsl-out Expression::Access { base, index } => { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7fbda0bf8..469581cf0 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1211,6 +1211,30 @@ impl Parser { fun: crate::AtomicFunction::Max(value), } } + "atomicExchange" => { + lexer.open_arguments()?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let value = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + crate::Expression::Atomic { + pointer, + fun: crate::AtomicFunction::Exchange(value), + } + } + "atomicCompareExchangeWeak" => { + lexer.open_arguments()?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let cmp = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let value = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + crate::Expression::Atomic { + pointer, + fun: crate::AtomicFunction::CompareExchange { cmp, value }, + } + } // texture sampling "textureSample" => { lexer.open_arguments()?; diff --git a/src/lib.rs b/src/lib.rs index 7ca561c5a..21a14ed6f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -751,6 +751,11 @@ pub enum AtomicFunction { }, Min(Handle), Max(Handle), + Exchange(Handle), + CompareExchange { + cmp: Handle, + value: Handle, + }, } /// Axis on which to compute a derivative. diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 649a61039..c29a4c812 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -508,7 +508,24 @@ impl<'a> ResolveContext<'a> { crate::Expression::Atomic { pointer: _, fun } => match fun { crate::AtomicFunction::Binary { op: _, value } | crate::AtomicFunction::Min(value) - | crate::AtomicFunction::Max(value) => past(value).clone(), + | crate::AtomicFunction::Max(value) + | crate::AtomicFunction::Exchange(value) => past(value).clone(), + crate::AtomicFunction::CompareExchange { cmp: _, value } => { + let (kind, width) = match *past(value).inner_with(types) { + Ti::Scalar { kind, width } => (kind, width), + ref other => { + return Err(ResolveError::IncompatibleOperands(format!( + "atomic ptr {:?}", + other + ))) + } + }; + TypeResolution::Value(Ti::Vector { + size: crate::VectorSize::Bi, + kind, + width, + }) + } }, crate::Expression::Select { accept, .. } => past(accept).clone(), crate::Expression::Derivative { axis: _, expr } => past(expr).clone(), diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 8cfbe48e3..99c13ca39 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -536,7 +536,11 @@ impl FunctionInfo { let non_uniform_result = match fun { crate::AtomicFunction::Binary { op: _, value } | crate::AtomicFunction::Min(value) - | crate::AtomicFunction::Max(value) => self.add_ref(value), + | crate::AtomicFunction::Max(value) + | crate::AtomicFunction::Exchange(value) => self.add_ref(value), + crate::AtomicFunction::CompareExchange { cmp, value } => { + self.add_ref(value).or(self.add_ref(cmp)) + } }; Uniformity { non_uniform_result: self.add_ref(pointer).or(non_uniform_result), diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 28e5a8897..9a1c90723 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -806,7 +806,18 @@ impl super::Validator { } value } - crate::AtomicFunction::Min(value) | crate::AtomicFunction::Max(value) => value, + crate::AtomicFunction::Min(value) + | crate::AtomicFunction::Max(value) + | crate::AtomicFunction::Exchange(value) => value, + crate::AtomicFunction::CompareExchange { cmp, value } => { + if resolver.resolve(cmp)? != resolver.resolve(value)? { + log::error!( + "Atomic exchange comparison has a different type from the value" + ); + return Err(ExpressionError::InvalidAtomicOperand(cmp)); + } + value + } }; match *resolver.resolve(value)? { Ti::Scalar { width, kind } if kind == ptr_kind && width == ptr_width => {} diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 64409c3d6..ba54363ed 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -42,11 +42,14 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { fn atomics() { var tmp: i32; let value = atomicLoad(&bar.atom); - tmp = atomicAdd(&bar.atom, 1); - tmp = atomicAnd(&bar.atom, 1); - tmp = atomicOr(&bar.atom, 1); - tmp = atomicXor(&bar.atom, 1); - tmp = atomicMin(&bar.atom, 1); - tmp = atomicMax(&bar.atom, 1); + tmp = atomicAdd(&bar.atom, 5); + tmp = atomicAnd(&bar.atom, 5); + tmp = atomicOr(&bar.atom, 5); + tmp = atomicXor(&bar.atom, 5); + tmp = atomicMin(&bar.atom, 5); + tmp = atomicMax(&bar.atom, 5); + tmp = atomicExchange(&bar.atom, 5); + // https://github.com/gpuweb/gpuweb/issues/2021 + // tmp = atomicCompareExchangeWeak(&bar.atom, 5, 5); atomicStore(&bar.atom, value); } diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 1dd0daac2..2e0859d2e 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -16,12 +16,13 @@ buffer Bar_block_0Cs { void main() { int tmp = 0; int value = _group_0_binding_0.atom; - tmp = atomicAdd(_group_0_binding_0.atom, 1); - tmp = atomicAnd(_group_0_binding_0.atom, 1); - tmp = atomicOr(_group_0_binding_0.atom, 1); - tmp = atomicXor(_group_0_binding_0.atom, 1); - tmp = atomicMin(_group_0_binding_0.atom, 1); - tmp = atomicMax(_group_0_binding_0.atom, 1); + tmp = atomicAdd(_group_0_binding_0.atom, 5); + tmp = atomicAnd(_group_0_binding_0.atom, 5); + tmp = atomicOr(_group_0_binding_0.atom, 5); + tmp = atomicXor(_group_0_binding_0.atom, 5); + tmp = atomicMin(_group_0_binding_0.atom, 5); + tmp = atomicMax(_group_0_binding_0.atom, 5); + tmp = atomicExchange(_group_0_binding_0.atom, 5); _group_0_binding_0.atom = value; return; } diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 58ea44f6c..abdec9dcf 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -56,12 +56,13 @@ kernel void atomics( ) { int tmp; int value = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_add_explicit(&bar.atom, 1, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_and_explicit(&bar.atom, 1, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_or_explicit(&bar.atom, 1, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_xor_explicit(&bar.atom, 1, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_min_explicit(&bar.atom, 1, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_max_explicit(&bar.atom, 1, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); metal::atomic_store_explicit(&bar.atom, value, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 57bf3363f..33920bc06 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 105 +; Bound: 107 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" @@ -81,7 +81,7 @@ OpDecorate %37 BuiltIn Position %86 = OpTypePointer StorageBuffer %4 %89 = OpConstant %9 66 %92 = OpConstant %9 72 -%104 = OpConstant %9 68 +%106 = OpConstant %9 68 %39 = OpFunction %2 None %40 %33 = OpLabel %29 = OpVariable %30 Function %5 @@ -138,24 +138,27 @@ OpBranch %85 %87 = OpAccessChain %86 %27 %15 %88 = OpAtomicLoad %4 %87 %11 %89 %91 = OpAccessChain %86 %27 %15 -%90 = OpAtomicIAdd %4 %91 %11 %92 %11 +%90 = OpAtomicIAdd %4 %91 %11 %92 %16 OpStore %82 %90 %94 = OpAccessChain %86 %27 %15 -%93 = OpAtomicAnd %4 %94 %11 %92 %11 +%93 = OpAtomicAnd %4 %94 %11 %92 %16 OpStore %82 %93 %96 = OpAccessChain %86 %27 %15 -%95 = OpAtomicOr %4 %96 %11 %92 %11 +%95 = OpAtomicOr %4 %96 %11 %92 %16 OpStore %82 %95 %98 = OpAccessChain %86 %27 %15 -%97 = OpAtomicXor %4 %98 %11 %92 %11 +%97 = OpAtomicXor %4 %98 %11 %92 %16 OpStore %82 %97 %100 = OpAccessChain %86 %27 %15 -%99 = OpAtomicSMin %4 %100 %11 %92 %11 +%99 = OpAtomicSMin %4 %100 %11 %92 %16 OpStore %82 %99 %102 = OpAccessChain %86 %27 %15 -%101 = OpAtomicSMax %4 %102 %11 %92 %11 +%101 = OpAtomicSMax %4 %102 %11 %92 %16 OpStore %82 %101 -%103 = OpAccessChain %86 %27 %15 -OpAtomicStore %103 %11 %104 %88 +%104 = OpAccessChain %86 %27 %15 +%103 = OpAtomicExchange %4 %104 %11 %92 %16 +OpStore %82 %103 +%105 = OpAccessChain %86 %27 %15 +OpAtomicStore %105 %11 %106 %88 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 854f033ed..967d6b0d3 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -35,12 +35,13 @@ fn atomics() { var tmp: i32; let value: i32 = bar.atom; - tmp = atomicAdd(bar.atom, 1); - tmp = atomicAnd(bar.atom, 1); - tmp = atomicOr(bar.atom, 1); - tmp = atomicXor(bar.atom, 1); - tmp = atomicMin(bar.atom, 1); - tmp = atomicMax(bar.atom, 1); + tmp = atomicAdd(&bar.atom, 5); + tmp = atomicAnd(&bar.atom, 5); + tmp = atomicOr(&bar.atom, 5); + tmp = atomicXor(&bar.atom, 5); + tmp = atomicMin(&bar.atom, 5); + tmp = atomicMax(&bar.atom, 5); + tmp = atomicExchange(&bar.atom, 5); bar.atom = value; return; } From bc4576c0a2d924032bcdb47b2840214df3d72824 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 6 Aug 2021 00:54:09 -0400 Subject: [PATCH 1210/2212] Make atomic operations to be statements --- src/back/dot/mod.rs | 51 ++-- src/back/glsl/mod.rs | 100 ++++---- src/back/hlsl/writer.rs | 2 +- src/back/msl/writer.rs | 84 ++++--- src/back/spv/block.rs | 238 +++++++++--------- src/back/spv/mod.rs | 2 +- src/back/spv/writer.rs | 4 +- src/back/wgsl/writer.rs | 98 ++++---- src/front/glsl/constants.rs | 4 +- src/front/glsl/functions.rs | 2 +- src/front/spv/mod.rs | 8 +- src/front/wgsl/mod.rs | 177 ++++++++----- src/lib.rs | 32 ++- src/proc/terminator.rs | 1 + src/proc/typifier.rs | 27 +- src/valid/analyzer.rs | 38 +-- src/valid/expression.rs | 72 ++---- src/valid/function.rs | 98 +++++++- tests/out/glsl/access.atomics.Compute.glsl | 21 +- tests/out/glsl/access.foo.Vertex.glsl | 4 +- tests/out/glsl/boids.main.Compute.glsl | 160 ++++++------ tests/out/glsl/interpolate.main.Vertex.glsl | 18 +- tests/out/glsl/operators.main.Compute.glsl | 6 +- tests/out/glsl/quad-vert.main.Vertex.glsl | 20 +- tests/out/glsl/shadow.fs_main.Fragment.glsl | 30 +-- tests/out/glsl/skybox.fs_main.Fragment.glsl | 4 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 18 +- tests/out/glsl/texture-arg.main.Fragment.glsl | 8 +- tests/out/ir/collatz.ron | 2 +- tests/out/ir/shadow.ron | 2 +- tests/out/msl/access.msl | 21 +- tests/out/wgsl/access.wgsl | 21 +- 32 files changed, 776 insertions(+), 597 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index b82493328..aa7af75c8 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -123,6 +123,27 @@ impl StatementGraph { self.calls.push((id, function)); "Call" } + S::Atomic { + pointer, + fun, + result, + } => { + self.emits.push((id, result)); + self.dependencies.push((id, pointer, "pointer")); + match fun { + crate::AtomicFunction::Binary { op: _, value } + | crate::AtomicFunction::Min(value) + | crate::AtomicFunction::Max(value) + | crate::AtomicFunction::Exchange(value) => { + self.dependencies.push((id, value, "value")); + } + crate::AtomicFunction::CompareExchange { cmp, value } => { + self.dependencies.push((id, cmp, "cmp")); + self.dependencies.push((id, value, "value")); + } + } + "Atomic" + } }; } root @@ -285,33 +306,6 @@ fn write_fun( edges.insert("right", right); (format!("{:?}", op).into(), 6) } - E::Atomic { pointer, fun } => { - edges.insert("pointer", pointer); - let description = match fun { - crate::AtomicFunction::Binary { op, value } => { - edges.insert("value", value); - Cow::Owned(format!("{:?}", op)) - } - crate::AtomicFunction::Min(value) => { - edges.insert("value", value); - Cow::Borrowed("Min") - } - crate::AtomicFunction::Max(value) => { - edges.insert("value", value); - Cow::Borrowed("Max") - } - crate::AtomicFunction::Exchange(value) => { - edges.insert("value", value); - Cow::Borrowed("Exchange") - } - crate::AtomicFunction::CompareExchange { cmp, value } => { - edges.insert("cmp", cmp); - edges.insert("value", value); - Cow::Borrowed("CompareExchange") - } - }; - (description, 3) - } E::Select { condition, accept, @@ -357,7 +351,8 @@ fn write_fun( }; (string.into(), 3) } - E::Call(_function) => ("Call".into(), 4), + E::CallResult(_function) => ("CallResult".into(), 4), + E::AtomicResult { .. } => ("AtomicResult".into(), 4), E::ArrayLength(expr) => { edges.insert("", expr); ("ArrayLength".into(), 7) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index aabe04a3e..c14c64694 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1327,7 +1327,7 @@ impl<'a, W: Write> Writer<'a, W> { } else { let min_ref_count = ctx.expressions[handle].bake_ref_count(); if min_ref_count <= ctx.info[handle].ref_count { - Some(format!("_expr{}", handle.index())) + Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) } else { None } @@ -1659,7 +1659,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { - let name = format!("_expr{}", expr.index()); + let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); let result = self.module.functions[function].result.as_ref().unwrap(); self.write_type(result.ty)?; write!(self.out, " {} = ", name)?; @@ -1680,6 +1680,57 @@ impl<'a, W: Write> Writer<'a, W> { self.write_slice(&arguments, |this, _, arg| this.write_expr(*arg, ctx))?; writeln!(self.out, ");")? } + Statement::Atomic { + pointer, + fun, + result, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); + let res_ty = ctx.info[result].ty.inner_with(&self.module.types); + self.write_value_type(res_ty)?; + write!(self.out, " {} = ", res_name)?; + self.named_expressions.insert(result, res_name); + match fun { + crate::AtomicFunction::Binary { op, value } => { + let fun_str = match op { + crate::BinaryOperator::Add => "Add", + crate::BinaryOperator::And => "And", + crate::BinaryOperator::InclusiveOr => "Or", + crate::BinaryOperator::ExclusiveOr => "Xor", + _ => unreachable!(), + }; + write!(self.out, "atomic{}(", fun_str)?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + } + crate::AtomicFunction::Min(value) => { + write!(self.out, "atomicMin(")?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + } + crate::AtomicFunction::Max(value) => { + write!(self.out, "atomicMax(")?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + } + crate::AtomicFunction::Exchange(value) => { + write!(self.out, "atomicExchange(")?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + } + crate::AtomicFunction::CompareExchange { .. } => { + return Err(Error::Custom( + "atomic CompareExchange is not implemented".to_string(), + )); + } + } + writeln!(self.out, ");")?; + } } Ok(()) @@ -2109,49 +2160,6 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } - Expression::Atomic { pointer, fun } => match fun { - crate::AtomicFunction::Binary { op, value } => { - let fun_str = match op { - crate::BinaryOperator::Add => "Add", - crate::BinaryOperator::And => "And", - crate::BinaryOperator::InclusiveOr => "Or", - crate::BinaryOperator::ExclusiveOr => "Xor", - _ => unreachable!(), - }; - write!(self.out, "atomic{}(", fun_str)?; - self.write_expr(pointer, ctx)?; - write!(self.out, ", ")?; - self.write_expr(value, ctx)?; - write!(self.out, ")")?; - } - crate::AtomicFunction::Min(value) => { - write!(self.out, "atomicMin(")?; - self.write_expr(pointer, ctx)?; - write!(self.out, ", ")?; - self.write_expr(value, ctx)?; - write!(self.out, ")")?; - } - crate::AtomicFunction::Max(value) => { - write!(self.out, "atomicMax(")?; - self.write_expr(pointer, ctx)?; - write!(self.out, ", ")?; - self.write_expr(value, ctx)?; - write!(self.out, ")")?; - } - crate::AtomicFunction::Exchange(value) => { - write!(self.out, "atomicExchange(")?; - self.write_expr(pointer, ctx)?; - write!(self.out, ", ")?; - self.write_expr(value, ctx)?; - write!(self.out, ")")?; - } - crate::AtomicFunction::CompareExchange { .. } => { - //TODO: write a wrapper function to return vec2 - return Err(Error::Custom( - "atomic CompareExchange is not implemented".to_string(), - )); - } - }, // `Select` is written as `condition ? accept : reject` // We wrap everything in parentheses to avoid precedence issues Expression::Select { @@ -2363,7 +2371,7 @@ impl<'a, W: Write> Writer<'a, W> { } } } - Expression::Call(_function) => unreachable!(), + Expression::CallResult(_) | Expression::AtomicResult { .. } => unreachable!(), // `ArrayLength` is written as `expr.length()` and we convert it to a uint Expression::ArrayLength(expr) => { write!(self.out, "uint(")?; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index faa2212b5..06868349e 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1667,7 +1667,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")? } // Nothing to do here, since call expression already cached - Expression::Call(_) => {} + Expression::CallResult(_) => {} _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 21ad99635..6520d6aed 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1056,34 +1056,6 @@ impl Writer { } } } - crate::Expression::Atomic { pointer, fun } => match fun { - crate::AtomicFunction::Binary { op, value } => { - self.put_atomic_fetch(pointer, op.to_msl_atomic_str(), value, context)?; - } - crate::AtomicFunction::Min(value) => { - self.put_atomic_fetch(pointer, "min", value, context)?; - } - crate::AtomicFunction::Max(value) => { - self.put_atomic_fetch(pointer, "max", value, context)?; - } - crate::AtomicFunction::Exchange(value) => { - write!( - self.out, - "{}::atomic_exchange_explicit({}", - NAMESPACE, ATOMIC_REFERENCE, - )?; - self.put_expression(pointer, context, true)?; - write!(self.out, ", ")?; - self.put_expression(value, context, true)?; - write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; - } - crate::AtomicFunction::CompareExchange { .. } => { - //TODO: add a wrapper function to return the vector - return Err(Error::FeatureNotImplemented( - "atomic CompareExchange".to_string(), - )); - } - }, crate::Expression::Select { condition, accept, @@ -1249,7 +1221,9 @@ impl Writer { write!(self.out, ")")?; } // has to be a named expression - crate::Expression::Call(_) => unreachable!(), + crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } => { + unreachable!() + } crate::Expression::ArrayLength(expr) => { self.put_array_length(expr, context)?; } @@ -1653,6 +1627,50 @@ impl Writer { // done writeln!(self.out, ");")?; } + crate::Statement::Atomic { + pointer, + fun, + result, + } => { + write!(self.out, "{}", level)?; + let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); + self.start_baking_expression(result, &context.expression, &res_name)?; + self.named_expressions.insert(result, res_name); + match fun { + crate::AtomicFunction::Binary { op, value } => { + self.put_atomic_fetch( + pointer, + op.to_msl_atomic_str(), + value, + &context.expression, + )?; + } + crate::AtomicFunction::Min(value) => { + self.put_atomic_fetch(pointer, "min", value, &context.expression)?; + } + crate::AtomicFunction::Max(value) => { + self.put_atomic_fetch(pointer, "max", value, &context.expression)?; + } + crate::AtomicFunction::Exchange(value) => { + write!( + self.out, + "{}::atomic_exchange_explicit({}", + NAMESPACE, ATOMIC_REFERENCE, + )?; + self.put_expression(pointer, &context.expression, true)?; + write!(self.out, ", ")?; + self.put_expression(value, &context.expression, true)?; + write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; + } + crate::AtomicFunction::CompareExchange { .. } => { + return Err(Error::FeatureNotImplemented( + "atomic CompareExchange".to_string(), + )); + } + } + // done + writeln!(self.out, ";")?; + } } } @@ -2587,8 +2605,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 20752 (from CI) - if stack_size < 16000 || stack_size > 21000 { + // last observed macOS value: 18304 + if stack_size < 15000 || stack_size > 20000 { panic!("`put_expression` stack size {} has changed!", stack_size); } } @@ -2602,8 +2620,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 16160 (on CI) - if stack_size < 12000 || stack_size > 17000 { + // last observed macOS value: 17504 + if stack_size < 14000 || stack_size > 19000 { panic!("`put_block` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 6ce689084..370712741 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -478,115 +478,6 @@ impl<'w> BlockContext<'w> { )); id } - crate::Expression::Atomic { pointer, fun } => { - let id = self.gen_id(); - - let pointer_id = match self.write_expression_pointer(pointer, block)? { - ExpressionPointer::Ready { pointer_id } => pointer_id, - ExpressionPointer::Conditional { .. } => { - return Err(Error::FeatureNotImplemented( - "Atomics out-of-bounds handling", - )); - } - }; - - let class = match *self.fun_info[pointer].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Pointer { base: _, class } => class, - _ => unimplemented!(), - }; - let semantics = - spirv::MemorySemantics::ACQUIRE_RELEASE | class.to_spirv_semantics(); - let scope_constant_id = self.get_scope_constant(ATOMIC_SCOPE as u32)?; - let semantics_id = self.get_index_constant(semantics.bits())?; - - let instruction = match fun { - crate::AtomicFunction::Binary { op, value } => { - let value_id = self.cached[value]; - let spirv_op = match op { - crate::BinaryOperator::Add => spirv::Op::AtomicIAdd, - crate::BinaryOperator::And => spirv::Op::AtomicAnd, - crate::BinaryOperator::InclusiveOr => spirv::Op::AtomicOr, - crate::BinaryOperator::ExclusiveOr => spirv::Op::AtomicXor, - _ => unimplemented!(), - }; - Instruction::atomic_binary( - spirv_op, - result_type_id, - id, - pointer_id, - scope_constant_id, - semantics_id, - value_id, - ) - } - crate::AtomicFunction::Min(value) => { - let value_id = self.cached[value]; - let spirv_op = - match *self.fun_info[value].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Sint, - width: _, - } => spirv::Op::AtomicSMin, - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: _, - } => spirv::Op::AtomicUMin, - _ => unimplemented!(), - }; - Instruction::atomic_binary( - spirv_op, - result_type_id, - id, - pointer_id, - scope_constant_id, - semantics_id, - value_id, - ) - } - crate::AtomicFunction::Max(value) => { - let value_id = self.cached[value]; - let spirv_op = - match *self.fun_info[value].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Sint, - width: _, - } => spirv::Op::AtomicSMax, - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: _, - } => spirv::Op::AtomicUMax, - _ => unimplemented!(), - }; - Instruction::atomic_binary( - spirv_op, - result_type_id, - id, - pointer_id, - scope_constant_id, - semantics_id, - value_id, - ) - } - crate::AtomicFunction::Exchange(value) => { - let value_id = self.cached[value]; - Instruction::atomic_binary( - spirv::Op::AtomicExchange, - result_type_id, - id, - pointer_id, - scope_constant_id, - semantics_id, - value_id, - ) - } - crate::AtomicFunction::CompareExchange { .. } => { - return Err(Error::FeatureNotImplemented("atomic CompareExchange")); - } - }; - - block.body.push(instruction); - id - } crate::Expression::Math { fun, arg, @@ -827,7 +718,9 @@ impl<'w> BlockContext<'w> { } } crate::Expression::FunctionArgument(index) => self.function.parameter_id(index), - crate::Expression::Call(_function) => self.writer.lookup_function_call[&expr_handle], + crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } => { + self.writer.lookup_statement_result[&expr_handle] + } crate::Expression::As { expr, kind, @@ -1805,13 +1698,8 @@ impl<'w> BlockContext<'w> { let type_id = match result { Some(expr) => { self.cached[expr] = id; - self.writer.lookup_function_call.insert(expr, id); - let ty_handle = self.ir_module.functions[local_function] - .result - .as_ref() - .unwrap() - .ty; - self.get_type_id(LookupType::Handle(ty_handle))? + self.writer.lookup_statement_result.insert(expr, id); + self.get_expression_type_id(&self.fun_info[expr].ty)? } None => self.writer.void_type, }; @@ -1823,6 +1711,122 @@ impl<'w> BlockContext<'w> { &self.temp_list, )); } + crate::Statement::Atomic { + pointer, + fun, + result, + } => { + let id = self.gen_id(); + let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty)?; + + self.cached[result] = id; + self.writer.lookup_statement_result.insert(result, id); + + let pointer_id = match self.write_expression_pointer(pointer, &mut block)? { + ExpressionPointer::Ready { pointer_id } => pointer_id, + ExpressionPointer::Conditional { .. } => { + return Err(Error::FeatureNotImplemented( + "Atomics out-of-bounds handling", + )); + } + }; + + let class = match *self.fun_info[pointer].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Pointer { base: _, class } => class, + _ => unimplemented!(), + }; + let semantics = + spirv::MemorySemantics::ACQUIRE_RELEASE | class.to_spirv_semantics(); + let scope_constant_id = self.get_scope_constant(ATOMIC_SCOPE as u32)?; + let semantics_id = self.get_index_constant(semantics.bits())?; + + let instruction = match fun { + crate::AtomicFunction::Binary { op, value } => { + let value_id = self.cached[value]; + let spirv_op = match op { + crate::BinaryOperator::Add => spirv::Op::AtomicIAdd, + crate::BinaryOperator::And => spirv::Op::AtomicAnd, + crate::BinaryOperator::InclusiveOr => spirv::Op::AtomicOr, + crate::BinaryOperator::ExclusiveOr => spirv::Op::AtomicXor, + _ => unimplemented!(), + }; + Instruction::atomic_binary( + spirv_op, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ) + } + crate::AtomicFunction::Min(value) => { + let value_id = self.cached[value]; + let spirv_op = + match *self.fun_info[value].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => spirv::Op::AtomicSMin, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + } => spirv::Op::AtomicUMin, + _ => unimplemented!(), + }; + Instruction::atomic_binary( + spirv_op, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ) + } + crate::AtomicFunction::Max(value) => { + let value_id = self.cached[value]; + let spirv_op = + match *self.fun_info[value].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => spirv::Op::AtomicSMax, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + } => spirv::Op::AtomicUMax, + _ => unimplemented!(), + }; + Instruction::atomic_binary( + spirv_op, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ) + } + crate::AtomicFunction::Exchange(value) => { + let value_id = self.cached[value]; + Instruction::atomic_binary( + spirv::Op::AtomicExchange, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ) + } + crate::AtomicFunction::CompareExchange { .. } => { + return Err(Error::FeatureNotImplemented("atomic CompareExchange")); + } + }; + + block.body.push(instruction); + } } } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 4140180a1..39b015728 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -396,7 +396,7 @@ pub struct Writer { lookup_type: crate::FastHashMap, lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, - lookup_function_call: crate::FastHashMap, Word>, + lookup_statement_result: crate::FastHashMap, Word>, constant_ids: Vec, cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>, global_variables: Vec, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b390cbb5c..fec4d5c33 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -78,7 +78,7 @@ impl Writer { lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), lookup_function_type: crate::FastHashMap::default(), - lookup_function_call: crate::FastHashMap::default(), + lookup_statement_result: crate::FastHashMap::default(), constant_ids: Vec::new(), cached_constants: crate::FastHashMap::default(), global_variables: Vec::new(), @@ -127,7 +127,7 @@ impl Writer { lookup_type: take(&mut self.lookup_type).recycle(), lookup_function: take(&mut self.lookup_function).recycle(), lookup_function_type: take(&mut self.lookup_function_type).recycle(), - lookup_function_call: take(&mut self.lookup_function_call).recycle(), + lookup_statement_result: take(&mut self.lookup_statement_result).recycle(), constant_ids: take(&mut self.constant_ids).recycle(), cached_constants: take(&mut self.cached_constants).recycle(), global_variables: take(&mut self.global_variables).recycle(), diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 44e8fa95f..68d1563b6 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -701,6 +701,58 @@ impl Writer { } writeln!(self.out, ");")? } + Statement::Atomic { + pointer, + fun, + result, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); + self.start_named_expr(module, result, func_ctx, &res_name)?; + self.write_expr(module, result, func_ctx)?; + self.named_expressions.insert(result, res_name); + + match fun { + crate::AtomicFunction::Binary { op, value } => { + write!( + self.out, + "atomic{}({}", + op.to_wgsl_atomic_suffix(), + ATOMIC_REFERENCE + )?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + } + crate::AtomicFunction::Min(value) => { + write!(self.out, "atomicMin({}", ATOMIC_REFERENCE)?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + } + crate::AtomicFunction::Max(value) => { + write!(self.out, "atomicMax({}", ATOMIC_REFERENCE)?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + } + crate::AtomicFunction::Exchange(value) => { + write!(self.out, "atomicExchange({}", ATOMIC_REFERENCE)?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + } + crate::AtomicFunction::CompareExchange { cmp, value } => { + write!(self.out, "atomicCompareExchangeWeak({}", ATOMIC_REFERENCE)?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, cmp, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + } + } + writeln!(self.out, ");")? + } Statement::ImageStore { image, coordinate, @@ -927,50 +979,6 @@ impl Writer { self.write_expr(module, right, func_ctx)?; write!(self.out, ")")?; } - Expression::Atomic { pointer, fun } => match fun { - crate::AtomicFunction::Binary { op, value } => { - write!( - self.out, - "atomic{}({}", - op.to_wgsl_atomic_suffix(), - ATOMIC_REFERENCE - )?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - write!(self.out, ")")?; - } - crate::AtomicFunction::Min(value) => { - write!(self.out, "atomicMin({}", ATOMIC_REFERENCE)?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - write!(self.out, ")")?; - } - crate::AtomicFunction::Max(value) => { - write!(self.out, "atomicMax({}", ATOMIC_REFERENCE)?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - write!(self.out, ")")?; - } - crate::AtomicFunction::Exchange(value) => { - write!(self.out, "atomicExchange({}", ATOMIC_REFERENCE)?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - write!(self.out, ")")?; - } - crate::AtomicFunction::CompareExchange { cmp, value } => { - write!(self.out, "atomicCompareExchangeWeak({}", ATOMIC_REFERENCE)?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, cmp, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - write!(self.out, ")")?; - } - }, // TODO: copy-paste from glsl-out Expression::Access { base, index } => { self.write_expr(module, base, func_ctx)?; @@ -1339,7 +1347,7 @@ impl Writer { write!(self.out, ")")? } // Nothing to do here, since call expression already cached - Expression::Call(_) => {} + Expression::CallResult(_) | Expression::AtomicResult { .. } => {} } Ok(()) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 3d4c3cdbc..ac0f7bef6 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -233,12 +233,12 @@ impl<'a> ConstantSolver<'a> { } Expression::Load { .. } => Err(ConstantSolvingError::Load), - Expression::Atomic { .. } => Err(ConstantSolvingError::Atomic), Expression::Select { .. } => Err(ConstantSolvingError::Select), Expression::LocalVariable(_) => Err(ConstantSolvingError::LocalVariable), Expression::Derivative { .. } => Err(ConstantSolvingError::Derivative), Expression::Relational { .. } => Err(ConstantSolvingError::Relational), - Expression::Call { .. } => Err(ConstantSolvingError::Call), + Expression::CallResult { .. } => Err(ConstantSolvingError::Call), + Expression::AtomicResult { .. } => Err(ConstantSolvingError::Atomic), Expression::FunctionArgument(_) => Err(ConstantSolvingError::FunctionArg), Expression::GlobalVariable(_) => Err(ConstantSolvingError::GlobalVariable), Expression::ImageSample { .. } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index dd2d6d0f7..7e3326bfb 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1020,7 +1020,7 @@ impl Parser { ctx.emit_flush(body); let result = if !is_void { - Some(ctx.add_expression(Expression::Call(function), body)) + Some(ctx.add_expression(Expression::CallResult(function), body)) } else { None }; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index c1e215017..438c4f4a1 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1756,7 +1756,8 @@ impl> Parser { let result = if self.lookup_void_type == Some(result_type_id) { None } else { - let expr_handle = expressions.append(crate::Expression::Call(function)); + let expr_handle = + expressions.append(crate::Expression::CallResult(function)); self.lookup_expression.insert( result_id, LookupExpression { @@ -2302,7 +2303,8 @@ impl> Parser { | S::Kill | S::Barrier(_) | S::Store { .. } - | S::ImageStore { .. } => {} + | S::ImageStore { .. } + | S::Atomic { .. } => {} S::Call { function: ref mut callee, ref arguments, @@ -2355,7 +2357,7 @@ impl> Parser { fun: &mut crate::Function, ) -> Result<(), Error> { for (_, expr) in fun.expressions.iter_mut() { - if let crate::Expression::Call(ref mut function) = *expr { + if let crate::Expression::CallResult(ref mut function) = *expr { let fun_id = self.deferred_function_calls[function.index()]; *function = *self.lookup_function.lookup(fun_id)?; } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 469581cf0..5dcdb9587 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -126,6 +126,7 @@ pub enum Error<'a> { UnknownLocalFunction(Span), InitializationTypeMismatch(Span, Handle), MissingType(Span), + InvalidAtomicOperandType(Span), Other, } @@ -337,6 +338,11 @@ impl<'a> Error<'a> { labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], notes: vec![], }, + Error::InvalidAtomicOperandType(ref span) => ParseError { + message: "atomic operand type is inconsistent with the operation".to_string(), + labels: vec![(span.clone(), "atomic operand type is invalid".into())], + notes: vec![], + }, Error::Other => ParseError { message: "other error".to_string(), labels: vec![], @@ -779,6 +785,13 @@ impl<'a> ExpressionContext<'a, '_, '_> { } Ok(left) } + + fn interrupt_emitter(&mut self, expression: crate::Expression) -> Handle { + self.block.extend(self.emitter.finish(self.expressions)); + let result = self.expressions.append(expression); + self.emitter.start(self.expressions); + result + } } enum Composition { @@ -1088,21 +1101,49 @@ impl Parser { Ok(Some((fun_handle, arguments))) } + fn parse_atomic_helper<'a, F: FnOnce(Handle) -> crate::AtomicFunction>( + &mut self, + lexer: &mut Lexer<'a>, + function_factory: F, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + lexer.open_arguments()?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let ctx_span = ctx.reborrow(); + let (value, value_span) = + lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx_span))?; + lexer.close_arguments()?; + + let expression = match *ctx.resolve_type(value)? { + crate::TypeInner::Scalar { kind, width } => crate::Expression::AtomicResult { + kind, + width, + comparison: false, + }, + _ => return Err(Error::InvalidAtomicOperandType(value_span)), + }; + + let result = ctx.interrupt_emitter(expression); + ctx.block.push(crate::Statement::Atomic { + pointer, + fun: function_factory(value), + result, + }); + Ok(result) + } + fn parse_atomic_binary_op<'a>( &mut self, lexer: &mut Lexer<'a>, op: crate::BinaryOperator, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result> { - lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let value = self.parse_singular_expression(lexer, ctx)?; - lexer.close_arguments()?; - Ok(crate::Expression::Atomic { - pointer, - fun: crate::AtomicFunction::Binary { op, value }, - }) + ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + self.parse_atomic_helper( + lexer, + |value| crate::AtomicFunction::Binary { op, value }, + ctx, + ) } fn parse_function_call_inner<'a>( @@ -1174,53 +1215,51 @@ impl Parser { crate::Expression::Load { pointer } } "atomicAdd" => { - self.parse_atomic_binary_op(lexer, crate::BinaryOperator::Add, ctx.reborrow())? + let handle = self.parse_atomic_binary_op( + lexer, + crate::BinaryOperator::Add, + ctx.reborrow(), + )?; + return Ok(Some(handle)); } "atomicAnd" => { - self.parse_atomic_binary_op(lexer, crate::BinaryOperator::And, ctx.reborrow())? + let handle = self.parse_atomic_binary_op( + lexer, + crate::BinaryOperator::And, + ctx.reborrow(), + )?; + return Ok(Some(handle)); + } + "atomicOr" => { + let handle = self.parse_atomic_binary_op( + lexer, + crate::BinaryOperator::InclusiveOr, + ctx.reborrow(), + )?; + return Ok(Some(handle)); + } + "atomicXor" => { + let handle = self.parse_atomic_binary_op( + lexer, + crate::BinaryOperator::ExclusiveOr, + ctx.reborrow(), + )?; + return Ok(Some(handle)); } - "atomicOr" => self.parse_atomic_binary_op( - lexer, - crate::BinaryOperator::InclusiveOr, - ctx.reborrow(), - )?, - "atomicXor" => self.parse_atomic_binary_op( - lexer, - crate::BinaryOperator::ExclusiveOr, - ctx.reborrow(), - )?, "atomicMin" => { - lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let value = self.parse_singular_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::Atomic { - pointer, - fun: crate::AtomicFunction::Min(value), - } + let handle = + self.parse_atomic_helper(lexer, crate::AtomicFunction::Min, ctx)?; + return Ok(Some(handle)); } "atomicMax" => { - lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let value = self.parse_singular_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::Atomic { - pointer, - fun: crate::AtomicFunction::Max(value), - } + let handle = + self.parse_atomic_helper(lexer, crate::AtomicFunction::Max, ctx)?; + return Ok(Some(handle)); } "atomicExchange" => { - lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let value = self.parse_singular_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::Atomic { - pointer, - fun: crate::AtomicFunction::Exchange(value), - } + let handle = + self.parse_atomic_helper(lexer, crate::AtomicFunction::Exchange, ctx)?; + return Ok(Some(handle)); } "atomicCompareExchangeWeak" => { lexer.open_arguments()?; @@ -1228,12 +1267,29 @@ impl Parser { lexer.expect(Token::Separator(','))?; let cmp = self.parse_singular_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let value = self.parse_singular_expression(lexer, ctx.reborrow())?; + let (value, value_span) = lexer.capture_span(|lexer| { + self.parse_singular_expression(lexer, ctx.reborrow()) + })?; lexer.close_arguments()?; - crate::Expression::Atomic { + + let expression = match *ctx.resolve_type(value)? { + crate::TypeInner::Scalar { kind, width } => { + crate::Expression::AtomicResult { + kind, + width, + comparison: true, + } + } + _ => return Err(Error::InvalidAtomicOperandType(value_span)), + }; + + let result = ctx.interrupt_emitter(expression); + ctx.block.push(crate::Statement::Atomic { pointer, fun: crate::AtomicFunction::CompareExchange { cmp, value }, - } + result, + }); + return Ok(Some(result)); } // texture sampling "textureSample" => { @@ -1511,16 +1567,14 @@ impl Parser { let handle = match self.parse_local_function_call(lexer, name, ctx.reborrow())? { Some((function, arguments)) => { - ctx.block.extend(ctx.emitter.finish(ctx.expressions)); - let result = - Some(ctx.expressions.append(crate::Expression::Call(function))); + let result = Some( + ctx.interrupt_emitter(crate::Expression::CallResult(function)), + ); ctx.block.push(crate::Statement::Call { function, arguments, result, }); - // restart the emitter - ctx.emitter.start(ctx.expressions); result } None => None, @@ -1721,12 +1775,7 @@ impl Parser { let const_handle = self.parse_const_expression_impl(token, lexer, None, ctx.types, ctx.constants)?; // pause the emitter while generating this expression, since it's pre-emitted - ctx.block.extend(ctx.emitter.finish(ctx.expressions)); - let expr = ctx - .expressions - .append(crate::Expression::Constant(const_handle)); - ctx.emitter.start(ctx.expressions); - expr + ctx.interrupt_emitter(crate::Expression::Constant(const_handle)) } (Token::Word(word), span) => { if let Some(&expr) = ctx.lookup_ident.get(word) { diff --git a/src/lib.rs b/src/lib.rs index 21a14ed6f..12a5a0283 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,7 +49,7 @@ element of an `Arena` has an index of 1, not 0.) Naga's representation of function calls is unusual. Most languages treat function calls as expressions, but because calls may have side effects, Naga represents them as a kind of statement, [`Statement::Call`]. If the function -returns a value, a call statement designates a particular [`Expression::Call`] +returns a value, a call statement designates a particular [`Expression::CallResult`] expression to represent its return value, for use by subsequent statements and expressions. @@ -87,7 +87,7 @@ Naga's rules for when `Expression`s are evaluated are as follows: a pointer. Such global variables hold opaque types like shaders or images, and cannot be assigned to. -- A [`Call`](Expression::Call) expression that is the `result` of a +- A [`Call`](Expression::CallResult) expression that is the `result` of a [`Statement::Call`], representing the call's return value, is evaluated when the `Call` statement is executed. @@ -745,6 +745,9 @@ pub enum BinaryOperator { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum AtomicFunction { + /// Binary operation of an atomic with a value. + /// + /// Note: only supports a subset of operations, defined by the validator. Binary { op: BinaryOperator, value: Handle, @@ -1122,12 +1125,6 @@ pub enum Expression { left: Handle, right: Handle, }, - /// Atomic function. - Atomic { - /// Pointer to an atomic value. - pointer: Handle, - fun: AtomicFunction, - }, /// Select between two values based on a condition. /// /// Note that, because expressions have no side effects, it is unobservable @@ -1167,7 +1164,13 @@ pub enum Expression { convert: Option, }, /// Result of calling another function. - Call(Handle), + CallResult(Handle), + /// Result of an atomic operation. + AtomicResult { + kind: ScalarKind, + width: Bytes, + comparison: bool, + }, /// Get the length of an array. /// The expression must resolve to a pointer to an array with a dynamic size. /// @@ -1311,10 +1314,19 @@ pub enum Statement { array_index: Option>, value: Handle, }, + /// Atomic function. + Atomic { + /// Pointer to an atomic value. + pointer: Handle, + /// Function to run on the atomic. + fun: AtomicFunction, + /// Emitted expression as a result. + result: Handle, + }, /// Calls a function. /// /// If the `result` is `Some`, the corresponding expression has to be - /// `Expression::Call`, and this statement serves as a barrier for any + /// `Expression::CallResult`, and this statement serves as a barrier for any /// operations on that expression. Call { function: Handle, diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index 131b62333..0f8b302cd 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -39,6 +39,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) { | Some(&mut S::Store { .. }) | Some(&mut S::ImageStore { .. }) | Some(&mut S::Call { .. }) + | Some(&mut S::Atomic { .. }) | Some(&mut S::Barrier(_)) | None => block.push(S::Return { value: None }), } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index c29a4c812..3529df804 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -505,28 +505,21 @@ impl<'a> ResolveContext<'a> { | crate::BinaryOperator::ShiftLeft | crate::BinaryOperator::ShiftRight => past(left).clone(), }, - crate::Expression::Atomic { pointer: _, fun } => match fun { - crate::AtomicFunction::Binary { op: _, value } - | crate::AtomicFunction::Min(value) - | crate::AtomicFunction::Max(value) - | crate::AtomicFunction::Exchange(value) => past(value).clone(), - crate::AtomicFunction::CompareExchange { cmp: _, value } => { - let (kind, width) = match *past(value).inner_with(types) { - Ti::Scalar { kind, width } => (kind, width), - ref other => { - return Err(ResolveError::IncompatibleOperands(format!( - "atomic ptr {:?}", - other - ))) - } - }; + crate::Expression::AtomicResult { + kind, + width, + comparison, + } => { + if comparison { TypeResolution::Value(Ti::Vector { size: crate::VectorSize::Bi, kind, width, }) + } else { + TypeResolution::Value(Ti::Scalar { kind, width }) } - }, + } crate::Expression::Select { accept, .. } => past(accept).clone(), crate::Expression::Derivative { axis: _, expr } => past(expr).clone(), crate::Expression::Relational { .. } => TypeResolution::Value(Ti::Scalar { @@ -685,7 +678,7 @@ impl<'a> ResolveContext<'a> { ))) } }, - crate::Expression::Call(function) => { + crate::Expression::CallResult(function) => { let result = self.functions[function] .result .as_ref() diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 99c13ca39..04f766c04 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -532,21 +532,6 @@ impl FunctionInfo { non_uniform_result: self.add_ref(left).or(self.add_ref(right)), requirements: UniformityRequirements::empty(), }, - E::Atomic { pointer, fun } => { - let non_uniform_result = match fun { - crate::AtomicFunction::Binary { op: _, value } - | crate::AtomicFunction::Min(value) - | crate::AtomicFunction::Max(value) - | crate::AtomicFunction::Exchange(value) => self.add_ref(value), - crate::AtomicFunction::CompareExchange { cmp, value } => { - self.add_ref(value).or(self.add_ref(cmp)) - } - }; - Uniformity { - non_uniform_result: self.add_ref(pointer).or(non_uniform_result), - requirements: UniformityRequirements::empty(), - } - } E::Select { condition, accept, @@ -582,13 +567,17 @@ impl FunctionInfo { non_uniform_result: self.add_ref(expr), requirements: UniformityRequirements::empty(), }, - E::Call(function) => { + E::CallResult(function) => { let info = other_functions .get(function.index()) .ok_or(ExpressionError::CallToUndeclaredFunction(function))?; info.uniformity.clone() } + E::AtomicResult { .. } => Uniformity { + non_uniform_result: Some(handle), + requirements: UniformityRequirements::empty(), + }, E::ArrayLength(expr) => Uniformity { non_uniform_result: self.add_ref_impl(expr, GlobalUse::QUERY), requirements: UniformityRequirements::empty(), @@ -789,6 +778,23 @@ impl FunctionInfo { //Note: the result is validated by the Validator, not here self.process_call(info, arguments, expression_arena)? } + S::Atomic { + pointer, + fun, + result: _, + } => { + let _ = self.add_ref_impl(pointer, GlobalUse::WRITE); + let _ = match fun { + crate::AtomicFunction::Binary { op: _, value } + | crate::AtomicFunction::Min(value) + | crate::AtomicFunction::Max(value) + | crate::AtomicFunction::Exchange(value) => self.add_ref(value), + crate::AtomicFunction::CompareExchange { cmp, value } => { + self.add_ref(value).or(self.add_ref(cmp)) + } + }; + FunctionUniformity::new() + } }; disruptor = disruptor.or(uniformity.exit_disruptor()); diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 9a1c90723..73cc0d132 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -105,12 +105,8 @@ pub enum ExpressionError { WrongArgumentCount(crate::MathFunction), #[error("Argument [{1}] to {0:?} as expression {2:?} has an invalid type.")] InvalidArgumentType(crate::MathFunction, u32, Handle), - #[error("Atomic function doesn't work on pointer to {0:?}.")] - InvalidAtomicPointer(Handle), - #[error("Atomic function doesn't work with operand {0:?}.")] - InvalidAtomicOperand(Handle), - #[error("Atomic binary op {0:?} doesn't work on {1:?}.")] - InvalidAtomicBinaryOp(crate::BinaryOperator, crate::ScalarKind), + #[error("Atomic result type can't be {0:?} of {1} bytes")] + InvalidAtomicResultType(crate::ScalarKind, crate::Bytes), } struct ExpressionTypeResolver<'a> { @@ -782,52 +778,6 @@ impl super::Validator { } ShaderStages::all() } - E::Atomic { pointer, fun } => { - use crate::BinaryOperator as Bo; - let pointer_inner = resolver.resolve(pointer)?; - let (ptr_kind, ptr_width) = match *pointer_inner { - Ti::Pointer { base, .. } => match module.types[base].inner { - Ti::Atomic { kind, width } => (kind, width), - ref other => { - log::error!("Atomic pointer to type {:?}", other); - return Err(ExpressionError::InvalidAtomicPointer(pointer)); - } - }, - ref other => { - log::error!("Atomic on type {:?}", other); - return Err(ExpressionError::InvalidAtomicPointer(pointer)); - } - }; - let value = match fun { - crate::AtomicFunction::Binary { op, value } => { - match op { - Bo::Add | Bo::And | Bo::InclusiveOr | Bo::ExclusiveOr => {} - _ => return Err(ExpressionError::InvalidAtomicBinaryOp(op, ptr_kind)), - } - value - } - crate::AtomicFunction::Min(value) - | crate::AtomicFunction::Max(value) - | crate::AtomicFunction::Exchange(value) => value, - crate::AtomicFunction::CompareExchange { cmp, value } => { - if resolver.resolve(cmp)? != resolver.resolve(value)? { - log::error!( - "Atomic exchange comparison has a different type from the value" - ); - return Err(ExpressionError::InvalidAtomicOperand(cmp)); - } - value - } - }; - match *resolver.resolve(value)? { - Ti::Scalar { width, kind } if kind == ptr_kind && width == ptr_width => {} - ref other => { - log::error!("Atomic operand type {:?}", other); - return Err(ExpressionError::InvalidAtomicOperand(value)); - } - } - ShaderStages::all() - } E::Select { condition, accept, @@ -1243,7 +1193,23 @@ impl super::Validator { } ShaderStages::all() } - E::Call(function) => other_infos[function.index()].available_stages, + E::CallResult(function) => other_infos[function.index()].available_stages, + E::AtomicResult { + kind, + width, + comparison: _, + } => { + let good = match kind { + crate::ScalarKind::Uint | crate::ScalarKind::Sint => { + self.check_width(kind, width) + } + _ => false, + }; + if !good { + return Err(ExpressionError::InvalidAtomicResultType(kind, width)); + } + ShaderStages::all() + } E::ArrayLength(expr) => match *resolver.resolve(expr)? { Ti::Pointer { base, .. } => { if let Some(&Ti::Array { diff --git a/src/valid/function.rs b/src/valid/function.rs index 178324658..612e979c6 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -34,6 +34,21 @@ pub enum CallError { ExpressionMismatch(Option>), } +#[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] +pub enum AtomicError { + #[error("Pointer {0:?} to atomic is invalid.")] + InvalidPointer(Handle), + #[error("Operand {0:?} has invalid type.")] + InvalidOperand(Handle), + #[error("Binary op {0:?} doesn't work on {1:?}.")] + InvalidBinaryOp(crate::BinaryOperator, crate::ScalarKind), + #[error("Result expression {0:?} has already been introduced earlier")] + ResultAlreadyInScope(Handle), + #[error("Result type for {0:?} doesn't match the statement")] + ResultTypeMismatch(Handle), +} + #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum LocalVariableError { @@ -98,6 +113,8 @@ pub enum FunctionError { #[source] error: CallError, }, + #[error("Atomic operation is invalid")] + InvalidAtomic(#[from] AtomicError), #[error( "Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}" )] @@ -239,7 +256,8 @@ impl super::Validator { return Err(CallError::ResultAlreadyInScope(expr)); } match context.expressions[expr] { - crate::Expression::Call(callee) if fun.result.is_some() && callee == function => {} + crate::Expression::CallResult(callee) + if fun.result.is_some() && callee == function => {} _ => return Err(CallError::ExpressionMismatch(result)), } } else if fun.result.is_some() { @@ -250,6 +268,77 @@ impl super::Validator { Ok(callee_info.available_stages) } + fn validate_atomic( + &mut self, + pointer: Handle, + fun: crate::AtomicFunction, + result: Handle, + context: &BlockContext, + ) -> Result<(), FunctionError> { + use crate::BinaryOperator as Bo; + + let pointer_inner = context.resolve_type(pointer, &self.valid_expression_set)?; + let (ptr_kind, ptr_width) = match *pointer_inner { + crate::TypeInner::Pointer { base, .. } => match context.types[base].inner { + crate::TypeInner::Atomic { kind, width } => (kind, width), + ref other => { + log::error!("Atomic pointer to type {:?}", other); + return Err(AtomicError::InvalidPointer(pointer).into()); + } + }, + ref other => { + log::error!("Atomic on type {:?}", other); + return Err(AtomicError::InvalidPointer(pointer).into()); + } + }; + + let value = match fun { + crate::AtomicFunction::Binary { op, value } => { + match op { + Bo::Add | Bo::And | Bo::InclusiveOr | Bo::ExclusiveOr => {} + _ => return Err(AtomicError::InvalidBinaryOp(op, ptr_kind).into()), + } + value + } + crate::AtomicFunction::Min(value) + | crate::AtomicFunction::Max(value) + | crate::AtomicFunction::Exchange(value) => value, + crate::AtomicFunction::CompareExchange { cmp, value } => { + if context.resolve_type(cmp, &self.valid_expression_set)? + != context.resolve_type(value, &self.valid_expression_set)? + { + log::error!("Atomic exchange comparison has a different type from the value"); + return Err(AtomicError::InvalidOperand(cmp).into()); + } + value + } + }; + + match *context.resolve_type(value, &self.valid_expression_set)? { + crate::TypeInner::Scalar { width, kind } if kind == ptr_kind && width == ptr_width => {} + ref other => { + log::error!("Atomic operand type {:?}", other); + return Err(AtomicError::InvalidOperand(value).into()); + } + } + + if self.valid_expression_set.insert(result.index()) { + self.valid_expression_list.push(result); + } else { + return Err(AtomicError::ResultAlreadyInScope(result).into()); + } + match context.expressions[result] { + //TODO: support atomic result with comparison + crate::Expression::AtomicResult { + kind, + width, + comparison: false, + } if kind == ptr_kind && width == ptr_width => {} + _ => return Err(AtomicError::ResultTypeMismatch(result).into()), + } + Ok(()) + } + fn validate_block_impl( &mut self, statements: &[crate::Statement], @@ -511,6 +600,13 @@ impl super::Validator { Ok(callee_stages) => stages &= callee_stages, Err(error) => return Err(FunctionError::InvalidCall { function, error }), }, + S::Atomic { + pointer, + fun, + result, + } => { + self.validate_atomic(pointer, fun, result, context)?; + } } } Ok(stages) diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 2e0859d2e..f0a982862 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -16,13 +16,20 @@ buffer Bar_block_0Cs { void main() { int tmp = 0; int value = _group_0_binding_0.atom; - tmp = atomicAdd(_group_0_binding_0.atom, 5); - tmp = atomicAnd(_group_0_binding_0.atom, 5); - tmp = atomicOr(_group_0_binding_0.atom, 5); - tmp = atomicXor(_group_0_binding_0.atom, 5); - tmp = atomicMin(_group_0_binding_0.atom, 5); - tmp = atomicMax(_group_0_binding_0.atom, 5); - tmp = atomicExchange(_group_0_binding_0.atom, 5); + int _e6 = atomicAdd(_group_0_binding_0.atom, 5); + tmp = _e6; + int _e9 = atomicAnd(_group_0_binding_0.atom, 5); + tmp = _e9; + int _e12 = atomicOr(_group_0_binding_0.atom, 5); + tmp = _e12; + int _e15 = atomicXor(_group_0_binding_0.atom, 5); + tmp = _e15; + int _e18 = atomicMin(_group_0_binding_0.atom, 5); + tmp = _e18; + int _e21 = atomicMax(_group_0_binding_0.atom, 5); + tmp = _e21; + int _e24 = atomicExchange(_group_0_binding_0.atom, 5); + tmp = _e24; _group_0_binding_0.atom = value; return; } diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index 6bd543677..c128dff78 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -19,8 +19,8 @@ void main() { foo1 = 1.0; mat4x4 matrix = _group_0_binding_0.matrix; uvec2 arr[2] = _group_0_binding_0.arr; - vec4 _expr13 = _group_0_binding_0.matrix[3]; - float b = _expr13.x; + vec4 _e13 = _group_0_binding_0.matrix[3]; + float b = _e13.x; int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)]; _group_0_binding_0.matrix[1][2] = 1.0; _group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index add4e0f9d..7a925d554 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -45,112 +45,112 @@ void main() { if ((index >= 1500u)) { return; } - vec2 _expr10 = _group_0_binding_1.particles[index].pos; - vPos = _expr10; - vec2 _expr15 = _group_0_binding_1.particles[index].vel; - vVel = _expr15; + vec2 _e10 = _group_0_binding_1.particles[index].pos; + vPos = _e10; + vec2 _e15 = _group_0_binding_1.particles[index].vel; + vVel = _e15; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); bool loop_init = true; while(true) { if (!loop_init) { - uint _expr86 = i; - i = (_expr86 + 1u); + uint _e86 = i; + i = (_e86 + 1u); } loop_init = false; - uint _expr37 = i; - if ((_expr37 >= 1500u)) { + uint _e37 = i; + if ((_e37 >= 1500u)) { break; } - uint _expr39 = i; - if ((_expr39 == index)) { + uint _e39 = i; + if ((_e39 == index)) { continue; } - uint _expr42 = i; - vec2 _expr45 = _group_0_binding_1.particles[_expr42].pos; - pos = _expr45; - uint _expr47 = i; - vec2 _expr50 = _group_0_binding_1.particles[_expr47].vel; - vel = _expr50; - vec2 _expr51 = pos; - vec2 _expr52 = vPos; - float _expr55 = _group_0_binding_0.rule1Distance; - if ((distance(_expr51, _expr52) < _expr55)) { - vec2 _expr57 = cMass; - vec2 _expr58 = pos; - cMass = (_expr57 + _expr58); - int _expr60 = cMassCount; - cMassCount = (_expr60 + 1); + uint _e42 = i; + vec2 _e45 = _group_0_binding_1.particles[_e42].pos; + pos = _e45; + uint _e47 = i; + vec2 _e50 = _group_0_binding_1.particles[_e47].vel; + vel = _e50; + vec2 _e51 = pos; + vec2 _e52 = vPos; + float _e55 = _group_0_binding_0.rule1Distance; + if ((distance(_e51, _e52) < _e55)) { + vec2 _e57 = cMass; + vec2 _e58 = pos; + cMass = (_e57 + _e58); + int _e60 = cMassCount; + cMassCount = (_e60 + 1); } - vec2 _expr63 = pos; - vec2 _expr64 = vPos; - float _expr67 = _group_0_binding_0.rule2Distance; - if ((distance(_expr63, _expr64) < _expr67)) { - vec2 _expr69 = colVel; - vec2 _expr70 = pos; - vec2 _expr71 = vPos; - colVel = (_expr69 - (_expr70 - _expr71)); + vec2 _e63 = pos; + vec2 _e64 = vPos; + float _e67 = _group_0_binding_0.rule2Distance; + if ((distance(_e63, _e64) < _e67)) { + vec2 _e69 = colVel; + vec2 _e70 = pos; + vec2 _e71 = vPos; + colVel = (_e69 - (_e70 - _e71)); } - vec2 _expr74 = pos; - vec2 _expr75 = vPos; - float _expr78 = _group_0_binding_0.rule3Distance; - if ((distance(_expr74, _expr75) < _expr78)) { - vec2 _expr80 = cVel; - vec2 _expr81 = vel; - cVel = (_expr80 + _expr81); - int _expr83 = cVelCount; - cVelCount = (_expr83 + 1); + vec2 _e74 = pos; + vec2 _e75 = vPos; + float _e78 = _group_0_binding_0.rule3Distance; + if ((distance(_e74, _e75) < _e78)) { + vec2 _e80 = cVel; + vec2 _e81 = vel; + cVel = (_e80 + _e81); + int _e83 = cVelCount; + cVelCount = (_e83 + 1); } } - int _expr89 = cMassCount; - if ((_expr89 > 0)) { - vec2 _expr92 = cMass; - int _expr93 = cMassCount; - vec2 _expr97 = vPos; - cMass = ((_expr92 / vec2(float(_expr93))) - _expr97); + int _e89 = cMassCount; + if ((_e89 > 0)) { + vec2 _e92 = cMass; + int _e93 = cMassCount; + vec2 _e97 = vPos; + cMass = ((_e92 / vec2(float(_e93))) - _e97); } - int _expr99 = cVelCount; - if ((_expr99 > 0)) { - vec2 _expr102 = cVel; - int _expr103 = cVelCount; - cVel = (_expr102 / vec2(float(_expr103))); + int _e99 = cVelCount; + if ((_e99 > 0)) { + vec2 _e102 = cVel; + int _e103 = cVelCount; + cVel = (_e102 / vec2(float(_e103))); } - vec2 _expr107 = vVel; - vec2 _expr108 = cMass; - float _expr110 = _group_0_binding_0.rule1Scale; - vec2 _expr113 = colVel; - float _expr115 = _group_0_binding_0.rule2Scale; - vec2 _expr118 = cVel; - float _expr120 = _group_0_binding_0.rule3Scale; - vVel = (((_expr107 + (_expr108 * _expr110)) + (_expr113 * _expr115)) + (_expr118 * _expr120)); - vec2 _expr123 = vVel; - vec2 _expr125 = vVel; - vVel = (normalize(_expr123) * clamp(length(_expr125), 0.0, 0.1)); - vec2 _expr131 = vPos; - vec2 _expr132 = vVel; - float _expr134 = _group_0_binding_0.deltaT; - vPos = (_expr131 + (_expr132 * _expr134)); - vec2 _expr137 = vPos; - if ((_expr137.x < -1.0)) { + vec2 _e107 = vVel; + vec2 _e108 = cMass; + float _e110 = _group_0_binding_0.rule1Scale; + vec2 _e113 = colVel; + float _e115 = _group_0_binding_0.rule2Scale; + vec2 _e118 = cVel; + float _e120 = _group_0_binding_0.rule3Scale; + vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); + vec2 _e123 = vVel; + vec2 _e125 = vVel; + vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.1)); + vec2 _e131 = vPos; + vec2 _e132 = vVel; + float _e134 = _group_0_binding_0.deltaT; + vPos = (_e131 + (_e132 * _e134)); + vec2 _e137 = vPos; + if ((_e137.x < -1.0)) { vPos.x = 1.0; } - vec2 _expr143 = vPos; - if ((_expr143.x > 1.0)) { + vec2 _e143 = vPos; + if ((_e143.x > 1.0)) { vPos.x = -1.0; } - vec2 _expr149 = vPos; - if ((_expr149.y < -1.0)) { + vec2 _e149 = vPos; + if ((_e149.y < -1.0)) { vPos.y = 1.0; } - vec2 _expr155 = vPos; - if ((_expr155.y > 1.0)) { + vec2 _e155 = vPos; + if ((_e155.y > 1.0)) { vPos.y = -1.0; } - vec2 _expr164 = vPos; - _group_0_binding_2.particles[index].pos = _expr164; - vec2 _expr168 = vVel; - _group_0_binding_2.particles[index].vel = _expr168; + vec2 _e164 = vPos; + _group_0_binding_2.particles[index].pos = _e164; + vec2 _e168 = vVel; + _group_0_binding_2.particles[index].vel = _e168; return; } diff --git a/tests/out/glsl/interpolate.main.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl index 5aefc78ed..76cdd0ac0 100644 --- a/tests/out/glsl/interpolate.main.Vertex.glsl +++ b/tests/out/glsl/interpolate.main.Vertex.glsl @@ -28,15 +28,15 @@ void main() { out1.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); out1.perspective_centroid = 2197.0; out1.perspective_sample = 2744.0; - FragmentInput _expr30 = out1; - gl_Position = _expr30.position; - _vs2fs_location0 = _expr30.flat1; - _vs2fs_location1 = _expr30.linear; - _vs2fs_location2 = _expr30.linear_centroid; - _vs2fs_location3 = _expr30.linear_sample; - _vs2fs_location4 = _expr30.perspective; - _vs2fs_location5 = _expr30.perspective_centroid; - _vs2fs_location6 = _expr30.perspective_sample; + FragmentInput _e30 = out1; + gl_Position = _e30.position; + _vs2fs_location0 = _e30.flat1; + _vs2fs_location1 = _e30.linear; + _vs2fs_location2 = _e30.linear_centroid; + _vs2fs_location3 = _e30.linear_sample; + _vs2fs_location4 = _e30.perspective; + _vs2fs_location5 = _e30.perspective_centroid; + _vs2fs_location6 = _e30.perspective_sample; return; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 332e991c8..a146d42bb 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -30,9 +30,9 @@ int unary() { } void main() { - vec4 _expr3 = builtins(); - vec4 _expr4 = splat(); - int _expr5 = unary(); + vec4 _e3 = builtins(); + vec4 _e4 = splat(); + int _e5 = unary(); return; } diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index 60f74cd94..e42681b2e 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -29,10 +29,10 @@ layout(location = 0) in vec2 _p2vs_location0; layout(location = 0) smooth out vec2 _vs2fs_location0; void main2() { - vec2 _expr12 = a_uv1; - v_uv = _expr12; - vec2 _expr13 = a_pos1; - perVertexStruct.gen_gl_Position = vec4(_expr13.x, _expr13.y, 0.0, 1.0); + vec2 _e12 = a_uv1; + v_uv = _e12; + vec2 _e13 = a_pos1; + perVertexStruct.gen_gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); return; } @@ -42,12 +42,12 @@ void main() { a_uv1 = a_uv; a_pos1 = a_pos; main2(); - vec2 _expr10 = v_uv; - vec4 _expr11 = perVertexStruct.gen_gl_Position; - float _expr12 = perVertexStruct.gen_gl_PointSize; - float _expr13[1] = perVertexStruct.gen_gl_ClipDistance; - float _expr14[1] = perVertexStruct.gen_gl_CullDistance; - type10 _tmp_return = type10(_expr10, _expr11, _expr12, _expr13, _expr14); + vec2 _e10 = v_uv; + vec4 _e11 = perVertexStruct.gen_gl_Position; + float _e12 = perVertexStruct.gen_gl_PointSize; + float _e13[1] = perVertexStruct.gen_gl_ClipDistance; + float _e14[1] = perVertexStruct.gen_gl_CullDistance; + type10 _tmp_return = type10(_e10, _e11, _e12, _e13, _e14); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 95466dc3a..e3502e2bc 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -29,8 +29,8 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } vec2 flip_correction = vec2(0.5, -0.5); vec2 light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - float _expr26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); - return _expr26; + float _e26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); + return _e26; } void main() { @@ -42,26 +42,26 @@ void main() { bool loop_init = true; while(true) { if (!loop_init) { - uint _expr40 = i; - i = (_expr40 + 1u); + uint _e40 = i; + i = (_e40 + 1u); } loop_init = false; - uint _expr12 = i; - uvec4 _expr14 = _group_0_binding_0.num_lights; - if ((_expr12 >= min(_expr14.x, 10u))) { + uint _e12 = i; + uvec4 _e14 = _group_0_binding_0.num_lights; + if ((_e12 >= min(_e14.x, 10u))) { break; } - uint _expr19 = i; - Light light = _group_0_binding_1.data[_expr19]; - uint _expr22 = i; - float _expr25 = fetch_shadow(_expr22, (light.proj * position)); + uint _e19 = i; + Light light = _group_0_binding_1.data[_e19]; + uint _e22 = i; + float _e25 = fetch_shadow(_e22, (light.proj * position)); vec3 light_dir = normalize((light.pos.xyz - position.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); - vec3 _expr34 = color; - color = (_expr34 + ((_expr25 * diffuse) * light.color.xyz)); + vec3 _e34 = color; + color = (_e34 + ((_e25 * diffuse) * light.color.xyz)); } - vec3 _expr43 = color; - _fs2p_location0 = vec4(_expr43, 1.0); + vec3 _e43 = color; + _fs2p_location0 = vec4(_e43, 1.0); return; } diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index 9cf825635..fa0b46f02 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -15,8 +15,8 @@ layout(location = 0) out vec4 _fs2p_location0; void main() { VertexOutput in1 = VertexOutput(gl_FragCoord, _vs2fs_location0); - vec4 _expr5 = texture(_group_0_binding_1, vec3(in1.uv)); - _fs2p_location0 = _expr5; + vec4 _e5 = texture(_group_0_binding_1, vec3(in1.uv)); + _fs2p_location0 = _e5; return; } diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index bae80935e..5f66bc1c6 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -21,15 +21,15 @@ void main() { int tmp2_ = 0; tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); - int _expr10 = tmp1_; - int _expr16 = tmp2_; - vec4 pos = vec4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); - vec4 _expr27 = _group_0_binding_0.view[0]; - vec4 _expr31 = _group_0_binding_0.view[1]; - vec4 _expr35 = _group_0_binding_0.view[2]; - mat3x3 inv_model_view = transpose(mat3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz)); - mat4x4 _expr40 = _group_0_binding_0.proj_inv; - vec4 unprojected = (_expr40 * pos); + int _e10 = tmp1_; + int _e16 = tmp2_; + vec4 pos = vec4(((float(_e10) * 4.0) - 1.0), ((float(_e16) * 4.0) - 1.0), 0.0, 1.0); + vec4 _e27 = _group_0_binding_0.view[0]; + vec4 _e31 = _group_0_binding_0.view[1]; + vec4 _e35 = _group_0_binding_0.view[2]; + mat3x3 inv_model_view = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); + mat4x4 _e40 = _group_0_binding_0.proj_inv; + vec4 unprojected = (_e40 * pos); VertexOutput _tmp_return = VertexOutput(pos, (inv_model_view * unprojected.xyz)); gl_Position = _tmp_return.position; _vs2fs_location0 = _tmp_return.uv; diff --git a/tests/out/glsl/texture-arg.main.Fragment.glsl b/tests/out/glsl/texture-arg.main.Fragment.glsl index 2c71caf43..3d46d1cd8 100644 --- a/tests/out/glsl/texture-arg.main.Fragment.glsl +++ b/tests/out/glsl/texture-arg.main.Fragment.glsl @@ -8,13 +8,13 @@ uniform highp sampler2D _group_0_binding_0; layout(location = 0) out vec4 _fs2p_location0; vec4 test(highp sampler2D Passed_Texture) { - vec4 _expr7 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); - return _expr7; + vec4 _e7 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); + return _e7; } void main() { - vec4 _expr2 = test(_group_0_binding_0); - _fs2p_location0 = _expr2; + vec4 _e2 = test(_group_0_binding_0); + _fs2p_location0 = _e2; return; } diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index c2e984f9a..bd2e15ee3 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -320,7 +320,7 @@ Load( pointer: 8, ), - Call(1), + CallResult(1), ], named_expressions: {}, body: [ diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 91bbd48db..52fa481c8 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -1189,7 +1189,7 @@ left: 61, right: 62, ), - Call(1), + CallResult(1), Load( pointer: 2, ), diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index abdec9dcf..fa0be834b 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -56,13 +56,20 @@ kernel void atomics( ) { int tmp; int value = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + int _e6 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e6; + int _e9 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e9; + int _e12 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e12; + int _e15 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e15; + int _e18 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e18; + int _e21 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e21; + int _e24 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e24; metal::atomic_store_explicit(&bar.atom, value, metal::memory_order_relaxed); return; } diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 967d6b0d3..9df5db293 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -35,13 +35,20 @@ fn atomics() { var tmp: i32; let value: i32 = bar.atom; - tmp = atomicAdd(&bar.atom, 5); - tmp = atomicAnd(&bar.atom, 5); - tmp = atomicOr(&bar.atom, 5); - tmp = atomicXor(&bar.atom, 5); - tmp = atomicMin(&bar.atom, 5); - tmp = atomicMax(&bar.atom, 5); - tmp = atomicExchange(&bar.atom, 5); + let _e6: i32 = atomicAdd(&bar.atom, 5); + tmp = _e6; + let _e9: i32 = atomicAnd(&bar.atom, 5); + tmp = _e9; + let _e12: i32 = atomicOr(&bar.atom, 5); + tmp = _e12; + let _e15: i32 = atomicXor(&bar.atom, 5); + tmp = _e15; + let _e18: i32 = atomicMin(&bar.atom, 5); + tmp = _e18; + let _e21: i32 = atomicMax(&bar.atom, 5); + tmp = _e21; + let _e24: i32 = atomicExchange(&bar.atom, 5); + tmp = _e24; bar.atom = value; return; } From 78f225a37a3ca405299b2d2991ac07d2742e9abb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 6 Aug 2021 01:18:51 -0400 Subject: [PATCH 1211/2212] Implemented atomics in HLSL-out --- src/back/hlsl/conv.rs | 13 ++++ src/back/hlsl/storage.rs | 2 +- src/back/hlsl/writer.rs | 125 +++++++++++++++++++++--------- tests/out/hlsl/access.hlsl | 32 +++++++- tests/out/hlsl/access.hlsl.config | 2 +- tests/snapshots.rs | 3 +- 6 files changed, 134 insertions(+), 43 deletions(-) diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 229158973..958858c41 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -122,3 +122,16 @@ impl crate::Sampling { } } } + +impl crate::BinaryOperator { + /// Return the HLSL suffix for the `InterlockedXxx` method. + pub(super) fn to_hlsl_atomic_suffix(self) -> &'static str { + match self { + Self::Add => "Add", + Self::And => "And", + Self::InclusiveOr => "Or", + Self::ExclusiveOr => "Xor", + _ => "", + } + } +} diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index d16c17c47..3ba13f545 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -40,7 +40,7 @@ pub(super) enum StoreValue { } impl super::Writer<'_, W> { - fn write_storage_address( + pub(super) fn write_storage_address( &mut self, module: &crate::Module, chain: &[SubAccess], diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 06868349e..5d651fe41 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -8,7 +8,7 @@ use crate::{ proc::{self, NameKey}, valid, Handle, Module, ShaderStage, TypeInner, }; -use std::fmt; +use std::{fmt, mem}; const LOCATION_SEMANTIC: &str = "LOC"; const SPECIAL_CBUF_TYPE: &str = "NagaConstants"; @@ -992,38 +992,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, ";")? } } - Statement::Call { - function, - ref arguments, - result, - } => { - write!(self.out, "{}", INDENT.repeat(indent))?; - if let Some(expr) = result { - write!(self.out, "const ")?; - let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); - let expr_ty = &func_ctx.info[expr].ty; - match *expr_ty { - proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?, - proc::TypeResolution::Value(ref value) => { - self.write_value_type(module, value)? - } - }; - write!(self.out, " {} = ", name)?; - self.write_expr(module, expr, func_ctx)?; - self.named_expressions.insert(expr, name); - } - let func_name = &self.names[&NameKey::Function(function)]; - write!(self.out, "{}(", func_name)?; - for (index, argument) in arguments.iter().enumerate() { - self.write_expr(module, *argument, func_ctx)?; - // Only write a comma if isn't the last element - if index != arguments.len().saturating_sub(1) { - // The leading space is for readability only - write!(self.out, ", ")?; - } - } - writeln!(self.out, ");")? - } Statement::Loop { ref body, ref continuing, @@ -1107,7 +1075,94 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, value, func_ctx)?; writeln!(self.out, ";")?; } - _ => return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))), + Statement::Call { + function, + ref arguments, + result, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + if let Some(expr) = result { + write!(self.out, "const ")?; + let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); + let expr_ty = &func_ctx.info[expr].ty; + match *expr_ty { + proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?, + proc::TypeResolution::Value(ref value) => { + self.write_value_type(module, value)? + } + }; + write!(self.out, " {} = ", name)?; + self.named_expressions.insert(expr, name); + } + let func_name = &self.names[&NameKey::Function(function)]; + write!(self.out, "{}(", func_name)?; + for (index, argument) in arguments.iter().enumerate() { + self.write_expr(module, *argument, func_ctx)?; + // Only write a comma if isn't the last element + if index != arguments.len().saturating_sub(1) { + // The leading space is for readability only + write!(self.out, ", ")?; + } + } + writeln!(self.out, ");")? + } + Statement::Atomic { + pointer, + fun, + result, + } => { + write!(self.out, "{}", INDENT.repeat(indent))?; + let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); + match func_ctx.info[result].ty { + proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?, + proc::TypeResolution::Value(ref value) => { + self.write_value_type(module, value)? + } + }; + + let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; + // working around the borrow checker in `self.write_expr` + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + + write!(self.out, " {}; {}.Interlocked", res_name, var_name)?; + match fun { + crate::AtomicFunction::Binary { op, value } => { + let suffix = op.to_hlsl_atomic_suffix(); + write!(self.out, "{}(", suffix)?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + } + crate::AtomicFunction::Min(value) => { + write!(self.out, "Min(")?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + } + crate::AtomicFunction::Max(value) => { + write!(self.out, "Max(")?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + } + crate::AtomicFunction::Exchange(value) => { + write!(self.out, "Exchange(")?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + } + crate::AtomicFunction::CompareExchange { .. } => { + return Err(Error::Unimplemented("atomic CompareExchange".to_string())); + } + } + writeln!(self.out, ", {});", res_name)?; + self.temp_access_chain = chain; + self.named_expressions.insert(result, res_name); + } + Statement::Switch { .. } => { + return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))) + } } Ok(()) @@ -1667,7 +1722,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")? } // Nothing to do here, since call expression already cached - Expression::CallResult(_) => {} + Expression::CallResult(_) | Expression::AtomicResult { .. } => {} _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 4e1494a9c..d724bbcaf 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -20,10 +20,10 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position float baz = foo1; foo1 = 1.0; float4x4 matrix1 = transpose(float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48)))); - uint2 arr[2] = {asuint(bar.Load2(64+0)), asuint(bar.Load2(64+8))}; + uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))}; float4 _expr13 = asfloat(bar.Load4(48+0)); float b = _expr13.x; - int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 80) / 4) - 2u)*4+80)); + int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 4) - 2u)*4+88)); bar.Store(8+16+0, asuint(1.0)); { float4x4 _value2 = transpose(float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx))); @@ -34,8 +34,8 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position } { uint2 _value2[2] = { uint2(0u.xx), uint2(1u.xx) }; - bar.Store2(64+0, asuint(_value2[0])); - bar.Store2(64+8, asuint(_value2[1])); + bar.Store2(72+0, asuint(_value2[0])); + bar.Store2(72+8, asuint(_value2[1])); } { int _result[5]={ a, int(b), 3, 4, 5 }; @@ -45,3 +45,27 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position int value = c[vertexinput_foo.vi1]; return mul(matrix1, float4(int4(value.xxxx))); } + +[numthreads(1, 1, 1)] +void atomics() +{ + int tmp = (int)0; + + int value = asint(bar.Load(64)); + int _e6; bar.InterlockedAdd(64, 5, _e6); + tmp = _e6; + int _e9; bar.InterlockedAnd(64, 5, _e9); + tmp = _e9; + int _e12; bar.InterlockedOr(64, 5, _e12); + tmp = _e12; + int _e15; bar.InterlockedXor(64, 5, _e15); + tmp = _e15; + int _e18; bar.InterlockedMin(64, 5, _e18); + tmp = _e18; + int _e21; bar.InterlockedMax(64, 5, _e21); + tmp = _e21; + int _e24; bar.InterlockedExchange(64, 5, _e24); + tmp = _e24; + bar.Store(64, asuint(value)); + return; +} diff --git a/tests/out/hlsl/access.hlsl.config b/tests/out/hlsl/access.hlsl.config index 0f887fb4c..49dcb6821 100644 --- a/tests/out/hlsl/access.hlsl.config +++ b/tests/out/hlsl/access.hlsl.config @@ -1,3 +1,3 @@ vertex=(foo:vs_5_1 ) fragment=() -compute=() +compute=(atomics:cs_5_1 ) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 12574b814..191ef8b62 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -421,8 +421,7 @@ fn convert_wgsl() { ), ( "access", - //TODO: atomics on HLSL - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "control-flow", From 1121a815ac156f62e5ba1035dc422fb11d9016f2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 8 Aug 2021 01:34:13 -0400 Subject: [PATCH 1212/2212] Separate enum for atomic binary operations --- src/back/dot/mod.rs | 17 ++--- src/back/glsl/mod.rs | 66 +++++++---------- src/back/hlsl/conv.rs | 9 ++- src/back/hlsl/writer.rs | 44 ++++------- src/back/msl/writer.rs | 43 +++++------ src/back/spv/block.rs | 138 ++++++++++++++++++----------------- src/back/spv/helpers.rs | 11 ++- src/back/spv/instructions.rs | 4 +- src/back/spv/mod.rs | 1 - src/back/spv/writer.rs | 2 - src/back/wgsl/mod.rs | 9 ++- src/back/wgsl/writer.rs | 49 +++---------- src/front/wgsl/mod.rs | 46 +++++------- src/lib.rs | 23 +++--- src/valid/analyzer.rs | 16 ++-- src/valid/function.rs | 42 ++++------- tests/out/spv/access.spvasm | 46 ++++++------ 17 files changed, 237 insertions(+), 329 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index aa7af75c8..e9fc13348 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -125,22 +125,15 @@ impl StatementGraph { } S::Atomic { pointer, - fun, + ref fun, + value, result, } => { self.emits.push((id, result)); self.dependencies.push((id, pointer, "pointer")); - match fun { - crate::AtomicFunction::Binary { op: _, value } - | crate::AtomicFunction::Min(value) - | crate::AtomicFunction::Max(value) - | crate::AtomicFunction::Exchange(value) => { - self.dependencies.push((id, value, "value")); - } - crate::AtomicFunction::CompareExchange { cmp, value } => { - self.dependencies.push((id, cmp, "cmp")); - self.dependencies.push((id, value, "value")); - } + self.dependencies.push((id, value, "value")); + if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun { + self.dependencies.push((id, cmp, "cmp")); } "Atomic" } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c14c64694..e47e89688 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -68,6 +68,21 @@ pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; pub type BindingMap = std::collections::BTreeMap; +impl crate::AtomicFunction { + fn to_glsl(self) -> &'static str { + match self { + Self::Add => "Add", + Self::And => "And", + Self::InclusiveOr => "Or", + Self::ExclusiveOr => "Xor", + Self::Min => "Min", + Self::Max => "Max", + Self::Exchange { compare: None } => "Exchange", + Self::Exchange { compare: Some(_) } => "", //TODO + } + } +} + /// glsl version #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -1682,7 +1697,8 @@ impl<'a, W: Write> Writer<'a, W> { } Statement::Atomic { pointer, - fun, + ref fun, + value, result, } => { write!(self.out, "{}", INDENT.repeat(indent))?; @@ -1691,44 +1707,17 @@ impl<'a, W: Write> Writer<'a, W> { self.write_value_type(res_ty)?; write!(self.out, " {} = ", res_name)?; self.named_expressions.insert(result, res_name); - match fun { - crate::AtomicFunction::Binary { op, value } => { - let fun_str = match op { - crate::BinaryOperator::Add => "Add", - crate::BinaryOperator::And => "And", - crate::BinaryOperator::InclusiveOr => "Or", - crate::BinaryOperator::ExclusiveOr => "Xor", - _ => unreachable!(), - }; - write!(self.out, "atomic{}(", fun_str)?; - self.write_expr(pointer, ctx)?; - write!(self.out, ", ")?; - self.write_expr(value, ctx)?; - } - crate::AtomicFunction::Min(value) => { - write!(self.out, "atomicMin(")?; - self.write_expr(pointer, ctx)?; - write!(self.out, ", ")?; - self.write_expr(value, ctx)?; - } - crate::AtomicFunction::Max(value) => { - write!(self.out, "atomicMax(")?; - self.write_expr(pointer, ctx)?; - write!(self.out, ", ")?; - self.write_expr(value, ctx)?; - } - crate::AtomicFunction::Exchange(value) => { - write!(self.out, "atomicExchange(")?; - self.write_expr(pointer, ctx)?; - write!(self.out, ", ")?; - self.write_expr(value, ctx)?; - } - crate::AtomicFunction::CompareExchange { .. } => { - return Err(Error::Custom( - "atomic CompareExchange is not implemented".to_string(), - )); - } + + let fun_str = fun.to_glsl(); + write!(self.out, "atomic{}(", fun_str)?; + self.write_expr(pointer, ctx)?; + if let crate::AtomicFunction::Exchange { compare: Some(_) } = *fun { + return Err(Error::Custom( + "atomic CompareExchange is not implemented".to_string(), + )); } + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; writeln!(self.out, ");")?; } } @@ -2371,6 +2360,7 @@ impl<'a, W: Write> Writer<'a, W> { } } } + // These expressions never show up in `Emit`. Expression::CallResult(_) | Expression::AtomicResult { .. } => unreachable!(), // `ArrayLength` is written as `expr.length()` and we convert it to a uint Expression::ArrayLength(expr) => { diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 958858c41..501cbbcd2 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -123,15 +123,18 @@ impl crate::Sampling { } } -impl crate::BinaryOperator { +impl crate::AtomicFunction { /// Return the HLSL suffix for the `InterlockedXxx` method. - pub(super) fn to_hlsl_atomic_suffix(self) -> &'static str { + pub(super) fn to_hlsl_suffix(self) -> &'static str { match self { Self::Add => "Add", Self::And => "And", Self::InclusiveOr => "Or", Self::ExclusiveOr => "Xor", - _ => "", + Self::Min => "Min", + Self::Max => "Max", + Self::Exchange { compare: None } => "Exchange", + Self::Exchange { .. } => "", //TODO } } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 5d651fe41..f46e4ee9a 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1108,7 +1108,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } Statement::Atomic { pointer, - fun, + ref fun, + value, result, } => { write!(self.out, "{}", INDENT.repeat(indent))?; @@ -1125,37 +1126,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let chain = mem::take(&mut self.temp_access_chain); let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; - write!(self.out, " {}; {}.Interlocked", res_name, var_name)?; - match fun { - crate::AtomicFunction::Binary { op, value } => { - let suffix = op.to_hlsl_atomic_suffix(); - write!(self.out, "{}(", suffix)?; - self.write_storage_address(module, &chain, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - } - crate::AtomicFunction::Min(value) => { - write!(self.out, "Min(")?; - self.write_storage_address(module, &chain, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - } - crate::AtomicFunction::Max(value) => { - write!(self.out, "Max(")?; - self.write_storage_address(module, &chain, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - } - crate::AtomicFunction::Exchange(value) => { - write!(self.out, "Exchange(")?; - self.write_storage_address(module, &chain, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - } - crate::AtomicFunction::CompareExchange { .. } => { - return Err(Error::Unimplemented("atomic CompareExchange".to_string())); - } + let fun_str = fun.to_hlsl_suffix(); + write!( + self.out, + " {}; {}.Interlocked{}(", + res_name, var_name, fun_str + )?; + self.write_storage_address(module, &chain, func_ctx)?; + if let crate::AtomicFunction::Exchange { compare: Some(_) } = *fun { + return Err(Error::Unimplemented("atomic CompareExchange".to_string())); } + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; writeln!(self.out, ", {});", res_name)?; self.temp_access_chain = chain; self.named_expressions.insert(result, res_name); diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 6520d6aed..fa9ec02bf 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -33,18 +33,6 @@ impl Display for Level { } } -impl crate::BinaryOperator { - fn to_msl_atomic_str(self) -> &'static str { - match self { - Self::Add => "add", - Self::And => "and", - Self::InclusiveOr => "or", - Self::ExclusiveOr => "xor", - _ => unreachable!(), - } - } -} - struct TypeContext<'a> { handle: Handle, arena: &'a crate::Arena, @@ -1629,29 +1617,34 @@ impl Writer { } crate::Statement::Atomic { pointer, - fun, + ref fun, + value, result, } => { write!(self.out, "{}", level)?; let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); self.start_baking_expression(result, &context.expression, &res_name)?; self.named_expressions.insert(result, res_name); - match fun { - crate::AtomicFunction::Binary { op, value } => { - self.put_atomic_fetch( - pointer, - op.to_msl_atomic_str(), - value, - &context.expression, - )?; + match *fun { + crate::AtomicFunction::Add => { + self.put_atomic_fetch(pointer, "add", value, &context.expression)?; } - crate::AtomicFunction::Min(value) => { + crate::AtomicFunction::And => { + self.put_atomic_fetch(pointer, "and", value, &context.expression)?; + } + crate::AtomicFunction::InclusiveOr => { + self.put_atomic_fetch(pointer, "or", value, &context.expression)?; + } + crate::AtomicFunction::ExclusiveOr => { + self.put_atomic_fetch(pointer, "xor", value, &context.expression)?; + } + crate::AtomicFunction::Min => { self.put_atomic_fetch(pointer, "min", value, &context.expression)?; } - crate::AtomicFunction::Max(value) => { + crate::AtomicFunction::Max => { self.put_atomic_fetch(pointer, "max", value, &context.expression)?; } - crate::AtomicFunction::Exchange(value) => { + crate::AtomicFunction::Exchange { compare: None } => { write!( self.out, "{}::atomic_exchange_explicit({}", @@ -1662,7 +1655,7 @@ impl Writer { self.put_expression(value, &context.expression, true)?; write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; } - crate::AtomicFunction::CompareExchange { .. } => { + crate::AtomicFunction::Exchange { .. } => { return Err(Error::FeatureNotImplemented( "atomic CompareExchange".to_string(), )); diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 370712741..0142e10ce 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -8,9 +8,6 @@ use super::{ use crate::{arena::Handle, proc::TypeResolution}; use spirv::Word; -//TODO: should this ever be `Workgroup`? -const ATOMIC_SCOPE: spirv::Scope = spirv::Scope::Device; - fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { match *type_inner { crate::TypeInner::Scalar { .. } => Dimension::Scalar, @@ -677,9 +674,8 @@ impl<'w> BlockContext<'w> { _ => None, }; let instruction = if let Some(class) = atomic_class { - let semantics = - spirv::MemorySemantics::ACQUIRE | class.to_spirv_semantics(); - let scope_constant_id = self.get_scope_constant(ATOMIC_SCOPE as u32)?; + let (semantics, scope) = class.to_spirv_semantics_and_scope(); + let scope_constant_id = self.get_scope_constant(scope as u32)?; let semantics_id = self.get_index_constant(semantics.bits())?; Instruction::atomic_load( result_type_id, @@ -719,7 +715,7 @@ impl<'w> BlockContext<'w> { } crate::Expression::FunctionArgument(index) => self.function.parameter_id(index), crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } => { - self.writer.lookup_statement_result[&expr_handle] + self.cached[expr_handle] } crate::Expression::As { expr, @@ -1619,10 +1615,8 @@ impl<'w> BlockContext<'w> { _ => None, }; let instruction = if let Some(class) = atomic_class { - let semantics = - spirv::MemorySemantics::RELEASE | class.to_spirv_semantics(); - let scope_constant_id = - self.get_scope_constant(ATOMIC_SCOPE as u32)?; + let (semantics, scope) = class.to_spirv_semantics_and_scope(); + let scope_constant_id = self.get_scope_constant(scope as u32)?; let semantics_id = self.get_index_constant(semantics.bits())?; Instruction::atomic_store( pointer_id, @@ -1698,7 +1692,6 @@ impl<'w> BlockContext<'w> { let type_id = match result { Some(expr) => { self.cached[expr] = id; - self.writer.lookup_statement_result.insert(expr, id); self.get_expression_type_id(&self.fun_info[expr].ty)? } None => self.writer.void_type, @@ -1713,14 +1706,14 @@ impl<'w> BlockContext<'w> { } crate::Statement::Atomic { pointer, - fun, + ref fun, + value, result, } => { let id = self.gen_id(); let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty)?; self.cached[result] = id; - self.writer.lookup_statement_result.insert(result, id); let pointer_id = match self.write_expression_pointer(pointer, &mut block)? { ExpressionPointer::Ready { pointer_id } => pointer_id, @@ -1735,19 +1728,59 @@ impl<'w> BlockContext<'w> { crate::TypeInner::Pointer { base: _, class } => class, _ => unimplemented!(), }; - let semantics = - spirv::MemorySemantics::ACQUIRE_RELEASE | class.to_spirv_semantics(); - let scope_constant_id = self.get_scope_constant(ATOMIC_SCOPE as u32)?; + let (semantics, scope) = class.to_spirv_semantics_and_scope(); + let scope_constant_id = self.get_scope_constant(scope as u32)?; let semantics_id = self.get_index_constant(semantics.bits())?; + let value_id = self.cached[value]; + let value_inner = self.fun_info[value].ty.inner_with(&self.ir_module.types); - let instruction = match fun { - crate::AtomicFunction::Binary { op, value } => { - let value_id = self.cached[value]; - let spirv_op = match op { - crate::BinaryOperator::Add => spirv::Op::AtomicIAdd, - crate::BinaryOperator::And => spirv::Op::AtomicAnd, - crate::BinaryOperator::InclusiveOr => spirv::Op::AtomicOr, - crate::BinaryOperator::ExclusiveOr => spirv::Op::AtomicXor, + let instruction = match *fun { + crate::AtomicFunction::Add => Instruction::atomic_binary( + spirv::Op::AtomicIAdd, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ), + crate::AtomicFunction::And => Instruction::atomic_binary( + spirv::Op::AtomicAnd, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ), + crate::AtomicFunction::InclusiveOr => Instruction::atomic_binary( + spirv::Op::AtomicOr, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ), + crate::AtomicFunction::ExclusiveOr => Instruction::atomic_binary( + spirv::Op::AtomicXor, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ), + crate::AtomicFunction::Min => { + let spirv_op = match *value_inner { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => spirv::Op::AtomicSMin, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + } => spirv::Op::AtomicUMin, _ => unimplemented!(), }; Instruction::atomic_binary( @@ -1760,20 +1793,18 @@ impl<'w> BlockContext<'w> { value_id, ) } - crate::AtomicFunction::Min(value) => { - let value_id = self.cached[value]; - let spirv_op = - match *self.fun_info[value].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Sint, - width: _, - } => spirv::Op::AtomicSMin, - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: _, - } => spirv::Op::AtomicUMin, - _ => unimplemented!(), - }; + crate::AtomicFunction::Max => { + let spirv_op = match *value_inner { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: _, + } => spirv::Op::AtomicSMax, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + } => spirv::Op::AtomicUMax, + _ => unimplemented!(), + }; Instruction::atomic_binary( spirv_op, result_type_id, @@ -1784,32 +1815,7 @@ impl<'w> BlockContext<'w> { value_id, ) } - crate::AtomicFunction::Max(value) => { - let value_id = self.cached[value]; - let spirv_op = - match *self.fun_info[value].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Sint, - width: _, - } => spirv::Op::AtomicSMax, - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - width: _, - } => spirv::Op::AtomicUMax, - _ => unimplemented!(), - }; - Instruction::atomic_binary( - spirv_op, - result_type_id, - id, - pointer_id, - scope_constant_id, - semantics_id, - value_id, - ) - } - crate::AtomicFunction::Exchange(value) => { - let value_id = self.cached[value]; + crate::AtomicFunction::Exchange { compare: None } => { Instruction::atomic_binary( spirv::Op::AtomicExchange, result_type_id, @@ -1820,7 +1826,7 @@ impl<'w> BlockContext<'w> { value_id, ) } - crate::AtomicFunction::CompareExchange { .. } => { + crate::AtomicFunction::Exchange { compare: Some(_) } => { return Err(Error::FeatureNotImplemented("atomic CompareExchange")); } }; diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index 9db704126..fe8fbaf75 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -50,11 +50,14 @@ pub(super) fn contains_builtin( } impl crate::StorageClass { - pub(super) fn to_spirv_semantics(self) -> spirv::MemorySemantics { + pub(super) fn to_spirv_semantics_and_scope(self) -> (spirv::MemorySemantics, spirv::Scope) { match self { - Self::Storage { .. } => spirv::MemorySemantics::UNIFORM_MEMORY, - Self::WorkGroup => spirv::MemorySemantics::WORKGROUP_MEMORY, - _ => spirv::MemorySemantics::empty(), + Self::Storage { .. } => (spirv::MemorySemantics::UNIFORM_MEMORY, spirv::Scope::Device), + Self::WorkGroup => ( + spirv::MemorySemantics::WORKGROUP_MEMORY, + spirv::Scope::Workgroup, + ), + _ => (spirv::MemorySemantics::empty(), spirv::Scope::Invocation), } } } diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index dd3947175..6530160e5 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -771,7 +771,7 @@ impl super::Instruction { pointer: Word, scope_id: Word, semantics_id: Word, - operand: Word, + value: Word, ) -> Self { let mut instruction = Self::new(op); instruction.set_type(result_type_id); @@ -779,7 +779,7 @@ impl super::Instruction { instruction.add_operand(pointer); instruction.add_operand(scope_id); instruction.add_operand(semantics_id); - instruction.add_operand(operand); + instruction.add_operand(value); instruction } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 39b015728..55c1d6ba4 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -396,7 +396,6 @@ pub struct Writer { lookup_type: crate::FastHashMap, lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, - lookup_statement_result: crate::FastHashMap, Word>, constant_ids: Vec, cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>, global_variables: Vec, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index fec4d5c33..31a2f9892 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -78,7 +78,6 @@ impl Writer { lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), lookup_function_type: crate::FastHashMap::default(), - lookup_statement_result: crate::FastHashMap::default(), constant_ids: Vec::new(), cached_constants: crate::FastHashMap::default(), global_variables: Vec::new(), @@ -127,7 +126,6 @@ impl Writer { lookup_type: take(&mut self.lookup_type).recycle(), lookup_function: take(&mut self.lookup_function).recycle(), lookup_function_type: take(&mut self.lookup_function_type).recycle(), - lookup_statement_result: take(&mut self.lookup_statement_result).recycle(), constant_ids: take(&mut self.constant_ids).recycle(), cached_constants: take(&mut self.cached_constants).recycle(), global_variables: take(&mut self.global_variables).recycle(), diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index e8fb1e493..33d01e245 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -27,14 +27,17 @@ pub fn write_string( Ok(output) } -impl crate::BinaryOperator { - fn to_wgsl_atomic_suffix(self) -> &'static str { +impl crate::AtomicFunction { + fn to_wgsl(self) -> &'static str { match self { Self::Add => "Add", Self::And => "And", Self::InclusiveOr => "Or", Self::ExclusiveOr => "Xor", - _ => unreachable!(), + Self::Min => "Min", + Self::Max => "Max", + Self::Exchange { compare: None } => "Exchange", + Self::Exchange { .. } => "CompareExchangeWeak", } } } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 68d1563b6..9748c4284 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -703,7 +703,8 @@ impl Writer { } Statement::Atomic { pointer, - fun, + ref fun, + value, result, } => { write!(self.out, "{}", INDENT.repeat(indent))?; @@ -712,45 +713,15 @@ impl Writer { self.write_expr(module, result, func_ctx)?; self.named_expressions.insert(result, res_name); - match fun { - crate::AtomicFunction::Binary { op, value } => { - write!( - self.out, - "atomic{}({}", - op.to_wgsl_atomic_suffix(), - ATOMIC_REFERENCE - )?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - } - crate::AtomicFunction::Min(value) => { - write!(self.out, "atomicMin({}", ATOMIC_REFERENCE)?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - } - crate::AtomicFunction::Max(value) => { - write!(self.out, "atomicMax({}", ATOMIC_REFERENCE)?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - } - crate::AtomicFunction::Exchange(value) => { - write!(self.out, "atomicExchange({}", ATOMIC_REFERENCE)?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - } - crate::AtomicFunction::CompareExchange { cmp, value } => { - write!(self.out, "atomicCompareExchangeWeak({}", ATOMIC_REFERENCE)?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, cmp, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - } + let fun_str = fun.to_wgsl(); + write!(self.out, "atomic{}({}", fun_str, ATOMIC_REFERENCE)?; + self.write_expr(module, pointer, func_ctx)?; + if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun { + write!(self.out, ", ")?; + self.write_expr(module, cmp, func_ctx)?; } + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; writeln!(self.out, ");")? } Statement::ImageStore { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5dcdb9587..96a3d88b9 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1101,10 +1101,10 @@ impl Parser { Ok(Some((fun_handle, arguments))) } - fn parse_atomic_helper<'a, F: FnOnce(Handle) -> crate::AtomicFunction>( + fn parse_atomic_helper<'a>( &mut self, lexer: &mut Lexer<'a>, - function_factory: F, + fun: crate::AtomicFunction, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { lexer.open_arguments()?; @@ -1127,25 +1127,13 @@ impl Parser { let result = ctx.interrupt_emitter(expression); ctx.block.push(crate::Statement::Atomic { pointer, - fun: function_factory(value), + fun, + value, result, }); Ok(result) } - fn parse_atomic_binary_op<'a>( - &mut self, - lexer: &mut Lexer<'a>, - op: crate::BinaryOperator, - ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - self.parse_atomic_helper( - lexer, - |value| crate::AtomicFunction::Binary { op, value }, - ctx, - ) - } - fn parse_function_call_inner<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -1215,33 +1203,33 @@ impl Parser { crate::Expression::Load { pointer } } "atomicAdd" => { - let handle = self.parse_atomic_binary_op( + let handle = self.parse_atomic_helper( lexer, - crate::BinaryOperator::Add, + crate::AtomicFunction::Add, ctx.reborrow(), )?; return Ok(Some(handle)); } "atomicAnd" => { - let handle = self.parse_atomic_binary_op( + let handle = self.parse_atomic_helper( lexer, - crate::BinaryOperator::And, + crate::AtomicFunction::And, ctx.reborrow(), )?; return Ok(Some(handle)); } "atomicOr" => { - let handle = self.parse_atomic_binary_op( + let handle = self.parse_atomic_helper( lexer, - crate::BinaryOperator::InclusiveOr, + crate::AtomicFunction::InclusiveOr, ctx.reborrow(), )?; return Ok(Some(handle)); } "atomicXor" => { - let handle = self.parse_atomic_binary_op( + let handle = self.parse_atomic_helper( lexer, - crate::BinaryOperator::ExclusiveOr, + crate::AtomicFunction::ExclusiveOr, ctx.reborrow(), )?; return Ok(Some(handle)); @@ -1257,8 +1245,11 @@ impl Parser { return Ok(Some(handle)); } "atomicExchange" => { - let handle = - self.parse_atomic_helper(lexer, crate::AtomicFunction::Exchange, ctx)?; + let handle = self.parse_atomic_helper( + lexer, + crate::AtomicFunction::Exchange { compare: None }, + ctx, + )?; return Ok(Some(handle)); } "atomicCompareExchangeWeak" => { @@ -1286,7 +1277,8 @@ impl Parser { let result = ctx.interrupt_emitter(expression); ctx.block.push(crate::Statement::Atomic { pointer, - fun: crate::AtomicFunction::CompareExchange { cmp, value }, + fun: crate::AtomicFunction::Exchange { compare: Some(cmp) }, + value, result, }); return Ok(Some(result)); diff --git a/src/lib.rs b/src/lib.rs index 12a5a0283..bc934cdde 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -745,20 +745,13 @@ pub enum BinaryOperator { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum AtomicFunction { - /// Binary operation of an atomic with a value. - /// - /// Note: only supports a subset of operations, defined by the validator. - Binary { - op: BinaryOperator, - value: Handle, - }, - Min(Handle), - Max(Handle), - Exchange(Handle), - CompareExchange { - cmp: Handle, - value: Handle, - }, + Add, + And, + ExclusiveOr, + InclusiveOr, + Min, + Max, + Exchange { compare: Option> }, } /// Axis on which to compute a derivative. @@ -1320,6 +1313,8 @@ pub enum Statement { pointer: Handle, /// Function to run on the atomic. fun: AtomicFunction, + /// Value to use in the function. + value: Handle, /// Emitted expression as a result. result: Handle, }, diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 04f766c04..543e25034 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -780,19 +780,15 @@ impl FunctionInfo { } S::Atomic { pointer, - fun, + ref fun, + value, result: _, } => { let _ = self.add_ref_impl(pointer, GlobalUse::WRITE); - let _ = match fun { - crate::AtomicFunction::Binary { op: _, value } - | crate::AtomicFunction::Min(value) - | crate::AtomicFunction::Max(value) - | crate::AtomicFunction::Exchange(value) => self.add_ref(value), - crate::AtomicFunction::CompareExchange { cmp, value } => { - self.add_ref(value).or(self.add_ref(cmp)) - } - }; + let _ = self.add_ref(value); + if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun { + let _ = self.add_ref(cmp); + } FunctionUniformity::new() } }; diff --git a/src/valid/function.rs b/src/valid/function.rs index 612e979c6..7238c2977 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -271,12 +271,11 @@ impl super::Validator { fn validate_atomic( &mut self, pointer: Handle, - fun: crate::AtomicFunction, + fun: &crate::AtomicFunction, + value: Handle, result: Handle, context: &BlockContext, ) -> Result<(), FunctionError> { - use crate::BinaryOperator as Bo; - let pointer_inner = context.resolve_type(pointer, &self.valid_expression_set)?; let (ptr_kind, ptr_width) = match *pointer_inner { crate::TypeInner::Pointer { base, .. } => match context.types[base].inner { @@ -292,29 +291,8 @@ impl super::Validator { } }; - let value = match fun { - crate::AtomicFunction::Binary { op, value } => { - match op { - Bo::Add | Bo::And | Bo::InclusiveOr | Bo::ExclusiveOr => {} - _ => return Err(AtomicError::InvalidBinaryOp(op, ptr_kind).into()), - } - value - } - crate::AtomicFunction::Min(value) - | crate::AtomicFunction::Max(value) - | crate::AtomicFunction::Exchange(value) => value, - crate::AtomicFunction::CompareExchange { cmp, value } => { - if context.resolve_type(cmp, &self.valid_expression_set)? - != context.resolve_type(value, &self.valid_expression_set)? - { - log::error!("Atomic exchange comparison has a different type from the value"); - return Err(AtomicError::InvalidOperand(cmp).into()); - } - value - } - }; - - match *context.resolve_type(value, &self.valid_expression_set)? { + let value_inner = context.resolve_type(value, &self.valid_expression_set)?; + match *value_inner { crate::TypeInner::Scalar { width, kind } if kind == ptr_kind && width == ptr_width => {} ref other => { log::error!("Atomic operand type {:?}", other); @@ -322,6 +300,13 @@ impl super::Validator { } } + if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun { + if context.resolve_type(cmp, &self.valid_expression_set)? != value_inner { + log::error!("Atomic exchange comparison has a different type from the value"); + return Err(AtomicError::InvalidOperand(cmp).into()); + } + } + if self.valid_expression_set.insert(result.index()) { self.valid_expression_list.push(result); } else { @@ -602,10 +587,11 @@ impl super::Validator { }, S::Atomic { pointer, - fun, + ref fun, + value, result, } => { - self.validate_atomic(pointer, fun, result, context)?; + self.validate_atomic(pointer, fun, value, result, context)?; } } } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 33920bc06..df869e495 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 107 +; Bound: 105 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" @@ -79,9 +79,7 @@ OpDecorate %37 BuiltIn Position %74 = OpTypePointer Function %4 %78 = OpTypeVector %4 4 %86 = OpTypePointer StorageBuffer %4 -%89 = OpConstant %9 66 -%92 = OpConstant %9 72 -%106 = OpConstant %9 68 +%89 = OpConstant %9 64 %39 = OpFunction %2 None %40 %33 = OpLabel %29 = OpVariable %30 Function %5 @@ -138,27 +136,27 @@ OpBranch %85 %87 = OpAccessChain %86 %27 %15 %88 = OpAtomicLoad %4 %87 %11 %89 %91 = OpAccessChain %86 %27 %15 -%90 = OpAtomicIAdd %4 %91 %11 %92 %16 +%90 = OpAtomicIAdd %4 %91 %11 %89 %16 OpStore %82 %90 -%94 = OpAccessChain %86 %27 %15 -%93 = OpAtomicAnd %4 %94 %11 %92 %16 -OpStore %82 %93 -%96 = OpAccessChain %86 %27 %15 -%95 = OpAtomicOr %4 %96 %11 %92 %16 -OpStore %82 %95 -%98 = OpAccessChain %86 %27 %15 -%97 = OpAtomicXor %4 %98 %11 %92 %16 -OpStore %82 %97 -%100 = OpAccessChain %86 %27 %15 -%99 = OpAtomicSMin %4 %100 %11 %92 %16 -OpStore %82 %99 -%102 = OpAccessChain %86 %27 %15 -%101 = OpAtomicSMax %4 %102 %11 %92 %16 -OpStore %82 %101 +%93 = OpAccessChain %86 %27 %15 +%92 = OpAtomicAnd %4 %93 %11 %89 %16 +OpStore %82 %92 +%95 = OpAccessChain %86 %27 %15 +%94 = OpAtomicOr %4 %95 %11 %89 %16 +OpStore %82 %94 +%97 = OpAccessChain %86 %27 %15 +%96 = OpAtomicXor %4 %97 %11 %89 %16 +OpStore %82 %96 +%99 = OpAccessChain %86 %27 %15 +%98 = OpAtomicSMin %4 %99 %11 %89 %16 +OpStore %82 %98 +%101 = OpAccessChain %86 %27 %15 +%100 = OpAtomicSMax %4 %101 %11 %89 %16 +OpStore %82 %100 +%103 = OpAccessChain %86 %27 %15 +%102 = OpAtomicExchange %4 %103 %11 %89 %16 +OpStore %82 %102 %104 = OpAccessChain %86 %27 %15 -%103 = OpAtomicExchange %4 %104 %11 %92 %16 -OpStore %82 %103 -%105 = OpAccessChain %86 %27 %15 -OpAtomicStore %105 %11 %106 %88 +OpAtomicStore %104 %11 %89 %88 OpReturn OpFunctionEnd \ No newline at end of file From 67dd604b0c44fe5c436182a3b8325173d8c001b1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 10 Aug 2021 15:30:41 -0400 Subject: [PATCH 1213/2212] [wgsl-out] atomic load/stores, [glsl-out] revert the prefix --- src/back/glsl/mod.rs | 9 +- src/back/wgsl/writer.rs | 41 ++++- src/front/wgsl/mod.rs | 39 ++++- src/lib.rs | 7 + src/proc/typifier.rs | 11 +- src/valid/function.rs | 2 - src/valid/type.rs | 15 +- tests/out/glsl/access.atomics.Compute.glsl | 28 +-- tests/out/glsl/access.foo.Vertex.glsl | 4 +- tests/out/glsl/boids.main.Compute.glsl | 160 +++++++++--------- tests/out/glsl/interpolate.main.Vertex.glsl | 18 +- tests/out/glsl/operators.main.Compute.glsl | 6 +- tests/out/glsl/quad-vert.main.Vertex.glsl | 20 +-- tests/out/glsl/shadow.fs_main.Fragment.glsl | 30 ++-- tests/out/glsl/skybox.fs_main.Fragment.glsl | 4 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 18 +- tests/out/glsl/texture-arg.main.Fragment.glsl | 8 +- tests/out/wgsl/access.wgsl | 4 +- tests/wgsl-errors.rs | 8 - 19 files changed, 252 insertions(+), 180 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index e47e89688..c87095d2d 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -66,6 +66,9 @@ pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450] /// List of supported es glsl versions pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; +//TODO: use `super::BAKE_PREFIX` instead +const BAKE_PREFIX: &str = "_expr"; + pub type BindingMap = std::collections::BTreeMap; impl crate::AtomicFunction { @@ -1342,7 +1345,7 @@ impl<'a, W: Write> Writer<'a, W> { } else { let min_ref_count = ctx.expressions[handle].bake_ref_count(); if min_ref_count <= ctx.info[handle].ref_count { - Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) + Some(format!("{}{}", BAKE_PREFIX, handle.index())) } else { None } @@ -1674,7 +1677,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { - let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); + let name = format!("{}{}", BAKE_PREFIX, expr.index()); let result = self.module.functions[function].result.as_ref().unwrap(); self.write_type(result.ty)?; write!(self.out, " {} = ", name)?; @@ -1702,7 +1705,7 @@ impl<'a, W: Write> Writer<'a, W> { result, } => { write!(self.out, "{}", INDENT.repeat(indent))?; - let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); + let res_name = format!("{}{}", BAKE_PREFIX, result.index()); let res_ty = ctx.info[result].ty.inner_with(&self.module.types); self.write_value_type(res_ty)?; write!(self.out, " {} = ", res_name)?; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 9748c4284..46958be80 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -672,9 +672,25 @@ impl Writer { } } write!(self.out, "{}", INDENT.repeat(indent))?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, " = ")?; - self.write_expr(module, value, func_ctx)?; + + let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { + crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { + crate::TypeInner::Atomic { .. } => true, + _ => false, + }, + _ => false, + }; + if is_atomic { + write!(self.out, "atomicStore({}", ATOMIC_REFERENCE)?; + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + write!(self.out, ")")?; + } else { + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, " = ")?; + self.write_expr(module, value, func_ctx)?; + } writeln!(self.out, ";")? } Statement::Call { @@ -686,7 +702,6 @@ impl Writer { if let Some(expr) = result { let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); self.start_named_expr(module, expr, func_ctx, &name)?; - self.write_expr(module, expr, func_ctx)?; self.named_expressions.insert(expr, name); } let func_name = &self.names[&NameKey::Function(function)]; @@ -710,7 +725,6 @@ impl Writer { write!(self.out, "{}", INDENT.repeat(indent))?; let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); self.start_named_expr(module, result, func_ctx, &res_name)?; - self.write_expr(module, result, func_ctx)?; self.named_expressions.insert(result, res_name); let fun_str = fun.to_wgsl(); @@ -1154,7 +1168,22 @@ impl Writer { self.write_expr(module, value, func_ctx)?; write!(self.out, ")")?; } - Expression::Load { pointer } => self.write_expr(module, pointer, func_ctx)?, + Expression::Load { pointer } => { + let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { + crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { + crate::TypeInner::Atomic { .. } => true, + _ => false, + }, + _ => false, + }; + if is_atomic { + write!(self.out, "atomicLoad({}", ATOMIC_REFERENCE)?; + } + self.write_expr(module, pointer, func_ctx)?; + if is_atomic { + write!(self.out, ")")?; + } + } Expression::LocalVariable(handle) => { write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])? } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 96a3d88b9..4990db0d0 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -126,6 +126,7 @@ pub enum Error<'a> { UnknownLocalFunction(Span), InitializationTypeMismatch(Span, Handle), MissingType(Span), + InvalidAtomicPointer(Span), InvalidAtomicOperandType(Span), Other, } @@ -338,6 +339,11 @@ impl<'a> Error<'a> { labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], notes: vec![], }, + Error::InvalidAtomicPointer(ref span) => ParseError { + message: "atomic operation is done on a pointer to a non-atomic".to_string(), + labels: vec![(span.clone(), "atomic pointer is invalid".into())], + notes: vec![], + }, Error::InvalidAtomicOperandType(ref span) => ParseError { message: "atomic operand type is inconsistent with the operation".to_string(), labels: vec![(span.clone(), "atomic operand type is invalid".into())], @@ -786,6 +792,10 @@ impl<'a> ExpressionContext<'a, '_, '_> { Ok(left) } + /// Add a single expression to the expression table that is not covered by `self.emitter`. + /// + /// This is useful for `CallResult` and `AtomicResult` expressions, which should not be covered by + /// `Emit` statements. fn interrupt_emitter(&mut self, expression: crate::Expression) -> Handle { self.block.extend(self.emitter.finish(self.expressions)); let result = self.expressions.append(expression); @@ -1073,6 +1083,31 @@ impl Parser { }) } + fn parse_atomic_pointer<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + let (pointer, pointer_span) = + lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx.reborrow()))?; + // Check if the pointer expression is to an atomic. + // The IR uses regular `Expression::Load` and `Statement::Store` for atomic load/stores, + // and it will not catch the use of a non-atomic variable here. + match *ctx.resolve_type(pointer)? { + crate::TypeInner::Pointer { base, .. } => match ctx.types[base].inner { + crate::TypeInner::Atomic { .. } => Ok(pointer), + ref other => { + log::error!("Pointer type to {:?} passed to atomic op", other); + Err(Error::InvalidAtomicPointer(pointer_span)) + } + }, + ref other => { + log::error!("Type {:?} passed to atomic op", other); + Err(Error::InvalidAtomicPointer(pointer_span)) + } + } + } + fn parse_local_function_call<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -1198,7 +1233,7 @@ impl Parser { // atomics "atomicLoad" => { lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + let pointer = self.parse_atomic_pointer(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::Load { pointer } } @@ -3065,7 +3100,7 @@ impl Parser { "atomicStore" => { lexer.open_arguments()?; let mut expression_ctx = context.as_expression(block, &mut emitter); - let pointer = self.parse_general_expression(lexer, expression_ctx.reborrow())?; + let pointer = self.parse_atomic_pointer(lexer, expression_ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let value = self.parse_general_expression(lexer, expression_ctx)?; lexer.close_arguments()?; diff --git a/src/lib.rs b/src/lib.rs index bc934cdde..bd5a7c1d0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1023,6 +1023,9 @@ pub enum Expression { LocalVariable(Handle), /// Load a value indirectly. + /// + /// For [`TypeInner::Atomic`] the result is a corresponding scalar. + /// For other types behind the pointer, the result is T. Load { pointer: Handle }, /// Sample a point from a sampled or a depth image. ImageSample { @@ -1282,6 +1285,10 @@ pub enum Statement { Barrier(Barrier), /// Stores a value at an address. /// + /// For [`TypeInner::Atomic`] type behind the pointer, the value + /// has to be a corresponding scalar. + /// For other types behind the pointer, the value is T. + /// /// This statement is a barrier for any operations on the /// `Expression::LocalVariable` or `Expression::GlobalVariable` /// that is the destination of an access chain, started diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 3529df804..afd4d73bf 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -350,10 +350,13 @@ impl<'a> ResolveContext<'a> { }) } crate::Expression::Load { pointer } => match *past(pointer).inner_with(types) { - Ti::Pointer { base, class: _ } => match types[base].inner { - Ti::Atomic { kind, width } => TypeResolution::Value(Ti::Scalar { kind, width }), - _ => TypeResolution::Handle(base), - }, + Ti::Pointer { base, class: _ } => { + if let Ti::Atomic { kind, width } = types[base].inner { + TypeResolution::Value(Ti::Scalar { kind, width }) + } else { + TypeResolution::Handle(base) + } + } Ti::ValuePointer { size, kind, diff --git a/src/valid/function.rs b/src/valid/function.rs index 7238c2977..703c1474f 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -41,8 +41,6 @@ pub enum AtomicError { InvalidPointer(Handle), #[error("Operand {0:?} has invalid type.")] InvalidOperand(Handle), - #[error("Binary op {0:?} doesn't work on {1:?}.")] - InvalidBinaryOp(crate::BinaryOperator, crate::ScalarKind), #[error("Result expression {0:?} has already been introduced earlier")] ResultAlreadyInScope(Handle), #[error("Result type for {0:?} doesn't match the statement")] diff --git a/src/valid/type.rs b/src/valid/type.rs index faf1e517d..ef1cc7e72 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -69,6 +69,8 @@ pub enum Disalignment { }, #[error("The struct member[{index}] is not statically sized")] UnsizedMember { index: u32 }, + #[error("The type is not host-shareable")] + NonHostShareable, } #[derive(Clone, Debug, thiserror::Error)] @@ -83,8 +85,6 @@ pub enum TypeError { InvalidPointerBase(Handle), #[error("Expected data type, found {0:?}")] InvalidData(Handle), - #[error("Structure type {0:?} can not be a block structure")] - InvalidBlockType(Handle), #[error("Base type {0:?} for the array is invalid")] InvalidArrayBaseType(Handle), #[error("The constant {0:?} can not be used for an array size")] @@ -421,12 +421,17 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); } - if top_level && !base_info.flags.contains(TypeFlags::HOST_SHARED) { - return Err(TypeError::InvalidBlockType(member.ty)); - } if base_info.flags.contains(TypeFlags::TOP_LEVEL) { return Err(TypeError::NestedTopLevel); } + if !base_info.flags.contains(TypeFlags::HOST_SHARED) { + if ti.uniform_layout.is_ok() { + ti.uniform_layout = Err((member.ty, Disalignment::NonHostShareable)); + } + if ti.storage_layout.is_ok() { + ti.storage_layout = Err((member.ty, Disalignment::NonHostShareable)); + } + } ti.flags &= base_info.flags; if member.offset < min_offset { diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index f0a982862..b4254c36d 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -16,20 +16,20 @@ buffer Bar_block_0Cs { void main() { int tmp = 0; int value = _group_0_binding_0.atom; - int _e6 = atomicAdd(_group_0_binding_0.atom, 5); - tmp = _e6; - int _e9 = atomicAnd(_group_0_binding_0.atom, 5); - tmp = _e9; - int _e12 = atomicOr(_group_0_binding_0.atom, 5); - tmp = _e12; - int _e15 = atomicXor(_group_0_binding_0.atom, 5); - tmp = _e15; - int _e18 = atomicMin(_group_0_binding_0.atom, 5); - tmp = _e18; - int _e21 = atomicMax(_group_0_binding_0.atom, 5); - tmp = _e21; - int _e24 = atomicExchange(_group_0_binding_0.atom, 5); - tmp = _e24; + int _expr6 = atomicAdd(_group_0_binding_0.atom, 5); + tmp = _expr6; + int _expr9 = atomicAnd(_group_0_binding_0.atom, 5); + tmp = _expr9; + int _expr12 = atomicOr(_group_0_binding_0.atom, 5); + tmp = _expr12; + int _expr15 = atomicXor(_group_0_binding_0.atom, 5); + tmp = _expr15; + int _expr18 = atomicMin(_group_0_binding_0.atom, 5); + tmp = _expr18; + int _expr21 = atomicMax(_group_0_binding_0.atom, 5); + tmp = _expr21; + int _expr24 = atomicExchange(_group_0_binding_0.atom, 5); + tmp = _expr24; _group_0_binding_0.atom = value; return; } diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index c128dff78..6bd543677 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -19,8 +19,8 @@ void main() { foo1 = 1.0; mat4x4 matrix = _group_0_binding_0.matrix; uvec2 arr[2] = _group_0_binding_0.arr; - vec4 _e13 = _group_0_binding_0.matrix[3]; - float b = _e13.x; + vec4 _expr13 = _group_0_binding_0.matrix[3]; + float b = _expr13.x; int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)]; _group_0_binding_0.matrix[1][2] = 1.0; _group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 7a925d554..add4e0f9d 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -45,112 +45,112 @@ void main() { if ((index >= 1500u)) { return; } - vec2 _e10 = _group_0_binding_1.particles[index].pos; - vPos = _e10; - vec2 _e15 = _group_0_binding_1.particles[index].vel; - vVel = _e15; + vec2 _expr10 = _group_0_binding_1.particles[index].pos; + vPos = _expr10; + vec2 _expr15 = _group_0_binding_1.particles[index].vel; + vVel = _expr15; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); bool loop_init = true; while(true) { if (!loop_init) { - uint _e86 = i; - i = (_e86 + 1u); + uint _expr86 = i; + i = (_expr86 + 1u); } loop_init = false; - uint _e37 = i; - if ((_e37 >= 1500u)) { + uint _expr37 = i; + if ((_expr37 >= 1500u)) { break; } - uint _e39 = i; - if ((_e39 == index)) { + uint _expr39 = i; + if ((_expr39 == index)) { continue; } - uint _e42 = i; - vec2 _e45 = _group_0_binding_1.particles[_e42].pos; - pos = _e45; - uint _e47 = i; - vec2 _e50 = _group_0_binding_1.particles[_e47].vel; - vel = _e50; - vec2 _e51 = pos; - vec2 _e52 = vPos; - float _e55 = _group_0_binding_0.rule1Distance; - if ((distance(_e51, _e52) < _e55)) { - vec2 _e57 = cMass; - vec2 _e58 = pos; - cMass = (_e57 + _e58); - int _e60 = cMassCount; - cMassCount = (_e60 + 1); + uint _expr42 = i; + vec2 _expr45 = _group_0_binding_1.particles[_expr42].pos; + pos = _expr45; + uint _expr47 = i; + vec2 _expr50 = _group_0_binding_1.particles[_expr47].vel; + vel = _expr50; + vec2 _expr51 = pos; + vec2 _expr52 = vPos; + float _expr55 = _group_0_binding_0.rule1Distance; + if ((distance(_expr51, _expr52) < _expr55)) { + vec2 _expr57 = cMass; + vec2 _expr58 = pos; + cMass = (_expr57 + _expr58); + int _expr60 = cMassCount; + cMassCount = (_expr60 + 1); } - vec2 _e63 = pos; - vec2 _e64 = vPos; - float _e67 = _group_0_binding_0.rule2Distance; - if ((distance(_e63, _e64) < _e67)) { - vec2 _e69 = colVel; - vec2 _e70 = pos; - vec2 _e71 = vPos; - colVel = (_e69 - (_e70 - _e71)); + vec2 _expr63 = pos; + vec2 _expr64 = vPos; + float _expr67 = _group_0_binding_0.rule2Distance; + if ((distance(_expr63, _expr64) < _expr67)) { + vec2 _expr69 = colVel; + vec2 _expr70 = pos; + vec2 _expr71 = vPos; + colVel = (_expr69 - (_expr70 - _expr71)); } - vec2 _e74 = pos; - vec2 _e75 = vPos; - float _e78 = _group_0_binding_0.rule3Distance; - if ((distance(_e74, _e75) < _e78)) { - vec2 _e80 = cVel; - vec2 _e81 = vel; - cVel = (_e80 + _e81); - int _e83 = cVelCount; - cVelCount = (_e83 + 1); + vec2 _expr74 = pos; + vec2 _expr75 = vPos; + float _expr78 = _group_0_binding_0.rule3Distance; + if ((distance(_expr74, _expr75) < _expr78)) { + vec2 _expr80 = cVel; + vec2 _expr81 = vel; + cVel = (_expr80 + _expr81); + int _expr83 = cVelCount; + cVelCount = (_expr83 + 1); } } - int _e89 = cMassCount; - if ((_e89 > 0)) { - vec2 _e92 = cMass; - int _e93 = cMassCount; - vec2 _e97 = vPos; - cMass = ((_e92 / vec2(float(_e93))) - _e97); + int _expr89 = cMassCount; + if ((_expr89 > 0)) { + vec2 _expr92 = cMass; + int _expr93 = cMassCount; + vec2 _expr97 = vPos; + cMass = ((_expr92 / vec2(float(_expr93))) - _expr97); } - int _e99 = cVelCount; - if ((_e99 > 0)) { - vec2 _e102 = cVel; - int _e103 = cVelCount; - cVel = (_e102 / vec2(float(_e103))); + int _expr99 = cVelCount; + if ((_expr99 > 0)) { + vec2 _expr102 = cVel; + int _expr103 = cVelCount; + cVel = (_expr102 / vec2(float(_expr103))); } - vec2 _e107 = vVel; - vec2 _e108 = cMass; - float _e110 = _group_0_binding_0.rule1Scale; - vec2 _e113 = colVel; - float _e115 = _group_0_binding_0.rule2Scale; - vec2 _e118 = cVel; - float _e120 = _group_0_binding_0.rule3Scale; - vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); - vec2 _e123 = vVel; - vec2 _e125 = vVel; - vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.1)); - vec2 _e131 = vPos; - vec2 _e132 = vVel; - float _e134 = _group_0_binding_0.deltaT; - vPos = (_e131 + (_e132 * _e134)); - vec2 _e137 = vPos; - if ((_e137.x < -1.0)) { + vec2 _expr107 = vVel; + vec2 _expr108 = cMass; + float _expr110 = _group_0_binding_0.rule1Scale; + vec2 _expr113 = colVel; + float _expr115 = _group_0_binding_0.rule2Scale; + vec2 _expr118 = cVel; + float _expr120 = _group_0_binding_0.rule3Scale; + vVel = (((_expr107 + (_expr108 * _expr110)) + (_expr113 * _expr115)) + (_expr118 * _expr120)); + vec2 _expr123 = vVel; + vec2 _expr125 = vVel; + vVel = (normalize(_expr123) * clamp(length(_expr125), 0.0, 0.1)); + vec2 _expr131 = vPos; + vec2 _expr132 = vVel; + float _expr134 = _group_0_binding_0.deltaT; + vPos = (_expr131 + (_expr132 * _expr134)); + vec2 _expr137 = vPos; + if ((_expr137.x < -1.0)) { vPos.x = 1.0; } - vec2 _e143 = vPos; - if ((_e143.x > 1.0)) { + vec2 _expr143 = vPos; + if ((_expr143.x > 1.0)) { vPos.x = -1.0; } - vec2 _e149 = vPos; - if ((_e149.y < -1.0)) { + vec2 _expr149 = vPos; + if ((_expr149.y < -1.0)) { vPos.y = 1.0; } - vec2 _e155 = vPos; - if ((_e155.y > 1.0)) { + vec2 _expr155 = vPos; + if ((_expr155.y > 1.0)) { vPos.y = -1.0; } - vec2 _e164 = vPos; - _group_0_binding_2.particles[index].pos = _e164; - vec2 _e168 = vVel; - _group_0_binding_2.particles[index].vel = _e168; + vec2 _expr164 = vPos; + _group_0_binding_2.particles[index].pos = _expr164; + vec2 _expr168 = vVel; + _group_0_binding_2.particles[index].vel = _expr168; return; } diff --git a/tests/out/glsl/interpolate.main.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl index 76cdd0ac0..5aefc78ed 100644 --- a/tests/out/glsl/interpolate.main.Vertex.glsl +++ b/tests/out/glsl/interpolate.main.Vertex.glsl @@ -28,15 +28,15 @@ void main() { out1.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); out1.perspective_centroid = 2197.0; out1.perspective_sample = 2744.0; - FragmentInput _e30 = out1; - gl_Position = _e30.position; - _vs2fs_location0 = _e30.flat1; - _vs2fs_location1 = _e30.linear; - _vs2fs_location2 = _e30.linear_centroid; - _vs2fs_location3 = _e30.linear_sample; - _vs2fs_location4 = _e30.perspective; - _vs2fs_location5 = _e30.perspective_centroid; - _vs2fs_location6 = _e30.perspective_sample; + FragmentInput _expr30 = out1; + gl_Position = _expr30.position; + _vs2fs_location0 = _expr30.flat1; + _vs2fs_location1 = _expr30.linear; + _vs2fs_location2 = _expr30.linear_centroid; + _vs2fs_location3 = _expr30.linear_sample; + _vs2fs_location4 = _expr30.perspective; + _vs2fs_location5 = _expr30.perspective_centroid; + _vs2fs_location6 = _expr30.perspective_sample; return; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index a146d42bb..332e991c8 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -30,9 +30,9 @@ int unary() { } void main() { - vec4 _e3 = builtins(); - vec4 _e4 = splat(); - int _e5 = unary(); + vec4 _expr3 = builtins(); + vec4 _expr4 = splat(); + int _expr5 = unary(); return; } diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index e42681b2e..60f74cd94 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -29,10 +29,10 @@ layout(location = 0) in vec2 _p2vs_location0; layout(location = 0) smooth out vec2 _vs2fs_location0; void main2() { - vec2 _e12 = a_uv1; - v_uv = _e12; - vec2 _e13 = a_pos1; - perVertexStruct.gen_gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); + vec2 _expr12 = a_uv1; + v_uv = _expr12; + vec2 _expr13 = a_pos1; + perVertexStruct.gen_gl_Position = vec4(_expr13.x, _expr13.y, 0.0, 1.0); return; } @@ -42,12 +42,12 @@ void main() { a_uv1 = a_uv; a_pos1 = a_pos; main2(); - vec2 _e10 = v_uv; - vec4 _e11 = perVertexStruct.gen_gl_Position; - float _e12 = perVertexStruct.gen_gl_PointSize; - float _e13[1] = perVertexStruct.gen_gl_ClipDistance; - float _e14[1] = perVertexStruct.gen_gl_CullDistance; - type10 _tmp_return = type10(_e10, _e11, _e12, _e13, _e14); + vec2 _expr10 = v_uv; + vec4 _expr11 = perVertexStruct.gen_gl_Position; + float _expr12 = perVertexStruct.gen_gl_PointSize; + float _expr13[1] = perVertexStruct.gen_gl_ClipDistance; + float _expr14[1] = perVertexStruct.gen_gl_CullDistance; + type10 _tmp_return = type10(_expr10, _expr11, _expr12, _expr13, _expr14); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index e3502e2bc..95466dc3a 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -29,8 +29,8 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } vec2 flip_correction = vec2(0.5, -0.5); vec2 light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - float _e26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); - return _e26; + float _expr26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); + return _expr26; } void main() { @@ -42,26 +42,26 @@ void main() { bool loop_init = true; while(true) { if (!loop_init) { - uint _e40 = i; - i = (_e40 + 1u); + uint _expr40 = i; + i = (_expr40 + 1u); } loop_init = false; - uint _e12 = i; - uvec4 _e14 = _group_0_binding_0.num_lights; - if ((_e12 >= min(_e14.x, 10u))) { + uint _expr12 = i; + uvec4 _expr14 = _group_0_binding_0.num_lights; + if ((_expr12 >= min(_expr14.x, 10u))) { break; } - uint _e19 = i; - Light light = _group_0_binding_1.data[_e19]; - uint _e22 = i; - float _e25 = fetch_shadow(_e22, (light.proj * position)); + uint _expr19 = i; + Light light = _group_0_binding_1.data[_expr19]; + uint _expr22 = i; + float _expr25 = fetch_shadow(_expr22, (light.proj * position)); vec3 light_dir = normalize((light.pos.xyz - position.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); - vec3 _e34 = color; - color = (_e34 + ((_e25 * diffuse) * light.color.xyz)); + vec3 _expr34 = color; + color = (_expr34 + ((_expr25 * diffuse) * light.color.xyz)); } - vec3 _e43 = color; - _fs2p_location0 = vec4(_e43, 1.0); + vec3 _expr43 = color; + _fs2p_location0 = vec4(_expr43, 1.0); return; } diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index fa0b46f02..9cf825635 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -15,8 +15,8 @@ layout(location = 0) out vec4 _fs2p_location0; void main() { VertexOutput in1 = VertexOutput(gl_FragCoord, _vs2fs_location0); - vec4 _e5 = texture(_group_0_binding_1, vec3(in1.uv)); - _fs2p_location0 = _e5; + vec4 _expr5 = texture(_group_0_binding_1, vec3(in1.uv)); + _fs2p_location0 = _expr5; return; } diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index 5f66bc1c6..bae80935e 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -21,15 +21,15 @@ void main() { int tmp2_ = 0; tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); - int _e10 = tmp1_; - int _e16 = tmp2_; - vec4 pos = vec4(((float(_e10) * 4.0) - 1.0), ((float(_e16) * 4.0) - 1.0), 0.0, 1.0); - vec4 _e27 = _group_0_binding_0.view[0]; - vec4 _e31 = _group_0_binding_0.view[1]; - vec4 _e35 = _group_0_binding_0.view[2]; - mat3x3 inv_model_view = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); - mat4x4 _e40 = _group_0_binding_0.proj_inv; - vec4 unprojected = (_e40 * pos); + int _expr10 = tmp1_; + int _expr16 = tmp2_; + vec4 pos = vec4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); + vec4 _expr27 = _group_0_binding_0.view[0]; + vec4 _expr31 = _group_0_binding_0.view[1]; + vec4 _expr35 = _group_0_binding_0.view[2]; + mat3x3 inv_model_view = transpose(mat3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz)); + mat4x4 _expr40 = _group_0_binding_0.proj_inv; + vec4 unprojected = (_expr40 * pos); VertexOutput _tmp_return = VertexOutput(pos, (inv_model_view * unprojected.xyz)); gl_Position = _tmp_return.position; _vs2fs_location0 = _tmp_return.uv; diff --git a/tests/out/glsl/texture-arg.main.Fragment.glsl b/tests/out/glsl/texture-arg.main.Fragment.glsl index 3d46d1cd8..2c71caf43 100644 --- a/tests/out/glsl/texture-arg.main.Fragment.glsl +++ b/tests/out/glsl/texture-arg.main.Fragment.glsl @@ -8,13 +8,13 @@ uniform highp sampler2D _group_0_binding_0; layout(location = 0) out vec4 _fs2p_location0; vec4 test(highp sampler2D Passed_Texture) { - vec4 _e7 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); - return _e7; + vec4 _expr7 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); + return _expr7; } void main() { - vec4 _e2 = test(_group_0_binding_0); - _fs2p_location0 = _e2; + vec4 _expr2 = test(_group_0_binding_0); + _fs2p_location0 = _expr2; return; } diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 9df5db293..7706cda4f 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -34,7 +34,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { fn atomics() { var tmp: i32; - let value: i32 = bar.atom; + let value: i32 = atomicLoad(&bar.atom); let _e6: i32 = atomicAdd(&bar.atom, 5); tmp = _e6; let _e9: i32 = atomicAnd(&bar.atom, 5); @@ -49,6 +49,6 @@ fn atomics() { tmp = _e21; let _e24: i32 = atomicExchange(&bar.atom, 5); tmp = _e24; - bar.atom = value; + atomicStore(&bar.atom, value); return; } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 48b1680f0..8f3f9ad8f 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -619,14 +619,6 @@ fn invalid_structs() { }) } - check_validation_error! { - "[[block]] struct Bad { data: ptr; };": - Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::InvalidBlockType(_), - .. - }) - } - check_validation_error! { "struct Bad { data: array; other: f32; };": Err(naga::valid::ValidationError::Type { From 172f6bf62fcdb31bd492b2ed438070a1037bdcc3 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 10 Aug 2021 22:03:26 -0700 Subject: [PATCH 1214/2212] [spv-out]: De-indent write_texture_coordinates with an early return. No intended change in behavior. --- src/back/spv/block.rs | 133 +++++++++++++++++++++--------------------- 1 file changed, 68 insertions(+), 65 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 0142e10ce..2d67d5583 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -110,79 +110,82 @@ impl<'w> BlockContext<'w> { ) -> Result { let coordinate_id = self.cached[coordinates]; - Ok(if let Some(array_index) = array_index { - let coordinate_scalar_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))?; + // If there's no array index, the texture coordinates are exactly the + // `coordinate` field of the `Expression::ImageLoad`. No work is needed. + let array_index = match array_index { + None => return Ok(coordinate_id), + Some(ix) => ix, + }; - let mut constituent_ids = [0u32; 4]; - let size = match *self.fun_info[coordinates] - .ty - .inner_with(&self.ir_module.types) - { - crate::TypeInner::Scalar { .. } => { - constituent_ids[0] = coordinate_id; - crate::VectorSize::Bi + let coordinate_scalar_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))?; + + let mut constituent_ids = [0u32; 4]; + let size = match *self.fun_info[coordinates] + .ty + .inner_with(&self.ir_module.types) + { + crate::TypeInner::Scalar { .. } => { + constituent_ids[0] = coordinate_id; + crate::VectorSize::Bi + } + crate::TypeInner::Vector { size, .. } => { + for i in 0..size as u32 { + let id = self.gen_id(); + constituent_ids[i as usize] = id; + block.body.push(Instruction::composite_extract( + coordinate_scalar_type_id, + id, + coordinate_id, + &[i], + )); } - crate::TypeInner::Vector { size, .. } => { - for i in 0..size as u32 { - let id = self.gen_id(); - constituent_ids[i as usize] = id; - block.body.push(Instruction::composite_extract( - coordinate_scalar_type_id, - id, - coordinate_id, - &[i], - )); - } - match size { - crate::VectorSize::Bi => crate::VectorSize::Tri, - crate::VectorSize::Tri => crate::VectorSize::Quad, - crate::VectorSize::Quad => { - return Err(Error::Validation("extending vec4 coordinate")); - } + match size { + crate::VectorSize::Bi => crate::VectorSize::Tri, + crate::VectorSize::Tri => crate::VectorSize::Quad, + crate::VectorSize::Quad => { + return Err(Error::Validation("extending vec4 coordinate")); } } - ref other => { - log::error!("wrong coordinate type {:?}", other); - return Err(Error::Validation("coordinate type")); - } - }; + } + ref other => { + log::error!("wrong coordinate type {:?}", other); + return Err(Error::Validation("coordinate type")); + } + }; - let array_index_f32_id = self.gen_id(); - constituent_ids[size as usize - 1] = array_index_f32_id; + let array_index_f32_id = self.gen_id(); + constituent_ids[size as usize - 1] = array_index_f32_id; - let array_index_u32_id = self.cached[array_index]; - let cast_instruction = Instruction::unary( - spirv::Op::ConvertUToF, - coordinate_scalar_type_id, - array_index_f32_id, - array_index_u32_id, - ); - block.body.push(cast_instruction); + let array_index_u32_id = self.cached[array_index]; + let cast_instruction = Instruction::unary( + spirv::Op::ConvertUToF, + coordinate_scalar_type_id, + array_index_f32_id, + array_index_u32_id, + ); + block.body.push(cast_instruction); - let extended_coordinate_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(size), - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))?; + let extended_coordinate_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))?; - let id = self.gen_id(); - block.body.push(Instruction::composite_construct( - extended_coordinate_type_id, - id, - &constituent_ids[..size as usize], - )); - id - } else { - coordinate_id - }) + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + extended_coordinate_type_id, + id, + &constituent_ids[..size as usize], + )); + Ok(id) } /// Decide whether to put off emitting instructions for `expr_handle`. From e2fc7ffd037ab25d7452fe7bcbf67f0b9fff22f9 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 10 Aug 2021 22:18:52 -0700 Subject: [PATCH 1215/2212] [spv-out]: Use OpCompositeConstruct's schmear behavior. In `back::spv::Writer::write_texture_coordinates`, OpCompositeConstruct can concatenate scalars and vectors, so when combining coordinates with an array index, there is no need to extract the coordinate vector's components individually: once the index has been converted to the appropriate component type, it can be combined with the coordinates in a single instruction. --- src/back/spv/block.rs | 54 ++++-------- tests/out/spv/shadow.spvasm | 162 ++++++++++++++++++------------------ 2 files changed, 96 insertions(+), 120 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 2d67d5583..ece8bdc72 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -108,6 +108,8 @@ impl<'w> BlockContext<'w> { array_index: Option>, block: &mut Block, ) -> Result { + use crate::VectorSize as Vs; + let coordinate_id = self.cached[coordinates]; // If there's no array index, the texture coordinates are exactly the @@ -116,7 +118,7 @@ impl<'w> BlockContext<'w> { None => return Ok(coordinate_id), Some(ix) => ix, }; - + let array_index_u32_id = self.cached[array_index]; let coordinate_scalar_type_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size: None, @@ -124,53 +126,29 @@ impl<'w> BlockContext<'w> { width: 4, pointer_class: None, }))?; + let array_index_f32_id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::ConvertUToF, + coordinate_scalar_type_id, + array_index_f32_id, + array_index_u32_id, + )); - let mut constituent_ids = [0u32; 4]; let size = match *self.fun_info[coordinates] .ty .inner_with(&self.ir_module.types) { - crate::TypeInner::Scalar { .. } => { - constituent_ids[0] = coordinate_id; - crate::VectorSize::Bi - } - crate::TypeInner::Vector { size, .. } => { - for i in 0..size as u32 { - let id = self.gen_id(); - constituent_ids[i as usize] = id; - block.body.push(Instruction::composite_extract( - coordinate_scalar_type_id, - id, - coordinate_id, - &[i], - )); - } - match size { - crate::VectorSize::Bi => crate::VectorSize::Tri, - crate::VectorSize::Tri => crate::VectorSize::Quad, - crate::VectorSize::Quad => { - return Err(Error::Validation("extending vec4 coordinate")); - } - } + crate::TypeInner::Scalar { .. } => Vs::Bi, + crate::TypeInner::Vector { size: Vs::Bi, .. } => Vs::Tri, + crate::TypeInner::Vector { size: Vs::Tri, .. } => Vs::Quad, + crate::TypeInner::Vector { size: Vs::Quad, .. } => { + return Err(Error::Validation("extending vec4 coordinate")); } ref other => { log::error!("wrong coordinate type {:?}", other); return Err(Error::Validation("coordinate type")); } }; - - let array_index_f32_id = self.gen_id(); - constituent_ids[size as usize - 1] = array_index_f32_id; - - let array_index_u32_id = self.cached[array_index]; - let cast_instruction = Instruction::unary( - spirv::Op::ConvertUToF, - coordinate_scalar_type_id, - array_index_f32_id, - array_index_u32_id, - ); - block.body.push(cast_instruction); - let extended_coordinate_type_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size: Some(size), @@ -183,7 +161,7 @@ impl<'w> BlockContext<'w> { block.body.push(Instruction::composite_construct( extended_coordinate_type_id, id, - &constituent_ids[..size as usize], + &[coordinate_id, array_index_f32_id] )); Ok(id) } diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index 6f3697e3a..cf7a3e5fb 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 124 +; Bound: 122 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %79 "fs_main" %71 %74 %77 -OpExecutionMode %79 OriginUpperLeft +OpEntryPoint Fragment %77 "fs_main" %69 %72 %75 +OpExecutionMode %77 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_max_lights" OpName %14 "Globals" @@ -24,11 +24,11 @@ OpName %27 "s_lights" OpName %29 "t_shadow" OpName %31 "sampler_shadow" OpName %36 "fetch_shadow" -OpName %66 "color" -OpName %68 "i" -OpName %71 "raw_normal" -OpName %74 "position" -OpName %79 "fs_main" +OpName %64 "color" +OpName %66 "i" +OpName %69 "raw_normal" +OpName %72 "position" +OpName %77 "fs_main" OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %17 0 Offset 0 @@ -48,9 +48,9 @@ OpDecorate %29 DescriptorSet 0 OpDecorate %29 Binding 2 OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 3 -OpDecorate %71 Location 0 -OpDecorate %74 Location 1 -OpDecorate %77 Location 0 +OpDecorate %69 Location 0 +OpDecorate %72 Location 1 +OpDecorate %75 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 @@ -86,18 +86,18 @@ OpDecorate %77 Location 0 %42 = OpTypeBool %54 = OpTypeInt 32 1 %59 = OpTypeSampledImage %20 -%67 = OpTypePointer Function %23 -%69 = OpTypePointer Function %10 -%72 = OpTypePointer Input %23 -%71 = OpVariable %72 Input -%75 = OpTypePointer Input %16 -%74 = OpVariable %75 Input -%78 = OpTypePointer Output %16 -%77 = OpVariable %78 Output -%80 = OpTypeFunction %2 -%90 = OpTypePointer Uniform %13 -%98 = OpTypePointer StorageBuffer %18 -%100 = OpTypePointer StorageBuffer %17 +%65 = OpTypePointer Function %23 +%67 = OpTypePointer Function %10 +%70 = OpTypePointer Input %23 +%69 = OpVariable %70 Input +%73 = OpTypePointer Input %16 +%72 = OpVariable %73 Input +%76 = OpTypePointer Output %16 +%75 = OpVariable %76 Output +%78 = OpTypeFunction %2 +%88 = OpTypePointer Uniform %13 +%96 = OpTypePointer StorageBuffer %18 +%98 = OpTypePointer StorageBuffer %17 %36 = OpFunction %4 None %37 %34 = OpFunctionParameter %10 %35 = OpFunctionParameter %16 @@ -125,71 +125,69 @@ OpReturnValue %5 %56 = OpCompositeExtract %4 %35 2 %57 = OpCompositeExtract %4 %35 3 %58 = OpFDiv %4 %56 %57 -%60 = OpCompositeExtract %4 %53 0 -%61 = OpCompositeExtract %4 %53 1 -%62 = OpConvertUToF %4 %55 -%63 = OpCompositeConstruct %23 %60 %61 %62 -%64 = OpSampledImage %59 %38 %39 -%65 = OpImageSampleDrefExplicitLod %4 %64 %63 %58 Lod %3 -OpReturnValue %65 +%60 = OpConvertUToF %4 %55 +%61 = OpCompositeConstruct %23 %53 %60 +%62 = OpSampledImage %59 %38 %39 +%63 = OpImageSampleDrefExplicitLod %4 %62 %61 %58 Lod %3 +OpReturnValue %63 OpFunctionEnd -%79 = OpFunction %2 None %80 -%70 = OpLabel -%66 = OpVariable %67 Function %24 -%68 = OpVariable %69 Function %11 -%73 = OpLoad %23 %71 -%76 = OpLoad %16 %74 -%81 = OpLoad %20 %29 -%82 = OpLoad %21 %31 +%77 = OpFunction %2 None %78 +%68 = OpLabel +%64 = OpVariable %65 Function %24 +%66 = OpVariable %67 Function %11 +%71 = OpLoad %23 %69 +%74 = OpLoad %16 %72 +%79 = OpLoad %20 %29 +%80 = OpLoad %21 %31 +OpBranch %81 +%81 = OpLabel +%82 = OpExtInst %23 %1 Normalize %71 OpBranch %83 %83 = OpLabel -%84 = OpExtInst %23 %1 Normalize %73 +OpLoopMerge %84 %86 None OpBranch %85 %85 = OpLabel -OpLoopMerge %86 %88 None -OpBranch %87 -%87 = OpLabel -%89 = OpLoad %10 %68 -%91 = OpAccessChain %90 %25 %11 -%92 = OpLoad %13 %91 -%93 = OpCompositeExtract %10 %92 0 -%94 = OpExtInst %10 %1 UMin %93 %9 -%95 = OpUGreaterThanEqual %42 %89 %94 -OpSelectionMerge %96 None -OpBranchConditional %95 %97 %96 -%97 = OpLabel +%87 = OpLoad %10 %66 +%89 = OpAccessChain %88 %25 %11 +%90 = OpLoad %13 %89 +%91 = OpCompositeExtract %10 %90 0 +%92 = OpExtInst %10 %1 UMin %91 %9 +%93 = OpUGreaterThanEqual %42 %87 %92 +OpSelectionMerge %94 None +OpBranchConditional %93 %95 %94 +%95 = OpLabel +OpBranch %84 +%94 = OpLabel +%97 = OpLoad %10 %66 +%99 = OpAccessChain %98 %27 %11 %97 +%100 = OpLoad %17 %99 +%101 = OpLoad %10 %66 +%102 = OpCompositeExtract %15 %100 0 +%103 = OpMatrixTimesVector %16 %102 %74 +%104 = OpFunctionCall %4 %36 %101 %103 +%105 = OpCompositeExtract %16 %100 1 +%106 = OpVectorShuffle %23 %105 %105 0 1 2 +%107 = OpVectorShuffle %23 %74 %74 0 1 2 +%108 = OpFSub %23 %106 %107 +%109 = OpExtInst %23 %1 Normalize %108 +%110 = OpDot %4 %82 %109 +%111 = OpExtInst %4 %1 FMax %3 %110 +%112 = OpLoad %23 %64 +%113 = OpFMul %4 %104 %111 +%114 = OpCompositeExtract %16 %100 2 +%115 = OpVectorShuffle %23 %114 %114 0 1 2 +%116 = OpVectorTimesScalar %23 %115 %113 +%117 = OpFAdd %23 %112 %116 +OpStore %64 %117 OpBranch %86 -%96 = OpLabel -%99 = OpLoad %10 %68 -%101 = OpAccessChain %100 %27 %11 %99 -%102 = OpLoad %17 %101 -%103 = OpLoad %10 %68 -%104 = OpCompositeExtract %15 %102 0 -%105 = OpMatrixTimesVector %16 %104 %76 -%106 = OpFunctionCall %4 %36 %103 %105 -%107 = OpCompositeExtract %16 %102 1 -%108 = OpVectorShuffle %23 %107 %107 0 1 2 -%109 = OpVectorShuffle %23 %76 %76 0 1 2 -%110 = OpFSub %23 %108 %109 -%111 = OpExtInst %23 %1 Normalize %110 -%112 = OpDot %4 %84 %111 -%113 = OpExtInst %4 %1 FMax %3 %112 -%114 = OpLoad %23 %66 -%115 = OpFMul %4 %106 %113 -%116 = OpCompositeExtract %16 %102 2 -%117 = OpVectorShuffle %23 %116 %116 0 1 2 -%118 = OpVectorTimesScalar %23 %117 %115 -%119 = OpFAdd %23 %114 %118 -OpStore %66 %119 -OpBranch %88 -%88 = OpLabel -%120 = OpLoad %10 %68 -%121 = OpIAdd %10 %120 %12 -OpStore %68 %121 -OpBranch %85 %86 = OpLabel -%122 = OpLoad %23 %66 -%123 = OpCompositeConstruct %16 %122 %5 -OpStore %77 %123 +%118 = OpLoad %10 %66 +%119 = OpIAdd %10 %118 %12 +OpStore %66 %119 +OpBranch %83 +%84 = OpLabel +%120 = OpLoad %23 %64 +%121 = OpCompositeConstruct %16 %120 %5 +OpStore %75 %121 OpReturn OpFunctionEnd \ No newline at end of file From fd7011666835bbe8e3c57e8c8a134ec56e662f87 Mon Sep 17 00:00:00 2001 From: Alex Es Date: Wed, 11 Aug 2021 23:04:32 +0300 Subject: [PATCH 1216/2212] Proof of concept for "span" feature, with WGSL & GLSL parsing augmented. (#1092) * Proof of concept for "span" feature, with WGSL parsing augmented. * Review: 1) add_span was actually a bad idea, make it set_span and add set_span_if_unknown too. 2) panics on getting/setting span for invalid handles. 3) only set span for constants with a name 4) don't overwrite spans for types. * Added spans to blocks & more expressions getting spans in frontends. Definitely the shotgunny type of commit, but what can you do. The design I went with made spans mandatory to specify, so I had to go and wire them through wherever I could. * Moved Block to a separate module, +clippy * More spans for types in GLSL. * Remove pointless body method. * Make Arena interface require spans. Another shotgun commit, oh boy... * Fix tests. My loathsome habit to "quickly fix things along the way" made a lot of extra work for me here, having to fix my "fixes" for WGSL parser. * Rustfmt + clippy. * Fix compile-errors with span feature enabled. * Nuked set_span* from orbit. Deleting code feels great! * Code review - move feature flags inside functions. * Fix build with "deserialize" feature enabled. --- Cargo.toml | 1 + src/arena.rs | 90 ++- src/back/msl/writer.rs | 51 +- src/back/spv/block.rs | 15 +- src/block.rs | 131 +++++ src/front/glsl/constants.rs | 387 ++++++++----- src/front/glsl/context.rs | 274 +++++---- src/front/glsl/functions.rs | 301 ++++++---- src/front/glsl/offset.rs | 36 +- src/front/glsl/parser.rs | 2 +- src/front/glsl/parser/declarations.rs | 74 +-- src/front/glsl/parser/expressions.rs | 314 +++++----- src/front/glsl/parser/functions.rs | 316 ++++++---- src/front/glsl/parser/types.rs | 53 +- src/front/glsl/token.rs | 4 + src/front/glsl/types.rs | 27 +- src/front/glsl/variables.rs | 81 ++- src/front/mod.rs | 14 +- src/front/spv/flow.rs | 148 +++-- src/front/spv/function.rs | 189 +++--- src/front/spv/image.rs | 116 ++-- src/front/spv/mod.rs | 805 ++++++++++++++++---------- src/front/spv/null.rs | 132 +++-- src/front/wgsl/lexer.rs | 4 + src/front/wgsl/mod.rs | 662 +++++++++++++-------- src/lib.rs | 10 +- src/proc/terminator.rs | 2 +- src/span.rs | 38 ++ src/valid/analyzer.rs | 110 ++-- 29 files changed, 2819 insertions(+), 1568 deletions(-) create mode 100644 src/block.rs create mode 100644 src/span.rs diff --git a/Cargo.toml b/Cargo.toml index e27d1705b..0c169d9a9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ spv-out = ["spirv"] wgsl-in = ["codespan-reporting"] wgsl-out = [] hlsl-out = [] +span = ["codespan-reporting"] [dev-dependencies] diff = "0.1" diff --git a/src/arena.rs b/src/arena.rs index bd3a3d776..4827433da 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -5,6 +5,8 @@ use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32, ops}; /// the same size and representation as `Handle`. type Index = NonZeroU32; +use crate::Span; + /// A strongly typed reference to an arena item. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] @@ -123,7 +125,6 @@ impl Iterator for Range { /// The arena can be indexed using the given handle to obtain /// a reference to the stored item. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] -#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[cfg_attr( any(feature = "serialize", feature = "deserialize"), serde(transparent) @@ -132,6 +133,9 @@ impl Iterator for Range { pub struct Arena { /// Values of this arena. data: Vec, + #[cfg(feature = "span")] + #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))] + span_info: Vec, } impl Default for Arena { @@ -148,7 +152,11 @@ impl fmt::Debug for Arena { impl Arena { /// Create a new arena with no initial capacity allocated. pub fn new() -> Self { - Arena { data: Vec::new() } + Arena { + data: Vec::new(), + #[cfg(feature = "span")] + span_info: Vec::new(), + } } /// Extracts the inner vector. @@ -187,11 +195,15 @@ impl Arena { } /// Adds a new value to the arena, returning a typed handle. - pub fn append(&mut self, value: T) -> Handle { + pub fn append(&mut self, value: T, span: Span) -> Handle { + #[cfg(not(feature = "span"))] + let _ = span; let position = self.data.len() + 1; let index = Index::new(position as u32).expect("Failed to append to Arena. Handle overflows"); self.data.push(value); + #[cfg(feature = "span")] + self.span_info.push(span); Handle::new(index) } @@ -207,30 +219,35 @@ impl Arena { /// returns a handle pointing to /// an existing element if the check succeeds, or adds a new /// element otherwise. - pub fn fetch_if_or_append bool>(&mut self, value: T, fun: F) -> Handle { + pub fn fetch_if_or_append bool>( + &mut self, + value: T, + span: Span, + fun: F, + ) -> Handle { if let Some(index) = self.data.iter().position(|d| fun(d, &value)) { let index = unsafe { Index::new_unchecked((index + 1) as u32) }; Handle::new(index) } else { - self.append(value) + self.append(value, span) } } /// Adds a value with a check for uniqueness, where the check is plain comparison. - pub fn fetch_or_append(&mut self, value: T) -> Handle + pub fn fetch_or_append(&mut self, value: T, span: Span) -> Handle where T: PartialEq, { - self.fetch_if_or_append(value, T::eq) + self.fetch_if_or_append(value, span, T::eq) } pub fn try_get(&self, handle: Handle) -> Option<&T> { - self.data.get(handle.index.get() as usize - 1) + self.data.get(handle.index()) } /// Get a mutable reference to an element in the arena. pub fn get_mut(&mut self, handle: Handle) -> &mut T { - self.data.get_mut(handle.index.get() as usize - 1).unwrap() + self.data.get_mut(handle.index()).unwrap() } /// Get the range of handles from a particular number of elements to the end. @@ -245,6 +262,39 @@ impl Arena { pub fn clear(&mut self) { self.data.clear() } + + pub fn get_span(&self, handle: Handle) -> &Span { + #[cfg(feature = "span")] + { + return self.span_info.get(handle.index()).unwrap_or(&Span::Unknown); + } + #[cfg(not(feature = "span"))] + { + let _ = handle; + &Span::Unknown + } + } +} + +#[cfg(feature = "deserialize")] +impl<'de, T> serde::Deserialize<'de> for Arena +where + T: serde::Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let data = Vec::deserialize(deserializer)?; + #[cfg(feature = "span")] + let span_info = std::iter::repeat(Span::Unknown).take(data.len()).collect(); + + Ok(Self { + data, + #[cfg(feature = "span")] + span_info, + }) + } } impl ops::Index> for Arena { @@ -254,6 +304,12 @@ impl ops::Index> for Arena { } } +impl ops::IndexMut> for Arena { + fn index_mut(&mut self, handle: Handle) -> &mut T { + &mut self.data[handle.index()] + } +} + impl ops::Index> for Arena { type Output = [T]; fn index(&self, range: Range) -> &[T] { @@ -268,8 +324,8 @@ mod tests { #[test] fn append_non_unique() { let mut arena: Arena = Arena::new(); - let t1 = arena.append(0); - let t2 = arena.append(0); + let t1 = arena.append(0, Default::default()); + let t2 = arena.append(0, Default::default()); assert!(t1 != t2); assert!(arena[t1] == arena[t2]); } @@ -277,8 +333,8 @@ mod tests { #[test] fn append_unique() { let mut arena: Arena = Arena::new(); - let t1 = arena.append(0); - let t2 = arena.append(1); + let t1 = arena.append(0, Default::default()); + let t2 = arena.append(1, Default::default()); assert!(t1 != t2); assert!(arena[t1] != arena[t2]); } @@ -286,8 +342,8 @@ mod tests { #[test] fn fetch_or_append_non_unique() { let mut arena: Arena = Arena::new(); - let t1 = arena.fetch_or_append(0); - let t2 = arena.fetch_or_append(0); + let t1 = arena.fetch_or_append(0, Default::default()); + let t2 = arena.fetch_or_append(0, Default::default()); assert!(t1 == t2); assert!(arena[t1] == arena[t2]) } @@ -295,8 +351,8 @@ mod tests { #[test] fn fetch_or_append_unique() { let mut arena: Arena = Arena::new(); - let t1 = arena.fetch_or_append(0); - let t2 = arena.fetch_or_append(1); + let t1 = arena.fetch_or_append(0, Default::default()); + let t2 = arena.fetch_or_append(1, Default::default()); assert!(t1 != t2); assert!(arena[t1] != arena[t2]); } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index fa9ec02bf..465992d82 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2555,30 +2555,41 @@ fn test_stack_size() { use crate::valid::{Capabilities, ValidationFlags}; // create a module with at least one expression nested let mut module = crate::Module::default(); - let constant = module.constants.append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - value: crate::ScalarValue::Float(1.0), - width: 4, + let constant = module.constants.append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + value: crate::ScalarValue::Float(1.0), + width: 4, + }, }, - }); + Default::default(), + ); let mut fun = crate::Function::default(); let const_expr = fun .expressions - .append(crate::Expression::Constant(constant)); - let nested_expr = fun.expressions.append(crate::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr: const_expr, - }); - fun.body - .push(crate::Statement::Emit(fun.expressions.range_from(1))); - fun.body.push(crate::Statement::If { - condition: nested_expr, - accept: Vec::new(), - reject: Vec::new(), - }); - let _ = module.functions.append(fun); + .append(crate::Expression::Constant(constant), Default::default()); + let nested_expr = fun.expressions.append( + crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr: const_expr, + }, + Default::default(), + ); + fun.body.push( + crate::Statement::Emit(fun.expressions.range_from(1)), + Default::default(), + ); + fun.body.push( + crate::Statement::If { + condition: nested_expr, + accept: crate::Block::new(), + reject: crate::Block::new(), + }, + Default::default(), + ); + let _ = module.functions.append(fun, Default::default()); // analyse the module let info = crate::valid::Validator::new(ValidationFlags::empty(), Capabilities::empty()) .validate(&module) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index ece8bdc72..daaf243b8 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -119,13 +119,12 @@ impl<'w> BlockContext<'w> { Some(ix) => ix, }; let array_index_u32_id = self.cached[array_index]; - let coordinate_scalar_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))?; + let coordinate_scalar_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }))?; let array_index_f32_id = self.gen_id(); block.body.push(Instruction::unary( spirv::Op::ConvertUToF, @@ -161,7 +160,7 @@ impl<'w> BlockContext<'w> { block.body.push(Instruction::composite_construct( extended_coordinate_type_id, id, - &[coordinate_id, array_index_f32_id] + &[coordinate_id, array_index_f32_id], )); Ok(id) } diff --git a/src/block.rs b/src/block.rs new file mode 100644 index 000000000..d7bcaed63 --- /dev/null +++ b/src/block.rs @@ -0,0 +1,131 @@ +use crate::{Span, Statement}; +use std::ops::{Deref, DerefMut, RangeBounds}; + +/// A code block is a vector of statements, with maybe a vector of spans. +#[derive(Debug, Clone, Default)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr( + any(feature = "serialize", feature = "deserialize"), + serde(transparent) +)] +pub struct Block { + body: Vec, + #[cfg(feature = "span")] + #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))] + span_info: Vec, +} + +impl Block { + pub fn new() -> Self { + Self { + body: Vec::new(), + #[cfg(feature = "span")] + span_info: Vec::new(), + } + } + + pub fn from_vec(body: Vec) -> Self { + #[cfg(feature = "span")] + let span_info = std::iter::repeat(Span::Unknown).take(body.len()).collect(); + Self { + body, + #[cfg(feature = "span")] + span_info, + } + } + + pub fn with_capacity(capacity: usize) -> Self { + Self { + body: Vec::with_capacity(capacity), + #[cfg(feature = "span")] + span_info: Vec::with_capacity(capacity), + } + } + + #[allow(unused_variables)] + pub fn push(&mut self, end: Statement, span: Span) { + self.body.push(end); + #[cfg(feature = "span")] + self.span_info.push(span); + } + + pub fn extend(&mut self, item: Option<(Statement, Span)>) { + if let Some((end, span)) = item { + self.push(end, span) + } + } + + pub fn extend_block(&mut self, other: Self) { + #[cfg(feature = "span")] + self.span_info.extend(other.span_info); + self.body.extend(other.body); + } + + pub fn cull + Clone>(&mut self, range: R) { + #[cfg(feature = "span")] + self.span_info.drain(range.clone()); + self.body.drain(range); + } + + pub fn splice + Clone>(&mut self, range: R, other: Self) { + #[cfg(feature = "span")] + self.span_info + .splice(range.clone(), other.span_info.into_iter()); + self.body.splice(range, other.body.into_iter()); + } + + pub fn span_iter_mut(&mut self) -> impl Iterator)> { + #[cfg(feature = "span")] + let span_iter = self.span_info.iter_mut().map(Some); + #[cfg(not(feature = "span"))] + let span_iter = std::iter::repeat_with(|| None); + + self.body.iter_mut().zip(span_iter) + } + + pub fn is_empty(&self) -> bool { + self.body.is_empty() + } + + pub fn len(&self) -> usize { + self.body.len() + } +} + +impl Deref for Block { + type Target = [Statement]; + fn deref(&self) -> &[Statement] { + &self.body + } +} + +impl DerefMut for Block { + fn deref_mut(&mut self) -> &mut [Statement] { + &mut self.body + } +} + +impl<'a> IntoIterator for &'a Block { + type Item = &'a Statement; + type IntoIter = std::slice::Iter<'a, Statement>; + + fn into_iter(self) -> std::slice::Iter<'a, Statement> { + self.iter() + } +} + +#[cfg(feature = "deserialize")] +impl<'de> serde::Deserialize<'de> for Block { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + Ok(Self::from_vec(Vec::deserialize(deserializer)?)) + } +} + +impl From> for Block { + fn from(body: Vec) -> Self { + Self::from_vec(body) + } +} diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index ac0f7bef6..0ac7f69d2 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -64,6 +64,7 @@ impl<'a> ConstantSolver<'a> { &mut self, expr: Handle, ) -> Result, ConstantSolvingError> { + let span = self.expressions.get_span(expr).clone(); match self.expressions[expr] { Expression::Constant(constant) => Ok(constant), Expression::AccessIndex { base, index } => self.access(base, index as usize), @@ -88,14 +89,17 @@ impl<'a> ConstantSolver<'a> { //TODO: register the new type if needed let ty = ty.ok_or(ConstantSolvingError::DestinationTypeNotFound)?; - Ok(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { - ty, - components: vec![value_constant; size as usize], + Ok(self.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty, + components: vec![value_constant; size as usize], + }, }, - })) + span, + )) } Expression::Swizzle { size, @@ -129,11 +133,14 @@ impl<'a> ConstantSolver<'a> { .map(|&sc| src_components[sc as usize]) .collect(); - Ok(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { ty, components }, - })) + Ok(self.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { ty, components }, + }, + span, + )) } Expression::Compose { ty, ref components } => { let components = components @@ -141,22 +148,25 @@ impl<'a> ConstantSolver<'a> { .map(|c| self.solve(*c)) .collect::>()?; - Ok(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { ty, components }, - })) + Ok(self.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { ty, components }, + }, + span, + )) } Expression::Unary { expr, op } => { let expr_constant = self.solve(expr)?; - self.unary_op(op, expr_constant) + self.unary_op(op, expr_constant, span) } Expression::Binary { left, right, op } => { let left_constant = self.solve(left)?; let right_constant = self.solve(right)?; - self.binary_op(op, left_constant, right_constant) + self.binary_op(op, left_constant, right_constant, span) } Expression::Math { fun, arg, arg1, .. } => { let arg = self.solve(arg)?; @@ -192,11 +202,14 @@ impl<'a> ConstantSolver<'a> { _ => return Err(ConstantSolvingError::InvalidMathArg), }; - Ok(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { width, value }, - })) + Ok(self.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { width, value }, + }, + span, + )) } _ => Err(ConstantSolvingError::NotImplemented(format!("{:?}", fun))), } @@ -209,7 +222,7 @@ impl<'a> ConstantSolver<'a> { let expr_constant = self.solve(expr)?; match convert { - Some(width) => self.cast(expr_constant, kind, width), + Some(width) => self.cast(expr_constant, kind, width, span), None => Err(ConstantSolvingError::Bitcast), } } @@ -288,6 +301,7 @@ impl<'a> ConstantSolver<'a> { constant: Handle, kind: ScalarKind, target_width: crate::Bytes, + span: crate::Span, ) -> Result, ConstantSolvingError> { fn inner_cast(value: ScalarValue) -> A { match value { @@ -324,22 +338,26 @@ impl<'a> ConstantSolver<'a> { } for component in components { - *component = self.cast(*component, kind, target_width)?; + *component = self.cast(*component, kind, target_width, span.clone())?; } } } - Ok(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner, - })) + Ok(self.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner, + }, + span, + )) } fn unary_op( &mut self, op: UnaryOperator, constant: Handle, + span: crate::Span, ) -> Result, ConstantSolvingError> { let mut inner = self.constants[constant].inner.clone(); @@ -367,16 +385,19 @@ impl<'a> ConstantSolver<'a> { } for component in components { - *component = self.unary_op(op, *component)? + *component = self.unary_op(op, *component, span.clone())? } } } - Ok(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner, - })) + Ok(self.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner, + }, + span, + )) } fn binary_op( @@ -384,6 +405,7 @@ impl<'a> ConstantSolver<'a> { op: BinaryOperator, left: Handle, right: Handle, + span: crate::Span, ) -> Result, ConstantSolvingError> { let left_inner = &self.constants[left].inner; let right_inner = &self.constants[right].inner; @@ -464,25 +486,28 @@ impl<'a> ConstantSolver<'a> { (&ConstantInner::Composite { ref components, ty }, &ConstantInner::Scalar { .. }) => { let mut components = components.clone(); for comp in components.iter_mut() { - *comp = self.binary_op(op, *comp, right)?; + *comp = self.binary_op(op, *comp, right, span.clone())?; } ConstantInner::Composite { ty, components } } (&ConstantInner::Scalar { .. }, &ConstantInner::Composite { ref components, ty }) => { let mut components = components.clone(); for comp in components.iter_mut() { - *comp = self.binary_op(op, left, *comp)?; + *comp = self.binary_op(op, left, *comp, span.clone())?; } ConstantInner::Composite { ty, components } } _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), }; - Ok(self.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner, - })) + Ok(self.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner, + }, + span, + )) } } @@ -503,59 +528,80 @@ mod tests { let mut expressions = Arena::new(); let mut constants = Arena::new(); - let vec_ty = types.append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Bi, - kind: ScalarKind::Sint, - width: 4, + let vec_ty = types.append( + Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Sint, + width: 4, + }, }, - }); + Default::default(), + ); - let h = constants.append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(4), + let h = constants.append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(4), + }, }, - }); + Default::default(), + ); - let h1 = constants.append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(8), + let h1 = constants.append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(8), + }, }, - }); + Default::default(), + ); - let vec_h = constants.append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { - ty: vec_ty, - components: vec![h, h1], + let vec_h = constants.append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: vec_ty, + components: vec![h, h1], + }, }, - }); + Default::default(), + ); - let expr = expressions.append(Expression::Constant(h)); - let expr1 = expressions.append(Expression::Constant(vec_h)); + let expr = expressions.append(Expression::Constant(h), Default::default()); + let expr1 = expressions.append(Expression::Constant(vec_h), Default::default()); - let root1 = expressions.append(Expression::Unary { - op: UnaryOperator::Negate, - expr, - }); + let root1 = expressions.append( + Expression::Unary { + op: UnaryOperator::Negate, + expr, + }, + Default::default(), + ); - let root2 = expressions.append(Expression::Unary { - op: UnaryOperator::Not, - expr, - }); + let root2 = expressions.append( + Expression::Unary { + op: UnaryOperator::Not, + expr, + }, + Default::default(), + ); - let root3 = expressions.append(Expression::Unary { - op: UnaryOperator::Not, - expr: expr1, - }); + let root3 = expressions.append( + Expression::Unary { + op: UnaryOperator::Not, + expr: expr1, + }, + Default::default(), + ); let mut solver = ConstantSolver { types: &types, @@ -614,22 +660,28 @@ mod tests { let mut expressions = Arena::new(); let mut constants = Arena::new(); - let h = constants.append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(4), + let h = constants.append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(4), + }, }, - }); + Default::default(), + ); - let expr = expressions.append(Expression::Constant(h)); + let expr = expressions.append(Expression::Constant(h), Default::default()); - let root = expressions.append(Expression::As { - expr, - kind: ScalarKind::Bool, - convert: Some(crate::BOOL_WIDTH), - }); + let root = expressions.append( + Expression::As { + expr, + kind: ScalarKind::Bool, + convert: Some(crate::BOOL_WIDTH), + }, + Default::default(), + ); let mut solver = ConstantSolver { types: &Arena::new(), @@ -654,86 +706,113 @@ mod tests { let mut expressions = Arena::new(); let mut constants = Arena::new(); - let matrix_ty = types.append(Type { - name: None, - inner: TypeInner::Matrix { - columns: VectorSize::Bi, - rows: VectorSize::Tri, - width: 4, + let matrix_ty = types.append( + Type { + name: None, + inner: TypeInner::Matrix { + columns: VectorSize::Bi, + rows: VectorSize::Tri, + width: 4, + }, }, - }); + Default::default(), + ); - let vec_ty = types.append(Type { - name: None, - inner: TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Float, - width: 4, + let vec_ty = types.append( + Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Float, + width: 4, + }, }, - }); + Default::default(), + ); let mut vec1_components = Vec::with_capacity(3); let mut vec2_components = Vec::with_capacity(3); for i in 0..3 { - let h = constants.append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(i as f64), + let h = constants.append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(i as f64), + }, }, - }); + Default::default(), + ); vec1_components.push(h) } for i in 3..6 { - let h = constants.append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(i as f64), + let h = constants.append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(i as f64), + }, }, - }); + Default::default(), + ); vec2_components.push(h) } - let vec1 = constants.append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { - ty: vec_ty, - components: vec1_components, + let vec1 = constants.append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: vec_ty, + components: vec1_components, + }, }, - }); + Default::default(), + ); - let vec2 = constants.append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { - ty: vec_ty, - components: vec2_components, + let vec2 = constants.append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: vec_ty, + components: vec2_components, + }, }, - }); + Default::default(), + ); - let h = constants.append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { - ty: matrix_ty, - components: vec![vec1, vec2], + let h = constants.append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: matrix_ty, + components: vec![vec1, vec2], + }, }, - }); + Default::default(), + ); - let base = expressions.append(Expression::Constant(h)); - let root1 = expressions.append(Expression::AccessIndex { base, index: 1 }); - let root2 = expressions.append(Expression::AccessIndex { - base: root1, - index: 2, - }); + let base = expressions.append(Expression::Constant(h), Default::default()); + let root1 = expressions.append( + Expression::AccessIndex { base, index: 1 }, + Default::default(), + ); + let root2 = expressions.append( + Expression::AccessIndex { + base: root1, + index: 2, + }, + Default::default(), + ); let mut solver = ConstantSolver { types: &types, diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 8b30a6a2b..1b8d7835c 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -79,8 +79,9 @@ impl Context { self.emit_flush(body); let (expr, load) = match kind { GlobalLookupKind::Variable(v) => { + let span = parser.module.global_variables.get_span(v).clone(); let res = ( - self.expressions.append(Expression::GlobalVariable(v)), + self.expressions.append(Expression::GlobalVariable(v), span), parser.module.global_variables[v].class != StorageClass::Handle, ); self.emit_start(); @@ -88,11 +89,14 @@ impl Context { res } GlobalLookupKind::BlockSelect(handle, index) => { - let base = self.expressions.append(Expression::GlobalVariable(handle)); + let span = parser.module.global_variables.get_span(handle).clone(); + let base = self + .expressions + .append(Expression::GlobalVariable(handle), span.clone()); self.emit_start(); let expr = self .expressions - .append(Expression::AccessIndex { base, index }); + .append(Expression::AccessIndex { base, index }, span); (expr, { let ty = parser.module.global_variables[handle].ty; @@ -114,7 +118,11 @@ impl Context { }) } GlobalLookupKind::Constant(v) => { - let res = (self.expressions.append(Expression::Constant(v)), false); + let span = parser.module.constants.get_span(v).clone(); + let res = ( + self.expressions.append(Expression::Constant(v), span), + false, + ); self.emit_start(); res } @@ -138,15 +146,21 @@ impl Context { body.extend(self.emitter.finish(&self.expressions)) } - pub fn add_expression(&mut self, expr: Expression, body: &mut Block) -> Handle { - if expr.needs_pre_emit() { + pub fn add_expression( + &mut self, + expr: Expression, + meta: SourceMetadata, + body: &mut Block, + ) -> Handle { + let needs_pre_emit = expr.needs_pre_emit(); + if needs_pre_emit { self.emit_flush(body); - let handle = self.expressions.append(expr); - self.emit_start(); - handle - } else { - self.expressions.append(expr) } + let handle = self.expressions.append(expr, meta.as_span()); + if needs_pre_emit { + self.emit_start(); + } + handle } pub fn lookup_local_var(&self, name: &str) -> Option { @@ -191,13 +205,13 @@ impl Context { &mut self, parser: &mut Parser, body: &mut Block, - name: Option, + name_meta: Option<(String, SourceMetadata)>, ty: Handle, qualifier: ParameterQualifier, ) { let index = self.arguments.len(); let mut arg = FunctionArgument { - name: name.clone(), + name: name_meta.as_ref().map(|&(ref name, _)| name.clone()), ty, binding: None, }; @@ -209,13 +223,17 @@ impl Context { }; if qualifier.is_lhs() { - arg.ty = parser.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Pointer { - base: arg.ty, - class: StorageClass::Function, + let span = parser.module.types.get_span(arg.ty).clone(); + arg.ty = parser.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Pointer { + base: arg.ty, + class: StorageClass::Function, + }, }, - }) + span, + ) } self.arguments.push(arg); @@ -225,26 +243,32 @@ impl Context { depth: false, }); - if let Some(name) = name { - let expr = self.add_expression(Expression::FunctionArgument(index as u32), body); + if let Some((name, meta)) = name_meta { + let expr = self.add_expression(Expression::FunctionArgument(index as u32), meta, body); let mutable = qualifier != ParameterQualifier::Const && !opaque; let load = qualifier.is_lhs(); if mutable && !load { - let handle = self.locals.append(LocalVariable { - name: Some(name.clone()), - ty, - init: None, - }); - let local_expr = self.add_expression(Expression::LocalVariable(handle), body); + let handle = self.locals.append( + LocalVariable { + name: Some(name.clone()), + ty, + init: None, + }, + meta.as_span(), + ); + let local_expr = self.add_expression(Expression::LocalVariable(handle), meta, body); self.emit_flush(body); self.emit_start(); - body.push(Statement::Store { - pointer: local_expr, - value: expr, - }); + body.push( + Statement::Store { + pointer: local_expr, + value: expr, + }, + meta.as_span(), + ); if let Some(current) = self.scopes.last_mut() { (*current).insert( @@ -395,18 +419,19 @@ impl Context { _ => return None, }, }, + meta, body, )) }) .unwrap_or_else(|| { - self.add_expression(Expression::Access { base, index }, body) + self.add_expression(Expression::Access { base, index }, meta, body) }); if !lhs { let resolved = parser.resolve_type(self, pointer, meta)?; if resolved.pointer_class().is_some() { return Ok(( - Some(self.add_expression(Expression::Load { pointer }, body)), + Some(self.add_expression(Expression::Load { pointer }, meta, body)), meta, )); } @@ -420,7 +445,7 @@ impl Context { parser.field_selection(self, lhs, body, base, field, meta)? } HirExprKind::Constant(constant) if !lhs => { - self.add_expression(Expression::Constant(constant), body) + self.add_expression(Expression::Constant(constant), meta, body) } HirExprKind::Binary { left, op, right } if !lhs => { let (mut left, left_meta) = @@ -453,13 +478,19 @@ impl Context { false => (BinaryOperator::NotEqual, RelationalFunction::Any), }; - let argument = - self.expressions - .append(Expression::Binary { op, left, right }); + let argument = self + .expressions + .append(Expression::Binary { op, left, right }, meta.as_span()); - self.add_expression(Expression::Relational { fun, argument }, body) + self.add_expression( + Expression::Relational { fun, argument }, + meta, + body, + ) + } + _ => { + self.add_expression(Expression::Binary { left, op, right }, meta, body) } - _ => self.add_expression(Expression::Binary { left, op, right }, body), }, (&TypeInner::Vector { size, .. }, &TypeInner::Scalar { .. }) => match op { BinaryOperator::Add @@ -467,8 +498,11 @@ impl Context { | BinaryOperator::Divide | BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => { - let scalar_vector = - self.add_expression(Expression::Splat { size, value: right }, body); + let scalar_vector = self.add_expression( + Expression::Splat { size, value: right }, + meta, + body, + ); self.add_expression( Expression::Binary { @@ -476,15 +510,21 @@ impl Context { left, right: scalar_vector, }, + meta, body, ) } - _ => self.add_expression(Expression::Binary { left, op, right }, body), + _ => { + self.add_expression(Expression::Binary { left, op, right }, meta, body) + } }, (&TypeInner::Scalar { .. }, &TypeInner::Vector { size, .. }) => match op { BinaryOperator::Add | BinaryOperator::Subtract | BinaryOperator::Divide => { - let scalar_vector = - self.add_expression(Expression::Splat { size, value: left }, body); + let scalar_vector = self.add_expression( + Expression::Splat { size, value: left }, + meta, + body, + ); self.add_expression( Expression::Binary { @@ -492,18 +532,21 @@ impl Context { left: scalar_vector, right, }, + meta, body, ) } - _ => self.add_expression(Expression::Binary { left, op, right }, body), + _ => { + self.add_expression(Expression::Binary { left, op, right }, meta, body) + } }, - _ => self.add_expression(Expression::Binary { left, op, right }, body), + _ => self.add_expression(Expression::Binary { left, op, right }, meta, body), } } HirExprKind::Unary { op, expr } if !lhs => { let expr = self.lower_expect_inner(stmt, parser, expr, false, body)?.0; - self.add_expression(Expression::Unary { op, expr }, body) + self.add_expression(Expression::Unary { op, expr }, meta, body) } HirExprKind::Variable(ref var) => { if lhs { @@ -518,7 +561,7 @@ impl Context { var.expr } else if var.load { - self.add_expression(Expression::Load { pointer: var.expr }, body) + self.add_expression(Expression::Load { pointer: var.expr }, meta, body) } else { var.expr } @@ -561,6 +604,7 @@ impl Context { accept, reject, }, + meta, body, ) } @@ -600,6 +644,7 @@ impl Context { base: vector, index: pattern[index].index(), }, + meta, body, ); let src = self.add_expression( @@ -607,22 +652,26 @@ impl Context { base: value, index: index as u32, }, + meta, body, ); self.emit_flush(body); self.emit_start(); - body.push(Statement::Store { - pointer: dst, - value: src, - }); + body.push( + Statement::Store { + pointer: dst, + value: src, + }, + meta.as_span(), + ); } } else { self.emit_flush(body); self.emit_start(); - body.push(Statement::Store { pointer, value }); + body.push(Statement::Store { pointer, value }, meta.as_span()); } value @@ -638,7 +687,7 @@ impl Context { }; let pointer = self.lower_expect_inner(stmt, parser, expr, true, body)?.0; - let left = self.add_expression(Expression::Load { pointer }, body); + let left = self.add_expression(Expression::Load { pointer }, meta, body); let uint = match parser.resolve_type(self, left, meta)?.scalar_kind() { Some(ScalarKind::Sint) => false, @@ -654,59 +703,71 @@ impl Context { } }; - let one = parser.module.constants.append(Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: match uint { - true => crate::ScalarValue::Uint(1), - false => crate::ScalarValue::Sint(1), + let one = parser.module.constants.append( + Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: match uint { + true => crate::ScalarValue::Uint(1), + false => crate::ScalarValue::Sint(1), + }, }, }, - }); - let right = self.add_expression(Expression::Constant(one), body); + Default::default(), + ); + let right = self.add_expression(Expression::Constant(one), meta, body); - let value = self.add_expression(Expression::Binary { op, left, right }, body); + let value = self.add_expression(Expression::Binary { op, left, right }, meta, body); if postfix { - let local = self.locals.append(LocalVariable { - name: None, - ty: parser.module.types.fetch_or_append(Type { + let local = self.locals.append( + LocalVariable { name: None, - inner: TypeInner::Scalar { - kind: match uint { - true => ScalarKind::Uint, - false => ScalarKind::Sint, + ty: parser.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Scalar { + kind: match uint { + true => ScalarKind::Uint, + false => ScalarKind::Sint, + }, + width: 4, + }, }, - width: 4, - }, - }), - init: None, - }); + meta.as_span(), + ), + init: None, + }, + meta.as_span(), + ); - let expr = self.add_expression(Expression::LocalVariable(local), body); - let load = self.add_expression(Expression::Load { pointer: expr }, body); + let expr = self.add_expression(Expression::LocalVariable(local), meta, body); + let load = self.add_expression(Expression::Load { pointer: expr }, meta, body); self.emit_flush(body); self.emit_start(); - body.push(Statement::Store { - pointer: expr, - value: left, - }); + body.push( + Statement::Store { + pointer: expr, + value: left, + }, + meta.as_span(), + ); self.emit_flush(body); self.emit_start(); - body.push(Statement::Store { pointer, value }); + body.push(Statement::Store { pointer, value }, meta.as_span()); load } else { self.emit_flush(body); self.emit_start(); - body.push(Statement::Store { pointer, value }); + body.push(Statement::Store { pointer, value }, meta.as_span()); left } @@ -758,11 +819,14 @@ impl Context { (type_power(kind), self.expr_power(parser, *expr, meta)?) { if tgt_power > expr_power { - *expr = self.expressions.append(Expression::As { - expr: *expr, - kind, - convert: Some(width), - }) + *expr = self.expressions.append( + Expression::As { + expr: *expr, + kind, + convert: Some(width), + }, + meta.as_span(), + ) } } @@ -789,19 +853,25 @@ impl Context { ) { match left_power.cmp(&right_power) { std::cmp::Ordering::Less => { - *left = self.expressions.append(Expression::As { - expr: *left, - kind: right_kind, - convert: Some(right_width), - }) + *left = self.expressions.append( + Expression::As { + expr: *left, + kind: right_kind, + convert: Some(right_width), + }, + left_meta.as_span(), + ) } std::cmp::Ordering::Equal => {} std::cmp::Ordering::Greater => { - *right = self.expressions.append(Expression::As { - expr: *right, - kind: left_kind, - convert: Some(left_width), - }) + *right = self.expressions.append( + Expression::As { + expr: *right, + kind: left_kind, + convert: Some(left_width), + }, + right_meta.as_span(), + ) } } } @@ -822,7 +892,7 @@ impl Context { if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { *expr = self .expressions - .append(Expression::Splat { size, value: *expr }) + .append(Expression::Splat { size, value: *expr }, meta.as_span()) } Ok(()) @@ -832,6 +902,7 @@ impl Context { &mut self, size: VectorSize, vector: Handle, + meta: SourceMetadata, body: &mut Block, ) -> Handle { self.add_expression( @@ -840,6 +911,7 @@ impl Context { vector, pattern: crate::SwizzleComponent::XYZW, }, + meta, body, ) } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 7e3326bfb..8d5a1b780 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -23,7 +23,12 @@ struct CoordComponents { } impl Parser { - fn add_constant_value(&mut self, scalar_kind: ScalarKind, value: u64) -> Handle { + fn add_constant_value( + &mut self, + scalar_kind: ScalarKind, + value: u64, + meta: SourceMetadata, + ) -> Handle { let value = match scalar_kind { ScalarKind::Uint => ScalarValue::Uint(value), ScalarKind::Sint => ScalarValue::Sint(value as i64), @@ -31,11 +36,14 @@ impl Parser { _ => unreachable!(), }; - self.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { width: 4, value }, - }) + self.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { width: 4, value }, + }, + meta.as_span(), + ) } pub(crate) fn function_or_constructor_call( @@ -68,10 +76,13 @@ impl Parser { if expr_type.scalar_kind() == Some(ScalarKind::Bool) && result_scalar_kind != ScalarKind::Bool => { - let c0 = self.add_constant_value(result_scalar_kind, 0u64); - let c1 = self.add_constant_value(result_scalar_kind, 1u64); - let mut reject = ctx.add_expression(Expression::Constant(c0), body); - let mut accept = ctx.add_expression(Expression::Constant(c1), body); + let (condition, expr_meta) = args[0]; + let c0 = self.add_constant_value(result_scalar_kind, 0u64, meta); + let c1 = self.add_constant_value(result_scalar_kind, 1u64, meta); + let mut reject = + ctx.add_expression(Expression::Constant(c0), expr_meta, body); + let mut accept = + ctx.add_expression(Expression::Constant(c1), expr_meta, body); ctx.implicit_splat(self, &mut reject, meta, vector_size)?; ctx.implicit_splat(self, &mut accept, meta, vector_size)?; @@ -80,8 +91,9 @@ impl Parser { Expression::Select { accept, reject, - condition: args[0].0, + condition, }, + expr_meta, body, ); @@ -95,7 +107,7 @@ impl Parser { let (mut value, meta) = args[0]; ctx.implicit_conversion(self, &mut value, meta, kind, width)?; - ctx.add_expression(Expression::Splat { size, value }, body) + ctx.add_expression(Expression::Splat { size, value }, meta, body) } TypeInner::Scalar { kind, width } => ctx.add_expression( Expression::As { @@ -103,13 +115,14 @@ impl Parser { expr: args[0].0, convert: Some(width), }, + args[0].1, body, ), TypeInner::Vector { size, kind, width } => { let mut expr = args[0].0; if vector_size.map_or(true, |s| s != size) { - expr = ctx.vector_resize(size, expr, body); + expr = ctx.vector_resize(size, expr, args[0].1, body); } ctx.add_expression( @@ -118,6 +131,7 @@ impl Parser { expr, convert: Some(width), }, + args[0].1, body, ) } @@ -144,25 +158,33 @@ impl Parser { // value is used to initialize all the values along the diagonal of // the matrix; the rest are given zeros. let mut components = Vec::with_capacity(columns as usize); - let vector_ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: rows, - kind: ScalarKind::Float, - width, + let vector_ty = self.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, + }, }, - }); - let zero_constant = - self.module.constants.fetch_or_append(Constant { + meta.as_span(), + ); + let zero_constant = self.module.constants.fetch_or_append( + Constant { name: None, specialization: None, inner: ConstantInner::Scalar { width, value: ScalarValue::Float(0.0), }, - }); - let zero = ctx - .add_expression(Expression::Constant(zero_constant), body); + }, + meta.as_span(), + ); + let zero = ctx.add_expression( + Expression::Constant(zero_constant), + meta, + body, + ); for i in 0..columns as u32 { components.push( @@ -177,12 +199,17 @@ impl Parser { }) .collect(), }, + meta, body, ), ) } - ctx.add_expression(Expression::Compose { ty, components }, body) + ctx.add_expression( + Expression::Compose { ty, components }, + meta, + body, + ) } TypeInner::Matrix { rows: ori_rows, .. } => { let mut components = Vec::new(); @@ -193,17 +220,22 @@ impl Parser { base: value, index: n, }, + meta, body, ); if ori_rows != rows { - vector = ctx.vector_resize(rows, vector, body); + vector = ctx.vector_resize(rows, vector, meta, body); } components.push(vector) } - ctx.add_expression(Expression::Compose { ty, components }, body) + ctx.add_expression( + Expression::Compose { ty, components }, + meta, + body, + ) } _ => { let columns = @@ -214,6 +246,7 @@ impl Parser { ty, components: columns, }, + meta, body, ) } @@ -224,6 +257,7 @@ impl Parser { ty, components: args.into_iter().map(|arg| arg.0).collect(), }, + meta, body, ), _ => { @@ -262,6 +296,7 @@ impl Parser { base: arg, index: i, }, + meta, body, )) } @@ -270,14 +305,17 @@ impl Parser { } } - let ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - size: rows, - kind: ScalarKind::Float, - width, + let ty = self.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, + }, }, - }); + meta.as_span(), + ); for chunk in flattened.chunks(rows as usize) { components.push(ctx.add_expression( @@ -285,6 +323,7 @@ impl Parser { ty, components: Vec::from(chunk), }, + meta, body, )) } @@ -302,7 +341,7 @@ impl Parser { } } - ctx.add_expression(Expression::Compose { ty, components }, body) + ctx.add_expression(Expression::Compose { ty, components }, meta, body) }; Ok(Some(h)) @@ -371,6 +410,7 @@ impl Parser { }), depth_ref: comps.depth_ref, }, + meta, body, ), )) @@ -401,6 +441,7 @@ impl Parser { level: SampleLevel::Exact(args[2].0), depth_ref: comps.depth_ref, }, + meta, body, ))) } else { @@ -437,17 +478,19 @@ impl Parser { base, index: size as u32 - 1, }, + meta, body, ); let left = if let VectorSize::Bi = size { - ctx.add_expression(Expression::AccessIndex { base, index: 0 }, body) + ctx.add_expression(Expression::AccessIndex { base, index: 0 }, meta, body) } else { let size = match size { VectorSize::Tri => VectorSize::Bi, _ => VectorSize::Tri, }; - right = ctx.add_expression(Expression::Splat { size, value: right }, body); - ctx.vector_resize(size, base, body) + right = + ctx.add_expression(Expression::Splat { size, value: right }, meta, body); + ctx.vector_resize(size, base, meta, body) }; let coords = ctx.add_expression( Expression::Binary { @@ -455,6 +498,7 @@ impl Parser { left, right, }, + meta, body, ); let comps = self.coordinate_components(ctx, args[0], (coords, base_meta), body)?; @@ -469,6 +513,7 @@ impl Parser { level, depth_ref: comps.depth_ref, }, + meta, body, ))) } else { @@ -503,6 +548,7 @@ impl Parser { }, depth_ref: comps.depth_ref, }, + meta, body, ))) } else { @@ -526,6 +572,7 @@ impl Parser { level: args.get(1).map(|e| e.0), }, }, + meta, body, ))) } @@ -546,6 +593,7 @@ impl Parser { array_index: comps.array_index, index: Some(args[2].0), }, + meta, body, ))) } else { @@ -599,6 +647,7 @@ impl Parser { arg1: None, arg2: None, }, + meta, body, ))) } @@ -618,7 +667,7 @@ impl Parser { }, _ => return Err(Error::wrong_function_args(name, 2, args.len(), meta)), }; - Ok(Some(ctx.add_expression(expr, body))) + Ok(Some(ctx.add_expression(expr, meta, body))) } "mod" => { if args.len() != 2 { @@ -636,6 +685,7 @@ impl Parser { left, right, }, + meta, body, ))) } @@ -667,6 +717,7 @@ impl Parser { arg1: Some(arg1), arg2: None, }, + meta, body, ))) } @@ -700,6 +751,7 @@ impl Parser { arg1: Some(arg1), arg2: None, }, + meta, body, ))) } @@ -739,6 +791,7 @@ impl Parser { size, value: selector, }, + meta, body, ) } @@ -771,7 +824,7 @@ impl Parser { }, }; - Ok(Some(ctx.add_expression(expr, body))) + Ok(Some(ctx.add_expression(expr, meta, body))) } "clamp" => { if args.len() != 3 { @@ -801,6 +854,7 @@ impl Parser { arg1: Some(arg1), arg2: Some(arg2), }, + meta, body, ))) } @@ -821,6 +875,7 @@ impl Parser { arg1: Some(args[1].0), arg2: Some(args[2].0), }, + meta, body, ))) } @@ -843,6 +898,7 @@ impl Parser { left: args[0].0, right: args[1].0, }, + meta, body, ))) } @@ -986,22 +1042,31 @@ impl Parser { if parameter_info.qualifier.is_lhs() && matches!(ctx[handle], Expression::Swizzle { .. }) { - let ty = self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { size, kind, width }, - }); - let temp_var = ctx.locals.append(LocalVariable { - name: None, - ty, - init: None, - }); + let ty = self.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }, + meta.as_span(), + ); + let temp_var = ctx.locals.append( + LocalVariable { + name: None, + ty, + init: None, + }, + meta.as_span(), + ); let temp_expr = - ctx.add_expression(Expression::LocalVariable(temp_var), body); + ctx.add_expression(Expression::LocalVariable(temp_var), meta, body); - body.push(Statement::Store { - pointer: temp_expr, - value: handle, - }); + body.push( + Statement::Store { + pointer: temp_expr, + value: handle, + }, + meta.as_span(), + ); arguments.push(temp_expr); proxy_writes.push((*expr, temp_expr)); @@ -1020,27 +1085,33 @@ impl Parser { ctx.emit_flush(body); let result = if !is_void { - Some(ctx.add_expression(Expression::CallResult(function), body)) + Some(ctx.add_expression(Expression::CallResult(function), meta, body)) } else { None }; - body.push(crate::Statement::Call { - function, - arguments, - result, - }); + body.push( + crate::Statement::Call { + function, + arguments, + result, + }, + meta.as_span(), + ); ctx.emit_start(); for (tgt, pointer) in proxy_writes { - let value = ctx.add_expression(Expression::Load { pointer }, body); + let value = ctx.add_expression(Expression::Load { pointer }, meta, body); let target = ctx.lower_expect_inner(stmt, self, tgt, true, body)?.0; ctx.emit_flush(body); - body.push(Statement::Store { - pointer: target, - value, - }); + body.push( + Statement::Store { + pointer: target, + value, + }, + meta.as_span(), + ); ctx.emit_start(); } @@ -1067,6 +1138,7 @@ impl Parser { fun, argument: args[0].0, }, + meta, body, )) } @@ -1135,7 +1207,7 @@ impl Parser { return; } - let handle = module.functions.append(function); + let handle = module.functions.append(function, meta.as_span()); declarations.push(FunctionDeclaration { parameters, parameters_info, @@ -1195,7 +1267,7 @@ impl Parser { }); } - let handle = module.functions.append(function); + let handle = module.functions.append(function, meta.as_span()); declarations.push(FunctionDeclaration { parameters, parameters_info, @@ -1208,7 +1280,7 @@ impl Parser { pub(crate) fn add_entry_point( &mut self, function: Handle, - mut global_init_body: Block, + global_init_body: Block, mut expressions: Arena, ) { let mut arguments = Vec::new(); @@ -1235,19 +1307,23 @@ impl Parser { binding: Some(arg.binding.clone()), }); - let pointer = expressions.append(Expression::GlobalVariable(arg.handle)); - let value = expressions.append(Expression::FunctionArgument(idx)); + let pointer = + expressions.append(Expression::GlobalVariable(arg.handle), Default::default()); + let value = expressions.append(Expression::FunctionArgument(idx), Default::default()); - body.push(Statement::Store { pointer, value }); + body.push(Statement::Store { pointer, value }, Default::default()); } - body.append(&mut global_init_body); + body.extend_block(global_init_body); - body.push(Statement::Call { - function, - arguments: Vec::new(), - result: None, - }); + body.push( + Statement::Call { + function, + arguments: Vec::new(), + result: None, + }, + Default::default(), + ); let mut span = 0; let mut members = Vec::new(); @@ -1269,33 +1345,44 @@ impl Parser { span += self.module.types[ty].inner.span(&self.module.constants); - let pointer = expressions.append(Expression::GlobalVariable(arg.handle)); + let pointer = + expressions.append(Expression::GlobalVariable(arg.handle), Default::default()); let len = expressions.len(); - let load = expressions.append(Expression::Load { pointer }); - body.push(Statement::Emit(expressions.range_from(len))); + let load = expressions.append(Expression::Load { pointer }, Default::default()); + body.push( + Statement::Emit(expressions.range_from(len)), + Default::default(), + ); components.push(load) } let (ty, value) = if !components.is_empty() { - let ty = self.module.types.append(Type { - name: None, - inner: TypeInner::Struct { - top_level: false, - members, - span, + let ty = self.module.types.append( + Type { + name: None, + inner: TypeInner::Struct { + top_level: false, + members, + span, + }, }, - }); + Default::default(), + ); let len = expressions.len(); - let res = expressions.append(Expression::Compose { ty, components }); - body.push(Statement::Emit(expressions.range_from(len))); + let res = + expressions.append(Expression::Compose { ty, components }, Default::default()); + body.push( + Statement::Emit(expressions.range_from(len)), + Default::default(), + ); (Some(ty), Some(res)) } else { (None, None) }; - body.push(Statement::Return { value }); + body.push(Statement::Return { value }, Default::default()); self.module.entry_points.push(EntryPoint { name: "main".to_string(), @@ -1344,13 +1431,14 @@ impl Parser { let coordinate = match (image_size, coord_size) { (Some(size), Some(coord_s)) if size != coord_s => { - ctx.vector_resize(size, coord, body) + ctx.vector_resize(size, coord, coord_meta, body) } (None, Some(_)) => ctx.add_expression( Expression::AccessIndex { base: coord, index: 0, }, + coord_meta, body, ), _ => coord, @@ -1362,7 +1450,11 @@ impl Parser { false => image_size.map_or(0, |s| s as u32), }; - Some(ctx.add_expression(Expression::AccessIndex { base: coord, index }, body)) + Some(ctx.add_expression( + Expression::AccessIndex { base: coord, index }, + coord_meta, + body, + )) } _ => None, }; @@ -1370,7 +1462,11 @@ impl Parser { true => { let index = image_size.map_or(0, |s| s as u32); - Some(ctx.add_expression(Expression::AccessIndex { base: coord, index }, body)) + Some(ctx.add_expression( + Expression::AccessIndex { base: coord, index }, + coord_meta, + body, + )) } false => None, }; @@ -1423,14 +1519,17 @@ fn sampled_to_depth( arrayed, } => match class { ImageClass::Sampled { multi, .. } => { - *ty = module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Image { - dim, - arrayed, - class: ImageClass::Depth { multi }, + *ty = module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Image { + dim, + arrayed, + class: ImageClass::Depth { multi }, + }, }, - }) + module.types.get_span(*ty).clone(), + ) } ImageClass::Depth { .. } => {} _ => errors.push(Error { diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 698aeab35..cb3f0b75d 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -84,14 +84,18 @@ pub fn calculate_offset( crate::ArraySize::Dynamic => stride, }; - ty = types.fetch_or_append(Type { - name, - inner: TypeInner::Array { - base: info.ty, - size, - stride, + let ty_span = types.get_span(ty).clone(); + ty = types.fetch_or_append( + Type { + name, + inner: TypeInner::Array { + base: info.ty, + size, + stride, + }, }, - }); + ty_span, + ); (align, span) } @@ -138,14 +142,18 @@ pub fn calculate_offset( span += info.span; } - ty = types.fetch_or_append(Type { - name, - inner: TypeInner::Struct { - top_level, - members, - span, + let ty_span = types.get_span(ty).clone(); + ty = types.fetch_or_append( + Type { + name, + inner: TypeInner::Struct { + top_level, + members, + span, + }, }, - }); + ty_span, + ); (align, span) } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index a5ee5f409..a43396df6 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -393,7 +393,7 @@ impl<'ctx> DeclarationContext<'ctx> { GlobalOrConstant::Global(handle) => Expression::GlobalVariable(handle), GlobalOrConstant::Constant(handle) => Expression::Constant(handle), }; - Ok(self.ctx.add_expression(expr, self.body)) + Ok(self.ctx.add_expression(expr, meta, self.body)) } false => parser.add_local_var(self.ctx, self.body, decl), } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index d6fbd7c70..806e98e35 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -25,7 +25,10 @@ impl<'source> ParsingContext<'source> { global_ctx: &mut Context, global_body: &mut Block, ) -> Result<()> { - if !self.parse_declaration(parser, global_ctx, global_body, true)? { + if self + .parse_declaration(parser, global_ctx, global_body, true)? + .is_none() + { let token = self.bump(parser)?; match token.value { TokenValue::Semicolon if parser.meta.version == 460 => Ok(()), @@ -94,7 +97,7 @@ impl<'source> ParsingContext<'source> { } Ok(( - ctx.add_expression(Expression::Compose { ty, components }, body), + ctx.add_expression(Expression::Compose { ty, components }, meta, body), meta, )) } else { @@ -173,7 +176,7 @@ impl<'source> ParsingContext<'source> { // NOTE: unlike other parse methods this one doesn't expect an array specifier and // returns Ok(None) rather than an error if there is not one let array_specifier = self.parse_array_specifier(parser)?; - let ty = parser.maybe_array(ty, array_specifier); + let ty = parser.maybe_array(ty, meta, array_specifier); let init = self .bump_if(parser, TokenValue::Assign) @@ -203,7 +206,8 @@ impl<'source> ParsingContext<'source> { if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) { ctx.flush_expressions(); - ctx.body.push(Statement::Store { pointer, value }); + ctx.body + .push(Statement::Store { pointer, value }, meta.as_span()); } let token = self.bump(parser)?; @@ -232,7 +236,7 @@ impl<'source> ParsingContext<'source> { ctx: &mut Context, body: &mut Block, external: bool, - ) -> Result { + ) -> Result> { //declaration: // function_prototype SEMICOLON // @@ -276,7 +280,7 @@ impl<'source> ParsingContext<'source> { // This branch handles function prototypes parser.add_prototype(context, name, result, meta); - Ok(true) + Ok(Some(meta)) } TokenValue::LeftBrace if external => { // This branch handles function definitions @@ -284,11 +288,16 @@ impl<'source> ParsingContext<'source> { // only happens if external is also true // parse the body - self.parse_compound_statement(parser, &mut context, &mut body)?; + self.parse_compound_statement( + token.meta, + parser, + &mut context, + &mut body, + )?; parser.add_function(context, name, result, body, meta); - Ok(true) + Ok(Some(meta)) } _ if external => Err(Error { kind: ErrorKind::InvalidToken( @@ -338,7 +347,7 @@ impl<'source> ParsingContext<'source> { }) } - Ok(true) + Ok(Some(meta)) } else { // This branch handles struct definitions and modifiers like // ```glsl @@ -356,6 +365,7 @@ impl<'source> ParsingContext<'source> { ty_name, token.meta, ) + .map(Some) } else { //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON @@ -367,7 +377,9 @@ impl<'source> ParsingContext<'source> { } } TokenValue::Semicolon => { + let mut meta_all = token.meta; for &(ref qualifier, meta) in qualifiers.iter() { + meta_all = meta_all.union(&meta); match *qualifier { TypeQualifier::WorkGroupSize(i, value) => { parser.meta.workgroup_size[i] = value @@ -391,7 +403,7 @@ impl<'source> ParsingContext<'source> { } } - Ok(true) + Ok(Some(meta_all)) } _ => Err(Error { kind: ErrorKind::InvalidToken( @@ -447,9 +459,9 @@ impl<'source> ParsingContext<'source> { self.expect(parser, TokenValue::Semicolon)?; - Ok(true) + Ok(Some(meta)) } - _ => Ok(false), + _ => Ok(None), } } } @@ -461,8 +473,8 @@ impl<'source> ParsingContext<'source> { body: &mut Block, qualifiers: &[(TypeQualifier, SourceMetadata)], ty_name: String, - mut meta: SourceMetadata, - ) -> Result { + meta: SourceMetadata, + ) -> Result { let mut storage = None; let mut layout = None; @@ -486,29 +498,24 @@ impl<'source> ParsingContext<'source> { let span = self.parse_struct_declaration_list(parser, &mut members, layout)?; self.expect(parser, TokenValue::RightBrace)?; - let mut ty = parser.module.types.append(Type { - name: Some(ty_name), - inner: TypeInner::Struct { - top_level: true, - members: members.clone(), - span, + let mut ty = parser.module.types.append( + Type { + name: Some(ty_name), + inner: TypeInner::Struct { + top_level: true, + members: members.clone(), + span, + }, }, - }); + Default::default(), + ); let token = self.bump(parser)?; let name = match token.value { TokenValue::Semicolon => None, TokenValue::Identifier(name) => { - if let Some(size) = self.parse_array_specifier(parser)? { - ty = parser.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: ty, - size, - stride: parser.module.types[ty].inner.span(&parser.module.constants), - }, - }); - } + let array_specifier = self.parse_array_specifier(parser)?; + ty = parser.maybe_array(ty, token.meta, array_specifier); self.expect(parser, TokenValue::Semicolon)?; @@ -524,7 +531,6 @@ impl<'source> ParsingContext<'source> { }) } }; - meta = meta.union(&token.meta); let global = parser.add_global_var( ctx, @@ -556,7 +562,7 @@ impl<'source> ParsingContext<'source> { parser.global_variables.push((k, lookup)); } - Ok(true) + Ok(meta) } // TODO: Accept layout arguments @@ -578,7 +584,7 @@ impl<'source> ParsingContext<'source> { meta = meta.union(&end_meta); let array_specifier = self.parse_array_specifier(parser)?; - let ty = parser.maybe_array(ty, array_specifier); + let ty = parser.maybe_array(ty, meta, array_specifier); self.expect(parser, TokenValue::Semicolon)?; diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 59eacb9a4..02184e9bd 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -59,16 +59,22 @@ impl<'source> ParsingContext<'source> { } }; - let handle = parser.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { width, value }, - }); + let handle = parser.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { width, value }, + }, + token.meta.as_span(), + ); - Ok(stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::Constant(handle), - meta: token.meta, - })) + Ok(stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Constant(handle), + meta: token.meta, + }, + Default::default(), + )) } pub fn parse_function_call_args( @@ -133,7 +139,7 @@ impl<'source> ParsingContext<'source> { meta, } } else { - let var = match parser.lookup_variable(ctx, body, &name) { + let var = match parser.lookup_variable(ctx, body, &name, meta) { Some(var) => var, None => { return Err(Error { @@ -149,13 +155,17 @@ impl<'source> ParsingContext<'source> { } }; - stmt.hir_exprs.append(expr) + stmt.hir_exprs.append(expr, Default::default()) } TokenValue::TypeName(_) => { - let Token { value, mut meta } = self.bump(parser)?; + let Token { + value, + meta: name_meta, + } = self.bump(parser)?; + let mut meta = name_meta; let mut handle = if let TokenValue::TypeName(ty) = value { - parser.module.types.fetch_or_append(ty) + parser.module.types.fetch_or_append(ty, name_meta.as_span()) } else { unreachable!() }; @@ -165,7 +175,7 @@ impl<'source> ParsingContext<'source> { self.expect(parser, TokenValue::LeftParen)?; let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; - if let Some(array_size) = maybe_size { + if let Some((array_size, array_meta)) = maybe_size { let stride = parser.module.types[handle] .inner .span(&parser.module.constants); @@ -173,36 +183,45 @@ impl<'source> ParsingContext<'source> { let size = match array_size { ArraySize::Constant(size) => ArraySize::Constant(size), ArraySize::Dynamic => { - let constant = parser.module.constants.fetch_or_append(Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(args.len() as i64), + let constant = parser.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Sint(args.len() as i64), + }, }, - }); + meta.as_span(), + ); ArraySize::Constant(constant) } }; - handle = parser.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base: handle, - size, - stride, + handle = parser.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Array { + base: handle, + size, + stride, + }, }, - }) + name_meta.union(&array_meta).as_span(), + ); } - stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::Call(FunctionCall { - kind: FunctionCallKind::TypeConstructor(handle), - args, - }), - meta, - }) + stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Call(FunctionCall { + kind: FunctionCallKind::TypeConstructor(handle), + args, + }), + meta, + }, + Default::default(), + ) } _ => self.parse_primary(parser, ctx, stmt, body)?, }; @@ -219,38 +238,50 @@ impl<'source> ParsingContext<'source> { let index = self.parse_expression(parser, ctx, stmt, body)?; let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; - base = stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::Access { base, index }, - meta: meta.union(&end_meta), - }) + base = stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Access { base, index }, + meta: meta.union(&end_meta), + }, + Default::default(), + ) } TokenValue::Dot => { let (field, end_meta) = self.expect_ident(parser)?; - base = stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::Select { base, field }, - meta: meta.union(&end_meta), - }) + base = stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Select { base, field }, + meta: meta.union(&end_meta), + }, + Default::default(), + ) } TokenValue::Increment => { - base = stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::IncDec { - increment: true, - postfix: true, - expr: base, + base = stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::IncDec { + increment: true, + postfix: true, + expr: base, + }, + meta, }, - meta, - }) + Default::default(), + ) } TokenValue::Decrement => { - base = stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::IncDec { - increment: false, - postfix: true, - expr: base, + base = stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::IncDec { + increment: false, + postfix: true, + expr: base, + }, + meta, }, - meta, - }) + Default::default(), + ) } _ => unreachable!(), } @@ -286,28 +317,34 @@ impl<'source> ParsingContext<'source> { _ => return Ok(expr), }; - stmt.hir_exprs.append(HirExpr { - kind, - meta: meta.union(&end_meta), - }) + stmt.hir_exprs.append( + HirExpr { + kind, + meta: meta.union(&end_meta), + }, + Default::default(), + ) } TokenValue::Increment | TokenValue::Decrement => { let Token { value, meta } = self.bump(parser)?; let expr = self.parse_unary(parser, ctx, stmt, body)?; - stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::IncDec { - increment: match value { - TokenValue::Increment => true, - TokenValue::Decrement => false, - _ => unreachable!(), + stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::IncDec { + increment: match value { + TokenValue::Increment => true, + TokenValue::Decrement => false, + _ => unreachable!(), + }, + postfix: false, + expr, }, - postfix: false, - expr, + meta, }, - meta, - }) + Default::default(), + ) } _ => self.parse_postfix(parser, ctx, stmt, body)?, }) @@ -337,35 +374,38 @@ impl<'source> ParsingContext<'source> { let right = self.parse_binary(parser, ctx, stmt, body, None, r_bp)?; let end_meta = stmt.hir_exprs[right].meta; - left = stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::Binary { - left, - op: match value { - TokenValue::LogicalOr => BinaryOperator::LogicalOr, - TokenValue::LogicalXor => BinaryOperator::NotEqual, - TokenValue::LogicalAnd => BinaryOperator::LogicalAnd, - TokenValue::VerticalBar => BinaryOperator::InclusiveOr, - TokenValue::Caret => BinaryOperator::ExclusiveOr, - TokenValue::Ampersand => BinaryOperator::And, - TokenValue::Equal => BinaryOperator::Equal, - TokenValue::NotEqual => BinaryOperator::NotEqual, - TokenValue::GreaterEqual => BinaryOperator::GreaterEqual, - TokenValue::LessEqual => BinaryOperator::LessEqual, - TokenValue::LeftAngle => BinaryOperator::Less, - TokenValue::RightAngle => BinaryOperator::Greater, - TokenValue::LeftShift => BinaryOperator::ShiftLeft, - TokenValue::RightShift => BinaryOperator::ShiftRight, - TokenValue::Plus => BinaryOperator::Add, - TokenValue::Dash => BinaryOperator::Subtract, - TokenValue::Star => BinaryOperator::Multiply, - TokenValue::Slash => BinaryOperator::Divide, - TokenValue::Percent => BinaryOperator::Modulo, - _ => unreachable!(), + left = stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Binary { + left, + op: match value { + TokenValue::LogicalOr => BinaryOperator::LogicalOr, + TokenValue::LogicalXor => BinaryOperator::NotEqual, + TokenValue::LogicalAnd => BinaryOperator::LogicalAnd, + TokenValue::VerticalBar => BinaryOperator::InclusiveOr, + TokenValue::Caret => BinaryOperator::ExclusiveOr, + TokenValue::Ampersand => BinaryOperator::And, + TokenValue::Equal => BinaryOperator::Equal, + TokenValue::NotEqual => BinaryOperator::NotEqual, + TokenValue::GreaterEqual => BinaryOperator::GreaterEqual, + TokenValue::LessEqual => BinaryOperator::LessEqual, + TokenValue::LeftAngle => BinaryOperator::Less, + TokenValue::RightAngle => BinaryOperator::Greater, + TokenValue::LeftShift => BinaryOperator::ShiftLeft, + TokenValue::RightShift => BinaryOperator::ShiftRight, + TokenValue::Plus => BinaryOperator::Add, + TokenValue::Dash => BinaryOperator::Subtract, + TokenValue::Star => BinaryOperator::Multiply, + TokenValue::Slash => BinaryOperator::Divide, + TokenValue::Percent => BinaryOperator::Modulo, + _ => unreachable!(), + }, + right, }, - right, + meta: start_meta.union(&end_meta), }, - meta: start_meta.union(&end_meta), - }) + Default::default(), + ) } Ok(left) @@ -388,14 +428,17 @@ impl<'source> ParsingContext<'source> { let reject = self.parse_assignment(parser, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[reject].meta; - condition = stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::Conditional { - condition, - accept, - reject, + condition = stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Conditional { + condition, + accept, + reject, + }, + meta: start_meta.union(&end_meta), }, - meta: start_meta.union(&end_meta), - }) + Default::default(), + ) } Ok(condition) @@ -417,10 +460,13 @@ impl<'source> ParsingContext<'source> { let value = self.parse_assignment(parser, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[value].meta; - stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::Assign { tgt, value }, - meta: start_meta.union(&end_meta), - }) + stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Assign { tgt, value }, + meta: start_meta.union(&end_meta), + }, + Default::default(), + ) } TokenValue::OrAssign | TokenValue::AndAssign @@ -436,31 +482,37 @@ impl<'source> ParsingContext<'source> { let right = self.parse_assignment(parser, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[right].meta; - let value = stmt.hir_exprs.append(HirExpr { - meta: start_meta.union(&end_meta), - kind: HirExprKind::Binary { - left: tgt, - op: match token.value { - TokenValue::OrAssign => BinaryOperator::InclusiveOr, - TokenValue::AndAssign => BinaryOperator::And, - TokenValue::AddAssign => BinaryOperator::Add, - TokenValue::DivAssign => BinaryOperator::Divide, - TokenValue::ModAssign => BinaryOperator::Modulo, - TokenValue::SubAssign => BinaryOperator::Subtract, - TokenValue::MulAssign => BinaryOperator::Multiply, - TokenValue::LeftShiftAssign => BinaryOperator::ShiftLeft, - TokenValue::RightShiftAssign => BinaryOperator::ShiftRight, - TokenValue::XorAssign => BinaryOperator::ExclusiveOr, - _ => unreachable!(), + let value = stmt.hir_exprs.append( + HirExpr { + meta: start_meta.union(&end_meta), + kind: HirExprKind::Binary { + left: tgt, + op: match token.value { + TokenValue::OrAssign => BinaryOperator::InclusiveOr, + TokenValue::AndAssign => BinaryOperator::And, + TokenValue::AddAssign => BinaryOperator::Add, + TokenValue::DivAssign => BinaryOperator::Divide, + TokenValue::ModAssign => BinaryOperator::Modulo, + TokenValue::SubAssign => BinaryOperator::Subtract, + TokenValue::MulAssign => BinaryOperator::Multiply, + TokenValue::LeftShiftAssign => BinaryOperator::ShiftLeft, + TokenValue::RightShiftAssign => BinaryOperator::ShiftRight, + TokenValue::XorAssign => BinaryOperator::ExclusiveOr, + _ => unreachable!(), + }, + right, }, - right, }, - }); + Default::default(), + ); - stmt.hir_exprs.append(HirExpr { - kind: HirExprKind::Assign { tgt, value }, - meta: start_meta.union(&end_meta), - }) + stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Assign { tgt, value }, + meta: start_meta.union(&end_meta), + }, + Default::default(), + ) } _ => self.parse_conditional(parser, ctx, stmt, body, Some(tgt))?, }) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index efc72803b..af1568fcd 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -1,3 +1,4 @@ +use crate::front::glsl::SourceMetadata; use crate::{ front::glsl::{ ast::ParameterQualifier, @@ -38,7 +39,7 @@ impl<'source> ParsingContext<'source> { parser: &mut Parser, ctx: &mut Context, body: &mut Block, - ) -> Result<()> { + ) -> Result> { // TODO: This prevents snippets like the following from working // ```glsl // vec4(1.0); @@ -47,55 +48,60 @@ impl<'source> ParsingContext<'source> { // declarations and since this statement is very unlikely and most // likely an error, for now we don't support it if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { - self.parse_declaration(parser, ctx, body, false)?; - return Ok(()); + return self.parse_declaration(parser, ctx, body, false); } - match self.expect_peek(parser)?.value { + let new_break = || { + let mut block = Block::new(); + block.push(Statement::Break, crate::Span::Unknown); + block + }; + + let &Token { ref value, meta } = self.expect_peek(parser)?; + + let meta_rest = match *value { TokenValue::Continue => { - self.bump(parser)?; - body.push(Statement::Continue); - self.expect(parser, TokenValue::Semicolon)?; + body.push(Statement::Continue, self.bump(parser)?.meta.as_span()); + self.expect(parser, TokenValue::Semicolon)?.meta } TokenValue::Break => { - self.bump(parser)?; - body.push(Statement::Break); - self.expect(parser, TokenValue::Semicolon)?; + body.push(Statement::Break, self.bump(parser)?.meta.as_span()); + self.expect(parser, TokenValue::Semicolon)?.meta } TokenValue::Return => { self.bump(parser)?; - let value = match self.expect_peek(parser)?.value { - TokenValue::Semicolon => { - self.bump(parser)?; - None - } + let (value, meta) = match self.expect_peek(parser)?.value { + TokenValue::Semicolon => (None, self.bump(parser)?.meta), _ => { // TODO: Implicit conversions let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; self.expect(parser, TokenValue::Semicolon)?; - Some(ctx.lower_expect(stmt, parser, expr, false, body)?.0) + let (handle, meta) = ctx.lower_expect(stmt, parser, expr, false, body)?; + (Some(handle), meta) } }; ctx.emit_flush(body); ctx.emit_start(); - body.push(Statement::Return { value }) + body.push(Statement::Return { value }, meta.as_span()); + meta } TokenValue::Discard => { - self.bump(parser)?; - body.push(Statement::Kill); - self.expect(parser, TokenValue::Semicolon)?; + body.push(Statement::Kill, self.bump(parser)?.meta.as_span()); + self.expect(parser, TokenValue::Semicolon)?.meta } TokenValue::If => { - self.bump(parser)?; + let mut meta = self.bump(parser)?.meta; self.expect(parser, TokenValue::LeftParen)?; let condition = { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower_expect(stmt, parser, expr, false, body)?.0 + let (handle, more_meta) = ctx.lower_expect(stmt, parser, expr, false, body)?; + meta = meta.union(&more_meta); + handle }; self.expect(parser, TokenValue::RightParen)?; @@ -103,21 +109,30 @@ impl<'source> ParsingContext<'source> { ctx.emit_start(); let mut accept = Block::new(); - self.parse_statement(parser, ctx, &mut accept)?; + if let Some(more_meta) = self.parse_statement(parser, ctx, &mut accept)? { + meta = meta.union(&more_meta) + } let mut reject = Block::new(); if self.bump_if(parser, TokenValue::Else).is_some() { - self.parse_statement(parser, ctx, &mut reject)?; + if let Some(more_meta) = self.parse_statement(parser, ctx, &mut reject)? { + meta = meta.union(&more_meta); + } } - body.push(Statement::If { - condition, - accept, - reject, - }); + body.push( + Statement::If { + condition, + accept, + reject, + }, + meta.as_span(), + ); + meta } TokenValue::Switch => { - self.bump(parser)?; + let start_meta = self.bump(parser)?.meta; + let end_meta; self.expect(parser, TokenValue::LeftParen)?; // TODO: Implicit conversions @@ -177,7 +192,9 @@ impl<'source> ParsingContext<'source> { TokenValue::Case | TokenValue::Default | TokenValue::RightBrace => break, - _ => self.parse_statement(parser, ctx, &mut body)?, + _ => { + self.parse_statement(parser, ctx, &mut body)?; + } } } @@ -186,7 +203,7 @@ impl<'source> ParsingContext<'source> { for (i, stmt) in body.iter().enumerate() { if let Statement::Break = *stmt { fall_through = false; - body.drain(i..); + body.cull(i..); break; } } @@ -214,19 +231,21 @@ impl<'source> ParsingContext<'source> { loop { match self.expect_peek(parser)?.value { TokenValue::Case | TokenValue::RightBrace => break, - _ => self.parse_statement(parser, ctx, &mut default)?, + _ => { + self.parse_statement(parser, ctx, &mut default)?; + } } } for (i, stmt) in default.iter().enumerate() { if let Statement::Break = *stmt { - default.drain(i..); + default.cull(i..); break; } } } TokenValue::RightBrace => { - self.bump(parser)?; + end_meta = self.bump(parser)?.meta; break; } _ => { @@ -246,51 +265,67 @@ impl<'source> ParsingContext<'source> { } } - body.push(Statement::Switch { - selector, - cases, - default, - }); + let meta = start_meta.union(&end_meta); + body.push( + Statement::Switch { + selector, + cases, + default, + }, + meta.as_span(), + ); + meta } TokenValue::While => { - self.bump(parser)?; + let meta = self.bump(parser)?.meta; let mut loop_body = Block::new(); let mut stmt = ctx.stmt_ctx(); self.expect(parser, TokenValue::LeftParen)?; let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; - self.expect(parser, TokenValue::RightParen)?; + let meta = meta.union(&self.expect(parser, TokenValue::RightParen)?.meta); - let expr = ctx - .lower_expect(stmt, parser, root, false, &mut loop_body)? - .0; + let (expr, expr_meta) = + ctx.lower_expect(stmt, parser, root, false, &mut loop_body)?; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, expr, }, + expr_meta, &mut loop_body, ); ctx.emit_flush(&mut loop_body); ctx.emit_start(); - loop_body.push(Statement::If { - condition, - accept: vec![Statement::Break], - reject: Block::new(), - }); + loop_body.push( + Statement::If { + condition, + accept: new_break(), + reject: Block::new(), + }, + crate::Span::Unknown, + ); - self.parse_statement(parser, ctx, &mut loop_body)?; + let mut meta = meta.union(&expr_meta); - body.push(Statement::Loop { - body: loop_body, - continuing: Block::new(), - }) + if let Some(body_meta) = self.parse_statement(parser, ctx, &mut loop_body)? { + meta = meta.union(&body_meta); + } + + body.push( + Statement::Loop { + body: loop_body, + continuing: Block::new(), + }, + meta.as_span(), + ); + meta } TokenValue::Do => { - self.bump(parser)?; + let start_meta = self.bump(parser)?.meta; let mut loop_body = Block::new(); self.parse_statement(parser, ctx, &mut loop_body)?; @@ -300,35 +335,44 @@ impl<'source> ParsingContext<'source> { self.expect(parser, TokenValue::While)?; self.expect(parser, TokenValue::LeftParen)?; let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; - self.expect(parser, TokenValue::RightParen)?; + let end_meta = self.expect(parser, TokenValue::RightParen)?.meta; - let expr = ctx - .lower_expect(stmt, parser, root, false, &mut loop_body)? - .0; + let meta = start_meta.union(&end_meta); + + let (expr, expr_meta) = + ctx.lower_expect(stmt, parser, root, false, &mut loop_body)?; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, expr, }, + expr_meta, &mut loop_body, ); ctx.emit_flush(&mut loop_body); ctx.emit_start(); - loop_body.push(Statement::If { - condition, - accept: vec![Statement::Break], - reject: Block::new(), - }); + loop_body.push( + Statement::If { + condition, + accept: new_break(), + reject: Block::new(), + }, + crate::Span::Unknown, + ); - body.push(Statement::Loop { - body: loop_body, - continuing: Block::new(), - }) + body.push( + Statement::Loop { + body: loop_body, + continuing: Block::new(), + }, + meta.as_span(), + ); + meta } TokenValue::For => { - self.bump(parser)?; + let meta = self.bump(parser)?.meta; ctx.push_scope(); self.expect(parser, TokenValue::LeftParen)?; @@ -347,54 +391,60 @@ impl<'source> ParsingContext<'source> { let (mut block, mut continuing) = (Block::new(), Block::new()); if self.bump_if(parser, TokenValue::Semicolon).is_none() { - let expr = if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { - let qualifiers = self.parse_type_qualifiers(parser)?; - let (ty, meta) = self.parse_type_non_void(parser)?; - let name = self.expect_ident(parser)?.0; + let (expr, expr_meta) = + if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { + let qualifiers = self.parse_type_qualifiers(parser)?; + let (ty, meta) = self.parse_type_non_void(parser)?; + let name = self.expect_ident(parser)?.0; - self.expect(parser, TokenValue::Assign)?; + self.expect(parser, TokenValue::Assign)?; - let (value, end_meta) = - self.parse_initializer(parser, ty, ctx, &mut block)?; + let (value, end_meta) = + self.parse_initializer(parser, ty, ctx, &mut block)?; + let meta = meta.union(&end_meta); - let decl = VarDeclaration { - qualifiers: &qualifiers, - ty, - name: Some(name), - init: None, - meta: meta.union(&end_meta), + let decl = VarDeclaration { + qualifiers: &qualifiers, + ty, + name: Some(name), + init: None, + meta, + }; + + let pointer = parser.add_local_var(ctx, &mut block, decl)?; + + ctx.emit_flush(&mut block); + ctx.emit_start(); + + block.push(Statement::Store { pointer, value }, meta.as_span()); + + (value, end_meta) + } else { + let mut stmt = ctx.stmt_ctx(); + let root = self.parse_expression(parser, ctx, &mut stmt, &mut block)?; + ctx.lower_expect(stmt, parser, root, false, &mut block)? }; - let pointer = parser.add_local_var(ctx, &mut block, decl)?; - - ctx.emit_flush(&mut block); - ctx.emit_start(); - - block.push(Statement::Store { pointer, value }); - - value - } else { - let mut stmt = ctx.stmt_ctx(); - let root = self.parse_expression(parser, ctx, &mut stmt, &mut block)?; - ctx.lower_expect(stmt, parser, root, false, &mut block)?.0 - }; - let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, expr, }, + expr_meta, &mut block, ); ctx.emit_flush(&mut block); ctx.emit_start(); - block.push(Statement::If { - condition, - accept: vec![Statement::Break], - reject: Block::new(), - }); + block.push( + Statement::If { + condition, + accept: new_break(), + reject: Block::new(), + }, + crate::Span::Unknown, + ); self.expect(parser, TokenValue::Semicolon)?; } @@ -409,27 +459,36 @@ impl<'source> ParsingContext<'source> { } } - self.expect(parser, TokenValue::RightParen)?; + let mut meta = meta.union(&self.expect(parser, TokenValue::RightParen)?.meta); - self.parse_statement(parser, ctx, &mut block)?; + if let Some(stmt_meta) = self.parse_statement(parser, ctx, &mut block)? { + meta = meta.union(&stmt_meta); + } - body.push(Statement::Loop { - body: block, - continuing, - }); + body.push( + Statement::Loop { + body: block, + continuing, + }, + meta.as_span(), + ); ctx.remove_current_scope(); + + meta } TokenValue::LeftBrace => { - self.bump(parser)?; + let meta = self.bump(parser)?.meta; let mut block = Block::new(); ctx.push_scope(); - self.parse_compound_statement(parser, ctx, &mut block)?; + let meta = self.parse_compound_statement(meta, parser, ctx, &mut block)?; ctx.remove_current_scope(); - body.push(Statement::Block(block)); + body.push(Statement::Block(block), meta.as_span()); + + meta } TokenValue::Plus | TokenValue::Dash @@ -444,32 +503,37 @@ impl<'source> ParsingContext<'source> { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; ctx.lower(stmt, parser, expr, false, body)?; - self.expect(parser, TokenValue::Semicolon)?; + self.expect(parser, TokenValue::Semicolon)?.meta } - TokenValue::Semicolon => { - self.bump(parser)?; - } - _ => {} - } + TokenValue::Semicolon => self.bump(parser)?.meta, + _ => meta, + }; - Ok(()) + Ok(Some(meta.union(&meta_rest))) } pub fn parse_compound_statement( &mut self, + mut meta: SourceMetadata, parser: &mut Parser, ctx: &mut Context, body: &mut Block, - ) -> Result<()> { + ) -> Result { loop { - if self.bump_if(parser, TokenValue::RightBrace).is_some() { + if let Some(Token { + meta: brace_meta, .. + }) = self.bump_if(parser, TokenValue::RightBrace) + { + meta = meta.union(&brace_meta); break; } - self.parse_statement(parser, ctx, body)?; + if let Some(stmt_meta) = self.parse_statement(parser, ctx, body)? { + meta = meta.union(&stmt_meta); + } } - Ok(()) + Ok(meta) } pub fn parse_function_args( @@ -490,12 +554,12 @@ impl<'source> ParsingContext<'source> { continue; } TokenValue::Identifier(_) => { - let name = self.expect_ident(parser)?.0; + let name_meta = self.expect_ident(parser)?; - let size = self.parse_array_specifier(parser)?; - let ty = parser.maybe_array(ty, size); + let array_specifier = self.parse_array_specifier(parser)?; + let ty = parser.maybe_array(ty, name_meta.1, array_specifier); - context.add_function_arg(parser, body, Some(name), ty, qualifier); + context.add_function_arg(parser, body, Some(name_meta), ty, qualifier); if self.bump_if(parser, TokenValue::Comma).is_some() { continue; diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index a575f5cb8..0d1e0441f 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -3,7 +3,7 @@ use crate::{ ast::{StorageQualifier, StructLayout, TypeQualifier}, error::ExpectedToken, parser::ParsingContext, - token::{SourceMetadata, TokenValue}, + token::{SourceMetadata, Token, TokenValue}, Error, ErrorKind, Parser, Result, }, ArraySize, Handle, StorageClass, Type, TypeInner, @@ -12,15 +12,20 @@ use crate::{ impl<'source> ParsingContext<'source> { /// Parses an optional array_specifier returning `Ok(None)` if there is no /// LeftBracket - pub fn parse_array_specifier(&mut self, parser: &mut Parser) -> Result> { - if self.bump_if(parser, TokenValue::LeftBracket).is_some() { - if self.bump_if(parser, TokenValue::RightBracket).is_some() { - return Ok(Some(ArraySize::Dynamic)); + pub fn parse_array_specifier( + &mut self, + parser: &mut Parser, + ) -> Result> { + if let Some(Token { meta, .. }) = self.bump_if(parser, TokenValue::LeftBracket) { + if let Some(Token { meta: end_meta, .. }) = + self.bump_if(parser, TokenValue::RightBracket) + { + return Ok(Some((ArraySize::Dynamic, meta.union(&end_meta)))); } let (constant, _) = self.parse_constant_expression(parser)?; - self.expect(parser, TokenValue::RightBracket)?; - Ok(Some(ArraySize::Constant(constant))) + let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; + Ok(Some((ArraySize::Constant(constant), meta.union(&end_meta)))) } else { Ok(None) } @@ -33,23 +38,32 @@ impl<'source> ParsingContext<'source> { let token = self.bump(parser)?; let handle = match token.value { TokenValue::Void => None, - TokenValue::TypeName(ty) => Some(parser.module.types.fetch_or_append(ty)), + TokenValue::TypeName(ty) => Some( + parser + .module + .types + .fetch_or_append(ty, token.meta.as_span()), + ), TokenValue::Struct => { + let meta = token.meta; let ty_name = self.expect_ident(parser)?.0; self.expect(parser, TokenValue::LeftBrace)?; let mut members = Vec::new(); let span = self.parse_struct_declaration_list(parser, &mut members, StructLayout::Std140)?; - self.expect(parser, TokenValue::RightBrace)?; + let end_meta = self.expect(parser, TokenValue::RightBrace)?.meta; - let ty = parser.module.types.append(Type { - name: Some(ty_name.clone()), - inner: TypeInner::Struct { - top_level: false, - members, - span, + let ty = parser.module.types.append( + Type { + name: Some(ty_name.clone()), + inner: TypeInner::Struct { + top_level: false, + members, + span, + }, }, - }); + meta.union(&end_meta).as_span(), + ); parser.lookup_type.insert(ty_name, ty); Some(ty) } @@ -77,8 +91,11 @@ impl<'source> ParsingContext<'source> { } }; - let size = self.parse_array_specifier(parser)?; - Ok((handle.map(|ty| parser.maybe_array(ty, size)), token.meta)) + let token_meta = token.meta; + let array_specifier = self.parse_array_specifier(parser)?; + let handle = handle.map(|ty| parser.maybe_array(ty, token_meta, array_specifier)); + let meta = array_specifier.map_or(token_meta, |(_, meta)| meta.union(&token_meta)); + Ok((handle, meta)) } pub fn parse_type_non_void( diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index cd35391af..0aa6a6d70 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -56,6 +56,10 @@ impl SourceMetadata { } } + pub fn as_span(&self) -> crate::Span { + crate::Span::ByteRange(self.start..self.end) + } + pub(crate) fn none() -> Self { SourceMetadata::default() } diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 7c8200caf..fe591f65b 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -257,18 +257,23 @@ impl Parser { pub(crate) fn maybe_array( &mut self, base: Handle, - size: Option, + meta: SourceMetadata, + array_specifier: Option<(ArraySize, SourceMetadata)>, ) -> Handle { - size.map(|size| { - self.module.types.fetch_or_append(Type { - name: None, - inner: TypeInner::Array { - base, - size, - stride: self.module.types[base].inner.span(&self.module.constants), - }, + array_specifier + .map(|(size, size_meta)| { + self.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Array { + base, + size, + stride: self.module.types[base].inner.span(&self.module.constants), + }, + }, + meta.union(&size_meta).as_span(), + ) }) - }) - .unwrap_or(base) + .unwrap_or(base) } } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index aa1a60b85..65d586f89 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -42,6 +42,7 @@ impl Parser { ctx: &mut Context, body: &mut Block, name: &str, + meta: SourceMetadata, ) -> Option { if let Some(local_var) = ctx.lookup_local_var(name) { return Some(local_var); @@ -54,15 +55,18 @@ impl Parser { let ty = self .module .types - .fetch_or_append(Type { name: None, inner }); + .fetch_or_append(Type { name: None, inner }, meta.as_span()); - let handle = self.module.global_variables.append(GlobalVariable { - name: Some(name.into()), - class: StorageClass::Private, - binding: None, - ty, - init: None, - }); + let handle = self.module.global_variables.append( + GlobalVariable { + name: Some(name.into()), + class: StorageClass::Private, + binding: None, + ty, + init: None, + }, + meta.as_span(), + ); let idx = self.entry_args.len(); self.entry_args.push(EntryArg { @@ -81,7 +85,7 @@ impl Parser { }, )); - let expr = ctx.add_expression(Expression::GlobalVariable(handle), body); + let expr = ctx.add_expression(Expression::GlobalVariable(handle), meta, body); ctx.lookup_global_var_exps.insert( name.into(), VariableReference { @@ -201,6 +205,7 @@ impl Parser { base: expression, index: index as u32, }, + meta, body, )) } @@ -273,6 +278,7 @@ impl Parser { base: expression, index: pattern[0].index(), }, + meta, body, )); } @@ -299,6 +305,7 @@ impl Parser { Expression::Load { pointer: expression, }, + meta, body, ); } @@ -309,6 +316,7 @@ impl Parser { vector: expression, pattern, }, + meta, body, )) } else { @@ -483,13 +491,16 @@ impl Parser { }) }); - let handle = self.module.global_variables.append(GlobalVariable { - name: name.clone(), - class: StorageClass::Private, - binding: None, - ty, - init, - }); + let handle = self.module.global_variables.append( + GlobalVariable { + name: name.clone(), + class: StorageClass::Private, + binding: None, + ty, + init, + }, + meta.as_span(), + ); let idx = self.entry_args.len(); self.entry_args.push(EntryArg { @@ -548,16 +559,19 @@ impl Parser { } }; - let handle = self.module.global_variables.append(GlobalVariable { - name: name.clone(), - class, - binding: binding.map(|binding| ResourceBinding { - group: set.unwrap_or(0), - binding, - }), - ty, - init, - }); + let handle = self.module.global_variables.append( + GlobalVariable { + name: name.clone(), + class, + binding: binding.map(|binding| ResourceBinding { + group: set.unwrap_or(0), + binding, + }), + ty, + init, + }, + meta.as_span(), + ); if let Some(name) = name { let lookup = GlobalLookup { @@ -628,12 +642,15 @@ impl Parser { } } - let handle = ctx.locals.append(LocalVariable { - name: name.clone(), - ty, - init, - }); - let expr = ctx.add_expression(Expression::LocalVariable(handle), body); + let handle = ctx.locals.append( + LocalVariable { + name: name.clone(), + ty, + init, + }, + meta.as_span(), + ); + let expr = ctx.add_expression(Expression::LocalVariable(handle), meta, body); if let Some(name) = name { ctx.add_local_var(name, expr, mutable); diff --git a/src/front/mod.rs b/src/front/mod.rs index 4bd1294ce..c9d71d298 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -29,10 +29,20 @@ impl Emitter { self.start_len = Some(arena.len()); } #[must_use] - fn finish(&mut self, arena: &Arena) -> Option { + fn finish( + &mut self, + arena: &Arena, + ) -> Option<(crate::Statement, crate::span::Span)> { let start_len = self.start_len.take().unwrap(); if start_len != arena.len() { - Some(crate::Statement::Emit(arena.range_from(start_len))) + #[allow(unused_mut)] + let mut span = crate::span::Span::Unknown; + let range = arena.range_from(start_len); + #[cfg(feature = "span")] + for handle in range.clone() { + span.subsume(arena.get_span(handle)) + } + Some((crate::Statement::Emit(range), span)) } else { None } diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs index c7c8b82af..4362c5d23 100644 --- a/src/front/spv/flow.rs +++ b/src/front/spv/flow.rs @@ -527,10 +527,13 @@ impl FlowGraph { let variable = &lookup_expression[&variable_id]; let parent_node = &mut self.flow[self.block_to_node[&parent_id]]; - parent_node.block.push(crate::Statement::Store { - pointer: phi.pointer, - value: variable.handle, - }); + parent_node.block.push( + crate::Statement::Store { + pointer: phi.pointer, + value: variable.handle, + }, + crate::Span::Unknown, + ); } } self.flow[node_index].phis = phis; @@ -548,7 +551,7 @@ impl FlowGraph { stop_nodes: std::collections::HashSet, ) -> Result { if stop_nodes.contains(&node_index) { - return Ok(vec![]); + return Ok(crate::Block::new()); } if self.flow[node_index].visited { @@ -647,21 +650,25 @@ impl FlowGraph { || edge == ControlFlowEdgeType::LoopBreak { // Do not add break if already has one as the last statement - if let Some(&crate::Statement::Break) = statements.last() { + if let Some(&crate::Statement::Break) = statements.as_ref().last() { } else { - statements.push(crate::Statement::Break); + statements.push(crate::Statement::Break, crate::Span::Unknown); } } } } - result.push(crate::Statement::If { - condition, - accept, - reject, - }); + result.push( + crate::Statement::If { + condition, + accept, + reject, + }, + crate::Span::Unknown, + ); - result.extend(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); + result + .extend_block(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); Ok(result) } @@ -703,16 +710,20 @@ impl FlowGraph { }); } - result.push(crate::Statement::Switch { - selector, - cases, - default: self.convert_to_naga_traverse( - self.block_to_node[&default_id], - stop_nodes_cases, - )?, - }); + result.push( + crate::Statement::Switch { + selector, + cases, + default: self.convert_to_naga_traverse( + self.block_to_node[&default_id], + stop_nodes_cases, + )?, + }, + crate::Span::Unknown, + ); - result.extend(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); + result + .extend_block(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); Ok(result) } @@ -745,25 +756,31 @@ impl FlowGraph { let true_node_index = self.block_to_node[&true_id]; let false_node_index = self.block_to_node[&false_id]; - body.push(crate::Statement::If { - condition, - accept: if true_node_index == merge_node_index { - vec![crate::Statement::Break] - } else { - self.convert_to_naga_traverse( - true_node_index, - stop_nodes_merge.clone(), - )? + body.push( + crate::Statement::If { + condition, + accept: if true_node_index == merge_node_index { + crate::Block::from_vec(vec![crate::Statement::Break]) + } else { + self.convert_to_naga_traverse( + true_node_index, + stop_nodes_merge.clone(), + )? + }, + reject: if false_node_index == merge_node_index { + crate::Block::from_vec(vec![crate::Statement::Break]) + } else { + self.convert_to_naga_traverse( + false_node_index, + stop_nodes_merge, + )? + }, }, - reject: if false_node_index == merge_node_index { - vec![crate::Statement::Break] - } else { - self.convert_to_naga_traverse(false_node_index, stop_nodes_merge)? - }, - }); + crate::Span::Unknown, + ); } Terminator::Branch { target_id } => { - body.extend(self.convert_to_naga_traverse( + body.extend_block(self.convert_to_naga_traverse( self.block_to_node[&target_id], stop_nodes_merge, )?) @@ -771,8 +788,9 @@ impl FlowGraph { _ => return Err(Error::InvalidTerminator), }; - let mut result = vec![crate::Statement::Loop { body, continuing }]; - result.extend(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); + let mut result = + crate::Block::from_vec(vec![crate::Statement::Loop { body, continuing }]); + result.extend_block(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); Ok(result) } @@ -795,27 +813,35 @@ impl FlowGraph { if true_edge == ControlFlowEdgeType::LoopBreak || true_edge == ControlFlowEdgeType::IfBreak { - result.push(crate::Statement::If { - condition, - accept: if true_edge == ControlFlowEdgeType::LoopBreak { - vec![crate::Statement::Break] - } else { - vec![] + result.push( + crate::Statement::If { + condition, + accept: if true_edge == ControlFlowEdgeType::LoopBreak { + crate::Block::from_vec(vec![crate::Statement::Break]) + } else { + crate::Block::new() + }, + reject: self + .convert_to_naga_traverse(false_node_id, stop_nodes)?, }, - reject: self.convert_to_naga_traverse(false_node_id, stop_nodes)?, - }); + crate::Span::Unknown, + ); } else if false_edge == ControlFlowEdgeType::LoopBreak || false_edge == ControlFlowEdgeType::IfBreak { - result.push(crate::Statement::If { - condition, - accept: self.convert_to_naga_traverse(true_node_id, stop_nodes)?, - reject: if false_edge == ControlFlowEdgeType::LoopBreak { - vec![crate::Statement::Break] - } else { - vec![] + result.push( + crate::Statement::If { + condition, + accept: self + .convert_to_naga_traverse(true_node_id, stop_nodes)?, + reject: if false_edge == ControlFlowEdgeType::LoopBreak { + crate::Block::from_vec(vec![crate::Statement::Break]) + } else { + crate::Block::new() + }, }, - }); + crate::Span::Unknown, + ); } else { return Err(Error::InvalidEdgeClassification); } @@ -827,7 +853,7 @@ impl FlowGraph { self.flow[self.flow.find_edge(node_index, target_index).unwrap()]; if edge == ControlFlowEdgeType::LoopBreak { - result.push(crate::Statement::Break); + result.push(crate::Statement::Break, crate::Span::Unknown); } } _ => return Err(Error::InvalidTerminator), @@ -839,7 +865,7 @@ impl FlowGraph { } Some(ControlFlowNodeType::Kill) => { let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); - result.push(crate::Statement::Kill); + result.push(crate::Statement::Kill, crate::Span::Unknown); Ok(result) } Some(ControlFlowNodeType::Return) => { @@ -848,13 +874,13 @@ impl FlowGraph { _ => return Err(Error::InvalidTerminator), }; let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); - result.push(crate::Statement::Return { value }); + result.push(crate::Statement::Return { value }, crate::Span::Unknown); Ok(result) } Some(ControlFlowNodeType::Merge) | None => match self.flow[node_index].terminator { Terminator::Branch { target_id } => { - let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); - result.extend( + let mut result = std::mem::take(&mut self.flow[node_index].block); + result.extend_block( self.convert_to_naga_traverse(self.block_to_node[&target_id], stop_nodes)?, ); Ok(result) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 401c14a60..81a4a5f88 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -1,6 +1,7 @@ use crate::arena::{Arena, Handle}; use super::{flow::*, Error, FunctionInfo, Instruction, LookupExpression, LookupHelper as _}; +use crate::front::Emitter; pub type BlockId = u32; @@ -56,13 +57,16 @@ impl> super::Parser { from: spirv::Word, to: spirv::Word, ) -> Handle { - let dummy_handle = self.dummy_functions.append(crate::Function::default()); + let dummy_handle = self + .dummy_functions + .append(crate::Function::default(), Default::default()); self.deferred_function_calls.push(to); self.function_call_graph.add_edge(from, to, ()); dummy_handle } pub(super) fn parse_function(&mut self, module: &mut crate::Module) -> Result<(), Error> { + let start = self.data_offset; self.lookup_expression.clear(); self.lookup_load_override.clear(); self.lookup_sampled_image.clear(); @@ -90,14 +94,16 @@ impl> super::Parser { }) }, local_variables: Arena::new(), - expressions: self.make_expression_storage(), + expressions: self + .make_expression_storage(&module.global_variables, &module.constants), named_expressions: crate::FastHashMap::default(), - body: Vec::new(), + body: crate::Block::new(), } }; // read parameters for i in 0..fun.arguments.capacity() { + let start = self.data_offset; match self.next_inst()? { Instruction { op: spirv::Op::FunctionParameter, @@ -105,9 +111,10 @@ impl> super::Parser { } => { let type_id = self.next()?; let id = self.next()?; - let handle = fun - .expressions - .append(crate::Expression::FunctionArgument(i as u32)); + let handle = fun.expressions.append( + crate::Expression::FunctionArgument(i as u32), + self.span_from(start), + ); self.lookup_expression .insert(id, LookupExpression { handle, type_id }); //Note: we redo the lookup in order to work around `self` borrowing @@ -192,7 +199,7 @@ impl> super::Parser { fun.body = flow_graph.convert_to_naga()?; // done - let fun_handle = module.functions.append(fun); + let fun_handle = module.functions.append(fun, self.span_from_with_op(start)); self.lookup_function.insert(fun_id, fun_handle); self.function_info.push(function_info); if let Some(ep) = self.lookup_entry_point.remove(&fun_id) { @@ -204,41 +211,46 @@ impl> super::Parser { local_variables: Arena::new(), expressions: Arena::new(), named_expressions: crate::FastHashMap::default(), - body: Vec::new(), + body: crate::Block::new(), }; // 1. copy the inputs from arguments to privates for &v_id in ep.variable_ids.iter() { let lvar = self.lookup_variable.lookup(v_id)?; if let super::Variable::Input(ref arg) = lvar.inner { - let arg_expr = - function - .expressions - .append(crate::Expression::FunctionArgument( - function.arguments.len() as u32, - )); + let span = module.global_variables.get_span(lvar.handle).clone(); + let arg_expr = function.expressions.append( + crate::Expression::FunctionArgument(function.arguments.len() as u32), + span.clone(), + ); let load_expr = if arg.ty == module.global_variables[lvar.handle].ty { arg_expr } else { // The only case where the type is different is if we need to treat // unsigned integer as signed. - let old_len = function.expressions.len(); - let handle = function.expressions.append(crate::Expression::As { - expr: arg_expr, - kind: crate::ScalarKind::Sint, - convert: Some(4), - }); - function.body.push(crate::Statement::Emit( - function.expressions.range_from(old_len), - )); + let mut emitter = Emitter::default(); + emitter.start(&function.expressions); + let handle = function.expressions.append( + crate::Expression::As { + expr: arg_expr, + kind: crate::ScalarKind::Sint, + convert: Some(4), + }, + span.clone(), + ); + function.body.extend(emitter.finish(&function.expressions)); handle }; - function.body.push(crate::Statement::Store { - pointer: function - .expressions - .append(crate::Expression::GlobalVariable(lvar.handle)), - value: load_expr, - }); + function.body.push( + crate::Statement::Store { + pointer: function.expressions.append( + crate::Expression::GlobalVariable(lvar.handle), + span.clone(), + ), + value: load_expr, + }, + span, + ); let mut arg = arg.clone(); if ep.stage == crate::ShaderStage::Fragment { @@ -257,11 +269,14 @@ impl> super::Parser { // 2. call the wrapped function let fake_id = !(module.entry_points.len() as u32); // doesn't matter, as long as it's not a collision let dummy_handle = self.add_call(fake_id, fun_id); - function.body.push(crate::Statement::Call { - function: dummy_handle, - arguments: Vec::new(), - result: None, - }); + function.body.push( + crate::Statement::Call { + function: dummy_handle, + arguments: Vec::new(), + result: None, + }, + crate::Span::Unknown, + ); // 3. copy the outputs from privates to the result let mut members = Vec::new(); @@ -269,9 +284,10 @@ impl> super::Parser { for &v_id in ep.variable_ids.iter() { let lvar = self.lookup_variable.lookup(v_id)?; if let super::Variable::Output(ref result) = lvar.inner { + let span = module.global_variables.get_span(lvar.handle).clone(); let expr_handle = function .expressions - .append(crate::Expression::GlobalVariable(lvar.handle)); + .append(crate::Expression::GlobalVariable(lvar.handle), span.clone()); match module.types[result.ty].inner { crate::TypeInner::Struct { members: ref sub_members, @@ -288,6 +304,7 @@ impl> super::Parser { base: expr_handle, index: index as u32, }, + span.clone(), )); } } @@ -311,72 +328,94 @@ impl> super::Parser { Some(crate::Binding::BuiltIn(crate::BuiltIn::Position)) if self.options.adjust_coordinate_space => { - let old_len = function.expressions.len(); + let mut emitter = Emitter::default(); + emitter.start(&function.expressions); let global_expr = components[member_index]; - let access_expr = - function.expressions.append(crate::Expression::AccessIndex { + let span = function.expressions.get_span(global_expr).clone(); + let access_expr = function.expressions.append( + crate::Expression::AccessIndex { base: global_expr, index: 1, - }); - let load_expr = function.expressions.append(crate::Expression::Load { - pointer: access_expr, - }); - let neg_expr = function.expressions.append(crate::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr: load_expr, - }); - function.body.push(crate::Statement::Emit( - function.expressions.range_from(old_len), - )); - function.body.push(crate::Statement::Store { - pointer: access_expr, - value: neg_expr, - }); + }, + span.clone(), + ); + let load_expr = function.expressions.append( + crate::Expression::Load { + pointer: access_expr, + }, + span.clone(), + ); + let neg_expr = function.expressions.append( + crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr: load_expr, + }, + span.clone(), + ); + function.body.extend(emitter.finish(&function.expressions)); + function.body.push( + crate::Statement::Store { + pointer: access_expr, + value: neg_expr, + }, + span, + ); } _ => {} } } - let old_len = function.expressions.len(); + let mut emitter = Emitter::default(); + emitter.start(&function.expressions); for component in components.iter_mut() { let load_expr = crate::Expression::Load { pointer: *component, }; - *component = function.expressions.append(load_expr); + let span = function.expressions.get_span(*component).clone(); + *component = function.expressions.append(load_expr, span); } match &members[..] { [] => {} [member] => { - function.body.push(crate::Statement::Emit( - function.expressions.range_from(old_len), - )); - function.body.push(crate::Statement::Return { - value: components.first().cloned(), - }); + function.body.extend(emitter.finish(&function.expressions)); + let span = function.expressions.get_span(components[0]).clone(); + function.body.push( + crate::Statement::Return { + value: components.first().cloned(), + }, + span, + ); function.result = Some(crate::FunctionResult { ty: member.ty, binding: member.binding.clone(), }); } _ => { - let ty = module.types.append(crate::Type { - name: None, - inner: crate::TypeInner::Struct { - top_level: false, - members, - span: 0xFFFF, // shouldn't matter + let span = crate::Span::total_span( + components.iter().map(|h| function.expressions.get_span(*h)), + ); + let ty = module.types.append( + crate::Type { + name: None, + inner: crate::TypeInner::Struct { + top_level: false, + members, + span: 0xFFFF, // shouldn't matter + }, }, - }); + span.clone(), + ); let result_expr = function .expressions - .append(crate::Expression::Compose { ty, components }); - function.body.push(crate::Statement::Emit( - function.expressions.range_from(old_len), - )); - function.body.push(crate::Statement::Return { - value: Some(result_expr), - }); + .append(crate::Expression::Compose { ty, components }, span.clone()); + function.body.extend(emitter.finish(&function.expressions)); + function.body.push( + crate::Statement::Return { + value: Some(result_expr), + }, + span, + ); function.result = Some(crate::FunctionResult { ty, binding: None }); } } diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index d7fe88cc3..72c10c123 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -89,59 +89,85 @@ fn extract_image_coordinates( index: required_size.map_or(1, |size| size as u32), }; + let base_span = expressions.get_span(base).clone(); + match extra_coordinate { ExtraCoordinate::ArrayLayer => { let extracted = match required_size { - None => expressions.append(crate::Expression::AccessIndex { base, index: 0 }), + None => expressions.append( + crate::Expression::AccessIndex { base, index: 0 }, + base_span.clone(), + ), Some(size) => { let mut components = Vec::with_capacity(size as usize); for index in 0..size as u32 { - let comp = - expressions.append(crate::Expression::AccessIndex { base, index }); + let comp = expressions.append( + crate::Expression::AccessIndex { base, index }, + base_span.clone(), + ); components.push(comp); } - expressions.append(crate::Expression::Compose { - ty: required_ty.unwrap(), - components, - }) + expressions.append( + crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }, + base_span.clone(), + ) } }; - let array_index_f32 = expressions.append(extra_expr); - let array_index = expressions.append(crate::Expression::As { - kind: crate::ScalarKind::Sint, - expr: array_index_f32, - convert: Some(4), - }); + let array_index_f32 = expressions.append(extra_expr, base_span.clone()); + let array_index = expressions.append( + crate::Expression::As { + kind: crate::ScalarKind::Sint, + expr: array_index_f32, + convert: Some(4), + }, + base_span, + ); (extracted, Some(array_index)) } ExtraCoordinate::Projection => { - let projection = expressions.append(extra_expr); + let projection = expressions.append(extra_expr, base_span.clone()); let divided = match required_size { None => { - let temp = - expressions.append(crate::Expression::AccessIndex { base, index: 0 }); - expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Divide, - left: temp, - right: projection, - }) + let temp = expressions.append( + crate::Expression::AccessIndex { base, index: 0 }, + base_span.clone(), + ); + expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: temp, + right: projection, + }, + base_span, + ) } Some(size) => { let mut components = Vec::with_capacity(size as usize); for index in 0..size as u32 { - let temp = - expressions.append(crate::Expression::AccessIndex { base, index }); - let comp = expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Divide, - left: temp, - right: projection, - }); + let temp = expressions.append( + crate::Expression::AccessIndex { base, index }, + base_span.clone(), + ); + let comp = expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: temp, + right: projection, + }, + base_span.clone(), + ); components.push(comp); } - expressions.append(crate::Expression::Compose { - ty: required_ty.unwrap(), - components, - }) + expressions.append( + crate::Expression::Compose { + ty: required_ty.unwrap(), + components, + }, + base_span, + ) } }; (divided, None) @@ -157,7 +183,7 @@ fn extract_image_coordinates( pattern: [Sc::X, Sc::Y, Sc::Z, Sc::W], }, }; - (expressions.append(cut_expr), None) + (expressions.append(cut_expr, base_span), None) } } } @@ -176,6 +202,7 @@ pub(super) fn patch_comparison_type( log::debug!("Flipping comparison for {:?}", var); let original_ty = &arena[var.ty]; + let original_ty_span = arena.get_span(var.ty).clone(); let ty_inner = match original_ty.inner { crate::TypeInner::Image { class: crate::ImageClass::Sampled { multi, .. }, @@ -191,10 +218,13 @@ pub(super) fn patch_comparison_type( }; let name = original_ty.name.clone(); - var.ty = arena.append(crate::Type { - name, - inner: ty_inner, - }); + var.ty = arena.append( + crate::Type { + name, + inner: ty_inner, + }, + original_ty_span, + ); true } @@ -295,6 +325,7 @@ impl> super::Parser { arguments: &[FunctionArgument], expressions: &mut Arena, ) -> Result<(), Error> { + let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let image_id = self.next()?; @@ -368,7 +399,7 @@ impl> super::Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, }, ); @@ -386,6 +417,7 @@ impl> super::Parser { expressions: &mut Arena, function_info: &mut FunctionInfo, ) -> Result<(), Error> { + let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let sampled_image_id = self.next()?; @@ -522,7 +554,7 @@ impl> super::Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, }, ); @@ -534,6 +566,7 @@ impl> super::Parser { at_level: bool, expressions: &mut Arena, ) -> Result<(), Error> { + let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let image_id = self.next()?; @@ -555,7 +588,7 @@ impl> super::Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, }, ); @@ -567,6 +600,7 @@ impl> super::Parser { query: crate::ImageQuery, expressions: &mut Arena, ) -> Result<(), Error> { + let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let image_id = self.next()?; @@ -580,7 +614,7 @@ impl> super::Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, }, ); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 438c4f4a1..c214ad8bd 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -378,6 +378,7 @@ struct FunctionInfo { pub struct Parser { data: I, + data_offset: usize, state: ModuleState, layouter: Layouter, temp_bytes: Vec, @@ -417,6 +418,7 @@ impl> Parser { pub fn new(data: I, options: &Options) -> Self { Parser { data, + data_offset: 0, state: ModuleState::Empty, layouter: Layouter::default(), temp_bytes: Vec::new(), @@ -446,8 +448,21 @@ impl> Parser { } } + fn span_from(&self, from: usize) -> crate::Span { + crate::Span::ByteRange(from..self.data_offset) + } + + fn span_from_with_op(&self, from: usize) -> crate::Span { + crate::Span::ByteRange((from - 4)..self.data_offset) + } + fn next(&mut self) -> Result { - self.data.next().ok_or(Error::IncompleteData) + if let Some(res) = self.data.next() { + self.data_offset += 4; + Ok(res) + } else { + Err(Error::IncompleteData) + } } fn next_inst(&mut self) -> Result { @@ -566,6 +581,7 @@ impl> Parser { expressions: &mut Arena, op: crate::UnaryOperator, ) -> Result<(), Error> { + let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let p_id = self.next()?; @@ -579,7 +595,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, }, ); @@ -591,6 +607,7 @@ impl> Parser { expressions: &mut Arena, op: crate::BinaryOperator, ) -> Result<(), Error> { + let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let p1_id = self.next()?; @@ -607,7 +624,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, }, ); @@ -623,10 +640,12 @@ impl> Parser { op: crate::BinaryOperator, types: &Arena, ) -> Result<(), Error> { + let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let p1_id = self.next()?; let p2_id = self.next()?; + let span = self.span_from_with_op(start); let p1_lexp = self.lookup_expression.lookup(p1_id)?; let p2_lexp = self.lookup_expression.lookup(p2_id)?; @@ -638,27 +657,33 @@ impl> Parser { left: if p1_lexp.type_id == result_type_id { p1_lexp.handle } else { - expressions.append(crate::Expression::As { - expr: p1_lexp.handle, - kind, - convert: None, - }) + expressions.append( + crate::Expression::As { + expr: p1_lexp.handle, + kind, + convert: None, + }, + span.clone(), + ) }, right: if p2_lexp.type_id == result_type_id { p2_lexp.handle } else { - expressions.append(crate::Expression::As { - expr: p2_lexp.handle, - kind, - convert: None, - }) + expressions.append( + crate::Expression::As { + expr: p2_lexp.handle, + kind, + convert: None, + }, + span.clone(), + ) }, }; self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -670,19 +695,25 @@ impl> Parser { expressions: &mut Arena, op: crate::BinaryOperator, ) -> Result<(), Error> { + let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let p1_id = self.next()?; let p2_id = self.next()?; + let span = self.span_from_with_op(start); + let p1_lexp = self.lookup_expression.lookup(p1_id)?; let p2_lexp = self.lookup_expression.lookup(p2_id)?; // convert the shift to Uint - let p2_handle = expressions.append(crate::Expression::As { - expr: p2_lexp.handle, - kind: crate::ScalarKind::Uint, - convert: None, - }); + let p2_handle = expressions.append( + crate::Expression::As { + expr: p2_lexp.handle, + kind: crate::ScalarKind::Uint, + convert: None, + }, + span.clone(), + ); let expr = crate::Expression::Binary { op, @@ -692,7 +723,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -704,6 +735,7 @@ impl> Parser { expressions: &mut Arena, axis: crate::DerivativeAxis, ) -> Result<(), Error> { + let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let arg_id = self.next()?; @@ -717,13 +749,14 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, }, ); Ok(()) } + #[allow(clippy::too_many_arguments)] fn insert_composite( &self, root_expr: Handle, @@ -732,11 +765,13 @@ impl> Parser { selections: &[spirv::Word], type_arena: &Arena, expressions: &mut Arena, + span: crate::Span, ) -> Result, Error> { let selection = match selections.first() { Some(&index) => index, None => return Ok(object_expr), }; + let root_span = expressions.get_span(root_expr).clone(); let root_lookup = self.lookup_type.lookup(root_type_id)?; let (count, child_type_id) = match type_arena[root_lookup.handle].inner { crate::TypeInner::Struct { ref members, .. } => { @@ -759,10 +794,17 @@ impl> Parser { let mut components = Vec::with_capacity(count); for index in 0..count as u32 { - let expr = expressions.append(crate::Expression::AccessIndex { - base: root_expr, - index, - }); + let expr = expressions.append( + crate::Expression::AccessIndex { + base: root_expr, + index, + }, + if index == selection { + span.clone() + } else { + root_span.clone() + }, + ); components.push(expr); } components[selection as usize] = self.insert_composite( @@ -772,12 +814,16 @@ impl> Parser { &selections[1..], type_arena, expressions, + span.clone(), )?; - Ok(expressions.append(crate::Expression::Compose { - ty: root_lookup.handle, - components, - })) + Ok(expressions.append( + crate::Expression::Compose { + ty: root_lookup.handle, + components, + }, + span, + )) } #[allow(clippy::too_many_arguments)] @@ -793,14 +839,16 @@ impl> Parser { arguments: &[crate::FunctionArgument], function_info: &mut FunctionInfo, ) -> Result { - let mut block = Vec::new(); + let mut block = crate::Block::new(); let mut phis = Vec::new(); let mut emitter = super::Emitter::default(); emitter.start(expressions); let mut merge = None; let terminator = loop { use spirv::Op; + let start = self.data_offset; let inst = self.next_inst()?; + let span = crate::Span::ByteRange(start..(start + 4 * (inst.wc as usize))); log::debug!("\t\t{:?} [{}]", inst.op, inst.wc); match inst.op { @@ -812,9 +860,15 @@ impl> Parser { } Op::Undef => { inst.expect(3)?; - let _result_type_id = self.next()?; - let _result_id = self.next()?; - //TODO? + let (type_id, id, handle) = + self.parse_null_constant(inst, type_arena, const_arena)?; + self.lookup_expression.insert( + id, + LookupExpression { + handle: expressions.append(crate::Expression::Constant(handle), span), + type_id, + }, + ); } Op::Variable => { inst.expect_at_least(4)?; @@ -840,20 +894,23 @@ impl> Parser { log::debug!("\t\t\tid={} name={}", result_id, name); } let lookup_ty = self.lookup_type.lookup(result_type_id)?; - let var_handle = local_arena.append(crate::LocalVariable { - name, - ty: match type_arena[lookup_ty.handle].inner { - crate::TypeInner::Pointer { base, .. } => base, - _ => lookup_ty.handle, + let var_handle = local_arena.append( + crate::LocalVariable { + name, + ty: match type_arena[lookup_ty.handle].inner { + crate::TypeInner::Pointer { base, .. } => base, + _ => lookup_ty.handle, + }, + init, }, - init, - }); + span.clone(), + ); self.lookup_expression.insert( result_id, LookupExpression { handle: expressions - .append(crate::Expression::LocalVariable(var_handle)), + .append(crate::Expression::LocalVariable(var_handle), span), type_id: result_type_id, }, ); @@ -867,12 +924,16 @@ impl> Parser { let result_id = self.next()?; let name = format!("phi_{}", result_id); - let var_handle = local_arena.append(crate::LocalVariable { - name: Some(name), - ty: self.lookup_type.lookup(result_type_id)?.handle, - init: None, - }); - let pointer = expressions.append(crate::Expression::LocalVariable(var_handle)); + let var_handle = local_arena.append( + crate::LocalVariable { + name: Some(name), + ty: self.lookup_type.lookup(result_type_id)?.handle, + init: None, + }, + self.span_from(start), + ); + let pointer = expressions + .append(crate::Expression::LocalVariable(var_handle), span.clone()); let in_count = (inst.wc - 3) / 2; let mut phi = PhiInstruction { @@ -894,7 +955,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(crate::Expression::Load { pointer }), + handle: expressions.append(crate::Expression::Load { pointer }, span), type_id: result_type_id, }, ); @@ -948,11 +1009,13 @@ impl> Parser { .lookup_member .get(&(type_lookup.handle, index)) .ok_or(Error::InvalidAccessType(acex.type_id))?; - let base_handle = - expressions.append(crate::Expression::AccessIndex { + let base_handle = expressions.append( + crate::Expression::AccessIndex { base: acex.base_handle, index, - }); + }, + span.clone(), + ); AccessExpression { base_handle, type_id: lookup_member.type_id, @@ -963,17 +1026,21 @@ impl> Parser { Some(match type_arena[sub_type_lookup.handle].inner { // load it transposed, to match column major expectations crate::TypeInner::Matrix { .. } => { - let loaded = - expressions.append(crate::Expression::Load { + let loaded = expressions.append( + crate::Expression::Load { pointer: base_handle, - }); - let transposed = - expressions.append(crate::Expression::Math { + }, + span.clone(), + ); + let transposed = expressions.append( + crate::Expression::Math { fun: crate::MathFunction::Transpose, arg: loaded, arg1: None, arg2: None, - }); + }, + span.clone(), + ); LookupLoadOverride::Loaded(transposed) } _ => LookupLoadOverride::Pending, @@ -990,11 +1057,13 @@ impl> Parser { let index = index_maybe.ok_or_else(|| { Error::InvalidAccess(index_expr_data.clone()) })?; - let sub_handle = - expressions.append(crate::Expression::AccessIndex { + let sub_handle = expressions.append( + crate::Expression::AccessIndex { base: load_expr, index, - }); + }, + span.clone(), + ); Some(LookupLoadOverride::Loaded(sub_handle)) } _ => None, @@ -1010,7 +1079,7 @@ impl> Parser { }, }; AccessExpression { - base_handle: expressions.append(sub_expr), + base_handle: expressions.append(sub_expr, span.clone()), type_id: type_lookup .base_id .ok_or(Error::InvalidAccessType(acex.type_id))?, @@ -1019,10 +1088,13 @@ impl> Parser { } // This must be a vector or an array. _ => { - let base_handle = expressions.append(crate::Expression::Access { - base: acex.base_handle, - index: index_expr.handle, - }); + let base_handle = expressions.append( + crate::Expression::Access { + base: acex.base_handle, + index: index_expr.handle, + }, + span.clone(), + ); let load_override = match acex.load_override { // If there is a load override in place, then we always end up // with a side-loaded value here. @@ -1031,23 +1103,31 @@ impl> Parser { // We must be indexing into the array of row-major matrices. // Let's load the result of indexing and transpose it. LookupLoadOverride::Pending => { - let loaded = - expressions.append(crate::Expression::Load { + let loaded = expressions.append( + crate::Expression::Load { pointer: base_handle, - }); - expressions.append(crate::Expression::Math { - fun: crate::MathFunction::Transpose, - arg: loaded, - arg1: None, - arg2: None, - }) + }, + span.clone(), + ); + expressions.append( + crate::Expression::Math { + fun: crate::MathFunction::Transpose, + arg: loaded, + arg1: None, + arg2: None, + }, + span.clone(), + ) } // We are indexing inside a row-major matrix. LookupLoadOverride::Loaded(load_expr) => expressions - .append(crate::Expression::Access { - base: load_expr, - index: index_expr.handle, - }), + .append( + crate::Expression::Access { + base: load_expr, + index: index_expr.handle, + }, + span.clone(), + ), }; Some(LookupLoadOverride::Loaded(sub_expr)) } @@ -1090,25 +1170,37 @@ impl> Parser { _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), }; - let mut handle = expressions.append(crate::Expression::Access { - base: root_lexp.handle, - index: self.index_constant_expressions[0], - }); - for &index_expr in self.index_constant_expressions[1..num_components].iter() { - let access_expr = expressions.append(crate::Expression::Access { + let mut handle = expressions.append( + crate::Expression::Access { base: root_lexp.handle, - index: index_expr, - }); - let cond = expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Equal, - left: index_expr, - right: index_lexp.handle, - }); - handle = expressions.append(crate::Expression::Select { - condition: cond, - accept: access_expr, - reject: handle, - }); + index: self.index_constant_expressions[0], + }, + span.clone(), + ); + for &index_expr in self.index_constant_expressions[1..num_components].iter() { + let access_expr = expressions.append( + crate::Expression::Access { + base: root_lexp.handle, + index: index_expr, + }, + span.clone(), + ); + let cond = expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Equal, + left: index_expr, + right: index_lexp.handle, + }, + span.clone(), + ); + handle = expressions.append( + crate::Expression::Select { + condition: cond, + accept: access_expr, + reject: handle, + }, + span.clone(), + ); } self.lookup_expression.insert( @@ -1139,26 +1231,38 @@ impl> Parser { }; let mut components = Vec::with_capacity(num_components); for &index_expr in self.index_constant_expressions[..num_components].iter() { - let access_expr = expressions.append(crate::Expression::Access { - base: root_lexp.handle, - index: index_expr, - }); - let cond = expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Equal, - left: index_expr, - right: index_lexp.handle, - }); - let handle = expressions.append(crate::Expression::Select { - condition: cond, - accept: object_lexp.handle, - reject: access_expr, - }); + let access_expr = expressions.append( + crate::Expression::Access { + base: root_lexp.handle, + index: index_expr, + }, + span.clone(), + ); + let cond = expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Equal, + left: index_expr, + right: index_lexp.handle, + }, + span.clone(), + ); + let handle = expressions.append( + crate::Expression::Select { + condition: cond, + accept: object_lexp.handle, + reject: access_expr, + }, + span.clone(), + ); components.push(handle); } - let handle = expressions.append(crate::Expression::Compose { - ty: root_type_lookup.handle, - components, - }); + let handle = expressions.append( + crate::Expression::Compose { + ty: root_type_lookup.handle, + components, + }, + span.clone(), + ); self.lookup_expression.insert( id, @@ -1198,10 +1302,13 @@ impl> Parser { } }; lexp = LookupExpression { - handle: expressions.append(crate::Expression::AccessIndex { - base: lexp.handle, - index, - }), + handle: expressions.append( + crate::Expression::AccessIndex { + base: lexp.handle, + index, + }, + span.clone(), + ), type_id, }; } @@ -1235,6 +1342,7 @@ impl> Parser { &selections, type_arena, expressions, + span, )?; self.lookup_expression.insert( @@ -1272,7 +1380,7 @@ impl> Parser { self.lookup_expression.insert( id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -1297,9 +1405,12 @@ impl> Parser { _ => match self.lookup_load_override.get(&pointer_id) { Some(&LookupLoadOverride::Loaded(handle)) => handle, //Note: we aren't handling `LookupLoadOverride::Pending` properly here - _ => expressions.append(crate::Expression::Load { - pointer: base_lexp.handle, - }), + _ => expressions.append( + crate::Expression::Load { + pointer: base_lexp.handle, + }, + span, + ), }, }; @@ -1323,10 +1434,13 @@ impl> Parser { } let base_expr = self.lookup_expression.lookup(pointer_id)?; let value_expr = self.lookup_expression.lookup(value_id)?; - block.push(crate::Statement::Store { - pointer: base_expr.handle, - value: value_expr.handle, - }); + block.push( + crate::Statement::Store { + pointer: base_expr.handle, + value: value_expr.handle, + }, + span, + ); emitter.start(expressions); } // Arithmetic Instructions +, -, *, /, % @@ -1394,7 +1508,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -1417,7 +1531,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -1440,7 +1554,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -1495,7 +1609,7 @@ impl> Parser { arguments, expressions, )?; - block.push(stmt); + block.push(stmt, span); emitter.start(expressions); } Op::ImageFetch | Op::ImageRead => { @@ -1603,7 +1717,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -1681,7 +1795,7 @@ impl> Parser { } else { return Err(Error::InvalidAccessIndex(index)); }; - components.push(expressions.append(expr)); + components.push(expressions.append(expr, span.clone())); } crate::Expression::Compose { ty: self.lookup_type.lookup(result_type_id)?.handle, @@ -1692,7 +1806,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -1705,7 +1819,7 @@ impl> Parser { | Op::FConvert | Op::UConvert | Op::SConvert => { - inst.expect_at_least(4)?; + inst.expect(4)?; let result_type_id = self.next()?; let result_id = self.next()?; let value_id = self.next()?; @@ -1731,7 +1845,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -1756,8 +1870,8 @@ impl> Parser { let result = if self.lookup_void_type == Some(result_type_id) { None } else { - let expr_handle = - expressions.append(crate::Expression::CallResult(function)); + let expr_handle = expressions + .append(crate::Expression::CallResult(function), span.clone()); self.lookup_expression.insert( result_id, LookupExpression { @@ -1767,11 +1881,14 @@ impl> Parser { ); Some(expr_handle) }; - block.push(crate::Statement::Call { - function, - arguments, - result, - }); + block.push( + crate::Statement::Call { + function, + arguments, + result, + }, + span, + ); emitter.start(expressions); } Op::ExtInst => { @@ -1797,30 +1914,38 @@ impl> Parser { self.lookup_expression.lookup(arg_id)?.handle }; - let constant_handle = const_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Float(match gl_op { - Glo::Radians => std::f64::consts::PI / 180.0, - Glo::Degrees => 180.0 / std::f64::consts::PI, - _ => unreachable!(), - }), + let constant_handle = const_arena.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Float(match gl_op { + Glo::Radians => std::f64::consts::PI / 180.0, + Glo::Degrees => 180.0 / std::f64::consts::PI, + _ => unreachable!(), + }), + }, }, - }); + Default::default(), + ); - let expr_handle = - expressions.append(crate::Expression::Constant(constant_handle)); + let expr_handle = expressions.append( + crate::Expression::Constant(constant_handle), + Default::default(), + ); self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(crate::Expression::Binary { - op: crate::BinaryOperator::Multiply, - left: arg, - right: expr_handle, - }), + handle: expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Multiply, + left: arg, + right: expr_handle, + }, + span, + ), type_id: result_type_id, }, ); @@ -1900,7 +2025,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -1962,7 +2087,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr), + handle: expressions.append(expr, span), type_id: result_type_id, }, ); @@ -2020,11 +2145,14 @@ impl> Parser { width: _, } => { // IR expects a signed integer, so do a bitcast - expressions.append(crate::Expression::As { - kind: crate::ScalarKind::Sint, - expr: selector_lexp.handle, - convert: None, - }) + expressions.append( + crate::Expression::As { + kind: crate::ScalarKind::Sint, + expr: selector_lexp.handle, + convert: None, + }, + span, + ) } crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, @@ -2093,12 +2221,16 @@ impl> Parser { let structure_ptr = self.lookup_expression.lookup(structure_id)?; - let member_ptr = expressions.append(crate::Expression::AccessIndex { - base: structure_ptr.handle, - index: member_index, - }); + let member_ptr = expressions.append( + crate::Expression::AccessIndex { + base: structure_ptr.handle, + index: member_index, + }, + span.clone(), + ); - let length = expressions.append(crate::Expression::ArrayLength(member_ptr)); + let length = + expressions.append(crate::Expression::ArrayLength(member_ptr), span); self.lookup_expression.insert( result_id, @@ -2125,15 +2257,21 @@ impl> Parser { let source = self.lookup_expression.lookup(source_id)?; // This operation is practically the same as loading and then storing, I think. - let value_expr = expressions.append(crate::Expression::Load { - pointer: source.handle, - }); + let value_expr = expressions.append( + crate::Expression::Load { + pointer: source.handle, + }, + span.clone(), + ); block.extend(emitter.finish(expressions)); - block.push(crate::Statement::Store { - pointer: target.handle, - value: value_expr, - }); + block.push( + crate::Statement::Store { + pointer: target.handle, + value: value_expr, + }, + span, + ); emitter.start(expressions); } @@ -2172,7 +2310,7 @@ impl> Parser { .bits() != 0, ); - block.push(crate::Statement::Barrier(flags)); + block.push(crate::Statement::Barrier(flags), span); } else { log::warn!("Unsupported barrier execution scope: {}", exec_scope); } @@ -2195,7 +2333,11 @@ impl> Parser { }) } - fn make_expression_storage(&mut self) -> Arena { + fn make_expression_storage( + &mut self, + globals: &Arena, + constants: &Arena, + ) -> Arena { let mut expressions = Arena::new(); #[allow(clippy::panic)] { @@ -2203,7 +2345,8 @@ impl> Parser { } // register global variables for (&id, var) in self.lookup_variable.iter() { - let handle = expressions.append(crate::Expression::GlobalVariable(var.handle)); + let span = globals.get_span(var.handle).clone(); + let handle = expressions.append(crate::Expression::GlobalVariable(var.handle), span); self.lookup_expression.insert( id, LookupExpression { @@ -2215,12 +2358,14 @@ impl> Parser { // register special constants self.index_constant_expressions.clear(); for &con_handle in self.index_constants.iter() { - let handle = expressions.append(crate::Expression::Constant(con_handle)); + let span = constants.get_span(con_handle).clone(); + let handle = expressions.append(crate::Expression::Constant(con_handle), span); self.index_constant_expressions.push(handle); } // register constants for (&id, con) in self.lookup_constant.iter() { - let handle = expressions.append(crate::Expression::Constant(con.handle)); + let span = constants.get_span(con.handle).clone(); + let handle = expressions.append(crate::Expression::Constant(con.handle), span); self.lookup_expression.insert( id, LookupExpression { @@ -2268,7 +2413,7 @@ impl> Parser { if let [S::Break] = reject[..] { // uplift "accept" into the parent let extracted = mem::take(accept); - statements.splice(i + 1..i + 1, extracted.into_iter()); + statements.splice(i + 1..i + 1, extracted); } else { self.patch_statements(reject, expressions, function)?; self.patch_statements(accept, expressions, function)?; @@ -2282,7 +2427,7 @@ impl> Parser { if cases.is_empty() { // uplift "default" into the parent let extracted = mem::take(default); - statements.splice(i + 1..i + 1, extracted.into_iter()); + statements.splice(i + 1..i + 1, extracted); } else { for case in cases.iter_mut() { self.patch_statements(&mut case.body, expressions, function)?; @@ -2382,14 +2527,17 @@ impl> Parser { // register indexing constants self.index_constants.clear(); for i in 0..4 { - let handle = module.constants.append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Sint(i), + let handle = module.constants.append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Sint(i), + }, }, - }); + Default::default(), + ); self.index_constants.push(handle); } @@ -2439,7 +2587,9 @@ impl> Parser { Op::TypeSampler => self.parse_type_sampler(inst, &mut module), Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), - Op::ConstantNull | Op::Undef => self.parse_null_constant(inst, &mut module), + Op::ConstantNull | Op::Undef => self + .parse_null_constant(inst, &module.types, &mut module.constants) + .map(|_| ()), Op::ConstantTrue => self.parse_bool_constant(inst, true, &mut module), Op::ConstantFalse => self.parse_bool_constant(inst, false, &mut module), Op::Variable => self.parse_global_variable(inst, &mut module), @@ -2457,7 +2607,7 @@ impl> Parser { let mut nodes = petgraph::algo::toposort(&self.function_call_graph, None) .map_err(|cycle| Error::FunctionCallCycle(cycle.node_id()))?; nodes.reverse(); // we need dominated first - let mut functions = mem::take(&mut module.functions).into_inner(); + let mut functions = mem::take(&mut module.functions); for fun_id in nodes { if fun_id > !(functions.len() as u32) { // skip all the fake IDs registered for the entry points @@ -2465,9 +2615,11 @@ impl> Parser { } let handle = self.lookup_function.get_mut(&fun_id).unwrap(); // take out the function from the old array - let fun = mem::take(&mut functions[handle.index()]); + let fun = mem::take(&mut functions[*handle]); // add it to the newly formed arena, and adjust the lookup - *handle = module.functions.append(fun); + *handle = module + .functions + .append(fun, functions.get_span(*handle).clone()); } } // patch all the functions @@ -2734,6 +2886,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(2)?; let id = self.next()?; @@ -2744,10 +2897,13 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - inner, - }), + handle: module.types.append( + crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }, + self.span_from_with_op(start), + ), base_id: None, }, ); @@ -2759,6 +2915,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(4)?; let id = self.next()?; @@ -2775,10 +2932,13 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - inner, - }), + handle: module.types.append( + crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }, + self.span_from_with_op(start), + ), base_id: None, }, ); @@ -2790,6 +2950,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(3)?; let id = self.next()?; @@ -2801,10 +2962,13 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - inner, - }), + handle: module.types.append( + crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }, + self.span_from_with_op(start), + ), base_id: None, }, ); @@ -2816,6 +2980,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(4)?; let id = self.next()?; @@ -2834,10 +2999,13 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - inner, - }), + handle: module.types.append( + crate::Type { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + inner, + }, + self.span_from_with_op(start), + ), base_id: Some(type_id), }, ); @@ -2849,6 +3017,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(4)?; let id = self.next()?; @@ -2869,10 +3038,13 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: decor.and_then(|dec| dec.name), - inner, - }), + handle: module.types.append( + crate::Type { + name: decor.and_then(|dec| dec.name), + inner, + }, + self.span_from_with_op(start), + ), base_id: Some(vector_type_id), }, ); @@ -2900,6 +3072,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(4)?; let id = self.next()?; @@ -2929,13 +3102,16 @@ impl> Parser { base_lookup_ty.clone() } else { LookupType { - handle: module.types.append(crate::Type { - name: decor.and_then(|dec| dec.name), - inner: crate::TypeInner::Pointer { - base: base_lookup_ty.handle, - class, + handle: module.types.append( + crate::Type { + name: decor.and_then(|dec| dec.name), + inner: crate::TypeInner::Pointer { + base: base_lookup_ty.handle, + class, + }, }, - }), + self.span_from_with_op(start), + ), base_id: Some(type_id), } }; @@ -2948,6 +3124,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(4)?; let id = self.next()?; @@ -2968,10 +3145,13 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: decor.name, - inner, - }), + handle: module.types.append( + crate::Type { + name: decor.name, + inner, + }, + self.span_from_with_op(start), + ), base_id: Some(type_id), }, ); @@ -2983,6 +3163,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(3)?; let id = self.next()?; @@ -3001,10 +3182,13 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append(crate::Type { - name: decor.name, - inner, - }), + handle: module.types.append( + crate::Type { + name: decor.name, + inner, + }, + self.span_from_with_op(start), + ), base_id: Some(type_id), }, ); @@ -3016,6 +3200,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(2)?; let id = self.next()?; @@ -3103,10 +3288,13 @@ impl> Parser { members, }; - let ty_handle = module.types.append(crate::Type { - name: parent_decor.and_then(|dec| dec.name), - inner, - }); + let ty_handle = module.types.append( + crate::Type { + name: parent_decor.and_then(|dec| dec.name), + inner, + }, + self.span_from_with_op(start), + ); if block_decor == Some(Block { buffer: true }) { self.lookup_storage_buffer_types @@ -3131,6 +3319,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(9)?; @@ -3147,17 +3336,20 @@ impl> Parser { let decor = self.future_decor.remove(&id).unwrap_or_default(); // ensure there is a type for texture coordinate without extra components - module.types.fetch_or_append(crate::Type { - name: None, - inner: { - let kind = crate::ScalarKind::Float; - let width = 4; - match dim.required_coordinate_size() { - None => crate::TypeInner::Scalar { kind, width }, - Some(size) => crate::TypeInner::Vector { size, kind, width }, - } + module.types.fetch_or_append( + crate::Type { + name: None, + inner: { + let kind = crate::ScalarKind::Float; + let width = 4; + match dim.required_coordinate_size() { + None => crate::TypeInner::Scalar { kind, width }, + Some(size) => crate::TypeInner::Vector { size, kind, width }, + } + }, }, - }); + Default::default(), + ); let base_handle = self.lookup_type.lookup(sample_type_id)?.handle; let kind = module.types[base_handle] @@ -3181,10 +3373,13 @@ impl> Parser { arrayed: is_array, }; - let handle = module.types.append(crate::Type { - name: decor.name, - inner, - }); + let handle = module.types.append( + crate::Type { + name: decor.name, + inner, + }, + self.span_from_with_op(start), + ); self.lookup_type.insert( id, @@ -3216,14 +3411,18 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(2)?; let id = self.next()?; let decor = self.future_decor.remove(&id).unwrap_or_default(); - let handle = module.types.append(crate::Type { - name: decor.name, - inner: crate::TypeInner::Sampler { comparison: false }, - }); + let handle = module.types.append( + crate::Type { + name: decor.name, + inner: crate::TypeInner::Sampler { comparison: false }, + }, + self.span_from_with_op(start), + ); self.lookup_type.insert( id, LookupType { @@ -3239,6 +3438,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(4)?; let type_id = self.next()?; @@ -3308,11 +3508,14 @@ impl> Parser { self.lookup_constant.insert( id, LookupConstant { - handle: module.constants.append(crate::Constant { - specialization: decor.specialization, - name: decor.name, - inner, - }), + handle: module.constants.append( + crate::Constant { + specialization: decor.specialization, + name: decor.name, + inner, + }, + self.span_from_with_op(start), + ), type_id, }, ); @@ -3324,6 +3527,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(3)?; let type_id = self.next()?; @@ -3341,11 +3545,14 @@ impl> Parser { self.lookup_constant.insert( id, LookupConstant { - handle: module.constants.append(crate::Constant { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - specialization: None, - inner: crate::ConstantInner::Composite { ty, components }, - }), + handle: module.constants.append( + crate::Constant { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + specialization: None, + inner: crate::ConstantInner::Composite { ty, components }, + }, + self.span_from_with_op(start), + ), type_id, }, ); @@ -3355,29 +3562,30 @@ impl> Parser { fn parse_null_constant( &mut self, inst: Instruction, - module: &mut crate::Module, - ) -> Result<(), Error> { + types: &Arena, + constants: &mut Arena, + ) -> Result<(u32, u32, Handle), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(3)?; let type_id = self.next()?; let id = self.next()?; + let span = self.span_from_with_op(start); let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; - let inner = null::generate_null_constant(ty, &mut module.types, &mut module.constants)?; - - self.lookup_constant.insert( - id, - LookupConstant { - handle: module.constants.append(crate::Constant { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - specialization: None, //TODO - inner, - }), - type_id, + let inner = null::generate_null_constant(ty, types, constants, span.clone())?; + let handle = constants.append( + crate::Constant { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + specialization: None, //TODO + inner, }, + span, ); - Ok(()) + self.lookup_constant + .insert(id, LookupConstant { handle, type_id }); + Ok((type_id, id, handle)) } fn parse_bool_constant( @@ -3386,6 +3594,7 @@ impl> Parser { value: bool, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(3)?; let type_id = self.next()?; @@ -3394,11 +3603,14 @@ impl> Parser { self.lookup_constant.insert( id, LookupConstant { - handle: module.constants.append(crate::Constant { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - specialization: None, //TODO - inner: crate::ConstantInner::boolean(value), - }), + handle: module.constants.append( + crate::Constant { + name: self.future_decor.remove(&id).and_then(|dec| dec.name), + specialization: None, //TODO + inner: crate::ConstantInner::boolean(value), + }, + self.span_from_with_op(start), + ), type_id, }, ); @@ -3410,6 +3622,7 @@ impl> Parser { inst: Instruction, module: &mut crate::Module, ) -> Result<(), Error> { + let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(4)?; let type_id = self.next()?; @@ -3423,6 +3636,7 @@ impl> Parser { } else { None }; + let span = self.span_from_with_op(start); let mut dec = self.future_decor.remove(&id).unwrap_or_default(); let original_ty = self.lookup_type.lookup(type_id)?.handle; @@ -3496,7 +3710,7 @@ impl> Parser { ) { unsigned_ty = module .types - .fetch_or_append(crate::Type { name: None, inner }); + .fetch_or_append(crate::Type { name: None, inner }, Default::default()); } } @@ -3522,8 +3736,9 @@ impl> Parser { match null::generate_default_built_in( Some(built_in), effective_ty, - &mut module.types, + &module.types, &mut module.constants, + span.clone(), ) { Ok(handle) => Some(handle), Err(e) => { @@ -3552,19 +3767,23 @@ impl> Parser { let handle = null::generate_default_built_in( built_in, member_ty, - &mut module.types, + &module.types, &mut module.constants, + span.clone(), )?; components.push(handle); } - Some(module.constants.append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Composite { - ty: effective_ty, - components, + Some(module.constants.append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Composite { + ty: effective_ty, + components, + }, }, - })) + span.clone(), + )) } _ => None, }, @@ -3585,7 +3804,7 @@ impl> Parser { } }; - let handle = module.global_variables.append(var); + let handle = module.global_variables.append(var, span); if module.types[effective_ty].inner.can_comparison_sample() { log::debug!("\t\ttracking {:?} for sampling properties", handle); self.handle_sampling diff --git a/src/front/spv/null.rs b/src/front/spv/null.rs index 1fc2b3043..8dfe55e89 100644 --- a/src/front/spv/null.rs +++ b/src/front/spv/null.rs @@ -15,19 +15,23 @@ fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::Con pub fn generate_null_constant( ty: Handle, - type_arena: &mut Arena, + type_arena: &Arena, constant_arena: &mut Arena, + span: crate::Span, ) -> Result { let inner = match type_arena[ty].inner { crate::TypeInner::Scalar { kind, width } => make_scalar_inner(kind, width), crate::TypeInner::Vector { size, kind, width } => { let mut components = Vec::with_capacity(size as usize); for _ in 0..size as usize { - components.push(constant_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: make_scalar_inner(kind, width), - })); + components.push(constant_arena.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: make_scalar_inner(kind, width), + }, + span.clone(), + )); } crate::ConstantInner::Composite { ty, components } } @@ -36,20 +40,27 @@ pub fn generate_null_constant( rows, width, } => { - let vector_ty = type_arena.fetch_or_append(crate::Type { - name: None, - inner: crate::TypeInner::Vector { - kind: crate::ScalarKind::Float, - size: rows, - width, + // If we successfully declared a matrix type, we have declared a vector type for it too. + let vector_ty = type_arena + .fetch_if(|t| { + t.inner + == crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + size: rows, + width, + } + }) + .unwrap(); + let vector_inner = + generate_null_constant(vector_ty, type_arena, constant_arena, span.clone())?; + let vector_handle = constant_arena.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: vector_inner, }, - }); - let vector_inner = generate_null_constant(vector_ty, type_arena, constant_arena)?; - let vector_handle = constant_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: vector_inner, - }); + span, + ); crate::ConstantInner::Composite { ty, components: vec![vector_handle; columns as usize], @@ -60,12 +71,16 @@ pub fn generate_null_constant( // copy out the types to avoid borrowing `members` let member_tys = members.iter().map(|member| member.ty).collect::>(); for member_ty in member_tys { - let inner = generate_null_constant(member_ty, type_arena, constant_arena)?; - components.push(constant_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner, - })); + let inner = + generate_null_constant(member_ty, type_arena, constant_arena, span.clone())?; + components.push(constant_arena.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + span.clone(), + )); } crate::ConstantInner::Composite { ty, components } } @@ -77,12 +92,15 @@ pub fn generate_null_constant( let size = constant_arena[handle] .to_array_length() .ok_or(Error::InvalidArraySize(handle))?; - let inner = generate_null_constant(base, type_arena, constant_arena)?; - let value = constant_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner, - }); + let inner = generate_null_constant(base, type_arena, constant_arena, span.clone())?; + let value = constant_arena.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + span, + ); crate::ConstantInner::Composite { ty, components: vec![value; size as usize], @@ -100,27 +118,34 @@ pub fn generate_null_constant( pub fn generate_default_built_in( built_in: Option, ty: Handle, - type_arena: &mut Arena, + type_arena: &Arena, constant_arena: &mut Arena, + span: crate::Span, ) -> Result, Error> { let inner = match built_in { Some(crate::BuiltIn::Position) => { - let zero = constant_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - value: crate::ScalarValue::Float(0.0), - width: 4, + let zero = constant_arena.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + value: crate::ScalarValue::Float(0.0), + width: 4, + }, }, - }); - let one = constant_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - value: crate::ScalarValue::Float(1.0), - width: 4, + span.clone(), + ); + let one = constant_arena.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + value: crate::ScalarValue::Float(1.0), + width: 4, + }, }, - }); + span.clone(), + ); crate::ConstantInner::Composite { ty, components: vec![zero, zero, zero, one], @@ -139,11 +164,14 @@ pub fn generate_default_built_in( width: 4, }, //Note: `crate::BuiltIn::ClipDistance` is intentionally left for the default path - _ => generate_null_constant(ty, type_arena, constant_arena)?, + _ => generate_null_constant(ty, type_arena, constant_arena, span.clone())?, }; - Ok(constant_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner, - })) + Ok(constant_arena.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + span, + )) } diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 9c6285524..39545ea73 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -201,6 +201,10 @@ impl<'a> Lexer<'a> { self.source.len() - self.input.len() } + pub(super) fn span_from(&self, offset: usize) -> Span { + offset..self.current_byte_offset() + } + #[must_use] pub(super) fn next(&mut self) -> TokenSpan<'a> { let mut start_byte_offset = self.current_byte_offset(); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 4990db0d0..414674773 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -12,6 +12,7 @@ use crate::{ proc::{ ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution, }, + span::Span as NagaSpan, ConstantInner, FastHashMap, ScalarValue, }; @@ -28,7 +29,6 @@ use std::{ borrow::Cow, convert::TryFrom, io::{self, Write}, - iter, num::{NonZeroU32, ParseFloatError, ParseIntError}, ops, }; @@ -504,31 +504,40 @@ mod type_inner_tests { fn to_wgsl() { let mut types = crate::Arena::new(); let mut constants = crate::Arena::new(); - let c = constants.append(crate::Constant { - name: Some("C".to_string()), - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(32), + let c = constants.append( + crate::Constant { + name: Some("C".to_string()), + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(32), + }, }, - }); + Default::default(), + ); - let mytype1 = types.append(crate::Type { - name: Some("MyType1".to_string()), - inner: crate::TypeInner::Struct { - top_level: true, - members: vec![], - span: 0, + let mytype1 = types.append( + crate::Type { + name: Some("MyType1".to_string()), + inner: crate::TypeInner::Struct { + top_level: true, + members: vec![], + span: 0, + }, }, - }); - let mytype2 = types.append(crate::Type { - name: Some("MyType2".to_string()), - inner: crate::TypeInner::Struct { - top_level: true, - members: vec![], - span: 0, + Default::default(), + ); + let mytype2 = types.append( + crate::Type { + name: Some("MyType2".to_string()), + inner: crate::TypeInner::Struct { + top_level: true, + members: vec![], + span: 0, + }, }, - }); + Default::default(), + ); let array = crate::TypeInner::Array { base: mytype1, @@ -741,13 +750,16 @@ impl<'a> ExpressionContext<'a, '_, '_> { ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>>, ) -> Result, Error<'a>> { + let start = lexer.current_byte_offset(); let mut left = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); let right = parser(lexer, self.reborrow())?; - left = self - .expressions - .append(crate::Expression::Binary { op, left, right }); + let end = lexer.current_byte_offset(); + left = self.expressions.append( + crate::Expression::Binary { op, left, right }, + NagaSpan::ByteRange(start..end), + ); } Ok(left) } @@ -761,10 +773,12 @@ impl<'a> ExpressionContext<'a, '_, '_> { ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>>, ) -> Result, Error<'a>> { + let start = lexer.current_byte_offset(); let mut left = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); let mut right = parser(lexer, self.reborrow())?; + let end = lexer.current_byte_offset(); // insert splats, if needed by the non-'*' operations if op != crate::BinaryOperator::Multiply { let left_size = match *self.resolve_type(left)? { @@ -773,21 +787,24 @@ impl<'a> ExpressionContext<'a, '_, '_> { }; match (left_size, self.resolve_type(right)?) { (Some(size), &crate::TypeInner::Scalar { .. }) => { - right = self - .expressions - .append(crate::Expression::Splat { size, value: right }); + right = self.expressions.append( + crate::Expression::Splat { size, value: right }, + self.expressions.get_span(right).clone(), + ); } (None, &crate::TypeInner::Vector { size, .. }) => { - left = self - .expressions - .append(crate::Expression::Splat { size, value: left }); + left = self.expressions.append( + crate::Expression::Splat { size, value: left }, + self.expressions.get_span(left).clone(), + ); } _ => {} } } - left = self - .expressions - .append(crate::Expression::Binary { op, left, right }); + left = self.expressions.append( + crate::Expression::Binary { op, left, right }, + NagaSpan::ByteRange(start..end), + ); } Ok(left) } @@ -796,9 +813,13 @@ impl<'a> ExpressionContext<'a, '_, '_> { /// /// This is useful for `CallResult` and `AtomicResult` expressions, which should not be covered by /// `Emit` statements. - fn interrupt_emitter(&mut self, expression: crate::Expression) -> Handle { + fn interrupt_emitter( + &mut self, + expression: crate::Expression, + span: NagaSpan, + ) -> Handle { self.block.extend(self.emitter.finish(self.expressions)); - let result = self.expressions.append(expression); + let result = self.expressions.append(expression, span); self.emitter.start(self.expressions); result } @@ -954,6 +975,7 @@ impl BindingParser { struct ParsedVariable<'a> { name: &'a str, + name_span: Span, class: Option, ty: Handle, init: Option>, @@ -1034,7 +1056,7 @@ impl std::error::Error for ParseError { } pub struct Parser { - scopes: Vec, + scopes: Vec<(Scope, usize)>, lookup_type: FastHashMap>, layouter: Layouter, } @@ -1048,6 +1070,20 @@ impl Parser { } } + fn push_scope(&mut self, scope: Scope, lexer: &Lexer<'_>) { + self.scopes.push((scope, lexer.current_byte_offset())); + } + + fn pop_scope(&mut self, lexer: &Lexer<'_>) -> Span { + let (_, initial) = self.scopes.pop().unwrap(); + lexer.span_from(initial) + } + + fn peek_scope(&mut self, lexer: &Lexer<'_>) -> Span { + let &(_, initial) = self.scopes.last().unwrap(); + lexer.span_from(initial) + } + fn get_constant_inner<'a>( word: &'a str, ty: char, @@ -1108,6 +1144,7 @@ impl Parser { } } + /// Expects name to be peeked from lexer, does not consume if returns None. fn parse_local_function_call<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -1124,6 +1161,7 @@ impl Parser { let count = ctx.functions[fun_handle].arguments.len(); let mut arguments = Vec::with_capacity(count); + let _ = lexer.next(); lexer.open_arguments()?; while arguments.len() != count { if !arguments.is_empty() { @@ -1159,33 +1197,42 @@ impl Parser { _ => return Err(Error::InvalidAtomicOperandType(value_span)), }; - let result = ctx.interrupt_emitter(expression); - ctx.block.push(crate::Statement::Atomic { - pointer, - fun, - value, - result, - }); + let result = ctx.interrupt_emitter(expression, NagaSpan::ByteRange(value_span.clone())); + ctx.block.push( + crate::Statement::Atomic { + pointer, + fun, + value, + result, + }, + NagaSpan::ByteRange(value_span), + ); Ok(result) } + /// Expects [`Scope::PrimaryExpr`] or [`Scope::SingularExpr`] on top; does not pop it. + /// Expects `word` to be peeked (still in lexer), doesn't consume if returning None. fn parse_function_call_inner<'a>( &mut self, lexer: &mut Lexer<'a>, name: &'a str, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { + assert!(self.scopes.last().is_some()); let expr = if let Some(fun) = conv::map_relational_fun(name) { + let _ = lexer.next(); lexer.open_arguments()?; let argument = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::Relational { fun, argument } } else if let Some(axis) = conv::map_derivative_axis(name) { + let _ = lexer.next(); lexer.open_arguments()?; let expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::Derivative { axis, expr } } else if let Some(fun) = conv::map_standard_fun(name) { + let _ = lexer.next(); lexer.open_arguments()?; let arg_count = fun.argument_count(); let arg = self.parse_general_expression(lexer, ctx.reborrow())?; @@ -1211,6 +1258,7 @@ impl Parser { } else { match name { "select" => { + let _ = lexer.next(); lexer.open_arguments()?; let reject = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; @@ -1225,6 +1273,7 @@ impl Parser { } } "arrayLength" => { + let _ = lexer.next(); lexer.open_arguments()?; let array = self.parse_singular_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; @@ -1232,12 +1281,14 @@ impl Parser { } // atomics "atomicLoad" => { + let _ = lexer.next(); lexer.open_arguments()?; let pointer = self.parse_atomic_pointer(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::Load { pointer } } "atomicAdd" => { + let _ = lexer.next(); let handle = self.parse_atomic_helper( lexer, crate::AtomicFunction::Add, @@ -1246,6 +1297,7 @@ impl Parser { return Ok(Some(handle)); } "atomicAnd" => { + let _ = lexer.next(); let handle = self.parse_atomic_helper( lexer, crate::AtomicFunction::And, @@ -1254,6 +1306,7 @@ impl Parser { return Ok(Some(handle)); } "atomicOr" => { + let _ = lexer.next(); let handle = self.parse_atomic_helper( lexer, crate::AtomicFunction::InclusiveOr, @@ -1262,6 +1315,7 @@ impl Parser { return Ok(Some(handle)); } "atomicXor" => { + let _ = lexer.next(); let handle = self.parse_atomic_helper( lexer, crate::AtomicFunction::ExclusiveOr, @@ -1270,16 +1324,19 @@ impl Parser { return Ok(Some(handle)); } "atomicMin" => { + let _ = lexer.next(); let handle = self.parse_atomic_helper(lexer, crate::AtomicFunction::Min, ctx)?; return Ok(Some(handle)); } "atomicMax" => { + let _ = lexer.next(); let handle = self.parse_atomic_helper(lexer, crate::AtomicFunction::Max, ctx)?; return Ok(Some(handle)); } "atomicExchange" => { + let _ = lexer.next(); let handle = self.parse_atomic_helper( lexer, crate::AtomicFunction::Exchange { compare: None }, @@ -1288,6 +1345,7 @@ impl Parser { return Ok(Some(handle)); } "atomicCompareExchangeWeak" => { + let _ = lexer.next(); lexer.open_arguments()?; let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; @@ -1309,17 +1367,23 @@ impl Parser { _ => return Err(Error::InvalidAtomicOperandType(value_span)), }; - let result = ctx.interrupt_emitter(expression); - ctx.block.push(crate::Statement::Atomic { - pointer, - fun: crate::AtomicFunction::Exchange { compare: Some(cmp) }, - value, - result, - }); + let span = self.peek_scope(lexer); + let result = + ctx.interrupt_emitter(expression, NagaSpan::ByteRange(span.clone())); + ctx.block.push( + crate::Statement::Atomic { + pointer, + fun: crate::AtomicFunction::Exchange { compare: Some(cmp) }, + value, + result, + }, + NagaSpan::ByteRange(span), + ); return Ok(Some(result)); } // texture sampling "textureSample" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; @@ -1350,6 +1414,7 @@ impl Parser { } } "textureSampleLevel" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; @@ -1382,6 +1447,7 @@ impl Parser { } } "textureSampleBias" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; @@ -1414,6 +1480,7 @@ impl Parser { } } "textureSampleGrad" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; @@ -1448,6 +1515,7 @@ impl Parser { } } "textureSampleCompare" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; @@ -1480,6 +1548,7 @@ impl Parser { } } "textureSampleCompareLevel" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; @@ -1512,6 +1581,7 @@ impl Parser { } } "textureLoad" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; let image = ctx.lookup_ident.lookup(image_name, image_span.clone())?; @@ -1544,6 +1614,7 @@ impl Parser { } } "textureDimensions" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; let image = ctx.lookup_ident.lookup(image_name, image_span)?; @@ -1560,6 +1631,7 @@ impl Parser { } } "textureNumLevels" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; let image = ctx.lookup_ident.lookup(image_name, image_span)?; @@ -1570,6 +1642,7 @@ impl Parser { } } "textureNumLayers" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; let image = ctx.lookup_ident.lookup(image_name, image_span)?; @@ -1580,6 +1653,7 @@ impl Parser { } } "textureNumSamples" => { + let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; let image = ctx.lookup_ident.lookup(image_name, image_span)?; @@ -1594,14 +1668,19 @@ impl Parser { let handle = match self.parse_local_function_call(lexer, name, ctx.reborrow())? { Some((function, arguments)) => { - let result = Some( - ctx.interrupt_emitter(crate::Expression::CallResult(function)), + let span = self.peek_scope(lexer); + let result = Some(ctx.interrupt_emitter( + crate::Expression::CallResult(function), + NagaSpan::ByteRange(span.clone()), + )); + ctx.block.push( + crate::Statement::Call { + function, + arguments, + result, + }, + NagaSpan::ByteRange(span), ); - ctx.block.push(crate::Statement::Call { - function, - arguments, - result, - }); result } None => None, @@ -1610,15 +1689,23 @@ impl Parser { } } }; - Ok(Some(ctx.expressions.append(expr))) + let span = self.peek_scope(lexer); + Ok(Some( + ctx.expressions.append(expr, NagaSpan::ByteRange(span)), + )) } + /// Expects [`Scope::PrimaryExpr`] scope on top; if returning Some(_), pops it. fn parse_construction<'a>( &mut self, lexer: &mut Lexer<'a>, type_name: &'a str, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { + assert_eq!( + self.scopes.last().map(|&(ref scope, _)| scope.clone()), + Some(Scope::PrimaryExpr) + ); let ty_resolution = match self.lookup_type.get(type_name) { Some(&handle) => TypeResolution::Handle(handle), None => match self.parse_type_decl_impl( @@ -1695,15 +1782,18 @@ impl Parser { } else { let ty = match ty_resolution { TypeResolution::Handle(handle) => handle, - TypeResolution::Value(inner) => { - ctx.types.fetch_or_append(crate::Type { name: None, inner }) - } + TypeResolution::Value(inner) => ctx + .types + .fetch_or_append(crate::Type { name: None, inner }, Default::default()), }; components.push(last_component); crate::Expression::Compose { ty, components } }; - Ok(Some(ctx.expressions.append(expr))) + let span = self.pop_scope(lexer); + Ok(Some( + ctx.expressions.append(expr, NagaSpan::ByteRange(span)), + )) } fn parse_const_expression_impl<'a>( @@ -1714,7 +1804,7 @@ impl Parser { type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result, Error<'a>> { - self.scopes.push(Scope::ConstantExpr); + self.push_scope(Scope::ConstantExpr, lexer); let inner = match first_token_span { (Token::Word("true"), _) => crate::ConstantInner::boolean(true), (Token::Word("false"), _) => crate::ConstantInner::boolean(false), @@ -1726,7 +1816,7 @@ impl Parser { for (handle, var) in const_arena.iter() { match var.name { Some(ref string) if string == name => { - self.scopes.pop(); + self.pop_scope(lexer); return Ok(handle); } _ => {} @@ -1757,21 +1847,29 @@ impl Parser { other => return Err(Error::Unexpected(other, ExpectedToken::Constant)), }; + // Only set span if it's a named constant. Otherwise, the enclosing Expression should have + // the span. + let span = self.pop_scope(lexer); let handle = if let Some(name) = register_name { - const_arena.append(crate::Constant { - name: Some(name.to_string()), - specialization: None, - inner, - }) + const_arena.append( + crate::Constant { + name: Some(name.to_string()), + specialization: None, + inner, + }, + NagaSpan::ByteRange(span), + ) } else { - const_arena.fetch_or_append(crate::Constant { - name: None, - specialization: None, - inner, - }) + const_arena.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + Default::default(), + ) }; - self.scopes.pop(); Ok(handle) } @@ -1789,43 +1887,56 @@ impl Parser { lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { - self.scopes.push(Scope::PrimaryExpr); - let handle = match lexer.next() { + // Will be popped inside match, possibly inside parse_function_call_inner or parse_construction + self.push_scope(Scope::PrimaryExpr, lexer); + let handle = match lexer.peek() { (Token::Paren('('), _) => { - let expr = self.parse_general_expression(lexer, ctx)?; + let _ = lexer.next(); + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; + self.pop_scope(lexer); expr } token @ (Token::Word("true"), _) | token @ (Token::Word("false"), _) | token @ (Token::Number { .. }, _) => { + let _ = lexer.next(); let const_handle = self.parse_const_expression_impl(token, lexer, None, ctx.types, ctx.constants)?; - // pause the emitter while generating this expression, since it's pre-emitted - ctx.interrupt_emitter(crate::Expression::Constant(const_handle)) + let span = self.pop_scope(lexer); + ctx.interrupt_emitter( + crate::Expression::Constant(const_handle), + NagaSpan::ByteRange(span), + ) } (Token::Word(word), span) => { if let Some(&expr) = ctx.lookup_ident.get(word) { + let _ = lexer.next(); + self.pop_scope(lexer); expr } else if let Some(expr) = self.parse_function_call_inner(lexer, word, ctx.reborrow())? { //TODO: resolve the duplicate call in `parse_singular_expression` - expr - } else if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow())? { + self.pop_scope(lexer); expr } else { - return Err(Error::UnknownIdent(span, word)); + let _ = lexer.next(); + if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow())? { + expr + } else { + return Err(Error::UnknownIdent(span, word)); + } } } other => return Err(Error::Unexpected(other, ExpectedToken::PrimaryExpression)), }; - self.scopes.pop(); Ok(handle) } fn parse_postfix<'a>( &mut self, + span_start: usize, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, mut handle: Handle, @@ -1851,7 +1962,9 @@ impl Parser { }; if now { let expression = crate::Expression::Load { pointer: handle }; - handle = ctx.expressions.append(expression); + handle = ctx + .expressions + .append(expression, NagaSpan::ByteRange(lexer.span_from(span_start))); needs_deref = false; } } @@ -1943,14 +2056,17 @@ impl Parser { // after we reached for the value, load it return Ok(if needs_deref { let expression = crate::Expression::Load { pointer: handle }; - ctx.expressions.append(expression) + ctx.expressions + .append(expression, ctx.expressions.get_span(handle).clone()) } else { handle }); } }; - handle = ctx.expressions.append(expression); + handle = ctx + .expressions + .append(expression, NagaSpan::ByteRange(lexer.span_from(span_start))); } } @@ -1959,47 +2075,54 @@ impl Parser { lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { - self.scopes.push(Scope::SingularExpr); + let start = lexer.current_byte_offset(); + self.push_scope(Scope::SingularExpr, lexer); //TODO: refactor this to avoid backing up - let backup = lexer.clone(); - let (allow_deref, handle) = match lexer.next().0 { + let (allow_deref, handle) = match lexer.peek().0 { Token::Operation('-') => { + let _ = lexer.next(); let expr = crate::Expression::Unary { op: crate::UnaryOperator::Negate, expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }; - (true, ctx.expressions.append(expr)) + let span = self.peek_scope(lexer); + ( + true, + ctx.expressions.append(expr, NagaSpan::ByteRange(span)), + ) } Token::Operation('!') | Token::Operation('~') => { + let _ = lexer.next(); let expr = crate::Expression::Unary { op: crate::UnaryOperator::Not, expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }; - (true, ctx.expressions.append(expr)) + let span = self.peek_scope(lexer); + ( + true, + ctx.expressions.append(expr, NagaSpan::ByteRange(span)), + ) } Token::Operation('&') => { + let _ = lexer.next(); let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; (false, handle) } Token::Word(word) => { let handle = match self.parse_function_call_inner(lexer, word, ctx.reborrow())? { Some(handle) => handle, - None => { - *lexer = backup; - self.parse_primary_expression(lexer, ctx.reborrow())? - } + None => self.parse_primary_expression(lexer, ctx.reborrow())?, }; (true, handle) } _ => { - *lexer = backup; let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; (true, handle) } }; - let post_handle = self.parse_postfix(lexer, ctx, handle, allow_deref)?; - self.scopes.pop(); + let post_handle = self.parse_postfix(start, lexer, ctx.reborrow(), handle, allow_deref)?; + self.pop_scope(lexer); Ok(post_handle) } @@ -2086,7 +2209,7 @@ impl Parser { lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { - self.scopes.push(Scope::GeneralExpr); + self.push_scope(Scope::GeneralExpr, lexer); // logical_or_expression let handle = context.parse_binary_op( lexer, @@ -2142,7 +2265,7 @@ impl Parser { ) }, )?; - self.scopes.pop(); + self.pop_scope(lexer); Ok(handle) } @@ -2164,7 +2287,7 @@ impl Parser { type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result, Error<'a>> { - self.scopes.push(Scope::VariableDecl); + self.push_scope(Scope::VariableDecl, lexer); let mut class = None; if lexer.skip(Token::Paren('<')) { @@ -2200,9 +2323,10 @@ impl Parser { None }; lexer.expect(Token::Separator(';'))?; - self.scopes.pop(); + let name_span = self.pop_scope(lexer); Ok(ParsedVariable { name, + name_span, class, ty, init, @@ -2222,10 +2346,9 @@ impl Parser { lexer.expect(Token::Paren('{'))?; loop { let (mut size, mut align) = (None, None); - let bind_start = lexer.current_byte_offset(); + self.push_scope(Scope::Attribute, lexer); let mut bind_parser = BindingParser::default(); if lexer.skip(Token::DoubleParen('[')) { - self.scopes.push(Scope::Attribute); let mut ready = true; loop { match lexer.next() { @@ -2269,10 +2392,9 @@ impl Parser { } } } - self.scopes.pop(); } - let bind_end = lexer.current_byte_offset(); + let bind_span = self.pop_scope(lexer); let name = match lexer.next() { (Token::Word(word), _) => word, @@ -2295,7 +2417,7 @@ impl Parser { members.push(crate::StructMember { name: Some(name.to_owned()), ty, - binding: bind_parser.finish(bind_start..bind_end)?, + binding: bind_parser.finish(bind_span)?, offset: range.start, }); } @@ -2625,10 +2747,16 @@ impl Parser { Some(&handle) => handle, None => { match self.parse_type_decl_impl(lexer, attribute, name, type_arena, const_arena)? { - Some(inner) => type_arena.fetch_or_append(crate::Type { - name: debug_name.map(|s| s.to_string()), - inner, - }), + Some(inner) => { + let span = name_span.start..lexer.current_byte_offset(); + type_arena.fetch_or_append( + crate::Type { + name: debug_name.map(|s| s.to_string()), + inner, + }, + NagaSpan::ByteRange(span), + ) + } None => return Err(Error::UnknownType(name_span)), } } @@ -2642,11 +2770,11 @@ impl Parser { type_arena: &mut Arena, const_arena: &mut Arena, ) -> Result<(Handle, crate::StorageAccess), Error<'a>> { - self.scopes.push(Scope::TypeDecl); + self.push_scope(Scope::TypeDecl, lexer); let mut attribute = TypeAttributes::default(); if lexer.skip(Token::DoubleParen('[')) { - self.scopes.push(Scope::Attribute); + self.push_scope(Scope::Attribute, lexer); loop { match lexer.next() { (Token::Word("stride"), _) => { @@ -2660,7 +2788,7 @@ impl Parser { other => return Err(Error::Unexpected(other, ExpectedToken::TypeAttribute)), } } - self.scopes.pop(); + self.pop_scope(lexer); } let storage_access = crate::StorageAccess::default(); @@ -2674,11 +2802,15 @@ impl Parser { type_arena, const_arena, )?; - self.scopes.pop(); + self.pop_scope(lexer); + // Only set span if it's the first occurrence of the type. + // Type spans therefore should only be used for errors in type declarations; + // use variable spans/expression spans/etc. otherwise Ok((handle, storage_access)) } /// Parse a statement that is either an assignment or a function call. + /// Expects `ident` to still be in the lexer. fn parse_statement_restricted<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, @@ -2686,10 +2818,13 @@ impl Parser { ident_span: Span, mut context: ExpressionContext<'a, '_, 'out>, ) -> Result<(), Error<'a>> { + let span_start = ident_span.start; context.emitter.start(context.expressions); let stmt = match context.lookup_ident.get(ident) { Some(&expr) => { - let left = self.parse_postfix(lexer, context.reborrow(), expr, false)?; + let _ = lexer.next(); + let left = + self.parse_postfix(span_start, lexer, context.reborrow(), expr, false)?; lexer.expect(Token::Operation('='))?; let value = self.parse_general_expression(lexer, context.reborrow())?; crate::Statement::Store { @@ -2708,10 +2843,13 @@ impl Parser { } } }; + let span_end = lexer.current_byte_offset(); context .block .extend(context.emitter.finish(context.expressions)); - context.block.push(stmt); + context + .block + .push(stmt, NagaSpan::ByteRange(span_start..span_end)); Ok(()) } @@ -2722,11 +2860,17 @@ impl Parser { block: &'out mut crate::Block, is_uniform_control_flow: bool, ) -> Result<(), Error<'a>> { - let (word, word_span) = match lexer.next() { - (Token::Separator(';'), _) => return Ok(()), + self.push_scope(Scope::Statement, lexer); + let (word, word_span) = match lexer.peek() { + (Token::Separator(';'), _) => { + let _ = lexer.next(); + self.pop_scope(lexer); + return Ok(()); + } (Token::Paren('{'), _) => { - self.scopes.push(Scope::Block); - let mut statements = Vec::new(); + self.push_scope(Scope::Block, lexer); + let _ = lexer.next(); + let mut statements = crate::Block::new(); while !lexer.skip(Token::Paren('}')) { self.parse_statement( lexer, @@ -2735,18 +2879,21 @@ impl Parser { is_uniform_control_flow, )?; } - self.scopes.pop(); - block.push(crate::Statement::Block(statements)); + self.pop_scope(lexer); + let span = self.pop_scope(lexer); + block.push( + crate::Statement::Block(statements), + NagaSpan::ByteRange(span), + ); return Ok(()); } (Token::Word(word), span) => (word, span), other => return Err(Error::Unexpected(other, ExpectedToken::Statement)), }; - - self.scopes.push(Scope::Statement); let mut emitter = super::Emitter::default(); - match word { + let statement = match word { "let" => { + let _ = lexer.next(); emitter.start(context.expressions); let (name, name_span) = lexer.next_ident_with_span()?; let given_ty = if lexer.skip(Token::Separator(':')) { @@ -2781,8 +2928,10 @@ impl Parser { context .named_expressions .insert(expr_id, String::from(name)); + None } "var" => { + let _ = lexer.next(); enum Init { Empty, Constant(Handle), @@ -2830,9 +2979,10 @@ impl Parser { // register the type, if needed match context.typifier[value].clone() { TypeResolution::Handle(ty) => ty, - TypeResolution::Value(inner) => context - .types - .fetch_or_append(crate::Type { name: None, inner }), + TypeResolution::Value(inner) => context.types.fetch_or_append( + crate::Type { name: None, inner }, + Default::default(), + ), } } }; @@ -2855,28 +3005,35 @@ impl Parser { }; lexer.expect(Token::Separator(';'))?; - let var_id = context.variables.append(crate::LocalVariable { - name: Some(name.to_owned()), - ty, - init: match init { - Init::Constant(value) => Some(value), - _ => None, + let var_id = context.variables.append( + crate::LocalVariable { + name: Some(name.to_owned()), + ty, + init: match init { + Init::Constant(value) => Some(value), + _ => None, + }, }, - }); + NagaSpan::ByteRange(name_span), + ); + // Doesn't make sense to assign a span to cached lookup let expr_id = context .expressions - .append(crate::Expression::LocalVariable(var_id)); + .append(crate::Expression::LocalVariable(var_id), Default::default()); context.lookup_ident.insert(name, expr_id); if let Init::Variable(value) = init { - block.push(crate::Statement::Store { + Some(crate::Statement::Store { pointer: expr_id, value, - }); + }) + } else { + None } } "return" => { + let _ = lexer.next(); let value = if lexer.peek().0 != Token::Separator(';') { emitter.start(context.expressions); let handle = self.parse_general_expression( @@ -2889,56 +3046,64 @@ impl Parser { None }; lexer.expect(Token::Separator(';'))?; - block.push(crate::Statement::Return { value }); + Some(crate::Statement::Return { value }) } "if" => { - emitter.start(context.expressions); + let _ = lexer.next(); lexer.expect(Token::Paren('('))?; + emitter.start(context.expressions); let condition = self .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; - lexer.expect(Token::Paren(')'))?; block.extend(emitter.finish(context.expressions)); + lexer.expect(Token::Paren(')'))?; let accept = self.parse_block(lexer, context.reborrow(), false)?; let mut elsif_stack = Vec::new(); + let mut elseif_span_start = lexer.current_byte_offset(); while lexer.skip(Token::Word("elseif")) { let mut sub_emitter = super::Emitter::default(); - sub_emitter.start(context.expressions); + lexer.expect(Token::Paren('('))?; + sub_emitter.start(context.expressions); let other_condition = self.parse_general_expression( lexer, context.as_expression(block, &mut sub_emitter), )?; - lexer.expect(Token::Paren(')'))?; let other_emit = sub_emitter.finish(context.expressions); + lexer.expect(Token::Paren(')'))?; let other_block = self.parse_block(lexer, context.reborrow(), false)?; - elsif_stack.push((other_condition, other_emit, other_block)); + elsif_stack.push((elseif_span_start, other_condition, other_emit, other_block)); + elseif_span_start = lexer.current_byte_offset(); } let mut reject = if lexer.skip(Token::Word("else")) { self.parse_block(lexer, context.reborrow(), false)? } else { - Vec::new() + crate::Block::new() }; + let span_end = lexer.current_byte_offset(); // reverse-fold the else-if blocks //Note: we may consider uplifting this to the IR - for (other_cond, other_emit, other_block) in elsif_stack.drain(..).rev() { - reject = other_emit - .into_iter() - .chain(iter::once(crate::Statement::If { - condition: other_cond, - accept: other_block, - reject, - })) - .collect(); + for (other_span_start, other_cond, other_emit, other_block) in + elsif_stack.into_iter().rev() + { + let sub_stmt = crate::Statement::If { + condition: other_cond, + accept: other_block, + reject, + }; + reject = crate::Block::new(); + reject.extend(other_emit); + reject.push(sub_stmt, NagaSpan::ByteRange(other_span_start..span_end)) } - block.push(crate::Statement::If { + Some(crate::Statement::If { condition, accept, reject, - }); + }) } "switch" => { + let _ = lexer.next(); emitter.start(context.expressions); lexer.expect(Token::Paren('('))?; let selector = self @@ -2947,7 +3112,7 @@ impl Parser { block.extend(emitter.finish(context.expressions)); lexer.expect(Token::Paren('{'))?; let mut cases = Vec::new(); - let mut default = Vec::new(); + let mut default = crate::Block::new(); loop { // cases + default @@ -2966,12 +3131,12 @@ impl Parser { } cases.push(crate::SwitchCase { value, - body: Vec::new(), + body: crate::Block::new(), fall_through: true, }); }; - let mut body = Vec::new(); + let mut body = crate::Block::new(); lexer.expect(Token::Paren('{'))?; let fall_through = loop { // default statements @@ -3001,15 +3166,16 @@ impl Parser { } } - block.push(crate::Statement::Switch { + Some(crate::Statement::Switch { selector, cases, default, - }); + }) } "loop" => { - let mut body = Vec::new(); - let mut continuing = Vec::new(); + let _ = lexer.next(); + let mut body = crate::Block::new(); + let mut continuing = crate::Block::new(); lexer.expect(Token::Paren('{'))?; loop { @@ -3024,9 +3190,10 @@ impl Parser { self.parse_statement(lexer, context.reborrow(), &mut body, false)?; } - block.push(crate::Statement::Loop { body, continuing }); + Some(crate::Statement::Loop { body, continuing }) } "for" => { + let _ = lexer.next(); lexer.expect(Token::Paren('('))?; if !lexer.skip(Token::Separator(';')) { let num_statements = block.len(); @@ -3047,27 +3214,34 @@ impl Parser { } }; - let mut body = Vec::new(); + let mut body = crate::Block::new(); if !lexer.skip(Token::Separator(';')) { - emitter.start(context.expressions); - let condition = self.parse_general_expression( - lexer, - context.as_expression(&mut body, &mut emitter), - )?; - lexer.expect(Token::Separator(';'))?; - body.extend(emitter.finish(context.expressions)); - body.push(crate::Statement::If { - condition, - accept: Vec::new(), - reject: vec![crate::Statement::Break], - }); + let (condition, span) = lexer.capture_span(|lexer| { + emitter.start(context.expressions); + let condition = self.parse_general_expression( + lexer, + context.as_expression(&mut body, &mut emitter), + )?; + lexer.expect(Token::Separator(';'))?; + body.extend(emitter.finish(context.expressions)); + Ok(condition) + })?; + let mut reject = crate::Block::new(); + reject.push(crate::Statement::Break, NagaSpan::Unknown); + body.push( + crate::Statement::If { + condition, + accept: crate::Block::new(), + reject, + }, + NagaSpan::ByteRange(span), + ); }; - let mut continuing = Vec::new(); - if let Token::Word(ident) = lexer.peek().0 { + let mut continuing = crate::Block::new(); + if let (Token::Word(ident), ident_span) = lexer.peek() { // manually parse the next statement here instead of calling parse_statement // because the statement is not terminated with a semicolon - let (_, ident_span) = lexer.next(); self.parse_statement_restricted( lexer, ident, @@ -3082,31 +3256,44 @@ impl Parser { self.parse_statement(lexer, context.reborrow(), &mut body, false)?; } - block.push(crate::Statement::Loop { body, continuing }); + Some(crate::Statement::Loop { body, continuing }) + } + "break" => { + let _ = lexer.next(); + Some(crate::Statement::Break) + } + "continue" => { + let _ = lexer.next(); + Some(crate::Statement::Continue) + } + "discard" => { + let _ = lexer.next(); + Some(crate::Statement::Kill) } - "break" => block.push(crate::Statement::Break), - "continue" => block.push(crate::Statement::Continue), - "discard" => block.push(crate::Statement::Kill), "storageBarrier" => { + let _ = lexer.next(); lexer.expect(Token::Paren('('))?; lexer.expect(Token::Paren(')'))?; - block.push(crate::Statement::Barrier(crate::Barrier::STORAGE)); + Some(crate::Statement::Barrier(crate::Barrier::STORAGE)) } "workgroupBarrier" => { + let _ = lexer.next(); lexer.expect(Token::Paren('('))?; lexer.expect(Token::Paren(')'))?; - block.push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP)); + Some(crate::Statement::Barrier(crate::Barrier::WORK_GROUP)) } "atomicStore" => { + let _ = lexer.next(); lexer.open_arguments()?; let mut expression_ctx = context.as_expression(block, &mut emitter); let pointer = self.parse_atomic_pointer(lexer, expression_ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let value = self.parse_general_expression(lexer, expression_ctx)?; lexer.close_arguments()?; - block.push(crate::Statement::Store { pointer, value }); + Some(crate::Statement::Store { pointer, value }) } "textureStore" => { + let _ = lexer.next(); emitter.start(context.expressions); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; @@ -3134,12 +3321,12 @@ impl Parser { .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; lexer.close_arguments()?; block.extend(emitter.finish(context.expressions)); - block.push(crate::Statement::ImageStore { + Some(crate::Statement::ImageStore { image, coordinate, array_index, value, - }); + }) } // assignment or a function call ident => { @@ -3150,9 +3337,13 @@ impl Parser { context.as_expression(block, &mut emitter), )?; lexer.expect(Token::Separator(';'))?; + None } + }; + let span = self.pop_scope(lexer); + if let Some(statement) = statement { + block.push(statement, NagaSpan::ByteRange(span)); } - self.scopes.pop(); Ok(()) } @@ -3161,10 +3352,10 @@ impl Parser { lexer: &mut Lexer<'a>, mut context: StatementContext<'a, '_, '_>, is_uniform_control_flow: bool, - ) -> Result, Error<'a>> { - self.scopes.push(Scope::Block); + ) -> Result> { + self.push_scope(Scope::Block, lexer); lexer.expect(Token::Paren('{'))?; - let mut block = Vec::new(); + let mut block = crate::Block::new(); while !lexer.skip(Token::Paren('}')) { self.parse_statement( lexer, @@ -3173,7 +3364,7 @@ impl Parser { is_uniform_control_flow, )?; } - self.scopes.pop(); + self.pop_scope(lexer); Ok(block) } @@ -3181,14 +3372,14 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, ) -> Result, Error<'a>> { - let start = lexer.current_byte_offset(); + self.push_scope(Scope::Attribute, lexer); if !lexer.skip(Token::DoubleParen('[')) { + self.pop_scope(lexer); return Ok(None); } let mut bind_parser = BindingParser::default(); - self.scopes.push(Scope::Attribute); loop { let (word, span) = lexer.next_ident_with_span()?; bind_parser.parse(lexer, word, span)?; @@ -3201,10 +3392,8 @@ impl Parser { } } - let end = lexer.current_byte_offset(); - - self.scopes.pop(); - bind_parser.finish(start..end) + let span = self.pop_scope(lexer); + bind_parser.finish(span) } fn parse_function_decl<'a>( @@ -3213,14 +3402,21 @@ impl Parser { module: &mut crate::Module, lookup_global_expression: &FastHashMap<&'a str, crate::Expression>, ) -> Result<(crate::Function, &'a str), Error<'a>> { - self.scopes.push(Scope::FunctionDecl); + self.push_scope(Scope::FunctionDecl, lexer); // read function name let mut lookup_ident = FastHashMap::default(); let fun_name = lexer.next_ident()?; // populate initial expressions let mut expressions = Arena::new(); for (&name, expression) in lookup_global_expression.iter() { - let expr_handle = expressions.append(expression.clone()); + let span = match *expression { + crate::Expression::GlobalVariable(handle) => { + module.global_variables.get_span(handle).clone() + } + crate::Expression::Constant(handle) => module.constants.get_span(handle).clone(), + _ => unreachable!(), + }; + let expr_handle = expressions.append(expression.clone(), span); lookup_ident.insert(name, expr_handle); } // read parameter list @@ -3235,11 +3431,13 @@ impl Parser { )); } let binding = self.parse_varying_binding(lexer)?; - let (param_name, _param_name_span, param_type, _access) = + let (param_name, param_name_span, param_type, _access) = self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; let param_index = arguments.len() as u32; - let expression_token = - expressions.append(crate::Expression::FunctionArgument(param_index)); + let expression_token = expressions.append( + crate::Expression::FunctionArgument(param_index), + NagaSpan::ByteRange(param_name_span), + ); lookup_ident.insert(param_name, expression_token); arguments.push(crate::FunctionArgument { name: Some(param_name.to_string()), @@ -3265,7 +3463,7 @@ impl Parser { local_variables: Arena::new(), expressions, named_expressions: crate::NamedExpressions::default(), - body: Vec::new(), + body: crate::Block::new(), }; // read body @@ -3290,7 +3488,7 @@ impl Parser { // fixup the IR ensure_block_returns(&mut fun.body); // done - self.scopes.pop(); + self.pop_scope(lexer); // Set named expressions after block parsing ends fun.named_expressions = named_expressions; @@ -3314,7 +3512,7 @@ impl Parser { if lexer.skip(Token::DoubleParen('[')) { let (mut bind_index, mut bind_group) = (None, None); - self.scopes.push(Scope::Attribute); + self.push_scope(Scope::Attribute, lexer); loop { match lexer.next_ident_with_span()? { ("binding", _) => { @@ -3386,24 +3584,29 @@ impl Parser { binding: index, }); } - self.scopes.pop(); + self.pop_scope(lexer); } // read items + let start = lexer.current_byte_offset(); match lexer.next() { (Token::Separator(';'), _) => {} (Token::Word("struct"), _) => { let name = lexer.next_ident()?; let (members, span) = self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?; - let ty = module.types.fetch_or_append(crate::Type { - name: Some(name.to_string()), - inner: crate::TypeInner::Struct { - top_level: is_block, - members, - span, + let type_span = lexer.span_from(start); + let ty = module.types.fetch_or_append( + crate::Type { + name: Some(name.to_string()), + inner: crate::TypeInner::Struct { + top_level: is_block, + members, + span, + }, }, - }); + NagaSpan::ByteRange(type_span), + ); self.lookup_type.insert(name.to_owned(), ty); lexer.expect(Token::Separator(';'))?; } @@ -3472,13 +3675,16 @@ impl Parser { _ => crate::StorageClass::Private, }, }; - let var_handle = module.global_variables.append(crate::GlobalVariable { - name: Some(pvar.name.to_owned()), - class, - binding: binding.take(), - ty: pvar.ty, - init: pvar.init, - }); + let var_handle = module.global_variables.append( + crate::GlobalVariable { + name: Some(pvar.name.to_owned()), + class, + binding: binding.take(), + ty: pvar.ty, + init: pvar.init, + }, + NagaSpan::ByteRange(pvar.name_span), + ); lookup_global_expression .insert(pvar.name, crate::Expression::GlobalVariable(var_handle)); } @@ -3494,7 +3700,9 @@ impl Parser { function, }), None => { - module.functions.append(function); + module + .functions + .append(function, NagaSpan::ByteRange(lexer.span_from(start))); } } } diff --git a/src/lib.rs b/src/lib.rs index bd5a7c1d0..ce3cc5d34 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,8 +29,8 @@ A Naga backend can generate code to evaluate an `Expression` however and whenever it pleases, as long as it is certain to observe the side effects of all previously executed `Statement`s. -Many `Statement` variants use the [`Block`] type, which is simply `Vec`, -representing a series of statements executed in order. The body of an +Many `Statement` variants use the [`Block`] type, which is `Vec`, +with optional span info, representing a series of statements executed in order. The body of an `EntryPoint`s or `Function` is a `Block`, and `Statement` has a [`Block`][Statement::Block] variant. @@ -151,8 +151,10 @@ tree. mod arena; pub mod back; +mod block; pub mod front; pub mod proc; +mod span; pub mod valid; pub use crate::arena::{Arena, Handle, Range}; @@ -162,6 +164,7 @@ use std::{ hash::BuildHasherDefault, }; +pub use crate::span::Span; #[cfg(feature = "deserialize")] use serde::Deserialize; #[cfg(feature = "serialize")] @@ -1175,8 +1178,7 @@ pub enum Expression { ArrayLength(Handle), } -/// A code block is just a vector of statements. -pub type Block = Vec; +pub use block::Block; /// A case for a switch statement. // Clone is used only for error reporting and is not intended for end users diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index 0f8b302cd..e35c2d9f9 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -41,6 +41,6 @@ pub fn ensure_block_returns(block: &mut crate::Block) { | Some(&mut S::Call { .. }) | Some(&mut S::Atomic { .. }) | Some(&mut S::Barrier(_)) - | None => block.push(S::Return { value: None }), + | None => block.push(S::Return { value: None }, Default::default()), } } diff --git a/src/span.rs b/src/span.rs new file mode 100644 index 000000000..dbd24c8d1 --- /dev/null +++ b/src/span.rs @@ -0,0 +1,38 @@ +use std::ops::Range; + +// A source code span, used for error reporting. +#[derive(Clone, Debug, PartialEq)] +pub enum Span { + // Span is unknown - no source information. + Unknown, + // Byte range. + ByteRange(Range), +} + +impl Default for Span { + fn default() -> Self { + Self::Unknown + } +} + +impl Span { + pub fn subsume(&mut self, other: &Self) { + match *self { + Self::Unknown => self.clone_from(other), + Self::ByteRange(ref mut self_range) => { + if let Self::ByteRange(ref other_range) = *other { + self_range.start = self_range.start.min(other_range.start); + self_range.end = self_range.end.max(other_range.end); + } + } + } + } + + pub fn total_span<'a, T: Iterator>(from: T) -> Self { + let mut span: Self = Default::default(); + for other in from { + span.subsume(other); + } + span + } +} diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 543e25034..0f917df7c 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -857,59 +857,79 @@ fn uniform_control_flow() { use crate::{Expression as E, Statement as S}; let mut constant_arena = Arena::new(); - let constant = constant_arena.append(crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(0), + let constant = constant_arena.append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(0), + }, }, - }); + Default::default(), + ); let mut type_arena = Arena::new(); - let ty = type_arena.append(crate::Type { - name: None, - inner: crate::TypeInner::Vector { - size: crate::VectorSize::Bi, - kind: crate::ScalarKind::Float, - width: 4, + let ty = type_arena.append( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Float, + width: 4, + }, }, - }); + Default::default(), + ); let mut global_var_arena = Arena::new(); - let non_uniform_global = global_var_arena.append(crate::GlobalVariable { - name: None, - init: None, - ty, - class: crate::StorageClass::Handle, - binding: None, - }); - let uniform_global = global_var_arena.append(crate::GlobalVariable { - name: None, - init: None, - ty, - binding: None, - class: crate::StorageClass::Uniform, - }); + let non_uniform_global = global_var_arena.append( + crate::GlobalVariable { + name: None, + init: None, + ty, + class: crate::StorageClass::Handle, + binding: None, + }, + Default::default(), + ); + let uniform_global = global_var_arena.append( + crate::GlobalVariable { + name: None, + init: None, + ty, + binding: None, + class: crate::StorageClass::Uniform, + }, + Default::default(), + ); let mut expressions = Arena::new(); // checks the uniform control flow - let constant_expr = expressions.append(E::Constant(constant)); + let constant_expr = expressions.append(E::Constant(constant), Default::default()); // checks the non-uniform control flow - let derivative_expr = expressions.append(E::Derivative { - axis: crate::DerivativeAxis::X, - expr: constant_expr, - }); + let derivative_expr = expressions.append( + E::Derivative { + axis: crate::DerivativeAxis::X, + expr: constant_expr, + }, + Default::default(), + ); let emit_range_constant_derivative = expressions.range_from(0); - let non_uniform_global_expr = expressions.append(E::GlobalVariable(non_uniform_global)); - let uniform_global_expr = expressions.append(E::GlobalVariable(uniform_global)); + let non_uniform_global_expr = + expressions.append(E::GlobalVariable(non_uniform_global), Default::default()); + let uniform_global_expr = + expressions.append(E::GlobalVariable(uniform_global), Default::default()); let emit_range_globals = expressions.range_from(2); // checks the QUERY flag - let query_expr = expressions.append(E::ArrayLength(uniform_global_expr)); + let query_expr = expressions.append(E::ArrayLength(uniform_global_expr), Default::default()); // checks the transitive WRITE flag - let access_expr = expressions.append(E::AccessIndex { - base: non_uniform_global_expr, - index: 1, - }); + let access_expr = expressions.append( + E::AccessIndex { + base: non_uniform_global_expr, + index: 1, + }, + Default::default(), + ); let emit_range_query_access_globals = expressions.range_from(2); let mut info = FunctionInfo { @@ -944,14 +964,15 @@ fn uniform_control_flow() { let stmt_emit1 = S::Emit(emit_range_globals.clone()); let stmt_if_uniform = S::If { condition: uniform_global_expr, - accept: Vec::new(), + accept: crate::Block::new(), reject: vec![ S::Emit(emit_range_constant_derivative.clone()), S::Store { pointer: constant_expr, value: derivative_expr, }, - ], + ] + .into(), }; assert_eq!( info.process_block(&[stmt_emit1, stmt_if_uniform], &[], None, &expressions), @@ -975,8 +996,9 @@ fn uniform_control_flow() { pointer: constant_expr, value: derivative_expr, }, - ], - reject: Vec::new(), + ] + .into(), + reject: crate::Block::new(), }; assert_eq!( info.process_block(&[stmt_emit2, stmt_if_non_uniform], &[], None, &expressions), From 47b9f4a2e51a978cb77780fe492c83fbe3ce1f02 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 11 Aug 2021 14:55:54 -0700 Subject: [PATCH 1217/2212] [spv-out] Writer::write_texture_coordinates: Fix result type. (#1188) Some SPIR-V texture access instructions take coordinates as integers, others as floats. The types of coordinates in Naga expressions generally match those in SPIR-V, but Naga indices for arrayed textures are always integers, whereas SPIR-V combines coordinates and array indices into a single vector, so indices need to be cast to match the coordinate component type. This commit makes `write_texture_coordinates` properly cast array indices to match the coordinates' component type before combining them all into a single result vector. Fixes #1186. --- src/back/spv/block.rs | 89 +++++-- tests/in/image.wgsl | 5 +- tests/out/hlsl/image.hlsl | 4 +- tests/out/msl/image.msl | 10 +- tests/out/spv/image.spvasm | 525 +++++++++++++++++++------------------ tests/out/wgsl/image.wgsl | 5 +- 6 files changed, 348 insertions(+), 290 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index daaf243b8..b02fa720e 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -92,22 +92,34 @@ impl<'w> BlockContext<'w> { /// Extend texture coordinates with an array index, if necessary. /// - /// SPIR-V image read and write instructions take the coordinates of the - /// texel to access as a vector. If the image is arrayed, the array index - /// must be supplied as the final component of the coordinate vector. + /// Whereas [`Expression::ImageLoad`] and [`ImageSample`] treat the array + /// index as a separate operand from the coordinates, SPIR-V image access + /// instructions include the array index in the `coordinates` operand. This + /// function builds a SPIR-V coordinate vector from a Naga coordinate vector + /// and array index. /// /// If `array_index` is `Some(expr)`, then this function constructs a new /// vector that is `coordinates` with `array_index` concatenated onto the /// end: a `vec2` becomes a `vec3`, a scalar becomes a `vec2`, and so on. /// + /// Naga's `ImageLoad` and SPIR-V's `OpImageRead`, `OpImageFetch`, and + /// `OpImageWrite` all use integer coordinates, while Naga's `ImageSample` + /// and SPIR-V's `OpImageSample...` instructions all take floating-point + /// coordinate vectors. The array index, always an integer scalar, may need + /// to be converted to match the component type of `coordinates`. + /// /// If `array_index` is `None`, this function simply returns the id for /// `coordinates`. + /// + /// [`Expression::ImageLoad`]: crate::Expression::ImageLoad + /// [`ImageSample`]: crate::Expression::ImageSample fn write_texture_coordinates( &mut self, coordinates: Handle, array_index: Option>, block: &mut Block, ) -> Result { + use crate::TypeInner as Ti; use crate::VectorSize as Vs; let coordinate_id = self.cached[coordinates]; @@ -118,29 +130,25 @@ impl<'w> BlockContext<'w> { None => return Ok(coordinate_id), Some(ix) => ix, }; - let array_index_u32_id = self.cached[array_index]; - let coordinate_scalar_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - }))?; - let array_index_f32_id = self.gen_id(); - block.body.push(Instruction::unary( - spirv::Op::ConvertUToF, - coordinate_scalar_type_id, - array_index_f32_id, - array_index_u32_id, - )); - let size = match *self.fun_info[coordinates] + // Find the component type of `coordinates`, and figure out the size the + // combined coordinate vector will have. + let (component_kind, result_size) = match *self.fun_info[coordinates] .ty .inner_with(&self.ir_module.types) { - crate::TypeInner::Scalar { .. } => Vs::Bi, - crate::TypeInner::Vector { size: Vs::Bi, .. } => Vs::Tri, - crate::TypeInner::Vector { size: Vs::Tri, .. } => Vs::Quad, - crate::TypeInner::Vector { size: Vs::Quad, .. } => { + Ti::Scalar { kind, width: 4 } => (kind, Vs::Bi), + Ti::Vector { + kind, + width: 4, + size: Vs::Bi, + } => (kind, Vs::Tri), + Ti::Vector { + kind, + width: 4, + size: Vs::Tri, + } => (kind, Vs::Quad), + Ti::Vector { size: Vs::Quad, .. } => { return Err(Error::Validation("extending vec4 coordinate")); } ref other => { @@ -148,19 +156,44 @@ impl<'w> BlockContext<'w> { return Err(Error::Validation("coordinate type")); } }; - let extended_coordinate_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(size), - kind: crate::ScalarKind::Float, + + // Convert the index to the coordinate component type, if necessary. + let array_index_i32_id = self.cached[array_index]; + let reconciled_array_index_id = if component_kind == crate::ScalarKind::Sint { + array_index_i32_id + } else { + let component_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: component_kind, width: 4, pointer_class: None, }))?; + let reconciled_id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::ConvertUToF, + component_type_id, + reconciled_id, + array_index_i32_id, + )); + reconciled_id + }; + + // Find the SPIR-V type for the combined coordinates/index vector. + let combined_coordinate_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(result_size), + kind: component_kind, + width: 4, + pointer_class: None, + }))?; + + // Schmear the coordinates and index together. let id = self.gen_id(); block.body.push(Instruction::composite_construct( - extended_coordinate_type_id, + combined_coordinate_type_id, id, - &[coordinate_id, array_index_f32_id], + &[coordinate_id, reconciled_array_index_id], )); Ok(id) } diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 1a449d0c3..308b3cdde 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -6,6 +6,8 @@ var image_multisampled_src: texture_multisampled_2d; var image_depth_multisampled_src: texture_depth_multisampled_2d; [[group(0), binding(1)]] var image_storage_src: texture_storage_2d; +[[group(0), binding(5)]] +var image_array_src: texture_2d_array; [[group(0), binding(2)]] var image_dst: texture_storage_1d; @@ -21,7 +23,8 @@ fn main( let value2 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); let value3 = textureLoad(image_depth_multisampled_src, itc, i32(local_id.z)); let value4 = textureLoad(image_storage_src, itc); - textureStore(image_dst, itc.x, value1 + value2 + u32(value3) + value4); + let value5 = textureLoad(image_array_src, itc, i32(local_id.z), i32(local_id.z) + 1); + textureStore(image_dst, itc.x, value1 + value2 + u32(value3) + value4 + value5); } [[group(0), binding(0)]] diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 9669e8259..fb39bceca 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -3,6 +3,7 @@ Texture2D image_mipmapped_src : register(t0); Texture2DMS image_multisampled_src : register(t3); Texture2DMS image_depth_multisampled_src : register(t4); RWTexture2D image_storage_src : register(u1); +Texture2DArray image_array_src : register(t5); RWTexture1D image_dst : register(u2); Texture1D image_1d : register(t0); Texture2D image_2d : register(t1); @@ -35,7 +36,8 @@ void main(ComputeInput_main computeinput_main) uint4 value2_ = image_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)); float value3_ = image_depth_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)).x; uint4 value4_ = image_storage_src.Load(itc); - image_dst[itc.x] = (((value1_ + value2_) + uint4(uint(value3_).xxxx)) + value4_); + uint4 value5_ = image_array_src.Load(int4(itc, int(computeinput_main.local_id1.z), (int(computeinput_main.local_id1.z) + 1))); + image_dst[itc.x] = ((((value1_ + value2_) + uint4(uint(value3_).xxxx)) + value4_) + value5_); return; } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 64014c8ec..3a615ef12 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -2,7 +2,7 @@ #include #include -constant metal::int2 const_type6_ = {3, 1}; +constant metal::int2 const_type7_ = {3, 1}; struct main1Input { }; @@ -12,6 +12,7 @@ kernel void main1( , metal::texture2d_ms image_multisampled_src [[user(fake0)]] , metal::depth2d_ms image_depth_multisampled_src [[user(fake0)]] , metal::texture2d image_storage_src [[user(fake0)]] +, metal::texture2d_array image_array_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { metal::int2 dim = int2(image_storage_src.get_width(), image_storage_src.get_height()); @@ -20,7 +21,8 @@ kernel void main1( metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); float value3_ = image_depth_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); - image_dst.write(((value1_ + value2_) + metal::uint4(static_cast(value3_))) + value4_, metal::uint(itc.x)); + metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); + image_dst.write((((value1_ + value2_) + metal::uint4(static_cast(value3_))) + value4_) + value5_, metal::uint(itc.x)); return; } @@ -70,9 +72,9 @@ fragment sampleOutput sample( ) { metal::float2 tc = metal::float2(0.5); metal::float4 s2d = image_2d.sample(sampler_reg, tc); - metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type6_); + metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type7_); metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.3)); - metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type6_); + metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type7_); return sampleOutput { ((s2d + s2d_offset) + s2d_level) + s2d_level_offset }; } diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index b853a7ddf..03a2cfc30 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,76 +1,79 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 201 +; Bound: 213 OpCapability Image1D OpCapability Shader OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %64 "main" %61 -OpEntryPoint Vertex %100 "queries" %98 -OpEntryPoint Fragment %168 "sample" %167 -OpEntryPoint Fragment %189 "sample_comparison" %187 -OpExecutionMode %64 LocalSize 16 1 1 -OpExecutionMode %168 OriginUpperLeft -OpExecutionMode %189 OriginUpperLeft +OpEntryPoint GLCompute %67 "main" %64 +OpEntryPoint Vertex %113 "queries" %111 +OpEntryPoint Fragment %180 "sample" %179 +OpEntryPoint Fragment %201 "sample_comparison" %199 +OpExecutionMode %67 LocalSize 16 1 1 +OpExecutionMode %180 OriginUpperLeft +OpExecutionMode %201 OriginUpperLeft OpSource GLSL 450 -OpName %30 "image_mipmapped_src" -OpName %32 "image_multisampled_src" -OpName %34 "image_depth_multisampled_src" -OpName %36 "image_storage_src" -OpName %38 "image_dst" -OpName %40 "image_1d" -OpName %42 "image_2d" -OpName %44 "image_2d_array" -OpName %46 "image_cube" -OpName %48 "image_cube_array" -OpName %50 "image_3d" -OpName %52 "image_aa" -OpName %54 "sampler_reg" -OpName %56 "sampler_cmp" -OpName %58 "image_2d_depth" -OpName %61 "local_id" -OpName %64 "main" -OpName %100 "queries" -OpName %168 "sample" -OpName %189 "sample_comparison" -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 0 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 3 -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 4 -OpDecorate %36 NonWritable -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 1 -OpDecorate %38 NonReadable -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 2 -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 0 -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 1 -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 2 -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 3 -OpDecorate %48 DescriptorSet 0 -OpDecorate %48 Binding 4 -OpDecorate %50 DescriptorSet 0 -OpDecorate %50 Binding 5 -OpDecorate %52 DescriptorSet 0 -OpDecorate %52 Binding 6 -OpDecorate %54 DescriptorSet 1 -OpDecorate %54 Binding 0 -OpDecorate %56 DescriptorSet 1 -OpDecorate %56 Binding 1 -OpDecorate %58 DescriptorSet 1 -OpDecorate %58 Binding 2 -OpDecorate %61 BuiltIn LocalInvocationId -OpDecorate %98 BuiltIn Position -OpDecorate %167 Location 0 -OpDecorate %187 Location 0 +OpName %31 "image_mipmapped_src" +OpName %33 "image_multisampled_src" +OpName %35 "image_depth_multisampled_src" +OpName %37 "image_storage_src" +OpName %39 "image_array_src" +OpName %41 "image_dst" +OpName %43 "image_1d" +OpName %45 "image_2d" +OpName %47 "image_2d_array" +OpName %49 "image_cube" +OpName %51 "image_cube_array" +OpName %53 "image_3d" +OpName %55 "image_aa" +OpName %57 "sampler_reg" +OpName %59 "sampler_cmp" +OpName %61 "image_2d_depth" +OpName %64 "local_id" +OpName %67 "main" +OpName %113 "queries" +OpName %180 "sample" +OpName %201 "sample_comparison" +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 0 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 3 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 4 +OpDecorate %37 NonWritable +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 1 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 5 +OpDecorate %41 NonReadable +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 2 +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 0 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 1 +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 2 +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 3 +OpDecorate %51 DescriptorSet 0 +OpDecorate %51 Binding 4 +OpDecorate %53 DescriptorSet 0 +OpDecorate %53 Binding 5 +OpDecorate %55 DescriptorSet 0 +OpDecorate %55 Binding 6 +OpDecorate %57 DescriptorSet 1 +OpDecorate %57 Binding 0 +OpDecorate %59 DescriptorSet 1 +OpDecorate %59 Binding 1 +OpDecorate %61 DescriptorSet 1 +OpDecorate %61 Binding 2 +OpDecorate %64 BuiltIn LocalInvocationId +OpDecorate %111 BuiltIn Position +OpDecorate %179 Location 0 +OpDecorate %199 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -85,204 +88,216 @@ OpDecorate %187 Location 0 %13 = OpTypeImage %12 2D 0 0 1 1 Unknown %14 = OpTypeImage %8 2D 1 0 1 1 Unknown %15 = OpTypeImage %12 2D 0 0 0 2 Rgba8ui -%16 = OpTypeImage %12 1D 0 0 0 2 R32ui -%17 = OpTypeVector %12 3 -%18 = OpTypeVector %4 2 -%19 = OpTypeImage %8 1D 0 0 0 1 Unknown -%20 = OpTypeImage %8 2D 0 0 0 1 Unknown -%21 = OpTypeImage %8 2D 0 1 0 1 Unknown -%22 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%23 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%24 = OpTypeImage %8 3D 0 0 0 1 Unknown -%25 = OpTypeImage %8 2D 0 0 1 1 Unknown -%26 = OpTypeVector %8 4 -%27 = OpTypeSampler -%28 = OpTypeImage %8 2D 1 0 0 1 Unknown -%29 = OpConstantComposite %18 %10 %6 -%31 = OpTypePointer UniformConstant %11 -%30 = OpVariable %31 UniformConstant -%33 = OpTypePointer UniformConstant %13 -%32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %14 -%34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %15 -%36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %16 -%38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %19 -%40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %20 -%42 = OpVariable %43 UniformConstant -%45 = OpTypePointer UniformConstant %21 -%44 = OpVariable %45 UniformConstant -%47 = OpTypePointer UniformConstant %22 -%46 = OpVariable %47 UniformConstant -%49 = OpTypePointer UniformConstant %23 -%48 = OpVariable %49 UniformConstant -%51 = OpTypePointer UniformConstant %24 -%50 = OpVariable %51 UniformConstant -%53 = OpTypePointer UniformConstant %25 -%52 = OpVariable %53 UniformConstant -%55 = OpTypePointer UniformConstant %27 -%54 = OpVariable %55 UniformConstant -%57 = OpTypePointer UniformConstant %27 -%56 = OpVariable %57 UniformConstant -%59 = OpTypePointer UniformConstant %28 -%58 = OpVariable %59 UniformConstant -%62 = OpTypePointer Input %17 -%61 = OpVariable %62 Input -%65 = OpTypeFunction %2 -%73 = OpTypeVector %12 2 -%81 = OpTypeVector %12 4 -%99 = OpTypePointer Output %26 -%98 = OpVariable %99 Output -%109 = OpConstant %12 0 -%114 = OpTypeVector %4 3 -%167 = OpVariable %99 Output -%172 = OpTypeVector %8 2 -%174 = OpTypeSampledImage %20 -%188 = OpTypePointer Output %8 -%187 = OpVariable %188 Output -%194 = OpTypeSampledImage %28 -%199 = OpConstant %8 0.0 -%64 = OpFunction %2 None %65 -%60 = OpLabel -%63 = OpLoad %17 %61 -%66 = OpLoad %11 %30 -%67 = OpLoad %13 %32 -%68 = OpLoad %14 %34 -%69 = OpLoad %15 %36 -%70 = OpLoad %16 %38 -OpBranch %71 -%71 = OpLabel -%72 = OpImageQuerySize %18 %69 -%74 = OpVectorShuffle %73 %63 %63 0 1 -%75 = OpBitcast %18 %74 -%76 = OpIMul %18 %72 %75 -%77 = OpCompositeConstruct %18 %3 %5 -%78 = OpSMod %18 %76 %77 -%79 = OpCompositeExtract %12 %63 2 -%80 = OpBitcast %4 %79 -%82 = OpImageFetch %81 %66 %78 Lod %80 -%83 = OpCompositeExtract %12 %63 2 +%16 = OpTypeImage %12 2D 0 1 0 1 Unknown +%17 = OpTypeImage %12 1D 0 0 0 2 R32ui +%18 = OpTypeVector %12 3 +%19 = OpTypeVector %4 2 +%20 = OpTypeImage %8 1D 0 0 0 1 Unknown +%21 = OpTypeImage %8 2D 0 0 0 1 Unknown +%22 = OpTypeImage %8 2D 0 1 0 1 Unknown +%23 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%24 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%25 = OpTypeImage %8 3D 0 0 0 1 Unknown +%26 = OpTypeImage %8 2D 0 0 1 1 Unknown +%27 = OpTypeVector %8 4 +%28 = OpTypeSampler +%29 = OpTypeImage %8 2D 1 0 0 1 Unknown +%30 = OpConstantComposite %19 %10 %6 +%32 = OpTypePointer UniformConstant %11 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %13 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %14 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %15 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %16 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %17 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %20 +%43 = OpVariable %44 UniformConstant +%46 = OpTypePointer UniformConstant %21 +%45 = OpVariable %46 UniformConstant +%48 = OpTypePointer UniformConstant %22 +%47 = OpVariable %48 UniformConstant +%50 = OpTypePointer UniformConstant %23 +%49 = OpVariable %50 UniformConstant +%52 = OpTypePointer UniformConstant %24 +%51 = OpVariable %52 UniformConstant +%54 = OpTypePointer UniformConstant %25 +%53 = OpVariable %54 UniformConstant +%56 = OpTypePointer UniformConstant %26 +%55 = OpVariable %56 UniformConstant +%58 = OpTypePointer UniformConstant %28 +%57 = OpVariable %58 UniformConstant +%60 = OpTypePointer UniformConstant %28 +%59 = OpVariable %60 UniformConstant +%62 = OpTypePointer UniformConstant %29 +%61 = OpVariable %62 UniformConstant +%65 = OpTypePointer Input %18 +%64 = OpVariable %65 Input +%68 = OpTypeFunction %2 +%77 = OpTypeVector %12 2 +%85 = OpTypeVector %12 4 +%100 = OpTypeVector %4 3 +%112 = OpTypePointer Output %27 +%111 = OpVariable %112 Output +%122 = OpConstant %12 0 +%179 = OpVariable %112 Output +%184 = OpTypeVector %8 2 +%186 = OpTypeSampledImage %21 +%200 = OpTypePointer Output %8 +%199 = OpVariable %200 Output +%206 = OpTypeSampledImage %29 +%211 = OpConstant %8 0.0 +%67 = OpFunction %2 None %68 +%63 = OpLabel +%66 = OpLoad %18 %64 +%69 = OpLoad %11 %31 +%70 = OpLoad %13 %33 +%71 = OpLoad %14 %35 +%72 = OpLoad %15 %37 +%73 = OpLoad %16 %39 +%74 = OpLoad %17 %41 +OpBranch %75 +%75 = OpLabel +%76 = OpImageQuerySize %19 %72 +%78 = OpVectorShuffle %77 %66 %66 0 1 +%79 = OpBitcast %19 %78 +%80 = OpIMul %19 %76 %79 +%81 = OpCompositeConstruct %19 %3 %5 +%82 = OpSMod %19 %80 %81 +%83 = OpCompositeExtract %12 %66 2 %84 = OpBitcast %4 %83 -%85 = OpImageFetch %81 %67 %78 Sample %84 -%86 = OpCompositeExtract %12 %63 2 -%87 = OpBitcast %4 %86 -%88 = OpImageFetch %26 %68 %78 Sample %87 -%89 = OpCompositeExtract %8 %88 0 -%90 = OpImageRead %81 %69 %78 -%91 = OpCompositeExtract %4 %78 0 -%92 = OpIAdd %81 %82 %85 -%93 = OpConvertFToU %12 %89 -%94 = OpCompositeConstruct %81 %93 %93 %93 %93 -%95 = OpIAdd %81 %92 %94 -%96 = OpIAdd %81 %95 %90 -OpImageWrite %70 %91 %96 +%86 = OpImageFetch %85 %69 %82 Lod %84 +%87 = OpCompositeExtract %12 %66 2 +%88 = OpBitcast %4 %87 +%89 = OpImageFetch %85 %70 %82 Sample %88 +%90 = OpCompositeExtract %12 %66 2 +%91 = OpBitcast %4 %90 +%92 = OpImageFetch %27 %71 %82 Sample %91 +%93 = OpCompositeExtract %8 %92 0 +%94 = OpImageRead %85 %72 %82 +%95 = OpCompositeExtract %12 %66 2 +%96 = OpBitcast %4 %95 +%97 = OpCompositeExtract %12 %66 2 +%98 = OpBitcast %4 %97 +%99 = OpIAdd %4 %98 %6 +%101 = OpCompositeConstruct %100 %82 %96 +%102 = OpImageFetch %85 %73 %101 Lod %99 +%103 = OpCompositeExtract %4 %82 0 +%104 = OpIAdd %85 %86 %89 +%105 = OpConvertFToU %12 %93 +%106 = OpCompositeConstruct %85 %105 %105 %105 %105 +%107 = OpIAdd %85 %104 %106 +%108 = OpIAdd %85 %107 %94 +%109 = OpIAdd %85 %108 %102 +OpImageWrite %74 %103 %109 OpReturn OpFunctionEnd -%100 = OpFunction %2 None %65 -%97 = OpLabel -%101 = OpLoad %19 %40 -%102 = OpLoad %20 %42 -%103 = OpLoad %21 %44 -%104 = OpLoad %22 %46 -%105 = OpLoad %23 %48 -%106 = OpLoad %24 %50 -%107 = OpLoad %25 %52 -OpBranch %108 -%108 = OpLabel -%110 = OpImageQuerySizeLod %4 %101 %109 -%111 = OpImageQuerySizeLod %18 %102 %109 -%112 = OpImageQueryLevels %4 %102 -%113 = OpImageQuerySizeLod %18 %102 %6 -%115 = OpImageQuerySizeLod %114 %103 %109 -%116 = OpVectorShuffle %18 %115 %115 0 1 -%117 = OpImageQueryLevels %4 %103 -%118 = OpImageQuerySizeLod %114 %103 %6 -%119 = OpVectorShuffle %18 %118 %118 0 1 -%120 = OpImageQuerySizeLod %114 %103 %109 -%121 = OpCompositeExtract %4 %120 2 -%122 = OpImageQuerySizeLod %18 %104 %109 -%123 = OpImageQueryLevels %4 %104 -%124 = OpImageQuerySizeLod %18 %104 %6 -%125 = OpImageQuerySizeLod %114 %105 %109 -%126 = OpVectorShuffle %18 %125 %125 0 0 -%127 = OpImageQueryLevels %4 %105 -%128 = OpImageQuerySizeLod %114 %105 %6 -%129 = OpVectorShuffle %18 %128 %128 0 0 -%130 = OpImageQuerySizeLod %114 %105 %109 -%131 = OpCompositeExtract %4 %130 2 -%132 = OpImageQuerySizeLod %114 %106 %109 -%133 = OpImageQueryLevels %4 %106 -%134 = OpImageQuerySizeLod %114 %106 %6 -%135 = OpImageQuerySamples %4 %107 -%136 = OpCompositeExtract %4 %111 1 -%137 = OpIAdd %4 %110 %136 -%138 = OpCompositeExtract %4 %113 1 -%139 = OpIAdd %4 %137 %138 -%140 = OpCompositeExtract %4 %116 1 -%141 = OpIAdd %4 %139 %140 -%142 = OpCompositeExtract %4 %119 1 -%143 = OpIAdd %4 %141 %142 -%144 = OpIAdd %4 %143 %121 -%145 = OpCompositeExtract %4 %122 1 -%146 = OpIAdd %4 %144 %145 -%147 = OpCompositeExtract %4 %124 1 -%148 = OpIAdd %4 %146 %147 -%149 = OpCompositeExtract %4 %126 1 -%150 = OpIAdd %4 %148 %149 -%151 = OpCompositeExtract %4 %129 1 -%152 = OpIAdd %4 %150 %151 -%153 = OpIAdd %4 %152 %131 -%154 = OpCompositeExtract %4 %132 2 +%113 = OpFunction %2 None %68 +%110 = OpLabel +%114 = OpLoad %20 %43 +%115 = OpLoad %21 %45 +%116 = OpLoad %22 %47 +%117 = OpLoad %23 %49 +%118 = OpLoad %24 %51 +%119 = OpLoad %25 %53 +%120 = OpLoad %26 %55 +OpBranch %121 +%121 = OpLabel +%123 = OpImageQuerySizeLod %4 %114 %122 +%124 = OpImageQuerySizeLod %19 %115 %122 +%125 = OpImageQueryLevels %4 %115 +%126 = OpImageQuerySizeLod %19 %115 %6 +%127 = OpImageQuerySizeLod %100 %116 %122 +%128 = OpVectorShuffle %19 %127 %127 0 1 +%129 = OpImageQueryLevels %4 %116 +%130 = OpImageQuerySizeLod %100 %116 %6 +%131 = OpVectorShuffle %19 %130 %130 0 1 +%132 = OpImageQuerySizeLod %100 %116 %122 +%133 = OpCompositeExtract %4 %132 2 +%134 = OpImageQuerySizeLod %19 %117 %122 +%135 = OpImageQueryLevels %4 %117 +%136 = OpImageQuerySizeLod %19 %117 %6 +%137 = OpImageQuerySizeLod %100 %118 %122 +%138 = OpVectorShuffle %19 %137 %137 0 0 +%139 = OpImageQueryLevels %4 %118 +%140 = OpImageQuerySizeLod %100 %118 %6 +%141 = OpVectorShuffle %19 %140 %140 0 0 +%142 = OpImageQuerySizeLod %100 %118 %122 +%143 = OpCompositeExtract %4 %142 2 +%144 = OpImageQuerySizeLod %100 %119 %122 +%145 = OpImageQueryLevels %4 %119 +%146 = OpImageQuerySizeLod %100 %119 %6 +%147 = OpImageQuerySamples %4 %120 +%148 = OpCompositeExtract %4 %124 1 +%149 = OpIAdd %4 %123 %148 +%150 = OpCompositeExtract %4 %126 1 +%151 = OpIAdd %4 %149 %150 +%152 = OpCompositeExtract %4 %128 1 +%153 = OpIAdd %4 %151 %152 +%154 = OpCompositeExtract %4 %131 1 %155 = OpIAdd %4 %153 %154 -%156 = OpCompositeExtract %4 %134 2 -%157 = OpIAdd %4 %155 %156 -%158 = OpIAdd %4 %157 %135 -%159 = OpIAdd %4 %158 %112 -%160 = OpIAdd %4 %159 %117 -%161 = OpIAdd %4 %160 %133 -%162 = OpIAdd %4 %161 %123 -%163 = OpIAdd %4 %162 %127 -%164 = OpConvertSToF %8 %163 -%165 = OpCompositeConstruct %26 %164 %164 %164 %164 -OpStore %98 %165 +%156 = OpIAdd %4 %155 %133 +%157 = OpCompositeExtract %4 %134 1 +%158 = OpIAdd %4 %156 %157 +%159 = OpCompositeExtract %4 %136 1 +%160 = OpIAdd %4 %158 %159 +%161 = OpCompositeExtract %4 %138 1 +%162 = OpIAdd %4 %160 %161 +%163 = OpCompositeExtract %4 %141 1 +%164 = OpIAdd %4 %162 %163 +%165 = OpIAdd %4 %164 %143 +%166 = OpCompositeExtract %4 %144 2 +%167 = OpIAdd %4 %165 %166 +%168 = OpCompositeExtract %4 %146 2 +%169 = OpIAdd %4 %167 %168 +%170 = OpIAdd %4 %169 %147 +%171 = OpIAdd %4 %170 %125 +%172 = OpIAdd %4 %171 %129 +%173 = OpIAdd %4 %172 %145 +%174 = OpIAdd %4 %173 %135 +%175 = OpIAdd %4 %174 %139 +%176 = OpConvertSToF %8 %175 +%177 = OpCompositeConstruct %27 %176 %176 %176 %176 +OpStore %111 %177 OpReturn OpFunctionEnd -%168 = OpFunction %2 None %65 -%166 = OpLabel -%169 = OpLoad %20 %42 -%170 = OpLoad %27 %54 -OpBranch %171 -%171 = OpLabel -%173 = OpCompositeConstruct %172 %7 %7 -%175 = OpSampledImage %174 %169 %170 -%176 = OpImageSampleImplicitLod %26 %175 %173 -%177 = OpSampledImage %174 %169 %170 -%178 = OpImageSampleImplicitLod %26 %177 %173 ConstOffset %29 -%179 = OpSampledImage %174 %169 %170 -%180 = OpImageSampleExplicitLod %26 %179 %173 Lod %9 -%181 = OpSampledImage %174 %169 %170 -%182 = OpImageSampleExplicitLod %26 %181 %173 Lod|ConstOffset %9 %29 -%183 = OpFAdd %26 %176 %178 -%184 = OpFAdd %26 %183 %180 -%185 = OpFAdd %26 %184 %182 -OpStore %167 %185 +%180 = OpFunction %2 None %68 +%178 = OpLabel +%181 = OpLoad %21 %45 +%182 = OpLoad %28 %57 +OpBranch %183 +%183 = OpLabel +%185 = OpCompositeConstruct %184 %7 %7 +%187 = OpSampledImage %186 %181 %182 +%188 = OpImageSampleImplicitLod %27 %187 %185 +%189 = OpSampledImage %186 %181 %182 +%190 = OpImageSampleImplicitLod %27 %189 %185 ConstOffset %30 +%191 = OpSampledImage %186 %181 %182 +%192 = OpImageSampleExplicitLod %27 %191 %185 Lod %9 +%193 = OpSampledImage %186 %181 %182 +%194 = OpImageSampleExplicitLod %27 %193 %185 Lod|ConstOffset %9 %30 +%195 = OpFAdd %27 %188 %190 +%196 = OpFAdd %27 %195 %192 +%197 = OpFAdd %27 %196 %194 +OpStore %179 %197 OpReturn OpFunctionEnd -%189 = OpFunction %2 None %65 -%186 = OpLabel -%190 = OpLoad %27 %56 -%191 = OpLoad %28 %58 -OpBranch %192 -%192 = OpLabel -%193 = OpCompositeConstruct %172 %7 %7 -%195 = OpSampledImage %194 %191 %190 -%196 = OpImageSampleDrefImplicitLod %8 %195 %193 %7 -%197 = OpSampledImage %194 %191 %190 -%198 = OpImageSampleDrefExplicitLod %8 %197 %193 %7 Lod %199 -%200 = OpFAdd %8 %196 %198 -OpStore %187 %200 +%201 = OpFunction %2 None %68 +%198 = OpLabel +%202 = OpLoad %28 %59 +%203 = OpLoad %29 %61 +OpBranch %204 +%204 = OpLabel +%205 = OpCompositeConstruct %184 %7 %7 +%207 = OpSampledImage %206 %203 %202 +%208 = OpImageSampleDrefImplicitLod %8 %207 %205 %7 +%209 = OpSampledImage %206 %203 %202 +%210 = OpImageSampleDrefExplicitLod %8 %209 %205 %7 Lod %211 +%212 = OpFAdd %8 %208 %210 +OpStore %199 %212 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index a888581b1..46f4ee05e 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -6,6 +6,8 @@ var image_multisampled_src: texture_multisampled_2d; var image_depth_multisampled_src: texture_depth_multisampled_2d; [[group(0), binding(1)]] var image_storage_src: texture_storage_2d; +[[group(0), binding(5)]] +var image_array_src: texture_2d_array; [[group(0), binding(2)]] var image_dst: texture_storage_1d; [[group(0), binding(0)]] @@ -37,7 +39,8 @@ fn main([[builtin(local_invocation_id)]] local_id: vec3) { let value2_: vec4 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); let value3_: f32 = textureLoad(image_depth_multisampled_src, itc, i32(local_id.z)); let value4_: vec4 = textureLoad(image_storage_src, itc); - textureStore(image_dst, itc.x, (((value1_ + value2_) + vec4(u32(value3_))) + value4_)); + let value5_: vec4 = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); + textureStore(image_dst, itc.x, ((((value1_ + value2_) + vec4(u32(value3_))) + value4_) + value5_)); return; } From d55645ac1ef354d1ad016dff91ac8576d9cf1e5b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 12 Aug 2021 00:57:13 -0400 Subject: [PATCH 1218/2212] Fix bitflags at 1.2 (#1190) --- Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 0c169d9a9..9ef3860d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,8 @@ resolver = "2" all-features = true [dependencies] -bitflags = "1" +# bitflags 1.3 requires Rust-1.46 +bitflags = "~1.2" bit-set = "0.5" codespan-reporting = { version = "0.11.0", optional = true } fxhash = "0.2" From 0feea58a3420b1c2823ebcdbed2d0c1aa207d658 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 12 Aug 2021 13:08:29 -0400 Subject: [PATCH 1219/2212] [hlsl-out] re-order interface struct fields (#1189) --- src/back/hlsl/writer.rs | 111 ++++++++++++++++++++++------------ tests/out/hlsl/interface.hlsl | 6 +- tests/out/hlsl/quad-vert.hlsl | 6 +- 3 files changed, 80 insertions(+), 43 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index f46e4ee9a..5393b3eb7 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -29,6 +29,24 @@ struct EpStructMember { name: String, ty: Handle, binding: Option, + index: usize, +} + +#[derive(Eq, PartialEq, PartialOrd, Ord)] +enum InterfaceKey { + Location(u32), + BuiltIn(crate::BuiltIn), + Other, +} + +impl InterfaceKey { + fn new(binding: Option<&crate::Binding>) -> Self { + match binding { + Some(&crate::Binding::Location { location, .. }) => Self::Location(location), + Some(&crate::Binding::BuiltIn(bi)) => Self::BuiltIn(bi), + None => Self::Other, + } + } } #[derive(Copy, Clone, PartialEq)] @@ -166,7 +184,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write all entry points wrapped structs for ep in module.entry_points.iter() { - self.write_ep_input_struct(module, &ep.function, ep.stage, &ep.name)?; + let ep_input = self.write_ep_input_struct(module, &ep.function, ep.stage, &ep.name)?; + self.ep_inputs.push(ep_input); } // Write all regular functions @@ -300,8 +319,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { func: &crate::Function, stage: ShaderStage, entry_point_name: &str, - ) -> BackendResult { - if !func.arguments.is_empty() { + ) -> Result, Error> { + Ok(if !func.arguments.is_empty() { let struct_name_prefix = match stage { ShaderStage::Vertex => "VertexInput", ShaderStage::Fragment => "FragmentInput", @@ -310,48 +329,49 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let struct_name = format!("{}_{}", struct_name_prefix, entry_point_name); let mut members = Vec::with_capacity(func.arguments.len()); - - write!(self.out, "struct {}", &struct_name)?; - writeln!(self.out, " {{")?; - - for arg in func.arguments.iter() { + for (index, arg) in func.arguments.iter().enumerate() { let member_name = if let Some(ref name) = arg.name { name } else { "member" }; - let member = EpStructMember { + members.push(EpStructMember { name: self.namer.call_unique(member_name), ty: arg.ty, binding: arg.binding.clone(), - }; - - write!(self.out, "{}", back::INDENT)?; - self.write_type(module, member.ty)?; - write!(self.out, " {}", &member.name)?; - if let Some(ref binding) = member.binding { - self.write_semantic(binding, Some((stage, Io::Input)))?; - } - write!(self.out, ";")?; - writeln!(self.out)?; - - members.push(member); + index, + }); } + // Sort the members so that first come the user-defined varyings + // in ascending locations, and then built-ins. This allows VS and FS + // interfaces to match with regards to order. + members.sort_by_key(|m| InterfaceKey::new(m.binding.as_ref())); + + write!(self.out, "struct {}", &struct_name)?; + writeln!(self.out, " {{")?; + for m in members.iter() { + write!(self.out, "{}", back::INDENT)?; + self.write_type(module, m.ty)?; + write!(self.out, " {}", &m.name)?; + if let Some(ref binding) = m.binding { + self.write_semantic(binding, Some((stage, Io::Input)))?; + } + writeln!(self.out, ";")?; + } writeln!(self.out, "}};")?; writeln!(self.out)?; - let ep_input = EntryPointBinding { + // now bring back the old order + members.sort_by_key(|m| m.index); + + Some(EntryPointBinding { name: struct_name, members, - }; - - self.ep_inputs.push(Some(ep_input)); + }) } else { - self.ep_inputs.push(None); - } - - Ok(()) + None + }) } /// Helper method used to write global variables @@ -536,18 +556,36 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { module: &Module, handle: Handle, _block: bool, - members: &[crate::StructMember], + original_members: &[crate::StructMember], shader_stage: Option<(ShaderStage, Io)>, ) -> BackendResult { // Write struct name write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?; writeln!(self.out, " {{")?; - for (index, member) in members.iter().enumerate() { + let has_layout = original_members.iter().any(|m| m.offset != 0); + let has_binding = original_members.iter().any(|m| m.binding.is_some()); + //TODO: avoid heap allocation + let mut members = original_members + .iter() + .enumerate() + .map(|(index, m)| (index, m.ty, m.binding.clone())) + .collect::>(); + //Note: this is a bit of a hack. We need to re-order the output fields, but we can only do this + // for non-layouted structures. It may be possible for an WGSL program can use the same struct + // for both host sharing and the interface. This case isn't supported here. + if has_binding && !has_layout { + // Sort the members so that first come the user-defined varyings + // in ascending locations, and then built-ins. This allows VS and FS + // interfaces to match with regards to order. + members.sort_by_key(|&(_, _, ref binding)| InterfaceKey::new(binding.as_ref())); + } + + for (index, ty, binding) in members { // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; - match module.types[member.ty].inner { + match module.types[ty].inner { TypeInner::Array { base, size, @@ -584,7 +622,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { interpolation, sampling, .. - }) = member.binding + }) = binding { if let Some(interpolation) = interpolation { write!(self.out, "{} ", interpolation.to_hlsl_str())? @@ -598,7 +636,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } // Write the member type and name - self.write_type(module, member.ty)?; + self.write_type(module, ty)?; write!( self.out, " {}", @@ -607,11 +645,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - if let Some(ref binding) = member.binding { + if let Some(ref binding) = binding { self.write_semantic(binding, shader_stage)?; }; - write!(self.out, ";")?; - writeln!(self.out)?; + writeln!(self.out, ";")?; } writeln!(self.out, "}};")?; diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 1d6fc884b..4a46710a8 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -11,16 +11,16 @@ struct FragmentOutput { }; struct VertexInput_vertex { - uint vertex_index1 : SV_VertexID; - uint instance_index1 : SV_InstanceID; uint color1 : LOC10; + uint instance_index1 : SV_InstanceID; + uint vertex_index1 : SV_VertexID; }; struct FragmentInput_fragment { - VertexOutput in2; bool front_facing1 : SV_IsFrontFace; uint sample_index1 : SV_SampleIndex; uint sample_mask1 : SV_Coverage; + VertexOutput in2; }; struct ComputeInput_compute { diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index c0f0f1fbf..cf91b74ee 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -1,17 +1,17 @@ struct gl_PerVertex { float4 gl_Position : SV_Position; - float gl_PointSize : PSIZE; float gl_ClipDistance[1] : SV_ClipDistance; float gl_CullDistance[1] : SV_CullDistance; + float gl_PointSize : PSIZE; }; struct type10 { linear float2 member : LOC0; float4 gl_Position : SV_Position; - float gl_PointSize : PSIZE; float gl_ClipDistance[1] : SV_ClipDistance; float gl_CullDistance[1] : SV_CullDistance; + float gl_PointSize : PSIZE; }; static float2 v_uv = (float2)0; @@ -20,8 +20,8 @@ static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, float(0 static float2 a_pos1 = (float2)0; struct VertexInput_main { - float2 a_uv2 : LOC1; float2 a_pos2 : LOC0; + float2 a_uv2 : LOC1; }; void main1() From 1907a92928933f312da10daad85bdc6de7d5f9a9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 12 Aug 2021 22:48:27 -0400 Subject: [PATCH 1220/2212] Fix deserialization of arenas --- src/arena.rs | 7 ++----- src/block.rs | 7 ++----- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 4827433da..c7b9e8664 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -125,16 +125,13 @@ impl Iterator for Range { /// The arena can be indexed using the given handle to obtain /// a reference to the stored item. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] -#[cfg_attr( - any(feature = "serialize", feature = "deserialize"), - serde(transparent) -)] +#[cfg_attr(feature = "serialize", serde(transparent))] #[cfg_attr(test, derive(PartialEq))] pub struct Arena { /// Values of this arena. data: Vec, #[cfg(feature = "span")] - #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))] + #[cfg_attr(feature = "serialize", serde(skip))] span_info: Vec, } diff --git a/src/block.rs b/src/block.rs index d7bcaed63..b46293eab 100644 --- a/src/block.rs +++ b/src/block.rs @@ -4,14 +4,11 @@ use std::ops::{Deref, DerefMut, RangeBounds}; /// A code block is a vector of statements, with maybe a vector of spans. #[derive(Debug, Clone, Default)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] -#[cfg_attr( - any(feature = "serialize", feature = "deserialize"), - serde(transparent) -)] +#[cfg_attr(feature = "serialize", serde(transparent))] pub struct Block { body: Vec, #[cfg(feature = "span")] - #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))] + #[cfg_attr(feature = "serialize", serde(skip))] span_info: Vec, } From e59582469c586b99f025fa99508964d9026746b9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 13 Aug 2021 00:28:33 -0400 Subject: [PATCH 1221/2212] [hlsl-out] basic support for pointer arguments --- src/back/hlsl/writer.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 5393b3eb7..19aadd51f 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -760,7 +760,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { back::FunctionType::Function(handle) => { for (index, arg) in func.arguments.iter().enumerate() { // Write argument type - self.write_type(module, arg.ty)?; + let arg_ty = match module.types[arg.ty].inner { + // pointers in function arguments are expected and resolve to `inout` + TypeInner::Pointer { base, .. } => { + //TODO: can we narrow this down to just `in` when possible? + write!(self.out, "inout ")?; + base + } + _ => arg.ty, + }; + self.write_type(module, arg_ty)?; let argument_name = &self.names[&NameKey::FunctionArgument(handle, index as u32)]; From 27e4ba59e4918494fca1e4cc2222a2dfdaa4a888 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 13 Aug 2021 00:37:02 -0400 Subject: [PATCH 1222/2212] Validate that SampleLevel::Exact isn't used for comparisons --- src/back/msl/writer.rs | 2 +- src/front/spv/image.rs | 7 ++++++- src/valid/expression.rs | 6 ++++++ tests/out/analysis/shadow.info.ron | 2 +- tests/out/ir/shadow.ron | 2 +- 5 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 465992d82..f206973b1 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2625,7 +2625,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 17504 - if stack_size < 14000 || stack_size > 19000 { + if stack_size < 13000 || stack_size > 19000 { panic!("`put_block` stack size {} has changed!", stack_size); } } diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 72c10c123..fac750ddb 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -449,7 +449,12 @@ impl> super::Parser { spirv::ImageOperands::LOD => { let lod_expr = self.next()?; let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; - level = crate::SampleLevel::Exact(lod_handle); + level = if options.compare { + log::debug!("Assuming {:?} is zero", lod_handle); + crate::SampleLevel::Zero + } else { + crate::SampleLevel::Exact(lod_handle) + }; words_left -= 1; } spirv::ImageOperands::GRAD => { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 73cc0d132..2324fb518 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -93,6 +93,8 @@ pub enum ExpressionError { InvalidSampleOffset(crate::ImageDimension, Handle), #[error("Depth reference {0:?} is not a scalar float")] InvalidDepthReference(Handle), + #[error("Depth sample level can only be Auto or Zero")] + InvalidDepthSampleLevel, #[error("Sample level (exact) type {0:?} is not a scalar float")] InvalidSampleLevelExactType(Handle), #[error("Sample level (bias) type {0:?} is not a scalar float")] @@ -451,6 +453,10 @@ impl super::Validator { } => {} _ => return Err(ExpressionError::InvalidDepthReference(expr)), } + match level { + crate::SampleLevel::Auto | crate::SampleLevel::Zero => {} + _ => return Err(ExpressionError::InvalidDepthSampleLevel), + } } // check level properties diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 142cdb078..f5695163b 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -385,7 +385,7 @@ bits: 0, ), ), - ref_count: 1, + ref_count: 0, assignable_global: None, ty: Value(Scalar( kind: Float, diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 52fa481c8..c71064af8 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -1039,7 +1039,7 @@ coordinate: 72, array_index: Some(74), offset: None, - level: Exact(25), + level: Zero, depth_ref: Some(69), ), ], From 69b70f8cc3acb988fa3f34d6a615c8c02259428c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 13 Aug 2021 01:33:25 -0400 Subject: [PATCH 1223/2212] [hlsl-out] reorder fields when composing structs --- src/back/hlsl/writer.rs | 60 +++++++++++++++++++++++++---------- tests/out/hlsl/quad-vert.hlsl | 2 +- 2 files changed, 44 insertions(+), 18 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 19aadd51f..2ad28204a 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -32,7 +32,7 @@ struct EpStructMember { index: usize, } -#[derive(Eq, PartialEq, PartialOrd, Ord)] +#[derive(Clone, Eq, PartialEq, PartialOrd, Ord)] enum InterfaceKey { Location(u32), BuiltIn(crate::BuiltIn), @@ -49,6 +49,19 @@ impl InterfaceKey { } } +// Returns true for structures that need their members permuted, +// so that first come the user-defined varyings +// in ascending locations, and then built-ins. This allows VS and FS +// interfaces to match with regards to order. +fn needs_permutation(members: &[crate::StructMember]) -> bool { + //Note: this is a bit of a hack. We need to re-order the output fields, but we can only do this + // for non-layouted structures. It may be possible for an WGSL program can use the same struct + // for both host sharing and the interface. This case isn't supported here. + let has_layout = members.iter().any(|m| m.offset != 0); + let has_binding = members.iter().any(|m| m.binding.is_some()); + has_binding && !has_layout +} + #[derive(Copy, Clone, PartialEq)] enum Io { Input, @@ -563,21 +576,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?; writeln!(self.out, " {{")?; - let has_layout = original_members.iter().any(|m| m.offset != 0); - let has_binding = original_members.iter().any(|m| m.binding.is_some()); //TODO: avoid heap allocation let mut members = original_members .iter() .enumerate() .map(|(index, m)| (index, m.ty, m.binding.clone())) .collect::>(); - //Note: this is a bit of a hack. We need to re-order the output fields, but we can only do this - // for non-layouted structures. It may be possible for an WGSL program can use the same struct - // for both host sharing and the interface. This case isn't supported here. - if has_binding && !has_layout { - // Sort the members so that first come the user-defined varyings - // in ascending locations, and then built-ins. This allows VS and FS - // interfaces to match with regards to order. + if needs_permutation(original_members) { members.sort_by_key(|&(_, _, ref binding)| InterfaceKey::new(binding.as_ref())); } @@ -1240,24 +1245,45 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::Compose { ty, ref components } => { - let braces_init = match module.types[ty].inner { - TypeInner::Struct { .. } | TypeInner::Array { .. } => true, - _ => false, + let (braces_init, permutation) = match module.types[ty].inner { + TypeInner::Struct { ref members, .. } => { + let permutation = if needs_permutation(members) { + //TODO: avoid heap allocation. We can pre-compute this at the module leve. + let mut permutation = members + .iter() + .enumerate() + .map(|(index, m)| (index, InterfaceKey::new(m.binding.as_ref()))) + .collect::>(); + permutation.sort_by_key(|&(_, ref key)| key.clone()); + Some(permutation) + } else { + None + }; + (true, permutation) + } + TypeInner::Array { .. } => (true, None), + _ => (false, None), }; + if braces_init { write!(self.out, "{{ ")?; } else { self.write_type(module, ty)?; write!(self.out, "(")?; } - for (index, component) in components.iter().enumerate() { - self.write_expr(module, *component, func_ctx)?; - // Only write a comma if isn't the last element - if index != components.len().saturating_sub(1) { + + for index in 0..components.len() { + if index != 0 { // The leading space is for readability only write!(self.out, ", ")?; } + let comp_index = match permutation { + Some(ref perm) => perm[index].0, + None => index, + }; + self.write_expr(module, components[comp_index], func_ctx)?; } + if braces_init { write!(self.out, " }}")? } else { diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index cf91b74ee..72cf5a0d5 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -43,6 +43,6 @@ type10 main(VertexInput_main vertexinput_main) float _expr12 = perVertexStruct.gl_PointSize; float _expr13[1] = perVertexStruct.gl_ClipDistance; float _expr14[1] = perVertexStruct.gl_CullDistance; - const type10 type10_ = { _expr10, _expr11, _expr12, _expr13, _expr14 }; + const type10 type10_ = { _expr10, _expr11, _expr13, _expr14, _expr12 }; return type10_; } From 5415d8c7c44cd95608aa6a0907b0a03a0aca86b1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 13 Aug 2021 22:47:44 -0400 Subject: [PATCH 1224/2212] Fix atomics in workgroup storage --- src/back/hlsl/writer.rs | 2 +- src/front/wgsl/mod.rs | 2 ++ tests/in/globals.wgsl | 2 ++ tests/out/glsl/globals.main.Compute.glsl | 3 ++ tests/out/hlsl/globals.hlsl | 2 ++ tests/out/msl/globals.msl | 2 ++ tests/out/spv/globals.spvasm | 36 ++++++++++++++---------- tests/out/wgsl/globals.wgsl | 2 ++ 8 files changed, 35 insertions(+), 16 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 2ad28204a..8bebbdbc6 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -682,7 +682,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { /// Adds no trailing or leading whitespace pub(super) fn write_value_type(&mut self, module: &Module, inner: &TypeInner) -> BackendResult { match *inner { - TypeInner::Scalar { kind, width } => { + TypeInner::Scalar { kind, width } | TypeInner::Atomic { kind, width } => { write!(self.out, "{}", kind.to_hlsl_str(width)?)?; } TypeInner::Vector { size, kind, width } => { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 414674773..0a5be03fa 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3284,12 +3284,14 @@ impl Parser { } "atomicStore" => { let _ = lexer.next(); + emitter.start(context.expressions); lexer.open_arguments()?; let mut expression_ctx = context.as_expression(block, &mut emitter); let pointer = self.parse_atomic_pointer(lexer, expression_ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let value = self.parse_general_expression(lexer, expression_ctx)?; lexer.close_arguments()?; + block.extend(emitter.finish(context.expressions)); Some(crate::Statement::Store { pointer, value }) } "textureStore" => { diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index bab28b3fe..f1b1a41f1 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -3,8 +3,10 @@ let Foo: bool = true; var wg : array; +var at: atomic; [[stage(compute), workgroup_size(1)]] fn main() { wg[3] = 1.0; + atomicStore(&at, 2u); } diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index b498b6f4e..a0e999dc2 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -7,9 +7,12 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; shared float wg[10]; +shared uint at; + void main() { wg[3] = 1.0; + at = 2u; return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 0236e1827..4bcb132fb 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -1,10 +1,12 @@ static const bool Foo = true; groupshared float wg[10]; +groupshared uint at; [numthreads(1, 1, 1)] void main() { wg[3] = 1.0; + at = 2u; return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 7fcd970bb..28e732194 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -9,7 +9,9 @@ struct type2 { kernel void main1( threadgroup type2& wg +, threadgroup metal::atomic_uint& at ) { wg.inner[3] = 1.0; + metal::atomic_store_explicit(&at, 2u, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 0e85aa503..2e0bd6684 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 21 +; Bound: 26 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %15 "main" -OpExecutionMode %15 LocalSize 1 1 1 -OpDecorate %11 ArrayStride 4 +OpEntryPoint GLCompute %18 "main" +OpExecutionMode %18 LocalSize 1 1 1 +OpDecorate %12 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -17,17 +17,23 @@ OpDecorate %11 ArrayStride 4 %7 = OpConstant %8 3 %10 = OpTypeFloat 32 %9 = OpConstant %10 1.0 -%11 = OpTypeArray %10 %5 -%13 = OpTypePointer Workgroup %11 -%12 = OpVariable %13 Workgroup -%16 = OpTypeFunction %2 -%18 = OpTypePointer Workgroup %10 -%19 = OpConstant %6 3 -%15 = OpFunction %2 None %16 -%14 = OpLabel -OpBranch %17 +%11 = OpConstant %6 2 +%12 = OpTypeArray %10 %5 +%14 = OpTypePointer Workgroup %12 +%13 = OpVariable %14 Workgroup +%16 = OpTypePointer Workgroup %6 +%15 = OpVariable %16 Workgroup +%19 = OpTypeFunction %2 +%21 = OpTypePointer Workgroup %10 +%22 = OpConstant %6 3 +%24 = OpConstant %8 2 +%25 = OpConstant %6 256 +%18 = OpFunction %2 None %19 %17 = OpLabel -%20 = OpAccessChain %18 %12 %19 -OpStore %20 %9 +OpBranch %20 +%20 = OpLabel +%23 = OpAccessChain %21 %13 %22 +OpStore %23 %9 +OpAtomicStore %15 %24 %25 %11 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 36856539f..21c506ce5 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -1,9 +1,11 @@ let Foo: bool = true; var wg: array; +var at: atomic; [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { wg[3] = 1.0; + atomicStore(&at, 2u); return; } From 0d829d6bb0565986407bc4fb438ad2500e4b608a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 15 Aug 2021 15:05:01 -0400 Subject: [PATCH 1225/2212] hlsl-out: relational expressions --- src/back/hlsl/writer.rs | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 8bebbdbc6..dde9d128e 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1735,18 +1735,30 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Expression::Derivative { axis, expr } => { use crate::DerivativeAxis as Da; - write!( - self.out, - "{}(", - match axis { - Da::X => "ddx", - Da::Y => "ddy", - Da::Width => "fwidth", - } - )?; + let fun_str = match axis { + Da::X => "ddx", + Da::Y => "ddy", + Da::Width => "fwidth", + }; + write!(self.out, "{}(", fun_str)?; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")? } + Expression::Relational { fun, argument } => { + use crate::RelationalFunction as Rf; + + let fun_str = match fun { + Rf::All => "all", + Rf::Any => "any", + Rf::IsNan => "isnan", + Rf::IsInf => "isinf", + Rf::IsFinite => "isfinite", + Rf::IsNormal => "isnormal", + }; + write!(self.out, "{}(", fun_str)?; + self.write_expr(module, argument, func_ctx)?; + write!(self.out, ")")? + } Expression::Splat { size, value } => { // hlsl is not supported one value constructor // if we write, for example, int4(0), dxc returns error: @@ -1777,7 +1789,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } // Nothing to do here, since call expression already cached Expression::CallResult(_) | Expression::AtomicResult { .. } => {} - _ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))), } if !closing_bracket.is_empty() { From 2dfcb7fcf0ba186bb7a11ffdf630a72f6156ac93 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 15 Aug 2021 22:21:52 -0400 Subject: [PATCH 1226/2212] [spv-in] treat Grad on depth textures as level 0 --- src/front/spv/image.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index fac750ddb..742624278 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -462,9 +462,18 @@ impl> super::Parser { let grad_x_handle = self.lookup_expression.lookup(grad_x_expr)?.handle; let grad_y_expr = self.next()?; let grad_y_handle = self.lookup_expression.lookup(grad_y_expr)?.handle; - level = crate::SampleLevel::Gradient { - x: grad_x_handle, - y: grad_y_handle, + level = if options.compare { + log::debug!( + "Assuming gradients {:?} and {:?} are not greater than 1", + grad_x_handle, + grad_y_handle + ); + crate::SampleLevel::Zero + } else { + crate::SampleLevel::Gradient { + x: grad_x_handle, + y: grad_y_handle, + } }; words_left -= 2; } From d7af2a84b7508f58684279db415cc07998833484 Mon Sep 17 00:00:00 2001 From: Kneelawk Date: Sat, 14 Aug 2021 08:40:42 -0700 Subject: [PATCH 1227/2212] Move case-closing-brace writer inside cases loop --- src/back/wgsl/writer.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 46958be80..ec2683fca 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -804,9 +804,9 @@ impl Writer { if case.fall_through { writeln!(self.out, "{}fallthrough;", INDENT.repeat(indent + 2))?; } - } - writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; + writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; + } } if !default.is_empty() { From 7613798aed17c83f55375c91aafe53ab55106444 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 15 Aug 2021 23:12:44 -0400 Subject: [PATCH 1228/2212] [wgsl-in] parse identifiers before builtin function calls --- src/front/wgsl/mod.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 0a5be03fa..2f2b5e5c6 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2108,13 +2108,6 @@ impl Parser { let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; (false, handle) } - Token::Word(word) => { - let handle = match self.parse_function_call_inner(lexer, word, ctx.reborrow())? { - Some(handle) => handle, - None => self.parse_primary_expression(lexer, ctx.reborrow())?, - }; - (true, handle) - } _ => { let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; (true, handle) From c6a6afdf370585001de53490fe78bf0ecab37346 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 16 Aug 2021 15:13:43 +0100 Subject: [PATCH 1229/2212] [spv-in] Parse OpNoLine --- src/front/spv/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index c214ad8bd..de8bc47df 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -858,6 +858,7 @@ impl> Parser { let _row_id = self.next()?; let _col_id = self.next()?; } + Op::NoLine => inst.expect(1)?, Op::Undef => { inst.expect(3)?; let (type_id, id, handle) = From 4b1363e122abf71d15e374ff384dba7ce857ad84 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 16 Aug 2021 08:50:50 -0700 Subject: [PATCH 1230/2212] [spv-out] Creating SPIR-V types is not, in fact, fallible. There's no need for functions that construct SPIR-V types to be fallible, or for their callers to check for errors. As a consequence of this change, there may be other functions that no longer need to be fallible, but Rust doesn't warn and Clippy doesn't lint, so we'll have to address them as they come up. --- src/back/spv/block.rs | 49 ++++++++++++++++++------------------ src/back/spv/index.rs | 10 ++++---- src/back/spv/mod.rs | 2 +- src/back/spv/writer.rs | 56 +++++++++++++++++++++--------------------- 4 files changed, 58 insertions(+), 59 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index b02fa720e..4ff0aef32 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -53,7 +53,7 @@ impl Writer { kind: crate::ScalarKind::Float, width: 4, pointer_class: Some(spirv::StorageClass::Output), - }))?; + })); let index_y_id = self.get_index_constant(1)?; body.push(Instruction::access_chain( float_ptr_type_id, @@ -68,7 +68,7 @@ impl Writer { kind: crate::ScalarKind::Float, width: 4, pointer_class: None, - }))?; + })); body.push(Instruction::load(float_type_id, load_id, access_id, None)); let neg_id = self.id_gen.next(); @@ -86,7 +86,7 @@ impl Writer { } impl<'w> BlockContext<'w> { - fn get_type_id(&mut self, lookup_type: LookupType) -> Result { + fn get_type_id(&mut self, lookup_type: LookupType) -> Word { self.writer.get_type_id(lookup_type) } @@ -167,7 +167,7 @@ impl<'w> BlockContext<'w> { kind: component_kind, width: 4, pointer_class: None, - }))?; + })); let reconciled_id = self.gen_id(); block.body.push(Instruction::unary( @@ -180,13 +180,12 @@ impl<'w> BlockContext<'w> { }; // Find the SPIR-V type for the combined coordinates/index vector. - let combined_coordinate_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(result_size), - kind: component_kind, - width: 4, - pointer_class: None, - }))?; + let combined_coordinate_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(result_size), + kind: component_kind, + width: 4, + pointer_class: None, + })); // Schmear the coordinates and index together. let id = self.gen_id(); @@ -227,7 +226,7 @@ impl<'w> BlockContext<'w> { expr_handle: Handle, block: &mut Block, ) -> Result<(), Error> { - let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty)?; + let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty); let id = match self.ir_function.expressions[expr_handle] { crate::Expression::Access { base, index: _ } if self.is_intermediate(base) => { @@ -619,7 +618,7 @@ impl<'w> BlockContext<'w> { kind, width, pointer_class: None, - }))?; + })); self.temp_list.clear(); self.temp_list.resize(size as usize, arg2_id); @@ -826,7 +825,7 @@ impl<'w> BlockContext<'w> { kind: crate::ScalarKind::Float, width: 4, pointer_class: None, - }))?; + })); Instruction::image_fetch(load_result_type_id, id, image_id, coordinate_id) } _ => Instruction::image_fetch(result_type_id, id, image_id, coordinate_id), @@ -893,15 +892,15 @@ impl<'w> BlockContext<'w> { kind: crate::ScalarKind::Float, width: 4, pointer_class: None, - }))? + })) } else { result_type_id }; // OpTypeSampledImage - let image_type_id = self.get_type_id(LookupType::Handle(image_type))?; + let image_type_id = self.get_type_id(LookupType::Handle(image_type)); let sampled_image_type_id = - self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id }))?; + self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id })); let sampler_id = self.get_image_id(sampler); let coordinate_id = @@ -1062,7 +1061,7 @@ impl<'w> BlockContext<'w> { kind: crate::ScalarKind::Bool, width, pointer_class: None, - }))?; + })); let id = self.gen_id(); block.body.push(Instruction::composite_construct( @@ -1131,7 +1130,7 @@ impl<'w> BlockContext<'w> { kind: crate::ScalarKind::Sint, width: 4, pointer_class: None, - }))? + })) }; let (query_op, level_id) = match class { @@ -1200,7 +1199,7 @@ impl<'w> BlockContext<'w> { kind: crate::ScalarKind::Sint, width: 4, pointer_class: None, - }))?; + })); let id_extended = self.gen_id(); let mut inst = Instruction::image_query( spirv::Op::ImageQuerySizeLod, @@ -1272,7 +1271,7 @@ impl<'w> BlockContext<'w> { TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), TypeResolution::Value(ref inner) => LookupType::Local(make_local(inner).unwrap()), }; - let result_type_id = self.get_type_id(result_lookup_ty)?; + let result_type_id = self.get_type_id(result_lookup_ty); // The id of the boolean `and` of all dynamic bounds checks up to this point. If // `None`, then we haven't done any dynamic bounds checks yet. @@ -1301,7 +1300,7 @@ impl<'w> BlockContext<'w> { let combined = self.gen_id(); block.body.push(Instruction::binary( spirv::Op::LogicalAnd, - self.writer.get_bool_type_id()?, + self.writer.get_bool_type_id(), combined, prior_checks, comparison_id, @@ -1705,7 +1704,7 @@ impl<'w> BlockContext<'w> { let type_id = match result { Some(expr) => { self.cached[expr] = id; - self.get_expression_type_id(&self.fun_info[expr].ty)? + self.get_expression_type_id(&self.fun_info[expr].ty) } None => self.writer.void_type, }; @@ -1724,7 +1723,7 @@ impl<'w> BlockContext<'w> { result, } => { let id = self.gen_id(); - let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty)?; + let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty); self.cached[result] = id; @@ -1856,7 +1855,7 @@ impl<'w> BlockContext<'w> { // Or it may be the end of the self.function. None => match self.ir_function.result { Some(ref result) if self.function.entry_point_context.is_none() => { - let type_id = self.get_type_id(LookupType::Handle(result.ty))?; + let type_id = self.get_type_id(LookupType::Handle(result.ty)); let null_id = self.writer.write_constant_null(type_id); Instruction::return_value(null_id) } diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 85662136d..1496e726b 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -77,7 +77,7 @@ impl<'w> BlockContext<'w> { let length_id = self.gen_id(); block.body.push(Instruction::array_length( - self.writer.get_uint_type_id()?, + self.writer.get_uint_type_id(), length_id, structure_id, last_member_index, @@ -145,7 +145,7 @@ impl<'w> BlockContext<'w> { let max_index_id = self.gen_id(); block.body.push(Instruction::binary( spirv::Op::ISub, - self.writer.get_uint_type_id()?, + self.writer.get_uint_type_id(), max_index_id, length_id, const_one_id, @@ -207,7 +207,7 @@ impl<'w> BlockContext<'w> { block.body.push(Instruction::ext_inst( self.writer.gl450_ext_inst_id, spirv::GLOp::UMin, - self.writer.get_uint_type_id()?, + self.writer.get_uint_type_id(), restricted_index_id, &[index_id, max_index_id], )); @@ -280,7 +280,7 @@ impl<'w> BlockContext<'w> { let condition_id = self.gen_id(); block.body.push(Instruction::binary( spirv::Op::ULessThan, - self.writer.get_bool_type_id()?, + self.writer.get_bool_type_id(), condition_id, index_id, length_id, @@ -382,7 +382,7 @@ impl<'w> BlockContext<'w> { index: Handle, block: &mut Block, ) -> Result { - let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty)?; + let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty); let base_id = self.cached[base]; let index_id = self.cached[index]; diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 55c1d6ba4..5f4eac72f 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -360,7 +360,7 @@ impl BlockContext<'_> { self.writer.id_gen.next() } - fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Result { + fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Word { self.writer.get_expression_type_id(tr) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 31a2f9892..3b247db40 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -154,9 +154,9 @@ impl Writer { Err(Error::MissingCapabilities(capabilities.to_vec())) } - pub(super) fn get_type_id(&mut self, lookup_ty: LookupType) -> Result { + pub(super) fn get_type_id(&mut self, lookup_ty: LookupType) -> Word { if let Entry::Occupied(e) = self.lookup_type.entry(lookup_ty) { - Ok(*e.get()) + *e.get() } else { match lookup_ty { LookupType::Handle(_handle) => unreachable!("Handles are populated at start"), @@ -165,7 +165,7 @@ impl Writer { } } - pub(super) fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Result { + pub(super) fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Word { let lookup_ty = match *tr { TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), TypeResolution::Value(ref inner) => LookupType::Local(make_local(inner).unwrap()), @@ -179,7 +179,7 @@ impl Writer { handle: Handle, class: spirv::StorageClass, ) -> Result { - let ty_id = self.get_type_id(LookupType::Handle(handle))?; + let ty_id = self.get_type_id(LookupType::Handle(handle)); if let crate::TypeInner::Pointer { .. } = arena[handle].inner { return Ok(ty_id); } @@ -198,7 +198,7 @@ impl Writer { }) } - pub(super) fn get_uint_type_id(&mut self) -> Result { + pub(super) fn get_uint_type_id(&mut self) -> Word { let local_type = LocalType::Value { vector_size: None, kind: crate::ScalarKind::Uint, @@ -208,7 +208,7 @@ impl Writer { self.get_type_id(local_type.into()) } - pub(super) fn get_bool_type_id(&mut self) -> Result { + pub(super) fn get_bool_type_id(&mut self) -> Word { let local_type = LocalType::Value { vector_size: None, kind: crate::ScalarKind::Bool, @@ -274,7 +274,7 @@ impl Writer { argument.ty, spirv::StorageClass::UniformConstant, )?, - false => self.get_type_id(LookupType::Handle(argument.ty))?, + false => self.get_type_id(LookupType::Handle(argument.ty)), }; if let Some(ref mut list) = varying_ids { let id = if let Some(ref binding) = argument.binding { @@ -293,7 +293,7 @@ impl Writer { let struct_id = self.id_gen.next(); let mut constituent_ids = Vec::with_capacity(members.len()); for member in members { - let type_id = self.get_type_id(LookupType::Handle(member.ty))?; + let type_id = self.get_type_id(LookupType::Handle(member.ty)); let name = member.name.as_ref().map(AsRef::as_ref); let binding = member.binding.as_ref().unwrap(); let varying_id = @@ -323,7 +323,7 @@ impl Writer { handle_id: if handle_ty { let id = self.id_gen.next(); prelude.body.push(Instruction::load( - self.get_type_id(LookupType::Handle(argument.ty))?, + self.get_type_id(LookupType::Handle(argument.ty)), id, argument_id, None, @@ -342,7 +342,7 @@ impl Writer { if let Some(ref mut list) = varying_ids { let class = spirv::StorageClass::Output; if let Some(ref binding) = result.binding { - let type_id = self.get_type_id(LookupType::Handle(result.ty))?; + let type_id = self.get_type_id(LookupType::Handle(result.ty)); let varying_id = self.write_varying(ir_module, class, None, result.ty, binding)?; list.push(varying_id); @@ -355,7 +355,7 @@ impl Writer { ir_module.types[result.ty].inner { for member in members { - let type_id = self.get_type_id(LookupType::Handle(member.ty))?; + let type_id = self.get_type_id(LookupType::Handle(member.ty)); let name = member.name.as_ref().map(AsRef::as_ref); let binding = member.binding.as_ref().unwrap(); let varying_id = @@ -372,7 +372,7 @@ impl Writer { } self.void_type } else { - self.get_type_id(LookupType::Handle(result.ty))? + self.get_type_id(LookupType::Handle(result.ty)) } } None => self.void_type, @@ -412,7 +412,7 @@ impl Writer { continue; } let id = self.id_gen.next(); - let result_type_id = self.get_type_id(LookupType::Handle(var.ty))?; + let result_type_id = self.get_type_id(LookupType::Handle(var.ty)); let gv = &mut self.global_variables[handle.index()]; prelude .body @@ -567,7 +567,7 @@ impl Writer { } } - fn write_type_declaration_local(&mut self, local_ty: LocalType) -> Result { + fn write_type_declaration_local(&mut self, local_ty: LocalType) -> Word { let id = self.id_gen.next(); let instruction = match local_ty { LocalType::Value { @@ -587,7 +587,7 @@ impl Writer { kind, width, pointer_class: None, - }))?; + })); Instruction::type_vector(id, scalar_id, size) } LocalType::Matrix { @@ -600,11 +600,11 @@ impl Writer { kind: crate::ScalarKind::Float, width, pointer_class: None, - }))?; + })); Instruction::type_matrix(id, vector_id, columns) } LocalType::Pointer { base, class } => { - let type_id = self.get_type_id(LookupType::Handle(base))?; + let type_id = self.get_type_id(LookupType::Handle(base)); Instruction::type_pointer(id, class, type_id) } LocalType::Value { @@ -618,7 +618,7 @@ impl Writer { kind, width, pointer_class: None, - }))?; + })); Instruction::type_pointer(id, class, type_id) } // all the samplers and image types go through `write_type_declaration_arena` @@ -630,7 +630,7 @@ impl Writer { self.lookup_type.insert(LookupType::Local(local_ty), id); instruction.to_words(&mut self.logical_layout.declarations); - Ok(id) + id } fn write_type_declaration_arena( @@ -678,7 +678,7 @@ impl Writer { kind, width, pointer_class: None, - }))?; + })); Instruction::type_vector(id, scalar_id, size) } crate::TypeInner::Matrix { @@ -691,7 +691,7 @@ impl Writer { kind: crate::ScalarKind::Float, width, pointer_class: None, - }))?; + })); Instruction::type_matrix(id, vector_id, columns) } crate::TypeInner::Image { @@ -720,7 +720,7 @@ impl Writer { }; let dim = map_dim(dim); self.check(dim.required_capabilities())?; - let type_id = self.get_type_id(LookupType::Local(local_type))?; + let type_id = self.get_type_id(LookupType::Local(local_type)); Instruction::type_image(id, type_id, dim, arrayed, class) } crate::TypeInner::Sampler { comparison: _ } => Instruction::type_sampler(id), @@ -729,7 +729,7 @@ impl Writer { self.decorate(id, Decoration::ArrayStride, &[stride]); } - let type_id = self.get_type_id(LookupType::Handle(base))?; + let type_id = self.get_type_id(LookupType::Handle(base)); match size { crate::ArraySize::Constant(const_handle) => { let length_id = self.constant_ids[const_handle.index()]; @@ -795,13 +795,13 @@ impl Writer { )); } - let member_id = self.get_type_id(LookupType::Handle(member.ty))?; + let member_id = self.get_type_id(LookupType::Handle(member.ty)); member_ids.push(member_id); } Instruction::type_struct(id, member_ids.as_slice()) } crate::TypeInner::Pointer { base, class } => { - let type_id = self.get_type_id(LookupType::Handle(base))?; + let type_id = self.get_type_id(LookupType::Handle(base)); let raw_class = map_storage_class(class); Instruction::type_pointer(id, raw_class, type_id) } @@ -817,7 +817,7 @@ impl Writer { kind, width, pointer_class: None, - }))?; + })); Instruction::type_pointer(id, raw_class, type_id) } }; @@ -861,7 +861,7 @@ impl Writer { kind: value.scalar_kind(), width, pointer_class: None, - }))?; + })); let (solo, pair); let instruction = match *value { crate::ScalarValue::Sint(val) => { @@ -927,7 +927,7 @@ impl Writer { constituent_ids.push(constituent_id); } - let type_id = self.get_type_id(LookupType::Handle(ty))?; + let type_id = self.get_type_id(LookupType::Handle(ty)); Instruction::constant_composite(type_id, id, constituent_ids.as_slice()) .to_words(&mut self.logical_layout.declarations); Ok(()) From 8e0295178c33f154d8b6d9006ae5b0a72703a13f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 16 Aug 2021 12:04:34 -0400 Subject: [PATCH 1231/2212] [spv-in] allow float16 and float64 --- src/front/spv/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index de8bc47df..6a6da2d57 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -69,6 +69,8 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Int8, spirv::Capability::Int16, spirv::Capability::Int64, + spirv::Capability::Float16, + spirv::Capability::Float64, spirv::Capability::Geometry, // tricky ones spirv::Capability::UniformBufferArrayDynamicIndexing, From 220081c4b2c9064c960c0eb37c1d3ea21d9b5411 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 16 Aug 2021 12:15:44 -0400 Subject: [PATCH 1232/2212] [msl-out] pass-through workgroup storage --- src/back/msl/writer.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index f206973b1..92b7ef640 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -386,9 +386,10 @@ impl crate::StorageClass { crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } | crate::StorageClass::Private + | crate::StorageClass::WorkGroup | crate::StorageClass::PushConstant | crate::StorageClass::Handle => true, - _ => false, + crate::StorageClass::Function => false, } } From ec64eaae6ba511d7f4b6635ba46df11558d50224 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 16 Aug 2021 10:56:06 -0400 Subject: [PATCH 1233/2212] [spv-in] work around storage image access --- src/front/spv/mod.rs | 56 ++++++++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 17 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 6a6da2d57..2dd40ea56 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -211,6 +211,19 @@ bitflags::bitflags! { } } +impl DecorationFlags { + fn to_storage_access(self) -> crate::StorageAccess { + let mut access = crate::StorageAccess::all(); + if self.contains(DecorationFlags::NON_READABLE) { + access &= !crate::StorageAccess::LOAD; + } + if self.contains(DecorationFlags::NON_WRITABLE) { + access &= !crate::StorageAccess::STORE; + } + access + } +} + #[derive(Debug, PartialEq)] enum Majority { Column, @@ -3226,14 +3239,7 @@ impl> Parser { .remove(&(id, i)) .unwrap_or_default(); - let mut member_access = crate::StorageAccess::all(); - if decor.flags.contains(DecorationFlags::NON_READABLE) { - member_access &= !crate::StorageAccess::LOAD; - } - if decor.flags.contains(DecorationFlags::NON_WRITABLE) { - member_access &= !crate::StorageAccess::STORE; - } - storage_access |= member_access; + storage_access |= decor.flags.to_storage_access(); member_lookups.push(LookupMember { type_id, @@ -3643,10 +3649,31 @@ impl> Parser { let mut dec = self.future_decor.remove(&id).unwrap_or_default(); let original_ty = self.lookup_type.lookup(type_id)?.handle; - let effective_ty = match module.types[original_ty].inner { - crate::TypeInner::Pointer { base, class: _ } => base, - _ => original_ty, + let mut effective_ty = original_ty; + if let crate::TypeInner::Pointer { base, class: _ } = module.types[original_ty].inner { + effective_ty = base; }; + if let crate::TypeInner::Image { + dim, + arrayed, + class: crate::ImageClass::Storage { format, access: _ }, + } = module.types[effective_ty].inner + { + // Storage image types in IR have to contain the access, but not in the SPIR-V. + // The same image type in SPIR-V can be used (and has to be used) for multiple images. + // So we copy the type out and apply the variable access decorations. + let access = dec.flags.to_storage_access(); + let ty = crate::Type { + name: None, + inner: crate::TypeInner::Image { + dim, + arrayed, + class: crate::ImageClass::Storage { format, access }, + }, + }; + effective_ty = module.types.append(ty, Default::default()); + } + let ext_class = match self.lookup_storage_buffer_types.get(&effective_ty) { Some(&access) => ExtendedClass::Global(crate::StorageClass::Storage { access }), None => map_storage_class(storage_class)?, @@ -3666,12 +3693,7 @@ impl> Parser { let (inner, var) = match ext_class { ExtendedClass::Global(mut class) => { if let crate::StorageClass::Storage { ref mut access } = class { - if dec.flags.contains(DecorationFlags::NON_READABLE) { - *access &= !crate::StorageAccess::LOAD; - } - if dec.flags.contains(DecorationFlags::NON_WRITABLE) { - *access &= !crate::StorageAccess::STORE; - } + *access &= dec.flags.to_storage_access(); } let var = crate::GlobalVariable { binding: dec.resource_binding(), From c39810233274b0973fe0fcbfedb3ced8c9f685b6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 16 Aug 2021 13:06:53 -0400 Subject: [PATCH 1234/2212] [msl-out]: avoid inner structure for run-time array sizes --- src/back/msl/writer.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 92b7ef640..cd50217c8 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -801,12 +801,15 @@ impl Writer { crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => { write!(self.out, ".{}", back::COMPONENTS[index as usize])?; } - crate::TypeInner::Matrix { .. } => { - write!(self.out, "[{}]", index)?; - } - crate::TypeInner::Array { .. } => { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(_), + .. + } => { write!(self.out, ".{}[{}]", WRAPPED_ARRAY_FIELD, index)?; } + crate::TypeInner::Array { .. } | crate::TypeInner::Matrix { .. } => { + write!(self.out, "[{}]", index)?; + } _ => { // unexpected indexing, should fail validation } From ab1e932e164ae2a567ba66ca04fd838c42f5cf3d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 17 Aug 2021 00:09:10 -0400 Subject: [PATCH 1235/2212] [glsl-out] use common bake prefix --- src/back/glsl/mod.rs | 9 +- tests/out/glsl/access.atomics.Compute.glsl | 28 +-- tests/out/glsl/access.foo.Vertex.glsl | 4 +- tests/out/glsl/boids.main.Compute.glsl | 160 +++++++++--------- tests/out/glsl/interpolate.main.Vertex.glsl | 18 +- tests/out/glsl/operators.main.Compute.glsl | 6 +- tests/out/glsl/quad-vert.main.Vertex.glsl | 20 +-- tests/out/glsl/shadow.fs_main.Fragment.glsl | 30 ++-- tests/out/glsl/skybox.fs_main.Fragment.glsl | 4 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 18 +- tests/out/glsl/texture-arg.main.Fragment.glsl | 8 +- 11 files changed, 151 insertions(+), 154 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c87095d2d..cccf959ec 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -66,9 +66,6 @@ pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450] /// List of supported es glsl versions pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; -//TODO: use `super::BAKE_PREFIX` instead -const BAKE_PREFIX: &str = "_expr"; - pub type BindingMap = std::collections::BTreeMap; impl crate::AtomicFunction { @@ -1345,7 +1342,7 @@ impl<'a, W: Write> Writer<'a, W> { } else { let min_ref_count = ctx.expressions[handle].bake_ref_count(); if min_ref_count <= ctx.info[handle].ref_count { - Some(format!("{}{}", BAKE_PREFIX, handle.index())) + Some(format!("{}{}", super::BAKE_PREFIX, handle.index())) } else { None } @@ -1677,7 +1674,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { write!(self.out, "{}", INDENT.repeat(indent))?; if let Some(expr) = result { - let name = format!("{}{}", BAKE_PREFIX, expr.index()); + let name = format!("{}{}", super::BAKE_PREFIX, expr.index()); let result = self.module.functions[function].result.as_ref().unwrap(); self.write_type(result.ty)?; write!(self.out, " {} = ", name)?; @@ -1705,7 +1702,7 @@ impl<'a, W: Write> Writer<'a, W> { result, } => { write!(self.out, "{}", INDENT.repeat(indent))?; - let res_name = format!("{}{}", BAKE_PREFIX, result.index()); + let res_name = format!("{}{}", super::BAKE_PREFIX, result.index()); let res_ty = ctx.info[result].ty.inner_with(&self.module.types); self.write_value_type(res_ty)?; write!(self.out, " {} = ", res_name)?; diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index b4254c36d..f0a982862 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -16,20 +16,20 @@ buffer Bar_block_0Cs { void main() { int tmp = 0; int value = _group_0_binding_0.atom; - int _expr6 = atomicAdd(_group_0_binding_0.atom, 5); - tmp = _expr6; - int _expr9 = atomicAnd(_group_0_binding_0.atom, 5); - tmp = _expr9; - int _expr12 = atomicOr(_group_0_binding_0.atom, 5); - tmp = _expr12; - int _expr15 = atomicXor(_group_0_binding_0.atom, 5); - tmp = _expr15; - int _expr18 = atomicMin(_group_0_binding_0.atom, 5); - tmp = _expr18; - int _expr21 = atomicMax(_group_0_binding_0.atom, 5); - tmp = _expr21; - int _expr24 = atomicExchange(_group_0_binding_0.atom, 5); - tmp = _expr24; + int _e6 = atomicAdd(_group_0_binding_0.atom, 5); + tmp = _e6; + int _e9 = atomicAnd(_group_0_binding_0.atom, 5); + tmp = _e9; + int _e12 = atomicOr(_group_0_binding_0.atom, 5); + tmp = _e12; + int _e15 = atomicXor(_group_0_binding_0.atom, 5); + tmp = _e15; + int _e18 = atomicMin(_group_0_binding_0.atom, 5); + tmp = _e18; + int _e21 = atomicMax(_group_0_binding_0.atom, 5); + tmp = _e21; + int _e24 = atomicExchange(_group_0_binding_0.atom, 5); + tmp = _e24; _group_0_binding_0.atom = value; return; } diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index 6bd543677..c128dff78 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -19,8 +19,8 @@ void main() { foo1 = 1.0; mat4x4 matrix = _group_0_binding_0.matrix; uvec2 arr[2] = _group_0_binding_0.arr; - vec4 _expr13 = _group_0_binding_0.matrix[3]; - float b = _expr13.x; + vec4 _e13 = _group_0_binding_0.matrix[3]; + float b = _e13.x; int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)]; _group_0_binding_0.matrix[1][2] = 1.0; _group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index add4e0f9d..7a925d554 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -45,112 +45,112 @@ void main() { if ((index >= 1500u)) { return; } - vec2 _expr10 = _group_0_binding_1.particles[index].pos; - vPos = _expr10; - vec2 _expr15 = _group_0_binding_1.particles[index].vel; - vVel = _expr15; + vec2 _e10 = _group_0_binding_1.particles[index].pos; + vPos = _e10; + vec2 _e15 = _group_0_binding_1.particles[index].vel; + vVel = _e15; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); bool loop_init = true; while(true) { if (!loop_init) { - uint _expr86 = i; - i = (_expr86 + 1u); + uint _e86 = i; + i = (_e86 + 1u); } loop_init = false; - uint _expr37 = i; - if ((_expr37 >= 1500u)) { + uint _e37 = i; + if ((_e37 >= 1500u)) { break; } - uint _expr39 = i; - if ((_expr39 == index)) { + uint _e39 = i; + if ((_e39 == index)) { continue; } - uint _expr42 = i; - vec2 _expr45 = _group_0_binding_1.particles[_expr42].pos; - pos = _expr45; - uint _expr47 = i; - vec2 _expr50 = _group_0_binding_1.particles[_expr47].vel; - vel = _expr50; - vec2 _expr51 = pos; - vec2 _expr52 = vPos; - float _expr55 = _group_0_binding_0.rule1Distance; - if ((distance(_expr51, _expr52) < _expr55)) { - vec2 _expr57 = cMass; - vec2 _expr58 = pos; - cMass = (_expr57 + _expr58); - int _expr60 = cMassCount; - cMassCount = (_expr60 + 1); + uint _e42 = i; + vec2 _e45 = _group_0_binding_1.particles[_e42].pos; + pos = _e45; + uint _e47 = i; + vec2 _e50 = _group_0_binding_1.particles[_e47].vel; + vel = _e50; + vec2 _e51 = pos; + vec2 _e52 = vPos; + float _e55 = _group_0_binding_0.rule1Distance; + if ((distance(_e51, _e52) < _e55)) { + vec2 _e57 = cMass; + vec2 _e58 = pos; + cMass = (_e57 + _e58); + int _e60 = cMassCount; + cMassCount = (_e60 + 1); } - vec2 _expr63 = pos; - vec2 _expr64 = vPos; - float _expr67 = _group_0_binding_0.rule2Distance; - if ((distance(_expr63, _expr64) < _expr67)) { - vec2 _expr69 = colVel; - vec2 _expr70 = pos; - vec2 _expr71 = vPos; - colVel = (_expr69 - (_expr70 - _expr71)); + vec2 _e63 = pos; + vec2 _e64 = vPos; + float _e67 = _group_0_binding_0.rule2Distance; + if ((distance(_e63, _e64) < _e67)) { + vec2 _e69 = colVel; + vec2 _e70 = pos; + vec2 _e71 = vPos; + colVel = (_e69 - (_e70 - _e71)); } - vec2 _expr74 = pos; - vec2 _expr75 = vPos; - float _expr78 = _group_0_binding_0.rule3Distance; - if ((distance(_expr74, _expr75) < _expr78)) { - vec2 _expr80 = cVel; - vec2 _expr81 = vel; - cVel = (_expr80 + _expr81); - int _expr83 = cVelCount; - cVelCount = (_expr83 + 1); + vec2 _e74 = pos; + vec2 _e75 = vPos; + float _e78 = _group_0_binding_0.rule3Distance; + if ((distance(_e74, _e75) < _e78)) { + vec2 _e80 = cVel; + vec2 _e81 = vel; + cVel = (_e80 + _e81); + int _e83 = cVelCount; + cVelCount = (_e83 + 1); } } - int _expr89 = cMassCount; - if ((_expr89 > 0)) { - vec2 _expr92 = cMass; - int _expr93 = cMassCount; - vec2 _expr97 = vPos; - cMass = ((_expr92 / vec2(float(_expr93))) - _expr97); + int _e89 = cMassCount; + if ((_e89 > 0)) { + vec2 _e92 = cMass; + int _e93 = cMassCount; + vec2 _e97 = vPos; + cMass = ((_e92 / vec2(float(_e93))) - _e97); } - int _expr99 = cVelCount; - if ((_expr99 > 0)) { - vec2 _expr102 = cVel; - int _expr103 = cVelCount; - cVel = (_expr102 / vec2(float(_expr103))); + int _e99 = cVelCount; + if ((_e99 > 0)) { + vec2 _e102 = cVel; + int _e103 = cVelCount; + cVel = (_e102 / vec2(float(_e103))); } - vec2 _expr107 = vVel; - vec2 _expr108 = cMass; - float _expr110 = _group_0_binding_0.rule1Scale; - vec2 _expr113 = colVel; - float _expr115 = _group_0_binding_0.rule2Scale; - vec2 _expr118 = cVel; - float _expr120 = _group_0_binding_0.rule3Scale; - vVel = (((_expr107 + (_expr108 * _expr110)) + (_expr113 * _expr115)) + (_expr118 * _expr120)); - vec2 _expr123 = vVel; - vec2 _expr125 = vVel; - vVel = (normalize(_expr123) * clamp(length(_expr125), 0.0, 0.1)); - vec2 _expr131 = vPos; - vec2 _expr132 = vVel; - float _expr134 = _group_0_binding_0.deltaT; - vPos = (_expr131 + (_expr132 * _expr134)); - vec2 _expr137 = vPos; - if ((_expr137.x < -1.0)) { + vec2 _e107 = vVel; + vec2 _e108 = cMass; + float _e110 = _group_0_binding_0.rule1Scale; + vec2 _e113 = colVel; + float _e115 = _group_0_binding_0.rule2Scale; + vec2 _e118 = cVel; + float _e120 = _group_0_binding_0.rule3Scale; + vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); + vec2 _e123 = vVel; + vec2 _e125 = vVel; + vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.1)); + vec2 _e131 = vPos; + vec2 _e132 = vVel; + float _e134 = _group_0_binding_0.deltaT; + vPos = (_e131 + (_e132 * _e134)); + vec2 _e137 = vPos; + if ((_e137.x < -1.0)) { vPos.x = 1.0; } - vec2 _expr143 = vPos; - if ((_expr143.x > 1.0)) { + vec2 _e143 = vPos; + if ((_e143.x > 1.0)) { vPos.x = -1.0; } - vec2 _expr149 = vPos; - if ((_expr149.y < -1.0)) { + vec2 _e149 = vPos; + if ((_e149.y < -1.0)) { vPos.y = 1.0; } - vec2 _expr155 = vPos; - if ((_expr155.y > 1.0)) { + vec2 _e155 = vPos; + if ((_e155.y > 1.0)) { vPos.y = -1.0; } - vec2 _expr164 = vPos; - _group_0_binding_2.particles[index].pos = _expr164; - vec2 _expr168 = vVel; - _group_0_binding_2.particles[index].vel = _expr168; + vec2 _e164 = vPos; + _group_0_binding_2.particles[index].pos = _e164; + vec2 _e168 = vVel; + _group_0_binding_2.particles[index].vel = _e168; return; } diff --git a/tests/out/glsl/interpolate.main.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl index 5aefc78ed..76cdd0ac0 100644 --- a/tests/out/glsl/interpolate.main.Vertex.glsl +++ b/tests/out/glsl/interpolate.main.Vertex.glsl @@ -28,15 +28,15 @@ void main() { out1.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); out1.perspective_centroid = 2197.0; out1.perspective_sample = 2744.0; - FragmentInput _expr30 = out1; - gl_Position = _expr30.position; - _vs2fs_location0 = _expr30.flat1; - _vs2fs_location1 = _expr30.linear; - _vs2fs_location2 = _expr30.linear_centroid; - _vs2fs_location3 = _expr30.linear_sample; - _vs2fs_location4 = _expr30.perspective; - _vs2fs_location5 = _expr30.perspective_centroid; - _vs2fs_location6 = _expr30.perspective_sample; + FragmentInput _e30 = out1; + gl_Position = _e30.position; + _vs2fs_location0 = _e30.flat1; + _vs2fs_location1 = _e30.linear; + _vs2fs_location2 = _e30.linear_centroid; + _vs2fs_location3 = _e30.linear_sample; + _vs2fs_location4 = _e30.perspective; + _vs2fs_location5 = _e30.perspective_centroid; + _vs2fs_location6 = _e30.perspective_sample; return; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 332e991c8..a146d42bb 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -30,9 +30,9 @@ int unary() { } void main() { - vec4 _expr3 = builtins(); - vec4 _expr4 = splat(); - int _expr5 = unary(); + vec4 _e3 = builtins(); + vec4 _e4 = splat(); + int _e5 = unary(); return; } diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index 60f74cd94..e42681b2e 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -29,10 +29,10 @@ layout(location = 0) in vec2 _p2vs_location0; layout(location = 0) smooth out vec2 _vs2fs_location0; void main2() { - vec2 _expr12 = a_uv1; - v_uv = _expr12; - vec2 _expr13 = a_pos1; - perVertexStruct.gen_gl_Position = vec4(_expr13.x, _expr13.y, 0.0, 1.0); + vec2 _e12 = a_uv1; + v_uv = _e12; + vec2 _e13 = a_pos1; + perVertexStruct.gen_gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); return; } @@ -42,12 +42,12 @@ void main() { a_uv1 = a_uv; a_pos1 = a_pos; main2(); - vec2 _expr10 = v_uv; - vec4 _expr11 = perVertexStruct.gen_gl_Position; - float _expr12 = perVertexStruct.gen_gl_PointSize; - float _expr13[1] = perVertexStruct.gen_gl_ClipDistance; - float _expr14[1] = perVertexStruct.gen_gl_CullDistance; - type10 _tmp_return = type10(_expr10, _expr11, _expr12, _expr13, _expr14); + vec2 _e10 = v_uv; + vec4 _e11 = perVertexStruct.gen_gl_Position; + float _e12 = perVertexStruct.gen_gl_PointSize; + float _e13[1] = perVertexStruct.gen_gl_ClipDistance; + float _e14[1] = perVertexStruct.gen_gl_CullDistance; + type10 _tmp_return = type10(_e10, _e11, _e12, _e13, _e14); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 95466dc3a..e3502e2bc 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -29,8 +29,8 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } vec2 flip_correction = vec2(0.5, -0.5); vec2 light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - float _expr26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); - return _expr26; + float _e26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); + return _e26; } void main() { @@ -42,26 +42,26 @@ void main() { bool loop_init = true; while(true) { if (!loop_init) { - uint _expr40 = i; - i = (_expr40 + 1u); + uint _e40 = i; + i = (_e40 + 1u); } loop_init = false; - uint _expr12 = i; - uvec4 _expr14 = _group_0_binding_0.num_lights; - if ((_expr12 >= min(_expr14.x, 10u))) { + uint _e12 = i; + uvec4 _e14 = _group_0_binding_0.num_lights; + if ((_e12 >= min(_e14.x, 10u))) { break; } - uint _expr19 = i; - Light light = _group_0_binding_1.data[_expr19]; - uint _expr22 = i; - float _expr25 = fetch_shadow(_expr22, (light.proj * position)); + uint _e19 = i; + Light light = _group_0_binding_1.data[_e19]; + uint _e22 = i; + float _e25 = fetch_shadow(_e22, (light.proj * position)); vec3 light_dir = normalize((light.pos.xyz - position.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); - vec3 _expr34 = color; - color = (_expr34 + ((_expr25 * diffuse) * light.color.xyz)); + vec3 _e34 = color; + color = (_e34 + ((_e25 * diffuse) * light.color.xyz)); } - vec3 _expr43 = color; - _fs2p_location0 = vec4(_expr43, 1.0); + vec3 _e43 = color; + _fs2p_location0 = vec4(_e43, 1.0); return; } diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index 9cf825635..fa0b46f02 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -15,8 +15,8 @@ layout(location = 0) out vec4 _fs2p_location0; void main() { VertexOutput in1 = VertexOutput(gl_FragCoord, _vs2fs_location0); - vec4 _expr5 = texture(_group_0_binding_1, vec3(in1.uv)); - _fs2p_location0 = _expr5; + vec4 _e5 = texture(_group_0_binding_1, vec3(in1.uv)); + _fs2p_location0 = _e5; return; } diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index bae80935e..5f66bc1c6 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -21,15 +21,15 @@ void main() { int tmp2_ = 0; tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); - int _expr10 = tmp1_; - int _expr16 = tmp2_; - vec4 pos = vec4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); - vec4 _expr27 = _group_0_binding_0.view[0]; - vec4 _expr31 = _group_0_binding_0.view[1]; - vec4 _expr35 = _group_0_binding_0.view[2]; - mat3x3 inv_model_view = transpose(mat3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz)); - mat4x4 _expr40 = _group_0_binding_0.proj_inv; - vec4 unprojected = (_expr40 * pos); + int _e10 = tmp1_; + int _e16 = tmp2_; + vec4 pos = vec4(((float(_e10) * 4.0) - 1.0), ((float(_e16) * 4.0) - 1.0), 0.0, 1.0); + vec4 _e27 = _group_0_binding_0.view[0]; + vec4 _e31 = _group_0_binding_0.view[1]; + vec4 _e35 = _group_0_binding_0.view[2]; + mat3x3 inv_model_view = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); + mat4x4 _e40 = _group_0_binding_0.proj_inv; + vec4 unprojected = (_e40 * pos); VertexOutput _tmp_return = VertexOutput(pos, (inv_model_view * unprojected.xyz)); gl_Position = _tmp_return.position; _vs2fs_location0 = _tmp_return.uv; diff --git a/tests/out/glsl/texture-arg.main.Fragment.glsl b/tests/out/glsl/texture-arg.main.Fragment.glsl index 2c71caf43..3d46d1cd8 100644 --- a/tests/out/glsl/texture-arg.main.Fragment.glsl +++ b/tests/out/glsl/texture-arg.main.Fragment.glsl @@ -8,13 +8,13 @@ uniform highp sampler2D _group_0_binding_0; layout(location = 0) out vec4 _fs2p_location0; vec4 test(highp sampler2D Passed_Texture) { - vec4 _expr7 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); - return _expr7; + vec4 _e7 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); + return _e7; } void main() { - vec4 _expr2 = test(_group_0_binding_0); - _fs2p_location0 = _expr2; + vec4 _e2 = test(_group_0_binding_0); + _fs2p_location0 = _e2; return; } From 939e8f0a7b899893c6b8d47ff61dfab75bb666f1 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 17 Aug 2021 00:06:43 -0400 Subject: [PATCH 1236/2212] [msl-out] insert padding struct initialization --- src/back/msl/writer.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index cd50217c8..6c95750e3 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3,7 +3,7 @@ use crate::{ arena::Handle, back, proc::{self, NameKey, TypeResolution}, - valid, FastHashMap, + valid, FastHashMap, FastHashSet, }; use std::{ fmt::{Display, Error as FmtError, Formatter, Write}, @@ -313,9 +313,10 @@ pub struct Writer { namer: proc::Namer, runtime_sized_buffers: FastHashMap, usize>, #[cfg(test)] - put_expression_stack_pointers: crate::FastHashSet<*const ()>, + put_expression_stack_pointers: FastHashSet<*const ()>, #[cfg(test)] - put_block_stack_pointers: crate::FastHashSet<*const ()>, + put_block_stack_pointers: FastHashSet<*const ()>, + struct_member_pads: FastHashSet<(Handle, u32)>, } fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { @@ -476,6 +477,7 @@ impl Writer { put_expression_stack_pointers: Default::default(), #[cfg(test)] put_block_stack_pointers: Default::default(), + struct_member_pads: FastHashSet::default(), } } @@ -653,10 +655,14 @@ impl Writer { } crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { write!(self.out, "{} {{", &self.names[&NameKey::Type(ty)])?; - for (i, &component) in components.iter().enumerate() { - if i != 0 { + for (index, &component) in components.iter().enumerate() { + if index != 0 { write!(self.out, ", ")?; } + // insert padding initialization, if needed + if self.struct_member_pads.contains(&(ty, index as u32)) { + write!(self.out, "{{}}, ")?; + } self.put_expression(component, context, true)?; } write!(self.out, "}}")?; @@ -1694,6 +1700,7 @@ impl Writer { self.namer .reset(module, super::keywords::RESERVED, &[], &mut self.names); self.runtime_sized_buffers.clear(); + self.struct_member_pads.clear(); writeln!( self.out, @@ -1785,8 +1792,8 @@ impl Writer { for (index, member) in members.iter().enumerate() { // quick and dirty way to figure out if we need this... if member.binding.is_none() && member.offset > last_offset { + self.struct_member_pads.insert((handle, index as u32)); let pad = member.offset - last_offset; - //TODO: adjust the struct initializers writeln!(self.out, "{}char _pad{}[{}];", back::INDENT, index, pad)?; } let ty_inner = &module.types[member.ty].inner; From b11f094287e8044fe295aaf34ba3e6853345209f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 16 Aug 2021 21:33:56 +0100 Subject: [PATCH 1237/2212] [wgsl-out] Write pointers types and loads --- src/back/wgsl/writer.rs | 143 +++-- src/front/wgsl/mod.rs | 901 ++++++++++++++------------- tests/out/wgsl/246-collatz-comp.wgsl | 2 +- tests/out/wgsl/access.wgsl | 2 +- tests/out/wgsl/boids.wgsl | 2 +- tests/out/wgsl/collatz.wgsl | 2 +- 6 files changed, 583 insertions(+), 469 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index ec2683fca..829f93380 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -6,11 +6,6 @@ use crate::{ }; use std::fmt::Write; -// This is a hack: we need to pass a pointer to an atomic, -// but generally the backend isn't putting "&" in front of every pointer. -// Some more general handling of pointers is needed to be implemented here. -const ATOMIC_REFERENCE: &str = "&"; - /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; @@ -537,9 +532,16 @@ impl Writer { )?; } TypeInner::Pointer { base, class } => { + let (storage, maybe_access) = storage_class_str(class); + if let Some(class) = storage { + write!(self.out, "ptr<{}, ", class)?; + if let Some(access) = maybe_access { + write!(self.out, ", {}", access)?; + } + } self.write_type(module, base)?; - if let Some(storage_class) = storage_class_str(class) { - write!(self.out, "<{}>", storage_class)?; + if storage.is_some() { + write!(self.out, ">")?; } } _ => { @@ -673,15 +675,22 @@ impl Writer { } write!(self.out, "{}", INDENT.repeat(indent))?; - let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { - crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { - crate::TypeInner::Atomic { .. } => true, - _ => false, - }, - _ => false, + let (is_ptr, is_atomic) = match *func_ctx.info[pointer].ty.inner_with(&module.types) + { + crate::TypeInner::Pointer { base, .. } => ( + func_ctx.expressions[pointer].should_deref(), + match module.types[base].inner { + crate::TypeInner::Atomic { .. } => true, + _ => false, + }, + ), + _ => (false, false), }; if is_atomic { - write!(self.out, "atomicStore({}", ATOMIC_REFERENCE)?; + write!(self.out, "atomicStore(")?; + if !is_ptr { + write!(self.out, "&")?; + } self.write_expr(module, pointer, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, value, func_ctx)?; @@ -727,8 +736,13 @@ impl Writer { self.start_named_expr(module, result, func_ctx, &res_name)?; self.named_expressions.insert(result, res_name); + let is_ptr = func_ctx.expressions[pointer].should_deref(); + let fun_str = fun.to_wgsl(); - write!(self.out, "atomic{}({}", fun_str, ATOMIC_REFERENCE)?; + write!(self.out, "atomic{}(", fun_str)?; + if !is_ptr { + write!(self.out, "&")?; + } self.write_expr(module, pointer, func_ctx)?; if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun { write!(self.out, ", ")?; @@ -973,10 +987,22 @@ impl Writer { } // TODO: copy-paste from glsl-out Expression::AccessIndex { base, index } => { - self.write_expr(module, base, func_ctx)?; - let base_ty_res = &func_ctx.info[base].ty; let mut resolved = base_ty_res.inner_with(&module.types); + + let deref = match *resolved { + TypeInner::Pointer { .. } => func_ctx.expressions[base].should_deref(), + _ => false, + }; + + if deref { + write!(self.out, "(*")?; + } + self.write_expr(module, base, func_ctx)?; + if deref { + write!(self.out, ")")?; + } + let base_ty_handle = match *resolved { TypeInner::Pointer { base, class: _ } => { resolved = &module.types[base].inner; @@ -1169,15 +1195,26 @@ impl Writer { write!(self.out, ")")?; } Expression::Load { pointer } => { - let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { - crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { - crate::TypeInner::Atomic { .. } => true, - _ => false, - }, - _ => false, - }; + let (is_pointer, is_atomic) = + match *func_ctx.info[pointer].ty.inner_with(&module.types) { + crate::TypeInner::Pointer { base, .. } => ( + func_ctx.expressions[pointer].should_deref(), + match module.types[base].inner { + crate::TypeInner::Atomic { .. } => true, + _ => false, + }, + ), + _ => (false, false), + }; if is_atomic { - write!(self.out, "atomicLoad({}", ATOMIC_REFERENCE)?; + write!(self.out, "atomicLoad(")?; + if !is_pointer { + // Write an indirection in case the underlying + // expression isn't a pointer but a reference + write!(self.out, "&")?; + } + } else if is_pointer { + write!(self.out, "*")?; } self.write_expr(module, pointer, func_ctx)?; if is_atomic { @@ -1377,8 +1414,13 @@ impl Writer { // First write global name and storage class if supported write!(self.out, "var")?; - if let Some(storage_class) = storage_class_str(global.class) { - write!(self.out, "<{}>", storage_class)?; + let (storage, maybe_access) = storage_class_str(global.class); + if let Some(class) = storage { + write!(self.out, "<{}", class)?; + if let Some(access) = maybe_access { + write!(self.out, ", {}", access)?; + } + write!(self.out, ">")?; } write!(self.out, " {}: ", name)?; @@ -1525,6 +1567,21 @@ impl Writer { } } +impl crate::Expression { + /// Wether an expression should be dereferenced, this is false when the + /// expression returns a reference instead of a pointer + fn should_deref(&self) -> bool { + match *self { + // Variables in the typifier have pointer types but in wgsl they + // have reference types and shouldn't be dereferenced + crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) + // Access chains might have pointer types but wgsl considers them as references + | crate::Expression::AccessIndex {..} | crate::Expression::Access {..} => false, + _ => true, + } + } +} + fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { use crate::BuiltIn as Bi; @@ -1629,21 +1686,29 @@ fn sampling_str(sampling: crate::Sampling) -> &'static str { } } -fn storage_class_str(storage_class: crate::StorageClass) -> Option<&'static str> { +fn storage_class_str( + storage_class: crate::StorageClass, +) -> (Option<&'static str>, Option<&'static str>) { use crate::StorageClass as Sc; - match storage_class { - Sc::Private => Some("private"), - Sc::Uniform => Some("uniform"), - Sc::Storage { access } => Some(if access.contains(crate::StorageAccess::STORE) { - "storage,read_write" - } else { - "storage" + ( + Some(match storage_class { + Sc::Private => "private", + Sc::Uniform => "uniform", + Sc::Storage { access } => { + if access.contains(crate::StorageAccess::STORE) { + return (Some("storage"), Some("read_write")); + } else { + "storage" + } + } + Sc::PushConstant => "push_constant", + Sc::WorkGroup => "workgroup", + Sc::Handle => return (None, None), + Sc::Function => "function", }), - Sc::PushConstant => Some("push_constant"), - Sc::WorkGroup => Some("workgroup"), - Sc::Function | Sc::Handle => None, - } + None, + ) } fn map_binding_to_attribute( diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2f2b5e5c6..4bbc70231 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2103,6 +2103,17 @@ impl Parser { ctx.expressions.append(expr, NagaSpan::ByteRange(span)), ) } + Token::Operation('*') => { + let _ = lexer.next(); + let expr = crate::Expression::Load { + pointer: self.parse_singular_expression(lexer, ctx.reborrow())?, + }; + let span = self.peek_scope(lexer); + ( + false, + ctx.expressions.append(expr, NagaSpan::ByteRange(span)), + ) + } Token::Operation('&') => { let _ = lexer.next(); let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; @@ -2854,7 +2865,7 @@ impl Parser { is_uniform_control_flow: bool, ) -> Result<(), Error<'a>> { self.push_scope(Scope::Statement, lexer); - let (word, word_span) = match lexer.peek() { + match lexer.peek() { (Token::Separator(';'), _) => { let _ = lexer.next(); self.pop_scope(lexer); @@ -2880,83 +2891,36 @@ impl Parser { ); return Ok(()); } - (Token::Word(word), span) => (word, span), - other => return Err(Error::Unexpected(other, ExpectedToken::Statement)), - }; - let mut emitter = super::Emitter::default(); - let statement = match word { - "let" => { - let _ = lexer.next(); - emitter.start(context.expressions); - let (name, name_span) = lexer.next_ident_with_span()?; - let given_ty = if lexer.skip(Token::Separator(':')) { - let (ty, _access) = - self.parse_type_decl(lexer, None, context.types, context.constants)?; - Some(ty) - } else { - None - }; - lexer.expect(Token::Operation('='))?; - let expr_id = self - .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; - lexer.expect(Token::Separator(';'))?; - if let Some(ty) = given_ty { - // prepare the typifier, but work around mutable borrowing... - let _ = context - .as_expression(block, &mut emitter) - .resolve_type(expr_id)?; - let expr_inner = context.typifier.get(expr_id, context.types); - let given_inner = &context.types[ty].inner; - if given_inner != expr_inner { - log::error!( - "Given type {:?} doesn't match expected {:?}", - given_inner, - expr_inner - ); - return Err(Error::InitializationTypeMismatch(name_span, ty)); - } - } - block.extend(emitter.finish(context.expressions)); - context.lookup_ident.insert(name, expr_id); - context - .named_expressions - .insert(expr_id, String::from(name)); - None - } - "var" => { - let _ = lexer.next(); - enum Init { - Empty, - Constant(Handle), - Variable(Handle), - } - - let (name, name_span) = lexer.next_ident_with_span()?; - let given_ty = if lexer.skip(Token::Separator(':')) { - let (ty, _access) = - self.parse_type_decl(lexer, None, context.types, context.constants)?; - Some(ty) - } else { - None - }; - - let (init, ty) = if lexer.skip(Token::Operation('=')) { - emitter.start(context.expressions); - let value = self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?; - block.extend(emitter.finish(context.expressions)); - - // prepare the typifier, but work around mutable borrowing... - let _ = context - .as_expression(block, &mut emitter) - .resolve_type(value)?; - - //TODO: share more of this code with `let` arm - let ty = match given_ty { - Some(ty) => { - let expr_inner = context.typifier.get(value, context.types); + (Token::Word(word), word_span) => { + let mut emitter = super::Emitter::default(); + let statement = match word { + "let" => { + let _ = lexer.next(); + emitter.start(context.expressions); + let (name, name_span) = lexer.next_ident_with_span()?; + let given_ty = if lexer.skip(Token::Separator(':')) { + let (ty, _access) = self.parse_type_decl( + lexer, + None, + context.types, + context.constants, + )?; + Some(ty) + } else { + None + }; + lexer.expect(Token::Operation('='))?; + let expr_id = self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?; + lexer.expect(Token::Separator(';'))?; + if let Some(ty) = given_ty { + // prepare the typifier, but work around mutable borrowing... + let _ = context + .as_expression(block, &mut emitter) + .resolve_type(expr_id)?; + let expr_inner = context.typifier.get(expr_id, context.types); let given_inner = &context.types[ty].inner; if given_inner != expr_inner { log::error!( @@ -2966,378 +2930,463 @@ impl Parser { ); return Err(Error::InitializationTypeMismatch(name_span, ty)); } - ty - } - None => { - // register the type, if needed - match context.typifier[value].clone() { - TypeResolution::Handle(ty) => ty, - TypeResolution::Value(inner) => context.types.fetch_or_append( - crate::Type { name: None, inner }, - Default::default(), - ), - } - } - }; - - let init = match context.expressions[value] { - crate::Expression::Constant(handle) if is_uniform_control_flow => { - Init::Constant(handle) - } - _ => Init::Variable(value), - }; - (init, ty) - } else { - match given_ty { - Some(ty) => (Init::Empty, ty), - None => { - log::error!("Variable '{}' without an initializer needs a type", name); - return Err(Error::MissingType(name_span)); } + block.extend(emitter.finish(context.expressions)); + context.lookup_ident.insert(name, expr_id); + context + .named_expressions + .insert(expr_id, String::from(name)); + None } - }; + "var" => { + let _ = lexer.next(); + enum Init { + Empty, + Constant(Handle), + Variable(Handle), + } - lexer.expect(Token::Separator(';'))?; - let var_id = context.variables.append( - crate::LocalVariable { - name: Some(name.to_owned()), - ty, - init: match init { - Init::Constant(value) => Some(value), - _ => None, - }, - }, - NagaSpan::ByteRange(name_span), - ); + let (name, name_span) = lexer.next_ident_with_span()?; + let given_ty = if lexer.skip(Token::Separator(':')) { + let (ty, _access) = self.parse_type_decl( + lexer, + None, + context.types, + context.constants, + )?; + Some(ty) + } else { + None + }; - // Doesn't make sense to assign a span to cached lookup - let expr_id = context - .expressions - .append(crate::Expression::LocalVariable(var_id), Default::default()); - context.lookup_ident.insert(name, expr_id); + let (init, ty) = if lexer.skip(Token::Operation('=')) { + emitter.start(context.expressions); + let value = self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?; + block.extend(emitter.finish(context.expressions)); - if let Init::Variable(value) = init { - Some(crate::Statement::Store { - pointer: expr_id, - value, - }) - } else { - None - } - } - "return" => { - let _ = lexer.next(); - let value = if lexer.peek().0 != Token::Separator(';') { - emitter.start(context.expressions); - let handle = self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?; - block.extend(emitter.finish(context.expressions)); - Some(handle) - } else { - None - }; - lexer.expect(Token::Separator(';'))?; - Some(crate::Statement::Return { value }) - } - "if" => { - let _ = lexer.next(); - lexer.expect(Token::Paren('('))?; - emitter.start(context.expressions); - let condition = self - .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; - block.extend(emitter.finish(context.expressions)); - lexer.expect(Token::Paren(')'))?; + // prepare the typifier, but work around mutable borrowing... + let _ = context + .as_expression(block, &mut emitter) + .resolve_type(value)?; - let accept = self.parse_block(lexer, context.reborrow(), false)?; - let mut elsif_stack = Vec::new(); - let mut elseif_span_start = lexer.current_byte_offset(); - while lexer.skip(Token::Word("elseif")) { - let mut sub_emitter = super::Emitter::default(); - - lexer.expect(Token::Paren('('))?; - sub_emitter.start(context.expressions); - let other_condition = self.parse_general_expression( - lexer, - context.as_expression(block, &mut sub_emitter), - )?; - let other_emit = sub_emitter.finish(context.expressions); - lexer.expect(Token::Paren(')'))?; - let other_block = self.parse_block(lexer, context.reborrow(), false)?; - elsif_stack.push((elseif_span_start, other_condition, other_emit, other_block)); - elseif_span_start = lexer.current_byte_offset(); - } - let mut reject = if lexer.skip(Token::Word("else")) { - self.parse_block(lexer, context.reborrow(), false)? - } else { - crate::Block::new() - }; - let span_end = lexer.current_byte_offset(); - // reverse-fold the else-if blocks - //Note: we may consider uplifting this to the IR - for (other_span_start, other_cond, other_emit, other_block) in - elsif_stack.into_iter().rev() - { - let sub_stmt = crate::Statement::If { - condition: other_cond, - accept: other_block, - reject, - }; - reject = crate::Block::new(); - reject.extend(other_emit); - reject.push(sub_stmt, NagaSpan::ByteRange(other_span_start..span_end)) - } - - Some(crate::Statement::If { - condition, - accept, - reject, - }) - } - "switch" => { - let _ = lexer.next(); - emitter.start(context.expressions); - lexer.expect(Token::Paren('('))?; - let selector = self - .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; - lexer.expect(Token::Paren(')'))?; - block.extend(emitter.finish(context.expressions)); - lexer.expect(Token::Paren('{'))?; - let mut cases = Vec::new(); - let mut default = crate::Block::new(); - - loop { - // cases + default - match lexer.next() { - (Token::Word("case"), _) => { - // parse a list of values - let value = loop { - let value = lexer.next_sint_literal()?; - if lexer.skip(Token::Separator(',')) { - if lexer.skip(Token::Separator(':')) { - break value; + //TODO: share more of this code with `let` arm + let ty = match given_ty { + Some(ty) => { + let expr_inner = context.typifier.get(value, context.types); + let given_inner = &context.types[ty].inner; + if given_inner != expr_inner { + log::error!( + "Given type {:?} doesn't match expected {:?}", + given_inner, + expr_inner + ); + return Err(Error::InitializationTypeMismatch( + name_span, ty, + )); + } + ty + } + None => { + // register the type, if needed + match context.typifier[value].clone() { + TypeResolution::Handle(ty) => ty, + TypeResolution::Value(inner) => { + context.types.fetch_or_append( + crate::Type { name: None, inner }, + Default::default(), + ) + } } - } else { - lexer.expect(Token::Separator(':'))?; - break value; } - cases.push(crate::SwitchCase { - value, - body: crate::Block::new(), - fall_through: true, - }); }; - let mut body = crate::Block::new(); - lexer.expect(Token::Paren('{'))?; - let fall_through = loop { - // default statements - if lexer.skip(Token::Word("fallthrough")) { - lexer.expect(Token::Separator(';'))?; - lexer.expect(Token::Paren('}'))?; - break true; + let init = match context.expressions[value] { + crate::Expression::Constant(handle) if is_uniform_control_flow => { + Init::Constant(handle) } - if lexer.skip(Token::Paren('}')) { - break false; - } - self.parse_statement(lexer, context.reborrow(), &mut body, false)?; + _ => Init::Variable(value), }; + (init, ty) + } else { + match given_ty { + Some(ty) => (Init::Empty, ty), + None => { + log::error!( + "Variable '{}' without an initializer needs a type", + name + ); + return Err(Error::MissingType(name_span)); + } + } + }; - cases.push(crate::SwitchCase { + lexer.expect(Token::Separator(';'))?; + let var_id = context.variables.append( + crate::LocalVariable { + name: Some(name.to_owned()), + ty, + init: match init { + Init::Constant(value) => Some(value), + _ => None, + }, + }, + NagaSpan::ByteRange(name_span), + ); + + // Doesn't make sense to assign a span to cached lookup + let expr_id = context + .expressions + .append(crate::Expression::LocalVariable(var_id), Default::default()); + context.lookup_ident.insert(name, expr_id); + + if let Init::Variable(value) = init { + Some(crate::Statement::Store { + pointer: expr_id, value, - body, - fall_through, - }); - } - (Token::Word("default"), _) => { - lexer.expect(Token::Separator(':'))?; - default = self.parse_block(lexer, context.reborrow(), false)?; - } - (Token::Paren('}'), _) => break, - other => return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)), - } - } - - Some(crate::Statement::Switch { - selector, - cases, - default, - }) - } - "loop" => { - let _ = lexer.next(); - let mut body = crate::Block::new(); - let mut continuing = crate::Block::new(); - lexer.expect(Token::Paren('{'))?; - - loop { - if lexer.skip(Token::Word("continuing")) { - continuing = self.parse_block(lexer, context.reborrow(), false)?; - lexer.expect(Token::Paren('}'))?; - break; - } - if lexer.skip(Token::Paren('}')) { - break; - } - self.parse_statement(lexer, context.reborrow(), &mut body, false)?; - } - - Some(crate::Statement::Loop { body, continuing }) - } - "for" => { - let _ = lexer.next(); - lexer.expect(Token::Paren('('))?; - if !lexer.skip(Token::Separator(';')) { - let num_statements = block.len(); - let (_, span) = lexer.capture_span(|lexer| { - self.parse_statement( - lexer, - context.reborrow(), - block, - is_uniform_control_flow, - ) - })?; - - if block.len() != num_statements { - match *block.last().unwrap() { - crate::Statement::Store { .. } | crate::Statement::Call { .. } => {} - _ => return Err(Error::InvalidForInitializer(span)), + }) + } else { + None } } - }; - - let mut body = crate::Block::new(); - if !lexer.skip(Token::Separator(';')) { - let (condition, span) = lexer.capture_span(|lexer| { + "return" => { + let _ = lexer.next(); + let value = if lexer.peek().0 != Token::Separator(';') { + emitter.start(context.expressions); + let handle = self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?; + block.extend(emitter.finish(context.expressions)); + Some(handle) + } else { + None + }; + lexer.expect(Token::Separator(';'))?; + Some(crate::Statement::Return { value }) + } + "if" => { + let _ = lexer.next(); + lexer.expect(Token::Paren('('))?; emitter.start(context.expressions); let condition = self.parse_general_expression( lexer, - context.as_expression(&mut body, &mut emitter), + context.as_expression(block, &mut emitter), + )?; + block.extend(emitter.finish(context.expressions)); + lexer.expect(Token::Paren(')'))?; + + let accept = self.parse_block(lexer, context.reborrow(), false)?; + let mut elsif_stack = Vec::new(); + let mut elseif_span_start = lexer.current_byte_offset(); + while lexer.skip(Token::Word("elseif")) { + let mut sub_emitter = super::Emitter::default(); + + lexer.expect(Token::Paren('('))?; + sub_emitter.start(context.expressions); + let other_condition = self.parse_general_expression( + lexer, + context.as_expression(block, &mut sub_emitter), + )?; + let other_emit = sub_emitter.finish(context.expressions); + lexer.expect(Token::Paren(')'))?; + let other_block = self.parse_block(lexer, context.reborrow(), false)?; + elsif_stack.push(( + elseif_span_start, + other_condition, + other_emit, + other_block, + )); + elseif_span_start = lexer.current_byte_offset(); + } + let mut reject = if lexer.skip(Token::Word("else")) { + self.parse_block(lexer, context.reborrow(), false)? + } else { + crate::Block::new() + }; + let span_end = lexer.current_byte_offset(); + // reverse-fold the else-if blocks + //Note: we may consider uplifting this to the IR + for (other_span_start, other_cond, other_emit, other_block) in + elsif_stack.into_iter().rev() + { + let sub_stmt = crate::Statement::If { + condition: other_cond, + accept: other_block, + reject, + }; + reject = crate::Block::new(); + reject.extend(other_emit); + reject.push(sub_stmt, NagaSpan::ByteRange(other_span_start..span_end)) + } + + Some(crate::Statement::If { + condition, + accept, + reject, + }) + } + "switch" => { + let _ = lexer.next(); + emitter.start(context.expressions); + lexer.expect(Token::Paren('('))?; + let selector = self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?; + lexer.expect(Token::Paren(')'))?; + block.extend(emitter.finish(context.expressions)); + lexer.expect(Token::Paren('{'))?; + let mut cases = Vec::new(); + let mut default = crate::Block::new(); + + loop { + // cases + default + match lexer.next() { + (Token::Word("case"), _) => { + // parse a list of values + let value = loop { + let value = lexer.next_sint_literal()?; + if lexer.skip(Token::Separator(',')) { + if lexer.skip(Token::Separator(':')) { + break value; + } + } else { + lexer.expect(Token::Separator(':'))?; + break value; + } + cases.push(crate::SwitchCase { + value, + body: crate::Block::new(), + fall_through: true, + }); + }; + + let mut body = crate::Block::new(); + lexer.expect(Token::Paren('{'))?; + let fall_through = loop { + // default statements + if lexer.skip(Token::Word("fallthrough")) { + lexer.expect(Token::Separator(';'))?; + lexer.expect(Token::Paren('}'))?; + break true; + } + if lexer.skip(Token::Paren('}')) { + break false; + } + self.parse_statement( + lexer, + context.reborrow(), + &mut body, + false, + )?; + }; + + cases.push(crate::SwitchCase { + value, + body, + fall_through, + }); + } + (Token::Word("default"), _) => { + lexer.expect(Token::Separator(':'))?; + default = self.parse_block(lexer, context.reborrow(), false)?; + } + (Token::Paren('}'), _) => break, + other => { + return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)) + } + } + } + + Some(crate::Statement::Switch { + selector, + cases, + default, + }) + } + "loop" => { + let _ = lexer.next(); + let mut body = crate::Block::new(); + let mut continuing = crate::Block::new(); + lexer.expect(Token::Paren('{'))?; + + loop { + if lexer.skip(Token::Word("continuing")) { + continuing = self.parse_block(lexer, context.reborrow(), false)?; + lexer.expect(Token::Paren('}'))?; + break; + } + if lexer.skip(Token::Paren('}')) { + break; + } + self.parse_statement(lexer, context.reborrow(), &mut body, false)?; + } + + Some(crate::Statement::Loop { body, continuing }) + } + "for" => { + let _ = lexer.next(); + lexer.expect(Token::Paren('('))?; + if !lexer.skip(Token::Separator(';')) { + let num_statements = block.len(); + let (_, span) = lexer.capture_span(|lexer| { + self.parse_statement( + lexer, + context.reborrow(), + block, + is_uniform_control_flow, + ) + })?; + + if block.len() != num_statements { + match *block.last().unwrap() { + crate::Statement::Store { .. } + | crate::Statement::Call { .. } => {} + _ => return Err(Error::InvalidForInitializer(span)), + } + } + }; + + let mut body = crate::Block::new(); + if !lexer.skip(Token::Separator(';')) { + let (condition, span) = lexer.capture_span(|lexer| { + emitter.start(context.expressions); + let condition = self.parse_general_expression( + lexer, + context.as_expression(&mut body, &mut emitter), + )?; + lexer.expect(Token::Separator(';'))?; + body.extend(emitter.finish(context.expressions)); + Ok(condition) + })?; + let mut reject = crate::Block::new(); + reject.push(crate::Statement::Break, NagaSpan::Unknown); + body.push( + crate::Statement::If { + condition, + accept: crate::Block::new(), + reject, + }, + NagaSpan::ByteRange(span), + ); + }; + + let mut continuing = crate::Block::new(); + if let (Token::Word(ident), ident_span) = lexer.peek() { + // manually parse the next statement here instead of calling parse_statement + // because the statement is not terminated with a semicolon + self.parse_statement_restricted( + lexer, + ident, + ident_span, + context.as_expression(&mut continuing, &mut emitter), + )?; + } + lexer.expect(Token::Paren(')'))?; + lexer.expect(Token::Paren('{'))?; + + while !lexer.skip(Token::Paren('}')) { + self.parse_statement(lexer, context.reborrow(), &mut body, false)?; + } + + Some(crate::Statement::Loop { body, continuing }) + } + "break" => { + let _ = lexer.next(); + Some(crate::Statement::Break) + } + "continue" => { + let _ = lexer.next(); + Some(crate::Statement::Continue) + } + "discard" => { + let _ = lexer.next(); + Some(crate::Statement::Kill) + } + "storageBarrier" => { + let _ = lexer.next(); + lexer.expect(Token::Paren('('))?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Statement::Barrier(crate::Barrier::STORAGE)) + } + "workgroupBarrier" => { + let _ = lexer.next(); + lexer.expect(Token::Paren('('))?; + lexer.expect(Token::Paren(')'))?; + Some(crate::Statement::Barrier(crate::Barrier::WORK_GROUP)) + } + "atomicStore" => { + let _ = lexer.next(); + emitter.start(context.expressions); + lexer.open_arguments()?; + let mut expression_ctx = context.as_expression(block, &mut emitter); + let pointer = + self.parse_atomic_pointer(lexer, expression_ctx.reborrow())?; + lexer.expect(Token::Separator(','))?; + let value = self.parse_general_expression(lexer, expression_ctx)?; + lexer.close_arguments()?; + block.extend(emitter.finish(context.expressions)); + Some(crate::Statement::Store { pointer, value }) + } + "textureStore" => { + let _ = lexer.next(); + emitter.start(context.expressions); + lexer.open_arguments()?; + let (image_name, image_span) = lexer.next_ident_with_span()?; + let image = context + .lookup_ident + .lookup(image_name, image_span.clone())?; + lexer.expect(Token::Separator(','))?; + let mut expr_context = context.as_expression(block, &mut emitter); + let arrayed = match *expr_context.resolve_type(image)? { + crate::TypeInner::Image { arrayed, .. } => arrayed, + _ => return Err(Error::BadTexture(image_span)), + }; + let coordinate = self.parse_general_expression(lexer, expr_context)?; + let array_index = if arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?) + } else { + None + }; + lexer.expect(Token::Separator(','))?; + let value = self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?; + lexer.close_arguments()?; + block.extend(emitter.finish(context.expressions)); + Some(crate::Statement::ImageStore { + image, + coordinate, + array_index, + value, + }) + } + // assignment or a function call + ident => { + self.parse_statement_restricted( + lexer, + ident, + word_span, + context.as_expression(block, &mut emitter), )?; lexer.expect(Token::Separator(';'))?; - body.extend(emitter.finish(context.expressions)); - Ok(condition) - })?; - let mut reject = crate::Block::new(); - reject.push(crate::Statement::Break, NagaSpan::Unknown); - body.push( - crate::Statement::If { - condition, - accept: crate::Block::new(), - reject, - }, - NagaSpan::ByteRange(span), - ); + None + } }; - - let mut continuing = crate::Block::new(); - if let (Token::Word(ident), ident_span) = lexer.peek() { - // manually parse the next statement here instead of calling parse_statement - // because the statement is not terminated with a semicolon - self.parse_statement_restricted( - lexer, - ident, - ident_span, - context.as_expression(&mut continuing, &mut emitter), - )?; + let span = self.pop_scope(lexer); + if let Some(statement) = statement { + block.push(statement, NagaSpan::ByteRange(span)); } - lexer.expect(Token::Paren(')'))?; - lexer.expect(Token::Paren('{'))?; - - while !lexer.skip(Token::Paren('}')) { - self.parse_statement(lexer, context.reborrow(), &mut body, false)?; - } - - Some(crate::Statement::Loop { body, continuing }) } - "break" => { - let _ = lexer.next(); - Some(crate::Statement::Break) - } - "continue" => { - let _ = lexer.next(); - Some(crate::Statement::Continue) - } - "discard" => { - let _ = lexer.next(); - Some(crate::Statement::Kill) - } - "storageBarrier" => { - let _ = lexer.next(); - lexer.expect(Token::Paren('('))?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Statement::Barrier(crate::Barrier::STORAGE)) - } - "workgroupBarrier" => { - let _ = lexer.next(); - lexer.expect(Token::Paren('('))?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Statement::Barrier(crate::Barrier::WORK_GROUP)) - } - "atomicStore" => { - let _ = lexer.next(); - emitter.start(context.expressions); - lexer.open_arguments()?; - let mut expression_ctx = context.as_expression(block, &mut emitter); - let pointer = self.parse_atomic_pointer(lexer, expression_ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let value = self.parse_general_expression(lexer, expression_ctx)?; - lexer.close_arguments()?; - block.extend(emitter.finish(context.expressions)); - Some(crate::Statement::Store { pointer, value }) - } - "textureStore" => { - let _ = lexer.next(); - emitter.start(context.expressions); - lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = context - .lookup_ident - .lookup(image_name, image_span.clone())?; - lexer.expect(Token::Separator(','))?; - let mut expr_context = context.as_expression(block, &mut emitter); - let arrayed = match *expr_context.resolve_type(image)? { - crate::TypeInner::Image { arrayed, .. } => arrayed, - _ => return Err(Error::BadTexture(image_span)), - }; - let coordinate = self.parse_general_expression(lexer, expr_context)?; - let array_index = if arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?) - } else { - None - }; - lexer.expect(Token::Separator(','))?; - let value = self - .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?; - lexer.close_arguments()?; - block.extend(emitter.finish(context.expressions)); - Some(crate::Statement::ImageStore { - image, - coordinate, - array_index, - value, - }) - } - // assignment or a function call - ident => { - self.parse_statement_restricted( - lexer, - ident, - word_span, - context.as_expression(block, &mut emitter), - )?; - lexer.expect(Token::Separator(';'))?; - None - } - }; - let span = self.pop_scope(lexer); - if let Some(statement) = statement { - block.push(statement, NagaSpan::ByteRange(span)); + other => return Err(Error::Unexpected(other, ExpectedToken::Statement)), } Ok(()) } diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 21fde3265..a0ee76535 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -4,7 +4,7 @@ struct PrimeIndices { }; [[group(0), binding(0)]] -var global: PrimeIndices; +var global: PrimeIndices; var gl_GlobalInvocationID: vec3; fn collatz_iterations(n: u32) -> u32 { diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 7706cda4f..d9a00535a 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -7,7 +7,7 @@ struct Bar { }; [[group(0), binding(0)]] -var bar: Bar; +var bar: Bar; [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 4546f1721..283169b58 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -26,7 +26,7 @@ var params: SimParams; [[group(0), binding(1)]] var particlesSrc: Particles; [[group(0), binding(2)]] -var particlesDst: Particles; +var particlesDst: Particles; [[stage(compute), workgroup_size(64, 1, 1)]] fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index 7d7a8dedc..e3bbb2cab 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -4,7 +4,7 @@ struct PrimeIndices { }; [[group(0), binding(0)]] -var v_indices: PrimeIndices; +var v_indices: PrimeIndices; fn collatz_iterations(n_base: u32) -> u32 { var n: u32; From ba92640482ce4a80eb34299485f8f4b1984a0918 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 16 Aug 2021 22:02:03 +0100 Subject: [PATCH 1238/2212] [wgsl-in] Parse function storage class --- src/front/wgsl/conv.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 2e47c0e0d..be9c8c59d 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -9,6 +9,7 @@ pub fn map_storage_class(word: &str, span: Span) -> Result Ok(crate::StorageClass::PushConstant), + "function" => Ok(crate::StorageClass::Function), _ => Err(Error::UnknownStorageClass(span)), } } From 91ea6e3d83e9f92e12204c088da325cad6311b87 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Sat, 14 Aug 2021 19:49:23 -0400 Subject: [PATCH 1239/2212] [hlsl-out] Fix reading from mat3 --- src/back/hlsl/storage.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 3ba13f545..4cbc3e20c 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -127,7 +127,14 @@ impl super::Writer<'_, W> { rows as u8, columns as u8, )?; - let row_stride = width as u32 * columns as u32; + + // Note: Matrices containing vec3s, due to padding, act like they contain vec4s. + let padded_columns = match columns { + crate::VectorSize::Tri => 4, + columns => columns as u32, + }; + + let row_stride = width as u32 * padded_columns; let iter = (0..rows as u32).map(|i| { let ty_inner = crate::TypeInner::Vector { size: columns, From 73be8c745477042e129e4cb6981a2e4ad643e466 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Sun, 15 Aug 2021 19:32:52 -0400 Subject: [PATCH 1240/2212] [hlsl-out] Implicitly transpose all matrices --- src/back/hlsl/mod.rs | 11 +++++++++++ src/back/hlsl/storage.rs | 9 ++++----- src/back/hlsl/writer.rs | 13 ++++++++++--- tests/out/hlsl/access.hlsl | 6 +++--- tests/out/hlsl/shadow.hlsl | 6 +++--- tests/out/hlsl/skybox.hlsl | 8 ++++---- 6 files changed, 35 insertions(+), 18 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 11e812a15..4dc3ed6e6 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -5,6 +5,17 @@ //! - 5.1 //! - 6.0 //! +//! All matrix construction/deconstruction is row based in HLSL. This means that when +//! we construct a matrix from column vectors, our matrix will be implicitly transposed. +//! The inverse transposition happens when we call `[0]` to get the zeroth column vector. +//! +//! Because all of our matrices are implicitly transposed, we flip arguments to `mul`. `mat * vec` +//! becomes `vec * mat`, etc. This acts as the inverse transpose making the results identical. +//! +//! The only time we don't get this implicit transposition is when reading matrices from Uniforms/Push Constants. +//! To deal with this, we add `row_major` to all declarations of matrices in Uniforms/Push Constants. +//! +//! Finally because all of our matrices are transposed, if you use `mat3x4`, it'll become `float4x3` in HLSL. mod conv; mod help; diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 4cbc3e20c..60d0b161f 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -1,7 +1,6 @@ //! Logic related to `ByteAddressBuffer` operations. //! //! HLSL backend uses byte address buffers for all storage buffers in IR. -//! Matrices have to be transposed, because HLSL syntax implies row majority. use super::{ super::{FunctionCtx, INDENT}, @@ -122,7 +121,7 @@ impl super::Writer<'_, W> { } => { write!( self.out, - "transpose({}{}x{}(", + "{}{}x{}(", crate::ScalarKind::Float.to_hlsl_str(width)?, rows as u8, columns as u8, @@ -144,7 +143,7 @@ impl super::Writer<'_, W> { (TypeResolution::Value(ty_inner), i * row_stride) }); self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; - write!(self.out, "))")?; + write!(self.out, ")")?; } crate::TypeInner::Array { base, @@ -267,7 +266,7 @@ impl super::Writer<'_, W> { let depth = indent + 1; write!( self.out, - "{}{}{}x{} {}{} = transpose(", + "{}{}{}x{} {}{} = ", INDENT.repeat(indent + 1), crate::ScalarKind::Float.to_hlsl_str(width)?, rows as u8, @@ -276,7 +275,7 @@ impl super::Writer<'_, W> { depth, )?; self.write_store_value(module, &value, func_ctx)?; - writeln!(self.out, ");")?; + writeln!(self.out, ";")?; // then iterate the stores let row_stride = width as u32 * columns as u32; for i in 0..rows as u32 { diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index dde9d128e..fbf41cd44 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -640,6 +640,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } + if let TypeInner::Matrix { .. } = module.types[ty].inner { + write!(self.out, "row_major ")?; + } + // Write the member type and name self.write_type(module, ty)?; write!( @@ -700,12 +704,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } => { // The IR supports only float matrix // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-matrix + + // Because of the implicit transpose all matrices have in HLSL, we need to tranpose the size as well. write!( self.out, "{}{}x{}", crate::ScalarKind::Float.to_hlsl_str(width)?, - back::vector_size_str(columns), back::vector_size_str(rows), + back::vector_size_str(columns), )?; } TypeInner::Image { @@ -1302,10 +1308,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { .inner_with(&module.types) .is_matrix() => { + // We intentionally flip the order of multiplication as our matrices are implicitly transposed. write!(self.out, "mul(")?; - self.write_expr(module, left, func_ctx)?; - write!(self.out, ", ")?; self.write_expr(module, right, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, left, func_ctx)?; write!(self.out, ")")?; } Expression::Binary { op, left, right } => { diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index d724bbcaf..1d9ff1ecf 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -19,14 +19,14 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position float baz = foo1; foo1 = 1.0; - float4x4 matrix1 = transpose(float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48)))); + float4x4 matrix1 = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))}; float4 _expr13 = asfloat(bar.Load4(48+0)); float b = _expr13.x; int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 4) - 2u)*4+88)); bar.Store(8+16+0, asuint(1.0)); { - float4x4 _value2 = transpose(float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx))); + float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx)); bar.Store4(0+0, asuint(_value2[0])); bar.Store4(0+16, asuint(_value2[1])); bar.Store4(0+32, asuint(_value2[2])); @@ -43,7 +43,7 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position } c[(vertexinput_foo.vi1 + 1u)] = 42; int value = c[vertexinput_foo.vi1]; - return mul(matrix1, float4(int4(value.xxxx))); + return mul(float4(int4(value.xxxx)), matrix1); } [numthreads(1, 1, 1)] diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 32d23dd93..742c41cbd 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -6,7 +6,7 @@ struct Globals { }; struct Light { - float4x4 proj; + row_major float4x4 proj; float4 pos; float4 color; }; @@ -51,9 +51,9 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 break; } uint _expr19 = i; - Light light = {transpose(float4x4(asfloat(s_lights.Load4(_expr19*96+0+0+0)), asfloat(s_lights.Load4(_expr19*96+0+0+16)), asfloat(s_lights.Load4(_expr19*96+0+0+32)), asfloat(s_lights.Load4(_expr19*96+0+0+48)))), asfloat(s_lights.Load4(_expr19*96+0+64)), asfloat(s_lights.Load4(_expr19*96+0+80))}; + Light light = {float4x4(asfloat(s_lights.Load4(_expr19*96+0+0+0)), asfloat(s_lights.Load4(_expr19*96+0+0+16)), asfloat(s_lights.Load4(_expr19*96+0+0+32)), asfloat(s_lights.Load4(_expr19*96+0+0+48))), asfloat(s_lights.Load4(_expr19*96+0+64)), asfloat(s_lights.Load4(_expr19*96+0+80))}; uint _expr22 = i; - const float _e25 = fetch_shadow(_expr22, mul(light.proj, fragmentinput_fs_main.position1)); + const float _e25 = fetch_shadow(_expr22, mul(fragmentinput_fs_main.position1, light.proj)); float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); float3 _expr34 = color; diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 058b0cbb6..39da82be7 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -10,8 +10,8 @@ struct VertexOutput { }; struct Data { - float4x4 proj_inv; - float4x4 view; + row_major float4x4 proj_inv; + row_major float4x4 view; }; cbuffer r_data : register(b0) { Data r_data; } @@ -41,8 +41,8 @@ VertexOutput vs_main(VertexInput_vs_main vertexinput_vs_main) float4 _expr35 = r_data.view[2]; float3x3 inv_model_view = transpose(float3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz)); float4x4 _expr40 = r_data.proj_inv; - float4 unprojected = mul(_expr40, pos); - const VertexOutput vertexoutput1 = { pos, mul(inv_model_view, unprojected.xyz) }; + float4 unprojected = mul(pos, _expr40); + const VertexOutput vertexoutput1 = { pos, mul(unprojected.xyz, inv_model_view) }; return vertexoutput1; } From 79d899fe4ce4d3bfc20a26232a53f317e2ea6132 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 17 Aug 2021 01:07:15 -0400 Subject: [PATCH 1241/2212] Support num_workgroups builtin --- CHANGELOG.md | 1 + src/back/glsl/mod.rs | 1 + src/back/hlsl/conv.rs | 8 +- src/back/hlsl/writer.rs | 20 ++- src/back/msl/mod.rs | 3 +- src/back/spv/writer.rs | 1 + src/back/wgsl/writer.rs | 1 + src/front/glsl/variables.rs | 10 ++ src/front/spv/convert.rs | 1 + src/front/wgsl/conv.rs | 1 + src/lib.rs | 1 + src/valid/analyzer.rs | 3 +- src/valid/interface.rs | 3 +- tests/in/interface.param.ron | 7 + tests/in/interface.wgsl | 6 +- tests/out/hlsl/interface.hlsl | 12 +- tests/out/hlsl/skybox.hlsl | 1 + tests/out/msl/interface.msl | 6 + tests/out/spv/interface.spvasm | 226 ++++++++++++++++++--------------- tests/out/wgsl/interface.wgsl | 5 +- 20 files changed, 206 insertions(+), 111 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 03f7d72bb..f2ab949b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## TBD - API: - atomic types and functions + - `num_workgroups` built-in - WGSL `select()` order of true/false is swapped ## v0.5 (2021-06-18) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index cccf959ec..0558c9096 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2643,6 +2643,7 @@ fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { Bi::LocalInvocationIndex => "gl_LocalInvocationIndex", Bi::WorkGroupId => "gl_WorkGroupID", Bi::WorkGroupSize => "gl_WorkGroupSize", + Bi::NumWorkGroups => "gl_NumWorkGroups", } } diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 501cbbcd2..e535d4534 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -96,7 +96,13 @@ impl crate::BuiltIn { Self::LocalInvocationId => "SV_GroupThreadID", Self::LocalInvocationIndex => "SV_GroupIndex", Self::WorkGroupId => "SV_GroupID", - _ => return Err(Error::Unimplemented(format!("builtin {:?}", self))), + // The specific semantic we use here doesn't matter, because references + // to this field will get replaced with references to `SPECIAL_CBUF_VAR` + // in `Writer::write_expr`. + Self::NumWorkGroups => "SV_GroupID", + Self::BaseInstance | Self::BaseVertex | Self::WorkGroupSize => { + return Err(Error::Unimplemented(format!("builtin {:?}", self))) + } }) } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index fbf41cd44..78cff0ce8 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -15,6 +15,7 @@ const SPECIAL_CBUF_TYPE: &str = "NagaConstants"; const SPECIAL_CBUF_VAR: &str = "_NagaConstants"; const SPECIAL_BASE_VERTEX: &str = "base_vertex"; const SPECIAL_BASE_INSTANCE: &str = "base_instance"; +const SPECIAL_OTHER: &str = "other"; /// Structure contains information required for generating /// wrapped structure of all entry points arguments @@ -105,6 +106,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, "struct {} {{", SPECIAL_CBUF_TYPE)?; writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_BASE_VERTEX)?; writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_BASE_INSTANCE)?; + writeln!(self.out, "{}uint {};", back::INDENT, SPECIAL_OTHER)?; writeln!(self.out, "}};")?; write!( self.out, @@ -1234,10 +1236,26 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!( self.out, "({}.{} + ", - SPECIAL_CBUF_VAR, SPECIAL_BASE_INSTANCE + SPECIAL_CBUF_VAR, SPECIAL_BASE_INSTANCE, )?; ")" } + Some(crate::BuiltIn::NumWorkGroups) => { + //Note: despite their names (`BASE_VERTEX` and `BASE_INSTANCE`), + // in compute shaders the special constants contain the number + // of workgroups, which we are using here. + write!( + self.out, + "uint3({}.{}, {}.{}, {}.{})", + SPECIAL_CBUF_VAR, + SPECIAL_BASE_VERTEX, + SPECIAL_CBUF_VAR, + SPECIAL_BASE_INSTANCE, + SPECIAL_CBUF_VAR, + SPECIAL_OTHER, + )?; + return Ok(()); + } _ => "", }; diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 6bc2b4052..8e840da05 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -357,7 +357,8 @@ impl ResolvedBinding { Bi::LocalInvocationIndex => "thread_index_in_threadgroup", Bi::WorkGroupId => "threadgroup_position_in_grid", Bi::WorkGroupSize => "dispatch_threads_per_threadgroup", - _ => return Err(Error::UnsupportedBuiltIn(built_in)), + Bi::NumWorkGroups => "threadgroups_per_grid", + Bi::CullDistance => return Err(Error::UnsupportedBuiltIn(built_in)), }; write!(out, "{}", name)?; } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 3b247db40..d2f254b54 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1043,6 +1043,7 @@ impl Writer { Bi::LocalInvocationIndex => BuiltIn::LocalInvocationIndex, Bi::WorkGroupId => BuiltIn::WorkgroupId, Bi::WorkGroupSize => BuiltIn::WorkgroupSize, + Bi::NumWorkGroups => BuiltIn::NumWorkgroups, }; self.decorate(id, Decoration::BuiltIn, &[built_in as u32]); diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 829f93380..b101b745d 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1596,6 +1596,7 @@ fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { Bi::GlobalInvocationId => Some("global_invocation_id"), Bi::WorkGroupId => Some("workgroup_id"), Bi::WorkGroupSize => Some("workgroup_size"), + Bi::NumWorkGroups => Some("num_workgroups"), Bi::SampleIndex => Some("sample_index"), Bi::SampleMask => Some("sample_mask"), Bi::PrimitiveIndex => Some("primitive_index"), diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 65d586f89..9c5957e7c 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -156,6 +156,16 @@ impl Parser { false, StorageQualifier::Input, ), + "gl_NumWorkGroups" => add_builtin( + TypeInner::Vector { + size: VectorSize::Tri, + kind: ScalarKind::Uint, + width: 4, + }, + BuiltIn::NumWorkGroups, + false, + StorageQualifier::Input, + ), "gl_FrontFacing" => add_builtin( TypeInner::Scalar { kind: ScalarKind::Bool, diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index d4fe91d57..569cb5865 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -141,6 +141,7 @@ pub(super) fn map_builtin(word: spirv::Word) -> Result { Some(Bi::LocalInvocationIndex) => crate::BuiltIn::LocalInvocationIndex, Some(Bi::WorkgroupId) => crate::BuiltIn::WorkGroupId, Some(Bi::WorkgroupSize) => crate::BuiltIn::WorkGroupSize, + Some(Bi::NumWorkgroups) => crate::BuiltIn::NumWorkGroups, _ => return Err(Error::UnsupportedBuiltIn(word)), }) } diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index be9c8c59d..519073fc3 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -32,6 +32,7 @@ pub fn map_built_in(word: &str, span: Span) -> Result> "local_invocation_index" => crate::BuiltIn::LocalInvocationIndex, "workgroup_id" => crate::BuiltIn::WorkGroupId, "workgroup_size" => crate::BuiltIn::WorkGroupSize, + "num_workgroups" => crate::BuiltIn::NumWorkGroups, _ => return Err(Error::UnknownBuiltin(span)), }) } diff --git a/src/lib.rs b/src/lib.rs index ce3cc5d34..3f40d366d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -281,6 +281,7 @@ pub enum BuiltIn { LocalInvocationIndex, WorkGroupId, WorkGroupSize, + NumWorkGroups, } /// Number of bytes per scalar. diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 0f917df7c..c70244272 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -406,7 +406,8 @@ impl FunctionInfo { crate::BuiltIn::FrontFacing // per-work-group built-ins are uniform | crate::BuiltIn::WorkGroupId - | crate::BuiltIn::WorkGroupSize => true, + | crate::BuiltIn::WorkGroupSize + | crate::BuiltIn::NumWorkGroups => true, _ => false, }, // only flat inputs are uniform diff --git a/src/valid/interface.rs b/src/valid/interface.rs index b715cfb2d..dccd02bd6 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -216,7 +216,8 @@ impl VaryingContext<'_> { Bi::GlobalInvocationId | Bi::LocalInvocationId | Bi::WorkGroupId - | Bi::WorkGroupSize => ( + | Bi::WorkGroupSize + | Bi::NumWorkGroups => ( self.stage == St::Compute && !self.output, *ty_inner == Ti::Vector { diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index ee3fa36da..25d844329 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -2,4 +2,11 @@ spv_version: (1, 0), spv_capabilities: [ Shader, SampleRateShading ], spv_adjust_coordinate_space: false, + hlsl_custom: true, + hlsl: ( + shader_model: V5_1, + binding_map: {}, + fake_missing_bindings: false, + special_constants_binding: Some((space: 1, register: 0)), + ), ) diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index 18b060702..6b38a434e 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -33,13 +33,15 @@ fn fragment( return FragmentOutput(in.varying, mask, color); } +var output: array; + [[stage(compute), workgroup_size(1)]] fn compute( [[builtin(global_invocation_id)]] global_id: vec3, [[builtin(local_invocation_id)]] local_id: vec3, [[builtin(local_invocation_index)]] local_index: u32, [[builtin(workgroup_id)]] wg_id: vec3, - //TODO: https://github.com/gpuweb/gpuweb/issues/1590 - //[[builtin(workgroup_size)]] wg_size: vec3, + [[builtin(num_workgroups)]] num_wgs: vec3, ) { + output[0] = global_id.x + local_id.x + local_index + wg_id.x + num_wgs.x; } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 4a46710a8..277a00cd0 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -1,3 +1,9 @@ +struct NagaConstants { + int base_vertex; + int base_instance; + uint other; +}; +ConstantBuffer _NagaConstants: register(b0, space1); struct VertexOutput { float4 position : SV_Position; @@ -10,6 +16,8 @@ struct FragmentOutput { float color : SV_Target0; }; +groupshared uint output[1]; + struct VertexInput_vertex { uint color1 : LOC10; uint instance_index1 : SV_InstanceID; @@ -28,11 +36,12 @@ struct ComputeInput_compute { uint3 local_id1 : SV_GroupThreadID; uint local_index1 : SV_GroupIndex; uint3 wg_id1 : SV_GroupID; + uint3 num_wgs1 : SV_GroupID; }; VertexOutput vertex(VertexInput_vertex vertexinput_vertex) { - uint tmp = ((vertexinput_vertex.vertex_index1 + vertexinput_vertex.instance_index1) + vertexinput_vertex.color1); + uint tmp = (((_NagaConstants.base_vertex + vertexinput_vertex.vertex_index1) + (_NagaConstants.base_instance + vertexinput_vertex.instance_index1)) + vertexinput_vertex.color1); const VertexOutput vertexoutput1 = { float4(1.0.xxxx), float(tmp) }; return vertexoutput1; } @@ -48,5 +57,6 @@ FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) [numthreads(1, 1, 1)] void compute(ComputeInput_compute computeinput_compute) { + output[0] = ((((computeinput_compute.global_id1.x + computeinput_compute.local_id1.x) + computeinput_compute.local_index1) + computeinput_compute.wg_id1.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x); return; } diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 39da82be7..36ec009f5 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -1,6 +1,7 @@ struct NagaConstants { int base_vertex; int base_instance; + uint other; }; ConstantBuffer _NagaConstants: register(b1); diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index efa936167..abe791a27 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -11,6 +11,9 @@ struct FragmentOutput { metal::uint sample_mask; float color; }; +struct type4 { + metal::uint inner[1]; +}; struct vertex1Input { metal::uint color [[attribute(10)]]; @@ -61,6 +64,9 @@ kernel void compute1( , metal::uint3 local_id [[thread_position_in_threadgroup]] , metal::uint local_index [[thread_index_in_threadgroup]] , metal::uint3 wg_id [[threadgroup_position_in_grid]] +, metal::uint3 num_wgs [[threadgroups_per_grid]] +, threadgroup type4& output ) { + output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x; return; } diff --git a/tests/out/spv/interface.spvasm b/tests/out/spv/interface.spvasm index 6f4b5d1d1..5af161688 100644 --- a/tests/out/spv/interface.spvasm +++ b/tests/out/spv/interface.spvasm @@ -1,124 +1,146 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 76 +; Bound: 95 OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %25 "vertex" %14 %17 %19 %21 %23 -OpEntryPoint Fragment %54 "fragment" %37 %40 %43 %46 %48 %50 %51 %53 -OpEntryPoint GLCompute %74 "compute" %65 %68 %70 %72 -OpExecutionMode %54 OriginUpperLeft -OpExecutionMode %54 DepthReplacing -OpExecutionMode %74 LocalSize 1 1 1 -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 16 -OpMemberDecorate %10 0 Offset 0 -OpMemberDecorate %10 1 Offset 4 -OpMemberDecorate %10 2 Offset 8 -OpDecorate %14 BuiltIn VertexIndex -OpDecorate %17 BuiltIn InstanceIndex -OpDecorate %19 Location 10 -OpDecorate %21 BuiltIn Position -OpDecorate %23 Location 1 -OpDecorate %37 BuiltIn FragCoord -OpDecorate %40 Location 1 -OpDecorate %43 BuiltIn FrontFacing -OpDecorate %46 BuiltIn SampleId -OpDecorate %48 BuiltIn SampleMask -OpDecorate %50 BuiltIn FragDepth -OpDecorate %51 BuiltIn SampleMask -OpDecorate %53 Location 0 -OpDecorate %65 BuiltIn GlobalInvocationId -OpDecorate %68 BuiltIn LocalInvocationId -OpDecorate %70 BuiltIn LocalInvocationIndex -OpDecorate %72 BuiltIn WorkgroupId +OpEntryPoint Vertex %31 "vertex" %20 %23 %25 %27 %29 +OpEntryPoint Fragment %60 "fragment" %43 %46 %49 %52 %54 %56 %57 %59 +OpEntryPoint GLCompute %82 "compute" %71 %74 %76 %78 %80 +OpExecutionMode %60 OriginUpperLeft +OpExecutionMode %60 DepthReplacing +OpExecutionMode %82 LocalSize 1 1 1 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 16 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 1 Offset 4 +OpMemberDecorate %13 2 Offset 8 +OpDecorate %15 ArrayStride 4 +OpDecorate %20 BuiltIn VertexIndex +OpDecorate %23 BuiltIn InstanceIndex +OpDecorate %25 Location 10 +OpDecorate %27 BuiltIn Position +OpDecorate %29 Location 1 +OpDecorate %43 BuiltIn FragCoord +OpDecorate %46 Location 1 +OpDecorate %49 BuiltIn FrontFacing +OpDecorate %52 BuiltIn SampleId +OpDecorate %54 BuiltIn SampleMask +OpDecorate %56 BuiltIn FragDepth +OpDecorate %57 BuiltIn SampleMask +OpDecorate %59 Location 0 +OpDecorate %71 BuiltIn GlobalInvocationId +OpDecorate %74 BuiltIn LocalInvocationId +OpDecorate %76 BuiltIn LocalInvocationIndex +OpDecorate %78 BuiltIn WorkgroupId +OpDecorate %80 BuiltIn NumWorkgroups %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 %6 = OpTypeInt 32 0 %5 = OpConstant %6 1 %7 = OpConstant %4 0.0 -%8 = OpTypeVector %4 4 -%9 = OpTypeStruct %8 %4 -%10 = OpTypeStruct %4 %6 %4 -%11 = OpTypeBool -%12 = OpTypeVector %6 3 -%15 = OpTypePointer Input %6 -%14 = OpVariable %15 Input -%17 = OpVariable %15 Input -%19 = OpVariable %15 Input -%22 = OpTypePointer Output %8 -%21 = OpVariable %22 Output -%24 = OpTypePointer Output %4 -%23 = OpVariable %24 Output -%26 = OpTypeFunction %2 -%38 = OpTypePointer Input %8 -%37 = OpVariable %38 Input -%41 = OpTypePointer Input %4 -%40 = OpVariable %41 Input +%9 = OpTypeInt 32 1 +%8 = OpConstant %9 1 +%10 = OpConstant %9 0 +%11 = OpTypeVector %4 4 +%12 = OpTypeStruct %11 %4 +%13 = OpTypeStruct %4 %6 %4 +%14 = OpTypeBool +%15 = OpTypeArray %6 %8 +%16 = OpTypeVector %6 3 +%18 = OpTypePointer Workgroup %15 +%17 = OpVariable %18 Workgroup +%21 = OpTypePointer Input %6 +%20 = OpVariable %21 Input +%23 = OpVariable %21 Input +%25 = OpVariable %21 Input +%28 = OpTypePointer Output %11 +%27 = OpVariable %28 Output +%30 = OpTypePointer Output %4 +%29 = OpVariable %30 Output +%32 = OpTypeFunction %2 %44 = OpTypePointer Input %11 %43 = OpVariable %44 Input -%46 = OpVariable %15 Input -%48 = OpVariable %15 Input -%50 = OpVariable %24 Output -%52 = OpTypePointer Output %6 -%51 = OpVariable %52 Output -%53 = OpVariable %24 Output -%66 = OpTypePointer Input %12 -%65 = OpVariable %66 Input -%68 = OpVariable %66 Input -%70 = OpVariable %15 Input -%72 = OpVariable %66 Input -%25 = OpFunction %2 None %26 -%13 = OpLabel -%16 = OpLoad %6 %14 -%18 = OpLoad %6 %17 -%20 = OpLoad %6 %19 -OpBranch %27 -%27 = OpLabel -%28 = OpIAdd %6 %16 %18 -%29 = OpIAdd %6 %28 %20 -%30 = OpCompositeConstruct %8 %3 %3 %3 %3 -%31 = OpConvertUToF %4 %29 -%32 = OpCompositeConstruct %9 %30 %31 -%33 = OpCompositeExtract %8 %32 0 -OpStore %21 %33 -%34 = OpCompositeExtract %4 %32 1 -OpStore %23 %34 +%47 = OpTypePointer Input %4 +%46 = OpVariable %47 Input +%50 = OpTypePointer Input %14 +%49 = OpVariable %50 Input +%52 = OpVariable %21 Input +%54 = OpVariable %21 Input +%56 = OpVariable %30 Output +%58 = OpTypePointer Output %6 +%57 = OpVariable %58 Output +%59 = OpVariable %30 Output +%72 = OpTypePointer Input %16 +%71 = OpVariable %72 Input +%74 = OpVariable %72 Input +%76 = OpVariable %21 Input +%78 = OpVariable %72 Input +%80 = OpVariable %72 Input +%84 = OpTypePointer Workgroup %6 +%93 = OpConstant %6 0 +%31 = OpFunction %2 None %32 +%19 = OpLabel +%22 = OpLoad %6 %20 +%24 = OpLoad %6 %23 +%26 = OpLoad %6 %25 +OpBranch %33 +%33 = OpLabel +%34 = OpIAdd %6 %22 %24 +%35 = OpIAdd %6 %34 %26 +%36 = OpCompositeConstruct %11 %3 %3 %3 %3 +%37 = OpConvertUToF %4 %35 +%38 = OpCompositeConstruct %12 %36 %37 +%39 = OpCompositeExtract %11 %38 0 +OpStore %27 %39 +%40 = OpCompositeExtract %4 %38 1 +OpStore %29 %40 OpReturn OpFunctionEnd -%54 = OpFunction %2 None %26 -%35 = OpLabel -%39 = OpLoad %8 %37 -%42 = OpLoad %4 %40 -%36 = OpCompositeConstruct %9 %39 %42 +%60 = OpFunction %2 None %32 +%41 = OpLabel %45 = OpLoad %11 %43 -%47 = OpLoad %6 %46 -%49 = OpLoad %6 %48 -OpBranch %55 -%55 = OpLabel -%56 = OpShiftLeftLogical %6 %5 %47 -%57 = OpBitwiseAnd %6 %49 %56 -%58 = OpSelect %4 %45 %3 %7 -%59 = OpCompositeExtract %4 %36 1 -%60 = OpCompositeConstruct %10 %59 %57 %58 -%61 = OpCompositeExtract %4 %60 0 -OpStore %50 %61 -%62 = OpCompositeExtract %6 %60 1 -OpStore %51 %62 -%63 = OpCompositeExtract %4 %60 2 -OpStore %53 %63 +%48 = OpLoad %4 %46 +%42 = OpCompositeConstruct %12 %45 %48 +%51 = OpLoad %14 %49 +%53 = OpLoad %6 %52 +%55 = OpLoad %6 %54 +OpBranch %61 +%61 = OpLabel +%62 = OpShiftLeftLogical %6 %5 %53 +%63 = OpBitwiseAnd %6 %55 %62 +%64 = OpSelect %4 %51 %3 %7 +%65 = OpCompositeExtract %4 %42 1 +%66 = OpCompositeConstruct %13 %65 %63 %64 +%67 = OpCompositeExtract %4 %66 0 +OpStore %56 %67 +%68 = OpCompositeExtract %6 %66 1 +OpStore %57 %68 +%69 = OpCompositeExtract %4 %66 2 +OpStore %59 %69 OpReturn OpFunctionEnd -%74 = OpFunction %2 None %26 -%64 = OpLabel -%67 = OpLoad %12 %65 -%69 = OpLoad %12 %68 -%71 = OpLoad %6 %70 -%73 = OpLoad %12 %72 -OpBranch %75 -%75 = OpLabel +%82 = OpFunction %2 None %32 +%70 = OpLabel +%73 = OpLoad %16 %71 +%75 = OpLoad %16 %74 +%77 = OpLoad %6 %76 +%79 = OpLoad %16 %78 +%81 = OpLoad %16 %80 +OpBranch %83 +%83 = OpLabel +%85 = OpCompositeExtract %6 %73 0 +%86 = OpCompositeExtract %6 %75 0 +%87 = OpIAdd %6 %85 %86 +%88 = OpIAdd %6 %87 %77 +%89 = OpCompositeExtract %6 %79 0 +%90 = OpIAdd %6 %88 %89 +%91 = OpCompositeExtract %6 %81 0 +%92 = OpIAdd %6 %90 %91 +%94 = OpAccessChain %84 %17 %93 +OpStore %94 %92 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index 30875ee8e..c86c9f556 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -9,6 +9,8 @@ struct FragmentOutput { [[location(0)]] color: f32; }; +var output: array; + [[stage(vertex)]] fn vertex([[builtin(vertex_index)]] vertex_index: u32, [[builtin(instance_index)]] instance_index: u32, [[location(10)]] color: u32) -> VertexOutput { let tmp: u32 = ((vertex_index + instance_index) + color); @@ -23,6 +25,7 @@ fn fragment(in: VertexOutput, [[builtin(front_facing)]] front_facing: bool, [[bu } [[stage(compute), workgroup_size(1, 1, 1)]] -fn compute([[builtin(global_invocation_id)]] global_id: vec3, [[builtin(local_invocation_id)]] local_id: vec3, [[builtin(local_invocation_index)]] local_index: u32, [[builtin(workgroup_id)]] wg_id: vec3) { +fn compute([[builtin(global_invocation_id)]] global_id: vec3, [[builtin(local_invocation_id)]] local_id: vec3, [[builtin(local_invocation_index)]] local_index: u32, [[builtin(workgroup_id)]] wg_id: vec3, [[builtin(num_workgroups)]] num_wgs: vec3) { + output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x); return; } From b05ca6e4036f3290ce091caaa903733b6afb7b55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 11 Aug 2021 14:44:14 +0100 Subject: [PATCH 1242/2212] [glsl-in] Builtin redefinition and calls fixes --- src/front/glsl/ast.rs | 25 +- src/front/glsl/builtins.rs | 1633 +++++++++++++++++++++++ src/front/glsl/context.rs | 15 +- src/front/glsl/error.rs | 19 - src/front/glsl/functions.rs | 1173 ++++------------ src/front/glsl/mod.rs | 1 + src/front/glsl/parser.rs | 12 +- src/front/glsl/parser/expressions.rs | 1 - src/front/glsl/types.rs | 11 +- tests/out/wgsl/246-collatz-comp.wgsl | 22 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 676 +++++----- tests/out/wgsl/bool-select-frag.wgsl | 6 +- tests/out/wgsl/clamp-splat-vert.wgsl | 4 +- tests/out/wgsl/math-functions-vert.wgsl | 169 +-- 14 files changed, 2426 insertions(+), 1341 deletions(-) create mode 100644 src/front/glsl/builtins.rs diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index b2e35741c..f449c661d 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,4 +1,6 @@ -use super::SourceMetadata; +use std::fmt; + +use super::{builtins::MacroCall, SourceMetadata}; use crate::{ BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, Interpolation, Sampling, StorageAccess, StorageClass, Type, UnaryOperator, @@ -26,12 +28,31 @@ pub struct ParameterInfo { pub depth: bool, } +/// How the function is implemented +#[derive(Clone, Copy)] +pub enum FunctionKind { + /// The function is user defined + Call(Handle), + /// The function is a buitin + Macro(MacroCall), +} + +impl fmt::Debug for FunctionKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::Call(_) => write!(f, "Call"), + Self::Macro(_) => write!(f, "Macro"), + } + } +} + #[derive(Debug)] pub struct FunctionDeclaration { /// Normalized function parameters, modifiers are not applied pub parameters: Vec>, pub parameters_info: Vec, - pub handle: Handle, + /// How the function is implemented + pub kind: FunctionKind, /// Wheter this function was already defined or is just a prototype pub defined: bool, /// Wheter or not this function returns void (nothing) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs new file mode 100644 index 000000000..7d45d44c1 --- /dev/null +++ b/src/front/glsl/builtins.rs @@ -0,0 +1,1633 @@ +use super::{ + ast::{FunctionDeclaration, FunctionKind, ParameterInfo, ParameterQualifier}, + context::Context, + Error, ErrorKind, Parser, Result, SourceMetadata, +}; +use crate::{ + BinaryOperator, Block, Expression, Handle, ImageClass, ImageDimension, ImageQuery, + MathFunction, Module, RelationalFunction, SampleLevel, Span, Type, TypeInner, VectorSize, +}; + +impl Module { + /// Helper function, to create a function prototype for a builtin + fn add_builtin(&mut self, args: Vec, builtin: MacroCall) -> FunctionDeclaration { + let mut parameters = Vec::with_capacity(args.len()); + let mut parameters_info = Vec::with_capacity(args.len()); + + for arg in args { + parameters.push(self.types.fetch_or_append( + Type { + name: None, + inner: arg, + }, + Span::Unknown, + )); + parameters_info.push(ParameterInfo { + qualifier: ParameterQualifier::In, + depth: false, + }); + } + + FunctionDeclaration { + parameters, + parameters_info, + kind: FunctionKind::Macro(builtin), + defined: false, + void: false, + } + } +} + +impl Parser { + /// Injects a builtin into the [`lookup_function`](Self::lookup_function) + /// + /// This is done to not add a large startup cost and not increase memory + /// usage if it isn't needed. + pub(crate) fn inject_builtin(&mut self, name: String) { + use crate::{ImageDimension as Dim, ScalarKind as Sk}; + + let declarations = self.lookup_function.entry(name.clone()).or_default(); + + match name.as_str() { + "sampler1D" | "sampler1DArray" | "sampler2D" | "sampler2DArray" | "sampler2DMS" + | "sampler2DMSArray" | "sampler3D" | "samplerCube" | "samplerCubeArray" => declarations + .push(self.module.add_builtin( + vec![ + TypeInner::Image { + dim: match name.as_str() { + "sampler1D" | "sampler1DArray" => Dim::D1, + "sampler2D" | "sampler2DArray" | "sampler2DMS" + | "sampler2DMSArray" => Dim::D2, + "sampler3D" => Dim::D3, + _ => Dim::Cube, + }, + arrayed: matches!( + name.as_str(), + "sampler1DArray" + | "sampler2DArray" + | "sampler2DMSArray" + | "samplerCubeArray" + ), + class: ImageClass::Sampled { + kind: Sk::Float, + multi: matches!(name.as_str(), "sampler2DMS" | "sampler2DMSArray"), + }, + }, + TypeInner::Sampler { comparison: false }, + ], + MacroCall::Sampler, + )), + "sampler1DShadow" + | "sampler1DArrayShadow" + | "sampler2DShadow" + | "sampler2DArrayShadow" + | "samplerCubeShadow" + | "samplerCubeArrayShadow" => { + let dim = match name.as_str() { + "sampler1DShadow" | "sampler1DArrayShadow" => Dim::D1, + "sampler2DShadow" | "sampler2DArrayShadow" => Dim::D2, + _ => Dim::Cube, + }; + let arrayed = matches!( + name.as_str(), + "sampler1DArrayShadow" | "sampler2DArrayShadow" | "samplerCubeArrayShadow" + ); + + for i in 0..2 { + let ty = TypeInner::Image { + dim, + arrayed, + class: match i { + 0 => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + _ => ImageClass::Depth { multi: false }, + }, + }; + + declarations.push(self.module.add_builtin( + vec![ty, TypeInner::Sampler { comparison: true }], + MacroCall::SamplerShadow, + )) + } + } + "texture" | "textureLod" => { + // bits layout + // bits 0 trough 1 - dims + // bit 2 - shadow + // bit 3 - array + // bit 4 - !bias + // + // 0b11111 is the latest since there are not 3D arrayed shadowed + // textures and cube arrayed shadows textures always have a + // compare argument + for bits in 0..(0b100000) { + let dim = bits & 0b11; + let shadow = bits & 0b100 == 0b100; + let arrayed = bits & 0b1000 == 0b1000; + let bias = bits & 0b10000 == 0b00000; + let builtin = match name.as_str() { + "texture" => MacroCall::Texture, + _ => MacroCall::TextureLod, + }; + + // Shadow, arrayed or both 3D images are not allowed + if (shadow || arrayed) && dim == 0b11 + || (builtin == MacroCall::TextureLod + && (dim != 0b00 && shadow && arrayed || dim == 0b10 && shadow || !bias)) + { + continue; + } + + let class = match shadow { + true => ImageClass::Depth { multi: false }, + false => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; + + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + 0b10 => Dim::Cube, + _ => Dim::D3, + }, + arrayed, + class, + }; + + let vector = match (dim, shadow) { + (0b00, false) => TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }, + (0b00, true) | (0b11, _) => TypeInner::Vector { + size: VectorSize::Tri, + kind: Sk::Float, + width: 4, + }, + (_, _) => { + let size = match dim + arrayed as u32 + shadow as u32 { + 1 => VectorSize::Bi, + 2 => VectorSize::Tri, + _ => VectorSize::Quad, + }; + + TypeInner::Vector { + size, + kind: Sk::Float, + width: 4, + } + } + }; + + let mut args = vec![image, vector]; + + if bias { + args.push(TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }) + } + + declarations.push(self.module.add_builtin(args, builtin)) + } + } + "textureProj" => { + // bits layout + // bit 0 - shadow + // bit 1 - bias + // bits 2 trough 3 - dims + // + // 0b0111 is the latest since there are only 1D and 2D shadow + // variants + for bits in 0..(0b1000) { + let dim = bits >> 2; + let shadow = bits & 0b1 == 0b1; + let bias = bits & 0b10 == 0b10; + + let class = match shadow { + true => ImageClass::Depth { multi: false }, + false => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; + + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + _ => Dim::Cube, + }, + arrayed: false, + class, + }; + + let vector = TypeInner::Vector { + size: VectorSize::Quad, + kind: Sk::Float, + width: 4, + }; + + let mut args = vec![image, vector]; + + if bias { + args.push(TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }) + } + + declarations.push(self.module.add_builtin(args, MacroCall::TextureProj)) + } + } + "textureGrad" => { + // bits layout + // bits 0 trough 1 - dims + // bit 2 - shadow + // bit 3 - array + // + // 0b1010 is the latest since there are no 3D arrayed shadowed + // textures and cube arrayed shadows textures are not allowed + for bits in 0..(0b1011) { + let dim = bits & 0b11; + let shadow = bits & 0b100 == 0b100; + let arrayed = bits & 0b1000 == 0b1000; + + // Shadow, arrayed or both 3D images are not allowed + if shadow && dim == 0b11 + // samplerCubeArrayShadow is not allowed + || shadow && arrayed && dim == 0b10 + { + continue; + } + + let class = match shadow { + true => ImageClass::Depth { multi: false }, + false => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; + + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + 0b10 => Dim::Cube, + _ => Dim::D3, + }, + arrayed, + class, + }; + + let vector = match (dim, shadow) { + (0b00, false) => TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }, + (0b00, true) | (0b11, _) => TypeInner::Vector { + size: VectorSize::Tri, + kind: Sk::Float, + width: 4, + }, + (_, _) => { + let size = match dim + arrayed as u32 + shadow as u32 { + 1 => VectorSize::Bi, + 2 => VectorSize::Tri, + _ => VectorSize::Quad, + }; + + TypeInner::Vector { + size, + kind: Sk::Float, + width: 4, + } + } + }; + + let size = match dim { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + _ => Some(VectorSize::Tri), + }; + + let ty = || match size { + None => TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }, + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: 4, + }, + }; + + let args = vec![image, vector, ty(), ty()]; + + declarations.push(self.module.add_builtin(args, MacroCall::TextureGrad)) + } + } + "textureSize" => { + // bits layout + // bits 0 trough 1 - dims + // bit 2 - shadow + // bit 3 - array + for bits in 0..(0b10000) { + let dim = bits & 0b11; + let shadow = bits & 0b100 == 0b100; + let arrayed = bits & 0b1000 == 0b1000; + + // Shadow, arrayed or both 3D images are not allowed + if (shadow || arrayed) && dim == 0b11 { + continue; + } + + let class = match shadow { + true => ImageClass::Depth { multi: false }, + false => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; + + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + 0b10 => Dim::Cube, + _ => Dim::D3, + }, + arrayed, + class, + }; + + let args = vec![ + image, + TypeInner::Scalar { + kind: Sk::Sint, + width: 4, + }, + ]; + + declarations.push(self.module.add_builtin(args, MacroCall::TextureSize)) + } + } + "texelFetch" => { + // bits layout + // bit 0 - dim part 1 - 1D/2D + // bit 1 - array + // bit 2 - dim part 2 - 3D + // + // 0b100 is the latest since 3D arrayed images aren't allowed + for bits in 0..(0b101) { + let dim = bits & 0b1 | (bits & 0b100) >> 1; + let arrayed = bits & 0b1000 == 0b1000; + + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + _ => Dim::D3, + }, + arrayed, + class: ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; + + let vector = match (dim, arrayed) { + (0b00, false) => TypeInner::Scalar { + kind: Sk::Sint, + width: 4, + }, + (_, _) => { + let size = match dim + arrayed as u32 { + 1 => VectorSize::Bi, + 2 => VectorSize::Tri, + _ => VectorSize::Quad, + }; + + TypeInner::Vector { + size, + kind: Sk::Sint, + width: 4, + } + } + }; + + let args = vec![ + image, + vector, + TypeInner::Scalar { + kind: Sk::Sint, + width: 4, + }, + ]; + + declarations.push(self.module.add_builtin(args, MacroCall::TexelFetch)) + } + } + "ceil" | "round" | "floor" | "fract" | "trunc" | "sqrt" | "inversesqrt" + | "normalize" | "length" | "isinf" | "isnan" => { + // bits layout + // bit 0 - float/double + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let width = (bits & 0b1) * 4 + 4; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let args = vec![match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + }]; + + let fun = match name.as_str() { + "ceil" => MacroCall::MathFunction(MathFunction::Ceil), + "round" => MacroCall::MathFunction(MathFunction::Round), + "floor" => MacroCall::MathFunction(MathFunction::Floor), + "fract" => MacroCall::MathFunction(MathFunction::Fract), + "trunc" => MacroCall::MathFunction(MathFunction::Trunc), + "sqrt" => MacroCall::MathFunction(MathFunction::Sqrt), + "inversesqrt" => MacroCall::MathFunction(MathFunction::InverseSqrt), + "normalize" => MacroCall::MathFunction(MathFunction::Normalize), + "length" => MacroCall::MathFunction(MathFunction::Length), + "isinf" => MacroCall::Relational(RelationalFunction::IsInf), + "isnan" => MacroCall::Relational(RelationalFunction::IsNan), + _ => unreachable!(), + }; + + declarations.push(self.module.add_builtin(args, fun)) + } + } + "dot" | "reflect" | "distance" | "ldexp" => { + // bits layout + // bit 0 - float/double + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let width = (bits & 0b1) * 4 + 4; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + }; + + let fun = match name.as_str() { + "dot" => MacroCall::MathFunction(MathFunction::Dot), + "reflect" => MacroCall::MathFunction(MathFunction::Reflect), + "distance" => MacroCall::MathFunction(MathFunction::Distance), + "ldexp" => MacroCall::MathFunction(MathFunction::Ldexp), + _ => unreachable!(), + }; + + declarations.push(self.module.add_builtin(vec![ty(), ty()], fun)) + } + } + "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" + | "log" | "log2" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + declarations.push(self.module.add_builtin( + vec![match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: 4, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }, + }], + MacroCall::MathFunction(match name.as_str() { + "sin" => MathFunction::Sin, + "exp" => MathFunction::Exp, + "exp2" => MathFunction::Exp2, + "sinh" => MathFunction::Sinh, + "cos" => MathFunction::Cos, + "cosh" => MathFunction::Cosh, + "tan" => MathFunction::Tan, + "tanh" => MathFunction::Tanh, + "acos" => MathFunction::Acos, + "asin" => MathFunction::Asin, + "log" => MathFunction::Log, + "log2" => MathFunction::Log2, + _ => unreachable!(), + }), + )) + } + } + "pow" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: 4, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }, + }; + + declarations.push( + self.module.add_builtin( + vec![ty(), ty()], + MacroCall::MathFunction(MathFunction::Pow), + ), + ) + } + } + "transpose" => { + // bits layout + // bit 0 - float/double + // bit 1 trough 4 - dims + for bits in 0..(0b10010) { + let width = (bits & 0b1) * 4 + 4; + let (rows, columns) = match bits >> 1 { + 0b0000 => (VectorSize::Bi, VectorSize::Bi), + 0b0001 => (VectorSize::Bi, VectorSize::Tri), + 0b0010 => (VectorSize::Bi, VectorSize::Quad), + 0b0011 => (VectorSize::Tri, VectorSize::Bi), + 0b0100 => (VectorSize::Tri, VectorSize::Tri), + 0b0101 => (VectorSize::Tri, VectorSize::Quad), + 0b0110 => (VectorSize::Quad, VectorSize::Bi), + 0b0111 => (VectorSize::Quad, VectorSize::Tri), + _ => (VectorSize::Quad, VectorSize::Quad), + }; + + if (bits >> 1) > 0b1000 { + continue; + } + + declarations.push(self.module.add_builtin( + vec![TypeInner::Matrix { + columns, + rows, + width, + }], + MacroCall::MathFunction(MathFunction::Transpose), + )) + } + } + "inverse" | "determinant" => { + // bits layout + // bit 0 - float/double + // bit 1 trough 2 - dims + for bits in 0..(0b110) { + let width = (bits & 0b1) * 4 + 4; + let (rows, columns) = match bits >> 1 { + 0b00 => (VectorSize::Bi, VectorSize::Bi), + 0b01 => (VectorSize::Tri, VectorSize::Tri), + _ => (VectorSize::Quad, VectorSize::Quad), + }; + + let args = vec![TypeInner::Matrix { + columns, + rows, + width, + }]; + + declarations.push(self.module.add_builtin( + args, + MacroCall::MathFunction(match name.as_str() { + "inverse" => MathFunction::Inverse, + "determinant" => MathFunction::Determinant, + _ => unreachable!(), + }), + )) + } + } + "abs" | "sign" => { + // bits layout + // bit 0 trough 1 - dims + // bit 2 trough 3 - kind + for bits in 0..(0b1100) { + let size = match bits & 0b11 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let (kind, width) = match bits >> 2 { + 0b00 => (Sk::Float, 4), + 0b01 => (Sk::Sint, 4), + _ => (Sk::Float, 8), + }; + + let args = vec![match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }]; + + declarations.push(self.module.add_builtin( + args, + MacroCall::MathFunction(match name.as_str() { + "abs" => MathFunction::Abs, + "sign" => MathFunction::Sign, + _ => unreachable!(), + }), + )) + } + } + "bitCount" | "bitfieldReverse" => { + // bits layout + // bit 0 - int/uint + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let kind = match bits & 0b1 { + 0b0 => Sk::Sint, + _ => Sk::Uint, + }; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let args = vec![match size { + Some(size) => TypeInner::Vector { + size, + kind, + width: 4, + }, + None => TypeInner::Scalar { kind, width: 4 }, + }]; + + declarations.push(self.module.add_builtin( + args, + MacroCall::MathFunction(match name.as_str() { + "bitCount" => MathFunction::CountOneBits, + "bitfieldReverse" => MathFunction::ReverseBits, + _ => unreachable!(), + }), + )) + } + } + "atan" => { + // bits layout + // bit 0 - atan/atan2 + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let fun = match bits & 0b1 { + 0b0 => MathFunction::Atan, + _ => MathFunction::Atan2, + }; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: 4, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }, + }; + + let mut args = vec![ty()]; + + if fun == MathFunction::Atan2 { + args.push(ty()) + } + + declarations.push(self.module.add_builtin(args, MacroCall::MathFunction(fun))) + } + } + "all" | "any" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b11) { + let size = match bits { + 0b00 => VectorSize::Bi, + 0b01 => VectorSize::Tri, + _ => VectorSize::Quad, + }; + + let args = vec![TypeInner::Vector { + size, + kind: Sk::Bool, + width: crate::BOOL_WIDTH, + }]; + + let fun = MacroCall::Relational(match name.as_str() { + "all" => RelationalFunction::All, + "any" => RelationalFunction::Any, + _ => unreachable!(), + }); + + declarations.push(self.module.add_builtin(args, fun)) + } + } + "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" + | "notEqual" => { + for bits in 0..(0b1001) { + let (size, kind) = match bits { + 0b0000 => (VectorSize::Bi, Sk::Float), + 0b0001 => (VectorSize::Tri, Sk::Float), + 0b0010 => (VectorSize::Quad, Sk::Float), + 0b0011 => (VectorSize::Bi, Sk::Sint), + 0b0100 => (VectorSize::Tri, Sk::Sint), + 0b0101 => (VectorSize::Quad, Sk::Sint), + 0b0110 => (VectorSize::Bi, Sk::Uint), + 0b0111 => (VectorSize::Tri, Sk::Uint), + _ => (VectorSize::Quad, Sk::Uint), + }; + + let ty = || TypeInner::Vector { + size, + kind, + width: 4, + }; + let args = vec![ty(), ty()]; + + let fun = MacroCall::Binary(match name.as_str() { + "lessThan" => BinaryOperator::Less, + "greaterThan" => BinaryOperator::Greater, + "lessThanEqual" => BinaryOperator::LessEqual, + "greaterThanEqual" => BinaryOperator::GreaterEqual, + "equal" => BinaryOperator::Equal, + "notEqual" => BinaryOperator::NotEqual, + _ => unreachable!(), + }); + + declarations.push(self.module.add_builtin(args, fun)) + } + } + "mod" | "step" => { + // bits layout + // bit 0 - float/double + // bit 1 trough 3 - dims + for bits in 0..(0b1110) { + let width = (bits & 0b1) * 4 + 4; + let (size, second_size) = match bits >> 1 { + 0b000 => (None, None), + 0b001 => (Some(VectorSize::Bi), None), + 0b010 => (Some(VectorSize::Tri), None), + 0b011 => (Some(VectorSize::Quad), None), + 0b100 => (Some(VectorSize::Bi), Some(VectorSize::Bi)), + 0b101 => (Some(VectorSize::Tri), Some(VectorSize::Tri)), + _ => (Some(VectorSize::Quad), Some(VectorSize::Quad)), + }; + + let mut args = Vec::with_capacity(2); + let step = name.as_str() == "step"; + + for i in 0..2 { + let maybe_size = match i == step as u32 { + true => size, + false => second_size, + }; + + args.push(match maybe_size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + }) + } + + let fun = match name.as_str() { + "mod" => MacroCall::Mod(size), + "step" => MacroCall::Splatted(MathFunction::Step, size, 0), + _ => unreachable!(), + }; + + declarations.push(self.module.add_builtin(args, fun)) + } + } + "min" | "max" => { + // bits layout + // bit 0 trough 1 - scalar kind and width + // bit 2 trough 4 - dims + for bits in 0..(0b11100) { + let (kind, width) = match bits & 0b11 { + 0b00 => (Sk::Float, 4), + 0b01 => (Sk::Float, 8), + 0b10 => (Sk::Sint, 4), + _ => (Sk::Uint, 4), + }; + let (size, second_size) = match bits >> 2 { + 0b000 => (None, None), + 0b001 => (Some(VectorSize::Bi), None), + 0b010 => (Some(VectorSize::Tri), None), + 0b011 => (Some(VectorSize::Quad), None), + 0b100 => (Some(VectorSize::Bi), Some(VectorSize::Bi)), + 0b101 => (Some(VectorSize::Tri), Some(VectorSize::Tri)), + _ => (Some(VectorSize::Quad), Some(VectorSize::Quad)), + }; + + let args = vec![ + match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }, + match second_size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }, + ]; + + let fun = match name.as_str() { + "max" => MacroCall::Splatted(MathFunction::Max, size, 1), + "min" => MacroCall::Splatted(MathFunction::Min, size, 1), + _ => unreachable!(), + }; + + declarations.push(self.module.add_builtin(args, fun)) + } + } + "modf" | "frexp" => { + // bits layout + // bit 0 - float/double + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let width = (bits & 0b1) * 4 + 4; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let ty = self.module.types.fetch_or_append( + Type { + name: None, + inner: match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + }, + }, + Span::Unknown, + ); + + let parameters = vec![ty, ty]; + + let fun = match name.as_str() { + "modf" => MacroCall::MathFunction(MathFunction::Modf), + "frexp" => MacroCall::MathFunction(MathFunction::Frexp), + _ => unreachable!(), + }; + + declarations.push(FunctionDeclaration { + parameters, + parameters_info: vec![ + ParameterInfo { + qualifier: ParameterQualifier::In, + depth: false, + }, + ParameterInfo { + qualifier: ParameterQualifier::Out, + depth: false, + }, + ], + kind: FunctionKind::Macro(fun), + defined: false, + void: false, + }) + } + } + "cross" => { + // bits layout + // bit 0 - float/double + for bits in 0..0b10 { + let width = bits * 4 + 4; + + let args = vec![ + TypeInner::Vector { + size: VectorSize::Tri, + kind: Sk::Float, + width, + }, + TypeInner::Vector { + size: VectorSize::Tri, + kind: Sk::Float, + width, + }, + ]; + + declarations.push( + self.module + .add_builtin(args, MacroCall::MathFunction(MathFunction::Cross)), + ) + } + } + "outerProduct" => { + // bits layout + // bit 0 - float/double + // bit 1 trough 4 - dims + for bits in 0..(0b10010) { + let width = (bits & 0b1) * 4 + 4; + let (size1, size2) = match bits >> 1 { + 0b0000 => (VectorSize::Bi, VectorSize::Bi), + 0b0001 => (VectorSize::Bi, VectorSize::Tri), + 0b0010 => (VectorSize::Bi, VectorSize::Quad), + 0b0011 => (VectorSize::Tri, VectorSize::Bi), + 0b0100 => (VectorSize::Tri, VectorSize::Tri), + 0b0101 => (VectorSize::Tri, VectorSize::Quad), + 0b0110 => (VectorSize::Quad, VectorSize::Bi), + 0b0111 => (VectorSize::Quad, VectorSize::Tri), + _ => (VectorSize::Quad, VectorSize::Quad), + }; + + if (bits >> 1) > 0b1000 { + continue; + } + + let args = vec![ + TypeInner::Vector { + size: size1, + kind: Sk::Float, + width, + }, + TypeInner::Vector { + size: size2, + kind: Sk::Float, + width, + }, + ]; + + declarations.push( + self.module + .add_builtin(args, MacroCall::MathFunction(MathFunction::Outer)), + ) + } + } + "mix" => { + // bits layout + // bit 0 trough 2 - types + // bit 3 trough 4 - dims + for bits in 0..(0b100000) { + let (kind, width, splatted, boolean) = match bits & 0b111 { + 0b000 => (Sk::Sint, 4, false, true), + 0b001 => (Sk::Uint, 4, false, true), + 0b010 => (Sk::Float, 4, false, true), + 0b011 => (Sk::Float, 8, false, true), + 0b100 => (Sk::Float, 4, true, false), + 0b101 => (Sk::Float, 8, true, false), + 0b110 => (Sk::Float, 4, false, false), + _ => (Sk::Float, 8, false, false), + }; + let size = match bits >> 3 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + if splatted && size.is_none() { + continue; + } + + let ty = |kind, width| match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; + let args = vec![ + ty(kind, width), + ty(kind, width), + match (boolean, splatted) { + (true, _) => ty(Sk::Bool, crate::BOOL_WIDTH), + (_, false) => TypeInner::Scalar { kind, width }, + _ => ty(kind, width), + }, + ]; + + declarations.push(self.module.add_builtin( + args, + match boolean { + true => MacroCall::MixBoolean, + false => MacroCall::Splatted(MathFunction::Mix, size, 2), + }, + )) + } + } + "clamp" => { + // bits layout + // bit 0 trough 1 - float/double/int/uint + // bit 2 trough 3 - dims + // bit 4 - splatted + for bits in 0..(0b100000) { + let (kind, width) = match bits & 0b11 { + 0b00 => (Sk::Float, 4), + 0b01 => (Sk::Float, 8), + 0b10 => (Sk::Sint, 4), + _ => (Sk::Uint, 4), + }; + let size = match (bits >> 2) & 0b11 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let splatted = bits & 0b10000 == 0b10000; + + if splatted && size.is_none() { + continue; + } + + let base_ty = || match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; + let limit_ty = || match splatted { + true => TypeInner::Scalar { kind, width }, + false => base_ty(), + }; + + let args = vec![base_ty(), limit_ty(), limit_ty()]; + + declarations.push(self.module.add_builtin(args, MacroCall::Clamp(size))) + } + } + "faceforward" | "fma" => { + // bits layout + // bit 0 - float/double + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let width = (bits & 0b1) * 4 + 4; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + }; + let args = vec![ty(), ty(), ty()]; + + let fun = match name.as_str() { + "faceforward" => MacroCall::MathFunction(MathFunction::FaceForward), + "fma" => MacroCall::MathFunction(MathFunction::Fma), + _ => unreachable!(), + }; + + declarations.push(self.module.add_builtin(args, fun)) + } + } + "refract" => { + // bits layout + // bit 0 - float/double + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let width = (bits & 0b1) * 4 + 4; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + }; + let args = vec![ + ty(), + ty(), + TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }, + ]; + declarations.push( + self.module + .add_builtin(args, MacroCall::MathFunction(MathFunction::Refract)), + ) + } + } + "smoothstep" => { + // bits layout + // bit 0 - float/double + // bit 1 - splatted + // bit 2 trough 3 - dims + for bits in 0..(0b10000) { + let width = (bits & 0b1) * 4 + 4; + let splatted = bits & 0b10 == 0b10; + let size = match bits >> 2 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + if splatted && size.is_none() { + continue; + } + + let base_ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + }; + let ty = || match splatted { + true => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + false => base_ty(), + }; + declarations.push(self.module.add_builtin( + vec![ty(), ty(), base_ty()], + MacroCall::MathFunction(MathFunction::SmoothStep), + )) + } + } + // Not a builtin (or at lest not yet handled) + _ => {} + } + } +} + +/// A compiler defined builtin function +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum MacroCall { + Sampler, + SamplerShadow, + Texture, + TextureLod, + TextureProj, + TextureGrad, + TextureSize, + TexelFetch, + MathFunction(MathFunction), + Relational(RelationalFunction), + Binary(BinaryOperator), + Mod(Option), + Splatted(MathFunction, Option, usize), + MixBoolean, + Clamp(Option), +} + +impl MacroCall { + /// Adds the necessary expressions and statements to the passed body and + /// finally returns the final expression with the correct result + pub fn call( + &self, + parser: &mut Parser, + ctx: &mut Context, + body: &mut Block, + args: &mut [Handle], + meta: SourceMetadata, + ) -> Result> { + match *self { + MacroCall::Sampler => { + ctx.samplers.insert(args[0], args[1]); + Ok(args[0]) + } + MacroCall::SamplerShadow => { + sampled_to_depth(&mut parser.module, ctx, args[0], meta, &mut parser.errors)?; + parser.invalidate_expression(ctx, args[0], meta)?; + ctx.samplers.insert(args[0], args[1]); + Ok(args[0]) + } + MacroCall::Texture | MacroCall::TextureLod | MacroCall::TextureGrad => { + let comps = parser.coordinate_components(ctx, args[0], args[1], meta, body)?; + let level = match *self { + MacroCall::Texture => args + .get(2) + .copied() + .map_or(SampleLevel::Auto, SampleLevel::Bias), + MacroCall::TextureLod => SampleLevel::Exact(args[2]), + MacroCall::TextureGrad => SampleLevel::Gradient { + x: args[2], + y: args[3], + }, + _ => unreachable!(), + }; + texture_call(ctx, args[0], level, comps, body, meta) + } + MacroCall::TextureProj => { + let level = args + .get(2) + .copied() + .map_or(SampleLevel::Auto, SampleLevel::Bias); + let size = match *parser.resolve_type(ctx, args[1], meta)? { + TypeInner::Vector { size, .. } => size, + _ => { + return Err(Error { + kind: ErrorKind::SemanticError("Bad call to textureProj".into()), + meta, + }) + } + }; + let base = args[1]; + let mut right = ctx.add_expression( + Expression::AccessIndex { + base, + index: size as u32 - 1, + }, + SourceMetadata::none(), + body, + ); + let left = if let VectorSize::Bi = size { + ctx.add_expression( + Expression::AccessIndex { base, index: 0 }, + SourceMetadata::none(), + body, + ) + } else { + let size = match size { + VectorSize::Tri => VectorSize::Bi, + _ => VectorSize::Tri, + }; + right = ctx.add_expression( + Expression::Splat { size, value: right }, + SourceMetadata::none(), + body, + ); + ctx.vector_resize(size, base, SourceMetadata::none(), body) + }; + let coords = ctx.add_expression( + Expression::Binary { + op: BinaryOperator::Divide, + left, + right, + }, + SourceMetadata::none(), + body, + ); + let comps = parser.coordinate_components(ctx, args[0], coords, meta, body)?; + texture_call(ctx, args[0], level, comps, body, meta) + } + MacroCall::TextureSize => Ok(ctx.add_expression( + Expression::ImageQuery { + image: args[0], + query: ImageQuery::Size { + level: args.get(1).copied(), + }, + }, + SourceMetadata::none(), + body, + )), + MacroCall::TexelFetch => { + let comps = parser.coordinate_components(ctx, args[0], args[1], meta, body)?; + Ok(ctx.add_expression( + Expression::ImageLoad { + image: args[0], + coordinate: comps.coordinate, + array_index: comps.array_index, + index: Some(args[2]), + }, + SourceMetadata::none(), + body, + )) + } + MacroCall::MathFunction(fun) => Ok(ctx.add_expression( + Expression::Math { + fun, + arg: args[0], + arg1: args.get(1).copied(), + arg2: args.get(2).copied(), + }, + SourceMetadata::none(), + body, + )), + MacroCall::Relational(fun) => Ok(ctx.add_expression( + Expression::Relational { + fun, + argument: args[0], + }, + SourceMetadata::none(), + body, + )), + MacroCall::Binary(op) => Ok(ctx.add_expression( + Expression::Binary { + op, + left: args[0], + right: args[1], + }, + SourceMetadata::none(), + body, + )), + MacroCall::Mod(size) => { + ctx.implicit_splat(parser, &mut args[1], meta, size)?; + + Ok(ctx.add_expression( + Expression::Binary { + op: BinaryOperator::Modulo, + left: args[0], + right: args[1], + }, + SourceMetadata::none(), + body, + )) + } + MacroCall::Splatted(fun, size, i) => { + ctx.implicit_splat(parser, &mut args[i], meta, size)?; + + Ok(ctx.add_expression( + Expression::Math { + fun, + arg: args[0], + arg1: args.get(1).copied(), + arg2: args.get(2).copied(), + }, + SourceMetadata::none(), + body, + )) + } + MacroCall::MixBoolean => Ok(ctx.add_expression( + Expression::Select { + condition: args[2], + accept: args[1], + reject: args[0], + }, + SourceMetadata::none(), + body, + )), + MacroCall::Clamp(size) => { + ctx.implicit_splat(parser, &mut args[1], meta, size)?; + ctx.implicit_splat(parser, &mut args[2], meta, size)?; + + Ok(ctx.add_expression( + Expression::Math { + fun: MathFunction::Clamp, + arg: args[0], + arg1: args.get(1).copied(), + arg2: args.get(2).copied(), + }, + SourceMetadata::none(), + body, + )) + } + } + } +} + +fn texture_call( + ctx: &mut Context, + image: Handle, + level: SampleLevel, + comps: CoordComponents, + body: &mut Block, + meta: SourceMetadata, +) -> Result> { + if let Some(sampler) = ctx.samplers.get(&image).copied() { + Ok(ctx.add_expression( + Expression::ImageSample { + image, + sampler, + coordinate: comps.coordinate, + array_index: comps.array_index, + offset: None, + level, + depth_ref: comps.depth_ref, + }, + meta, + body, + )) + } else { + Err(Error { + kind: ErrorKind::SemanticError("Bad call".into()), + meta, + }) + } +} + +/// Helper struct for texture calls with the separate components from the vector argument +/// +/// Obtained by calling [`coordinate_components`](Parser::coordinate_components) +struct CoordComponents { + coordinate: Handle, + depth_ref: Option>, + array_index: Option>, +} + +impl Parser { + /// Helper function for texture calls, splits the vector argument into it's components + fn coordinate_components( + &mut self, + ctx: &mut Context, + image: Handle, + coord: Handle, + meta: SourceMetadata, + body: &mut Block, + ) -> Result { + if let TypeInner::Image { + dim, + arrayed, + class, + } = *self.resolve_type(ctx, image, meta)? + { + let image_size = match dim { + ImageDimension::D1 => None, + ImageDimension::D2 => Some(VectorSize::Bi), + ImageDimension::D3 => Some(VectorSize::Tri), + ImageDimension::Cube => Some(VectorSize::Tri), + }; + let coord_size = match *self.resolve_type(ctx, coord, meta)? { + TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + let shadow = match class { + ImageClass::Depth { .. } => true, + _ => false, + }; + + let coordinate = match (image_size, coord_size) { + (Some(size), Some(coord_s)) if size != coord_s => { + ctx.vector_resize(size, coord, SourceMetadata::none(), body) + } + (None, Some(_)) => ctx.add_expression( + Expression::AccessIndex { + base: coord, + index: 0, + }, + SourceMetadata::none(), + body, + ), + _ => coord, + }; + let array_index = match arrayed { + true => { + let index = match shadow { + true => image_size.map_or(0, |s| s as u32 - 1), + false => image_size.map_or(0, |s| s as u32), + }; + + Some(ctx.add_expression( + Expression::AccessIndex { base: coord, index }, + SourceMetadata::none(), + body, + )) + } + _ => None, + }; + let depth_ref = match shadow { + true => { + let index = image_size.map_or(0, |s| s as u32); + + Some(ctx.add_expression( + Expression::AccessIndex { base: coord, index }, + SourceMetadata::none(), + body, + )) + } + false => None, + }; + + Ok(CoordComponents { + coordinate, + depth_ref, + array_index, + }) + } else { + self.errors.push(Error { + kind: ErrorKind::SemanticError("Type is not an image".into()), + meta, + }); + + Ok(CoordComponents { + coordinate: coord, + depth_ref: None, + array_index: None, + }) + } + } +} + +/// Helper function to cast a expression holding a sampled image to a +/// depth image. +pub fn sampled_to_depth( + module: &mut Module, + ctx: &mut Context, + image: Handle, + meta: SourceMetadata, + errors: &mut Vec, +) -> Result<()> { + let ty = match ctx[image] { + Expression::GlobalVariable(handle) => &mut module.global_variables.get_mut(handle).ty, + Expression::FunctionArgument(i) => { + ctx.parameters_info[i as usize].depth = true; + &mut ctx.arguments[i as usize].ty + } + _ => { + return Err(Error { + kind: ErrorKind::SemanticError("Not a valid texture expression".into()), + meta, + }) + } + }; + match module.types[*ty].inner { + TypeInner::Image { + class, + dim, + arrayed, + } => match class { + ImageClass::Sampled { multi, .. } => { + *ty = module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Image { + dim, + arrayed, + class: ImageClass::Depth { multi }, + }, + }, + Span::Unknown, + ) + } + ImageClass::Depth { .. } => {} + _ => errors.push(Error { + kind: ErrorKind::SemanticError("Not a texture".into()), + meta, + }), + }, + _ => errors.push(Error { + kind: ErrorKind::SemanticError("Not a texture".into()), + meta, + }), + }; + + Ok(()) +} diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 1b8d7835c..57787463c 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -804,7 +804,7 @@ impl Context { ) -> Result> { Ok(self .expr_scalar_components(parser, expr, meta)? - .and_then(|(kind, _)| type_power(kind))) + .and_then(|(kind, width)| type_power(kind, width))) } pub fn implicit_conversion( @@ -815,9 +815,10 @@ impl Context { kind: ScalarKind, width: crate::Bytes, ) -> Result<()> { - if let (Some(tgt_power), Some(expr_power)) = - (type_power(kind), self.expr_power(parser, *expr, meta)?) - { + if let (Some(tgt_power), Some(expr_power)) = ( + type_power(kind, width), + self.expr_power(parser, *expr, meta)?, + ) { if tgt_power > expr_power { *expr = self.expressions.append( Expression::As { @@ -848,8 +849,9 @@ impl Context { Some((left_power, left_width, left_kind)), Some((right_power, right_width, right_kind)), ) = ( - left_components.and_then(|(kind, width)| Some((type_power(kind)?, width, kind))), - right_components.and_then(|(kind, width)| Some((type_power(kind)?, width, kind))), + left_components.and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), + right_components + .and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), ) { match left_power.cmp(&right_power) { std::cmp::Ordering::Less => { @@ -882,7 +884,6 @@ impl Context { pub fn implicit_splat( &mut self, parser: &mut Parser, - expr: &mut Handle, meta: SourceMetadata, vector_size: Option, diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 3bd0c8af2..0a3c75298 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -124,22 +124,3 @@ pub struct Error { /// Holds information about the range of the source code where the error happened. pub meta: SourceMetadata, } - -impl Error { - pub(crate) fn wrong_function_args( - name: String, - expected: usize, - got: usize, - meta: SourceMetadata, - ) -> Self { - let msg = format!( - "Function \"{}\" expects {} arguments, got {}", - name, expected, got - ); - - Error { - kind: ErrorKind::SemanticError(msg.into()), - meta, - } - } -} diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 8d5a1b780..7c3444bfd 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,27 +1,18 @@ use super::{ ast::*, + builtins::sampled_to_depth, context::{Context, StmtContext}, error::{Error, ErrorKind}, - types::{scalar_components, type_power}, + types::scalar_components, Parser, Result, SourceMetadata, }; use crate::{ - proc::ensure_block_returns, Arena, BinaryOperator, Block, Constant, ConstantInner, EntryPoint, - Expression, FastHashMap, Function, FunctionArgument, FunctionResult, Handle, ImageClass, - ImageDimension, ImageQuery, LocalVariable, MathFunction, Module, RelationalFunction, - SampleLevel, ScalarKind, ScalarValue, Statement, StructMember, Type, TypeInner, VectorSize, + front::glsl::types::type_power, proc::ensure_block_returns, Arena, Block, Constant, + ConstantInner, EntryPoint, Expression, FastHashMap, Function, FunctionArgument, FunctionResult, + Handle, LocalVariable, ScalarKind, ScalarValue, Span, Statement, StructMember, Type, TypeInner, }; use std::iter; -/// Helper struct for texture calls with the separate components from the vector argument -/// -/// Obtained by calling [`coordinate_components`](Parser::coordinate_components) -struct CoordComponents { - coordinate: Handle, - depth_ref: Option>, - array_index: Option>, -} - impl Parser { fn add_constant_value( &mut self, @@ -359,729 +350,266 @@ impl Parser { stmt: &StmtContext, body: &mut Block, name: String, - mut args: Vec<(Handle, SourceMetadata)>, + args: Vec<(Handle, SourceMetadata)>, raw_args: &[Handle], meta: SourceMetadata, ) -> Result>> { - match name.as_str() { - "sampler1D" | "sampler1DArray" | "sampler2D" | "sampler2DArray" | "sampler2DMS" - | "sampler2DMSArray" | "sampler3D" | "samplerCube" | "samplerCubeArray" => { - if args.len() != 2 { - return Err(Error::wrong_function_args(name, 2, args.len(), meta)); - } - ctx.samplers.insert(args[0].0, args[1].0); - Ok(Some(args[0].0)) + // If the name for the function hasn't yet been initialized check if any + // builtin can be injected. + // + // NOTE: A name not being initialized is not the same as no declarations + // being existing. + if self.lookup_function.get(&name).is_none() { + self.inject_builtin(name.clone()); + } + + let declarations = self.lookup_function.get(&name).ok_or_else(|| Error { + kind: ErrorKind::SemanticError(format!("Unknown function '{}'", name).into()), + meta, + })?; + + // Helper enum containing the type of conversion need for a call + #[derive(PartialEq, Eq, Clone, Copy, Debug)] + enum Conversion { + // No conversion needed + Exact, + // Float to double conversion needed + FloatToDouble, + // Int or uint to float conversion needed + IntToFloat, + // Int or uint to double conversion needed + IntToDouble, + // Other type of conversion needed + Other, + // No conversion was yet registered + None, + } + + let mut maybe_decl = None; + let mut old_conversions = vec![Conversion::None; args.len()]; + let mut ambiguous = false; + + 'outer: for decl in declarations { + if args.len() != decl.parameters.len() { + continue; } - "sampler1DShadow" - | "sampler1DArrayShadow" - | "sampler2DShadow" - | "sampler2DArrayShadow" - | "samplerCubeShadow" - | "samplerCubeArrayShadow" => { - if args.len() != 2 { - return Err(Error::wrong_function_args(name, 2, args.len(), meta)); - } - sampled_to_depth(&mut self.module, ctx, args[0], &mut self.errors)?; - self.invalidate_expression(ctx, args[0].0, args[0].1)?; - ctx.samplers.insert(args[0].0, args[1].0); - Ok(Some(args[0].0)) - } - "texture" => { - if !(2..=3).contains(&args.len()) { - return Err(Error::wrong_function_args(name, 2, args.len(), meta)); - } - let arg_1 = &mut args[1]; - ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; - if let Some(&mut (ref mut expr, meta)) = args.get_mut(2) { - ctx.implicit_conversion(self, expr, meta, ScalarKind::Float, 4)?; - } - let comps = self.coordinate_components(ctx, args[0], args[1], body)?; - if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(Some( - ctx.add_expression( - Expression::ImageSample { - image: args[0].0, - sampler, - coordinate: comps.coordinate, - array_index: comps.array_index, - offset: None, - level: args.get(2).map_or(SampleLevel::Auto, |&(expr, _)| { - SampleLevel::Bias(expr) - }), - depth_ref: comps.depth_ref, - }, - meta, - body, - ), - )) - } else { - Err(Error { - kind: ErrorKind::SemanticError("Bad call to texture".into()), - meta, - }) - } - } - "textureLod" => { - if args.len() != 3 { - return Err(Error::wrong_function_args(name, 3, args.len(), meta)); - } - let arg_1 = &mut args[1]; - ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; - let arg_2 = &mut args[2]; - ctx.implicit_conversion(self, &mut arg_2.0, arg_2.1, ScalarKind::Float, 4)?; - let comps = self.coordinate_components(ctx, args[0], args[1], body)?; - if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(Some(ctx.add_expression( - Expression::ImageSample { - image: args[0].0, - sampler, - coordinate: comps.coordinate, - array_index: comps.array_index, - offset: None, - level: SampleLevel::Exact(args[2].0), - depth_ref: comps.depth_ref, - }, - meta, - body, - ))) - } else { - Err(Error { - kind: ErrorKind::SemanticError("Bad call to textureLod".into()), - meta, - }) - } - } - "textureProj" => { - if !(2..=3).contains(&args.len()) { - return Err(Error::wrong_function_args(name, 2, args.len(), meta)); - } - let arg_1 = &mut args[1]; - ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; - if let Some(&mut (ref mut expr, meta)) = args.get_mut(2) { - ctx.implicit_conversion(self, expr, meta, ScalarKind::Float, 4)?; - } - let level = args - .get(2) - .map_or(SampleLevel::Auto, |&(expr, _)| SampleLevel::Bias(expr)); - let size = match *self.resolve_type(ctx, args[1].0, args[1].1)? { - TypeInner::Vector { size, .. } => size, - _ => { - return Err(Error { - kind: ErrorKind::SemanticError("Bad call to textureProj".into()), - meta, - }) - } - }; - let (base, base_meta) = args[1]; - let mut right = ctx.add_expression( - Expression::AccessIndex { - base, - index: size as u32 - 1, - }, - meta, - body, - ); - let left = if let VectorSize::Bi = size { - ctx.add_expression(Expression::AccessIndex { base, index: 0 }, meta, body) - } else { - let size = match size { - VectorSize::Tri => VectorSize::Bi, - _ => VectorSize::Tri, - }; - right = - ctx.add_expression(Expression::Splat { size, value: right }, meta, body); - ctx.vector_resize(size, base, meta, body) - }; - let coords = ctx.add_expression( - Expression::Binary { - op: BinaryOperator::Divide, - left, - right, - }, - meta, - body, - ); - let comps = self.coordinate_components(ctx, args[0], (coords, base_meta), body)?; - if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(Some(ctx.add_expression( - Expression::ImageSample { - image: args[0].0, - sampler, - coordinate: comps.coordinate, - array_index: comps.array_index, - offset: None, - level, - depth_ref: comps.depth_ref, - }, - meta, - body, - ))) - } else { - Err(Error { - kind: ErrorKind::SemanticError("Bad call to textureProj".into()), - meta, - }) - } - } - "textureGrad" => { - if args.len() != 4 { - return Err(Error::wrong_function_args(name, 3, args.len(), meta)); - } - let arg_1 = &mut args[1]; - ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Float, 4)?; - let arg_2 = &mut args[2]; - ctx.implicit_conversion(self, &mut arg_2.0, arg_2.1, ScalarKind::Float, 4)?; - let arg_3 = &mut args[3]; - ctx.implicit_conversion(self, &mut arg_3.0, arg_3.1, ScalarKind::Float, 4)?; - let comps = self.coordinate_components(ctx, args[0], args[1], body)?; - if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() { - Ok(Some(ctx.add_expression( - Expression::ImageSample { - image: args[0].0, - sampler, - coordinate: comps.coordinate, - array_index: comps.array_index, - offset: None, - level: SampleLevel::Gradient { - x: args[2].0, - y: args[3].0, - }, - depth_ref: comps.depth_ref, - }, - meta, - body, - ))) - } else { - Err(Error { - kind: ErrorKind::SemanticError("Bad call to textureGrad".into()), - meta, - }) - } - } - "textureSize" => { - if !(1..=2).contains(&args.len()) { - return Err(Error::wrong_function_args(name, 1, args.len(), meta)); - } - if let Some(&mut (ref mut expr, meta)) = args.get_mut(1) { - ctx.implicit_conversion(self, expr, meta, ScalarKind::Sint, 4)?; - } - Ok(Some(ctx.add_expression( - Expression::ImageQuery { - image: args[0].0, - query: ImageQuery::Size { - level: args.get(1).map(|e| e.0), - }, - }, - meta, - body, - ))) - } - "texelFetch" => { - if args.len() != 3 { - return Err(Error::wrong_function_args(name, 3, args.len(), meta)); - } - let arg_1 = &mut args[1]; - ctx.implicit_conversion(self, &mut arg_1.0, arg_1.1, ScalarKind::Sint, 4)?; - let arg_2 = &mut args[2]; - ctx.implicit_conversion(self, &mut arg_2.0, arg_2.1, ScalarKind::Sint, 4)?; - let comps = self.coordinate_components(ctx, args[0], args[1], body)?; - if ctx.samplers.get(&args[0].0).is_some() && comps.depth_ref.is_none() { - Ok(Some(ctx.add_expression( - Expression::ImageLoad { - image: args[0].0, - coordinate: comps.coordinate, - array_index: comps.array_index, - index: Some(args[2].0), - }, - meta, - body, - ))) - } else { - Err(Error { - kind: ErrorKind::SemanticError("Bad call to texelFetch".into()), - meta, - }) - } - } - "ceil" | "round" | "floor" | "fract" | "trunc" | "sin" | "abs" | "sqrt" - | "inversesqrt" | "exp" | "exp2" | "sign" | "transpose" | "inverse" | "normalize" - | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" | "log" | "log2" - | "length" | "determinant" | "bitCount" | "bitfieldReverse" => { - if args.len() != 1 { - return Err(Error::wrong_function_args(name, 1, args.len(), meta)); - } - Ok(Some(ctx.add_expression( - Expression::Math { - fun: match name.as_str() { - "ceil" => MathFunction::Ceil, - "round" => MathFunction::Round, - "floor" => MathFunction::Floor, - "fract" => MathFunction::Fract, - "trunc" => MathFunction::Trunc, - "sin" => MathFunction::Sin, - "abs" => MathFunction::Abs, - "sqrt" => MathFunction::Sqrt, - "inversesqrt" => MathFunction::InverseSqrt, - "exp" => MathFunction::Exp, - "exp2" => MathFunction::Exp2, - "sign" => MathFunction::Sign, - "transpose" => MathFunction::Transpose, - "inverse" => MathFunction::Inverse, - "normalize" => MathFunction::Normalize, - "sinh" => MathFunction::Sinh, - "cos" => MathFunction::Cos, - "cosh" => MathFunction::Cosh, - "tan" => MathFunction::Tan, - "tanh" => MathFunction::Tanh, - "acos" => MathFunction::Acos, - "asin" => MathFunction::Asin, - "log" => MathFunction::Log, - "log2" => MathFunction::Log2, - "length" => MathFunction::Length, - "determinant" => MathFunction::Determinant, - "bitCount" => MathFunction::CountOneBits, - "bitfieldReverse" => MathFunction::ReverseBits, - _ => unreachable!(), - }, - arg: args[0].0, - arg1: None, - arg2: None, - }, - meta, - body, - ))) - } - "atan" => { - let expr = match args.len() { - 1 => Expression::Math { - fun: MathFunction::Atan, - arg: args[0].0, - arg1: None, - arg2: None, - }, - 2 => Expression::Math { - fun: MathFunction::Atan2, - arg: args[0].0, - arg1: Some(args[1].0), - arg2: None, - }, - _ => return Err(Error::wrong_function_args(name, 2, args.len(), meta)), - }; - Ok(Some(ctx.add_expression(expr, meta, body))) - } - "mod" => { - if args.len() != 2 { - return Err(Error::wrong_function_args(name, 2, args.len(), meta)); - } - let (mut left, left_meta) = args[0]; - let (mut right, right_meta) = args[1]; + let mut exact = true; + // State of the selection + // If None we still don't know what is the best declaration + // If Some(true) the new declaration is better + // If Some(false) the old declaration is better + let mut superior = None; + let mut new_conversions = vec![Conversion::None; args.len()]; - ctx.binary_implicit_conversion(self, &mut left, left_meta, &mut right, right_meta)?; + for ((i, decl_arg), call_arg) in decl.parameters.iter().enumerate().zip(args.iter()) { + use ScalarKind::*; - Ok(Some(ctx.add_expression( - Expression::Binary { - op: BinaryOperator::Modulo, - left, - right, - }, - meta, - body, - ))) - } - "min" | "max" => { - if args.len() != 2 { - return Err(Error::wrong_function_args(name, 2, args.len(), meta)); - } - - let (mut arg0, arg0_meta) = args[0]; - let (mut arg1, arg1_meta) = args[1]; - - ctx.binary_implicit_conversion(self, &mut arg0, arg0_meta, &mut arg1, arg1_meta)?; - - if let TypeInner::Vector { size, .. } = *self.resolve_type(ctx, arg0, arg0_meta)? { - ctx.implicit_splat(self, &mut arg1, arg1_meta, Some(size))?; - } - if let TypeInner::Vector { size, .. } = *self.resolve_type(ctx, arg1, arg1_meta)? { - ctx.implicit_splat(self, &mut arg0, arg0_meta, Some(size))?; - } - - Ok(Some(ctx.add_expression( - Expression::Math { - fun: match name.as_str() { - "min" => MathFunction::Min, - "max" => MathFunction::Max, - _ => unreachable!(), - }, - arg: arg0, - arg1: Some(arg1), - arg2: None, - }, - meta, - body, - ))) - } - "pow" | "dot" | "reflect" | "cross" | "outerProduct" | "distance" | "step" | "modf" - | "frexp" | "ldexp" => { - if args.len() != 2 { - return Err(Error::wrong_function_args(name, 2, args.len(), meta)); - } - - let (mut arg0, arg0_meta) = args[0]; - let (mut arg1, arg1_meta) = args[1]; - - ctx.binary_implicit_conversion(self, &mut arg0, arg0_meta, &mut arg1, arg1_meta)?; - - Ok(Some(ctx.add_expression( - Expression::Math { - fun: match name.as_str() { - "pow" => MathFunction::Pow, - "dot" => MathFunction::Dot, - "reflect" => MathFunction::Reflect, - "cross" => MathFunction::Cross, - "outerProduct" => MathFunction::Outer, - "distance" => MathFunction::Distance, - "step" => MathFunction::Step, - "modf" => MathFunction::Modf, - "frexp" => MathFunction::Frexp, - "ldexp" => MathFunction::Ldexp, - _ => unreachable!(), - }, - arg: arg0, - arg1: Some(arg1), - arg2: None, - }, - meta, - body, - ))) - } - "mix" => { - if args.len() != 3 { - return Err(Error::wrong_function_args(name, 3, args.len(), meta)); - } - - let (mut arg, arg_meta) = args[0]; - let (mut arg1, arg1_meta) = args[1]; - let (mut selector, selector_meta) = args[2]; - - ctx.binary_implicit_conversion(self, &mut arg, arg_meta, &mut arg1, arg1_meta)?; - ctx.binary_implicit_conversion( - self, - &mut arg, - arg_meta, - &mut selector, - selector_meta, - )?; - ctx.binary_implicit_conversion( - self, - &mut arg1, - arg1_meta, - &mut selector, - selector_meta, - )?; - - let is_vector = match *self.resolve_type(ctx, selector, selector_meta)? { - TypeInner::Vector { .. } => true, - _ => false, - }; - match *self.resolve_type(ctx, args[0].0, args[0].1)? { - TypeInner::Vector { size, .. } if !is_vector => { - selector = ctx.add_expression( - Expression::Splat { - size, - value: selector, - }, - meta, - body, - ) - } - _ => {} - }; - - let expr = match self - .resolve_type(ctx, selector, selector_meta)? - .scalar_kind() - { - // When the selector is a boolean vector the result is - // calculated per component, for each component of the - // selector if it's false the respective component from the - // first argument is selected, if it's true the respective - // component from the second argument is selected - // - // Note(jcapucho): yes, it's inverted in comparison with the - // IR and SPIR-V and yes I spent a full debugging a shader - // because of this weird behavior - Some(ScalarKind::Bool) => Expression::Select { - condition: selector, - accept: arg1, - reject: arg, - }, - _ => Expression::Math { - fun: MathFunction::Mix, - arg, - arg1: Some(arg1), - arg2: Some(selector), - }, - }; - - Ok(Some(ctx.add_expression(expr, meta, body))) - } - "clamp" => { - if args.len() != 3 { - return Err(Error::wrong_function_args(name, 3, args.len(), meta)); - } - - let (mut arg0, arg0_meta) = args[0]; - let (mut arg1, arg1_meta) = args[1]; - let (mut arg2, arg2_meta) = args[2]; - - let vector_size = match *(self.resolve_type(ctx, arg0, arg0_meta)?) { - TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - - ctx.binary_implicit_conversion(self, &mut arg0, arg0_meta, &mut arg1, arg1_meta)?; - ctx.binary_implicit_conversion(self, &mut arg1, arg1_meta, &mut arg2, arg2_meta)?; - ctx.binary_implicit_conversion(self, &mut arg2, arg2_meta, &mut arg0, arg0_meta)?; - - ctx.implicit_splat(self, &mut arg1, arg1_meta, vector_size)?; - ctx.implicit_splat(self, &mut arg2, arg2_meta, vector_size)?; - - Ok(Some(ctx.add_expression( - Expression::Math { - fun: MathFunction::Clamp, - arg: arg0, - arg1: Some(arg1), - arg2: Some(arg2), - }, - meta, - body, - ))) - } - "faceforward" | "refract" | "fma" | "smoothstep" => { - if args.len() != 3 { - return Err(Error::wrong_function_args(name, 3, args.len(), meta)); - } - Ok(Some(ctx.add_expression( - Expression::Math { - fun: match name.as_str() { - "faceforward" => MathFunction::FaceForward, - "refract" => MathFunction::Refract, - "fma" => MathFunction::Fma, - "smoothstep" => MathFunction::SmoothStep, - _ => unreachable!(), - }, - arg: args[0].0, - arg1: Some(args[1].0), - arg2: Some(args[2].0), - }, - meta, - body, - ))) - } - "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" - | "notEqual" => { - if args.len() != 2 { - return Err(Error::wrong_function_args(name, 2, args.len(), meta)); - } - Ok(Some(ctx.add_expression( - Expression::Binary { - op: match name.as_str() { - "lessThan" => BinaryOperator::Less, - "greaterThan" => BinaryOperator::Greater, - "lessThanEqual" => BinaryOperator::LessEqual, - "greaterThanEqual" => BinaryOperator::GreaterEqual, - "equal" => BinaryOperator::Equal, - "notEqual" => BinaryOperator::NotEqual, - _ => unreachable!(), - }, - left: args[0].0, - right: args[1].0, - }, - meta, - body, - ))) - } - "isinf" | "isnan" | "all" | "any" => { - let fun = match name.as_str() { - "isinf" => RelationalFunction::IsInf, - "isnan" => RelationalFunction::IsNan, - "all" => RelationalFunction::All, - "any" => RelationalFunction::Any, - _ => unreachable!(), - }; - - Ok(Some( - self.parse_relational_fun(ctx, body, name, &args, fun, meta)?, - )) - } - _ => { - let declarations = self.lookup_function.get(&name).ok_or_else(|| Error { - kind: ErrorKind::SemanticError(format!("Unknown function '{}'", name).into()), - meta, - })?; - - let mut maybe_decl = None; - let mut ambiguous = false; - - 'outer: for decl in declarations { - if args.len() != decl.parameters.len() { - continue; - } - - let mut exact = true; - - for ((i, decl_arg), call_arg) in - decl.parameters.iter().enumerate().zip(args.iter()) - { - if decl.parameters_info[i].depth { - sampled_to_depth(&mut self.module, ctx, *call_arg, &mut self.errors)?; - self.invalidate_expression(ctx, call_arg.0, call_arg.1)? - } - - let decl_inner = &self.module.types[*decl_arg].inner; - let call_inner = self.resolve_type(ctx, call_arg.0, call_arg.1)?; - - if decl_inner == call_inner { - continue; - } - - exact = false; - - let (decl_kind, call_kind) = match (decl_inner, call_inner) { - ( - &TypeInner::Scalar { - kind: decl_kind, .. - }, - &TypeInner::Scalar { - kind: call_kind, .. - }, - ) => (decl_kind, call_kind), - ( - &TypeInner::Vector { - kind: decl_kind, - size: decl_size, - .. - }, - &TypeInner::Vector { - kind: call_kind, - size: call_size, - .. - }, - ) if decl_size == call_size => (decl_kind, call_kind), - ( - &TypeInner::Matrix { - rows: decl_rows, - columns: decl_columns, - .. - }, - &TypeInner::Matrix { - rows: call_rows, - columns: call_columns, - .. - }, - ) if decl_columns == call_columns && decl_rows == call_rows => { - (ScalarKind::Float, ScalarKind::Float) - } - _ => continue 'outer, - }; - - match (type_power(decl_kind), type_power(call_kind)) { - (Some(decl_power), Some(call_power)) if decl_power > call_power => {} - _ => continue 'outer, - } - } - - if exact { - maybe_decl = Some(decl); - ambiguous = false; - break; - } else if maybe_decl.is_some() { - ambiguous = true; - } else { - maybe_decl = Some(decl) - } - } - - if ambiguous { - self.errors.push(Error { - kind: ErrorKind::SemanticError( - format!("Ambiguous best function for '{}'", name).into(), - ), - meta, - }) - } - - let decl = maybe_decl.ok_or_else(|| Error { - kind: ErrorKind::SemanticError(format!("Unknown function '{}'", name).into()), - meta, - })?; - - let parameters_info = decl.parameters_info.clone(); - let parameters = decl.parameters.clone(); - let function = decl.handle; - let is_void = decl.void; - - let mut arguments = Vec::with_capacity(args.len()); - let mut proxy_writes = Vec::new(); - for (parameter_info, (expr, parameter)) in parameters_info - .iter() - .zip(raw_args.iter().zip(parameters.iter())) - { - let (mut handle, meta) = ctx.lower_expect_inner( - stmt, - self, - *expr, - parameter_info.qualifier.is_lhs(), - body, + if decl.parameters_info[i].depth { + sampled_to_depth( + &mut self.module, + ctx, + call_arg.0, + call_arg.1, + &mut self.errors, )?; - - if let TypeInner::Vector { size, kind, width } = - *self.resolve_type(ctx, handle, meta)? - { - if parameter_info.qualifier.is_lhs() - && matches!(ctx[handle], Expression::Swizzle { .. }) - { - let ty = self.module.types.fetch_or_append( - Type { - name: None, - inner: TypeInner::Vector { size, kind, width }, - }, - meta.as_span(), - ); - let temp_var = ctx.locals.append( - LocalVariable { - name: None, - ty, - init: None, - }, - meta.as_span(), - ); - let temp_expr = - ctx.add_expression(Expression::LocalVariable(temp_var), meta, body); - - body.push( - Statement::Store { - pointer: temp_expr, - value: handle, - }, - meta.as_span(), - ); - - arguments.push(temp_expr); - proxy_writes.push((*expr, temp_expr)); - continue; - } - } - - let scalar_components = scalar_components(&self.module.types[*parameter].inner); - if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut handle, meta, kind, width)?; - } - - arguments.push(handle) + self.invalidate_expression(ctx, call_arg.0, call_arg.1)? } + let decl_inner = &self.module.types[*decl_arg].inner; + let call_inner = self.resolve_type(ctx, call_arg.0, call_arg.1)?; + + if decl_inner == call_inner { + new_conversions[i] = Conversion::Exact; + continue; + } + + exact = false; + + let (decl_kind, decl_width, call_kind, call_width) = match (decl_inner, call_inner) + { + ( + &TypeInner::Scalar { + kind: decl_kind, + width: decl_width, + }, + &TypeInner::Scalar { + kind: call_kind, + width: call_width, + }, + ) => (decl_kind, decl_width, call_kind, call_width), + ( + &TypeInner::Vector { + kind: decl_kind, + size: decl_size, + width: decl_width, + }, + &TypeInner::Vector { + kind: call_kind, + size: call_size, + width: call_width, + }, + ) if decl_size == call_size => (decl_kind, decl_width, call_kind, call_width), + ( + &TypeInner::Matrix { + rows: decl_rows, + columns: decl_columns, + width: decl_width, + }, + &TypeInner::Matrix { + rows: call_rows, + columns: call_columns, + width: call_width, + }, + ) if decl_columns == call_columns && decl_rows == call_rows => { + (Float, decl_width, Float, call_width) + } + _ => continue 'outer, + }; + + if type_power(decl_kind, decl_width) < type_power(call_kind, call_width) { + continue 'outer; + } + + let conversion = match ((decl_kind, decl_width), (call_kind, call_width)) { + ((Float, 8), (Float, 4)) => Conversion::FloatToDouble, + ((Float, 4), (Sint, _)) | ((Float, 4), (Uint, _)) => Conversion::IntToFloat, + ((Float, 8), (Sint, _)) | ((Float, 8), (Uint, _)) => Conversion::IntToDouble, + _ => Conversion::Other, + }; + + // true - New declaration argument has a better conversion + // false - Old declaration argument has a better conversion + let best_arg = match (conversion, old_conversions[i]) { + (_, Conversion::Exact) => false, + (Conversion::FloatToDouble, _) + | (_, Conversion::None) + | (Conversion::IntToFloat, Conversion::IntToDouble) => true, + (_, Conversion::FloatToDouble) + | (Conversion::IntToDouble, Conversion::IntToFloat) => false, + _ => continue, + }; + + match best_arg { + true => match superior { + Some(false) => ambiguous = true, + _ => { + superior = Some(true); + new_conversions[i] = conversion + } + }, + false => match superior { + Some(true) => ambiguous = true, + _ => superior = Some(false), + }, + } + } + + if exact { + maybe_decl = Some(decl); + ambiguous = false; + break; + } + + match superior { + // New declaration is better keep it + Some(true) => { + maybe_decl = Some(decl); + // Replace the conversions + old_conversions = new_conversions; + } + // Old declaration is better do nothing + Some(false) => {} + // No declaration was better than the other this can be caused + // when + None => { + ambiguous = true; + // Assign the new declaration to make sure we always have + // one to make error reporting happy + maybe_decl = Some(decl); + } + } + } + + if ambiguous { + self.errors.push(Error { + kind: ErrorKind::SemanticError( + format!("Ambiguous best function for '{}'", name).into(), + ), + meta, + }) + } + + let decl = maybe_decl.ok_or_else(|| Error { + kind: ErrorKind::SemanticError(format!("Unknown function '{}'", name).into()), + meta, + })?; + + let parameters_info = decl.parameters_info.clone(); + let parameters = decl.parameters.clone(); + let is_void = decl.void; + let kind = decl.kind; + + let mut arguments = Vec::with_capacity(args.len()); + let mut proxy_writes = Vec::new(); + for (parameter_info, (expr, parameter)) in parameters_info + .iter() + .zip(raw_args.iter().zip(parameters.iter())) + { + let (mut handle, meta) = + ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.is_lhs(), body)?; + + if let TypeInner::Vector { size, kind, width } = + *self.resolve_type(ctx, handle, meta)? + { + if parameter_info.qualifier.is_lhs() + && matches!(ctx[handle], Expression::Swizzle { .. }) + { + let ty = self.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }, + Span::Unknown, + ); + let temp_var = ctx.locals.append( + LocalVariable { + name: None, + ty, + init: None, + }, + Span::Unknown, + ); + let temp_expr = ctx.add_expression( + Expression::LocalVariable(temp_var), + SourceMetadata::none(), + body, + ); + + body.push( + Statement::Store { + pointer: temp_expr, + value: handle, + }, + Span::Unknown, + ); + + arguments.push(temp_expr); + proxy_writes.push((*expr, temp_expr)); + continue; + } + } + + let scalar_components = scalar_components(&self.module.types[*parameter].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut handle, meta, kind, width)?; + } + + arguments.push(handle) + } + + match kind { + FunctionKind::Call(function) => { ctx.emit_flush(body); let result = if !is_void { @@ -1117,32 +645,12 @@ impl Parser { Ok(result) } + FunctionKind::Macro(builtin) => builtin + .call(self, ctx, body, arguments.as_mut_slice(), meta) + .map(Some), } } - pub(crate) fn parse_relational_fun( - &mut self, - ctx: &mut Context, - body: &mut Block, - name: String, - args: &[(Handle, SourceMetadata)], - fun: RelationalFunction, - meta: SourceMetadata, - ) -> Result> { - if args.len() != 1 { - return Err(Error::wrong_function_args(name, 1, args.len(), meta)); - } - - Ok(ctx.add_expression( - Expression::Relational { - fun, - argument: args[0].0, - }, - meta, - body, - )) - } - pub(crate) fn add_function( &mut self, ctx: Context, @@ -1151,6 +659,10 @@ impl Parser { mut body: Block, meta: SourceMetadata, ) { + if self.lookup_function.get(&name).is_none() { + self.inject_builtin(name.clone()); + } + ensure_block_returns(&mut body); let void = result.is_none(); @@ -1203,7 +715,13 @@ impl Parser { decl.defined = true; decl.parameters_info = parameters_info; - *self.module.functions.get_mut(decl.handle) = function; + match decl.kind { + FunctionKind::Call(handle) => *self.module.functions.get_mut(handle) = function, + FunctionKind::Macro(_) => { + let handle = module.functions.append(function, meta.as_span()); + decl.kind = FunctionKind::Call(handle) + } + } return; } @@ -1211,7 +729,7 @@ impl Parser { declarations.push(FunctionDeclaration { parameters, parameters_info, - handle, + kind: FunctionKind::Call(handle), defined: true, void, }); @@ -1224,6 +742,10 @@ impl Parser { result: Option, meta: SourceMetadata, ) { + if self.lookup_function.get(&name).is_none() { + self.inject_builtin(name.clone()); + } + let void = result.is_none(); let &mut Parser { @@ -1271,7 +793,7 @@ impl Parser { declarations.push(FunctionDeclaration { parameters, parameters_info, - handle, + kind: FunctionKind::Call(handle), defined: false, void, }); @@ -1399,149 +921,4 @@ impl Parser { }, }); } - - /// Helper function for texture calls, splits the vector argument into it's components - fn coordinate_components( - &mut self, - ctx: &mut Context, - (image, image_meta): (Handle, SourceMetadata), - (coord, coord_meta): (Handle, SourceMetadata), - body: &mut Block, - ) -> Result { - if let TypeInner::Image { - dim, - arrayed, - class, - } = *self.resolve_type(ctx, image, image_meta)? - { - let image_size = match dim { - ImageDimension::D1 => None, - ImageDimension::D2 => Some(VectorSize::Bi), - ImageDimension::D3 => Some(VectorSize::Tri), - ImageDimension::Cube => Some(VectorSize::Tri), - }; - let coord_size = match *self.resolve_type(ctx, coord, coord_meta)? { - TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - let shadow = match class { - ImageClass::Depth { .. } => true, - _ => false, - }; - - let coordinate = match (image_size, coord_size) { - (Some(size), Some(coord_s)) if size != coord_s => { - ctx.vector_resize(size, coord, coord_meta, body) - } - (None, Some(_)) => ctx.add_expression( - Expression::AccessIndex { - base: coord, - index: 0, - }, - coord_meta, - body, - ), - _ => coord, - }; - let array_index = match arrayed { - true => { - let index = match shadow { - true => image_size.map_or(0, |s| s as u32 - 1), - false => image_size.map_or(0, |s| s as u32), - }; - - Some(ctx.add_expression( - Expression::AccessIndex { base: coord, index }, - coord_meta, - body, - )) - } - _ => None, - }; - let depth_ref = match shadow { - true => { - let index = image_size.map_or(0, |s| s as u32); - - Some(ctx.add_expression( - Expression::AccessIndex { base: coord, index }, - coord_meta, - body, - )) - } - false => None, - }; - - Ok(CoordComponents { - coordinate, - depth_ref, - array_index, - }) - } else { - self.errors.push(Error { - kind: ErrorKind::SemanticError("Type is not an image".into()), - meta: image_meta, - }); - - Ok(CoordComponents { - coordinate: coord, - depth_ref: None, - array_index: None, - }) - } - } -} - -/// Helper function to cast a expression holding a sampled image to a -/// depth image. -fn sampled_to_depth( - module: &mut Module, - ctx: &mut Context, - (image, meta): (Handle, SourceMetadata), - errors: &mut Vec, -) -> Result<()> { - let ty = match ctx[image] { - Expression::GlobalVariable(handle) => &mut module.global_variables.get_mut(handle).ty, - Expression::FunctionArgument(i) => { - ctx.parameters_info[i as usize].depth = true; - &mut ctx.arguments[i as usize].ty - } - _ => { - return Err(Error { - kind: ErrorKind::SemanticError("Not a valid texture expression".into()), - meta, - }) - } - }; - match module.types[*ty].inner { - TypeInner::Image { - class, - dim, - arrayed, - } => match class { - ImageClass::Sampled { multi, .. } => { - *ty = module.types.fetch_or_append( - Type { - name: None, - inner: TypeInner::Image { - dim, - arrayed, - class: ImageClass::Depth { multi }, - }, - }, - module.types.get_span(*ty).clone(), - ) - } - ImageClass::Depth { .. } => {} - _ => errors.push(Error { - kind: ErrorKind::SemanticError("Not a texture".into()), - meta, - }), - }, - _ => errors.push(Error { - kind: ErrorKind::SemanticError("Not a texture".into()), - meta, - }), - }; - - Ok(()) } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 7f8fba66c..29a062b3c 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -15,6 +15,7 @@ use ast::{EntryArg, FunctionDeclaration, GlobalLookup}; use parser::ParsingContext; mod ast; +mod builtins; mod constants; mod context; mod error; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index a43396df6..b62adcca0 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,5 +1,5 @@ use super::{ - ast::{Profile, TypeQualifier}, + ast::{FunctionKind, Profile, TypeQualifier}, context::Context, error::ExpectedToken, error::{Error, ErrorKind}, @@ -140,10 +140,12 @@ impl<'source> ParsingContext<'source> { } match parser.lookup_function.get("main").and_then(|declarations| { - declarations - .iter() - .find(|decl| decl.defined && decl.parameters.is_empty()) - .map(|decl| decl.handle) + declarations.iter().find_map(|decl| match decl.kind { + FunctionKind::Call(handle) if decl.defined && decl.parameters.is_empty() => { + Some(handle) + } + _ => None, + }) }) { Some(handle) => parser.add_entry_point(handle, body, ctx.expressions), None => parser.errors.push(Error { diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 02184e9bd..175c451dc 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -297,7 +297,6 @@ impl<'source> ParsingContext<'source> { stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - // TODO: prefix inc/dec Ok(match self.expect_peek(parser)?.value { TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { let Token { value, meta } = self.bump(parser)?; diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index fe591f65b..7901edcb9 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -2,8 +2,8 @@ use super::{ constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, SourceMetadata, }; use crate::{ - proc::ResolveContext, ArraySize, Constant, Expression, Handle, ImageClass, ImageDimension, - ScalarKind, Type, TypeInner, VectorSize, + proc::ResolveContext, ArraySize, Bytes, Constant, Expression, Handle, ImageClass, + ImageDimension, ScalarKind, Type, TypeInner, VectorSize, }; pub fn parse_type(type_name: &str) -> Option { @@ -159,7 +159,7 @@ pub fn parse_type(type_name: &str) -> Option { } } -pub fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, crate::Bytes)> { +pub fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, Bytes)> { match *ty { TypeInner::Scalar { kind, width } => Some((kind, width)), TypeInner::Vector { kind, width, .. } => Some((kind, width)), @@ -169,11 +169,12 @@ pub fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, crate::Bytes)> { } } -pub fn type_power(kind: ScalarKind) -> Option { +pub fn type_power(kind: ScalarKind, width: Bytes) -> Option { Some(match kind { ScalarKind::Sint => 0, ScalarKind::Uint => 1, - ScalarKind::Float => 2, + ScalarKind::Float if width == 4 => 2, + ScalarKind::Float => 3, ScalarKind::Bool => return None, }) } diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index a0ee76535..e052f4b48 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -19,25 +19,25 @@ fn collatz_iterations(n: u32) -> u32 { break; } { - let _e12: u32 = n1; - if (((_e12 % u32(2)) == u32(0))) { + let _e14: u32 = n1; + if (((f32(_e14) % f32(2)) == f32(0))) { { - let _e19: u32 = n1; - n1 = (_e19 / u32(2)); + let _e22: u32 = n1; + n1 = (_e22 / u32(2)); } } else { { - let _e24: u32 = n1; - n1 = ((u32(3) * _e24) + u32(1)); + let _e27: u32 = n1; + n1 = ((u32(3) * _e27) + u32(1)); } } - let _e30: u32 = i; - local = _e30; - i = (_e30 + 1u); + let _e33: u32 = i; + local = _e33; + i = (_e33 + 1u); } } - let _e35: u32 = i; - return _e35; + let _e38: u32 = i; + return _e38; } fn main1() { diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index ef3344386..8ff5b8823 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -127,13 +127,15 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 factor = (_e44 * _e45); let _e49: f32 = factor; let _e50: f32 = factor; - smoothFactor = clamp((1.0 - (_e49 * _e50)), 0.0, 1.0); - let _e57: f32 = smoothFactor; - let _e58: f32 = smoothFactor; - attenuation = (_e57 * _e58); - let _e61: f32 = attenuation; - let _e64: f32 = distanceSquare1; - return ((_e61 * 1.0) / max(_e64, 0.00009999999747378752)); + let _e56: f32 = factor; + let _e57: f32 = factor; + smoothFactor = clamp((1.0 - (_e56 * _e57)), 0.0, 1.0); + let _e64: f32 = smoothFactor; + let _e65: f32 = smoothFactor; + attenuation = (_e64 * _e65); + let _e68: f32 = attenuation; + let _e73: f32 = distanceSquare1; + return ((_e68 * 1.0) / max(_e73, 0.00009999999747378752)); } fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { @@ -185,19 +187,29 @@ fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 { let _e53: f32 = NoV1; let _e56: f32 = NoV1; let _e58: f32 = a2_; - lambdaV = (_e50 * sqrt((((_e51 - (_e52 * _e53)) * _e56) + _e58))); - let _e63: f32 = NoV1; - let _e64: f32 = NoL1; - let _e65: f32 = a2_; - let _e66: f32 = NoL1; - let _e69: f32 = NoL1; - let _e71: f32 = a2_; - lambdaL = (_e63 * sqrt((((_e64 - (_e65 * _e66)) * _e69) + _e71))); - let _e77: f32 = lambdaV; - let _e78: f32 = lambdaL; - v = (0.5 / (_e77 + _e78)); - let _e82: f32 = v; - return _e82; + let _e60: f32 = NoV1; + let _e61: f32 = a2_; + let _e62: f32 = NoV1; + let _e65: f32 = NoV1; + let _e67: f32 = a2_; + lambdaV = (_e50 * sqrt((((_e60 - (_e61 * _e62)) * _e65) + _e67))); + let _e72: f32 = NoV1; + let _e73: f32 = NoL1; + let _e74: f32 = a2_; + let _e75: f32 = NoL1; + let _e78: f32 = NoL1; + let _e80: f32 = a2_; + let _e82: f32 = NoL1; + let _e83: f32 = a2_; + let _e84: f32 = NoL1; + let _e87: f32 = NoL1; + let _e89: f32 = a2_; + lambdaL = (_e72 * sqrt((((_e82 - (_e83 * _e84)) * _e87) + _e89))); + let _e95: f32 = lambdaV; + let _e96: f32 = lambdaL; + v = (0.5 / (_e95 + _e96)); + let _e100: f32 = v; + return _e100; } fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { @@ -237,13 +249,14 @@ fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { f0_4 = f0_3; LoH1 = LoH; - let _e44: vec3 = f0_4; - f90_4 = clamp(dot(_e44, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); - let _e57: vec3 = f0_4; - let _e58: f32 = f90_4; - let _e59: f32 = LoH1; - let _e60: vec3 = F_Schlick(_e57, _e58, _e59); - return _e60; + let _e49: vec3 = f0_4; + let _e62: vec3 = f0_4; + f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); + let _e75: vec3 = f0_4; + let _e76: f32 = f90_4; + let _e77: f32 = LoH1; + let _e78: vec3 = F_Schlick(_e75, _e76, _e77); + return _e78; } fn specular(f0_5: vec3, roughness4: f32, h1: vec3, NoV2: f32, NoL2: f32, NoH2: f32, LoH2: f32, specularIntensity: f32) -> vec3 { @@ -335,16 +348,21 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV6: f32) -> vec3< let _e69: vec4 = r; let _e71: vec4 = r; let _e76: f32 = NoV7; - let _e80: vec4 = r; + let _e80: f32 = NoV7; let _e83: vec4 = r; - a004_ = ((min((_e69.x * _e71.x), exp2((-(9.279999732971191) * _e76))) * _e80.x) + _e83.y); - let _e91: f32 = a004_; - let _e94: vec4 = r; - AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(_e91)) + _e94.zw); - let _e98: vec3 = f0_8; - let _e99: vec2 = AB; - let _e103: vec2 = AB; - return ((_e98 * vec3(_e99.x)) + vec3(_e103.y)); + let _e85: vec4 = r; + let _e90: f32 = NoV7; + let _e94: f32 = NoV7; + let _e98: vec4 = r; + let _e101: vec4 = r; + a004_ = ((min((_e83.x * _e85.x), exp2((-(9.279999732971191) * _e94))) * _e98.x) + _e101.y); + let _e109: f32 = a004_; + let _e112: vec4 = r; + AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(_e109)) + _e112.zw); + let _e116: vec3 = f0_8; + let _e117: vec2 = AB; + let _e121: vec2 = AB; + return ((_e116 * vec3(_e117.x)) + vec3(_e121.y)); } fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { @@ -352,11 +370,11 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { var clampedPerceptualRoughness: f32; perceptualRoughness1 = perceptualRoughness; - let _e42: f32 = perceptualRoughness1; - clampedPerceptualRoughness = clamp(_e42, 0.08900000154972076, 1.0); - let _e47: f32 = clampedPerceptualRoughness; - let _e48: f32 = clampedPerceptualRoughness; - return (_e47 * _e48); + let _e45: f32 = perceptualRoughness1; + clampedPerceptualRoughness = clamp(_e45, 0.08900000154972076, 1.0); + let _e50: f32 = clampedPerceptualRoughness; + let _e51: f32 = clampedPerceptualRoughness; + return (_e50 * _e51); } fn reinhard(color: vec3) -> vec3 { @@ -389,8 +407,8 @@ fn luminance(v1: vec3) -> f32 { var v2: vec3; v2 = v1; - let _e42: vec3 = v2; - return dot(_e42, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); + let _e47: vec3 = v2; + return dot(_e47, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); } fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { @@ -491,92 +509,120 @@ fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: let _e56: PointLight = light1; let _e59: vec3 = v_WorldPosition1; light_to_frag = (_e56.pos.xyz - _e59.xyz); - let _e63: vec3 = light_to_frag; - let _e64: vec3 = light_to_frag; - distance_square = dot(_e63, _e64); - let _e68: PointLight = light1; - let _e71: f32 = distance_square; - let _e72: PointLight = light1; - let _e75: f32 = getDistanceAttenuation(_e71, _e72.lightParams.x); - rangeAttenuation = _e75; - let _e77: f32 = roughness9; - a1 = _e77; - let _e79: PointLight = light1; - radius = _e79.lightParams.y; - let _e83: vec3 = light_to_frag; - let _e84: vec3 = R1; - let _e86: vec3 = R1; - let _e88: vec3 = light_to_frag; - centerToRay = ((dot(_e83, _e84) * _e86) - _e88); - let _e91: vec3 = light_to_frag; - let _e92: vec3 = centerToRay; - let _e93: f32 = radius; - let _e94: vec3 = centerToRay; - let _e95: vec3 = centerToRay; - closestPoint = (_e91 + (_e92 * clamp((_e93 * inverseSqrt(dot(_e94, _e95))), 0.0, 1.0))); - let _e105: vec3 = closestPoint; - let _e106: vec3 = closestPoint; - LspecLengthInverse = inverseSqrt(dot(_e105, _e106)); - let _e110: f32 = a1; - let _e111: f32 = a1; + let _e65: vec3 = light_to_frag; + let _e66: vec3 = light_to_frag; + distance_square = dot(_e65, _e66); + let _e70: PointLight = light1; + let _e73: f32 = distance_square; + let _e74: PointLight = light1; + let _e77: f32 = getDistanceAttenuation(_e73, _e74.lightParams.x); + rangeAttenuation = _e77; + let _e79: f32 = roughness9; + a1 = _e79; + let _e81: PointLight = light1; + radius = _e81.lightParams.y; + let _e87: vec3 = light_to_frag; + let _e88: vec3 = R1; + let _e90: vec3 = R1; + let _e92: vec3 = light_to_frag; + centerToRay = ((dot(_e87, _e88) * _e90) - _e92); + let _e95: vec3 = light_to_frag; + let _e96: vec3 = centerToRay; + let _e97: f32 = radius; + let _e100: vec3 = centerToRay; + let _e101: vec3 = centerToRay; + let _e105: vec3 = centerToRay; + let _e106: vec3 = centerToRay; let _e112: f32 = radius; - let _e115: f32 = LspecLengthInverse; - normalizationFactor = (_e110 / clamp((_e111 + ((_e112 * 0.5) * _e115)), 0.0, 1.0)); - let _e123: f32 = normalizationFactor; - let _e124: f32 = normalizationFactor; - specularIntensity2 = (_e123 * _e124); - let _e127: vec3 = closestPoint; - let _e128: f32 = LspecLengthInverse; - L = (_e127 * _e128); - let _e131: vec3 = L; - let _e132: vec3 = V2; - H = normalize((_e131 + _e132)); - let _e136: vec3 = N1; - let _e137: vec3 = L; - NoL6 = clamp(dot(_e136, _e137), 0.0, 1.0); - let _e143: vec3 = N1; - let _e144: vec3 = H; - NoH4 = clamp(dot(_e143, _e144), 0.0, 1.0); - let _e150: vec3 = L; - let _e151: vec3 = H; - LoH6 = clamp(dot(_e150, _e151), 0.0, 1.0); - let _e165: vec3 = F0_1; - let _e166: f32 = roughness9; - let _e167: vec3 = H; - let _e168: f32 = NdotV1; - let _e169: f32 = NoL6; - let _e170: f32 = NoH4; - let _e171: f32 = LoH6; - let _e172: f32 = specularIntensity2; - let _e173: vec3 = specular(_e165, _e166, _e167, _e168, _e169, _e170, _e171, _e172); - specular1 = _e173; - let _e175: vec3 = light_to_frag; - L = normalize(_e175); - let _e177: vec3 = L; - let _e178: vec3 = V2; - H = normalize((_e177 + _e178)); - let _e181: vec3 = N1; - let _e182: vec3 = L; - NoL6 = clamp(dot(_e181, _e182), 0.0, 1.0); - let _e187: vec3 = N1; - let _e188: vec3 = H; - NoH4 = clamp(dot(_e187, _e188), 0.0, 1.0); - let _e193: vec3 = L; - let _e194: vec3 = H; - LoH6 = clamp(dot(_e193, _e194), 0.0, 1.0); - let _e199: vec3 = diffuseColor1; - let _e204: f32 = roughness9; - let _e205: f32 = NdotV1; - let _e206: f32 = NoL6; - let _e207: f32 = LoH6; - let _e208: f32 = Fd_Burley(_e204, _e205, _e206, _e207); - diffuse = (_e199 * _e208); - let _e211: vec3 = diffuse; - let _e212: vec3 = specular1; - let _e214: PointLight = light1; - let _e218: f32 = rangeAttenuation; - let _e219: f32 = NoL6; - return (((_e211 + _e212) * _e214.color.xyz) * (_e218 * _e219)); + let _e115: vec3 = centerToRay; + let _e116: vec3 = centerToRay; + let _e120: vec3 = centerToRay; + let _e121: vec3 = centerToRay; + closestPoint = (_e95 + (_e96 * clamp((_e112 * inverseSqrt(dot(_e120, _e121))), 0.0, 1.0))); + let _e133: vec3 = closestPoint; + let _e134: vec3 = closestPoint; + let _e138: vec3 = closestPoint; + let _e139: vec3 = closestPoint; + LspecLengthInverse = inverseSqrt(dot(_e138, _e139)); + let _e143: f32 = a1; + let _e144: f32 = a1; + let _e145: f32 = radius; + let _e148: f32 = LspecLengthInverse; + let _e153: f32 = a1; + let _e154: f32 = radius; + let _e157: f32 = LspecLengthInverse; + normalizationFactor = (_e143 / clamp((_e153 + ((_e154 * 0.5) * _e157)), 0.0, 1.0)); + let _e165: f32 = normalizationFactor; + let _e166: f32 = normalizationFactor; + specularIntensity2 = (_e165 * _e166); + let _e169: vec3 = closestPoint; + let _e170: f32 = LspecLengthInverse; + L = (_e169 * _e170); + let _e173: vec3 = L; + let _e174: vec3 = V2; + let _e176: vec3 = L; + let _e177: vec3 = V2; + H = normalize((_e176 + _e177)); + let _e183: vec3 = N1; + let _e184: vec3 = L; + let _e190: vec3 = N1; + let _e191: vec3 = L; + NoL6 = clamp(dot(_e190, _e191), 0.0, 1.0); + let _e199: vec3 = N1; + let _e200: vec3 = H; + let _e206: vec3 = N1; + let _e207: vec3 = H; + NoH4 = clamp(dot(_e206, _e207), 0.0, 1.0); + let _e215: vec3 = L; + let _e216: vec3 = H; + let _e222: vec3 = L; + let _e223: vec3 = H; + LoH6 = clamp(dot(_e222, _e223), 0.0, 1.0); + let _e237: vec3 = F0_1; + let _e238: f32 = roughness9; + let _e239: vec3 = H; + let _e240: f32 = NdotV1; + let _e241: f32 = NoL6; + let _e242: f32 = NoH4; + let _e243: f32 = LoH6; + let _e244: f32 = specularIntensity2; + let _e245: vec3 = specular(_e237, _e238, _e239, _e240, _e241, _e242, _e243, _e244); + specular1 = _e245; + let _e248: vec3 = light_to_frag; + L = normalize(_e248); + let _e250: vec3 = L; + let _e251: vec3 = V2; + let _e253: vec3 = L; + let _e254: vec3 = V2; + H = normalize((_e253 + _e254)); + let _e259: vec3 = N1; + let _e260: vec3 = L; + let _e266: vec3 = N1; + let _e267: vec3 = L; + NoL6 = clamp(dot(_e266, _e267), 0.0, 1.0); + let _e274: vec3 = N1; + let _e275: vec3 = H; + let _e281: vec3 = N1; + let _e282: vec3 = H; + NoH4 = clamp(dot(_e281, _e282), 0.0, 1.0); + let _e289: vec3 = L; + let _e290: vec3 = H; + let _e296: vec3 = L; + let _e297: vec3 = H; + LoH6 = clamp(dot(_e296, _e297), 0.0, 1.0); + let _e302: vec3 = diffuseColor1; + let _e307: f32 = roughness9; + let _e308: f32 = NdotV1; + let _e309: f32 = NoL6; + let _e310: f32 = LoH6; + let _e311: f32 = Fd_Burley(_e307, _e308, _e309, _e310); + diffuse = (_e302 * _e311); + let _e314: vec3 = diffuse; + let _e315: vec3 = specular1; + let _e317: PointLight = light1; + let _e321: f32 = rangeAttenuation; + let _e322: f32 = NoL6; + return (((_e314 + _e315) * _e317.color.xyz) * (_e321 * _e322)); } fn dir_light(light2: DirectionalLight, roughness10: f32, NdotV2: f32, normal: vec3, view: vec3, R2: vec3, F0_2: vec3, diffuseColor2: vec3) -> vec3 { @@ -609,38 +655,46 @@ fn dir_light(light2: DirectionalLight, roughness10: f32, NdotV2: f32, normal: ve incident_light = _e56.direction.xyz; let _e60: vec3 = incident_light; let _e61: vec3 = view1; - half_vector = normalize((_e60 + _e61)); - let _e65: vec3 = normal1; - let _e66: vec3 = incident_light; - NoL7 = clamp(dot(_e65, _e66), 0.0, 1.0); - let _e72: vec3 = normal1; - let _e73: vec3 = half_vector; - NoH5 = clamp(dot(_e72, _e73), 0.0, 1.0); - let _e79: vec3 = incident_light; - let _e80: vec3 = half_vector; - LoH7 = clamp(dot(_e79, _e80), 0.0, 1.0); - let _e86: vec3 = diffuseColor3; - let _e91: f32 = roughness11; - let _e92: f32 = NdotV3; - let _e93: f32 = NoL7; - let _e94: f32 = LoH7; - let _e95: f32 = Fd_Burley(_e91, _e92, _e93, _e94); - diffuse1 = (_e86 * _e95); - let _e108: vec3 = F0_3; - let _e109: f32 = roughness11; + let _e63: vec3 = incident_light; + let _e64: vec3 = view1; + half_vector = normalize((_e63 + _e64)); + let _e70: vec3 = normal1; + let _e71: vec3 = incident_light; + let _e77: vec3 = normal1; + let _e78: vec3 = incident_light; + NoL7 = clamp(dot(_e77, _e78), 0.0, 1.0); + let _e86: vec3 = normal1; + let _e87: vec3 = half_vector; + let _e93: vec3 = normal1; + let _e94: vec3 = half_vector; + NoH5 = clamp(dot(_e93, _e94), 0.0, 1.0); + let _e102: vec3 = incident_light; + let _e103: vec3 = half_vector; + let _e109: vec3 = incident_light; let _e110: vec3 = half_vector; - let _e111: f32 = NdotV3; - let _e112: f32 = NoL7; - let _e113: f32 = NoH5; - let _e114: f32 = LoH7; - let _e115: f32 = specularIntensity3; - let _e116: vec3 = specular(_e108, _e109, _e110, _e111, _e112, _e113, _e114, _e115); - specular2 = _e116; - let _e118: vec3 = specular2; - let _e119: vec3 = diffuse1; - let _e121: DirectionalLight = light3; - let _e125: f32 = NoL7; - return (((_e118 + _e119) * _e121.color.xyz) * _e125); + LoH7 = clamp(dot(_e109, _e110), 0.0, 1.0); + let _e116: vec3 = diffuseColor3; + let _e121: f32 = roughness11; + let _e122: f32 = NdotV3; + let _e123: f32 = NoL7; + let _e124: f32 = LoH7; + let _e125: f32 = Fd_Burley(_e121, _e122, _e123, _e124); + diffuse1 = (_e116 * _e125); + let _e138: vec3 = F0_3; + let _e139: f32 = roughness11; + let _e140: vec3 = half_vector; + let _e141: f32 = NdotV3; + let _e142: f32 = NoL7; + let _e143: f32 = NoH5; + let _e144: f32 = LoH7; + let _e145: f32 = specularIntensity3; + let _e146: vec3 = specular(_e138, _e139, _e140, _e141, _e142, _e143, _e144, _e145); + specular2 = _e146; + let _e148: vec3 = specular2; + let _e149: vec3 = diffuse1; + let _e151: DirectionalLight = light3; + let _e155: f32 = NoL7; + return (((_e148 + _e149) * _e151.color.xyz) * _e155); } fn main1() { @@ -669,175 +723,183 @@ fn main1() { let _e40: vec4 = global3.base_color; output_color = _e40; let _e42: vec4 = output_color; - let _e43: vec2 = v_Uv1; - let _e44: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e43); - output_color = (_e42 * _e44); - let _e46: vec2 = v_Uv1; - let _e47: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e46); - metallic_roughness = _e47; - let _e49: f32 = global5.metallic; - let _e50: vec4 = metallic_roughness; - metallic = (_e49 * _e50.z); - let _e54: f32 = global4.perceptual_roughness; - let _e55: vec4 = metallic_roughness; - perceptual_roughness2 = (_e54 * _e55.y); - let _e60: f32 = perceptual_roughness2; - let _e61: f32 = perceptualRoughnessToRoughness(_e60); - roughness12 = _e61; - let _e63: vec3 = v_WorldNormal1; - N2 = normalize(_e63); - let _e66: vec4 = v_WorldTangent1; - T = normalize(_e66.xyz); - let _e70: vec3 = N2; - let _e71: vec3 = T; - let _e73: vec4 = v_WorldTangent1; - B = (cross(_e70, _e71) * _e73.w); - let _e78: bool = gl_FrontFacing; - let _e79: vec3 = N2; - let _e80: vec3 = N2; - N2 = select(-(_e80), _e79, _e78); - let _e83: bool = gl_FrontFacing; - let _e84: vec3 = T; - let _e85: vec3 = T; - T = select(-(_e85), _e84, _e83); - let _e88: bool = gl_FrontFacing; - let _e89: vec3 = B; - let _e90: vec3 = B; - B = select(-(_e90), _e89, _e88); - let _e93: vec3 = T; - let _e94: vec3 = B; - let _e95: vec3 = N2; - TBN = mat3x3(vec3(_e93.x, _e93.y, _e93.z), vec3(_e94.x, _e94.y, _e94.z), vec3(_e95.x, _e95.y, _e95.z)); - let _e110: mat3x3 = TBN; - let _e111: vec2 = v_Uv1; - let _e112: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e111); - N2 = (_e110 * normalize(((_e112.xyz * 2.0) - vec3(1.0)))); - let _e121: vec2 = v_Uv1; - let _e122: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e121); - occlusion = _e122.x; - let _e125: vec4 = global7.emissive; - emissive = _e125; - let _e127: vec4 = emissive; - let _e129: vec4 = emissive; - let _e131: vec2 = v_Uv1; - let _e132: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e131); - let _e134: vec3 = (_e129.xyz * _e132.xyz); - emissive.x = _e134.x; - emissive.y = _e134.y; - emissive.z = _e134.z; - let _e141: vec4 = global1.CameraPos; - let _e143: vec3 = v_WorldPosition1; - V3 = normalize((_e141.xyz - _e143.xyz)); - let _e148: vec3 = N2; - let _e149: vec3 = V3; - NdotV4 = max(dot(_e148, _e149), 0.00009999999747378752); - let _e155: f32 = global6.reflectance; - let _e157: f32 = global6.reflectance; - let _e160: f32 = metallic; - let _e164: vec4 = output_color; - let _e166: f32 = metallic; - F0_4 = (vec3((((0.1599999964237213 * _e155) * _e157) * (1.0 - _e160))) + (_e164.xyz * vec3(_e166))); - let _e171: vec4 = output_color; - let _e174: f32 = metallic; - diffuseColor4 = (_e171.xyz * vec3((1.0 - _e174))); - let _e179: vec3 = V3; - let _e181: vec3 = N2; - R4 = reflect(-(_e179), _e181); + let _e44: vec2 = v_Uv1; + let _e45: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e44); + output_color = (_e42 * _e45); + let _e48: vec2 = v_Uv1; + let _e49: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e48); + metallic_roughness = _e49; + let _e51: f32 = global5.metallic; + let _e52: vec4 = metallic_roughness; + metallic = (_e51 * _e52.z); + let _e56: f32 = global4.perceptual_roughness; + let _e57: vec4 = metallic_roughness; + perceptual_roughness2 = (_e56 * _e57.y); + let _e62: f32 = perceptual_roughness2; + let _e63: f32 = perceptualRoughnessToRoughness(_e62); + roughness12 = _e63; + let _e66: vec3 = v_WorldNormal1; + N2 = normalize(_e66); + let _e69: vec4 = v_WorldTangent1; + let _e71: vec4 = v_WorldTangent1; + T = normalize(_e71.xyz); + let _e77: vec3 = N2; + let _e78: vec3 = T; + let _e80: vec4 = v_WorldTangent1; + B = (cross(_e77, _e78) * _e80.w); + let _e85: bool = gl_FrontFacing; + let _e86: vec3 = N2; + let _e87: vec3 = N2; + N2 = select(-(_e87), _e86, _e85); + let _e90: bool = gl_FrontFacing; + let _e91: vec3 = T; + let _e92: vec3 = T; + T = select(-(_e92), _e91, _e90); + let _e95: bool = gl_FrontFacing; + let _e96: vec3 = B; + let _e97: vec3 = B; + B = select(-(_e97), _e96, _e95); + let _e100: vec3 = T; + let _e101: vec3 = B; + let _e102: vec3 = N2; + TBN = mat3x3(vec3(_e100.x, _e100.y, _e100.z), vec3(_e101.x, _e101.y, _e101.z), vec3(_e102.x, _e102.y, _e102.z)); + let _e117: mat3x3 = TBN; + let _e119: vec2 = v_Uv1; + let _e120: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e119); + let _e128: vec2 = v_Uv1; + let _e129: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e128); + N2 = (_e117 * normalize(((_e129.xyz * 2.0) - vec3(1.0)))); + let _e139: vec2 = v_Uv1; + let _e140: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e139); + occlusion = _e140.x; + let _e143: vec4 = global7.emissive; + emissive = _e143; + let _e145: vec4 = emissive; + let _e147: vec4 = emissive; + let _e150: vec2 = v_Uv1; + let _e151: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e150); + let _e153: vec3 = (_e147.xyz * _e151.xyz); + emissive.x = _e153.x; + emissive.y = _e153.y; + emissive.z = _e153.z; + let _e160: vec4 = global1.CameraPos; + let _e162: vec3 = v_WorldPosition1; + let _e165: vec4 = global1.CameraPos; + let _e167: vec3 = v_WorldPosition1; + V3 = normalize((_e165.xyz - _e167.xyz)); + let _e174: vec3 = N2; + let _e175: vec3 = V3; + let _e180: vec3 = N2; + let _e181: vec3 = V3; + NdotV4 = max(dot(_e180, _e181), 0.00009999999747378752); + let _e187: f32 = global6.reflectance; + let _e189: f32 = global6.reflectance; + let _e192: f32 = metallic; + let _e196: vec4 = output_color; + let _e198: f32 = metallic; + F0_4 = (vec3((((0.1599999964237213 * _e187) * _e189) * (1.0 - _e192))) + (_e196.xyz * vec3(_e198))); + let _e203: vec4 = output_color; + let _e206: f32 = metallic; + diffuseColor4 = (_e203.xyz * vec3((1.0 - _e206))); + let _e211: vec3 = V3; + let _e214: vec3 = V3; + let _e216: vec3 = N2; + R4 = reflect(-(_e214), _e216); loop { - let _e189: i32 = i; - let _e190: vec4 = global2.NumLights; - let _e194: i32 = i; - if (!(((_e189 < i32(_e190.x)) && (_e194 < 10)))) { + let _e224: i32 = i; + let _e225: vec4 = global2.NumLights; + let _e229: i32 = i; + if (!(((_e224 < i32(_e225.x)) && (_e229 < 10)))) { break; } { - let _e201: vec3 = light_accum; - let _e202: i32 = i; - let _e212: i32 = i; - let _e214: PointLight = global2.PointLights[_e212]; - let _e215: f32 = roughness12; - let _e216: f32 = NdotV4; - let _e217: vec3 = N2; - let _e218: vec3 = V3; - let _e219: vec3 = R4; - let _e220: vec3 = F0_4; - let _e221: vec3 = diffuseColor4; - let _e222: vec3 = point_light(_e214, _e215, _e216, _e217, _e218, _e219, _e220, _e221); - light_accum = (_e201 + _e222); + let _e236: vec3 = light_accum; + let _e237: i32 = i; + let _e247: i32 = i; + let _e249: PointLight = global2.PointLights[_e247]; + let _e250: f32 = roughness12; + let _e251: f32 = NdotV4; + let _e252: vec3 = N2; + let _e253: vec3 = V3; + let _e254: vec3 = R4; + let _e255: vec3 = F0_4; + let _e256: vec3 = diffuseColor4; + let _e257: vec3 = point_light(_e249, _e250, _e251, _e252, _e253, _e254, _e255, _e256); + light_accum = (_e236 + _e257); } continuing { - let _e198: i32 = i; - i = (_e198 + 1); + let _e233: i32 = i; + i = (_e233 + 1); } } loop { - let _e226: i32 = i1; - let _e227: vec4 = global2.NumLights; - let _e231: i32 = i1; - if (!(((_e226 < i32(_e227.y)) && (_e231 < 1)))) { + let _e261: i32 = i1; + let _e262: vec4 = global2.NumLights; + let _e266: i32 = i1; + if (!(((_e261 < i32(_e262.y)) && (_e266 < 1)))) { break; } { - let _e238: vec3 = light_accum; - let _e239: i32 = i1; - let _e249: i32 = i1; - let _e251: DirectionalLight = global2.DirectionalLights[_e249]; - let _e252: f32 = roughness12; - let _e253: f32 = NdotV4; - let _e254: vec3 = N2; - let _e255: vec3 = V3; - let _e256: vec3 = R4; - let _e257: vec3 = F0_4; - let _e258: vec3 = diffuseColor4; - let _e259: vec3 = dir_light(_e251, _e252, _e253, _e254, _e255, _e256, _e257, _e258); - light_accum = (_e238 + _e259); + let _e273: vec3 = light_accum; + let _e274: i32 = i1; + let _e284: i32 = i1; + let _e286: DirectionalLight = global2.DirectionalLights[_e284]; + let _e287: f32 = roughness12; + let _e288: f32 = NdotV4; + let _e289: vec3 = N2; + let _e290: vec3 = V3; + let _e291: vec3 = R4; + let _e292: vec3 = F0_4; + let _e293: vec3 = diffuseColor4; + let _e294: vec3 = dir_light(_e286, _e287, _e288, _e289, _e290, _e291, _e292, _e293); + light_accum = (_e273 + _e294); } continuing { - let _e235: i32 = i1; - i1 = (_e235 + 1); + let _e270: i32 = i1; + i1 = (_e270 + 1); } } - let _e264: vec3 = diffuseColor4; - let _e266: f32 = NdotV4; - let _e267: vec3 = EnvBRDFApprox(_e264, 1.0, _e266); - diffuse_ambient = _e267; - let _e272: vec3 = F0_4; - let _e273: f32 = perceptual_roughness2; - let _e274: f32 = NdotV4; - let _e275: vec3 = EnvBRDFApprox(_e272, _e273, _e274); - specular_ambient = _e275; - let _e277: vec4 = output_color; - let _e279: vec3 = light_accum; - output_color.x = _e279.x; - output_color.y = _e279.y; - output_color.z = _e279.z; - let _e286: vec4 = output_color; - let _e288: vec4 = output_color; - let _e290: vec3 = diffuse_ambient; - let _e291: vec3 = specular_ambient; - let _e293: vec4 = global2.AmbientColor; - let _e296: f32 = occlusion; - let _e298: vec3 = (_e288.xyz + (((_e290 + _e291) * _e293.xyz) * _e296)); - output_color.x = _e298.x; - output_color.y = _e298.y; - output_color.z = _e298.z; - let _e305: vec4 = output_color; - let _e307: vec4 = output_color; - let _e309: vec4 = emissive; - let _e311: vec4 = output_color; - let _e314: vec3 = (_e307.xyz + (_e309.xyz * _e311.w)); + let _e299: vec3 = diffuseColor4; + let _e301: f32 = NdotV4; + let _e302: vec3 = EnvBRDFApprox(_e299, 1.0, _e301); + diffuse_ambient = _e302; + let _e307: vec3 = F0_4; + let _e308: f32 = perceptual_roughness2; + let _e309: f32 = NdotV4; + let _e310: vec3 = EnvBRDFApprox(_e307, _e308, _e309); + specular_ambient = _e310; + let _e312: vec4 = output_color; + let _e314: vec3 = light_accum; output_color.x = _e314.x; output_color.y = _e314.y; output_color.z = _e314.z; let _e321: vec4 = output_color; let _e323: vec4 = output_color; - let _e325: vec4 = output_color; - let _e327: vec3 = reinhard_luminance(_e325.xyz); - output_color.x = _e327.x; - output_color.y = _e327.y; - output_color.z = _e327.z; - let _e334: vec4 = output_color; - o_Target = _e334; + let _e325: vec3 = diffuse_ambient; + let _e326: vec3 = specular_ambient; + let _e328: vec4 = global2.AmbientColor; + let _e331: f32 = occlusion; + let _e333: vec3 = (_e323.xyz + (((_e325 + _e326) * _e328.xyz) * _e331)); + output_color.x = _e333.x; + output_color.y = _e333.y; + output_color.z = _e333.z; + let _e340: vec4 = output_color; + let _e342: vec4 = output_color; + let _e344: vec4 = emissive; + let _e346: vec4 = output_color; + let _e349: vec3 = (_e342.xyz + (_e344.xyz * _e346.w)); + output_color.x = _e349.x; + output_color.y = _e349.y; + output_color.z = _e349.z; + let _e356: vec4 = output_color; + let _e358: vec4 = output_color; + let _e360: vec4 = output_color; + let _e362: vec3 = reinhard_luminance(_e360.xyz); + output_color.x = _e362.x; + output_color.y = _e362.y; + output_color.z = _e362.z; + let _e369: vec4 = output_color; + o_Target = _e369; return; } diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index bf0e64fb4..9f26d9d76 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -21,9 +21,9 @@ fn TevPerCompGT1(a2: vec3, b2: vec3) -> vec3 { a3 = a2; b3 = b2; - let _e5: vec3 = a3; - let _e6: vec3 = b3; - return select(vec3(0.0), vec3(1.0), (_e5 > _e6)); + let _e7: vec3 = a3; + let _e8: vec3 = b3; + return select(vec3(0.0), vec3(1.0), (_e7 > _e8)); } fn main1() { diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index 3c9ec4535..bbc28b22a 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -6,8 +6,8 @@ var a_pos1: vec2; var gl_Position: vec4; fn main1() { - let _e2: vec2 = a_pos1; - gl_Position = vec4(clamp(_e2, vec2(0.0), vec2(1.0)), 0.0, 1.0); + let _e5: vec2 = a_pos1; + gl_Position = vec4(clamp(_e5, vec2(0.0), vec2(1.0)), 0.0, 1.0); return; } diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 03ec93e05..32602b9b5 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -48,95 +48,102 @@ fn main1() { let _e8: vec4 = a; let _e9: vec4 = b; m = mat4x4(vec4(_e6.x, _e6.y, _e6.z, _e6.w), vec4(_e7.x, _e7.y, _e7.z, _e7.w), vec4(_e8.x, _e8.y, _e8.z, _e8.w), vec4(_e9.x, _e9.y, _e9.z, _e9.w)); - let _e34: vec4 = a; - ceilOut = ceil(_e34); - let _e37: vec4 = a; - roundOut = round(_e37); - let _e40: vec4 = a; - floorOut = floor(_e40); + let _e35: vec4 = a; + ceilOut = ceil(_e35); + let _e39: vec4 = a; + roundOut = round(_e39); let _e43: vec4 = a; - fractOut = fract(_e43); - let _e46: vec4 = a; - truncOut = trunc(_e46); - let _e49: vec4 = a; - sinOut = sin(_e49); - let _e52: vec4 = a; - absOut = abs(_e52); + floorOut = floor(_e43); + let _e47: vec4 = a; + fractOut = fract(_e47); + let _e51: vec4 = a; + truncOut = trunc(_e51); let _e55: vec4 = a; - sqrtOut = sqrt(_e55); - let _e58: vec4 = a; - inversesqrtOut = inverseSqrt(_e58); - let _e61: vec4 = a; - expOut = exp(_e61); - let _e64: vec4 = a; - exp2Out = exp2(_e64); + sinOut = sin(_e55); + let _e59: vec4 = a; + absOut = abs(_e59); + let _e63: vec4 = a; + sqrtOut = sqrt(_e63); let _e67: vec4 = a; - signOut = sign(_e67); - let _e70: mat4x4 = m; - transposeOut = transpose(_e70); - let _e73: vec4 = a; - normalizeOut = normalize(_e73); - let _e76: vec4 = a; - sinhOut = sinh(_e76); + inversesqrtOut = inverseSqrt(_e67); + let _e71: vec4 = a; + expOut = exp(_e71); + let _e75: vec4 = a; + exp2Out = exp2(_e75); let _e79: vec4 = a; - cosOut = cos(_e79); - let _e82: vec4 = a; - coshOut = cosh(_e82); - let _e85: vec4 = a; - tanOut = tan(_e85); - let _e88: vec4 = a; - tanhOut = tanh(_e88); + signOut = sign(_e79); + let _e83: mat4x4 = m; + transposeOut = transpose(_e83); + let _e87: vec4 = a; + normalizeOut = normalize(_e87); let _e91: vec4 = a; - acosOut = acos(_e91); - let _e94: vec4 = a; - asinOut = asin(_e94); - let _e97: vec4 = a; - logOut = log(_e97); - let _e100: vec4 = a; - log2Out = log2(_e100); + sinhOut = sinh(_e91); + let _e95: vec4 = a; + cosOut = cos(_e95); + let _e99: vec4 = a; + coshOut = cosh(_e99); let _e103: vec4 = a; - lengthOut = length(_e103); - let _e106: mat4x4 = m; - determinantOut = determinant(_e106); - let _e109: i32 = i; - bitCountOut = countOneBits(_e109); - let _e112: i32 = i; - bitfieldReverseOut = reverseBits(_e112); + tanOut = tan(_e103); + let _e107: vec4 = a; + tanhOut = tanh(_e107); + let _e111: vec4 = a; + acosOut = acos(_e111); let _e115: vec4 = a; - atanOut = atan(_e115.x); + asinOut = asin(_e115); let _e119: vec4 = a; - let _e121: vec4 = a; - atan2Out = atan2(_e119.x, _e121.y); - let _e125: vec4 = a; - let _e127: vec4 = b; - modOut = (_e125.x % _e127.x); - let _e131: vec4 = a; - let _e132: vec4 = b; - powOut = pow(_e131, _e132); - let _e135: vec4 = a; - let _e136: vec4 = b; - dotOut = dot(_e135, _e136); - let _e139: vec4 = a; - let _e140: vec4 = b; - maxOut = max(_e139, _e140); - let _e143: vec4 = a; - let _e144: vec4 = b; - minOut = min(_e143, _e144); - let _e147: vec4 = a; - let _e148: vec4 = b; - reflectOut = reflect(_e147, _e148); - let _e151: vec4 = a; - let _e153: vec4 = b; - crossOut = cross(_e151.xyz, _e153.xyz); - let _e157: vec4 = a; - let _e158: vec4 = b; - outerProductOut = outerProduct(_e157, _e158); - let _e161: vec4 = a; - let _e162: vec4 = b; - distanceOut = distance(_e161, _e162); - let _e165: vec4 = a; - let _e166: vec4 = b; - stepOut = step(_e165, _e166); + logOut = log(_e119); + let _e123: vec4 = a; + log2Out = log2(_e123); + let _e127: vec4 = a; + lengthOut = length(_e127); + let _e131: mat4x4 = m; + determinantOut = determinant(_e131); + let _e135: i32 = i; + bitCountOut = countOneBits(_e135); + let _e139: i32 = i; + bitfieldReverseOut = reverseBits(_e139); + let _e142: vec4 = a; + let _e144: vec4 = a; + atanOut = atan(_e144.x); + let _e148: vec4 = a; + let _e150: vec4 = a; + let _e152: vec4 = a; + let _e154: vec4 = a; + atan2Out = atan2(_e152.x, _e154.y); + let _e158: vec4 = a; + let _e160: vec4 = b; + let _e162: vec4 = a; + let _e164: vec4 = b; + modOut = (_e162.x % _e164.x); + let _e170: vec4 = a; + let _e171: vec4 = b; + powOut = pow(_e170, _e171); + let _e176: vec4 = a; + let _e177: vec4 = b; + dotOut = dot(_e176, _e177); + let _e182: vec4 = a; + let _e183: vec4 = b; + maxOut = max(_e182, _e183); + let _e188: vec4 = a; + let _e189: vec4 = b; + minOut = min(_e188, _e189); + let _e194: vec4 = a; + let _e195: vec4 = b; + reflectOut = reflect(_e194, _e195); + let _e198: vec4 = a; + let _e200: vec4 = b; + let _e202: vec4 = a; + let _e204: vec4 = b; + crossOut = cross(_e202.xyz, _e204.xyz); + let _e210: vec4 = a; + let _e211: vec4 = b; + outerProductOut = outerProduct(_e210, _e211); + let _e216: vec4 = a; + let _e217: vec4 = b; + distanceOut = distance(_e216, _e217); + let _e222: vec4 = a; + let _e223: vec4 = b; + stepOut = step(_e222, _e223); return; } From 4e181d6af4b758c11482b633b3a54b58bfbd4a59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 18 Aug 2021 00:14:47 +0100 Subject: [PATCH 1243/2212] [glsl-in] Only add builtins with double arguments if needed --- src/front/glsl/ast.rs | 12 +- src/front/glsl/builtins.rs | 2435 ++++++++++++++++++----------------- src/front/glsl/functions.rs | 77 +- src/front/glsl/mod.rs | 2 +- src/front/glsl/parser.rs | 17 +- 5 files changed, 1356 insertions(+), 1187 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index f449c661d..8a8cdc0cd 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -47,7 +47,7 @@ impl fmt::Debug for FunctionKind { } #[derive(Debug)] -pub struct FunctionDeclaration { +pub struct Overload { /// Normalized function parameters, modifiers are not applied pub parameters: Vec>, pub parameters_info: Vec, @@ -59,6 +59,16 @@ pub struct FunctionDeclaration { pub void: bool, } +#[derive(Debug, Default)] +pub struct FunctionDeclaration { + pub overloads: Vec, + /// Wether or not this function has the name of a builtin + pub builtin: bool, + /// In case [`builtin`](Self::builtin) is true, this field indicates wether + /// this function already has double overloads added or not, otherwise is unused + pub double: bool, +} + #[derive(Debug)] pub struct EntryArg { pub name: Option, diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 7d45d44c1..19fb38949 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1,16 +1,17 @@ use super::{ - ast::{FunctionDeclaration, FunctionKind, ParameterInfo, ParameterQualifier}, + ast::{FunctionDeclaration, FunctionKind, Overload, ParameterInfo, ParameterQualifier}, context::Context, Error, ErrorKind, Parser, Result, SourceMetadata, }; use crate::{ BinaryOperator, Block, Expression, Handle, ImageClass, ImageDimension, ImageQuery, - MathFunction, Module, RelationalFunction, SampleLevel, Span, Type, TypeInner, VectorSize, + MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind as Sk, Span, Type, TypeInner, + VectorSize, }; impl Module { /// Helper function, to create a function prototype for a builtin - fn add_builtin(&mut self, args: Vec, builtin: MacroCall) -> FunctionDeclaration { + fn add_builtin(&mut self, args: Vec, builtin: MacroCall) -> Overload { let mut parameters = Vec::with_capacity(args.len()); let mut parameters_info = Vec::with_capacity(args.len()); @@ -28,7 +29,7 @@ impl Module { }); } - FunctionDeclaration { + Overload { parameters, parameters_info, kind: FunctionKind::Macro(builtin), @@ -38,1193 +39,1307 @@ impl Module { } } -impl Parser { - /// Injects a builtin into the [`lookup_function`](Self::lookup_function) - /// - /// This is done to not add a large startup cost and not increase memory - /// usage if it isn't needed. - pub(crate) fn inject_builtin(&mut self, name: String) { - use crate::{ImageDimension as Dim, ScalarKind as Sk}; +/// Inject builtins into +/// +/// This is done to not add a large startup cost and not increase memory +/// usage if it isn't needed. +/// +/// This version does not add builtins with arguments using the double type +/// [`inject_double_builtin`](inject_double_builtin) for builtins +/// using the double type +pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module, name: &str) { + use crate::ImageDimension as Dim; - let declarations = self.lookup_function.entry(name.clone()).or_default(); - - match name.as_str() { - "sampler1D" | "sampler1DArray" | "sampler2D" | "sampler2DArray" | "sampler2DMS" - | "sampler2DMSArray" | "sampler3D" | "samplerCube" | "samplerCubeArray" => declarations - .push(self.module.add_builtin( - vec![ - TypeInner::Image { - dim: match name.as_str() { - "sampler1D" | "sampler1DArray" => Dim::D1, - "sampler2D" | "sampler2DArray" | "sampler2DMS" - | "sampler2DMSArray" => Dim::D2, - "sampler3D" => Dim::D3, - _ => Dim::Cube, - }, - arrayed: matches!( - name.as_str(), - "sampler1DArray" - | "sampler2DArray" - | "sampler2DMSArray" - | "samplerCubeArray" - ), - class: ImageClass::Sampled { - kind: Sk::Float, - multi: matches!(name.as_str(), "sampler2DMS" | "sampler2DMSArray"), - }, - }, - TypeInner::Sampler { comparison: false }, - ], - MacroCall::Sampler, - )), - "sampler1DShadow" - | "sampler1DArrayShadow" - | "sampler2DShadow" - | "sampler2DArrayShadow" - | "samplerCubeShadow" - | "samplerCubeArrayShadow" => { - let dim = match name.as_str() { - "sampler1DShadow" | "sampler1DArrayShadow" => Dim::D1, - "sampler2DShadow" | "sampler2DArrayShadow" => Dim::D2, - _ => Dim::Cube, - }; - let arrayed = matches!( - name.as_str(), - "sampler1DArrayShadow" | "sampler2DArrayShadow" | "samplerCubeArrayShadow" - ); - - for i in 0..2 { - let ty = TypeInner::Image { - dim, - arrayed, - class: match i { - 0 => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, - _ => ImageClass::Depth { multi: false }, - }, - }; - - declarations.push(self.module.add_builtin( - vec![ty, TypeInner::Sampler { comparison: true }], - MacroCall::SamplerShadow, - )) - } - } - "texture" | "textureLod" => { - // bits layout - // bits 0 trough 1 - dims - // bit 2 - shadow - // bit 3 - array - // bit 4 - !bias - // - // 0b11111 is the latest since there are not 3D arrayed shadowed - // textures and cube arrayed shadows textures always have a - // compare argument - for bits in 0..(0b100000) { - let dim = bits & 0b11; - let shadow = bits & 0b100 == 0b100; - let arrayed = bits & 0b1000 == 0b1000; - let bias = bits & 0b10000 == 0b00000; - let builtin = match name.as_str() { - "texture" => MacroCall::Texture, - _ => MacroCall::TextureLod, - }; - - // Shadow, arrayed or both 3D images are not allowed - if (shadow || arrayed) && dim == 0b11 - || (builtin == MacroCall::TextureLod - && (dim != 0b00 && shadow && arrayed || dim == 0b10 && shadow || !bias)) - { - continue; - } - - let class = match shadow { - true => ImageClass::Depth { multi: false }, - false => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, - }; - - let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, - 0b10 => Dim::Cube, - _ => Dim::D3, - }, - arrayed, - class, - }; - - let vector = match (dim, shadow) { - (0b00, false) => TypeInner::Scalar { - kind: Sk::Float, - width: 4, - }, - (0b00, true) | (0b11, _) => TypeInner::Vector { - size: VectorSize::Tri, - kind: Sk::Float, - width: 4, - }, - (_, _) => { - let size = match dim + arrayed as u32 + shadow as u32 { - 1 => VectorSize::Bi, - 2 => VectorSize::Tri, - _ => VectorSize::Quad, - }; - - TypeInner::Vector { - size, - kind: Sk::Float, - width: 4, + declaration.builtin = true; + let width = 4; + match name { + "sampler1D" | "sampler1DArray" | "sampler2D" | "sampler2DArray" | "sampler2DMS" + | "sampler2DMSArray" | "sampler3D" | "samplerCube" | "samplerCubeArray" => { + declaration.overloads.push(module.add_builtin( + vec![ + TypeInner::Image { + dim: match name { + "sampler1D" | "sampler1DArray" => Dim::D1, + "sampler2D" | "sampler2DArray" | "sampler2DMS" | "sampler2DMSArray" => { + Dim::D2 } - } - }; - - let mut args = vec![image, vector]; - - if bias { - args.push(TypeInner::Scalar { - kind: Sk::Float, - width: 4, - }) - } - - declarations.push(self.module.add_builtin(args, builtin)) - } - } - "textureProj" => { - // bits layout - // bit 0 - shadow - // bit 1 - bias - // bits 2 trough 3 - dims - // - // 0b0111 is the latest since there are only 1D and 2D shadow - // variants - for bits in 0..(0b1000) { - let dim = bits >> 2; - let shadow = bits & 0b1 == 0b1; - let bias = bits & 0b10 == 0b10; - - let class = match shadow { - true => ImageClass::Depth { multi: false }, - false => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, - }; - - let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, + "sampler3D" => Dim::D3, _ => Dim::Cube, }, - arrayed: false, - class, - }; - - let vector = TypeInner::Vector { - size: VectorSize::Quad, - kind: Sk::Float, - width: 4, - }; - - let mut args = vec![image, vector]; - - if bias { - args.push(TypeInner::Scalar { - kind: Sk::Float, - width: 4, - }) - } - - declarations.push(self.module.add_builtin(args, MacroCall::TextureProj)) - } - } - "textureGrad" => { - // bits layout - // bits 0 trough 1 - dims - // bit 2 - shadow - // bit 3 - array - // - // 0b1010 is the latest since there are no 3D arrayed shadowed - // textures and cube arrayed shadows textures are not allowed - for bits in 0..(0b1011) { - let dim = bits & 0b11; - let shadow = bits & 0b100 == 0b100; - let arrayed = bits & 0b1000 == 0b1000; - - // Shadow, arrayed or both 3D images are not allowed - if shadow && dim == 0b11 - // samplerCubeArrayShadow is not allowed - || shadow && arrayed && dim == 0b10 - { - continue; - } - - let class = match shadow { - true => ImageClass::Depth { multi: false }, - false => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, - }; - - let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, - 0b10 => Dim::Cube, - _ => Dim::D3, - }, - arrayed, - class, - }; - - let vector = match (dim, shadow) { - (0b00, false) => TypeInner::Scalar { - kind: Sk::Float, - width: 4, - }, - (0b00, true) | (0b11, _) => TypeInner::Vector { - size: VectorSize::Tri, - kind: Sk::Float, - width: 4, - }, - (_, _) => { - let size = match dim + arrayed as u32 + shadow as u32 { - 1 => VectorSize::Bi, - 2 => VectorSize::Tri, - _ => VectorSize::Quad, - }; - - TypeInner::Vector { - size, - kind: Sk::Float, - width: 4, - } - } - }; - - let size = match dim { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - _ => Some(VectorSize::Tri), - }; - - let ty = || match size { - None => TypeInner::Scalar { - kind: Sk::Float, - width: 4, - }, - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width: 4, - }, - }; - - let args = vec![image, vector, ty(), ty()]; - - declarations.push(self.module.add_builtin(args, MacroCall::TextureGrad)) - } - } - "textureSize" => { - // bits layout - // bits 0 trough 1 - dims - // bit 2 - shadow - // bit 3 - array - for bits in 0..(0b10000) { - let dim = bits & 0b11; - let shadow = bits & 0b100 == 0b100; - let arrayed = bits & 0b1000 == 0b1000; - - // Shadow, arrayed or both 3D images are not allowed - if (shadow || arrayed) && dim == 0b11 { - continue; - } - - let class = match shadow { - true => ImageClass::Depth { multi: false }, - false => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, - }; - - let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, - 0b10 => Dim::Cube, - _ => Dim::D3, - }, - arrayed, - class, - }; - - let args = vec![ - image, - TypeInner::Scalar { - kind: Sk::Sint, - width: 4, - }, - ]; - - declarations.push(self.module.add_builtin(args, MacroCall::TextureSize)) - } - } - "texelFetch" => { - // bits layout - // bit 0 - dim part 1 - 1D/2D - // bit 1 - array - // bit 2 - dim part 2 - 3D - // - // 0b100 is the latest since 3D arrayed images aren't allowed - for bits in 0..(0b101) { - let dim = bits & 0b1 | (bits & 0b100) >> 1; - let arrayed = bits & 0b1000 == 0b1000; - - let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, - _ => Dim::D3, - }, - arrayed, + arrayed: matches!( + name, + "sampler1DArray" + | "sampler2DArray" + | "sampler2DMSArray" + | "samplerCubeArray" + ), class: ImageClass::Sampled { + kind: Sk::Float, + multi: matches!(name, "sampler2DMS" | "sampler2DMSArray"), + }, + }, + TypeInner::Sampler { comparison: false }, + ], + MacroCall::Sampler, + )) + } + "sampler1DShadow" + | "sampler1DArrayShadow" + | "sampler2DShadow" + | "sampler2DArrayShadow" + | "samplerCubeShadow" + | "samplerCubeArrayShadow" => { + let dim = match name { + "sampler1DShadow" | "sampler1DArrayShadow" => Dim::D1, + "sampler2DShadow" | "sampler2DArrayShadow" => Dim::D2, + _ => Dim::Cube, + }; + let arrayed = matches!( + name, + "sampler1DArrayShadow" | "sampler2DArrayShadow" | "samplerCubeArrayShadow" + ); + + for i in 0..2 { + let ty = TypeInner::Image { + dim, + arrayed, + class: match i { + 0 => ImageClass::Sampled { kind: Sk::Float, multi: false, }, - }; + _ => ImageClass::Depth { multi: false }, + }, + }; - let vector = match (dim, arrayed) { - (0b00, false) => TypeInner::Scalar { - kind: Sk::Sint, - width: 4, - }, - (_, _) => { - let size = match dim + arrayed as u32 { - 1 => VectorSize::Bi, - 2 => VectorSize::Tri, - _ => VectorSize::Quad, - }; - - TypeInner::Vector { - size, - kind: Sk::Sint, - width: 4, - } - } - }; - - let args = vec![ - image, - vector, - TypeInner::Scalar { - kind: Sk::Sint, - width: 4, - }, - ]; - - declarations.push(self.module.add_builtin(args, MacroCall::TexelFetch)) - } + declaration.overloads.push(module.add_builtin( + vec![ty, TypeInner::Sampler { comparison: true }], + MacroCall::SamplerShadow, + )) } - "ceil" | "round" | "floor" | "fract" | "trunc" | "sqrt" | "inversesqrt" - | "normalize" | "length" | "isinf" | "isnan" => { - // bits layout - // bit 0 - float/double - // bit 1 trough 2 - dims - for bits in 0..(0b1000) { - let width = (bits & 0b1) * 4 + 4; - let size = match bits >> 1 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; + } + "texture" | "textureLod" => { + // bits layout + // bits 0 trough 1 - dims + // bit 2 - shadow + // bit 3 - array + // bit 4 - !bias + // + // 0b11111 is the latest since there are not 3D arrayed shadowed + // textures and cube arrayed shadows textures always have a + // compare argument + for bits in 0..(0b100000) { + let dim = bits & 0b11; + let shadow = bits & 0b100 == 0b100; + let arrayed = bits & 0b1000 == 0b1000; + let bias = bits & 0b10000 == 0b00000; + let builtin = match name { + "texture" => MacroCall::Texture, + _ => MacroCall::TextureLod, + }; - let args = vec![match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width, - }, - }]; - - let fun = match name.as_str() { - "ceil" => MacroCall::MathFunction(MathFunction::Ceil), - "round" => MacroCall::MathFunction(MathFunction::Round), - "floor" => MacroCall::MathFunction(MathFunction::Floor), - "fract" => MacroCall::MathFunction(MathFunction::Fract), - "trunc" => MacroCall::MathFunction(MathFunction::Trunc), - "sqrt" => MacroCall::MathFunction(MathFunction::Sqrt), - "inversesqrt" => MacroCall::MathFunction(MathFunction::InverseSqrt), - "normalize" => MacroCall::MathFunction(MathFunction::Normalize), - "length" => MacroCall::MathFunction(MathFunction::Length), - "isinf" => MacroCall::Relational(RelationalFunction::IsInf), - "isnan" => MacroCall::Relational(RelationalFunction::IsNan), - _ => unreachable!(), - }; - - declarations.push(self.module.add_builtin(args, fun)) + // Shadow, arrayed or both 3D images are not allowed + if (shadow || arrayed) && dim == 0b11 + || (builtin == MacroCall::TextureLod + && (dim != 0b00 && shadow && arrayed || dim == 0b10 && shadow || !bias)) + { + continue; } - } - "dot" | "reflect" | "distance" | "ldexp" => { - // bits layout - // bit 0 - float/double - // bit 1 trough 2 - dims - for bits in 0..(0b1000) { - let width = (bits & 0b1) * 4 + 4; - let size = match bits >> 1 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - let ty = || match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width, - }, - }; - let fun = match name.as_str() { - "dot" => MacroCall::MathFunction(MathFunction::Dot), - "reflect" => MacroCall::MathFunction(MathFunction::Reflect), - "distance" => MacroCall::MathFunction(MathFunction::Distance), - "ldexp" => MacroCall::MathFunction(MathFunction::Ldexp), - _ => unreachable!(), - }; + let class = match shadow { + true => ImageClass::Depth { multi: false }, + false => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; - declarations.push(self.module.add_builtin(vec![ty(), ty()], fun)) - } - } - "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" - | "log" | "log2" => { - // bits layout - // bit 0 trough 1 - dims - for bits in 0..(0b100) { - let size = match bits { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + 0b10 => Dim::Cube, + _ => Dim::D3, + }, + arrayed, + class, + }; - declarations.push(self.module.add_builtin( - vec![match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width: 4, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width: 4, - }, - }], - MacroCall::MathFunction(match name.as_str() { - "sin" => MathFunction::Sin, - "exp" => MathFunction::Exp, - "exp2" => MathFunction::Exp2, - "sinh" => MathFunction::Sinh, - "cos" => MathFunction::Cos, - "cosh" => MathFunction::Cosh, - "tan" => MathFunction::Tan, - "tanh" => MathFunction::Tanh, - "acos" => MathFunction::Acos, - "asin" => MathFunction::Asin, - "log" => MathFunction::Log, - "log2" => MathFunction::Log2, - _ => unreachable!(), - }), - )) - } - } - "pow" => { - // bits layout - // bit 0 trough 1 - dims - for bits in 0..(0b100) { - let size = match bits { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - let ty = || match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width: 4, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width: 4, - }, - }; - - declarations.push( - self.module.add_builtin( - vec![ty(), ty()], - MacroCall::MathFunction(MathFunction::Pow), - ), - ) - } - } - "transpose" => { - // bits layout - // bit 0 - float/double - // bit 1 trough 4 - dims - for bits in 0..(0b10010) { - let width = (bits & 0b1) * 4 + 4; - let (rows, columns) = match bits >> 1 { - 0b0000 => (VectorSize::Bi, VectorSize::Bi), - 0b0001 => (VectorSize::Bi, VectorSize::Tri), - 0b0010 => (VectorSize::Bi, VectorSize::Quad), - 0b0011 => (VectorSize::Tri, VectorSize::Bi), - 0b0100 => (VectorSize::Tri, VectorSize::Tri), - 0b0101 => (VectorSize::Tri, VectorSize::Quad), - 0b0110 => (VectorSize::Quad, VectorSize::Bi), - 0b0111 => (VectorSize::Quad, VectorSize::Tri), - _ => (VectorSize::Quad, VectorSize::Quad), - }; - - if (bits >> 1) > 0b1000 { - continue; - } - - declarations.push(self.module.add_builtin( - vec![TypeInner::Matrix { - columns, - rows, - width, - }], - MacroCall::MathFunction(MathFunction::Transpose), - )) - } - } - "inverse" | "determinant" => { - // bits layout - // bit 0 - float/double - // bit 1 trough 2 - dims - for bits in 0..(0b110) { - let width = (bits & 0b1) * 4 + 4; - let (rows, columns) = match bits >> 1 { - 0b00 => (VectorSize::Bi, VectorSize::Bi), - 0b01 => (VectorSize::Tri, VectorSize::Tri), - _ => (VectorSize::Quad, VectorSize::Quad), - }; - - let args = vec![TypeInner::Matrix { - columns, - rows, + let vector = match (dim, shadow) { + (0b00, false) => TypeInner::Scalar { + kind: Sk::Float, width, - }]; - - declarations.push(self.module.add_builtin( - args, - MacroCall::MathFunction(match name.as_str() { - "inverse" => MathFunction::Inverse, - "determinant" => MathFunction::Determinant, - _ => unreachable!(), - }), - )) - } - } - "abs" | "sign" => { - // bits layout - // bit 0 trough 1 - dims - // bit 2 trough 3 - kind - for bits in 0..(0b1100) { - let size = match bits & 0b11 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - let (kind, width) = match bits >> 2 { - 0b00 => (Sk::Float, 4), - 0b01 => (Sk::Sint, 4), - _ => (Sk::Float, 8), - }; - - let args = vec![match size { - Some(size) => TypeInner::Vector { size, kind, width }, - None => TypeInner::Scalar { kind, width }, - }]; - - declarations.push(self.module.add_builtin( - args, - MacroCall::MathFunction(match name.as_str() { - "abs" => MathFunction::Abs, - "sign" => MathFunction::Sign, - _ => unreachable!(), - }), - )) - } - } - "bitCount" | "bitfieldReverse" => { - // bits layout - // bit 0 - int/uint - // bit 1 trough 2 - dims - for bits in 0..(0b1000) { - let kind = match bits & 0b1 { - 0b0 => Sk::Sint, - _ => Sk::Uint, - }; - let size = match bits >> 1 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - - let args = vec![match size { - Some(size) => TypeInner::Vector { - size, - kind, - width: 4, - }, - None => TypeInner::Scalar { kind, width: 4 }, - }]; - - declarations.push(self.module.add_builtin( - args, - MacroCall::MathFunction(match name.as_str() { - "bitCount" => MathFunction::CountOneBits, - "bitfieldReverse" => MathFunction::ReverseBits, - _ => unreachable!(), - }), - )) - } - } - "atan" => { - // bits layout - // bit 0 - atan/atan2 - // bit 1 trough 2 - dims - for bits in 0..(0b1000) { - let fun = match bits & 0b1 { - 0b0 => MathFunction::Atan, - _ => MathFunction::Atan2, - }; - let size = match bits >> 1 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - let ty = || match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width: 4, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width: 4, - }, - }; - - let mut args = vec![ty()]; - - if fun == MathFunction::Atan2 { - args.push(ty()) - } - - declarations.push(self.module.add_builtin(args, MacroCall::MathFunction(fun))) - } - } - "all" | "any" => { - // bits layout - // bit 0 trough 1 - dims - for bits in 0..(0b11) { - let size = match bits { - 0b00 => VectorSize::Bi, - 0b01 => VectorSize::Tri, - _ => VectorSize::Quad, - }; - - let args = vec![TypeInner::Vector { - size, - kind: Sk::Bool, - width: crate::BOOL_WIDTH, - }]; - - let fun = MacroCall::Relational(match name.as_str() { - "all" => RelationalFunction::All, - "any" => RelationalFunction::Any, - _ => unreachable!(), - }); - - declarations.push(self.module.add_builtin(args, fun)) - } - } - "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" - | "notEqual" => { - for bits in 0..(0b1001) { - let (size, kind) = match bits { - 0b0000 => (VectorSize::Bi, Sk::Float), - 0b0001 => (VectorSize::Tri, Sk::Float), - 0b0010 => (VectorSize::Quad, Sk::Float), - 0b0011 => (VectorSize::Bi, Sk::Sint), - 0b0100 => (VectorSize::Tri, Sk::Sint), - 0b0101 => (VectorSize::Quad, Sk::Sint), - 0b0110 => (VectorSize::Bi, Sk::Uint), - 0b0111 => (VectorSize::Tri, Sk::Uint), - _ => (VectorSize::Quad, Sk::Uint), - }; - - let ty = || TypeInner::Vector { - size, - kind, - width: 4, - }; - let args = vec![ty(), ty()]; - - let fun = MacroCall::Binary(match name.as_str() { - "lessThan" => BinaryOperator::Less, - "greaterThan" => BinaryOperator::Greater, - "lessThanEqual" => BinaryOperator::LessEqual, - "greaterThanEqual" => BinaryOperator::GreaterEqual, - "equal" => BinaryOperator::Equal, - "notEqual" => BinaryOperator::NotEqual, - _ => unreachable!(), - }); - - declarations.push(self.module.add_builtin(args, fun)) - } - } - "mod" | "step" => { - // bits layout - // bit 0 - float/double - // bit 1 trough 3 - dims - for bits in 0..(0b1110) { - let width = (bits & 0b1) * 4 + 4; - let (size, second_size) = match bits >> 1 { - 0b000 => (None, None), - 0b001 => (Some(VectorSize::Bi), None), - 0b010 => (Some(VectorSize::Tri), None), - 0b011 => (Some(VectorSize::Quad), None), - 0b100 => (Some(VectorSize::Bi), Some(VectorSize::Bi)), - 0b101 => (Some(VectorSize::Tri), Some(VectorSize::Tri)), - _ => (Some(VectorSize::Quad), Some(VectorSize::Quad)), - }; - - let mut args = Vec::with_capacity(2); - let step = name.as_str() == "step"; - - for i in 0..2 { - let maybe_size = match i == step as u32 { - true => size, - false => second_size, + }, + (0b00, true) | (0b11, _) => TypeInner::Vector { + size: VectorSize::Tri, + kind: Sk::Float, + width, + }, + (_, _) => { + let size = match dim + arrayed as u32 + shadow as u32 { + 1 => VectorSize::Bi, + 2 => VectorSize::Tri, + _ => VectorSize::Quad, }; - args.push(match maybe_size { + TypeInner::Vector { + size, + kind: Sk::Float, + width, + } + } + }; + + let mut args = vec![image, vector]; + + if bias { + args.push(TypeInner::Scalar { + kind: Sk::Float, + width, + }) + } + + declaration + .overloads + .push(module.add_builtin(args, builtin)) + } + } + "textureProj" => { + // bits layout + // bit 0 - shadow + // bit 1 - bias + // bits 2 trough 3 - dims + // + // 0b0111 is the latest since there are only 1D and 2D shadow + // variants + for bits in 0..(0b1000) { + let dim = bits >> 2; + let shadow = bits & 0b1 == 0b1; + let bias = bits & 0b10 == 0b10; + + let class = match shadow { + true => ImageClass::Depth { multi: false }, + false => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; + + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + _ => Dim::Cube, + }, + arrayed: false, + class, + }; + + let vector = TypeInner::Vector { + size: VectorSize::Quad, + kind: Sk::Float, + width, + }; + + let mut args = vec![image, vector]; + + if bias { + args.push(TypeInner::Scalar { + kind: Sk::Float, + width, + }) + } + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::TextureProj)) + } + } + "textureGrad" => { + // bits layout + // bits 0 trough 1 - dims + // bit 2 - shadow + // bit 3 - array + // + // 0b1010 is the latest since there are no 3D arrayed shadowed + // textures and cube arrayed shadows textures are not allowed + for bits in 0..(0b1011) { + let dim = bits & 0b11; + let shadow = bits & 0b100 == 0b100; + let arrayed = bits & 0b1000 == 0b1000; + + // Shadow, arrayed or both 3D images are not allowed + if shadow && dim == 0b11 + // samplerCubeArrayShadow is not allowed + || shadow && arrayed && dim == 0b10 + { + continue; + } + + let class = match shadow { + true => ImageClass::Depth { multi: false }, + false => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; + + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + 0b10 => Dim::Cube, + _ => Dim::D3, + }, + arrayed, + class, + }; + + let vector = match (dim, shadow) { + (0b00, false) => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + (0b00, true) | (0b11, _) => TypeInner::Vector { + size: VectorSize::Tri, + kind: Sk::Float, + width, + }, + (_, _) => { + let size = match dim + arrayed as u32 + shadow as u32 { + 1 => VectorSize::Bi, + 2 => VectorSize::Tri, + _ => VectorSize::Quad, + }; + + TypeInner::Vector { + size, + kind: Sk::Float, + width, + } + } + }; + + let size = match dim { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + _ => Some(VectorSize::Tri), + }; + + let ty = || match size { + None => TypeInner::Scalar { + kind: Sk::Float, + width, + }, + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width, + }, + }; + + let args = vec![image, vector, ty(), ty()]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::TextureGrad)) + } + } + "textureSize" => { + // bits layout + // bits 0 trough 1 - dims + // bit 2 - shadow + // bit 3 - array + for bits in 0..(0b10000) { + let dim = bits & 0b11; + let shadow = bits & 0b100 == 0b100; + let arrayed = bits & 0b1000 == 0b1000; + + // Shadow, arrayed or both 3D images are not allowed + if (shadow || arrayed) && dim == 0b11 { + continue; + } + + let class = match shadow { + true => ImageClass::Depth { multi: false }, + false => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; + + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + 0b10 => Dim::Cube, + _ => Dim::D3, + }, + arrayed, + class, + }; + + let args = vec![ + image, + TypeInner::Scalar { + kind: Sk::Sint, + width, + }, + ]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::TextureSize)) + } + } + "texelFetch" => { + // bits layout + // bit 0 - dim part 1 - 1D/2D + // bit 1 - array + // bit 2 - dim part 2 - 3D + // + // 0b100 is the latest since 3D arrayed images aren't allowed + for bits in 0..(0b101) { + let dim = bits & 0b1 | (bits & 0b100) >> 1; + let arrayed = bits & 0b1000 == 0b1000; + + let image = TypeInner::Image { + dim: match dim { + 0b00 => Dim::D1, + 0b01 => Dim::D2, + _ => Dim::D3, + }, + arrayed, + class: ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + }; + + let vector = match (dim, arrayed) { + (0b00, false) => TypeInner::Scalar { + kind: Sk::Sint, + width, + }, + (_, _) => { + let size = match dim + arrayed as u32 { + 1 => VectorSize::Bi, + 2 => VectorSize::Tri, + _ => VectorSize::Quad, + }; + + TypeInner::Vector { + size, + kind: Sk::Sint, + width, + } + } + }; + + let args = vec![ + image, + vector, + TypeInner::Scalar { + kind: Sk::Sint, + width, + }, + ]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::TexelFetch)) + } + } + "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" + | "log" | "log2" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let kind = Sk::Float; + + declaration.overloads.push(module.add_builtin( + vec![match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }], + MacroCall::MathFunction(match name { + "sin" => MathFunction::Sin, + "exp" => MathFunction::Exp, + "exp2" => MathFunction::Exp2, + "sinh" => MathFunction::Sinh, + "cos" => MathFunction::Cos, + "cosh" => MathFunction::Cosh, + "tan" => MathFunction::Tan, + "tanh" => MathFunction::Tanh, + "acos" => MathFunction::Acos, + "asin" => MathFunction::Asin, + "log" => MathFunction::Log, + "log2" => MathFunction::Log2, + _ => unreachable!(), + }), + )) + } + } + "pow" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let kind = Sk::Float; + let ty = || match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; + + declaration.overloads.push( + module + .add_builtin(vec![ty(), ty()], MacroCall::MathFunction(MathFunction::Pow)), + ) + } + } + "abs" | "sign" => { + // bits layout + // bit 0 trough 1 - dims + // bit 2 - float/sint + for bits in 0..(0b1000) { + let size = match bits & 0b11 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let kind = match bits >> 2 { + 0b0 => Sk::Float, + _ => Sk::Sint, + }; + + let args = vec![match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }]; + + declaration.overloads.push(module.add_builtin( + args, + MacroCall::MathFunction(match name { + "abs" => MathFunction::Abs, + "sign" => MathFunction::Sign, + _ => unreachable!(), + }), + )) + } + } + "bitCount" | "bitfieldReverse" => { + // bits layout + // bit 0 - int/uint + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let kind = match bits & 0b1 { + 0b0 => Sk::Sint, + _ => Sk::Uint, + }; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let args = vec![match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }]; + + declaration.overloads.push(module.add_builtin( + args, + MacroCall::MathFunction(match name { + "bitCount" => MathFunction::CountOneBits, + "bitfieldReverse" => MathFunction::ReverseBits, + _ => unreachable!(), + }), + )) + } + } + "atan" => { + // bits layout + // bit 0 - atan/atan2 + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let fun = match bits & 0b1 { + 0b0 => MathFunction::Atan, + _ => MathFunction::Atan2, + }; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let kind = Sk::Float; + let ty = || match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; + + let mut args = vec![ty()]; + + if fun == MathFunction::Atan2 { + args.push(ty()) + } + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::MathFunction(fun))) + } + } + "all" | "any" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b11) { + let size = match bits { + 0b00 => VectorSize::Bi, + 0b01 => VectorSize::Tri, + _ => VectorSize::Quad, + }; + + let args = vec![TypeInner::Vector { + size, + kind: Sk::Bool, + width: crate::BOOL_WIDTH, + }]; + + let fun = MacroCall::Relational(match name { + "all" => RelationalFunction::All, + "any" => RelationalFunction::Any, + _ => unreachable!(), + }); + + declaration.overloads.push(module.add_builtin(args, fun)) + } + } + "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" + | "notEqual" => { + for bits in 0..(0b1001) { + let (size, kind) = match bits { + 0b0000 => (VectorSize::Bi, Sk::Float), + 0b0001 => (VectorSize::Tri, Sk::Float), + 0b0010 => (VectorSize::Quad, Sk::Float), + 0b0011 => (VectorSize::Bi, Sk::Sint), + 0b0100 => (VectorSize::Tri, Sk::Sint), + 0b0101 => (VectorSize::Quad, Sk::Sint), + 0b0110 => (VectorSize::Bi, Sk::Uint), + 0b0111 => (VectorSize::Tri, Sk::Uint), + _ => (VectorSize::Quad, Sk::Uint), + }; + + let ty = || TypeInner::Vector { size, kind, width }; + let args = vec![ty(), ty()]; + + let fun = MacroCall::Binary(match name { + "lessThan" => BinaryOperator::Less, + "greaterThan" => BinaryOperator::Greater, + "lessThanEqual" => BinaryOperator::LessEqual, + "greaterThanEqual" => BinaryOperator::GreaterEqual, + "equal" => BinaryOperator::Equal, + "notEqual" => BinaryOperator::NotEqual, + _ => unreachable!(), + }); + + declaration.overloads.push(module.add_builtin(args, fun)) + } + } + "min" | "max" => { + // bits layout + // bit 0 trough 1 - scalar kind + // bit 2 trough 4 - dims + for bits in 0..(0b11100) { + let kind = match bits & 0b11 { + 0b00 => Sk::Float, + 0b01 => Sk::Sint, + 0b10 => Sk::Uint, + _ => continue, + }; + let (size, second_size) = match bits >> 2 { + 0b000 => (None, None), + 0b001 => (Some(VectorSize::Bi), None), + 0b010 => (Some(VectorSize::Tri), None), + 0b011 => (Some(VectorSize::Quad), None), + 0b100 => (Some(VectorSize::Bi), Some(VectorSize::Bi)), + 0b101 => (Some(VectorSize::Tri), Some(VectorSize::Tri)), + _ => (Some(VectorSize::Quad), Some(VectorSize::Quad)), + }; + + let args = vec![ + match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }, + match second_size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }, + ]; + + let fun = match name { + "max" => MacroCall::Splatted(MathFunction::Max, size, 1), + "min" => MacroCall::Splatted(MathFunction::Min, size, 1), + _ => unreachable!(), + }; + + declaration.overloads.push(module.add_builtin(args, fun)) + } + } + "mix" => { + // bits layout + // bit 0 trough 1 - dims + // bit 2 trough 4 - types + // + // 0b10011 is the last element since splatted single elements + // were already added + for bits in 0..(0b10011) { + let size = match bits & 0b11 { + 0b00 => Some(VectorSize::Bi), + 0b01 => Some(VectorSize::Tri), + 0b10 => Some(VectorSize::Quad), + _ => None, + }; + let (kind, splatted, boolean) = match bits >> 2 { + 0b000 => (Sk::Sint, false, true), + 0b001 => (Sk::Uint, false, true), + 0b010 => (Sk::Float, false, true), + 0b011 => (Sk::Float, false, false), + _ => (Sk::Float, true, false), + }; + + let ty = |kind, width| match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; + let args = vec![ + ty(kind, width), + ty(kind, width), + match (boolean, splatted) { + (true, _) => ty(Sk::Bool, crate::BOOL_WIDTH), + (_, false) => TypeInner::Scalar { kind, width }, + _ => ty(kind, width), + }, + ]; + + declaration.overloads.push(module.add_builtin( + args, + match boolean { + true => MacroCall::MixBoolean, + false => MacroCall::Splatted(MathFunction::Mix, size, 2), + }, + )) + } + } + "clamp" => { + // bits layout + // bit 0 trough 1 - float/int/uint + // bit 2 trough 3 - dims + // bit 4 - splatted + // + // 0b11010 is the last element since splatted single elements + // were already added + for bits in 0..(0b11011) { + let kind = match bits & 0b11 { + 0b00 => Sk::Float, + 0b01 => Sk::Sint, + 0b10 => Sk::Uint, + _ => continue, + }; + let size = match (bits >> 2) & 0b11 { + 0b00 => Some(VectorSize::Bi), + 0b01 => Some(VectorSize::Tri), + 0b10 => Some(VectorSize::Quad), + _ => None, + }; + let splatted = bits & 0b10000 == 0b10000; + + let base_ty = || match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; + let limit_ty = || match splatted { + true => TypeInner::Scalar { kind, width }, + false => base_ty(), + }; + + let args = vec![base_ty(), limit_ty(), limit_ty()]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::Clamp(size))) + } + } + // Add common builtins with floats + _ => inject_common_builtin(declaration, module, name, 4), + } +} + +/// Double version of [`inject_builtin`](inject_builtin) +pub fn inject_double_builtin( + declaration: &mut FunctionDeclaration, + module: &mut Module, + name: &str, +) { + declaration.double = true; + let width = 8; + match name { + "abs" | "sign" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let kind = Sk::Float; + + let args = vec![match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }]; + + declaration.overloads.push(module.add_builtin( + args, + MacroCall::MathFunction(match name { + "abs" => MathFunction::Abs, + "sign" => MathFunction::Sign, + _ => unreachable!(), + }), + )) + } + } + "min" | "max" => { + // bits layout + // bit 0 trough 2 - dims + for bits in 0..(0b111) { + let (size, second_size) = match bits { + 0b000 => (None, None), + 0b001 => (Some(VectorSize::Bi), None), + 0b010 => (Some(VectorSize::Tri), None), + 0b011 => (Some(VectorSize::Quad), None), + 0b100 => (Some(VectorSize::Bi), Some(VectorSize::Bi)), + 0b101 => (Some(VectorSize::Tri), Some(VectorSize::Tri)), + _ => (Some(VectorSize::Quad), Some(VectorSize::Quad)), + }; + let kind = Sk::Float; + + let args = vec![ + match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }, + match second_size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }, + ]; + + let fun = match name { + "max" => MacroCall::Splatted(MathFunction::Max, size, 1), + "min" => MacroCall::Splatted(MathFunction::Min, size, 1), + _ => unreachable!(), + }; + + declaration.overloads.push(module.add_builtin(args, fun)) + } + } + "mix" => { + // bits layout + // bit 0 trough 1 - dims + // bit 2 trough 3 - splatted/boolean + // + // 0b1010 is the last element since splatted with single elements + // is equal to normal single elements + for bits in 0..(0b1011) { + let size = match bits & 0b11 { + 0b00 => Some(VectorSize::Quad), + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => None, + }; + let kind = Sk::Float; + let (splatted, boolean) = match bits >> 2 { + 0b00 => (false, false), + 0b01 => (false, true), + _ => (true, false), + }; + + let ty = |kind, width| match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; + let args = vec![ + ty(kind, width), + ty(kind, width), + match (boolean, splatted) { + (true, _) => ty(Sk::Bool, crate::BOOL_WIDTH), + (_, false) => TypeInner::Scalar { kind, width }, + _ => ty(kind, width), + }, + ]; + + declaration.overloads.push(module.add_builtin( + args, + match boolean { + true => MacroCall::MixBoolean, + false => MacroCall::Splatted(MathFunction::Mix, size, 2), + }, + )) + } + } + "clamp" => { + // bits layout + // bit 0 trough 1 - dims + // bit 2 - splatted + // + // 0b110 is the last element since splatted with single elements + // is equal to normal single elements + for bits in 0..(0b111) { + let kind = Sk::Float; + let size = match bits & 0b11 { + 0b00 => Some(VectorSize::Bi), + 0b01 => Some(VectorSize::Tri), + 0b10 => Some(VectorSize::Quad), + _ => None, + }; + let splatted = bits & 0b100 == 0b100; + + let base_ty = || match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; + let limit_ty = || match splatted { + true => TypeInner::Scalar { kind, width }, + false => base_ty(), + }; + + let args = vec![base_ty(), limit_ty(), limit_ty()]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::Clamp(size))) + } + } + // Add common builtins with doubles + _ => inject_common_builtin(declaration, module, name, 8), + } +} + +fn inject_common_builtin( + declaration: &mut FunctionDeclaration, + module: &mut Module, + name: &str, + float_width: crate::Bytes, +) { + match name { + "ceil" | "round" | "floor" | "fract" | "trunc" | "sqrt" | "inversesqrt" | "normalize" + | "length" | "isinf" | "isnan" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let args = vec![match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: float_width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width: float_width, + }, + }]; + + let fun = match name { + "ceil" => MacroCall::MathFunction(MathFunction::Ceil), + "round" => MacroCall::MathFunction(MathFunction::Round), + "floor" => MacroCall::MathFunction(MathFunction::Floor), + "fract" => MacroCall::MathFunction(MathFunction::Fract), + "trunc" => MacroCall::MathFunction(MathFunction::Trunc), + "sqrt" => MacroCall::MathFunction(MathFunction::Sqrt), + "inversesqrt" => MacroCall::MathFunction(MathFunction::InverseSqrt), + "normalize" => MacroCall::MathFunction(MathFunction::Normalize), + "length" => MacroCall::MathFunction(MathFunction::Length), + "isinf" => MacroCall::Relational(RelationalFunction::IsInf), + "isnan" => MacroCall::Relational(RelationalFunction::IsNan), + _ => unreachable!(), + }; + + declaration.overloads.push(module.add_builtin(args, fun)) + } + } + "dot" | "reflect" | "distance" | "ldexp" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: float_width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width: float_width, + }, + }; + + let fun = match name { + "dot" => MacroCall::MathFunction(MathFunction::Dot), + "reflect" => MacroCall::MathFunction(MathFunction::Reflect), + "distance" => MacroCall::MathFunction(MathFunction::Distance), + "ldexp" => MacroCall::MathFunction(MathFunction::Ldexp), + _ => unreachable!(), + }; + + declaration + .overloads + .push(module.add_builtin(vec![ty(), ty()], fun)) + } + } + "transpose" => { + // bits layout + // bit 0 trough 3 - dims + for bits in 0..(0b1001) { + let (rows, columns) = match bits { + 0b0000 => (VectorSize::Bi, VectorSize::Bi), + 0b0001 => (VectorSize::Bi, VectorSize::Tri), + 0b0010 => (VectorSize::Bi, VectorSize::Quad), + 0b0011 => (VectorSize::Tri, VectorSize::Bi), + 0b0100 => (VectorSize::Tri, VectorSize::Tri), + 0b0101 => (VectorSize::Tri, VectorSize::Quad), + 0b0110 => (VectorSize::Quad, VectorSize::Bi), + 0b0111 => (VectorSize::Quad, VectorSize::Tri), + _ => (VectorSize::Quad, VectorSize::Quad), + }; + + declaration.overloads.push(module.add_builtin( + vec![TypeInner::Matrix { + columns, + rows, + width: float_width, + }], + MacroCall::MathFunction(MathFunction::Transpose), + )) + } + } + "inverse" | "determinant" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b11) { + let (rows, columns) = match bits { + 0b00 => (VectorSize::Bi, VectorSize::Bi), + 0b01 => (VectorSize::Tri, VectorSize::Tri), + _ => (VectorSize::Quad, VectorSize::Quad), + }; + + let args = vec![TypeInner::Matrix { + columns, + rows, + width: float_width, + }]; + + declaration.overloads.push(module.add_builtin( + args, + MacroCall::MathFunction(match name { + "inverse" => MathFunction::Inverse, + "determinant" => MathFunction::Determinant, + _ => unreachable!(), + }), + )) + } + } + "mod" | "step" => { + // bits layout + // bit 0 trough 2 - dims + for bits in 0..(0b111) { + let (size, second_size) = match bits { + 0b000 => (None, None), + 0b001 => (Some(VectorSize::Bi), None), + 0b010 => (Some(VectorSize::Tri), None), + 0b011 => (Some(VectorSize::Quad), None), + 0b100 => (Some(VectorSize::Bi), Some(VectorSize::Bi)), + 0b101 => (Some(VectorSize::Tri), Some(VectorSize::Tri)), + _ => (Some(VectorSize::Quad), Some(VectorSize::Quad)), + }; + + let mut args = Vec::with_capacity(2); + let step = name == "step"; + + for i in 0..2 { + let maybe_size = match i == step as u32 { + true => size, + false => second_size, + }; + + args.push(match maybe_size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: float_width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width: float_width, + }, + }) + } + + let fun = match name { + "mod" => MacroCall::Mod(size), + "step" => MacroCall::Splatted(MathFunction::Step, size, 0), + _ => unreachable!(), + }; + + declaration.overloads.push(module.add_builtin(args, fun)) + } + } + "modf" | "frexp" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let ty = module.types.fetch_or_append( + Type { + name: None, + inner: match size { Some(size) => TypeInner::Vector { size, kind: Sk::Float, - width, + width: float_width, }, None => TypeInner::Scalar { kind: Sk::Float, - width, - }, - }) - } - - let fun = match name.as_str() { - "mod" => MacroCall::Mod(size), - "step" => MacroCall::Splatted(MathFunction::Step, size, 0), - _ => unreachable!(), - }; - - declarations.push(self.module.add_builtin(args, fun)) - } - } - "min" | "max" => { - // bits layout - // bit 0 trough 1 - scalar kind and width - // bit 2 trough 4 - dims - for bits in 0..(0b11100) { - let (kind, width) = match bits & 0b11 { - 0b00 => (Sk::Float, 4), - 0b01 => (Sk::Float, 8), - 0b10 => (Sk::Sint, 4), - _ => (Sk::Uint, 4), - }; - let (size, second_size) = match bits >> 2 { - 0b000 => (None, None), - 0b001 => (Some(VectorSize::Bi), None), - 0b010 => (Some(VectorSize::Tri), None), - 0b011 => (Some(VectorSize::Quad), None), - 0b100 => (Some(VectorSize::Bi), Some(VectorSize::Bi)), - 0b101 => (Some(VectorSize::Tri), Some(VectorSize::Tri)), - _ => (Some(VectorSize::Quad), Some(VectorSize::Quad)), - }; - - let args = vec![ - match size { - Some(size) => TypeInner::Vector { size, kind, width }, - None => TypeInner::Scalar { kind, width }, - }, - match second_size { - Some(size) => TypeInner::Vector { size, kind, width }, - None => TypeInner::Scalar { kind, width }, - }, - ]; - - let fun = match name.as_str() { - "max" => MacroCall::Splatted(MathFunction::Max, size, 1), - "min" => MacroCall::Splatted(MathFunction::Min, size, 1), - _ => unreachable!(), - }; - - declarations.push(self.module.add_builtin(args, fun)) - } - } - "modf" | "frexp" => { - // bits layout - // bit 0 - float/double - // bit 1 trough 2 - dims - for bits in 0..(0b1000) { - let width = (bits & 0b1) * 4 + 4; - let size = match bits >> 1 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - - let ty = self.module.types.fetch_or_append( - Type { - name: None, - inner: match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width, - }, + width: float_width, }, }, - Span::Unknown, - ); + }, + Span::Unknown, + ); - let parameters = vec![ty, ty]; + let parameters = vec![ty, ty]; - let fun = match name.as_str() { - "modf" => MacroCall::MathFunction(MathFunction::Modf), - "frexp" => MacroCall::MathFunction(MathFunction::Frexp), - _ => unreachable!(), - }; + let fun = match name { + "modf" => MacroCall::MathFunction(MathFunction::Modf), + "frexp" => MacroCall::MathFunction(MathFunction::Frexp), + _ => unreachable!(), + }; - declarations.push(FunctionDeclaration { - parameters, - parameters_info: vec![ - ParameterInfo { - qualifier: ParameterQualifier::In, - depth: false, - }, - ParameterInfo { - qualifier: ParameterQualifier::Out, - depth: false, - }, - ], - kind: FunctionKind::Macro(fun), - defined: false, - void: false, - }) - } + declaration.overloads.push(Overload { + parameters, + parameters_info: vec![ + ParameterInfo { + qualifier: ParameterQualifier::In, + depth: false, + }, + ParameterInfo { + qualifier: ParameterQualifier::Out, + depth: false, + }, + ], + kind: FunctionKind::Macro(fun), + defined: false, + void: false, + }) } - "cross" => { - // bits layout - // bit 0 - float/double - for bits in 0..0b10 { - let width = bits * 4 + 4; - - let args = vec![ - TypeInner::Vector { - size: VectorSize::Tri, - kind: Sk::Float, - width, - }, - TypeInner::Vector { - size: VectorSize::Tri, - kind: Sk::Float, - width, - }, - ]; - - declarations.push( - self.module - .add_builtin(args, MacroCall::MathFunction(MathFunction::Cross)), - ) - } - } - "outerProduct" => { - // bits layout - // bit 0 - float/double - // bit 1 trough 4 - dims - for bits in 0..(0b10010) { - let width = (bits & 0b1) * 4 + 4; - let (size1, size2) = match bits >> 1 { - 0b0000 => (VectorSize::Bi, VectorSize::Bi), - 0b0001 => (VectorSize::Bi, VectorSize::Tri), - 0b0010 => (VectorSize::Bi, VectorSize::Quad), - 0b0011 => (VectorSize::Tri, VectorSize::Bi), - 0b0100 => (VectorSize::Tri, VectorSize::Tri), - 0b0101 => (VectorSize::Tri, VectorSize::Quad), - 0b0110 => (VectorSize::Quad, VectorSize::Bi), - 0b0111 => (VectorSize::Quad, VectorSize::Tri), - _ => (VectorSize::Quad, VectorSize::Quad), - }; - - if (bits >> 1) > 0b1000 { - continue; - } - - let args = vec![ - TypeInner::Vector { - size: size1, - kind: Sk::Float, - width, - }, - TypeInner::Vector { - size: size2, - kind: Sk::Float, - width, - }, - ]; - - declarations.push( - self.module - .add_builtin(args, MacroCall::MathFunction(MathFunction::Outer)), - ) - } - } - "mix" => { - // bits layout - // bit 0 trough 2 - types - // bit 3 trough 4 - dims - for bits in 0..(0b100000) { - let (kind, width, splatted, boolean) = match bits & 0b111 { - 0b000 => (Sk::Sint, 4, false, true), - 0b001 => (Sk::Uint, 4, false, true), - 0b010 => (Sk::Float, 4, false, true), - 0b011 => (Sk::Float, 8, false, true), - 0b100 => (Sk::Float, 4, true, false), - 0b101 => (Sk::Float, 8, true, false), - 0b110 => (Sk::Float, 4, false, false), - _ => (Sk::Float, 8, false, false), - }; - let size = match bits >> 3 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - - if splatted && size.is_none() { - continue; - } - - let ty = |kind, width| match size { - Some(size) => TypeInner::Vector { size, kind, width }, - None => TypeInner::Scalar { kind, width }, - }; - let args = vec![ - ty(kind, width), - ty(kind, width), - match (boolean, splatted) { - (true, _) => ty(Sk::Bool, crate::BOOL_WIDTH), - (_, false) => TypeInner::Scalar { kind, width }, - _ => ty(kind, width), - }, - ]; - - declarations.push(self.module.add_builtin( - args, - match boolean { - true => MacroCall::MixBoolean, - false => MacroCall::Splatted(MathFunction::Mix, size, 2), - }, - )) - } - } - "clamp" => { - // bits layout - // bit 0 trough 1 - float/double/int/uint - // bit 2 trough 3 - dims - // bit 4 - splatted - for bits in 0..(0b100000) { - let (kind, width) = match bits & 0b11 { - 0b00 => (Sk::Float, 4), - 0b01 => (Sk::Float, 8), - 0b10 => (Sk::Sint, 4), - _ => (Sk::Uint, 4), - }; - let size = match (bits >> 2) & 0b11 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - let splatted = bits & 0b10000 == 0b10000; - - if splatted && size.is_none() { - continue; - } - - let base_ty = || match size { - Some(size) => TypeInner::Vector { size, kind, width }, - None => TypeInner::Scalar { kind, width }, - }; - let limit_ty = || match splatted { - true => TypeInner::Scalar { kind, width }, - false => base_ty(), - }; - - let args = vec![base_ty(), limit_ty(), limit_ty()]; - - declarations.push(self.module.add_builtin(args, MacroCall::Clamp(size))) - } - } - "faceforward" | "fma" => { - // bits layout - // bit 0 - float/double - // bit 1 trough 2 - dims - for bits in 0..(0b1000) { - let width = (bits & 0b1) * 4 + 4; - let size = match bits >> 1 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - - let ty = || match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width, - }, - }; - let args = vec![ty(), ty(), ty()]; - - let fun = match name.as_str() { - "faceforward" => MacroCall::MathFunction(MathFunction::FaceForward), - "fma" => MacroCall::MathFunction(MathFunction::Fma), - _ => unreachable!(), - }; - - declarations.push(self.module.add_builtin(args, fun)) - } - } - "refract" => { - // bits layout - // bit 0 - float/double - // bit 1 trough 2 - dims - for bits in 0..(0b1000) { - let width = (bits & 0b1) * 4 + 4; - let size = match bits >> 1 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - - let ty = || match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width, - }, - }; - let args = vec![ - ty(), - ty(), - TypeInner::Scalar { - kind: Sk::Float, - width: 4, - }, - ]; - declarations.push( - self.module - .add_builtin(args, MacroCall::MathFunction(MathFunction::Refract)), - ) - } - } - "smoothstep" => { - // bits layout - // bit 0 - float/double - // bit 1 - splatted - // bit 2 trough 3 - dims - for bits in 0..(0b10000) { - let width = (bits & 0b1) * 4 + 4; - let splatted = bits & 0b10 == 0b10; - let size = match bits >> 2 { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - - if splatted && size.is_none() { - continue; - } - - let base_ty = || match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width, - }, - }; - let ty = || match splatted { - true => TypeInner::Scalar { - kind: Sk::Float, - width, - }, - false => base_ty(), - }; - declarations.push(self.module.add_builtin( - vec![ty(), ty(), base_ty()], - MacroCall::MathFunction(MathFunction::SmoothStep), - )) - } - } - // Not a builtin (or at lest not yet handled) - _ => {} } + "cross" => { + let args = vec![ + TypeInner::Vector { + size: VectorSize::Tri, + kind: Sk::Float, + width: float_width, + }, + TypeInner::Vector { + size: VectorSize::Tri, + kind: Sk::Float, + width: float_width, + }, + ]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::MathFunction(MathFunction::Cross))) + } + "outerProduct" => { + // bits layout + // bit 0 trough 3 - dims + for bits in 0..(0b1001) { + let (size1, size2) = match bits { + 0b0000 => (VectorSize::Bi, VectorSize::Bi), + 0b0001 => (VectorSize::Bi, VectorSize::Tri), + 0b0010 => (VectorSize::Bi, VectorSize::Quad), + 0b0011 => (VectorSize::Tri, VectorSize::Bi), + 0b0100 => (VectorSize::Tri, VectorSize::Tri), + 0b0101 => (VectorSize::Tri, VectorSize::Quad), + 0b0110 => (VectorSize::Quad, VectorSize::Bi), + 0b0111 => (VectorSize::Quad, VectorSize::Tri), + _ => (VectorSize::Quad, VectorSize::Quad), + }; + + let args = vec![ + TypeInner::Vector { + size: size1, + kind: Sk::Float, + width: float_width, + }, + TypeInner::Vector { + size: size2, + kind: Sk::Float, + width: float_width, + }, + ]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::MathFunction(MathFunction::Outer))) + } + } + "faceforward" | "fma" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: float_width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width: float_width, + }, + }; + let args = vec![ty(), ty(), ty()]; + + let fun = match name { + "faceforward" => MacroCall::MathFunction(MathFunction::FaceForward), + "fma" => MacroCall::MathFunction(MathFunction::Fma), + _ => unreachable!(), + }; + + declaration.overloads.push(module.add_builtin(args, fun)) + } + } + "refract" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + let ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: float_width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width: float_width, + }, + }; + let args = vec![ + ty(), + ty(), + TypeInner::Scalar { + kind: Sk::Float, + width: 4, + }, + ]; + declaration + .overloads + .push(module.add_builtin(args, MacroCall::MathFunction(MathFunction::Refract))) + } + } + "smoothstep" => { + // bits layout + // bit 0 - splatted + // bit 1 trough 2 - dims + for bits in 0..(0b1000) { + let splatted = bits & 0b1 == 0b1; + let size = match bits >> 1 { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + + if splatted && size.is_none() { + continue; + } + + let base_ty = || match size { + Some(size) => TypeInner::Vector { + size, + kind: Sk::Float, + width: float_width, + }, + None => TypeInner::Scalar { + kind: Sk::Float, + width: float_width, + }, + }; + let ty = || match splatted { + true => TypeInner::Scalar { + kind: Sk::Float, + width: float_width, + }, + false => base_ty(), + }; + declaration.overloads.push(module.add_builtin( + vec![ty(), ty(), base_ty()], + MacroCall::MathFunction(MathFunction::SmoothStep), + )) + } + } + // The function isn't a builtin or we don't yet support it + _ => declaration.builtin = false, } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 7c3444bfd..28190699a 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,6 +1,6 @@ use super::{ ast::*, - builtins::sampled_to_depth, + builtins::{inject_builtin, inject_double_builtin, sampled_to_depth}, context::{Context, StmtContext}, error::{Error, ErrorKind}, types::scalar_components, @@ -356,17 +356,25 @@ impl Parser { ) -> Result>> { // If the name for the function hasn't yet been initialized check if any // builtin can be injected. - // - // NOTE: A name not being initialized is not the same as no declarations - // being existing. if self.lookup_function.get(&name).is_none() { - self.inject_builtin(name.clone()); + let declaration = self.lookup_function.entry(name.clone()).or_default(); + inject_builtin(declaration, &mut self.module, &name); } - let declarations = self.lookup_function.get(&name).ok_or_else(|| Error { - kind: ErrorKind::SemanticError(format!("Unknown function '{}'", name).into()), - meta, - })?; + // Check if any argument uses a double type + let has_double = args + .iter() + .any(|&(expr, meta)| self.resolve_type(ctx, expr, meta).map_or(false, is_double)); + + // At this point a declaration is guaranteed + let declaration = self.lookup_function.get_mut(&name).unwrap(); + + if declaration.builtin && !declaration.double && has_double { + inject_double_builtin(declaration, &mut self.module, &name); + } + + // Borrow again but without mutability + let declaration = self.lookup_function.get(&name).unwrap(); // Helper enum containing the type of conversion need for a call #[derive(PartialEq, Eq, Clone, Copy, Debug)] @@ -389,7 +397,7 @@ impl Parser { let mut old_conversions = vec![Conversion::None; args.len()]; let mut ambiguous = false; - 'outer: for decl in declarations { + 'outer: for decl in declaration.overloads.iter() { if args.len() != decl.parameters.len() { continue; } @@ -660,7 +668,8 @@ impl Parser { meta: SourceMetadata, ) { if self.lookup_function.get(&name).is_none() { - self.inject_builtin(name.clone()); + let declaration = self.lookup_function.entry(name.clone()).or_default(); + inject_builtin(declaration, &mut self.module, &name); } ensure_block_returns(&mut body); @@ -673,7 +682,8 @@ impl Parser { .. } = self; - let declarations = lookup_function.entry(name.clone()).or_default(); + let declaration = lookup_function.entry(name.clone()).or_default(); + let Context { expressions, locals, @@ -682,6 +692,16 @@ impl Parser { parameters_info, .. } = ctx; + + if declaration.builtin + && !declaration.double + && parameters + .iter() + .any(|ty| is_double(&module.types[*ty].inner)) + { + inject_double_builtin(declaration, module, &name); + } + let function = Function { name: Some(name), arguments, @@ -692,7 +712,7 @@ impl Parser { body, }; - 'outer: for decl in declarations.iter_mut() { + 'outer: for decl in declaration.overloads.iter_mut() { if parameters.len() != decl.parameters.len() { continue; } @@ -726,7 +746,7 @@ impl Parser { } let handle = module.functions.append(function, meta.as_span()); - declarations.push(FunctionDeclaration { + declaration.overloads.push(Overload { parameters, parameters_info, kind: FunctionKind::Call(handle), @@ -743,7 +763,8 @@ impl Parser { meta: SourceMetadata, ) { if self.lookup_function.get(&name).is_none() { - self.inject_builtin(name.clone()); + let declaration = self.lookup_function.entry(name.clone()).or_default(); + inject_builtin(declaration, &mut self.module, &name); } let void = result.is_none(); @@ -754,7 +775,7 @@ impl Parser { .. } = self; - let declarations = lookup_function.entry(name.clone()).or_default(); + let declaration = lookup_function.entry(name.clone()).or_default(); let Context { arguments, @@ -762,6 +783,16 @@ impl Parser { parameters_info, .. } = ctx; + + if declaration.builtin + && !declaration.double + && parameters + .iter() + .any(|ty| is_double(&module.types[*ty].inner)) + { + inject_double_builtin(declaration, module, &name); + } + let function = Function { name: Some(name), arguments, @@ -769,7 +800,7 @@ impl Parser { ..Default::default() }; - 'outer: for decl in declarations.iter_mut() { + 'outer: for decl in declaration.overloads.iter() { if parameters.len() != decl.parameters.len() { continue; } @@ -790,7 +821,7 @@ impl Parser { } let handle = module.functions.append(function, meta.as_span()); - declarations.push(FunctionDeclaration { + declaration.overloads.push(Overload { parameters, parameters_info, kind: FunctionKind::Call(handle), @@ -922,3 +953,13 @@ impl Parser { }); } } + +fn is_double(ty: &TypeInner) -> bool { + match *ty { + TypeInner::ValuePointer { kind, width, .. } + | TypeInner::Scalar { kind, width } + | TypeInner::Vector { kind, width, .. } => kind == ScalarKind::Float && width == 8, + TypeInner::Matrix { width, .. } => width == 8, + _ => false, + } +} diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 29a062b3c..60e839d9c 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -159,7 +159,7 @@ impl Default for ShaderMetadata { pub struct Parser { meta: ShaderMetadata, - lookup_function: FastHashMap>, + lookup_function: FastHashMap, lookup_type: FastHashMap>, global_variables: Vec<(String, GlobalLookup)>, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b62adcca0..b30c9b65c 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -139,13 +139,16 @@ impl<'source> ParsingContext<'source> { self.parse_external_declaration(parser, &mut ctx, &mut body)?; } - match parser.lookup_function.get("main").and_then(|declarations| { - declarations.iter().find_map(|decl| match decl.kind { - FunctionKind::Call(handle) if decl.defined && decl.parameters.is_empty() => { - Some(handle) - } - _ => None, - }) + match parser.lookup_function.get("main").and_then(|declaration| { + declaration + .overloads + .iter() + .find_map(|decl| match decl.kind { + FunctionKind::Call(handle) if decl.defined && decl.parameters.is_empty() => { + Some(handle) + } + _ => None, + }) }) { Some(handle) => parser.add_entry_point(handle, body, ctx.expressions), None => parser.errors.push(Error { From 7a45d73465d90a11fbfdb6892f5a15c050c6d3bb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 18 Aug 2021 00:11:14 -0400 Subject: [PATCH 1244/2212] Release v0.6 version, changelog, and spirv update --- CHANGELOG.md | 12 +++++++++--- Cargo.toml | 8 ++++---- src/back/spv/writer.rs | 17 ++++++++++------- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f2ab949b0..1bd8fa736 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,16 @@ # Change Log -## TBD +## v0.6 (2021-08-18) + - development release for wgpu-0.10 - API: - atomic types and functions - - `num_workgroups` built-in - - WGSL `select()` order of true/false is swapped + - storage access is moved from global variables to the storage class and storage texture type + - new built-ins: `primitive_index` and `num_workgroups` + - support for multi-sampled depth images + - WGSL: + - `select()` order of true/false is swapped + - HLSL backend is vastly improved and now usable + - GLSL frontend is heavily reworked ## v0.5 (2021-06-18) - development release for wgpu-0.9 diff --git a/Cargo.toml b/Cargo.toml index 9ef3860d9..f72aa0ae6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.5.0" +version = "0.6.0" authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" @@ -22,7 +22,7 @@ codespan-reporting = { version = "0.11.0", optional = true } fxhash = "0.2" log = "0.4" num-traits = "0.2" -spirv = { package = "spirv_headers", version = "1.5", optional = true } +spirv = { version = "0.2", optional = true } thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } @@ -49,8 +49,8 @@ span = ["codespan-reporting"] diff = "0.1" ron = "0.6" serde = { version = "1.0", features = ["derive"] } -spirv = { package = "spirv_headers", version = "1.5", features = ["deserialize"] } -rspirv = "0.7" +spirv = { version = "0.2", features = ["deserialize"] } +rspirv = "0.10" env_logger = "0.8" [workspace] diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d2f254b54..90aee19ac 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -136,6 +136,9 @@ impl Writer { *self = fresh; } + //TODO: revive and rewrite this, see: + // https://github.com/gfx-rs/rspirv/issues/198 + // https://github.com/gfx-rs/rspirv/pull/185#issuecomment-900796025 pub(super) fn check(&mut self, capabilities: &[spirv::Capability]) -> Result<(), Error> { if capabilities.is_empty() || capabilities @@ -468,7 +471,7 @@ impl Writer { function_id: Word, mode: spirv::ExecutionMode, ) -> Result<(), Error> { - self.check(mode.required_capabilities())?; + //self.check(mode.required_capabilities())?; Instruction::execution_mode(function_id, mode, &[]) .to_words(&mut self.logical_layout.execution_modes); Ok(()) @@ -510,7 +513,7 @@ impl Writer { } crate::ShaderStage::Compute => { let execution_mode = spirv::ExecutionMode::LocalSize; - self.check(execution_mode.required_capabilities())?; + //self.check(execution_mode.required_capabilities())?; Instruction::execution_mode( function_id, execution_mode, @@ -520,7 +523,7 @@ impl Writer { spirv::ExecutionModel::GLCompute } }; - self.check(exec_model.required_capabilities())?; + //self.check(exec_model.required_capabilities())?; Ok(Instruction::entry_point( exec_model, @@ -719,7 +722,7 @@ impl Writer { pointer_class: None, }; let dim = map_dim(dim); - self.check(dim.required_capabilities())?; + //self.check(dim.required_capabilities())?; let type_id = self.get_type_id(LookupType::Local(local_type)); Instruction::type_image(id, type_id, dim, arrayed, class) } @@ -1061,7 +1064,7 @@ impl Writer { let id = self.id_gen.next(); let class = map_storage_class(global_variable.class); - self.check(class.required_capabilities())?; + //self.check(class.required_capabilities())?; let init_word = global_variable .init @@ -1230,8 +1233,8 @@ impl Writer { let addressing_model = spirv::AddressingModel::Logical; let memory_model = spirv::MemoryModel::GLSL450; - self.check(addressing_model.required_capabilities())?; - self.check(memory_model.required_capabilities())?; + //self.check(addressing_model.required_capabilities())?; + //self.check(memory_model.required_capabilities())?; Instruction::memory_model(addressing_model, memory_model) .to_words(&mut self.logical_layout.memory_model); From 01250b85fe8f48b45100d4f03c740cb26334ee84 Mon Sep 17 00:00:00 2001 From: Hans Christian Schmitz Date: Wed, 18 Aug 2021 08:06:04 +0200 Subject: [PATCH 1245/2212] Fix WGSL vector splat constructor's type handling Previously the constructor just used the type of the scalar argument regardless of whether or not it actually matched the vector splat constructors target type. This resulted in e.g. `vec2(0)` erroneously getting the type of a bi-vector of Sints with width 4. Now the splat constructor checks that the kind and width of the scalar argument is the same as that of the target specified in the constructor's type parameter. --- src/front/wgsl/mod.rs | 19 +++++++++++++------ src/front/wgsl/tests.rs | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 4bbc70231..7d2ad1dbf 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1746,12 +1746,19 @@ impl Parser { ty_resolution.inner_with(ctx.types), ctx.typifier.get(last_component, ctx.types), ) { - (&crate::TypeInner::Vector { size, .. }, &crate::TypeInner::Scalar { .. }) => { - crate::Expression::Splat { - size, - value: last_component, - } - } + ( + &crate::TypeInner::Vector { + size, kind, width, .. + }, + &crate::TypeInner::Scalar { + kind: arg_kind, + width: arg_width, + .. + }, + ) if arg_kind == kind && arg_width == width => crate::Expression::Splat { + size, + value: last_component, + }, ( &crate::TypeInner::Scalar { kind, width, .. }, &crate::TypeInner::Scalar { .. }, diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 4297eccde..d22310945 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -65,6 +65,22 @@ fn parse_type_cast() { ", ) .unwrap(); + parse_str( + " + fn main() { + let x: vec2 = vec2(0.0); + } + ", + ) + .unwrap(); + assert!(parse_str( + " + fn main() { + let x: vec2 = vec2(0); + } + ", + ) + .is_err()); } #[test] From cefaa396d490024b19b31a2fcf9410d5d2b5bb2c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 18 Aug 2021 11:13:11 -0700 Subject: [PATCH 1246/2212] [spv-out] Generating constants is not, in fact, fallible. --- src/back/spv/block.rs | 32 ++++++++++++++++---------------- src/back/spv/index.rs | 6 +++--- src/back/spv/mod.rs | 4 ++-- src/back/spv/writer.rs | 17 ++++++++--------- 4 files changed, 29 insertions(+), 30 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 4ff0aef32..41b37373e 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -54,7 +54,7 @@ impl Writer { width: 4, pointer_class: Some(spirv::StorageClass::Output), })); - let index_y_id = self.get_index_constant(1)?; + let index_y_id = self.get_index_constant(1); body.push(Instruction::access_chain( float_ptr_type_id, access_id, @@ -687,8 +687,8 @@ impl<'w> BlockContext<'w> { }; let instruction = if let Some(class) = atomic_class { let (semantics, scope) = class.to_spirv_semantics_and_scope(); - let scope_constant_id = self.get_scope_constant(scope as u32)?; - let semantics_id = self.get_index_constant(semantics.bits())?; + let scope_constant_id = self.get_scope_constant(scope as u32); + let semantics_id = self.get_index_constant(semantics.bits()); Instruction::atomic_load( result_type_id, id, @@ -764,7 +764,7 @@ impl<'w> BlockContext<'w> { } Sk::Bool => unreachable!(), }; - let zero_id = self.writer.get_constant_scalar(value, 4)?; + let zero_id = self.writer.get_constant_scalar(value, 4); Instruction::binary(op, result_type_id, id, expr_id, zero_id) } @@ -932,7 +932,7 @@ impl<'w> BlockContext<'w> { let zero_id = self .writer - .get_constant_scalar(crate::ScalarValue::Float(0.0), 4)?; + .get_constant_scalar(crate::ScalarValue::Float(0.0), 4); mask |= spirv::ImageOperands::LOD; inst.add_operand(mask.bits()); @@ -1138,7 +1138,7 @@ impl<'w> BlockContext<'w> { _ => { let level_id = match level { Some(expr) => self.cached[expr], - None => self.get_index_constant(0)?, + None => self.get_index_constant(0), }; (spirv::Op::ImageQuerySizeLod, Some(level_id)) } @@ -1207,7 +1207,7 @@ impl<'w> BlockContext<'w> { id_extended, image_id, ); - inst.add_operand(self.get_index_constant(0)?); + inst.add_operand(self.get_index_constant(0)); block.body.push(inst); let id = self.gen_id(); block.body.push(Instruction::composite_extract( @@ -1291,7 +1291,7 @@ impl<'w> BlockContext<'w> { // Even if the index is known, `OpAccessIndex` // requires expression operands, not literals. let scalar = crate::ScalarValue::Uint(known_index as u64); - self.writer.get_constant_scalar(scalar, 4)? + self.writer.get_constant_scalar(scalar, 4) } BoundsCheckResult::Computed(computed_index_id) => computed_index_id, BoundsCheckResult::Conditional(comparison_id) => { @@ -1322,7 +1322,7 @@ impl<'w> BlockContext<'w> { base } crate::Expression::AccessIndex { base, index } => { - let const_id = self.get_index_constant(index)?; + let const_id = self.get_index_constant(index); self.temp_list.push(const_id); base } @@ -1601,9 +1601,9 @@ impl<'w> BlockContext<'w> { spirv::MemorySemantics::WORKGROUP_MEMORY, flags.contains(crate::Barrier::WORK_GROUP), ); - let exec_scope_id = self.get_index_constant(spirv::Scope::Workgroup as u32)?; - let mem_scope_id = self.get_index_constant(memory_scope as u32)?; - let semantics_id = self.get_index_constant(semantics.bits())?; + let exec_scope_id = self.get_index_constant(spirv::Scope::Workgroup as u32); + let mem_scope_id = self.get_index_constant(memory_scope as u32); + let semantics_id = self.get_index_constant(semantics.bits()); block.body.push(Instruction::control_barrier( exec_scope_id, mem_scope_id, @@ -1628,8 +1628,8 @@ impl<'w> BlockContext<'w> { }; let instruction = if let Some(class) = atomic_class { let (semantics, scope) = class.to_spirv_semantics_and_scope(); - let scope_constant_id = self.get_scope_constant(scope as u32)?; - let semantics_id = self.get_index_constant(semantics.bits())?; + let scope_constant_id = self.get_scope_constant(scope as u32); + let semantics_id = self.get_index_constant(semantics.bits()); Instruction::atomic_store( pointer_id, scope_constant_id, @@ -1741,8 +1741,8 @@ impl<'w> BlockContext<'w> { _ => unimplemented!(), }; let (semantics, scope) = class.to_spirv_semantics_and_scope(); - let scope_constant_id = self.get_scope_constant(scope as u32)?; - let semantics_id = self.get_index_constant(semantics.bits())?; + let scope_constant_id = self.get_scope_constant(scope as u32); + let semantics_id = self.get_index_constant(semantics.bits()); let value_id = self.cached[value]; let value_inner = self.fun_info[value].ty.inner_with(&self.ir_module.types); diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 1496e726b..a6b4b0dd2 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -141,7 +141,7 @@ impl<'w> BlockContext<'w> { } MaybeKnown::Computed(length_id) => { // Emit code to compute the max index from the length. - let const_one_id = self.get_index_constant(1)?; + let const_one_id = self.get_index_constant(1); let max_index_id = self.gen_id(); block.body.push(Instruction::binary( spirv::Op::ISub, @@ -196,7 +196,7 @@ impl<'w> BlockContext<'w> { } } - self.get_index_constant(known_max_index)? + self.get_index_constant(known_max_index) } MaybeKnown::Computed(max_index_id) => max_index_id, }; @@ -271,7 +271,7 @@ impl<'w> BlockContext<'w> { } } - self.get_index_constant(known_length)? + self.get_index_constant(known_length) } MaybeKnown::Computed(length_id) => length_id, }; diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 5f4eac72f..4c2c06e6d 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -364,12 +364,12 @@ impl BlockContext<'_> { self.writer.get_expression_type_id(tr) } - fn get_index_constant(&mut self, index: Word) -> Result { + fn get_index_constant(&mut self, index: Word) -> Word { self.writer .get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) } - fn get_scope_constant(&mut self, scope: Word) -> Result { + fn get_scope_constant(&mut self, scope: Word) -> Word { self.writer .get_constant_scalar(crate::ScalarValue::Sint(scope as _), 4) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 90aee19ac..ce7e6c068 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -829,7 +829,7 @@ impl Writer { Ok(id) } - pub(super) fn get_index_constant(&mut self, index: Word) -> Result { + pub(super) fn get_index_constant(&mut self, index: Word) -> Word { self.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) } @@ -837,14 +837,14 @@ impl Writer { &mut self, value: crate::ScalarValue, width: crate::Bytes, - ) -> Result { + ) -> Word { if let Some(&id) = self.cached_constants.get(&(value, width)) { - return Ok(id); + return id; } let id = self.id_gen.next(); - self.write_constant_scalar(id, &value, width, None)?; + self.write_constant_scalar(id, &value, width, None); self.cached_constants.insert((value, width), id); - Ok(id) + id } fn write_constant_scalar( @@ -853,7 +853,7 @@ impl Writer { value: &crate::ScalarValue, width: crate::Bytes, debug_name: Option<&String>, - ) -> Result<(), Error> { + ) { if self.flags.contains(WriterFlags::DEBUG) { if let Some(name) = debug_name { self.debugs.push(Instruction::name(id, name)); @@ -915,7 +915,6 @@ impl Writer { }; instruction.to_words(&mut self.logical_layout.declarations); - Ok(()) } fn write_constant_composite( @@ -1168,10 +1167,10 @@ impl Writer { self.constant_ids[handle.index()] = match constant.name { Some(ref name) => { let id = self.id_gen.next(); - self.write_constant_scalar(id, value, width, Some(name))?; + self.write_constant_scalar(id, value, width, Some(name)); id } - None => self.get_constant_scalar(*value, width)?, + None => self.get_constant_scalar(*value, width), }; } } From 6ab6d6fc46684b16bc493d06aab094361b0598f0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 18 Aug 2021 12:10:43 -0700 Subject: [PATCH 1247/2212] `ImageLoad` doc fix: `Depth` images can be multisampled, now. --- src/lib.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 3f40d366d..f3904eb09 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1082,11 +1082,9 @@ pub enum Expression { /// - [`Storage`] images hold exactly one sample per texel, so `index` must /// be `None`. /// - /// - [`Depth`] images may have mipmaps, so `index` must be `Some(level)`, - /// where `level` identifies the level of detail. - /// - /// - [`Sampled`] images may be multisampled or have mipmaps, but not both. - /// Which one is indicated by the `Sampled` variant's [`multi`] field: + /// - [`Depth`] and [`Sampled`] images may be multisampled or have + /// mipmaps, but not both. Which one is indicated by the variant's + /// [`multi`] field: /// /// - If `multi` is `true`, then the image has multiple samples per /// texel, and `index` must be `Some(sample)`, where `sample` is From dad4b1bb107a7e4cb975b34da5cdf6b4fdfbc292 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 19 Aug 2021 10:02:24 -0400 Subject: [PATCH 1248/2212] [hlsl-out] fix array arguments in functions --- src/back/hlsl/writer.rs | 8 ++++++-- tests/out/hlsl/quad-vert.hlsl | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 78cff0ce8..c42cf9f45 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -773,7 +773,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { back::FunctionType::Function(handle) => { for (index, arg) in func.arguments.iter().enumerate() { // Write argument type - let arg_ty = match module.types[arg.ty].inner { + let ty_inner = &module.types[arg.ty].inner; + let arg_ty = match *ty_inner { // pointers in function arguments are expected and resolve to `inout` TypeInner::Pointer { base, .. } => { //TODO: can we narrow this down to just `in` when possible? @@ -789,6 +790,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write argument name. Space is important. write!(self.out, " {}", argument_name)?; + if let TypeInner::Array { size, .. } = *ty_inner { + self.write_array_size(module, size)?; + } if index < func.arguments.len() - 1 { // Add a separator between args write!(self.out, ", ")?; @@ -1858,7 +1862,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { components: &[Handle], ) -> BackendResult { let (open_b, close_b) = match module.types[ty].inner { - TypeInner::Struct { .. } => ("{ ", " }"), + TypeInner::Array { .. } | TypeInner::Struct { .. } => ("{ ", " }"), _ => { // We should write type only for non struct constants self.write_type(module, ty)?; diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 72cf5a0d5..d190a05e5 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -16,7 +16,7 @@ struct type10 { static float2 v_uv = (float2)0; static float2 a_uv1 = (float2)0; -static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, float(0.0), float(0.0) }; +static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, { 0.0 }, { 0.0 } }; static float2 a_pos1 = (float2)0; struct VertexInput_main { From dfcb79880f3a42781efc72ae47ea291cbea8efec Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Thu, 19 Aug 2021 12:55:29 -0400 Subject: [PATCH 1249/2212] [hlsl-out] Fix pointer-to-array arguments (#1240) --- src/back/hlsl/writer.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index c42cf9f45..108d2b6c6 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -748,7 +748,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } - /// Helper method used to write structs + /// Helper method used to write functions /// # Notes /// Ends in a newline fn write_function( @@ -773,8 +773,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { back::FunctionType::Function(handle) => { for (index, arg) in func.arguments.iter().enumerate() { // Write argument type - let ty_inner = &module.types[arg.ty].inner; - let arg_ty = match *ty_inner { + let arg_ty = match module.types[arg.ty].inner { // pointers in function arguments are expected and resolve to `inout` TypeInner::Pointer { base, .. } => { //TODO: can we narrow this down to just `in` when possible? @@ -790,7 +789,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write argument name. Space is important. write!(self.out, " {}", argument_name)?; - if let TypeInner::Array { size, .. } = *ty_inner { + if let TypeInner::Array { size, .. } = module.types[arg.ty].inner { self.write_array_size(module, size)?; } if index < func.arguments.len() - 1 { @@ -1864,7 +1863,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let (open_b, close_b) = match module.types[ty].inner { TypeInner::Array { .. } | TypeInner::Struct { .. } => ("{ ", " }"), _ => { - // We should write type only for non struct constants + // We should write type only for non struct/array constants self.write_type(module, ty)?; ("(", ")") } From 02142d098082b610a4d28e2a7ab88d6746f7c87d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 18 Aug 2021 20:32:24 +0100 Subject: [PATCH 1250/2212] [wgsl-in] Add support for the dereference operator --- src/front/wgsl/mod.rs | 322 ++++++++++++++++++++++++++++-------------- 1 file changed, 219 insertions(+), 103 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7d2ad1dbf..cc76df158 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1055,6 +1055,15 @@ impl std::error::Error for ParseError { } } +/// The expression position in a assignment statement +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +enum ExprPosition { + /// The expression is in the left hand side of the assignment + Lhs, + /// The expression is in the right hand side of the assignment + Rhs, +} + pub struct Parser { scopes: Vec<(Scope, usize)>, lookup_type: FastHashMap>, @@ -1124,8 +1133,9 @@ impl Parser { lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { - let (pointer, pointer_span) = - lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx.reborrow()))?; + let (pointer, pointer_span) = lexer.capture_span(|lexer| { + self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs) + })?; // Check if the pointer expression is to an atomic. // The IR uses regular `Expression::Load` and `Statement::Store` for atomic load/stores, // and it will not catch the use of a non-atomic variable here. @@ -1167,7 +1177,7 @@ impl Parser { if !arguments.is_empty() { lexer.expect(Token::Separator(','))?; } - let arg = self.parse_general_expression(lexer, ctx.reborrow())?; + let arg = self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; arguments.push(arg); } lexer.close_arguments()?; @@ -1181,11 +1191,12 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.expect(Token::Separator(','))?; let ctx_span = ctx.reborrow(); - let (value, value_span) = - lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx_span))?; + let (value, value_span) = lexer.capture_span(|lexer| { + self.parse_singular_expression(lexer, ctx_span, ExprPosition::Rhs) + })?; lexer.close_arguments()?; let expression = match *ctx.resolve_type(value)? { @@ -1222,29 +1233,30 @@ impl Parser { let expr = if let Some(fun) = conv::map_relational_fun(name) { let _ = lexer.next(); lexer.open_arguments()?; - let argument = self.parse_general_expression(lexer, ctx.reborrow())?; + let argument = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.close_arguments()?; crate::Expression::Relational { fun, argument } } else if let Some(axis) = conv::map_derivative_axis(name) { let _ = lexer.next(); lexer.open_arguments()?; - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; + let expr = self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.close_arguments()?; crate::Expression::Derivative { axis, expr } } else if let Some(fun) = conv::map_standard_fun(name) { let _ = lexer.next(); lexer.open_arguments()?; let arg_count = fun.argument_count(); - let arg = self.parse_general_expression(lexer, ctx.reborrow())?; + let arg = self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let arg1 = if arg_count > 1 { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?) } else { None }; let arg2 = if arg_count > 2 { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?) } else { None }; @@ -1260,11 +1272,14 @@ impl Parser { "select" => { let _ = lexer.next(); lexer.open_arguments()?; - let reject = self.parse_general_expression(lexer, ctx.reborrow())?; + let reject = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.expect(Token::Separator(','))?; - let accept = self.parse_general_expression(lexer, ctx.reborrow())?; + let accept = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.expect(Token::Separator(','))?; - let condition = self.parse_general_expression(lexer, ctx.reborrow())?; + let condition = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.close_arguments()?; crate::Expression::Select { condition, @@ -1275,7 +1290,8 @@ impl Parser { "arrayLength" => { let _ = lexer.next(); lexer.open_arguments()?; - let array = self.parse_singular_expression(lexer, ctx.reborrow())?; + let array = + self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.close_arguments()?; crate::Expression::ArrayLength(array) } @@ -1347,12 +1363,14 @@ impl Parser { "atomicCompareExchangeWeak" => { let _ = lexer.next(); lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + let pointer = + self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.expect(Token::Separator(','))?; - let cmp = self.parse_singular_expression(lexer, ctx.reborrow())?; + let cmp = + self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.expect(Token::Separator(','))?; let (value, value_span) = lexer.capture_span(|lexer| { - self.parse_singular_expression(lexer, ctx.reborrow()) + self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs) })?; lexer.close_arguments()?; @@ -1389,11 +1407,16 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let coordinate = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression( + lexer, + ctx.reborrow(), + ExprPosition::Rhs, + )?) } else { None }; @@ -1420,16 +1443,22 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let coordinate = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression( + lexer, + ctx.reborrow(), + ExprPosition::Rhs, + )?) } else { None }; lexer.expect(Token::Separator(','))?; - let level = self.parse_general_expression(lexer, ctx.reborrow())?; + let level = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1453,16 +1482,22 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let coordinate = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression( + lexer, + ctx.reborrow(), + ExprPosition::Rhs, + )?) } else { None }; lexer.expect(Token::Separator(','))?; - let bias = self.parse_general_expression(lexer, ctx.reborrow())?; + let bias = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1486,18 +1521,25 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let coordinate = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression( + lexer, + ctx.reborrow(), + ExprPosition::Rhs, + )?) } else { None }; lexer.expect(Token::Separator(','))?; - let x = self.parse_general_expression(lexer, ctx.reborrow())?; + let x = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; lexer.expect(Token::Separator(','))?; - let y = self.parse_general_expression(lexer, ctx.reborrow())?; + let y = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1521,16 +1563,22 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let coordinate = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression( + lexer, + ctx.reborrow(), + ExprPosition::Rhs, + )?) } else { None }; lexer.expect(Token::Separator(','))?; - let reference = self.parse_general_expression(lexer, ctx.reborrow())?; + let reference = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1554,16 +1602,22 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let coordinate = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression( + lexer, + ctx.reborrow(), + ExprPosition::Rhs, + )?) } else { None }; lexer.expect(Token::Separator(','))?; - let reference = self.parse_general_expression(lexer, ctx.reborrow())?; + let reference = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1586,14 +1640,19 @@ impl Parser { let (image_name, image_span) = lexer.next_ident_with_span()?; let image = ctx.lookup_ident.lookup(image_name, image_span.clone())?; lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let coordinate = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let (class, arrayed) = match *ctx.resolve_type(image)? { crate::TypeInner::Image { class, arrayed, .. } => (class, arrayed), _ => return Err(Error::BadTexture(image_span)), }; let array_index = if arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression( + lexer, + ctx.reborrow(), + ExprPosition::Rhs, + )?) } else { None }; @@ -1602,7 +1661,11 @@ impl Parser { // it's the MSAA index for multi-sampled, and LOD for the others crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) + Some(self.parse_general_expression( + lexer, + ctx.reborrow(), + ExprPosition::Rhs, + )?) } }; lexer.close_arguments()?; @@ -1619,7 +1682,11 @@ impl Parser { let (image_name, image_span) = lexer.next_ident_with_span()?; let image = ctx.lookup_ident.lookup(image_name, image_span)?; let level = if lexer.skip(Token::Separator(',')) { - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; + let expr = self.parse_general_expression( + lexer, + ctx.reborrow(), + ExprPosition::Rhs, + )?; Some(expr) } else { None @@ -1723,11 +1790,13 @@ impl Parser { let mut components = Vec::new(); let (last_component, arguments_span) = lexer.capture_span(|lexer| { lexer.open_arguments()?; - let mut last_component = self.parse_general_expression(lexer, ctx.reborrow())?; + let mut last_component = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; while lexer.next_argument()? { components.push(last_component); - last_component = self.parse_general_expression(lexer, ctx.reborrow())?; + last_component = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; } Ok(last_component) @@ -1893,13 +1962,14 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, + pos: ExprPosition, ) -> Result, Error<'a>> { // Will be popped inside match, possibly inside parse_function_call_inner or parse_construction self.push_scope(Scope::PrimaryExpr, lexer); let handle = match lexer.peek() { (Token::Paren('('), _) => { let _ = lexer.next(); - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; + let expr = self.parse_general_expression(lexer, ctx.reborrow(), pos)?; lexer.expect(Token::Paren(')'))?; self.pop_scope(lexer); expr @@ -2030,7 +2100,8 @@ impl Parser { } Token::Paren('[') => { let (_, open_brace_span) = lexer.next(); - let index = self.parse_general_expression(lexer, ctx.reborrow())?; + let index = + self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; let close_brace_span = lexer.expect_span(Token::Paren(']'))?; if let crate::Expression::Constant(constant) = ctx.expressions[index] { @@ -2081,6 +2152,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, + pos: ExprPosition, ) -> Result, Error<'a>> { let start = lexer.current_byte_offset(); self.push_scope(Scope::SingularExpr, lexer); @@ -2090,7 +2162,7 @@ impl Parser { let _ = lexer.next(); let expr = crate::Expression::Unary { op: crate::UnaryOperator::Negate, - expr: self.parse_singular_expression(lexer, ctx.reborrow())?, + expr: self.parse_singular_expression(lexer, ctx.reborrow(), pos)?, }; let span = self.peek_scope(lexer); ( @@ -2102,7 +2174,7 @@ impl Parser { let _ = lexer.next(); let expr = crate::Expression::Unary { op: crate::UnaryOperator::Not, - expr: self.parse_singular_expression(lexer, ctx.reborrow())?, + expr: self.parse_singular_expression(lexer, ctx.reborrow(), pos)?, }; let span = self.peek_scope(lexer); ( @@ -2112,23 +2184,27 @@ impl Parser { } Token::Operation('*') => { let _ = lexer.next(); - let expr = crate::Expression::Load { - pointer: self.parse_singular_expression(lexer, ctx.reborrow())?, - }; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow(), pos)?; let span = self.peek_scope(lexer); ( false, - ctx.expressions.append(expr, NagaSpan::ByteRange(span)), + match pos { + ExprPosition::Rhs => ctx.expressions.append( + crate::Expression::Load { pointer }, + NagaSpan::ByteRange(span), + ), + ExprPosition::Lhs => pointer, + }, ) } Token::Operation('&') => { let _ = lexer.next(); - let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; + let handle = self.parse_primary_expression(lexer, ctx.reborrow(), pos)?; (false, handle) } _ => { - let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; - (true, handle) + let handle = self.parse_primary_expression(lexer, ctx.reborrow(), pos)?; + (ExprPosition::Rhs == pos, handle) } }; @@ -2141,6 +2217,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, + pos: ExprPosition, ) -> Result, Error<'a>> { // equality_expression context.parse_binary_op( @@ -2202,7 +2279,7 @@ impl Parser { _ => None, }, |lexer, context| { - self.parse_singular_expression(lexer, context) + self.parse_singular_expression(lexer, context, pos) }, ) }, @@ -2219,6 +2296,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, + pos: ExprPosition, ) -> Result, Error<'a>> { self.push_scope(Scope::GeneralExpr, lexer); // logical_or_expression @@ -2265,7 +2343,7 @@ impl Parser { _ => None, }, |lexer, context| { - self.parse_equality_expression(lexer, context) + self.parse_equality_expression(lexer, context, pos) }, ) }, @@ -2820,9 +2898,31 @@ impl Parser { Ok((handle, storage_access)) } - /// Parse a statement that is either an assignment or a function call. - /// Expects `ident` to still be in the lexer. - fn parse_statement_restricted<'a, 'out>( + /// Parse a assignment statement + fn parse_assignment_statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, 'out>, + ) -> Result<(), Error<'a>> { + let span_start = lexer.current_byte_offset(); + context.emitter.start(context.expressions); + let pointer = + self.parse_singular_expression(lexer, context.reborrow(), ExprPosition::Lhs)?; + lexer.expect(Token::Operation('='))?; + let value = self.parse_general_expression(lexer, context.reborrow(), ExprPosition::Rhs)?; + let span_end = lexer.current_byte_offset(); + context + .block + .extend(context.emitter.finish(context.expressions)); + context.block.push( + crate::Statement::Store { pointer, value }, + NagaSpan::ByteRange(span_start..span_end), + ); + Ok(()) + } + + /// Parse a function call statement. + fn parse_function_statement<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, ident: &'a str, @@ -2831,36 +2931,21 @@ impl Parser { ) -> Result<(), Error<'a>> { let span_start = ident_span.start; context.emitter.start(context.expressions); - let stmt = match context.lookup_ident.get(ident) { - Some(&expr) => { - let _ = lexer.next(); - let left = - self.parse_postfix(span_start, lexer, context.reborrow(), expr, false)?; - lexer.expect(Token::Operation('='))?; - let value = self.parse_general_expression(lexer, context.reborrow())?; - crate::Statement::Store { - pointer: left, - value, - } - } - None => { - let (function, arguments) = self - .parse_local_function_call(lexer, ident, context.reborrow())? - .ok_or(Error::UnknownLocalFunction(ident_span))?; - crate::Statement::Call { - function, - arguments, - result: None, - } - } - }; + let (function, arguments) = self + .parse_local_function_call(lexer, ident, context.reborrow())? + .ok_or(Error::UnknownLocalFunction(ident_span))?; let span_end = lexer.current_byte_offset(); context .block .extend(context.emitter.finish(context.expressions)); - context - .block - .push(stmt, NagaSpan::ByteRange(span_start..span_end)); + context.block.push( + crate::Statement::Call { + function, + arguments, + result: None, + }, + NagaSpan::ByteRange(span_start..span_end), + ); Ok(()) } @@ -2920,6 +3005,7 @@ impl Parser { let expr_id = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), + ExprPosition::Rhs, )?; lexer.expect(Token::Separator(';'))?; if let Some(ty) = given_ty { @@ -2971,6 +3057,7 @@ impl Parser { let value = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), + ExprPosition::Rhs, )?; block.extend(emitter.finish(context.expressions)); @@ -3065,6 +3152,7 @@ impl Parser { let handle = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), + ExprPosition::Rhs, )?; block.extend(emitter.finish(context.expressions)); Some(handle) @@ -3081,6 +3169,7 @@ impl Parser { let condition = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), + ExprPosition::Rhs, )?; block.extend(emitter.finish(context.expressions)); lexer.expect(Token::Paren(')'))?; @@ -3096,6 +3185,7 @@ impl Parser { let other_condition = self.parse_general_expression( lexer, context.as_expression(block, &mut sub_emitter), + ExprPosition::Rhs, )?; let other_emit = sub_emitter.finish(context.expressions); lexer.expect(Token::Paren(')'))?; @@ -3142,6 +3232,7 @@ impl Parser { let selector = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), + ExprPosition::Rhs, )?; lexer.expect(Token::Paren(')'))?; block.extend(emitter.finish(context.expressions)); @@ -3264,6 +3355,7 @@ impl Parser { let condition = self.parse_general_expression( lexer, context.as_expression(&mut body, &mut emitter), + ExprPosition::Rhs, )?; lexer.expect(Token::Separator(';'))?; body.extend(emitter.finish(context.expressions)); @@ -3282,17 +3374,24 @@ impl Parser { }; let mut continuing = crate::Block::new(); - if let (Token::Word(ident), ident_span) = lexer.peek() { - // manually parse the next statement here instead of calling parse_statement - // because the statement is not terminated with a semicolon - self.parse_statement_restricted( - lexer, - ident, - ident_span, - context.as_expression(&mut continuing, &mut emitter), - )?; + if !lexer.skip(Token::Paren(')')) { + let (token, span) = lexer.peek(); + match token { + Token::Word(ident) if context.lookup_ident.get(ident).is_none() => { + self.parse_function_statement( + lexer, + ident, + span, + context.as_expression(&mut continuing, &mut emitter), + )? + } + _ => self.parse_assignment_statement( + lexer, + context.as_expression(&mut continuing, &mut emitter), + )?, + } + lexer.expect(Token::Paren(')'))?; } - lexer.expect(Token::Paren(')'))?; lexer.expect(Token::Paren('{'))?; while !lexer.skip(Token::Paren('}')) { @@ -3333,7 +3432,11 @@ impl Parser { let pointer = self.parse_atomic_pointer(lexer, expression_ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let value = self.parse_general_expression(lexer, expression_ctx)?; + let value = self.parse_general_expression( + lexer, + expression_ctx, + ExprPosition::Rhs, + )?; lexer.close_arguments()?; block.extend(emitter.finish(context.expressions)); Some(crate::Statement::Store { pointer, value }) @@ -3352,12 +3455,14 @@ impl Parser { crate::TypeInner::Image { arrayed, .. } => arrayed, _ => return Err(Error::BadTexture(image_span)), }; - let coordinate = self.parse_general_expression(lexer, expr_context)?; + let coordinate = + self.parse_general_expression(lexer, expr_context, ExprPosition::Rhs)?; let array_index = if arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), + ExprPosition::Rhs, )?) } else { None @@ -3366,6 +3471,7 @@ impl Parser { let value = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), + ExprPosition::Rhs, )?; lexer.close_arguments()?; block.extend(emitter.finish(context.expressions)); @@ -3378,12 +3484,18 @@ impl Parser { } // assignment or a function call ident => { - self.parse_statement_restricted( - lexer, - ident, - word_span, - context.as_expression(block, &mut emitter), - )?; + match context.lookup_ident.get(ident) { + Some(_) => self.parse_assignment_statement( + lexer, + context.as_expression(block, &mut emitter), + )?, + None => self.parse_function_statement( + lexer, + ident, + word_span, + context.as_expression(block, &mut emitter), + )?, + } lexer.expect(Token::Separator(';'))?; None } @@ -3393,7 +3505,11 @@ impl Parser { block.push(statement, NagaSpan::ByteRange(span)); } } - other => return Err(Error::Unexpected(other, ExpectedToken::Statement)), + _ => { + let mut emitter = super::Emitter::default(); + self.parse_assignment_statement(lexer, context.as_expression(block, &mut emitter))?; + self.pop_scope(lexer); + } } Ok(()) } From f14817e8a091c464b5b309af9f313720faa7defd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 18 Aug 2021 21:24:01 +0100 Subject: [PATCH 1251/2212] [wgsl-in] Store expression position in context --- src/front/wgsl/mod.rs | 228 +++++++++++++++--------------------------- 1 file changed, 78 insertions(+), 150 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index cc76df158..745d1ea2d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -668,6 +668,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { arguments: self.arguments, block, emitter, + rhs: true, } } } @@ -689,6 +690,9 @@ struct ExpressionContext<'input, 'temp, 'out> { functions: &'out Arena, block: &'temp mut crate::Block, emitter: &'temp mut super::Emitter, + /// Wether or not the current expression is in the right hand side of an + /// assignemnt statement or equivalent + rhs: bool, } impl<'a> ExpressionContext<'a, '_, '_> { @@ -705,9 +709,22 @@ impl<'a> ExpressionContext<'a, '_, '_> { arguments: self.arguments, block: self.block, emitter: self.emitter, + rhs: self.rhs, } } + fn reborrow_rhs(&mut self) -> ExpressionContext<'a, '_, '_> { + let mut reborrow = self.reborrow(); + reborrow.rhs = true; + reborrow + } + + fn reborrow_lhs(&mut self) -> ExpressionContext<'a, '_, '_> { + let mut reborrow = self.reborrow(); + reborrow.rhs = false; + reborrow + } + fn resolve_type( &mut self, handle: Handle, @@ -1055,15 +1072,6 @@ impl std::error::Error for ParseError { } } -/// The expression position in a assignment statement -#[derive(Debug, PartialEq, Eq, Clone, Copy)] -enum ExprPosition { - /// The expression is in the left hand side of the assignment - Lhs, - /// The expression is in the right hand side of the assignment - Rhs, -} - pub struct Parser { scopes: Vec<(Scope, usize)>, lookup_type: FastHashMap>, @@ -1133,9 +1141,8 @@ impl Parser { lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { - let (pointer, pointer_span) = lexer.capture_span(|lexer| { - self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs) - })?; + let (pointer, pointer_span) = + lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx.reborrow()))?; // Check if the pointer expression is to an atomic. // The IR uses regular `Expression::Load` and `Statement::Store` for atomic load/stores, // and it will not catch the use of a non-atomic variable here. @@ -1177,7 +1184,7 @@ impl Parser { if !arguments.is_empty() { lexer.expect(Token::Separator(','))?; } - let arg = self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let arg = self.parse_general_expression(lexer, ctx.reborrow())?; arguments.push(arg); } lexer.close_arguments()?; @@ -1191,12 +1198,11 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let ctx_span = ctx.reborrow(); - let (value, value_span) = lexer.capture_span(|lexer| { - self.parse_singular_expression(lexer, ctx_span, ExprPosition::Rhs) - })?; + let (value, value_span) = + lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx_span))?; lexer.close_arguments()?; let expression = match *ctx.resolve_type(value)? { @@ -1233,30 +1239,29 @@ impl Parser { let expr = if let Some(fun) = conv::map_relational_fun(name) { let _ = lexer.next(); lexer.open_arguments()?; - let argument = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let argument = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::Relational { fun, argument } } else if let Some(axis) = conv::map_derivative_axis(name) { let _ = lexer.next(); lexer.open_arguments()?; - let expr = self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::Derivative { axis, expr } } else if let Some(fun) = conv::map_standard_fun(name) { let _ = lexer.next(); lexer.open_arguments()?; let arg_count = fun.argument_count(); - let arg = self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let arg = self.parse_general_expression(lexer, ctx.reborrow())?; let arg1 = if arg_count > 1 { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; let arg2 = if arg_count > 2 { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; @@ -1272,14 +1277,11 @@ impl Parser { "select" => { let _ = lexer.next(); lexer.open_arguments()?; - let reject = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let reject = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let accept = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let accept = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let condition = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let condition = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::Select { condition, @@ -1290,8 +1292,7 @@ impl Parser { "arrayLength" => { let _ = lexer.next(); lexer.open_arguments()?; - let array = - self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let array = self.parse_singular_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::ArrayLength(array) } @@ -1363,14 +1364,12 @@ impl Parser { "atomicCompareExchangeWeak" => { let _ = lexer.next(); lexer.open_arguments()?; - let pointer = - self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let cmp = - self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let cmp = self.parse_singular_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let (value, value_span) = lexer.capture_span(|lexer| { - self.parse_singular_expression(lexer, ctx.reborrow(), ExprPosition::Rhs) + self.parse_singular_expression(lexer, ctx.reborrow()) })?; lexer.close_arguments()?; @@ -1407,16 +1406,11 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - ctx.reborrow(), - ExprPosition::Rhs, - )?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; @@ -1443,22 +1437,16 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - ctx.reborrow(), - ExprPosition::Rhs, - )?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; lexer.expect(Token::Separator(','))?; - let level = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let level = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1482,22 +1470,16 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - ctx.reborrow(), - ExprPosition::Rhs, - )?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; lexer.expect(Token::Separator(','))?; - let bias = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let bias = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1521,25 +1503,18 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - ctx.reborrow(), - ExprPosition::Rhs, - )?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; lexer.expect(Token::Separator(','))?; - let x = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let x = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let y = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let y = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1563,22 +1538,16 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - ctx.reborrow(), - ExprPosition::Rhs, - )?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; lexer.expect(Token::Separator(','))?; - let reference = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let reference = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1602,22 +1571,16 @@ impl Parser { lexer.expect(Token::Separator(','))?; let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let sc = ctx.prepare_sampling(image_name, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - ctx.reborrow(), - ExprPosition::Rhs, - )?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; lexer.expect(Token::Separator(','))?; - let reference = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let reference = self.parse_general_expression(lexer, ctx.reborrow())?; let offset = if lexer.skip(Token::Separator(',')) { Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) } else { @@ -1640,19 +1603,14 @@ impl Parser { let (image_name, image_span) = lexer.next_ident_with_span()?; let image = ctx.lookup_ident.lookup(image_name, image_span.clone())?; lexer.expect(Token::Separator(','))?; - let coordinate = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let (class, arrayed) = match *ctx.resolve_type(image)? { crate::TypeInner::Image { class, arrayed, .. } => (class, arrayed), _ => return Err(Error::BadTexture(image_span)), }; let array_index = if arrayed { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - ctx.reborrow(), - ExprPosition::Rhs, - )?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } else { None }; @@ -1661,11 +1619,7 @@ impl Parser { // it's the MSAA index for multi-sampled, and LOD for the others crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => { lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - ctx.reborrow(), - ExprPosition::Rhs, - )?) + Some(self.parse_general_expression(lexer, ctx.reborrow())?) } }; lexer.close_arguments()?; @@ -1682,11 +1636,7 @@ impl Parser { let (image_name, image_span) = lexer.next_ident_with_span()?; let image = ctx.lookup_ident.lookup(image_name, image_span)?; let level = if lexer.skip(Token::Separator(',')) { - let expr = self.parse_general_expression( - lexer, - ctx.reborrow(), - ExprPosition::Rhs, - )?; + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; Some(expr) } else { None @@ -1790,13 +1740,11 @@ impl Parser { let mut components = Vec::new(); let (last_component, arguments_span) = lexer.capture_span(|lexer| { lexer.open_arguments()?; - let mut last_component = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let mut last_component = self.parse_general_expression(lexer, ctx.reborrow())?; while lexer.next_argument()? { components.push(last_component); - last_component = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + last_component = self.parse_general_expression(lexer, ctx.reborrow())?; } Ok(last_component) @@ -1962,14 +1910,13 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, - pos: ExprPosition, ) -> Result, Error<'a>> { // Will be popped inside match, possibly inside parse_function_call_inner or parse_construction self.push_scope(Scope::PrimaryExpr, lexer); let handle = match lexer.peek() { (Token::Paren('('), _) => { let _ = lexer.next(); - let expr = self.parse_general_expression(lexer, ctx.reborrow(), pos)?; + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; self.pop_scope(lexer); expr @@ -1992,14 +1939,14 @@ impl Parser { self.pop_scope(lexer); expr } else if let Some(expr) = - self.parse_function_call_inner(lexer, word, ctx.reborrow())? + self.parse_function_call_inner(lexer, word, ctx.reborrow_rhs())? { //TODO: resolve the duplicate call in `parse_singular_expression` self.pop_scope(lexer); expr } else { let _ = lexer.next(); - if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow())? { + if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow_rhs())? { expr } else { return Err(Error::UnknownIdent(span, word)); @@ -2100,8 +2047,7 @@ impl Parser { } Token::Paren('[') => { let (_, open_brace_span) = lexer.next(); - let index = - self.parse_general_expression(lexer, ctx.reborrow(), ExprPosition::Rhs)?; + let index = self.parse_general_expression(lexer, ctx.reborrow_rhs())?; let close_brace_span = lexer.expect_span(Token::Paren(']'))?; if let crate::Expression::Constant(constant) = ctx.expressions[index] { @@ -2152,7 +2098,6 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, - pos: ExprPosition, ) -> Result, Error<'a>> { let start = lexer.current_byte_offset(); self.push_scope(Scope::SingularExpr, lexer); @@ -2162,7 +2107,7 @@ impl Parser { let _ = lexer.next(); let expr = crate::Expression::Unary { op: crate::UnaryOperator::Negate, - expr: self.parse_singular_expression(lexer, ctx.reborrow(), pos)?, + expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }; let span = self.peek_scope(lexer); ( @@ -2174,7 +2119,7 @@ impl Parser { let _ = lexer.next(); let expr = crate::Expression::Unary { op: crate::UnaryOperator::Not, - expr: self.parse_singular_expression(lexer, ctx.reborrow(), pos)?, + expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }; let span = self.peek_scope(lexer); ( @@ -2184,27 +2129,27 @@ impl Parser { } Token::Operation('*') => { let _ = lexer.next(); - let pointer = self.parse_singular_expression(lexer, ctx.reborrow(), pos)?; + let pointer = self.parse_primary_expression(lexer, ctx.reborrow())?; let span = self.peek_scope(lexer); ( false, - match pos { - ExprPosition::Rhs => ctx.expressions.append( + match ctx.rhs { + true => ctx.expressions.append( crate::Expression::Load { pointer }, NagaSpan::ByteRange(span), ), - ExprPosition::Lhs => pointer, + false => pointer, }, ) } Token::Operation('&') => { let _ = lexer.next(); - let handle = self.parse_primary_expression(lexer, ctx.reborrow(), pos)?; + let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; (false, handle) } _ => { - let handle = self.parse_primary_expression(lexer, ctx.reborrow(), pos)?; - (ExprPosition::Rhs == pos, handle) + let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; + (ctx.rhs, handle) } }; @@ -2217,7 +2162,6 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, - pos: ExprPosition, ) -> Result, Error<'a>> { // equality_expression context.parse_binary_op( @@ -2279,7 +2223,7 @@ impl Parser { _ => None, }, |lexer, context| { - self.parse_singular_expression(lexer, context, pos) + self.parse_singular_expression(lexer, context) }, ) }, @@ -2296,7 +2240,6 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, - pos: ExprPosition, ) -> Result, Error<'a>> { self.push_scope(Scope::GeneralExpr, lexer); // logical_or_expression @@ -2343,7 +2286,7 @@ impl Parser { _ => None, }, |lexer, context| { - self.parse_equality_expression(lexer, context, pos) + self.parse_equality_expression(lexer, context) }, ) }, @@ -2906,10 +2849,9 @@ impl Parser { ) -> Result<(), Error<'a>> { let span_start = lexer.current_byte_offset(); context.emitter.start(context.expressions); - let pointer = - self.parse_singular_expression(lexer, context.reborrow(), ExprPosition::Lhs)?; + let pointer = self.parse_singular_expression(lexer, context.reborrow_lhs())?; lexer.expect(Token::Operation('='))?; - let value = self.parse_general_expression(lexer, context.reborrow(), ExprPosition::Rhs)?; + let value = self.parse_general_expression(lexer, context.reborrow())?; let span_end = lexer.current_byte_offset(); context .block @@ -3005,7 +2947,6 @@ impl Parser { let expr_id = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), - ExprPosition::Rhs, )?; lexer.expect(Token::Separator(';'))?; if let Some(ty) = given_ty { @@ -3057,7 +2998,6 @@ impl Parser { let value = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), - ExprPosition::Rhs, )?; block.extend(emitter.finish(context.expressions)); @@ -3152,7 +3092,6 @@ impl Parser { let handle = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), - ExprPosition::Rhs, )?; block.extend(emitter.finish(context.expressions)); Some(handle) @@ -3169,7 +3108,6 @@ impl Parser { let condition = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), - ExprPosition::Rhs, )?; block.extend(emitter.finish(context.expressions)); lexer.expect(Token::Paren(')'))?; @@ -3185,7 +3123,6 @@ impl Parser { let other_condition = self.parse_general_expression( lexer, context.as_expression(block, &mut sub_emitter), - ExprPosition::Rhs, )?; let other_emit = sub_emitter.finish(context.expressions); lexer.expect(Token::Paren(')'))?; @@ -3232,7 +3169,6 @@ impl Parser { let selector = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), - ExprPosition::Rhs, )?; lexer.expect(Token::Paren(')'))?; block.extend(emitter.finish(context.expressions)); @@ -3355,7 +3291,6 @@ impl Parser { let condition = self.parse_general_expression( lexer, context.as_expression(&mut body, &mut emitter), - ExprPosition::Rhs, )?; lexer.expect(Token::Separator(';'))?; body.extend(emitter.finish(context.expressions)); @@ -3432,11 +3367,7 @@ impl Parser { let pointer = self.parse_atomic_pointer(lexer, expression_ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let value = self.parse_general_expression( - lexer, - expression_ctx, - ExprPosition::Rhs, - )?; + let value = self.parse_general_expression(lexer, expression_ctx)?; lexer.close_arguments()?; block.extend(emitter.finish(context.expressions)); Some(crate::Statement::Store { pointer, value }) @@ -3455,14 +3386,12 @@ impl Parser { crate::TypeInner::Image { arrayed, .. } => arrayed, _ => return Err(Error::BadTexture(image_span)), }; - let coordinate = - self.parse_general_expression(lexer, expr_context, ExprPosition::Rhs)?; + let coordinate = self.parse_general_expression(lexer, expr_context)?; let array_index = if arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), - ExprPosition::Rhs, )?) } else { None @@ -3471,7 +3400,6 @@ impl Parser { let value = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), - ExprPosition::Rhs, )?; lexer.close_arguments()?; block.extend(emitter.finish(context.expressions)); From fc47008d0c01fd1658626f6ed7fa4a7a695da3be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 19 Aug 2021 20:56:44 +0100 Subject: [PATCH 1252/2212] [glsl-in] Allow expression statements to begin with ++ or -- This would otherwise cause the parser to enter an infinite loop. Fixes #1232 --- src/front/glsl/parser/functions.rs | 2 ++ src/front/glsl/parser_tests.rs | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index af1568fcd..c91e6aeb2 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -495,6 +495,8 @@ impl<'source> ParsingContext<'source> { | TokenValue::Bang | TokenValue::Tilde | TokenValue::LeftParen + | TokenValue::Increment + | TokenValue::Decrement | TokenValue::Identifier(_) | TokenValue::TypeName(_) | TokenValue::IntConstant(_) diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 10c4b92c2..717737bc5 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -778,9 +778,10 @@ fn swizzles() { } #[test] -fn vector_indexing() { +fn expressions() { let mut parser = Parser::default(); + // Vector indexing parser .parse( &Options::from(ShaderStage::Vertex), @@ -795,4 +796,20 @@ fn vector_indexing() { "#, ) .unwrap(); + + // Prefix increment/decrement + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" + # version 450 + void main() { + uint index = 0; + + --index; + ++index; + } + "#, + ) + .unwrap(); } From ca405e3acf5c4785128c0a9ff5114f28bbef5289 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 19 Aug 2021 22:07:57 +0100 Subject: [PATCH 1253/2212] [glsl-in] Allow dynamic indexing on constant variables Previously we always set the lhs flag when lowering to generate a pointer so that dynamic indexing would work, this would produce an error on constant variables since they can't be in a lhs context. Now we introduce an enum which distinguishes not only between lhs and rhs but also in array base, if lowering in a lhs context the base is also lowered in a lhs context but if lowering in rhs the base is lowered in a special array base context which bypasses the mutability check. Fixes #1237 --- src/front/glsl/ast.rs | 10 +++- src/front/glsl/context.rs | 85 ++++++++++++++++++--------- src/front/glsl/functions.rs | 10 ++-- src/front/glsl/parser.rs | 4 +- src/front/glsl/parser/declarations.rs | 4 +- src/front/glsl/parser/functions.rs | 23 ++++---- src/front/glsl/parser_tests.rs | 15 +++++ 7 files changed, 103 insertions(+), 48 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 8a8cdc0cd..5cadd03cb 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,6 +1,6 @@ use std::fmt; -use super::{builtins::MacroCall, SourceMetadata}; +use super::{builtins::MacroCall, context::ExprPos, SourceMetadata}; use crate::{ BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, Interpolation, Sampling, StorageAccess, StorageClass, Type, UnaryOperator, @@ -214,6 +214,14 @@ impl ParameterQualifier { _ => false, } } + + /// Converts from a parameter qualifier into a [`ExprPos`](ExprPos) + pub fn as_pos(&self) -> ExprPos { + match *self { + ParameterQualifier::Out | ParameterQualifier::InOut => ExprPos::Lhs, + _ => ExprPos::Rhs, + } + } } /// The glsl profile used by a shader diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 57787463c..eb40a6a3f 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -15,6 +15,28 @@ use crate::{ }; use std::{convert::TryFrom, ops::Index}; +/// The position at which an expression is, used while lowering +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum ExprPos { + /// The expression is in the left hand side of an assignment + Lhs, + /// The expression is in the right hand side of an assignment + Rhs, + /// The expression is an array being indexed, needed to allow constant + /// arrays to be dinamically indexed + ArrayBase, +} + +impl ExprPos { + /// Returns an lhs position if the current position is lhs otherwise ArrayBase + fn maybe_array_base(&self) -> Self { + match *self { + ExprPos::Lhs => *self, + _ => ExprPos::ArrayBase, + } + } +} + #[derive(Debug)] pub struct Context { pub expressions: Arena, @@ -323,10 +345,10 @@ impl Context { mut stmt: StmtContext, parser: &mut Parser, expr: Handle, - lhs: bool, + pos: ExprPos, body: &mut Block, ) -> Result<(Option>, SourceMetadata)> { - let res = self.lower_inner(&stmt, parser, expr, lhs, body); + let res = self.lower_inner(&stmt, parser, expr, pos, body); stmt.hir_exprs.clear(); self.stmt_ctx = Some(stmt); @@ -344,10 +366,10 @@ impl Context { mut stmt: StmtContext, parser: &mut Parser, expr: Handle, - lhs: bool, + pos: ExprPos, body: &mut Block, ) -> Result<(Handle, SourceMetadata)> { - let res = self.lower_expect_inner(&stmt, parser, expr, lhs, body); + let res = self.lower_expect_inner(&stmt, parser, expr, pos, body); stmt.hir_exprs.clear(); self.stmt_ctx = Some(stmt); @@ -365,10 +387,10 @@ impl Context { stmt: &StmtContext, parser: &mut Parser, expr: Handle, - lhs: bool, + pos: ExprPos, body: &mut Block, ) -> Result<(Handle, SourceMetadata)> { - let (maybe_expr, meta) = self.lower_inner(stmt, parser, expr, lhs, body)?; + let (maybe_expr, meta) = self.lower_inner(stmt, parser, expr, pos, body)?; let expr = match maybe_expr { Some(e) => e, @@ -389,16 +411,18 @@ impl Context { stmt: &StmtContext, parser: &mut Parser, expr: Handle, - lhs: bool, + pos: ExprPos, body: &mut Block, ) -> Result<(Option>, SourceMetadata)> { let HirExpr { ref kind, meta } = stmt.hir_exprs[expr]; let handle = match *kind { HirExprKind::Access { base, index } => { - let base = self.lower_expect_inner(stmt, parser, base, true, body)?.0; + let base = self + .lower_expect_inner(stmt, parser, base, pos.maybe_array_base(), body)? + .0; let (index, index_meta) = - self.lower_expect_inner(stmt, parser, index, false, body)?; + self.lower_expect_inner(stmt, parser, index, ExprPos::Rhs, body)?; let pointer = parser .solve_constant(self, index, index_meta) @@ -427,7 +451,7 @@ impl Context { self.add_expression(Expression::Access { base, index }, meta, body) }); - if !lhs { + if ExprPos::Rhs == pos { let resolved = parser.resolve_type(self, pointer, meta)?; if resolved.pointer_class().is_some() { return Ok(( @@ -440,18 +464,18 @@ impl Context { pointer } HirExprKind::Select { base, ref field } => { - let base = self.lower_expect_inner(stmt, parser, base, lhs, body)?.0; + let base = self.lower_expect_inner(stmt, parser, base, pos, body)?.0; - parser.field_selection(self, lhs, body, base, field, meta)? + parser.field_selection(self, ExprPos::Lhs == pos, body, base, field, meta)? } - HirExprKind::Constant(constant) if !lhs => { + HirExprKind::Constant(constant) if pos == ExprPos::Rhs => { self.add_expression(Expression::Constant(constant), meta, body) } - HirExprKind::Binary { left, op, right } if !lhs => { + HirExprKind::Binary { left, op, right } if pos == ExprPos::Rhs => { let (mut left, left_meta) = - self.lower_expect_inner(stmt, parser, left, false, body)?; + self.lower_expect_inner(stmt, parser, left, pos, body)?; let (mut right, right_meta) = - self.lower_expect_inner(stmt, parser, right, false, body)?; + self.lower_expect_inner(stmt, parser, right, pos, body)?; match op { BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self @@ -543,14 +567,14 @@ impl Context { _ => self.add_expression(Expression::Binary { left, op, right }, meta, body), } } - HirExprKind::Unary { op, expr } if !lhs => { - let expr = self.lower_expect_inner(stmt, parser, expr, false, body)?.0; + HirExprKind::Unary { op, expr } if pos == ExprPos::Rhs => { + let expr = self.lower_expect_inner(stmt, parser, expr, pos, body)?.0; self.add_expression(Expression::Unary { op, expr }, meta, body) } HirExprKind::Variable(ref var) => { - if lhs { - if !var.mutable { + if pos != ExprPos::Rhs { + if !var.mutable && ExprPos::Lhs == pos { parser.errors.push(Error { kind: ErrorKind::SemanticError( "Variable cannot be used in LHS position".into(), @@ -566,7 +590,7 @@ impl Context { var.expr } } - HirExprKind::Call(ref call) if !lhs => { + HirExprKind::Call(ref call) if pos != ExprPos::Lhs => { let maybe_expr = parser.function_or_constructor_call( self, stmt, @@ -581,14 +605,14 @@ impl Context { condition, accept, reject, - } if !lhs => { + } if ExprPos::Lhs != pos => { let condition = self - .lower_expect_inner(stmt, parser, condition, false, body)? + .lower_expect_inner(stmt, parser, condition, ExprPos::Rhs, body)? .0; let (mut accept, accept_meta) = - self.lower_expect_inner(stmt, parser, accept, false, body)?; + self.lower_expect_inner(stmt, parser, accept, pos, body)?; let (mut reject, reject_meta) = - self.lower_expect_inner(stmt, parser, reject, false, body)?; + self.lower_expect_inner(stmt, parser, reject, pos, body)?; self.binary_implicit_conversion( parser, @@ -608,10 +632,11 @@ impl Context { body, ) } - HirExprKind::Assign { tgt, value } if !lhs => { - let (pointer, ptr_meta) = self.lower_expect_inner(stmt, parser, tgt, true, body)?; + HirExprKind::Assign { tgt, value } if ExprPos::Lhs != pos => { + let (pointer, ptr_meta) = + self.lower_expect_inner(stmt, parser, tgt, ExprPos::Lhs, body)?; let (mut value, value_meta) = - self.lower_expect_inner(stmt, parser, value, false, body)?; + self.lower_expect_inner(stmt, parser, value, ExprPos::Rhs, body)?; let scalar_components = self.expr_scalar_components(parser, pointer, ptr_meta)?; @@ -686,7 +711,9 @@ impl Context { false => BinaryOperator::Subtract, }; - let pointer = self.lower_expect_inner(stmt, parser, expr, true, body)?.0; + let pointer = self + .lower_expect_inner(stmt, parser, expr, ExprPos::Lhs, body)? + .0; let left = self.add_expression(Expression::Load { pointer }, meta, body); let uint = match parser.resolve_type(self, left, meta)?.scalar_kind() { diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 28190699a..0b014aad3 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,7 +1,7 @@ use super::{ ast::*, builtins::{inject_builtin, inject_double_builtin, sampled_to_depth}, - context::{Context, StmtContext}, + context::{Context, ExprPos, StmtContext}, error::{Error, ErrorKind}, types::scalar_components, Parser, Result, SourceMetadata, @@ -48,7 +48,7 @@ impl Parser { ) -> Result>> { let args: Vec<_> = raw_args .iter() - .map(|e| ctx.lower_expect_inner(stmt, self, *e, false, body)) + .map(|e| ctx.lower_expect_inner(stmt, self, *e, ExprPos::Rhs, body)) .collect::>()?; match fc { @@ -565,7 +565,7 @@ impl Parser { .zip(raw_args.iter().zip(parameters.iter())) { let (mut handle, meta) = - ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.is_lhs(), body)?; + ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.as_pos(), body)?; if let TypeInner::Vector { size, kind, width } = *self.resolve_type(ctx, handle, meta)? @@ -638,7 +638,9 @@ impl Parser { ctx.emit_start(); for (tgt, pointer) in proxy_writes { let value = ctx.add_expression(Expression::Load { pointer }, meta, body); - let target = ctx.lower_expect_inner(stmt, self, tgt, true, body)?.0; + let target = ctx + .lower_expect_inner(stmt, self, tgt, ExprPos::Rhs, body)? + .0; ctx.emit_flush(body); body.push( diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index b30c9b65c..d0e14b004 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,6 +1,6 @@ use super::{ ast::{FunctionKind, Profile, TypeQualifier}, - context::Context, + context::{Context, ExprPos}, error::ExpectedToken, error::{Error, ErrorKind}, lex::{Lexer, LexerResultKind}, @@ -199,7 +199,7 @@ impl<'source> ParsingContext<'source> { let mut stmt_ctx = ctx.stmt_ctx(); let expr = self.parse_conditional(parser, &mut ctx, &mut stmt_ctx, &mut block, None)?; - let (root, meta) = ctx.lower_expect(stmt_ctx, parser, expr, false, &mut block)?; + let (root, meta) = ctx.lower_expect(stmt_ctx, parser, expr, ExprPos::Rhs, &mut block)?; Ok((parser.solve_constant(&ctx, root, meta)?, meta)) } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 806e98e35..546c366a2 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -4,7 +4,7 @@ use crate::{ GlobalLookup, GlobalLookupKind, Precision, StorageQualifier, StructLayout, TypeQualifier, }, - context::Context, + context::{Context, ExprPos}, error::ExpectedToken, offset, token::{Token, TokenValue}, @@ -103,7 +103,7 @@ impl<'source> ParsingContext<'source> { } else { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_assignment(parser, ctx, &mut stmt, body)?; - let (mut init, init_meta) = ctx.lower_expect(stmt, parser, expr, false, body)?; + let (mut init, init_meta) = ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; let scalar_components = scalar_components(&parser.module.types[ty].inner); if let Some((kind, width)) = scalar_components { diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index c91e6aeb2..e1b41b1bc 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -1,3 +1,4 @@ +use crate::front::glsl::context::ExprPos; use crate::front::glsl::SourceMetadata; use crate::{ front::glsl::{ @@ -77,7 +78,8 @@ impl<'source> ParsingContext<'source> { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; self.expect(parser, TokenValue::Semicolon)?; - let (handle, meta) = ctx.lower_expect(stmt, parser, expr, false, body)?; + let (handle, meta) = + ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; (Some(handle), meta) } }; @@ -99,7 +101,8 @@ impl<'source> ParsingContext<'source> { let condition = { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - let (handle, more_meta) = ctx.lower_expect(stmt, parser, expr, false, body)?; + let (handle, more_meta) = + ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; meta = meta.union(&more_meta); handle }; @@ -139,7 +142,7 @@ impl<'source> ParsingContext<'source> { let selector = { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower_expect(stmt, parser, expr, false, body)?.0 + ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?.0 }; self.expect(parser, TokenValue::RightParen)?; @@ -158,7 +161,7 @@ impl<'source> ParsingContext<'source> { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; let (root, meta) = - ctx.lower_expect(stmt, parser, expr, false, body)?; + ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; let constant = parser.solve_constant(ctx, root, meta)?; match parser.module.constants[constant].inner { @@ -287,7 +290,7 @@ impl<'source> ParsingContext<'source> { let meta = meta.union(&self.expect(parser, TokenValue::RightParen)?.meta); let (expr, expr_meta) = - ctx.lower_expect(stmt, parser, root, false, &mut loop_body)?; + ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -340,7 +343,7 @@ impl<'source> ParsingContext<'source> { let meta = start_meta.union(&end_meta); let (expr, expr_meta) = - ctx.lower_expect(stmt, parser, root, false, &mut loop_body)?; + ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -383,7 +386,7 @@ impl<'source> ParsingContext<'source> { } else { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower(stmt, parser, expr, false, body)?; + ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?; self.expect(parser, TokenValue::Semicolon)?; } } @@ -422,7 +425,7 @@ impl<'source> ParsingContext<'source> { } else { let mut stmt = ctx.stmt_ctx(); let root = self.parse_expression(parser, ctx, &mut stmt, &mut block)?; - ctx.lower_expect(stmt, parser, root, false, &mut block)? + ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut block)? }; let condition = ctx.add_expression( @@ -455,7 +458,7 @@ impl<'source> ParsingContext<'source> { let mut stmt = ctx.stmt_ctx(); let rest = self.parse_expression(parser, ctx, &mut stmt, &mut continuing)?; - ctx.lower(stmt, parser, rest, false, &mut continuing)?; + ctx.lower(stmt, parser, rest, ExprPos::Rhs, &mut continuing)?; } } @@ -504,7 +507,7 @@ impl<'source> ParsingContext<'source> { | TokenValue::FloatConstant(_) => { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower(stmt, parser, expr, false, body)?; + ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?; self.expect(parser, TokenValue::Semicolon)?.meta } TokenValue::Semicolon => self.bump(parser)?.meta, diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 717737bc5..58d4a7e71 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -812,4 +812,19 @@ fn expressions() { "#, ) .unwrap(); + + // Dynamic indexing of array + parser + .parse( + &Options::from(ShaderStage::Vertex), + r#" + # version 450 + void main() { + const vec4 positions[1] = { vec4(0) }; + + gl_Position = positions[gl_VertexIndex]; + } + "#, + ) + .unwrap(); } From 2b08525ed12559381bf51ded31882a42d0e2fe06 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 19 Aug 2021 11:07:42 -0700 Subject: [PATCH 1254/2212] [spv-out] Request Sample1D capability when texture_1d is used. Fixes #1241. --- src/back/spv/writer.rs | 7 ++++++- tests/out/spv/image.spvasm | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index ce7e6c068..a53dc9cf6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -703,7 +703,12 @@ impl Writer { class, } => { let kind = match class { - crate::ImageClass::Sampled { kind, multi: _ } => kind, + crate::ImageClass::Sampled { kind, multi: _ } => { + if dim == crate::ImageDimension::D1 { + self.check(&[spirv::Capability::Sampled1D])?; + } + kind + } crate::ImageClass::Depth { multi: _ } => crate::ScalarKind::Float, crate::ImageClass::Storage { format, .. } => { let required_caps: &[_] = match dim { diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 03a2cfc30..299dc344a 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -2,9 +2,10 @@ ; Version: 1.1 ; Generator: rspirv ; Bound: 213 +OpCapability ImageQuery OpCapability Image1D OpCapability Shader -OpCapability ImageQuery +OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %67 "main" %64 From a741e4b86dffb6839b5bdbec02c218e97987f3c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 19 Aug 2021 22:43:17 +0100 Subject: [PATCH 1255/2212] [glsl-in] parse shared qualifier --- src/front/glsl/lex.rs | 1 + src/front/glsl/parser/types.rs | 4 ++++ src/front/glsl/token.rs | 1 + 3 files changed, 6 insertions(+) diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index e054217a7..3400e0626 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -71,6 +71,7 @@ impl<'a> Iterator for Lexer<'a> { "out" => TokenValue::Out, "uniform" => TokenValue::Uniform, "buffer" => TokenValue::Buffer, + "shared" => TokenValue::Shared, "flat" => TokenValue::Interpolation(crate::Interpolation::Flat), "noperspective" => TokenValue::Interpolation(crate::Interpolation::Linear), "smooth" => TokenValue::Interpolation(crate::Interpolation::Perspective), diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 0d1e0441f..dcde9bacb 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -120,6 +120,7 @@ impl<'source> ParsingContext<'source> { | TokenValue::In | TokenValue::Out | TokenValue::Uniform + | TokenValue::Shared | TokenValue::Buffer | TokenValue::Restrict | TokenValue::StorageAccess(_) @@ -152,6 +153,9 @@ impl<'source> ParsingContext<'source> { TokenValue::Uniform => TypeQualifier::StorageQualifier( StorageQualifier::StorageClass(StorageClass::Uniform), ), + TokenValue::Shared => TypeQualifier::StorageQualifier( + StorageQualifier::StorageClass(StorageClass::WorkGroup), + ), TokenValue::Buffer => TypeQualifier::StorageQualifier( StorageQualifier::StorageClass(StorageClass::Storage { access: crate::StorageAccess::default(), diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 0aa6a6d70..230362794 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -106,6 +106,7 @@ pub enum TokenValue { Uniform, Buffer, Const, + Shared, Restrict, StorageAccess(crate::StorageAccess), From 0dd32219c5491d16fe1b966419f545a1bc13a7bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 19 Aug 2021 22:22:41 +0100 Subject: [PATCH 1256/2212] [glsl-in] Cast grad sampling on shadow image into zero sampling --- src/front/glsl/builtins.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 19fb38949..3ac9021e7 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -342,7 +342,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module declaration .overloads - .push(module.add_builtin(args, MacroCall::TextureGrad)) + .push(module.add_builtin(args, MacroCall::TextureGrad(shadow))) } } "textureSize" => { @@ -1351,7 +1351,7 @@ pub enum MacroCall { Texture, TextureLod, TextureProj, - TextureGrad, + TextureGrad(bool), TextureSize, TexelFetch, MathFunction(MathFunction), @@ -1385,7 +1385,7 @@ impl MacroCall { ctx.samplers.insert(args[0], args[1]); Ok(args[0]) } - MacroCall::Texture | MacroCall::TextureLod | MacroCall::TextureGrad => { + MacroCall::Texture | MacroCall::TextureLod => { let comps = parser.coordinate_components(ctx, args[0], args[1], meta, body)?; let level = match *self { MacroCall::Texture => args @@ -1393,11 +1393,25 @@ impl MacroCall { .copied() .map_or(SampleLevel::Auto, SampleLevel::Bias), MacroCall::TextureLod => SampleLevel::Exact(args[2]), - MacroCall::TextureGrad => SampleLevel::Gradient { + _ => unreachable!(), + }; + texture_call(ctx, args[0], level, comps, body, meta) + } + MacroCall::TextureGrad(shadow) => { + let comps = parser.coordinate_components(ctx, args[0], args[1], meta, body)?; + let level = match shadow { + true => { + log::debug!( + "Assuming gradients {:?} and {:?} are not greater than 1", + args[2], + args[3] + ); + SampleLevel::Zero + } + false => SampleLevel::Gradient { x: args[2], y: args[3], }, - _ => unreachable!(), }; texture_call(ctx, args[0], level, comps, body, meta) } From 448ea65940354e9eea27bb8942886e47e117aacd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 19 Aug 2021 23:49:25 +0100 Subject: [PATCH 1257/2212] [glsl-in] Add support for more builtins Fixes #1245 --- src/front/glsl/variables.rs | 290 +++++++++++++++++++++--------------- 1 file changed, 171 insertions(+), 119 deletions(-) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 9c5957e7c..cff89959e 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -6,8 +6,8 @@ use super::{ }; use crate::{ Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, Interpolation, - LocalVariable, ResourceBinding, ScalarKind, StorageAccess, StorageClass, SwizzleComponent, - Type, TypeInner, VectorSize, + LocalVariable, ResourceBinding, ScalarKind, ShaderStage, StorageAccess, StorageClass, + SwizzleComponent, Type, TypeInner, VectorSize, }; macro_rules! qualifier_arm { @@ -31,12 +31,83 @@ pub struct VarDeclaration<'a> { pub meta: SourceMetadata, } +/// Information about a builtin used in [`add_builtin`](Parser::add_builtin) +struct BuiltInData { + /// The type of the builtin + inner: TypeInner, + /// The builtin class associated with + builtin: BuiltIn, + /// Wether it should be allowed to write to the builtin or not + mutable: bool, + /// The storage used for the builtin + storage: StorageQualifier, +} + pub enum GlobalOrConstant { Global(Handle), Constant(Handle), } impl Parser { + /// Adds a builtin and returns a variable reference to it + fn add_builtin( + &mut self, + ctx: &mut Context, + body: &mut Block, + name: &str, + data: BuiltInData, + meta: SourceMetadata, + ) -> Option { + let ty = self.module.types.fetch_or_append( + Type { + name: None, + inner: data.inner, + }, + meta.as_span(), + ); + + let handle = self.module.global_variables.append( + GlobalVariable { + name: Some(name.into()), + class: StorageClass::Private, + binding: None, + ty, + init: None, + }, + meta.as_span(), + ); + + let idx = self.entry_args.len(); + self.entry_args.push(EntryArg { + name: None, + binding: Binding::BuiltIn(data.builtin), + handle, + storage: data.storage, + }); + + self.global_variables.push(( + name.into(), + GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: Some(idx), + mutable: data.mutable, + }, + )); + + let expr = ctx.add_expression(Expression::GlobalVariable(handle), meta, body); + ctx.lookup_global_var_exps.insert( + name.into(), + VariableReference { + expr, + load: true, + mutable: data.mutable, + entry_arg: Some(idx), + }, + ); + + ctx.lookup_global_var(name) + } + pub(crate) fn lookup_variable( &mut self, ctx: &mut Context, @@ -51,141 +122,122 @@ impl Parser { return Some(global_var); } - let mut add_builtin = |inner, builtin, mutable, storage| { - let ty = self - .module - .types - .fetch_or_append(Type { name: None, inner }, meta.as_span()); - - let handle = self.module.global_variables.append( - GlobalVariable { - name: Some(name.into()), - class: StorageClass::Private, - binding: None, - ty, - init: None, - }, - meta.as_span(), - ); - - let idx = self.entry_args.len(); - self.entry_args.push(EntryArg { - name: None, - binding: Binding::BuiltIn(builtin), - handle, - storage, - }); - - self.global_variables.push(( - name.into(), - GlobalLookup { - kind: GlobalLookupKind::Variable(handle), - entry_arg: Some(idx), - mutable, - }, - )); - - let expr = ctx.add_expression(Expression::GlobalVariable(handle), meta, body); - ctx.lookup_global_var_exps.insert( - name.into(), - VariableReference { - expr, - load: true, - mutable, - entry_arg: Some(idx), - }, - ); - - ctx.lookup_global_var(name) - }; - match name { - "gl_Position" => add_builtin( - TypeInner::Vector { + let data = match name { + "gl_Position" => BuiltInData { + inner: TypeInner::Vector { size: VectorSize::Quad, kind: ScalarKind::Float, width: 4, }, - BuiltIn::Position, - true, - StorageQualifier::Output, - ), - "gl_FragCoord" => add_builtin( - TypeInner::Vector { + builtin: BuiltIn::Position, + mutable: true, + storage: StorageQualifier::Output, + }, + "gl_FragCoord" => BuiltInData { + inner: TypeInner::Vector { size: VectorSize::Quad, kind: ScalarKind::Float, width: 4, }, - BuiltIn::Position, - false, - StorageQualifier::Input, - ), - "gl_FragDepth" => add_builtin( - TypeInner::Scalar { - kind: ScalarKind::Float, - width: 4, - }, - BuiltIn::FragDepth, - true, - StorageQualifier::Output, - ), - "gl_VertexIndex" => add_builtin( - TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - BuiltIn::VertexIndex, - false, - StorageQualifier::Input, - ), - "gl_InstanceIndex" => add_builtin( - TypeInner::Scalar { - kind: ScalarKind::Uint, - width: 4, - }, - BuiltIn::InstanceIndex, - false, - StorageQualifier::Input, - ), - "gl_GlobalInvocationID" => add_builtin( - TypeInner::Vector { + builtin: BuiltIn::Position, + mutable: false, + storage: StorageQualifier::Input, + }, + "gl_GlobalInvocationID" + | "gl_NumWorkGroups" + | "gl_WorkGroupSize" + | "gl_WorkGroupID" + | "gl_LocalInvocationID" => BuiltInData { + inner: TypeInner::Vector { size: VectorSize::Tri, kind: ScalarKind::Uint, width: 4, }, - BuiltIn::GlobalInvocationId, - false, - StorageQualifier::Input, - ), - "gl_NumWorkGroups" => add_builtin( - TypeInner::Vector { - size: VectorSize::Tri, - kind: ScalarKind::Uint, - width: 4, + builtin: match name { + "gl_GlobalInvocationID" => BuiltIn::GlobalInvocationId, + "gl_NumWorkGroups" => BuiltIn::NumWorkGroups, + "gl_WorkGroupSize" => BuiltIn::WorkGroupSize, + "gl_WorkGroupID" => BuiltIn::WorkGroupId, + "gl_LocalInvocationID" => BuiltIn::LocalInvocationId, + _ => unreachable!(), }, - BuiltIn::NumWorkGroups, - false, - StorageQualifier::Input, - ), - "gl_FrontFacing" => add_builtin( - TypeInner::Scalar { + mutable: false, + storage: StorageQualifier::Input, + }, + "gl_FrontFacing" => BuiltInData { + inner: TypeInner::Scalar { kind: ScalarKind::Bool, width: crate::BOOL_WIDTH, }, - BuiltIn::FrontFacing, - false, - StorageQualifier::Input, - ), - "gl_PrimitiveID" => add_builtin( - TypeInner::Scalar { - kind: ScalarKind::Uint, + builtin: BuiltIn::FrontFacing, + mutable: false, + storage: StorageQualifier::Input, + }, + "gl_PointSize" | "gl_FragDepth" => BuiltInData { + inner: TypeInner::Scalar { + kind: ScalarKind::Float, width: 4, }, - BuiltIn::PrimitiveIndex, - false, - StorageQualifier::Input, - ), - _ => None, - } + builtin: match name { + "gl_PointSize" => BuiltIn::PointSize, + "gl_FragDepth" => BuiltIn::FragDepth, + _ => unreachable!(), + }, + mutable: true, + storage: StorageQualifier::Output, + }, + "gl_ClipDistance" | "gl_CullDistance" => { + let base = self.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 4, + }, + }, + meta.as_span(), + ); + + BuiltInData { + inner: TypeInner::Array { + base, + size: crate::ArraySize::Dynamic, + stride: 4, + }, + builtin: match name { + "gl_ClipDistance" => BuiltIn::PointSize, + "gl_CullDistance" => BuiltIn::FragDepth, + _ => unreachable!(), + }, + mutable: self.meta.stage == ShaderStage::Vertex, + storage: StorageQualifier::Output, + } + } + _ => { + let builtin = match name { + "gl_BaseVertex" => BuiltIn::BaseVertex, + "gl_BaseInstance" => BuiltIn::BaseInstance, + "gl_PrimitiveID" => BuiltIn::PrimitiveIndex, + "gl_InstanceIndex" => BuiltIn::InstanceIndex, + "gl_VertexIndex" => BuiltIn::VertexIndex, + "gl_SampleID" => BuiltIn::SampleIndex, + "gl_LocalInvocationIndex" => BuiltIn::LocalInvocationIndex, + _ => return None, + }; + + BuiltInData { + inner: TypeInner::Scalar { + kind: ScalarKind::Uint, + width: 4, + }, + builtin, + mutable: false, + storage: StorageQualifier::Input, + } + } + }; + + self.add_builtin(ctx, body, name, data, meta) } pub(crate) fn field_selection( From 0b0d2ab0f3dedd111fe129d68f2cae6d6c435f06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 20 Aug 2021 01:10:47 +0100 Subject: [PATCH 1258/2212] [glsl-in] Use power of two alignment for bad type in struct Fixes #1243 --- src/front/glsl/offset.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index cb3f0b75d..9b9f7957d 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -162,7 +162,7 @@ pub fn calculate_offset( kind: ErrorKind::SemanticError("Invalid struct member type".into()), meta, }); - (0, 0) + (1, 0) } }; From 846ea0ec0920498cbec9512806a23eccdfa6491b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 20 Aug 2021 01:30:51 +0100 Subject: [PATCH 1259/2212] [glsl-in] Align child structs --- src/front/glsl/offset.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 9b9f7957d..2c2140b93 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -142,6 +142,8 @@ pub fn calculate_offset( span += info.span; } + span = align_up(span, align); + let ty_span = types.get_span(ty).clone(); ty = types.fetch_or_append( Type { From 8d6647d369b1d982b645ee729412ddae98053217 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 20 Aug 2021 16:34:04 +0100 Subject: [PATCH 1260/2212] [glsl-in] Add support for radians and degrees builtins --- src/front/glsl/builtins.rs | 68 +++++++++++++++++++++++++++----------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 3ac9021e7..e7e995674 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -4,9 +4,9 @@ use super::{ Error, ErrorKind, Parser, Result, SourceMetadata, }; use crate::{ - BinaryOperator, Block, Expression, Handle, ImageClass, ImageDimension, ImageQuery, - MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind as Sk, Span, Type, TypeInner, - VectorSize, + BinaryOperator, Block, Constant, ConstantInner, Expression, Handle, ImageClass, ImageDimension, + ImageQuery, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind as Sk, + ScalarValue, Span, Type, TypeInner, VectorSize, }; impl Module { @@ -451,7 +451,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module } } "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" - | "log" | "log2" => { + | "log" | "log2" | "radians" | "degrees" => { // bits layout // bit 0 trough 1 - dims for bits in 0..(0b100) { @@ -468,21 +468,23 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module Some(size) => TypeInner::Vector { size, kind, width }, None => TypeInner::Scalar { kind, width }, }], - MacroCall::MathFunction(match name { - "sin" => MathFunction::Sin, - "exp" => MathFunction::Exp, - "exp2" => MathFunction::Exp2, - "sinh" => MathFunction::Sinh, - "cos" => MathFunction::Cos, - "cosh" => MathFunction::Cosh, - "tan" => MathFunction::Tan, - "tanh" => MathFunction::Tanh, - "acos" => MathFunction::Acos, - "asin" => MathFunction::Asin, - "log" => MathFunction::Log, - "log2" => MathFunction::Log2, + match name { + "sin" => MacroCall::MathFunction(MathFunction::Sin), + "exp" => MacroCall::MathFunction(MathFunction::Exp), + "exp2" => MacroCall::MathFunction(MathFunction::Exp2), + "sinh" => MacroCall::MathFunction(MathFunction::Sinh), + "cos" => MacroCall::MathFunction(MathFunction::Cos), + "cosh" => MacroCall::MathFunction(MathFunction::Cosh), + "tan" => MacroCall::MathFunction(MathFunction::Tan), + "tanh" => MacroCall::MathFunction(MathFunction::Tanh), + "acos" => MacroCall::MathFunction(MathFunction::Acos), + "asin" => MacroCall::MathFunction(MathFunction::Asin), + "log" => MacroCall::MathFunction(MathFunction::Log), + "log2" => MacroCall::MathFunction(MathFunction::Log2), + "radians" => MacroCall::ConstMultiply(std::f64::consts::PI / 180.0), + "degrees" => MacroCall::ConstMultiply(180.0 / std::f64::consts::PI), _ => unreachable!(), - }), + }, )) } } @@ -1344,7 +1346,7 @@ fn inject_common_builtin( } /// A compiler defined builtin function -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq)] pub enum MacroCall { Sampler, SamplerShadow, @@ -1361,6 +1363,7 @@ pub enum MacroCall { Splatted(MathFunction, Option, usize), MixBoolean, Clamp(Option), + ConstMultiply(f64), } impl MacroCall { @@ -1569,6 +1572,33 @@ impl MacroCall { body, )) } + MacroCall::ConstMultiply(value) => { + let constant = parser.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(value), + }, + }, + Span::Unknown, + ); + let right = ctx.add_expression( + Expression::Constant(constant), + SourceMetadata::none(), + body, + ); + Ok(ctx.add_expression( + Expression::Binary { + op: BinaryOperator::Multiply, + left: args[0], + right, + }, + SourceMetadata::none(), + body, + )) + } } } } From 9050108a95d7a6cab6d2c4127e7b6817a15ed4e1 Mon Sep 17 00:00:00 2001 From: sigaloid <69441971+sigaloid@users.noreply.github.com> Date: Fri, 20 Aug 2021 14:17:05 -0400 Subject: [PATCH 1261/2212] Fix some clippy suggestions --- src/back/msl/writer.rs | 4 ++-- src/back/spv/layout.rs | 6 ++---- src/valid/analyzer.rs | 2 +- tests/snapshots.rs | 15 +++++++-------- 4 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 6c95750e3..a15a4d207 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2621,7 +2621,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 18304 - if stack_size < 15000 || stack_size > 20000 { + if !(15000..=20000).contains(&stack_size) { panic!("`put_expression` stack size {} has changed!", stack_size); } } @@ -2636,7 +2636,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 17504 - if stack_size < 13000 || stack_size > 19000 { + if !(13000..=19000).contains(&stack_size) { panic!("`put_block` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index 492ec0f74..95d154cd7 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -135,10 +135,8 @@ impl Instruction { inst_index += 1; } - let mut op_index = 0; - for i in inst_index..wc as usize { + for (op_index, i) in (inst_index..wc as usize).enumerate() { assert_eq!(words[i], self.operands[op_index]); - op_index += 1; } } } @@ -178,7 +176,7 @@ fn test_logical_layout_in_words() { "Function Definitions", ]; - for i in 0..layout_vectors { + for (i, _) in vector_names.iter().enumerate().take(layout_vectors) { let mut dummy_instruction = Instruction::new(Op::Constant); dummy_instruction.set_type((i + 1) as u32); dummy_instruction.set_result((i + 2) as u32); diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index c70244272..dc9e29166 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -992,7 +992,7 @@ fn uniform_control_flow() { let stmt_if_non_uniform = S::If { condition: non_uniform_global_expr, accept: vec![ - S::Emit(emit_range_constant_derivative.clone()), + S::Emit(emit_range_constant_derivative), S::Store { pointer: constant_expr, value: derivative_expr, diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 191ef8b62..e5c9c3e76 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -1,7 +1,7 @@ //TODO: move this to a binary target once Rust supports // binary-specific dependencies. -use std::{fs, path::PathBuf}; +use std::{fs, path::Path, path::PathBuf}; const BASE_DIR_IN: &str = "tests/in"; const BASE_DIR_OUT: &str = "tests/out"; @@ -143,7 +143,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { fn write_output_spv( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, params: &Parameters, ) { @@ -172,7 +172,6 @@ fn write_output_spv( } else { naga::back::IndexBoundsCheckPolicy::UndefinedBehavior }, - ..spv::Options::default() }; let spv = spv::write_vec(module, info, &options).unwrap(); @@ -188,7 +187,7 @@ fn write_output_spv( fn write_output_msl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, params: &Parameters, ) { @@ -225,7 +224,7 @@ fn write_output_msl( fn write_output_glsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, stage: naga::ShaderStage, ep_name: &str, @@ -252,7 +251,7 @@ fn write_output_glsl( let mut buffer = String::new(); let mut writer = - glsl::Writer::new(&mut buffer, module, info, &options, &pipeline_options).unwrap(); + glsl::Writer::new(&mut buffer, module, info, options, &pipeline_options).unwrap(); writer.write().unwrap(); fs::write( @@ -266,7 +265,7 @@ fn write_output_glsl( fn write_output_hlsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, params: &Parameters, ) { @@ -355,7 +354,7 @@ fn write_output_hlsl( fn write_output_wgsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, ) { use naga::back::wgsl; From 644fa684bad4afa121bbc21c7ae26daba5ddd258 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 20 Aug 2021 16:56:14 -0400 Subject: [PATCH 1262/2212] Fix quad testcase parameters --- tests/in/quad.param.ron | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index aca1da9b9..bb22a33e0 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -2,6 +2,7 @@ spv_version: (1, 0), spv_debug: true, spv_adjust_coordinate_space: true, + glsl_custom: true, glsl: ( version: Embedded(300), writer_flags: (bits: 0), From bbf3e465f3669507fac271f1481e8292d3abac2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 20 Aug 2021 17:11:55 +0100 Subject: [PATCH 1263/2212] Add support for inverse hyperbolic trignometric functions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hlsl and wgsl don't support them directly so a polyfill is used taken from the msl spec. `asinh` = `log(x + sqrt(x * x + 1.0))` `acosh` = `log(x + sqrt(x * x - 1.0))` `atanh` = `0.5 * log((1.0 + x) / (1.0 – x))` --- src/back/glsl/mod.rs | 3 + src/back/hlsl/writer.rs | 165 +++++++++------- src/back/msl/writer.rs | 3 + src/back/spv/block.rs | 3 + src/back/wgsl/writer.rs | 158 ++++++++------- src/front/glsl/builtins.rs | 5 +- src/front/spv/mod.rs | 3 + src/lib.rs | 3 + src/proc/mod.rs | 3 + src/proc/typifier.rs | 3 + src/valid/expression.rs | 3 + .../in/spv/inv-hyperbolic-trig-functions.spv | Bin 0 -> 480 bytes .../hlsl/inv-hyperbolic-trig-functions.hlsl | 22 +++ .../inv-hyperbolic-trig-functions.hlsl.config | 3 + .../out/ir/inv-hyperbolic-trig-functions.ron | 182 ++++++++++++++++++ .../wgsl/inv-hyperbolic-trig-functions.wgsl | 20 ++ tests/snapshots.rs | 10 + 17 files changed, 454 insertions(+), 135 deletions(-) create mode 100644 tests/in/spv/inv-hyperbolic-trig-functions.spv create mode 100644 tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl create mode 100644 tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config create mode 100644 tests/out/ir/inv-hyperbolic-trig-functions.ron create mode 100644 tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 0558c9096..fb3e1f47a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2242,6 +2242,9 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Acos => "acos", Mf::Asin => "asin", Mf::Atan => "atan", + Mf::Asinh => "asinh", + Mf::Acosh => "acosh", + Mf::Atanh => "atanh", // glsl doesn't have atan2 function // use two-argument variation of the atan function Mf::Atan2 => "atan", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 108d2b6c6..87dabd863 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1635,76 +1635,105 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } => { use crate::MathFunction as Mf; - let fun_name = match fun { - // comparison - Mf::Abs => "abs", - Mf::Min => "min", - Mf::Max => "max", - Mf::Clamp => "clamp", - // trigonometry - Mf::Cos => "cos", - Mf::Cosh => "cosh", - Mf::Sin => "sin", - Mf::Sinh => "sinh", - Mf::Tan => "tan", - Mf::Tanh => "tanh", - Mf::Acos => "acos", - Mf::Asin => "asin", - Mf::Atan => "atan", - Mf::Atan2 => "atan2", - // decomposition - Mf::Ceil => "ceil", - Mf::Floor => "floor", - Mf::Round => "round", - Mf::Fract => "frac", - Mf::Trunc => "trunc", - Mf::Modf => "modf", - Mf::Frexp => "frexp", - Mf::Ldexp => "ldexp", - // exponent - Mf::Exp => "exp", - Mf::Exp2 => "exp2", - Mf::Log => "log", - Mf::Log2 => "log2", - Mf::Pow => "pow", - // geometry - Mf::Dot => "dot", - //Mf::Outer => , - Mf::Cross => "cross", - Mf::Distance => "distance", - Mf::Length => "length", - Mf::Normalize => "normalize", - Mf::FaceForward => "faceforward", - Mf::Reflect => "reflect", - Mf::Refract => "refract", - // computational - Mf::Sign => "sign", - Mf::Fma => "fma", - Mf::Mix => "lerp", - Mf::Step => "step", - Mf::SmoothStep => "smoothstep", - Mf::Sqrt => "sqrt", - Mf::InverseSqrt => "rsqrt", - //Mf::Inverse =>, - Mf::Transpose => "transpose", - Mf::Determinant => "determinant", - // bits - Mf::CountOneBits => "countbits", - Mf::ReverseBits => "reversebits", - _ => return Err(Error::Unimplemented(format!("write_expr_math {:?}", fun))), - }; + match fun { + Mf::Asinh | Mf::Acosh => { + write!(self.out, "log(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " + sqrt(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " * ")?; + self.write_expr(module, arg, func_ctx)?; + if fun == Mf::Asinh { + write!(self.out, " + 1.0))")? + } else { + write!(self.out, " - 1.0))")? + } + } + Mf::Atanh => { + write!(self.out, "0.5 * log((1.0 + ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ") / (1.0 - ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))")?; + } + _ => { + let fun_name = match fun { + // comparison + Mf::Abs => "abs", + Mf::Min => "min", + Mf::Max => "max", + Mf::Clamp => "clamp", + // trigonometry + Mf::Cos => "cos", + Mf::Cosh => "cosh", + Mf::Sin => "sin", + Mf::Sinh => "sinh", + Mf::Tan => "tan", + Mf::Tanh => "tanh", + Mf::Acos => "acos", + Mf::Asin => "asin", + Mf::Atan => "atan", + Mf::Atan2 => "atan2", + // decomposition + Mf::Ceil => "ceil", + Mf::Floor => "floor", + Mf::Round => "round", + Mf::Fract => "frac", + Mf::Trunc => "trunc", + Mf::Modf => "modf", + Mf::Frexp => "frexp", + Mf::Ldexp => "ldexp", + // exponent + Mf::Exp => "exp", + Mf::Exp2 => "exp2", + Mf::Log => "log", + Mf::Log2 => "log2", + Mf::Pow => "pow", + // geometry + Mf::Dot => "dot", + //Mf::Outer => , + Mf::Cross => "cross", + Mf::Distance => "distance", + Mf::Length => "length", + Mf::Normalize => "normalize", + Mf::FaceForward => "faceforward", + Mf::Reflect => "reflect", + Mf::Refract => "refract", + // computational + Mf::Sign => "sign", + Mf::Fma => "fma", + Mf::Mix => "lerp", + Mf::Step => "step", + Mf::SmoothStep => "smoothstep", + Mf::Sqrt => "sqrt", + Mf::InverseSqrt => "rsqrt", + //Mf::Inverse =>, + Mf::Transpose => "transpose", + Mf::Determinant => "determinant", + // bits + Mf::CountOneBits => "countbits", + Mf::ReverseBits => "reversebits", + _ => { + return Err(Error::Unimplemented(format!( + "write_expr_math {:?}", + fun + ))) + } + }; - write!(self.out, "{}(", fun_name)?; - self.write_expr(module, arg, func_ctx)?; - if let Some(arg) = arg1 { - write!(self.out, ", ")?; - self.write_expr(module, arg, func_ctx)?; + write!(self.out, "{}(", fun_name)?; + self.write_expr(module, arg, func_ctx)?; + if let Some(arg) = arg1 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } + if let Some(arg) = arg2 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } + write!(self.out, ")")? + } } - if let Some(arg) = arg2 { - write!(self.out, ", ")?; - self.write_expr(module, arg, func_ctx)?; - } - write!(self.out, ")")? } Expression::Swizzle { size, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a15a4d207..0d1fbd36b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1140,6 +1140,9 @@ impl Writer { Mf::Asin => "asin", Mf::Atan => "atan", Mf::Atan2 => "atan2", + Mf::Asinh => "asinh", + Mf::Acosh => "acosh", + Mf::Atanh => "atanh", // decomposition Mf::Ceil => "ceil", Mf::Floor => "floor", diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 41b37373e..19450c02f 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -558,6 +558,9 @@ impl<'w> BlockContext<'w> { Mf::Tanh => MathOp::Ext(spirv::GLOp::Tanh), Mf::Atan => MathOp::Ext(spirv::GLOp::Atan), Mf::Atan2 => MathOp::Ext(spirv::GLOp::Atan2), + Mf::Asinh => MathOp::Ext(spirv::GLOp::Asinh), + Mf::Acosh => MathOp::Ext(spirv::GLOp::Acosh), + Mf::Atanh => MathOp::Ext(spirv::GLOp::Atanh), // decomposition Mf::Ceil => MathOp::Ext(spirv::GLOp::Ceil), Mf::Round => MathOp::Ext(spirv::GLOp::Round), diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index b101b745d..2dfc72e80 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1240,75 +1240,101 @@ impl Writer { } => { use crate::MathFunction as Mf; - let fun_name = match fun { - Mf::Abs => "abs", - Mf::Min => "min", - Mf::Max => "max", - Mf::Clamp => "clamp", - // trigonometry - Mf::Cos => "cos", - Mf::Cosh => "cosh", - Mf::Sin => "sin", - Mf::Sinh => "sinh", - Mf::Tan => "tan", - Mf::Tanh => "tanh", - Mf::Acos => "acos", - Mf::Asin => "asin", - Mf::Atan => "atan", - Mf::Atan2 => "atan2", - // decomposition - Mf::Ceil => "ceil", - Mf::Floor => "floor", - Mf::Round => "round", - Mf::Fract => "fract", - Mf::Trunc => "trunc", - Mf::Modf => "modf", - Mf::Frexp => "frexp", - Mf::Ldexp => "ldexp", - // exponent - Mf::Exp => "exp", - Mf::Exp2 => "exp2", - Mf::Log => "log", - Mf::Log2 => "log2", - Mf::Pow => "pow", - // geometry - Mf::Dot => "dot", - Mf::Outer => "outerProduct", - Mf::Cross => "cross", - Mf::Distance => "distance", - Mf::Length => "length", - Mf::Normalize => "normalize", - Mf::FaceForward => "faceForward", - Mf::Reflect => "reflect", - // computational - Mf::Sign => "sign", - Mf::Fma => "fma", - Mf::Mix => "mix", - Mf::Step => "step", - Mf::SmoothStep => "smoothStep", - Mf::Sqrt => "sqrt", - Mf::InverseSqrt => "inverseSqrt", - Mf::Transpose => "transpose", - Mf::Determinant => "determinant", - // bits - Mf::CountOneBits => "countOneBits", - Mf::ReverseBits => "reverseBits", - _ => { - return Err(Error::UnsupportedMathFunction(fun)); + // NOTE: If https://github.com/gpuweb/gpuweb/issues/1622 ever is + // accepted, replace this with the builtin functions + match fun { + Mf::Asinh | Mf::Acosh => { + write!(self.out, "log(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " + sqrt(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " * ")?; + self.write_expr(module, arg, func_ctx)?; + if fun == Mf::Asinh { + write!(self.out, " + 1.0))")? + } else { + write!(self.out, " - 1.0))")? + } } - }; + Mf::Atanh => { + write!(self.out, "0.5 * log((1.0 + ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ") / (1.0 - ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))")?; + } + _ => { + let fun_name = match fun { + Mf::Abs => "abs", + Mf::Min => "min", + Mf::Max => "max", + Mf::Clamp => "clamp", + // trigonometry + Mf::Cos => "cos", + Mf::Cosh => "cosh", + Mf::Sin => "sin", + Mf::Sinh => "sinh", + Mf::Tan => "tan", + Mf::Tanh => "tanh", + Mf::Acos => "acos", + Mf::Asin => "asin", + Mf::Atan => "atan", + Mf::Atan2 => "atan2", + // decomposition + Mf::Ceil => "ceil", + Mf::Floor => "floor", + Mf::Round => "round", + Mf::Fract => "fract", + Mf::Trunc => "trunc", + Mf::Modf => "modf", + Mf::Frexp => "frexp", + Mf::Ldexp => "ldexp", + // exponent + Mf::Exp => "exp", + Mf::Exp2 => "exp2", + Mf::Log => "log", + Mf::Log2 => "log2", + Mf::Pow => "pow", + // geometry + Mf::Dot => "dot", + Mf::Outer => "outerProduct", + Mf::Cross => "cross", + Mf::Distance => "distance", + Mf::Length => "length", + Mf::Normalize => "normalize", + Mf::FaceForward => "faceForward", + Mf::Reflect => "reflect", + // computational + Mf::Sign => "sign", + Mf::Fma => "fma", + Mf::Mix => "mix", + Mf::Step => "step", + Mf::SmoothStep => "smoothStep", + Mf::Sqrt => "sqrt", + Mf::InverseSqrt => "inverseSqrt", + Mf::Transpose => "transpose", + Mf::Determinant => "determinant", + // bits + Mf::CountOneBits => "countOneBits", + Mf::ReverseBits => "reverseBits", + _ => { + return Err(Error::UnsupportedMathFunction(fun)); + } + }; - write!(self.out, "{}(", fun_name)?; - self.write_expr(module, arg, func_ctx)?; - if let Some(arg) = arg1 { - write!(self.out, ", ")?; - self.write_expr(module, arg, func_ctx)?; + write!(self.out, "{}(", fun_name)?; + self.write_expr(module, arg, func_ctx)?; + if let Some(arg) = arg1 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } + if let Some(arg) = arg2 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } + write!(self.out, ")")? + } } - if let Some(arg) = arg2 { - write!(self.out, ", ")?; - self.write_expr(module, arg, func_ctx)?; - } - write!(self.out, ")")? } Expression::Swizzle { size, diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index e7e995674..4af2c7de4 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -451,7 +451,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module } } "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" - | "log" | "log2" | "radians" | "degrees" => { + | "log" | "log2" | "radians" | "degrees" | "asinh" | "acosh" | "atanh" => { // bits layout // bit 0 trough 1 - dims for bits in 0..(0b100) { @@ -481,6 +481,9 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module "asin" => MacroCall::MathFunction(MathFunction::Asin), "log" => MacroCall::MathFunction(MathFunction::Log), "log2" => MacroCall::MathFunction(MathFunction::Log2), + "asinh" => MacroCall::MathFunction(MathFunction::Asinh), + "acosh" => MacroCall::MathFunction(MathFunction::Acosh), + "atanh" => MacroCall::MathFunction(MathFunction::Atanh), "radians" => MacroCall::ConstMultiply(std::f64::consts::PI / 180.0), "degrees" => MacroCall::ConstMultiply(180.0 / std::f64::consts::PI), _ => unreachable!(), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 2dd40ea56..ce7080873 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1984,6 +1984,9 @@ impl> Parser { Glo::Cosh => Mf::Cosh, Glo::Tanh => Mf::Tanh, Glo::Atan2 => Mf::Atan2, + Glo::Asinh => Mf::Asinh, + Glo::Acosh => Mf::Acosh, + Glo::Atanh => Mf::Atanh, Glo::Pow => Mf::Pow, Glo::Exp => Mf::Exp, Glo::Log => Mf::Log, diff --git a/src/lib.rs b/src/lib.rs index f3904eb09..d5167f372 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -802,6 +802,9 @@ pub enum MathFunction { Asin, Atan, Atan2, + Asinh, + Acosh, + Atanh, // decomposition Ceil, Floor, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 7919c4267..867782ffe 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -151,6 +151,9 @@ impl super::MathFunction { Self::Asin => 1, Self::Atan => 1, Self::Atan2 => 2, + Self::Asinh => 1, + Self::Acosh => 1, + Self::Atanh => 1, // decomposition Self::Ceil => 1, Self::Floor => 1, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index afd4d73bf..e5635f901 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -554,6 +554,9 @@ impl<'a> ResolveContext<'a> { Mf::Asin | Mf::Atan | Mf::Atan2 | + Mf::Asinh | + Mf::Acosh | + Mf::Atanh | // decomposition Mf::Ceil | Mf::Floor | diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 2324fb518..e3e189453 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -931,6 +931,9 @@ impl super::Validator { | Mf::Acos | Mf::Asin | Mf::Atan + | Mf::Asinh + | Mf::Acosh + | Mf::Atanh | Mf::Ceil | Mf::Floor | Mf::Round diff --git a/tests/in/spv/inv-hyperbolic-trig-functions.spv b/tests/in/spv/inv-hyperbolic-trig-functions.spv new file mode 100644 index 0000000000000000000000000000000000000000..a87d8deec536a7f8691a77be664e6f194e751217 GIT binary patch literal 480 zcmYk2yG{a86h)8oKwdID612qF6ACpXMp_#>zJNzVp^bi_Uqxf$S{EkFz1eg2KJPnu z_H-L@6WwUXB+h3P8J>t@Nvr z6x?g9B-TdnfV_*{Uick$f8j&y0Ziy*ugBCi5}(3b_+|-3@PLG~uZRv>F5Z}~c8>a$ zsrGXxk1sjl@fGIU%l)*qcCV&(H}yOD_Ur-s_fhIT@ZU^yuIjl1dpBeDelFpUxV literal 0 HcmV?d00001 diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl new file mode 100644 index 000000000..5857257ff --- /dev/null +++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl @@ -0,0 +1,22 @@ + +static float a = (float)0; + +void main1() +{ + float b = (float)0; + float c = (float)0; + float d = (float)0; + + float _expr8 = a; + b = log(_expr8 + sqrt(_expr8 * _expr8 + 1.0)); + float _expr10 = a; + c = log(_expr10 + sqrt(_expr10 * _expr10 - 1.0)); + float _expr12 = a; + d = 0.5 * log((1.0 + _expr12) / (1.0 - _expr12)); + return; +} + +void main() +{ + main1(); +} diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config new file mode 100644 index 000000000..f72fafd91 --- /dev/null +++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config @@ -0,0 +1,3 @@ +vertex=(main:vs_5_1 ) +fragment=() +compute=() diff --git a/tests/out/ir/inv-hyperbolic-trig-functions.ron b/tests/out/ir/inv-hyperbolic-trig-functions.ron new file mode 100644 index 000000000..bdf53ea71 --- /dev/null +++ b/tests/out/ir/inv-hyperbolic-trig-functions.ron @@ -0,0 +1,182 @@ +( + types: [ + ( + name: None, + inner: Scalar( + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Function, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + class: Private, + ), + ), + ], + constants: [ + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(3), + ), + ), + ], + global_variables: [ + ( + name: Some("a"), + class: Private, + binding: None, + ty: 1, + init: None, + ), + ], + functions: [ + ( + name: Some("main"), + arguments: [], + result: None, + local_variables: [ + ( + name: Some("b"), + ty: 1, + init: None, + ), + ( + name: Some("c"), + ty: 1, + init: None, + ), + ( + name: Some("d"), + ty: 1, + init: None, + ), + ], + expressions: [ + GlobalVariable(1), + Constant(1), + Constant(2), + Constant(3), + Constant(4), + LocalVariable(1), + LocalVariable(2), + LocalVariable(3), + Load( + pointer: 1, + ), + Math( + fun: Asinh, + arg: 9, + arg1: None, + arg2: None, + ), + Load( + pointer: 1, + ), + Math( + fun: Acosh, + arg: 11, + arg1: None, + arg2: None, + ), + Load( + pointer: 1, + ), + Math( + fun: Atanh, + arg: 13, + arg1: None, + arg2: None, + ), + ], + named_expressions: {}, + body: [ + Emit(( + start: 8, + end: 10, + )), + Store( + pointer: 6, + value: 10, + ), + Emit(( + start: 10, + end: 12, + )), + Store( + pointer: 7, + value: 12, + ), + Emit(( + start: 12, + end: 14, + )), + Store( + pointer: 8, + value: 14, + ), + Return( + value: None, + ), + ], + ), + ], + entry_points: [ + ( + name: "main", + stage: Vertex, + early_depth_test: None, + workgroup_size: (0, 0, 0), + function: ( + name: Some("main_wrap"), + arguments: [], + result: None, + local_variables: [], + expressions: [], + named_expressions: {}, + body: [ + Call( + function: 1, + arguments: [], + result: None, + ), + ], + ), + ), + ], +) \ No newline at end of file diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl new file mode 100644 index 000000000..7378cb300 --- /dev/null +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -0,0 +1,20 @@ +var a: f32; + +fn main1() { + var b: f32; + var c: f32; + var d: f32; + + let _e8: f32 = a; + b = log(_e8 + sqrt(_e8 * _e8 + 1.0)); + let _e10: f32 = a; + c = log(_e10 + sqrt(_e10 * _e10 - 1.0)); + let _e12: f32 = a; + d = 0.5 * log((1.0 + _e12) / (1.0 - _e12)); + return; +} + +[[stage(vertex)]] +fn main() { + main1(); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e5c9c3e76..e2a957e24 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -498,6 +498,16 @@ fn convert_spv_shadow() { convert_spv("shadow", true, Targets::IR | Targets::ANALYSIS); } +#[cfg(feature = "spv-in")] +#[test] +fn convert_spv_inverse_hyperbolic_trig_functions() { + convert_spv( + "inv-hyperbolic-trig-functions", + true, + Targets::HLSL | Targets::WGSL | Targets::IR, + ); +} + #[cfg(all(feature = "spv-in", feature = "spv-out"))] #[test] fn convert_spv_pointer_access() { From 778049f97a48c8682ab3d38f0b69495a00f9ac1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 20 Aug 2021 20:43:17 +0100 Subject: [PATCH 1264/2212] Apply comments --- src/back/hlsl/writer.rs | 145 +++++++------- src/back/wgsl/writer.rs | 140 +++++++------- .../out/ir/inv-hyperbolic-trig-functions.ron | 182 ------------------ tests/snapshots.rs | 2 +- 4 files changed, 149 insertions(+), 320 deletions(-) delete mode 100644 tests/out/ir/inv-hyperbolic-trig-functions.ron diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 87dabd863..d94587707 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1635,92 +1635,95 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } => { use crate::MathFunction as Mf; + enum Function { + Asincosh { is_sin: bool }, + Atanh, + Regular(&'static str), + } + + let fun = match fun { + // comparison + Mf::Abs => Function::Regular("abs"), + Mf::Min => Function::Regular("min"), + Mf::Max => Function::Regular("max"), + Mf::Clamp => Function::Regular("clamp"), + // trigonometry + Mf::Cos => Function::Regular("cos"), + Mf::Cosh => Function::Regular("cosh"), + Mf::Sin => Function::Regular("sin"), + Mf::Sinh => Function::Regular("sinh"), + Mf::Tan => Function::Regular("tan"), + Mf::Tanh => Function::Regular("tanh"), + Mf::Acos => Function::Regular("acos"), + Mf::Asin => Function::Regular("asin"), + Mf::Atan => Function::Regular("atan"), + Mf::Atan2 => Function::Regular("atan2"), + Mf::Asinh => Function::Asincosh { is_sin: true }, + Mf::Acosh => Function::Asincosh { is_sin: false }, + Mf::Atanh => Function::Atanh, + // decomposition + Mf::Ceil => Function::Regular("ceil"), + Mf::Floor => Function::Regular("floor"), + Mf::Round => Function::Regular("round"), + Mf::Fract => Function::Regular("frac"), + Mf::Trunc => Function::Regular("trunc"), + Mf::Modf => Function::Regular("modf"), + Mf::Frexp => Function::Regular("frexp"), + Mf::Ldexp => Function::Regular("ldexp"), + // exponent + Mf::Exp => Function::Regular("exp"), + Mf::Exp2 => Function::Regular("exp2"), + Mf::Log => Function::Regular("log"), + Mf::Log2 => Function::Regular("log2"), + Mf::Pow => Function::Regular("pow"), + // geometry + Mf::Dot => Function::Regular("dot"), + //Mf::Outer => , + Mf::Cross => Function::Regular("cross"), + Mf::Distance => Function::Regular("distance"), + Mf::Length => Function::Regular("length"), + Mf::Normalize => Function::Regular("normalize"), + Mf::FaceForward => Function::Regular("faceforward"), + Mf::Reflect => Function::Regular("reflect"), + Mf::Refract => Function::Regular("refract"), + // computational + Mf::Sign => Function::Regular("sign"), + Mf::Fma => Function::Regular("fma"), + Mf::Mix => Function::Regular("lerp"), + Mf::Step => Function::Regular("step"), + Mf::SmoothStep => Function::Regular("smoothstep"), + Mf::Sqrt => Function::Regular("sqrt"), + Mf::InverseSqrt => Function::Regular("rsqrt"), + //Mf::Inverse =>, + Mf::Transpose => Function::Regular("transpose"), + Mf::Determinant => Function::Regular("determinant"), + // bits + Mf::CountOneBits => Function::Regular("countbits"), + Mf::ReverseBits => Function::Regular("reversebits"), + _ => return Err(Error::Unimplemented(format!("write_expr_math {:?}", fun))), + }; + match fun { - Mf::Asinh | Mf::Acosh => { + Function::Asincosh { is_sin } => { write!(self.out, "log(")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, " + sqrt(")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, " * ")?; self.write_expr(module, arg, func_ctx)?; - if fun == Mf::Asinh { - write!(self.out, " + 1.0))")? - } else { - write!(self.out, " - 1.0))")? + match is_sin { + true => write!(self.out, " + 1.0))")?, + false => write!(self.out, " - 1.0))")?, } } - Mf::Atanh => { + Function::Atanh => { write!(self.out, "0.5 * log((1.0 + ")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, ") / (1.0 - ")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, "))")?; } - _ => { - let fun_name = match fun { - // comparison - Mf::Abs => "abs", - Mf::Min => "min", - Mf::Max => "max", - Mf::Clamp => "clamp", - // trigonometry - Mf::Cos => "cos", - Mf::Cosh => "cosh", - Mf::Sin => "sin", - Mf::Sinh => "sinh", - Mf::Tan => "tan", - Mf::Tanh => "tanh", - Mf::Acos => "acos", - Mf::Asin => "asin", - Mf::Atan => "atan", - Mf::Atan2 => "atan2", - // decomposition - Mf::Ceil => "ceil", - Mf::Floor => "floor", - Mf::Round => "round", - Mf::Fract => "frac", - Mf::Trunc => "trunc", - Mf::Modf => "modf", - Mf::Frexp => "frexp", - Mf::Ldexp => "ldexp", - // exponent - Mf::Exp => "exp", - Mf::Exp2 => "exp2", - Mf::Log => "log", - Mf::Log2 => "log2", - Mf::Pow => "pow", - // geometry - Mf::Dot => "dot", - //Mf::Outer => , - Mf::Cross => "cross", - Mf::Distance => "distance", - Mf::Length => "length", - Mf::Normalize => "normalize", - Mf::FaceForward => "faceforward", - Mf::Reflect => "reflect", - Mf::Refract => "refract", - // computational - Mf::Sign => "sign", - Mf::Fma => "fma", - Mf::Mix => "lerp", - Mf::Step => "step", - Mf::SmoothStep => "smoothstep", - Mf::Sqrt => "sqrt", - Mf::InverseSqrt => "rsqrt", - //Mf::Inverse =>, - Mf::Transpose => "transpose", - Mf::Determinant => "determinant", - // bits - Mf::CountOneBits => "countbits", - Mf::ReverseBits => "reversebits", - _ => { - return Err(Error::Unimplemented(format!( - "write_expr_math {:?}", - fun - ))) - } - }; - + Function::Regular(fun_name) => { write!(self.out, "{}(", fun_name)?; self.write_expr(module, arg, func_ctx)?; if let Some(arg) = arg1 { diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 2dfc72e80..20b6a1eec 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1240,88 +1240,96 @@ impl Writer { } => { use crate::MathFunction as Mf; + enum Function { + Asincosh { is_sin: bool }, + Atanh, + Regular(&'static str), + } + // NOTE: If https://github.com/gpuweb/gpuweb/issues/1622 ever is // accepted, replace this with the builtin functions - match fun { - Mf::Asinh | Mf::Acosh => { + let function = match fun { + Mf::Abs => Function::Regular("abs"), + Mf::Min => Function::Regular("min"), + Mf::Max => Function::Regular("max"), + Mf::Clamp => Function::Regular("clamp"), + // trigonometry + Mf::Cos => Function::Regular("cos"), + Mf::Cosh => Function::Regular("cosh"), + Mf::Sin => Function::Regular("sin"), + Mf::Sinh => Function::Regular("sinh"), + Mf::Tan => Function::Regular("tan"), + Mf::Tanh => Function::Regular("tanh"), + Mf::Acos => Function::Regular("acos"), + Mf::Asin => Function::Regular("asin"), + Mf::Atan => Function::Regular("atan"), + Mf::Atan2 => Function::Regular("atan2"), + Mf::Asinh => Function::Asincosh { is_sin: true }, + Mf::Acosh => Function::Asincosh { is_sin: false }, + Mf::Atanh => Function::Atanh, + // decomposition + Mf::Ceil => Function::Regular("ceil"), + Mf::Floor => Function::Regular("floor"), + Mf::Round => Function::Regular("round"), + Mf::Fract => Function::Regular("fract"), + Mf::Trunc => Function::Regular("trunc"), + Mf::Modf => Function::Regular("modf"), + Mf::Frexp => Function::Regular("frexp"), + Mf::Ldexp => Function::Regular("ldexp"), + // exponent + Mf::Exp => Function::Regular("exp"), + Mf::Exp2 => Function::Regular("exp2"), + Mf::Log => Function::Regular("log"), + Mf::Log2 => Function::Regular("log2"), + Mf::Pow => Function::Regular("pow"), + // geometry + Mf::Dot => Function::Regular("dot"), + Mf::Outer => Function::Regular("outerProduct"), + Mf::Cross => Function::Regular("cross"), + Mf::Distance => Function::Regular("distance"), + Mf::Length => Function::Regular("length"), + Mf::Normalize => Function::Regular("normalize"), + Mf::FaceForward => Function::Regular("faceForward"), + Mf::Reflect => Function::Regular("reflect"), + // computational + Mf::Sign => Function::Regular("sign"), + Mf::Fma => Function::Regular("fma"), + Mf::Mix => Function::Regular("mix"), + Mf::Step => Function::Regular("step"), + Mf::SmoothStep => Function::Regular("smoothStep"), + Mf::Sqrt => Function::Regular("sqrt"), + Mf::InverseSqrt => Function::Regular("inverseSqrt"), + Mf::Transpose => Function::Regular("transpose"), + Mf::Determinant => Function::Regular("determinant"), + // bits + Mf::CountOneBits => Function::Regular("countOneBits"), + Mf::ReverseBits => Function::Regular("reverseBits"), + _ => { + return Err(Error::UnsupportedMathFunction(fun)); + } + }; + + match function { + Function::Asincosh { is_sin } => { write!(self.out, "log(")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, " + sqrt(")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, " * ")?; self.write_expr(module, arg, func_ctx)?; - if fun == Mf::Asinh { - write!(self.out, " + 1.0))")? - } else { - write!(self.out, " - 1.0))")? + match is_sin { + true => write!(self.out, " + 1.0))")?, + false => write!(self.out, " - 1.0))")?, } } - Mf::Atanh => { + Function::Atanh => { write!(self.out, "0.5 * log((1.0 + ")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, ") / (1.0 - ")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, "))")?; } - _ => { - let fun_name = match fun { - Mf::Abs => "abs", - Mf::Min => "min", - Mf::Max => "max", - Mf::Clamp => "clamp", - // trigonometry - Mf::Cos => "cos", - Mf::Cosh => "cosh", - Mf::Sin => "sin", - Mf::Sinh => "sinh", - Mf::Tan => "tan", - Mf::Tanh => "tanh", - Mf::Acos => "acos", - Mf::Asin => "asin", - Mf::Atan => "atan", - Mf::Atan2 => "atan2", - // decomposition - Mf::Ceil => "ceil", - Mf::Floor => "floor", - Mf::Round => "round", - Mf::Fract => "fract", - Mf::Trunc => "trunc", - Mf::Modf => "modf", - Mf::Frexp => "frexp", - Mf::Ldexp => "ldexp", - // exponent - Mf::Exp => "exp", - Mf::Exp2 => "exp2", - Mf::Log => "log", - Mf::Log2 => "log2", - Mf::Pow => "pow", - // geometry - Mf::Dot => "dot", - Mf::Outer => "outerProduct", - Mf::Cross => "cross", - Mf::Distance => "distance", - Mf::Length => "length", - Mf::Normalize => "normalize", - Mf::FaceForward => "faceForward", - Mf::Reflect => "reflect", - // computational - Mf::Sign => "sign", - Mf::Fma => "fma", - Mf::Mix => "mix", - Mf::Step => "step", - Mf::SmoothStep => "smoothStep", - Mf::Sqrt => "sqrt", - Mf::InverseSqrt => "inverseSqrt", - Mf::Transpose => "transpose", - Mf::Determinant => "determinant", - // bits - Mf::CountOneBits => "countOneBits", - Mf::ReverseBits => "reverseBits", - _ => { - return Err(Error::UnsupportedMathFunction(fun)); - } - }; - + Function::Regular(fun_name) => { write!(self.out, "{}(", fun_name)?; self.write_expr(module, arg, func_ctx)?; if let Some(arg) = arg1 { diff --git a/tests/out/ir/inv-hyperbolic-trig-functions.ron b/tests/out/ir/inv-hyperbolic-trig-functions.ron deleted file mode 100644 index bdf53ea71..000000000 --- a/tests/out/ir/inv-hyperbolic-trig-functions.ron +++ /dev/null @@ -1,182 +0,0 @@ -( - types: [ - ( - name: None, - inner: Scalar( - kind: Float, - width: 4, - ), - ), - ( - name: None, - inner: Pointer( - base: 1, - class: Function, - ), - ), - ( - name: None, - inner: Pointer( - base: 1, - class: Private, - ), - ), - ], - constants: [ - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(1), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(2), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(3), - ), - ), - ], - global_variables: [ - ( - name: Some("a"), - class: Private, - binding: None, - ty: 1, - init: None, - ), - ], - functions: [ - ( - name: Some("main"), - arguments: [], - result: None, - local_variables: [ - ( - name: Some("b"), - ty: 1, - init: None, - ), - ( - name: Some("c"), - ty: 1, - init: None, - ), - ( - name: Some("d"), - ty: 1, - init: None, - ), - ], - expressions: [ - GlobalVariable(1), - Constant(1), - Constant(2), - Constant(3), - Constant(4), - LocalVariable(1), - LocalVariable(2), - LocalVariable(3), - Load( - pointer: 1, - ), - Math( - fun: Asinh, - arg: 9, - arg1: None, - arg2: None, - ), - Load( - pointer: 1, - ), - Math( - fun: Acosh, - arg: 11, - arg1: None, - arg2: None, - ), - Load( - pointer: 1, - ), - Math( - fun: Atanh, - arg: 13, - arg1: None, - arg2: None, - ), - ], - named_expressions: {}, - body: [ - Emit(( - start: 8, - end: 10, - )), - Store( - pointer: 6, - value: 10, - ), - Emit(( - start: 10, - end: 12, - )), - Store( - pointer: 7, - value: 12, - ), - Emit(( - start: 12, - end: 14, - )), - Store( - pointer: 8, - value: 14, - ), - Return( - value: None, - ), - ], - ), - ], - entry_points: [ - ( - name: "main", - stage: Vertex, - early_depth_test: None, - workgroup_size: (0, 0, 0), - function: ( - name: Some("main_wrap"), - arguments: [], - result: None, - local_variables: [], - expressions: [], - named_expressions: {}, - body: [ - Call( - function: 1, - arguments: [], - result: None, - ), - ], - ), - ), - ], -) \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e2a957e24..879af0c06 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -504,7 +504,7 @@ fn convert_spv_inverse_hyperbolic_trig_functions() { convert_spv( "inv-hyperbolic-trig-functions", true, - Targets::HLSL | Targets::WGSL | Targets::IR, + Targets::HLSL | Targets::WGSL, ); } From 897afbd710c3f1aa4b6bf82e4b6a08f70daa9a51 Mon Sep 17 00:00:00 2001 From: Zicklag Date: Thu, 19 Aug 2021 19:21:35 -0500 Subject: [PATCH 1265/2212] [wgsl-in] [wgsl-out] Implement bitcast() --- src/back/wgsl/writer.rs | 14 +- src/front/wgsl/mod.rs | 30 ++++ tests/in/operators.wgsl | 6 +- tests/out/glsl/operators.main.Compute.glsl | 10 +- tests/out/hlsl/operators.hlsl | 11 +- tests/out/msl/operators.msl | 11 +- tests/out/spv/operators.spvasm | 157 +++++++++++---------- tests/out/wgsl/operators.wgsl | 11 +- 8 files changed, 156 insertions(+), 94 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 20b6a1eec..123c12e7b 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1145,7 +1145,11 @@ impl Writer { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; } - Expression::As { expr, kind, .. } => { + Expression::As { + expr, + kind, + convert, + } => { let inner = func_ctx.info[expr].ty.inner_with(&module.types); match *inner { TypeInner::Matrix { columns, rows, .. } => { @@ -1164,7 +1168,13 @@ impl Writer { scalar_kind_str(kind) )?; } - TypeInner::Scalar { .. } => write!(self.out, "{}", scalar_kind_str(kind))?, + TypeInner::Scalar { .. } => { + if convert.is_some() { + write!(self.out, "{}", scalar_kind_str(kind))? + } else { + write!(self.out, "bitcast<{}>", scalar_kind_str(kind))? + } + } _ => { return Err(Error::Unimplemented(format!( "write_expr expression::as {:?}", diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 745d1ea2d..3b931f784 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1274,6 +1274,36 @@ impl Parser { } } else { match name { + "bitcast" => { + let _ = lexer.next(); + lexer.expect_generic_paren('<')?; + let ((ty, _access), type_span) = lexer.capture_span(|lexer| { + self.parse_type_decl(lexer, None, ctx.types, ctx.constants) + })?; + lexer.expect_generic_paren('>')?; + + lexer.open_arguments()?; + let expr = self.parse_general_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + + let kind = match ctx.types[ty].inner { + crate::TypeInner::Scalar { kind, .. } => kind, + crate::TypeInner::Vector { kind, .. } => kind, + _ => { + return Err(Error::BadTypeCast { + from_type: format!("{:?}", ctx.resolve_type(expr)?), + span: type_span, + to_type: format!("{:?}", ctx.types[ty].inner), + }) + } + }; + + crate::Expression::As { + expr, + kind, + convert: None, + } + } "select" => { let _ = lexer.next(); lexer.open_arguments()?; diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 1ab3550d2..da2be1cff 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -2,6 +2,7 @@ let v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); +let v_i32_one: vec4 = vec4(1, 1, 1, 1); fn builtins() -> vec4 { // select() @@ -12,8 +13,11 @@ fn builtins() -> vec4 { // mix() let m1 = mix(v_f32_zero, v_f32_one, v_f32_half); let m2 = mix(v_f32_zero, v_f32_one, 0.1); + // bitcast() + let b1 = bitcast(v_i32_one.x); + let b2 = bitcast>(v_i32_one); // done - return vec4(vec4(s1)) + s2 + m1 + m2; + return vec4(vec4(s1)) + s2 + m1 + m2 + b1 + b2; } fn splat() -> vec4 { diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index a146d42bb..1c1cf2bd1 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -12,7 +12,9 @@ vec4 builtins() { vec4 s3_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), bvec4(false, false, false, false)); vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); - return (((vec4(ivec4(s1_)) + s2_) + m1_) + m2_); + float b1_ = intBitsToFloat(ivec4(1, 1, 1, 1).x); + vec4 b2_ = intBitsToFloat(ivec4(1, 1, 1, 1)); + return (((((vec4(ivec4(s1_)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } vec4 splat() { @@ -30,9 +32,9 @@ int unary() { } void main() { - vec4 _e3 = builtins(); - vec4 _e4 = splat(); - int _e5 = unary(); + vec4 _e4 = builtins(); + vec4 _e5 = splat(); + int _e6 = unary(); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 1ff8d4229..98a0da293 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -1,6 +1,7 @@ static const float4 v_f32_one = float4(1.0, 1.0, 1.0, 1.0); static const float4 v_f32_zero = float4(0.0, 0.0, 0.0, 0.0); static const float4 v_f32_half = float4(0.5, 0.5, 0.5, 0.5); +static const int4 v_i32_one = int4(1, 1, 1, 1); float4 builtins() { @@ -9,7 +10,9 @@ float4 builtins() float4 s3_ = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.1); - return (((float4(int4(s1_.xxxx)) + s2_) + m1_) + m2_); + float b1_ = float(int4(1, 1, 1, 1).x); + float4 b2_ = float4(int4(1, 1, 1, 1)); + return (((((float4(int4(s1_.xxxx)) + s2_) + m1_) + m2_) + float4(b1_.xxxx)) + b2_); } float4 splat() @@ -31,8 +34,8 @@ int unary() [numthreads(1, 1, 1)] void main() { - const float4 _e3 = builtins(); - const float4 _e4 = splat(); - const int _e5 = unary(); + const float4 _e4 = builtins(); + const float4 _e5 = splat(); + const int _e6 = unary(); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index a193bc096..105da6b90 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -5,6 +5,7 @@ constant metal::float4 v_f32_one = {1.0, 1.0, 1.0, 1.0}; constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0}; constant metal::float4 v_f32_half = {0.5, 0.5, 0.5, 0.5}; +constant metal::int4 v_i32_one = {1, 1, 1, 1}; metal::float4 builtins( ) { @@ -13,7 +14,9 @@ metal::float4 builtins( metal::float4 s3_ = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false)); metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half); metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.1); - return ((static_cast(metal::int4(s1_)) + s2_) + m1_) + m2_; + float b1_ = as_type(v_i32_one.x); + metal::float4 b2_ = as_type(v_i32_one); + return ((((static_cast(metal::int4(s1_)) + s2_) + m1_) + m2_) + metal::float4(b1_)) + b2_; } metal::float4 splat( @@ -34,8 +37,8 @@ int unary( kernel void main1( ) { - metal::float4 _e3 = builtins(); - metal::float4 _e4 = splat(); - int _e5 = unary(); + metal::float4 _e4 = builtins(); + metal::float4 _e5 = splat(); + int _e6 = unary(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 7e904842a..e6de2a778 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,99 +1,106 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 76 +; Bound: 83 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %70 "main" -OpExecutionMode %70 LocalSize 1 1 1 +OpEntryPoint GLCompute %77 "main" +OpExecutionMode %77 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 %5 = OpConstant %4 0.0 %6 = OpConstant %4 0.5 -%8 = OpTypeBool -%7 = OpConstantTrue %8 -%10 = OpTypeInt 32 1 -%9 = OpConstant %10 0 -%11 = OpConstant %10 1 -%12 = OpConstantFalse %8 +%8 = OpTypeInt 32 1 +%7 = OpConstant %8 1 +%10 = OpTypeBool +%9 = OpConstantTrue %10 +%11 = OpConstant %8 0 +%12 = OpConstantFalse %10 %13 = OpConstant %4 0.1 %14 = OpConstant %4 2.0 %15 = OpConstant %4 3.0 %16 = OpConstant %4 4.0 -%17 = OpConstant %10 5 -%18 = OpConstant %10 2 +%17 = OpConstant %8 5 +%18 = OpConstant %8 2 %19 = OpTypeVector %4 4 %20 = OpTypeVector %8 4 -%21 = OpConstantComposite %19 %3 %3 %3 %3 -%22 = OpConstantComposite %19 %5 %5 %5 %5 -%23 = OpConstantComposite %19 %6 %6 %6 %6 -%26 = OpTypeFunction %19 -%36 = OpTypeVector %10 4 -%45 = OpTypeVector %4 2 -%61 = OpTypeFunction %10 -%68 = OpConstantNull %10 -%71 = OpTypeFunction %2 -%25 = OpFunction %19 None %26 -%24 = OpLabel -OpBranch %27 -%27 = OpLabel -%28 = OpSelect %10 %7 %11 %9 -%30 = OpCompositeConstruct %20 %7 %7 %7 %7 -%29 = OpSelect %19 %30 %21 %22 -%31 = OpCompositeConstruct %20 %12 %12 %12 %12 -%32 = OpSelect %19 %31 %22 %21 -%33 = OpExtInst %19 %1 FMix %22 %21 %23 -%35 = OpCompositeConstruct %19 %13 %13 %13 %13 -%34 = OpExtInst %19 %1 FMix %22 %21 %35 -%37 = OpCompositeConstruct %36 %28 %28 %28 %28 -%38 = OpConvertSToF %19 %37 -%39 = OpFAdd %19 %38 %29 -%40 = OpFAdd %19 %39 %33 -%41 = OpFAdd %19 %40 %34 -OpReturnValue %41 +%21 = OpTypeVector %10 4 +%22 = OpConstantComposite %19 %3 %3 %3 %3 +%23 = OpConstantComposite %19 %5 %5 %5 %5 +%24 = OpConstantComposite %19 %6 %6 %6 %6 +%25 = OpConstantComposite %20 %7 %7 %7 %7 +%28 = OpTypeFunction %19 +%52 = OpTypeVector %4 2 +%68 = OpTypeFunction %8 +%75 = OpConstantNull %8 +%78 = OpTypeFunction %2 +%27 = OpFunction %19 None %28 +%26 = OpLabel +OpBranch %29 +%29 = OpLabel +%30 = OpSelect %8 %9 %7 %11 +%32 = OpCompositeConstruct %21 %9 %9 %9 %9 +%31 = OpSelect %19 %32 %22 %23 +%33 = OpCompositeConstruct %21 %12 %12 %12 %12 +%34 = OpSelect %19 %33 %23 %22 +%35 = OpExtInst %19 %1 FMix %23 %22 %24 +%37 = OpCompositeConstruct %19 %13 %13 %13 %13 +%36 = OpExtInst %19 %1 FMix %23 %22 %37 +%38 = OpCompositeExtract %8 %25 0 +%39 = OpBitcast %4 %38 +%40 = OpBitcast %19 %25 +%41 = OpCompositeConstruct %20 %30 %30 %30 %30 +%42 = OpConvertSToF %19 %41 +%43 = OpFAdd %19 %42 %31 +%44 = OpFAdd %19 %43 %35 +%45 = OpFAdd %19 %44 %36 +%46 = OpCompositeConstruct %19 %39 %39 %39 %39 +%47 = OpFAdd %19 %45 %46 +%48 = OpFAdd %19 %47 %40 +OpReturnValue %48 OpFunctionEnd -%43 = OpFunction %19 None %26 -%42 = OpLabel -OpBranch %44 -%44 = OpLabel -%46 = OpCompositeConstruct %45 %14 %14 -%47 = OpCompositeConstruct %45 %3 %3 -%48 = OpFAdd %45 %47 %46 -%49 = OpCompositeConstruct %45 %15 %15 -%50 = OpFSub %45 %48 %49 -%51 = OpCompositeConstruct %45 %16 %16 -%52 = OpFDiv %45 %50 %51 -%53 = OpCompositeConstruct %36 %17 %17 %17 %17 -%54 = OpCompositeConstruct %36 %18 %18 %18 %18 -%55 = OpSMod %36 %53 %54 -%56 = OpVectorShuffle %19 %52 %52 0 1 0 1 -%57 = OpConvertSToF %19 %55 -%58 = OpFAdd %19 %56 %57 -OpReturnValue %58 +%50 = OpFunction %19 None %28 +%49 = OpLabel +OpBranch %51 +%51 = OpLabel +%53 = OpCompositeConstruct %52 %14 %14 +%54 = OpCompositeConstruct %52 %3 %3 +%55 = OpFAdd %52 %54 %53 +%56 = OpCompositeConstruct %52 %15 %15 +%57 = OpFSub %52 %55 %56 +%58 = OpCompositeConstruct %52 %16 %16 +%59 = OpFDiv %52 %57 %58 +%60 = OpCompositeConstruct %20 %17 %17 %17 %17 +%61 = OpCompositeConstruct %20 %18 %18 %18 %18 +%62 = OpSMod %20 %60 %61 +%63 = OpVectorShuffle %19 %59 %59 0 1 0 1 +%64 = OpConvertSToF %19 %62 +%65 = OpFAdd %19 %63 %64 +OpReturnValue %65 OpFunctionEnd -%60 = OpFunction %10 None %61 -%59 = OpLabel -OpBranch %62 -%62 = OpLabel -%63 = OpLogicalNot %8 %7 -OpSelectionMerge %64 None -OpBranchConditional %63 %65 %66 -%65 = OpLabel -OpReturnValue %11 +%67 = OpFunction %8 None %68 %66 = OpLabel -%67 = OpNot %10 %11 -OpReturnValue %67 -%64 = OpLabel -OpReturnValue %68 -OpFunctionEnd -%70 = OpFunction %2 None %71 +OpBranch %69 %69 = OpLabel -OpBranch %72 +%70 = OpLogicalNot %10 %9 +OpSelectionMerge %71 None +OpBranchConditional %70 %72 %73 %72 = OpLabel -%73 = OpFunctionCall %19 %25 -%74 = OpFunctionCall %19 %43 -%75 = OpFunctionCall %10 %60 +OpReturnValue %7 +%73 = OpLabel +%74 = OpNot %8 %7 +OpReturnValue %74 +%71 = OpLabel +OpReturnValue %75 +OpFunctionEnd +%77 = OpFunction %2 None %78 +%76 = OpLabel +OpBranch %79 +%79 = OpLabel +%80 = OpFunctionCall %19 %27 +%81 = OpFunctionCall %19 %50 +%82 = OpFunctionCall %8 %67 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index f83e8c28a..569804ed1 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -1,13 +1,16 @@ let v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); +let v_i32_one: vec4 = vec4(1, 1, 1, 1); fn builtins() -> vec4 { let s1_: i32 = select(0, 1, true); let s2_: vec4 = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); let s3_: vec4 = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); let m1_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); - return (((vec4(vec4(s1_)) + s2_) + m1_) + m2_); + let b1_: f32 = bitcast(vec4(1, 1, 1, 1).x); + let b2_: vec4 = vec4(vec4(1, 1, 1, 1)); + return (((((vec4(vec4(s1_)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } fn splat() -> vec4 { @@ -26,8 +29,8 @@ fn unary() -> i32 { [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { - let _e3: vec4 = builtins(); - let _e4: vec4 = splat(); - let _e5: i32 = unary(); + let _e4: vec4 = builtins(); + let _e5: vec4 = splat(); + let _e6: i32 = unary(); return; } From ea168baf569448b52fbe07fd145dd566de35a439 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 19 Aug 2021 23:00:36 -0700 Subject: [PATCH 1266/2212] [spv-out] Clean up capability handling. Remove `forbidden_caps`. Accumulate capabilities actually used separately from the permitted capabilities, so that the latter can be retained across Writer resets, while the former is cleared between modules. --- src/back/spv/block.rs | 3 +- src/back/spv/mod.rs | 28 ++++++--- src/back/spv/recyclable.rs | 7 +++ src/back/spv/writer.rs | 124 ++++++++++++++++++++++++------------- 4 files changed, 112 insertions(+), 50 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 19450c02f..f4923aa6f 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1111,7 +1111,8 @@ impl<'w> BlockContext<'w> { } }; - self.writer.check(&[spirv::Capability::ImageQuery])?; + self.writer + .require_any("image queries", &[spirv::Capability::ImageQuery])?; match query { Iq::Size { level } => { diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 4c2c06e6d..bd52a0377 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -55,8 +55,8 @@ const BITS_PER_BYTE: crate::Bytes = 8; pub enum Error { #[error("target SPIRV-{0}.{1} is not supported")] UnsupportedVersion(u8, u8), - #[error("one of the required capabilities {0:?} is missing")] - MissingCapabilities(Vec), + #[error("using {0} requires at least one of the capabilities {1:?}, but none are available")] + MissingCapabilities(&'static str, Vec), #[error("unimplemented {0}")] FeatureNotImplemented(&'static str), #[error("module is not validated properly: {0}")] @@ -385,8 +385,18 @@ pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, id_gen: IdGenerator, - capabilities: crate::FastHashSet, - forbidden_caps: Option<&'static [Capability]>, + + /// The set of capabilities modules are permitted to use. + /// + /// This is initialized from `Options::capabilities`. + capabilities_available: Option>, + + /// The set of capabilities used by this module. + /// + /// If `capabilities_available` is `Some`, then this is always a subset of + /// that. + capabilities_used: crate::FastHashSet, + debugs: Vec, annotations: Vec, flags: WriterFlags, @@ -422,12 +432,16 @@ bitflags::bitflags! { pub struct Options { /// (Major, Minor) target version of the SPIR-V. pub lang_version: (u8, u8), + /// Configuration flags for the writer. pub flags: WriterFlags, - /// Set of SPIR-V allowed capabilities, if provided. - // Note: there is a major bug currently associated with deriving the capabilities. - // We are calling `required_capabilities`, but the semantics of this is broken. + + /// If given, the set of capabilities modules are allowed to use. Code that + /// requires capabilities beyond these is rejected with an error. + /// + /// If this is `None`, all capabilities are permitted. pub capabilities: Option>, + /// How should the generated code handle array, vector, or matrix indices /// that are out of range? pub index_bounds_check_policy: IndexBoundsCheckPolicy, diff --git a/src/back/spv/recyclable.rs b/src/back/spv/recyclable.rs index c1b7fdcc6..e8813497f 100644 --- a/src/back/spv/recyclable.rs +++ b/src/back/spv/recyclable.rs @@ -42,3 +42,10 @@ impl Recyclable for std::collections::HashMap { self } } + +impl Recyclable for std::collections::HashSet { + fn recycle(mut self) -> Self { + self.clear(); + self + } +} diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a53dc9cf6..6a0c634cd 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -50,15 +50,8 @@ impl Writer { } let raw_version = ((major as u32) << 16) | ((minor as u32) << 8); - let (capabilities, forbidden_caps) = match options.capabilities { - Some(ref caps) => (caps.clone(), None), - None => { - let mut caps = crate::FastHashSet::default(); - caps.insert(spirv::Capability::Shader); - let forbidden: &[_] = &[spirv::Capability::Kernel]; - (caps, Some(forbidden)) - } - }; + let mut capabilities_used = crate::FastHashSet::default(); + capabilities_used.insert(spirv::Capability::Shader); let mut id_gen = IdGenerator::default(); let gl450_ext_inst_id = id_gen.next(); @@ -68,8 +61,8 @@ impl Writer { physical_layout: PhysicalLayout::new(raw_version), logical_layout: LogicalLayout::default(), id_gen, - capabilities, - forbidden_caps, + capabilities_available: options.capabilities.clone(), + capabilities_used, debugs: vec![], annotations: vec![], flags: options.flags, @@ -110,8 +103,7 @@ impl Writer { // Copied from the old Writer: flags: self.flags, index_bounds_check_policy: self.index_bounds_check_policy, - capabilities: take(&mut self.capabilities), - forbidden_caps: take(&mut self.forbidden_caps), + capabilities_available: take(&mut self.capabilities_available), // Initialized afresh: id_gen, @@ -119,6 +111,7 @@ impl Writer { gl450_ext_inst_id, // Recycled: + capabilities_used: take(&mut self.capabilities_used).recycle(), physical_layout: self.physical_layout.clone().recycle(), logical_layout: take(&mut self.logical_layout).recycle(), debugs: take(&mut self.debugs).recycle(), @@ -134,27 +127,49 @@ impl Writer { }; *self = fresh; + + self.capabilities_used.insert(spirv::Capability::Shader); } - //TODO: revive and rewrite this, see: - // https://github.com/gfx-rs/rspirv/issues/198 - // https://github.com/gfx-rs/rspirv/pull/185#issuecomment-900796025 - pub(super) fn check(&mut self, capabilities: &[spirv::Capability]) -> Result<(), Error> { - if capabilities.is_empty() - || capabilities - .iter() - .any(|cap| self.capabilities.contains(cap)) - { - return Ok(()); - } - if let Some(forbidden) = self.forbidden_caps { - // take the first allowed capability, blindly - if let Some(&cap) = capabilities.iter().find(|cap| !forbidden.contains(cap)) { - self.capabilities.insert(cap); - return Ok(()); + /// Indicate that the code requires any one of the listed capabilities. + /// + /// If nothing in `capabilities` appears in the available capabilities + /// specified in the [`Options`] from which this `Writer` was created, + /// return an error. The `what` string is used in the error message to + /// explain what provoked the requirement. (If no available capabilites were + /// given, assume everything is available.) + /// + /// The first acceptable capability will be added to this `Writer`'s + /// [`capabilities_used`] table, and an `OpCapability` emitted for it in the + /// result. For this reason, more specific capabilities should be listed + /// before more general. + /// + /// [`capabilities_used`]: Writer::capabilities_used + pub(super) fn require_any( + &mut self, + what: &'static str, + capabilities: &[spirv::Capability], + ) -> Result<(), Error> { + match *capabilities { + [] => Ok(()), + [first, ..] => { + // Find the first acceptable capability, or return an error if + // there is none. + let selected = match self.capabilities_available { + None => first, + Some(ref available) => { + match capabilities.iter().find(|cap| available.contains(cap)) { + Some(&cap) => cap, + None => { + return Err(Error::MissingCapabilities(what, capabilities.to_vec())) + } + } + } + }; + self.capabilities_used.insert(selected); + Ok(()) } } - Err(Error::MissingCapabilities(capabilities.to_vec())) } pub(super) fn get_type_id(&mut self, lookup_ty: LookupType) -> Word { @@ -556,13 +571,13 @@ impl Writer { _ => None, }; if let Some(cap) = cap { - self.capabilities.insert(cap); + self.capabilities_used.insert(cap); } Instruction::type_int(id, bits, signedness) } Sk::Float => { if bits == 64 { - self.capabilities.insert(spirv::Capability::Float64); + self.capabilities_used.insert(spirv::Capability::Float64); } Instruction::type_float(id, bits) } @@ -705,18 +720,30 @@ impl Writer { let kind = match class { crate::ImageClass::Sampled { kind, multi: _ } => { if dim == crate::ImageDimension::D1 { - self.check(&[spirv::Capability::Sampled1D])?; + self.require_any("1D sampled images", &[spirv::Capability::Sampled1D])?; } kind } crate::ImageClass::Depth { multi: _ } => crate::ScalarKind::Float, crate::ImageClass::Storage { format, .. } => { - let required_caps: &[_] = match dim { - crate::ImageDimension::D1 => &[spirv::Capability::Image1D], - crate::ImageDimension::Cube => &[spirv::Capability::ImageCubeArray], - _ => &[], + match dim { + crate::ImageDimension::D1 => { + self.require_any( + "1D storage images", + &[spirv::Capability::Image1D], + )?; + } + crate::ImageDimension::Cube => { + if arrayed { + self.require_any( + "arrayed cube images", + &[spirv::Capability::ImageCubeArray], + )?; + } + } + _ => {} }; - self.check(required_caps)?; + format.into() } }; @@ -727,7 +754,6 @@ impl Writer { pointer_class: None, }; let dim = map_dim(dim); - //self.check(dim.required_capabilities())?; let type_id = self.get_type_id(LookupType::Local(local_type)); Instruction::type_image(id, type_id, dim, arrayed, class) } @@ -1013,6 +1039,10 @@ impl Writer { self.decorate(id, Decoration::Centroid, &[]); } Some(crate::Sampling::Sample) => { + self.require_any( + "per-sample interpolation", + &[spirv::Capability::SampleRateShading], + )?; self.decorate(id, Decoration::Sample, &[]); } } @@ -1039,10 +1069,20 @@ impl Writer { Bi::FragDepth => BuiltIn::FragDepth, Bi::FrontFacing => BuiltIn::FrontFacing, Bi::PrimitiveIndex => { - self.capabilities.insert(spirv::Capability::Geometry); + self.require_any( + "`primitive_index` built-in", + &[spirv::Capability::Geometry], + )?; BuiltIn::PrimitiveId } - Bi::SampleIndex => BuiltIn::SampleId, + Bi::SampleIndex => { + self.require_any( + "`sample_index` built-in", + &[spirv::Capability::SampleRateShading], + )?; + + BuiltIn::SampleId + } Bi::SampleMask => BuiltIn::SampleMask, // compute Bi::GlobalInvocationId => BuiltIn::GlobalInvocationId, @@ -1226,7 +1266,7 @@ impl Writer { ep_instruction.to_words(&mut self.logical_layout.entry_points); } - for capability in self.capabilities.iter() { + for capability in self.capabilities_used.iter() { Instruction::capability(*capability).to_words(&mut self.logical_layout.capabilities); } if ir_module.entry_points.is_empty() { From fd3f9543b55aff03b7087d075fca9b340d60f5a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 20 Aug 2021 23:17:48 +0100 Subject: [PATCH 1267/2212] Fix round in backends and add support for roundEven in frontends --- src/back/glsl/mod.rs | 2 +- src/back/msl/writer.rs | 2 +- src/back/spv/block.rs | 2 +- src/front/glsl/builtins.rs | 5 +++-- src/front/spv/mod.rs | 1 + 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index fb3e1f47a..b9ba220bf 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2251,7 +2251,7 @@ impl<'a, W: Write> Writer<'a, W> { // decomposition Mf::Ceil => "ceil", Mf::Floor => "floor", - Mf::Round => "round", + Mf::Round => "roundEven", Mf::Fract => "fract", Mf::Trunc => "trunc", Mf::Modf => "modf", diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0d1fbd36b..87e5fb6a0 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1146,7 +1146,7 @@ impl Writer { // decomposition Mf::Ceil => "ceil", Mf::Floor => "floor", - Mf::Round => "round", + Mf::Round => "rint", Mf::Fract => "fract", Mf::Trunc => "trunc", Mf::Modf => "modf", diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index f4923aa6f..49827a2eb 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -563,7 +563,7 @@ impl<'w> BlockContext<'w> { Mf::Atanh => MathOp::Ext(spirv::GLOp::Atanh), // decomposition Mf::Ceil => MathOp::Ext(spirv::GLOp::Ceil), - Mf::Round => MathOp::Ext(spirv::GLOp::Round), + Mf::Round => MathOp::Ext(spirv::GLOp::RoundEven), Mf::Floor => MathOp::Ext(spirv::GLOp::Floor), Mf::Fract => MathOp::Ext(spirv::GLOp::Fract), Mf::Trunc => MathOp::Ext(spirv::GLOp::Trunc), diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 4af2c7de4..074dc6562 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -953,8 +953,8 @@ fn inject_common_builtin( float_width: crate::Bytes, ) { match name { - "ceil" | "round" | "floor" | "fract" | "trunc" | "sqrt" | "inversesqrt" | "normalize" - | "length" | "isinf" | "isnan" => { + "ceil" | "round" | "roundEven" | "floor" | "fract" | "trunc" | "sqrt" | "inversesqrt" + | "normalize" | "length" | "isinf" | "isnan" => { // bits layout // bit 0 trough 1 - dims for bits in 0..(0b100) { @@ -980,6 +980,7 @@ fn inject_common_builtin( let fun = match name { "ceil" => MacroCall::MathFunction(MathFunction::Ceil), "round" => MacroCall::MathFunction(MathFunction::Round), + "roundEven" => MacroCall::MathFunction(MathFunction::Round), "floor" => MacroCall::MathFunction(MathFunction::Floor), "fract" => MacroCall::MathFunction(MathFunction::Fract), "trunc" => MacroCall::MathFunction(MathFunction::Trunc), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index ce7080873..6d9d0a8a8 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1968,6 +1968,7 @@ impl> Parser { } else { let fun = match gl_op { Glo::Round => Mf::Round, + Glo::RoundEven => Mf::Round, Glo::Trunc => Mf::Trunc, Glo::FAbs | Glo::SAbs => Mf::Abs, Glo::FSign | Glo::SSign => Mf::Sign, From c09354c78e0ceda96fd97a6951e4d0cd5d1b3185 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 21 Aug 2021 00:33:35 +0100 Subject: [PATCH 1268/2212] [glsl-in] Add support for float encoding/decoding builtins Fixes #1246 --- src/front/glsl/builtins.rs | 42 +++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 074dc6562..b1b6ae4e2 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -451,7 +451,8 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module } } "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" - | "log" | "log2" | "radians" | "degrees" | "asinh" | "acosh" | "atanh" => { + | "log" | "log2" | "radians" | "degrees" | "asinh" | "acosh" | "atanh" + | "floatBitsToInt" | "floatBitsToUint" => { // bits layout // bit 0 trough 1 - dims for bits in 0..(0b100) { @@ -486,11 +487,37 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module "atanh" => MacroCall::MathFunction(MathFunction::Atanh), "radians" => MacroCall::ConstMultiply(std::f64::consts::PI / 180.0), "degrees" => MacroCall::ConstMultiply(180.0 / std::f64::consts::PI), + "floatBitsToInt" => MacroCall::BitCast(Sk::Sint), + "floatBitsToUint" => MacroCall::BitCast(Sk::Uint), _ => unreachable!(), }, )) } } + "intBitsToFloat" | "uintBitsToFloat" => { + // bits layout + // bit 0 trough 1 - dims + for bits in 0..(0b100) { + let size = match bits { + 0b00 => None, + 0b01 => Some(VectorSize::Bi), + 0b10 => Some(VectorSize::Tri), + _ => Some(VectorSize::Quad), + }; + let kind = match name { + "intBitsToFloat" => Sk::Sint, + _ => Sk::Uint, + }; + + declaration.overloads.push(module.add_builtin( + vec![match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }], + MacroCall::BitCast(Sk::Float), + )) + } + } "pow" => { // bits layout // bit 0 trough 1 - dims @@ -979,8 +1006,7 @@ fn inject_common_builtin( let fun = match name { "ceil" => MacroCall::MathFunction(MathFunction::Ceil), - "round" => MacroCall::MathFunction(MathFunction::Round), - "roundEven" => MacroCall::MathFunction(MathFunction::Round), + "round" | "roundEven" => MacroCall::MathFunction(MathFunction::Round), "floor" => MacroCall::MathFunction(MathFunction::Floor), "fract" => MacroCall::MathFunction(MathFunction::Fract), "trunc" => MacroCall::MathFunction(MathFunction::Trunc), @@ -1368,6 +1394,7 @@ pub enum MacroCall { MixBoolean, Clamp(Option), ConstMultiply(f64), + BitCast(Sk), } impl MacroCall { @@ -1603,6 +1630,15 @@ impl MacroCall { body, )) } + MacroCall::BitCast(kind) => Ok(ctx.add_expression( + Expression::As { + expr: args[0], + kind, + convert: None, + }, + SourceMetadata::none(), + body, + )), } } } From 70be72d9b9615557fa8726829813755ee6b52279 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 20 Aug 2021 21:31:40 -0400 Subject: [PATCH 1269/2212] [spv-in] fix expression emit in image store --- src/front/spv/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 6d9d0a8a8..d608ef604 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1617,7 +1617,6 @@ impl> Parser { } Op::ImageWrite => { let extra = inst.expect_at_least(4)?; - block.extend(emitter.finish(expressions)); let stmt = self.parse_image_write( extra, type_arena, @@ -1625,6 +1624,7 @@ impl> Parser { arguments, expressions, )?; + block.extend(emitter.finish(expressions)); block.push(stmt, span); emitter.start(expressions); } From 800f9101032cdf804477ee29ec617af0710a4741 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Sun, 22 Aug 2021 17:28:28 -0400 Subject: [PATCH 1270/2212] Allow newer bitflags --- .github/workflows/pipeline.yml | 8 +++++++- Cargo.toml | 4 ++-- README.md | 12 ++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index bba081e5f..dc9823869 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - rust: [1.43.0, nightly] + rust: ["1.43.0", nightly] steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 @@ -16,6 +16,12 @@ jobs: profile: minimal toolchain: ${{ matrix.rust }} override: true + - uses: actions-rs/cargo@v1 + name: Downgrade bitflags to MSRV + if: ${{ matrix.rust }} == "1.43.0" + with: + command: update + args: -p bitflags --precise 1.2.1 - uses: actions-rs/cargo@v1 name: Default test with: diff --git a/Cargo.toml b/Cargo.toml index f72aa0ae6..92f911b71 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,8 +15,8 @@ resolver = "2" all-features = true [dependencies] -# bitflags 1.3 requires Rust-1.46 -bitflags = "~1.2" +# MSRV warning: bitflags 1.3 requires Rust-1.46 +bitflags = "1" bit-set = "0.5" codespan-reporting = { version = "0.11.0", optional = true } fxhash = "0.2" diff --git a/README.md b/README.md index 13bd5afec..b90bd9ee8 100644 --- a/README.md +++ b/README.md @@ -66,3 +66,15 @@ make validate-dot # for dot files, requires GraphViz installed make validate-wgsl # for WGSL shaders make validate-hlsl # for HLSL shaders. Note: this Make target makes use of the "sh" shell. This is not the default shell in Windows. ``` + +## MSRV + +The `naga` codebase's MSRV is 1.43. However some newer versions of our dependencies have newer MSRVs than that. Here are a list of all known MSRV breaking dependencies and the versions that hold to MSRV. + +- `bitflags`: `>1.3` have an MSRV of 1.46. `<=1.2` has an MSRV of 1.43 or earlier. + +If you want to use `naga` with `1.43` add the following to your Cargo.toml dependency list even if you don't use bitflags yourself: + +```toml +bitflags = "<1.3" +``` From 222e0949bdd0a06aaceabfb105fafc2e336de6eb Mon Sep 17 00:00:00 2001 From: Mikko Lehtonen Date: Sun, 22 Aug 2021 22:36:49 +0300 Subject: [PATCH 1271/2212] [msl-out] Fix gradient sampling typo --- src/back/msl/writer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 87e5fb6a0..cdbd554af 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -610,7 +610,7 @@ impl Writer { write!(self.out, ")")?; } crate::SampleLevel::Gradient { x, y } => { - write!(self.out, ", {}::gradient(", NAMESPACE)?; + write!(self.out, ", {}::gradient2d(", NAMESPACE)?; self.put_expression(x, context, true)?; write!(self.out, ", ")?; self.put_expression(y, context, true)?; From b0569d9593398feece975756501758e6647f99e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 22 Aug 2021 17:29:09 +0100 Subject: [PATCH 1272/2212] [glsl-in] Add support for derivative functions --- src/front/glsl/builtins.rs | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index b1b6ae4e2..922c1af7b 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -4,9 +4,9 @@ use super::{ Error, ErrorKind, Parser, Result, SourceMetadata, }; use crate::{ - BinaryOperator, Block, Constant, ConstantInner, Expression, Handle, ImageClass, ImageDimension, - ImageQuery, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind as Sk, - ScalarValue, Span, Type, TypeInner, VectorSize, + BinaryOperator, Block, Constant, ConstantInner, DerivativeAxis, Expression, Handle, ImageClass, + ImageDimension, ImageQuery, MathFunction, Module, RelationalFunction, SampleLevel, + ScalarKind as Sk, ScalarValue, Span, Type, TypeInner, VectorSize, }; impl Module { @@ -452,7 +452,8 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module } "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" | "log" | "log2" | "radians" | "degrees" | "asinh" | "acosh" | "atanh" - | "floatBitsToInt" | "floatBitsToUint" => { + | "floatBitsToInt" | "floatBitsToUint" | "dFdx" | "dFdxFine" | "dFdxCoarse" | "dFdy" + | "dFdyFine" | "dFdyCoarse" | "fwidth" | "fwidthFine" | "fwidthCoarse" => { // bits layout // bit 0 trough 1 - dims for bits in 0..(0b100) { @@ -489,6 +490,15 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module "degrees" => MacroCall::ConstMultiply(180.0 / std::f64::consts::PI), "floatBitsToInt" => MacroCall::BitCast(Sk::Sint), "floatBitsToUint" => MacroCall::BitCast(Sk::Uint), + "dFdx" | "dFdxFine" | "dFdxCoarse" => { + MacroCall::Derivate(DerivativeAxis::X) + } + "dFdy" | "dFdyFine" | "dFdyCoarse" => { + MacroCall::Derivate(DerivativeAxis::Y) + } + "fwidth" | "fwidthFine" | "fwidthCoarse" => { + MacroCall::Derivate(DerivativeAxis::Width) + } _ => unreachable!(), }, )) @@ -1395,6 +1405,7 @@ pub enum MacroCall { Clamp(Option), ConstMultiply(f64), BitCast(Sk), + Derivate(DerivativeAxis), } impl MacroCall { @@ -1639,6 +1650,14 @@ impl MacroCall { SourceMetadata::none(), body, )), + MacroCall::Derivate(axis) => Ok(ctx.add_expression( + Expression::Derivative { + axis, + expr: args[0], + }, + SourceMetadata::none(), + body, + )), } } } From 464788dc8ddbe1fb3127a6f6baef86c319eb62de Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 23 Aug 2021 05:30:22 +0300 Subject: [PATCH 1273/2212] [hlsl-out] Implement switch statement (#1265) * [hlsl-out] Implement switch statement * [hlsl-out] Implement switch statement * Add switch tests to control-flow snapshot --- src/back/glsl/mod.rs | 5 -- src/back/hlsl/writer.rs | 57 ++++++++++++++++++- tests/in/control-flow.wgsl | 26 +++++++++ tests/out/glsl/control-flow.main.Compute.glsl | 22 ++++++- tests/out/hlsl/control-flow.hlsl | 35 +++++++++++- tests/out/msl/control-flow.msl | 31 +++++++++- tests/out/wgsl/control-flow.wgsl | 30 +++++++++- tests/snapshots.rs | 4 +- 8 files changed, 198 insertions(+), 12 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b9ba220bf..62e360bb3 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1441,11 +1441,6 @@ impl<'a, W: Write> Writer<'a, W> { for sta in case.body.iter() { self.write_stmt(sta, ctx, indent + 2)?; } - - // Write `break;` if the block isn't fallthrough - if !case.fall_through { - writeln!(self.out, "{}break;", INDENT.repeat(indent + 2))?; - } } // Only write the default block if the block isn't empty diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index d94587707..f3170c3e4 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1204,8 +1204,61 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.temp_access_chain = chain; self.named_expressions.insert(result, res_name); } - Statement::Switch { .. } => { - return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))) + Statement::Switch { + selector, + ref cases, + ref default, + } => { + // Start the switch + write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "switch(")?; + self.write_expr(module, selector, func_ctx)?; + writeln!(self.out, ") {{")?; + + // Write all cases + let indent_str_1 = INDENT.repeat(indent + 1); + let indent_str_2 = INDENT.repeat(indent + 2); + + for case in cases { + writeln!(self.out, "{}case {}: {{", &indent_str_1, case.value)?; + + if case.fall_through { + // Generate each fallthrough case statement in a new block. This is done to + // prevent symbol collision of variables declared in these cases statements. + writeln!(self.out, "{}/* fallthrough */", &indent_str_2)?; + writeln!(self.out, "{}{{", &indent_str_2)?; + } + for sta in case.body.iter() { + self.write_stmt( + module, + sta, + func_ctx, + indent + 2 + usize::from(case.fall_through), + )?; + } + + if case.fall_through { + writeln!(self.out, "{}}}", &indent_str_2)?; + } else { + writeln!(self.out, "{}break;", &indent_str_2)?; + } + + writeln!(self.out, "{}}}", &indent_str_1)?; + } + + // Only write the default block if the block isn't empty + // Writing default without a block is valid but it's more readable this way + if !default.is_empty() { + writeln!(self.out, "{}default: {{", &indent_str_1)?; + + for sta in default { + self.write_stmt(module, sta, func_ctx, indent + 2)?; + } + + writeln!(self.out, "{}}}", &indent_str_1)?; + } + + writeln!(self.out, "{}}}", INDENT.repeat(indent))? } } diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index 893546e43..6cb0f3619 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -3,4 +3,30 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { //TODO: execution-only barrier? storageBarrier(); workgroupBarrier(); + + var pos: i32; + // switch without cases + switch (1) { + default: { + pos = 1; + } + } + + switch (pos) { + case 1: { + pos = 0; + break; + } + case 2: { + pos = 1; + } + case 3: { + pos = 2; + fallthrough; + } + case 4: {} + default: { + pos = 3; + } + } } diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index d2bc4571f..fd12e4346 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -8,8 +8,28 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; void main() { uvec3 global_id = gl_GlobalInvocationID; + int pos = 0; groupMemoryBarrier(); groupMemoryBarrier(); - return; + switch(1) { + default: + pos = 1; + } + int _e4 = pos; + switch(_e4) { + case 1: + pos = 0; + break; + case 2: + pos = 1; + return; + case 3: + pos = 2; + case 4: + return; + default: + pos = 3; + return; + } } diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index 2d6810aab..b4e519241 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -6,7 +6,40 @@ struct ComputeInput_main { [numthreads(1, 1, 1)] void main(ComputeInput_main computeinput_main) { + int pos = (int)0; + DeviceMemoryBarrierWithGroupSync(); GroupMemoryBarrierWithGroupSync(); - return; + switch(1) { + default: { + pos = 1; + } + } + int _expr4 = pos; + switch(_expr4) { + case 1: { + pos = 0; + break; + break; + } + case 2: { + pos = 1; + return; + break; + } + case 3: { + /* fallthrough */ + { + pos = 2; + } + } + case 4: { + return; + break; + } + default: { + pos = 3; + return; + } + } } diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index ef3b1eee2..bd9b8d27d 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -8,7 +8,36 @@ struct main1Input { kernel void main1( metal::uint3 global_id [[thread_position_in_grid]] ) { + int pos; metal::threadgroup_barrier(metal::mem_flags::mem_device); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - return; + switch(1) { + default: { + pos = 1; + } + } + int _e4 = pos; + switch(_e4) { + case 1: { + pos = 0; + break; + break; + } + case 2: { + pos = 1; + return; + break; + } + case 3: { + pos = 2; + } + case 4: { + return; + break; + } + default: { + pos = 3; + return; + } + } } diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index 31b2fa2cb..3eb55cfd8 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -1,6 +1,34 @@ [[stage(compute), workgroup_size(1, 1, 1)]] fn main([[builtin(global_invocation_id)]] global_id: vec3) { + var pos: i32; + storageBarrier(); workgroupBarrier(); - return; + switch(1) { + default: { + pos = 1; + } + } + let _e4: i32 = pos; + switch(_e4) { + case 1: { + pos = 0; + break; + } + case 2: { + pos = 1; + return; + } + case 3: { + pos = 2; + fallthrough; + } + case 4: { + return; + } + default: { + pos = 3; + return; + } + } } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 879af0c06..023a0cc91 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -424,7 +424,9 @@ fn convert_wgsl() { ), ( "control-flow", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + // TODO: SPIRV https://github.com/gfx-rs/naga/issues/1017 + //Targets::SPIRV | + Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "standard", From 63e58f20222da13a6e50a26b4b594c0cf3369833 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 22 Aug 2021 19:31:11 -0700 Subject: [PATCH 1274/2212] [wgsl-in] Print errors nicely in convert_wgsl snapshot tests. (#1274) --- tests/snapshots.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 023a0cc91..339f944dd 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -455,7 +455,7 @@ fn convert_wgsl() { .expect("Couldn't find wgsl file"); match naga::front::wgsl::parse_str(&file) { Ok(module) => check_targets(&module, name, targets), - Err(e) => panic!("{}", e), + Err(e) => panic!("{}", e.emit_to_string(&file)), } } } From 81f4ff032f8658d1d6b1e64e567b11419ae5a373 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 22 Aug 2021 22:40:31 -0400 Subject: [PATCH 1275/2212] HLSL: rewrite handling of interface matching rules (#1276) * [hlsl-out] flatten the entry point inputs Previously, the logic was re-ordering the inputs according to the binding. This breaks if one of the inputs is a struct. With this change, the struct fields are also flattened into the fake entry point struct. We also construct the original arguments at the beginning of the function. * hlsl-out: completely separate the flattened IO structs from the original IR structs Previously, we had heuristics to detect if a particular struct needs the fields to be re-ordered. We'd re-order interface structs without layout, and the detection was very fragile and easily wrong. The new logic is spawning separate struct types if we need any re-ordering to happen. It's solid, there are no heuristics. --- src/back/hlsl/mod.rs | 4 +- src/back/hlsl/writer.rs | 490 ++++++++++++++++++++----------- tests/out/hlsl/access.hlsl | 10 +- tests/out/hlsl/boids.hlsl | 8 +- tests/out/hlsl/collatz.hlsl | 10 +- tests/out/hlsl/control-flow.hlsl | 6 +- tests/out/hlsl/image.hlsl | 16 +- tests/out/hlsl/interface.hlsl | 41 ++- tests/out/hlsl/interpolate.hlsl | 28 +- tests/out/hlsl/quad-vert.hlsl | 24 +- tests/out/hlsl/quad.hlsl | 14 +- tests/out/hlsl/shadow.hlsl | 8 +- tests/out/hlsl/skybox.hlsl | 20 +- tests/out/hlsl/standard.hlsl | 7 +- 14 files changed, 423 insertions(+), 263 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 4dc3ed6e6..242c090a5 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -164,8 +164,8 @@ pub struct Writer<'a, W> { namer: proc::Namer, /// HLSL backend options options: &'a Options, - /// Information about entry point arguments wrapped into structure - ep_inputs: Vec>, + /// Information about entry point arguments and result types. + entry_point_io: Vec, /// Set of expressions that have associated temporary variables named_expressions: crate::NamedExpressions, wrapped_array_lengths: crate::FastHashSet, diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index f3170c3e4..96740fbec 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -17,20 +17,36 @@ const SPECIAL_BASE_VERTEX: &str = "base_vertex"; const SPECIAL_BASE_INSTANCE: &str = "base_instance"; const SPECIAL_OTHER: &str = "other"; +struct EpStructMember { + name: String, + ty: Handle, + // technically, this should always be `Some` + binding: Option, + index: u32, +} + /// Structure contains information required for generating /// wrapped structure of all entry points arguments -pub(super) struct EntryPointBinding { +struct EntryPointBinding { + /// Name of the fake EP argument that contains the struct + /// with all the flattened input data. + arg_name: String, /// Generated structure name - name: String, + ty_name: String, /// Members of generated structure members: Vec, } -struct EpStructMember { - name: String, - ty: Handle, - binding: Option, - index: usize, +pub(super) struct EntryPointInterface { + /// If `Some`, the input of an entry point is gathered in a special + /// struct with members sorted by binding. + /// The `EntryPointBinding::members` array is sorted by index, + /// so that we can walk it in `write_ep_arguments_initialization`. + input: Option, + /// If `Some`, the output of an entry point is flattened. + /// The `EntryPointBinding::members` array is sorted by binding, + /// So that we can walk it in `Statement::Return` handler. + output: Option, } #[derive(Clone, Eq, PartialEq, PartialOrd, Ord)] @@ -50,19 +66,6 @@ impl InterfaceKey { } } -// Returns true for structures that need their members permuted, -// so that first come the user-defined varyings -// in ascending locations, and then built-ins. This allows VS and FS -// interfaces to match with regards to order. -fn needs_permutation(members: &[crate::StructMember]) -> bool { - //Note: this is a bit of a hack. We need to re-order the output fields, but we can only do this - // for non-layouted structures. It may be possible for an WGSL program can use the same struct - // for both host sharing and the interface. This case isn't supported here. - let has_layout = members.iter().any(|m| m.offset != 0); - let has_binding = members.iter().any(|m| m.binding.is_some()); - has_binding && !has_layout -} - #[derive(Copy, Clone, PartialEq)] enum Io { Input, @@ -76,7 +79,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { names: crate::FastHashMap::default(), namer: proc::Namer::default(), options, - ep_inputs: Vec::new(), + entry_point_io: Vec::new(), named_expressions: crate::NamedExpressions::default(), wrapped_array_lengths: crate::FastHashSet::default(), wrapped_image_queries: crate::FastHashSet::default(), @@ -88,7 +91,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.names.clear(); self.namer .reset(module, super::keywords::RESERVED, &[], &mut self.names); - self.ep_inputs.clear(); + self.entry_point_io.clear(); self.named_expressions.clear(); self.wrapped_array_lengths.clear(); self.wrapped_image_queries.clear(); @@ -199,8 +202,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write all entry points wrapped structs for ep in module.entry_points.iter() { - let ep_input = self.write_ep_input_struct(module, &ep.function, ep.stage, &ep.name)?; - self.ep_inputs.push(ep_input); + let ep_io = self.write_ep_interface(module, &ep.function, ep.stage, &ep.name)?; + self.entry_point_io.push(ep_io); } // Write all regular functions @@ -306,6 +309,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(super::ReflectionInfo { entry_point_names }) } + //TODO: we could force fragment outputs to always go through `entry_point_io.output` path + // if they are struct, so that the `stage` argument here could be omitted. fn write_semantic( &mut self, binding: &crate::Binding, @@ -328,67 +333,209 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } + fn write_interface_struct( + &mut self, + module: &Module, + shader_stage: (ShaderStage, Io), + struct_name: String, + mut members: Vec, + ) -> Result { + // Sort the members so that first come the user-defined varyings + // in ascending locations, and then built-ins. This allows VS and FS + // interfaces to match with regards to order. + members.sort_by_key(|m| InterfaceKey::new(m.binding.as_ref())); + + write!(self.out, "struct {}", struct_name)?; + writeln!(self.out, " {{")?; + for m in members.iter() { + write!(self.out, "{}", back::INDENT)?; + self.write_type(module, m.ty)?; + write!(self.out, " {}", &m.name)?; + if let Some(ref binding) = m.binding { + self.write_semantic(binding, Some(shader_stage))?; + } + writeln!(self.out, ";")?; + } + writeln!(self.out, "}};")?; + writeln!(self.out)?; + + match shader_stage.1 { + Io::Input => { + // bring back the original order + members.sort_by_key(|m| m.index); + } + Io::Output => { + // keep it sorted by binding + } + } + + Ok(EntryPointBinding { + arg_name: self.namer.call_unique(struct_name.to_lowercase().as_str()), + ty_name: struct_name, + members, + }) + } + + /// Flatten all entry point arguments into a single struct. + /// This is needed since we need to re-order them: first placing user locations, + /// then built-ins. fn write_ep_input_struct( &mut self, module: &Module, func: &crate::Function, stage: ShaderStage, entry_point_name: &str, - ) -> Result, Error> { - Ok(if !func.arguments.is_empty() { - let struct_name_prefix = match stage { - ShaderStage::Vertex => "VertexInput", - ShaderStage::Fragment => "FragmentInput", - ShaderStage::Compute => "ComputeInput", - }; - let struct_name = format!("{}_{}", struct_name_prefix, entry_point_name); + ) -> Result { + let struct_name = format!("{:?}Input_{}", stage, entry_point_name); - let mut members = Vec::with_capacity(func.arguments.len()); - for (index, arg) in func.arguments.iter().enumerate() { - let member_name = if let Some(ref name) = arg.name { - name - } else { - "member" - }; - members.push(EpStructMember { - name: self.namer.call_unique(member_name), - ty: arg.ty, - binding: arg.binding.clone(), - index, - }); - } - - // Sort the members so that first come the user-defined varyings - // in ascending locations, and then built-ins. This allows VS and FS - // interfaces to match with regards to order. - members.sort_by_key(|m| InterfaceKey::new(m.binding.as_ref())); - - write!(self.out, "struct {}", &struct_name)?; - writeln!(self.out, " {{")?; - for m in members.iter() { - write!(self.out, "{}", back::INDENT)?; - self.write_type(module, m.ty)?; - write!(self.out, " {}", &m.name)?; - if let Some(ref binding) = m.binding { - self.write_semantic(binding, Some((stage, Io::Input)))?; + let mut fake_members = Vec::new(); + for arg in func.arguments.iter() { + match module.types[arg.ty].inner { + TypeInner::Struct { ref members, .. } => { + for member in members.iter() { + let member_name = if let Some(ref name) = member.name { + name + } else { + "member" + }; + let index = fake_members.len() as u32; + fake_members.push(EpStructMember { + name: self.namer.call_unique(member_name), + ty: member.ty, + binding: member.binding.clone(), + index, + }); + } + } + _ => { + let member_name = if let Some(ref name) = arg.name { + name + } else { + "member" + }; + let index = fake_members.len() as u32; + fake_members.push(EpStructMember { + name: self.namer.call_unique(member_name), + ty: arg.ty, + binding: arg.binding.clone(), + index, + }); } - writeln!(self.out, ";")?; } - writeln!(self.out, "}};")?; - writeln!(self.out)?; + } - // now bring back the old order - members.sort_by_key(|m| m.index); + self.write_interface_struct(module, (stage, Io::Input), struct_name, fake_members) + } - Some(EntryPointBinding { - name: struct_name, - members, - }) - } else { - None + /// Flatten all entry point results into a single struct. + /// This is needed since we need to re-order them: first placing user locations, + /// then built-ins. + fn write_ep_output_struct( + &mut self, + module: &Module, + result: &crate::FunctionResult, + stage: ShaderStage, + entry_point_name: &str, + ) -> Result { + let struct_name = format!("{:?}Output_{}", stage, entry_point_name); + + let mut fake_members = Vec::new(); + let empty = []; + let members = match module.types[result.ty].inner { + TypeInner::Struct { ref members, .. } => members, + ref other => { + log::error!("Unexpected {:?} output type without a binding", other); + &empty[..] + } + }; + + for member in members.iter() { + let member_name = if let Some(ref name) = member.name { + name + } else { + "member" + }; + let index = fake_members.len() as u32; + fake_members.push(EpStructMember { + name: self.namer.call_unique(member_name), + ty: member.ty, + binding: member.binding.clone(), + index, + }); + } + + self.write_interface_struct(module, (stage, Io::Output), struct_name, fake_members) + } + + /// Writes special interface structures for an entry point. The special structures have + /// all the fields flattened into them and sorted by binding. They are only needed for + /// VS outputs and FS inputs, so that these interfaces match. + fn write_ep_interface( + &mut self, + module: &Module, + func: &crate::Function, + stage: ShaderStage, + ep_name: &str, + ) -> Result { + Ok(EntryPointInterface { + input: if !func.arguments.is_empty() && stage == ShaderStage::Fragment { + Some(self.write_ep_input_struct(module, func, stage, ep_name)?) + } else { + None + }, + output: match func.result { + Some(ref fr) if fr.binding.is_none() && stage == ShaderStage::Vertex => { + Some(self.write_ep_output_struct(module, fr, stage, ep_name)?) + } + _ => None, + }, }) } + /// Write an entry point preface that initializes the arguments as specified in IR. + fn write_ep_arguments_initialization( + &mut self, + module: &Module, + func: &crate::Function, + ep_index: u16, + ) -> BackendResult { + let ep_input = match self.entry_point_io[ep_index as usize].input.take() { + Some(ep_input) => ep_input, + None => return Ok(()), + }; + let mut fake_iter = ep_input.members.iter(); + for (arg_index, arg) in func.arguments.iter().enumerate() { + write!(self.out, "{}", back::INDENT)?; + self.write_type(module, arg.ty)?; + let arg_name = &self.names[&NameKey::EntryPointArgument(ep_index, arg_index as u32)]; + write!(self.out, " {}", arg_name)?; + match module.types[arg.ty].inner { + TypeInner::Array { size, .. } => { + self.write_array_size(module, size)?; + let fake_member = fake_iter.next().unwrap(); + writeln!(self.out, " = {}.{};", ep_input.arg_name, fake_member.name)?; + } + TypeInner::Struct { ref members, .. } => { + write!(self.out, " = {{ ")?; + for index in 0..members.len() { + if index != 0 { + write!(self.out, ", ")?; + } + let fake_member = fake_iter.next().unwrap(); + write!(self.out, "{}.{}", ep_input.arg_name, fake_member.name)?; + } + writeln!(self.out, " }};")?; + } + _ => { + let fake_member = fake_iter.next().unwrap(); + writeln!(self.out, " = {}.{};", ep_input.arg_name, fake_member.name)?; + } + } + } + assert!(fake_iter.next().is_none()); + Ok(()) + } + /// Helper method used to write global variables /// # Notes /// Always adds a newline @@ -571,28 +718,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { module: &Module, handle: Handle, _block: bool, - original_members: &[crate::StructMember], + members: &[crate::StructMember], shader_stage: Option<(ShaderStage, Io)>, ) -> BackendResult { // Write struct name - write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?; - writeln!(self.out, " {{")?; + let struct_name = &self.names[&NameKey::Type(handle)]; + writeln!(self.out, "struct {} {{", struct_name)?; - //TODO: avoid heap allocation - let mut members = original_members - .iter() - .enumerate() - .map(|(index, m)| (index, m.ty, m.binding.clone())) - .collect::>(); - if needs_permutation(original_members) { - members.sort_by_key(|&(_, _, ref binding)| InterfaceKey::new(binding.as_ref())); - } - - for (index, ty, binding) in members { + for (index, member) in members.iter().enumerate() { // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; - match module.types[ty].inner { + match module.types[member.ty].inner { TypeInner::Array { base, size, @@ -629,7 +766,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { interpolation, sampling, .. - }) = binding + }) = member.binding { if let Some(interpolation) = interpolation { write!(self.out, "{} ", interpolation.to_hlsl_str())? @@ -642,12 +779,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - if let TypeInner::Matrix { .. } = module.types[ty].inner { + if let TypeInner::Matrix { .. } = module.types[member.ty].inner { write!(self.out, "row_major ")?; } // Write the member type and name - self.write_type(module, ty)?; + self.write_type(module, member.ty)?; write!( self.out, " {}", @@ -656,7 +793,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - if let Some(ref binding) = binding { + if let Some(ref binding) = member.binding { self.write_semantic(binding, shader_stage)?; }; writeln!(self.out, ";")?; @@ -760,7 +897,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ) -> BackendResult { // Function Declaration Syntax - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-function-syntax if let Some(ref result) = func.result { - self.write_type(module, result.ty)?; + match func_ctx.ty { + back::FunctionType::Function(_) => { + self.write_type(module, result.ty)?; + } + back::FunctionType::EntryPoint(index) => { + if let Some(ref ep_output) = self.entry_point_io[index as usize].output { + write!(self.out, "{}", ep_output.ty_name)?; + } else { + self.write_type(module, result.ty)?; + } + } + } } else { write!(self.out, "void")?; } @@ -772,6 +920,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match func_ctx.ty { back::FunctionType::Function(handle) => { for (index, arg) in func.arguments.iter().enumerate() { + if index != 0 { + write!(self.out, ", ")?; + } // Write argument type let arg_ty = match module.types[arg.ty].inner { // pointers in function arguments are expected and resolve to `inout` @@ -792,31 +943,30 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if let TypeInner::Array { size, .. } = module.types[arg.ty].inner { self.write_array_size(module, size)?; } - if index < func.arguments.len() - 1 { - // Add a separator between args - write!(self.out, ", ")?; - } } } - back::FunctionType::EntryPoint(index) => { - // EntryPoint arguments wrapped into structure - // We need to ensure that entry points have arguments too. - // For the case when we working with multiple entry points - // for example vertex shader with arguments and fragment shader without arguments. - if !self.ep_inputs.is_empty() - && !module.entry_points[index as usize] - .function - .arguments - .is_empty() - { - if let Some(ref ep_input) = self.ep_inputs[index as usize] { - write!( - self.out, - "{} {}", - ep_input.name, - self.namer - .call_unique(ep_input.name.to_lowercase().as_str()) - )?; + back::FunctionType::EntryPoint(ep_index) => { + if let Some(ref ep_input) = self.entry_point_io[ep_index as usize].input { + write!(self.out, "{} {}", ep_input.ty_name, ep_input.arg_name,)?; + } else { + let stage = module.entry_points[ep_index as usize].stage; + for (index, arg) in func.arguments.iter().enumerate() { + if index != 0 { + write!(self.out, ", ")?; + } + self.write_type(module, arg.ty)?; + + let argument_name = + &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)]; + + write!(self.out, " {}", argument_name)?; + if let TypeInner::Array { size, .. } = module.types[arg.ty].inner { + self.write_array_size(module, size)?; + } + + if let Some(ref binding) = arg.binding { + self.write_semantic(binding, Some((stage, Io::Input)))?; + } } } } @@ -825,21 +975,25 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; // Write semantic if it present - let stage = match func_ctx.ty { - back::FunctionType::EntryPoint(index) => { - Some(module.entry_points[index as usize].stage) - } - _ => None, - }; - if let Some(ref result) = func.result { - if let Some(ref binding) = result.binding { - self.write_semantic(binding, stage.map(|s| (s, Io::Output)))?; + if let back::FunctionType::EntryPoint(index) = func_ctx.ty { + let stage = module.entry_points[index as usize].stage; + if let Some(crate::FunctionResult { + binding: Some(ref binding), + .. + }) = func.result + { + self.write_semantic(binding, Some((stage, Io::Output)))?; } } // Function body start writeln!(self.out)?; writeln!(self.out, "{{")?; + + if let back::FunctionType::EntryPoint(index) = func_ctx.ty { + self.write_ep_arguments_initialization(module, func, index)?; + } + // Write function local variables for (handle, local) in func.local_variables.iter() { // Write indentation (only for readability) @@ -982,22 +1136,47 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // We can safery unwrap here, since we now we working with struct let ty = base_ty_res.handle().unwrap(); let struct_name = &self.names[&NameKey::Type(ty)]; - let variable_name = self.namer.call_unique(struct_name.as_str()).to_lowercase(); + let variable_name = self.namer.call(&struct_name.to_lowercase()); write!( self.out, "{}const {} {} = ", INDENT.repeat(indent), struct_name, - variable_name + variable_name, )?; self.write_expr(module, expr, func_ctx)?; writeln!(self.out, ";")?; - writeln!( - self.out, - "{}return {};", - INDENT.repeat(indent), - variable_name - )?; + + // for entry point returns, we may need to reshuffle the outputs into a different struct + let ep_output = match func_ctx.ty { + back::FunctionType::Function(_) => None, + back::FunctionType::EntryPoint(index) => { + self.entry_point_io[index as usize].output.as_ref() + } + }; + let final_name = match ep_output { + Some(ep_output) => { + let final_name = self.namer.call_unique(&variable_name); + write!( + self.out, + "{}const {} {} = {{ ", + INDENT.repeat(indent), + ep_output.ty_name, + final_name, + )?; + for (index, m) in ep_output.members.iter().enumerate() { + if index != 0 { + write!(self.out, ", ")?; + } + let member_name = &self.names[&NameKey::StructMember(ty, m.index)]; + write!(self.out, "{}.{}", variable_name, member_name)?; + } + writeln!(self.out, " }};")?; + final_name + } + None => variable_name, + }; + writeln!(self.out, "{}return {};", INDENT.repeat(indent), final_name)?; } else { write!(self.out, "{}return ", INDENT.repeat(indent))?; self.write_expr(module, expr, func_ctx)?; @@ -1325,24 +1504,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::Compose { ty, ref components } => { - let (braces_init, permutation) = match module.types[ty].inner { - TypeInner::Struct { ref members, .. } => { - let permutation = if needs_permutation(members) { - //TODO: avoid heap allocation. We can pre-compute this at the module leve. - let mut permutation = members - .iter() - .enumerate() - .map(|(index, m)| (index, InterfaceKey::new(m.binding.as_ref()))) - .collect::>(); - permutation.sort_by_key(|&(_, ref key)| key.clone()); - Some(permutation) - } else { - None - }; - (true, permutation) - } - TypeInner::Array { .. } => (true, None), - _ => (false, None), + let braces_init = match module.types[ty].inner { + TypeInner::Struct { .. } | TypeInner::Array { .. } => true, + _ => false, }; if braces_init { @@ -1352,16 +1516,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "(")?; } - for index in 0..components.len() { + for (index, &component) in components.iter().enumerate() { if index != 0 { // The leading space is for readability only write!(self.out, ", ")?; } - let comp_index = match permutation { - Some(ref perm) => perm[index].0, - None => index, - }; - self.write_expr(module, components[comp_index], func_ctx)?; + self.write_expr(module, component, func_ctx)?; } if braces_init { @@ -1456,24 +1616,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Expression::FunctionArgument(pos) => { - match func_ctx.ty { - back::FunctionType::Function(handle) => { - let name = &self.names[&NameKey::FunctionArgument(handle, pos)]; - write!(self.out, "{}", name)?; - } + let key = match func_ctx.ty { + back::FunctionType::Function(handle) => NameKey::FunctionArgument(handle, pos), back::FunctionType::EntryPoint(index) => { - // EntryPoint arguments wrapped into structure - // We can safery unwrap here, because if we write function arguments it means, that ep_input struct already exists - let ep_input = self.ep_inputs[index as usize].as_ref().unwrap(); - let member_name = &ep_input.members[pos as usize].name; - write!( - self.out, - "{}.{}", - &ep_input.name.to_lowercase(), - member_name - )? + NameKey::EntryPointArgument(index, pos) } }; + let name = &self.names[&key]; + write!(self.out, "{}", name)?; } Expression::ImageSample { image, diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 1d9ff1ecf..9e306fcd8 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -1,10 +1,6 @@ RWByteAddressBuffer bar : register(u0); -struct VertexInput_foo { - uint vi1 : SV_VertexID; -}; - uint NagaBufferLengthRW(RWByteAddressBuffer buffer) { uint ret; @@ -12,7 +8,7 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer) return ret; } -float4 foo(VertexInput_foo vertexinput_foo) : SV_Position +float4 foo(uint vi : SV_VertexID) : SV_Position { float foo1 = 0.0; int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; @@ -41,8 +37,8 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position int _result[5]={ a, int(b), 3, 4, 5 }; for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; } - c[(vertexinput_foo.vi1 + 1u)] = 42; - int value = c[vertexinput_foo.vi1]; + c[(vi + 1u)] = 42; + int value = c[vi]; return mul(float4(int4(value.xxxx)), matrix1); } diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index 03fd86d05..9288e5c0c 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -19,12 +19,8 @@ cbuffer params : register(b0) { SimParams params; } ByteAddressBuffer particlesSrc : register(t1); RWByteAddressBuffer particlesDst : register(u2); -struct ComputeInput_main { - uint3 global_invocation_id1 : SV_DispatchThreadID; -}; - [numthreads(64, 1, 1)] -void main(ComputeInput_main computeinput_main) +void main(uint3 global_invocation_id : SV_DispatchThreadID) { float2 vPos = (float2)0; float2 vVel = (float2)0; @@ -37,7 +33,7 @@ void main(ComputeInput_main computeinput_main) float2 vel = (float2)0; uint i = 0u; - uint index = computeinput_main.global_invocation_id1.x; + uint index = global_invocation_id.x; if ((index >= NUM_PARTICLES)) { return; } diff --git a/tests/out/hlsl/collatz.hlsl b/tests/out/hlsl/collatz.hlsl index 3f85ea87e..babae9c90 100644 --- a/tests/out/hlsl/collatz.hlsl +++ b/tests/out/hlsl/collatz.hlsl @@ -1,10 +1,6 @@ RWByteAddressBuffer v_indices : register(u0); -struct ComputeInput_main { - uint3 global_id1 : SV_DispatchThreadID; -}; - uint collatz_iterations(uint n_base) { uint n = (uint)0; @@ -32,10 +28,10 @@ uint collatz_iterations(uint n_base) } [numthreads(1, 1, 1)] -void main(ComputeInput_main computeinput_main) +void main(uint3 global_id : SV_DispatchThreadID) { - uint _expr8 = asuint(v_indices.Load(computeinput_main.global_id1.x*4+0)); + uint _expr8 = asuint(v_indices.Load(global_id.x*4+0)); const uint _e9 = collatz_iterations(_expr8); - v_indices.Store(computeinput_main.global_id1.x*4+0, asuint(_e9)); + v_indices.Store(global_id.x*4+0, asuint(_e9)); return; } diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index b4e519241..020e228f0 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -1,10 +1,6 @@ -struct ComputeInput_main { - uint3 global_id1 : SV_DispatchThreadID; -}; - [numthreads(1, 1, 1)] -void main(ComputeInput_main computeinput_main) +void main(uint3 global_id : SV_DispatchThreadID) { int pos = (int)0; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index fb39bceca..d2d46cfda 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -16,10 +16,6 @@ SamplerState sampler_reg : register(s0, space1); SamplerComparisonState sampler_cmp : register(s1, space1); Texture2D image_2d_depth : register(t2, space1); -struct ComputeInput_main { - uint3 local_id1 : SV_GroupThreadID; -}; - int2 NagaRWDimensions2D(RWTexture2D texture) { uint4 ret; @@ -28,15 +24,15 @@ int2 NagaRWDimensions2D(RWTexture2D texture) } [numthreads(16, 1, 1)] -void main(ComputeInput_main computeinput_main) +void main(uint3 local_id : SV_GroupThreadID) { int2 dim = NagaRWDimensions2D(image_storage_src); - int2 itc = ((dim * int2(computeinput_main.local_id1.xy)) % int2(10, 20)); - uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(computeinput_main.local_id1.z))); - uint4 value2_ = image_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)); - float value3_ = image_depth_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)).x; + int2 itc = ((dim * int2(local_id.xy)) % int2(10, 20)); + uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(local_id.z))); + uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z)); + float value3_ = image_depth_multisampled_src.Load(itc, int(local_id.z)).x; uint4 value4_ = image_storage_src.Load(itc); - uint4 value5_ = image_array_src.Load(int4(itc, int(computeinput_main.local_id1.z), (int(computeinput_main.local_id1.z) + 1))); + uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); image_dst[itc.x] = ((((value1_ + value2_) + uint4(uint(value3_).xxxx)) + value4_) + value5_); return; } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 277a00cd0..1899fc95d 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -18,45 +18,42 @@ struct FragmentOutput { groupshared uint output[1]; -struct VertexInput_vertex { - uint color1 : LOC10; - uint instance_index1 : SV_InstanceID; - uint vertex_index1 : SV_VertexID; +struct VertexOutput_vertex { + float varying : LOC1; + float4 position : SV_Position; }; struct FragmentInput_fragment { + float varying : LOC1; + float4 position : SV_Position; bool front_facing1 : SV_IsFrontFace; uint sample_index1 : SV_SampleIndex; uint sample_mask1 : SV_Coverage; - VertexOutput in2; }; -struct ComputeInput_compute { - uint3 global_id1 : SV_DispatchThreadID; - uint3 local_id1 : SV_GroupThreadID; - uint local_index1 : SV_GroupIndex; - uint3 wg_id1 : SV_GroupID; - uint3 num_wgs1 : SV_GroupID; -}; - -VertexOutput vertex(VertexInput_vertex vertexinput_vertex) +VertexOutput_vertex vertex(uint vertex_index : SV_VertexID, uint instance_index : SV_InstanceID, uint color : LOC10) { - uint tmp = (((_NagaConstants.base_vertex + vertexinput_vertex.vertex_index1) + (_NagaConstants.base_instance + vertexinput_vertex.instance_index1)) + vertexinput_vertex.color1); - const VertexOutput vertexoutput1 = { float4(1.0.xxxx), float(tmp) }; + uint tmp = (((_NagaConstants.base_vertex + vertex_index) + (_NagaConstants.base_instance + instance_index)) + color); + const VertexOutput vertexoutput = { float4(1.0.xxxx), float(tmp) }; + const VertexOutput_vertex vertexoutput1 = { vertexoutput.varying, vertexoutput.position }; return vertexoutput1; } FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) { - uint mask = (fragmentinput_fragment.sample_mask1 & (1u << fragmentinput_fragment.sample_index1)); - float color2 = (fragmentinput_fragment.front_facing1 ? 1.0 : 0.0); - const FragmentOutput fragmentoutput1 = { fragmentinput_fragment.in2.varying, mask, color2 }; - return fragmentoutput1; + VertexOutput in1 = { fragmentinput_fragment.position, fragmentinput_fragment.varying }; + bool front_facing = fragmentinput_fragment.front_facing1; + uint sample_index = fragmentinput_fragment.sample_index1; + uint sample_mask = fragmentinput_fragment.sample_mask1; + uint mask = (sample_mask & (1u << sample_index)); + float color1 = (front_facing ? 1.0 : 0.0); + const FragmentOutput fragmentoutput = { in1.varying, mask, color1 }; + return fragmentoutput; } [numthreads(1, 1, 1)] -void compute(ComputeInput_compute computeinput_compute) +void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThreadID, uint local_index : SV_GroupIndex, uint3 wg_id : SV_GroupID, uint3 num_wgs : SV_GroupID) { - output[0] = ((((computeinput_compute.global_id1.x + computeinput_compute.local_id1.x) + computeinput_compute.local_index1) + computeinput_compute.wg_id1.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x); + output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x); return; } diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index 555727e2c..f4c56957c 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -10,11 +10,29 @@ struct FragmentInput { linear sample float perspective_sample : LOC6; }; -struct FragmentInput_main { - FragmentInput val1; +struct VertexOutput_main { + uint flat : LOC0; + float linear1 : LOC1; + float2 linear_centroid : LOC2; + float3 linear_sample : LOC3; + float4 perspective : LOC4; + float perspective_centroid : LOC5; + float perspective_sample : LOC6; + float4 position : SV_Position; }; -FragmentInput main() +struct FragmentInput_main { + uint flat : LOC0; + float linear2 : LOC1; + float2 linear_centroid : LOC2; + float3 linear_sample : LOC3; + float4 perspective : LOC4; + float perspective_centroid : LOC5; + float perspective_sample : LOC6; + float4 position : SV_Position; +}; + +VertexOutput_main main() { FragmentInput out1 = (FragmentInput)0; @@ -27,11 +45,13 @@ FragmentInput main() out1.perspective_centroid = 2197.0; out1.perspective_sample = 2744.0; FragmentInput _expr30 = out1; - const FragmentInput fragmentinput1 = _expr30; + const FragmentInput fragmentinput = _expr30; + const VertexOutput_main fragmentinput1 = { fragmentinput.flat, fragmentinput.linear1, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position }; return fragmentinput1; } void main1(FragmentInput_main fragmentinput_main) { + FragmentInput val = { fragmentinput_main.position, fragmentinput_main.flat, fragmentinput_main.linear2, fragmentinput_main.linear_centroid, fragmentinput_main.linear_sample, fragmentinput_main.perspective, fragmentinput_main.perspective_centroid, fragmentinput_main.perspective_sample }; return; } diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index d190a05e5..a5cce3fcd 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -1,17 +1,17 @@ struct gl_PerVertex { float4 gl_Position : SV_Position; + float gl_PointSize : PSIZE; float gl_ClipDistance[1] : SV_ClipDistance; float gl_CullDistance[1] : SV_CullDistance; - float gl_PointSize : PSIZE; }; struct type10 { linear float2 member : LOC0; float4 gl_Position : SV_Position; + float gl_PointSize : PSIZE; float gl_ClipDistance[1] : SV_ClipDistance; float gl_CullDistance[1] : SV_CullDistance; - float gl_PointSize : PSIZE; }; static float2 v_uv = (float2)0; @@ -19,9 +19,12 @@ static float2 a_uv1 = (float2)0; static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, { 0.0 }, { 0.0 } }; static float2 a_pos1 = (float2)0; -struct VertexInput_main { - float2 a_pos2 : LOC0; - float2 a_uv2 : LOC1; +struct VertexOutput_main { + float2 member : LOC0; + float4 gl_Position : SV_Position; + float gl_ClipDistance : SV_ClipDistance; + float gl_CullDistance : SV_CullDistance; + float gl_PointSize : PSIZE; }; void main1() @@ -33,16 +36,17 @@ void main1() return; } -type10 main(VertexInput_main vertexinput_main) +VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0) { - a_uv1 = vertexinput_main.a_uv2; - a_pos1 = vertexinput_main.a_pos2; + a_uv1 = a_uv; + a_pos1 = a_pos; main1(); float2 _expr10 = v_uv; float4 _expr11 = perVertexStruct.gl_Position; float _expr12 = perVertexStruct.gl_PointSize; float _expr13[1] = perVertexStruct.gl_ClipDistance; float _expr14[1] = perVertexStruct.gl_CullDistance; - const type10 type10_ = { _expr10, _expr11, _expr13, _expr14, _expr12 }; - return type10_; + const type10 type10_ = { _expr10, _expr11, _expr12, _expr13, _expr14 }; + const VertexOutput_main type10_1 = { type10_.member, type10_.gl_Position, type10_.gl_ClipDistance, type10_.gl_CullDistance, type10_.gl_PointSize }; + return type10_1; } diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index 90cd39274..2aba7768e 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -8,24 +8,26 @@ struct VertexOutput { Texture2D u_texture : register(t0); SamplerState u_sampler : register(s1); -struct VertexInput_main { - float2 pos1 : LOC0; - float2 uv2 : LOC1; +struct VertexOutput_main { + float2 uv2 : LOC0; + float4 position : SV_Position; }; struct FragmentInput_main { float2 uv3 : LOC0; }; -VertexOutput main(VertexInput_main vertexinput_main) +VertexOutput_main main(float2 pos : LOC0, float2 uv : LOC1) { - const VertexOutput vertexoutput1 = { vertexinput_main.uv2, float4((c_scale * vertexinput_main.pos1), 0.0, 1.0) }; + const VertexOutput vertexoutput = { uv, float4((c_scale * pos), 0.0, 1.0) }; + const VertexOutput_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position }; return vertexoutput1; } float4 main1(FragmentInput_main fragmentinput_main) : SV_Target0 { - float4 color = u_texture.Sample(u_sampler, fragmentinput_main.uv3); + float2 uv1 = fragmentinput_main.uv3; + float4 color = u_texture.Sample(u_sampler, uv1); if ((color.w == 0.0)) { discard; } diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 742c41cbd..85cdbf88f 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -34,10 +34,12 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords) float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { + float3 raw_normal = fragmentinput_fs_main.raw_normal1; + float4 position = fragmentinput_fs_main.position1; float3 color = float3(0.05, 0.05, 0.05); uint i = 0u; - float3 normal = normalize(fragmentinput_fs_main.raw_normal1); + float3 normal = normalize(raw_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -53,8 +55,8 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 uint _expr19 = i; Light light = {float4x4(asfloat(s_lights.Load4(_expr19*96+0+0+0)), asfloat(s_lights.Load4(_expr19*96+0+0+16)), asfloat(s_lights.Load4(_expr19*96+0+0+32)), asfloat(s_lights.Load4(_expr19*96+0+0+48))), asfloat(s_lights.Load4(_expr19*96+0+64)), asfloat(s_lights.Load4(_expr19*96+0+80))}; uint _expr22 = i; - const float _e25 = fetch_shadow(_expr22, mul(fragmentinput_fs_main.position1, light.proj)); - float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz)); + const float _e25 = fetch_shadow(_expr22, mul(position, light.proj)); + float3 light_dir = normalize((light.pos.xyz - position.xyz)); float diffuse = max(0.0, dot(normal, light_dir)); float3 _expr34 = color; color = (_expr34 + ((_e25 * diffuse) * light.color.xyz)); diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 36ec009f5..dd58f0240 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -19,21 +19,23 @@ cbuffer r_data : register(b0) { Data r_data; } TextureCube r_texture : register(t0); SamplerState r_sampler : register(s0, space1); -struct VertexInput_vs_main { - uint vertex_index1 : SV_VertexID; +struct VertexOutput_vs_main { + float3 uv : LOC0; + float4 position : SV_Position; }; struct FragmentInput_fs_main { - VertexOutput in2; + float3 uv : LOC0; + float4 position : SV_Position; }; -VertexOutput vs_main(VertexInput_vs_main vertexinput_vs_main) +VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) { int tmp1_ = (int)0; int tmp2_ = (int)0; - tmp1_ = (int((_NagaConstants.base_vertex + vertexinput_vs_main.vertex_index1)) / 2); - tmp2_ = (int((_NagaConstants.base_vertex + vertexinput_vs_main.vertex_index1)) & 1); + tmp1_ = (int((_NagaConstants.base_vertex + vertex_index)) / 2); + tmp2_ = (int((_NagaConstants.base_vertex + vertex_index)) & 1); int _expr10 = tmp1_; int _expr16 = tmp2_; float4 pos = float4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); @@ -43,12 +45,14 @@ VertexOutput vs_main(VertexInput_vs_main vertexinput_vs_main) float3x3 inv_model_view = transpose(float3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz)); float4x4 _expr40 = r_data.proj_inv; float4 unprojected = mul(pos, _expr40); - const VertexOutput vertexoutput1 = { pos, mul(unprojected.xyz, inv_model_view) }; + const VertexOutput vertexoutput = { pos, mul(unprojected.xyz, inv_model_view) }; + const VertexOutput_vs_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position }; return vertexoutput1; } float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { - float4 _expr5 = r_texture.Sample(r_sampler, fragmentinput_fs_main.in2.uv); + VertexOutput in1 = { fragmentinput_fs_main.position, fragmentinput_fs_main.uv }; + float4 _expr5 = r_texture.Sample(r_sampler, in1.uv); return _expr5; } diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl index 7f0bed219..e70e87f57 100644 --- a/tests/out/hlsl/standard.hlsl +++ b/tests/out/hlsl/standard.hlsl @@ -5,8 +5,9 @@ struct FragmentInput_derivatives { float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Target0 { - float4 x = ddx(fragmentinput_derivatives.foo1); - float4 y = ddy(fragmentinput_derivatives.foo1); - float4 z = fwidth(fragmentinput_derivatives.foo1); + float4 foo = fragmentinput_derivatives.foo1; + float4 x = ddx(foo); + float4 y = ddy(foo); + float4 z = fwidth(foo); return ((x + y) * z); } From fd10b7d9e80a340acc4e4fda099d527343c0062d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 23 Aug 2021 03:43:52 +0100 Subject: [PATCH 1276/2212] [glsl-out] Modulo operator on float must be converted to mod function (#1271) Fixes #1266 --- src/back/glsl/mod.rs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 62e360bb3..b3075c9e7 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2112,13 +2112,13 @@ impl<'a, W: Write> Writer<'a, W> { Expression::Binary { op, left, right } => { // Holds `Some(function_name)` if the binary operation is // implemented as a function call - use crate::BinaryOperator as Bo; + use crate::{BinaryOperator as Bo, ScalarKind as Sk, TypeInner as Ti}; - let function = if let (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) = ( - ctx.info[left].ty.inner_with(&self.module.types), - ctx.info[right].ty.inner_with(&self.module.types), - ) { - match op { + let left_inner = ctx.info[left].ty.inner_with(&self.module.types); + let right_inner = ctx.info[right].ty.inner_with(&self.module.types); + + let function = match (left_inner, right_inner) { + (&Ti::Vector { .. }, &Ti::Vector { .. }) => match op { Bo::Less => Some("lessThan"), Bo::LessEqual => Some("lessThanEqual"), Bo::Greater => Some("greaterThan"), @@ -2126,9 +2126,14 @@ impl<'a, W: Write> Writer<'a, W> { Bo::Equal => Some("equal"), Bo::NotEqual => Some("notEqual"), _ => None, - } - } else { - None + }, + _ => match (left_inner.scalar_kind(), right_inner.scalar_kind()) { + (Some(Sk::Float), _) | (_, Some(Sk::Float)) => match op { + Bo::Modulo => Some("mod"), + _ => None, + }, + _ => None, + }, }; write!(self.out, "{}(", function.unwrap_or(""))?; From de114e479b8999937e856400c31f3e46b98d02b3 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 22 Aug 2021 12:52:27 -0700 Subject: [PATCH 1277/2212] Rename `IndexBoundsCheckPolicy` to `BoundsCheckPolicy`. --- cli/src/main.rs | 18 +++++++++--------- src/back/mod.rs | 8 ++++---- src/back/spv/index.rs | 24 +++++++++++------------- src/back/spv/mod.rs | 8 ++++---- tests/in/bounds-check-zero.wgsl | 2 +- tests/snapshots.rs | 8 ++++---- 6 files changed, 33 insertions(+), 35 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index d5ef5ccc4..8930791d3 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -14,7 +14,7 @@ struct Args { /// /// May be `Restrict`, `ReadZeroSkipWrite`, or `UndefinedBehavior` #[argh(option)] - index_bounds_check_policy: Option, + index_bounds_check_policy: Option, /// directory to dump the SPIR-V flow dump to #[argh(option)] @@ -43,19 +43,19 @@ struct Args { output: Vec, } -/// Newtype so we can implement [`FromStr`] for `IndexBoundsCheckPolicy`. +/// Newtype so we can implement [`FromStr`] for `BoundsCheckPolicy`. #[derive(Debug, Clone)] -struct IndexBoundsCheckPolicyArg(naga::back::IndexBoundsCheckPolicy); +struct BoundsCheckPolicyArg(naga::back::BoundsCheckPolicy); -impl FromStr for IndexBoundsCheckPolicyArg { +impl FromStr for BoundsCheckPolicyArg { type Err = String; fn from_str(s: &str) -> Result { - use naga::back::IndexBoundsCheckPolicy; + use naga::back::BoundsCheckPolicy; Ok(Self(match s.to_lowercase().as_str() { - "restrict" => IndexBoundsCheckPolicy::Restrict, - "readzeroskipwrite" => IndexBoundsCheckPolicy::ReadZeroSkipWrite, - "undefinedbehavior" => IndexBoundsCheckPolicy::UndefinedBehavior, + "restrict" => BoundsCheckPolicy::Restrict, + "readzeroskipwrite" => BoundsCheckPolicy::ReadZeroSkipWrite, + "undefinedbehavior" => BoundsCheckPolicy::UndefinedBehavior, _ => { return Err(format!( "Invalid value for --index-bounds-check-policy: {}", @@ -106,7 +106,7 @@ impl FromStr for GlslProfileArg { #[derive(Default)] struct Parameters { validation_flags: naga::valid::ValidationFlags, - index_bounds_check_policy: naga::back::IndexBoundsCheckPolicy, + index_bounds_check_policy: naga::back::BoundsCheckPolicy, entry_point: Option, spv_adjust_coordinate_space: bool, spv_flow_dump_prefix: Option, diff --git a/src/back/mod.rs b/src/back/mod.rs index e753e7aa5..7ac135f9d 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -123,7 +123,7 @@ impl<'a> FunctionCtx<'_> { /// - Naga's own default is `UndefinedBehavior`, so that shader translations /// are as faithful to the original as possible. #[derive(Clone, Copy, Debug)] -pub enum IndexBoundsCheckPolicy { +pub enum BoundsCheckPolicy { /// Replace out-of-bounds indexes with some arbitrary in-bounds index. /// /// (This does not necessarily mean clamping. For example, interpreting the @@ -141,10 +141,10 @@ pub enum IndexBoundsCheckPolicy { UndefinedBehavior, } -/// The default `IndexBoundsCheckPolicy` is `UndefinedBehavior`. -impl Default for IndexBoundsCheckPolicy { +/// The default `BoundsCheckPolicy` is `UndefinedBehavior`. +impl Default for BoundsCheckPolicy { fn default() -> Self { - IndexBoundsCheckPolicy::UndefinedBehavior + BoundsCheckPolicy::UndefinedBehavior } } diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index a6b4b0dd2..e82e71972 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -1,7 +1,7 @@ //! Bounds-checking for SPIR-V output. use super::{Block, BlockContext, Error, IdGenerator, Instruction, Word}; -use crate::{arena::Handle, back::IndexBoundsCheckPolicy}; +use crate::{arena::Handle, back::BoundsCheckPolicy}; /// The results of emitting code for a left-hand-side expression. /// @@ -157,11 +157,11 @@ impl<'w> BlockContext<'w> { /// Restrict an index to be in range for a vector, matrix, or array. /// - /// This is used to implement `IndexBoundsCheckPolicy::Restrict`. An - /// in-bounds index is left unchanged. An out-of-bounds index is replaced - /// with some arbitrary in-bounds index. Note,this is not necessarily - /// clamping; for example, negative indices might be changed to refer to the - /// last element of the sequence, not the first, as clamping would do. + /// This is used to implement `BoundsCheckPolicy::Restrict`. An in-bounds + /// index is left unchanged. An out-of-bounds index is replaced with some + /// arbitrary in-bounds index. Note,this is not necessarily clamping; for + /// example, negative indices might be changed to refer to the last element + /// of the sequence, not the first, as clamping would do. /// /// Either return the restricted index value, if known, or add instructions /// to `block` to compute it, and return the id of the result. See the @@ -202,7 +202,7 @@ impl<'w> BlockContext<'w> { }; // One or the other of the index or length is dynamic, so emit code for - // IndexBoundsCheckPolicy::Restrict. + // BoundsCheckPolicy::Restrict. let restricted_index_id = self.gen_id(); block.body.push(Instruction::ext_inst( self.writer.gl450_ext_inst_id, @@ -290,7 +290,7 @@ impl<'w> BlockContext<'w> { Ok(BoundsCheckResult::Conditional(condition_id)) } - /// Emit a conditional load for `IndexBoundsCheckPolicy::ReadZeroSkipWrite`. + /// Emit a conditional load for `BoundsCheckPolicy::ReadZeroSkipWrite`. /// /// Generate code to load a value of `result_type` if `condition` is true, /// and generate a null value of that type if it is false. Call `emit_load` @@ -362,13 +362,11 @@ impl<'w> BlockContext<'w> { block: &mut Block, ) -> Result { Ok(match self.writer.index_bounds_check_policy { - IndexBoundsCheckPolicy::Restrict => self.write_restricted_index(base, index, block)?, - IndexBoundsCheckPolicy::ReadZeroSkipWrite => { + BoundsCheckPolicy::Restrict => self.write_restricted_index(base, index, block)?, + BoundsCheckPolicy::ReadZeroSkipWrite => { self.write_index_comparison(base, index, block)? } - IndexBoundsCheckPolicy::UndefinedBehavior => { - BoundsCheckResult::Computed(self.cached[index]) - } + BoundsCheckPolicy::UndefinedBehavior => BoundsCheckResult::Computed(self.cached[index]), }) } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index bd52a0377..0d871ac3d 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -11,7 +11,7 @@ mod writer; pub use spirv::Capability; -use crate::{arena::Handle, back::IndexBoundsCheckPolicy, proc::TypeResolution}; +use crate::{arena::Handle, back::BoundsCheckPolicy, proc::TypeResolution}; use spirv::Word; use std::ops; @@ -400,7 +400,7 @@ pub struct Writer { debugs: Vec, annotations: Vec, flags: WriterFlags, - index_bounds_check_policy: IndexBoundsCheckPolicy, + index_bounds_check_policy: BoundsCheckPolicy, void_type: Word, //TODO: convert most of these into vectors, addressable by handle indices lookup_type: crate::FastHashMap, @@ -444,7 +444,7 @@ pub struct Options { /// How should the generated code handle array, vector, or matrix indices /// that are out of range? - pub index_bounds_check_policy: IndexBoundsCheckPolicy, + pub index_bounds_check_policy: BoundsCheckPolicy, } impl Default for Options { @@ -457,7 +457,7 @@ impl Default for Options { lang_version: (1, 0), flags, capabilities: None, - index_bounds_check_policy: super::IndexBoundsCheckPolicy::default(), + index_bounds_check_policy: super::BoundsCheckPolicy::default(), } } } diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl index 773a1788f..74811c12b 100644 --- a/tests/in/bounds-check-zero.wgsl +++ b/tests/in/bounds-check-zero.wgsl @@ -1,4 +1,4 @@ -// Tests for `naga::back::IndexBoundsCheckPolicy::ReadZeroSkipWrite`. +// Tests for `naga::back::BoundsCheckPolicy::ReadZeroSkipWrite`. [[block]] struct Globals { diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 339f944dd..9d917f47d 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -24,7 +24,7 @@ struct Parameters { #[serde(default)] god_mode: bool, - // We can only deserialize `IndexBoundsCheckPolicy` values if `deserialize` + // We can only deserialize `BoundsCheckPolicy` values if `deserialize` // feature was enabled, but features should not affect snapshot contents, so // just take the policy as booleans instead. #[serde(default)] @@ -166,11 +166,11 @@ fn write_output_spv( Some(params.spv_capabilities.clone()) }, index_bounds_check_policy: if params.bounds_check_restrict { - naga::back::IndexBoundsCheckPolicy::Restrict + naga::back::BoundsCheckPolicy::Restrict } else if params.bounds_check_read_zero_skip_write { - naga::back::IndexBoundsCheckPolicy::ReadZeroSkipWrite + naga::back::BoundsCheckPolicy::ReadZeroSkipWrite } else { - naga::back::IndexBoundsCheckPolicy::UndefinedBehavior + naga::back::BoundsCheckPolicy::UndefinedBehavior }, }; From c1121a1e622fe5444738ba3aca223d4da3d0e200 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 22 Aug 2021 13:27:32 -0700 Subject: [PATCH 1278/2212] [spv-out] Use 'image' instead of 'texture', consistent with SPIR-V. --- src/back/spv/block.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 49827a2eb..eb6b020c4 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -90,7 +90,7 @@ impl<'w> BlockContext<'w> { self.writer.get_type_id(lookup_type) } - /// Extend texture coordinates with an array index, if necessary. + /// Extend image coordinates with an array index, if necessary. /// /// Whereas [`Expression::ImageLoad`] and [`ImageSample`] treat the array /// index as a separate operand from the coordinates, SPIR-V image access @@ -113,7 +113,7 @@ impl<'w> BlockContext<'w> { /// /// [`Expression::ImageLoad`]: crate::Expression::ImageLoad /// [`ImageSample`]: crate::Expression::ImageSample - fn write_texture_coordinates( + fn write_image_coordinates( &mut self, coordinates: Handle, array_index: Option>, @@ -124,7 +124,7 @@ impl<'w> BlockContext<'w> { let coordinate_id = self.cached[coordinates]; - // If there's no array index, the texture coordinates are exactly the + // If there's no array index, the image coordinates are exactly the // `coordinate` field of the `Expression::ImageLoad`. No work is needed. let array_index = match array_index { None => return Ok(coordinate_id), @@ -805,8 +805,7 @@ impl<'w> BlockContext<'w> { index, } => { let image_id = self.get_image_id(image); - let coordinate_id = - self.write_texture_coordinates(coordinate, array_index, block)?; + let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; let id = self.gen_id(); @@ -906,8 +905,7 @@ impl<'w> BlockContext<'w> { self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id })); let sampler_id = self.get_image_id(sampler); - let coordinate_id = - self.write_texture_coordinates(coordinate, array_index, block)?; + let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; let sampled_image_id = self.gen_id(); block.body.push(Instruction::sampled_image( @@ -1687,7 +1685,7 @@ impl<'w> BlockContext<'w> { } => { let image_id = self.get_image_id(image); let coordinate_id = - self.write_texture_coordinates(coordinate, array_index, &mut block)?; + self.write_image_coordinates(coordinate, array_index, &mut block)?; let value_id = self.cached[value]; block From 3f4cd9dc8885e575738ea99b4b2b58c37cab1e21 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 10 Jul 2021 15:36:57 -0700 Subject: [PATCH 1279/2212] [spv-out] Add GlobalVariable helper functions. --- src/back/spv/mod.rs | 11 +++++++++++ src/back/spv/writer.rs | 5 ++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 0d871ac3d..32c8ecb4c 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -324,6 +324,17 @@ struct GlobalVariable { handle_id: Word, } +impl GlobalVariable { + fn new(id: Word) -> GlobalVariable { + GlobalVariable { id, handle_id: 0 } + } + + /// Prepare `self` for use within a single function. + fn reset_for_function(&mut self) { + self.handle_id = 0; + } +} + struct FunctionArgument { /// Actual instruction of the argument. instruction: Instruction, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 6a0c634cd..5a82bae5b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -422,7 +422,7 @@ impl Writer { // fill up the `GlobalVariable::handle_id` for gv in self.global_variables.iter_mut() { - gv.handle_id = 0; + gv.reset_for_function(); } for (handle, var) in ir_module.global_variables.iter() { // Handle globals are pre-emitted and should be loaded automatically. @@ -1248,8 +1248,7 @@ impl Writer { for (_, var) in ir_module.global_variables.iter() { let (instruction, id) = self.write_global_variable(ir_module, var)?; instruction.to_words(&mut self.logical_layout.declarations); - self.global_variables - .push(GlobalVariable { id, handle_id: 0 }); + self.global_variables.push(GlobalVariable::new(id)); } // all functions From 99de38730205b80d767dcfc188a8ca10671e8cc4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 13 Jul 2021 15:10:08 -0700 Subject: [PATCH 1280/2212] [spv-out] Move image operations into their own module. For ease of review, there should be no meaningful code changes in this commit. Match arms are merely moved out into their own functions, whose arguments are the enum variant's fields, along with any free variables from the function containing the match. --- src/back/spv/block.rs | 510 ++------------------------------------ src/back/spv/image.rs | 553 ++++++++++++++++++++++++++++++++++++++++++ src/back/spv/mod.rs | 5 + 3 files changed, 572 insertions(+), 496 deletions(-) create mode 100644 src/back/spv/image.rs diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index eb6b020c4..904340fde 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -86,117 +86,6 @@ impl Writer { } impl<'w> BlockContext<'w> { - fn get_type_id(&mut self, lookup_type: LookupType) -> Word { - self.writer.get_type_id(lookup_type) - } - - /// Extend image coordinates with an array index, if necessary. - /// - /// Whereas [`Expression::ImageLoad`] and [`ImageSample`] treat the array - /// index as a separate operand from the coordinates, SPIR-V image access - /// instructions include the array index in the `coordinates` operand. This - /// function builds a SPIR-V coordinate vector from a Naga coordinate vector - /// and array index. - /// - /// If `array_index` is `Some(expr)`, then this function constructs a new - /// vector that is `coordinates` with `array_index` concatenated onto the - /// end: a `vec2` becomes a `vec3`, a scalar becomes a `vec2`, and so on. - /// - /// Naga's `ImageLoad` and SPIR-V's `OpImageRead`, `OpImageFetch`, and - /// `OpImageWrite` all use integer coordinates, while Naga's `ImageSample` - /// and SPIR-V's `OpImageSample...` instructions all take floating-point - /// coordinate vectors. The array index, always an integer scalar, may need - /// to be converted to match the component type of `coordinates`. - /// - /// If `array_index` is `None`, this function simply returns the id for - /// `coordinates`. - /// - /// [`Expression::ImageLoad`]: crate::Expression::ImageLoad - /// [`ImageSample`]: crate::Expression::ImageSample - fn write_image_coordinates( - &mut self, - coordinates: Handle, - array_index: Option>, - block: &mut Block, - ) -> Result { - use crate::TypeInner as Ti; - use crate::VectorSize as Vs; - - let coordinate_id = self.cached[coordinates]; - - // If there's no array index, the image coordinates are exactly the - // `coordinate` field of the `Expression::ImageLoad`. No work is needed. - let array_index = match array_index { - None => return Ok(coordinate_id), - Some(ix) => ix, - }; - - // Find the component type of `coordinates`, and figure out the size the - // combined coordinate vector will have. - let (component_kind, result_size) = match *self.fun_info[coordinates] - .ty - .inner_with(&self.ir_module.types) - { - Ti::Scalar { kind, width: 4 } => (kind, Vs::Bi), - Ti::Vector { - kind, - width: 4, - size: Vs::Bi, - } => (kind, Vs::Tri), - Ti::Vector { - kind, - width: 4, - size: Vs::Tri, - } => (kind, Vs::Quad), - Ti::Vector { size: Vs::Quad, .. } => { - return Err(Error::Validation("extending vec4 coordinate")); - } - ref other => { - log::error!("wrong coordinate type {:?}", other); - return Err(Error::Validation("coordinate type")); - } - }; - - // Convert the index to the coordinate component type, if necessary. - let array_index_i32_id = self.cached[array_index]; - let reconciled_array_index_id = if component_kind == crate::ScalarKind::Sint { - array_index_i32_id - } else { - let component_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: component_kind, - width: 4, - pointer_class: None, - })); - - let reconciled_id = self.gen_id(); - block.body.push(Instruction::unary( - spirv::Op::ConvertUToF, - component_type_id, - reconciled_id, - array_index_i32_id, - )); - reconciled_id - }; - - // Find the SPIR-V type for the combined coordinates/index vector. - let combined_coordinate_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(result_size), - kind: component_kind, - width: 4, - pointer_class: None, - })); - - // Schmear the coordinates and index together. - let id = self.gen_id(); - block.body.push(Instruction::composite_construct( - combined_coordinate_type_id, - id, - &[coordinate_id, reconciled_array_index_id], - )); - Ok(id) - } - /// Decide whether to put off emitting instructions for `expr_handle`. /// /// We would like to gather together chains of `Access` and `AccessIndex` @@ -804,67 +693,7 @@ impl<'w> BlockContext<'w> { array_index, index, } => { - let image_id = self.get_image_id(image); - let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; - - let id = self.gen_id(); - - let image_ty = self.fun_info[image].ty.inner_with(&self.ir_module.types); - let mut instruction = match *image_ty { - crate::TypeInner::Image { - class: crate::ImageClass::Storage { .. }, - .. - } => Instruction::image_read(result_type_id, id, image_id, coordinate_id), - crate::TypeInner::Image { - class: crate::ImageClass::Depth { multi: _ }, - .. - } => { - // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, - // so we need to grab the first component out of it. - let load_result_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(crate::VectorSize::Quad), - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - })); - Instruction::image_fetch(load_result_type_id, id, image_id, coordinate_id) - } - _ => Instruction::image_fetch(result_type_id, id, image_id, coordinate_id), - }; - - if let Some(index) = index { - let index_id = self.cached[index]; - let image_ops = match *self.fun_info[image].ty.inner_with(&self.ir_module.types) - { - crate::TypeInner::Image { - class: crate::ImageClass::Sampled { multi: true, .. }, - .. - } - | crate::TypeInner::Image { - class: crate::ImageClass::Depth { multi: true }, - .. - } => spirv::ImageOperands::SAMPLE, - _ => spirv::ImageOperands::LOD, - }; - instruction.add_operand(image_ops.bits()); - instruction.add_operand(index_id); - } - - let inst_type_id = instruction.type_id; - block.body.push(instruction); - if inst_type_id != Some(result_type_id) { - let sub_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - result_type_id, - sub_id, - id, - &[0], - )); - sub_id - } else { - id - } + self.write_image_load(result_type_id, image, coordinate, array_index, index, block)? } crate::Expression::ImageSample { image, @@ -874,162 +703,17 @@ impl<'w> BlockContext<'w> { offset, level, depth_ref, - } => { - use super::instructions::SampleLod; - // image - let image_id = self.get_image_id(image); - let image_type = self.fun_info[image].ty.handle().unwrap(); - // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, - // so we need to grab the first component out of it. - let needs_sub_access = match self.ir_module.types[image_type].inner { - crate::TypeInner::Image { - class: crate::ImageClass::Depth { .. }, - .. - } => depth_ref.is_none(), - _ => false, - }; - let sample_result_type_id = if needs_sub_access { - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(crate::VectorSize::Quad), - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - })) - } else { - result_type_id - }; - - // OpTypeSampledImage - let image_type_id = self.get_type_id(LookupType::Handle(image_type)); - let sampled_image_type_id = - self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id })); - - let sampler_id = self.get_image_id(sampler); - let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; - - let sampled_image_id = self.gen_id(); - block.body.push(Instruction::sampled_image( - sampled_image_type_id, - sampled_image_id, - image_id, - sampler_id, - )); - let id = self.gen_id(); - - let depth_id = depth_ref.map(|handle| self.cached[handle]); - let mut mask = spirv::ImageOperands::empty(); - mask.set(spirv::ImageOperands::CONST_OFFSET, offset.is_some()); - - let mut main_instruction = match level { - crate::SampleLevel::Zero => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Explicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - - let zero_id = self - .writer - .get_constant_scalar(crate::ScalarValue::Float(0.0), 4); - - mask |= spirv::ImageOperands::LOD; - inst.add_operand(mask.bits()); - inst.add_operand(zero_id); - - inst - } - crate::SampleLevel::Auto => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Implicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - if !mask.is_empty() { - inst.add_operand(mask.bits()); - } - inst - } - crate::SampleLevel::Exact(lod_handle) => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Explicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - - let lod_id = self.cached[lod_handle]; - mask |= spirv::ImageOperands::LOD; - inst.add_operand(mask.bits()); - inst.add_operand(lod_id); - - inst - } - crate::SampleLevel::Bias(bias_handle) => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Implicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - - let bias_id = self.cached[bias_handle]; - mask |= spirv::ImageOperands::BIAS; - inst.add_operand(mask.bits()); - inst.add_operand(bias_id); - - inst - } - crate::SampleLevel::Gradient { x, y } => { - let mut inst = Instruction::image_sample( - sample_result_type_id, - id, - SampleLod::Explicit, - sampled_image_id, - coordinate_id, - depth_id, - ); - - let x_id = self.cached[x]; - let y_id = self.cached[y]; - mask |= spirv::ImageOperands::GRAD; - inst.add_operand(mask.bits()); - inst.add_operand(x_id); - inst.add_operand(y_id); - - inst - } - }; - - if let Some(offset_const) = offset { - let offset_id = self.writer.constant_ids[offset_const.index()]; - main_instruction.add_operand(offset_id); - } - - block.body.push(main_instruction); - - if needs_sub_access { - let sub_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - result_type_id, - sub_id, - id, - &[0], - )); - sub_id - } else { - id - } - } + } => self.write_image_sample( + result_type_id, + image, + sampler, + coordinate, + array_index, + offset, + level, + depth_ref, + block, + )?, crate::Expression::Select { condition, accept, @@ -1094,143 +778,7 @@ impl<'w> BlockContext<'w> { id } crate::Expression::ImageQuery { image, query } => { - use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq}; - - let image_id = self.get_image_id(image); - let image_type = self.fun_info[image].ty.handle().unwrap(); - let (dim, arrayed, class) = match self.ir_module.types[image_type].inner { - crate::TypeInner::Image { - dim, - arrayed, - class, - } => (dim, arrayed, class), - _ => { - return Err(Error::Validation("image type")); - } - }; - - self.writer - .require_any("image queries", &[spirv::Capability::ImageQuery])?; - - match query { - Iq::Size { level } => { - let dim_coords = match dim { - Id::D1 => 1, - Id::D2 | Id::Cube => 2, - Id::D3 => 3, - }; - let extended_size_type_id = { - let array_coords = if arrayed { 1 } else { 0 }; - let vector_size = match dim_coords + array_coords { - 2 => Some(crate::VectorSize::Bi), - 3 => Some(crate::VectorSize::Tri), - 4 => Some(crate::VectorSize::Quad), - _ => None, - }; - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size, - kind: crate::ScalarKind::Sint, - width: 4, - pointer_class: None, - })) - }; - - let (query_op, level_id) = match class { - Ic::Storage { .. } => (spirv::Op::ImageQuerySize, None), - _ => { - let level_id = match level { - Some(expr) => self.cached[expr], - None => self.get_index_constant(0), - }; - (spirv::Op::ImageQuerySizeLod, Some(level_id)) - } - }; - - // The ID of the vector returned by SPIR-V, which contains the dimensions - // as well as the layer count. - let id_extended = self.gen_id(); - let mut inst = Instruction::image_query( - query_op, - extended_size_type_id, - id_extended, - image_id, - ); - if let Some(expr_id) = level_id { - inst.add_operand(expr_id); - } - block.body.push(inst); - - if result_type_id != extended_size_type_id { - let id = self.gen_id(); - let components = match dim { - // always pick the first component, and duplicate it for all 3 dimensions - Id::Cube => &[0u32, 0][..], - _ => &[0u32, 1, 2, 3][..dim_coords], - }; - block.body.push(Instruction::vector_shuffle( - result_type_id, - id, - id_extended, - id_extended, - components, - )); - id - } else { - id_extended - } - } - Iq::NumLevels => { - let id = self.gen_id(); - block.body.push(Instruction::image_query( - spirv::Op::ImageQueryLevels, - result_type_id, - id, - image_id, - )); - id - } - Iq::NumLayers => { - let vec_size = match dim { - Id::D1 => crate::VectorSize::Bi, - Id::D2 | Id::Cube => crate::VectorSize::Tri, - Id::D3 => crate::VectorSize::Quad, - }; - let extended_size_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(vec_size), - kind: crate::ScalarKind::Sint, - width: 4, - pointer_class: None, - })); - let id_extended = self.gen_id(); - let mut inst = Instruction::image_query( - spirv::Op::ImageQuerySizeLod, - extended_size_type_id, - id_extended, - image_id, - ); - inst.add_operand(self.get_index_constant(0)); - block.body.push(inst); - let id = self.gen_id(); - block.body.push(Instruction::composite_extract( - result_type_id, - id, - id_extended, - &[vec_size as u32 - 1], - )); - id - } - Iq::NumSamples => { - let id = self.gen_id(); - block.body.push(Instruction::image_query( - spirv::Op::ImageQuerySamples, - result_type_id, - id, - image_id, - )); - id - } - } + self.write_image_query(result_type_id, image, query, block)? } crate::Expression::Relational { fun, argument } => { use crate::RelationalFunction as Rf; @@ -1369,27 +917,6 @@ impl<'w> BlockContext<'w> { Ok(pointer) } - fn get_image_id(&mut self, expr_handle: Handle) -> Word { - let id = match self.ir_function.expressions[expr_handle] { - crate::Expression::GlobalVariable(handle) => { - self.writer.global_variables[handle.index()].handle_id - } - crate::Expression::FunctionArgument(i) => { - self.function.parameters[i as usize].handle_id - } - ref other => unreachable!("Unexpected image expression {:?}", other), - }; - - if id == 0 { - unreachable!( - "Image expression {:?} doesn't have a handle ID", - expr_handle - ); - } - - id - } - pub(super) fn write_block( &mut self, label_id: Word, @@ -1682,16 +1209,7 @@ impl<'w> BlockContext<'w> { coordinate, array_index, value, - } => { - let image_id = self.get_image_id(image); - let coordinate_id = - self.write_image_coordinates(coordinate, array_index, &mut block)?; - let value_id = self.cached[value]; - - block - .body - .push(Instruction::image_write(image_id, coordinate_id, value_id)); - } + } => self.write_image_store(image, coordinate, array_index, value, &mut block)?, crate::Statement::Call { function: local_function, ref arguments, diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs new file mode 100644 index 000000000..1d5e4385b --- /dev/null +++ b/src/back/spv/image.rs @@ -0,0 +1,553 @@ +//! Generating SPIR-V for image operations. + +use super::{Block, BlockContext, Error, Instruction, LocalType, LookupType}; +use crate::arena::Handle; +use spirv::Word; + +impl<'w> BlockContext<'w> { + /// Extend image coordinates with an array index, if necessary. + /// + /// Whereas [`Expression::ImageLoad`] and [`ImageSample`] treat the array + /// index as a separate operand from the coordinates, SPIR-V image access + /// instructions include the array index in the `coordinates` operand. This + /// function builds a SPIR-V coordinate vector from a Naga coordinate vector + /// and array index. + /// + /// If `array_index` is `Some(expr)`, then this function constructs a new + /// vector that is `coordinates` with `array_index` concatenated onto the + /// end: a `vec2` becomes a `vec3`, a scalar becomes a `vec2`, and so on. + /// + /// Naga's `ImageLoad` and SPIR-V's `OpImageRead`, `OpImageFetch`, and + /// `OpImageWrite` all use integer coordinates, while Naga's `ImageSample` + /// and SPIR-V's `OpImageSample...` instructions all take floating-point + /// coordinate vectors. The array index, always an integer scalar, may need + /// to be converted to match the component type of `coordinates`. + /// + /// If `array_index` is `None`, this function simply returns the id for + /// `coordinates`. + /// + /// [`Expression::ImageLoad`]: crate::Expression::ImageLoad + /// [`ImageSample`]: crate::Expression::ImageSample + fn write_image_coordinates( + &mut self, + coordinates: Handle, + array_index: Option>, + block: &mut Block, + ) -> Result { + use crate::TypeInner as Ti; + use crate::VectorSize as Vs; + + let coordinate_id = self.cached[coordinates]; + + // If there's no array index, the image coordinates are exactly the + // `coordinate` field of the `Expression::ImageLoad`. No work is needed. + let array_index = match array_index { + None => return Ok(coordinate_id), + Some(ix) => ix, + }; + + // Find the component type of `coordinates`, and figure out the size the + // combined coordinate vector will have. + let (component_kind, result_size) = match *self.fun_info[coordinates] + .ty + .inner_with(&self.ir_module.types) + { + Ti::Scalar { kind, width: 4 } => (kind, Vs::Bi), + Ti::Vector { + kind, + width: 4, + size: Vs::Bi, + } => (kind, Vs::Tri), + Ti::Vector { + kind, + width: 4, + size: Vs::Tri, + } => (kind, Vs::Quad), + Ti::Vector { size: Vs::Quad, .. } => { + return Err(Error::Validation("extending vec4 coordinate")); + } + ref other => { + log::error!("wrong coordinate type {:?}", other); + return Err(Error::Validation("coordinate type")); + } + }; + + // Convert the index to the coordinate component type, if necessary. + let array_index_i32_id = self.cached[array_index]; + let reconciled_array_index_id = if component_kind == crate::ScalarKind::Sint { + array_index_i32_id + } else { + let component_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: component_kind, + width: 4, + pointer_class: None, + })); + + let reconciled_id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::ConvertUToF, + component_type_id, + reconciled_id, + array_index_i32_id, + )); + reconciled_id + }; + + // Find the SPIR-V type for the combined coordinates/index vector. + let combined_coordinate_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(result_size), + kind: component_kind, + width: 4, + pointer_class: None, + })); + + // Schmear the coordinates and index together. + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + combined_coordinate_type_id, + id, + &[coordinate_id, reconciled_array_index_id], + )); + Ok(id) + } + + fn get_image_id(&mut self, expr_handle: Handle) -> Word { + let id = match self.ir_function.expressions[expr_handle] { + crate::Expression::GlobalVariable(handle) => { + self.writer.global_variables[handle.index()].handle_id + } + crate::Expression::FunctionArgument(i) => { + self.function.parameters[i as usize].handle_id + } + ref other => unreachable!("Unexpected image expression {:?}", other), + }; + + if id == 0 { + unreachable!( + "Image expression {:?} doesn't have a handle ID", + expr_handle + ); + } + + id + } + + /// Generate code for an `ImageLoad` expression. + /// + /// The arguments are the components of an `Expression::ImageLoad` variant. + pub(super) fn write_image_load( + &mut self, + result_type_id: Word, + image: Handle, + coordinate: Handle, + array_index: Option>, + index: Option>, + block: &mut Block, + ) -> Result { + let image_id = self.get_image_id(image); + let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; + + let id = self.gen_id(); + + let image_ty = self.fun_info[image].ty.inner_with(&self.ir_module.types); + let mut instruction = match *image_ty { + crate::TypeInner::Image { + class: crate::ImageClass::Storage { .. }, + .. + } => Instruction::image_read(result_type_id, id, image_id, coordinate_id), + crate::TypeInner::Image { + class: crate::ImageClass::Depth { multi: _ }, + .. + } => { + // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, + // so we need to grab the first component out of it. + let load_result_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Quad), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + })); + Instruction::image_fetch(load_result_type_id, id, image_id, coordinate_id) + } + _ => Instruction::image_fetch(result_type_id, id, image_id, coordinate_id), + }; + + if let Some(index) = index { + let index_id = self.cached[index]; + let image_ops = match *self.fun_info[image].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Image { + class: crate::ImageClass::Sampled { multi: true, .. }, + .. + } + | crate::TypeInner::Image { + class: crate::ImageClass::Depth { multi: true }, + .. + } => spirv::ImageOperands::SAMPLE, + _ => spirv::ImageOperands::LOD, + }; + instruction.add_operand(image_ops.bits()); + instruction.add_operand(index_id); + } + + let inst_type_id = instruction.type_id; + block.body.push(instruction); + let id = if inst_type_id != Some(result_type_id) { + let sub_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + result_type_id, + sub_id, + id, + &[0], + )); + sub_id + } else { + id + }; + + Ok(id) + } + + /// Generate code for an `ImageSample` expression. + /// + /// The arguments are the components of an `Expression::ImageSample` variant. + #[allow(clippy::too_many_arguments)] + pub(super) fn write_image_sample( + &mut self, + result_type_id: Word, + image: Handle, + sampler: Handle, + coordinate: Handle, + array_index: Option>, + offset: Option>, + level: crate::SampleLevel, + depth_ref: Option>, + block: &mut Block, + ) -> Result { + use super::instructions::SampleLod; + // image + let image_id = self.get_image_id(image); + let image_type = self.fun_info[image].ty.handle().unwrap(); + // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, + // so we need to grab the first component out of it. + let needs_sub_access = match self.ir_module.types[image_type].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Depth { .. }, + .. + } => depth_ref.is_none(), + _ => false, + }; + let sample_result_type_id = if needs_sub_access { + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Quad), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + })) + } else { + result_type_id + }; + + // OpTypeSampledImage + let image_type_id = self.get_type_id(LookupType::Handle(image_type)); + let sampled_image_type_id = + self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id })); + + let sampler_id = self.get_image_id(sampler); + let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; + + let sampled_image_id = self.gen_id(); + block.body.push(Instruction::sampled_image( + sampled_image_type_id, + sampled_image_id, + image_id, + sampler_id, + )); + let id = self.gen_id(); + + let depth_id = depth_ref.map(|handle| self.cached[handle]); + let mut mask = spirv::ImageOperands::empty(); + mask.set(spirv::ImageOperands::CONST_OFFSET, offset.is_some()); + + let mut main_instruction = match level { + crate::SampleLevel::Zero => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Explicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let zero_id = self + .writer + .get_constant_scalar(crate::ScalarValue::Float(0.0), 4); + + mask |= spirv::ImageOperands::LOD; + inst.add_operand(mask.bits()); + inst.add_operand(zero_id); + + inst + } + crate::SampleLevel::Auto => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Implicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + if !mask.is_empty() { + inst.add_operand(mask.bits()); + } + inst + } + crate::SampleLevel::Exact(lod_handle) => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Explicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let lod_id = self.cached[lod_handle]; + mask |= spirv::ImageOperands::LOD; + inst.add_operand(mask.bits()); + inst.add_operand(lod_id); + + inst + } + crate::SampleLevel::Bias(bias_handle) => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Implicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let bias_id = self.cached[bias_handle]; + mask |= spirv::ImageOperands::BIAS; + inst.add_operand(mask.bits()); + inst.add_operand(bias_id); + + inst + } + crate::SampleLevel::Gradient { x, y } => { + let mut inst = Instruction::image_sample( + sample_result_type_id, + id, + SampleLod::Explicit, + sampled_image_id, + coordinate_id, + depth_id, + ); + + let x_id = self.cached[x]; + let y_id = self.cached[y]; + mask |= spirv::ImageOperands::GRAD; + inst.add_operand(mask.bits()); + inst.add_operand(x_id); + inst.add_operand(y_id); + + inst + } + }; + + if let Some(offset_const) = offset { + let offset_id = self.writer.constant_ids[offset_const.index()]; + main_instruction.add_operand(offset_id); + } + + block.body.push(main_instruction); + + let id = if needs_sub_access { + let sub_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + result_type_id, + sub_id, + id, + &[0], + )); + sub_id + } else { + id + }; + + Ok(id) + } + + /// Generate code for an `ImageQuery` expression. + /// + /// The arguments are the components of an `Expression::ImageQuery` variant. + pub(super) fn write_image_query( + &mut self, + result_type_id: Word, + image: Handle, + query: crate::ImageQuery, + block: &mut Block, + ) -> Result { + use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq}; + + let image_id = self.get_image_id(image); + let image_type = self.fun_info[image].ty.handle().unwrap(); + let (dim, arrayed, class) = match self.ir_module.types[image_type].inner { + crate::TypeInner::Image { + dim, + arrayed, + class, + } => (dim, arrayed, class), + _ => { + return Err(Error::Validation("image type")); + } + }; + + self.writer + .require_any("image queries", &[spirv::Capability::ImageQuery])?; + + let id = match query { + Iq::Size { level } => { + let dim_coords = match dim { + Id::D1 => 1, + Id::D2 | Id::Cube => 2, + Id::D3 => 3, + }; + let extended_size_type_id = { + let array_coords = if arrayed { 1 } else { 0 }; + let vector_size = match dim_coords + array_coords { + 2 => Some(crate::VectorSize::Bi), + 3 => Some(crate::VectorSize::Tri), + 4 => Some(crate::VectorSize::Quad), + _ => None, + }; + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + })) + }; + + let (query_op, level_id) = match class { + Ic::Storage { .. } => (spirv::Op::ImageQuerySize, None), + _ => { + let level_id = match level { + Some(expr) => self.cached[expr], + None => self.get_index_constant(0), + }; + (spirv::Op::ImageQuerySizeLod, Some(level_id)) + } + }; + + // The ID of the vector returned by SPIR-V, which contains the dimensions + // as well as the layer count. + let id_extended = self.gen_id(); + let mut inst = Instruction::image_query( + query_op, + extended_size_type_id, + id_extended, + image_id, + ); + if let Some(expr_id) = level_id { + inst.add_operand(expr_id); + } + block.body.push(inst); + + if result_type_id != extended_size_type_id { + let id = self.gen_id(); + let components = match dim { + // always pick the first component, and duplicate it for all 3 dimensions + Id::Cube => &[0u32, 0][..], + _ => &[0u32, 1, 2, 3][..dim_coords], + }; + block.body.push(Instruction::vector_shuffle( + result_type_id, + id, + id_extended, + id_extended, + components, + )); + id + } else { + id_extended + } + } + Iq::NumLevels => { + let id = self.gen_id(); + block.body.push(Instruction::image_query( + spirv::Op::ImageQueryLevels, + result_type_id, + id, + image_id, + )); + id + } + Iq::NumLayers => { + let vec_size = match dim { + Id::D1 => crate::VectorSize::Bi, + Id::D2 | Id::Cube => crate::VectorSize::Tri, + Id::D3 => crate::VectorSize::Quad, + }; + let extended_size_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(vec_size), + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + })); + let id_extended = self.gen_id(); + let mut inst = Instruction::image_query( + spirv::Op::ImageQuerySizeLod, + extended_size_type_id, + id_extended, + image_id, + ); + inst.add_operand(self.get_index_constant(0)); + block.body.push(inst); + let id = self.gen_id(); + block.body.push(Instruction::composite_extract( + result_type_id, + id, + id_extended, + &[vec_size as u32 - 1], + )); + id + } + Iq::NumSamples => { + let id = self.gen_id(); + block.body.push(Instruction::image_query( + spirv::Op::ImageQuerySamples, + result_type_id, + id, + image_id, + )); + id + } + }; + + Ok(id) + } + + pub(super) fn write_image_store( + &mut self, + image: Handle, + coordinate: Handle, + array_index: Option>, + value: Handle, + block: &mut Block, + ) -> Result<(), Error> { + let image_id = self.get_image_id(image); + let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; + let value_id = self.cached[value]; + + block + .body + .push(Instruction::image_write(image_id, coordinate_id, value_id)); + + Ok(()) + } +} diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 32c8ecb4c..bd59f8dbe 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -3,6 +3,7 @@ mod block; mod helpers; +mod image; mod index; mod instructions; mod layout; @@ -371,6 +372,10 @@ impl BlockContext<'_> { self.writer.id_gen.next() } + fn get_type_id(&mut self, lookup_type: LookupType) -> Word { + self.writer.get_type_id(lookup_type) + } + fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Word { self.writer.get_expression_type_id(tr) } From c6ecd973e7db5c305cc285c2681702b353859725 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 12 Aug 2021 11:04:43 -0700 Subject: [PATCH 1281/2212] [spv-out] Use `Selection` for building conditionals. Introduce a helper type that manages the details of emitting SPIR-V conditionals, tracking labels, branches, merge annotations and phi nodes. Change index bounds checks to use this helper. --- src/back/spv/block.rs | 34 +--- src/back/spv/index.rs | 63 +++--- src/back/spv/mod.rs | 1 + src/back/spv/selection.rs | 257 +++++++++++++++++++++++++ tests/out/spv/bounds-check-zero.spvasm | 90 ++++----- 5 files changed, 335 insertions(+), 110 deletions(-) create mode 100644 src/back/spv/selection.rs diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 904340fde..f1e95f771 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -2,8 +2,10 @@ use super::{ index::{BoundsCheckResult, ExpressionPointer}, - make_local, Block, BlockContext, Dimension, Error, Instruction, LocalType, LookupType, - LoopContext, ResultMember, Writer, WriterFlags, + make_local, + selection::Selection, + Block, BlockContext, Dimension, Error, Instruction, LocalType, LookupType, LoopContext, + ResultMember, Writer, WriterFlags, }; use crate::{arena::Handle, proc::TypeResolution}; use spirv::Word; @@ -1171,36 +1173,20 @@ impl<'w> BlockContext<'w> { block.body.push(instruction); } ExpressionPointer::Conditional { condition, access } => { - let merge_block = self.gen_id(); - let in_bounds_block = self.gen_id(); - - // Emit the conditional branch. - block.body.push(Instruction::selection_merge( - merge_block, - spirv::SelectionControl::NONE, - )); - self.function.consume( - std::mem::replace(&mut block, Block::new(in_bounds_block)), - Instruction::branch_conditional( - condition, - in_bounds_block, - merge_block, - ), - ); + let mut selection = Selection::start(&mut block, ()); + selection.if_true(self, condition, ()); // The in-bounds path. Perform the access and the store. let pointer_id = access.result_id.unwrap(); - block.body.push(access); - block + selection.block().body.push(access); + selection + .block() .body .push(Instruction::store(pointer_id, value_id, None)); // Finish the in-bounds block and start the merge block. This // is the block we'll leave current on return. - self.function.consume( - std::mem::replace(&mut block, Block::new(merge_block)), - Instruction::branch(merge_block), - ); + selection.finish(self, ()); } }; } diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index e82e71972..91bafbb01 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -1,6 +1,6 @@ //! Bounds-checking for SPIR-V output. -use super::{Block, BlockContext, Error, IdGenerator, Instruction, Word}; +use super::{selection::Selection, Block, BlockContext, Error, IdGenerator, Instruction, Word}; use crate::{arena::Handle, back::BoundsCheckPolicy}; /// The results of emitting code for a left-hand-side expression. @@ -306,49 +306,30 @@ impl<'w> BlockContext<'w> { where F: FnOnce(&mut IdGenerator, &mut Block) -> Word, { - let header_block = block.label_id; - let merge_block = self.gen_id(); - let in_bounds_block = self.gen_id(); - - // Branch based on whether the index was in bounds. - // - // As it turns out, our out-of-bounds branch block would contain no - // instructions: it just produces a constant zero, whose instruction is - // in the module's declarations section at the front. In this case, - // SPIR-V lets us omit the empty 'else' block, and branch directly to - // the merge block. The phi instruction in the merge block can cite the - // header block as its CFG predecessor. - block.body.push(Instruction::selection_merge( - merge_block, - spirv::SelectionControl::NONE, - )); - self.function.consume( - std::mem::replace(block, Block::new(in_bounds_block)), - Instruction::branch_conditional(condition, in_bounds_block, merge_block), - ); - - // The in-bounds path. Perform the access and the load. - let value_id = emit_load(&mut self.writer.id_gen, block); - - // Finish the in-bounds block and start the merge block. This - // is the block we'll leave current on return. - self.function.consume( - std::mem::replace(block, Block::new(merge_block)), - Instruction::branch(merge_block), - ); - - // For the out-of-bounds case, produce a zero value. + // For the out-of-bounds case, we produce a zero value. let null_id = self.writer.write_constant_null(result_type); - // Merge the results from the two paths. - let result_id = self.gen_id(); - block.body.push(Instruction::phi( - result_type, - result_id, - &[(value_id, in_bounds_block), (null_id, header_block)], - )); + let mut selection = Selection::start(block, result_type); - result_id + // As it turns out, we don't actually need a full 'if-then-else' + // structure for this: SPIR-V constants are declared up front, so the + // 'else' block would have no instructions. Instead we emit something + // like this: + // + // result = zero; + // if in_bounds { + // result = do the load; + // } + // use result; + + // Continue only if the index was in bounds. Otherwise, branch to the + // merge block. + selection.if_true(self, condition, null_id); + + // The in-bounds path. Perform the access and the load. + let loaded_value = emit_load(&mut self.writer.id_gen, selection.block()); + + selection.finish(self, loaded_value) } /// Emit code for bounds checks, per self.index_bounds_check_policy. diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index bd59f8dbe..42e51059a 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -8,6 +8,7 @@ mod index; mod instructions; mod layout; mod recyclable; +mod selection; mod writer; pub use spirv::Capability; diff --git a/src/back/spv/selection.rs b/src/back/spv/selection.rs new file mode 100644 index 000000000..a5558a05e --- /dev/null +++ b/src/back/spv/selection.rs @@ -0,0 +1,257 @@ +//! Generate SPIR-V conditional structures. +//! +//! Builders for `if` structures with `and`s. +//! +//! The types in this module track the information needed to emit SPIR-V code +//! for complex conditional structures, like those whose conditions involve +//! short-circuiting 'and' and 'or' structures. These track labels and can emit +//! `OpPhi` instructions to merge values produced along different paths. +//! +//! This currently only supports exactly the forms Naga uses, so it doesn't +//! support `or` or `else`, and only supports zero or one merged values. +//! +//! Naga needs to emit code roughly like this: +//! +//! ```ignore +//! +//! value = DEFAULT; +//! if COND1 && COND2 { +//! value = THEN_VALUE; +//! } +//! // use value +//! +//! ``` +//! +//! Assuming `ctx` and `block` are a mutable references to a [`BlockContext`] +//! and the current [`Block`], and `merge_type` is the SPIR-V type for the +//! merged value `value`, we can build SPIR-V for the code above like so: +//! +//! ```ignore +//! +//! let cond = Selection::start(block, merge_type); +//! // ... compute `cond1` ... +//! cond.if_true(ctx, cond1, DEFAULT); +//! // ... compute `cond2` ... +//! cond.if_true(ctx, cond2, DEFAULT); +//! // ... compute THEN_VALUE +//! let merged_value = cond.finish(ctx, THEN_VALUE); +//! +//! ``` +//! +//! After this, `merged_value` is either `DEFAULT` or `THEN_VALUE`, depending on +//! the path by which the merged block was reached. +//! +//! This takes care of writing all branch instructions, including an +//! `OpSelectionMerge` annotation in the header block; starting new blocks and +//! assigning them labels; and emitting the `OpPhi` that gathers together the +//! right sources for the merged values, for every path through the selection +//! construct. +//! +//! When there is no merged value to produce, you can pass `()` for `merge_type` +//! and the merge values. In this case no `OpPhi` instructions are produced, and +//! the `finish` method returns `()`. +//! +//! To enforce proper nesting, a `Selection` takes ownership of the `&mut Block` +//! pointer for the duration of its lifetime. To obtain the block for generating +//! code in the selection's body, call the `Selection::block` method. + +#![allow(dead_code)] // until texture bounds checks + +use super::{Block, BlockContext, Instruction}; +use spirv::Word; + +/// A private struct recording what we know about the selection construct so far. +pub(super) struct Selection<'b, M: MergeTuple> { + /// The block pointer we're emitting code into. + block: &'b mut Block, + + /// The label of the selection construct's merge block, or `None` if we + /// haven't yet written the `OpSelectionMerge` merge instruction. + merge_label: Option, + + /// A set of `(VALUES, PARENT)` pairs, used to build `OpPhi` instructions in + /// the merge block. Each `PARENT` is the label of a predecessor block of + /// the merge block. The corresponding `VALUES` holds the ids of the values + /// that `PARENT` contributes to the merged values. + /// + /// We emit all branches to the merge block, so we know all its + /// predecessors. And we refuse to emit a branch unless we're given the + /// values the branching block contributes to the merge, so we always have + /// everything we need to emit the correct phis, by construction. + values: Vec<(M, Word)>, + + /// The types of the values in each element of `values`. + merge_types: M, +} + +impl<'b, M: MergeTuple> Selection<'b, M> { + /// Start a new selection construct. + /// + /// The `block` argument indicates the selection's header block. + /// + /// The `merge_types` argument should be a `Word` or tuple of `Word`s, each + /// value being the SPIR-V result type id of an `OpPhi` instruction that + /// will be written to the selection's merge block when this selection's + /// [`finish`] method is called. This argument may also be `()`, for + /// selections that produce no values. + /// + /// (This function writes no code to `block` itself; it simply constructs a + /// fresh `Selection`.) + /// + /// [`finish`]: Selection::finish + pub(super) fn start(block: &'b mut Block, merge_types: M) -> Self { + Selection { + block, + merge_label: None, + values: vec![], + merge_types, + } + } + + pub(super) fn block(&mut self) -> &mut Block { + self.block + } + + /// Branch to a successor block if `cond` is true, otherwise merge. + /// + /// If `cond` is false, branch to the merge block, using `values` as the + /// merged values. Otherwise, proceed to a new block. + /// + /// The `values` argument must be the same shape as the `merge_types` + /// argument passed to `Selection::start`. + pub(super) fn if_true(&mut self, ctx: &mut BlockContext, cond: Word, values: M) { + self.values.push((values, self.block.label_id)); + + let merge_label = self.make_merge_label(ctx); + let next_label = ctx.gen_id(); + ctx.function.consume( + std::mem::replace(self.block, Block::new(next_label)), + Instruction::branch_conditional(cond, next_label, merge_label), + ); + } + + /// Emit an unconditional branch to the merge block, and compute merged + /// values. + /// + /// Use `final_values` as the merged values contributed by the current + /// block, and transition to the merge block, emitting `OpPhi` instructions + /// to produce the merged values. This must be the same shape as the + /// `merge_types` argument passed to [`Selection::start`]. + /// + /// Return the SPIR-V ids of the merged values. This value has the same + /// shape as the `merge_types` argument passed to `Selection::start`. + pub(super) fn finish(self, ctx: &mut BlockContext, final_values: M) -> M { + match self { + Selection { + merge_label: None, .. + } => { + // We didn't actually emit any branches, so `self.values` must + // be empty, and `final_values` are the only sources we have for + // the merged values. Easy peasy. + final_values + } + + Selection { + block, + merge_label: Some(merge_label), + mut values, + merge_types, + } => { + // Emit the final branch and transition to the merge block. + values.push((final_values, block.label_id)); + ctx.function.consume( + std::mem::replace(block, Block::new(merge_label)), + Instruction::branch(merge_label), + ); + + // Now that we're in the merge block, build the phi instructions. + merge_types.write_phis(ctx, block, &values) + } + } + } + + /// Return the id of the merge block, writing a merge instruction if needed. + fn make_merge_label(&mut self, ctx: &mut BlockContext) -> Word { + match self.merge_label { + None => { + let merge_label = ctx.gen_id(); + self.block.body.push(Instruction::selection_merge( + merge_label, + spirv::SelectionControl::NONE, + )); + self.merge_label = Some(merge_label); + merge_label + } + Some(merge_label) => merge_label, + } + } +} + +/// A trait to help `Selection` manage any number of merged values. +/// +/// Some selection constructs, like a `ReadZeroSkipWrite` bounds check on a +/// [`Load`] expression, produce a single merged value. Others produce no merged +/// value, like a bounds check on a [`Store`] statement. +/// +/// To let `Selection` work nicely with both cases, we let the merge type +/// argument passed to [`Selection::start`] be any type that implements this +/// `MergeTuple` trait. `MergeTuple` is then implemented for `()`, `Word`, +/// `(Word, Word)`, and so on. +/// +/// A `MergeTuple` type can represent either a bunch of SPIR-V types or values; +/// the `merge_types` argument to `Selection::start` are type ids, whereas the +/// `values` arguments to the [`if_true`] and [`finish`] methods are value ids. +/// The set of merged value returned by `finish` is a tuple of value ids. +/// +/// In fact, since Naga only uses zero- and single-valued selection constructs +/// at present, we only implement `MergeTuple` for `()` and `Word`. But if you +/// add more cases, feel free to add more implementations. Once const generics +/// are available, we could have a single implementation of `MergeTuple` for all +/// lengths of arrays, and be done with it. +/// +/// [`Load`]: crate::Expression::Load +/// [`Store`]: crate::Statement::Store +/// [`if_true`]: Selection::if_true +/// [`finish`]: Selection::finish +pub(super) trait MergeTuple: Sized { + /// Write OpPhi instructions for the given set of predecessors. + /// + /// The `predecessors` vector should be a vector of `(LABEL, VALUES)` pairs, + /// where each `VALUES` holds the values contributed by the branch from + /// `LABEL`, which should be one of the current block's predecessors. + fn write_phis( + self, + ctx: &mut BlockContext, + block: &mut Block, + predecessors: &[(Self, Word)], + ) -> Self; +} + +/// Selections that produce a single merged value. +/// +/// For example, `ImageLoad` with `BoundsCheckPolicy::ReadZeroSkipWrite` either +/// returns a texel value or zeros. +impl MergeTuple for Word { + fn write_phis( + self, + ctx: &mut BlockContext, + block: &mut Block, + predecessors: &[(Word, Word)], + ) -> Word { + let merged_value = ctx.gen_id(); + block + .body + .push(Instruction::phi(self, merged_value, predecessors)); + merged_value + } +} + +/// Selections that produce no merged values. +/// +/// For example, `ImageStore` under `BoundsCheckPolicy::ReadZeroSkipWrite` +/// either does the store or skips it, but in neither case does it produce a +/// value. +impl MergeTuple for () { + /// No phis need to be generated. + fn write_phis(self, _: &mut BlockContext, _: &mut Block, _: &[((), Word)]) {} +} diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index 7dd458711..84af0e2a7 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -34,22 +34,22 @@ OpDecorate %10 Binding 0 %19 = OpConstant %20 10 %22 = OpTypeBool %23 = OpConstant %20 0 -%28 = OpConstantNull %5 +%25 = OpConstantNull %5 %34 = OpTypePointer StorageBuffer %7 %35 = OpConstant %20 1 %38 = OpConstant %20 4 -%43 = OpConstantNull %5 +%40 = OpConstantNull %5 %49 = OpTypeFunction %5 %7 %4 -%55 = OpConstantNull %5 +%52 = OpConstantNull %5 %60 = OpTypeFunction %7 %4 %62 = OpTypePointer StorageBuffer %8 %63 = OpTypePointer StorageBuffer %7 %64 = OpConstant %20 3 %66 = OpConstant %20 2 -%71 = OpConstantNull %7 +%68 = OpConstantNull %7 %77 = OpTypeFunction %5 %4 %4 -%84 = OpConstantNull %7 -%90 = OpConstantNull %5 +%81 = OpConstantNull %7 +%87 = OpConstantNull %5 %96 = OpTypeFunction %2 %4 %5 %107 = OpTypePointer StorageBuffer %5 %116 = OpTypeFunction %2 %4 %7 @@ -60,14 +60,14 @@ OpDecorate %10 Binding 0 OpBranch %16 %16 = OpLabel %21 = OpULessThan %22 %13 %19 -OpSelectionMerge %25 None -OpBranchConditional %21 %26 %25 -%26 = OpLabel +OpSelectionMerge %26 None +OpBranchConditional %21 %27 %26 +%27 = OpLabel %24 = OpAccessChain %18 %10 %23 %13 -%27 = OpLoad %5 %24 -OpBranch %25 -%25 = OpLabel -%29 = OpPhi %5 %27 %26 %28 %16 +%28 = OpLoad %5 %24 +OpBranch %26 +%26 = OpLabel +%29 = OpPhi %5 %25 %16 %28 %27 OpReturnValue %29 OpFunctionEnd %32 = OpFunction %5 None %15 @@ -78,13 +78,13 @@ OpBranch %33 %36 = OpAccessChain %34 %10 %35 %37 = OpLoad %7 %36 %39 = OpULessThan %22 %31 %38 -OpSelectionMerge %40 None -OpBranchConditional %39 %41 %40 +OpSelectionMerge %41 None +OpBranchConditional %39 %42 %41 +%42 = OpLabel +%43 = OpVectorExtractDynamic %5 %37 %31 +OpBranch %41 %41 = OpLabel -%42 = OpVectorExtractDynamic %5 %37 %31 -OpBranch %40 -%40 = OpLabel -%44 = OpPhi %5 %42 %41 %43 %33 +%44 = OpPhi %5 %40 %33 %43 %42 OpReturnValue %44 OpFunctionEnd %48 = OpFunction %5 None %49 @@ -94,13 +94,13 @@ OpFunctionEnd OpBranch %50 %50 = OpLabel %51 = OpULessThan %22 %47 %38 -OpSelectionMerge %52 None -OpBranchConditional %51 %53 %52 +OpSelectionMerge %53 None +OpBranchConditional %51 %54 %53 +%54 = OpLabel +%55 = OpVectorExtractDynamic %5 %46 %47 +OpBranch %53 %53 = OpLabel -%54 = OpVectorExtractDynamic %5 %46 %47 -OpBranch %52 -%52 = OpLabel -%56 = OpPhi %5 %54 %53 %55 %50 +%56 = OpPhi %5 %52 %50 %55 %54 OpReturnValue %56 OpFunctionEnd %59 = OpFunction %7 None %60 @@ -109,14 +109,14 @@ OpFunctionEnd OpBranch %61 %61 = OpLabel %65 = OpULessThan %22 %58 %64 -OpSelectionMerge %68 None -OpBranchConditional %65 %69 %68 -%69 = OpLabel +OpSelectionMerge %69 None +OpBranchConditional %65 %70 %69 +%70 = OpLabel %67 = OpAccessChain %63 %10 %66 %58 -%70 = OpLoad %7 %67 -OpBranch %68 -%68 = OpLabel -%72 = OpPhi %7 %70 %69 %71 %61 +%71 = OpLoad %7 %67 +OpBranch %69 +%69 = OpLabel +%72 = OpPhi %7 %68 %61 %71 %70 OpReturnValue %72 OpFunctionEnd %76 = OpFunction %5 None %77 @@ -126,22 +126,22 @@ OpFunctionEnd OpBranch %78 %78 = OpLabel %79 = OpULessThan %22 %74 %64 -OpSelectionMerge %81 None -OpBranchConditional %79 %82 %81 -%82 = OpLabel +OpSelectionMerge %82 None +OpBranchConditional %79 %83 %82 +%83 = OpLabel %80 = OpAccessChain %63 %10 %66 %74 -%83 = OpLoad %7 %80 -OpBranch %81 -%81 = OpLabel -%85 = OpPhi %7 %83 %82 %84 %78 +%84 = OpLoad %7 %80 +OpBranch %82 +%82 = OpLabel +%85 = OpPhi %7 %81 %78 %84 %83 %86 = OpULessThan %22 %75 %38 -OpSelectionMerge %87 None -OpBranchConditional %86 %88 %87 +OpSelectionMerge %88 None +OpBranchConditional %86 %89 %88 +%89 = OpLabel +%90 = OpVectorExtractDynamic %5 %85 %75 +OpBranch %88 %88 = OpLabel -%89 = OpVectorExtractDynamic %5 %85 %75 -OpBranch %87 -%87 = OpLabel -%91 = OpPhi %5 %89 %88 %90 %81 +%91 = OpPhi %5 %87 %82 %90 %89 OpReturnValue %91 OpFunctionEnd %95 = OpFunction %2 None %96 From 901e2c0694c8d838ab66abb403ea19e2409215b6 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 14 Aug 2021 10:27:45 -0700 Subject: [PATCH 1282/2212] [spv-out] Implement BoundsCheckPolicy for image access --- cli/src/main.rs | 14 +- src/back/spv/image.rs | 785 ++++++++++++++++-- src/back/spv/index.rs | 4 +- src/back/spv/instructions.rs | 19 +- src/back/spv/mod.rs | 5 + src/back/spv/selection.rs | 2 - src/back/spv/writer.rs | 2 + src/lib.rs | 16 + .../in/bounds-check-image-restrict.param.ron | 5 + tests/in/bounds-check-image-restrict.wgsl | 83 ++ tests/in/bounds-check-image-rzsw.param.ron | 5 + tests/in/bounds-check-image-rzsw.wgsl | 83 ++ .../spv/bounds-check-image-restrict.spvasm | 316 +++++++ tests/out/spv/bounds-check-image-rzsw.spvasm | 390 +++++++++ tests/snapshots.rs | 14 + 15 files changed, 1634 insertions(+), 109 deletions(-) create mode 100644 tests/in/bounds-check-image-restrict.param.ron create mode 100644 tests/in/bounds-check-image-restrict.wgsl create mode 100644 tests/in/bounds-check-image-rzsw.param.ron create mode 100644 tests/in/bounds-check-image-rzsw.wgsl create mode 100644 tests/out/spv/bounds-check-image-restrict.spvasm create mode 100644 tests/out/spv/bounds-check-image-rzsw.spvasm diff --git a/cli/src/main.rs b/cli/src/main.rs index 8930791d3..372a8303b 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -10,12 +10,19 @@ struct Args { #[argh(switch)] validate: bool, - /// what policy to use for index bounds checking. + /// what policy to use for index bounds checking for arrays, vectors, and + /// matrices. /// /// May be `Restrict`, `ReadZeroSkipWrite`, or `UndefinedBehavior` #[argh(option)] index_bounds_check_policy: Option, + /// what policy to use for texture bounds checking. + /// + /// May be `Restrict`, `ReadZeroSkipWrite`, or `UndefinedBehavior` + #[argh(option)] + image_bounds_check_policy: Option, + /// directory to dump the SPIR-V flow dump to #[argh(option)] flow_dir: Option, @@ -107,6 +114,7 @@ impl FromStr for GlslProfileArg { struct Parameters { validation_flags: naga::valid::ValidationFlags, index_bounds_check_policy: naga::back::BoundsCheckPolicy, + image_bounds_check_policy: naga::back::BoundsCheckPolicy, entry_point: Option, spv_adjust_coordinate_space: bool, spv_flow_dump_prefix: Option, @@ -186,6 +194,9 @@ fn run() -> Result<(), Box> { if let Some(policy) = args.index_bounds_check_policy { params.index_bounds_check_policy = policy.0; } + if let Some(policy) = args.image_bounds_check_policy { + params.image_bounds_check_policy = policy.0; + } params.spv_flow_dump_prefix = args.flow_dir; params.entry_point = args.entry_point; if let Some(version) = args.profile { @@ -307,6 +318,7 @@ fn run() -> Result<(), Box> { use naga::back::spv; params.spv.index_bounds_check_policy = params.index_bounds_check_policy; + params.spv.image_bounds_check_policy = params.image_bounds_check_policy; let spv = spv::write_vec( &module, diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 1d5e4385b..cf9cf802a 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -1,9 +1,231 @@ //! Generating SPIR-V for image operations. -use super::{Block, BlockContext, Error, Instruction, LocalType, LookupType}; +use super::{ + selection::{MergeTuple, Selection}, + Block, BlockContext, Error, IdGenerator, Instruction, LocalType, LookupType, +}; use crate::arena::Handle; use spirv::Word; +/// Information about a vector of coordinates. +/// +/// The coordinate vectors expected by SPIR-V `OpImageRead` and `OpImageFetch` +/// supply the array index for arrayed images as an additional component at +/// the end, whereas Naga's `ImageLoad`, `ImageStore`, and `ImageSample` carry +/// the array index as a separate field. +/// +/// In the process of generating code to compute the combined vector, we also +/// produce SPIR-V types and vector lengths that are useful elsewhere. This +/// struct gathers that information into one place, with standard names. +struct ImageCoordinates { + /// The SPIR-V id of the combined coordinate/index vector value. + /// + /// Note: when indexing a non-arrayed 1D image, this will be a scalar. + value_id: Word, + + /// The SPIR-V id of the type of `value`. + type_id: Word, + + /// The number of components in `value`, if it is a vector, or `None` if it + /// is a scalar. + size: Option, +} + +/// A trait for image access (load or store) code generators. +/// +/// When generating code for `ImageLoad` and `ImageStore` expressions, the image +/// bounds checks policy can affect some operands of the image access +/// instruction (the coordinates, level of detail, and sample index), but other +/// aspects are unaffected: the image id, result type (if any), and the specific +/// SPIR-V instruction used. +/// +/// This struct holds the latter category of information, saving us from passing +/// a half-dozen parameters along the various code paths. The parts that are +/// affected by bounds checks, are passed as parameters to the `generate` +/// method. +trait Access { + /// The Rust type that represents SPIR-V values and types for this access. + /// + /// For operations like loads, this is `Word`. For operations like stores, + /// this is `()`. + /// + /// For `ReadZeroSkipWrite`, this will be the type of the selection + /// construct that performs the bounds checks, so it must implement + /// `MergeTuple`. + type Output: MergeTuple + Copy + Clone; + + /// Write an image access to `block`. + /// + /// Access the texel at `coordinates_id`. The optional `level_id` indicates + /// the level of detail, and `sample_id` is the index of the sample to + /// access in a multisampled texel. + /// + /// Ths method assumes that `coordinates_id` has already had the image array + /// index, if any, folded in, as done by `write_image_coordinates`. + /// + /// Return the value id produced by the instruction, if any. + /// + /// Use `id_gen` to generate SPIR-V ids as necessary. + fn generate( + &self, + id_gen: &mut IdGenerator, + coordinates_id: Word, + level_id: Option, + sample_id: Option, + block: &mut Block, + ) -> Self::Output; + + /// Return the SPIR-V type of the value produced by the code written by + /// `generate`. If the access does not produce a value, `Self::Output` + /// should be `()`. + fn result_type(&self) -> Self::Output; + + /// Construct the SPIR-V 'zero' value to be returned for an out-of-bounds + /// access under the `ReadZeroSkipWrite` policy. If the access does not + /// produce a value, `Self::Output` should be `()`. + fn out_of_bounds_value(&self, ctx: &mut BlockContext<'_>) -> Self::Output; +} + +/// Texel access information for an [`ImageLoad`] expression. +/// +/// [`ImageLoad`]: crate::Expression::ImageLoad +struct Load { + /// The specific opcode we'll use to perform the fetch. Storage images + /// require `OpImageRead`, while sampled images require `OpImageFetch`. + opcode: spirv::Op, + + /// The type id produced by the actual image access instruction. + type_id: Word, + + /// The id of the image being accessed. + image_id: Word, +} + +impl Load { + fn from_image_expr( + ctx: &mut BlockContext<'_>, + image_id: Word, + image_class: crate::ImageClass, + result_type_id: Word, + ) -> Result { + let opcode = match image_class { + crate::ImageClass::Storage { .. } => spirv::Op::ImageRead, + crate::ImageClass::Depth { .. } | crate::ImageClass::Sampled { .. } => { + spirv::Op::ImageFetch + } + }; + + // `OpImageRead` and `OpImageFetch` instructions produce vec4 + // values. Most of the time, we can just use `result_type_id` for + // this. The exception is that `Expression::ImageLoad` from a depth + // image produces a scalar `f32`, so in that case we need to find + // the right SPIR-V type for the access instruction here. + let type_id = match image_class { + crate::ImageClass::Depth { .. } => { + ctx.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Quad), + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + })) + } + _ => result_type_id, + }; + + Ok(Load { + opcode, + type_id, + image_id, + }) + } +} + +impl Access for Load { + type Output = Word; + + /// Write an instruction to access a given texel of this image. + fn generate( + &self, + id_gen: &mut IdGenerator, + coordinates_id: Word, + level_id: Option, + sample_id: Option, + block: &mut Block, + ) -> Word { + let texel_id = id_gen.next(); + let mut instruction = Instruction::image_fetch_or_read( + self.opcode, + self.type_id, + texel_id, + self.image_id, + coordinates_id, + ); + + match (level_id, sample_id) { + (None, None) => {} + (Some(level_id), None) => { + instruction.add_operand(spirv::ImageOperands::LOD.bits()); + instruction.add_operand(level_id); + } + (None, Some(sample_id)) => { + instruction.add_operand(spirv::ImageOperands::SAMPLE.bits()); + instruction.add_operand(sample_id); + } + // There's no such thing as a multi-sampled mipmap. + (Some(_), Some(_)) => unreachable!(), + } + + block.body.push(instruction); + + texel_id + } + + fn result_type(&self) -> Word { + self.type_id + } + + fn out_of_bounds_value(&self, ctx: &mut BlockContext<'_>) -> Word { + ctx.writer.write_constant_null(self.type_id) + } +} + +/// Texel access information for a [`Store`] statement. +/// +/// [`Store`]: crate::Statement::Store +struct Store { + /// The id of the image being written to. + image_id: Word, + + /// The value we're going to write to the texel. + value_id: Word, +} + +impl Access for Store { + /// Stores don't generate any value. + type Output = (); + + fn generate( + &self, + _id_gen: &mut IdGenerator, + coordinates_id: Word, + _level_id: Option, + _sample_id: Option, + block: &mut Block, + ) { + block.body.push(Instruction::image_write( + self.image_id, + coordinates_id, + self.value_id, + )); + } + + /// Stores don't generate any value, so this just returns `()`. + fn result_type(&self) {} + + /// Stores don't generate any value, so this just returns `()`. + fn out_of_bounds_value(&self, _ctx: &mut BlockContext<'_>) {} +} + impl<'w> BlockContext<'w> { /// Extend image coordinates with an array index, if necessary. /// @@ -11,20 +233,23 @@ impl<'w> BlockContext<'w> { /// index as a separate operand from the coordinates, SPIR-V image access /// instructions include the array index in the `coordinates` operand. This /// function builds a SPIR-V coordinate vector from a Naga coordinate vector - /// and array index. + /// and array index, if one is supplied, and returns a `ImageCoordinates` + /// struct describing what it built. /// /// If `array_index` is `Some(expr)`, then this function constructs a new /// vector that is `coordinates` with `array_index` concatenated onto the /// end: a `vec2` becomes a `vec3`, a scalar becomes a `vec2`, and so on. /// + /// If `array_index` is `None`, then the return value uses `coordinates` + /// unchanged. Note that, when indexing a non-arrayed 1D image, this will be + /// a scalar value. + /// + /// If needed, this function generates code to convert the array index, + /// always an integer scalar, to match the component type of `coordinates`. /// Naga's `ImageLoad` and SPIR-V's `OpImageRead`, `OpImageFetch`, and /// `OpImageWrite` all use integer coordinates, while Naga's `ImageSample` /// and SPIR-V's `OpImageSample...` instructions all take floating-point - /// coordinate vectors. The array index, always an integer scalar, may need - /// to be converted to match the component type of `coordinates`. - /// - /// If `array_index` is `None`, this function simply returns the id for - /// `coordinates`. + /// coordinate vectors. /// /// [`Expression::ImageLoad`]: crate::Expression::ImageLoad /// [`ImageSample`]: crate::Expression::ImageSample @@ -33,36 +258,48 @@ impl<'w> BlockContext<'w> { coordinates: Handle, array_index: Option>, block: &mut Block, - ) -> Result { + ) -> Result { use crate::TypeInner as Ti; use crate::VectorSize as Vs; - let coordinate_id = self.cached[coordinates]; + let coordinates_id = self.cached[coordinates]; + let ty = &self.fun_info[coordinates].ty; + let inner_ty = ty.inner_with(&self.ir_module.types); // If there's no array index, the image coordinates are exactly the // `coordinate` field of the `Expression::ImageLoad`. No work is needed. let array_index = match array_index { - None => return Ok(coordinate_id), + None => { + let value_id = coordinates_id; + let type_id = self.get_expression_type_id(ty); + let size = match *inner_ty { + Ti::Scalar { .. } => None, + Ti::Vector { size, .. } => Some(size), + _ => return Err(Error::Validation("coordinate type")), + }; + return Ok(ImageCoordinates { + value_id, + type_id, + size, + }); + } Some(ix) => ix, }; // Find the component type of `coordinates`, and figure out the size the // combined coordinate vector will have. - let (component_kind, result_size) = match *self.fun_info[coordinates] - .ty - .inner_with(&self.ir_module.types) - { - Ti::Scalar { kind, width: 4 } => (kind, Vs::Bi), + let (component_kind, size) = match *inner_ty { + Ti::Scalar { kind, width: 4 } => (kind, Some(Vs::Bi)), Ti::Vector { kind, width: 4, size: Vs::Bi, - } => (kind, Vs::Tri), + } => (kind, Some(Vs::Tri)), Ti::Vector { kind, width: 4, size: Vs::Tri, - } => (kind, Vs::Quad), + } => (kind, Some(Vs::Quad)), Ti::Vector { size: Vs::Quad, .. } => { return Err(Error::Validation("extending vec4 coordinate")); } @@ -95,21 +332,25 @@ impl<'w> BlockContext<'w> { }; // Find the SPIR-V type for the combined coordinates/index vector. - let combined_coordinate_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(result_size), + let type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: size, kind: component_kind, width: 4, pointer_class: None, })); // Schmear the coordinates and index together. - let id = self.gen_id(); + let value_id = self.gen_id(); block.body.push(Instruction::composite_construct( - combined_coordinate_type_id, - id, - &[coordinate_id, reconciled_array_index_id], + type_id, + value_id, + &[coordinates_id, reconciled_array_index_id], )); - Ok(id) + Ok(ImageCoordinates { + value_id, + type_id, + size, + }) } fn get_image_id(&mut self, expr_handle: Handle) -> Word { @@ -133,6 +374,334 @@ impl<'w> BlockContext<'w> { id } + /// Generate a vector or scalar 'one' for arithmetic on `coordinates`. + /// + /// If `coordinates` is a scalar, return a scalar one. Otherwise, return + /// a vector of ones. + fn write_coordinate_one(&mut self, coordinates: &ImageCoordinates) -> Result { + let one = self.get_scope_constant(1); + match coordinates.size { + None => Ok(one), + Some(vector_size) => { + let ones = [one; 4]; + let id = self.gen_id(); + Instruction::constant_composite( + coordinates.type_id, + id, + &ones[..vector_size as usize], + ) + .to_words(&mut self.writer.logical_layout.declarations); + Ok(id) + } + } + } + + /// Generate code to restrict `input` to fall between zero and one less than + /// `size_id`. + /// + /// Both must be 32-bit scalar integer values, whose type is given by + /// `type_id`. The computed value is also of type `type_id`. + fn restrict_scalar( + &mut self, + type_id: Word, + input_id: Word, + size_id: Word, + block: &mut Block, + ) -> Result { + let i32_one_id = self.get_scope_constant(1); + + // Subtract one from `size` to get the largest valid value. + let limit_id = self.gen_id(); + block.body.push(Instruction::binary( + spirv::Op::ISub, + type_id, + limit_id, + size_id, + i32_one_id, + )); + + // Use an unsigned minimum, to handle both positive out-of-range values + // and negative values in a single instruction: negative values of + // `input_id` get treated as very large positive values. + let restricted_id = self.gen_id(); + block.body.push(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + spirv::GLOp::UMin, + type_id, + restricted_id, + &[input_id, limit_id], + )); + + Ok(restricted_id) + } + + /// Write instructions to query the size of an image. + /// + /// This takes care of selecting the right instruction depending on whether + /// a level of detail parameter is present. + fn write_coordinate_bounds( + &mut self, + type_id: Word, + image_id: Word, + level_id: Option, + block: &mut Block, + ) -> Word { + let coordinate_bounds_id = self.gen_id(); + match level_id { + Some(level_id) => { + // A level of detail was provided, so fetch the image size for + // that level. + let mut inst = Instruction::image_query( + spirv::Op::ImageQuerySizeLod, + type_id, + coordinate_bounds_id, + image_id, + ); + inst.add_operand(level_id); + block.body.push(inst); + } + _ => { + // No level of detail was given. + block.body.push(Instruction::image_query( + spirv::Op::ImageQuerySize, + type_id, + coordinate_bounds_id, + image_id, + )); + } + } + + coordinate_bounds_id + } + + /// Write code to restrict coordinates for an image reference. + /// + /// First, clamp the level of detail or sample index to fall within bounds. + /// Then, obtain the image size, possibly using the clamped level of detail. + /// Finally, use an unsigned minimum instruction to force all coordinates + /// into range. + /// + /// Return a triple `(COORDS, LEVEL, SAMPLE)`, where `COORDS` is a coordinate + /// vector (including the array index, if any), `LEVEL` is an optional level + /// of detail, and `SAMPLE` is an optional sample index, all guaranteed to + /// be in-bounds for `image_id`. + /// + /// The result is usually a vector, but it is a scalar when indexing + /// non-arrayed 1D images. + fn write_restricted_coordinates( + &mut self, + image_id: Word, + coordinates: ImageCoordinates, + level_id: Option, + sample_id: Option, + block: &mut Block, + ) -> Result<(Word, Option, Option), Error> { + self.writer.require_any( + "the `Restrict` image bounds check policy", + &[spirv::Capability::ImageQuery], + )?; + + let i32_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + })); + + // If `level` is `Some`, clamp it to fall within bounds. This must + // happen first, because we'll use it to query the image size for + // clamping the actual coordinates. + let level_id = level_id + .map(|level_id| { + // Find the number of mipmap levels in this image. + let num_levels_id = self.gen_id(); + block.body.push(Instruction::image_query( + spirv::Op::ImageQueryLevels, + i32_type_id, + num_levels_id, + image_id, + )); + + self.restrict_scalar(i32_type_id, level_id, num_levels_id, block) + }) + .transpose()?; + + // If `sample_id` is `Some`, clamp it to fall within bounds. + let sample_id = sample_id + .map(|sample_id| { + // Find the number of samples per texel. + let num_samples_id = self.gen_id(); + block.body.push(Instruction::image_query( + spirv::Op::ImageQuerySamples, + i32_type_id, + num_samples_id, + image_id, + )); + + self.restrict_scalar(i32_type_id, sample_id, num_samples_id, block) + }) + .transpose()?; + + // Obtain the image bounds, including the array element count. + let coordinate_bounds_id = + self.write_coordinate_bounds(coordinates.type_id, image_id, level_id, block); + + // Compute maximum valid values from the bounds. + let ones = self.write_coordinate_one(&coordinates)?; + let coordinate_limit_id = self.gen_id(); + block.body.push(Instruction::binary( + spirv::Op::ISub, + coordinates.type_id, + coordinate_limit_id, + coordinate_bounds_id, + ones, + )); + + // Restrict the coordinates to fall within those bounds. + // + // Use an unsigned minimum, to handle both positive out-of-range values + // and negative values in a single instruction: negative values of + // `coordinates` get treated as very large positive values. + let restricted_coordinates_id = self.gen_id(); + block.body.push(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + spirv::GLOp::UMin, + coordinates.type_id, + restricted_coordinates_id, + &[coordinates.value_id, coordinate_limit_id], + )); + + Ok((restricted_coordinates_id, level_id, sample_id)) + } + + fn write_conditional_image_access( + &mut self, + image_id: Word, + coordinates: ImageCoordinates, + level_id: Option, + sample_id: Option, + block: &mut Block, + access: &A, + ) -> Result { + self.writer.require_any( + "the `ReadZeroSkipWrite` image bounds check policy", + &[spirv::Capability::ImageQuery], + )?; + + let bool_type_id = self.writer.get_bool_type_id(); + let i32_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_class: None, + })); + + let null_id = access.out_of_bounds_value(self); + + let mut selection = Selection::start(block, access.result_type()); + + // If `level_id` is `Some`, check whether it is within bounds. This must + // happen first, because we'll be supplying this as an argument when we + // query the image size. + if let Some(level_id) = level_id { + // Find the number of mipmap levels in this image. + let num_levels_id = self.gen_id(); + selection.block().body.push(Instruction::image_query( + spirv::Op::ImageQueryLevels, + i32_type_id, + num_levels_id, + image_id, + )); + + let lod_cond_id = self.gen_id(); + selection.block().body.push(Instruction::binary( + spirv::Op::ULessThan, + bool_type_id, + lod_cond_id, + level_id, + num_levels_id, + )); + + selection.if_true(self, lod_cond_id, null_id); + } + + // If `sample_id` is `Some`, check whether it is in bounds. + if let Some(sample_id) = sample_id { + // Find the number of samples per texel. + let num_samples_id = self.gen_id(); + selection.block().body.push(Instruction::image_query( + spirv::Op::ImageQuerySamples, + i32_type_id, + num_samples_id, + image_id, + )); + + let samples_cond_id = self.gen_id(); + selection.block().body.push(Instruction::binary( + spirv::Op::ULessThan, + bool_type_id, + samples_cond_id, + sample_id, + num_samples_id, + )); + + selection.if_true(self, samples_cond_id, null_id); + } + + // Obtain the image bounds, including any array element count. + let coordinate_bounds_id = self.write_coordinate_bounds( + coordinates.type_id, + image_id, + level_id, + selection.block(), + ); + + // Compare the coordinates against the bounds. + let coords_bool_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: coordinates.size, + kind: crate::ScalarKind::Bool, + width: 1, + pointer_class: None, + })); + let coords_conds_id = self.gen_id(); + selection.block().body.push(Instruction::binary( + spirv::Op::ULessThan, + coords_bool_type_id, + coords_conds_id, + coordinates.value_id, + coordinate_bounds_id, + )); + + // If the comparison above was a vector comparison, then we need to + // check that all components of the comparison are true. + let coords_cond_id = if coords_bool_type_id != bool_type_id { + let id = self.gen_id(); + selection.block().body.push(Instruction::relational( + spirv::Op::All, + bool_type_id, + id, + coords_conds_id, + )); + id + } else { + coords_conds_id + }; + + selection.if_true(self, coords_cond_id, null_id); + + // All conditions are met. We can carry out the access. + let texel_id = access.generate( + &mut self.writer.id_gen, + coordinates.value_id, + level_id, + sample_id, + selection.block(), + ); + + // This, then, is the value of the 'true' branch. + Ok(selection.finish(self, texel_id)) + } + /// Generate code for an `ImageLoad` expression. /// /// The arguments are the components of an `Expression::ImageLoad` variant. @@ -142,70 +711,83 @@ impl<'w> BlockContext<'w> { image: Handle, coordinate: Handle, array_index: Option>, - index: Option>, + level_or_sample: Option>, block: &mut Block, ) -> Result { let image_id = self.get_image_id(image); - let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; - - let id = self.gen_id(); - - let image_ty = self.fun_info[image].ty.inner_with(&self.ir_module.types); - let mut instruction = match *image_ty { - crate::TypeInner::Image { - class: crate::ImageClass::Storage { .. }, - .. - } => Instruction::image_read(result_type_id, id, image_id, coordinate_id), - crate::TypeInner::Image { - class: crate::ImageClass::Depth { multi: _ }, - .. - } => { - // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, - // so we need to grab the first component out of it. - let load_result_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(crate::VectorSize::Quad), - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - })); - Instruction::image_fetch(load_result_type_id, id, image_id, coordinate_id) - } - _ => Instruction::image_fetch(result_type_id, id, image_id, coordinate_id), + let image_type = self.fun_info[image].ty.inner_with(&self.ir_module.types); + let image_class = match *image_type { + crate::TypeInner::Image { class, .. } => class, + _ => return Err(Error::Validation("image type")), }; - if let Some(index) = index { - let index_id = self.cached[index]; - let image_ops = match *self.fun_info[image].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Image { - class: crate::ImageClass::Sampled { multi: true, .. }, - .. - } - | crate::TypeInner::Image { - class: crate::ImageClass::Depth { multi: true }, - .. - } => spirv::ImageOperands::SAMPLE, - _ => spirv::ImageOperands::LOD, - }; - instruction.add_operand(image_ops.bits()); - instruction.add_operand(index_id); - } + let access = Load::from_image_expr(self, image_id, image_class, result_type_id)?; + let coordinates = self.write_image_coordinates(coordinate, array_index, block)?; - let inst_type_id = instruction.type_id; - block.body.push(instruction); - let id = if inst_type_id != Some(result_type_id) { - let sub_id = self.gen_id(); + // Figure out what the `level_or_sample` operand really means. + let level_or_sample_id = level_or_sample.map(|i| self.cached[i]); + let (level_id, sample_id) = match image_class { + crate::ImageClass::Sampled { multi, .. } | crate::ImageClass::Depth { multi } => { + if multi { + (None, level_or_sample_id) + } else { + (level_or_sample_id, None) + } + } + crate::ImageClass::Storage { .. } => (None, None), + }; + + // Perform the access, according to the bounds check policy. + let access_id = match self.writer.image_bounds_check_policy { + crate::back::BoundsCheckPolicy::Restrict => { + let (coords, level_id, sample_id) = self.write_restricted_coordinates( + image_id, + coordinates, + level_id, + sample_id, + block, + )?; + access.generate(&mut self.writer.id_gen, coords, level_id, sample_id, block) + } + crate::back::BoundsCheckPolicy::ReadZeroSkipWrite => self + .write_conditional_image_access( + image_id, + coordinates, + level_id, + sample_id, + block, + &access, + )?, + crate::back::BoundsCheckPolicy::UndefinedBehavior => access.generate( + &mut self.writer.id_gen, + coordinates.value_id, + level_id, + sample_id, + block, + ), + }; + + // For depth images, `ImageLoad` expressions produce a single f32, + // whereas the SPIR-V instructions always produce a vec4. So we may have + // to pull out the component we need. + let result_id = if result_type_id == access.result_type() { + // The instruction produced the type we expected. We can use + // its result as-is. + access_id + } else { + // For `ImageClass::Depth` images, SPIR-V gave us four components, + // but we only want the first one. + let component_id = self.gen_id(); block.body.push(Instruction::composite_extract( result_type_id, - sub_id, - id, + component_id, + access_id, &[0], )); - sub_id - } else { - id + component_id }; - Ok(id) + Ok(result_id) } /// Generate code for an `ImageSample` expression. @@ -228,8 +810,8 @@ impl<'w> BlockContext<'w> { // image let image_id = self.get_image_id(image); let image_type = self.fun_info[image].ty.handle().unwrap(); - // Vulkan doesn't know about our `Depth` class, and it returns `vec4`, - // so we need to grab the first component out of it. + // SPIR-V doesn't know about our `Depth` class, and it returns + // `vec4`, so we need to grab the first component out of it. let needs_sub_access = match self.ir_module.types[image_type].inner { crate::TypeInner::Image { class: crate::ImageClass::Depth { .. }, @@ -254,7 +836,9 @@ impl<'w> BlockContext<'w> { self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id })); let sampler_id = self.get_image_id(sampler); - let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; + let coordinates_id = self + .write_image_coordinates(coordinate, array_index, block)? + .value_id; let sampled_image_id = self.gen_id(); block.body.push(Instruction::sampled_image( @@ -276,7 +860,7 @@ impl<'w> BlockContext<'w> { id, SampleLod::Explicit, sampled_image_id, - coordinate_id, + coordinates_id, depth_id, ); @@ -296,7 +880,7 @@ impl<'w> BlockContext<'w> { id, SampleLod::Implicit, sampled_image_id, - coordinate_id, + coordinates_id, depth_id, ); if !mask.is_empty() { @@ -310,7 +894,7 @@ impl<'w> BlockContext<'w> { id, SampleLod::Explicit, sampled_image_id, - coordinate_id, + coordinates_id, depth_id, ); @@ -327,7 +911,7 @@ impl<'w> BlockContext<'w> { id, SampleLod::Implicit, sampled_image_id, - coordinate_id, + coordinates_id, depth_id, ); @@ -344,7 +928,7 @@ impl<'w> BlockContext<'w> { id, SampleLod::Explicit, sampled_image_id, - coordinate_id, + coordinates_id, depth_id, ); @@ -541,12 +1125,37 @@ impl<'w> BlockContext<'w> { block: &mut Block, ) -> Result<(), Error> { let image_id = self.get_image_id(image); - let coordinate_id = self.write_image_coordinates(coordinate, array_index, block)?; + let coordinates = self.write_image_coordinates(coordinate, array_index, block)?; let value_id = self.cached[value]; - block - .body - .push(Instruction::image_write(image_id, coordinate_id, value_id)); + let write = Store { image_id, value_id }; + + match self.writer.image_bounds_check_policy { + crate::back::BoundsCheckPolicy::Restrict => { + let (coords, _, _) = + self.write_restricted_coordinates(image_id, coordinates, None, None, block)?; + write.generate(&mut self.writer.id_gen, coords, None, None, block); + } + crate::back::BoundsCheckPolicy::ReadZeroSkipWrite => { + self.write_conditional_image_access( + image_id, + coordinates, + None, + None, + block, + &write, + )?; + } + crate::back::BoundsCheckPolicy::UndefinedBehavior => { + write.generate( + &mut self.writer.id_gen, + coordinates.value_id, + None, + None, + block, + ); + } + } Ok(()) } diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 91bafbb01..5176dd0d5 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -25,7 +25,7 @@ pub(super) enum ExpressionPointer { /// The results of performing a bounds check. /// /// On success, `write_bounds_check` returns a value of this type. -pub enum BoundsCheckResult { +pub(super) enum BoundsCheckResult { /// The index is statically known and in bounds, with the given value. KnownInBounds(u32), @@ -38,7 +38,7 @@ pub enum BoundsCheckResult { } /// A value that we either know at translation time, or need to compute at runtime. -pub enum MaybeKnown { +pub(super) enum MaybeKnown { /// The value is known at shader translation time. Known(T), diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 6530160e5..ff7b3c5d3 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -609,27 +609,14 @@ impl super::Instruction { instruction } - pub(super) fn image_fetch( + pub(super) fn image_fetch_or_read( + op: Op, result_type_id: Word, id: Word, image: Word, coordinates: Word, ) -> Self { - let mut instruction = Self::new(Op::ImageFetch); - instruction.set_type(result_type_id); - instruction.set_result(id); - instruction.add_operand(image); - instruction.add_operand(coordinates); - instruction - } - - pub(super) fn image_read( - result_type_id: Word, - id: Word, - image: Word, - coordinates: Word, - ) -> Self { - let mut instruction = Self::new(Op::ImageRead); + let mut instruction = Self::new(op); instruction.set_type(result_type_id); instruction.set_result(id); instruction.add_operand(image); diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 42e51059a..9da70e0ce 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -418,6 +418,7 @@ pub struct Writer { annotations: Vec, flags: WriterFlags, index_bounds_check_policy: BoundsCheckPolicy, + image_bounds_check_policy: BoundsCheckPolicy, void_type: Word, //TODO: convert most of these into vectors, addressable by handle indices lookup_type: crate::FastHashMap, @@ -462,6 +463,9 @@ pub struct Options { /// How should the generated code handle array, vector, or matrix indices /// that are out of range? pub index_bounds_check_policy: BoundsCheckPolicy, + /// How should the generated code handle image references that are out of + /// range? + pub image_bounds_check_policy: BoundsCheckPolicy, } impl Default for Options { @@ -475,6 +479,7 @@ impl Default for Options { flags, capabilities: None, index_bounds_check_policy: super::BoundsCheckPolicy::default(), + image_bounds_check_policy: super::BoundsCheckPolicy::default(), } } } diff --git a/src/back/spv/selection.rs b/src/back/spv/selection.rs index a5558a05e..5922dedde 100644 --- a/src/back/spv/selection.rs +++ b/src/back/spv/selection.rs @@ -55,8 +55,6 @@ //! pointer for the duration of its lifetime. To obtain the block for generating //! code in the selection's body, call the `Selection::block` method. -#![allow(dead_code)] // until texture bounds checks - use super::{Block, BlockContext, Instruction}; use spirv::Word; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 5a82bae5b..0ebf6fb32 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -67,6 +67,7 @@ impl Writer { annotations: vec![], flags: options.flags, index_bounds_check_policy: options.index_bounds_check_policy, + image_bounds_check_policy: options.image_bounds_check_policy, void_type, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), @@ -103,6 +104,7 @@ impl Writer { // Copied from the old Writer: flags: self.flags, index_bounds_check_policy: self.index_bounds_check_policy, + image_bounds_check_policy: self.image_bounds_check_policy, capabilities_available: take(&mut self.capabilities_available), // Initialized afresh: diff --git a/src/lib.rs b/src/lib.rs index d5167f372..0b7f02ddd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1044,7 +1044,22 @@ pub enum Expression { level: SampleLevel, depth_ref: Option>, }, + /// Load a texel from an image. + /// + /// For most images, this returns a four-element vector of the same + /// [`ScalarKind`] as the image. If the format of the image does not have + /// four components, default values are provided: the first three components + /// (typically R, G, and B) default to zero, and the final component + /// (typically alpha) defaults to one. + /// + /// However, if the image's [`class`] is [`Depth`], then this returns a + /// [`Float`] scalar value. + /// + /// [`ScalarKind`]: ScalarKind + /// [`class`]: TypeInner::Image::class + /// [`Depth`]: ImageClass::Depth + /// [`Float`]: ScalarKind::Float ImageLoad { /// The image to load a texel from. This must have type [`Image`]. (This /// will necessarily be a [`GlobalVariable`] or [`FunctionArgument`] @@ -1110,6 +1125,7 @@ pub enum Expression { /// [`multi`]: ImageClass::Sampled::multi index: Option>, }, + /// Query information from an image. ImageQuery { image: Handle, diff --git a/tests/in/bounds-check-image-restrict.param.ron b/tests/in/bounds-check-image-restrict.param.ron new file mode 100644 index 000000000..30ade34f5 --- /dev/null +++ b/tests/in/bounds-check-image-restrict.param.ron @@ -0,0 +1,5 @@ +( + image_bounds_check_restrict: true, + spv_version: (1, 1), + spv_debug: true, +) diff --git a/tests/in/bounds-check-image-restrict.wgsl b/tests/in/bounds-check-image-restrict.wgsl new file mode 100644 index 000000000..e2f913183 --- /dev/null +++ b/tests/in/bounds-check-image-restrict.wgsl @@ -0,0 +1,83 @@ +[[group(0), binding(0)]] +var image_1d: texture_1d; + +fn test_textureLoad_1d(coords: i32, level: i32) -> vec4 { + return textureLoad(image_1d, coords, level); +} + +[[group(0), binding(0)]] +var image_2d: texture_2d; + +fn test_textureLoad_2d(coords: vec2, level: i32) -> vec4 { + return textureLoad(image_2d, coords, level); +} + +[[group(0), binding(0)]] +var image_2d_array: texture_2d_array; + +fn test_textureLoad_2d_array(coords: vec2, index: i32, level: i32) -> vec4 { + return textureLoad(image_2d_array, coords, index, level); +} + +[[group(0), binding(0)]] +var image_3d: texture_3d; + +fn test_textureLoad_3d(coords: vec3, level: i32) -> vec4 { + return textureLoad(image_3d, coords, level); +} + +[[group(0), binding(0)]] +var image_multisampled_2d: texture_multisampled_2d; + +fn test_textureLoad_multisampled_2d(coords: vec2, sample: i32) -> vec4 { + return textureLoad(image_multisampled_2d, coords, sample); +} + +[[group(0), binding(0)]] +var image_depth_2d: texture_depth_2d; + +fn test_textureLoad_depth_2d(coords: vec2, level: i32) -> f32 { + return textureLoad(image_depth_2d, coords, level); +} + +[[group(0), binding(0)]] +var image_depth_2d_array: texture_depth_2d_array; + +fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> f32 { + return textureLoad(image_depth_2d_array, coords, index, level); +} + +[[group(0), binding(0)]] +var image_depth_multisampled_2d: texture_depth_multisampled_2d; + +fn test_textureLoad_depth_multisampled_2d(coords: vec2, sample: i32) -> f32 { + return textureLoad(image_depth_multisampled_2d, coords, sample); +} + +[[group(0), binding(0)]] +var image_storage_1d: texture_storage_1d; + +fn test_textureStore_1d(coords: i32, value: vec4) { + textureStore(image_storage_1d, coords, value); +} + +[[group(0), binding(0)]] +var image_storage_2d: texture_storage_2d; + +fn test_textureStore_2d(coords: vec2, value: vec4) { + textureStore(image_storage_2d, coords, value); +} + +[[group(0), binding(0)]] +var image_storage_2d_array: texture_storage_2d_array; + +fn test_textureStore_2d_array(coords: vec2, array_index: i32, value: vec4) { + textureStore(image_storage_2d_array, coords, array_index, value); +} + +[[group(0), binding(0)]] +var image_storage_3d: texture_storage_3d; + +fn test_textureStore_3d(coords: vec3, value: vec4) { + textureStore(image_storage_3d, coords, value); +} diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/tests/in/bounds-check-image-rzsw.param.ron new file mode 100644 index 000000000..3922919f5 --- /dev/null +++ b/tests/in/bounds-check-image-rzsw.param.ron @@ -0,0 +1,5 @@ +( + image_bounds_check_read_zero_skip_write: true, + spv_version: (1, 1), + spv_debug: true, +) diff --git a/tests/in/bounds-check-image-rzsw.wgsl b/tests/in/bounds-check-image-rzsw.wgsl new file mode 100644 index 000000000..e2f913183 --- /dev/null +++ b/tests/in/bounds-check-image-rzsw.wgsl @@ -0,0 +1,83 @@ +[[group(0), binding(0)]] +var image_1d: texture_1d; + +fn test_textureLoad_1d(coords: i32, level: i32) -> vec4 { + return textureLoad(image_1d, coords, level); +} + +[[group(0), binding(0)]] +var image_2d: texture_2d; + +fn test_textureLoad_2d(coords: vec2, level: i32) -> vec4 { + return textureLoad(image_2d, coords, level); +} + +[[group(0), binding(0)]] +var image_2d_array: texture_2d_array; + +fn test_textureLoad_2d_array(coords: vec2, index: i32, level: i32) -> vec4 { + return textureLoad(image_2d_array, coords, index, level); +} + +[[group(0), binding(0)]] +var image_3d: texture_3d; + +fn test_textureLoad_3d(coords: vec3, level: i32) -> vec4 { + return textureLoad(image_3d, coords, level); +} + +[[group(0), binding(0)]] +var image_multisampled_2d: texture_multisampled_2d; + +fn test_textureLoad_multisampled_2d(coords: vec2, sample: i32) -> vec4 { + return textureLoad(image_multisampled_2d, coords, sample); +} + +[[group(0), binding(0)]] +var image_depth_2d: texture_depth_2d; + +fn test_textureLoad_depth_2d(coords: vec2, level: i32) -> f32 { + return textureLoad(image_depth_2d, coords, level); +} + +[[group(0), binding(0)]] +var image_depth_2d_array: texture_depth_2d_array; + +fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> f32 { + return textureLoad(image_depth_2d_array, coords, index, level); +} + +[[group(0), binding(0)]] +var image_depth_multisampled_2d: texture_depth_multisampled_2d; + +fn test_textureLoad_depth_multisampled_2d(coords: vec2, sample: i32) -> f32 { + return textureLoad(image_depth_multisampled_2d, coords, sample); +} + +[[group(0), binding(0)]] +var image_storage_1d: texture_storage_1d; + +fn test_textureStore_1d(coords: i32, value: vec4) { + textureStore(image_storage_1d, coords, value); +} + +[[group(0), binding(0)]] +var image_storage_2d: texture_storage_2d; + +fn test_textureStore_2d(coords: vec2, value: vec4) { + textureStore(image_storage_2d, coords, value); +} + +[[group(0), binding(0)]] +var image_storage_2d_array: texture_storage_2d_array; + +fn test_textureStore_2d_array(coords: vec2, array_index: i32, value: vec4) { + textureStore(image_storage_2d_array, coords, array_index, value); +} + +[[group(0), binding(0)]] +var image_storage_3d: texture_storage_3d; + +fn test_textureStore_3d(coords: vec3, value: vec4) { + textureStore(image_storage_3d, coords, value); +} diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm new file mode 100644 index 000000000..d99451d2f --- /dev/null +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -0,0 +1,316 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 214 +OpCapability ImageQuery +OpCapability Image1D +OpCapability Shader +OpCapability Sampled1D +OpCapability Linkage +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpSource GLSL 450 +OpName %20 "image_1d" +OpName %22 "image_2d" +OpName %24 "image_2d_array" +OpName %26 "image_3d" +OpName %28 "image_multisampled_2d" +OpName %30 "image_depth_2d" +OpName %32 "image_depth_2d_array" +OpName %34 "image_depth_multisampled_2d" +OpName %36 "image_storage_1d" +OpName %38 "image_storage_2d" +OpName %40 "image_storage_2d_array" +OpName %42 "image_storage_3d" +OpName %47 "test_textureLoad_1d" +OpName %62 "test_textureLoad_2d" +OpName %78 "test_textureLoad_2d_array" +OpName %94 "test_textureLoad_3d" +OpName %109 "test_textureLoad_multisampled_2d" +OpName %123 "test_textureLoad_depth_2d" +OpName %140 "test_textureLoad_depth_2d_array" +OpName %157 "test_textureLoad_depth_multisampled_2d" +OpName %172 "test_textureStore_1d" +OpName %182 "test_textureStore_2d" +OpName %194 "test_textureStore_2d_array" +OpName %206 "test_textureStore_3d" +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 0 +OpDecorate %22 DescriptorSet 0 +OpDecorate %22 Binding 0 +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 0 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 0 +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 0 +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 0 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 0 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 0 +OpDecorate %36 NonReadable +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 0 +OpDecorate %38 NonReadable +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 0 +OpDecorate %40 NonReadable +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 0 +OpDecorate %42 NonReadable +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 0 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpTypeImage %4 1D 0 0 0 1 Unknown +%5 = OpTypeInt 32 1 +%6 = OpTypeVector %4 4 +%7 = OpTypeImage %4 2D 0 0 0 1 Unknown +%8 = OpTypeVector %5 2 +%9 = OpTypeImage %4 2D 0 1 0 1 Unknown +%10 = OpTypeImage %4 3D 0 0 0 1 Unknown +%11 = OpTypeVector %5 3 +%12 = OpTypeImage %4 2D 0 0 1 1 Unknown +%13 = OpTypeImage %4 2D 1 0 0 1 Unknown +%14 = OpTypeImage %4 2D 1 1 0 1 Unknown +%15 = OpTypeImage %4 2D 1 0 1 1 Unknown +%16 = OpTypeImage %4 1D 0 0 0 2 Rgba8 +%17 = OpTypeImage %4 2D 0 0 0 2 Rgba8 +%18 = OpTypeImage %4 2D 0 1 0 2 Rgba8 +%19 = OpTypeImage %4 3D 0 0 0 2 Rgba8 +%21 = OpTypePointer UniformConstant %3 +%20 = OpVariable %21 UniformConstant +%23 = OpTypePointer UniformConstant %7 +%22 = OpVariable %23 UniformConstant +%25 = OpTypePointer UniformConstant %9 +%24 = OpVariable %25 UniformConstant +%27 = OpTypePointer UniformConstant %10 +%26 = OpVariable %27 UniformConstant +%29 = OpTypePointer UniformConstant %12 +%28 = OpVariable %29 UniformConstant +%31 = OpTypePointer UniformConstant %13 +%30 = OpVariable %31 UniformConstant +%33 = OpTypePointer UniformConstant %14 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer UniformConstant %15 +%34 = OpVariable %35 UniformConstant +%37 = OpTypePointer UniformConstant %16 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %17 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %18 +%40 = OpVariable %41 UniformConstant +%43 = OpTypePointer UniformConstant %19 +%42 = OpVariable %43 UniformConstant +%48 = OpTypeFunction %6 %5 %5 +%52 = OpConstant %5 1 +%63 = OpTypeFunction %6 %8 %5 +%70 = OpConstantComposite %8 %52 %52 +%79 = OpTypeFunction %6 %8 %5 %5 +%87 = OpConstantComposite %11 %52 %52 %52 +%95 = OpTypeFunction %6 %11 %5 +%102 = OpConstantComposite %11 %52 %52 %52 +%116 = OpConstantComposite %8 %52 %52 +%124 = OpTypeFunction %4 %8 %5 +%131 = OpConstantComposite %8 %52 %52 +%141 = OpTypeFunction %4 %8 %5 %5 +%149 = OpConstantComposite %11 %52 %52 %52 +%164 = OpConstantComposite %8 %52 %52 +%173 = OpTypeFunction %2 %5 %6 +%183 = OpTypeFunction %2 %8 %6 +%187 = OpConstantComposite %8 %52 %52 +%195 = OpTypeFunction %2 %8 %5 %6 +%200 = OpConstantComposite %11 %52 %52 %52 +%207 = OpTypeFunction %2 %11 %6 +%211 = OpConstantComposite %11 %52 %52 %52 +%47 = OpFunction %6 None %48 +%45 = OpFunctionParameter %5 +%46 = OpFunctionParameter %5 +%44 = OpLabel +%49 = OpLoad %3 %20 +OpBranch %50 +%50 = OpLabel +%51 = OpImageQueryLevels %5 %49 +%53 = OpISub %5 %51 %52 +%54 = OpExtInst %5 %1 UMin %46 %53 +%55 = OpImageQuerySizeLod %5 %49 %54 +%56 = OpISub %5 %55 %52 +%57 = OpExtInst %5 %1 UMin %45 %56 +%58 = OpImageFetch %6 %49 %57 Lod %54 +OpReturnValue %58 +OpFunctionEnd +%62 = OpFunction %6 None %63 +%60 = OpFunctionParameter %8 +%61 = OpFunctionParameter %5 +%59 = OpLabel +%64 = OpLoad %7 %22 +OpBranch %65 +%65 = OpLabel +%66 = OpImageQueryLevels %5 %64 +%67 = OpISub %5 %66 %52 +%68 = OpExtInst %5 %1 UMin %61 %67 +%69 = OpImageQuerySizeLod %8 %64 %68 +%71 = OpISub %8 %69 %70 +%72 = OpExtInst %8 %1 UMin %60 %71 +%73 = OpImageFetch %6 %64 %72 Lod %68 +OpReturnValue %73 +OpFunctionEnd +%78 = OpFunction %6 None %79 +%75 = OpFunctionParameter %8 +%76 = OpFunctionParameter %5 +%77 = OpFunctionParameter %5 +%74 = OpLabel +%80 = OpLoad %9 %24 +OpBranch %81 +%81 = OpLabel +%82 = OpCompositeConstruct %11 %75 %76 +%83 = OpImageQueryLevels %5 %80 +%84 = OpISub %5 %83 %52 +%85 = OpExtInst %5 %1 UMin %77 %84 +%86 = OpImageQuerySizeLod %11 %80 %85 +%88 = OpISub %11 %86 %87 +%89 = OpExtInst %11 %1 UMin %82 %88 +%90 = OpImageFetch %6 %80 %89 Lod %85 +OpReturnValue %90 +OpFunctionEnd +%94 = OpFunction %6 None %95 +%92 = OpFunctionParameter %11 +%93 = OpFunctionParameter %5 +%91 = OpLabel +%96 = OpLoad %10 %26 +OpBranch %97 +%97 = OpLabel +%98 = OpImageQueryLevels %5 %96 +%99 = OpISub %5 %98 %52 +%100 = OpExtInst %5 %1 UMin %93 %99 +%101 = OpImageQuerySizeLod %11 %96 %100 +%103 = OpISub %11 %101 %102 +%104 = OpExtInst %11 %1 UMin %92 %103 +%105 = OpImageFetch %6 %96 %104 Lod %100 +OpReturnValue %105 +OpFunctionEnd +%109 = OpFunction %6 None %63 +%107 = OpFunctionParameter %8 +%108 = OpFunctionParameter %5 +%106 = OpLabel +%110 = OpLoad %12 %28 +OpBranch %111 +%111 = OpLabel +%112 = OpImageQuerySamples %5 %110 +%113 = OpISub %5 %112 %52 +%114 = OpExtInst %5 %1 UMin %108 %113 +%115 = OpImageQuerySize %8 %110 +%117 = OpISub %8 %115 %116 +%118 = OpExtInst %8 %1 UMin %107 %117 +%119 = OpImageFetch %6 %110 %118 Sample %114 +OpReturnValue %119 +OpFunctionEnd +%123 = OpFunction %4 None %124 +%121 = OpFunctionParameter %8 +%122 = OpFunctionParameter %5 +%120 = OpLabel +%125 = OpLoad %13 %30 +OpBranch %126 +%126 = OpLabel +%127 = OpImageQueryLevels %5 %125 +%128 = OpISub %5 %127 %52 +%129 = OpExtInst %5 %1 UMin %122 %128 +%130 = OpImageQuerySizeLod %8 %125 %129 +%132 = OpISub %8 %130 %131 +%133 = OpExtInst %8 %1 UMin %121 %132 +%134 = OpImageFetch %6 %125 %133 Lod %129 +%135 = OpCompositeExtract %4 %134 0 +OpReturnValue %135 +OpFunctionEnd +%140 = OpFunction %4 None %141 +%137 = OpFunctionParameter %8 +%138 = OpFunctionParameter %5 +%139 = OpFunctionParameter %5 +%136 = OpLabel +%142 = OpLoad %14 %32 +OpBranch %143 +%143 = OpLabel +%144 = OpCompositeConstruct %11 %137 %138 +%145 = OpImageQueryLevels %5 %142 +%146 = OpISub %5 %145 %52 +%147 = OpExtInst %5 %1 UMin %139 %146 +%148 = OpImageQuerySizeLod %11 %142 %147 +%150 = OpISub %11 %148 %149 +%151 = OpExtInst %11 %1 UMin %144 %150 +%152 = OpImageFetch %6 %142 %151 Lod %147 +%153 = OpCompositeExtract %4 %152 0 +OpReturnValue %153 +OpFunctionEnd +%157 = OpFunction %4 None %124 +%155 = OpFunctionParameter %8 +%156 = OpFunctionParameter %5 +%154 = OpLabel +%158 = OpLoad %15 %34 +OpBranch %159 +%159 = OpLabel +%160 = OpImageQuerySamples %5 %158 +%161 = OpISub %5 %160 %52 +%162 = OpExtInst %5 %1 UMin %156 %161 +%163 = OpImageQuerySize %8 %158 +%165 = OpISub %8 %163 %164 +%166 = OpExtInst %8 %1 UMin %155 %165 +%167 = OpImageFetch %6 %158 %166 Sample %162 +%168 = OpCompositeExtract %4 %167 0 +OpReturnValue %168 +OpFunctionEnd +%172 = OpFunction %2 None %173 +%170 = OpFunctionParameter %5 +%171 = OpFunctionParameter %6 +%169 = OpLabel +%174 = OpLoad %16 %36 +OpBranch %175 +%175 = OpLabel +%176 = OpImageQuerySize %5 %174 +%177 = OpISub %5 %176 %52 +%178 = OpExtInst %5 %1 UMin %170 %177 +OpImageWrite %174 %178 %171 +OpReturn +OpFunctionEnd +%182 = OpFunction %2 None %183 +%180 = OpFunctionParameter %8 +%181 = OpFunctionParameter %6 +%179 = OpLabel +%184 = OpLoad %17 %38 +OpBranch %185 +%185 = OpLabel +%186 = OpImageQuerySize %8 %184 +%188 = OpISub %8 %186 %187 +%189 = OpExtInst %8 %1 UMin %180 %188 +OpImageWrite %184 %189 %181 +OpReturn +OpFunctionEnd +%194 = OpFunction %2 None %195 +%191 = OpFunctionParameter %8 +%192 = OpFunctionParameter %5 +%193 = OpFunctionParameter %6 +%190 = OpLabel +%196 = OpLoad %18 %40 +OpBranch %197 +%197 = OpLabel +%198 = OpCompositeConstruct %11 %191 %192 +%199 = OpImageQuerySize %11 %196 +%201 = OpISub %11 %199 %200 +%202 = OpExtInst %11 %1 UMin %198 %201 +OpImageWrite %196 %202 %193 +OpReturn +OpFunctionEnd +%206 = OpFunction %2 None %207 +%204 = OpFunctionParameter %11 +%205 = OpFunctionParameter %6 +%203 = OpLabel +%208 = OpLoad %19 %42 +OpBranch %209 +%209 = OpLabel +%210 = OpImageQuerySize %11 %208 +%212 = OpISub %11 %210 %211 +%213 = OpExtInst %11 %1 UMin %204 %212 +OpImageWrite %208 %213 %205 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm new file mode 100644 index 000000000..faf74b49c --- /dev/null +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -0,0 +1,390 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 244 +OpCapability ImageQuery +OpCapability Image1D +OpCapability Shader +OpCapability Sampled1D +OpCapability Linkage +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpSource GLSL 450 +OpName %20 "image_1d" +OpName %22 "image_2d" +OpName %24 "image_2d_array" +OpName %26 "image_3d" +OpName %28 "image_multisampled_2d" +OpName %30 "image_depth_2d" +OpName %32 "image_depth_2d_array" +OpName %34 "image_depth_multisampled_2d" +OpName %36 "image_storage_1d" +OpName %38 "image_storage_2d" +OpName %40 "image_storage_2d_array" +OpName %42 "image_storage_3d" +OpName %47 "test_textureLoad_1d" +OpName %65 "test_textureLoad_2d" +OpName %85 "test_textureLoad_2d_array" +OpName %105 "test_textureLoad_3d" +OpName %123 "test_textureLoad_multisampled_2d" +OpName %140 "test_textureLoad_depth_2d" +OpName %160 "test_textureLoad_depth_2d_array" +OpName %180 "test_textureLoad_depth_multisampled_2d" +OpName %198 "test_textureStore_1d" +OpName %209 "test_textureStore_2d" +OpName %222 "test_textureStore_2d_array" +OpName %235 "test_textureStore_3d" +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 0 +OpDecorate %22 DescriptorSet 0 +OpDecorate %22 Binding 0 +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 0 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 0 +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 0 +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 0 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 0 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 0 +OpDecorate %36 NonReadable +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 0 +OpDecorate %38 NonReadable +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 0 +OpDecorate %40 NonReadable +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 0 +OpDecorate %42 NonReadable +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 0 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpTypeImage %4 1D 0 0 0 1 Unknown +%5 = OpTypeInt 32 1 +%6 = OpTypeVector %4 4 +%7 = OpTypeImage %4 2D 0 0 0 1 Unknown +%8 = OpTypeVector %5 2 +%9 = OpTypeImage %4 2D 0 1 0 1 Unknown +%10 = OpTypeImage %4 3D 0 0 0 1 Unknown +%11 = OpTypeVector %5 3 +%12 = OpTypeImage %4 2D 0 0 1 1 Unknown +%13 = OpTypeImage %4 2D 1 0 0 1 Unknown +%14 = OpTypeImage %4 2D 1 1 0 1 Unknown +%15 = OpTypeImage %4 2D 1 0 1 1 Unknown +%16 = OpTypeImage %4 1D 0 0 0 2 Rgba8 +%17 = OpTypeImage %4 2D 0 0 0 2 Rgba8 +%18 = OpTypeImage %4 2D 0 1 0 2 Rgba8 +%19 = OpTypeImage %4 3D 0 0 0 2 Rgba8 +%21 = OpTypePointer UniformConstant %3 +%20 = OpVariable %21 UniformConstant +%23 = OpTypePointer UniformConstant %7 +%22 = OpVariable %23 UniformConstant +%25 = OpTypePointer UniformConstant %9 +%24 = OpVariable %25 UniformConstant +%27 = OpTypePointer UniformConstant %10 +%26 = OpVariable %27 UniformConstant +%29 = OpTypePointer UniformConstant %12 +%28 = OpVariable %29 UniformConstant +%31 = OpTypePointer UniformConstant %13 +%30 = OpVariable %31 UniformConstant +%33 = OpTypePointer UniformConstant %14 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer UniformConstant %15 +%34 = OpVariable %35 UniformConstant +%37 = OpTypePointer UniformConstant %16 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %17 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %18 +%40 = OpVariable %41 UniformConstant +%43 = OpTypePointer UniformConstant %19 +%42 = OpVariable %43 UniformConstant +%48 = OpTypeFunction %6 %5 %5 +%51 = OpTypeBool +%52 = OpConstantNull %6 +%66 = OpTypeFunction %6 %8 %5 +%69 = OpConstantNull %6 +%75 = OpTypeVector %51 2 +%86 = OpTypeFunction %6 %8 %5 %5 +%90 = OpConstantNull %6 +%96 = OpTypeVector %51 3 +%106 = OpTypeFunction %6 %11 %5 +%109 = OpConstantNull %6 +%126 = OpConstantNull %6 +%141 = OpTypeFunction %4 %8 %5 +%144 = OpConstantNull %6 +%161 = OpTypeFunction %4 %8 %5 %5 +%165 = OpConstantNull %6 +%183 = OpConstantNull %6 +%199 = OpTypeFunction %2 %5 %6 +%210 = OpTypeFunction %2 %8 %6 +%223 = OpTypeFunction %2 %8 %5 %6 +%236 = OpTypeFunction %2 %11 %6 +%47 = OpFunction %6 None %48 +%45 = OpFunctionParameter %5 +%46 = OpFunctionParameter %5 +%44 = OpLabel +%49 = OpLoad %3 %20 +OpBranch %50 +%50 = OpLabel +%53 = OpImageQueryLevels %5 %49 +%54 = OpULessThan %51 %46 %53 +OpSelectionMerge %55 None +OpBranchConditional %54 %56 %55 +%56 = OpLabel +%57 = OpImageQuerySizeLod %5 %49 %46 +%58 = OpULessThan %51 %45 %57 +OpBranchConditional %58 %59 %55 +%59 = OpLabel +%60 = OpImageFetch %6 %49 %45 Lod %46 +OpBranch %55 +%55 = OpLabel +%61 = OpPhi %6 %52 %50 %52 %56 %60 %59 +OpReturnValue %61 +OpFunctionEnd +%65 = OpFunction %6 None %66 +%63 = OpFunctionParameter %8 +%64 = OpFunctionParameter %5 +%62 = OpLabel +%67 = OpLoad %7 %22 +OpBranch %68 +%68 = OpLabel +%70 = OpImageQueryLevels %5 %67 +%71 = OpULessThan %51 %64 %70 +OpSelectionMerge %72 None +OpBranchConditional %71 %73 %72 +%73 = OpLabel +%74 = OpImageQuerySizeLod %8 %67 %64 +%76 = OpULessThan %75 %63 %74 +%77 = OpAll %51 %76 +OpBranchConditional %77 %78 %72 +%78 = OpLabel +%79 = OpImageFetch %6 %67 %63 Lod %64 +OpBranch %72 +%72 = OpLabel +%80 = OpPhi %6 %69 %68 %69 %73 %79 %78 +OpReturnValue %80 +OpFunctionEnd +%85 = OpFunction %6 None %86 +%82 = OpFunctionParameter %8 +%83 = OpFunctionParameter %5 +%84 = OpFunctionParameter %5 +%81 = OpLabel +%87 = OpLoad %9 %24 +OpBranch %88 +%88 = OpLabel +%89 = OpCompositeConstruct %11 %82 %83 +%91 = OpImageQueryLevels %5 %87 +%92 = OpULessThan %51 %84 %91 +OpSelectionMerge %93 None +OpBranchConditional %92 %94 %93 +%94 = OpLabel +%95 = OpImageQuerySizeLod %11 %87 %84 +%97 = OpULessThan %96 %89 %95 +%98 = OpAll %51 %97 +OpBranchConditional %98 %99 %93 +%99 = OpLabel +%100 = OpImageFetch %6 %87 %89 Lod %84 +OpBranch %93 +%93 = OpLabel +%101 = OpPhi %6 %90 %88 %90 %94 %100 %99 +OpReturnValue %101 +OpFunctionEnd +%105 = OpFunction %6 None %106 +%103 = OpFunctionParameter %11 +%104 = OpFunctionParameter %5 +%102 = OpLabel +%107 = OpLoad %10 %26 +OpBranch %108 +%108 = OpLabel +%110 = OpImageQueryLevels %5 %107 +%111 = OpULessThan %51 %104 %110 +OpSelectionMerge %112 None +OpBranchConditional %111 %113 %112 +%113 = OpLabel +%114 = OpImageQuerySizeLod %11 %107 %104 +%115 = OpULessThan %96 %103 %114 +%116 = OpAll %51 %115 +OpBranchConditional %116 %117 %112 +%117 = OpLabel +%118 = OpImageFetch %6 %107 %103 Lod %104 +OpBranch %112 +%112 = OpLabel +%119 = OpPhi %6 %109 %108 %109 %113 %118 %117 +OpReturnValue %119 +OpFunctionEnd +%123 = OpFunction %6 None %66 +%121 = OpFunctionParameter %8 +%122 = OpFunctionParameter %5 +%120 = OpLabel +%124 = OpLoad %12 %28 +OpBranch %125 +%125 = OpLabel +%127 = OpImageQuerySamples %5 %124 +%128 = OpULessThan %51 %122 %127 +OpSelectionMerge %129 None +OpBranchConditional %128 %130 %129 +%130 = OpLabel +%131 = OpImageQuerySize %8 %124 +%132 = OpULessThan %75 %121 %131 +%133 = OpAll %51 %132 +OpBranchConditional %133 %134 %129 +%134 = OpLabel +%135 = OpImageFetch %6 %124 %121 Sample %122 +OpBranch %129 +%129 = OpLabel +%136 = OpPhi %6 %126 %125 %126 %130 %135 %134 +OpReturnValue %136 +OpFunctionEnd +%140 = OpFunction %4 None %141 +%138 = OpFunctionParameter %8 +%139 = OpFunctionParameter %5 +%137 = OpLabel +%142 = OpLoad %13 %30 +OpBranch %143 +%143 = OpLabel +%145 = OpImageQueryLevels %5 %142 +%146 = OpULessThan %51 %139 %145 +OpSelectionMerge %147 None +OpBranchConditional %146 %148 %147 +%148 = OpLabel +%149 = OpImageQuerySizeLod %8 %142 %139 +%150 = OpULessThan %75 %138 %149 +%151 = OpAll %51 %150 +OpBranchConditional %151 %152 %147 +%152 = OpLabel +%153 = OpImageFetch %6 %142 %138 Lod %139 +OpBranch %147 +%147 = OpLabel +%154 = OpPhi %6 %144 %143 %144 %148 %153 %152 +%155 = OpCompositeExtract %4 %154 0 +OpReturnValue %155 +OpFunctionEnd +%160 = OpFunction %4 None %161 +%157 = OpFunctionParameter %8 +%158 = OpFunctionParameter %5 +%159 = OpFunctionParameter %5 +%156 = OpLabel +%162 = OpLoad %14 %32 +OpBranch %163 +%163 = OpLabel +%164 = OpCompositeConstruct %11 %157 %158 +%166 = OpImageQueryLevels %5 %162 +%167 = OpULessThan %51 %159 %166 +OpSelectionMerge %168 None +OpBranchConditional %167 %169 %168 +%169 = OpLabel +%170 = OpImageQuerySizeLod %11 %162 %159 +%171 = OpULessThan %96 %164 %170 +%172 = OpAll %51 %171 +OpBranchConditional %172 %173 %168 +%173 = OpLabel +%174 = OpImageFetch %6 %162 %164 Lod %159 +OpBranch %168 +%168 = OpLabel +%175 = OpPhi %6 %165 %163 %165 %169 %174 %173 +%176 = OpCompositeExtract %4 %175 0 +OpReturnValue %176 +OpFunctionEnd +%180 = OpFunction %4 None %141 +%178 = OpFunctionParameter %8 +%179 = OpFunctionParameter %5 +%177 = OpLabel +%181 = OpLoad %15 %34 +OpBranch %182 +%182 = OpLabel +%184 = OpImageQuerySamples %5 %181 +%185 = OpULessThan %51 %179 %184 +OpSelectionMerge %186 None +OpBranchConditional %185 %187 %186 +%187 = OpLabel +%188 = OpImageQuerySize %8 %181 +%189 = OpULessThan %75 %178 %188 +%190 = OpAll %51 %189 +OpBranchConditional %190 %191 %186 +%191 = OpLabel +%192 = OpImageFetch %6 %181 %178 Sample %179 +OpBranch %186 +%186 = OpLabel +%193 = OpPhi %6 %183 %182 %183 %187 %192 %191 +%194 = OpCompositeExtract %4 %193 0 +OpReturnValue %194 +OpFunctionEnd +%198 = OpFunction %2 None %199 +%196 = OpFunctionParameter %5 +%197 = OpFunctionParameter %6 +%195 = OpLabel +%200 = OpLoad %16 %36 +OpBranch %201 +%201 = OpLabel +%202 = OpImageQuerySize %5 %200 +%203 = OpULessThan %51 %196 %202 +OpSelectionMerge %204 None +OpBranchConditional %203 %205 %204 +%205 = OpLabel +OpImageWrite %200 %196 %197 +OpBranch %204 +%204 = OpLabel +OpReturn +OpFunctionEnd +%209 = OpFunction %2 None %210 +%207 = OpFunctionParameter %8 +%208 = OpFunctionParameter %6 +%206 = OpLabel +%211 = OpLoad %17 %38 +OpBranch %212 +%212 = OpLabel +%213 = OpImageQuerySize %8 %211 +%214 = OpULessThan %75 %207 %213 +%215 = OpAll %51 %214 +OpSelectionMerge %216 None +OpBranchConditional %215 %217 %216 +%217 = OpLabel +OpImageWrite %211 %207 %208 +OpBranch %216 +%216 = OpLabel +OpReturn +OpFunctionEnd +%222 = OpFunction %2 None %223 +%219 = OpFunctionParameter %8 +%220 = OpFunctionParameter %5 +%221 = OpFunctionParameter %6 +%218 = OpLabel +%224 = OpLoad %18 %40 +OpBranch %225 +%225 = OpLabel +%226 = OpCompositeConstruct %11 %219 %220 +%227 = OpImageQuerySize %11 %224 +%228 = OpULessThan %96 %226 %227 +%229 = OpAll %51 %228 +OpSelectionMerge %230 None +OpBranchConditional %229 %231 %230 +%231 = OpLabel +OpImageWrite %224 %226 %221 +OpBranch %230 +%230 = OpLabel +OpReturn +OpFunctionEnd +%235 = OpFunction %2 None %236 +%233 = OpFunctionParameter %11 +%234 = OpFunctionParameter %6 +%232 = OpLabel +%237 = OpLoad %19 %42 +OpBranch %238 +%238 = OpLabel +%239 = OpImageQuerySize %11 %237 +%240 = OpULessThan %96 %233 %239 +%241 = OpAll %51 %240 +OpSelectionMerge %242 None +OpBranchConditional %241 %243 %242 +%243 = OpLabel +OpImageWrite %237 %233 %234 +OpBranch %242 +%242 = OpLabel +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 9d917f47d..f92ddebdc 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -31,6 +31,10 @@ struct Parameters { bounds_check_read_zero_skip_write: bool, #[serde(default)] bounds_check_restrict: bool, + #[serde(default)] + image_bounds_check_restrict: bool, + #[serde(default)] + image_bounds_check_read_zero_skip_write: bool, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_version: (u8, u8), @@ -172,6 +176,14 @@ fn write_output_spv( } else { naga::back::BoundsCheckPolicy::UndefinedBehavior }, + image_bounds_check_policy: if params.image_bounds_check_restrict { + naga::back::BoundsCheckPolicy::Restrict + } else if params.image_bounds_check_read_zero_skip_write { + naga::back::BoundsCheckPolicy::ReadZeroSkipWrite + } else { + naga::back::BoundsCheckPolicy::UndefinedBehavior + }, + ..spv::Options::default() }; let spv = spv::write_vec(module, info, &options).unwrap(); @@ -442,6 +454,8 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ("bounds-check-zero", Targets::SPIRV), + ("bounds-check-image-restrict", Targets::SPIRV), + ("bounds-check-image-rzsw", Targets::SPIRV), ( "texture-arg", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From ea883d98e2b49a3bab843f29ee526f83bac93019 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 23 Aug 2021 01:37:05 -0400 Subject: [PATCH 1283/2212] [spv-in] track function parameter sampling flags across handle permutation --- src/front/spv/function.rs | 20 +++++--- src/front/spv/image.rs | 11 ++--- src/front/spv/mod.rs | 100 ++++++++++++++++++++++---------------- 3 files changed, 73 insertions(+), 58 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 81a4a5f88..74a00f9b1 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -1,6 +1,6 @@ use crate::arena::{Arena, Handle}; -use super::{flow::*, Error, FunctionInfo, Instruction, LookupExpression, LookupHelper as _}; +use super::{flow::*, Error, Instruction, LookupExpression, LookupHelper as _}; use crate::front::Emitter; pub type BlockId = u32; @@ -142,10 +142,8 @@ impl> super::Parser { // Read body self.function_call_graph.add_node(fun_id); let mut flow_graph = FlowGraph::new(); - - let mut function_info = FunctionInfo { - parameters_sampling: vec![super::image::SamplingFlags::empty(); fun.arguments.len()], - }; + let mut parameters_sampling = + vec![super::image::SamplingFlags::empty(); fun.arguments.len()]; // Scan the blocks and add them as nodes loop { @@ -166,7 +164,7 @@ impl> super::Parser { &module.types, &module.global_variables, &fun.arguments, - &mut function_info, + &mut parameters_sampling, )?; flow_graph.add_node(node); @@ -200,8 +198,14 @@ impl> super::Parser { // done let fun_handle = module.functions.append(fun, self.span_from_with_op(start)); - self.lookup_function.insert(fun_id, fun_handle); - self.function_info.push(function_info); + self.lookup_function.insert( + fun_id, + super::LookupFunction { + handle: fun_handle, + parameters_sampling, + }, + ); + if let Some(ep) = self.lookup_entry_point.remove(&fun_id) { // create a wrapping function let mut function = crate::Function { diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 742624278..6651a52a8 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -3,7 +3,7 @@ use crate::{ FunctionArgument, }; -use super::{Error, FunctionInfo, LookupExpression, LookupHelper as _}; +use super::{Error, LookupExpression, LookupHelper as _}; #[derive(Clone, Debug)] pub(super) struct LookupSampledImage { @@ -415,7 +415,7 @@ impl> super::Parser { global_arena: &Arena, arguments: &[FunctionArgument], expressions: &mut Arena, - function_info: &mut FunctionInfo, + parameters_sampling: &mut [SamplingFlags], ) -> Result<(), Error> { let start = self.data_offset; let result_type_id = self.next()?; @@ -513,9 +513,7 @@ impl> super::Parser { global_arena[handle].ty } crate::Expression::FunctionArgument(i) => { - let flags = &mut function_info.parameters_sampling[i as usize]; - *flags |= sampling_bit; - + parameters_sampling[i as usize] |= sampling_bit; arguments[i as usize].ty } ref other => return Err(Error::InvalidGlobalVar(other.clone())), @@ -525,8 +523,7 @@ impl> super::Parser { *self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit } crate::Expression::FunctionArgument(i) => { - let flags = &mut function_info.parameters_sampling[i as usize]; - *flags |= sampling_bit; + parameters_sampling[i as usize] |= sampling_bit; } ref other => return Err(Error::InvalidGlobalVar(other.clone())), } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d608ef604..35646e059 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -296,6 +296,11 @@ struct LookupFunctionType { return_type_id: spirv::Word, } +struct LookupFunction { + handle: Handle, + parameters_sampling: Vec, +} + #[derive(Debug)] struct EntryPoint { stage: crate::ShaderStage, @@ -387,10 +392,6 @@ impl Default for Options { } } -struct FunctionInfo { - parameters_sampling: Vec, -} - pub struct Parser { data: I, data_offset: usize, @@ -413,7 +414,7 @@ pub struct Parser { lookup_load_override: FastHashMap, lookup_sampled_image: FastHashMap, lookup_function_type: FastHashMap, - lookup_function: FastHashMap>, + lookup_function: FastHashMap, lookup_entry_point: FastHashMap, //Note: each `OpFunctionCall` gets a single entry here, indexed by the // dummy `Handle` of the call site. @@ -426,7 +427,6 @@ pub struct Parser { options: Options, index_constants: Vec>, index_constant_expressions: Vec>, - function_info: Vec, } impl> Parser { @@ -459,7 +459,6 @@ impl> Parser { options: options.clone(), index_constants: Vec::new(), index_constant_expressions: Vec::new(), - function_info: Vec::new(), } } @@ -852,7 +851,7 @@ impl> Parser { type_arena: &Arena, global_arena: &Arena, arguments: &[crate::FunctionArgument], - function_info: &mut FunctionInfo, + parmeter_sampling: &mut [image::SamplingFlags], ) -> Result { let mut block = crate::Block::new(); let mut phis = Vec::new(); @@ -1645,7 +1644,7 @@ impl> Parser { global_arena, arguments, expressions, - function_info, + parmeter_sampling, )?; } Op::ImageSampleProjImplicitLod | Op::ImageSampleProjExplicitLod => { @@ -1661,7 +1660,7 @@ impl> Parser { global_arena, arguments, expressions, - function_info, + parmeter_sampling, )?; } Op::ImageSampleDrefImplicitLod | Op::ImageSampleDrefExplicitLod => { @@ -1677,7 +1676,7 @@ impl> Parser { global_arena, arguments, expressions, - function_info, + parmeter_sampling, )?; } Op::ImageSampleProjDrefImplicitLod | Op::ImageSampleProjDrefExplicitLod => { @@ -1693,7 +1692,7 @@ impl> Parser { global_arena, arguments, expressions, - function_info, + parmeter_sampling, )?; } Op::ImageQuerySize => { @@ -2415,7 +2414,7 @@ impl> Parser { &mut self, statements: &mut crate::Block, expressions: &mut Arena, - function: Option>, + fun_parameter_sampling: &mut [image::SamplingFlags], ) -> Result<(), Error> { use crate::Statement as S; let mut i = 0usize; @@ -2423,7 +2422,7 @@ impl> Parser { match statements[i] { S::Emit(_) => {} S::Block(ref mut block) => { - self.patch_statements(block, expressions, function)?; + self.patch_statements(block, expressions, fun_parameter_sampling)?; } S::If { condition: _, @@ -2435,8 +2434,8 @@ impl> Parser { let extracted = mem::take(accept); statements.splice(i + 1..i + 1, extracted); } else { - self.patch_statements(reject, expressions, function)?; - self.patch_statements(accept, expressions, function)?; + self.patch_statements(reject, expressions, fun_parameter_sampling)?; + self.patch_statements(accept, expressions, fun_parameter_sampling)?; } } S::Switch { @@ -2450,17 +2449,21 @@ impl> Parser { statements.splice(i + 1..i + 1, extracted); } else { for case in cases.iter_mut() { - self.patch_statements(&mut case.body, expressions, function)?; + self.patch_statements( + &mut case.body, + expressions, + fun_parameter_sampling, + )?; } - self.patch_statements(default, expressions, function)?; + self.patch_statements(default, expressions, fun_parameter_sampling)?; } } S::Loop { ref mut body, ref mut continuing, } => { - self.patch_statements(body, expressions, function)?; - self.patch_statements(continuing, expressions, function)?; + self.patch_statements(body, expressions, fun_parameter_sampling)?; + self.patch_statements(continuing, expressions, fun_parameter_sampling)?; } S::Break | S::Continue @@ -2476,21 +2479,16 @@ impl> Parser { .. } => { let fun_id = self.deferred_function_calls[callee.index()]; - let handle = *self.lookup_function.lookup(fun_id)?; + let fun_lookup = self.lookup_function.lookup(fun_id)?; + *callee = fun_lookup.handle; // Patch sampling flags - for (i, arg) in arguments.iter().enumerate() { - let callee_info = &self.function_info[handle.index()]; - - let flags = match callee_info.parameters_sampling.get(i) { - Some(&flags) => flags, + for (arg_index, arg) in arguments.iter().enumerate() { + let flags = match fun_lookup.parameters_sampling.get(arg_index) { + Some(&flags) if !flags.is_empty() => flags, _ => continue, }; - if flags.is_empty() { - continue; - } - match expressions[*arg] { crate::Expression::GlobalVariable(handle) => { if let Some(sampling) = self.handle_sampling.get_mut(&handle) { @@ -2498,17 +2496,11 @@ impl> Parser { } } crate::Expression::FunctionArgument(i) => { - if let Some(handle) = function { - let function_info = - self.function_info.get_mut(handle.index()).unwrap(); - function_info.parameters_sampling[i as usize] |= flags; - } + fun_parameter_sampling[i as usize] |= flags; } ref other => return Err(Error::InvalidGlobalVar(other.clone())), } } - - *callee = handle; } } i += 1; @@ -2521,13 +2513,35 @@ impl> Parser { handle: Option>, fun: &mut crate::Function, ) -> Result<(), Error> { + // Note: this search is a bit unfortunate + let (fun_id, mut parameters_sampling) = match handle { + Some(h) => { + let (&fun_id, lookup) = self + .lookup_function + .iter_mut() + .find(|&(_, ref lookup)| lookup.handle == h) + .unwrap(); + (fun_id, mem::take(&mut lookup.parameters_sampling)) + } + None => (0, Vec::new()), + }; + for (_, expr) in fun.expressions.iter_mut() { if let crate::Expression::CallResult(ref mut function) = *expr { let fun_id = self.deferred_function_calls[function.index()]; - *function = *self.lookup_function.lookup(fun_id)?; + *function = self.lookup_function.lookup(fun_id)?.handle; } } - self.patch_statements(&mut fun.body, &mut fun.expressions, handle)?; + + self.patch_statements( + &mut fun.body, + &mut fun.expressions, + &mut parameters_sampling, + )?; + + if let Some(lookup) = self.lookup_function.get_mut(&fun_id) { + lookup.parameters_sampling = parameters_sampling; + } Ok(()) } @@ -2633,13 +2647,13 @@ impl> Parser { // skip all the fake IDs registered for the entry points continue; } - let handle = self.lookup_function.get_mut(&fun_id).unwrap(); + let lookup = self.lookup_function.get_mut(&fun_id).unwrap(); // take out the function from the old array - let fun = mem::take(&mut functions[*handle]); + let fun = mem::take(&mut functions[lookup.handle]); // add it to the newly formed arena, and adjust the lookup - *handle = module + lookup.handle = module .functions - .append(fun, functions.get_span(*handle).clone()); + .append(fun, functions.get_span(lookup.handle).clone()); } } // patch all the functions From b56349e9bff3412c2aec1107075df982c59dc817 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 21 Aug 2021 13:59:31 -0700 Subject: [PATCH 1284/2212] [spv-out] Fix the processing of cube array images. Using 1D images should require either the `Sampled1D` or `Image1D` capability. Using cube array images should require either the `SampledCubeArray` or `ImageCubeArray` capability. --- src/back/spv/writer.rs | 56 ++++++++++++++++++-------------------- tests/out/spv/image.spvasm | 1 + 2 files changed, 28 insertions(+), 29 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 0ebf6fb32..1af929eda 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -719,35 +719,10 @@ impl Writer { arrayed, class, } => { - let kind = match class { - crate::ImageClass::Sampled { kind, multi: _ } => { - if dim == crate::ImageDimension::D1 { - self.require_any("1D sampled images", &[spirv::Capability::Sampled1D])?; - } - kind - } - crate::ImageClass::Depth { multi: _ } => crate::ScalarKind::Float, - crate::ImageClass::Storage { format, .. } => { - match dim { - crate::ImageDimension::D1 => { - self.require_any( - "1D storage images", - &[spirv::Capability::Image1D], - )?; - } - crate::ImageDimension::Cube => { - if arrayed { - self.require_any( - "arrayed cube images", - &[spirv::Capability::ImageCubeArray], - )?; - } - } - _ => {} - }; - - format.into() - } + let (kind, sampled) = match class { + crate::ImageClass::Sampled { kind, multi: _ } => (kind, true), + crate::ImageClass::Depth { multi: _ } => (crate::ScalarKind::Float, true), + crate::ImageClass::Storage { format, .. } => (format.into(), false), }; let local_type = LocalType::Value { vector_size: None, @@ -756,6 +731,29 @@ impl Writer { pointer_class: None, }; let dim = map_dim(dim); + match dim { + spirv::Dim::Dim1D => { + if sampled { + self.require_any("sampled 1D images", &[spirv::Capability::Sampled1D])?; + } else { + self.require_any("1D storage images", &[spirv::Capability::Image1D])?; + } + } + spirv::Dim::DimCube if arrayed => { + if sampled { + self.require_any( + "sampled cube array images", + &[spirv::Capability::SampledCubeArray], + )?; + } else { + self.require_any( + "cube array storage images", + &[spirv::Capability::ImageCubeArray], + )?; + } + } + _ => {} + } let type_id = self.get_type_id(LookupType::Local(local_type)); Instruction::type_image(id, type_id, dim, arrayed, class) } diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 299dc344a..f2b104fc4 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -2,6 +2,7 @@ ; Version: 1.1 ; Generator: rspirv ; Bound: 213 +OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D OpCapability Shader From 9713dbbbc195697fff86429e3d507a1b3960f047 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 19 Aug 2021 13:03:45 -0700 Subject: [PATCH 1285/2212] [spv-out] Quick tests for capability requests. --- src/back/spv/writer.rs | 5 ++ tests/spirv-capabilities.rs | 172 ++++++++++++++++++++++++++++++++++++ 2 files changed, 177 insertions(+) create mode 100644 tests/spirv-capabilities.rs diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 1af929eda..dac71b19f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1310,6 +1310,11 @@ impl Writer { self.logical_layout.in_words(words); Ok(()) } + + /// Return the set of capabilities the last module written used. + pub fn get_capabilities_used(&self) -> &crate::FastHashSet { + &self.capabilities_used + } } #[test] diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs new file mode 100644 index 000000000..c4664a90c --- /dev/null +++ b/tests/spirv-capabilities.rs @@ -0,0 +1,172 @@ +//! Test SPIR-V backend capability checks. + +#![cfg(all(feature = "wgsl-in", feature = "spv-out"))] + +use spirv::Capability as Ca; + +fn capabilities_used(source: &str) -> naga::FastHashSet { + use naga::back::spv; + use naga::valid; + + let module = naga::front::wgsl::parse_str(source).unwrap_or_else(|e| { + panic!( + "expected WGSL to parse successfully:\n{}", + e.emit_to_string(source) + ); + }); + + let info = valid::Validator::new(valid::ValidationFlags::all(), valid::Capabilities::all()) + .validate(&module) + .expect("validation failed"); + + let mut words = vec![]; + let mut writer = spv::Writer::new(&spv::Options::default()).unwrap(); + writer.write(&module, &info, &mut words).unwrap(); + writer.get_capabilities_used().clone() +} + +fn require(capabilities: &[Ca], source: &str) { + let caps_used = capabilities_used(source); + + let missing_caps: Vec<_> = capabilities + .iter() + .filter(|cap| !caps_used.contains(cap)) + .cloned() + .collect(); + if !missing_caps.is_empty() { + panic!( + "shader code should have requested these caps: {:?}", + missing_caps + ); + } +} + +fn require_and_forbid(required: &[Ca], forbidden: &[Ca], source: &str) { + let caps_used = capabilities_used(source); + + let missing_caps: Vec<_> = required + .iter() + .filter(|cap| !caps_used.contains(cap)) + .cloned() + .collect(); + if !missing_caps.is_empty() { + panic!( + "shader code should have requested these caps: {:?}", + missing_caps + ); + } + + let forbidden_caps: Vec<_> = forbidden + .iter() + .filter(|cap| caps_used.contains(cap)) + .cloned() + .collect(); + if !forbidden_caps.is_empty() { + panic!( + "shader code should not have requested these caps: {:?}", + forbidden_caps + ); + } +} + +#[test] +fn sampler1d() { + require( + &[Ca::Sampled1D], + r#" + [[group(0), binding(0)]] + var image_1d: texture_1d; + "#, + ); +} + +#[test] +fn storage1d() { + require( + &[Ca::Image1D], + r#" + [[group(0), binding(0)]] + var image_1d: texture_storage_1d; + "#, + ); +} + +#[test] +fn cube_array() { + // ImageCubeArray is only for storage cube array images, which WGSL doesn't + // support + require_and_forbid( + &[Ca::SampledCubeArray], + &[Ca::ImageCubeArray], + r#" + [[group(0), binding(0)]] + var image_cube: texture_cube_array; + "#, + ); +} + +#[test] +fn image_queries() { + require( + &[Ca::ImageQuery], + r#" + fn f(i: texture_2d) -> vec2 { + return textureDimensions(i); + } + "#, + ); + require( + &[Ca::ImageQuery], + r#" + fn f(i: texture_2d_array) -> i32 { + return textureNumLayers(i); + } + "#, + ); + require( + &[Ca::ImageQuery], + r#" + fn f(i: texture_2d) -> i32 { + return textureNumLevels(i); + } + "#, + ); + require( + &[Ca::ImageQuery], + r#" + fn f(i: texture_multisampled_2d) -> i32 { + return textureNumSamples(i); + } + "#, + ); +} + +#[test] +fn sample_rate_shading() { + require( + &[Ca::SampleRateShading], + r#" + [[stage(fragment)]] + fn f([[location(0), interpolate(perspective, sample)]] x: f32) { } + "#, + ); + + require( + &[Ca::SampleRateShading], + r#" + [[stage(fragment)]] + fn f([[builtin(sample_index)]] x: u32) { } + "#, + ); +} + +#[test] +fn geometry() { + require( + &[Ca::Geometry], + r#" + [[stage(fragment)]] + fn f([[builtin(primitive_index)]] x: u32) { } + "#, + ); +} From 93db57c12b4a5eff48bdd00c494efa5ec89567ad Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 16 Jun 2021 14:42:20 -0700 Subject: [PATCH 1286/2212] [wgsl-in] Test validation of arrays with zero and negative lengths. --- tests/wgsl-errors.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 8f3f9ad8f..a99cd96aa 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -606,6 +606,15 @@ fn invalid_arrays() { .. }) } + + check_validation_error! { + "type Bad = array;", + "type Bad = array;": + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::NonPositiveArrayLength(_), + .. + }) + } } #[test] From 58a5b7d2b9d9e09e4e55521e060849f5ebe64ad2 Mon Sep 17 00:00:00 2001 From: Hans Christian Schmitz Date: Tue, 24 Aug 2021 07:50:53 +0200 Subject: [PATCH 1287/2212] Implement lexing and parsing for all WGSL number literal types (#1184) * Implement lexing for all WGSL number literal types * Move number literal test cases * Adjust tests to match WGSL spec on number literals Suffixes are not type names and currently only a plain `u` is supported for uints. More specifically, `i` and `f` suffixes or suffixes with widths in bits like `u32` are not supported at the moment. * Add more tests for invalid number literal suffixes * Replace code too new for Rust 1.43 * Implement parsing for hexadecimal integers * Switch to enum number types, and Bytes for width * Check for negative and leading zeros in int literals * Implement parsing of hex floats with hexf-parse * Update error message tests * Update snapshot test output files * Clean up lexer state machine code * Clean up unexpected token error code * Move number literal parsing to own submodule --- Cargo.toml | 3 +- src/front/wgsl/lexer.rs | 364 ++++++++++++++++---- src/front/wgsl/mod.rs | 176 +++++++--- src/front/wgsl/number_literals.rs | 239 +++++++++++++ src/front/wgsl/tests.rs | 72 +++- tests/in/interpolate.wgsl | 2 +- tests/out/glsl/boids.main.Compute.glsl | 2 +- tests/out/glsl/operators.main.Compute.glsl | 2 +- tests/out/glsl/quad.main.Vertex.glsl | 2 +- tests/out/glsl/shadow.fs_main.Fragment.glsl | 2 +- tests/out/hlsl/boids.hlsl | 2 +- tests/out/hlsl/image.hlsl | 4 +- tests/out/hlsl/operators.hlsl | 2 +- tests/out/hlsl/quad.hlsl | 2 +- tests/out/hlsl/shadow.hlsl | 4 +- tests/out/msl/boids.msl | 2 +- tests/out/msl/image.msl | 4 +- tests/out/msl/operators.msl | 2 +- tests/out/msl/quad.msl | 2 +- tests/out/msl/shadow.msl | 2 +- tests/out/wgsl/boids.wgsl | 2 +- tests/out/wgsl/image.wgsl | 4 +- tests/out/wgsl/operators.wgsl | 2 +- tests/out/wgsl/quad.wgsl | 2 +- tests/out/wgsl/shadow.wgsl | 4 +- tests/wgsl-errors.rs | 28 +- 26 files changed, 750 insertions(+), 182 deletions(-) create mode 100644 src/front/wgsl/number_literals.rs diff --git a/Cargo.toml b/Cargo.toml index 92f911b71..3e99aa6b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.5", optional = true } rose_tree = { version ="0.2", optional = true } pp-rs = { version = "0.2.1", optional = true } +hexf-parse = { version = "0.2.1", optional = true } [features] default = [] @@ -40,7 +41,7 @@ serialize = ["serde"] deserialize = ["serde"] spv-in = ["petgraph", "spirv", "rose_tree"] spv-out = ["spirv"] -wgsl-in = ["codespan-reporting"] +wgsl-in = ["codespan-reporting", "hexf-parse"] wgsl-out = [] hlsl-out = [] span = ["codespan-reporting"] diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 39545ea73..1a3b63b2d 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -1,4 +1,4 @@ -use super::{conv, Error, ExpectedToken, Span, Token, TokenSpan}; +use super::{conv, Error, ExpectedToken, NumberType, Span, Token, TokenSpan}; fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { if input.starts_with(what) { @@ -13,48 +13,283 @@ fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { input.split_at(pos) } +/// Tries to skip a given prefix in the input string. +/// Returns whether the prefix was present and could therefore be skipped, +/// the remaining str and the number of *bytes* skipped. +pub fn try_skip_prefix<'a, 'b>(input: &'a str, prefix: &'b str) -> (bool, &'a str, usize) { + if input.starts_with(prefix) { + (true, &input[prefix.len()..], prefix.len()) + } else { + (false, input, 0) + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum NLDigitState { + Nothing, + LeadingZero, + DigitBeforeDot, + OnlyDot, + DigitsThenDot, + DigitAfterDot, + Exponent, + SignAfterExponent, + DigitAfterExponent, +} + +struct NumberLexerState { + _minus: bool, + hex: bool, + leading_zeros: usize, + digit_state: NLDigitState, + uint_suffix: bool, +} + +impl NumberLexerState { + // TODO: add proper error reporting, possibly through try_into_token function returning Result + + pub fn _is_valid_number(&self) -> bool { + match *self { + Self { + _minus: false, // No negative zero for integers. + hex, + leading_zeros, + digit_state: NLDigitState::LeadingZero, + .. + } => hex || leading_zeros == 1, // No leading zeros allowed in non-hex integers, "0" is always allowed. + Self { + _minus: minus, + hex, + leading_zeros, + digit_state: NLDigitState::DigitBeforeDot, + uint_suffix, + } => { + (hex || leading_zeros == 0) // No leading zeros allowed in non-hex integers. + // In this state the number has non-zero digits, + // i.e. it is not just "0". + && (minus ^ uint_suffix) // Either a negative number, or and unsigned integer, not both. + } + _ => self.is_float(), + } + } + + pub fn is_float(&self) -> bool { + !self.uint_suffix + && (self.digit_state == NLDigitState::DigitsThenDot + || self.digit_state == NLDigitState::DigitAfterDot + || self.digit_state == NLDigitState::DigitAfterExponent) + } +} + fn consume_number(input: &str) -> (Token, &str) { - //Note: I wish this function was simpler and faster... - let mut is_first_char = true; - let mut right_after_exponent = false; + let (minus, working_substr, minus_offset) = try_skip_prefix(input, "-"); + + let (hex, working_substr, hex_offset) = try_skip_prefix(working_substr, "0x"); + + let mut state = NumberLexerState { + _minus: minus, + hex, + leading_zeros: 0, + digit_state: NLDigitState::Nothing, + uint_suffix: false, + }; let mut what = |c| { - if is_first_char { - is_first_char = false; - c == '-' || ('0'..='9').contains(&c) || c == '.' - } else if c == 'e' || c == 'E' { - right_after_exponent = true; - true - } else if right_after_exponent { - right_after_exponent = false; - ('0'..='9').contains(&c) || c == '-' - } else { - ('0'..='9').contains(&c) || c == '.' - } - }; - let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); - let (value, rest) = input.split_at(pos); - - let mut rest_iter = rest.chars(); - let ty = rest_iter.next().unwrap_or(' '); - match ty { - 'u' | 'i' | 'f' => { - let width_end = rest_iter - .position(|c| !('0'..='9').contains(&c)) - .unwrap_or_else(|| rest.len() - 1); - let (width, rest) = rest[1..].split_at(width_end); - (Token::Number { value, ty, width }, rest) - } - // default to `i32` or `f32` - _ => ( - Token::Number { - value, - ty: if value.contains('.') { 'f' } else { 'i' }, - width: "", + match state { + NumberLexerState { + hex, + digit_state: NLDigitState::Nothing, + uint_suffix: false, + .. + } => match c { + '0' => { + state.digit_state = NLDigitState::LeadingZero; + state.leading_zeros += 1; + } + '1'..='9' => { + state.digit_state = NLDigitState::DigitBeforeDot; + } + 'a'..='f' | 'A'..='F' if hex => { + state.digit_state = NLDigitState::DigitBeforeDot; + } + '.' => { + state.digit_state = NLDigitState::OnlyDot; + } + _ => return false, }, - rest, - ), - } + + NumberLexerState { + hex, + digit_state: NLDigitState::LeadingZero, + uint_suffix: false, + .. + } => match c { + '0' => { + // We stay in NLDigitState::LeadingZero. + state.leading_zeros += 1; + } + '1'..='9' => { + state.digit_state = NLDigitState::DigitBeforeDot; + } + 'a'..='f' | 'A'..='F' if hex => { + state.digit_state = NLDigitState::DigitBeforeDot; + } + '.' => { + state.digit_state = NLDigitState::DigitsThenDot; + } + 'e' | 'E' if !hex => { + state.digit_state = NLDigitState::Exponent; + } + 'p' | 'P' if hex => { + state.digit_state = NLDigitState::Exponent; + } + 'u' => { + // We stay in NLDigitState::LeadingZero. + state.uint_suffix = true; + } + _ => return false, + }, + + NumberLexerState { + hex, + digit_state: NLDigitState::DigitBeforeDot, + uint_suffix: false, + .. + } => match c { + '0'..='9' => { + // We stay in NLDigitState::DigitBeforeDot. + } + 'a'..='f' | 'A'..='F' if hex => { + // We stay in NLDigitState::DigitBeforeDot. + } + '.' => { + state.digit_state = NLDigitState::DigitsThenDot; + } + 'e' | 'E' if !hex => { + state.digit_state = NLDigitState::Exponent; + } + 'p' | 'P' if hex => { + state.digit_state = NLDigitState::Exponent; + } + 'u' => { + // We stay in NLDigitState::DigitBeforeDot. + state.uint_suffix = true; + } + _ => return false, + }, + + NumberLexerState { + hex, + digit_state: NLDigitState::OnlyDot, + uint_suffix: false, + .. + } => match c { + '0'..='9' => { + state.digit_state = NLDigitState::DigitAfterDot; + } + 'a'..='f' | 'A'..='F' if hex => { + state.digit_state = NLDigitState::DigitAfterDot; + } + _ => return false, + }, + + NumberLexerState { + hex, + digit_state: NLDigitState::DigitsThenDot, + uint_suffix: false, + .. + } + | NumberLexerState { + hex, + digit_state: NLDigitState::DigitAfterDot, + uint_suffix: false, + .. + } => match c { + '0'..='9' => { + state.digit_state = NLDigitState::DigitAfterDot; + } + 'a'..='f' | 'A'..='F' if hex => { + state.digit_state = NLDigitState::DigitAfterDot; + } + 'e' | 'E' if !hex => { + state.digit_state = NLDigitState::Exponent; + } + 'p' | 'P' if hex => { + state.digit_state = NLDigitState::Exponent; + } + _ => return false, + }, + + NumberLexerState { + digit_state: NLDigitState::Exponent, + uint_suffix: false, + .. + } => match c { + '0'..='9' => { + state.digit_state = NLDigitState::DigitAfterExponent; + } + '-' | '+' => { + state.digit_state = NLDigitState::SignAfterExponent; + } + _ => return false, + }, + + NumberLexerState { + digit_state: NLDigitState::SignAfterExponent, + uint_suffix: false, + .. + } + | NumberLexerState { + digit_state: NLDigitState::DigitAfterExponent, + uint_suffix: false, + .. + } => match c { + '0'..='9' => { + state.digit_state = NLDigitState::DigitAfterExponent; + } + _ => return false, + }, + + NumberLexerState { + uint_suffix: true, .. + } => return false, // Scanning is done once we've reached a type suffix. + } + + // No match branch has rejected this yet, so we are still in a number literal + true + }; + + let pos = working_substr + .find(|c| !what(c)) + .unwrap_or_else(|| working_substr.len()); + let (value, rest) = input.split_at(pos + minus_offset + hex_offset); + + // NOTE: This code can use string slicing, + // because number literals are exclusively ASCII. + // This means all relevant characters fit into one byte + // and using string slicing (which slices UTF-8 bytes) works for us. + + // TODO: A syntax error can already be recognized here, possibly report it at this stage. + + // Return possibly knowably incorrect (given !state.is_valid_number()) token for now. + ( + Token::Number { + value: if state.uint_suffix { + &value[..value.len() - 1] + } else { + value + }, + ty: if state.uint_suffix { + NumberType::Uint + } else if state.is_float() { + NumberType::Float + } else { + NumberType::Sint + }, + width: None, + }, + rest, + ) } fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { @@ -291,34 +526,6 @@ impl<'a> Lexer<'a> { } } - fn _next_float_literal(&mut self) -> Result> { - match self.next() { - (Token::Number { value, .. }, span) => { - value.parse().map_err(|e| Error::BadFloat(span, e)) - } - other => Err(Error::Unexpected(other, ExpectedToken::Float)), - } - } - - pub(super) fn next_uint_literal(&mut self) -> Result> { - match self.next() { - (Token::Number { value, .. }, span) => { - let v = value.parse(); - v.map_err(|e| Error::BadU32(span, e)) - } - other => Err(Error::Unexpected(other, ExpectedToken::Uint)), - } - } - - pub(super) fn next_sint_literal(&mut self) -> Result> { - match self.next() { - (Token::Number { value, .. }, span) => { - value.parse().map_err(|e| Error::BadI32(span, e)) - } - other => Err(Error::Unexpected(other, ExpectedToken::Sint)), - } - } - /// Parses a generic scalar type, for example ``. pub(super) fn next_scalar_generic( &mut self, @@ -409,8 +616,8 @@ fn test_tokens() { &[ Token::Number { value: "92", - ty: 'i', - width: "", + ty: NumberType::Sint, + width: None, }, Token::Word("No"), ], @@ -420,8 +627,13 @@ fn test_tokens() { &[ Token::Number { value: "2", - ty: 'u', - width: "3", + ty: NumberType::Uint, + width: None, + }, + Token::Number { + value: "3", + ty: NumberType::Sint, + width: None, }, Token::Word("o"), ], @@ -431,10 +643,10 @@ fn test_tokens() { &[ Token::Number { value: "2.4", - ty: 'f', - width: "44", + ty: NumberType::Float, + width: None, }, - Token::Word("po"), + Token::Word("f44po"), ], ); sub_test( @@ -456,8 +668,8 @@ fn test_variable_decl() { Token::Paren('('), Token::Number { value: "0", - ty: 'i', - width: "", + ty: NumberType::Sint, + width: None, }, Token::Paren(')'), Token::DoubleParen(']'), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 3b931f784..bf97c8e0c 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -4,6 +4,7 @@ mod conv; mod lexer; +mod number_literals; #[cfg(test)] mod tests; @@ -13,10 +14,16 @@ use crate::{ ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution, }, span::Span as NagaSpan, - ConstantInner, FastHashMap, ScalarValue, + Bytes, ConstantInner, FastHashMap, ScalarValue, }; -use self::lexer::Lexer; +use self::{ + lexer::Lexer, + number_literals::{ + get_f32_literal, get_i32_literal, get_u32_literal, parse_generic_non_negative_int_literal, + parse_non_negative_sint_literal, parse_sint_literal, + }, +}; use codespan_reporting::{ diagnostic::{Diagnostic, Label}, files::{Files, SimpleFile}, @@ -25,6 +32,7 @@ use codespan_reporting::{ termcolor::{ColorChoice, ColorSpec, StandardStream, WriteColor}, }, }; +use hexf_parse::ParseHexfError; use std::{ borrow::Cow, convert::TryFrom, @@ -37,6 +45,13 @@ use thiserror::Error; type Span = ops::Range; type TokenSpan<'a> = (Token<'a>, Span); +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum NumberType { + Sint, + Uint, + Float, +} + #[derive(Copy, Clone, Debug, PartialEq)] pub enum Token<'a> { Separator(char), @@ -45,8 +60,8 @@ pub enum Token<'a> { DoubleParen(char), Number { value: &'a str, - ty: char, - width: &'a str, + ty: NumberType, + width: Option, }, String(&'a str), Word(&'a str), @@ -64,9 +79,10 @@ pub enum Token<'a> { pub enum ExpectedToken<'a> { Token(Token<'a>), Identifier, - Float, - Uint, - Sint, + Number { + ty: Option, + width: Option, + }, Constant, /// Expected: constant, parenthesized expression, identifier PrimaryExpression, @@ -88,14 +104,35 @@ pub enum ExpectedToken<'a> { StructAttribute, } +#[derive(Clone, Debug, Error)] +pub enum BadIntError { + #[error(transparent)] + ParseIntError(#[from] ParseIntError), + #[error("non-hex negative zero integer literals are not allowed")] + NegativeZero, + #[error("leading zeros for non-hex integer literals are not allowed")] + LeadingZeros, +} + +#[derive(Clone, Debug, Error)] +pub enum BadFloatError { + #[error(transparent)] + ParseFloatError(#[from] ParseFloatError), + #[error(transparent)] + ParseHexfError(#[from] ParseHexfError), +} + #[derive(Clone, Debug)] pub enum Error<'a> { Unexpected(TokenSpan<'a>, ExpectedToken<'a>), - BadU32(Span, ParseIntError), - BadI32(Span, ParseIntError), - BadFloat(Span, ParseFloatError), + BadU32(Span, BadIntError), + BadI32(Span, BadIntError), + /// A negative signed integer literal where both signed and unsigned, + /// but only non-negative literals are allowed. + NegativeInt(Span), + BadFloat(Span, BadFloatError), BadU32Constant(Span), - BadScalarWidth(Span, &'a str), + BadScalarWidth(Span, Bytes), BadAccessor(Span), BadTexture(Span), BadTypeCast { @@ -158,9 +195,26 @@ impl<'a> Error<'a> { } } ExpectedToken::Identifier => "identifier".to_string(), - ExpectedToken::Float => "floating point literal".to_string(), - ExpectedToken::Uint => "non-negative integer literal".to_string(), - ExpectedToken::Sint => "integer literal".to_string(), + ExpectedToken::Number { ty, width } => { + let literal_ty_str = match ty { + Some(NumberType::Float) => "floating-point", + Some(NumberType::Uint) => "unsigned integer", + Some(NumberType::Sint) => "signed integer", + None => "arbitrary number", + }; + if let Some(width) = width { + format!( + "{} literal of {}-bit width", + literal_ty_str, + width as u32 * 8, + ) + } else { + format!( + "{} literal of arbitrary width", + literal_ty_str, + ) + } + }, ExpectedToken::Constant => "constant".to_string(), ExpectedToken::PrimaryExpression => "expression".to_string(), ExpectedToken::AttributeSeparator => "attribute separator (',') or an end of the attribute list (']]')".to_string(), @@ -187,10 +241,10 @@ impl<'a> Error<'a> { }, Error::BadU32(ref bad_span, ref err) => ParseError { message: format!( - "expected non-negative integer literal, found `{}`", + "expected unsigned integer literal, found `{}`", &source[bad_span.clone()], ), - labels: vec![(bad_span.clone(), "expected positive integer".into())], + labels: vec![(bad_span.clone(), "expected unsigned integer".into())], notes: vec![err.to_string()], }, Error::BadI32(ref bad_span, ref err) => ParseError { @@ -198,9 +252,17 @@ impl<'a> Error<'a> { "expected integer literal, found `{}`", &source[bad_span.clone()], ), - labels: vec![(bad_span.clone(), "expected integer".into())], + labels: vec![(bad_span.clone(), "expected signed integer".into())], notes: vec![err.to_string()], }, + Error::NegativeInt(ref bad_span) => ParseError { + message: format!( + "expected non-negative integer literal, found `{}`", + &source[bad_span.clone()], + ), + labels: vec![(bad_span.clone(), "expected non-negative integer".into())], + notes: vec![], + }, Error::BadFloat(ref bad_span, ref err) => ParseError { message: format!( "expected floating-point literal, found `{}`", @@ -211,17 +273,17 @@ impl<'a> Error<'a> { }, Error::BadU32Constant(ref bad_span) => ParseError { message: format!( - "expected non-negative integer constant expression, found `{}`", + "expected unsigned integer constant expression, found `{}`", &source[bad_span.clone()], ), - labels: vec![(bad_span.clone(), "expected non-negative integer".into())], + labels: vec![(bad_span.clone(), "expected unsigned integer".into())], notes: vec![], }, Error::BadScalarWidth(ref bad_span, width) => ParseError { - message: format!("invalid width of `{}` for literal", width,), + message: format!("invalid width of `{}` bits for literal", width as u32 * 8,), labels: vec![(bad_span.clone(), "invalid width".into())], - notes: vec!["valid widths are 8, 16, 32, 64".to_string()], + notes: vec!["the only valid width is 32 for now".to_string()], }, Error::BadAccessor(ref accessor_span) => ParseError { message: format!( @@ -941,7 +1003,7 @@ impl BindingParser { match name { "location" => { lexer.expect(Token::Paren('('))?; - self.location = Some(lexer.next_uint_literal()?); + self.location = Some(parse_non_negative_sint_literal(lexer, 4)?); lexer.expect(Token::Paren(')'))?; } "builtin" => { @@ -1103,36 +1165,34 @@ impl Parser { fn get_constant_inner<'a>( word: &'a str, - ty: char, - width: &'a str, - token: TokenSpan<'a>, + ty: NumberType, + width: Option, + token_span: TokenSpan<'a>, ) -> Result> { - let span = token.1; + let span = token_span.1; + + if let Some(width) = width { + if width != 4 { + // Only 32-bit literals supported by the spec and naga for now! + return Err(Error::BadScalarWidth(span, width)); + } + } + let value = match ty { - 'i' => word - .parse() - .map(crate::ScalarValue::Sint) - .map_err(|e| Error::BadI32(span.clone(), e))?, - 'u' => word - .parse() - .map(crate::ScalarValue::Uint) - .map_err(|e| Error::BadU32(span.clone(), e))?, - 'f' => word - .parse() - .map(crate::ScalarValue::Float) - .map_err(|e| Error::BadFloat(span.clone(), e))?, - _ => unreachable!(), + NumberType::Sint => { + get_i32_literal(word, span).map(|val| crate::ScalarValue::Sint(val as i64))? + } + NumberType::Uint => { + get_u32_literal(word, span).map(|val| crate::ScalarValue::Uint(val as u64))? + } + NumberType::Float => { + get_f32_literal(word, span).map(|val| crate::ScalarValue::Float(val as f64))? + } }; + Ok(crate::ConstantInner::Scalar { value, - width: if width.is_empty() { - 4 - } else { - match width.parse::() { - Ok(bits) if (bits % 8) == 0 => Ok(bits / 8), - _ => Err(Error::BadScalarWidth(span, width)), - }? - }, + width: width.unwrap_or(4), }) } @@ -2424,8 +2484,9 @@ impl Parser { match word { "size" => { lexer.expect(Token::Paren('('))?; - let (value, span) = - lexer.capture_span(Lexer::next_uint_literal)?; + let (value, span) = lexer.capture_span(|lexer| { + parse_non_negative_sint_literal(lexer, 4) + })?; lexer.expect(Token::Paren(')'))?; size = Some( NonZeroU32::new(value) @@ -2434,8 +2495,9 @@ impl Parser { } "align" => { lexer.expect(Token::Paren('('))?; - let (value, span) = - lexer.capture_span(Lexer::next_uint_literal)?; + let (value, span) = lexer.capture_span(|lexer| { + parse_non_negative_sint_literal(lexer, 4) + })?; lexer.expect(Token::Paren(')'))?; align = Some( NonZeroU32::new(value) @@ -2841,7 +2903,8 @@ impl Parser { match lexer.next() { (Token::Word("stride"), _) => { lexer.expect(Token::Paren('('))?; - let (stride, span) = lexer.capture_span(Lexer::next_uint_literal)?; + let (stride, span) = lexer + .capture_span(|lexer| parse_non_negative_sint_literal(lexer, 4))?; attribute.stride = Some(NonZeroU32::new(stride).ok_or(Error::ZeroStride(span))?); lexer.expect(Token::Paren(')'))?; @@ -3212,7 +3275,8 @@ impl Parser { (Token::Word("case"), _) => { // parse a list of values let value = loop { - let value = lexer.next_sint_literal()?; + // TODO: Switch statements also allow for floats, bools and unsigned integers. See https://www.w3.org/TR/WGSL/#switch-statement + let value = parse_sint_literal(lexer, 4)?; if lexer.skip(Token::Separator(',')) { if lexer.skip(Token::Separator(':')) { break value; @@ -3642,7 +3706,7 @@ impl Parser { match lexer.next_ident_with_span()? { ("binding", _) => { lexer.expect(Token::Paren('('))?; - bind_index = Some(lexer.next_uint_literal()?); + bind_index = Some(parse_non_negative_sint_literal(lexer, 4)?); lexer.expect(Token::Paren(')'))?; } ("block", _) => { @@ -3650,7 +3714,7 @@ impl Parser { } ("group", _) => { lexer.expect(Token::Paren('('))?; - bind_group = Some(lexer.next_uint_literal()?); + bind_group = Some(parse_non_negative_sint_literal(lexer, 4)?); lexer.expect(Token::Paren(')'))?; } ("stage", _) => { @@ -3662,7 +3726,7 @@ impl Parser { ("workgroup_size", _) => { lexer.expect(Token::Paren('('))?; for (i, size) in workgroup_size.iter_mut().enumerate() { - *size = lexer.next_uint_literal()?; + *size = parse_generic_non_negative_int_literal(lexer, 4)?; match lexer.next() { (Token::Paren(')'), _) => break, (Token::Separator(','), _) if i != 2 => (), diff --git a/src/front/wgsl/number_literals.rs b/src/front/wgsl/number_literals.rs new file mode 100644 index 000000000..2f6122414 --- /dev/null +++ b/src/front/wgsl/number_literals.rs @@ -0,0 +1,239 @@ +use std::convert::TryFrom; + +use hexf_parse::parse_hexf32; + +use crate::Bytes; + +use super::{ + lexer::{try_skip_prefix, Lexer}, + BadFloatError, BadIntError, Error, ExpectedToken, NumberType, Span, Token, +}; + +fn check_int_literal(word_without_minus: &str, minus: bool, hex: bool) -> Result<(), BadIntError> { + let leading_zeros = word_without_minus + .bytes() + .take_while(|&b| b == b'0') + .count(); + + if word_without_minus == "0" && minus { + Err(BadIntError::NegativeZero) + } else if word_without_minus != "0" && !hex && leading_zeros != 0 { + Err(BadIntError::LeadingZeros) + } else { + Ok(()) + } +} + +pub fn get_i32_literal(word: &str, span: Span) -> Result> { + let (minus, word_without_minus, _) = try_skip_prefix(word, "-"); + let (hex, word_without_minus_and_0x, _) = try_skip_prefix(word_without_minus, "0x"); + + check_int_literal(word_without_minus, minus, hex) + .map_err(|e| Error::BadI32(span.clone(), e))?; + + let parsed_val = match (hex, minus) { + (true, true) => i32::from_str_radix(&format!("-{}", word_without_minus_and_0x), 16), + (true, false) => i32::from_str_radix(word_without_minus_and_0x, 16), + (false, _) => word.parse(), + }; + + parsed_val.map_err(|e| Error::BadI32(span, e.into())) +} + +pub fn get_u32_literal(word: &str, span: Span) -> Result> { + let (minus, word_without_minus, _) = try_skip_prefix(word, "-"); + let (hex, word_without_minus_and_0x, _) = try_skip_prefix(word_without_minus, "0x"); + + check_int_literal(word_without_minus, minus, hex) + .map_err(|e| Error::BadU32(span.clone(), e))?; + + // We need to add a minus here as well, since the lexer also accepts syntactically incorrect negative uints + let parsed_val = match (hex, minus) { + (true, true) => u32::from_str_radix(&format!("-{}", word_without_minus_and_0x), 16), + (true, false) => u32::from_str_radix(word_without_minus_and_0x, 16), + (false, _) => word.parse(), + }; + + parsed_val.map_err(|e| Error::BadU32(span, e.into())) +} + +pub fn get_f32_literal(word: &str, span: Span) -> Result> { + let hex = word.starts_with("0x") || word.starts_with("-0x"); + + let parsed_val = if hex { + parse_hexf32(word, false).map_err(BadFloatError::ParseHexfError) + } else { + word.parse::().map_err(BadFloatError::ParseFloatError) + }; + + parsed_val.map_err(|e| Error::BadFloat(span, e)) +} + +pub(super) fn parse_sint_literal<'a>( + lexer: &mut Lexer<'a>, + width: Bytes, +) -> Result> { + let token_span = lexer.next(); + + if width != 4 { + // Only 32-bit literals supported by the spec and naga for now! + return Err(Error::BadScalarWidth(token_span.1, width)); + } + + match token_span { + ( + Token::Number { + value, + ty: NumberType::Sint, + width: token_width, + }, + span, + ) if token_width.unwrap_or(4) == width => get_i32_literal(value, span), + other => Err(Error::Unexpected( + other, + ExpectedToken::Number { + ty: Some(NumberType::Sint), + width: Some(width), + }, + )), + } +} + +pub(super) fn _parse_uint_literal<'a>( + lexer: &mut Lexer<'a>, + width: Bytes, +) -> Result> { + let token_span = lexer.next(); + + if width != 4 { + // Only 32-bit literals supported by the spec and naga for now! + return Err(Error::BadScalarWidth(token_span.1, width)); + } + + match token_span { + ( + Token::Number { + value, + ty: NumberType::Uint, + width: token_width, + }, + span, + ) if token_width.unwrap_or(4) == width => get_u32_literal(value, span), + other => Err(Error::Unexpected( + other, + ExpectedToken::Number { + ty: Some(NumberType::Uint), + width: Some(width), + }, + )), + } +} + +/// Parse a non-negative signed integer literal. +/// This is for attributes like `size`, `location` and others. +pub(super) fn parse_non_negative_sint_literal<'a>( + lexer: &mut Lexer<'a>, + width: Bytes, +) -> Result> { + let token_span = lexer.next(); + + if width != 4 { + // Only 32-bit literals supported by the spec and naga for now! + return Err(Error::BadScalarWidth(token_span.1, width)); + } + + match token_span { + ( + Token::Number { + value, + ty: NumberType::Sint, + width: token_width, + }, + span, + ) if token_width.unwrap_or(4) == width => { + let i32_val = get_i32_literal(value, span.clone())?; + u32::try_from(i32_val).map_err(|_| Error::NegativeInt(span)) + } + other => Err(Error::Unexpected( + other, + ExpectedToken::Number { + ty: Some(NumberType::Sint), + width: Some(width), + }, + )), + } +} + +/// Parse a non-negative integer literal that may be either signed or unsigned. +/// This is for the `workgroup_size` attribute and array lengths. +/// Note: these values should be no larger than [`i32::MAX`], but this is not checked here. +pub(super) fn parse_generic_non_negative_int_literal<'a>( + lexer: &mut Lexer<'a>, + width: Bytes, +) -> Result> { + let token_span = lexer.next(); + + if width != 4 { + // Only 32-bit literals supported by the spec and naga for now! + return Err(Error::BadScalarWidth(token_span.1, width)); + } + + match token_span { + ( + Token::Number { + value, + ty: NumberType::Sint, + width: token_width, + }, + span, + ) if token_width.unwrap_or(4) == width => { + let i32_val = get_i32_literal(value, span.clone())?; + u32::try_from(i32_val).map_err(|_| Error::NegativeInt(span)) + } + ( + Token::Number { + value, + ty: NumberType::Uint, + width: token_width, + }, + span, + ) if token_width.unwrap_or(4) == width => get_u32_literal(value, span), + other => Err(Error::Unexpected( + other, + ExpectedToken::Number { + ty: Some(NumberType::Sint), + width: Some(width), + }, + )), + } +} + +pub(super) fn _parse_float_literal<'a>( + lexer: &mut Lexer<'a>, + width: Bytes, +) -> Result> { + let token_span = lexer.next(); + + if width != 4 { + // Only 32-bit literals supported by the spec and naga for now! + return Err(Error::BadScalarWidth(token_span.1, width)); + } + + match token_span { + ( + Token::Number { + value, + ty: NumberType::Float, + width: token_width, + }, + span, + ) if token_width.unwrap_or(4) == width => get_f32_literal(value, span), + other => Err(Error::Unexpected( + other, + ExpectedToken::Number { + ty: Some(NumberType::Float), + width: Some(width), + }, + )), + } +} diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index d22310945..432b39f46 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -14,6 +14,76 @@ fn parse_comment() { .unwrap(); } +// Regexes for the literals are taken from the working draft at +// https://www.w3.org/TR/2021/WD-WGSL-20210806/#literals + +#[test] +fn parse_decimal_floats() { + // /^(-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?$/ + parse_str("let a : f32 = -1.;").unwrap(); + parse_str("let a : f32 = -.1;").unwrap(); + parse_str("let a : f32 = 42.1234;").unwrap(); + parse_str("let a : f32 = -1.E3;").unwrap(); + parse_str("let a : f32 = -.1e-5;").unwrap(); + parse_str("let a : f32 = 2.3e+55;").unwrap(); + + assert!(parse_str("let a : f32 = 42.1234f;").is_err()); + assert!(parse_str("let a : f32 = 42.1234f32;").is_err()); +} + +#[test] +fn parse_hex_floats() { + // /^-?0x([0-9a-fA-F]*\.?[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)(p|P)(\+|-)?[0-9]+$/ + parse_str("let a : f32 = -0xa.p1;").unwrap(); + parse_str("let a : f32 = -0x.fp9;").unwrap(); + parse_str("let a : f32 = 0x2a.4D2P4;").unwrap(); + parse_str("let a : f32 = -0x.1p-5;").unwrap(); + parse_str("let a : f32 = 0xC.8p+55;").unwrap(); + parse_str("let a : f32 = 0x1p1;").unwrap(); + + assert!(parse_str("let a : f32 = 0x1p1f;").is_err()); + assert!(parse_str("let a : f32 = 0x1p1f32;").is_err()); +} + +#[test] +fn parse_decimal_ints() { + // i32 /^-?0x[0-9a-fA-F]+|0|-?[1-9][0-9]*$/ + parse_str("let a : i32 = 0;").unwrap(); + parse_str("let a : i32 = 1092;").unwrap(); + parse_str("let a : i32 = -9923;").unwrap(); + + assert!(parse_str("let a : i32 = -0;").is_err()); + assert!(parse_str("let a : i32 = 01;").is_err()); + assert!(parse_str("let a : i32 = 1.0;").is_err()); + assert!(parse_str("let a : i32 = 1i;").is_err()); + assert!(parse_str("let a : i32 = 1i32;").is_err()); + + // u32 /^0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u$/ + parse_str("let a : u32 = 0u;").unwrap(); + parse_str("let a : u32 = 1092u;").unwrap(); + + assert!(parse_str("let a : u32 = -0u;").is_err()); + assert!(parse_str("let a : u32 = 01u;").is_err()); + assert!(parse_str("let a : u32 = 1.0u;").is_err()); + assert!(parse_str("let a : u32 = 1u32;").is_err()); +} + +#[test] +fn parse_hex_ints() { + // i32 /^-?0x[0-9a-fA-F]+|0|-?[1-9][0-9]*$/ + parse_str("let a : i32 = -0x0;").unwrap(); + parse_str("let a : i32 = 0x2a4D2;").unwrap(); + + assert!(parse_str("let a : i32 = 0x2a4D2i;").is_err()); + assert!(parse_str("let a : i32 = 0x2a4D2i32;").is_err()); + + // u32 /^0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u$/ + parse_str("let a : u32 = 0x0u;").unwrap(); + parse_str("let a : u32 = 0x2a4D2u;").unwrap(); + + assert!(parse_str("let a : u32 = 0x2a4D2u32;").is_err()); +} + #[test] fn parse_types() { parse_str("let a : i32 = 2;").unwrap(); @@ -32,7 +102,7 @@ fn parse_type_inference() { fn foo() { let a = 2u; let b: u32 = a; - var x = 3f32; + var x = 3.; var y = vec2(1, 2); }", ) diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index f95c0b6ca..ba134c943 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -16,7 +16,7 @@ fn main() -> FragmentInput { var out: FragmentInput; out.position = vec4(2.0, 4.0, 5.0, 6.0); - out.flat = 8u32; + out.flat = 8u; out.linear = 27.0; out.linear_centroid = vec2(64.0, 125.0); out.linear_sample = vec3(216.0, 343.0, 512.0); diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 7a925d554..e4620e662 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -126,7 +126,7 @@ void main() { vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); vec2 _e123 = vVel; vec2 _e125 = vVel; - vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.1)); + vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.10000000149011612)); vec2 _e131 = vPos; vec2 _e132 = vVel; float _e134 = _group_0_binding_0.deltaT; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 1c1cf2bd1..6c679229a 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -11,7 +11,7 @@ vec4 builtins() { vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); vec4 s3_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), bvec4(false, false, false, false)); vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); + vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); float b1_ = intBitsToFloat(ivec4(1, 1, 1, 1).x); vec4 b2_ = intBitsToFloat(ivec4(1, 1, 1, 1)); return (((((vec4(ivec4(s1_)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); diff --git a/tests/out/glsl/quad.main.Vertex.glsl b/tests/out/glsl/quad.main.Vertex.glsl index 63a447283..cda43f508 100644 --- a/tests/out/glsl/quad.main.Vertex.glsl +++ b/tests/out/glsl/quad.main.Vertex.glsl @@ -15,7 +15,7 @@ smooth out vec2 _vs2fs_location0; void main() { vec2 pos = _p2vs_location0; vec2 uv = _p2vs_location1; - VertexOutput _tmp_return = VertexOutput(uv, vec4((1.2 * pos), 0.0, 1.0)); + VertexOutput _tmp_return = VertexOutput(uv, vec4((1.2000000476837158 * pos), 0.0, 1.0)); _vs2fs_location0 = _tmp_return.uv; gl_Position = _tmp_return.position; return; diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index e3502e2bc..7e5bf3653 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -36,7 +36,7 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { void main() { vec3 raw_normal = _vs2fs_location0; vec4 position = _vs2fs_location1; - vec3 color = vec3(0.05, 0.05, 0.05); + vec3 color = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i = 0u; vec3 normal = normalize(raw_normal); bool loop_init = true; diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index 9288e5c0c..02744cc40 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -118,7 +118,7 @@ void main(uint3 global_invocation_id : SV_DispatchThreadID) vVel = (((_expr107 + (_expr108 * _expr110)) + (_expr113 * _expr115)) + (_expr118 * _expr120)); float2 _expr123 = vVel; float2 _expr125 = vVel; - vVel = (normalize(_expr123) * clamp(length(_expr125), 0.0, 0.1)); + vVel = (normalize(_expr123) * clamp(length(_expr125), 0.0, 0.10000000149011612)); float2 _expr131 = vPos; float2 _expr132 = vVel; float _expr134 = params.deltaT; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index d2d46cfda..65f49a1a6 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -200,8 +200,8 @@ float4 sample1() : SV_Target0 float2 tc = float2(0.5.xx); float4 s2d = image_2d.Sample(sampler_reg, tc); float4 s2d_offset = image_2d.Sample(sampler_reg, tc, int2(3, 1)); - float4 s2d_level = image_2d.SampleLevel(sampler_reg, tc, 2.3); - float4 s2d_level_offset = image_2d.SampleLevel(sampler_reg, tc, 2.3, int2(3, 1)); + float4 s2d_level = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284); + float4 s2d_level_offset = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284, int2(3, 1)); return (((s2d + s2d_offset) + s2d_level) + s2d_level_offset); } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 98a0da293..de36774a2 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -9,7 +9,7 @@ float4 builtins() float4 s2_ = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0)); float4 s3_ = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); - float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.1); + float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); float b1_ = float(int4(1, 1, 1, 1).x); float4 b2_ = float4(int4(1, 1, 1, 1)); return (((((float4(int4(s1_.xxxx)) + s2_) + m1_) + m2_) + float4(b1_.xxxx)) + b2_); diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index 2aba7768e..c12c5184c 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -1,4 +1,4 @@ -static const float c_scale = 1.2; +static const float c_scale = 1.2000000476837158; struct VertexOutput { linear float2 uv : LOC0; diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 85cdbf88f..0f878d6a8 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -1,4 +1,4 @@ -static const float3 c_ambient = float3(0.05, 0.05, 0.05); +static const float3 c_ambient = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); static const uint c_max_lights = 10; struct Globals { @@ -36,7 +36,7 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { float3 raw_normal = fragmentinput_fs_main.raw_normal1; float4 position = fragmentinput_fs_main.position1; - float3 color = float3(0.05, 0.05, 0.05); + float3 color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i = 0u; float3 normal = normalize(raw_normal); diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index ef9d6d710..53edfad1f 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -130,7 +130,7 @@ kernel void main1( vVel = ((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120); metal::float2 _e123 = vVel; metal::float2 _e125 = vVel; - vVel = metal::normalize(_e123) * metal::clamp(metal::length(_e125), 0.0, 0.1); + vVel = metal::normalize(_e123) * metal::clamp(metal::length(_e125), 0.0, 0.10000000149011612); metal::float2 _e131 = vPos; metal::float2 _e132 = vVel; float _e134 = params.deltaT; diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 3a615ef12..2fbe17aa8 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -73,8 +73,8 @@ fragment sampleOutput sample( metal::float2 tc = metal::float2(0.5); metal::float4 s2d = image_2d.sample(sampler_reg, tc); metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type7_); - metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.3)); - metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type7_); + metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); + metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type7_); return sampleOutput { ((s2d + s2d_offset) + s2d_level) + s2d_level_offset }; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 105da6b90..fd03a429b 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -13,7 +13,7 @@ metal::float4 builtins( metal::float4 s2_ = true ? v_f32_one : v_f32_zero; metal::float4 s3_ = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false)); metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half); - metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.1); + metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.10000000149011612); float b1_ = as_type(v_i32_one.x); metal::float4 b2_ = as_type(v_i32_one); return ((((static_cast(metal::int4(s1_)) + s2_) + m1_) + m2_) + metal::float4(b1_)) + b2_; diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl index 9811ae517..bb7e971be 100644 --- a/tests/out/msl/quad.msl +++ b/tests/out/msl/quad.msl @@ -2,7 +2,7 @@ #include #include -constexpr constant float c_scale = 1.2; +constexpr constant float c_scale = 1.2000000476837158; struct VertexOutput { metal::float2 uv; metal::float4 position; diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 60a9a023d..c098c0142 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -19,7 +19,7 @@ typedef Light type3[1]; struct Lights { type3 data; }; -constant metal::float3 c_ambient = {0.05, 0.05, 0.05}; +constant metal::float3 c_ambient = {0.05000000074505806, 0.05000000074505806, 0.05000000074505806}; float fetch_shadow( metal::uint light_id, diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 283169b58..5c510d2bf 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -124,7 +124,7 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); let _e123: vec2 = vVel; let _e125: vec2 = vVel; - vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.1)); + vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.10000000149011612)); let _e131: vec2 = vPos; let _e132: vec2 = vVel; let _e134: f32 = params.deltaT; diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 46f4ee05e..8fc336f7d 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -74,8 +74,8 @@ fn sample() -> [[location(0)]] vec4 { let tc: vec2 = vec2(0.5); let s2d: vec4 = textureSample(image_2d, sampler_reg, tc); let s2d_offset: vec4 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); - let s2d_level: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3); - let s2d_level_offset: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3, vec2(3, 1)); + let s2d_level: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284); + let s2d_level_offset: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284, vec2(3, 1)); return (((s2d + s2d_offset) + s2d_level) + s2d_level_offset); } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 569804ed1..a4cf8bdd5 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -7,7 +7,7 @@ fn builtins() -> vec4 { let s2_: vec4 = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); let s3_: vec4 = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); let m1_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); + let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); let b1_: f32 = bitcast(vec4(1, 1, 1, 1).x); let b2_: vec4 = vec4(vec4(1, 1, 1, 1)); return (((((vec4(vec4(s1_)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 0b2a0c1d8..9fccc34b4 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -3,7 +3,7 @@ struct VertexOutput { [[builtin(position)]] position: vec4; }; -let c_scale: f32 = 1.2; +let c_scale: f32 = 1.2000000476837158; [[group(0), binding(0)]] var u_texture: texture_2d; diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index a0b5fbd9a..49c70fa9b 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -14,7 +14,7 @@ struct Lights { data: [[stride(96)]] array; }; -let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); +let c_ambient: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); let c_max_lights: u32 = 10u; [[group(0), binding(0)]] @@ -38,7 +38,7 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { [[stage(fragment)]] fn fs_main([[location(0)]] raw_normal: vec3, [[location(1)]] position: vec4) -> [[location(0)]] vec4 { - var color: vec3 = vec3(0.05, 0.05, 0.05); + var color: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i: u32 = 0u; let normal: vec3 = normalize(raw_normal); diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index a99cd96aa..0556cb824 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -49,29 +49,11 @@ fn invalid_integer() { fn invalid_float() { check( "let scale: f32 = 1.1.;", - r###"error: expected floating-point literal, found `1.1.` - ┌─ wgsl:1:18 + r###"error: expected ';', found '.' + ┌─ wgsl:1:21 │ 1 │ let scale: f32 = 1.1.; - │ ^^^^ expected floating-point literal - │ - = note: invalid float literal - -"###, - ); -} - -#[test] -fn invalid_scalar_width() { - check( - "let scale: f32 = 1.1f1000;", - r###"error: invalid width of `1000` for literal - ┌─ wgsl:1:18 - │ -1 │ let scale: f32 = 1.1f1000; - │ ^^^^^^^^ invalid width - │ - = note: valid widths are 8, 16, 32, 64 + │ ^ expected ';' "###, ); @@ -118,11 +100,11 @@ fn negative_index() { return a[-1]; } "#, - r#"error: expected non-negative integer constant expression, found `-1` + r#"error: expected unsigned integer constant expression, found `-1` ┌─ wgsl:4:26 │ 4 │ return a[-1]; - │ ^^ expected non-negative integer + │ ^^ expected unsigned integer "#, ); From a35de06f33f43b3a44ab911143c35dd630b00893 Mon Sep 17 00:00:00 2001 From: aentity Date: Mon, 23 Aug 2021 19:45:43 -0400 Subject: [PATCH 1288/2212] Update deps petgraph and rose-tree --- Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3e99aa6b5..352ad9845 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,8 +25,8 @@ num-traits = "0.2" spirv = { version = "0.2", optional = true } thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } -petgraph = { version ="0.5", optional = true } -rose_tree = { version ="0.2", optional = true } +petgraph = { version ="0.6", optional = true } +rose_tree = { version ="0.3", optional = true } pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } From f11afd4fcf16350cba29cfdac5f09ef9df7a57a7 Mon Sep 17 00:00:00 2001 From: fsh Date: Tue, 24 Aug 2021 21:46:54 +0200 Subject: [PATCH 1289/2212] [glsl-in] Avoid infinite loop when parsing invalid statements (#1280) --- src/front/glsl/parser/functions.rs | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index e1b41b1bc..b2db84080 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -493,25 +493,16 @@ impl<'source> ParsingContext<'source> { meta } - TokenValue::Plus - | TokenValue::Dash - | TokenValue::Bang - | TokenValue::Tilde - | TokenValue::LeftParen - | TokenValue::Increment - | TokenValue::Decrement - | TokenValue::Identifier(_) - | TokenValue::TypeName(_) - | TokenValue::IntConstant(_) - | TokenValue::BoolConstant(_) - | TokenValue::FloatConstant(_) => { + TokenValue::Semicolon => self.bump(parser)?.meta, + _ => { + // Attempt to force expression parsing for remainder of the + // tokens. Unknown or invalid tokens will be caught there and + // turned into an error. let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?; self.expect(parser, TokenValue::Semicolon)?.meta } - TokenValue::Semicolon => self.bump(parser)?.meta, - _ => meta, }; Ok(Some(meta.union(&meta_rest))) From db845347f23f3a00add894d38cf62d28f47669ed Mon Sep 17 00:00:00 2001 From: Hans Christian Schmitz Date: Wed, 25 Aug 2021 17:22:09 +0200 Subject: [PATCH 1290/2212] Fix fuzzing setup Set naga features in `fuzz/Cargo.toml` to those required for SPIR-V and WGSL input. Also bump libfuzzer-sys version. --- fuzz/Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index a2b18642e..a95afc0f4 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -9,11 +9,11 @@ edition = "2018" cargo-fuzz = true [dependencies] -libfuzzer-sys = "0.3" +libfuzzer-sys = "0.4" [dependencies.naga] path = ".." -features = ["spirv"] +features = ["spv-in", "wgsl-in"] # Prevent this from interfering with workspaces [workspace] From 715a53f891e488d5c1bfb962e10c1598263fbcc7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 25 Aug 2021 16:34:13 -0400 Subject: [PATCH 1291/2212] [msl-out] don't pack location fields --- src/back/msl/writer.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index cdbd554af..a1be83b74 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -343,8 +343,13 @@ fn should_pack_struct_member( module: &crate::Module, ) -> Option { let member = &members[index]; - let ty_inner = &module.types[member.ty].inner; + //Note: this is imperfect - the same structure can be used for host-shared + // things, where packed float would matter. + if member.binding.is_some() { + return None; + } + let ty_inner = &module.types[member.ty].inner; let last_offset = member.offset + ty_inner.span(&module.constants); let next_offset = match members.get(index + 1) { Some(next) => next.offset, From 1e9f2b9287855558fce07bf8a89c9149a4abdd55 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 24 Aug 2021 17:45:29 -0400 Subject: [PATCH 1292/2212] Add atomicSubtract support --- src/back/glsl/mod.rs | 20 ++++++++++++++------ src/back/hlsl/conv.rs | 2 +- src/back/hlsl/writer.rs | 14 +++++++++++--- src/back/msl/writer.rs | 7 +++++-- src/back/spv/block.rs | 9 +++++++++ src/back/wgsl/mod.rs | 1 + src/front/wgsl/mod.rs | 9 +++++++++ src/lib.rs | 1 + tests/in/access.wgsl | 1 + tests/out/glsl/access.atomics.Compute.glsl | 14 ++++++++------ tests/out/hlsl/access.hlsl | 14 ++++++++------ tests/out/msl/access.msl | 14 ++++++++------ tests/out/spv/access.spvasm | 21 ++++++++++++--------- tests/out/wgsl/access.wgsl | 14 ++++++++------ 14 files changed, 96 insertions(+), 45 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b3075c9e7..b3d268203 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -71,7 +71,7 @@ pub type BindingMap = std::collections::BTreeMap; impl crate::AtomicFunction { fn to_glsl(self) -> &'static str { match self { - Self::Add => "Add", + Self::Add | Self::Subtract => "Add", Self::And => "And", Self::InclusiveOr => "Or", Self::ExclusiveOr => "Xor", @@ -1706,12 +1706,20 @@ impl<'a, W: Write> Writer<'a, W> { let fun_str = fun.to_glsl(); write!(self.out, "atomic{}(", fun_str)?; self.write_expr(pointer, ctx)?; - if let crate::AtomicFunction::Exchange { compare: Some(_) } = *fun { - return Err(Error::Custom( - "atomic CompareExchange is not implemented".to_string(), - )); - } write!(self.out, ", ")?; + // handle the special cases + match *fun { + crate::AtomicFunction::Subtract => { + // we just wrote `InterlockedAdd`, so negate the argument + write!(self.out, "-")?; + } + crate::AtomicFunction::Exchange { compare: Some(_) } => { + return Err(Error::Custom( + "atomic CompareExchange is not implemented".to_string(), + )); + } + _ => {} + } self.write_expr(value, ctx)?; writeln!(self.out, ");")?; } diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index e535d4534..b8cb10daa 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -133,7 +133,7 @@ impl crate::AtomicFunction { /// Return the HLSL suffix for the `InterlockedXxx` method. pub(super) fn to_hlsl_suffix(self) -> &'static str { match self { - Self::Add => "Add", + Self::Add | Self::Subtract => "Add", Self::And => "And", Self::InclusiveOr => "Or", Self::ExclusiveOr => "Xor", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 96740fbec..136aee3ca 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1374,10 +1374,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { res_name, var_name, fun_str )?; self.write_storage_address(module, &chain, func_ctx)?; - if let crate::AtomicFunction::Exchange { compare: Some(_) } = *fun { - return Err(Error::Unimplemented("atomic CompareExchange".to_string())); - } write!(self.out, ", ")?; + // handle the special cases + match *fun { + crate::AtomicFunction::Subtract => { + // we just wrote `InterlockedAdd`, so negate the argument + write!(self.out, "-")?; + } + crate::AtomicFunction::Exchange { compare: Some(_) } => { + return Err(Error::Unimplemented("atomic CompareExchange".to_string())); + } + _ => {} + } self.write_expr(module, value, func_ctx)?; writeln!(self.out, ", {});", res_name)?; self.temp_access_chain = chain; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a1be83b74..aa6597055 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1647,6 +1647,9 @@ impl Writer { crate::AtomicFunction::Add => { self.put_atomic_fetch(pointer, "add", value, &context.expression)?; } + crate::AtomicFunction::Subtract => { + self.put_atomic_fetch(pointer, "sub", value, &context.expression)?; + } crate::AtomicFunction::And => { self.put_atomic_fetch(pointer, "and", value, &context.expression)?; } @@ -2643,8 +2646,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 17504 - if !(13000..=19000).contains(&stack_size) { + // last observed macOS value: 19152 (CI) + if !(13000..=20000).contains(&stack_size) { panic!("`put_block` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index f1e95f771..3009085ce 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1262,6 +1262,15 @@ impl<'w> BlockContext<'w> { semantics_id, value_id, ), + crate::AtomicFunction::Subtract => Instruction::atomic_binary( + spirv::Op::AtomicISub, + result_type_id, + id, + pointer_id, + scope_constant_id, + semantics_id, + value_id, + ), crate::AtomicFunction::And => Instruction::atomic_binary( spirv::Op::AtomicAnd, result_type_id, diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index 33d01e245..c99df6d81 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -31,6 +31,7 @@ impl crate::AtomicFunction { fn to_wgsl(self) -> &'static str { match self { Self::Add => "Add", + Self::Subtract => "Sub", Self::And => "And", Self::InclusiveOr => "Or", Self::ExclusiveOr => "Xor", diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index bf97c8e0c..ba3f54a98 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1403,6 +1403,15 @@ impl Parser { )?; return Ok(Some(handle)); } + "atomicSub" => { + let _ = lexer.next(); + let handle = self.parse_atomic_helper( + lexer, + crate::AtomicFunction::Subtract, + ctx.reborrow(), + )?; + return Ok(Some(handle)); + } "atomicAnd" => { let _ = lexer.next(); let handle = self.parse_atomic_helper( diff --git a/src/lib.rs b/src/lib.rs index 0b7f02ddd..f67260456 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -750,6 +750,7 @@ pub enum BinaryOperator { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum AtomicFunction { Add, + Subtract, And, ExclusiveOr, InclusiveOr, diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index ba54363ed..8ab506c27 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -43,6 +43,7 @@ fn atomics() { var tmp: i32; let value = atomicLoad(&bar.atom); tmp = atomicAdd(&bar.atom, 5); + tmp = atomicSub(&bar.atom, 5); tmp = atomicAnd(&bar.atom, 5); tmp = atomicOr(&bar.atom, 5); tmp = atomicXor(&bar.atom, 5); diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index f0a982862..2af1e7827 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -18,18 +18,20 @@ void main() { int value = _group_0_binding_0.atom; int _e6 = atomicAdd(_group_0_binding_0.atom, 5); tmp = _e6; - int _e9 = atomicAnd(_group_0_binding_0.atom, 5); + int _e9 = atomicAdd(_group_0_binding_0.atom, -5); tmp = _e9; - int _e12 = atomicOr(_group_0_binding_0.atom, 5); + int _e12 = atomicAnd(_group_0_binding_0.atom, 5); tmp = _e12; - int _e15 = atomicXor(_group_0_binding_0.atom, 5); + int _e15 = atomicOr(_group_0_binding_0.atom, 5); tmp = _e15; - int _e18 = atomicMin(_group_0_binding_0.atom, 5); + int _e18 = atomicXor(_group_0_binding_0.atom, 5); tmp = _e18; - int _e21 = atomicMax(_group_0_binding_0.atom, 5); + int _e21 = atomicMin(_group_0_binding_0.atom, 5); tmp = _e21; - int _e24 = atomicExchange(_group_0_binding_0.atom, 5); + int _e24 = atomicMax(_group_0_binding_0.atom, 5); tmp = _e24; + int _e27 = atomicExchange(_group_0_binding_0.atom, 5); + tmp = _e27; _group_0_binding_0.atom = value; return; } diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 9e306fcd8..d9c765e03 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -50,18 +50,20 @@ void atomics() int value = asint(bar.Load(64)); int _e6; bar.InterlockedAdd(64, 5, _e6); tmp = _e6; - int _e9; bar.InterlockedAnd(64, 5, _e9); + int _e9; bar.InterlockedAdd(64, -5, _e9); tmp = _e9; - int _e12; bar.InterlockedOr(64, 5, _e12); + int _e12; bar.InterlockedAnd(64, 5, _e12); tmp = _e12; - int _e15; bar.InterlockedXor(64, 5, _e15); + int _e15; bar.InterlockedOr(64, 5, _e15); tmp = _e15; - int _e18; bar.InterlockedMin(64, 5, _e18); + int _e18; bar.InterlockedXor(64, 5, _e18); tmp = _e18; - int _e21; bar.InterlockedMax(64, 5, _e21); + int _e21; bar.InterlockedMin(64, 5, _e21); tmp = _e21; - int _e24; bar.InterlockedExchange(64, 5, _e24); + int _e24; bar.InterlockedMax(64, 5, _e24); tmp = _e24; + int _e27; bar.InterlockedExchange(64, 5, _e27); + tmp = _e27; bar.Store(64, asuint(value)); return; } diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index fa0be834b..cb9f88101 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -58,18 +58,20 @@ kernel void atomics( int value = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); int _e6 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e6; - int _e9 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); + int _e9 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e9; - int _e12 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); + int _e12 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e12; - int _e15 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); + int _e15 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e15; - int _e18 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); + int _e18 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e18; - int _e21 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); + int _e21 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e21; - int _e24 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + int _e24 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e24; + int _e27 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e27; metal::atomic_store_explicit(&bar.atom, value, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index df869e495..40698045e 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 105 +; Bound: 107 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" @@ -139,24 +139,27 @@ OpBranch %85 %90 = OpAtomicIAdd %4 %91 %11 %89 %16 OpStore %82 %90 %93 = OpAccessChain %86 %27 %15 -%92 = OpAtomicAnd %4 %93 %11 %89 %16 +%92 = OpAtomicISub %4 %93 %11 %89 %16 OpStore %82 %92 %95 = OpAccessChain %86 %27 %15 -%94 = OpAtomicOr %4 %95 %11 %89 %16 +%94 = OpAtomicAnd %4 %95 %11 %89 %16 OpStore %82 %94 %97 = OpAccessChain %86 %27 %15 -%96 = OpAtomicXor %4 %97 %11 %89 %16 +%96 = OpAtomicOr %4 %97 %11 %89 %16 OpStore %82 %96 %99 = OpAccessChain %86 %27 %15 -%98 = OpAtomicSMin %4 %99 %11 %89 %16 +%98 = OpAtomicXor %4 %99 %11 %89 %16 OpStore %82 %98 %101 = OpAccessChain %86 %27 %15 -%100 = OpAtomicSMax %4 %101 %11 %89 %16 +%100 = OpAtomicSMin %4 %101 %11 %89 %16 OpStore %82 %100 %103 = OpAccessChain %86 %27 %15 -%102 = OpAtomicExchange %4 %103 %11 %89 %16 +%102 = OpAtomicSMax %4 %103 %11 %89 %16 OpStore %82 %102 -%104 = OpAccessChain %86 %27 %15 -OpAtomicStore %104 %11 %89 %88 +%105 = OpAccessChain %86 %27 %15 +%104 = OpAtomicExchange %4 %105 %11 %89 %16 +OpStore %82 %104 +%106 = OpAccessChain %86 %27 %15 +OpAtomicStore %106 %11 %89 %88 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index d9a00535a..5eca81ff0 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -37,18 +37,20 @@ fn atomics() { let value: i32 = atomicLoad(&bar.atom); let _e6: i32 = atomicAdd(&bar.atom, 5); tmp = _e6; - let _e9: i32 = atomicAnd(&bar.atom, 5); + let _e9: i32 = atomicSub(&bar.atom, 5); tmp = _e9; - let _e12: i32 = atomicOr(&bar.atom, 5); + let _e12: i32 = atomicAnd(&bar.atom, 5); tmp = _e12; - let _e15: i32 = atomicXor(&bar.atom, 5); + let _e15: i32 = atomicOr(&bar.atom, 5); tmp = _e15; - let _e18: i32 = atomicMin(&bar.atom, 5); + let _e18: i32 = atomicXor(&bar.atom, 5); tmp = _e18; - let _e21: i32 = atomicMax(&bar.atom, 5); + let _e21: i32 = atomicMin(&bar.atom, 5); tmp = _e21; - let _e24: i32 = atomicExchange(&bar.atom, 5); + let _e24: i32 = atomicMax(&bar.atom, 5); tmp = _e24; + let _e27: i32 = atomicExchange(&bar.atom, 5); + tmp = _e27; atomicStore(&bar.atom, value); return; } From bdf774aa8bd6914685a993ba0bcdc4efdc0ee1bb Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 24 Aug 2021 17:44:16 -0700 Subject: [PATCH 1293/2212] Rename `BoundsCheckPolicy::UndefinedBehavior` to `Unchecked`. When we are leaning on robust buffer access to do the job for us, there's no undefined behavior going on. So `UndefinedBehavior` suggests people are doing something reckless even if they're not. The policy just says what Naga is doing, and it shouldn't pretend to say what the rest of the system is doing. --- cli/src/main.rs | 6 +++--- src/back/mod.rs | 26 +++++++++++++++++++------- src/back/spv/image.rs | 4 ++-- src/back/spv/index.rs | 2 +- tests/snapshots.rs | 4 ++-- 5 files changed, 27 insertions(+), 15 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 372a8303b..f0ddbbd47 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -13,13 +13,13 @@ struct Args { /// what policy to use for index bounds checking for arrays, vectors, and /// matrices. /// - /// May be `Restrict`, `ReadZeroSkipWrite`, or `UndefinedBehavior` + /// May be `Restrict`, `ReadZeroSkipWrite`, or `Unchecked` #[argh(option)] index_bounds_check_policy: Option, /// what policy to use for texture bounds checking. /// - /// May be `Restrict`, `ReadZeroSkipWrite`, or `UndefinedBehavior` + /// May be `Restrict`, `ReadZeroSkipWrite`, or `Unchecked` #[argh(option)] image_bounds_check_policy: Option, @@ -62,7 +62,7 @@ impl FromStr for BoundsCheckPolicyArg { Ok(Self(match s.to_lowercase().as_str() { "restrict" => BoundsCheckPolicy::Restrict, "readzeroskipwrite" => BoundsCheckPolicy::ReadZeroSkipWrite, - "undefinedbehavior" => BoundsCheckPolicy::UndefinedBehavior, + "unchecked" => BoundsCheckPolicy::Unchecked, _ => { return Err(format!( "Invalid value for --index-bounds-check-policy: {}", diff --git a/src/back/mod.rs b/src/back/mod.rs index 7ac135f9d..1ad49e348 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -105,23 +105,35 @@ impl<'a> FunctionCtx<'_> { } } -/// How should code generated by Naga do indexing bounds checks? +/// How should code generated by Naga do bounds checks? /// /// When a vector, matrix, or array index is out of bounds—either negative, or /// greater than or equal to the number of elements in the type—WGSL requires /// that some other index of the implementation's choice that is in bounds is /// used instead. (There are no types with zero elements.) /// +/// Similarly, when out-of-bounds coordinates, array indices, or sample indices +/// are presented to the WGSL `textureLoad` and `textureStore` operations, the +/// operation is redirected to do something safe. +/// /// Different users of Naga will prefer different defaults: /// /// - When used as part of a WebGPU implementation, the WGSL specification -/// requires the `Restrict` behavior. +/// requires the `Restrict` behavior for array, vector, and matrix accesses, +/// and either the `Restrict` or `ReadZeroSkipWrite` behaviors for texture +/// accesses. /// /// - When used by the `wgpu` crate for native development, `wgpu` selects /// `ReadZeroSkipWrite` as its default. /// -/// - Naga's own default is `UndefinedBehavior`, so that shader translations +/// - Naga's own default is `Unchanged`, so that shader translations /// are as faithful to the original as possible. +/// +/// Sometimes the underlying hardware and drivers can perform bounds checks +/// themselves, in a way that performs better than the checks Naga would inject. +/// If you're using native checks like this, then having Naga inject its own +/// checks as well would be redundant, and the `Unchecked` policy is +/// appropriate. #[derive(Clone, Copy, Debug)] pub enum BoundsCheckPolicy { /// Replace out-of-bounds indexes with some arbitrary in-bounds index. @@ -135,16 +147,16 @@ pub enum BoundsCheckPolicy { /// Out-of-bounds reads return zero, and writes have no effect. ReadZeroSkipWrite, - /// Out-of-bounds indexes are undefined behavior. Generate the fastest code + /// Naga adds no checks to indexing operations. Generate the fastest code /// possible. This is the default for Naga, as a translator, but consumers /// should consider defaulting to a safer behavior. - UndefinedBehavior, + Unchecked, } -/// The default `BoundsCheckPolicy` is `UndefinedBehavior`. +/// The default `BoundsCheckPolicy` is `Unchecked`. impl Default for BoundsCheckPolicy { fn default() -> Self { - BoundsCheckPolicy::UndefinedBehavior + BoundsCheckPolicy::Unchecked } } diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index cf9cf802a..0a93e735a 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -758,7 +758,7 @@ impl<'w> BlockContext<'w> { block, &access, )?, - crate::back::BoundsCheckPolicy::UndefinedBehavior => access.generate( + crate::back::BoundsCheckPolicy::Unchecked => access.generate( &mut self.writer.id_gen, coordinates.value_id, level_id, @@ -1146,7 +1146,7 @@ impl<'w> BlockContext<'w> { &write, )?; } - crate::back::BoundsCheckPolicy::UndefinedBehavior => { + crate::back::BoundsCheckPolicy::Unchecked => { write.generate( &mut self.writer.id_gen, coordinates.value_id, diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 5176dd0d5..a6cf6bfb8 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -347,7 +347,7 @@ impl<'w> BlockContext<'w> { BoundsCheckPolicy::ReadZeroSkipWrite => { self.write_index_comparison(base, index, block)? } - BoundsCheckPolicy::UndefinedBehavior => BoundsCheckResult::Computed(self.cached[index]), + BoundsCheckPolicy::Unchecked => BoundsCheckResult::Computed(self.cached[index]), }) } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index f92ddebdc..320e311e9 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -174,14 +174,14 @@ fn write_output_spv( } else if params.bounds_check_read_zero_skip_write { naga::back::BoundsCheckPolicy::ReadZeroSkipWrite } else { - naga::back::BoundsCheckPolicy::UndefinedBehavior + naga::back::BoundsCheckPolicy::Unchecked }, image_bounds_check_policy: if params.image_bounds_check_restrict { naga::back::BoundsCheckPolicy::Restrict } else if params.image_bounds_check_read_zero_skip_write { naga::back::BoundsCheckPolicy::ReadZeroSkipWrite } else { - naga::back::BoundsCheckPolicy::UndefinedBehavior + naga::back::BoundsCheckPolicy::Unchecked }, ..spv::Options::default() }; From 140e3223e2564a8d313c6f237068591283c5da97 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 25 Aug 2021 10:40:47 -0700 Subject: [PATCH 1294/2212] snapshot tests: Parse bounds checks policy properly. --- .../in/bounds-check-image-restrict.param.ron | 2 +- tests/in/bounds-check-image-rzsw.param.ron | 2 +- tests/in/bounds-check-zero.param.ron | 2 +- tests/snapshots.rs | 60 ++++++++++--------- 4 files changed, 36 insertions(+), 30 deletions(-) diff --git a/tests/in/bounds-check-image-restrict.param.ron b/tests/in/bounds-check-image-restrict.param.ron index 30ade34f5..725c767df 100644 --- a/tests/in/bounds-check-image-restrict.param.ron +++ b/tests/in/bounds-check-image-restrict.param.ron @@ -1,5 +1,5 @@ ( - image_bounds_check_restrict: true, + image_bounds_check_policy: Restrict, spv_version: (1, 1), spv_debug: true, ) diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/tests/in/bounds-check-image-rzsw.param.ron index 3922919f5..22e3d47b5 100644 --- a/tests/in/bounds-check-image-rzsw.param.ron +++ b/tests/in/bounds-check-image-rzsw.param.ron @@ -1,5 +1,5 @@ ( - image_bounds_check_read_zero_skip_write: true, + image_bounds_check_policy: ReadZeroSkipWrite, spv_version: (1, 1), spv_debug: true, ) diff --git a/tests/in/bounds-check-zero.param.ron b/tests/in/bounds-check-zero.param.ron index e6fc09bf4..1e772dd17 100644 --- a/tests/in/bounds-check-zero.param.ron +++ b/tests/in/bounds-check-zero.param.ron @@ -1,4 +1,4 @@ ( - bounds_check_read_zero_skip_write: true, + index_bounds_check_policy: ReadZeroSkipWrite, spv_version: (1, 1), ) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 320e311e9..5c44c7a4a 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -19,22 +19,41 @@ bitflags::bitflags! { } } +/// Twin of `naga::back::BoundsCheckPolicy`, always serializable. +#[derive(Clone, Copy, serde::Deserialize)] +enum BoundsCheckPolicyArg { + Restrict, + ReadZeroSkipWrite, + Unchecked, +} + +impl Default for BoundsCheckPolicyArg { + fn default() -> Self { + BoundsCheckPolicyArg::Unchecked + } +} + +impl From for naga::back::BoundsCheckPolicy { + fn from(arg: BoundsCheckPolicyArg) -> Self { + match arg { + BoundsCheckPolicyArg::Restrict => Self::Restrict, + BoundsCheckPolicyArg::ReadZeroSkipWrite => Self::ReadZeroSkipWrite, + BoundsCheckPolicyArg::Unchecked => Self::Unchecked, + } + } +} + #[derive(Default, serde::Deserialize)] struct Parameters { #[serde(default)] god_mode: bool, - // We can only deserialize `BoundsCheckPolicy` values if `deserialize` - // feature was enabled, but features should not affect snapshot contents, so - // just take the policy as booleans instead. + #[allow(dead_code)] #[serde(default)] - bounds_check_read_zero_skip_write: bool, + index_bounds_check_policy: BoundsCheckPolicyArg, + #[allow(dead_code)] #[serde(default)] - bounds_check_restrict: bool, - #[serde(default)] - image_bounds_check_restrict: bool, - #[serde(default)] - image_bounds_check_read_zero_skip_write: bool, + image_bounds_check_policy: BoundsCheckPolicyArg, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] spv_version: (u8, u8), @@ -71,12 +90,9 @@ struct Parameters { fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let root = env!("CARGO_MANIFEST_DIR"); let params = match fs::read_to_string(format!("{}/{}/{}.param.ron", root, BASE_DIR_IN, name)) { - Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"), + Ok(string) => ron::de::from_str(&string).expect("Couldn't parse param file"), Err(_) => Parameters::default(), }; - if params.bounds_check_restrict && params.bounds_check_read_zero_skip_write { - panic!("select only one bounds check policy"); - } let capabilities = if params.god_mode { naga::valid::Capabilities::all() } else { @@ -169,20 +185,10 @@ fn write_output_spv( } else { Some(params.spv_capabilities.clone()) }, - index_bounds_check_policy: if params.bounds_check_restrict { - naga::back::BoundsCheckPolicy::Restrict - } else if params.bounds_check_read_zero_skip_write { - naga::back::BoundsCheckPolicy::ReadZeroSkipWrite - } else { - naga::back::BoundsCheckPolicy::Unchecked - }, - image_bounds_check_policy: if params.image_bounds_check_restrict { - naga::back::BoundsCheckPolicy::Restrict - } else if params.image_bounds_check_read_zero_skip_write { - naga::back::BoundsCheckPolicy::ReadZeroSkipWrite - } else { - naga::back::BoundsCheckPolicy::Unchecked - }, + + index_bounds_check_policy: params.index_bounds_check_policy.into(), + image_bounds_check_policy: params.image_bounds_check_policy.into(), + ..spv::Options::default() }; From 1b95e023e79357a85258e68f88fa20ed1a79fb30 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 24 Aug 2021 18:26:22 -0700 Subject: [PATCH 1295/2212] [spv-out] Support a separate bounds check policy for buffers. --- cli/src/main.rs | 13 +++ src/back/spv/index.rs | 25 ++++- src/back/spv/mod.rs | 38 ++++++++ src/back/spv/writer.rs | 2 + tests/in/bounds-check-zero.param.ron | 1 + tests/in/policy-mix.param.ron | 7 ++ tests/in/policy-mix.wgsl | 35 +++++++ tests/out/spv/policy-mix.spvasm | 137 +++++++++++++++++++++++++++ tests/snapshots.rs | 5 + 9 files changed, 261 insertions(+), 2 deletions(-) create mode 100644 tests/in/policy-mix.param.ron create mode 100644 tests/in/policy-mix.wgsl create mode 100644 tests/out/spv/policy-mix.spvasm diff --git a/cli/src/main.rs b/cli/src/main.rs index f0ddbbd47..05d459ce0 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -17,6 +17,14 @@ struct Args { #[argh(option)] index_bounds_check_policy: Option, + /// what policy to use for index bounds checking for arrays, vectors, and + /// matrices, when they are stored in globals in the `storage` or `uniform` + /// storage classes. + /// + /// May be `Restrict`, `ReadZeroSkipWrite`, or `Unchecked` + #[argh(option)] + buffer_bounds_check_policy: Option, + /// what policy to use for texture bounds checking. /// /// May be `Restrict`, `ReadZeroSkipWrite`, or `Unchecked` @@ -114,6 +122,7 @@ impl FromStr for GlslProfileArg { struct Parameters { validation_flags: naga::valid::ValidationFlags, index_bounds_check_policy: naga::back::BoundsCheckPolicy, + buffer_bounds_check_policy: naga::back::BoundsCheckPolicy, image_bounds_check_policy: naga::back::BoundsCheckPolicy, entry_point: Option, spv_adjust_coordinate_space: bool, @@ -194,6 +203,9 @@ fn run() -> Result<(), Box> { if let Some(policy) = args.index_bounds_check_policy { params.index_bounds_check_policy = policy.0; } + if let Some(policy) = args.buffer_bounds_check_policy { + params.buffer_bounds_check_policy = policy.0; + } if let Some(policy) = args.image_bounds_check_policy { params.image_bounds_check_policy = policy.0; } @@ -318,6 +330,7 @@ fn run() -> Result<(), Box> { use naga::back::spv; params.spv.index_bounds_check_policy = params.index_bounds_check_policy; + params.spv.buffer_bounds_check_policy = params.buffer_bounds_check_policy; params.spv.image_bounds_check_policy = params.image_bounds_check_policy; let spv = spv::write_vec( diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index a6cf6bfb8..53b1d48cb 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -332,7 +332,11 @@ impl<'w> BlockContext<'w> { selection.finish(self, loaded_value) } - /// Emit code for bounds checks, per self.index_bounds_check_policy. + /// Emit code for bounds checks for an array, vector, or matrix access. + /// + /// This implements either `index_bounds_check_policy` or + /// `buffer_bounds_check_policy`, depending on the storage class of the + /// pointer being accessed. /// /// Return a `BoundsCheckResult` indicating how the index should be /// consumed. See that type's documentation for details. @@ -342,7 +346,24 @@ impl<'w> BlockContext<'w> { index: Handle, block: &mut Block, ) -> Result { - Ok(match self.writer.index_bounds_check_policy { + // Should this access be covered by `index_bounds_check_policy` or + // `buffer_bounds_check_policy`? + let is_buffer = match *self.fun_info[base].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Pointer { class, .. } + | crate::TypeInner::ValuePointer { class, .. } => match class { + crate::StorageClass::Storage { access: _ } | crate::StorageClass::Uniform => true, + _ => false, + }, + _ => false, + }; + + let policy = if is_buffer { + self.writer.buffer_bounds_check_policy + } else { + self.writer.index_bounds_check_policy + }; + + Ok(match policy { BoundsCheckPolicy::Restrict => self.write_restricted_index(base, index, block)?, BoundsCheckPolicy::ReadZeroSkipWrite => { self.write_index_comparison(base, index, block)? diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 9da70e0ce..d57e53975 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -419,6 +419,7 @@ pub struct Writer { flags: WriterFlags, index_bounds_check_policy: BoundsCheckPolicy, image_bounds_check_policy: BoundsCheckPolicy, + buffer_bounds_check_policy: BoundsCheckPolicy, void_type: Word, //TODO: convert most of these into vectors, addressable by handle indices lookup_type: crate::FastHashMap, @@ -463,6 +464,42 @@ pub struct Options { /// How should the generated code handle array, vector, or matrix indices /// that are out of range? pub index_bounds_check_policy: BoundsCheckPolicy, + + /// How should the generated code handle array, vector, or matrix indices + /// that are out of range, when those values live in a [`GlobalVariable`] in + /// the [`Storage`] or [`Uniform`] storage classes? + /// + /// Some graphics hardware provides "robust buffer access", a feature that + /// ensures that using a pointer cannot access memory outside the 'buffer' + /// that it was derived from. In Naga terms, this means that the hardware + /// ensures that pointers computed by applying [`Access`] and + /// [`AccessIndex`] expressions to a [`GlobalVariable`] whose [`class`] is + /// [`Storage`] or [`Uniform`] will never read or write memory outside that + /// global variable. + /// + /// When hardware offers such a feature, it is probably undesirable to have + /// Naga inject bounds checking code for such accesses, since the hardware + /// can probably provide the same protection more efficiently. However, + /// bounds checks are still needed on accesses to indexable values that do + /// not live in buffers, like local variables. + /// + /// So, this option provides a separate policy that applies only to accesses + /// to storage and uniform globals. When depending on hardware bounds + /// checking, this policy can be `Unchecked` to avoid unnecessary overhead. + /// + /// When special hardware support is not available, this should probably be + /// the same as `index_bounds_check_policy`. + /// + /// [`GlobalVariable`]: crate::GlobalVariable + /// [`class`]: crate::GlobalVariable::class + /// [`Restrict`]: crate::back::BoundsCheckPolicy::Restrict + /// [`ReadZeroSkipWrite`]: crate::back::BoundsCheckPolicy::ReadZeroSkipWrite + /// [`Access`]: crate::Expression::Access + /// [`AccessIndex`]: crate::Expression::AccessIndex + /// [`Storage`]: crate::StorageClass::Storage + /// [`Uniform`]: crate::StorageClass::Uniform + pub buffer_bounds_check_policy: BoundsCheckPolicy, + /// How should the generated code handle image references that are out of /// range? pub image_bounds_check_policy: BoundsCheckPolicy, @@ -480,6 +517,7 @@ impl Default for Options { capabilities: None, index_bounds_check_policy: super::BoundsCheckPolicy::default(), image_bounds_check_policy: super::BoundsCheckPolicy::default(), + buffer_bounds_check_policy: super::BoundsCheckPolicy::default(), } } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index dac71b19f..f845a7ff6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -68,6 +68,7 @@ impl Writer { flags: options.flags, index_bounds_check_policy: options.index_bounds_check_policy, image_bounds_check_policy: options.image_bounds_check_policy, + buffer_bounds_check_policy: options.buffer_bounds_check_policy, void_type, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), @@ -105,6 +106,7 @@ impl Writer { flags: self.flags, index_bounds_check_policy: self.index_bounds_check_policy, image_bounds_check_policy: self.image_bounds_check_policy, + buffer_bounds_check_policy: self.buffer_bounds_check_policy, capabilities_available: take(&mut self.capabilities_available), // Initialized afresh: diff --git a/tests/in/bounds-check-zero.param.ron b/tests/in/bounds-check-zero.param.ron index 1e772dd17..10f3305b4 100644 --- a/tests/in/bounds-check-zero.param.ron +++ b/tests/in/bounds-check-zero.param.ron @@ -1,4 +1,5 @@ ( index_bounds_check_policy: ReadZeroSkipWrite, + buffer_bounds_check_policy: ReadZeroSkipWrite, spv_version: (1, 1), ) diff --git a/tests/in/policy-mix.param.ron b/tests/in/policy-mix.param.ron new file mode 100644 index 000000000..e3f7a182c --- /dev/null +++ b/tests/in/policy-mix.param.ron @@ -0,0 +1,7 @@ +( + index_bounds_check_policy: Restrict, + buffer_bounds_check_policy: Unchecked, + image_bounds_check_policy: ReadZeroSkipWrite, + spv_version: (1, 1), + spv_debug: true, +) diff --git a/tests/in/policy-mix.wgsl b/tests/in/policy-mix.wgsl new file mode 100644 index 000000000..e9b55709c --- /dev/null +++ b/tests/in/policy-mix.wgsl @@ -0,0 +1,35 @@ +// Tests that the index, buffer, and texture bounds checks policies are +// implemented separately. + +// Storage and Uniform storage classes +[[block]] +struct InStorage { + a: array, 10>; +}; +[[group(0), binding(0)]] var in_storage: InStorage; + +[[block]] +struct InUniform { + a: array, 20>; +}; +[[group(0), binding(1)]] var in_uniform: InUniform; + +// Textures automatically land in the `handle` storage class. +[[group(0), binding(2)]] var image_2d_array: texture_2d_array; + +// None of the above. +var in_workgroup: array; +var in_private: array; + +fn mock_function(c: vec2, i: i32, l: i32) -> vec4 { + var in_function: array, 2> = + array, 2>(vec4(0.707, 0.0, 0.0, 1.0), + vec4(0.0, 0.707, 0.0, 1.0)); + + return (in_storage.a[i] + + in_uniform.a[i] + + textureLoad(image_2d_array, c, i, l) + + in_workgroup[i] + + in_private[i] + + in_function[i]); +} diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm new file mode 100644 index 000000000..466cc8585 --- /dev/null +++ b/tests/out/spv/policy-mix.spvasm @@ -0,0 +1,137 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 93 +OpCapability Shader +OpCapability ImageQuery +OpCapability Linkage +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpSource GLSL 450 +OpName %15 "InStorage" +OpMemberName %15 0 "a" +OpName %17 "InUniform" +OpMemberName %17 0 "a" +OpName %23 "in_storage" +OpName %25 "in_uniform" +OpName %27 "image_2d_array" +OpName %29 "in_workgroup" +OpName %31 "in_private" +OpName %33 "in_function" +OpName %39 "mock_function" +OpDecorate %14 ArrayStride 16 +OpDecorate %15 Block +OpMemberDecorate %15 0 Offset 0 +OpDecorate %16 ArrayStride 16 +OpDecorate %17 Block +OpMemberDecorate %17 0 Offset 0 +OpDecorate %19 ArrayStride 4 +OpDecorate %20 ArrayStride 4 +OpDecorate %22 ArrayStride 16 +OpDecorate %23 NonWritable +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 0 +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 1 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 2 +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 10 +%5 = OpConstant %4 20 +%6 = OpConstant %4 30 +%7 = OpConstant %4 40 +%8 = OpConstant %4 2 +%10 = OpTypeFloat 32 +%9 = OpConstant %10 0.707 +%11 = OpConstant %10 0.0 +%12 = OpConstant %10 1.0 +%13 = OpTypeVector %10 4 +%14 = OpTypeArray %13 %3 +%15 = OpTypeStruct %14 +%16 = OpTypeArray %13 %5 +%17 = OpTypeStruct %16 +%18 = OpTypeImage %10 2D 0 1 0 1 Unknown +%19 = OpTypeArray %10 %6 +%20 = OpTypeArray %10 %7 +%21 = OpTypeVector %4 2 +%22 = OpTypeArray %13 %8 +%24 = OpTypePointer StorageBuffer %15 +%23 = OpVariable %24 StorageBuffer +%26 = OpTypePointer Uniform %17 +%25 = OpVariable %26 Uniform +%28 = OpTypePointer UniformConstant %18 +%27 = OpVariable %28 UniformConstant +%30 = OpTypePointer Workgroup %19 +%29 = OpVariable %30 Workgroup +%32 = OpTypePointer Private %20 +%31 = OpVariable %32 Private +%34 = OpTypePointer Function %22 +%40 = OpTypeFunction %13 %21 %4 %4 +%46 = OpTypePointer StorageBuffer %14 +%47 = OpTypePointer StorageBuffer %13 +%49 = OpTypeInt 32 0 +%48 = OpConstant %49 0 +%52 = OpTypePointer Uniform %16 +%53 = OpTypePointer Uniform %13 +%57 = OpTypeVector %4 3 +%59 = OpTypeBool +%60 = OpConstantNull %13 +%66 = OpTypeVector %59 3 +%73 = OpTypePointer Workgroup %10 +%74 = OpConstant %49 29 +%80 = OpTypePointer Private %10 +%81 = OpConstant %49 39 +%87 = OpTypePointer Function %13 +%88 = OpConstant %49 1 +%39 = OpFunction %13 None %40 +%36 = OpFunctionParameter %21 +%37 = OpFunctionParameter %4 +%38 = OpFunctionParameter %4 +%35 = OpLabel +%33 = OpVariable %34 Function +%41 = OpLoad %18 %27 +OpBranch %42 +%42 = OpLabel +%43 = OpCompositeConstruct %13 %9 %11 %11 %12 +%44 = OpCompositeConstruct %13 %11 %9 %11 %12 +%45 = OpCompositeConstruct %22 %43 %44 +OpStore %33 %45 +%50 = OpAccessChain %47 %23 %48 %37 +%51 = OpLoad %13 %50 +%54 = OpAccessChain %53 %25 %48 %37 +%55 = OpLoad %13 %54 +%56 = OpFAdd %13 %51 %55 +%58 = OpCompositeConstruct %57 %36 %37 +%61 = OpImageQueryLevels %4 %41 +%62 = OpULessThan %59 %38 %61 +OpSelectionMerge %63 None +OpBranchConditional %62 %64 %63 +%64 = OpLabel +%65 = OpImageQuerySizeLod %57 %41 %38 +%67 = OpULessThan %66 %58 %65 +%68 = OpAll %59 %67 +OpBranchConditional %68 %69 %63 +%69 = OpLabel +%70 = OpImageFetch %13 %41 %58 Lod %38 +OpBranch %63 +%63 = OpLabel +%71 = OpPhi %13 %60 %42 %60 %64 %70 %69 +%72 = OpFAdd %13 %56 %71 +%75 = OpExtInst %49 %1 UMin %37 %74 +%76 = OpAccessChain %73 %29 %75 +%77 = OpLoad %10 %76 +%78 = OpCompositeConstruct %13 %77 %77 %77 %77 +%79 = OpFAdd %13 %72 %78 +%82 = OpExtInst %49 %1 UMin %37 %81 +%83 = OpAccessChain %80 %31 %82 +%84 = OpLoad %10 %83 +%85 = OpCompositeConstruct %13 %84 %84 %84 %84 +%86 = OpFAdd %13 %79 %85 +%89 = OpExtInst %49 %1 UMin %37 %88 +%90 = OpAccessChain %87 %33 %89 +%91 = OpLoad %13 %90 +%92 = OpFAdd %13 %86 %91 +OpReturnValue %92 +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 5c44c7a4a..6902520d9 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -53,6 +53,9 @@ struct Parameters { index_bounds_check_policy: BoundsCheckPolicyArg, #[allow(dead_code)] #[serde(default)] + buffer_bounds_check_policy: BoundsCheckPolicyArg, + #[allow(dead_code)] + #[serde(default)] image_bounds_check_policy: BoundsCheckPolicyArg, #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] @@ -187,6 +190,7 @@ fn write_output_spv( }, index_bounds_check_policy: params.index_bounds_check_policy.into(), + buffer_bounds_check_policy: params.buffer_bounds_check_policy.into(), image_bounds_check_policy: params.image_bounds_check_policy.into(), ..spv::Options::default() @@ -462,6 +466,7 @@ fn convert_wgsl() { ("bounds-check-zero", Targets::SPIRV), ("bounds-check-image-restrict", Targets::SPIRV), ("bounds-check-image-rzsw", Targets::SPIRV), + ("policy-mix", Targets::SPIRV), ( "texture-arg", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From 496525b7d376d5a1b3c97a4731d43eb294a5ccb8 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 26 Aug 2021 13:25:05 -0700 Subject: [PATCH 1296/2212] Improve help messages, defaults for CLI bounds checking options. --- cli/src/main.rs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 05d459ce0..358e02f25 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -13,7 +13,11 @@ struct Args { /// what policy to use for index bounds checking for arrays, vectors, and /// matrices. /// - /// May be `Restrict`, `ReadZeroSkipWrite`, or `Unchecked` + /// May be `Restrict` (force all indices in-bounds), `ReadZeroSkipWrite` + /// (out-of-bounds indices read zeros, and don't write at all), or + /// `Unchecked` (generate the simplest code, and whatever happens, happens) + /// + /// `Unchecked` is the default. #[argh(option)] index_bounds_check_policy: Option, @@ -21,13 +25,15 @@ struct Args { /// matrices, when they are stored in globals in the `storage` or `uniform` /// storage classes. /// - /// May be `Restrict`, `ReadZeroSkipWrite`, or `Unchecked` + /// Possible values are the same as for `index-bounds-check-policy`. If + /// omitted, defaults to the index bounds check policy. #[argh(option)] buffer_bounds_check_policy: Option, /// what policy to use for texture bounds checking. /// - /// May be `Restrict`, `ReadZeroSkipWrite`, or `Unchecked` + /// Possible values are the same as for `index-bounds-check-policy`. If + /// omitted, defaults to the index bounds check policy. #[argh(option)] image_bounds_check_policy: Option, @@ -59,7 +65,7 @@ struct Args { } /// Newtype so we can implement [`FromStr`] for `BoundsCheckPolicy`. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Copy)] struct BoundsCheckPolicyArg(naga::back::BoundsCheckPolicy); impl FromStr for BoundsCheckPolicyArg { @@ -203,12 +209,14 @@ fn run() -> Result<(), Box> { if let Some(policy) = args.index_bounds_check_policy { params.index_bounds_check_policy = policy.0; } - if let Some(policy) = args.buffer_bounds_check_policy { - params.buffer_bounds_check_policy = policy.0; - } - if let Some(policy) = args.image_bounds_check_policy { - params.image_bounds_check_policy = policy.0; - } + params.buffer_bounds_check_policy = match args.buffer_bounds_check_policy { + Some(arg) => arg.0, + None => params.index_bounds_check_policy, + }; + params.image_bounds_check_policy = match args.image_bounds_check_policy { + Some(arg) => arg.0, + None => params.index_bounds_check_policy, + }; params.spv_flow_dump_prefix = args.flow_dir; params.entry_point = args.entry_point; if let Some(version) = args.profile { From 28547e3d3b61a7872cdba66638f0bae17154f031 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 26 Aug 2021 13:45:55 -0700 Subject: [PATCH 1297/2212] Gather index, buffer, and texture bounds check policies into a single struct. --- cli/src/main.rs | 18 ++++++-------- src/back/mod.rs | 56 ++++++++++++++++++++++++++++++++++++++++++ src/back/spv/image.rs | 4 +-- src/back/spv/index.rs | 4 +-- src/back/spv/mod.rs | 55 +++++------------------------------------ src/back/spv/writer.rs | 8 ++---- tests/snapshots.rs | 8 +++--- 7 files changed, 80 insertions(+), 73 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 358e02f25..0f64f0a1b 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -127,9 +127,7 @@ impl FromStr for GlslProfileArg { #[derive(Default)] struct Parameters { validation_flags: naga::valid::ValidationFlags, - index_bounds_check_policy: naga::back::BoundsCheckPolicy, - buffer_bounds_check_policy: naga::back::BoundsCheckPolicy, - image_bounds_check_policy: naga::back::BoundsCheckPolicy, + bounds_check_policies: naga::back::BoundsCheckPolicies, entry_point: Option, spv_adjust_coordinate_space: bool, spv_flow_dump_prefix: Option, @@ -207,15 +205,15 @@ fn run() -> Result<(), Box> { params.validation_flags = naga::valid::ValidationFlags::all(); } if let Some(policy) = args.index_bounds_check_policy { - params.index_bounds_check_policy = policy.0; + params.bounds_check_policies.index = policy.0; } - params.buffer_bounds_check_policy = match args.buffer_bounds_check_policy { + params.bounds_check_policies.buffer = match args.buffer_bounds_check_policy { Some(arg) => arg.0, - None => params.index_bounds_check_policy, + None => params.bounds_check_policies.index, }; - params.image_bounds_check_policy = match args.image_bounds_check_policy { + params.bounds_check_policies.image = match args.image_bounds_check_policy { Some(arg) => arg.0, - None => params.index_bounds_check_policy, + None => params.bounds_check_policies.index, }; params.spv_flow_dump_prefix = args.flow_dir; params.entry_point = args.entry_point; @@ -337,9 +335,7 @@ fn run() -> Result<(), Box> { "spv" => { use naga::back::spv; - params.spv.index_bounds_check_policy = params.index_bounds_check_policy; - params.spv.buffer_bounds_check_policy = params.buffer_bounds_check_policy; - params.spv.image_bounds_check_policy = params.image_bounds_check_policy; + params.spv.bounds_check_policies = params.bounds_check_policies; let spv = spv::write_vec( &module, diff --git a/src/back/mod.rs b/src/back/mod.rs index 1ad49e348..34cd45a87 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -153,6 +153,62 @@ pub enum BoundsCheckPolicy { Unchecked, } +#[derive(Clone, Copy, Debug, Default)] +/// Policies for injecting bounds checks during code generation. +/// +/// For SPIR-V generation, see [`spv::Options::bounds_check_policies`]. +pub struct BoundsCheckPolicies { + /// How should the generated code handle array, vector, or matrix indices + /// that are out of range? + pub index: BoundsCheckPolicy, + + /// How should the generated code handle array, vector, or matrix indices + /// that are out of range, when those values live in a [`GlobalVariable`] in + /// the [`Storage`] or [`Uniform`] storage classes? + /// + /// Some graphics hardware provides "robust buffer access", a feature that + /// ensures that using a pointer cannot access memory outside the 'buffer' + /// that it was derived from. In Naga terms, this means that the hardware + /// ensures that pointers computed by applying [`Access`] and + /// [`AccessIndex`] expressions to a [`GlobalVariable`] whose [`class`] is + /// [`Storage`] or [`Uniform`] will never read or write memory outside that + /// global variable. + /// + /// When hardware offers such a feature, it is probably undesirable to have + /// Naga inject bounds checking code for such accesses, since the hardware + /// can probably provide the same protection more efficiently. However, + /// bounds checks are still needed on accesses to indexable values that do + /// not live in buffers, like local variables. + /// + /// So, this option provides a separate policy that applies only to accesses + /// to storage and uniform globals. When depending on hardware bounds + /// checking, this policy can be `Unchecked` to avoid unnecessary overhead. + /// + /// When special hardware support is not available, this should probably be + /// the same as `index_bounds_check_policy`. + /// + /// [`GlobalVariable`]: crate::GlobalVariable + /// [`class`]: crate::GlobalVariable::class + /// [`Restrict`]: crate::back::BoundsCheckPolicy::Restrict + /// [`ReadZeroSkipWrite`]: crate::back::BoundsCheckPolicy::ReadZeroSkipWrite + /// [`Access`]: crate::Expression::Access + /// [`AccessIndex`]: crate::Expression::AccessIndex + /// [`Storage`]: crate::StorageClass::Storage + /// [`Uniform`]: crate::StorageClass::Uniform + pub buffer: BoundsCheckPolicy, + + /// How should the generated code handle image texel references that are out + /// of range? + /// + /// This controls the behavior of [`ImageLoad`] expressions and + /// [`ImageStore`] statements when a coordinate, texture array index, level + /// of detail, or multisampled sample number is out of range. + /// + /// [`ImageLoad`]: crate::Expression::ImageLoad + /// [`ImageStore`]: crate::Statement::ImageStore + pub image: BoundsCheckPolicy, +} + /// The default `BoundsCheckPolicy` is `Unchecked`. impl Default for BoundsCheckPolicy { fn default() -> Self { diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 0a93e735a..5966ee0ef 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -738,7 +738,7 @@ impl<'w> BlockContext<'w> { }; // Perform the access, according to the bounds check policy. - let access_id = match self.writer.image_bounds_check_policy { + let access_id = match self.writer.bounds_check_policies.image { crate::back::BoundsCheckPolicy::Restrict => { let (coords, level_id, sample_id) = self.write_restricted_coordinates( image_id, @@ -1130,7 +1130,7 @@ impl<'w> BlockContext<'w> { let write = Store { image_id, value_id }; - match self.writer.image_bounds_check_policy { + match self.writer.bounds_check_policies.image { crate::back::BoundsCheckPolicy::Restrict => { let (coords, _, _) = self.write_restricted_coordinates(image_id, coordinates, None, None, block)?; diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 53b1d48cb..0fc4c3ffe 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -358,9 +358,9 @@ impl<'w> BlockContext<'w> { }; let policy = if is_buffer { - self.writer.buffer_bounds_check_policy + self.writer.bounds_check_policies.buffer } else { - self.writer.index_bounds_check_policy + self.writer.bounds_check_policies.index }; Ok(match policy { diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index d57e53975..c26ed6187 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -13,7 +13,7 @@ mod writer; pub use spirv::Capability; -use crate::{arena::Handle, back::BoundsCheckPolicy, proc::TypeResolution}; +use crate::{arena::Handle, back::BoundsCheckPolicies, proc::TypeResolution}; use spirv::Word; use std::ops; @@ -417,9 +417,7 @@ pub struct Writer { debugs: Vec, annotations: Vec, flags: WriterFlags, - index_bounds_check_policy: BoundsCheckPolicy, - image_bounds_check_policy: BoundsCheckPolicy, - buffer_bounds_check_policy: BoundsCheckPolicy, + bounds_check_policies: BoundsCheckPolicies, void_type: Word, //TODO: convert most of these into vectors, addressable by handle indices lookup_type: crate::FastHashMap, @@ -461,48 +459,9 @@ pub struct Options { /// If this is `None`, all capabilities are permitted. pub capabilities: Option>, - /// How should the generated code handle array, vector, or matrix indices - /// that are out of range? - pub index_bounds_check_policy: BoundsCheckPolicy, - - /// How should the generated code handle array, vector, or matrix indices - /// that are out of range, when those values live in a [`GlobalVariable`] in - /// the [`Storage`] or [`Uniform`] storage classes? - /// - /// Some graphics hardware provides "robust buffer access", a feature that - /// ensures that using a pointer cannot access memory outside the 'buffer' - /// that it was derived from. In Naga terms, this means that the hardware - /// ensures that pointers computed by applying [`Access`] and - /// [`AccessIndex`] expressions to a [`GlobalVariable`] whose [`class`] is - /// [`Storage`] or [`Uniform`] will never read or write memory outside that - /// global variable. - /// - /// When hardware offers such a feature, it is probably undesirable to have - /// Naga inject bounds checking code for such accesses, since the hardware - /// can probably provide the same protection more efficiently. However, - /// bounds checks are still needed on accesses to indexable values that do - /// not live in buffers, like local variables. - /// - /// So, this option provides a separate policy that applies only to accesses - /// to storage and uniform globals. When depending on hardware bounds - /// checking, this policy can be `Unchecked` to avoid unnecessary overhead. - /// - /// When special hardware support is not available, this should probably be - /// the same as `index_bounds_check_policy`. - /// - /// [`GlobalVariable`]: crate::GlobalVariable - /// [`class`]: crate::GlobalVariable::class - /// [`Restrict`]: crate::back::BoundsCheckPolicy::Restrict - /// [`ReadZeroSkipWrite`]: crate::back::BoundsCheckPolicy::ReadZeroSkipWrite - /// [`Access`]: crate::Expression::Access - /// [`AccessIndex`]: crate::Expression::AccessIndex - /// [`Storage`]: crate::StorageClass::Storage - /// [`Uniform`]: crate::StorageClass::Uniform - pub buffer_bounds_check_policy: BoundsCheckPolicy, - - /// How should the generated code handle image references that are out of - /// range? - pub image_bounds_check_policy: BoundsCheckPolicy, + /// How should generate code handle array, vector, matrix, or image texel + /// indices that are out of range? + pub bounds_check_policies: BoundsCheckPolicies, } impl Default for Options { @@ -515,9 +474,7 @@ impl Default for Options { lang_version: (1, 0), flags, capabilities: None, - index_bounds_check_policy: super::BoundsCheckPolicy::default(), - image_bounds_check_policy: super::BoundsCheckPolicy::default(), - buffer_bounds_check_policy: super::BoundsCheckPolicy::default(), + bounds_check_policies: super::BoundsCheckPolicies::default(), } } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f845a7ff6..b8aa9008e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -66,9 +66,7 @@ impl Writer { debugs: vec![], annotations: vec![], flags: options.flags, - index_bounds_check_policy: options.index_bounds_check_policy, - image_bounds_check_policy: options.image_bounds_check_policy, - buffer_bounds_check_policy: options.buffer_bounds_check_policy, + bounds_check_policies: options.bounds_check_policies, void_type, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), @@ -104,9 +102,7 @@ impl Writer { let fresh = Writer { // Copied from the old Writer: flags: self.flags, - index_bounds_check_policy: self.index_bounds_check_policy, - image_bounds_check_policy: self.image_bounds_check_policy, - buffer_bounds_check_policy: self.buffer_bounds_check_policy, + bounds_check_policies: self.bounds_check_policies, capabilities_available: take(&mut self.capabilities_available), // Initialized afresh: diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 6902520d9..b346cc77f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -189,9 +189,11 @@ fn write_output_spv( Some(params.spv_capabilities.clone()) }, - index_bounds_check_policy: params.index_bounds_check_policy.into(), - buffer_bounds_check_policy: params.buffer_bounds_check_policy.into(), - image_bounds_check_policy: params.image_bounds_check_policy.into(), + bounds_check_policies: naga::back::BoundsCheckPolicies { + index: params.index_bounds_check_policy.into(), + buffer: params.buffer_bounds_check_policy.into(), + image: params.image_bounds_check_policy.into(), + }, ..spv::Options::default() }; From cb0ad2504ce8bbd868237032f49c10c944b490cb Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 27 Aug 2021 15:44:57 -0700 Subject: [PATCH 1298/2212] [spv-out] Handle break and continue in switch statements. Fixes #1030. Fixes #1017. --- src/back/spv/block.rs | 9 +- tests/in/control-flow.wgsl | 27 ++++ tests/out/glsl/control-flow.main.Compute.glsl | 25 ++++ tests/out/hlsl/control-flow.hlsl | 33 +++++ tests/out/msl/control-flow.msl | 39 ++++++ tests/out/spv/control-flow.spvasm | 120 +++++++++++++++--- tests/out/wgsl/control-flow.wgsl | 28 ++++ tests/snapshots.rs | 4 +- 8 files changed, 260 insertions(+), 25 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 3009085ce..e9970c23c 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1013,6 +1013,11 @@ impl<'w> BlockContext<'w> { Instruction::switch(selector_id, default_id, &raw_cases), ); + let inner_context = LoopContext { + break_id: Some(merge_id), + ..loop_context + }; + for (i, (case, raw_case)) in cases.iter().zip(raw_cases.iter()).enumerate() { let case_finish_id = if case.fall_through { match raw_cases.get(i + 1) { @@ -1026,11 +1031,11 @@ impl<'w> BlockContext<'w> { raw_case.label_id, &case.body, Some(case_finish_id), - LoopContext::default(), + inner_context, )?; } - self.write_block(default_id, default, Some(merge_id), LoopContext::default())?; + self.write_block(default_id, default, Some(merge_id), inner_context)?; block = Block::new(merge_id); } diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index 6cb0f3619..50e8b2229 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -30,3 +30,30 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { } } } + +fn switch_default_break(i: i32) { + switch (i) { + default: { + break; + } + } +} + +fn switch_case_break() { + switch(0) { + case 0: { + break; + } + } + return; +} + +fn loop_switch_continue(x: i32) { + loop { + switch (x) { + case 1: { + continue; + } + } + } +} diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index fd12e4346..2a42aa55c 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -6,6 +6,31 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +void switch_default_break(int i) { + switch(i) { + default: + break; + } +} + +void switch_case_break() { + switch(0) { + case 0: + break; + } + return; +} + +void loop_switch_continue(int x) { + while(true) { + switch(x) { + case 1: + continue; + } + } + return; +} + void main() { uvec3 global_id = gl_GlobalInvocationID; int pos = 0; diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index 020e228f0..3dd0ab7a2 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -1,4 +1,37 @@ +void switch_default_break(int i) +{ + switch(i) { + default: { + break; + } + } +} + +void switch_case_break() +{ + switch(0) { + case 0: { + break; + break; + } + } + return; +} + +void loop_switch_continue(int x) +{ + while(true) { + switch(x) { + case 1: { + continue; + break; + } + } + } + return; +} + [numthreads(1, 1, 1)] void main(uint3 global_id : SV_DispatchThreadID) { diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index bd9b8d27d..a2a80ac7b 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -3,6 +3,45 @@ #include +void switch_default_break( + int i +) { + switch(i) { + default: { + break; + } + } +} + +void switch_case_break( +) { + switch(0) { + case 0: { + break; + break; + } + default: { + } + } + return; +} + +void loop_switch_continue( + int x +) { + while(true) { + switch(x) { + case 1: { + continue; + break; + } + default: { + } + } + } + return; +} + struct main1Input { }; kernel void main1( diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index b46424b80..fc79a6c7b 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -1,29 +1,109 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 16 +; Bound: 56 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %9 "main" %6 -OpExecutionMode %9 LocalSize 1 1 1 -OpDecorate %6 BuiltIn GlobalInvocationId +OpEntryPoint GLCompute %41 "main" %38 +OpExecutionMode %41 LocalSize 1 1 1 +OpDecorate %38 BuiltIn GlobalInvocationId %2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpTypeVector %4 3 -%7 = OpTypePointer Input %3 -%6 = OpVariable %7 Input -%10 = OpTypeFunction %2 -%12 = OpConstant %4 2 -%13 = OpConstant %4 1 -%14 = OpConstant %4 72 -%15 = OpConstant %4 264 -%9 = OpFunction %2 None %10 -%5 = OpLabel -%8 = OpLoad %3 %6 -OpBranch %11 -%11 = OpLabel -OpControlBarrier %12 %13 %14 -OpControlBarrier %12 %12 %15 +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 1 +%5 = OpConstant %4 0 +%6 = OpConstant %4 2 +%7 = OpConstant %4 3 +%9 = OpTypeInt 32 0 +%8 = OpTypeVector %9 3 +%13 = OpTypeFunction %2 %4 +%19 = OpTypeFunction %2 +%36 = OpTypePointer Function %4 +%39 = OpTypePointer Input %8 +%38 = OpVariable %39 Input +%43 = OpConstant %9 2 +%44 = OpConstant %9 1 +%45 = OpConstant %9 72 +%46 = OpConstant %9 264 +%12 = OpFunction %2 None %13 +%11 = OpFunctionParameter %4 +%10 = OpLabel +OpBranch %14 +%14 = OpLabel +OpSelectionMerge %15 None +OpSwitch %11 %16 +%16 = OpLabel +OpBranch %15 +%15 = OpLabel +OpReturn +OpFunctionEnd +%18 = OpFunction %2 None %19 +%17 = OpLabel +OpBranch %20 +%20 = OpLabel +OpSelectionMerge %21 None +OpSwitch %5 %22 0 %23 +%23 = OpLabel +OpBranch %21 +%22 = OpLabel +OpBranch %21 +%21 = OpLabel +OpReturn +OpFunctionEnd +%26 = OpFunction %2 None %13 +%25 = OpFunctionParameter %4 +%24 = OpLabel +OpBranch %27 +%27 = OpLabel +OpBranch %28 +%28 = OpLabel +OpLoopMerge %29 %31 None +OpBranch %30 +%30 = OpLabel +OpSelectionMerge %32 None +OpSwitch %25 %33 1 %34 +%34 = OpLabel +OpBranch %31 +%33 = OpLabel +OpBranch %32 +%32 = OpLabel +OpBranch %31 +%31 = OpLabel +OpBranch %28 +%29 = OpLabel +OpReturn +OpFunctionEnd +%41 = OpFunction %2 None %19 +%37 = OpLabel +%35 = OpVariable %36 Function +%40 = OpLoad %8 %38 +OpBranch %42 +%42 = OpLabel +OpControlBarrier %43 %44 %45 +OpControlBarrier %43 %43 %46 +OpSelectionMerge %47 None +OpSwitch %3 %48 +%48 = OpLabel +OpStore %35 %3 +OpBranch %47 +%47 = OpLabel +%49 = OpLoad %4 %35 +OpSelectionMerge %50 None +OpSwitch %49 %51 1 %52 2 %53 3 %54 4 %55 +%52 = OpLabel +OpStore %35 %5 +OpBranch %50 +%53 = OpLabel +OpStore %35 %3 +OpReturn +%54 = OpLabel +OpStore %35 %6 +OpBranch %55 +%55 = OpLabel +OpReturn +%51 = OpLabel +OpStore %35 %7 +OpReturn +%50 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index 3eb55cfd8..903ad9923 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -1,3 +1,31 @@ +fn switch_default_break(i: i32) { + switch(i) { + default: { + break; + } + } +} + +fn switch_case_break() { + switch(0) { + case 0: { + break; + } + } + return; +} + +fn loop_switch_continue(x: i32) { + loop { + switch(x) { + case 1: { + continue; + } + } + } + return; +} + [[stage(compute), workgroup_size(1, 1, 1)]] fn main([[builtin(global_invocation_id)]] global_id: vec3) { var pos: i32; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b346cc77f..d25aa0df6 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -448,9 +448,7 @@ fn convert_wgsl() { ), ( "control-flow", - // TODO: SPIRV https://github.com/gfx-rs/naga/issues/1017 - //Targets::SPIRV | - Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "standard", From f7040a2787b1de8cd169ed83765d12908d781156 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 27 Aug 2021 20:16:46 +0300 Subject: [PATCH 1299/2212] [hlsl-out] Fix output struct member names --- src/back/hlsl/writer.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 136aee3ca..ed4e963b7 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -400,7 +400,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; let index = fake_members.len() as u32; fake_members.push(EpStructMember { - name: self.namer.call_unique(member_name), + name: self.namer.call(member_name), ty: member.ty, binding: member.binding.clone(), index, @@ -409,13 +409,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } _ => { let member_name = if let Some(ref name) = arg.name { - name + self.namer.call_unique(name) } else { - "member" + self.namer.call("member") }; let index = fake_members.len() as u32; fake_members.push(EpStructMember { - name: self.namer.call_unique(member_name), + name: member_name, ty: arg.ty, binding: arg.binding.clone(), index, @@ -451,13 +451,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { for member in members.iter() { let member_name = if let Some(ref name) = member.name { - name + self.namer.call_unique(name) } else { - "member" + self.namer.call("member") }; let index = fake_members.len() as u32; fake_members.push(EpStructMember { - name: self.namer.call_unique(member_name), + name: member_name, ty: member.ty, binding: member.binding.clone(), index, From 846dbb5a3e47bacb83727f767228f9f3622365b1 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 27 Aug 2021 20:42:11 -0700 Subject: [PATCH 1300/2212] [spv-out] Request proper capabilities for storage image formats. --- src/back/spv/instructions.rs | 75 ++++++++++++++++++++---------------- src/back/spv/writer.rs | 61 ++++++++++++++++++++++++++++- tests/spirv-capabilities.rs | 42 ++++++++++++-------- 3 files changed, 126 insertions(+), 52 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index ff7b3c5d3..8369102d5 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -242,40 +242,7 @@ impl super::Instruction { instruction.add_operand(if sampled { 1 } else { 2 }); let format = match image_class { - crate::ImageClass::Storage { format, .. } => match format { - crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8, - crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm, - crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui, - crate::StorageFormat::R8Sint => spirv::ImageFormat::R8i, - crate::StorageFormat::R16Uint => spirv::ImageFormat::R16ui, - crate::StorageFormat::R16Sint => spirv::ImageFormat::R16i, - crate::StorageFormat::R16Float => spirv::ImageFormat::R16f, - crate::StorageFormat::Rg8Unorm => spirv::ImageFormat::Rg8, - crate::StorageFormat::Rg8Snorm => spirv::ImageFormat::Rg8Snorm, - crate::StorageFormat::Rg8Uint => spirv::ImageFormat::Rg8ui, - crate::StorageFormat::Rg8Sint => spirv::ImageFormat::Rg8i, - crate::StorageFormat::R32Uint => spirv::ImageFormat::R32ui, - crate::StorageFormat::R32Sint => spirv::ImageFormat::R32i, - crate::StorageFormat::R32Float => spirv::ImageFormat::R32f, - crate::StorageFormat::Rg16Uint => spirv::ImageFormat::Rg16ui, - crate::StorageFormat::Rg16Sint => spirv::ImageFormat::Rg16i, - crate::StorageFormat::Rg16Float => spirv::ImageFormat::Rg16f, - crate::StorageFormat::Rgba8Unorm => spirv::ImageFormat::Rgba8, - crate::StorageFormat::Rgba8Snorm => spirv::ImageFormat::Rgba8Snorm, - crate::StorageFormat::Rgba8Uint => spirv::ImageFormat::Rgba8ui, - crate::StorageFormat::Rgba8Sint => spirv::ImageFormat::Rgba8i, - crate::StorageFormat::Rgb10a2Unorm => spirv::ImageFormat::Rgb10a2ui, - crate::StorageFormat::Rg11b10Float => spirv::ImageFormat::R11fG11fB10f, - crate::StorageFormat::Rg32Uint => spirv::ImageFormat::Rg32ui, - crate::StorageFormat::Rg32Sint => spirv::ImageFormat::Rg32i, - crate::StorageFormat::Rg32Float => spirv::ImageFormat::Rg32f, - crate::StorageFormat::Rgba16Uint => spirv::ImageFormat::Rgba16ui, - crate::StorageFormat::Rgba16Sint => spirv::ImageFormat::Rgba16i, - crate::StorageFormat::Rgba16Float => spirv::ImageFormat::Rgba16f, - crate::StorageFormat::Rgba32Uint => spirv::ImageFormat::Rgba32ui, - crate::StorageFormat::Rgba32Sint => spirv::ImageFormat::Rgba32i, - crate::StorageFormat::Rgba32Float => spirv::ImageFormat::Rgba32f, - }, + crate::ImageClass::Storage { format, .. } => format.into(), _ => spirv::ImageFormat::Unknown, }; @@ -919,3 +886,43 @@ impl super::Instruction { instruction } } + +impl From for spirv::ImageFormat { + fn from(format: crate::StorageFormat) -> Self { + use crate::StorageFormat as Sf; + match format { + Sf::R8Unorm => Self::R8, + Sf::R8Snorm => Self::R8Snorm, + Sf::R8Uint => Self::R8ui, + Sf::R8Sint => Self::R8i, + Sf::R16Uint => Self::R16ui, + Sf::R16Sint => Self::R16i, + Sf::R16Float => Self::R16f, + Sf::Rg8Unorm => Self::Rg8, + Sf::Rg8Snorm => Self::Rg8Snorm, + Sf::Rg8Uint => Self::Rg8ui, + Sf::Rg8Sint => Self::Rg8i, + Sf::R32Uint => Self::R32ui, + Sf::R32Sint => Self::R32i, + Sf::R32Float => Self::R32f, + Sf::Rg16Uint => Self::Rg16ui, + Sf::Rg16Sint => Self::Rg16i, + Sf::Rg16Float => Self::Rg16f, + Sf::Rgba8Unorm => Self::Rgba8, + Sf::Rgba8Snorm => Self::Rgba8Snorm, + Sf::Rgba8Uint => Self::Rgba8ui, + Sf::Rgba8Sint => Self::Rgba8i, + Sf::Rgb10a2Unorm => Self::Rgb10a2ui, + Sf::Rg11b10Float => Self::R11fG11fB10f, + Sf::Rg32Uint => Self::Rg32ui, + Sf::Rg32Sint => Self::Rg32i, + Sf::Rg32Float => Self::Rg32f, + Sf::Rgba16Uint => Self::Rgba16ui, + Sf::Rgba16Sint => Self::Rgba16i, + Sf::Rgba16Float => Self::Rgba16f, + Sf::Rgba32Uint => Self::Rgba32ui, + Sf::Rgba32Sint => Self::Rgba32i, + Sf::Rgba32Float => Self::Rgba32f, + } + } +} diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index b8aa9008e..d665a29c0 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -720,7 +720,10 @@ impl Writer { let (kind, sampled) = match class { crate::ImageClass::Sampled { kind, multi: _ } => (kind, true), crate::ImageClass::Depth { multi: _ } => (crate::ScalarKind::Float, true), - crate::ImageClass::Storage { format, .. } => (format.into(), false), + crate::ImageClass::Storage { format, .. } => { + self.request_image_format_capabilities(spirv::ImageFormat::from(format))?; + (crate::ScalarKind::from(format), false) + } }; let local_type = LocalType::Value { vector_size: None, @@ -858,6 +861,62 @@ impl Writer { Ok(id) } + fn request_image_format_capabilities( + &mut self, + format: spirv::ImageFormat, + ) -> Result<(), Error> { + use spirv::ImageFormat as If; + match format { + If::Rg32f + | If::Rg16f + | If::R11fG11fB10f + | If::R16f + | If::Rgba16 + | If::Rgb10A2 + | If::Rg16 + | If::Rg8 + | If::R16 + | If::R8 + | If::Rgba16Snorm + | If::Rg16Snorm + | If::Rg8Snorm + | If::R16Snorm + | If::R8Snorm + | If::Rg32i + | If::Rg16i + | If::Rg8i + | If::R16i + | If::R8i + | If::Rgb10a2ui + | If::Rg32ui + | If::Rg16ui + | If::Rg8ui + | If::R16ui + | If::R8ui => self.require_any( + "storage image format", + &[spirv::Capability::StorageImageExtendedFormats], + ), + If::R64ui | If::R64i => self.require_any( + "64-bit integer storage image format", + &[spirv::Capability::Int64ImageEXT], + ), + If::Unknown + | If::Rgba32f + | If::Rgba16f + | If::R32f + | If::Rgba8 + | If::Rgba8Snorm + | If::Rgba32i + | If::Rgba16i + | If::Rgba8i + | If::R32i + | If::Rgba32ui + | If::Rgba16ui + | If::Rgba8ui + | If::R32ui => Ok(()), + } + } + pub(super) fn get_index_constant(&mut self, index: Word) -> Word { self.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) } diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs index c4664a90c..be5fa62bf 100644 --- a/tests/spirv-capabilities.rs +++ b/tests/spirv-capabilities.rs @@ -26,19 +26,7 @@ fn capabilities_used(source: &str) -> naga::FastHashSet { } fn require(capabilities: &[Ca], source: &str) { - let caps_used = capabilities_used(source); - - let missing_caps: Vec<_> = capabilities - .iter() - .filter(|cap| !caps_used.contains(cap)) - .cloned() - .collect(); - if !missing_caps.is_empty() { - panic!( - "shader code should have requested these caps: {:?}", - missing_caps - ); - } + require_and_forbid(capabilities, &[], source); } fn require_and_forbid(required: &[Ca], forbidden: &[Ca], source: &str) { @@ -51,8 +39,8 @@ fn require_and_forbid(required: &[Ca], forbidden: &[Ca], source: &str) { .collect(); if !missing_caps.is_empty() { panic!( - "shader code should have requested these caps: {:?}", - missing_caps + "shader code should have requested these caps: {:?}\n\n{}", + missing_caps, source ); } @@ -63,8 +51,8 @@ fn require_and_forbid(required: &[Ca], forbidden: &[Ca], source: &str) { .collect(); if !forbidden_caps.is_empty() { panic!( - "shader code should not have requested these caps: {:?}", - forbidden_caps + "shader code should not have requested these caps: {:?}\n\n{}", + forbidden_caps, source ); } } @@ -170,3 +158,23 @@ fn geometry() { "#, ); } + +#[test] +fn storage_image_formats() { + require_and_forbid( + &[Ca::Shader], + &[Ca::StorageImageExtendedFormats], + r#" + [[group(0), binding(0)]] + var image_rg32f: texture_storage_2d; + "#, + ); + + require( + &[Ca::StorageImageExtendedFormats], + r#" + [[group(0), binding(0)]] + var image_rg32f: texture_storage_2d; + "#, + ); +} From e8d35e8035968c076a1569ea76513b58e8bf8dcf Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 28 Aug 2021 17:00:32 -0700 Subject: [PATCH 1301/2212] [spv-out] Avoid duplicate lookup in write_type_declaration_local. --- src/back/spv/writer.rs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d665a29c0..bbb9827f5 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -173,12 +173,18 @@ impl Writer { } pub(super) fn get_type_id(&mut self, lookup_ty: LookupType) -> Word { - if let Entry::Occupied(e) = self.lookup_type.entry(lookup_ty) { - *e.get() - } else { - match lookup_ty { - LookupType::Handle(_handle) => unreachable!("Handles are populated at start"), - LookupType::Local(local_ty) => self.write_type_declaration_local(local_ty), + match self.lookup_type.entry(lookup_ty) { + Entry::Occupied(e) => *e.get(), + Entry::Vacant(e) => { + let local = match lookup_ty { + LookupType::Handle(_handle) => unreachable!("Handles are populated at start"), + LookupType::Local(local) => local, + }; + + let id = self.id_gen.next(); + e.insert(id); + self.write_type_declaration_local(id, local); + id } } } @@ -585,8 +591,7 @@ impl Writer { } } - fn write_type_declaration_local(&mut self, local_ty: LocalType) -> Word { - let id = self.id_gen.next(); + fn write_type_declaration_local(&mut self, id: Word, local_ty: LocalType) { let instruction = match local_ty { LocalType::Value { vector_size: None, @@ -646,9 +651,7 @@ impl Writer { } }; - self.lookup_type.insert(LookupType::Local(local_ty), id); instruction.to_words(&mut self.logical_layout.declarations); - id } fn write_type_declaration_arena( From 6b72099d763243830eafcd9d801ce9cd2d93965f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 28 Aug 2021 21:07:28 -0700 Subject: [PATCH 1302/2212] [spv-out] Let write_type_declaration_local handle all LocalTypes. Change `write_type_declaration_local` to handle any type that can be represented as a `LocalType`. This means that Image and Sampler types are handled there now. Change `write_type_declaration_arena` to defer to `write_type_declaration_local` to handle any type that can be represented as a `LocalType`. This makes the code for those types in `write_type_declaration_arena` redundant, so remove it. However, continue to request SPIR-V capabilities for image types from `write_type_declaration_arena`, since that function is fallible, while `write_type_declaration_local` is not. --- src/back/spv/mod.rs | 7 + src/back/spv/writer.rs | 374 ++++++++++++++++++++--------------------- 2 files changed, 190 insertions(+), 191 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index c26ed6187..7aeef7582 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -161,6 +161,13 @@ impl Function { /// so we can't ever create a `Handle` to refer to them. So for local use /// in the SPIR-V writer, we have this home-grown type enum that covers only the /// cases we need (for example, it doesn't cover structs). +/// +/// As explained in §2.8 of the SPIR-V spec, some classes of type instructions +/// must be unique; for example, you can't have two `OpTypeInt 32 1` +/// instructions in the same module. `Writer::lookup_type` maps each `LocalType` +/// value for which we've written instructions to its id, so we can avoid +/// writing out duplicates. `LocalType` also includes variants like `Pointer` +/// that do not need to be unique - but it is harmless to avoid the duplication. #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LocalType { /// A scalar, vector, or pointer to one of those. diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index bbb9827f5..036eb4e74 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -591,6 +591,50 @@ impl Writer { } } + fn request_image_capabilities(&mut self, inner: &crate::TypeInner) -> Result<(), Error> { + if let crate::TypeInner::Image { + dim, + arrayed, + class, + } = *inner + { + let sampled = match class { + crate::ImageClass::Sampled { .. } => true, + crate::ImageClass::Depth { .. } => true, + crate::ImageClass::Storage { format, .. } => { + self.request_image_format_capabilities(format.into())?; + false + } + }; + + match dim { + crate::ImageDimension::D1 => { + if sampled { + self.require_any("sampled 1D images", &[spirv::Capability::Sampled1D])?; + } else { + self.require_any("1D storage images", &[spirv::Capability::Image1D])?; + } + } + crate::ImageDimension::Cube if arrayed => { + if sampled { + self.require_any( + "sampled cube array images", + &[spirv::Capability::SampledCubeArray], + )?; + } else { + self.require_any( + "cube array storage images", + &[spirv::Capability::ImageCubeArray], + )?; + } + } + _ => {} + } + } + + Ok(()) + } + fn write_type_declaration_local(&mut self, id: Word, local_ty: LocalType) { let instruction = match local_ty { LocalType::Value { @@ -644,8 +688,27 @@ impl Writer { })); Instruction::type_pointer(id, class, type_id) } - // all the samplers and image types go through `write_type_declaration_arena` - LocalType::Image { .. } | LocalType::Sampler => unreachable!(), + LocalType::Image { + dim, + arrayed, + class, + } => { + let kind = match class { + crate::ImageClass::Sampled { kind, multi: _ } => kind, + crate::ImageClass::Depth { multi: _ } => crate::ScalarKind::Float, + crate::ImageClass::Storage { format, .. } => format.into(), + }; + let local_type = LocalType::Value { + vector_size: None, + kind, + width: 4, + pointer_class: None, + }; + let type_id = self.get_type_id(LookupType::Local(local_type)); + let dim = map_dim(dim); + Instruction::type_image(id, type_id, dim, arrayed, class) + } + LocalType::Sampler => Instruction::type_sampler(id), LocalType::SampledImage { image_type_id } => { Instruction::type_sampled_image(id, image_type_id) } @@ -663,204 +726,133 @@ impl Writer { let decorate_layout = true; //TODO? let id = if let Some(local) = make_local(&ty.inner) { + // This type can be represented as a `LocalType`, so check if we've + // already written an instruction for it. If not, do so now, with + // `write_type_declaration_local`. match self.lookup_type.entry(LookupType::Local(local)) { - // if it's already known as local, re-use it - Entry::Occupied(e) => { - let id = *e.into_mut(); - self.lookup_type.insert(LookupType::Handle(handle), id); - return Ok(id); - } - // also register the type as "local", to avoid duplication + // We already have an id for this `LocalType`. + Entry::Occupied(e) => *e.get(), + + // It's a type we haven't seen before. Entry::Vacant(e) => { let id = self.id_gen.next(); - *e.insert(id) + e.insert(id); + self.write_type_declaration_local(id, local); + + // If it's an image type, request SPIR-V capabilities here, so + // write_type_declaration_local can stay infallible. + self.request_image_capabilities(&ty.inner)?; + + id } } } else { - self.id_gen.next() + use spirv::Decoration; + + let id = self.id_gen.next(); + let instruction = match ty.inner { + crate::TypeInner::Array { base, size, stride } => { + if decorate_layout { + self.decorate(id, Decoration::ArrayStride, &[stride]); + } + + let type_id = self.get_type_id(LookupType::Handle(base)); + match size { + crate::ArraySize::Constant(const_handle) => { + let length_id = self.constant_ids[const_handle.index()]; + Instruction::type_array(id, type_id, length_id) + } + crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), + } + } + crate::TypeInner::Struct { + top_level, + ref members, + span: _, + } => { + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = ty.name { + self.debugs.push(Instruction::name(id, name)); + } + } + + if top_level { + self.decorate(id, Decoration::Block, &[]); + } + + let mut member_ids = Vec::with_capacity(members.len()); + for (index, member) in members.iter().enumerate() { + if decorate_layout { + self.annotations.push(Instruction::member_decorate( + id, + index as u32, + Decoration::Offset, + &[member.offset], + )); + } + + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = member.name { + self.debugs + .push(Instruction::member_name(id, index as u32, name)); + } + } + + // The matrix decorations also go on arrays of matrices, + // so lets check this first. + let member_array_subty_inner = match arena[member.ty].inner { + crate::TypeInner::Array { base, .. } => &arena[base].inner, + ref other => other, + }; + if let crate::TypeInner::Matrix { + columns, + rows: _, + width, + } = *member_array_subty_inner + { + let byte_stride = match columns { + crate::VectorSize::Bi => 2 * width, + crate::VectorSize::Tri | crate::VectorSize::Quad => 4 * width, + }; + self.annotations.push(Instruction::member_decorate( + id, + index as u32, + Decoration::ColMajor, + &[], + )); + self.annotations.push(Instruction::member_decorate( + id, + index as u32, + Decoration::MatrixStride, + &[byte_stride as u32], + )); + } + + let member_id = self.get_type_id(LookupType::Handle(member.ty)); + member_ids.push(member_id); + } + Instruction::type_struct(id, member_ids.as_slice()) + } + + // These all have TypeLocal representations, so they should have been + // handled by `write_type_declaration_local` above. + crate::TypeInner::Scalar { .. } + | crate::TypeInner::Atomic { .. } + | crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } + | crate::TypeInner::Pointer { .. } + | crate::TypeInner::ValuePointer { .. } + | crate::TypeInner::Image { .. } + | crate::TypeInner::Sampler { .. } => unreachable!(), + }; + + instruction.to_words(&mut self.logical_layout.declarations); + id }; + + // Add this handle as a new alias for that type. self.lookup_type.insert(LookupType::Handle(handle), id); - if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = ty.name { - self.debugs.push(Instruction::name(id, name)); - } - } - - use spirv::Decoration; - - let instruction = match ty.inner { - crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Atomic { kind, width } => { - self.make_scalar(id, kind, width) - } - crate::TypeInner::Vector { size, kind, width } => { - let scalar_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind, - width, - pointer_class: None, - })); - Instruction::type_vector(id, scalar_id, size) - } - crate::TypeInner::Matrix { - columns, - rows, - width, - } => { - let vector_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(rows), - kind: crate::ScalarKind::Float, - width, - pointer_class: None, - })); - Instruction::type_matrix(id, vector_id, columns) - } - crate::TypeInner::Image { - dim, - arrayed, - class, - } => { - let (kind, sampled) = match class { - crate::ImageClass::Sampled { kind, multi: _ } => (kind, true), - crate::ImageClass::Depth { multi: _ } => (crate::ScalarKind::Float, true), - crate::ImageClass::Storage { format, .. } => { - self.request_image_format_capabilities(spirv::ImageFormat::from(format))?; - (crate::ScalarKind::from(format), false) - } - }; - let local_type = LocalType::Value { - vector_size: None, - kind, - width: 4, - pointer_class: None, - }; - let dim = map_dim(dim); - match dim { - spirv::Dim::Dim1D => { - if sampled { - self.require_any("sampled 1D images", &[spirv::Capability::Sampled1D])?; - } else { - self.require_any("1D storage images", &[spirv::Capability::Image1D])?; - } - } - spirv::Dim::DimCube if arrayed => { - if sampled { - self.require_any( - "sampled cube array images", - &[spirv::Capability::SampledCubeArray], - )?; - } else { - self.require_any( - "cube array storage images", - &[spirv::Capability::ImageCubeArray], - )?; - } - } - _ => {} - } - let type_id = self.get_type_id(LookupType::Local(local_type)); - Instruction::type_image(id, type_id, dim, arrayed, class) - } - crate::TypeInner::Sampler { comparison: _ } => Instruction::type_sampler(id), - crate::TypeInner::Array { base, size, stride } => { - if decorate_layout { - self.decorate(id, Decoration::ArrayStride, &[stride]); - } - - let type_id = self.get_type_id(LookupType::Handle(base)); - match size { - crate::ArraySize::Constant(const_handle) => { - let length_id = self.constant_ids[const_handle.index()]; - Instruction::type_array(id, type_id, length_id) - } - crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), - } - } - crate::TypeInner::Struct { - top_level, - ref members, - span: _, - } => { - if top_level { - self.decorate(id, Decoration::Block, &[]); - } - - let mut member_ids = Vec::with_capacity(members.len()); - for (index, member) in members.iter().enumerate() { - if decorate_layout { - self.annotations.push(Instruction::member_decorate( - id, - index as u32, - Decoration::Offset, - &[member.offset], - )); - } - - if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = member.name { - self.debugs - .push(Instruction::member_name(id, index as u32, name)); - } - } - - // The matrix decorations also go on arrays of matrices, - // so lets check this first. - let member_array_subty_inner = match arena[member.ty].inner { - crate::TypeInner::Array { base, .. } => &arena[base].inner, - ref other => other, - }; - if let crate::TypeInner::Matrix { - columns, - rows: _, - width, - } = *member_array_subty_inner - { - let byte_stride = match columns { - crate::VectorSize::Bi => 2 * width, - crate::VectorSize::Tri | crate::VectorSize::Quad => 4 * width, - }; - self.annotations.push(Instruction::member_decorate( - id, - index as u32, - Decoration::ColMajor, - &[], - )); - self.annotations.push(Instruction::member_decorate( - id, - index as u32, - Decoration::MatrixStride, - &[byte_stride as u32], - )); - } - - let member_id = self.get_type_id(LookupType::Handle(member.ty)); - member_ids.push(member_id); - } - Instruction::type_struct(id, member_ids.as_slice()) - } - crate::TypeInner::Pointer { base, class } => { - let type_id = self.get_type_id(LookupType::Handle(base)); - let raw_class = map_storage_class(class); - Instruction::type_pointer(id, raw_class, type_id) - } - crate::TypeInner::ValuePointer { - size, - kind, - width, - class, - } => { - let raw_class = map_storage_class(class); - let type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: size, - kind, - width, - pointer_class: None, - })); - Instruction::type_pointer(id, raw_class, type_id) - } - }; - - instruction.to_words(&mut self.logical_layout.declarations); Ok(id) } From 5b1c2e59f6e9208eea77a60f6866ddc5f6d8f998 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 28 Aug 2021 21:51:49 -0700 Subject: [PATCH 1303/2212] [spv-out] Write debug names for all types, not just structs. This affects a lot of snapshots, so it's in its own commit, for easier review. --- src/back/spv/writer.rs | 12 ++++++------ tests/out/spv/access.spvasm | 2 +- tests/out/spv/boids.spvasm | 6 +++--- tests/out/spv/collatz.spvasm | 2 +- tests/out/spv/interpolate.spvasm | 2 +- tests/out/spv/policy-mix.spvasm | 4 ++-- tests/out/spv/quad.spvasm | 2 +- tests/out/spv/shadow.spvasm | 6 +++--- 8 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 036eb4e74..1f108c20b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -770,12 +770,6 @@ impl Writer { ref members, span: _, } => { - if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = ty.name { - self.debugs.push(Instruction::name(id, name)); - } - } - if top_level { self.decorate(id, Decoration::Block, &[]); } @@ -853,6 +847,12 @@ impl Writer { // Add this handle as a new alias for that type. self.lookup_type.insert(LookupType::Handle(handle), id); + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = ty.name { + self.debugs.push(Instruction::name(id, name)); + } + } + Ok(id) } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 40698045e..1db429ce7 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -10,11 +10,11 @@ OpEntryPoint Vertex %39 "foo" %34 %37 OpEntryPoint GLCompute %84 "atomics" OpExecutionMode %84 LocalSize 1 1 1 OpSource GLSL 450 -OpName %25 "Bar" OpMemberName %25 0 "matrix" OpMemberName %25 1 "atom" OpMemberName %25 2 "arr" OpMemberName %25 3 "data" +OpName %25 "Bar" OpName %27 "bar" OpName %29 "foo" OpName %31 "c" diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index a40311f79..1bb7edcde 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -10,10 +10,9 @@ OpEntryPoint GLCompute %43 "main" %40 OpExecutionMode %43 LocalSize 64 1 1 OpSource GLSL 450 OpName %3 "NUM_PARTICLES" -OpName %16 "Particle" OpMemberName %16 0 "pos" OpMemberName %16 1 "vel" -OpName %17 "SimParams" +OpName %16 "Particle" OpMemberName %17 0 "deltaT" OpMemberName %17 1 "rule1Distance" OpMemberName %17 2 "rule2Distance" @@ -21,8 +20,9 @@ OpMemberName %17 3 "rule3Distance" OpMemberName %17 4 "rule1Scale" OpMemberName %17 5 "rule2Scale" OpMemberName %17 6 "rule3Scale" -OpName %19 "Particles" +OpName %17 "SimParams" OpMemberName %19 0 "particles" +OpName %19 "Particles" OpName %21 "params" OpName %23 "particlesSrc" OpName %25 "particlesDst" diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index ce1b3e5e2..5ac6c3d3f 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -9,8 +9,8 @@ OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %48 "main" %45 OpExecutionMode %48 LocalSize 1 1 1 OpSource GLSL 450 -OpName %9 "PrimeIndices" OpMemberName %9 0 "data" +OpName %9 "PrimeIndices" OpName %11 "v_indices" OpName %13 "n" OpName %15 "i" diff --git a/tests/out/spv/interpolate.spvasm b/tests/out/spv/interpolate.spvasm index 80f62b6a4..019b9ae0e 100644 --- a/tests/out/spv/interpolate.spvasm +++ b/tests/out/spv/interpolate.spvasm @@ -10,7 +10,6 @@ OpEntryPoint Vertex %42 "main" %29 %31 %33 %35 %37 %39 %40 %41 OpEntryPoint Fragment %106 "main" %85 %88 %91 %94 %97 %100 %102 %104 OpExecutionMode %106 OriginUpperLeft OpSource GLSL 450 -OpName %25 "FragmentInput" OpMemberName %25 0 "position" OpMemberName %25 1 "flat" OpMemberName %25 2 "linear" @@ -19,6 +18,7 @@ OpMemberName %25 4 "linear_sample" OpMemberName %25 5 "perspective" OpMemberName %25 6 "perspective_centroid" OpMemberName %25 7 "perspective_sample" +OpName %25 "FragmentInput" OpName %26 "out" OpName %29 "position" OpName %31 "flat" diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index 466cc8585..5d81184d3 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -9,10 +9,10 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpSource GLSL 450 -OpName %15 "InStorage" OpMemberName %15 0 "a" -OpName %17 "InUniform" +OpName %15 "InStorage" OpMemberName %17 0 "a" +OpName %17 "InUniform" OpName %23 "in_storage" OpName %25 "in_uniform" OpName %27 "image_2d_array" diff --git a/tests/out/spv/quad.spvasm b/tests/out/spv/quad.spvasm index 51b6b61e4..cbf63236d 100644 --- a/tests/out/spv/quad.spvasm +++ b/tests/out/spv/quad.spvasm @@ -12,9 +12,9 @@ OpExecutionMode %45 OriginUpperLeft OpExecutionMode %61 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" -OpName %10 "VertexOutput" OpMemberName %10 0 "uv" OpMemberName %10 1 "position" +OpName %10 "VertexOutput" OpName %13 "u_texture" OpName %15 "u_sampler" OpName %18 "pos" diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index cf7a3e5fb..0361ff2f4 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -10,14 +10,14 @@ OpEntryPoint Fragment %77 "fs_main" %69 %72 %75 OpExecutionMode %77 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_max_lights" -OpName %14 "Globals" OpMemberName %14 0 "num_lights" -OpName %17 "Light" +OpName %14 "Globals" OpMemberName %17 0 "proj" OpMemberName %17 1 "pos" OpMemberName %17 2 "color" -OpName %19 "Lights" +OpName %17 "Light" OpMemberName %19 0 "data" +OpName %19 "Lights" OpName %24 "c_ambient" OpName %25 "u_globals" OpName %27 "s_lights" From 81fbad182c54fdf9296585c373bc454425a868c8 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 28 Aug 2021 22:15:06 -0700 Subject: [PATCH 1304/2212] [spv-out] Avoid generating duplicate OpTypeImage instructions. Fixes #1305. Ensure that two `back::spv::LocalType::Image` values are sure to be equal (and hash equal) whenever they would generate the same `OpTypeImage` instruction, so that the usual duplicate removal via `Writer::lookup_type` works. Accomplish this by changing the contents of `LocalType::Image` to more closely match the operands of `OpTypeImage` instructions. Previously, `LocalType::Image` included a `ImageClass::Storage::access` value, which did not affect the `OpTypeImage` instruction generated. If two `LocalType::Image` values differered only in their `access`, then they would get separate entries in `Writer::lookup_type`, two identical `OpTypeImage` instructions would be generated, and SPIR-V validation would fail. --- src/back/spv/instructions.rs | 22 ++++------- src/back/spv/mod.rs | 76 +++++++++++++++++++++++++++++++----- src/back/spv/writer.rs | 34 ++++++---------- 3 files changed, 85 insertions(+), 47 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 8369102d5..f881294bc 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -219,34 +219,26 @@ impl super::Instruction { instruction } + #[allow(clippy::too_many_arguments)] pub(super) fn type_image( id: Word, sampled_type_id: Word, dim: spirv::Dim, + depth: bool, arrayed: bool, - image_class: crate::ImageClass, + multisampled: bool, + sampled: bool, + image_format: spirv::ImageFormat, ) -> Self { let mut instruction = Self::new(Op::TypeImage); instruction.set_result(id); instruction.add_operand(sampled_type_id); instruction.add_operand(dim as u32); - - let (depth, multi, sampled) = match image_class { - crate::ImageClass::Sampled { kind: _, multi } => (false, multi, true), - crate::ImageClass::Depth { multi } => (true, multi, true), - crate::ImageClass::Storage { .. } => (false, false, false), - }; instruction.add_operand(depth as u32); instruction.add_operand(arrayed as u32); - instruction.add_operand(multi as u32); + instruction.add_operand(multisampled as u32); instruction.add_operand(if sampled { 1 } else { 2 }); - - let format = match image_class { - crate::ImageClass::Storage { format, .. } => format.into(), - _ => spirv::ImageFormat::Unknown, - }; - - instruction.add_operand(format as u32); + instruction.add_operand(image_format as u32); instruction } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 7aeef7582..6c272db28 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -153,6 +153,70 @@ impl Function { } } +fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { + match dim { + crate::ImageDimension::D1 => spirv::Dim::Dim1D, + crate::ImageDimension::D2 => spirv::Dim::Dim2D, + crate::ImageDimension::D3 => spirv::Dim::Dim3D, + crate::ImageDimension::Cube => spirv::Dim::DimCube, + } +} + +/// Characteristics of a SPIR-V `OpTypeImage` type. +/// +/// SPIR-V requires non-composite types to be unique, including images. Since we +/// use `LocalType` for this deduplication, it's essential that `LocalImageType` +/// be equal whenever the corresponding `OpTypeImage`s would be. To reduce the +/// likelihood of mistakes, we use fields that correspond exactly to the +/// operands of an `OpTypeImage` instruction, using the actual SPIR-V types +/// where practical. +#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] +struct LocalImageType { + sampled_type: crate::ScalarKind, + dim: spirv::Dim, + depth: bool, + arrayed: bool, + multisampled: bool, + sampled: bool, + image_format: spirv::ImageFormat, +} + +impl LocalImageType { + /// Construct a `LocalImageType` from the fields of a `TypeInner::Image`. + fn from_inner(dim: crate::ImageDimension, arrayed: bool, class: crate::ImageClass) -> Self { + let dim = map_dim(dim); + match class { + crate::ImageClass::Sampled { kind, multi } => LocalImageType { + sampled_type: kind, + dim, + depth: false, + arrayed, + multisampled: multi, + sampled: true, + image_format: spirv::ImageFormat::Unknown, + }, + crate::ImageClass::Depth { multi } => LocalImageType { + sampled_type: crate::ScalarKind::Float, + dim, + depth: true, + arrayed, + multisampled: multi, + sampled: true, + image_format: spirv::ImageFormat::Unknown, + }, + crate::ImageClass::Storage { format, access: _ } => LocalImageType { + sampled_type: crate::ScalarKind::from(format), + dim, + depth: false, + arrayed, + multisampled: false, + sampled: false, + image_format: format.into(), + }, + } + } +} + /// A SPIR-V type constructed during code generation. /// /// In the process of writing SPIR-V, we need to synthesize various types for @@ -189,11 +253,7 @@ enum LocalType { base: Handle, class: spirv::StorageClass, }, - Image { - dim: crate::ImageDimension, - arrayed: bool, - class: crate::ImageClass, - }, + Image(LocalImageType), SampledImage { image_type_id: Word, }, @@ -262,11 +322,7 @@ fn make_local(inner: &crate::TypeInner) -> Option { dim, arrayed, class, - } => LocalType::Image { - dim, - arrayed, - class, - }, + } => LocalType::Image(LocalImageType::from_inner(dim, arrayed, class)), crate::TypeInner::Sampler { comparison: _ } => LocalType::Sampler, _ => return None, }) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 1f108c20b..9c0fe3201 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -13,15 +13,6 @@ use crate::{ use spirv::Word; use std::collections::hash_map::Entry; -fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { - match dim { - crate::ImageDimension::D1 => spirv::Dim::Dim1D, - crate::ImageDimension::D2 => spirv::Dim::Dim2D, - crate::ImageDimension::D3 => spirv::Dim::Dim3D, - crate::ImageDimension::Cube => spirv::Dim::DimCube, - } -} - impl Function { fn to_words(&self, sink: &mut impl Extend) { self.signature.as_ref().unwrap().to_words(sink); @@ -688,25 +679,24 @@ impl Writer { })); Instruction::type_pointer(id, class, type_id) } - LocalType::Image { - dim, - arrayed, - class, - } => { - let kind = match class { - crate::ImageClass::Sampled { kind, multi: _ } => kind, - crate::ImageClass::Depth { multi: _ } => crate::ScalarKind::Float, - crate::ImageClass::Storage { format, .. } => format.into(), - }; + LocalType::Image(image) => { let local_type = LocalType::Value { vector_size: None, - kind, + kind: image.sampled_type, width: 4, pointer_class: None, }; let type_id = self.get_type_id(LookupType::Local(local_type)); - let dim = map_dim(dim); - Instruction::type_image(id, type_id, dim, arrayed, class) + Instruction::type_image( + id, + type_id, + image.dim, + image.depth, + image.arrayed, + image.multisampled, + image.sampled, + image.image_format, + ) } LocalType::Sampler => Instruction::type_sampler(id), LocalType::SampledImage { image_type_id } => { From b226c5108a56606f4815ed0b119367224d90a6a5 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 28 Aug 2021 23:54:33 -0700 Subject: [PATCH 1305/2212] [spv-out] Add test for duplicate OpTypeImage instructions. --- tests/in/image.wgsl | 2 + tests/out/hlsl/image.hlsl | 1 + tests/out/msl/image.msl | 6 +- tests/out/spv/image.spvasm | 398 +++++++++++++++++++------------------ tests/out/wgsl/image.wgsl | 2 + 5 files changed, 210 insertions(+), 199 deletions(-) diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 308b3cdde..74378d4fe 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -8,6 +8,8 @@ var image_depth_multisampled_src: texture_depth_multisampled_2d; var image_storage_src: texture_storage_2d; [[group(0), binding(5)]] var image_array_src: texture_2d_array; +[[group(0), binding(6)]] +var image_dup_src: texture_storage_1d; // for #1307 [[group(0), binding(2)]] var image_dst: texture_storage_1d; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 65f49a1a6..902418a04 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -4,6 +4,7 @@ Texture2DMS image_multisampled_src : register(t3); Texture2DMS image_depth_multisampled_src : register(t4); RWTexture2D image_storage_src : register(u1); Texture2DArray image_array_src : register(t5); +RWTexture1D image_dup_src : register(u6); RWTexture1D image_dst : register(u2); Texture1D image_1d : register(t0); Texture2D image_2d : register(t1); diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 2fbe17aa8..a9379f897 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -2,7 +2,7 @@ #include #include -constant metal::int2 const_type7_ = {3, 1}; +constant metal::int2 const_type8_ = {3, 1}; struct main1Input { }; @@ -72,9 +72,9 @@ fragment sampleOutput sample( ) { metal::float2 tc = metal::float2(0.5); metal::float4 s2d = image_2d.sample(sampler_reg, tc); - metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type7_); + metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type8_); metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); - metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type7_); + metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type8_); return sampleOutput { ((s2d + s2d_offset) + s2d_level) + s2d_level_offset }; } diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index f2b104fc4..e0617cfe4 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 213 +; Bound: 215 OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D @@ -9,35 +9,36 @@ OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %67 "main" %64 -OpEntryPoint Vertex %113 "queries" %111 -OpEntryPoint Fragment %180 "sample" %179 -OpEntryPoint Fragment %201 "sample_comparison" %199 -OpExecutionMode %67 LocalSize 16 1 1 -OpExecutionMode %180 OriginUpperLeft -OpExecutionMode %201 OriginUpperLeft +OpEntryPoint GLCompute %69 "main" %66 +OpEntryPoint Vertex %115 "queries" %113 +OpEntryPoint Fragment %182 "sample" %181 +OpEntryPoint Fragment %203 "sample_comparison" %201 +OpExecutionMode %69 LocalSize 16 1 1 +OpExecutionMode %182 OriginUpperLeft +OpExecutionMode %203 OriginUpperLeft OpSource GLSL 450 OpName %31 "image_mipmapped_src" OpName %33 "image_multisampled_src" OpName %35 "image_depth_multisampled_src" OpName %37 "image_storage_src" OpName %39 "image_array_src" -OpName %41 "image_dst" -OpName %43 "image_1d" -OpName %45 "image_2d" -OpName %47 "image_2d_array" -OpName %49 "image_cube" -OpName %51 "image_cube_array" -OpName %53 "image_3d" -OpName %55 "image_aa" -OpName %57 "sampler_reg" -OpName %59 "sampler_cmp" -OpName %61 "image_2d_depth" -OpName %64 "local_id" -OpName %67 "main" -OpName %113 "queries" -OpName %180 "sample" -OpName %201 "sample_comparison" +OpName %41 "image_dup_src" +OpName %43 "image_dst" +OpName %45 "image_1d" +OpName %47 "image_2d" +OpName %49 "image_2d_array" +OpName %51 "image_cube" +OpName %53 "image_cube_array" +OpName %55 "image_3d" +OpName %57 "image_aa" +OpName %59 "sampler_reg" +OpName %61 "sampler_cmp" +OpName %63 "image_2d_depth" +OpName %66 "local_id" +OpName %69 "main" +OpName %115 "queries" +OpName %182 "sample" +OpName %203 "sample_comparison" OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 0 OpDecorate %33 DescriptorSet 0 @@ -49,33 +50,36 @@ OpDecorate %37 DescriptorSet 0 OpDecorate %37 Binding 1 OpDecorate %39 DescriptorSet 0 OpDecorate %39 Binding 5 -OpDecorate %41 NonReadable +OpDecorate %41 NonWritable OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 2 +OpDecorate %41 Binding 6 +OpDecorate %43 NonReadable OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 0 +OpDecorate %43 Binding 2 OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 1 +OpDecorate %45 Binding 0 OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 2 +OpDecorate %47 Binding 1 OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 3 +OpDecorate %49 Binding 2 OpDecorate %51 DescriptorSet 0 -OpDecorate %51 Binding 4 +OpDecorate %51 Binding 3 OpDecorate %53 DescriptorSet 0 -OpDecorate %53 Binding 5 +OpDecorate %53 Binding 4 OpDecorate %55 DescriptorSet 0 -OpDecorate %55 Binding 6 -OpDecorate %57 DescriptorSet 1 -OpDecorate %57 Binding 0 +OpDecorate %55 Binding 5 +OpDecorate %57 DescriptorSet 0 +OpDecorate %57 Binding 6 OpDecorate %59 DescriptorSet 1 -OpDecorate %59 Binding 1 +OpDecorate %59 Binding 0 OpDecorate %61 DescriptorSet 1 -OpDecorate %61 Binding 2 -OpDecorate %64 BuiltIn LocalInvocationId -OpDecorate %111 BuiltIn Position -OpDecorate %179 Location 0 -OpDecorate %199 Location 0 +OpDecorate %61 Binding 1 +OpDecorate %63 DescriptorSet 1 +OpDecorate %63 Binding 2 +OpDecorate %66 BuiltIn LocalInvocationId +OpDecorate %113 BuiltIn Position +OpDecorate %181 Location 0 +OpDecorate %201 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -117,189 +121,191 @@ OpDecorate %199 Location 0 %39 = OpVariable %40 UniformConstant %42 = OpTypePointer UniformConstant %17 %41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %20 +%44 = OpTypePointer UniformConstant %17 %43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %21 +%46 = OpTypePointer UniformConstant %20 %45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %22 +%48 = OpTypePointer UniformConstant %21 %47 = OpVariable %48 UniformConstant -%50 = OpTypePointer UniformConstant %23 +%50 = OpTypePointer UniformConstant %22 %49 = OpVariable %50 UniformConstant -%52 = OpTypePointer UniformConstant %24 +%52 = OpTypePointer UniformConstant %23 %51 = OpVariable %52 UniformConstant -%54 = OpTypePointer UniformConstant %25 +%54 = OpTypePointer UniformConstant %24 %53 = OpVariable %54 UniformConstant -%56 = OpTypePointer UniformConstant %26 +%56 = OpTypePointer UniformConstant %25 %55 = OpVariable %56 UniformConstant -%58 = OpTypePointer UniformConstant %28 +%58 = OpTypePointer UniformConstant %26 %57 = OpVariable %58 UniformConstant %60 = OpTypePointer UniformConstant %28 %59 = OpVariable %60 UniformConstant -%62 = OpTypePointer UniformConstant %29 +%62 = OpTypePointer UniformConstant %28 %61 = OpVariable %62 UniformConstant -%65 = OpTypePointer Input %18 -%64 = OpVariable %65 Input -%68 = OpTypeFunction %2 -%77 = OpTypeVector %12 2 -%85 = OpTypeVector %12 4 -%100 = OpTypeVector %4 3 -%112 = OpTypePointer Output %27 -%111 = OpVariable %112 Output -%122 = OpConstant %12 0 -%179 = OpVariable %112 Output -%184 = OpTypeVector %8 2 -%186 = OpTypeSampledImage %21 -%200 = OpTypePointer Output %8 -%199 = OpVariable %200 Output -%206 = OpTypeSampledImage %29 -%211 = OpConstant %8 0.0 -%67 = OpFunction %2 None %68 -%63 = OpLabel -%66 = OpLoad %18 %64 -%69 = OpLoad %11 %31 -%70 = OpLoad %13 %33 -%71 = OpLoad %14 %35 -%72 = OpLoad %15 %37 -%73 = OpLoad %16 %39 -%74 = OpLoad %17 %41 -OpBranch %75 -%75 = OpLabel -%76 = OpImageQuerySize %19 %72 -%78 = OpVectorShuffle %77 %66 %66 0 1 -%79 = OpBitcast %19 %78 -%80 = OpIMul %19 %76 %79 -%81 = OpCompositeConstruct %19 %3 %5 -%82 = OpSMod %19 %80 %81 -%83 = OpCompositeExtract %12 %66 2 -%84 = OpBitcast %4 %83 -%86 = OpImageFetch %85 %69 %82 Lod %84 -%87 = OpCompositeExtract %12 %66 2 -%88 = OpBitcast %4 %87 -%89 = OpImageFetch %85 %70 %82 Sample %88 -%90 = OpCompositeExtract %12 %66 2 -%91 = OpBitcast %4 %90 -%92 = OpImageFetch %27 %71 %82 Sample %91 -%93 = OpCompositeExtract %8 %92 0 -%94 = OpImageRead %85 %72 %82 -%95 = OpCompositeExtract %12 %66 2 -%96 = OpBitcast %4 %95 -%97 = OpCompositeExtract %12 %66 2 +%64 = OpTypePointer UniformConstant %29 +%63 = OpVariable %64 UniformConstant +%67 = OpTypePointer Input %18 +%66 = OpVariable %67 Input +%70 = OpTypeFunction %2 +%79 = OpTypeVector %12 2 +%87 = OpTypeVector %12 4 +%102 = OpTypeVector %4 3 +%114 = OpTypePointer Output %27 +%113 = OpVariable %114 Output +%124 = OpConstant %12 0 +%181 = OpVariable %114 Output +%186 = OpTypeVector %8 2 +%188 = OpTypeSampledImage %21 +%202 = OpTypePointer Output %8 +%201 = OpVariable %202 Output +%208 = OpTypeSampledImage %29 +%213 = OpConstant %8 0.0 +%69 = OpFunction %2 None %70 +%65 = OpLabel +%68 = OpLoad %18 %66 +%71 = OpLoad %11 %31 +%72 = OpLoad %13 %33 +%73 = OpLoad %14 %35 +%74 = OpLoad %15 %37 +%75 = OpLoad %16 %39 +%76 = OpLoad %17 %43 +OpBranch %77 +%77 = OpLabel +%78 = OpImageQuerySize %19 %74 +%80 = OpVectorShuffle %79 %68 %68 0 1 +%81 = OpBitcast %19 %80 +%82 = OpIMul %19 %78 %81 +%83 = OpCompositeConstruct %19 %3 %5 +%84 = OpSMod %19 %82 %83 +%85 = OpCompositeExtract %12 %68 2 +%86 = OpBitcast %4 %85 +%88 = OpImageFetch %87 %71 %84 Lod %86 +%89 = OpCompositeExtract %12 %68 2 +%90 = OpBitcast %4 %89 +%91 = OpImageFetch %87 %72 %84 Sample %90 +%92 = OpCompositeExtract %12 %68 2 +%93 = OpBitcast %4 %92 +%94 = OpImageFetch %27 %73 %84 Sample %93 +%95 = OpCompositeExtract %8 %94 0 +%96 = OpImageRead %87 %74 %84 +%97 = OpCompositeExtract %12 %68 2 %98 = OpBitcast %4 %97 -%99 = OpIAdd %4 %98 %6 -%101 = OpCompositeConstruct %100 %82 %96 -%102 = OpImageFetch %85 %73 %101 Lod %99 -%103 = OpCompositeExtract %4 %82 0 -%104 = OpIAdd %85 %86 %89 -%105 = OpConvertFToU %12 %93 -%106 = OpCompositeConstruct %85 %105 %105 %105 %105 -%107 = OpIAdd %85 %104 %106 -%108 = OpIAdd %85 %107 %94 -%109 = OpIAdd %85 %108 %102 -OpImageWrite %74 %103 %109 +%99 = OpCompositeExtract %12 %68 2 +%100 = OpBitcast %4 %99 +%101 = OpIAdd %4 %100 %6 +%103 = OpCompositeConstruct %102 %84 %98 +%104 = OpImageFetch %87 %75 %103 Lod %101 +%105 = OpCompositeExtract %4 %84 0 +%106 = OpIAdd %87 %88 %91 +%107 = OpConvertFToU %12 %95 +%108 = OpCompositeConstruct %87 %107 %107 %107 %107 +%109 = OpIAdd %87 %106 %108 +%110 = OpIAdd %87 %109 %96 +%111 = OpIAdd %87 %110 %104 +OpImageWrite %76 %105 %111 OpReturn OpFunctionEnd -%113 = OpFunction %2 None %68 -%110 = OpLabel -%114 = OpLoad %20 %43 -%115 = OpLoad %21 %45 -%116 = OpLoad %22 %47 -%117 = OpLoad %23 %49 -%118 = OpLoad %24 %51 -%119 = OpLoad %25 %53 -%120 = OpLoad %26 %55 -OpBranch %121 -%121 = OpLabel -%123 = OpImageQuerySizeLod %4 %114 %122 -%124 = OpImageQuerySizeLod %19 %115 %122 -%125 = OpImageQueryLevels %4 %115 -%126 = OpImageQuerySizeLod %19 %115 %6 -%127 = OpImageQuerySizeLod %100 %116 %122 -%128 = OpVectorShuffle %19 %127 %127 0 1 -%129 = OpImageQueryLevels %4 %116 -%130 = OpImageQuerySizeLod %100 %116 %6 -%131 = OpVectorShuffle %19 %130 %130 0 1 -%132 = OpImageQuerySizeLod %100 %116 %122 -%133 = OpCompositeExtract %4 %132 2 -%134 = OpImageQuerySizeLod %19 %117 %122 -%135 = OpImageQueryLevels %4 %117 -%136 = OpImageQuerySizeLod %19 %117 %6 -%137 = OpImageQuerySizeLod %100 %118 %122 -%138 = OpVectorShuffle %19 %137 %137 0 0 -%139 = OpImageQueryLevels %4 %118 -%140 = OpImageQuerySizeLod %100 %118 %6 -%141 = OpVectorShuffle %19 %140 %140 0 0 -%142 = OpImageQuerySizeLod %100 %118 %122 -%143 = OpCompositeExtract %4 %142 2 -%144 = OpImageQuerySizeLod %100 %119 %122 -%145 = OpImageQueryLevels %4 %119 -%146 = OpImageQuerySizeLod %100 %119 %6 -%147 = OpImageQuerySamples %4 %120 -%148 = OpCompositeExtract %4 %124 1 -%149 = OpIAdd %4 %123 %148 +%115 = OpFunction %2 None %70 +%112 = OpLabel +%116 = OpLoad %20 %45 +%117 = OpLoad %21 %47 +%118 = OpLoad %22 %49 +%119 = OpLoad %23 %51 +%120 = OpLoad %24 %53 +%121 = OpLoad %25 %55 +%122 = OpLoad %26 %57 +OpBranch %123 +%123 = OpLabel +%125 = OpImageQuerySizeLod %4 %116 %124 +%126 = OpImageQuerySizeLod %19 %117 %124 +%127 = OpImageQueryLevels %4 %117 +%128 = OpImageQuerySizeLod %19 %117 %6 +%129 = OpImageQuerySizeLod %102 %118 %124 +%130 = OpVectorShuffle %19 %129 %129 0 1 +%131 = OpImageQueryLevels %4 %118 +%132 = OpImageQuerySizeLod %102 %118 %6 +%133 = OpVectorShuffle %19 %132 %132 0 1 +%134 = OpImageQuerySizeLod %102 %118 %124 +%135 = OpCompositeExtract %4 %134 2 +%136 = OpImageQuerySizeLod %19 %119 %124 +%137 = OpImageQueryLevels %4 %119 +%138 = OpImageQuerySizeLod %19 %119 %6 +%139 = OpImageQuerySizeLod %102 %120 %124 +%140 = OpVectorShuffle %19 %139 %139 0 0 +%141 = OpImageQueryLevels %4 %120 +%142 = OpImageQuerySizeLod %102 %120 %6 +%143 = OpVectorShuffle %19 %142 %142 0 0 +%144 = OpImageQuerySizeLod %102 %120 %124 +%145 = OpCompositeExtract %4 %144 2 +%146 = OpImageQuerySizeLod %102 %121 %124 +%147 = OpImageQueryLevels %4 %121 +%148 = OpImageQuerySizeLod %102 %121 %6 +%149 = OpImageQuerySamples %4 %122 %150 = OpCompositeExtract %4 %126 1 -%151 = OpIAdd %4 %149 %150 +%151 = OpIAdd %4 %125 %150 %152 = OpCompositeExtract %4 %128 1 %153 = OpIAdd %4 %151 %152 -%154 = OpCompositeExtract %4 %131 1 +%154 = OpCompositeExtract %4 %130 1 %155 = OpIAdd %4 %153 %154 -%156 = OpIAdd %4 %155 %133 -%157 = OpCompositeExtract %4 %134 1 -%158 = OpIAdd %4 %156 %157 +%156 = OpCompositeExtract %4 %133 1 +%157 = OpIAdd %4 %155 %156 +%158 = OpIAdd %4 %157 %135 %159 = OpCompositeExtract %4 %136 1 %160 = OpIAdd %4 %158 %159 %161 = OpCompositeExtract %4 %138 1 %162 = OpIAdd %4 %160 %161 -%163 = OpCompositeExtract %4 %141 1 +%163 = OpCompositeExtract %4 %140 1 %164 = OpIAdd %4 %162 %163 -%165 = OpIAdd %4 %164 %143 -%166 = OpCompositeExtract %4 %144 2 -%167 = OpIAdd %4 %165 %166 +%165 = OpCompositeExtract %4 %143 1 +%166 = OpIAdd %4 %164 %165 +%167 = OpIAdd %4 %166 %145 %168 = OpCompositeExtract %4 %146 2 %169 = OpIAdd %4 %167 %168 -%170 = OpIAdd %4 %169 %147 -%171 = OpIAdd %4 %170 %125 -%172 = OpIAdd %4 %171 %129 -%173 = OpIAdd %4 %172 %145 -%174 = OpIAdd %4 %173 %135 -%175 = OpIAdd %4 %174 %139 -%176 = OpConvertSToF %8 %175 -%177 = OpCompositeConstruct %27 %176 %176 %176 %176 -OpStore %111 %177 +%170 = OpCompositeExtract %4 %148 2 +%171 = OpIAdd %4 %169 %170 +%172 = OpIAdd %4 %171 %149 +%173 = OpIAdd %4 %172 %127 +%174 = OpIAdd %4 %173 %131 +%175 = OpIAdd %4 %174 %147 +%176 = OpIAdd %4 %175 %137 +%177 = OpIAdd %4 %176 %141 +%178 = OpConvertSToF %8 %177 +%179 = OpCompositeConstruct %27 %178 %178 %178 %178 +OpStore %113 %179 OpReturn OpFunctionEnd -%180 = OpFunction %2 None %68 -%178 = OpLabel -%181 = OpLoad %21 %45 -%182 = OpLoad %28 %57 -OpBranch %183 -%183 = OpLabel -%185 = OpCompositeConstruct %184 %7 %7 -%187 = OpSampledImage %186 %181 %182 -%188 = OpImageSampleImplicitLod %27 %187 %185 -%189 = OpSampledImage %186 %181 %182 -%190 = OpImageSampleImplicitLod %27 %189 %185 ConstOffset %30 -%191 = OpSampledImage %186 %181 %182 -%192 = OpImageSampleExplicitLod %27 %191 %185 Lod %9 -%193 = OpSampledImage %186 %181 %182 -%194 = OpImageSampleExplicitLod %27 %193 %185 Lod|ConstOffset %9 %30 -%195 = OpFAdd %27 %188 %190 -%196 = OpFAdd %27 %195 %192 -%197 = OpFAdd %27 %196 %194 -OpStore %179 %197 +%182 = OpFunction %2 None %70 +%180 = OpLabel +%183 = OpLoad %21 %47 +%184 = OpLoad %28 %59 +OpBranch %185 +%185 = OpLabel +%187 = OpCompositeConstruct %186 %7 %7 +%189 = OpSampledImage %188 %183 %184 +%190 = OpImageSampleImplicitLod %27 %189 %187 +%191 = OpSampledImage %188 %183 %184 +%192 = OpImageSampleImplicitLod %27 %191 %187 ConstOffset %30 +%193 = OpSampledImage %188 %183 %184 +%194 = OpImageSampleExplicitLod %27 %193 %187 Lod %9 +%195 = OpSampledImage %188 %183 %184 +%196 = OpImageSampleExplicitLod %27 %195 %187 Lod|ConstOffset %9 %30 +%197 = OpFAdd %27 %190 %192 +%198 = OpFAdd %27 %197 %194 +%199 = OpFAdd %27 %198 %196 +OpStore %181 %199 OpReturn OpFunctionEnd -%201 = OpFunction %2 None %68 -%198 = OpLabel -%202 = OpLoad %28 %59 -%203 = OpLoad %29 %61 -OpBranch %204 -%204 = OpLabel -%205 = OpCompositeConstruct %184 %7 %7 -%207 = OpSampledImage %206 %203 %202 -%208 = OpImageSampleDrefImplicitLod %8 %207 %205 %7 -%209 = OpSampledImage %206 %203 %202 -%210 = OpImageSampleDrefExplicitLod %8 %209 %205 %7 Lod %211 -%212 = OpFAdd %8 %208 %210 -OpStore %199 %212 +%203 = OpFunction %2 None %70 +%200 = OpLabel +%204 = OpLoad %28 %61 +%205 = OpLoad %29 %63 +OpBranch %206 +%206 = OpLabel +%207 = OpCompositeConstruct %186 %7 %7 +%209 = OpSampledImage %208 %205 %204 +%210 = OpImageSampleDrefImplicitLod %8 %209 %207 %7 +%211 = OpSampledImage %208 %205 %204 +%212 = OpImageSampleDrefExplicitLod %8 %211 %207 %7 Lod %213 +%214 = OpFAdd %8 %210 %212 +OpStore %201 %214 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 8fc336f7d..64e3cdae8 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -8,6 +8,8 @@ var image_depth_multisampled_src: texture_depth_multisampled_2d; var image_storage_src: texture_storage_2d; [[group(0), binding(5)]] var image_array_src: texture_2d_array; +[[group(0), binding(6)]] +var image_dup_src: texture_storage_1d; [[group(0), binding(2)]] var image_dst: texture_storage_1d; [[group(0), binding(0)]] From b35e40ec596e6dc192f745c402c7355cba4d6122 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 30 Aug 2021 10:10:15 -0700 Subject: [PATCH 1306/2212] [spv-out] Use bit flags in LocalImageType, instead of bools. --- src/back/spv/instructions.rs | 17 ++++++++-------- src/back/spv/mod.rs | 38 +++++++++++++++++++++--------------- src/back/spv/writer.rs | 11 +---------- 3 files changed, 32 insertions(+), 34 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index f881294bc..a05e92ae2 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -224,20 +224,21 @@ impl super::Instruction { id: Word, sampled_type_id: Word, dim: spirv::Dim, - depth: bool, - arrayed: bool, - multisampled: bool, - sampled: bool, + flags: super::ImageTypeFlags, image_format: spirv::ImageFormat, ) -> Self { let mut instruction = Self::new(Op::TypeImage); instruction.set_result(id); instruction.add_operand(sampled_type_id); instruction.add_operand(dim as u32); - instruction.add_operand(depth as u32); - instruction.add_operand(arrayed as u32); - instruction.add_operand(multisampled as u32); - instruction.add_operand(if sampled { 1 } else { 2 }); + instruction.add_operand(flags.contains(super::ImageTypeFlags::DEPTH) as u32); + instruction.add_operand(flags.contains(super::ImageTypeFlags::ARRAYED) as u32); + instruction.add_operand(flags.contains(super::ImageTypeFlags::MULTISAMPLED) as u32); + instruction.add_operand(if flags.contains(super::ImageTypeFlags::SAMPLED) { + 1 + } else { + 2 + }); instruction.add_operand(image_format as u32); instruction } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 6c272db28..74eb2a489 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -174,43 +174,49 @@ fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { struct LocalImageType { sampled_type: crate::ScalarKind, dim: spirv::Dim, - depth: bool, - arrayed: bool, - multisampled: bool, - sampled: bool, + flags: ImageTypeFlags, image_format: spirv::ImageFormat, } +bitflags::bitflags! { + /// Flags corresponding to the boolean(-ish) parameters to OpTypeImage. + pub struct ImageTypeFlags: u8 { + const DEPTH = 0x1; + const ARRAYED = 0x2; + const MULTISAMPLED = 0x4; + const SAMPLED = 0x8; + } +} + impl LocalImageType { /// Construct a `LocalImageType` from the fields of a `TypeInner::Image`. fn from_inner(dim: crate::ImageDimension, arrayed: bool, class: crate::ImageClass) -> Self { + let make_flags = |multi: bool, other: ImageTypeFlags| -> ImageTypeFlags { + let mut flags = other; + flags.set(ImageTypeFlags::ARRAYED, arrayed); + flags.set(ImageTypeFlags::MULTISAMPLED, multi); + flags + }; + let dim = map_dim(dim); + match class { crate::ImageClass::Sampled { kind, multi } => LocalImageType { sampled_type: kind, dim, - depth: false, - arrayed, - multisampled: multi, - sampled: true, + flags: make_flags(multi, ImageTypeFlags::SAMPLED), image_format: spirv::ImageFormat::Unknown, }, crate::ImageClass::Depth { multi } => LocalImageType { sampled_type: crate::ScalarKind::Float, dim, - depth: true, - arrayed, - multisampled: multi, - sampled: true, + flags: make_flags(multi, ImageTypeFlags::DEPTH | ImageTypeFlags::SAMPLED), image_format: spirv::ImageFormat::Unknown, }, crate::ImageClass::Storage { format, access: _ } => LocalImageType { sampled_type: crate::ScalarKind::from(format), dim, - depth: false, - arrayed, - multisampled: false, - sampled: false, + flags: make_flags(false, ImageTypeFlags::empty()), image_format: format.into(), }, } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 9c0fe3201..018ecf640 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -687,16 +687,7 @@ impl Writer { pointer_class: None, }; let type_id = self.get_type_id(LookupType::Local(local_type)); - Instruction::type_image( - id, - type_id, - image.dim, - image.depth, - image.arrayed, - image.multisampled, - image.sampled, - image.image_format, - ) + Instruction::type_image(id, type_id, image.dim, image.flags, image.image_format) } LocalType::Sampler => Instruction::type_sampler(id), LocalType::SampledImage { image_type_id } => { From 995a7752a99a2f00653280850301bd3ed345fc3d Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 30 Aug 2021 10:14:28 -0700 Subject: [PATCH 1307/2212] [spv-out] Replace `map_dim` with a `From` implementation. --- src/back/spv/instructions.rs | 12 ++++++++++++ src/back/spv/mod.rs | 11 +---------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index a05e92ae2..ac738dfa6 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -919,3 +919,15 @@ impl From for spirv::ImageFormat { } } } + +impl From for spirv::Dim { + fn from(dim: crate::ImageDimension) -> Self { + use crate::ImageDimension as Id; + match dim { + Id::D1 => Self::Dim1D, + Id::D2 => Self::Dim2D, + Id::D3 => Self::Dim3D, + Id::Cube => Self::DimCube, + } + } +} diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 74eb2a489..b06db365c 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -153,15 +153,6 @@ impl Function { } } -fn map_dim(dim: crate::ImageDimension) -> spirv::Dim { - match dim { - crate::ImageDimension::D1 => spirv::Dim::Dim1D, - crate::ImageDimension::D2 => spirv::Dim::Dim2D, - crate::ImageDimension::D3 => spirv::Dim::Dim3D, - crate::ImageDimension::Cube => spirv::Dim::DimCube, - } -} - /// Characteristics of a SPIR-V `OpTypeImage` type. /// /// SPIR-V requires non-composite types to be unique, including images. Since we @@ -198,7 +189,7 @@ impl LocalImageType { flags }; - let dim = map_dim(dim); + let dim = spirv::Dim::from(dim); match class { crate::ImageClass::Sampled { kind, multi } => LocalImageType { From bd411c28c2247a27bbca10347db0094d2e317b44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 31 Aug 2021 17:15:30 +0100 Subject: [PATCH 1308/2212] [glsl-in] Allow code after terminator statements (#1308) * [glsl-in] Allow code after terminator statements * [glsl-in] Track finished state in the context * [glsl-in] Cull statements after terminators --- src/front/glsl/functions.rs | 3 +- src/front/glsl/parser/functions.rs | 80 ++++++++++++++++++++++-------- 2 files changed, 60 insertions(+), 23 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 0b014aad3..b2a512509 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -643,6 +643,8 @@ impl Parser { .0; ctx.emit_flush(body); + ctx.emit_start(); + body.push( Statement::Store { pointer: target, @@ -650,7 +652,6 @@ impl Parser { }, meta.as_span(), ); - ctx.emit_start(); } Ok(result) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index b2db84080..a3a1ef37f 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -40,6 +40,7 @@ impl<'source> ParsingContext<'source> { parser: &mut Parser, ctx: &mut Context, body: &mut Block, + terminator: &mut Option, ) -> Result> { // TODO: This prevents snippets like the following from working // ```glsl @@ -62,11 +63,15 @@ impl<'source> ParsingContext<'source> { let meta_rest = match *value { TokenValue::Continue => { - body.push(Statement::Continue, self.bump(parser)?.meta.as_span()); + let meta = self.bump(parser)?.meta; + body.push(Statement::Continue, meta.as_span()); + terminator.get_or_insert(body.len()); self.expect(parser, TokenValue::Semicolon)?.meta } TokenValue::Break => { - body.push(Statement::Break, self.bump(parser)?.meta.as_span()); + let meta = self.bump(parser)?.meta; + body.push(Statement::Break, meta.as_span()); + terminator.get_or_insert(body.len()); self.expect(parser, TokenValue::Semicolon)?.meta } TokenValue::Return => { @@ -88,10 +93,15 @@ impl<'source> ParsingContext<'source> { ctx.emit_start(); body.push(Statement::Return { value }, meta.as_span()); + terminator.get_or_insert(body.len()); + meta } TokenValue::Discard => { - body.push(Statement::Kill, self.bump(parser)?.meta.as_span()); + let meta = self.bump(parser)?.meta; + body.push(Statement::Kill, meta.as_span()); + terminator.get_or_insert(body.len()); + self.expect(parser, TokenValue::Semicolon)?.meta } TokenValue::If => { @@ -112,13 +122,17 @@ impl<'source> ParsingContext<'source> { ctx.emit_start(); let mut accept = Block::new(); - if let Some(more_meta) = self.parse_statement(parser, ctx, &mut accept)? { + if let Some(more_meta) = + self.parse_statement(parser, ctx, &mut accept, &mut None)? + { meta = meta.union(&more_meta) } let mut reject = Block::new(); if self.bump_if(parser, TokenValue::Else).is_some() { - if let Some(more_meta) = self.parse_statement(parser, ctx, &mut reject)? { + if let Some(more_meta) = + self.parse_statement(parser, ctx, &mut reject, &mut None)? + { meta = meta.union(&more_meta); } } @@ -131,6 +145,7 @@ impl<'source> ParsingContext<'source> { }, meta.as_span(), ); + meta } TokenValue::Switch => { @@ -190,25 +205,32 @@ impl<'source> ParsingContext<'source> { let mut body = Block::new(); + let mut case_terminator = None; loop { match self.expect_peek(parser)?.value { TokenValue::Case | TokenValue::Default | TokenValue::RightBrace => break, _ => { - self.parse_statement(parser, ctx, &mut body)?; + self.parse_statement( + parser, + ctx, + &mut body, + &mut case_terminator, + )?; } } } let mut fall_through = true; - for (i, stmt) in body.iter().enumerate() { - if let Statement::Break = *stmt { + if let Some(mut idx) = case_terminator { + if let Statement::Break = body[idx - 1] { fall_through = false; - body.cull(i..); - break; + idx -= 1; } + + body.cull(idx..) } cases.push(SwitchCase { @@ -231,21 +253,20 @@ impl<'source> ParsingContext<'source> { }); } + let mut default_terminator = None; loop { match self.expect_peek(parser)?.value { TokenValue::Case | TokenValue::RightBrace => break, _ => { - self.parse_statement(parser, ctx, &mut default)?; + self.parse_statement( + parser, + ctx, + &mut default, + &mut default_terminator, + )?; } } } - - for (i, stmt) in default.iter().enumerate() { - if let Statement::Break = *stmt { - default.cull(i..); - break; - } - } } TokenValue::RightBrace => { end_meta = self.bump(parser)?.meta; @@ -269,6 +290,7 @@ impl<'source> ParsingContext<'source> { } let meta = start_meta.union(&end_meta); + body.push( Statement::Switch { selector, @@ -277,6 +299,7 @@ impl<'source> ParsingContext<'source> { }, meta.as_span(), ); + meta } TokenValue::While => { @@ -314,7 +337,9 @@ impl<'source> ParsingContext<'source> { let mut meta = meta.union(&expr_meta); - if let Some(body_meta) = self.parse_statement(parser, ctx, &mut loop_body)? { + if let Some(body_meta) = + self.parse_statement(parser, ctx, &mut loop_body, &mut None)? + { meta = meta.union(&body_meta); } @@ -325,13 +350,15 @@ impl<'source> ParsingContext<'source> { }, meta.as_span(), ); + meta } TokenValue::Do => { let start_meta = self.bump(parser)?.meta; let mut loop_body = Block::new(); - self.parse_statement(parser, ctx, &mut loop_body)?; + + self.parse_statement(parser, ctx, &mut loop_body, &mut None)?; let mut stmt = ctx.stmt_ctx(); @@ -372,6 +399,7 @@ impl<'source> ParsingContext<'source> { }, meta.as_span(), ); + meta } TokenValue::For => { @@ -464,7 +492,7 @@ impl<'source> ParsingContext<'source> { let mut meta = meta.union(&self.expect(parser, TokenValue::RightParen)?.meta); - if let Some(stmt_meta) = self.parse_statement(parser, ctx, &mut block)? { + if let Some(stmt_meta) = self.parse_statement(parser, ctx, &mut block, &mut None)? { meta = meta.union(&stmt_meta); } @@ -489,6 +517,7 @@ impl<'source> ParsingContext<'source> { let meta = self.parse_compound_statement(meta, parser, ctx, &mut block)?; ctx.remove_current_scope(); + body.push(Statement::Block(block), meta.as_span()); meta @@ -515,6 +544,7 @@ impl<'source> ParsingContext<'source> { ctx: &mut Context, body: &mut Block, ) -> Result { + let mut terminator = None; loop { if let Some(Token { meta: brace_meta, .. @@ -524,11 +554,17 @@ impl<'source> ParsingContext<'source> { break; } - if let Some(stmt_meta) = self.parse_statement(parser, ctx, body)? { + let stmt = self.parse_statement(parser, ctx, body, &mut terminator)?; + + if let Some(stmt_meta) = stmt { meta = meta.union(&stmt_meta); } } + if let Some(idx) = terminator { + body.cull(idx..) + } + Ok(meta) } From 2069ea698f4ff570c7d065b899f16a88725aca85 Mon Sep 17 00:00:00 2001 From: Hans Christian Schmitz Date: Tue, 31 Aug 2021 19:00:50 +0200 Subject: [PATCH 1309/2212] Implement fuzzing for the GLSL parser (#1301) * Implement fuzzing for the GLSL parser * Remove arbitrary dependency from naga Derive `Arbitrary` for proxy objects in `fuzz/fuzz_targets/glsl_parser.rs` instead. --- fuzz/Cargo.toml | 9 ++++++- fuzz/fuzz_targets/glsl_parser.rs | 46 ++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 fuzz/fuzz_targets/glsl_parser.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index a95afc0f4..ceb30ea55 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -9,11 +9,12 @@ edition = "2018" cargo-fuzz = true [dependencies] +arbitrary = { version = "1.0.2", features = ["derive"] } libfuzzer-sys = "0.4" [dependencies.naga] path = ".." -features = ["spv-in", "wgsl-in"] +features = ["spv-in", "wgsl-in", "glsl-in"] # Prevent this from interfering with workspaces [workspace] @@ -30,3 +31,9 @@ name = "wgsl_parser" path = "fuzz_targets/wgsl_parser.rs" test = false doc = false + +[[bin]] +name = "glsl_parser" +path = "fuzz_targets/glsl_parser.rs" +test = false +doc = false diff --git a/fuzz/fuzz_targets/glsl_parser.rs b/fuzz/fuzz_targets/glsl_parser.rs new file mode 100644 index 000000000..b600eb513 --- /dev/null +++ b/fuzz/fuzz_targets/glsl_parser.rs @@ -0,0 +1,46 @@ +#![no_main] +use arbitrary::Arbitrary; +use libfuzzer_sys::fuzz_target; +use naga::{ + front::glsl::{Options, Parser}, + FastHashMap, ShaderStage, +}; + +#[derive(Debug, Arbitrary)] +enum ShaderStageProxy { + Vertex, + Fragment, + Compute, +} + +impl From for ShaderStage { + fn from(proxy: ShaderStageProxy) -> Self { + match proxy { + ShaderStageProxy::Vertex => ShaderStage::Vertex, + ShaderStageProxy::Fragment => ShaderStage::Fragment, + ShaderStageProxy::Compute => ShaderStage::Compute, + } + } +} + +#[derive(Debug, Arbitrary)] +struct OptionsProxy { + pub stage: ShaderStageProxy, + pub defines: FastHashMap, +} + +impl From for Options { + fn from(proxy: OptionsProxy) -> Self { + Options { + stage: proxy.stage.into(), + defines: proxy.defines, + } + } +} + +fuzz_target!(|data: (OptionsProxy, String)| { + let (options, source) = data; + // Ensure the parser can handle potentially malformed strings without crashing. + let mut parser = Parser::default(); + let _result = parser.parse(&options.into(), &source); +}); From 8417f849b1ddcd076a6435572e99b07a2c83af07 Mon Sep 17 00:00:00 2001 From: Hans Christian Schmitz Date: Tue, 31 Aug 2021 23:48:28 +0200 Subject: [PATCH 1310/2212] Fix GLSL output for non-fallthrough switch cases (#1310) * Fix GLSL output for non-fallthrough switch cases Partially reverts 02c74b50021379092a9d4567fd11aeb0879c5405 and fixes #1309. * Fix indentation of control-flow WGSL code * Clean up glsl-out switch case fallthrough handling Only insert a break if needed and if a case is fallthrough, insert a comment indicating this. --- src/back/glsl/mod.rs | 15 +++ tests/in/control-flow.wgsl | 97 +++++++++++-------- tests/out/glsl/control-flow.main.Compute.glsl | 17 ++++ tests/out/hlsl/control-flow.hlsl | 24 +++++ tests/out/msl/control-flow.msl | 21 ++++ tests/out/spv/control-flow.spvasm | 26 ++++- tests/out/wgsl/control-flow.wgsl | 19 ++++ 7 files changed, 177 insertions(+), 42 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b3d268203..e8827e679 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1441,6 +1441,21 @@ impl<'a, W: Write> Writer<'a, W> { for sta in case.body.iter() { self.write_stmt(sta, ctx, indent + 2)?; } + + // Write fallthrough comment if the case is fallthrough, + // otherwise write a break, if the case is not already + // broken out of at the end of its body. + if case.fall_through { + writeln!(self.out, "{}/* fallthrough */", INDENT.repeat(indent + 2))?; + } else if !matches!( + case.body.last(), + Some(&Statement::Break) + | Some(&Statement::Continue) + | Some(&Statement::Return { .. }) + | Some(&Statement::Kill) + ) { + writeln!(self.out, "{}break;", INDENT.repeat(indent + 2))?; + } } // Only write the default block if the block isn't empty diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index 50e8b2229..679ad3d8a 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -1,59 +1,80 @@ [[stage(compute), workgroup_size(1)]] fn main([[builtin(global_invocation_id)]] global_id: vec3) { - //TODO: execution-only barrier? - storageBarrier(); - workgroupBarrier(); + //TODO: execution-only barrier? + storageBarrier(); + workgroupBarrier(); - var pos: i32; - // switch without cases + var pos: i32; + // switch without cases switch (1) { default: { - pos = 1; - } + pos = 1; + } } - switch (pos) { - case 1: { - pos = 0; - break; - } - case 2: { - pos = 1; - } - case 3: { - pos = 2; - fallthrough; - } - case 4: {} + // non-empty switch *not* in last-statement-in-function position + // (return statements might be inserted into the switch cases otherwise) + switch (pos) { + case 1: { + pos = 0; + break; + } + case 2: { + pos = 1; + } + case 3: { + pos = 2; + fallthrough; + } + case 4: {} default: { - pos = 3; - } + pos = 3; + } + } + + // non-empty switch in last-statement-in-function position + switch (pos) { + case 1: { + pos = 0; + break; + } + case 2: { + pos = 1; + } + case 3: { + pos = 2; + fallthrough; + } + case 4: {} + default: { + pos = 3; + } } } fn switch_default_break(i: i32) { - switch (i) { - default: { - break; + switch (i) { + default: { + break; + } } - } } fn switch_case_break() { - switch(0) { - case 0: { - break; + switch(0) { + case 0: { + break; + } } - } - return; + return; } fn loop_switch_continue(x: i32) { - loop { - switch (x) { - case 1: { - continue; - } - } - } + loop { + switch (x) { + case 1: { + continue; + } + } + } } diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index 2a42aa55c..e8b566b9d 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -42,6 +42,22 @@ void main() { } int _e4 = pos; switch(_e4) { + case 1: + pos = 0; + break; + case 2: + pos = 1; + break; + case 3: + pos = 2; + /* fallthrough */ + case 4: + break; + default: + pos = 3; + } + int _e9 = pos; + switch(_e9) { case 1: pos = 0; break; @@ -50,6 +66,7 @@ void main() { return; case 3: pos = 2; + /* fallthrough */ case 4: return; default: diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index 3dd0ab7a2..d425b0991 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -46,6 +46,30 @@ void main(uint3 global_id : SV_DispatchThreadID) } int _expr4 = pos; switch(_expr4) { + case 1: { + pos = 0; + break; + break; + } + case 2: { + pos = 1; + break; + } + case 3: { + /* fallthrough */ + { + pos = 2; + } + } + case 4: { + break; + } + default: { + pos = 3; + } + } + int _expr9 = pos; + switch(_expr9) { case 1: { pos = 0; break; diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index a2a80ac7b..52f990134 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -57,6 +57,27 @@ kernel void main1( } int _e4 = pos; switch(_e4) { + case 1: { + pos = 0; + break; + break; + } + case 2: { + pos = 1; + break; + } + case 3: { + pos = 2; + } + case 4: { + break; + } + default: { + pos = 3; + } + } + int _e9 = pos; + switch(_e9) { case 1: { pos = 0; break; diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index fc79a6c7b..e8f0e2cf1 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 56 +; Bound: 63 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -95,15 +95,33 @@ OpStore %35 %5 OpBranch %50 %53 = OpLabel OpStore %35 %3 -OpReturn +OpBranch %50 %54 = OpLabel OpStore %35 %6 OpBranch %55 %55 = OpLabel -OpReturn +OpBranch %50 %51 = OpLabel OpStore %35 %7 -OpReturn +OpBranch %50 %50 = OpLabel +%56 = OpLoad %4 %35 +OpSelectionMerge %57 None +OpSwitch %56 %58 1 %59 2 %60 3 %61 4 %62 +%59 = OpLabel +OpStore %35 %5 +OpBranch %57 +%60 = OpLabel +OpStore %35 %3 +OpReturn +%61 = OpLabel +OpStore %35 %6 +OpBranch %62 +%62 = OpLabel +OpReturn +%58 = OpLabel +OpStore %35 %7 +OpReturn +%57 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index 903ad9923..2859edd61 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -39,6 +39,25 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { } let _e4: i32 = pos; switch(_e4) { + case 1: { + pos = 0; + break; + } + case 2: { + pos = 1; + } + case 3: { + pos = 2; + fallthrough; + } + case 4: { + } + default: { + pos = 3; + } + } + let _e9: i32 = pos; + switch(_e9) { case 1: { pos = 0; break; From 8ef92227c161dfb1cdb6a553ea5e555c53592834 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 1 Sep 2021 13:34:33 -0700 Subject: [PATCH 1311/2212] Document the `bake_ref_count` hack. (#1315) --- src/back/mod.rs | 3 +++ src/lib.rs | 47 +++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/src/back/mod.rs b/src/back/mod.rs index 34cd45a87..5de7bce01 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -222,6 +222,9 @@ impl crate::Expression { /// /// Note: we have to cache any expressions that depend on the control flow, /// or otherwise they may be moved into a non-uniform contol flow, accidentally. + /// See the [module-level documentation][emit] for details. + /// + /// [emit]: index.html#expression-evaluation-time #[allow(dead_code)] fn bake_ref_count(&self) -> usize { match *self { diff --git a/src/lib.rs b/src/lib.rs index f67260456..076a57349 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,7 +53,7 @@ returns a value, a call statement designates a particular [`Expression::CallResu expression to represent its return value, for use by subsequent statements and expressions. -## `Expression` evaluation time and scope +## `Expression` evaluation time It is essential to know when an [`Expression`] should be evaluated, because its value may depend on previous [`Statement`]s' effects. But whereas the order of @@ -96,6 +96,38 @@ Naga's rules for when `Expression`s are evaluated are as follows: method returns `true` if the given expression is one of those variants that does *not* need to be covered by an `Emit` statement. +Now, strictly speaking, not all `Expression` variants actually care when they're +evaluated. For example, you can evaluate a [`BinaryOperator::Add`] expression +any time you like, as long as you give it the right operands. It's really only a +very small set of expressions that are affected by timing: + +- [`Load`], [`ImageSample`], and [`ImageLoad`] expressions are influenced by + stores to the variables or images they access, and must execute at the + proper time relative to them. + +- [`Derivative`] expressions are sensitive to control flow uniformity: they + must not be moved out of an area of uniform control flow into a non-uniform + area. + +- More generally, any expression that's used by more than one other expression + or statement should probably be evaluated only once, and then stored in a + variable to be cited at each point of use. + +Naga tries to help back ends handle all these cases correctly in a somewhat +circuitous way. The [`ModuleInfo`] structure returned by [`Validator::validate`] +provides a reference count for each expression in each function in the module. +Naturally, any expression with a reference count of two or more deserves to be +evaluated and stored in a temporary variable at the point that the `Emit` +statement covering it is executed. But if we selectively lower the reference +count threshold to _one_ for the sensitive expression types listed above, so +that we _always_ generate a temporary variable and save their value, then the +same code that manages multiply referenced expressions will take care of +introducing temporaries for time-sensitive expressions as well. The +`Expression::bake_ref_count` method (private to the back ends) is meant to help +with this. + +## `Expression` scope + Each `Expression` has a *scope*, which is the region of the function within which it can be used by `Statement`s and other `Expression`s. It is a validation error to use an `Expression` outside its scope. @@ -119,15 +151,22 @@ nested `Block` is not available in the `Block`'s parents. Such a value would need to be stored in a local variable to be carried upwards in the statement tree. -[`Call`]: Statement::Call [`Constant`]: Expression::Constant -[`Emit`]: Statement::Emit +[`Derivative`]: Expression::Derivative [`FunctionArgument`]: Expression::FunctionArgument [`GlobalVariable`]: Expression::GlobalVariable +[`ImageLoad`]: Expression::ImageLoad +[`ImageSample`]: Expression::ImageSample [`Load`]: Expression::Load [`LocalVariable`]: Expression::LocalVariable + +[`Call`]: Statement::Call +[`Emit`]: Statement::Emit [`Store`]: Statement::Store +[`Validator::validate`]: valid::Validator::validate +[`ModuleInfo`]: valid::ModuleInfo + !*/ // TODO: use `strip_prefix` instead when Rust 1.45 <= MSRV @@ -1225,7 +1264,7 @@ pub enum Statement { /// /// See the [module-level documentation][emit] for details. /// - /// [emit]: index.html#expression-evaluation-time-and-scope + /// [emit]: index.html#expression-evaluation-time Emit(Range), /// A block containing more statements, to be executed sequentially. Block(Block), From dad26c543c5835707ae6d852d5c661e0927cffa5 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 3 Sep 2021 00:45:56 +0300 Subject: [PATCH 1312/2212] [wgsl-out] Reduce heap allocation --- src/back/wgsl/writer.rs | 138 +++++++++++++++++++++++----------------- 1 file changed, 78 insertions(+), 60 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 123c12e7b..1b0e9a18f 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -292,71 +292,88 @@ impl Writer { /// # Notes /// Adds an extra space if required fn write_attributes(&mut self, attributes: &[Attribute], extra_space: bool) -> BackendResult { - let mut attributes_str = String::new(); - for (index, attribute) in attributes.iter().enumerate() { - let attribute_str = match *attribute { - Attribute::Block => String::from("block"), - Attribute::Location(id) => format!("location({})", id), + write!(self.out, "[[")?; + + let mut need_last_comma = true; + if let Some(last_attrib) = attributes.last() { + // We duplicate the logic a little, but this will help to avoid extra heap allocation + match *last_attrib { Attribute::BuiltIn(builtin_attrib) => { - let builtin_str = builtin_str(builtin_attrib); - if let Some(builtin) = builtin_str { - format!("builtin({})", builtin) + need_last_comma = builtin_str(builtin_attrib).is_some(); + } + Attribute::Interpolate(interpolation, sampling) => { + need_last_comma = (sampling.is_some() + && sampling != Some(crate::Sampling::Center)) + || (interpolation.is_some() + && interpolation != Some(crate::Interpolation::Perspective)) + } + _ => {} + } + } + + for (index, attribute) in attributes.iter().enumerate() { + match *attribute { + Attribute::Block => write!(self.out, "block")?, + Attribute::Location(id) => write!(self.out, "location({})", id)?, + Attribute::BuiltIn(builtin_attrib) => { + if let Some(builtin) = builtin_str(builtin_attrib) { + write!(self.out, "builtin({})", builtin)?; } else { log::warn!("Unsupported builtin attribute: {:?}", builtin_attrib); - String::from("") } } - Attribute::Stage(shader_stage) => match shader_stage { - ShaderStage::Vertex => String::from("stage(vertex)"), - ShaderStage::Fragment => String::from("stage(fragment)"), - ShaderStage::Compute => String::from("stage(compute)"), - }, - Attribute::Stride(stride) => format!("stride({})", stride), - Attribute::WorkGroupSize(size) => { - format!("workgroup_size({}, {}, {})", size[0], size[1], size[2]) + Attribute::Stage(shader_stage) => { + let stage_str = match shader_stage { + ShaderStage::Vertex => "stage(vertex)", + ShaderStage::Fragment => "stage(fragment)", + ShaderStage::Compute => "stage(compute)", + }; + write!(self.out, "{}", stage_str)?; } - Attribute::Binding(id) => format!("binding({})", id), - Attribute::Group(id) => format!("group({})", id), + Attribute::Stride(stride) => write!(self.out, "stride({})", stride)?, + Attribute::WorkGroupSize(size) => { + write!( + self.out, + "workgroup_size({}, {}, {})", + size[0], size[1], size[2] + )?; + } + Attribute::Binding(id) => write!(self.out, "binding({})", id)?, + Attribute::Group(id) => write!(self.out, "group({})", id)?, Attribute::Interpolate(interpolation, sampling) => { if sampling.is_some() && sampling != Some(crate::Sampling::Center) { - format!( + write!( + self.out, "interpolate({}, {})", interpolation_str( interpolation.unwrap_or(crate::Interpolation::Perspective) ), sampling_str(sampling.unwrap_or(crate::Sampling::Center)) - ) + )?; } else if interpolation.is_some() && interpolation != Some(crate::Interpolation::Perspective) { - format!( + write!( + self.out, "interpolate({})", interpolation_str( interpolation.unwrap_or(crate::Interpolation::Perspective) ) - ) - } else { - String::from("") + )?; } } }; - if !attribute_str.is_empty() { - // Add a separator between args - let separator = if index < attributes.len() - 1 { - ", " - } else { - "" - }; - attributes_str = format!("{}{}{}", attributes_str, attribute_str, separator); + + // Only write a comma if isn't the last element + if index + 1 != attributes.len() && need_last_comma { + // The leading space is for readability only + write!(self.out, ", ")?; } } - if !attributes_str.is_empty() { - //TODO: looks ugly - if attributes_str.ends_with(", ") { - attributes_str = attributes_str[0..attributes_str.len() - 2].to_string(); - } - let extra_space_str = if extra_space { " " } else { "" }; - write!(self.out, "[[{}]]{}", attributes_str, extra_space_str)?; + + write!(self.out, "]]")?; + if extra_space { + write!(self.out, " ")?; } Ok(()) @@ -445,12 +462,9 @@ impl Writer { match *inner { TypeInner::Vector { size, kind, .. } => write!( self.out, - "{}", - format!( - "vec{}<{}>", - back::vector_size_str(size), - scalar_kind_str(kind), - ) + "vec{}<{}>", + back::vector_size_str(size), + scalar_kind_str(kind), )?, TypeInner::Sampler { comparison: false } => { write!(self.out, "sampler")?; @@ -468,32 +482,36 @@ impl Writer { let dim_str = image_dimension_str(dim); let arrayed_str = if arrayed { "_array" } else { "" }; - let (class_str, multisampled_str, scalar_str) = match class { + let (class_str, multisampled_str, format_str, storage_str) = match class { Ic::Sampled { kind, multi } => ( "", if multi { "multisampled_" } else { "" }, - format!("<{}>", scalar_kind_str(kind)), - ), - Ic::Depth { multi } => ( - "depth_", - if multi { "multisampled_" } else { "" }, - String::from(""), + scalar_kind_str(kind), + "", ), + Ic::Depth { multi } => { + ("depth_", if multi { "multisampled_" } else { "" }, "", "") + } Ic::Storage { format, access } => ( "storage_", "", + storage_format_str(format), if access.contains(crate::StorageAccess::STORE) { - format!("<{},write>", storage_format_str(format)) + ",write" } else { - format!("<{}>", storage_format_str(format)) + "" }, ), }; - let ty_str = format!( - "texture_{}{}{}{}{}", - class_str, multisampled_str, dim_str, arrayed_str, scalar_str - ); - write!(self.out, "{}", ty_str)?; + write!( + self.out, + "texture_{}{}{}{}", + class_str, multisampled_str, dim_str, arrayed_str + )?; + + if !format_str.is_empty() { + write!(self.out, "<{}{}>", format_str, storage_str)?; + } } TypeInner::Scalar { kind, .. } => { write!(self.out, "{}", scalar_kind_str(kind))?; From a4f19833b5679fd9a8c39e6535a7e98fe5a41432 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 3 Sep 2021 12:19:00 -0400 Subject: [PATCH 1313/2212] hlsl: implement struct constructors --- src/back/hlsl/help.rs | 98 +++++++++++- src/back/hlsl/mod.rs | 18 ++- src/back/hlsl/writer.rs | 45 +++--- tests/in/operators.wgsl | 12 ++ tests/out/glsl/operators.main.Compute.glsl | 13 ++ tests/out/hlsl/interface.hlsl | 19 ++- tests/out/hlsl/operators.hlsl | 22 +++ tests/out/hlsl/quad-vert.hlsl | 12 +- tests/out/hlsl/quad.hlsl | 9 +- tests/out/hlsl/skybox.hlsl | 9 +- tests/out/msl/operators.msl | 13 ++ tests/out/spv/operators.spvasm | 164 ++++++++++++--------- tests/out/wgsl/operators.wgsl | 14 ++ 13 files changed, 338 insertions(+), 110 deletions(-) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index a8147aa5a..a98cc3859 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -24,8 +24,8 @@ //! int dim_1d = NagaDimensions1D(image_1d); //! ``` -use super::{super::FunctionCtx, BackendResult}; -use crate::arena::Handle; +use super::{super::FunctionCtx, BackendResult, Error}; +use crate::{arena::Handle, proc::NameKey}; use std::fmt::Write; #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] @@ -41,6 +41,11 @@ pub(super) struct WrappedImageQuery { pub(super) query: ImageQuery, } +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) struct WrappedConstructor { + pub(super) ty: Handle, +} + /// HLSL backend requires its own `ImageQuery` enum. /// /// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function. @@ -342,6 +347,77 @@ impl<'a, W: Write> super::Writer<'a, W> { Ok(()) } + pub(super) fn write_wrapped_constructor_function_name( + &mut self, + constructor: WrappedConstructor, + ) -> BackendResult { + let name = &self.names[&NameKey::Type(constructor.ty)]; + write!(self.out, "Construct{}", name)?; + Ok(()) + } + + /// Helper function that write wrapped function for `Expression::Compose` for structures. + pub(super) fn write_wrapped_constructor_function( + &mut self, + module: &crate::Module, + constructor: WrappedConstructor, + ) -> BackendResult { + use crate::back::INDENT; + + const ARGUMENT_VARIABLE_NAME: &str = "arg"; + const RETURN_VARIABLE_NAME: &str = "ret"; + + // Write function return type and name + let struct_name = &self.names[&NameKey::Type(constructor.ty)]; + write!(self.out, "{} ", struct_name)?; + self.write_wrapped_constructor_function_name(constructor)?; + + // Write function parameters + write!(self.out, "(")?; + let members = match module.types[constructor.ty].inner { + crate::TypeInner::Struct { ref members, .. } => members, + _ => return Err(Error::Unimplemented("non-struct constructor".to_string())), + }; + for (i, member) in members.iter().enumerate() { + if i != 0 { + write!(self.out, ", ")?; + } + self.write_type(module, member.ty)?; + write!(self.out, " {}{}", ARGUMENT_VARIABLE_NAME, i)?; + if let crate::TypeInner::Array { size, .. } = module.types[member.ty].inner { + self.write_array_size(module, size)?; + } + } + // Write function body + writeln!(self.out, ") {{")?; + + let struct_name = &self.names[&NameKey::Type(constructor.ty)]; + writeln!( + self.out, + "{}{} {};", + INDENT, struct_name, RETURN_VARIABLE_NAME + )?; + for i in 0..members.len() as u32 { + let field_name = &self.names[&NameKey::StructMember(constructor.ty, i)]; + //TODO: handle arrays? + writeln!( + self.out, + "{}{}.{} = {}{};", + INDENT, RETURN_VARIABLE_NAME, field_name, ARGUMENT_VARIABLE_NAME, i, + )?; + } + + // Write return value + writeln!(self.out, "{}return {};", INDENT, RETURN_VARIABLE_NAME)?; + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + + Ok(()) + } + /// Helper function that write wrapped function for `Expression::ImageQuery` and `Expression::ArrayLength` /// /// @@ -371,9 +447,9 @@ impl<'a, W: Write> super::Writer<'a, W> { writable: storage_access.contains(crate::StorageAccess::STORE), }; - if !self.wrapped_array_lengths.contains(&wal) { + if !self.wrapped.array_lengths.contains(&wal) { self.write_wrapped_array_length_function(module, wal, handle, func_ctx)?; - self.wrapped_array_lengths.insert(wal); + self.wrapped.array_lengths.insert(wal); } } crate::Expression::ImageQuery { image, query } => { @@ -391,9 +467,19 @@ impl<'a, W: Write> super::Writer<'a, W> { _ => unreachable!("we only query images"), }; - if !self.wrapped_image_queries.contains(&wiq) { + if !self.wrapped.image_queries.contains(&wiq) { self.write_wrapped_image_query_function(module, wiq, handle, func_ctx)?; - self.wrapped_image_queries.insert(wiq); + self.wrapped.image_queries.insert(wiq); + } + } + crate::Expression::Compose { ty, components: _ } => { + let constructor = match module.types[ty].inner { + crate::TypeInner::Struct { .. } => WrappedConstructor { ty }, + _ => continue, + }; + if !self.wrapped.constructors.contains(&constructor) { + self.write_wrapped_constructor_function(module, constructor)?; + self.wrapped.constructors.insert(constructor); } } _ => {} diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 242c090a5..693b00182 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -158,6 +158,21 @@ pub enum Error { Custom(String), } +#[derive(Default)] +struct Wrapped { + array_lengths: crate::FastHashSet, + image_queries: crate::FastHashSet, + constructors: crate::FastHashSet, +} + +impl Wrapped { + fn clear(&mut self) { + self.array_lengths.clear(); + self.image_queries.clear(); + self.constructors.clear(); + } +} + pub struct Writer<'a, W> { out: W, names: crate::FastHashMap, @@ -168,7 +183,6 @@ pub struct Writer<'a, W> { entry_point_io: Vec, /// Set of expressions that have associated temporary variables named_expressions: crate::NamedExpressions, - wrapped_array_lengths: crate::FastHashSet, - wrapped_image_queries: crate::FastHashSet, + wrapped: Wrapped, temp_access_chain: Vec, } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index ed4e963b7..df1d20f22 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,5 +1,5 @@ use super::{ - help::{MipLevelCoordinate, WrappedArrayLength, WrappedImageQuery}, + help::{MipLevelCoordinate, WrappedArrayLength, WrappedConstructor, WrappedImageQuery}, storage::StoreValue, BackendResult, Error, Options, }; @@ -81,8 +81,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { options, entry_point_io: Vec::new(), named_expressions: crate::NamedExpressions::default(), - wrapped_array_lengths: crate::FastHashSet::default(), - wrapped_image_queries: crate::FastHashSet::default(), + wrapped: super::Wrapped::default(), temp_access_chain: Vec::new(), } } @@ -93,8 +92,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { .reset(module, super::keywords::RESERVED, &[], &mut self.names); self.entry_point_io.clear(); self.named_expressions.clear(); - self.wrapped_array_lengths.clear(); - self.wrapped_image_queries.clear(); + self.wrapped.clear(); } pub fn write( @@ -807,7 +805,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { /// /// # Notes /// Adds no trailing or leading whitespace - fn write_type(&mut self, module: &Module, ty: Handle) -> BackendResult { + pub(super) fn write_type(&mut self, module: &Module, ty: Handle) -> BackendResult { let inner = &module.types[ty].inner; match *inner { TypeInner::Struct { .. } => write!(self.out, "{}", self.names[&NameKey::Type(ty)])?, @@ -1184,7 +1182,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Statement::Store { pointer, value } => { - let array_info = match *func_ctx.info[pointer].ty.inner_with(&module.types) { + let ty_inner = func_ctx.info[pointer].ty.inner_with(&module.types); + let array_info = match *ty_inner { TypeInner::Pointer { base, .. } => match module.types[base].inner { crate::TypeInner::Array { size: crate::ArraySize::Constant(ch), @@ -1195,11 +1194,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { _ => None, }; - if let Some(crate::StorageClass::Storage { .. }) = func_ctx.info[pointer] - .ty - .inner_with(&module.types) - .pointer_class() - { + if let Some(crate::StorageClass::Storage { .. }) = ty_inner.pointer_class() { let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; self.write_storage_store( module, @@ -1512,17 +1507,19 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::Compose { ty, ref components } => { - let braces_init = match module.types[ty].inner { - TypeInner::Struct { .. } | TypeInner::Array { .. } => true, - _ => false, + let (brace_open, brace_close) = match module.types[ty].inner { + TypeInner::Struct { .. } => { + self.write_wrapped_constructor_function_name(WrappedConstructor { ty })?; + ("(", ")") + } + TypeInner::Array { .. } => ("{ ", " }"), + _ => { + self.write_type(module, ty)?; + ("(", ")") + } }; - if braces_init { - write!(self.out, "{{ ")?; - } else { - self.write_type(module, ty)?; - write!(self.out, "(")?; - } + write!(self.out, "{}", brace_open)?; for (index, &component) in components.iter().enumerate() { if index != 0 { @@ -1532,11 +1529,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, component, func_ctx)?; } - if braces_init { - write!(self.out, " }}")? - } else { - write!(self.out, ")")? - } + write!(self.out, "{}", brace_close)?; } // All of the multiplication can be expressed as `mul`, // except vector * vector, which needs to use the "*" operator. diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index da2be1cff..e28eb6410 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -31,9 +31,21 @@ fn unary() -> i32 { if (!true) { return a; } else { return ~a; }; } +struct Foo { + a: vec4; + b: i32; +}; + +fn constructors() -> f32 { + var foo: Foo; + foo = Foo(vec4(1.0), 1); + return foo.a.x; +} + [[stage(compute), workgroup_size(1)]] fn main() { let a = builtins(); let b = splat(); let c = unary(); + let d = constructors(); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 6c679229a..519ab775e 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -5,6 +5,11 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +struct Foo { + vec4 a; + int b; +}; + vec4 builtins() { int s1_ = (true ? 1 : 0); @@ -31,10 +36,18 @@ int unary() { } } +float constructors() { + Foo foo; + foo = Foo(vec4(1.0), 1); + vec4 _e10 = foo.a; + return _e10.x; +} + void main() { vec4 _e4 = builtins(); vec4 _e5 = splat(); int _e6 = unary(); + float _e7 = constructors(); return; } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 1899fc95d..affd807ec 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -31,14 +31,29 @@ struct FragmentInput_fragment { uint sample_mask1 : SV_Coverage; }; +VertexOutput ConstructVertexOutput(float4 arg0, float arg1) { + VertexOutput ret; + ret.position = arg0; + ret.varying = arg1; + return ret; +} + VertexOutput_vertex vertex(uint vertex_index : SV_VertexID, uint instance_index : SV_InstanceID, uint color : LOC10) { uint tmp = (((_NagaConstants.base_vertex + vertex_index) + (_NagaConstants.base_instance + instance_index)) + color); - const VertexOutput vertexoutput = { float4(1.0.xxxx), float(tmp) }; + const VertexOutput vertexoutput = ConstructVertexOutput(float4(1.0.xxxx), float(tmp)); const VertexOutput_vertex vertexoutput1 = { vertexoutput.varying, vertexoutput.position }; return vertexoutput1; } +FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) { + FragmentOutput ret; + ret.depth = arg0; + ret.sample_mask = arg1; + ret.color = arg2; + return ret; +} + FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) { VertexOutput in1 = { fragmentinput_fragment.position, fragmentinput_fragment.varying }; @@ -47,7 +62,7 @@ FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) uint sample_mask = fragmentinput_fragment.sample_mask1; uint mask = (sample_mask & (1u << sample_index)); float color1 = (front_facing ? 1.0 : 0.0); - const FragmentOutput fragmentoutput = { in1.varying, mask, color1 }; + const FragmentOutput fragmentoutput = ConstructFragmentOutput(in1.varying, mask, color1); return fragmentoutput; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index de36774a2..cf96e4618 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -3,6 +3,11 @@ static const float4 v_f32_zero = float4(0.0, 0.0, 0.0, 0.0); static const float4 v_f32_half = float4(0.5, 0.5, 0.5, 0.5); static const int4 v_i32_one = int4(1, 1, 1, 1); +struct Foo { + float4 a; + int b; +}; + float4 builtins() { int s1_ = (true ? 1 : 0); @@ -31,11 +36,28 @@ int unary() } } +Foo ConstructFoo(float4 arg0, int arg1) { + Foo ret; + ret.a = arg0; + ret.b = arg1; + return ret; +} + +float constructors() +{ + Foo foo = (Foo)0; + + foo = ConstructFoo(float4(1.0.xxxx), 1); + float4 _expr10 = foo.a; + return _expr10.x; +} + [numthreads(1, 1, 1)] void main() { const float4 _e4 = builtins(); const float4 _e5 = splat(); const int _e6 = unary(); + const float _e7 = constructors(); return; } diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index a5cce3fcd..ea6323b5a 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -36,6 +36,16 @@ void main1() return; } +type10 Constructtype10(float2 arg0, float4 arg1, float arg2, float arg3[1], float arg4[1]) { + type10 ret; + ret.member = arg0; + ret.gl_Position = arg1; + ret.gl_PointSize = arg2; + ret.gl_ClipDistance = arg3; + ret.gl_CullDistance = arg4; + return ret; +} + VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0) { a_uv1 = a_uv; @@ -46,7 +56,7 @@ VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0) float _expr12 = perVertexStruct.gl_PointSize; float _expr13[1] = perVertexStruct.gl_ClipDistance; float _expr14[1] = perVertexStruct.gl_CullDistance; - const type10 type10_ = { _expr10, _expr11, _expr12, _expr13, _expr14 }; + const type10 type10_ = Constructtype10(_expr10, _expr11, _expr12, _expr13, _expr14); const VertexOutput_main type10_1 = { type10_.member, type10_.gl_Position, type10_.gl_ClipDistance, type10_.gl_CullDistance, type10_.gl_PointSize }; return type10_1; } diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index c12c5184c..cde665800 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -17,9 +17,16 @@ struct FragmentInput_main { float2 uv3 : LOC0; }; +VertexOutput ConstructVertexOutput(float2 arg0, float4 arg1) { + VertexOutput ret; + ret.uv = arg0; + ret.position = arg1; + return ret; +} + VertexOutput_main main(float2 pos : LOC0, float2 uv : LOC1) { - const VertexOutput vertexoutput = { uv, float4((c_scale * pos), 0.0, 1.0) }; + const VertexOutput vertexoutput = ConstructVertexOutput(uv, float4((c_scale * pos), 0.0, 1.0)); const VertexOutput_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position }; return vertexoutput1; } diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index dd58f0240..b598ad8d4 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -29,6 +29,13 @@ struct FragmentInput_fs_main { float4 position : SV_Position; }; +VertexOutput ConstructVertexOutput(float4 arg0, float3 arg1) { + VertexOutput ret; + ret.position = arg0; + ret.uv = arg1; + return ret; +} + VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) { int tmp1_ = (int)0; @@ -45,7 +52,7 @@ VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) float3x3 inv_model_view = transpose(float3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz)); float4x4 _expr40 = r_data.proj_inv; float4 unprojected = mul(pos, _expr40); - const VertexOutput vertexoutput = { pos, mul(unprojected.xyz, inv_model_view) }; + const VertexOutput vertexoutput = ConstructVertexOutput(pos, mul(unprojected.xyz, inv_model_view)); const VertexOutput_vs_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position }; return vertexoutput1; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index fd03a429b..e5100def7 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -2,6 +2,10 @@ #include #include +struct Foo { + metal::float4 a; + int b; +}; constant metal::float4 v_f32_one = {1.0, 1.0, 1.0, 1.0}; constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0}; constant metal::float4 v_f32_half = {0.5, 0.5, 0.5, 0.5}; @@ -35,10 +39,19 @@ int unary( } } +float constructors( +) { + Foo foo; + foo = Foo {metal::float4(1.0), 1}; + metal::float4 _e10 = foo.a; + return _e10.x; +} + kernel void main1( ) { metal::float4 _e4 = builtins(); metal::float4 _e5 = splat(); int _e6 = unary(); + float _e7 = constructors(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index e6de2a778..dc1261e90 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,14 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 83 +; Bound: 99 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %77 "main" -OpExecutionMode %77 LocalSize 1 1 1 +OpEntryPoint GLCompute %92 "main" +OpExecutionMode %92 LocalSize 1 1 1 +OpMemberDecorate %22 0 Offset 0 +OpMemberDecorate %22 1 Offset 16 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -27,80 +29,100 @@ OpExecutionMode %77 LocalSize 1 1 1 %19 = OpTypeVector %4 4 %20 = OpTypeVector %8 4 %21 = OpTypeVector %10 4 -%22 = OpConstantComposite %19 %3 %3 %3 %3 -%23 = OpConstantComposite %19 %5 %5 %5 %5 -%24 = OpConstantComposite %19 %6 %6 %6 %6 -%25 = OpConstantComposite %20 %7 %7 %7 %7 -%28 = OpTypeFunction %19 -%52 = OpTypeVector %4 2 -%68 = OpTypeFunction %8 -%75 = OpConstantNull %8 -%78 = OpTypeFunction %2 -%27 = OpFunction %19 None %28 -%26 = OpLabel -OpBranch %29 -%29 = OpLabel -%30 = OpSelect %8 %9 %7 %11 -%32 = OpCompositeConstruct %21 %9 %9 %9 %9 -%31 = OpSelect %19 %32 %22 %23 -%33 = OpCompositeConstruct %21 %12 %12 %12 %12 -%34 = OpSelect %19 %33 %23 %22 -%35 = OpExtInst %19 %1 FMix %23 %22 %24 -%37 = OpCompositeConstruct %19 %13 %13 %13 %13 -%36 = OpExtInst %19 %1 FMix %23 %22 %37 -%38 = OpCompositeExtract %8 %25 0 -%39 = OpBitcast %4 %38 -%40 = OpBitcast %19 %25 -%41 = OpCompositeConstruct %20 %30 %30 %30 %30 -%42 = OpConvertSToF %19 %41 -%43 = OpFAdd %19 %42 %31 -%44 = OpFAdd %19 %43 %35 +%22 = OpTypeStruct %19 %8 +%23 = OpConstantComposite %19 %3 %3 %3 %3 +%24 = OpConstantComposite %19 %5 %5 %5 %5 +%25 = OpConstantComposite %19 %6 %6 %6 %6 +%26 = OpConstantComposite %20 %7 %7 %7 %7 +%29 = OpTypeFunction %19 +%53 = OpTypeVector %4 2 +%69 = OpTypeFunction %8 +%76 = OpConstantNull %8 +%78 = OpTypePointer Function %22 +%81 = OpTypeFunction %4 +%85 = OpTypePointer Function %19 +%87 = OpTypeInt 32 0 +%86 = OpConstant %87 0 +%93 = OpTypeFunction %2 +%28 = OpFunction %19 None %29 +%27 = OpLabel +OpBranch %30 +%30 = OpLabel +%31 = OpSelect %8 %9 %7 %11 +%33 = OpCompositeConstruct %21 %9 %9 %9 %9 +%32 = OpSelect %19 %33 %23 %24 +%34 = OpCompositeConstruct %21 %12 %12 %12 %12 +%35 = OpSelect %19 %34 %24 %23 +%36 = OpExtInst %19 %1 FMix %24 %23 %25 +%38 = OpCompositeConstruct %19 %13 %13 %13 %13 +%37 = OpExtInst %19 %1 FMix %24 %23 %38 +%39 = OpCompositeExtract %8 %26 0 +%40 = OpBitcast %4 %39 +%41 = OpBitcast %19 %26 +%42 = OpCompositeConstruct %20 %31 %31 %31 %31 +%43 = OpConvertSToF %19 %42 +%44 = OpFAdd %19 %43 %32 %45 = OpFAdd %19 %44 %36 -%46 = OpCompositeConstruct %19 %39 %39 %39 %39 -%47 = OpFAdd %19 %45 %46 -%48 = OpFAdd %19 %47 %40 -OpReturnValue %48 +%46 = OpFAdd %19 %45 %37 +%47 = OpCompositeConstruct %19 %40 %40 %40 %40 +%48 = OpFAdd %19 %46 %47 +%49 = OpFAdd %19 %48 %41 +OpReturnValue %49 OpFunctionEnd -%50 = OpFunction %19 None %28 -%49 = OpLabel -OpBranch %51 -%51 = OpLabel -%53 = OpCompositeConstruct %52 %14 %14 -%54 = OpCompositeConstruct %52 %3 %3 -%55 = OpFAdd %52 %54 %53 -%56 = OpCompositeConstruct %52 %15 %15 -%57 = OpFSub %52 %55 %56 -%58 = OpCompositeConstruct %52 %16 %16 -%59 = OpFDiv %52 %57 %58 -%60 = OpCompositeConstruct %20 %17 %17 %17 %17 -%61 = OpCompositeConstruct %20 %18 %18 %18 %18 -%62 = OpSMod %20 %60 %61 -%63 = OpVectorShuffle %19 %59 %59 0 1 0 1 -%64 = OpConvertSToF %19 %62 -%65 = OpFAdd %19 %63 %64 -OpReturnValue %65 +%51 = OpFunction %19 None %29 +%50 = OpLabel +OpBranch %52 +%52 = OpLabel +%54 = OpCompositeConstruct %53 %14 %14 +%55 = OpCompositeConstruct %53 %3 %3 +%56 = OpFAdd %53 %55 %54 +%57 = OpCompositeConstruct %53 %15 %15 +%58 = OpFSub %53 %56 %57 +%59 = OpCompositeConstruct %53 %16 %16 +%60 = OpFDiv %53 %58 %59 +%61 = OpCompositeConstruct %20 %17 %17 %17 %17 +%62 = OpCompositeConstruct %20 %18 %18 %18 %18 +%63 = OpSMod %20 %61 %62 +%64 = OpVectorShuffle %19 %60 %60 0 1 0 1 +%65 = OpConvertSToF %19 %63 +%66 = OpFAdd %19 %64 %65 +OpReturnValue %66 OpFunctionEnd -%67 = OpFunction %8 None %68 -%66 = OpLabel -OpBranch %69 -%69 = OpLabel -%70 = OpLogicalNot %10 %9 -OpSelectionMerge %71 None -OpBranchConditional %70 %72 %73 -%72 = OpLabel -OpReturnValue %7 +%68 = OpFunction %8 None %69 +%67 = OpLabel +OpBranch %70 +%70 = OpLabel +%71 = OpLogicalNot %10 %9 +OpSelectionMerge %72 None +OpBranchConditional %71 %73 %74 %73 = OpLabel -%74 = OpNot %8 %7 -OpReturnValue %74 -%71 = OpLabel +OpReturnValue %7 +%74 = OpLabel +%75 = OpNot %8 %7 OpReturnValue %75 +%72 = OpLabel +OpReturnValue %76 OpFunctionEnd -%77 = OpFunction %2 None %78 -%76 = OpLabel -OpBranch %79 +%80 = OpFunction %4 None %81 %79 = OpLabel -%80 = OpFunctionCall %19 %27 -%81 = OpFunctionCall %19 %50 -%82 = OpFunctionCall %8 %67 +%77 = OpVariable %78 Function +OpBranch %82 +%82 = OpLabel +%83 = OpCompositeConstruct %19 %3 %3 %3 %3 +%84 = OpCompositeConstruct %22 %83 %7 +OpStore %77 %84 +%88 = OpAccessChain %85 %77 %86 +%89 = OpLoad %19 %88 +%90 = OpCompositeExtract %4 %89 0 +OpReturnValue %90 +OpFunctionEnd +%92 = OpFunction %2 None %93 +%91 = OpLabel +OpBranch %94 +%94 = OpLabel +%95 = OpFunctionCall %19 %28 +%96 = OpFunctionCall %19 %51 +%97 = OpFunctionCall %8 %68 +%98 = OpFunctionCall %4 %80 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index a4cf8bdd5..b3f245b5d 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -1,3 +1,8 @@ +struct Foo { + a: vec4; + b: i32; +}; + let v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); @@ -27,10 +32,19 @@ fn unary() -> i32 { } } +fn constructors() -> f32 { + var foo: Foo; + + foo = Foo(vec4(1.0), 1); + let _e10: vec4 = foo.a; + return _e10.x; +} + [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { let _e4: vec4 = builtins(); let _e5: vec4 = splat(); let _e6: i32 = unary(); + let _e7: f32 = constructors(); return; } From 4fa280d9316c5f6b9e5681de3c4616094ab8375f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 4 Sep 2021 11:28:03 +0100 Subject: [PATCH 1314/2212] [glsl-out] Fix select order --- src/back/glsl/mod.rs | 6 ++++-- tests/out/glsl/operators.main.Compute.glsl | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index e8827e679..5a16975cf 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2188,11 +2188,13 @@ impl<'a, W: Write> Writer<'a, W> { // TODO: Boolean mix on desktop required GL_EXT_shader_integer_mix if vec_select { + // Glsl defines that for mix when the condition is a boolean the first element + // is picked if condition is false and the second if condition is true write!(self.out, "mix(")?; - self.write_expr(accept, ctx)?; - write!(self.out, ", ")?; self.write_expr(reject, ctx)?; write!(self.out, ", ")?; + self.write_expr(accept, ctx)?; + write!(self.out, ", ")?; self.write_expr(condition, ctx)?; } else { write!(self.out, "(")?; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 519ab775e..d66947dff 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -14,7 +14,7 @@ struct Foo { vec4 builtins() { int s1_ = (true ? 1 : 0); vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); - vec4 s3_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), bvec4(false, false, false, false)); + vec4 s3_ = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), bvec4(false, false, false, false)); vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); float b1_ = intBitsToFloat(ivec4(1, 1, 1, 1).x); From 803093e710b1a3b1989a7984ae9caf4151306f95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 4 Sep 2021 16:28:56 +0100 Subject: [PATCH 1315/2212] [spv-in] Handle structs with no offset decorations --- src/front/glsl/offset.rs | 19 +----------------- src/front/glsl/parser/declarations.rs | 4 ++-- src/front/mod.rs | 17 ++++++++++++++++ src/front/spv/mod.rs | 29 ++++++++++++++------------- 4 files changed, 35 insertions(+), 34 deletions(-) diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 2c2140b93..2d4f238da 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -13,7 +13,7 @@ use super::{ error::{Error, ErrorKind}, SourceMetadata, }; -use crate::{Arena, Constant, Handle, Type, TypeInner}; +use crate::{front::align_up, Arena, Constant, Handle, Type, TypeInner}; /// Struct with information needed for defining a struct member. /// @@ -170,20 +170,3 @@ pub fn calculate_offset( TypeAlignSpan { ty, align, span } } - -/// Helper function used for aligning `value` to the next multiple of `align` -/// -/// # Notes: -/// - `align` must be a power of two. -/// - The returned value will be greater or equal to `value`. -/// # Examples: -/// ```ignore -/// assert_eq!(0, align_up(0, 16)); -/// assert_eq!(16, align_up(1, 16)); -/// assert_eq!(16, align_up(16, 16)); -/// assert_eq!(334, align_up(333, 2)); -/// assert_eq!(384, align_up(257, 128)); -/// ``` -pub fn align_up(value: u32, align: u32) -> u32 { - ((value.wrapping_sub(1)) & !(align - 1)).wrapping_add(align) -} diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 546c366a2..53e1687d2 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -597,7 +597,7 @@ impl<'source> ParsingContext<'source> { &mut parser.errors, ); - span = offset::align_up(span, info.align); + span = crate::front::align_up(span, info.align); align = align.max(info.align); members.push(StructMember { @@ -614,7 +614,7 @@ impl<'source> ParsingContext<'source> { } } - span = offset::align_up(span, align); + span = crate::front::align_up(span, align); Ok(span) } diff --git a/src/front/mod.rs b/src/front/mod.rs index c9d71d298..8c7b03a7e 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -127,3 +127,20 @@ impl ops::Index> for Typifier { &self.resolutions[handle.index()] } } + +/// Helper function used for aligning `value` to the next multiple of `align` +/// +/// # Notes: +/// - `align` must be a power of two. +/// - The returned value will be greater or equal to `value`. +/// # Examples: +/// ```ignore +/// assert_eq!(0, align_up(0, 16)); +/// assert_eq!(16, align_up(1, 16)); +/// assert_eq!(16, align_up(16, 16)); +/// assert_eq!(334, align_up(333, 2)); +/// assert_eq!(384, align_up(257, 128)); +/// ``` +pub fn align_up(value: u32, align: u32) -> u32 { + ((value.wrapping_sub(1)) & !(align - 1)).wrapping_add(align) +} diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 35646e059..60191d2cb 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -40,7 +40,7 @@ use function::*; use crate::{ arena::{Arena, Handle}, - proc::{Alignment, Layouter}, + proc::Layouter, FastHashMap, }; @@ -3245,10 +3245,11 @@ impl> Parser { .update(&module.types, &module.constants) .unwrap(); - let mut struct_alignment = Alignment::new(1).unwrap(); let mut members = Vec::::with_capacity(inst.wc as usize - 2); let mut member_lookups = Vec::with_capacity(members.capacity()); let mut storage_access = crate::StorageAccess::empty(); + let mut span = 0; + let mut alignment = 1; for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; let ty = self.lookup_type.lookup(type_id)?.handle; @@ -3264,9 +3265,16 @@ impl> Parser { row_major: decor.matrix_major == Some(Majority::Row), }); + span = crate::front::align_up(span, self.layouter[ty].alignment.get()); + alignment = self.layouter[ty].alignment.get().max(alignment); + let binding = decor.io_binding().ok(); - // I/O structs don't have to have offsets, others do - let offset = decor.offset.unwrap_or(0); + if let Some(offset) = decor.offset { + span = offset; + } + let offset = span; + + span += self.layouter[ty].size; if let crate::TypeInner::Matrix { columns, @@ -3292,8 +3300,6 @@ impl> Parser { } } - struct_alignment = struct_alignment.max(self.layouter[ty].alignment); - members.push(crate::StructMember { name: decor.name, ty, @@ -3302,16 +3308,11 @@ impl> Parser { }); } + span = crate::front::align_up(span, alignment); + let inner = crate::TypeInner::Struct { top_level: block_decor.is_some(), - span: members - .iter() - .map(|member| { - let end = member.offset + module.types[member.ty].inner.span(&module.constants); - ((end - 1) | (struct_alignment.get() - 1)) + 1 - }) - .max() - .unwrap_or(4), //do we support this? + span, members, }; From 843c6d57585da7951b9bb332eca149a7cb49fb41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 5 Sep 2021 00:23:18 +0100 Subject: [PATCH 1316/2212] [spv-in] Divide the depth ref in projection sample --- src/front/spv/image.rs | 61 ++++++++++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 6651a52a8..752ddde3e 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -528,24 +528,54 @@ impl> super::Parser { ref other => return Err(Error::InvalidGlobalVar(other.clone())), } - let (coordinate, array_index) = match type_arena[image_ty].inner { + let ((coordinate, array_index), depth_ref) = match type_arena[image_ty].inner { crate::TypeInner::Image { dim, arrayed, class: _, - } => extract_image_coordinates( - dim, - if options.project { - ExtraCoordinate::Projection - } else if arrayed { - ExtraCoordinate::ArrayLayer - } else { - ExtraCoordinate::Garbage + } => ( + extract_image_coordinates( + dim, + if options.project { + ExtraCoordinate::Projection + } else if arrayed { + ExtraCoordinate::ArrayLayer + } else { + ExtraCoordinate::Garbage + }, + coord_lexp.handle, + coord_type_handle, + type_arena, + expressions, + ), + { + match dref_id { + Some(id) => { + let mut expr = self.lookup_expression.lookup(id)?.handle; + + if options.project { + let required_size = dim.required_coordinate_size(); + let right = expressions.append( + crate::Expression::AccessIndex { + base: coord_lexp.handle, + index: required_size.map_or(1, |size| size as u32), + }, + crate::Span::Unknown, + ); + expr = expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: expr, + right, + }, + crate::Span::Unknown, + ) + }; + Some(expr) + } + None => None, + } }, - coord_lexp.handle, - coord_type_handle, - type_arena, - expressions, ), _ => return Err(Error::InvalidImage(image_ty)), }; @@ -557,10 +587,7 @@ impl> super::Parser { array_index, offset, level, - depth_ref: match dref_id { - Some(id) => Some(self.lookup_expression.lookup(id)?.handle), - None => None, - }, + depth_ref, }; self.lookup_expression.insert( result_id, From 3b9dcc568f5d55bc057fd88929cdbdea036ec7ee Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 6 Sep 2021 13:36:32 +0300 Subject: [PATCH 1317/2212] Move `Level` from msl to backend module --- src/back/mod.rs | 18 ++++++++++++++++++ src/back/msl/writer.rs | 27 +++++++-------------------- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/src/back/mod.rs b/src/back/mod.rs index 5de7bce01..77afc12e4 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -20,6 +20,24 @@ const INDENT: &str = " "; #[allow(dead_code)] const BAKE_PREFIX: &str = "_e"; +#[derive(Clone, Copy)] +#[allow(dead_code)] +struct Level(usize); + +#[allow(dead_code)] +impl Level { + fn next(&self) -> Self { + Level(self.0 + 1) + } +} + +#[allow(dead_code)] +impl std::fmt::Display for Level { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + (0..self.0).try_for_each(|_| formatter.write_str(INDENT)) + } +} + /// Stores the current function type (either a regular function or an entry point) /// /// Also stores data needed to identify it (handle for a regular function or index for an entry point) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index aa6597055..da96424df 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -20,19 +20,6 @@ const WRAPPED_ARRAY_FIELD: &str = "inner"; // Some more general handling of pointers is needed to be implemented here. const ATOMIC_REFERENCE: &str = "&"; -#[derive(Clone)] -struct Level(usize); -impl Level { - fn next(&self) -> Self { - Level(self.0 + 1) - } -} -impl Display for Level { - fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> { - (0..self.0).try_for_each(|_| formatter.write_str(back::INDENT)) - } -} - struct TypeContext<'a> { handle: Handle, arena: &'a crate::Arena, @@ -1239,7 +1226,7 @@ impl Writer { fn put_return_value( &mut self, - level: Level, + level: back::Level, expr_handle: Handle, result_struct: Option<&str>, context: &ExpressionContext, @@ -1368,7 +1355,7 @@ impl Writer { fn put_block( &mut self, - level: Level, + level: back::Level, statements: &[crate::Statement], context: &StatementContext, ) -> BackendResult { @@ -1483,7 +1470,7 @@ impl Writer { value: Some(expr_handle), } => { self.put_return_value( - level.clone(), + level, expr_handle, context.result_struct, &context.expression, @@ -1940,7 +1927,7 @@ impl Writer { fn put_inline_sampler_properties( &mut self, - level: Level, + level: back::Level, sampler: &sm::InlineSampler, ) -> BackendResult { for (&letter, address) in ['s', 't', 'r'].iter().zip(sampler.address.iter()) { @@ -2139,7 +2126,7 @@ impl Writer { result_struct: None, }; self.named_expressions.clear(); - self.put_block(Level(1), &fun.body, &context)?; + self.put_block(back::Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; } @@ -2477,7 +2464,7 @@ impl Writer { NAMESPACE, name )?; - self.put_inline_sampler_properties(Level(2), sampler)?; + self.put_inline_sampler_properties(back::Level(2), sampler)?; writeln!(self.out, "{});", back::INDENT)?; } } @@ -2561,7 +2548,7 @@ impl Writer { result_struct: Some(&stage_out_name), }; self.named_expressions.clear(); - self.put_block(Level(1), &fun.body, &context)?; + self.put_block(back::Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; if ep_index + 1 != module.entry_points.len() { writeln!(self.out)?; From f24ea5c5345862ebd5f942196736539c72fc466d Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 6 Sep 2021 13:36:39 +0300 Subject: [PATCH 1318/2212] [wgsl-out] Rewrite indent logic. Reduce heap allocation --- src/back/wgsl/writer.rs | 77 +++++++++++++++++++++-------------------- 1 file changed, 40 insertions(+), 37 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 1b0e9a18f..f5df2f6fb 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -277,7 +277,7 @@ impl Writer { // Write the function body (statement list) for sta in func.body.iter() { // The indentation should always be 1 when writing the function body - self.write_stmt(module, sta, func_ctx, 1)?; + self.write_stmt(module, sta, func_ctx, back::Level(1))?; } writeln!(self.out, "}}")?; @@ -581,10 +581,9 @@ impl Writer { module: &Module, stmt: &crate::Statement, func_ctx: &back::FunctionCtx<'_>, - indent: usize, + level: back::Level, ) -> BackendResult { use crate::{Expression, Statement}; - use back::INDENT; match *stmt { Statement::Emit(ref range) => { @@ -630,7 +629,7 @@ impl Writer { }; if let Some(name) = expr_name { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; self.start_named_expr(module, handle, func_ctx, &name)?; self.write_expr(module, handle, func_ctx)?; self.named_expressions.insert(handle, name); @@ -644,31 +643,32 @@ impl Writer { ref accept, ref reject, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; write!(self.out, "if (")?; self.write_expr(module, condition, func_ctx)?; writeln!(self.out, ") {{")?; + let l2 = level.next(); for sta in accept { // Increase indentation to help with readability - self.write_stmt(module, sta, func_ctx, indent + 1)?; + self.write_stmt(module, sta, func_ctx, l2)?; } // If there are no statements in the reject block we skip writing it // This is only for readability if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", INDENT.repeat(indent))?; + writeln!(self.out, "{}}} else {{", level)?; for sta in reject { // Increase indentation to help with readability - self.write_stmt(module, sta, func_ctx, indent + 1)?; + self.write_stmt(module, sta, func_ctx, l2)?; } } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } Statement::Return { value } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; write!(self.out, "return")?; if let Some(return_value) = value { // The leading space is important @@ -679,7 +679,7 @@ impl Writer { } // TODO: copy-paste from glsl-out Statement::Kill => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; writeln!(self.out, "discard;")? } Statement::Store { pointer, value } => { @@ -691,7 +691,7 @@ impl Writer { return Ok(()); } } - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; let (is_ptr, is_atomic) = match *func_ctx.info[pointer].ty.inner_with(&module.types) { @@ -725,7 +725,7 @@ impl Writer { ref arguments, result, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; if let Some(expr) = result { let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); self.start_named_expr(module, expr, func_ctx, &name)?; @@ -749,7 +749,7 @@ impl Writer { value, result, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); self.start_named_expr(module, result, func_ctx, &res_name)?; self.named_expressions.insert(result, res_name); @@ -776,7 +776,7 @@ impl Writer { array_index, value, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; write!(self.out, "textureStore(")?; self.write_expr(module, image, func_ctx)?; write!(self.out, ", ")?; @@ -791,13 +791,13 @@ impl Writer { } // TODO: copy-paste from glsl-out Statement::Block(ref block) => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; writeln!(self.out, "{{")?; for sta in block.iter() { // Increase the indentation to help with readability - self.write_stmt(module, sta, func_ctx, indent + 1)? + self.write_stmt(module, sta, func_ctx, level.next())? } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } Statement::Switch { selector, @@ -805,7 +805,7 @@ impl Writer { ref default, } => { // Start the switch - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; write!(self.out, "switch(")?; self.write_expr(module, selector, func_ctx)?; writeln!(self.out, ") {{")?; @@ -815,10 +815,12 @@ impl Writer { let all_fall_through = cases .iter() .all(|case| case.fall_through && case.body.is_empty()); + + let l2 = level.next(); if !cases.is_empty() { for case in cases { if write_case { - write!(self.out, "{}case ", INDENT.repeat(indent + 1))?; + write!(self.out, "{}case ", l2)?; } if !all_fall_through && case.fall_through && case.body.is_empty() { write_case = false; @@ -830,63 +832,64 @@ impl Writer { } for sta in case.body.iter() { - self.write_stmt(module, sta, func_ctx, indent + 2)?; + self.write_stmt(module, sta, func_ctx, l2.next())?; } if case.fall_through { - writeln!(self.out, "{}fallthrough;", INDENT.repeat(indent + 2))?; + writeln!(self.out, "{}fallthrough;", l2.next())?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; + writeln!(self.out, "{}}}", l2)?; } } if !default.is_empty() { - writeln!(self.out, "{}default: {{", INDENT.repeat(indent + 1))?; + writeln!(self.out, "{}default: {{", l2)?; for sta in default { - self.write_stmt(module, sta, func_ctx, indent + 2)?; + self.write_stmt(module, sta, func_ctx, l2.next())?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))? + writeln!(self.out, "{}}}", l2)? } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } Statement::Loop { ref body, ref continuing, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; writeln!(self.out, "loop {{")?; + let l2 = level.next(); for sta in body.iter() { - self.write_stmt(module, sta, func_ctx, indent + 1)?; + self.write_stmt(module, sta, func_ctx, l2)?; } if !continuing.is_empty() { - writeln!(self.out, "{}continuing {{", INDENT.repeat(indent + 1))?; + writeln!(self.out, "{}continuing {{", l2)?; for sta in continuing.iter() { - self.write_stmt(module, sta, func_ctx, indent + 2)?; + self.write_stmt(module, sta, func_ctx, l2.next())?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; + writeln!(self.out, "{}}}", l2)?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } Statement::Break => { - writeln!(self.out, "{}break;", INDENT.repeat(indent))?; + writeln!(self.out, "{}break;", level)?; } Statement::Continue => { - writeln!(self.out, "{}continue;", INDENT.repeat(indent))?; + writeln!(self.out, "{}continue;", level)?; } Statement::Barrier(barrier) => { if barrier.contains(crate::Barrier::STORAGE) { - writeln!(self.out, "{}storageBarrier();", INDENT.repeat(indent))?; + writeln!(self.out, "{}storageBarrier();", level)?; } if barrier.contains(crate::Barrier::WORK_GROUP) { - writeln!(self.out, "{}workgroupBarrier();", INDENT.repeat(indent))?; + writeln!(self.out, "{}workgroupBarrier();", level)?; } } } From 9afb581364b37c85d006c2322031793b59c59a87 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 6 Sep 2021 13:36:51 +0300 Subject: [PATCH 1319/2212] [glsl-out] Rewrite indent logic. Reduce heap allocation --- src/back/glsl/mod.rs | 106 ++++++++++++++++++------------------------- 1 file changed, 43 insertions(+), 63 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5a16975cf..62781147b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1146,7 +1146,7 @@ impl<'a, W: Write> Writer<'a, W> { for sta in func.body.iter() { // Write a statement, the indentation should always be 1 when writing the function body // `write_stmt` adds a newline - self.write_stmt(sta, &ctx, 1)?; + self.write_stmt(sta, &ctx, back::Level(1))?; } // Close braces and add a newline @@ -1324,10 +1324,9 @@ impl<'a, W: Write> Writer<'a, W> { &mut self, sta: &crate::Statement, ctx: &back::FunctionCtx, - indent: usize, + level: back::Level, ) -> BackendResult { use crate::Statement; - use back::INDENT; match *sta { // This is where we can generate intermediate constants for some expression types. @@ -1349,7 +1348,7 @@ impl<'a, W: Write> Writer<'a, W> { }; if let Some(name) = expr_name { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; self.write_named_expr(handle, name, ctx)?; } } @@ -1358,13 +1357,13 @@ impl<'a, W: Write> Writer<'a, W> { // We could also just print the statements but this is more readable and maps more // closely to the IR Statement::Block(ref block) => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; writeln!(self.out, "{{")?; for sta in block.iter() { // Increase the indentation to help with readability - self.write_stmt(sta, ctx, indent + 1)? + self.write_stmt(sta, ctx, level.next())? } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } // Ifs are written as in C: // ``` @@ -1379,28 +1378,28 @@ impl<'a, W: Write> Writer<'a, W> { ref accept, ref reject, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; write!(self.out, "if (")?; self.write_expr(condition, ctx)?; writeln!(self.out, ") {{")?; for sta in accept { // Increase indentation to help with readability - self.write_stmt(sta, ctx, indent + 1)?; + self.write_stmt(sta, ctx, level.next())?; } // If there are no statements in the reject block we skip writing it // This is only for readability if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", INDENT.repeat(indent))?; + writeln!(self.out, "{}}} else {{", level)?; for sta in reject { // Increase indentation to help with readability - self.write_stmt(sta, ctx, indent + 1)?; + self.write_stmt(sta, ctx, level.next())?; } } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } // Switch are written as in C: // ``` @@ -1424,29 +1423,25 @@ impl<'a, W: Write> Writer<'a, W> { ref default, } => { // Start the switch - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; write!(self.out, "switch(")?; self.write_expr(selector, ctx)?; writeln!(self.out, ") {{")?; // Write all cases + let l2 = level.next(); for case in cases { - writeln!( - self.out, - "{}case {}:", - INDENT.repeat(indent + 1), - case.value - )?; + writeln!(self.out, "{}case {}:", l2, case.value)?; for sta in case.body.iter() { - self.write_stmt(sta, ctx, indent + 2)?; + self.write_stmt(sta, ctx, l2.next())?; } // Write fallthrough comment if the case is fallthrough, // otherwise write a break, if the case is not already // broken out of at the end of its body. if case.fall_through { - writeln!(self.out, "{}/* fallthrough */", INDENT.repeat(indent + 2))?; + writeln!(self.out, "{}/* fallthrough */", l2.next())?; } else if !matches!( case.body.last(), Some(&Statement::Break) @@ -1454,21 +1449,21 @@ impl<'a, W: Write> Writer<'a, W> { | Some(&Statement::Return { .. }) | Some(&Statement::Kill) ) { - writeln!(self.out, "{}break;", INDENT.repeat(indent + 2))?; + writeln!(self.out, "{}break;", l2.next())?; } } // Only write the default block if the block isn't empty // Writing default without a block is valid but it's more readable this way if !default.is_empty() { - writeln!(self.out, "{}default:", INDENT.repeat(indent + 1))?; + writeln!(self.out, "{}default:", level.next())?; for sta in default { - self.write_stmt(sta, ctx, indent + 2)?; + self.write_stmt(sta, ctx, l2.next())?; } } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a // while true loop and appending the continuing block to the body resulting on: @@ -1486,51 +1481,36 @@ impl<'a, W: Write> Writer<'a, W> { } => { if !continuing.is_empty() { let gate_name = self.namer.call("loop_init"); - writeln!( - self.out, - "{}bool {} = true;", - INDENT.repeat(indent), - gate_name - )?; - writeln!(self.out, "{}while(true) {{", INDENT.repeat(indent))?; - writeln!( - self.out, - "{}if (!{}) {{", - INDENT.repeat(indent + 1), - gate_name - )?; + writeln!(self.out, "{}bool {} = true;", level, gate_name)?; + writeln!(self.out, "{}while(true) {{", level)?; + writeln!(self.out, "{}if (!{}) {{", level.next(), gate_name)?; for sta in continuing { - self.write_stmt(sta, ctx, indent + 1)?; + self.write_stmt(sta, ctx, level.next())?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; - writeln!( - self.out, - "{}{} = false;", - INDENT.repeat(indent + 1), - gate_name - )?; + writeln!(self.out, "{}}}", level.next())?; + writeln!(self.out, "{}{} = false;", level.next(), gate_name)?; } else { - writeln!(self.out, "{}while(true) {{", INDENT.repeat(indent))?; + writeln!(self.out, "{}while(true) {{", level)?; } for sta in body { - self.write_stmt(sta, ctx, indent + 1)?; + self.write_stmt(sta, ctx, level.next())?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } // Break, continue and return as written as in C // `break;` Statement::Break => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; writeln!(self.out, "break;")? } // `continue;` Statement::Continue => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; writeln!(self.out, "continue;")? } // `return expr;`, `expr` is optional Statement::Return { value } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; match ctx.ty { back::FunctionType::Function(_) => { write!(self.out, "return")?; @@ -1558,7 +1538,7 @@ impl<'a, W: Write> Writer<'a, W> { )?; self.write_expr(value, ctx)?; writeln!(self.out, ";")?; - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; Some(return_struct) } _ => None, @@ -1598,7 +1578,7 @@ impl<'a, W: Write> Writer<'a, W> { } writeln!(self.out, ".{};", field_name)?; - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; } } _ => { @@ -1610,7 +1590,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{} = ", name)?; self.write_expr(value, ctx)?; writeln!(self.out, ";")?; - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; } } } @@ -1627,7 +1607,7 @@ impl<'a, W: Write> Writer<'a, W> { self.out, "gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);", )?; - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; } } writeln!(self.out, "return;")?; @@ -1637,18 +1617,18 @@ impl<'a, W: Write> Writer<'a, W> { // This is one of the places were glsl adds to the syntax of C in this case the discard // keyword which ceases all further processing in a fragment shader, it's called OpKill // in spir-v that's why it's called `Statement::Kill` - Statement::Kill => writeln!(self.out, "{}discard;", INDENT.repeat(indent))?, + Statement::Kill => writeln!(self.out, "{}discard;", level)?, // Issue an execution or a memory barrier. Statement::Barrier(flags) => { if flags.is_empty() { - writeln!(self.out, "{}barrier();", INDENT.repeat(indent))?; + writeln!(self.out, "{}barrier();", level)?; } else { - writeln!(self.out, "{}groupMemoryBarrier();", INDENT.repeat(indent))?; + writeln!(self.out, "{}groupMemoryBarrier();", level)?; } } // Stores in glsl are just variable assignments written as `pointer = value;` Statement::Store { pointer, value } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; self.write_expr(pointer, ctx)?; write!(self.out, " = ")?; self.write_expr(value, ctx)?; @@ -1661,7 +1641,7 @@ impl<'a, W: Write> Writer<'a, W> { array_index, value, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; // This will only panic if the module is invalid let dim = match *ctx.info[image].ty.inner_with(&self.module.types) { TypeInner::Image { dim, .. } => dim, @@ -1682,7 +1662,7 @@ impl<'a, W: Write> Writer<'a, W> { ref arguments, result, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; if let Some(expr) = result { let name = format!("{}{}", super::BAKE_PREFIX, expr.index()); let result = self.module.functions[function].result.as_ref().unwrap(); @@ -1711,7 +1691,7 @@ impl<'a, W: Write> Writer<'a, W> { value, result, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; let res_name = format!("{}{}", super::BAKE_PREFIX, result.index()); let res_ty = ctx.info[result].ty.inner_with(&self.module.types); self.write_value_type(res_ty)?; From 35f27cfe7ee09588add02e3c8ce9e3b391953711 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 6 Sep 2021 13:36:59 +0300 Subject: [PATCH 1320/2212] [hlsl-out] Rewrite indent logic. Reduce heap allocation --- src/back/hlsl/storage.rs | 47 ++++++-------- src/back/hlsl/writer.rs | 136 ++++++++++++++++----------------------- 2 files changed, 74 insertions(+), 109 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 60d0b161f..b19129790 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -2,10 +2,7 @@ //! //! HLSL backend uses byte address buffers for all storage buffers in IR. -use super::{ - super::{FunctionCtx, INDENT}, - BackendResult, Error, -}; +use super::{super::FunctionCtx, BackendResult, Error}; use crate::{ proc::{NameKey, TypeResolution}, Handle, @@ -202,7 +199,7 @@ impl super::Writer<'_, W> { var_handle: Handle, value: StoreValue, func_ctx: &FunctionCtx, - indent: usize, + level: crate::back::Level, ) -> BackendResult { let temp_resolution; let ty_resolution = match value { @@ -232,7 +229,7 @@ impl super::Writer<'_, W> { // working around the borrow checker in `self.write_expr` let chain = mem::take(&mut self.temp_access_chain); let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; - write!(self.out, "{}{}.Store(", INDENT.repeat(indent), var_name)?; + write!(self.out, "{}{}.Store(", level, var_name)?; self.write_storage_address(module, &chain, func_ctx)?; write!(self.out, ", asuint(")?; self.write_store_value(module, &value, func_ctx)?; @@ -243,13 +240,7 @@ impl super::Writer<'_, W> { // working around the borrow checker in `self.write_expr` let chain = mem::take(&mut self.temp_access_chain); let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; - write!( - self.out, - "{}{}.Store{}(", - INDENT.repeat(indent), - var_name, - size as u8 - )?; + write!(self.out, "{}{}.Store{}(", level, var_name, size as u8)?; self.write_storage_address(module, &chain, func_ctx)?; write!(self.out, ", asuint(")?; self.write_store_value(module, &value, func_ctx)?; @@ -262,12 +253,12 @@ impl super::Writer<'_, W> { width, } => { // first, assign the value to a temporary - writeln!(self.out, "{}{{", INDENT.repeat(indent))?; - let depth = indent + 1; + writeln!(self.out, "{}{{", level)?; + let depth = level.0 + 1; write!( self.out, "{}{}{}x{} {}{} = ", - INDENT.repeat(indent + 1), + level.next(), crate::ScalarKind::Float.to_hlsl_str(width)?, rows as u8, columns as u8, @@ -291,11 +282,11 @@ impl super::Writer<'_, W> { index: i, ty: TypeResolution::Value(ty_inner), }; - self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; + self.write_storage_store(module, var_handle, sv, func_ctx, level.next())?; self.temp_access_chain.pop(); } // done - writeln!(self.out, "{}}}", INDENT.repeat(indent))?; + writeln!(self.out, "{}}}", level)?; } crate::TypeInner::Array { base, @@ -303,10 +294,10 @@ impl super::Writer<'_, W> { .. } => { // first, assign the value to a temporary - writeln!(self.out, "{}{{", INDENT.repeat(indent))?; - write!(self.out, "{}", INDENT.repeat(indent + 1))?; + writeln!(self.out, "{}{{", level)?; + write!(self.out, "{}", level.next())?; self.write_value_type(module, &module.types[base].inner)?; - let depth = indent + 1; + let depth = level.next().0; write!(self.out, " {}{}", STORE_TEMP_NAME, depth)?; self.write_array_size(module, crate::ArraySize::Constant(const_handle))?; write!(self.out, " = ")?; @@ -322,22 +313,22 @@ impl super::Writer<'_, W> { index: i, ty: TypeResolution::Handle(base), }; - self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; + self.write_storage_store(module, var_handle, sv, func_ctx, level.next())?; self.temp_access_chain.pop(); } // done - writeln!(self.out, "{}}}", INDENT.repeat(indent))?; + writeln!(self.out, "{}}}", level)?; } crate::TypeInner::Struct { ref members, .. } => { // first, assign the value to a temporary - writeln!(self.out, "{}{{", INDENT.repeat(indent))?; - let depth = indent + 1; + writeln!(self.out, "{}{{", level)?; + let depth = level.next().0; let struct_ty = ty_resolution.handle().unwrap(); let struct_name = &self.names[&NameKey::Type(struct_ty)]; write!( self.out, "{}{} {}{} = ", - INDENT.repeat(indent + 1), + level.next(), struct_name, STORE_TEMP_NAME, depth @@ -353,11 +344,11 @@ impl super::Writer<'_, W> { base: struct_ty, member_index: i as u32, }; - self.write_storage_store(module, var_handle, sv, func_ctx, indent + 1)?; + self.write_storage_store(module, var_handle, sv, func_ctx, level.next())?; self.temp_access_chain.pop(); } // done - writeln!(self.out, "{}}}", INDENT.repeat(indent))?; + writeln!(self.out, "{}}}", level)?; } _ => unreachable!(), } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index df1d20f22..b0b0d1a98 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1031,7 +1031,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write the function body (statement list) for sta in func.body.iter() { // The indentation should always be 1 when writing the function body - self.write_stmt(module, sta, func_ctx, 1)?; + self.write_stmt(module, sta, func_ctx, back::Level(1))?; } writeln!(self.out, "}}")?; @@ -1050,10 +1050,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { module: &Module, stmt: &crate::Statement, func_ctx: &back::FunctionCtx<'_>, - indent: usize, + level: back::Level, ) -> BackendResult { use crate::Statement; - use back::INDENT; match *stmt { Statement::Emit(ref range) => { @@ -1074,20 +1073,20 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; if let Some(name) = expr_name { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; self.write_named_expr(module, handle, name, func_ctx)?; } } } // TODO: copy-paste from glsl-out Statement::Block(ref block) => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; writeln!(self.out, "{{")?; for sta in block.iter() { // Increase the indentation to help with readability - self.write_stmt(module, sta, func_ctx, indent + 1)? + self.write_stmt(module, sta, func_ctx, level.next())? } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } // TODO: copy-paste from glsl-out Statement::If { @@ -1095,33 +1094,34 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ref accept, ref reject, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; write!(self.out, "if (")?; self.write_expr(module, condition, func_ctx)?; writeln!(self.out, ") {{")?; + let l2 = level.next(); for sta in accept { // Increase indentation to help with readability - self.write_stmt(module, sta, func_ctx, indent + 1)?; + self.write_stmt(module, sta, func_ctx, l2)?; } // If there are no statements in the reject block we skip writing it // This is only for readability if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", INDENT.repeat(indent))?; + writeln!(self.out, "{}}} else {{", level)?; for sta in reject { // Increase indentation to help with readability - self.write_stmt(module, sta, func_ctx, indent + 1)?; + self.write_stmt(module, sta, func_ctx, l2)?; } } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } // TODO: copy-paste from glsl-out - Statement::Kill => writeln!(self.out, "{}discard;", INDENT.repeat(indent))?, + Statement::Kill => writeln!(self.out, "{}discard;", level)?, Statement::Return { value: None } => { - writeln!(self.out, "{}return;", INDENT.repeat(indent))?; + writeln!(self.out, "{}return;", level)?; } Statement::Return { value: Some(expr) } => { let base_ty_res = &func_ctx.info[expr].ty; @@ -1138,9 +1138,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!( self.out, "{}const {} {} = ", - INDENT.repeat(indent), - struct_name, - variable_name, + level, struct_name, variable_name, )?; self.write_expr(module, expr, func_ctx)?; writeln!(self.out, ";")?; @@ -1158,9 +1156,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!( self.out, "{}const {} {} = {{ ", - INDENT.repeat(indent), - ep_output.ty_name, - final_name, + level, ep_output.ty_name, final_name, )?; for (index, m) in ep_output.members.iter().enumerate() { if index != 0 { @@ -1174,9 +1170,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } None => variable_name, }; - writeln!(self.out, "{}return {};", INDENT.repeat(indent), final_name)?; + writeln!(self.out, "{}return {};", level, final_name)?; } else { - write!(self.out, "{}return ", INDENT.repeat(indent))?; + write!(self.out, "{}return ", level)?; self.write_expr(module, expr, func_ctx)?; writeln!(self.out, ";")? } @@ -1201,12 +1197,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { var_handle, StoreValue::Expression(value), func_ctx, - indent, + level, )?; } else if let Some((const_handle, base_ty)) = array_info { let size = module.constants[const_handle].to_array_length().unwrap(); - writeln!(self.out, "{}{{", INDENT.repeat(indent))?; - write!(self.out, "{}", INDENT.repeat(indent + 1))?; + writeln!(self.out, "{}{{", level)?; + write!(self.out, "{}", level.next())?; self.write_type(module, base_ty)?; write!(self.out, " _result[{}]=", size)?; self.write_expr(module, value, func_ctx)?; @@ -1214,14 +1210,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!( self.out, "{}for(int _i=0; _i<{}; ++_i) ", - INDENT.repeat(indent + 1), + level.next(), size )?; self.write_expr(module, pointer, func_ctx)?; writeln!(self.out, "[_i] = _result[_i];")?; - writeln!(self.out, "{}}}", INDENT.repeat(indent))?; + writeln!(self.out, "{}}}", level)?; } else { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; self.write_expr(module, pointer, func_ctx)?; write!(self.out, " = ")?; self.write_expr(module, value, func_ctx)?; @@ -1232,57 +1228,35 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ref body, ref continuing, } => { + let l2 = level.next(); if !continuing.is_empty() { let gate_name = self.namer.call("loop_init"); - writeln!( - self.out, - "{}bool {} = true;", - INDENT.repeat(indent), - gate_name - )?; - writeln!(self.out, "{}while(true) {{", INDENT.repeat(indent))?; - writeln!( - self.out, - "{}if (!{}) {{", - INDENT.repeat(indent + 1), - gate_name - )?; + writeln!(self.out, "{}bool {} = true;", level, gate_name)?; + writeln!(self.out, "{}while(true) {{", level)?; + writeln!(self.out, "{}if (!{}) {{", l2, gate_name)?; for sta in continuing.iter() { - self.write_stmt(module, sta, func_ctx, indent + 1)?; + self.write_stmt(module, sta, func_ctx, l2)?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent + 1))?; - writeln!( - self.out, - "{}{} = false;", - INDENT.repeat(indent + 1), - gate_name - )?; + writeln!(self.out, "{}}}", level.next())?; + writeln!(self.out, "{}{} = false;", level.next(), gate_name)?; } else { - writeln!(self.out, "{}while(true) {{", INDENT.repeat(indent))?; + writeln!(self.out, "{}while(true) {{", level)?; } for sta in body.iter() { - self.write_stmt(module, sta, func_ctx, indent + 1)?; + self.write_stmt(module, sta, func_ctx, l2)?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } - Statement::Break => writeln!(self.out, "{}break;", INDENT.repeat(indent))?, - Statement::Continue => writeln!(self.out, "{}continue;", INDENT.repeat(indent))?, + Statement::Break => writeln!(self.out, "{}break;", level)?, + Statement::Continue => writeln!(self.out, "{}continue;", level)?, Statement::Barrier(barrier) => { if barrier.contains(crate::Barrier::STORAGE) { - writeln!( - self.out, - "{}DeviceMemoryBarrierWithGroupSync();", - INDENT.repeat(indent) - )?; + writeln!(self.out, "{}DeviceMemoryBarrierWithGroupSync();", level)?; } if barrier.contains(crate::Barrier::WORK_GROUP) { - writeln!( - self.out, - "{}GroupMemoryBarrierWithGroupSync();", - INDENT.repeat(indent) - )?; + writeln!(self.out, "{}GroupMemoryBarrierWithGroupSync();", level)?; } } Statement::ImageStore { @@ -1291,7 +1265,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { array_index, value, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; self.write_expr(module, image, func_ctx)?; write!(self.out, "[")?; @@ -1316,7 +1290,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ref arguments, result, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; if let Some(expr) = result { write!(self.out, "const ")?; let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); @@ -1348,7 +1322,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { value, result, } => { - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); match func_ctx.info[result].ty { proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?, @@ -1392,55 +1366,55 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ref default, } => { // Start the switch - write!(self.out, "{}", INDENT.repeat(indent))?; + write!(self.out, "{}", level)?; write!(self.out, "switch(")?; self.write_expr(module, selector, func_ctx)?; writeln!(self.out, ") {{")?; // Write all cases - let indent_str_1 = INDENT.repeat(indent + 1); - let indent_str_2 = INDENT.repeat(indent + 2); + let indent_level_1 = level.next(); + let indent_level_2 = indent_level_1.next(); for case in cases { - writeln!(self.out, "{}case {}: {{", &indent_str_1, case.value)?; + writeln!(self.out, "{}case {}: {{", indent_level_1, case.value)?; if case.fall_through { // Generate each fallthrough case statement in a new block. This is done to // prevent symbol collision of variables declared in these cases statements. - writeln!(self.out, "{}/* fallthrough */", &indent_str_2)?; - writeln!(self.out, "{}{{", &indent_str_2)?; + writeln!(self.out, "{}/* fallthrough */", indent_level_2)?; + writeln!(self.out, "{}{{", indent_level_2)?; } for sta in case.body.iter() { self.write_stmt( module, sta, func_ctx, - indent + 2 + usize::from(case.fall_through), + back::Level(indent_level_2.0 + usize::from(case.fall_through)), )?; } if case.fall_through { - writeln!(self.out, "{}}}", &indent_str_2)?; + writeln!(self.out, "{}}}", indent_level_2)?; } else { - writeln!(self.out, "{}break;", &indent_str_2)?; + writeln!(self.out, "{}break;", indent_level_2)?; } - writeln!(self.out, "{}}}", &indent_str_1)?; + writeln!(self.out, "{}}}", indent_level_1)?; } // Only write the default block if the block isn't empty // Writing default without a block is valid but it's more readable this way if !default.is_empty() { - writeln!(self.out, "{}default: {{", &indent_str_1)?; + writeln!(self.out, "{}default: {{", indent_level_1)?; for sta in default { - self.write_stmt(module, sta, func_ctx, indent + 2)?; + self.write_stmt(module, sta, func_ctx, indent_level_2)?; } - writeln!(self.out, "{}}}", &indent_str_1)?; + writeln!(self.out, "{}}}", indent_level_1)?; } - writeln!(self.out, "{}}}", INDENT.repeat(indent))? + writeln!(self.out, "{}}}", level)? } } From 7138876625029a59c1f2a0890e9c03b755b11b73 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 7 Sep 2021 10:42:29 -0400 Subject: [PATCH 1321/2212] [spv-out]: ability to separate entry points --- cli/src/main.rs | 18 +++ src/back/spv/mod.rs | 30 ++++- src/back/spv/writer.rs | 55 +++++++-- tests/in/interface.param.ron | 1 + tests/out/spv/interface.Compute.spvasm | 68 +++++++++++ tests/out/spv/interface.Fragment.spvasm | 78 +++++++++++++ tests/out/spv/interface.Vertex.spvasm | 61 ++++++++++ tests/out/spv/interface.spvasm | 146 ------------------------ tests/snapshots.rs | 30 +++-- tests/spirv-capabilities.rs | 2 +- 10 files changed, 324 insertions(+), 165 deletions(-) create mode 100644 tests/out/spv/interface.Compute.spvasm create mode 100644 tests/out/spv/interface.Fragment.spvasm create mode 100644 tests/out/spv/interface.Vertex.spvasm delete mode 100644 tests/out/spv/interface.spvasm diff --git a/cli/src/main.rs b/cli/src/main.rs index 0f64f0a1b..1fa20373f 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -335,6 +335,23 @@ fn run() -> Result<(), Box> { "spv" => { use naga::back::spv; + let pipeline_options_owned; + let pipeline_options = match params.entry_point { + Some(ref name) => { + let ep_index = module + .entry_points + .iter() + .position(|ep| ep.name == *name) + .expect("Unable to find the entry point"); + pipeline_options_owned = spv::PipelineOptions { + entry_point: name.clone(), + shader_stage: module.entry_points[ep_index].stage, + }; + Some(&pipeline_options_owned) + } + None => None, + }; + params.spv.bounds_check_policies = params.bounds_check_policies; let spv = spv::write_vec( @@ -344,6 +361,7 @@ fn run() -> Result<(), Box> { succeed, and it failed in a previous step", ))?, ¶ms.spv, + pipeline_options, ) .unwrap_pretty(); let bytes = spv diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index b06db365c..09e98ab53 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -55,6 +55,8 @@ const BITS_PER_BYTE: crate::Bytes = 8; #[derive(Clone, Debug, Error)] pub enum Error { + #[error("The requested entry point couldn't be found")] + EntryPointNotFound, #[error("target SPIRV-{0}.{1} is not supported")] UnsupportedVersion(u8, u8), #[error("using {0} requires at least one of the capabilities {1:?}, but none are available")] @@ -387,8 +389,15 @@ struct GlobalVariable { } impl GlobalVariable { - fn new(id: Word) -> GlobalVariable { - GlobalVariable { id, handle_id: 0 } + fn dummy() -> Self { + Self { + id: 0, + handle_id: 0, + } + } + + fn new(id: Word) -> Self { + Self { id, handle_id: 0 } } /// Prepare `self` for use within a single function. @@ -539,13 +548,28 @@ impl Default for Options { } } +// A subset of options that are meant to be changed per pipeline. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct PipelineOptions { + /// The stage of the entry point + pub shader_stage: crate::ShaderStage, + /// The name of the entry point + /// + /// If no entry point that matches is found a error will be thrown while creating a new instance + /// of [`Writer`](struct.Writer.html) + pub entry_point: String, +} + pub fn write_vec( module: &crate::Module, info: &crate::valid::ModuleInfo, options: &Options, + pipeline_options: Option<&PipelineOptions>, ) -> Result, Error> { let mut words = Vec::new(); let mut w = Writer::new(options)?; - w.write(module, info, &mut words)?; + w.write(module, info, pipeline_options, &mut words)?; Ok(words) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 018ecf640..943b96dcf 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -3,7 +3,7 @@ use super::{ make_local, Block, BlockContext, CachedExpressions, EntryPointContext, Error, Function, FunctionArgument, GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, LogicalLayout, LookupFunctionType, LookupType, LoopContext, Options, PhysicalLayout, - ResultMember, Writer, WriterFlags, BITS_PER_BYTE, + PipelineOptions, ResultMember, Writer, WriterFlags, BITS_PER_BYTE, }; use crate::{ arena::{Arena, Handle}, @@ -1213,6 +1213,7 @@ impl Writer { &mut self, ir_module: &crate::Module, mod_info: &ModuleInfo, + ep_index: Option, ) -> Result<(), Error> { let has_storage_buffers = ir_module @@ -1278,22 +1279,46 @@ impl Writer { debug_assert_eq!(self.constant_ids.iter().position(|&id| id == 0), None); // now write all globals - for (_, var) in ir_module.global_variables.iter() { - let (instruction, id) = self.write_global_variable(ir_module, var)?; - instruction.to_words(&mut self.logical_layout.declarations); - self.global_variables.push(GlobalVariable::new(id)); + for (handle, var) in ir_module.global_variables.iter() { + // If a single entry point was specified, only write `OpVariable` instructions + // for the globals it actually uses. Emit dummies for the others, + // to preserve the indices in `global_variables`. + let gvar = match ep_index { + Some(index) if mod_info.get_entry_point(index)[handle].is_empty() => { + GlobalVariable::dummy() + } + _ => { + let (instruction, id) = self.write_global_variable(ir_module, var)?; + instruction.to_words(&mut self.logical_layout.declarations); + GlobalVariable::new(id) + } + }; + self.global_variables.push(gvar); } // all functions for (handle, ir_function) in ir_module.functions.iter() { let info = &mod_info[handle]; + if let Some(index) = ep_index { + let ep_info = mod_info.get_entry_point(index); + // If this function uses globals that we omitted from the SPIR-V + // because the entry point and its callees didn't use them, + // then we must skip it. + if !ep_info.dominates_global_use(info) { + log::info!("Skip function {:?}", ir_function.name); + continue; + } + } let id = self.write_function(ir_function, info, ir_module, None)?; self.lookup_function.insert(handle, id); } // and entry points - for (ep_index, ir_ep) in ir_module.entry_points.iter().enumerate() { - let info = mod_info.get_entry_point(ep_index); + for (index, ir_ep) in ir_module.entry_points.iter().enumerate() { + if ep_index.is_some() && ep_index != Some(index) { + continue; + } + let info = mod_info.get_entry_point(index); let ep_instruction = self.write_entry_point(ir_ep, info, ir_module)?; ep_instruction.to_words(&mut self.logical_layout.entry_points); } @@ -1332,11 +1357,25 @@ impl Writer { &mut self, ir_module: &crate::Module, info: &ModuleInfo, + pipeline_options: Option<&PipelineOptions>, words: &mut Vec, ) -> Result<(), Error> { self.reset(); - self.write_logical_layout(ir_module, info)?; + // Try to find the entry point and corresponding index + let ep_index = match pipeline_options { + Some(po) => { + let index = ir_module + .entry_points + .iter() + .position(|ep| po.shader_stage == ep.stage && po.entry_point == ep.name) + .ok_or(Error::EntryPointNotFound)?; + Some(index) + } + None => None, + }; + + self.write_logical_layout(ir_module, info, ep_index)?; self.write_physical_layout(); self.physical_layout.in_words(words); diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index 25d844329..1bad562f9 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -2,6 +2,7 @@ spv_version: (1, 0), spv_capabilities: [ Shader, SampleRateShading ], spv_adjust_coordinate_space: false, + spv_separate_entry_points: true, hlsl_custom: true, hlsl: ( shader_model: V5_1, diff --git a/tests/out/spv/interface.Compute.spvasm b/tests/out/spv/interface.Compute.spvasm new file mode 100644 index 000000000..91397f159 --- /dev/null +++ b/tests/out/spv/interface.Compute.spvasm @@ -0,0 +1,68 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 46 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %32 "compute" %20 %23 %25 %28 %30 +OpExecutionMode %32 LocalSize 1 1 1 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 16 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 1 Offset 4 +OpMemberDecorate %13 2 Offset 8 +OpDecorate %15 ArrayStride 4 +OpDecorate %20 BuiltIn GlobalInvocationId +OpDecorate %23 BuiltIn LocalInvocationId +OpDecorate %25 BuiltIn LocalInvocationIndex +OpDecorate %28 BuiltIn WorkgroupId +OpDecorate %30 BuiltIn NumWorkgroups +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.0 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 1 +%7 = OpConstant %4 0.0 +%9 = OpTypeInt 32 1 +%8 = OpConstant %9 1 +%10 = OpConstant %9 0 +%11 = OpTypeVector %4 4 +%12 = OpTypeStruct %11 %4 +%13 = OpTypeStruct %4 %6 %4 +%14 = OpTypeBool +%15 = OpTypeArray %6 %8 +%16 = OpTypeVector %6 3 +%18 = OpTypePointer Workgroup %15 +%17 = OpVariable %18 Workgroup +%21 = OpTypePointer Input %16 +%20 = OpVariable %21 Input +%23 = OpVariable %21 Input +%26 = OpTypePointer Input %6 +%25 = OpVariable %26 Input +%28 = OpVariable %21 Input +%30 = OpVariable %21 Input +%33 = OpTypeFunction %2 +%35 = OpTypePointer Workgroup %6 +%44 = OpConstant %6 0 +%32 = OpFunction %2 None %33 +%19 = OpLabel +%22 = OpLoad %16 %20 +%24 = OpLoad %16 %23 +%27 = OpLoad %6 %25 +%29 = OpLoad %16 %28 +%31 = OpLoad %16 %30 +OpBranch %34 +%34 = OpLabel +%36 = OpCompositeExtract %6 %22 0 +%37 = OpCompositeExtract %6 %24 0 +%38 = OpIAdd %6 %36 %37 +%39 = OpIAdd %6 %38 %27 +%40 = OpCompositeExtract %6 %29 0 +%41 = OpIAdd %6 %39 %40 +%42 = OpCompositeExtract %6 %31 0 +%43 = OpIAdd %6 %41 %42 +%45 = OpAccessChain %35 %17 %44 +OpStore %45 %43 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.Fragment.spvasm b/tests/out/spv/interface.Fragment.spvasm new file mode 100644 index 000000000..425344990 --- /dev/null +++ b/tests/out/spv/interface.Fragment.spvasm @@ -0,0 +1,78 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 49 +OpCapability Shader +OpCapability SampleRateShading +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %38 "fragment" %19 %22 %25 %28 %31 %33 %35 %37 +OpExecutionMode %38 OriginUpperLeft +OpExecutionMode %38 DepthReplacing +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 16 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 1 Offset 4 +OpMemberDecorate %13 2 Offset 8 +OpDecorate %15 ArrayStride 4 +OpDecorate %19 BuiltIn FragCoord +OpDecorate %22 Location 1 +OpDecorate %25 BuiltIn FrontFacing +OpDecorate %28 BuiltIn SampleId +OpDecorate %31 BuiltIn SampleMask +OpDecorate %33 BuiltIn FragDepth +OpDecorate %35 BuiltIn SampleMask +OpDecorate %37 Location 0 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.0 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 1 +%7 = OpConstant %4 0.0 +%9 = OpTypeInt 32 1 +%8 = OpConstant %9 1 +%10 = OpConstant %9 0 +%11 = OpTypeVector %4 4 +%12 = OpTypeStruct %11 %4 +%13 = OpTypeStruct %4 %6 %4 +%14 = OpTypeBool +%15 = OpTypeArray %6 %8 +%16 = OpTypeVector %6 3 +%20 = OpTypePointer Input %11 +%19 = OpVariable %20 Input +%23 = OpTypePointer Input %4 +%22 = OpVariable %23 Input +%26 = OpTypePointer Input %14 +%25 = OpVariable %26 Input +%29 = OpTypePointer Input %6 +%28 = OpVariable %29 Input +%31 = OpVariable %29 Input +%34 = OpTypePointer Output %4 +%33 = OpVariable %34 Output +%36 = OpTypePointer Output %6 +%35 = OpVariable %36 Output +%37 = OpVariable %34 Output +%39 = OpTypeFunction %2 +%38 = OpFunction %2 None %39 +%17 = OpLabel +%21 = OpLoad %11 %19 +%24 = OpLoad %4 %22 +%18 = OpCompositeConstruct %12 %21 %24 +%27 = OpLoad %14 %25 +%30 = OpLoad %6 %28 +%32 = OpLoad %6 %31 +OpBranch %40 +%40 = OpLabel +%41 = OpShiftLeftLogical %6 %5 %30 +%42 = OpBitwiseAnd %6 %32 %41 +%43 = OpSelect %4 %27 %3 %7 +%44 = OpCompositeExtract %4 %18 1 +%45 = OpCompositeConstruct %13 %44 %42 %43 +%46 = OpCompositeExtract %4 %45 0 +OpStore %33 %46 +%47 = OpCompositeExtract %6 %45 1 +OpStore %35 %47 +%48 = OpCompositeExtract %4 %45 2 +OpStore %37 %48 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.Vertex.spvasm b/tests/out/spv/interface.Vertex.spvasm new file mode 100644 index 000000000..6604f4219 --- /dev/null +++ b/tests/out/spv/interface.Vertex.spvasm @@ -0,0 +1,61 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 39 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %29 "vertex" %18 %21 %23 %25 %27 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 16 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 1 Offset 4 +OpMemberDecorate %13 2 Offset 8 +OpDecorate %15 ArrayStride 4 +OpDecorate %18 BuiltIn VertexIndex +OpDecorate %21 BuiltIn InstanceIndex +OpDecorate %23 Location 10 +OpDecorate %25 BuiltIn Position +OpDecorate %27 Location 1 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.0 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 1 +%7 = OpConstant %4 0.0 +%9 = OpTypeInt 32 1 +%8 = OpConstant %9 1 +%10 = OpConstant %9 0 +%11 = OpTypeVector %4 4 +%12 = OpTypeStruct %11 %4 +%13 = OpTypeStruct %4 %6 %4 +%14 = OpTypeBool +%15 = OpTypeArray %6 %8 +%16 = OpTypeVector %6 3 +%19 = OpTypePointer Input %6 +%18 = OpVariable %19 Input +%21 = OpVariable %19 Input +%23 = OpVariable %19 Input +%26 = OpTypePointer Output %11 +%25 = OpVariable %26 Output +%28 = OpTypePointer Output %4 +%27 = OpVariable %28 Output +%30 = OpTypeFunction %2 +%29 = OpFunction %2 None %30 +%17 = OpLabel +%20 = OpLoad %6 %18 +%22 = OpLoad %6 %21 +%24 = OpLoad %6 %23 +OpBranch %31 +%31 = OpLabel +%32 = OpIAdd %6 %20 %22 +%33 = OpIAdd %6 %32 %24 +%34 = OpCompositeConstruct %11 %3 %3 %3 %3 +%35 = OpConvertUToF %4 %33 +%36 = OpCompositeConstruct %12 %34 %35 +%37 = OpCompositeExtract %11 %36 0 +OpStore %25 %37 +%38 = OpCompositeExtract %4 %36 1 +OpStore %27 %38 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.spvasm b/tests/out/spv/interface.spvasm deleted file mode 100644 index 5af161688..000000000 --- a/tests/out/spv/interface.spvasm +++ /dev/null @@ -1,146 +0,0 @@ -; SPIR-V -; Version: 1.0 -; Generator: rspirv -; Bound: 95 -OpCapability Shader -OpCapability SampleRateShading -%1 = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %31 "vertex" %20 %23 %25 %27 %29 -OpEntryPoint Fragment %60 "fragment" %43 %46 %49 %52 %54 %56 %57 %59 -OpEntryPoint GLCompute %82 "compute" %71 %74 %76 %78 %80 -OpExecutionMode %60 OriginUpperLeft -OpExecutionMode %60 DepthReplacing -OpExecutionMode %82 LocalSize 1 1 1 -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 16 -OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 4 -OpMemberDecorate %13 2 Offset 8 -OpDecorate %15 ArrayStride 4 -OpDecorate %20 BuiltIn VertexIndex -OpDecorate %23 BuiltIn InstanceIndex -OpDecorate %25 Location 10 -OpDecorate %27 BuiltIn Position -OpDecorate %29 Location 1 -OpDecorate %43 BuiltIn FragCoord -OpDecorate %46 Location 1 -OpDecorate %49 BuiltIn FrontFacing -OpDecorate %52 BuiltIn SampleId -OpDecorate %54 BuiltIn SampleMask -OpDecorate %56 BuiltIn FragDepth -OpDecorate %57 BuiltIn SampleMask -OpDecorate %59 Location 0 -OpDecorate %71 BuiltIn GlobalInvocationId -OpDecorate %74 BuiltIn LocalInvocationId -OpDecorate %76 BuiltIn LocalInvocationIndex -OpDecorate %78 BuiltIn WorkgroupId -OpDecorate %80 BuiltIn NumWorkgroups -%2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 1.0 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 1 -%7 = OpConstant %4 0.0 -%9 = OpTypeInt 32 1 -%8 = OpConstant %9 1 -%10 = OpConstant %9 0 -%11 = OpTypeVector %4 4 -%12 = OpTypeStruct %11 %4 -%13 = OpTypeStruct %4 %6 %4 -%14 = OpTypeBool -%15 = OpTypeArray %6 %8 -%16 = OpTypeVector %6 3 -%18 = OpTypePointer Workgroup %15 -%17 = OpVariable %18 Workgroup -%21 = OpTypePointer Input %6 -%20 = OpVariable %21 Input -%23 = OpVariable %21 Input -%25 = OpVariable %21 Input -%28 = OpTypePointer Output %11 -%27 = OpVariable %28 Output -%30 = OpTypePointer Output %4 -%29 = OpVariable %30 Output -%32 = OpTypeFunction %2 -%44 = OpTypePointer Input %11 -%43 = OpVariable %44 Input -%47 = OpTypePointer Input %4 -%46 = OpVariable %47 Input -%50 = OpTypePointer Input %14 -%49 = OpVariable %50 Input -%52 = OpVariable %21 Input -%54 = OpVariable %21 Input -%56 = OpVariable %30 Output -%58 = OpTypePointer Output %6 -%57 = OpVariable %58 Output -%59 = OpVariable %30 Output -%72 = OpTypePointer Input %16 -%71 = OpVariable %72 Input -%74 = OpVariable %72 Input -%76 = OpVariable %21 Input -%78 = OpVariable %72 Input -%80 = OpVariable %72 Input -%84 = OpTypePointer Workgroup %6 -%93 = OpConstant %6 0 -%31 = OpFunction %2 None %32 -%19 = OpLabel -%22 = OpLoad %6 %20 -%24 = OpLoad %6 %23 -%26 = OpLoad %6 %25 -OpBranch %33 -%33 = OpLabel -%34 = OpIAdd %6 %22 %24 -%35 = OpIAdd %6 %34 %26 -%36 = OpCompositeConstruct %11 %3 %3 %3 %3 -%37 = OpConvertUToF %4 %35 -%38 = OpCompositeConstruct %12 %36 %37 -%39 = OpCompositeExtract %11 %38 0 -OpStore %27 %39 -%40 = OpCompositeExtract %4 %38 1 -OpStore %29 %40 -OpReturn -OpFunctionEnd -%60 = OpFunction %2 None %32 -%41 = OpLabel -%45 = OpLoad %11 %43 -%48 = OpLoad %4 %46 -%42 = OpCompositeConstruct %12 %45 %48 -%51 = OpLoad %14 %49 -%53 = OpLoad %6 %52 -%55 = OpLoad %6 %54 -OpBranch %61 -%61 = OpLabel -%62 = OpShiftLeftLogical %6 %5 %53 -%63 = OpBitwiseAnd %6 %55 %62 -%64 = OpSelect %4 %51 %3 %7 -%65 = OpCompositeExtract %4 %42 1 -%66 = OpCompositeConstruct %13 %65 %63 %64 -%67 = OpCompositeExtract %4 %66 0 -OpStore %56 %67 -%68 = OpCompositeExtract %6 %66 1 -OpStore %57 %68 -%69 = OpCompositeExtract %4 %66 2 -OpStore %59 %69 -OpReturn -OpFunctionEnd -%82 = OpFunction %2 None %32 -%70 = OpLabel -%73 = OpLoad %16 %71 -%75 = OpLoad %16 %74 -%77 = OpLoad %6 %76 -%79 = OpLoad %16 %78 -%81 = OpLoad %16 %80 -OpBranch %83 -%83 = OpLabel -%85 = OpCompositeExtract %6 %73 0 -%86 = OpCompositeExtract %6 %75 0 -%87 = OpIAdd %6 %85 %86 -%88 = OpIAdd %6 %87 %77 -%89 = OpCompositeExtract %6 %79 0 -%90 = OpIAdd %6 %88 %89 -%91 = OpCompositeExtract %6 %81 0 -%92 = OpIAdd %6 %90 %91 -%94 = OpAccessChain %84 %17 %93 -OpStore %94 %92 -OpReturn -OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d25aa0df6..b1b153678 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -69,6 +69,9 @@ struct Parameters { #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] #[serde(default)] spv_adjust_coordinate_space: bool, + #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + #[serde(default)] + spv_separate_entry_points: bool, #[cfg(all(feature = "deserialize", feature = "msl-out"))] #[serde(default)] msl: naga::back::msl::Options, @@ -198,13 +201,26 @@ fn write_output_spv( ..spv::Options::default() }; - let spv = spv::write_vec(module, info, &options).unwrap(); - - let dis = rspirv::dr::load_words(spv) - .expect("Produced invalid SPIR-V") - .disassemble(); - - fs::write(destination.join(format!("spv/{}.spvasm", file_name)), dis).unwrap(); + if params.spv_separate_entry_points { + for ep in module.entry_points.iter() { + let pipeline_options = spv::PipelineOptions { + entry_point: ep.name.clone(), + shader_stage: ep.stage, + }; + let spv = spv::write_vec(module, info, &options, Some(&pipeline_options)).unwrap(); + let dis = rspirv::dr::load_words(spv) + .expect("Produced invalid SPIR-V") + .disassemble(); + let path = format!("spv/{}.{}.spvasm", file_name, ep.name); + fs::write(destination.join(path), dis).unwrap(); + } + } else { + let spv = spv::write_vec(module, info, &options, None).unwrap(); + let dis = rspirv::dr::load_words(spv) + .expect("Produced invalid SPIR-V") + .disassemble(); + fs::write(destination.join(format!("spv/{}.spvasm", file_name)), dis).unwrap(); + } } #[cfg(feature = "msl-out")] diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs index be5fa62bf..0567c19f0 100644 --- a/tests/spirv-capabilities.rs +++ b/tests/spirv-capabilities.rs @@ -21,7 +21,7 @@ fn capabilities_used(source: &str) -> naga::FastHashSet { let mut words = vec![]; let mut writer = spv::Writer::new(&spv::Options::default()).unwrap(); - writer.write(&module, &info, &mut words).unwrap(); + writer.write(&module, &info, None, &mut words).unwrap(); writer.get_capabilities_used().clone() } From d4bedafbda6e625825fc2c4fedb7281f177ab383 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 7 Sep 2021 12:58:37 -0700 Subject: [PATCH 1322/2212] Move `#[must_use]` attr on `Capabilities` to where it'll take effect. This was causing warnings in nightly (1.56.0). --- src/valid/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index f6d3d380b..5441fb2ef 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -47,9 +47,9 @@ impl Default for ValidationFlags { } } -#[must_use] bitflags::bitflags! { /// Allowed IR capabilities. + #[must_use] #[derive(Default)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] From c1eed779fe7501dbad4e04c39cf183ee40fe9e7e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 8 Sep 2021 09:35:54 -0400 Subject: [PATCH 1323/2212] Infer types of module-scope let declarations --- src/front/wgsl/mod.rs | 47 +++++++++++++++++++++++++---------------- tests/in/operators.wgsl | 8 +++---- 2 files changed, 33 insertions(+), 22 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index ba3f54a98..5e39a280d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3821,11 +3821,19 @@ impl Parser { lexer.expect(Token::Separator(';'))?; } (Token::Word("let"), _) => { - let (name, name_span, explicit_ty, _access) = self.parse_variable_ident_decl( - lexer, - &mut module.types, - &mut module.constants, - )?; + let (name, name_span) = lexer.next_ident_with_span()?; + let given_ty = if lexer.skip(Token::Separator(':')) { + let (ty, _access) = self.parse_type_decl( + lexer, + None, + &mut module.types, + &mut module.constants, + )?; + Some(ty) + } else { + None + }; + lexer.expect(Token::Operation('='))?; let first_token_span = lexer.next(); let const_handle = self.parse_const_expression_impl( @@ -3835,21 +3843,24 @@ impl Parser { &mut module.types, &mut module.constants, )?; - let con = &module.constants[const_handle]; - let type_match = match con.inner { - crate::ConstantInner::Scalar { width, value } => { - module.types[explicit_ty].inner - == crate::TypeInner::Scalar { - kind: value.scalar_kind(), - width, - } + + if let Some(explicit_ty) = given_ty { + let con = &module.constants[const_handle]; + let type_match = match con.inner { + crate::ConstantInner::Scalar { width, value } => { + module.types[explicit_ty].inner + == crate::TypeInner::Scalar { + kind: value.scalar_kind(), + width, + } + } + crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty, + }; + if !type_match { + return Err(Error::InitializationTypeMismatch(name_span, explicit_ty)); } - crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty, - }; - if !type_match { - return Err(Error::InitializationTypeMismatch(name_span, explicit_ty)); } - //TODO: check `ty` against `const_handle`. + lexer.expect(Token::Separator(';'))?; lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); } diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index e28eb6410..16aad6db1 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -1,8 +1,8 @@ //TODO: support splatting constructors for globals? -let v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); -let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); -let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); -let v_i32_one: vec4 = vec4(1, 1, 1, 1); +let v_f32_one = vec4(1.0, 1.0, 1.0, 1.0); +let v_f32_zero = vec4(0.0, 0.0, 0.0, 0.0); +let v_f32_half = vec4(0.5, 0.5, 0.5, 0.5); +let v_i32_one = vec4(1, 1, 1, 1); fn builtins() -> vec4 { // select() From e226cf3f1d67d0bf91587e392879f0aee109ec42 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 8 Sep 2021 09:45:02 -0400 Subject: [PATCH 1324/2212] spv-out: option to skip OpName for varyings --- src/back/spv/mod.rs | 5 ++++- src/back/spv/writer.rs | 5 ++++- tests/snapshots.rs | 13 ++++++------- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 09e98ab53..0c89821af 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -511,6 +511,9 @@ bitflags::bitflags! { const DEBUG = 0x1; /// Flip Y coordinate of `BuiltIn::Position` output. const ADJUST_COORDINATE_SPACE = 0x2; + /// Emit `OpLabel` for input/output locations. + /// Some drivers treat it as semantic, not allowing any conflicts. + const LABEL_VARYINGS = 0x4; } } @@ -535,7 +538,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { - let mut flags = WriterFlags::ADJUST_COORDINATE_SPACE; + let mut flags = WriterFlags::ADJUST_COORDINATE_SPACE | WriterFlags::LABEL_VARYINGS; if cfg!(debug_assertions) { flags |= WriterFlags::DEBUG; } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 943b96dcf..2501c9125 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1038,7 +1038,10 @@ impl Writer { Instruction::variable(pointer_type_id, id, class, None) .to_words(&mut self.logical_layout.declarations); - if self.flags.contains(WriterFlags::DEBUG) { + if self + .flags + .contains(WriterFlags::DEBUG | WriterFlags::LABEL_VARYINGS) + { if let Some(name) = debug_name { self.debugs.push(Instruction::name(id, name)); } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b1b153678..020368148 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -176,13 +176,12 @@ fn write_output_spv( use naga::back::spv; use rspirv::binary::Disassemble; - let mut flags = spv::WriterFlags::empty(); - if params.spv_debug { - flags |= spv::WriterFlags::DEBUG; - } - if params.spv_adjust_coordinate_space { - flags |= spv::WriterFlags::ADJUST_COORDINATE_SPACE; - } + let mut flags = spv::WriterFlags::LABEL_VARYINGS; + flags.set(spv::WriterFlags::DEBUG, params.spv_debug); + flags.set( + spv::WriterFlags::ADJUST_COORDINATE_SPACE, + params.spv_adjust_coordinate_space, + ); let options = spv::Options { lang_version: params.spv_version, flags, From ce676cf13090b87e1405640ea8ee43e1a1666005 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 7 Sep 2021 23:21:05 -0700 Subject: [PATCH 1325/2212] [wgsl-out] Correct production of `*` and `&` operators. Fixes #1322. --- src/back/wgsl/writer.rs | 241 +++++++++++++++++++++++++--------------- 1 file changed, 150 insertions(+), 91 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index f5df2f6fb..3e40c8183 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -22,6 +22,85 @@ enum Attribute { WorkGroupSize([u32; 3]), } +/// The WGSL form that `write_expr_with_indirection` should use to render a Naga +/// expression. +/// +/// Sometimes a Naga `Expression` alone doesn't provide enough information to +/// choose the right rendering for it in WGSL. For example, one natural WGSL +/// rendering of a Naga `LocalVariable(x)` expression might be `&x`, since +/// `LocalVariable` produces a pointer to the local variable's storage. But when +/// rendering a `Store` statement, the `pointer` operand must be the left hand +/// side of a WGSL assignment, so the proper rendering is `x`. +/// +/// The caller of `write_expr_with_indirection` must provide an `Expected` value +/// to indicate how ambiguous expressions should be rendered. +#[derive(Clone, Copy, Debug)] +enum Indirection { + /// Render pointer-construction expressions as WGSL `ptr`-typed expressions. + /// + /// This is the right choice for most cases. Whenever a Naga pointer + /// expression is not the `pointer` operand of a `Load` or `Store`, it + /// must be a WGSL pointer expression. + Ordinary, + + /// Render pointer-construction expressions as WGSL reference-typed + /// expressions. + /// + /// For example, this is the right choice for the `pointer` operand when + /// rendering a `Store` statement as a WGSL assignment. + Reference, +} + +/// Return the sort of indirection that `expr`'s plain form evaluates to. +/// +/// An expression's 'plain form' is the most general rendition of that +/// expression into WGSL, lacking `&` or `*` operators: +/// +/// - The plain form of `LocalVariable(x)` is simply `x`, which is a reference +/// to the local variable's storage. +/// +/// - The plain form of `GlobalVariable(g)` is simply `g`, which is usually a +/// reference to the global variable's storage. However, globals in the +/// `Handle` storage class are immutable, and `GlobalVariable` expressions for +/// those produce the value directly, not a pointer to it. Such +/// `GlobalVariable` expressions are `Ordinary`. +/// +/// - `Access` and `AccessIndex` are `Reference` when their `base` operand is a +/// pointer. If they are applied directly to a composite value, they are +/// `Ordinary`. +/// +/// Note that `FunctionArgument` expressions are never `Reference`, even when +/// the argument's type is `Pointer`. `FunctionArgument` always evaluates to the +/// argument's value directly, so any pointer it produces is merely the value +/// passed by the caller. +fn plain_form_indirection( + expr: Handle, + module: &Module, + func_ctx: &back::FunctionCtx<'_>, +) -> Indirection { + use crate::Expression as Ex; + match func_ctx.expressions[expr] { + Ex::LocalVariable(_) => Indirection::Reference, + Ex::GlobalVariable(handle) => { + let global = &module.global_variables[handle]; + match global.class { + crate::StorageClass::Handle => Indirection::Ordinary, + _ => Indirection::Reference, + } + } + Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => { + let base_ty = func_ctx.info[base].ty.inner_with(&module.types); + match *base_ty { + crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { + Indirection::Reference + } + _ => Indirection::Ordinary, + } + } + _ => Indirection::Ordinary, + } +} + pub struct Writer { out: W, names: crate::FastHashMap, @@ -693,28 +772,26 @@ impl Writer { } write!(self.out, "{}", level)?; - let (is_ptr, is_atomic) = match *func_ctx.info[pointer].ty.inner_with(&module.types) - { - crate::TypeInner::Pointer { base, .. } => ( - func_ctx.expressions[pointer].should_deref(), - match module.types[base].inner { - crate::TypeInner::Atomic { .. } => true, - _ => false, - }, - ), - _ => (false, false), + let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { + crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { + crate::TypeInner::Atomic { .. } => true, + _ => false, + }, + _ => false, }; if is_atomic { write!(self.out, "atomicStore(")?; - if !is_ptr { - write!(self.out, "&")?; - } self.write_expr(module, pointer, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, value, func_ctx)?; write!(self.out, ")")?; } else { - self.write_expr(module, pointer, func_ctx)?; + self.write_expr_with_indirection( + module, + pointer, + func_ctx, + Indirection::Reference, + )?; write!(self.out, " = ")?; self.write_expr(module, value, func_ctx)?; } @@ -754,13 +831,8 @@ impl Writer { self.start_named_expr(module, result, func_ctx, &res_name)?; self.named_expressions.insert(result, res_name); - let is_ptr = func_ctx.expressions[pointer].should_deref(); - let fun_str = fun.to_wgsl(); write!(self.out, "atomic{}(", fun_str)?; - if !is_ptr { - write!(self.out, "&")?; - } self.write_expr(module, pointer, func_ctx)?; if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun { write!(self.out, ", ")?; @@ -921,15 +993,36 @@ impl Writer { Ok(()) } - /// Helper method to write expressions + /// Write the ordinary WGSL form of `expr`. /// - /// # Notes - /// Doesn't add any newlines or leading/trailing spaces + /// See `write_expr_with_indirection` for details. fn write_expr( &mut self, module: &Module, expr: Handle, func_ctx: &back::FunctionCtx<'_>, + ) -> BackendResult { + self.write_expr_with_indirection(module, expr, func_ctx, Indirection::Ordinary) + } + + /// Write `expr` as a WGSL expression with the requested indirection. + /// + /// In terms of the WGSL grammar, the resulting expression is a + /// `singular_expression`. It may be parenthesized. This makes it suitable + /// for use as the operand of a unary or binary operator without worrying + /// about precedence. + /// + /// This does not produce newlines or indentation. + /// + /// The `requested` argument indicates (roughly) whether Naga + /// `Pointer`-valued expressions represent WGSL references or pointers. See + /// `Indirection` for details. + fn write_expr_with_indirection( + &mut self, + module: &Module, + expr: Handle, + func_ctx: &back::FunctionCtx<'_>, + requested: Indirection, ) -> BackendResult { use crate::Expression; @@ -938,8 +1031,25 @@ impl Writer { return Ok(()); } + // If the plain form of the expression is not what we need, emit the + // operator necessary to correct that. + let plain = plain_form_indirection(expr, module, func_ctx); + match (requested, plain) { + (Indirection::Ordinary, Indirection::Reference) => write!(self.out, "&")?, + (Indirection::Reference, Indirection::Ordinary) => write!(self.out, "*")?, + (_, _) => {} + } + let expression = &func_ctx.expressions[expr]; + // Write the plain WGSL form of a Naga expression. + // + // The plain form of `LocalVariable` and `GlobalVariable` expressions is + // simply the variable name; `*` and `&` operators are never emitted. + // + // The plain form of `Access` and `AccessIndex` expressions are WGSL + // `postfix_expression` forms for member/component access and + // subscripting. match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::Compose { ty, ref components } => { @@ -1001,7 +1111,7 @@ impl Writer { } // TODO: copy-paste from glsl-out Expression::Access { base, index } => { - self.write_expr(module, base, func_ctx)?; + self.write_expr_with_indirection(module, base, func_ctx, plain)?; write!(self.out, "[")?; self.write_expr(module, index, func_ctx)?; write!(self.out, "]")? @@ -1011,18 +1121,7 @@ impl Writer { let base_ty_res = &func_ctx.info[base].ty; let mut resolved = base_ty_res.inner_with(&module.types); - let deref = match *resolved { - TypeInner::Pointer { .. } => func_ctx.expressions[base].should_deref(), - _ => false, - }; - - if deref { - write!(self.out, "(*")?; - } - self.write_expr(module, base, func_ctx)?; - if deref { - write!(self.out, ")")?; - } + self.write_expr_with_indirection(module, base, func_ctx, plain)?; let base_ty_handle = match *resolved { TypeInner::Pointer { base, class: _ } => { @@ -1226,30 +1325,25 @@ impl Writer { write!(self.out, ")")?; } Expression::Load { pointer } => { - let (is_pointer, is_atomic) = - match *func_ctx.info[pointer].ty.inner_with(&module.types) { - crate::TypeInner::Pointer { base, .. } => ( - func_ctx.expressions[pointer].should_deref(), - match module.types[base].inner { - crate::TypeInner::Atomic { .. } => true, - _ => false, - }, - ), - _ => (false, false), - }; + let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { + crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { + crate::TypeInner::Atomic { .. } => true, + _ => false, + }, + _ => false, + }; + if is_atomic { write!(self.out, "atomicLoad(")?; - if !is_pointer { - // Write an indirection in case the underlying - // expression isn't a pointer but a reference - write!(self.out, "&")?; - } - } else if is_pointer { - write!(self.out, "*")?; - } - self.write_expr(module, pointer, func_ctx)?; - if is_atomic { + self.write_expr(module, pointer, func_ctx)?; write!(self.out, ")")?; + } else { + self.write_expr_with_indirection( + module, + pointer, + func_ctx, + Indirection::Reference, + )?; } } Expression::LocalVariable(handle) => { @@ -1257,9 +1351,6 @@ impl Writer { } Expression::ArrayLength(expr) => { write!(self.out, "arrayLength(")?; - if is_deref_required(expr, module, func_ctx.info) { - write!(self.out, "&")?; - }; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")?; } @@ -1632,21 +1723,6 @@ impl Writer { } } -impl crate::Expression { - /// Wether an expression should be dereferenced, this is false when the - /// expression returns a reference instead of a pointer - fn should_deref(&self) -> bool { - match *self { - // Variables in the typifier have pointer types but in wgsl they - // have reference types and shouldn't be dereferenced - crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) - // Access chains might have pointer types but wgsl considers them as references - | crate::Expression::AccessIndex {..} | crate::Expression::Access {..} => false, - _ => true, - } - } -} - fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { use crate::BuiltIn as Bi; @@ -1797,23 +1873,6 @@ fn map_binding_to_attribute( } } -fn is_deref_required( - expr: Handle, - module: &Module, - info: &valid::FunctionInfo, -) -> bool { - let base_ty_res = &info[expr].ty; - let resolved = base_ty_res.inner_with(&module.types); - match *resolved { - TypeInner::Pointer { base, class: _ } => match module.types[base].inner { - TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Array { .. } => true, - _ => false, - }, - TypeInner::ValuePointer { .. } => true, - _ => false, - } -} - /// Helper function that check that expression don't access to structure member with unsupported builtin. fn access_to_unsupported_builtin( expr: Handle, From 135df311b143c4ce033e8d49eec1eea57c704049 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 9 Sep 2021 15:39:37 -0400 Subject: [PATCH 1326/2212] hlsl: avoid using texture keyword --- src/back/hlsl/help.rs | 2 +- tests/out/hlsl/image.hlsl | 80 +++++++++++++++++++-------------------- 2 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index a98cc3859..4d9265d72 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -244,7 +244,7 @@ impl<'a, W: Write> super::Writer<'a, W> { ImageDimension as IDim, }; - const ARGUMENT_VARIABLE_NAME: &str = "texture"; + const ARGUMENT_VARIABLE_NAME: &str = "tex"; const RETURN_VARIABLE_NAME: &str = "ret"; const MIP_LEVEL_PARAM: &str = "mip_level"; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 902418a04..d53a95844 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -17,10 +17,10 @@ SamplerState sampler_reg : register(s0, space1); SamplerComparisonState sampler_cmp : register(s1, space1); Texture2D image_2d_depth : register(t2, space1); -int2 NagaRWDimensions2D(RWTexture2D texture) +int2 NagaRWDimensions2D(RWTexture2D tex) { uint4 ret; - texture.GetDimensions(ret.x, ret.y); + tex.GetDimensions(ret.x, ret.y); return ret.xy; } @@ -38,136 +38,136 @@ void main(uint3 local_id : SV_GroupThreadID) return; } -int NagaDimensions1D(Texture1D texture) +int NagaDimensions1D(Texture1D tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y); + tex.GetDimensions(0, ret.x, ret.y); return ret.x; } -int2 NagaDimensions2D(Texture2D texture) +int2 NagaDimensions2D(Texture2D tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z); + tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.xy; } -int NagaNumLevels2D(Texture2D texture) +int NagaNumLevels2D(Texture2D tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z); + tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.z; } -int2 NagaMipDimensions2D(Texture2D texture, uint mip_level) +int2 NagaMipDimensions2D(Texture2D tex, uint mip_level) { uint4 ret; - texture.GetDimensions(mip_level, ret.x, ret.y, ret.z); + tex.GetDimensions(mip_level, ret.x, ret.y, ret.z); return ret.xy; } -int2 NagaDimensions2DArray(Texture2DArray texture) +int2 NagaDimensions2DArray(Texture2DArray tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int NagaNumLevels2DArray(Texture2DArray texture) +int NagaNumLevels2DArray(Texture2DArray tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int2 NagaMipDimensions2DArray(Texture2DArray texture, uint mip_level) +int2 NagaMipDimensions2DArray(Texture2DArray tex, uint mip_level) { uint4 ret; - texture.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int NagaNumLayers2DArray(Texture2DArray texture) +int NagaNumLayers2DArray(Texture2DArray tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int2 NagaDimensionsCube(TextureCube texture) +int2 NagaDimensionsCube(TextureCube tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z); + tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.xy; } -int NagaNumLevelsCube(TextureCube texture) +int NagaNumLevelsCube(TextureCube tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z); + tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.z; } -int2 NagaMipDimensionsCube(TextureCube texture, uint mip_level) +int2 NagaMipDimensionsCube(TextureCube tex, uint mip_level) { uint4 ret; - texture.GetDimensions(mip_level, ret.x, ret.y, ret.z); + tex.GetDimensions(mip_level, ret.x, ret.y, ret.z); return ret.xy; } -int2 NagaDimensionsCubeArray(TextureCubeArray texture) +int2 NagaDimensionsCubeArray(TextureCubeArray tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int NagaNumLevelsCubeArray(TextureCubeArray texture) +int NagaNumLevelsCubeArray(TextureCubeArray tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int2 NagaMipDimensionsCubeArray(TextureCubeArray texture, uint mip_level) +int2 NagaMipDimensionsCubeArray(TextureCubeArray tex, uint mip_level) { uint4 ret; - texture.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int NagaNumLayersCubeArray(TextureCubeArray texture) +int NagaNumLayersCubeArray(TextureCubeArray tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int3 NagaDimensions3D(Texture3D texture) +int3 NagaDimensions3D(Texture3D tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.xyz; } -int NagaNumLevels3D(Texture3D texture) +int NagaNumLevels3D(Texture3D tex) { uint4 ret; - texture.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int3 NagaMipDimensions3D(Texture3D texture, uint mip_level) +int3 NagaMipDimensions3D(Texture3D tex, uint mip_level) { uint4 ret; - texture.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); + tex.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); return ret.xyz; } -int NagaMSNumSamples2D(Texture2DMS texture) +int NagaMSNumSamples2D(Texture2DMS tex) { uint4 ret; - texture.GetDimensions(ret.x, ret.y, ret.z); + tex.GetDimensions(ret.x, ret.y, ret.z); return ret.z; } From 7681f4a21f554412dad494809855edb8367f8994 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 9 Sep 2021 21:04:38 -0400 Subject: [PATCH 1327/2212] msl-out: fix as_type expressions --- src/back/msl/writer.rs | 25 +++- tests/in/operators.wgsl | 4 +- tests/out/glsl/operators.main.Compute.glsl | 3 +- tests/out/hlsl/operators.hlsl | 3 +- tests/out/msl/access.msl | 2 +- tests/out/msl/image.msl | 2 +- tests/out/msl/operators.msl | 7 +- tests/out/spv/operators.spvasm | 144 +++++++++++---------- tests/out/wgsl/operators.wgsl | 3 +- 9 files changed, 107 insertions(+), 86 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index da96424df..0bedf3287 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1194,11 +1194,9 @@ impl Writer { convert, } => { let scalar = scalar_kind_string(kind); - let (size, width) = match *context.resolve_type(expr) { - crate::TypeInner::Scalar { width, .. } => ("", width), - crate::TypeInner::Vector { size, width, .. } => { - (back::vector_size_str(size), width) - } + let width = match *context.resolve_type(expr) { + crate::TypeInner::Scalar { width, .. } + | crate::TypeInner::Vector { width, .. } => width, _ => return Err(Error::Validation), }; let op = match convert { @@ -1209,7 +1207,22 @@ impl Writer { Some(_) => return Err(Error::Validation), None => "as_type", }; - write!(self.out, "{}<{}{}>(", op, scalar, size)?; + write!(self.out, "{}<", op)?; + match *context.resolve_type(expr) { + crate::TypeInner::Vector { size, .. } => { + write!( + self.out, + "{}::{}{}", + NAMESPACE, + scalar, + back::vector_size_str(size) + )?; + } + _ => { + write!(self.out, "{}", scalar)?; + } + } + write!(self.out, ">(")?; self.put_expression(expr, context, true)?; write!(self.out, ")")?; } diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 16aad6db1..1b7ec7585 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -16,8 +16,10 @@ fn builtins() -> vec4 { // bitcast() let b1 = bitcast(v_i32_one.x); let b2 = bitcast>(v_i32_one); + // convert + let v_i32_zero = vec4(v_f32_zero); // done - return vec4(vec4(s1)) + s2 + m1 + m2 + b1 + b2; + return vec4(vec4(s1) + v_i32_zero) + s2 + m1 + m2 + b1 + b2; } fn splat() -> vec4 { diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index d66947dff..6a4edf707 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -19,7 +19,8 @@ vec4 builtins() { vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); float b1_ = intBitsToFloat(ivec4(1, 1, 1, 1).x); vec4 b2_ = intBitsToFloat(ivec4(1, 1, 1, 1)); - return (((((vec4(ivec4(s1_)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); + ivec4 v_i32_zero = ivec4(vec4(0.0, 0.0, 0.0, 0.0)); + return (((((vec4((ivec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } vec4 splat() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index cf96e4618..d9d48d485 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -17,7 +17,8 @@ float4 builtins() float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); float b1_ = float(int4(1, 1, 1, 1).x); float4 b2_ = float4(int4(1, 1, 1, 1)); - return (((((float4(int4(s1_.xxxx)) + s2_) + m1_) + m2_) + float4(b1_.xxxx)) + b2_); + int4 v_i32_zero = int4(float4(0.0, 0.0, 0.0, 0.0)); + return (((((float4((int4(s1_.xxxx) + v_i32_zero)) + s2_) + m1_) + m2_) + float4(b1_.xxxx)) + b2_); } float4 splat() diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index cb9f88101..15505a5dd 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -46,7 +46,7 @@ vertex fooOutput foo( for(int _i=0; _i<5; ++_i) c.inner[_i] = type9 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; - return fooOutput { matrix * static_cast(metal::int4(value)) }; + return fooOutput { matrix * static_cast(metal::int4(value)) }; } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index a9379f897..ee635ab81 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -16,7 +16,7 @@ kernel void main1( , metal::texture1d image_dst [[user(fake0)]] ) { metal::int2 dim = int2(image_storage_src.get_width(), image_storage_src.get_height()); - metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); + metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); float value3_ = image_depth_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index e5100def7..61afdd52c 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -19,15 +19,16 @@ metal::float4 builtins( metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half); metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.10000000149011612); float b1_ = as_type(v_i32_one.x); - metal::float4 b2_ = as_type(v_i32_one); - return ((((static_cast(metal::int4(s1_)) + s2_) + m1_) + m2_) + metal::float4(b1_)) + b2_; + metal::float4 b2_ = as_type(v_i32_one); + metal::int4 v_i32_zero = static_cast(v_f32_zero); + return ((((static_cast(metal::int4(s1_) + v_i32_zero) + s2_) + m1_) + m2_) + metal::float4(b1_)) + b2_; } metal::float4 splat( ) { metal::float2 a = ((metal::float2(1.0) + metal::float2(2.0)) - metal::float2(3.0)) / metal::float2(4.0); metal::int4 b = metal::int4(5) % metal::int4(2); - return a.xyxy + static_cast(b); + return a.xyxy + static_cast(b); } int unary( diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index dc1261e90..81708762d 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 99 +; Bound: 101 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %92 "main" -OpExecutionMode %92 LocalSize 1 1 1 +OpEntryPoint GLCompute %94 "main" +OpExecutionMode %94 LocalSize 1 1 1 OpMemberDecorate %22 0 Offset 0 OpMemberDecorate %22 1 Offset 16 %2 = OpTypeVoid @@ -35,15 +35,15 @@ OpMemberDecorate %22 1 Offset 16 %25 = OpConstantComposite %19 %6 %6 %6 %6 %26 = OpConstantComposite %20 %7 %7 %7 %7 %29 = OpTypeFunction %19 -%53 = OpTypeVector %4 2 -%69 = OpTypeFunction %8 -%76 = OpConstantNull %8 -%78 = OpTypePointer Function %22 -%81 = OpTypeFunction %4 -%85 = OpTypePointer Function %19 -%87 = OpTypeInt 32 0 -%86 = OpConstant %87 0 -%93 = OpTypeFunction %2 +%55 = OpTypeVector %4 2 +%71 = OpTypeFunction %8 +%78 = OpConstantNull %8 +%80 = OpTypePointer Function %22 +%83 = OpTypeFunction %4 +%87 = OpTypePointer Function %19 +%89 = OpTypeInt 32 0 +%88 = OpConstant %89 0 +%95 = OpTypeFunction %2 %28 = OpFunction %19 None %29 %27 = OpLabel OpBranch %30 @@ -59,70 +59,72 @@ OpBranch %30 %39 = OpCompositeExtract %8 %26 0 %40 = OpBitcast %4 %39 %41 = OpBitcast %19 %26 -%42 = OpCompositeConstruct %20 %31 %31 %31 %31 -%43 = OpConvertSToF %19 %42 -%44 = OpFAdd %19 %43 %32 -%45 = OpFAdd %19 %44 %36 -%46 = OpFAdd %19 %45 %37 -%47 = OpCompositeConstruct %19 %40 %40 %40 %40 -%48 = OpFAdd %19 %46 %47 -%49 = OpFAdd %19 %48 %41 -OpReturnValue %49 +%42 = OpConvertFToS %20 %24 +%43 = OpCompositeConstruct %20 %31 %31 %31 %31 +%44 = OpIAdd %20 %43 %42 +%45 = OpConvertSToF %19 %44 +%46 = OpFAdd %19 %45 %32 +%47 = OpFAdd %19 %46 %36 +%48 = OpFAdd %19 %47 %37 +%49 = OpCompositeConstruct %19 %40 %40 %40 %40 +%50 = OpFAdd %19 %48 %49 +%51 = OpFAdd %19 %50 %41 +OpReturnValue %51 OpFunctionEnd -%51 = OpFunction %19 None %29 -%50 = OpLabel -OpBranch %52 +%53 = OpFunction %19 None %29 %52 = OpLabel -%54 = OpCompositeConstruct %53 %14 %14 -%55 = OpCompositeConstruct %53 %3 %3 -%56 = OpFAdd %53 %55 %54 -%57 = OpCompositeConstruct %53 %15 %15 -%58 = OpFSub %53 %56 %57 -%59 = OpCompositeConstruct %53 %16 %16 -%60 = OpFDiv %53 %58 %59 -%61 = OpCompositeConstruct %20 %17 %17 %17 %17 -%62 = OpCompositeConstruct %20 %18 %18 %18 %18 -%63 = OpSMod %20 %61 %62 -%64 = OpVectorShuffle %19 %60 %60 0 1 0 1 -%65 = OpConvertSToF %19 %63 -%66 = OpFAdd %19 %64 %65 -OpReturnValue %66 +OpBranch %54 +%54 = OpLabel +%56 = OpCompositeConstruct %55 %14 %14 +%57 = OpCompositeConstruct %55 %3 %3 +%58 = OpFAdd %55 %57 %56 +%59 = OpCompositeConstruct %55 %15 %15 +%60 = OpFSub %55 %58 %59 +%61 = OpCompositeConstruct %55 %16 %16 +%62 = OpFDiv %55 %60 %61 +%63 = OpCompositeConstruct %20 %17 %17 %17 %17 +%64 = OpCompositeConstruct %20 %18 %18 %18 %18 +%65 = OpSMod %20 %63 %64 +%66 = OpVectorShuffle %19 %62 %62 0 1 0 1 +%67 = OpConvertSToF %19 %65 +%68 = OpFAdd %19 %66 %67 +OpReturnValue %68 OpFunctionEnd -%68 = OpFunction %8 None %69 -%67 = OpLabel -OpBranch %70 -%70 = OpLabel -%71 = OpLogicalNot %10 %9 -OpSelectionMerge %72 None -OpBranchConditional %71 %73 %74 -%73 = OpLabel -OpReturnValue %7 -%74 = OpLabel -%75 = OpNot %8 %7 -OpReturnValue %75 +%70 = OpFunction %8 None %71 +%69 = OpLabel +OpBranch %72 %72 = OpLabel -OpReturnValue %76 +%73 = OpLogicalNot %10 %9 +OpSelectionMerge %74 None +OpBranchConditional %73 %75 %76 +%75 = OpLabel +OpReturnValue %7 +%76 = OpLabel +%77 = OpNot %8 %7 +OpReturnValue %77 +%74 = OpLabel +OpReturnValue %78 OpFunctionEnd -%80 = OpFunction %4 None %81 -%79 = OpLabel -%77 = OpVariable %78 Function -OpBranch %82 -%82 = OpLabel -%83 = OpCompositeConstruct %19 %3 %3 %3 %3 -%84 = OpCompositeConstruct %22 %83 %7 -OpStore %77 %84 -%88 = OpAccessChain %85 %77 %86 -%89 = OpLoad %19 %88 -%90 = OpCompositeExtract %4 %89 0 -OpReturnValue %90 +%82 = OpFunction %4 None %83 +%81 = OpLabel +%79 = OpVariable %80 Function +OpBranch %84 +%84 = OpLabel +%85 = OpCompositeConstruct %19 %3 %3 %3 %3 +%86 = OpCompositeConstruct %22 %85 %7 +OpStore %79 %86 +%90 = OpAccessChain %87 %79 %88 +%91 = OpLoad %19 %90 +%92 = OpCompositeExtract %4 %91 0 +OpReturnValue %92 OpFunctionEnd -%92 = OpFunction %2 None %93 -%91 = OpLabel -OpBranch %94 -%94 = OpLabel -%95 = OpFunctionCall %19 %28 -%96 = OpFunctionCall %19 %51 -%97 = OpFunctionCall %8 %68 -%98 = OpFunctionCall %4 %80 +%94 = OpFunction %2 None %95 +%93 = OpLabel +OpBranch %96 +%96 = OpLabel +%97 = OpFunctionCall %19 %28 +%98 = OpFunctionCall %19 %53 +%99 = OpFunctionCall %8 %70 +%100 = OpFunctionCall %4 %82 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index b3f245b5d..08006faaf 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -15,7 +15,8 @@ fn builtins() -> vec4 { let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); let b1_: f32 = bitcast(vec4(1, 1, 1, 1).x); let b2_: vec4 = vec4(vec4(1, 1, 1, 1)); - return (((((vec4(vec4(s1_)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); + let v_i32_zero: vec4 = vec4(vec4(0.0, 0.0, 0.0, 0.0)); + return (((((vec4((vec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } fn splat() -> vec4 { From 3049f63cad4b4b2069139722c07668b3e7dc010f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 10 Sep 2021 16:51:05 +0100 Subject: [PATCH 1328/2212] [spv-in] new block parser (#1294) * [spv-in] New two pass parser based * [spv-in] Allow expressions defined in dominant block in different scopes * Make the patch non breaking * [spv-in] Allow scope transfers in phi instructions * [spv-in] Remove unused stuff * [spv-in] Handle switch merges as breaks * Remove no longer needed stuff * Revert some changes to prepare to merge * Remove dead code * Don't spill into local if in scope * [spv-in] Documentation, comments, some renaming for clarity. * Address comments Co-authored-by: Jim Blandy --- Cargo.toml | 3 +- cli/src/main.rs | 23 +- src/block.rs | 6 + src/front/spv/flow.rs | 1164 ------------------------------------- src/front/spv/function.rs | 268 +++++++-- src/front/spv/image.rs | 121 +++- src/front/spv/mod.rs | 1098 +++++++++++++++++++++++++++------- tests/out/ir/shadow.ron | 1 + tests/snapshots.rs | 2 +- 9 files changed, 1224 insertions(+), 1462 deletions(-) delete mode 100644 src/front/spv/flow.rs diff --git a/Cargo.toml b/Cargo.toml index 352ad9845..935ece3f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,6 @@ spirv = { version = "0.2", optional = true } thiserror = "1.0.21" serde = { version = "1.0", features = ["derive"], optional = true } petgraph = { version ="0.6", optional = true } -rose_tree = { version ="0.3", optional = true } pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } @@ -39,7 +38,7 @@ glsl-out = ["petgraph"] msl-out = [] serialize = ["serde"] deserialize = ["serde"] -spv-in = ["petgraph", "spirv", "rose_tree"] +spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] wgsl-in = ["codespan-reporting", "hexf-parse"] wgsl-out = [] diff --git a/cli/src/main.rs b/cli/src/main.rs index 1fa20373f..7bda20c54 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -6,9 +6,9 @@ use std::{error::Error, fmt, path::Path, str::FromStr}; /// Translate shaders to different formats #[derive(argh::FromArgs, Debug, Clone)] struct Args { - /// validate the shader during translation - #[argh(switch)] - validate: bool, + /// bitmask of the ValidationFlags to be used, use 0 to disable validation + #[argh(option)] + validate: Option, /// what policy to use for index bounds checking for arrays, vectors, and /// matrices. @@ -37,9 +37,9 @@ struct Args { #[argh(option)] image_bounds_check_policy: Option, - /// directory to dump the SPIR-V flow dump to + /// directory to dump the SPIR-V block context dump to #[argh(option)] - flow_dir: Option, + block_ctx_dir: Option, /// the shader entrypoint to use when compiling to GLSL #[argh(option)] @@ -130,7 +130,7 @@ struct Parameters { bounds_check_policies: naga::back::BoundsCheckPolicies, entry_point: Option, spv_adjust_coordinate_space: bool, - spv_flow_dump_prefix: Option, + spv_block_ctx_dump_prefix: Option, spv: naga::back::spv::Options, msl: naga::back::msl::Options, glsl: naga::back::glsl::Options, @@ -201,8 +201,9 @@ fn run() -> Result<(), Box> { let output_paths = args.output; // Update parameters from commandline arguments - if args.validate { - params.validation_flags = naga::valid::ValidationFlags::all(); + if let Some(bits) = args.validate { + params.validation_flags = naga::valid::ValidationFlags::from_bits(bits) + .ok_or(CliError("Invalid validation flags"))?; } if let Some(policy) = args.index_bounds_check_policy { params.bounds_check_policies.index = policy.0; @@ -215,7 +216,7 @@ fn run() -> Result<(), Box> { Some(arg) => arg.0, None => params.bounds_check_policies.index, }; - params.spv_flow_dump_prefix = args.flow_dir; + params.spv_block_ctx_dump_prefix = args.block_ctx_dir; params.entry_point = args.entry_point; if let Some(version) = args.profile { params.glsl.version = version.0; @@ -234,7 +235,9 @@ fn run() -> Result<(), Box> { let options = naga::front::spv::Options { adjust_coordinate_space: params.spv_adjust_coordinate_space, strict_capabilities: false, - flow_graph_dump_prefix: params.spv_flow_dump_prefix.map(std::path::PathBuf::from), + block_ctx_dump_prefix: params + .spv_block_ctx_dump_prefix + .map(std::path::PathBuf::from), }; let input = fs::read(input_path)?; naga::front::spv::parse_u8_slice(&input, &options)? diff --git a/src/block.rs b/src/block.rs index b46293eab..5b832ba8f 100644 --- a/src/block.rs +++ b/src/block.rs @@ -58,6 +58,12 @@ impl Block { self.body.extend(other.body); } + pub fn append(&mut self, other: &mut Self) { + #[cfg(feature = "span")] + self.span_info.append(&mut other.span_info); + self.body.append(&mut other.body); + } + pub fn cull + Clone>(&mut self, range: R) { #[cfg(feature = "span")] self.span_info.drain(range.clone()); diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs deleted file mode 100644 index 4362c5d23..000000000 --- a/src/front/spv/flow.rs +++ /dev/null @@ -1,1164 +0,0 @@ -#![allow(dead_code)] - -use super::error::Error; -///! see https://en.wikipedia.org/wiki/Control-flow_graph -///! see https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#_a_id_structuredcontrolflow_a_structured_control_flow -use super::{ - function::{BlockId, MergeInstruction, Terminator}, - LookupExpression, PhiInstruction, -}; - -use crate::FastHashMap; - -use petgraph::{ - algo::has_path_connecting, - graph::{node_index, NodeIndex}, - visit::EdgeRef, - Directed, Direction, -}; - -use std::fmt::Write; - -/// Index of a block node in the `ControlFlowGraph`. -type BlockNodeIndex = NodeIndex; - -/// Internal representation of a CFG constisting of function's basic blocks. -type ControlFlowGraph = petgraph::Graph; - -type ConstructNodeIndex = NodeIndex; - -type ConstructsGraph = rose_tree::RoseTree; - -/// Control flow graph (CFG) containing relationships between blocks. -pub(super) struct FlowGraph { - /// - flow: ControlFlowGraph, - - /// - constructs: ConstructsGraph, - - /// Block ID to Node index mapping. Internal helper to speed up the classification. - block_to_node: FastHashMap, - - /// Reversed post-order traversal of the `flow` graph. - traversal_order: Vec, -} - -impl FlowGraph { - /// Creates empty flow graph. - pub(super) fn new() -> Self { - Self { - flow: ControlFlowGraph::default(), - constructs: ConstructsGraph::new(ConstructNode { - ty: ConstructType::Function, - ..Default::default() - }) - .0, - block_to_node: FastHashMap::default(), - traversal_order: Vec::new(), - } - } - - /// Add a control flow node. - pub(super) fn add_node(&mut self, node: ControlFlowNode) { - let block_id = node.id; - let node_index = self.flow.add_node(node); - self.block_to_node.insert(block_id, node_index); - } - - /// - /// 1. Creates edges in the CFG. - /// 2. Computes the traversal order - /// 3. Finds constructs - /// 4. Classifies types of blocks and edges in the CFG. - pub(super) fn classify(&mut self) { - let block_to_node = &mut self.block_to_node; - - // 1. - // Add all edges - // Classify Nodes as one of [Header, Loop, Kill, Return] - for source_node_index in self.flow.node_indices() { - // Merge edges - if let Some(merge) = self.flow[source_node_index].merge { - let merge_block_index = block_to_node[&merge.merge_block_id]; - - self.flow[source_node_index].ty = Some(ControlFlowNodeType::Header); - self.flow[merge_block_index].ty = Some(ControlFlowNodeType::Merge); - self.flow.add_edge( - source_node_index, - merge_block_index, - ControlFlowEdgeType::ForwardMerge, - ); - - if let Some(continue_block_id) = merge.continue_block_id { - let continue_block_index = block_to_node[&continue_block_id]; - - self.flow[source_node_index].ty = Some(ControlFlowNodeType::Loop); - self.flow.add_edge( - source_node_index, - continue_block_index, - ControlFlowEdgeType::ForwardContinue, - ); - - // Back edge - self.flow[continue_block_index].ty = Some(ControlFlowNodeType::Back); - self.flow.add_edge( - continue_block_index, - source_node_index, - ControlFlowEdgeType::Back, - ); - } - } - - // Branch Edges - let terminator = self.flow[source_node_index].terminator.clone(); - match terminator { - Terminator::Branch { target_id } => { - let target_node_index = block_to_node[&target_id]; - - if self.flow[source_node_index].ty != Some(ControlFlowNodeType::Back) { - self.flow.add_edge( - source_node_index, - target_node_index, - ControlFlowEdgeType::Forward, - ); - } - } - Terminator::BranchConditional { - true_id, false_id, .. - } => { - let true_node_index = block_to_node[&true_id]; - let false_node_index = block_to_node[&false_id]; - - self.flow.add_edge( - source_node_index, - true_node_index, - ControlFlowEdgeType::IfTrue, - ); - self.flow.add_edge( - source_node_index, - false_node_index, - ControlFlowEdgeType::IfFalse, - ); - } - Terminator::Switch { - selector: _, - default_id, - ref targets, - } => { - let default_node_index = block_to_node[&default_id]; - - self.flow.add_edge( - source_node_index, - default_node_index, - ControlFlowEdgeType::Forward, - ); - - for &(_, target_block_id) in targets.iter() { - let target_node_index = block_to_node[&target_block_id]; - - self.flow.add_edge( - source_node_index, - target_node_index, - ControlFlowEdgeType::Forward, - ); - } - } - Terminator::Return { .. } => { - self.flow[source_node_index].ty = Some(ControlFlowNodeType::Return) - } - Terminator::Kill => { - self.flow[source_node_index].ty = Some(ControlFlowNodeType::Kill) - } - _ => {} - }; - } - - // 2. - self.compute_postorder_traverse(Some(node_index(0))); - self.traversal_order.reverse(); - - for (i, node_index) in self.traversal_order.iter().enumerate() { - self.flow[*node_index].position = i; - } - - for node_index in self.flow.node_indices() { - self.flow[node_index].visited = false; - } - - // 3. - // The stack of enclosing constructs - let mut enclosing = vec![node_index(0)]; - - let postorder_len = self.traversal_order.len(); - let push_construct = |enclosing: &mut Vec, - constructs: &mut ConstructsGraph, - ty: ConstructType, - begin: BlockNodeIndex, - begin_position: usize, - end: BlockNodeIndex, - end_position: usize, - depth: usize| - -> ConstructNodeIndex { - let mut parent_index = *enclosing.last().unwrap_or(&node_index(0)); - - // A loop construct is added right after its associated continue construct. - // In that case, adjust the parent up. - if ty == ConstructType::Loop { - parent_index = constructs.parent(parent_index).unwrap(); - } - - let end_position = if end_position == 0 { - postorder_len - } else { - end_position - }; - - let node_index = constructs.add_child( - parent_index, - ConstructNode { - ty, - begin, - begin_position, - end, - end_position, - depth, - ..Default::default() - }, - ); - - let parent = { - if let Some(parent) = constructs.parent(node_index) { - if constructs[parent].depth < depth { - Some(constructs[parent]) - } else { - None - } - } else { - None - } - }; - - constructs[node_index].enclosing_loop = { - if constructs[node_index].ty == ConstructType::Loop { - Some(node_index) - } else if let Some(parent) = parent { - parent.enclosing_loop - } else { - None - } - }; - - constructs[node_index].enclosing_continue = { - if constructs[node_index].ty == ConstructType::Continue { - Some(node_index) - } else if let Some(parent) = parent { - parent.enclosing_continue - } else { - None - } - }; - - constructs[node_index].enclosing_loop_or_continue_or_switch = { - if constructs[node_index].ty == ConstructType::Loop - || constructs[node_index].ty == ConstructType::Continue - || constructs[node_index].ty == ConstructType::Case - { - Some(node_index) - } else if let Some(parent) = parent { - parent.enclosing_loop_or_continue_or_switch - } else { - None - } - }; - - enclosing.push(node_index); - - node_index - }; - - self.constructs[node_index(0)].begin = self.traversal_order[0]; - - for block_index in self.traversal_order.iter() { - let mut top_construct_index = *enclosing.last().unwrap(); - - if top_construct_index != node_index(0) { - while *block_index == self.constructs[top_construct_index].end { - enclosing.pop().unwrap(); - top_construct_index = *enclosing.last().unwrap(); - } - } - - if let Some(merge) = self.flow[*block_index].merge { - let merge_index = self.block_to_node[&merge.merge_block_id]; - let depth = self.constructs[top_construct_index].depth + 1; - - match self.flow[*block_index].ty { - Some(ControlFlowNodeType::Loop) => { - let continue_index = self.block_to_node[&merge.continue_block_id.unwrap()]; - - top_construct_index = push_construct( - &mut enclosing, - &mut self.constructs, - ConstructType::Continue, - continue_index, - self.flow[continue_index].position, - merge_index, - self.flow[merge_index].position, - depth, - ); - - // A loop header that is its own continue target will have an - // empty loop construct. Only create a loop construct when - // the continue target is *not* the same as the loop header. - if *block_index != continue_index { - // From the interval rule, the loop construct consists of blocks - // in the block order, starting at the header, until just - // before the continue target. - top_construct_index = push_construct( - &mut enclosing, - &mut self.constructs, - ConstructType::Loop, - *block_index, - self.flow[*block_index].position, - continue_index, - self.flow[continue_index].position, - depth, - ); - - // If the loop header branches to two different blocks inside the loop - // construct, then the loop body should be modeled as an if-selection - // construct - let neighbors: Vec = self - .flow - .neighbors_directed(*block_index, Direction::Outgoing) - .collect(); - if neighbors.len() == 2 && neighbors[0] != neighbors[1] { - let target0_pos = self.flow[neighbors[0]].position; - let target1_pos = self.flow[neighbors[1]].position; - if self.constructs[top_construct_index] - .contains_position(target0_pos) - && self.constructs[top_construct_index] - .contains_position(target1_pos) - { - // Insert a synthetic if-selection - top_construct_index = push_construct( - &mut enclosing, - &mut self.constructs, - ConstructType::Selection, - *block_index, - self.flow[*block_index].position, - continue_index, - self.flow[continue_index].position, - depth + 1, - ); - } - } - } - } - Some(ControlFlowNodeType::Header) => { - let ty = match self.flow[*block_index].terminator { - Terminator::Switch { .. } => ConstructType::Case, - _ => ConstructType::Selection, - }; - - top_construct_index = push_construct( - &mut enclosing, - &mut self.constructs, - ty, - *block_index, - self.flow[*block_index].position, - merge_index, - self.flow[merge_index].position, - depth, - ); - } - _ => {} - } - } - - self.flow[*block_index].construct = top_construct_index; - } - - // 2. - // Classify Nodes/Edges as one of [Break, Continue] - for edge_index in self.flow.edge_indices() { - let (node_source_index, node_target_index) = - self.flow.edge_endpoints(edge_index).unwrap(); - - if self.flow[node_source_index].ty == Some(ControlFlowNodeType::Header) - || self.flow[node_source_index].ty == Some(ControlFlowNodeType::Loop) - { - continue; - } - - let construct_index = self.flow[node_source_index].construct; - let header_index = self.constructs[construct_index].begin; - - // Loop break/Switch break - if let Some(enclosing_construct_index) = - self.constructs[construct_index].enclosing_loop_or_continue_or_switch - { - let enclosing_construct = self.constructs[enclosing_construct_index]; - let breakable_header = &self.flow[enclosing_construct.begin]; - - if let Some(merge_instruction) = breakable_header.merge { - let merge_node_index = self.block_to_node[&merge_instruction.merge_block_id]; - if node_target_index == merge_node_index { - self.flow[node_source_index].ty = Some(ControlFlowNodeType::Break); - self.flow[edge_index] = if enclosing_construct.ty == ConstructType::Case { - ControlFlowEdgeType::SwitchBreak - } else { - ControlFlowEdgeType::LoopBreak - }; - continue; - } - } - } - - // Continue - if let Some(enclosing_construct_index) = self.constructs[construct_index].enclosing_loop - { - let loop_header = &self.flow[self.constructs[enclosing_construct_index].begin]; - - if let Some(continue_block_id) = - loop_header.merge.and_then(|merge| merge.continue_block_id) - { - if node_target_index == self.block_to_node[&continue_block_id] { - self.flow[node_source_index].ty = Some(ControlFlowNodeType::Continue); - self.flow[edge_index] = ControlFlowEdgeType::LoopContinue; - continue; - } - } - } - - // If break - if let Some(merge_instruction) = self.flow[header_index].merge { - if node_target_index == self.block_to_node[&merge_instruction.merge_block_id] { - self.flow[node_source_index].ty = Some(ControlFlowNodeType::Break); - self.flow[edge_index] = ControlFlowEdgeType::IfBreak; - continue; - } - } - } - } - - fn header_if_breakable(&self, construct_index: ConstructNodeIndex) -> Option { - match self.constructs[construct_index].ty { - ConstructType::Loop | ConstructType::Case => { - Some(self.constructs[construct_index].begin) - } - ConstructType::Continue => { - let continue_target = self.constructs[construct_index].begin; - Some( - self.flow - .neighbors_directed(continue_target, Direction::Outgoing) - .next() - .unwrap(), - ) - } - _ => None, - } - } - - fn compute_postorder_traverse(&mut self, node_index: Option) { - if node_index.is_none() { - return; - } - let node_index = node_index.unwrap(); - - if self.flow[node_index].visited { - return; - } - self.flow[node_index].visited = true; - - if let Some(merge) = self.flow[node_index].merge { - self.compute_postorder_traverse(Some(self.block_to_node[&merge.merge_block_id])); - } - - let continue_edge = self - .flow - .edges_directed(node_index, Direction::Outgoing) - .find(|&ty| *ty.weight() == ControlFlowEdgeType::ForwardContinue) - .map(|continue_edge| continue_edge.target()); - self.compute_postorder_traverse(continue_edge); - - let terminator = self.flow[node_index].terminator.clone(); - match terminator { - Terminator::BranchConditional { - condition: _, - true_id, - false_id, - } => { - self.compute_postorder_traverse(Some(self.block_to_node[&false_id])); - self.compute_postorder_traverse(Some(self.block_to_node[&true_id])); - } - Terminator::Branch { target_id } => { - self.compute_postorder_traverse(Some(self.block_to_node[&target_id])); - } - Terminator::Switch { - selector: _, - default_id, - ref targets, - } => { - self.compute_postorder_traverse(Some(self.block_to_node[&default_id])); - for &(_, target_id) in targets.iter() { - self.compute_postorder_traverse(Some(self.block_to_node[&target_id])); - } - } - _ => {} - }; - - self.traversal_order.push(node_index); - } - - /// Removes OpPhi instructions from the control flow graph and turns them into ordinary variables. - /// - /// Phi instructions are not supported inside Naga nor do they exist as instructions on CPUs. It is necessary - /// to remove them and turn into ordinary variables before converting to Naga's IR and shader code. - pub(super) fn remove_phi_instructions( - &mut self, - lookup_expression: &FastHashMap, - ) { - for node_index in self.flow.node_indices() { - let phis = std::mem::take(&mut self.flow[node_index].phis); - for phi in phis.iter() { - for &(variable_id, parent_id) in phi.variables.iter() { - let variable = &lookup_expression[&variable_id]; - let parent_node = &mut self.flow[self.block_to_node[&parent_id]]; - - parent_node.block.push( - crate::Statement::Store { - pointer: phi.pointer, - value: variable.handle, - }, - crate::Span::Unknown, - ); - } - } - self.flow[node_index].phis = phis; - } - } - - /// Traverses the flow graph and returns a list of Naga's statements. - pub(super) fn convert_to_naga(&mut self) -> Result { - self.convert_to_naga_traverse(node_index(0), std::collections::HashSet::new()) - } - - fn convert_to_naga_traverse( - &mut self, - node_index: BlockNodeIndex, - stop_nodes: std::collections::HashSet, - ) -> Result { - if stop_nodes.contains(&node_index) { - return Ok(crate::Block::new()); - } - - if self.flow[node_index].visited { - return Err(Error::ControlFlowGraphCycle(self.flow[node_index].id)); - } - - self.flow[node_index].visited = true; - - let terminator = self.flow[node_index].terminator.clone(); - - match self.flow[node_index].ty { - Some(ControlFlowNodeType::Header) => match terminator { - Terminator::BranchConditional { - condition, - true_id, - false_id, - } => { - let true_node_index = self.block_to_node[&true_id]; - let false_node_index = self.block_to_node[&false_id]; - let merge_node_index = - self.block_to_node[&self.flow[node_index].merge.unwrap().merge_block_id]; - - let premerge_index: Option = { - let second_head = self.flow[true_node_index] - .position - .max(self.flow[false_node_index].position); - let end_first_clause = self.traversal_order[second_head - 1]; - - self.flow - .edges_directed(end_first_clause, Direction::Outgoing) - .find(|e| match *e.weight() { - ControlFlowEdgeType::Forward - | ControlFlowEdgeType::ForwardContinue - | ControlFlowEdgeType::ForwardMerge - | ControlFlowEdgeType::IfFalse - | ControlFlowEdgeType::IfTrue => self.constructs - [self.flow[node_index].construct] - .contains_position(self.flow[e.target()].position), - _ => false, - }) - .map(|e| e.target()) - }; - - let is_false_inside_construct = self.constructs - [self.flow[node_index].construct] - .contains_position(self.flow[false_node_index].position); - - let intended_merge = if let Some(premerge_index) = premerge_index { - premerge_index - } else { - merge_node_index - }; - let then_end_index = if is_false_inside_construct { - false_node_index - } else { - intended_merge - }; - let else_end_index = if let Some(premerge_index) = premerge_index { - premerge_index - } else { - intended_merge - }; - - let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); - - let mut accept_stop_nodes = stop_nodes.clone(); - accept_stop_nodes.insert(merge_node_index); - accept_stop_nodes.insert(intended_merge); - accept_stop_nodes.insert(then_end_index); - - let mut reject_stop_nodes = stop_nodes.clone(); - reject_stop_nodes.insert(merge_node_index); - reject_stop_nodes.insert(intended_merge); - reject_stop_nodes.insert(else_end_index); - - let mut accept = - self.convert_to_naga_traverse(true_node_index, accept_stop_nodes)?; - let mut reject = - self.convert_to_naga_traverse(false_node_index, reject_stop_nodes)?; - - // If the true/false block of a header is breaking from switch or loop we add a break statement after its statements - for &mut (target_index, ref mut statements) in [ - (true_node_index, &mut accept), - (false_node_index, &mut reject), - ] - .iter_mut() - { - if let Some(ControlFlowNodeType::Break) = self.flow[target_index].ty { - let edge = *self - .flow - .edges_directed(target_index, Direction::Outgoing) - .next() - .unwrap() - .weight(); - if edge == ControlFlowEdgeType::SwitchBreak - || edge == ControlFlowEdgeType::LoopBreak - { - // Do not add break if already has one as the last statement - if let Some(&crate::Statement::Break) = statements.as_ref().last() { - } else { - statements.push(crate::Statement::Break, crate::Span::Unknown); - } - } - } - } - - result.push( - crate::Statement::If { - condition, - accept, - reject, - }, - crate::Span::Unknown, - ); - - result - .extend_block(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); - - Ok(result) - } - Terminator::Switch { - selector, - default_id, - ref targets, - } => { - let merge_node_index = - self.block_to_node[&self.flow[node_index].merge.unwrap().merge_block_id]; - let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); - let mut cases = Vec::with_capacity(targets.len()); - - let mut stop_nodes_cases = stop_nodes.clone(); - stop_nodes_cases.insert(merge_node_index); - - for i in 0..targets.len() { - let left_target_node_index = self.block_to_node[&targets[i].1]; - - let fall_through = if i < targets.len() - 1 { - let right_target_node_index = self.block_to_node[&targets[i + 1].1]; - has_path_connecting( - &self.flow, - left_target_node_index, - right_target_node_index, - None, - ) - } else { - false - }; - - cases.push(crate::SwitchCase { - value: targets[i].0, - body: self.convert_to_naga_traverse( - left_target_node_index, - stop_nodes_cases.clone(), - )?, - fall_through, - }); - } - - result.push( - crate::Statement::Switch { - selector, - cases, - default: self.convert_to_naga_traverse( - self.block_to_node[&default_id], - stop_nodes_cases, - )?, - }, - crate::Span::Unknown, - ); - - result - .extend_block(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); - - Ok(result) - } - _ => Err(Error::InvalidTerminator), - }, - Some(ControlFlowNodeType::Loop) => { - let merge_node_index = - self.block_to_node[&self.flow[node_index].merge.unwrap().merge_block_id]; - let continuing: crate::Block = { - let continue_edge = self - .flow - .edges_directed(node_index, Direction::Outgoing) - .find(|&ty| *ty.weight() == ControlFlowEdgeType::ForwardContinue) - .unwrap() - .target(); - - std::mem::take(&mut self.flow[continue_edge].block) - }; - - let mut body: crate::Block = std::mem::take(&mut self.flow[node_index].block); - - let mut stop_nodes_merge = stop_nodes.clone(); - stop_nodes_merge.insert(merge_node_index); - match self.flow[node_index].terminator { - Terminator::BranchConditional { - condition, - true_id, - false_id, - } => { - let true_node_index = self.block_to_node[&true_id]; - let false_node_index = self.block_to_node[&false_id]; - - body.push( - crate::Statement::If { - condition, - accept: if true_node_index == merge_node_index { - crate::Block::from_vec(vec![crate::Statement::Break]) - } else { - self.convert_to_naga_traverse( - true_node_index, - stop_nodes_merge.clone(), - )? - }, - reject: if false_node_index == merge_node_index { - crate::Block::from_vec(vec![crate::Statement::Break]) - } else { - self.convert_to_naga_traverse( - false_node_index, - stop_nodes_merge, - )? - }, - }, - crate::Span::Unknown, - ); - } - Terminator::Branch { target_id } => { - body.extend_block(self.convert_to_naga_traverse( - self.block_to_node[&target_id], - stop_nodes_merge, - )?) - } - _ => return Err(Error::InvalidTerminator), - }; - - let mut result = - crate::Block::from_vec(vec![crate::Statement::Loop { body, continuing }]); - result.extend_block(self.convert_to_naga_traverse(merge_node_index, stop_nodes)?); - - Ok(result) - } - Some(ControlFlowNodeType::Break) => { - let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); - match self.flow[node_index].terminator { - Terminator::BranchConditional { - condition, - true_id, - false_id, - } => { - let true_node_id = self.block_to_node[&true_id]; - let false_node_id = self.block_to_node[&false_id]; - - let true_edge = - self.flow[self.flow.find_edge(node_index, true_node_id).unwrap()]; - let false_edge = - self.flow[self.flow.find_edge(node_index, false_node_id).unwrap()]; - - if true_edge == ControlFlowEdgeType::LoopBreak - || true_edge == ControlFlowEdgeType::IfBreak - { - result.push( - crate::Statement::If { - condition, - accept: if true_edge == ControlFlowEdgeType::LoopBreak { - crate::Block::from_vec(vec![crate::Statement::Break]) - } else { - crate::Block::new() - }, - reject: self - .convert_to_naga_traverse(false_node_id, stop_nodes)?, - }, - crate::Span::Unknown, - ); - } else if false_edge == ControlFlowEdgeType::LoopBreak - || false_edge == ControlFlowEdgeType::IfBreak - { - result.push( - crate::Statement::If { - condition, - accept: self - .convert_to_naga_traverse(true_node_id, stop_nodes)?, - reject: if false_edge == ControlFlowEdgeType::LoopBreak { - crate::Block::from_vec(vec![crate::Statement::Break]) - } else { - crate::Block::new() - }, - }, - crate::Span::Unknown, - ); - } else { - return Err(Error::InvalidEdgeClassification); - } - } - Terminator::Branch { target_id } => { - let target_index = self.block_to_node[&target_id]; - - let edge = - self.flow[self.flow.find_edge(node_index, target_index).unwrap()]; - - if edge == ControlFlowEdgeType::LoopBreak { - result.push(crate::Statement::Break, crate::Span::Unknown); - } - } - _ => return Err(Error::InvalidTerminator), - }; - Ok(result) - } - Some(ControlFlowNodeType::Continue) | Some(ControlFlowNodeType::Back) => { - Ok(std::mem::take(&mut self.flow[node_index].block)) - } - Some(ControlFlowNodeType::Kill) => { - let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); - result.push(crate::Statement::Kill, crate::Span::Unknown); - Ok(result) - } - Some(ControlFlowNodeType::Return) => { - let value = match self.flow[node_index].terminator { - Terminator::Return { value } => value, - _ => return Err(Error::InvalidTerminator), - }; - let mut result: crate::Block = std::mem::take(&mut self.flow[node_index].block); - result.push(crate::Statement::Return { value }, crate::Span::Unknown); - Ok(result) - } - Some(ControlFlowNodeType::Merge) | None => match self.flow[node_index].terminator { - Terminator::Branch { target_id } => { - let mut result = std::mem::take(&mut self.flow[node_index].block); - result.extend_block( - self.convert_to_naga_traverse(self.block_to_node[&target_id], stop_nodes)?, - ); - Ok(result) - } - _ => Ok(std::mem::take(&mut self.flow[node_index].block)), - }, - } - } - - /// Get the entire graph in a graphviz dot format for visualization. Useful for debugging purposes. - pub(super) fn to_graphviz(&self) -> Result { - let mut output = String::new(); - - output += "digraph ControlFlowGraph {\n"; - - for node_index in self.flow.node_indices() { - let node = &self.flow[node_index]; - - let node_name = match node.ty { - Some(ControlFlowNodeType::Header) => { - if self.constructs[node.construct].ty == ConstructType::Case { - "Switch" - } else { - "If" - } - } - Some(ControlFlowNodeType::Loop) => "Loop", - Some(ControlFlowNodeType::Merge) => "", - Some(ControlFlowNodeType::Break) => "Break", - Some(ControlFlowNodeType::Continue) => "Continue", - Some(ControlFlowNodeType::Back) => "Back", - Some(ControlFlowNodeType::Kill) => "Kill", - Some(ControlFlowNodeType::Return) => "Return", - None => "Unlabeled", - }; - - writeln!( - output, - "{} [ label = \"%{}({}) {}\" shape=ellipse ]", - node_index.index(), - node.id, - node_index.index(), - node_name, - )?; - } - - self.to_graphviz_constructs(&mut output, node_index(0))?; - - for edge in self.flow.raw_edges() { - let source = edge.source(); - let target = edge.target(); - - let style = match edge.weight { - ControlFlowEdgeType::Forward => "", - ControlFlowEdgeType::ForwardMerge => "style=dotted", - ControlFlowEdgeType::ForwardContinue => "color=green", - ControlFlowEdgeType::Back => "style=dashed", - ControlFlowEdgeType::LoopContinue => "color=green", - ControlFlowEdgeType::IfTrue => "color=blue", - ControlFlowEdgeType::IfFalse => "color=red", - ControlFlowEdgeType::LoopBreak => "color=orange", - ControlFlowEdgeType::SwitchBreak => "color=tomato", - ControlFlowEdgeType::IfBreak => "color=yellow", - ControlFlowEdgeType::CaseFallThrough => "style=dotted", - }; - - writeln!( - &mut output, - "{} -> {} [ {} ]", - source.index(), - target.index(), - style - )?; - } - - output += "}\n"; - - Ok(output) - } - - fn to_graphviz_constructs( - &self, - output: &mut String, - node_index: ConstructNodeIndex, - ) -> Result<(), std::fmt::Error> { - let construct = self.constructs[node_index]; - - writeln!( - output, - "subgraph cluster_{:?} {{ label = {:?}", - construct.ty, construct.ty - )?; - - let traversal_order_begin = self.flow[construct.begin].position; - let traversal_order_end = if construct.end.index() >= self.traversal_order.len() { - self.traversal_order.len() - 1 - } else { - self.flow[construct.end].position - }; - - for i in traversal_order_begin..=traversal_order_end { - write!(output, "{} ", self.traversal_order[i].index())?; - } - - for child_index in self.constructs.children(node_index) { - self.to_graphviz_constructs(output, child_index)?; - } - - writeln!(output, "}}",)?; - - Ok(()) - } -} - -/// Type of an edge(flow) in the `ControlFlowGraph`. -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub(super) enum ControlFlowEdgeType { - /// Default - Forward, - - /// Forward edge to a merge block. - ForwardMerge, - - /// Forward edge to a OpLoopMerge continue's instruction. - ForwardContinue, - - /// A back-edge: An edge from a node to one of its ancestors in a depth-first - /// search from the entry block. - /// Can only be to a ControlFlowNodeType::Loop. - Back, - - /// An edge from a node in a loop body to the associated continue target, where - /// there are no other intervening loops or switches. - /// The source block is a "continue block" as defined by SPIR-V. - LoopContinue, - - /// An edge from a node with OpBranchConditional to the block of true operand. - IfTrue, - - /// An edge from a node with OpBranchConditional to the block of false operand. - IfFalse, - - /// An edge from a node to the merge block of the nearest enclosing loop, where - /// there is no intervening switch. - /// The source block is a "break block" as defined by SPIR-V. - LoopBreak, - - /// An edge from a node to the merge block of the nearest enclosing switch, - /// where there is no intervening loop. - SwitchBreak, - - /// An edge from a node to the merge block of the nearest enclosing structured - /// construct, but which is neither a SwitchBreak or a LoopBreak. - /// This can only occur for an "if" selection, i.e. where the selection - /// header ends in OpBranchConditional. - IfBreak, - - /// An edge from one switch case to the next sibling switch case. - CaseFallThrough, -} -/// Type of a node(block) in the `ControlFlowGraph`. -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub(super) enum ControlFlowNodeType { - /// A block whose merge instruction is an OpSelectionMerge. - Header, - - /// A header block whose merge instruction is an OpLoopMerge. - Loop, - - /// A block declared by the Merge Block operand of a merge instruction. - Merge, - - /// A block containing a branch to the Merge Block of a loop header’s merge instruction. - Break, - - /// A block containing a branch to an OpLoopMerge instruction’s Continue Target. - Continue, - - /// A block containing an OpBranch to a Loop block. - Back, - - /// A block containing an OpKill instruction. - Kill, - - /// A block containing an OpReturn or OpReturnValue branch. - Return, -} -/// ControlFlowGraph's node representing a block in the control flow. -pub(super) struct ControlFlowNode { - /// SPIR-V ID. - pub id: BlockId, - - /// Type of the node. See *ControlFlowNodeType*. - pub ty: Option, - - /// Phi instructions. - pub phis: Vec, - - /// Naga's statements inside this block. - pub block: crate::Block, - - /// Termination instruction of the block. - pub terminator: Terminator, - - /// Merge Instruction. - pub merge: Option, - - /// Construct that this block belongs to. - pub construct: ConstructNodeIndex, - - /// Position in the postorder traversal. - pub position: usize, - - /// Flag determining whether this node was already visited by the graph traversal while converting a SPIR-V to Naga's IR. - /// This flag serves as a check in case an incorrect SPIR-V is supplied to the front-end. When a SPIR-V is correct there can be no cycles in it and there is no reason - /// to visit any node twice. - pub visited: bool, -} -/// Type of a node(block) in the `ConstructsGraph`. -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub(super) enum ConstructType { - /// Includes all the nodes in the `ControlFlowGraph`. - Function, - /// Includes the nodes(blocks) dominated by a `ControlFlowNodeType::Header` node(block), while excluding nodes(blocks) dominated by the selection construct’s `ControlFlowNodeType::Merge` node(block). - Selection, - /// Includes the nodes(blocks) dominated by a `ControlFlowNodeType::Loop` Continue Target and post dominated by the corresponding loop’s `ControlFlowNodeType::Back` block, while excluding blocks dominated by that `ControlFlowNodeType::Merge` node(block). - Continue, - /// Includes the nodes(blocks) dominated by a `ControlFlowNodeType::Loop`, while excluding both that header’s continue construct and the blocks dominated by the loop’s `ControlFlowNodeType::Merge` node(block). - Loop, - /// Includes the nodes(blocks) dominated by an OpSwitch Target or Default (this construct is only defined for those OpSwitch Target or Default that are not equal to the OpSwitch’s corresponding merge block) - Case, -} - -impl Default for ConstructType { - fn default() -> Self { - ConstructType::Function - } -} - -/// ConstructsGraph's construct node that encompasses a series of blocks in `ControlFlowGraph` -#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)] -pub(super) struct ConstructNode { - /// - pub ty: ConstructType, - - /// - pub begin: BlockNodeIndex, - - /// - pub begin_position: usize, - - /// - pub end: BlockNodeIndex, - - /// - pub end_position: usize, - - /// Control flow nesting depth. The entry block is at nesting depth 0. - pub depth: usize, - - /// The nearest enclosing loop construct, if one exists. Points to itself - /// when this is a loop construct. - pub enclosing_loop: Option, - - /// The nearest enclosing continue construct, if one exists. Points to - /// itself when this is a contnue construct. - pub enclosing_continue: Option, - - /// The nearest enclosing loop construct or continue construct or - /// switch-selection construct, if one exists. The signficance is - /// that a high level language "break" will branch to the merge block - /// of such an enclosing construct. Points to itself when this is - /// a loop construct, a continue construct, or a switch-selection construct. - pub enclosing_loop_or_continue_or_switch: Option, -} - -impl ConstructNode { - pub(super) fn contains_position(&self, position: usize) -> bool { - self.begin_position <= position && position < self.end_position - } -} diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 74a00f9b1..ac9f78fc2 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -1,6 +1,9 @@ -use crate::arena::{Arena, Handle}; +use crate::{ + arena::{Arena, Handle}, + front::spv::{BlockContext, BodyIndex}, +}; -use super::{flow::*, Error, Instruction, LookupExpression, LookupHelper as _}; +use super::{Error, Instruction, LookupExpression, LookupHelper as _}; use crate::front::Emitter; pub type BlockId = u32; @@ -10,44 +13,6 @@ pub struct MergeInstruction { pub merge_block_id: BlockId, pub continue_block_id: Option, } -/// Terminator instruction of a SPIR-V's block. -#[derive(Clone, Debug)] -#[allow(dead_code)] -pub enum Terminator { - /// - Return { - value: Option>, - }, - /// - Branch { target_id: BlockId }, - /// - BranchConditional { - condition: Handle, - true_id: BlockId, - false_id: BlockId, - }, - /// - /// switch(SELECTOR) { - /// case TARGET_LITERAL#: { - /// TARGET_BLOCK# - /// } - /// default: { - /// DEFAULT - /// } - /// } - Switch { - /// - selector: Handle, - /// Default block of the switch case. - default_id: BlockId, - /// Tuples of (literal, target block) - targets: Vec<(i32, BlockId)>, - }, - /// Fragment shader discard - Kill, - /// - Unreachable, -} impl> super::Parser { // Registers a function call. It will generate a dummy handle to call, which @@ -115,8 +80,17 @@ impl> super::Parser { crate::Expression::FunctionArgument(i as u32), self.span_from(start), ); - self.lookup_expression - .insert(id, LookupExpression { handle, type_id }); + self.lookup_expression.insert( + id, + LookupExpression { + handle, + type_id, + // Setting this to an invalid id will cause get_expr_handle + // to default to the main body making sure no load/stores + // are added. + block_id: 0, + }, + ); //Note: we redo the lookup in order to work around `self` borrowing if type_id @@ -141,10 +115,13 @@ impl> super::Parser { // Read body self.function_call_graph.add_node(fun_id); - let mut flow_graph = FlowGraph::new(); let mut parameters_sampling = vec![super::image::SamplingFlags::empty(); fun.arguments.len()]; + let mut block_ctx = BlockContext::default(); + // Insert the main body whose parent is also himself + block_ctx.bodies.push(super::Body::with_parent(0)); + // Scan the blocks and add them as nodes loop { let fun_inst = self.next_inst()?; @@ -155,7 +132,7 @@ impl> super::Parser { fun_inst.expect(2)?; let block_id = self.next()?; - let node = self.next_block( + self.next_block( block_id, fun_id, &mut fun.expressions, @@ -165,9 +142,8 @@ impl> super::Parser { &module.global_variables, &fun.arguments, &mut parameters_sampling, + &mut block_ctx, )?; - - flow_graph.add_node(node); } spirv::Op::FunctionEnd => { fun_inst.expect(1)?; @@ -179,22 +155,121 @@ impl> super::Parser { } } - flow_graph.classify(); - flow_graph.remove_phi_instructions(&self.lookup_expression); - - if let Some(ref prefix) = self.options.flow_graph_dump_prefix { - let dump = flow_graph.to_graphviz().unwrap_or_default(); + if let Some(ref prefix) = self.options.block_ctx_dump_prefix { let dump_suffix = match self.lookup_entry_point.get(&fun_id) { - Some(ep) => format!("flow.{:?}-{}.dot", ep.stage, ep.name), - None => format!("flow.Fun-{}.dot", module.functions.len()), + Some(ep) => format!("block_ctx.{:?}-{}.txt", ep.stage, ep.name), + None => format!("block_ctx.Fun-{}.txt", module.functions.len()), }; let dest = prefix.join(dump_suffix); + let dump = format!("{:#?}", block_ctx); if let Err(e) = std::fs::write(&dest, dump) { - log::error!("Unable to dump the flow graph into {:?}: {}", dest, e); + log::error!("Unable to dump the block context into {:?}: {}", dest, e); } } - fun.body = flow_graph.convert_to_naga()?; + // Emit `Store` statements to properly initialize all the local variables we + // created for `phi` expressions. + // + // Note that get_expr_handle also contributes slightly odd entries to this table, + // to get the spill. + for phi in block_ctx.phis.iter() { + // Get a pointer to the local variable for the phi's value. + let phi_pointer = fun.expressions.append( + crate::Expression::LocalVariable(phi.local), + crate::Span::Unknown, + ); + + // At the end of each of `phi`'s predecessor blocks, store the corresponding + // source value in the phi's local variable. + for &(source, predecessor) in phi.expressions.iter() { + let source_lexp = &self.lookup_expression[&source]; + let predecessor_body_idx = block_ctx.body_for_label[&predecessor]; + // If the expression is a global/argument it will have a 0 block + // id so we must use a default value instead of panicking + let source_body_idx = block_ctx + .body_for_label + .get(&source_lexp.block_id) + .copied() + .unwrap_or(0); + + // If the Naga `Expression` generated for `source` is in scope, then we + // can simply store that in the phi's local variable. + // + // Otherwise, spill the source value to a local variable in the block that + // defines it. (We know this store dominates the predecessor; otherwise, + // the phi wouldn't have been able to refer to that source expression in + // the first place.) Then, the predecessor block can count on finding the + // source's value in that local variable. + let value = if super::is_parent(predecessor_body_idx, source_body_idx, &block_ctx) { + source_lexp.handle + } else { + // The source SPIR-V expression is not defined in the phi's + // predecessor block, nor is it a globally available expression. So it + // must be defined off in some other block that merely dominates the + // predecessor. This means that the corresponding Naga `Expression` + // may not be in scope in the predecessor block. + // + // In the block that defines `source`, spill it to a fresh local + // variable, to ensure we can still use it at the end of the + // predecessor. + let ty = self.lookup_type[&source_lexp.type_id].handle; + let local = fun.local_variables.append( + crate::LocalVariable { + name: None, + ty, + init: None, + }, + crate::Span::Unknown, + ); + + let pointer = fun.expressions.append( + crate::Expression::LocalVariable(local), + crate::Span::Unknown, + ); + + // Get the spilled value of the source expression. + let start = fun.expressions.len(); + let expr = fun + .expressions + .append(crate::Expression::Load { pointer }, crate::Span::Unknown); + let range = fun.expressions.range_from(start); + + block_ctx + .blocks + .get_mut(&predecessor) + .unwrap() + .push(crate::Statement::Emit(range), crate::Span::Unknown); + + // At the end of the block that defines it, spill the source + // expression's value. + block_ctx + .blocks + .get_mut(&source_lexp.block_id) + .unwrap() + .push( + crate::Statement::Store { + pointer, + value: source_lexp.handle, + }, + crate::Span::Unknown, + ); + + expr + }; + + // At the end of the phi predecessor block, store the source + // value in the phi's value. + block_ctx.blocks.get_mut(&predecessor).unwrap().push( + crate::Statement::Store { + pointer: phi_pointer, + value, + }, + crate::Span::Unknown, + ) + } + } + + fun.body = block_ctx.lower(); // done let fun_handle = module.functions.append(fun, self.span_from_with_op(start)); @@ -438,3 +513,86 @@ impl> super::Parser { Ok(()) } } + +impl BlockContext { + /// Consumes the `BlockContext` producing a Ir [`Block`](crate::Block) + fn lower(mut self) -> crate::Block { + fn lower_impl( + blocks: &mut crate::FastHashMap, + bodies: &[super::Body], + body_idx: BodyIndex, + ) -> crate::Block { + let mut block = crate::Block::new(); + + for item in bodies[body_idx].data.iter() { + match *item { + super::BodyFragment::BlockId(id) => block.append(blocks.get_mut(&id).unwrap()), + super::BodyFragment::If { + condition, + accept, + reject, + } => { + let accept = lower_impl(blocks, bodies, accept); + let reject = lower_impl(blocks, bodies, reject); + + block.push( + crate::Statement::If { + condition, + accept, + reject, + }, + crate::Span::Unknown, + ) + } + super::BodyFragment::Loop { body, continuing } => { + let body = lower_impl(blocks, bodies, body); + let continuing = lower_impl(blocks, bodies, continuing); + + block.push( + crate::Statement::Loop { body, continuing }, + crate::Span::Unknown, + ) + } + super::BodyFragment::Switch { + selector, + ref cases, + default, + } => { + let default = lower_impl(blocks, bodies, default); + + block.push( + crate::Statement::Switch { + selector, + cases: cases + .iter() + .map(|&(value, body_idx)| { + let body = lower_impl(blocks, bodies, body_idx); + + crate::SwitchCase { + value, + body, + // TODO + fall_through: true, + } + }) + .collect(), + default, + }, + crate::Span::Unknown, + ) + } + super::BodyFragment::Break => { + block.push(crate::Statement::Break, crate::Span::Unknown) + } + super::BodyFragment::Continue => { + block.push(crate::Statement::Continue, crate::Span::Unknown) + } + } + } + + block + } + + lower_impl(&mut self.blocks, &self.bodies, 0) + } +} diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 752ddde3e..fb688a53e 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -246,7 +246,7 @@ impl> super::Parser { Ok(()) } - pub(super) fn parse_image_uncouple(&mut self) -> Result<(), Error> { + pub(super) fn parse_image_uncouple(&mut self, block_id: spirv::Word) -> Result<(), Error> { let result_type_id = self.next()?; let result_id = self.next()?; let sampled_image_id = self.next()?; @@ -255,6 +255,7 @@ impl> super::Parser { LookupExpression { handle: self.lookup_sampled_image.lookup(sampled_image_id)?.image, type_id: result_type_id, + block_id, }, ); Ok(()) @@ -317,13 +318,20 @@ impl> super::Parser { }) } + #[allow(clippy::too_many_arguments)] pub(super) fn parse_image_load( &mut self, mut words_left: u16, type_arena: &Arena, global_arena: &Arena, arguments: &[FunctionArgument], + block_ctx: &mut super::BlockContext, + emitter: &mut crate::front::Emitter, + block: &mut crate::Block, expressions: &mut Arena, + local_arena: &mut Arena, + block_id: spirv::Word, + body_idx: usize, ) -> Result<(), Error> { let start = self.data_offset; let result_type_id = self.next()?; @@ -365,10 +373,22 @@ impl> super::Parser { image_ops ^= bit; } + // No need to call get_expr_handle here since only globals/arguments are + // allowed as images and they are always in the root scope let image_lexp = self.lookup_expression.lookup(image_id)?; let image_ty = expressions.get_image_expr_ty(image_lexp.handle, global_arena, arguments)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_handle = self.get_expr_handle( + coordinate_id, + coord_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; let (coordinate, array_index) = match type_arena[image_ty].inner { crate::TypeInner::Image { @@ -382,7 +402,7 @@ impl> super::Parser { } else { ExtraCoordinate::Garbage }, - coord_lexp.handle, + coord_handle, coord_type_handle, type_arena, expressions, @@ -401,6 +421,7 @@ impl> super::Parser { LookupExpression { handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, + block_id, }, ); Ok(()) @@ -414,8 +435,14 @@ impl> super::Parser { type_arena: &Arena, global_arena: &Arena, arguments: &[FunctionArgument], - expressions: &mut Arena, parameters_sampling: &mut [SamplingFlags], + block_ctx: &mut super::BlockContext, + emitter: &mut crate::front::Emitter, + block: &mut crate::Block, + expressions: &mut Arena, + local_arena: &mut Arena, + block_id: spirv::Word, + body_idx: usize, ) -> Result<(), Error> { let start = self.data_offset; let result_type_id = self.next()?; @@ -442,13 +469,33 @@ impl> super::Parser { match spirv::ImageOperands::from_bits_truncate(bit) { spirv::ImageOperands::BIAS => { let bias_expr = self.next()?; - let bias_handle = self.lookup_expression.lookup(bias_expr)?.handle; + let bias_lexp = self.lookup_expression.lookup(bias_expr)?; + let bias_handle = self.get_expr_handle( + bias_expr, + bias_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); level = crate::SampleLevel::Bias(bias_handle); words_left -= 1; } spirv::ImageOperands::LOD => { let lod_expr = self.next()?; - let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; + let lod_lexp = self.lookup_expression.lookup(lod_expr)?; + let lod_handle = self.get_expr_handle( + lod_expr, + lod_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); level = if options.compare { log::debug!("Assuming {:?} is zero", lod_handle); crate::SampleLevel::Zero @@ -459,9 +506,29 @@ impl> super::Parser { } spirv::ImageOperands::GRAD => { let grad_x_expr = self.next()?; - let grad_x_handle = self.lookup_expression.lookup(grad_x_expr)?.handle; + let grad_x_lexp = self.lookup_expression.lookup(grad_x_expr)?; + let grad_x_handle = self.get_expr_handle( + grad_x_expr, + grad_x_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); let grad_y_expr = self.next()?; - let grad_y_handle = self.lookup_expression.lookup(grad_y_expr)?.handle; + let grad_y_lexp = self.lookup_expression.lookup(grad_y_expr)?; + let grad_y_handle = self.get_expr_handle( + grad_y_expr, + grad_y_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); level = if options.compare { log::debug!( "Assuming gradients {:?} and {:?} are not greater than 1", @@ -496,6 +563,16 @@ impl> super::Parser { let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_handle = self.get_expr_handle( + coordinate_id, + coord_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; let sampling_bit = if options.compare { @@ -543,7 +620,7 @@ impl> super::Parser { } else { ExtraCoordinate::Garbage }, - coord_lexp.handle, + coord_handle, coord_type_handle, type_arena, expressions, @@ -557,7 +634,7 @@ impl> super::Parser { let required_size = dim.required_coordinate_size(); let right = expressions.append( crate::Expression::AccessIndex { - base: coord_lexp.handle, + base: coord_handle, index: required_size.map_or(1, |size| size as u32), }, crate::Span::Unknown, @@ -594,15 +671,23 @@ impl> super::Parser { LookupExpression { handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, + block_id, }, ); Ok(()) } + #[allow(clippy::too_many_arguments)] pub(super) fn parse_image_query_size( &mut self, at_level: bool, + block_ctx: &mut super::BlockContext, + emitter: &mut crate::front::Emitter, + block: &mut crate::Block, expressions: &mut Arena, + local_arena: &mut Arena, + block_id: spirv::Word, + body_idx: usize, ) -> Result<(), Error> { let start = self.data_offset; let result_type_id = self.next()?; @@ -611,11 +696,22 @@ impl> super::Parser { let level = if at_level { let level_id = self.next()?; let level_lexp = self.lookup_expression.lookup(level_id)?; - Some(level_lexp.handle) + Some(self.get_expr_handle( + level_id, + level_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + )) } else { None }; + // No need to call get_expr_handle here since only globals/arguments are + // allowed as images and they are always in the root scope //TODO: handle arrays and cubes let image_lexp = self.lookup_expression.lookup(image_id)?; @@ -628,6 +724,7 @@ impl> super::Parser { LookupExpression { handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, + block_id, }, ); Ok(()) @@ -637,12 +734,15 @@ impl> super::Parser { &mut self, query: crate::ImageQuery, expressions: &mut Arena, + block_id: spirv::Word, ) -> Result<(), Error> { let start = self.data_offset; let result_type_id = self.next()?; let result_id = self.next()?; let image_id = self.next()?; + // No need to call get_expr_handle here since only globals/arguments are + // allowed as images and they are always in the root scope let image_lexp = self.lookup_expression.lookup(image_id)?.clone(); let expr = crate::Expression::ImageQuery { @@ -654,6 +754,7 @@ impl> super::Parser { LookupExpression { handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, + block_id, }, ); Ok(()) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 60191d2cb..50608113a 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -24,18 +24,14 @@ and we generate a parallel expression that loads the value, but transposed. This value then gets used instead of `OpLoad` result later on. !*/ -#![allow(dead_code)] - mod convert; mod error; -mod flow; mod function; mod image; mod null; use convert::*; pub use error::Error; -use flow::*; use function::*; use crate::{ @@ -121,17 +117,6 @@ impl crate::TypeInner { } } -/// OpPhi instruction. -#[derive(Debug)] -struct PhiInstruction { - /// SPIR-V's ID. - id: u32, - - pointer: Handle, - - /// Tuples of (variable, parent). - variables: Vec<(u32, u32)>, -} #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] pub enum ModuleState { Empty, @@ -161,30 +146,6 @@ impl LookupHelper for FastHashMap { } } -fn check_sample_coordinates( - ty: &crate::Type, - expect_kind: crate::ScalarKind, - dim: crate::ImageDimension, - is_array: bool, -) -> bool { - let base_count = match dim { - crate::ImageDimension::D1 => 1, - crate::ImageDimension::D2 => 2, - crate::ImageDimension::D3 | crate::ImageDimension::Cube => 3, - }; - let extra_count = if is_array { 1 } else { 0 }; - let count = base_count + extra_count; - match ty.inner { - crate::TypeInner::Scalar { kind, width: _ } => count == 1 && kind == expect_kind, - crate::TypeInner::Vector { - size, - kind, - width: _, - } => size as u8 == count && kind == expect_kind, - _ => false, - } -} - impl crate::ImageDimension { fn required_coordinate_size(&self) -> Option { match *self { @@ -337,10 +298,24 @@ struct LookupVariable { type_id: spirv::Word, } +/// Information about SPIR-V result ids, stored in `Parser::lookup_expression`. #[derive(Clone, Debug)] struct LookupExpression { + /// The `Expression` constructed for this result. + /// + /// Note that, while a SPIR-V result id can be used in any block dominated + /// by its definition, a Naga `Expression` is only in scope for the rest of + /// its subtree. `Parser::get_expr_handle` takes care of handle: Handle, + + /// The SPIR-V type of this result. type_id: spirv::Word, + + /// The label id of the block that defines this expression. + /// + /// This is zero for globals, constants, and function parameters, since they + /// originate outside any function's block. + block_id: spirv::Word, } #[derive(Debug)] @@ -379,7 +354,7 @@ pub struct Options { pub adjust_coordinate_space: bool, /// Only allow shaders with the known set of capabilities. pub strict_capabilities: bool, - pub flow_graph_dump_prefix: Option, + pub block_ctx_dump_prefix: Option, } impl Default for Options { @@ -387,11 +362,137 @@ impl Default for Options { Options { adjust_coordinate_space: true, strict_capabilities: false, - flow_graph_dump_prefix: None, + block_ctx_dump_prefix: None, } } } +/// An index into the `BlockContext::bodies` table. +type BodyIndex = usize; + +/// An intermediate representation of a Naga [`Statement`]. +/// +/// `Body` and `BodyFragment` values form a tree: the `BodyIndex` fields of the +/// variants are indices of the child `Body` values in [`BlockContext::bodies`]. +/// The `lower` function assembles the final `Statement` tree from this `Body` +/// tree. See [`BlockContext`] for details. +/// +/// [`Statement`]: crate::Statement +#[derive(Debug)] +enum BodyFragment { + BlockId(spirv::Word), + If { + condition: Handle, + accept: BodyIndex, + reject: BodyIndex, + }, + Loop { + body: BodyIndex, + continuing: BodyIndex, + }, + Switch { + selector: Handle, + cases: Vec<(i32, BodyIndex)>, + default: BodyIndex, + }, + Break, + Continue, +} + +/// An intermediate representation of a Naga [`Block`]. +/// +/// This will be assembled into a `Block` once we've added spills for phi nodes +/// and out-of-scope expressions. See [`BlockContext`] for details. +/// +/// [`Block`]: crate::Block +#[derive(Debug)] +struct Body { + /// The index of the direct parent of this body + parent: usize, + data: Vec, +} + +impl Body { + /// Creates a new empty `Body` with the specified `parent` + pub fn with_parent(parent: usize) -> Self { + Body { + parent, + data: Vec::new(), + } + } +} + +#[derive(Debug)] +struct PhiExpression { + /// The local variable used for the phi node + local: Handle, + /// List of (expression, block) + expressions: Vec<(spirv::Word, spirv::Word)>, +} + +#[derive(Debug)] +enum MergeBlockInformation { + LoopMerge, + LoopContinue, + SelectionMerge, + SwitchMerge, +} + +/// Fragments of Naga IR, to be assembled into `Statements` once data flow is +/// resolved. +/// +/// We can't build a Naga `Statement` tree directly from SPIR-V blocks for two +/// main reasons: +/// +/// - A SPIR-V expression can be used in any SPIR-V block dominated by its +/// definition, whereas Naga expressions are scoped to the rest of their +/// subtree. This means that discovering an expression use later in the +/// function retroactively requires us to have spilled that expression into a +/// local variable back before we left its scope. +/// +/// - We translate SPIR-V OpPhi expressions as Naga local variables in which we +/// store the appropriate value before jumping to the OpPhi's block. +/// +/// Both cases require us to go back and amend previously generated Naga IR +/// based on things we discover later. But modifying old blocks in arbitrary +/// spots in a `Statement` tree is awkward. +/// +/// Instead, as we iterate through the function's body, we accumulate +/// control-flow-free fragments of Naga IR in the [`blocks`] table, while +/// building a skeleton of the Naga `Statement` tree in [`bodies`]. We note any +/// spills and temporaries we must introduce in [`phis`]. +/// +/// Finally, once we've processed the entire function, we add temporaries and +/// spills to the fragmentary `Blocks` as directed by `phis`, and assemble them +/// into the final Naga `Statement` tree as directed by `bodies`. +/// +/// [`blocks`]: BlockContext::blocks +/// [`bodies`]: BlockContext::bodies +/// [`phis`]: BlockContext::phis +/// [`lower`]: function::lower +#[derive(Default, Debug)] +struct BlockContext { + /// Phi nodes encountered when parsing the function, used to generate spills + /// to local variables. + phis: Vec, + + /// Fragments of control-flow-free Naga IR. + /// + /// These will be stitched together into a proper `Statement` tree according + /// to `bodies`, once parsing is complete. + blocks: FastHashMap, + + /// Map from block label ids to the index of the corresponding `Body` in + /// `bodies`. + body_for_label: FastHashMap, + + /// SPIR-V metadata about merge/continue blocks. + mergers: FastHashMap, + + /// A table of `Body` values, each representing a block in the final IR. + bodies: Vec, +} + pub struct Parser { data: I, data_offset: usize, @@ -590,9 +691,96 @@ impl> Parser { Ok(()) } + /// Return the Naga `Expression` for a given SPIR-V result `id`. + /// + /// `lookup` must be the `LookupExpression` for `id`. + /// + /// SPIR-V result ids can be used by any block dominated by the id's + /// definition, but Naga `Expressions` are only in scope for the remainder + /// of their `Statement` subtree. This means that the `Expression` generated + /// for `id` may no longer be in scope. In such cases, this function takes + /// care of spilling the value of `id` to a `LocalVariable` which can then + /// be used anywhere. The SPIR-V domination rule ensures that the + /// `LocalVariable` has been initialized before it is used. + /// + /// The `body_idx` argument should be the index of the `Body` that hopes to + /// use `id`'s `Expression`. + #[allow(clippy::too_many_arguments)] + fn get_expr_handle( + &self, + id: spirv::Word, + lookup: &LookupExpression, + block_ctx: &mut BlockContext, + emitter: &mut super::Emitter, + block: &mut crate::Block, + expressions: &mut Arena, + local_arena: &mut Arena, + body_idx: BodyIndex, + ) -> Handle { + // What `Body` was `id` defined in? + let expr_body_idx = block_ctx + .body_for_label + .get(&lookup.block_id) + .copied() + .unwrap_or(0); + + // Don't need to do a load/store if the expression is in the main body + // or if the expression is in the same body as where the query was + // requested. The body_idx might actually not be the final one if a loop + // or conditional occurs but in those cases we know that the new body + // will be a subscope of the body that was passed so we can still reuse + // the handle and not issue a load/store. + if is_parent(body_idx, expr_body_idx, block_ctx) { + lookup.handle + } else { + // Add a temporary variable of the same type which will be used to + // store the original expression and used in the current block + let ty = self.lookup_type[&lookup.type_id].handle; + let local = local_arena.append( + crate::LocalVariable { + name: None, + ty, + init: None, + }, + crate::Span::Unknown, + ); + + block.extend(emitter.finish(expressions)); + let pointer = expressions.append( + crate::Expression::LocalVariable(local), + crate::Span::Unknown, + ); + emitter.start(expressions); + let expr = + expressions.append(crate::Expression::Load { pointer }, crate::Span::Unknown); + + // Add a slightly odd entry to the phi table, so that while `id`'s + // `Expression` is still in scope, the usual phi processing will + // spill its value to `local`, where we can find it later. + // + // This pretends that the block in which `id` is defined is the + // predecessor of some other block with a phi in it that cites id as + // one of its sources, and uses `local` as its variable. There is no + // such phi, but nobody needs to know that. + block_ctx.phis.push(PhiExpression { + local, + expressions: vec![(id, lookup.block_id)], + }); + + expr + } + } + + #[allow(clippy::too_many_arguments)] fn parse_expr_unary_op( &mut self, + block_ctx: &mut BlockContext, + emitter: &mut super::Emitter, + block: &mut crate::Block, expressions: &mut Arena, + local_arena: &mut Arena, + block_id: spirv::Word, + body_idx: usize, op: crate::UnaryOperator, ) -> Result<(), Error> { let start = self.data_offset; @@ -601,24 +789,39 @@ impl> Parser { let p_id = self.next()?; let p_lexp = self.lookup_expression.lookup(p_id)?; + let handle = self.get_expr_handle( + p_id, + p_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); - let expr = crate::Expression::Unary { - op, - expr: p_lexp.handle, - }; + let expr = crate::Expression::Unary { op, expr: handle }; self.lookup_expression.insert( result_id, LookupExpression { handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, + block_id, }, ); Ok(()) } + #[allow(clippy::too_many_arguments)] fn parse_expr_binary_op( &mut self, + block_ctx: &mut BlockContext, + emitter: &mut super::Emitter, + block: &mut crate::Block, expressions: &mut Arena, + local_arena: &mut Arena, + block_id: spirv::Word, + body_idx: usize, op: crate::BinaryOperator, ) -> Result<(), Error> { let start = self.data_offset; @@ -628,18 +831,35 @@ impl> Parser { let p2_id = self.next()?; let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let left = self.get_expr_handle( + p1_id, + p1_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); let p2_lexp = self.lookup_expression.lookup(p2_id)?; + let right = self.get_expr_handle( + p2_id, + p2_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); - let expr = crate::Expression::Binary { - op, - left: p1_lexp.handle, - right: p2_lexp.handle, - }; + let expr = crate::Expression::Binary { op, left, right }; self.lookup_expression.insert( result_id, LookupExpression { handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, + block_id, }, ); Ok(()) @@ -648,9 +868,16 @@ impl> Parser { /// A more complicated version of the binary op, /// where we force the operand to have the same type as the result. /// This is mostly needed for "i++" and "i--" coming from GLSL. + #[allow(clippy::too_many_arguments)] fn parse_expr_binary_op_sign_adjusted( &mut self, + block_ctx: &mut BlockContext, + emitter: &mut super::Emitter, + block: &mut crate::Block, expressions: &mut Arena, + local_arena: &mut Arena, + block_id: spirv::Word, + body_idx: usize, op: crate::BinaryOperator, types: &Arena, ) -> Result<(), Error> { @@ -662,18 +889,38 @@ impl> Parser { let span = self.span_from_with_op(start); let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let left = self.get_expr_handle( + p1_id, + p1_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); let p2_lexp = self.lookup_expression.lookup(p2_id)?; + let right = self.get_expr_handle( + p2_id, + p2_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); let result_lookup_ty = self.lookup_type.lookup(result_type_id)?; let kind = types[result_lookup_ty.handle].inner.scalar_kind().unwrap(); let expr = crate::Expression::Binary { op, left: if p1_lexp.type_id == result_type_id { - p1_lexp.handle + left } else { expressions.append( crate::Expression::As { - expr: p1_lexp.handle, + expr: left, kind, convert: None, }, @@ -681,11 +928,11 @@ impl> Parser { ) }, right: if p2_lexp.type_id == result_type_id { - p2_lexp.handle + right } else { expressions.append( crate::Expression::As { - expr: p2_lexp.handle, + expr: right, kind, convert: None, }, @@ -699,14 +946,22 @@ impl> Parser { LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); Ok(()) } + #[allow(clippy::too_many_arguments)] fn parse_expr_shift_op( &mut self, + block_ctx: &mut BlockContext, + emitter: &mut super::Emitter, + block: &mut crate::Block, expressions: &mut Arena, + local_arena: &mut Arena, + block_id: spirv::Word, + body_idx: usize, op: crate::BinaryOperator, ) -> Result<(), Error> { let start = self.data_offset; @@ -718,35 +973,59 @@ impl> Parser { let span = self.span_from_with_op(start); let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let left = self.get_expr_handle( + p1_id, + p1_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); let p2_lexp = self.lookup_expression.lookup(p2_id)?; + let p2_handle = self.get_expr_handle( + p2_id, + p2_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); // convert the shift to Uint - let p2_handle = expressions.append( + let right = expressions.append( crate::Expression::As { - expr: p2_lexp.handle, + expr: p2_handle, kind: crate::ScalarKind::Uint, convert: None, }, span.clone(), ); - let expr = crate::Expression::Binary { - op, - left: p1_lexp.handle, - right: p2_handle, - }; + let expr = crate::Expression::Binary { op, left, right }; self.lookup_expression.insert( result_id, LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); Ok(()) } + #[allow(clippy::too_many_arguments)] fn parse_expr_derivative( &mut self, + block_ctx: &mut BlockContext, + emitter: &mut super::Emitter, + block: &mut crate::Block, expressions: &mut Arena, + local_arena: &mut Arena, + block_id: spirv::Word, + body_idx: usize, axis: crate::DerivativeAxis, ) -> Result<(), Error> { let start = self.data_offset; @@ -755,16 +1034,27 @@ impl> Parser { let arg_id = self.next()?; let arg_lexp = self.lookup_expression.lookup(arg_id)?; + let arg_handle = self.get_expr_handle( + arg_id, + arg_lexp, + block_ctx, + emitter, + block, + expressions, + local_arena, + body_idx, + ); let expr = crate::Expression::Derivative { axis, - expr: arg_lexp.handle, + expr: arg_handle, }; self.lookup_expression.insert( result_id, LookupExpression { handle: expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, + block_id, }, ); Ok(()) @@ -840,6 +1130,11 @@ impl> Parser { )) } + /// Add the next SPIR-V block's contents to `block_ctx`. + /// + /// Except for the function's entry block, `block_id` should be the label of + /// a block we've seen mentioned before, with an entry in + /// `block_ctx.body_for_label` to tell us which `Body` it contributes to. #[allow(clippy::too_many_arguments)] fn next_block( &mut self, @@ -852,12 +1147,115 @@ impl> Parser { global_arena: &Arena, arguments: &[crate::FunctionArgument], parmeter_sampling: &mut [image::SamplingFlags], - ) -> Result { - let mut block = crate::Block::new(); - let mut phis = Vec::new(); + block_ctx: &mut BlockContext, + ) -> Result<(), Error> { + // Extend `body` with the correct form for a branch to `target`. + fn merger(body: &mut Body, target: &MergeBlockInformation) { + body.data.push(match *target { + MergeBlockInformation::LoopContinue => BodyFragment::Continue, + MergeBlockInformation::LoopMerge | MergeBlockInformation::SwitchMerge => { + BodyFragment::Break + } + + // Finishing a selection merge means just falling off the end of + // the `accept` or `reject` block of the `If` statement. + MergeBlockInformation::SelectionMerge => return, + }) + } + let mut emitter = super::Emitter::default(); emitter.start(expressions); - let mut merge = None; + + // Find the `Body` that this block belongs to. Index zero is the + // function's root `Body`, corresponding to `Function::body`. + let mut body_idx = *block_ctx.body_for_label.entry(block_id).or_default(); + let mut block = crate::Block::new(); + // Stores the merge block as defined by a `OpSelectionMerge` otherwise is `None` + // + // This is used in `OpSwitch` to promote the `MergeBlockInformation` from + // `SelectionMerge` to `SwitchMerge` to allow `Break`s this isn't desirable for + // `LoopMerge`s because otherwise `Continue`s wouldn't be allowed + let mut selection_merge_block = None; + + macro_rules! get_expr_handle { + ($id:expr, $lexp:expr) => { + self.get_expr_handle( + $id, + $lexp, + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + body_idx, + ) + }; + } + macro_rules! parse_expr_op { + ($op:expr, BINARY) => { + self.parse_expr_binary_op( + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, + $op, + ) + }; + + ($op:expr, BINARY_SIGN_ADJUSTED) => { + self.parse_expr_binary_op_sign_adjusted( + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, + $op, + type_arena, + ) + }; + ($op:expr, SHIFT) => { + self.parse_expr_shift_op( + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, + $op, + ) + }; + ($op:expr, UNARY) => { + self.parse_expr_unary_op( + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, + $op, + ) + }; + ($axis:expr, DERIVATIVE) => { + self.parse_expr_derivative( + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, + $axis, + ) + }; + } + let terminator = loop { use spirv::Op; let start = self.data_offset; @@ -882,6 +1280,7 @@ impl> Parser { LookupExpression { handle: expressions.append(crate::Expression::Constant(handle), span), type_id, + block_id, }, ); } @@ -927,6 +1326,7 @@ impl> Parser { handle: expressions .append(crate::Expression::LocalVariable(var_handle), span), type_id: result_type_id, + block_id, }, ); emitter.start(expressions); @@ -939,7 +1339,7 @@ impl> Parser { let result_id = self.next()?; let name = format!("phi_{}", result_id); - let var_handle = local_arena.append( + let local = local_arena.append( crate::LocalVariable { name: Some(name), ty: self.lookup_type.lookup(result_type_id)?.handle, @@ -947,22 +1347,21 @@ impl> Parser { }, self.span_from(start), ); - let pointer = expressions - .append(crate::Expression::LocalVariable(var_handle), span.clone()); + let pointer = + expressions.append(crate::Expression::LocalVariable(local), span.clone()); let in_count = (inst.wc - 3) / 2; - let mut phi = PhiInstruction { - id: result_id, - pointer, - variables: Vec::with_capacity(in_count as usize), + let mut phi = PhiExpression { + local, + expressions: Vec::with_capacity(in_count as usize), }; for _ in 0..in_count { - let source_id = self.next()?; - let value = self.next()?; - phi.variables.push((source_id, value)); + let expr = self.next()?; + let block = self.next()?; + phi.expressions.push((expr, block)); } - phis.push(phi); + block_ctx.phis.push(phi); emitter.start(expressions); // Associate the lookup with an actual value, which is emitted @@ -972,6 +1371,7 @@ impl> Parser { LookupExpression { handle: expressions.append(crate::Expression::Load { pointer }, span), type_id: result_type_id, + block_id, }, ); } @@ -994,7 +1394,7 @@ impl> Parser { let lexp = self.lookup_expression.lookup(base_id)?; let lty = self.lookup_type.lookup(lexp.type_id)?; AccessExpression { - base_handle: lexp.handle, + base_handle: get_expr_handle!(base_id, lexp), type_id: lty.base_id.ok_or(Error::InvalidAccessType(lexp.type_id))?, load_override: self.lookup_load_override.get(&base_id).cloned(), } @@ -1003,6 +1403,7 @@ impl> Parser { let access_id = self.next()?; log::trace!("\t\t\tlooking up index expr {:?}", access_id); let index_expr = self.lookup_expression.lookup(access_id)?.clone(); + let index_expr_handle = get_expr_handle!(access_id, &index_expr); let index_expr_data = &expressions[index_expr.handle]; let index_maybe = match *index_expr_data { crate::Expression::Constant(const_handle) => { @@ -1090,7 +1491,7 @@ impl> Parser { }, None => crate::Expression::Access { base: acex.base_handle, - index: index_expr.handle, + index: index_expr_handle, }, }; AccessExpression { @@ -1106,7 +1507,7 @@ impl> Parser { let base_handle = expressions.append( crate::Expression::Access { base: acex.base_handle, - index: index_expr.handle, + index: index_expr_handle, }, span.clone(), ); @@ -1139,7 +1540,7 @@ impl> Parser { .append( crate::Expression::Access { base: load_expr, - index: index_expr.handle, + index: index_expr_handle, }, span.clone(), ), @@ -1165,6 +1566,7 @@ impl> Parser { let lookup_expression = LookupExpression { handle: acex.base_handle, type_id: result_type_id, + block_id, }; self.lookup_expression.insert(result_id, lookup_expression); } @@ -1177,8 +1579,10 @@ impl> Parser { let index_id = self.next()?; let root_lexp = self.lookup_expression.lookup(composite_id)?; + let root_handle = get_expr_handle!(composite_id, root_lexp); let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; let index_lexp = self.lookup_expression.lookup(index_id)?; + let index_handle = get_expr_handle!(index_id, index_lexp); let num_components = match type_arena[root_type_lookup.handle].inner { crate::TypeInner::Vector { size, .. } => size as usize, @@ -1187,7 +1591,7 @@ impl> Parser { let mut handle = expressions.append( crate::Expression::Access { - base: root_lexp.handle, + base: root_handle, index: self.index_constant_expressions[0], }, span.clone(), @@ -1195,7 +1599,7 @@ impl> Parser { for &index_expr in self.index_constant_expressions[1..num_components].iter() { let access_expr = expressions.append( crate::Expression::Access { - base: root_lexp.handle, + base: root_handle, index: index_expr, }, span.clone(), @@ -1204,7 +1608,7 @@ impl> Parser { crate::Expression::Binary { op: crate::BinaryOperator::Equal, left: index_expr, - right: index_lexp.handle, + right: index_handle, }, span.clone(), ); @@ -1223,6 +1627,7 @@ impl> Parser { LookupExpression { handle, type_id: result_type_id, + block_id, }, ); } @@ -1236,9 +1641,12 @@ impl> Parser { let index_id = self.next()?; let object_lexp = self.lookup_expression.lookup(object_id)?; + let object_handle = get_expr_handle!(object_id, object_lexp); let root_lexp = self.lookup_expression.lookup(composite_id)?; + let root_handle = get_expr_handle!(composite_id, root_lexp); let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; let index_lexp = self.lookup_expression.lookup(index_id)?; + let index_handle = get_expr_handle!(index_id, index_lexp); let num_components = match type_arena[root_type_lookup.handle].inner { crate::TypeInner::Vector { size, .. } => size as usize, @@ -1248,7 +1656,7 @@ impl> Parser { for &index_expr in self.index_constant_expressions[..num_components].iter() { let access_expr = expressions.append( crate::Expression::Access { - base: root_lexp.handle, + base: root_handle, index: index_expr, }, span.clone(), @@ -1257,14 +1665,14 @@ impl> Parser { crate::Expression::Binary { op: crate::BinaryOperator::Equal, left: index_expr, - right: index_lexp.handle, + right: index_handle, }, span.clone(), ); let handle = expressions.append( crate::Expression::Select { condition: cond, - accept: object_lexp.handle, + accept: object_handle, reject: access_expr, }, span.clone(), @@ -1284,6 +1692,7 @@ impl> Parser { LookupExpression { handle, type_id: result_type_id, + block_id, }, ); } @@ -1295,6 +1704,7 @@ impl> Parser { let base_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", base_id); let mut lexp = self.lookup_expression.lookup(base_id)?.clone(); + lexp.handle = get_expr_handle!(base_id, &lexp); for _ in 4..inst.wc { let index = self.next()?; log::trace!("\t\t\tlooking up type {:?}", lexp.type_id); @@ -1325,6 +1735,7 @@ impl> Parser { span.clone(), ), type_id, + block_id, }; } @@ -1333,6 +1744,7 @@ impl> Parser { LookupExpression { handle: lexp.handle, type_id: result_type_id, + block_id, }, ); } @@ -1349,11 +1761,13 @@ impl> Parser { } let object_lexp = self.lookup_expression.lookup(object_id)?.clone(); + let object_handle = get_expr_handle!(object_id, &object_lexp); let root_lexp = self.lookup_expression.lookup(composite_id)?.clone(); + let root_handle = get_expr_handle!(composite_id, &root_lexp); let handle = self.insert_composite( - root_lexp.handle, + root_handle, result_type_id, - object_lexp.handle, + object_handle, &selections, type_arena, expressions, @@ -1365,6 +1779,7 @@ impl> Parser { LookupExpression { handle, type_id: result_type_id, + block_id, }, ); } @@ -1378,7 +1793,8 @@ impl> Parser { let comp_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", comp_id); let lexp = self.lookup_expression.lookup(comp_id)?; - components.push(lexp.handle); + let handle = get_expr_handle!(comp_id, lexp); + components.push(handle); } let ty = self.lookup_type.lookup(result_type_id)?.handle; let first = components[0]; @@ -1397,6 +1813,7 @@ impl> Parser { LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); } @@ -1412,17 +1829,18 @@ impl> Parser { } let base_lexp = self.lookup_expression.lookup(pointer_id)?; + let base_handle = get_expr_handle!(pointer_id, base_lexp); let type_lookup = self.lookup_type.lookup(base_lexp.type_id)?; let handle = match type_arena[type_lookup.handle].inner { crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { - base_lexp.handle + base_handle } _ => match self.lookup_load_override.get(&pointer_id) { Some(&LookupLoadOverride::Loaded(handle)) => handle, //Note: we aren't handling `LookupLoadOverride::Pending` properly here _ => expressions.append( crate::Expression::Load { - pointer: base_lexp.handle, + pointer: base_handle, }, span, ), @@ -1434,12 +1852,12 @@ impl> Parser { LookupExpression { handle, type_id: result_type_id, + block_id, }, ); } Op::Store => { inst.expect_at_least(3)?; - block.extend(emitter.finish(expressions)); let pointer_id = self.next()?; let value_id = self.next()?; @@ -1448,11 +1866,15 @@ impl> Parser { let _memory_access = self.next()?; } let base_expr = self.lookup_expression.lookup(pointer_id)?; + let base_handle = get_expr_handle!(pointer_id, base_expr); let value_expr = self.lookup_expression.lookup(value_id)?; + let value_handle = get_expr_handle!(value_id, value_expr); + + block.extend(emitter.finish(expressions)); block.push( crate::Statement::Store { - pointer: base_expr.handle, - value: value_expr.handle, + pointer: base_handle, + value: value_handle, }, span, ); @@ -1461,43 +1883,35 @@ impl> Parser { // Arithmetic Instructions +, -, *, /, % Op::SNegate | Op::FNegate => { inst.expect(4)?; - self.parse_expr_unary_op(expressions, crate::UnaryOperator::Negate)?; + parse_expr_op!(crate::UnaryOperator::Negate, UNARY)?; } Op::IAdd => { inst.expect(5)?; - self.parse_expr_binary_op_sign_adjusted( - expressions, - crate::BinaryOperator::Add, - type_arena, - )?; + parse_expr_op!(crate::BinaryOperator::Add, BINARY_SIGN_ADJUSTED)?; } Op::FAdd => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::Add)?; + parse_expr_op!(crate::BinaryOperator::Add, BINARY)?; } Op::ISub => { inst.expect(5)?; - self.parse_expr_binary_op_sign_adjusted( - expressions, - crate::BinaryOperator::Subtract, - type_arena, - )?; + parse_expr_op!(crate::BinaryOperator::Subtract, BINARY_SIGN_ADJUSTED)?; } Op::FSub => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::Subtract)?; + parse_expr_op!(crate::BinaryOperator::Subtract, BINARY)?; } Op::IMul | Op::FMul => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::Multiply)?; + parse_expr_op!(crate::BinaryOperator::Multiply, BINARY)?; } Op::SDiv | Op::UDiv | Op::FDiv => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::Divide)?; + parse_expr_op!(crate::BinaryOperator::Divide, BINARY)?; } Op::SMod | Op::UMod | Op::FMod | Op::SRem | Op::FRem => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::Modulo)?; + parse_expr_op!(crate::BinaryOperator::Modulo, BINARY)?; } Op::VectorTimesScalar | Op::VectorTimesMatrix @@ -1505,7 +1919,7 @@ impl> Parser { | Op::MatrixTimesVector | Op::MatrixTimesMatrix => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::Multiply)?; + parse_expr_op!(crate::BinaryOperator::Multiply, BINARY)?; } Op::Transpose => { inst.expect(4)?; @@ -1514,9 +1928,10 @@ impl> Parser { let result_id = self.next()?; let matrix_id = self.next()?; let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; + let matrix_handle = get_expr_handle!(matrix_id, matrix_lexp); let expr = crate::Expression::Math { fun: crate::MathFunction::Transpose, - arg: matrix_lexp.handle, + arg: matrix_handle, arg1: None, arg2: None, }; @@ -1525,6 +1940,7 @@ impl> Parser { LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); } @@ -1536,11 +1952,13 @@ impl> Parser { let left_id = self.next()?; let right_id = self.next()?; let left_lexp = self.lookup_expression.lookup(left_id)?; + let left_handle = get_expr_handle!(left_id, left_lexp); let right_lexp = self.lookup_expression.lookup(right_id)?; + let right_handle = get_expr_handle!(right_id, right_lexp); let expr = crate::Expression::Math { fun: crate::MathFunction::Dot, - arg: left_lexp.handle, - arg1: Some(right_lexp.handle), + arg: left_handle, + arg1: Some(right_handle), arg2: None, }; self.lookup_expression.insert( @@ -1548,6 +1966,7 @@ impl> Parser { LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); } @@ -1559,11 +1978,13 @@ impl> Parser { let left_id = self.next()?; let right_id = self.next()?; let left_lexp = self.lookup_expression.lookup(left_id)?; + let left_handle = get_expr_handle!(left_id, left_lexp); let right_lexp = self.lookup_expression.lookup(right_id)?; + let right_handle = get_expr_handle!(right_id, right_lexp); let expr = crate::Expression::Math { fun: crate::MathFunction::Outer, - arg: left_lexp.handle, - arg1: Some(right_lexp.handle), + arg: left_handle, + arg1: Some(right_handle), arg2: None, }; self.lookup_expression.insert( @@ -1571,44 +1992,45 @@ impl> Parser { LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); } // Bitwise instructions Op::Not => { inst.expect(4)?; - self.parse_expr_unary_op(expressions, crate::UnaryOperator::Not)?; + parse_expr_op!(crate::UnaryOperator::Not, UNARY)?; } Op::BitwiseOr => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::InclusiveOr)?; + parse_expr_op!(crate::BinaryOperator::InclusiveOr, BINARY)?; } Op::BitwiseXor => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::ExclusiveOr)?; + parse_expr_op!(crate::BinaryOperator::ExclusiveOr, BINARY)?; } Op::BitwiseAnd => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::And)?; + parse_expr_op!(crate::BinaryOperator::And, BINARY)?; } Op::ShiftRightLogical => { inst.expect(5)?; //TODO: convert input and result to usigned - self.parse_expr_shift_op(expressions, crate::BinaryOperator::ShiftRight)?; + parse_expr_op!(crate::BinaryOperator::ShiftRight, SHIFT)?; } Op::ShiftRightArithmetic => { inst.expect(5)?; //TODO: convert input and result to signed - self.parse_expr_shift_op(expressions, crate::BinaryOperator::ShiftRight)?; + parse_expr_op!(crate::BinaryOperator::ShiftRight, SHIFT)?; } Op::ShiftLeftLogical => { inst.expect(5)?; - self.parse_expr_shift_op(expressions, crate::BinaryOperator::ShiftLeft)?; + parse_expr_op!(crate::BinaryOperator::ShiftLeft, SHIFT)?; } // Sampling Op::Image => { inst.expect(4)?; - self.parse_image_uncouple()?; + self.parse_image_uncouple(block_id)?; } Op::SampledImage => { inst.expect(5)?; @@ -1629,7 +2051,19 @@ impl> Parser { } Op::ImageFetch | Op::ImageRead => { let extra = inst.expect_at_least(5)?; - self.parse_image_load(extra, type_arena, global_arena, arguments, expressions)?; + self.parse_image_load( + extra, + type_arena, + global_arena, + arguments, + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, + )?; } Op::ImageSampleImplicitLod | Op::ImageSampleExplicitLod => { let extra = inst.expect_at_least(5)?; @@ -1643,8 +2077,14 @@ impl> Parser { type_arena, global_arena, arguments, - expressions, parmeter_sampling, + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, )?; } Op::ImageSampleProjImplicitLod | Op::ImageSampleProjExplicitLod => { @@ -1659,8 +2099,14 @@ impl> Parser { type_arena, global_arena, arguments, - expressions, parmeter_sampling, + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, )?; } Op::ImageSampleDrefImplicitLod | Op::ImageSampleDrefExplicitLod => { @@ -1675,8 +2121,14 @@ impl> Parser { type_arena, global_arena, arguments, - expressions, parmeter_sampling, + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, )?; } Op::ImageSampleProjDrefImplicitLod | Op::ImageSampleProjDrefExplicitLod => { @@ -1691,25 +2143,57 @@ impl> Parser { type_arena, global_arena, arguments, - expressions, parmeter_sampling, + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, )?; } Op::ImageQuerySize => { inst.expect(4)?; - self.parse_image_query_size(false, expressions)?; + self.parse_image_query_size( + false, + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, + )?; } Op::ImageQuerySizeLod => { inst.expect(5)?; - self.parse_image_query_size(true, expressions)?; + self.parse_image_query_size( + true, + block_ctx, + &mut emitter, + &mut block, + expressions, + local_arena, + block_id, + body_idx, + )?; } Op::ImageQueryLevels => { inst.expect(4)?; - self.parse_image_query_other(crate::ImageQuery::NumLevels, expressions)?; + self.parse_image_query_other( + crate::ImageQuery::NumLevels, + expressions, + block_id, + )?; } Op::ImageQuerySamples => { inst.expect(4)?; - self.parse_image_query_other(crate::ImageQuery::NumSamples, expressions)?; + self.parse_image_query_other( + crate::ImageQuery::NumSamples, + expressions, + block_id, + )?; } // other ops Op::Select => { @@ -1721,19 +2205,23 @@ impl> Parser { let o2_id = self.next()?; let cond_lexp = self.lookup_expression.lookup(condition)?; + let cond_handle = get_expr_handle!(condition, cond_lexp); let o1_lexp = self.lookup_expression.lookup(o1_id)?; + let o1_handle = get_expr_handle!(o1_id, o1_lexp); let o2_lexp = self.lookup_expression.lookup(o2_id)?; + let o2_handle = get_expr_handle!(o2_id, o2_lexp); let expr = crate::Expression::Select { - condition: cond_lexp.handle, - accept: o1_lexp.handle, - reject: o2_lexp.handle, + condition: cond_handle, + accept: o1_handle, + reject: o2_handle, }; self.lookup_expression.insert( result_id, LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); } @@ -1746,14 +2234,14 @@ impl> Parser { let v1_lexp = self.lookup_expression.lookup(v1_id)?; let v1_lty = self.lookup_type.lookup(v1_lexp.type_id)?; - let v1_handle = v1_lexp.handle; + let v1_handle = get_expr_handle!(v1_id, v1_lexp); let n1 = match type_arena[v1_lty.handle].inner { crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidInnerType(v1_lexp.type_id)), }; let v2_lexp = self.lookup_expression.lookup(v2_id)?; let v2_lty = self.lookup_type.lookup(v2_lexp.type_id)?; - let v2_handle = v2_lexp.handle; + let v2_handle = get_expr_handle!(v2_id, v2_lexp); let n2 = match type_arena[v2_lty.handle].inner { crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidInnerType(v2_lexp.type_id)), @@ -1823,6 +2311,7 @@ impl> Parser { LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); } @@ -1849,7 +2338,7 @@ impl> Parser { }; let expr = crate::Expression::As { - expr: value_lexp.handle, + expr: get_expr_handle!(value_id, value_lexp), kind, convert: if inst.op == Op::Bitcast { None @@ -1862,6 +2351,7 @@ impl> Parser { LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); } @@ -1876,7 +2366,8 @@ impl> Parser { let mut arguments = Vec::with_capacity(inst.wc as usize - 4); for _ in 0..arguments.capacity() { let arg_id = self.next()?; - arguments.push(self.lookup_expression.lookup(arg_id)?.handle); + let lexp = self.lookup_expression.lookup(arg_id)?; + arguments.push(get_expr_handle!(arg_id, lexp)); } // We just need an unique handle here, nothing more. @@ -1892,6 +2383,7 @@ impl> Parser { LookupExpression { handle: expr_handle, type_id: result_type_id, + block_id, }, ); Some(expr_handle) @@ -1926,7 +2418,8 @@ impl> Parser { inst.expect(base_wc + 1)?; let arg = { let arg_id = self.next()?; - self.lookup_expression.lookup(arg_id)?.handle + let lexp = self.lookup_expression.lookup(arg_id)?; + get_expr_handle!(arg_id, lexp) }; let constant_handle = const_arena.fetch_or_append( @@ -1962,6 +2455,7 @@ impl> Parser { span, ), type_id: result_type_id, + block_id, }, ); } else { @@ -2020,17 +2514,20 @@ impl> Parser { inst.expect(base_wc + arg_count as u16)?; let arg = { let arg_id = self.next()?; - self.lookup_expression.lookup(arg_id)?.handle + let lexp = self.lookup_expression.lookup(arg_id)?; + get_expr_handle!(arg_id, lexp) }; let arg1 = if arg_count > 1 { let arg_id = self.next()?; - Some(self.lookup_expression.lookup(arg_id)?.handle) + let lexp = self.lookup_expression.lookup(arg_id)?; + Some(get_expr_handle!(arg_id, lexp)) } else { None }; let arg2 = if arg_count > 2 { let arg_id = self.next()?; - Some(self.lookup_expression.lookup(arg_id)?.handle) + let lexp = self.lookup_expression.lookup(arg_id)?; + Some(get_expr_handle!(arg_id, lexp)) } else { None }; @@ -2046,6 +2543,7 @@ impl> Parser { LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); } @@ -2053,15 +2551,15 @@ impl> Parser { // Relational and Logical Instructions Op::LogicalNot => { inst.expect(4)?; - self.parse_expr_unary_op(expressions, crate::UnaryOperator::Not)?; + parse_expr_op!(crate::UnaryOperator::Not, UNARY)?; } Op::LogicalOr => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::LogicalOr)?; + parse_expr_op!(crate::BinaryOperator::LogicalOr, BINARY)?; } Op::LogicalAnd => { inst.expect(5)?; - self.parse_expr_binary_op(expressions, crate::BinaryOperator::LogicalAnd)?; + parse_expr_op!(crate::BinaryOperator::LogicalAnd, BINARY)?; } Op::IEqual | Op::INotEqual @@ -2089,7 +2587,7 @@ impl> Parser { | Op::LogicalNotEqual => { inst.expect(5)?; let operator = map_binary_operator(inst.op)?; - self.parse_expr_binary_op(expressions, operator)?; + parse_expr_op!(operator, BINARY)?; } Op::Any | Op::All | Op::IsNan | Op::IsInf | Op::IsFinite | Op::IsNormal => { inst.expect(4)?; @@ -2098,66 +2596,152 @@ impl> Parser { let arg_id = self.next()?; let arg_lexp = self.lookup_expression.lookup(arg_id)?; + let arg_handle = get_expr_handle!(arg_id, arg_lexp); let expr = crate::Expression::Relational { fun: map_relational_fun(inst.op)?, - argument: arg_lexp.handle, + argument: arg_handle, }; self.lookup_expression.insert( result_id, LookupExpression { handle: expressions.append(expr, span), type_id: result_type_id, + block_id, }, ); } Op::Kill => { inst.expect(1)?; - break Terminator::Kill; + break Some(crate::Statement::Kill); } Op::Unreachable => { inst.expect(1)?; - break Terminator::Unreachable; + break None; } Op::Return => { inst.expect(1)?; - break Terminator::Return { value: None }; + break Some(crate::Statement::Return { value: None }); } Op::ReturnValue => { inst.expect(2)?; let value_id = self.next()?; let value_lexp = self.lookup_expression.lookup(value_id)?; - break Terminator::Return { - value: Some(value_lexp.handle), - }; + let value_handle = get_expr_handle!(value_id, value_lexp); + break Some(crate::Statement::Return { + value: Some(value_handle), + }); } Op::Branch => { inst.expect(2)?; let target_id = self.next()?; - break Terminator::Branch { target_id }; + + // If this is a branch to a merge or continue block, + // then that ends the current body. + if let Some(info) = block_ctx.mergers.get(&target_id) { + block.extend(emitter.finish(expressions)); + block_ctx.blocks.insert(block_id, block); + let body = &mut block_ctx.bodies[body_idx]; + body.data.push(BodyFragment::BlockId(block_id)); + + merger(body, info); + + return Ok(()); + } + + // Since the target of the branch has no merge information, + // this must be the only branch to that block. This means + // we can treat it as an extension of the current `Body`. + // + // NOTE: it's possible that another branch was already made to this block + // setting the body index in which case it SHOULD NOT be overriden. + // For example a switch with falltrough, the OpSwitch will set the body to + // the respective case and the case may branch to another case in which case + // the body index shouldn't be changed + block_ctx + .body_for_label + .entry(target_id) + .or_insert(body_idx); + + break None; } Op::BranchConditional => { inst.expect_at_least(4)?; - let condition_id = self.next()?; - let condition = self.lookup_expression.lookup(condition_id)?.handle; + let condition = { + let condition_id = self.next()?; + let lexp = self.lookup_expression.lookup(condition_id)?; + get_expr_handle!(condition_id, lexp) + }; let true_id = self.next()?; let false_id = self.next()?; - break Terminator::BranchConditional { + // Start a body block for the `accept` branch. + let accept = block_ctx.bodies.len(); + let mut accept_block = Body::with_parent(body_idx); + + // If the `OpBranchConditional`target is somebody else's + // merge or continue block, then put a `Break` or `Continue` + // statement in this new body block. + if let Some(info) = block_ctx.mergers.get(&true_id) { + merger(&mut accept_block, info) + } else { + // Note the body index for the block we're branching to. + debug_assert!(block_ctx.body_for_label.insert(true_id, accept).is_none()); + } + + block_ctx.bodies.push(accept_block); + + // Handle the `reject` branch just like the `accept` block. + let reject = block_ctx.bodies.len(); + let mut reject_block = Body::with_parent(body_idx); + + if let Some(info) = block_ctx.mergers.get(&false_id) { + merger(&mut reject_block, info) + } else { + debug_assert!(block_ctx.body_for_label.insert(false_id, reject).is_none()); + } + + block_ctx.bodies.push(reject_block); + + block.extend(emitter.finish(expressions)); + block_ctx.blocks.insert(block_id, block); + let body = &mut block_ctx.bodies[body_idx]; + // Make sure the vector has space for at least two more allocations + body.data.reserve(2); + body.data.push(BodyFragment::BlockId(block_id)); + body.data.push(BodyFragment::If { condition, - true_id, - false_id, - }; + accept, + reject, + }); + + return Ok(()); } Op::Switch => { inst.expect_at_least(3)?; let selector = self.next()?; let default_id = self.next()?; + // If the previous instruction was a `OpSelectionMerge` then we must + // promote the `MergeBlockInformation` to a `SwitchMerge` + if let Some(merge) = selection_merge_block { + block_ctx + .mergers + .insert(merge, MergeBlockInformation::SwitchMerge); + } + + let default = block_ctx.bodies.len(); + block_ctx.bodies.push(Body::with_parent(body_idx)); + block_ctx + .body_for_label + .entry(default_id) + .or_insert(default); + let selector_lexp = &self.lookup_expression[&selector]; let selector_lty = self.lookup_type.lookup(selector_lexp.type_id)?; + let selector_handle = get_expr_handle!(selector, selector_lexp); let selector = match type_arena[selector_lty.handle].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, @@ -2167,7 +2751,7 @@ impl> Parser { expressions.append( crate::Expression::As { kind: crate::ScalarKind::Sint, - expr: selector_lexp.handle, + expr: selector_handle, convert: None, }, span, @@ -2176,57 +2760,123 @@ impl> Parser { crate::TypeInner::Scalar { kind: crate::ScalarKind::Sint, width: _, - } => selector_lexp.handle, + } => selector_handle, ref other => unimplemented!("Unexpected selector {:?}", other), }; - let mut targets = Vec::new(); + let mut cases = Vec::new(); for _ in 0..(inst.wc - 3) / 2 { let literal = self.next()?; let target = self.next()?; - targets.push((literal as i32, target)); + + let case_body_idx = block_ctx.bodies.len(); + let mut body = Body::with_parent(body_idx); + + if let Some(info) = block_ctx.mergers.get(&target) { + merger(&mut body, info); + } + + block_ctx.bodies.push(body); + block_ctx + .body_for_label + .entry(target) + .or_insert(case_body_idx); + + cases.push((literal as i32, case_body_idx)); } - break Terminator::Switch { + block.extend(emitter.finish(expressions)); + + let body = &mut block_ctx.bodies[body_idx]; + block_ctx.blocks.insert(block_id, block); + // Make sure the vector has space for at least two more allocations + body.data.reserve(2); + body.data.push(BodyFragment::BlockId(block_id)); + body.data.push(BodyFragment::Switch { selector, - default_id, - targets, - }; + cases, + default, + }); + + return Ok(()); } Op::SelectionMerge => { inst.expect(3)?; let merge_block_id = self.next()?; // TODO: Selection Control Mask let _selection_control = self.next()?; - let continue_block_id = None; - merge = Some(MergeInstruction { - merge_block_id, - continue_block_id, - }); + + // Indicate that the merge block is a continuation of the + // current `Body`. + block_ctx + .body_for_label + .entry(merge_block_id) + .or_insert(body_idx); + + // Let subsequent branches to the merge block know that + // they've reached the end of the selection construct. + block_ctx + .mergers + .insert(merge_block_id, MergeBlockInformation::SelectionMerge); + + selection_merge_block = Some(merge_block_id); } Op::LoopMerge => { inst.expect_at_least(4)?; let merge_block_id = self.next()?; - let continue_block_id = Some(self.next()?); + let continuing = self.next()?; // TODO: Loop Control Parameters for _ in 0..inst.wc - 3 { self.next()?; } - merge = Some(MergeInstruction { - merge_block_id, - continue_block_id, + // Indicate that the merge block is a continuation of the + // current `Body`. + block_ctx + .body_for_label + .entry(merge_block_id) + .or_insert(body_idx); + // Let subsequent branches to the merge block know that + // they're `Break` statements. + block_ctx + .mergers + .insert(merge_block_id, MergeBlockInformation::LoopMerge); + + let loop_body_idx = block_ctx.bodies.len(); + block_ctx.bodies.push(Body::with_parent(body_idx)); + + let continue_idx = block_ctx.bodies.len(); + // The continue block inherits the scope of the loop body + block_ctx.bodies.push(Body::with_parent(loop_body_idx)); + block_ctx + .body_for_label + .entry(continuing) + .or_insert(continue_idx); + // Let subsequent branches to the continue block know that + // they're `Continue` statements. + block_ctx + .mergers + .insert(continuing, MergeBlockInformation::LoopContinue); + + // The loop header always belongs to the loop body + block_ctx.body_for_label.insert(block_id, loop_body_idx); + + let parent_body = &mut block_ctx.bodies[body_idx]; + parent_body.data.push(BodyFragment::Loop { + body: loop_body_idx, + continuing: continue_idx, }); + body_idx = loop_body_idx; } Op::DPdx | Op::DPdxFine | Op::DPdxCoarse => { - self.parse_expr_derivative(expressions, crate::DerivativeAxis::X)?; + parse_expr_op!(crate::DerivativeAxis::X, DERIVATIVE)?; } Op::DPdy | Op::DPdyFine | Op::DPdyCoarse => { - self.parse_expr_derivative(expressions, crate::DerivativeAxis::Y)?; + parse_expr_op!(crate::DerivativeAxis::Y, DERIVATIVE)?; } Op::Fwidth | Op::FwidthFine | Op::FwidthCoarse => { - self.parse_expr_derivative(expressions, crate::DerivativeAxis::Width)?; + parse_expr_op!(crate::DerivativeAxis::Width, DERIVATIVE)?; } Op::ArrayLength => { inst.expect(5)?; @@ -2239,10 +2889,11 @@ impl> Parser { // wrong types or parameters are supplied here. let structure_ptr = self.lookup_expression.lookup(structure_id)?; + let structure_handle = get_expr_handle!(structure_id, structure_ptr); let member_ptr = expressions.append( crate::Expression::AccessIndex { - base: structure_ptr.handle, + base: structure_handle, index: member_index, }, span.clone(), @@ -2256,6 +2907,7 @@ impl> Parser { LookupExpression { handle: length, type_id: result_type_id, + block_id, }, ); } @@ -2273,12 +2925,14 @@ impl> Parser { // TODO: check if the source and target types are the same? let target = self.lookup_expression.lookup(target_id)?; + let target_handle = get_expr_handle!(target_id, target); let source = self.lookup_expression.lookup(source_id)?; + let source_handle = get_expr_handle!(source_id, source); // This operation is practically the same as loading and then storing, I think. let value_expr = expressions.append( crate::Expression::Load { - pointer: source.handle, + pointer: source_handle, }, span.clone(), ); @@ -2286,7 +2940,7 @@ impl> Parser { block.extend(emitter.finish(expressions)); block.push( crate::Statement::Store { - pointer: target.handle, + pointer: target_handle, value: value_expr, }, span, @@ -2339,17 +2993,16 @@ impl> Parser { }; block.extend(emitter.finish(expressions)); - Ok(ControlFlowNode { - id: block_id, - ty: None, - phis, - block, - terminator, - merge, - construct: petgraph::graph::node_index(0), - position: 0, - visited: false, - }) + if let Some(stmt) = terminator { + block.push(stmt, crate::Span::Unknown); + } + + // Save this block fragment in `block_ctx.blocks`, and mark it to be + // incorporated into the current body at `Statement` assembly time. + block_ctx.blocks.insert(block_id, block); + let body = &mut block_ctx.bodies[body_idx]; + body.data.push(BodyFragment::BlockId(block_id)); + Ok(()) } fn make_expression_storage( @@ -2371,6 +3024,10 @@ impl> Parser { LookupExpression { type_id: var.type_id, handle, + // Setting this to an invalid id will cause get_expr_handle + // to default to the main body making sure no load/stores + // are added. + block_id: 0, }, ); } @@ -2390,6 +3047,10 @@ impl> Parser { LookupExpression { type_id: con.type_id, handle, + // Setting this to an invalid id will cause get_expr_handle + // to default to the main body making sure no load/stores + // are added. + block_id: 0, }, ); } @@ -2408,8 +3069,6 @@ impl> Parser { /// Walk the statement tree and patch it in the following cases: /// 1. Function call targets are replaced by `deferred_function_calls` map - /// 2. Lift the contents of "If" that only breaks on rejection, onto the parent after it. - /// 3. Lift the contents of "Switch" that only has a default, onto the parent after it. fn patch_statements( &mut self, statements: &mut crate::Block, @@ -2429,34 +3088,18 @@ impl> Parser { ref mut accept, ref mut reject, } => { - if let [S::Break] = reject[..] { - // uplift "accept" into the parent - let extracted = mem::take(accept); - statements.splice(i + 1..i + 1, extracted); - } else { - self.patch_statements(reject, expressions, fun_parameter_sampling)?; - self.patch_statements(accept, expressions, fun_parameter_sampling)?; - } + self.patch_statements(reject, expressions, fun_parameter_sampling)?; + self.patch_statements(accept, expressions, fun_parameter_sampling)?; } S::Switch { selector: _, ref mut cases, ref mut default, } => { - if cases.is_empty() { - // uplift "default" into the parent - let extracted = mem::take(default); - statements.splice(i + 1..i + 1, extracted); - } else { - for case in cases.iter_mut() { - self.patch_statements( - &mut case.body, - expressions, - fun_parameter_sampling, - )?; - } - self.patch_statements(default, expressions, fun_parameter_sampling)?; + for case in cases.iter_mut() { + self.patch_statements(&mut case.body, expressions, fun_parameter_sampling)?; } + self.patch_statements(default, expressions, fun_parameter_sampling)?; } S::Loop { ref mut body, @@ -3894,3 +4537,18 @@ mod test { let _ = super::parse_u8_slice(&bin, &Default::default()).unwrap(); } } + +/// Helper function to check if `child` is in the scope of `parent` +fn is_parent(mut child: usize, parent: usize, block_ctx: &BlockContext) -> bool { + loop { + if child == parent { + // The child is in the scope parent + break true; + } else if child == 0 { + // Searched finished at the root the child isn't in the parent's body + break false; + } + + child = block_ctx.bodies[child].parent; + } +} diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index c71064af8..8c4e2df9e 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -1468,6 +1468,7 @@ pointer: 47, value: 118, ), + Continue, ], continuing: [ Emit(( diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 020368148..63d99ebad 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -511,7 +511,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { &naga::front::spv::Options { adjust_coordinate_space, strict_capabilities: false, - flow_graph_dump_prefix: None, + block_ctx_dump_prefix: None, }, ) .unwrap(); From 439148b1a76a0bc31d95a67064a8016176547a32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 10 Sep 2021 17:23:38 +0100 Subject: [PATCH 1329/2212] [spv-in] Move essential code out of debug_assert --- src/front/spv/mod.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 50608113a..6c14d161b 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2688,7 +2688,8 @@ impl> Parser { merger(&mut accept_block, info) } else { // Note the body index for the block we're branching to. - debug_assert!(block_ctx.body_for_label.insert(true_id, accept).is_none()); + let prev = block_ctx.body_for_label.insert(true_id, accept); + debug_assert!(prev.is_none()); } block_ctx.bodies.push(accept_block); @@ -2700,7 +2701,8 @@ impl> Parser { if let Some(info) = block_ctx.mergers.get(&false_id) { merger(&mut reject_block, info) } else { - debug_assert!(block_ctx.body_for_label.insert(false_id, reject).is_none()); + let prev = block_ctx.body_for_label.insert(false_id, reject); + debug_assert!(prev.is_none()); } block_ctx.bodies.push(reject_block); From 130f802c89d488b719a0e494f3e1ea9ba6f5ba92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 10 Sep 2021 20:52:45 +0100 Subject: [PATCH 1330/2212] Make span copyable (#1314) * Make span copyable * Use fixed size integers for span --- src/arena.rs | 13 +++- src/block.rs | 4 +- src/front/glsl/builtins.rs | 9 +-- src/front/glsl/constants.rs | 10 +-- src/front/glsl/context.rs | 10 +-- src/front/glsl/functions.rs | 6 +- src/front/glsl/offset.rs | 4 +- src/front/glsl/parser/functions.rs | 8 +- src/front/glsl/token.rs | 2 +- src/front/mod.rs | 2 +- src/front/spv/function.rs | 61 ++++++++------- src/front/spv/image.rs | 41 +++++----- src/front/spv/mod.rs | 97 +++++++++++------------ src/front/spv/null.rs | 18 ++--- src/front/wgsl/mod.rs | 119 +++++++++++++---------------- src/span.rs | 74 ++++++++++++------ 16 files changed, 241 insertions(+), 237 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index c7b9e8664..d93a7877a 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -260,15 +260,18 @@ impl Arena { self.data.clear() } - pub fn get_span(&self, handle: Handle) -> &Span { + pub fn get_span(&self, handle: Handle) -> Span { #[cfg(feature = "span")] { - return self.span_info.get(handle.index()).unwrap_or(&Span::Unknown); + *self + .span_info + .get(handle.index()) + .unwrap_or(&Span::default()) } #[cfg(not(feature = "span"))] { let _ = handle; - &Span::Unknown + Span::default() } } } @@ -284,7 +287,9 @@ where { let data = Vec::deserialize(deserializer)?; #[cfg(feature = "span")] - let span_info = std::iter::repeat(Span::Unknown).take(data.len()).collect(); + let span_info = std::iter::repeat(Span::default()) + .take(data.len()) + .collect(); Ok(Self { data, diff --git a/src/block.rs b/src/block.rs index 5b832ba8f..1a35e4394 100644 --- a/src/block.rs +++ b/src/block.rs @@ -23,7 +23,9 @@ impl Block { pub fn from_vec(body: Vec) -> Self { #[cfg(feature = "span")] - let span_info = std::iter::repeat(Span::Unknown).take(body.len()).collect(); + let span_info = std::iter::repeat(Span::default()) + .take(body.len()) + .collect(); Self { body, #[cfg(feature = "span")] diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 922c1af7b..e6219e62c 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -21,7 +21,7 @@ impl Module { name: None, inner: arg, }, - Span::Unknown, + Span::default(), )); parameters_info.push(ParameterInfo { qualifier: ParameterQualifier::In, @@ -1190,7 +1190,7 @@ fn inject_common_builtin( }, }, }, - Span::Unknown, + Span::default(), ); let parameters = vec![ty, ty]; @@ -1340,7 +1340,6 @@ fn inject_common_builtin( } } "smoothstep" => { - // bits layout // bit 0 - splatted // bit 1 trough 2 - dims for bits in 0..(0b1000) { @@ -1624,7 +1623,7 @@ impl MacroCall { value: ScalarValue::Float(value), }, }, - Span::Unknown, + Span::default(), ); let right = ctx.add_expression( Expression::Constant(constant), @@ -1832,7 +1831,7 @@ pub fn sampled_to_depth( class: ImageClass::Depth { multi }, }, }, - Span::Unknown, + Span::default(), ) } ImageClass::Depth { .. } => {} diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 0ac7f69d2..4d2a1a900 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -64,7 +64,7 @@ impl<'a> ConstantSolver<'a> { &mut self, expr: Handle, ) -> Result, ConstantSolvingError> { - let span = self.expressions.get_span(expr).clone(); + let span = self.expressions.get_span(expr); match self.expressions[expr] { Expression::Constant(constant) => Ok(constant), Expression::AccessIndex { base, index } => self.access(base, index as usize), @@ -338,7 +338,7 @@ impl<'a> ConstantSolver<'a> { } for component in components { - *component = self.cast(*component, kind, target_width, span.clone())?; + *component = self.cast(*component, kind, target_width, span)?; } } } @@ -385,7 +385,7 @@ impl<'a> ConstantSolver<'a> { } for component in components { - *component = self.unary_op(op, *component, span.clone())? + *component = self.unary_op(op, *component, span)? } } } @@ -486,14 +486,14 @@ impl<'a> ConstantSolver<'a> { (&ConstantInner::Composite { ref components, ty }, &ConstantInner::Scalar { .. }) => { let mut components = components.clone(); for comp in components.iter_mut() { - *comp = self.binary_op(op, *comp, right, span.clone())?; + *comp = self.binary_op(op, *comp, right, span)?; } ConstantInner::Composite { ty, components } } (&ConstantInner::Scalar { .. }, &ConstantInner::Composite { ref components, ty }) => { let mut components = components.clone(); for comp in components.iter_mut() { - *comp = self.binary_op(op, left, *comp, span.clone())?; + *comp = self.binary_op(op, left, *comp, span)?; } ConstantInner::Composite { ty, components } } diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index eb40a6a3f..2ff59a8ea 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -101,7 +101,7 @@ impl Context { self.emit_flush(body); let (expr, load) = match kind { GlobalLookupKind::Variable(v) => { - let span = parser.module.global_variables.get_span(v).clone(); + let span = parser.module.global_variables.get_span(v); let res = ( self.expressions.append(Expression::GlobalVariable(v), span), parser.module.global_variables[v].class != StorageClass::Handle, @@ -111,10 +111,10 @@ impl Context { res } GlobalLookupKind::BlockSelect(handle, index) => { - let span = parser.module.global_variables.get_span(handle).clone(); + let span = parser.module.global_variables.get_span(handle); let base = self .expressions - .append(Expression::GlobalVariable(handle), span.clone()); + .append(Expression::GlobalVariable(handle), span); self.emit_start(); let expr = self .expressions @@ -140,7 +140,7 @@ impl Context { }) } GlobalLookupKind::Constant(v) => { - let span = parser.module.constants.get_span(v).clone(); + let span = parser.module.constants.get_span(v); let res = ( self.expressions.append(Expression::Constant(v), span), false, @@ -245,7 +245,7 @@ impl Context { }; if qualifier.is_lhs() { - let span = parser.module.types.get_span(arg.ty).clone(); + let span = parser.module.types.get_span(arg.ty); arg.ty = parser.module.types.fetch_or_append( Type { name: None, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index b2a512509..95d434700 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -578,7 +578,7 @@ impl Parser { name: None, inner: TypeInner::Vector { size, kind, width }, }, - Span::Unknown, + Span::default(), ); let temp_var = ctx.locals.append( LocalVariable { @@ -586,7 +586,7 @@ impl Parser { ty, init: None, }, - Span::Unknown, + Span::default(), ); let temp_expr = ctx.add_expression( Expression::LocalVariable(temp_var), @@ -599,7 +599,7 @@ impl Parser { pointer: temp_expr, value: handle, }, - Span::Unknown, + Span::default(), ); arguments.push(temp_expr); diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 2d4f238da..d6ac4d3f1 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -84,7 +84,7 @@ pub fn calculate_offset( crate::ArraySize::Dynamic => stride, }; - let ty_span = types.get_span(ty).clone(); + let ty_span = types.get_span(ty); ty = types.fetch_or_append( Type { name, @@ -144,7 +144,7 @@ pub fn calculate_offset( span = align_up(span, align); - let ty_span = types.get_span(ty).clone(); + let ty_span = types.get_span(ty); ty = types.fetch_or_append( Type { name, diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index a3a1ef37f..3110cdbae 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -55,7 +55,7 @@ impl<'source> ParsingContext<'source> { let new_break = || { let mut block = Block::new(); - block.push(Statement::Break, crate::Span::Unknown); + block.push(Statement::Break, crate::Span::default()); block }; @@ -332,7 +332,7 @@ impl<'source> ParsingContext<'source> { accept: new_break(), reject: Block::new(), }, - crate::Span::Unknown, + crate::Span::default(), ); let mut meta = meta.union(&expr_meta); @@ -389,7 +389,7 @@ impl<'source> ParsingContext<'source> { accept: new_break(), reject: Block::new(), }, - crate::Span::Unknown, + crate::Span::default(), ); body.push( @@ -474,7 +474,7 @@ impl<'source> ParsingContext<'source> { accept: new_break(), reject: Block::new(), }, - crate::Span::Unknown, + crate::Span::default(), ); self.expect(parser, TokenValue::Semicolon)?; diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 230362794..0980ed5fc 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -57,7 +57,7 @@ impl SourceMetadata { } pub fn as_span(&self) -> crate::Span { - crate::Span::ByteRange(self.start..self.end) + crate::Span::new(self.start as u32, self.end as u32) } pub(crate) fn none() -> Self { diff --git a/src/front/mod.rs b/src/front/mod.rs index 8c7b03a7e..292acf3da 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -36,7 +36,7 @@ impl Emitter { let start_len = self.start_len.take().unwrap(); if start_len != arena.len() { #[allow(unused_mut)] - let mut span = crate::span::Span::Unknown; + let mut span = crate::span::Span::default(); let range = arena.range_from(start_len); #[cfg(feature = "span")] for handle in range.clone() { diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index ac9f78fc2..d7cf7129b 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -176,7 +176,7 @@ impl> super::Parser { // Get a pointer to the local variable for the phi's value. let phi_pointer = fun.expressions.append( crate::Expression::LocalVariable(phi.local), - crate::Span::Unknown, + crate::Span::default(), ); // At the end of each of `phi`'s predecessor blocks, store the corresponding @@ -219,26 +219,26 @@ impl> super::Parser { ty, init: None, }, - crate::Span::Unknown, + crate::Span::default(), ); let pointer = fun.expressions.append( crate::Expression::LocalVariable(local), - crate::Span::Unknown, + crate::Span::default(), ); // Get the spilled value of the source expression. let start = fun.expressions.len(); let expr = fun .expressions - .append(crate::Expression::Load { pointer }, crate::Span::Unknown); + .append(crate::Expression::Load { pointer }, crate::Span::default()); let range = fun.expressions.range_from(start); block_ctx .blocks .get_mut(&predecessor) .unwrap() - .push(crate::Statement::Emit(range), crate::Span::Unknown); + .push(crate::Statement::Emit(range), crate::Span::default()); // At the end of the block that defines it, spill the source // expression's value. @@ -251,7 +251,7 @@ impl> super::Parser { pointer, value: source_lexp.handle, }, - crate::Span::Unknown, + crate::Span::default(), ); expr @@ -264,7 +264,7 @@ impl> super::Parser { pointer: phi_pointer, value, }, - crate::Span::Unknown, + crate::Span::default(), ) } } @@ -297,10 +297,10 @@ impl> super::Parser { for &v_id in ep.variable_ids.iter() { let lvar = self.lookup_variable.lookup(v_id)?; if let super::Variable::Input(ref arg) = lvar.inner { - let span = module.global_variables.get_span(lvar.handle).clone(); + let span = module.global_variables.get_span(lvar.handle); let arg_expr = function.expressions.append( crate::Expression::FunctionArgument(function.arguments.len() as u32), - span.clone(), + span, ); let load_expr = if arg.ty == module.global_variables[lvar.handle].ty { arg_expr @@ -315,17 +315,16 @@ impl> super::Parser { kind: crate::ScalarKind::Sint, convert: Some(4), }, - span.clone(), + span, ); function.body.extend(emitter.finish(&function.expressions)); handle }; function.body.push( crate::Statement::Store { - pointer: function.expressions.append( - crate::Expression::GlobalVariable(lvar.handle), - span.clone(), - ), + pointer: function + .expressions + .append(crate::Expression::GlobalVariable(lvar.handle), span), value: load_expr, }, span, @@ -354,7 +353,7 @@ impl> super::Parser { arguments: Vec::new(), result: None, }, - crate::Span::Unknown, + crate::Span::default(), ); // 3. copy the outputs from privates to the result @@ -363,10 +362,10 @@ impl> super::Parser { for &v_id in ep.variable_ids.iter() { let lvar = self.lookup_variable.lookup(v_id)?; if let super::Variable::Output(ref result) = lvar.inner { - let span = module.global_variables.get_span(lvar.handle).clone(); + let span = module.global_variables.get_span(lvar.handle); let expr_handle = function .expressions - .append(crate::Expression::GlobalVariable(lvar.handle), span.clone()); + .append(crate::Expression::GlobalVariable(lvar.handle), span); match module.types[result.ty].inner { crate::TypeInner::Struct { members: ref sub_members, @@ -383,7 +382,7 @@ impl> super::Parser { base: expr_handle, index: index as u32, }, - span.clone(), + span, )); } } @@ -410,26 +409,26 @@ impl> super::Parser { let mut emitter = Emitter::default(); emitter.start(&function.expressions); let global_expr = components[member_index]; - let span = function.expressions.get_span(global_expr).clone(); + let span = function.expressions.get_span(global_expr); let access_expr = function.expressions.append( crate::Expression::AccessIndex { base: global_expr, index: 1, }, - span.clone(), + span, ); let load_expr = function.expressions.append( crate::Expression::Load { pointer: access_expr, }, - span.clone(), + span, ); let neg_expr = function.expressions.append( crate::Expression::Unary { op: crate::UnaryOperator::Negate, expr: load_expr, }, - span.clone(), + span, ); function.body.extend(emitter.finish(&function.expressions)); function.body.push( @@ -450,7 +449,7 @@ impl> super::Parser { let load_expr = crate::Expression::Load { pointer: *component, }; - let span = function.expressions.get_span(*component).clone(); + let span = function.expressions.get_span(*component); *component = function.expressions.append(load_expr, span); } @@ -458,7 +457,7 @@ impl> super::Parser { [] => {} [member] => { function.body.extend(emitter.finish(&function.expressions)); - let span = function.expressions.get_span(components[0]).clone(); + let span = function.expressions.get_span(components[0]); function.body.push( crate::Statement::Return { value: components.first().cloned(), @@ -483,11 +482,11 @@ impl> super::Parser { span: 0xFFFF, // shouldn't matter }, }, - span.clone(), + span, ); let result_expr = function .expressions - .append(crate::Expression::Compose { ty, components }, span.clone()); + .append(crate::Expression::Compose { ty, components }, span); function.body.extend(emitter.finish(&function.expressions)); function.body.push( crate::Statement::Return { @@ -541,7 +540,7 @@ impl BlockContext { accept, reject, }, - crate::Span::Unknown, + crate::Span::default(), ) } super::BodyFragment::Loop { body, continuing } => { @@ -550,7 +549,7 @@ impl BlockContext { block.push( crate::Statement::Loop { body, continuing }, - crate::Span::Unknown, + crate::Span::default(), ) } super::BodyFragment::Switch { @@ -578,14 +577,14 @@ impl BlockContext { .collect(), default, }, - crate::Span::Unknown, + crate::Span::default(), ) } super::BodyFragment::Break => { - block.push(crate::Statement::Break, crate::Span::Unknown) + block.push(crate::Statement::Break, crate::Span::default()) } super::BodyFragment::Continue => { - block.push(crate::Statement::Continue, crate::Span::Unknown) + block.push(crate::Statement::Continue, crate::Span::default()) } } } diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index fb688a53e..1f1baf805 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -89,22 +89,19 @@ fn extract_image_coordinates( index: required_size.map_or(1, |size| size as u32), }; - let base_span = expressions.get_span(base).clone(); + let base_span = expressions.get_span(base); match extra_coordinate { ExtraCoordinate::ArrayLayer => { let extracted = match required_size { - None => expressions.append( - crate::Expression::AccessIndex { base, index: 0 }, - base_span.clone(), - ), + None => { + expressions.append(crate::Expression::AccessIndex { base, index: 0 }, base_span) + } Some(size) => { let mut components = Vec::with_capacity(size as usize); for index in 0..size as u32 { - let comp = expressions.append( - crate::Expression::AccessIndex { base, index }, - base_span.clone(), - ); + let comp = expressions + .append(crate::Expression::AccessIndex { base, index }, base_span); components.push(comp); } expressions.append( @@ -112,11 +109,11 @@ fn extract_image_coordinates( ty: required_ty.unwrap(), components, }, - base_span.clone(), + base_span, ) } }; - let array_index_f32 = expressions.append(extra_expr, base_span.clone()); + let array_index_f32 = expressions.append(extra_expr, base_span); let array_index = expressions.append( crate::Expression::As { kind: crate::ScalarKind::Sint, @@ -128,13 +125,11 @@ fn extract_image_coordinates( (extracted, Some(array_index)) } ExtraCoordinate::Projection => { - let projection = expressions.append(extra_expr, base_span.clone()); + let projection = expressions.append(extra_expr, base_span); let divided = match required_size { None => { - let temp = expressions.append( - crate::Expression::AccessIndex { base, index: 0 }, - base_span.clone(), - ); + let temp = expressions + .append(crate::Expression::AccessIndex { base, index: 0 }, base_span); expressions.append( crate::Expression::Binary { op: crate::BinaryOperator::Divide, @@ -147,17 +142,15 @@ fn extract_image_coordinates( Some(size) => { let mut components = Vec::with_capacity(size as usize); for index in 0..size as u32 { - let temp = expressions.append( - crate::Expression::AccessIndex { base, index }, - base_span.clone(), - ); + let temp = expressions + .append(crate::Expression::AccessIndex { base, index }, base_span); let comp = expressions.append( crate::Expression::Binary { op: crate::BinaryOperator::Divide, left: temp, right: projection, }, - base_span.clone(), + base_span, ); components.push(comp); } @@ -202,7 +195,7 @@ pub(super) fn patch_comparison_type( log::debug!("Flipping comparison for {:?}", var); let original_ty = &arena[var.ty]; - let original_ty_span = arena.get_span(var.ty).clone(); + let original_ty_span = arena.get_span(var.ty); let ty_inner = match original_ty.inner { crate::TypeInner::Image { class: crate::ImageClass::Sampled { multi, .. }, @@ -637,7 +630,7 @@ impl> super::Parser { base: coord_handle, index: required_size.map_or(1, |size| size as u32), }, - crate::Span::Unknown, + crate::Span::default(), ); expr = expressions.append( crate::Expression::Binary { @@ -645,7 +638,7 @@ impl> super::Parser { left: expr, right, }, - crate::Span::Unknown, + crate::Span::default(), ) }; Some(expr) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 6c14d161b..85c1faf90 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -564,11 +564,11 @@ impl> Parser { } fn span_from(&self, from: usize) -> crate::Span { - crate::Span::ByteRange(from..self.data_offset) + crate::Span::from(from..self.data_offset) } fn span_from_with_op(&self, from: usize) -> crate::Span { - crate::Span::ByteRange((from - 4)..self.data_offset) + crate::Span::from((from - 4)..self.data_offset) } fn next(&mut self) -> Result { @@ -742,17 +742,17 @@ impl> Parser { ty, init: None, }, - crate::Span::Unknown, + crate::Span::default(), ); block.extend(emitter.finish(expressions)); let pointer = expressions.append( crate::Expression::LocalVariable(local), - crate::Span::Unknown, + crate::Span::default(), ); emitter.start(expressions); let expr = - expressions.append(crate::Expression::Load { pointer }, crate::Span::Unknown); + expressions.append(crate::Expression::Load { pointer }, crate::Span::default()); // Add a slightly odd entry to the phi table, so that while `id`'s // `Expression` is still in scope, the usual phi processing will @@ -924,7 +924,7 @@ impl> Parser { kind, convert: None, }, - span.clone(), + span, ) }, right: if p2_lexp.type_id == result_type_id { @@ -936,7 +936,7 @@ impl> Parser { kind, convert: None, }, - span.clone(), + span, ) }, }; @@ -1001,7 +1001,7 @@ impl> Parser { kind: crate::ScalarKind::Uint, convert: None, }, - span.clone(), + span, ); let expr = crate::Expression::Binary { op, left, right }; @@ -1075,7 +1075,7 @@ impl> Parser { Some(&index) => index, None => return Ok(object_expr), }; - let root_span = expressions.get_span(root_expr).clone(); + let root_span = expressions.get_span(root_expr); let root_lookup = self.lookup_type.lookup(root_type_id)?; let (count, child_type_id) = match type_arena[root_lookup.handle].inner { crate::TypeInner::Struct { ref members, .. } => { @@ -1103,11 +1103,7 @@ impl> Parser { base: root_expr, index, }, - if index == selection { - span.clone() - } else { - root_span.clone() - }, + if index == selection { span } else { root_span }, ); components.push(expr); } @@ -1118,7 +1114,7 @@ impl> Parser { &selections[1..], type_arena, expressions, - span.clone(), + span, )?; Ok(expressions.append( @@ -1260,7 +1256,7 @@ impl> Parser { use spirv::Op; let start = self.data_offset; let inst = self.next_inst()?; - let span = crate::Span::ByteRange(start..(start + 4 * (inst.wc as usize))); + let span = crate::Span::from(start..(start + 4 * (inst.wc as usize))); log::debug!("\t\t{:?} [{}]", inst.op, inst.wc); match inst.op { @@ -1317,7 +1313,7 @@ impl> Parser { }, init, }, - span.clone(), + span, ); self.lookup_expression.insert( @@ -1347,8 +1343,7 @@ impl> Parser { }, self.span_from(start), ); - let pointer = - expressions.append(crate::Expression::LocalVariable(local), span.clone()); + let pointer = expressions.append(crate::Expression::LocalVariable(local), span); let in_count = (inst.wc - 3) / 2; let mut phi = PhiExpression { @@ -1430,7 +1425,7 @@ impl> Parser { base: acex.base_handle, index, }, - span.clone(), + span, ); AccessExpression { base_handle, @@ -1446,7 +1441,7 @@ impl> Parser { crate::Expression::Load { pointer: base_handle, }, - span.clone(), + span, ); let transposed = expressions.append( crate::Expression::Math { @@ -1455,7 +1450,7 @@ impl> Parser { arg1: None, arg2: None, }, - span.clone(), + span, ); LookupLoadOverride::Loaded(transposed) } @@ -1478,7 +1473,7 @@ impl> Parser { base: load_expr, index, }, - span.clone(), + span, ); Some(LookupLoadOverride::Loaded(sub_handle)) } @@ -1495,7 +1490,7 @@ impl> Parser { }, }; AccessExpression { - base_handle: expressions.append(sub_expr, span.clone()), + base_handle: expressions.append(sub_expr, span), type_id: type_lookup .base_id .ok_or(Error::InvalidAccessType(acex.type_id))?, @@ -1509,7 +1504,7 @@ impl> Parser { base: acex.base_handle, index: index_expr_handle, }, - span.clone(), + span, ); let load_override = match acex.load_override { // If there is a load override in place, then we always end up @@ -1523,7 +1518,7 @@ impl> Parser { crate::Expression::Load { pointer: base_handle, }, - span.clone(), + span, ); expressions.append( crate::Expression::Math { @@ -1532,7 +1527,7 @@ impl> Parser { arg1: None, arg2: None, }, - span.clone(), + span, ) } // We are indexing inside a row-major matrix. @@ -1542,7 +1537,7 @@ impl> Parser { base: load_expr, index: index_expr_handle, }, - span.clone(), + span, ), }; Some(LookupLoadOverride::Loaded(sub_expr)) @@ -1594,7 +1589,7 @@ impl> Parser { base: root_handle, index: self.index_constant_expressions[0], }, - span.clone(), + span, ); for &index_expr in self.index_constant_expressions[1..num_components].iter() { let access_expr = expressions.append( @@ -1602,7 +1597,7 @@ impl> Parser { base: root_handle, index: index_expr, }, - span.clone(), + span, ); let cond = expressions.append( crate::Expression::Binary { @@ -1610,7 +1605,7 @@ impl> Parser { left: index_expr, right: index_handle, }, - span.clone(), + span, ); handle = expressions.append( crate::Expression::Select { @@ -1618,7 +1613,7 @@ impl> Parser { accept: access_expr, reject: handle, }, - span.clone(), + span, ); } @@ -1659,7 +1654,7 @@ impl> Parser { base: root_handle, index: index_expr, }, - span.clone(), + span, ); let cond = expressions.append( crate::Expression::Binary { @@ -1667,7 +1662,7 @@ impl> Parser { left: index_expr, right: index_handle, }, - span.clone(), + span, ); let handle = expressions.append( crate::Expression::Select { @@ -1675,7 +1670,7 @@ impl> Parser { accept: object_handle, reject: access_expr, }, - span.clone(), + span, ); components.push(handle); } @@ -1684,7 +1679,7 @@ impl> Parser { ty: root_type_lookup.handle, components, }, - span.clone(), + span, ); self.lookup_expression.insert( @@ -1732,7 +1727,7 @@ impl> Parser { base: lexp.handle, index, }, - span.clone(), + span, ), type_id, block_id, @@ -2298,7 +2293,7 @@ impl> Parser { } else { return Err(Error::InvalidAccessIndex(index)); }; - components.push(expressions.append(expr, span.clone())); + components.push(expressions.append(expr, span)); } crate::Expression::Compose { ty: self.lookup_type.lookup(result_type_id)?.handle, @@ -2376,8 +2371,8 @@ impl> Parser { let result = if self.lookup_void_type == Some(result_type_id) { None } else { - let expr_handle = expressions - .append(crate::Expression::CallResult(function), span.clone()); + let expr_handle = + expressions.append(crate::Expression::CallResult(function), span); self.lookup_expression.insert( result_id, LookupExpression { @@ -2898,7 +2893,7 @@ impl> Parser { base: structure_handle, index: member_index, }, - span.clone(), + span, ); let length = @@ -2936,7 +2931,7 @@ impl> Parser { crate::Expression::Load { pointer: source_handle, }, - span.clone(), + span, ); block.extend(emitter.finish(expressions)); @@ -2996,7 +2991,7 @@ impl> Parser { block.extend(emitter.finish(expressions)); if let Some(stmt) = terminator { - block.push(stmt, crate::Span::Unknown); + block.push(stmt, crate::Span::default()); } // Save this block fragment in `block_ctx.blocks`, and mark it to be @@ -3019,7 +3014,7 @@ impl> Parser { } // register global variables for (&id, var) in self.lookup_variable.iter() { - let span = globals.get_span(var.handle).clone(); + let span = globals.get_span(var.handle); let handle = expressions.append(crate::Expression::GlobalVariable(var.handle), span); self.lookup_expression.insert( id, @@ -3036,13 +3031,13 @@ impl> Parser { // register special constants self.index_constant_expressions.clear(); for &con_handle in self.index_constants.iter() { - let span = constants.get_span(con_handle).clone(); + let span = constants.get_span(con_handle); let handle = expressions.append(crate::Expression::Constant(con_handle), span); self.index_constant_expressions.push(handle); } // register constants for (&id, con) in self.lookup_constant.iter() { - let span = constants.get_span(con.handle).clone(); + let span = constants.get_span(con.handle); let handle = expressions.append(crate::Expression::Constant(con.handle), span); self.lookup_expression.insert( id, @@ -3298,7 +3293,7 @@ impl> Parser { // add it to the newly formed arena, and adjust the lookup lookup.handle = module .functions - .append(fun, functions.get_span(lookup.handle).clone()); + .append(fun, functions.get_span(lookup.handle)); } } // patch all the functions @@ -4247,7 +4242,7 @@ impl> Parser { let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; - let inner = null::generate_null_constant(ty, types, constants, span.clone())?; + let inner = null::generate_null_constant(ty, types, constants, span)?; let handle = constants.append( crate::Constant { name: self.future_decor.remove(&id).and_then(|dec| dec.name), @@ -4427,7 +4422,7 @@ impl> Parser { effective_ty, &module.types, &mut module.constants, - span.clone(), + span, ) { Ok(handle) => Some(handle), Err(e) => { @@ -4458,7 +4453,7 @@ impl> Parser { member_ty, &module.types, &mut module.constants, - span.clone(), + span, )?; components.push(handle); } @@ -4471,7 +4466,7 @@ impl> Parser { components, }, }, - span.clone(), + span, )) } _ => None, diff --git a/src/front/spv/null.rs b/src/front/spv/null.rs index 8dfe55e89..b6c8ca33c 100644 --- a/src/front/spv/null.rs +++ b/src/front/spv/null.rs @@ -30,7 +30,7 @@ pub fn generate_null_constant( specialization: None, inner: make_scalar_inner(kind, width), }, - span.clone(), + span, )); } crate::ConstantInner::Composite { ty, components } @@ -51,8 +51,7 @@ pub fn generate_null_constant( } }) .unwrap(); - let vector_inner = - generate_null_constant(vector_ty, type_arena, constant_arena, span.clone())?; + let vector_inner = generate_null_constant(vector_ty, type_arena, constant_arena, span)?; let vector_handle = constant_arena.fetch_or_append( crate::Constant { name: None, @@ -71,15 +70,14 @@ pub fn generate_null_constant( // copy out the types to avoid borrowing `members` let member_tys = members.iter().map(|member| member.ty).collect::>(); for member_ty in member_tys { - let inner = - generate_null_constant(member_ty, type_arena, constant_arena, span.clone())?; + let inner = generate_null_constant(member_ty, type_arena, constant_arena, span)?; components.push(constant_arena.fetch_or_append( crate::Constant { name: None, specialization: None, inner, }, - span.clone(), + span, )); } crate::ConstantInner::Composite { ty, components } @@ -92,7 +90,7 @@ pub fn generate_null_constant( let size = constant_arena[handle] .to_array_length() .ok_or(Error::InvalidArraySize(handle))?; - let inner = generate_null_constant(base, type_arena, constant_arena, span.clone())?; + let inner = generate_null_constant(base, type_arena, constant_arena, span)?; let value = constant_arena.fetch_or_append( crate::Constant { name: None, @@ -133,7 +131,7 @@ pub fn generate_default_built_in( width: 4, }, }, - span.clone(), + span, ); let one = constant_arena.fetch_or_append( crate::Constant { @@ -144,7 +142,7 @@ pub fn generate_default_built_in( width: 4, }, }, - span.clone(), + span, ); crate::ConstantInner::Composite { ty, @@ -164,7 +162,7 @@ pub fn generate_default_built_in( width: 4, }, //Note: `crate::BuiltIn::ClipDistance` is intentionally left for the default path - _ => generate_null_constant(ty, type_arena, constant_arena, span.clone())?, + _ => generate_null_constant(ty, type_arena, constant_arena, span)?, }; Ok(constant_arena.fetch_or_append( crate::Constant { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5e39a280d..84018f534 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -829,15 +829,15 @@ impl<'a> ExpressionContext<'a, '_, '_> { ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>>, ) -> Result, Error<'a>> { - let start = lexer.current_byte_offset(); + let start = lexer.current_byte_offset() as u32; let mut left = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); let right = parser(lexer, self.reborrow())?; - let end = lexer.current_byte_offset(); + let end = lexer.current_byte_offset() as u32; left = self.expressions.append( crate::Expression::Binary { op, left, right }, - NagaSpan::ByteRange(start..end), + NagaSpan::new(start, end), ); } Ok(left) @@ -852,12 +852,12 @@ impl<'a> ExpressionContext<'a, '_, '_> { ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>>, ) -> Result, Error<'a>> { - let start = lexer.current_byte_offset(); + let start = lexer.current_byte_offset() as u32; let mut left = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); let mut right = parser(lexer, self.reborrow())?; - let end = lexer.current_byte_offset(); + let end = lexer.current_byte_offset() as u32; // insert splats, if needed by the non-'*' operations if op != crate::BinaryOperator::Multiply { let left_size = match *self.resolve_type(left)? { @@ -868,13 +868,13 @@ impl<'a> ExpressionContext<'a, '_, '_> { (Some(size), &crate::TypeInner::Scalar { .. }) => { right = self.expressions.append( crate::Expression::Splat { size, value: right }, - self.expressions.get_span(right).clone(), + self.expressions.get_span(right), ); } (None, &crate::TypeInner::Vector { size, .. }) => { left = self.expressions.append( crate::Expression::Splat { size, value: left }, - self.expressions.get_span(left).clone(), + self.expressions.get_span(left), ); } _ => {} @@ -882,7 +882,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { } left = self.expressions.append( crate::Expression::Binary { op, left, right }, - NagaSpan::ByteRange(start..end), + NagaSpan::new(start, end), ); } Ok(left) @@ -1274,7 +1274,8 @@ impl Parser { _ => return Err(Error::InvalidAtomicOperandType(value_span)), }; - let result = ctx.interrupt_emitter(expression, NagaSpan::ByteRange(value_span.clone())); + let span = NagaSpan::from(value_span); + let result = ctx.interrupt_emitter(expression, span); ctx.block.push( crate::Statement::Atomic { pointer, @@ -1282,7 +1283,7 @@ impl Parser { value, result, }, - NagaSpan::ByteRange(value_span), + span, ); Ok(result) } @@ -1483,9 +1484,8 @@ impl Parser { _ => return Err(Error::InvalidAtomicOperandType(value_span)), }; - let span = self.peek_scope(lexer); - let result = - ctx.interrupt_emitter(expression, NagaSpan::ByteRange(span.clone())); + let span = NagaSpan::from(self.peek_scope(lexer)); + let result = ctx.interrupt_emitter(expression, span); ctx.block.push( crate::Statement::Atomic { pointer, @@ -1493,7 +1493,7 @@ impl Parser { value, result, }, - NagaSpan::ByteRange(span), + span, ); return Ok(Some(result)); } @@ -1784,10 +1784,10 @@ impl Parser { let handle = match self.parse_local_function_call(lexer, name, ctx.reborrow())? { Some((function, arguments)) => { - let span = self.peek_scope(lexer); + let span = NagaSpan::from(self.peek_scope(lexer)); let result = Some(ctx.interrupt_emitter( crate::Expression::CallResult(function), - NagaSpan::ByteRange(span.clone()), + span, )); ctx.block.push( crate::Statement::Call { @@ -1795,7 +1795,7 @@ impl Parser { arguments, result, }, - NagaSpan::ByteRange(span), + span, ); result } @@ -1805,10 +1805,8 @@ impl Parser { } } }; - let span = self.peek_scope(lexer); - Ok(Some( - ctx.expressions.append(expr, NagaSpan::ByteRange(span)), - )) + let span = NagaSpan::from(self.peek_scope(lexer)); + Ok(Some(ctx.expressions.append(expr, span))) } /// Expects [`Scope::PrimaryExpr`] scope on top; if returning Some(_), pops it. @@ -1913,10 +1911,8 @@ impl Parser { crate::Expression::Compose { ty, components } }; - let span = self.pop_scope(lexer); - Ok(Some( - ctx.expressions.append(expr, NagaSpan::ByteRange(span)), - )) + let span = NagaSpan::from(self.pop_scope(lexer)); + Ok(Some(ctx.expressions.append(expr, span))) } fn parse_const_expression_impl<'a>( @@ -1972,7 +1968,7 @@ impl Parser { // Only set span if it's a named constant. Otherwise, the enclosing Expression should have // the span. - let span = self.pop_scope(lexer); + let span = NagaSpan::from(self.pop_scope(lexer)); let handle = if let Some(name) = register_name { const_arena.append( crate::Constant { @@ -1980,7 +1976,7 @@ impl Parser { specialization: None, inner, }, - NagaSpan::ByteRange(span), + span, ) } else { const_arena.fetch_or_append( @@ -2026,11 +2022,8 @@ impl Parser { let _ = lexer.next(); let const_handle = self.parse_const_expression_impl(token, lexer, None, ctx.types, ctx.constants)?; - let span = self.pop_scope(lexer); - ctx.interrupt_emitter( - crate::Expression::Constant(const_handle), - NagaSpan::ByteRange(span), - ) + let span = NagaSpan::from(self.pop_scope(lexer)); + ctx.interrupt_emitter(crate::Expression::Constant(const_handle), span) } (Token::Word(word), span) => { if let Some(&expr) = ctx.lookup_ident.get(word) { @@ -2087,7 +2080,7 @@ impl Parser { let expression = crate::Expression::Load { pointer: handle }; handle = ctx .expressions - .append(expression, NagaSpan::ByteRange(lexer.span_from(span_start))); + .append(expression, NagaSpan::from(lexer.span_from(span_start))); needs_deref = false; } } @@ -2180,7 +2173,7 @@ impl Parser { return Ok(if needs_deref { let expression = crate::Expression::Load { pointer: handle }; ctx.expressions - .append(expression, ctx.expressions.get_span(handle).clone()) + .append(expression, ctx.expressions.get_span(handle)) } else { handle }); @@ -2189,7 +2182,7 @@ impl Parser { handle = ctx .expressions - .append(expression, NagaSpan::ByteRange(lexer.span_from(span_start))); + .append(expression, NagaSpan::from(lexer.span_from(span_start))); } } @@ -2209,10 +2202,7 @@ impl Parser { expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }; let span = self.peek_scope(lexer); - ( - true, - ctx.expressions.append(expr, NagaSpan::ByteRange(span)), - ) + (true, ctx.expressions.append(expr, NagaSpan::from(span))) } Token::Operation('!') | Token::Operation('~') => { let _ = lexer.next(); @@ -2221,10 +2211,7 @@ impl Parser { expr: self.parse_singular_expression(lexer, ctx.reborrow())?, }; let span = self.peek_scope(lexer); - ( - true, - ctx.expressions.append(expr, NagaSpan::ByteRange(span)), - ) + (true, ctx.expressions.append(expr, NagaSpan::from(span))) } Token::Operation('*') => { let _ = lexer.next(); @@ -2233,10 +2220,9 @@ impl Parser { ( false, match ctx.rhs { - true => ctx.expressions.append( - crate::Expression::Load { pointer }, - NagaSpan::ByteRange(span), - ), + true => ctx + .expressions + .append(crate::Expression::Load { pointer }, NagaSpan::from(span)), false => pointer, }, ) @@ -2887,7 +2873,7 @@ impl Parser { name: debug_name.map(|s| s.to_string()), inner, }, - NagaSpan::ByteRange(span), + NagaSpan::from(span), ) } None => return Err(Error::UnknownType(name_span)), @@ -2960,7 +2946,7 @@ impl Parser { .extend(context.emitter.finish(context.expressions)); context.block.push( crate::Statement::Store { pointer, value }, - NagaSpan::ByteRange(span_start..span_end), + NagaSpan::from(span_start..span_end), ); Ok(()) } @@ -2988,7 +2974,7 @@ impl Parser { arguments, result: None, }, - NagaSpan::ByteRange(span_start..span_end), + NagaSpan::from(span_start..span_end), ); Ok(()) } @@ -3020,11 +3006,8 @@ impl Parser { )?; } self.pop_scope(lexer); - let span = self.pop_scope(lexer); - block.push( - crate::Statement::Block(statements), - NagaSpan::ByteRange(span), - ); + let span = NagaSpan::from(self.pop_scope(lexer)); + block.push(crate::Statement::Block(statements), span); return Ok(()); } (Token::Word(word), word_span) => { @@ -3169,7 +3152,7 @@ impl Parser { _ => None, }, }, - NagaSpan::ByteRange(name_span), + NagaSpan::from(name_span), ); // Doesn't make sense to assign a span to cached lookup @@ -3255,7 +3238,7 @@ impl Parser { }; reject = crate::Block::new(); reject.extend(other_emit); - reject.push(sub_stmt, NagaSpan::ByteRange(other_span_start..span_end)) + reject.push(sub_stmt, NagaSpan::from(other_span_start..span_end)) } Some(crate::Statement::If { @@ -3400,14 +3383,14 @@ impl Parser { Ok(condition) })?; let mut reject = crate::Block::new(); - reject.push(crate::Statement::Break, NagaSpan::Unknown); + reject.push(crate::Statement::Break, NagaSpan::default()); body.push( crate::Statement::If { condition, accept: crate::Block::new(), reject, }, - NagaSpan::ByteRange(span), + NagaSpan::from(span), ); }; @@ -3531,9 +3514,9 @@ impl Parser { None } }; - let span = self.pop_scope(lexer); + let span = NagaSpan::from(self.pop_scope(lexer)); if let Some(statement) = statement { - block.push(statement, NagaSpan::ByteRange(span)); + block.push(statement, span); } } _ => { @@ -3609,9 +3592,9 @@ impl Parser { for (&name, expression) in lookup_global_expression.iter() { let span = match *expression { crate::Expression::GlobalVariable(handle) => { - module.global_variables.get_span(handle).clone() + module.global_variables.get_span(handle) } - crate::Expression::Constant(handle) => module.constants.get_span(handle).clone(), + crate::Expression::Constant(handle) => module.constants.get_span(handle), _ => unreachable!(), }; let expr_handle = expressions.append(expression.clone(), span); @@ -3634,7 +3617,7 @@ impl Parser { let param_index = arguments.len() as u32; let expression_token = expressions.append( crate::Expression::FunctionArgument(param_index), - NagaSpan::ByteRange(param_name_span), + NagaSpan::from(param_name_span), ); lookup_ident.insert(param_name, expression_token); arguments.push(crate::FunctionArgument { @@ -3793,7 +3776,7 @@ impl Parser { let name = lexer.next_ident()?; let (members, span) = self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?; - let type_span = lexer.span_from(start); + let type_span = NagaSpan::from(lexer.span_from(start)); let ty = module.types.fetch_or_append( crate::Type { name: Some(name.to_string()), @@ -3803,7 +3786,7 @@ impl Parser { span, }, }, - NagaSpan::ByteRange(type_span), + type_span, ); self.lookup_type.insert(name.to_owned(), ty); lexer.expect(Token::Separator(';'))?; @@ -3892,7 +3875,7 @@ impl Parser { ty: pvar.ty, init: pvar.init, }, - NagaSpan::ByteRange(pvar.name_span), + NagaSpan::from(pvar.name_span), ); lookup_global_expression .insert(pvar.name, crate::Expression::GlobalVariable(var_handle)); @@ -3911,7 +3894,7 @@ impl Parser { None => { module .functions - .append(function, NagaSpan::ByteRange(lexer.span_from(start))); + .append(function, NagaSpan::from(lexer.span_from(start))); } } } diff --git a/src/span.rs b/src/span.rs index dbd24c8d1..3421c35f0 100644 --- a/src/span.rs +++ b/src/span.rs @@ -1,38 +1,68 @@ use std::ops::Range; -// A source code span, used for error reporting. -#[derive(Clone, Debug, PartialEq)] -pub enum Span { - // Span is unknown - no source information. - Unknown, - // Byte range. - ByteRange(Range), -} - -impl Default for Span { - fn default() -> Self { - Self::Unknown - } +/// A source code span, used for error reporting. +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub struct Span { + start: u32, + end: u32, } impl Span { - pub fn subsume(&mut self, other: &Self) { - match *self { - Self::Unknown => self.clone_from(other), - Self::ByteRange(ref mut self_range) => { - if let Self::ByteRange(ref other_range) = *other { - self_range.start = self_range.start.min(other_range.start); - self_range.end = self_range.end.max(other_range.end); - } + /// Creates a new `Span` from a range of byte indices + /// + /// Note: end is exclusive, it doesn't belong to the `Span` + pub fn new(start: u32, end: u32) -> Self { + Span { start, end } + } + + /// Modifies `self` to contain the smallest `Span` possible that + /// contains both `self` and `other` + pub fn subsume(&mut self, other: Self) { + *self = if !self.is_defined() { + // self isn't defined so use other + other + } else if !other.is_defined() { + // other isn't defined so don't try to subsume + *self + } else { + // Both self and other are defined so calculate the span that contains them both + Span { + start: self.start.min(other.start), + end: self.end.max(other.end), } } } - pub fn total_span<'a, T: Iterator>(from: T) -> Self { + /// Returns the smallest `Span` possible that contains all the `Span`s + /// defined in the `from` iterator + pub fn total_span>(from: T) -> Self { let mut span: Self = Default::default(); for other in from { span.subsume(other); } span } + + /// Converts `self` to a range if the span is not unknown + pub fn to_range(self) -> Option> { + if self.is_defined() { + Some(self.start as usize..self.end as usize) + } else { + None + } + } + + /// Check wether `self` was defined or is a default/unknown span + fn is_defined(&self) -> bool { + *self == Self::default() + } +} + +impl From> for Span { + fn from(range: Range) -> Self { + Span { + start: range.start as u32, + end: range.end as u32, + } + } } From ba39fd47c32e132072bd5338b7d2afa603f953bc Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Sat, 11 Sep 2021 23:32:10 -0700 Subject: [PATCH 1331/2212] Output parentheses around dereference (#1348) Regression from ce676cf13090b87e1405640ea8ee43e1a1666005. We need to output (*d).mx rather than *d.mx, at least according to Tint. wgsl-in seems to handle *d.mx just fine, which is likely a separate bug. --- src/back/wgsl/writer.rs | 14 ++++++++---- tests/in/glsl/fma.frag | 9 ++++++++ tests/out/wgsl/fma-frag.wgsl | 44 ++++++++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 5 deletions(-) create mode 100644 tests/in/glsl/fma.frag create mode 100644 tests/out/wgsl/fma-frag.wgsl diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 3e40c8183..1406d1a29 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1034,11 +1034,11 @@ impl Writer { // If the plain form of the expression is not what we need, emit the // operator necessary to correct that. let plain = plain_form_indirection(expr, module, func_ctx); - match (requested, plain) { - (Indirection::Ordinary, Indirection::Reference) => write!(self.out, "&")?, - (Indirection::Reference, Indirection::Ordinary) => write!(self.out, "*")?, - (_, _) => {} - } + let opened_paren = match (requested, plain) { + (Indirection::Ordinary, Indirection::Reference) => { write!(self.out, "&")?; false }, + (Indirection::Reference, Indirection::Ordinary) => { write!(self.out, "(*")?; true }, + (_, _) => { false }, + }; let expression = &func_ctx.expressions[expr]; @@ -1543,6 +1543,10 @@ impl Writer { Expression::CallResult(_) | Expression::AtomicResult { .. } => {} } + if opened_paren { + write!(self.out, ")")? + }; + Ok(()) } diff --git a/tests/in/glsl/fma.frag b/tests/in/glsl/fma.frag new file mode 100644 index 000000000..2e3fb9b74 --- /dev/null +++ b/tests/in/glsl/fma.frag @@ -0,0 +1,9 @@ +#version 440 core + +struct Mat4x3 { vec4 mx; vec4 my; vec4 mz; }; +void Fma(inout Mat4x3 d, Mat4x3 m, float s) { d.mx += m.mx * s; d.my += m.my * s; d.mz += m.mz * s; } + +out vec4 o_color; +void main() { + o_color.rgba = vec4(1.0); +} diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl new file mode 100644 index 000000000..352945808 --- /dev/null +++ b/tests/out/wgsl/fma-frag.wgsl @@ -0,0 +1,44 @@ +struct Mat4x3_ { + mx: vec4; + my: vec4; + mz: vec4; +}; + +var o_color: vec4; + +fn Fma(d: ptr, m: Mat4x3_, s: f32) { + var m1: Mat4x3_; + var s1: f32; + + m1 = m; + s1 = s; + let _e6: Mat4x3_ = (*d); + let _e8: Mat4x3_ = m1; + let _e10: f32 = s1; + (*d).mx = (_e6.mx + (_e8.mx * _e10)); + let _e14: Mat4x3_ = (*d); + let _e16: Mat4x3_ = m1; + let _e18: f32 = s1; + (*d).my = (_e14.my + (_e16.my * _e18)); + let _e22: Mat4x3_ = (*d); + let _e24: Mat4x3_ = m1; + let _e26: f32 = s1; + (*d).mz = (_e22.mz + (_e24.mz * _e26)); + return; +} + +fn main1() { + let _e1: vec4 = o_color; + let _e4: vec4 = vec4(1.0); + o_color.x = _e4.x; + o_color.y = _e4.y; + o_color.z = _e4.z; + o_color.w = _e4.w; + return; +} + +[[stage(fragment)]] +fn main() { + main1(); + return; +} From 0e66930aff1340d5c636df616d573cc326702158 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Sat, 11 Sep 2021 14:47:33 -0700 Subject: [PATCH 1332/2212] [glsl-in] Fix sampling texture array types Fixes #1349. --- src/front/glsl/builtins.rs | 8 +++++- src/front/glsl/context.rs | 46 +++++++++++++++---------------- src/front/glsl/types.rs | 8 +++--- tests/in/glsl/samplers.frag | 12 ++++++++ tests/out/wgsl/samplers-frag.wgsl | 31 +++++++++++++++++++++ 5 files changed, 76 insertions(+), 29 deletions(-) create mode 100644 tests/in/glsl/samplers.frag create mode 100644 tests/out/wgsl/samplers-frag.wgsl diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index e6219e62c..17cd412d1 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1670,12 +1670,18 @@ fn texture_call( meta: SourceMetadata, ) -> Result> { if let Some(sampler) = ctx.samplers.get(&image).copied() { + let mut array_index = comps.array_index; + + if let Some(ref mut array_index_expr) = array_index { + ctx.conversion(array_index_expr, meta, Sk::Sint, 4)?; + } + Ok(ctx.add_expression( Expression::ImageSample { image, sampler, coordinate: comps.coordinate, - array_index: comps.array_index, + array_index, offset: None, level, depth_ref: comps.depth_ref, diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 2ff59a8ea..541950a98 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -834,6 +834,25 @@ impl Context { .and_then(|(kind, width)| type_power(kind, width))) } + pub fn conversion( + &mut self, + expr: &mut Handle, + meta: SourceMetadata, + kind: ScalarKind, + width: crate::Bytes, + ) -> Result<()> { + *expr = self.expressions.append( + Expression::As { + expr: *expr, + kind, + convert: Some(width), + }, + meta.as_span(), + ); + + Ok(()) + } + pub fn implicit_conversion( &mut self, parser: &mut Parser, @@ -847,14 +866,7 @@ impl Context { self.expr_power(parser, *expr, meta)?, ) { if tgt_power > expr_power { - *expr = self.expressions.append( - Expression::As { - expr: *expr, - kind, - convert: Some(width), - }, - meta.as_span(), - ) + self.conversion(expr, meta, kind, width)?; } } @@ -882,25 +894,11 @@ impl Context { ) { match left_power.cmp(&right_power) { std::cmp::Ordering::Less => { - *left = self.expressions.append( - Expression::As { - expr: *left, - kind: right_kind, - convert: Some(right_width), - }, - left_meta.as_span(), - ) + self.conversion(left, left_meta, right_kind, right_width)?; } std::cmp::Ordering::Equal => {} std::cmp::Ordering::Greater => { - *right = self.expressions.append( - Expression::As { - expr: *right, - kind: left_kind, - convert: Some(left_width), - }, - right_meta.as_span(), - ) + self.conversion(right, right_meta, left_kind, left_width)?; } } } diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 7901edcb9..4151c6855 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -131,14 +131,14 @@ pub fn parse_type(type_name: &str) -> Option { let (dim, arrayed, class) = match size { "1D" => (ImageDimension::D1, false, sampled(false)), - "1DArray" => (ImageDimension::D1, false, sampled(false)), + "1DArray" => (ImageDimension::D1, true, sampled(false)), "2D" => (ImageDimension::D2, false, sampled(false)), - "2DArray" => (ImageDimension::D2, false, sampled(false)), - "2DMS" => (ImageDimension::D2, true, sampled(true)), + "2DArray" => (ImageDimension::D2, true, sampled(false)), + "2DMS" => (ImageDimension::D2, false, sampled(true)), "2DMSArray" => (ImageDimension::D2, true, sampled(true)), "3D" => (ImageDimension::D3, false, sampled(false)), "Cube" => (ImageDimension::Cube, false, sampled(false)), - "CubeArray" => (ImageDimension::D2, false, sampled(false)), + "CubeArray" => (ImageDimension::D2, true, sampled(false)), _ => return None, }; diff --git a/tests/in/glsl/samplers.frag b/tests/in/glsl/samplers.frag new file mode 100644 index 000000000..0bd849d5b --- /dev/null +++ b/tests/in/glsl/samplers.frag @@ -0,0 +1,12 @@ +#version 440 core +precision mediump float; + +layout(set = 1, binding = 0) uniform texture2DArray tex; +layout(set = 1, binding = 1) uniform sampler samp; + +layout(location = 0) in vec2 v_TexCoord; +layout(location = 0) out vec4 o_color; + +void main() { + o_color.rgba = texture(sampler2DArray(tex, samp), vec3(v_TexCoord, 0.0)); +} diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl new file mode 100644 index 000000000..00beae9be --- /dev/null +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -0,0 +1,31 @@ +struct FragmentOutput { + [[location(0)]] o_color: vec4; +}; + +[[group(1), binding(0)]] +var tex: texture_2d_array; +[[group(1), binding(1)]] +var samp: sampler; +var v_TexCoord1: vec2; +var o_color: vec4; + +fn main1() { + let _e4: vec4 = o_color; + let _e6: vec2 = v_TexCoord1; + let _e9: vec2 = v_TexCoord1; + let _e11: vec3 = vec3(_e9, 0.0); + let _e15: vec4 = textureSample(tex, samp, _e11.xy, i32(_e11.z)); + o_color.x = _e15.x; + o_color.y = _e15.y; + o_color.z = _e15.z; + o_color.w = _e15.w; + return; +} + +[[stage(fragment)]] +fn main([[location(0)]] v_TexCoord: vec2) -> FragmentOutput { + v_TexCoord1 = v_TexCoord; + main1(); + let _e11: vec4 = o_color; + return FragmentOutput(_e11); +} From 807accd7ded15dd8589c93f5f42c5a0076b0f728 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 13 Sep 2021 15:34:33 -0400 Subject: [PATCH 1333/2212] wgsl-in: require storage class to be given --- src/back/wgsl/writer.rs | 12 +++++++++--- src/front/wgsl/mod.rs | 19 +------------------ tests/in/skybox.wgsl | 2 +- 3 files changed, 11 insertions(+), 22 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 1406d1a29..07e4bed05 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1035,9 +1035,15 @@ impl Writer { // operator necessary to correct that. let plain = plain_form_indirection(expr, module, func_ctx); let opened_paren = match (requested, plain) { - (Indirection::Ordinary, Indirection::Reference) => { write!(self.out, "&")?; false }, - (Indirection::Reference, Indirection::Ordinary) => { write!(self.out, "(*")?; true }, - (_, _) => { false }, + (Indirection::Ordinary, Indirection::Reference) => { + write!(self.out, "&")?; + false + } + (Indirection::Reference, Indirection::Ordinary) => { + write!(self.out, "(*")?; + true + } + (_, _) => false, }; let expression = &func_ctx.expressions[expr]; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 84018f534..b4eeeaac8 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3850,27 +3850,10 @@ impl Parser { (Token::Word("var"), _) => { let pvar = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; - let class = match pvar.class { - Some(c) => c, - None => match module.types[pvar.ty].inner { - crate::TypeInner::Struct { .. } if binding.is_some() => { - crate::StorageClass::Uniform - } - crate::TypeInner::Array { .. } if binding.is_some() => { - crate::StorageClass::Storage { - access: crate::StorageAccess::LOAD, - } - } - crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { - crate::StorageClass::Handle - } - _ => crate::StorageClass::Private, - }, - }; let var_handle = module.global_variables.append( crate::GlobalVariable { name: Some(pvar.name.to_owned()), - class, + class: pvar.class.unwrap_or(crate::StorageClass::Handle), binding: binding.take(), ty: pvar.ty, init: pvar.init, diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index 0c00ebf72..33a110840 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -9,7 +9,7 @@ struct Data { view: mat4x4; }; [[group(0), binding(0)]] -var r_data: Data; +var r_data: Data; [[stage(vertex)]] fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { From c03427b15452e3beef90de10f1f3d05444ffddf8 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 13 Sep 2021 22:34:10 -0700 Subject: [PATCH 1334/2212] Document TypeResolution and TypeInner::ValuePointer. --- src/lib.rs | 6 +++ src/proc/typifier.rs | 101 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 076a57349..b8190cf19 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -579,7 +579,13 @@ pub enum TypeInner { base: Handle, class: StorageClass, }, + /// Pointer to a value. + /// + /// A `ValuePointer` type is equivalent to a `Pointer` to a `Scalar` or `Vector`. + /// This is for use in [`TypeResolution::Value`] variants. + /// + /// [`TypeResolution::Value`]: proc::TypeResolution::Value ValuePointer { size: Option, kind: ScalarKind, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index e5635f901..4a38ea6fd 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -2,11 +2,97 @@ use crate::arena::{Arena, Handle}; use thiserror::Error; +/// The result of computing an expression's type. +/// +/// This is the type returned by [`ResolveContext::resolve`] to represent the type +/// it ascribes to some expression. +/// +/// You might expect such a function to simply return a `Handle`. However, +/// we want type resolution to be a read-only process, and that would limit the +/// possible results to types already present in the expression's associated +/// `Arena`. Naga IR does have certain expressions whose types are not +/// certain to be present. +/// +/// So instead, type resolution returns a `TypeResolution` enum: either a +/// [`Handle`], referencing some type in the arena, or a [`Value`], holding a +/// free-floating [`TypeInner`]. This extends the range to cover anything that +/// can be represented with a `TypeInner` referring to the existing arena. +/// +/// What sorts of expressions can have types not available in the arena? +/// +/// - An [`Access`] or [`AccessIndex`] expression applied to a [`Vector`] or +/// [`Matrix`] must have a [`Scalar`] or [`Vector`] type. But since `Vector` +/// and `Matrix` represent their element and column types implicitly, not +/// via a handle, there may not be a suitable type in the expression's +/// associated arena. Instead, resolving such an expression returns a +/// `TypeResolution::Value(TypeInner::X { ... })`, where `X` is `Scalar` or +/// `Vector`. +/// +/// - Similarly, the type of an [`Access`] or [`AccessIndex`] expression +/// applied to a *pointer to* a vector or matrix must produce a *pointer to* +/// a scalar or vector type. These cannot be represented with a +/// [`TypeInner::Pointer`], since the `Pointer`'s `base` must point into the +/// arena, and as before, we cannot assume that a suitable scalar or vector +/// type is there. So we take things one step further and provide +/// [`TypeInner::ValuePointer`], specifically for the case of pointers to +/// scalars or vectors. This type fits in a `TypeInner` and is exactly +/// equivalent to a `Pointer` to a `Vector` or `Scalar`. +/// +/// So, for example, the type of an `Access` expression applied to a value of type: +/// +/// ```ignore +/// TypeInner::Matrix { columns, rows, width } +/// ``` +/// +/// might be: +/// +/// ```ignore +/// TypeResolution::Value(TypeInner::Vector { +/// size: rows, +/// kind: ScalarKind::Float, +/// width, +/// }) +/// ``` +/// +/// and the type of an access to a pointer of storage class `class` to such a +/// matrix might be: +/// +/// ```ignore +/// TypeResolution::Value(TypeInner::ValuePointer { +/// size: Some(rows), +/// kind: ScalarKind::Float, +/// width, +/// class +/// }) +/// ``` +/// +/// [`Handle`]: TypeResolution::Handle +/// [`Value`]: TypeResolution::Value +/// +/// [`Access`]: crate::Expression::Access +/// [`AccessIndex`]: crate::Expression::AccessIndex +/// +/// [`TypeInner`]: crate::TypeInner +/// [`Matrix`]: crate::TypeInner::Matrix +/// [`Pointer`]: crate::TypeInner::Pointer +/// [`Scalar`]: crate::TypeInner::Scalar +/// [`ValuePointer`]: crate::TypeInner::ValuePointer +/// [`Vector`]: crate::TypeInner::Vector +/// +/// [`TypeInner::Pointer`]: crate::TypeInner::Pointer +/// [`TypeInner::ValuePointer`]: crate::TypeInner::ValuePointer #[derive(Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum TypeResolution { + /// A type stored in the associated arena. Handle(Handle), + + /// A free-floating [`TypeInner`], representing a type that may not be + /// available in the associated arena. However, the `TypeInner` itself may + /// contain `Handle` values referring to types from the arena. + /// + /// [`TypeInner`]: crate::TypeInner Value(crate::TypeInner), } @@ -119,6 +205,21 @@ pub struct ResolveContext<'a> { } impl<'a> ResolveContext<'a> { + /// Determine the type of `expr`. + /// + /// The `past` argument must be a closure that can resolve the types of any + /// expressions that `expr` refers to. These can be gathered by caching the + /// results of prior calls to `resolve`, perhaps as done by the + /// [`front::Typifier`] utility type. + /// + /// Type resolution is a read-only process: this method takes `self` by + /// shared reference. However, this means that we cannot add anything to + /// `self.types` that we might need to describe `expr`. To work around this, + /// this method returns a [`TypeResolution`], rather than simply returning a + /// `Handle`; see the documentation for [`TypeResolution`] for + /// details. + /// + /// [`front::Typifier`]: crate::front::Typifier pub fn resolve( &self, expr: &crate::Expression, From db80ed4fa935b3ab63a8cfa999a7e9981a51659d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 14 Sep 2021 09:41:05 -0400 Subject: [PATCH 1335/2212] Fix warnings in snapshots and spv-in --- src/front/spv/mod.rs | 8 -------- tests/snapshots.rs | 15 ++++++--------- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 85c1faf90..3e55254f6 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -268,7 +268,6 @@ struct EntryPoint { name: String, early_depth_test: Option, workgroup_size: [u32; 3], - function_id: spirv::Word, variable_ids: Vec, } @@ -333,12 +332,6 @@ enum LookupLoadOverride { Loaded(Handle), } -#[derive(Clone, Debug)] -struct Assignment { - to: Handle, - value: Handle, -} - #[derive(PartialEq)] enum ExtendedClass { Global(crate::StorageClass), @@ -3397,7 +3390,6 @@ impl> Parser { name, early_depth_test: None, workgroup_size: [0; 3], - function_id, variable_ids: self.data.by_ref().take(left as usize).collect(), }; self.lookup_entry_point.insert(function_id, ep); diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 63d99ebad..f9376f31e 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -1,7 +1,4 @@ -//TODO: move this to a binary target once Rust supports -// binary-specific dependencies. - -use std::{fs, path::Path, path::PathBuf}; +use std::{fs, path::PathBuf}; const BASE_DIR_IN: &str = "tests/in"; const BASE_DIR_OUT: &str = "tests/out"; @@ -169,7 +166,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { fn write_output_spv( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, + destination: &PathBuf, file_name: &str, params: &Parameters, ) { @@ -226,7 +223,7 @@ fn write_output_spv( fn write_output_msl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, + destination: &PathBuf, file_name: &str, params: &Parameters, ) { @@ -263,7 +260,7 @@ fn write_output_msl( fn write_output_glsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, + destination: &PathBuf, file_name: &str, stage: naga::ShaderStage, ep_name: &str, @@ -304,7 +301,7 @@ fn write_output_glsl( fn write_output_hlsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, + destination: &PathBuf, file_name: &str, params: &Parameters, ) { @@ -393,7 +390,7 @@ fn write_output_hlsl( fn write_output_wgsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, + destination: &PathBuf, file_name: &str, ) { use naga::back::wgsl; From 3fdd8592fca818710919584dd6ac5e614ca555d8 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 13 Sep 2021 23:47:57 -0700 Subject: [PATCH 1336/2212] [wgsl-in] Rework Load Rule handling and indirection. Make the parser code more closely follow the spec's grammar around `unary_expression`, `postfix_expression`, and `singular_expression`. Change the handling of postfix expressions (indexing, member/component access, and swizzling) to apply the indirection at the appropriate time, resulting in code improvements on all output formats. For example, where we used to generate the following MSL: metal::float4 _e13 = bar.matrix[3]; float b = _e13.x; we now generate, simply: float b = bar.matrix[3].x; Propagate WGSL reference types correctly, so that parenthesizing expressions no longer causes the Load Rule to be applied. Together with #1332 (already landed), this is a replacement for #1312, and unblocks #1352. Fixes #1351. --- src/front/wgsl/mod.rs | 478 +++++++++++++------- tests/out/glsl/access.foo.Vertex.glsl | 3 +- tests/out/glsl/boids.main.Compute.glsl | 16 +- tests/out/glsl/operators.main.Compute.glsl | 4 +- tests/out/glsl/shadow.fs_main.Fragment.glsl | 4 +- tests/out/hlsl/access.hlsl | 3 +- tests/out/hlsl/boids.hlsl | 16 +- tests/out/hlsl/operators.hlsl | 4 +- tests/out/hlsl/shadow.hlsl | 4 +- tests/out/msl/access.msl | 3 +- tests/out/msl/boids.msl | 16 +- tests/out/msl/operators.msl | 4 +- tests/out/msl/shadow.msl | 4 +- tests/out/spv/access.spvasm | 143 +++--- tests/out/spv/boids.spvasm | 38 +- tests/out/spv/bounds-check-zero.spvasm | 164 ++++--- tests/out/spv/operators.spvasm | 10 +- tests/out/spv/shadow.spvasm | 6 +- tests/out/wgsl/access.wgsl | 3 +- tests/out/wgsl/boids.wgsl | 16 +- tests/out/wgsl/operators.wgsl | 4 +- tests/out/wgsl/shadow.wgsl | 4 +- 22 files changed, 533 insertions(+), 414 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b4eeeaac8..f388a4bc8 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -165,6 +165,9 @@ pub enum Error<'a> { MissingType(Span), InvalidAtomicPointer(Span), InvalidAtomicOperandType(Span), + NotPointer(Span), + AddressOfNotReference(Span), + AssignmentNotReference(Span), Other, } @@ -411,6 +414,21 @@ impl<'a> Error<'a> { labels: vec![(span.clone(), "atomic operand type is invalid".into())], notes: vec![], }, + Error::NotPointer(ref span) => ParseError { + message: "the operand of the `*` operator must be a pointer".to_string(), + labels: vec![(span.clone(), "expression is not a pointer".into())], + notes: vec![], + }, + Error::AddressOfNotReference(ref span) => ParseError { + message: "the operand of the `&` operator must be a reference".to_string(), + labels: vec![(span.clone(), "expression is not a reference".into())], + notes: vec![], + }, + Error::AssignmentNotReference(ref span) => ParseError { + message: "the left-hand side of an assignment be a reference".to_string(), + labels: vec![(span.clone(), "expression is not a reference".into())], + notes: vec![], + }, Error::Other => ParseError { message: "other error".to_string(), labels: vec![], @@ -730,7 +748,6 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { arguments: self.arguments, block, emitter, - rhs: true, } } } @@ -752,9 +769,6 @@ struct ExpressionContext<'input, 'temp, 'out> { functions: &'out Arena, block: &'temp mut crate::Block, emitter: &'temp mut super::Emitter, - /// Wether or not the current expression is in the right hand side of an - /// assignemnt statement or equivalent - rhs: bool, } impl<'a> ExpressionContext<'a, '_, '_> { @@ -771,22 +785,9 @@ impl<'a> ExpressionContext<'a, '_, '_> { arguments: self.arguments, block: self.block, emitter: self.emitter, - rhs: self.rhs, } } - fn reborrow_rhs(&mut self) -> ExpressionContext<'a, '_, '_> { - let mut reborrow = self.reborrow(); - reborrow.rhs = true; - reborrow - } - - fn reborrow_lhs(&mut self) -> ExpressionContext<'a, '_, '_> { - let mut reborrow = self.reborrow(); - reborrow.rhs = false; - reborrow - } - fn resolve_type( &mut self, handle: Handle, @@ -827,20 +828,25 @@ impl<'a> ExpressionContext<'a, '_, '_> { mut parser: impl FnMut( &mut Lexer<'a>, ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>>, - ) -> Result, Error<'a>> { + ) -> Result>, + ) -> Result> { let start = lexer.current_byte_offset() as u32; - let mut left = parser(lexer, self.reborrow())?; + let mut accumulator = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); - let right = parser(lexer, self.reborrow())?; + // Binary expressions always apply the load rule to their operands. + let mut left = self.apply_load_rule(accumulator); + let unloaded_right = parser(lexer, self.reborrow())?; + let right = self.apply_load_rule(unloaded_right); let end = lexer.current_byte_offset() as u32; left = self.expressions.append( crate::Expression::Binary { op, left, right }, NagaSpan::new(start, end), ); + // Binary expressions never produce references. + accumulator = TypedExpression::non_reference(left); } - Ok(left) + Ok(accumulator) } fn parse_binary_splat_op( @@ -850,15 +856,20 @@ impl<'a> ExpressionContext<'a, '_, '_> { mut parser: impl FnMut( &mut Lexer<'a>, ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>>, - ) -> Result, Error<'a>> { + ) -> Result>, + ) -> Result> { let start = lexer.current_byte_offset() as u32; - let mut left = parser(lexer, self.reborrow())?; + let mut accumulator = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); - let mut right = parser(lexer, self.reborrow())?; + // Binary expressions always apply the load rule to their operands. + let mut left = self.apply_load_rule(accumulator); + let unloaded_right = parser(lexer, self.reborrow())?; + let mut right = self.apply_load_rule(unloaded_right); let end = lexer.current_byte_offset() as u32; - // insert splats, if needed by the non-'*' operations + + // Insert splats, if needed by the non-'*' operations. + // (`BinaryOperator::Multiply` handles splats itself.) if op != crate::BinaryOperator::Multiply { let left_size = match *self.resolve_type(left)? { crate::TypeInner::Vector { size, .. } => Some(size), @@ -880,12 +891,12 @@ impl<'a> ExpressionContext<'a, '_, '_> { _ => {} } } - left = self.expressions.append( + accumulator = TypedExpression::non_reference(self.expressions.append( crate::Expression::Binary { op, left, right }, NagaSpan::new(start, end), - ); + )); } - Ok(left) + Ok(accumulator) } /// Add a single expression to the expression table that is not covered by `self.emitter`. @@ -902,6 +913,49 @@ impl<'a> ExpressionContext<'a, '_, '_> { self.emitter.start(self.expressions); result } + + /// Apply the WGSL Load Rule to `expr`. + /// + /// If `expr` is has type `ref`, perform a load to produce a value of type + /// `T`. Otherwise, return `expr` unchanged. + fn apply_load_rule(&mut self, expr: TypedExpression) -> Handle { + if expr.is_reference { + let load = crate::Expression::Load { + pointer: expr.handle, + }; + let span = self.expressions.get_span(expr.handle); + self.expressions.append(load, span) + } else { + expr.handle + } + } +} + +/// A Naga [`Expression`] handle, with WGSL type information. +/// +/// Naga and WGSL types are very close, but Naga lacks WGSL's 'reference' types, +/// which we need to know to apply the Load Rule. This struct carries a Naga +/// `Handle` along with enough information to determine its WGSL type. +/// +/// [`Expression`]: crate::Expression +#[derive(Debug, Copy, Clone)] +struct TypedExpression { + /// The handle of the Naga expression. + handle: Handle, + + /// True if this expression's WGSL type is a reference. + /// + /// When this is true, `handle` must be a pointer. + is_reference: bool, +} + +impl TypedExpression { + fn non_reference(handle: Handle) -> TypedExpression { + TypedExpression { + handle, + is_reference: false, + } + } } enum Composition { @@ -933,15 +987,6 @@ impl Composition { } } - fn extract( - base: Handle, - name: &str, - name_span: Span, - ) -> Result { - Self::extract_impl(name, name_span) - .map(|index| crate::Expression::AccessIndex { base, index }) - } - fn make(name: &str, name_span: Span) -> Result { if name.len() > 1 { let mut components = [crate::SwizzleComponent::X; 4]; @@ -980,6 +1025,7 @@ pub enum Scope { ConstantExpr, PrimaryExpr, SingularExpr, + UnaryExpr, GeneralExpr, } @@ -1202,7 +1248,7 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { let (pointer, pointer_span) = - lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx.reborrow()))?; + lexer.capture_span(|lexer| self.parse_general_expression(lexer, ctx.reborrow()))?; // Check if the pointer expression is to an atomic. // The IR uses regular `Expression::Load` and `Statement::Store` for atomic load/stores, // and it will not catch the use of a non-atomic variable here. @@ -1258,11 +1304,11 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + let pointer = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let ctx_span = ctx.reborrow(); let (value, value_span) = - lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx_span))?; + lexer.capture_span(|lexer| self.parse_general_expression(lexer, ctx_span))?; lexer.close_arguments()?; let expression = match *ctx.resolve_type(value)? { @@ -1383,7 +1429,7 @@ impl Parser { "arrayLength" => { let _ = lexer.next(); lexer.open_arguments()?; - let array = self.parse_singular_expression(lexer, ctx.reborrow())?; + let array = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::ArrayLength(array) } @@ -1464,12 +1510,12 @@ impl Parser { "atomicCompareExchangeWeak" => { let _ = lexer.next(); lexer.open_arguments()?; - let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?; + let pointer = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let cmp = self.parse_singular_expression(lexer, ctx.reborrow())?; + let cmp = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let (value, value_span) = lexer.capture_span(|lexer| { - self.parse_singular_expression(lexer, ctx.reborrow()) + self.parse_general_expression(lexer, ctx.reborrow()) })?; lexer.close_arguments()?; @@ -2005,13 +2051,13 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { + ) -> Result> { // Will be popped inside match, possibly inside parse_function_call_inner or parse_construction self.push_scope(Scope::PrimaryExpr, lexer); - let handle = match lexer.peek() { + let expr = match lexer.peek() { (Token::Paren('('), _) => { let _ = lexer.next(); - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; + let expr = self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; self.pop_scope(lexer); expr @@ -2023,23 +2069,45 @@ impl Parser { let const_handle = self.parse_const_expression_impl(token, lexer, None, ctx.types, ctx.constants)?; let span = NagaSpan::from(self.pop_scope(lexer)); - ctx.interrupt_emitter(crate::Expression::Constant(const_handle), span) + TypedExpression::non_reference( + ctx.interrupt_emitter(crate::Expression::Constant(const_handle), span), + ) } (Token::Word(word), span) => { - if let Some(&expr) = ctx.lookup_ident.get(word) { + if let Some(&handle) = ctx.lookup_ident.get(word) { let _ = lexer.next(); self.pop_scope(lexer); - expr + + // Not all identifiers constitute references in WGSL. + let is_reference = match ctx.expressions[handle] { + // `let`-bound identifiers don't evaluate to references. But that + // means `let` declarations apply the Load Rule to their values, + // so we will never see a `LocalVariable` in `lookup_ident` for a + // `let` binding. Thus, a Naga `LocalVariable` always means a WGSL + // `var` binding. + crate::Expression::LocalVariable(_) => true, + // Global variables in the `Handle` storage class do not evaluate + // to references. + crate::Expression::GlobalVariable(global) => { + ctx.global_vars[global].class != crate::StorageClass::Handle + } + _ => false, + }; + + TypedExpression { + handle, + is_reference, + } } else if let Some(expr) = - self.parse_function_call_inner(lexer, word, ctx.reborrow_rhs())? + self.parse_function_call_inner(lexer, word, ctx.reborrow())? { //TODO: resolve the duplicate call in `parse_singular_expression` self.pop_scope(lexer); - expr + TypedExpression::non_reference(expr) } else { let _ = lexer.next(); - if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow_rhs())? { - expr + if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow())? { + TypedExpression::non_reference(expr) } else { return Err(Error::UnknownIdent(span, word)); } @@ -2047,7 +2115,7 @@ impl Parser { } other => return Err(Error::Unexpected(other, ExpectedToken::PrimaryExpression)), }; - Ok(handle) + Ok(expr) } fn parse_postfix<'a>( @@ -2055,41 +2123,57 @@ impl Parser { span_start: usize, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, - mut handle: Handle, - allow_deref: bool, - ) -> Result, Error<'a>> { - let mut needs_deref = match ctx.expressions[handle] { - crate::Expression::LocalVariable(_) => allow_deref, - crate::Expression::GlobalVariable(var) => { - ctx.global_vars[var].class != crate::StorageClass::Handle && allow_deref - } - _ => false, - }; - loop { - // insert the E::Load when we reach a value - if needs_deref { - let now = match *ctx.resolve_type(handle)? { - crate::TypeInner::Pointer { base, class: _ } => match ctx.types[base].inner { - crate::TypeInner::Scalar { .. } | crate::TypeInner::Vector { .. } => true, - _ => false, - }, - crate::TypeInner::ValuePointer { .. } => true, - _ => false, - }; - if now { - let expression = crate::Expression::Load { pointer: handle }; - handle = ctx - .expressions - .append(expression, NagaSpan::from(lexer.span_from(span_start))); - needs_deref = false; - } - } + expr: TypedExpression, + ) -> Result> { + // Parse postfix expressions, adjusting `handle` and `is_reference` along the way. + // + // Most postfix expressions don't affect `is_reference`: for example, `s.x` is a + // reference whenever `s` is a reference. But swizzles (WGSL spec: "multiple + // component selection") apply the load rule, converting references to values, so + // those affect `is_reference` as well as `handle`. + let TypedExpression { + mut handle, + mut is_reference, + } = expr; + loop { let expression = match lexer.peek().0 { Token::Separator('.') => { let _ = lexer.next(); let (name, name_span) = lexer.next_ident_with_span()?; - match *ctx.resolve_type(handle)? { + + // Step lightly around `resolve_type`'s mutable borrow. + ctx.resolve_type(handle)?; + + // Find the type of the composite whose components or members we're + // accessing, skipping through pointers: except for swizzles, the + // `Access` or `AccessIndex` expressions we'd generate are the same + // either way. + let temp_inner; + let composite = match *ctx.typifier.get(handle, ctx.types) { + crate::TypeInner::Pointer { base, .. } => &ctx.types[base].inner, + crate::TypeInner::ValuePointer { + size: None, + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Scalar { kind, width }; + &temp_inner + } + crate::TypeInner::ValuePointer { + size: Some(size), + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Vector { size, kind, width }; + &temp_inner + } + ref other => other, + }; + + let access = match *composite { crate::TypeInner::Struct { ref members, .. } => { let index = members .iter() @@ -2103,10 +2187,19 @@ impl Parser { } crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { match Composition::make(name, name_span)? { - Composition::Multi(dst_size, pattern) => { + Composition::Multi(size, pattern) => { + // Once you apply the load rule, the expression is no + // longer a reference. + let current_expr = TypedExpression { + handle, + is_reference, + }; + let vector = ctx.apply_load_rule(current_expr); + is_reference = false; + crate::Expression::Swizzle { - size: dst_size, - vector: handle, + size, + vector, pattern, } } @@ -2116,30 +2209,14 @@ impl Parser { }, } } - crate::TypeInner::ValuePointer { .. } => { - Composition::extract(handle, name, name_span)? - } - crate::TypeInner::Pointer { base, class: _ } => match ctx.types[base].inner - { - crate::TypeInner::Struct { ref members, .. } => { - let index = members - .iter() - .position(|m| m.name.as_deref() == Some(name)) - .ok_or(Error::BadAccessor(name_span))? - as u32; - crate::Expression::AccessIndex { - base: handle, - index, - } - } - _ => Composition::extract(handle, name, name_span)?, - }, _ => return Err(Error::BadAccessor(name_span)), - } + }; + + access } Token::Paren('[') => { let (_, open_brace_span) = lexer.next(); - let index = self.parse_general_expression(lexer, ctx.reborrow_rhs())?; + let index = self.parse_general_expression(lexer, ctx.reborrow())?; let close_brace_span = lexer.expect_span(Token::Paren(']'))?; if let crate::Expression::Constant(constant) = ctx.expressions[index] { @@ -2168,86 +2245,124 @@ impl Parser { } } } - _ => { - // after we reached for the value, load it - return Ok(if needs_deref { - let expression = crate::Expression::Load { pointer: handle }; - ctx.expressions - .append(expression, ctx.expressions.get_span(handle)) - } else { - handle - }); - } + _ => break, }; handle = ctx .expressions .append(expression, NagaSpan::from(lexer.span_from(span_start))); } + + Ok(TypedExpression { + handle, + is_reference, + }) } + /// Parse a `unary_expression`. + fn parse_unary_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result> { + self.push_scope(Scope::UnaryExpr, lexer); + //TODO: refactor this to avoid backing up + let expr = match lexer.peek().0 { + Token::Operation('-') => { + let _ = lexer.next(); + let unloaded_expr = self.parse_unary_expression(lexer, ctx.reborrow())?; + let expr = ctx.apply_load_rule(unloaded_expr); + let expr = crate::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr, + }; + let span = NagaSpan::from(self.peek_scope(lexer)); + TypedExpression::non_reference(ctx.expressions.append(expr, span)) + } + Token::Operation('!') | Token::Operation('~') => { + let _ = lexer.next(); + let unloaded_expr = self.parse_unary_expression(lexer, ctx.reborrow())?; + let expr = ctx.apply_load_rule(unloaded_expr); + let expr = crate::Expression::Unary { + op: crate::UnaryOperator::Not, + expr, + }; + let span = NagaSpan::from(self.peek_scope(lexer)); + TypedExpression::non_reference(ctx.expressions.append(expr, span)) + } + Token::Operation('*') => { + let _ = lexer.next(); + // The `*` operator does not accept a reference, so we must apply the Load + // Rule here. But the operator itself simply changes the type from + // `ptr` to `ref`, so we generate no code for the + // operator itself. We simply return a `TypedExpression` with + // `is_reference` set to true. + let unloaded_pointer = self.parse_unary_expression(lexer, ctx.reborrow())?; + let pointer = ctx.apply_load_rule(unloaded_pointer); + + // An expression like `&*ptr` may generate no Naga IR at all, but WGSL requires + // an error if `ptr` is not a pointer. So we have to type-check this ourselves. + if ctx.resolve_type(pointer)?.pointer_class().is_none() { + let span = ctx + .expressions + .get_span(pointer) + .to_range() + .unwrap_or_else(|| self.peek_scope(lexer)); + return Err(Error::NotPointer(span)); + } + + TypedExpression { + handle: pointer, + is_reference: true, + } + } + Token::Operation('&') => { + let _ = lexer.next(); + // The `&` operator simply converts a reference to a pointer. And since a + // reference is required, the Load Rule is not applied. + let operand = self.parse_unary_expression(lexer, ctx.reborrow())?; + if !operand.is_reference { + let span = ctx + .expressions + .get_span(operand.handle) + .to_range() + .unwrap_or_else(|| self.peek_scope(lexer)); + return Err(Error::AddressOfNotReference(span)); + } + + // No code is generated. We just declare the pointer a reference now. + TypedExpression { + is_reference: false, + ..operand + } + } + _ => self.parse_singular_expression(lexer, ctx.reborrow())?, + }; + + self.pop_scope(lexer); + Ok(expr) + } + + /// Parse a `singular_expression`. fn parse_singular_expression<'a>( &mut self, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { + ) -> Result> { let start = lexer.current_byte_offset(); self.push_scope(Scope::SingularExpr, lexer); - //TODO: refactor this to avoid backing up - let (allow_deref, handle) = match lexer.peek().0 { - Token::Operation('-') => { - let _ = lexer.next(); - let expr = crate::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr: self.parse_singular_expression(lexer, ctx.reborrow())?, - }; - let span = self.peek_scope(lexer); - (true, ctx.expressions.append(expr, NagaSpan::from(span))) - } - Token::Operation('!') | Token::Operation('~') => { - let _ = lexer.next(); - let expr = crate::Expression::Unary { - op: crate::UnaryOperator::Not, - expr: self.parse_singular_expression(lexer, ctx.reborrow())?, - }; - let span = self.peek_scope(lexer); - (true, ctx.expressions.append(expr, NagaSpan::from(span))) - } - Token::Operation('*') => { - let _ = lexer.next(); - let pointer = self.parse_primary_expression(lexer, ctx.reborrow())?; - let span = self.peek_scope(lexer); - ( - false, - match ctx.rhs { - true => ctx - .expressions - .append(crate::Expression::Load { pointer }, NagaSpan::from(span)), - false => pointer, - }, - ) - } - Token::Operation('&') => { - let _ = lexer.next(); - let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; - (false, handle) - } - _ => { - let handle = self.parse_primary_expression(lexer, ctx.reborrow())?; - (ctx.rhs, handle) - } - }; - - let post_handle = self.parse_postfix(start, lexer, ctx.reborrow(), handle, allow_deref)?; + let primary_expr = self.parse_primary_expression(lexer, ctx.reborrow())?; + let singular_expr = self.parse_postfix(start, lexer, ctx.reborrow(), primary_expr)?; self.pop_scope(lexer); - Ok(post_handle) + + Ok(singular_expr) } fn parse_equality_expression<'a>( &mut self, lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { + ) -> Result> { // equality_expression context.parse_binary_op( lexer, @@ -2308,7 +2423,7 @@ impl Parser { _ => None, }, |lexer, context| { - self.parse_singular_expression(lexer, context) + self.parse_unary_expression(lexer, context) }, ) }, @@ -2324,8 +2439,17 @@ impl Parser { fn parse_general_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut context: ExpressionContext<'a, '_, '_>, + mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { + let expr = self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; + Ok(ctx.apply_load_rule(expr)) + } + + fn parse_general_expression_for_reference<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, '_>, + ) -> Result> { self.push_scope(Scope::GeneralExpr, lexer); // logical_or_expression let handle = context.parse_binary_op( @@ -2937,7 +3061,12 @@ impl Parser { ) -> Result<(), Error<'a>> { let span_start = lexer.current_byte_offset(); context.emitter.start(context.expressions); - let pointer = self.parse_singular_expression(lexer, context.reborrow_lhs())?; + let reference = self.parse_unary_expression(lexer, context.reborrow())?; + // The left hand side of an assignment must be a reference. + if !reference.is_reference { + let span = span_start..lexer.current_byte_offset(); + return Err(Error::AssignmentNotReference(span)); + } lexer.expect(Token::Operation('='))?; let value = self.parse_general_expression(lexer, context.reborrow())?; let span_end = lexer.current_byte_offset(); @@ -2945,7 +3074,10 @@ impl Parser { .block .extend(context.emitter.finish(context.expressions)); context.block.push( - crate::Statement::Store { pointer, value }, + crate::Statement::Store { + pointer: reference.handle, + value, + }, NagaSpan::from(span_start..span_end), ); Ok(()) diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index c128dff78..9cf0b27af 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -19,8 +19,7 @@ void main() { foo1 = 1.0; mat4x4 matrix = _group_0_binding_0.matrix; uvec2 arr[2] = _group_0_binding_0.arr; - vec4 _e13 = _group_0_binding_0.matrix[3]; - float b = _e13.x; + float b = _group_0_binding_0.matrix[3][0]; int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)]; _group_0_binding_0.matrix[1][2] = 1.0; _group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index e4620e662..b14406715 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -131,20 +131,20 @@ void main() { vec2 _e132 = vVel; float _e134 = _group_0_binding_0.deltaT; vPos = (_e131 + (_e132 * _e134)); - vec2 _e137 = vPos; - if ((_e137.x < -1.0)) { + float _e138 = vPos.x; + if ((_e138 < -1.0)) { vPos.x = 1.0; } - vec2 _e143 = vPos; - if ((_e143.x > 1.0)) { + float _e144 = vPos.x; + if ((_e144 > 1.0)) { vPos.x = -1.0; } - vec2 _e149 = vPos; - if ((_e149.y < -1.0)) { + float _e150 = vPos.y; + if ((_e150 < -1.0)) { vPos.y = 1.0; } - vec2 _e155 = vPos; - if ((_e155.y > 1.0)) { + float _e156 = vPos.y; + if ((_e156 > 1.0)) { vPos.y = -1.0; } vec2 _e164 = vPos; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 6a4edf707..99c42467f 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -40,8 +40,8 @@ int unary() { float constructors() { Foo foo; foo = Foo(vec4(1.0), 1); - vec4 _e10 = foo.a; - return _e10.x; + float _e11 = foo.a.x; + return _e11; } void main() { diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 7e5bf3653..a856f247f 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -47,8 +47,8 @@ void main() { } loop_init = false; uint _e12 = i; - uvec4 _e14 = _group_0_binding_0.num_lights; - if ((_e12 >= min(_e14.x, 10u))) { + uint _e15 = _group_0_binding_0.num_lights.x; + if ((_e12 >= min(_e15, 10u))) { break; } uint _e19 = i; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index d9c765e03..e9af3b110 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -17,8 +17,7 @@ float4 foo(uint vi : SV_VertexID) : SV_Position foo1 = 1.0; float4x4 matrix1 = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))}; - float4 _expr13 = asfloat(bar.Load4(48+0)); - float b = _expr13.x; + float b = asfloat(bar.Load(0+48+0)); int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 4) - 2u)*4+88)); bar.Store(8+16+0, asuint(1.0)); { diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index 02744cc40..34798d5e3 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -123,20 +123,20 @@ void main(uint3 global_invocation_id : SV_DispatchThreadID) float2 _expr132 = vVel; float _expr134 = params.deltaT; vPos = (_expr131 + (_expr132 * _expr134)); - float2 _expr137 = vPos; - if ((_expr137.x < -1.0)) { + float _expr138 = vPos.x; + if ((_expr138 < -1.0)) { vPos.x = 1.0; } - float2 _expr143 = vPos; - if ((_expr143.x > 1.0)) { + float _expr144 = vPos.x; + if ((_expr144 > 1.0)) { vPos.x = -1.0; } - float2 _expr149 = vPos; - if ((_expr149.y < -1.0)) { + float _expr150 = vPos.y; + if ((_expr150 < -1.0)) { vPos.y = 1.0; } - float2 _expr155 = vPos; - if ((_expr155.y > 1.0)) { + float _expr156 = vPos.y; + if ((_expr156 > 1.0)) { vPos.y = -1.0; } float2 _expr164 = vPos; diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index d9d48d485..904ca2e1c 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -49,8 +49,8 @@ float constructors() Foo foo = (Foo)0; foo = ConstructFoo(float4(1.0.xxxx), 1); - float4 _expr10 = foo.a; - return _expr10.x; + float _expr11 = foo.a.x; + return _expr11; } [numthreads(1, 1, 1)] diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 0f878d6a8..37fdef90a 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -48,8 +48,8 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 } loop_init = false; uint _expr12 = i; - uint4 _expr14 = u_globals.num_lights; - if ((_expr12 >= min(_expr14.x, c_max_lights))) { + uint _expr15 = u_globals.num_lights.x; + if ((_expr12 >= min(_expr15, c_max_lights))) { break; } uint _expr19 = i; diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 15505a5dd..dd9622a60 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -37,8 +37,7 @@ vertex fooOutput foo( foo1 = 1.0; metal::float4x4 matrix = bar.matrix; type3 arr = bar.arr; - metal::float4 _e13 = bar.matrix[3]; - float b = _e13.x; + float b = bar.matrix[3].x; int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 4) - 2u]; bar.matrix[1].z = 1.0; bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index 53edfad1f..0d3809c91 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -135,20 +135,20 @@ kernel void main1( metal::float2 _e132 = vVel; float _e134 = params.deltaT; vPos = _e131 + (_e132 * _e134); - metal::float2 _e137 = vPos; - if (_e137.x < -1.0) { + float _e138 = vPos.x; + if (_e138 < -1.0) { vPos.x = 1.0; } - metal::float2 _e143 = vPos; - if (_e143.x > 1.0) { + float _e144 = vPos.x; + if (_e144 > 1.0) { vPos.x = -1.0; } - metal::float2 _e149 = vPos; - if (_e149.y < -1.0) { + float _e150 = vPos.y; + if (_e150 < -1.0) { vPos.y = 1.0; } - metal::float2 _e155 = vPos; - if (_e155.y > 1.0) { + float _e156 = vPos.y; + if (_e156 > 1.0) { vPos.y = -1.0; } metal::float2 _e164 = vPos; diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 61afdd52c..daf4b3a10 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -44,8 +44,8 @@ float constructors( ) { Foo foo; foo = Foo {metal::float4(1.0), 1}; - metal::float4 _e10 = foo.a; - return _e10.x; + float _e11 = foo.a.x; + return _e11; } kernel void main1( diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index c098c0142..7b1146447 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -63,8 +63,8 @@ fragment fs_mainOutput fs_main( } loop_init = false; metal::uint _e12 = i; - metal::uint4 _e14 = u_globals.num_lights; - if (_e12 >= metal::min(_e14.x, c_max_lights)) { + uint _e15 = u_globals.num_lights.x; + if (_e12 >= metal::min(_e15, c_max_lights)) { break; } metal::uint _e19 = i; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 1db429ce7..f143347e5 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,14 +1,14 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 107 +; Bound: 106 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %39 "foo" %34 %37 -OpEntryPoint GLCompute %84 "atomics" -OpExecutionMode %84 LocalSize 1 1 1 +OpEntryPoint GLCompute %83 "atomics" +OpExecutionMode %83 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %25 0 "matrix" OpMemberName %25 1 "atom" @@ -20,8 +20,8 @@ OpName %29 "foo" OpName %31 "c" OpName %34 "vi" OpName %39 "foo" -OpName %82 "tmp" -OpName %84 "atomics" +OpName %81 "tmp" +OpName %83 "atomics" OpDecorate %23 ArrayStride 8 OpDecorate %24 ArrayStride 4 OpDecorate %25 Block @@ -73,13 +73,13 @@ OpDecorate %37 BuiltIn Position %43 = OpTypePointer StorageBuffer %20 %46 = OpTypePointer StorageBuffer %23 %49 = OpTypePointer StorageBuffer %21 +%50 = OpTypePointer StorageBuffer %6 %53 = OpTypePointer StorageBuffer %24 %56 = OpTypePointer StorageBuffer %4 -%59 = OpTypePointer StorageBuffer %6 -%74 = OpTypePointer Function %4 -%78 = OpTypeVector %4 4 -%86 = OpTypePointer StorageBuffer %4 -%89 = OpConstant %9 64 +%73 = OpTypePointer Function %4 +%77 = OpTypeVector %4 4 +%85 = OpTypePointer StorageBuffer %4 +%88 = OpConstant %9 64 %39 = OpFunction %2 None %40 %33 = OpLabel %29 = OpVariable %30 Function %5 @@ -93,73 +93,72 @@ OpStore %29 %7 %45 = OpLoad %20 %44 %47 = OpAccessChain %46 %27 %10 %48 = OpLoad %23 %47 -%50 = OpAccessChain %49 %27 %14 %8 -%51 = OpLoad %21 %50 -%52 = OpCompositeExtract %6 %51 0 +%51 = OpAccessChain %50 %27 %14 %8 %14 +%52 = OpLoad %6 %51 %54 = OpArrayLength %9 %27 3 %55 = OpISub %9 %54 %10 %57 = OpAccessChain %56 %27 %8 %55 %58 = OpLoad %4 %57 -%60 = OpAccessChain %59 %27 %14 %15 %10 -OpStore %60 %7 -%61 = OpCompositeConstruct %21 %5 %5 %5 %5 -%62 = OpCompositeConstruct %21 %7 %7 %7 %7 -%63 = OpCompositeConstruct %21 %12 %12 %12 %12 -%64 = OpCompositeConstruct %21 %13 %13 %13 %13 -%65 = OpCompositeConstruct %20 %61 %62 %63 %64 -%66 = OpAccessChain %43 %27 %14 -OpStore %66 %65 -%67 = OpCompositeConstruct %22 %14 %14 -%68 = OpCompositeConstruct %22 %15 %15 -%69 = OpCompositeConstruct %23 %67 %68 -%70 = OpAccessChain %46 %27 %10 -OpStore %70 %69 -%71 = OpConvertFToS %4 %52 -%72 = OpCompositeConstruct %26 %58 %71 %17 %18 %16 -OpStore %31 %72 -%73 = OpIAdd %9 %36 %15 -%75 = OpAccessChain %74 %31 %73 -OpStore %75 %19 -%76 = OpAccessChain %74 %31 %36 -%77 = OpLoad %4 %76 -%79 = OpCompositeConstruct %78 %77 %77 %77 %77 -%80 = OpConvertSToF %21 %79 -%81 = OpMatrixTimesVector %21 %45 %80 -OpStore %37 %81 +%59 = OpAccessChain %50 %27 %14 %15 %10 +OpStore %59 %7 +%60 = OpCompositeConstruct %21 %5 %5 %5 %5 +%61 = OpCompositeConstruct %21 %7 %7 %7 %7 +%62 = OpCompositeConstruct %21 %12 %12 %12 %12 +%63 = OpCompositeConstruct %21 %13 %13 %13 %13 +%64 = OpCompositeConstruct %20 %60 %61 %62 %63 +%65 = OpAccessChain %43 %27 %14 +OpStore %65 %64 +%66 = OpCompositeConstruct %22 %14 %14 +%67 = OpCompositeConstruct %22 %15 %15 +%68 = OpCompositeConstruct %23 %66 %67 +%69 = OpAccessChain %46 %27 %10 +OpStore %69 %68 +%70 = OpConvertFToS %4 %52 +%71 = OpCompositeConstruct %26 %58 %70 %17 %18 %16 +OpStore %31 %71 +%72 = OpIAdd %9 %36 %15 +%74 = OpAccessChain %73 %31 %72 +OpStore %74 %19 +%75 = OpAccessChain %73 %31 %36 +%76 = OpLoad %4 %75 +%78 = OpCompositeConstruct %77 %76 %76 %76 %76 +%79 = OpConvertSToF %21 %78 +%80 = OpMatrixTimesVector %21 %45 %79 +OpStore %37 %80 OpReturn OpFunctionEnd -%84 = OpFunction %2 None %40 -%83 = OpLabel -%82 = OpVariable %74 Function -OpBranch %85 -%85 = OpLabel -%87 = OpAccessChain %86 %27 %15 -%88 = OpAtomicLoad %4 %87 %11 %89 -%91 = OpAccessChain %86 %27 %15 -%90 = OpAtomicIAdd %4 %91 %11 %89 %16 -OpStore %82 %90 -%93 = OpAccessChain %86 %27 %15 -%92 = OpAtomicISub %4 %93 %11 %89 %16 -OpStore %82 %92 -%95 = OpAccessChain %86 %27 %15 -%94 = OpAtomicAnd %4 %95 %11 %89 %16 -OpStore %82 %94 -%97 = OpAccessChain %86 %27 %15 -%96 = OpAtomicOr %4 %97 %11 %89 %16 -OpStore %82 %96 -%99 = OpAccessChain %86 %27 %15 -%98 = OpAtomicXor %4 %99 %11 %89 %16 -OpStore %82 %98 -%101 = OpAccessChain %86 %27 %15 -%100 = OpAtomicSMin %4 %101 %11 %89 %16 -OpStore %82 %100 -%103 = OpAccessChain %86 %27 %15 -%102 = OpAtomicSMax %4 %103 %11 %89 %16 -OpStore %82 %102 -%105 = OpAccessChain %86 %27 %15 -%104 = OpAtomicExchange %4 %105 %11 %89 %16 -OpStore %82 %104 -%106 = OpAccessChain %86 %27 %15 -OpAtomicStore %106 %11 %89 %88 +%83 = OpFunction %2 None %40 +%82 = OpLabel +%81 = OpVariable %73 Function +OpBranch %84 +%84 = OpLabel +%86 = OpAccessChain %85 %27 %15 +%87 = OpAtomicLoad %4 %86 %11 %88 +%90 = OpAccessChain %85 %27 %15 +%89 = OpAtomicIAdd %4 %90 %11 %88 %16 +OpStore %81 %89 +%92 = OpAccessChain %85 %27 %15 +%91 = OpAtomicISub %4 %92 %11 %88 %16 +OpStore %81 %91 +%94 = OpAccessChain %85 %27 %15 +%93 = OpAtomicAnd %4 %94 %11 %88 %16 +OpStore %81 %93 +%96 = OpAccessChain %85 %27 %15 +%95 = OpAtomicOr %4 %96 %11 %88 %16 +OpStore %81 %95 +%98 = OpAccessChain %85 %27 %15 +%97 = OpAtomicXor %4 %98 %11 %88 %16 +OpStore %81 %97 +%100 = OpAccessChain %85 %27 %15 +%99 = OpAtomicSMin %4 %100 %11 %88 %16 +OpStore %81 %99 +%102 = OpAccessChain %85 %27 %15 +%101 = OpAtomicSMax %4 %102 %11 %88 %16 +OpStore %81 %101 +%104 = OpAccessChain %85 %27 %15 +%103 = OpAtomicExchange %4 %104 %11 %88 %16 +OpStore %81 %103 +%105 = OpAccessChain %85 %27 %15 +OpAtomicStore %105 %11 %88 %87 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 1bb7edcde..12d0cf69a 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -99,7 +99,7 @@ OpDecorate %40 BuiltIn GlobalInvocationId %145 = OpConstant %4 4 %151 = OpConstant %4 5 %157 = OpConstant %4 6 -%179 = OpTypePointer Function %6 +%174 = OpTypePointer Function %6 %43 = OpFunction %2 None %44 %39 = OpLabel %37 = OpVariable %38 Function %9 @@ -280,43 +280,43 @@ OpStore %28 %167 %172 = OpVectorTimesScalar %15 %169 %171 %173 = OpFAdd %15 %168 %172 OpStore %26 %173 -%174 = OpLoad %15 %26 -%175 = OpCompositeExtract %6 %174 0 -%176 = OpFOrdLessThan %47 %175 %13 -OpSelectionMerge %177 None -OpBranchConditional %176 %178 %177 -%178 = OpLabel -%180 = OpAccessChain %179 %26 %9 +%175 = OpAccessChain %174 %26 %9 +%176 = OpLoad %6 %175 +%177 = OpFOrdLessThan %47 %176 %13 +OpSelectionMerge %178 None +OpBranchConditional %177 %179 %178 +%179 = OpLabel +%180 = OpAccessChain %174 %26 %9 OpStore %180 %14 -OpBranch %177 -%177 = OpLabel -%181 = OpLoad %15 %26 -%182 = OpCompositeExtract %6 %181 0 +OpBranch %178 +%178 = OpLabel +%181 = OpAccessChain %174 %26 %9 +%182 = OpLoad %6 %181 %183 = OpFOrdGreaterThan %47 %182 %14 OpSelectionMerge %184 None OpBranchConditional %183 %185 %184 %185 = OpLabel -%186 = OpAccessChain %179 %26 %9 +%186 = OpAccessChain %174 %26 %9 OpStore %186 %13 OpBranch %184 %184 = OpLabel -%187 = OpLoad %15 %26 -%188 = OpCompositeExtract %6 %187 1 +%187 = OpAccessChain %174 %26 %11 +%188 = OpLoad %6 %187 %189 = OpFOrdLessThan %47 %188 %13 OpSelectionMerge %190 None OpBranchConditional %189 %191 %190 %191 = OpLabel -%192 = OpAccessChain %179 %26 %11 +%192 = OpAccessChain %174 %26 %11 OpStore %192 %14 OpBranch %190 %190 = OpLabel -%193 = OpLoad %15 %26 -%194 = OpCompositeExtract %6 %193 1 +%193 = OpAccessChain %174 %26 %11 +%194 = OpLoad %6 %193 %195 = OpFOrdGreaterThan %47 %194 %14 OpSelectionMerge %196 None OpBranchConditional %195 %197 %196 %197 = OpLabel -%198 = OpAccessChain %179 %26 %11 +%198 = OpAccessChain %174 %26 %11 OpStore %198 %13 OpBranch %196 %196 = OpLabel diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index 84af0e2a7..156954c8a 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 135 +; Bound: 130 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -36,8 +36,9 @@ OpDecorate %10 Binding 0 %23 = OpConstant %20 0 %25 = OpConstantNull %5 %34 = OpTypePointer StorageBuffer %7 -%35 = OpConstant %20 1 -%38 = OpConstant %20 4 +%35 = OpTypePointer StorageBuffer %5 +%36 = OpConstant %20 4 +%38 = OpConstant %20 1 %40 = OpConstantNull %5 %49 = OpTypeFunction %5 %7 %4 %52 = OpConstantNull %5 @@ -48,12 +49,10 @@ OpDecorate %10 Binding 0 %66 = OpConstant %20 2 %68 = OpConstantNull %7 %77 = OpTypeFunction %5 %4 %4 -%81 = OpConstantNull %7 -%87 = OpConstantNull %5 -%96 = OpTypeFunction %2 %4 %5 -%107 = OpTypePointer StorageBuffer %5 -%116 = OpTypeFunction %2 %4 %7 -%127 = OpTypeFunction %2 %4 %4 %5 +%83 = OpConstantNull %5 +%92 = OpTypeFunction %2 %4 %5 +%111 = OpTypeFunction %2 %4 %7 +%122 = OpTypeFunction %2 %4 %4 %5 %14 = OpFunction %5 None %15 %13 = OpFunctionParameter %4 %12 = OpLabel @@ -75,13 +74,12 @@ OpFunctionEnd %30 = OpLabel OpBranch %33 %33 = OpLabel -%36 = OpAccessChain %34 %10 %35 -%37 = OpLoad %7 %36 -%39 = OpULessThan %22 %31 %38 +%37 = OpULessThan %22 %31 %36 OpSelectionMerge %41 None -OpBranchConditional %39 %42 %41 +OpBranchConditional %37 %42 %41 %42 = OpLabel -%43 = OpVectorExtractDynamic %5 %37 %31 +%39 = OpAccessChain %35 %10 %38 %31 +%43 = OpLoad %5 %39 OpBranch %41 %41 = OpLabel %44 = OpPhi %5 %40 %33 %43 %42 @@ -93,7 +91,7 @@ OpFunctionEnd %45 = OpLabel OpBranch %50 %50 = OpLabel -%51 = OpULessThan %22 %47 %38 +%51 = OpULessThan %22 %47 %36 OpSelectionMerge %53 None OpBranchConditional %51 %54 %53 %54 = OpLabel @@ -125,89 +123,83 @@ OpFunctionEnd %73 = OpLabel OpBranch %78 %78 = OpLabel -%79 = OpULessThan %22 %74 %64 -OpSelectionMerge %82 None -OpBranchConditional %79 %83 %82 -%83 = OpLabel -%80 = OpAccessChain %63 %10 %66 %74 -%84 = OpLoad %7 %80 -OpBranch %82 -%82 = OpLabel -%85 = OpPhi %7 %81 %78 %84 %83 -%86 = OpULessThan %22 %75 %38 -OpSelectionMerge %88 None -OpBranchConditional %86 %89 %88 -%89 = OpLabel -%90 = OpVectorExtractDynamic %5 %85 %75 -OpBranch %88 +%79 = OpULessThan %22 %75 %36 +%80 = OpULessThan %22 %74 %64 +%81 = OpLogicalAnd %22 %79 %80 +OpSelectionMerge %84 None +OpBranchConditional %81 %85 %84 +%85 = OpLabel +%82 = OpAccessChain %35 %10 %66 %74 %75 +%86 = OpLoad %5 %82 +OpBranch %84 +%84 = OpLabel +%87 = OpPhi %5 %83 %78 %86 %85 +OpReturnValue %87 +OpFunctionEnd +%91 = OpFunction %2 None %92 +%89 = OpFunctionParameter %4 +%90 = OpFunctionParameter %5 %88 = OpLabel -%91 = OpPhi %5 %87 %82 %90 %89 -OpReturnValue %91 -OpFunctionEnd -%95 = OpFunction %2 None %96 -%93 = OpFunctionParameter %4 -%94 = OpFunctionParameter %5 -%92 = OpLabel -OpBranch %97 +OpBranch %93 +%93 = OpLabel +%94 = OpULessThan %22 %89 %19 +OpSelectionMerge %96 None +OpBranchConditional %94 %97 %96 %97 = OpLabel -%98 = OpULessThan %22 %93 %19 -OpSelectionMerge %100 None -OpBranchConditional %98 %101 %100 -%101 = OpLabel -%99 = OpAccessChain %18 %10 %23 %93 -OpStore %99 %94 -OpBranch %100 -%100 = OpLabel +%95 = OpAccessChain %18 %10 %23 %89 +OpStore %95 %90 +OpBranch %96 +%96 = OpLabel OpReturn OpFunctionEnd -%105 = OpFunction %2 None %96 -%103 = OpFunctionParameter %4 -%104 = OpFunctionParameter %5 +%101 = OpFunction %2 None %92 +%99 = OpFunctionParameter %4 +%100 = OpFunctionParameter %5 +%98 = OpLabel +OpBranch %102 %102 = OpLabel -OpBranch %106 +%103 = OpULessThan %22 %99 %36 +OpSelectionMerge %105 None +OpBranchConditional %103 %106 %105 %106 = OpLabel -%108 = OpULessThan %22 %103 %38 -OpSelectionMerge %110 None -OpBranchConditional %108 %111 %110 -%111 = OpLabel -%109 = OpAccessChain %107 %10 %35 %103 -OpStore %109 %104 -OpBranch %110 -%110 = OpLabel +%104 = OpAccessChain %35 %10 %38 %99 +OpStore %104 %100 +OpBranch %105 +%105 = OpLabel OpReturn OpFunctionEnd -%115 = OpFunction %2 None %116 -%113 = OpFunctionParameter %4 -%114 = OpFunctionParameter %7 +%110 = OpFunction %2 None %111 +%108 = OpFunctionParameter %4 +%109 = OpFunctionParameter %7 +%107 = OpLabel +OpBranch %112 %112 = OpLabel -OpBranch %117 -%117 = OpLabel -%118 = OpULessThan %22 %113 %64 -OpSelectionMerge %120 None -OpBranchConditional %118 %121 %120 -%121 = OpLabel -%119 = OpAccessChain %63 %10 %66 %113 -OpStore %119 %114 -OpBranch %120 -%120 = OpLabel +%113 = OpULessThan %22 %108 %64 +OpSelectionMerge %115 None +OpBranchConditional %113 %116 %115 +%116 = OpLabel +%114 = OpAccessChain %63 %10 %66 %108 +OpStore %114 %109 +OpBranch %115 +%115 = OpLabel OpReturn OpFunctionEnd -%126 = OpFunction %2 None %127 -%123 = OpFunctionParameter %4 -%124 = OpFunctionParameter %4 -%125 = OpFunctionParameter %5 -%122 = OpLabel +%121 = OpFunction %2 None %122 +%118 = OpFunctionParameter %4 +%119 = OpFunctionParameter %4 +%120 = OpFunctionParameter %5 +%117 = OpLabel +OpBranch %123 +%123 = OpLabel +%124 = OpULessThan %22 %119 %36 +%125 = OpULessThan %22 %118 %64 +%126 = OpLogicalAnd %22 %124 %125 +OpSelectionMerge %128 None +OpBranchConditional %126 %129 %128 +%129 = OpLabel +%127 = OpAccessChain %35 %10 %66 %118 %119 +OpStore %127 %120 OpBranch %128 %128 = OpLabel -%129 = OpULessThan %22 %124 %38 -%130 = OpULessThan %22 %123 %64 -%131 = OpLogicalAnd %22 %129 %130 -OpSelectionMerge %133 None -OpBranchConditional %131 %134 %133 -%134 = OpLabel -%132 = OpAccessChain %107 %10 %66 %123 %124 -OpStore %132 %125 -OpBranch %133 -%133 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 81708762d..7e36cb4ab 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -41,8 +41,9 @@ OpMemberDecorate %22 1 Offset 16 %80 = OpTypePointer Function %22 %83 = OpTypeFunction %4 %87 = OpTypePointer Function %19 -%89 = OpTypeInt 32 0 -%88 = OpConstant %89 0 +%88 = OpTypePointer Function %4 +%90 = OpTypeInt 32 0 +%89 = OpConstant %90 0 %95 = OpTypeFunction %2 %28 = OpFunction %19 None %29 %27 = OpLabel @@ -113,9 +114,8 @@ OpBranch %84 %85 = OpCompositeConstruct %19 %3 %3 %3 %3 %86 = OpCompositeConstruct %22 %85 %7 OpStore %79 %86 -%90 = OpAccessChain %87 %79 %88 -%91 = OpLoad %19 %90 -%92 = OpCompositeExtract %4 %91 0 +%91 = OpAccessChain %88 %79 %89 %89 +%92 = OpLoad %4 %91 OpReturnValue %92 OpFunctionEnd %94 = OpFunction %2 None %95 diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index 0361ff2f4..e8532e88c 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -96,6 +96,7 @@ OpDecorate %75 Location 0 %75 = OpVariable %76 Output %78 = OpTypeFunction %2 %88 = OpTypePointer Uniform %13 +%89 = OpTypePointer Uniform %10 %96 = OpTypePointer StorageBuffer %18 %98 = OpTypePointer StorageBuffer %17 %36 = OpFunction %4 None %37 @@ -148,9 +149,8 @@ OpLoopMerge %84 %86 None OpBranch %85 %85 = OpLabel %87 = OpLoad %10 %66 -%89 = OpAccessChain %88 %25 %11 -%90 = OpLoad %13 %89 -%91 = OpCompositeExtract %10 %90 0 +%90 = OpAccessChain %89 %25 %11 %11 +%91 = OpLoad %10 %90 %92 = OpExtInst %10 %1 UMin %91 %9 %93 = OpUGreaterThanEqual %42 %87 %92 OpSelectionMerge %94 None diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 5eca81ff0..a1b8faa2c 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -18,8 +18,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { foo1 = 1.0; let matrix: mat4x4 = bar.matrix; let arr: array,2> = bar.arr; - let _e13: vec4 = bar.matrix[3]; - let b: f32 = _e13.x; + let b: f32 = bar.matrix[3][0]; let a: i32 = bar.data[(arrayLength(&bar.data) - 2u)]; bar.matrix[1][2] = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 5c510d2bf..a0e5e8eab 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -129,20 +129,20 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { let _e132: vec2 = vVel; let _e134: f32 = params.deltaT; vPos = (_e131 + (_e132 * _e134)); - let _e137: vec2 = vPos; - if ((_e137.x < -1.0)) { + let _e138: f32 = vPos.x; + if ((_e138 < -1.0)) { vPos.x = 1.0; } - let _e143: vec2 = vPos; - if ((_e143.x > 1.0)) { + let _e144: f32 = vPos.x; + if ((_e144 > 1.0)) { vPos.x = -1.0; } - let _e149: vec2 = vPos; - if ((_e149.y < -1.0)) { + let _e150: f32 = vPos.y; + if ((_e150 < -1.0)) { vPos.y = 1.0; } - let _e155: vec2 = vPos; - if ((_e155.y > 1.0)) { + let _e156: f32 = vPos.y; + if ((_e156 > 1.0)) { vPos.y = -1.0; } let _e164: vec2 = vPos; diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 08006faaf..8f6c6ad8f 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -37,8 +37,8 @@ fn constructors() -> f32 { var foo: Foo; foo = Foo(vec4(1.0), 1); - let _e10: vec4 = foo.a; - return _e10.x; + let _e11: f32 = foo.a.x; + return _e11; } [[stage(compute), workgroup_size(1, 1, 1)]] diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 49c70fa9b..e6b3967d7 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -44,8 +44,8 @@ fn fs_main([[location(0)]] raw_normal: vec3, [[location(1)]] position: vec4 let normal: vec3 = normalize(raw_normal); loop { let _e12: u32 = i; - let _e14: vec4 = u_globals.num_lights; - if ((_e12 >= min(_e14.x, c_max_lights))) { + let _e15: u32 = u_globals.num_lights.x; + if ((_e12 >= min(_e15, c_max_lights))) { break; } let _e19: u32 = i; From 0d3dbfe781bc9b5e0c8f63696dd0fff58887e050 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 14 Sep 2021 13:49:28 -0700 Subject: [PATCH 1337/2212] Clean up some old snapshot files. `tests/out/glsl/operators.main.Fragment.glsl` is no longer generated because the function in question changed to a Compute entry point. `tests/out/wgsl/multiple_entry_points-glsl.wgsl` is no longer generated because the input test was removed in 057dc310. --- tests/out/glsl/operators.main.Fragment.glsl | 35 ------------ .../out/wgsl/multiple_entry_points-glsl.wgsl | 53 ------------------- 2 files changed, 88 deletions(-) delete mode 100644 tests/out/glsl/operators.main.Fragment.glsl delete mode 100644 tests/out/wgsl/multiple_entry_points-glsl.wgsl diff --git a/tests/out/glsl/operators.main.Fragment.glsl b/tests/out/glsl/operators.main.Fragment.glsl deleted file mode 100644 index 0c1eaa482..000000000 --- a/tests/out/glsl/operators.main.Fragment.glsl +++ /dev/null @@ -1,35 +0,0 @@ -#version 310 es - -precision highp float; - -layout(location = 0) out vec4 _fs2p_location0; - -vec4 splat() { - vec2 a = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); - ivec4 b = (ivec4(5) % ivec4(2)); - return (a.xyxy + vec4(b)); -} - -int unary() { - if ((! true)) { - return 1; - } else { - return (~ 1); - } -} - -int unary1() { - if ((! true)) { - return 1; - } else { - return (~ 1); - } -} - -void main() { - vec4 vector1_ = vec4(1.0); - vec4 vector2_ = vec4(1.0); - _fs2p_location0 = (true ? vector1_ : vector2_); - return; -} - diff --git a/tests/out/wgsl/multiple_entry_points-glsl.wgsl b/tests/out/wgsl/multiple_entry_points-glsl.wgsl deleted file mode 100644 index 2c10716a5..000000000 --- a/tests/out/wgsl/multiple_entry_points-glsl.wgsl +++ /dev/null @@ -1,53 +0,0 @@ -struct VertexOutput { - [[builtin(position)]] member: vec4; -}; - -struct FragmentOutput { - [[location(0)]] o_color: vec4; -}; - -var gl_Position: vec4; -var o_color: vec4; -var gl_GlobalInvocationID: vec3; - -fn vert_main1() { - gl_Position = vec4(1.0, 1.0, 1.0, 1.0); - return; -} - -fn frag_main1() { - o_color = vec4(1.0, 1.0, 1.0, 1.0); - return; -} - -fn comp_main1() { - let _e3: vec3 = gl_GlobalInvocationID; - if ((_e3.x > u32(1))) { - { - return; - } - } else { - return; - } -} - -[[stage(vertex)]] -fn vert_main() -> VertexOutput { - vert_main1(); - let _e3: vec4 = gl_Position; - return VertexOutput(_e3); -} - -[[stage(fragment)]] -fn frag_main() -> FragmentOutput { - frag_main1(); - let _e3: vec4 = o_color; - return FragmentOutput(_e3); -} - -[[stage(compute), workgroup_size(1, 1, 1)]] -fn comp_main([[builtin(global_invocation_id)]] param: vec3) { - gl_GlobalInvocationID = param; - comp_main1(); - return; -} From 933ecc4a443cb882bce0283fe77897bba6007080 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 14 Sep 2021 13:45:25 -0700 Subject: [PATCH 1338/2212] [spv-out] Rename test snapshot files. The old filenames were probably based on the shader stage, not the shader function name, which the PR changed to do in response to a review suggestion. --- .../spv/{interface.Compute.spvasm => interface.compute.spvasm} | 0 .../spv/{interface.Fragment.spvasm => interface.fragment.spvasm} | 0 .../out/spv/{interface.Vertex.spvasm => interface.vertex.spvasm} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename tests/out/spv/{interface.Compute.spvasm => interface.compute.spvasm} (100%) rename tests/out/spv/{interface.Fragment.spvasm => interface.fragment.spvasm} (100%) rename tests/out/spv/{interface.Vertex.spvasm => interface.vertex.spvasm} (100%) diff --git a/tests/out/spv/interface.Compute.spvasm b/tests/out/spv/interface.compute.spvasm similarity index 100% rename from tests/out/spv/interface.Compute.spvasm rename to tests/out/spv/interface.compute.spvasm diff --git a/tests/out/spv/interface.Fragment.spvasm b/tests/out/spv/interface.fragment.spvasm similarity index 100% rename from tests/out/spv/interface.Fragment.spvasm rename to tests/out/spv/interface.fragment.spvasm diff --git a/tests/out/spv/interface.Vertex.spvasm b/tests/out/spv/interface.vertex.spvasm similarity index 100% rename from tests/out/spv/interface.Vertex.spvasm rename to tests/out/spv/interface.vertex.spvasm From 36114d95b6be797bdf3efb3d1edf544e5f176546 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 15 Sep 2021 14:42:26 +0100 Subject: [PATCH 1339/2212] [spv-in] Move function data into BlockContext This allows removing many arguments from functions dealing with instruction parsing --- src/front/spv/function.rs | 43 +-- src/front/spv/image.rs | 128 +++----- src/front/spv/mod.rs | 594 ++++++++++++++------------------------ 3 files changed, 268 insertions(+), 497 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index d7cf7129b..1317b755f 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -118,7 +118,21 @@ impl> super::Parser { let mut parameters_sampling = vec![super::image::SamplingFlags::empty(); fun.arguments.len()]; - let mut block_ctx = BlockContext::default(); + let mut block_ctx = BlockContext { + phis: Default::default(), + blocks: Default::default(), + body_for_label: Default::default(), + mergers: Default::default(), + bodies: Default::default(), + function_id: fun_id, + expressions: &mut fun.expressions, + local_arena: &mut fun.local_variables, + const_arena: &mut module.constants, + type_arena: &module.types, + global_arena: &module.global_variables, + arguments: &fun.arguments, + parameter_sampling: &mut parameters_sampling, + }; // Insert the main body whose parent is also himself block_ctx.bodies.push(super::Body::with_parent(0)); @@ -132,18 +146,7 @@ impl> super::Parser { fun_inst.expect(2)?; let block_id = self.next()?; - self.next_block( - block_id, - fun_id, - &mut fun.expressions, - &mut fun.local_variables, - &mut module.constants, - &module.types, - &module.global_variables, - &fun.arguments, - &mut parameters_sampling, - &mut block_ctx, - )?; + self.next_block(block_id, &mut block_ctx)?; } spirv::Op::FunctionEnd => { fun_inst.expect(1)?; @@ -174,7 +177,7 @@ impl> super::Parser { // to get the spill. for phi in block_ctx.phis.iter() { // Get a pointer to the local variable for the phi's value. - let phi_pointer = fun.expressions.append( + let phi_pointer = block_ctx.expressions.append( crate::Expression::LocalVariable(phi.local), crate::Span::default(), ); @@ -213,7 +216,7 @@ impl> super::Parser { // variable, to ensure we can still use it at the end of the // predecessor. let ty = self.lookup_type[&source_lexp.type_id].handle; - let local = fun.local_variables.append( + let local = block_ctx.local_arena.append( crate::LocalVariable { name: None, ty, @@ -222,17 +225,17 @@ impl> super::Parser { crate::Span::default(), ); - let pointer = fun.expressions.append( + let pointer = block_ctx.expressions.append( crate::Expression::LocalVariable(local), crate::Span::default(), ); // Get the spilled value of the source expression. - let start = fun.expressions.len(); - let expr = fun + let start = block_ctx.expressions.len(); + let expr = block_ctx .expressions .append(crate::Expression::Load { pointer }, crate::Span::default()); - let range = fun.expressions.range_from(start); + let range = block_ctx.expressions.range_from(start); block_ctx .blocks @@ -513,7 +516,7 @@ impl> super::Parser { } } -impl BlockContext { +impl<'function> BlockContext<'function> { /// Consumes the `BlockContext` producing a Ir [`Block`](crate::Block) fn lower(mut self) -> crate::Block { fn lower_impl( diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 1f1baf805..b46fcbce1 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -311,18 +311,12 @@ impl> super::Parser { }) } - #[allow(clippy::too_many_arguments)] pub(super) fn parse_image_load( &mut self, mut words_left: u16, - type_arena: &Arena, - global_arena: &Arena, - arguments: &[FunctionArgument], - block_ctx: &mut super::BlockContext, + ctx: &mut super::BlockContext, emitter: &mut crate::front::Emitter, block: &mut crate::Block, - expressions: &mut Arena, - local_arena: &mut Arena, block_id: spirv::Word, body_idx: usize, ) -> Result<(), Error> { @@ -369,21 +363,17 @@ impl> super::Parser { // No need to call get_expr_handle here since only globals/arguments are // allowed as images and they are always in the root scope let image_lexp = self.lookup_expression.lookup(image_id)?; - let image_ty = expressions.get_image_expr_ty(image_lexp.handle, global_arena, arguments)?; + let image_ty = ctx.expressions.get_image_expr_ty( + image_lexp.handle, + ctx.global_arena, + ctx.arguments, + )?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - let coord_handle = self.get_expr_handle( - coordinate_id, - coord_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let coord_handle = + self.get_expr_handle(coordinate_id, coord_lexp, ctx, emitter, block, body_idx); let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let (coordinate, array_index) = match type_arena[image_ty].inner { + let (coordinate, array_index) = match ctx.type_arena[image_ty].inner { crate::TypeInner::Image { dim, arrayed, @@ -397,8 +387,8 @@ impl> super::Parser { }, coord_handle, coord_type_handle, - type_arena, - expressions, + ctx.type_arena, + ctx.expressions, ), _ => return Err(Error::InvalidImage(image_ty)), }; @@ -412,7 +402,7 @@ impl> super::Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, self.span_from_with_op(start)), + handle: ctx.expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, block_id, }, @@ -425,15 +415,9 @@ impl> super::Parser { &mut self, mut words_left: u16, options: SamplingOptions, - type_arena: &Arena, - global_arena: &Arena, - arguments: &[FunctionArgument], - parameters_sampling: &mut [SamplingFlags], - block_ctx: &mut super::BlockContext, + ctx: &mut super::BlockContext, emitter: &mut crate::front::Emitter, block: &mut crate::Block, - expressions: &mut Arena, - local_arena: &mut Arena, block_id: spirv::Word, body_idx: usize, ) -> Result<(), Error> { @@ -463,32 +447,16 @@ impl> super::Parser { spirv::ImageOperands::BIAS => { let bias_expr = self.next()?; let bias_lexp = self.lookup_expression.lookup(bias_expr)?; - let bias_handle = self.get_expr_handle( - bias_expr, - bias_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let bias_handle = + self.get_expr_handle(bias_expr, bias_lexp, ctx, emitter, block, body_idx); level = crate::SampleLevel::Bias(bias_handle); words_left -= 1; } spirv::ImageOperands::LOD => { let lod_expr = self.next()?; let lod_lexp = self.lookup_expression.lookup(lod_expr)?; - let lod_handle = self.get_expr_handle( - lod_expr, - lod_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let lod_handle = + self.get_expr_handle(lod_expr, lod_lexp, ctx, emitter, block, body_idx); level = if options.compare { log::debug!("Assuming {:?} is zero", lod_handle); crate::SampleLevel::Zero @@ -503,11 +471,9 @@ impl> super::Parser { let grad_x_handle = self.get_expr_handle( grad_x_expr, grad_x_lexp, - block_ctx, + ctx, emitter, block, - expressions, - local_arena, body_idx, ); let grad_y_expr = self.next()?; @@ -515,11 +481,9 @@ impl> super::Parser { let grad_y_handle = self.get_expr_handle( grad_y_expr, grad_y_lexp, - block_ctx, + ctx, emitter, block, - expressions, - local_arena, body_idx, ); level = if options.compare { @@ -556,16 +520,8 @@ impl> super::Parser { let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; - let coord_handle = self.get_expr_handle( - coordinate_id, - coord_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let coord_handle = + self.get_expr_handle(coordinate_id, coord_lexp, ctx, emitter, block, body_idx); let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; let sampling_bit = if options.compare { @@ -574,31 +530,31 @@ impl> super::Parser { SamplingFlags::REGULAR }; - let image_ty = match expressions[si_lexp.image] { + let image_ty = match ctx.expressions[si_lexp.image] { crate::Expression::GlobalVariable(handle) => { if let Some(flags) = self.handle_sampling.get_mut(&handle) { *flags |= sampling_bit; } - global_arena[handle].ty + ctx.global_arena[handle].ty } crate::Expression::FunctionArgument(i) => { - parameters_sampling[i as usize] |= sampling_bit; - arguments[i as usize].ty + ctx.parameter_sampling[i as usize] |= sampling_bit; + ctx.arguments[i as usize].ty } ref other => return Err(Error::InvalidGlobalVar(other.clone())), }; - match expressions[si_lexp.sampler] { + match ctx.expressions[si_lexp.sampler] { crate::Expression::GlobalVariable(handle) => { *self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit } crate::Expression::FunctionArgument(i) => { - parameters_sampling[i as usize] |= sampling_bit; + ctx.parameter_sampling[i as usize] |= sampling_bit; } ref other => return Err(Error::InvalidGlobalVar(other.clone())), } - let ((coordinate, array_index), depth_ref) = match type_arena[image_ty].inner { + let ((coordinate, array_index), depth_ref) = match ctx.type_arena[image_ty].inner { crate::TypeInner::Image { dim, arrayed, @@ -615,8 +571,8 @@ impl> super::Parser { }, coord_handle, coord_type_handle, - type_arena, - expressions, + ctx.type_arena, + ctx.expressions, ), { match dref_id { @@ -625,14 +581,14 @@ impl> super::Parser { if options.project { let required_size = dim.required_coordinate_size(); - let right = expressions.append( + let right = ctx.expressions.append( crate::Expression::AccessIndex { base: coord_handle, index: required_size.map_or(1, |size| size as u32), }, crate::Span::default(), ); - expr = expressions.append( + expr = ctx.expressions.append( crate::Expression::Binary { op: crate::BinaryOperator::Divide, left: expr, @@ -662,7 +618,7 @@ impl> super::Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, self.span_from_with_op(start)), + handle: ctx.expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, block_id, }, @@ -670,15 +626,12 @@ impl> super::Parser { Ok(()) } - #[allow(clippy::too_many_arguments)] pub(super) fn parse_image_query_size( &mut self, at_level: bool, - block_ctx: &mut super::BlockContext, + ctx: &mut super::BlockContext, emitter: &mut crate::front::Emitter, block: &mut crate::Block, - expressions: &mut Arena, - local_arena: &mut Arena, block_id: spirv::Word, body_idx: usize, ) -> Result<(), Error> { @@ -689,16 +642,7 @@ impl> super::Parser { let level = if at_level { let level_id = self.next()?; let level_lexp = self.lookup_expression.lookup(level_id)?; - Some(self.get_expr_handle( - level_id, - level_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - )) + Some(self.get_expr_handle(level_id, level_lexp, ctx, emitter, block, body_idx)) } else { None }; @@ -715,7 +659,7 @@ impl> super::Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, self.span_from_with_op(start)), + handle: ctx.expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, block_id, }, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3e55254f6..cdb8e89d9 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -463,8 +463,8 @@ enum MergeBlockInformation { /// [`bodies`]: BlockContext::bodies /// [`phis`]: BlockContext::phis /// [`lower`]: function::lower -#[derive(Default, Debug)] -struct BlockContext { +#[derive(Debug)] +struct BlockContext<'function> { /// Phi nodes encountered when parsing the function, used to generate spills /// to local variables. phis: Vec, @@ -484,6 +484,23 @@ struct BlockContext { /// A table of `Body` values, each representing a block in the final IR. bodies: Vec, + + /// Id of the function currently being processed + function_id: spirv::Word, + /// Expression arena of the function currently being processed + expressions: &'function mut Arena, + /// Local variables arena of the function currently being processed + local_arena: &'function mut Arena, + /// Constants arena of the module being processed + const_arena: &'function mut Arena, + /// Type arena of the module being processed + type_arena: &'function Arena, + /// Global arena of the module being processed + global_arena: &'function Arena, + /// Arguments of the function currently being processed + arguments: &'function [crate::FunctionArgument], + /// Metadata about the usage of function parameters as sampling objects + parameter_sampling: &'function mut [image::SamplingFlags], } pub struct Parser { @@ -698,20 +715,17 @@ impl> Parser { /// /// The `body_idx` argument should be the index of the `Body` that hopes to /// use `id`'s `Expression`. - #[allow(clippy::too_many_arguments)] fn get_expr_handle( &self, id: spirv::Word, lookup: &LookupExpression, - block_ctx: &mut BlockContext, + ctx: &mut BlockContext, emitter: &mut super::Emitter, block: &mut crate::Block, - expressions: &mut Arena, - local_arena: &mut Arena, body_idx: BodyIndex, ) -> Handle { // What `Body` was `id` defined in? - let expr_body_idx = block_ctx + let expr_body_idx = ctx .body_for_label .get(&lookup.block_id) .copied() @@ -723,13 +737,13 @@ impl> Parser { // or conditional occurs but in those cases we know that the new body // will be a subscope of the body that was passed so we can still reuse // the handle and not issue a load/store. - if is_parent(body_idx, expr_body_idx, block_ctx) { + if is_parent(body_idx, expr_body_idx, ctx) { lookup.handle } else { // Add a temporary variable of the same type which will be used to // store the original expression and used in the current block let ty = self.lookup_type[&lookup.type_id].handle; - let local = local_arena.append( + let local = ctx.local_arena.append( crate::LocalVariable { name: None, ty, @@ -738,14 +752,15 @@ impl> Parser { crate::Span::default(), ); - block.extend(emitter.finish(expressions)); - let pointer = expressions.append( + block.extend(emitter.finish(ctx.expressions)); + let pointer = ctx.expressions.append( crate::Expression::LocalVariable(local), crate::Span::default(), ); - emitter.start(expressions); - let expr = - expressions.append(crate::Expression::Load { pointer }, crate::Span::default()); + emitter.start(ctx.expressions); + let expr = ctx + .expressions + .append(crate::Expression::Load { pointer }, crate::Span::default()); // Add a slightly odd entry to the phi table, so that while `id`'s // `Expression` is still in scope, the usual phi processing will @@ -755,7 +770,7 @@ impl> Parser { // predecessor of some other block with a phi in it that cites id as // one of its sources, and uses `local` as its variable. There is no // such phi, but nobody needs to know that. - block_ctx.phis.push(PhiExpression { + ctx.phis.push(PhiExpression { local, expressions: vec![(id, lookup.block_id)], }); @@ -764,14 +779,11 @@ impl> Parser { } } - #[allow(clippy::too_many_arguments)] fn parse_expr_unary_op( &mut self, - block_ctx: &mut BlockContext, + ctx: &mut BlockContext, emitter: &mut super::Emitter, block: &mut crate::Block, - expressions: &mut Arena, - local_arena: &mut Arena, block_id: spirv::Word, body_idx: usize, op: crate::UnaryOperator, @@ -782,22 +794,13 @@ impl> Parser { let p_id = self.next()?; let p_lexp = self.lookup_expression.lookup(p_id)?; - let handle = self.get_expr_handle( - p_id, - p_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let handle = self.get_expr_handle(p_id, p_lexp, ctx, emitter, block, body_idx); let expr = crate::Expression::Unary { op, expr: handle }; self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, self.span_from_with_op(start)), + handle: ctx.expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, block_id, }, @@ -805,14 +808,11 @@ impl> Parser { Ok(()) } - #[allow(clippy::too_many_arguments)] fn parse_expr_binary_op( &mut self, - block_ctx: &mut BlockContext, + ctx: &mut BlockContext, emitter: &mut super::Emitter, block: &mut crate::Block, - expressions: &mut Arena, - local_arena: &mut Arena, block_id: spirv::Word, body_idx: usize, op: crate::BinaryOperator, @@ -824,33 +824,15 @@ impl> Parser { let p2_id = self.next()?; let p1_lexp = self.lookup_expression.lookup(p1_id)?; - let left = self.get_expr_handle( - p1_id, - p1_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); let p2_lexp = self.lookup_expression.lookup(p2_id)?; - let right = self.get_expr_handle( - p2_id, - p2_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let right = self.get_expr_handle(p2_id, p2_lexp, ctx, emitter, block, body_idx); let expr = crate::Expression::Binary { op, left, right }; self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, self.span_from_with_op(start)), + handle: ctx.expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, block_id, }, @@ -861,18 +843,14 @@ impl> Parser { /// A more complicated version of the binary op, /// where we force the operand to have the same type as the result. /// This is mostly needed for "i++" and "i--" coming from GLSL. - #[allow(clippy::too_many_arguments)] fn parse_expr_binary_op_sign_adjusted( &mut self, - block_ctx: &mut BlockContext, + ctx: &mut BlockContext, emitter: &mut super::Emitter, block: &mut crate::Block, - expressions: &mut Arena, - local_arena: &mut Arena, block_id: spirv::Word, body_idx: usize, op: crate::BinaryOperator, - types: &Arena, ) -> Result<(), Error> { let start = self.data_offset; let result_type_id = self.next()?; @@ -882,36 +860,21 @@ impl> Parser { let span = self.span_from_with_op(start); let p1_lexp = self.lookup_expression.lookup(p1_id)?; - let left = self.get_expr_handle( - p1_id, - p1_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); let p2_lexp = self.lookup_expression.lookup(p2_id)?; - let right = self.get_expr_handle( - p2_id, - p2_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let right = self.get_expr_handle(p2_id, p2_lexp, ctx, emitter, block, body_idx); let result_lookup_ty = self.lookup_type.lookup(result_type_id)?; - let kind = types[result_lookup_ty.handle].inner.scalar_kind().unwrap(); + let kind = ctx.type_arena[result_lookup_ty.handle] + .inner + .scalar_kind() + .unwrap(); let expr = crate::Expression::Binary { op, left: if p1_lexp.type_id == result_type_id { left } else { - expressions.append( + ctx.expressions.append( crate::Expression::As { expr: left, kind, @@ -923,7 +886,7 @@ impl> Parser { right: if p2_lexp.type_id == result_type_id { right } else { - expressions.append( + ctx.expressions.append( crate::Expression::As { expr: right, kind, @@ -937,7 +900,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -945,14 +908,11 @@ impl> Parser { Ok(()) } - #[allow(clippy::too_many_arguments)] fn parse_expr_shift_op( &mut self, - block_ctx: &mut BlockContext, + ctx: &mut BlockContext, emitter: &mut super::Emitter, block: &mut crate::Block, - expressions: &mut Arena, - local_arena: &mut Arena, block_id: spirv::Word, body_idx: usize, op: crate::BinaryOperator, @@ -966,29 +926,11 @@ impl> Parser { let span = self.span_from_with_op(start); let p1_lexp = self.lookup_expression.lookup(p1_id)?; - let left = self.get_expr_handle( - p1_id, - p1_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); let p2_lexp = self.lookup_expression.lookup(p2_id)?; - let p2_handle = self.get_expr_handle( - p2_id, - p2_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let p2_handle = self.get_expr_handle(p2_id, p2_lexp, ctx, emitter, block, body_idx); // convert the shift to Uint - let right = expressions.append( + let right = ctx.expressions.append( crate::Expression::As { expr: p2_handle, kind: crate::ScalarKind::Uint, @@ -1001,7 +943,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -1009,14 +951,11 @@ impl> Parser { Ok(()) } - #[allow(clippy::too_many_arguments)] fn parse_expr_derivative( &mut self, - block_ctx: &mut BlockContext, + ctx: &mut BlockContext, emitter: &mut super::Emitter, block: &mut crate::Block, - expressions: &mut Arena, - local_arena: &mut Arena, block_id: spirv::Word, body_idx: usize, axis: crate::DerivativeAxis, @@ -1027,16 +966,7 @@ impl> Parser { let arg_id = self.next()?; let arg_lexp = self.lookup_expression.lookup(arg_id)?; - let arg_handle = self.get_expr_handle( - arg_id, - arg_lexp, - block_ctx, - emitter, - block, - expressions, - local_arena, - body_idx, - ); + let arg_handle = self.get_expr_handle(arg_id, arg_lexp, ctx, emitter, block, body_idx); let expr = crate::Expression::Derivative { axis, @@ -1045,7 +975,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, self.span_from_with_op(start)), + handle: ctx.expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, block_id, }, @@ -1124,20 +1054,7 @@ impl> Parser { /// Except for the function's entry block, `block_id` should be the label of /// a block we've seen mentioned before, with an entry in /// `block_ctx.body_for_label` to tell us which `Body` it contributes to. - #[allow(clippy::too_many_arguments)] - fn next_block( - &mut self, - block_id: spirv::Word, - function_id: spirv::Word, - expressions: &mut Arena, - local_arena: &mut Arena, - const_arena: &mut Arena, - type_arena: &Arena, - global_arena: &Arena, - arguments: &[crate::FunctionArgument], - parmeter_sampling: &mut [image::SamplingFlags], - block_ctx: &mut BlockContext, - ) -> Result<(), Error> { + fn next_block(&mut self, block_id: spirv::Word, ctx: &mut BlockContext) -> Result<(), Error> { // Extend `body` with the correct form for a branch to `target`. fn merger(body: &mut Body, target: &MergeBlockInformation) { body.data.push(match *target { @@ -1153,11 +1070,11 @@ impl> Parser { } let mut emitter = super::Emitter::default(); - emitter.start(expressions); + emitter.start(ctx.expressions); // Find the `Body` that this block belongs to. Index zero is the // function's root `Body`, corresponding to `Function::body`. - let mut body_idx = *block_ctx.body_for_label.entry(block_id).or_default(); + let mut body_idx = *ctx.body_for_label.entry(block_id).or_default(); let mut block = crate::Block::new(); // Stores the merge block as defined by a `OpSelectionMerge` otherwise is `None` // @@ -1168,80 +1085,32 @@ impl> Parser { macro_rules! get_expr_handle { ($id:expr, $lexp:expr) => { - self.get_expr_handle( - $id, - $lexp, - block_ctx, - &mut emitter, - &mut block, - expressions, - local_arena, - body_idx, - ) + self.get_expr_handle($id, $lexp, ctx, &mut emitter, &mut block, body_idx) }; } macro_rules! parse_expr_op { ($op:expr, BINARY) => { - self.parse_expr_binary_op( - block_ctx, - &mut emitter, - &mut block, - expressions, - local_arena, - block_id, - body_idx, - $op, - ) + self.parse_expr_binary_op(ctx, &mut emitter, &mut block, block_id, body_idx, $op) }; ($op:expr, BINARY_SIGN_ADJUSTED) => { self.parse_expr_binary_op_sign_adjusted( - block_ctx, + ctx, &mut emitter, &mut block, - expressions, - local_arena, block_id, body_idx, $op, - type_arena, ) }; ($op:expr, SHIFT) => { - self.parse_expr_shift_op( - block_ctx, - &mut emitter, - &mut block, - expressions, - local_arena, - block_id, - body_idx, - $op, - ) + self.parse_expr_shift_op(ctx, &mut emitter, &mut block, block_id, body_idx, $op) }; ($op:expr, UNARY) => { - self.parse_expr_unary_op( - block_ctx, - &mut emitter, - &mut block, - expressions, - local_arena, - block_id, - body_idx, - $op, - ) + self.parse_expr_unary_op(ctx, &mut emitter, &mut block, block_id, body_idx, $op) }; ($axis:expr, DERIVATIVE) => { - self.parse_expr_derivative( - block_ctx, - &mut emitter, - &mut block, - expressions, - local_arena, - block_id, - body_idx, - $axis, - ) + self.parse_expr_derivative(ctx, &mut emitter, &mut block, block_id, body_idx, $axis) }; } @@ -1263,11 +1132,13 @@ impl> Parser { Op::Undef => { inst.expect(3)?; let (type_id, id, handle) = - self.parse_null_constant(inst, type_arena, const_arena)?; + self.parse_null_constant(inst, ctx.type_arena, ctx.const_arena)?; self.lookup_expression.insert( id, LookupExpression { - handle: expressions.append(crate::Expression::Constant(handle), span), + handle: ctx + .expressions + .append(crate::Expression::Constant(handle), span), type_id, block_id, }, @@ -1275,7 +1146,7 @@ impl> Parser { } Op::Variable => { inst.expect_at_least(4)?; - block.extend(emitter.finish(expressions)); + block.extend(emitter.finish(ctx.expressions)); let result_type_id = self.next()?; let result_id = self.next()?; @@ -1297,10 +1168,10 @@ impl> Parser { log::debug!("\t\t\tid={} name={}", result_id, name); } let lookup_ty = self.lookup_type.lookup(result_type_id)?; - let var_handle = local_arena.append( + let var_handle = ctx.local_arena.append( crate::LocalVariable { name, - ty: match type_arena[lookup_ty.handle].inner { + ty: match ctx.type_arena[lookup_ty.handle].inner { crate::TypeInner::Pointer { base, .. } => base, _ => lookup_ty.handle, }, @@ -1312,23 +1183,24 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions + handle: ctx + .expressions .append(crate::Expression::LocalVariable(var_handle), span), type_id: result_type_id, block_id, }, ); - emitter.start(expressions); + emitter.start(ctx.expressions); } Op::Phi => { inst.expect_at_least(3)?; - block.extend(emitter.finish(expressions)); + block.extend(emitter.finish(ctx.expressions)); let result_type_id = self.next()?; let result_id = self.next()?; let name = format!("phi_{}", result_id); - let local = local_arena.append( + let local = ctx.local_arena.append( crate::LocalVariable { name: Some(name), ty: self.lookup_type.lookup(result_type_id)?.handle, @@ -1336,7 +1208,9 @@ impl> Parser { }, self.span_from(start), ); - let pointer = expressions.append(crate::Expression::LocalVariable(local), span); + let pointer = ctx + .expressions + .append(crate::Expression::LocalVariable(local), span); let in_count = (inst.wc - 3) / 2; let mut phi = PhiExpression { @@ -1349,15 +1223,17 @@ impl> Parser { phi.expressions.push((expr, block)); } - block_ctx.phis.push(phi); - emitter.start(expressions); + ctx.phis.push(phi); + emitter.start(ctx.expressions); // Associate the lookup with an actual value, which is emitted // into the current block. self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(crate::Expression::Load { pointer }, span), + handle: ctx + .expressions + .append(crate::Expression::Load { pointer }, span), type_id: result_type_id, block_id, }, @@ -1392,10 +1268,10 @@ impl> Parser { log::trace!("\t\t\tlooking up index expr {:?}", access_id); let index_expr = self.lookup_expression.lookup(access_id)?.clone(); let index_expr_handle = get_expr_handle!(access_id, &index_expr); - let index_expr_data = &expressions[index_expr.handle]; + let index_expr_data = &ctx.expressions[index_expr.handle]; let index_maybe = match *index_expr_data { crate::Expression::Constant(const_handle) => { - Some(const_arena[const_handle].to_array_length().ok_or( + Some(ctx.const_arena[const_handle].to_array_length().ok_or( Error::InvalidAccess(crate::Expression::Constant(const_handle)), )?) } @@ -1404,7 +1280,7 @@ impl> Parser { log::trace!("\t\t\tlooking up type {:?}", acex.type_id); let type_lookup = self.lookup_type.lookup(acex.type_id)?; - acex = match type_arena[type_lookup.handle].inner { + acex = match ctx.type_arena[type_lookup.handle].inner { // can only index a struct with a constant crate::TypeInner::Struct { .. } => { let index = index_maybe @@ -1413,7 +1289,7 @@ impl> Parser { .lookup_member .get(&(type_lookup.handle, index)) .ok_or(Error::InvalidAccessType(acex.type_id))?; - let base_handle = expressions.append( + let base_handle = ctx.expressions.append( crate::Expression::AccessIndex { base: acex.base_handle, index, @@ -1427,16 +1303,16 @@ impl> Parser { debug_assert!(acex.load_override.is_none()); let sub_type_lookup = self.lookup_type.lookup(lookup_member.type_id)?; - Some(match type_arena[sub_type_lookup.handle].inner { + Some(match ctx.type_arena[sub_type_lookup.handle].inner { // load it transposed, to match column major expectations crate::TypeInner::Matrix { .. } => { - let loaded = expressions.append( + let loaded = ctx.expressions.append( crate::Expression::Load { pointer: base_handle, }, span, ); - let transposed = expressions.append( + let transposed = ctx.expressions.append( crate::Expression::Math { fun: crate::MathFunction::Transpose, arg: loaded, @@ -1461,7 +1337,7 @@ impl> Parser { let index = index_maybe.ok_or_else(|| { Error::InvalidAccess(index_expr_data.clone()) })?; - let sub_handle = expressions.append( + let sub_handle = ctx.expressions.append( crate::Expression::AccessIndex { base: load_expr, index, @@ -1483,7 +1359,7 @@ impl> Parser { }, }; AccessExpression { - base_handle: expressions.append(sub_expr, span), + base_handle: ctx.expressions.append(sub_expr, span), type_id: type_lookup .base_id .ok_or(Error::InvalidAccessType(acex.type_id))?, @@ -1492,7 +1368,7 @@ impl> Parser { } // This must be a vector or an array. _ => { - let base_handle = expressions.append( + let base_handle = ctx.expressions.append( crate::Expression::Access { base: acex.base_handle, index: index_expr_handle, @@ -1507,13 +1383,13 @@ impl> Parser { // We must be indexing into the array of row-major matrices. // Let's load the result of indexing and transpose it. LookupLoadOverride::Pending => { - let loaded = expressions.append( + let loaded = ctx.expressions.append( crate::Expression::Load { pointer: base_handle, }, span, ); - expressions.append( + ctx.expressions.append( crate::Expression::Math { fun: crate::MathFunction::Transpose, arg: loaded, @@ -1524,14 +1400,15 @@ impl> Parser { ) } // We are indexing inside a row-major matrix. - LookupLoadOverride::Loaded(load_expr) => expressions - .append( + LookupLoadOverride::Loaded(load_expr) => { + ctx.expressions.append( crate::Expression::Access { base: load_expr, index: index_expr_handle, }, span, - ), + ) + } }; Some(LookupLoadOverride::Loaded(sub_expr)) } @@ -1572,12 +1449,12 @@ impl> Parser { let index_lexp = self.lookup_expression.lookup(index_id)?; let index_handle = get_expr_handle!(index_id, index_lexp); - let num_components = match type_arena[root_type_lookup.handle].inner { + let num_components = match ctx.type_arena[root_type_lookup.handle].inner { crate::TypeInner::Vector { size, .. } => size as usize, _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), }; - let mut handle = expressions.append( + let mut handle = ctx.expressions.append( crate::Expression::Access { base: root_handle, index: self.index_constant_expressions[0], @@ -1585,14 +1462,14 @@ impl> Parser { span, ); for &index_expr in self.index_constant_expressions[1..num_components].iter() { - let access_expr = expressions.append( + let access_expr = ctx.expressions.append( crate::Expression::Access { base: root_handle, index: index_expr, }, span, ); - let cond = expressions.append( + let cond = ctx.expressions.append( crate::Expression::Binary { op: crate::BinaryOperator::Equal, left: index_expr, @@ -1600,7 +1477,7 @@ impl> Parser { }, span, ); - handle = expressions.append( + handle = ctx.expressions.append( crate::Expression::Select { condition: cond, accept: access_expr, @@ -1636,20 +1513,20 @@ impl> Parser { let index_lexp = self.lookup_expression.lookup(index_id)?; let index_handle = get_expr_handle!(index_id, index_lexp); - let num_components = match type_arena[root_type_lookup.handle].inner { + let num_components = match ctx.type_arena[root_type_lookup.handle].inner { crate::TypeInner::Vector { size, .. } => size as usize, _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), }; let mut components = Vec::with_capacity(num_components); for &index_expr in self.index_constant_expressions[..num_components].iter() { - let access_expr = expressions.append( + let access_expr = ctx.expressions.append( crate::Expression::Access { base: root_handle, index: index_expr, }, span, ); - let cond = expressions.append( + let cond = ctx.expressions.append( crate::Expression::Binary { op: crate::BinaryOperator::Equal, left: index_expr, @@ -1657,7 +1534,7 @@ impl> Parser { }, span, ); - let handle = expressions.append( + let handle = ctx.expressions.append( crate::Expression::Select { condition: cond, accept: object_handle, @@ -1667,7 +1544,7 @@ impl> Parser { ); components.push(handle); } - let handle = expressions.append( + let handle = ctx.expressions.append( crate::Expression::Compose { ty: root_type_lookup.handle, components, @@ -1697,7 +1574,7 @@ impl> Parser { let index = self.next()?; log::trace!("\t\t\tlooking up type {:?}", lexp.type_id); let type_lookup = self.lookup_type.lookup(lexp.type_id)?; - let type_id = match type_arena[type_lookup.handle].inner { + let type_id = match ctx.type_arena[type_lookup.handle].inner { crate::TypeInner::Struct { .. } => { self.lookup_member .get(&(type_lookup.handle, index)) @@ -1715,7 +1592,7 @@ impl> Parser { } }; lexp = LookupExpression { - handle: expressions.append( + handle: ctx.expressions.append( crate::Expression::AccessIndex { base: lexp.handle, index, @@ -1757,8 +1634,8 @@ impl> Parser { result_type_id, object_handle, &selections, - type_arena, - expressions, + ctx.type_arena, + ctx.expressions, span, )?; @@ -1786,7 +1663,7 @@ impl> Parser { } let ty = self.lookup_type.lookup(result_type_id)?.handle; let first = components[0]; - let expr = match type_arena[ty].inner { + let expr = match ctx.type_arena[ty].inner { // this is an optimization to detect the splat crate::TypeInner::Vector { size, .. } if components.len() == size as usize @@ -1799,7 +1676,7 @@ impl> Parser { self.lookup_expression.insert( id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -1819,14 +1696,14 @@ impl> Parser { let base_lexp = self.lookup_expression.lookup(pointer_id)?; let base_handle = get_expr_handle!(pointer_id, base_lexp); let type_lookup = self.lookup_type.lookup(base_lexp.type_id)?; - let handle = match type_arena[type_lookup.handle].inner { + let handle = match ctx.type_arena[type_lookup.handle].inner { crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { base_handle } _ => match self.lookup_load_override.get(&pointer_id) { Some(&LookupLoadOverride::Loaded(handle)) => handle, //Note: we aren't handling `LookupLoadOverride::Pending` properly here - _ => expressions.append( + _ => ctx.expressions.append( crate::Expression::Load { pointer: base_handle, }, @@ -1858,7 +1735,7 @@ impl> Parser { let value_expr = self.lookup_expression.lookup(value_id)?; let value_handle = get_expr_handle!(value_id, value_expr); - block.extend(emitter.finish(expressions)); + block.extend(emitter.finish(ctx.expressions)); block.push( crate::Statement::Store { pointer: base_handle, @@ -1866,7 +1743,7 @@ impl> Parser { }, span, ); - emitter.start(expressions); + emitter.start(ctx.expressions); } // Arithmetic Instructions +, -, *, /, % Op::SNegate | Op::FNegate => { @@ -1926,7 +1803,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -1952,7 +1829,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -1978,7 +1855,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -2028,27 +1905,22 @@ impl> Parser { let extra = inst.expect_at_least(4)?; let stmt = self.parse_image_write( extra, - type_arena, - global_arena, - arguments, - expressions, + ctx.type_arena, + ctx.global_arena, + ctx.arguments, + ctx.expressions, )?; - block.extend(emitter.finish(expressions)); + block.extend(emitter.finish(ctx.expressions)); block.push(stmt, span); - emitter.start(expressions); + emitter.start(ctx.expressions); } Op::ImageFetch | Op::ImageRead => { let extra = inst.expect_at_least(5)?; self.parse_image_load( extra, - type_arena, - global_arena, - arguments, - block_ctx, + ctx, &mut emitter, &mut block, - expressions, - local_arena, block_id, body_idx, )?; @@ -2062,15 +1934,9 @@ impl> Parser { self.parse_image_sample( extra, options, - type_arena, - global_arena, - arguments, - parmeter_sampling, - block_ctx, + ctx, &mut emitter, &mut block, - expressions, - local_arena, block_id, body_idx, )?; @@ -2084,15 +1950,9 @@ impl> Parser { self.parse_image_sample( extra, options, - type_arena, - global_arena, - arguments, - parmeter_sampling, - block_ctx, + ctx, &mut emitter, &mut block, - expressions, - local_arena, block_id, body_idx, )?; @@ -2106,15 +1966,9 @@ impl> Parser { self.parse_image_sample( extra, options, - type_arena, - global_arena, - arguments, - parmeter_sampling, - block_ctx, + ctx, &mut emitter, &mut block, - expressions, - local_arena, block_id, body_idx, )?; @@ -2128,15 +1982,9 @@ impl> Parser { self.parse_image_sample( extra, options, - type_arena, - global_arena, - arguments, - parmeter_sampling, - block_ctx, + ctx, &mut emitter, &mut block, - expressions, - local_arena, block_id, body_idx, )?; @@ -2145,11 +1993,9 @@ impl> Parser { inst.expect(4)?; self.parse_image_query_size( false, - block_ctx, + ctx, &mut emitter, &mut block, - expressions, - local_arena, block_id, body_idx, )?; @@ -2158,11 +2004,9 @@ impl> Parser { inst.expect(5)?; self.parse_image_query_size( true, - block_ctx, + ctx, &mut emitter, &mut block, - expressions, - local_arena, block_id, body_idx, )?; @@ -2171,7 +2015,7 @@ impl> Parser { inst.expect(4)?; self.parse_image_query_other( crate::ImageQuery::NumLevels, - expressions, + ctx.expressions, block_id, )?; } @@ -2179,7 +2023,7 @@ impl> Parser { inst.expect(4)?; self.parse_image_query_other( crate::ImageQuery::NumSamples, - expressions, + ctx.expressions, block_id, )?; } @@ -2207,7 +2051,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -2223,14 +2067,14 @@ impl> Parser { let v1_lexp = self.lookup_expression.lookup(v1_id)?; let v1_lty = self.lookup_type.lookup(v1_lexp.type_id)?; let v1_handle = get_expr_handle!(v1_id, v1_lexp); - let n1 = match type_arena[v1_lty.handle].inner { + let n1 = match ctx.type_arena[v1_lty.handle].inner { crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidInnerType(v1_lexp.type_id)), }; let v2_lexp = self.lookup_expression.lookup(v2_id)?; let v2_lty = self.lookup_type.lookup(v2_lexp.type_id)?; let v2_handle = get_expr_handle!(v2_id, v2_lexp); - let n2 = match type_arena[v2_lty.handle].inner { + let n2 = match ctx.type_arena[v2_lty.handle].inner { crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidInnerType(v2_lexp.type_id)), }; @@ -2286,7 +2130,7 @@ impl> Parser { } else { return Err(Error::InvalidAccessIndex(index)); }; - components.push(expressions.append(expr, span)); + components.push(ctx.expressions.append(expr, span)); } crate::Expression::Compose { ty: self.lookup_type.lookup(result_type_id)?.handle, @@ -2297,7 +2141,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -2318,7 +2162,7 @@ impl> Parser { let value_lexp = self.lookup_expression.lookup(value_id)?; let ty_lookup = self.lookup_type.lookup(result_type_id)?; - let (kind, width) = match type_arena[ty_lookup.handle].inner { + let (kind, width) = match ctx.type_arena[ty_lookup.handle].inner { crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Vector { kind, width, .. } => (kind, width), crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), @@ -2337,7 +2181,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -2345,7 +2189,7 @@ impl> Parser { } Op::FunctionCall => { inst.expect_at_least(4)?; - block.extend(emitter.finish(expressions)); + block.extend(emitter.finish(ctx.expressions)); let result_type_id = self.next()?; let result_id = self.next()?; @@ -2359,13 +2203,14 @@ impl> Parser { } // We just need an unique handle here, nothing more. - let function = self.add_call(function_id, func_id); + let function = self.add_call(ctx.function_id, func_id); let result = if self.lookup_void_type == Some(result_type_id) { None } else { - let expr_handle = - expressions.append(crate::Expression::CallResult(function), span); + let expr_handle = ctx + .expressions + .append(crate::Expression::CallResult(function), span); self.lookup_expression.insert( result_id, LookupExpression { @@ -2384,7 +2229,7 @@ impl> Parser { }, span, ); - emitter.start(expressions); + emitter.start(ctx.expressions); } Op::ExtInst => { use crate::MathFunction as Mf; @@ -2410,7 +2255,7 @@ impl> Parser { get_expr_handle!(arg_id, lexp) }; - let constant_handle = const_arena.fetch_or_append( + let constant_handle = ctx.const_arena.fetch_or_append( crate::Constant { name: None, specialization: None, @@ -2426,7 +2271,7 @@ impl> Parser { Default::default(), ); - let expr_handle = expressions.append( + let expr_handle = ctx.expressions.append( crate::Expression::Constant(constant_handle), Default::default(), ); @@ -2434,7 +2279,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append( + handle: ctx.expressions.append( crate::Expression::Binary { op: crate::BinaryOperator::Multiply, left: arg, @@ -2529,7 +2374,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -2593,7 +2438,7 @@ impl> Parser { self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, span), + handle: ctx.expressions.append(expr, span), type_id: result_type_id, block_id, }, @@ -2626,10 +2471,10 @@ impl> Parser { // If this is a branch to a merge or continue block, // then that ends the current body. - if let Some(info) = block_ctx.mergers.get(&target_id) { - block.extend(emitter.finish(expressions)); - block_ctx.blocks.insert(block_id, block); - let body = &mut block_ctx.bodies[body_idx]; + if let Some(info) = ctx.mergers.get(&target_id) { + block.extend(emitter.finish(ctx.expressions)); + ctx.blocks.insert(block_id, block); + let body = &mut ctx.bodies[body_idx]; body.data.push(BodyFragment::BlockId(block_id)); merger(body, info); @@ -2646,10 +2491,7 @@ impl> Parser { // For example a switch with falltrough, the OpSwitch will set the body to // the respective case and the case may branch to another case in which case // the body index shouldn't be changed - block_ctx - .body_for_label - .entry(target_id) - .or_insert(body_idx); + ctx.body_for_label.entry(target_id).or_insert(body_idx); break None; } @@ -2666,38 +2508,38 @@ impl> Parser { let false_id = self.next()?; // Start a body block for the `accept` branch. - let accept = block_ctx.bodies.len(); + let accept = ctx.bodies.len(); let mut accept_block = Body::with_parent(body_idx); // If the `OpBranchConditional`target is somebody else's // merge or continue block, then put a `Break` or `Continue` // statement in this new body block. - if let Some(info) = block_ctx.mergers.get(&true_id) { + if let Some(info) = ctx.mergers.get(&true_id) { merger(&mut accept_block, info) } else { // Note the body index for the block we're branching to. - let prev = block_ctx.body_for_label.insert(true_id, accept); + let prev = ctx.body_for_label.insert(true_id, accept); debug_assert!(prev.is_none()); } - block_ctx.bodies.push(accept_block); + ctx.bodies.push(accept_block); // Handle the `reject` branch just like the `accept` block. - let reject = block_ctx.bodies.len(); + let reject = ctx.bodies.len(); let mut reject_block = Body::with_parent(body_idx); - if let Some(info) = block_ctx.mergers.get(&false_id) { + if let Some(info) = ctx.mergers.get(&false_id) { merger(&mut reject_block, info) } else { - let prev = block_ctx.body_for_label.insert(false_id, reject); + let prev = ctx.body_for_label.insert(false_id, reject); debug_assert!(prev.is_none()); } - block_ctx.bodies.push(reject_block); + ctx.bodies.push(reject_block); - block.extend(emitter.finish(expressions)); - block_ctx.blocks.insert(block_id, block); - let body = &mut block_ctx.bodies[body_idx]; + block.extend(emitter.finish(ctx.expressions)); + ctx.blocks.insert(block_id, block); + let body = &mut ctx.bodies[body_idx]; // Make sure the vector has space for at least two more allocations body.data.reserve(2); body.data.push(BodyFragment::BlockId(block_id)); @@ -2717,28 +2559,24 @@ impl> Parser { // If the previous instruction was a `OpSelectionMerge` then we must // promote the `MergeBlockInformation` to a `SwitchMerge` if let Some(merge) = selection_merge_block { - block_ctx - .mergers + ctx.mergers .insert(merge, MergeBlockInformation::SwitchMerge); } - let default = block_ctx.bodies.len(); - block_ctx.bodies.push(Body::with_parent(body_idx)); - block_ctx - .body_for_label - .entry(default_id) - .or_insert(default); + let default = ctx.bodies.len(); + ctx.bodies.push(Body::with_parent(body_idx)); + ctx.body_for_label.entry(default_id).or_insert(default); let selector_lexp = &self.lookup_expression[&selector]; let selector_lty = self.lookup_type.lookup(selector_lexp.type_id)?; let selector_handle = get_expr_handle!(selector, selector_lexp); - let selector = match type_arena[selector_lty.handle].inner { + let selector = match ctx.type_arena[selector_lty.handle].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width: _, } => { // IR expects a signed integer, so do a bitcast - expressions.append( + ctx.expressions.append( crate::Expression::As { kind: crate::ScalarKind::Sint, expr: selector_handle, @@ -2759,26 +2597,23 @@ impl> Parser { let literal = self.next()?; let target = self.next()?; - let case_body_idx = block_ctx.bodies.len(); + let case_body_idx = ctx.bodies.len(); let mut body = Body::with_parent(body_idx); - if let Some(info) = block_ctx.mergers.get(&target) { + if let Some(info) = ctx.mergers.get(&target) { merger(&mut body, info); } - block_ctx.bodies.push(body); - block_ctx - .body_for_label - .entry(target) - .or_insert(case_body_idx); + ctx.bodies.push(body); + ctx.body_for_label.entry(target).or_insert(case_body_idx); cases.push((literal as i32, case_body_idx)); } - block.extend(emitter.finish(expressions)); + block.extend(emitter.finish(ctx.expressions)); - let body = &mut block_ctx.bodies[body_idx]; - block_ctx.blocks.insert(block_id, block); + let body = &mut ctx.bodies[body_idx]; + ctx.blocks.insert(block_id, block); // Make sure the vector has space for at least two more allocations body.data.reserve(2); body.data.push(BodyFragment::BlockId(block_id)); @@ -2798,15 +2633,11 @@ impl> Parser { // Indicate that the merge block is a continuation of the // current `Body`. - block_ctx - .body_for_label - .entry(merge_block_id) - .or_insert(body_idx); + ctx.body_for_label.entry(merge_block_id).or_insert(body_idx); // Let subsequent branches to the merge block know that // they've reached the end of the selection construct. - block_ctx - .mergers + ctx.mergers .insert(merge_block_id, MergeBlockInformation::SelectionMerge); selection_merge_block = Some(merge_block_id); @@ -2823,36 +2654,28 @@ impl> Parser { // Indicate that the merge block is a continuation of the // current `Body`. - block_ctx - .body_for_label - .entry(merge_block_id) - .or_insert(body_idx); + ctx.body_for_label.entry(merge_block_id).or_insert(body_idx); // Let subsequent branches to the merge block know that // they're `Break` statements. - block_ctx - .mergers + ctx.mergers .insert(merge_block_id, MergeBlockInformation::LoopMerge); - let loop_body_idx = block_ctx.bodies.len(); - block_ctx.bodies.push(Body::with_parent(body_idx)); + let loop_body_idx = ctx.bodies.len(); + ctx.bodies.push(Body::with_parent(body_idx)); - let continue_idx = block_ctx.bodies.len(); + let continue_idx = ctx.bodies.len(); // The continue block inherits the scope of the loop body - block_ctx.bodies.push(Body::with_parent(loop_body_idx)); - block_ctx - .body_for_label - .entry(continuing) - .or_insert(continue_idx); + ctx.bodies.push(Body::with_parent(loop_body_idx)); + ctx.body_for_label.entry(continuing).or_insert(continue_idx); // Let subsequent branches to the continue block know that // they're `Continue` statements. - block_ctx - .mergers + ctx.mergers .insert(continuing, MergeBlockInformation::LoopContinue); // The loop header always belongs to the loop body - block_ctx.body_for_label.insert(block_id, loop_body_idx); + ctx.body_for_label.insert(block_id, loop_body_idx); - let parent_body = &mut block_ctx.bodies[body_idx]; + let parent_body = &mut ctx.bodies[body_idx]; parent_body.data.push(BodyFragment::Loop { body: loop_body_idx, continuing: continue_idx, @@ -2881,7 +2704,7 @@ impl> Parser { let structure_ptr = self.lookup_expression.lookup(structure_id)?; let structure_handle = get_expr_handle!(structure_id, structure_ptr); - let member_ptr = expressions.append( + let member_ptr = ctx.expressions.append( crate::Expression::AccessIndex { base: structure_handle, index: member_index, @@ -2889,8 +2712,9 @@ impl> Parser { span, ); - let length = - expressions.append(crate::Expression::ArrayLength(member_ptr), span); + let length = ctx + .expressions + .append(crate::Expression::ArrayLength(member_ptr), span); self.lookup_expression.insert( result_id, @@ -2920,14 +2744,14 @@ impl> Parser { let source_handle = get_expr_handle!(source_id, source); // This operation is practically the same as loading and then storing, I think. - let value_expr = expressions.append( + let value_expr = ctx.expressions.append( crate::Expression::Load { pointer: source_handle, }, span, ); - block.extend(emitter.finish(expressions)); + block.extend(emitter.finish(ctx.expressions)); block.push( crate::Statement::Store { pointer: target_handle, @@ -2936,7 +2760,7 @@ impl> Parser { span, ); - emitter.start(expressions); + emitter.start(ctx.expressions); } Op::ControlBarrier => { inst.expect(4)?; @@ -2945,14 +2769,14 @@ impl> Parser { let semantics_id = self.next()?; let exec_scope_const = self.lookup_constant.lookup(exec_scope_id)?; let semantics_const = self.lookup_constant.lookup(semantics_id)?; - let exec_scope = match const_arena[exec_scope_const.handle].inner { + let exec_scope = match ctx.const_arena[exec_scope_const.handle].inner { crate::ConstantInner::Scalar { value: crate::ScalarValue::Uint(raw), width: _, } => raw as u32, _ => return Err(Error::InvalidBarrierScope(exec_scope_id)), }; - let semantics = match const_arena[semantics_const.handle].inner { + let semantics = match ctx.const_arena[semantics_const.handle].inner { crate::ConstantInner::Scalar { value: crate::ScalarValue::Uint(raw), width: _, @@ -2982,15 +2806,15 @@ impl> Parser { } }; - block.extend(emitter.finish(expressions)); + block.extend(emitter.finish(ctx.expressions)); if let Some(stmt) = terminator { block.push(stmt, crate::Span::default()); } // Save this block fragment in `block_ctx.blocks`, and mark it to be // incorporated into the current body at `Statement` assembly time. - block_ctx.blocks.insert(block_id, block); - let body = &mut block_ctx.bodies[body_idx]; + ctx.blocks.insert(block_id, block); + let body = &mut ctx.bodies[body_idx]; body.data.push(BodyFragment::BlockId(block_id)); Ok(()) } From 4abf22c4d115b8ea354bae259706202824965cf9 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 14 Sep 2021 17:11:39 -0700 Subject: [PATCH 1340/2212] snapshot tests: Always write IR when requested, even if validation fails. --- tests/snapshots.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index f9376f31e..10ac867ed 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -101,9 +101,6 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { } else { naga::valid::Capabilities::empty() }; - let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities) - .validate(module) - .unwrap(); let dest = PathBuf::from(root).join(BASE_DIR_OUT); @@ -114,6 +111,14 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let string = ron::ser::to_string_pretty(module, config).unwrap(); fs::write(dest.join(format!("ir/{}.ron", name)), string).unwrap(); } + } + + let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities) + .validate(module) + .unwrap(); + + #[cfg(feature = "serialize")] + { if targets.contains(Targets::ANALYSIS) { let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); let string = ron::ser::to_string_pretty(&info, config).unwrap(); From 08c1a1e9a39a9a47dc2425705b5b3473b4c8dbbd Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 14 Sep 2021 19:06:13 -0700 Subject: [PATCH 1341/2212] [wgsl-in] Record identifier definitions as TypedExpression values. Both a `var` binding and a `let` binding of a pointer to a variable create entries in the `lookup_ident` tables whose expression is a `LocalVariable`. However, the `let` should be a pointer, whereas the `var` should be a reference. This patch changes the tables to hold `TypedExpression` values, thus preserving the distinction. --- src/front/wgsl/mod.rs | 100 ++++++++++++++++++++++++++---------------- 1 file changed, 63 insertions(+), 37 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f388a4bc8..69d29ef58 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -692,15 +692,15 @@ trait StringValueLookup<'a> { type Value; fn lookup(&self, key: &'a str, span: Span) -> Result>; } -impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle> { - type Value = Handle; +impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, TypedExpression> { + type Value = TypedExpression; fn lookup(&self, key: &'a str, span: Span) -> Result> { self.get(key).cloned().ok_or(Error::UnknownIdent(span, key)) } } struct StatementContext<'input, 'temp, 'out> { - lookup_ident: &'temp mut FastHashMap<&'input str, Handle>, + lookup_ident: &'temp mut FastHashMap<&'input str, TypedExpression>, typifier: &'temp mut super::Typifier, variables: &'out mut Arena, expressions: &'out mut Arena, @@ -758,7 +758,7 @@ struct SamplingContext { } struct ExpressionContext<'input, 'temp, 'out> { - lookup_ident: &'temp FastHashMap<&'input str, Handle>, + lookup_ident: &'temp FastHashMap<&'input str, TypedExpression>, typifier: &'temp mut super::Typifier, expressions: &'out mut Arena, types: &'out mut Arena, @@ -811,7 +811,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { image_name: &'a str, span: Span, ) -> Result> { - let image = self.lookup_ident.lookup(image_name, span.clone())?; + let image = self.lookup_ident.lookup(image_name, span.clone())?.handle; Ok(SamplingContext { image, arrayed: match *self.resolve_type(image)? { @@ -1567,7 +1567,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, coordinate, array_index, offset, @@ -1600,7 +1600,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, coordinate, array_index, offset, @@ -1633,7 +1633,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, coordinate, array_index, offset, @@ -1668,7 +1668,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, coordinate, array_index, offset, @@ -1701,7 +1701,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, coordinate, array_index, offset, @@ -1734,7 +1734,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, coordinate, array_index, offset, @@ -1746,7 +1746,10 @@ impl Parser { let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span.clone())?; + let image = ctx + .lookup_ident + .lookup(image_name, image_span.clone())? + .handle; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let (class, arrayed) = match *ctx.resolve_type(image)? { @@ -1779,7 +1782,7 @@ impl Parser { let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span)?; + let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle; let level = if lexer.skip(Token::Separator(',')) { let expr = self.parse_general_expression(lexer, ctx.reborrow())?; Some(expr) @@ -1796,7 +1799,7 @@ impl Parser { let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span)?; + let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle; lexer.close_arguments()?; crate::Expression::ImageQuery { image, @@ -1807,7 +1810,7 @@ impl Parser { let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span)?; + let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle; lexer.close_arguments()?; crate::Expression::ImageQuery { image, @@ -1818,7 +1821,7 @@ impl Parser { let _ = lexer.next(); lexer.open_arguments()?; let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span)?; + let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle; lexer.close_arguments()?; crate::Expression::ImageQuery { image, @@ -2074,18 +2077,15 @@ impl Parser { ) } (Token::Word(word), span) => { - if let Some(&handle) = ctx.lookup_ident.get(word) { + if let Some(definition) = ctx.lookup_ident.get(word) { let _ = lexer.next(); self.pop_scope(lexer); // Not all identifiers constitute references in WGSL. - let is_reference = match ctx.expressions[handle] { - // `let`-bound identifiers don't evaluate to references. But that - // means `let` declarations apply the Load Rule to their values, - // so we will never see a `LocalVariable` in `lookup_ident` for a - // `let` binding. Thus, a Naga `LocalVariable` always means a WGSL - // `var` binding. - crate::Expression::LocalVariable(_) => true, + let is_reference = match ctx.expressions[definition.handle] { + // `let`-bound identifiers don't evaluate to references: `let` + // declarations apply the Load Rule to their values. + crate::Expression::LocalVariable(_) => definition.is_reference, // Global variables in the `Handle` storage class do not evaluate // to references. crate::Expression::GlobalVariable(global) => { @@ -2095,7 +2095,7 @@ impl Parser { }; TypedExpression { - handle, + handle: definition.handle, is_reference, } } else if let Some(expr) = @@ -3183,7 +3183,13 @@ impl Parser { } } block.extend(emitter.finish(context.expressions)); - context.lookup_ident.insert(name, expr_id); + context.lookup_ident.insert( + name, + TypedExpression { + handle: expr_id, + is_reference: false, + }, + ); context .named_expressions .insert(expr_id, String::from(name)); @@ -3291,7 +3297,13 @@ impl Parser { let expr_id = context .expressions .append(crate::Expression::LocalVariable(var_id), Default::default()); - context.lookup_ident.insert(name, expr_id); + context.lookup_ident.insert( + name, + TypedExpression { + handle: expr_id, + is_reference: true, + }, + ); if let Init::Variable(value) = init { Some(crate::Statement::Store { @@ -3597,7 +3609,8 @@ impl Parser { let (image_name, image_span) = lexer.next_ident_with_span()?; let image = context .lookup_ident - .lookup(image_name, image_span.clone())?; + .lookup(image_name, image_span.clone())? + .handle; lexer.expect(Token::Separator(','))?; let mut expr_context = context.as_expression(block, &mut emitter); let arrayed = match *expr_context.resolve_type(image)? { @@ -3722,15 +3735,22 @@ impl Parser { // populate initial expressions let mut expressions = Arena::new(); for (&name, expression) in lookup_global_expression.iter() { - let span = match *expression { - crate::Expression::GlobalVariable(handle) => { - module.global_variables.get_span(handle) - } - crate::Expression::Constant(handle) => module.constants.get_span(handle), + let (span, is_reference) = match *expression { + crate::Expression::GlobalVariable(handle) => ( + module.global_variables.get_span(handle), + module.global_variables[handle].class != crate::StorageClass::Handle, + ), + crate::Expression::Constant(handle) => (module.constants.get_span(handle), false), _ => unreachable!(), }; - let expr_handle = expressions.append(expression.clone(), span); - lookup_ident.insert(name, expr_handle); + let expression = expressions.append(expression.clone(), span); + lookup_ident.insert( + name, + TypedExpression { + handle: expression, + is_reference, + }, + ); } // read parameter list let mut arguments = Vec::new(); @@ -3747,11 +3767,17 @@ impl Parser { let (param_name, param_name_span, param_type, _access) = self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; let param_index = arguments.len() as u32; - let expression_token = expressions.append( + let expression = expressions.append( crate::Expression::FunctionArgument(param_index), NagaSpan::from(param_name_span), ); - lookup_ident.insert(param_name, expression_token); + lookup_ident.insert( + param_name, + TypedExpression { + handle: expression, + is_reference: false, + }, + ); arguments.push(crate::FunctionArgument { name: Some(param_name.to_string()), ty: param_type, From d31121df77a4a2c960b8efcd2b877b6f9b0165c3 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 14 Sep 2021 19:59:59 -0700 Subject: [PATCH 1342/2212] [wgsl-in] Refuse to apply postfix expressions to WGSL pointers. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #1356. Output for the test case in that issue is now: error: the value indexed by a `[]` subscripting expression must not be a pointer ┌─ wgsl:5:14 │ 5 │ let a = *pv[3]; // Problematic line │ ^^ expression is a pointer Could not parse WGSL --- src/front/wgsl/mod.rs | 106 ++++++++++++++++++++++++++---------------- tests/wgsl-errors.rs | 47 ++++++++++++++++++- 2 files changed, 112 insertions(+), 41 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 69d29ef58..28f1e83b7 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -165,9 +165,9 @@ pub enum Error<'a> { MissingType(Span), InvalidAtomicPointer(Span), InvalidAtomicOperandType(Span), + Pointer(&'static str, Span), NotPointer(Span), - AddressOfNotReference(Span), - AssignmentNotReference(Span), + NotReference(&'static str, Span), Other, } @@ -419,14 +419,14 @@ impl<'a> Error<'a> { labels: vec![(span.clone(), "expression is not a pointer".into())], notes: vec![], }, - Error::AddressOfNotReference(ref span) => ParseError { - message: "the operand of the `&` operator must be a reference".to_string(), + Error::NotReference(what, ref span) => ParseError { + message: format!("{} must be a reference", what), labels: vec![(span.clone(), "expression is not a reference".into())], notes: vec![], }, - Error::AssignmentNotReference(ref span) => ParseError { - message: "the left-hand side of an assignment be a reference".to_string(), - labels: vec![(span.clone(), "expression is not a reference".into())], + Error::Pointer(what, ref span) => ParseError { + message: format!("{} must not be a pointer", what), + labels: vec![(span.clone(), "expression is a pointer".into())], notes: vec![], }, Error::Other => ParseError { @@ -2135,43 +2135,56 @@ impl Parser { mut handle, mut is_reference, } = expr; + let mut prefix_span = lexer.span_from(span_start); loop { + // Step lightly around `resolve_type`'s mutable borrow. + ctx.resolve_type(handle)?; + + // Find the type of the composite whose elements, components or members we're + // accessing, skipping through references: except for swizzles, the `Access` + // or `AccessIndex` expressions we'd generate are the same either way. + // + // Pointers, however, are not permitted. For error checks below, note whether + // the base expression is a WGSL pointer. + let temp_inner; + let (composite, wgsl_pointer) = match *ctx.typifier.get(handle, ctx.types) { + crate::TypeInner::Pointer { base, .. } => (&ctx.types[base].inner, !is_reference), + crate::TypeInner::ValuePointer { + size: None, + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Scalar { kind, width }; + (&temp_inner, !is_reference) + } + crate::TypeInner::ValuePointer { + size: Some(size), + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Vector { size, kind, width }; + (&temp_inner, !is_reference) + } + ref other => (other, false), + }; + let expression = match lexer.peek().0 { Token::Separator('.') => { let _ = lexer.next(); let (name, name_span) = lexer.next_ident_with_span()?; - // Step lightly around `resolve_type`'s mutable borrow. - ctx.resolve_type(handle)?; - - // Find the type of the composite whose components or members we're - // accessing, skipping through pointers: except for swizzles, the - // `Access` or `AccessIndex` expressions we'd generate are the same - // either way. - let temp_inner; - let composite = match *ctx.typifier.get(handle, ctx.types) { - crate::TypeInner::Pointer { base, .. } => &ctx.types[base].inner, - crate::TypeInner::ValuePointer { - size: None, - kind, - width, - .. - } => { - temp_inner = crate::TypeInner::Scalar { kind, width }; - &temp_inner - } - crate::TypeInner::ValuePointer { - size: Some(size), - kind, - width, - .. - } => { - temp_inner = crate::TypeInner::Vector { size, kind, width }; - &temp_inner - } - ref other => other, - }; + // WGSL doesn't allow accessing members on pointers, or swizzling + // them. But Naga IR doesn't distinguish pointers and references, so + // we must check here. + if wgsl_pointer { + return Err(Error::Pointer( + "the value accessed by a `.member` expression", + prefix_span, + )); + } let access = match *composite { crate::TypeInner::Struct { ref members, .. } => { @@ -2219,6 +2232,15 @@ impl Parser { let index = self.parse_general_expression(lexer, ctx.reborrow())?; let close_brace_span = lexer.expect_span(Token::Paren(']'))?; + // WGSL doesn't allow pointers to be subscripted. But Naga IR doesn't + // distinguish pointers and references, so we must check here. + if wgsl_pointer { + return Err(Error::Pointer( + "the value indexed by a `[]` subscripting expression", + prefix_span, + )); + } + if let crate::Expression::Constant(constant) = ctx.expressions[index] { let expr_span = open_brace_span.end..close_brace_span.start; @@ -2248,9 +2270,10 @@ impl Parser { _ => break, }; + prefix_span = lexer.span_from(span_start); handle = ctx .expressions - .append(expression, NagaSpan::from(lexer.span_from(span_start))); + .append(expression, NagaSpan::from(prefix_span.clone())); } Ok(TypedExpression { @@ -2327,7 +2350,7 @@ impl Parser { .get_span(operand.handle) .to_range() .unwrap_or_else(|| self.peek_scope(lexer)); - return Err(Error::AddressOfNotReference(span)); + return Err(Error::NotReference("the operand of the `&` operator", span)); } // No code is generated. We just declare the pointer a reference now. @@ -3065,7 +3088,10 @@ impl Parser { // The left hand side of an assignment must be a reference. if !reference.is_reference { let span = span_start..lexer.current_byte_offset(); - return Err(Error::AssignmentNotReference(span)); + return Err(Error::NotReference( + "the left-hand side of an assignment", + span, + )); } lexer.expect(Token::Operation('='))?; let value = self.parse_general_expression(lexer, context.reborrow())?; diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 0556cb824..44c5706e0 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -493,6 +493,44 @@ fn local_var_missing_type() { ); } +#[test] +fn postfix_pointers() { + check( + r#" + fn main() { + var v: vec4 = vec4(1.0, 1.0, 1.0, 1.0); + let pv = &v; + let a = *pv[3]; // Problematic line + } + "#, + r#"error: the value indexed by a `[]` subscripting expression must not be a pointer + ┌─ wgsl:5:26 + │ +5 │ let a = *pv[3]; // Problematic line + │ ^^ expression is a pointer + +"#, + ); + + check( + r#" + struct S { m: i32; }; + fn main() { + var s: S = S(42); + let ps = &s; + let a = *ps.m; // Problematic line + } + "#, + r#"error: the value accessed by a `.member` expression must not be a pointer + ┌─ wgsl:6:26 + │ +6 │ let a = *ps.m; // Problematic line + │ ^^ expression is a pointer + +"#, + ); +} + macro_rules! check_validation_error { // We want to support an optional guard expression after the pattern, so // that we can check values we can't match against, like strings. @@ -778,6 +816,13 @@ fn valid_access() { // `Access` to a `ValuePointer`. return temp[i][j]; } + ", + " + fn main() { + var v: vec4 = vec4(1.0, 1.0, 1.0, 1.0); + let pv = &v; + let a = (*pv)[3]; + } ": Ok(_) } @@ -789,7 +834,7 @@ fn invalid_local_vars() { " struct Unsized { data: array; }; fn local_ptr_dynamic_array(okay: ptr) { - var not_okay: ptr> = okay.data; + var not_okay: ptr> = &(*okay).data; } ": Err(naga::valid::ValidationError::Function { From e5ba11332ffc0ffcddbcdb327123b23c37c77f8a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 14 Sep 2021 17:04:16 -0700 Subject: [PATCH 1343/2212] Correctly recognize defined spans. Without this change, the `to_range` method method returns `None` even when spans are enabled. --- src/span.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/span.rs b/src/span.rs index 3421c35f0..2324b5b8b 100644 --- a/src/span.rs +++ b/src/span.rs @@ -54,7 +54,7 @@ impl Span { /// Check wether `self` was defined or is a default/unknown span fn is_defined(&self) -> bool { - *self == Self::default() + *self != Self::default() } } From 95d3a4e6992ae345802d1df1cecb676a9611711c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 15 Sep 2021 15:32:19 -0700 Subject: [PATCH 1344/2212] Enable span tracking by default in the Naga CLI. (#1364) --- cli/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 98f3eeabc..a60e8cd26 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -14,7 +14,7 @@ name = "naga" path = "src/main.rs" [dependencies] -naga = { path = "../", features = ["wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate"] } +naga = { path = "../", features = ["span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate"] } log = "0.4" codespan-reporting = "0.11" env_logger = "0.8" From 045ec6db32398119e5e418b28d7226ceb9201808 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 15 Sep 2021 15:34:42 -0700 Subject: [PATCH 1345/2212] [spv-out] Various doc fixes. --- src/back/spv/mod.rs | 79 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 65 insertions(+), 14 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 0c89821af..78d98e884 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -218,19 +218,47 @@ impl LocalImageType { /// A SPIR-V type constructed during code generation. /// -/// In the process of writing SPIR-V, we need to synthesize various types for -/// intermediate results and such. However, it's inconvenient to use -/// `crate::Type` or `crate::TypeInner` for these, as the IR module is immutable -/// so we can't ever create a `Handle` to refer to them. So for local use -/// in the SPIR-V writer, we have this home-grown type enum that covers only the -/// cases we need (for example, it doesn't cover structs). +/// This is the variant of [`LookupType`] used to represent types that might not +/// be available in the arena. Variants are present here for one of two reasons: /// -/// As explained in §2.8 of the SPIR-V spec, some classes of type instructions -/// must be unique; for example, you can't have two `OpTypeInt 32 1` -/// instructions in the same module. `Writer::lookup_type` maps each `LocalType` -/// value for which we've written instructions to its id, so we can avoid -/// writing out duplicates. `LocalType` also includes variants like `Pointer` -/// that do not need to be unique - but it is harmless to avoid the duplication. +/// - They represent types synthesized during code generation, as explained +/// in the documentation for [`LookupType`]. +/// +/// - They represent types for which SPIR-V forbids duplicate `OpType...` +/// instructions, requiring deduplication. +/// +/// This is not a complete copy of [`TypeInner`]: for example, SPIR-V generation +/// never synthesizes new struct types, so `LocalType` has nothing for that. +/// +/// Each `LocalType` variant should be handled identically to its analogous +/// `TypeInner` variant. You can use the [`make_local`] function to help with +/// this, by converting everything possible to a `LocalType` before inspecting +/// it. +/// +/// ## `Localtype` equality and SPIR-V `OpType` uniqueness +/// +/// The definition of `Eq` on `LocalType` is carefully chosen to help us follow +/// certain SPIR-V rules. SPIR-V §2.8 requires some classes of `OpType...` +/// instructions to be unique; for example, you can't have two `OpTypeInt 32 1` +/// instructions in the same module. All 32-bit signed integers must use the +/// same type id. +/// +/// All SPIR-V types that must be unique can be represented as a `LocalType`, +/// and two `LocalType`s are always `Eq` if SPIR-V would require them to use the +/// same `OpType...` instruction. This lets us avoid duplicates by recording the +/// ids of the type instructions we've already generated in a hash table, +/// [`Writer::lookup_type`], keyed by `LocalType`. +/// +/// As another example, [`LocalImageType`], stored in the `LocalType::Image` +/// variant, is designed to help us deduplicate `OpTypeImage` instructions. See +/// its documentation for details. +/// +/// `LocalType` also includes variants like `Pointer` that do not need to be +/// unique - but it is harmless to avoid the duplication. +/// +/// As it always must, the `Hash` implementation respects the `Eq` relation. +/// +/// [`TypeInner`]: crate::TypeInner #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LocalType { /// A scalar, vector, or pointer to one of those. @@ -259,6 +287,28 @@ enum LocalType { Sampler, } +/// A type encountered during SPIR-V generation. +/// +/// In the process of writing SPIR-V, we need to synthesize various types for +/// intermediate results and such: pointer types, vector/matrix component types, +/// or even booleans, which usually appear in SPIR-V code even when they're not +/// used by the module source. +/// +/// However, we can't use `crate::Type` or `crate::TypeInner` for these, as the +/// type arena may not contain what we need (it only contains types used +/// directly by other parts of the IR), and the IR module is immutable, so we +/// can't add anything to it. +/// +/// So for local use in the SPIR-V writer, we use this type, which holds either +/// a handle into the arena, or a [`LocalType`] containing something synthesized +/// locally. +/// +/// This is very similar to the [`proc::TypeResolution`] enum, with `LocalType` +/// playing the role of `TypeInner`. However, `LocalType` also has other +/// properties needed for SPIR-V generation; see the description of +/// [`LocalType`] for details. +/// +/// [`proc::TypeResolution`]: crate::proc::TypeResolution #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LookupType { Handle(Handle), @@ -511,8 +561,9 @@ bitflags::bitflags! { const DEBUG = 0x1; /// Flip Y coordinate of `BuiltIn::Position` output. const ADJUST_COORDINATE_SPACE = 0x2; - /// Emit `OpLabel` for input/output locations. - /// Some drivers treat it as semantic, not allowing any conflicts. + /// Emit `OpName` for input/output locations. + /// Contrary to spec, some drivers treat it as semantic, not allowing + /// any conflicts. const LABEL_VARYINGS = 0x4; } } From 5d3c93e8c776411406be72be08dd51d7ecef8b91 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 14 Sep 2021 14:40:57 -0700 Subject: [PATCH 1346/2212] [wgsl-out] Properly parenthesize address-of expressions. Fixes #1352. --- src/back/wgsl/writer.rs | 4 ++-- tests/out/wgsl/access.wgsl | 22 +++++++++++----------- tests/out/wgsl/globals.wgsl | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 07e4bed05..bed97fa7d 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1036,8 +1036,8 @@ impl Writer { let plain = plain_form_indirection(expr, module, func_ctx); let opened_paren = match (requested, plain) { (Indirection::Ordinary, Indirection::Reference) => { - write!(self.out, "&")?; - false + write!(self.out, "(&")?; + true } (Indirection::Reference, Indirection::Ordinary) => { write!(self.out, "(*")?; diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index a1b8faa2c..dd0d9b65e 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -19,7 +19,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let matrix: mat4x4 = bar.matrix; let arr: array,2> = bar.arr; let b: f32 = bar.matrix[3][0]; - let a: i32 = bar.data[(arrayLength(&bar.data) - 2u)]; + let a: i32 = bar.data[(arrayLength((&bar.data)) - 2u)]; bar.matrix[1][2] = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); @@ -33,23 +33,23 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { fn atomics() { var tmp: i32; - let value: i32 = atomicLoad(&bar.atom); - let _e6: i32 = atomicAdd(&bar.atom, 5); + let value: i32 = atomicLoad((&bar.atom)); + let _e6: i32 = atomicAdd((&bar.atom), 5); tmp = _e6; - let _e9: i32 = atomicSub(&bar.atom, 5); + let _e9: i32 = atomicSub((&bar.atom), 5); tmp = _e9; - let _e12: i32 = atomicAnd(&bar.atom, 5); + let _e12: i32 = atomicAnd((&bar.atom), 5); tmp = _e12; - let _e15: i32 = atomicOr(&bar.atom, 5); + let _e15: i32 = atomicOr((&bar.atom), 5); tmp = _e15; - let _e18: i32 = atomicXor(&bar.atom, 5); + let _e18: i32 = atomicXor((&bar.atom), 5); tmp = _e18; - let _e21: i32 = atomicMin(&bar.atom, 5); + let _e21: i32 = atomicMin((&bar.atom), 5); tmp = _e21; - let _e24: i32 = atomicMax(&bar.atom, 5); + let _e24: i32 = atomicMax((&bar.atom), 5); tmp = _e24; - let _e27: i32 = atomicExchange(&bar.atom, 5); + let _e27: i32 = atomicExchange((&bar.atom), 5); tmp = _e27; - atomicStore(&bar.atom, value); + atomicStore((&bar.atom), value); return; } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 21c506ce5..4eea757c9 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -6,6 +6,6 @@ var at: atomic; [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { wg[3] = 1.0; - atomicStore(&at, 2u); + atomicStore((&at), 2u); return; } From 52d74e91a4b062d317304250b5461890913d3bb8 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 15 Sep 2021 14:43:52 -0400 Subject: [PATCH 1347/2212] spv-out: option to emit PointSize --- src/back/spv/mod.rs | 3 + src/back/spv/writer.rs | 84 ++++++- tests/in/access.param.ron | 8 +- tests/in/boids.param.ron | 8 +- .../in/bounds-check-image-restrict.param.ron | 6 +- tests/in/bounds-check-image-rzsw.param.ron | 8 +- tests/in/bounds-check-zero.param.ron | 5 +- tests/in/collatz.param.ron | 6 +- tests/in/control-flow.param.ron | 1 - tests/in/empty.param.ron | 1 - tests/in/extra.param.ron | 4 +- tests/in/globals.param.ron | 1 - tests/in/image.param.ron | 6 +- tests/in/interface.param.ron | 11 +- tests/in/interpolate.param.ron | 11 +- tests/in/operators.param.ron | 1 - tests/in/pointer-access.param.ron | 8 +- tests/in/policy-mix.param.ron | 12 +- tests/in/quad.param.ron | 8 +- tests/in/shadow.param.ron | 8 +- tests/in/skybox.param.ron | 8 +- tests/in/standard.param.ron | 2 - tests/in/texture-arg.param.ron | 8 +- tests/out/spv/extra.spvasm | 2 +- tests/out/spv/globals.spvasm | 2 +- tests/out/spv/interface.vertex.spvasm | 34 +-- tests/out/spv/interpolate.spvasm | 228 +++++++++--------- tests/out/spv/operators.spvasm | 2 +- tests/out/spv/standard.spvasm | 2 +- tests/snapshots.rs | 55 +++-- 30 files changed, 331 insertions(+), 212 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 78d98e884..7acbd3b6d 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -565,6 +565,9 @@ bitflags::bitflags! { /// Contrary to spec, some drivers treat it as semantic, not allowing /// any conflicts. const LABEL_VARYINGS = 0x4; + /// Emit `PointSize` output builtin to vertex shaders, which is + /// required for drawing with `PointList` topology. + const FORCE_POINT_SIZE = 0x8; } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 2501c9125..4b83ff96d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -13,6 +13,11 @@ use crate::{ use spirv::Word; use std::collections::hash_map::Entry; +struct FunctionInterface<'a> { + varying_ids: &'a mut Vec, + stage: crate::ShaderStage, +} + impl Function { fn to_words(&self, sink: &mut impl Extend) { self.signature.as_ref().unwrap().to_words(sink); @@ -223,6 +228,35 @@ impl Writer { self.get_type_id(local_type.into()) } + pub(super) fn get_float_type_id(&mut self) -> Word { + let local_type = LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + }; + self.get_type_id(local_type.into()) + } + + pub(super) fn get_float_pointer_type_id(&mut self, class: spirv::StorageClass) -> Word { + let lookup_type = LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: Some(class), + }); + if let Some(&id) = self.lookup_type.get(&lookup_type) { + id + } else { + let id = self.id_gen.next(); + let ty_id = self.get_float_type_id(); + let instruction = Instruction::type_pointer(id, class, ty_id); + instruction.to_words(&mut self.logical_layout.declarations); + self.lookup_type.insert(lookup_type, id); + id + } + } + pub(super) fn get_bool_type_id(&mut self) -> Word { let local_type = LocalType::Value { vector_size: None, @@ -243,7 +277,7 @@ impl Writer { ir_function: &crate::Function, info: &FunctionInfo, ir_module: &crate::Module, - mut varying_ids: Option<&mut Vec>, + mut interface: Option, ) -> Result { let mut function = Function::default(); @@ -291,12 +325,13 @@ impl Writer { )?, false => self.get_type_id(LookupType::Handle(argument.ty)), }; - if let Some(ref mut list) = varying_ids { + + if let Some(ref mut iface) = interface { let id = if let Some(ref binding) = argument.binding { let name = argument.name.as_ref().map(AsRef::as_ref); let varying_id = self.write_varying(ir_module, class, name, argument.ty, binding)?; - list.push(varying_id); + iface.varying_ids.push(varying_id); let id = self.id_gen.next(); prelude .body @@ -313,7 +348,7 @@ impl Writer { let binding = member.binding.as_ref().unwrap(); let varying_id = self.write_varying(ir_module, class, name, member.ty, binding)?; - list.push(varying_id); + iface.varying_ids.push(varying_id); let id = self.id_gen.next(); prelude .body @@ -354,13 +389,16 @@ impl Writer { let return_type_id = match ir_function.result { Some(ref result) => { - if let Some(ref mut list) = varying_ids { + if let Some(ref mut iface) = interface { + let mut has_point_size = false; let class = spirv::StorageClass::Output; if let Some(ref binding) = result.binding { + has_point_size |= + *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); let type_id = self.get_type_id(LookupType::Handle(result.ty)); let varying_id = self.write_varying(ir_module, class, None, result.ty, binding)?; - list.push(varying_id); + iface.varying_ids.push(varying_id); ep_context.results.push(ResultMember { id: varying_id, type_id, @@ -373,9 +411,11 @@ impl Writer { let type_id = self.get_type_id(LookupType::Handle(member.ty)); let name = member.name.as_ref().map(AsRef::as_ref); let binding = member.binding.as_ref().unwrap(); + has_point_size |= + *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); let varying_id = self.write_varying(ir_module, class, name, member.ty, binding)?; - list.push(varying_id); + iface.varying_ids.push(varying_id); ep_context.results.push(ResultMember { id: varying_id, type_id, @@ -385,6 +425,29 @@ impl Writer { } else { unreachable!("Missing result binding on an entry point"); } + + if self.flags.contains(WriterFlags::FORCE_POINT_SIZE) + && iface.stage == crate::ShaderStage::Vertex + && !has_point_size + { + // add point size artificially + let varying_id = self.id_gen.next(); + let pointer_type_id = self.get_float_pointer_type_id(class); + Instruction::variable(pointer_type_id, varying_id, class, None) + .to_words(&mut self.logical_layout.declarations); + self.decorate( + varying_id, + spirv::Decoration::BuiltIn, + &[spirv::BuiltIn::PointSize as u32], + ); + iface.varying_ids.push(varying_id); + + let default_value_id = + self.get_constant_scalar(crate::ScalarValue::Float(1.0), 4); + prelude + .body + .push(Instruction::store(varying_id, default_value_id, None)); + } self.void_type } else { self.get_type_id(LookupType::Handle(result.ty)) @@ -413,7 +476,7 @@ impl Writer { function_type, )); - if varying_ids.is_some() { + if interface.is_some() { function.entry_point_context = Some(ep_context); } @@ -501,7 +564,10 @@ impl Writer { &entry_point.function, info, ir_module, - Some(&mut interface_ids), + Some(FunctionInterface { + varying_ids: &mut interface_ids, + stage: entry_point.stage, + }), )?; let exec_model = match entry_point.stage { diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 71227754b..4cff7e55c 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -1,7 +1,9 @@ ( - spv_version: (1, 1), - spv_debug: true, - spv_adjust_coordinate_space: false, + spv: ( + version: (1, 1), + debug: true, + adjust_coordinate_space: false, + ), msl_custom: true, msl: ( lang_version: (2, 0), diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index 8f304e5c2..e17036fc9 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -1,7 +1,9 @@ ( - spv_version: (1, 0), - spv_debug: true, - spv_adjust_coordinate_space: false, + spv: ( + version: (1, 0), + debug: true, + adjust_coordinate_space: false, + ), msl_custom: true, msl: ( lang_version: (2, 0), diff --git a/tests/in/bounds-check-image-restrict.param.ron b/tests/in/bounds-check-image-restrict.param.ron index 725c767df..2baa4fa0b 100644 --- a/tests/in/bounds-check-image-restrict.param.ron +++ b/tests/in/bounds-check-image-restrict.param.ron @@ -1,5 +1,7 @@ ( image_bounds_check_policy: Restrict, - spv_version: (1, 1), - spv_debug: true, + spv: ( + version: (1, 1), + debug: true, + ), ) diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/tests/in/bounds-check-image-rzsw.param.ron index 22e3d47b5..7bfacb741 100644 --- a/tests/in/bounds-check-image-rzsw.param.ron +++ b/tests/in/bounds-check-image-rzsw.param.ron @@ -1,5 +1,7 @@ ( - image_bounds_check_policy: ReadZeroSkipWrite, - spv_version: (1, 1), - spv_debug: true, + image_bounds_check_policy: ReadZeroSkipWrite, + spv: ( + version: (1, 1), + debug: true, + ), ) diff --git a/tests/in/bounds-check-zero.param.ron b/tests/in/bounds-check-zero.param.ron index 10f3305b4..5bb269c91 100644 --- a/tests/in/bounds-check-zero.param.ron +++ b/tests/in/bounds-check-zero.param.ron @@ -1,5 +1,4 @@ ( - index_bounds_check_policy: ReadZeroSkipWrite, - buffer_bounds_check_policy: ReadZeroSkipWrite, - spv_version: (1, 1), + index_bounds_check_policy: ReadZeroSkipWrite, + buffer_bounds_check_policy: ReadZeroSkipWrite, ) diff --git a/tests/in/collatz.param.ron b/tests/in/collatz.param.ron index 6da4b84fd..5b157849b 100644 --- a/tests/in/collatz.param.ron +++ b/tests/in/collatz.param.ron @@ -1,4 +1,6 @@ ( - spv_version: (1, 0), - spv_debug: true, + spv: ( + version: (1, 0), + debug: true, + ), ) diff --git a/tests/in/control-flow.param.ron b/tests/in/control-flow.param.ron index bd7d7cc3e..72873dd66 100644 --- a/tests/in/control-flow.param.ron +++ b/tests/in/control-flow.param.ron @@ -1,3 +1,2 @@ ( - spv_version: (1, 1), ) diff --git a/tests/in/empty.param.ron b/tests/in/empty.param.ron index bd7d7cc3e..72873dd66 100644 --- a/tests/in/empty.param.ron +++ b/tests/in/empty.param.ron @@ -1,3 +1,2 @@ ( - spv_version: (1, 1), ) diff --git a/tests/in/extra.param.ron b/tests/in/extra.param.ron index 653d7f035..e08588bfa 100644 --- a/tests/in/extra.param.ron +++ b/tests/in/extra.param.ron @@ -1,6 +1,8 @@ ( god_mode: true, - spv_version: (1, 0), + spv: ( + version: (1, 2), + ), msl_custom: true, msl: ( lang_version: (2, 2), diff --git a/tests/in/globals.param.ron b/tests/in/globals.param.ron index 8b306e5b7..72873dd66 100644 --- a/tests/in/globals.param.ron +++ b/tests/in/globals.param.ron @@ -1,3 +1,2 @@ ( - spv_version: (1, 0), ) diff --git a/tests/in/image.param.ron b/tests/in/image.param.ron index aca18ab38..91e6e8597 100644 --- a/tests/in/image.param.ron +++ b/tests/in/image.param.ron @@ -1,4 +1,6 @@ ( - spv_version: (1, 1), - spv_debug: true, + spv: ( + version: (1, 1), + debug: true, + ), ) diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index 1bad562f9..fdca2996b 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -1,8 +1,11 @@ ( - spv_version: (1, 0), - spv_capabilities: [ Shader, SampleRateShading ], - spv_adjust_coordinate_space: false, - spv_separate_entry_points: true, + spv: ( + version: (1, 0), + capabilities: [ Shader, SampleRateShading ], + adjust_coordinate_space: false, + force_point_size: true, + separate_entry_points: true, + ), hlsl_custom: true, hlsl: ( shader_model: V5_1, diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index 6a2a10266..8566e665c 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -1,8 +1,11 @@ ( - spv_version: (1, 0), - spv_capabilities: [ Shader, SampleRateShading ], - spv_debug: true, - spv_adjust_coordinate_space: true, + spv: ( + version: (1, 0), + capabilities: [ Shader, SampleRateShading ], + debug: true, + force_point_size: true, + adjust_coordinate_space: true, + ), glsl: ( version: Desktop(400), writer_flags: (bits: 0), diff --git a/tests/in/operators.param.ron b/tests/in/operators.param.ron index 8b306e5b7..72873dd66 100644 --- a/tests/in/operators.param.ron +++ b/tests/in/operators.param.ron @@ -1,3 +1,2 @@ ( - spv_version: (1, 0), ) diff --git a/tests/in/pointer-access.param.ron b/tests/in/pointer-access.param.ron index a049e71aa..4fc2cfe56 100644 --- a/tests/in/pointer-access.param.ron +++ b/tests/in/pointer-access.param.ron @@ -1,5 +1,7 @@ ( - spv_version: (1, 0), - spv_debug: true, - spv_adjust_coordinate_space: true, + spv: ( + version: (1, 0), + debug: true, + adjust_coordinate_space: true, + ), ) diff --git a/tests/in/policy-mix.param.ron b/tests/in/policy-mix.param.ron index e3f7a182c..1387e5f60 100644 --- a/tests/in/policy-mix.param.ron +++ b/tests/in/policy-mix.param.ron @@ -1,7 +1,9 @@ ( - index_bounds_check_policy: Restrict, - buffer_bounds_check_policy: Unchecked, - image_bounds_check_policy: ReadZeroSkipWrite, - spv_version: (1, 1), - spv_debug: true, + index_bounds_check_policy: Restrict, + buffer_bounds_check_policy: Unchecked, + image_bounds_check_policy: ReadZeroSkipWrite, + spv: ( + version: (1, 1), + debug: true, + ), ) diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index bb22a33e0..f346a2a67 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -1,7 +1,9 @@ ( - spv_version: (1, 0), - spv_debug: true, - spv_adjust_coordinate_space: true, + spv: ( + version: (1, 0), + debug: true, + adjust_coordinate_space: true, + ), glsl_custom: true, glsl: ( version: Embedded(300), diff --git a/tests/in/shadow.param.ron b/tests/in/shadow.param.ron index 63926c63c..e37f9108a 100644 --- a/tests/in/shadow.param.ron +++ b/tests/in/shadow.param.ron @@ -1,5 +1,7 @@ ( - spv_version: (1, 2), - spv_debug: true, - spv_adjust_coordinate_space: true, + spv: ( + version: (1, 2), + debug: true, + adjust_coordinate_space: true, + ), ) diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 951981e72..dad0ab483 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -1,8 +1,10 @@ ( spv_flow_dump_prefix: "", - spv_version: (1, 0), - spv_debug: false, - spv_adjust_coordinate_space: false, + spv: ( + version: (1, 0), + debug: false, + adjust_coordinate_space: false, + ), msl_custom: true, msl: ( lang_version: (2, 1), diff --git a/tests/in/standard.param.ron b/tests/in/standard.param.ron index d6d9d69be..72873dd66 100644 --- a/tests/in/standard.param.ron +++ b/tests/in/standard.param.ron @@ -1,4 +1,2 @@ ( - spv_version: (1, 0), - spv_adjust_coordinate_space: false, ) diff --git a/tests/in/texture-arg.param.ron b/tests/in/texture-arg.param.ron index a049e71aa..4fc2cfe56 100644 --- a/tests/in/texture-arg.param.ron +++ b/tests/in/texture-arg.param.ron @@ -1,5 +1,7 @@ ( - spv_version: (1, 0), - spv_debug: true, - spv_adjust_coordinate_space: true, + spv: ( + version: (1, 0), + debug: true, + adjust_coordinate_space: true, + ), ) diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index 1131df183..6f6f153a3 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -1,5 +1,5 @@ ; SPIR-V -; Version: 1.0 +; Version: 1.2 ; Generator: rspirv ; Bound: 44 OpCapability Shader diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 2e0bd6684..f44983e9b 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,5 +1,5 @@ ; SPIR-V -; Version: 1.0 +; Version: 1.1 ; Generator: rspirv ; Bound: 26 OpCapability Shader diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index 6604f4219..9910b2bc5 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -1,11 +1,11 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 39 +; Bound: 41 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %29 "vertex" %18 %21 %23 %25 %27 +OpEntryPoint Vertex %31 "vertex" %18 %21 %23 %25 %27 %29 OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpMemberDecorate %13 0 Offset 0 @@ -17,6 +17,7 @@ OpDecorate %21 BuiltIn InstanceIndex OpDecorate %23 Location 10 OpDecorate %25 BuiltIn Position OpDecorate %27 Location 1 +OpDecorate %29 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -40,22 +41,25 @@ OpDecorate %27 Location 1 %25 = OpVariable %26 Output %28 = OpTypePointer Output %4 %27 = OpVariable %28 Output -%30 = OpTypeFunction %2 -%29 = OpFunction %2 None %30 +%30 = OpTypePointer Output %4 +%29 = OpVariable %30 Output +%32 = OpTypeFunction %2 +%31 = OpFunction %2 None %32 %17 = OpLabel %20 = OpLoad %6 %18 %22 = OpLoad %6 %21 %24 = OpLoad %6 %23 -OpBranch %31 -%31 = OpLabel -%32 = OpIAdd %6 %20 %22 -%33 = OpIAdd %6 %32 %24 -%34 = OpCompositeConstruct %11 %3 %3 %3 %3 -%35 = OpConvertUToF %4 %33 -%36 = OpCompositeConstruct %12 %34 %35 -%37 = OpCompositeExtract %11 %36 0 -OpStore %25 %37 -%38 = OpCompositeExtract %4 %36 1 -OpStore %27 %38 +OpStore %29 %3 +OpBranch %33 +%33 = OpLabel +%34 = OpIAdd %6 %20 %22 +%35 = OpIAdd %6 %34 %24 +%36 = OpCompositeConstruct %11 %3 %3 %3 %3 +%37 = OpConvertUToF %4 %35 +%38 = OpCompositeConstruct %12 %36 %37 +%39 = OpCompositeExtract %11 %38 0 +OpStore %25 %39 +%40 = OpCompositeExtract %4 %38 1 +OpStore %27 %40 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interpolate.spvasm b/tests/out/spv/interpolate.spvasm index 019b9ae0e..fc888a7a1 100644 --- a/tests/out/spv/interpolate.spvasm +++ b/tests/out/spv/interpolate.spvasm @@ -1,14 +1,14 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 108 +; Bound: 110 OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %42 "main" %29 %31 %33 %35 %37 %39 %40 %41 -OpEntryPoint Fragment %106 "main" %85 %88 %91 %94 %97 %100 %102 %104 -OpExecutionMode %106 OriginUpperLeft +OpEntryPoint Vertex %45 "main" %29 %31 %33 %35 %37 %39 %40 %41 %42 +OpEntryPoint Fragment %108 "main" %87 %90 %93 %96 %99 %102 %104 %106 +OpExecutionMode %108 OriginUpperLeft OpSource GLSL 450 OpMemberName %25 0 "position" OpMemberName %25 1 "flat" @@ -28,16 +28,16 @@ OpName %37 "linear_sample" OpName %39 "perspective" OpName %40 "perspective_centroid" OpName %41 "perspective_sample" -OpName %42 "main" -OpName %85 "position" -OpName %88 "flat" -OpName %91 "linear" -OpName %94 "linear_centroid" -OpName %97 "linear_sample" -OpName %100 "perspective" -OpName %102 "perspective_centroid" -OpName %104 "perspective_sample" -OpName %106 "main" +OpName %45 "main" +OpName %87 "position" +OpName %90 "flat" +OpName %93 "linear" +OpName %96 "linear_centroid" +OpName %99 "linear_sample" +OpName %102 "perspective" +OpName %104 "perspective_centroid" +OpName %106 "perspective_sample" +OpName %108 "main" OpMemberDecorate %25 0 Offset 0 OpMemberDecorate %25 1 Offset 16 OpMemberDecorate %25 2 Offset 20 @@ -62,22 +62,23 @@ OpDecorate %40 Location 5 OpDecorate %40 Centroid OpDecorate %41 Location 6 OpDecorate %41 Sample -OpDecorate %85 BuiltIn FragCoord -OpDecorate %88 Location 0 -OpDecorate %88 Flat -OpDecorate %91 Location 1 -OpDecorate %91 NoPerspective -OpDecorate %94 Location 2 -OpDecorate %94 NoPerspective -OpDecorate %94 Centroid -OpDecorate %97 Location 3 -OpDecorate %97 NoPerspective -OpDecorate %97 Sample -OpDecorate %100 Location 4 -OpDecorate %102 Location 5 -OpDecorate %102 Centroid -OpDecorate %104 Location 6 -OpDecorate %104 Sample +OpDecorate %42 BuiltIn PointSize +OpDecorate %87 BuiltIn FragCoord +OpDecorate %90 Location 0 +OpDecorate %90 Flat +OpDecorate %93 Location 1 +OpDecorate %93 NoPerspective +OpDecorate %96 Location 2 +OpDecorate %96 NoPerspective +OpDecorate %96 Centroid +OpDecorate %99 Location 3 +OpDecorate %99 NoPerspective +OpDecorate %99 Sample +OpDecorate %102 Location 4 +OpDecorate %104 Location 5 +OpDecorate %104 Centroid +OpDecorate %106 Location 6 +OpDecorate %106 Sample %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 2.0 @@ -116,94 +117,97 @@ OpDecorate %104 Sample %39 = OpVariable %30 Output %40 = OpVariable %34 Output %41 = OpVariable %34 Output -%43 = OpTypeFunction %2 -%45 = OpTypePointer Function %22 -%47 = OpConstant %9 0 -%49 = OpTypePointer Function %9 -%50 = OpConstant %9 1 -%52 = OpTypePointer Function %4 -%53 = OpConstant %9 2 -%55 = OpTypePointer Function %23 -%57 = OpConstant %9 3 -%59 = OpTypePointer Function %24 -%61 = OpConstant %9 4 -%64 = OpConstant %9 5 -%66 = OpConstant %9 6 -%68 = OpConstant %9 7 -%73 = OpTypePointer Output %4 -%86 = OpTypePointer Input %22 -%85 = OpVariable %86 Input -%89 = OpTypePointer Input %9 -%88 = OpVariable %89 Input -%92 = OpTypePointer Input %4 -%91 = OpVariable %92 Input -%95 = OpTypePointer Input %23 -%94 = OpVariable %95 Input -%98 = OpTypePointer Input %24 -%97 = OpVariable %98 Input -%100 = OpVariable %86 Input -%102 = OpVariable %92 Input -%104 = OpVariable %92 Input -%42 = OpFunction %2 None %43 +%43 = OpTypePointer Output %4 +%42 = OpVariable %43 Output +%44 = OpConstant %4 1.0 +%46 = OpTypeFunction %2 +%48 = OpTypePointer Function %22 +%50 = OpConstant %9 0 +%52 = OpTypePointer Function %9 +%53 = OpConstant %9 1 +%55 = OpTypePointer Function %4 +%56 = OpConstant %9 2 +%58 = OpTypePointer Function %23 +%60 = OpConstant %9 3 +%62 = OpTypePointer Function %24 +%64 = OpConstant %9 4 +%67 = OpConstant %9 5 +%69 = OpConstant %9 6 +%71 = OpConstant %9 7 +%88 = OpTypePointer Input %22 +%87 = OpVariable %88 Input +%91 = OpTypePointer Input %9 +%90 = OpVariable %91 Input +%94 = OpTypePointer Input %4 +%93 = OpVariable %94 Input +%97 = OpTypePointer Input %23 +%96 = OpVariable %97 Input +%100 = OpTypePointer Input %24 +%99 = OpVariable %100 Input +%102 = OpVariable %88 Input +%104 = OpVariable %94 Input +%106 = OpVariable %94 Input +%45 = OpFunction %2 None %46 %28 = OpLabel %26 = OpVariable %27 Function -OpBranch %44 -%44 = OpLabel -%46 = OpCompositeConstruct %22 %3 %5 %6 %7 -%48 = OpAccessChain %45 %26 %47 -OpStore %48 %46 -%51 = OpAccessChain %49 %26 %50 -OpStore %51 %8 +OpStore %42 %44 +OpBranch %47 +%47 = OpLabel +%49 = OpCompositeConstruct %22 %3 %5 %6 %7 +%51 = OpAccessChain %48 %26 %50 +OpStore %51 %49 %54 = OpAccessChain %52 %26 %53 -OpStore %54 %10 -%56 = OpCompositeConstruct %23 %11 %12 -%58 = OpAccessChain %55 %26 %57 -OpStore %58 %56 -%60 = OpCompositeConstruct %24 %13 %14 %15 -%62 = OpAccessChain %59 %26 %61 -OpStore %62 %60 -%63 = OpCompositeConstruct %22 %16 %17 %18 %19 -%65 = OpAccessChain %45 %26 %64 +OpStore %54 %8 +%57 = OpAccessChain %55 %26 %56 +OpStore %57 %10 +%59 = OpCompositeConstruct %23 %11 %12 +%61 = OpAccessChain %58 %26 %60 +OpStore %61 %59 +%63 = OpCompositeConstruct %24 %13 %14 %15 +%65 = OpAccessChain %62 %26 %64 OpStore %65 %63 -%67 = OpAccessChain %52 %26 %66 -OpStore %67 %20 -%69 = OpAccessChain %52 %26 %68 -OpStore %69 %21 -%70 = OpLoad %25 %26 -%71 = OpCompositeExtract %22 %70 0 -OpStore %29 %71 -%72 = OpAccessChain %73 %29 %50 -%74 = OpLoad %4 %72 -%75 = OpFNegate %4 %74 -OpStore %72 %75 -%76 = OpCompositeExtract %9 %70 1 -OpStore %31 %76 -%77 = OpCompositeExtract %4 %70 2 -OpStore %33 %77 -%78 = OpCompositeExtract %23 %70 3 -OpStore %35 %78 -%79 = OpCompositeExtract %24 %70 4 -OpStore %37 %79 -%80 = OpCompositeExtract %22 %70 5 -OpStore %39 %80 -%81 = OpCompositeExtract %4 %70 6 -OpStore %40 %81 -%82 = OpCompositeExtract %4 %70 7 -OpStore %41 %82 +%66 = OpCompositeConstruct %22 %16 %17 %18 %19 +%68 = OpAccessChain %48 %26 %67 +OpStore %68 %66 +%70 = OpAccessChain %55 %26 %69 +OpStore %70 %20 +%72 = OpAccessChain %55 %26 %71 +OpStore %72 %21 +%73 = OpLoad %25 %26 +%74 = OpCompositeExtract %22 %73 0 +OpStore %29 %74 +%75 = OpAccessChain %43 %29 %53 +%76 = OpLoad %4 %75 +%77 = OpFNegate %4 %76 +OpStore %75 %77 +%78 = OpCompositeExtract %9 %73 1 +OpStore %31 %78 +%79 = OpCompositeExtract %4 %73 2 +OpStore %33 %79 +%80 = OpCompositeExtract %23 %73 3 +OpStore %35 %80 +%81 = OpCompositeExtract %24 %73 4 +OpStore %37 %81 +%82 = OpCompositeExtract %22 %73 5 +OpStore %39 %82 +%83 = OpCompositeExtract %4 %73 6 +OpStore %40 %83 +%84 = OpCompositeExtract %4 %73 7 +OpStore %41 %84 OpReturn OpFunctionEnd -%106 = OpFunction %2 None %43 -%83 = OpLabel -%87 = OpLoad %22 %85 -%90 = OpLoad %9 %88 -%93 = OpLoad %4 %91 -%96 = OpLoad %23 %94 -%99 = OpLoad %24 %97 -%101 = OpLoad %22 %100 -%103 = OpLoad %4 %102 +%108 = OpFunction %2 None %46 +%85 = OpLabel +%89 = OpLoad %22 %87 +%92 = OpLoad %9 %90 +%95 = OpLoad %4 %93 +%98 = OpLoad %23 %96 +%101 = OpLoad %24 %99 +%103 = OpLoad %22 %102 %105 = OpLoad %4 %104 -%84 = OpCompositeConstruct %25 %87 %90 %93 %96 %99 %101 %103 %105 -OpBranch %107 -%107 = OpLabel +%107 = OpLoad %4 %106 +%86 = OpCompositeConstruct %25 %89 %92 %95 %98 %101 %103 %105 %107 +OpBranch %109 +%109 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 7e36cb4ab..475241ab7 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,5 +1,5 @@ ; SPIR-V -; Version: 1.0 +; Version: 1.1 ; Generator: rspirv ; Bound: 101 OpCapability Shader diff --git a/tests/out/spv/standard.spvasm b/tests/out/spv/standard.spvasm index a8c5d0693..ef0bac6c9 100644 --- a/tests/out/spv/standard.spvasm +++ b/tests/out/spv/standard.spvasm @@ -1,5 +1,5 @@ ; SPIR-V -; Version: 1.0 +; Version: 1.1 ; Generator: rspirv ; Bound: 19 OpCapability Shader diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 10ac867ed..7a8873f37 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -40,6 +40,31 @@ impl From for naga::back::BoundsCheckPolicy { } } +#[cfg_attr(not(feature = "spv-out"), allow(dead_code))] +#[derive(serde::Deserialize)] +struct SpvOutVersion(u8, u8); +impl Default for SpvOutVersion { + fn default() -> Self { + SpvOutVersion(1, 1) + } +} + +#[cfg_attr(not(feature = "spv-out"), allow(dead_code))] +#[derive(Default, serde::Deserialize)] +struct SpirvOutParameters { + version: SpvOutVersion, + #[serde(default)] + capabilities: naga::FastHashSet, + #[serde(default)] + debug: bool, + #[serde(default)] + adjust_coordinate_space: bool, + #[serde(default)] + force_point_size: bool, + #[serde(default)] + separate_entry_points: bool, +} + #[derive(Default, serde::Deserialize)] struct Parameters { #[serde(default)] @@ -54,21 +79,9 @@ struct Parameters { #[allow(dead_code)] #[serde(default)] image_bounds_check_policy: BoundsCheckPolicyArg, - - #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] - spv_version: (u8, u8), #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] #[serde(default)] - spv_capabilities: naga::FastHashSet, - #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] - #[serde(default)] - spv_debug: bool, - #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] - #[serde(default)] - spv_adjust_coordinate_space: bool, - #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] - #[serde(default)] - spv_separate_entry_points: bool, + spv: SpirvOutParameters, #[cfg(all(feature = "deserialize", feature = "msl-out"))] #[serde(default)] msl: naga::back::msl::Options, @@ -179,18 +192,22 @@ fn write_output_spv( use rspirv::binary::Disassemble; let mut flags = spv::WriterFlags::LABEL_VARYINGS; - flags.set(spv::WriterFlags::DEBUG, params.spv_debug); + flags.set(spv::WriterFlags::DEBUG, params.spv.debug); flags.set( spv::WriterFlags::ADJUST_COORDINATE_SPACE, - params.spv_adjust_coordinate_space, + params.spv.adjust_coordinate_space, + ); + flags.set( + spv::WriterFlags::FORCE_POINT_SIZE, + params.spv.force_point_size, ); let options = spv::Options { - lang_version: params.spv_version, + lang_version: (params.spv.version.0, params.spv.version.1), flags, - capabilities: if params.spv_capabilities.is_empty() { + capabilities: if params.spv.capabilities.is_empty() { None } else { - Some(params.spv_capabilities.clone()) + Some(params.spv.capabilities.clone()) }, bounds_check_policies: naga::back::BoundsCheckPolicies { @@ -202,7 +219,7 @@ fn write_output_spv( ..spv::Options::default() }; - if params.spv_separate_entry_points { + if params.spv.separate_entry_points { for ep in module.entry_points.iter() { let pipeline_options = spv::PipelineOptions { entry_point: ep.name.clone(), From 636b8ed606a36f0b137b548d797dbbc7b581f368 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 2 Sep 2021 22:24:29 -0700 Subject: [PATCH 1348/2212] Document `AtomicResult` expressions. --- src/lib.rs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index b8190cf19..1ee273e58 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -87,9 +87,13 @@ Naga's rules for when `Expression`s are evaluated are as follows: a pointer. Such global variables hold opaque types like shaders or images, and cannot be assigned to. -- A [`Call`](Expression::CallResult) expression that is the `result` of a - [`Statement::Call`], representing the call's return value, is evaluated when - the `Call` statement is executed. +- A [`CallResult`] expression that is the `result` of a [`Statement::Call`], + representing the call's return value, is evaluated when the `Call` statement + is executed. + +- Similarly, an [`AtomicResult`] expression that is the `result` of an + [`Atomic`] statement, representing the result of the atomic operation, is + evaluated when the `Atomic` statement is executed. - All other expressions are evaluated when the (unique) [`Statement::Emit`] statement that covers them is executed. The [`Expression::needs_pre_emit`] @@ -142,15 +146,17 @@ An expression's scope is defined as follows: subsequent expressions in that `Emit`, the subsequent statements in the `Block` to which that `Emit` belongs (if any) and their sub-statements (if any). -- If a [`Call`] statement has a `result` expression, then that expression's - scope covers the subsequent statements in the `Block` to which that `Call` - belongs (if any) and their sub-statements (if any). +- The `result` expression of a [`Call`] or [`Atomic`] statement has a scope + covering the subsequent statements in the `Block` in which the statement + occurs (if any) and their sub-statements (if any). For example, this implies that an expression evaluated by some statement in a nested `Block` is not available in the `Block`'s parents. Such a value would need to be stored in a local variable to be carried upwards in the statement tree. +[`AtomicResult`]: Expression::AtomicResult +[`CallResult`]: Expression::CallResult [`Constant`]: Expression::Constant [`Derivative`]: Expression::Derivative [`FunctionArgument`]: Expression::FunctionArgument @@ -160,6 +166,7 @@ tree. [`Load`]: Expression::Load [`LocalVariable`]: Expression::LocalVariable +[`Atomic`]: Statement::Atomic [`Call`]: Statement::Call [`Emit`]: Statement::Emit [`Store`]: Statement::Store @@ -1388,7 +1395,9 @@ pub enum Statement { fun: AtomicFunction, /// Value to use in the function. value: Handle, - /// Emitted expression as a result. + /// [`AtomicResult`] expression representing this function's result. + /// + /// [`AtomicResult`]: crate::Expression::AtomicResult result: Handle, }, /// Calls a function. From 8aae069f22ac94ec46329a9adbfaf341cd3e7adf Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 7 Sep 2021 11:14:42 -0700 Subject: [PATCH 1349/2212] Document some Expression, EntryPoint, and Module rules. --- src/lib.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 1ee273e58..97af89d3f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1451,6 +1451,9 @@ pub struct Function { /// Local variables defined and used in the function. pub local_variables: Arena, /// Expressions used inside this function. + /// + /// An `Expression` must occur before all other `Expression`s that use its + /// value. pub expressions: Arena, /// Map of expressions that have associated variable names pub named_expressions: NamedExpressions, @@ -1503,6 +1506,8 @@ pub struct Function { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct EntryPoint { /// Name of this entry point, visible externally. + /// + /// Entry point names for a given `stage` must be distinct within a module. pub name: String, /// Shader stage. pub stage: ShaderStage, @@ -1536,6 +1541,9 @@ pub struct Module { /// Storage for the global variables defined in this module. pub global_variables: Arena, /// Storage for the functions defined in this module. + /// + /// Each function must appear in this arena strictly before all its callers. + /// Recursion is not supported. pub functions: Arena, /// Entry points. pub entry_points: Vec, From 60bd9ec88427d58eb7457d3bcf2997fc0ea3f29c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 16 Sep 2021 20:49:26 +0100 Subject: [PATCH 1350/2212] [glsl-in] Compile tests without codespan --- src/front/glsl/token.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 0980ed5fc..a2449e588 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -25,10 +25,13 @@ use std::ops::Range; /// /// ```rust /// # use naga::front::glsl::SourceMetadata; +/// # #[cfg(feature = "codespan_reporting")] +/// # { /// use codespan_reporting::diagnostic::Label; /// # let file = (); /// # let meta = SourceMetadata::default(); /// let label = Label::primary(file, meta); +/// # } /// ``` /// /// # Notes From a9d20d8ef4a03bf60402dec806b9949a733f11a7 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Wed, 15 Sep 2021 09:54:48 -0700 Subject: [PATCH 1351/2212] [glsl-in] Add support for a large number of texture sample overrides --- src/front/glsl/builtins.rs | 559 ++++++++++++++-------------- src/front/glsl/types.rs | 2 +- tests/in/glsl/samplers.frag | 222 +++++++++++- tests/out/wgsl/samplers-frag.wgsl | 583 +++++++++++++++++++++++++++++- 4 files changed, 1066 insertions(+), 300 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 17cd412d1..78b9877b5 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -39,6 +39,26 @@ impl Module { } } +fn make_coords_arg(number_of_components: usize, kind: Sk) -> TypeInner { + let width = 4; + + match number_of_components { + 1 => TypeInner::Scalar { + kind, + width, + }, + _ => TypeInner::Vector { + size: match number_of_components { + 2 => VectorSize::Bi, + 3 => VectorSize::Tri, + _ => VectorSize::Quad, + }, + kind, + width, + }, + } +} + /// Inject builtins into /// /// This is done to not add a large startup cost and not increase memory @@ -118,31 +138,79 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module )) } } - "texture" | "textureLod" => { + "texture" | "textureGrad" | "textureGradOffset" | "textureLod" | "textureLodOffset" | "textureOffset" + | "textureProj" | "textureProjGrad" | "textureProjGradOffset" | "textureProjLod" + | "textureProjLodOffset" | "textureProjOffset" => { // bits layout - // bits 0 trough 1 - dims + // bits 0 through 1 - dims // bit 2 - shadow // bit 3 - array - // bit 4 - !bias - // - // 0b11111 is the latest since there are not 3D arrayed shadowed - // textures and cube arrayed shadows textures always have a - // compare argument - for bits in 0..(0b100000) { + // bit 4 - extra variant + // bit 5 - bias + + for bits in 0..(0b1000000) { let dim = bits & 0b11; let shadow = bits & 0b100 == 0b100; let arrayed = bits & 0b1000 == 0b1000; - let bias = bits & 0b10000 == 0b00000; + let variant = bits & 0b10000 == 0b10000; + let bias = bits & 0b100000 == 0b100000; + let builtin = match name { - "texture" => MacroCall::Texture, - _ => MacroCall::TextureLod, + // texture(gsampler, gvec P, [float bias]); + "texture" => MacroCall::Texture { proj: false, offset: false, shadow, level_type: TextureLevelType::None, }, + // textureGrad(gsampler, gvec P, gvec dPdx, gvec dPdy); + "textureGrad" => MacroCall::Texture { proj: false, offset: false, shadow, level_type: TextureLevelType::Grad, }, + // textureGradOffset(gsampler, gvec P, gvec dPdx, gvec dPdy, ivec offset); + "textureGradOffset" => MacroCall::Texture { proj: false, offset: true, shadow, level_type: TextureLevelType::Grad, }, + // textureLod(gsampler, gvec P, float lod); + "textureLod" => MacroCall::Texture { proj: false, offset: false, shadow, level_type: TextureLevelType::Lod, }, + // textureLodOffset(gsampler, gvec P, float lod, ivec offset); + "textureLodOffset" => MacroCall::Texture { proj: false, offset: true, shadow, level_type: TextureLevelType::Lod, }, + // textureOffset(gsampler, gvec+1 P, ivec offset, [float bias]); + "textureOffset" => MacroCall::Texture { proj: false, offset: true, shadow, level_type: TextureLevelType::None, }, + // textureProj(gsampler, gvec+1 P, [float bias]); + "textureProj" => MacroCall::Texture { proj: true, offset: false, shadow, level_type: TextureLevelType::None, }, + // textureProjGrad(gsampler, gvec+1 P, gvec dPdx, gvec dPdy); + "textureProjGrad" => MacroCall::Texture { proj: true, offset: false, shadow, level_type: TextureLevelType::Grad, }, + // textureProjGradOffset(gsampler, gvec+1 P, gvec dPdx, gvec dPdy, ivec offset); + "textureProjGradOffset" => MacroCall::Texture { proj: true, offset: true, shadow, level_type: TextureLevelType::Grad, }, + // textureProjLod(gsampler, gvec+1 P, float lod); + "textureProjLod" => MacroCall::Texture { proj: true, offset: false, shadow, level_type: TextureLevelType::Lod, }, + // textureProjLodOffset(gsampler, gvec+1 P, gvec dPdx, gvec dPdy, ivec offset); + "textureProjLodOffset" => MacroCall::Texture { proj: true, offset: true, shadow, level_type: TextureLevelType::Lod, }, + // textureProjOffset(gsampler, gvec+1 P, ivec offset, [float bias]); + "textureProjOffset" => MacroCall::Texture { proj: true, offset: true, shadow, level_type: TextureLevelType::None, }, + _ => unreachable!(), }; - // Shadow, arrayed or both 3D images are not allowed - if (shadow || arrayed) && dim == 0b11 - || (builtin == MacroCall::TextureLod - && (dim != 0b00 && shadow && arrayed || dim == 0b10 && shadow || !bias)) - { + // Parse out the variant settings. + let proj = matches!(builtin, MacroCall::Texture { proj: true, .. }); + let grad = matches!(builtin, MacroCall::Texture { level_type: TextureLevelType::Grad, .. }); + let lod = matches!(builtin, MacroCall::Texture { level_type: TextureLevelType::Lod, .. }); + let offset = matches!(builtin, MacroCall::Texture { offset: true, .. }); + + let supports_variant = proj && !shadow; + if variant && !supports_variant { + continue; + } + + let supports_bias = matches!(builtin, MacroCall::Texture { level_type: TextureLevelType::None, .. }) && !shadow; + if bias && !supports_bias { + continue; + } + + // Proj doesn't work with arrayed, Cube or 3D samplers + if proj && (arrayed || dim == 0b10 || dim == 0b11) { + continue; + } + + // 3DArray and 3DShadow are not valid texture types + if dim == 0b11 && (arrayed || shadow) { + continue; + } + + // It seems that textureGradOffset(samplerCube) is not defined by GLSL for some reason... + if dim == 0b10 && grad && offset { continue; } @@ -165,184 +233,75 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module class, }; - let vector = match (dim, shadow) { - (0b00, false) => TypeInner::Scalar { - kind: Sk::Float, - width, - }, - (0b00, true) | (0b11, _) => TypeInner::Vector { - size: VectorSize::Tri, - kind: Sk::Float, - width, - }, - (_, _) => { - let size = match dim + arrayed as u32 + shadow as u32 { - 1 => VectorSize::Bi, - 2 => VectorSize::Tri, - _ => VectorSize::Quad, - }; + let num_coords_from_dim = (dim + 1).min(3); + let mut num_coords = num_coords_from_dim; - TypeInner::Vector { - size, + if shadow && proj { + num_coords = 4; + } else if shadow { + num_coords += 1; + } else if proj { + if variant && num_coords == 4 { + // Normal form already has 4 components, no need to have a variant form. + continue; + } else if variant { + num_coords = 4; + } else { + num_coords += 1; + } + } + + num_coords += arrayed as usize; + + // Special case: texture(gsamplerCubeArrayShadow) kicks the shadow compare ref to a separate argument, + // since it would otherwise take five arguments. It also can't take a bias, nor can it be proj/grad/lod/offset + // (presumably because nobody asked for it, and implementation complexity?) + if num_coords >= 5 { + if lod || grad || offset || proj || bias { + continue; + } + debug_assert!(dim == 0b10 && shadow && arrayed); + } + debug_assert!(num_coords <= 5); + + let vector = make_coords_arg(num_coords, Sk::Float); + let mut args = vec![image, vector]; + + if num_coords == 5 { + args.push(TypeInner::Scalar { + kind: Sk::Float, + width, + }); + } + + match builtin { + MacroCall::Texture { level_type: TextureLevelType::Lod, .. } => { + args.push(TypeInner::Scalar { kind: Sk::Float, width, - } - } + }); + }, + MacroCall::Texture { level_type: TextureLevelType::Grad, .. } => { + args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); + args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); + }, + _ => {}, }; - let mut args = vec![image, vector]; + if offset { + args.push(make_coords_arg(num_coords_from_dim, Sk::Sint)); + } if bias { args.push(TypeInner::Scalar { kind: Sk::Float, width, - }) + }); } declaration .overloads - .push(module.add_builtin(args, builtin)) - } - } - "textureProj" => { - // bits layout - // bit 0 - shadow - // bit 1 - bias - // bits 2 trough 3 - dims - // - // 0b0111 is the latest since there are only 1D and 2D shadow - // variants - for bits in 0..(0b1000) { - let dim = bits >> 2; - let shadow = bits & 0b1 == 0b1; - let bias = bits & 0b10 == 0b10; - - let class = match shadow { - true => ImageClass::Depth { multi: false }, - false => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, - }; - - let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, - _ => Dim::Cube, - }, - arrayed: false, - class, - }; - - let vector = TypeInner::Vector { - size: VectorSize::Quad, - kind: Sk::Float, - width, - }; - - let mut args = vec![image, vector]; - - if bias { - args.push(TypeInner::Scalar { - kind: Sk::Float, - width, - }) - } - - declaration - .overloads - .push(module.add_builtin(args, MacroCall::TextureProj)) - } - } - "textureGrad" => { - // bits layout - // bits 0 trough 1 - dims - // bit 2 - shadow - // bit 3 - array - // - // 0b1010 is the latest since there are no 3D arrayed shadowed - // textures and cube arrayed shadows textures are not allowed - for bits in 0..(0b1011) { - let dim = bits & 0b11; - let shadow = bits & 0b100 == 0b100; - let arrayed = bits & 0b1000 == 0b1000; - - // Shadow, arrayed or both 3D images are not allowed - if shadow && dim == 0b11 - // samplerCubeArrayShadow is not allowed - || shadow && arrayed && dim == 0b10 - { - continue; - } - - let class = match shadow { - true => ImageClass::Depth { multi: false }, - false => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, - }; - - let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, - 0b10 => Dim::Cube, - _ => Dim::D3, - }, - arrayed, - class, - }; - - let vector = match (dim, shadow) { - (0b00, false) => TypeInner::Scalar { - kind: Sk::Float, - width, - }, - (0b00, true) | (0b11, _) => TypeInner::Vector { - size: VectorSize::Tri, - kind: Sk::Float, - width, - }, - (_, _) => { - let size = match dim + arrayed as u32 + shadow as u32 { - 1 => VectorSize::Bi, - 2 => VectorSize::Tri, - _ => VectorSize::Quad, - }; - - TypeInner::Vector { - size, - kind: Sk::Float, - width, - } - } - }; - - let size = match dim { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - _ => Some(VectorSize::Tri), - }; - - let ty = || match size { - None => TypeInner::Scalar { - kind: Sk::Float, - width, - }, - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width, - }, - }; - - let args = vec![image, vector, ty(), ty()]; - - declaration - .overloads - .push(module.add_builtin(args, MacroCall::TextureGrad(shadow))) + .push(module.add_builtin(args, builtin)); } } "textureSize" => { @@ -1384,15 +1343,20 @@ fn inject_common_builtin( } } +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum TextureLevelType { None, Lod, Grad } + /// A compiler defined builtin function -#[derive(Clone, Copy, PartialEq)] +#[derive(Clone, Copy, PartialEq, Debug)] pub enum MacroCall { Sampler, SamplerShadow, - Texture, - TextureLod, - TextureProj, - TextureGrad(bool), + Texture { + proj: bool, + offset: bool, + shadow: bool, + level_type: TextureLevelType, + }, TextureSize, TexelFetch, MathFunction(MathFunction), @@ -1429,88 +1393,122 @@ impl MacroCall { ctx.samplers.insert(args[0], args[1]); Ok(args[0]) } - MacroCall::Texture | MacroCall::TextureLod => { - let comps = parser.coordinate_components(ctx, args[0], args[1], meta, body)?; - let level = match *self { - MacroCall::Texture => args - .get(2) - .copied() - .map_or(SampleLevel::Auto, SampleLevel::Bias), - MacroCall::TextureLod => SampleLevel::Exact(args[2]), - _ => unreachable!(), - }; - texture_call(ctx, args[0], level, comps, body, meta) - } - MacroCall::TextureGrad(shadow) => { - let comps = parser.coordinate_components(ctx, args[0], args[1], meta, body)?; - let level = match shadow { - true => { - log::debug!( - "Assuming gradients {:?} and {:?} are not greater than 1", - args[2], - args[3] - ); - SampleLevel::Zero - } - false => SampleLevel::Gradient { - x: args[2], - y: args[3], - }, - }; - texture_call(ctx, args[0], level, comps, body, meta) - } - MacroCall::TextureProj => { - let level = args - .get(2) - .copied() - .map_or(SampleLevel::Auto, SampleLevel::Bias); - let size = match *parser.resolve_type(ctx, args[1], meta)? { - TypeInner::Vector { size, .. } => size, - _ => { - return Err(Error { - kind: ErrorKind::SemanticError("Bad call to textureProj".into()), - meta, - }) - } - }; - let base = args[1]; - let mut right = ctx.add_expression( - Expression::AccessIndex { - base, - index: size as u32 - 1, - }, - SourceMetadata::none(), - body, - ); - let left = if let VectorSize::Bi = size { - ctx.add_expression( - Expression::AccessIndex { base, index: 0 }, - SourceMetadata::none(), - body, - ) - } else { - let size = match size { - VectorSize::Tri => VectorSize::Bi, - _ => VectorSize::Tri, + MacroCall::Texture { proj, offset, shadow, level_type } => { + let mut coords = args[1]; + + if proj { + let size = match *parser.resolve_type(ctx, coords, meta)? { + TypeInner::Vector { size, .. } => size, + _ => unreachable!(), }; - right = ctx.add_expression( - Expression::Splat { size, value: right }, + let mut right = ctx.add_expression( + Expression::AccessIndex { + base: coords, + index: size as u32 - 1, + }, SourceMetadata::none(), body, ); - ctx.vector_resize(size, base, SourceMetadata::none(), body) + let left = if let VectorSize::Bi = size { + ctx.add_expression( + Expression::AccessIndex { base: coords, index: 0 }, + SourceMetadata::none(), + body, + ) + } else { + let size = match size { + VectorSize::Tri => VectorSize::Bi, + _ => VectorSize::Tri, + }; + right = ctx.add_expression( + Expression::Splat { size, value: right }, + SourceMetadata::none(), + body, + ); + ctx.vector_resize(size, coords, SourceMetadata::none(), body) + }; + coords = ctx.add_expression( + Expression::Binary { + op: BinaryOperator::Divide, + left, + right, + }, + SourceMetadata::none(), + body, + ); + } + + let extra = args.get(2).copied(); + let comps = parser.coordinate_components(ctx, args[0], coords, extra, meta, body)?; + + let mut num_args = 2; + + if comps.used_extra { + num_args += 1; }; - let coords = ctx.add_expression( - Expression::Binary { - op: BinaryOperator::Divide, - left, - right, - }, - SourceMetadata::none(), - body, - ); - let comps = parser.coordinate_components(ctx, args[0], coords, meta, body)?; - texture_call(ctx, args[0], level, comps, body, meta) + + // Parse out explicit texture level. + let mut level = match level_type { + TextureLevelType::None => SampleLevel::Auto, + + TextureLevelType::Lod => { + num_args += 1; + + if shadow { + log::warn!( + "Assuming LOD {:?} is zero", + args[2], + ); + + SampleLevel::Zero + } else { + SampleLevel::Exact(args[2]) + } + } + + TextureLevelType::Grad => { + num_args += 2; + + if shadow { + log::warn!( + "Assuming gradients {:?} and {:?} are not greater than 1", + args[2], + args[3], + ); + SampleLevel::Zero + } else { + SampleLevel::Gradient { + x: args[2], + y: args[3], + } + } + } + }; + + let texture_offset = match offset { + true => { + let offset_arg = args[num_args]; + num_args += 1; + match parser.solve_constant(ctx, offset_arg, meta) { + Ok(v) => Some(v), + Err(e) => { + parser.errors.push(e); + None + }, + } + } + false => None + }; + + // Now go back and look for optional bias arg (if available) + if let TextureLevelType::None = level_type { + level = args + .get(num_args) + .copied() + .map_or(SampleLevel::Auto, SampleLevel::Bias); + } + + texture_call(ctx, args[0], level, comps, texture_offset, body, meta) } MacroCall::TextureSize => Ok(ctx.add_expression( Expression::ImageQuery { @@ -1523,7 +1521,7 @@ impl MacroCall { body, )), MacroCall::TexelFetch => { - let comps = parser.coordinate_components(ctx, args[0], args[1], meta, body)?; + let comps = parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; Ok(ctx.add_expression( Expression::ImageLoad { image: args[0], @@ -1666,6 +1664,7 @@ fn texture_call( image: Handle, level: SampleLevel, comps: CoordComponents, + offset: Option>, body: &mut Block, meta: SourceMetadata, ) -> Result> { @@ -1682,7 +1681,7 @@ fn texture_call( sampler, coordinate: comps.coordinate, array_index, - offset: None, + offset, level, depth_ref: comps.depth_ref, }, @@ -1700,10 +1699,12 @@ fn texture_call( /// Helper struct for texture calls with the separate components from the vector argument /// /// Obtained by calling [`coordinate_components`](Parser::coordinate_components) +#[derive(Debug)] struct CoordComponents { coordinate: Handle, depth_ref: Option>, array_index: Option>, + used_extra: bool, } impl Parser { @@ -1713,6 +1714,7 @@ impl Parser { ctx: &mut Context, image: Handle, coord: Handle, + extra: Option>, meta: SourceMetadata, body: &mut Block, ) -> Result { @@ -1751,12 +1753,13 @@ impl Parser { ), _ => coord, }; + + let mut coord_index = image_size.map_or(0, |s| s as u32); + let array_index = match arrayed { true => { - let index = match shadow { - true => image_size.map_or(0, |s| s as u32 - 1), - false => image_size.map_or(0, |s| s as u32), - }; + let index = coord_index; + coord_index += 1; Some(ctx.add_expression( Expression::AccessIndex { base: coord, index }, @@ -1766,15 +1769,21 @@ impl Parser { } _ => None, }; + let mut used_extra = false; let depth_ref = match shadow { true => { - let index = image_size.map_or(0, |s| s as u32); + let index = coord_index; - Some(ctx.add_expression( - Expression::AccessIndex { base: coord, index }, - SourceMetadata::none(), - body, - )) + if index == 4 { + used_extra = true; + extra + } else { + Some(ctx.add_expression( + Expression::AccessIndex { base: coord, index }, + SourceMetadata::none(), + body, + )) + } } false => None, }; @@ -1783,6 +1792,7 @@ impl Parser { coordinate, depth_ref, array_index, + used_extra, }) } else { self.errors.push(Error { @@ -1794,6 +1804,7 @@ impl Parser { coordinate: coord, depth_ref: None, array_index: None, + used_extra: false, }) } } diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 4151c6855..de26a8b32 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -138,7 +138,7 @@ pub fn parse_type(type_name: &str) -> Option { "2DMSArray" => (ImageDimension::D2, true, sampled(true)), "3D" => (ImageDimension::D3, false, sampled(false)), "Cube" => (ImageDimension::Cube, false, sampled(false)), - "CubeArray" => (ImageDimension::D2, true, sampled(false)), + "CubeArray" => (ImageDimension::Cube, true, sampled(false)), _ => return None, }; diff --git a/tests/in/glsl/samplers.frag b/tests/in/glsl/samplers.frag index 0bd849d5b..c3f6484c2 100644 --- a/tests/in/glsl/samplers.frag +++ b/tests/in/glsl/samplers.frag @@ -1,12 +1,224 @@ #version 440 core precision mediump float; -layout(set = 1, binding = 0) uniform texture2DArray tex; -layout(set = 1, binding = 1) uniform sampler samp; +layout(set = 1, binding = 0) uniform texture1D tex1D; +layout(set = 1, binding = 1) uniform texture1DArray tex1DArray; +layout(set = 1, binding = 2) uniform texture2D tex2D; +layout(set = 1, binding = 3) uniform texture2DArray tex2DArray; +layout(set = 1, binding = 4) uniform textureCube texCube; +layout(set = 1, binding = 5) uniform textureCubeArray texCubeArray; +layout(set = 1, binding = 6) uniform texture3D tex3D; +layout(set = 1, binding = 7) uniform sampler samp; -layout(location = 0) in vec2 v_TexCoord; -layout(location = 0) out vec4 o_color; +// WGSL doesn't have 1D depth samplers. +#define HAS_1D_DEPTH_TEXTURES 0 + +#if HAS_1D_DEPTH_TEXTURES +layout(set = 1, binding = 10) uniform texture1D tex1DShadow; +layout(set = 1, binding = 11) uniform texture1DArray tex1DArrayShadow; +#endif + +layout(set = 1, binding = 12) uniform texture2D tex2DShadow; +layout(set = 1, binding = 13) uniform texture2DArray tex2DArrayShadow; +layout(set = 1, binding = 14) uniform textureCube texCubeShadow; +layout(set = 1, binding = 15) uniform textureCubeArray texCubeArrayShadow; +layout(set = 1, binding = 16) uniform texture3D tex3DShadow; +layout(set = 1, binding = 17) uniform samplerShadow sampShadow; + +// Conventions for readability: +// 1.0 = Shadow Ref +// 2.0 = LOD Bias +// 3.0 = Explicit LOD +// 4.0 = Grad Derivatives +// 5 = Offset +// 6.0 = Proj W + +void testTex1D(in float coord) { + vec4 c; + c = texture(sampler1D(tex1D, samp), coord); + c = texture(sampler1D(tex1D, samp), coord, 2.0); + c = textureGrad(sampler1D(tex1D, samp), coord, 4.0, 4.0); + c = textureGradOffset(sampler1D(tex1D, samp), coord, 4.0, 4.0, 5); + c = textureLod(sampler1D(tex1D, samp), coord, 3.0); + c = textureLodOffset(sampler1D(tex1D, samp), coord, 3.0, 5); + c = textureOffset(sampler1D(tex1D, samp), coord, 5); + c = textureOffset(sampler1D(tex1D, samp), coord, 5, 2.0); + c = textureProj(sampler1D(tex1D, samp), vec2(coord, 6.0)); + c = textureProj(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0)); + c = textureProj(sampler1D(tex1D, samp), vec2(coord, 6.0), 2.0); + c = textureProj(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 2.0); + c = textureProjGrad(sampler1D(tex1D, samp), vec2(coord, 6.0), 4.0, 4.0); + c = textureProjGrad(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 4.0, 4.0); + c = textureProjGradOffset(sampler1D(tex1D, samp), vec2(coord, 6.0), 4.0, 4.0, 5); + c = textureProjGradOffset(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 4.0, 4.0, 5); + c = textureProjLod(sampler1D(tex1D, samp), vec2(coord, 6.0), 3.0); + c = textureProjLod(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 3.0); + c = textureProjLodOffset(sampler1D(tex1D, samp), vec2(coord, 6.0), 3.0, 5); + c = textureProjLodOffset(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 3.0, 5); + c = textureProjOffset(sampler1D(tex1D, samp), vec2(coord, 6.0), 5); + c = textureProjOffset(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 5); + c = textureProjOffset(sampler1D(tex1D, samp), vec2(coord, 6.0), 5, 2.0); + c = textureProjOffset(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 5, 2.0); +} + +#if HAS_1D_DEPTH_TEXTURES +void testTex1DShadow(float coord) { + float d; + d = texture(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0)); + d = textureGrad(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 4.0, 4.0); + d = textureGradOffset(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 4.0, 4.0, 5); + d = textureLod(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 3.0); + d = textureLodOffset(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 3.0, 5); + d = textureOffset(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 5); + d = textureProj(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0)); + d = textureProjGrad(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 4.0, 4.0); + d = textureProjGradOffset(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 4.0, 4.0, 5); + d = textureProjLod(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 3.0); + d = textureProjLodOffset(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 3.0, 5); + d = textureProjOffset(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 5); +} +#endif + +void testTex1DArray(in vec2 coord) { + vec4 c; + c = texture(sampler1DArray(tex1DArray, samp), coord); + c = texture(sampler1DArray(tex1DArray, samp), coord, 2.0); + c = textureGrad(sampler1DArray(tex1DArray, samp), coord, 4.0, 4.0); + c = textureGradOffset(sampler1DArray(tex1DArray, samp), coord, 4.0, 4.0, 5); + c = textureLod(sampler1DArray(tex1DArray, samp), coord, 3.0); + c = textureLodOffset(sampler1DArray(tex1DArray, samp), coord, 3.0, 5); + c = textureOffset(sampler1DArray(tex1DArray, samp), coord, 5); + c = textureOffset(sampler1DArray(tex1DArray, samp), coord, 5, 2.0); +} + +#if HAS_1D_DEPTH_TEXTURES +void testTex1DArrayShadow(in vec2 coord) { + float d; + d = texture(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0)); + d = textureGrad(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 4.0, 4.0); + d = textureGradOffset(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 4.0, 4.0, 5); + d = textureLod(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 3.0); + d = textureLodOffset(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 3.0, 5); + d = textureOffset(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 5); +} +#endif + +void testTex2D(in vec2 coord) { + vec4 c; + c = texture(sampler2D(tex2D, samp), coord); + c = texture(sampler2D(tex2D, samp), coord, 2.0); + c = textureGrad(sampler2D(tex2D, samp), coord, vec2(4.0), vec2(4.0)); + c = textureGradOffset(sampler2D(tex2D, samp), coord, vec2(4.0), vec2(4.0), ivec2(5)); + c = textureLod(sampler2D(tex2D, samp), coord, 3.0); + c = textureLodOffset(sampler2D(tex2D, samp), coord, 3.0, ivec2(5)); + c = textureOffset(sampler2D(tex2D, samp), coord, ivec2(5)); + c = textureOffset(sampler2D(tex2D, samp), coord, ivec2(5), 2.0); + c = textureProj(sampler2D(tex2D, samp), vec3(coord, 6.0)); + c = textureProj(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0)); + c = textureProj(sampler2D(tex2D, samp), vec3(coord, 6.0), 2.0); + c = textureProj(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), 2.0); + c = textureProjGrad(sampler2D(tex2D, samp), vec3(coord, 6.0), vec2(4.0), vec2(4.0)); + c = textureProjGrad(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), vec2(4.0), vec2(4.0)); + c = textureProjGradOffset(sampler2D(tex2D, samp), vec3(coord, 6.0), vec2(4.0), vec2(4.0), ivec2(5)); + c = textureProjGradOffset(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), vec2(4.0), vec2(4.0), ivec2(5)); + c = textureProjLod(sampler2D(tex2D, samp), vec3(coord, 6.0), 3.0); + c = textureProjLod(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), 3.0); + c = textureProjLodOffset(sampler2D(tex2D, samp), vec3(coord, 6.0), 3.0, ivec2(5)); + c = textureProjLodOffset(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), 3.0, ivec2(5)); + c = textureProjOffset(sampler2D(tex2D, samp), vec3(coord, 6.0), ivec2(5)); + c = textureProjOffset(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), ivec2(5)); + c = textureProjOffset(sampler2D(tex2D, samp), vec3(coord, 6.0), ivec2(5), 2.0); + c = textureProjOffset(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), ivec2(5), 2.0); +} + +void testTex2DShadow(vec2 coord) { + float d; + d = texture(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0)); + d = textureGrad(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), vec2(4.0), vec2(4.0)); + d = textureGradOffset(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), vec2(4.0), vec2(4.0), ivec2(5)); + d = textureLod(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), 3.0); + d = textureLodOffset(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), 3.0, ivec2(5)); + d = textureOffset(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), ivec2(5)); + d = textureProj(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0)); + d = textureProjGrad(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), vec2(4.0), vec2(4.0)); + d = textureProjGradOffset(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), vec2(4.0), vec2(4.0), ivec2(5)); + d = textureProjLod(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), 3.0); + d = textureProjLodOffset(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), 3.0, ivec2(5)); + d = textureProjOffset(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), ivec2(5)); +} + +void testTex2DArray(in vec3 coord) { + vec4 c; + c = texture(sampler2DArray(tex2DArray, samp), coord); + c = texture(sampler2DArray(tex2DArray, samp), coord, 2.0); + c = textureGrad(sampler2DArray(tex2DArray, samp), coord, vec2(4.0), vec2(4.0)); + c = textureGradOffset(sampler2DArray(tex2DArray, samp), coord, vec2(4.0), vec2(4.0), ivec2(5)); + c = textureLod(sampler2DArray(tex2DArray, samp), coord, 3.0); + c = textureLodOffset(sampler2DArray(tex2DArray, samp), coord, 3.0, ivec2(5)); + c = textureOffset(sampler2DArray(tex2DArray, samp), coord, ivec2(5)); + c = textureOffset(sampler2DArray(tex2DArray, samp), coord, ivec2(5), 2.0); +} + +void testTex2DArrayShadow(in vec3 coord) { + float d; + d = texture(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0)); + d = textureGrad(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), vec2(4.0), vec2(4.0)); + d = textureGradOffset(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), vec2(4.0), vec2(4.0), ivec2(5)); + d = textureLod(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), 3.0); + d = textureLodOffset(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), 3.0, ivec2(5)); + d = textureOffset(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), ivec2(5)); +} + +void testTexCube(in vec3 coord) { + vec4 c; + c = texture(samplerCube(texCube, samp), coord); + c = texture(samplerCube(texCube, samp), coord, 2.0); + c = textureGrad(samplerCube(texCube, samp), coord, vec3(4.0), vec3(4.0)); + c = textureLod(samplerCube(texCube, samp), coord, 3.0); + c = textureLodOffset(samplerCube(texCube, samp), coord, 3.0, ivec3(5)); + c = textureOffset(samplerCube(texCube, samp), coord, ivec3(5)); + c = textureOffset(samplerCube(texCube, samp), coord, ivec3(5), 2.0); +} + +void testTexCubeShadow(in vec3 coord) { + float d; + d = texture(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0)); + d = textureGrad(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0), vec3(4.0), vec3(4.0)); + d = textureLod(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0), 3.0); + d = textureLodOffset(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0), 3.0, ivec3(5)); + d = textureOffset(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0), ivec3(5)); +} + +void testTexCubeArray(in vec4 coord) { + vec4 c; + c = texture(samplerCubeArray(texCubeArray, samp), coord); + c = texture(samplerCubeArray(texCubeArray, samp), coord, 2.0); + c = textureGrad(samplerCubeArray(texCubeArray, samp), coord, vec3(4.0), vec3(4.0)); + c = textureLod(samplerCubeArray(texCubeArray, samp), coord, 3.0); + c = textureLodOffset(samplerCubeArray(texCubeArray, samp), coord, 3.0, ivec3(5)); + c = textureOffset(samplerCubeArray(texCubeArray, samp), coord, ivec3(5)); + c = textureOffset(samplerCubeArray(texCubeArray, samp), coord, ivec3(5), 2.0); +} + +void testTexCubeArrayShadow(in vec4 coord) { + float d; + d = texture(samplerCubeArrayShadow(texCubeArrayShadow, sampShadow), coord, 1.0); + // The rest of the variants aren't defined by GLSL. +} + +void testTex3D(in vec3 coord) { + vec4 c; + c = texture(sampler3D(tex3D, samp), coord); + c = texture(sampler3D(tex3D, samp), coord, 2.0); + c = textureGrad(sampler3D(tex3D, samp), coord, vec3(4.0), vec3(4.0)); + c = textureGradOffset(sampler3D(tex3D, samp), coord, vec3(4.0), vec3(4.0), ivec3(5)); + c = textureLod(sampler3D(tex3D, samp), coord, 3.0); + c = textureLodOffset(sampler3D(tex3D, samp), coord, 3.0, ivec3(5)); + c = textureOffset(sampler3D(tex3D, samp), coord, ivec3(5)); + c = textureOffset(sampler3D(tex3D, samp), coord, ivec3(5), 2.0); +} + +layout(location = 0) in vec4 texcoord; void main() { - o_color.rgba = texture(sampler2DArray(tex, samp), vec3(v_TexCoord, 0.0)); } diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 00beae9be..3381d2105 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -1,31 +1,574 @@ -struct FragmentOutput { - [[location(0)]] o_color: vec4; -}; - [[group(1), binding(0)]] -var tex: texture_2d_array; +var tex1D: texture_1d; [[group(1), binding(1)]] +var tex1DArray: texture_1d_array; +[[group(1), binding(2)]] +var tex2D: texture_2d; +[[group(1), binding(3)]] +var tex2DArray: texture_2d_array; +[[group(1), binding(4)]] +var texCube: texture_cube; +[[group(1), binding(5)]] +var texCubeArray: texture_cube_array; +[[group(1), binding(6)]] +var tex3D: texture_3d; +[[group(1), binding(7)]] var samp: sampler; -var v_TexCoord1: vec2; -var o_color: vec4; +[[group(1), binding(12)]] +var tex2DShadow: texture_depth_2d; +[[group(1), binding(13)]] +var tex2DArrayShadow: texture_depth_2d_array; +[[group(1), binding(14)]] +var texCubeShadow: texture_depth_cube; +[[group(1), binding(15)]] +var texCubeArrayShadow: texture_depth_cube_array; +[[group(1), binding(16)]] +var tex3DShadow: texture_3d; +[[group(1), binding(17)]] +var sampShadow: sampler_comparison; +var texcoord1: vec4; + +fn testTex1D(coord: f32) { + var coord1: f32; + var c: vec4; + + coord1 = coord; + let _e18: f32 = coord1; + let _e19: vec4 = textureSample(tex1D, samp, _e18); + c = _e19; + let _e22: f32 = coord1; + let _e24: vec4 = textureSampleBias(tex1D, samp, _e22, 2.0); + c = _e24; + let _e28: f32 = coord1; + let _e31: vec4 = textureSampleGrad(tex1D, samp, _e28, 4.0, 4.0); + c = _e31; + let _e36: f32 = coord1; + let _e40: vec4 = textureSampleGrad(tex1D, samp, _e36, 4.0, 4.0, 5); + c = _e40; + let _e43: f32 = coord1; + let _e45: vec4 = textureSampleLevel(tex1D, samp, _e43, 3.0); + c = _e45; + let _e49: f32 = coord1; + let _e52: vec4 = textureSampleLevel(tex1D, samp, _e49, 3.0, 5); + c = _e52; + let _e55: f32 = coord1; + let _e57: vec4 = textureSample(tex1D, samp, _e55, 5); + c = _e57; + let _e61: f32 = coord1; + let _e64: vec4 = textureSampleBias(tex1D, samp, _e61, 2.0, 5); + c = _e64; + let _e65: f32 = coord1; + let _e68: f32 = coord1; + let _e70: vec2 = vec2(_e68, 6.0); + let _e74: vec4 = textureSample(tex1D, samp, (_e70.x / _e70.y)); + c = _e74; + let _e75: f32 = coord1; + let _e80: f32 = coord1; + let _e84: vec4 = vec4(_e80, 0.0, 0.0, 6.0); + let _e90: vec4 = textureSample(tex1D, samp, (_e84.xyz / vec3(_e84.w)).x); + c = _e90; + let _e91: f32 = coord1; + let _e95: f32 = coord1; + let _e97: vec2 = vec2(_e95, 6.0); + let _e102: vec4 = textureSampleBias(tex1D, samp, (_e97.x / _e97.y), 2.0); + c = _e102; + let _e103: f32 = coord1; + let _e109: f32 = coord1; + let _e113: vec4 = vec4(_e109, 0.0, 0.0, 6.0); + let _e120: vec4 = textureSampleBias(tex1D, samp, (_e113.xyz / vec3(_e113.w)).x, 2.0); + c = _e120; + let _e121: f32 = coord1; + let _e126: f32 = coord1; + let _e128: vec2 = vec2(_e126, 6.0); + let _e134: vec4 = textureSampleGrad(tex1D, samp, (_e128.x / _e128.y), 4.0, 4.0); + c = _e134; + let _e135: f32 = coord1; + let _e142: f32 = coord1; + let _e146: vec4 = vec4(_e142, 0.0, 0.0, 6.0); + let _e154: vec4 = textureSampleGrad(tex1D, samp, (_e146.xyz / vec3(_e146.w)).x, 4.0, 4.0); + c = _e154; + let _e155: f32 = coord1; + let _e161: f32 = coord1; + let _e163: vec2 = vec2(_e161, 6.0); + let _e170: vec4 = textureSampleGrad(tex1D, samp, (_e163.x / _e163.y), 4.0, 4.0, 5); + c = _e170; + let _e171: f32 = coord1; + let _e179: f32 = coord1; + let _e183: vec4 = vec4(_e179, 0.0, 0.0, 6.0); + let _e192: vec4 = textureSampleGrad(tex1D, samp, (_e183.xyz / vec3(_e183.w)).x, 4.0, 4.0, 5); + c = _e192; + let _e193: f32 = coord1; + let _e197: f32 = coord1; + let _e199: vec2 = vec2(_e197, 6.0); + let _e204: vec4 = textureSampleLevel(tex1D, samp, (_e199.x / _e199.y), 3.0); + c = _e204; + let _e205: f32 = coord1; + let _e211: f32 = coord1; + let _e215: vec4 = vec4(_e211, 0.0, 0.0, 6.0); + let _e222: vec4 = textureSampleLevel(tex1D, samp, (_e215.xyz / vec3(_e215.w)).x, 3.0); + c = _e222; + let _e223: f32 = coord1; + let _e228: f32 = coord1; + let _e230: vec2 = vec2(_e228, 6.0); + let _e236: vec4 = textureSampleLevel(tex1D, samp, (_e230.x / _e230.y), 3.0, 5); + c = _e236; + let _e237: f32 = coord1; + let _e244: f32 = coord1; + let _e248: vec4 = vec4(_e244, 0.0, 0.0, 6.0); + let _e256: vec4 = textureSampleLevel(tex1D, samp, (_e248.xyz / vec3(_e248.w)).x, 3.0, 5); + c = _e256; + let _e257: f32 = coord1; + let _e261: f32 = coord1; + let _e263: vec2 = vec2(_e261, 6.0); + let _e268: vec4 = textureSample(tex1D, samp, (_e263.x / _e263.y), 5); + c = _e268; + let _e269: f32 = coord1; + let _e275: f32 = coord1; + let _e279: vec4 = vec4(_e275, 0.0, 0.0, 6.0); + let _e286: vec4 = textureSample(tex1D, samp, (_e279.xyz / vec3(_e279.w)).x, 5); + c = _e286; + let _e287: f32 = coord1; + let _e292: f32 = coord1; + let _e294: vec2 = vec2(_e292, 6.0); + let _e300: vec4 = textureSampleBias(tex1D, samp, (_e294.x / _e294.y), 2.0, 5); + c = _e300; + let _e301: f32 = coord1; + let _e308: f32 = coord1; + let _e312: vec4 = vec4(_e308, 0.0, 0.0, 6.0); + let _e320: vec4 = textureSampleBias(tex1D, samp, (_e312.xyz / vec3(_e312.w)).x, 2.0, 5); + c = _e320; + return; +} + +fn testTex1DArray(coord2: vec2) { + var coord3: vec2; + var c1: vec4; + + coord3 = coord2; + let _e18: vec2 = coord3; + let _e22: vec4 = textureSample(tex1DArray, samp, _e18.x, i32(_e18.x)); + c1 = _e22; + let _e25: vec2 = coord3; + let _e30: vec4 = textureSampleBias(tex1DArray, samp, _e25.x, i32(_e25.x), 2.0); + c1 = _e30; + let _e34: vec2 = coord3; + let _e40: vec4 = textureSampleGrad(tex1DArray, samp, _e34.x, i32(_e34.x), 4.0, 4.0); + c1 = _e40; + let _e45: vec2 = coord3; + let _e52: vec4 = textureSampleGrad(tex1DArray, samp, _e45.x, i32(_e45.x), 4.0, 4.0, 5); + c1 = _e52; + let _e55: vec2 = coord3; + let _e60: vec4 = textureSampleLevel(tex1DArray, samp, _e55.x, i32(_e55.x), 3.0); + c1 = _e60; + let _e64: vec2 = coord3; + let _e70: vec4 = textureSampleLevel(tex1DArray, samp, _e64.x, i32(_e64.x), 3.0, 5); + c1 = _e70; + let _e73: vec2 = coord3; + let _e78: vec4 = textureSample(tex1DArray, samp, _e73.x, i32(_e73.x), 5); + c1 = _e78; + let _e82: vec2 = coord3; + let _e88: vec4 = textureSampleBias(tex1DArray, samp, _e82.x, i32(_e82.x), 2.0, 5); + c1 = _e88; + return; +} + +fn testTex2D(coord4: vec2) { + var coord5: vec2; + var c2: vec4; + + coord5 = coord4; + let _e18: vec2 = coord5; + let _e19: vec4 = textureSample(tex2D, samp, _e18); + c2 = _e19; + let _e22: vec2 = coord5; + let _e24: vec4 = textureSampleBias(tex2D, samp, _e22, 2.0); + c2 = _e24; + let _e30: vec2 = coord5; + let _e35: vec4 = textureSampleGrad(tex2D, samp, _e30, vec2(4.0), vec2(4.0)); + c2 = _e35; + let _e43: vec2 = coord5; + let _e50: vec4 = textureSampleGrad(tex2D, samp, _e43, vec2(4.0), vec2(4.0), vec2(5, 5)); + c2 = _e50; + let _e53: vec2 = coord5; + let _e55: vec4 = textureSampleLevel(tex2D, samp, _e53, 3.0); + c2 = _e55; + let _e60: vec2 = coord5; + let _e64: vec4 = textureSampleLevel(tex2D, samp, _e60, 3.0, vec2(5, 5)); + c2 = _e64; + let _e68: vec2 = coord5; + let _e71: vec4 = textureSample(tex2D, samp, _e68, vec2(5, 5)); + c2 = _e71; + let _e76: vec2 = coord5; + let _e80: vec4 = textureSampleBias(tex2D, samp, _e76, 2.0, vec2(5, 5)); + c2 = _e80; + let _e81: vec2 = coord5; + let _e84: vec2 = coord5; + let _e86: vec3 = vec3(_e84, 6.0); + let _e91: vec4 = textureSample(tex2D, samp, (_e86.xy / vec2(_e86.z))); + c2 = _e91; + let _e92: vec2 = coord5; + let _e96: vec2 = coord5; + let _e99: vec4 = vec4(_e96, 0.0, 6.0); + let _e105: vec4 = textureSample(tex2D, samp, (_e99.xyz / vec3(_e99.w)).xy); + c2 = _e105; + let _e106: vec2 = coord5; + let _e110: vec2 = coord5; + let _e112: vec3 = vec3(_e110, 6.0); + let _e118: vec4 = textureSampleBias(tex2D, samp, (_e112.xy / vec2(_e112.z)), 2.0); + c2 = _e118; + let _e119: vec2 = coord5; + let _e124: vec2 = coord5; + let _e127: vec4 = vec4(_e124, 0.0, 6.0); + let _e134: vec4 = textureSampleBias(tex2D, samp, (_e127.xyz / vec3(_e127.w)).xy, 2.0); + c2 = _e134; + let _e135: vec2 = coord5; + let _e142: vec2 = coord5; + let _e144: vec3 = vec3(_e142, 6.0); + let _e153: vec4 = textureSampleGrad(tex2D, samp, (_e144.xy / vec2(_e144.z)), vec2(4.0), vec2(4.0)); + c2 = _e153; + let _e154: vec2 = coord5; + let _e162: vec2 = coord5; + let _e165: vec4 = vec4(_e162, 0.0, 6.0); + let _e175: vec4 = textureSampleGrad(tex2D, samp, (_e165.xyz / vec3(_e165.w)).xy, vec2(4.0), vec2(4.0)); + c2 = _e175; + let _e176: vec2 = coord5; + let _e185: vec2 = coord5; + let _e187: vec3 = vec3(_e185, 6.0); + let _e198: vec4 = textureSampleGrad(tex2D, samp, (_e187.xy / vec2(_e187.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); + c2 = _e198; + let _e199: vec2 = coord5; + let _e209: vec2 = coord5; + let _e212: vec4 = vec4(_e209, 0.0, 6.0); + let _e224: vec4 = textureSampleGrad(tex2D, samp, (_e212.xyz / vec3(_e212.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); + c2 = _e224; + let _e225: vec2 = coord5; + let _e229: vec2 = coord5; + let _e231: vec3 = vec3(_e229, 6.0); + let _e237: vec4 = textureSampleLevel(tex2D, samp, (_e231.xy / vec2(_e231.z)), 3.0); + c2 = _e237; + let _e238: vec2 = coord5; + let _e243: vec2 = coord5; + let _e246: vec4 = vec4(_e243, 0.0, 6.0); + let _e253: vec4 = textureSampleLevel(tex2D, samp, (_e246.xyz / vec3(_e246.w)).xy, 3.0); + c2 = _e253; + let _e254: vec2 = coord5; + let _e260: vec2 = coord5; + let _e262: vec3 = vec3(_e260, 6.0); + let _e270: vec4 = textureSampleLevel(tex2D, samp, (_e262.xy / vec2(_e262.z)), 3.0, vec2(5, 5)); + c2 = _e270; + let _e271: vec2 = coord5; + let _e278: vec2 = coord5; + let _e281: vec4 = vec4(_e278, 0.0, 6.0); + let _e290: vec4 = textureSampleLevel(tex2D, samp, (_e281.xyz / vec3(_e281.w)).xy, 3.0, vec2(5, 5)); + c2 = _e290; + let _e291: vec2 = coord5; + let _e296: vec2 = coord5; + let _e298: vec3 = vec3(_e296, 6.0); + let _e305: vec4 = textureSample(tex2D, samp, (_e298.xy / vec2(_e298.z)), vec2(5, 5)); + c2 = _e305; + let _e306: vec2 = coord5; + let _e312: vec2 = coord5; + let _e315: vec4 = vec4(_e312, 0.0, 6.0); + let _e323: vec4 = textureSample(tex2D, samp, (_e315.xyz / vec3(_e315.w)).xy, vec2(5, 5)); + c2 = _e323; + let _e324: vec2 = coord5; + let _e330: vec2 = coord5; + let _e332: vec3 = vec3(_e330, 6.0); + let _e340: vec4 = textureSampleBias(tex2D, samp, (_e332.xy / vec2(_e332.z)), 2.0, vec2(5, 5)); + c2 = _e340; + let _e341: vec2 = coord5; + let _e348: vec2 = coord5; + let _e351: vec4 = vec4(_e348, 0.0, 6.0); + let _e360: vec4 = textureSampleBias(tex2D, samp, (_e351.xyz / vec3(_e351.w)).xy, 2.0, vec2(5, 5)); + c2 = _e360; + return; +} + +fn testTex2DShadow(coord6: vec2) { + var coord7: vec2; + var d: f32; + + coord7 = coord6; + let _e17: vec2 = coord7; + let _e20: vec2 = coord7; + let _e22: vec3 = vec3(_e20, 1.0); + let _e25: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e22.xy, _e22.z); + d = _e25; + let _e26: vec2 = coord7; + let _e33: vec2 = coord7; + let _e35: vec3 = vec3(_e33, 1.0); + let _e42: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e35.xy, _e35.z); + d = _e42; + let _e43: vec2 = coord7; + let _e52: vec2 = coord7; + let _e54: vec3 = vec3(_e52, 1.0); + let _e63: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e54.xy, _e54.z, vec2(5, 5)); + d = _e63; + let _e64: vec2 = coord7; + let _e68: vec2 = coord7; + let _e70: vec3 = vec3(_e68, 1.0); + let _e74: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e70.xy, _e70.z); + d = _e74; + let _e75: vec2 = coord7; + let _e81: vec2 = coord7; + let _e83: vec3 = vec3(_e81, 1.0); + let _e89: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e83.xy, _e83.z, vec2(5, 5)); + d = _e89; + let _e90: vec2 = coord7; + let _e95: vec2 = coord7; + let _e97: vec3 = vec3(_e95, 1.0); + let _e102: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e97.xy, _e97.z, vec2(5, 5)); + d = _e102; + let _e103: vec2 = coord7; + let _e107: vec2 = coord7; + let _e110: vec4 = vec4(_e107, 1.0, 6.0); + let _e114: vec3 = (_e110.xyz / vec3(_e110.w)); + let _e117: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e114.xy, _e114.z); + d = _e117; + let _e118: vec2 = coord7; + let _e126: vec2 = coord7; + let _e129: vec4 = vec4(_e126, 1.0, 6.0); + let _e137: vec3 = (_e129.xyz / vec3(_e129.w)); + let _e140: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e137.xy, _e137.z); + d = _e140; + let _e141: vec2 = coord7; + let _e151: vec2 = coord7; + let _e154: vec4 = vec4(_e151, 1.0, 6.0); + let _e164: vec3 = (_e154.xyz / vec3(_e154.w)); + let _e167: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e164.xy, _e164.z, vec2(5, 5)); + d = _e167; + let _e168: vec2 = coord7; + let _e173: vec2 = coord7; + let _e176: vec4 = vec4(_e173, 1.0, 6.0); + let _e181: vec3 = (_e176.xyz / vec3(_e176.w)); + let _e184: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e181.xy, _e181.z); + d = _e184; + let _e185: vec2 = coord7; + let _e192: vec2 = coord7; + let _e195: vec4 = vec4(_e192, 1.0, 6.0); + let _e202: vec3 = (_e195.xyz / vec3(_e195.w)); + let _e205: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e202.xy, _e202.z, vec2(5, 5)); + d = _e205; + let _e206: vec2 = coord7; + let _e212: vec2 = coord7; + let _e215: vec4 = vec4(_e212, 1.0, 6.0); + let _e221: vec3 = (_e215.xyz / vec3(_e215.w)); + let _e224: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e221.xy, _e221.z, vec2(5, 5)); + d = _e224; + return; +} + +fn testTex2DArray(coord8: vec3) { + var coord9: vec3; + var c3: vec4; + + coord9 = coord8; + let _e18: vec3 = coord9; + let _e22: vec4 = textureSample(tex2DArray, samp, _e18.xy, i32(_e18.z)); + c3 = _e22; + let _e25: vec3 = coord9; + let _e30: vec4 = textureSampleBias(tex2DArray, samp, _e25.xy, i32(_e25.z), 2.0); + c3 = _e30; + let _e36: vec3 = coord9; + let _e44: vec4 = textureSampleGrad(tex2DArray, samp, _e36.xy, i32(_e36.z), vec2(4.0), vec2(4.0)); + c3 = _e44; + let _e52: vec3 = coord9; + let _e62: vec4 = textureSampleGrad(tex2DArray, samp, _e52.xy, i32(_e52.z), vec2(4.0), vec2(4.0), vec2(5, 5)); + c3 = _e62; + let _e65: vec3 = coord9; + let _e70: vec4 = textureSampleLevel(tex2DArray, samp, _e65.xy, i32(_e65.z), 3.0); + c3 = _e70; + let _e75: vec3 = coord9; + let _e82: vec4 = textureSampleLevel(tex2DArray, samp, _e75.xy, i32(_e75.z), 3.0, vec2(5, 5)); + c3 = _e82; + let _e86: vec3 = coord9; + let _e92: vec4 = textureSample(tex2DArray, samp, _e86.xy, i32(_e86.z), vec2(5, 5)); + c3 = _e92; + let _e97: vec3 = coord9; + let _e104: vec4 = textureSampleBias(tex2DArray, samp, _e97.xy, i32(_e97.z), 2.0, vec2(5, 5)); + c3 = _e104; + return; +} + +fn testTex2DArrayShadow(coord10: vec3) { + var coord11: vec3; + var d1: f32; + + coord11 = coord10; + let _e17: vec3 = coord11; + let _e20: vec3 = coord11; + let _e22: vec4 = vec4(_e20, 1.0); + let _e27: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e22.xy, i32(_e22.z), _e22.w); + d1 = _e27; + let _e28: vec3 = coord11; + let _e35: vec3 = coord11; + let _e37: vec4 = vec4(_e35, 1.0); + let _e46: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e37.xy, i32(_e37.z), _e37.w); + d1 = _e46; + let _e47: vec3 = coord11; + let _e56: vec3 = coord11; + let _e58: vec4 = vec4(_e56, 1.0); + let _e69: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e58.xy, i32(_e58.z), _e58.w, vec2(5, 5)); + d1 = _e69; + let _e70: vec3 = coord11; + let _e74: vec3 = coord11; + let _e76: vec4 = vec4(_e74, 1.0); + let _e82: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e76.xy, i32(_e76.z), _e76.w); + d1 = _e82; + let _e83: vec3 = coord11; + let _e89: vec3 = coord11; + let _e91: vec4 = vec4(_e89, 1.0); + let _e99: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e91.xy, i32(_e91.z), _e91.w, vec2(5, 5)); + d1 = _e99; + let _e100: vec3 = coord11; + let _e105: vec3 = coord11; + let _e107: vec4 = vec4(_e105, 1.0); + let _e114: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e107.xy, i32(_e107.z), _e107.w, vec2(5, 5)); + d1 = _e114; + return; +} + +fn testTexCube(coord12: vec3) { + var coord13: vec3; + var c4: vec4; + + coord13 = coord12; + let _e18: vec3 = coord13; + let _e19: vec4 = textureSample(texCube, samp, _e18); + c4 = _e19; + let _e22: vec3 = coord13; + let _e24: vec4 = textureSampleBias(texCube, samp, _e22, 2.0); + c4 = _e24; + let _e30: vec3 = coord13; + let _e35: vec4 = textureSampleGrad(texCube, samp, _e30, vec3(4.0), vec3(4.0)); + c4 = _e35; + let _e38: vec3 = coord13; + let _e40: vec4 = textureSampleLevel(texCube, samp, _e38, 3.0); + c4 = _e40; + let _e45: vec3 = coord13; + let _e49: vec4 = textureSampleLevel(texCube, samp, _e45, 3.0, vec3(5, 5, 5)); + c4 = _e49; + let _e53: vec3 = coord13; + let _e56: vec4 = textureSample(texCube, samp, _e53, vec3(5, 5, 5)); + c4 = _e56; + let _e61: vec3 = coord13; + let _e65: vec4 = textureSampleBias(texCube, samp, _e61, 2.0, vec3(5, 5, 5)); + c4 = _e65; + return; +} + +fn testTexCubeShadow(coord14: vec3) { + var coord15: vec3; + var d2: f32; + + coord15 = coord14; + let _e17: vec3 = coord15; + let _e20: vec3 = coord15; + let _e22: vec4 = vec4(_e20, 1.0); + let _e25: f32 = textureSampleCompare(texCubeShadow, sampShadow, _e22.xyz, _e22.w); + d2 = _e25; + let _e26: vec3 = coord15; + let _e33: vec3 = coord15; + let _e35: vec4 = vec4(_e33, 1.0); + let _e42: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e35.xyz, _e35.w); + d2 = _e42; + let _e43: vec3 = coord15; + let _e47: vec3 = coord15; + let _e49: vec4 = vec4(_e47, 1.0); + let _e53: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e49.xyz, _e49.w); + d2 = _e53; + let _e54: vec3 = coord15; + let _e60: vec3 = coord15; + let _e62: vec4 = vec4(_e60, 1.0); + let _e68: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e62.xyz, _e62.w, vec3(5, 5, 5)); + d2 = _e68; + let _e69: vec3 = coord15; + let _e74: vec3 = coord15; + let _e76: vec4 = vec4(_e74, 1.0); + let _e81: f32 = textureSampleCompare(texCubeShadow, sampShadow, _e76.xyz, _e76.w, vec3(5, 5, 5)); + d2 = _e81; + return; +} + +fn testTexCubeArray(coord16: vec4) { + var coord17: vec4; + var c5: vec4; + + coord17 = coord16; + let _e18: vec4 = coord17; + let _e22: vec4 = textureSample(texCubeArray, samp, _e18.xyz, i32(_e18.w)); + c5 = _e22; + let _e25: vec4 = coord17; + let _e30: vec4 = textureSampleBias(texCubeArray, samp, _e25.xyz, i32(_e25.w), 2.0); + c5 = _e30; + let _e36: vec4 = coord17; + let _e44: vec4 = textureSampleGrad(texCubeArray, samp, _e36.xyz, i32(_e36.w), vec3(4.0), vec3(4.0)); + c5 = _e44; + let _e47: vec4 = coord17; + let _e52: vec4 = textureSampleLevel(texCubeArray, samp, _e47.xyz, i32(_e47.w), 3.0); + c5 = _e52; + let _e57: vec4 = coord17; + let _e64: vec4 = textureSampleLevel(texCubeArray, samp, _e57.xyz, i32(_e57.w), 3.0, vec3(5, 5, 5)); + c5 = _e64; + let _e68: vec4 = coord17; + let _e74: vec4 = textureSample(texCubeArray, samp, _e68.xyz, i32(_e68.w), vec3(5, 5, 5)); + c5 = _e74; + let _e79: vec4 = coord17; + let _e86: vec4 = textureSampleBias(texCubeArray, samp, _e79.xyz, i32(_e79.w), 2.0, vec3(5, 5, 5)); + c5 = _e86; + return; +} + +fn testTexCubeArrayShadow(coord18: vec4) { + var coord19: vec4; + var d3: f32; + + coord19 = coord18; + let _e19: vec4 = coord19; + let _e24: f32 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e19.xyz, i32(_e19.w), 1.0); + d3 = _e24; + return; +} + +fn testTex3D(coord20: vec3) { + var coord21: vec3; + var c6: vec4; + + coord21 = coord20; + let _e18: vec3 = coord21; + let _e19: vec4 = textureSample(tex3D, samp, _e18); + c6 = _e19; + let _e22: vec3 = coord21; + let _e24: vec4 = textureSampleBias(tex3D, samp, _e22, 2.0); + c6 = _e24; + let _e30: vec3 = coord21; + let _e35: vec4 = textureSampleGrad(tex3D, samp, _e30, vec3(4.0), vec3(4.0)); + c6 = _e35; + let _e43: vec3 = coord21; + let _e50: vec4 = textureSampleGrad(tex3D, samp, _e43, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + c6 = _e50; + let _e53: vec3 = coord21; + let _e55: vec4 = textureSampleLevel(tex3D, samp, _e53, 3.0); + c6 = _e55; + let _e60: vec3 = coord21; + let _e64: vec4 = textureSampleLevel(tex3D, samp, _e60, 3.0, vec3(5, 5, 5)); + c6 = _e64; + let _e68: vec3 = coord21; + let _e71: vec4 = textureSample(tex3D, samp, _e68, vec3(5, 5, 5)); + c6 = _e71; + let _e76: vec3 = coord21; + let _e80: vec4 = textureSampleBias(tex3D, samp, _e76, 2.0, vec3(5, 5, 5)); + c6 = _e80; + return; +} fn main1() { - let _e4: vec4 = o_color; - let _e6: vec2 = v_TexCoord1; - let _e9: vec2 = v_TexCoord1; - let _e11: vec3 = vec3(_e9, 0.0); - let _e15: vec4 = textureSample(tex, samp, _e11.xy, i32(_e11.z)); - o_color.x = _e15.x; - o_color.y = _e15.y; - o_color.z = _e15.z; - o_color.w = _e15.w; return; } [[stage(fragment)]] -fn main([[location(0)]] v_TexCoord: vec2) -> FragmentOutput { - v_TexCoord1 = v_TexCoord; +fn main([[location(0)]] texcoord: vec4) { + texcoord1 = texcoord; main1(); - let _e11: vec4 = o_color; - return FragmentOutput(_e11); + return; } From 2610082bbf03bc2ddba03a86cd2d1cbf9a896c97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 16 Sep 2021 22:50:00 +0100 Subject: [PATCH 1352/2212] [glsl-in] Use local for constant indexing Constants that are to be dynamically indexed now are first transformed into locals with them as the initializer. --- src/front/glsl/ast.rs | 3 +- src/front/glsl/context.rs | 109 ++++++++++++++++++-------- src/front/glsl/parser/declarations.rs | 11 ++- src/front/glsl/variables.rs | 3 +- 4 files changed, 84 insertions(+), 42 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 5cadd03cb..f03a89a9d 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -9,7 +9,7 @@ use crate::{ #[derive(Debug, Clone, Copy)] pub enum GlobalLookupKind { Variable(Handle), - Constant(Handle), + Constant(Handle, Handle), BlockSelect(Handle, u32), } @@ -82,6 +82,7 @@ pub struct VariableReference { pub expr: Handle, pub load: bool, pub mutable: bool, + pub constant: Option<(Handle, Handle)>, pub entry_arg: Option, } diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 541950a98..42bc6b6d3 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -24,15 +24,18 @@ pub enum ExprPos { Rhs, /// The expression is an array being indexed, needed to allow constant /// arrays to be dinamically indexed - ArrayBase, + ArrayBase { + /// The index is a constant + constant_index: bool, + }, } impl ExprPos { /// Returns an lhs position if the current position is lhs otherwise ArrayBase - fn maybe_array_base(&self) -> Self { + fn maybe_array_base(&self, constant_index: bool) -> Self { match *self { ExprPos::Lhs => *self, - _ => ExprPos::ArrayBase, + _ => ExprPos::ArrayBase { constant_index }, } } } @@ -99,12 +102,13 @@ impl Context { body: &mut Block, ) { self.emit_flush(body); - let (expr, load) = match kind { + let (expr, load, constant) = match kind { GlobalLookupKind::Variable(v) => { let span = parser.module.global_variables.get_span(v); let res = ( self.expressions.append(Expression::GlobalVariable(v), span), parser.module.global_variables[v].class != StorageClass::Handle, + None, ); self.emit_start(); @@ -120,30 +124,35 @@ impl Context { .expressions .append(Expression::AccessIndex { base, index }, span); - (expr, { - let ty = parser.module.global_variables[handle].ty; + ( + expr, + { + let ty = parser.module.global_variables[handle].ty; - match parser.module.types[ty].inner { - TypeInner::Struct { ref members, .. } => { - if let TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } = parser.module.types[members[index as usize].ty].inner - { - false - } else { - true + match parser.module.types[ty].inner { + TypeInner::Struct { ref members, .. } => { + if let TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } = parser.module.types[members[index as usize].ty].inner + { + false + } else { + true + } } + _ => true, } - _ => true, - } - }) + }, + None, + ) } - GlobalLookupKind::Constant(v) => { + GlobalLookupKind::Constant(v, ty) => { let span = parser.module.constants.get_span(v); let res = ( self.expressions.append(Expression::Constant(v), span), false, + Some((v, ty)), ); self.emit_start(); res @@ -154,6 +163,7 @@ impl Context { expr, load, mutable, + constant, entry_arg, }; @@ -216,6 +226,7 @@ impl Context { expr, load: true, mutable, + constant: None, entry_arg: None, }, ); @@ -299,6 +310,7 @@ impl Context { expr: local_expr, load: true, mutable, + constant: None, entry_arg: None, }, ); @@ -310,6 +322,7 @@ impl Context { expr, load, mutable, + constant: None, entry_arg: None, }, ); @@ -418,15 +431,21 @@ impl Context { let handle = match *kind { HirExprKind::Access { base, index } => { - let base = self - .lower_expect_inner(stmt, parser, base, pos.maybe_array_base(), body)? - .0; let (index, index_meta) = self.lower_expect_inner(stmt, parser, index, ExprPos::Rhs, body)?; + let maybe_constant_index = parser.solve_constant(self, index, index_meta).ok(); - let pointer = parser - .solve_constant(self, index, index_meta) - .ok() + let base = self + .lower_expect_inner( + stmt, + parser, + base, + pos.maybe_array_base(maybe_constant_index.is_some()), + body, + )? + .0; + + let pointer = maybe_constant_index .and_then(|constant| { Some(self.add_expression( Expression::AccessIndex { @@ -572,9 +591,9 @@ impl Context { self.add_expression(Expression::Unary { op, expr }, meta, body) } - HirExprKind::Variable(ref var) => { - if pos != ExprPos::Rhs { - if !var.mutable && ExprPos::Lhs == pos { + HirExprKind::Variable(ref var) => match pos { + ExprPos::Lhs => { + if !var.mutable { parser.errors.push(Error { kind: ErrorKind::SemanticError( "Variable cannot be used in LHS position".into(), @@ -583,13 +602,35 @@ impl Context { }) } - var.expr - } else if var.load { - self.add_expression(Expression::Load { pointer: var.expr }, meta, body) - } else { var.expr } - } + ExprPos::ArrayBase { + constant_index: false, + } => { + if let Some((constant, ty)) = var.constant { + let local = self.locals.append( + LocalVariable { + name: None, + ty, + init: Some(constant), + }, + crate::Span::default(), + ); + + self.add_expression( + Expression::LocalVariable(local), + SourceMetadata::none(), + body, + ) + } else { + var.expr + } + } + _ if var.load => { + self.add_expression(Expression::Load { pointer: var.expr }, meta, body) + } + _ => var.expr, + }, HirExprKind::Call(ref call) if pos != ExprPos::Lhs => { let maybe_expr = parser.function_or_constructor_call( self, diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 53e1687d2..ca0ffb74a 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -544,15 +544,14 @@ impl<'source> ParsingContext<'source> { }, )?; - for (i, k) in members - .into_iter() - .enumerate() - .filter_map(|(i, m)| m.name.map(|s| (i as u32, s))) - { + for (i, k, ty) in members.into_iter().enumerate().filter_map(|(i, m)| { + let ty = m.ty; + m.name.map(|s| (i as u32, s, ty)) + }) { let lookup = GlobalLookup { kind: match global { GlobalOrConstant::Global(handle) => GlobalLookupKind::BlockSelect(handle, i), - GlobalOrConstant::Constant(handle) => GlobalLookupKind::Constant(handle), + GlobalOrConstant::Constant(handle) => GlobalLookupKind::Constant(handle, ty), }, entry_arg: None, mutable: true, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index cff89959e..200e6aca0 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -101,6 +101,7 @@ impl Parser { expr, load: true, mutable: data.mutable, + constant: None, entry_arg: Some(idx), }, ); @@ -595,7 +596,7 @@ impl Parser { })?; if let Some(name) = name { let lookup = GlobalLookup { - kind: GlobalLookupKind::Constant(init), + kind: GlobalLookupKind::Constant(init, ty), entry_arg: None, mutable: false, }; From 27d6e442d29a17c4d32d7caafda61a000a2656a8 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Thu, 16 Sep 2021 16:43:20 -0700 Subject: [PATCH 1353/2212] [glsl-in] Also apply vector splatting to bitwise ops --- src/front/glsl/context.rs | 10 +- tests/in/glsl/binop.frag | 68 ++++++++++++ tests/out/wgsl/binop-frag.wgsl | 187 +++++++++++++++++++++++++++++++++ 3 files changed, 264 insertions(+), 1 deletion(-) create mode 100644 tests/in/glsl/binop.frag create mode 100644 tests/out/wgsl/binop-frag.wgsl diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 42bc6b6d3..ef2882187 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -539,6 +539,9 @@ impl Context { BinaryOperator::Add | BinaryOperator::Subtract | BinaryOperator::Divide + | BinaryOperator::And + | BinaryOperator::ExclusiveOr + | BinaryOperator::InclusiveOr | BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => { let scalar_vector = self.add_expression( @@ -562,7 +565,12 @@ impl Context { } }, (&TypeInner::Scalar { .. }, &TypeInner::Vector { size, .. }) => match op { - BinaryOperator::Add | BinaryOperator::Subtract | BinaryOperator::Divide => { + BinaryOperator::Add + | BinaryOperator::Subtract + | BinaryOperator::Divide + | BinaryOperator::And + | BinaryOperator::ExclusiveOr + | BinaryOperator::InclusiveOr => { let scalar_vector = self.add_expression( Expression::Splat { size, value: left }, meta, diff --git a/tests/in/glsl/binop.frag b/tests/in/glsl/binop.frag new file mode 100644 index 000000000..1416cb649 --- /dev/null +++ b/tests/in/glsl/binop.frag @@ -0,0 +1,68 @@ +#version 440 core + +void testBinOpVecFloat(vec4 a, float b) { + vec4 v; + v = a * 2.0; + v = a / 2.0; + v = a + 2.0; + v = a - 2.0; +} + +void testBinOpFloatVec(vec4 a, float b) { + vec4 v; + v = a * b; + v = a / b; + v = a + b; + v = a - b; +} + +void testBinOpIVecInt(ivec4 a, int b) { + ivec4 v; + v = a * b; + v = a / b; + v = a + b; + v = a - b; + v = a & b; + v = a | b; + v = a ^ b; + v = a >> b; + v = a << b; +} + +void testBinOpIntIVec(int a, ivec4 b) { + ivec4 v; + v = a * b; + v = a + b; + v = a - b; + v = a & b; + v = a | b; + v = a ^ b; +} + +void testBinOpUVecUint(uvec4 a, uint b) { + uvec4 v; + v = a * b; + v = a / b; + v = a + b; + v = a - b; + v = a & b; + v = a | b; + v = a ^ b; + v = a >> b; + v = a << b; +} + +void testBinOpUintUVec(uint a, uvec4 b) { + uvec4 v; + v = a * b; + v = a + b; + v = a - b; + v = a & b; + v = a | b; + v = a ^ b; +} + +out vec4 o_color; +void main() { + o_color.rgba = vec4(1.0); +} diff --git a/tests/out/wgsl/binop-frag.wgsl b/tests/out/wgsl/binop-frag.wgsl new file mode 100644 index 000000000..dd75aeb11 --- /dev/null +++ b/tests/out/wgsl/binop-frag.wgsl @@ -0,0 +1,187 @@ +var o_color: vec4; + +fn testBinOpVecFloat(a: vec4, b: f32) { + var a1: vec4; + var b1: f32; + var v: vec4; + + a1 = a; + b1 = b; + let _e5: vec4 = a1; + v = (_e5 * 2.0); + let _e8: vec4 = a1; + v = (_e8 / vec4(2.0)); + let _e12: vec4 = a1; + v = (_e12 + vec4(2.0)); + let _e16: vec4 = a1; + v = (_e16 - vec4(2.0)); + return; +} + +fn testBinOpFloatVec(a2: vec4, b2: f32) { + var a3: vec4; + var b3: f32; + var v1: vec4; + + a3 = a2; + b3 = b2; + let _e5: vec4 = a3; + let _e6: f32 = b3; + v1 = (_e5 * _e6); + let _e8: vec4 = a3; + let _e9: f32 = b3; + v1 = (_e8 / vec4(_e9)); + let _e12: vec4 = a3; + let _e13: f32 = b3; + v1 = (_e12 + vec4(_e13)); + let _e16: vec4 = a3; + let _e17: f32 = b3; + v1 = (_e16 - vec4(_e17)); + return; +} + +fn testBinOpIVecInt(a4: vec4, b4: i32) { + var a5: vec4; + var b5: i32; + var v2: vec4; + + a5 = a4; + b5 = b4; + let _e5: vec4 = a5; + let _e6: i32 = b5; + v2 = (_e5 * _e6); + let _e8: vec4 = a5; + let _e9: i32 = b5; + v2 = (_e8 / vec4(_e9)); + let _e12: vec4 = a5; + let _e13: i32 = b5; + v2 = (_e12 + vec4(_e13)); + let _e16: vec4 = a5; + let _e17: i32 = b5; + v2 = (_e16 - vec4(_e17)); + let _e20: vec4 = a5; + let _e21: i32 = b5; + v2 = (_e20 & vec4(_e21)); + let _e24: vec4 = a5; + let _e25: i32 = b5; + v2 = (_e24 | vec4(_e25)); + let _e28: vec4 = a5; + let _e29: i32 = b5; + v2 = (_e28 ^ vec4(_e29)); + let _e32: vec4 = a5; + let _e33: i32 = b5; + v2 = (_e32 >> vec4(u32(_e33))); + let _e37: vec4 = a5; + let _e38: i32 = b5; + v2 = (_e37 << vec4(u32(_e38))); + return; +} + +fn testBinOpIntIVec(a6: i32, b6: vec4) { + var a7: i32; + var b7: vec4; + var v3: vec4; + + a7 = a6; + b7 = b6; + let _e5: i32 = a7; + let _e6: vec4 = b7; + v3 = (_e5 * _e6); + let _e8: i32 = a7; + let _e9: vec4 = b7; + v3 = (vec4(_e8) + _e9); + let _e12: i32 = a7; + let _e13: vec4 = b7; + v3 = (vec4(_e12) - _e13); + let _e16: i32 = a7; + let _e17: vec4 = b7; + v3 = (vec4(_e16) & _e17); + let _e20: i32 = a7; + let _e21: vec4 = b7; + v3 = (vec4(_e20) | _e21); + let _e24: i32 = a7; + let _e25: vec4 = b7; + v3 = (vec4(_e24) ^ _e25); + return; +} + +fn testBinOpUVecUint(a8: vec4, b8: u32) { + var a9: vec4; + var b9: u32; + var v4: vec4; + + a9 = a8; + b9 = b8; + let _e5: vec4 = a9; + let _e6: u32 = b9; + v4 = (_e5 * _e6); + let _e8: vec4 = a9; + let _e9: u32 = b9; + v4 = (_e8 / vec4(_e9)); + let _e12: vec4 = a9; + let _e13: u32 = b9; + v4 = (_e12 + vec4(_e13)); + let _e16: vec4 = a9; + let _e17: u32 = b9; + v4 = (_e16 - vec4(_e17)); + let _e20: vec4 = a9; + let _e21: u32 = b9; + v4 = (_e20 & vec4(_e21)); + let _e24: vec4 = a9; + let _e25: u32 = b9; + v4 = (_e24 | vec4(_e25)); + let _e28: vec4 = a9; + let _e29: u32 = b9; + v4 = (_e28 ^ vec4(_e29)); + let _e32: vec4 = a9; + let _e33: u32 = b9; + v4 = (_e32 >> vec4(_e33)); + let _e36: vec4 = a9; + let _e37: u32 = b9; + v4 = (_e36 << vec4(_e37)); + return; +} + +fn testBinOpUintUVec(a10: u32, b10: vec4) { + var a11: u32; + var b11: vec4; + var v5: vec4; + + a11 = a10; + b11 = b10; + let _e5: u32 = a11; + let _e6: vec4 = b11; + v5 = (_e5 * _e6); + let _e8: u32 = a11; + let _e9: vec4 = b11; + v5 = (vec4(_e8) + _e9); + let _e12: u32 = a11; + let _e13: vec4 = b11; + v5 = (vec4(_e12) - _e13); + let _e16: u32 = a11; + let _e17: vec4 = b11; + v5 = (vec4(_e16) & _e17); + let _e20: u32 = a11; + let _e21: vec4 = b11; + v5 = (vec4(_e20) | _e21); + let _e24: u32 = a11; + let _e25: vec4 = b11; + v5 = (vec4(_e24) ^ _e25); + return; +} + +fn main1() { + let _e1: vec4 = o_color; + let _e4: vec4 = vec4(1.0); + o_color.x = _e4.x; + o_color.y = _e4.y; + o_color.z = _e4.z; + o_color.w = _e4.w; + return; +} + +[[stage(fragment)]] +fn main() { + main1(); + return; +} From 796f5f14b0358cec3b6c6c7aec27337fdf8cf020 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 16 Sep 2021 22:09:08 +0100 Subject: [PATCH 1354/2212] [glsl-in] Fix bad bit pattern in texelFetch This caused arrayed textures to not be accepted --- src/front/glsl/builtins.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 78b9877b5..4e91b7b16 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -360,7 +360,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module // 0b100 is the latest since 3D arrayed images aren't allowed for bits in 0..(0b101) { let dim = bits & 0b1 | (bits & 0b100) >> 1; - let arrayed = bits & 0b1000 == 0b1000; + let arrayed = bits & 0b10 == 0b10; let image = TypeInner::Image { dim: match dim { From e824519378333d7794187e7d732286a269f5de42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 17 Sep 2021 17:18:13 +0100 Subject: [PATCH 1355/2212] [glsl-in] Cast switch selector to int if it's uint --- src/front/glsl/parser/functions.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 3110cdbae..9abd11b81 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -153,12 +153,20 @@ impl<'source> ParsingContext<'source> { let end_meta; self.expect(parser, TokenValue::LeftParen)?; - // TODO: Implicit conversions - let selector = { + + let (mut selector, selector_meta) = { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?.0 + ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)? }; + + if let Some(crate::ScalarKind::Uint) = parser + .resolve_type(ctx, selector, selector_meta)? + .scalar_kind() + { + ctx.conversion(&mut selector, selector_meta, crate::ScalarKind::Sint, 4)? + } + self.expect(parser, TokenValue::RightParen)?; ctx.emit_flush(body); From 1cb4447ec305f24f5c22b4a3530df55ed4a04393 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 17 Sep 2021 18:43:27 +0100 Subject: [PATCH 1356/2212] [glsl-in] Add test array constant dynamic indexing --- tests/in/glsl/global-constant-array.vert | 6 ++++++ tests/out/wgsl/global-constant-array-vert.wgsl | 13 +++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 tests/in/glsl/global-constant-array.vert create mode 100644 tests/out/wgsl/global-constant-array-vert.wgsl diff --git a/tests/in/glsl/global-constant-array.vert b/tests/in/glsl/global-constant-array.vert new file mode 100644 index 000000000..de4f3c708 --- /dev/null +++ b/tests/in/glsl/global-constant-array.vert @@ -0,0 +1,6 @@ +#version 450 core + +uint i; +const float[2] array = { 1.0, 2.0 }; + +void main() { array[i]; } diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl new file mode 100644 index 000000000..01ec742e0 --- /dev/null +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -0,0 +1,13 @@ +var i: u32; + +fn main1() { + var local: array = array(1.0, 2.0); + + let _e2: u32 = i; +} + +[[stage(vertex)]] +fn main() { + main1(); + return; +} From d7ca7d43b987c17f553db2823d833646ff1d48e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 17 Sep 2021 17:01:55 +0100 Subject: [PATCH 1357/2212] [glsl-in] Improve infix handling Add support for float, vector and matrices targets. Fix prefix and postfix being inverted (one was returning the value of the other). Remove an unneeded local indirection for prefix handling. Add tests. --- src/front/glsl/ast.rs | 8 +- src/front/glsl/context.rs | 150 ++++++++++--------- src/front/glsl/parser/expressions.rs | 31 ++-- tests/in/glsl/prepostfix.frag | 18 +++ tests/out/wgsl/246-collatz-comp.wgsl | 6 +- tests/out/wgsl/constant-array-size-vert.wgsl | 14 +- tests/out/wgsl/prepostfix-frag.wgsl | 40 +++++ 7 files changed, 160 insertions(+), 107 deletions(-) create mode 100644 tests/in/glsl/prepostfix.frag create mode 100644 tests/out/wgsl/prepostfix-frag.wgsl diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index f03a89a9d..779d17223 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -123,9 +123,13 @@ pub enum HirExprKind { tgt: Handle, value: Handle, }, - IncDec { - increment: bool, + /// A prefix/postfix operator like `++` + PrePostfix { + /// The operation to be performed + op: BinaryOperator, + /// Whether this is a postfix or a prefix postfix: bool, + /// The target expression expr: Handle, }, } diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index ef2882187..9d35bf1ce 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -750,102 +750,108 @@ impl Context { value } - HirExprKind::IncDec { - increment, - postfix, - expr, - } => { - let op = match increment { - true => BinaryOperator::Add, - false => BinaryOperator::Subtract, - }; - + HirExprKind::PrePostfix { op, postfix, expr } if ExprPos::Lhs != pos => { let pointer = self .lower_expect_inner(stmt, parser, expr, ExprPos::Lhs, body)? .0; let left = self.add_expression(Expression::Load { pointer }, meta, body); - let uint = match parser.resolve_type(self, left, meta)?.scalar_kind() { - Some(ScalarKind::Sint) => false, - Some(ScalarKind::Uint) => true, - _ => { + let make_constant_inner = |kind, width| { + let value = match kind { + ScalarKind::Sint => crate::ScalarValue::Sint(1), + ScalarKind::Uint => crate::ScalarValue::Uint(1), + ScalarKind::Float => crate::ScalarValue::Float(1.0), + ScalarKind::Bool => return None, + }; + + Some(crate::ConstantInner::Scalar { width, value }) + }; + let res = match *parser.resolve_type(self, left, meta)? { + TypeInner::Scalar { kind, width } => { + let ty = TypeInner::Scalar { kind, width }; + make_constant_inner(kind, width).map(|i| (ty, i, None, None)) + } + TypeInner::Vector { size, kind, width } => { + let ty = TypeInner::Vector { size, kind, width }; + make_constant_inner(kind, width).map(|i| (ty, i, Some(size), None)) + } + TypeInner::Matrix { + columns, + rows, + width, + } => { + let ty = TypeInner::Matrix { + columns, + rows, + width, + }; + make_constant_inner(ScalarKind::Float, width) + .map(|i| (ty, i, Some(rows), Some(columns))) + } + _ => None, + }; + let (ty_inner, inner, rows, columns) = match res { + Some(res) => res, + None => { parser.errors.push(Error { kind: ErrorKind::SemanticError( - "Increment/decrement operations must operate in integers".into(), + "Increment/decrement only works on scalar/vector/matrix".into(), ), meta, }); - true + return Ok((Some(left), meta)); } }; - let one = parser.module.constants.append( + let constant_1 = parser.module.constants.append( Constant { name: None, specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: match uint { - true => crate::ScalarValue::Uint(1), - false => crate::ScalarValue::Sint(1), - }, - }, + inner, }, Default::default(), ); - let right = self.add_expression(Expression::Constant(one), meta, body); + let mut right = self.add_expression(Expression::Constant(constant_1), meta, body); + + // Glsl allows pre/postfixes operations on vectors and matrices, so if the + // target is either of them change the right side of the addition to be splatted + // to the same size as the target, furthermore if the target is a matrix + // use a composed matrix using the splatted value. + if let Some(size) = rows { + right = + self.add_expression(Expression::Splat { size, value: right }, meta, body); + + if let Some(cols) = columns { + let ty = parser.module.types.fetch_or_append( + Type { + name: None, + inner: ty_inner, + }, + meta.as_span(), + ); + + right = self.add_expression( + Expression::Compose { + ty, + components: std::iter::repeat(right).take(cols as usize).collect(), + }, + meta, + body, + ); + } + } let value = self.add_expression(Expression::Binary { op, left, right }, meta, body); + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { pointer, value }, meta.as_span()); + if postfix { - let local = self.locals.append( - LocalVariable { - name: None, - ty: parser.module.types.fetch_or_append( - Type { - name: None, - inner: TypeInner::Scalar { - kind: match uint { - true => ScalarKind::Uint, - false => ScalarKind::Sint, - }, - width: 4, - }, - }, - meta.as_span(), - ), - init: None, - }, - meta.as_span(), - ); - - let expr = self.add_expression(Expression::LocalVariable(local), meta, body); - let load = self.add_expression(Expression::Load { pointer: expr }, meta, body); - - self.emit_flush(body); - self.emit_start(); - - body.push( - Statement::Store { - pointer: expr, - value: left, - }, - meta.as_span(), - ); - - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { pointer, value }, meta.as_span()); - - load - } else { - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { pointer, value }, meta.as_span()); - left + } else { + value } } _ => { diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 175c451dc..2eb77d572 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -257,24 +257,14 @@ impl<'source> ParsingContext<'source> { Default::default(), ) } - TokenValue::Increment => { + TokenValue::Increment | TokenValue::Decrement => { base = stmt.hir_exprs.append( HirExpr { - kind: HirExprKind::IncDec { - increment: true, - postfix: true, - expr: base, - }, - meta, - }, - Default::default(), - ) - } - TokenValue::Decrement => { - base = stmt.hir_exprs.append( - HirExpr { - kind: HirExprKind::IncDec { - increment: false, + kind: HirExprKind::PrePostfix { + op: match value { + TokenValue::Increment => crate::BinaryOperator::Add, + _ => crate::BinaryOperator::Subtract, + }, postfix: true, expr: base, }, @@ -331,11 +321,10 @@ impl<'source> ParsingContext<'source> { stmt.hir_exprs.append( HirExpr { - kind: HirExprKind::IncDec { - increment: match value { - TokenValue::Increment => true, - TokenValue::Decrement => false, - _ => unreachable!(), + kind: HirExprKind::PrePostfix { + op: match value { + TokenValue::Increment => crate::BinaryOperator::Add, + _ => crate::BinaryOperator::Subtract, }, postfix: false, expr, diff --git a/tests/in/glsl/prepostfix.frag b/tests/in/glsl/prepostfix.frag new file mode 100644 index 000000000..1b5942892 --- /dev/null +++ b/tests/in/glsl/prepostfix.frag @@ -0,0 +1,18 @@ +#version 450 core + +void main() { + int scalar_target; + int scalar = 1; + scalar_target = scalar++; + scalar_target = --scalar; + + uvec2 vec_target; + uvec2 vec = uvec2(1); + vec_target = vec--; + vec_target = ++vec; + + mat4x3 mat_target; + mat4x3 mat = mat4x3(1); + mat_target = mat++; + mat_target = --mat; +} diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index e052f4b48..fe75c08fb 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -10,7 +10,6 @@ var gl_GlobalInvocationID: vec3; fn collatz_iterations(n: u32) -> u32 { var n1: u32; var i: u32 = 0u; - var local: u32; n1 = n; loop { @@ -32,12 +31,11 @@ fn collatz_iterations(n: u32) -> u32 { } } let _e33: u32 = i; - local = _e33; i = (_e33 + 1u); } } - let _e38: u32 = i; - return _e38; + let _e36: u32 = i; + return _e36; } fn main1() { diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 2eaec3086..ac18b2539 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -9,7 +9,6 @@ var global: Data; fn function() -> vec4 { var sum: vec4 = vec4(0.0, 0.0, 0.0, 0.0); var i: i32 = 0; - var local: i32; loop { let _e9: i32 = i; @@ -17,19 +16,18 @@ fn function() -> vec4 { break; } { - let _e17: vec4 = sum; - let _e18: i32 = i; - let _e20: vec4 = global.vecs[_e18]; - sum = (_e17 + _e20); + let _e15: vec4 = sum; + let _e16: i32 = i; + let _e18: vec4 = global.vecs[_e16]; + sum = (_e15 + _e18); } continuing { let _e12: i32 = i; - local = _e12; i = (_e12 + 1); } } - let _e22: vec4 = sum; - return _e22; + let _e20: vec4 = sum; + return _e20; } fn main1() { diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl new file mode 100644 index 000000000..df723ccf7 --- /dev/null +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -0,0 +1,40 @@ +fn main1() { + var scalar_target: i32; + var scalar: i32 = 1; + var vec_target: vec2; + var vec: vec2 = vec2(1u, 1u); + var mat_target: mat4x3; + var mat: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); + + let _e3: i32 = scalar; + scalar = (_e3 + 1); + scalar_target = _e3; + let _e6: i32 = scalar; + let _e8: i32 = (_e6 - 1); + scalar = _e8; + scalar_target = _e8; + let _e14: vec2 = vec; + vec = (_e14 - vec2(1u)); + vec_target = _e14; + let _e18: vec2 = vec; + let _e21: vec2 = (_e18 + vec2(1u)); + vec = _e21; + vec_target = _e21; + let _e24: f32 = f32(1); + let _e32: mat4x3 = mat; + let _e34: vec3 = vec3(1.0); + mat = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); + mat_target = _e32; + let _e37: mat4x3 = mat; + let _e39: vec3 = vec3(1.0); + let _e41: mat4x3 = (_e37 - mat4x3(_e39, _e39, _e39, _e39)); + mat = _e41; + mat_target = _e41; + return; +} + +[[stage(fragment)]] +fn main() { + main1(); + return; +} From 9b34d503da0ebfd134c7fc1c472c1af2333a718f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 18 Sep 2021 21:19:59 +0100 Subject: [PATCH 1358/2212] Add formating checks to CI --- .github/workflows/pipeline.yml | 14 +++ .monocodus | 7 -- src/front/glsl/builtins.rs | 177 ++++++++++++++++++++++++++------- 3 files changed, 153 insertions(+), 45 deletions(-) delete mode 100644 .monocodus diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index dc9823869..d7e652155 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -71,3 +71,17 @@ jobs: with: command: doc args: -p naga --all-features --document-private-items + fmt: + name: Format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + components: rustfmt + - name: run rustfmt + run: | + cargo fmt -- --check diff --git a/.monocodus b/.monocodus deleted file mode 100644 index 7900103af..000000000 --- a/.monocodus +++ /dev/null @@ -1,7 +0,0 @@ -version: 1.1.0 - -rust: - formatter: - name: rustfmt - repo_checkers: - - name: rust-clippy diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 4e91b7b16..a8030bf6d 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -43,10 +43,7 @@ fn make_coords_arg(number_of_components: usize, kind: Sk) -> TypeInner { let width = 4; match number_of_components { - 1 => TypeInner::Scalar { - kind, - width, - }, + 1 => TypeInner::Scalar { kind, width }, _ => TypeInner::Vector { size: match number_of_components { 2 => VectorSize::Bi, @@ -138,9 +135,18 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module )) } } - "texture" | "textureGrad" | "textureGradOffset" | "textureLod" | "textureLodOffset" | "textureOffset" - | "textureProj" | "textureProjGrad" | "textureProjGradOffset" | "textureProjLod" - | "textureProjLodOffset" | "textureProjOffset" => { + "texture" + | "textureGrad" + | "textureGradOffset" + | "textureLod" + | "textureLodOffset" + | "textureOffset" + | "textureProj" + | "textureProjGrad" + | "textureProjGradOffset" + | "textureProjLod" + | "textureProjLodOffset" + | "textureProjOffset" => { // bits layout // bits 0 through 1 - dims // bit 2 - shadow @@ -157,36 +163,108 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module let builtin = match name { // texture(gsampler, gvec P, [float bias]); - "texture" => MacroCall::Texture { proj: false, offset: false, shadow, level_type: TextureLevelType::None, }, + "texture" => MacroCall::Texture { + proj: false, + offset: false, + shadow, + level_type: TextureLevelType::None, + }, // textureGrad(gsampler, gvec P, gvec dPdx, gvec dPdy); - "textureGrad" => MacroCall::Texture { proj: false, offset: false, shadow, level_type: TextureLevelType::Grad, }, + "textureGrad" => MacroCall::Texture { + proj: false, + offset: false, + shadow, + level_type: TextureLevelType::Grad, + }, // textureGradOffset(gsampler, gvec P, gvec dPdx, gvec dPdy, ivec offset); - "textureGradOffset" => MacroCall::Texture { proj: false, offset: true, shadow, level_type: TextureLevelType::Grad, }, + "textureGradOffset" => MacroCall::Texture { + proj: false, + offset: true, + shadow, + level_type: TextureLevelType::Grad, + }, // textureLod(gsampler, gvec P, float lod); - "textureLod" => MacroCall::Texture { proj: false, offset: false, shadow, level_type: TextureLevelType::Lod, }, + "textureLod" => MacroCall::Texture { + proj: false, + offset: false, + shadow, + level_type: TextureLevelType::Lod, + }, // textureLodOffset(gsampler, gvec P, float lod, ivec offset); - "textureLodOffset" => MacroCall::Texture { proj: false, offset: true, shadow, level_type: TextureLevelType::Lod, }, + "textureLodOffset" => MacroCall::Texture { + proj: false, + offset: true, + shadow, + level_type: TextureLevelType::Lod, + }, // textureOffset(gsampler, gvec+1 P, ivec offset, [float bias]); - "textureOffset" => MacroCall::Texture { proj: false, offset: true, shadow, level_type: TextureLevelType::None, }, + "textureOffset" => MacroCall::Texture { + proj: false, + offset: true, + shadow, + level_type: TextureLevelType::None, + }, // textureProj(gsampler, gvec+1 P, [float bias]); - "textureProj" => MacroCall::Texture { proj: true, offset: false, shadow, level_type: TextureLevelType::None, }, + "textureProj" => MacroCall::Texture { + proj: true, + offset: false, + shadow, + level_type: TextureLevelType::None, + }, // textureProjGrad(gsampler, gvec+1 P, gvec dPdx, gvec dPdy); - "textureProjGrad" => MacroCall::Texture { proj: true, offset: false, shadow, level_type: TextureLevelType::Grad, }, + "textureProjGrad" => MacroCall::Texture { + proj: true, + offset: false, + shadow, + level_type: TextureLevelType::Grad, + }, // textureProjGradOffset(gsampler, gvec+1 P, gvec dPdx, gvec dPdy, ivec offset); - "textureProjGradOffset" => MacroCall::Texture { proj: true, offset: true, shadow, level_type: TextureLevelType::Grad, }, + "textureProjGradOffset" => MacroCall::Texture { + proj: true, + offset: true, + shadow, + level_type: TextureLevelType::Grad, + }, // textureProjLod(gsampler, gvec+1 P, float lod); - "textureProjLod" => MacroCall::Texture { proj: true, offset: false, shadow, level_type: TextureLevelType::Lod, }, + "textureProjLod" => MacroCall::Texture { + proj: true, + offset: false, + shadow, + level_type: TextureLevelType::Lod, + }, // textureProjLodOffset(gsampler, gvec+1 P, gvec dPdx, gvec dPdy, ivec offset); - "textureProjLodOffset" => MacroCall::Texture { proj: true, offset: true, shadow, level_type: TextureLevelType::Lod, }, + "textureProjLodOffset" => MacroCall::Texture { + proj: true, + offset: true, + shadow, + level_type: TextureLevelType::Lod, + }, // textureProjOffset(gsampler, gvec+1 P, ivec offset, [float bias]); - "textureProjOffset" => MacroCall::Texture { proj: true, offset: true, shadow, level_type: TextureLevelType::None, }, + "textureProjOffset" => MacroCall::Texture { + proj: true, + offset: true, + shadow, + level_type: TextureLevelType::None, + }, _ => unreachable!(), }; // Parse out the variant settings. let proj = matches!(builtin, MacroCall::Texture { proj: true, .. }); - let grad = matches!(builtin, MacroCall::Texture { level_type: TextureLevelType::Grad, .. }); - let lod = matches!(builtin, MacroCall::Texture { level_type: TextureLevelType::Lod, .. }); + let grad = matches!( + builtin, + MacroCall::Texture { + level_type: TextureLevelType::Grad, + .. + } + ); + let lod = matches!( + builtin, + MacroCall::Texture { + level_type: TextureLevelType::Lod, + .. + } + ); let offset = matches!(builtin, MacroCall::Texture { offset: true, .. }); let supports_variant = proj && !shadow; @@ -194,7 +272,13 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module continue; } - let supports_bias = matches!(builtin, MacroCall::Texture { level_type: TextureLevelType::None, .. }) && !shadow; + let supports_bias = matches!( + builtin, + MacroCall::Texture { + level_type: TextureLevelType::None, + .. + } + ) && !shadow; if bias && !supports_bias { continue; } @@ -275,17 +359,23 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module } match builtin { - MacroCall::Texture { level_type: TextureLevelType::Lod, .. } => { + MacroCall::Texture { + level_type: TextureLevelType::Lod, + .. + } => { args.push(TypeInner::Scalar { kind: Sk::Float, width, }); - }, - MacroCall::Texture { level_type: TextureLevelType::Grad, .. } => { + } + MacroCall::Texture { + level_type: TextureLevelType::Grad, + .. + } => { args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); - }, - _ => {}, + } + _ => {} }; if offset { @@ -1344,7 +1434,11 @@ fn inject_common_builtin( } #[derive(Clone, Copy, PartialEq, Debug)] -pub enum TextureLevelType { None, Lod, Grad } +pub enum TextureLevelType { + None, + Lod, + Grad, +} /// A compiler defined builtin function #[derive(Clone, Copy, PartialEq, Debug)] @@ -1393,7 +1487,12 @@ impl MacroCall { ctx.samplers.insert(args[0], args[1]); Ok(args[0]) } - MacroCall::Texture { proj, offset, shadow, level_type } => { + MacroCall::Texture { + proj, + offset, + shadow, + level_type, + } => { let mut coords = args[1]; if proj { @@ -1411,7 +1510,10 @@ impl MacroCall { ); let left = if let VectorSize::Bi = size { ctx.add_expression( - Expression::AccessIndex { base: coords, index: 0 }, + Expression::AccessIndex { + base: coords, + index: 0, + }, SourceMetadata::none(), body, ) @@ -1439,7 +1541,8 @@ impl MacroCall { } let extra = args.get(2).copied(); - let comps = parser.coordinate_components(ctx, args[0], coords, extra, meta, body)?; + let comps = + parser.coordinate_components(ctx, args[0], coords, extra, meta, body)?; let mut num_args = 2; @@ -1455,10 +1558,7 @@ impl MacroCall { num_args += 1; if shadow { - log::warn!( - "Assuming LOD {:?} is zero", - args[2], - ); + log::warn!("Assuming LOD {:?} is zero", args[2],); SampleLevel::Zero } else { @@ -1494,10 +1594,10 @@ impl MacroCall { Err(e) => { parser.errors.push(e); None - }, + } } } - false => None + false => None, }; // Now go back and look for optional bias arg (if available) @@ -1521,7 +1621,8 @@ impl MacroCall { body, )), MacroCall::TexelFetch => { - let comps = parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; + let comps = + parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; Ok(ctx.add_expression( Expression::ImageLoad { image: args[0], From aea755fd327456566ec8eb4e46d8da9426b9b208 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 18 Sep 2021 21:32:24 +0100 Subject: [PATCH 1359/2212] [spv-in] Allow OpLine anywhere in the function --- src/front/spv/function.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 1317b755f..8814bb59b 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -141,6 +141,12 @@ impl> super::Parser { let fun_inst = self.next_inst()?; log::debug!("{:?}", fun_inst.op); match fun_inst.op { + spirv::Op::Line => { + fun_inst.expect(4)?; + let _file_id = self.next()?; + let _row_id = self.next()?; + let _col_id = self.next()?; + } spirv::Op::Label => { // Read the label ID fun_inst.expect(2)?; From 7895e7f036debe59f5f35e2d5be9e1598d28393e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 17 Sep 2021 22:03:54 +0100 Subject: [PATCH 1360/2212] Don't output identifiers starting with _ --- src/back/wgsl/mod.rs | 2 + src/back/wgsl/writer.rs | 6 +- src/proc/namer.rs | 2 +- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 12 +- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 24 +- tests/out/wgsl/210-bevy-shader-vert.wgsl | 38 +- tests/out/wgsl/246-collatz-comp.wgsl | 40 +- tests/out/wgsl/280-matrix-cast-vert.wgsl | 2 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 24 +- tests/out/wgsl/932-for-loop-if-vert.wgsl | 8 +- tests/out/wgsl/access.wgsl | 32 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 1042 ++++++++--------- tests/out/wgsl/bevy-pbr-vert.wgsl | 46 +- tests/out/wgsl/binop-frag.wgsl | 232 ++-- tests/out/wgsl/boids.wgsl | 160 +-- tests/out/wgsl/bool-select-frag.wgsl | 30 +- tests/out/wgsl/clamp-splat-vert.wgsl | 8 +- tests/out/wgsl/collatz.wgsl | 30 +- tests/out/wgsl/constant-array-size-vert.wgsl | 20 +- tests/out/wgsl/control-flow.wgsl | 8 +- tests/out/wgsl/fma-frag.wgsl | 36 +- .../out/wgsl/global-constant-array-vert.wgsl | 2 +- tests/out/wgsl/interpolate.wgsl | 4 +- .../wgsl/inv-hyperbolic-trig-functions.wgsl | 12 +- tests/out/wgsl/long-form-matrix-vert.wgsl | 28 +- tests/out/wgsl/math-functions-vert.wgsl | 202 ++-- tests/out/wgsl/operators.wgsl | 12 +- tests/out/wgsl/prepostfix-frag.wgsl | 48 +- tests/out/wgsl/quad-vert.wgsl | 14 +- tests/out/wgsl/quad_glsl-frag.wgsl | 4 +- tests/out/wgsl/quad_glsl-vert.wgsl | 14 +- tests/out/wgsl/samplers-frag.wgsl | 892 +++++++------- tests/out/wgsl/shadow.wgsl | 30 +- tests/out/wgsl/skybox.wgsl | 22 +- tests/out/wgsl/swizzle_write-frag.wgsl | 18 +- tests/out/wgsl/texture-arg.wgsl | 8 +- 36 files changed, 1557 insertions(+), 1555 deletions(-) diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index c99df6d81..3198e65b6 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -5,6 +5,8 @@ use thiserror::Error; pub use writer::Writer; +const BAKE_PREFIX: &str = "e"; + #[derive(Error, Debug)] pub enum Error { #[error(transparent)] diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index bed97fa7d..7f05d7915 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -701,7 +701,7 @@ impl Writer { } } - Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) + Some(format!("{}{}", super::BAKE_PREFIX, handle.index())) } else { None } @@ -804,7 +804,7 @@ impl Writer { } => { write!(self.out, "{}", level)?; if let Some(expr) = result { - let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); + let name = format!("{}{}", super::BAKE_PREFIX, expr.index()); self.start_named_expr(module, expr, func_ctx, &name)?; self.named_expressions.insert(expr, name); } @@ -827,7 +827,7 @@ impl Writer { result, } => { write!(self.out, "{}", level)?; - let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); + let res_name = format!("{}{}", super::BAKE_PREFIX, result.index()); self.start_named_expr(module, result, func_ctx, &res_name)?; self.named_expressions.insert(result, res_name); diff --git a/src/proc/namer.rs b/src/proc/namer.rs index b8f03b25c..f250fc1f6 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -32,7 +32,7 @@ impl Namer { fn sanitize(&self, string: &str) -> String { let mut base = string .chars() - .skip_while(|c| c.is_numeric()) + .skip_while(|&c| c.is_numeric() || c == '_') .filter(|&c| c.is_ascii_alphanumeric() || c == '_') .collect::(); // close the name by '_' if the re is a number, so that diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index 950979fdd..30cd00291 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -15,10 +15,10 @@ var global: ColorMaterial_color; fn main1() { var color: vec4; - let _e4: vec4 = global.Color; - color = _e4; - let _e6: vec4 = color; - o_Target = _e6; + let e4: vec4 = global.Color; + color = e4; + let e6: vec4 = color; + o_Target = e6; return; } @@ -26,6 +26,6 @@ fn main1() { fn main([[location(0)]] v_Uv: vec2) -> FragmentOutput { v_Uv1 = v_Uv; main1(); - let _e9: vec4 = o_Target; - return FragmentOutput(_e9); + let e9: vec4 = o_Target; + return FragmentOutput(e9); } diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index c495a7232..0d0de959a 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -33,15 +33,15 @@ var gl_Position: vec4; fn main1() { var position: vec3; - let _e10: vec2 = Vertex_Uv1; - v_Uv = _e10; - let _e11: vec3 = Vertex_Position1; - let _e12: vec2 = global2.size; - position = (_e11 * vec3(_e12, 1.0)); - let _e18: mat4x4 = global.ViewProj; - let _e19: mat4x4 = global1.Model; - let _e21: vec3 = position; - gl_Position = ((_e18 * _e19) * vec4(_e21, 1.0)); + let e10: vec2 = Vertex_Uv1; + v_Uv = e10; + let e11: vec3 = Vertex_Position1; + let e12: vec2 = global2.size; + position = (e11 * vec3(e12, 1.0)); + let e18: mat4x4 = global.ViewProj; + let e19: mat4x4 = global1.Model; + let e21: vec3 = position; + gl_Position = ((e18 * e19) * vec4(e21, 1.0)); return; } @@ -51,7 +51,7 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Normal1 = Vertex_Normal; Vertex_Uv1 = Vertex_Uv; main1(); - let _e21: vec2 = v_Uv; - let _e23: vec4 = gl_Position; - return VertexOutput(_e21, _e23); + let e21: vec2 = v_Uv; + let e23: vec4 = gl_Position; + return VertexOutput(e21, e23); } diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 7c94a048f..83495e2ae 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -28,20 +28,20 @@ var global1: Transform; var gl_Position: vec4; fn main1() { - let _e10: mat4x4 = global1.Model; - let _e11: vec3 = Vertex_Normal1; - v_Normal = (_e10 * vec4(_e11, 1.0)).xyz; - let _e16: mat4x4 = global1.Model; - let _e24: vec3 = Vertex_Normal1; - v_Normal = (mat3x3(_e16[0].xyz, _e16[1].xyz, _e16[2].xyz) * _e24); - let _e26: mat4x4 = global1.Model; - let _e27: vec3 = Vertex_Position1; - v_Position = (_e26 * vec4(_e27, 1.0)).xyz; - let _e32: vec2 = Vertex_Uv1; - v_Uv = _e32; - let _e34: mat4x4 = global.ViewProj; - let _e35: vec3 = v_Position; - gl_Position = (_e34 * vec4(_e35, 1.0)); + let e10: mat4x4 = global1.Model; + let e11: vec3 = Vertex_Normal1; + v_Normal = (e10 * vec4(e11, 1.0)).xyz; + let e16: mat4x4 = global1.Model; + let e24: vec3 = Vertex_Normal1; + v_Normal = (mat3x3(e16[0].xyz, e16[1].xyz, e16[2].xyz) * e24); + let e26: mat4x4 = global1.Model; + let e27: vec3 = Vertex_Position1; + v_Position = (e26 * vec4(e27, 1.0)).xyz; + let e32: vec2 = Vertex_Uv1; + v_Uv = e32; + let e34: mat4x4 = global.ViewProj; + let e35: vec3 = v_Position; + gl_Position = (e34 * vec4(e35, 1.0)); return; } @@ -51,9 +51,9 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Normal1 = Vertex_Normal; Vertex_Uv1 = Vertex_Uv; main1(); - let _e23: vec3 = v_Position; - let _e25: vec3 = v_Normal; - let _e27: vec2 = v_Uv; - let _e29: vec4 = gl_Position; - return VertexOutput(_e23, _e25, _e27, _e29); + let e23: vec3 = v_Position; + let e25: vec3 = v_Normal; + let e27: vec2 = v_Uv; + let e29: vec4 = gl_Position; + return VertexOutput(e23, e25, e27, e29); } diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index fe75c08fb..993ec7ff8 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -13,42 +13,42 @@ fn collatz_iterations(n: u32) -> u32 { n1 = n; loop { - let _e7: u32 = n1; - if (!((_e7 != u32(1)))) { + let e7: u32 = n1; + if (!((e7 != u32(1)))) { break; } { - let _e14: u32 = n1; - if (((f32(_e14) % f32(2)) == f32(0))) { + let e14: u32 = n1; + if (((f32(e14) % f32(2)) == f32(0))) { { - let _e22: u32 = n1; - n1 = (_e22 / u32(2)); + let e22: u32 = n1; + n1 = (e22 / u32(2)); } } else { { - let _e27: u32 = n1; - n1 = ((u32(3) * _e27) + u32(1)); + let e27: u32 = n1; + n1 = ((u32(3) * e27) + u32(1)); } } - let _e33: u32 = i; - i = (_e33 + 1u); + let e33: u32 = i; + i = (e33 + 1u); } } - let _e36: u32 = i; - return _e36; + let e36: u32 = i; + return e36; } fn main1() { var index: u32; - let _e3: vec3 = gl_GlobalInvocationID; - index = _e3.x; - let _e6: u32 = index; - let _e8: u32 = index; - let _e11: u32 = index; - let _e13: u32 = global.indices[_e11]; - let _e14: u32 = collatz_iterations(_e13); - global.indices[_e6] = _e14; + let e3: vec3 = gl_GlobalInvocationID; + index = e3.x; + let e6: u32 = index; + let e8: u32 = index; + let e11: u32 = index; + let e13: u32 = global.indices[e11]; + let e14: u32 = collatz_iterations(e13); + global.indices[e6] = e14; return; } diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl index c5676cd28..d3a55eb8e 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl @@ -1,7 +1,7 @@ fn main1() { var a: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let _e1: f32 = f32(1); + let e1: f32 = f32(1); } [[stage(vertex)]] diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index 6046dc3f4..10ae39b3b 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -22,15 +22,15 @@ var frag_color: vec4; var gl_Position: vec4; fn main1() { - let _e7: vec4 = color1; - frag_color = _e7; - let _e9: mat4x4 = global.view_matrix; - let _e10: mat4x4 = global1.world_matrix; - let _e12: vec2 = position1; - gl_Position = ((_e9 * _e10) * vec4(_e12, 0.0, 1.0)); - let _e18: vec4 = gl_Position; - let _e20: vec4 = gl_Position; - gl_Position.z = ((_e18.z + _e20.w) / 2.0); + let e7: vec4 = color1; + frag_color = e7; + let e9: mat4x4 = global.view_matrix; + let e10: mat4x4 = global1.world_matrix; + let e12: vec2 = position1; + gl_Position = ((e9 * e10) * vec4(e12, 0.0, 1.0)); + let e18: vec4 = gl_Position; + let e20: vec4 = gl_Position; + gl_Position.z = ((e18.z + e20.w) / 2.0); return; } @@ -39,7 +39,7 @@ fn main([[location(0)]] position: vec2, [[location(1)]] color: vec4) - position1 = position; color1 = color; main1(); - let _e15: vec4 = frag_color; - let _e17: vec4 = gl_Position; - return VertexOutput(_e15, _e17); + let e15: vec4 = frag_color; + let e17: vec4 = gl_Position; + return VertexOutput(e15, e17); } diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl index a9fc14ab3..a66020fd8 100644 --- a/tests/out/wgsl/932-for-loop-if-vert.wgsl +++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl @@ -2,15 +2,15 @@ fn main1() { var i: i32 = 0; loop { - let _e2: i32 = i; - if (!((_e2 < 1))) { + let e2: i32 = i; + if (!((e2 < 1))) { break; } { } continuing { - let _e6: i32 = i; - i = (_e6 + 1); + let e6: i32 = i; + i = (e6 + 1); } } return; diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index dd0d9b65e..143960419 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -34,22 +34,22 @@ fn atomics() { var tmp: i32; let value: i32 = atomicLoad((&bar.atom)); - let _e6: i32 = atomicAdd((&bar.atom), 5); - tmp = _e6; - let _e9: i32 = atomicSub((&bar.atom), 5); - tmp = _e9; - let _e12: i32 = atomicAnd((&bar.atom), 5); - tmp = _e12; - let _e15: i32 = atomicOr((&bar.atom), 5); - tmp = _e15; - let _e18: i32 = atomicXor((&bar.atom), 5); - tmp = _e18; - let _e21: i32 = atomicMin((&bar.atom), 5); - tmp = _e21; - let _e24: i32 = atomicMax((&bar.atom), 5); - tmp = _e24; - let _e27: i32 = atomicExchange((&bar.atom), 5); - tmp = _e27; + let e6: i32 = atomicAdd((&bar.atom), 5); + tmp = e6; + let e9: i32 = atomicSub((&bar.atom), 5); + tmp = e9; + let e12: i32 = atomicAnd((&bar.atom), 5); + tmp = e12; + let e15: i32 = atomicOr((&bar.atom), 5); + tmp = e15; + let e18: i32 = atomicXor((&bar.atom), 5); + tmp = e18; + let e21: i32 = atomicMin((&bar.atom), 5); + tmp = e21; + let e24: i32 = atomicMax((&bar.atom), 5); + tmp = e24; + let e27: i32 = atomicExchange((&bar.atom), 5); + tmp = e27; atomicStore((&bar.atom), value); return; } diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 8ff5b8823..23ca8a5f1 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -104,13 +104,13 @@ fn pow5_(x: f32) -> f32 { var x2_: f32; x1 = x; - let _e42: f32 = x1; - let _e43: f32 = x1; - x2_ = (_e42 * _e43); - let _e46: f32 = x2_; - let _e47: f32 = x2_; - let _e49: f32 = x1; - return ((_e46 * _e47) * _e49); + let e42: f32 = x1; + let e43: f32 = x1; + x2_ = (e42 * e43); + let e46: f32 = x2_; + let e47: f32 = x2_; + let e49: f32 = x1; + return ((e46 * e47) * e49); } fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 { @@ -122,20 +122,20 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 distanceSquare1 = distanceSquare; inverseRangeSquared1 = inverseRangeSquared; - let _e44: f32 = distanceSquare1; - let _e45: f32 = inverseRangeSquared1; - factor = (_e44 * _e45); - let _e49: f32 = factor; - let _e50: f32 = factor; - let _e56: f32 = factor; - let _e57: f32 = factor; - smoothFactor = clamp((1.0 - (_e56 * _e57)), 0.0, 1.0); - let _e64: f32 = smoothFactor; - let _e65: f32 = smoothFactor; - attenuation = (_e64 * _e65); - let _e68: f32 = attenuation; - let _e73: f32 = distanceSquare1; - return ((_e68 * 1.0) / max(_e73, 0.00009999999747378752)); + let e44: f32 = distanceSquare1; + let e45: f32 = inverseRangeSquared1; + factor = (e44 * e45); + let e49: f32 = factor; + let e50: f32 = factor; + let e56: f32 = factor; + let e57: f32 = factor; + smoothFactor = clamp((1.0 - (e56 * e57)), 0.0, 1.0); + let e64: f32 = smoothFactor; + let e65: f32 = smoothFactor; + attenuation = (e64 * e65); + let e68: f32 = attenuation; + let e73: f32 = distanceSquare1; + return ((e68 * 1.0) / max(e73, 0.00009999999747378752)); } fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { @@ -148,22 +148,22 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { roughness1 = roughness; NoH1 = NoH; - let _e46: f32 = NoH1; - let _e47: f32 = NoH1; - oneMinusNoHSquared = (1.0 - (_e46 * _e47)); - let _e51: f32 = NoH1; - let _e52: f32 = roughness1; - a = (_e51 * _e52); - let _e55: f32 = roughness1; - let _e56: f32 = oneMinusNoHSquared; - let _e57: f32 = a; - let _e58: f32 = a; - k = (_e55 / (_e56 + (_e57 * _e58))); - let _e63: f32 = k; - let _e64: f32 = k; - d = ((_e63 * _e64) * (1.0 / 3.1415927410125732)); - let _e70: f32 = d; - return _e70; + let e46: f32 = NoH1; + let e47: f32 = NoH1; + oneMinusNoHSquared = (1.0 - (e46 * e47)); + let e51: f32 = NoH1; + let e52: f32 = roughness1; + a = (e51 * e52); + let e55: f32 = roughness1; + let e56: f32 = oneMinusNoHSquared; + let e57: f32 = a; + let e58: f32 = a; + k = (e55 / (e56 + (e57 * e58))); + let e63: f32 = k; + let e64: f32 = k; + d = ((e63 * e64) * (1.0 / 3.1415927410125732)); + let e70: f32 = d; + return e70; } fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 { @@ -178,38 +178,38 @@ fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 { roughness3 = roughness2; NoV1 = NoV; NoL1 = NoL; - let _e46: f32 = roughness3; - let _e47: f32 = roughness3; - a2_ = (_e46 * _e47); - let _e50: f32 = NoL1; - let _e51: f32 = NoV1; - let _e52: f32 = a2_; - let _e53: f32 = NoV1; - let _e56: f32 = NoV1; - let _e58: f32 = a2_; - let _e60: f32 = NoV1; - let _e61: f32 = a2_; - let _e62: f32 = NoV1; - let _e65: f32 = NoV1; - let _e67: f32 = a2_; - lambdaV = (_e50 * sqrt((((_e60 - (_e61 * _e62)) * _e65) + _e67))); - let _e72: f32 = NoV1; - let _e73: f32 = NoL1; - let _e74: f32 = a2_; - let _e75: f32 = NoL1; - let _e78: f32 = NoL1; - let _e80: f32 = a2_; - let _e82: f32 = NoL1; - let _e83: f32 = a2_; - let _e84: f32 = NoL1; - let _e87: f32 = NoL1; - let _e89: f32 = a2_; - lambdaL = (_e72 * sqrt((((_e82 - (_e83 * _e84)) * _e87) + _e89))); - let _e95: f32 = lambdaV; - let _e96: f32 = lambdaL; - v = (0.5 / (_e95 + _e96)); - let _e100: f32 = v; - return _e100; + let e46: f32 = roughness3; + let e47: f32 = roughness3; + a2_ = (e46 * e47); + let e50: f32 = NoL1; + let e51: f32 = NoV1; + let e52: f32 = a2_; + let e53: f32 = NoV1; + let e56: f32 = NoV1; + let e58: f32 = a2_; + let e60: f32 = NoV1; + let e61: f32 = a2_; + let e62: f32 = NoV1; + let e65: f32 = NoV1; + let e67: f32 = a2_; + lambdaV = (e50 * sqrt((((e60 - (e61 * e62)) * e65) + e67))); + let e72: f32 = NoV1; + let e73: f32 = NoL1; + let e74: f32 = a2_; + let e75: f32 = NoL1; + let e78: f32 = NoL1; + let e80: f32 = a2_; + let e82: f32 = NoL1; + let e83: f32 = a2_; + let e84: f32 = NoL1; + let e87: f32 = NoL1; + let e89: f32 = a2_; + lambdaL = (e72 * sqrt((((e82 - (e83 * e84)) * e87) + e89))); + let e95: f32 = lambdaV; + let e96: f32 = lambdaL; + v = (0.5 / (e95 + e96)); + let e100: f32 = v; + return e100; } fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { @@ -218,11 +218,11 @@ fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { f90_1 = f90_; VoH1 = VoH; - let _e45: f32 = f90_1; - let _e49: f32 = VoH1; - let _e52: f32 = VoH1; - let _e54: f32 = pow5_((1.0 - _e52)); - return (f0_ + ((vec3(_e45) - f0_) * _e54)); + let e45: f32 = f90_1; + let e49: f32 = VoH1; + let e52: f32 = VoH1; + let e54: f32 = pow5_((1.0 - e52)); + return (f0_ + ((vec3(e45) - f0_) * e54)); } fn F_Schlick1(f0_1: f32, f90_2: f32, VoH2: f32) -> f32 { @@ -233,13 +233,13 @@ fn F_Schlick1(f0_1: f32, f90_2: f32, VoH2: f32) -> f32 { f0_2 = f0_1; f90_3 = f90_2; VoH3 = VoH2; - let _e46: f32 = f0_2; - let _e47: f32 = f90_3; - let _e48: f32 = f0_2; - let _e51: f32 = VoH3; - let _e54: f32 = VoH3; - let _e56: f32 = pow5_((1.0 - _e54)); - return (_e46 + ((_e47 - _e48) * _e56)); + let e46: f32 = f0_2; + let e47: f32 = f90_3; + let e48: f32 = f0_2; + let e51: f32 = VoH3; + let e54: f32 = VoH3; + let e56: f32 = pow5_((1.0 - e54)); + return (e46 + ((e47 - e48) * e56)); } fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { @@ -249,14 +249,14 @@ fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { f0_4 = f0_3; LoH1 = LoH; - let _e49: vec3 = f0_4; - let _e62: vec3 = f0_4; - f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); - let _e75: vec3 = f0_4; - let _e76: f32 = f90_4; - let _e77: f32 = LoH1; - let _e78: vec3 = F_Schlick(_e75, _e76, _e77); - return _e78; + let e49: vec3 = f0_4; + let e62: vec3 = f0_4; + f90_4 = clamp(dot(e62, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); + let e75: vec3 = f0_4; + let e76: f32 = f90_4; + let e77: f32 = LoH1; + let e78: vec3 = F_Schlick(e75, e76, e77); + return e78; } fn specular(f0_5: vec3, roughness4: f32, h1: vec3, NoV2: f32, NoL2: f32, NoH2: f32, LoH2: f32, specularIntensity: f32) -> vec3 { @@ -278,24 +278,24 @@ fn specular(f0_5: vec3, roughness4: f32, h1: vec3, NoV2: f32, NoL2: f3 NoH3 = NoH2; LoH3 = LoH2; specularIntensity1 = specularIntensity; - let _e57: f32 = roughness5; - let _e58: f32 = NoH3; - let _e59: f32 = D_GGX(_e57, _e58, h1); - D = _e59; - let _e64: f32 = roughness5; - let _e65: f32 = NoV3; - let _e66: f32 = NoL3; - let _e67: f32 = V_SmithGGXCorrelated(_e64, _e65, _e66); - V = _e67; - let _e71: vec3 = f0_6; - let _e72: f32 = LoH3; - let _e73: vec3 = fresnel(_e71, _e72); - F = _e73; - let _e75: f32 = specularIntensity1; - let _e76: f32 = D; - let _e78: f32 = V; - let _e80: vec3 = F; - return (((_e75 * _e76) * _e78) * _e80); + let e57: f32 = roughness5; + let e58: f32 = NoH3; + let e59: f32 = D_GGX(e57, e58, h1); + D = e59; + let e64: f32 = roughness5; + let e65: f32 = NoV3; + let e66: f32 = NoL3; + let e67: f32 = V_SmithGGXCorrelated(e64, e65, e66); + V = e67; + let e71: vec3 = f0_6; + let e72: f32 = LoH3; + let e73: vec3 = fresnel(e71, e72); + F = e73; + let e75: f32 = specularIntensity1; + let e76: f32 = D; + let e78: f32 = V; + let e80: vec3 = F; + return (((e75 * e76) * e78) * e80); } fn Fd_Burley(roughness6: f32, NoV4: f32, NoL4: f32, LoH4: f32) -> f32 { @@ -311,21 +311,21 @@ fn Fd_Burley(roughness6: f32, NoV4: f32, NoL4: f32, LoH4: f32) -> f32 { NoV5 = NoV4; NoL5 = NoL4; LoH5 = LoH4; - let _e50: f32 = roughness7; - let _e52: f32 = LoH5; - let _e54: f32 = LoH5; - f90_5 = (0.5 + (((2.0 * _e50) * _e52) * _e54)); - let _e62: f32 = f90_5; - let _e63: f32 = NoL5; - let _e64: f32 = F_Schlick1(1.0, _e62, _e63); - lightScatter = _e64; - let _e70: f32 = f90_5; - let _e71: f32 = NoV5; - let _e72: f32 = F_Schlick1(1.0, _e70, _e71); - viewScatter = _e72; - let _e74: f32 = lightScatter; - let _e75: f32 = viewScatter; - return ((_e74 * _e75) * (1.0 / 3.1415927410125732)); + let e50: f32 = roughness7; + let e52: f32 = LoH5; + let e54: f32 = LoH5; + f90_5 = (0.5 + (((2.0 * e50) * e52) * e54)); + let e62: f32 = f90_5; + let e63: f32 = NoL5; + let e64: f32 = F_Schlick1(1.0, e62, e63); + lightScatter = e64; + let e70: f32 = f90_5; + let e71: f32 = NoV5; + let e72: f32 = F_Schlick1(1.0, e70, e71); + viewScatter = e72; + let e74: f32 = lightScatter; + let e75: f32 = viewScatter; + return ((e74 * e75) * (1.0 / 3.1415927410125732)); } fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV6: f32) -> vec3 { @@ -341,28 +341,28 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV6: f32) -> vec3< f0_8 = f0_7; perceptual_roughness1 = perceptual_roughness; NoV7 = NoV6; - let _e62: f32 = perceptual_roughness1; - let _e64: vec4 = c0_; - let _e66: vec4 = c1_; - r = ((vec4(_e62) * _e64) + _e66); - let _e69: vec4 = r; - let _e71: vec4 = r; - let _e76: f32 = NoV7; - let _e80: f32 = NoV7; - let _e83: vec4 = r; - let _e85: vec4 = r; - let _e90: f32 = NoV7; - let _e94: f32 = NoV7; - let _e98: vec4 = r; - let _e101: vec4 = r; - a004_ = ((min((_e83.x * _e85.x), exp2((-(9.279999732971191) * _e94))) * _e98.x) + _e101.y); - let _e109: f32 = a004_; - let _e112: vec4 = r; - AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(_e109)) + _e112.zw); - let _e116: vec3 = f0_8; - let _e117: vec2 = AB; - let _e121: vec2 = AB; - return ((_e116 * vec3(_e117.x)) + vec3(_e121.y)); + let e62: f32 = perceptual_roughness1; + let e64: vec4 = c0_; + let e66: vec4 = c1_; + r = ((vec4(e62) * e64) + e66); + let e69: vec4 = r; + let e71: vec4 = r; + let e76: f32 = NoV7; + let e80: f32 = NoV7; + let e83: vec4 = r; + let e85: vec4 = r; + let e90: f32 = NoV7; + let e94: f32 = NoV7; + let e98: vec4 = r; + let e101: vec4 = r; + a004_ = ((min((e83.x * e85.x), exp2((-(9.279999732971191) * e94))) * e98.x) + e101.y); + let e109: f32 = a004_; + let e112: vec4 = r; + AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(e109)) + e112.zw); + let e116: vec3 = f0_8; + let e117: vec2 = AB; + let e121: vec2 = AB; + return ((e116 * vec3(e117.x)) + vec3(e121.y)); } fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { @@ -370,20 +370,20 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { var clampedPerceptualRoughness: f32; perceptualRoughness1 = perceptualRoughness; - let _e45: f32 = perceptualRoughness1; - clampedPerceptualRoughness = clamp(_e45, 0.08900000154972076, 1.0); - let _e50: f32 = clampedPerceptualRoughness; - let _e51: f32 = clampedPerceptualRoughness; - return (_e50 * _e51); + let e45: f32 = perceptualRoughness1; + clampedPerceptualRoughness = clamp(e45, 0.08900000154972076, 1.0); + let e50: f32 = clampedPerceptualRoughness; + let e51: f32 = clampedPerceptualRoughness; + return (e50 * e51); } fn reinhard(color: vec3) -> vec3 { var color1: vec3; color1 = color; - let _e42: vec3 = color1; - let _e45: vec3 = color1; - return (_e42 / (vec3(1.0) + _e45)); + let e42: vec3 = color1; + let e45: vec3 = color1; + return (e42 / (vec3(1.0) + e45)); } fn reinhard_extended(color2: vec3, max_white: f32) -> vec3 { @@ -393,22 +393,22 @@ fn reinhard_extended(color2: vec3, max_white: f32) -> vec3 { color3 = color2; max_white1 = max_white; - let _e44: vec3 = color3; - let _e47: vec3 = color3; - let _e48: f32 = max_white1; - let _e49: f32 = max_white1; - numerator = (_e44 * (vec3(1.0) + (_e47 / vec3((_e48 * _e49))))); - let _e56: vec3 = numerator; - let _e59: vec3 = color3; - return (_e56 / (vec3(1.0) + _e59)); + let e44: vec3 = color3; + let e47: vec3 = color3; + let e48: f32 = max_white1; + let e49: f32 = max_white1; + numerator = (e44 * (vec3(1.0) + (e47 / vec3((e48 * e49))))); + let e56: vec3 = numerator; + let e59: vec3 = color3; + return (e56 / (vec3(1.0) + e59)); } fn luminance(v1: vec3) -> f32 { var v2: vec3; v2 = v1; - let _e47: vec3 = v2; - return dot(_e47, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); + let e47: vec3 = v2; + return dot(e47, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); } fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { @@ -418,13 +418,13 @@ fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { c_in1 = c_in; l_out1 = l_out; - let _e45: vec3 = c_in1; - let _e46: f32 = luminance(_e45); - l_in = _e46; - let _e48: vec3 = c_in1; - let _e49: f32 = l_out1; - let _e50: f32 = l_in; - return (_e48 * (_e49 / _e50)); + let e45: vec3 = c_in1; + let e46: f32 = luminance(e45); + l_in = e46; + let e48: vec3 = c_in1; + let e49: f32 = l_out1; + let e50: f32 = l_in; + return (e48 * (e49 / e50)); } fn reinhard_luminance(color4: vec3) -> vec3 { @@ -433,16 +433,16 @@ fn reinhard_luminance(color4: vec3) -> vec3 { var l_new: f32; color5 = color4; - let _e43: vec3 = color5; - let _e44: f32 = luminance(_e43); - l_old = _e44; - let _e46: f32 = l_old; - let _e48: f32 = l_old; - l_new = (_e46 / (1.0 + _e48)); - let _e54: vec3 = color5; - let _e55: f32 = l_new; - let _e56: vec3 = change_luminance(_e54, _e55); - return _e56; + let e43: vec3 = color5; + let e44: f32 = luminance(e43); + l_old = e44; + let e46: f32 = l_old; + let e48: f32 = l_old; + l_new = (e46 / (1.0 + e48)); + let e54: vec3 = color5; + let e55: f32 = l_new; + let e56: vec3 = change_luminance(e54, e55); + return e56; } fn reinhard_extended_luminance(color6: vec3, max_white_l: f32) -> vec3 { @@ -454,21 +454,21 @@ fn reinhard_extended_luminance(color6: vec3, max_white_l: f32) -> vec3 color7 = color6; max_white_l1 = max_white_l; - let _e45: vec3 = color7; - let _e46: f32 = luminance(_e45); - l_old1 = _e46; - let _e48: f32 = l_old1; - let _e50: f32 = l_old1; - let _e51: f32 = max_white_l1; - let _e52: f32 = max_white_l1; - numerator1 = (_e48 * (1.0 + (_e50 / (_e51 * _e52)))); - let _e58: f32 = numerator1; - let _e60: f32 = l_old1; - l_new1 = (_e58 / (1.0 + _e60)); - let _e66: vec3 = color7; - let _e67: f32 = l_new1; - let _e68: vec3 = change_luminance(_e66, _e67); - return _e68; + let e45: vec3 = color7; + let e46: f32 = luminance(e45); + l_old1 = e46; + let e48: f32 = l_old1; + let e50: f32 = l_old1; + let e51: f32 = max_white_l1; + let e52: f32 = max_white_l1; + numerator1 = (e48 * (1.0 + (e50 / (e51 * e52)))); + let e58: f32 = numerator1; + let e60: f32 = l_old1; + l_new1 = (e58 / (1.0 + e60)); + let e66: vec3 = color7; + let e67: f32 = l_new1; + let e68: vec3 = change_luminance(e66, e67); + return e68; } fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: vec3, R: vec3, F0_: vec3, diffuseColor: vec3) -> vec3 { @@ -506,123 +506,123 @@ fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: R1 = R; F0_1 = F0_; diffuseColor1 = diffuseColor; - let _e56: PointLight = light1; - let _e59: vec3 = v_WorldPosition1; - light_to_frag = (_e56.pos.xyz - _e59.xyz); - let _e65: vec3 = light_to_frag; - let _e66: vec3 = light_to_frag; - distance_square = dot(_e65, _e66); - let _e70: PointLight = light1; - let _e73: f32 = distance_square; - let _e74: PointLight = light1; - let _e77: f32 = getDistanceAttenuation(_e73, _e74.lightParams.x); - rangeAttenuation = _e77; - let _e79: f32 = roughness9; - a1 = _e79; - let _e81: PointLight = light1; - radius = _e81.lightParams.y; - let _e87: vec3 = light_to_frag; - let _e88: vec3 = R1; - let _e90: vec3 = R1; - let _e92: vec3 = light_to_frag; - centerToRay = ((dot(_e87, _e88) * _e90) - _e92); - let _e95: vec3 = light_to_frag; - let _e96: vec3 = centerToRay; - let _e97: f32 = radius; - let _e100: vec3 = centerToRay; - let _e101: vec3 = centerToRay; - let _e105: vec3 = centerToRay; - let _e106: vec3 = centerToRay; - let _e112: f32 = radius; - let _e115: vec3 = centerToRay; - let _e116: vec3 = centerToRay; - let _e120: vec3 = centerToRay; - let _e121: vec3 = centerToRay; - closestPoint = (_e95 + (_e96 * clamp((_e112 * inverseSqrt(dot(_e120, _e121))), 0.0, 1.0))); - let _e133: vec3 = closestPoint; - let _e134: vec3 = closestPoint; - let _e138: vec3 = closestPoint; - let _e139: vec3 = closestPoint; - LspecLengthInverse = inverseSqrt(dot(_e138, _e139)); - let _e143: f32 = a1; - let _e144: f32 = a1; - let _e145: f32 = radius; - let _e148: f32 = LspecLengthInverse; - let _e153: f32 = a1; - let _e154: f32 = radius; - let _e157: f32 = LspecLengthInverse; - normalizationFactor = (_e143 / clamp((_e153 + ((_e154 * 0.5) * _e157)), 0.0, 1.0)); - let _e165: f32 = normalizationFactor; - let _e166: f32 = normalizationFactor; - specularIntensity2 = (_e165 * _e166); - let _e169: vec3 = closestPoint; - let _e170: f32 = LspecLengthInverse; - L = (_e169 * _e170); - let _e173: vec3 = L; - let _e174: vec3 = V2; - let _e176: vec3 = L; - let _e177: vec3 = V2; - H = normalize((_e176 + _e177)); - let _e183: vec3 = N1; - let _e184: vec3 = L; - let _e190: vec3 = N1; - let _e191: vec3 = L; - NoL6 = clamp(dot(_e190, _e191), 0.0, 1.0); - let _e199: vec3 = N1; - let _e200: vec3 = H; - let _e206: vec3 = N1; - let _e207: vec3 = H; - NoH4 = clamp(dot(_e206, _e207), 0.0, 1.0); - let _e215: vec3 = L; - let _e216: vec3 = H; - let _e222: vec3 = L; - let _e223: vec3 = H; - LoH6 = clamp(dot(_e222, _e223), 0.0, 1.0); - let _e237: vec3 = F0_1; - let _e238: f32 = roughness9; - let _e239: vec3 = H; - let _e240: f32 = NdotV1; - let _e241: f32 = NoL6; - let _e242: f32 = NoH4; - let _e243: f32 = LoH6; - let _e244: f32 = specularIntensity2; - let _e245: vec3 = specular(_e237, _e238, _e239, _e240, _e241, _e242, _e243, _e244); - specular1 = _e245; - let _e248: vec3 = light_to_frag; - L = normalize(_e248); - let _e250: vec3 = L; - let _e251: vec3 = V2; - let _e253: vec3 = L; - let _e254: vec3 = V2; - H = normalize((_e253 + _e254)); - let _e259: vec3 = N1; - let _e260: vec3 = L; - let _e266: vec3 = N1; - let _e267: vec3 = L; - NoL6 = clamp(dot(_e266, _e267), 0.0, 1.0); - let _e274: vec3 = N1; - let _e275: vec3 = H; - let _e281: vec3 = N1; - let _e282: vec3 = H; - NoH4 = clamp(dot(_e281, _e282), 0.0, 1.0); - let _e289: vec3 = L; - let _e290: vec3 = H; - let _e296: vec3 = L; - let _e297: vec3 = H; - LoH6 = clamp(dot(_e296, _e297), 0.0, 1.0); - let _e302: vec3 = diffuseColor1; - let _e307: f32 = roughness9; - let _e308: f32 = NdotV1; - let _e309: f32 = NoL6; - let _e310: f32 = LoH6; - let _e311: f32 = Fd_Burley(_e307, _e308, _e309, _e310); - diffuse = (_e302 * _e311); - let _e314: vec3 = diffuse; - let _e315: vec3 = specular1; - let _e317: PointLight = light1; - let _e321: f32 = rangeAttenuation; - let _e322: f32 = NoL6; - return (((_e314 + _e315) * _e317.color.xyz) * (_e321 * _e322)); + let e56: PointLight = light1; + let e59: vec3 = v_WorldPosition1; + light_to_frag = (e56.pos.xyz - e59.xyz); + let e65: vec3 = light_to_frag; + let e66: vec3 = light_to_frag; + distance_square = dot(e65, e66); + let e70: PointLight = light1; + let e73: f32 = distance_square; + let e74: PointLight = light1; + let e77: f32 = getDistanceAttenuation(e73, e74.lightParams.x); + rangeAttenuation = e77; + let e79: f32 = roughness9; + a1 = e79; + let e81: PointLight = light1; + radius = e81.lightParams.y; + let e87: vec3 = light_to_frag; + let e88: vec3 = R1; + let e90: vec3 = R1; + let e92: vec3 = light_to_frag; + centerToRay = ((dot(e87, e88) * e90) - e92); + let e95: vec3 = light_to_frag; + let e96: vec3 = centerToRay; + let e97: f32 = radius; + let e100: vec3 = centerToRay; + let e101: vec3 = centerToRay; + let e105: vec3 = centerToRay; + let e106: vec3 = centerToRay; + let e112: f32 = radius; + let e115: vec3 = centerToRay; + let e116: vec3 = centerToRay; + let e120: vec3 = centerToRay; + let e121: vec3 = centerToRay; + closestPoint = (e95 + (e96 * clamp((e112 * inverseSqrt(dot(e120, e121))), 0.0, 1.0))); + let e133: vec3 = closestPoint; + let e134: vec3 = closestPoint; + let e138: vec3 = closestPoint; + let e139: vec3 = closestPoint; + LspecLengthInverse = inverseSqrt(dot(e138, e139)); + let e143: f32 = a1; + let e144: f32 = a1; + let e145: f32 = radius; + let e148: f32 = LspecLengthInverse; + let e153: f32 = a1; + let e154: f32 = radius; + let e157: f32 = LspecLengthInverse; + normalizationFactor = (e143 / clamp((e153 + ((e154 * 0.5) * e157)), 0.0, 1.0)); + let e165: f32 = normalizationFactor; + let e166: f32 = normalizationFactor; + specularIntensity2 = (e165 * e166); + let e169: vec3 = closestPoint; + let e170: f32 = LspecLengthInverse; + L = (e169 * e170); + let e173: vec3 = L; + let e174: vec3 = V2; + let e176: vec3 = L; + let e177: vec3 = V2; + H = normalize((e176 + e177)); + let e183: vec3 = N1; + let e184: vec3 = L; + let e190: vec3 = N1; + let e191: vec3 = L; + NoL6 = clamp(dot(e190, e191), 0.0, 1.0); + let e199: vec3 = N1; + let e200: vec3 = H; + let e206: vec3 = N1; + let e207: vec3 = H; + NoH4 = clamp(dot(e206, e207), 0.0, 1.0); + let e215: vec3 = L; + let e216: vec3 = H; + let e222: vec3 = L; + let e223: vec3 = H; + LoH6 = clamp(dot(e222, e223), 0.0, 1.0); + let e237: vec3 = F0_1; + let e238: f32 = roughness9; + let e239: vec3 = H; + let e240: f32 = NdotV1; + let e241: f32 = NoL6; + let e242: f32 = NoH4; + let e243: f32 = LoH6; + let e244: f32 = specularIntensity2; + let e245: vec3 = specular(e237, e238, e239, e240, e241, e242, e243, e244); + specular1 = e245; + let e248: vec3 = light_to_frag; + L = normalize(e248); + let e250: vec3 = L; + let e251: vec3 = V2; + let e253: vec3 = L; + let e254: vec3 = V2; + H = normalize((e253 + e254)); + let e259: vec3 = N1; + let e260: vec3 = L; + let e266: vec3 = N1; + let e267: vec3 = L; + NoL6 = clamp(dot(e266, e267), 0.0, 1.0); + let e274: vec3 = N1; + let e275: vec3 = H; + let e281: vec3 = N1; + let e282: vec3 = H; + NoH4 = clamp(dot(e281, e282), 0.0, 1.0); + let e289: vec3 = L; + let e290: vec3 = H; + let e296: vec3 = L; + let e297: vec3 = H; + LoH6 = clamp(dot(e296, e297), 0.0, 1.0); + let e302: vec3 = diffuseColor1; + let e307: f32 = roughness9; + let e308: f32 = NdotV1; + let e309: f32 = NoL6; + let e310: f32 = LoH6; + let e311: f32 = Fd_Burley(e307, e308, e309, e310); + diffuse = (e302 * e311); + let e314: vec3 = diffuse; + let e315: vec3 = specular1; + let e317: PointLight = light1; + let e321: f32 = rangeAttenuation; + let e322: f32 = NoL6; + return (((e314 + e315) * e317.color.xyz) * (e321 * e322)); } fn dir_light(light2: DirectionalLight, roughness10: f32, NdotV2: f32, normal: vec3, view: vec3, R2: vec3, F0_2: vec3, diffuseColor2: vec3) -> vec3 { @@ -651,50 +651,50 @@ fn dir_light(light2: DirectionalLight, roughness10: f32, NdotV2: f32, normal: ve R3 = R2; F0_3 = F0_2; diffuseColor3 = diffuseColor2; - let _e56: DirectionalLight = light3; - incident_light = _e56.direction.xyz; - let _e60: vec3 = incident_light; - let _e61: vec3 = view1; - let _e63: vec3 = incident_light; - let _e64: vec3 = view1; - half_vector = normalize((_e63 + _e64)); - let _e70: vec3 = normal1; - let _e71: vec3 = incident_light; - let _e77: vec3 = normal1; - let _e78: vec3 = incident_light; - NoL7 = clamp(dot(_e77, _e78), 0.0, 1.0); - let _e86: vec3 = normal1; - let _e87: vec3 = half_vector; - let _e93: vec3 = normal1; - let _e94: vec3 = half_vector; - NoH5 = clamp(dot(_e93, _e94), 0.0, 1.0); - let _e102: vec3 = incident_light; - let _e103: vec3 = half_vector; - let _e109: vec3 = incident_light; - let _e110: vec3 = half_vector; - LoH7 = clamp(dot(_e109, _e110), 0.0, 1.0); - let _e116: vec3 = diffuseColor3; - let _e121: f32 = roughness11; - let _e122: f32 = NdotV3; - let _e123: f32 = NoL7; - let _e124: f32 = LoH7; - let _e125: f32 = Fd_Burley(_e121, _e122, _e123, _e124); - diffuse1 = (_e116 * _e125); - let _e138: vec3 = F0_3; - let _e139: f32 = roughness11; - let _e140: vec3 = half_vector; - let _e141: f32 = NdotV3; - let _e142: f32 = NoL7; - let _e143: f32 = NoH5; - let _e144: f32 = LoH7; - let _e145: f32 = specularIntensity3; - let _e146: vec3 = specular(_e138, _e139, _e140, _e141, _e142, _e143, _e144, _e145); - specular2 = _e146; - let _e148: vec3 = specular2; - let _e149: vec3 = diffuse1; - let _e151: DirectionalLight = light3; - let _e155: f32 = NoL7; - return (((_e148 + _e149) * _e151.color.xyz) * _e155); + let e56: DirectionalLight = light3; + incident_light = e56.direction.xyz; + let e60: vec3 = incident_light; + let e61: vec3 = view1; + let e63: vec3 = incident_light; + let e64: vec3 = view1; + half_vector = normalize((e63 + e64)); + let e70: vec3 = normal1; + let e71: vec3 = incident_light; + let e77: vec3 = normal1; + let e78: vec3 = incident_light; + NoL7 = clamp(dot(e77, e78), 0.0, 1.0); + let e86: vec3 = normal1; + let e87: vec3 = half_vector; + let e93: vec3 = normal1; + let e94: vec3 = half_vector; + NoH5 = clamp(dot(e93, e94), 0.0, 1.0); + let e102: vec3 = incident_light; + let e103: vec3 = half_vector; + let e109: vec3 = incident_light; + let e110: vec3 = half_vector; + LoH7 = clamp(dot(e109, e110), 0.0, 1.0); + let e116: vec3 = diffuseColor3; + let e121: f32 = roughness11; + let e122: f32 = NdotV3; + let e123: f32 = NoL7; + let e124: f32 = LoH7; + let e125: f32 = Fd_Burley(e121, e122, e123, e124); + diffuse1 = (e116 * e125); + let e138: vec3 = F0_3; + let e139: f32 = roughness11; + let e140: vec3 = half_vector; + let e141: f32 = NdotV3; + let e142: f32 = NoL7; + let e143: f32 = NoH5; + let e144: f32 = LoH7; + let e145: f32 = specularIntensity3; + let e146: vec3 = specular(e138, e139, e140, e141, e142, e143, e144, e145); + specular2 = e146; + let e148: vec3 = specular2; + let e149: vec3 = diffuse1; + let e151: DirectionalLight = light3; + let e155: f32 = NoL7; + return (((e148 + e149) * e151.color.xyz) * e155); } fn main1() { @@ -720,186 +720,186 @@ fn main1() { var diffuse_ambient: vec3; var specular_ambient: vec3; - let _e40: vec4 = global3.base_color; - output_color = _e40; - let _e42: vec4 = output_color; - let _e44: vec2 = v_Uv1; - let _e45: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e44); - output_color = (_e42 * _e45); - let _e48: vec2 = v_Uv1; - let _e49: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e48); - metallic_roughness = _e49; - let _e51: f32 = global5.metallic; - let _e52: vec4 = metallic_roughness; - metallic = (_e51 * _e52.z); - let _e56: f32 = global4.perceptual_roughness; - let _e57: vec4 = metallic_roughness; - perceptual_roughness2 = (_e56 * _e57.y); - let _e62: f32 = perceptual_roughness2; - let _e63: f32 = perceptualRoughnessToRoughness(_e62); - roughness12 = _e63; - let _e66: vec3 = v_WorldNormal1; - N2 = normalize(_e66); - let _e69: vec4 = v_WorldTangent1; - let _e71: vec4 = v_WorldTangent1; - T = normalize(_e71.xyz); - let _e77: vec3 = N2; - let _e78: vec3 = T; - let _e80: vec4 = v_WorldTangent1; - B = (cross(_e77, _e78) * _e80.w); - let _e85: bool = gl_FrontFacing; - let _e86: vec3 = N2; - let _e87: vec3 = N2; - N2 = select(-(_e87), _e86, _e85); - let _e90: bool = gl_FrontFacing; - let _e91: vec3 = T; - let _e92: vec3 = T; - T = select(-(_e92), _e91, _e90); - let _e95: bool = gl_FrontFacing; - let _e96: vec3 = B; - let _e97: vec3 = B; - B = select(-(_e97), _e96, _e95); - let _e100: vec3 = T; - let _e101: vec3 = B; - let _e102: vec3 = N2; - TBN = mat3x3(vec3(_e100.x, _e100.y, _e100.z), vec3(_e101.x, _e101.y, _e101.z), vec3(_e102.x, _e102.y, _e102.z)); - let _e117: mat3x3 = TBN; - let _e119: vec2 = v_Uv1; - let _e120: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e119); - let _e128: vec2 = v_Uv1; - let _e129: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e128); - N2 = (_e117 * normalize(((_e129.xyz * 2.0) - vec3(1.0)))); - let _e139: vec2 = v_Uv1; - let _e140: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e139); - occlusion = _e140.x; - let _e143: vec4 = global7.emissive; - emissive = _e143; - let _e145: vec4 = emissive; - let _e147: vec4 = emissive; - let _e150: vec2 = v_Uv1; - let _e151: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e150); - let _e153: vec3 = (_e147.xyz * _e151.xyz); - emissive.x = _e153.x; - emissive.y = _e153.y; - emissive.z = _e153.z; - let _e160: vec4 = global1.CameraPos; - let _e162: vec3 = v_WorldPosition1; - let _e165: vec4 = global1.CameraPos; - let _e167: vec3 = v_WorldPosition1; - V3 = normalize((_e165.xyz - _e167.xyz)); - let _e174: vec3 = N2; - let _e175: vec3 = V3; - let _e180: vec3 = N2; - let _e181: vec3 = V3; - NdotV4 = max(dot(_e180, _e181), 0.00009999999747378752); - let _e187: f32 = global6.reflectance; - let _e189: f32 = global6.reflectance; - let _e192: f32 = metallic; - let _e196: vec4 = output_color; - let _e198: f32 = metallic; - F0_4 = (vec3((((0.1599999964237213 * _e187) * _e189) * (1.0 - _e192))) + (_e196.xyz * vec3(_e198))); - let _e203: vec4 = output_color; - let _e206: f32 = metallic; - diffuseColor4 = (_e203.xyz * vec3((1.0 - _e206))); - let _e211: vec3 = V3; - let _e214: vec3 = V3; - let _e216: vec3 = N2; - R4 = reflect(-(_e214), _e216); + let e40: vec4 = global3.base_color; + output_color = e40; + let e42: vec4 = output_color; + let e44: vec2 = v_Uv1; + let e45: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, e44); + output_color = (e42 * e45); + let e48: vec2 = v_Uv1; + let e49: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, e48); + metallic_roughness = e49; + let e51: f32 = global5.metallic; + let e52: vec4 = metallic_roughness; + metallic = (e51 * e52.z); + let e56: f32 = global4.perceptual_roughness; + let e57: vec4 = metallic_roughness; + perceptual_roughness2 = (e56 * e57.y); + let e62: f32 = perceptual_roughness2; + let e63: f32 = perceptualRoughnessToRoughness(e62); + roughness12 = e63; + let e66: vec3 = v_WorldNormal1; + N2 = normalize(e66); + let e69: vec4 = v_WorldTangent1; + let e71: vec4 = v_WorldTangent1; + T = normalize(e71.xyz); + let e77: vec3 = N2; + let e78: vec3 = T; + let e80: vec4 = v_WorldTangent1; + B = (cross(e77, e78) * e80.w); + let e85: bool = gl_FrontFacing; + let e86: vec3 = N2; + let e87: vec3 = N2; + N2 = select(-(e87), e86, e85); + let e90: bool = gl_FrontFacing; + let e91: vec3 = T; + let e92: vec3 = T; + T = select(-(e92), e91, e90); + let e95: bool = gl_FrontFacing; + let e96: vec3 = B; + let e97: vec3 = B; + B = select(-(e97), e96, e95); + let e100: vec3 = T; + let e101: vec3 = B; + let e102: vec3 = N2; + TBN = mat3x3(vec3(e100.x, e100.y, e100.z), vec3(e101.x, e101.y, e101.z), vec3(e102.x, e102.y, e102.z)); + let e117: mat3x3 = TBN; + let e119: vec2 = v_Uv1; + let e120: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e119); + let e128: vec2 = v_Uv1; + let e129: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e128); + N2 = (e117 * normalize(((e129.xyz * 2.0) - vec3(1.0)))); + let e139: vec2 = v_Uv1; + let e140: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, e139); + occlusion = e140.x; + let e143: vec4 = global7.emissive; + emissive = e143; + let e145: vec4 = emissive; + let e147: vec4 = emissive; + let e150: vec2 = v_Uv1; + let e151: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, e150); + let e153: vec3 = (e147.xyz * e151.xyz); + emissive.x = e153.x; + emissive.y = e153.y; + emissive.z = e153.z; + let e160: vec4 = global1.CameraPos; + let e162: vec3 = v_WorldPosition1; + let e165: vec4 = global1.CameraPos; + let e167: vec3 = v_WorldPosition1; + V3 = normalize((e165.xyz - e167.xyz)); + let e174: vec3 = N2; + let e175: vec3 = V3; + let e180: vec3 = N2; + let e181: vec3 = V3; + NdotV4 = max(dot(e180, e181), 0.00009999999747378752); + let e187: f32 = global6.reflectance; + let e189: f32 = global6.reflectance; + let e192: f32 = metallic; + let e196: vec4 = output_color; + let e198: f32 = metallic; + F0_4 = (vec3((((0.1599999964237213 * e187) * e189) * (1.0 - e192))) + (e196.xyz * vec3(e198))); + let e203: vec4 = output_color; + let e206: f32 = metallic; + diffuseColor4 = (e203.xyz * vec3((1.0 - e206))); + let e211: vec3 = V3; + let e214: vec3 = V3; + let e216: vec3 = N2; + R4 = reflect(-(e214), e216); loop { - let _e224: i32 = i; - let _e225: vec4 = global2.NumLights; - let _e229: i32 = i; - if (!(((_e224 < i32(_e225.x)) && (_e229 < 10)))) { + let e224: i32 = i; + let e225: vec4 = global2.NumLights; + let e229: i32 = i; + if (!(((e224 < i32(e225.x)) && (e229 < 10)))) { break; } { - let _e236: vec3 = light_accum; - let _e237: i32 = i; - let _e247: i32 = i; - let _e249: PointLight = global2.PointLights[_e247]; - let _e250: f32 = roughness12; - let _e251: f32 = NdotV4; - let _e252: vec3 = N2; - let _e253: vec3 = V3; - let _e254: vec3 = R4; - let _e255: vec3 = F0_4; - let _e256: vec3 = diffuseColor4; - let _e257: vec3 = point_light(_e249, _e250, _e251, _e252, _e253, _e254, _e255, _e256); - light_accum = (_e236 + _e257); + let e236: vec3 = light_accum; + let e237: i32 = i; + let e247: i32 = i; + let e249: PointLight = global2.PointLights[e247]; + let e250: f32 = roughness12; + let e251: f32 = NdotV4; + let e252: vec3 = N2; + let e253: vec3 = V3; + let e254: vec3 = R4; + let e255: vec3 = F0_4; + let e256: vec3 = diffuseColor4; + let e257: vec3 = point_light(e249, e250, e251, e252, e253, e254, e255, e256); + light_accum = (e236 + e257); } continuing { - let _e233: i32 = i; - i = (_e233 + 1); + let e233: i32 = i; + i = (e233 + 1); } } loop { - let _e261: i32 = i1; - let _e262: vec4 = global2.NumLights; - let _e266: i32 = i1; - if (!(((_e261 < i32(_e262.y)) && (_e266 < 1)))) { + let e261: i32 = i1; + let e262: vec4 = global2.NumLights; + let e266: i32 = i1; + if (!(((e261 < i32(e262.y)) && (e266 < 1)))) { break; } { - let _e273: vec3 = light_accum; - let _e274: i32 = i1; - let _e284: i32 = i1; - let _e286: DirectionalLight = global2.DirectionalLights[_e284]; - let _e287: f32 = roughness12; - let _e288: f32 = NdotV4; - let _e289: vec3 = N2; - let _e290: vec3 = V3; - let _e291: vec3 = R4; - let _e292: vec3 = F0_4; - let _e293: vec3 = diffuseColor4; - let _e294: vec3 = dir_light(_e286, _e287, _e288, _e289, _e290, _e291, _e292, _e293); - light_accum = (_e273 + _e294); + let e273: vec3 = light_accum; + let e274: i32 = i1; + let e284: i32 = i1; + let e286: DirectionalLight = global2.DirectionalLights[e284]; + let e287: f32 = roughness12; + let e288: f32 = NdotV4; + let e289: vec3 = N2; + let e290: vec3 = V3; + let e291: vec3 = R4; + let e292: vec3 = F0_4; + let e293: vec3 = diffuseColor4; + let e294: vec3 = dir_light(e286, e287, e288, e289, e290, e291, e292, e293); + light_accum = (e273 + e294); } continuing { - let _e270: i32 = i1; - i1 = (_e270 + 1); + let e270: i32 = i1; + i1 = (e270 + 1); } } - let _e299: vec3 = diffuseColor4; - let _e301: f32 = NdotV4; - let _e302: vec3 = EnvBRDFApprox(_e299, 1.0, _e301); - diffuse_ambient = _e302; - let _e307: vec3 = F0_4; - let _e308: f32 = perceptual_roughness2; - let _e309: f32 = NdotV4; - let _e310: vec3 = EnvBRDFApprox(_e307, _e308, _e309); - specular_ambient = _e310; - let _e312: vec4 = output_color; - let _e314: vec3 = light_accum; - output_color.x = _e314.x; - output_color.y = _e314.y; - output_color.z = _e314.z; - let _e321: vec4 = output_color; - let _e323: vec4 = output_color; - let _e325: vec3 = diffuse_ambient; - let _e326: vec3 = specular_ambient; - let _e328: vec4 = global2.AmbientColor; - let _e331: f32 = occlusion; - let _e333: vec3 = (_e323.xyz + (((_e325 + _e326) * _e328.xyz) * _e331)); - output_color.x = _e333.x; - output_color.y = _e333.y; - output_color.z = _e333.z; - let _e340: vec4 = output_color; - let _e342: vec4 = output_color; - let _e344: vec4 = emissive; - let _e346: vec4 = output_color; - let _e349: vec3 = (_e342.xyz + (_e344.xyz * _e346.w)); - output_color.x = _e349.x; - output_color.y = _e349.y; - output_color.z = _e349.z; - let _e356: vec4 = output_color; - let _e358: vec4 = output_color; - let _e360: vec4 = output_color; - let _e362: vec3 = reinhard_luminance(_e360.xyz); - output_color.x = _e362.x; - output_color.y = _e362.y; - output_color.z = _e362.z; - let _e369: vec4 = output_color; - o_Target = _e369; + let e299: vec3 = diffuseColor4; + let e301: f32 = NdotV4; + let e302: vec3 = EnvBRDFApprox(e299, 1.0, e301); + diffuse_ambient = e302; + let e307: vec3 = F0_4; + let e308: f32 = perceptual_roughness2; + let e309: f32 = NdotV4; + let e310: vec3 = EnvBRDFApprox(e307, e308, e309); + specular_ambient = e310; + let e312: vec4 = output_color; + let e314: vec3 = light_accum; + output_color.x = e314.x; + output_color.y = e314.y; + output_color.z = e314.z; + let e321: vec4 = output_color; + let e323: vec4 = output_color; + let e325: vec3 = diffuse_ambient; + let e326: vec3 = specular_ambient; + let e328: vec4 = global2.AmbientColor; + let e331: f32 = occlusion; + let e333: vec3 = (e323.xyz + (((e325 + e326) * e328.xyz) * e331)); + output_color.x = e333.x; + output_color.y = e333.y; + output_color.z = e333.z; + let e340: vec4 = output_color; + let e342: vec4 = output_color; + let e344: vec4 = emissive; + let e346: vec4 = output_color; + let e349: vec3 = (e342.xyz + (e344.xyz * e346.w)); + output_color.x = e349.x; + output_color.y = e349.y; + output_color.z = e349.z; + let e356: vec4 = output_color; + let e358: vec4 = output_color; + let e360: vec4 = output_color; + let e362: vec3 = reinhard_luminance(e360.xyz); + output_color.x = e362.x; + output_color.y = e362.y; + output_color.z = e362.z; + let e369: vec4 = output_color; + o_Target = e369; return; } @@ -911,6 +911,6 @@ fn main([[location(0)]] v_WorldPosition: vec3, [[location(1)]] v_WorldNorma v_WorldTangent1 = v_WorldTangent; gl_FrontFacing = param; main1(); - let _e72: vec4 = o_Target; - return FragmentOutput(_e72); + let e72: vec4 = o_Target; + return FragmentOutput(e72); } diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 5eb6dc897..2f629ea89 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -33,23 +33,23 @@ var gl_Position: vec4; fn main1() { var world_position: vec4; - let _e12: mat4x4 = global1.Model; - let _e13: vec3 = Vertex_Position1; - world_position = (_e12 * vec4(_e13, 1.0)); - let _e18: vec4 = world_position; - v_WorldPosition = _e18.xyz; - let _e20: mat4x4 = global1.Model; - let _e28: vec3 = Vertex_Normal1; - v_WorldNormal = (mat3x3(_e20[0].xyz, _e20[1].xyz, _e20[2].xyz) * _e28); - let _e30: vec2 = Vertex_Uv1; - v_Uv = _e30; - let _e31: mat4x4 = global1.Model; - let _e39: vec4 = Vertex_Tangent1; - let _e42: vec4 = Vertex_Tangent1; - v_WorldTangent = vec4((mat3x3(_e31[0].xyz, _e31[1].xyz, _e31[2].xyz) * _e39.xyz), _e42.w); - let _e46: mat4x4 = global.ViewProj; - let _e47: vec4 = world_position; - gl_Position = (_e46 * _e47); + let e12: mat4x4 = global1.Model; + let e13: vec3 = Vertex_Position1; + world_position = (e12 * vec4(e13, 1.0)); + let e18: vec4 = world_position; + v_WorldPosition = e18.xyz; + let e20: mat4x4 = global1.Model; + let e28: vec3 = Vertex_Normal1; + v_WorldNormal = (mat3x3(e20[0].xyz, e20[1].xyz, e20[2].xyz) * e28); + let e30: vec2 = Vertex_Uv1; + v_Uv = e30; + let e31: mat4x4 = global1.Model; + let e39: vec4 = Vertex_Tangent1; + let e42: vec4 = Vertex_Tangent1; + v_WorldTangent = vec4((mat3x3(e31[0].xyz, e31[1].xyz, e31[2].xyz) * e39.xyz), e42.w); + let e46: mat4x4 = global.ViewProj; + let e47: vec4 = world_position; + gl_Position = (e46 * e47); return; } @@ -60,10 +60,10 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Uv1 = Vertex_Uv; Vertex_Tangent1 = Vertex_Tangent; main1(); - let _e29: vec3 = v_WorldPosition; - let _e31: vec3 = v_WorldNormal; - let _e33: vec2 = v_Uv; - let _e35: vec4 = v_WorldTangent; - let _e37: vec4 = gl_Position; - return VertexOutput(_e29, _e31, _e33, _e35, _e37); + let e29: vec3 = v_WorldPosition; + let e31: vec3 = v_WorldNormal; + let e33: vec2 = v_Uv; + let e35: vec4 = v_WorldTangent; + let e37: vec4 = gl_Position; + return VertexOutput(e29, e31, e33, e35, e37); } diff --git a/tests/out/wgsl/binop-frag.wgsl b/tests/out/wgsl/binop-frag.wgsl index dd75aeb11..40e8c8216 100644 --- a/tests/out/wgsl/binop-frag.wgsl +++ b/tests/out/wgsl/binop-frag.wgsl @@ -7,14 +7,14 @@ fn testBinOpVecFloat(a: vec4, b: f32) { a1 = a; b1 = b; - let _e5: vec4 = a1; - v = (_e5 * 2.0); - let _e8: vec4 = a1; - v = (_e8 / vec4(2.0)); - let _e12: vec4 = a1; - v = (_e12 + vec4(2.0)); - let _e16: vec4 = a1; - v = (_e16 - vec4(2.0)); + let e5: vec4 = a1; + v = (e5 * 2.0); + let e8: vec4 = a1; + v = (e8 / vec4(2.0)); + let e12: vec4 = a1; + v = (e12 + vec4(2.0)); + let e16: vec4 = a1; + v = (e16 - vec4(2.0)); return; } @@ -25,18 +25,18 @@ fn testBinOpFloatVec(a2: vec4, b2: f32) { a3 = a2; b3 = b2; - let _e5: vec4 = a3; - let _e6: f32 = b3; - v1 = (_e5 * _e6); - let _e8: vec4 = a3; - let _e9: f32 = b3; - v1 = (_e8 / vec4(_e9)); - let _e12: vec4 = a3; - let _e13: f32 = b3; - v1 = (_e12 + vec4(_e13)); - let _e16: vec4 = a3; - let _e17: f32 = b3; - v1 = (_e16 - vec4(_e17)); + let e5: vec4 = a3; + let e6: f32 = b3; + v1 = (e5 * e6); + let e8: vec4 = a3; + let e9: f32 = b3; + v1 = (e8 / vec4(e9)); + let e12: vec4 = a3; + let e13: f32 = b3; + v1 = (e12 + vec4(e13)); + let e16: vec4 = a3; + let e17: f32 = b3; + v1 = (e16 - vec4(e17)); return; } @@ -47,33 +47,33 @@ fn testBinOpIVecInt(a4: vec4, b4: i32) { a5 = a4; b5 = b4; - let _e5: vec4 = a5; - let _e6: i32 = b5; - v2 = (_e5 * _e6); - let _e8: vec4 = a5; - let _e9: i32 = b5; - v2 = (_e8 / vec4(_e9)); - let _e12: vec4 = a5; - let _e13: i32 = b5; - v2 = (_e12 + vec4(_e13)); - let _e16: vec4 = a5; - let _e17: i32 = b5; - v2 = (_e16 - vec4(_e17)); - let _e20: vec4 = a5; - let _e21: i32 = b5; - v2 = (_e20 & vec4(_e21)); - let _e24: vec4 = a5; - let _e25: i32 = b5; - v2 = (_e24 | vec4(_e25)); - let _e28: vec4 = a5; - let _e29: i32 = b5; - v2 = (_e28 ^ vec4(_e29)); - let _e32: vec4 = a5; - let _e33: i32 = b5; - v2 = (_e32 >> vec4(u32(_e33))); - let _e37: vec4 = a5; - let _e38: i32 = b5; - v2 = (_e37 << vec4(u32(_e38))); + let e5: vec4 = a5; + let e6: i32 = b5; + v2 = (e5 * e6); + let e8: vec4 = a5; + let e9: i32 = b5; + v2 = (e8 / vec4(e9)); + let e12: vec4 = a5; + let e13: i32 = b5; + v2 = (e12 + vec4(e13)); + let e16: vec4 = a5; + let e17: i32 = b5; + v2 = (e16 - vec4(e17)); + let e20: vec4 = a5; + let e21: i32 = b5; + v2 = (e20 & vec4(e21)); + let e24: vec4 = a5; + let e25: i32 = b5; + v2 = (e24 | vec4(e25)); + let e28: vec4 = a5; + let e29: i32 = b5; + v2 = (e28 ^ vec4(e29)); + let e32: vec4 = a5; + let e33: i32 = b5; + v2 = (e32 >> vec4(u32(e33))); + let e37: vec4 = a5; + let e38: i32 = b5; + v2 = (e37 << vec4(u32(e38))); return; } @@ -84,24 +84,24 @@ fn testBinOpIntIVec(a6: i32, b6: vec4) { a7 = a6; b7 = b6; - let _e5: i32 = a7; - let _e6: vec4 = b7; - v3 = (_e5 * _e6); - let _e8: i32 = a7; - let _e9: vec4 = b7; - v3 = (vec4(_e8) + _e9); - let _e12: i32 = a7; - let _e13: vec4 = b7; - v3 = (vec4(_e12) - _e13); - let _e16: i32 = a7; - let _e17: vec4 = b7; - v3 = (vec4(_e16) & _e17); - let _e20: i32 = a7; - let _e21: vec4 = b7; - v3 = (vec4(_e20) | _e21); - let _e24: i32 = a7; - let _e25: vec4 = b7; - v3 = (vec4(_e24) ^ _e25); + let e5: i32 = a7; + let e6: vec4 = b7; + v3 = (e5 * e6); + let e8: i32 = a7; + let e9: vec4 = b7; + v3 = (vec4(e8) + e9); + let e12: i32 = a7; + let e13: vec4 = b7; + v3 = (vec4(e12) - e13); + let e16: i32 = a7; + let e17: vec4 = b7; + v3 = (vec4(e16) & e17); + let e20: i32 = a7; + let e21: vec4 = b7; + v3 = (vec4(e20) | e21); + let e24: i32 = a7; + let e25: vec4 = b7; + v3 = (vec4(e24) ^ e25); return; } @@ -112,33 +112,33 @@ fn testBinOpUVecUint(a8: vec4, b8: u32) { a9 = a8; b9 = b8; - let _e5: vec4 = a9; - let _e6: u32 = b9; - v4 = (_e5 * _e6); - let _e8: vec4 = a9; - let _e9: u32 = b9; - v4 = (_e8 / vec4(_e9)); - let _e12: vec4 = a9; - let _e13: u32 = b9; - v4 = (_e12 + vec4(_e13)); - let _e16: vec4 = a9; - let _e17: u32 = b9; - v4 = (_e16 - vec4(_e17)); - let _e20: vec4 = a9; - let _e21: u32 = b9; - v4 = (_e20 & vec4(_e21)); - let _e24: vec4 = a9; - let _e25: u32 = b9; - v4 = (_e24 | vec4(_e25)); - let _e28: vec4 = a9; - let _e29: u32 = b9; - v4 = (_e28 ^ vec4(_e29)); - let _e32: vec4 = a9; - let _e33: u32 = b9; - v4 = (_e32 >> vec4(_e33)); - let _e36: vec4 = a9; - let _e37: u32 = b9; - v4 = (_e36 << vec4(_e37)); + let e5: vec4 = a9; + let e6: u32 = b9; + v4 = (e5 * e6); + let e8: vec4 = a9; + let e9: u32 = b9; + v4 = (e8 / vec4(e9)); + let e12: vec4 = a9; + let e13: u32 = b9; + v4 = (e12 + vec4(e13)); + let e16: vec4 = a9; + let e17: u32 = b9; + v4 = (e16 - vec4(e17)); + let e20: vec4 = a9; + let e21: u32 = b9; + v4 = (e20 & vec4(e21)); + let e24: vec4 = a9; + let e25: u32 = b9; + v4 = (e24 | vec4(e25)); + let e28: vec4 = a9; + let e29: u32 = b9; + v4 = (e28 ^ vec4(e29)); + let e32: vec4 = a9; + let e33: u32 = b9; + v4 = (e32 >> vec4(e33)); + let e36: vec4 = a9; + let e37: u32 = b9; + v4 = (e36 << vec4(e37)); return; } @@ -149,34 +149,34 @@ fn testBinOpUintUVec(a10: u32, b10: vec4) { a11 = a10; b11 = b10; - let _e5: u32 = a11; - let _e6: vec4 = b11; - v5 = (_e5 * _e6); - let _e8: u32 = a11; - let _e9: vec4 = b11; - v5 = (vec4(_e8) + _e9); - let _e12: u32 = a11; - let _e13: vec4 = b11; - v5 = (vec4(_e12) - _e13); - let _e16: u32 = a11; - let _e17: vec4 = b11; - v5 = (vec4(_e16) & _e17); - let _e20: u32 = a11; - let _e21: vec4 = b11; - v5 = (vec4(_e20) | _e21); - let _e24: u32 = a11; - let _e25: vec4 = b11; - v5 = (vec4(_e24) ^ _e25); + let e5: u32 = a11; + let e6: vec4 = b11; + v5 = (e5 * e6); + let e8: u32 = a11; + let e9: vec4 = b11; + v5 = (vec4(e8) + e9); + let e12: u32 = a11; + let e13: vec4 = b11; + v5 = (vec4(e12) - e13); + let e16: u32 = a11; + let e17: vec4 = b11; + v5 = (vec4(e16) & e17); + let e20: u32 = a11; + let e21: vec4 = b11; + v5 = (vec4(e20) | e21); + let e24: u32 = a11; + let e25: vec4 = b11; + v5 = (vec4(e24) ^ e25); return; } fn main1() { - let _e1: vec4 = o_color; - let _e4: vec4 = vec4(1.0); - o_color.x = _e4.x; - o_color.y = _e4.y; - o_color.z = _e4.z; - o_color.w = _e4.w; + let e1: vec4 = o_color; + let e4: vec4 = vec4(1.0); + o_color.x = e4.x; + o_color.y = e4.y; + o_color.z = e4.z; + o_color.w = e4.w; return; } diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index a0e5e8eab..902aa4edc 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -45,109 +45,109 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { if ((index >= NUM_PARTICLES)) { return; } - let _e10: vec2 = particlesSrc.particles[index].pos; - vPos = _e10; - let _e15: vec2 = particlesSrc.particles[index].vel; - vVel = _e15; + let e10: vec2 = particlesSrc.particles[index].pos; + vPos = e10; + let e15: vec2 = particlesSrc.particles[index].vel; + vVel = e15; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); loop { - let _e37: u32 = i; - if ((_e37 >= NUM_PARTICLES)) { + let e37: u32 = i; + if ((e37 >= NUM_PARTICLES)) { break; } - let _e39: u32 = i; - if ((_e39 == index)) { + let e39: u32 = i; + if ((e39 == index)) { continue; } - let _e42: u32 = i; - let _e45: vec2 = particlesSrc.particles[_e42].pos; - pos = _e45; - let _e47: u32 = i; - let _e50: vec2 = particlesSrc.particles[_e47].vel; - vel = _e50; - let _e51: vec2 = pos; - let _e52: vec2 = vPos; - let _e55: f32 = params.rule1Distance; - if ((distance(_e51, _e52) < _e55)) { - let _e57: vec2 = cMass; - let _e58: vec2 = pos; - cMass = (_e57 + _e58); - let _e60: i32 = cMassCount; - cMassCount = (_e60 + 1); + let e42: u32 = i; + let e45: vec2 = particlesSrc.particles[e42].pos; + pos = e45; + let e47: u32 = i; + let e50: vec2 = particlesSrc.particles[e47].vel; + vel = e50; + let e51: vec2 = pos; + let e52: vec2 = vPos; + let e55: f32 = params.rule1Distance; + if ((distance(e51, e52) < e55)) { + let e57: vec2 = cMass; + let e58: vec2 = pos; + cMass = (e57 + e58); + let e60: i32 = cMassCount; + cMassCount = (e60 + 1); } - let _e63: vec2 = pos; - let _e64: vec2 = vPos; - let _e67: f32 = params.rule2Distance; - if ((distance(_e63, _e64) < _e67)) { - let _e69: vec2 = colVel; - let _e70: vec2 = pos; - let _e71: vec2 = vPos; - colVel = (_e69 - (_e70 - _e71)); + let e63: vec2 = pos; + let e64: vec2 = vPos; + let e67: f32 = params.rule2Distance; + if ((distance(e63, e64) < e67)) { + let e69: vec2 = colVel; + let e70: vec2 = pos; + let e71: vec2 = vPos; + colVel = (e69 - (e70 - e71)); } - let _e74: vec2 = pos; - let _e75: vec2 = vPos; - let _e78: f32 = params.rule3Distance; - if ((distance(_e74, _e75) < _e78)) { - let _e80: vec2 = cVel; - let _e81: vec2 = vel; - cVel = (_e80 + _e81); - let _e83: i32 = cVelCount; - cVelCount = (_e83 + 1); + let e74: vec2 = pos; + let e75: vec2 = vPos; + let e78: f32 = params.rule3Distance; + if ((distance(e74, e75) < e78)) { + let e80: vec2 = cVel; + let e81: vec2 = vel; + cVel = (e80 + e81); + let e83: i32 = cVelCount; + cVelCount = (e83 + 1); } continuing { - let _e86: u32 = i; - i = (_e86 + 1u); + let e86: u32 = i; + i = (e86 + 1u); } } - let _e89: i32 = cMassCount; - if ((_e89 > 0)) { - let _e92: vec2 = cMass; - let _e93: i32 = cMassCount; - let _e97: vec2 = vPos; - cMass = ((_e92 / vec2(f32(_e93))) - _e97); + let e89: i32 = cMassCount; + if ((e89 > 0)) { + let e92: vec2 = cMass; + let e93: i32 = cMassCount; + let e97: vec2 = vPos; + cMass = ((e92 / vec2(f32(e93))) - e97); } - let _e99: i32 = cVelCount; - if ((_e99 > 0)) { - let _e102: vec2 = cVel; - let _e103: i32 = cVelCount; - cVel = (_e102 / vec2(f32(_e103))); + let e99: i32 = cVelCount; + if ((e99 > 0)) { + let e102: vec2 = cVel; + let e103: i32 = cVelCount; + cVel = (e102 / vec2(f32(e103))); } - let _e107: vec2 = vVel; - let _e108: vec2 = cMass; - let _e110: f32 = params.rule1Scale; - let _e113: vec2 = colVel; - let _e115: f32 = params.rule2Scale; - let _e118: vec2 = cVel; - let _e120: f32 = params.rule3Scale; - vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); - let _e123: vec2 = vVel; - let _e125: vec2 = vVel; - vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.10000000149011612)); - let _e131: vec2 = vPos; - let _e132: vec2 = vVel; - let _e134: f32 = params.deltaT; - vPos = (_e131 + (_e132 * _e134)); - let _e138: f32 = vPos.x; - if ((_e138 < -1.0)) { + let e107: vec2 = vVel; + let e108: vec2 = cMass; + let e110: f32 = params.rule1Scale; + let e113: vec2 = colVel; + let e115: f32 = params.rule2Scale; + let e118: vec2 = cVel; + let e120: f32 = params.rule3Scale; + vVel = (((e107 + (e108 * e110)) + (e113 * e115)) + (e118 * e120)); + let e123: vec2 = vVel; + let e125: vec2 = vVel; + vVel = (normalize(e123) * clamp(length(e125), 0.0, 0.10000000149011612)); + let e131: vec2 = vPos; + let e132: vec2 = vVel; + let e134: f32 = params.deltaT; + vPos = (e131 + (e132 * e134)); + let e138: f32 = vPos.x; + if ((e138 < -1.0)) { vPos.x = 1.0; } - let _e144: f32 = vPos.x; - if ((_e144 > 1.0)) { + let e144: f32 = vPos.x; + if ((e144 > 1.0)) { vPos.x = -1.0; } - let _e150: f32 = vPos.y; - if ((_e150 < -1.0)) { + let e150: f32 = vPos.y; + if ((e150 < -1.0)) { vPos.y = 1.0; } - let _e156: f32 = vPos.y; - if ((_e156 > 1.0)) { + let e156: f32 = vPos.y; + if ((e156 > 1.0)) { vPos.y = -1.0; } - let _e164: vec2 = vPos; - particlesDst.particles[index].pos = _e164; - let _e168: vec2 = vVel; - particlesDst.particles[index].vel = _e168; + let e164: vec2 = vPos; + particlesDst.particles[index].pos = e164; + let e168: vec2 = vVel; + particlesDst.particles[index].vel = e168; return; } diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index 9f26d9d76..1ef8e9465 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -10,9 +10,9 @@ fn TevPerCompGT(a: f32, b: f32) -> f32 { a1 = a; b1 = b; - let _e5: f32 = a1; - let _e6: f32 = b1; - return select(0.0, 1.0, (_e5 > _e6)); + let e5: f32 = a1; + let e6: f32 = b1; + return select(0.0, 1.0, (e5 > e6)); } fn TevPerCompGT1(a2: vec3, b2: vec3) -> vec3 { @@ -21,25 +21,25 @@ fn TevPerCompGT1(a2: vec3, b2: vec3) -> vec3 { a3 = a2; b3 = b2; - let _e7: vec3 = a3; - let _e8: vec3 = b3; - return select(vec3(0.0), vec3(1.0), (_e7 > _e8)); + let e7: vec3 = a3; + let e8: vec3 = b3; + return select(vec3(0.0), vec3(1.0), (e7 > e8)); } fn main1() { - let _e1: vec4 = o_color; - let _e11: vec3 = TevPerCompGT1(vec3(3.0), vec3(5.0)); - o_color.x = _e11.x; - o_color.y = _e11.y; - o_color.z = _e11.z; - let _e23: f32 = TevPerCompGT(3.0, 5.0); - o_color.w = _e23; + let e1: vec4 = o_color; + let e11: vec3 = TevPerCompGT1(vec3(3.0), vec3(5.0)); + o_color.x = e11.x; + o_color.y = e11.y; + o_color.z = e11.z; + let e23: f32 = TevPerCompGT(3.0, 5.0); + o_color.w = e23; return; } [[stage(fragment)]] fn main() -> FragmentOutput { main1(); - let _e3: vec4 = o_color; - return FragmentOutput(_e3); + let e3: vec4 = o_color; + return FragmentOutput(e3); } diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index bbc28b22a..4dfea0b08 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -6,8 +6,8 @@ var a_pos1: vec2; var gl_Position: vec4; fn main1() { - let _e5: vec2 = a_pos1; - gl_Position = vec4(clamp(_e5, vec2(0.0), vec2(1.0)), 0.0, 1.0); + let e5: vec2 = a_pos1; + gl_Position = vec4(clamp(e5, vec2(0.0), vec2(1.0)), 0.0, 1.0); return; } @@ -15,6 +15,6 @@ fn main1() { fn main([[location(0)]] a_pos: vec2) -> VertexOutput { a_pos1 = a_pos; main1(); - let _e5: vec4 = gl_Position; - return VertexOutput(_e5); + let e5: vec4 = gl_Position; + return VertexOutput(e5); } diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index e3bbb2cab..b17dbd045 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -12,29 +12,29 @@ fn collatz_iterations(n_base: u32) -> u32 { n = n_base; loop { - let _e5: u32 = n; - if ((_e5 <= 1u)) { + let e5: u32 = n; + if ((e5 <= 1u)) { break; } - let _e8: u32 = n; - if (((_e8 % 2u) == 0u)) { - let _e13: u32 = n; - n = (_e13 / 2u); + let e8: u32 = n; + if (((e8 % 2u) == 0u)) { + let e13: u32 = n; + n = (e13 / 2u); } else { - let _e17: u32 = n; - n = ((3u * _e17) + 1u); + let e17: u32 = n; + n = ((3u * e17) + 1u); } - let _e21: u32 = i; - i = (_e21 + 1u); + let e21: u32 = i; + i = (e21 + 1u); } - let _e24: u32 = i; - return _e24; + let e24: u32 = i; + return e24; } [[stage(compute), workgroup_size(1, 1, 1)]] fn main([[builtin(global_invocation_id)]] global_id: vec3) { - let _e8: u32 = v_indices.data[global_id.x]; - let _e9: u32 = collatz_iterations(_e8); - v_indices.data[global_id.x] = _e9; + let e8: u32 = v_indices.data[global_id.x]; + let e9: u32 = collatz_iterations(e8); + v_indices.data[global_id.x] = e9; return; } diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index ac18b2539..ad51ae6b7 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -11,23 +11,23 @@ fn function() -> vec4 { var i: i32 = 0; loop { - let _e9: i32 = i; - if (!((_e9 < 42))) { + let e9: i32 = i; + if (!((e9 < 42))) { break; } { - let _e15: vec4 = sum; - let _e16: i32 = i; - let _e18: vec4 = global.vecs[_e16]; - sum = (_e15 + _e18); + let e15: vec4 = sum; + let e16: i32 = i; + let e18: vec4 = global.vecs[e16]; + sum = (e15 + e18); } continuing { - let _e12: i32 = i; - i = (_e12 + 1); + let e12: i32 = i; + i = (e12 + 1); } } - let _e20: vec4 = sum; - return _e20; + let e20: vec4 = sum; + return e20; } fn main1() { diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index 2859edd61..511c08aa5 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -37,8 +37,8 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { pos = 1; } } - let _e4: i32 = pos; - switch(_e4) { + let e4: i32 = pos; + switch(e4) { case 1: { pos = 0; break; @@ -56,8 +56,8 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { pos = 3; } } - let _e9: i32 = pos; - switch(_e9) { + let e9: i32 = pos; + switch(e9) { case 1: { pos = 0; break; diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 352945808..e943de29b 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -12,28 +12,28 @@ fn Fma(d: ptr, m: Mat4x3_, s: f32) { m1 = m; s1 = s; - let _e6: Mat4x3_ = (*d); - let _e8: Mat4x3_ = m1; - let _e10: f32 = s1; - (*d).mx = (_e6.mx + (_e8.mx * _e10)); - let _e14: Mat4x3_ = (*d); - let _e16: Mat4x3_ = m1; - let _e18: f32 = s1; - (*d).my = (_e14.my + (_e16.my * _e18)); - let _e22: Mat4x3_ = (*d); - let _e24: Mat4x3_ = m1; - let _e26: f32 = s1; - (*d).mz = (_e22.mz + (_e24.mz * _e26)); + let e6: Mat4x3_ = (*d); + let e8: Mat4x3_ = m1; + let e10: f32 = s1; + (*d).mx = (e6.mx + (e8.mx * e10)); + let e14: Mat4x3_ = (*d); + let e16: Mat4x3_ = m1; + let e18: f32 = s1; + (*d).my = (e14.my + (e16.my * e18)); + let e22: Mat4x3_ = (*d); + let e24: Mat4x3_ = m1; + let e26: f32 = s1; + (*d).mz = (e22.mz + (e24.mz * e26)); return; } fn main1() { - let _e1: vec4 = o_color; - let _e4: vec4 = vec4(1.0); - o_color.x = _e4.x; - o_color.y = _e4.y; - o_color.z = _e4.z; - o_color.w = _e4.w; + let e1: vec4 = o_color; + let e4: vec4 = vec4(1.0); + o_color.x = e4.x; + o_color.y = e4.y; + o_color.z = e4.z; + o_color.w = e4.w; return; } diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index 01ec742e0..066088b1f 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -3,7 +3,7 @@ var i: u32; fn main1() { var local: array = array(1.0, 2.0); - let _e2: u32 = i; + let e2: u32 = i; } [[stage(vertex)]] diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index cf1a3824c..972bc2523 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -21,8 +21,8 @@ fn main() -> FragmentInput { out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); out.perspective_centroid = 2197.0; out.perspective_sample = 2744.0; - let _e30: FragmentInput = out; - return _e30; + let e30: FragmentInput = out; + return e30; } [[stage(fragment)]] diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl index 7378cb300..ff4d9fa0e 100644 --- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -5,12 +5,12 @@ fn main1() { var c: f32; var d: f32; - let _e8: f32 = a; - b = log(_e8 + sqrt(_e8 * _e8 + 1.0)); - let _e10: f32 = a; - c = log(_e10 + sqrt(_e10 * _e10 - 1.0)); - let _e12: f32 = a; - d = 0.5 * log((1.0 + _e12) / (1.0 - _e12)); + let e8: f32 = a; + b = log(e8 + sqrt(e8 * e8 + 1.0)); + let e10: f32 = a; + c = log(e10 + sqrt(e10 * e10 - 1.0)); + let e12: f32 = a; + d = 0.5 * log((1.0 + e12) / (1.0 - e12)); return; } diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index dee8738ff..9806b1185 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -7,20 +7,20 @@ fn main1() { var d: mat3x3 = mat3x3(vec3(2.0, 2.0, 1.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); var e: mat4x4 = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); - let _e1: f32 = f32(1); - let _e9: vec2 = vec2(f32(1)); - let _e12: vec2 = vec2(f32(2)); - let _e38: vec2 = vec2(f32(2), f32(3)); - let _e53: vec3 = vec3(f32(1)); - let _e56: vec3 = vec3(f32(1)); - let _e73: vec2 = vec2(f32(2)); - let _e77: vec3 = vec3(f32(1)); - let _e80: vec3 = vec3(f32(1)); - let _e97: vec2 = vec2(f32(2)); - let _e100: vec4 = vec4(f32(1)); - let _e103: vec2 = vec2(f32(2)); - let _e106: vec4 = vec4(f32(1)); - let _e109: vec4 = vec4(f32(1)); + let e1: f32 = f32(1); + let e9: vec2 = vec2(f32(1)); + let e12: vec2 = vec2(f32(2)); + let e38: vec2 = vec2(f32(2), f32(3)); + let e53: vec3 = vec3(f32(1)); + let e56: vec3 = vec3(f32(1)); + let e73: vec2 = vec2(f32(2)); + let e77: vec3 = vec3(f32(1)); + let e80: vec3 = vec3(f32(1)); + let e97: vec2 = vec2(f32(2)); + let e100: vec4 = vec4(f32(1)); + let e103: vec2 = vec2(f32(2)); + let e106: vec4 = vec4(f32(1)); + let e109: vec4 = vec4(f32(1)); } [[stage(vertex)]] diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 32602b9b5..33a8f909e 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -43,107 +43,107 @@ fn main1() { var distanceOut: f32; var stepOut: vec4; - let _e6: vec4 = a; - let _e7: vec4 = b; - let _e8: vec4 = a; - let _e9: vec4 = b; - m = mat4x4(vec4(_e6.x, _e6.y, _e6.z, _e6.w), vec4(_e7.x, _e7.y, _e7.z, _e7.w), vec4(_e8.x, _e8.y, _e8.z, _e8.w), vec4(_e9.x, _e9.y, _e9.z, _e9.w)); - let _e35: vec4 = a; - ceilOut = ceil(_e35); - let _e39: vec4 = a; - roundOut = round(_e39); - let _e43: vec4 = a; - floorOut = floor(_e43); - let _e47: vec4 = a; - fractOut = fract(_e47); - let _e51: vec4 = a; - truncOut = trunc(_e51); - let _e55: vec4 = a; - sinOut = sin(_e55); - let _e59: vec4 = a; - absOut = abs(_e59); - let _e63: vec4 = a; - sqrtOut = sqrt(_e63); - let _e67: vec4 = a; - inversesqrtOut = inverseSqrt(_e67); - let _e71: vec4 = a; - expOut = exp(_e71); - let _e75: vec4 = a; - exp2Out = exp2(_e75); - let _e79: vec4 = a; - signOut = sign(_e79); - let _e83: mat4x4 = m; - transposeOut = transpose(_e83); - let _e87: vec4 = a; - normalizeOut = normalize(_e87); - let _e91: vec4 = a; - sinhOut = sinh(_e91); - let _e95: vec4 = a; - cosOut = cos(_e95); - let _e99: vec4 = a; - coshOut = cosh(_e99); - let _e103: vec4 = a; - tanOut = tan(_e103); - let _e107: vec4 = a; - tanhOut = tanh(_e107); - let _e111: vec4 = a; - acosOut = acos(_e111); - let _e115: vec4 = a; - asinOut = asin(_e115); - let _e119: vec4 = a; - logOut = log(_e119); - let _e123: vec4 = a; - log2Out = log2(_e123); - let _e127: vec4 = a; - lengthOut = length(_e127); - let _e131: mat4x4 = m; - determinantOut = determinant(_e131); - let _e135: i32 = i; - bitCountOut = countOneBits(_e135); - let _e139: i32 = i; - bitfieldReverseOut = reverseBits(_e139); - let _e142: vec4 = a; - let _e144: vec4 = a; - atanOut = atan(_e144.x); - let _e148: vec4 = a; - let _e150: vec4 = a; - let _e152: vec4 = a; - let _e154: vec4 = a; - atan2Out = atan2(_e152.x, _e154.y); - let _e158: vec4 = a; - let _e160: vec4 = b; - let _e162: vec4 = a; - let _e164: vec4 = b; - modOut = (_e162.x % _e164.x); - let _e170: vec4 = a; - let _e171: vec4 = b; - powOut = pow(_e170, _e171); - let _e176: vec4 = a; - let _e177: vec4 = b; - dotOut = dot(_e176, _e177); - let _e182: vec4 = a; - let _e183: vec4 = b; - maxOut = max(_e182, _e183); - let _e188: vec4 = a; - let _e189: vec4 = b; - minOut = min(_e188, _e189); - let _e194: vec4 = a; - let _e195: vec4 = b; - reflectOut = reflect(_e194, _e195); - let _e198: vec4 = a; - let _e200: vec4 = b; - let _e202: vec4 = a; - let _e204: vec4 = b; - crossOut = cross(_e202.xyz, _e204.xyz); - let _e210: vec4 = a; - let _e211: vec4 = b; - outerProductOut = outerProduct(_e210, _e211); - let _e216: vec4 = a; - let _e217: vec4 = b; - distanceOut = distance(_e216, _e217); - let _e222: vec4 = a; - let _e223: vec4 = b; - stepOut = step(_e222, _e223); + let e6: vec4 = a; + let e7: vec4 = b; + let e8: vec4 = a; + let e9: vec4 = b; + m = mat4x4(vec4(e6.x, e6.y, e6.z, e6.w), vec4(e7.x, e7.y, e7.z, e7.w), vec4(e8.x, e8.y, e8.z, e8.w), vec4(e9.x, e9.y, e9.z, e9.w)); + let e35: vec4 = a; + ceilOut = ceil(e35); + let e39: vec4 = a; + roundOut = round(e39); + let e43: vec4 = a; + floorOut = floor(e43); + let e47: vec4 = a; + fractOut = fract(e47); + let e51: vec4 = a; + truncOut = trunc(e51); + let e55: vec4 = a; + sinOut = sin(e55); + let e59: vec4 = a; + absOut = abs(e59); + let e63: vec4 = a; + sqrtOut = sqrt(e63); + let e67: vec4 = a; + inversesqrtOut = inverseSqrt(e67); + let e71: vec4 = a; + expOut = exp(e71); + let e75: vec4 = a; + exp2Out = exp2(e75); + let e79: vec4 = a; + signOut = sign(e79); + let e83: mat4x4 = m; + transposeOut = transpose(e83); + let e87: vec4 = a; + normalizeOut = normalize(e87); + let e91: vec4 = a; + sinhOut = sinh(e91); + let e95: vec4 = a; + cosOut = cos(e95); + let e99: vec4 = a; + coshOut = cosh(e99); + let e103: vec4 = a; + tanOut = tan(e103); + let e107: vec4 = a; + tanhOut = tanh(e107); + let e111: vec4 = a; + acosOut = acos(e111); + let e115: vec4 = a; + asinOut = asin(e115); + let e119: vec4 = a; + logOut = log(e119); + let e123: vec4 = a; + log2Out = log2(e123); + let e127: vec4 = a; + lengthOut = length(e127); + let e131: mat4x4 = m; + determinantOut = determinant(e131); + let e135: i32 = i; + bitCountOut = countOneBits(e135); + let e139: i32 = i; + bitfieldReverseOut = reverseBits(e139); + let e142: vec4 = a; + let e144: vec4 = a; + atanOut = atan(e144.x); + let e148: vec4 = a; + let e150: vec4 = a; + let e152: vec4 = a; + let e154: vec4 = a; + atan2Out = atan2(e152.x, e154.y); + let e158: vec4 = a; + let e160: vec4 = b; + let e162: vec4 = a; + let e164: vec4 = b; + modOut = (e162.x % e164.x); + let e170: vec4 = a; + let e171: vec4 = b; + powOut = pow(e170, e171); + let e176: vec4 = a; + let e177: vec4 = b; + dotOut = dot(e176, e177); + let e182: vec4 = a; + let e183: vec4 = b; + maxOut = max(e182, e183); + let e188: vec4 = a; + let e189: vec4 = b; + minOut = min(e188, e189); + let e194: vec4 = a; + let e195: vec4 = b; + reflectOut = reflect(e194, e195); + let e198: vec4 = a; + let e200: vec4 = b; + let e202: vec4 = a; + let e204: vec4 = b; + crossOut = cross(e202.xyz, e204.xyz); + let e210: vec4 = a; + let e211: vec4 = b; + outerProductOut = outerProduct(e210, e211); + let e216: vec4 = a; + let e217: vec4 = b; + distanceOut = distance(e216, e217); + let e222: vec4 = a; + let e223: vec4 = b; + stepOut = step(e222, e223); return; } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 8f6c6ad8f..f43c1c88a 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -37,15 +37,15 @@ fn constructors() -> f32 { var foo: Foo; foo = Foo(vec4(1.0), 1); - let _e11: f32 = foo.a.x; - return _e11; + let e11: f32 = foo.a.x; + return e11; } [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { - let _e4: vec4 = builtins(); - let _e5: vec4 = splat(); - let _e6: i32 = unary(); - let _e7: f32 = constructors(); + let e4: vec4 = builtins(); + let e5: vec4 = splat(); + let e6: i32 = unary(); + let e7: f32 = constructors(); return; } diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index df723ccf7..5b2e53a81 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -6,30 +6,30 @@ fn main1() { var mat_target: mat4x3; var mat: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); - let _e3: i32 = scalar; - scalar = (_e3 + 1); - scalar_target = _e3; - let _e6: i32 = scalar; - let _e8: i32 = (_e6 - 1); - scalar = _e8; - scalar_target = _e8; - let _e14: vec2 = vec; - vec = (_e14 - vec2(1u)); - vec_target = _e14; - let _e18: vec2 = vec; - let _e21: vec2 = (_e18 + vec2(1u)); - vec = _e21; - vec_target = _e21; - let _e24: f32 = f32(1); - let _e32: mat4x3 = mat; - let _e34: vec3 = vec3(1.0); - mat = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); - mat_target = _e32; - let _e37: mat4x3 = mat; - let _e39: vec3 = vec3(1.0); - let _e41: mat4x3 = (_e37 - mat4x3(_e39, _e39, _e39, _e39)); - mat = _e41; - mat_target = _e41; + let e3: i32 = scalar; + scalar = (e3 + 1); + scalar_target = e3; + let e6: i32 = scalar; + let e8: i32 = (e6 - 1); + scalar = e8; + scalar_target = e8; + let e14: vec2 = vec; + vec = (e14 - vec2(1u)); + vec_target = e14; + let e18: vec2 = vec; + let e21: vec2 = (e18 + vec2(1u)); + vec = e21; + vec_target = e21; + let e24: f32 = f32(1); + let e32: mat4x3 = mat; + let e34: vec3 = vec3(1.0); + mat = (e32 + mat4x3(e34, e34, e34, e34)); + mat_target = e32; + let e37: mat4x3 = mat; + let e39: vec3 = vec3(1.0); + let e41: mat4x3 = (e37 - mat4x3(e39, e39, e39, e39)); + mat = e41; + mat_target = e41; return; } diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index bb6a86a19..09a9cfdbb 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -14,10 +14,10 @@ var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0. var a_pos1: vec2; fn main1() { - let _e12: vec2 = a_uv1; - v_uv = _e12; - let _e13: vec2 = a_pos1; - perVertexStruct.gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); + let e12: vec2 = a_uv1; + v_uv = e12; + let e13: vec2 = a_pos1; + perVertexStruct.gl_Position = vec4(e13.x, e13.y, 0.0, 1.0); return; } @@ -26,7 +26,7 @@ fn main([[location(1)]] a_uv: vec2, [[location(0)]] a_pos: vec2) -> Ve a_uv1 = a_uv; a_pos1 = a_pos; main1(); - let _e10: vec2 = v_uv; - let _e11: vec4 = perVertexStruct.gl_Position; - return VertexOutput(_e10, _e11); + let e10: vec2 = v_uv; + let e11: vec4 = perVertexStruct.gl_Position; + return VertexOutput(e10, e11); } diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 18ee145e7..022cc70ad 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -14,6 +14,6 @@ fn main1() { fn main([[location(0)]] v_uv: vec2) -> FragmentOutput { v_uv1 = v_uv; main1(); - let _e7: vec4 = o_color; - return FragmentOutput(_e7); + let e7: vec4 = o_color; + return FragmentOutput(e7); } diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index c010a38cb..81c155564 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -9,10 +9,10 @@ var v_uv: vec2; var gl_Position: vec4; fn main1() { - let _e4: vec2 = a_uv1; - v_uv = _e4; - let _e6: vec2 = a_pos1; - gl_Position = vec4((1.2000000476837158 * _e6), 0.0, 1.0); + let e4: vec2 = a_uv1; + v_uv = e4; + let e6: vec2 = a_pos1; + gl_Position = vec4((1.2000000476837158 * e6), 0.0, 1.0); return; } @@ -21,7 +21,7 @@ fn main([[location(0)]] a_pos: vec2, [[location(1)]] a_uv: vec2) -> Ve a_pos1 = a_pos; a_uv1 = a_uv; main1(); - let _e14: vec2 = v_uv; - let _e16: vec4 = gl_Position; - return VertexOutput(_e14, _e16); + let e14: vec2 = v_uv; + let e16: vec4 = gl_Position; + return VertexOutput(e14, e16); } diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 3381d2105..18433b50f 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -33,110 +33,110 @@ fn testTex1D(coord: f32) { var c: vec4; coord1 = coord; - let _e18: f32 = coord1; - let _e19: vec4 = textureSample(tex1D, samp, _e18); - c = _e19; - let _e22: f32 = coord1; - let _e24: vec4 = textureSampleBias(tex1D, samp, _e22, 2.0); - c = _e24; - let _e28: f32 = coord1; - let _e31: vec4 = textureSampleGrad(tex1D, samp, _e28, 4.0, 4.0); - c = _e31; - let _e36: f32 = coord1; - let _e40: vec4 = textureSampleGrad(tex1D, samp, _e36, 4.0, 4.0, 5); - c = _e40; - let _e43: f32 = coord1; - let _e45: vec4 = textureSampleLevel(tex1D, samp, _e43, 3.0); - c = _e45; - let _e49: f32 = coord1; - let _e52: vec4 = textureSampleLevel(tex1D, samp, _e49, 3.0, 5); - c = _e52; - let _e55: f32 = coord1; - let _e57: vec4 = textureSample(tex1D, samp, _e55, 5); - c = _e57; - let _e61: f32 = coord1; - let _e64: vec4 = textureSampleBias(tex1D, samp, _e61, 2.0, 5); - c = _e64; - let _e65: f32 = coord1; - let _e68: f32 = coord1; - let _e70: vec2 = vec2(_e68, 6.0); - let _e74: vec4 = textureSample(tex1D, samp, (_e70.x / _e70.y)); - c = _e74; - let _e75: f32 = coord1; - let _e80: f32 = coord1; - let _e84: vec4 = vec4(_e80, 0.0, 0.0, 6.0); - let _e90: vec4 = textureSample(tex1D, samp, (_e84.xyz / vec3(_e84.w)).x); - c = _e90; - let _e91: f32 = coord1; - let _e95: f32 = coord1; - let _e97: vec2 = vec2(_e95, 6.0); - let _e102: vec4 = textureSampleBias(tex1D, samp, (_e97.x / _e97.y), 2.0); - c = _e102; - let _e103: f32 = coord1; - let _e109: f32 = coord1; - let _e113: vec4 = vec4(_e109, 0.0, 0.0, 6.0); - let _e120: vec4 = textureSampleBias(tex1D, samp, (_e113.xyz / vec3(_e113.w)).x, 2.0); - c = _e120; - let _e121: f32 = coord1; - let _e126: f32 = coord1; - let _e128: vec2 = vec2(_e126, 6.0); - let _e134: vec4 = textureSampleGrad(tex1D, samp, (_e128.x / _e128.y), 4.0, 4.0); - c = _e134; - let _e135: f32 = coord1; - let _e142: f32 = coord1; - let _e146: vec4 = vec4(_e142, 0.0, 0.0, 6.0); - let _e154: vec4 = textureSampleGrad(tex1D, samp, (_e146.xyz / vec3(_e146.w)).x, 4.0, 4.0); - c = _e154; - let _e155: f32 = coord1; - let _e161: f32 = coord1; - let _e163: vec2 = vec2(_e161, 6.0); - let _e170: vec4 = textureSampleGrad(tex1D, samp, (_e163.x / _e163.y), 4.0, 4.0, 5); - c = _e170; - let _e171: f32 = coord1; - let _e179: f32 = coord1; - let _e183: vec4 = vec4(_e179, 0.0, 0.0, 6.0); - let _e192: vec4 = textureSampleGrad(tex1D, samp, (_e183.xyz / vec3(_e183.w)).x, 4.0, 4.0, 5); - c = _e192; - let _e193: f32 = coord1; - let _e197: f32 = coord1; - let _e199: vec2 = vec2(_e197, 6.0); - let _e204: vec4 = textureSampleLevel(tex1D, samp, (_e199.x / _e199.y), 3.0); - c = _e204; - let _e205: f32 = coord1; - let _e211: f32 = coord1; - let _e215: vec4 = vec4(_e211, 0.0, 0.0, 6.0); - let _e222: vec4 = textureSampleLevel(tex1D, samp, (_e215.xyz / vec3(_e215.w)).x, 3.0); - c = _e222; - let _e223: f32 = coord1; - let _e228: f32 = coord1; - let _e230: vec2 = vec2(_e228, 6.0); - let _e236: vec4 = textureSampleLevel(tex1D, samp, (_e230.x / _e230.y), 3.0, 5); - c = _e236; - let _e237: f32 = coord1; - let _e244: f32 = coord1; - let _e248: vec4 = vec4(_e244, 0.0, 0.0, 6.0); - let _e256: vec4 = textureSampleLevel(tex1D, samp, (_e248.xyz / vec3(_e248.w)).x, 3.0, 5); - c = _e256; - let _e257: f32 = coord1; - let _e261: f32 = coord1; - let _e263: vec2 = vec2(_e261, 6.0); - let _e268: vec4 = textureSample(tex1D, samp, (_e263.x / _e263.y), 5); - c = _e268; - let _e269: f32 = coord1; - let _e275: f32 = coord1; - let _e279: vec4 = vec4(_e275, 0.0, 0.0, 6.0); - let _e286: vec4 = textureSample(tex1D, samp, (_e279.xyz / vec3(_e279.w)).x, 5); - c = _e286; - let _e287: f32 = coord1; - let _e292: f32 = coord1; - let _e294: vec2 = vec2(_e292, 6.0); - let _e300: vec4 = textureSampleBias(tex1D, samp, (_e294.x / _e294.y), 2.0, 5); - c = _e300; - let _e301: f32 = coord1; - let _e308: f32 = coord1; - let _e312: vec4 = vec4(_e308, 0.0, 0.0, 6.0); - let _e320: vec4 = textureSampleBias(tex1D, samp, (_e312.xyz / vec3(_e312.w)).x, 2.0, 5); - c = _e320; + let e18: f32 = coord1; + let e19: vec4 = textureSample(tex1D, samp, e18); + c = e19; + let e22: f32 = coord1; + let e24: vec4 = textureSampleBias(tex1D, samp, e22, 2.0); + c = e24; + let e28: f32 = coord1; + let e31: vec4 = textureSampleGrad(tex1D, samp, e28, 4.0, 4.0); + c = e31; + let e36: f32 = coord1; + let e40: vec4 = textureSampleGrad(tex1D, samp, e36, 4.0, 4.0, 5); + c = e40; + let e43: f32 = coord1; + let e45: vec4 = textureSampleLevel(tex1D, samp, e43, 3.0); + c = e45; + let e49: f32 = coord1; + let e52: vec4 = textureSampleLevel(tex1D, samp, e49, 3.0, 5); + c = e52; + let e55: f32 = coord1; + let e57: vec4 = textureSample(tex1D, samp, e55, 5); + c = e57; + let e61: f32 = coord1; + let e64: vec4 = textureSampleBias(tex1D, samp, e61, 2.0, 5); + c = e64; + let e65: f32 = coord1; + let e68: f32 = coord1; + let e70: vec2 = vec2(e68, 6.0); + let e74: vec4 = textureSample(tex1D, samp, (e70.x / e70.y)); + c = e74; + let e75: f32 = coord1; + let e80: f32 = coord1; + let e84: vec4 = vec4(e80, 0.0, 0.0, 6.0); + let e90: vec4 = textureSample(tex1D, samp, (e84.xyz / vec3(e84.w)).x); + c = e90; + let e91: f32 = coord1; + let e95: f32 = coord1; + let e97: vec2 = vec2(e95, 6.0); + let e102: vec4 = textureSampleBias(tex1D, samp, (e97.x / e97.y), 2.0); + c = e102; + let e103: f32 = coord1; + let e109: f32 = coord1; + let e113: vec4 = vec4(e109, 0.0, 0.0, 6.0); + let e120: vec4 = textureSampleBias(tex1D, samp, (e113.xyz / vec3(e113.w)).x, 2.0); + c = e120; + let e121: f32 = coord1; + let e126: f32 = coord1; + let e128: vec2 = vec2(e126, 6.0); + let e134: vec4 = textureSampleGrad(tex1D, samp, (e128.x / e128.y), 4.0, 4.0); + c = e134; + let e135: f32 = coord1; + let e142: f32 = coord1; + let e146: vec4 = vec4(e142, 0.0, 0.0, 6.0); + let e154: vec4 = textureSampleGrad(tex1D, samp, (e146.xyz / vec3(e146.w)).x, 4.0, 4.0); + c = e154; + let e155: f32 = coord1; + let e161: f32 = coord1; + let e163: vec2 = vec2(e161, 6.0); + let e170: vec4 = textureSampleGrad(tex1D, samp, (e163.x / e163.y), 4.0, 4.0, 5); + c = e170; + let e171: f32 = coord1; + let e179: f32 = coord1; + let e183: vec4 = vec4(e179, 0.0, 0.0, 6.0); + let e192: vec4 = textureSampleGrad(tex1D, samp, (e183.xyz / vec3(e183.w)).x, 4.0, 4.0, 5); + c = e192; + let e193: f32 = coord1; + let e197: f32 = coord1; + let e199: vec2 = vec2(e197, 6.0); + let e204: vec4 = textureSampleLevel(tex1D, samp, (e199.x / e199.y), 3.0); + c = e204; + let e205: f32 = coord1; + let e211: f32 = coord1; + let e215: vec4 = vec4(e211, 0.0, 0.0, 6.0); + let e222: vec4 = textureSampleLevel(tex1D, samp, (e215.xyz / vec3(e215.w)).x, 3.0); + c = e222; + let e223: f32 = coord1; + let e228: f32 = coord1; + let e230: vec2 = vec2(e228, 6.0); + let e236: vec4 = textureSampleLevel(tex1D, samp, (e230.x / e230.y), 3.0, 5); + c = e236; + let e237: f32 = coord1; + let e244: f32 = coord1; + let e248: vec4 = vec4(e244, 0.0, 0.0, 6.0); + let e256: vec4 = textureSampleLevel(tex1D, samp, (e248.xyz / vec3(e248.w)).x, 3.0, 5); + c = e256; + let e257: f32 = coord1; + let e261: f32 = coord1; + let e263: vec2 = vec2(e261, 6.0); + let e268: vec4 = textureSample(tex1D, samp, (e263.x / e263.y), 5); + c = e268; + let e269: f32 = coord1; + let e275: f32 = coord1; + let e279: vec4 = vec4(e275, 0.0, 0.0, 6.0); + let e286: vec4 = textureSample(tex1D, samp, (e279.xyz / vec3(e279.w)).x, 5); + c = e286; + let e287: f32 = coord1; + let e292: f32 = coord1; + let e294: vec2 = vec2(e292, 6.0); + let e300: vec4 = textureSampleBias(tex1D, samp, (e294.x / e294.y), 2.0, 5); + c = e300; + let e301: f32 = coord1; + let e308: f32 = coord1; + let e312: vec4 = vec4(e308, 0.0, 0.0, 6.0); + let e320: vec4 = textureSampleBias(tex1D, samp, (e312.xyz / vec3(e312.w)).x, 2.0, 5); + c = e320; return; } @@ -145,30 +145,30 @@ fn testTex1DArray(coord2: vec2) { var c1: vec4; coord3 = coord2; - let _e18: vec2 = coord3; - let _e22: vec4 = textureSample(tex1DArray, samp, _e18.x, i32(_e18.x)); - c1 = _e22; - let _e25: vec2 = coord3; - let _e30: vec4 = textureSampleBias(tex1DArray, samp, _e25.x, i32(_e25.x), 2.0); - c1 = _e30; - let _e34: vec2 = coord3; - let _e40: vec4 = textureSampleGrad(tex1DArray, samp, _e34.x, i32(_e34.x), 4.0, 4.0); - c1 = _e40; - let _e45: vec2 = coord3; - let _e52: vec4 = textureSampleGrad(tex1DArray, samp, _e45.x, i32(_e45.x), 4.0, 4.0, 5); - c1 = _e52; - let _e55: vec2 = coord3; - let _e60: vec4 = textureSampleLevel(tex1DArray, samp, _e55.x, i32(_e55.x), 3.0); - c1 = _e60; - let _e64: vec2 = coord3; - let _e70: vec4 = textureSampleLevel(tex1DArray, samp, _e64.x, i32(_e64.x), 3.0, 5); - c1 = _e70; - let _e73: vec2 = coord3; - let _e78: vec4 = textureSample(tex1DArray, samp, _e73.x, i32(_e73.x), 5); - c1 = _e78; - let _e82: vec2 = coord3; - let _e88: vec4 = textureSampleBias(tex1DArray, samp, _e82.x, i32(_e82.x), 2.0, 5); - c1 = _e88; + let e18: vec2 = coord3; + let e22: vec4 = textureSample(tex1DArray, samp, e18.x, i32(e18.x)); + c1 = e22; + let e25: vec2 = coord3; + let e30: vec4 = textureSampleBias(tex1DArray, samp, e25.x, i32(e25.x), 2.0); + c1 = e30; + let e34: vec2 = coord3; + let e40: vec4 = textureSampleGrad(tex1DArray, samp, e34.x, i32(e34.x), 4.0, 4.0); + c1 = e40; + let e45: vec2 = coord3; + let e52: vec4 = textureSampleGrad(tex1DArray, samp, e45.x, i32(e45.x), 4.0, 4.0, 5); + c1 = e52; + let e55: vec2 = coord3; + let e60: vec4 = textureSampleLevel(tex1DArray, samp, e55.x, i32(e55.x), 3.0); + c1 = e60; + let e64: vec2 = coord3; + let e70: vec4 = textureSampleLevel(tex1DArray, samp, e64.x, i32(e64.x), 3.0, 5); + c1 = e70; + let e73: vec2 = coord3; + let e78: vec4 = textureSample(tex1DArray, samp, e73.x, i32(e73.x), 5); + c1 = e78; + let e82: vec2 = coord3; + let e88: vec4 = textureSampleBias(tex1DArray, samp, e82.x, i32(e82.x), 2.0, 5); + c1 = e88; return; } @@ -177,110 +177,110 @@ fn testTex2D(coord4: vec2) { var c2: vec4; coord5 = coord4; - let _e18: vec2 = coord5; - let _e19: vec4 = textureSample(tex2D, samp, _e18); - c2 = _e19; - let _e22: vec2 = coord5; - let _e24: vec4 = textureSampleBias(tex2D, samp, _e22, 2.0); - c2 = _e24; - let _e30: vec2 = coord5; - let _e35: vec4 = textureSampleGrad(tex2D, samp, _e30, vec2(4.0), vec2(4.0)); - c2 = _e35; - let _e43: vec2 = coord5; - let _e50: vec4 = textureSampleGrad(tex2D, samp, _e43, vec2(4.0), vec2(4.0), vec2(5, 5)); - c2 = _e50; - let _e53: vec2 = coord5; - let _e55: vec4 = textureSampleLevel(tex2D, samp, _e53, 3.0); - c2 = _e55; - let _e60: vec2 = coord5; - let _e64: vec4 = textureSampleLevel(tex2D, samp, _e60, 3.0, vec2(5, 5)); - c2 = _e64; - let _e68: vec2 = coord5; - let _e71: vec4 = textureSample(tex2D, samp, _e68, vec2(5, 5)); - c2 = _e71; - let _e76: vec2 = coord5; - let _e80: vec4 = textureSampleBias(tex2D, samp, _e76, 2.0, vec2(5, 5)); - c2 = _e80; - let _e81: vec2 = coord5; - let _e84: vec2 = coord5; - let _e86: vec3 = vec3(_e84, 6.0); - let _e91: vec4 = textureSample(tex2D, samp, (_e86.xy / vec2(_e86.z))); - c2 = _e91; - let _e92: vec2 = coord5; - let _e96: vec2 = coord5; - let _e99: vec4 = vec4(_e96, 0.0, 6.0); - let _e105: vec4 = textureSample(tex2D, samp, (_e99.xyz / vec3(_e99.w)).xy); - c2 = _e105; - let _e106: vec2 = coord5; - let _e110: vec2 = coord5; - let _e112: vec3 = vec3(_e110, 6.0); - let _e118: vec4 = textureSampleBias(tex2D, samp, (_e112.xy / vec2(_e112.z)), 2.0); - c2 = _e118; - let _e119: vec2 = coord5; - let _e124: vec2 = coord5; - let _e127: vec4 = vec4(_e124, 0.0, 6.0); - let _e134: vec4 = textureSampleBias(tex2D, samp, (_e127.xyz / vec3(_e127.w)).xy, 2.0); - c2 = _e134; - let _e135: vec2 = coord5; - let _e142: vec2 = coord5; - let _e144: vec3 = vec3(_e142, 6.0); - let _e153: vec4 = textureSampleGrad(tex2D, samp, (_e144.xy / vec2(_e144.z)), vec2(4.0), vec2(4.0)); - c2 = _e153; - let _e154: vec2 = coord5; - let _e162: vec2 = coord5; - let _e165: vec4 = vec4(_e162, 0.0, 6.0); - let _e175: vec4 = textureSampleGrad(tex2D, samp, (_e165.xyz / vec3(_e165.w)).xy, vec2(4.0), vec2(4.0)); - c2 = _e175; - let _e176: vec2 = coord5; - let _e185: vec2 = coord5; - let _e187: vec3 = vec3(_e185, 6.0); - let _e198: vec4 = textureSampleGrad(tex2D, samp, (_e187.xy / vec2(_e187.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); - c2 = _e198; - let _e199: vec2 = coord5; - let _e209: vec2 = coord5; - let _e212: vec4 = vec4(_e209, 0.0, 6.0); - let _e224: vec4 = textureSampleGrad(tex2D, samp, (_e212.xyz / vec3(_e212.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); - c2 = _e224; - let _e225: vec2 = coord5; - let _e229: vec2 = coord5; - let _e231: vec3 = vec3(_e229, 6.0); - let _e237: vec4 = textureSampleLevel(tex2D, samp, (_e231.xy / vec2(_e231.z)), 3.0); - c2 = _e237; - let _e238: vec2 = coord5; - let _e243: vec2 = coord5; - let _e246: vec4 = vec4(_e243, 0.0, 6.0); - let _e253: vec4 = textureSampleLevel(tex2D, samp, (_e246.xyz / vec3(_e246.w)).xy, 3.0); - c2 = _e253; - let _e254: vec2 = coord5; - let _e260: vec2 = coord5; - let _e262: vec3 = vec3(_e260, 6.0); - let _e270: vec4 = textureSampleLevel(tex2D, samp, (_e262.xy / vec2(_e262.z)), 3.0, vec2(5, 5)); - c2 = _e270; - let _e271: vec2 = coord5; - let _e278: vec2 = coord5; - let _e281: vec4 = vec4(_e278, 0.0, 6.0); - let _e290: vec4 = textureSampleLevel(tex2D, samp, (_e281.xyz / vec3(_e281.w)).xy, 3.0, vec2(5, 5)); - c2 = _e290; - let _e291: vec2 = coord5; - let _e296: vec2 = coord5; - let _e298: vec3 = vec3(_e296, 6.0); - let _e305: vec4 = textureSample(tex2D, samp, (_e298.xy / vec2(_e298.z)), vec2(5, 5)); - c2 = _e305; - let _e306: vec2 = coord5; - let _e312: vec2 = coord5; - let _e315: vec4 = vec4(_e312, 0.0, 6.0); - let _e323: vec4 = textureSample(tex2D, samp, (_e315.xyz / vec3(_e315.w)).xy, vec2(5, 5)); - c2 = _e323; - let _e324: vec2 = coord5; - let _e330: vec2 = coord5; - let _e332: vec3 = vec3(_e330, 6.0); - let _e340: vec4 = textureSampleBias(tex2D, samp, (_e332.xy / vec2(_e332.z)), 2.0, vec2(5, 5)); - c2 = _e340; - let _e341: vec2 = coord5; - let _e348: vec2 = coord5; - let _e351: vec4 = vec4(_e348, 0.0, 6.0); - let _e360: vec4 = textureSampleBias(tex2D, samp, (_e351.xyz / vec3(_e351.w)).xy, 2.0, vec2(5, 5)); - c2 = _e360; + let e18: vec2 = coord5; + let e19: vec4 = textureSample(tex2D, samp, e18); + c2 = e19; + let e22: vec2 = coord5; + let e24: vec4 = textureSampleBias(tex2D, samp, e22, 2.0); + c2 = e24; + let e30: vec2 = coord5; + let e35: vec4 = textureSampleGrad(tex2D, samp, e30, vec2(4.0), vec2(4.0)); + c2 = e35; + let e43: vec2 = coord5; + let e50: vec4 = textureSampleGrad(tex2D, samp, e43, vec2(4.0), vec2(4.0), vec2(5, 5)); + c2 = e50; + let e53: vec2 = coord5; + let e55: vec4 = textureSampleLevel(tex2D, samp, e53, 3.0); + c2 = e55; + let e60: vec2 = coord5; + let e64: vec4 = textureSampleLevel(tex2D, samp, e60, 3.0, vec2(5, 5)); + c2 = e64; + let e68: vec2 = coord5; + let e71: vec4 = textureSample(tex2D, samp, e68, vec2(5, 5)); + c2 = e71; + let e76: vec2 = coord5; + let e80: vec4 = textureSampleBias(tex2D, samp, e76, 2.0, vec2(5, 5)); + c2 = e80; + let e81: vec2 = coord5; + let e84: vec2 = coord5; + let e86: vec3 = vec3(e84, 6.0); + let e91: vec4 = textureSample(tex2D, samp, (e86.xy / vec2(e86.z))); + c2 = e91; + let e92: vec2 = coord5; + let e96: vec2 = coord5; + let e99: vec4 = vec4(e96, 0.0, 6.0); + let e105: vec4 = textureSample(tex2D, samp, (e99.xyz / vec3(e99.w)).xy); + c2 = e105; + let e106: vec2 = coord5; + let e110: vec2 = coord5; + let e112: vec3 = vec3(e110, 6.0); + let e118: vec4 = textureSampleBias(tex2D, samp, (e112.xy / vec2(e112.z)), 2.0); + c2 = e118; + let e119: vec2 = coord5; + let e124: vec2 = coord5; + let e127: vec4 = vec4(e124, 0.0, 6.0); + let e134: vec4 = textureSampleBias(tex2D, samp, (e127.xyz / vec3(e127.w)).xy, 2.0); + c2 = e134; + let e135: vec2 = coord5; + let e142: vec2 = coord5; + let e144: vec3 = vec3(e142, 6.0); + let e153: vec4 = textureSampleGrad(tex2D, samp, (e144.xy / vec2(e144.z)), vec2(4.0), vec2(4.0)); + c2 = e153; + let e154: vec2 = coord5; + let e162: vec2 = coord5; + let e165: vec4 = vec4(e162, 0.0, 6.0); + let e175: vec4 = textureSampleGrad(tex2D, samp, (e165.xyz / vec3(e165.w)).xy, vec2(4.0), vec2(4.0)); + c2 = e175; + let e176: vec2 = coord5; + let e185: vec2 = coord5; + let e187: vec3 = vec3(e185, 6.0); + let e198: vec4 = textureSampleGrad(tex2D, samp, (e187.xy / vec2(e187.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); + c2 = e198; + let e199: vec2 = coord5; + let e209: vec2 = coord5; + let e212: vec4 = vec4(e209, 0.0, 6.0); + let e224: vec4 = textureSampleGrad(tex2D, samp, (e212.xyz / vec3(e212.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); + c2 = e224; + let e225: vec2 = coord5; + let e229: vec2 = coord5; + let e231: vec3 = vec3(e229, 6.0); + let e237: vec4 = textureSampleLevel(tex2D, samp, (e231.xy / vec2(e231.z)), 3.0); + c2 = e237; + let e238: vec2 = coord5; + let e243: vec2 = coord5; + let e246: vec4 = vec4(e243, 0.0, 6.0); + let e253: vec4 = textureSampleLevel(tex2D, samp, (e246.xyz / vec3(e246.w)).xy, 3.0); + c2 = e253; + let e254: vec2 = coord5; + let e260: vec2 = coord5; + let e262: vec3 = vec3(e260, 6.0); + let e270: vec4 = textureSampleLevel(tex2D, samp, (e262.xy / vec2(e262.z)), 3.0, vec2(5, 5)); + c2 = e270; + let e271: vec2 = coord5; + let e278: vec2 = coord5; + let e281: vec4 = vec4(e278, 0.0, 6.0); + let e290: vec4 = textureSampleLevel(tex2D, samp, (e281.xyz / vec3(e281.w)).xy, 3.0, vec2(5, 5)); + c2 = e290; + let e291: vec2 = coord5; + let e296: vec2 = coord5; + let e298: vec3 = vec3(e296, 6.0); + let e305: vec4 = textureSample(tex2D, samp, (e298.xy / vec2(e298.z)), vec2(5, 5)); + c2 = e305; + let e306: vec2 = coord5; + let e312: vec2 = coord5; + let e315: vec4 = vec4(e312, 0.0, 6.0); + let e323: vec4 = textureSample(tex2D, samp, (e315.xyz / vec3(e315.w)).xy, vec2(5, 5)); + c2 = e323; + let e324: vec2 = coord5; + let e330: vec2 = coord5; + let e332: vec3 = vec3(e330, 6.0); + let e340: vec4 = textureSampleBias(tex2D, samp, (e332.xy / vec2(e332.z)), 2.0, vec2(5, 5)); + c2 = e340; + let e341: vec2 = coord5; + let e348: vec2 = coord5; + let e351: vec4 = vec4(e348, 0.0, 6.0); + let e360: vec4 = textureSampleBias(tex2D, samp, (e351.xyz / vec3(e351.w)).xy, 2.0, vec2(5, 5)); + c2 = e360; return; } @@ -289,72 +289,72 @@ fn testTex2DShadow(coord6: vec2) { var d: f32; coord7 = coord6; - let _e17: vec2 = coord7; - let _e20: vec2 = coord7; - let _e22: vec3 = vec3(_e20, 1.0); - let _e25: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e22.xy, _e22.z); - d = _e25; - let _e26: vec2 = coord7; - let _e33: vec2 = coord7; - let _e35: vec3 = vec3(_e33, 1.0); - let _e42: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e35.xy, _e35.z); - d = _e42; - let _e43: vec2 = coord7; - let _e52: vec2 = coord7; - let _e54: vec3 = vec3(_e52, 1.0); - let _e63: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e54.xy, _e54.z, vec2(5, 5)); - d = _e63; - let _e64: vec2 = coord7; - let _e68: vec2 = coord7; - let _e70: vec3 = vec3(_e68, 1.0); - let _e74: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e70.xy, _e70.z); - d = _e74; - let _e75: vec2 = coord7; - let _e81: vec2 = coord7; - let _e83: vec3 = vec3(_e81, 1.0); - let _e89: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e83.xy, _e83.z, vec2(5, 5)); - d = _e89; - let _e90: vec2 = coord7; - let _e95: vec2 = coord7; - let _e97: vec3 = vec3(_e95, 1.0); - let _e102: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e97.xy, _e97.z, vec2(5, 5)); - d = _e102; - let _e103: vec2 = coord7; - let _e107: vec2 = coord7; - let _e110: vec4 = vec4(_e107, 1.0, 6.0); - let _e114: vec3 = (_e110.xyz / vec3(_e110.w)); - let _e117: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e114.xy, _e114.z); - d = _e117; - let _e118: vec2 = coord7; - let _e126: vec2 = coord7; - let _e129: vec4 = vec4(_e126, 1.0, 6.0); - let _e137: vec3 = (_e129.xyz / vec3(_e129.w)); - let _e140: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e137.xy, _e137.z); - d = _e140; - let _e141: vec2 = coord7; - let _e151: vec2 = coord7; - let _e154: vec4 = vec4(_e151, 1.0, 6.0); - let _e164: vec3 = (_e154.xyz / vec3(_e154.w)); - let _e167: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e164.xy, _e164.z, vec2(5, 5)); - d = _e167; - let _e168: vec2 = coord7; - let _e173: vec2 = coord7; - let _e176: vec4 = vec4(_e173, 1.0, 6.0); - let _e181: vec3 = (_e176.xyz / vec3(_e176.w)); - let _e184: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e181.xy, _e181.z); - d = _e184; - let _e185: vec2 = coord7; - let _e192: vec2 = coord7; - let _e195: vec4 = vec4(_e192, 1.0, 6.0); - let _e202: vec3 = (_e195.xyz / vec3(_e195.w)); - let _e205: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e202.xy, _e202.z, vec2(5, 5)); - d = _e205; - let _e206: vec2 = coord7; - let _e212: vec2 = coord7; - let _e215: vec4 = vec4(_e212, 1.0, 6.0); - let _e221: vec3 = (_e215.xyz / vec3(_e215.w)); - let _e224: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e221.xy, _e221.z, vec2(5, 5)); - d = _e224; + let e17: vec2 = coord7; + let e20: vec2 = coord7; + let e22: vec3 = vec3(e20, 1.0); + let e25: f32 = textureSampleCompare(tex2DShadow, sampShadow, e22.xy, e22.z); + d = e25; + let e26: vec2 = coord7; + let e33: vec2 = coord7; + let e35: vec3 = vec3(e33, 1.0); + let e42: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e35.xy, e35.z); + d = e42; + let e43: vec2 = coord7; + let e52: vec2 = coord7; + let e54: vec3 = vec3(e52, 1.0); + let e63: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e54.xy, e54.z, vec2(5, 5)); + d = e63; + let e64: vec2 = coord7; + let e68: vec2 = coord7; + let e70: vec3 = vec3(e68, 1.0); + let e74: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e70.xy, e70.z); + d = e74; + let e75: vec2 = coord7; + let e81: vec2 = coord7; + let e83: vec3 = vec3(e81, 1.0); + let e89: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e83.xy, e83.z, vec2(5, 5)); + d = e89; + let e90: vec2 = coord7; + let e95: vec2 = coord7; + let e97: vec3 = vec3(e95, 1.0); + let e102: f32 = textureSampleCompare(tex2DShadow, sampShadow, e97.xy, e97.z, vec2(5, 5)); + d = e102; + let e103: vec2 = coord7; + let e107: vec2 = coord7; + let e110: vec4 = vec4(e107, 1.0, 6.0); + let e114: vec3 = (e110.xyz / vec3(e110.w)); + let e117: f32 = textureSampleCompare(tex2DShadow, sampShadow, e114.xy, e114.z); + d = e117; + let e118: vec2 = coord7; + let e126: vec2 = coord7; + let e129: vec4 = vec4(e126, 1.0, 6.0); + let e137: vec3 = (e129.xyz / vec3(e129.w)); + let e140: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e137.xy, e137.z); + d = e140; + let e141: vec2 = coord7; + let e151: vec2 = coord7; + let e154: vec4 = vec4(e151, 1.0, 6.0); + let e164: vec3 = (e154.xyz / vec3(e154.w)); + let e167: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e164.xy, e164.z, vec2(5, 5)); + d = e167; + let e168: vec2 = coord7; + let e173: vec2 = coord7; + let e176: vec4 = vec4(e173, 1.0, 6.0); + let e181: vec3 = (e176.xyz / vec3(e176.w)); + let e184: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e181.xy, e181.z); + d = e184; + let e185: vec2 = coord7; + let e192: vec2 = coord7; + let e195: vec4 = vec4(e192, 1.0, 6.0); + let e202: vec3 = (e195.xyz / vec3(e195.w)); + let e205: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e202.xy, e202.z, vec2(5, 5)); + d = e205; + let e206: vec2 = coord7; + let e212: vec2 = coord7; + let e215: vec4 = vec4(e212, 1.0, 6.0); + let e221: vec3 = (e215.xyz / vec3(e215.w)); + let e224: f32 = textureSampleCompare(tex2DShadow, sampShadow, e221.xy, e221.z, vec2(5, 5)); + d = e224; return; } @@ -363,30 +363,30 @@ fn testTex2DArray(coord8: vec3) { var c3: vec4; coord9 = coord8; - let _e18: vec3 = coord9; - let _e22: vec4 = textureSample(tex2DArray, samp, _e18.xy, i32(_e18.z)); - c3 = _e22; - let _e25: vec3 = coord9; - let _e30: vec4 = textureSampleBias(tex2DArray, samp, _e25.xy, i32(_e25.z), 2.0); - c3 = _e30; - let _e36: vec3 = coord9; - let _e44: vec4 = textureSampleGrad(tex2DArray, samp, _e36.xy, i32(_e36.z), vec2(4.0), vec2(4.0)); - c3 = _e44; - let _e52: vec3 = coord9; - let _e62: vec4 = textureSampleGrad(tex2DArray, samp, _e52.xy, i32(_e52.z), vec2(4.0), vec2(4.0), vec2(5, 5)); - c3 = _e62; - let _e65: vec3 = coord9; - let _e70: vec4 = textureSampleLevel(tex2DArray, samp, _e65.xy, i32(_e65.z), 3.0); - c3 = _e70; - let _e75: vec3 = coord9; - let _e82: vec4 = textureSampleLevel(tex2DArray, samp, _e75.xy, i32(_e75.z), 3.0, vec2(5, 5)); - c3 = _e82; - let _e86: vec3 = coord9; - let _e92: vec4 = textureSample(tex2DArray, samp, _e86.xy, i32(_e86.z), vec2(5, 5)); - c3 = _e92; - let _e97: vec3 = coord9; - let _e104: vec4 = textureSampleBias(tex2DArray, samp, _e97.xy, i32(_e97.z), 2.0, vec2(5, 5)); - c3 = _e104; + let e18: vec3 = coord9; + let e22: vec4 = textureSample(tex2DArray, samp, e18.xy, i32(e18.z)); + c3 = e22; + let e25: vec3 = coord9; + let e30: vec4 = textureSampleBias(tex2DArray, samp, e25.xy, i32(e25.z), 2.0); + c3 = e30; + let e36: vec3 = coord9; + let e44: vec4 = textureSampleGrad(tex2DArray, samp, e36.xy, i32(e36.z), vec2(4.0), vec2(4.0)); + c3 = e44; + let e52: vec3 = coord9; + let e62: vec4 = textureSampleGrad(tex2DArray, samp, e52.xy, i32(e52.z), vec2(4.0), vec2(4.0), vec2(5, 5)); + c3 = e62; + let e65: vec3 = coord9; + let e70: vec4 = textureSampleLevel(tex2DArray, samp, e65.xy, i32(e65.z), 3.0); + c3 = e70; + let e75: vec3 = coord9; + let e82: vec4 = textureSampleLevel(tex2DArray, samp, e75.xy, i32(e75.z), 3.0, vec2(5, 5)); + c3 = e82; + let e86: vec3 = coord9; + let e92: vec4 = textureSample(tex2DArray, samp, e86.xy, i32(e86.z), vec2(5, 5)); + c3 = e92; + let e97: vec3 = coord9; + let e104: vec4 = textureSampleBias(tex2DArray, samp, e97.xy, i32(e97.z), 2.0, vec2(5, 5)); + c3 = e104; return; } @@ -395,36 +395,36 @@ fn testTex2DArrayShadow(coord10: vec3) { var d1: f32; coord11 = coord10; - let _e17: vec3 = coord11; - let _e20: vec3 = coord11; - let _e22: vec4 = vec4(_e20, 1.0); - let _e27: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e22.xy, i32(_e22.z), _e22.w); - d1 = _e27; - let _e28: vec3 = coord11; - let _e35: vec3 = coord11; - let _e37: vec4 = vec4(_e35, 1.0); - let _e46: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e37.xy, i32(_e37.z), _e37.w); - d1 = _e46; - let _e47: vec3 = coord11; - let _e56: vec3 = coord11; - let _e58: vec4 = vec4(_e56, 1.0); - let _e69: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e58.xy, i32(_e58.z), _e58.w, vec2(5, 5)); - d1 = _e69; - let _e70: vec3 = coord11; - let _e74: vec3 = coord11; - let _e76: vec4 = vec4(_e74, 1.0); - let _e82: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e76.xy, i32(_e76.z), _e76.w); - d1 = _e82; - let _e83: vec3 = coord11; - let _e89: vec3 = coord11; - let _e91: vec4 = vec4(_e89, 1.0); - let _e99: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e91.xy, i32(_e91.z), _e91.w, vec2(5, 5)); - d1 = _e99; - let _e100: vec3 = coord11; - let _e105: vec3 = coord11; - let _e107: vec4 = vec4(_e105, 1.0); - let _e114: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e107.xy, i32(_e107.z), _e107.w, vec2(5, 5)); - d1 = _e114; + let e17: vec3 = coord11; + let e20: vec3 = coord11; + let e22: vec4 = vec4(e20, 1.0); + let e27: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e22.xy, i32(e22.z), e22.w); + d1 = e27; + let e28: vec3 = coord11; + let e35: vec3 = coord11; + let e37: vec4 = vec4(e35, 1.0); + let e46: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e37.xy, i32(e37.z), e37.w); + d1 = e46; + let e47: vec3 = coord11; + let e56: vec3 = coord11; + let e58: vec4 = vec4(e56, 1.0); + let e69: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e58.xy, i32(e58.z), e58.w, vec2(5, 5)); + d1 = e69; + let e70: vec3 = coord11; + let e74: vec3 = coord11; + let e76: vec4 = vec4(e74, 1.0); + let e82: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e76.xy, i32(e76.z), e76.w); + d1 = e82; + let e83: vec3 = coord11; + let e89: vec3 = coord11; + let e91: vec4 = vec4(e89, 1.0); + let e99: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e91.xy, i32(e91.z), e91.w, vec2(5, 5)); + d1 = e99; + let e100: vec3 = coord11; + let e105: vec3 = coord11; + let e107: vec4 = vec4(e105, 1.0); + let e114: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e107.xy, i32(e107.z), e107.w, vec2(5, 5)); + d1 = e114; return; } @@ -433,27 +433,27 @@ fn testTexCube(coord12: vec3) { var c4: vec4; coord13 = coord12; - let _e18: vec3 = coord13; - let _e19: vec4 = textureSample(texCube, samp, _e18); - c4 = _e19; - let _e22: vec3 = coord13; - let _e24: vec4 = textureSampleBias(texCube, samp, _e22, 2.0); - c4 = _e24; - let _e30: vec3 = coord13; - let _e35: vec4 = textureSampleGrad(texCube, samp, _e30, vec3(4.0), vec3(4.0)); - c4 = _e35; - let _e38: vec3 = coord13; - let _e40: vec4 = textureSampleLevel(texCube, samp, _e38, 3.0); - c4 = _e40; - let _e45: vec3 = coord13; - let _e49: vec4 = textureSampleLevel(texCube, samp, _e45, 3.0, vec3(5, 5, 5)); - c4 = _e49; - let _e53: vec3 = coord13; - let _e56: vec4 = textureSample(texCube, samp, _e53, vec3(5, 5, 5)); - c4 = _e56; - let _e61: vec3 = coord13; - let _e65: vec4 = textureSampleBias(texCube, samp, _e61, 2.0, vec3(5, 5, 5)); - c4 = _e65; + let e18: vec3 = coord13; + let e19: vec4 = textureSample(texCube, samp, e18); + c4 = e19; + let e22: vec3 = coord13; + let e24: vec4 = textureSampleBias(texCube, samp, e22, 2.0); + c4 = e24; + let e30: vec3 = coord13; + let e35: vec4 = textureSampleGrad(texCube, samp, e30, vec3(4.0), vec3(4.0)); + c4 = e35; + let e38: vec3 = coord13; + let e40: vec4 = textureSampleLevel(texCube, samp, e38, 3.0); + c4 = e40; + let e45: vec3 = coord13; + let e49: vec4 = textureSampleLevel(texCube, samp, e45, 3.0, vec3(5, 5, 5)); + c4 = e49; + let e53: vec3 = coord13; + let e56: vec4 = textureSample(texCube, samp, e53, vec3(5, 5, 5)); + c4 = e56; + let e61: vec3 = coord13; + let e65: vec4 = textureSampleBias(texCube, samp, e61, 2.0, vec3(5, 5, 5)); + c4 = e65; return; } @@ -462,31 +462,31 @@ fn testTexCubeShadow(coord14: vec3) { var d2: f32; coord15 = coord14; - let _e17: vec3 = coord15; - let _e20: vec3 = coord15; - let _e22: vec4 = vec4(_e20, 1.0); - let _e25: f32 = textureSampleCompare(texCubeShadow, sampShadow, _e22.xyz, _e22.w); - d2 = _e25; - let _e26: vec3 = coord15; - let _e33: vec3 = coord15; - let _e35: vec4 = vec4(_e33, 1.0); - let _e42: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e35.xyz, _e35.w); - d2 = _e42; - let _e43: vec3 = coord15; - let _e47: vec3 = coord15; - let _e49: vec4 = vec4(_e47, 1.0); - let _e53: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e49.xyz, _e49.w); - d2 = _e53; - let _e54: vec3 = coord15; - let _e60: vec3 = coord15; - let _e62: vec4 = vec4(_e60, 1.0); - let _e68: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e62.xyz, _e62.w, vec3(5, 5, 5)); - d2 = _e68; - let _e69: vec3 = coord15; - let _e74: vec3 = coord15; - let _e76: vec4 = vec4(_e74, 1.0); - let _e81: f32 = textureSampleCompare(texCubeShadow, sampShadow, _e76.xyz, _e76.w, vec3(5, 5, 5)); - d2 = _e81; + let e17: vec3 = coord15; + let e20: vec3 = coord15; + let e22: vec4 = vec4(e20, 1.0); + let e25: f32 = textureSampleCompare(texCubeShadow, sampShadow, e22.xyz, e22.w); + d2 = e25; + let e26: vec3 = coord15; + let e33: vec3 = coord15; + let e35: vec4 = vec4(e33, 1.0); + let e42: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e35.xyz, e35.w); + d2 = e42; + let e43: vec3 = coord15; + let e47: vec3 = coord15; + let e49: vec4 = vec4(e47, 1.0); + let e53: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e49.xyz, e49.w); + d2 = e53; + let e54: vec3 = coord15; + let e60: vec3 = coord15; + let e62: vec4 = vec4(e60, 1.0); + let e68: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e62.xyz, e62.w, vec3(5, 5, 5)); + d2 = e68; + let e69: vec3 = coord15; + let e74: vec3 = coord15; + let e76: vec4 = vec4(e74, 1.0); + let e81: f32 = textureSampleCompare(texCubeShadow, sampShadow, e76.xyz, e76.w, vec3(5, 5, 5)); + d2 = e81; return; } @@ -495,27 +495,27 @@ fn testTexCubeArray(coord16: vec4) { var c5: vec4; coord17 = coord16; - let _e18: vec4 = coord17; - let _e22: vec4 = textureSample(texCubeArray, samp, _e18.xyz, i32(_e18.w)); - c5 = _e22; - let _e25: vec4 = coord17; - let _e30: vec4 = textureSampleBias(texCubeArray, samp, _e25.xyz, i32(_e25.w), 2.0); - c5 = _e30; - let _e36: vec4 = coord17; - let _e44: vec4 = textureSampleGrad(texCubeArray, samp, _e36.xyz, i32(_e36.w), vec3(4.0), vec3(4.0)); - c5 = _e44; - let _e47: vec4 = coord17; - let _e52: vec4 = textureSampleLevel(texCubeArray, samp, _e47.xyz, i32(_e47.w), 3.0); - c5 = _e52; - let _e57: vec4 = coord17; - let _e64: vec4 = textureSampleLevel(texCubeArray, samp, _e57.xyz, i32(_e57.w), 3.0, vec3(5, 5, 5)); - c5 = _e64; - let _e68: vec4 = coord17; - let _e74: vec4 = textureSample(texCubeArray, samp, _e68.xyz, i32(_e68.w), vec3(5, 5, 5)); - c5 = _e74; - let _e79: vec4 = coord17; - let _e86: vec4 = textureSampleBias(texCubeArray, samp, _e79.xyz, i32(_e79.w), 2.0, vec3(5, 5, 5)); - c5 = _e86; + let e18: vec4 = coord17; + let e22: vec4 = textureSample(texCubeArray, samp, e18.xyz, i32(e18.w)); + c5 = e22; + let e25: vec4 = coord17; + let e30: vec4 = textureSampleBias(texCubeArray, samp, e25.xyz, i32(e25.w), 2.0); + c5 = e30; + let e36: vec4 = coord17; + let e44: vec4 = textureSampleGrad(texCubeArray, samp, e36.xyz, i32(e36.w), vec3(4.0), vec3(4.0)); + c5 = e44; + let e47: vec4 = coord17; + let e52: vec4 = textureSampleLevel(texCubeArray, samp, e47.xyz, i32(e47.w), 3.0); + c5 = e52; + let e57: vec4 = coord17; + let e64: vec4 = textureSampleLevel(texCubeArray, samp, e57.xyz, i32(e57.w), 3.0, vec3(5, 5, 5)); + c5 = e64; + let e68: vec4 = coord17; + let e74: vec4 = textureSample(texCubeArray, samp, e68.xyz, i32(e68.w), vec3(5, 5, 5)); + c5 = e74; + let e79: vec4 = coord17; + let e86: vec4 = textureSampleBias(texCubeArray, samp, e79.xyz, i32(e79.w), 2.0, vec3(5, 5, 5)); + c5 = e86; return; } @@ -524,9 +524,9 @@ fn testTexCubeArrayShadow(coord18: vec4) { var d3: f32; coord19 = coord18; - let _e19: vec4 = coord19; - let _e24: f32 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e19.xyz, i32(_e19.w), 1.0); - d3 = _e24; + let e19: vec4 = coord19; + let e24: f32 = textureSampleCompare(texCubeArrayShadow, sampShadow, e19.xyz, i32(e19.w), 1.0); + d3 = e24; return; } @@ -535,30 +535,30 @@ fn testTex3D(coord20: vec3) { var c6: vec4; coord21 = coord20; - let _e18: vec3 = coord21; - let _e19: vec4 = textureSample(tex3D, samp, _e18); - c6 = _e19; - let _e22: vec3 = coord21; - let _e24: vec4 = textureSampleBias(tex3D, samp, _e22, 2.0); - c6 = _e24; - let _e30: vec3 = coord21; - let _e35: vec4 = textureSampleGrad(tex3D, samp, _e30, vec3(4.0), vec3(4.0)); - c6 = _e35; - let _e43: vec3 = coord21; - let _e50: vec4 = textureSampleGrad(tex3D, samp, _e43, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); - c6 = _e50; - let _e53: vec3 = coord21; - let _e55: vec4 = textureSampleLevel(tex3D, samp, _e53, 3.0); - c6 = _e55; - let _e60: vec3 = coord21; - let _e64: vec4 = textureSampleLevel(tex3D, samp, _e60, 3.0, vec3(5, 5, 5)); - c6 = _e64; - let _e68: vec3 = coord21; - let _e71: vec4 = textureSample(tex3D, samp, _e68, vec3(5, 5, 5)); - c6 = _e71; - let _e76: vec3 = coord21; - let _e80: vec4 = textureSampleBias(tex3D, samp, _e76, 2.0, vec3(5, 5, 5)); - c6 = _e80; + let e18: vec3 = coord21; + let e19: vec4 = textureSample(tex3D, samp, e18); + c6 = e19; + let e22: vec3 = coord21; + let e24: vec4 = textureSampleBias(tex3D, samp, e22, 2.0); + c6 = e24; + let e30: vec3 = coord21; + let e35: vec4 = textureSampleGrad(tex3D, samp, e30, vec3(4.0), vec3(4.0)); + c6 = e35; + let e43: vec3 = coord21; + let e50: vec4 = textureSampleGrad(tex3D, samp, e43, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + c6 = e50; + let e53: vec3 = coord21; + let e55: vec4 = textureSampleLevel(tex3D, samp, e53, 3.0); + c6 = e55; + let e60: vec3 = coord21; + let e64: vec4 = textureSampleLevel(tex3D, samp, e60, 3.0, vec3(5, 5, 5)); + c6 = e64; + let e68: vec3 = coord21; + let e71: vec4 = textureSample(tex3D, samp, e68, vec3(5, 5, 5)); + c6 = e71; + let e76: vec3 = coord21; + let e80: vec4 = textureSampleBias(tex3D, samp, e76, 2.0, vec3(5, 5, 5)); + c6 = e80; return; } diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index e6b3967d7..376b66d87 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -32,8 +32,8 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { } let flip_correction: vec2 = vec2(0.5, -0.5); let light_local: vec2 = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - let _e26: f32 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); - return _e26; + let e26: f32 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); + return e26; } [[stage(fragment)]] @@ -43,24 +43,24 @@ fn fs_main([[location(0)]] raw_normal: vec3, [[location(1)]] position: vec4 let normal: vec3 = normalize(raw_normal); loop { - let _e12: u32 = i; - let _e15: u32 = u_globals.num_lights.x; - if ((_e12 >= min(_e15, c_max_lights))) { + let e12: u32 = i; + let e15: u32 = u_globals.num_lights.x; + if ((e12 >= min(e15, c_max_lights))) { break; } - let _e19: u32 = i; - let light: Light = s_lights.data[_e19]; - let _e22: u32 = i; - let _e25: f32 = fetch_shadow(_e22, (light.proj * position)); + let e19: u32 = i; + let light: Light = s_lights.data[e19]; + let e22: u32 = i; + let e25: f32 = fetch_shadow(e22, (light.proj * position)); let light_dir: vec3 = normalize((light.pos.xyz - position.xyz)); let diffuse: f32 = max(0.0, dot(normal, light_dir)); - let _e34: vec3 = color; - color = (_e34 + ((_e25 * diffuse) * light.color.xyz)); + let e34: vec3 = color; + color = (e34 + ((e25 * diffuse) * light.color.xyz)); continuing { - let _e40: u32 = i; - i = (_e40 + 1u); + let e40: u32 = i; + i = (e40 + 1u); } } - let _e43: vec3 = color; - return vec4(_e43, 1.0); + let e43: vec3 = color; + return vec4(e43, 1.0); } diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index 75460c49b..27565be73 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -23,20 +23,20 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { tmp1_ = (i32(vertex_index) / 2); tmp2_ = (i32(vertex_index) & 1); - let _e10: i32 = tmp1_; - let _e16: i32 = tmp2_; - let pos: vec4 = vec4(((f32(_e10) * 4.0) - 1.0), ((f32(_e16) * 4.0) - 1.0), 0.0, 1.0); - let _e27: vec4 = r_data.view[0]; - let _e31: vec4 = r_data.view[1]; - let _e35: vec4 = r_data.view[2]; - let inv_model_view: mat3x3 = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); - let _e40: mat4x4 = r_data.proj_inv; - let unprojected: vec4 = (_e40 * pos); + let e10: i32 = tmp1_; + let e16: i32 = tmp2_; + let pos: vec4 = vec4(((f32(e10) * 4.0) - 1.0), ((f32(e16) * 4.0) - 1.0), 0.0, 1.0); + let e27: vec4 = r_data.view[0]; + let e31: vec4 = r_data.view[1]; + let e35: vec4 = r_data.view[2]; + let inv_model_view: mat3x3 = transpose(mat3x3(e27.xyz, e31.xyz, e35.xyz)); + let e40: mat4x4 = r_data.proj_inv; + let unprojected: vec4 = (e40 * pos); return VertexOutput(pos, (inv_model_view * unprojected.xyz)); } [[stage(fragment)]] fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 { - let _e5: vec4 = textureSample(r_texture, r_sampler, in.uv); - return _e5; + let e5: vec4 = textureSample(r_texture, r_sampler, in.uv); + return e5; } diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index 63c0696f8..1e56f90a5 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -1,15 +1,15 @@ fn main1() { var x: vec3 = vec3(2.0, 2.0, 2.0); - let _e3: vec3 = x; - let _e8: vec2 = vec2(3.0, 4.0); - x.z = _e8.x; - x.x = _e8.y; - let _e13: vec3 = x; - let _e15: vec3 = x; - let _e18: vec2 = (_e15.xy * 5.0); - x.x = _e18.x; - x.y = _e18.y; + let e3: vec3 = x; + let e8: vec2 = vec2(3.0, 4.0); + x.z = e8.x; + x.x = e8.y; + let e13: vec3 = x; + let e15: vec3 = x; + let e18: vec2 = (e15.xy * 5.0); + x.x = e18.x; + x.y = e18.y; return; } diff --git a/tests/out/wgsl/texture-arg.wgsl b/tests/out/wgsl/texture-arg.wgsl index 420b43780..a013b1527 100644 --- a/tests/out/wgsl/texture-arg.wgsl +++ b/tests/out/wgsl/texture-arg.wgsl @@ -4,12 +4,12 @@ var Texture: texture_2d; var Sampler: sampler; fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { - let _e7: vec4 = textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); - return _e7; + let e7: vec4 = textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); + return e7; } [[stage(fragment)]] fn main() -> [[location(0)]] vec4 { - let _e2: vec4 = test(Texture, Sampler); - return _e2; + let e2: vec4 = test(Texture, Sampler); + return e2; } From cd65484a2219ef877ae8b653670fdfac7e590b57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 17 Sep 2021 21:34:33 +0100 Subject: [PATCH 1361/2212] [wgsl-in] Disallow identifiers starting with _ --- src/front/wgsl/lexer.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 1a3b63b2d..54a2660ea 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -336,7 +336,7 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { } } '0'..='9' => consume_number(input), - 'a'..='z' | 'A'..='Z' | '_' => { + 'a'..='z' | 'A'..='Z' => { let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); (Token::Word(word), rest) } @@ -655,6 +655,7 @@ fn test_tokens() { ); sub_test("No¾", &[Token::Word("No"), Token::Unknown('¾')]); sub_test("No好", &[Token::Word("No"), Token::Unknown('好')]); + sub_test("_No", &[Token::Unknown('_'), Token::Word("No")]); sub_test("\"\u{2}ПЀ\u{0}\"", &[Token::String("\u{2}ПЀ\u{0}")]); // https://github.com/gfx-rs/naga/issues/90 } From 60d0bf850b5bfeb87aeb5a0d4db6bb4059f80290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 19 Sep 2021 20:46:07 +0100 Subject: [PATCH 1362/2212] Add support for multi view extensions --- src/back/glsl/features.rs | 15 +++++++++++++++ src/back/glsl/mod.rs | 1 + src/back/hlsl/conv.rs | 3 +++ src/back/msl/mod.rs | 4 +++- src/back/spv/writer.rs | 27 +++++++++++++++++++++++++++ src/front/spv/convert.rs | 1 + src/front/spv/mod.rs | 1 + src/lib.rs | 1 + src/valid/interface.rs | 11 +++++++++++ 9 files changed, 63 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 425361586..d2e83e004 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -34,6 +34,7 @@ bitflags::bitflags! { const SAMPLE_VARIABLES = 1 << 15; /// Arrays with a dynamic length const DYNAMIC_ARRAY_SIZE = 1 << 16; + const MULTI_VIEW = 1 << 17; } } @@ -101,6 +102,7 @@ impl FeaturesManager { check_feature!(CULL_DISTANCE, 450, 300); check_feature!(SAMPLE_VARIABLES, 400, 300); check_feature!(DYNAMIC_ARRAY_SIZE, 430, 310); + check_feature!(MULTI_VIEW, 140, 310); // Return an error if there are missing features if missing.is_empty() { @@ -194,6 +196,16 @@ impl FeaturesManager { writeln!(out, "#extension GL_OES_sample_variables : require")?; } + if self.0.contains(Features::SAMPLE_VARIABLES) && version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/OES/OES_sample_variables.txt + writeln!(out, "#extension GL_OES_sample_variables : require")?; + } + + if self.0.contains(Features::MULTI_VIEW) { + // https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GL_EXT_multiview.txt + writeln!(out, "#extension GL_EXT_multiview : require")?; + } + Ok(()) } } @@ -372,6 +384,9 @@ impl<'a, W> Writer<'a, W> { crate::BuiltIn::SampleIndex => { self.features.request(Features::SAMPLE_VARIABLES) } + crate::BuiltIn::ViewIndex => { + self.features.request(Features::MULTI_VIEW) + } _ => {} }, Binding::Location { diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 62781147b..bc46c3d0e 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2625,6 +2625,7 @@ fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { "gl_FragCoord" } } + Bi::ViewIndex => "gl_ViewIndex", // vertex Bi::BaseInstance => "uint(gl_BaseInstance)", Bi::BaseVertex => "uint(gl_BaseVertex)", diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index b8cb10daa..eb6515f9c 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -103,6 +103,9 @@ impl crate::BuiltIn { Self::BaseInstance | Self::BaseVertex | Self::WorkGroupSize => { return Err(Error::Unimplemented(format!("builtin {:?}", self))) } + Self::ViewIndex => { + return Err(Error::Custom(format!("Unsupported builtin {:?}", self))) + } }) } } diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 8e840da05..de82096a4 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -358,7 +358,9 @@ impl ResolvedBinding { Bi::WorkGroupId => "threadgroup_position_in_grid", Bi::WorkGroupSize => "dispatch_threads_per_threadgroup", Bi::NumWorkGroups => "threadgroups_per_grid", - Bi::CullDistance => return Err(Error::UnsupportedBuiltIn(built_in)), + Bi::CullDistance | Bi::ViewIndex => { + return Err(Error::UnsupportedBuiltIn(built_in)) + } }; write!(out, "{}", name)?; } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4b83ff96d..c9d62f50b 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1159,6 +1159,10 @@ impl Writer { BuiltIn::FragCoord } } + Bi::ViewIndex => { + self.require_any("`view_index` built-in", &[spirv::Capability::MultiView])?; + BuiltIn::ViewIndex + } // vertex Bi::BaseInstance => BuiltIn::BaseInstance, Bi::BaseVertex => BuiltIn::BaseVertex, @@ -1284,6 +1288,19 @@ impl Writer { mod_info: &ModuleInfo, ep_index: Option, ) -> Result<(), Error> { + fn has_view_index_check( + ir_module: &crate::Module, + binding: Option<&crate::Binding>, + ty: Handle, + ) -> bool { + match ir_module.types[ty].inner { + crate::TypeInner::Struct { ref members, .. } => members.iter().any(|member| { + has_view_index_check(ir_module, member.binding.as_ref(), member.ty) + }), + _ => binding == Some(&crate::Binding::BuiltIn(crate::BuiltIn::ViewIndex)), + } + } + let has_storage_buffers = ir_module .global_variables @@ -1292,11 +1309,21 @@ impl Writer { crate::StorageClass::Storage { .. } => true, _ => false, }); + let has_view_index = ir_module + .entry_points + .iter() + .flat_map(|entry| entry.function.arguments.iter()) + .any(|arg| has_view_index_check(ir_module, arg.binding.as_ref(), arg.ty)); + if self.physical_layout.version < 0x10300 && has_storage_buffers { // enable the storage buffer class on < SPV-1.3 Instruction::extension("SPV_KHR_storage_buffer_storage_class") .to_words(&mut self.logical_layout.extensions); } + if has_view_index { + Instruction::extension("SPV_KHR_multiview") + .to_words(&mut self.logical_layout.extensions) + } Instruction::type_void(self.void_type).to_words(&mut self.logical_layout.declarations); Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 569cb5865..ce9055152 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -121,6 +121,7 @@ pub(super) fn map_builtin(word: spirv::Word) -> Result { use spirv::BuiltIn as Bi; Ok(match spirv::BuiltIn::from_u32(word) { Some(Bi::Position) | Some(Bi::FragCoord) => crate::BuiltIn::Position, + Some(Bi::ViewIndex) => crate::BuiltIn::ViewIndex, // vertex Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, Some(Bi::BaseVertex) => crate::BuiltIn::BaseVertex, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index cdb8e89d9..4869a4786 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -75,6 +75,7 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ pub const SUPPORTED_EXTENSIONS: &[&str] = &[ "SPV_KHR_storage_buffer_storage_class", "SPV_KHR_vulkan_memory_model", + "SPV_KHR_multiview", ]; pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"]; diff --git a/src/lib.rs b/src/lib.rs index 97af89d3f..3c8325485 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -307,6 +307,7 @@ pub enum StorageClass { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum BuiltIn { Position, + ViewIndex, // vertex BaseInstance, BaseVertex, diff --git a/src/valid/interface.rs b/src/valid/interface.rs index dccd02bd6..9253042af 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -158,6 +158,17 @@ impl VaryingContext<'_> { width, }, ), + Bi::ViewIndex => ( + match self.stage { + St::Vertex | St::Fragment => !self.output, + St::Compute => false, + }, + *ty_inner + == Ti::Scalar { + kind: Sk::Sint, + width, + }, + ), Bi::FragDepth => ( self.stage == St::Fragment && self.output, *ty_inner From dc8a41de04068b4766c1e74f9d77f765e815172a Mon Sep 17 00:00:00 2001 From: Aleksi Sapon Date: Fri, 17 Sep 2021 16:54:48 -0400 Subject: [PATCH 1363/2212] spv-in: no case fallthrough when last statement allows it --- src/front/spv/function.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 8814bb59b..90ea81033 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -576,11 +576,19 @@ impl<'function> BlockContext<'function> { .map(|&(value, body_idx)| { let body = lower_impl(blocks, bodies, body_idx); + // Handle simple cases that would make a fallthrough statement unreachable code + let fall_through = match body.last() { + Some(&crate::Statement::Break) + | Some(&crate::Statement::Continue) + | Some(&crate::Statement::Kill) + | Some(&crate::Statement::Return { .. }) => false, + _ => true, + }; + crate::SwitchCase { value, body, - // TODO - fall_through: true, + fall_through, } }) .collect(), From 98944bb7a65dd18e251752912b9c72368333a706 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 20 Sep 2021 16:45:53 +0100 Subject: [PATCH 1364/2212] Track finished across compound statements --- src/valid/function.rs | 65 ++++++++++++++++++++++++++----------------- tests/wgsl-errors.rs | 31 +++++++++++++++++++++ 2 files changed, 70 insertions(+), 26 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 703c1474f..ff39fcd57 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -135,6 +135,11 @@ bitflags::bitflags! { } } +struct BlockInfo { + stages: ShaderStages, + finished: bool, +} + struct BlockContext<'a> { abilities: ControlFlowAbility, info: &'a FunctionInfo, @@ -326,7 +331,7 @@ impl super::Validator { &mut self, statements: &[crate::Statement], context: &BlockContext, - ) -> Result { + ) -> Result { use crate::{Statement as S, TypeInner as Ti}; let mut finished = false; let mut stages = ShaderStages::all(); @@ -345,7 +350,9 @@ impl super::Validator { } } S::Block(ref block) => { - stages &= self.validate_block(block, context)?; + let info = self.validate_block(block, context)?; + stages &= info.stages; + finished = info.finished; } S::If { condition, @@ -359,8 +366,8 @@ impl super::Validator { } => {} _ => return Err(FunctionError::InvalidIfType(condition)), } - stages &= self.validate_block(accept, context)?; - stages &= self.validate_block(reject, context)?; + stages &= self.validate_block(accept, context)?.stages; + stages &= self.validate_block(reject, context)?.stages; } S::Switch { selector, @@ -385,9 +392,9 @@ impl super::Validator { let sub_context = context.with_abilities(pass_through_abilities | ControlFlowAbility::BREAK); for case in cases { - stages &= self.validate_block(&case.body, &sub_context)?; + stages &= self.validate_block(&case.body, &sub_context)?.stages; } - stages &= self.validate_block(default, &sub_context)?; + stages &= self.validate_block(default, &sub_context)?.stages; } S::Loop { ref body, @@ -397,18 +404,22 @@ impl super::Validator { // because the continuing{} block inherits the scope let base_expression_count = self.valid_expression_list.len(); let pass_through_abilities = context.abilities & ControlFlowAbility::RETURN; - stages &= self.validate_block_impl( - body, - &context.with_abilities( - pass_through_abilities - | ControlFlowAbility::BREAK - | ControlFlowAbility::CONTINUE, - ), - )?; - stages &= self.validate_block_impl( - continuing, - &context.with_abilities(ControlFlowAbility::empty()), - )?; + stages &= self + .validate_block_impl( + body, + &context.with_abilities( + pass_through_abilities + | ControlFlowAbility::BREAK + | ControlFlowAbility::CONTINUE, + ), + )? + .stages; + stages &= self + .validate_block_impl( + continuing, + &context.with_abilities(ControlFlowAbility::empty()), + )? + .stages; for handle in self.valid_expression_list.drain(base_expression_count..) { self.valid_expression_set.remove(handle.index()); } @@ -593,20 +604,20 @@ impl super::Validator { } } } - Ok(stages) + Ok(BlockInfo { stages, finished }) } fn validate_block( &mut self, statements: &[crate::Statement], context: &BlockContext, - ) -> Result { + ) -> Result { let base_expression_count = self.valid_expression_list.len(); - let stages = self.validate_block_impl(statements, context)?; + let info = self.validate_block_impl(statements, context)?; for handle in self.valid_expression_list.drain(base_expression_count..) { self.valid_expression_set.remove(handle.index()); } - Ok(stages) + Ok(info) } fn validate_local_var( @@ -694,10 +705,12 @@ impl super::Validator { } if self.flags.contains(ValidationFlags::BLOCKS) { - let stages = self.validate_block( - &fun.body, - &BlockContext::new(fun, module, &info, &mod_info.functions), - )?; + let stages = self + .validate_block( + &fun.body, + &BlockContext::new(fun, module, &info, &mod_info.functions), + )? + .stages; info.available_stages &= stages; } Ok(info) diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 44c5706e0..941865ab9 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -848,3 +848,34 @@ fn invalid_local_vars() { if local_var_name == "not_okay" } } + +#[test] +fn dead_code() { + check_validation_error! { + " + fn dead_code_after_if(condition: bool) -> i32 { + if (condition) { + return 1; + } else { + return 2; + } + return 3; + } + ": + Ok(_) + } + check_validation_error! { + " + fn dead_code_after_block() -> i32 { + { + return 1; + } + return 2; + } + ": + Err(naga::valid::ValidationError::Function { + error: naga::valid::FunctionError::InstructionsAfterReturn, + .. + }) + } +} From 42db64628ed2b42b439a7e7cacc957e6b209a077 Mon Sep 17 00:00:00 2001 From: Aleksi Sapon Date: Mon, 20 Sep 2021 16:18:01 -0400 Subject: [PATCH 1365/2212] wgsl-out: vector bitcast --- src/back/wgsl/writer.rs | 17 +++++++++++------ tests/out/wgsl/operators.wgsl | 2 +- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 7f05d7915..5c0b61cb4 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1287,12 +1287,17 @@ impl Writer { )?; } TypeInner::Vector { size, .. } => { - write!( - self.out, - "vec{}<{}>", - back::vector_size_str(size), - scalar_kind_str(kind) - )?; + let vector_size_str = back::vector_size_str(size); + let scalar_kind_str = scalar_kind_str(kind); + if convert.is_some() { + write!(self.out, "vec{}<{}>", vector_size_str, scalar_kind_str)?; + } else { + write!( + self.out, + "bitcast>", + vector_size_str, scalar_kind_str + )?; + } } TypeInner::Scalar { .. } => { if convert.is_some() { diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index f43c1c88a..6c7ab1147 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -14,7 +14,7 @@ fn builtins() -> vec4 { let m1_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); let b1_: f32 = bitcast(vec4(1, 1, 1, 1).x); - let b2_: vec4 = vec4(vec4(1, 1, 1, 1)); + let b2_: vec4 = bitcast>(vec4(1, 1, 1, 1)); let v_i32_zero: vec4 = vec4(vec4(0.0, 0.0, 0.0, 0.0)); return (((((vec4((vec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } From af44603e47de7a8009837f7e6be969ede4f8c110 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 21 Sep 2021 15:51:27 +0100 Subject: [PATCH 1366/2212] [glsl-in] Use Span instead of SourceMetadata --- cli/src/main.rs | 8 ++- src/front/glsl/ast.rs | 4 +- src/front/glsl/builtins.rs | 59 +++++++++---------- src/front/glsl/context.rs | 62 +++++++++----------- src/front/glsl/error.rs | 8 +-- src/front/glsl/functions.rs | 34 +++++------ src/front/glsl/lex.rs | 35 +++++------ src/front/glsl/mod.rs | 4 +- src/front/glsl/offset.rs | 4 +- src/front/glsl/parser.rs | 22 +++---- src/front/glsl/parser/declarations.rs | 27 +++++---- src/front/glsl/parser/expressions.rs | 61 ++++++++++--------- src/front/glsl/parser/functions.rs | 74 ++++++++++++----------- src/front/glsl/parser/types.rs | 48 +++++++-------- src/front/glsl/parser_tests.rs | 27 +++------ src/front/glsl/token.rs | 84 ++------------------------- src/front/glsl/types.rs | 19 +++--- src/front/glsl/variables.rs | 24 ++++---- 18 files changed, 256 insertions(+), 348 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 7bda20c54..96c7b378e 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -465,9 +465,11 @@ pub fn emit_glsl_parser_error(errors: Vec, filename: & let writer = StandardStream::stderr(ColorChoice::Auto); for err in errors { - let diagnostic = Diagnostic::error() - .with_message(err.kind.to_string()) - .with_labels(vec![Label::primary((), err.meta.start..err.meta.end)]); + let mut diagnostic = Diagnostic::error().with_message(err.kind.to_string()); + + if let Some(range) = err.meta.to_range() { + diagnostic = diagnostic.with_labels(vec![Label::primary((), range)]); + } term::emit(&mut writer.lock(), &config, &files, &diagnostic).expect("cannot write error"); } diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 779d17223..36cd777dc 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,6 +1,6 @@ use std::fmt; -use super::{builtins::MacroCall, context::ExprPos, SourceMetadata}; +use super::{builtins::MacroCall, context::ExprPos, Span}; use crate::{ BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, Interpolation, Sampling, StorageAccess, StorageClass, Type, UnaryOperator, @@ -89,7 +89,7 @@ pub struct VariableReference { #[derive(Debug, Clone)] pub struct HirExpr { pub kind: HirExprKind, - pub meta: SourceMetadata, + pub meta: Span, } #[derive(Debug, Clone)] diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index a8030bf6d..5f7fd49d1 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1,7 +1,7 @@ use super::{ ast::{FunctionDeclaration, FunctionKind, Overload, ParameterInfo, ParameterQualifier}, context::Context, - Error, ErrorKind, Parser, Result, SourceMetadata, + Error, ErrorKind, Parser, Result, }; use crate::{ BinaryOperator, Block, Constant, ConstantInner, DerivativeAxis, Expression, Handle, ImageClass, @@ -1474,7 +1474,7 @@ impl MacroCall { ctx: &mut Context, body: &mut Block, args: &mut [Handle], - meta: SourceMetadata, + meta: Span, ) -> Result> { match *self { MacroCall::Sampler => { @@ -1505,7 +1505,7 @@ impl MacroCall { base: coords, index: size as u32 - 1, }, - SourceMetadata::none(), + Span::default(), body, ); let left = if let VectorSize::Bi = size { @@ -1514,7 +1514,7 @@ impl MacroCall { base: coords, index: 0, }, - SourceMetadata::none(), + Span::default(), body, ) } else { @@ -1524,10 +1524,10 @@ impl MacroCall { }; right = ctx.add_expression( Expression::Splat { size, value: right }, - SourceMetadata::none(), + Span::default(), body, ); - ctx.vector_resize(size, coords, SourceMetadata::none(), body) + ctx.vector_resize(size, coords, Span::default(), body) }; coords = ctx.add_expression( Expression::Binary { @@ -1535,7 +1535,7 @@ impl MacroCall { left, right, }, - SourceMetadata::none(), + Span::default(), body, ); } @@ -1617,7 +1617,7 @@ impl MacroCall { level: args.get(1).copied(), }, }, - SourceMetadata::none(), + Span::default(), body, )), MacroCall::TexelFetch => { @@ -1630,7 +1630,7 @@ impl MacroCall { array_index: comps.array_index, index: Some(args[2]), }, - SourceMetadata::none(), + Span::default(), body, )) } @@ -1641,7 +1641,7 @@ impl MacroCall { arg1: args.get(1).copied(), arg2: args.get(2).copied(), }, - SourceMetadata::none(), + Span::default(), body, )), MacroCall::Relational(fun) => Ok(ctx.add_expression( @@ -1649,7 +1649,7 @@ impl MacroCall { fun, argument: args[0], }, - SourceMetadata::none(), + Span::default(), body, )), MacroCall::Binary(op) => Ok(ctx.add_expression( @@ -1658,7 +1658,7 @@ impl MacroCall { left: args[0], right: args[1], }, - SourceMetadata::none(), + Span::default(), body, )), MacroCall::Mod(size) => { @@ -1670,7 +1670,7 @@ impl MacroCall { left: args[0], right: args[1], }, - SourceMetadata::none(), + Span::default(), body, )) } @@ -1684,7 +1684,7 @@ impl MacroCall { arg1: args.get(1).copied(), arg2: args.get(2).copied(), }, - SourceMetadata::none(), + Span::default(), body, )) } @@ -1694,7 +1694,7 @@ impl MacroCall { accept: args[1], reject: args[0], }, - SourceMetadata::none(), + Span::default(), body, )), MacroCall::Clamp(size) => { @@ -1708,7 +1708,7 @@ impl MacroCall { arg1: args.get(1).copied(), arg2: args.get(2).copied(), }, - SourceMetadata::none(), + Span::default(), body, )) } @@ -1724,18 +1724,15 @@ impl MacroCall { }, Span::default(), ); - let right = ctx.add_expression( - Expression::Constant(constant), - SourceMetadata::none(), - body, - ); + let right = + ctx.add_expression(Expression::Constant(constant), Span::default(), body); Ok(ctx.add_expression( Expression::Binary { op: BinaryOperator::Multiply, left: args[0], right, }, - SourceMetadata::none(), + Span::default(), body, )) } @@ -1745,7 +1742,7 @@ impl MacroCall { kind, convert: None, }, - SourceMetadata::none(), + Span::default(), body, )), MacroCall::Derivate(axis) => Ok(ctx.add_expression( @@ -1753,7 +1750,7 @@ impl MacroCall { axis, expr: args[0], }, - SourceMetadata::none(), + Span::default(), body, )), } @@ -1767,7 +1764,7 @@ fn texture_call( comps: CoordComponents, offset: Option>, body: &mut Block, - meta: SourceMetadata, + meta: Span, ) -> Result> { if let Some(sampler) = ctx.samplers.get(&image).copied() { let mut array_index = comps.array_index; @@ -1816,7 +1813,7 @@ impl Parser { image: Handle, coord: Handle, extra: Option>, - meta: SourceMetadata, + meta: Span, body: &mut Block, ) -> Result { if let TypeInner::Image { @@ -1842,14 +1839,14 @@ impl Parser { let coordinate = match (image_size, coord_size) { (Some(size), Some(coord_s)) if size != coord_s => { - ctx.vector_resize(size, coord, SourceMetadata::none(), body) + ctx.vector_resize(size, coord, Span::default(), body) } (None, Some(_)) => ctx.add_expression( Expression::AccessIndex { base: coord, index: 0, }, - SourceMetadata::none(), + Span::default(), body, ), _ => coord, @@ -1864,7 +1861,7 @@ impl Parser { Some(ctx.add_expression( Expression::AccessIndex { base: coord, index }, - SourceMetadata::none(), + Span::default(), body, )) } @@ -1881,7 +1878,7 @@ impl Parser { } else { Some(ctx.add_expression( Expression::AccessIndex { base: coord, index }, - SourceMetadata::none(), + Span::default(), body, )) } @@ -1917,7 +1914,7 @@ pub fn sampled_to_depth( module: &mut Module, ctx: &mut Context, image: Handle, - meta: SourceMetadata, + meta: Span, errors: &mut Vec, ) -> Result<()> { let ty = match ctx[image] { diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 9d35bf1ce..d6dfa2738 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -5,13 +5,13 @@ use super::{ }, error::{Error, ErrorKind}, types::{scalar_components, type_power}, - Parser, Result, SourceMetadata, + Parser, Result, }; use crate::{ front::{Emitter, Typifier}, Arena, BinaryOperator, Block, Constant, Expression, FastHashMap, FunctionArgument, Handle, - LocalVariable, RelationalFunction, ScalarKind, ScalarValue, Statement, StorageClass, Type, - TypeInner, VectorSize, + LocalVariable, RelationalFunction, ScalarKind, ScalarValue, Span, Statement, StorageClass, + Type, TypeInner, VectorSize, }; use std::{convert::TryFrom, ops::Index}; @@ -181,14 +181,14 @@ impl Context { pub fn add_expression( &mut self, expr: Expression, - meta: SourceMetadata, + meta: Span, body: &mut Block, ) -> Handle { let needs_pre_emit = expr.needs_pre_emit(); if needs_pre_emit { self.emit_flush(body); } - let handle = self.expressions.append(expr, meta.as_span()); + let handle = self.expressions.append(expr, meta); if needs_pre_emit { self.emit_start(); } @@ -238,7 +238,7 @@ impl Context { &mut self, parser: &mut Parser, body: &mut Block, - name_meta: Option<(String, SourceMetadata)>, + name_meta: Option<(String, Span)>, ty: Handle, qualifier: ParameterQualifier, ) { @@ -288,7 +288,7 @@ impl Context { ty, init: None, }, - meta.as_span(), + meta, ); let local_expr = self.add_expression(Expression::LocalVariable(handle), meta, body); @@ -300,7 +300,7 @@ impl Context { pointer: local_expr, value: expr, }, - meta.as_span(), + meta, ); if let Some(current) = self.scopes.last_mut() { @@ -360,7 +360,7 @@ impl Context { expr: Handle, pos: ExprPos, body: &mut Block, - ) -> Result<(Option>, SourceMetadata)> { + ) -> Result<(Option>, Span)> { let res = self.lower_inner(&stmt, parser, expr, pos, body); stmt.hir_exprs.clear(); @@ -381,7 +381,7 @@ impl Context { expr: Handle, pos: ExprPos, body: &mut Block, - ) -> Result<(Handle, SourceMetadata)> { + ) -> Result<(Handle, Span)> { let res = self.lower_expect_inner(&stmt, parser, expr, pos, body); stmt.hir_exprs.clear(); @@ -402,7 +402,7 @@ impl Context { expr: Handle, pos: ExprPos, body: &mut Block, - ) -> Result<(Handle, SourceMetadata)> { + ) -> Result<(Handle, Span)> { let (maybe_expr, meta) = self.lower_inner(stmt, parser, expr, pos, body)?; let expr = match maybe_expr { @@ -426,7 +426,7 @@ impl Context { expr: Handle, pos: ExprPos, body: &mut Block, - ) -> Result<(Option>, SourceMetadata)> { + ) -> Result<(Option>, Span)> { let HirExpr { ref kind, meta } = stmt.hir_exprs[expr]; let handle = match *kind { @@ -523,7 +523,7 @@ impl Context { let argument = self .expressions - .append(Expression::Binary { op, left, right }, meta.as_span()); + .append(Expression::Binary { op, left, right }, meta); self.add_expression( Expression::Relational { fun, argument }, @@ -622,14 +622,10 @@ impl Context { ty, init: Some(constant), }, - crate::Span::default(), + Span::default(), ); - self.add_expression( - Expression::LocalVariable(local), - SourceMetadata::none(), - body, - ) + self.add_expression(Expression::LocalVariable(local), Span::default(), body) } else { var.expr } @@ -738,14 +734,14 @@ impl Context { pointer: dst, value: src, }, - meta.as_span(), + meta, ); } } else { self.emit_flush(body); self.emit_start(); - body.push(Statement::Store { pointer, value }, meta.as_span()); + body.push(Statement::Store { pointer, value }, meta); } value @@ -827,7 +823,7 @@ impl Context { name: None, inner: ty_inner, }, - meta.as_span(), + meta, ); right = self.add_expression( @@ -846,7 +842,7 @@ impl Context { self.emit_flush(body); self.emit_start(); - body.push(Statement::Store { pointer, value }, meta.as_span()); + body.push(Statement::Store { pointer, value }, meta); if postfix { left @@ -872,7 +868,7 @@ impl Context { &mut self, parser: &mut Parser, expr: Handle, - meta: SourceMetadata, + meta: Span, ) -> Result> { let ty = parser.resolve_type(self, expr, meta)?; Ok(scalar_components(ty)) @@ -882,7 +878,7 @@ impl Context { &mut self, parser: &mut Parser, expr: Handle, - meta: SourceMetadata, + meta: Span, ) -> Result> { Ok(self .expr_scalar_components(parser, expr, meta)? @@ -892,7 +888,7 @@ impl Context { pub fn conversion( &mut self, expr: &mut Handle, - meta: SourceMetadata, + meta: Span, kind: ScalarKind, width: crate::Bytes, ) -> Result<()> { @@ -902,7 +898,7 @@ impl Context { kind, convert: Some(width), }, - meta.as_span(), + meta, ); Ok(()) @@ -912,7 +908,7 @@ impl Context { &mut self, parser: &mut Parser, expr: &mut Handle, - meta: SourceMetadata, + meta: Span, kind: ScalarKind, width: crate::Bytes, ) -> Result<()> { @@ -932,9 +928,9 @@ impl Context { &mut self, parser: &mut Parser, left: &mut Handle, - left_meta: SourceMetadata, + left_meta: Span, right: &mut Handle, - right_meta: SourceMetadata, + right_meta: Span, ) -> Result<()> { let left_components = self.expr_scalar_components(parser, *left, left_meta)?; let right_components = self.expr_scalar_components(parser, *right, right_meta)?; @@ -965,7 +961,7 @@ impl Context { &mut self, parser: &mut Parser, expr: &mut Handle, - meta: SourceMetadata, + meta: Span, vector_size: Option, ) -> Result<()> { let expr_type = parser.resolve_type(self, *expr, meta)?; @@ -973,7 +969,7 @@ impl Context { if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { *expr = self .expressions - .append(Expression::Splat { size, value: *expr }, meta.as_span()) + .append(Expression::Splat { size, value: *expr }, meta) } Ok(()) @@ -983,7 +979,7 @@ impl Context { &mut self, size: VectorSize, vector: Handle, - meta: SourceMetadata, + meta: Span, body: &mut Block, ) -> Handle { self.add_expression( diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 0a3c75298..132a4208f 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -1,7 +1,5 @@ -use super::{ - constants::ConstantSolvingError, - token::{SourceMetadata, TokenValue}, -}; +use super::{constants::ConstantSolvingError, token::TokenValue}; +use crate::Span; use pp_rs::token::PreprocessorError; use std::borrow::Cow; use thiserror::Error; @@ -122,5 +120,5 @@ pub struct Error { /// Holds the information about the error itself. pub kind: ErrorKind, /// Holds information about the range of the source code where the error happened. - pub meta: SourceMetadata, + pub meta: Span, } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 95d434700..36db43c0c 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -4,7 +4,7 @@ use super::{ context::{Context, ExprPos, StmtContext}, error::{Error, ErrorKind}, types::scalar_components, - Parser, Result, SourceMetadata, + Parser, Result, }; use crate::{ front::glsl::types::type_power, proc::ensure_block_returns, Arena, Block, Constant, @@ -18,7 +18,7 @@ impl Parser { &mut self, scalar_kind: ScalarKind, value: u64, - meta: SourceMetadata, + meta: Span, ) -> Handle { let value = match scalar_kind { ScalarKind::Uint => ScalarValue::Uint(value), @@ -33,7 +33,7 @@ impl Parser { specialization: None, inner: ConstantInner::Scalar { width: 4, value }, }, - meta.as_span(), + meta, ) } @@ -44,7 +44,7 @@ impl Parser { body: &mut Block, fc: FunctionCallKind, raw_args: &[Handle], - meta: SourceMetadata, + meta: Span, ) -> Result>> { let args: Vec<_> = raw_args .iter() @@ -158,7 +158,7 @@ impl Parser { width, }, }, - meta.as_span(), + meta, ); let zero_constant = self.module.constants.fetch_or_append( Constant { @@ -169,7 +169,7 @@ impl Parser { value: ScalarValue::Float(0.0), }, }, - meta.as_span(), + meta, ); let zero = ctx.add_expression( Expression::Constant(zero_constant), @@ -305,7 +305,7 @@ impl Parser { width, }, }, - meta.as_span(), + meta, ); for chunk in flattened.chunks(rows as usize) { @@ -350,9 +350,9 @@ impl Parser { stmt: &StmtContext, body: &mut Block, name: String, - args: Vec<(Handle, SourceMetadata)>, + args: Vec<(Handle, Span)>, raw_args: &[Handle], - meta: SourceMetadata, + meta: Span, ) -> Result>> { // If the name for the function hasn't yet been initialized check if any // builtin can be injected. @@ -590,7 +590,7 @@ impl Parser { ); let temp_expr = ctx.add_expression( Expression::LocalVariable(temp_var), - SourceMetadata::none(), + Span::default(), body, ); @@ -632,7 +632,7 @@ impl Parser { arguments, result, }, - meta.as_span(), + meta, ); ctx.emit_start(); @@ -650,7 +650,7 @@ impl Parser { pointer: target, value, }, - meta.as_span(), + meta, ); } @@ -668,7 +668,7 @@ impl Parser { name: String, result: Option, mut body: Block, - meta: SourceMetadata, + meta: Span, ) { if self.lookup_function.get(&name).is_none() { let declaration = self.lookup_function.entry(name.clone()).or_default(); @@ -741,14 +741,14 @@ impl Parser { match decl.kind { FunctionKind::Call(handle) => *self.module.functions.get_mut(handle) = function, FunctionKind::Macro(_) => { - let handle = module.functions.append(function, meta.as_span()); + let handle = module.functions.append(function, meta); decl.kind = FunctionKind::Call(handle) } } return; } - let handle = module.functions.append(function, meta.as_span()); + let handle = module.functions.append(function, meta); declaration.overloads.push(Overload { parameters, parameters_info, @@ -763,7 +763,7 @@ impl Parser { ctx: Context, name: String, result: Option, - meta: SourceMetadata, + meta: Span, ) { if self.lookup_function.get(&name).is_none() { let declaration = self.lookup_function.entry(name.clone()).or_default(); @@ -823,7 +823,7 @@ impl Parser { }); } - let handle = module.functions.append(function, meta.as_span()); + let handle = module.functions.append(function, meta); declaration.overloads.push(Overload { parameters, parameters_info, diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index 3400e0626..a96f6a701 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -1,9 +1,9 @@ use super::{ ast::Precision, - token::{Directive, DirectiveKind, SourceMetadata, Token, TokenValue}, + token::{Directive, DirectiveKind, Token, TokenValue}, types::parse_type, }; -use crate::{FastHashMap, StorageAccess}; +use crate::{FastHashMap, Span, StorageAccess}; use pp_rs::{ pp::Preprocessor, token::{PreprocessorError, Punct, TokenValue as PPTokenValue}, @@ -13,7 +13,7 @@ use pp_rs::{ #[cfg_attr(test, derive(PartialEq))] pub struct LexerResult { pub kind: LexerResultKind, - pub meta: SourceMetadata, + pub meta: Span, } #[derive(Debug)] @@ -202,9 +202,10 @@ mod tests { use pp_rs::token::{Integer, Location, Token as PPToken, TokenValue as PPTokenValue}; use super::{ - super::token::{Directive, DirectiveKind, SourceMetadata, Token, TokenValue}, + super::token::{Directive, DirectiveKind, Token, TokenValue}, Lexer, LexerResult, LexerResultKind, }; + use crate::Span; #[test] fn lex_tokens() { @@ -231,7 +232,7 @@ mod tests { location }] }), - meta: SourceMetadata { start: 1, end: 8 } + meta: Span::new(1, 8) } ); assert_eq!( @@ -239,9 +240,9 @@ mod tests { LexerResult { kind: LexerResultKind::Token(Token { value: TokenValue::Void, - meta: SourceMetadata { start: 13, end: 17 } + meta: Span::new(13, 17) }), - meta: SourceMetadata { start: 13, end: 17 } + meta: Span::new(13, 17) } ); assert_eq!( @@ -249,9 +250,9 @@ mod tests { LexerResult { kind: LexerResultKind::Token(Token { value: TokenValue::Identifier("main".into()), - meta: SourceMetadata { start: 18, end: 22 } + meta: Span::new(18, 22) }), - meta: SourceMetadata { start: 18, end: 22 } + meta: Span::new(18, 22) } ); assert_eq!( @@ -259,9 +260,9 @@ mod tests { LexerResult { kind: LexerResultKind::Token(Token { value: TokenValue::LeftParen, - meta: SourceMetadata { start: 23, end: 24 } + meta: Span::new(23, 24) }), - meta: SourceMetadata { start: 23, end: 24 } + meta: Span::new(23, 24) } ); assert_eq!( @@ -269,9 +270,9 @@ mod tests { LexerResult { kind: LexerResultKind::Token(Token { value: TokenValue::RightParen, - meta: SourceMetadata { start: 24, end: 25 } + meta: Span::new(24, 25) }), - meta: SourceMetadata { start: 24, end: 25 } + meta: Span::new(24, 25) } ); assert_eq!( @@ -279,9 +280,9 @@ mod tests { LexerResult { kind: LexerResultKind::Token(Token { value: TokenValue::LeftBrace, - meta: SourceMetadata { start: 26, end: 27 } + meta: Span::new(26, 27) }), - meta: SourceMetadata { start: 26, end: 27 } + meta: Span::new(26, 27) } ); assert_eq!( @@ -289,9 +290,9 @@ mod tests { LexerResult { kind: LexerResultKind::Token(Token { value: TokenValue::RightBrace, - meta: SourceMetadata { start: 27, end: 28 } + meta: Span::new(27, 28) }), - meta: SourceMetadata { start: 27, end: 28 } + meta: Span::new(27, 28) } ); assert_eq!(lex.next(), None); diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 60e839d9c..1d4c6c1a9 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -8,9 +8,9 @@ pub use ast::{Precision, Profile}; pub use error::{Error, ErrorKind, ExpectedToken}; -pub use token::{SourceMetadata, TokenValue}; +pub use token::TokenValue; -use crate::{FastHashMap, FastHashSet, Handle, Module, ShaderStage, Type}; +use crate::{FastHashMap, FastHashSet, Handle, Module, ShaderStage, Span, Type}; use ast::{EntryArg, FunctionDeclaration, GlobalLookup}; use parser::ParsingContext; diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index d6ac4d3f1..088480232 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -11,7 +11,7 @@ use super::{ ast::StructLayout, error::{Error, ErrorKind}, - SourceMetadata, + Span, }; use crate::{front::align_up, Arena, Constant, Handle, Type, TypeInner}; @@ -37,7 +37,7 @@ pub struct TypeAlignSpan { /// change the stride and as such need to have a different type. pub fn calculate_offset( mut ty: Handle, - meta: SourceMetadata, + meta: Span, layout: StructLayout, types: &mut Arena, constants: &Arena, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index d0e14b004..2180b9b6e 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -5,11 +5,11 @@ use super::{ error::{Error, ErrorKind}, lex::{Lexer, LexerResultKind}, token::{Directive, DirectiveKind}, - token::{SourceMetadata, Token, TokenValue}, + token::{Token, TokenValue}, variables::{GlobalOrConstant, VarDeclaration}, Parser, Result, }; -use crate::{arena::Handle, Block, Constant, ConstantInner, Expression, ScalarValue, Type}; +use crate::{arena::Handle, Block, Constant, ConstantInner, Expression, ScalarValue, Span, Type}; use core::convert::TryFrom; use pp_rs::token::{PreprocessorError, Token as PPToken, TokenValue as PPTokenValue}; use std::iter::Peekable; @@ -21,18 +21,18 @@ mod types; pub struct ParsingContext<'source> { lexer: Peekable>, - last_meta: SourceMetadata, + last_meta: Span, } impl<'source> ParsingContext<'source> { pub fn new(lexer: Lexer<'source>) -> Self { ParsingContext { lexer: lexer.peekable(), - last_meta: SourceMetadata::none(), + last_meta: Span::default(), } } - pub fn expect_ident(&mut self, parser: &mut Parser) -> Result<(String, SourceMetadata)> { + pub fn expect_ident(&mut self, parser: &mut Parser) -> Result<(String, Span)> { let token = self.bump(parser)?; match token.value { @@ -153,14 +153,14 @@ impl<'source> ParsingContext<'source> { Some(handle) => parser.add_entry_point(handle, body, ctx.expressions), None => parser.errors.push(Error { kind: ErrorKind::SemanticError("Missing entry point".into()), - meta: SourceMetadata::none(), + meta: Span::default(), }), } Ok(()) } - fn parse_uint_constant(&mut self, parser: &mut Parser) -> Result<(u32, SourceMetadata)> { + fn parse_uint_constant(&mut self, parser: &mut Parser) -> Result<(u32, Span)> { let (value, meta) = self.parse_constant_expression(parser)?; let int = match parser.module.constants[value].inner { @@ -192,7 +192,7 @@ impl<'source> ParsingContext<'source> { fn parse_constant_expression( &mut self, parser: &mut Parser, - ) -> Result<(Handle, SourceMetadata)> { + ) -> Result<(Handle, Span)> { let mut block = Block::new(); let mut ctx = Context::new(parser, &mut block); @@ -206,7 +206,7 @@ impl<'source> ParsingContext<'source> { } impl Parser { - fn handle_directive(&mut self, directive: Directive, meta: SourceMetadata) { + fn handle_directive(&mut self, directive: Directive, meta: Span) { let mut tokens = directive.tokens.into_iter(); match directive.kind { @@ -367,7 +367,7 @@ impl Parser { } pub struct DeclarationContext<'ctx> { - qualifiers: Vec<(TypeQualifier, SourceMetadata)>, + qualifiers: Vec<(TypeQualifier, Span)>, external: bool, ctx: &'ctx mut Context, @@ -381,7 +381,7 @@ impl<'ctx> DeclarationContext<'ctx> { ty: Handle, name: String, init: Option>, - meta: SourceMetadata, + meta: Span, ) -> Result> { let decl = VarDeclaration { qualifiers: &self.qualifiers, diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index ca0ffb74a..47506c060 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -10,7 +10,7 @@ use crate::{ token::{Token, TokenValue}, types::scalar_components, variables::{GlobalOrConstant, VarDeclaration}, - Error, ErrorKind, Parser, SourceMetadata, + Error, ErrorKind, Parser, Span, }, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StorageClass, StructMember, Type, TypeInner, @@ -54,7 +54,7 @@ impl<'source> ParsingContext<'source> { ty: Handle, ctx: &mut Context, body: &mut Block, - ) -> Result<(Handle, SourceMetadata)> { + ) -> Result<(Handle, Span)> { // initializer: // assignment_expression // LEFT_BRACE initializer_list RIGHT_BRACE @@ -76,12 +76,12 @@ impl<'source> ParsingContext<'source> { if let Some(Token { meta: end_meta, .. }) = self.bump_if(parser, TokenValue::RightBrace) { - meta = meta.union(&end_meta); + meta.subsume(end_meta); break; } } TokenValue::RightBrace => { - meta = meta.union(&token.meta); + meta.subsume(token.meta); break; } _ => { @@ -190,7 +190,7 @@ impl<'source> ParsingContext<'source> { .implicit_conversion(parser, &mut expr, init_meta, kind, width)?; } - meta = meta.union(&init_meta); + meta.subsume(init_meta); Ok((expr, init_meta)) }) @@ -206,8 +206,7 @@ impl<'source> ParsingContext<'source> { if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) { ctx.flush_expressions(); - ctx.body - .push(Statement::Store { pointer, value }, meta.as_span()); + ctx.body.push(Statement::Store { pointer, value }, meta); } let token = self.bump(parser)?; @@ -236,7 +235,7 @@ impl<'source> ParsingContext<'source> { ctx: &mut Context, body: &mut Block, external: bool, - ) -> Result> { + ) -> Result> { //declaration: // function_prototype SEMICOLON // @@ -272,7 +271,7 @@ impl<'source> ParsingContext<'source> { self.parse_function_args(parser, &mut context, &mut body)?; let end_meta = self.expect(parser, TokenValue::RightParen)?.meta; - meta = meta.union(&end_meta); + meta.subsume(end_meta); let token = self.bump(parser)?; return match token.value { @@ -379,7 +378,7 @@ impl<'source> ParsingContext<'source> { TokenValue::Semicolon => { let mut meta_all = token.meta; for &(ref qualifier, meta) in qualifiers.iter() { - meta_all = meta_all.union(&meta); + meta_all.subsume(meta); match *qualifier { TypeQualifier::WorkGroupSize(i, value) => { parser.meta.workgroup_size[i] = value @@ -471,10 +470,10 @@ impl<'source> ParsingContext<'source> { parser: &mut Parser, ctx: &mut Context, body: &mut Block, - qualifiers: &[(TypeQualifier, SourceMetadata)], + qualifiers: &[(TypeQualifier, Span)], ty_name: String, - meta: SourceMetadata, - ) -> Result { + meta: Span, + ) -> Result { let mut storage = None; let mut layout = None; @@ -580,7 +579,7 @@ impl<'source> ParsingContext<'source> { let (ty, mut meta) = self.parse_type_non_void(parser)?; let (name, end_meta) = self.expect_ident(parser)?; - meta = meta.union(&end_meta); + meta.subsume(end_meta); let array_specifier = self.parse_array_specifier(parser)?; let ty = parser.maybe_array(ty, meta, array_specifier); diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 2eb77d572..40cf2122f 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -5,7 +5,7 @@ use crate::{ error::{ErrorKind, ExpectedToken}, parser::ParsingContext, token::{Token, TokenValue}, - Error, Parser, Result, SourceMetadata, + Error, Parser, Result, Span, }, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Handle, ScalarValue, Type, TypeInner, UnaryOperator, @@ -39,7 +39,7 @@ impl<'source> ParsingContext<'source> { let expr = self.parse_expression(parser, ctx, stmt, body)?; let meta = self.expect(parser, TokenValue::RightParen)?.meta; - token.meta = token.meta.union(&meta); + token.meta.subsume(meta); return Ok(expr); } @@ -65,7 +65,7 @@ impl<'source> ParsingContext<'source> { specialization: None, inner: ConstantInner::Scalar { width, value }, }, - token.meta.as_span(), + token.meta, ); Ok(stmt.hir_exprs.append( @@ -83,11 +83,11 @@ impl<'source> ParsingContext<'source> { ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, - meta: &mut SourceMetadata, + meta: &mut Span, ) -> Result>> { let mut args = Vec::new(); if let Some(token) = self.bump_if(parser, TokenValue::RightParen) { - *meta = meta.union(&token.meta); + meta.subsume(token.meta); } else { loop { args.push(self.parse_assignment(parser, ctx, stmt, body)?); @@ -96,7 +96,7 @@ impl<'source> ParsingContext<'source> { match token.value { TokenValue::Comma => {} TokenValue::RightParen => { - *meta = meta.union(&token.meta); + meta.subsume(token.meta); break; } _ => { @@ -160,12 +160,12 @@ impl<'source> ParsingContext<'source> { TokenValue::TypeName(_) => { let Token { value, - meta: name_meta, + meta: mut name_meta, } = self.bump(parser)?; let mut meta = name_meta; let mut handle = if let TokenValue::TypeName(ty) = value { - parser.module.types.fetch_or_append(ty, name_meta.as_span()) + parser.module.types.fetch_or_append(ty, name_meta) } else { unreachable!() }; @@ -192,13 +192,14 @@ impl<'source> ParsingContext<'source> { value: ScalarValue::Sint(args.len() as i64), }, }, - meta.as_span(), + meta, ); ArraySize::Constant(constant) } }; + name_meta.subsume(array_meta); handle = parser.module.types.fetch_or_append( Type { name: None, @@ -208,7 +209,7 @@ impl<'source> ParsingContext<'source> { stride, }, }, - name_meta.union(&array_meta).as_span(), + name_meta, ); } @@ -231,17 +232,18 @@ impl<'source> ParsingContext<'source> { | TokenValue::Increment | TokenValue::Decrement = self.expect_peek(parser)?.value { - let Token { value, meta } = self.bump(parser)?; + let Token { value, mut meta } = self.bump(parser)?; match value { TokenValue::LeftBracket => { let index = self.parse_expression(parser, ctx, stmt, body)?; let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; + meta.subsume(end_meta); base = stmt.hir_exprs.append( HirExpr { kind: HirExprKind::Access { base, index }, - meta: meta.union(&end_meta), + meta, }, Default::default(), ) @@ -249,10 +251,11 @@ impl<'source> ParsingContext<'source> { TokenValue::Dot => { let (field, end_meta) = self.expect_ident(parser)?; + meta.subsume(end_meta); base = stmt.hir_exprs.append( HirExpr { kind: HirExprKind::Select { base, field }, - meta: meta.union(&end_meta), + meta, }, Default::default(), ) @@ -289,7 +292,7 @@ impl<'source> ParsingContext<'source> { ) -> Result> { Ok(match self.expect_peek(parser)?.value { TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { - let Token { value, meta } = self.bump(parser)?; + let Token { value, mut meta } = self.bump(parser)?; let expr = self.parse_unary(parser, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[expr].meta; @@ -306,13 +309,9 @@ impl<'source> ParsingContext<'source> { _ => return Ok(expr), }; - stmt.hir_exprs.append( - HirExpr { - kind, - meta: meta.union(&end_meta), - }, - Default::default(), - ) + meta.subsume(end_meta); + stmt.hir_exprs + .append(HirExpr { kind, meta }, Default::default()) } TokenValue::Increment | TokenValue::Decrement => { let Token { value, meta } = self.bump(parser)?; @@ -350,7 +349,7 @@ impl<'source> ParsingContext<'source> { let mut left = passtrough .ok_or(ErrorKind::EndOfFile /* Dummy error */) .or_else(|_| self.parse_unary(parser, ctx, stmt, body))?; - let start_meta = stmt.hir_exprs[left].meta; + let mut meta = stmt.hir_exprs[left].meta; while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(parser)?.value) { if l_bp < min_bp { @@ -362,6 +361,7 @@ impl<'source> ParsingContext<'source> { let right = self.parse_binary(parser, ctx, stmt, body, None, r_bp)?; let end_meta = stmt.hir_exprs[right].meta; + meta.subsume(end_meta); left = stmt.hir_exprs.append( HirExpr { kind: HirExprKind::Binary { @@ -390,7 +390,7 @@ impl<'source> ParsingContext<'source> { }, right, }, - meta: start_meta.union(&end_meta), + meta, }, Default::default(), ) @@ -408,7 +408,7 @@ impl<'source> ParsingContext<'source> { passtrough: Option>, ) -> Result> { let mut condition = self.parse_binary(parser, ctx, stmt, body, passtrough, 0)?; - let start_meta = stmt.hir_exprs[condition].meta; + let mut meta = stmt.hir_exprs[condition].meta; if self.bump_if(parser, TokenValue::Question).is_some() { let accept = self.parse_expression(parser, ctx, stmt, body)?; @@ -416,6 +416,7 @@ impl<'source> ParsingContext<'source> { let reject = self.parse_assignment(parser, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[reject].meta; + meta.subsume(end_meta); condition = stmt.hir_exprs.append( HirExpr { kind: HirExprKind::Conditional { @@ -423,7 +424,7 @@ impl<'source> ParsingContext<'source> { accept, reject, }, - meta: start_meta.union(&end_meta), + meta, }, Default::default(), ) @@ -440,7 +441,7 @@ impl<'source> ParsingContext<'source> { body: &mut Block, ) -> Result> { let tgt = self.parse_unary(parser, ctx, stmt, body)?; - let start_meta = stmt.hir_exprs[tgt].meta; + let mut meta = stmt.hir_exprs[tgt].meta; Ok(match self.expect_peek(parser)?.value { TokenValue::Assign => { @@ -448,10 +449,11 @@ impl<'source> ParsingContext<'source> { let value = self.parse_assignment(parser, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[value].meta; + meta.subsume(end_meta); stmt.hir_exprs.append( HirExpr { kind: HirExprKind::Assign { tgt, value }, - meta: start_meta.union(&end_meta), + meta, }, Default::default(), ) @@ -470,9 +472,10 @@ impl<'source> ParsingContext<'source> { let right = self.parse_assignment(parser, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[right].meta; + meta.subsume(end_meta); let value = stmt.hir_exprs.append( HirExpr { - meta: start_meta.union(&end_meta), + meta, kind: HirExprKind::Binary { left: tgt, op: match token.value { @@ -497,7 +500,7 @@ impl<'source> ParsingContext<'source> { stmt.hir_exprs.append( HirExpr { kind: HirExprKind::Assign { tgt, value }, - meta: start_meta.union(&end_meta), + meta, }, Default::default(), ) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 9abd11b81..4b956a0da 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -1,5 +1,5 @@ use crate::front::glsl::context::ExprPos; -use crate::front::glsl::SourceMetadata; +use crate::front::glsl::Span; use crate::{ front::glsl::{ ast::ParameterQualifier, @@ -41,7 +41,7 @@ impl<'source> ParsingContext<'source> { ctx: &mut Context, body: &mut Block, terminator: &mut Option, - ) -> Result> { + ) -> Result> { // TODO: This prevents snippets like the following from working // ```glsl // vec4(1.0); @@ -59,18 +59,21 @@ impl<'source> ParsingContext<'source> { block }; - let &Token { ref value, meta } = self.expect_peek(parser)?; + let &Token { + ref value, + mut meta, + } = self.expect_peek(parser)?; let meta_rest = match *value { TokenValue::Continue => { let meta = self.bump(parser)?.meta; - body.push(Statement::Continue, meta.as_span()); + body.push(Statement::Continue, meta); terminator.get_or_insert(body.len()); self.expect(parser, TokenValue::Semicolon)?.meta } TokenValue::Break => { let meta = self.bump(parser)?.meta; - body.push(Statement::Break, meta.as_span()); + body.push(Statement::Break, meta); terminator.get_or_insert(body.len()); self.expect(parser, TokenValue::Semicolon)?.meta } @@ -92,14 +95,14 @@ impl<'source> ParsingContext<'source> { ctx.emit_flush(body); ctx.emit_start(); - body.push(Statement::Return { value }, meta.as_span()); + body.push(Statement::Return { value }, meta); terminator.get_or_insert(body.len()); meta } TokenValue::Discard => { let meta = self.bump(parser)?.meta; - body.push(Statement::Kill, meta.as_span()); + body.push(Statement::Kill, meta); terminator.get_or_insert(body.len()); self.expect(parser, TokenValue::Semicolon)?.meta @@ -113,7 +116,7 @@ impl<'source> ParsingContext<'source> { let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; let (handle, more_meta) = ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; - meta = meta.union(&more_meta); + meta.subsume(more_meta); handle }; self.expect(parser, TokenValue::RightParen)?; @@ -125,7 +128,7 @@ impl<'source> ParsingContext<'source> { if let Some(more_meta) = self.parse_statement(parser, ctx, &mut accept, &mut None)? { - meta = meta.union(&more_meta) + meta.subsume(more_meta) } let mut reject = Block::new(); @@ -133,7 +136,7 @@ impl<'source> ParsingContext<'source> { if let Some(more_meta) = self.parse_statement(parser, ctx, &mut reject, &mut None)? { - meta = meta.union(&more_meta); + meta.subsume(more_meta); } } @@ -143,13 +146,13 @@ impl<'source> ParsingContext<'source> { accept, reject, }, - meta.as_span(), + meta, ); meta } TokenValue::Switch => { - let start_meta = self.bump(parser)?.meta; + let mut meta = self.bump(parser)?.meta; let end_meta; self.expect(parser, TokenValue::LeftParen)?; @@ -297,7 +300,7 @@ impl<'source> ParsingContext<'source> { } } - let meta = start_meta.union(&end_meta); + meta.subsume(end_meta); body.push( Statement::Switch { @@ -305,20 +308,20 @@ impl<'source> ParsingContext<'source> { cases, default, }, - meta.as_span(), + meta, ); meta } TokenValue::While => { - let meta = self.bump(parser)?.meta; + let mut meta = self.bump(parser)?.meta; let mut loop_body = Block::new(); let mut stmt = ctx.stmt_ctx(); self.expect(parser, TokenValue::LeftParen)?; let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; - let meta = meta.union(&self.expect(parser, TokenValue::RightParen)?.meta); + meta.subsume(self.expect(parser, TokenValue::RightParen)?.meta); let (expr, expr_meta) = ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?; @@ -343,12 +346,12 @@ impl<'source> ParsingContext<'source> { crate::Span::default(), ); - let mut meta = meta.union(&expr_meta); + meta.subsume(expr_meta); if let Some(body_meta) = self.parse_statement(parser, ctx, &mut loop_body, &mut None)? { - meta = meta.union(&body_meta); + meta.subsume(body_meta); } body.push( @@ -356,13 +359,13 @@ impl<'source> ParsingContext<'source> { body: loop_body, continuing: Block::new(), }, - meta.as_span(), + meta, ); meta } TokenValue::Do => { - let start_meta = self.bump(parser)?.meta; + let mut meta = self.bump(parser)?.meta; let mut loop_body = Block::new(); @@ -375,7 +378,7 @@ impl<'source> ParsingContext<'source> { let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; let end_meta = self.expect(parser, TokenValue::RightParen)?.meta; - let meta = start_meta.union(&end_meta); + meta.subsume(end_meta); let (expr, expr_meta) = ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?; @@ -405,13 +408,13 @@ impl<'source> ParsingContext<'source> { body: loop_body, continuing: Block::new(), }, - meta.as_span(), + meta, ); meta } TokenValue::For => { - let meta = self.bump(parser)?.meta; + let mut meta = self.bump(parser)?.meta; ctx.push_scope(); self.expect(parser, TokenValue::LeftParen)?; @@ -433,14 +436,14 @@ impl<'source> ParsingContext<'source> { let (expr, expr_meta) = if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { let qualifiers = self.parse_type_qualifiers(parser)?; - let (ty, meta) = self.parse_type_non_void(parser)?; + let (ty, mut meta) = self.parse_type_non_void(parser)?; let name = self.expect_ident(parser)?.0; self.expect(parser, TokenValue::Assign)?; let (value, end_meta) = self.parse_initializer(parser, ty, ctx, &mut block)?; - let meta = meta.union(&end_meta); + meta.subsume(end_meta); let decl = VarDeclaration { qualifiers: &qualifiers, @@ -455,7 +458,7 @@ impl<'source> ParsingContext<'source> { ctx.emit_flush(&mut block); ctx.emit_start(); - block.push(Statement::Store { pointer, value }, meta.as_span()); + block.push(Statement::Store { pointer, value }, meta); (value, end_meta) } else { @@ -498,10 +501,10 @@ impl<'source> ParsingContext<'source> { } } - let mut meta = meta.union(&self.expect(parser, TokenValue::RightParen)?.meta); + meta.subsume(self.expect(parser, TokenValue::RightParen)?.meta); if let Some(stmt_meta) = self.parse_statement(parser, ctx, &mut block, &mut None)? { - meta = meta.union(&stmt_meta); + meta.subsume(stmt_meta); } body.push( @@ -509,7 +512,7 @@ impl<'source> ParsingContext<'source> { body: block, continuing, }, - meta.as_span(), + meta, ); ctx.remove_current_scope(); @@ -526,7 +529,7 @@ impl<'source> ParsingContext<'source> { ctx.remove_current_scope(); - body.push(Statement::Block(block), meta.as_span()); + body.push(Statement::Block(block), meta); meta } @@ -542,30 +545,31 @@ impl<'source> ParsingContext<'source> { } }; - Ok(Some(meta.union(&meta_rest))) + meta.subsume(meta_rest); + Ok(Some(meta)) } pub fn parse_compound_statement( &mut self, - mut meta: SourceMetadata, + mut meta: Span, parser: &mut Parser, ctx: &mut Context, body: &mut Block, - ) -> Result { + ) -> Result { let mut terminator = None; loop { if let Some(Token { meta: brace_meta, .. }) = self.bump_if(parser, TokenValue::RightBrace) { - meta = meta.union(&brace_meta); + meta.subsume(brace_meta); break; } let stmt = self.parse_statement(parser, ctx, body, &mut terminator)?; if let Some(stmt_meta) = stmt { - meta = meta.union(&stmt_meta); + meta.subsume(stmt_meta); } } diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index dcde9bacb..c056c1395 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -3,10 +3,10 @@ use crate::{ ast::{StorageQualifier, StructLayout, TypeQualifier}, error::ExpectedToken, parser::ParsingContext, - token::{SourceMetadata, Token, TokenValue}, + token::{Token, TokenValue}, Error, ErrorKind, Parser, Result, }, - ArraySize, Handle, StorageClass, Type, TypeInner, + ArraySize, Handle, Span, StorageClass, Type, TypeInner, }; impl<'source> ParsingContext<'source> { @@ -15,44 +15,38 @@ impl<'source> ParsingContext<'source> { pub fn parse_array_specifier( &mut self, parser: &mut Parser, - ) -> Result> { - if let Some(Token { meta, .. }) = self.bump_if(parser, TokenValue::LeftBracket) { + ) -> Result> { + if let Some(Token { mut meta, .. }) = self.bump_if(parser, TokenValue::LeftBracket) { if let Some(Token { meta: end_meta, .. }) = self.bump_if(parser, TokenValue::RightBracket) { - return Ok(Some((ArraySize::Dynamic, meta.union(&end_meta)))); + meta.subsume(end_meta); + return Ok(Some((ArraySize::Dynamic, meta))); } let (constant, _) = self.parse_constant_expression(parser)?; let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; - Ok(Some((ArraySize::Constant(constant), meta.union(&end_meta)))) + meta.subsume(end_meta); + Ok(Some((ArraySize::Constant(constant), meta))) } else { Ok(None) } } - pub fn parse_type( - &mut self, - parser: &mut Parser, - ) -> Result<(Option>, SourceMetadata)> { + pub fn parse_type(&mut self, parser: &mut Parser) -> Result<(Option>, Span)> { let token = self.bump(parser)?; let handle = match token.value { TokenValue::Void => None, - TokenValue::TypeName(ty) => Some( - parser - .module - .types - .fetch_or_append(ty, token.meta.as_span()), - ), + TokenValue::TypeName(ty) => Some(parser.module.types.fetch_or_append(ty, token.meta)), TokenValue::Struct => { - let meta = token.meta; + let mut meta = token.meta; let ty_name = self.expect_ident(parser)?.0; self.expect(parser, TokenValue::LeftBrace)?; let mut members = Vec::new(); let span = self.parse_struct_declaration_list(parser, &mut members, StructLayout::Std140)?; let end_meta = self.expect(parser, TokenValue::RightBrace)?.meta; - + meta.subsume(end_meta); let ty = parser.module.types.append( Type { name: Some(ty_name.clone()), @@ -62,7 +56,7 @@ impl<'source> ParsingContext<'source> { span, }, }, - meta.union(&end_meta).as_span(), + meta, ); parser.lookup_type.insert(ty_name, ty); Some(ty) @@ -94,14 +88,12 @@ impl<'source> ParsingContext<'source> { let token_meta = token.meta; let array_specifier = self.parse_array_specifier(parser)?; let handle = handle.map(|ty| parser.maybe_array(ty, token_meta, array_specifier)); - let meta = array_specifier.map_or(token_meta, |(_, meta)| meta.union(&token_meta)); + let mut meta = array_specifier.map_or(token_meta, |(_, meta)| meta); + meta.subsume(token_meta); Ok((handle, meta)) } - pub fn parse_type_non_void( - &mut self, - parser: &mut Parser, - ) -> Result<(Handle, SourceMetadata)> { + pub fn parse_type_non_void(&mut self, parser: &mut Parser) -> Result<(Handle, Span)> { let (maybe_ty, meta) = self.parse_type(parser)?; let ty = maybe_ty.ok_or_else(|| Error { kind: ErrorKind::SemanticError("Type can't be void".into()), @@ -132,7 +124,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_type_qualifiers( &mut self, parser: &mut Parser, - ) -> Result> { + ) -> Result> { let mut qualifiers = Vec::new(); while self.peek_type_qualifier(parser) { @@ -177,7 +169,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id_list( &mut self, parser: &mut Parser, - qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, + qualifiers: &mut Vec<(TypeQualifier, Span)>, ) -> Result<()> { self.expect(parser, TokenValue::LeftParen)?; loop { @@ -197,7 +189,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id( &mut self, parser: &mut Parser, - qualifiers: &mut Vec<(TypeQualifier, SourceMetadata)>, + qualifiers: &mut Vec<(TypeQualifier, Span)>, ) -> Result<()> { // layout_qualifier_id: // IDENTIFIER @@ -208,7 +200,7 @@ impl<'source> ParsingContext<'source> { TokenValue::Identifier(name) => { if self.bump_if(parser, TokenValue::Assign).is_some() { let (value, end_meta) = self.parse_uint_constant(parser)?; - token.meta = token.meta.union(&end_meta); + token.meta.subsume(end_meta); qualifiers.push(( match name.as_str() { diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 58d4a7e71..9ec7ad215 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -3,7 +3,7 @@ use super::{ error::ExpectedToken, error::{Error, ErrorKind}, token::TokenValue, - Options, Parser, SourceMetadata, + Options, Parser, Span, }; use crate::ShaderStage; use pp_rs::token::PreprocessorError; @@ -23,7 +23,7 @@ fn version() { .unwrap(), vec![Error { kind: ErrorKind::InvalidVersion(99000), - meta: SourceMetadata { start: 9, end: 14 } + meta: Span::new(9, 14) }], ); @@ -37,7 +37,7 @@ fn version() { .unwrap(), vec![Error { kind: ErrorKind::InvalidVersion(449), - meta: SourceMetadata { start: 9, end: 12 } + meta: Span::new(9, 12) }] ); @@ -51,7 +51,7 @@ fn version() { .unwrap(), vec![Error { kind: ErrorKind::InvalidProfile("smart".into()), - meta: SourceMetadata { start: 13, end: 18 }, + meta: Span::new(13, 18), }] ); @@ -66,14 +66,14 @@ fn version() { vec![ Error { kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedHash,), - meta: SourceMetadata { start: 27, end: 28 }, + meta: Span::new(27, 28), }, Error { kind: ErrorKind::InvalidToken( TokenValue::Identifier("version".into()), vec![ExpectedToken::Eof] ), - meta: SourceMetadata { start: 28, end: 35 } + meta: Span::new(28, 35) } ] ); @@ -449,10 +449,7 @@ fn functions() { .unwrap(), vec![Error { kind: ErrorKind::SemanticError("Function already defined".into()), - meta: SourceMetadata { - start: 134, - end: 152 - }, + meta: Span::new(134, 152), }] ); @@ -608,10 +605,7 @@ fn implicit_conversions() { .unwrap(), vec![Error { kind: ErrorKind::SemanticError("Unknown function \'test\'".into()), - meta: SourceMetadata { - start: 156, - end: 165 - }, + meta: Span::new(156, 165), }] ); @@ -633,10 +627,7 @@ fn implicit_conversions() { .unwrap(), vec![Error { kind: ErrorKind::SemanticError("Ambiguous best function for \'test\'".into()), - meta: SourceMetadata { - start: 158, - end: 165 - }, + meta: Span::new(158, 165), }] ); } diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index a2449e588..148f105a1 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -1,85 +1,11 @@ -use pp_rs::token::Location; -pub use pp_rs::token::{Float, Integer, PreprocessorError, Token as PPToken}; +pub use pp_rs::token::{Float, Integer, Location, PreprocessorError, Token as PPToken}; use super::ast::Precision; -use crate::{Interpolation, Sampling, Type}; -use std::ops::Range; +use crate::{Interpolation, Sampling, Span, Type}; -/// Represents a range of the source code -/// -/// The `SourceMetadata` is used in error reporting to indicate a range of the -/// original source code where the error happened. -/// -/// For easy interaction with error crates like -/// [`codespan`][codespan] the [`From`](From) trait is -/// implemeted for [`Range`](Range) allowing for conversions from `SourceMetadata`. -/// -/// ```rust -/// # use naga::front::glsl::SourceMetadata; -/// # use std::ops::Range; -/// # let meta = SourceMetadata::default(); -/// let range: Range = meta.into(); -/// ``` -/// -/// Or in the case of [`codespan`][codespan] -/// -/// ```rust -/// # use naga::front::glsl::SourceMetadata; -/// # #[cfg(feature = "codespan_reporting")] -/// # { -/// use codespan_reporting::diagnostic::Label; -/// # let file = (); -/// # let meta = SourceMetadata::default(); -/// let label = Label::primary(file, meta); -/// # } -/// ``` -/// -/// # Notes -/// -/// [`start`](SourceMetadata::start) can be equal to -/// [`end`](SourceMetadata::end) especially when reporting errors which aren't -/// associated with a specific portion of the code. -/// -/// [codespan]: https://docs.rs/codespan-reporting -#[derive(Debug, Clone, Copy, Default)] -#[cfg_attr(test, derive(PartialEq))] -pub struct SourceMetadata { - /// Byte offset into the source where the first char starts - pub start: usize, - /// Byte offset into the source where the first char not belonging to this - /// source metadata starts - pub end: usize, -} - -impl SourceMetadata { - pub(crate) fn union(&self, other: &Self) -> Self { - SourceMetadata { - start: self.start.min(other.start), - end: self.end.max(other.end), - } - } - - pub fn as_span(&self) -> crate::Span { - crate::Span::new(self.start as u32, self.end as u32) - } - - pub(crate) fn none() -> Self { - SourceMetadata::default() - } -} - -impl From for SourceMetadata { +impl From for Span { fn from(loc: Location) -> Self { - SourceMetadata { - start: loc.start as usize, - end: loc.end as usize, - } - } -} - -impl From for Range { - fn from(meta: SourceMetadata) -> Self { - meta.start..meta.end + Span::new(loc.start, loc.end) } } @@ -87,7 +13,7 @@ impl From for Range { #[cfg_attr(test, derive(PartialEq))] pub struct Token { pub value: TokenValue, - pub meta: SourceMetadata, + pub meta: Span, } /// A token passed from the lexing used in the parsing diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index de26a8b32..803901764 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,6 +1,4 @@ -use super::{ - constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, SourceMetadata, -}; +use super::{constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, Span}; use crate::{ proc::ResolveContext, ArraySize, Bytes, Constant, Expression, Handle, ImageClass, ImageDimension, ScalarKind, Type, TypeInner, VectorSize, @@ -184,7 +182,7 @@ impl Parser { &self, ctx: &mut Context, handle: Handle, - meta: SourceMetadata, + meta: Span, ) -> Result<()> { let resolve_ctx = ResolveContext { constants: &self.module.constants, @@ -207,7 +205,7 @@ impl Parser { &'b self, ctx: &'b mut Context, handle: Handle, - meta: SourceMetadata, + meta: Span, ) -> Result<&'b TypeInner> { self.typifier_grow(ctx, handle, meta)?; Ok(ctx.typifier.get(handle, &self.module.types)) @@ -218,7 +216,7 @@ impl Parser { &'b self, ctx: &'b mut Context, handle: Handle, - meta: SourceMetadata, + meta: Span, ) -> Result<()> { let resolve_ctx = ResolveContext { constants: &self.module.constants, @@ -241,7 +239,7 @@ impl Parser { &mut self, ctx: &Context, root: Handle, - meta: SourceMetadata, + meta: Span, ) -> Result> { let mut solver = ConstantSolver { types: &self.module.types, @@ -258,11 +256,12 @@ impl Parser { pub(crate) fn maybe_array( &mut self, base: Handle, - meta: SourceMetadata, - array_specifier: Option<(ArraySize, SourceMetadata)>, + mut meta: Span, + array_specifier: Option<(ArraySize, Span)>, ) -> Handle { array_specifier .map(|(size, size_meta)| { + meta.subsume(size_meta); self.module.types.fetch_or_append( Type { name: None, @@ -272,7 +271,7 @@ impl Parser { stride: self.module.types[base].inner.span(&self.module.constants), }, }, - meta.union(&size_meta).as_span(), + meta, ) }) .unwrap_or(base) diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 200e6aca0..6d82a40a9 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -2,7 +2,7 @@ use super::{ ast::*, context::Context, error::{Error, ErrorKind}, - Parser, Result, SourceMetadata, + Parser, Result, Span, }; use crate::{ Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, Interpolation, @@ -24,11 +24,11 @@ macro_rules! qualifier_arm { } pub struct VarDeclaration<'a> { - pub qualifiers: &'a [(TypeQualifier, SourceMetadata)], + pub qualifiers: &'a [(TypeQualifier, Span)], pub ty: Handle, pub name: Option, pub init: Option>, - pub meta: SourceMetadata, + pub meta: Span, } /// Information about a builtin used in [`add_builtin`](Parser::add_builtin) @@ -56,14 +56,14 @@ impl Parser { body: &mut Block, name: &str, data: BuiltInData, - meta: SourceMetadata, + meta: Span, ) -> Option { let ty = self.module.types.fetch_or_append( Type { name: None, inner: data.inner, }, - meta.as_span(), + meta, ); let handle = self.module.global_variables.append( @@ -74,7 +74,7 @@ impl Parser { ty, init: None, }, - meta.as_span(), + meta, ); let idx = self.entry_args.len(); @@ -114,7 +114,7 @@ impl Parser { ctx: &mut Context, body: &mut Block, name: &str, - meta: SourceMetadata, + meta: Span, ) -> Option { if let Some(local_var) = ctx.lookup_local_var(name) { return Some(local_var); @@ -196,7 +196,7 @@ impl Parser { width: 4, }, }, - meta.as_span(), + meta, ); BuiltInData { @@ -248,7 +248,7 @@ impl Parser { body: &mut Block, expression: Handle, name: &str, - meta: SourceMetadata, + meta: Span, ) -> Result> { let (ty, is_pointer) = match *self.resolve_type(ctx, expression, meta)? { TypeInner::Pointer { base, .. } => (&self.module.types[base].inner, true), @@ -562,7 +562,7 @@ impl Parser { ty, init, }, - meta.as_span(), + meta, ); let idx = self.entry_args.len(); @@ -633,7 +633,7 @@ impl Parser { ty, init, }, - meta.as_span(), + meta, ); if let Some(name) = name { @@ -711,7 +711,7 @@ impl Parser { ty, init, }, - meta.as_span(), + meta, ); let expr = ctx.add_expression(Expression::LocalVariable(handle), meta, body); From 115d170584392fc998b236d6616cea4dcb6925b3 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 21 Sep 2021 13:46:59 -0400 Subject: [PATCH 1367/2212] wgsl-out: update reserved words --- src/back/wgsl/keywords.rs | 222 +++++++++--------- .../out/wgsl/931-constant-emitting-vert.wgsl | 2 +- tests/out/wgsl/constant-array-size-vert.wgsl | 2 +- tests/out/wgsl/prepostfix-frag.wgsl | 20 +- 4 files changed, 127 insertions(+), 119 deletions(-) diff --git a/src/back/wgsl/keywords.rs b/src/back/wgsl/keywords.rs index a0ec86810..f40ecd0ce 100644 --- a/src/back/wgsl/keywords.rs +++ b/src/back/wgsl/keywords.rs @@ -1,126 +1,134 @@ // https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary pub const RESERVED: &[&str] = &[ - // Type-defining keywords - "ARRAY", - "BOOL", - "FLOAT32", - "INT32", - "MAT2x2", - "MAT2x3", - "MAT2x4", - "MAT3x2", - "MAT3x3", - "MAT3x4", - "MAT4x2", - "MAT4x3", - "MAT4x4", - "POINTER", - "SAMPLER", - "SAMPLER_COMPARISON", - "STRUCT", - "TEXTURE_1D", - "TEXTURE_2D", - "TEXTURE_2D_ARRAY", - "TEXTURE_3D", - "TEXTURE_CUBE", - "TEXTURE_CUBE_ARRAY", - "TEXTURE_MULTISAMPLED_2D", - "TEXTURE_STORAGE_1D", - "TEXTURE_STORAGE_2D", - "TEXTURE_STORAGE_2D_ARRAY", - "TEXTURE_STORAGE_3D", - "TEXTURE_DEPTH_2D", - "TEXTURE_DEPTH_2D_ARRAY", - "TEXTURE_DEPTH_CUBE", - "TEXTURE_DEPTH_CUBE_ARRAY", - "UINT32", - "VEC2", - "VEC3", - "VEC4", - // Other keywords - "BITCAST", - "BLOCK", - "BREAK", - "CASE", - "CONTINUE", - "CONTINUING", - "DEFAULT", - "DISCARD", - "ELSE", - "ELSE_IF", - "ENABLE", - "FALLTHROUGH", - "FALSE", - "FN", - "FOR", - "FUNCTION", - "IF", - "LET", - "LOOP", - "PRIVATE", - "RETURN", - "STORAGE", - "SWITCH", - "TRUE", - "TYPE", - "UNIFORM", - "VAR", - "WORKGROUP", - // Image format keywords - "R8UNORM", - "R8SNORM", - "R8UINT", - "R8SINT", - "R16UINT", - "R16SINT", - "R16FLOAT", - "RG8UNORM", - "RG8SNORM", - "RG8UINT", - "RG8SINT", - "R32UINT", - "R32SINT", - "R32FLOAT", - "RG16UINT", - "RG16SINT", - "RG16FLOAT", - "RGBA8UNORM", - "RGBA8UNORM-SRGB", - "RGBA8SNORM", - "RGBA8UINT", - "RGBA8SINT", - "BGRA8UNORM", - "BGRA8UNORM-SRGB", - "RGB10A2UNORM", - "RG11B10FLOAT", - "RG32UINT", - "RG32SINT", - "RG32FLOAT", - "RGBA16UINT", - "RGBA16SINT", - "RGBA16FLOAT", - "RGBA32UINT", - "RGBA32SINT", - "RGBA32FLOAT", - // Reserved Keywords + // type-defining keywords + "array", + "atomic", + "bool", + "float32", + "int32", + "mat2x2", + "mat2x3", + "mat2x4", + "mat3x2", + "mat3x3", + "mat3x4", + "mat4x2", + "mat4x3", + "mat4x4", + "pointer", + "sampler", + "sampler_comparison", + "struct", + "texture_1d", + "texture_2d", + "texture_2d_array", + "texture_3d", + "texture_cube", + "texture_cube_array", + "texture_multisampled_2d", + "texture_storage_1d", + "texture_storage_2d", + "texture_storage_2d_array", + "texture_storage_3d", + "texture_depth_2d", + "texture_depth_2d_array", + "texture_depth_cube", + "texture_depth_cube_array", + "texture_depth_multisampled_2d", + "uint32", + "vec2", + "vec3", + "vec4", + // other keywords + "bitcast", + "block", + "break", + "case", + "continue", + "continuing", + "default", + "discard", + "else", + "else_if", + "enable", + "fallthrough", + "false", + "fn", + "for", + "function", + "if", + "let", + "loop", + "private", + "read", + "read_write", + "return", + "storage", + "switch", + "true", + "type", + "uniform", + "var", + "workgroup", + "write", + // image format keywords + "r8unorm", + "r8snorm", + "r8uint", + "r8sint", + "r16uint", + "r16sint", + "r16float", + "rg8unorm", + "rg8snorm", + "rg8uint", + "rg8sint", + "r32uint", + "r32sint", + "r32float", + "rg16uint", + "rg16sint", + "rg16float", + "rgba8unorm", + "rgba8unorm_srgb", + "rgba8snorm", + "rgba8uint", + "rgba8sint", + "bgra8unorm", + "bgra8unorm_srgb", + "rgb10a2unorm", + "rg11b10float", + "rg32uint", + "rg32sint", + "rg32float", + "rgba16uint", + "rgba16sint", + "rgba16float", + "rgba32uint", + "rgba32sint", + "rgba32float", + // reserved keywords "asm", "bf16", + "const", "do", "enum", "f16", "f64", + "handle", "i8", "i16", "i64", - "const", + "mat", + "premerge", + "regardless", "typedef", "u8", "u16", "u64", "unless", "using", + "vec", + "void", "while", - "regardless", - "premerge", - "handle", ]; diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl index db5670f1a..56a4015bd 100644 --- a/tests/out/wgsl/931-constant-emitting-vert.wgsl +++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl @@ -1,4 +1,4 @@ -fn function() -> f32 { +fn function1() -> f32 { return 0.0; } diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index ad51ae6b7..27ff1eb37 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -6,7 +6,7 @@ struct Data { [[group(1), binding(0)]] var global: Data; -fn function() -> vec4 { +fn function1() -> vec4 { var sum: vec4 = vec4(0.0, 0.0, 0.0, 0.0); var i: i32 = 0; diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index 5b2e53a81..0aef32967 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -2,9 +2,9 @@ fn main1() { var scalar_target: i32; var scalar: i32 = 1; var vec_target: vec2; - var vec: vec2 = vec2(1u, 1u); + var vec1: vec2 = vec2(1u, 1u); var mat_target: mat4x3; - var mat: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); + var mat1: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); let e3: i32 = scalar; scalar = (e3 + 1); @@ -13,22 +13,22 @@ fn main1() { let e8: i32 = (e6 - 1); scalar = e8; scalar_target = e8; - let e14: vec2 = vec; - vec = (e14 - vec2(1u)); + let e14: vec2 = vec1; + vec1 = (e14 - vec2(1u)); vec_target = e14; - let e18: vec2 = vec; + let e18: vec2 = vec1; let e21: vec2 = (e18 + vec2(1u)); - vec = e21; + vec1 = e21; vec_target = e21; let e24: f32 = f32(1); - let e32: mat4x3 = mat; + let e32: mat4x3 = mat1; let e34: vec3 = vec3(1.0); - mat = (e32 + mat4x3(e34, e34, e34, e34)); + mat1 = (e32 + mat4x3(e34, e34, e34, e34)); mat_target = e32; - let e37: mat4x3 = mat; + let e37: mat4x3 = mat1; let e39: vec3 = vec3(1.0); let e41: mat4x3 = (e37 - mat4x3(e39, e39, e39, e39)); - mat = e41; + mat1 = e41; mat_target = e41; return; } From 63a8463edd3d205ea8f8bb43a0ae1f91cee3addc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 20 Sep 2021 23:04:45 +0100 Subject: [PATCH 1368/2212] [glsl-in] Support function declarations with void as arguments --- src/front/glsl/parser/functions.rs | 4 ++++ src/front/glsl/parser_tests.rs | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 4b956a0da..cfcb2f989 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -586,6 +586,10 @@ impl<'source> ParsingContext<'source> { context: &mut Context, body: &mut Block, ) -> Result<()> { + if self.bump_if(parser, TokenValue::Void).is_some() { + return Ok(()); + } + loop { if self.peek_type_name(parser) || self.peek_parameter_qualifier(parser) { let qualifier = self.parse_parameter_qualifier(parser); diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 9ec7ad215..5f865e975 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -104,7 +104,7 @@ fn version() { parser .parse( &Options::from(ShaderStage::Vertex), - "#version 450 core\nvoid main() {}", + "#version 450 core\nvoid main(void) {}", ) .unwrap(); assert_eq!( From 6a575590704d02210698ee3f4e4e0907fd5b6e72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 21 Sep 2021 16:57:37 +0100 Subject: [PATCH 1369/2212] [glsl-out] Improve handling of samplerCubeArrayShadow Adds checks that it isn't used in an unsupported function and emits the depth_ref as a separate argument. --- src/back/glsl/mod.rs | 36 ++++++++++++++++--- tests/in/cubeArrayShadow.wgsl | 12 +++++++ .../cubeArrayShadow.fragment.Fragment.glsl | 17 +++++++++ tests/snapshots.rs | 1 + 4 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 tests/in/cubeArrayShadow.wgsl create mode 100644 tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index bc46c3d0e..9bba3c241 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1860,6 +1860,24 @@ impl<'a, W: Write> Writer<'a, W> { _ => unreachable!(), }; + if dim == crate::ImageDimension::Cube + && array_index.is_some() + && depth_ref.is_some() + { + match level { + crate::SampleLevel::Zero + | crate::SampleLevel::Exact(_) + | crate::SampleLevel::Gradient { .. } + | crate::SampleLevel::Bias(_) => { + return Err(Error::Custom(String::from( + "gsamplerCubeArrayShadow isn't supported in textureGrad, \ + textureLod or texture with bias", + ))) + } + crate::SampleLevel::Auto => {} + } + } + // textureLod on sampler2DArrayShadow and samplerCubeShadow does not exist in GLSL. // To emulate this, we will have to use textureGrad with a constant gradient of 0. let workaround_lod_array_shadow_as_grad = (array_index.is_some() @@ -1905,7 +1923,8 @@ impl<'a, W: Write> Writer<'a, W> { if array_index.is_some() { coord_dim += 1; } - if depth_ref.is_some() { + let cube_array_shadow = coord_dim == 4; + if depth_ref.is_some() && !cube_array_shadow { coord_dim += 1; } @@ -1916,12 +1935,21 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ", ")?; self.write_expr(expr, ctx)?; } - if let Some(expr) = depth_ref { - write!(self.out, ", ")?; - self.write_expr(expr, ctx)?; + if !cube_array_shadow { + if let Some(expr) = depth_ref { + write!(self.out, ", ")?; + self.write_expr(expr, ctx)?; + } } write!(self.out, ")")?; + if cube_array_shadow { + if let Some(expr) = depth_ref { + write!(self.out, ", ")?; + self.write_expr(expr, ctx)?; + } + } + match level { // Auto needs no more arguments crate::SampleLevel::Auto => (), diff --git a/tests/in/cubeArrayShadow.wgsl b/tests/in/cubeArrayShadow.wgsl new file mode 100644 index 000000000..a2a376564 --- /dev/null +++ b/tests/in/cubeArrayShadow.wgsl @@ -0,0 +1,12 @@ +[[group(0), binding(4)]] +var point_shadow_textures: texture_depth_cube_array; +[[group(0), binding(5)]] +var point_shadow_textures_sampler: sampler_comparison; + +[[stage(fragment)]] +fn fragment() -> [[location(0)]] vec4 { + let frag_ls = vec4(1., 1., 2., 1.).xyz; + let a = textureSampleCompare(point_shadow_textures, point_shadow_textures_sampler, frag_ls, i32(1), 1.); + + return vec4(a, 1., 1., 1.); +} diff --git a/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl b/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl new file mode 100644 index 000000000..57f819281 --- /dev/null +++ b/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl @@ -0,0 +1,17 @@ +#version 310 es +#extension GL_EXT_texture_cube_map_array : require + +precision highp float; +precision highp int; + +uniform highp samplerCubeArrayShadow _group_0_binding_4; + +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + vec3 frag_ls = vec4(1.0, 1.0, 2.0, 1.0).xyz; + float a = texture(_group_0_binding_4, vec4(frag_ls, int(1)), 1.0); + _fs2p_location0 = vec4(a, 1.0, 1.0, 1.0); + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 7a8873f37..a712d7b33 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -505,6 +505,7 @@ fn convert_wgsl() { "texture-arg", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ("cubeArrayShadow", Targets::GLSL), ]; for &(name, targets) in inputs.iter() { From d5fc05e8a4ea39aa91a4c9cc2da149eef5a03ba0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 19 Sep 2021 22:31:38 +0100 Subject: [PATCH 1370/2212] Allow unsigned integers in switch --- src/back/glsl/mod.rs | 9 +- src/back/hlsl/writer.rs | 13 +- src/back/msl/writer.rs | 9 +- src/back/wgsl/writer.rs | 11 +- src/front/glsl/parser/functions.rs | 11 +- src/front/wgsl/mod.rs | 33 +++- src/front/wgsl/number_literals.rs | 30 --- src/lib.rs | 2 +- src/valid/function.rs | 6 +- tests/in/control-flow.wgsl | 6 + tests/out/glsl/control-flow.main.Compute.glsl | 8 +- tests/out/hlsl/control-flow.hlsl | 9 +- tests/out/msl/control-flow.msl | 11 +- tests/out/spv/control-flow.spvasm | 180 +++++++++--------- tests/out/wgsl/control-flow.wgsl | 8 +- 15 files changed, 204 insertions(+), 142 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9bba3c241..4cb694ccd 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1427,11 +1427,18 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "switch(")?; self.write_expr(selector, ctx)?; writeln!(self.out, ") {{")?; + let type_postfix = match *ctx.info[selector].ty.inner_with(&self.module.types) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } => "u", + _ => "", + }; // Write all cases let l2 = level.next(); for case in cases { - writeln!(self.out, "{}case {}:", l2, case.value)?; + writeln!(self.out, "{}case {}{}:", l2, case.value, type_postfix)?; for sta in case.body.iter() { self.write_stmt(sta, ctx, l2.next())?; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index b0b0d1a98..d48daf1aa 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1370,13 +1370,24 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "switch(")?; self.write_expr(module, selector, func_ctx)?; writeln!(self.out, ") {{")?; + let type_postfix = match *func_ctx.info[selector].ty.inner_with(&module.types) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } => "u", + _ => "", + }; // Write all cases let indent_level_1 = level.next(); let indent_level_2 = indent_level_1.next(); for case in cases { - writeln!(self.out, "{}case {}: {{", indent_level_1, case.value)?; + writeln!( + self.out, + "{}case {}{}: {{", + indent_level_1, case.value, type_postfix + )?; if case.fall_through { // Generate each fallthrough case statement in a new block. This is done to diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0bedf3287..0bf159e54 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1439,10 +1439,17 @@ impl Writer { } => { write!(self.out, "{}switch(", level)?; self.put_expression(selector, &context.expression, true)?; + let type_postfix = match *context.expression.resolve_type(selector) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } => "u", + _ => "", + }; writeln!(self.out, ") {{")?; let lcase = level.next(); for case in cases.iter() { - writeln!(self.out, "{}case {}: {{", lcase, case.value)?; + writeln!(self.out, "{}case {}{}: {{", lcase, case.value, type_postfix)?; self.put_block(lcase.next(), &case.body, context)?; if !case.fall_through { writeln!(self.out, "{}break;", lcase.next())?; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 5c0b61cb4..f8956a691 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -887,6 +887,13 @@ impl Writer { let all_fall_through = cases .iter() .all(|case| case.fall_through && case.body.is_empty()); + let type_postfix = match *func_ctx.info[selector].ty.inner_with(&module.types) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } => "u", + _ => "", + }; let l2 = level.next(); if !cases.is_empty() { @@ -896,11 +903,11 @@ impl Writer { } if !all_fall_through && case.fall_through && case.body.is_empty() { write_case = false; - write!(self.out, "{}, ", case.value)?; + write!(self.out, "{}{}, ", case.value, type_postfix)?; continue; } else { write_case = true; - writeln!(self.out, "{}: {{", case.value)?; + writeln!(self.out, "{}{}: {{", case.value, type_postfix)?; } for sta in case.body.iter() { diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index cfcb2f989..68001558b 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -157,19 +157,12 @@ impl<'source> ParsingContext<'source> { self.expect(parser, TokenValue::LeftParen)?; - let (mut selector, selector_meta) = { + let selector = { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)? + ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?.0 }; - if let Some(crate::ScalarKind::Uint) = parser - .resolve_type(ctx, selector, selector_meta)? - .scalar_kind() - { - ctx.conversion(&mut selector, selector_meta, crate::ScalarKind::Sint, 4)? - } - self.expect(parser, TokenValue::RightParen)?; ctx.emit_flush(body); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 28f1e83b7..bc013f147 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -21,7 +21,7 @@ use self::{ lexer::Lexer, number_literals::{ get_f32_literal, get_i32_literal, get_u32_literal, parse_generic_non_negative_int_literal, - parse_non_negative_sint_literal, parse_sint_literal, + parse_non_negative_sint_literal, }, }; use codespan_reporting::{ @@ -83,6 +83,7 @@ pub enum ExpectedToken<'a> { ty: Option, width: Option, }, + Integer, Constant, /// Expected: constant, parenthesized expression, identifier PrimaryExpression, @@ -218,6 +219,7 @@ impl<'a> Error<'a> { ) } }, + ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), ExpectedToken::Constant => "constant".to_string(), ExpectedToken::PrimaryExpression => "expression".to_string(), ExpectedToken::AttributeSeparator => "attribute separator (',') or an end of the attribute list (']]')".to_string(), @@ -1242,6 +1244,28 @@ impl Parser { }) } + fn parse_switch_value<'a>(lexer: &mut Lexer<'a>, uint: bool) -> Result> { + let token_span = lexer.next(); + let word = match token_span.0 { + Token::Number { value, width, .. } => { + if let Some(width) = width { + if width != 4 { + // Only 32-bit literals supported by the spec and naga for now! + return Err(Error::BadScalarWidth(token_span.1, width)); + } + } + + value + } + _ => return Err(Error::Unexpected(token_span, ExpectedToken::Integer)), + }; + + match uint { + true => get_u32_literal(word, token_span.1).map(|v| v as i32), + false => get_i32_literal(word, token_span.1), + } + } + fn parse_atomic_pointer<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -3425,6 +3449,11 @@ impl Parser { lexer, context.as_expression(block, &mut emitter), )?; + let uint = Some(crate::ScalarKind::Uint) + == context + .as_expression(block, &mut emitter) + .resolve_type(selector)? + .scalar_kind(); lexer.expect(Token::Paren(')'))?; block.extend(emitter.finish(context.expressions)); lexer.expect(Token::Paren('{'))?; @@ -3438,7 +3467,7 @@ impl Parser { // parse a list of values let value = loop { // TODO: Switch statements also allow for floats, bools and unsigned integers. See https://www.w3.org/TR/WGSL/#switch-statement - let value = parse_sint_literal(lexer, 4)?; + let value = Self::parse_switch_value(lexer, uint)?; if lexer.skip(Token::Separator(',')) { if lexer.skip(Token::Separator(':')) { break value; diff --git a/src/front/wgsl/number_literals.rs b/src/front/wgsl/number_literals.rs index 2f6122414..9279989e9 100644 --- a/src/front/wgsl/number_literals.rs +++ b/src/front/wgsl/number_literals.rs @@ -69,36 +69,6 @@ pub fn get_f32_literal(word: &str, span: Span) -> Result> { parsed_val.map_err(|e| Error::BadFloat(span, e)) } -pub(super) fn parse_sint_literal<'a>( - lexer: &mut Lexer<'a>, - width: Bytes, -) -> Result> { - let token_span = lexer.next(); - - if width != 4 { - // Only 32-bit literals supported by the spec and naga for now! - return Err(Error::BadScalarWidth(token_span.1, width)); - } - - match token_span { - ( - Token::Number { - value, - ty: NumberType::Sint, - width: token_width, - }, - span, - ) if token_width.unwrap_or(4) == width => get_i32_literal(value, span), - other => Err(Error::Unexpected( - other, - ExpectedToken::Number { - ty: Some(NumberType::Sint), - width: Some(width), - }, - )), - } -} - pub(super) fn _parse_uint_literal<'a>( lexer: &mut Lexer<'a>, width: Bytes, diff --git a/src/lib.rs b/src/lib.rs index 3c8325485..697264c51 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1260,7 +1260,7 @@ pub use block::Block; pub struct SwitchCase { /// Value, upon which the case is considered true. pub value: i32, - /// Body of the cae. + /// Body of the case. pub body: Block, /// If true, the control flow continues to the next case in the list, /// or default. diff --git a/src/valid/function.rs b/src/valid/function.rs index ff39fcd57..ddfcb60bb 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -90,7 +90,7 @@ pub enum FunctionError { InvalidIfType(Handle), #[error("The `switch` value {0:?} is not an integer scalar")] InvalidSwitchType(Handle), - #[error("Multiple `switch` cases for {0} are present")] + #[error("Multiple `switch` cases for {0:?} are present")] ConflictingSwitchCase(i32), #[error("The pointer {0:?} doesn't relate to a valid destination for a store")] InvalidStorePointer(Handle), @@ -375,6 +375,10 @@ impl super::Validator { ref default, } => { match *context.resolve_type(selector, &self.valid_expression_set)? { + Ti::Scalar { + kind: crate::ScalarKind::Uint, + width: _, + } => {} Ti::Scalar { kind: crate::ScalarKind::Sint, width: _, diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index 679ad3d8a..5ca59817c 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -32,6 +32,12 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { } } + // switch with unsigned integer selectors + switch(0u) { + case 0u: { + } + } + // non-empty switch in last-statement-in-function position switch (pos) { case 1: { diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index e8b566b9d..4de563e89 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -56,8 +56,12 @@ void main() { default: pos = 3; } - int _e9 = pos; - switch(_e9) { + switch(0u) { + case 0u: + break; + } + int _e10 = pos; + switch(_e10) { case 1: pos = 0; break; diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index d425b0991..5a771342f 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -68,8 +68,13 @@ void main(uint3 global_id : SV_DispatchThreadID) pos = 3; } } - int _expr9 = pos; - switch(_expr9) { + switch(0u) { + case 0u: { + break; + } + } + int _expr10 = pos; + switch(_expr10) { case 1: { pos = 0; break; diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index 52f990134..8662b8b30 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -76,8 +76,15 @@ kernel void main1( pos = 3; } } - int _e9 = pos; - switch(_e9) { + switch(0u) { + case 0u: { + break; + } + default: { + } + } + int _e10 = pos; + switch(_e10) { case 1: { pos = 0; break; diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index e8f0e2cf1..1a34638d8 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 63 +; Bound: 67 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %41 "main" %38 -OpExecutionMode %41 LocalSize 1 1 1 -OpDecorate %38 BuiltIn GlobalInvocationId +OpEntryPoint GLCompute %42 "main" %39 +OpExecutionMode %42 LocalSize 1 1 1 +OpDecorate %39 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 @@ -15,113 +15,121 @@ OpDecorate %38 BuiltIn GlobalInvocationId %6 = OpConstant %4 2 %7 = OpConstant %4 3 %9 = OpTypeInt 32 0 -%8 = OpTypeVector %9 3 -%13 = OpTypeFunction %2 %4 -%19 = OpTypeFunction %2 -%36 = OpTypePointer Function %4 -%39 = OpTypePointer Input %8 -%38 = OpVariable %39 Input -%43 = OpConstant %9 2 -%44 = OpConstant %9 1 -%45 = OpConstant %9 72 -%46 = OpConstant %9 264 -%12 = OpFunction %2 None %13 -%11 = OpFunctionParameter %4 -%10 = OpLabel -OpBranch %14 -%14 = OpLabel -OpSelectionMerge %15 None -OpSwitch %11 %16 -%16 = OpLabel +%8 = OpConstant %9 0 +%10 = OpTypeVector %9 3 +%14 = OpTypeFunction %2 %4 +%20 = OpTypeFunction %2 +%37 = OpTypePointer Function %4 +%40 = OpTypePointer Input %10 +%39 = OpVariable %40 Input +%44 = OpConstant %9 2 +%45 = OpConstant %9 1 +%46 = OpConstant %9 72 +%47 = OpConstant %9 264 +%13 = OpFunction %2 None %14 +%12 = OpFunctionParameter %4 +%11 = OpLabel OpBranch %15 %15 = OpLabel +OpSelectionMerge %16 None +OpSwitch %12 %17 +%17 = OpLabel +OpBranch %16 +%16 = OpLabel OpReturn OpFunctionEnd -%18 = OpFunction %2 None %19 -%17 = OpLabel -OpBranch %20 -%20 = OpLabel -OpSelectionMerge %21 None -OpSwitch %5 %22 0 %23 -%23 = OpLabel -OpBranch %21 -%22 = OpLabel +%19 = OpFunction %2 None %20 +%18 = OpLabel OpBranch %21 %21 = OpLabel +OpSelectionMerge %22 None +OpSwitch %5 %23 0 %24 +%24 = OpLabel +OpBranch %22 +%23 = OpLabel +OpBranch %22 +%22 = OpLabel OpReturn OpFunctionEnd -%26 = OpFunction %2 None %13 -%25 = OpFunctionParameter %4 -%24 = OpLabel -OpBranch %27 -%27 = OpLabel +%27 = OpFunction %2 None %14 +%26 = OpFunctionParameter %4 +%25 = OpLabel OpBranch %28 %28 = OpLabel -OpLoopMerge %29 %31 None -OpBranch %30 -%30 = OpLabel -OpSelectionMerge %32 None -OpSwitch %25 %33 1 %34 -%34 = OpLabel +OpBranch %29 +%29 = OpLabel +OpLoopMerge %30 %32 None OpBranch %31 +%31 = OpLabel +OpSelectionMerge %33 None +OpSwitch %26 %34 1 %35 +%35 = OpLabel +OpBranch %32 +%34 = OpLabel +OpBranch %33 %33 = OpLabel OpBranch %32 %32 = OpLabel -OpBranch %31 -%31 = OpLabel -OpBranch %28 -%29 = OpLabel +OpBranch %29 +%30 = OpLabel OpReturn OpFunctionEnd -%41 = OpFunction %2 None %19 -%37 = OpLabel -%35 = OpVariable %36 Function -%40 = OpLoad %8 %38 -OpBranch %42 -%42 = OpLabel -OpControlBarrier %43 %44 %45 -OpControlBarrier %43 %43 %46 -OpSelectionMerge %47 None -OpSwitch %3 %48 +%42 = OpFunction %2 None %20 +%38 = OpLabel +%36 = OpVariable %37 Function +%41 = OpLoad %10 %39 +OpBranch %43 +%43 = OpLabel +OpControlBarrier %44 %45 %46 +OpControlBarrier %44 %44 %47 +OpSelectionMerge %48 None +OpSwitch %3 %49 +%49 = OpLabel +OpStore %36 %3 +OpBranch %48 %48 = OpLabel -OpStore %35 %3 -OpBranch %47 -%47 = OpLabel -%49 = OpLoad %4 %35 -OpSelectionMerge %50 None -OpSwitch %49 %51 1 %52 2 %53 3 %54 4 %55 -%52 = OpLabel -OpStore %35 %5 -OpBranch %50 +%50 = OpLoad %4 %36 +OpSelectionMerge %51 None +OpSwitch %50 %52 1 %53 2 %54 3 %55 4 %56 %53 = OpLabel -OpStore %35 %3 -OpBranch %50 +OpStore %36 %5 +OpBranch %51 %54 = OpLabel -OpStore %35 %6 -OpBranch %55 +OpStore %36 %3 +OpBranch %51 %55 = OpLabel -OpBranch %50 +OpStore %36 %6 +OpBranch %56 +%56 = OpLabel +OpBranch %51 +%52 = OpLabel +OpStore %36 %7 +OpBranch %51 %51 = OpLabel -OpStore %35 %7 -OpBranch %50 -%50 = OpLabel -%56 = OpLoad %4 %35 OpSelectionMerge %57 None -OpSwitch %56 %58 1 %59 2 %60 3 %61 4 %62 +OpSwitch %8 %58 0 %59 %59 = OpLabel -OpStore %35 %5 OpBranch %57 -%60 = OpLabel -OpStore %35 %3 +%58 = OpLabel +OpBranch %57 +%57 = OpLabel +%60 = OpLoad %4 %36 +OpSelectionMerge %61 None +OpSwitch %60 %62 1 %63 2 %64 3 %65 4 %66 +%63 = OpLabel +OpStore %36 %5 +OpBranch %61 +%64 = OpLabel +OpStore %36 %3 +OpReturn +%65 = OpLabel +OpStore %36 %6 +OpBranch %66 +%66 = OpLabel +OpReturn +%62 = OpLabel +OpStore %36 %7 OpReturn %61 = OpLabel -OpStore %35 %6 -OpBranch %62 -%62 = OpLabel -OpReturn -%58 = OpLabel -OpStore %35 %7 -OpReturn -%57 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index 511c08aa5..cdb3fc53c 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -56,8 +56,12 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { pos = 3; } } - let e9: i32 = pos; - switch(e9) { + switch(0u) { + case 0u: { + } + } + let e10: i32 = pos; + switch(e10) { case 1: { pos = 0; break; From 70db5f681dd4f899d197b55a7d74f0f1923f9505 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 21 Sep 2021 22:29:16 +0100 Subject: [PATCH 1371/2212] [glsl-in] Allow use of constructors for user types --- src/front/glsl/parser/expressions.rs | 172 +++++++-------- .../in/glsl/{binop.frag => expressions.frag} | 8 + tests/out/wgsl/expressions-frag.wgsl | 196 ++++++++++++++++++ 3 files changed, 280 insertions(+), 96 deletions(-) rename tests/in/glsl/{binop.frag => expressions.frag} (92%) create mode 100644 tests/out/wgsl/expressions-frag.wgsl diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 40cf2122f..51acb0594 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -122,109 +122,89 @@ impl<'source> ParsingContext<'source> { stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let mut base = match self.expect_peek(parser)?.value { - TokenValue::Identifier(_) => { - let (name, mut meta) = self.expect_ident(parser)?; + let mut base = if self.peek_type_name(parser) { + let (mut handle, mut meta) = self.parse_type_non_void(parser)?; - let expr = if self.bump_if(parser, TokenValue::LeftParen).is_some() { - let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; + self.expect(parser, TokenValue::LeftParen)?; + let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; - let kind = match parser.lookup_type.get(&name) { - Some(ty) => FunctionCallKind::TypeConstructor(*ty), - None => FunctionCallKind::Function(name), - }; + if let TypeInner::Array { + size: ArraySize::Dynamic, + stride, + base, + } = parser.module.types[handle].inner + { + let span = parser.module.types.get_span(handle); - HirExpr { - kind: HirExprKind::Call(FunctionCall { kind, args }), - meta, - } - } else { - let var = match parser.lookup_variable(ctx, body, &name, meta) { - Some(var) => var, - None => { - return Err(Error { - kind: ErrorKind::UnknownVariable(name), - meta, - }) - } - }; - - HirExpr { - kind: HirExprKind::Variable(var), - meta, - } - }; - - stmt.hir_exprs.append(expr, Default::default()) - } - TokenValue::TypeName(_) => { - let Token { - value, - meta: mut name_meta, - } = self.bump(parser)?; - let mut meta = name_meta; - - let mut handle = if let TokenValue::TypeName(ty) = value { - parser.module.types.fetch_or_append(ty, name_meta) - } else { - unreachable!() - }; - - let maybe_size = self.parse_array_specifier(parser)?; - - self.expect(parser, TokenValue::LeftParen)?; - let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; - - if let Some((array_size, array_meta)) = maybe_size { - let stride = parser.module.types[handle] - .inner - .span(&parser.module.constants); - - let size = match array_size { - ArraySize::Constant(size) => ArraySize::Constant(size), - ArraySize::Dynamic => { - let constant = parser.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(args.len() as i64), - }, - }, - meta, - ); - - ArraySize::Constant(constant) - } - }; - - name_meta.subsume(array_meta); - handle = parser.module.types.fetch_or_append( - Type { - name: None, - inner: TypeInner::Array { - base: handle, - size, - stride, - }, + let constant = parser.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Uint(args.len() as u64), }, - name_meta, - ); - } - - stmt.hir_exprs.append( - HirExpr { - kind: HirExprKind::Call(FunctionCall { - kind: FunctionCallKind::TypeConstructor(handle), - args, - }), - meta, }, - Default::default(), + Span::default(), + ); + handle = parser.module.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Array { + stride, + base, + size: ArraySize::Constant(constant), + }, + }, + span, ) } - _ => self.parse_primary(parser, ctx, stmt, body)?, + + stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Call(FunctionCall { + kind: FunctionCallKind::TypeConstructor(handle), + args, + }), + meta, + }, + Default::default(), + ) + } else if let TokenValue::Identifier(_) = self.expect_peek(parser)?.value { + let (name, mut meta) = self.expect_ident(parser)?; + + let expr = if self.bump_if(parser, TokenValue::LeftParen).is_some() { + let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; + + let kind = match parser.lookup_type.get(&name) { + Some(ty) => FunctionCallKind::TypeConstructor(*ty), + None => FunctionCallKind::Function(name), + }; + + HirExpr { + kind: HirExprKind::Call(FunctionCall { kind, args }), + meta, + } + } else { + let var = match parser.lookup_variable(ctx, body, &name, meta) { + Some(var) => var, + None => { + return Err(Error { + kind: ErrorKind::UnknownVariable(name), + meta, + }) + } + }; + + HirExpr { + kind: HirExprKind::Variable(var), + meta, + } + }; + + stmt.hir_exprs.append(expr, Default::default()) + } else { + self.parse_primary(parser, ctx, stmt, body)? }; while let TokenValue::LeftBracket diff --git a/tests/in/glsl/binop.frag b/tests/in/glsl/expressions.frag similarity index 92% rename from tests/in/glsl/binop.frag rename to tests/in/glsl/expressions.frag index 1416cb649..00ff8d31a 100644 --- a/tests/in/glsl/binop.frag +++ b/tests/in/glsl/expressions.frag @@ -62,6 +62,14 @@ void testBinOpUintUVec(uint a, uvec4 b) { v = a ^ b; } +void testStructConstructor() { + struct BST { + int data; + }; + + BST tree = BST(1); +} + out vec4 o_color; void main() { o_color.rgba = vec4(1.0); diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl new file mode 100644 index 000000000..452ff85d1 --- /dev/null +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -0,0 +1,196 @@ +struct BST { + data: i32; +}; + +var o_color: vec4; + +fn testBinOpVecFloat(a: vec4, b: f32) { + var a1: vec4; + var b1: f32; + var v: vec4; + + a1 = a; + b1 = b; + let e5: vec4 = a1; + v = (e5 * 2.0); + let e8: vec4 = a1; + v = (e8 / vec4(2.0)); + let e12: vec4 = a1; + v = (e12 + vec4(2.0)); + let e16: vec4 = a1; + v = (e16 - vec4(2.0)); + return; +} + +fn testBinOpFloatVec(a2: vec4, b2: f32) { + var a3: vec4; + var b3: f32; + var v1: vec4; + + a3 = a2; + b3 = b2; + let e5: vec4 = a3; + let e6: f32 = b3; + v1 = (e5 * e6); + let e8: vec4 = a3; + let e9: f32 = b3; + v1 = (e8 / vec4(e9)); + let e12: vec4 = a3; + let e13: f32 = b3; + v1 = (e12 + vec4(e13)); + let e16: vec4 = a3; + let e17: f32 = b3; + v1 = (e16 - vec4(e17)); + return; +} + +fn testBinOpIVecInt(a4: vec4, b4: i32) { + var a5: vec4; + var b5: i32; + var v2: vec4; + + a5 = a4; + b5 = b4; + let e5: vec4 = a5; + let e6: i32 = b5; + v2 = (e5 * e6); + let e8: vec4 = a5; + let e9: i32 = b5; + v2 = (e8 / vec4(e9)); + let e12: vec4 = a5; + let e13: i32 = b5; + v2 = (e12 + vec4(e13)); + let e16: vec4 = a5; + let e17: i32 = b5; + v2 = (e16 - vec4(e17)); + let e20: vec4 = a5; + let e21: i32 = b5; + v2 = (e20 & vec4(e21)); + let e24: vec4 = a5; + let e25: i32 = b5; + v2 = (e24 | vec4(e25)); + let e28: vec4 = a5; + let e29: i32 = b5; + v2 = (e28 ^ vec4(e29)); + let e32: vec4 = a5; + let e33: i32 = b5; + v2 = (e32 >> vec4(u32(e33))); + let e37: vec4 = a5; + let e38: i32 = b5; + v2 = (e37 << vec4(u32(e38))); + return; +} + +fn testBinOpIntIVec(a6: i32, b6: vec4) { + var a7: i32; + var b7: vec4; + var v3: vec4; + + a7 = a6; + b7 = b6; + let e5: i32 = a7; + let e6: vec4 = b7; + v3 = (e5 * e6); + let e8: i32 = a7; + let e9: vec4 = b7; + v3 = (vec4(e8) + e9); + let e12: i32 = a7; + let e13: vec4 = b7; + v3 = (vec4(e12) - e13); + let e16: i32 = a7; + let e17: vec4 = b7; + v3 = (vec4(e16) & e17); + let e20: i32 = a7; + let e21: vec4 = b7; + v3 = (vec4(e20) | e21); + let e24: i32 = a7; + let e25: vec4 = b7; + v3 = (vec4(e24) ^ e25); + return; +} + +fn testBinOpUVecUint(a8: vec4, b8: u32) { + var a9: vec4; + var b9: u32; + var v4: vec4; + + a9 = a8; + b9 = b8; + let e5: vec4 = a9; + let e6: u32 = b9; + v4 = (e5 * e6); + let e8: vec4 = a9; + let e9: u32 = b9; + v4 = (e8 / vec4(e9)); + let e12: vec4 = a9; + let e13: u32 = b9; + v4 = (e12 + vec4(e13)); + let e16: vec4 = a9; + let e17: u32 = b9; + v4 = (e16 - vec4(e17)); + let e20: vec4 = a9; + let e21: u32 = b9; + v4 = (e20 & vec4(e21)); + let e24: vec4 = a9; + let e25: u32 = b9; + v4 = (e24 | vec4(e25)); + let e28: vec4 = a9; + let e29: u32 = b9; + v4 = (e28 ^ vec4(e29)); + let e32: vec4 = a9; + let e33: u32 = b9; + v4 = (e32 >> vec4(e33)); + let e36: vec4 = a9; + let e37: u32 = b9; + v4 = (e36 << vec4(e37)); + return; +} + +fn testBinOpUintUVec(a10: u32, b10: vec4) { + var a11: u32; + var b11: vec4; + var v5: vec4; + + a11 = a10; + b11 = b10; + let e5: u32 = a11; + let e6: vec4 = b11; + v5 = (e5 * e6); + let e8: u32 = a11; + let e9: vec4 = b11; + v5 = (vec4(e8) + e9); + let e12: u32 = a11; + let e13: vec4 = b11; + v5 = (vec4(e12) - e13); + let e16: u32 = a11; + let e17: vec4 = b11; + v5 = (vec4(e16) & e17); + let e20: u32 = a11; + let e21: vec4 = b11; + v5 = (vec4(e20) | e21); + let e24: u32 = a11; + let e25: vec4 = b11; + v5 = (vec4(e24) ^ e25); + return; +} + +fn testStructConstructor() { + var tree: BST = BST(1); + +} + +fn main1() { + let e1: vec4 = o_color; + let e4: vec4 = vec4(1.0); + o_color.x = e4.x; + o_color.y = e4.y; + o_color.z = e4.z; + o_color.w = e4.w; + return; +} + +[[stage(fragment)]] +fn main() { + main1(); + return; +} From 160ab82feeba2d4c555543a998a3f022bde2dfcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 21 Sep 2021 22:29:39 +0100 Subject: [PATCH 1372/2212] [glsl-in] Allow array constructors --- src/front/glsl/functions.rs | 4 ++-- tests/in/glsl/expressions.frag | 4 ++++ tests/out/wgsl/expressions-frag.wgsl | 5 +++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 36db43c0c..870d60537 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -243,7 +243,7 @@ impl Parser { } } } - TypeInner::Struct { .. } => ctx.add_expression( + TypeInner::Struct { .. } | TypeInner::Array { .. } => ctx.add_expression( Expression::Compose { ty, components: args.into_iter().map(|arg| arg.0).collect(), @@ -253,7 +253,7 @@ impl Parser { ), _ => { self.errors.push(Error { - kind: ErrorKind::SemanticError("Bad cast".into()), + kind: ErrorKind::SemanticError("Bad type constructor".into()), meta, }); diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 00ff8d31a..58176f5ae 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -70,6 +70,10 @@ void testStructConstructor() { BST tree = BST(1); } +void testArrayConstructor() { + float tree[1] = float[1](0.0); +} + out vec4 o_color; void main() { o_color.rgba = vec4(1.0); diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 452ff85d1..f7514881e 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -179,6 +179,11 @@ fn testStructConstructor() { } +fn testArrayConstructor() { + var tree1: array = array(0.0); + +} + fn main1() { let e1: vec4 = o_color; let e4: vec4 = vec4(1.0); From 04b176ec6bd16929c45bd9db932ec11f86195c6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 23 Sep 2021 18:17:41 +0100 Subject: [PATCH 1373/2212] [glsl-in] Refractor overload selector and add comments --- src/front/glsl/builtins.rs | 8 +- src/front/glsl/functions.rs | 288 ++++++++++++++++++++++-------------- 2 files changed, 183 insertions(+), 113 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 5f7fd49d1..0c65d5f15 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1482,7 +1482,7 @@ impl MacroCall { Ok(args[0]) } MacroCall::SamplerShadow => { - sampled_to_depth(&mut parser.module, ctx, args[0], meta, &mut parser.errors)?; + sampled_to_depth(&mut parser.module, ctx, args[0], meta, &mut parser.errors); parser.invalidate_expression(ctx, args[0], meta)?; ctx.samplers.insert(args[0], args[1]); Ok(args[0]) @@ -1916,7 +1916,7 @@ pub fn sampled_to_depth( image: Handle, meta: Span, errors: &mut Vec, -) -> Result<()> { +) { let ty = match ctx[image] { Expression::GlobalVariable(handle) => &mut module.global_variables.get_mut(handle).ty, Expression::FunctionArgument(i) => { @@ -1924,7 +1924,7 @@ pub fn sampled_to_depth( &mut ctx.arguments[i as usize].ty } _ => { - return Err(Error { + return errors.push(Error { kind: ErrorKind::SemanticError("Not a valid texture expression".into()), meta, }) @@ -1960,6 +1960,4 @@ pub fn sampled_to_depth( meta, }), }; - - Ok(()) } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 870d60537..f080c2d48 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -376,128 +376,103 @@ impl Parser { // Borrow again but without mutability let declaration = self.lookup_function.get(&name).unwrap(); - // Helper enum containing the type of conversion need for a call - #[derive(PartialEq, Eq, Clone, Copy, Debug)] - enum Conversion { - // No conversion needed - Exact, - // Float to double conversion needed - FloatToDouble, - // Int or uint to float conversion needed - IntToFloat, - // Int or uint to double conversion needed - IntToDouble, - // Other type of conversion needed - Other, - // No conversion was yet registered - None, - } - - let mut maybe_decl = None; + // Possibly contains the overload to be used in the call + let mut maybe_overload = None; + // The conversions needed for the best analyzed overload, this is initialized all to + // `NONE` to make sure that conversions always pass the first time without ambiguity let mut old_conversions = vec![Conversion::None; args.len()]; + // Tracks whether the comparison between overloads lead to an ambiguity let mut ambiguous = false; - 'outer: for decl in declaration.overloads.iter() { - if args.len() != decl.parameters.len() { + // Iterate over all the available overloads to select either an exact match or a + // overload which has suitable implicit conversions + 'outer: for overload in declaration.overloads.iter() { + // If the overload and the function call don't have the same number of arguments + // continue to the next overload + if args.len() != overload.parameters.len() { continue; } + // Stores whether the current overload matches exactly the function call let mut exact = true; // State of the selection - // If None we still don't know what is the best declaration - // If Some(true) the new declaration is better - // If Some(false) the old declaration is better + // If None we still don't know what is the best overload + // If Some(true) the new overload is better + // If Some(false) the old overload is better let mut superior = None; + // Store the conversions for the current overload so that later they can replace the + // conversions used for querying the best overload let mut new_conversions = vec![Conversion::None; args.len()]; - for ((i, decl_arg), call_arg) in decl.parameters.iter().enumerate().zip(args.iter()) { - use ScalarKind::*; + // Loop trough the overload parameters and check if the current overload is better + // compared to the previous best overload. + for (i, overload_parameter) in overload.parameters.iter().enumerate() { + let call_argument = &args[i]; + let parameter_info = &overload.parameters_info[i]; - if decl.parameters_info[i].depth { + // If the image is used in the overload as a depth texture convert it + // before comparing, otherwise exact matches wouldn't be reported + if parameter_info.depth { sampled_to_depth( &mut self.module, ctx, - call_arg.0, - call_arg.1, + call_argument.0, + call_argument.1, &mut self.errors, - )?; - self.invalidate_expression(ctx, call_arg.0, call_arg.1)? + ); + self.invalidate_expression(ctx, call_argument.0, call_argument.1)? } - let decl_inner = &self.module.types[*decl_arg].inner; - let call_inner = self.resolve_type(ctx, call_arg.0, call_arg.1)?; + let overload_param_ty = &self.module.types[*overload_parameter].inner; + let call_arg_ty = self.resolve_type(ctx, call_argument.0, call_argument.1)?; - if decl_inner == call_inner { + // If the types match there's no need to check for conversions so continue + if overload_param_ty == call_arg_ty { new_conversions[i] = Conversion::Exact; continue; } - exact = false; - - let (decl_kind, decl_width, call_kind, call_width) = match (decl_inner, call_inner) - { - ( - &TypeInner::Scalar { - kind: decl_kind, - width: decl_width, - }, - &TypeInner::Scalar { - kind: call_kind, - width: call_width, - }, - ) => (decl_kind, decl_width, call_kind, call_width), - ( - &TypeInner::Vector { - kind: decl_kind, - size: decl_size, - width: decl_width, - }, - &TypeInner::Vector { - kind: call_kind, - size: call_size, - width: call_width, - }, - ) if decl_size == call_size => (decl_kind, decl_width, call_kind, call_width), - ( - &TypeInner::Matrix { - rows: decl_rows, - columns: decl_columns, - width: decl_width, - }, - &TypeInner::Matrix { - rows: call_rows, - columns: call_columns, - width: call_width, - }, - ) if decl_columns == call_columns && decl_rows == call_rows => { - (Float, decl_width, Float, call_width) - } - _ => continue 'outer, - }; - - if type_power(decl_kind, decl_width) < type_power(call_kind, call_width) { + // If the argument is to be passed as a pointer (i.e. either `out` or + // `inout` where used as qualifiers) no conversion shall be performed + if parameter_info.qualifier.is_lhs() { continue 'outer; } - let conversion = match ((decl_kind, decl_width), (call_kind, call_width)) { - ((Float, 8), (Float, 4)) => Conversion::FloatToDouble, - ((Float, 4), (Sint, _)) | ((Float, 4), (Uint, _)) => Conversion::IntToFloat, - ((Float, 8), (Sint, _)) | ((Float, 8), (Uint, _)) => Conversion::IntToDouble, - _ => Conversion::Other, + // Try to get the type of conversion needed otherwise this overload can't be used + // since no conversion makes it possible so skip it + let conversion = match conversion(overload_param_ty, call_arg_ty) { + Some(info) => info, + None => continue 'outer, }; - // true - New declaration argument has a better conversion - // false - Old declaration argument has a better conversion + // At this point a conversion will be needed so the overload no longer + // exactly matches the call arguments + exact = false; + + // Compare the conversions needed for this overload parameter to that of the + // last overload analyzed respective parameter, the value is: + // - `true` when the new overload argument has a better conversion + // - `false` when the old overload argument has a better conversion let best_arg = match (conversion, old_conversions[i]) { + // An exact match is always better, we don't need to check this for the + // current overload since it was checked earlier (_, Conversion::Exact) => false, - (Conversion::FloatToDouble, _) - | (_, Conversion::None) - | (Conversion::IntToFloat, Conversion::IntToDouble) => true, - (_, Conversion::FloatToDouble) - | (Conversion::IntToDouble, Conversion::IntToFloat) => false, + // No overload was yet analyzed so this one is the best yet + (_, Conversion::None) => true, + // A conversion from a float to a double is the best possible conversion + (Conversion::FloatToDouble, _) => true, + (_, Conversion::FloatToDouble) => false, + // A conversion from a float to an integer is preferred than one + // from double to an integer + (Conversion::IntToFloat, Conversion::IntToDouble) => true, + (Conversion::IntToDouble, Conversion::IntToFloat) => false, + // This case handles things like no conversion and exact which were already + // treated and other cases which no conversion is better than the other _ => continue, }; + // Check if the best parameter corresponds to the current selected overload + // to pass to the next comparation, if this isn't true mark it as ambiguous match best_arg { true => match superior { Some(false) => ambiguous = true, @@ -513,28 +488,33 @@ impl Parser { } } + // The overload matches exactly the function call so there's no ambiguity (since + // repeated overload aren't allowed) and the current overload is selected, no + // further querying is needed. if exact { - maybe_decl = Some(decl); + maybe_overload = Some(overload); ambiguous = false; break; } match superior { - // New declaration is better keep it + // New overload is better keep it Some(true) => { - maybe_decl = Some(decl); + maybe_overload = Some(overload); // Replace the conversions old_conversions = new_conversions; } - // Old declaration is better do nothing + // Old overload is better do nothing Some(false) => {} - // No declaration was better than the other this can be caused - // when + // No overload was better than the other this can be caused + // when all conversions are ambiguous in which the overloads themselves are + // ambiguous. None => { ambiguous = true; - // Assign the new declaration to make sure we always have - // one to make error reporting happy - maybe_decl = Some(decl); + // Assign the new overload, this helps ensures that in this case of + // amiguity the parsing won't end immediately and allow for further + // collection of errors. + maybe_overload = Some(overload); } } } @@ -548,18 +528,19 @@ impl Parser { }) } - let decl = maybe_decl.ok_or_else(|| Error { + let overload = maybe_overload.ok_or_else(|| Error { kind: ErrorKind::SemanticError(format!("Unknown function '{}'", name).into()), meta, })?; - let parameters_info = decl.parameters_info.clone(); - let parameters = decl.parameters.clone(); - let is_void = decl.void; - let kind = decl.kind; + let parameters_info = overload.parameters_info.clone(); + let parameters = overload.parameters.clone(); + let is_void = overload.void; + let kind = overload.kind; let mut arguments = Vec::with_capacity(args.len()); let mut proxy_writes = Vec::new(); + // Iterate trough the function call arguments applying transformations as needed for (parameter_info, (expr, parameter)) in parameters_info .iter() .zip(raw_args.iter().zip(parameters.iter())) @@ -567,11 +548,12 @@ impl Parser { let (mut handle, meta) = ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.as_pos(), body)?; - if let TypeInner::Vector { size, kind, width } = - *self.resolve_type(ctx, handle, meta)? - { - if parameter_info.qualifier.is_lhs() - && matches!(ctx[handle], Expression::Swizzle { .. }) + if parameter_info.qualifier.is_lhs() { + // If the argument is to be passed as a pointer but the type of the + // expression returns a vector it must mean that it was for example + // swizzled and it must be spilled into a local before calling + if let TypeInner::Vector { size, kind, width } = + *self.resolve_type(ctx, handle, meta)? { let ty = self.module.types.fetch_or_append( Type { @@ -603,11 +585,14 @@ impl Parser { ); arguments.push(temp_expr); + // Register the temporary local to be written back to it's original + // place after the function call proxy_writes.push((*expr, temp_expr)); continue; } } + // Apply implicit conversions as needed let scalar_components = scalar_components(&self.module.types[*parameter].inner); if let Some((kind, width)) = scalar_components { ctx.implicit_conversion(self, &mut handle, meta, kind, width)?; @@ -636,6 +621,8 @@ impl Parser { ); ctx.emit_start(); + + // Write back all the variables that were scheduled to their original place for (tgt, pointer) in proxy_writes { let value = ctx.add_expression(Expression::Load { pointer }, meta, body); let target = ctx @@ -966,3 +953,88 @@ fn is_double(ty: &TypeInner) -> bool { _ => false, } } + +/// Helper enum containing the type of conversion need for a call +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +enum Conversion { + /// No conversion needed + Exact, + /// Float to double conversion needed + FloatToDouble, + /// Int or uint to float conversion needed + IntToFloat, + /// Int or uint to double conversion needed + IntToDouble, + /// Other type of conversion needed + Other, + /// No conversion was yet registered + None, +} + +/// Helper function, returns the type of conversion from `source` to `target`, if a +/// conversion is not possible returns None. +fn conversion(target: &TypeInner, source: &TypeInner) -> Option { + use ScalarKind::*; + + // Gather the `ScalarKind` and scalar width from both the target and the source + let (target_kind, target_width, source_kind, source_width) = match (target, source) { + // Conversions between scalars are allowed + ( + &TypeInner::Scalar { + kind: tgt_kind, + width: tgt_width, + }, + &TypeInner::Scalar { + kind: src_kind, + width: src_width, + }, + ) => (tgt_kind, tgt_width, src_kind, src_width), + // Conversions between vectors of the same size are allowed + ( + &TypeInner::Vector { + kind: tgt_kind, + size: tgt_size, + width: tgt_width, + }, + &TypeInner::Vector { + kind: src_kind, + size: src_size, + width: src_width, + }, + ) if tgt_size == src_size => (tgt_kind, tgt_width, src_kind, src_width), + // Conversions between matrices of the same size are allowed + ( + &TypeInner::Matrix { + rows: tgt_rows, + columns: tgt_cols, + width: tgt_width, + }, + &TypeInner::Matrix { + rows: src_rows, + columns: src_cols, + width: src_width, + }, + ) if tgt_cols == src_cols && tgt_rows == src_rows => (Float, tgt_width, Float, src_width), + _ => return None, + }; + + // Check if source can be converted into target, if this is the case then the type + // power of target must be higher than that of source + let target_power = type_power(target_kind, target_width); + let source_power = type_power(source_kind, source_width); + if target_power < source_power { + return None; + } + + Some( + match ((target_kind, target_width), (source_kind, source_width)) { + // A conversion from a float to a double is special + ((Float, 8), (Float, 4)) => Conversion::FloatToDouble, + // A conversion from an integer to a float is special + ((Float, 4), (Sint, _)) | ((Float, 4), (Uint, _)) => Conversion::IntToFloat, + // A conversion from an integer to a double is special + ((Float, 8), (Sint, _)) | ((Float, 8), (Uint, _)) => Conversion::IntToDouble, + _ => Conversion::Other, + }, + ) +} From 73f9d072079246ccf119c4e27de2b624afa6e466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 24 Sep 2021 09:40:05 +0100 Subject: [PATCH 1374/2212] [Typifier] Some relational functions output vectors Previously the typifier flagged all relational functions as producing a scalar boolean but with the exception of `all` and `any`, according to the wgsl spec, all other relational functions output a type the same size as the input. --- src/proc/typifier.rs | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 4a38ea6fd..0e7171b87 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -626,10 +626,34 @@ impl<'a> ResolveContext<'a> { } crate::Expression::Select { accept, .. } => past(accept).clone(), crate::Expression::Derivative { axis: _, expr } => past(expr).clone(), - crate::Expression::Relational { .. } => TypeResolution::Value(Ti::Scalar { - kind: crate::ScalarKind::Bool, - width: crate::BOOL_WIDTH, - }), + crate::Expression::Relational { fun, argument } => match fun { + crate::RelationalFunction::All | crate::RelationalFunction::Any => { + TypeResolution::Value(Ti::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }) + } + crate::RelationalFunction::IsNan + | crate::RelationalFunction::IsInf + | crate::RelationalFunction::IsFinite + | crate::RelationalFunction::IsNormal => match *past(argument).inner_with(types) { + Ti::Scalar { .. } => TypeResolution::Value(Ti::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }), + Ti::Vector { size, .. } => TypeResolution::Value(Ti::Vector { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + size, + }), + ref other => { + return Err(ResolveError::IncompatibleOperands(format!( + "{:?}({:?})", + fun, other + ))) + } + }, + }, crate::Expression::Math { fun, arg, From d44e2ad207883f47019316ccbd6f02c27b27cde9 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 22 Sep 2021 12:08:04 -0700 Subject: [PATCH 1375/2212] Simplify interpolation defaulting. Replace `Module::apply_common_default_interpolation` with a simpler function that handles a single `Binding` at a time. In exchange for the simplicity, the function must be called at each point function arguments, function results, and struct members are prepared. (Any missed spots will be caught by the verifier.) This approach no longer requires mutating types in the arena, a prerequisite for properly handling type identity. Applying defaults to struct members when the struct declaration is parsed does have a disadvantage, compared to the old whole-module pass: at struct parse time, we don't yet know which pipeline stages the struct will be used in. The best we can do is apply defaults to anything with a `Location` binding. This causes needless qualifiers to appear in some output. However, it seems that our back end languages all tolerate such qualifiers. --- src/front/interpolator.rs | 59 ++++++++++ src/front/mod.rs | 2 + src/front/spv/function.rs | 11 +- src/front/spv/mod.rs | 18 +++- src/front/wgsl/mod.rs | 19 +++- src/lib.rs | 16 +++ src/proc/interpolator.rs | 149 -------------------------- src/proc/mod.rs | 1 - src/valid/interface.rs | 4 - tests/out/hlsl/interface.hlsl | 2 +- tests/out/ir/shadow.ron | 4 +- tests/out/spv/interface.vertex.spvasm | 1 + 12 files changed, 111 insertions(+), 175 deletions(-) create mode 100644 src/front/interpolator.rs delete mode 100644 src/proc/interpolator.rs diff --git a/src/front/interpolator.rs b/src/front/interpolator.rs new file mode 100644 index 000000000..491ca5a0b --- /dev/null +++ b/src/front/interpolator.rs @@ -0,0 +1,59 @@ +//! Interpolation defaults. + +impl crate::Binding { + /// Apply the usual default interpolation for `ty` to `binding`. + /// + /// This function is a utility front ends may use to satisfy the Naga IR's + /// requirement, meant to ensure that input languages' policies have been + /// applied appropriately, that all I/O `Binding`s from the vertex shader to the + /// fragment shader must have non-`None` `interpolation` values. + /// + /// All the shader languages Naga supports have similar rules: + /// perspective-correct, center-sampled interpolation is the default for any + /// binding that can vary, and everything else either defaults to flat, or + /// requires an explicit flat qualifier/attribute/what-have-you. + /// + /// If `binding` is not a [`Location`] binding, or if its [`interpolation`] is + /// already set, then make no changes. Otherwise, set `binding`'s interpolation + /// and sampling to reasonable defaults depending on `ty`, the type of the value + /// being interpolated: + /// + /// - If `ty` is a floating-point scalar, vector, or matrix type, then + /// default to [`Perspective`] interpolation and [`Center`] sampling. + /// + /// - If `ty` is an integral scalar or vector, then default to [`Flat`] + /// interpolation, which has no associated sampling. + /// + /// - For any other types, make no change. Such types are not permitted as + /// user-defined IO values, and will probably be flagged by the verifier + /// + /// When structs appear in input or output types, each member ought to have its + /// own [`Binding`], so structs are simply covered by the third case. + /// + /// [`Binding`]: crate::Binding + /// [`Location`]: crate::Binding::Location + /// [`interpolation`]: crate::Binding::Location::interpolation + /// [`Perspective`]: crate::Interpolation::Perspective + /// [`Flat`]: crate::Interpolation::Flat + /// [`Center`]: crate::Sampling::Center + pub fn apply_default_interpolation(&mut self, ty: &crate::TypeInner) { + if let crate::Binding::Location { + location: _, + interpolation: ref mut interpolation @ None, + ref mut sampling, + } = *self + { + match ty.scalar_kind() { + Some(crate::ScalarKind::Float) => { + *interpolation = Some(crate::Interpolation::Perspective); + *sampling = Some(crate::Sampling::Center); + } + Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { + *interpolation = Some(crate::Interpolation::Flat); + *sampling = None; + } + Some(_) | None => {} + } + } + } +} diff --git a/src/front/mod.rs b/src/front/mod.rs index 292acf3da..56e000d62 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,5 +1,7 @@ //! Parsers which load shaders into memory. +mod interpolator; + #[cfg(feature = "glsl-in")] pub mod glsl; #[cfg(feature = "spv-in")] diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 90ea81033..0ce8e7686 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -341,13 +341,8 @@ impl> super::Parser { let mut arg = arg.clone(); if ep.stage == crate::ShaderStage::Fragment { - if let Some(crate::Binding::Location { - interpolation: ref mut interpolation @ None, - .. - }) = arg.binding - { - *interpolation = Some(crate::Interpolation::Perspective); - // default + if let Some(ref mut binding) = arg.binding { + binding.apply_default_interpolation(&module.types[arg.ty].inner); } } function.arguments.push(arg); @@ -516,8 +511,6 @@ impl> super::Parser { }); } - module.apply_common_default_interpolation(); - Ok(()) } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 4869a4786..34b510d35 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3725,7 +3725,7 @@ impl> Parser { span = crate::front::align_up(span, self.layouter[ty].alignment.get()); alignment = self.layouter[ty].alignment.get().max(alignment); - let binding = decor.io_binding().ok(); + let mut binding = decor.io_binding().ok(); if let Some(offset) = decor.offset { span = offset; } @@ -3733,11 +3733,12 @@ impl> Parser { span += self.layouter[ty].size; + let inner = &module.types[ty].inner; if let crate::TypeInner::Matrix { columns, rows, width, - } = module.types[ty].inner + } = *inner { if let Some(stride) = decor.matrix_stride { let rounded_rows = if rows > crate::VectorSize::Bi { @@ -3757,6 +3758,9 @@ impl> Parser { } } + if let Some(ref mut binding) = binding { + binding.apply_default_interpolation(inner); + } members.push(crate::StructMember { name: decor.name, ty, @@ -4181,7 +4185,7 @@ impl> Parser { (Variable::Global, var) } ExtendedClass::Input => { - let binding = dec.io_binding()?; + let mut binding = dec.io_binding()?; let mut unsigned_ty = effective_ty; if let crate::Binding::BuiltIn(built_in) = binding { let needs_inner_uint = match built_in { @@ -4222,6 +4226,9 @@ impl> Parser { ty: effective_ty, init: None, }; + + binding.apply_default_interpolation(&module.types[unsigned_ty].inner); + let inner = Variable::Input(crate::FunctionArgument { name: dec.name, ty: unsigned_ty, @@ -4231,7 +4238,7 @@ impl> Parser { } ExtendedClass::Output => { // For output interface blocks, this would be a structure. - let binding = dec.io_binding().ok(); + let mut binding = dec.io_binding().ok(); let init = match binding { Some(crate::Binding::BuiltIn(built_in)) => { match null::generate_default_built_in( @@ -4297,6 +4304,9 @@ impl> Parser { ty: effective_ty, init, }; + if let Some(ref mut binding) = binding { + binding.apply_default_interpolation(&module.types[effective_ty].inner); + } let inner = Variable::Output(crate::FunctionResult { ty: effective_ty, binding, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index bc013f147..09c66bb63 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1085,7 +1085,7 @@ impl BindingParser { (None, None, None, None) => Ok(None), (Some(location), None, interpolation, sampling) => { // Before handing over the completed `Module`, we call - // `apply_common_default_interpolation` to ensure that the interpolation and + // `apply_default_interpolation` to ensure that the interpolation and // sampling have been explicitly specified on all vertex shader output and fragment // shader input user bindings, so leaving them potentially `None` here is fine. Ok(Some(crate::Binding::Location { @@ -2704,10 +2704,14 @@ impl Parser { alignment = alignment.max(align); offset = range.end; + let mut binding = bind_parser.finish(bind_span)?; + if let Some(ref mut binding) = binding { + binding.apply_default_interpolation(&type_arena[ty].inner); + } members.push(crate::StructMember { name: Some(name.to_owned()), ty, - binding: bind_parser.finish(bind_span)?, + binding, offset: range.start, }); } @@ -3818,7 +3822,7 @@ impl Parser { ExpectedToken::Token(Token::Separator(',')), )); } - let binding = self.parse_varying_binding(lexer)?; + let mut binding = self.parse_varying_binding(lexer)?; let (param_name, param_name_span, param_type, _access) = self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; let param_index = arguments.len() as u32; @@ -3833,6 +3837,9 @@ impl Parser { is_reference: false, }, ); + if let Some(ref mut binding) = binding { + binding.apply_default_interpolation(&module.types[param_type].inner); + } arguments.push(crate::FunctionArgument { name: Some(param_name.to_string()), ty: param_type, @@ -3842,9 +3849,12 @@ impl Parser { } // read return type let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { - let binding = self.parse_varying_binding(lexer)?; + let mut binding = self.parse_varying_binding(lexer)?; let (ty, _access) = self.parse_type_decl(lexer, None, &mut module.types, &mut module.constants)?; + if let Some(ref mut binding) = binding { + binding.apply_default_interpolation(&module.types[ty].inner); + } Some(crate::FunctionResult { ty, binding }) } else { None @@ -4122,7 +4132,6 @@ impl Parser { log::error!("Reached the end of file, but scopes are not closed"); return Err(Error::Other.as_parse_error(lexer.source)); }; - module.apply_common_default_interpolation(); return Ok(module); } } diff --git a/src/lib.rs b/src/lib.rs index 697264c51..afc93094d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -710,7 +710,23 @@ pub enum ConstantInner { pub enum Binding { /// Built-in shader variable. BuiltIn(BuiltIn), + /// Indexed location. + /// + /// Values passed from the [`Vertex`] stage to the [`Fragment`] stage must + /// have their `interpolation` defaulted (i.e. not `None`) by the front end + /// as appropriate for that language. + /// + /// For other stages, we permit interpolations even though they're ignored. + /// When a front end is parsing a struct type, it usually doesn't know what + /// stages will be using it for IO, so it's easiest if it can apply the + /// defaults to anything with a `Location` binding, just in case. + /// + /// For anything other than floating-point scalars and vectors, the + /// interpolation must be `Flat`. + /// + /// [`Vertex`]: crate::ShaderStage::Vertex + /// [`Fragment`]: crate::ShaderStage::Fragment Location { location: u32, interpolation: Option, diff --git a/src/proc/interpolator.rs b/src/proc/interpolator.rs deleted file mode 100644 index 3b550782c..000000000 --- a/src/proc/interpolator.rs +++ /dev/null @@ -1,149 +0,0 @@ -pub use crate::{Arena, Handle}; - -impl crate::Module { - /// Apply the usual default interpolation for vertex shader outputs and fragment shader inputs. - /// - /// For every [`Binding`] that is a vertex shader output or a fragment shader - /// input, and that has an `interpolation` or `sampling` of `None`, assign a - /// default interpolation and sampling as follows: - /// - /// - If the `Binding`'s type contains only 32-bit floating-point values or - /// vectors of such, default its interpolation to `Perspective` and its - /// sampling to `Center`. - /// - /// - Otherwise, mark its interpolation as `Flat`. - /// - /// When struct appear in input or output types, apply these rules to their - /// leaves, since those are the things that actually get assigned locations. - /// - /// This function is a utility front ends may use to satisfy the Naga IR's - /// requirement that all I/O `Binding`s from the vertex shader to the - /// fragment shader must have non-`None` `interpolation` values. This - /// requirement is meant to ensure that input languages' policies have been - /// applied appropriately. - /// - /// All the shader languages Naga supports have similar rules: - /// perspective-correct, center-sampled interpolation is the default for any - /// binding that can vary, and everything else either defaults to flat, or - /// requires an explicit flat qualifier/attribute/what-have-you. - /// - /// [`Binding`]: crate::Binding - pub fn apply_common_default_interpolation(&mut self) { - use crate::{Binding, ScalarKind, Type, TypeInner}; - - /// Choose a default interpolation for a function argument or result. - /// - /// `binding` refers to the `Binding` whose type is `ty`. If `ty` is a struct, then it's the - /// bindings of the struct's members that we care about, and the binding of the struct - /// itself is meaningless, so `binding` should be `None`. - fn default_binding_or_struct( - binding: &mut Option, - ty: Handle, - types: &mut Arena, - ) { - let inner = &mut types.get_mut(ty).inner; - if let TypeInner::Struct { - members: ref mut m, .. - } = *inner - { - // A struct. It's the individual members we care about, so recurse. - - // To choose the right interpolations for `members`, we must consult other - // elements of `types`. But both `members` and the types it refers to are stored - // in `types`, and Rust won't let us mutate one element of the `Arena`'s `Vec` - // while reading others. - // - // So, temporarily swap the member list out its type, assign appropriate - // interpolations to its members, and then swap the list back in. - use std::mem; - let mut members = mem::take(m); - - for member in &mut members { - default_binding_or_struct(&mut member.binding, member.ty, types); - } - - // Swap the member list back in. It's essential that we call `types.get_mut` - // afresh here, rather than just using `m`: it's only because `m` was dead that - // we were able to pass `types` to the recursive call. - match types.get_mut(ty).inner { - TypeInner::Struct { - members: ref mut m, .. - } => mem::replace(m, members), - _ => unreachable!("ty must be a struct"), - }; - - return; - } - - // For all other types, a binding is required. Missing bindings will - // be caught during validation, but this processor is meant for use - // by front ends before validation, so just return for now. - let binding = match binding.as_mut() { - None => return, - Some(binding) => binding, - }; - - match *inner { - // Some interpolatable type. - // - // GLSL has 64-bit floats, but it won't interpolate them. WGSL and MSL only have - // 32-bit floats. SPIR-V has 16- and 64-bit float capabilities, but Vulkan is vague - // about what can and cannot be interpolated. - TypeInner::Scalar { - kind: ScalarKind::Float, - width: 4, - } - | TypeInner::Vector { - kind: ScalarKind::Float, - width: 4, - .. - } => { - if let Binding::Location { - ref mut interpolation, - ref mut sampling, - .. - } = *binding - { - if interpolation.is_none() { - *interpolation = Some(crate::Interpolation::Perspective); - } - if sampling.is_none() && *interpolation != Some(crate::Interpolation::Flat) - { - *sampling = Some(crate::Sampling::Center); - } - } - } - - // Some type that can't be interpolated. - _ => { - if let Binding::Location { - ref mut interpolation, - ref mut sampling, - .. - } = *binding - { - *interpolation = Some(crate::Interpolation::Flat); - *sampling = None; - } - } - } - } - - for ep in &mut self.entry_points { - let function = &mut ep.function; - match ep.stage { - crate::ShaderStage::Fragment => { - for arg in &mut function.arguments { - default_binding_or_struct(&mut arg.binding, arg.ty, &mut self.types); - } - } - crate::ShaderStage::Vertex => { - if let Some(result) = function.result.as_mut() { - default_binding_or_struct(&mut result.binding, result.ty, &mut self.types); - } - } - _ => (), - } - } - } -} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 867782ffe..d672e905c 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,7 +1,6 @@ //! Module processing functionality. mod index; -mod interpolator; mod layouter; mod namer; mod terminator; diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 9253042af..ff3f2401c 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -256,10 +256,6 @@ impl VaryingContext<'_> { return Err(VaryingError::BindingCollision { location }); } - // Values passed from the vertex shader to the fragment shader must have their - // interpolation defaulted (i.e. not `None`) by the front end, as appropriate for - // that language. For anything other than floating-point scalars and vectors, the - // interpolation must be `Flat`. let needs_interpolation = match self.stage { crate::ShaderStage::Vertex => self.output, crate::ShaderStage::Fragment => !self.output, diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index affd807ec..3c4334def 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -13,7 +13,7 @@ struct VertexOutput { struct FragmentOutput { float depth : SV_Depth; uint sample_mask : SV_Coverage; - float color : SV_Target0; + linear float color : SV_Target0; }; groupshared uint output[1]; diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 8c4e2df9e..763aa28e9 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -1527,8 +1527,8 @@ ty: 4, binding: Some(Location( location: 0, - interpolation: None, - sampling: None, + interpolation: Some(Perspective), + sampling: Some(Center), )), )), local_variables: [], diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index 9910b2bc5..c51a4d563 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -15,6 +15,7 @@ OpDecorate %15 ArrayStride 4 OpDecorate %18 BuiltIn VertexIndex OpDecorate %21 BuiltIn InstanceIndex OpDecorate %23 Location 10 +OpDecorate %23 Flat OpDecorate %25 BuiltIn Position OpDecorate %27 Location 1 OpDecorate %29 BuiltIn PointSize From f91e95b22e4cde9537d58443a6f7fe8930451621 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 17 Sep 2021 18:24:01 -0700 Subject: [PATCH 1376/2212] [glsl-in]: Register new types as necessary during constant solving. --- src/front/glsl/constants.rs | 50 ++++++++++++++++++++++++------------- src/front/glsl/types.rs | 2 +- 2 files changed, 33 insertions(+), 19 deletions(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 4d2a1a900..e39a59621 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -6,7 +6,7 @@ use crate::{ #[derive(Debug)] pub struct ConstantSolver<'a> { - pub types: &'a Arena, + pub types: &'a mut Arena, pub expressions: &'a Arena, pub constants: &'a mut Arena, } @@ -53,8 +53,10 @@ pub enum ConstantSolvingError { InvalidBinaryOpArgs, #[error("Cannot apply math function to type")] InvalidMathArg, - #[error("Splat/swizzle type is not registered")] - DestinationTypeNotFound, + #[error("Splat is defined only on scalar values")] + SplatScalarOnly, + #[error("Can only swizzle vector constants")] + SwizzleVectorOnly, #[error("Not implemented: {0}")] NotImplemented(String), } @@ -81,14 +83,19 @@ impl<'a> ConstantSolver<'a> { let ty = match self.constants[value_constant].inner { ConstantInner::Scalar { ref value, width } => { let kind = value.scalar_kind(); - self.types - .fetch_if(|t| t.inner == crate::TypeInner::Vector { size, kind, width }) + self.types.fetch_or_append( + Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }, + span, + ) + } + ConstantInner::Composite { .. } => { + return Err(ConstantSolvingError::SplatScalarOnly); } - ConstantInner::Composite { .. } => None, }; - //TODO: register the new type if needed - let ty = ty.ok_or(ConstantSolvingError::DestinationTypeNotFound)?; Ok(self.constants.fetch_or_append( Constant { name: None, @@ -108,7 +115,9 @@ impl<'a> ConstantSolver<'a> { } => { let src_constant = self.solve(src_vector)?; let (ty, src_components) = match self.constants[src_constant].inner { - ConstantInner::Scalar { .. } => (None, &[][..]), + ConstantInner::Scalar { .. } => { + return Err(ConstantSolvingError::SwizzleVectorOnly); + } ConstantInner::Composite { ty, components: ref src_components, @@ -118,16 +127,21 @@ impl<'a> ConstantSolver<'a> { kind, width, } => { - let dst_ty = self.types.fetch_if(|t| { - t.inner == crate::TypeInner::Vector { size, kind, width } - }); + let dst_ty = self.types.fetch_or_append( + Type { + name: None, + inner: crate::TypeInner::Vector { size, kind, width }, + }, + span, + ); (dst_ty, &src_components[..]) } - _ => (None, &[][..]), + _ => { + return Err(ConstantSolvingError::SwizzleVectorOnly); + } }, }; - //TODO: register the new type if needed - let ty = ty.ok_or(ConstantSolvingError::DestinationTypeNotFound)?; + let components = pattern .iter() .map(|&sc| src_components[sc as usize]) @@ -604,7 +618,7 @@ mod tests { ); let mut solver = ConstantSolver { - types: &types, + types: &mut types, expressions: &expressions, constants: &mut constants, }; @@ -684,7 +698,7 @@ mod tests { ); let mut solver = ConstantSolver { - types: &Arena::new(), + types: &mut Arena::new(), expressions: &expressions, constants: &mut constants, }; @@ -815,7 +829,7 @@ mod tests { ); let mut solver = ConstantSolver { - types: &types, + types: &mut types, expressions: &expressions, constants: &mut constants, }; diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 803901764..dd0942db9 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -242,7 +242,7 @@ impl Parser { meta: Span, ) -> Result> { let mut solver = ConstantSolver { - types: &self.module.types, + types: &mut self.module.types, expressions: &ctx.expressions, constants: &mut self.module.constants, }; From d026577a913ea4d849995a4a622dca244f872ffa Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 24 Sep 2021 00:37:25 -0700 Subject: [PATCH 1377/2212] Consolidate Handle construction code. --- src/arena.rs | 44 +++++++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index d93a7877a..93cba7c50 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -75,6 +75,21 @@ impl Handle { let index = self.index.get() - 1; index as usize } + + /// Convert a `usize` index into a `Handle`. + fn from_usize(index: usize) -> Self { + use std::convert::TryFrom; + + let handle_index = u32::try_from(index + 1) + .and_then(Index::try_from) + .expect("Failed to insert into UniqueArena. Handle overflows"); + Handle::new(handle_index) + } + + /// Convert a `usize` index into a `Handle`, without range checks. + unsafe fn from_usize_unchecked(index: usize) -> Self { + Handle::new(Index::new_unchecked((index + 1) as u32)) + } } /// A strongly typed range of handles. @@ -174,34 +189,30 @@ impl Arena { /// Returns an iterator over the items stored in this arena, returning both /// the item's handle and a reference to it. pub fn iter(&self) -> impl DoubleEndedIterator, &T)> { - self.data.iter().enumerate().map(|(i, v)| { - let position = i + 1; - let index = unsafe { Index::new_unchecked(position as u32) }; - (Handle::new(index), v) - }) + self.data + .iter() + .enumerate() + .map(|(i, v)| unsafe { (Handle::from_usize_unchecked(i), v) }) } /// Returns a iterator over the items stored in this arena, /// returning both the item's handle and a mutable reference to it. pub fn iter_mut(&mut self) -> impl DoubleEndedIterator, &mut T)> { - self.data.iter_mut().enumerate().map(|(i, v)| { - let position = i + 1; - let index = unsafe { Index::new_unchecked(position as u32) }; - (Handle::new(index), v) - }) + self.data + .iter_mut() + .enumerate() + .map(|(i, v)| unsafe { (Handle::from_usize_unchecked(i), v) }) } /// Adds a new value to the arena, returning a typed handle. pub fn append(&mut self, value: T, span: Span) -> Handle { #[cfg(not(feature = "span"))] let _ = span; - let position = self.data.len() + 1; - let index = - Index::new(position as u32).expect("Failed to append to Arena. Handle overflows"); + let index = self.data.len(); self.data.push(value); #[cfg(feature = "span")] self.span_info.push(span); - Handle::new(index) + Handle::from_usize(index) } /// Fetch a handle to an existing type. @@ -209,7 +220,7 @@ impl Arena { self.data .iter() .position(fun) - .map(|index| Handle::new(unsafe { Index::new_unchecked((index + 1) as u32) })) + .map(|index| unsafe { Handle::from_usize_unchecked(index) }) } /// Adds a value with a custom check for uniqueness: @@ -223,8 +234,7 @@ impl Arena { fun: F, ) -> Handle { if let Some(index) = self.data.iter().position(|d| fun(d, &value)) { - let index = unsafe { Index::new_unchecked((index + 1) as u32) }; - Handle::new(index) + unsafe { Handle::from_usize_unchecked(index) } } else { self.append(value, span) } From 944a693ae5aec702d58d321b809762818f6bca7a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 17 Sep 2021 16:22:29 -0700 Subject: [PATCH 1378/2212] Use `UniqueArena` for types. Ensure that each distinct type occurs only once in `Module::types`, so that we can use `Eq` on `Type` or `TypeInner` for type equivalence, without being confused by differing `Handle` values that point to identical types. This removes a number of duplicate types from the ir snapshots. Fixes #1385. --- Cargo.toml | 5 +- src/arena.rs | 195 ++++++++++++++++++- src/back/msl/writer.rs | 4 +- src/back/spv/helpers.rs | 4 +- src/back/spv/writer.rs | 6 +- src/front/glsl/constants.rs | 18 +- src/front/glsl/functions.rs | 2 +- src/front/glsl/offset.rs | 4 +- src/front/glsl/parser/declarations.rs | 2 +- src/front/glsl/parser/types.rs | 2 +- src/front/mod.rs | 4 +- src/front/spv/function.rs | 2 +- src/front/spv/image.rs | 24 +-- src/front/spv/mod.rs | 32 ++-- src/front/spv/null.rs | 20 +- src/front/wgsl/mod.rs | 34 ++-- src/lib.rs | 21 +- src/proc/layouter.rs | 4 +- src/proc/typifier.rs | 10 +- src/span.rs | 2 +- src/valid/analyzer.rs | 4 +- src/valid/compose.rs | 4 +- src/valid/expression.rs | 4 +- src/valid/function.rs | 6 +- src/valid/interface.rs | 6 +- src/valid/mod.rs | 4 +- src/valid/type.rs | 4 +- tests/out/analysis/shadow.info.ron | 60 +++--- tests/out/glsl/quad-vert.main.Vertex.glsl | 4 +- tests/out/hlsl/quad-vert.hlsl | 12 +- tests/out/ir/shadow.ron | 223 ++-------------------- tests/out/msl/quad-vert.msl | 24 +-- 32 files changed, 387 insertions(+), 363 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 935ece3f9..8d577643d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ bitflags = "1" bit-set = "0.5" codespan-reporting = { version = "0.11.0", optional = true } fxhash = "0.2" +indexmap = "1.6" # 1.7 has MSRV 1.49 log = "0.4" num-traits = "0.2" spirv = { version = "0.2", optional = true } @@ -36,8 +37,8 @@ glsl-in = ["pp-rs"] glsl-validate = [] glsl-out = ["petgraph"] msl-out = [] -serialize = ["serde"] -deserialize = ["serde"] +serialize = ["serde", "indexmap/serde-1"] +deserialize = ["serde", "indexmap/serde-1"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] wgsl-in = ["codespan-reporting", "hexf-parse"] diff --git a/src/arena.rs b/src/arena.rs index 93cba7c50..ed1aa3e0b 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -6,8 +6,11 @@ use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32, ops}; type Index = NonZeroU32; use crate::Span; +use indexmap::set::IndexSet; /// A strongly typed reference to an arena item. +/// +/// A `Handle` value can be used as an index into an [`Arena`] or [`UniqueArena`]. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[cfg_attr( @@ -81,7 +84,8 @@ impl Handle { use std::convert::TryFrom; let handle_index = u32::try_from(index + 1) - .and_then(Index::try_from) + .ok() + .and_then(Index::new) .expect("Failed to insert into UniqueArena. Handle overflows"); Handle::new(handle_index) } @@ -369,3 +373,192 @@ mod tests { assert!(arena[t1] != arena[t2]); } } + +/// An arena whose elements are guaranteed to be unique. +/// +/// A `UniqueArena` holds a set of unique values of type `T`, each with an +/// associated [`Span`]. Inserting a value returns a `Handle`, which can be +/// used to index the `UniqueArena` and obtain shared access to the `T` element. +/// Access via a `Handle` is an array lookup - no hash lookup is necessary. +/// +/// The element type must implement `Eq` and `Hash`. Insertions of equivalent +/// elements, according to `Eq`, all return the same `Handle`. +/// +/// Once inserted, elements may not be mutated. +/// +/// `UniqueArena` is similar to [`Arena`]: If `Arena` is vector-like, +/// `UniqueArena` is `HashSet`-like. +pub struct UniqueArena { + set: IndexSet, + + /// Spans for the elements, indexed by handle. + /// + /// The length of this vector is always equal to `set.len()`. `IndexSet` + /// promises that its elements "are indexed in a compact range, without + /// holes in the range 0..set.len()", so we can always use the indices + /// returned by insertion as indices into this vector. + #[cfg(feature = "span")] + span_info: Vec, +} + +impl UniqueArena { + /// Create a new arena with no initial capacity allocated. + pub fn new() -> Self { + UniqueArena { + set: IndexSet::new(), + #[cfg(feature = "span")] + span_info: Vec::new(), + } + } + + /// Return the current number of items stored in this arena. + pub fn len(&self) -> usize { + self.set.len() + } + + /// Return `true` if the arena contains no elements. + pub fn is_empty(&self) -> bool { + self.set.is_empty() + } + + /// Clears the arena, keeping all allocations. + pub fn clear(&mut self) { + self.set.clear(); + #[cfg(feature = "span")] + self.span_info.clear(); + } + + /// Return the span associated with `handle`. + /// + /// If a value has been inserted multiple times, the span returned is the + /// one provided with the first insertion. + /// + /// If the `span` feature is not enabled, always return `Span::default`. + /// This can be detected with [`Span::is_defined`]. + pub fn get_span(&self, handle: Handle) -> Span { + #[cfg(feature = "span")] + { + *self + .span_info + .get(handle.index()) + .unwrap_or(&Span::default()) + } + #[cfg(not(feature = "span"))] + { + let _ = handle; + Span::default() + } + } +} + +impl UniqueArena { + /// Returns an iterator over the items stored in this arena, returning both + /// the item's handle and a reference to it. + pub fn iter(&self) -> impl DoubleEndedIterator, &T)> { + self.set.iter().enumerate().map(|(i, v)| { + let position = i + 1; + let index = unsafe { Index::new_unchecked(position as u32) }; + (Handle::new(index), v) + }) + } + + /// Insert a new value into the arena. + /// + /// Return a [`Handle`], which can be used to index this arena to get a + /// shared reference to the element. + /// + /// If this arena already contains an element that is `Eq` to `value`, + /// return a `Handle` to the existing element, and drop `value`. + /// + /// When the `span` feature is enabled, if `value` is inserted into the + /// arena, associate `span` with it. An element's span can be retrieved with + /// the [`get_span`] method. + /// + /// [`Handle`]: Handle + /// [`get_span`]: UniqueArena::get_span + pub fn fetch_or_append(&mut self, value: T, span: Span) -> Handle { + let (index, added) = self.set.insert_full(value); + + #[cfg(feature = "span")] + { + if added { + debug_assert!(index == self.span_info.len()); + self.span_info.push(span); + } + + debug_assert!(self.set.len() == self.span_info.len()); + } + + Handle::from_usize(index) + } + + /// Return this arena's handle for `value`, if present. + /// + /// If this arena already contains an element equal to `value`, + /// return its handle. Otherwise, return `None`. + pub fn get(&self, value: &T) -> Option> { + self.set + .get_index_of(value) + .map(|index| unsafe { Handle::from_usize_unchecked(index) }) + } + + /// Return this arena's value at `handle`, if that is a valid handle. + pub fn try_get(&self, handle: Handle) -> Option<&T> { + self.set.get_index(handle.index()) + } +} + +impl Default for UniqueArena { + fn default() -> Self { + Self::new() + } +} + +impl fmt::Debug for UniqueArena { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_map().entries(self.iter()).finish() + } +} + +impl ops::Index> for UniqueArena { + type Output = T; + fn index(&self, handle: Handle) -> &T { + &self.set[handle.index()] + } +} + +#[cfg(feature = "serialize")] +impl serde::Serialize for UniqueArena +where + T: Eq + hash::Hash, + T: serde::Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + self.set.serialize(serializer) + } +} + +#[cfg(feature = "deserialize")] +impl<'de, T> serde::Deserialize<'de> for UniqueArena +where + T: Eq + hash::Hash, + T: serde::Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let set = IndexSet::deserialize(deserializer)?; + #[cfg(feature = "span")] + let span_info = std::iter::repeat(Span::default()).take(set.len()).collect(); + + Ok(Self { + set, + #[cfg(feature = "span")] + span_info, + }) + } +} diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0bf159e54..8f0368908 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -22,7 +22,7 @@ const ATOMIC_REFERENCE: &str = "&"; struct TypeContext<'a> { handle: Handle, - arena: &'a crate::Arena, + arena: &'a crate::UniqueArena, names: &'a FastHashMap, access: crate::StorageAccess, first_time: bool, @@ -354,7 +354,7 @@ fn should_pack_struct_member( } } -fn needs_array_length(ty: Handle, arena: &crate::Arena) -> bool { +fn needs_array_length(ty: Handle, arena: &crate::UniqueArena) -> bool { if let crate::TypeInner::Struct { ref members, .. } = arena[ty].inner { if let Some(member) = members.last() { if let crate::TypeInner::Array { diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index fe8fbaf75..aa7952ad2 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -1,4 +1,4 @@ -use crate::{Arena, Handle}; +use crate::{Handle, UniqueArena}; use spirv::Word; pub(super) fn bytes_to_words(bytes: &[u8]) -> Vec { @@ -35,7 +35,7 @@ pub(super) fn map_storage_class(class: crate::StorageClass) -> spirv::StorageCla pub(super) fn contains_builtin( binding: Option<&crate::Binding>, ty: Handle, - arena: &Arena, + arena: &UniqueArena, built_in: crate::BuiltIn, ) -> bool { if let Some(&crate::Binding::BuiltIn(bi)) = binding { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index c9d62f50b..dfe088cd6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -6,7 +6,7 @@ use super::{ PipelineOptions, ResultMember, Writer, WriterFlags, BITS_PER_BYTE, }; use crate::{ - arena::{Arena, Handle}, + arena::{Handle, UniqueArena}, proc::TypeResolution, valid::{FunctionInfo, ModuleInfo}, }; @@ -195,7 +195,7 @@ impl Writer { pub(super) fn get_pointer_id( &mut self, - arena: &Arena, + arena: &UniqueArena, handle: Handle, class: spirv::StorageClass, ) -> Result { @@ -766,7 +766,7 @@ impl Writer { fn write_type_declaration_arena( &mut self, - arena: &Arena, + arena: &UniqueArena, handle: Handle, ) -> Result { let ty = &arena[handle]; diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index e39a59621..1584e9b52 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -1,12 +1,12 @@ use crate::{ - arena::{Arena, Handle}, + arena::{Arena, Handle, UniqueArena}, BinaryOperator, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, TypeInner, UnaryOperator, }; #[derive(Debug)] pub struct ConstantSolver<'a> { - pub types: &'a mut Arena, + pub types: &'a mut UniqueArena, pub expressions: &'a Arena, pub constants: &'a mut Arena, } @@ -531,18 +531,18 @@ mod tests { use crate::{ Arena, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, TypeInner, - UnaryOperator, VectorSize, + UnaryOperator, UniqueArena, VectorSize, }; use super::ConstantSolver; #[test] fn unary_op() { - let mut types = Arena::new(); + let mut types = UniqueArena::new(); let mut expressions = Arena::new(); let mut constants = Arena::new(); - let vec_ty = types.append( + let vec_ty = types.fetch_or_append( Type { name: None, inner: TypeInner::Vector { @@ -698,7 +698,7 @@ mod tests { ); let mut solver = ConstantSolver { - types: &mut Arena::new(), + types: &mut UniqueArena::new(), expressions: &expressions, constants: &mut constants, }; @@ -716,11 +716,11 @@ mod tests { #[test] fn access() { - let mut types = Arena::new(); + let mut types = UniqueArena::new(); let mut expressions = Arena::new(); let mut constants = Arena::new(); - let matrix_ty = types.append( + let matrix_ty = types.fetch_or_append( Type { name: None, inner: TypeInner::Matrix { @@ -732,7 +732,7 @@ mod tests { Default::default(), ); - let vec_ty = types.append( + let vec_ty = types.fetch_or_append( Type { name: None, inner: TypeInner::Vector { diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index f080c2d48..e46ababac 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -900,7 +900,7 @@ impl Parser { } let (ty, value) = if !components.is_empty() { - let ty = self.module.types.append( + let ty = self.module.types.fetch_or_append( Type { name: None, inner: TypeInner::Struct { diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 088480232..01c2edd15 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -13,7 +13,7 @@ use super::{ error::{Error, ErrorKind}, Span, }; -use crate::{front::align_up, Arena, Constant, Handle, Type, TypeInner}; +use crate::{front::align_up, Arena, Constant, Handle, Type, TypeInner, UniqueArena}; /// Struct with information needed for defining a struct member. /// @@ -39,7 +39,7 @@ pub fn calculate_offset( mut ty: Handle, meta: Span, layout: StructLayout, - types: &mut Arena, + types: &mut UniqueArena, constants: &Arena, errors: &mut Vec, ) -> TypeAlignSpan { diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 47506c060..8ef71ef28 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -497,7 +497,7 @@ impl<'source> ParsingContext<'source> { let span = self.parse_struct_declaration_list(parser, &mut members, layout)?; self.expect(parser, TokenValue::RightBrace)?; - let mut ty = parser.module.types.append( + let mut ty = parser.module.types.fetch_or_append( Type { name: Some(ty_name), inner: TypeInner::Struct { diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index c056c1395..3dc00c33f 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -47,7 +47,7 @@ impl<'source> ParsingContext<'source> { self.parse_struct_declaration_list(parser, &mut members, StructLayout::Std140)?; let end_meta = self.expect(parser, TokenValue::RightBrace)?.meta; meta.subsume(end_meta); - let ty = parser.module.types.append( + let ty = parser.module.types.fetch_or_append( Type { name: Some(ty_name.clone()), inner: TypeInner::Struct { diff --git a/src/front/mod.rs b/src/front/mod.rs index 56e000d62..3264f0c35 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -10,7 +10,7 @@ pub mod spv; pub mod wgsl; use crate::{ - arena::{Arena, Handle}, + arena::{Arena, Handle, UniqueArena}, proc::{ResolveContext, ResolveError, TypeResolution}, }; use std::ops; @@ -81,7 +81,7 @@ impl Typifier { pub fn get<'a>( &'a self, expr_handle: Handle, - types: &'a Arena, + types: &'a UniqueArena, ) -> &'a crate::TypeInner { self.resolutions[expr_handle.index()].inner_with(types) } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 0ce8e7686..0c45aca71 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -477,7 +477,7 @@ impl> super::Parser { let span = crate::Span::total_span( components.iter().map(|h| function.expressions.get_span(*h)), ); - let ty = module.types.append( + let ty = module.types.fetch_or_append( crate::Type { name: None, inner: crate::TypeInner::Struct { diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index b46fcbce1..c58fe370f 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -1,5 +1,5 @@ use crate::{ - arena::{Arena, Handle}, + arena::{Arena, Handle, UniqueArena}, FunctionArgument, }; @@ -62,7 +62,7 @@ fn extract_image_coordinates( extra_coordinate: ExtraCoordinate, base: Handle, coordinate_ty: Handle, - type_arena: &Arena, + type_arena: &UniqueArena, expressions: &mut Arena, ) -> (Handle, Option>) { let (given_size, kind) = match type_arena[coordinate_ty].inner { @@ -74,13 +74,13 @@ fn extract_image_coordinates( let required_size = image_dim.required_coordinate_size(); let required_ty = required_size.map(|size| { type_arena - .fetch_if(|ty| { - ty.inner - == crate::TypeInner::Vector { - size, - kind, - width: 4, - } + .get(&crate::Type { + name: None, + inner: crate::TypeInner::Vector { + size, + kind, + width: 4, + }, }) .expect("Required coordinate type should have been set up by `parse_type_image`!") }); @@ -184,7 +184,7 @@ fn extract_image_coordinates( pub(super) fn patch_comparison_type( flags: SamplingFlags, var: &mut crate::GlobalVariable, - arena: &mut Arena, + arena: &mut UniqueArena, ) -> bool { if !flags.contains(SamplingFlags::COMPARISON) { return true; @@ -211,7 +211,7 @@ pub(super) fn patch_comparison_type( }; let name = original_ty.name.clone(); - var.ty = arena.append( + var.ty = arena.fetch_or_append( crate::Type { name, inner: ty_inner, @@ -257,7 +257,7 @@ impl> super::Parser { pub(super) fn parse_image_write( &mut self, words_left: u16, - type_arena: &Arena, + type_arena: &UniqueArena, global_arena: &Arena, arguments: &[FunctionArgument], expressions: &mut Arena, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 34b510d35..09c5103b2 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -35,7 +35,7 @@ pub use error::Error; use function::*; use crate::{ - arena::{Arena, Handle}, + arena::{Arena, Handle, UniqueArena}, proc::Layouter, FastHashMap, }; @@ -495,7 +495,7 @@ struct BlockContext<'function> { /// Constants arena of the module being processed const_arena: &'function mut Arena, /// Type arena of the module being processed - type_arena: &'function Arena, + type_arena: &'function UniqueArena, /// Global arena of the module being processed global_arena: &'function Arena, /// Arguments of the function currently being processed @@ -991,7 +991,7 @@ impl> Parser { root_type_id: spirv::Word, object_expr: Handle, selections: &[spirv::Word], - type_arena: &Arena, + type_arena: &UniqueArena, expressions: &mut Arena, span: crate::Span, ) -> Result, Error> { @@ -3388,7 +3388,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append( + handle: module.types.fetch_or_append( crate::Type { name: self.future_decor.remove(&id).and_then(|dec| dec.name), inner, @@ -3423,7 +3423,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append( + handle: module.types.fetch_or_append( crate::Type { name: self.future_decor.remove(&id).and_then(|dec| dec.name), inner, @@ -3453,7 +3453,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append( + handle: module.types.fetch_or_append( crate::Type { name: self.future_decor.remove(&id).and_then(|dec| dec.name), inner, @@ -3490,7 +3490,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append( + handle: module.types.fetch_or_append( crate::Type { name: self.future_decor.remove(&id).and_then(|dec| dec.name), inner, @@ -3529,7 +3529,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append( + handle: module.types.fetch_or_append( crate::Type { name: decor.and_then(|dec| dec.name), inner, @@ -3593,7 +3593,7 @@ impl> Parser { base_lookup_ty.clone() } else { LookupType { - handle: module.types.append( + handle: module.types.fetch_or_append( crate::Type { name: decor.and_then(|dec| dec.name), inner: crate::TypeInner::Pointer { @@ -3636,7 +3636,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append( + handle: module.types.fetch_or_append( crate::Type { name: decor.name, inner, @@ -3673,7 +3673,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.append( + handle: module.types.fetch_or_append( crate::Type { name: decor.name, inner, @@ -3777,7 +3777,7 @@ impl> Parser { members, }; - let ty_handle = module.types.append( + let ty_handle = module.types.fetch_or_append( crate::Type { name: parent_decor.and_then(|dec| dec.name), inner, @@ -3862,7 +3862,7 @@ impl> Parser { arrayed: is_array, }; - let handle = module.types.append( + let handle = module.types.fetch_or_append( crate::Type { name: decor.name, inner, @@ -3905,7 +3905,7 @@ impl> Parser { inst.expect(2)?; let id = self.next()?; let decor = self.future_decor.remove(&id).unwrap_or_default(); - let handle = module.types.append( + let handle = module.types.fetch_or_append( crate::Type { name: decor.name, inner: crate::TypeInner::Sampler { comparison: false }, @@ -4051,7 +4051,7 @@ impl> Parser { fn parse_null_constant( &mut self, inst: Instruction, - types: &Arena, + types: &UniqueArena, constants: &mut Arena, ) -> Result<(u32, u32, Handle), Error> { let start = self.data_offset; @@ -4151,7 +4151,7 @@ impl> Parser { class: crate::ImageClass::Storage { format, access }, }, }; - effective_ty = module.types.append(ty, Default::default()); + effective_ty = module.types.fetch_or_append(ty, Default::default()); } let ext_class = match self.lookup_storage_buffer_types.get(&effective_ty) { diff --git a/src/front/spv/null.rs b/src/front/spv/null.rs index b6c8ca33c..5d40dfa91 100644 --- a/src/front/spv/null.rs +++ b/src/front/spv/null.rs @@ -1,5 +1,5 @@ use super::Error; -use crate::arena::{Arena, Handle}; +use crate::arena::{Arena, Handle, UniqueArena}; fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { crate::ConstantInner::Scalar { @@ -15,7 +15,7 @@ fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::Con pub fn generate_null_constant( ty: Handle, - type_arena: &Arena, + type_arena: &UniqueArena, constant_arena: &mut Arena, span: crate::Span, ) -> Result { @@ -42,13 +42,13 @@ pub fn generate_null_constant( } => { // If we successfully declared a matrix type, we have declared a vector type for it too. let vector_ty = type_arena - .fetch_if(|t| { - t.inner - == crate::TypeInner::Vector { - kind: crate::ScalarKind::Float, - size: rows, - width, - } + .get(&crate::Type { + name: None, + inner: crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + size: rows, + width, + }, }) .unwrap(); let vector_inner = generate_null_constant(vector_ty, type_arena, constant_arena, span)?; @@ -116,7 +116,7 @@ pub fn generate_null_constant( pub fn generate_default_built_in( built_in: Option, ty: Handle, - type_arena: &Arena, + type_arena: &UniqueArena, constant_arena: &mut Arena, span: crate::Span, ) -> Result, Error> { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 09c66bb63..b665ce1e1 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -9,7 +9,7 @@ mod number_literals; mod tests; use crate::{ - arena::{Arena, Handle}, + arena::{Arena, Handle, UniqueArena}, proc::{ ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution, }, @@ -486,7 +486,11 @@ impl crate::TypeInner { /// For example `vec3`. /// /// Note: The names of a `TypeInner::Struct` is not known. Therefore this method will simply return "struct" for them. - fn to_wgsl(&self, types: &Arena, constants: &Arena) -> String { + fn to_wgsl( + &self, + types: &UniqueArena, + constants: &Arena, + ) -> String { use crate::TypeInner as Ti; match *self { @@ -584,7 +588,7 @@ impl crate::TypeInner { mod type_inner_tests { #[test] fn to_wgsl() { - let mut types = crate::Arena::new(); + let mut types = crate::UniqueArena::new(); let mut constants = crate::Arena::new(); let c = constants.append( crate::Constant { @@ -598,7 +602,7 @@ mod type_inner_tests { Default::default(), ); - let mytype1 = types.append( + let mytype1 = types.fetch_or_append( crate::Type { name: Some("MyType1".to_string()), inner: crate::TypeInner::Struct { @@ -609,7 +613,7 @@ mod type_inner_tests { }, Default::default(), ); - let mytype2 = types.append( + let mytype2 = types.fetch_or_append( crate::Type { name: Some("MyType2".to_string()), inner: crate::TypeInner::Struct { @@ -707,7 +711,7 @@ struct StatementContext<'input, 'temp, 'out> { variables: &'out mut Arena, expressions: &'out mut Arena, named_expressions: &'out mut FastHashMap, String>, - types: &'out mut Arena, + types: &'out mut UniqueArena, constants: &'out mut Arena, global_vars: &'out Arena, functions: &'out Arena, @@ -763,7 +767,7 @@ struct ExpressionContext<'input, 'temp, 'out> { lookup_ident: &'temp FastHashMap<&'input str, TypedExpression>, typifier: &'temp mut super::Typifier, expressions: &'out mut Arena, - types: &'out mut Arena, + types: &'out mut UniqueArena, constants: &'out mut Arena, global_vars: &'out Arena, local_vars: &'out Arena, @@ -1993,7 +1997,7 @@ impl Parser { first_token_span: TokenSpan<'a>, lexer: &mut Lexer<'a>, register_name: Option<&'a str>, - type_arena: &mut Arena, + type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result, Error<'a>> { self.push_scope(Scope::ConstantExpr, lexer); @@ -2068,7 +2072,7 @@ impl Parser { fn parse_const_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - type_arena: &mut Arena, + type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result, Error<'a>> { self.parse_const_expression_impl(lexer.next(), lexer, None, type_arena, const_arena) @@ -2560,7 +2564,7 @@ impl Parser { fn parse_variable_ident_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - type_arena: &mut Arena, + type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result<(&'a str, Span, Handle, crate::StorageAccess), Error<'a>> { let (name, name_span) = lexer.next_ident_with_span()?; @@ -2572,7 +2576,7 @@ impl Parser { fn parse_variable_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - type_arena: &mut Arena, + type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result, Error<'a>> { self.push_scope(Scope::VariableDecl, lexer); @@ -2624,7 +2628,7 @@ impl Parser { fn parse_struct_body<'a>( &mut self, lexer: &mut Lexer<'a>, - type_arena: &mut Arena, + type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result<(Vec, u32), Error<'a>> { let mut offset = 0; @@ -2722,7 +2726,7 @@ impl Parser { lexer: &mut Lexer<'a>, attribute: TypeAttributes, word: &'a str, - type_arena: &mut Arena, + type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result, Error<'a>> { if let Some((kind, width)) = conv::get_scalar_type(word) { @@ -3034,7 +3038,7 @@ impl Parser { name_span: Span, debug_name: Option<&'a str>, attribute: TypeAttributes, - type_arena: &mut Arena, + type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result, Error<'a>> { Ok(match self.lookup_type.get(name) { @@ -3061,7 +3065,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, debug_name: Option<&'a str>, - type_arena: &mut Arena, + type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result<(Handle, crate::StorageAccess), Error<'a>> { self.push_scope(Scope::TypeDecl, lexer); diff --git a/src/lib.rs b/src/lib.rs index afc93094d..bc0681d9f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,6 +44,15 @@ and compound expressions refer to their sub-expressions via `Handle` values. (When examining the serialized form of a `Module`, note that the first element of an `Arena` has an index of 1, not 0.) +A [`UniqueArena`] is just like an `Arena`, except that it stores only a single +instance of each value. The value type must implement `Eq` and `Hash`. Like an +`Arena`, inserting a value into a `UniqueArena` returns a `Handle` which can be +used to efficiently access the value, without a hash lookup. Inserting a value +multiple times returns the same `Handle`. + +If the `span` feature is enabled, both `Arena` and `UniqueArena` can associate a +source code span with each element. + ## Function Calls Naga's representation of function calls is unusual. Most languages treat @@ -203,7 +212,7 @@ pub mod proc; mod span; pub mod valid; -pub use crate::arena::{Arena, Handle, Range}; +pub use crate::arena::{Arena, Handle, Range, UniqueArena}; use std::{ collections::{HashMap, HashSet}, @@ -412,7 +421,7 @@ pub enum Sampling { /// Member of a user-defined structure. // Clone is used only for error reporting and is not intended for end users -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct StructMember { @@ -531,7 +540,7 @@ pub enum ImageClass { } /// A data type declared in the module. -#[derive(Debug, PartialEq)] +#[derive(Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct Type { @@ -542,7 +551,7 @@ pub struct Type { } /// Enum with additional information, depending on the kind of type. -#[derive(Debug, PartialEq)] +#[derive(Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum TypeInner { @@ -704,7 +713,7 @@ pub enum ConstantInner { } /// Describes how an input/output variable is to be bound. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Hash)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum Binding { @@ -1552,7 +1561,7 @@ pub struct EntryPoint { #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct Module { /// Storage for the types defined in this module. - pub types: Arena, + pub types: UniqueArena, /// Storage for the constants defined in this module. pub constants: Arena, /// Storage for the global variables defined in this module. diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index f2921f15e..5facecdac 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -1,4 +1,4 @@ -use crate::arena::{Arena, Handle}; +use crate::arena::{Arena, Handle, UniqueArena}; use std::{num::NonZeroU32, ops}; pub type Alignment = NonZeroU32; @@ -64,7 +64,7 @@ impl Layouter { pub fn update( &mut self, - types: &Arena, + types: &UniqueArena, constants: &Arena, ) -> Result<(), InvalidBaseType> { use crate::TypeInner as Ti; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 0e7171b87..9bca13e48 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -1,4 +1,4 @@ -use crate::arena::{Arena, Handle}; +use crate::arena::{Arena, Handle, UniqueArena}; use thiserror::Error; @@ -10,8 +10,8 @@ use thiserror::Error; /// You might expect such a function to simply return a `Handle`. However, /// we want type resolution to be a read-only process, and that would limit the /// possible results to types already present in the expression's associated -/// `Arena`. Naga IR does have certain expressions whose types are not -/// certain to be present. +/// `UniqueArena`. Naga IR does have certain expressions whose types are +/// not certain to be present. /// /// So instead, type resolution returns a `TypeResolution` enum: either a /// [`Handle`], referencing some type in the arena, or a [`Value`], holding a @@ -104,7 +104,7 @@ impl TypeResolution { } } - pub fn inner_with<'a>(&'a self, arena: &'a Arena) -> &'a crate::TypeInner { + pub fn inner_with<'a>(&'a self, arena: &'a UniqueArena) -> &'a crate::TypeInner { match *self { Self::Handle(handle) => &arena[handle].inner, Self::Value(ref inner) => inner, @@ -197,7 +197,7 @@ pub enum ResolveError { pub struct ResolveContext<'a> { pub constants: &'a Arena, - pub types: &'a Arena, + pub types: &'a UniqueArena, pub global_vars: &'a Arena, pub local_vars: &'a Arena, pub functions: &'a Arena, diff --git a/src/span.rs b/src/span.rs index 2324b5b8b..3eaadd212 100644 --- a/src/span.rs +++ b/src/span.rs @@ -53,7 +53,7 @@ impl Span { } /// Check wether `self` was defined or is a default/unknown span - fn is_defined(&self) -> bool { + pub fn is_defined(&self) -> bool { *self != Self::default() } } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index dc9e29166..3045defef 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -869,8 +869,8 @@ fn uniform_control_flow() { }, Default::default(), ); - let mut type_arena = Arena::new(); - let ty = type_arena.append( + let mut type_arena = crate::UniqueArena::new(); + let ty = type_arena.fetch_or_append( crate::Type { name: None, inner: crate::TypeInner::Vector { diff --git a/src/valid/compose.rs b/src/valid/compose.rs index e25a7379d..378f22faa 100644 --- a/src/valid/compose.rs +++ b/src/valid/compose.rs @@ -1,5 +1,5 @@ use crate::{ - arena::{Arena, Handle}, + arena::{Arena, Handle, UniqueArena}, proc::TypeResolution, }; @@ -19,7 +19,7 @@ pub enum ComposeError { pub fn validate_compose( self_ty_handle: Handle, constant_arena: &Arena, - type_arena: &Arena, + type_arena: &UniqueArena, component_resolutions: impl ExactSizeIterator, ) -> Result<(), ComposeError> { use crate::TypeInner as Ti; diff --git a/src/valid/expression.rs b/src/valid/expression.rs index e3e189453..56a464f9c 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,6 +1,6 @@ use super::{compose::validate_compose, ComposeError, FunctionInfo, ShaderStages, TypeFlags}; use crate::{ - arena::{Arena, Handle}, + arena::{Handle, UniqueArena}, proc::{ProcError, ResolveError}, }; @@ -113,7 +113,7 @@ pub enum ExpressionError { struct ExpressionTypeResolver<'a> { root: Handle, - types: &'a Arena, + types: &'a UniqueArena, info: &'a FunctionInfo, } diff --git a/src/valid/function.rs b/src/valid/function.rs index ddfcb60bb..79917722b 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -2,7 +2,7 @@ use super::{ analyzer::{UniformityDisruptor, UniformityRequirements}, ExpressionError, FunctionInfo, ModuleInfo, ShaderStages, TypeFlags, ValidationFlags, }; -use crate::arena::{Arena, Handle}; +use crate::arena::{Arena, Handle, UniqueArena}; use bit_set::BitSet; #[derive(Clone, Debug, thiserror::Error)] @@ -144,7 +144,7 @@ struct BlockContext<'a> { abilities: ControlFlowAbility, info: &'a FunctionInfo, expressions: &'a Arena, - types: &'a Arena, + types: &'a UniqueArena, global_vars: &'a Arena, functions: &'a Arena, prev_infos: &'a [FunctionInfo], @@ -627,7 +627,7 @@ impl super::Validator { fn validate_local_var( &self, var: &crate::LocalVariable, - types: &Arena, + types: &UniqueArena, constants: &Arena, ) -> Result<(), LocalVariableError> { log::debug!("var {:?}", var); diff --git a/src/valid/interface.rs b/src/valid/interface.rs index ff3f2401c..eb2465617 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -3,7 +3,7 @@ use super::{ Capabilities, Disalignment, FunctionError, ModuleInfo, ShaderStages, TypeFlags, ValidationFlags, }; -use crate::arena::{Arena, Handle}; +use crate::arena::{Handle, UniqueArena}; use bit_set::BitSet; @@ -93,7 +93,7 @@ struct VaryingContext<'a> { ty: Handle, stage: crate::ShaderStage, output: bool, - types: &'a Arena, + types: &'a UniqueArena, location_mask: &'a mut BitSet, built_in_mask: u32, capabilities: Capabilities, @@ -320,7 +320,7 @@ impl super::Validator { pub(super) fn validate_global_var( &self, var: &crate::GlobalVariable, - types: &Arena, + types: &UniqueArena, ) -> Result<(), GlobalVariableError> { log::debug!("var {:?}", var); let type_info = &self.types[var.ty.index()]; diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 5441fb2ef..3278d6ce1 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -6,7 +6,7 @@ mod interface; mod r#type; use crate::{ - arena::{Arena, Handle}, + arena::{Arena, Handle, UniqueArena}, proc::{InvalidBaseType, Layouter}, FastHashSet, }; @@ -217,7 +217,7 @@ impl Validator { &self, handle: Handle, constants: &Arena, - types: &Arena, + types: &UniqueArena, ) -> Result<(), ConstantError> { let con = &constants[handle]; match con.inner { diff --git a/src/valid/type.rs b/src/valid/type.rs index ef1cc7e72..540818ca2 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -1,6 +1,6 @@ use super::Capabilities; use crate::{ - arena::{Arena, Handle}, + arena::{Arena, Handle, UniqueArena}, proc::Alignment, }; @@ -187,7 +187,7 @@ impl super::Validator { pub(super) fn validate_type( &self, handle: Handle, - types: &Arena, + types: &UniqueArena, constants: &Arena, ) -> Result { use crate::TypeInner as Ti; diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index f5695163b..07bb11eeb 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -54,7 +54,7 @@ ref_count: 0, assignable_global: Some(3), ty: Value(Pointer( - base: 14, + base: 13, class: Uniform, )), ), @@ -95,7 +95,7 @@ ), ref_count: 1, assignable_global: Some(1), - ty: Handle(56), + ty: Handle(30), ), ( uniformity: ( @@ -106,7 +106,7 @@ ), ref_count: 1, assignable_global: Some(2), - ty: Handle(57), + ty: Handle(31), ), ( uniformity: ( @@ -118,7 +118,7 @@ ref_count: 0, assignable_global: Some(4), ty: Value(Pointer( - base: 21, + base: 20, class: Storage( access: ( bits: 1, @@ -770,7 +770,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), + ty: Handle(6), ), ( uniformity: ( @@ -781,7 +781,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), + ty: Handle(6), ), ( uniformity: ( @@ -792,7 +792,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), + ty: Handle(6), ), ( uniformity: ( @@ -831,7 +831,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), + ty: Handle(6), ), ( uniformity: ( @@ -857,7 +857,7 @@ ), ref_count: 2, assignable_global: None, - ty: Handle(9), + ty: Handle(6), ), ( uniformity: ( @@ -1120,7 +1120,7 @@ ref_count: 1, assignable_global: Some(3), ty: Value(Pointer( - base: 14, + base: 13, class: Uniform, )), ), @@ -1161,7 +1161,7 @@ ), ref_count: 0, assignable_global: Some(1), - ty: Handle(56), + ty: Handle(30), ), ( uniformity: ( @@ -1172,7 +1172,7 @@ ), ref_count: 0, assignable_global: Some(2), - ty: Handle(57), + ty: Handle(31), ), ( uniformity: ( @@ -1184,7 +1184,7 @@ ref_count: 7, assignable_global: Some(4), ty: Value(Pointer( - base: 21, + base: 20, class: Storage( access: ( bits: 1, @@ -1798,7 +1798,7 @@ ref_count: 1, assignable_global: Some(3), ty: Value(Pointer( - base: 13, + base: 12, class: Uniform, )), ), @@ -1892,7 +1892,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 20, + base: 19, class: Storage( access: ( bits: 1, @@ -1921,7 +1921,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 18, class: Storage( access: ( bits: 1, @@ -1939,7 +1939,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 18, + base: 17, class: Storage( access: ( bits: 1, @@ -1956,7 +1956,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(18), + ty: Handle(17), ), ( uniformity: ( @@ -2027,7 +2027,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 20, + base: 19, class: Storage( access: ( bits: 1, @@ -2056,7 +2056,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 18, class: Storage( access: ( bits: 1, @@ -2126,7 +2126,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 20, + base: 19, class: Storage( access: ( bits: 1, @@ -2155,7 +2155,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 18, class: Storage( access: ( bits: 1, @@ -2225,7 +2225,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 20, + base: 19, class: Storage( access: ( bits: 1, @@ -2254,7 +2254,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 18, class: Storage( access: ( bits: 1, @@ -2500,7 +2500,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 20, + base: 19, class: Storage( access: ( bits: 1, @@ -2529,7 +2529,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 18, class: Storage( access: ( bits: 1, @@ -2599,7 +2599,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 20, + base: 19, class: Storage( access: ( bits: 1, @@ -2628,7 +2628,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 18, class: Storage( access: ( bits: 1, @@ -2698,7 +2698,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 20, + base: 19, class: Storage( access: ( bits: 1, @@ -2727,7 +2727,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 18, class: Storage( access: ( bits: 1, diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index e42681b2e..5203c330e 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -3,7 +3,7 @@ precision highp float; precision highp int; -struct type10 { +struct type9 { vec2 member; vec4 gen_gl_Position; float gen_gl_PointSize; @@ -47,7 +47,7 @@ void main() { float _e12 = perVertexStruct.gen_gl_PointSize; float _e13[1] = perVertexStruct.gen_gl_ClipDistance; float _e14[1] = perVertexStruct.gen_gl_CullDistance; - type10 _tmp_return = type10(_e10, _e11, _e12, _e13, _e14); + type9 _tmp_return = type9(_e10, _e11, _e12, _e13, _e14); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index ea6323b5a..261468de1 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -6,7 +6,7 @@ struct gl_PerVertex { float gl_CullDistance[1] : SV_CullDistance; }; -struct type10 { +struct type9 { linear float2 member : LOC0; float4 gl_Position : SV_Position; float gl_PointSize : PSIZE; @@ -36,8 +36,8 @@ void main1() return; } -type10 Constructtype10(float2 arg0, float4 arg1, float arg2, float arg3[1], float arg4[1]) { - type10 ret; +type9 Constructtype9(float2 arg0, float4 arg1, float arg2, float arg3[1], float arg4[1]) { + type9 ret; ret.member = arg0; ret.gl_Position = arg1; ret.gl_PointSize = arg2; @@ -56,7 +56,7 @@ VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0) float _expr12 = perVertexStruct.gl_PointSize; float _expr13[1] = perVertexStruct.gl_ClipDistance; float _expr14[1] = perVertexStruct.gl_CullDistance; - const type10 type10_ = Constructtype10(_expr10, _expr11, _expr12, _expr13, _expr14); - const VertexOutput_main type10_1 = { type10_.member, type10_.gl_Position, type10_.gl_ClipDistance, type10_.gl_CullDistance, type10_.gl_PointSize }; - return type10_1; + const type9 type9_ = Constructtype9(_expr10, _expr11, _expr12, _expr13, _expr14); + const VertexOutput_main type9_1 = { type9_.member, type9_.gl_Position, type9_.gl_ClipDistance, type9_.gl_CullDistance, type9_.gl_PointSize }; + return type9_1; } diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 763aa28e9..4dae9ffae 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -62,14 +62,6 @@ comparison: false, ), ), - ( - name: None, - inner: Vector( - size: Bi, - kind: Float, - width: 4, - ), - ), ( name: None, inner: Scalar( @@ -106,7 +98,7 @@ members: [ ( name: Some("num_lights"), - ty: 13, + ty: 12, binding: None, offset: 0, ), @@ -117,14 +109,14 @@ ( name: None, inner: Pointer( - base: 14, + base: 13, class: Uniform, ), ), ( name: None, inner: Pointer( - base: 13, + base: 12, class: Uniform, ), ), @@ -150,7 +142,7 @@ members: [ ( name: Some("proj"), - ty: 18, + ty: 17, binding: None, offset: 0, ), @@ -173,7 +165,7 @@ ( name: None, inner: Array( - base: 19, + base: 18, size: Dynamic, stride: 96, ), @@ -185,7 +177,7 @@ members: [ ( name: Some("data"), - ty: 20, + ty: 19, binding: None, offset: 0, ), @@ -196,7 +188,7 @@ ( name: None, inner: Pointer( - base: 21, + base: 20, class: Storage( access: ( bits: 0, @@ -204,13 +196,6 @@ ), ), ), - ( - name: None, - inner: Pointer( - base: 20, - class: Uniform, - ), - ), ( name: None, inner: Pointer( @@ -225,6 +210,13 @@ class: Uniform, ), ), + ( + name: None, + inner: Pointer( + base: 17, + class: Uniform, + ), + ), ( name: None, inner: Pointer( @@ -239,76 +231,6 @@ class: Private, ), ), - ( - name: None, - inner: Pointer( - base: 20, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 19, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 4, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 1, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 20, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 19, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 4, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 1, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 20, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 19, - class: Uniform, - ), - ), ( name: None, inner: Pointer( @@ -330,111 +252,6 @@ class: Private, ), ), - ( - name: None, - inner: Pointer( - base: 1, - class: Private, - ), - ), - ( - name: None, - inner: Pointer( - base: 1, - class: Private, - ), - ), - ( - name: None, - inner: Pointer( - base: 20, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 19, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 4, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 1, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 20, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 19, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 4, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 1, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 20, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 19, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 4, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 1, - class: Uniform, - ), - ), - ( - name: None, - inner: Pointer( - base: 4, - class: Private, - ), - ), ( name: None, inner: Image( @@ -778,7 +595,7 @@ group: 0, binding: 2, )), - ty: 56, + ty: 30, init: None, ), ( @@ -788,7 +605,7 @@ group: 0, binding: 3, )), - ty: 57, + ty: 31, init: None, ), ( @@ -798,7 +615,7 @@ group: 0, binding: 0, )), - ty: 14, + ty: 13, init: None, ), ( @@ -812,7 +629,7 @@ group: 0, binding: 1, )), - ty: 21, + ty: 20, init: None, ), ( @@ -924,14 +741,14 @@ index: 1, ), Compose( - ty: 9, + ty: 6, components: [ 51, 52, ], ), Compose( - ty: 9, + ty: 6, components: [ 13, 22, diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index ef2264a13..8caf6fc49 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -2,25 +2,25 @@ #include #include -struct type6 { +struct type5 { float inner[1u]; }; struct gl_PerVertex { metal::float4 gl_Position; float gl_PointSize; - type6 gl_ClipDistance; - type6 gl_CullDistance; + type5 gl_ClipDistance; + type5 gl_CullDistance; }; -struct type10 { +struct type9 { metal::float2 member; metal::float4 gl_Position; float gl_PointSize; - type6 gl_ClipDistance; - type6 gl_CullDistance; + type5 gl_ClipDistance; + type5 gl_CullDistance; }; -constant metal::float4 const_type4_ = {0.0, 0.0, 0.0, 1.0}; -constant type6 const_type6_ = {0.0}; -constant gl_PerVertex const_gl_PerVertex = {const_type4_, 1.0, const_type6_, const_type6_}; +constant metal::float4 const_type3_ = {0.0, 0.0, 0.0, 1.0}; +constant type5 const_type5_ = {0.0}; +constant gl_PerVertex const_gl_PerVertex = {const_type3_, 1.0, const_type5_, const_type5_}; void main2( thread metal::float2& v_uv, @@ -60,8 +60,8 @@ vertex main1Output main1( metal::float2 _e10 = v_uv; metal::float4 _e11 = perVertexStruct.gl_Position; float _e12 = perVertexStruct.gl_PointSize; - type6 _e13 = perVertexStruct.gl_ClipDistance; - type6 _e14 = perVertexStruct.gl_CullDistance; - const auto _tmp = type10 {_e10, _e11, _e12, _e13, _e14}; + type5 _e13 = perVertexStruct.gl_ClipDistance; + type5 _e14 = perVertexStruct.gl_CullDistance; + const auto _tmp = type9 {_e10, _e11, _e12, _e13, _e14}; return main1Output { _tmp.member, _tmp.gl_Position, _tmp.gl_PointSize, {_tmp.gl_ClipDistance.inner[0]} }; } From 6e4401ae964e88a506590cc05049463b96343eec Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 24 Sep 2021 01:25:08 -0700 Subject: [PATCH 1379/2212] Rename `UniqueArena` methods to more closely resemble `HashSet`. `UniqueArena::fetch_or_append` becomes `insert`. `UniqueArena::try_get` becomes `get_handle`, by analogy with `get`, that takes a type as a key. --- src/arena.rs | 4 ++-- src/front/glsl/builtins.rs | 6 +++--- src/front/glsl/constants.rs | 10 +++++----- src/front/glsl/context.rs | 4 ++-- src/front/glsl/functions.rs | 8 ++++---- src/front/glsl/offset.rs | 4 ++-- src/front/glsl/parser/declarations.rs | 2 +- src/front/glsl/parser/expressions.rs | 2 +- src/front/glsl/parser/types.rs | 4 ++-- src/front/glsl/types.rs | 2 +- src/front/glsl/variables.rs | 4 ++-- src/front/spv/function.rs | 2 +- src/front/spv/image.rs | 2 +- src/front/spv/mod.rs | 28 +++++++++++++-------------- src/front/wgsl/mod.rs | 20 +++++++++---------- src/valid/analyzer.rs | 2 +- src/valid/compose.rs | 2 +- src/valid/expression.rs | 2 +- 18 files changed, 53 insertions(+), 55 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index ed1aa3e0b..5e1c65cf7 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -476,7 +476,7 @@ impl UniqueArena { /// /// [`Handle`]: Handle /// [`get_span`]: UniqueArena::get_span - pub fn fetch_or_append(&mut self, value: T, span: Span) -> Handle { + pub fn insert(&mut self, value: T, span: Span) -> Handle { let (index, added) = self.set.insert_full(value); #[cfg(feature = "span")] @@ -503,7 +503,7 @@ impl UniqueArena { } /// Return this arena's value at `handle`, if that is a valid handle. - pub fn try_get(&self, handle: Handle) -> Option<&T> { + pub fn get_handle(&self, handle: Handle) -> Option<&T> { self.set.get_index(handle.index()) } } diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 0c65d5f15..ed678538c 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -16,7 +16,7 @@ impl Module { let mut parameters_info = Vec::with_capacity(args.len()); for arg in args { - parameters.push(self.types.fetch_or_append( + parameters.push(self.types.insert( Type { name: None, inner: arg, @@ -1224,7 +1224,7 @@ fn inject_common_builtin( _ => Some(VectorSize::Quad), }; - let ty = module.types.fetch_or_append( + let ty = module.types.insert( Type { name: None, inner: match size { @@ -1937,7 +1937,7 @@ pub fn sampled_to_depth( arrayed, } => match class { ImageClass::Sampled { multi, .. } => { - *ty = module.types.fetch_or_append( + *ty = module.types.insert( Type { name: None, inner: TypeInner::Image { diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 1584e9b52..e0cce7247 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -83,7 +83,7 @@ impl<'a> ConstantSolver<'a> { let ty = match self.constants[value_constant].inner { ConstantInner::Scalar { ref value, width } => { let kind = value.scalar_kind(); - self.types.fetch_or_append( + self.types.insert( Type { name: None, inner: TypeInner::Vector { size, kind, width }, @@ -127,7 +127,7 @@ impl<'a> ConstantSolver<'a> { kind, width, } => { - let dst_ty = self.types.fetch_or_append( + let dst_ty = self.types.insert( Type { name: None, inner: crate::TypeInner::Vector { size, kind, width }, @@ -542,7 +542,7 @@ mod tests { let mut expressions = Arena::new(); let mut constants = Arena::new(); - let vec_ty = types.fetch_or_append( + let vec_ty = types.insert( Type { name: None, inner: TypeInner::Vector { @@ -720,7 +720,7 @@ mod tests { let mut expressions = Arena::new(); let mut constants = Arena::new(); - let matrix_ty = types.fetch_or_append( + let matrix_ty = types.insert( Type { name: None, inner: TypeInner::Matrix { @@ -732,7 +732,7 @@ mod tests { Default::default(), ); - let vec_ty = types.fetch_or_append( + let vec_ty = types.insert( Type { name: None, inner: TypeInner::Vector { diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index d6dfa2738..dcbac2276 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -257,7 +257,7 @@ impl Context { if qualifier.is_lhs() { let span = parser.module.types.get_span(arg.ty); - arg.ty = parser.module.types.fetch_or_append( + arg.ty = parser.module.types.insert( Type { name: None, inner: TypeInner::Pointer { @@ -818,7 +818,7 @@ impl Context { self.add_expression(Expression::Splat { size, value: right }, meta, body); if let Some(cols) = columns { - let ty = parser.module.types.fetch_or_append( + let ty = parser.module.types.insert( Type { name: None, inner: ty_inner, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index e46ababac..1b84a10bb 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -149,7 +149,7 @@ impl Parser { // value is used to initialize all the values along the diagonal of // the matrix; the rest are given zeros. let mut components = Vec::with_capacity(columns as usize); - let vector_ty = self.module.types.fetch_or_append( + let vector_ty = self.module.types.insert( Type { name: None, inner: TypeInner::Vector { @@ -296,7 +296,7 @@ impl Parser { } } - let ty = self.module.types.fetch_or_append( + let ty = self.module.types.insert( Type { name: None, inner: TypeInner::Vector { @@ -555,7 +555,7 @@ impl Parser { if let TypeInner::Vector { size, kind, width } = *self.resolve_type(ctx, handle, meta)? { - let ty = self.module.types.fetch_or_append( + let ty = self.module.types.insert( Type { name: None, inner: TypeInner::Vector { size, kind, width }, @@ -900,7 +900,7 @@ impl Parser { } let (ty, value) = if !components.is_empty() { - let ty = self.module.types.fetch_or_append( + let ty = self.module.types.insert( Type { name: None, inner: TypeInner::Struct { diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 01c2edd15..7a7b5e2f6 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -85,7 +85,7 @@ pub fn calculate_offset( }; let ty_span = types.get_span(ty); - ty = types.fetch_or_append( + ty = types.insert( Type { name, inner: TypeInner::Array { @@ -145,7 +145,7 @@ pub fn calculate_offset( span = align_up(span, align); let ty_span = types.get_span(ty); - ty = types.fetch_or_append( + ty = types.insert( Type { name, inner: TypeInner::Struct { diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 8ef71ef28..2cb4f43e0 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -497,7 +497,7 @@ impl<'source> ParsingContext<'source> { let span = self.parse_struct_declaration_list(parser, &mut members, layout)?; self.expect(parser, TokenValue::RightBrace)?; - let mut ty = parser.module.types.fetch_or_append( + let mut ty = parser.module.types.insert( Type { name: Some(ty_name), inner: TypeInner::Struct { diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 51acb0594..3f1d0fd39 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -147,7 +147,7 @@ impl<'source> ParsingContext<'source> { }, Span::default(), ); - handle = parser.module.types.fetch_or_append( + handle = parser.module.types.insert( Type { name: None, inner: TypeInner::Array { diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 3dc00c33f..fe6ed3b96 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -37,7 +37,7 @@ impl<'source> ParsingContext<'source> { let token = self.bump(parser)?; let handle = match token.value { TokenValue::Void => None, - TokenValue::TypeName(ty) => Some(parser.module.types.fetch_or_append(ty, token.meta)), + TokenValue::TypeName(ty) => Some(parser.module.types.insert(ty, token.meta)), TokenValue::Struct => { let mut meta = token.meta; let ty_name = self.expect_ident(parser)?.0; @@ -47,7 +47,7 @@ impl<'source> ParsingContext<'source> { self.parse_struct_declaration_list(parser, &mut members, StructLayout::Std140)?; let end_meta = self.expect(parser, TokenValue::RightBrace)?.meta; meta.subsume(end_meta); - let ty = parser.module.types.fetch_or_append( + let ty = parser.module.types.insert( Type { name: Some(ty_name.clone()), inner: TypeInner::Struct { diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index dd0942db9..e008ec382 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -262,7 +262,7 @@ impl Parser { array_specifier .map(|(size, size_meta)| { meta.subsume(size_meta); - self.module.types.fetch_or_append( + self.module.types.insert( Type { name: None, inner: TypeInner::Array { diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 6d82a40a9..d4043c033 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -58,7 +58,7 @@ impl Parser { data: BuiltInData, meta: Span, ) -> Option { - let ty = self.module.types.fetch_or_append( + let ty = self.module.types.insert( Type { name: None, inner: data.inner, @@ -188,7 +188,7 @@ impl Parser { storage: StorageQualifier::Output, }, "gl_ClipDistance" | "gl_CullDistance" => { - let base = self.module.types.fetch_or_append( + let base = self.module.types.insert( Type { name: None, inner: TypeInner::Scalar { diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 0c45aca71..04b67dd06 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -477,7 +477,7 @@ impl> super::Parser { let span = crate::Span::total_span( components.iter().map(|h| function.expressions.get_span(*h)), ); - let ty = module.types.fetch_or_append( + let ty = module.types.insert( crate::Type { name: None, inner: crate::TypeInner::Struct { diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index c58fe370f..48b38f658 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -211,7 +211,7 @@ pub(super) fn patch_comparison_type( }; let name = original_ty.name.clone(); - var.ty = arena.fetch_or_append( + var.ty = arena.insert( crate::Type { name, inner: ty_inner, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 09c5103b2..8301f2229 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3388,7 +3388,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.fetch_or_append( + handle: module.types.insert( crate::Type { name: self.future_decor.remove(&id).and_then(|dec| dec.name), inner, @@ -3423,7 +3423,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.fetch_or_append( + handle: module.types.insert( crate::Type { name: self.future_decor.remove(&id).and_then(|dec| dec.name), inner, @@ -3453,7 +3453,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.fetch_or_append( + handle: module.types.insert( crate::Type { name: self.future_decor.remove(&id).and_then(|dec| dec.name), inner, @@ -3490,7 +3490,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.fetch_or_append( + handle: module.types.insert( crate::Type { name: self.future_decor.remove(&id).and_then(|dec| dec.name), inner, @@ -3529,7 +3529,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.fetch_or_append( + handle: module.types.insert( crate::Type { name: decor.and_then(|dec| dec.name), inner, @@ -3593,7 +3593,7 @@ impl> Parser { base_lookup_ty.clone() } else { LookupType { - handle: module.types.fetch_or_append( + handle: module.types.insert( crate::Type { name: decor.and_then(|dec| dec.name), inner: crate::TypeInner::Pointer { @@ -3636,7 +3636,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.fetch_or_append( + handle: module.types.insert( crate::Type { name: decor.name, inner, @@ -3673,7 +3673,7 @@ impl> Parser { self.lookup_type.insert( id, LookupType { - handle: module.types.fetch_or_append( + handle: module.types.insert( crate::Type { name: decor.name, inner, @@ -3777,7 +3777,7 @@ impl> Parser { members, }; - let ty_handle = module.types.fetch_or_append( + let ty_handle = module.types.insert( crate::Type { name: parent_decor.and_then(|dec| dec.name), inner, @@ -3825,7 +3825,7 @@ impl> Parser { let decor = self.future_decor.remove(&id).unwrap_or_default(); // ensure there is a type for texture coordinate without extra components - module.types.fetch_or_append( + module.types.insert( crate::Type { name: None, inner: { @@ -3862,7 +3862,7 @@ impl> Parser { arrayed: is_array, }; - let handle = module.types.fetch_or_append( + let handle = module.types.insert( crate::Type { name: decor.name, inner, @@ -3905,7 +3905,7 @@ impl> Parser { inst.expect(2)?; let id = self.next()?; let decor = self.future_decor.remove(&id).unwrap_or_default(); - let handle = module.types.fetch_or_append( + let handle = module.types.insert( crate::Type { name: decor.name, inner: crate::TypeInner::Sampler { comparison: false }, @@ -4151,7 +4151,7 @@ impl> Parser { class: crate::ImageClass::Storage { format, access }, }, }; - effective_ty = module.types.fetch_or_append(ty, Default::default()); + effective_ty = module.types.insert(ty, Default::default()); } let ext_class = match self.lookup_storage_buffer_types.get(&effective_ty) { @@ -4215,7 +4215,7 @@ impl> Parser { ) { unsigned_ty = module .types - .fetch_or_append(crate::Type { name: None, inner }, Default::default()); + .insert(crate::Type { name: None, inner }, Default::default()); } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b665ce1e1..6b13942a1 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -602,7 +602,7 @@ mod type_inner_tests { Default::default(), ); - let mytype1 = types.fetch_or_append( + let mytype1 = types.insert( crate::Type { name: Some("MyType1".to_string()), inner: crate::TypeInner::Struct { @@ -613,7 +613,7 @@ mod type_inner_tests { }, Default::default(), ); - let mytype2 = types.fetch_or_append( + let mytype2 = types.insert( crate::Type { name: Some("MyType2".to_string()), inner: crate::TypeInner::Struct { @@ -1982,7 +1982,7 @@ impl Parser { TypeResolution::Handle(handle) => handle, TypeResolution::Value(inner) => ctx .types - .fetch_or_append(crate::Type { name: None, inner }, Default::default()), + .insert(crate::Type { name: None, inner }, Default::default()), }; components.push(last_component); crate::Expression::Compose { ty, components } @@ -3047,7 +3047,7 @@ impl Parser { match self.parse_type_decl_impl(lexer, attribute, name, type_arena, const_arena)? { Some(inner) => { let span = name_span.start..lexer.current_byte_offset(); - type_arena.fetch_or_append( + type_arena.insert( crate::Type { name: debug_name.map(|s| s.to_string()), inner, @@ -3308,12 +3308,10 @@ impl Parser { // register the type, if needed match context.typifier[value].clone() { TypeResolution::Handle(ty) => ty, - TypeResolution::Value(inner) => { - context.types.fetch_or_append( - crate::Type { name: None, inner }, - Default::default(), - ) - } + TypeResolution::Value(inner) => context.types.insert( + crate::Type { name: None, inner }, + Default::default(), + ), } } }; @@ -4004,7 +4002,7 @@ impl Parser { let (members, span) = self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?; let type_span = NagaSpan::from(lexer.span_from(start)); - let ty = module.types.fetch_or_append( + let ty = module.types.insert( crate::Type { name: Some(name.to_string()), inner: crate::TypeInner::Struct { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 3045defef..1526856d0 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -870,7 +870,7 @@ fn uniform_control_flow() { Default::default(), ); let mut type_arena = crate::UniqueArena::new(); - let ty = type_arena.fetch_or_append( + let ty = type_arena.insert( crate::Type { name: None, inner: crate::TypeInner::Vector { diff --git a/src/valid/compose.rs b/src/valid/compose.rs index 378f22faa..9f3aa8242 100644 --- a/src/valid/compose.rs +++ b/src/valid/compose.rs @@ -25,7 +25,7 @@ pub fn validate_compose( use crate::TypeInner as Ti; let self_ty = type_arena - .try_get(self_ty_handle) + .get_handle(self_ty_handle) .ok_or(ComposeError::TypeDoesntExist(self_ty_handle))?; match self_ty.inner { // vectors are composed from scalars or other vectors diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 56a464f9c..547cef2b9 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1224,7 +1224,7 @@ impl super::Validator { if let Some(&Ti::Array { size: crate::ArraySize::Dynamic, .. - }) = resolver.types.try_get(base).map(|ty| &ty.inner) + }) = resolver.types.get_handle(base).map(|ty| &ty.inner) { ShaderStages::all() } else { From f3ea2130a45f06a1fbbd6e7f0364a32dcd7d3965 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 16 Sep 2021 14:42:13 -0700 Subject: [PATCH 1380/2212] [wgsl-in]: Correctly compare pointer types. Treat `TypeInner::ValuePointer` and `TypeInner::Pointer` as equivalent by converting them to a canonical form before comparison. Support `ValuePointer` in WGSL type output. Fixes #1318. --- src/back/wgsl/writer.rs | 55 ++++++++++++++++++++++++++++++++++++++--- src/front/wgsl/mod.rs | 4 +-- src/proc/mod.rs | 53 +++++++++++++++++++++++++++++++++++++++ src/valid/compose.rs | 12 +++++++-- src/valid/function.rs | 15 +++++++++-- tests/wgsl-errors.rs | 18 ++++++++++++++ 6 files changed, 148 insertions(+), 9 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index f8956a691..fd2d1adfb 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -630,17 +630,66 @@ impl Writer { } TypeInner::Pointer { base, class } => { let (storage, maybe_access) = storage_class_str(class); + // Everything but `StorageClass::Handle` gives us a `storage` name, but + // Naga IR never produces pointers to handles, so it doesn't matter much + // how we write such a type. Just write it as the base type alone. if let Some(class) = storage { write!(self.out, "ptr<{}, ", class)?; - if let Some(access) = maybe_access { - write!(self.out, ", {}", access)?; - } } self.write_type(module, base)?; if storage.is_some() { + if let Some(access) = maybe_access { + write!(self.out, ", {}", access)?; + } write!(self.out, ">")?; } } + TypeInner::ValuePointer { + size: None, + kind, + width: _, + class, + } => { + let (storage, maybe_access) = storage_class_str(class); + if let Some(class) = storage { + write!(self.out, "ptr<{}, {}", class, scalar_kind_str(kind))?; + if let Some(access) = maybe_access { + write!(self.out, ", {}", access)?; + } + write!(self.out, ">")?; + } else { + return Err(Error::Unimplemented(format!( + "ValuePointer to StorageClass::Handle {:?}", + inner + ))); + } + } + TypeInner::ValuePointer { + size: Some(size), + kind, + width: _, + class, + } => { + let (storage, maybe_access) = storage_class_str(class); + if let Some(class) = storage { + write!( + self.out, + "ptr<{}, vec{}<{}>", + class, + back::vector_size_str(size), + scalar_kind_str(kind) + )?; + if let Some(access) = maybe_access { + write!(self.out, ", {}", access)?; + } + write!(self.out, ">")?; + } else { + return Err(Error::Unimplemented(format!( + "ValuePointer to StorageClass::Handle {:?}", + inner + ))); + } + } _ => { return Err(Error::Unimplemented(format!( "write_value_type {:?}", diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6b13942a1..95b0e174c 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3231,7 +3231,7 @@ impl Parser { .resolve_type(expr_id)?; let expr_inner = context.typifier.get(expr_id, context.types); let given_inner = &context.types[ty].inner; - if given_inner != expr_inner { + if !given_inner.equivalent(expr_inner, context.types) { log::error!( "Given type {:?} doesn't match expected {:?}", given_inner, @@ -3292,7 +3292,7 @@ impl Parser { Some(ty) => { let expr_inner = context.typifier.get(value, context.types); let given_inner = &context.types[ty].inner; - if given_inner != expr_inner { + if !given_inner.equivalent(expr_inner, context.types) { log::error!( "Given type {:?} doesn't match expected {:?}", given_inner, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index d672e905c..fd6015e62 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -6,6 +6,8 @@ mod namer; mod terminator; mod typifier; +use std::cmp::PartialEq; + pub use index::IndexableLength; pub use layouter::{Alignment, InvalidBaseType, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; @@ -129,6 +131,57 @@ impl super::TypeInner { Self::Image { .. } | Self::Sampler { .. } => 0, } } + + /// Return the canoncal form of `self`, or `None` if it's already in + /// canonical form. + /// + /// Certain types have multiple representations in `TypeInner`. This + /// function converts all forms of equivalent types to a single + /// representative of their class, so that simply applying `Eq` to the + /// result indicates whether the types are equivalent, as far as Naga IR is + /// concerned. + pub fn canonical_form( + &self, + types: &crate::UniqueArena, + ) -> Option { + use crate::TypeInner as Ti; + match *self { + Ti::Pointer { base, class } => match types[base].inner { + Ti::Scalar { kind, width } => Some(Ti::ValuePointer { + size: None, + kind, + width, + class, + }), + Ti::Vector { size, kind, width } => Some(Ti::ValuePointer { + size: Some(size), + kind, + width, + class, + }), + _ => None, + }, + _ => None, + } + } + + /// Compare `self` and `rhs` as types. + /// + /// This is mostly the same as `::eq`, but it treats + /// `ValuePointer` and `Pointer` types as equivalent. + /// + /// When you know that one side of the comparison is never a pointer, it's + /// fine to not bother with canonicalization, and just compare `TypeInner` + /// values with `==`. + pub fn equivalent( + &self, + rhs: &crate::TypeInner, + types: &crate::UniqueArena, + ) -> bool { + let left = self.canonical_form(types); + let right = rhs.canonical_form(types); + left.as_ref().unwrap_or(self) == right.as_ref().unwrap_or(rhs) + } } impl super::MathFunction { diff --git a/src/valid/compose.rs b/src/valid/compose.rs index 9f3aa8242..15148fc7a 100644 --- a/src/valid/compose.rs +++ b/src/valid/compose.rs @@ -96,7 +96,11 @@ pub fn validate_compose( }); } for (index, comp_res) in component_resolutions.enumerate() { - if comp_res.inner_with(type_arena) != &type_arena[base].inner { + let base_inner = &type_arena[base].inner; + let comp_res_inner = comp_res.inner_with(type_arena); + // We don't support arrays of pointers, but it seems best not to + // embed that assumption here, so use `TypeInner::equivalent`. + if !base_inner.equivalent(comp_res_inner, type_arena) { log::error!("Array component[{}] type {:?}", index, comp_res); return Err(ComposeError::ComponentType { index: index as u32, @@ -113,7 +117,11 @@ pub fn validate_compose( } for (index, (member, comp_res)) in members.iter().zip(component_resolutions).enumerate() { - if comp_res.inner_with(type_arena) != &type_arena[member.ty].inner { + let member_inner = &type_arena[member.ty].inner; + let comp_res_inner = comp_res.inner_with(type_arena); + // We don't support pointers in structs, but it seems best not to embed + // that assumption here, so use `TypeInner::equivalent`. + if !comp_res_inner.equivalent(member_inner, type_arena) { log::error!("Struct component[{}] type {:?}", index, comp_res); return Err(ComposeError::ComponentType { index: index as u32, diff --git a/src/valid/function.rs b/src/valid/function.rs index 79917722b..792b600e2 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -243,7 +243,8 @@ impl super::Validator { let ty = context .resolve_type_impl(expr, &self.valid_expression_set) .map_err(|error| CallError::Argument { index, error })?; - if ty != &context.types[arg.ty].inner { + let arg_inner = &context.types[arg.ty].inner; + if !ty.equivalent(arg_inner, context.types) { return Err(CallError::ArgumentType { index, required: arg.ty, @@ -448,7 +449,17 @@ impl super::Validator { .map(|expr| context.resolve_type(expr, &self.valid_expression_set)) .transpose()?; let expected_ty = context.return_type.map(|ty| &context.types[ty].inner); - if value_ty != expected_ty { + // We can't return pointers, but it seems best not to embed that + // assumption here, so use `TypeInner::equivalent` for comparison. + let okay = match (value_ty, expected_ty) { + (None, None) => true, + (Some(value_inner), Some(expected_inner)) => { + value_inner.equivalent(expected_inner, context.types) + } + (_, _) => false, + }; + + if !okay { log::error!( "Returning {:?} where {:?} is expected", value_ty, diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 941865ab9..f1b3fc55b 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -687,6 +687,24 @@ fn invalid_functions() { } } +#[test] +fn pointer_type_equivalence() { + check_validation_error! { + r#" + fn f(pv: ptr>, pf: ptr) { } + + fn g() { + var m: mat2x2; + let pv: ptr> = &m.x; + let pf: ptr = &m.x.x; + + f(pv, pf); + } + "#: + Ok(_) + } +} + #[test] fn missing_bindings() { check_validation_error! { From 7b023ce396967c20f660655a2aba72a2e5e1c387 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 16 Sep 2021 16:07:15 -0700 Subject: [PATCH 1381/2212] [wgsl-out] Make plain_form_indirection an associated fn of Writer. --- src/back/wgsl/writer.rs | 102 ++++++++++++++++++++-------------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index fd2d1adfb..0b70a4113 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -51,56 +51,6 @@ enum Indirection { Reference, } -/// Return the sort of indirection that `expr`'s plain form evaluates to. -/// -/// An expression's 'plain form' is the most general rendition of that -/// expression into WGSL, lacking `&` or `*` operators: -/// -/// - The plain form of `LocalVariable(x)` is simply `x`, which is a reference -/// to the local variable's storage. -/// -/// - The plain form of `GlobalVariable(g)` is simply `g`, which is usually a -/// reference to the global variable's storage. However, globals in the -/// `Handle` storage class are immutable, and `GlobalVariable` expressions for -/// those produce the value directly, not a pointer to it. Such -/// `GlobalVariable` expressions are `Ordinary`. -/// -/// - `Access` and `AccessIndex` are `Reference` when their `base` operand is a -/// pointer. If they are applied directly to a composite value, they are -/// `Ordinary`. -/// -/// Note that `FunctionArgument` expressions are never `Reference`, even when -/// the argument's type is `Pointer`. `FunctionArgument` always evaluates to the -/// argument's value directly, so any pointer it produces is merely the value -/// passed by the caller. -fn plain_form_indirection( - expr: Handle, - module: &Module, - func_ctx: &back::FunctionCtx<'_>, -) -> Indirection { - use crate::Expression as Ex; - match func_ctx.expressions[expr] { - Ex::LocalVariable(_) => Indirection::Reference, - Ex::GlobalVariable(handle) => { - let global = &module.global_variables[handle]; - match global.class { - crate::StorageClass::Handle => Indirection::Ordinary, - _ => Indirection::Reference, - } - } - Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => { - let base_ty = func_ctx.info[base].ty.inner_with(&module.types); - match *base_ty { - crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { - Indirection::Reference - } - _ => Indirection::Ordinary, - } - } - _ => Indirection::Ordinary, - } -} - pub struct Writer { out: W, names: crate::FastHashMap, @@ -1025,6 +975,56 @@ impl Writer { Ok(()) } + /// Return the sort of indirection that `expr`'s plain form evaluates to. + /// + /// An expression's 'plain form' is the most general rendition of that + /// expression into WGSL, lacking `&` or `*` operators: + /// + /// - The plain form of `LocalVariable(x)` is simply `x`, which is a reference + /// to the local variable's storage. + /// + /// - The plain form of `GlobalVariable(g)` is simply `g`, which is usually a + /// reference to the global variable's storage. However, globals in the + /// `Handle` storage class are immutable, and `GlobalVariable` expressions for + /// those produce the value directly, not a pointer to it. Such + /// `GlobalVariable` expressions are `Ordinary`. + /// + /// - `Access` and `AccessIndex` are `Reference` when their `base` operand is a + /// pointer. If they are applied directly to a composite value, they are + /// `Ordinary`. + /// + /// Note that `FunctionArgument` expressions are never `Reference`, even when + /// the argument's type is `Pointer`. `FunctionArgument` always evaluates to the + /// argument's value directly, so any pointer it produces is merely the value + /// passed by the caller. + fn plain_form_indirection( + expr: Handle, + module: &Module, + func_ctx: &back::FunctionCtx<'_>, + ) -> Indirection { + use crate::Expression as Ex; + match func_ctx.expressions[expr] { + Ex::LocalVariable(_) => Indirection::Reference, + Ex::GlobalVariable(handle) => { + let global = &module.global_variables[handle]; + match global.class { + crate::StorageClass::Handle => Indirection::Ordinary, + _ => Indirection::Reference, + } + } + Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => { + let base_ty = func_ctx.info[base].ty.inner_with(&module.types); + match *base_ty { + crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { + Indirection::Reference + } + _ => Indirection::Ordinary, + } + } + _ => Indirection::Ordinary, + } + } + fn start_named_expr( &mut self, module: &Module, @@ -1089,7 +1089,7 @@ impl Writer { // If the plain form of the expression is not what we need, emit the // operator necessary to correct that. - let plain = plain_form_indirection(expr, module, func_ctx); + let plain = Self::plain_form_indirection(expr, module, func_ctx); let opened_paren = match (requested, plain) { (Indirection::Ordinary, Indirection::Reference) => { write!(self.out, "(&")?; From 8122598fe790896bd689fa24371408760519196f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 16 Sep 2021 16:03:20 -0700 Subject: [PATCH 1382/2212] [wgsl-out] Correct handling of named pointer expressions. Treat expressions in `Function::named_expressions` like WGSL `let` declarations, assuming that the Load Rule was applied to the rhs of the declaration, meaning that their values are always `Indirection::Ordinary`. Split `write_expr_plain_form` out from `write_expr_with_indirection`, to clean up the parenthesis generation: no more `opened_paren` variable, just function calls. This makes the early return for named expressions neater. Fixes #1382. --- src/back/wgsl/writer.rs | 66 ++++++++++++++++++++++++----------- tests/in/pointers.param.ron | 7 ++++ tests/in/pointers.wgsl | 5 +++ tests/out/spv/pointers.spvasm | 29 +++++++++++++++ tests/out/wgsl/pointers.wgsl | 8 +++++ tests/snapshots.rs | 1 + 6 files changed, 95 insertions(+), 21 deletions(-) create mode 100644 tests/in/pointers.param.ron create mode 100644 tests/in/pointers.wgsl create mode 100644 tests/out/spv/pointers.spvasm create mode 100644 tests/out/wgsl/pointers.wgsl diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 0b70a4113..c95aa3375 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -998,11 +998,20 @@ impl Writer { /// argument's value directly, so any pointer it produces is merely the value /// passed by the caller. fn plain_form_indirection( + &self, expr: Handle, module: &Module, func_ctx: &back::FunctionCtx<'_>, ) -> Indirection { use crate::Expression as Ex; + + // Named expressions are `let` expressions, which apply the Load Rule, + // so if their type is a Naga pointer, then that must be a WGSL pointer + // as well. + if self.named_expressions.contains_key(&expr) { + return Indirection::Ordinary; + } + match func_ctx.expressions[expr] { Ex::LocalVariable(_) => Indirection::Reference, Ex::GlobalVariable(handle) => { @@ -1079,6 +1088,40 @@ impl Writer { expr: Handle, func_ctx: &back::FunctionCtx<'_>, requested: Indirection, + ) -> BackendResult { + // If the plain form of the expression is not what we need, emit the + // operator necessary to correct that. + let plain = self.plain_form_indirection(expr, module, func_ctx); + match (requested, plain) { + (Indirection::Ordinary, Indirection::Reference) => { + write!(self.out, "(&")?; + self.write_expr_plain_form(module, expr, func_ctx, plain)?; + write!(self.out, ")")?; + } + (Indirection::Reference, Indirection::Ordinary) => { + write!(self.out, "(*")?; + self.write_expr_plain_form(module, expr, func_ctx, plain)?; + write!(self.out, ")")?; + } + (_, _) => self.write_expr_plain_form(module, expr, func_ctx, plain)?, + } + + Ok(()) + } + + /// Write the 'plain form' of `expr`. + /// + /// An expression's 'plain form' is the most general rendition of that + /// expression into WGSL, lacking `&` or `*` operators. The plain forms of + /// `LocalVariable(x)` and `GlobalVariable(g)` are simply `x` and `g`. Such + /// Naga expressions represent both WGSL pointers and references; it's the + /// caller's responsibility to distinguish those cases appropriately. + fn write_expr_plain_form( + &mut self, + module: &Module, + expr: Handle, + func_ctx: &back::FunctionCtx<'_>, + indirection: Indirection, ) -> BackendResult { use crate::Expression; @@ -1087,21 +1130,6 @@ impl Writer { return Ok(()); } - // If the plain form of the expression is not what we need, emit the - // operator necessary to correct that. - let plain = Self::plain_form_indirection(expr, module, func_ctx); - let opened_paren = match (requested, plain) { - (Indirection::Ordinary, Indirection::Reference) => { - write!(self.out, "(&")?; - true - } - (Indirection::Reference, Indirection::Ordinary) => { - write!(self.out, "(*")?; - true - } - (_, _) => false, - }; - let expression = &func_ctx.expressions[expr]; // Write the plain WGSL form of a Naga expression. @@ -1173,7 +1201,7 @@ impl Writer { } // TODO: copy-paste from glsl-out Expression::Access { base, index } => { - self.write_expr_with_indirection(module, base, func_ctx, plain)?; + self.write_expr_with_indirection(module, base, func_ctx, indirection)?; write!(self.out, "[")?; self.write_expr(module, index, func_ctx)?; write!(self.out, "]")? @@ -1183,7 +1211,7 @@ impl Writer { let base_ty_res = &func_ctx.info[base].ty; let mut resolved = base_ty_res.inner_with(&module.types); - self.write_expr_with_indirection(module, base, func_ctx, plain)?; + self.write_expr_with_indirection(module, base, func_ctx, indirection)?; let base_ty_handle = match *resolved { TypeInner::Pointer { base, class: _ } => { @@ -1610,10 +1638,6 @@ impl Writer { Expression::CallResult(_) | Expression::AtomicResult { .. } => {} } - if opened_paren { - write!(self.out, ")")? - }; - Ok(()) } diff --git a/tests/in/pointers.param.ron b/tests/in/pointers.param.ron new file mode 100644 index 000000000..de304854b --- /dev/null +++ b/tests/in/pointers.param.ron @@ -0,0 +1,7 @@ +( + spv: ( + version: (1, 2), + debug: true, + adjust_coordinate_space: false, + ), +) diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl new file mode 100644 index 000000000..8dd12442e --- /dev/null +++ b/tests/in/pointers.wgsl @@ -0,0 +1,5 @@ +fn f() { + var v: vec2; + let px = &v.x; + *px = 10; +} diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm new file mode 100644 index 000000000..b019f8b5c --- /dev/null +++ b/tests/out/spv/pointers.spvasm @@ -0,0 +1,29 @@ +; SPIR-V +; Version: 1.2 +; Generator: rspirv +; Bound: 16 +OpCapability Shader +OpCapability Linkage +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpSource GLSL 450 +OpName %6 "v" +OpName %9 "f" +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 10 +%5 = OpTypeVector %4 2 +%7 = OpTypePointer Function %5 +%10 = OpTypeFunction %2 +%12 = OpTypePointer Function %4 +%14 = OpTypeInt 32 0 +%13 = OpConstant %14 0 +%9 = OpFunction %2 None %10 +%8 = OpLabel +%6 = OpVariable %7 Function +OpBranch %11 +%11 = OpLabel +%15 = OpAccessChain %12 %6 %13 +OpStore %15 %3 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl new file mode 100644 index 000000000..15a5157ae --- /dev/null +++ b/tests/out/wgsl/pointers.wgsl @@ -0,0 +1,8 @@ +fn f() { + var v: vec2; + + let px: ptr = (&v.x); + (*px) = 10; + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index a712d7b33..b34aadf84 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -480,6 +480,7 @@ fn convert_wgsl() { "access", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ("pointers", Targets::SPIRV | Targets::WGSL), ( "control-flow", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From aa08cf94a4da1cad7ff8bef27611ff0650bdfb02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 26 Sep 2021 21:55:32 +0100 Subject: [PATCH 1383/2212] [spv-in] preserve case order when reusing blocks --- src/front/spv/mod.rs | 54 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 8301f2229..552382480 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -539,6 +539,16 @@ pub struct Parser { options: Options, index_constants: Vec>, index_constant_expressions: Vec>, + + /// Maps for a switch from a case target to the respective body and associated literals that + /// use that target block id. + /// + /// Used to preserve allocations between instruction parsing. + switch_cases: indexmap::IndexMap< + spirv::Word, + (BodyIndex, Vec), + std::hash::BuildHasherDefault, + >, } impl> Parser { @@ -571,6 +581,7 @@ impl> Parser { options: options.clone(), index_constants: Vec::new(), index_constant_expressions: Vec::new(), + switch_cases: indexmap::IndexMap::default(), } } @@ -2593,12 +2604,24 @@ impl> Parser { ref other => unimplemented!("Unexpected selector {:?}", other), }; - let mut cases = Vec::new(); + // Clear past switch cases to prevent them from entering this one + self.switch_cases.clear(); + for _ in 0..(inst.wc - 3) / 2 { let literal = self.next()?; let target = self.next()?; let case_body_idx = ctx.bodies.len(); + + // Check if any previous case already used this target block id, if so + // group them together to reorder them later so that no weird + // falltrough cases happen. + if let Some(&mut (_, ref mut literals)) = self.switch_cases.get_mut(&target) + { + literals.push(literal as i32); + continue; + } + let mut body = Body::with_parent(body_idx); if let Some(info) = ctx.mergers.get(&target) { @@ -2608,7 +2631,34 @@ impl> Parser { ctx.bodies.push(body); ctx.body_for_label.entry(target).or_insert(case_body_idx); - cases.push((literal as i32, case_body_idx)); + // Register this target block id as already having been processed and + // the respective body index assigned and the first case value + self.switch_cases + .insert(target, (case_body_idx, vec![literal as i32])); + } + + // Loop trough the collected target blocks creating a new case for each + // literal pointing to it, only one case will have the true body and all the + // others will be empty falltrough so that they all execute the same body + // without duplicating code. + // + // Since `switch_cases` is an indexmap the order of insertation is preserved + // this is needed because spir-v defines falltrough order in the switch + // instruction. + let mut cases = Vec::with_capacity((inst.wc as usize - 3) / 2); + for &(case_body_idx, ref literals) in self.switch_cases.values() { + let value = literals[0]; + + for &literal in literals.iter().skip(1) { + let empty_body_idx = ctx.bodies.len(); + let body = Body::with_parent(body_idx); + + ctx.bodies.push(body); + + cases.push((literal, empty_body_idx)); + } + + cases.push((value, case_body_idx)); } block.extend(emitter.finish(ctx.expressions)); From 38d74a7f0aa723355a35a3011d044f59d38e79a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 23 Sep 2021 22:20:08 +0100 Subject: [PATCH 1384/2212] [glsl-in] Use intermediate local if storage class isn't function Automatically spills to a local variable function call arguments to parameters expecting a pointer where the argument storage class isn't function since the storage classes wouldn't match. --- src/front/glsl/context.rs | 7 +- src/front/glsl/functions.rs | 126 +++++++++++++++++---------- tests/in/glsl/expressions.frag | 14 +-- tests/out/wgsl/expressions-frag.wgsl | 24 +++-- 4 files changed, 114 insertions(+), 57 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index dcbac2276..6729c6f79 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -433,7 +433,12 @@ impl Context { HirExprKind::Access { base, index } => { let (index, index_meta) = self.lower_expect_inner(stmt, parser, index, ExprPos::Rhs, body)?; - let maybe_constant_index = parser.solve_constant(self, index, index_meta).ok(); + let maybe_constant_index = match pos { + // Don't try to generate `AccessIndex` if in a LHS position, since it + // wouldn't produce a pointer. + ExprPos::Lhs => None, + _ => parser.solve_constant(self, index, index_meta).ok(), + }; let base = self .lower_expect_inner( diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 1b84a10bb..e8693fb20 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -9,7 +9,8 @@ use super::{ use crate::{ front::glsl::types::type_power, proc::ensure_block_returns, Arena, Block, Constant, ConstantInner, EntryPoint, Expression, FastHashMap, Function, FunctionArgument, FunctionResult, - Handle, LocalVariable, ScalarKind, ScalarValue, Span, Statement, StructMember, Type, TypeInner, + Handle, LocalVariable, ScalarKind, ScalarValue, Span, Statement, StorageClass, StructMember, + Type, TypeInner, }; use std::iter; @@ -549,47 +550,85 @@ impl Parser { ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.as_pos(), body)?; if parameter_info.qualifier.is_lhs() { - // If the argument is to be passed as a pointer but the type of the - // expression returns a vector it must mean that it was for example - // swizzled and it must be spilled into a local before calling - if let TypeInner::Vector { size, kind, width } = - *self.resolve_type(ctx, handle, meta)? - { - let ty = self.module.types.insert( - Type { - name: None, - inner: TypeInner::Vector { size, kind, width }, - }, - Span::default(), - ); - let temp_var = ctx.locals.append( - LocalVariable { - name: None, - ty, - init: None, - }, - Span::default(), - ); - let temp_expr = ctx.add_expression( - Expression::LocalVariable(temp_var), - Span::default(), - body, - ); + let (ty, value) = match *self.resolve_type(ctx, handle, meta)? { + // If the argument is to be passed as a pointer but the type of the + // expression returns a vector it must mean that it was for example + // swizzled and it must be spilled into a local before calling + // TODO: this part doesn't work because of #1385 once that's sorted out + // revisit this part. + TypeInner::Vector { size, kind, width } => ( + self.module.types.insert( + Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }, + Span::default(), + ), + handle, + ), + // If the argument is a pointer whose storage class isn't `Function` an + // indirection trough a local variable is needed to align the storage + // classes of the call argument and the overload parameter + TypeInner::Pointer { base, class } if class != StorageClass::Function => ( + base, + ctx.add_expression( + Expression::Load { pointer: handle }, + Span::default(), + body, + ), + ), + TypeInner::ValuePointer { + size, + kind, + width, + class, + } if class != StorageClass::Function => { + let inner = match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; - body.push( - Statement::Store { - pointer: temp_expr, - value: handle, - }, - Span::default(), - ); + ( + self.module + .types + .insert(Type { name: None, inner }, Span::default()), + ctx.add_expression( + Expression::Load { pointer: handle }, + Span::default(), + body, + ), + ) + } + _ => { + arguments.push(handle); + continue; + } + }; - arguments.push(temp_expr); - // Register the temporary local to be written back to it's original - // place after the function call - proxy_writes.push((*expr, temp_expr)); - continue; - } + let temp_var = ctx.locals.append( + LocalVariable { + name: None, + ty, + init: None, + }, + Span::default(), + ); + let temp_expr = + ctx.add_expression(Expression::LocalVariable(temp_var), Span::default(), body); + + body.push( + Statement::Store { + pointer: temp_expr, + value, + }, + Span::default(), + ); + + arguments.push(temp_expr); + // Register the temporary local to be written back to it's original + // place after the function call + proxy_writes.push((handle, temp_expr)); + continue; } // Apply implicit conversions as needed @@ -623,18 +662,15 @@ impl Parser { ctx.emit_start(); // Write back all the variables that were scheduled to their original place - for (tgt, pointer) in proxy_writes { + for (original, pointer) in proxy_writes { let value = ctx.add_expression(Expression::Load { pointer }, meta, body); - let target = ctx - .lower_expect_inner(stmt, self, tgt, ExprPos::Rhs, body)? - .0; ctx.emit_flush(body); ctx.emit_start(); body.push( Statement::Store { - pointer: target, + pointer: original, value, }, meta, diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 58176f5ae..105d6116d 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -63,18 +63,22 @@ void testBinOpUintUVec(uint a, uvec4 b) { } void testStructConstructor() { - struct BST { - int data; - }; + struct BST { + int data; + }; - BST tree = BST(1); + BST tree = BST(1); } void testArrayConstructor() { - float tree[1] = float[1](0.0); + float tree[1] = float[1](0.0); } +float global; +void privatePointer(inout float a) {} + out vec4 o_color; void main() { + privatePointer(global); o_color.rgba = vec4(1.0); } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index f7514881e..8bed050c1 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -2,6 +2,7 @@ struct BST { data: i32; }; +var global: f32; var o_color: vec4; fn testBinOpVecFloat(a: vec4, b: f32) { @@ -184,13 +185,24 @@ fn testArrayConstructor() { } +fn privatePointer(a12: ptr) { + return; +} + fn main1() { - let e1: vec4 = o_color; - let e4: vec4 = vec4(1.0); - o_color.x = e4.x; - o_color.y = e4.y; - o_color.z = e4.z; - o_color.w = e4.w; + var local: f32; + + let e3: f32 = global; + local = e3; + privatePointer((&local)); + let e5: f32 = local; + global = e5; + let e6: vec4 = o_color; + let e9: vec4 = vec4(1.0); + o_color.x = e9.x; + o_color.y = e9.y; + o_color.z = e9.z; + o_color.w = e9.w; return; } From 21324b8feaecd5808ea32997dc4a64cbef8640ab Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 27 Sep 2021 18:49:28 -0400 Subject: [PATCH 1385/2212] Update WGSL grammar for pointer access. (#1312) * Update WGSL grammar for pointer access. Comes with a small test, which revealed a number of issues in the backends. * Validate pointer arguments to functions to only have function/private/workgroup classes. Comes with a small test. Also, "pointer-access.spv" test is temporarily disabled. --- src/back/glsl/mod.rs | 15 +- src/back/hlsl/writer.rs | 11 +- src/back/msl/writer.rs | 13 +- src/back/wgsl/writer.rs | 20 +- src/front/wgsl/lexer.rs | 24 +- src/front/wgsl/mod.rs | 17 +- src/front/wgsl/tests.rs | 4 +- src/valid/function.rs | 19 ++ tests/in/access.wgsl | 8 + tests/in/image.wgsl | 2 +- tests/out/glsl/access.atomics.Compute.glsl | 5 + tests/out/glsl/access.foo.Vertex.glsl | 6 + tests/out/hlsl/access.hlsl | 7 + tests/out/msl/access.msl | 14 +- tests/out/spv/access.spvasm | 296 +++++++++++---------- tests/out/wgsl/access.wgsl | 7 + tests/out/wgsl/image.wgsl | 4 +- tests/snapshots.rs | 17 +- tests/wgsl-errors.rs | 20 +- 19 files changed, 312 insertions(+), 197 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 4cb694ccd..9b171fd9e 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -715,7 +715,9 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Pointer { .. } | TypeInner::Struct { .. } | TypeInner::Image { .. } - | TypeInner::Sampler { .. } => unreachable!(), + | TypeInner::Sampler { .. } => { + return Err(Error::Custom(format!("Unable to write type {:?}", inner))) + } } Ok(()) @@ -1332,7 +1334,14 @@ impl<'a, W: Write> Writer<'a, W> { // This is where we can generate intermediate constants for some expression types. Statement::Emit(ref range) => { for handle in range.clone() { - let expr_name = if let Some(name) = ctx.named_expressions.get(&handle) { + let info = &ctx.info[handle]; + let ptr_class = info.ty.inner_with(&self.module.types).pointer_class(); + let expr_name = if ptr_class.is_some() { + // GLSL can't save a pointer-valued expression in a variable, + // but we shouldn't ever need to: they should never be named expressions, + // and none of the expression types flagged by bake_ref_count can be pointer-valued. + None + } else if let Some(name) = ctx.named_expressions.get(&handle) { // Front end provides names for all variables at the start of writing. // But we write them to step by step. We need to recache them // Otherwise, we could accidentally write variable name instead of full expression. @@ -1340,7 +1349,7 @@ impl<'a, W: Write> Writer<'a, W> { Some(self.namer.call_unique(name)) } else { let min_ref_count = ctx.expressions[handle].bake_ref_count(); - if min_ref_count <= ctx.info[handle].ref_count { + if min_ref_count <= info.ref_count { Some(format!("{}{}", super::BAKE_PREFIX, handle.index())) } else { None diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index d48daf1aa..339523f40 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1057,7 +1057,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *stmt { Statement::Emit(ref range) => { for handle in range.clone() { - let expr_name = if let Some(name) = func_ctx.named_expressions.get(&handle) { + let info = &func_ctx.info[handle]; + let ptr_class = info.ty.inner_with(&module.types).pointer_class(); + let expr_name = if ptr_class.is_some() { + // HLSL can't save a pointer-valued expression in a variable, + // but we shouldn't ever need to: they should never be named expressions, + // and none of the expression types flagged by bake_ref_count can be pointer-valued. + None + } else if let Some(name) = func_ctx.named_expressions.get(&handle) { // Front end provides names for all variables at the start of writing. // But we write them to step by step. We need to recache them // Otherwise, we could accidentally write variable name instead of full expression. @@ -1065,7 +1072,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Some(self.namer.call_unique(name)) } else { let min_ref_count = func_ctx.expressions[handle].bake_ref_count(); - if min_ref_count <= func_ctx.info[handle].ref_count { + if min_ref_count <= info.ref_count { Some(format!("_expr{}", handle.index())) } else { None diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8f0368908..78d56aa0c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1355,7 +1355,7 @@ impl Writer { )?; } TypeResolution::Value(ref other) => { - log::error!("Type {:?} isn't a known local", other); + log::warn!("Type {:?} isn't a known local", other); //TEMP! return Err(Error::FeatureNotImplemented("weird local type".to_string())); } } @@ -1383,7 +1383,14 @@ impl Writer { match *statement { crate::Statement::Emit(ref range) => { for handle in range.clone() { - let expr_name = if let Some(name) = + let info = &context.expression.info[handle]; + let ptr_class = info + .ty + .inner_with(&context.expression.module.types) + .pointer_class(); + let expr_name = if ptr_class.is_some() { + None // don't bake pointer expressions (just yet) + } else if let Some(name) = context.expression.function.named_expressions.get(&handle) { // Front end provides names for all variables at the start of writing. @@ -1394,7 +1401,7 @@ impl Writer { } else { let min_ref_count = context.expression.function.expressions[handle].bake_ref_count(); - if min_ref_count <= context.expression.info[handle].ref_count { + if min_ref_count <= info.ref_count { Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) } else { None diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index c95aa3375..c108d90e8 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -525,10 +525,13 @@ impl Writer { "storage_", "", storage_format_str(format), - if access.contains(crate::StorageAccess::STORE) { - ",write" + if access.contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) + { + ",read_write" + } else if access.contains(crate::StorageAccess::LOAD) { + ",read" } else { - "" + ",write" }, ), }; @@ -639,6 +642,7 @@ impl Writer { inner ))); } + write!(self.out, ">")?; } _ => { return Err(Error::Unimplemented(format!( @@ -666,6 +670,7 @@ impl Writer { match *stmt { Statement::Emit(ref range) => { for handle in range.clone() { + let info = &func_ctx.info[handle]; let expr_name = if let Some(name) = func_ctx.named_expressions.get(&handle) { // Front end provides names for all variables at the start of writing. // But we write them to step by step. We need to recache them @@ -682,8 +687,7 @@ impl Writer { | Expression::ImageSample { .. } => true, _ => false, }; - if min_ref_count <= func_ctx.info[handle].ref_count || required_baking_expr - { + if min_ref_count <= info.ref_count || required_baking_expr { // If expression contains unsupported builtin we should skip it if let Expression::Load { pointer } = func_ctx.expressions[handle] { if let Expression::AccessIndex { base, index } = @@ -809,8 +813,8 @@ impl Writer { } let func_name = &self.names[&NameKey::Function(function)]; write!(self.out, "{}(", func_name)?; - for (index, argument) in arguments.iter().enumerate() { - self.write_expr(module, *argument, func_ctx)?; + for (index, &argument) in arguments.iter().enumerate() { + self.write_expr(module, argument, func_ctx)?; // Only write a comma if isn't the last element if index != arguments.len().saturating_sub(1) { // The leading space is for readability only @@ -1199,14 +1203,12 @@ impl Writer { self.write_expr(module, right, func_ctx)?; write!(self.out, ")")?; } - // TODO: copy-paste from glsl-out Expression::Access { base, index } => { self.write_expr_with_indirection(module, base, func_ctx, indirection)?; write!(self.out, "[")?; self.write_expr(module, index, func_ctx)?; write!(self.out, "]")? } - // TODO: copy-paste from glsl-out Expression::AccessIndex { base, index } => { let base_ty_res = &func_ctx.info[base].ty; let mut resolved = base_ty_res.inner_with(&module.types); diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 54a2660ea..91f2a5ead 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -558,24 +558,24 @@ impl<'a> Lexer<'a> { Ok(pair) } - // TODO relocate storage texture specifics + pub(super) fn next_storage_access(&mut self) -> Result> { + let (ident, span) = self.next_ident_with_span()?; + match ident { + "read" => Ok(crate::StorageAccess::LOAD), + "write" => Ok(crate::StorageAccess::STORE), + "read_write" => Ok(crate::StorageAccess::LOAD | crate::StorageAccess::STORE), + _ => Err(Error::UnknownAccess(span)), + } + } + pub(super) fn next_format_generic( &mut self, ) -> Result<(crate::StorageFormat, crate::StorageAccess), Error<'a>> { self.expect(Token::Paren('<'))?; let (ident, ident_span) = self.next_ident_with_span()?; let format = conv::map_storage_format(ident, ident_span)?; - let access = if self.skip(Token::Separator(',')) { - let (raw, span) = self.next_ident_with_span()?; - match raw { - "read" => crate::StorageAccess::LOAD, - "write" => crate::StorageAccess::STORE, - "read_write" => crate::StorageAccess::all(), - _ => return Err(Error::UnknownAccess(span)), - } - } else { - crate::StorageAccess::LOAD - }; + self.expect(Token::Separator(','))?; + let access = self.next_storage_access()?; self.expect(Token::Paren('>'))?; Ok((format, access)) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 95b0e174c..800851a74 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2587,13 +2587,7 @@ impl Parser { class = Some(match class_str { "storage" => { let access = if lexer.skip(Token::Separator(',')) { - let (ident, span) = lexer.next_ident_with_span()?; - match ident { - "read" => crate::StorageAccess::LOAD, - "write" => crate::StorageAccess::STORE, - "read_write" => crate::StorageAccess::all(), - _ => return Err(Error::UnknownAccess(span)), - } + lexer.next_storage_access()? } else { // defaulting to `read` crate::StorageAccess::LOAD @@ -2836,9 +2830,16 @@ impl Parser { "ptr" => { lexer.expect_generic_paren('<')?; let (ident, span) = lexer.next_ident_with_span()?; - let class = conv::map_storage_class(ident, span)?; + let mut class = conv::map_storage_class(ident, span)?; lexer.expect(Token::Separator(','))?; let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + if let crate::StorageClass::Storage { ref mut access } = class { + *access = if lexer.skip(Token::Separator(',')) { + lexer.next_storage_access()? + } else { + crate::StorageAccess::LOAD + }; + } lexer.expect_generic_paren('>')?; crate::TypeInner::Pointer { base, class } } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 432b39f46..da1670c14 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -92,7 +92,7 @@ fn parse_types() { parse_str("var t: texture_cube_array;").unwrap(); parse_str("var t: texture_multisampled_2d;").unwrap(); parse_str("var t: texture_storage_1d;").unwrap(); - parse_str("var t: texture_storage_3d;").unwrap(); + parse_str("var t: texture_storage_3d;").unwrap(); } #[test] @@ -305,7 +305,7 @@ fn parse_texture_load() { .unwrap(); parse_str( " - var t: texture_storage_1d_array; + var t: texture_storage_1d_array; fn foo() { let r: vec4 = textureLoad(t, 10, 2); } diff --git a/src/valid/function.rs b/src/valid/function.rs index 792b600e2..23d4c0074 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -76,6 +76,12 @@ pub enum FunctionError { }, #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")] InvalidArgumentType { index: usize, name: String }, + #[error("Argument '{name}' at index {index} is a pointer of class {class:?}, which can't be passed into functions.")] + InvalidArgumentPointerClass { + index: usize, + name: String, + class: crate::StorageClass, + }, #[error("There are instructions after `return`/`break`/`continue`")] InstructionsAfterReturn, #[error("The `break` is used outside of a `loop` or `switch` context")] @@ -696,6 +702,19 @@ impl super::Validator { name: argument.name.clone().unwrap_or_default(), }); } + match module.types[argument.ty].inner.pointer_class() { + Some(crate::StorageClass::Private) + | Some(crate::StorageClass::Function) + | Some(crate::StorageClass::WorkGroup) + | None => {} + Some(other) => { + return Err(FunctionError::InvalidArgumentPointerClass { + index, + name: argument.name.clone().unwrap_or_default(), + class: other, + }) + } + } } self.valid_expression_set.clear(); diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 8ab506c27..f4af84913 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -11,6 +11,10 @@ struct Bar { [[group(0), binding(0)]] var bar: Bar; +fn read_from_private(foo: ptr) -> f32 { + return *foo; +} + [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { var foo: f32 = 0.0; @@ -25,6 +29,10 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let b = bar.matrix[index].x; let a = bar.data[arrayLength(&bar.data) - 2u]; + // test pointer types + let pointer: ptr = &bar.data[0]; + let foo_value = read_from_private(&foo); + // test storage stores bar.matrix[1].z = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 74378d4fe..c4621a407 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -5,7 +5,7 @@ var image_multisampled_src: texture_multisampled_2d; [[group(0), binding(4)]] var image_depth_multisampled_src: texture_depth_multisampled_2d; [[group(0), binding(1)]] -var image_storage_src: texture_storage_2d; +var image_storage_src: texture_storage_2d; [[group(0), binding(5)]] var image_array_src: texture_2d_array; [[group(0), binding(6)]] diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 2af1e7827..958cd5a6a 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -13,6 +13,11 @@ buffer Bar_block_0Cs { } _group_0_binding_0; +float read_from_private(inout float foo2) { + float _e2 = foo2; + return _e2; +} + void main() { int tmp = 0; int value = _group_0_binding_0.atom; diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index 9cf0b27af..97248f546 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -11,6 +11,11 @@ buffer Bar_block_0Vs { } _group_0_binding_0; +float read_from_private(inout float foo2) { + float _e2 = foo2; + return _e2; +} + void main() { uint vi = uint(gl_VertexID); float foo1 = 0.0; @@ -21,6 +26,7 @@ void main() { uvec2 arr[2] = _group_0_binding_0.arr; float b = _group_0_binding_0.matrix[3][0]; int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)]; + float _e25 = read_from_private(foo1); _group_0_binding_0.matrix[1][2] = 1.0; _group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); _group_0_binding_0.arr = uvec2[2](uvec2(0u), uvec2(1u)); diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index e9af3b110..fe8c701ca 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -1,6 +1,12 @@ RWByteAddressBuffer bar : register(u0); +float read_from_private(inout float foo2) +{ + float _expr2 = foo2; + return _expr2; +} + uint NagaBufferLengthRW(RWByteAddressBuffer buffer) { uint ret; @@ -19,6 +25,7 @@ float4 foo(uint vi : SV_VertexID) : SV_Position uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))}; float b = asfloat(bar.Load(0+48+0)); int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 4) - 2u)*4+88)); + const float _e25 = read_from_private(foo1); bar.Store(8+16+0, asuint(1.0)); { float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx)); diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index dd9622a60..44134f29d 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -17,10 +17,17 @@ struct Bar { type3 arr; type5 data; }; -struct type9 { +struct type11 { int inner[5]; }; +float read_from_private( + thread float& foo2 +) { + float _e2 = foo2; + return _e2; +} + struct fooInput { }; struct fooOutput { @@ -32,17 +39,18 @@ vertex fooOutput foo( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo1 = 0.0; - type9 c; + type11 c; float baz = foo1; foo1 = 1.0; metal::float4x4 matrix = bar.matrix; type3 arr = bar.arr; float b = bar.matrix[3].x; int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 4) - 2u]; + float _e25 = read_from_private(foo1); bar.matrix[1].z = 1.0; bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; - for(int _i=0; _i<5; ++_i) c.inner[_i] = type9 {a, static_cast(b), 3, 4, 5}.inner[_i]; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type11 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; return fooOutput { matrix * static_cast(metal::int4(value)) }; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index f143347e5..3bdea548b 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,41 +1,42 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 106 +; Bound: 114 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %39 "foo" %34 %37 -OpEntryPoint GLCompute %83 "atomics" -OpExecutionMode %83 LocalSize 1 1 1 +OpEntryPoint Vertex %47 "foo" %42 %45 +OpEntryPoint GLCompute %91 "atomics" +OpExecutionMode %91 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %25 0 "matrix" -OpMemberName %25 1 "atom" -OpMemberName %25 2 "arr" -OpMemberName %25 3 "data" -OpName %25 "Bar" -OpName %27 "bar" -OpName %29 "foo" -OpName %31 "c" -OpName %34 "vi" -OpName %39 "foo" -OpName %81 "tmp" -OpName %83 "atomics" -OpDecorate %23 ArrayStride 8 -OpDecorate %24 ArrayStride 4 -OpDecorate %25 Block -OpMemberDecorate %25 0 Offset 0 -OpMemberDecorate %25 0 ColMajor -OpMemberDecorate %25 0 MatrixStride 16 -OpMemberDecorate %25 1 Offset 64 -OpMemberDecorate %25 2 Offset 72 -OpMemberDecorate %25 3 Offset 88 -OpDecorate %26 ArrayStride 4 -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 0 -OpDecorate %34 BuiltIn VertexIndex -OpDecorate %37 BuiltIn Position +OpMemberName %26 0 "matrix" +OpMemberName %26 1 "atom" +OpMemberName %26 2 "arr" +OpMemberName %26 3 "data" +OpName %26 "Bar" +OpName %30 "bar" +OpName %34 "read_from_private" +OpName %38 "foo" +OpName %39 "c" +OpName %42 "vi" +OpName %47 "foo" +OpName %89 "tmp" +OpName %91 "atomics" +OpDecorate %24 ArrayStride 8 +OpDecorate %25 ArrayStride 4 +OpDecorate %26 Block +OpMemberDecorate %26 0 Offset 0 +OpMemberDecorate %26 0 ColMajor +OpMemberDecorate %26 0 MatrixStride 16 +OpMemberDecorate %26 1 Offset 64 +OpMemberDecorate %26 2 Offset 72 +OpMemberDecorate %26 3 Offset 88 +OpDecorate %29 ArrayStride 4 +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 0 +OpDecorate %42 BuiltIn VertexIndex +OpDecorate %45 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -45,120 +46,131 @@ OpDecorate %37 BuiltIn Position %9 = OpTypeInt 32 0 %8 = OpConstant %9 3 %10 = OpConstant %9 2 -%11 = OpConstant %4 1 -%12 = OpConstant %6 2.0 -%13 = OpConstant %6 3.0 -%14 = OpConstant %9 0 -%15 = OpConstant %9 1 -%16 = OpConstant %4 5 -%17 = OpConstant %4 3 -%18 = OpConstant %4 4 -%19 = OpConstant %4 42 -%21 = OpTypeVector %6 4 -%20 = OpTypeMatrix %21 4 -%22 = OpTypeVector %9 2 -%23 = OpTypeArray %22 %3 -%24 = OpTypeRuntimeArray %4 -%25 = OpTypeStruct %20 %4 %23 %24 -%26 = OpTypeArray %4 %16 -%28 = OpTypePointer StorageBuffer %25 -%27 = OpVariable %28 StorageBuffer -%30 = OpTypePointer Function %6 -%32 = OpTypePointer Function %26 -%35 = OpTypePointer Input %9 -%34 = OpVariable %35 Input -%38 = OpTypePointer Output %21 -%37 = OpVariable %38 Output -%40 = OpTypeFunction %2 -%43 = OpTypePointer StorageBuffer %20 -%46 = OpTypePointer StorageBuffer %23 -%49 = OpTypePointer StorageBuffer %21 -%50 = OpTypePointer StorageBuffer %6 -%53 = OpTypePointer StorageBuffer %24 -%56 = OpTypePointer StorageBuffer %4 -%73 = OpTypePointer Function %4 -%77 = OpTypeVector %4 4 -%85 = OpTypePointer StorageBuffer %4 -%88 = OpConstant %9 64 -%39 = OpFunction %2 None %40 -%33 = OpLabel -%29 = OpVariable %30 Function %5 -%31 = OpVariable %32 Function -%36 = OpLoad %9 %34 -OpBranch %41 +%11 = OpConstant %4 0 +%12 = OpConstant %4 1 +%13 = OpConstant %6 2.0 +%14 = OpConstant %6 3.0 +%15 = OpConstant %9 0 +%16 = OpConstant %9 1 +%17 = OpConstant %4 5 +%18 = OpConstant %4 3 +%19 = OpConstant %4 4 +%20 = OpConstant %4 42 +%22 = OpTypeVector %6 4 +%21 = OpTypeMatrix %22 4 +%23 = OpTypeVector %9 2 +%24 = OpTypeArray %23 %3 +%25 = OpTypeRuntimeArray %4 +%26 = OpTypeStruct %21 %4 %24 %25 +%27 = OpTypePointer Function %6 +%28 = OpTypePointer StorageBuffer %4 +%29 = OpTypeArray %4 %17 +%31 = OpTypePointer StorageBuffer %26 +%30 = OpVariable %31 StorageBuffer +%35 = OpTypeFunction %6 %27 +%40 = OpTypePointer Function %29 +%43 = OpTypePointer Input %9 +%42 = OpVariable %43 Input +%46 = OpTypePointer Output %22 +%45 = OpVariable %46 Output +%48 = OpTypeFunction %2 +%51 = OpTypePointer StorageBuffer %21 +%54 = OpTypePointer StorageBuffer %24 +%57 = OpTypePointer StorageBuffer %22 +%58 = OpTypePointer StorageBuffer %6 +%61 = OpTypePointer StorageBuffer %25 +%81 = OpTypePointer Function %4 +%85 = OpTypeVector %4 4 +%93 = OpTypePointer StorageBuffer %4 +%96 = OpConstant %9 64 +%34 = OpFunction %6 None %35 +%33 = OpFunctionParameter %27 +%32 = OpLabel +OpBranch %36 +%36 = OpLabel +%37 = OpLoad %6 %33 +OpReturnValue %37 +OpFunctionEnd +%47 = OpFunction %2 None %48 %41 = OpLabel -%42 = OpLoad %6 %29 -OpStore %29 %7 -%44 = OpAccessChain %43 %27 %14 -%45 = OpLoad %20 %44 -%47 = OpAccessChain %46 %27 %10 -%48 = OpLoad %23 %47 -%51 = OpAccessChain %50 %27 %14 %8 %14 -%52 = OpLoad %6 %51 -%54 = OpArrayLength %9 %27 3 -%55 = OpISub %9 %54 %10 -%57 = OpAccessChain %56 %27 %8 %55 -%58 = OpLoad %4 %57 -%59 = OpAccessChain %50 %27 %14 %15 %10 -OpStore %59 %7 -%60 = OpCompositeConstruct %21 %5 %5 %5 %5 -%61 = OpCompositeConstruct %21 %7 %7 %7 %7 -%62 = OpCompositeConstruct %21 %12 %12 %12 %12 -%63 = OpCompositeConstruct %21 %13 %13 %13 %13 -%64 = OpCompositeConstruct %20 %60 %61 %62 %63 -%65 = OpAccessChain %43 %27 %14 -OpStore %65 %64 -%66 = OpCompositeConstruct %22 %14 %14 -%67 = OpCompositeConstruct %22 %15 %15 -%68 = OpCompositeConstruct %23 %66 %67 -%69 = OpAccessChain %46 %27 %10 -OpStore %69 %68 -%70 = OpConvertFToS %4 %52 -%71 = OpCompositeConstruct %26 %58 %70 %17 %18 %16 -OpStore %31 %71 -%72 = OpIAdd %9 %36 %15 -%74 = OpAccessChain %73 %31 %72 -OpStore %74 %19 -%75 = OpAccessChain %73 %31 %36 -%76 = OpLoad %4 %75 -%78 = OpCompositeConstruct %77 %76 %76 %76 %76 -%79 = OpConvertSToF %21 %78 -%80 = OpMatrixTimesVector %21 %45 %79 -OpStore %37 %80 +%38 = OpVariable %27 Function %5 +%39 = OpVariable %40 Function +%44 = OpLoad %9 %42 +OpBranch %49 +%49 = OpLabel +%50 = OpLoad %6 %38 +OpStore %38 %7 +%52 = OpAccessChain %51 %30 %15 +%53 = OpLoad %21 %52 +%55 = OpAccessChain %54 %30 %10 +%56 = OpLoad %24 %55 +%59 = OpAccessChain %58 %30 %15 %8 %15 +%60 = OpLoad %6 %59 +%62 = OpArrayLength %9 %30 3 +%63 = OpISub %9 %62 %10 +%64 = OpAccessChain %28 %30 %8 %63 +%65 = OpLoad %4 %64 +%66 = OpFunctionCall %6 %34 %38 +%67 = OpAccessChain %58 %30 %15 %16 %10 +OpStore %67 %7 +%68 = OpCompositeConstruct %22 %5 %5 %5 %5 +%69 = OpCompositeConstruct %22 %7 %7 %7 %7 +%70 = OpCompositeConstruct %22 %13 %13 %13 %13 +%71 = OpCompositeConstruct %22 %14 %14 %14 %14 +%72 = OpCompositeConstruct %21 %68 %69 %70 %71 +%73 = OpAccessChain %51 %30 %15 +OpStore %73 %72 +%74 = OpCompositeConstruct %23 %15 %15 +%75 = OpCompositeConstruct %23 %16 %16 +%76 = OpCompositeConstruct %24 %74 %75 +%77 = OpAccessChain %54 %30 %10 +OpStore %77 %76 +%78 = OpConvertFToS %4 %60 +%79 = OpCompositeConstruct %29 %65 %78 %18 %19 %17 +OpStore %39 %79 +%80 = OpIAdd %9 %44 %16 +%82 = OpAccessChain %81 %39 %80 +OpStore %82 %20 +%83 = OpAccessChain %81 %39 %44 +%84 = OpLoad %4 %83 +%86 = OpCompositeConstruct %85 %84 %84 %84 %84 +%87 = OpConvertSToF %22 %86 +%88 = OpMatrixTimesVector %22 %53 %87 +OpStore %45 %88 OpReturn OpFunctionEnd -%83 = OpFunction %2 None %40 -%82 = OpLabel -%81 = OpVariable %73 Function -OpBranch %84 -%84 = OpLabel -%86 = OpAccessChain %85 %27 %15 -%87 = OpAtomicLoad %4 %86 %11 %88 -%90 = OpAccessChain %85 %27 %15 -%89 = OpAtomicIAdd %4 %90 %11 %88 %16 -OpStore %81 %89 -%92 = OpAccessChain %85 %27 %15 -%91 = OpAtomicISub %4 %92 %11 %88 %16 -OpStore %81 %91 -%94 = OpAccessChain %85 %27 %15 -%93 = OpAtomicAnd %4 %94 %11 %88 %16 -OpStore %81 %93 -%96 = OpAccessChain %85 %27 %15 -%95 = OpAtomicOr %4 %96 %11 %88 %16 -OpStore %81 %95 -%98 = OpAccessChain %85 %27 %15 -%97 = OpAtomicXor %4 %98 %11 %88 %16 -OpStore %81 %97 -%100 = OpAccessChain %85 %27 %15 -%99 = OpAtomicSMin %4 %100 %11 %88 %16 -OpStore %81 %99 -%102 = OpAccessChain %85 %27 %15 -%101 = OpAtomicSMax %4 %102 %11 %88 %16 -OpStore %81 %101 -%104 = OpAccessChain %85 %27 %15 -%103 = OpAtomicExchange %4 %104 %11 %88 %16 -OpStore %81 %103 -%105 = OpAccessChain %85 %27 %15 -OpAtomicStore %105 %11 %88 %87 +%91 = OpFunction %2 None %48 +%90 = OpLabel +%89 = OpVariable %81 Function +OpBranch %92 +%92 = OpLabel +%94 = OpAccessChain %93 %30 %16 +%95 = OpAtomicLoad %4 %94 %12 %96 +%98 = OpAccessChain %93 %30 %16 +%97 = OpAtomicIAdd %4 %98 %12 %96 %17 +OpStore %89 %97 +%100 = OpAccessChain %93 %30 %16 +%99 = OpAtomicISub %4 %100 %12 %96 %17 +OpStore %89 %99 +%102 = OpAccessChain %93 %30 %16 +%101 = OpAtomicAnd %4 %102 %12 %96 %17 +OpStore %89 %101 +%104 = OpAccessChain %93 %30 %16 +%103 = OpAtomicOr %4 %104 %12 %96 %17 +OpStore %89 %103 +%106 = OpAccessChain %93 %30 %16 +%105 = OpAtomicXor %4 %106 %12 %96 %17 +OpStore %89 %105 +%108 = OpAccessChain %93 %30 %16 +%107 = OpAtomicSMin %4 %108 %12 %96 %17 +OpStore %89 %107 +%110 = OpAccessChain %93 %30 %16 +%109 = OpAtomicSMax %4 %110 %12 %96 %17 +OpStore %89 %109 +%112 = OpAccessChain %93 %30 %16 +%111 = OpAtomicExchange %4 %112 %12 %96 %17 +OpStore %89 %111 +%113 = OpAccessChain %93 %30 %16 +OpAtomicStore %113 %12 %96 %95 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 143960419..11ef27c13 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -9,6 +9,11 @@ struct Bar { [[group(0), binding(0)]] var bar: Bar; +fn read_from_private(foo2: ptr) -> f32 { + let e2: f32 = (*foo2); + return e2; +} + [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { var foo1: f32 = 0.0; @@ -20,6 +25,8 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let arr: array,2> = bar.arr; let b: f32 = bar.matrix[3][0]; let a: i32 = bar.data[(arrayLength((&bar.data)) - 2u)]; + let pointer1: ptr = (&bar.data[0]); + let e25: f32 = read_from_private((&foo1)); bar.matrix[1][2] = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 64e3cdae8..504a630bb 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -5,11 +5,11 @@ var image_multisampled_src: texture_multisampled_2d; [[group(0), binding(4)]] var image_depth_multisampled_src: texture_depth_multisampled_2d; [[group(0), binding(1)]] -var image_storage_src: texture_storage_2d; +var image_storage_src: texture_storage_2d; [[group(0), binding(5)]] var image_array_src: texture_2d_array; [[group(0), binding(6)]] -var image_dup_src: texture_storage_1d; +var image_dup_src: texture_storage_1d; [[group(0), binding(2)]] var image_dst: texture_storage_1d; [[group(0), binding(0)]] diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b34aadf84..35ed0cf13 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -267,7 +267,8 @@ fn write_output_msl( allow_point_size: true, }; - let (string, tr_info) = msl::write_string(module, info, options, &pipeline_options).unwrap(); + let (string, tr_info) = + msl::write_string(module, info, options, &pipeline_options).expect("Metal write failed"); for (ep, result) in module.entry_points.iter().zip(tr_info.entry_point_names) { if let Err(error) = result { @@ -308,9 +309,9 @@ fn write_output_glsl( }; let mut buffer = String::new(); - let mut writer = - glsl::Writer::new(&mut buffer, module, info, options, &pipeline_options).unwrap(); - writer.write().unwrap(); + let mut writer = glsl::Writer::new(&mut buffer, module, info, options, &pipeline_options) + .expect("GLSL init failed"); + writer.write().expect("GLSL write failed"); fs::write( destination.join(format!("glsl/{}.{}.{:?}.glsl", file_name, ep_name, stage)), @@ -344,7 +345,7 @@ fn write_output_hlsl( let mut buffer = String::new(); let mut writer = hlsl::Writer::new(&mut buffer, options); - let reflection_info = writer.write(module, info).unwrap(); + let reflection_info = writer.write(module, info).expect("HLSL write failed"); fs::write(destination.join(format!("hlsl/{}.hlsl", file_name)), buffer).unwrap(); @@ -417,7 +418,7 @@ fn write_output_wgsl( ) { use naga::back::wgsl; - let string = wgsl::write_string(module, info).unwrap(); + let string = wgsl::write_string(module, info).expect("WGSL write failed"); fs::write(destination.join(format!("wgsl/{}.wgsl", file_name)), string).unwrap(); } @@ -572,8 +573,8 @@ fn convert_spv_inverse_hyperbolic_trig_functions() { } #[cfg(all(feature = "spv-in", feature = "spv-out"))] -#[test] -fn convert_spv_pointer_access() { +//#[test] //TODO: https://github.com/gfx-rs/naga/issues/1432 +fn _convert_spv_pointer_access() { convert_spv("pointer-access", true, Targets::SPIRV); } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index f1b3fc55b..8ccfdfa0e 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -677,14 +677,30 @@ fn invalid_functions() { if function_name == "unacceptable_unsized" && argument_name == "arg" } - // A *valid* way to pass an unsized value. check_validation_error! { " struct Unsized { data: array; }; - fn acceptable_ptr_to_unsized(okay: ptr) { } + fn acceptable_pointer_to_unsized(arg: ptr) { } ": Ok(_) } + + check_validation_error! { + " + struct Unsized { data: array; }; + fn unacceptable_uniform_class(arg: ptr) { } + ": + Err(naga::valid::ValidationError::Function { + name: function_name, + error: naga::valid::FunctionError::InvalidArgumentPointerClass { + index: 0, + name: argument_name, + class: naga::StorageClass::Uniform, + }, + .. + }) + if function_name == "unacceptable_uniform_class" && argument_name == "arg" + } } #[test] From 004a12e21d470c854c539d882bae8c953683b202 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 27 Sep 2021 19:00:10 -0400 Subject: [PATCH 1386/2212] [spv-out] option to clamp frag_depth (#1431) --- src/back/spv/block.rs | 130 +++++++++++++++++------- src/back/spv/mod.rs | 6 +- tests/in/interface.param.ron | 1 + tests/out/spv/interface.fragment.spvasm | 13 ++- tests/out/spv/quad.spvasm | 12 +-- tests/snapshots.rs | 6 ++ 6 files changed, 119 insertions(+), 49 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index e9970c23c..491ab79ce 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -20,6 +20,87 @@ fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { } impl Writer { + // Flip Y coordinate to adjust for coordinate space difference + // between SPIR-V and our IR. + // The `position_id` argument is a pointer to a `vecN`, + // whose `y` component we will negate. + fn write_epilogue_position_y_flip( + &mut self, + position_id: Word, + body: &mut Vec, + ) -> Result<(), Error> { + let float_ptr_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: Some(spirv::StorageClass::Output), + })); + let index_y_id = self.get_index_constant(1); + let access_id = self.id_gen.next(); + body.push(Instruction::access_chain( + float_ptr_type_id, + access_id, + position_id, + &[index_y_id], + )); + + let float_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + })); + let load_id = self.id_gen.next(); + body.push(Instruction::load(float_type_id, load_id, access_id, None)); + + let neg_id = self.id_gen.next(); + body.push(Instruction::unary( + spirv::Op::FNegate, + float_type_id, + neg_id, + load_id, + )); + + body.push(Instruction::store(access_id, neg_id, None)); + Ok(()) + } + + // Clamp fragment depth between 0 and 1. + fn write_epilogue_frag_depth_clamp( + &mut self, + frag_depth_id: Word, + body: &mut Vec, + ) -> Result<(), Error> { + let float_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width: 4, + pointer_class: None, + })); + let value0_id = self.get_constant_scalar(crate::ScalarValue::Float(0.0), 4); + let value1_id = self.get_constant_scalar(crate::ScalarValue::Float(1.0), 4); + + let original_id = self.id_gen.next(); + body.push(Instruction::load( + float_type_id, + original_id, + frag_depth_id, + None, + )); + + let clamp_id = self.id_gen.next(); + body.push(Instruction::ext_inst( + self.gl450_ext_inst_id, + spirv::GLOp::FClamp, + float_type_id, + clamp_id, + &[original_id, value0_id, value1_id], + )); + + body.push(Instruction::store(frag_depth_id, clamp_id, None)); + Ok(()) + } + fn write_entry_point_return( &mut self, value_id: Word, @@ -44,43 +125,18 @@ impl Writer { body.push(Instruction::store(res_member.id, member_value_id, None)); - // Flip Y coordinate to adjust for coordinate space difference - // between SPIR-V and our IR. - if self.flags.contains(WriterFlags::ADJUST_COORDINATE_SPACE) - && res_member.built_in == Some(crate::BuiltIn::Position) - { - let access_id = self.id_gen.next(); - let float_ptr_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: Some(spirv::StorageClass::Output), - })); - let index_y_id = self.get_index_constant(1); - body.push(Instruction::access_chain( - float_ptr_type_id, - access_id, - res_member.id, - &[index_y_id], - )); - - let load_id = self.id_gen.next(); - let float_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width: 4, - pointer_class: None, - })); - body.push(Instruction::load(float_type_id, load_id, access_id, None)); - - let neg_id = self.id_gen.next(); - body.push(Instruction::unary( - spirv::Op::FNegate, - float_type_id, - neg_id, - load_id, - )); - body.push(Instruction::store(access_id, neg_id, None)); + match res_member.built_in { + Some(crate::BuiltIn::Position) + if self.flags.contains(WriterFlags::ADJUST_COORDINATE_SPACE) => + { + self.write_epilogue_position_y_flip(res_member.id, body)?; + } + Some(crate::BuiltIn::FragDepth) + if self.flags.contains(WriterFlags::CLAMP_FRAG_DEPTH) => + { + self.write_epilogue_frag_depth_clamp(res_member.id, body)?; + } + _ => {} } } Ok(()) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 7acbd3b6d..4eb75706b 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -568,6 +568,8 @@ bitflags::bitflags! { /// Emit `PointSize` output builtin to vertex shaders, which is /// required for drawing with `PointList` topology. const FORCE_POINT_SIZE = 0x8; + /// Clamp `BuiltIn::FragDepth` output between 0 and 1. + const CLAMP_FRAG_DEPTH = 0x10; } } @@ -592,7 +594,9 @@ pub struct Options { impl Default for Options { fn default() -> Self { - let mut flags = WriterFlags::ADJUST_COORDINATE_SPACE | WriterFlags::LABEL_VARYINGS; + let mut flags = WriterFlags::ADJUST_COORDINATE_SPACE + | WriterFlags::LABEL_VARYINGS + | WriterFlags::CLAMP_FRAG_DEPTH; if cfg!(debug_assertions) { flags |= WriterFlags::DEBUG; } diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index fdca2996b..4e32d785c 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -4,6 +4,7 @@ capabilities: [ Shader, SampleRateShading ], adjust_coordinate_space: false, force_point_size: true, + clamp_frag_depth: true, separate_entry_points: true, ), hlsl_custom: true, diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 425344990..5e7b97af1 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 49 +; Bound: 51 OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" @@ -70,9 +70,12 @@ OpBranch %40 %45 = OpCompositeConstruct %13 %44 %42 %43 %46 = OpCompositeExtract %4 %45 0 OpStore %33 %46 -%47 = OpCompositeExtract %6 %45 1 -OpStore %35 %47 -%48 = OpCompositeExtract %4 %45 2 -OpStore %37 %48 +%47 = OpLoad %4 %33 +%48 = OpExtInst %4 %1 FClamp %47 %7 %3 +OpStore %33 %48 +%49 = OpCompositeExtract %6 %45 1 +OpStore %35 %49 +%50 = OpCompositeExtract %4 %45 2 +OpStore %37 %50 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/quad.spvasm b/tests/out/spv/quad.spvasm index cbf63236d..c3a70b0e1 100644 --- a/tests/out/spv/quad.spvasm +++ b/tests/out/spv/quad.spvasm @@ -61,9 +61,9 @@ OpDecorate %60 Location 0 %26 = OpTypePointer Output %9 %25 = OpVariable %26 Output %28 = OpTypeFunction %2 -%36 = OpTypePointer Output %4 -%38 = OpTypeInt 32 0 -%37 = OpConstant %38 1 +%35 = OpTypePointer Output %4 +%37 = OpTypeInt 32 0 +%36 = OpConstant %37 1 %42 = OpVariable %19 Input %44 = OpVariable %26 Output %49 = OpTypeSampledImage %11 @@ -82,10 +82,10 @@ OpBranch %29 OpStore %23 %33 %34 = OpCompositeExtract %9 %32 1 OpStore %25 %34 -%35 = OpAccessChain %36 %25 %37 -%39 = OpLoad %4 %35 +%38 = OpAccessChain %35 %25 %36 +%39 = OpLoad %4 %38 %40 = OpFNegate %4 %39 -OpStore %35 %40 +OpStore %38 %40 OpReturn OpFunctionEnd %45 = OpFunction %2 None %28 diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 35ed0cf13..cecf8a4fc 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -62,6 +62,8 @@ struct SpirvOutParameters { #[serde(default)] force_point_size: bool, #[serde(default)] + clamp_frag_depth: bool, + #[serde(default)] separate_entry_points: bool, } @@ -201,6 +203,10 @@ fn write_output_spv( spv::WriterFlags::FORCE_POINT_SIZE, params.spv.force_point_size, ); + flags.set( + spv::WriterFlags::CLAMP_FRAG_DEPTH, + params.spv.clamp_frag_depth, + ); let options = spv::Options { lang_version: (params.spv.version.0, params.spv.version.1), flags, From 3e992d8bbfa1c587c5fc6ba760d286c9a4977e84 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 27 Sep 2021 16:17:20 -0700 Subject: [PATCH 1387/2212] Address 'unused variable' warnings when 'span' feature is off. (#1433) --- src/arena.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/arena.rs b/src/arena.rs index 5e1c65cf7..536a4bd28 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -489,6 +489,9 @@ impl UniqueArena { debug_assert!(self.set.len() == self.span_info.len()); } + #[cfg(not(feature = "span"))] + let _ = (span, added); + Handle::from_usize(index) } From 2e73e486570e62171058bbfe88a69f2de50997ad Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 28 Sep 2021 10:42:26 -0700 Subject: [PATCH 1388/2212] When writing snapshots, reliably identify which writer has failed. (#1427) --- tests/snapshots.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index cecf8a4fc..102a4864f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -130,7 +130,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities) .validate(module) - .unwrap(); + .expect("Naga module validation failed"); #[cfg(feature = "serialize")] { @@ -193,6 +193,7 @@ fn write_output_spv( use naga::back::spv; use rspirv::binary::Disassemble; + println!("writing SPIR-V"); let mut flags = spv::WriterFlags::LABEL_VARYINGS; flags.set(spv::WriterFlags::DEBUG, params.spv.debug); flags.set( @@ -257,6 +258,8 @@ fn write_output_msl( ) { use naga::back::msl; + println!("writing MSL"); + #[cfg_attr(feature = "deserialize", allow(unused_variables))] let default_options = msl::Options::default(); #[cfg(feature = "deserialize")] @@ -297,6 +300,8 @@ fn write_output_glsl( ) { use naga::back::glsl; + println!("writing GLSL"); + #[cfg_attr(feature = "deserialize", allow(unused_variables))] let default_options = glsl::Options::default(); #[cfg(feature = "deserialize")] @@ -337,6 +342,8 @@ fn write_output_hlsl( use naga::back::hlsl; use std::fmt::Write; + println!("writing HLSL"); + #[cfg_attr(feature = "deserialize", allow(unused_variables))] let default_options = hlsl::Options::default(); #[cfg(feature = "deserialize")] @@ -424,6 +431,8 @@ fn write_output_wgsl( ) { use naga::back::wgsl; + println!("writing WGSL"); + let string = wgsl::write_string(module, info).expect("WGSL write failed"); fs::write(destination.join(format!("wgsl/{}.wgsl", file_name)), string).unwrap(); From a4bf25a0d5b87a7f0fdd85eac1e2e5041d536f21 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 29 Sep 2021 19:24:34 +0300 Subject: [PATCH 1389/2212] Emit std430 layout qualifiers for storage buffers (#1435) * Remove unused petgraph dependency from glsl-out * Emit std430 layout qualifiers for storage buffers --- Cargo.toml | 2 +- src/back/glsl/mod.rs | 28 +++++++++++++++++++-- tests/out/glsl/access.atomics.Compute.glsl | 2 +- tests/out/glsl/access.foo.Vertex.glsl | 2 +- tests/out/glsl/boids.main.Compute.glsl | 4 +-- tests/out/glsl/shadow.fs_main.Fragment.glsl | 2 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 2 +- 7 files changed, 33 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8d577643d..26b1d3e94 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,7 +35,7 @@ default = [] dot-out = [] glsl-in = ["pp-rs"] glsl-validate = [] -glsl-out = ["petgraph"] +glsl-out = [] msl-out = [] serialize = ["serde", "indexmap/serde-1"] deserialize = ["serde", "indexmap/serde-1"] diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9b171fd9e..fe6f4e2e8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -129,6 +129,10 @@ impl Version { fn supports_early_depth_test(&self) -> bool { *self >= Version::Desktop(130) || *self >= Version::Embedded(310) } + + fn supports_std430_layout(&self) -> bool { + *self >= Version::Desktop(430) || *self >= Version::Embedded(310) + } } impl PartialOrd for Version { @@ -816,8 +820,28 @@ impl<'a, W: Write> Writer<'a, W> { if self.options.version.supports_explicit_locations() { if let Some(ref br) = global.binding { match self.options.binding_map.get(br) { - Some(binding) => write!(self.out, "layout(binding = {}) ", binding)?, - None => log::debug!("unassigned binding for {:?}", global.name), + Some(binding) => { + let layout = match global.class { + crate::StorageClass::Storage { .. } => { + if self.options.version.supports_std430_layout() { + "std430, " + } else { + "std140, " + } + } + crate::StorageClass::Uniform => "std140, ", + _ => "", + }; + write!(self.out, "layout({}binding = {}) ", layout, binding)? + } + None => { + log::debug!("unassigned binding for {:?}", global.name); + if let crate::StorageClass::Storage { .. } = global.class { + if self.options.version.supports_std430_layout() { + write!(self.out, "layout(std430) ")? + } + } + } } } } diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 958cd5a6a..81eb83e53 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -5,7 +5,7 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; -buffer Bar_block_0Cs { +layout(std430) buffer Bar_block_0Cs { mat4x4 matrix; int atom; uvec2 arr[2]; diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index 97248f546..680f52ee5 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -3,7 +3,7 @@ precision highp float; precision highp int; -buffer Bar_block_0Vs { +layout(std430) buffer Bar_block_0Vs { mat4x4 matrix; int atom; uvec2 arr[2]; diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index b14406715..51bf0101f 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -20,11 +20,11 @@ uniform SimParams_block_0Cs { float rule3Scale; } _group_0_binding_0; -readonly buffer Particles_block_1Cs { +layout(std430) readonly buffer Particles_block_1Cs { Particle particles[]; } _group_0_binding_1; -buffer Particles_block_2Cs { +layout(std430) buffer Particles_block_2Cs { Particle particles[]; } _group_0_binding_2; diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index a856f247f..7220591b9 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -13,7 +13,7 @@ uniform Globals_block_0Fs { uvec4 num_lights; } _group_0_binding_0; -readonly buffer Lights_block_1Fs { +layout(std430) readonly buffer Lights_block_1Fs { Light data[]; } _group_0_binding_1; diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index 5f66bc1c6..06494a70f 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -8,7 +8,7 @@ struct VertexOutput { vec3 uv; }; -layout(binding = 0) uniform Data_block_0Vs { +layout(std140, binding = 0) uniform Data_block_0Vs { mat4x4 proj_inv; mat4x4 view; } _group_0_binding_0; From 92a97fb7d5a5edfe363b38f69cff22ba0a7bc1d0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 29 Sep 2021 12:55:37 -0700 Subject: [PATCH 1390/2212] Simplify implementation of `Namer::namespace`. (#1438) Eliminate `Namer::namespace_index` and remove namespace indices from `Namer::unique` keys. Instead, implement `Namer::namespace` by just swapping in a fresh table for the duration of the call. Create the fresh hash table with the right initial capacity. The prior implementation did manage to avoid allocations by sharing a hash table, and we'd like to not lose that advantage entirely. This has no effect on generated code. --- src/proc/namer.rs | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/src/proc/namer.rs b/src/proc/namer.rs index f250fc1f6..9b557932d 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -21,10 +21,9 @@ pub enum NameKey { /// that may need identifiers in a textual backend. #[derive(Default)] pub struct Namer { - unique: FastHashMap<(String, u32), u32>, + /// The last numeric suffix used for each base name. + unique: FastHashMap, keywords: FastHashSet, - /// Currently active namespace. - namespace_index: u32, reserved_prefixes: Vec, } @@ -55,14 +54,14 @@ impl Namer { /// This function should be used **after** [`Namer`](crate::proc::Namer) initialization by [`reset`](Self::reset()) function. pub fn call_unique(&mut self, string: &str) -> String { let base = self.sanitize(string); - match self.unique.entry((base, self.namespace_index)) { + match self.unique.entry(base) { Entry::Occupied(mut e) => { *e.get_mut() += 1; - format!("{}{}", e.key().0, e.get()) + format!("{}{}", e.key(), e.get()) } Entry::Vacant(e) => { - let name = &e.key().0; - if self.keywords.contains(&e.key().0) { + let name = e.key(); + if self.keywords.contains(e.key()) { let name = format!("{}1", name); e.insert(1); name @@ -75,14 +74,14 @@ impl Namer { pub fn call(&mut self, label_raw: &str) -> String { let base = self.sanitize(label_raw); - match self.unique.entry((base, self.namespace_index)) { + match self.unique.entry(base) { Entry::Occupied(mut e) => { *e.get_mut() += 1; - format!("{}{}", e.key().0, e.get()) + format!("{}{}", e.key(), e.get()) } Entry::Vacant(e) => { - let name = &e.key().0; - if self.keywords.contains(&e.key().0) { + let name = e.key(); + if self.keywords.contains(e.key()) { let name = format!("{}1", name); e.insert(1); name @@ -102,12 +101,16 @@ impl Namer { }) } - fn namespace(&mut self, f: impl FnOnce(&mut Self)) { - self.namespace_index += 1; - f(self); - let current_ns = self.namespace_index; - self.unique.retain(|&(_, ns), _| ns != current_ns); - self.namespace_index -= 1; + /// Enter a local namespace for things like structs. + /// + /// Struct member names only need to be unique amongst themselves, not + /// globally. This function temporarily establishes a fresh, empty naming + /// context for the duration of the call to `body`. + fn namespace(&mut self, capacity: usize, body: impl FnOnce(&mut Self)) { + let fresh = FastHashMap::with_capacity_and_hasher(capacity, Default::default()); + let outer = std::mem::replace(&mut self.unique, fresh); + body(self); + self.unique = outer; } pub fn reset( @@ -133,7 +136,7 @@ impl Namer { if let crate::TypeInner::Struct { ref members, .. } = ty.inner { // struct members have their own namespace, because access is always prefixed - self.namespace(|namer| { + self.namespace(members.len(), |namer| { for (index, member) in members.iter().enumerate() { let name = namer.call_or(&member.name, "member"); output.insert(NameKey::StructMember(ty_handle, index as u32), name); From 4ef1cc403b0a6be96e88f73f1e71680a97199cb1 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 29 Sep 2021 16:33:38 -0700 Subject: [PATCH 1391/2212] Remove Namer::call_unique. (#1439) Replace uses of `call_unique` with uses of `call` and `call_or`, which becomes public. It's not clear when `call_unique` is correct to use, and avoiding a few numeric suffixes here and there isn't worth it. --- src/back/glsl/mod.rs | 2 +- src/back/hlsl/writer.rs | 26 +++++++------------------- src/back/msl/writer.rs | 2 +- src/back/wgsl/writer.rs | 2 +- src/proc/namer.rs | 24 +----------------------- tests/out/hlsl/access.hlsl | 4 ++-- tests/out/hlsl/image.hlsl | 6 +++--- tests/out/hlsl/interface.hlsl | 6 +++--- tests/out/hlsl/interpolate.hlsl | 16 ++++++++-------- tests/out/hlsl/skybox.hlsl | 6 +++--- tests/out/msl/access.msl | 4 ++-- tests/out/msl/image.msl | 6 +++--- tests/out/wgsl/access.wgsl | 4 ++-- tests/out/wgsl/image.wgsl | 6 +++--- 14 files changed, 40 insertions(+), 74 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index fe6f4e2e8..60e0d57b0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1370,7 +1370,7 @@ impl<'a, W: Write> Writer<'a, W> { // But we write them to step by step. We need to recache them // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. - Some(self.namer.call_unique(name)) + Some(self.namer.call(name)) } else { let min_ref_count = ctx.expressions[handle].bake_ref_count(); if min_ref_count <= info.ref_count { diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 339523f40..883b67d13 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -368,7 +368,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } Ok(EntryPointBinding { - arg_name: self.namer.call_unique(struct_name.to_lowercase().as_str()), + arg_name: self.namer.call(struct_name.to_lowercase().as_str()), ty_name: struct_name, members, }) @@ -391,14 +391,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match module.types[arg.ty].inner { TypeInner::Struct { ref members, .. } => { for member in members.iter() { - let member_name = if let Some(ref name) = member.name { - name - } else { - "member" - }; + let name = self.namer.call_or(&member.name, "member"); let index = fake_members.len() as u32; fake_members.push(EpStructMember { - name: self.namer.call(member_name), + name, ty: member.ty, binding: member.binding.clone(), index, @@ -406,11 +402,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } _ => { - let member_name = if let Some(ref name) = arg.name { - self.namer.call_unique(name) - } else { - self.namer.call("member") - }; + let member_name = self.namer.call_or(&arg.name, "member"); let index = fake_members.len() as u32; fake_members.push(EpStructMember { name: member_name, @@ -448,11 +440,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; for member in members.iter() { - let member_name = if let Some(ref name) = member.name { - self.namer.call_unique(name) - } else { - self.namer.call("member") - }; + let member_name = self.namer.call_or(&member.name, "member"); let index = fake_members.len() as u32; fake_members.push(EpStructMember { name: member_name, @@ -1069,7 +1057,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // But we write them to step by step. We need to recache them // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. - Some(self.namer.call_unique(name)) + Some(self.namer.call(name)) } else { let min_ref_count = func_ctx.expressions[handle].bake_ref_count(); if min_ref_count <= info.ref_count { @@ -1159,7 +1147,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; let final_name = match ep_output { Some(ep_output) => { - let final_name = self.namer.call_unique(&variable_name); + let final_name = self.namer.call(&variable_name); write!( self.out, "{}const {} {} = {{ ", diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 78d56aa0c..a34fbfdd0 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1397,7 +1397,7 @@ impl Writer { // But we write them to step by step. We need to recache them // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. - Some(self.namer.call_unique(name)) + Some(self.namer.call(name)) } else { let min_ref_count = context.expression.function.expressions[handle].bake_ref_count(); diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index c108d90e8..a215722fb 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -676,7 +676,7 @@ impl Writer { // But we write them to step by step. We need to recache them // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. - Some(self.namer.call_unique(name)) + Some(self.namer.call(name)) } else { let expr = &func_ctx.expressions[handle]; let min_ref_count = expr.bake_ref_count(); diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 9b557932d..0c2038cbf 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -50,28 +50,6 @@ impl Namer { base } - /// Helper function that return unique name without cache update. - /// This function should be used **after** [`Namer`](crate::proc::Namer) initialization by [`reset`](Self::reset()) function. - pub fn call_unique(&mut self, string: &str) -> String { - let base = self.sanitize(string); - match self.unique.entry(base) { - Entry::Occupied(mut e) => { - *e.get_mut() += 1; - format!("{}{}", e.key(), e.get()) - } - Entry::Vacant(e) => { - let name = e.key(); - if self.keywords.contains(e.key()) { - let name = format!("{}1", name); - e.insert(1); - name - } else { - name.to_string() - } - } - } - } - pub fn call(&mut self, label_raw: &str) -> String { let base = self.sanitize(label_raw); match self.unique.entry(base) { @@ -94,7 +72,7 @@ impl Namer { } } - fn call_or(&mut self, label: &Option, fallback: &str) -> String { + pub fn call_or(&mut self, label: &Option, fallback: &str) -> String { self.call(match *label { Some(ref name) => name, None => fallback, diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index fe8c701ca..41b7acc84 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -53,7 +53,7 @@ void atomics() { int tmp = (int)0; - int value = asint(bar.Load(64)); + int value1 = asint(bar.Load(64)); int _e6; bar.InterlockedAdd(64, 5, _e6); tmp = _e6; int _e9; bar.InterlockedAdd(64, -5, _e9); @@ -70,6 +70,6 @@ void atomics() tmp = _e24; int _e27; bar.InterlockedExchange(64, 5, _e27); tmp = _e27; - bar.Store(64, asuint(value)); + bar.Store(64, asuint(value1)); return; } diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index d53a95844..4eb297de5 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -208,8 +208,8 @@ float4 sample1() : SV_Target0 float sample_comparison() : SV_Target0 { - float2 tc = float2(0.5.xx); - float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc, 0.5); - float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc, 0.5); + float2 tc1 = float2(0.5.xx); + float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc1, 0.5); + float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc1, 0.5); return (s2d_depth + s2d_depth_level); } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 3c4334def..38d6cb820 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -24,8 +24,8 @@ struct VertexOutput_vertex { }; struct FragmentInput_fragment { - float varying : LOC1; - float4 position : SV_Position; + float varying1 : LOC1; + float4 position1 : SV_Position; bool front_facing1 : SV_IsFrontFace; uint sample_index1 : SV_SampleIndex; uint sample_mask1 : SV_Coverage; @@ -56,7 +56,7 @@ FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) { FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) { - VertexOutput in1 = { fragmentinput_fragment.position, fragmentinput_fragment.varying }; + VertexOutput in1 = { fragmentinput_fragment.position1, fragmentinput_fragment.varying1 }; bool front_facing = fragmentinput_fragment.front_facing1; uint sample_index = fragmentinput_fragment.sample_index1; uint sample_mask = fragmentinput_fragment.sample_mask1; diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index f4c56957c..788542e9e 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -22,14 +22,14 @@ struct VertexOutput_main { }; struct FragmentInput_main { - uint flat : LOC0; + uint flat1 : LOC0; float linear2 : LOC1; - float2 linear_centroid : LOC2; - float3 linear_sample : LOC3; - float4 perspective : LOC4; - float perspective_centroid : LOC5; - float perspective_sample : LOC6; - float4 position : SV_Position; + float2 linear_centroid1 : LOC2; + float3 linear_sample1 : LOC3; + float4 perspective1 : LOC4; + float perspective_centroid1 : LOC5; + float perspective_sample1 : LOC6; + float4 position1 : SV_Position; }; VertexOutput_main main() @@ -52,6 +52,6 @@ VertexOutput_main main() void main1(FragmentInput_main fragmentinput_main) { - FragmentInput val = { fragmentinput_main.position, fragmentinput_main.flat, fragmentinput_main.linear2, fragmentinput_main.linear_centroid, fragmentinput_main.linear_sample, fragmentinput_main.perspective, fragmentinput_main.perspective_centroid, fragmentinput_main.perspective_sample }; + FragmentInput val = { fragmentinput_main.position1, fragmentinput_main.flat1, fragmentinput_main.linear2, fragmentinput_main.linear_centroid1, fragmentinput_main.linear_sample1, fragmentinput_main.perspective1, fragmentinput_main.perspective_centroid1, fragmentinput_main.perspective_sample1 }; return; } diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index b598ad8d4..0120ff7fb 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -25,8 +25,8 @@ struct VertexOutput_vs_main { }; struct FragmentInput_fs_main { - float3 uv : LOC0; - float4 position : SV_Position; + float3 uv1 : LOC0; + float4 position1 : SV_Position; }; VertexOutput ConstructVertexOutput(float4 arg0, float3 arg1) { @@ -59,7 +59,7 @@ VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { - VertexOutput in1 = { fragmentinput_fs_main.position, fragmentinput_fs_main.uv }; + VertexOutput in1 = { fragmentinput_fs_main.position1, fragmentinput_fs_main.uv1 }; float4 _expr5 = r_texture.Sample(r_sampler, in1.uv); return _expr5; } diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 44134f29d..09f011fe4 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -62,7 +62,7 @@ kernel void atomics( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { int tmp; - int value = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); + int value1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); int _e6 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e6; int _e9 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); @@ -79,6 +79,6 @@ kernel void atomics( tmp = _e24; int _e27 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e27; - metal::atomic_store_explicit(&bar.atom, value, metal::memory_order_relaxed); + metal::atomic_store_explicit(&bar.atom, value1, metal::memory_order_relaxed); return; } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index ee635ab81..44fde4992 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -86,8 +86,8 @@ fragment sample_comparisonOutput sample_comparison( metal::sampler sampler_cmp [[user(fake0)]] , metal::depth2d image_2d_depth [[user(fake0)]] ) { - metal::float2 tc = metal::float2(0.5); - float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc, 0.5); - float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc, 0.5); + metal::float2 tc1 = metal::float2(0.5); + float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc1, 0.5); + float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc1, 0.5); return sample_comparisonOutput { s2d_depth + s2d_depth_level }; } diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 11ef27c13..c041a2047 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -40,7 +40,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { fn atomics() { var tmp: i32; - let value: i32 = atomicLoad((&bar.atom)); + let value1: i32 = atomicLoad((&bar.atom)); let e6: i32 = atomicAdd((&bar.atom), 5); tmp = e6; let e9: i32 = atomicSub((&bar.atom), 5); @@ -57,6 +57,6 @@ fn atomics() { tmp = e24; let e27: i32 = atomicExchange((&bar.atom), 5); tmp = e27; - atomicStore((&bar.atom), value); + atomicStore((&bar.atom), value1); return; } diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 504a630bb..166faf6d6 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -83,8 +83,8 @@ fn sample() -> [[location(0)]] vec4 { [[stage(fragment)]] fn sample_comparison() -> [[location(0)]] f32 { - let tc: vec2 = vec2(0.5); - let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc, 0.5); - let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc, 0.5); + let tc1: vec2 = vec2(0.5); + let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc1, 0.5); + let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc1, 0.5); return (s2d_depth + s2d_depth_level); } From 4ea2d96cfb697079d240db5ed4ad41fbd0c7730d Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 30 Sep 2021 05:56:09 -0700 Subject: [PATCH 1392/2212] Various doc fixes. (#1440) --- src/back/msl/writer.rs | 16 ++++++++++++++++ src/lib.rs | 35 +++++++++++++++++++++-------------- src/proc/namer.rs | 15 +++++++++++++++ src/proc/typifier.rs | 4 ++-- 4 files changed, 54 insertions(+), 16 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a34fbfdd0..efe58d3dd 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -14,6 +14,9 @@ use std::{ type BackendResult = Result<(), Error>; const NAMESPACE: &str = "metal"; +// The name of the array member of the Metal struct types we generate to +// represent Naga `Array` types. See the comments in `Writer::write_type_defs` +// for details. const WRAPPED_ARRAY_FIELD: &str = "inner"; // This is a hack: we need to pass a pointer to an atomic, // but generally the backend isn't putting "&" in front of every pointer. @@ -1771,6 +1774,19 @@ impl Writer { } let name = &self.names[&NameKey::Type(handle)]; match ty.inner { + // Naga IR can pass around arrays by value, but Metal, following + // C++, performs an array-to-pointer conversion (C++ [conv.array]) + // on expressions of array type, so assigning the array by value + // isn't possible. However, Metal *does* assign structs by + // value. So in our Metal output, we wrap all array types in + // synthetic struct types: + // + // struct type1 { + // float inner[10] + // }; + // + // Then we carefully include `.inner` (`WRAPPED_ARRAY_FIELD`) in + // any expression that actually wants access to the array. crate::TypeInner::Array { base, size, diff --git a/src/lib.rs b/src/lib.rs index bc0681d9f..97b5b9f52 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -573,6 +573,10 @@ pub enum TypeInner { Atomic { kind: ScalarKind, width: Bytes }, /// Pointer to another type. /// + /// Pointers to scalars and vectors should be treated as equivalent to + /// [`ValuePointer`] types. Use the [`TypeInner::equivalent`] method to + /// compare types in a way that treats pointers correctly. + /// /// ## Pointers to non-`SIZED` types /// /// The `base` type of a pointer may be a non-[`SIZED`] type like a @@ -590,6 +594,7 @@ pub enum TypeInner { /// [`DATA`]: valid::TypeFlags::DATA /// [`Array`]: TypeInner::Array /// [`Struct`]: TypeInner::Struct + /// [`ValuePointer`]: TypeInner::ValuePointer /// [`GlobalVariable`]: Expression::GlobalVariable /// [`AccessIndex`]: Expression::AccessIndex Pointer { @@ -597,11 +602,17 @@ pub enum TypeInner { class: StorageClass, }, - /// Pointer to a value. + /// Pointer to a scalar or vector. /// - /// A `ValuePointer` type is equivalent to a `Pointer` to a `Scalar` or `Vector`. - /// This is for use in [`TypeResolution::Value`] variants. + /// A `ValuePointer` type is equivalent to a `Pointer` whose `base` is a + /// `Scalar` or `Vector` type. This is for use in [`TypeResolution::Value`] + /// variants; see the documentation for [`TypeResolution`] for details. /// + /// Use the [`TypeInner::equivalent`] method to compare types that could be + /// pointers, to ensure that `Pointer` and `ValuePointer` types are + /// recognized as equivalent. + /// + /// [`TypeResolution`]: proc::TypeResolution /// [`TypeResolution::Value`]: proc::TypeResolution::Value ValuePointer { size: Option, @@ -1008,17 +1019,12 @@ pub enum Expression { /// Indexing a [`Vector`] or [`Array`] produces a value of its element type. /// Indexing a [`Matrix`] produces a [`Vector`]. /// - /// Indexing a [`Pointer`] to an [`Array`] produces a [`Pointer`] to its - /// `base` type, taking on the `Pointer`'s storage class. - /// - /// Indexing a [`Pointer`] to a [`Vector`] produces a [`ValuePointer`] whose - /// size is `None`, taking on the [`Vector`]'s scalar kind and width and the - /// [`Pointer`]'s storage class. - /// - /// Indexing a [`Pointer`] to a [`Matrix`] produces a [`ValuePointer`] for a - /// column of the matrix: its size is the matrix's height, its `kind` is - /// [`Float`], and it inherits the [`Matrix`]'s width and the [`Pointer`]'s - /// storage class. + /// Indexing a [`Pointer`] to any of the above produces a pointer to the + /// element/component type, in the same [`class`]. In the case of [`Array`], + /// the result is an actual [`Pointer`], but for vectors and matrices, there + /// may not be any type in the arena representing the component's type, so + /// those produce [`ValuePointer`] types equivalent to the appropriate + /// [`Pointer`]. /// /// ## Dynamic indexing restrictions /// @@ -1043,6 +1049,7 @@ pub enum Expression { /// [`Matrix`]: TypeInner::Matrix /// [`Array`]: TypeInner::Array /// [`Pointer`]: TypeInner::Pointer + /// [`class`]: TypeInner::Pointer::class /// [`ValuePointer`]: TypeInner::ValuePointer /// [`Float`]: ScalarKind::Float Access { diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 0c2038cbf..90c91e503 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -28,6 +28,12 @@ pub struct Namer { } impl Namer { + /// Return a form of `string` suitable for use as the base of an identifier. + /// + /// Retain only alphanumeric and `_` characters. Drop leading digits. Ensure + /// that the string does not end with a digit, so we can attach numeric + /// suffixes without merging. Avoid prefixes in + /// [`Namer::reserved_prefixes`]. fn sanitize(&self, string: &str) -> String { let mut base = string .chars() @@ -50,6 +56,15 @@ impl Namer { base } + /// Return a new identifier based on `label_raw`. + /// + /// The result: + /// - is a valid identifier even if `label_raw` is not + /// - conflicts with no keywords listed in `Namer::keywords`, and + /// - is different from any identifier previously constructed by this + /// `Namer`. + /// + /// Guarantee uniqueness by applying a numeric suffix when necessary. pub fn call(&mut self, label_raw: &str) -> String { let base = self.sanitize(label_raw); match self.unique.entry(base) { diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 9bca13e48..217eeb1e2 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -4,8 +4,8 @@ use thiserror::Error; /// The result of computing an expression's type. /// -/// This is the type returned by [`ResolveContext::resolve`] to represent the type -/// it ascribes to some expression. +/// This is the (Rust) type returned by [`ResolveContext::resolve`] to represent +/// the (Naga) type it ascribes to some expression. /// /// You might expect such a function to simply return a `Handle`. However, /// we want type resolution to be a read-only process, and that would limit the From ea50486b2dfce3e41411aa50e23646768d9558d0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 1 Oct 2021 06:40:18 -0700 Subject: [PATCH 1393/2212] Forbid unsized structs as final members of structs. (#1443) WGSL says: > - The last member of the structure type defining the store type for a variable > ... may be a runtime-sized array. > > - A runtime-sized array must not be used as the store type or contained within > a store type in any other cases. Thus, a struct whose final member is a struct whose final member is a runtime-sized array is verboten. --- src/valid/type.rs | 8 ++++++-- tests/wgsl-errors.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/valid/type.rs b/src/valid/type.rs index 540818ca2..a180831df 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -473,9 +473,13 @@ impl super::Validator { handle, ); - // only the last field can be unsized + // The last field may be an unsized array. if !base_info.flags.contains(TypeFlags::SIZED) { - if i + 1 != members.len() { + let is_array = match types[member.ty].inner { + crate::TypeInner::Array { .. } => true, + _ => false, + }; + if !is_array || i + 1 != members.len() { let name = member.name.clone().unwrap_or_default(); return Err(TypeError::InvalidDynamicArray(name, member.ty)); } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 8ccfdfa0e..9f4f0711b 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -913,3 +913,35 @@ fn dead_code() { }) } } + +#[test] +fn invalid_runtime_sized_arrays() { + // You can't have structs whose last member is an unsized struct. An unsized + // array may only appear as the last member of a struct used directly as a + // variable's store type. + check_validation_error! { + " + struct Unsized { + arr: array; + }; + + [[block]] + struct Outer { + legit: i32; + unsized: Unsized; + }; + + [[group(0), binding(0)]] var outer: Outer; + + fn fetch(i: i32) -> f32 { + return outer.unsized.arr[i]; + } + ": + Err(naga::valid::ValidationError::Type { + name: struct_name, + error: naga::valid::TypeError::InvalidDynamicArray(member_name, _), + .. + }) + if struct_name == "Outer" && member_name == "unsized" + } +} From f30f3a3db6e126e8e07531a693ea1e28832087db Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 1 Oct 2021 09:47:39 -0700 Subject: [PATCH 1394/2212] Properly type-check `Expression::Select` arguments. (#1442) Require the `accept` and `reject` arguments to `select` to be scalars or vectors, per WGSL spec. --- src/valid/expression.rs | 9 ++++++++- tests/wgsl-errors.rs | 42 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 547cef2b9..0295e2c85 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -795,7 +795,14 @@ impl super::Validator { Ti::Scalar { kind: Sk::Bool, width: _, - } => accept_inner.is_sized(), + } => { + // When `condition` is a single boolean, `accept` and + // `reject` can be vectors or scalars. + match *accept_inner { + Ti::Scalar { .. } | Ti::Vector { .. } => true, + _ => false, + } + } Ti::Vector { size, kind: Sk::Bool, diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 9f4f0711b..dedd2042d 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -945,3 +945,45 @@ fn invalid_runtime_sized_arrays() { if struct_name == "Outer" && member_name == "unsized" } } + +#[test] +fn select() { + check_validation_error! { + " + fn select_pointers(which: bool) -> i32 { + var x: i32 = 1; + var y: i32 = 2; + let ptr = select(&x, &y, which); + return *ptr; + } + ", + " + fn select_arrays(which: bool) -> i32 { + var x: array; + var y: array; + let s = select(x, y, which); + return s[0]; + } + ", + " + struct S { member: i32; }; + fn select_structs(which: bool) -> S { + var x: S = S(1); + var y: S = S(2); + let s = select(x, y, which); + return s; + } + ": + Err( + naga::valid::ValidationError::Function { + name, + error: naga::valid::FunctionError::Expression { + error: naga::valid::ExpressionError::InvalidSelectTypes, + .. + }, + .. + }, + ) + if name.starts_with("select_") + } +} From f01eb723780691b20b2debb8f4d31e505e085816 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 3 Oct 2021 04:22:49 +0100 Subject: [PATCH 1395/2212] [Snapshots] Allow a blacklist of entrypoints for glsl-out (#1444) --- tests/snapshots.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 102a4864f..54e5f6d6b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -96,6 +96,9 @@ struct Parameters { #[cfg(all(not(feature = "deserialize"), feature = "glsl-out"))] #[serde(default)] glsl_custom: bool, + #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] + #[serde(default)] + glsl_blacklist: naga::FastHashSet, #[cfg(all(feature = "deserialize", feature = "hlsl-out"))] #[serde(default)] hlsl: naga::back::hlsl::Options, @@ -314,6 +317,10 @@ fn write_output_glsl( &default_options }; + if params.glsl_blacklist.contains(ep_name) { + return; + } + let pipeline_options = glsl::PipelineOptions { shader_stage: stage, entry_point: ep_name.to_string(), From b34fa5f2cc2d4ddd42b64125f811fb51ace942e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 3 Oct 2021 17:22:14 +0100 Subject: [PATCH 1396/2212] [glsl-in] Fix array index parsing for 1D images (#1445) --- src/front/glsl/builtins.rs | 2 +- tests/out/wgsl/samplers-frag.wgsl | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index ed678538c..84d7ee8e2 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1852,7 +1852,7 @@ impl Parser { _ => coord, }; - let mut coord_index = image_size.map_or(0, |s| s as u32); + let mut coord_index = image_size.map_or(1, |s| s as u32); let array_index = match arrayed { true => { diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 18433b50f..016b87693 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -146,28 +146,28 @@ fn testTex1DArray(coord2: vec2) { coord3 = coord2; let e18: vec2 = coord3; - let e22: vec4 = textureSample(tex1DArray, samp, e18.x, i32(e18.x)); + let e22: vec4 = textureSample(tex1DArray, samp, e18.x, i32(e18.y)); c1 = e22; let e25: vec2 = coord3; - let e30: vec4 = textureSampleBias(tex1DArray, samp, e25.x, i32(e25.x), 2.0); + let e30: vec4 = textureSampleBias(tex1DArray, samp, e25.x, i32(e25.y), 2.0); c1 = e30; let e34: vec2 = coord3; - let e40: vec4 = textureSampleGrad(tex1DArray, samp, e34.x, i32(e34.x), 4.0, 4.0); + let e40: vec4 = textureSampleGrad(tex1DArray, samp, e34.x, i32(e34.y), 4.0, 4.0); c1 = e40; let e45: vec2 = coord3; - let e52: vec4 = textureSampleGrad(tex1DArray, samp, e45.x, i32(e45.x), 4.0, 4.0, 5); + let e52: vec4 = textureSampleGrad(tex1DArray, samp, e45.x, i32(e45.y), 4.0, 4.0, 5); c1 = e52; let e55: vec2 = coord3; - let e60: vec4 = textureSampleLevel(tex1DArray, samp, e55.x, i32(e55.x), 3.0); + let e60: vec4 = textureSampleLevel(tex1DArray, samp, e55.x, i32(e55.y), 3.0); c1 = e60; let e64: vec2 = coord3; - let e70: vec4 = textureSampleLevel(tex1DArray, samp, e64.x, i32(e64.x), 3.0, 5); + let e70: vec4 = textureSampleLevel(tex1DArray, samp, e64.x, i32(e64.y), 3.0, 5); c1 = e70; let e73: vec2 = coord3; - let e78: vec4 = textureSample(tex1DArray, samp, e73.x, i32(e73.x), 5); + let e78: vec4 = textureSample(tex1DArray, samp, e73.x, i32(e73.y), 5); c1 = e78; let e82: vec2 = coord3; - let e88: vec4 = textureSampleBias(tex1DArray, samp, e82.x, i32(e82.x), 2.0, 5); + let e88: vec4 = textureSampleBias(tex1DArray, samp, e82.x, i32(e82.y), 2.0, 5); c1 = e88; return; } From 71a75d727d2a9ff898b3bc50f94728be7efaae87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 4 Oct 2021 04:01:44 +0100 Subject: [PATCH 1397/2212] [glsl-out] Es: convert 1D images to 2D (#1436) --- src/back/glsl/features.rs | 7 - src/back/glsl/mod.rs | 52 ++- tests/in/image.param.ron | 1 + tests/in/image.wgsl | 42 ++- tests/out/glsl/image.main.Compute.glsl | 31 ++ tests/out/glsl/image.queries.Vertex.glsl | 37 ++ tests/out/glsl/image.sample.Fragment.glsl | 23 ++ .../image.sample_comparison.Fragment.glsl | 18 + tests/out/hlsl/image.hlsl | 142 +++---- tests/out/hlsl/image.hlsl.config | 4 +- tests/out/msl/image.msl | 67 +++- tests/out/spv/image.spvasm | 357 ++++++++++-------- tests/out/wgsl/image.wgsl | 39 +- tests/snapshots.rs | 2 +- 14 files changed, 540 insertions(+), 282 deletions(-) create mode 100644 tests/out/glsl/image.main.Compute.glsl create mode 100644 tests/out/glsl/image.queries.Vertex.glsl create mode 100644 tests/out/glsl/image.sample.Fragment.glsl create mode 100644 tests/out/glsl/image.sample_comparison.Fragment.glsl diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index d2e83e004..74db74c70 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -22,8 +22,6 @@ bitflags::bitflags! { /// Adds support for image load and early depth tests const IMAGE_LOAD_STORE = 1 << 8; const CONSERVATIVE_DEPTH = 1 << 9; - /// Isn't supported in ES - const TEXTURE_1D = 1 << 10; /// Interpolation and auxiliary qualifiers. Perspective, Flat, and /// Centroid are available in all GLSL versions we support. const NOPERSPECTIVE_QUALIFIER = 1 << 11; @@ -92,9 +90,6 @@ impl FeaturesManager { check_feature!(IMAGE_LOAD_STORE, 130, 310); check_feature!(CONSERVATIVE_DEPTH, 130, 300); check_feature!(CONSERVATIVE_DEPTH, 130, 300); - // 1D textures are supported by all core versions and aren't supported by an es versions - // so use 0 that way the check will always be false and can be optimized away - check_feature!(TEXTURE_1D, 0); check_feature!(NOPERSPECTIVE_QUALIFIER, 130); check_feature!(SAMPLE_QUALIFIER, 400, 320); // gl_ClipDistance is supported by core versions > 1.3 and aren't supported by an es versions without extensions @@ -298,8 +293,6 @@ impl<'a, W> Writer<'a, W> { } => { if arrayed && dim == ImageDimension::Cube { self.features.request(Features::CUBE_TEXTURES_ARRAY) - } else if dim == ImageDimension::D1 { - self.features.request(Features::TEXTURE_1D) } match class { diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 60e0d57b0..f2406fa9c 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -514,7 +514,7 @@ impl<'a, W: Write> Writer<'a, W> { // We treat images separately because they might require // writing the storage format TypeInner::Image { - dim, + mut dim, arrayed, class, } => { @@ -526,6 +526,11 @@ impl<'a, W: Write> Writer<'a, W> { } => Some((format, access)), _ => None, }; + + if dim == crate::ImageDimension::D1 && es { + dim = crate::ImageDimension::D2 + } + // Gether the location if needed let layout_binding = if self.options.version.supports_explicit_locations() { let br = global.binding.as_ref().unwrap(); @@ -1954,12 +1959,12 @@ impl<'a, W: Write> Writer<'a, W> { // We need to get the coordinates vector size to later build a vector that's `size + 1` // if `depth_ref` is some, if it isn't a vector we panic as that's not a valid expression - let size = match *ctx.info[coordinate].ty.inner_with(&self.module.types) { - TypeInner::Vector { size, .. } => size, + let mut coord_dim = match *ctx.info[coordinate].ty.inner_with(&self.module.types) { + TypeInner::Vector { size, .. } => size as u8, + TypeInner::Scalar { .. } => 1, _ => unreachable!(), }; - let mut coord_dim = size as u8; if array_index.is_some() { coord_dim += 1; } @@ -1968,9 +1973,16 @@ impl<'a, W: Write> Writer<'a, W> { coord_dim += 1; } + let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es(); + let is_vec = tex_1d_hack || coord_dim != 1; // Compose a new texture coordinates vector - write!(self.out, "vec{}(", coord_dim)?; + if is_vec { + write!(self.out, "vec{}(", coord_dim + tex_1d_hack as u8)?; + } self.write_expr(coordinate, ctx)?; + if tex_1d_hack { + write!(self.out, ", 0.0")?; + } if let Some(expr) = array_index { write!(self.out, ", ")?; self.write_expr(expr, ctx)?; @@ -1981,7 +1993,9 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(expr, ctx)?; } } - write!(self.out, ")")?; + if is_vec { + write!(self.out, ")")?; + } if cube_array_shadow { if let Some(expr) = depth_ref { @@ -2025,7 +2039,13 @@ impl<'a, W: Write> Writer<'a, W> { if let Some(constant) = offset { write!(self.out, ", ")?; + if tex_1d_hack { + write!(self.out, "ivec2(")?; + } self.write_constant(constant)?; + if tex_1d_hack { + write!(self.out, ", 0)")?; + } } // End the function @@ -2103,11 +2123,11 @@ impl<'a, W: Write> Writer<'a, W> { ImageClass::Sampled { .. } | ImageClass::Depth { .. } => { write!(self.out, "textureSize(")?; self.write_expr(image, ctx)?; - write!(self.out, ",")?; + write!(self.out, ", ")?; if let Some(expr) = level { self.write_expr(expr, ctx)?; } else { - write!(self.out, "0",)?; + write!(self.out, "0")?; } } ImageClass::Storage { .. } => { @@ -2115,7 +2135,10 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(image, ctx)?; } } - write!(self.out, ").{}", &"xyz"[..components])?; + write!(self.out, ")")?; + if components != 1 || self.options.version.is_es() { + write!(self.out, ".{}", &"xyz"[..components])?; + } } crate::ImageQuery::NumLevels => { write!(self.out, "textureQueryLevels(",)?; @@ -2129,7 +2152,9 @@ impl<'a, W: Write> Writer<'a, W> { }; write!(self.out, "{}(", fun_name)?; self.write_expr(image, ctx)?; - write!(self.out, ",0).{}", back::COMPONENTS[components])?; + if components != 1 || self.options.version.is_es() { + write!(self.out, ", 0).{}", back::COMPONENTS[components])?; + } } crate::ImageQuery::NumSamples => { // assumes ARB_shader_texture_image_samples @@ -2473,7 +2498,14 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")?; } None => { + let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es(); + if tex_1d_hack { + write!(self.out, "ivec2(")?; + } self.write_expr(coordinate, ctx)?; + if tex_1d_hack { + write!(self.out, ", 0.0)")?; + } } } Ok(()) diff --git a/tests/in/image.param.ron b/tests/in/image.param.ron index 91e6e8597..721b98fb2 100644 --- a/tests/in/image.param.ron +++ b/tests/in/image.param.ron @@ -3,4 +3,5 @@ version: (1, 1), debug: true, ), + glsl_blacklist: ["depth_load", "levels_queries"] ) diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index c4621a407..e9fd4f0fa 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -23,10 +23,18 @@ fn main( let itc = dim * vec2(local_id.xy) % vec2(10, 20); let value1 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); let value2 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); - let value3 = textureLoad(image_depth_multisampled_src, itc, i32(local_id.z)); let value4 = textureLoad(image_storage_src, itc); let value5 = textureLoad(image_array_src, itc, i32(local_id.z), i32(local_id.z) + 1); - textureStore(image_dst, itc.x, value1 + value2 + u32(value3) + value4 + value5); + textureStore(image_dst, itc.x, value1 + value2 + value4 + value5); +} + +[[stage(compute), workgroup_size(16, 1, 1)]] +fn depth_load([[builtin(local_invocation_id)]] local_id: vec3) { + let dim: vec2 = textureDimensions(image_storage_src); + let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); + let val: f32 = textureLoad(image_depth_multisampled_src, itc, i32(local_id.z)); + textureStore(image_dst, itc.x, vec4(u32(val))); + return; } [[group(0), binding(0)]] @@ -48,27 +56,34 @@ var image_aa: texture_multisampled_2d; fn queries() -> [[builtin(position)]] vec4 { let dim_1d = textureDimensions(image_1d); let dim_2d = textureDimensions(image_2d); - let num_levels_2d = textureNumLevels(image_2d); let dim_2d_lod = textureDimensions(image_2d, 1); let dim_2d_array = textureDimensions(image_2d_array); - let num_levels_2d_array = textureNumLevels(image_2d_array); let dim_2d_array_lod = textureDimensions(image_2d_array, 1); - let num_layers_2d = textureNumLayers(image_2d_array); let dim_cube = textureDimensions(image_cube); - let num_levels_cube = textureNumLevels(image_cube); let dim_cube_lod = textureDimensions(image_cube, 1); let dim_cube_array = textureDimensions(image_cube_array); - let num_levels_cube_array = textureNumLevels(image_cube_array); let dim_cube_array_lod = textureDimensions(image_cube_array, 1); - let num_layers_cube = textureNumLayers(image_cube_array); let dim_3d = textureDimensions(image_3d); - let num_levels_3d = textureNumLevels(image_3d); let dim_3d_lod = textureDimensions(image_3d, 1); - let num_samples_aa = textureNumSamples(image_aa); let sum = dim_1d + dim_2d.y + dim_2d_lod.y + dim_2d_array.y + dim_2d_array_lod.y + - num_layers_2d + dim_cube.y + dim_cube_lod.y + dim_cube_array.y + dim_cube_array_lod.y + - num_layers_cube + dim_3d.z + dim_3d_lod.z + num_samples_aa + + dim_cube.y + dim_cube_lod.y + dim_cube_array.y + dim_cube_array_lod.y + + dim_3d.z + dim_3d_lod.z; + return vec4(f32(sum)); +} + +[[stage(vertex)]] +fn levels_queries() -> [[builtin(position)]] vec4 { + let num_levels_2d = textureNumLevels(image_2d); + let num_levels_2d_array = textureNumLevels(image_2d_array); + let num_layers_2d = textureNumLayers(image_2d_array); + let num_levels_cube = textureNumLevels(image_cube); + let num_levels_cube_array = textureNumLevels(image_cube_array); + let num_layers_cube = textureNumLayers(image_cube_array); + let num_levels_3d = textureNumLevels(image_3d); + let num_samples_aa = textureNumSamples(image_aa); + + let sum = num_layers_2d + num_layers_cube + num_samples_aa + num_levels_2d + num_levels_2d_array + num_levels_3d + num_levels_cube + num_levels_cube_array; return vec4(f32(sum)); } @@ -80,11 +95,12 @@ var sampler_reg: sampler; fn sample() -> [[location(0)]] vec4 { let tc = vec2(0.5); let level = 2.3; + let s1d = textureSample(image_1d, sampler_reg, tc.x); let s2d = textureSample(image_2d, sampler_reg, tc); let s2d_offset = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); let s2d_level = textureSampleLevel(image_2d, sampler_reg, tc, level); let s2d_level_offset = textureSampleLevel(image_2d, sampler_reg, tc, level, vec2(3, 1)); - return s2d + s2d_offset + s2d_level + s2d_level_offset; + return s1d + s2d + s2d_offset + s2d_level + s2d_level_offset; } [[group(1), binding(1)]] diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl new file mode 100644 index 000000000..be6b7ed97 --- /dev/null +++ b/tests/out/glsl/image.main.Compute.glsl @@ -0,0 +1,31 @@ +#version 310 es +#extension GL_EXT_texture_cube_map_array : require + +precision highp float; +precision highp int; + +layout(local_size_x = 16, local_size_y = 1, local_size_z = 1) in; + +uniform highp usampler2D _group_0_binding_0; + +uniform highp usampler2DMS _group_0_binding_3; + +layout(rgba8ui) readonly uniform highp uimage2D _group_0_binding_1; + +uniform highp usampler2DArray _group_0_binding_5; + +layout(r32ui) writeonly uniform highp uimage2D _group_0_binding_2; + + +void main() { + uvec3 local_id = gl_LocalInvocationID; + ivec2 dim = imageSize(_group_0_binding_1).xy; + ivec2 itc = ((dim * ivec2(local_id.xy)) % ivec2(10, 20)); + uvec4 value1_ = texelFetch(_group_0_binding_0, itc, int(local_id.z)); + uvec4 value2_ = texelFetch(_group_0_binding_3, itc, int(local_id.z)); + uvec4 value4_ = imageLoad(_group_0_binding_1, itc); + uvec4 value5_ = texelFetch(_group_0_binding_5, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); + imageStore(_group_0_binding_2, ivec2(itc.x, 0.0), (((value1_ + value2_) + value4_) + value5_)); + return; +} + diff --git a/tests/out/glsl/image.queries.Vertex.glsl b/tests/out/glsl/image.queries.Vertex.glsl new file mode 100644 index 000000000..8f89d2dad --- /dev/null +++ b/tests/out/glsl/image.queries.Vertex.glsl @@ -0,0 +1,37 @@ +#version 310 es +#extension GL_EXT_texture_cube_map_array : require + +precision highp float; +precision highp int; + +uniform highp sampler2D _group_0_binding_0; + +uniform highp sampler2D _group_0_binding_1; + +uniform highp sampler2DArray _group_0_binding_2; + +uniform highp samplerCube _group_0_binding_3; + +uniform highp samplerCubeArray _group_0_binding_4; + +uniform highp sampler3D _group_0_binding_5; + + +void main() { + int dim_1d = textureSize(_group_0_binding_0, 0).x; + ivec2 dim_2d = textureSize(_group_0_binding_1, 0).xy; + ivec2 dim_2d_lod = textureSize(_group_0_binding_1, 1).xy; + ivec2 dim_2d_array = textureSize(_group_0_binding_2, 0).xy; + ivec2 dim_2d_array_lod = textureSize(_group_0_binding_2, 1).xy; + ivec2 dim_cube = textureSize(_group_0_binding_3, 0).xy; + ivec2 dim_cube_lod = textureSize(_group_0_binding_3, 1).xy; + ivec2 dim_cube_array = textureSize(_group_0_binding_4, 0).xy; + ivec2 dim_cube_array_lod = textureSize(_group_0_binding_4, 1).xy; + ivec3 dim_3d = textureSize(_group_0_binding_5, 0).xyz; + ivec3 dim_3d_lod = textureSize(_group_0_binding_5, 1).xyz; + int sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); + gl_Position = vec4(float(sum)); + gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); + return; +} + diff --git a/tests/out/glsl/image.sample.Fragment.glsl b/tests/out/glsl/image.sample.Fragment.glsl new file mode 100644 index 000000000..a0d7946d0 --- /dev/null +++ b/tests/out/glsl/image.sample.Fragment.glsl @@ -0,0 +1,23 @@ +#version 310 es +#extension GL_EXT_texture_cube_map_array : require + +precision highp float; +precision highp int; + +uniform highp sampler2D _group_0_binding_0; + +uniform highp sampler2D _group_0_binding_1; + +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + vec2 tc = vec2(0.5); + vec4 s1d = texture(_group_0_binding_0, vec2(tc.x, 0.0)); + vec4 s2d = texture(_group_0_binding_1, vec2(tc)); + vec4 s2d_offset = textureOffset(_group_0_binding_1, vec2(tc), ivec2(3, 1)); + vec4 s2d_level = textureLod(_group_0_binding_1, vec2(tc), 2.299999952316284); + vec4 s2d_level_offset = textureLodOffset(_group_0_binding_1, vec2(tc), 2.299999952316284, ivec2(3, 1)); + _fs2p_location0 = ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); + return; +} + diff --git a/tests/out/glsl/image.sample_comparison.Fragment.glsl b/tests/out/glsl/image.sample_comparison.Fragment.glsl new file mode 100644 index 000000000..4b52baac2 --- /dev/null +++ b/tests/out/glsl/image.sample_comparison.Fragment.glsl @@ -0,0 +1,18 @@ +#version 310 es +#extension GL_EXT_texture_cube_map_array : require + +precision highp float; +precision highp int; + +uniform highp sampler2DShadow _group_1_binding_2; + +layout(location = 0) out float _fs2p_location0; + +void main() { + vec2 tc = vec2(0.5); + float s2d_depth = texture(_group_1_binding_2, vec3(tc, 0.5)); + float s2d_depth_level = textureLod(_group_1_binding_2, vec3(tc, 0.5), 0.0); + _fs2p_location0 = (s2d_depth + s2d_depth_level); + return; +} + diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 4eb297de5..d6da396a5 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -31,10 +31,19 @@ void main(uint3 local_id : SV_GroupThreadID) int2 itc = ((dim * int2(local_id.xy)) % int2(10, 20)); uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(local_id.z))); uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z)); - float value3_ = image_depth_multisampled_src.Load(itc, int(local_id.z)).x; uint4 value4_ = image_storage_src.Load(itc); uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); - image_dst[itc.x] = ((((value1_ + value2_) + uint4(uint(value3_).xxxx)) + value4_) + value5_); + image_dst[itc.x] = (((value1_ + value2_) + value4_) + value5_); + return; +} + +[numthreads(16, 1, 1)] +void depth_load(uint3 local_id1 : SV_GroupThreadID) +{ + int2 dim1 = NagaRWDimensions2D(image_storage_src); + int2 itc1 = ((dim1 * int2(local_id1.xy)) % int2(10, 20)); + float val = image_depth_multisampled_src.Load(itc1, int(local_id1.z)).x; + image_dst[itc1.x] = uint4(uint(val).xxxx); return; } @@ -52,13 +61,6 @@ int2 NagaDimensions2D(Texture2D tex) return ret.xy; } -int NagaNumLevels2D(Texture2D tex) -{ - uint4 ret; - tex.GetDimensions(0, ret.x, ret.y, ret.z); - return ret.z; -} - int2 NagaMipDimensions2D(Texture2D tex, uint mip_level) { uint4 ret; @@ -73,13 +75,6 @@ int2 NagaDimensions2DArray(Texture2DArray tex) return ret.xy; } -int NagaNumLevels2DArray(Texture2DArray tex) -{ - uint4 ret; - tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); - return ret.w; -} - int2 NagaMipDimensions2DArray(Texture2DArray tex, uint mip_level) { uint4 ret; @@ -87,13 +82,6 @@ int2 NagaMipDimensions2DArray(Texture2DArray tex, uint mip_level) return ret.xy; } -int NagaNumLayers2DArray(Texture2DArray tex) -{ - uint4 ret; - tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); - return ret.w; -} - int2 NagaDimensionsCube(TextureCube tex) { uint4 ret; @@ -101,13 +89,6 @@ int2 NagaDimensionsCube(TextureCube tex) return ret.xy; } -int NagaNumLevelsCube(TextureCube tex) -{ - uint4 ret; - tex.GetDimensions(0, ret.x, ret.y, ret.z); - return ret.z; -} - int2 NagaMipDimensionsCube(TextureCube tex, uint mip_level) { uint4 ret; @@ -122,13 +103,6 @@ int2 NagaDimensionsCubeArray(TextureCubeArray tex) return ret.xy; } -int NagaNumLevelsCubeArray(TextureCubeArray tex) -{ - uint4 ret; - tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); - return ret.w; -} - int2 NagaMipDimensionsCubeArray(TextureCubeArray tex, uint mip_level) { uint4 ret; @@ -136,13 +110,6 @@ int2 NagaMipDimensionsCubeArray(TextureCubeArray tex, uint mip_level) return ret.xy; } -int NagaNumLayersCubeArray(TextureCubeArray tex) -{ - uint4 ret; - tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); - return ret.w; -} - int3 NagaDimensions3D(Texture3D tex) { uint4 ret; @@ -150,18 +117,77 @@ int3 NagaDimensions3D(Texture3D tex) return ret.xyz; } -int NagaNumLevels3D(Texture3D tex) +int3 NagaMipDimensions3D(Texture3D tex, uint mip_level) +{ + uint4 ret; + tex.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); + return ret.xyz; +} + +float4 queries() : SV_Position +{ + int dim_1d = NagaDimensions1D(image_1d); + int2 dim_2d = NagaDimensions2D(image_2d); + int2 dim_2d_lod = NagaMipDimensions2D(image_2d, 1); + int2 dim_2d_array = NagaDimensions2DArray(image_2d_array); + int2 dim_2d_array_lod = NagaMipDimensions2DArray(image_2d_array, 1); + int2 dim_cube = NagaDimensionsCube(image_cube); + int2 dim_cube_lod = NagaMipDimensionsCube(image_cube, 1); + int2 dim_cube_array = NagaDimensionsCubeArray(image_cube_array); + int2 dim_cube_array_lod = NagaMipDimensionsCubeArray(image_cube_array, 1); + int3 dim_3d = NagaDimensions3D(image_3d); + int3 dim_3d_lod = NagaMipDimensions3D(image_3d, 1); + int sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); + return float4(float(sum).xxxx); +} + +int NagaNumLevels2D(Texture2D tex) +{ + uint4 ret; + tex.GetDimensions(0, ret.x, ret.y, ret.z); + return ret.z; +} + +int NagaNumLevels2DArray(Texture2DArray tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int3 NagaMipDimensions3D(Texture3D tex, uint mip_level) +int NagaNumLayers2DArray(Texture2DArray tex) { uint4 ret; - tex.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); - return ret.xyz; + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; +} + +int NagaNumLevelsCube(TextureCube tex) +{ + uint4 ret; + tex.GetDimensions(0, ret.x, ret.y, ret.z); + return ret.z; +} + +int NagaNumLevelsCubeArray(TextureCubeArray tex) +{ + uint4 ret; + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; +} + +int NagaNumLayersCubeArray(TextureCubeArray tex) +{ + uint4 ret; + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; +} + +int NagaNumLevels3D(Texture3D tex) +{ + uint4 ret; + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; } int NagaMSNumSamples2D(Texture2DMS tex) @@ -171,39 +197,29 @@ int NagaMSNumSamples2D(Texture2DMS tex) return ret.z; } -float4 queries() : SV_Position +float4 levels_queries() : SV_Position { - int dim_1d = NagaDimensions1D(image_1d); - int2 dim_2d = NagaDimensions2D(image_2d); int num_levels_2d = NagaNumLevels2D(image_2d); - int2 dim_2d_lod = NagaMipDimensions2D(image_2d, 1); - int2 dim_2d_array = NagaDimensions2DArray(image_2d_array); int num_levels_2d_array = NagaNumLevels2DArray(image_2d_array); - int2 dim_2d_array_lod = NagaMipDimensions2DArray(image_2d_array, 1); int num_layers_2d = NagaNumLayers2DArray(image_2d_array); - int2 dim_cube = NagaDimensionsCube(image_cube); int num_levels_cube = NagaNumLevelsCube(image_cube); - int2 dim_cube_lod = NagaMipDimensionsCube(image_cube, 1); - int2 dim_cube_array = NagaDimensionsCubeArray(image_cube_array); int num_levels_cube_array = NagaNumLevelsCubeArray(image_cube_array); - int2 dim_cube_array_lod = NagaMipDimensionsCubeArray(image_cube_array, 1); int num_layers_cube = NagaNumLayersCubeArray(image_cube_array); - int3 dim_3d = NagaDimensions3D(image_3d); int num_levels_3d = NagaNumLevels3D(image_3d); - int3 dim_3d_lod = NagaMipDimensions3D(image_3d, 1); int num_samples_aa = NagaMSNumSamples2D(image_aa); - int sum = ((((((((((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + num_layers_2d) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + num_layers_cube) + dim_3d.z) + dim_3d_lod.z) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); - return float4(float(sum).xxxx); + int sum1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); + return float4(float(sum1).xxxx); } float4 sample1() : SV_Target0 { float2 tc = float2(0.5.xx); + float4 s1d = image_1d.Sample(sampler_reg, tc.x); float4 s2d = image_2d.Sample(sampler_reg, tc); float4 s2d_offset = image_2d.Sample(sampler_reg, tc, int2(3, 1)); float4 s2d_level = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284); float4 s2d_level_offset = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284, int2(3, 1)); - return (((s2d + s2d_offset) + s2d_level) + s2d_level_offset); + return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); } float sample_comparison() : SV_Target0 diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config index c5d0760d9..4f6c8ecdb 100644 --- a/tests/out/hlsl/image.hlsl.config +++ b/tests/out/hlsl/image.hlsl.config @@ -1,3 +1,3 @@ -vertex=(queries:vs_5_1 ) +vertex=(queries:vs_5_1 levels_queries:vs_5_1 ) fragment=(sample1:ps_5_1 sample_comparison:ps_5_1 ) -compute=(main:cs_5_1 ) +compute=(main:cs_5_1 depth_load:cs_5_1 ) diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 44fde4992..1c8e5e4ea 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -10,7 +10,6 @@ kernel void main1( metal::uint3 local_id [[thread_position_in_threadgroup]] , metal::texture2d image_mipmapped_src [[user(fake0)]] , metal::texture2d_ms image_multisampled_src [[user(fake0)]] -, metal::depth2d_ms image_depth_multisampled_src [[user(fake0)]] , metal::texture2d image_storage_src [[user(fake0)]] , metal::texture2d_array image_array_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] @@ -19,16 +18,31 @@ kernel void main1( metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); - float value3_ = image_depth_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); - image_dst.write((((value1_ + value2_) + metal::uint4(static_cast(value3_))) + value4_) + value5_, metal::uint(itc.x)); + image_dst.write(((value1_ + value2_) + value4_) + value5_, metal::uint(itc.x)); + return; +} + + +struct depth_loadInput { +}; +kernel void depth_load( + metal::uint3 local_id1 [[thread_position_in_threadgroup]] +, metal::depth2d_ms image_depth_multisampled_src [[user(fake0)]] +, metal::texture2d image_storage_src [[user(fake0)]] +, metal::texture1d image_dst [[user(fake0)]] +) { + metal::int2 dim1 = int2(image_storage_src.get_width(), image_storage_src.get_height()); + metal::int2 itc1 = (dim1 * static_cast(local_id1.xy)) % metal::int2(10, 20); + float val = image_depth_multisampled_src.read(metal::uint2(itc1), static_cast(local_id1.z)); + image_dst.write(metal::uint4(static_cast(val)), metal::uint(itc1.x)); return; } struct queriesOutput { - metal::float4 member1 [[position]]; + metal::float4 member2 [[position]]; }; vertex queriesOutput queries( metal::texture1d image_1d [[user(fake0)]] @@ -37,50 +51,67 @@ vertex queriesOutput queries( , metal::texturecube image_cube [[user(fake0)]] , metal::texturecube_array image_cube_array [[user(fake0)]] , metal::texture3d image_3d [[user(fake0)]] -, metal::texture2d_ms image_aa [[user(fake0)]] ) { int dim_1d = int(image_1d.get_width()); metal::int2 dim_2d = int2(image_2d.get_width(), image_2d.get_height()); - int num_levels_2d = int(image_2d.get_num_mip_levels()); metal::int2 dim_2d_lod = int2(image_2d.get_width(1), image_2d.get_height(1)); metal::int2 dim_2d_array = int2(image_2d_array.get_width(), image_2d_array.get_height()); - int num_levels_2d_array = int(image_2d_array.get_num_mip_levels()); metal::int2 dim_2d_array_lod = int2(image_2d_array.get_width(1), image_2d_array.get_height(1)); - int num_layers_2d = int(image_2d_array.get_array_size()); metal::int2 dim_cube = int2(image_cube.get_width()); - int num_levels_cube = int(image_cube.get_num_mip_levels()); metal::int2 dim_cube_lod = int2(image_cube.get_width(1)); metal::int2 dim_cube_array = int2(image_cube_array.get_width()); - int num_levels_cube_array = int(image_cube_array.get_num_mip_levels()); metal::int2 dim_cube_array_lod = int2(image_cube_array.get_width(1)); - int num_layers_cube = int(image_cube_array.get_array_size()); metal::int3 dim_3d = int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()); - int num_levels_3d = int(image_3d.get_num_mip_levels()); metal::int3 dim_3d_lod = int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)); - int num_samples_aa = int(image_aa.get_num_samples()); - int sum = (((((((((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + num_layers_2d) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + num_layers_cube) + dim_3d.z) + dim_3d_lod.z) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array; + int sum = (((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z; return queriesOutput { metal::float4(static_cast(sum)) }; } +struct levels_queriesOutput { + metal::float4 member3 [[position]]; +}; +vertex levels_queriesOutput levels_queries( + metal::texture2d image_2d [[user(fake0)]] +, metal::texture2d_array image_2d_array [[user(fake0)]] +, metal::texturecube image_cube [[user(fake0)]] +, metal::texturecube_array image_cube_array [[user(fake0)]] +, metal::texture3d image_3d [[user(fake0)]] +, metal::texture2d_ms image_aa [[user(fake0)]] +) { + int num_levels_2d = int(image_2d.get_num_mip_levels()); + int num_levels_2d_array = int(image_2d_array.get_num_mip_levels()); + int num_layers_2d = int(image_2d_array.get_array_size()); + int num_levels_cube = int(image_cube.get_num_mip_levels()); + int num_levels_cube_array = int(image_cube_array.get_num_mip_levels()); + int num_layers_cube = int(image_cube_array.get_array_size()); + int num_levels_3d = int(image_3d.get_num_mip_levels()); + int num_samples_aa = int(image_aa.get_num_samples()); + int sum1 = ((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array; + return levels_queriesOutput { metal::float4(static_cast(sum1)) }; +} + + struct sampleOutput { - metal::float4 member2 [[color(0)]]; + metal::float4 member4 [[color(0)]]; }; fragment sampleOutput sample( - metal::texture2d image_2d [[user(fake0)]] + metal::texture1d image_1d [[user(fake0)]] +, metal::texture2d image_2d [[user(fake0)]] , metal::sampler sampler_reg [[user(fake0)]] ) { metal::float2 tc = metal::float2(0.5); + metal::float4 s1d = image_1d.sample(sampler_reg, tc.x); metal::float4 s2d = image_2d.sample(sampler_reg, tc); metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type8_); metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type8_); - return sampleOutput { ((s2d + s2d_offset) + s2d_level) + s2d_level_offset }; + return sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset }; } struct sample_comparisonOutput { - float member3 [[color(0)]]; + float member5 [[color(0)]]; }; fragment sample_comparisonOutput sample_comparison( metal::sampler sampler_cmp [[user(fake0)]] diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index e0617cfe4..9fc7d518e 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 215 +; Bound: 244 OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D @@ -10,12 +10,15 @@ OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %69 "main" %66 -OpEntryPoint Vertex %115 "queries" %113 -OpEntryPoint Fragment %182 "sample" %181 -OpEntryPoint Fragment %203 "sample_comparison" %201 +OpEntryPoint GLCompute %107 "depth_load" %105 +OpEntryPoint Vertex %128 "queries" %126 +OpEntryPoint Vertex %176 "levels_queries" %175 +OpEntryPoint Fragment %205 "sample" %204 +OpEntryPoint Fragment %232 "sample_comparison" %230 OpExecutionMode %69 LocalSize 16 1 1 -OpExecutionMode %182 OriginUpperLeft -OpExecutionMode %203 OriginUpperLeft +OpExecutionMode %107 LocalSize 16 1 1 +OpExecutionMode %205 OriginUpperLeft +OpExecutionMode %232 OriginUpperLeft OpSource GLSL 450 OpName %31 "image_mipmapped_src" OpName %33 "image_multisampled_src" @@ -36,9 +39,12 @@ OpName %61 "sampler_cmp" OpName %63 "image_2d_depth" OpName %66 "local_id" OpName %69 "main" -OpName %115 "queries" -OpName %182 "sample" -OpName %203 "sample_comparison" +OpName %105 "local_id" +OpName %107 "depth_load" +OpName %128 "queries" +OpName %176 "levels_queries" +OpName %205 "sample" +OpName %232 "sample_comparison" OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 0 OpDecorate %33 DescriptorSet 0 @@ -77,9 +83,11 @@ OpDecorate %61 Binding 1 OpDecorate %63 DescriptorSet 1 OpDecorate %63 Binding 2 OpDecorate %66 BuiltIn LocalInvocationId -OpDecorate %113 BuiltIn Position -OpDecorate %181 Location 0 -OpDecorate %201 Location 0 +OpDecorate %105 BuiltIn LocalInvocationId +OpDecorate %126 BuiltIn Position +OpDecorate %175 BuiltIn Position +OpDecorate %204 Location 0 +OpDecorate %230 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -146,166 +154,203 @@ OpDecorate %201 Location 0 %67 = OpTypePointer Input %18 %66 = OpVariable %67 Input %70 = OpTypeFunction %2 -%79 = OpTypeVector %12 2 -%87 = OpTypeVector %12 4 -%102 = OpTypeVector %4 3 -%114 = OpTypePointer Output %27 -%113 = OpVariable %114 Output -%124 = OpConstant %12 0 -%181 = OpVariable %114 Output -%186 = OpTypeVector %8 2 -%188 = OpTypeSampledImage %21 -%202 = OpTypePointer Output %8 -%201 = OpVariable %202 Output -%208 = OpTypeSampledImage %29 -%213 = OpConstant %8 0.0 +%78 = OpTypeVector %12 2 +%86 = OpTypeVector %12 4 +%97 = OpTypeVector %4 3 +%105 = OpVariable %67 Input +%127 = OpTypePointer Output %27 +%126 = OpVariable %127 Output +%136 = OpConstant %12 0 +%175 = OpVariable %127 Output +%204 = OpVariable %127 Output +%210 = OpTypeVector %8 2 +%213 = OpTypeSampledImage %20 +%216 = OpTypeSampledImage %21 +%231 = OpTypePointer Output %8 +%230 = OpVariable %231 Output +%237 = OpTypeSampledImage %29 +%242 = OpConstant %8 0.0 %69 = OpFunction %2 None %70 %65 = OpLabel %68 = OpLoad %18 %66 %71 = OpLoad %11 %31 %72 = OpLoad %13 %33 -%73 = OpLoad %14 %35 -%74 = OpLoad %15 %37 -%75 = OpLoad %16 %39 -%76 = OpLoad %17 %43 -OpBranch %77 -%77 = OpLabel -%78 = OpImageQuerySize %19 %74 -%80 = OpVectorShuffle %79 %68 %68 0 1 -%81 = OpBitcast %19 %80 -%82 = OpIMul %19 %78 %81 -%83 = OpCompositeConstruct %19 %3 %5 -%84 = OpSMod %19 %82 %83 -%85 = OpCompositeExtract %12 %68 2 -%86 = OpBitcast %4 %85 -%88 = OpImageFetch %87 %71 %84 Lod %86 -%89 = OpCompositeExtract %12 %68 2 -%90 = OpBitcast %4 %89 -%91 = OpImageFetch %87 %72 %84 Sample %90 +%73 = OpLoad %15 %37 +%74 = OpLoad %16 %39 +%75 = OpLoad %17 %43 +OpBranch %76 +%76 = OpLabel +%77 = OpImageQuerySize %19 %73 +%79 = OpVectorShuffle %78 %68 %68 0 1 +%80 = OpBitcast %19 %79 +%81 = OpIMul %19 %77 %80 +%82 = OpCompositeConstruct %19 %3 %5 +%83 = OpSMod %19 %81 %82 +%84 = OpCompositeExtract %12 %68 2 +%85 = OpBitcast %4 %84 +%87 = OpImageFetch %86 %71 %83 Lod %85 +%88 = OpCompositeExtract %12 %68 2 +%89 = OpBitcast %4 %88 +%90 = OpImageFetch %86 %72 %83 Sample %89 +%91 = OpImageRead %86 %73 %83 %92 = OpCompositeExtract %12 %68 2 %93 = OpBitcast %4 %92 -%94 = OpImageFetch %27 %73 %84 Sample %93 -%95 = OpCompositeExtract %8 %94 0 -%96 = OpImageRead %87 %74 %84 -%97 = OpCompositeExtract %12 %68 2 -%98 = OpBitcast %4 %97 -%99 = OpCompositeExtract %12 %68 2 -%100 = OpBitcast %4 %99 -%101 = OpIAdd %4 %100 %6 -%103 = OpCompositeConstruct %102 %84 %98 -%104 = OpImageFetch %87 %75 %103 Lod %101 -%105 = OpCompositeExtract %4 %84 0 -%106 = OpIAdd %87 %88 %91 -%107 = OpConvertFToU %12 %95 -%108 = OpCompositeConstruct %87 %107 %107 %107 %107 -%109 = OpIAdd %87 %106 %108 -%110 = OpIAdd %87 %109 %96 -%111 = OpIAdd %87 %110 %104 -OpImageWrite %76 %105 %111 +%94 = OpCompositeExtract %12 %68 2 +%95 = OpBitcast %4 %94 +%96 = OpIAdd %4 %95 %6 +%98 = OpCompositeConstruct %97 %83 %93 +%99 = OpImageFetch %86 %74 %98 Lod %96 +%100 = OpCompositeExtract %4 %83 0 +%101 = OpIAdd %86 %87 %90 +%102 = OpIAdd %86 %101 %91 +%103 = OpIAdd %86 %102 %99 +OpImageWrite %75 %100 %103 OpReturn OpFunctionEnd -%115 = OpFunction %2 None %70 -%112 = OpLabel -%116 = OpLoad %20 %45 -%117 = OpLoad %21 %47 -%118 = OpLoad %22 %49 -%119 = OpLoad %23 %51 -%120 = OpLoad %24 %53 -%121 = OpLoad %25 %55 -%122 = OpLoad %26 %57 -OpBranch %123 -%123 = OpLabel -%125 = OpImageQuerySizeLod %4 %116 %124 -%126 = OpImageQuerySizeLod %19 %117 %124 -%127 = OpImageQueryLevels %4 %117 -%128 = OpImageQuerySizeLod %19 %117 %6 -%129 = OpImageQuerySizeLod %102 %118 %124 -%130 = OpVectorShuffle %19 %129 %129 0 1 -%131 = OpImageQueryLevels %4 %118 -%132 = OpImageQuerySizeLod %102 %118 %6 -%133 = OpVectorShuffle %19 %132 %132 0 1 -%134 = OpImageQuerySizeLod %102 %118 %124 -%135 = OpCompositeExtract %4 %134 2 -%136 = OpImageQuerySizeLod %19 %119 %124 -%137 = OpImageQueryLevels %4 %119 -%138 = OpImageQuerySizeLod %19 %119 %6 -%139 = OpImageQuerySizeLod %102 %120 %124 -%140 = OpVectorShuffle %19 %139 %139 0 0 -%141 = OpImageQueryLevels %4 %120 -%142 = OpImageQuerySizeLod %102 %120 %6 -%143 = OpVectorShuffle %19 %142 %142 0 0 -%144 = OpImageQuerySizeLod %102 %120 %124 -%145 = OpCompositeExtract %4 %144 2 -%146 = OpImageQuerySizeLod %102 %121 %124 -%147 = OpImageQueryLevels %4 %121 -%148 = OpImageQuerySizeLod %102 %121 %6 -%149 = OpImageQuerySamples %4 %122 -%150 = OpCompositeExtract %4 %126 1 -%151 = OpIAdd %4 %125 %150 -%152 = OpCompositeExtract %4 %128 1 -%153 = OpIAdd %4 %151 %152 -%154 = OpCompositeExtract %4 %130 1 +%107 = OpFunction %2 None %70 +%104 = OpLabel +%106 = OpLoad %18 %105 +%108 = OpLoad %14 %35 +%109 = OpLoad %15 %37 +%110 = OpLoad %17 %43 +OpBranch %111 +%111 = OpLabel +%112 = OpImageQuerySize %19 %109 +%113 = OpVectorShuffle %78 %106 %106 0 1 +%114 = OpBitcast %19 %113 +%115 = OpIMul %19 %112 %114 +%116 = OpCompositeConstruct %19 %3 %5 +%117 = OpSMod %19 %115 %116 +%118 = OpCompositeExtract %12 %106 2 +%119 = OpBitcast %4 %118 +%120 = OpImageFetch %27 %108 %117 Sample %119 +%121 = OpCompositeExtract %8 %120 0 +%122 = OpCompositeExtract %4 %117 0 +%123 = OpConvertFToU %12 %121 +%124 = OpCompositeConstruct %86 %123 %123 %123 %123 +OpImageWrite %110 %122 %124 +OpReturn +OpFunctionEnd +%128 = OpFunction %2 None %70 +%125 = OpLabel +%129 = OpLoad %20 %45 +%130 = OpLoad %21 %47 +%131 = OpLoad %22 %49 +%132 = OpLoad %23 %51 +%133 = OpLoad %24 %53 +%134 = OpLoad %25 %55 +OpBranch %135 +%135 = OpLabel +%137 = OpImageQuerySizeLod %4 %129 %136 +%138 = OpImageQuerySizeLod %19 %130 %136 +%139 = OpImageQuerySizeLod %19 %130 %6 +%140 = OpImageQuerySizeLod %97 %131 %136 +%141 = OpVectorShuffle %19 %140 %140 0 1 +%142 = OpImageQuerySizeLod %97 %131 %6 +%143 = OpVectorShuffle %19 %142 %142 0 1 +%144 = OpImageQuerySizeLod %19 %132 %136 +%145 = OpImageQuerySizeLod %19 %132 %6 +%146 = OpImageQuerySizeLod %97 %133 %136 +%147 = OpVectorShuffle %19 %146 %146 0 0 +%148 = OpImageQuerySizeLod %97 %133 %6 +%149 = OpVectorShuffle %19 %148 %148 0 0 +%150 = OpImageQuerySizeLod %97 %134 %136 +%151 = OpImageQuerySizeLod %97 %134 %6 +%152 = OpCompositeExtract %4 %138 1 +%153 = OpIAdd %4 %137 %152 +%154 = OpCompositeExtract %4 %139 1 %155 = OpIAdd %4 %153 %154 -%156 = OpCompositeExtract %4 %133 1 +%156 = OpCompositeExtract %4 %141 1 %157 = OpIAdd %4 %155 %156 -%158 = OpIAdd %4 %157 %135 -%159 = OpCompositeExtract %4 %136 1 -%160 = OpIAdd %4 %158 %159 -%161 = OpCompositeExtract %4 %138 1 -%162 = OpIAdd %4 %160 %161 -%163 = OpCompositeExtract %4 %140 1 -%164 = OpIAdd %4 %162 %163 -%165 = OpCompositeExtract %4 %143 1 -%166 = OpIAdd %4 %164 %165 -%167 = OpIAdd %4 %166 %145 -%168 = OpCompositeExtract %4 %146 2 +%158 = OpCompositeExtract %4 %143 1 +%159 = OpIAdd %4 %157 %158 +%160 = OpCompositeExtract %4 %144 1 +%161 = OpIAdd %4 %159 %160 +%162 = OpCompositeExtract %4 %145 1 +%163 = OpIAdd %4 %161 %162 +%164 = OpCompositeExtract %4 %147 1 +%165 = OpIAdd %4 %163 %164 +%166 = OpCompositeExtract %4 %149 1 +%167 = OpIAdd %4 %165 %166 +%168 = OpCompositeExtract %4 %150 2 %169 = OpIAdd %4 %167 %168 -%170 = OpCompositeExtract %4 %148 2 +%170 = OpCompositeExtract %4 %151 2 %171 = OpIAdd %4 %169 %170 -%172 = OpIAdd %4 %171 %149 -%173 = OpIAdd %4 %172 %127 -%174 = OpIAdd %4 %173 %131 -%175 = OpIAdd %4 %174 %147 -%176 = OpIAdd %4 %175 %137 -%177 = OpIAdd %4 %176 %141 -%178 = OpConvertSToF %8 %177 -%179 = OpCompositeConstruct %27 %178 %178 %178 %178 -OpStore %113 %179 +%172 = OpConvertSToF %8 %171 +%173 = OpCompositeConstruct %27 %172 %172 %172 %172 +OpStore %126 %173 OpReturn OpFunctionEnd -%182 = OpFunction %2 None %70 -%180 = OpLabel -%183 = OpLoad %21 %47 -%184 = OpLoad %28 %59 -OpBranch %185 -%185 = OpLabel -%187 = OpCompositeConstruct %186 %7 %7 -%189 = OpSampledImage %188 %183 %184 -%190 = OpImageSampleImplicitLod %27 %189 %187 -%191 = OpSampledImage %188 %183 %184 -%192 = OpImageSampleImplicitLod %27 %191 %187 ConstOffset %30 -%193 = OpSampledImage %188 %183 %184 -%194 = OpImageSampleExplicitLod %27 %193 %187 Lod %9 -%195 = OpSampledImage %188 %183 %184 -%196 = OpImageSampleExplicitLod %27 %195 %187 Lod|ConstOffset %9 %30 -%197 = OpFAdd %27 %190 %192 -%198 = OpFAdd %27 %197 %194 -%199 = OpFAdd %27 %198 %196 -OpStore %181 %199 +%176 = OpFunction %2 None %70 +%174 = OpLabel +%177 = OpLoad %21 %47 +%178 = OpLoad %22 %49 +%179 = OpLoad %23 %51 +%180 = OpLoad %24 %53 +%181 = OpLoad %25 %55 +%182 = OpLoad %26 %57 +OpBranch %183 +%183 = OpLabel +%184 = OpImageQueryLevels %4 %177 +%185 = OpImageQueryLevels %4 %178 +%186 = OpImageQuerySizeLod %97 %178 %136 +%187 = OpCompositeExtract %4 %186 2 +%188 = OpImageQueryLevels %4 %179 +%189 = OpImageQueryLevels %4 %180 +%190 = OpImageQuerySizeLod %97 %180 %136 +%191 = OpCompositeExtract %4 %190 2 +%192 = OpImageQueryLevels %4 %181 +%193 = OpImageQuerySamples %4 %182 +%194 = OpIAdd %4 %187 %191 +%195 = OpIAdd %4 %194 %193 +%196 = OpIAdd %4 %195 %184 +%197 = OpIAdd %4 %196 %185 +%198 = OpIAdd %4 %197 %192 +%199 = OpIAdd %4 %198 %188 +%200 = OpIAdd %4 %199 %189 +%201 = OpConvertSToF %8 %200 +%202 = OpCompositeConstruct %27 %201 %201 %201 %201 +OpStore %175 %202 OpReturn OpFunctionEnd -%203 = OpFunction %2 None %70 -%200 = OpLabel -%204 = OpLoad %28 %61 -%205 = OpLoad %29 %63 -OpBranch %206 -%206 = OpLabel -%207 = OpCompositeConstruct %186 %7 %7 -%209 = OpSampledImage %208 %205 %204 -%210 = OpImageSampleDrefImplicitLod %8 %209 %207 %7 -%211 = OpSampledImage %208 %205 %204 -%212 = OpImageSampleDrefExplicitLod %8 %211 %207 %7 Lod %213 -%214 = OpFAdd %8 %210 %212 -OpStore %201 %214 +%205 = OpFunction %2 None %70 +%203 = OpLabel +%206 = OpLoad %20 %45 +%207 = OpLoad %21 %47 +%208 = OpLoad %28 %59 +OpBranch %209 +%209 = OpLabel +%211 = OpCompositeConstruct %210 %7 %7 +%212 = OpCompositeExtract %8 %211 0 +%214 = OpSampledImage %213 %206 %208 +%215 = OpImageSampleImplicitLod %27 %214 %212 +%217 = OpSampledImage %216 %207 %208 +%218 = OpImageSampleImplicitLod %27 %217 %211 +%219 = OpSampledImage %216 %207 %208 +%220 = OpImageSampleImplicitLod %27 %219 %211 ConstOffset %30 +%221 = OpSampledImage %216 %207 %208 +%222 = OpImageSampleExplicitLod %27 %221 %211 Lod %9 +%223 = OpSampledImage %216 %207 %208 +%224 = OpImageSampleExplicitLod %27 %223 %211 Lod|ConstOffset %9 %30 +%225 = OpFAdd %27 %215 %218 +%226 = OpFAdd %27 %225 %220 +%227 = OpFAdd %27 %226 %222 +%228 = OpFAdd %27 %227 %224 +OpStore %204 %228 +OpReturn +OpFunctionEnd +%232 = OpFunction %2 None %70 +%229 = OpLabel +%233 = OpLoad %28 %61 +%234 = OpLoad %29 %63 +OpBranch %235 +%235 = OpLabel +%236 = OpCompositeConstruct %210 %7 %7 +%238 = OpSampledImage %237 %234 %233 +%239 = OpImageSampleDrefImplicitLod %8 %238 %236 %7 +%240 = OpSampledImage %237 %234 %233 +%241 = OpImageSampleDrefExplicitLod %8 %240 %236 %7 Lod %242 +%243 = OpFAdd %8 %239 %241 +OpStore %230 %243 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 166faf6d6..34d642a2f 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -39,10 +39,18 @@ fn main([[builtin(local_invocation_id)]] local_id: vec3) { let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); let value1_: vec4 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); let value2_: vec4 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); - let value3_: f32 = textureLoad(image_depth_multisampled_src, itc, i32(local_id.z)); let value4_: vec4 = textureLoad(image_storage_src, itc); let value5_: vec4 = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); - textureStore(image_dst, itc.x, ((((value1_ + value2_) + vec4(u32(value3_))) + value4_) + value5_)); + textureStore(image_dst, itc.x, (((value1_ + value2_) + value4_) + value5_)); + return; +} + +[[stage(compute), workgroup_size(16, 1, 1)]] +fn depth_load([[builtin(local_invocation_id)]] local_id1: vec3) { + let dim1: vec2 = textureDimensions(image_storage_src); + let itc1: vec2 = ((dim1 * vec2(local_id1.xy)) % vec2(10, 20)); + let val: f32 = textureLoad(image_depth_multisampled_src, itc1, i32(local_id1.z)); + textureStore(image_dst, itc1.x, vec4(u32(val))); return; } @@ -50,35 +58,42 @@ fn main([[builtin(local_invocation_id)]] local_id: vec3) { fn queries() -> [[builtin(position)]] vec4 { let dim_1d: i32 = textureDimensions(image_1d); let dim_2d: vec2 = textureDimensions(image_2d); - let num_levels_2d: i32 = textureNumLevels(image_2d); let dim_2d_lod: vec2 = textureDimensions(image_2d, 1); let dim_2d_array: vec2 = textureDimensions(image_2d_array); - let num_levels_2d_array: i32 = textureNumLevels(image_2d_array); let dim_2d_array_lod: vec2 = textureDimensions(image_2d_array, 1); - let num_layers_2d: i32 = textureNumLayers(image_2d_array); let dim_cube: vec2 = textureDimensions(image_cube); - let num_levels_cube: i32 = textureNumLevels(image_cube); let dim_cube_lod: vec2 = textureDimensions(image_cube, 1); let dim_cube_array: vec2 = textureDimensions(image_cube_array); - let num_levels_cube_array: i32 = textureNumLevels(image_cube_array); let dim_cube_array_lod: vec2 = textureDimensions(image_cube_array, 1); - let num_layers_cube: i32 = textureNumLayers(image_cube_array); let dim_3d: vec3 = textureDimensions(image_3d); - let num_levels_3d: i32 = textureNumLevels(image_3d); let dim_3d_lod: vec3 = textureDimensions(image_3d, 1); - let num_samples_aa: i32 = textureNumSamples(image_aa); - let sum: i32 = ((((((((((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + num_layers_2d) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + num_layers_cube) + dim_3d.z) + dim_3d_lod.z) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); + let sum: i32 = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); return vec4(f32(sum)); } +[[stage(vertex)]] +fn levels_queries() -> [[builtin(position)]] vec4 { + let num_levels_2d: i32 = textureNumLevels(image_2d); + let num_levels_2d_array: i32 = textureNumLevels(image_2d_array); + let num_layers_2d: i32 = textureNumLayers(image_2d_array); + let num_levels_cube: i32 = textureNumLevels(image_cube); + let num_levels_cube_array: i32 = textureNumLevels(image_cube_array); + let num_layers_cube: i32 = textureNumLayers(image_cube_array); + let num_levels_3d: i32 = textureNumLevels(image_3d); + let num_samples_aa: i32 = textureNumSamples(image_aa); + let sum1: i32 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); + return vec4(f32(sum1)); +} + [[stage(fragment)]] fn sample() -> [[location(0)]] vec4 { let tc: vec2 = vec2(0.5); + let s1d: vec4 = textureSample(image_1d, sampler_reg, tc.x); let s2d: vec4 = textureSample(image_2d, sampler_reg, tc); let s2d_offset: vec4 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); let s2d_level: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284); let s2d_level_offset: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284, vec2(3, 1)); - return (((s2d + s2d_offset) + s2d_level) + s2d_level_offset); + return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); } [[stage(fragment)]] diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 54e5f6d6b..5725695e6 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -488,7 +488,7 @@ fn convert_wgsl() { ), ( "image", - Targets::SPIRV | Targets::METAL | Targets::HLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::HLSL | Targets::WGSL | Targets::GLSL, ), ("extra", Targets::SPIRV | Targets::METAL | Targets::WGSL), ( From da00bf2be6a8c3cd27153d820cc15e0470e4a1b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 5 Oct 2021 18:05:47 +0100 Subject: [PATCH 1398/2212] [glsl-in] Always use uint for array size (#1448) --- src/front/glsl/parser/types.rs | 13 ++++++++++++- tests/out/wgsl/bevy-pbr-frag.wgsl | 4 ++-- tests/out/wgsl/constant-array-size-vert.wgsl | 2 +- tests/out/wgsl/expressions-frag.wgsl | 2 +- tests/out/wgsl/global-constant-array-vert.wgsl | 2 +- 5 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index fe6ed3b96..7fc74e2dd 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -24,7 +24,18 @@ impl<'source> ParsingContext<'source> { return Ok(Some((ArraySize::Dynamic, meta))); } - let (constant, _) = self.parse_constant_expression(parser)?; + let (value, span) = self.parse_uint_constant(parser)?; + let constant = parser.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(value as u64), + }, + }, + span, + ); let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; meta.subsume(end_meta); Ok(Some((ArraySize::Constant(constant), meta))) diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 23ca8a5f1..b2c97f693 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -23,8 +23,8 @@ struct CameraPosition { struct Lights { AmbientColor: vec4; NumLights: vec4; - PointLights: [[stride(48)]] array; - DirectionalLights: [[stride(32)]] array; + PointLights: [[stride(48)]] array; + DirectionalLights: [[stride(32)]] array; }; [[block]] diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 27ff1eb37..4987dae38 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -1,6 +1,6 @@ [[block]] struct Data { - vecs: [[stride(16)]] array,42>; + vecs: [[stride(16)]] array,42u>; }; [[group(1), binding(0)]] diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 8bed050c1..8e1316750 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -181,7 +181,7 @@ fn testStructConstructor() { } fn testArrayConstructor() { - var tree1: array = array(0.0); + var tree1: array = array(0.0); } diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index 066088b1f..0e652c5f8 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -1,7 +1,7 @@ var i: u32; fn main1() { - var local: array = array(1.0, 2.0); + var local: array = array(1.0, 2.0); let e2: u32 = i; } From 3e1244c5cbff24506b82bed906e283260fc19849 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 5 Oct 2021 22:11:32 +0300 Subject: [PATCH 1399/2212] Make shader validation under a separate feature (#1437) --- .github/workflows/lazy.yml | 11 ++++++++++ Cargo.toml | 1 + cli/Cargo.toml | 2 +- src/valid/analyzer.rs | 3 +++ src/valid/compose.rs | 6 +++++- src/valid/expression.rs | 13 +++++++++--- src/valid/function.rs | 41 ++++++++++++++++++++++++++++--------- src/valid/interface.rs | 42 +++++++++++++++++++++++++------------- src/valid/mod.rs | 16 ++++++++++++++- 9 files changed, 105 insertions(+), 30 deletions(-) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index 2065da0d4..ff21d63a7 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -149,3 +149,14 @@ jobs: echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter done cat counter + check_snapshots_without_validation: + name: Check snapshots (without validation) + runs-on: ubuntu-latest + steps: + - uses: actions-rs/cargo@v1 + name: Test all (without validation) + with: + command: test + args: --features wgsl-in,wgsl-out,glsl-in,glsl-out,spv-in,spv-out,msl-out,hlsl-out,dot-out --workspace + - name: Check snapshots (without validation) + run: git diff --exit-code -- tests/out diff --git a/Cargo.toml b/Cargo.toml index 26b1d3e94..430da0f81 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,7 @@ wgsl-in = ["codespan-reporting", "hexf-parse"] wgsl-out = [] hlsl-out = [] span = ["codespan-reporting"] +validate = [] [dev-dependencies] diff = "0.1" diff --git a/cli/Cargo.toml b/cli/Cargo.toml index a60e8cd26..36443d90f 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -14,7 +14,7 @@ name = "naga" path = "src/main.rs" [dependencies] -naga = { path = "../", features = ["span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate"] } +naga = { path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate"] } log = "0.4" codespan-reporting = "0.11" env_logger = "0.8" diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 1526856d0..d6e2452ad 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -190,6 +190,7 @@ struct Sampling { #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct FunctionInfo { /// Validation flags. + #[allow(dead_code)] flags: ValidationFlags, /// Set of shader stages where calling this function is valid. pub available_stages: ShaderStages, @@ -621,6 +622,7 @@ impl FunctionInfo { let mut requirements = UniformityRequirements::empty(); for expr in range.clone() { let req = self.expressions[expr.index()].uniformity.requirements; + #[cfg(feature = "validate")] if self .flags .contains(super::ValidationFlags::CONTROL_FLOW_UNIFORMITY) @@ -854,6 +856,7 @@ impl ModuleInfo { } #[test] +#[cfg(feature = "validate")] fn uniform_control_flow() { use crate::{Expression as E, Statement as S}; diff --git a/src/valid/compose.rs b/src/valid/compose.rs index 15148fc7a..23599b5a0 100644 --- a/src/valid/compose.rs +++ b/src/valid/compose.rs @@ -1,8 +1,11 @@ +#[cfg(feature = "validate")] use crate::{ - arena::{Arena, Handle, UniqueArena}, + arena::{Arena, UniqueArena}, proc::TypeResolution, }; +use crate::Handle; + #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum ComposeError { @@ -16,6 +19,7 @@ pub enum ComposeError { ComponentType { index: u32 }, } +#[cfg(feature = "validate")] pub fn validate_compose( self_ty_handle: Handle, constant_arena: &Arena, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 0295e2c85..8c1f659f9 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,6 +1,10 @@ -use super::{compose::validate_compose, ComposeError, FunctionInfo, ShaderStages, TypeFlags}; +#[cfg(feature = "validate")] +use super::{compose::validate_compose, FunctionInfo, ShaderStages, TypeFlags}; +#[cfg(feature = "validate")] +use crate::arena::UniqueArena; + use crate::{ - arena::{Handle, UniqueArena}, + arena::Handle, proc::{ProcError, ResolveError}, }; @@ -40,7 +44,7 @@ pub enum ExpressionError { #[error("Swizzle component {0:?} is outside of vector size {1:?}")] InvalidSwizzleComponent(crate::SwizzleComponent, crate::VectorSize), #[error(transparent)] - Compose(#[from] ComposeError), + Compose(#[from] super::ComposeError), #[error(transparent)] Proc(#[from] ProcError), #[error("Operation {0:?} can't work with {1:?}")] @@ -111,12 +115,14 @@ pub enum ExpressionError { InvalidAtomicResultType(crate::ScalarKind, crate::Bytes), } +#[cfg(feature = "validate")] struct ExpressionTypeResolver<'a> { root: Handle, types: &'a UniqueArena, info: &'a FunctionInfo, } +#[cfg(feature = "validate")] impl<'a> ExpressionTypeResolver<'a> { fn resolve( &self, @@ -130,6 +136,7 @@ impl<'a> ExpressionTypeResolver<'a> { } } +#[cfg(feature = "validate")] impl super::Validator { pub(super) fn validate_expression( &self, diff --git a/src/valid/function.rs b/src/valid/function.rs index 23d4c0074..4ee4a08bc 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -1,8 +1,13 @@ +use crate::arena::Handle; +#[cfg(feature = "validate")] +use crate::arena::{Arena, UniqueArena}; + use super::{ analyzer::{UniformityDisruptor, UniformityRequirements}, - ExpressionError, FunctionInfo, ModuleInfo, ShaderStages, TypeFlags, ValidationFlags, + ExpressionError, FunctionInfo, ModuleInfo, }; -use crate::arena::{Arena, Handle, UniqueArena}; + +#[cfg(feature = "validate")] use bit_set::BitSet; #[derive(Clone, Debug, thiserror::Error)] @@ -141,11 +146,13 @@ bitflags::bitflags! { } } +#[cfg(feature = "validate")] struct BlockInfo { - stages: ShaderStages, + stages: super::ShaderStages, finished: bool, } +#[cfg(feature = "validate")] struct BlockContext<'a> { abilities: ControlFlowAbility, info: &'a FunctionInfo, @@ -157,6 +164,7 @@ struct BlockContext<'a> { return_type: Option>, } +#[cfg(feature = "validate")] impl<'a> BlockContext<'a> { fn new( fun: &'a crate::Function, @@ -228,13 +236,14 @@ impl<'a> BlockContext<'a> { } impl super::Validator { + #[cfg(feature = "validate")] fn validate_call( &mut self, function: Handle, arguments: &[Handle], result: Option>, context: &BlockContext, - ) -> Result { + ) -> Result { let fun = context .functions .try_get(function) @@ -278,6 +287,7 @@ impl super::Validator { Ok(callee_info.available_stages) } + #[cfg(feature = "validate")] fn validate_atomic( &mut self, pointer: Handle, @@ -334,6 +344,7 @@ impl super::Validator { Ok(()) } + #[cfg(feature = "validate")] fn validate_block_impl( &mut self, statements: &[crate::Statement], @@ -341,7 +352,7 @@ impl super::Validator { ) -> Result { use crate::{Statement as S, TypeInner as Ti}; let mut finished = false; - let mut stages = ShaderStages::all(); + let mut stages = super::ShaderStages::all(); for statement in statements { if finished { return Err(FunctionError::InstructionsAfterReturn); @@ -479,7 +490,7 @@ impl super::Validator { finished = true; } S::Barrier(_) => { - stages &= ShaderStages::COMPUTE; + stages &= super::ShaderStages::COMPUTE; } S::Store { pointer, value } => { let mut current = pointer; @@ -628,6 +639,7 @@ impl super::Validator { Ok(BlockInfo { stages, finished }) } + #[cfg(feature = "validate")] fn validate_block( &mut self, statements: &[crate::Statement], @@ -641,6 +653,7 @@ impl super::Validator { Ok(info) } + #[cfg(feature = "validate")] fn validate_local_var( &self, var: &crate::LocalVariable, @@ -650,7 +663,7 @@ impl super::Validator { log::debug!("var {:?}", var); if !self.types[var.ty.index()] .flags - .contains(TypeFlags::DATA | TypeFlags::SIZED) + .contains(super::TypeFlags::DATA | super::TypeFlags::SIZED) { return Err(LocalVariableError::InvalidType(var.ty)); } @@ -681,8 +694,13 @@ impl super::Validator { module: &crate::Module, mod_info: &ModuleInfo, ) -> Result { + #[cfg(feature = "validate")] let mut info = mod_info.process_function(fun, module, self.flags)?; + #[cfg(not(feature = "validate"))] + let info = mod_info.process_function(fun, module, self.flags)?; + + #[cfg(feature = "validate")] for (var_handle, var) in fun.local_variables.iter() { self.validate_local_var(var, &module.types, &module.constants) .map_err(|error| FunctionError::LocalVariable { @@ -692,10 +710,11 @@ impl super::Validator { })?; } + #[cfg(feature = "validate")] for (index, argument) in fun.arguments.iter().enumerate() { if !self.types[argument.ty.index()] .flags - .contains(TypeFlags::ARGUMENT) + .contains(super::TypeFlags::ARGUMENT) { return Err(FunctionError::InvalidArgumentType { index, @@ -723,7 +742,8 @@ impl super::Validator { if expr.needs_pre_emit() { self.valid_expression_set.insert(handle.index()); } - if self.flags.contains(ValidationFlags::EXPRESSIONS) { + #[cfg(feature = "validate")] + if self.flags.contains(super::ValidationFlags::EXPRESSIONS) { match self.validate_expression( handle, expr, @@ -738,7 +758,8 @@ impl super::Validator { } } - if self.flags.contains(ValidationFlags::BLOCKS) { + #[cfg(feature = "validate")] + if self.flags.contains(super::ValidationFlags::BLOCKS) { let stages = self .validate_block( &fun.body, diff --git a/src/valid/interface.rs b/src/valid/interface.rs index eb2465617..7ab34d703 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -1,12 +1,12 @@ use super::{ analyzer::{FunctionInfo, GlobalUse}, - Capabilities, Disalignment, FunctionError, ModuleInfo, ShaderStages, TypeFlags, - ValidationFlags, + Capabilities, Disalignment, FunctionError, ModuleInfo, }; use crate::arena::{Handle, UniqueArena}; use bit_set::BitSet; +#[cfg(feature = "validate")] const MAX_WORKGROUP_SIZE: u32 = 0x4000; #[derive(Clone, Debug, thiserror::Error)] @@ -17,8 +17,8 @@ pub enum GlobalVariableError { InvalidType, #[error("Type flags {seen:?} do not meet the required {required:?}")] MissingTypeFlags { - required: TypeFlags, - seen: TypeFlags, + required: super::TypeFlags, + seen: super::TypeFlags, }, #[error("Capability {0:?} is not supported")] UnsupportedCapability(Capabilities), @@ -78,6 +78,7 @@ pub enum EntryPointError { Function(#[from] FunctionError), } +#[cfg(feature = "validate")] fn storage_usage(access: crate::StorageAccess) -> GlobalUse { let mut storage_usage = GlobalUse::QUERY; if access.contains(crate::StorageAccess::LOAD) { @@ -317,11 +318,14 @@ impl VaryingContext<'_> { } impl super::Validator { + #[cfg(feature = "validate")] pub(super) fn validate_global_var( &self, var: &crate::GlobalVariable, types: &UniqueArena, ) -> Result<(), GlobalVariableError> { + use super::TypeFlags; + log::debug!("var {:?}", var); let type_info = &self.types[var.ty.index()]; @@ -329,7 +333,7 @@ impl super::Validator { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), crate::StorageClass::Storage { .. } => { if let Err((ty_handle, disalignment)) = type_info.storage_layout { - if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { + if self.flags.contains(super::ValidationFlags::STRUCT_LAYOUTS) { return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); } } @@ -340,7 +344,7 @@ impl super::Validator { } crate::StorageClass::Uniform => { if let Err((ty_handle, disalignment)) = type_info.uniform_layout { - if self.flags.contains(ValidationFlags::STRUCT_LAYOUTS) { + if self.flags.contains(super::ValidationFlags::STRUCT_LAYOUTS) { return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); } } @@ -396,9 +400,12 @@ impl super::Validator { module: &crate::Module, mod_info: &ModuleInfo, ) -> Result { + #[cfg(feature = "validate")] if ep.early_depth_test.is_some() && ep.stage != crate::ShaderStage::Fragment { return Err(EntryPointError::UnexpectedEarlyDepthTest); } + + #[cfg(feature = "validate")] if ep.stage == crate::ShaderStage::Compute { if ep .workgroup_size @@ -411,16 +418,21 @@ impl super::Validator { return Err(EntryPointError::UnexpectedWorkgroupSize); } - let stage_bit = match ep.stage { - crate::ShaderStage::Vertex => ShaderStages::VERTEX, - crate::ShaderStage::Fragment => ShaderStages::FRAGMENT, - crate::ShaderStage::Compute => ShaderStages::COMPUTE, - }; - let info = self.validate_function(&ep.function, module, mod_info)?; - if !info.available_stages.contains(stage_bit) { - return Err(EntryPointError::ForbiddenStageOperations); + #[cfg(feature = "validate")] + { + use super::ShaderStages; + + let stage_bit = match ep.stage { + crate::ShaderStage::Vertex => ShaderStages::VERTEX, + crate::ShaderStage::Fragment => ShaderStages::FRAGMENT, + crate::ShaderStage::Compute => ShaderStages::COMPUTE, + }; + + if !info.available_stages.contains(stage_bit) { + return Err(EntryPointError::ForbiddenStageOperations); + } } self.location_mask.clear(); @@ -458,6 +470,8 @@ impl super::Validator { for bg in self.bind_group_masks.iter_mut() { bg.clear(); } + + #[cfg(feature = "validate")] for (var_handle, var) in module.global_variables.iter() { let usage = info[var_handle]; if usage.is_empty() { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 3278d6ce1..fb72cdafc 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -5,8 +5,11 @@ mod function; mod interface; mod r#type; +#[cfg(feature = "validate")] +use crate::arena::{Arena, UniqueArena}; + use crate::{ - arena::{Arena, Handle, UniqueArena}, + arena::Handle, proc::{InvalidBaseType, Layouter}, FastHashSet, }; @@ -29,14 +32,19 @@ bitflags::bitflags! { #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ValidationFlags: u8 { /// Expressions. + #[cfg(feature = "validate")] const EXPRESSIONS = 0x1; /// Statements and blocks of them. + #[cfg(feature = "validate")] const BLOCKS = 0x2; /// Uniformity of control flow for operations that require it. + #[cfg(feature = "validate")] const CONTROL_FLOW_UNIFORMITY = 0x4; /// Host-shareable structure layouts. + #[cfg(feature = "validate")] const STRUCT_LAYOUTS = 0x8; /// Constants. + #[cfg(feature = "validate")] const CONSTANTS = 0x10; } } @@ -97,6 +105,7 @@ pub struct Validator { layouter: Layouter, location_mask: BitSet, bind_group_masks: Vec, + #[allow(dead_code)] select_cases: FastHashSet, valid_expression_list: Vec>, valid_expression_set: BitSet, @@ -158,6 +167,7 @@ pub enum ValidationError { } impl crate::TypeInner { + #[cfg(feature = "validate")] fn is_sized(&self) -> bool { match *self { Self::Scalar { .. } @@ -176,6 +186,7 @@ impl crate::TypeInner { } /// Return the `ImageDimension` for which `self` is an appropriate coordinate. + #[cfg(feature = "validate")] fn image_storage_coordinates(&self) -> Option { match *self { Self::Scalar { @@ -213,6 +224,7 @@ impl Validator { } } + #[cfg(feature = "validate")] fn validate_constant( &self, handle: Handle, @@ -257,6 +269,7 @@ impl Validator { self.reset_types(module.types.len()); self.layouter.update(&module.types, &module.constants)?; + #[cfg(feature = "validate")] if self.flags.contains(ValidationFlags::CONSTANTS) { for (handle, constant) in module.constants.iter() { self.validate_constant(handle, &module.constants, &module.types) @@ -279,6 +292,7 @@ impl Validator { self.types[handle.index()] = ty_info; } + #[cfg(feature = "validate")] for (var_handle, var) in module.global_variables.iter() { self.validate_global_var(var, &module.types) .map_err(|error| ValidationError::GlobalVariable { From 2f5a41cce9aff2818b64c6faaf804e9eec969eef Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Tue, 5 Oct 2021 20:32:57 -0400 Subject: [PATCH 1400/2212] Add insert/extractBits and pack/unpack functions (#1449) --- src/back/dot/mod.rs | 4 + src/back/glsl/mod.rs | 44 ++++++- src/back/hlsl/writer.rs | 5 + src/back/msl/writer.rs | 32 ++++- src/back/spv/block.rs | 41 +++++- src/back/spv/instructions.rs | 36 ++++++ src/back/wgsl/writer.rs | 19 +++ src/front/glsl/builtins.rs | 175 ++++++++++++++++++++++++-- src/front/spv/mod.rs | 86 +++++++++++++ src/front/wgsl/conv.rs | 14 +++ src/front/wgsl/mod.rs | 7 ++ src/lib.rs | 15 +++ src/proc/mod.rs | 14 +++ src/proc/typifier.rs | 17 ++- src/valid/expression.rs | 158 +++++++++++++++++++---- tests/in/bits.param.ron | 15 +++ tests/in/bits.wgsl | 39 ++++++ tests/in/glsl/bits_glsl.frag | 40 ++++++ tests/out/glsl/bits.main.Compute.glsl | 90 +++++++++++++ tests/out/ir/shadow.ron | 5 + tests/out/msl/bits.msl | 87 +++++++++++++ tests/out/spv/bits.spvasm | 155 +++++++++++++++++++++++ tests/out/wgsl/bits.wgsl | 83 ++++++++++++ tests/out/wgsl/bits_glsl-frag.wgsl | 80 ++++++++++++ tests/snapshots.rs | 4 + 25 files changed, 1225 insertions(+), 40 deletions(-) create mode 100644 tests/in/bits.param.ron create mode 100644 tests/in/bits.wgsl create mode 100644 tests/in/glsl/bits_glsl.frag create mode 100644 tests/out/glsl/bits.main.Compute.glsl create mode 100644 tests/out/msl/bits.msl create mode 100644 tests/out/spv/bits.spvasm create mode 100644 tests/out/wgsl/bits.wgsl create mode 100644 tests/out/wgsl/bits_glsl-frag.wgsl diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index e9fc13348..d9f774911 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -322,6 +322,7 @@ fn write_fun( arg, arg1, arg2, + arg3, } => { edges.insert("arg", arg); if let Some(expr) = arg1 { @@ -330,6 +331,9 @@ fn write_fun( if let Some(expr) = arg2 { edges.insert("arg2", expr); } + if let Some(expr) = arg3 { + edges.insert("arg3", expr); + } (format!("{:?}", fun).into(), 7) } E::As { diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index f2406fa9c..b79aabb87 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2321,6 +2321,7 @@ impl<'a, W: Write> Writer<'a, W> { arg, arg1, arg2, + arg3, } => { use crate::MathFunction as Mf; @@ -2385,17 +2386,56 @@ impl<'a, W: Write> Writer<'a, W> { // bits Mf::CountOneBits => "bitCount", Mf::ReverseBits => "bitfieldReverse", + Mf::ExtractBits => "bitfieldExtract", + Mf::InsertBits => "bitfieldInsert", + // data packing + Mf::Pack4x8snorm => "packSnorm4x8", + Mf::Pack4x8unorm => "packUnorm4x8", + Mf::Pack2x16snorm => "packSnorm2x16", + Mf::Pack2x16unorm => "packUnorm2x16", + Mf::Pack2x16float => "packHalf2x16", + // data unpacking + Mf::Unpack4x8snorm => "unpackSnorm4x8", + Mf::Unpack4x8unorm => "unpackUnorm4x8", + Mf::Unpack2x16snorm => "unpackSnorm2x16", + Mf::Unpack2x16unorm => "unpackUnorm2x16", + Mf::Unpack2x16float => "unpackHalf2x16", }; + let extract_bits = fun == Mf::ExtractBits; + let insert_bits = fun == Mf::InsertBits; + write!(self.out, "{}(", fun_name)?; self.write_expr(arg, ctx)?; if let Some(arg) = arg1 { write!(self.out, ", ")?; - self.write_expr(arg, ctx)?; + if extract_bits { + write!(self.out, "int(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ")")?; + } else { + self.write_expr(arg, ctx)?; + } } if let Some(arg) = arg2 { write!(self.out, ", ")?; - self.write_expr(arg, ctx)?; + if extract_bits || insert_bits { + write!(self.out, "int(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ")")?; + } else { + self.write_expr(arg, ctx)?; + } + } + if let Some(arg) = arg3 { + write!(self.out, ", ")?; + if insert_bits { + write!(self.out, "int(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ")")?; + } else { + self.write_expr(arg, ctx)?; + } } write!(self.out, ")")? } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 883b67d13..604fd94d8 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1816,6 +1816,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { arg, arg1, arg2, + arg3, } => { use crate::MathFunction as Mf; @@ -1918,6 +1919,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ", ")?; self.write_expr(module, arg, func_ctx)?; } + if let Some(arg) = arg3 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } write!(self.out, ")")? } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index efe58d3dd..bcd4dd6c4 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1110,6 +1110,7 @@ impl Writer { arg, arg1, arg2, + arg3, } => { use crate::MathFunction as Mf; @@ -1178,6 +1179,20 @@ impl Writer { // bits Mf::CountOneBits => "popcount", Mf::ReverseBits => "reverse_bits", + Mf::ExtractBits => "extract_bits", + Mf::InsertBits => "insert_bits", + // data packing + Mf::Pack4x8snorm => "pack_float_to_unorm4x8", + Mf::Pack4x8unorm => "pack_float_to_snorm4x8", + Mf::Pack2x16snorm => "pack_float_to_unorm2x16", + Mf::Pack2x16unorm => "pack_float_to_snorm2x16", + Mf::Pack2x16float => "", + // data unpacking + Mf::Unpack4x8snorm => "unpack_snorm4x8_to_float", + Mf::Unpack4x8unorm => "unpack_unorm4x8_to_float", + Mf::Unpack2x16snorm => "unpack_snorm2x16_to_float", + Mf::Unpack2x16unorm => "unpack_unorm2x16_to_float", + Mf::Unpack2x16float => "", }; if fun == Mf::Distance && scalar_argument { @@ -1186,9 +1201,20 @@ impl Writer { write!(self.out, " - ")?; self.put_expression(arg1.unwrap(), context, false)?; write!(self.out, ")")?; + } else if fun == Mf::Unpack2x16float { + write!(self.out, "float2(as_type(")?; + self.put_expression(arg, context, false)?; + write!(self.out, "))")?; + } else if fun == Mf::Pack2x16float { + write!(self.out, "as_type(half2(")?; + self.put_expression(arg, context, false)?; + write!(self.out, "))")?; } else { write!(self.out, "{}::{}", NAMESPACE, fun_name)?; - self.put_call_parameters(iter::once(arg).chain(arg1).chain(arg2), context)?; + self.put_call_parameters( + iter::once(arg).chain(arg1).chain(arg2).chain(arg3), + context, + )?; } } crate::Expression::As { @@ -2661,8 +2687,8 @@ fn test_stack_size() { } let stack_size = addresses.end - addresses.start; // check the size (in debug only) - // last observed macOS value: 18304 - if !(15000..=20000).contains(&stack_size) { + // last observed macOS value: 20528 (CI) + if !(15000..=25000).contains(&stack_size) { panic!("`put_expression` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 491ab79ce..88c16e7cf 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -439,6 +439,7 @@ impl<'w> BlockContext<'w> { arg, arg1, arg2, + arg3, } => { use crate::MathFunction as Mf; enum MathOp { @@ -457,6 +458,10 @@ impl<'w> BlockContext<'w> { Some(handle) => self.cached[handle], None => 0, }; + let arg3_id = match arg3 { + Some(handle) => self.cached[handle], + None => 0, + }; let id = self.gen_id(); let math_op = match fun { @@ -606,6 +611,40 @@ impl<'w> BlockContext<'w> { log::error!("unimplemented math function {:?}", fun); return Err(Error::FeatureNotImplemented("math function")); } + Mf::ExtractBits => { + let op = match arg_scalar_kind { + Some(crate::ScalarKind::Uint) => spirv::Op::BitFieldUExtract, + Some(crate::ScalarKind::Sint) => spirv::Op::BitFieldSExtract, + other => unimplemented!("Unexpected sign({:?})", other), + }; + MathOp::Custom(Instruction::ternary( + op, + result_type_id, + id, + arg0_id, + arg1_id, + arg2_id, + )) + } + Mf::InsertBits => MathOp::Custom(Instruction::quaternary( + spirv::Op::BitFieldInsert, + result_type_id, + id, + arg0_id, + arg1_id, + arg2_id, + arg3_id, + )), + Mf::Pack4x8unorm => MathOp::Ext(spirv::GLOp::PackUnorm4x8), + Mf::Pack4x8snorm => MathOp::Ext(spirv::GLOp::PackSnorm4x8), + Mf::Pack2x16float => MathOp::Ext(spirv::GLOp::PackHalf2x16), + Mf::Pack2x16unorm => MathOp::Ext(spirv::GLOp::PackSnorm2x16), + Mf::Pack2x16snorm => MathOp::Ext(spirv::GLOp::PackSnorm2x16), + Mf::Unpack4x8unorm => MathOp::Ext(spirv::GLOp::UnpackUnorm4x8), + Mf::Unpack4x8snorm => MathOp::Ext(spirv::GLOp::UnpackSnorm4x8), + Mf::Unpack2x16float => MathOp::Ext(spirv::GLOp::UnpackHalf2x16), + Mf::Unpack2x16unorm => MathOp::Ext(spirv::GLOp::UnpackSnorm2x16), + Mf::Unpack2x16snorm => MathOp::Ext(spirv::GLOp::UnpackSnorm2x16), }; block.body.push(match math_op { @@ -614,7 +653,7 @@ impl<'w> BlockContext<'w> { op, result_type_id, id, - &[arg0_id, arg1_id, arg2_id][..fun.argument_count()], + &[arg0_id, arg1_id, arg2_id, arg3_id][..fun.argument_count()], ), MathOp::Custom(inst) => inst, }); diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index ac738dfa6..211c51a1e 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -703,6 +703,42 @@ impl super::Instruction { instruction } + pub(super) fn ternary( + op: Op, + result_type_id: Word, + id: Word, + operand_1: Word, + operand_2: Word, + operand_3: Word, + ) -> Self { + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(operand_1); + instruction.add_operand(operand_2); + instruction.add_operand(operand_3); + instruction + } + + pub(super) fn quaternary( + op: Op, + result_type_id: Word, + id: Word, + operand_1: Word, + operand_2: Word, + operand_3: Word, + operand_4: Word, + ) -> Self { + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(operand_1); + instruction.add_operand(operand_2); + instruction.add_operand(operand_3); + instruction.add_operand(operand_4); + instruction + } + pub(super) fn relational(op: Op, result_type_id: Word, id: Word, expr_id: Word) -> Self { let mut instruction = Self::new(op); instruction.set_type(result_type_id); diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index a215722fb..82b46838b 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1456,6 +1456,7 @@ impl Writer { arg, arg1, arg2, + arg3, } => { use crate::MathFunction as Mf; @@ -1523,6 +1524,20 @@ impl Writer { // bits Mf::CountOneBits => Function::Regular("countOneBits"), Mf::ReverseBits => Function::Regular("reverseBits"), + Mf::ExtractBits => Function::Regular("extractBits"), + Mf::InsertBits => Function::Regular("insertBits"), + // data packing + Mf::Pack4x8snorm => Function::Regular("pack4x8snorm"), + Mf::Pack4x8unorm => Function::Regular("pack4x8unorm"), + Mf::Pack2x16snorm => Function::Regular("pack2x16snorm"), + Mf::Pack2x16unorm => Function::Regular("pack2x16unorm"), + Mf::Pack2x16float => Function::Regular("pack2x16float"), + // data unpacking + Mf::Unpack4x8snorm => Function::Regular("unpack4x8snorm"), + Mf::Unpack4x8unorm => Function::Regular("unpack4x8unorm"), + Mf::Unpack2x16snorm => Function::Regular("unpack2x16snorm"), + Mf::Unpack2x16unorm => Function::Regular("unpack2x16unorm"), + Mf::Unpack2x16float => Function::Regular("unpack2x16float"), _ => { return Err(Error::UnsupportedMathFunction(fun)); } @@ -1559,6 +1574,10 @@ impl Writer { write!(self.out, ", ")?; self.write_expr(module, arg, func_ctx)?; } + if let Some(arg) = arg3 { + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + } write!(self.out, ")")? } } diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 84d7ee8e2..ed220bc98 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -630,7 +630,21 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module )) } } - "bitCount" | "bitfieldReverse" => { + "bitCount" | "bitfieldReverse" | "bitfieldExtract" | "bitfieldInsert" => { + let fun = match name { + "bitCount" => MathFunction::CountOneBits, + "bitfieldReverse" => MathFunction::ReverseBits, + "bitfieldExtract" => MathFunction::ExtractBits, + "bitfieldInsert" => MathFunction::InsertBits, + _ => unreachable!(), + }; + + let mc = match fun { + MathFunction::ExtractBits => MacroCall::BitfieldExtract, + MathFunction::InsertBits => MacroCall::BitfieldInsert, + _ => MacroCall::MathFunction(fun), + }; + // bits layout // bit 0 - int/uint // bit 1 trough 2 - dims @@ -646,21 +660,93 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module _ => Some(VectorSize::Quad), }; - let args = vec![match size { + let ty = || match size { Some(size) => TypeInner::Vector { size, kind, width }, None => TypeInner::Scalar { kind, width }, - }]; + }; - declaration.overloads.push(module.add_builtin( - args, - MacroCall::MathFunction(match name { - "bitCount" => MathFunction::CountOneBits, - "bitfieldReverse" => MathFunction::ReverseBits, - _ => unreachable!(), - }), - )) + let mut args = vec![ty()]; + + match fun { + MathFunction::ExtractBits => { + args.push(TypeInner::Scalar { + kind: Sk::Sint, + width: 4, + }); + args.push(TypeInner::Scalar { + kind: Sk::Sint, + width: 4, + }); + } + MathFunction::InsertBits => { + args.push(ty()); + args.push(TypeInner::Scalar { + kind: Sk::Sint, + width: 4, + }); + args.push(TypeInner::Scalar { + kind: Sk::Sint, + width: 4, + }); + } + _ => {} + } + + declaration.overloads.push(module.add_builtin(args, mc)) } } + "packSnorm4x8" | "packUnorm4x8" | "packSnorm2x16" | "packUnorm2x16" | "packHalf2x16" => { + let fun = match name { + "packSnorm4x8" => MathFunction::Pack4x8snorm, + "packUnorm4x8" => MathFunction::Pack4x8unorm, + "packSnorm2x16" => MathFunction::Pack2x16unorm, + "packUnorm2x16" => MathFunction::Pack2x16snorm, + "packHalf2x16" => MathFunction::Pack2x16float, + _ => unreachable!(), + }; + + let ty = match fun { + MathFunction::Pack4x8snorm | MathFunction::Pack4x8unorm => TypeInner::Vector { + size: crate::VectorSize::Quad, + kind: Sk::Float, + width: 4, + }, + MathFunction::Pack2x16unorm + | MathFunction::Pack2x16snorm + | MathFunction::Pack2x16float => TypeInner::Vector { + size: crate::VectorSize::Bi, + kind: Sk::Float, + width: 4, + }, + _ => unreachable!(), + }; + + let args = vec![ty]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::MathFunction(fun))); + } + "unpackSnorm4x8" | "unpackUnorm4x8" | "unpackSnorm2x16" | "unpackUnorm2x16" + | "unpackHalf2x16" => { + let fun = match name { + "unpackSnorm4x8" => MathFunction::Unpack4x8snorm, + "unpackUnorm4x8" => MathFunction::Unpack4x8unorm, + "unpackSnorm2x16" => MathFunction::Unpack2x16snorm, + "unpackUnorm2x16" => MathFunction::Unpack2x16unorm, + "unpackHalf2x16" => MathFunction::Unpack2x16float, + _ => unreachable!(), + }; + + let args = vec![TypeInner::Scalar { + kind: Sk::Uint, + width: 4, + }]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::MathFunction(fun))); + } "atan" => { // bits layout // bit 0 - atan/atan2 @@ -1454,6 +1540,8 @@ pub enum MacroCall { TextureSize, TexelFetch, MathFunction(MathFunction), + BitfieldExtract, + BitfieldInsert, Relational(RelationalFunction), Binary(BinaryOperator), Mod(Option), @@ -1640,10 +1728,73 @@ impl MacroCall { arg: args[0], arg1: args.get(1).copied(), arg2: args.get(2).copied(), + arg3: args.get(3).copied(), }, Span::default(), body, )), + MacroCall::BitfieldInsert => { + let conv_arg_2 = ctx.add_expression( + Expression::As { + expr: args[2], + kind: Sk::Uint, + convert: Some(4), + }, + Span::default(), + body, + ); + let conv_arg_3 = ctx.add_expression( + Expression::As { + expr: args[3], + kind: Sk::Uint, + convert: Some(4), + }, + Span::default(), + body, + ); + Ok(ctx.add_expression( + Expression::Math { + fun: MathFunction::InsertBits, + arg: args[0], + arg1: Some(args[1]), + arg2: Some(conv_arg_2), + arg3: Some(conv_arg_3), + }, + Span::default(), + body, + )) + } + MacroCall::BitfieldExtract => { + let conv_arg_1 = ctx.add_expression( + Expression::As { + expr: args[1], + kind: Sk::Uint, + convert: Some(4), + }, + Span::default(), + body, + ); + let conv_arg_2 = ctx.add_expression( + Expression::As { + expr: args[2], + kind: Sk::Uint, + convert: Some(4), + }, + Span::default(), + body, + ); + Ok(ctx.add_expression( + Expression::Math { + fun: MathFunction::ExtractBits, + arg: args[0], + arg1: Some(conv_arg_1), + arg2: Some(conv_arg_2), + arg3: None, + }, + Span::default(), + body, + )) + } MacroCall::Relational(fun) => Ok(ctx.add_expression( Expression::Relational { fun, @@ -1683,6 +1834,7 @@ impl MacroCall { arg: args[0], arg1: args.get(1).copied(), arg2: args.get(2).copied(), + arg3: args.get(3).copied(), }, Span::default(), body, @@ -1707,6 +1859,7 @@ impl MacroCall { arg: args[0], arg1: args.get(1).copied(), arg2: args.get(2).copied(), + arg3: args.get(3).copied(), }, Span::default(), body, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 552382480..4cc048150 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1330,6 +1330,7 @@ impl> Parser { arg: loaded, arg1: None, arg2: None, + arg3: None, }, span, ); @@ -1407,6 +1408,7 @@ impl> Parser { arg: loaded, arg1: None, arg2: None, + arg3: None, }, span, ) @@ -1811,6 +1813,7 @@ impl> Parser { arg: matrix_handle, arg1: None, arg2: None, + arg3: None, }; self.lookup_expression.insert( result_id, @@ -1837,6 +1840,70 @@ impl> Parser { arg: left_handle, arg1: Some(right_handle), arg2: None, + arg3: None, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: ctx.expressions.append(expr, span), + type_id: result_type_id, + block_id, + }, + ); + } + Op::BitFieldInsert => { + inst.expect(7)?; + + let result_type_id = self.next()?; + let result_id = self.next()?; + let base_id = self.next()?; + let insert_id = self.next()?; + let offset_id = self.next()?; + let count_id = self.next()?; + let base_lexp = self.lookup_expression.lookup(base_id)?; + let base_handle = get_expr_handle!(base_id, base_lexp); + let insert_lexp = self.lookup_expression.lookup(insert_id)?; + let insert_handle = get_expr_handle!(insert_id, insert_lexp); + let offset_lexp = self.lookup_expression.lookup(offset_id)?; + let offset_handle = get_expr_handle!(offset_id, offset_lexp); + let count_lexp = self.lookup_expression.lookup(count_id)?; + let count_handle = get_expr_handle!(count_id, count_lexp); + let expr = crate::Expression::Math { + fun: crate::MathFunction::InsertBits, + arg: base_handle, + arg1: Some(insert_handle), + arg2: Some(offset_handle), + arg3: Some(count_handle), + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: ctx.expressions.append(expr, span), + type_id: result_type_id, + block_id, + }, + ); + } + Op::BitFieldSExtract | Op::BitFieldUExtract => { + inst.expect(6)?; + + let result_type_id = self.next()?; + let result_id = self.next()?; + let base_id = self.next()?; + let offset_id = self.next()?; + let count_id = self.next()?; + let base_lexp = self.lookup_expression.lookup(base_id)?; + let base_handle = get_expr_handle!(base_id, base_lexp); + let offset_lexp = self.lookup_expression.lookup(offset_id)?; + let offset_handle = get_expr_handle!(offset_id, offset_lexp); + let count_lexp = self.lookup_expression.lookup(count_id)?; + let count_handle = get_expr_handle!(count_id, count_lexp); + let expr = crate::Expression::Math { + fun: crate::MathFunction::ExtractBits, + arg: base_handle, + arg1: Some(offset_handle), + arg2: Some(count_handle), + arg3: None, }; self.lookup_expression.insert( result_id, @@ -1863,6 +1930,7 @@ impl> Parser { arg: left_handle, arg1: Some(right_handle), arg2: None, + arg3: None, }; self.lookup_expression.insert( result_id, @@ -2352,6 +2420,16 @@ impl> Parser { Glo::FaceForward => Mf::FaceForward, Glo::Reflect => Mf::Reflect, Glo::Refract => Mf::Refract, + Glo::PackUnorm4x8 => Mf::Pack4x8unorm, + Glo::PackSnorm4x8 => Mf::Pack4x8snorm, + Glo::PackHalf2x16 => Mf::Pack2x16float, + Glo::PackUnorm2x16 => Mf::Pack2x16unorm, + Glo::PackSnorm2x16 => Mf::Pack2x16snorm, + Glo::UnpackUnorm4x8 => Mf::Unpack4x8unorm, + Glo::UnpackSnorm4x8 => Mf::Unpack4x8snorm, + Glo::UnpackHalf2x16 => Mf::Unpack2x16float, + Glo::UnpackUnorm2x16 => Mf::Unpack2x16unorm, + Glo::UnpackSnorm2x16 => Mf::Unpack2x16snorm, _ => return Err(Error::UnsupportedExtInst(inst_id)), }; @@ -2376,12 +2454,20 @@ impl> Parser { } else { None }; + let arg3 = if arg_count > 3 { + let arg_id = self.next()?; + let lexp = self.lookup_expression.lookup(arg_id)?; + Some(get_expr_handle!(arg_id, lexp)) + } else { + None + }; let expr = crate::Expression::Math { fun, arg, arg1, arg2, + arg3, }; self.lookup_expression.insert( result_id, diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 519073fc3..add465f18 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -198,6 +198,20 @@ pub fn map_standard_fun(word: &str) -> Option { // bits "countOneBits" => Mf::CountOneBits, "reverseBits" => Mf::ReverseBits, + "extractBits" => Mf::ExtractBits, + "insertBits" => Mf::InsertBits, + // data packing + "pack4x8snorm" => Mf::Pack4x8snorm, + "pack4x8unorm" => Mf::Pack4x8unorm, + "pack2x16snorm" => Mf::Pack2x16snorm, + "pack2x16unorm" => Mf::Pack2x16unorm, + "pack2x16float" => Mf::Pack2x16float, + // data unpacking + "unpack4x8snorm" => Mf::Unpack4x8snorm, + "unpack4x8unorm" => Mf::Unpack4x8unorm, + "unpack2x16snorm" => Mf::Unpack2x16snorm, + "unpack2x16unorm" => Mf::Unpack2x16unorm, + "unpack2x16float" => Mf::Unpack2x16float, _ => return None, }) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 800851a74..289282a43 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1400,12 +1400,19 @@ impl Parser { } else { None }; + let arg3 = if arg_count > 3 { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; lexer.close_arguments()?; crate::Expression::Math { fun, arg, arg1, arg2, + arg3, } } else { match name { diff --git a/src/lib.rs b/src/lib.rs index 97b5b9f52..737e0bfca 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -934,6 +934,20 @@ pub enum MathFunction { // bits CountOneBits, ReverseBits, + ExtractBits, + InsertBits, + // data packing + Pack4x8snorm, + Pack4x8unorm, + Pack2x16snorm, + Pack2x16unorm, + Pack2x16float, + // data unpacking + Unpack4x8snorm, + Unpack4x8unorm, + Unpack2x16snorm, + Unpack2x16unorm, + Unpack2x16float, } /// Sampling modifier to control the level of detail. @@ -1255,6 +1269,7 @@ pub enum Expression { arg: Handle, arg1: Option>, arg2: Option>, + arg3: Option>, }, /// Cast a simple type to another kind. As { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index fd6015e62..c9a66585c 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -245,6 +245,20 @@ impl super::MathFunction { // bits Self::CountOneBits => 1, Self::ReverseBits => 1, + Self::ExtractBits => 3, + Self::InsertBits => 4, + // data packing + Self::Pack4x8snorm => 1, + Self::Pack4x8unorm => 1, + Self::Pack2x16snorm => 1, + Self::Pack2x16unorm => 1, + Self::Pack2x16float => 1, + // data unpacking + Self::Unpack4x8snorm => 1, + Self::Unpack4x8unorm => 1, + Self::Unpack2x16snorm => 1, + Self::Unpack2x16unorm => 1, + Self::Unpack2x16float => 1, } } } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 217eeb1e2..e1d2bd6b8 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -659,6 +659,7 @@ impl<'a> ResolveContext<'a> { arg, arg1, arg2: _, + arg3: _, } => { use crate::MathFunction as Mf; let res_arg = past(arg); @@ -781,7 +782,21 @@ impl<'a> ResolveContext<'a> { }, // bits Mf::CountOneBits | - Mf::ReverseBits => res_arg.clone(), + Mf::ReverseBits | + Mf::ExtractBits | + Mf::InsertBits => res_arg.clone(), + // data packing + Mf::Pack4x8snorm | + Mf::Pack4x8unorm | + Mf::Pack2x16snorm | + Mf::Pack2x16unorm | + Mf::Pack2x16float => TypeResolution::Value(Ti::Scalar { kind: crate::ScalarKind::Uint, width: 4 }), + // data unpacking + Mf::Unpack4x8snorm | + Mf::Unpack4x8unorm => TypeResolution::Value(Ti::Vector { size: crate::VectorSize::Quad, kind: crate::ScalarKind::Float, width: 4 }), + Mf::Unpack2x16snorm | + Mf::Unpack2x16unorm | + Mf::Unpack2x16float => TypeResolution::Value(Ti::Vector { size: crate::VectorSize::Bi, kind: crate::ScalarKind::Float, width: 4 }), } } crate::Expression::As { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 8c1f659f9..a9dab24cd 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -870,15 +870,17 @@ impl super::Validator { arg, arg1, arg2, + arg3, } => { use crate::MathFunction as Mf; let arg_ty = resolver.resolve(arg)?; let arg1_ty = arg1.map(|expr| resolver.resolve(expr)).transpose()?; let arg2_ty = arg2.map(|expr| resolver.resolve(expr)).transpose()?; + let arg3_ty = arg3.map(|expr| resolver.resolve(expr)).transpose()?; match fun { Mf::Abs => { - if arg1_ty.is_some() | arg2_ty.is_some() { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } let good = match *arg_ty { @@ -890,8 +892,8 @@ impl super::Validator { } } Mf::Min | Mf::Max => { - let arg1_ty = match (arg1_ty, arg2_ty) { - (Some(ty1), None) => ty1, + let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), None, None) => ty1, _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; let good = match *arg_ty { @@ -910,8 +912,8 @@ impl super::Validator { } } Mf::Clamp => { - let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty) { - (Some(ty1), Some(ty2)) => (ty1, ty2), + let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), Some(ty2), None) => (ty1, ty2), _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; let good = match *arg_ty { @@ -961,7 +963,7 @@ impl super::Validator { | Mf::Sign | Mf::Sqrt | Mf::InverseSqrt => { - if arg1_ty.is_some() | arg2_ty.is_some() { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -975,8 +977,8 @@ impl super::Validator { } } Mf::Atan2 | Mf::Pow | Mf::Distance | Mf::Step => { - let arg1_ty = match (arg1_ty, arg2_ty) { - (Some(ty1), None) => ty1, + let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), None, None) => ty1, _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; match *arg_ty { @@ -997,8 +999,8 @@ impl super::Validator { } } Mf::Modf | Mf::Frexp | Mf::Ldexp => { - let arg1_ty = match (arg1_ty, arg2_ty) { - (Some(ty1), None) => ty1, + let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), None, None) => ty1, _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; let (size0, width0) = match *arg_ty { @@ -1032,8 +1034,8 @@ impl super::Validator { } } Mf::Dot | Mf::Outer | Mf::Cross | Mf::Reflect => { - let arg1_ty = match (arg1_ty, arg2_ty) { - (Some(ty1), None) => ty1, + let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), None, None) => ty1, _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; match *arg_ty { @@ -1051,8 +1053,8 @@ impl super::Validator { } } Mf::Refract => { - let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty) { - (Some(ty1), Some(ty2)) => (ty1, ty2), + let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), Some(ty2), None) => (ty1, ty2), _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; @@ -1092,7 +1094,7 @@ impl super::Validator { } } Mf::Normalize => { - if arg1_ty.is_some() | arg2_ty.is_some() { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -1103,8 +1105,8 @@ impl super::Validator { } } Mf::FaceForward | Mf::Fma | Mf::SmoothStep => { - let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty) { - (Some(ty1), Some(ty2)) => (ty1, ty2), + let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), Some(ty2), None) => (ty1, ty2), _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; match *arg_ty { @@ -1132,8 +1134,8 @@ impl super::Validator { } } Mf::Mix => { - let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty) { - (Some(ty1), Some(ty2)) => (ty1, ty2), + let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), Some(ty2), None) => (ty1, ty2), _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; let arg_width = match *arg_ty { @@ -1172,7 +1174,7 @@ impl super::Validator { } } Mf::Inverse | Mf::Determinant => { - if arg1_ty.is_some() | arg2_ty.is_some() { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } let good = match *arg_ty { @@ -1184,7 +1186,7 @@ impl super::Validator { } } Mf::Transpose => { - if arg1_ty.is_some() | arg2_ty.is_some() { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -1193,7 +1195,7 @@ impl super::Validator { } } Mf::CountOneBits | Mf::ReverseBits => { - if arg1_ty.is_some() | arg2_ty.is_some() { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -1204,6 +1206,118 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } } + Mf::InsertBits => { + let (arg1_ty, arg2_ty, arg3_ty) = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), Some(ty2), Some(ty3)) => (ty1, ty2, ty3), + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + match *arg_ty { + Ti::Scalar { kind: Sk::Sint, .. } + | Ti::Scalar { kind: Sk::Uint, .. } + | Ti::Vector { kind: Sk::Sint, .. } + | Ti::Vector { kind: Sk::Uint, .. } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + if arg1_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + match *arg2_ty { + Ti::Scalar { kind: Sk::Uint, .. } => {} + _ => { + return Err(ExpressionError::InvalidArgumentType( + fun, + 2, + arg2.unwrap(), + )) + } + } + match *arg3_ty { + Ti::Scalar { kind: Sk::Uint, .. } => {} + _ => { + return Err(ExpressionError::InvalidArgumentType( + fun, + 2, + arg3.unwrap(), + )) + } + } + } + Mf::ExtractBits => { + let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), Some(ty2), None) => (ty1, ty2), + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + match *arg_ty { + Ti::Scalar { kind: Sk::Sint, .. } + | Ti::Scalar { kind: Sk::Uint, .. } + | Ti::Vector { kind: Sk::Sint, .. } + | Ti::Vector { kind: Sk::Uint, .. } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + match *arg1_ty { + Ti::Scalar { kind: Sk::Uint, .. } => {} + _ => { + return Err(ExpressionError::InvalidArgumentType( + fun, + 2, + arg1.unwrap(), + )) + } + } + match *arg2_ty { + Ti::Scalar { kind: Sk::Uint, .. } => {} + _ => { + return Err(ExpressionError::InvalidArgumentType( + fun, + 2, + arg2.unwrap(), + )) + } + } + } + Mf::Pack2x16unorm | Mf::Pack2x16snorm | Mf::Pack2x16float => { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + match *arg_ty { + Ti::Vector { + size: crate::VectorSize::Bi, + kind: Sk::Float, + .. + } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + } + Mf::Pack4x8snorm | Mf::Pack4x8unorm => { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + match *arg_ty { + Ti::Vector { + size: crate::VectorSize::Quad, + kind: Sk::Float, + .. + } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + } + Mf::Unpack2x16float + | Mf::Unpack2x16snorm + | Mf::Unpack2x16unorm + | Mf::Unpack4x8snorm + | Mf::Unpack4x8unorm => { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + match *arg_ty { + Ti::Scalar { kind: Sk::Uint, .. } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + } } ShaderStages::all() } diff --git a/tests/in/bits.param.ron b/tests/in/bits.param.ron new file mode 100644 index 000000000..fb45784e5 --- /dev/null +++ b/tests/in/bits.param.ron @@ -0,0 +1,15 @@ +( + msl: ( + lang_version: (1, 2), + per_stage_map: ( + cs: ( + resources: { + }, + sizes_buffer: Some(0), + ) + ), + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + ), +) diff --git a/tests/in/bits.wgsl b/tests/in/bits.wgsl new file mode 100644 index 000000000..1834411f3 --- /dev/null +++ b/tests/in/bits.wgsl @@ -0,0 +1,39 @@ +[[stage(compute), workgroup_size(1)]] +fn main() { + var i = 0; + var i2 = vec2(0); + var i3 = vec3(0); + var i4 = vec4(0); + var u = 0u; + var u2 = vec2(0u); + var u3 = vec3(0u); + var u4 = vec4(0u); + var f2 = vec2(0.0); + var f4 = vec4(0.0); + u = pack4x8snorm(f4); + u = pack4x8unorm(f4); + u = pack2x16snorm(f2); + u = pack2x16unorm(f2); + u = pack2x16float(f2); + f4 = unpack4x8snorm(u); + f4 = unpack4x8unorm(u); + f2 = unpack2x16snorm(u); + f2 = unpack2x16unorm(u); + f2 = unpack2x16float(u); + i = insertBits(i, i, 5u, 10u); + i2 = insertBits(i2, i2, 5u, 10u); + i3 = insertBits(i3, i3, 5u, 10u); + i4 = insertBits(i4, i4, 5u, 10u); + u = insertBits(u, u, 5u, 10u); + u2 = insertBits(u2, u2, 5u, 10u); + u3 = insertBits(u3, u3, 5u, 10u); + u4 = insertBits(u4, u4, 5u, 10u); + i = extractBits(i, 5u, 10u); + i2 = extractBits(i2, 5u, 10u); + i3 = extractBits(i3, 5u, 10u); + i4 = extractBits(i4, 5u, 10u); + u = extractBits(u, 5u, 10u); + u2 = extractBits(u2, 5u, 10u); + u3 = extractBits(u3, 5u, 10u); + u4 = extractBits(u4, 5u, 10u); +} diff --git a/tests/in/glsl/bits_glsl.frag b/tests/in/glsl/bits_glsl.frag new file mode 100644 index 000000000..cd960ed86 --- /dev/null +++ b/tests/in/glsl/bits_glsl.frag @@ -0,0 +1,40 @@ +#version 450 + +void main() { + int i = 0; + ivec2 i2 = ivec2(0); + ivec3 i3 = ivec3(0); + ivec4 i4 = ivec4(0); + uint u = 0; + uvec2 u2 = uvec2(0); + uvec3 u3 = uvec3(0); + uvec4 u4 = uvec4(0); + vec2 f2 = vec2(0.0); + vec4 f4 = vec4(0.0); + u = packSnorm4x8(f4); + u = packUnorm4x8(f4); + u = packSnorm2x16(f2); + u = packUnorm2x16(f2); + u = packHalf2x16(f2); + f4 = unpackSnorm4x8(u); + f4 = unpackUnorm4x8(u); + f2 = unpackSnorm2x16(u); + f2 = unpackUnorm2x16(u); + f2 = unpackHalf2x16(u); + i = bitfieldInsert(i, i, 5, 10); + i2 = bitfieldInsert(i2, i2, 5, 10); + i3 = bitfieldInsert(i3, i3, 5, 10); + i4 = bitfieldInsert(i4, i4, 5, 10); + u = bitfieldInsert(u, u, 5, 10); + u2 = bitfieldInsert(u2, u2, 5, 10); + u3 = bitfieldInsert(u3, u3, 5, 10); + u4 = bitfieldInsert(u4, u4, 5, 10); + i = bitfieldExtract(i, 5, 10); + i2 = bitfieldExtract(i2, 5, 10); + i3 = bitfieldExtract(i3, 5, 10); + i4 = bitfieldExtract(i4, 5, 10); + u = bitfieldExtract(u, 5, 10); + u2 = bitfieldExtract(u2, 5, 10); + u3 = bitfieldExtract(u3, 5, 10); + u4 = bitfieldExtract(u4, 5, 10); +} \ No newline at end of file diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl new file mode 100644 index 000000000..303cdbc44 --- /dev/null +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -0,0 +1,90 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + + +void main() { + int i = 0; + ivec2 i2_ = ivec2(0, 0); + ivec3 i3_ = ivec3(0, 0, 0); + ivec4 i4_ = ivec4(0, 0, 0, 0); + uint u = 0u; + uvec2 u2_ = uvec2(0u, 0u); + uvec3 u3_ = uvec3(0u, 0u, 0u); + uvec4 u4_ = uvec4(0u, 0u, 0u, 0u); + vec2 f2_ = vec2(0.0, 0.0); + vec4 f4_ = vec4(0.0, 0.0, 0.0, 0.0); + i2_ = ivec2(0); + i3_ = ivec3(0); + i4_ = ivec4(0); + u2_ = uvec2(0u); + u3_ = uvec3(0u); + u4_ = uvec4(0u); + f2_ = vec2(0.0); + f4_ = vec4(0.0); + vec4 _e28 = f4_; + u = packSnorm4x8(_e28); + vec4 _e30 = f4_; + u = packUnorm4x8(_e30); + vec2 _e32 = f2_; + u = packSnorm2x16(_e32); + vec2 _e34 = f2_; + u = packUnorm2x16(_e34); + vec2 _e36 = f2_; + u = packHalf2x16(_e36); + uint _e38 = u; + f4_ = unpackSnorm4x8(_e38); + uint _e40 = u; + f4_ = unpackUnorm4x8(_e40); + uint _e42 = u; + f2_ = unpackSnorm2x16(_e42); + uint _e44 = u; + f2_ = unpackUnorm2x16(_e44); + uint _e46 = u; + f2_ = unpackHalf2x16(_e46); + int _e48 = i; + int _e49 = i; + i = bitfieldInsert(_e48, _e49, int(5u), int(10u)); + ivec2 _e53 = i2_; + ivec2 _e54 = i2_; + i2_ = bitfieldInsert(_e53, _e54, int(5u), int(10u)); + ivec3 _e58 = i3_; + ivec3 _e59 = i3_; + i3_ = bitfieldInsert(_e58, _e59, int(5u), int(10u)); + ivec4 _e63 = i4_; + ivec4 _e64 = i4_; + i4_ = bitfieldInsert(_e63, _e64, int(5u), int(10u)); + uint _e68 = u; + uint _e69 = u; + u = bitfieldInsert(_e68, _e69, int(5u), int(10u)); + uvec2 _e73 = u2_; + uvec2 _e74 = u2_; + u2_ = bitfieldInsert(_e73, _e74, int(5u), int(10u)); + uvec3 _e78 = u3_; + uvec3 _e79 = u3_; + u3_ = bitfieldInsert(_e78, _e79, int(5u), int(10u)); + uvec4 _e83 = u4_; + uvec4 _e84 = u4_; + u4_ = bitfieldInsert(_e83, _e84, int(5u), int(10u)); + int _e88 = i; + i = bitfieldExtract(_e88, int(5u), int(10u)); + ivec2 _e92 = i2_; + i2_ = bitfieldExtract(_e92, int(5u), int(10u)); + ivec3 _e96 = i3_; + i3_ = bitfieldExtract(_e96, int(5u), int(10u)); + ivec4 _e100 = i4_; + i4_ = bitfieldExtract(_e100, int(5u), int(10u)); + uint _e104 = u; + u = bitfieldExtract(_e104, int(5u), int(10u)); + uvec2 _e108 = u2_; + u2_ = bitfieldExtract(_e108, int(5u), int(10u)); + uvec3 _e112 = u3_; + u3_ = bitfieldExtract(_e112, int(5u), int(10u)); + uvec4 _e116 = u4_; + u4_ = bitfieldExtract(_e116, int(5u), int(10u)); + return; +} + diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 4dae9ffae..572ffe39f 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -968,6 +968,7 @@ arg: 52, arg1: Some(32), arg2: None, + arg3: None, ), Binary( op: GreaterEqual, @@ -1015,6 +1016,7 @@ arg: 65, arg1: None, arg2: None, + arg3: None, ), AccessIndex( base: 6, @@ -1129,18 +1131,21 @@ arg: 93, arg1: None, arg2: None, + arg3: None, ), Math( fun: Dot, arg: 66, arg1: Some(94), arg2: None, + arg3: None, ), Math( fun: Max, arg: 46, arg1: Some(95), arg2: None, + arg3: None, ), Binary( op: Multiply, diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl new file mode 100644 index 000000000..70ca905e3 --- /dev/null +++ b/tests/out/msl/bits.msl @@ -0,0 +1,87 @@ +// language: metal1.2 +#include +#include + + +kernel void main1( +) { + int i = 0; + metal::int2 i2_; + metal::int3 i3_; + metal::int4 i4_; + metal::uint u = 0u; + metal::uint2 u2_; + metal::uint3 u3_; + metal::uint4 u4_; + metal::float2 f2_; + metal::float4 f4_; + i2_ = metal::int2(0); + i3_ = metal::int3(0); + i4_ = metal::int4(0); + u2_ = metal::uint2(0u); + u3_ = metal::uint3(0u); + u4_ = metal::uint4(0u); + f2_ = metal::float2(0.0); + f4_ = metal::float4(0.0); + metal::float4 _e28 = f4_; + u = metal::pack_float_to_unorm4x8(_e28); + metal::float4 _e30 = f4_; + u = metal::pack_float_to_snorm4x8(_e30); + metal::float2 _e32 = f2_; + u = metal::pack_float_to_unorm2x16(_e32); + metal::float2 _e34 = f2_; + u = metal::pack_float_to_snorm2x16(_e34); + metal::float2 _e36 = f2_; + u = as_type(half2(_e36)); + metal::uint _e38 = u; + f4_ = metal::unpack_snorm4x8_to_float(_e38); + metal::uint _e40 = u; + f4_ = metal::unpack_unorm4x8_to_float(_e40); + metal::uint _e42 = u; + f2_ = metal::unpack_snorm2x16_to_float(_e42); + metal::uint _e44 = u; + f2_ = metal::unpack_unorm2x16_to_float(_e44); + metal::uint _e46 = u; + f2_ = float2(as_type(_e46)); + int _e48 = i; + int _e49 = i; + i = metal::insert_bits(_e48, _e49, 5u, 10u); + metal::int2 _e53 = i2_; + metal::int2 _e54 = i2_; + i2_ = metal::insert_bits(_e53, _e54, 5u, 10u); + metal::int3 _e58 = i3_; + metal::int3 _e59 = i3_; + i3_ = metal::insert_bits(_e58, _e59, 5u, 10u); + metal::int4 _e63 = i4_; + metal::int4 _e64 = i4_; + i4_ = metal::insert_bits(_e63, _e64, 5u, 10u); + metal::uint _e68 = u; + metal::uint _e69 = u; + u = metal::insert_bits(_e68, _e69, 5u, 10u); + metal::uint2 _e73 = u2_; + metal::uint2 _e74 = u2_; + u2_ = metal::insert_bits(_e73, _e74, 5u, 10u); + metal::uint3 _e78 = u3_; + metal::uint3 _e79 = u3_; + u3_ = metal::insert_bits(_e78, _e79, 5u, 10u); + metal::uint4 _e83 = u4_; + metal::uint4 _e84 = u4_; + u4_ = metal::insert_bits(_e83, _e84, 5u, 10u); + int _e88 = i; + i = metal::extract_bits(_e88, 5u, 10u); + metal::int2 _e92 = i2_; + i2_ = metal::extract_bits(_e92, 5u, 10u); + metal::int3 _e96 = i3_; + i3_ = metal::extract_bits(_e96, 5u, 10u); + metal::int4 _e100 = i4_; + i4_ = metal::extract_bits(_e100, 5u, 10u); + metal::uint _e104 = u; + u = metal::extract_bits(_e104, 5u, 10u); + metal::uint2 _e108 = u2_; + u2_ = metal::extract_bits(_e108, 5u, 10u); + metal::uint3 _e112 = u3_; + u3_ = metal::extract_bits(_e112, 5u, 10u); + metal::uint4 _e116 = u4_; + u4_ = metal::extract_bits(_e116, 5u, 10u); + return; +} diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm new file mode 100644 index 000000000..f7b838453 --- /dev/null +++ b/tests/out/spv/bits.spvasm @@ -0,0 +1,155 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 111 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %40 "main" +OpExecutionMode %40 LocalSize 1 1 1 +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 0 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 0 +%8 = OpTypeFloat 32 +%7 = OpConstant %8 0.0 +%9 = OpConstant %6 5 +%10 = OpConstant %6 10 +%11 = OpTypeVector %4 2 +%12 = OpTypeVector %4 3 +%13 = OpTypeVector %4 4 +%14 = OpTypeVector %6 2 +%15 = OpTypeVector %6 3 +%16 = OpTypeVector %6 4 +%17 = OpTypeVector %8 2 +%18 = OpTypeVector %8 4 +%20 = OpTypePointer Function %4 +%22 = OpTypePointer Function %11 +%24 = OpTypePointer Function %12 +%26 = OpTypePointer Function %13 +%28 = OpTypePointer Function %6 +%30 = OpTypePointer Function %14 +%32 = OpTypePointer Function %15 +%34 = OpTypePointer Function %16 +%36 = OpTypePointer Function %17 +%38 = OpTypePointer Function %18 +%41 = OpTypeFunction %2 +%40 = OpFunction %2 None %41 +%39 = OpLabel +%37 = OpVariable %38 Function +%31 = OpVariable %32 Function +%25 = OpVariable %26 Function +%19 = OpVariable %20 Function %3 +%33 = OpVariable %34 Function +%27 = OpVariable %28 Function %5 +%21 = OpVariable %22 Function +%35 = OpVariable %36 Function +%29 = OpVariable %30 Function +%23 = OpVariable %24 Function +OpBranch %42 +%42 = OpLabel +%43 = OpCompositeConstruct %11 %3 %3 +OpStore %21 %43 +%44 = OpCompositeConstruct %12 %3 %3 %3 +OpStore %23 %44 +%45 = OpCompositeConstruct %13 %3 %3 %3 %3 +OpStore %25 %45 +%46 = OpCompositeConstruct %14 %5 %5 +OpStore %29 %46 +%47 = OpCompositeConstruct %15 %5 %5 %5 +OpStore %31 %47 +%48 = OpCompositeConstruct %16 %5 %5 %5 %5 +OpStore %33 %48 +%49 = OpCompositeConstruct %17 %7 %7 +OpStore %35 %49 +%50 = OpCompositeConstruct %18 %7 %7 %7 %7 +OpStore %37 %50 +%51 = OpLoad %18 %37 +%52 = OpExtInst %6 %1 PackSnorm4x8 %51 +OpStore %27 %52 +%53 = OpLoad %18 %37 +%54 = OpExtInst %6 %1 PackUnorm4x8 %53 +OpStore %27 %54 +%55 = OpLoad %17 %35 +%56 = OpExtInst %6 %1 PackSnorm2x16 %55 +OpStore %27 %56 +%57 = OpLoad %17 %35 +%58 = OpExtInst %6 %1 PackSnorm2x16 %57 +OpStore %27 %58 +%59 = OpLoad %17 %35 +%60 = OpExtInst %6 %1 PackHalf2x16 %59 +OpStore %27 %60 +%61 = OpLoad %6 %27 +%62 = OpExtInst %18 %1 UnpackSnorm4x8 %61 +OpStore %37 %62 +%63 = OpLoad %6 %27 +%64 = OpExtInst %18 %1 UnpackUnorm4x8 %63 +OpStore %37 %64 +%65 = OpLoad %6 %27 +%66 = OpExtInst %17 %1 UnpackSnorm2x16 %65 +OpStore %35 %66 +%67 = OpLoad %6 %27 +%68 = OpExtInst %17 %1 UnpackSnorm2x16 %67 +OpStore %35 %68 +%69 = OpLoad %6 %27 +%70 = OpExtInst %17 %1 UnpackHalf2x16 %69 +OpStore %35 %70 +%71 = OpLoad %4 %19 +%72 = OpLoad %4 %19 +%73 = OpBitFieldInsert %4 %71 %72 %9 %10 +OpStore %19 %73 +%74 = OpLoad %11 %21 +%75 = OpLoad %11 %21 +%76 = OpBitFieldInsert %11 %74 %75 %9 %10 +OpStore %21 %76 +%77 = OpLoad %12 %23 +%78 = OpLoad %12 %23 +%79 = OpBitFieldInsert %12 %77 %78 %9 %10 +OpStore %23 %79 +%80 = OpLoad %13 %25 +%81 = OpLoad %13 %25 +%82 = OpBitFieldInsert %13 %80 %81 %9 %10 +OpStore %25 %82 +%83 = OpLoad %6 %27 +%84 = OpLoad %6 %27 +%85 = OpBitFieldInsert %6 %83 %84 %9 %10 +OpStore %27 %85 +%86 = OpLoad %14 %29 +%87 = OpLoad %14 %29 +%88 = OpBitFieldInsert %14 %86 %87 %9 %10 +OpStore %29 %88 +%89 = OpLoad %15 %31 +%90 = OpLoad %15 %31 +%91 = OpBitFieldInsert %15 %89 %90 %9 %10 +OpStore %31 %91 +%92 = OpLoad %16 %33 +%93 = OpLoad %16 %33 +%94 = OpBitFieldInsert %16 %92 %93 %9 %10 +OpStore %33 %94 +%95 = OpLoad %4 %19 +%96 = OpBitFieldSExtract %4 %95 %9 %10 +OpStore %19 %96 +%97 = OpLoad %11 %21 +%98 = OpBitFieldSExtract %11 %97 %9 %10 +OpStore %21 %98 +%99 = OpLoad %12 %23 +%100 = OpBitFieldSExtract %12 %99 %9 %10 +OpStore %23 %100 +%101 = OpLoad %13 %25 +%102 = OpBitFieldSExtract %13 %101 %9 %10 +OpStore %25 %102 +%103 = OpLoad %6 %27 +%104 = OpBitFieldUExtract %6 %103 %9 %10 +OpStore %27 %104 +%105 = OpLoad %14 %29 +%106 = OpBitFieldUExtract %14 %105 %9 %10 +OpStore %29 %106 +%107 = OpLoad %15 %31 +%108 = OpBitFieldUExtract %15 %107 %9 %10 +OpStore %31 %108 +%109 = OpLoad %16 %33 +%110 = OpBitFieldUExtract %16 %109 %9 %10 +OpStore %33 %110 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl new file mode 100644 index 000000000..c4054d8e3 --- /dev/null +++ b/tests/out/wgsl/bits.wgsl @@ -0,0 +1,83 @@ +[[stage(compute), workgroup_size(1, 1, 1)]] +fn main() { + var i: i32 = 0; + var i2_: vec2; + var i3_: vec3; + var i4_: vec4; + var u: u32 = 0u; + var u2_: vec2; + var u3_: vec3; + var u4_: vec4; + var f2_: vec2; + var f4_: vec4; + + i2_ = vec2(0); + i3_ = vec3(0); + i4_ = vec4(0); + u2_ = vec2(0u); + u3_ = vec3(0u); + u4_ = vec4(0u); + f2_ = vec2(0.0); + f4_ = vec4(0.0); + let e28: vec4 = f4_; + u = pack4x8snorm(e28); + let e30: vec4 = f4_; + u = pack4x8unorm(e30); + let e32: vec2 = f2_; + u = pack2x16snorm(e32); + let e34: vec2 = f2_; + u = pack2x16unorm(e34); + let e36: vec2 = f2_; + u = pack2x16float(e36); + let e38: u32 = u; + f4_ = unpack4x8snorm(e38); + let e40: u32 = u; + f4_ = unpack4x8unorm(e40); + let e42: u32 = u; + f2_ = unpack2x16snorm(e42); + let e44: u32 = u; + f2_ = unpack2x16unorm(e44); + let e46: u32 = u; + f2_ = unpack2x16float(e46); + let e48: i32 = i; + let e49: i32 = i; + i = insertBits(e48, e49, 5u, 10u); + let e53: vec2 = i2_; + let e54: vec2 = i2_; + i2_ = insertBits(e53, e54, 5u, 10u); + let e58: vec3 = i3_; + let e59: vec3 = i3_; + i3_ = insertBits(e58, e59, 5u, 10u); + let e63: vec4 = i4_; + let e64: vec4 = i4_; + i4_ = insertBits(e63, e64, 5u, 10u); + let e68: u32 = u; + let e69: u32 = u; + u = insertBits(e68, e69, 5u, 10u); + let e73: vec2 = u2_; + let e74: vec2 = u2_; + u2_ = insertBits(e73, e74, 5u, 10u); + let e78: vec3 = u3_; + let e79: vec3 = u3_; + u3_ = insertBits(e78, e79, 5u, 10u); + let e83: vec4 = u4_; + let e84: vec4 = u4_; + u4_ = insertBits(e83, e84, 5u, 10u); + let e88: i32 = i; + i = extractBits(e88, 5u, 10u); + let e92: vec2 = i2_; + i2_ = extractBits(e92, 5u, 10u); + let e96: vec3 = i3_; + i3_ = extractBits(e96, 5u, 10u); + let e100: vec4 = i4_; + i4_ = extractBits(e100, 5u, 10u); + let e104: u32 = u; + u = extractBits(e104, 5u, 10u); + let e108: vec2 = u2_; + u2_ = extractBits(e108, 5u, 10u); + let e112: vec3 = u3_; + u3_ = extractBits(e112, 5u, 10u); + let e116: vec4 = u4_; + u4_ = extractBits(e116, 5u, 10u); + return; +} diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl new file mode 100644 index 000000000..2eb77888c --- /dev/null +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -0,0 +1,80 @@ +fn main1() { + var i: i32 = 0; + var i2_: vec2 = vec2(0, 0); + var i3_: vec3 = vec3(0, 0, 0); + var i4_: vec4 = vec4(0, 0, 0, 0); + var u: u32 = 0u; + var u2_: vec2 = vec2(0u, 0u); + var u3_: vec3 = vec3(0u, 0u, 0u); + var u4_: vec4 = vec4(0u, 0u, 0u, 0u); + var f2_: vec2 = vec2(0.0, 0.0); + var f4_: vec4 = vec4(0.0, 0.0, 0.0, 0.0); + + let e33: vec4 = f4_; + u = pack4x8snorm(e33); + let e36: vec4 = f4_; + u = pack4x8unorm(e36); + let e39: vec2 = f2_; + u = pack2x16unorm(e39); + let e42: vec2 = f2_; + u = pack2x16snorm(e42); + let e45: vec2 = f2_; + u = pack2x16float(e45); + let e48: u32 = u; + f4_ = unpack4x8snorm(e48); + let e51: u32 = u; + f4_ = unpack4x8unorm(e51); + let e54: u32 = u; + f2_ = unpack2x16snorm(e54); + let e57: u32 = u; + f2_ = unpack2x16unorm(e57); + let e60: u32 = u; + f2_ = unpack2x16float(e60); + let e66: i32 = i; + let e67: i32 = i; + i = insertBits(e66, e67, u32(5), u32(10)); + let e77: vec2 = i2_; + let e78: vec2 = i2_; + i2_ = insertBits(e77, e78, u32(5), u32(10)); + let e88: vec3 = i3_; + let e89: vec3 = i3_; + i3_ = insertBits(e88, e89, u32(5), u32(10)); + let e99: vec4 = i4_; + let e100: vec4 = i4_; + i4_ = insertBits(e99, e100, u32(5), u32(10)); + let e110: u32 = u; + let e111: u32 = u; + u = insertBits(e110, e111, u32(5), u32(10)); + let e121: vec2 = u2_; + let e122: vec2 = u2_; + u2_ = insertBits(e121, e122, u32(5), u32(10)); + let e132: vec3 = u3_; + let e133: vec3 = u3_; + u3_ = insertBits(e132, e133, u32(5), u32(10)); + let e143: vec4 = u4_; + let e144: vec4 = u4_; + u4_ = insertBits(e143, e144, u32(5), u32(10)); + let e153: i32 = i; + i = extractBits(e153, u32(5), u32(10)); + let e162: vec2 = i2_; + i2_ = extractBits(e162, u32(5), u32(10)); + let e171: vec3 = i3_; + i3_ = extractBits(e171, u32(5), u32(10)); + let e180: vec4 = i4_; + i4_ = extractBits(e180, u32(5), u32(10)); + let e189: u32 = u; + u = extractBits(e189, u32(5), u32(10)); + let e198: vec2 = u2_; + u2_ = extractBits(e198, u32(5), u32(10)); + let e207: vec3 = u3_; + u3_ = extractBits(e207, u32(5), u32(10)); + let e216: vec4 = u4_; + u4_ = extractBits(e216, u32(5), u32(10)); + return; +} + +[[stage(fragment)]] +fn main() { + main1(); + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 5725695e6..7d05d0fbf 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -465,6 +465,10 @@ fn convert_wgsl() { | Targets::HLSL | Targets::WGSL, ), + ( + "bits", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + ), ( "boids", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From 943e321bc697ccedab4618e1b3733034abc42390 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 5 Oct 2021 21:01:54 -0400 Subject: [PATCH 1401/2212] Fix lazy CI for snapshots --- .github/workflows/lazy.yml | 5 +++++ tests/in/bits.param.ron | 1 + 2 files changed, 6 insertions(+) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index ff21d63a7..e7e26d329 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -153,6 +153,11 @@ jobs: name: Check snapshots (without validation) runs-on: ubuntu-latest steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable - uses: actions-rs/cargo@v1 name: Test all (without validation) with: diff --git a/tests/in/bits.param.ron b/tests/in/bits.param.ron index fb45784e5..3017db2d6 100644 --- a/tests/in/bits.param.ron +++ b/tests/in/bits.param.ron @@ -1,4 +1,5 @@ ( + msl_custom: true, msl: ( lang_version: (1, 2), per_stage_map: ( From 0e3fbc81664a263e8be278d11a6083b227a5b1a2 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 6 Oct 2021 13:30:36 -0700 Subject: [PATCH 1402/2212] Replace pointer-access.spv snapshot test with WGSL source. (#1450) The original pointer access test used SPIR-V for its input because WGSL didn't have a working pointer indirection operator at the time. Now that it does, we can just write this test in WGSL directly. Fixes #1432. --- tests/in/pointer-access.param.ron | 7 --- tests/in/pointers.param.ron | 1 + tests/in/pointers.wgsl | 11 +++++ tests/in/spv/pointer-access.spv | Bin 664 -> 0 bytes tests/out/spv/pointers.spvasm | 72 +++++++++++++++++++++++------- tests/out/wgsl/pointers.wgsl | 11 +++++ tests/snapshots.rs | 6 --- 7 files changed, 80 insertions(+), 28 deletions(-) delete mode 100644 tests/in/pointer-access.param.ron delete mode 100644 tests/in/spv/pointer-access.spv diff --git a/tests/in/pointer-access.param.ron b/tests/in/pointer-access.param.ron deleted file mode 100644 index 4fc2cfe56..000000000 --- a/tests/in/pointer-access.param.ron +++ /dev/null @@ -1,7 +0,0 @@ -( - spv: ( - version: (1, 0), - debug: true, - adjust_coordinate_space: true, - ), -) diff --git a/tests/in/pointers.param.ron b/tests/in/pointers.param.ron index de304854b..10454c4d1 100644 --- a/tests/in/pointers.param.ron +++ b/tests/in/pointers.param.ron @@ -1,4 +1,5 @@ ( + index_bounds_check_policy: ReadZeroSkipWrite, spv: ( version: (1, 2), debug: true, diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl index 8dd12442e..d7148e8db 100644 --- a/tests/in/pointers.wgsl +++ b/tests/in/pointers.wgsl @@ -3,3 +3,14 @@ fn f() { let px = &v.x; *px = 10; } + +[[block]] +struct DynamicArray { + array: array; +}; + +fn index_dynamic_array(p: ptr, i: i32, v: u32) -> u32 { + let old = (*p).array[i]; + (*p).array[i] = v; + return old; +} diff --git a/tests/in/spv/pointer-access.spv b/tests/in/spv/pointer-access.spv deleted file mode 100644 index ba5664c3a7ad4b4d88069e858c69699126167a69..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 664 zcmYk3%}c{T5XGly(`c*Js`Ud@T6^@af_Uhu1uvrDHN++@f@s;Kp#Qli@%@sGxG;G$ zZ|3dW-86%7WMRY1B0JHS)wjT4z);w+u01_G$M>_xI4?e2vdrR_^|G?u=IMEI8I8rdf`_Zp` Lj+N8Hha8_@_)arN diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index b019f8b5c..d6e2bcf2b 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -1,29 +1,71 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 16 +; Bound: 42 OpCapability Shader OpCapability Linkage %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpSource GLSL 450 -OpName %6 "v" -OpName %9 "f" +OpMemberName %8 0 "array" +OpName %8 "DynamicArray" +OpName %10 "v" +OpName %13 "f" +OpName %23 "index_dynamic_array" +OpDecorate %7 ArrayStride 4 +OpDecorate %8 Block +OpMemberDecorate %8 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 %5 = OpTypeVector %4 2 -%7 = OpTypePointer Function %5 -%10 = OpTypeFunction %2 -%12 = OpTypePointer Function %4 -%14 = OpTypeInt 32 0 -%13 = OpConstant %14 0 -%9 = OpFunction %2 None %10 -%8 = OpLabel -%6 = OpVariable %7 Function -OpBranch %11 -%11 = OpLabel -%15 = OpAccessChain %12 %6 %13 -OpStore %15 %3 +%6 = OpTypeInt 32 0 +%7 = OpTypeRuntimeArray %6 +%8 = OpTypeStruct %7 +%9 = OpTypePointer Workgroup %8 +%11 = OpTypePointer Function %5 +%14 = OpTypeFunction %2 +%16 = OpTypePointer Function %4 +%17 = OpConstant %6 0 +%24 = OpTypeFunction %6 %9 %4 %6 +%26 = OpTypePointer Workgroup %7 +%27 = OpTypePointer Workgroup %6 +%30 = OpTypeBool +%32 = OpConstantNull %6 +%13 = OpFunction %2 None %14 +%12 = OpLabel +%10 = OpVariable %11 Function +OpBranch %15 +%15 = OpLabel +%18 = OpAccessChain %16 %10 %17 +OpStore %18 %3 OpReturn +OpFunctionEnd +%23 = OpFunction %6 None %24 +%20 = OpFunctionParameter %9 +%21 = OpFunctionParameter %4 +%22 = OpFunctionParameter %6 +%19 = OpLabel +OpBranch %25 +%25 = OpLabel +%28 = OpArrayLength %6 %20 0 +%29 = OpULessThan %30 %21 %28 +OpSelectionMerge %33 None +OpBranchConditional %29 %34 %33 +%34 = OpLabel +%31 = OpAccessChain %27 %20 %17 %21 +%35 = OpLoad %6 %31 +OpBranch %33 +%33 = OpLabel +%36 = OpPhi %6 %32 %25 %35 %34 +%37 = OpArrayLength %6 %20 0 +%38 = OpULessThan %30 %21 %37 +OpSelectionMerge %40 None +OpBranchConditional %38 %41 %40 +%41 = OpLabel +%39 = OpAccessChain %27 %20 %17 %21 +OpStore %39 %22 +OpBranch %40 +%40 = OpLabel +OpReturnValue %36 OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index 15a5157ae..cabe2eaed 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -1,3 +1,8 @@ +[[block]] +struct DynamicArray { + array1: [[stride(4)]] array; +}; + fn f() { var v: vec2; @@ -6,3 +11,9 @@ fn f() { return; } +fn index_dynamic_array(p: ptr, i: i32, v1: u32) -> u32 { + let old: u32 = (*p).array1[i]; + (*p).array1[i] = v1; + return old; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 7d05d0fbf..abccc15eb 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -598,12 +598,6 @@ fn convert_spv_inverse_hyperbolic_trig_functions() { ); } -#[cfg(all(feature = "spv-in", feature = "spv-out"))] -//#[test] //TODO: https://github.com/gfx-rs/naga/issues/1432 -fn _convert_spv_pointer_access() { - convert_spv("pointer-access", true, Targets::SPIRV); -} - #[cfg(feature = "glsl-in")] #[allow(unused_variables)] #[test] From 2e7d629aefe6857ade4f96fe2c3dc1a09f0fa4db Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Thu, 7 Oct 2021 09:15:38 -0400 Subject: [PATCH 1403/2212] [spv-in] Fix bitfieldExtract/Insert argument types (#1453) --- src/front/spv/mod.rs | 87 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 83 insertions(+), 4 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 4cc048150..dad84ab25 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1854,6 +1854,9 @@ impl> Parser { Op::BitFieldInsert => { inst.expect(7)?; + let start = self.data_offset; + let span = self.span_from_with_op(start); + let result_type_id = self.next()?; let result_id = self.next()?; let base_id = self.next()?; @@ -1866,14 +1869,52 @@ impl> Parser { let insert_handle = get_expr_handle!(insert_id, insert_lexp); let offset_lexp = self.lookup_expression.lookup(offset_id)?; let offset_handle = get_expr_handle!(offset_id, offset_lexp); + let offset_lookup_ty = self.lookup_type.lookup(offset_lexp.type_id)?; let count_lexp = self.lookup_expression.lookup(count_id)?; let count_handle = get_expr_handle!(count_id, count_lexp); + let count_lookup_ty = self.lookup_type.lookup(count_lexp.type_id)?; + + let offset_kind = ctx.type_arena[offset_lookup_ty.handle] + .inner + .scalar_kind() + .unwrap(); + let count_kind = ctx.type_arena[count_lookup_ty.handle] + .inner + .scalar_kind() + .unwrap(); + + let offset_cast_handle = if offset_kind != crate::ScalarKind::Uint { + ctx.expressions.append( + crate::Expression::As { + expr: offset_handle, + kind: crate::ScalarKind::Uint, + convert: None, + }, + span, + ) + } else { + offset_handle + }; + + let count_cast_handle = if count_kind != crate::ScalarKind::Uint { + ctx.expressions.append( + crate::Expression::As { + expr: count_handle, + kind: crate::ScalarKind::Uint, + convert: None, + }, + span, + ) + } else { + count_handle + }; + let expr = crate::Expression::Math { fun: crate::MathFunction::InsertBits, arg: base_handle, arg1: Some(insert_handle), - arg2: Some(offset_handle), - arg3: Some(count_handle), + arg2: Some(offset_cast_handle), + arg3: Some(count_cast_handle), }; self.lookup_expression.insert( result_id, @@ -1896,13 +1937,51 @@ impl> Parser { let base_handle = get_expr_handle!(base_id, base_lexp); let offset_lexp = self.lookup_expression.lookup(offset_id)?; let offset_handle = get_expr_handle!(offset_id, offset_lexp); + let offset_lookup_ty = self.lookup_type.lookup(offset_lexp.type_id)?; let count_lexp = self.lookup_expression.lookup(count_id)?; let count_handle = get_expr_handle!(count_id, count_lexp); + let count_lookup_ty = self.lookup_type.lookup(count_lexp.type_id)?; + + let offset_kind = ctx.type_arena[offset_lookup_ty.handle] + .inner + .scalar_kind() + .unwrap(); + let count_kind = ctx.type_arena[count_lookup_ty.handle] + .inner + .scalar_kind() + .unwrap(); + + let offset_cast_handle = if offset_kind != crate::ScalarKind::Uint { + ctx.expressions.append( + crate::Expression::As { + expr: offset_handle, + kind: crate::ScalarKind::Uint, + convert: None, + }, + span, + ) + } else { + offset_handle + }; + + let count_cast_handle = if count_kind != crate::ScalarKind::Uint { + ctx.expressions.append( + crate::Expression::As { + expr: count_handle, + kind: crate::ScalarKind::Uint, + convert: None, + }, + span, + ) + } else { + count_handle + }; + let expr = crate::Expression::Math { fun: crate::MathFunction::ExtractBits, arg: base_handle, - arg1: Some(offset_handle), - arg2: Some(count_handle), + arg1: Some(offset_cast_handle), + arg2: Some(count_cast_handle), arg3: None, }; self.lookup_expression.insert( From 943235cd5e91df9a1d41c60f525d26734bc0d261 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 7 Oct 2021 23:59:39 +0300 Subject: [PATCH 1404/2212] [glsl-out] Convert modulo operator on float to SPIR-V OpFRem equivalent function (#1452) --- src/back/glsl/mod.rs | 97 +++++++++++++++++----- src/lib.rs | 1 + tests/in/operators.wgsl | 9 ++ tests/out/glsl/operators.main.Compute.glsl | 8 ++ tests/out/hlsl/operators.hlsl | 9 ++ tests/out/msl/operators.msl | 9 ++ tests/out/spv/operators.spvasm | 31 +++++-- tests/out/wgsl/operators.wgsl | 8 ++ 8 files changed, 144 insertions(+), 28 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b79aabb87..e472c6826 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -311,6 +311,16 @@ pub enum Error { Custom(String), } +/// Binary operation with a different logic on the GLSL side +enum BinaryOperation { + /// Vector comparison should use the function like `greaterThan()`, etc. + VectorCompare, + /// GLSL `%` is SPIR-V `OpUMod/OpSMod` and `mod()` is `OpFMod`, but [`BinaryOperator::Modulo`](crate::BinaryOperator::Modulo) is `OpFRem` + Modulo, + /// Any plain operation. No additional logic required + Other, +} + /// Main structure of the glsl backend responsible for all code generation pub struct Writer<'a, W> { // Inputs @@ -2214,36 +2224,81 @@ impl<'a, W: Write> Writer<'a, W> { let right_inner = ctx.info[right].ty.inner_with(&self.module.types); let function = match (left_inner, right_inner) { - (&Ti::Vector { .. }, &Ti::Vector { .. }) => match op { - Bo::Less => Some("lessThan"), - Bo::LessEqual => Some("lessThanEqual"), - Bo::Greater => Some("greaterThan"), - Bo::GreaterEqual => Some("greaterThanEqual"), - Bo::Equal => Some("equal"), - Bo::NotEqual => Some("notEqual"), - _ => None, + ( + &Ti::Vector { + kind: left_kind, .. + }, + &Ti::Vector { + kind: right_kind, .. + }, + ) => match op { + Bo::Less + | Bo::LessEqual + | Bo::Greater + | Bo::GreaterEqual + | Bo::Equal + | Bo::NotEqual => BinaryOperation::VectorCompare, + Bo::Modulo => match (left_kind, right_kind) { + (Sk::Float, _) | (_, Sk::Float) => match op { + Bo::Modulo => BinaryOperation::Modulo, + _ => BinaryOperation::Other, + }, + _ => BinaryOperation::Other, + }, + _ => BinaryOperation::Other, }, _ => match (left_inner.scalar_kind(), right_inner.scalar_kind()) { (Some(Sk::Float), _) | (_, Some(Sk::Float)) => match op { - Bo::Modulo => Some("mod"), - _ => None, + Bo::Modulo => BinaryOperation::Modulo, + _ => BinaryOperation::Other, }, - _ => None, + _ => BinaryOperation::Other, }, }; - write!(self.out, "{}(", function.unwrap_or(""))?; - self.write_expr(left, ctx)?; + match function { + BinaryOperation::VectorCompare => { + let op_str = match op { + Bo::Less => "lessThan(", + Bo::LessEqual => "lessThanEqual(", + Bo::Greater => "greaterThan(", + Bo::GreaterEqual => "greaterThanEqual(", + Bo::Equal => "equal(", + Bo::NotEqual => "notEqual(", + _ => unreachable!(), + }; + write!(self.out, "{}", op_str)?; + self.write_expr(left, ctx)?; + write!(self.out, ", ")?; + self.write_expr(right, ctx)?; + write!(self.out, ")")?; + } + BinaryOperation::Modulo => { + write!(self.out, "(")?; - if function.is_some() { - write!(self.out, ",")? - } else { - write!(self.out, " {} ", super::binary_operation_str(op))?; + // write `e1 - e2 * trunc(e1 / e2)` + self.write_expr(left, ctx)?; + write!(self.out, " - ")?; + self.write_expr(right, ctx)?; + write!(self.out, " * ")?; + write!(self.out, "trunc(")?; + self.write_expr(left, ctx)?; + write!(self.out, " / ")?; + self.write_expr(right, ctx)?; + write!(self.out, ")")?; + + write!(self.out, ")")?; + } + BinaryOperation::Other => { + write!(self.out, "(")?; + + self.write_expr(left, ctx)?; + write!(self.out, " {} ", super::binary_operation_str(op))?; + self.write_expr(right, ctx)?; + + write!(self.out, ")")?; + } } - - self.write_expr(right, ctx)?; - - write!(self.out, ")")? } // `Select` is written as `condition ? accept : reject` // We wrap everything in parentheses to avoid precedence issues diff --git a/src/lib.rs b/src/lib.rs index 737e0bfca..036b197a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -813,6 +813,7 @@ pub enum BinaryOperator { Subtract, Multiply, Divide, + /// Equivalent of the WGSL's `%` operator or SPIR-V's `OpFRem` Modulo, Equal, NotEqual, diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 1b7ec7585..7335f5775 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -44,10 +44,19 @@ fn constructors() -> f32 { return foo.a.x; } +fn modulo() { + // Modulo operator on float scalar or vector must be converted to mod function for GLSL + let a = 1 % 1; + let b = 1.0 % 1.0; + let c = vec3(1) % vec3(1); + let d = vec3(1.0) % vec3(1.0); +} + [[stage(compute), workgroup_size(1)]] fn main() { let a = builtins(); let b = splat(); let c = unary(); let d = constructors(); + modulo(); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 99c42467f..17e996622 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -44,11 +44,19 @@ float constructors() { return _e11; } +void modulo() { + int a1 = (1 % 1); + float b1 = (1.0 - 1.0 * trunc(1.0 / 1.0)); + ivec3 c = (ivec3(1) % ivec3(1)); + vec3 d = (vec3(1.0) - vec3(1.0) * trunc(vec3(1.0) / vec3(1.0))); +} + void main() { vec4 _e4 = builtins(); vec4 _e5 = splat(); int _e6 = unary(); float _e7 = constructors(); + modulo(); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 904ca2e1c..31aacb164 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -53,6 +53,14 @@ float constructors() return _expr11; } +void modulo() +{ + int a1 = (1 % 1); + float b1 = (1.0 % 1.0); + int3 c = (int3(1.xxx) % int3(1.xxx)); + float3 d = (float3(1.0.xxx) % float3(1.0.xxx)); +} + [numthreads(1, 1, 1)] void main() { @@ -60,5 +68,6 @@ void main() const float4 _e5 = splat(); const int _e6 = unary(); const float _e7 = constructors(); + modulo(); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index daf4b3a10..a552a33e9 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -48,11 +48,20 @@ float constructors( return _e11; } +void modulo( +) { + int a1 = 1 % 1; + float b1 = metal::fmod(1.0, 1.0); + metal::int3 c = metal::int3(1) % metal::int3(1); + metal::float3 d = metal::fmod(metal::float3(1.0), metal::float3(1.0)); +} + kernel void main1( ) { metal::float4 _e4 = builtins(); metal::float4 _e5 = splat(); int _e6 = unary(); float _e7 = constructors(); + modulo(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 475241ab7..688917bf3 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 101 +; Bound: 115 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %94 "main" -OpExecutionMode %94 LocalSize 1 1 1 +OpEntryPoint GLCompute %108 "main" +OpExecutionMode %108 LocalSize 1 1 1 OpMemberDecorate %22 0 Offset 0 OpMemberDecorate %22 1 Offset 16 %2 = OpTypeVoid @@ -45,6 +45,8 @@ OpMemberDecorate %22 1 Offset 16 %90 = OpTypeInt 32 0 %89 = OpConstant %90 0 %95 = OpTypeFunction %2 +%99 = OpTypeVector %8 3 +%103 = OpTypeVector %4 3 %28 = OpFunction %19 None %29 %27 = OpLabel OpBranch %30 @@ -122,9 +124,24 @@ OpFunctionEnd %93 = OpLabel OpBranch %96 %96 = OpLabel -%97 = OpFunctionCall %19 %28 -%98 = OpFunctionCall %19 %53 -%99 = OpFunctionCall %8 %70 -%100 = OpFunctionCall %4 %82 +%97 = OpSMod %8 %7 %7 +%98 = OpFMod %4 %3 %3 +%100 = OpCompositeConstruct %99 %7 %7 %7 +%101 = OpCompositeConstruct %99 %7 %7 %7 +%102 = OpSMod %99 %100 %101 +%104 = OpCompositeConstruct %103 %3 %3 %3 +%105 = OpCompositeConstruct %103 %3 %3 %3 +%106 = OpFMod %103 %104 %105 +OpReturn +OpFunctionEnd +%108 = OpFunction %2 None %95 +%107 = OpLabel +OpBranch %109 +%109 = OpLabel +%110 = OpFunctionCall %19 %28 +%111 = OpFunctionCall %19 %53 +%112 = OpFunctionCall %8 %70 +%113 = OpFunctionCall %4 %82 +%114 = OpFunctionCall %2 %94 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 6c7ab1147..ed5b9f78f 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -41,11 +41,19 @@ fn constructors() -> f32 { return e11; } +fn modulo() { + let a1: i32 = (1 % 1); + let b1: f32 = (1.0 % 1.0); + let c: vec3 = (vec3(1) % vec3(1)); + let d: vec3 = (vec3(1.0) % vec3(1.0)); +} + [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { let e4: vec4 = builtins(); let e5: vec4 = splat(); let e6: i32 = unary(); let e7: f32 = constructors(); + modulo(); return; } From 3a2f7e611e4fe8ec50d9bb365916f22e7c30e46c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 7 Oct 2021 18:04:30 -0400 Subject: [PATCH 1405/2212] Release 0.7 (#1455) --- CHANGELOG.md | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 2 +- 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bd8fa736..5340a6011 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,77 @@ # Change Log +## v0.7 (2021-10-07) + - development release for wgpu-0.11 + - API: + - bit extraction and packing functions + - hyperbolic trigonometry functionss + - validation is gated by a cargo feature + - `view_index` builtin + - separate bounds checking policies for locals/buffers/textures + - IR: + - types and constants are guaranteed to be unique + - WGSL-in: + - new hex literal parser + - updated list of reserved words + - rewritten logic for resolving references and pointers + - `switch` can use unsigned selectors + - GLSL-in: + - better support for texture sampling + - better logic for auto-splatting scalars + - GLSL-out: + - fixed storage buffer layout + - fix module operator + - HLSL-out: + - fixed texture queries + - SPV-in: + - control flow handling is rewritten from scratch + - SPV-out: + - fully covered out-of-bounds checking + - option to emit point size + - option to clamp output depth + +### v0.6.3 (2021-09-08) + - Reduced heap allocations when generating WGSL, HLSL, and GLSL + - WGSL-in: + - support module-scope `let` type inference + - SPV-in: + - fix depth sampling with projection + - HLSL-out: + - fix local struct construction + - GLSL-out: + - fix `select()` order + - SPV-out: + - allow working around Adreno issue with `OpName` + +### v0.6.2 (2021-09-01) + - SPV-out fixes: + - requested capabilities for 1D and cube images, storage formats + - handling `break` and `continue` in a `switch` statement + - avoid generating duplicate `OpTypeImage` types + - HLSL-out fixes: + - fix output struct member names + - MSL-out fixes: + - fix packing of fields in interface structs + - GLSL-out fixes: + - fix non-fallthrough `switch` cases + - GLSL-in fixes: + - avoid infinite loop on invalid statements + +### v0.6.1 (2021-08-24) + - HLSL-out fixes: + - array arguments + - pointers to array arguments + - switch statement + - rewritten interface matching + - SPV-in fixes: + - array storage texture stores + - tracking sampling across function parameters + - updated petgraph dependencies + - MSL-out: + - gradient sampling + - GLSL-out: + - modulo operator on floats + ## v0.6 (2021-08-18) - development release for wgpu-0.10 - API: diff --git a/Cargo.toml b/Cargo.toml index 430da0f81..16adbe469 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.6.0" +version = "0.7.0" authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" From ee450c1ee4da4e46bc482b3bcdd71600d387a384 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 12 Oct 2021 11:42:20 -0400 Subject: [PATCH 1406/2212] Fix float-bool casts in MSL, SPV, and HLSL backends (#1459) --- src/back/hlsl/writer.rs | 24 +-- src/back/msl/writer.rs | 18 +- src/back/spv/block.rs | 139 +++++++++---- tests/in/operators.wgsl | 8 +- tests/out/glsl/operators.main.Compute.glsl | 8 +- tests/out/hlsl/operators.hlsl | 9 +- tests/out/msl/operators.msl | 10 +- tests/out/spv/operators.spvasm | 226 +++++++++++---------- tests/out/wgsl/operators.wgsl | 8 +- 9 files changed, 285 insertions(+), 165 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 604fd94d8..ce51a4823 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1786,20 +1786,15 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "{}", op_str)?; self.write_expr(module, expr, func_ctx)?; } - Expression::As { expr, kind, .. } => { + Expression::As { + expr, + kind, + convert, + } => { let inner = func_ctx.info[expr].ty.inner_with(&module.types); - match *inner { - TypeInner::Vector { size, width, .. } => { - write!( - self.out, - "{}{}", - kind.to_hlsl_str(width)?, - back::vector_size_str(size), - )?; - } - TypeInner::Scalar { width, .. } => { - write!(self.out, "{}", kind.to_hlsl_str(width)?)? - } + let (size_str, src_width) = match *inner { + TypeInner::Vector { size, width, .. } => (back::vector_size_str(size), width), + TypeInner::Scalar { width, .. } => ("", width), _ => { return Err(Error::Unimplemented(format!( "write_expr expression::as {:?}", @@ -1807,7 +1802,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ))); } }; - write!(self.out, "(")?; + let kind_str = kind.to_hlsl_str(convert.unwrap_or(src_width))?; + write!(self.out, "{}{}(", kind_str, size_str,)?; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")?; } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index bcd4dd6c4..e743dc5f6 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -165,7 +165,13 @@ impl<'a> Display for TypeContext<'a> { } else if self.access.contains(crate::StorageAccess::LOAD) { "read" } else { - unreachable!("module is not valid") + log::warn!( + "Storage access for {:?} (name '{}'): {:?}", + self.handle, + ty.name.as_deref().unwrap_or_default(), + self.access + ); + unreachable!("module is not valid"); }; ("texture", "", format.into(), access) } @@ -1223,13 +1229,15 @@ impl Writer { convert, } => { let scalar = scalar_kind_string(kind); - let width = match *context.resolve_type(expr) { - crate::TypeInner::Scalar { width, .. } - | crate::TypeInner::Vector { width, .. } => width, + let (src_kind, src_width) = match *context.resolve_type(expr) { + crate::TypeInner::Scalar { kind, width } + | crate::TypeInner::Vector { kind, width, .. } => (kind, width), _ => return Err(Error::Validation), }; + let is_bool_cast = + kind == crate::ScalarKind::Bool || src_kind == crate::ScalarKind::Bool; let op = match convert { - Some(w) if w == width => "static_cast", + Some(w) if w == src_width || is_bool_cast => "static_cast", Some(8) if kind == crate::ScalarKind::Float => { return Err(Error::CapabilityNotSupported(valid::Capabilities::FLOAT64)) } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 88c16e7cf..b65a58bb2 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -232,14 +232,12 @@ impl<'w> BlockContext<'w> { crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], crate::Expression::Splat { size, value } => { let value_id = self.cached[value]; - self.temp_list.clear(); - self.temp_list.resize(size as usize, value_id); - + let components = [value_id; 4]; let id = self.gen_id(); block.body.push(Instruction::composite_construct( result_type_id, id, - &self.temp_list, + &components[..size as usize], )); id } @@ -726,25 +724,26 @@ impl<'w> BlockContext<'w> { use crate::ScalarKind as Sk; let expr_id = self.cached[expr]; - let (src_kind, src_width) = + let (src_kind, src_size, src_width) = match *self.fun_info[expr].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Scalar { kind, width } - | crate::TypeInner::Vector { - kind, - width, - size: _, - } => (kind, width), - crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), + crate::TypeInner::Scalar { kind, width } => (kind, None, width), + crate::TypeInner::Vector { kind, width, size } => (kind, Some(size), width), ref other => { log::error!("As source {:?}", other); return Err(Error::Validation("Unexpected Expression::As source")); } }; - let id = self.gen_id(); + enum Cast { + Unary(spirv::Op), + Binary(spirv::Op, Word), + Ternary(spirv::Op, Word, Word), + } - let instruction = match (src_kind, kind, convert) { - (_, Sk::Bool, Some(_)) if src_kind != Sk::Bool => { + let cast = match (src_kind, kind, convert) { + (_, _, None) | (Sk::Bool, Sk::Bool, Some(_)) => Cast::Unary(spirv::Op::Bitcast), + // casting to a bool - generate `OpXxxNotEqual` + (_, Sk::Bool, Some(_)) => { let (op, value) = match src_kind { Sk::Sint => (spirv::Op::INotEqual, crate::ScalarValue::Sint(0)), Sk::Uint => (spirv::Op::INotEqual, crate::ScalarValue::Uint(0)), @@ -753,34 +752,102 @@ impl<'w> BlockContext<'w> { } Sk::Bool => unreachable!(), }; - let zero_id = self.writer.get_constant_scalar(value, 4); + let zero_scalar_id = self.writer.get_constant_scalar(value, src_width); + let zero_id = match src_size { + Some(size) => { + let vector_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind: src_kind, + width: src_width, + pointer_class: None, + })); + let components = [zero_scalar_id; 4]; - Instruction::binary(op, result_type_id, id, expr_id, zero_id) - } - _ => { - let op = match (src_kind, kind, convert) { - (_, _, None) => spirv::Op::Bitcast, - (Sk::Float, Sk::Uint, Some(_)) => spirv::Op::ConvertFToU, - (Sk::Float, Sk::Sint, Some(_)) => spirv::Op::ConvertFToS, - (Sk::Float, Sk::Float, Some(dst_width)) if src_width != dst_width => { - spirv::Op::FConvert + let zero_id = self.gen_id(); + block.body.push(Instruction::composite_construct( + vector_type_id, + zero_id, + &components[..size as usize], + )); + zero_id } - (Sk::Sint, Sk::Float, Some(_)) => spirv::Op::ConvertSToF, - (Sk::Sint, Sk::Sint, Some(dst_width)) if src_width != dst_width => { - spirv::Op::SConvert - } - (Sk::Uint, Sk::Float, Some(_)) => spirv::Op::ConvertUToF, - (Sk::Uint, Sk::Uint, Some(dst_width)) if src_width != dst_width => { - spirv::Op::UConvert - } - // We assume it's either an identity cast, or int-uint. - _ => spirv::Op::Bitcast, + None => zero_scalar_id, }; - Instruction::unary(op, result_type_id, id, expr_id) + Cast::Binary(op, zero_id) } + // casting from a bool - generate `OpSelect` + (Sk::Bool, _, Some(dst_width)) => { + let (val0, val1) = match kind { + Sk::Sint => (crate::ScalarValue::Sint(0), crate::ScalarValue::Sint(1)), + Sk::Uint => (crate::ScalarValue::Uint(0), crate::ScalarValue::Uint(1)), + Sk::Float => ( + crate::ScalarValue::Float(0.0), + crate::ScalarValue::Float(1.0), + ), + Sk::Bool => unreachable!(), + }; + let scalar0_id = self.writer.get_constant_scalar(val0, dst_width); + let scalar1_id = self.writer.get_constant_scalar(val1, dst_width); + let (accept_id, reject_id) = match src_size { + Some(size) => { + let vector_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind, + width: dst_width, + pointer_class: None, + })); + let components0 = [scalar0_id; 4]; + let components1 = [scalar1_id; 4]; + + let vec0_id = self.gen_id(); + block.body.push(Instruction::composite_construct( + vector_type_id, + vec0_id, + &components0[..size as usize], + )); + let vec1_id = self.gen_id(); + block.body.push(Instruction::composite_construct( + vector_type_id, + vec1_id, + &components1[..size as usize], + )); + (vec1_id, vec0_id) + } + None => (scalar1_id, scalar0_id), + }; + + Cast::Ternary(spirv::Op::Select, accept_id, reject_id) + } + (Sk::Float, Sk::Uint, Some(_)) => Cast::Unary(spirv::Op::ConvertFToU), + (Sk::Float, Sk::Sint, Some(_)) => Cast::Unary(spirv::Op::ConvertFToS), + (Sk::Float, Sk::Float, Some(dst_width)) if src_width != dst_width => { + Cast::Unary(spirv::Op::FConvert) + } + (Sk::Sint, Sk::Float, Some(_)) => Cast::Unary(spirv::Op::ConvertSToF), + (Sk::Sint, Sk::Sint, Some(dst_width)) if src_width != dst_width => { + Cast::Unary(spirv::Op::SConvert) + } + (Sk::Uint, Sk::Float, Some(_)) => Cast::Unary(spirv::Op::ConvertUToF), + (Sk::Uint, Sk::Uint, Some(dst_width)) if src_width != dst_width => { + Cast::Unary(spirv::Op::UConvert) + } + // We assume it's either an identity cast, or int-uint. + _ => Cast::Unary(spirv::Op::Bitcast), }; + let id = self.gen_id(); + let instruction = match cast { + Cast::Unary(op) => Instruction::unary(op, result_type_id, id, expr_id), + Cast::Binary(op, operand) => { + Instruction::binary(op, result_type_id, id, expr_id, operand) + } + Cast::Ternary(op, op1, op2) => { + Instruction::ternary(op, result_type_id, id, expr_id, op1, op2) + } + }; block.body.push(instruction); id } diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 7335f5775..99eca092a 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -33,6 +33,11 @@ fn unary() -> i32 { if (!true) { return a; } else { return ~a; }; } +fn bool_cast(x: vec3) -> vec3 { + let y = vec3(x); + return vec3(y); +} + struct Foo { a: vec4; b: i32; @@ -57,6 +62,7 @@ fn main() { let a = builtins(); let b = splat(); let c = unary(); - let d = constructors(); + let d = bool_cast(v_f32_one.xyz); + let e = constructors(); modulo(); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 17e996622..a135e6c4d 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -37,6 +37,11 @@ int unary() { } } +vec3 bool_cast(vec3 x) { + bvec3 y = bvec3(x); + return vec3(y); +} + float constructors() { Foo foo; foo = Foo(vec4(1.0), 1); @@ -55,7 +60,8 @@ void main() { vec4 _e4 = builtins(); vec4 _e5 = splat(); int _e6 = unary(); - float _e7 = constructors(); + vec3 _e8 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + float _e9 = constructors(); modulo(); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 31aacb164..0f6a23e30 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -37,6 +37,12 @@ int unary() } } +float3 bool_cast(float3 x) +{ + bool3 y = bool3(x); + return float3(y); +} + Foo ConstructFoo(float4 arg0, int arg1) { Foo ret; ret.a = arg0; @@ -67,7 +73,8 @@ void main() const float4 _e4 = builtins(); const float4 _e5 = splat(); const int _e6 = unary(); - const float _e7 = constructors(); + const float3 _e8 = bool_cast(float4(1.0, 1.0, 1.0, 1.0).xyz); + const float _e9 = constructors(); modulo(); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index a552a33e9..c1e52481c 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -40,6 +40,13 @@ int unary( } } +metal::float3 bool_cast( + metal::float3 x +) { + metal::bool3 y = static_cast(x); + return static_cast(y); +} + float constructors( ) { Foo foo; @@ -61,7 +68,8 @@ kernel void main1( metal::float4 _e4 = builtins(); metal::float4 _e5 = splat(); int _e6 = unary(); - float _e7 = constructors(); + metal::float3 _e8 = bool_cast(v_f32_one.xyz); + float _e9 = constructors(); modulo(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 688917bf3..47aeab816 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,14 +1,14 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 115 +; Bound: 128 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %108 "main" -OpExecutionMode %108 LocalSize 1 1 1 -OpMemberDecorate %22 0 Offset 0 -OpMemberDecorate %22 1 Offset 16 +OpEntryPoint GLCompute %119 "main" +OpExecutionMode %119 LocalSize 1 1 1 +OpMemberDecorate %23 0 Offset 0 +OpMemberDecorate %23 1 Offset 16 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -29,119 +29,135 @@ OpMemberDecorate %22 1 Offset 16 %19 = OpTypeVector %4 4 %20 = OpTypeVector %8 4 %21 = OpTypeVector %10 4 -%22 = OpTypeStruct %19 %8 -%23 = OpConstantComposite %19 %3 %3 %3 %3 -%24 = OpConstantComposite %19 %5 %5 %5 %5 -%25 = OpConstantComposite %19 %6 %6 %6 %6 -%26 = OpConstantComposite %20 %7 %7 %7 %7 -%29 = OpTypeFunction %19 -%55 = OpTypeVector %4 2 -%71 = OpTypeFunction %8 -%78 = OpConstantNull %8 -%80 = OpTypePointer Function %22 -%83 = OpTypeFunction %4 -%87 = OpTypePointer Function %19 -%88 = OpTypePointer Function %4 -%90 = OpTypeInt 32 0 -%89 = OpConstant %90 0 -%95 = OpTypeFunction %2 -%99 = OpTypeVector %8 3 -%103 = OpTypeVector %4 3 -%28 = OpFunction %19 None %29 -%27 = OpLabel -OpBranch %30 -%30 = OpLabel -%31 = OpSelect %8 %9 %7 %11 -%33 = OpCompositeConstruct %21 %9 %9 %9 %9 -%32 = OpSelect %19 %33 %23 %24 -%34 = OpCompositeConstruct %21 %12 %12 %12 %12 -%35 = OpSelect %19 %34 %24 %23 -%36 = OpExtInst %19 %1 FMix %24 %23 %25 -%38 = OpCompositeConstruct %19 %13 %13 %13 %13 -%37 = OpExtInst %19 %1 FMix %24 %23 %38 -%39 = OpCompositeExtract %8 %26 0 -%40 = OpBitcast %4 %39 -%41 = OpBitcast %19 %26 -%42 = OpConvertFToS %20 %24 -%43 = OpCompositeConstruct %20 %31 %31 %31 %31 -%44 = OpIAdd %20 %43 %42 -%45 = OpConvertSToF %19 %44 -%46 = OpFAdd %19 %45 %32 -%47 = OpFAdd %19 %46 %36 +%22 = OpTypeVector %4 3 +%23 = OpTypeStruct %19 %8 +%24 = OpConstantComposite %19 %3 %3 %3 %3 +%25 = OpConstantComposite %19 %5 %5 %5 %5 +%26 = OpConstantComposite %19 %6 %6 %6 %6 +%27 = OpConstantComposite %20 %7 %7 %7 %7 +%30 = OpTypeFunction %19 +%56 = OpTypeVector %4 2 +%72 = OpTypeFunction %8 +%79 = OpConstantNull %8 +%83 = OpTypeFunction %22 %22 +%85 = OpTypeVector %10 3 +%92 = OpTypePointer Function %23 +%95 = OpTypeFunction %4 +%99 = OpTypePointer Function %19 +%100 = OpTypePointer Function %4 +%102 = OpTypeInt 32 0 +%101 = OpConstant %102 0 +%107 = OpTypeFunction %2 +%111 = OpTypeVector %8 3 +%29 = OpFunction %19 None %30 +%28 = OpLabel +OpBranch %31 +%31 = OpLabel +%32 = OpSelect %8 %9 %7 %11 +%34 = OpCompositeConstruct %21 %9 %9 %9 %9 +%33 = OpSelect %19 %34 %24 %25 +%35 = OpCompositeConstruct %21 %12 %12 %12 %12 +%36 = OpSelect %19 %35 %25 %24 +%37 = OpExtInst %19 %1 FMix %25 %24 %26 +%39 = OpCompositeConstruct %19 %13 %13 %13 %13 +%38 = OpExtInst %19 %1 FMix %25 %24 %39 +%40 = OpCompositeExtract %8 %27 0 +%41 = OpBitcast %4 %40 +%42 = OpBitcast %19 %27 +%43 = OpConvertFToS %20 %25 +%44 = OpCompositeConstruct %20 %32 %32 %32 %32 +%45 = OpIAdd %20 %44 %43 +%46 = OpConvertSToF %19 %45 +%47 = OpFAdd %19 %46 %33 %48 = OpFAdd %19 %47 %37 -%49 = OpCompositeConstruct %19 %40 %40 %40 %40 -%50 = OpFAdd %19 %48 %49 -%51 = OpFAdd %19 %50 %41 -OpReturnValue %51 +%49 = OpFAdd %19 %48 %38 +%50 = OpCompositeConstruct %19 %41 %41 %41 %41 +%51 = OpFAdd %19 %49 %50 +%52 = OpFAdd %19 %51 %42 +OpReturnValue %52 OpFunctionEnd -%53 = OpFunction %19 None %29 -%52 = OpLabel -OpBranch %54 -%54 = OpLabel -%56 = OpCompositeConstruct %55 %14 %14 -%57 = OpCompositeConstruct %55 %3 %3 -%58 = OpFAdd %55 %57 %56 -%59 = OpCompositeConstruct %55 %15 %15 -%60 = OpFSub %55 %58 %59 -%61 = OpCompositeConstruct %55 %16 %16 -%62 = OpFDiv %55 %60 %61 -%63 = OpCompositeConstruct %20 %17 %17 %17 %17 -%64 = OpCompositeConstruct %20 %18 %18 %18 %18 -%65 = OpSMod %20 %63 %64 -%66 = OpVectorShuffle %19 %62 %62 0 1 0 1 -%67 = OpConvertSToF %19 %65 -%68 = OpFAdd %19 %66 %67 -OpReturnValue %68 +%54 = OpFunction %19 None %30 +%53 = OpLabel +OpBranch %55 +%55 = OpLabel +%57 = OpCompositeConstruct %56 %14 %14 +%58 = OpCompositeConstruct %56 %3 %3 +%59 = OpFAdd %56 %58 %57 +%60 = OpCompositeConstruct %56 %15 %15 +%61 = OpFSub %56 %59 %60 +%62 = OpCompositeConstruct %56 %16 %16 +%63 = OpFDiv %56 %61 %62 +%64 = OpCompositeConstruct %20 %17 %17 %17 %17 +%65 = OpCompositeConstruct %20 %18 %18 %18 %18 +%66 = OpSMod %20 %64 %65 +%67 = OpVectorShuffle %19 %63 %63 0 1 0 1 +%68 = OpConvertSToF %19 %66 +%69 = OpFAdd %19 %67 %68 +OpReturnValue %69 OpFunctionEnd -%70 = OpFunction %8 None %71 -%69 = OpLabel -OpBranch %72 -%72 = OpLabel -%73 = OpLogicalNot %10 %9 -OpSelectionMerge %74 None -OpBranchConditional %73 %75 %76 -%75 = OpLabel -OpReturnValue %7 +%71 = OpFunction %8 None %72 +%70 = OpLabel +OpBranch %73 +%73 = OpLabel +%74 = OpLogicalNot %10 %9 +OpSelectionMerge %75 None +OpBranchConditional %74 %76 %77 %76 = OpLabel -%77 = OpNot %8 %7 -OpReturnValue %77 -%74 = OpLabel +OpReturnValue %7 +%77 = OpLabel +%78 = OpNot %8 %7 OpReturnValue %78 +%75 = OpLabel +OpReturnValue %79 OpFunctionEnd -%82 = OpFunction %4 None %83 -%81 = OpLabel -%79 = OpVariable %80 Function +%82 = OpFunction %22 None %83 +%81 = OpFunctionParameter %22 +%80 = OpLabel OpBranch %84 %84 = OpLabel -%85 = OpCompositeConstruct %19 %3 %3 %3 %3 -%86 = OpCompositeConstruct %22 %85 %7 -OpStore %79 %86 -%91 = OpAccessChain %88 %79 %89 %89 -%92 = OpLoad %4 %91 -OpReturnValue %92 +%86 = OpCompositeConstruct %22 %5 %5 %5 +%87 = OpFUnordNotEqual %85 %81 %86 +%88 = OpCompositeConstruct %22 %5 %5 %5 +%89 = OpCompositeConstruct %22 %3 %3 %3 +%90 = OpSelect %22 %87 %89 %88 +OpReturnValue %90 OpFunctionEnd -%94 = OpFunction %2 None %95 +%94 = OpFunction %4 None %95 %93 = OpLabel +%91 = OpVariable %92 Function OpBranch %96 %96 = OpLabel -%97 = OpSMod %8 %7 %7 -%98 = OpFMod %4 %3 %3 -%100 = OpCompositeConstruct %99 %7 %7 %7 -%101 = OpCompositeConstruct %99 %7 %7 %7 -%102 = OpSMod %99 %100 %101 -%104 = OpCompositeConstruct %103 %3 %3 %3 -%105 = OpCompositeConstruct %103 %3 %3 %3 -%106 = OpFMod %103 %104 %105 +%97 = OpCompositeConstruct %19 %3 %3 %3 %3 +%98 = OpCompositeConstruct %23 %97 %7 +OpStore %91 %98 +%103 = OpAccessChain %100 %91 %101 %101 +%104 = OpLoad %4 %103 +OpReturnValue %104 +OpFunctionEnd +%106 = OpFunction %2 None %107 +%105 = OpLabel +OpBranch %108 +%108 = OpLabel +%109 = OpSMod %8 %7 %7 +%110 = OpFMod %4 %3 %3 +%112 = OpCompositeConstruct %111 %7 %7 %7 +%113 = OpCompositeConstruct %111 %7 %7 %7 +%114 = OpSMod %111 %112 %113 +%115 = OpCompositeConstruct %22 %3 %3 %3 +%116 = OpCompositeConstruct %22 %3 %3 %3 +%117 = OpFMod %22 %115 %116 OpReturn OpFunctionEnd -%108 = OpFunction %2 None %95 -%107 = OpLabel -OpBranch %109 -%109 = OpLabel -%110 = OpFunctionCall %19 %28 -%111 = OpFunctionCall %19 %53 -%112 = OpFunctionCall %8 %70 -%113 = OpFunctionCall %4 %82 -%114 = OpFunctionCall %2 %94 +%119 = OpFunction %2 None %107 +%118 = OpLabel +OpBranch %120 +%120 = OpLabel +%121 = OpFunctionCall %19 %29 +%122 = OpFunctionCall %19 %54 +%123 = OpFunctionCall %8 %71 +%124 = OpVectorShuffle %22 %24 %24 0 1 2 +%125 = OpFunctionCall %22 %82 %124 +%126 = OpFunctionCall %4 %94 +%127 = OpFunctionCall %2 %106 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index ed5b9f78f..b3f7bba03 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -33,6 +33,11 @@ fn unary() -> i32 { } } +fn bool_cast(x: vec3) -> vec3 { + let y: vec3 = vec3(x); + return vec3(y); +} + fn constructors() -> f32 { var foo: Foo; @@ -53,7 +58,8 @@ fn main() { let e4: vec4 = builtins(); let e5: vec4 = splat(); let e6: i32 = unary(); - let e7: f32 = constructors(); + let e8: vec3 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + let e9: f32 = constructors(); modulo(); return; } From 3b499811116dd4a29449af134181e28878a9e0a4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 12 Oct 2021 11:44:13 -0400 Subject: [PATCH 1407/2212] Bump version to 0.7.1 --- CHANGELOG.md | 3 +++ Cargo.toml | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5340a6011..8439ecbc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Change Log +## v0.7.1 (2021-10-12) + - implement casts from and to booleans in the backends + ## v0.7 (2021-10-07) - development release for wgpu-0.11 - API: diff --git a/Cargo.toml b/Cargo.toml index 16adbe469..eb2a84a4d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,11 +1,11 @@ [package] name = "naga" -version = "0.7.0" +version = "0.7.1" authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" homepage = "https://github.com/gfx-rs/naga" -repository = "https://github.com/gfx-rs/naga/tree/v0.5" +repository = "https://github.com/gfx-rs/naga/tree/v0.7" keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] From 4cb91f2c98ab97d42442aa5b8da05367f263d227 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 13 Oct 2021 08:21:29 -0400 Subject: [PATCH 1408/2212] cli: option to keep coordinate space unchanged (#1460) --- cli/src/main.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 96c7b378e..abb00aaa7 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -55,6 +55,11 @@ struct Args { #[argh(option)] shader_model: Option, + /// if the selected frontends/backends support coordinate space conversions, + /// disable them + #[argh(switch)] + keep_coordinate_space: bool, + /// the input file #[argh(positional)] input: String, @@ -129,7 +134,7 @@ struct Parameters { validation_flags: naga::valid::ValidationFlags, bounds_check_policies: naga::back::BoundsCheckPolicies, entry_point: Option, - spv_adjust_coordinate_space: bool, + keep_coordinate_space: bool, spv_block_ctx_dump_prefix: Option, spv: naga::back::spv::Options, msl: naga::back::msl::Options, @@ -224,6 +229,7 @@ fn run() -> Result<(), Box> { if let Some(model) = args.shader_model { params.hlsl.shader_model = model.0; } + params.keep_coordinate_space = args.keep_coordinate_space; let module = match Path::new(&input_path) .extension() @@ -233,7 +239,7 @@ fn run() -> Result<(), Box> { { "spv" => { let options = naga::front::spv::Options { - adjust_coordinate_space: params.spv_adjust_coordinate_space, + adjust_coordinate_space: !params.keep_coordinate_space, strict_capabilities: false, block_ctx_dump_prefix: params .spv_block_ctx_dump_prefix @@ -356,6 +362,10 @@ fn run() -> Result<(), Box> { }; params.spv.bounds_check_policies = params.bounds_check_policies; + params.spv.flags.set( + spv::WriterFlags::ADJUST_COORDINATE_SPACE, + !params.keep_coordinate_space, + ); let spv = spv::write_vec( &module, From 62cc5fc6462da1a4bbcd6cce06e49e1a04d4c258 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 14 Oct 2021 21:44:28 -0700 Subject: [PATCH 1409/2212] [msl-out] Delete Writer::runtime_sized_buffers. (#1462) This is just a table mapping handles to their indices, but we can just fetch the index directly from the handle. We never iterate over its entries, but even if we did, we could at least use a HashSet instead of a HashMap. --- src/back/msl/writer.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e743dc5f6..e35bee19b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -307,7 +307,6 @@ pub struct Writer { names: FastHashMap, named_expressions: crate::NamedExpressions, namer: proc::Namer, - runtime_sized_buffers: FastHashMap, usize>, #[cfg(test)] put_expression_stack_pointers: FastHashSet<*const ()>, #[cfg(test)] @@ -473,7 +472,6 @@ impl Writer { names: FastHashMap::default(), named_expressions: crate::NamedExpressions::default(), namer: proc::Namer::default(), - runtime_sized_buffers: FastHashMap::default(), #[cfg(test)] put_expression_stack_pointers: Default::default(), #[cfg(test)] @@ -707,11 +705,10 @@ impl Writer { _ => return Err(Error::Validation), }; - let buffer_idx = self.runtime_sized_buffers[&handle]; write!( self.out, "(1 + (_buffer_sizes.size{idx} - {offset} - {span}) / {stride})", - idx = buffer_idx, + idx = handle.index(), offset = offset, span = span, stride = stride, @@ -1761,7 +1758,6 @@ impl Writer { self.names.clear(); self.namer .reset(module, super::keywords::RESERVED, &[], &mut self.names); - self.runtime_sized_buffers.clear(); self.struct_member_pads.clear(); writeln!( @@ -1778,7 +1774,6 @@ impl Writer { for (handle, var) in module.global_variables.iter() { if needs_array_length(var.ty, &module.types) { let idx = handle.index(); - self.runtime_sized_buffers.insert(handle, idx); indices.push(idx); } } From 528f52fba0db368dae60048bf4cb6f2373820bc8 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 16 Oct 2021 07:55:31 -0700 Subject: [PATCH 1410/2212] [msl-out] Put serde(default) on the whole struct, not on each field. (#1463) This has no effect, but makes the code more legible. --- src/back/msl/mod.rs | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index de82096a4..ca7b9682c 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -49,14 +49,11 @@ pub enum BindSamplerTarget { #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +#[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(default))] pub struct BindTarget { - #[cfg_attr(feature = "deserialize", serde(default))] pub buffer: Option, - #[cfg_attr(feature = "deserialize", serde(default))] pub texture: Option, - #[cfg_attr(feature = "deserialize", serde(default))] pub sampler: Option, - #[cfg_attr(feature = "deserialize", serde(default))] pub mutable: bool, } @@ -66,29 +63,25 @@ pub type BindingMap = std::collections::BTreeMap, /// The slot of a buffer that contains an array of `u32`, /// one for the size of each bound buffer that contains a runtime array, /// in order of [`crate::GlobalVariable`] declarations. - #[cfg_attr(feature = "deserialize", serde(default))] pub sizes_buffer: Option, } #[derive(Clone, Debug, Default, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +#[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(default))] pub struct PerStageMap { - #[cfg_attr(feature = "deserialize", serde(default))] pub vs: PerStageResources, - #[cfg_attr(feature = "deserialize", serde(default))] pub fs: PerStageResources, - #[cfg_attr(feature = "deserialize", serde(default))] pub cs: PerStageResources, } From ed4cc8e4d884e0d6aaa6c4041a679a1137f24b22 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 16 Oct 2021 10:56:59 -0700 Subject: [PATCH 1411/2212] Use Cow to reduce allocation in proc::Namer. (#1465) Minimize allocation in the namer. Heap-allocate string only when needed to provide an owned key for a hash table, or to hold synthesized text. Try to reuse allocations. Many unnecessary trailing `_` characters are removed from test output. These were all superfluous; separators are still inserted where necessary. --- src/proc/namer.rs | 92 +++++++++++------ tests/out/glsl/bits.main.Compute.glsl | 112 ++++++++++----------- tests/out/glsl/image.main.Compute.glsl | 10 +- tests/out/glsl/operators.main.Compute.glsl | 16 +-- tests/out/glsl/skybox.vs_main.Vertex.glsl | 12 +-- tests/out/hlsl/image.hlsl | 10 +- tests/out/hlsl/operators.hlsl | 16 +-- tests/out/hlsl/quad-vert.hlsl | 4 +- tests/out/hlsl/skybox.hlsl | 12 +-- tests/out/msl/bits.msl | 112 ++++++++++----------- tests/out/msl/image.msl | 16 +-- tests/out/msl/operators.msl | 16 +-- tests/out/msl/quad-vert.msl | 6 +- tests/out/msl/skybox.msl | 12 +-- tests/out/wgsl/bevy-pbr-frag.wgsl | 58 +++++------ tests/out/wgsl/bits.wgsl | 112 ++++++++++----------- tests/out/wgsl/bits_glsl-frag.wgsl | 96 +++++++++--------- tests/out/wgsl/fma-frag.wgsl | 18 ++-- tests/out/wgsl/image.wgsl | 10 +- tests/out/wgsl/operators.wgsl | 16 +-- tests/out/wgsl/skybox.wgsl | 12 +-- 21 files changed, 398 insertions(+), 370 deletions(-) diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 90c91e503..0a74b178b 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -1,5 +1,5 @@ use crate::{arena::Handle, FastHashMap, FastHashSet}; -use std::collections::hash_map::Entry; +use std::borrow::Cow; pub type EntryPointIndex = u16; @@ -21,7 +21,7 @@ pub enum NameKey { /// that may need identifiers in a textual backend. #[derive(Default)] pub struct Namer { - /// The last numeric suffix used for each base name. + /// The last numeric suffix used for each base name. Zero means "no suffix". unique: FastHashMap, keywords: FastHashSet, reserved_prefixes: Vec, @@ -30,26 +30,28 @@ pub struct Namer { impl Namer { /// Return a form of `string` suitable for use as the base of an identifier. /// - /// Retain only alphanumeric and `_` characters. Drop leading digits. Ensure - /// that the string does not end with a digit, so we can attach numeric - /// suffixes without merging. Avoid prefixes in - /// [`Namer::reserved_prefixes`]. - fn sanitize(&self, string: &str) -> String { - let mut base = string + /// Retain only alphanumeric and `_` characters. Drop leading digits. Avoid + /// prefixes in [`Namer::reserved_prefixes`]. + fn sanitize<'s>(&self, string: &'s str) -> Cow<'s, str> { + let string = string.trim_start_matches(|c: char| c.is_numeric() || c == '_'); + + let base = if string .chars() - .skip_while(|&c| c.is_numeric() || c == '_') - .filter(|&c| c.is_ascii_alphanumeric() || c == '_') - .collect::(); - // close the name by '_' if the re is a number, so that - // we can have our own number! - match base.chars().next_back() { - Some(c) if !c.is_numeric() => {} - _ => base.push('_'), + .all(|c: char| c.is_ascii_alphanumeric() || c == '_') + { + Cow::Borrowed(string) + } else { + Cow::Owned( + string + .chars() + .filter(|&c| c.is_ascii_alphanumeric() || c == '_') + .collect::(), + ) }; for prefix in &self.reserved_prefixes { if base.starts_with(prefix) { - return format!("gen_{}", base); + return format!("gen_{}", base).into(); } } @@ -64,25 +66,51 @@ impl Namer { /// - is different from any identifier previously constructed by this /// `Namer`. /// - /// Guarantee uniqueness by applying a numeric suffix when necessary. + /// Guarantee uniqueness by applying a numeric suffix when necessary. If `label_raw` + /// itself ends with digits, separate them from the suffix with an underscore. pub fn call(&mut self, label_raw: &str) -> String { + use std::fmt::Write; // for write!-ing to Strings + let base = self.sanitize(label_raw); - match self.unique.entry(base) { - Entry::Occupied(mut e) => { - *e.get_mut() += 1; - format!("{}{}", e.key(), e.get()) + let separator = if base.ends_with(char::is_numeric) { + "_" + } else { + "" + }; + + // This would seem to be a natural place to use `HashMap::entry`. However, `entry` + // requires an owned key, and we'd like to avoid heap-allocating strings we're + // just going to throw away. The approach below double-hashes only when we create + // a new entry, in which case the heap allocation of the owned key was more + // expensive anyway. + match self.unique.get_mut(base.as_ref()) { + Some(count) => { + *count += 1; + // Add the suffix. This may fit in base's existing allocation. + let mut suffixed = base.into_owned(); + write!(&mut suffixed, "{}{}", separator, *count).unwrap(); + suffixed } - Entry::Vacant(e) => { - let name = e.key(); - if self.keywords.contains(e.key()) { - let name = format!("{}1", name); - e.insert(1); - name - } else { - let name = name.to_string(); - e.insert(0); - name + None => { + let mut count = 0; + let mut suffixed = Cow::Borrowed(base.as_ref()); + while self.keywords.contains(suffixed.as_ref()) { + count += 1; + // Try to reuse suffixed's allocation. + let mut buf = suffixed.into_owned(); + buf.clear(); + write!(&mut buf, "{}{}{}", base, separator, count).unwrap(); + suffixed = Cow::Owned(buf); } + // Produce our return value, which must be an owned string. This allocates + // only if we haven't already done so earlier. + let suffixed = suffixed.into_owned(); + + // `self.unique` wants to own its keys. This allocates only if we haven't + // already done so earlier. + self.unique.insert(base.into_owned(), count); + + suffixed } } } diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl index 303cdbc44..af5eaec56 100644 --- a/tests/out/glsl/bits.main.Compute.glsl +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -8,83 +8,83 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; void main() { int i = 0; - ivec2 i2_ = ivec2(0, 0); - ivec3 i3_ = ivec3(0, 0, 0); - ivec4 i4_ = ivec4(0, 0, 0, 0); + ivec2 i2 = ivec2(0, 0); + ivec3 i3 = ivec3(0, 0, 0); + ivec4 i4 = ivec4(0, 0, 0, 0); uint u = 0u; - uvec2 u2_ = uvec2(0u, 0u); - uvec3 u3_ = uvec3(0u, 0u, 0u); - uvec4 u4_ = uvec4(0u, 0u, 0u, 0u); - vec2 f2_ = vec2(0.0, 0.0); - vec4 f4_ = vec4(0.0, 0.0, 0.0, 0.0); - i2_ = ivec2(0); - i3_ = ivec3(0); - i4_ = ivec4(0); - u2_ = uvec2(0u); - u3_ = uvec3(0u); - u4_ = uvec4(0u); - f2_ = vec2(0.0); - f4_ = vec4(0.0); - vec4 _e28 = f4_; + uvec2 u2 = uvec2(0u, 0u); + uvec3 u3 = uvec3(0u, 0u, 0u); + uvec4 u4 = uvec4(0u, 0u, 0u, 0u); + vec2 f2 = vec2(0.0, 0.0); + vec4 f4 = vec4(0.0, 0.0, 0.0, 0.0); + i2 = ivec2(0); + i3 = ivec3(0); + i4 = ivec4(0); + u2 = uvec2(0u); + u3 = uvec3(0u); + u4 = uvec4(0u); + f2 = vec2(0.0); + f4 = vec4(0.0); + vec4 _e28 = f4; u = packSnorm4x8(_e28); - vec4 _e30 = f4_; + vec4 _e30 = f4; u = packUnorm4x8(_e30); - vec2 _e32 = f2_; + vec2 _e32 = f2; u = packSnorm2x16(_e32); - vec2 _e34 = f2_; + vec2 _e34 = f2; u = packUnorm2x16(_e34); - vec2 _e36 = f2_; + vec2 _e36 = f2; u = packHalf2x16(_e36); uint _e38 = u; - f4_ = unpackSnorm4x8(_e38); + f4 = unpackSnorm4x8(_e38); uint _e40 = u; - f4_ = unpackUnorm4x8(_e40); + f4 = unpackUnorm4x8(_e40); uint _e42 = u; - f2_ = unpackSnorm2x16(_e42); + f2 = unpackSnorm2x16(_e42); uint _e44 = u; - f2_ = unpackUnorm2x16(_e44); + f2 = unpackUnorm2x16(_e44); uint _e46 = u; - f2_ = unpackHalf2x16(_e46); + f2 = unpackHalf2x16(_e46); int _e48 = i; int _e49 = i; i = bitfieldInsert(_e48, _e49, int(5u), int(10u)); - ivec2 _e53 = i2_; - ivec2 _e54 = i2_; - i2_ = bitfieldInsert(_e53, _e54, int(5u), int(10u)); - ivec3 _e58 = i3_; - ivec3 _e59 = i3_; - i3_ = bitfieldInsert(_e58, _e59, int(5u), int(10u)); - ivec4 _e63 = i4_; - ivec4 _e64 = i4_; - i4_ = bitfieldInsert(_e63, _e64, int(5u), int(10u)); + ivec2 _e53 = i2; + ivec2 _e54 = i2; + i2 = bitfieldInsert(_e53, _e54, int(5u), int(10u)); + ivec3 _e58 = i3; + ivec3 _e59 = i3; + i3 = bitfieldInsert(_e58, _e59, int(5u), int(10u)); + ivec4 _e63 = i4; + ivec4 _e64 = i4; + i4 = bitfieldInsert(_e63, _e64, int(5u), int(10u)); uint _e68 = u; uint _e69 = u; u = bitfieldInsert(_e68, _e69, int(5u), int(10u)); - uvec2 _e73 = u2_; - uvec2 _e74 = u2_; - u2_ = bitfieldInsert(_e73, _e74, int(5u), int(10u)); - uvec3 _e78 = u3_; - uvec3 _e79 = u3_; - u3_ = bitfieldInsert(_e78, _e79, int(5u), int(10u)); - uvec4 _e83 = u4_; - uvec4 _e84 = u4_; - u4_ = bitfieldInsert(_e83, _e84, int(5u), int(10u)); + uvec2 _e73 = u2; + uvec2 _e74 = u2; + u2 = bitfieldInsert(_e73, _e74, int(5u), int(10u)); + uvec3 _e78 = u3; + uvec3 _e79 = u3; + u3 = bitfieldInsert(_e78, _e79, int(5u), int(10u)); + uvec4 _e83 = u4; + uvec4 _e84 = u4; + u4 = bitfieldInsert(_e83, _e84, int(5u), int(10u)); int _e88 = i; i = bitfieldExtract(_e88, int(5u), int(10u)); - ivec2 _e92 = i2_; - i2_ = bitfieldExtract(_e92, int(5u), int(10u)); - ivec3 _e96 = i3_; - i3_ = bitfieldExtract(_e96, int(5u), int(10u)); - ivec4 _e100 = i4_; - i4_ = bitfieldExtract(_e100, int(5u), int(10u)); + ivec2 _e92 = i2; + i2 = bitfieldExtract(_e92, int(5u), int(10u)); + ivec3 _e96 = i3; + i3 = bitfieldExtract(_e96, int(5u), int(10u)); + ivec4 _e100 = i4; + i4 = bitfieldExtract(_e100, int(5u), int(10u)); uint _e104 = u; u = bitfieldExtract(_e104, int(5u), int(10u)); - uvec2 _e108 = u2_; - u2_ = bitfieldExtract(_e108, int(5u), int(10u)); - uvec3 _e112 = u3_; - u3_ = bitfieldExtract(_e112, int(5u), int(10u)); - uvec4 _e116 = u4_; - u4_ = bitfieldExtract(_e116, int(5u), int(10u)); + uvec2 _e108 = u2; + u2 = bitfieldExtract(_e108, int(5u), int(10u)); + uvec3 _e112 = u3; + u3 = bitfieldExtract(_e112, int(5u), int(10u)); + uvec4 _e116 = u4; + u4 = bitfieldExtract(_e116, int(5u), int(10u)); return; } diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl index be6b7ed97..17ed23538 100644 --- a/tests/out/glsl/image.main.Compute.glsl +++ b/tests/out/glsl/image.main.Compute.glsl @@ -21,11 +21,11 @@ void main() { uvec3 local_id = gl_LocalInvocationID; ivec2 dim = imageSize(_group_0_binding_1).xy; ivec2 itc = ((dim * ivec2(local_id.xy)) % ivec2(10, 20)); - uvec4 value1_ = texelFetch(_group_0_binding_0, itc, int(local_id.z)); - uvec4 value2_ = texelFetch(_group_0_binding_3, itc, int(local_id.z)); - uvec4 value4_ = imageLoad(_group_0_binding_1, itc); - uvec4 value5_ = texelFetch(_group_0_binding_5, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); - imageStore(_group_0_binding_2, ivec2(itc.x, 0.0), (((value1_ + value2_) + value4_) + value5_)); + uvec4 value1 = texelFetch(_group_0_binding_0, itc, int(local_id.z)); + uvec4 value2 = texelFetch(_group_0_binding_3, itc, int(local_id.z)); + uvec4 value4 = imageLoad(_group_0_binding_1, itc); + uvec4 value5 = texelFetch(_group_0_binding_5, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); + imageStore(_group_0_binding_2, ivec2(itc.x, 0.0), (((value1 + value2) + value4) + value5)); return; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index a135e6c4d..4a03f215d 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -12,15 +12,15 @@ struct Foo { vec4 builtins() { - int s1_ = (true ? 1 : 0); - vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); - vec4 s3_ = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), bvec4(false, false, false, false)); - vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); - float b1_ = intBitsToFloat(ivec4(1, 1, 1, 1).x); - vec4 b2_ = intBitsToFloat(ivec4(1, 1, 1, 1)); + int s1 = (true ? 1 : 0); + vec4 s2 = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); + vec4 s3 = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), bvec4(false, false, false, false)); + vec4 m1 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); + vec4 m2 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + float b1 = intBitsToFloat(ivec4(1, 1, 1, 1).x); + vec4 b2 = intBitsToFloat(ivec4(1, 1, 1, 1)); ivec4 v_i32_zero = ivec4(vec4(0.0, 0.0, 0.0, 0.0)); - return (((((vec4((ivec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); + return (((((vec4((ivec4(s1) + v_i32_zero)) + s2) + m1) + m2) + vec4(b1)) + b2); } vec4 splat() { diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index 06494a70f..34f21901d 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -17,12 +17,12 @@ layout(location = 0) smooth out vec3 _vs2fs_location0; void main() { uint vertex_index = uint(gl_VertexID); - int tmp1_ = 0; - int tmp2_ = 0; - tmp1_ = (int(vertex_index) / 2); - tmp2_ = (int(vertex_index) & 1); - int _e10 = tmp1_; - int _e16 = tmp2_; + int tmp1 = 0; + int tmp2 = 0; + tmp1 = (int(vertex_index) / 2); + tmp2 = (int(vertex_index) & 1); + int _e10 = tmp1; + int _e16 = tmp2; vec4 pos = vec4(((float(_e10) * 4.0) - 1.0), ((float(_e16) * 4.0) - 1.0), 0.0, 1.0); vec4 _e27 = _group_0_binding_0.view[0]; vec4 _e31 = _group_0_binding_0.view[1]; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index d6da396a5..9f04aa0cb 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -29,11 +29,11 @@ void main(uint3 local_id : SV_GroupThreadID) { int2 dim = NagaRWDimensions2D(image_storage_src); int2 itc = ((dim * int2(local_id.xy)) % int2(10, 20)); - uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(local_id.z))); - uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z)); - uint4 value4_ = image_storage_src.Load(itc); - uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); - image_dst[itc.x] = (((value1_ + value2_) + value4_) + value5_); + uint4 value1 = image_mipmapped_src.Load(int3(itc, int(local_id.z))); + uint4 value2 = image_multisampled_src.Load(itc, int(local_id.z)); + uint4 value4 = image_storage_src.Load(itc); + uint4 value5 = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); + image_dst[itc.x] = (((value1 + value2) + value4) + value5); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 0f6a23e30..d624c32aa 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -10,15 +10,15 @@ struct Foo { float4 builtins() { - int s1_ = (true ? 1 : 0); - float4 s2_ = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0)); - float4 s3_ = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); - float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); - float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); - float b1_ = float(int4(1, 1, 1, 1).x); - float4 b2_ = float4(int4(1, 1, 1, 1)); + int s1 = (true ? 1 : 0); + float4 s2 = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0)); + float4 s3 = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); + float4 m1 = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); + float4 m2 = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + float b1 = float(int4(1, 1, 1, 1).x); + float4 b2 = float4(int4(1, 1, 1, 1)); int4 v_i32_zero = int4(float4(0.0, 0.0, 0.0, 0.0)); - return (((((float4((int4(s1_.xxxx) + v_i32_zero)) + s2_) + m1_) + m2_) + float4(b1_.xxxx)) + b2_); + return (((((float4((int4(s1.xxxx) + v_i32_zero)) + s2) + m1) + m2) + float4(b1.xxxx)) + b2); } float4 splat() diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 261468de1..582fb0dd9 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -56,7 +56,7 @@ VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0) float _expr12 = perVertexStruct.gl_PointSize; float _expr13[1] = perVertexStruct.gl_ClipDistance; float _expr14[1] = perVertexStruct.gl_CullDistance; - const type9 type9_ = Constructtype9(_expr10, _expr11, _expr12, _expr13, _expr14); - const VertexOutput_main type9_1 = { type9_.member, type9_.gl_Position, type9_.gl_ClipDistance, type9_.gl_CullDistance, type9_.gl_PointSize }; + const type9 type9 = Constructtype9(_expr10, _expr11, _expr12, _expr13, _expr14); + const VertexOutput_main type9_1 = { type9.member, type9.gl_Position, type9.gl_ClipDistance, type9.gl_CullDistance, type9.gl_PointSize }; return type9_1; } diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 0120ff7fb..7bb6af6ca 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -38,13 +38,13 @@ VertexOutput ConstructVertexOutput(float4 arg0, float3 arg1) { VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) { - int tmp1_ = (int)0; - int tmp2_ = (int)0; + int tmp1 = (int)0; + int tmp2 = (int)0; - tmp1_ = (int((_NagaConstants.base_vertex + vertex_index)) / 2); - tmp2_ = (int((_NagaConstants.base_vertex + vertex_index)) & 1); - int _expr10 = tmp1_; - int _expr16 = tmp2_; + tmp1 = (int((_NagaConstants.base_vertex + vertex_index)) / 2); + tmp2 = (int((_NagaConstants.base_vertex + vertex_index)) & 1); + int _expr10 = tmp1; + int _expr16 = tmp2; float4 pos = float4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); float4 _expr27 = r_data.view[0]; float4 _expr31 = r_data.view[1]; diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index 70ca905e3..3e1911342 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -6,82 +6,82 @@ kernel void main1( ) { int i = 0; - metal::int2 i2_; - metal::int3 i3_; - metal::int4 i4_; + metal::int2 i2; + metal::int3 i3; + metal::int4 i4; metal::uint u = 0u; - metal::uint2 u2_; - metal::uint3 u3_; - metal::uint4 u4_; - metal::float2 f2_; - metal::float4 f4_; - i2_ = metal::int2(0); - i3_ = metal::int3(0); - i4_ = metal::int4(0); - u2_ = metal::uint2(0u); - u3_ = metal::uint3(0u); - u4_ = metal::uint4(0u); - f2_ = metal::float2(0.0); - f4_ = metal::float4(0.0); - metal::float4 _e28 = f4_; + metal::uint2 u2; + metal::uint3 u3; + metal::uint4 u4; + metal::float2 f2; + metal::float4 f4; + i2 = metal::int2(0); + i3 = metal::int3(0); + i4 = metal::int4(0); + u2 = metal::uint2(0u); + u3 = metal::uint3(0u); + u4 = metal::uint4(0u); + f2 = metal::float2(0.0); + f4 = metal::float4(0.0); + metal::float4 _e28 = f4; u = metal::pack_float_to_unorm4x8(_e28); - metal::float4 _e30 = f4_; + metal::float4 _e30 = f4; u = metal::pack_float_to_snorm4x8(_e30); - metal::float2 _e32 = f2_; + metal::float2 _e32 = f2; u = metal::pack_float_to_unorm2x16(_e32); - metal::float2 _e34 = f2_; + metal::float2 _e34 = f2; u = metal::pack_float_to_snorm2x16(_e34); - metal::float2 _e36 = f2_; + metal::float2 _e36 = f2; u = as_type(half2(_e36)); metal::uint _e38 = u; - f4_ = metal::unpack_snorm4x8_to_float(_e38); + f4 = metal::unpack_snorm4x8_to_float(_e38); metal::uint _e40 = u; - f4_ = metal::unpack_unorm4x8_to_float(_e40); + f4 = metal::unpack_unorm4x8_to_float(_e40); metal::uint _e42 = u; - f2_ = metal::unpack_snorm2x16_to_float(_e42); + f2 = metal::unpack_snorm2x16_to_float(_e42); metal::uint _e44 = u; - f2_ = metal::unpack_unorm2x16_to_float(_e44); + f2 = metal::unpack_unorm2x16_to_float(_e44); metal::uint _e46 = u; - f2_ = float2(as_type(_e46)); + f2 = float2(as_type(_e46)); int _e48 = i; int _e49 = i; i = metal::insert_bits(_e48, _e49, 5u, 10u); - metal::int2 _e53 = i2_; - metal::int2 _e54 = i2_; - i2_ = metal::insert_bits(_e53, _e54, 5u, 10u); - metal::int3 _e58 = i3_; - metal::int3 _e59 = i3_; - i3_ = metal::insert_bits(_e58, _e59, 5u, 10u); - metal::int4 _e63 = i4_; - metal::int4 _e64 = i4_; - i4_ = metal::insert_bits(_e63, _e64, 5u, 10u); + metal::int2 _e53 = i2; + metal::int2 _e54 = i2; + i2 = metal::insert_bits(_e53, _e54, 5u, 10u); + metal::int3 _e58 = i3; + metal::int3 _e59 = i3; + i3 = metal::insert_bits(_e58, _e59, 5u, 10u); + metal::int4 _e63 = i4; + metal::int4 _e64 = i4; + i4 = metal::insert_bits(_e63, _e64, 5u, 10u); metal::uint _e68 = u; metal::uint _e69 = u; u = metal::insert_bits(_e68, _e69, 5u, 10u); - metal::uint2 _e73 = u2_; - metal::uint2 _e74 = u2_; - u2_ = metal::insert_bits(_e73, _e74, 5u, 10u); - metal::uint3 _e78 = u3_; - metal::uint3 _e79 = u3_; - u3_ = metal::insert_bits(_e78, _e79, 5u, 10u); - metal::uint4 _e83 = u4_; - metal::uint4 _e84 = u4_; - u4_ = metal::insert_bits(_e83, _e84, 5u, 10u); + metal::uint2 _e73 = u2; + metal::uint2 _e74 = u2; + u2 = metal::insert_bits(_e73, _e74, 5u, 10u); + metal::uint3 _e78 = u3; + metal::uint3 _e79 = u3; + u3 = metal::insert_bits(_e78, _e79, 5u, 10u); + metal::uint4 _e83 = u4; + metal::uint4 _e84 = u4; + u4 = metal::insert_bits(_e83, _e84, 5u, 10u); int _e88 = i; i = metal::extract_bits(_e88, 5u, 10u); - metal::int2 _e92 = i2_; - i2_ = metal::extract_bits(_e92, 5u, 10u); - metal::int3 _e96 = i3_; - i3_ = metal::extract_bits(_e96, 5u, 10u); - metal::int4 _e100 = i4_; - i4_ = metal::extract_bits(_e100, 5u, 10u); + metal::int2 _e92 = i2; + i2 = metal::extract_bits(_e92, 5u, 10u); + metal::int3 _e96 = i3; + i3 = metal::extract_bits(_e96, 5u, 10u); + metal::int4 _e100 = i4; + i4 = metal::extract_bits(_e100, 5u, 10u); metal::uint _e104 = u; u = metal::extract_bits(_e104, 5u, 10u); - metal::uint2 _e108 = u2_; - u2_ = metal::extract_bits(_e108, 5u, 10u); - metal::uint3 _e112 = u3_; - u3_ = metal::extract_bits(_e112, 5u, 10u); - metal::uint4 _e116 = u4_; - u4_ = metal::extract_bits(_e116, 5u, 10u); + metal::uint2 _e108 = u2; + u2 = metal::extract_bits(_e108, 5u, 10u); + metal::uint3 _e112 = u3; + u3 = metal::extract_bits(_e112, 5u, 10u); + metal::uint4 _e116 = u4; + u4 = metal::extract_bits(_e116, 5u, 10u); return; } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 1c8e5e4ea..c0e3ad41c 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -2,7 +2,7 @@ #include #include -constant metal::int2 const_type8_ = {3, 1}; +constant metal::int2 const_type8 = {3, 1}; struct main1Input { }; @@ -16,11 +16,11 @@ kernel void main1( ) { metal::int2 dim = int2(image_storage_src.get_width(), image_storage_src.get_height()); metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); - metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); - metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); - metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); - metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); - image_dst.write(((value1_ + value2_) + value4_) + value5_, metal::uint(itc.x)); + metal::uint4 value1 = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); + metal::uint4 value2 = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); + metal::uint4 value4 = image_storage_src.read(metal::uint2(itc)); + metal::uint4 value5 = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); + image_dst.write(((value1 + value2) + value4) + value5, metal::uint(itc.x)); return; } @@ -103,9 +103,9 @@ fragment sampleOutput sample( metal::float2 tc = metal::float2(0.5); metal::float4 s1d = image_1d.sample(sampler_reg, tc.x); metal::float4 s2d = image_2d.sample(sampler_reg, tc); - metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type8_); + metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type8); metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); - metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type8_); + metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type8); return sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset }; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index c1e52481c..98fb58457 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -13,15 +13,15 @@ constant metal::int4 v_i32_one = {1, 1, 1, 1}; metal::float4 builtins( ) { - int s1_ = true ? 1 : 0; - metal::float4 s2_ = true ? v_f32_one : v_f32_zero; - metal::float4 s3_ = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false)); - metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half); - metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.10000000149011612); - float b1_ = as_type(v_i32_one.x); - metal::float4 b2_ = as_type(v_i32_one); + int s1 = true ? 1 : 0; + metal::float4 s2 = true ? v_f32_one : v_f32_zero; + metal::float4 s3 = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false)); + metal::float4 m1 = metal::mix(v_f32_zero, v_f32_one, v_f32_half); + metal::float4 m2 = metal::mix(v_f32_zero, v_f32_one, 0.10000000149011612); + float b1 = as_type(v_i32_one.x); + metal::float4 b2 = as_type(v_i32_one); metal::int4 v_i32_zero = static_cast(v_f32_zero); - return ((((static_cast(metal::int4(s1_) + v_i32_zero) + s2_) + m1_) + m2_) + metal::float4(b1_)) + b2_; + return ((((static_cast(metal::int4(s1) + v_i32_zero) + s2) + m1) + m2) + metal::float4(b1)) + b2; } metal::float4 splat( diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index 8caf6fc49..7efab9a63 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -18,9 +18,9 @@ struct type9 { type5 gl_ClipDistance; type5 gl_CullDistance; }; -constant metal::float4 const_type3_ = {0.0, 0.0, 0.0, 1.0}; -constant type5 const_type5_ = {0.0}; -constant gl_PerVertex const_gl_PerVertex = {const_type3_, 1.0, const_type5_, const_type5_}; +constant metal::float4 const_type3 = {0.0, 0.0, 0.0, 1.0}; +constant type5 const_type5 = {0.0}; +constant gl_PerVertex const_gl_PerVertex = {const_type3, 1.0, const_type5, const_type5}; void main2( thread metal::float2& v_uv, diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index 1a479a89e..2b37de6c8 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -21,12 +21,12 @@ vertex vs_mainOutput vs_main( metal::uint vertex_index [[vertex_id]] , constant Data& r_data [[buffer(0)]] ) { - int tmp1_; - int tmp2_; - tmp1_ = static_cast(vertex_index) / 2; - tmp2_ = static_cast(vertex_index) & 1; - int _e10 = tmp1_; - int _e16 = tmp2_; + int tmp1; + int tmp2; + tmp1 = static_cast(vertex_index) / 2; + tmp2 = static_cast(vertex_index) & 1; + int _e10 = tmp1; + int _e16 = tmp2; metal::float4 pos = metal::float4((static_cast(_e10) * 4.0) - 1.0, (static_cast(_e16) * 4.0) - 1.0, 0.0, 1.0); metal::float4 _e27 = r_data.view[0]; metal::float4 _e31 = r_data.view[1]; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index b2c97f693..f775281be 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -99,16 +99,16 @@ var StandardMaterial_emissive_texture: texture_2d; var StandardMaterial_emissive_texture_sampler: sampler; var gl_FrontFacing: bool; -fn pow5_(x: f32) -> f32 { +fn pow5(x: f32) -> f32 { var x1: f32; - var x2_: f32; + var x2: f32; x1 = x; let e42: f32 = x1; let e43: f32 = x1; - x2_ = (e42 * e43); - let e46: f32 = x2_; - let e47: f32 = x2_; + x2 = (e42 * e43); + let e46: f32 = x2; + let e47: f32 = x2; let e49: f32 = x1; return ((e46 * e47) * e49); } @@ -170,7 +170,7 @@ fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 { var roughness3: f32; var NoV1: f32; var NoL1: f32; - var a2_: f32; + var a2: f32; var lambdaV: f32; var lambdaL: f32; var v: f32; @@ -180,30 +180,30 @@ fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 { NoL1 = NoL; let e46: f32 = roughness3; let e47: f32 = roughness3; - a2_ = (e46 * e47); + a2 = (e46 * e47); let e50: f32 = NoL1; let e51: f32 = NoV1; - let e52: f32 = a2_; + let e52: f32 = a2; let e53: f32 = NoV1; let e56: f32 = NoV1; - let e58: f32 = a2_; + let e58: f32 = a2; let e60: f32 = NoV1; - let e61: f32 = a2_; + let e61: f32 = a2; let e62: f32 = NoV1; let e65: f32 = NoV1; - let e67: f32 = a2_; + let e67: f32 = a2; lambdaV = (e50 * sqrt((((e60 - (e61 * e62)) * e65) + e67))); let e72: f32 = NoV1; let e73: f32 = NoL1; - let e74: f32 = a2_; + let e74: f32 = a2; let e75: f32 = NoL1; let e78: f32 = NoL1; - let e80: f32 = a2_; + let e80: f32 = a2; let e82: f32 = NoL1; - let e83: f32 = a2_; + let e83: f32 = a2; let e84: f32 = NoL1; let e87: f32 = NoL1; - let e89: f32 = a2_; + let e89: f32 = a2; lambdaL = (e72 * sqrt((((e82 - (e83 * e84)) * e87) + e89))); let e95: f32 = lambdaV; let e96: f32 = lambdaL; @@ -212,17 +212,17 @@ fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 { return e100; } -fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { +fn F_Schlick(f0: vec3, f90: f32, VoH: f32) -> vec3 { var f90_1: f32; var VoH1: f32; - f90_1 = f90_; + f90_1 = f90; VoH1 = VoH; let e45: f32 = f90_1; let e49: f32 = VoH1; let e52: f32 = VoH1; - let e54: f32 = pow5_((1.0 - e52)); - return (f0_ + ((vec3(e45) - f0_) * e54)); + let e54: f32 = pow5((1.0 - e52)); + return (f0 + ((vec3(e45) - f0) * e54)); } fn F_Schlick1(f0_1: f32, f90_2: f32, VoH2: f32) -> f32 { @@ -238,7 +238,7 @@ fn F_Schlick1(f0_1: f32, f90_2: f32, VoH2: f32) -> f32 { let e48: f32 = f0_2; let e51: f32 = VoH3; let e54: f32 = VoH3; - let e56: f32 = pow5_((1.0 - e54)); + let e56: f32 = pow5((1.0 - e54)); return (e46 + ((e47 - e48) * e56)); } @@ -332,18 +332,18 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV6: f32) -> vec3< var f0_8: vec3; var perceptual_roughness1: f32; var NoV7: f32; - var c0_: vec4 = vec4(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071); - var c1_: vec4 = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033); + var c0: vec4 = vec4(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071); + var c1: vec4 = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033); var r: vec4; - var a004_: f32; + var a004: f32; var AB: vec2; f0_8 = f0_7; perceptual_roughness1 = perceptual_roughness; NoV7 = NoV6; let e62: f32 = perceptual_roughness1; - let e64: vec4 = c0_; - let e66: vec4 = c1_; + let e64: vec4 = c0; + let e66: vec4 = c1; r = ((vec4(e62) * e64) + e66); let e69: vec4 = r; let e71: vec4 = r; @@ -355,8 +355,8 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV6: f32) -> vec3< let e94: f32 = NoV7; let e98: vec4 = r; let e101: vec4 = r; - a004_ = ((min((e83.x * e85.x), exp2((-(9.279999732971191) * e94))) * e98.x) + e101.y); - let e109: f32 = a004_; + a004 = ((min((e83.x * e85.x), exp2((-(9.279999732971191) * e94))) * e98.x) + e101.y); + let e109: f32 = a004; let e112: vec4 = r; AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(e109)) + e112.zw); let e116: vec3 = f0_8; @@ -471,7 +471,7 @@ fn reinhard_extended_luminance(color6: vec3, max_white_l: f32) -> vec3 return e68; } -fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: vec3, R: vec3, F0_: vec3, diffuseColor: vec3) -> vec3 { +fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: vec3, R: vec3, F0: vec3, diffuseColor: vec3) -> vec3 { var light1: PointLight; var roughness9: f32; var NdotV1: f32; @@ -504,7 +504,7 @@ fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: N1 = N; V2 = V1; R1 = R; - F0_1 = F0_; + F0_1 = F0; diffuseColor1 = diffuseColor; let e56: PointLight = light1; let e59: vec3 = v_WorldPosition1; diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index c4054d8e3..f2984d5ac 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -1,83 +1,83 @@ [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { var i: i32 = 0; - var i2_: vec2; - var i3_: vec3; - var i4_: vec4; + var i2: vec2; + var i3: vec3; + var i4: vec4; var u: u32 = 0u; - var u2_: vec2; - var u3_: vec3; - var u4_: vec4; - var f2_: vec2; - var f4_: vec4; + var u2: vec2; + var u3: vec3; + var u4: vec4; + var f2: vec2; + var f4: vec4; - i2_ = vec2(0); - i3_ = vec3(0); - i4_ = vec4(0); - u2_ = vec2(0u); - u3_ = vec3(0u); - u4_ = vec4(0u); - f2_ = vec2(0.0); - f4_ = vec4(0.0); - let e28: vec4 = f4_; + i2 = vec2(0); + i3 = vec3(0); + i4 = vec4(0); + u2 = vec2(0u); + u3 = vec3(0u); + u4 = vec4(0u); + f2 = vec2(0.0); + f4 = vec4(0.0); + let e28: vec4 = f4; u = pack4x8snorm(e28); - let e30: vec4 = f4_; + let e30: vec4 = f4; u = pack4x8unorm(e30); - let e32: vec2 = f2_; + let e32: vec2 = f2; u = pack2x16snorm(e32); - let e34: vec2 = f2_; + let e34: vec2 = f2; u = pack2x16unorm(e34); - let e36: vec2 = f2_; + let e36: vec2 = f2; u = pack2x16float(e36); let e38: u32 = u; - f4_ = unpack4x8snorm(e38); + f4 = unpack4x8snorm(e38); let e40: u32 = u; - f4_ = unpack4x8unorm(e40); + f4 = unpack4x8unorm(e40); let e42: u32 = u; - f2_ = unpack2x16snorm(e42); + f2 = unpack2x16snorm(e42); let e44: u32 = u; - f2_ = unpack2x16unorm(e44); + f2 = unpack2x16unorm(e44); let e46: u32 = u; - f2_ = unpack2x16float(e46); + f2 = unpack2x16float(e46); let e48: i32 = i; let e49: i32 = i; i = insertBits(e48, e49, 5u, 10u); - let e53: vec2 = i2_; - let e54: vec2 = i2_; - i2_ = insertBits(e53, e54, 5u, 10u); - let e58: vec3 = i3_; - let e59: vec3 = i3_; - i3_ = insertBits(e58, e59, 5u, 10u); - let e63: vec4 = i4_; - let e64: vec4 = i4_; - i4_ = insertBits(e63, e64, 5u, 10u); + let e53: vec2 = i2; + let e54: vec2 = i2; + i2 = insertBits(e53, e54, 5u, 10u); + let e58: vec3 = i3; + let e59: vec3 = i3; + i3 = insertBits(e58, e59, 5u, 10u); + let e63: vec4 = i4; + let e64: vec4 = i4; + i4 = insertBits(e63, e64, 5u, 10u); let e68: u32 = u; let e69: u32 = u; u = insertBits(e68, e69, 5u, 10u); - let e73: vec2 = u2_; - let e74: vec2 = u2_; - u2_ = insertBits(e73, e74, 5u, 10u); - let e78: vec3 = u3_; - let e79: vec3 = u3_; - u3_ = insertBits(e78, e79, 5u, 10u); - let e83: vec4 = u4_; - let e84: vec4 = u4_; - u4_ = insertBits(e83, e84, 5u, 10u); + let e73: vec2 = u2; + let e74: vec2 = u2; + u2 = insertBits(e73, e74, 5u, 10u); + let e78: vec3 = u3; + let e79: vec3 = u3; + u3 = insertBits(e78, e79, 5u, 10u); + let e83: vec4 = u4; + let e84: vec4 = u4; + u4 = insertBits(e83, e84, 5u, 10u); let e88: i32 = i; i = extractBits(e88, 5u, 10u); - let e92: vec2 = i2_; - i2_ = extractBits(e92, 5u, 10u); - let e96: vec3 = i3_; - i3_ = extractBits(e96, 5u, 10u); - let e100: vec4 = i4_; - i4_ = extractBits(e100, 5u, 10u); + let e92: vec2 = i2; + i2 = extractBits(e92, 5u, 10u); + let e96: vec3 = i3; + i3 = extractBits(e96, 5u, 10u); + let e100: vec4 = i4; + i4 = extractBits(e100, 5u, 10u); let e104: u32 = u; u = extractBits(e104, 5u, 10u); - let e108: vec2 = u2_; - u2_ = extractBits(e108, 5u, 10u); - let e112: vec3 = u3_; - u3_ = extractBits(e112, 5u, 10u); - let e116: vec4 = u4_; - u4_ = extractBits(e116, 5u, 10u); + let e108: vec2 = u2; + u2 = extractBits(e108, 5u, 10u); + let e112: vec3 = u3; + u3 = extractBits(e112, 5u, 10u); + let e116: vec4 = u4; + u4 = extractBits(e116, 5u, 10u); return; } diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 2eb77888c..3f0e7cf7e 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -1,75 +1,75 @@ fn main1() { var i: i32 = 0; - var i2_: vec2 = vec2(0, 0); - var i3_: vec3 = vec3(0, 0, 0); - var i4_: vec4 = vec4(0, 0, 0, 0); + var i2: vec2 = vec2(0, 0); + var i3: vec3 = vec3(0, 0, 0); + var i4: vec4 = vec4(0, 0, 0, 0); var u: u32 = 0u; - var u2_: vec2 = vec2(0u, 0u); - var u3_: vec3 = vec3(0u, 0u, 0u); - var u4_: vec4 = vec4(0u, 0u, 0u, 0u); - var f2_: vec2 = vec2(0.0, 0.0); - var f4_: vec4 = vec4(0.0, 0.0, 0.0, 0.0); + var u2: vec2 = vec2(0u, 0u); + var u3: vec3 = vec3(0u, 0u, 0u); + var u4: vec4 = vec4(0u, 0u, 0u, 0u); + var f2: vec2 = vec2(0.0, 0.0); + var f4: vec4 = vec4(0.0, 0.0, 0.0, 0.0); - let e33: vec4 = f4_; + let e33: vec4 = f4; u = pack4x8snorm(e33); - let e36: vec4 = f4_; + let e36: vec4 = f4; u = pack4x8unorm(e36); - let e39: vec2 = f2_; + let e39: vec2 = f2; u = pack2x16unorm(e39); - let e42: vec2 = f2_; + let e42: vec2 = f2; u = pack2x16snorm(e42); - let e45: vec2 = f2_; + let e45: vec2 = f2; u = pack2x16float(e45); let e48: u32 = u; - f4_ = unpack4x8snorm(e48); + f4 = unpack4x8snorm(e48); let e51: u32 = u; - f4_ = unpack4x8unorm(e51); + f4 = unpack4x8unorm(e51); let e54: u32 = u; - f2_ = unpack2x16snorm(e54); + f2 = unpack2x16snorm(e54); let e57: u32 = u; - f2_ = unpack2x16unorm(e57); + f2 = unpack2x16unorm(e57); let e60: u32 = u; - f2_ = unpack2x16float(e60); + f2 = unpack2x16float(e60); let e66: i32 = i; let e67: i32 = i; i = insertBits(e66, e67, u32(5), u32(10)); - let e77: vec2 = i2_; - let e78: vec2 = i2_; - i2_ = insertBits(e77, e78, u32(5), u32(10)); - let e88: vec3 = i3_; - let e89: vec3 = i3_; - i3_ = insertBits(e88, e89, u32(5), u32(10)); - let e99: vec4 = i4_; - let e100: vec4 = i4_; - i4_ = insertBits(e99, e100, u32(5), u32(10)); + let e77: vec2 = i2; + let e78: vec2 = i2; + i2 = insertBits(e77, e78, u32(5), u32(10)); + let e88: vec3 = i3; + let e89: vec3 = i3; + i3 = insertBits(e88, e89, u32(5), u32(10)); + let e99: vec4 = i4; + let e100: vec4 = i4; + i4 = insertBits(e99, e100, u32(5), u32(10)); let e110: u32 = u; let e111: u32 = u; u = insertBits(e110, e111, u32(5), u32(10)); - let e121: vec2 = u2_; - let e122: vec2 = u2_; - u2_ = insertBits(e121, e122, u32(5), u32(10)); - let e132: vec3 = u3_; - let e133: vec3 = u3_; - u3_ = insertBits(e132, e133, u32(5), u32(10)); - let e143: vec4 = u4_; - let e144: vec4 = u4_; - u4_ = insertBits(e143, e144, u32(5), u32(10)); + let e121: vec2 = u2; + let e122: vec2 = u2; + u2 = insertBits(e121, e122, u32(5), u32(10)); + let e132: vec3 = u3; + let e133: vec3 = u3; + u3 = insertBits(e132, e133, u32(5), u32(10)); + let e143: vec4 = u4; + let e144: vec4 = u4; + u4 = insertBits(e143, e144, u32(5), u32(10)); let e153: i32 = i; i = extractBits(e153, u32(5), u32(10)); - let e162: vec2 = i2_; - i2_ = extractBits(e162, u32(5), u32(10)); - let e171: vec3 = i3_; - i3_ = extractBits(e171, u32(5), u32(10)); - let e180: vec4 = i4_; - i4_ = extractBits(e180, u32(5), u32(10)); + let e162: vec2 = i2; + i2 = extractBits(e162, u32(5), u32(10)); + let e171: vec3 = i3; + i3 = extractBits(e171, u32(5), u32(10)); + let e180: vec4 = i4; + i4 = extractBits(e180, u32(5), u32(10)); let e189: u32 = u; u = extractBits(e189, u32(5), u32(10)); - let e198: vec2 = u2_; - u2_ = extractBits(e198, u32(5), u32(10)); - let e207: vec3 = u3_; - u3_ = extractBits(e207, u32(5), u32(10)); - let e216: vec4 = u4_; - u4_ = extractBits(e216, u32(5), u32(10)); + let e198: vec2 = u2; + u2 = extractBits(e198, u32(5), u32(10)); + let e207: vec3 = u3; + u3 = extractBits(e207, u32(5), u32(10)); + let e216: vec4 = u4; + u4 = extractBits(e216, u32(5), u32(10)); return; } diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index e943de29b..86dfdc0c4 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -1,4 +1,4 @@ -struct Mat4x3_ { +struct Mat4x3 { mx: vec4; my: vec4; mz: vec4; @@ -6,22 +6,22 @@ struct Mat4x3_ { var o_color: vec4; -fn Fma(d: ptr, m: Mat4x3_, s: f32) { - var m1: Mat4x3_; +fn Fma(d: ptr, m: Mat4x3, s: f32) { + var m1: Mat4x3; var s1: f32; m1 = m; s1 = s; - let e6: Mat4x3_ = (*d); - let e8: Mat4x3_ = m1; + let e6: Mat4x3 = (*d); + let e8: Mat4x3 = m1; let e10: f32 = s1; (*d).mx = (e6.mx + (e8.mx * e10)); - let e14: Mat4x3_ = (*d); - let e16: Mat4x3_ = m1; + let e14: Mat4x3 = (*d); + let e16: Mat4x3 = m1; let e18: f32 = s1; (*d).my = (e14.my + (e16.my * e18)); - let e22: Mat4x3_ = (*d); - let e24: Mat4x3_ = m1; + let e22: Mat4x3 = (*d); + let e24: Mat4x3 = m1; let e26: f32 = s1; (*d).mz = (e22.mz + (e24.mz * e26)); return; diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 34d642a2f..ab374b0de 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -37,11 +37,11 @@ var image_2d_depth: texture_depth_2d; fn main([[builtin(local_invocation_id)]] local_id: vec3) { let dim: vec2 = textureDimensions(image_storage_src); let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); - let value1_: vec4 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); - let value2_: vec4 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); - let value4_: vec4 = textureLoad(image_storage_src, itc); - let value5_: vec4 = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); - textureStore(image_dst, itc.x, (((value1_ + value2_) + value4_) + value5_)); + let value1: vec4 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); + let value2: vec4 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); + let value4: vec4 = textureLoad(image_storage_src, itc); + let value5: vec4 = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); + textureStore(image_dst, itc.x, (((value1 + value2) + value4) + value5)); return; } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index b3f7bba03..3174b289b 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -8,15 +8,15 @@ let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); let v_i32_one: vec4 = vec4(1, 1, 1, 1); fn builtins() -> vec4 { - let s1_: i32 = select(0, 1, true); - let s2_: vec4 = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); - let s3_: vec4 = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); - let m1_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); - let b1_: f32 = bitcast(vec4(1, 1, 1, 1).x); - let b2_: vec4 = bitcast>(vec4(1, 1, 1, 1)); + let s1: i32 = select(0, 1, true); + let s2: vec4 = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); + let s3: vec4 = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); + let m1: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); + let m2: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + let b1: f32 = bitcast(vec4(1, 1, 1, 1).x); + let b2: vec4 = bitcast>(vec4(1, 1, 1, 1)); let v_i32_zero: vec4 = vec4(vec4(0.0, 0.0, 0.0, 0.0)); - return (((((vec4((vec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); + return (((((vec4((vec4(s1) + v_i32_zero)) + s2) + m1) + m2) + vec4(b1)) + b2); } fn splat() -> vec4 { diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index 27565be73..a21bbb6d6 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -18,13 +18,13 @@ var r_sampler: sampler; [[stage(vertex)]] fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { - var tmp1_: i32; - var tmp2_: i32; + var tmp1: i32; + var tmp2: i32; - tmp1_ = (i32(vertex_index) / 2); - tmp2_ = (i32(vertex_index) & 1); - let e10: i32 = tmp1_; - let e16: i32 = tmp2_; + tmp1 = (i32(vertex_index) / 2); + tmp2 = (i32(vertex_index) & 1); + let e10: i32 = tmp1; + let e16: i32 = tmp2; let pos: vec4 = vec4(((f32(e10) * 4.0) - 1.0), ((f32(e16) * 4.0) - 1.0), 0.0, 1.0); let e27: vec4 = r_data.view[0]; let e31: vec4 = r_data.view[1]; From c4ab9a3956c063773a813b9b6123e5d8a6892d19 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 18 Oct 2021 01:04:06 -0400 Subject: [PATCH 1412/2212] hlsl: Fix mat3 stores (#1467) --- src/back/hlsl/storage.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index b19129790..5840e43ed 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -129,7 +129,6 @@ impl super::Writer<'_, W> { crate::VectorSize::Tri => 4, columns => columns as u32, }; - let row_stride = width as u32 * padded_columns; let iter = (0..rows as u32).map(|i| { let ty_inner = crate::TypeInner::Vector { @@ -267,8 +266,15 @@ impl super::Writer<'_, W> { )?; self.write_store_value(module, &value, func_ctx)?; writeln!(self.out, ";")?; + + // Note: Matrices containing vec3s, due to padding, act like they contain vec4s. + let padded_columns = match columns { + crate::VectorSize::Tri => 4, + columns => columns as u32, + }; + let row_stride = width as u32 * padded_columns; + // then iterate the stores - let row_stride = width as u32 * columns as u32; for i in 0..rows as u32 { self.temp_access_chain .push(SubAccess::Offset(i * row_stride)); From 70ad084ad4916bef0cdeeed076abd2b5e1f803c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 20 Oct 2021 02:55:20 +0000 Subject: [PATCH 1413/2212] [spv-in]: Cull unused builtins inside structs (#1469) Some compilers like shaderc introduce a full gl_PerVertex struct, this includes gl_ClipDistance. Normally this isn't a problem since most drivers optimize it away, but naga zero inits globals if they weren't previously initialized. This causes gl_ClipDistance to be initialized to zero which can be really bad for performance. --- src/front/spv/function.rs | 11 +++++++++-- src/front/spv/mod.rs | 17 +++++++++++++++-- tests/out/glsl/quad-vert.main.Vertex.glsl | 12 +++--------- tests/out/hlsl/quad-vert.hlsl | 22 +++++----------------- tests/out/msl/quad-vert.msl | 16 ++++------------ tests/out/wgsl/quad-vert.wgsl | 6 +++--- 6 files changed, 39 insertions(+), 45 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 04b67dd06..ca7d002b5 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -376,9 +376,16 @@ impl> super::Parser { .. } => { for (index, sm) in sub_members.iter().enumerate() { - if sm.binding.is_none() { + match sm.binding { + Some(crate::Binding::BuiltIn(builtin)) => { + // Cull unused builtins to preserve performances + if !self.builtin_usage.contains(&builtin) { + continue; + } + } // unrecognized binding, skip - continue; + None => continue, + _ => {} } members.push(sm.clone()); components.push(function.expressions.append( diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index dad84ab25..8dbaba383 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -37,7 +37,7 @@ use function::*; use crate::{ arena::{Arena, Handle, UniqueArena}, proc::Layouter, - FastHashMap, + FastHashMap, FastHashSet, }; use num_traits::cast::FromPrimitive; @@ -549,6 +549,10 @@ pub struct Parser { (BodyIndex, Vec), std::hash::BuildHasherDefault, >, + + /// Tracks usage of builtins, used to cull unused builtins since they can + /// have serious performance implications. + builtin_usage: FastHashSet, } impl> Parser { @@ -582,6 +586,7 @@ impl> Parser { index_constants: Vec::new(), index_constant_expressions: Vec::new(), switch_cases: indexmap::IndexMap::default(), + builtin_usage: FastHashSet::default(), } } @@ -1294,9 +1299,10 @@ impl> Parser { let type_lookup = self.lookup_type.lookup(acex.type_id)?; acex = match ctx.type_arena[type_lookup.handle].inner { // can only index a struct with a constant - crate::TypeInner::Struct { .. } => { + crate::TypeInner::Struct { ref members, .. } => { let index = index_maybe .ok_or_else(|| Error::InvalidAccess(index_expr_data.clone()))?; + let lookup_member = self .lookup_member .get(&(type_lookup.handle, index)) @@ -1308,6 +1314,13 @@ impl> Parser { }, span, ); + + if let Some(crate::Binding::BuiltIn(builtin)) = + members[index as usize].binding + { + self.builtin_usage.insert(builtin); + } + AccessExpression { base_handle, type_id: lookup_member.type_id, diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index 5203c330e..d873765dd 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -6,9 +6,6 @@ precision highp int; struct type9 { vec2 member; vec4 gen_gl_Position; - float gen_gl_PointSize; - float gen_gl_ClipDistance[1]; - float gen_gl_CullDistance[1]; }; vec2 v_uv = vec2(0.0, 0.0); @@ -42,12 +39,9 @@ void main() { a_uv1 = a_uv; a_pos1 = a_pos; main2(); - vec2 _e10 = v_uv; - vec4 _e11 = perVertexStruct.gen_gl_Position; - float _e12 = perVertexStruct.gen_gl_PointSize; - float _e13[1] = perVertexStruct.gen_gl_ClipDistance; - float _e14[1] = perVertexStruct.gen_gl_CullDistance; - type9 _tmp_return = type9(_e10, _e11, _e12, _e13, _e14); + vec2 _e7 = v_uv; + vec4 _e8 = perVertexStruct.gen_gl_Position; + type9 _tmp_return = type9(_e7, _e8); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 582fb0dd9..ded5170b7 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -9,9 +9,6 @@ struct gl_PerVertex { struct type9 { linear float2 member : LOC0; float4 gl_Position : SV_Position; - float gl_PointSize : PSIZE; - float gl_ClipDistance[1] : SV_ClipDistance; - float gl_CullDistance[1] : SV_CullDistance; }; static float2 v_uv = (float2)0; @@ -22,9 +19,6 @@ static float2 a_pos1 = (float2)0; struct VertexOutput_main { float2 member : LOC0; float4 gl_Position : SV_Position; - float gl_ClipDistance : SV_ClipDistance; - float gl_CullDistance : SV_CullDistance; - float gl_PointSize : PSIZE; }; void main1() @@ -36,13 +30,10 @@ void main1() return; } -type9 Constructtype9(float2 arg0, float4 arg1, float arg2, float arg3[1], float arg4[1]) { +type9 Constructtype9(float2 arg0, float4 arg1) { type9 ret; ret.member = arg0; ret.gl_Position = arg1; - ret.gl_PointSize = arg2; - ret.gl_ClipDistance = arg3; - ret.gl_CullDistance = arg4; return ret; } @@ -51,12 +42,9 @@ VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0) a_uv1 = a_uv; a_pos1 = a_pos; main1(); - float2 _expr10 = v_uv; - float4 _expr11 = perVertexStruct.gl_Position; - float _expr12 = perVertexStruct.gl_PointSize; - float _expr13[1] = perVertexStruct.gl_ClipDistance; - float _expr14[1] = perVertexStruct.gl_CullDistance; - const type9 type9 = Constructtype9(_expr10, _expr11, _expr12, _expr13, _expr14); - const VertexOutput_main type9_1 = { type9.member, type9.gl_Position, type9.gl_ClipDistance, type9.gl_CullDistance, type9.gl_PointSize }; + float2 _expr7 = v_uv; + float4 _expr8 = perVertexStruct.gl_Position; + const type9 type9 = Constructtype9(_expr7, _expr8); + const VertexOutput_main type9_1 = { type9.member, type9.gl_Position }; return type9_1; } diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index 7efab9a63..88b6181b9 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -14,9 +14,6 @@ struct gl_PerVertex { struct type9 { metal::float2 member; metal::float4 gl_Position; - float gl_PointSize; - type5 gl_ClipDistance; - type5 gl_CullDistance; }; constant metal::float4 const_type3 = {0.0, 0.0, 0.0, 1.0}; constant type5 const_type5 = {0.0}; @@ -42,8 +39,6 @@ struct main1Input { struct main1Output { metal::float2 member [[user(loc0), center_perspective]]; metal::float4 gl_Position [[position]]; - float gl_PointSize [[point_size]]; - float gl_ClipDistance [[clip_distance]] [1]; }; vertex main1Output main1( main1Input varyings [[stage_in]] @@ -57,11 +52,8 @@ vertex main1Output main1( a_uv1 = a_uv; a_pos1 = a_pos; main2(v_uv, a_uv1, perVertexStruct, a_pos1); - metal::float2 _e10 = v_uv; - metal::float4 _e11 = perVertexStruct.gl_Position; - float _e12 = perVertexStruct.gl_PointSize; - type5 _e13 = perVertexStruct.gl_ClipDistance; - type5 _e14 = perVertexStruct.gl_CullDistance; - const auto _tmp = type9 {_e10, _e11, _e12, _e13, _e14}; - return main1Output { _tmp.member, _tmp.gl_Position, _tmp.gl_PointSize, {_tmp.gl_ClipDistance.inner[0]} }; + metal::float2 _e7 = v_uv; + metal::float4 _e8 = perVertexStruct.gl_Position; + const auto _tmp = type9 {_e7, _e8}; + return main1Output { _tmp.member, _tmp.gl_Position }; } diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index 09a9cfdbb..8516563d1 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -26,7 +26,7 @@ fn main([[location(1)]] a_uv: vec2, [[location(0)]] a_pos: vec2) -> Ve a_uv1 = a_uv; a_pos1 = a_pos; main1(); - let e10: vec2 = v_uv; - let e11: vec4 = perVertexStruct.gl_Position; - return VertexOutput(e10, e11); + let e7: vec2 = v_uv; + let e8: vec4 = perVertexStruct.gl_Position; + return VertexOutput(e7, e8); } From c3a0d71f8b7696a355627422966fe47520f597fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 24 Oct 2021 04:20:12 +0100 Subject: [PATCH 1414/2212] [spv-out] Write function arguments names (#1472) --- src/back/spv/writer.rs | 5 ++++ tests/out/spv/access.spvasm | 1 + .../spv/bounds-check-image-restrict.spvasm | 27 +++++++++++++++++++ tests/out/spv/bounds-check-image-rzsw.spvasm | 27 +++++++++++++++++++ tests/out/spv/collatz.spvasm | 1 + tests/out/spv/pointers.spvasm | 3 +++ tests/out/spv/policy-mix.spvasm | 3 +++ tests/out/spv/shadow.spvasm | 2 ++ tests/out/spv/texture-arg.spvasm | 2 ++ 9 files changed, 71 insertions(+) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index dfe088cd6..43ed95c5e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -368,6 +368,11 @@ impl Writer { } else { let argument_id = self.id_gen.next(); let instruction = Instruction::function_parameter(argument_type_id, argument_id); + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = argument.name { + self.debugs.push(Instruction::name(argument_id, name)); + } + } function.parameters.push(FunctionArgument { instruction, handle_id: if handle_ty { diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 3bdea548b..a5864e90e 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -16,6 +16,7 @@ OpMemberName %26 2 "arr" OpMemberName %26 3 "data" OpName %26 "Bar" OpName %30 "bar" +OpName %33 "foo" OpName %34 "read_from_private" OpName %38 "foo" OpName %39 "c" diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index d99451d2f..6a6ae6388 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -22,17 +22,44 @@ OpName %36 "image_storage_1d" OpName %38 "image_storage_2d" OpName %40 "image_storage_2d_array" OpName %42 "image_storage_3d" +OpName %45 "coords" +OpName %46 "level" OpName %47 "test_textureLoad_1d" +OpName %60 "coords" +OpName %61 "level" OpName %62 "test_textureLoad_2d" +OpName %75 "coords" +OpName %76 "index" +OpName %77 "level" OpName %78 "test_textureLoad_2d_array" +OpName %92 "coords" +OpName %93 "level" OpName %94 "test_textureLoad_3d" +OpName %107 "coords" +OpName %108 "sample" OpName %109 "test_textureLoad_multisampled_2d" +OpName %121 "coords" +OpName %122 "level" OpName %123 "test_textureLoad_depth_2d" +OpName %137 "coords" +OpName %138 "index" +OpName %139 "level" OpName %140 "test_textureLoad_depth_2d_array" +OpName %155 "coords" +OpName %156 "sample" OpName %157 "test_textureLoad_depth_multisampled_2d" +OpName %170 "coords" +OpName %171 "value" OpName %172 "test_textureStore_1d" +OpName %180 "coords" +OpName %181 "value" OpName %182 "test_textureStore_2d" +OpName %191 "coords" +OpName %192 "array_index" +OpName %193 "value" OpName %194 "test_textureStore_2d_array" +OpName %204 "coords" +OpName %205 "value" OpName %206 "test_textureStore_3d" OpDecorate %20 DescriptorSet 0 OpDecorate %20 Binding 0 diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index faf74b49c..5716cca40 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -22,17 +22,44 @@ OpName %36 "image_storage_1d" OpName %38 "image_storage_2d" OpName %40 "image_storage_2d_array" OpName %42 "image_storage_3d" +OpName %45 "coords" +OpName %46 "level" OpName %47 "test_textureLoad_1d" +OpName %63 "coords" +OpName %64 "level" OpName %65 "test_textureLoad_2d" +OpName %82 "coords" +OpName %83 "index" +OpName %84 "level" OpName %85 "test_textureLoad_2d_array" +OpName %103 "coords" +OpName %104 "level" OpName %105 "test_textureLoad_3d" +OpName %121 "coords" +OpName %122 "sample" OpName %123 "test_textureLoad_multisampled_2d" +OpName %138 "coords" +OpName %139 "level" OpName %140 "test_textureLoad_depth_2d" +OpName %157 "coords" +OpName %158 "index" +OpName %159 "level" OpName %160 "test_textureLoad_depth_2d_array" +OpName %178 "coords" +OpName %179 "sample" OpName %180 "test_textureLoad_depth_multisampled_2d" +OpName %196 "coords" +OpName %197 "value" OpName %198 "test_textureStore_1d" +OpName %207 "coords" +OpName %208 "value" OpName %209 "test_textureStore_2d" +OpName %219 "coords" +OpName %220 "array_index" +OpName %221 "value" OpName %222 "test_textureStore_2d_array" +OpName %233 "coords" +OpName %234 "value" OpName %235 "test_textureStore_3d" OpDecorate %20 DescriptorSet 0 OpDecorate %20 Binding 0 diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index 5ac6c3d3f..fd2065bb5 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -14,6 +14,7 @@ OpName %9 "PrimeIndices" OpName %11 "v_indices" OpName %13 "n" OpName %15 "i" +OpName %17 "n_base" OpName %18 "collatz_iterations" OpName %45 "global_id" OpName %48 "main" diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index d6e2bcf2b..b14aab93c 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -11,6 +11,9 @@ OpMemberName %8 0 "array" OpName %8 "DynamicArray" OpName %10 "v" OpName %13 "f" +OpName %20 "p" +OpName %21 "i" +OpName %22 "v" OpName %23 "index_dynamic_array" OpDecorate %7 ArrayStride 4 OpDecorate %8 Block diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index 5d81184d3..1e34e65e6 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -19,6 +19,9 @@ OpName %27 "image_2d_array" OpName %29 "in_workgroup" OpName %31 "in_private" OpName %33 "in_function" +OpName %36 "c" +OpName %37 "i" +OpName %38 "l" OpName %39 "mock_function" OpDecorate %14 ArrayStride 16 OpDecorate %15 Block diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index e8532e88c..a0554ed94 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -23,6 +23,8 @@ OpName %25 "u_globals" OpName %27 "s_lights" OpName %29 "t_shadow" OpName %31 "sampler_shadow" +OpName %34 "light_id" +OpName %35 "homogeneous_coords" OpName %36 "fetch_shadow" OpName %64 "color" OpName %66 "i" diff --git a/tests/out/spv/texture-arg.spvasm b/tests/out/spv/texture-arg.spvasm index 12fd6965c..eca3f80c6 100644 --- a/tests/out/spv/texture-arg.spvasm +++ b/tests/out/spv/texture-arg.spvasm @@ -10,6 +10,8 @@ OpExecutionMode %28 OriginUpperLeft OpSource GLSL 450 OpName %9 "Texture" OpName %11 "Sampler" +OpName %14 "Passed_Texture" +OpName %16 "Passed_Sampler" OpName %18 "test" OpName %28 "main" OpDecorate %9 DescriptorSet 0 From 044fc1b742d12069e720a4d8acf2b24035a136c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 24 Oct 2021 04:22:31 +0100 Subject: [PATCH 1415/2212] [spv-in] Cast int comparisons arguments (#1471) Operations like `OpUGreaterThan` accept arguments as long as they are integers (signedness doesn't matter) but they must be interpreted as `Uint`s. --- src/front/spv/mod.rs | 132 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 110 insertions(+), 22 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 8dbaba383..9ee0397f1 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -925,6 +925,81 @@ impl> Parser { Ok(()) } + /// A version of the binary op where one or both of the arguments might need to be casted to a + /// specific integer kind (unsigned or signed), used for operations like OpINotEqual or + /// OpUGreaterThan. + #[allow(clippy::too_many_arguments)] + fn parse_expr_int_comparison( + &mut self, + ctx: &mut BlockContext, + emitter: &mut super::Emitter, + block: &mut crate::Block, + block_id: spirv::Word, + body_idx: usize, + op: crate::BinaryOperator, + kind: crate::ScalarKind, + ) -> Result<(), Error> { + let start = self.data_offset; + let result_type_id = self.next()?; + let result_id = self.next()?; + let p1_id = self.next()?; + let p2_id = self.next()?; + let span = self.span_from_with_op(start); + + let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); + let p1_lookup_ty = self.lookup_type.lookup(p1_lexp.type_id)?; + let p1_kind = ctx.type_arena[p1_lookup_ty.handle] + .inner + .scalar_kind() + .unwrap(); + let p2_lexp = self.lookup_expression.lookup(p2_id)?; + let right = self.get_expr_handle(p2_id, p2_lexp, ctx, emitter, block, body_idx); + let p2_lookup_ty = self.lookup_type.lookup(p2_lexp.type_id)?; + let p2_kind = ctx.type_arena[p2_lookup_ty.handle] + .inner + .scalar_kind() + .unwrap(); + + let expr = crate::Expression::Binary { + op, + left: if p1_kind == kind { + left + } else { + ctx.expressions.append( + crate::Expression::As { + expr: left, + kind, + convert: None, + }, + span, + ) + }, + right: if p2_kind == kind { + right + } else { + ctx.expressions.append( + crate::Expression::As { + expr: right, + kind, + convert: None, + }, + span, + ) + }, + }; + + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: ctx.expressions.append(expr, span), + type_id: result_type_id, + block_id, + }, + ); + Ok(()) + } + fn parse_expr_shift_op( &mut self, ctx: &mut BlockContext, @@ -1110,16 +1185,6 @@ impl> Parser { self.parse_expr_binary_op(ctx, &mut emitter, &mut block, block_id, body_idx, $op) }; - ($op:expr, BINARY_SIGN_ADJUSTED) => { - self.parse_expr_binary_op_sign_adjusted( - ctx, - &mut emitter, - &mut block, - block_id, - body_idx, - $op, - ) - }; ($op:expr, SHIFT) => { self.parse_expr_shift_op(ctx, &mut emitter, &mut block, block_id, body_idx, $op) }; @@ -1777,18 +1842,22 @@ impl> Parser { inst.expect(4)?; parse_expr_op!(crate::UnaryOperator::Negate, UNARY)?; } - Op::IAdd => { + Op::IAdd | Op::ISub => { inst.expect(5)?; - parse_expr_op!(crate::BinaryOperator::Add, BINARY_SIGN_ADJUSTED)?; + let operator = map_binary_operator(inst.op)?; + self.parse_expr_binary_op_sign_adjusted( + ctx, + &mut emitter, + &mut block, + block_id, + body_idx, + operator, + )?; } Op::FAdd => { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Add, BINARY)?; } - Op::ISub => { - inst.expect(5)?; - parse_expr_op!(crate::BinaryOperator::Subtract, BINARY_SIGN_ADJUSTED)?; - } Op::FSub => { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Subtract, BINARY)?; @@ -2586,15 +2655,34 @@ impl> Parser { } Op::IEqual | Op::INotEqual - | Op::UGreaterThan | Op::SGreaterThan - | Op::UGreaterThanEqual | Op::SGreaterThanEqual - | Op::ULessThan | Op::SLessThan - | Op::ULessThanEqual - | Op::SLessThanEqual - | Op::FOrdEqual + | Op::SLessThanEqual => { + inst.expect(5)?; + self.parse_expr_int_comparison( + ctx, + &mut emitter, + &mut block, + block_id, + body_idx, + map_binary_operator(inst.op)?, + crate::ScalarKind::Sint, + )?; + } + Op::UGreaterThan | Op::UGreaterThanEqual | Op::ULessThan | Op::ULessThanEqual => { + inst.expect(5)?; + self.parse_expr_int_comparison( + ctx, + &mut emitter, + &mut block, + block_id, + body_idx, + map_binary_operator(inst.op)?, + crate::ScalarKind::Uint, + )?; + } + Op::FOrdEqual | Op::FUnordEqual | Op::FOrdNotEqual | Op::FUnordNotEqual From a03f23c1326b6bd89994b1a554fc520b70f98741 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 23 Oct 2021 23:25:25 -0400 Subject: [PATCH 1416/2212] Allow new clippy::if_same_then_else --- src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib.rs b/src/lib.rs index 036b197a1..2e9f60831 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -193,6 +193,7 @@ tree. clippy::unneeded_field_pattern, clippy::match_like_matches_macro, clippy::manual_strip, + clippy::if_same_then_else, clippy::unknown_clippy_lints, )] #![warn( From fd5085277a942b8497aad08d75c82dde7c6021ce Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 23 Oct 2021 23:31:30 -0400 Subject: [PATCH 1417/2212] Switch the constant in bevy-pbr to avoid display incosistencies --- tests/in/glsl/bevy-pbr.frag | 4 ++-- tests/out/wgsl/bevy-pbr-frag.wgsl | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/in/glsl/bevy-pbr.frag b/tests/in/glsl/bevy-pbr.frag index 1c65f9e96..976ff91f8 100644 --- a/tests/in/glsl/bevy-pbr.frag +++ b/tests/in/glsl/bevy-pbr.frag @@ -115,7 +115,7 @@ float getDistanceAttenuation(float distanceSquare, float inverseRangeSquared) { float factor = distanceSquare * inverseRangeSquared; float smoothFactor = saturate(1.0 - factor * factor); float attenuation = smoothFactor * smoothFactor; - return attenuation * 1.0 / max(distanceSquare, 1e-4); + return attenuation * 1.0 / max(distanceSquare, 1e-3); } // Normal distribution function (specular D) @@ -353,7 +353,7 @@ void main() { emissive.rgb *= texture(sampler2D(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler), v_Uv).rgb; vec3 V = normalize(CameraPos.xyz - v_WorldPosition.xyz); // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886" - float NdotV = max(dot(N, V), 1e-4); + float NdotV = max(dot(N, V), 1e-3); // Remapping [0,1] reflectance to F0 // See https://google.github.io/filament/Filament.html#materialsystem/parameterization/remapping diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index f775281be..cecda28ad 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -135,7 +135,7 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 attenuation = (e64 * e65); let e68: f32 = attenuation; let e73: f32 = distanceSquare1; - return ((e68 * 1.0) / max(e73, 0.00009999999747378752)); + return ((e68 * 1.0) / max(e73, 0.0010000000474974513)); } fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { @@ -791,7 +791,7 @@ fn main1() { let e175: vec3 = V3; let e180: vec3 = N2; let e181: vec3 = V3; - NdotV4 = max(dot(e180, e181), 0.00009999999747378752); + NdotV4 = max(dot(e180, e181), 0.0010000000474974513); let e187: f32 = global6.reflectance; let e189: f32 = global6.reflectance; let e192: f32 = metallic; From ec001c3eadd4cd7d09b11cb2e88b90b9a4f9bea5 Mon Sep 17 00:00:00 2001 From: Alex Es Date: Mon, 25 Oct 2021 05:47:03 +0300 Subject: [PATCH 1418/2212] Use span information in analyzer errors (proof of concept) (#1470) * Proof-of-concept for adding spans to validation errors. Still missing: actually printing the damn stuff. * Emit errors from analyzer in the CLI. TODO: tests, I guess! * Simplification refactoring: avoid avoiding allocations so vehemently. * Mask helper traits with `as _`. * Fix block iterator throwing up when span feature is disabled. * Nest use statements. * Add basic docs. * Axe AddSpanResult. --- cli/src/main.rs | 65 +++++++++---- src/arena.rs | 10 ++ src/block.rs | 8 ++ src/lib.rs | 2 +- src/span.rs | 203 ++++++++++++++++++++++++++++++++++++++++- src/valid/analyzer.rs | 51 ++++++++--- src/valid/function.rs | 201 ++++++++++++++++++++++++++++------------ src/valid/interface.rs | 48 ++++++---- src/valid/mod.rs | 77 ++++++++++------ tests/wgsl-errors.rs | 1 + 10 files changed, 528 insertions(+), 138 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index abb00aaa7..4330d882d 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -231,7 +231,7 @@ fn run() -> Result<(), Box> { } params.keep_coordinate_space = args.keep_coordinate_space; - let module = match Path::new(&input_path) + let (module, input_text) = match Path::new(&input_path) .extension() .ok_or(CliError("Input filename has no extension"))? .to_str() @@ -246,13 +246,13 @@ fn run() -> Result<(), Box> { .map(std::path::PathBuf::from), }; let input = fs::read(input_path)?; - naga::front::spv::parse_u8_slice(&input, &options)? + naga::front::spv::parse_u8_slice(&input, &options).map(|m| (m, None))? } "wgsl" => { let input = fs::read_to_string(input_path)?; let result = naga::front::wgsl::parse_str(&input); match result { - Ok(v) => v, + Ok(v) => (v, Some(input)), Err(ref e) => { e.emit_to_stderr(&input); return Err(CliError("Could not parse WGSL").into()); @@ -263,24 +263,27 @@ fn run() -> Result<(), Box> { let input = fs::read_to_string(input_path)?; let mut parser = naga::front::glsl::Parser::default(); - parser - .parse( - &naga::front::glsl::Options { - stage: match ext { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - _ => unreachable!(), + ( + parser + .parse( + &naga::front::glsl::Options { + stage: match ext { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + _ => unreachable!(), + }, + defines: Default::default(), }, - defines: Default::default(), - }, - &input, - ) - .unwrap_or_else(|errors| { - let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); - emit_glsl_parser_error(errors, filename.unwrap_or("glsl"), &input); - std::process::exit(1); - }) + &input, + ) + .unwrap_or_else(|errors| { + let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); + emit_glsl_parser_error(errors, filename.unwrap_or("glsl"), &input); + std::process::exit(1); + }), + Some(input), + ) } _ => return Err(CliError("Unknown input file extension").into()), }; @@ -294,6 +297,10 @@ fn run() -> Result<(), Box> { { Ok(info) => Some(info), Err(error) => { + if let Some(input) = input_text { + let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); + emit_annotated_error(&error, filename.unwrap_or("input"), &input); + } print_err(&error); None } @@ -468,6 +475,7 @@ use codespan_reporting::{ termcolor::{ColorChoice, StandardStream}, }, }; +use naga::WithSpan; pub fn emit_glsl_parser_error(errors: Vec, filename: &str, source: &str) { let files = SimpleFile::new(filename, source); @@ -484,3 +492,20 @@ pub fn emit_glsl_parser_error(errors: Vec, filename: & term::emit(&mut writer.lock(), &config, &files, &diagnostic).expect("cannot write error"); } } + +pub fn emit_annotated_error(ann_err: &WithSpan, filename: &str, source: &str) { + let files = SimpleFile::new(filename, source); + let config = codespan_reporting::term::Config::default(); + let writer = StandardStream::stderr(ColorChoice::Auto); + + let diagnostic = Diagnostic::error().with_labels( + ann_err + .spans() + .map(|(span, desc)| { + Label::primary((), span.to_range().unwrap()).with_message(desc.to_owned()) + }) + .collect(), + ); + + term::emit(&mut writer.lock(), &config, &files, &diagnostic).expect("cannot write error"); +} diff --git a/src/arena.rs b/src/arena.rs index 536a4bd28..4884010d3 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -31,28 +31,35 @@ impl Clone for Handle { } } } + impl Copy for Handle {} + impl PartialEq for Handle { fn eq(&self, other: &Self) -> bool { self.index == other.index } } + impl Eq for Handle {} + impl PartialOrd for Handle { fn partial_cmp(&self, other: &Self) -> Option { self.index.partial_cmp(&other.index) } } + impl Ord for Handle { fn cmp(&self, other: &Self) -> Ordering { self.index.cmp(&other.index) } } + impl fmt::Debug for Handle { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "[{}]", self.index) } } + impl hash::Hash for Handle { fn hash(&self, hasher: &mut H) { self.index.hash(hasher) @@ -117,11 +124,13 @@ impl Clone for Range { } } } + impl fmt::Debug for Range { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "[{}..{}]", self.inner.start + 1, self.inner.end) } } + impl Iterator for Range { type Item = Handle; fn next(&mut self) -> Option { @@ -159,6 +168,7 @@ impl Default for Arena { Self::new() } } + impl fmt::Debug for Arena { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_map().entries(self.iter()).finish() diff --git a/src/block.rs b/src/block.rs index 1a35e4394..6a31301e1 100644 --- a/src/block.rs +++ b/src/block.rs @@ -78,6 +78,14 @@ impl Block { .splice(range.clone(), other.span_info.into_iter()); self.body.splice(range, other.body.into_iter()); } + pub fn span_iter(&self) -> impl Iterator { + #[cfg(feature = "span")] + let span_iter = self.span_info.iter(); + #[cfg(not(feature = "span"))] + let span_iter = std::iter::repeat_with(|| &Span::UNDEFINED); + + self.body.iter().zip(span_iter) + } pub fn span_iter_mut(&mut self) -> impl Iterator)> { #[cfg(feature = "span")] diff --git a/src/lib.rs b/src/lib.rs index 2e9f60831..99b77b267 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -220,7 +220,7 @@ use std::{ hash::BuildHasherDefault, }; -pub use crate::span::Span; +pub use crate::span::{Span, SpanContext, WithSpan}; #[cfg(feature = "deserialize")] use serde::Deserialize; #[cfg(feature = "serialize")] diff --git a/src/span.rs b/src/span.rs index 3eaadd212..dabcabdb0 100644 --- a/src/span.rs +++ b/src/span.rs @@ -1,4 +1,5 @@ -use std::ops::Range; +use crate::{Arena, Handle, UniqueArena}; +use std::{error::Error, fmt, ops::Range}; /// A source code span, used for error reporting. #[derive(Clone, Copy, Debug, PartialEq, Default)] @@ -8,6 +9,7 @@ pub struct Span { } impl Span { + pub const UNDEFINED: Self = Self { start: 0, end: 0 }; /// Creates a new `Span` from a range of byte indices /// /// Note: end is exclusive, it doesn't belong to the `Span` @@ -66,3 +68,202 @@ impl From> for Span { } } } + +/// A source code span together with "context", a user-readable description of what part of the error it refers to. +pub type SpanContext = (Span, String); + +/// Wrapper class for [`Error`], augmenting it with a list of [`SpanContext`]s. +#[derive(Debug)] +pub struct WithSpan { + inner: E, + #[cfg(feature = "span")] + spans: Vec, +} + +impl fmt::Display for WithSpan +where + E: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { + self.inner.fmt(f) + } +} + +#[cfg(test)] +impl PartialEq for WithSpan +where + E: PartialEq, +{ + fn eq(&self, other: &Self) -> bool { + self.inner.eq(&other.inner) + } +} + +impl Error for WithSpan +where + E: Error, +{ + fn source(&self) -> Option<&(dyn Error + 'static)> { + self.inner.source() + } +} + +impl WithSpan { + /// Create a new [`WithSpan`] from an [`Error`], containing no spans. + pub fn new(inner: E) -> Self { + Self { + inner, + #[cfg(feature = "span")] + spans: Vec::new(), + } + } + + /// Reverse of [`Self::new`], discards span information and returns an inner error. + pub fn into_inner(self) -> E { + self.inner + } + + /// Iterator over stored [`SpanContext`]s. + pub fn spans(&self) -> impl Iterator { + #[cfg(feature = "span")] + return self.spans.iter(); + #[cfg(not(feature = "span"))] + return std::iter::empty(); + } + + /// Add a new span with description. + #[cfg_attr(not(feature = "span"), allow(unused_variables, unused_mut))] + pub fn with_span(mut self, span: Span, description: S) -> Self + where + S: ToString, + { + #[cfg(feature = "span")] + if span.is_defined() { + self.spans.push((span, description.to_string())); + } + self + } + + /// Add a [`SpanContext`]. + pub fn with_context(self, span_context: SpanContext) -> Self { + let (span, description) = span_context; + self.with_span(span, description) + } + + /// Add a [`Handle`] from either [`Arena`] or [`UniqueArena`], borrowing its span information from there + /// and annotating with a type and the handle representation. + pub(crate) fn with_handle>(self, handle: Handle, arena: &A) -> Self { + self.with_context(arena.get_span_context(handle)) + } + + /// Convert inner error using [`From`]. + pub fn into_other(self) -> WithSpan + where + E2: From, + { + WithSpan { + inner: self.inner.into(), + #[cfg(feature = "span")] + spans: self.spans, + } + } + + /// Convert inner error into another type. Joins span information contained in `self` + /// with what is returned from `func`. + pub fn and_then(self, func: F) -> WithSpan + where + F: FnOnce(E) -> WithSpan, + { + #[cfg_attr(not(feature = "span"), allow(unused_mut))] + let mut res = func(self.inner); + #[cfg(feature = "span")] + res.spans.extend(self.spans); + res + } +} + +/// Convenience trait for [`Error`] to be able to apply spans to anything. +pub(crate) trait AddSpan: Sized { + type Output; + /// See [`WithSpan::new`]. + fn with_span(self) -> Self::Output; + /// See [`WithSpan::with_span`]. + fn with_span_static(self, span: Span, description: &'static str) -> Self::Output; + /// See [`WithSpan::with_context`]. + fn with_span_context(self, span_context: SpanContext) -> Self::Output; + /// See [`WithSpan::with_handle`]. + fn with_span_handle>(self, handle: Handle, arena: &A) -> Self::Output; +} + +/// Trait abstracting over getting a span from an [`Arena`] or a [`UniqueArena`]. +pub(crate) trait SpanProvider { + fn get_span(&self, handle: Handle) -> Span; + fn get_span_context(&self, handle: Handle) -> SpanContext { + match self.get_span(handle) { + x if !x.is_defined() => (Default::default(), "".to_string()), + known => ( + known, + format!("{} {:?}", std::any::type_name::(), handle), + ), + } + } +} + +impl SpanProvider for Arena { + fn get_span(&self, handle: Handle) -> Span { + self.get_span(handle) + } +} + +impl SpanProvider for UniqueArena { + fn get_span(&self, handle: Handle) -> Span { + self.get_span(handle) + } +} + +impl AddSpan for E +where + E: Error, +{ + type Output = WithSpan; + fn with_span(self) -> WithSpan { + WithSpan::new(self) + } + + fn with_span_static(self, span: Span, description: &'static str) -> WithSpan { + WithSpan::new(self).with_span(span, description) + } + + fn with_span_context(self, span_context: SpanContext) -> WithSpan { + WithSpan::new(self).with_context(span_context) + } + + fn with_span_handle>( + self, + handle: Handle, + arena: &A, + ) -> WithSpan { + WithSpan::new(self).with_handle(handle, arena) + } +} + +/// Convenience trait for [`Result`], adding a [`MapErrWithSpan::map_err_inner`] +/// mapping to [`WithSpan::and_then`]. +pub trait MapErrWithSpan: Sized { + type Output: Sized; + fn map_err_inner(self, func: F) -> Self::Output + where + F: FnOnce(E) -> WithSpan, + E2: From; +} + +impl MapErrWithSpan for Result> { + type Output = Result>; + fn map_err_inner(self, func: F) -> Result> + where + F: FnOnce(E) -> WithSpan, + E2: From, + { + self.map_err(|e| e.and_then(func).into_other::()) + } +} diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index d6e2452ad..051bf4ca8 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -7,6 +7,7 @@ Figures out the following properties: !*/ use super::{CallError, ExpressionError, FunctionError, ModuleInfo, ShaderStages, ValidationFlags}; +use crate::span::{AddSpan as _, WithSpan}; use crate::{ arena::{Arena, Handle}, proc::{ResolveContext, TypeResolution}, @@ -307,7 +308,7 @@ impl FunctionInfo { info: &Self, arguments: &[Handle], expression_arena: &Arena, - ) -> Result { + ) -> Result> { for key in info.sampling_set.iter() { self.sampling_set.insert(key.clone()); } @@ -318,7 +319,10 @@ impl FunctionInfo { let handle = arguments[i as usize]; expression_arena[handle] .to_global_or_argument() - .map_err(|error| FunctionError::Expression { handle, error })? + .map_err(|error| { + FunctionError::Expression { handle, error } + .with_span_handle(handle, expression_arena) + })? } }; @@ -328,7 +332,10 @@ impl FunctionInfo { let handle = arguments[i as usize]; expression_arena[handle] .to_global_or_argument() - .map_err(|error| FunctionError::Expression { handle, error })? + .map_err(|error| { + FunctionError::Expression { handle, error } + .with_span_handle(handle, expression_arena) + })? } }; @@ -608,15 +615,15 @@ impl FunctionInfo { #[allow(clippy::or_fun_call)] fn process_block( &mut self, - statements: &[crate::Statement], + statements: &crate::Block, other_functions: &[FunctionInfo], mut disruptor: Option, expression_arena: &Arena, - ) -> Result { + ) -> Result> { use crate::Statement as S; let mut combined_uniformity = FunctionUniformity::new(); - for statement in statements { + for (statement, &span) in statements.span_iter() { let uniformity = match *statement { S::Emit(ref range) => { let mut requirements = UniformityRequirements::empty(); @@ -629,7 +636,8 @@ impl FunctionInfo { && !req.is_empty() { if let Some(cause) = disruptor { - return Err(FunctionError::NonUniformControlFlow(req, expr, cause)); + return Err(FunctionError::NonUniformControlFlow(req, expr, cause) + .with_span_handle(expr, expression_arena)); } } requirements |= req; @@ -776,7 +784,8 @@ impl FunctionInfo { FunctionError::InvalidCall { function, error: CallError::ForwardDeclaredFunction, - }, + } + .with_span_static(span, "forward call"), )?; //Note: the result is validated by the Validator, not here self.process_call(info, arguments, expression_arena)? @@ -811,7 +820,7 @@ impl ModuleInfo { fun: &crate::Function, module: &crate::Module, flags: ValidationFlags, - ) -> Result { + ) -> Result> { let mut info = FunctionInfo { flags, available_stages: ShaderStages::all(), @@ -839,7 +848,8 @@ impl ModuleInfo { &self.functions, &resolve_context, ) { - return Err(FunctionError::Expression { handle, error }); + return Err(FunctionError::Expression { handle, error } + .with_span_handle(handle, &fun.expressions)); } } @@ -979,7 +989,12 @@ fn uniform_control_flow() { .into(), }; assert_eq!( - info.process_block(&[stmt_emit1, stmt_if_uniform], &[], None, &expressions), + info.process_block( + &vec![stmt_emit1, stmt_if_uniform].into(), + &[], + None, + &expressions + ), Ok(FunctionUniformity { result: Uniformity { non_uniform_result: None, @@ -1005,12 +1020,18 @@ fn uniform_control_flow() { reject: crate::Block::new(), }; assert_eq!( - info.process_block(&[stmt_emit2, stmt_if_non_uniform], &[], None, &expressions), + info.process_block( + &vec![stmt_emit2, stmt_if_non_uniform].into(), + &[], + None, + &expressions + ), Err(FunctionError::NonUniformControlFlow( UniformityRequirements::DERIVATIVE, derivative_expr, UniformityDisruptor::Expression(non_uniform_global_expr) - )), + ) + .with_span()), ); assert_eq!(info[derivative_expr].ref_count, 1); assert_eq!(info[non_uniform_global], GlobalUse::READ); @@ -1021,7 +1042,7 @@ fn uniform_control_flow() { }; assert_eq!( info.process_block( - &[stmt_emit3, stmt_return_non_uniform], + &vec![stmt_emit3, stmt_return_non_uniform].into(), &[], Some(UniformityDisruptor::Return), &expressions @@ -1048,7 +1069,7 @@ fn uniform_control_flow() { let stmt_kill = S::Kill; assert_eq!( info.process_block( - &[stmt_emit4, stmt_assign, stmt_kill, stmt_return_pointer], + &vec![stmt_emit4, stmt_assign, stmt_kill, stmt_return_pointer].into(), &[], Some(UniformityDisruptor::Discard), &expressions diff --git a/src/valid/function.rs b/src/valid/function.rs index 4ee4a08bc..0df8e2f56 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -6,6 +6,7 @@ use super::{ analyzer::{UniformityDisruptor, UniformityRequirements}, ExpressionError, FunctionInfo, ModuleInfo, }; +use crate::span::{AddSpan as _, MapErrWithSpan as _, WithSpan}; #[cfg(feature = "validate")] use bit_set::BitSet; @@ -201,11 +202,11 @@ impl<'a> BlockContext<'a> { &self, handle: Handle, valid_expressions: &BitSet, - ) -> Result<&crate::TypeInner, ExpressionError> { + ) -> Result<&crate::TypeInner, WithSpan> { if handle.index() >= self.expressions.len() { - Err(ExpressionError::DoesntExist) + Err(ExpressionError::DoesntExist.with_span()) } else if !valid_expressions.contains(handle.index()) { - Err(ExpressionError::NotInScope) + Err(ExpressionError::NotInScope.with_span_handle(handle, self.expressions)) } else { Ok(self.info[handle].ty.inner_with(self.types)) } @@ -215,9 +216,9 @@ impl<'a> BlockContext<'a> { &self, handle: Handle, valid_expressions: &BitSet, - ) -> Result<&crate::TypeInner, FunctionError> { + ) -> Result<&crate::TypeInner, WithSpan> { self.resolve_type_impl(handle, valid_expressions) - .map_err(|error| FunctionError::Expression { handle, error }) + .map_err_inner(|error| FunctionError::Expression { handle, error }.with_span()) } fn resolve_pointer_type( @@ -243,28 +244,33 @@ impl super::Validator { arguments: &[Handle], result: Option>, context: &BlockContext, - ) -> Result { + ) -> Result> { let fun = context .functions .try_get(function) - .ok_or(CallError::InvalidFunction)?; + .ok_or(CallError::InvalidFunction) + .map_err(WithSpan::new)?; if fun.arguments.len() != arguments.len() { return Err(CallError::ArgumentCount { required: fun.arguments.len(), seen: arguments.len(), - }); + } + .with_span()); } for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { let ty = context .resolve_type_impl(expr, &self.valid_expression_set) - .map_err(|error| CallError::Argument { index, error })?; + .map_err_inner(|error| { + CallError::Argument { index, error }.with_span_handle(expr, context.expressions) + })?; let arg_inner = &context.types[arg.ty].inner; if !ty.equivalent(arg_inner, context.types) { return Err(CallError::ArgumentType { index, required: arg.ty, seen_expression: expr, - }); + } + .with_span_handle(expr, context.expressions)); } } @@ -272,15 +278,19 @@ impl super::Validator { if self.valid_expression_set.insert(expr.index()) { self.valid_expression_list.push(expr); } else { - return Err(CallError::ResultAlreadyInScope(expr)); + return Err(CallError::ResultAlreadyInScope(expr) + .with_span_handle(expr, context.expressions)); } match context.expressions[expr] { crate::Expression::CallResult(callee) if fun.result.is_some() && callee == function => {} - _ => return Err(CallError::ExpressionMismatch(result)), + _ => { + return Err(CallError::ExpressionMismatch(result) + .with_span_handle(expr, context.expressions)) + } } } else if fun.result.is_some() { - return Err(CallError::ExpressionMismatch(result)); + return Err(CallError::ExpressionMismatch(result).with_span()); } let callee_info = &context.prev_infos[function.index()]; @@ -295,19 +305,23 @@ impl super::Validator { value: Handle, result: Handle, context: &BlockContext, - ) -> Result<(), FunctionError> { + ) -> Result<(), WithSpan> { let pointer_inner = context.resolve_type(pointer, &self.valid_expression_set)?; let (ptr_kind, ptr_width) = match *pointer_inner { crate::TypeInner::Pointer { base, .. } => match context.types[base].inner { crate::TypeInner::Atomic { kind, width } => (kind, width), ref other => { log::error!("Atomic pointer to type {:?}", other); - return Err(AtomicError::InvalidPointer(pointer).into()); + return Err(AtomicError::InvalidPointer(pointer) + .with_span_handle(pointer, context.expressions) + .into_other()); } }, ref other => { log::error!("Atomic on type {:?}", other); - return Err(AtomicError::InvalidPointer(pointer).into()); + return Err(AtomicError::InvalidPointer(pointer) + .with_span_handle(pointer, context.expressions) + .into_other()); } }; @@ -316,21 +330,27 @@ impl super::Validator { crate::TypeInner::Scalar { width, kind } if kind == ptr_kind && width == ptr_width => {} ref other => { log::error!("Atomic operand type {:?}", other); - return Err(AtomicError::InvalidOperand(value).into()); + return Err(AtomicError::InvalidOperand(value) + .with_span_handle(value, context.expressions) + .into_other()); } } if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun { if context.resolve_type(cmp, &self.valid_expression_set)? != value_inner { log::error!("Atomic exchange comparison has a different type from the value"); - return Err(AtomicError::InvalidOperand(cmp).into()); + return Err(AtomicError::InvalidOperand(cmp) + .with_span_handle(cmp, context.expressions) + .into_other()); } } if self.valid_expression_set.insert(result.index()) { self.valid_expression_list.push(result); } else { - return Err(AtomicError::ResultAlreadyInScope(result).into()); + return Err(AtomicError::ResultAlreadyInScope(result) + .with_span_handle(result, context.expressions) + .into_other()); } match context.expressions[result] { //TODO: support atomic result with comparison @@ -339,7 +359,11 @@ impl super::Validator { width, comparison: false, } if kind == ptr_kind && width == ptr_width => {} - _ => return Err(AtomicError::ResultTypeMismatch(result).into()), + _ => { + return Err(AtomicError::ResultTypeMismatch(result) + .with_span_handle(result, context.expressions) + .into_other()) + } } Ok(()) } @@ -347,15 +371,16 @@ impl super::Validator { #[cfg(feature = "validate")] fn validate_block_impl( &mut self, - statements: &[crate::Statement], + statements: &crate::Block, context: &BlockContext, - ) -> Result { + ) -> Result> { use crate::{Statement as S, TypeInner as Ti}; let mut finished = false; let mut stages = super::ShaderStages::all(); - for statement in statements { + for (statement, &span) in statements.span_iter() { if finished { - return Err(FunctionError::InstructionsAfterReturn); + return Err(FunctionError::InstructionsAfterReturn + .with_span_static(span, "instructions after return")); } match *statement { S::Emit(ref range) => { @@ -363,7 +388,8 @@ impl super::Validator { if self.valid_expression_set.insert(handle.index()) { self.valid_expression_list.push(handle); } else { - return Err(FunctionError::ExpressionAlreadyInScope(handle)); + return Err(FunctionError::ExpressionAlreadyInScope(handle) + .with_span_handle(handle, context.expressions)); } } } @@ -382,7 +408,10 @@ impl super::Validator { kind: crate::ScalarKind::Bool, width: _, } => {} - _ => return Err(FunctionError::InvalidIfType(condition)), + _ => { + return Err(FunctionError::InvalidIfType(condition) + .with_span_handle(condition, context.expressions)) + } } stages &= self.validate_block(accept, context)?.stages; stages &= self.validate_block(reject, context)?.stages; @@ -401,12 +430,22 @@ impl super::Validator { kind: crate::ScalarKind::Sint, width: _, } => {} - _ => return Err(FunctionError::InvalidSwitchType(selector)), + _ => { + return Err(FunctionError::InvalidSwitchType(selector) + .with_span_handle(selector, context.expressions)) + } } self.select_cases.clear(); for case in cases { if !self.select_cases.insert(case.value) { - return Err(FunctionError::ConflictingSwitchCase(case.value)); + return Err(FunctionError::ConflictingSwitchCase(case.value) + .with_span_static( + case.body + .span_iter() + .next() + .map_or(Default::default(), |(_, s)| *s), + "conflicting switch arm here", + )); } } let pass_through_abilities = context.abilities @@ -448,19 +487,22 @@ impl super::Validator { } S::Break => { if !context.abilities.contains(ControlFlowAbility::BREAK) { - return Err(FunctionError::BreakOutsideOfLoopOrSwitch); + return Err(FunctionError::BreakOutsideOfLoopOrSwitch + .with_span_static(span, "invalid break")); } finished = true; } S::Continue => { if !context.abilities.contains(ControlFlowAbility::CONTINUE) { - return Err(FunctionError::ContinueOutsideOfLoop); + return Err(FunctionError::ContinueOutsideOfLoop + .with_span_static(span, "invalid continue")); } finished = true; } S::Return { value } => { if !context.abilities.contains(ControlFlowAbility::RETURN) { - return Err(FunctionError::InvalidReturnSpot); + return Err(FunctionError::InvalidReturnSpot + .with_span_static(span, "invalid return")); } let value_ty = value .map(|expr| context.resolve_type(expr, &self.valid_expression_set)) @@ -482,7 +524,13 @@ impl super::Validator { value_ty, expected_ty ); - return Err(FunctionError::InvalidReturnType(value)); + if let Some(handle) = value { + return Err(FunctionError::InvalidReturnType(value) + .with_span_handle(handle, context.expressions)); + } else { + return Err(FunctionError::InvalidReturnType(value) + .with_span_static(span, "invalid return")); + } } finished = true; } @@ -495,25 +543,34 @@ impl super::Validator { S::Store { pointer, value } => { let mut current = pointer; loop { - let _ = context.resolve_pointer_type(current)?; - match *context.get_expression(current)? { + let _ = context + .resolve_pointer_type(current) + .map_err(|e| e.with_span())?; + match context.expressions[current] { crate::Expression::Access { base, .. } | crate::Expression::AccessIndex { base, .. } => current = base, crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) | crate::Expression::FunctionArgument(_) => break, - _ => return Err(FunctionError::InvalidStorePointer(current)), + _ => { + return Err(FunctionError::InvalidStorePointer(current) + .with_span_handle(pointer, context.expressions)) + } } } let value_ty = context.resolve_type(value, &self.valid_expression_set)?; match *value_ty { Ti::Image { .. } | Ti::Sampler { .. } => { - return Err(FunctionError::InvalidStoreValue(value)); + return Err(FunctionError::InvalidStoreValue(value) + .with_span_handle(value, context.expressions)); } _ => {} } - let good = match *context.resolve_pointer_type(pointer)? { + let good = match *context + .resolve_pointer_type(pointer) + .map_err(|e| e.with_span())? + { Ti::Pointer { base, class: _ } => match context.types[base].inner { Ti::Atomic { kind, width } => *value_ty == Ti::Scalar { kind, width }, ref other => value_ty == other, @@ -533,7 +590,10 @@ impl super::Validator { _ => false, }; if !good { - return Err(FunctionError::InvalidStoreTypes { pointer, value }); + return Err(FunctionError::InvalidStoreTypes { pointer, value } + .with_span() + .with_handle(pointer, context.expressions) + .with_handle(value, context.expressions)); } } S::ImageStore { @@ -544,14 +604,15 @@ impl super::Validator { } => { //Note: this code uses a lot of `FunctionError::InvalidImageStore`, // and could probably be refactored. - let var = match *context.get_expression(image)? { + let var = match *context.get_expression(image).map_err(|e| e.with_span())? { crate::Expression::GlobalVariable(var_handle) => { &context.global_vars[var_handle] } _ => { return Err(FunctionError::InvalidImageStore( ExpressionError::ExpectedGlobalVariable, - )) + ) + .with_span_handle(image, context.expressions)) } }; @@ -571,13 +632,15 @@ impl super::Validator { ExpressionError::InvalidImageCoordinateType( dim, coordinate, ), - )) + ) + .with_span_handle(coordinate, context.expressions)); } }; if arrayed != array_index.is_some() { return Err(FunctionError::InvalidImageStore( ExpressionError::InvalidImageArrayIndex, - )); + ) + .with_span_handle(coordinate, context.expressions)); } if let Some(expr) = array_index { match *context.resolve_type(expr, &self.valid_expression_set)? { @@ -588,7 +651,8 @@ impl super::Validator { _ => { return Err(FunctionError::InvalidImageStore( ExpressionError::InvalidImageArrayIndexType(expr), - )) + ) + .with_span_handle(expr, context.expressions)); } } } @@ -603,19 +667,24 @@ impl super::Validator { _ => { return Err(FunctionError::InvalidImageStore( ExpressionError::InvalidImageClass(class), - )) + ) + .with_span_handle(image, context.expressions)); } } } _ => { return Err(FunctionError::InvalidImageStore( ExpressionError::ExpectedImageType(var.ty), - )) + ) + .with_span() + .with_handle(var.ty, context.types) + .with_handle(image, context.expressions)) } }; if *context.resolve_type(value, &self.valid_expression_set)? != value_ty { - return Err(FunctionError::InvalidStoreValue(value)); + return Err(FunctionError::InvalidStoreValue(value) + .with_span_handle(value, context.expressions)); } } S::Call { @@ -624,7 +693,12 @@ impl super::Validator { result, } => match self.validate_call(function, arguments, result, context) { Ok(callee_stages) => stages &= callee_stages, - Err(error) => return Err(FunctionError::InvalidCall { function, error }), + Err(error) => { + return Err(error.and_then(|error| { + FunctionError::InvalidCall { function, error } + .with_span_static(span, "invalid function call") + })) + } }, S::Atomic { pointer, @@ -642,9 +716,9 @@ impl super::Validator { #[cfg(feature = "validate")] fn validate_block( &mut self, - statements: &[crate::Statement], + statements: &crate::Block, context: &BlockContext, - ) -> Result { + ) -> Result> { let base_expression_count = self.valid_expression_list.len(); let info = self.validate_block_impl(statements, context)?; for handle in self.valid_expression_list.drain(base_expression_count..) { @@ -693,9 +767,11 @@ impl super::Validator { fun: &crate::Function, module: &crate::Module, mod_info: &ModuleInfo, - ) -> Result { + ) -> Result> { #[cfg(feature = "validate")] - let mut info = mod_info.process_function(fun, module, self.flags)?; + let mut info = mod_info + .process_function(fun, module, self.flags) + .map_err(WithSpan::into_other)?; #[cfg(not(feature = "validate"))] let info = mod_info.process_function(fun, module, self.flags)?; @@ -703,10 +779,14 @@ impl super::Validator { #[cfg(feature = "validate")] for (var_handle, var) in fun.local_variables.iter() { self.validate_local_var(var, &module.types, &module.constants) - .map_err(|error| FunctionError::LocalVariable { - handle: var_handle, - name: var.name.clone().unwrap_or_default(), - error, + .map_err(|error| { + FunctionError::LocalVariable { + handle: var_handle, + name: var.name.clone().unwrap_or_default(), + error, + } + .with_span_handle(var.ty, &module.types) + .with_handle(var_handle, &fun.local_variables) })?; } @@ -719,7 +799,8 @@ impl super::Validator { return Err(FunctionError::InvalidArgumentType { index, name: argument.name.clone().unwrap_or_default(), - }); + } + .with_span_handle(argument.ty, &module.types)); } match module.types[argument.ty].inner.pointer_class() { Some(crate::StorageClass::Private) @@ -731,7 +812,8 @@ impl super::Validator { index, name: argument.name.clone().unwrap_or_default(), class: other, - }) + } + .with_span_handle(argument.ty, &module.types)) } } } @@ -753,7 +835,10 @@ impl super::Validator { &mod_info.functions, ) { Ok(stages) => info.available_stages &= stages, - Err(error) => return Err(FunctionError::Expression { handle, error }), + Err(error) => { + return Err(FunctionError::Expression { handle, error } + .with_span_handle(handle, &fun.expressions)) + } } } } diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 7ab34d703..68326b8a8 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -4,6 +4,7 @@ use super::{ }; use crate::arena::{Handle, UniqueArena}; +use crate::span::{AddSpan as _, MapErrWithSpan as _, SpanProvider as _, WithSpan}; use bit_set::BitSet; #[cfg(feature = "validate")] @@ -70,8 +71,8 @@ pub enum EntryPointError { BindingCollision(Handle), #[error("Argument {0} varying error")] Argument(u32, #[source] VaryingError), - #[error("Result varying error")] - Result(#[source] VaryingError), + #[error(transparent)] + Result(#[from] VaryingError), #[error("Location {location} onterpolation of an integer has to be flat")] InvalidIntegerInterpolation { location: u32 }, #[error(transparent)] @@ -288,9 +289,12 @@ impl VaryingContext<'_> { Ok(()) } - fn validate(&mut self, binding: Option<&crate::Binding>) -> Result<(), VaryingError> { + fn validate(&mut self, binding: Option<&crate::Binding>) -> Result<(), WithSpan> { + let span_context = self.types.get_span_context(self.ty); match binding { - Some(binding) => self.validate_impl(binding), + Some(binding) => self + .validate_impl(binding) + .map_err(|e| e.with_span_context(span_context)), None => { match self.types[self.ty].inner { //TODO: check the member types @@ -301,15 +305,20 @@ impl VaryingContext<'_> { } => { for (index, member) in members.iter().enumerate() { self.ty = member.ty; + let span_context = self.types.get_span_context(self.ty); match member.binding { None => { - return Err(VaryingError::MemberMissingBinding(index as u32)) + return Err(VaryingError::MemberMissingBinding(index as u32) + .with_span_context(span_context)) } - Some(ref binding) => self.validate_impl(binding)?, + // TODO: shouldn't this be validate? + Some(ref binding) => self + .validate_impl(binding) + .map_err(|e| e.with_span_context(span_context))?, } } } - _ => return Err(VaryingError::MissingBinding), + _ => return Err(VaryingError::MissingBinding.with_span()), } Ok(()) } @@ -399,10 +408,10 @@ impl super::Validator { ep: &crate::EntryPoint, module: &crate::Module, mod_info: &ModuleInfo, - ) -> Result { + ) -> Result> { #[cfg(feature = "validate")] if ep.early_depth_test.is_some() && ep.stage != crate::ShaderStage::Fragment { - return Err(EntryPointError::UnexpectedEarlyDepthTest); + return Err(EntryPointError::UnexpectedEarlyDepthTest.with_span()); } #[cfg(feature = "validate")] @@ -412,13 +421,15 @@ impl super::Validator { .iter() .any(|&s| s == 0 || s > MAX_WORKGROUP_SIZE) { - return Err(EntryPointError::OutOfRangeWorkgroupSize); + return Err(EntryPointError::OutOfRangeWorkgroupSize.with_span()); } } else if ep.workgroup_size != [0; 3] { - return Err(EntryPointError::UnexpectedWorkgroupSize); + return Err(EntryPointError::UnexpectedWorkgroupSize.with_span()); } - let info = self.validate_function(&ep.function, module, mod_info)?; + let info = self + .validate_function(&ep.function, module, mod_info) + .map_err(WithSpan::into_other)?; #[cfg(feature = "validate")] { @@ -431,12 +442,13 @@ impl super::Validator { }; if !info.available_stages.contains(stage_bit) { - return Err(EntryPointError::ForbiddenStageOperations); + return Err(EntryPointError::ForbiddenStageOperations.with_span()); } } self.location_mask.clear(); let mut argument_built_ins = 0; + // TODO: add span info to function arguments for (index, fa) in ep.function.arguments.iter().enumerate() { let mut ctx = VaryingContext { ty: fa.ty, @@ -448,7 +460,7 @@ impl super::Validator { capabilities: self.capabilities, }; ctx.validate(fa.binding.as_ref()) - .map_err(|e| EntryPointError::Argument(index as u32, e))?; + .map_err_inner(|e| EntryPointError::Argument(index as u32, e).with_span())?; argument_built_ins = ctx.built_in_mask; } @@ -464,7 +476,7 @@ impl super::Validator { capabilities: self.capabilities, }; ctx.validate(fr.binding.as_ref()) - .map_err(EntryPointError::Result)?; + .map_err_inner(|e| EntryPointError::Result(e).with_span())?; } for bg in self.bind_group_masks.iter_mut() { @@ -499,7 +511,8 @@ impl super::Validator { allowed_usage, usage ); - return Err(EntryPointError::InvalidGlobalUsage(var_handle, usage)); + return Err(EntryPointError::InvalidGlobalUsage(var_handle, usage) + .with_span_handle(var_handle, &module.global_variables)); } if let Some(ref bind) = var.binding { @@ -507,7 +520,8 @@ impl super::Validator { self.bind_group_masks.push(BitSet::new()); } if !self.bind_group_masks[bind.group as usize].insert(bind.binding as usize) { - return Err(EntryPointError::BindingCollision(var_handle)); + return Err(EntryPointError::BindingCollision(var_handle) + .with_span_handle(var_handle, &module.global_variables)); } } } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index fb72cdafc..6b2c80475 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -19,6 +19,7 @@ use std::ops; //TODO: analyze the model at the same time as we validate it, // merge the corresponding matches over expressions and statements. +use crate::span::{AddSpan as _, WithSpan}; pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements}; pub use compose::ComposeError; pub use expression::ExpressionError; @@ -265,29 +266,43 @@ impl Validator { } /// Check the given module to be valid. - pub fn validate(&mut self, module: &crate::Module) -> Result { + pub fn validate( + &mut self, + module: &crate::Module, + ) -> Result> { self.reset_types(module.types.len()); - self.layouter.update(&module.types, &module.constants)?; + self.layouter + .update(&module.types, &module.constants) + .map_err(|e| { + let InvalidBaseType(handle) = e; + ValidationError::from(e).with_span_handle(handle, &module.types) + })?; #[cfg(feature = "validate")] if self.flags.contains(ValidationFlags::CONSTANTS) { for (handle, constant) in module.constants.iter() { self.validate_constant(handle, &module.constants, &module.types) - .map_err(|error| ValidationError::Constant { - handle, - name: constant.name.clone().unwrap_or_default(), - error, - })?; + .map_err(|error| { + ValidationError::Constant { + handle, + name: constant.name.clone().unwrap_or_default(), + error, + } + .with_span_handle(handle, &module.constants) + })? } } for (handle, ty) in module.types.iter() { let ty_info = self .validate_type(handle, &module.types, &module.constants) - .map_err(|error| ValidationError::Type { - handle, - name: ty.name.clone().unwrap_or_default(), - error, + .map_err(|error| { + ValidationError::Type { + handle, + name: ty.name.clone().unwrap_or_default(), + error, + } + .with_span_handle(handle, &module.types) })?; self.types[handle.index()] = ty_info; } @@ -295,10 +310,13 @@ impl Validator { #[cfg(feature = "validate")] for (var_handle, var) in module.global_variables.iter() { self.validate_global_var(var, &module.types) - .map_err(|error| ValidationError::GlobalVariable { - handle: var_handle, - name: var.name.clone().unwrap_or_default(), - error, + .map_err(|error| { + ValidationError::GlobalVariable { + handle: var_handle, + name: var.name.clone().unwrap_or_default(), + error, + } + .with_span_handle(var_handle, &module.global_variables) })?; } @@ -311,11 +329,14 @@ impl Validator { match self.validate_function(fun, module, &mod_info) { Ok(info) => mod_info.functions.push(info), Err(error) => { - return Err(ValidationError::Function { - handle, - name: fun.name.clone().unwrap_or_default(), - error, - }) + return Err(error.and_then(|error| { + ValidationError::Function { + handle, + name: fun.name.clone().unwrap_or_default(), + error, + } + .with_span_handle(handle, &module.functions) + })) } } } @@ -327,17 +348,21 @@ impl Validator { stage: ep.stage, name: ep.name.clone(), error: EntryPointError::Conflict, - }); + } + .with_span()); // TODO: keep some EP span information? } match self.validate_entry_point(ep, module, &mod_info) { Ok(info) => mod_info.entry_points.push(info), Err(error) => { - return Err(ValidationError::EntryPoint { - stage: ep.stage, - name: ep.name.clone(), - error, - }) + return Err(error.and_then(|inner| { + ValidationError::EntryPoint { + stage: ep.stage, + name: ep.name.clone(), + error: inner, + } + .with_span() + })) } } } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index dedd2042d..ab9232bbf 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -580,6 +580,7 @@ fn validation_error(source: &str) -> Result Date: Mon, 25 Oct 2021 17:15:58 +0100 Subject: [PATCH 1419/2212] [wgsl-in] Add support for function call statements (#1476) * [wgsl-in] Add support for function call statements * Apply comments --- src/front/wgsl/mod.rs | 96 ++++++++++++++++++++++++++----------------- 1 file changed, 58 insertions(+), 38 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 289282a43..ffad6a48b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1112,6 +1112,10 @@ struct ParsedVariable<'a> { init: Option>, } +struct CalledFunction { + result: Option>, +} + #[derive(Clone, Debug)] pub struct ParseError { message: String, @@ -1369,7 +1373,7 @@ impl Parser { lexer: &mut Lexer<'a>, name: &'a str, mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { + ) -> Result, Error<'a>> { assert!(self.scopes.last().is_some()); let expr = if let Some(fun) = conv::map_relational_fun(name) { let _ = lexer.next(); @@ -1483,7 +1487,9 @@ impl Parser { crate::AtomicFunction::Add, ctx.reborrow(), )?; - return Ok(Some(handle)); + return Ok(Some(CalledFunction { + result: Some(handle), + })); } "atomicSub" => { let _ = lexer.next(); @@ -1492,7 +1498,9 @@ impl Parser { crate::AtomicFunction::Subtract, ctx.reborrow(), )?; - return Ok(Some(handle)); + return Ok(Some(CalledFunction { + result: Some(handle), + })); } "atomicAnd" => { let _ = lexer.next(); @@ -1501,7 +1509,9 @@ impl Parser { crate::AtomicFunction::And, ctx.reborrow(), )?; - return Ok(Some(handle)); + return Ok(Some(CalledFunction { + result: Some(handle), + })); } "atomicOr" => { let _ = lexer.next(); @@ -1510,7 +1520,9 @@ impl Parser { crate::AtomicFunction::InclusiveOr, ctx.reborrow(), )?; - return Ok(Some(handle)); + return Ok(Some(CalledFunction { + result: Some(handle), + })); } "atomicXor" => { let _ = lexer.next(); @@ -1519,19 +1531,25 @@ impl Parser { crate::AtomicFunction::ExclusiveOr, ctx.reborrow(), )?; - return Ok(Some(handle)); + return Ok(Some(CalledFunction { + result: Some(handle), + })); } "atomicMin" => { let _ = lexer.next(); let handle = self.parse_atomic_helper(lexer, crate::AtomicFunction::Min, ctx)?; - return Ok(Some(handle)); + return Ok(Some(CalledFunction { + result: Some(handle), + })); } "atomicMax" => { let _ = lexer.next(); let handle = self.parse_atomic_helper(lexer, crate::AtomicFunction::Max, ctx)?; - return Ok(Some(handle)); + return Ok(Some(CalledFunction { + result: Some(handle), + })); } "atomicExchange" => { let _ = lexer.next(); @@ -1540,7 +1558,9 @@ impl Parser { crate::AtomicFunction::Exchange { compare: None }, ctx, )?; - return Ok(Some(handle)); + return Ok(Some(CalledFunction { + result: Some(handle), + })); } "atomicCompareExchangeWeak" => { let _ = lexer.next(); @@ -1576,7 +1596,9 @@ impl Parser { }, span, ); - return Ok(Some(result)); + return Ok(Some(CalledFunction { + result: Some(result), + })); } // texture sampling "textureSample" => { @@ -1865,14 +1887,16 @@ impl Parser { } // other _ => { - let handle = + let result = match self.parse_local_function_call(lexer, name, ctx.reborrow())? { Some((function, arguments)) => { let span = NagaSpan::from(self.peek_scope(lexer)); - let result = Some(ctx.interrupt_emitter( - crate::Expression::CallResult(function), - span, - )); + let result = ctx.functions[function].result.as_ref().map(|_| { + ctx.interrupt_emitter( + crate::Expression::CallResult(function), + span, + ) + }); ctx.block.push( crate::Statement::Call { function, @@ -1883,14 +1907,17 @@ impl Parser { ); result } - None => None, + None => return Ok(None), }; - return Ok(handle); + return Ok(Some(CalledFunction { result })); } } }; let span = NagaSpan::from(self.peek_scope(lexer)); - Ok(Some(ctx.expressions.append(expr, span))) + let handle = ctx.expressions.append(expr, span); + Ok(Some(CalledFunction { + result: Some(handle), + })) } /// Expects [`Scope::PrimaryExpr`] scope on top; if returning Some(_), pops it. @@ -2133,7 +2160,7 @@ impl Parser { handle: definition.handle, is_reference, } - } else if let Some(expr) = + } else if let Some(CalledFunction { result: Some(expr) }) = self.parse_function_call_inner(lexer, word, ctx.reborrow())? { //TODO: resolve the duplicate call in `parse_singular_expression` @@ -3154,26 +3181,22 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, ident: &'a str, - ident_span: Span, mut context: ExpressionContext<'a, '_, 'out>, ) -> Result<(), Error<'a>> { - let span_start = ident_span.start; + self.push_scope(Scope::SingularExpr, lexer); context.emitter.start(context.expressions); - let (function, arguments) = self - .parse_local_function_call(lexer, ident, context.reborrow())? - .ok_or(Error::UnknownLocalFunction(ident_span))?; - let span_end = lexer.current_byte_offset(); + if self + .parse_function_call_inner(lexer, ident, context.reborrow())? + .is_none() + { + let span = lexer.next().1; + return Err(Error::UnknownLocalFunction(span)); + } context .block .extend(context.emitter.finish(context.expressions)); - context.block.push( - crate::Statement::Call { - function, - arguments, - result: None, - }, - NagaSpan::from(span_start..span_end), - ); + self.pop_scope(lexer); + Ok(()) } @@ -3208,7 +3231,7 @@ impl Parser { block.push(crate::Statement::Block(statements), span); return Ok(()); } - (Token::Word(word), word_span) => { + (Token::Word(word), _) => { let mut emitter = super::Emitter::default(); let statement = match word { "let" => { @@ -3609,13 +3632,11 @@ impl Parser { let mut continuing = crate::Block::new(); if !lexer.skip(Token::Paren(')')) { - let (token, span) = lexer.peek(); - match token { + match lexer.peek().0 { Token::Word(ident) if context.lookup_ident.get(ident).is_none() => { self.parse_function_statement( lexer, ident, - span, context.as_expression(&mut continuing, &mut emitter), )? } @@ -3720,7 +3741,6 @@ impl Parser { None => self.parse_function_statement( lexer, ident, - word_span, context.as_expression(block, &mut emitter), )?, } From 8c071ef1220ce51581abd789a6918c9eae63a169 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 25 Oct 2021 19:17:55 +0100 Subject: [PATCH 1420/2212] [wgsl-in] Always flush expressions in function call (#1478) --- .github/workflows/validation-linux.yml | 1 + src/front/wgsl/mod.rs | 8 ++++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/validation-linux.yml b/.github/workflows/validation-linux.yml index 9bc653d39..1ac1a4759 100644 --- a/.github/workflows/validation-linux.yml +++ b/.github/workflows/validation-linux.yml @@ -6,6 +6,7 @@ on: - 'tests/out/glsl/*.glsl' - 'tests/out/dot/*.dot' - 'tests/out/wgsl/*.wgsl' + - 'src/front/wgsl/*' jobs: validate-linux: diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index ffad6a48b..6eaa6f8d5 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1891,12 +1891,12 @@ impl Parser { match self.parse_local_function_call(lexer, name, ctx.reborrow())? { Some((function, arguments)) => { let span = NagaSpan::from(self.peek_scope(lexer)); + ctx.block.extend(ctx.emitter.finish(ctx.expressions)); let result = ctx.functions[function].result.as_ref().map(|_| { - ctx.interrupt_emitter( - crate::Expression::CallResult(function), - span, - ) + ctx.expressions + .append(crate::Expression::CallResult(function), span) }); + ctx.emitter.start(ctx.expressions); ctx.block.push( crate::Statement::Call { function, From 5cf11ab73429f4b64cda6617459e7eca379f4135 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 25 Oct 2021 11:31:22 -0700 Subject: [PATCH 1421/2212] Make use of `AddSpan` and `MapErrWithSpan` conditional. This avoids warnings in default-feature builds, like `cargo test -p naga`. --- src/valid/function.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 0df8e2f56..56e4ab6fd 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -6,7 +6,9 @@ use super::{ analyzer::{UniformityDisruptor, UniformityRequirements}, ExpressionError, FunctionInfo, ModuleInfo, }; -use crate::span::{AddSpan as _, MapErrWithSpan as _, WithSpan}; +use crate::span::WithSpan; +#[cfg(feature = "span")] +use crate::span::{AddSpan as _, MapErrWithSpan as _}; #[cfg(feature = "validate")] use bit_set::BitSet; From 63dbd38edc6bdc542b23d2c1dfd55cb753ac4691 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 26 Oct 2021 18:31:54 +0100 Subject: [PATCH 1422/2212] Make default a switch case (#1477) * Make default a switch case Previously the default case of a switch statement was encoded as a block in the statement but the wgsl spec defines it in such a way that the default case ordering matters. * [spv-out] Support for the new switch IR * [dot-out] Use different labels for default cases --- src/back/dot/mod.rs | 9 +- src/back/glsl/mod.rs | 26 ++-- src/back/hlsl/writer.rs | 30 ++--- src/back/mod.rs | 15 +++ src/back/msl/writer.rs | 17 ++- src/back/spv/block.rs | 47 +++++--- src/back/wgsl/writer.rs | 33 ++--- src/front/glsl/parser/functions.rs | 113 ++++++------------ src/front/spv/function.rs | 44 ++++--- src/front/spv/mod.rs | 2 - src/front/wgsl/mod.rs | 64 +++++----- src/lib.rs | 13 +- src/proc/terminator.rs | 2 - src/valid/analyzer.rs | 10 +- src/valid/function.rs | 40 +++++-- tests/out/glsl/control-flow.main.Compute.glsl | 2 + tests/out/hlsl/control-flow.hlsl | 8 +- tests/out/msl/control-flow.msl | 14 +-- 18 files changed, 229 insertions(+), 260 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index d9f774911..b63a16359 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -63,15 +63,16 @@ impl StatementGraph { S::Switch { selector, ref cases, - ref default, } => { self.dependencies.push((id, selector, "selector")); for case in cases { let case_id = self.add(&case.body); - self.flow.push((id, case_id, "case")); + let label = match case.value { + crate::SwitchValue::Integer(_) => "case", + crate::SwitchValue::Default => "default", + }; + self.flow.push((id, case_id, label)); } - let default_id = self.add(default); - self.flow.push((id, default_id, "default")); "Switch" } S::Loop { diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index e472c6826..35ccb0e25 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1468,7 +1468,6 @@ impl<'a, W: Write> Writer<'a, W> { Statement::Switch { selector, ref cases, - ref default, } => { // Start the switch write!(self.out, "{}", level)?; @@ -1486,7 +1485,12 @@ impl<'a, W: Write> Writer<'a, W> { // Write all cases let l2 = level.next(); for case in cases { - writeln!(self.out, "{}case {}{}:", l2, case.value, type_postfix)?; + match case.value { + crate::SwitchValue::Integer(value) => { + writeln!(self.out, "{}case {}{}:", l2, value, type_postfix)? + } + crate::SwitchValue::Default => writeln!(self.out, "{}default:", l2)?, + } for sta in case.body.iter() { self.write_stmt(sta, ctx, l2.next())?; @@ -1497,27 +1501,11 @@ impl<'a, W: Write> Writer<'a, W> { // broken out of at the end of its body. if case.fall_through { writeln!(self.out, "{}/* fallthrough */", l2.next())?; - } else if !matches!( - case.body.last(), - Some(&Statement::Break) - | Some(&Statement::Continue) - | Some(&Statement::Return { .. }) - | Some(&Statement::Kill) - ) { + } else if case.body.last().map_or(true, |s| !s.is_terminator()) { writeln!(self.out, "{}break;", l2.next())?; } } - // Only write the default block if the block isn't empty - // Writing default without a block is valid but it's more readable this way - if !default.is_empty() { - writeln!(self.out, "{}default:", level.next())?; - - for sta in default { - self.write_stmt(sta, ctx, l2.next())?; - } - } - writeln!(self.out, "{}}}", level)? } // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index ce51a4823..6f05f1bd1 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1358,7 +1358,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Statement::Switch { selector, ref cases, - ref default, } => { // Start the switch write!(self.out, "{}", level)?; @@ -1378,11 +1377,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let indent_level_2 = indent_level_1.next(); for case in cases { - writeln!( - self.out, - "{}case {}{}: {{", - indent_level_1, case.value, type_postfix - )?; + match case.value { + crate::SwitchValue::Integer(value) => writeln!( + self.out, + "{}case {}{}: {{", + indent_level_1, value, type_postfix + )?, + crate::SwitchValue::Default => { + writeln!(self.out, "{}default: {{", indent_level_1)? + } + } if case.fall_through { // Generate each fallthrough case statement in a new block. This is done to @@ -1401,25 +1405,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if case.fall_through { writeln!(self.out, "{}}}", indent_level_2)?; - } else { + } else if case.body.last().map_or(true, |s| !s.is_terminator()) { writeln!(self.out, "{}break;", indent_level_2)?; } writeln!(self.out, "{}}}", indent_level_1)?; } - // Only write the default block if the block isn't empty - // Writing default without a block is valid but it's more readable this way - if !default.is_empty() { - writeln!(self.out, "{}default: {{", indent_level_1)?; - - for sta in default { - self.write_stmt(module, sta, func_ctx, indent_level_2)?; - } - - writeln!(self.out, "{}}}", indent_level_1)?; - } - writeln!(self.out, "{}}}", level)? } } diff --git a/src/back/mod.rs b/src/back/mod.rs index 77afc12e4..d2ebce38b 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -311,3 +311,18 @@ impl crate::TypeInner { } } } + +impl crate::Statement { + /// Returns true if the statement directly terminates the current block + /// + /// Used to decided wether case blocks require a explicit `break` + pub fn is_terminator(&self) -> bool { + match *self { + crate::Statement::Break + | crate::Statement::Continue + | crate::Statement::Return { .. } + | crate::Statement::Kill => true, + _ => false, + } + } +} diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e35bee19b..8b29ab2c9 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1476,7 +1476,6 @@ impl Writer { crate::Statement::Switch { selector, ref cases, - ref default, } => { write!(self.out, "{}switch(", level)?; self.put_expression(selector, &context.expression, true)?; @@ -1490,16 +1489,22 @@ impl Writer { writeln!(self.out, ") {{")?; let lcase = level.next(); for case in cases.iter() { - writeln!(self.out, "{}case {}{}: {{", lcase, case.value, type_postfix)?; + match case.value { + crate::SwitchValue::Integer(value) => { + writeln!(self.out, "{}case {}{}: {{", lcase, value, type_postfix)?; + } + crate::SwitchValue::Default => { + writeln!(self.out, "{}default: {{", lcase)?; + } + } self.put_block(lcase.next(), &case.body, context)?; - if !case.fall_through { + if !case.fall_through + && case.body.last().map_or(true, |s| !s.is_terminator()) + { writeln!(self.out, "{}break;", lcase.next())?; } writeln!(self.out, "{}}}", lcase)?; } - writeln!(self.out, "{}default: {{", lcase)?; - self.put_block(lcase.next(), default, context)?; - writeln!(self.out, "{}}}", lcase)?; writeln!(self.out, "{}}}", level)?; } crate::Statement::Loop { diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index b65a58bb2..b827d157e 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1151,7 +1151,6 @@ impl<'w> BlockContext<'w> { crate::Statement::Switch { selector, ref cases, - ref default, } => { let selector_id = self.cached[selector]; @@ -1162,13 +1161,30 @@ impl<'w> BlockContext<'w> { )); let default_id = self.gen_id(); - let raw_cases = cases - .iter() - .map(|c| super::instructions::Case { - value: c.value as Word, - label_id: self.gen_id(), - }) - .collect::>(); + + let mut reached_default = false; + let mut raw_cases = Vec::with_capacity(cases.len()); + let mut case_ids = Vec::with_capacity(cases.len()); + for case in cases.iter() { + match case.value { + crate::SwitchValue::Integer(value) => { + let label_id = self.gen_id(); + // No cases should be added after the default case is encountered + // since the default case catches all + if !reached_default { + raw_cases.push(super::instructions::Case { + value: value as Word, + label_id, + }); + } + case_ids.push(label_id); + } + crate::SwitchValue::Default => { + case_ids.push(default_id); + reached_default = true; + } + } + } self.function.consume( block, @@ -1180,24 +1196,25 @@ impl<'w> BlockContext<'w> { ..loop_context }; - for (i, (case, raw_case)) in cases.iter().zip(raw_cases.iter()).enumerate() { + for (i, (case, label_id)) in cases.iter().zip(case_ids.iter()).enumerate() { let case_finish_id = if case.fall_through { - match raw_cases.get(i + 1) { - Some(rc) => rc.label_id, - None => default_id, - } + case_ids[i + 1] } else { merge_id }; self.write_block( - raw_case.label_id, + *label_id, &case.body, Some(case_finish_id), inner_context, )?; } - self.write_block(default_id, default, Some(merge_id), inner_context)?; + // If no default was encountered write a empty block to satisfy the presence of + // a block the default label + if !reached_default { + self.write_block(default_id, &[], Some(merge_id), inner_context)?; + } block = Block::new(merge_id); } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 82b46838b..3c5d6a415 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -877,7 +877,6 @@ impl Writer { Statement::Switch { selector, ref cases, - ref default, } => { // Start the switch write!(self.out, "{}", level)?; @@ -885,11 +884,6 @@ impl Writer { self.write_expr(module, selector, func_ctx)?; writeln!(self.out, ") {{")?; - // Write all cases - let mut write_case = true; - let all_fall_through = cases - .iter() - .all(|case| case.fall_through && case.body.is_empty()); let type_postfix = match *func_ctx.info[selector].ty.inner_with(&module.types) { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, @@ -901,16 +895,13 @@ impl Writer { let l2 = level.next(); if !cases.is_empty() { for case in cases { - if write_case { - write!(self.out, "{}case ", l2)?; - } - if !all_fall_through && case.fall_through && case.body.is_empty() { - write_case = false; - write!(self.out, "{}{}, ", case.value, type_postfix)?; - continue; - } else { - write_case = true; - writeln!(self.out, "{}{}: {{", case.value, type_postfix)?; + match case.value { + crate::SwitchValue::Integer(value) => { + writeln!(self.out, "{}case {}{}: {{", l2, value, type_postfix)?; + } + crate::SwitchValue::Default => { + writeln!(self.out, "{}default: {{", l2)?; + } } for sta in case.body.iter() { @@ -925,16 +916,6 @@ impl Writer { } } - if !default.is_empty() { - writeln!(self.out, "{}default: {{", l2)?; - - for sta in default { - self.write_stmt(module, sta, func_ctx, l2.next())?; - } - - writeln!(self.out, "{}}}", l2)? - } - writeln!(self.out, "{}}}", level)? } Statement::Loop { diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 68001558b..aec40357a 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -169,11 +169,10 @@ impl<'source> ParsingContext<'source> { ctx.emit_start(); let mut cases = Vec::new(); - let mut default = Block::new(); self.expect(parser, TokenValue::LeftBrace)?; loop { - match self.expect_peek(parser)?.value { + let value = match self.expect_peek(parser)?.value { TokenValue::Case => { self.bump(parser)?; let value = { @@ -204,73 +203,11 @@ impl<'source> ParsingContext<'source> { } } }; - - self.expect(parser, TokenValue::Colon)?; - - let mut body = Block::new(); - - let mut case_terminator = None; - loop { - match self.expect_peek(parser)?.value { - TokenValue::Case - | TokenValue::Default - | TokenValue::RightBrace => break, - _ => { - self.parse_statement( - parser, - ctx, - &mut body, - &mut case_terminator, - )?; - } - } - } - - let mut fall_through = true; - - if let Some(mut idx) = case_terminator { - if let Statement::Break = body[idx - 1] { - fall_through = false; - idx -= 1; - } - - body.cull(idx..) - } - - cases.push(SwitchCase { - value, - body, - fall_through, - }) + crate::SwitchValue::Integer(value) } TokenValue::Default => { - let Token { meta, .. } = self.bump(parser)?; - self.expect(parser, TokenValue::Colon)?; - - if !default.is_empty() { - parser.errors.push(Error { - kind: ErrorKind::SemanticError( - "Can only have one default case per switch statement" - .into(), - ), - meta, - }); - } - - let mut default_terminator = None; - loop { - match self.expect_peek(parser)?.value { - TokenValue::Case | TokenValue::RightBrace => break, - _ => { - self.parse_statement( - parser, - ctx, - &mut default, - &mut default_terminator, - )?; - } - } - } + self.bump(parser)?; + crate::SwitchValue::Default } TokenValue::RightBrace => { end_meta = self.bump(parser)?.meta; @@ -290,19 +227,45 @@ impl<'source> ParsingContext<'source> { meta, }); } + }; + + self.expect(parser, TokenValue::Colon)?; + + let mut body = Block::new(); + + let mut case_terminator = None; + loop { + match self.expect_peek(parser)?.value { + TokenValue::Case | TokenValue::Default | TokenValue::RightBrace => { + break + } + _ => { + self.parse_statement(parser, ctx, &mut body, &mut case_terminator)?; + } + } } + + let mut fall_through = true; + + if let Some(mut idx) = case_terminator { + if let Statement::Break = body[idx - 1] { + fall_through = false; + idx -= 1; + } + + body.cull(idx..) + } + + cases.push(SwitchCase { + value, + body, + fall_through, + }) } meta.subsume(end_meta); - body.push( - Statement::Switch { - selector, - cases, - default, - }, - meta, - ); + body.push(Statement::Switch { selector, cases }, meta); meta } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index ca7d002b5..d85c61438 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -566,33 +566,31 @@ impl<'function> BlockContext<'function> { ref cases, default, } => { - let default = lower_impl(blocks, bodies, default); + let mut ir_cases: Vec<_> = cases + .iter() + .map(|&(value, body_idx)| { + let body = lower_impl(blocks, bodies, body_idx); + + // Handle simple cases that would make a fallthrough statement unreachable code + let fall_through = body.last().map_or(true, |s| !s.is_terminator()); + + crate::SwitchCase { + value: crate::SwitchValue::Integer(value), + body, + fall_through, + } + }) + .collect(); + ir_cases.push(crate::SwitchCase { + value: crate::SwitchValue::Default, + body: lower_impl(blocks, bodies, default), + fall_through: false, + }); block.push( crate::Statement::Switch { selector, - cases: cases - .iter() - .map(|&(value, body_idx)| { - let body = lower_impl(blocks, bodies, body_idx); - - // Handle simple cases that would make a fallthrough statement unreachable code - let fall_through = match body.last() { - Some(&crate::Statement::Break) - | Some(&crate::Statement::Continue) - | Some(&crate::Statement::Kill) - | Some(&crate::Statement::Return { .. }) => false, - _ => true, - }; - - crate::SwitchCase { - value, - body, - fall_through, - } - }) - .collect(), - default, + cases: ir_cases, }, crate::Span::default(), ) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 9ee0397f1..3df39bde3 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3225,12 +3225,10 @@ impl> Parser { S::Switch { selector: _, ref mut cases, - ref mut default, } => { for case in cases.iter_mut() { self.patch_statements(&mut case.body, expressions, fun_parameter_sampling)?; } - self.patch_statements(default, expressions, fun_parameter_sampling)?; } S::Loop { ref mut body, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6eaa6f8d5..e2879c722 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3200,6 +3200,29 @@ impl Parser { Ok(()) } + fn parse_switch_case_body<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: StatementContext<'a, '_, 'out>, + ) -> Result<(bool, crate::Block), Error<'a>> { + let mut body = crate::Block::new(); + lexer.expect(Token::Paren('{'))?; + let fall_through = loop { + // default statements + if lexer.skip(Token::Word("fallthrough")) { + lexer.expect(Token::Separator(';'))?; + lexer.expect(Token::Paren('}'))?; + break true; + } + if lexer.skip(Token::Paren('}')) { + break false; + } + self.parse_statement(lexer, context.reborrow(), &mut body, false)?; + }; + + Ok((fall_through, body)) + } + fn parse_statement<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, @@ -3495,7 +3518,6 @@ impl Parser { block.extend(emitter.finish(context.expressions)); lexer.expect(Token::Paren('{'))?; let mut cases = Vec::new(); - let mut default = crate::Block::new(); loop { // cases + default @@ -3503,7 +3525,6 @@ impl Parser { (Token::Word("case"), _) => { // parse a list of values let value = loop { - // TODO: Switch statements also allow for floats, bools and unsigned integers. See https://www.w3.org/TR/WGSL/#switch-statement let value = Self::parse_switch_value(lexer, uint)?; if lexer.skip(Token::Separator(',')) { if lexer.skip(Token::Separator(':')) { @@ -3514,41 +3535,30 @@ impl Parser { break value; } cases.push(crate::SwitchCase { - value, + value: crate::SwitchValue::Integer(value), body: crate::Block::new(), fall_through: true, }); }; - let mut body = crate::Block::new(); - lexer.expect(Token::Paren('{'))?; - let fall_through = loop { - // default statements - if lexer.skip(Token::Word("fallthrough")) { - lexer.expect(Token::Separator(';'))?; - lexer.expect(Token::Paren('}'))?; - break true; - } - if lexer.skip(Token::Paren('}')) { - break false; - } - self.parse_statement( - lexer, - context.reborrow(), - &mut body, - false, - )?; - }; + let (fall_through, body) = + self.parse_switch_case_body(lexer, context.reborrow())?; cases.push(crate::SwitchCase { - value, + value: crate::SwitchValue::Integer(value), body, fall_through, }); } (Token::Word("default"), _) => { lexer.expect(Token::Separator(':'))?; - default = self.parse_block(lexer, context.reborrow(), false)?; + let (fall_through, body) = + self.parse_switch_case_body(lexer, context.reborrow())?; + cases.push(crate::SwitchCase { + value: crate::SwitchValue::Default, + body, + fall_through, + }); } (Token::Paren('}'), _) => break, other => { @@ -3557,11 +3567,7 @@ impl Parser { } } - Some(crate::Statement::Switch { - selector, - cases, - default, - }) + Some(crate::Statement::Switch { selector, cases }) } "loop" => { let _ = lexer.next(); diff --git a/src/lib.rs b/src/lib.rs index 99b77b267..6cda40f21 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1301,6 +1301,16 @@ pub enum Expression { pub use block::Block; +/// The value of the switch case +// Clone is used only for error reporting and is not intended for end users +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum SwitchValue { + Integer(i32), + Default, +} + /// A case for a switch statement. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug)] @@ -1308,7 +1318,7 @@ pub use block::Block; #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub struct SwitchCase { /// Value, upon which the case is considered true. - pub value: i32, + pub value: SwitchValue, /// Body of the case. pub body: Block, /// If true, the control flow continues to the next case in the list, @@ -1341,7 +1351,6 @@ pub enum Statement { Switch { selector: Handle, //int cases: Vec, - default: Block, }, /// Executes a block repeatedly. diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index e35c2d9f9..83034a82a 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -21,14 +21,12 @@ pub fn ensure_block_returns(block: &mut crate::Block) { Some(&mut S::Switch { selector: _, ref mut cases, - ref mut default, }) => { for case in cases.iter_mut() { if !case.fall_through { ensure_block_returns(&mut case.body); } } - ensure_block_returns(default); } Some(&mut S::Emit(_)) | Some(&mut S::Break) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 051bf4ca8..c581a5681 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -694,7 +694,6 @@ impl FunctionInfo { S::Switch { selector, ref cases, - ref default, } => { let selector_nur = self.add_ref(selector); let branch_disruptor = @@ -715,14 +714,7 @@ impl FunctionInfo { }; uniformity = uniformity | case_uniformity; } - // using the disruptor inherited from the last fall-through chain - let default_exit = self.process_block( - default, - other_functions, - case_disruptor, - expression_arena, - )?; - uniformity | default_exit + uniformity } S::Loop { ref body, diff --git a/src/valid/function.rs b/src/valid/function.rs index 56e4ab6fd..14068e3e4 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -106,6 +106,8 @@ pub enum FunctionError { InvalidSwitchType(Handle), #[error("Multiple `switch` cases for {0:?} are present")] ConflictingSwitchCase(i32), + #[error("Multiple `default` cases are present")] + MultipleDefaultCases, #[error("The pointer {0:?} doesn't relate to a valid destination for a store")] InvalidStorePointer(Handle), #[error("The value {0:?} can not be stored")] @@ -421,7 +423,6 @@ impl super::Validator { S::Switch { selector, ref cases, - ref default, } => { match *context.resolve_type(selector, &self.valid_expression_set)? { Ti::Scalar { @@ -438,16 +439,34 @@ impl super::Validator { } } self.select_cases.clear(); + let mut default = false; for case in cases { - if !self.select_cases.insert(case.value) { - return Err(FunctionError::ConflictingSwitchCase(case.value) - .with_span_static( - case.body - .span_iter() - .next() - .map_or(Default::default(), |(_, s)| *s), - "conflicting switch arm here", - )); + match case.value { + crate::SwitchValue::Integer(value) => { + if !self.select_cases.insert(value) { + return Err(FunctionError::ConflictingSwitchCase(value) + .with_span_static( + case.body + .span_iter() + .next() + .map_or(Default::default(), |(_, s)| *s), + "conflicting switch arm here", + )); + } + } + crate::SwitchValue::Default => { + if default { + return Err(FunctionError::MultipleDefaultCases + .with_span_static( + case.body + .span_iter() + .next() + .map_or(Default::default(), |(_, s)| *s), + "duplicated switch arm here", + )); + } + default = true + } } } let pass_through_abilities = context.abilities @@ -457,7 +476,6 @@ impl super::Validator { for case in cases { stages &= self.validate_block(&case.body, &sub_context)?.stages; } - stages &= self.validate_block(default, &sub_context)?.stages; } S::Loop { ref body, diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index 4de563e89..2e5673b1d 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -39,6 +39,7 @@ void main() { switch(1) { default: pos = 1; + break; } int _e4 = pos; switch(_e4) { @@ -55,6 +56,7 @@ void main() { break; default: pos = 3; + break; } switch(0u) { case 0u: diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index 5a771342f..7922462e9 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -13,7 +13,6 @@ void switch_case_break() switch(0) { case 0: { break; - break; } } return; @@ -25,7 +24,6 @@ void loop_switch_continue(int x) switch(x) { case 1: { continue; - break; } } } @@ -42,6 +40,7 @@ void main(uint3 global_id : SV_DispatchThreadID) switch(1) { default: { pos = 1; + break; } } int _expr4 = pos; @@ -49,7 +48,6 @@ void main(uint3 global_id : SV_DispatchThreadID) case 1: { pos = 0; break; - break; } case 2: { pos = 1; @@ -66,6 +64,7 @@ void main(uint3 global_id : SV_DispatchThreadID) } default: { pos = 3; + break; } } switch(0u) { @@ -78,12 +77,10 @@ void main(uint3 global_id : SV_DispatchThreadID) case 1: { pos = 0; break; - break; } case 2: { pos = 1; return; - break; } case 3: { /* fallthrough */ @@ -93,7 +90,6 @@ void main(uint3 global_id : SV_DispatchThreadID) } case 4: { return; - break; } default: { pos = 3; diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index 8662b8b30..c6332190d 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -18,9 +18,6 @@ void switch_case_break( switch(0) { case 0: { break; - break; - } - default: { } } return; @@ -33,9 +30,6 @@ void loop_switch_continue( switch(x) { case 1: { continue; - break; - } - default: { } } } @@ -53,6 +47,7 @@ kernel void main1( switch(1) { default: { pos = 1; + break; } } int _e4 = pos; @@ -60,7 +55,6 @@ kernel void main1( case 1: { pos = 0; break; - break; } case 2: { pos = 1; @@ -74,33 +68,29 @@ kernel void main1( } default: { pos = 3; + break; } } switch(0u) { case 0u: { break; } - default: { - } } int _e10 = pos; switch(_e10) { case 1: { pos = 0; break; - break; } case 2: { pos = 1; return; - break; } case 3: { pos = 2; } case 4: { return; - break; } default: { pos = 3; From 00bbbed90a14b8f1d4b7d6c261eb1b3be2150a89 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 27 Oct 2021 00:46:27 +0300 Subject: [PATCH 1423/2212] Handle empty variable names in namer (#1484) * Handle empty variable names in namer * Add glsl-in test with empty global name --- src/proc/namer.rs | 8 +++++++- tests/in/glsl/empty-global-name.frag | 7 +++++++ tests/out/wgsl/empty-global-name-frag.wgsl | 21 +++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 tests/in/glsl/empty-global-name.frag create mode 100644 tests/out/wgsl/empty-global-name-frag.wgsl diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 0a74b178b..126d985db 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -117,7 +117,13 @@ impl Namer { pub fn call_or(&mut self, label: &Option, fallback: &str) -> String { self.call(match *label { - Some(ref name) => name, + Some(ref name) => { + if name.trim().is_empty() { + fallback + } else { + name + } + } None => fallback, }) } diff --git a/tests/in/glsl/empty-global-name.frag b/tests/in/glsl/empty-global-name.frag new file mode 100644 index 000000000..d2b495c62 --- /dev/null +++ b/tests/in/glsl/empty-global-name.frag @@ -0,0 +1,7 @@ +layout(set = 1, binding = 1) uniform TextureData { + vec4 material; +}; + +void main() { + vec2 coords = vec2(material.xy); +} diff --git a/tests/out/wgsl/empty-global-name-frag.wgsl b/tests/out/wgsl/empty-global-name-frag.wgsl new file mode 100644 index 000000000..b3d73f14d --- /dev/null +++ b/tests/out/wgsl/empty-global-name-frag.wgsl @@ -0,0 +1,21 @@ +[[block]] +struct TextureData { + material: vec4; +}; + +[[group(1), binding(1)]] +var global: TextureData; + +fn main1() { + var coords: vec2; + + let e2: vec4 = global.material; + coords = vec2(e2.xy); + return; +} + +[[stage(fragment)]] +fn main() { + main1(); + return; +} From 0458f0a40476e5f89db95dad7323fd8e0e051962 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 27 Oct 2021 02:33:49 +0100 Subject: [PATCH 1424/2212] [valid] Check that the last switch case isn't falltrough (#1485) --- src/valid/function.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/valid/function.rs b/src/valid/function.rs index 14068e3e4..70980e125 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -108,6 +108,8 @@ pub enum FunctionError { ConflictingSwitchCase(i32), #[error("Multiple `default` cases are present")] MultipleDefaultCases, + #[error("The last `switch` case contains a `falltrough`")] + LastCaseFallTrough, #[error("The pointer {0:?} doesn't relate to a valid destination for a store")] InvalidStorePointer(Handle), #[error("The value {0:?} can not be stored")] @@ -469,6 +471,17 @@ impl super::Validator { } } } + if let Some(case) = cases.last() { + if case.fall_through { + return Err(FunctionError::LastCaseFallTrough.with_span_static( + case.body + .span_iter() + .next() + .map_or(Default::default(), |(_, s)| *s), + "bad switch arm here", + )); + } + } let pass_through_abilities = context.abilities & (ControlFlowAbility::RETURN | ControlFlowAbility::CONTINUE); let sub_context = From d1cfdd15a0548d1bf9fc0f51c8df63eaffa4c7a4 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 27 Oct 2021 11:59:15 +0300 Subject: [PATCH 1425/2212] Add test for last falltrough switch case --- tests/wgsl-errors.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index ab9232bbf..4bf6b557a 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -988,3 +988,24 @@ fn select() { if name.starts_with("select_") } } + +#[test] +fn last_case_falltrough() { + check_validation_error! { + " + fn test_falltrough() { + switch(0) { + case 0: { + fallthrough; + } + } + } + ": + Err( + naga::valid::ValidationError::Function { + error: naga::valid::FunctionError::LastCaseFallTrough, + .. + }, + ) + } +} From 9d2b357214dacce0fe30587844d4c7bf41b51773 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 28 Oct 2021 20:54:32 +0300 Subject: [PATCH 1426/2212] [glsl\wgsl out] Remove unnecessary clones (#1492) * [glsl-out] Remove unnecessary clones * [wgsl-out] Remove unnecessary clones --- src/back/glsl/mod.rs | 52 +++++++++++++++++++++++++++-------------- src/back/wgsl/writer.rs | 11 +++++---- 2 files changed, 41 insertions(+), 22 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 35ccb0e25..c29bd174b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -617,17 +617,10 @@ impl<'a, W: Write> Writer<'a, W> { continue; } - // We also `clone` to satisfy the borrow checker - let name = self.names[&NameKey::Function(handle)].clone(); let fun_info = &self.info[handle]; // Write the function - self.write_function( - back::FunctionType::Function(handle), - function, - fun_info, - &name, - )?; + self.write_function(back::FunctionType::Function(handle), function, fun_info)?; writeln!(self.out)?; } @@ -636,7 +629,6 @@ impl<'a, W: Write> Writer<'a, W> { back::FunctionType::EntryPoint(self.entry_point_idx), &self.entry_point.function, ep_info, - "main", )?; // Add newline at the end of file @@ -882,8 +874,8 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the global name and end the global with a `;` and a newline // Leading space is important - let global_name = self.get_global_name(handle, global); - write!(self.out, " {}", global_name)?; + write!(self.out, " ")?; + self.write_global_name(handle, global)?; if let TypeInner::Array { size, .. } = self.module.types[global.ty].inner { self.write_array_size(size)?; } @@ -920,6 +912,24 @@ impl<'a, W: Write> Writer<'a, W> { } } + /// Helper method used to write a name for a global without additional heap allocation + fn write_global_name( + &mut self, + handle: Handle, + global: &crate::GlobalVariable, + ) -> BackendResult { + match global.binding { + Some(ref br) => write!(self.out, "_group_{}_binding_{}", br.group, br.binding)?, + None => write!( + self.out, + "{}", + &self.names[&NameKey::GlobalVariable(handle)] + )?, + } + + Ok(()) + } + /// Writes the varying declaration. fn write_varying( &mut self, @@ -1013,7 +1023,6 @@ impl<'a, W: Write> Writer<'a, W> { ty: back::FunctionType, func: &crate::Function, info: &valid::FunctionInfo, - name: &str, ) -> BackendResult { // Create a function context for the function being written let ctx = back::FunctionCtx { @@ -1047,7 +1056,11 @@ impl<'a, W: Write> Writer<'a, W> { } // Write the function name and open parentheses for the argument list - write!(self.out, " {}(", name)?; + let function_name = match ctx.ty { + back::FunctionType::Function(handle) => &self.names[&NameKey::Function(handle)], + back::FunctionType::EntryPoint(_) => "main", + }; + write!(self.out, " {}(", function_name)?; // Write the comma separated argument list // @@ -1609,9 +1622,6 @@ impl<'a, W: Write> Writer<'a, W> { stage: ep.stage, output: true, }; - let field_name = self.names - [&NameKey::StructMember(result.ty, index as u32)] - .clone(); write!(self.out, "{} = ", varying_name)?; if let Some(struct_name) = temp_struct_name { @@ -1620,7 +1630,13 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(value, ctx)?; } - writeln!(self.out, ".{};", field_name)?; + // Write field name + writeln!( + self.out, + ".{};", + &self.names + [&NameKey::StructMember(result.ty, index as u32)] + )?; write!(self.out, "{}", level)?; } } @@ -1872,7 +1888,7 @@ impl<'a, W: Write> Writer<'a, W> { // `get_global_name` does the work for us Expression::GlobalVariable(handle) => { let global = &self.module.global_variables[handle]; - write!(self.out, "{}", self.get_global_name(handle, global))? + self.write_global_name(handle, global)? } // A local is written as it's name Expression::LocalVariable(handle) => { diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 3c5d6a415..8fa8ea43f 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1652,7 +1652,6 @@ impl Writer { global: &crate::GlobalVariable, handle: Handle, ) -> BackendResult { - let name = self.names[&NameKey::GlobalVariable(handle)].clone(); // Write group and dinding attributes if present if let Some(ref binding) = global.binding { self.write_attributes( @@ -1675,7 +1674,11 @@ impl Writer { } write!(self.out, ">")?; } - write!(self.out, " {}: ", name)?; + write!( + self.out, + " {}: ", + &self.names[&NameKey::GlobalVariable(handle)] + )?; // Write global type self.write_type(module, global.ty)?; @@ -1765,7 +1768,7 @@ impl Writer { width: _, ref value, } => { - let name = self.names[&NameKey::Constant(handle)].clone(); + let name = &self.names[&NameKey::Constant(handle)]; // First write only constant name write!(self.out, "let {}: ", name)?; // Next write constant type and value @@ -1789,7 +1792,7 @@ impl Writer { writeln!(self.out, ";")?; } crate::ConstantInner::Composite { ty, ref components } => { - let name = self.names[&NameKey::Constant(handle)].clone(); + let name = &self.names[&NameKey::Constant(handle)]; // First write only constant name write!(self.out, "let {}: ", name)?; // Next write constant type From 323999fcb9eb8e8c525d75d2878fe1e2e5a99aad Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 31 Oct 2021 23:58:58 -0400 Subject: [PATCH 1427/2212] Fix span includes into function validation (#1500) --- .github/workflows/lazy.yml | 13 +++++++++++-- src/valid/function.rs | 2 +- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index e7e26d329..9423e22cb 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -26,6 +26,7 @@ jobs: with: name: code-coverage-report path: cobertura.xml + parse-dota2: name: Parse Dota2 shaders runs-on: ubuntu-latest @@ -44,6 +45,7 @@ jobs: run: cargo build --release --bin naga - name: Convert shaders run: for file in data/*.spv ; do echo "Translating" ${file} && target/release/naga --validate 27 ${file} ${file}.metal; done + parse-vulkan-tutorial-shaders: name: Parse Sascha Willems Vulkan tutorial shaders runs-on: ubuntu-latest @@ -76,6 +78,7 @@ jobs: echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter done cat counter + dneto0_spirv-samples: name: Parse dneto0 spirv-samples runs-on: ubuntu-latest @@ -149,8 +152,9 @@ jobs: echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter done cat counter - check_snapshots_without_validation: - name: Check snapshots (without validation) + + check-snapshots-extra: + name: Check snapshots (validated or not) runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -158,6 +162,11 @@ jobs: with: profile: minimal toolchain: stable + - uses: actions-rs/cargo@v1 + name: Test minimal (without span) + with: + command: test + args: --features validate -p naga - uses: actions-rs/cargo@v1 name: Test all (without validation) with: diff --git a/src/valid/function.rs b/src/valid/function.rs index 70980e125..34c833db0 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -7,7 +7,7 @@ use super::{ ExpressionError, FunctionInfo, ModuleInfo, }; use crate::span::WithSpan; -#[cfg(feature = "span")] +#[cfg(feature = "validate")] use crate::span::{AddSpan as _, MapErrWithSpan as _}; #[cfg(feature = "validate")] From c1b378842eb6723e8ca782f6612e84241508b8ad Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 1 Nov 2021 11:07:11 -0700 Subject: [PATCH 1428/2212] Make tests properly exercise Some("") global names. (#1503) The GLSL empty-global-name.frag test doesn't suffice because the GLSL front end doesn't produce the same IR as the SPIR-V included in the bug report. As far as I know, only a genuine SPIR-V input test can produce a global whose name is `Some("")`. Include the SPIR-V assembly source. --- tests/in/glsl/empty-global-name.frag | 7 --- tests/in/spv/empty-global-name.spv | Bin 0 -> 408 bytes tests/in/spv/empty-global-name.spvasm | 44 +++++++++++++++++++ tests/out/hlsl/empty-global-name.hlsl | 19 ++++++++ tests/out/hlsl/empty-global-name.hlsl.config | 3 ++ tests/out/msl/empty-global-name.msl | 21 +++++++++ tests/out/wgsl/empty-global-name-frag.wgsl | 21 --------- tests/out/wgsl/empty-global-name.wgsl | 18 ++++++++ tests/snapshots.rs | 10 +++++ 9 files changed, 115 insertions(+), 28 deletions(-) delete mode 100644 tests/in/glsl/empty-global-name.frag create mode 100644 tests/in/spv/empty-global-name.spv create mode 100644 tests/in/spv/empty-global-name.spvasm create mode 100644 tests/out/hlsl/empty-global-name.hlsl create mode 100644 tests/out/hlsl/empty-global-name.hlsl.config create mode 100644 tests/out/msl/empty-global-name.msl delete mode 100644 tests/out/wgsl/empty-global-name-frag.wgsl create mode 100644 tests/out/wgsl/empty-global-name.wgsl diff --git a/tests/in/glsl/empty-global-name.frag b/tests/in/glsl/empty-global-name.frag deleted file mode 100644 index d2b495c62..000000000 --- a/tests/in/glsl/empty-global-name.frag +++ /dev/null @@ -1,7 +0,0 @@ -layout(set = 1, binding = 1) uniform TextureData { - vec4 material; -}; - -void main() { - vec2 coords = vec2(material.xy); -} diff --git a/tests/in/spv/empty-global-name.spv b/tests/in/spv/empty-global-name.spv new file mode 100644 index 0000000000000000000000000000000000000000..02089e13d029b00c8454d00f35e74984d90716f0 GIT binary patch literal 408 zcmZ9GIS#^53`B=4gf)v0Eh40(M@R?+6^N#Nr2|Qs zO20&XR~csm4pRR`C$8o=QQumHuGDnNdeUl}zq$_f z!fIl^^vexvgB`2j+w~G(BF&7x&O*)Z+Os2PeBfhe=C;9eVovn+)SMj$>-cax-aG%o o1C7A*V-@XUjT`0$^LQSEe;)d8&#<>J=&|SId-y}|Yv;Z31IT;|%m4rY literal 0 HcmV?d00001 diff --git a/tests/in/spv/empty-global-name.spvasm b/tests/in/spv/empty-global-name.spvasm new file mode 100644 index 000000000..d0102eedd --- /dev/null +++ b/tests/in/spv/empty-global-name.spvasm @@ -0,0 +1,44 @@ +;; Make sure we handle globals whose assigned name is "". +;; +;; In MSL, the anonymous global sometimes ends up looking like +;; +;; struct Blah { int member; } ; +;; +;; where the null name just becomes an empty string before that last semicolon. +;; This is, unfortunately, valid MSL, simply declaring the type Blah, so it will +;; pass validation. However, an attempt to *use* the global will generate a +;; garbage expression like ".member", so we include a function that returns the +;; member's value. + + OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %global + OpExecutionMode %main LocalSize 64 1 1 + + OpName %global "" + OpDecorate %block Block + OpMemberDecorate %block 0 Offset 0 + OpDecorate %global DescriptorSet 0 + OpDecorate %global Binding 0 + + %void = OpTypeVoid + %int = OpTypeInt 32 1 + %block = OpTypeStruct %int + %ptr_int = OpTypePointer StorageBuffer %int + %ptr_block = OpTypePointer StorageBuffer %block + %fn_void = OpTypeFunction %void + %fn_int = OpTypeFunction %int + %zero = OpConstant %int 0 + %one = OpConstant %int 1 + +;; This global is said to have a name of "". + %global = OpVariable %ptr_block StorageBuffer + + %main = OpFunction %void None %fn_void + %main_prelude = OpLabel + %member_ptr = OpAccessChain %ptr_int %global %zero + %member_val = OpLoad %int %member_ptr + %plus_one = OpIAdd %int %member_val %one + OpStore %member_ptr %plus_one + OpReturn + OpFunctionEnd diff --git a/tests/out/hlsl/empty-global-name.hlsl b/tests/out/hlsl/empty-global-name.hlsl new file mode 100644 index 000000000..5bc384866 --- /dev/null +++ b/tests/out/hlsl/empty-global-name.hlsl @@ -0,0 +1,19 @@ + +struct type1 { + int member; +}; + +RWByteAddressBuffer global : register(u0); + +void function() +{ + int _expr8 = asint(global.Load(0)); + global.Store(0, asuint((_expr8 + 1))); + return; +} + +[numthreads(64, 1, 1)] +void main() +{ + function(); +} diff --git a/tests/out/hlsl/empty-global-name.hlsl.config b/tests/out/hlsl/empty-global-name.hlsl.config new file mode 100644 index 000000000..246c485cf --- /dev/null +++ b/tests/out/hlsl/empty-global-name.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(main:cs_5_1 ) diff --git a/tests/out/msl/empty-global-name.msl b/tests/out/msl/empty-global-name.msl new file mode 100644 index 000000000..a0bb212dc --- /dev/null +++ b/tests/out/msl/empty-global-name.msl @@ -0,0 +1,21 @@ +// language: metal1.1 +#include +#include + +struct type1 { + int member; +}; + +void function( + device type1& global +) { + int _e8 = global.member; + global.member = _e8 + 1; + return; +} + +kernel void main1( + device type1& global [[user(fake0)]] +) { + function(global); +} diff --git a/tests/out/wgsl/empty-global-name-frag.wgsl b/tests/out/wgsl/empty-global-name-frag.wgsl deleted file mode 100644 index b3d73f14d..000000000 --- a/tests/out/wgsl/empty-global-name-frag.wgsl +++ /dev/null @@ -1,21 +0,0 @@ -[[block]] -struct TextureData { - material: vec4; -}; - -[[group(1), binding(1)]] -var global: TextureData; - -fn main1() { - var coords: vec2; - - let e2: vec4 = global.material; - coords = vec2(e2.xy); - return; -} - -[[stage(fragment)]] -fn main() { - main1(); - return; -} diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl new file mode 100644 index 000000000..40c02ee05 --- /dev/null +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -0,0 +1,18 @@ +[[block]] +struct type2 { + member: i32; +}; + +[[group(0), binding(0)]] +var global: type2; + +fn function1() { + let e8: i32 = global.member; + global.member = (e8 + 1); + return; +} + +[[stage(compute), workgroup_size(64, 1, 1)]] +fn main() { + function1(); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index abccc15eb..c513dbb82 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -598,6 +598,16 @@ fn convert_spv_inverse_hyperbolic_trig_functions() { ); } +#[cfg(feature = "spv-in")] +#[test] +fn convert_spv_empty_global_name() { + convert_spv( + "empty-global-name", + true, + Targets::HLSL | Targets::WGSL | Targets::METAL, + ); +} + #[cfg(feature = "glsl-in")] #[allow(unused_variables)] #[test] From d9b166816bb633bf8d69282a44228ef176431b5a Mon Sep 17 00:00:00 2001 From: Shohei Jinno <18493164+sjinno@users.noreply.github.com> Date: Tue, 2 Nov 2021 18:05:59 -0700 Subject: [PATCH 1429/2212] [glsl-in] Add helper to reduce repetition. (#1505) ``` Ok(self.constants.fetch_or_append( Constant { name: None, specialization: None, inner, }, span, )) ``` was called repetitively, so I added `ConstantSolver::register_constant(&mut self, ConstantInner, Span)` that returns Handle. --- src/front/glsl/constants.rs | 72 ++++++++++--------------------------- 1 file changed, 19 insertions(+), 53 deletions(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index e0cce7247..8718b96ff 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -96,17 +96,11 @@ impl<'a> ConstantSolver<'a> { } }; - Ok(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { - ty, - components: vec![value_constant; size as usize], - }, - }, - span, - )) + let inner = ConstantInner::Composite { + ty, + components: vec![value_constant; size as usize], + }; + Ok(self.register_constant(inner, span)) } Expression::Swizzle { size, @@ -146,30 +140,18 @@ impl<'a> ConstantSolver<'a> { .iter() .map(|&sc| src_components[sc as usize]) .collect(); + let inner = ConstantInner::Composite { ty, components }; - Ok(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { ty, components }, - }, - span, - )) + Ok(self.register_constant(inner, span)) } Expression::Compose { ty, ref components } => { let components = components .iter() .map(|c| self.solve(*c)) .collect::>()?; + let inner = ConstantInner::Composite { ty, components }; - Ok(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { ty, components }, - }, - span, - )) + Ok(self.register_constant(inner, span)) } Expression::Unary { expr, op } => { let expr_constant = self.solve(expr)?; @@ -216,14 +198,8 @@ impl<'a> ConstantSolver<'a> { _ => return Err(ConstantSolvingError::InvalidMathArg), }; - Ok(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { width, value }, - }, - span, - )) + let inner = ConstantInner::Scalar { width, value }; + Ok(self.register_constant(inner, span)) } _ => Err(ConstantSolvingError::NotImplemented(format!("{:?}", fun))), } @@ -357,14 +333,7 @@ impl<'a> ConstantSolver<'a> { } } - Ok(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner, - }, - span, - )) + Ok(self.register_constant(inner, span)) } fn unary_op( @@ -404,14 +373,7 @@ impl<'a> ConstantSolver<'a> { } } - Ok(self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner, - }, - span, - )) + Ok(self.register_constant(inner, span)) } fn binary_op( @@ -514,14 +476,18 @@ impl<'a> ConstantSolver<'a> { _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), }; - Ok(self.constants.fetch_or_append( + Ok(self.register_constant(inner, span)) + } + + fn register_constant(&mut self, inner: ConstantInner, span: crate::Span) -> Handle { + self.constants.fetch_or_append( Constant { name: None, specialization: None, inner, }, span, - )) + ) } } From 28c45321e53c3dac8a613e2402d0e336d886ad49 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 3 Nov 2021 22:44:46 -0400 Subject: [PATCH 1430/2212] hlsl: respect array stride in storage buffers (#1507) --- src/back/hlsl/storage.rs | 73 ++++++++++------- tests/in/access.wgsl | 3 +- tests/out/glsl/access.foo.Vertex.glsl | 1 + tests/out/hlsl/access.hlsl | 3 +- tests/out/msl/access.msl | 3 +- tests/out/spv/access.spvasm | 112 +++++++++++++------------- tests/out/wgsl/access.wgsl | 3 +- 7 files changed, 110 insertions(+), 88 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 5840e43ed..b235a061f 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -367,39 +367,22 @@ impl super::Writer<'_, W> { mut cur_expr: Handle, func_ctx: &FunctionCtx, ) -> Result, Error> { + enum AccessIndex { + Expression(Handle), + Constant(u32), + } + enum Parent<'a> { + Array { stride: u32 }, + Struct(&'a [crate::StructMember]), + } self.temp_access_chain.clear(); - loop { - // determine the size of the pointee - let stride = match *func_ctx.info[cur_expr].ty.inner_with(&module.types) { - crate::TypeInner::Pointer { base, class: _ } => { - module.types[base].inner.span(&module.constants) - } - crate::TypeInner::ValuePointer { size, width, .. } => { - size.map_or(1, |s| s as u32) * width as u32 - } - _ => 0, - }; - let (next_expr, sub) = match func_ctx.expressions[cur_expr] { + loop { + let (next_expr, access_index) = match func_ctx.expressions[cur_expr] { crate::Expression::GlobalVariable(handle) => return Ok(handle), - crate::Expression::Access { base, index } => ( - base, - SubAccess::Index { - value: index, - stride, - }, - ), + crate::Expression::Access { base, index } => (base, AccessIndex::Expression(index)), crate::Expression::AccessIndex { base, index } => { - let sub = match *func_ctx.info[base].ty.inner_with(&module.types) { - crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { - crate::TypeInner::Struct { ref members, .. } => { - SubAccess::Offset(members[index as usize].offset) - } - _ => SubAccess::Offset(index * stride), - }, - _ => SubAccess::Offset(index * stride), - }; - (base, sub) + (base, AccessIndex::Constant(index)) } ref other => { return Err(Error::Unimplemented(format!( @@ -408,6 +391,38 @@ impl super::Writer<'_, W> { ))) } }; + + let parent = match *func_ctx.info[next_expr].ty.inner_with(&module.types) { + crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { + crate::TypeInner::Struct { ref members, .. } => Parent::Struct(members), + crate::TypeInner::Array { stride, .. } => Parent::Array { stride }, + crate::TypeInner::Vector { width, .. } => Parent::Array { + stride: width as u32, + }, + crate::TypeInner::Matrix { rows, width, .. } => Parent::Array { + stride: width as u32 * if rows > crate::VectorSize::Bi { 4 } else { 2 }, + }, + _ => unreachable!(), + }, + crate::TypeInner::ValuePointer { width, .. } => Parent::Array { + stride: width as u32, + }, + _ => unreachable!(), + }; + + let sub = match (parent, access_index) { + (Parent::Array { stride }, AccessIndex::Expression(value)) => { + SubAccess::Index { value, stride } + } + (Parent::Array { stride }, AccessIndex::Constant(index)) => { + SubAccess::Offset(stride * index) + } + (Parent::Struct(members), AccessIndex::Constant(index)) => { + SubAccess::Offset(members[index as usize].offset) + } + (Parent::Struct(_), AccessIndex::Expression(_)) => unreachable!(), + }; + self.temp_access_chain.push(sub); cur_expr = next_expr; } diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index f4af84913..4a2228fa3 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -5,7 +5,7 @@ struct Bar { matrix: mat4x4; atom: atomic; arr: [[stride(8)]] array, 2>; - data: [[stride(4)]] array; + data: [[stride(8)]] array; }; [[group(0), binding(0)]] @@ -37,6 +37,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { bar.matrix[1].z = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); bar.arr = array, 2>(vec2(0u), vec2(1u)); + bar.data[1] = 1; // test array indexing var c = array(a, i32(b), 3, 4, 5); diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index 680f52ee5..848bce8cd 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -30,6 +30,7 @@ void main() { _group_0_binding_0.matrix[1][2] = 1.0; _group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); _group_0_binding_0.arr = uvec2[2](uvec2(0u), uvec2(1u)); + _group_0_binding_0.data[1] = 1; c = int[5](a, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 41b7acc84..22f27b881 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -24,7 +24,7 @@ float4 foo(uint vi : SV_VertexID) : SV_Position float4x4 matrix1 = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))}; float b = asfloat(bar.Load(0+48+0)); - int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 4) - 2u)*4+88)); + int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 8) - 2u)*8+88)); const float _e25 = read_from_private(foo1); bar.Store(8+16+0, asuint(1.0)); { @@ -39,6 +39,7 @@ float4 foo(uint vi : SV_VertexID) : SV_Position bar.Store2(72+0, asuint(_value2[0])); bar.Store2(72+8, asuint(_value2[1])); } + bar.Store(8+88, asuint(1)); { int _result[5]={ a, int(b), 3, 4, 5 }; for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 09f011fe4..884e606b3 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -45,11 +45,12 @@ vertex fooOutput foo( metal::float4x4 matrix = bar.matrix; type3 arr = bar.arr; float b = bar.matrix[3].x; - int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 4) - 2u]; + int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 8) - 2u]; float _e25 = read_from_private(foo1); bar.matrix[1].z = 1.0; bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; + bar.data[1] = 1; for(int _i=0; _i<5; ++_i) c.inner[_i] = type11 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index a5864e90e..96127247a 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,14 +1,14 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 114 +; Bound: 115 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %47 "foo" %42 %45 -OpEntryPoint GLCompute %91 "atomics" -OpExecutionMode %91 LocalSize 1 1 1 +OpEntryPoint GLCompute %92 "atomics" +OpExecutionMode %92 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %26 0 "matrix" OpMemberName %26 1 "atom" @@ -22,10 +22,10 @@ OpName %38 "foo" OpName %39 "c" OpName %42 "vi" OpName %47 "foo" -OpName %89 "tmp" -OpName %91 "atomics" +OpName %90 "tmp" +OpName %92 "atomics" OpDecorate %24 ArrayStride 8 -OpDecorate %25 ArrayStride 4 +OpDecorate %25 ArrayStride 8 OpDecorate %26 Block OpMemberDecorate %26 0 Offset 0 OpMemberDecorate %26 0 ColMajor @@ -80,10 +80,10 @@ OpDecorate %45 BuiltIn Position %57 = OpTypePointer StorageBuffer %22 %58 = OpTypePointer StorageBuffer %6 %61 = OpTypePointer StorageBuffer %25 -%81 = OpTypePointer Function %4 -%85 = OpTypeVector %4 4 -%93 = OpTypePointer StorageBuffer %4 -%96 = OpConstant %9 64 +%82 = OpTypePointer Function %4 +%86 = OpTypeVector %4 4 +%94 = OpTypePointer StorageBuffer %4 +%97 = OpConstant %9 64 %34 = OpFunction %6 None %35 %33 = OpFunctionParameter %27 %32 = OpLabel @@ -126,52 +126,54 @@ OpStore %73 %72 %76 = OpCompositeConstruct %24 %74 %75 %77 = OpAccessChain %54 %30 %10 OpStore %77 %76 -%78 = OpConvertFToS %4 %60 -%79 = OpCompositeConstruct %29 %65 %78 %18 %19 %17 -OpStore %39 %79 -%80 = OpIAdd %9 %44 %16 -%82 = OpAccessChain %81 %39 %80 -OpStore %82 %20 -%83 = OpAccessChain %81 %39 %44 -%84 = OpLoad %4 %83 -%86 = OpCompositeConstruct %85 %84 %84 %84 %84 -%87 = OpConvertSToF %22 %86 -%88 = OpMatrixTimesVector %22 %53 %87 -OpStore %45 %88 +%78 = OpAccessChain %28 %30 %8 %16 +OpStore %78 %12 +%79 = OpConvertFToS %4 %60 +%80 = OpCompositeConstruct %29 %65 %79 %18 %19 %17 +OpStore %39 %80 +%81 = OpIAdd %9 %44 %16 +%83 = OpAccessChain %82 %39 %81 +OpStore %83 %20 +%84 = OpAccessChain %82 %39 %44 +%85 = OpLoad %4 %84 +%87 = OpCompositeConstruct %86 %85 %85 %85 %85 +%88 = OpConvertSToF %22 %87 +%89 = OpMatrixTimesVector %22 %53 %88 +OpStore %45 %89 OpReturn OpFunctionEnd -%91 = OpFunction %2 None %48 -%90 = OpLabel -%89 = OpVariable %81 Function -OpBranch %92 -%92 = OpLabel -%94 = OpAccessChain %93 %30 %16 -%95 = OpAtomicLoad %4 %94 %12 %96 -%98 = OpAccessChain %93 %30 %16 -%97 = OpAtomicIAdd %4 %98 %12 %96 %17 -OpStore %89 %97 -%100 = OpAccessChain %93 %30 %16 -%99 = OpAtomicISub %4 %100 %12 %96 %17 -OpStore %89 %99 -%102 = OpAccessChain %93 %30 %16 -%101 = OpAtomicAnd %4 %102 %12 %96 %17 -OpStore %89 %101 -%104 = OpAccessChain %93 %30 %16 -%103 = OpAtomicOr %4 %104 %12 %96 %17 -OpStore %89 %103 -%106 = OpAccessChain %93 %30 %16 -%105 = OpAtomicXor %4 %106 %12 %96 %17 -OpStore %89 %105 -%108 = OpAccessChain %93 %30 %16 -%107 = OpAtomicSMin %4 %108 %12 %96 %17 -OpStore %89 %107 -%110 = OpAccessChain %93 %30 %16 -%109 = OpAtomicSMax %4 %110 %12 %96 %17 -OpStore %89 %109 -%112 = OpAccessChain %93 %30 %16 -%111 = OpAtomicExchange %4 %112 %12 %96 %17 -OpStore %89 %111 -%113 = OpAccessChain %93 %30 %16 -OpAtomicStore %113 %12 %96 %95 +%92 = OpFunction %2 None %48 +%91 = OpLabel +%90 = OpVariable %82 Function +OpBranch %93 +%93 = OpLabel +%95 = OpAccessChain %94 %30 %16 +%96 = OpAtomicLoad %4 %95 %12 %97 +%99 = OpAccessChain %94 %30 %16 +%98 = OpAtomicIAdd %4 %99 %12 %97 %17 +OpStore %90 %98 +%101 = OpAccessChain %94 %30 %16 +%100 = OpAtomicISub %4 %101 %12 %97 %17 +OpStore %90 %100 +%103 = OpAccessChain %94 %30 %16 +%102 = OpAtomicAnd %4 %103 %12 %97 %17 +OpStore %90 %102 +%105 = OpAccessChain %94 %30 %16 +%104 = OpAtomicOr %4 %105 %12 %97 %17 +OpStore %90 %104 +%107 = OpAccessChain %94 %30 %16 +%106 = OpAtomicXor %4 %107 %12 %97 %17 +OpStore %90 %106 +%109 = OpAccessChain %94 %30 %16 +%108 = OpAtomicSMin %4 %109 %12 %97 %17 +OpStore %90 %108 +%111 = OpAccessChain %94 %30 %16 +%110 = OpAtomicSMax %4 %111 %12 %97 %17 +OpStore %90 %110 +%113 = OpAccessChain %94 %30 %16 +%112 = OpAtomicExchange %4 %113 %12 %97 %17 +OpStore %90 %112 +%114 = OpAccessChain %94 %30 %16 +OpAtomicStore %114 %12 %97 %96 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index c041a2047..9b4c7b0e7 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -3,7 +3,7 @@ struct Bar { matrix: mat4x4; atom: atomic; arr: [[stride(8)]] array,2>; - data: [[stride(4)]] array; + data: [[stride(8)]] array; }; [[group(0), binding(0)]] @@ -30,6 +30,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { bar.matrix[1][2] = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); + bar.data[1] = 1; c = array(a, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value: i32 = c[vi]; From 098e4af52f16dc0d9f1e0c143ab62e996c82df02 Mon Sep 17 00:00:00 2001 From: Jonathan Behrens Date: Sat, 6 Nov 2021 18:39:35 -0400 Subject: [PATCH 1431/2212] [spv-out] Fix word order for constants --- src/back/spv/writer.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 43ed95c5e..73066c905 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1009,7 +1009,7 @@ impl Writer { &solo[..] } 8 => { - pair = [(val >> 32) as u32, val as u32]; + pair = [val as u32, (val >> 32) as u32]; &pair } _ => unreachable!(), @@ -1023,7 +1023,7 @@ impl Writer { &solo[..] } 8 => { - pair = [(val >> 32) as u32, val as u32]; + pair = [val as u32, (val >> 32) as u32]; &pair } _ => unreachable!(), @@ -1038,7 +1038,7 @@ impl Writer { } 8 => { let bits = f64::to_bits(val); - pair = [(bits >> 32) as u32, bits as u32]; + pair = [bits as u32, (bits >> 32) as u32]; &pair } _ => unreachable!(), From 8bc3aa824b63e2e7d6cf5c50ea9f21b1a9d8fff9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 9 Nov 2021 09:24:41 -0500 Subject: [PATCH 1432/2212] Refactor namer scheme, fix trailing digits (#1510) --- src/proc/namer.rs | 83 +- tests/out/glsl/access.atomics.Compute.glsl | 4 +- tests/out/glsl/access.foo.Vertex.glsl | 12 +- tests/out/glsl/bits.main.Compute.glsl | 112 +-- tests/out/glsl/image.main.Compute.glsl | 10 +- tests/out/glsl/interpolate.main.Fragment.glsl | 2 +- tests/out/glsl/interpolate.main.Vertex.glsl | 24 +- tests/out/glsl/operators.main.Compute.glsl | 20 +- tests/out/glsl/quad-vert.main.Vertex.glsl | 20 +- tests/out/glsl/quad.main.Fragment.glsl | 4 +- tests/out/glsl/skybox.fs_main.Fragment.glsl | 4 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 12 +- tests/out/hlsl/access.hlsl | 20 +- tests/out/hlsl/empty-global-name.hlsl | 8 +- tests/out/hlsl/image.hlsl | 32 +- tests/out/hlsl/image.hlsl.config | 2 +- tests/out/hlsl/interface.hlsl | 26 +- tests/out/hlsl/interpolate.hlsl | 48 +- tests/out/hlsl/interpolate.hlsl.config | 2 +- .../hlsl/inv-hyperbolic-trig-functions.hlsl | 4 +- tests/out/hlsl/operators.hlsl | 20 +- tests/out/hlsl/quad-vert.hlsl | 28 +- tests/out/hlsl/quad.hlsl | 14 +- tests/out/hlsl/quad.hlsl.config | 2 +- tests/out/hlsl/shadow.hlsl | 8 +- tests/out/hlsl/skybox.hlsl | 24 +- tests/out/hlsl/standard.hlsl | 4 +- tests/out/msl/access.msl | 34 +- tests/out/msl/bits.msl | 114 +-- tests/out/msl/boids.msl | 8 +- tests/out/msl/collatz.msl | 8 +- tests/out/msl/control-flow.msl | 4 +- tests/out/msl/empty-global-name.msl | 14 +- tests/out/msl/empty.msl | 2 +- tests/out/msl/extra.msl | 14 +- tests/out/msl/globals.msl | 6 +- tests/out/msl/image.msl | 48 +- tests/out/msl/interface.msl | 34 +- tests/out/msl/interpolate.msl | 14 +- tests/out/msl/operators.msl | 22 +- tests/out/msl/quad-vert.msl | 46 +- tests/out/msl/quad.msl | 30 +- tests/out/msl/shadow.msl | 4 +- tests/out/msl/skybox.msl | 18 +- tests/out/msl/texture-arg.msl | 6 +- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 8 +- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 28 +- tests/out/wgsl/210-bevy-shader-vert.wgsl | 32 +- tests/out/wgsl/246-collatz-comp.wgsl | 20 +- tests/out/wgsl/277-casting-vert.wgsl | 4 +- tests/out/wgsl/280-matrix-cast-vert.wgsl | 4 +- tests/out/wgsl/484-preprocessor-if-vert.wgsl | 4 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 20 +- tests/out/wgsl/896-push-constant-vert.wgsl | 4 +- .../wgsl/900-implicit-conversions-vert.wgsl | 52 +- tests/out/wgsl/901-lhs-field-select-vert.wgsl | 4 +- .../out/wgsl/931-constant-emitting-vert.wgsl | 6 +- tests/out/wgsl/932-for-loop-if-vert.wgsl | 4 +- tests/out/wgsl/access.wgsl | 18 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 784 +++++++++--------- tests/out/wgsl/bevy-pbr-vert.wgsl | 38 +- tests/out/wgsl/bits.wgsl | 112 +-- tests/out/wgsl/bits_glsl-frag.wgsl | 100 +-- tests/out/wgsl/bool-select-frag.wgsl | 32 +- tests/out/wgsl/clamp-splat-vert.wgsl | 10 +- tests/out/wgsl/constant-array-size-vert.wgsl | 6 +- tests/out/wgsl/empty-global-name.wgsl | 12 +- tests/out/wgsl/expressions-frag.wgsl | 288 +++---- tests/out/wgsl/fma-frag.wgsl | 34 +- .../out/wgsl/global-constant-array-vert.wgsl | 4 +- tests/out/wgsl/image.wgsl | 30 +- tests/out/wgsl/interface.wgsl | 4 +- tests/out/wgsl/interpolate.wgsl | 2 +- .../wgsl/inv-hyperbolic-trig-functions.wgsl | 4 +- tests/out/wgsl/long-form-matrix-vert.wgsl | 4 +- tests/out/wgsl/math-functions-vert.wgsl | 4 +- tests/out/wgsl/operators.wgsl | 20 +- tests/out/wgsl/pointers.wgsl | 8 +- tests/out/wgsl/prepostfix-frag.wgsl | 24 +- tests/out/wgsl/quad-vert.wgsl | 16 +- tests/out/wgsl/quad.wgsl | 4 +- tests/out/wgsl/quad_glsl-frag.wgsl | 8 +- tests/out/wgsl/quad_glsl-vert.wgsl | 16 +- tests/out/wgsl/samplers-frag.wgsl | 568 ++++++------- tests/out/wgsl/skybox.wgsl | 12 +- tests/out/wgsl/swizzle_write-frag.wgsl | 4 +- 86 files changed, 1666 insertions(+), 1665 deletions(-) diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 126d985db..b613060ac 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -2,6 +2,7 @@ use crate::{arena::Handle, FastHashMap, FastHashSet}; use std::borrow::Cow; pub type EntryPointIndex = u16; +const SEPARATOR: char = '_'; #[derive(Debug, Eq, Hash, PartialEq)] pub enum NameKey { @@ -30,23 +31,35 @@ pub struct Namer { impl Namer { /// Return a form of `string` suitable for use as the base of an identifier. /// - /// Retain only alphanumeric and `_` characters. Drop leading digits. Avoid - /// prefixes in [`Namer::reserved_prefixes`]. + /// - Drop leading digits. + /// - Retain only alphanumeric and `_` characters. + /// - Avoid prefixes in [`Namer::reserved_prefixes`]. + /// + /// The return value is a valid identifier prefix in all of Naga's output languages, + /// and it never ends with a `SEPARATOR` character. + /// It is used as a key into the unique table. fn sanitize<'s>(&self, string: &'s str) -> Cow<'s, str> { - let string = string.trim_start_matches(|c: char| c.is_numeric() || c == '_'); + let string = string + .trim_start_matches(|c: char| c.is_numeric()) + .trim_end_matches(SEPARATOR); - let base = if string - .chars() - .all(|c: char| c.is_ascii_alphanumeric() || c == '_') + let base = if !string.is_empty() + && string + .chars() + .all(|c: char| c.is_ascii_alphanumeric() || c == '_') { Cow::Borrowed(string) } else { - Cow::Owned( - string - .chars() - .filter(|&c| c.is_ascii_alphanumeric() || c == '_') - .collect::(), - ) + let mut filtered = string + .chars() + .filter(|&c| c.is_ascii_alphanumeric() || c == '_') + .collect::(); + let stripped_len = filtered.trim_end_matches(SEPARATOR).len(); + filtered.truncate(stripped_len); + if filtered.is_empty() { + filtered.push_str("unnamed"); + } + Cow::Owned(filtered) }; for prefix in &self.reserved_prefixes { @@ -69,14 +82,10 @@ impl Namer { /// Guarantee uniqueness by applying a numeric suffix when necessary. If `label_raw` /// itself ends with digits, separate them from the suffix with an underscore. pub fn call(&mut self, label_raw: &str) -> String { - use std::fmt::Write; // for write!-ing to Strings + use std::fmt::Write as _; // for write!-ing to Strings let base = self.sanitize(label_raw); - let separator = if base.ends_with(char::is_numeric) { - "_" - } else { - "" - }; + debug_assert!(!base.is_empty() && !base.ends_with(SEPARATOR)); // This would seem to be a natural place to use `HashMap::entry`. However, `entry` // requires an owned key, and we'd like to avoid heap-allocating strings we're @@ -88,28 +97,18 @@ impl Namer { *count += 1; // Add the suffix. This may fit in base's existing allocation. let mut suffixed = base.into_owned(); - write!(&mut suffixed, "{}{}", separator, *count).unwrap(); + write!(&mut suffixed, "{}{}", SEPARATOR, *count).unwrap(); suffixed } None => { - let mut count = 0; - let mut suffixed = Cow::Borrowed(base.as_ref()); - while self.keywords.contains(suffixed.as_ref()) { - count += 1; - // Try to reuse suffixed's allocation. - let mut buf = suffixed.into_owned(); - buf.clear(); - write!(&mut buf, "{}{}{}", base, separator, count).unwrap(); - suffixed = Cow::Owned(buf); + let mut suffixed = base.to_string(); + if base.ends_with(char::is_numeric) || self.keywords.contains(base.as_ref()) { + suffixed.push(SEPARATOR); } - // Produce our return value, which must be an owned string. This allocates - // only if we haven't already done so earlier. - let suffixed = suffixed.into_owned(); - + debug_assert!(!self.keywords.contains(&suffixed)); // `self.unique` wants to own its keys. This allocates only if we haven't // already done so earlier. - self.unique.insert(base.into_owned(), count); - + self.unique.insert(base.into_owned(), 0); suffixed } } @@ -117,13 +116,7 @@ impl Namer { pub fn call_or(&mut self, label: &Option, fallback: &str) -> String { self.call(match *label { - Some(ref name) => { - if name.trim().is_empty() { - fallback - } else { - name - } - } + Some(ref name) => name, None => fallback, }) } @@ -258,3 +251,11 @@ impl Namer { } } } + +#[test] +fn test() { + let mut namer = Namer::default(); + assert_eq!(namer.call("x"), "x"); + assert_eq!(namer.call("x"), "x_1"); + assert_eq!(namer.call("x1"), "x1_"); +} diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 81eb83e53..0145ad498 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -13,8 +13,8 @@ layout(std430) buffer Bar_block_0Cs { } _group_0_binding_0; -float read_from_private(inout float foo2) { - float _e2 = foo2; +float read_from_private(inout float foo_2) { + float _e2 = foo_2; return _e2; } diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index 848bce8cd..d4502b031 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -11,22 +11,22 @@ layout(std430) buffer Bar_block_0Vs { } _group_0_binding_0; -float read_from_private(inout float foo2) { - float _e2 = foo2; +float read_from_private(inout float foo_2) { + float _e2 = foo_2; return _e2; } void main() { uint vi = uint(gl_VertexID); - float foo1 = 0.0; + float foo_1 = 0.0; int c[5]; - float baz = foo1; - foo1 = 1.0; + float baz = foo_1; + foo_1 = 1.0; mat4x4 matrix = _group_0_binding_0.matrix; uvec2 arr[2] = _group_0_binding_0.arr; float b = _group_0_binding_0.matrix[3][0]; int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)]; - float _e25 = read_from_private(foo1); + float _e25 = read_from_private(foo_1); _group_0_binding_0.matrix[1][2] = 1.0; _group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); _group_0_binding_0.arr = uvec2[2](uvec2(0u), uvec2(1u)); diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl index af5eaec56..303cdbc44 100644 --- a/tests/out/glsl/bits.main.Compute.glsl +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -8,83 +8,83 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; void main() { int i = 0; - ivec2 i2 = ivec2(0, 0); - ivec3 i3 = ivec3(0, 0, 0); - ivec4 i4 = ivec4(0, 0, 0, 0); + ivec2 i2_ = ivec2(0, 0); + ivec3 i3_ = ivec3(0, 0, 0); + ivec4 i4_ = ivec4(0, 0, 0, 0); uint u = 0u; - uvec2 u2 = uvec2(0u, 0u); - uvec3 u3 = uvec3(0u, 0u, 0u); - uvec4 u4 = uvec4(0u, 0u, 0u, 0u); - vec2 f2 = vec2(0.0, 0.0); - vec4 f4 = vec4(0.0, 0.0, 0.0, 0.0); - i2 = ivec2(0); - i3 = ivec3(0); - i4 = ivec4(0); - u2 = uvec2(0u); - u3 = uvec3(0u); - u4 = uvec4(0u); - f2 = vec2(0.0); - f4 = vec4(0.0); - vec4 _e28 = f4; + uvec2 u2_ = uvec2(0u, 0u); + uvec3 u3_ = uvec3(0u, 0u, 0u); + uvec4 u4_ = uvec4(0u, 0u, 0u, 0u); + vec2 f2_ = vec2(0.0, 0.0); + vec4 f4_ = vec4(0.0, 0.0, 0.0, 0.0); + i2_ = ivec2(0); + i3_ = ivec3(0); + i4_ = ivec4(0); + u2_ = uvec2(0u); + u3_ = uvec3(0u); + u4_ = uvec4(0u); + f2_ = vec2(0.0); + f4_ = vec4(0.0); + vec4 _e28 = f4_; u = packSnorm4x8(_e28); - vec4 _e30 = f4; + vec4 _e30 = f4_; u = packUnorm4x8(_e30); - vec2 _e32 = f2; + vec2 _e32 = f2_; u = packSnorm2x16(_e32); - vec2 _e34 = f2; + vec2 _e34 = f2_; u = packUnorm2x16(_e34); - vec2 _e36 = f2; + vec2 _e36 = f2_; u = packHalf2x16(_e36); uint _e38 = u; - f4 = unpackSnorm4x8(_e38); + f4_ = unpackSnorm4x8(_e38); uint _e40 = u; - f4 = unpackUnorm4x8(_e40); + f4_ = unpackUnorm4x8(_e40); uint _e42 = u; - f2 = unpackSnorm2x16(_e42); + f2_ = unpackSnorm2x16(_e42); uint _e44 = u; - f2 = unpackUnorm2x16(_e44); + f2_ = unpackUnorm2x16(_e44); uint _e46 = u; - f2 = unpackHalf2x16(_e46); + f2_ = unpackHalf2x16(_e46); int _e48 = i; int _e49 = i; i = bitfieldInsert(_e48, _e49, int(5u), int(10u)); - ivec2 _e53 = i2; - ivec2 _e54 = i2; - i2 = bitfieldInsert(_e53, _e54, int(5u), int(10u)); - ivec3 _e58 = i3; - ivec3 _e59 = i3; - i3 = bitfieldInsert(_e58, _e59, int(5u), int(10u)); - ivec4 _e63 = i4; - ivec4 _e64 = i4; - i4 = bitfieldInsert(_e63, _e64, int(5u), int(10u)); + ivec2 _e53 = i2_; + ivec2 _e54 = i2_; + i2_ = bitfieldInsert(_e53, _e54, int(5u), int(10u)); + ivec3 _e58 = i3_; + ivec3 _e59 = i3_; + i3_ = bitfieldInsert(_e58, _e59, int(5u), int(10u)); + ivec4 _e63 = i4_; + ivec4 _e64 = i4_; + i4_ = bitfieldInsert(_e63, _e64, int(5u), int(10u)); uint _e68 = u; uint _e69 = u; u = bitfieldInsert(_e68, _e69, int(5u), int(10u)); - uvec2 _e73 = u2; - uvec2 _e74 = u2; - u2 = bitfieldInsert(_e73, _e74, int(5u), int(10u)); - uvec3 _e78 = u3; - uvec3 _e79 = u3; - u3 = bitfieldInsert(_e78, _e79, int(5u), int(10u)); - uvec4 _e83 = u4; - uvec4 _e84 = u4; - u4 = bitfieldInsert(_e83, _e84, int(5u), int(10u)); + uvec2 _e73 = u2_; + uvec2 _e74 = u2_; + u2_ = bitfieldInsert(_e73, _e74, int(5u), int(10u)); + uvec3 _e78 = u3_; + uvec3 _e79 = u3_; + u3_ = bitfieldInsert(_e78, _e79, int(5u), int(10u)); + uvec4 _e83 = u4_; + uvec4 _e84 = u4_; + u4_ = bitfieldInsert(_e83, _e84, int(5u), int(10u)); int _e88 = i; i = bitfieldExtract(_e88, int(5u), int(10u)); - ivec2 _e92 = i2; - i2 = bitfieldExtract(_e92, int(5u), int(10u)); - ivec3 _e96 = i3; - i3 = bitfieldExtract(_e96, int(5u), int(10u)); - ivec4 _e100 = i4; - i4 = bitfieldExtract(_e100, int(5u), int(10u)); + ivec2 _e92 = i2_; + i2_ = bitfieldExtract(_e92, int(5u), int(10u)); + ivec3 _e96 = i3_; + i3_ = bitfieldExtract(_e96, int(5u), int(10u)); + ivec4 _e100 = i4_; + i4_ = bitfieldExtract(_e100, int(5u), int(10u)); uint _e104 = u; u = bitfieldExtract(_e104, int(5u), int(10u)); - uvec2 _e108 = u2; - u2 = bitfieldExtract(_e108, int(5u), int(10u)); - uvec3 _e112 = u3; - u3 = bitfieldExtract(_e112, int(5u), int(10u)); - uvec4 _e116 = u4; - u4 = bitfieldExtract(_e116, int(5u), int(10u)); + uvec2 _e108 = u2_; + u2_ = bitfieldExtract(_e108, int(5u), int(10u)); + uvec3 _e112 = u3_; + u3_ = bitfieldExtract(_e112, int(5u), int(10u)); + uvec4 _e116 = u4_; + u4_ = bitfieldExtract(_e116, int(5u), int(10u)); return; } diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl index 17ed23538..be6b7ed97 100644 --- a/tests/out/glsl/image.main.Compute.glsl +++ b/tests/out/glsl/image.main.Compute.glsl @@ -21,11 +21,11 @@ void main() { uvec3 local_id = gl_LocalInvocationID; ivec2 dim = imageSize(_group_0_binding_1).xy; ivec2 itc = ((dim * ivec2(local_id.xy)) % ivec2(10, 20)); - uvec4 value1 = texelFetch(_group_0_binding_0, itc, int(local_id.z)); - uvec4 value2 = texelFetch(_group_0_binding_3, itc, int(local_id.z)); - uvec4 value4 = imageLoad(_group_0_binding_1, itc); - uvec4 value5 = texelFetch(_group_0_binding_5, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); - imageStore(_group_0_binding_2, ivec2(itc.x, 0.0), (((value1 + value2) + value4) + value5)); + uvec4 value1_ = texelFetch(_group_0_binding_0, itc, int(local_id.z)); + uvec4 value2_ = texelFetch(_group_0_binding_3, itc, int(local_id.z)); + uvec4 value4_ = imageLoad(_group_0_binding_1, itc); + uvec4 value5_ = texelFetch(_group_0_binding_5, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); + imageStore(_group_0_binding_2, ivec2(itc.x, 0.0), (((value1_ + value2_) + value4_) + value5_)); return; } diff --git a/tests/out/glsl/interpolate.main.Fragment.glsl b/tests/out/glsl/interpolate.main.Fragment.glsl index b41599730..918e78b9c 100644 --- a/tests/out/glsl/interpolate.main.Fragment.glsl +++ b/tests/out/glsl/interpolate.main.Fragment.glsl @@ -1,7 +1,7 @@ #version 400 core struct FragmentInput { vec4 position; - uint flat1; + uint flat_; float linear; vec2 linear_centroid; vec3 linear_sample; diff --git a/tests/out/glsl/interpolate.main.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl index 76cdd0ac0..40d64ccf0 100644 --- a/tests/out/glsl/interpolate.main.Vertex.glsl +++ b/tests/out/glsl/interpolate.main.Vertex.glsl @@ -1,7 +1,7 @@ #version 400 core struct FragmentInput { vec4 position; - uint flat1; + uint flat_; float linear; vec2 linear_centroid; vec3 linear_sample; @@ -19,18 +19,18 @@ smooth centroid out float _vs2fs_location5; smooth sample out float _vs2fs_location6; void main() { - FragmentInput out1; - out1.position = vec4(2.0, 4.0, 5.0, 6.0); - out1.flat1 = 8u; - out1.linear = 27.0; - out1.linear_centroid = vec2(64.0, 125.0); - out1.linear_sample = vec3(216.0, 343.0, 512.0); - out1.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); - out1.perspective_centroid = 2197.0; - out1.perspective_sample = 2744.0; - FragmentInput _e30 = out1; + FragmentInput out_; + out_.position = vec4(2.0, 4.0, 5.0, 6.0); + out_.flat_ = 8u; + out_.linear = 27.0; + out_.linear_centroid = vec2(64.0, 125.0); + out_.linear_sample = vec3(216.0, 343.0, 512.0); + out_.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + out_.perspective_centroid = 2197.0; + out_.perspective_sample = 2744.0; + FragmentInput _e30 = out_; gl_Position = _e30.position; - _vs2fs_location0 = _e30.flat1; + _vs2fs_location0 = _e30.flat_; _vs2fs_location1 = _e30.linear; _vs2fs_location2 = _e30.linear_centroid; _vs2fs_location3 = _e30.linear_sample; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 4a03f215d..ac6ecfa62 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -12,15 +12,15 @@ struct Foo { vec4 builtins() { - int s1 = (true ? 1 : 0); - vec4 s2 = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); - vec4 s3 = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), bvec4(false, false, false, false)); - vec4 m1 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - vec4 m2 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); - float b1 = intBitsToFloat(ivec4(1, 1, 1, 1).x); - vec4 b2 = intBitsToFloat(ivec4(1, 1, 1, 1)); + int s1_ = (true ? 1 : 0); + vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); + vec4 s3_ = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), bvec4(false, false, false, false)); + vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); + vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + float b1_ = intBitsToFloat(ivec4(1, 1, 1, 1).x); + vec4 b2_ = intBitsToFloat(ivec4(1, 1, 1, 1)); ivec4 v_i32_zero = ivec4(vec4(0.0, 0.0, 0.0, 0.0)); - return (((((vec4((ivec4(s1) + v_i32_zero)) + s2) + m1) + m2) + vec4(b1)) + b2); + return (((((vec4((ivec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } vec4 splat() { @@ -50,8 +50,8 @@ float constructors() { } void modulo() { - int a1 = (1 % 1); - float b1 = (1.0 - 1.0 * trunc(1.0 / 1.0)); + int a_1 = (1 % 1); + float b_1 = (1.0 - 1.0 * trunc(1.0 / 1.0)); ivec3 c = (ivec3(1) % ivec3(1)); vec3 d = (vec3(1.0) - vec3(1.0) * trunc(vec3(1.0) / vec3(1.0))); } diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index d873765dd..26df41767 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -3,14 +3,14 @@ precision highp float; precision highp int; -struct type9 { +struct type_9 { vec2 member; vec4 gen_gl_Position; }; vec2 v_uv = vec2(0.0, 0.0); -vec2 a_uv1 = vec2(0.0, 0.0); +vec2 a_uv_1 = vec2(0.0, 0.0); struct gen_gl_PerVertex_block_0Vs { vec4 gen_gl_Position; @@ -19,16 +19,16 @@ struct gen_gl_PerVertex_block_0Vs { float gen_gl_CullDistance[1]; } perVertexStruct; -vec2 a_pos1 = vec2(0.0, 0.0); +vec2 a_pos_1 = vec2(0.0, 0.0); layout(location = 1) in vec2 _p2vs_location1; layout(location = 0) in vec2 _p2vs_location0; layout(location = 0) smooth out vec2 _vs2fs_location0; -void main2() { - vec2 _e12 = a_uv1; +void main_1() { + vec2 _e12 = a_uv_1; v_uv = _e12; - vec2 _e13 = a_pos1; + vec2 _e13 = a_pos_1; perVertexStruct.gen_gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); return; } @@ -36,12 +36,12 @@ void main2() { void main() { vec2 a_uv = _p2vs_location1; vec2 a_pos = _p2vs_location0; - a_uv1 = a_uv; - a_pos1 = a_pos; - main2(); + a_uv_1 = a_uv; + a_pos_1 = a_pos; + main_1(); vec2 _e7 = v_uv; vec4 _e8 = perVertexStruct.gen_gl_Position; - type9 _tmp_return = type9(_e7, _e8); + type_9 _tmp_return = type_9(_e7, _e8); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/glsl/quad.main.Fragment.glsl b/tests/out/glsl/quad.main.Fragment.glsl index 6b03a6515..b290ed5a0 100644 --- a/tests/out/glsl/quad.main.Fragment.glsl +++ b/tests/out/glsl/quad.main.Fragment.glsl @@ -14,8 +14,8 @@ smooth in vec2 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { - vec2 uv1 = _vs2fs_location0; - vec4 color = texture(_group_0_binding_0, vec2(uv1)); + vec2 uv_1 = _vs2fs_location0; + vec4 color = texture(_group_0_binding_0, vec2(uv_1)); if ((color.w == 0.0)) { discard; } diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index fa0b46f02..08b733b84 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -14,8 +14,8 @@ layout(location = 0) smooth in vec3 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { - VertexOutput in1 = VertexOutput(gl_FragCoord, _vs2fs_location0); - vec4 _e5 = texture(_group_0_binding_1, vec3(in1.uv)); + VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0); + vec4 _e5 = texture(_group_0_binding_1, vec3(in_.uv)); _fs2p_location0 = _e5; return; } diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index 34f21901d..06494a70f 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -17,12 +17,12 @@ layout(location = 0) smooth out vec3 _vs2fs_location0; void main() { uint vertex_index = uint(gl_VertexID); - int tmp1 = 0; - int tmp2 = 0; - tmp1 = (int(vertex_index) / 2); - tmp2 = (int(vertex_index) & 1); - int _e10 = tmp1; - int _e16 = tmp2; + int tmp1_ = 0; + int tmp2_ = 0; + tmp1_ = (int(vertex_index) / 2); + tmp2_ = (int(vertex_index) & 1); + int _e10 = tmp1_; + int _e16 = tmp2_; vec4 pos = vec4(((float(_e10) * 4.0) - 1.0), ((float(_e16) * 4.0) - 1.0), 0.0, 1.0); vec4 _e27 = _group_0_binding_0.view[0]; vec4 _e31 = _group_0_binding_0.view[1]; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 22f27b881..91b15a93c 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -1,9 +1,9 @@ RWByteAddressBuffer bar : register(u0); -float read_from_private(inout float foo2) +float read_from_private(inout float foo_2) { - float _expr2 = foo2; + float _expr2 = foo_2; return _expr2; } @@ -16,16 +16,16 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer) float4 foo(uint vi : SV_VertexID) : SV_Position { - float foo1 = 0.0; + float foo_1 = 0.0; int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; - float baz = foo1; - foo1 = 1.0; - float4x4 matrix1 = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); + float baz = foo_1; + foo_1 = 1.0; + float4x4 matrix_ = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))}; float b = asfloat(bar.Load(0+48+0)); int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 8) - 2u)*8+88)); - const float _e25 = read_from_private(foo1); + const float _e25 = read_from_private(foo_1); bar.Store(8+16+0, asuint(1.0)); { float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx)); @@ -46,7 +46,7 @@ float4 foo(uint vi : SV_VertexID) : SV_Position } c[(vi + 1u)] = 42; int value = c[vi]; - return mul(float4(int4(value.xxxx)), matrix1); + return mul(float4(int4(value.xxxx)), matrix_); } [numthreads(1, 1, 1)] @@ -54,7 +54,7 @@ void atomics() { int tmp = (int)0; - int value1 = asint(bar.Load(64)); + int value_1 = asint(bar.Load(64)); int _e6; bar.InterlockedAdd(64, 5, _e6); tmp = _e6; int _e9; bar.InterlockedAdd(64, -5, _e9); @@ -71,6 +71,6 @@ void atomics() tmp = _e24; int _e27; bar.InterlockedExchange(64, 5, _e27); tmp = _e27; - bar.Store(64, asuint(value1)); + bar.Store(64, asuint(value_1)); return; } diff --git a/tests/out/hlsl/empty-global-name.hlsl b/tests/out/hlsl/empty-global-name.hlsl index 5bc384866..18c5831de 100644 --- a/tests/out/hlsl/empty-global-name.hlsl +++ b/tests/out/hlsl/empty-global-name.hlsl @@ -1,14 +1,14 @@ -struct type1 { +struct type_1 { int member; }; -RWByteAddressBuffer global : register(u0); +RWByteAddressBuffer unnamed : register(u0); void function() { - int _expr8 = asint(global.Load(0)); - global.Store(0, asuint((_expr8 + 1))); + int _expr8 = asint(unnamed.Load(0)); + unnamed.Store(0, asuint((_expr8 + 1))); return; } diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 9f04aa0cb..796c74841 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -29,21 +29,21 @@ void main(uint3 local_id : SV_GroupThreadID) { int2 dim = NagaRWDimensions2D(image_storage_src); int2 itc = ((dim * int2(local_id.xy)) % int2(10, 20)); - uint4 value1 = image_mipmapped_src.Load(int3(itc, int(local_id.z))); - uint4 value2 = image_multisampled_src.Load(itc, int(local_id.z)); - uint4 value4 = image_storage_src.Load(itc); - uint4 value5 = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); - image_dst[itc.x] = (((value1 + value2) + value4) + value5); + uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(local_id.z))); + uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z)); + uint4 value4_ = image_storage_src.Load(itc); + uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); + image_dst[itc.x] = (((value1_ + value2_) + value4_) + value5_); return; } [numthreads(16, 1, 1)] -void depth_load(uint3 local_id1 : SV_GroupThreadID) +void depth_load(uint3 local_id_1 : SV_GroupThreadID) { - int2 dim1 = NagaRWDimensions2D(image_storage_src); - int2 itc1 = ((dim1 * int2(local_id1.xy)) % int2(10, 20)); - float val = image_depth_multisampled_src.Load(itc1, int(local_id1.z)).x; - image_dst[itc1.x] = uint4(uint(val).xxxx); + int2 dim_1 = NagaRWDimensions2D(image_storage_src); + int2 itc_1 = ((dim_1 * int2(local_id_1.xy)) % int2(10, 20)); + float val = image_depth_multisampled_src.Load(itc_1, int(local_id_1.z)).x; + image_dst[itc_1.x] = uint4(uint(val).xxxx); return; } @@ -207,11 +207,11 @@ float4 levels_queries() : SV_Position int num_layers_cube = NagaNumLayersCubeArray(image_cube_array); int num_levels_3d = NagaNumLevels3D(image_3d); int num_samples_aa = NagaMSNumSamples2D(image_aa); - int sum1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); - return float4(float(sum1).xxxx); + int sum_1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); + return float4(float(sum_1).xxxx); } -float4 sample1() : SV_Target0 +float4 sample_() : SV_Target0 { float2 tc = float2(0.5.xx); float4 s1d = image_1d.Sample(sampler_reg, tc.x); @@ -224,8 +224,8 @@ float4 sample1() : SV_Target0 float sample_comparison() : SV_Target0 { - float2 tc1 = float2(0.5.xx); - float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc1, 0.5); - float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc1, 0.5); + float2 tc_1 = float2(0.5.xx); + float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc_1, 0.5); + float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc_1, 0.5); return (s2d_depth + s2d_depth_level); } diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config index 4f6c8ecdb..28af7d931 100644 --- a/tests/out/hlsl/image.hlsl.config +++ b/tests/out/hlsl/image.hlsl.config @@ -1,3 +1,3 @@ vertex=(queries:vs_5_1 levels_queries:vs_5_1 ) -fragment=(sample1:ps_5_1 sample_comparison:ps_5_1 ) +fragment=(sample_:ps_5_1 sample_comparison:ps_5_1 ) compute=(main:cs_5_1 depth_load:cs_5_1 ) diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 38d6cb820..99ed31acd 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -24,11 +24,11 @@ struct VertexOutput_vertex { }; struct FragmentInput_fragment { - float varying1 : LOC1; - float4 position1 : SV_Position; - bool front_facing1 : SV_IsFrontFace; - uint sample_index1 : SV_SampleIndex; - uint sample_mask1 : SV_Coverage; + float varying_1 : LOC1; + float4 position_1 : SV_Position; + bool front_facing_1 : SV_IsFrontFace; + uint sample_index_1 : SV_SampleIndex; + uint sample_mask_1 : SV_Coverage; }; VertexOutput ConstructVertexOutput(float4 arg0, float arg1) { @@ -42,8 +42,8 @@ VertexOutput_vertex vertex(uint vertex_index : SV_VertexID, uint instance_index { uint tmp = (((_NagaConstants.base_vertex + vertex_index) + (_NagaConstants.base_instance + instance_index)) + color); const VertexOutput vertexoutput = ConstructVertexOutput(float4(1.0.xxxx), float(tmp)); - const VertexOutput_vertex vertexoutput1 = { vertexoutput.varying, vertexoutput.position }; - return vertexoutput1; + const VertexOutput_vertex vertexoutput_1 = { vertexoutput.varying, vertexoutput.position }; + return vertexoutput_1; } FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) { @@ -56,13 +56,13 @@ FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) { FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) { - VertexOutput in1 = { fragmentinput_fragment.position1, fragmentinput_fragment.varying1 }; - bool front_facing = fragmentinput_fragment.front_facing1; - uint sample_index = fragmentinput_fragment.sample_index1; - uint sample_mask = fragmentinput_fragment.sample_mask1; + VertexOutput in_ = { fragmentinput_fragment.position_1, fragmentinput_fragment.varying_1 }; + bool front_facing = fragmentinput_fragment.front_facing_1; + uint sample_index = fragmentinput_fragment.sample_index_1; + uint sample_mask = fragmentinput_fragment.sample_mask_1; uint mask = (sample_mask & (1u << sample_index)); - float color1 = (front_facing ? 1.0 : 0.0); - const FragmentOutput fragmentoutput = ConstructFragmentOutput(in1.varying, mask, color1); + float color_1 = (front_facing ? 1.0 : 0.0); + const FragmentOutput fragmentoutput = ConstructFragmentOutput(in_.varying, mask, color_1); return fragmentoutput; } diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index 788542e9e..7372b0f81 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -2,7 +2,7 @@ struct FragmentInput { float4 position : SV_Position; nointerpolation uint flat : LOC0; - noperspective float linear1 : LOC1; + noperspective float linear_ : LOC1; noperspective centroid float2 linear_centroid : LOC2; noperspective sample float3 linear_sample : LOC3; linear float4 perspective : LOC4; @@ -12,7 +12,7 @@ struct FragmentInput { struct VertexOutput_main { uint flat : LOC0; - float linear1 : LOC1; + float linear_ : LOC1; float2 linear_centroid : LOC2; float3 linear_sample : LOC3; float4 perspective : LOC4; @@ -22,36 +22,36 @@ struct VertexOutput_main { }; struct FragmentInput_main { - uint flat1 : LOC0; - float linear2 : LOC1; - float2 linear_centroid1 : LOC2; - float3 linear_sample1 : LOC3; - float4 perspective1 : LOC4; - float perspective_centroid1 : LOC5; - float perspective_sample1 : LOC6; - float4 position1 : SV_Position; + uint flat_1 : LOC0; + float linear_1 : LOC1; + float2 linear_centroid_1 : LOC2; + float3 linear_sample_1 : LOC3; + float4 perspective_1 : LOC4; + float perspective_centroid_1 : LOC5; + float perspective_sample_1 : LOC6; + float4 position_1 : SV_Position; }; VertexOutput_main main() { - FragmentInput out1 = (FragmentInput)0; + FragmentInput out_ = (FragmentInput)0; - out1.position = float4(2.0, 4.0, 5.0, 6.0); - out1.flat = 8u; - out1.linear1 = 27.0; - out1.linear_centroid = float2(64.0, 125.0); - out1.linear_sample = float3(216.0, 343.0, 512.0); - out1.perspective = float4(729.0, 1000.0, 1331.0, 1728.0); - out1.perspective_centroid = 2197.0; - out1.perspective_sample = 2744.0; - FragmentInput _expr30 = out1; + out_.position = float4(2.0, 4.0, 5.0, 6.0); + out_.flat = 8u; + out_.linear_ = 27.0; + out_.linear_centroid = float2(64.0, 125.0); + out_.linear_sample = float3(216.0, 343.0, 512.0); + out_.perspective = float4(729.0, 1000.0, 1331.0, 1728.0); + out_.perspective_centroid = 2197.0; + out_.perspective_sample = 2744.0; + FragmentInput _expr30 = out_; const FragmentInput fragmentinput = _expr30; - const VertexOutput_main fragmentinput1 = { fragmentinput.flat, fragmentinput.linear1, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position }; - return fragmentinput1; + const VertexOutput_main fragmentinput_1 = { fragmentinput.flat, fragmentinput.linear_, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position }; + return fragmentinput_1; } -void main1(FragmentInput_main fragmentinput_main) +void main_1(FragmentInput_main fragmentinput_main) { - FragmentInput val = { fragmentinput_main.position1, fragmentinput_main.flat1, fragmentinput_main.linear2, fragmentinput_main.linear_centroid1, fragmentinput_main.linear_sample1, fragmentinput_main.perspective1, fragmentinput_main.perspective_centroid1, fragmentinput_main.perspective_sample1 }; + FragmentInput val = { fragmentinput_main.position_1, fragmentinput_main.flat_1, fragmentinput_main.linear_1, fragmentinput_main.linear_centroid_1, fragmentinput_main.linear_sample_1, fragmentinput_main.perspective_1, fragmentinput_main.perspective_centroid_1, fragmentinput_main.perspective_sample_1 }; return; } diff --git a/tests/out/hlsl/interpolate.hlsl.config b/tests/out/hlsl/interpolate.hlsl.config index b0a8e4ba9..5a8cb0c2e 100644 --- a/tests/out/hlsl/interpolate.hlsl.config +++ b/tests/out/hlsl/interpolate.hlsl.config @@ -1,3 +1,3 @@ vertex=(main:vs_5_1 ) -fragment=(main1:ps_5_1 ) +fragment=(main_1:ps_5_1 ) compute=() diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl index 5857257ff..23fdc45f4 100644 --- a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl +++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl @@ -1,7 +1,7 @@ static float a = (float)0; -void main1() +void main_1() { float b = (float)0; float c = (float)0; @@ -18,5 +18,5 @@ void main1() void main() { - main1(); + main_1(); } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index d624c32aa..1e35bb0a9 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -10,15 +10,15 @@ struct Foo { float4 builtins() { - int s1 = (true ? 1 : 0); - float4 s2 = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0)); - float4 s3 = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); - float4 m1 = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); - float4 m2 = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); - float b1 = float(int4(1, 1, 1, 1).x); - float4 b2 = float4(int4(1, 1, 1, 1)); + int s1_ = (true ? 1 : 0); + float4 s2_ = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0)); + float4 s3_ = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); + float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); + float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + float b1_ = float(int4(1, 1, 1, 1).x); + float4 b2_ = float4(int4(1, 1, 1, 1)); int4 v_i32_zero = int4(float4(0.0, 0.0, 0.0, 0.0)); - return (((((float4((int4(s1.xxxx) + v_i32_zero)) + s2) + m1) + m2) + float4(b1.xxxx)) + b2); + return (((((float4((int4(s1_.xxxx) + v_i32_zero)) + s2_) + m1_) + m2_) + float4(b1_.xxxx)) + b2_); } float4 splat() @@ -61,8 +61,8 @@ float constructors() void modulo() { - int a1 = (1 % 1); - float b1 = (1.0 % 1.0); + int a_1 = (1 % 1); + float b_1 = (1.0 % 1.0); int3 c = (int3(1.xxx) % int3(1.xxx)); float3 d = (float3(1.0.xxx) % float3(1.0.xxx)); } diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index ded5170b7..7b926b106 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -6,32 +6,32 @@ struct gl_PerVertex { float gl_CullDistance[1] : SV_CullDistance; }; -struct type9 { +struct type_9 { linear float2 member : LOC0; float4 gl_Position : SV_Position; }; static float2 v_uv = (float2)0; -static float2 a_uv1 = (float2)0; +static float2 a_uv_1 = (float2)0; static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, { 0.0 }, { 0.0 } }; -static float2 a_pos1 = (float2)0; +static float2 a_pos_1 = (float2)0; struct VertexOutput_main { float2 member : LOC0; float4 gl_Position : SV_Position; }; -void main1() +void main_1() { - float2 _expr12 = a_uv1; + float2 _expr12 = a_uv_1; v_uv = _expr12; - float2 _expr13 = a_pos1; + float2 _expr13 = a_pos_1; perVertexStruct.gl_Position = float4(_expr13.x, _expr13.y, 0.0, 1.0); return; } -type9 Constructtype9(float2 arg0, float4 arg1) { - type9 ret; +type_9 Constructtype_9(float2 arg0, float4 arg1) { + type_9 ret; ret.member = arg0; ret.gl_Position = arg1; return ret; @@ -39,12 +39,12 @@ type9 Constructtype9(float2 arg0, float4 arg1) { VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0) { - a_uv1 = a_uv; - a_pos1 = a_pos; - main1(); + a_uv_1 = a_uv; + a_pos_1 = a_pos; + main_1(); float2 _expr7 = v_uv; float4 _expr8 = perVertexStruct.gl_Position; - const type9 type9 = Constructtype9(_expr7, _expr8); - const VertexOutput_main type9_1 = { type9.member, type9.gl_Position }; - return type9_1; + const type_9 type_9_ = Constructtype_9(_expr7, _expr8); + const VertexOutput_main type_9_1 = { type_9_.member, type_9_.gl_Position }; + return type_9_1; } diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index cde665800..1a6c3caaf 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -9,12 +9,12 @@ Texture2D u_texture : register(t0); SamplerState u_sampler : register(s1); struct VertexOutput_main { - float2 uv2 : LOC0; + float2 uv_2 : LOC0; float4 position : SV_Position; }; struct FragmentInput_main { - float2 uv3 : LOC0; + float2 uv_3 : LOC0; }; VertexOutput ConstructVertexOutput(float2 arg0, float4 arg1) { @@ -27,14 +27,14 @@ VertexOutput ConstructVertexOutput(float2 arg0, float4 arg1) { VertexOutput_main main(float2 pos : LOC0, float2 uv : LOC1) { const VertexOutput vertexoutput = ConstructVertexOutput(uv, float4((c_scale * pos), 0.0, 1.0)); - const VertexOutput_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position }; - return vertexoutput1; + const VertexOutput_main vertexoutput_1 = { vertexoutput.uv, vertexoutput.position }; + return vertexoutput_1; } -float4 main1(FragmentInput_main fragmentinput_main) : SV_Target0 +float4 main_1(FragmentInput_main fragmentinput_main) : SV_Target0 { - float2 uv1 = fragmentinput_main.uv3; - float4 color = u_texture.Sample(u_sampler, uv1); + float2 uv_1 = fragmentinput_main.uv_3; + float4 color = u_texture.Sample(u_sampler, uv_1); if ((color.w == 0.0)) { discard; } diff --git a/tests/out/hlsl/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config index 24b516da9..7678a4e57 100644 --- a/tests/out/hlsl/quad.hlsl.config +++ b/tests/out/hlsl/quad.hlsl.config @@ -1,3 +1,3 @@ vertex=(main:vs_5_1 ) -fragment=(main1:ps_5_1 fs_extra:ps_5_1 ) +fragment=(main_1:ps_5_1 fs_extra:ps_5_1 ) compute=() diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 37fdef90a..e0d509c72 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -17,8 +17,8 @@ Texture2DArray t_shadow : register(t2); SamplerComparisonState sampler_shadow : register(s3); struct FragmentInput_fs_main { - float3 raw_normal1 : LOC0; - float4 position1 : LOC1; + float3 raw_normal_1 : LOC0; + float4 position_1 : LOC1; }; float fetch_shadow(uint light_id, float4 homogeneous_coords) @@ -34,8 +34,8 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords) float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { - float3 raw_normal = fragmentinput_fs_main.raw_normal1; - float4 position = fragmentinput_fs_main.position1; + float3 raw_normal = fragmentinput_fs_main.raw_normal_1; + float4 position = fragmentinput_fs_main.position_1; float3 color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i = 0u; diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 7bb6af6ca..3988369cf 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -25,8 +25,8 @@ struct VertexOutput_vs_main { }; struct FragmentInput_fs_main { - float3 uv1 : LOC0; - float4 position1 : SV_Position; + float3 uv_1 : LOC0; + float4 position_1 : SV_Position; }; VertexOutput ConstructVertexOutput(float4 arg0, float3 arg1) { @@ -38,13 +38,13 @@ VertexOutput ConstructVertexOutput(float4 arg0, float3 arg1) { VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) { - int tmp1 = (int)0; - int tmp2 = (int)0; + int tmp1_ = (int)0; + int tmp2_ = (int)0; - tmp1 = (int((_NagaConstants.base_vertex + vertex_index)) / 2); - tmp2 = (int((_NagaConstants.base_vertex + vertex_index)) & 1); - int _expr10 = tmp1; - int _expr16 = tmp2; + tmp1_ = (int((_NagaConstants.base_vertex + vertex_index)) / 2); + tmp2_ = (int((_NagaConstants.base_vertex + vertex_index)) & 1); + int _expr10 = tmp1_; + int _expr16 = tmp2_; float4 pos = float4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); float4 _expr27 = r_data.view[0]; float4 _expr31 = r_data.view[1]; @@ -53,13 +53,13 @@ VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) float4x4 _expr40 = r_data.proj_inv; float4 unprojected = mul(pos, _expr40); const VertexOutput vertexoutput = ConstructVertexOutput(pos, mul(unprojected.xyz, inv_model_view)); - const VertexOutput_vs_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position }; - return vertexoutput1; + const VertexOutput_vs_main vertexoutput_1 = { vertexoutput.uv, vertexoutput.position }; + return vertexoutput_1; } float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { - VertexOutput in1 = { fragmentinput_fs_main.position1, fragmentinput_fs_main.uv1 }; - float4 _expr5 = r_texture.Sample(r_sampler, in1.uv); + VertexOutput in_ = { fragmentinput_fs_main.position_1, fragmentinput_fs_main.uv_1 }; + float4 _expr5 = r_texture.Sample(r_sampler, in_.uv); return _expr5; } diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl index e70e87f57..e4077b5f0 100644 --- a/tests/out/hlsl/standard.hlsl +++ b/tests/out/hlsl/standard.hlsl @@ -1,11 +1,11 @@ struct FragmentInput_derivatives { - float4 foo1 : SV_Position; + float4 foo_1 : SV_Position; }; float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Target0 { - float4 foo = fragmentinput_derivatives.foo1; + float4 foo = fragmentinput_derivatives.foo_1; float4 x = ddx(foo); float4 y = ddy(foo); float4 z = fwidth(foo); diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 884e606b3..fda0a3201 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -6,25 +6,25 @@ struct _mslBufferSizes { metal::uint size0; }; -struct type3 { +struct type_3 { metal::uint2 inner[2]; }; -typedef int type5[1]; +typedef int type_5[1]; struct Bar { metal::float4x4 matrix; metal::atomic_int atom; char _pad2[4]; - type3 arr; - type5 data; + type_3 arr; + type_5 data; }; -struct type11 { +struct type_11 { int inner[5]; }; float read_from_private( - thread float& foo2 + thread float& foo_2 ) { - float _e2 = foo2; + float _e2 = foo_2; return _e2; } @@ -38,20 +38,20 @@ vertex fooOutput foo( , device Bar& bar [[buffer(0)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - float foo1 = 0.0; - type11 c; - float baz = foo1; - foo1 = 1.0; + float foo_1 = 0.0; + type_11 c; + float baz = foo_1; + foo_1 = 1.0; metal::float4x4 matrix = bar.matrix; - type3 arr = bar.arr; + type_3 arr = bar.arr; float b = bar.matrix[3].x; int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 8) - 2u]; - float _e25 = read_from_private(foo1); + float _e25 = read_from_private(foo_1); bar.matrix[1].z = 1.0; bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); - for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; + for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; bar.data[1] = 1; - for(int _i=0; _i<5; ++_i) c.inner[_i] = type11 {a, static_cast(b), 3, 4, 5}.inner[_i]; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type_11 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; return fooOutput { matrix * static_cast(metal::int4(value)) }; @@ -63,7 +63,7 @@ kernel void atomics( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { int tmp; - int value1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); + int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); int _e6 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e6; int _e9 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); @@ -80,6 +80,6 @@ kernel void atomics( tmp = _e24; int _e27 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e27; - metal::atomic_store_explicit(&bar.atom, value1, metal::memory_order_relaxed); + metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed); return; } diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index 3e1911342..3067ab416 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -3,85 +3,85 @@ #include -kernel void main1( +kernel void main_( ) { int i = 0; - metal::int2 i2; - metal::int3 i3; - metal::int4 i4; + metal::int2 i2_; + metal::int3 i3_; + metal::int4 i4_; metal::uint u = 0u; - metal::uint2 u2; - metal::uint3 u3; - metal::uint4 u4; - metal::float2 f2; - metal::float4 f4; - i2 = metal::int2(0); - i3 = metal::int3(0); - i4 = metal::int4(0); - u2 = metal::uint2(0u); - u3 = metal::uint3(0u); - u4 = metal::uint4(0u); - f2 = metal::float2(0.0); - f4 = metal::float4(0.0); - metal::float4 _e28 = f4; + metal::uint2 u2_; + metal::uint3 u3_; + metal::uint4 u4_; + metal::float2 f2_; + metal::float4 f4_; + i2_ = metal::int2(0); + i3_ = metal::int3(0); + i4_ = metal::int4(0); + u2_ = metal::uint2(0u); + u3_ = metal::uint3(0u); + u4_ = metal::uint4(0u); + f2_ = metal::float2(0.0); + f4_ = metal::float4(0.0); + metal::float4 _e28 = f4_; u = metal::pack_float_to_unorm4x8(_e28); - metal::float4 _e30 = f4; + metal::float4 _e30 = f4_; u = metal::pack_float_to_snorm4x8(_e30); - metal::float2 _e32 = f2; + metal::float2 _e32 = f2_; u = metal::pack_float_to_unorm2x16(_e32); - metal::float2 _e34 = f2; + metal::float2 _e34 = f2_; u = metal::pack_float_to_snorm2x16(_e34); - metal::float2 _e36 = f2; + metal::float2 _e36 = f2_; u = as_type(half2(_e36)); metal::uint _e38 = u; - f4 = metal::unpack_snorm4x8_to_float(_e38); + f4_ = metal::unpack_snorm4x8_to_float(_e38); metal::uint _e40 = u; - f4 = metal::unpack_unorm4x8_to_float(_e40); + f4_ = metal::unpack_unorm4x8_to_float(_e40); metal::uint _e42 = u; - f2 = metal::unpack_snorm2x16_to_float(_e42); + f2_ = metal::unpack_snorm2x16_to_float(_e42); metal::uint _e44 = u; - f2 = metal::unpack_unorm2x16_to_float(_e44); + f2_ = metal::unpack_unorm2x16_to_float(_e44); metal::uint _e46 = u; - f2 = float2(as_type(_e46)); + f2_ = float2(as_type(_e46)); int _e48 = i; int _e49 = i; i = metal::insert_bits(_e48, _e49, 5u, 10u); - metal::int2 _e53 = i2; - metal::int2 _e54 = i2; - i2 = metal::insert_bits(_e53, _e54, 5u, 10u); - metal::int3 _e58 = i3; - metal::int3 _e59 = i3; - i3 = metal::insert_bits(_e58, _e59, 5u, 10u); - metal::int4 _e63 = i4; - metal::int4 _e64 = i4; - i4 = metal::insert_bits(_e63, _e64, 5u, 10u); + metal::int2 _e53 = i2_; + metal::int2 _e54 = i2_; + i2_ = metal::insert_bits(_e53, _e54, 5u, 10u); + metal::int3 _e58 = i3_; + metal::int3 _e59 = i3_; + i3_ = metal::insert_bits(_e58, _e59, 5u, 10u); + metal::int4 _e63 = i4_; + metal::int4 _e64 = i4_; + i4_ = metal::insert_bits(_e63, _e64, 5u, 10u); metal::uint _e68 = u; metal::uint _e69 = u; u = metal::insert_bits(_e68, _e69, 5u, 10u); - metal::uint2 _e73 = u2; - metal::uint2 _e74 = u2; - u2 = metal::insert_bits(_e73, _e74, 5u, 10u); - metal::uint3 _e78 = u3; - metal::uint3 _e79 = u3; - u3 = metal::insert_bits(_e78, _e79, 5u, 10u); - metal::uint4 _e83 = u4; - metal::uint4 _e84 = u4; - u4 = metal::insert_bits(_e83, _e84, 5u, 10u); + metal::uint2 _e73 = u2_; + metal::uint2 _e74 = u2_; + u2_ = metal::insert_bits(_e73, _e74, 5u, 10u); + metal::uint3 _e78 = u3_; + metal::uint3 _e79 = u3_; + u3_ = metal::insert_bits(_e78, _e79, 5u, 10u); + metal::uint4 _e83 = u4_; + metal::uint4 _e84 = u4_; + u4_ = metal::insert_bits(_e83, _e84, 5u, 10u); int _e88 = i; i = metal::extract_bits(_e88, 5u, 10u); - metal::int2 _e92 = i2; - i2 = metal::extract_bits(_e92, 5u, 10u); - metal::int3 _e96 = i3; - i3 = metal::extract_bits(_e96, 5u, 10u); - metal::int4 _e100 = i4; - i4 = metal::extract_bits(_e100, 5u, 10u); + metal::int2 _e92 = i2_; + i2_ = metal::extract_bits(_e92, 5u, 10u); + metal::int3 _e96 = i3_; + i3_ = metal::extract_bits(_e96, 5u, 10u); + metal::int4 _e100 = i4_; + i4_ = metal::extract_bits(_e100, 5u, 10u); metal::uint _e104 = u; u = metal::extract_bits(_e104, 5u, 10u); - metal::uint2 _e108 = u2; - u2 = metal::extract_bits(_e108, 5u, 10u); - metal::uint3 _e112 = u3; - u3 = metal::extract_bits(_e112, 5u, 10u); - metal::uint4 _e116 = u4; - u4 = metal::extract_bits(_e116, 5u, 10u); + metal::uint2 _e108 = u2_; + u2_ = metal::extract_bits(_e108, 5u, 10u); + metal::uint3 _e112 = u3_; + u3_ = metal::extract_bits(_e112, 5u, 10u); + metal::uint4 _e116 = u4_; + u4_ = metal::extract_bits(_e116, 5u, 10u); return; } diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index 0d3809c91..461602f88 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -21,14 +21,14 @@ struct SimParams { float rule2Scale; float rule3Scale; }; -typedef Particle type3[1]; +typedef Particle type_3[1]; struct Particles { - type3 particles; + type_3 particles; }; -struct main1Input { +struct main_Input { }; -kernel void main1( +kernel void main_( metal::uint3 global_invocation_id [[thread_position_in_grid]] , constant SimParams& params [[buffer(0)]] , constant Particles& particlesSrc [[buffer(1)]] diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index b3053e6c5..22769a8a5 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -6,9 +6,9 @@ struct _mslBufferSizes { metal::uint size0; }; -typedef metal::uint type1[1]; +typedef metal::uint type_1[1]; struct PrimeIndices { - type1 data; + type_1 data; }; metal::uint collatz_iterations( @@ -37,9 +37,9 @@ metal::uint collatz_iterations( return _e24; } -struct main1Input { +struct main_Input { }; -kernel void main1( +kernel void main_( metal::uint3 global_id [[thread_position_in_grid]] , device PrimeIndices& v_indices [[user(fake0)]] ) { diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index c6332190d..8c3780024 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -36,9 +36,9 @@ void loop_switch_continue( return; } -struct main1Input { +struct main_Input { }; -kernel void main1( +kernel void main_( metal::uint3 global_id [[thread_position_in_grid]] ) { int pos; diff --git a/tests/out/msl/empty-global-name.msl b/tests/out/msl/empty-global-name.msl index a0bb212dc..efae101f4 100644 --- a/tests/out/msl/empty-global-name.msl +++ b/tests/out/msl/empty-global-name.msl @@ -2,20 +2,20 @@ #include #include -struct type1 { +struct type_1 { int member; }; void function( - device type1& global + device type_1& unnamed ) { - int _e8 = global.member; - global.member = _e8 + 1; + int _e8 = unnamed.member; + unnamed.member = _e8 + 1; return; } -kernel void main1( - device type1& global [[user(fake0)]] +kernel void main_( + device type_1& unnamed [[user(fake0)]] ) { - function(global); + function(unnamed); } diff --git a/tests/out/msl/empty.msl b/tests/out/msl/empty.msl index b918cf431..ddc6b6bf1 100644 --- a/tests/out/msl/empty.msl +++ b/tests/out/msl/empty.msl @@ -3,7 +3,7 @@ #include -kernel void main1( +kernel void main_( ) { return; } diff --git a/tests/out/msl/extra.msl b/tests/out/msl/extra.msl index a2613a6e0..e13f0c2ac 100644 --- a/tests/out/msl/extra.msl +++ b/tests/out/msl/extra.msl @@ -5,27 +5,27 @@ struct PushConstants { metal::uint index; char _pad1[12]; - metal::float2 double1; + metal::float2 double_; }; struct FragmentIn { metal::float4 color; metal::uint primitive_index; }; -struct main1Input { +struct main_Input { metal::float4 color [[user(loc0), center_perspective]]; }; -struct main1Output { +struct main_Output { metal::float4 member [[color(0)]]; }; -fragment main1Output main1( - main1Input varyings [[stage_in]] +fragment main_Output main_( + main_Input varyings [[stage_in]] , metal::uint primitive_index [[primitive_id]] ) { const FragmentIn in = { varyings.color, primitive_index }; if ((in.primitive_index % 2u) == 0u) { - return main1Output { in.color }; + return main_Output { in.color }; } else { - return main1Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) }; + return main_Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) }; } } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 28e732194..a7693a0eb 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -3,12 +3,12 @@ #include constexpr constant bool Foo = true; -struct type2 { +struct type_2 { float inner[10u]; }; -kernel void main1( - threadgroup type2& wg +kernel void main_( + threadgroup type_2& wg , threadgroup metal::atomic_uint& at ) { wg.inner[3] = 1.0; diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index c0e3ad41c..449dc9c43 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -2,11 +2,11 @@ #include #include -constant metal::int2 const_type8 = {3, 1}; +constant metal::int2 const_type_8_ = {3, 1}; -struct main1Input { +struct main_Input { }; -kernel void main1( +kernel void main_( metal::uint3 local_id [[thread_position_in_threadgroup]] , metal::texture2d image_mipmapped_src [[user(fake0)]] , metal::texture2d_ms image_multisampled_src [[user(fake0)]] @@ -16,11 +16,11 @@ kernel void main1( ) { metal::int2 dim = int2(image_storage_src.get_width(), image_storage_src.get_height()); metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); - metal::uint4 value1 = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); - metal::uint4 value2 = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); - metal::uint4 value4 = image_storage_src.read(metal::uint2(itc)); - metal::uint4 value5 = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); - image_dst.write(((value1 + value2) + value4) + value5, metal::uint(itc.x)); + metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); + metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); + metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); + metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); + image_dst.write(((value1_ + value2_) + value4_) + value5_, metal::uint(itc.x)); return; } @@ -28,21 +28,21 @@ kernel void main1( struct depth_loadInput { }; kernel void depth_load( - metal::uint3 local_id1 [[thread_position_in_threadgroup]] + metal::uint3 local_id_1 [[thread_position_in_threadgroup]] , metal::depth2d_ms image_depth_multisampled_src [[user(fake0)]] , metal::texture2d image_storage_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 dim1 = int2(image_storage_src.get_width(), image_storage_src.get_height()); - metal::int2 itc1 = (dim1 * static_cast(local_id1.xy)) % metal::int2(10, 20); - float val = image_depth_multisampled_src.read(metal::uint2(itc1), static_cast(local_id1.z)); - image_dst.write(metal::uint4(static_cast(val)), metal::uint(itc1.x)); + metal::int2 dim_1 = int2(image_storage_src.get_width(), image_storage_src.get_height()); + metal::int2 itc_1 = (dim_1 * static_cast(local_id_1.xy)) % metal::int2(10, 20); + float val = image_depth_multisampled_src.read(metal::uint2(itc_1), static_cast(local_id_1.z)); + image_dst.write(metal::uint4(static_cast(val)), metal::uint(itc_1.x)); return; } struct queriesOutput { - metal::float4 member2 [[position]]; + metal::float4 member_2 [[position]]; }; vertex queriesOutput queries( metal::texture1d image_1d [[user(fake0)]] @@ -69,7 +69,7 @@ vertex queriesOutput queries( struct levels_queriesOutput { - metal::float4 member3 [[position]]; + metal::float4 member_3 [[position]]; }; vertex levels_queriesOutput levels_queries( metal::texture2d image_2d [[user(fake0)]] @@ -87,13 +87,13 @@ vertex levels_queriesOutput levels_queries( int num_layers_cube = int(image_cube_array.get_array_size()); int num_levels_3d = int(image_3d.get_num_mip_levels()); int num_samples_aa = int(image_aa.get_num_samples()); - int sum1 = ((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array; - return levels_queriesOutput { metal::float4(static_cast(sum1)) }; + int sum_1 = ((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array; + return levels_queriesOutput { metal::float4(static_cast(sum_1)) }; } struct sampleOutput { - metal::float4 member4 [[color(0)]]; + metal::float4 member_4 [[color(0)]]; }; fragment sampleOutput sample( metal::texture1d image_1d [[user(fake0)]] @@ -103,22 +103,22 @@ fragment sampleOutput sample( metal::float2 tc = metal::float2(0.5); metal::float4 s1d = image_1d.sample(sampler_reg, tc.x); metal::float4 s2d = image_2d.sample(sampler_reg, tc); - metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type8); + metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type_8_); metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); - metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type8); + metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_8_); return sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset }; } struct sample_comparisonOutput { - float member5 [[color(0)]]; + float member_5 [[color(0)]]; }; fragment sample_comparisonOutput sample_comparison( metal::sampler sampler_cmp [[user(fake0)]] , metal::depth2d image_2d_depth [[user(fake0)]] ) { - metal::float2 tc1 = metal::float2(0.5); - float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc1, 0.5); - float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc1, 0.5); + metal::float2 tc_1 = metal::float2(0.5); + float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); + float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); return sample_comparisonOutput { s2d_depth + s2d_depth_level }; } diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index abe791a27..9dca449a6 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -11,61 +11,61 @@ struct FragmentOutput { metal::uint sample_mask; float color; }; -struct type4 { +struct type_4 { metal::uint inner[1]; }; -struct vertex1Input { +struct vertex_Input { metal::uint color [[attribute(10)]]; }; -struct vertex1Output { +struct vertex_Output { metal::float4 position [[position]]; float varying [[user(loc1), center_perspective]]; }; -vertex vertex1Output vertex1( - vertex1Input varyings [[stage_in]] +vertex vertex_Output vertex_( + vertex_Input varyings [[stage_in]] , metal::uint vertex_index [[vertex_id]] , metal::uint instance_index [[instance_id]] ) { const auto color = varyings.color; metal::uint tmp = (vertex_index + instance_index) + color; const auto _tmp = VertexOutput {metal::float4(1.0), static_cast(tmp)}; - return vertex1Output { _tmp.position, _tmp.varying }; + return vertex_Output { _tmp.position, _tmp.varying }; } -struct fragment1Input { +struct fragment_Input { float varying [[user(loc1), center_perspective]]; }; -struct fragment1Output { +struct fragment_Output { float depth [[depth(any)]]; metal::uint sample_mask [[sample_mask]]; float color [[color(0)]]; }; -fragment fragment1Output fragment1( - fragment1Input varyings1 [[stage_in]] +fragment fragment_Output fragment_( + fragment_Input varyings_1 [[stage_in]] , metal::float4 position [[position]] , bool front_facing [[front_facing]] , metal::uint sample_index [[sample_id]] , metal::uint sample_mask [[sample_mask]] ) { - const VertexOutput in = { position, varyings1.varying }; + const VertexOutput in = { position, varyings_1.varying }; metal::uint mask = sample_mask & (1u << sample_index); - float color1 = front_facing ? 1.0 : 0.0; - const auto _tmp = FragmentOutput {in.varying, mask, color1}; - return fragment1Output { _tmp.depth, _tmp.sample_mask, _tmp.color }; + float color_1 = front_facing ? 1.0 : 0.0; + const auto _tmp = FragmentOutput {in.varying, mask, color_1}; + return fragment_Output { _tmp.depth, _tmp.sample_mask, _tmp.color }; } -struct compute1Input { +struct compute_Input { }; -kernel void compute1( +kernel void compute_( metal::uint3 global_id [[thread_position_in_grid]] , metal::uint3 local_id [[thread_position_in_threadgroup]] , metal::uint local_index [[thread_index_in_threadgroup]] , metal::uint3 wg_id [[threadgroup_position_in_grid]] , metal::uint3 num_wgs [[threadgroups_per_grid]] -, threadgroup type4& output +, threadgroup type_4& output ) { output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x; return; diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl index f2600ba13..24a259806 100644 --- a/tests/out/msl/interpolate.msl +++ b/tests/out/msl/interpolate.msl @@ -13,7 +13,7 @@ struct FragmentInput { float perspective_sample; }; -struct main1Output { +struct main_Output { metal::float4 position [[position]]; metal::uint flat [[user(loc0), flat]]; float linear [[user(loc1), center_no_perspective]]; @@ -23,7 +23,7 @@ struct main1Output { float perspective_centroid [[user(loc5), centroid_perspective]]; float perspective_sample [[user(loc6), sample_perspective]]; }; -vertex main1Output main1( +vertex main_Output main_( ) { FragmentInput out; out.position = metal::float4(2.0, 4.0, 5.0, 6.0); @@ -36,11 +36,11 @@ vertex main1Output main1( out.perspective_sample = 2744.0; FragmentInput _e30 = out; const auto _tmp = _e30; - return main1Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample }; + return main_Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample }; } -struct main2Input { +struct main_1Input { metal::uint flat [[user(loc0), flat]]; float linear [[user(loc1), center_no_perspective]]; metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]]; @@ -49,10 +49,10 @@ struct main2Input { float perspective_centroid [[user(loc5), centroid_perspective]]; float perspective_sample [[user(loc6), sample_perspective]]; }; -fragment void main2( - main2Input varyings1 [[stage_in]] +fragment void main_1( + main_1Input varyings_1 [[stage_in]] , metal::float4 position [[position]] ) { - const FragmentInput val = { position, varyings1.flat, varyings1.linear, varyings1.linear_centroid, varyings1.linear_sample, varyings1.perspective, varyings1.perspective_centroid, varyings1.perspective_sample }; + const FragmentInput val = { position, varyings_1.flat, varyings_1.linear, varyings_1.linear_centroid, varyings_1.linear_sample, varyings_1.perspective, varyings_1.perspective_centroid, varyings_1.perspective_sample }; return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 98fb58457..37cf121fb 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -13,15 +13,15 @@ constant metal::int4 v_i32_one = {1, 1, 1, 1}; metal::float4 builtins( ) { - int s1 = true ? 1 : 0; - metal::float4 s2 = true ? v_f32_one : v_f32_zero; - metal::float4 s3 = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false)); - metal::float4 m1 = metal::mix(v_f32_zero, v_f32_one, v_f32_half); - metal::float4 m2 = metal::mix(v_f32_zero, v_f32_one, 0.10000000149011612); - float b1 = as_type(v_i32_one.x); - metal::float4 b2 = as_type(v_i32_one); + int s1_ = true ? 1 : 0; + metal::float4 s2_ = true ? v_f32_one : v_f32_zero; + metal::float4 s3_ = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false)); + metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half); + metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.10000000149011612); + float b1_ = as_type(v_i32_one.x); + metal::float4 b2_ = as_type(v_i32_one); metal::int4 v_i32_zero = static_cast(v_f32_zero); - return ((((static_cast(metal::int4(s1) + v_i32_zero) + s2) + m1) + m2) + metal::float4(b1)) + b2; + return ((((static_cast(metal::int4(s1_) + v_i32_zero) + s2_) + m1_) + m2_) + metal::float4(b1_)) + b2_; } metal::float4 splat( @@ -57,13 +57,13 @@ float constructors( void modulo( ) { - int a1 = 1 % 1; - float b1 = metal::fmod(1.0, 1.0); + int a_1 = 1 % 1; + float b_1 = metal::fmod(1.0, 1.0); metal::int3 c = metal::int3(1) % metal::int3(1); metal::float3 d = metal::fmod(metal::float3(1.0), metal::float3(1.0)); } -kernel void main1( +kernel void main_( ) { metal::float4 _e4 = builtins(); metal::float4 _e5 = splat(); diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index 88b6181b9..de1bfb598 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -2,58 +2,58 @@ #include #include -struct type5 { +struct type_5 { float inner[1u]; }; struct gl_PerVertex { metal::float4 gl_Position; float gl_PointSize; - type5 gl_ClipDistance; - type5 gl_CullDistance; + type_5 gl_ClipDistance; + type_5 gl_CullDistance; }; -struct type9 { +struct type_9 { metal::float2 member; metal::float4 gl_Position; }; -constant metal::float4 const_type3 = {0.0, 0.0, 0.0, 1.0}; -constant type5 const_type5 = {0.0}; -constant gl_PerVertex const_gl_PerVertex = {const_type3, 1.0, const_type5, const_type5}; +constant metal::float4 const_type_3_ = {0.0, 0.0, 0.0, 1.0}; +constant type_5 const_type_5_ = {0.0}; +constant gl_PerVertex const_gl_PerVertex = {const_type_3_, 1.0, const_type_5_, const_type_5_}; -void main2( +void main_1( thread metal::float2& v_uv, - thread metal::float2 const& a_uv1, + thread metal::float2 const& a_uv_1, thread gl_PerVertex& perVertexStruct, - thread metal::float2 const& a_pos1 + thread metal::float2 const& a_pos_1 ) { - metal::float2 _e12 = a_uv1; + metal::float2 _e12 = a_uv_1; v_uv = _e12; - metal::float2 _e13 = a_pos1; + metal::float2 _e13 = a_pos_1; perVertexStruct.gl_Position = metal::float4(_e13.x, _e13.y, 0.0, 1.0); return; } -struct main1Input { +struct main_Input { metal::float2 a_uv [[attribute(1)]]; metal::float2 a_pos [[attribute(0)]]; }; -struct main1Output { +struct main_Output { metal::float2 member [[user(loc0), center_perspective]]; metal::float4 gl_Position [[position]]; }; -vertex main1Output main1( - main1Input varyings [[stage_in]] +vertex main_Output main_( + main_Input varyings [[stage_in]] ) { metal::float2 v_uv = {}; - metal::float2 a_uv1 = {}; + metal::float2 a_uv_1 = {}; gl_PerVertex perVertexStruct = const_gl_PerVertex; - metal::float2 a_pos1 = {}; + metal::float2 a_pos_1 = {}; const auto a_uv = varyings.a_uv; const auto a_pos = varyings.a_pos; - a_uv1 = a_uv; - a_pos1 = a_pos; - main2(v_uv, a_uv1, perVertexStruct, a_pos1); + a_uv_1 = a_uv; + a_pos_1 = a_pos; + main_1(v_uv, a_uv_1, perVertexStruct, a_pos_1); metal::float2 _e7 = v_uv; metal::float4 _e8 = perVertexStruct.gl_Position; - const auto _tmp = type9 {_e7, _e8}; - return main1Output { _tmp.member, _tmp.gl_Position }; + const auto _tmp = type_9 {_e7, _e8}; + return main_Output { _tmp.member, _tmp.gl_Position }; } diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl index bb7e971be..b55036702 100644 --- a/tests/out/msl/quad.msl +++ b/tests/out/msl/quad.msl @@ -8,47 +8,47 @@ struct VertexOutput { metal::float4 position; }; -struct main1Input { +struct main_Input { metal::float2 pos [[attribute(0)]]; metal::float2 uv [[attribute(1)]]; }; -struct main1Output { +struct main_Output { metal::float2 uv [[user(loc0), center_perspective]]; metal::float4 position [[position]]; }; -vertex main1Output main1( - main1Input varyings [[stage_in]] +vertex main_Output main_( + main_Input varyings [[stage_in]] ) { const auto pos = varyings.pos; const auto uv = varyings.uv; const auto _tmp = VertexOutput {uv, metal::float4(c_scale * pos, 0.0, 1.0)}; - return main1Output { _tmp.uv, _tmp.position }; + return main_Output { _tmp.uv, _tmp.position }; } -struct main2Input { - metal::float2 uv1 [[user(loc0), center_perspective]]; +struct main_1Input { + metal::float2 uv_1 [[user(loc0), center_perspective]]; }; -struct main2Output { - metal::float4 member1 [[color(0)]]; +struct main_1Output { + metal::float4 member_1 [[color(0)]]; }; -fragment main2Output main2( - main2Input varyings1 [[stage_in]] +fragment main_1Output main_1( + main_1Input varyings_1 [[stage_in]] , metal::texture2d u_texture [[user(fake0)]] , metal::sampler u_sampler [[user(fake0)]] ) { - const auto uv1 = varyings1.uv1; - metal::float4 color = u_texture.sample(u_sampler, uv1); + const auto uv_1 = varyings_1.uv_1; + metal::float4 color = u_texture.sample(u_sampler, uv_1); if (color.w == 0.0) { metal::discard_fragment(); } metal::float4 premultiplied = color.w * color; - return main2Output { premultiplied }; + return main_1Output { premultiplied }; } struct fs_extraOutput { - metal::float4 member2 [[color(0)]]; + metal::float4 member_2 [[color(0)]]; }; fragment fs_extraOutput fs_extra( ) { diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 7b1146447..33475b841 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -15,9 +15,9 @@ struct Light { metal::float4 pos; metal::float4 color; }; -typedef Light type3[1]; +typedef Light type_3[1]; struct Lights { - type3 data; + type_3 data; }; constant metal::float3 c_ambient = {0.05000000074505806, 0.05000000074505806, 0.05000000074505806}; diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index 2b37de6c8..ec7942cb4 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -21,12 +21,12 @@ vertex vs_mainOutput vs_main( metal::uint vertex_index [[vertex_id]] , constant Data& r_data [[buffer(0)]] ) { - int tmp1; - int tmp2; - tmp1 = static_cast(vertex_index) / 2; - tmp2 = static_cast(vertex_index) & 1; - int _e10 = tmp1; - int _e16 = tmp2; + int tmp1_; + int tmp2_; + tmp1_ = static_cast(vertex_index) / 2; + tmp2_ = static_cast(vertex_index) & 1; + int _e10 = tmp1_; + int _e16 = tmp2_; metal::float4 pos = metal::float4((static_cast(_e10) * 4.0) - 1.0, (static_cast(_e16) * 4.0) - 1.0, 0.0, 1.0); metal::float4 _e27 = r_data.view[0]; metal::float4 _e31 = r_data.view[1]; @@ -43,10 +43,10 @@ struct fs_mainInput { metal::float3 uv [[user(loc0), center_perspective]]; }; struct fs_mainOutput { - metal::float4 member1 [[color(0)]]; + metal::float4 member_1 [[color(0)]]; }; fragment fs_mainOutput fs_main( - fs_mainInput varyings1 [[stage_in]] + fs_mainInput varyings_1 [[stage_in]] , metal::float4 position [[position]] , metal::texturecube r_texture [[texture(0)]] ) { @@ -58,7 +58,7 @@ fragment fs_mainOutput fs_main( metal::min_filter::linear, metal::coord::normalized ); - const VertexOutput in = { position, varyings1.uv }; + const VertexOutput in = { position, varyings_1.uv }; metal::float4 _e5 = r_texture.sample(r_sampler, in.uv); return fs_mainOutput { _e5 }; } diff --git a/tests/out/msl/texture-arg.msl b/tests/out/msl/texture-arg.msl index 39919e06d..49533df9e 100644 --- a/tests/out/msl/texture-arg.msl +++ b/tests/out/msl/texture-arg.msl @@ -11,13 +11,13 @@ metal::float4 test( return _e7; } -struct main1Output { +struct main_Output { metal::float4 member [[color(0)]]; }; -fragment main1Output main1( +fragment main_Output main_( metal::texture2d Texture [[user(fake0)]] , metal::sampler Sampler [[user(fake0)]] ) { metal::float4 _e2 = test(Texture, Sampler); - return main1Output { _e2 }; + return main_Output { _e2 }; } diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index 30cd00291..c4e736b46 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -7,12 +7,12 @@ struct FragmentOutput { [[location(0)]] o_Target: vec4; }; -var v_Uv1: vec2; +var v_Uv_1: vec2; var o_Target: vec4; [[group(1), binding(0)]] var global: ColorMaterial_color; -fn main1() { +fn main_1() { var color: vec4; let e4: vec4 = global.Color; @@ -24,8 +24,8 @@ fn main1() { [[stage(fragment)]] fn main([[location(0)]] v_Uv: vec2) -> FragmentOutput { - v_Uv1 = v_Uv; - main1(); + v_Uv_1 = v_Uv; + main_1(); let e9: vec4 = o_Target; return FragmentOutput(e9); } diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 0d0de959a..122ed9853 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -18,28 +18,28 @@ struct VertexOutput { [[builtin(position)]] member: vec4; }; -var Vertex_Position1: vec3; -var Vertex_Normal1: vec3; -var Vertex_Uv1: vec2; +var Vertex_Position_1: vec3; +var Vertex_Normal_1: vec3; +var Vertex_Uv_1: vec2; var v_Uv: vec2; [[group(0), binding(0)]] var global: Camera; [[group(2), binding(0)]] -var global1: Transform; +var global_1: Transform; [[group(2), binding(1)]] -var global2: Sprite_size; +var global_2: Sprite_size; var gl_Position: vec4; -fn main1() { +fn main_1() { var position: vec3; - let e10: vec2 = Vertex_Uv1; + let e10: vec2 = Vertex_Uv_1; v_Uv = e10; - let e11: vec3 = Vertex_Position1; - let e12: vec2 = global2.size; + let e11: vec3 = Vertex_Position_1; + let e12: vec2 = global_2.size; position = (e11 * vec3(e12, 1.0)); let e18: mat4x4 = global.ViewProj; - let e19: mat4x4 = global1.Model; + let e19: mat4x4 = global_1.Model; let e21: vec3 = position; gl_Position = ((e18 * e19) * vec4(e21, 1.0)); return; @@ -47,10 +47,10 @@ fn main1() { [[stage(vertex)]] fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Normal: vec3, [[location(2)]] Vertex_Uv: vec2) -> VertexOutput { - Vertex_Position1 = Vertex_Position; - Vertex_Normal1 = Vertex_Normal; - Vertex_Uv1 = Vertex_Uv; - main1(); + Vertex_Position_1 = Vertex_Position; + Vertex_Normal_1 = Vertex_Normal; + Vertex_Uv_1 = Vertex_Uv; + main_1(); let e21: vec2 = v_Uv; let e23: vec4 = gl_Position; return VertexOutput(e21, e23); diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 83495e2ae..29af6ada8 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -15,29 +15,29 @@ struct VertexOutput { [[builtin(position)]] member: vec4; }; -var Vertex_Position1: vec3; -var Vertex_Normal1: vec3; -var Vertex_Uv1: vec2; +var Vertex_Position_1: vec3; +var Vertex_Normal_1: vec3; +var Vertex_Uv_1: vec2; var v_Position: vec3; var v_Normal: vec3; var v_Uv: vec2; [[group(0), binding(0)]] var global: Camera; [[group(2), binding(0)]] -var global1: Transform; +var global_1: Transform; var gl_Position: vec4; -fn main1() { - let e10: mat4x4 = global1.Model; - let e11: vec3 = Vertex_Normal1; +fn main_1() { + let e10: mat4x4 = global_1.Model; + let e11: vec3 = Vertex_Normal_1; v_Normal = (e10 * vec4(e11, 1.0)).xyz; - let e16: mat4x4 = global1.Model; - let e24: vec3 = Vertex_Normal1; + let e16: mat4x4 = global_1.Model; + let e24: vec3 = Vertex_Normal_1; v_Normal = (mat3x3(e16[0].xyz, e16[1].xyz, e16[2].xyz) * e24); - let e26: mat4x4 = global1.Model; - let e27: vec3 = Vertex_Position1; + let e26: mat4x4 = global_1.Model; + let e27: vec3 = Vertex_Position_1; v_Position = (e26 * vec4(e27, 1.0)).xyz; - let e32: vec2 = Vertex_Uv1; + let e32: vec2 = Vertex_Uv_1; v_Uv = e32; let e34: mat4x4 = global.ViewProj; let e35: vec3 = v_Position; @@ -47,10 +47,10 @@ fn main1() { [[stage(vertex)]] fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Normal: vec3, [[location(2)]] Vertex_Uv: vec2) -> VertexOutput { - Vertex_Position1 = Vertex_Position; - Vertex_Normal1 = Vertex_Normal; - Vertex_Uv1 = Vertex_Uv; - main1(); + Vertex_Position_1 = Vertex_Position; + Vertex_Normal_1 = Vertex_Normal; + Vertex_Uv_1 = Vertex_Uv; + main_1(); let e23: vec3 = v_Position; let e25: vec3 = v_Normal; let e27: vec2 = v_Uv; diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 993ec7ff8..4451a7908 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -8,26 +8,26 @@ var global: PrimeIndices; var gl_GlobalInvocationID: vec3; fn collatz_iterations(n: u32) -> u32 { - var n1: u32; + var n_1: u32; var i: u32 = 0u; - n1 = n; + n_1 = n; loop { - let e7: u32 = n1; + let e7: u32 = n_1; if (!((e7 != u32(1)))) { break; } { - let e14: u32 = n1; + let e14: u32 = n_1; if (((f32(e14) % f32(2)) == f32(0))) { { - let e22: u32 = n1; - n1 = (e22 / u32(2)); + let e22: u32 = n_1; + n_1 = (e22 / u32(2)); } } else { { - let e27: u32 = n1; - n1 = ((u32(3) * e27) + u32(1)); + let e27: u32 = n_1; + n_1 = ((u32(3) * e27) + u32(1)); } } let e33: u32 = i; @@ -38,7 +38,7 @@ fn collatz_iterations(n: u32) -> u32 { return e36; } -fn main1() { +fn main_1() { var index: u32; let e3: vec3 = gl_GlobalInvocationID; @@ -55,6 +55,6 @@ fn main1() { [[stage(compute), workgroup_size(1, 1, 1)]] fn main([[builtin(global_invocation_id)]] param: vec3) { gl_GlobalInvocationID = param; - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/277-casting-vert.wgsl b/tests/out/wgsl/277-casting-vert.wgsl index 673f8443d..f05db0372 100644 --- a/tests/out/wgsl/277-casting-vert.wgsl +++ b/tests/out/wgsl/277-casting-vert.wgsl @@ -1,10 +1,10 @@ -fn main1() { +fn main_1() { var a: f32 = 1.0; } [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl index d3a55eb8e..da13932f3 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl @@ -1,4 +1,4 @@ -fn main1() { +fn main_1() { var a: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); let e1: f32 = f32(1); @@ -6,6 +6,6 @@ fn main1() { [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/484-preprocessor-if-vert.wgsl b/tests/out/wgsl/484-preprocessor-if-vert.wgsl index a5c402fad..ebd8567c9 100644 --- a/tests/out/wgsl/484-preprocessor-if-vert.wgsl +++ b/tests/out/wgsl/484-preprocessor-if-vert.wgsl @@ -1,9 +1,9 @@ -fn main1() { +fn main_1() { return; } [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index 10ae39b3b..bbd10113c 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -15,18 +15,18 @@ struct VertexOutput { [[group(0), binding(0)]] var global: Globals; -var global1: VertexPushConstants; -var position1: vec2; -var color1: vec4; +var global_1: VertexPushConstants; +var position_1: vec2; +var color_1: vec4; var frag_color: vec4; var gl_Position: vec4; -fn main1() { - let e7: vec4 = color1; +fn main_1() { + let e7: vec4 = color_1; frag_color = e7; let e9: mat4x4 = global.view_matrix; - let e10: mat4x4 = global1.world_matrix; - let e12: vec2 = position1; + let e10: mat4x4 = global_1.world_matrix; + let e12: vec2 = position_1; gl_Position = ((e9 * e10) * vec4(e12, 0.0, 1.0)); let e18: vec4 = gl_Position; let e20: vec4 = gl_Position; @@ -36,9 +36,9 @@ fn main1() { [[stage(vertex)]] fn main([[location(0)]] position: vec2, [[location(1)]] color: vec4) -> VertexOutput { - position1 = position; - color1 = color; - main1(); + position_1 = position; + color_1 = color; + main_1(); let e15: vec4 = frag_color; let e17: vec4 = gl_Position; return VertexOutput(e15, e17); diff --git a/tests/out/wgsl/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-vert.wgsl index a8f7df78f..063f22a4f 100644 --- a/tests/out/wgsl/896-push-constant-vert.wgsl +++ b/tests/out/wgsl/896-push-constant-vert.wgsl @@ -5,12 +5,12 @@ struct PushConstants { var c: PushConstants; -fn main1() { +fn main_1() { return; } [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/900-implicit-conversions-vert.wgsl b/tests/out/wgsl/900-implicit-conversions-vert.wgsl index 4704b4419..bb86b505f 100644 --- a/tests/out/wgsl/900-implicit-conversions-vert.wgsl +++ b/tests/out/wgsl/900-implicit-conversions-vert.wgsl @@ -1,68 +1,68 @@ fn exact(a: f32) { - var a1: f32; + var a_1: f32; - a1 = a; + a_1 = a; return; } -fn exact1(a2: i32) { - var a3: i32; +fn exact_1(a_2: i32) { + var a_3: i32; - a3 = a2; + a_3 = a_2; return; } -fn implicit(a4: f32) { - var a5: f32; +fn implicit(a_4: f32) { + var a_5: f32; - a5 = a4; + a_5 = a_4; return; } -fn implicit1(a6: i32) { - var a7: i32; +fn implicit_1(a_6: i32) { + var a_7: i32; - a7 = a6; + a_7 = a_6; return; } fn implicit_dims(v: f32) { - var v1: f32; + var v_1: f32; - v1 = v; + v_1 = v; return; } -fn implicit_dims1(v2: vec2) { - var v3: vec2; +fn implicit_dims_1(v_2: vec2) { + var v_3: vec2; - v3 = v2; + v_3 = v_2; return; } -fn implicit_dims2(v4: vec3) { - var v5: vec3; +fn implicit_dims_2(v_4: vec3) { + var v_5: vec3; - v5 = v4; + v_5 = v_4; return; } -fn implicit_dims3(v6: vec4) { - var v7: vec4; +fn implicit_dims_3(v_6: vec4) { + var v_7: vec4; - v7 = v6; + v_7 = v_6; return; } -fn main1() { - exact1(1); +fn main_1() { + exact_1(1); implicit(f32(1u)); - implicit_dims2(vec3(vec3(1))); + implicit_dims_2(vec3(vec3(1))); return; } [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl index aa791b917..13695097b 100644 --- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl +++ b/tests/out/wgsl/901-lhs-field-select-vert.wgsl @@ -1,4 +1,4 @@ -fn main1() { +fn main_1() { var a: vec4 = vec4(1.0, 1.0, 1.0, 1.0); a.x = 2.0; @@ -7,6 +7,6 @@ fn main1() { [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl index 56a4015bd..0e3e656a7 100644 --- a/tests/out/wgsl/931-constant-emitting-vert.wgsl +++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl @@ -1,13 +1,13 @@ -fn function1() -> f32 { +fn function_() -> f32 { return 0.0; } -fn main1() { +fn main_1() { return; } [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl index a66020fd8..9af904e9a 100644 --- a/tests/out/wgsl/932-for-loop-if-vert.wgsl +++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl @@ -1,4 +1,4 @@ -fn main1() { +fn main_1() { var i: i32 = 0; loop { @@ -18,6 +18,6 @@ fn main1() { [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 9b4c7b0e7..ad1666f9a 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -9,24 +9,24 @@ struct Bar { [[group(0), binding(0)]] var bar: Bar; -fn read_from_private(foo2: ptr) -> f32 { - let e2: f32 = (*foo2); +fn read_from_private(foo_2: ptr) -> f32 { + let e2: f32 = (*foo_2); return e2; } [[stage(vertex)]] fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { - var foo1: f32 = 0.0; + var foo_1: f32 = 0.0; var c: array; - let baz: f32 = foo1; - foo1 = 1.0; + let baz: f32 = foo_1; + foo_1 = 1.0; let matrix: mat4x4 = bar.matrix; let arr: array,2> = bar.arr; let b: f32 = bar.matrix[3][0]; let a: i32 = bar.data[(arrayLength((&bar.data)) - 2u)]; - let pointer1: ptr = (&bar.data[0]); - let e25: f32 = read_from_private((&foo1)); + let pointer_: ptr = (&bar.data[0]); + let e25: f32 = read_from_private((&foo_1)); bar.matrix[1][2] = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); @@ -41,7 +41,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { fn atomics() { var tmp: i32; - let value1: i32 = atomicLoad((&bar.atom)); + let value_1: i32 = atomicLoad((&bar.atom)); let e6: i32 = atomicAdd((&bar.atom), 5); tmp = e6; let e9: i32 = atomicSub((&bar.atom), 5); @@ -58,6 +58,6 @@ fn atomics() { tmp = e24; let e27: i32 = atomicExchange((&bar.atom), 5); tmp = e27; - atomicStore((&bar.atom), value1); + atomicStore((&bar.atom), value_1); return; } diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index cecda28ad..b9cc3ac3f 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -56,33 +56,33 @@ struct FragmentOutput { [[location(0)]] o_Target: vec4; }; -var v_WorldPosition1: vec3; -var v_WorldNormal1: vec3; -var v_Uv1: vec2; -var v_WorldTangent1: vec4; +var v_WorldPosition_1: vec3; +var v_WorldNormal_1: vec3; +var v_Uv_1: vec2; +var v_WorldTangent_1: vec4; var o_Target: vec4; [[group(0), binding(0)]] var global: CameraViewProj; [[group(0), binding(1)]] -var global1: CameraPosition; +var global_1: CameraPosition; [[group(1), binding(0)]] -var global2: Lights; +var global_2: Lights; [[group(3), binding(0)]] -var global3: StandardMaterial_base_color; +var global_3: StandardMaterial_base_color; [[group(3), binding(1)]] var StandardMaterial_base_color_texture: texture_2d; [[group(3), binding(2)]] var StandardMaterial_base_color_texture_sampler: sampler; [[group(3), binding(3)]] -var global4: StandardMaterial_roughness; +var global_4: StandardMaterial_roughness; [[group(3), binding(4)]] -var global5: StandardMaterial_metallic; +var global_5: StandardMaterial_metallic; [[group(3), binding(5)]] var StandardMaterial_metallic_roughness_texture: texture_2d; [[group(3), binding(6)]] var StandardMaterial_metallic_roughness_texture_sampler: sampler; [[group(3), binding(7)]] -var global6: StandardMaterial_reflectance; +var global_6: StandardMaterial_reflectance; [[group(3), binding(8)]] var StandardMaterial_normal_map: texture_2d; [[group(3), binding(9)]] @@ -92,38 +92,38 @@ var StandardMaterial_occlusion_texture: texture_2d; [[group(3), binding(11)]] var StandardMaterial_occlusion_texture_sampler: sampler; [[group(3), binding(12)]] -var global7: StandardMaterial_emissive; +var global_7: StandardMaterial_emissive; [[group(3), binding(13)]] var StandardMaterial_emissive_texture: texture_2d; [[group(3), binding(14)]] var StandardMaterial_emissive_texture_sampler: sampler; var gl_FrontFacing: bool; -fn pow5(x: f32) -> f32 { - var x1: f32; - var x2: f32; +fn pow5_(x: f32) -> f32 { + var x_1: f32; + var x2_: f32; - x1 = x; - let e42: f32 = x1; - let e43: f32 = x1; - x2 = (e42 * e43); - let e46: f32 = x2; - let e47: f32 = x2; - let e49: f32 = x1; + x_1 = x; + let e42: f32 = x_1; + let e43: f32 = x_1; + x2_ = (e42 * e43); + let e46: f32 = x2_; + let e47: f32 = x2_; + let e49: f32 = x_1; return ((e46 * e47) * e49); } fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 { - var distanceSquare1: f32; - var inverseRangeSquared1: f32; + var distanceSquare_1: f32; + var inverseRangeSquared_1: f32; var factor: f32; var smoothFactor: f32; var attenuation: f32; - distanceSquare1 = distanceSquare; - inverseRangeSquared1 = inverseRangeSquared; - let e44: f32 = distanceSquare1; - let e45: f32 = inverseRangeSquared1; + distanceSquare_1 = distanceSquare; + inverseRangeSquared_1 = inverseRangeSquared; + let e44: f32 = distanceSquare_1; + let e45: f32 = inverseRangeSquared_1; factor = (e44 * e45); let e49: f32 = factor; let e50: f32 = factor; @@ -134,27 +134,27 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 let e65: f32 = smoothFactor; attenuation = (e64 * e65); let e68: f32 = attenuation; - let e73: f32 = distanceSquare1; + let e73: f32 = distanceSquare_1; return ((e68 * 1.0) / max(e73, 0.0010000000474974513)); } fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { - var roughness1: f32; - var NoH1: f32; + var roughness_1: f32; + var NoH_1: f32; var oneMinusNoHSquared: f32; var a: f32; var k: f32; var d: f32; - roughness1 = roughness; - NoH1 = NoH; - let e46: f32 = NoH1; - let e47: f32 = NoH1; + roughness_1 = roughness; + NoH_1 = NoH; + let e46: f32 = NoH_1; + let e47: f32 = NoH_1; oneMinusNoHSquared = (1.0 - (e46 * e47)); - let e51: f32 = NoH1; - let e52: f32 = roughness1; + let e51: f32 = NoH_1; + let e52: f32 = roughness_1; a = (e51 * e52); - let e55: f32 = roughness1; + let e55: f32 = roughness_1; let e56: f32 = oneMinusNoHSquared; let e57: f32 = a; let e58: f32 = a; @@ -166,44 +166,44 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { return e70; } -fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 { - var roughness3: f32; - var NoV1: f32; - var NoL1: f32; - var a2: f32; +fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { + var roughness_3: f32; + var NoV_1: f32; + var NoL_1: f32; + var a2_: f32; var lambdaV: f32; var lambdaL: f32; var v: f32; - roughness3 = roughness2; - NoV1 = NoV; - NoL1 = NoL; - let e46: f32 = roughness3; - let e47: f32 = roughness3; - a2 = (e46 * e47); - let e50: f32 = NoL1; - let e51: f32 = NoV1; - let e52: f32 = a2; - let e53: f32 = NoV1; - let e56: f32 = NoV1; - let e58: f32 = a2; - let e60: f32 = NoV1; - let e61: f32 = a2; - let e62: f32 = NoV1; - let e65: f32 = NoV1; - let e67: f32 = a2; + roughness_3 = roughness_2; + NoV_1 = NoV; + NoL_1 = NoL; + let e46: f32 = roughness_3; + let e47: f32 = roughness_3; + a2_ = (e46 * e47); + let e50: f32 = NoL_1; + let e51: f32 = NoV_1; + let e52: f32 = a2_; + let e53: f32 = NoV_1; + let e56: f32 = NoV_1; + let e58: f32 = a2_; + let e60: f32 = NoV_1; + let e61: f32 = a2_; + let e62: f32 = NoV_1; + let e65: f32 = NoV_1; + let e67: f32 = a2_; lambdaV = (e50 * sqrt((((e60 - (e61 * e62)) * e65) + e67))); - let e72: f32 = NoV1; - let e73: f32 = NoL1; - let e74: f32 = a2; - let e75: f32 = NoL1; - let e78: f32 = NoL1; - let e80: f32 = a2; - let e82: f32 = NoL1; - let e83: f32 = a2; - let e84: f32 = NoL1; - let e87: f32 = NoL1; - let e89: f32 = a2; + let e72: f32 = NoV_1; + let e73: f32 = NoL_1; + let e74: f32 = a2_; + let e75: f32 = NoL_1; + let e78: f32 = NoL_1; + let e80: f32 = a2_; + let e82: f32 = NoL_1; + let e83: f32 = a2_; + let e84: f32 = NoL_1; + let e87: f32 = NoL_1; + let e89: f32 = a2_; lambdaL = (e72 * sqrt((((e82 - (e83 * e84)) * e87) + e89))); let e95: f32 = lambdaV; let e96: f32 = lambdaL; @@ -212,151 +212,151 @@ fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 { return e100; } -fn F_Schlick(f0: vec3, f90: f32, VoH: f32) -> vec3 { +fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { var f90_1: f32; - var VoH1: f32; + var VoH_1: f32; - f90_1 = f90; - VoH1 = VoH; + f90_1 = f90_; + VoH_1 = VoH; let e45: f32 = f90_1; - let e49: f32 = VoH1; - let e52: f32 = VoH1; - let e54: f32 = pow5((1.0 - e52)); - return (f0 + ((vec3(e45) - f0) * e54)); + let e49: f32 = VoH_1; + let e52: f32 = VoH_1; + let e54: f32 = pow5_((1.0 - e52)); + return (f0_ + ((vec3(e45) - f0_) * e54)); } -fn F_Schlick1(f0_1: f32, f90_2: f32, VoH2: f32) -> f32 { +fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 { var f0_2: f32; var f90_3: f32; - var VoH3: f32; + var VoH_3: f32; f0_2 = f0_1; f90_3 = f90_2; - VoH3 = VoH2; + VoH_3 = VoH_2; let e46: f32 = f0_2; let e47: f32 = f90_3; let e48: f32 = f0_2; - let e51: f32 = VoH3; - let e54: f32 = VoH3; - let e56: f32 = pow5((1.0 - e54)); + let e51: f32 = VoH_3; + let e54: f32 = VoH_3; + let e56: f32 = pow5_((1.0 - e54)); return (e46 + ((e47 - e48) * e56)); } fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { var f0_4: vec3; - var LoH1: f32; + var LoH_1: f32; var f90_4: f32; f0_4 = f0_3; - LoH1 = LoH; + LoH_1 = LoH; let e49: vec3 = f0_4; let e62: vec3 = f0_4; f90_4 = clamp(dot(e62, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); let e75: vec3 = f0_4; let e76: f32 = f90_4; - let e77: f32 = LoH1; + let e77: f32 = LoH_1; let e78: vec3 = F_Schlick(e75, e76, e77); return e78; } -fn specular(f0_5: vec3, roughness4: f32, h1: vec3, NoV2: f32, NoL2: f32, NoH2: f32, LoH2: f32, specularIntensity: f32) -> vec3 { +fn specular(f0_5: vec3, roughness_4: f32, h_1: vec3, NoV_2: f32, NoL_2: f32, NoH_2: f32, LoH_2: f32, specularIntensity: f32) -> vec3 { var f0_6: vec3; - var roughness5: f32; - var NoV3: f32; - var NoL3: f32; - var NoH3: f32; - var LoH3: f32; - var specularIntensity1: f32; + var roughness_5: f32; + var NoV_3: f32; + var NoL_3: f32; + var NoH_3: f32; + var LoH_3: f32; + var specularIntensity_1: f32; var D: f32; var V: f32; var F: vec3; f0_6 = f0_5; - roughness5 = roughness4; - NoV3 = NoV2; - NoL3 = NoL2; - NoH3 = NoH2; - LoH3 = LoH2; - specularIntensity1 = specularIntensity; - let e57: f32 = roughness5; - let e58: f32 = NoH3; - let e59: f32 = D_GGX(e57, e58, h1); + roughness_5 = roughness_4; + NoV_3 = NoV_2; + NoL_3 = NoL_2; + NoH_3 = NoH_2; + LoH_3 = LoH_2; + specularIntensity_1 = specularIntensity; + let e57: f32 = roughness_5; + let e58: f32 = NoH_3; + let e59: f32 = D_GGX(e57, e58, h_1); D = e59; - let e64: f32 = roughness5; - let e65: f32 = NoV3; - let e66: f32 = NoL3; + let e64: f32 = roughness_5; + let e65: f32 = NoV_3; + let e66: f32 = NoL_3; let e67: f32 = V_SmithGGXCorrelated(e64, e65, e66); V = e67; let e71: vec3 = f0_6; - let e72: f32 = LoH3; + let e72: f32 = LoH_3; let e73: vec3 = fresnel(e71, e72); F = e73; - let e75: f32 = specularIntensity1; + let e75: f32 = specularIntensity_1; let e76: f32 = D; let e78: f32 = V; let e80: vec3 = F; return (((e75 * e76) * e78) * e80); } -fn Fd_Burley(roughness6: f32, NoV4: f32, NoL4: f32, LoH4: f32) -> f32 { - var roughness7: f32; - var NoV5: f32; - var NoL5: f32; - var LoH5: f32; +fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { + var roughness_7: f32; + var NoV_5: f32; + var NoL_5: f32; + var LoH_5: f32; var f90_5: f32; var lightScatter: f32; var viewScatter: f32; - roughness7 = roughness6; - NoV5 = NoV4; - NoL5 = NoL4; - LoH5 = LoH4; - let e50: f32 = roughness7; - let e52: f32 = LoH5; - let e54: f32 = LoH5; + roughness_7 = roughness_6; + NoV_5 = NoV_4; + NoL_5 = NoL_4; + LoH_5 = LoH_4; + let e50: f32 = roughness_7; + let e52: f32 = LoH_5; + let e54: f32 = LoH_5; f90_5 = (0.5 + (((2.0 * e50) * e52) * e54)); let e62: f32 = f90_5; - let e63: f32 = NoL5; - let e64: f32 = F_Schlick1(1.0, e62, e63); + let e63: f32 = NoL_5; + let e64: f32 = F_Schlick_1(1.0, e62, e63); lightScatter = e64; let e70: f32 = f90_5; - let e71: f32 = NoV5; - let e72: f32 = F_Schlick1(1.0, e70, e71); + let e71: f32 = NoV_5; + let e72: f32 = F_Schlick_1(1.0, e70, e71); viewScatter = e72; let e74: f32 = lightScatter; let e75: f32 = viewScatter; return ((e74 * e75) * (1.0 / 3.1415927410125732)); } -fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV6: f32) -> vec3 { +fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 { var f0_8: vec3; - var perceptual_roughness1: f32; - var NoV7: f32; - var c0: vec4 = vec4(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071); - var c1: vec4 = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033); + var perceptual_roughness_1: f32; + var NoV_7: f32; + var c0_: vec4 = vec4(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071); + var c1_: vec4 = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033); var r: vec4; - var a004: f32; + var a004_: f32; var AB: vec2; f0_8 = f0_7; - perceptual_roughness1 = perceptual_roughness; - NoV7 = NoV6; - let e62: f32 = perceptual_roughness1; - let e64: vec4 = c0; - let e66: vec4 = c1; + perceptual_roughness_1 = perceptual_roughness; + NoV_7 = NoV_6; + let e62: f32 = perceptual_roughness_1; + let e64: vec4 = c0_; + let e66: vec4 = c1_; r = ((vec4(e62) * e64) + e66); let e69: vec4 = r; let e71: vec4 = r; - let e76: f32 = NoV7; - let e80: f32 = NoV7; + let e76: f32 = NoV_7; + let e80: f32 = NoV_7; let e83: vec4 = r; let e85: vec4 = r; - let e90: f32 = NoV7; - let e94: f32 = NoV7; + let e90: f32 = NoV_7; + let e94: f32 = NoV_7; let e98: vec4 = r; let e101: vec4 = r; - a004 = ((min((e83.x * e85.x), exp2((-(9.279999732971191) * e94))) * e98.x) + e101.y); - let e109: f32 = a004; + a004_ = ((min((e83.x * e85.x), exp2((-(9.279999732971191) * e94))) * e98.x) + e101.y); + let e109: f32 = a004_; let e112: vec4 = r; AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(e109)) + e112.zw); let e116: vec3 = f0_8; @@ -366,11 +366,11 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV6: f32) -> vec3< } fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { - var perceptualRoughness1: f32; + var perceptualRoughness_1: f32; var clampedPerceptualRoughness: f32; - perceptualRoughness1 = perceptualRoughness; - let e45: f32 = perceptualRoughness1; + perceptualRoughness_1 = perceptualRoughness; + let e45: f32 = perceptualRoughness_1; clampedPerceptualRoughness = clamp(e45, 0.08900000154972076, 1.0); let e50: f32 = clampedPerceptualRoughness; let e51: f32 = clampedPerceptualRoughness; @@ -378,152 +378,152 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { } fn reinhard(color: vec3) -> vec3 { - var color1: vec3; + var color_1: vec3; - color1 = color; - let e42: vec3 = color1; - let e45: vec3 = color1; + color_1 = color; + let e42: vec3 = color_1; + let e45: vec3 = color_1; return (e42 / (vec3(1.0) + e45)); } -fn reinhard_extended(color2: vec3, max_white: f32) -> vec3 { - var color3: vec3; - var max_white1: f32; +fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { + var color_3: vec3; + var max_white_1: f32; var numerator: vec3; - color3 = color2; - max_white1 = max_white; - let e44: vec3 = color3; - let e47: vec3 = color3; - let e48: f32 = max_white1; - let e49: f32 = max_white1; + color_3 = color_2; + max_white_1 = max_white; + let e44: vec3 = color_3; + let e47: vec3 = color_3; + let e48: f32 = max_white_1; + let e49: f32 = max_white_1; numerator = (e44 * (vec3(1.0) + (e47 / vec3((e48 * e49))))); let e56: vec3 = numerator; - let e59: vec3 = color3; + let e59: vec3 = color_3; return (e56 / (vec3(1.0) + e59)); } -fn luminance(v1: vec3) -> f32 { - var v2: vec3; +fn luminance(v_1: vec3) -> f32 { + var v_2: vec3; - v2 = v1; - let e47: vec3 = v2; + v_2 = v_1; + let e47: vec3 = v_2; return dot(e47, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); } fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { - var c_in1: vec3; - var l_out1: f32; + var c_in_1: vec3; + var l_out_1: f32; var l_in: f32; - c_in1 = c_in; - l_out1 = l_out; - let e45: vec3 = c_in1; + c_in_1 = c_in; + l_out_1 = l_out; + let e45: vec3 = c_in_1; let e46: f32 = luminance(e45); l_in = e46; - let e48: vec3 = c_in1; - let e49: f32 = l_out1; + let e48: vec3 = c_in_1; + let e49: f32 = l_out_1; let e50: f32 = l_in; return (e48 * (e49 / e50)); } -fn reinhard_luminance(color4: vec3) -> vec3 { - var color5: vec3; +fn reinhard_luminance(color_4: vec3) -> vec3 { + var color_5: vec3; var l_old: f32; var l_new: f32; - color5 = color4; - let e43: vec3 = color5; + color_5 = color_4; + let e43: vec3 = color_5; let e44: f32 = luminance(e43); l_old = e44; let e46: f32 = l_old; let e48: f32 = l_old; l_new = (e46 / (1.0 + e48)); - let e54: vec3 = color5; + let e54: vec3 = color_5; let e55: f32 = l_new; let e56: vec3 = change_luminance(e54, e55); return e56; } -fn reinhard_extended_luminance(color6: vec3, max_white_l: f32) -> vec3 { - var color7: vec3; - var max_white_l1: f32; - var l_old1: f32; - var numerator1: f32; - var l_new1: f32; +fn reinhard_extended_luminance(color_6: vec3, max_white_l: f32) -> vec3 { + var color_7: vec3; + var max_white_l_1: f32; + var l_old_1: f32; + var numerator_1: f32; + var l_new_1: f32; - color7 = color6; - max_white_l1 = max_white_l; - let e45: vec3 = color7; + color_7 = color_6; + max_white_l_1 = max_white_l; + let e45: vec3 = color_7; let e46: f32 = luminance(e45); - l_old1 = e46; - let e48: f32 = l_old1; - let e50: f32 = l_old1; - let e51: f32 = max_white_l1; - let e52: f32 = max_white_l1; - numerator1 = (e48 * (1.0 + (e50 / (e51 * e52)))); - let e58: f32 = numerator1; - let e60: f32 = l_old1; - l_new1 = (e58 / (1.0 + e60)); - let e66: vec3 = color7; - let e67: f32 = l_new1; + l_old_1 = e46; + let e48: f32 = l_old_1; + let e50: f32 = l_old_1; + let e51: f32 = max_white_l_1; + let e52: f32 = max_white_l_1; + numerator_1 = (e48 * (1.0 + (e50 / (e51 * e52)))); + let e58: f32 = numerator_1; + let e60: f32 = l_old_1; + l_new_1 = (e58 / (1.0 + e60)); + let e66: vec3 = color_7; + let e67: f32 = l_new_1; let e68: vec3 = change_luminance(e66, e67); return e68; } -fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: vec3, R: vec3, F0: vec3, diffuseColor: vec3) -> vec3 { - var light1: PointLight; - var roughness9: f32; - var NdotV1: f32; - var N1: vec3; - var V2: vec3; - var R1: vec3; +fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_1: vec3, R: vec3, F0_: vec3, diffuseColor: vec3) -> vec3 { + var light_1: PointLight; + var roughness_9: f32; + var NdotV_1: f32; + var N_1: vec3; + var V_2: vec3; + var R_1: vec3; var F0_1: vec3; - var diffuseColor1: vec3; + var diffuseColor_1: vec3; var light_to_frag: vec3; var distance_square: f32; var rangeAttenuation: f32; - var a1: f32; + var a_1: f32; var radius: f32; var centerToRay: vec3; var closestPoint: vec3; var LspecLengthInverse: f32; var normalizationFactor: f32; - var specularIntensity2: f32; + var specularIntensity_2: f32; var L: vec3; var H: vec3; - var NoL6: f32; - var NoH4: f32; - var LoH6: f32; - var specular1: vec3; + var NoL_6: f32; + var NoH_4: f32; + var LoH_6: f32; + var specular_1: vec3; var diffuse: vec3; - light1 = light; - roughness9 = roughness8; - NdotV1 = NdotV; - N1 = N; - V2 = V1; - R1 = R; - F0_1 = F0; - diffuseColor1 = diffuseColor; - let e56: PointLight = light1; - let e59: vec3 = v_WorldPosition1; + light_1 = light; + roughness_9 = roughness_8; + NdotV_1 = NdotV; + N_1 = N; + V_2 = V_1; + R_1 = R; + F0_1 = F0_; + diffuseColor_1 = diffuseColor; + let e56: PointLight = light_1; + let e59: vec3 = v_WorldPosition_1; light_to_frag = (e56.pos.xyz - e59.xyz); let e65: vec3 = light_to_frag; let e66: vec3 = light_to_frag; distance_square = dot(e65, e66); - let e70: PointLight = light1; + let e70: PointLight = light_1; let e73: f32 = distance_square; - let e74: PointLight = light1; + let e74: PointLight = light_1; let e77: f32 = getDistanceAttenuation(e73, e74.lightParams.x); rangeAttenuation = e77; - let e79: f32 = roughness9; - a1 = e79; - let e81: PointLight = light1; + let e79: f32 = roughness_9; + a_1 = e79; + let e81: PointLight = light_1; radius = e81.lightParams.y; let e87: vec3 = light_to_frag; - let e88: vec3 = R1; - let e90: vec3 = R1; + let e88: vec3 = R_1; + let e90: vec3 = R_1; let e92: vec3 = light_to_frag; centerToRay = ((dot(e87, e88) * e90) - e92); let e95: vec3 = light_to_frag; @@ -544,213 +544,213 @@ fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3, V1: let e138: vec3 = closestPoint; let e139: vec3 = closestPoint; LspecLengthInverse = inverseSqrt(dot(e138, e139)); - let e143: f32 = a1; - let e144: f32 = a1; + let e143: f32 = a_1; + let e144: f32 = a_1; let e145: f32 = radius; let e148: f32 = LspecLengthInverse; - let e153: f32 = a1; + let e153: f32 = a_1; let e154: f32 = radius; let e157: f32 = LspecLengthInverse; normalizationFactor = (e143 / clamp((e153 + ((e154 * 0.5) * e157)), 0.0, 1.0)); let e165: f32 = normalizationFactor; let e166: f32 = normalizationFactor; - specularIntensity2 = (e165 * e166); + specularIntensity_2 = (e165 * e166); let e169: vec3 = closestPoint; let e170: f32 = LspecLengthInverse; L = (e169 * e170); let e173: vec3 = L; - let e174: vec3 = V2; + let e174: vec3 = V_2; let e176: vec3 = L; - let e177: vec3 = V2; + let e177: vec3 = V_2; H = normalize((e176 + e177)); - let e183: vec3 = N1; + let e183: vec3 = N_1; let e184: vec3 = L; - let e190: vec3 = N1; + let e190: vec3 = N_1; let e191: vec3 = L; - NoL6 = clamp(dot(e190, e191), 0.0, 1.0); - let e199: vec3 = N1; + NoL_6 = clamp(dot(e190, e191), 0.0, 1.0); + let e199: vec3 = N_1; let e200: vec3 = H; - let e206: vec3 = N1; + let e206: vec3 = N_1; let e207: vec3 = H; - NoH4 = clamp(dot(e206, e207), 0.0, 1.0); + NoH_4 = clamp(dot(e206, e207), 0.0, 1.0); let e215: vec3 = L; let e216: vec3 = H; let e222: vec3 = L; let e223: vec3 = H; - LoH6 = clamp(dot(e222, e223), 0.0, 1.0); + LoH_6 = clamp(dot(e222, e223), 0.0, 1.0); let e237: vec3 = F0_1; - let e238: f32 = roughness9; + let e238: f32 = roughness_9; let e239: vec3 = H; - let e240: f32 = NdotV1; - let e241: f32 = NoL6; - let e242: f32 = NoH4; - let e243: f32 = LoH6; - let e244: f32 = specularIntensity2; + let e240: f32 = NdotV_1; + let e241: f32 = NoL_6; + let e242: f32 = NoH_4; + let e243: f32 = LoH_6; + let e244: f32 = specularIntensity_2; let e245: vec3 = specular(e237, e238, e239, e240, e241, e242, e243, e244); - specular1 = e245; + specular_1 = e245; let e248: vec3 = light_to_frag; L = normalize(e248); let e250: vec3 = L; - let e251: vec3 = V2; + let e251: vec3 = V_2; let e253: vec3 = L; - let e254: vec3 = V2; + let e254: vec3 = V_2; H = normalize((e253 + e254)); - let e259: vec3 = N1; + let e259: vec3 = N_1; let e260: vec3 = L; - let e266: vec3 = N1; + let e266: vec3 = N_1; let e267: vec3 = L; - NoL6 = clamp(dot(e266, e267), 0.0, 1.0); - let e274: vec3 = N1; + NoL_6 = clamp(dot(e266, e267), 0.0, 1.0); + let e274: vec3 = N_1; let e275: vec3 = H; - let e281: vec3 = N1; + let e281: vec3 = N_1; let e282: vec3 = H; - NoH4 = clamp(dot(e281, e282), 0.0, 1.0); + NoH_4 = clamp(dot(e281, e282), 0.0, 1.0); let e289: vec3 = L; let e290: vec3 = H; let e296: vec3 = L; let e297: vec3 = H; - LoH6 = clamp(dot(e296, e297), 0.0, 1.0); - let e302: vec3 = diffuseColor1; - let e307: f32 = roughness9; - let e308: f32 = NdotV1; - let e309: f32 = NoL6; - let e310: f32 = LoH6; + LoH_6 = clamp(dot(e296, e297), 0.0, 1.0); + let e302: vec3 = diffuseColor_1; + let e307: f32 = roughness_9; + let e308: f32 = NdotV_1; + let e309: f32 = NoL_6; + let e310: f32 = LoH_6; let e311: f32 = Fd_Burley(e307, e308, e309, e310); diffuse = (e302 * e311); let e314: vec3 = diffuse; - let e315: vec3 = specular1; - let e317: PointLight = light1; + let e315: vec3 = specular_1; + let e317: PointLight = light_1; let e321: f32 = rangeAttenuation; - let e322: f32 = NoL6; + let e322: f32 = NoL_6; return (((e314 + e315) * e317.color.xyz) * (e321 * e322)); } -fn dir_light(light2: DirectionalLight, roughness10: f32, NdotV2: f32, normal: vec3, view: vec3, R2: vec3, F0_2: vec3, diffuseColor2: vec3) -> vec3 { - var light3: DirectionalLight; - var roughness11: f32; - var NdotV3: f32; - var normal1: vec3; - var view1: vec3; - var R3: vec3; +fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: vec3, view: vec3, R_2: vec3, F0_2: vec3, diffuseColor_2: vec3) -> vec3 { + var light_3: DirectionalLight; + var roughness_11: f32; + var NdotV_3: f32; + var normal_1: vec3; + var view_1: vec3; + var R_3: vec3; var F0_3: vec3; - var diffuseColor3: vec3; + var diffuseColor_3: vec3; var incident_light: vec3; var half_vector: vec3; - var NoL7: f32; - var NoH5: f32; - var LoH7: f32; - var diffuse1: vec3; - var specularIntensity3: f32 = 1.0; - var specular2: vec3; + var NoL_7: f32; + var NoH_5: f32; + var LoH_7: f32; + var diffuse_1: vec3; + var specularIntensity_3: f32 = 1.0; + var specular_2: vec3; - light3 = light2; - roughness11 = roughness10; - NdotV3 = NdotV2; - normal1 = normal; - view1 = view; - R3 = R2; + light_3 = light_2; + roughness_11 = roughness_10; + NdotV_3 = NdotV_2; + normal_1 = normal; + view_1 = view; + R_3 = R_2; F0_3 = F0_2; - diffuseColor3 = diffuseColor2; - let e56: DirectionalLight = light3; + diffuseColor_3 = diffuseColor_2; + let e56: DirectionalLight = light_3; incident_light = e56.direction.xyz; let e60: vec3 = incident_light; - let e61: vec3 = view1; + let e61: vec3 = view_1; let e63: vec3 = incident_light; - let e64: vec3 = view1; + let e64: vec3 = view_1; half_vector = normalize((e63 + e64)); - let e70: vec3 = normal1; + let e70: vec3 = normal_1; let e71: vec3 = incident_light; - let e77: vec3 = normal1; + let e77: vec3 = normal_1; let e78: vec3 = incident_light; - NoL7 = clamp(dot(e77, e78), 0.0, 1.0); - let e86: vec3 = normal1; + NoL_7 = clamp(dot(e77, e78), 0.0, 1.0); + let e86: vec3 = normal_1; let e87: vec3 = half_vector; - let e93: vec3 = normal1; + let e93: vec3 = normal_1; let e94: vec3 = half_vector; - NoH5 = clamp(dot(e93, e94), 0.0, 1.0); + NoH_5 = clamp(dot(e93, e94), 0.0, 1.0); let e102: vec3 = incident_light; let e103: vec3 = half_vector; let e109: vec3 = incident_light; let e110: vec3 = half_vector; - LoH7 = clamp(dot(e109, e110), 0.0, 1.0); - let e116: vec3 = diffuseColor3; - let e121: f32 = roughness11; - let e122: f32 = NdotV3; - let e123: f32 = NoL7; - let e124: f32 = LoH7; + LoH_7 = clamp(dot(e109, e110), 0.0, 1.0); + let e116: vec3 = diffuseColor_3; + let e121: f32 = roughness_11; + let e122: f32 = NdotV_3; + let e123: f32 = NoL_7; + let e124: f32 = LoH_7; let e125: f32 = Fd_Burley(e121, e122, e123, e124); - diffuse1 = (e116 * e125); + diffuse_1 = (e116 * e125); let e138: vec3 = F0_3; - let e139: f32 = roughness11; + let e139: f32 = roughness_11; let e140: vec3 = half_vector; - let e141: f32 = NdotV3; - let e142: f32 = NoL7; - let e143: f32 = NoH5; - let e144: f32 = LoH7; - let e145: f32 = specularIntensity3; + let e141: f32 = NdotV_3; + let e142: f32 = NoL_7; + let e143: f32 = NoH_5; + let e144: f32 = LoH_7; + let e145: f32 = specularIntensity_3; let e146: vec3 = specular(e138, e139, e140, e141, e142, e143, e144, e145); - specular2 = e146; - let e148: vec3 = specular2; - let e149: vec3 = diffuse1; - let e151: DirectionalLight = light3; - let e155: f32 = NoL7; + specular_2 = e146; + let e148: vec3 = specular_2; + let e149: vec3 = diffuse_1; + let e151: DirectionalLight = light_3; + let e155: f32 = NoL_7; return (((e148 + e149) * e151.color.xyz) * e155); } -fn main1() { +fn main_1() { var output_color: vec4; var metallic_roughness: vec4; var metallic: f32; - var perceptual_roughness2: f32; - var roughness12: f32; - var N2: vec3; + var perceptual_roughness_2: f32; + var roughness_12: f32; + var N_2: vec3; var T: vec3; var B: vec3; var TBN: mat3x3; var occlusion: f32; var emissive: vec4; - var V3: vec3; - var NdotV4: f32; + var V_3: vec3; + var NdotV_4: f32; var F0_4: vec3; - var diffuseColor4: vec3; - var R4: vec3; + var diffuseColor_4: vec3; + var R_4: vec3; var light_accum: vec3 = vec3(0.0, 0.0, 0.0); var i: i32 = 0; - var i1: i32 = 0; + var i_1: i32 = 0; var diffuse_ambient: vec3; var specular_ambient: vec3; - let e40: vec4 = global3.base_color; + let e40: vec4 = global_3.base_color; output_color = e40; let e42: vec4 = output_color; - let e44: vec2 = v_Uv1; + let e44: vec2 = v_Uv_1; let e45: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, e44); output_color = (e42 * e45); - let e48: vec2 = v_Uv1; + let e48: vec2 = v_Uv_1; let e49: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, e48); metallic_roughness = e49; - let e51: f32 = global5.metallic; + let e51: f32 = global_5.metallic; let e52: vec4 = metallic_roughness; metallic = (e51 * e52.z); - let e56: f32 = global4.perceptual_roughness; + let e56: f32 = global_4.perceptual_roughness; let e57: vec4 = metallic_roughness; - perceptual_roughness2 = (e56 * e57.y); - let e62: f32 = perceptual_roughness2; + perceptual_roughness_2 = (e56 * e57.y); + let e62: f32 = perceptual_roughness_2; let e63: f32 = perceptualRoughnessToRoughness(e62); - roughness12 = e63; - let e66: vec3 = v_WorldNormal1; - N2 = normalize(e66); - let e69: vec4 = v_WorldTangent1; - let e71: vec4 = v_WorldTangent1; + roughness_12 = e63; + let e66: vec3 = v_WorldNormal_1; + N_2 = normalize(e66); + let e69: vec4 = v_WorldTangent_1; + let e71: vec4 = v_WorldTangent_1; T = normalize(e71.xyz); - let e77: vec3 = N2; + let e77: vec3 = N_2; let e78: vec3 = T; - let e80: vec4 = v_WorldTangent1; + let e80: vec4 = v_WorldTangent_1; B = (cross(e77, e78) * e80.w); let e85: bool = gl_FrontFacing; - let e86: vec3 = N2; - let e87: vec3 = N2; - N2 = select(-(e87), e86, e85); + let e86: vec3 = N_2; + let e87: vec3 = N_2; + N_2 = select(-(e87), e86, e85); let e90: bool = gl_FrontFacing; let e91: vec3 = T; let e92: vec3 = T; @@ -761,53 +761,53 @@ fn main1() { B = select(-(e97), e96, e95); let e100: vec3 = T; let e101: vec3 = B; - let e102: vec3 = N2; + let e102: vec3 = N_2; TBN = mat3x3(vec3(e100.x, e100.y, e100.z), vec3(e101.x, e101.y, e101.z), vec3(e102.x, e102.y, e102.z)); let e117: mat3x3 = TBN; - let e119: vec2 = v_Uv1; + let e119: vec2 = v_Uv_1; let e120: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e119); - let e128: vec2 = v_Uv1; + let e128: vec2 = v_Uv_1; let e129: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e128); - N2 = (e117 * normalize(((e129.xyz * 2.0) - vec3(1.0)))); - let e139: vec2 = v_Uv1; + N_2 = (e117 * normalize(((e129.xyz * 2.0) - vec3(1.0)))); + let e139: vec2 = v_Uv_1; let e140: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, e139); occlusion = e140.x; - let e143: vec4 = global7.emissive; + let e143: vec4 = global_7.emissive; emissive = e143; let e145: vec4 = emissive; let e147: vec4 = emissive; - let e150: vec2 = v_Uv1; + let e150: vec2 = v_Uv_1; let e151: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, e150); let e153: vec3 = (e147.xyz * e151.xyz); emissive.x = e153.x; emissive.y = e153.y; emissive.z = e153.z; - let e160: vec4 = global1.CameraPos; - let e162: vec3 = v_WorldPosition1; - let e165: vec4 = global1.CameraPos; - let e167: vec3 = v_WorldPosition1; - V3 = normalize((e165.xyz - e167.xyz)); - let e174: vec3 = N2; - let e175: vec3 = V3; - let e180: vec3 = N2; - let e181: vec3 = V3; - NdotV4 = max(dot(e180, e181), 0.0010000000474974513); - let e187: f32 = global6.reflectance; - let e189: f32 = global6.reflectance; + let e160: vec4 = global_1.CameraPos; + let e162: vec3 = v_WorldPosition_1; + let e165: vec4 = global_1.CameraPos; + let e167: vec3 = v_WorldPosition_1; + V_3 = normalize((e165.xyz - e167.xyz)); + let e174: vec3 = N_2; + let e175: vec3 = V_3; + let e180: vec3 = N_2; + let e181: vec3 = V_3; + NdotV_4 = max(dot(e180, e181), 0.0010000000474974513); + let e187: f32 = global_6.reflectance; + let e189: f32 = global_6.reflectance; let e192: f32 = metallic; let e196: vec4 = output_color; let e198: f32 = metallic; F0_4 = (vec3((((0.1599999964237213 * e187) * e189) * (1.0 - e192))) + (e196.xyz * vec3(e198))); let e203: vec4 = output_color; let e206: f32 = metallic; - diffuseColor4 = (e203.xyz * vec3((1.0 - e206))); - let e211: vec3 = V3; - let e214: vec3 = V3; - let e216: vec3 = N2; - R4 = reflect(-(e214), e216); + diffuseColor_4 = (e203.xyz * vec3((1.0 - e206))); + let e211: vec3 = V_3; + let e214: vec3 = V_3; + let e216: vec3 = N_2; + R_4 = reflect(-(e214), e216); loop { let e224: i32 = i; - let e225: vec4 = global2.NumLights; + let e225: vec4 = global_2.NumLights; let e229: i32 = i; if (!(((e224 < i32(e225.x)) && (e229 < 10)))) { break; @@ -816,14 +816,14 @@ fn main1() { let e236: vec3 = light_accum; let e237: i32 = i; let e247: i32 = i; - let e249: PointLight = global2.PointLights[e247]; - let e250: f32 = roughness12; - let e251: f32 = NdotV4; - let e252: vec3 = N2; - let e253: vec3 = V3; - let e254: vec3 = R4; + let e249: PointLight = global_2.PointLights[e247]; + let e250: f32 = roughness_12; + let e251: f32 = NdotV_4; + let e252: vec3 = N_2; + let e253: vec3 = V_3; + let e254: vec3 = R_4; let e255: vec3 = F0_4; - let e256: vec3 = diffuseColor4; + let e256: vec3 = diffuseColor_4; let e257: vec3 = point_light(e249, e250, e251, e252, e253, e254, e255, e256); light_accum = (e236 + e257); } @@ -833,39 +833,39 @@ fn main1() { } } loop { - let e261: i32 = i1; - let e262: vec4 = global2.NumLights; - let e266: i32 = i1; + let e261: i32 = i_1; + let e262: vec4 = global_2.NumLights; + let e266: i32 = i_1; if (!(((e261 < i32(e262.y)) && (e266 < 1)))) { break; } { let e273: vec3 = light_accum; - let e274: i32 = i1; - let e284: i32 = i1; - let e286: DirectionalLight = global2.DirectionalLights[e284]; - let e287: f32 = roughness12; - let e288: f32 = NdotV4; - let e289: vec3 = N2; - let e290: vec3 = V3; - let e291: vec3 = R4; + let e274: i32 = i_1; + let e284: i32 = i_1; + let e286: DirectionalLight = global_2.DirectionalLights[e284]; + let e287: f32 = roughness_12; + let e288: f32 = NdotV_4; + let e289: vec3 = N_2; + let e290: vec3 = V_3; + let e291: vec3 = R_4; let e292: vec3 = F0_4; - let e293: vec3 = diffuseColor4; + let e293: vec3 = diffuseColor_4; let e294: vec3 = dir_light(e286, e287, e288, e289, e290, e291, e292, e293); light_accum = (e273 + e294); } continuing { - let e270: i32 = i1; - i1 = (e270 + 1); + let e270: i32 = i_1; + i_1 = (e270 + 1); } } - let e299: vec3 = diffuseColor4; - let e301: f32 = NdotV4; + let e299: vec3 = diffuseColor_4; + let e301: f32 = NdotV_4; let e302: vec3 = EnvBRDFApprox(e299, 1.0, e301); diffuse_ambient = e302; let e307: vec3 = F0_4; - let e308: f32 = perceptual_roughness2; - let e309: f32 = NdotV4; + let e308: f32 = perceptual_roughness_2; + let e309: f32 = NdotV_4; let e310: vec3 = EnvBRDFApprox(e307, e308, e309); specular_ambient = e310; let e312: vec4 = output_color; @@ -877,7 +877,7 @@ fn main1() { let e323: vec4 = output_color; let e325: vec3 = diffuse_ambient; let e326: vec3 = specular_ambient; - let e328: vec4 = global2.AmbientColor; + let e328: vec4 = global_2.AmbientColor; let e331: f32 = occlusion; let e333: vec3 = (e323.xyz + (((e325 + e326) * e328.xyz) * e331)); output_color.x = e333.x; @@ -905,12 +905,12 @@ fn main1() { [[stage(fragment)]] fn main([[location(0)]] v_WorldPosition: vec3, [[location(1)]] v_WorldNormal: vec3, [[location(2)]] v_Uv: vec2, [[location(3)]] v_WorldTangent: vec4, [[builtin(front_facing)]] param: bool) -> FragmentOutput { - v_WorldPosition1 = v_WorldPosition; - v_WorldNormal1 = v_WorldNormal; - v_Uv1 = v_Uv; - v_WorldTangent1 = v_WorldTangent; + v_WorldPosition_1 = v_WorldPosition; + v_WorldNormal_1 = v_WorldNormal; + v_Uv_1 = v_Uv; + v_WorldTangent_1 = v_WorldTangent; gl_FrontFacing = param; - main1(); + main_1(); let e72: vec4 = o_Target; return FragmentOutput(e72); } diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 2f629ea89..e448ca91f 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -16,10 +16,10 @@ struct VertexOutput { [[builtin(position)]] member: vec4; }; -var Vertex_Position1: vec3; -var Vertex_Normal1: vec3; -var Vertex_Uv1: vec2; -var Vertex_Tangent1: vec4; +var Vertex_Position_1: vec3; +var Vertex_Normal_1: vec3; +var Vertex_Uv_1: vec2; +var Vertex_Tangent_1: vec4; var v_WorldPosition: vec3; var v_WorldNormal: vec3; var v_Uv: vec2; @@ -27,25 +27,25 @@ var v_Uv: vec2; var global: CameraViewProj; var v_WorldTangent: vec4; [[group(2), binding(0)]] -var global1: Transform; +var global_1: Transform; var gl_Position: vec4; -fn main1() { +fn main_1() { var world_position: vec4; - let e12: mat4x4 = global1.Model; - let e13: vec3 = Vertex_Position1; + let e12: mat4x4 = global_1.Model; + let e13: vec3 = Vertex_Position_1; world_position = (e12 * vec4(e13, 1.0)); let e18: vec4 = world_position; v_WorldPosition = e18.xyz; - let e20: mat4x4 = global1.Model; - let e28: vec3 = Vertex_Normal1; + let e20: mat4x4 = global_1.Model; + let e28: vec3 = Vertex_Normal_1; v_WorldNormal = (mat3x3(e20[0].xyz, e20[1].xyz, e20[2].xyz) * e28); - let e30: vec2 = Vertex_Uv1; + let e30: vec2 = Vertex_Uv_1; v_Uv = e30; - let e31: mat4x4 = global1.Model; - let e39: vec4 = Vertex_Tangent1; - let e42: vec4 = Vertex_Tangent1; + let e31: mat4x4 = global_1.Model; + let e39: vec4 = Vertex_Tangent_1; + let e42: vec4 = Vertex_Tangent_1; v_WorldTangent = vec4((mat3x3(e31[0].xyz, e31[1].xyz, e31[2].xyz) * e39.xyz), e42.w); let e46: mat4x4 = global.ViewProj; let e47: vec4 = world_position; @@ -55,11 +55,11 @@ fn main1() { [[stage(vertex)]] fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Normal: vec3, [[location(2)]] Vertex_Uv: vec2, [[location(3)]] Vertex_Tangent: vec4) -> VertexOutput { - Vertex_Position1 = Vertex_Position; - Vertex_Normal1 = Vertex_Normal; - Vertex_Uv1 = Vertex_Uv; - Vertex_Tangent1 = Vertex_Tangent; - main1(); + Vertex_Position_1 = Vertex_Position; + Vertex_Normal_1 = Vertex_Normal; + Vertex_Uv_1 = Vertex_Uv; + Vertex_Tangent_1 = Vertex_Tangent; + main_1(); let e29: vec3 = v_WorldPosition; let e31: vec3 = v_WorldNormal; let e33: vec2 = v_Uv; diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index f2984d5ac..c4054d8e3 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -1,83 +1,83 @@ [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { var i: i32 = 0; - var i2: vec2; - var i3: vec3; - var i4: vec4; + var i2_: vec2; + var i3_: vec3; + var i4_: vec4; var u: u32 = 0u; - var u2: vec2; - var u3: vec3; - var u4: vec4; - var f2: vec2; - var f4: vec4; + var u2_: vec2; + var u3_: vec3; + var u4_: vec4; + var f2_: vec2; + var f4_: vec4; - i2 = vec2(0); - i3 = vec3(0); - i4 = vec4(0); - u2 = vec2(0u); - u3 = vec3(0u); - u4 = vec4(0u); - f2 = vec2(0.0); - f4 = vec4(0.0); - let e28: vec4 = f4; + i2_ = vec2(0); + i3_ = vec3(0); + i4_ = vec4(0); + u2_ = vec2(0u); + u3_ = vec3(0u); + u4_ = vec4(0u); + f2_ = vec2(0.0); + f4_ = vec4(0.0); + let e28: vec4 = f4_; u = pack4x8snorm(e28); - let e30: vec4 = f4; + let e30: vec4 = f4_; u = pack4x8unorm(e30); - let e32: vec2 = f2; + let e32: vec2 = f2_; u = pack2x16snorm(e32); - let e34: vec2 = f2; + let e34: vec2 = f2_; u = pack2x16unorm(e34); - let e36: vec2 = f2; + let e36: vec2 = f2_; u = pack2x16float(e36); let e38: u32 = u; - f4 = unpack4x8snorm(e38); + f4_ = unpack4x8snorm(e38); let e40: u32 = u; - f4 = unpack4x8unorm(e40); + f4_ = unpack4x8unorm(e40); let e42: u32 = u; - f2 = unpack2x16snorm(e42); + f2_ = unpack2x16snorm(e42); let e44: u32 = u; - f2 = unpack2x16unorm(e44); + f2_ = unpack2x16unorm(e44); let e46: u32 = u; - f2 = unpack2x16float(e46); + f2_ = unpack2x16float(e46); let e48: i32 = i; let e49: i32 = i; i = insertBits(e48, e49, 5u, 10u); - let e53: vec2 = i2; - let e54: vec2 = i2; - i2 = insertBits(e53, e54, 5u, 10u); - let e58: vec3 = i3; - let e59: vec3 = i3; - i3 = insertBits(e58, e59, 5u, 10u); - let e63: vec4 = i4; - let e64: vec4 = i4; - i4 = insertBits(e63, e64, 5u, 10u); + let e53: vec2 = i2_; + let e54: vec2 = i2_; + i2_ = insertBits(e53, e54, 5u, 10u); + let e58: vec3 = i3_; + let e59: vec3 = i3_; + i3_ = insertBits(e58, e59, 5u, 10u); + let e63: vec4 = i4_; + let e64: vec4 = i4_; + i4_ = insertBits(e63, e64, 5u, 10u); let e68: u32 = u; let e69: u32 = u; u = insertBits(e68, e69, 5u, 10u); - let e73: vec2 = u2; - let e74: vec2 = u2; - u2 = insertBits(e73, e74, 5u, 10u); - let e78: vec3 = u3; - let e79: vec3 = u3; - u3 = insertBits(e78, e79, 5u, 10u); - let e83: vec4 = u4; - let e84: vec4 = u4; - u4 = insertBits(e83, e84, 5u, 10u); + let e73: vec2 = u2_; + let e74: vec2 = u2_; + u2_ = insertBits(e73, e74, 5u, 10u); + let e78: vec3 = u3_; + let e79: vec3 = u3_; + u3_ = insertBits(e78, e79, 5u, 10u); + let e83: vec4 = u4_; + let e84: vec4 = u4_; + u4_ = insertBits(e83, e84, 5u, 10u); let e88: i32 = i; i = extractBits(e88, 5u, 10u); - let e92: vec2 = i2; - i2 = extractBits(e92, 5u, 10u); - let e96: vec3 = i3; - i3 = extractBits(e96, 5u, 10u); - let e100: vec4 = i4; - i4 = extractBits(e100, 5u, 10u); + let e92: vec2 = i2_; + i2_ = extractBits(e92, 5u, 10u); + let e96: vec3 = i3_; + i3_ = extractBits(e96, 5u, 10u); + let e100: vec4 = i4_; + i4_ = extractBits(e100, 5u, 10u); let e104: u32 = u; u = extractBits(e104, 5u, 10u); - let e108: vec2 = u2; - u2 = extractBits(e108, 5u, 10u); - let e112: vec3 = u3; - u3 = extractBits(e112, 5u, 10u); - let e116: vec4 = u4; - u4 = extractBits(e116, 5u, 10u); + let e108: vec2 = u2_; + u2_ = extractBits(e108, 5u, 10u); + let e112: vec3 = u3_; + u3_ = extractBits(e112, 5u, 10u); + let e116: vec4 = u4_; + u4_ = extractBits(e116, 5u, 10u); return; } diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 3f0e7cf7e..3efc01918 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -1,80 +1,80 @@ -fn main1() { +fn main_1() { var i: i32 = 0; - var i2: vec2 = vec2(0, 0); - var i3: vec3 = vec3(0, 0, 0); - var i4: vec4 = vec4(0, 0, 0, 0); + var i2_: vec2 = vec2(0, 0); + var i3_: vec3 = vec3(0, 0, 0); + var i4_: vec4 = vec4(0, 0, 0, 0); var u: u32 = 0u; - var u2: vec2 = vec2(0u, 0u); - var u3: vec3 = vec3(0u, 0u, 0u); - var u4: vec4 = vec4(0u, 0u, 0u, 0u); - var f2: vec2 = vec2(0.0, 0.0); - var f4: vec4 = vec4(0.0, 0.0, 0.0, 0.0); + var u2_: vec2 = vec2(0u, 0u); + var u3_: vec3 = vec3(0u, 0u, 0u); + var u4_: vec4 = vec4(0u, 0u, 0u, 0u); + var f2_: vec2 = vec2(0.0, 0.0); + var f4_: vec4 = vec4(0.0, 0.0, 0.0, 0.0); - let e33: vec4 = f4; + let e33: vec4 = f4_; u = pack4x8snorm(e33); - let e36: vec4 = f4; + let e36: vec4 = f4_; u = pack4x8unorm(e36); - let e39: vec2 = f2; + let e39: vec2 = f2_; u = pack2x16unorm(e39); - let e42: vec2 = f2; + let e42: vec2 = f2_; u = pack2x16snorm(e42); - let e45: vec2 = f2; + let e45: vec2 = f2_; u = pack2x16float(e45); let e48: u32 = u; - f4 = unpack4x8snorm(e48); + f4_ = unpack4x8snorm(e48); let e51: u32 = u; - f4 = unpack4x8unorm(e51); + f4_ = unpack4x8unorm(e51); let e54: u32 = u; - f2 = unpack2x16snorm(e54); + f2_ = unpack2x16snorm(e54); let e57: u32 = u; - f2 = unpack2x16unorm(e57); + f2_ = unpack2x16unorm(e57); let e60: u32 = u; - f2 = unpack2x16float(e60); + f2_ = unpack2x16float(e60); let e66: i32 = i; let e67: i32 = i; i = insertBits(e66, e67, u32(5), u32(10)); - let e77: vec2 = i2; - let e78: vec2 = i2; - i2 = insertBits(e77, e78, u32(5), u32(10)); - let e88: vec3 = i3; - let e89: vec3 = i3; - i3 = insertBits(e88, e89, u32(5), u32(10)); - let e99: vec4 = i4; - let e100: vec4 = i4; - i4 = insertBits(e99, e100, u32(5), u32(10)); + let e77: vec2 = i2_; + let e78: vec2 = i2_; + i2_ = insertBits(e77, e78, u32(5), u32(10)); + let e88: vec3 = i3_; + let e89: vec3 = i3_; + i3_ = insertBits(e88, e89, u32(5), u32(10)); + let e99: vec4 = i4_; + let e100: vec4 = i4_; + i4_ = insertBits(e99, e100, u32(5), u32(10)); let e110: u32 = u; let e111: u32 = u; u = insertBits(e110, e111, u32(5), u32(10)); - let e121: vec2 = u2; - let e122: vec2 = u2; - u2 = insertBits(e121, e122, u32(5), u32(10)); - let e132: vec3 = u3; - let e133: vec3 = u3; - u3 = insertBits(e132, e133, u32(5), u32(10)); - let e143: vec4 = u4; - let e144: vec4 = u4; - u4 = insertBits(e143, e144, u32(5), u32(10)); + let e121: vec2 = u2_; + let e122: vec2 = u2_; + u2_ = insertBits(e121, e122, u32(5), u32(10)); + let e132: vec3 = u3_; + let e133: vec3 = u3_; + u3_ = insertBits(e132, e133, u32(5), u32(10)); + let e143: vec4 = u4_; + let e144: vec4 = u4_; + u4_ = insertBits(e143, e144, u32(5), u32(10)); let e153: i32 = i; i = extractBits(e153, u32(5), u32(10)); - let e162: vec2 = i2; - i2 = extractBits(e162, u32(5), u32(10)); - let e171: vec3 = i3; - i3 = extractBits(e171, u32(5), u32(10)); - let e180: vec4 = i4; - i4 = extractBits(e180, u32(5), u32(10)); + let e162: vec2 = i2_; + i2_ = extractBits(e162, u32(5), u32(10)); + let e171: vec3 = i3_; + i3_ = extractBits(e171, u32(5), u32(10)); + let e180: vec4 = i4_; + i4_ = extractBits(e180, u32(5), u32(10)); let e189: u32 = u; u = extractBits(e189, u32(5), u32(10)); - let e198: vec2 = u2; - u2 = extractBits(e198, u32(5), u32(10)); - let e207: vec3 = u3; - u3 = extractBits(e207, u32(5), u32(10)); - let e216: vec4 = u4; - u4 = extractBits(e216, u32(5), u32(10)); + let e198: vec2 = u2_; + u2_ = extractBits(e198, u32(5), u32(10)); + let e207: vec3 = u3_; + u3_ = extractBits(e207, u32(5), u32(10)); + let e216: vec4 = u4_; + u4_ = extractBits(e216, u32(5), u32(10)); return; } [[stage(fragment)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index 1ef8e9465..f1c4890d0 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -5,30 +5,30 @@ struct FragmentOutput { var o_color: vec4; fn TevPerCompGT(a: f32, b: f32) -> f32 { - var a1: f32; - var b1: f32; + var a_1: f32; + var b_1: f32; - a1 = a; - b1 = b; - let e5: f32 = a1; - let e6: f32 = b1; + a_1 = a; + b_1 = b; + let e5: f32 = a_1; + let e6: f32 = b_1; return select(0.0, 1.0, (e5 > e6)); } -fn TevPerCompGT1(a2: vec3, b2: vec3) -> vec3 { - var a3: vec3; - var b3: vec3; +fn TevPerCompGT_1(a_2: vec3, b_2: vec3) -> vec3 { + var a_3: vec3; + var b_3: vec3; - a3 = a2; - b3 = b2; - let e7: vec3 = a3; - let e8: vec3 = b3; + a_3 = a_2; + b_3 = b_2; + let e7: vec3 = a_3; + let e8: vec3 = b_3; return select(vec3(0.0), vec3(1.0), (e7 > e8)); } -fn main1() { +fn main_1() { let e1: vec4 = o_color; - let e11: vec3 = TevPerCompGT1(vec3(3.0), vec3(5.0)); + let e11: vec3 = TevPerCompGT_1(vec3(3.0), vec3(5.0)); o_color.x = e11.x; o_color.y = e11.y; o_color.z = e11.z; @@ -39,7 +39,7 @@ fn main1() { [[stage(fragment)]] fn main() -> FragmentOutput { - main1(); + main_1(); let e3: vec4 = o_color; return FragmentOutput(e3); } diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index 4dfea0b08..cfdb9a50b 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -2,19 +2,19 @@ struct VertexOutput { [[builtin(position)]] member: vec4; }; -var a_pos1: vec2; +var a_pos_1: vec2; var gl_Position: vec4; -fn main1() { - let e5: vec2 = a_pos1; +fn main_1() { + let e5: vec2 = a_pos_1; gl_Position = vec4(clamp(e5, vec2(0.0), vec2(1.0)), 0.0, 1.0); return; } [[stage(vertex)]] fn main([[location(0)]] a_pos: vec2) -> VertexOutput { - a_pos1 = a_pos; - main1(); + a_pos_1 = a_pos; + main_1(); let e5: vec4 = gl_Position; return VertexOutput(e5); } diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 4987dae38..4fb8538b6 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -6,7 +6,7 @@ struct Data { [[group(1), binding(0)]] var global: Data; -fn function1() -> vec4 { +fn function_() -> vec4 { var sum: vec4 = vec4(0.0, 0.0, 0.0, 0.0); var i: i32 = 0; @@ -30,12 +30,12 @@ fn function1() -> vec4 { return e20; } -fn main1() { +fn main_1() { return; } [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index 40c02ee05..ae85915b3 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -1,18 +1,18 @@ [[block]] -struct type2 { +struct type_1 { member: i32; }; [[group(0), binding(0)]] -var global: type2; +var unnamed: type_1; -fn function1() { - let e8: i32 = global.member; - global.member = (e8 + 1); +fn function_() { + let e8: i32 = unnamed.member; + unnamed.member = (e8 + 1); return; } [[stage(compute), workgroup_size(64, 1, 1)]] fn main() { - function1(); + function_(); } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 8e1316750..899978fbb 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -6,172 +6,172 @@ var global: f32; var o_color: vec4; fn testBinOpVecFloat(a: vec4, b: f32) { - var a1: vec4; - var b1: f32; + var a_1: vec4; + var b_1: f32; var v: vec4; - a1 = a; - b1 = b; - let e5: vec4 = a1; + a_1 = a; + b_1 = b; + let e5: vec4 = a_1; v = (e5 * 2.0); - let e8: vec4 = a1; + let e8: vec4 = a_1; v = (e8 / vec4(2.0)); - let e12: vec4 = a1; + let e12: vec4 = a_1; v = (e12 + vec4(2.0)); - let e16: vec4 = a1; + let e16: vec4 = a_1; v = (e16 - vec4(2.0)); return; } -fn testBinOpFloatVec(a2: vec4, b2: f32) { - var a3: vec4; - var b3: f32; - var v1: vec4; +fn testBinOpFloatVec(a_2: vec4, b_2: f32) { + var a_3: vec4; + var b_3: f32; + var v_1: vec4; - a3 = a2; - b3 = b2; - let e5: vec4 = a3; - let e6: f32 = b3; - v1 = (e5 * e6); - let e8: vec4 = a3; - let e9: f32 = b3; - v1 = (e8 / vec4(e9)); - let e12: vec4 = a3; - let e13: f32 = b3; - v1 = (e12 + vec4(e13)); - let e16: vec4 = a3; - let e17: f32 = b3; - v1 = (e16 - vec4(e17)); + a_3 = a_2; + b_3 = b_2; + let e5: vec4 = a_3; + let e6: f32 = b_3; + v_1 = (e5 * e6); + let e8: vec4 = a_3; + let e9: f32 = b_3; + v_1 = (e8 / vec4(e9)); + let e12: vec4 = a_3; + let e13: f32 = b_3; + v_1 = (e12 + vec4(e13)); + let e16: vec4 = a_3; + let e17: f32 = b_3; + v_1 = (e16 - vec4(e17)); return; } -fn testBinOpIVecInt(a4: vec4, b4: i32) { - var a5: vec4; - var b5: i32; - var v2: vec4; +fn testBinOpIVecInt(a_4: vec4, b_4: i32) { + var a_5: vec4; + var b_5: i32; + var v_2: vec4; - a5 = a4; - b5 = b4; - let e5: vec4 = a5; - let e6: i32 = b5; - v2 = (e5 * e6); - let e8: vec4 = a5; - let e9: i32 = b5; - v2 = (e8 / vec4(e9)); - let e12: vec4 = a5; - let e13: i32 = b5; - v2 = (e12 + vec4(e13)); - let e16: vec4 = a5; - let e17: i32 = b5; - v2 = (e16 - vec4(e17)); - let e20: vec4 = a5; - let e21: i32 = b5; - v2 = (e20 & vec4(e21)); - let e24: vec4 = a5; - let e25: i32 = b5; - v2 = (e24 | vec4(e25)); - let e28: vec4 = a5; - let e29: i32 = b5; - v2 = (e28 ^ vec4(e29)); - let e32: vec4 = a5; - let e33: i32 = b5; - v2 = (e32 >> vec4(u32(e33))); - let e37: vec4 = a5; - let e38: i32 = b5; - v2 = (e37 << vec4(u32(e38))); + a_5 = a_4; + b_5 = b_4; + let e5: vec4 = a_5; + let e6: i32 = b_5; + v_2 = (e5 * e6); + let e8: vec4 = a_5; + let e9: i32 = b_5; + v_2 = (e8 / vec4(e9)); + let e12: vec4 = a_5; + let e13: i32 = b_5; + v_2 = (e12 + vec4(e13)); + let e16: vec4 = a_5; + let e17: i32 = b_5; + v_2 = (e16 - vec4(e17)); + let e20: vec4 = a_5; + let e21: i32 = b_5; + v_2 = (e20 & vec4(e21)); + let e24: vec4 = a_5; + let e25: i32 = b_5; + v_2 = (e24 | vec4(e25)); + let e28: vec4 = a_5; + let e29: i32 = b_5; + v_2 = (e28 ^ vec4(e29)); + let e32: vec4 = a_5; + let e33: i32 = b_5; + v_2 = (e32 >> vec4(u32(e33))); + let e37: vec4 = a_5; + let e38: i32 = b_5; + v_2 = (e37 << vec4(u32(e38))); return; } -fn testBinOpIntIVec(a6: i32, b6: vec4) { - var a7: i32; - var b7: vec4; - var v3: vec4; +fn testBinOpIntIVec(a_6: i32, b_6: vec4) { + var a_7: i32; + var b_7: vec4; + var v_3: vec4; - a7 = a6; - b7 = b6; - let e5: i32 = a7; - let e6: vec4 = b7; - v3 = (e5 * e6); - let e8: i32 = a7; - let e9: vec4 = b7; - v3 = (vec4(e8) + e9); - let e12: i32 = a7; - let e13: vec4 = b7; - v3 = (vec4(e12) - e13); - let e16: i32 = a7; - let e17: vec4 = b7; - v3 = (vec4(e16) & e17); - let e20: i32 = a7; - let e21: vec4 = b7; - v3 = (vec4(e20) | e21); - let e24: i32 = a7; - let e25: vec4 = b7; - v3 = (vec4(e24) ^ e25); + a_7 = a_6; + b_7 = b_6; + let e5: i32 = a_7; + let e6: vec4 = b_7; + v_3 = (e5 * e6); + let e8: i32 = a_7; + let e9: vec4 = b_7; + v_3 = (vec4(e8) + e9); + let e12: i32 = a_7; + let e13: vec4 = b_7; + v_3 = (vec4(e12) - e13); + let e16: i32 = a_7; + let e17: vec4 = b_7; + v_3 = (vec4(e16) & e17); + let e20: i32 = a_7; + let e21: vec4 = b_7; + v_3 = (vec4(e20) | e21); + let e24: i32 = a_7; + let e25: vec4 = b_7; + v_3 = (vec4(e24) ^ e25); return; } -fn testBinOpUVecUint(a8: vec4, b8: u32) { - var a9: vec4; - var b9: u32; - var v4: vec4; +fn testBinOpUVecUint(a_8: vec4, b_8: u32) { + var a_9: vec4; + var b_9: u32; + var v_4: vec4; - a9 = a8; - b9 = b8; - let e5: vec4 = a9; - let e6: u32 = b9; - v4 = (e5 * e6); - let e8: vec4 = a9; - let e9: u32 = b9; - v4 = (e8 / vec4(e9)); - let e12: vec4 = a9; - let e13: u32 = b9; - v4 = (e12 + vec4(e13)); - let e16: vec4 = a9; - let e17: u32 = b9; - v4 = (e16 - vec4(e17)); - let e20: vec4 = a9; - let e21: u32 = b9; - v4 = (e20 & vec4(e21)); - let e24: vec4 = a9; - let e25: u32 = b9; - v4 = (e24 | vec4(e25)); - let e28: vec4 = a9; - let e29: u32 = b9; - v4 = (e28 ^ vec4(e29)); - let e32: vec4 = a9; - let e33: u32 = b9; - v4 = (e32 >> vec4(e33)); - let e36: vec4 = a9; - let e37: u32 = b9; - v4 = (e36 << vec4(e37)); + a_9 = a_8; + b_9 = b_8; + let e5: vec4 = a_9; + let e6: u32 = b_9; + v_4 = (e5 * e6); + let e8: vec4 = a_9; + let e9: u32 = b_9; + v_4 = (e8 / vec4(e9)); + let e12: vec4 = a_9; + let e13: u32 = b_9; + v_4 = (e12 + vec4(e13)); + let e16: vec4 = a_9; + let e17: u32 = b_9; + v_4 = (e16 - vec4(e17)); + let e20: vec4 = a_9; + let e21: u32 = b_9; + v_4 = (e20 & vec4(e21)); + let e24: vec4 = a_9; + let e25: u32 = b_9; + v_4 = (e24 | vec4(e25)); + let e28: vec4 = a_9; + let e29: u32 = b_9; + v_4 = (e28 ^ vec4(e29)); + let e32: vec4 = a_9; + let e33: u32 = b_9; + v_4 = (e32 >> vec4(e33)); + let e36: vec4 = a_9; + let e37: u32 = b_9; + v_4 = (e36 << vec4(e37)); return; } -fn testBinOpUintUVec(a10: u32, b10: vec4) { - var a11: u32; - var b11: vec4; - var v5: vec4; +fn testBinOpUintUVec(a_10: u32, b_10: vec4) { + var a_11: u32; + var b_11: vec4; + var v_5: vec4; - a11 = a10; - b11 = b10; - let e5: u32 = a11; - let e6: vec4 = b11; - v5 = (e5 * e6); - let e8: u32 = a11; - let e9: vec4 = b11; - v5 = (vec4(e8) + e9); - let e12: u32 = a11; - let e13: vec4 = b11; - v5 = (vec4(e12) - e13); - let e16: u32 = a11; - let e17: vec4 = b11; - v5 = (vec4(e16) & e17); - let e20: u32 = a11; - let e21: vec4 = b11; - v5 = (vec4(e20) | e21); - let e24: u32 = a11; - let e25: vec4 = b11; - v5 = (vec4(e24) ^ e25); + a_11 = a_10; + b_11 = b_10; + let e5: u32 = a_11; + let e6: vec4 = b_11; + v_5 = (e5 * e6); + let e8: u32 = a_11; + let e9: vec4 = b_11; + v_5 = (vec4(e8) + e9); + let e12: u32 = a_11; + let e13: vec4 = b_11; + v_5 = (vec4(e12) - e13); + let e16: u32 = a_11; + let e17: vec4 = b_11; + v_5 = (vec4(e16) & e17); + let e20: u32 = a_11; + let e21: vec4 = b_11; + v_5 = (vec4(e20) | e21); + let e24: u32 = a_11; + let e25: vec4 = b_11; + v_5 = (vec4(e24) ^ e25); return; } @@ -181,15 +181,15 @@ fn testStructConstructor() { } fn testArrayConstructor() { - var tree1: array = array(0.0); + var tree_1: array = array(0.0); } -fn privatePointer(a12: ptr) { +fn privatePointer(a_12: ptr) { return; } -fn main1() { +fn main_1() { var local: f32; let e3: f32 = global; @@ -208,6 +208,6 @@ fn main1() { [[stage(fragment)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 86dfdc0c4..9bab2da67 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -1,4 +1,4 @@ -struct Mat4x3 { +struct Mat4x3_ { mx: vec4; my: vec4; mz: vec4; @@ -6,28 +6,28 @@ struct Mat4x3 { var o_color: vec4; -fn Fma(d: ptr, m: Mat4x3, s: f32) { - var m1: Mat4x3; - var s1: f32; +fn Fma(d: ptr, m: Mat4x3_, s: f32) { + var m_1: Mat4x3_; + var s_1: f32; - m1 = m; - s1 = s; - let e6: Mat4x3 = (*d); - let e8: Mat4x3 = m1; - let e10: f32 = s1; + m_1 = m; + s_1 = s; + let e6: Mat4x3_ = (*d); + let e8: Mat4x3_ = m_1; + let e10: f32 = s_1; (*d).mx = (e6.mx + (e8.mx * e10)); - let e14: Mat4x3 = (*d); - let e16: Mat4x3 = m1; - let e18: f32 = s1; + let e14: Mat4x3_ = (*d); + let e16: Mat4x3_ = m_1; + let e18: f32 = s_1; (*d).my = (e14.my + (e16.my * e18)); - let e22: Mat4x3 = (*d); - let e24: Mat4x3 = m1; - let e26: f32 = s1; + let e22: Mat4x3_ = (*d); + let e24: Mat4x3_ = m_1; + let e26: f32 = s_1; (*d).mz = (e22.mz + (e24.mz * e26)); return; } -fn main1() { +fn main_1() { let e1: vec4 = o_color; let e4: vec4 = vec4(1.0); o_color.x = e4.x; @@ -39,6 +39,6 @@ fn main1() { [[stage(fragment)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index 0e652c5f8..8fade8ae0 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -1,6 +1,6 @@ var i: u32; -fn main1() { +fn main_1() { var local: array = array(1.0, 2.0); let e2: u32 = i; @@ -8,6 +8,6 @@ fn main1() { [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index ab374b0de..631ca5db0 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -37,20 +37,20 @@ var image_2d_depth: texture_depth_2d; fn main([[builtin(local_invocation_id)]] local_id: vec3) { let dim: vec2 = textureDimensions(image_storage_src); let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); - let value1: vec4 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); - let value2: vec4 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); - let value4: vec4 = textureLoad(image_storage_src, itc); - let value5: vec4 = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); - textureStore(image_dst, itc.x, (((value1 + value2) + value4) + value5)); + let value1_: vec4 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); + let value2_: vec4 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); + let value4_: vec4 = textureLoad(image_storage_src, itc); + let value5_: vec4 = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); + textureStore(image_dst, itc.x, (((value1_ + value2_) + value4_) + value5_)); return; } [[stage(compute), workgroup_size(16, 1, 1)]] -fn depth_load([[builtin(local_invocation_id)]] local_id1: vec3) { - let dim1: vec2 = textureDimensions(image_storage_src); - let itc1: vec2 = ((dim1 * vec2(local_id1.xy)) % vec2(10, 20)); - let val: f32 = textureLoad(image_depth_multisampled_src, itc1, i32(local_id1.z)); - textureStore(image_dst, itc1.x, vec4(u32(val))); +fn depth_load([[builtin(local_invocation_id)]] local_id_1: vec3) { + let dim_1: vec2 = textureDimensions(image_storage_src); + let itc_1: vec2 = ((dim_1 * vec2(local_id_1.xy)) % vec2(10, 20)); + let val: f32 = textureLoad(image_depth_multisampled_src, itc_1, i32(local_id_1.z)); + textureStore(image_dst, itc_1.x, vec4(u32(val))); return; } @@ -81,8 +81,8 @@ fn levels_queries() -> [[builtin(position)]] vec4 { let num_layers_cube: i32 = textureNumLayers(image_cube_array); let num_levels_3d: i32 = textureNumLevels(image_3d); let num_samples_aa: i32 = textureNumSamples(image_aa); - let sum1: i32 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); - return vec4(f32(sum1)); + let sum_1: i32 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); + return vec4(f32(sum_1)); } [[stage(fragment)]] @@ -98,8 +98,8 @@ fn sample() -> [[location(0)]] vec4 { [[stage(fragment)]] fn sample_comparison() -> [[location(0)]] f32 { - let tc1: vec2 = vec2(0.5); - let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc1, 0.5); - let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc1, 0.5); + let tc_1: vec2 = vec2(0.5); + let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); + let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5); return (s2d_depth + s2d_depth_level); } diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index c86c9f556..f576915f3 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -20,8 +20,8 @@ fn vertex([[builtin(vertex_index)]] vertex_index: u32, [[builtin(instance_index) [[stage(fragment)]] fn fragment(in: VertexOutput, [[builtin(front_facing)]] front_facing: bool, [[builtin(sample_index)]] sample_index: u32, [[builtin(sample_mask)]] sample_mask: u32) -> FragmentOutput { let mask: u32 = (sample_mask & (1u << sample_index)); - let color1: f32 = select(0.0, 1.0, front_facing); - return FragmentOutput(in.varying, mask, color1); + let color_1: f32 = select(0.0, 1.0, front_facing); + return FragmentOutput(in.varying, mask, color_1); } [[stage(compute), workgroup_size(1, 1, 1)]] diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index 972bc2523..91b935db1 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -26,6 +26,6 @@ fn main() -> FragmentInput { } [[stage(fragment)]] -fn main1(val: FragmentInput) { +fn main_1(val: FragmentInput) { return; } diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl index ff4d9fa0e..370bab047 100644 --- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -1,6 +1,6 @@ var a: f32; -fn main1() { +fn main_1() { var b: f32; var c: f32; var d: f32; @@ -16,5 +16,5 @@ fn main1() { [[stage(vertex)]] fn main() { - main1(); + main_1(); } diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index 9806b1185..60f702df6 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -1,4 +1,4 @@ -fn main1() { +fn main_1() { var splat: mat2x2 = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); var normal: mat2x2 = mat2x2(vec2(1.0, 1.0), vec2(2.0, 2.0)); var a: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); @@ -25,6 +25,6 @@ fn main1() { [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 33a8f909e..f7f3c26be 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -1,4 +1,4 @@ -fn main1() { +fn main_1() { var a: vec4 = vec4(1.0, 1.0, 1.0, 1.0); var b: vec4 = vec4(2.0, 2.0, 2.0, 2.0); var m: mat4x4; @@ -149,6 +149,6 @@ fn main1() { [[stage(vertex)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 3174b289b..17985a6c1 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -8,15 +8,15 @@ let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); let v_i32_one: vec4 = vec4(1, 1, 1, 1); fn builtins() -> vec4 { - let s1: i32 = select(0, 1, true); - let s2: vec4 = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); - let s3: vec4 = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); - let m1: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - let m2: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); - let b1: f32 = bitcast(vec4(1, 1, 1, 1).x); - let b2: vec4 = bitcast>(vec4(1, 1, 1, 1)); + let s1_: i32 = select(0, 1, true); + let s2_: vec4 = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); + let s3_: vec4 = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); + let m1_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); + let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + let b1_: f32 = bitcast(vec4(1, 1, 1, 1).x); + let b2_: vec4 = bitcast>(vec4(1, 1, 1, 1)); let v_i32_zero: vec4 = vec4(vec4(0.0, 0.0, 0.0, 0.0)); - return (((((vec4((vec4(s1) + v_i32_zero)) + s2) + m1) + m2) + vec4(b1)) + b2); + return (((((vec4((vec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } fn splat() -> vec4 { @@ -47,8 +47,8 @@ fn constructors() -> f32 { } fn modulo() { - let a1: i32 = (1 % 1); - let b1: f32 = (1.0 % 1.0); + let a_1: i32 = (1 % 1); + let b_1: f32 = (1.0 % 1.0); let c: vec3 = (vec3(1) % vec3(1)); let d: vec3 = (vec3(1.0) % vec3(1.0)); } diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index cabe2eaed..0979097b9 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -1,6 +1,6 @@ [[block]] struct DynamicArray { - array1: [[stride(4)]] array; + array_: [[stride(4)]] array; }; fn f() { @@ -11,9 +11,9 @@ fn f() { return; } -fn index_dynamic_array(p: ptr, i: i32, v1: u32) -> u32 { - let old: u32 = (*p).array1[i]; - (*p).array1[i] = v1; +fn index_dynamic_array(p: ptr, i: i32, v_1: u32) -> u32 { + let old: u32 = (*p).array_[i]; + (*p).array_[i] = v_1; return old; } diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index 0aef32967..9c4a4e831 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -1,10 +1,10 @@ -fn main1() { +fn main_1() { var scalar_target: i32; var scalar: i32 = 1; var vec_target: vec2; - var vec1: vec2 = vec2(1u, 1u); + var vec_: vec2 = vec2(1u, 1u); var mat_target: mat4x3; - var mat1: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); + var mat_: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); let e3: i32 = scalar; scalar = (e3 + 1); @@ -13,28 +13,28 @@ fn main1() { let e8: i32 = (e6 - 1); scalar = e8; scalar_target = e8; - let e14: vec2 = vec1; - vec1 = (e14 - vec2(1u)); + let e14: vec2 = vec_; + vec_ = (e14 - vec2(1u)); vec_target = e14; - let e18: vec2 = vec1; + let e18: vec2 = vec_; let e21: vec2 = (e18 + vec2(1u)); - vec1 = e21; + vec_ = e21; vec_target = e21; let e24: f32 = f32(1); - let e32: mat4x3 = mat1; + let e32: mat4x3 = mat_; let e34: vec3 = vec3(1.0); - mat1 = (e32 + mat4x3(e34, e34, e34, e34)); + mat_ = (e32 + mat4x3(e34, e34, e34, e34)); mat_target = e32; - let e37: mat4x3 = mat1; + let e37: mat4x3 = mat_; let e39: vec3 = vec3(1.0); let e41: mat4x3 = (e37 - mat4x3(e39, e39, e39, e39)); - mat1 = e41; + mat_ = e41; mat_target = e41; return; } [[stage(fragment)]] fn main() { - main1(); + main_1(); return; } diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index 8516563d1..8bde11485 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -9,23 +9,23 @@ struct VertexOutput { }; var v_uv: vec2; -var a_uv1: vec2; +var a_uv_1: vec2; var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), ); -var a_pos1: vec2; +var a_pos_1: vec2; -fn main1() { - let e12: vec2 = a_uv1; +fn main_1() { + let e12: vec2 = a_uv_1; v_uv = e12; - let e13: vec2 = a_pos1; + let e13: vec2 = a_pos_1; perVertexStruct.gl_Position = vec4(e13.x, e13.y, 0.0, 1.0); return; } [[stage(vertex)]] fn main([[location(1)]] a_uv: vec2, [[location(0)]] a_pos: vec2) -> VertexOutput { - a_uv1 = a_uv; - a_pos1 = a_pos; - main1(); + a_uv_1 = a_uv; + a_pos_1 = a_pos; + main_1(); let e7: vec2 = v_uv; let e8: vec4 = perVertexStruct.gl_Position; return VertexOutput(e7, e8); diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 9fccc34b4..0b8720927 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -16,8 +16,8 @@ fn main([[location(0)]] pos: vec2, [[location(1)]] uv: vec2) -> Vertex } [[stage(fragment)]] -fn main1([[location(0)]] uv1: vec2) -> [[location(0)]] vec4 { - let color: vec4 = textureSample(u_texture, u_sampler, uv1); +fn main_1([[location(0)]] uv_1: vec2) -> [[location(0)]] vec4 { + let color: vec4 = textureSample(u_texture, u_sampler, uv_1); if ((color.w == 0.0)) { discard; } diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 022cc70ad..538112384 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -2,18 +2,18 @@ struct FragmentOutput { [[location(0)]] o_color: vec4; }; -var v_uv1: vec2; +var v_uv_1: vec2; var o_color: vec4; -fn main1() { +fn main_1() { o_color = vec4(1.0, 1.0, 1.0, 1.0); return; } [[stage(fragment)]] fn main([[location(0)]] v_uv: vec2) -> FragmentOutput { - v_uv1 = v_uv; - main1(); + v_uv_1 = v_uv; + main_1(); let e7: vec4 = o_color; return FragmentOutput(e7); } diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index 81c155564..1348b9a4a 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -3,24 +3,24 @@ struct VertexOutput { [[builtin(position)]] member: vec4; }; -var a_pos1: vec2; -var a_uv1: vec2; +var a_pos_1: vec2; +var a_uv_1: vec2; var v_uv: vec2; var gl_Position: vec4; -fn main1() { - let e4: vec2 = a_uv1; +fn main_1() { + let e4: vec2 = a_uv_1; v_uv = e4; - let e6: vec2 = a_pos1; + let e6: vec2 = a_pos_1; gl_Position = vec4((1.2000000476837158 * e6), 0.0, 1.0); return; } [[stage(vertex)]] fn main([[location(0)]] a_pos: vec2, [[location(1)]] a_uv: vec2) -> VertexOutput { - a_pos1 = a_pos; - a_uv1 = a_uv; - main1(); + a_pos_1 = a_pos; + a_uv_1 = a_uv; + main_1(); let e14: vec2 = v_uv; let e16: vec4 = gl_Position; return VertexOutput(e14, e16); diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 016b87693..670db9f82 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -26,331 +26,331 @@ var texCubeArrayShadow: texture_depth_cube_array; var tex3DShadow: texture_3d; [[group(1), binding(17)]] var sampShadow: sampler_comparison; -var texcoord1: vec4; +var texcoord_1: vec4; fn testTex1D(coord: f32) { - var coord1: f32; + var coord_1: f32; var c: vec4; - coord1 = coord; - let e18: f32 = coord1; + coord_1 = coord; + let e18: f32 = coord_1; let e19: vec4 = textureSample(tex1D, samp, e18); c = e19; - let e22: f32 = coord1; + let e22: f32 = coord_1; let e24: vec4 = textureSampleBias(tex1D, samp, e22, 2.0); c = e24; - let e28: f32 = coord1; + let e28: f32 = coord_1; let e31: vec4 = textureSampleGrad(tex1D, samp, e28, 4.0, 4.0); c = e31; - let e36: f32 = coord1; + let e36: f32 = coord_1; let e40: vec4 = textureSampleGrad(tex1D, samp, e36, 4.0, 4.0, 5); c = e40; - let e43: f32 = coord1; + let e43: f32 = coord_1; let e45: vec4 = textureSampleLevel(tex1D, samp, e43, 3.0); c = e45; - let e49: f32 = coord1; + let e49: f32 = coord_1; let e52: vec4 = textureSampleLevel(tex1D, samp, e49, 3.0, 5); c = e52; - let e55: f32 = coord1; + let e55: f32 = coord_1; let e57: vec4 = textureSample(tex1D, samp, e55, 5); c = e57; - let e61: f32 = coord1; + let e61: f32 = coord_1; let e64: vec4 = textureSampleBias(tex1D, samp, e61, 2.0, 5); c = e64; - let e65: f32 = coord1; - let e68: f32 = coord1; + let e65: f32 = coord_1; + let e68: f32 = coord_1; let e70: vec2 = vec2(e68, 6.0); let e74: vec4 = textureSample(tex1D, samp, (e70.x / e70.y)); c = e74; - let e75: f32 = coord1; - let e80: f32 = coord1; + let e75: f32 = coord_1; + let e80: f32 = coord_1; let e84: vec4 = vec4(e80, 0.0, 0.0, 6.0); let e90: vec4 = textureSample(tex1D, samp, (e84.xyz / vec3(e84.w)).x); c = e90; - let e91: f32 = coord1; - let e95: f32 = coord1; + let e91: f32 = coord_1; + let e95: f32 = coord_1; let e97: vec2 = vec2(e95, 6.0); let e102: vec4 = textureSampleBias(tex1D, samp, (e97.x / e97.y), 2.0); c = e102; - let e103: f32 = coord1; - let e109: f32 = coord1; + let e103: f32 = coord_1; + let e109: f32 = coord_1; let e113: vec4 = vec4(e109, 0.0, 0.0, 6.0); let e120: vec4 = textureSampleBias(tex1D, samp, (e113.xyz / vec3(e113.w)).x, 2.0); c = e120; - let e121: f32 = coord1; - let e126: f32 = coord1; + let e121: f32 = coord_1; + let e126: f32 = coord_1; let e128: vec2 = vec2(e126, 6.0); let e134: vec4 = textureSampleGrad(tex1D, samp, (e128.x / e128.y), 4.0, 4.0); c = e134; - let e135: f32 = coord1; - let e142: f32 = coord1; + let e135: f32 = coord_1; + let e142: f32 = coord_1; let e146: vec4 = vec4(e142, 0.0, 0.0, 6.0); let e154: vec4 = textureSampleGrad(tex1D, samp, (e146.xyz / vec3(e146.w)).x, 4.0, 4.0); c = e154; - let e155: f32 = coord1; - let e161: f32 = coord1; + let e155: f32 = coord_1; + let e161: f32 = coord_1; let e163: vec2 = vec2(e161, 6.0); let e170: vec4 = textureSampleGrad(tex1D, samp, (e163.x / e163.y), 4.0, 4.0, 5); c = e170; - let e171: f32 = coord1; - let e179: f32 = coord1; + let e171: f32 = coord_1; + let e179: f32 = coord_1; let e183: vec4 = vec4(e179, 0.0, 0.0, 6.0); let e192: vec4 = textureSampleGrad(tex1D, samp, (e183.xyz / vec3(e183.w)).x, 4.0, 4.0, 5); c = e192; - let e193: f32 = coord1; - let e197: f32 = coord1; + let e193: f32 = coord_1; + let e197: f32 = coord_1; let e199: vec2 = vec2(e197, 6.0); let e204: vec4 = textureSampleLevel(tex1D, samp, (e199.x / e199.y), 3.0); c = e204; - let e205: f32 = coord1; - let e211: f32 = coord1; + let e205: f32 = coord_1; + let e211: f32 = coord_1; let e215: vec4 = vec4(e211, 0.0, 0.0, 6.0); let e222: vec4 = textureSampleLevel(tex1D, samp, (e215.xyz / vec3(e215.w)).x, 3.0); c = e222; - let e223: f32 = coord1; - let e228: f32 = coord1; + let e223: f32 = coord_1; + let e228: f32 = coord_1; let e230: vec2 = vec2(e228, 6.0); let e236: vec4 = textureSampleLevel(tex1D, samp, (e230.x / e230.y), 3.0, 5); c = e236; - let e237: f32 = coord1; - let e244: f32 = coord1; + let e237: f32 = coord_1; + let e244: f32 = coord_1; let e248: vec4 = vec4(e244, 0.0, 0.0, 6.0); let e256: vec4 = textureSampleLevel(tex1D, samp, (e248.xyz / vec3(e248.w)).x, 3.0, 5); c = e256; - let e257: f32 = coord1; - let e261: f32 = coord1; + let e257: f32 = coord_1; + let e261: f32 = coord_1; let e263: vec2 = vec2(e261, 6.0); let e268: vec4 = textureSample(tex1D, samp, (e263.x / e263.y), 5); c = e268; - let e269: f32 = coord1; - let e275: f32 = coord1; + let e269: f32 = coord_1; + let e275: f32 = coord_1; let e279: vec4 = vec4(e275, 0.0, 0.0, 6.0); let e286: vec4 = textureSample(tex1D, samp, (e279.xyz / vec3(e279.w)).x, 5); c = e286; - let e287: f32 = coord1; - let e292: f32 = coord1; + let e287: f32 = coord_1; + let e292: f32 = coord_1; let e294: vec2 = vec2(e292, 6.0); let e300: vec4 = textureSampleBias(tex1D, samp, (e294.x / e294.y), 2.0, 5); c = e300; - let e301: f32 = coord1; - let e308: f32 = coord1; + let e301: f32 = coord_1; + let e308: f32 = coord_1; let e312: vec4 = vec4(e308, 0.0, 0.0, 6.0); let e320: vec4 = textureSampleBias(tex1D, samp, (e312.xyz / vec3(e312.w)).x, 2.0, 5); c = e320; return; } -fn testTex1DArray(coord2: vec2) { - var coord3: vec2; - var c1: vec4; +fn testTex1DArray(coord_2: vec2) { + var coord_3: vec2; + var c_1: vec4; - coord3 = coord2; - let e18: vec2 = coord3; + coord_3 = coord_2; + let e18: vec2 = coord_3; let e22: vec4 = textureSample(tex1DArray, samp, e18.x, i32(e18.y)); - c1 = e22; - let e25: vec2 = coord3; + c_1 = e22; + let e25: vec2 = coord_3; let e30: vec4 = textureSampleBias(tex1DArray, samp, e25.x, i32(e25.y), 2.0); - c1 = e30; - let e34: vec2 = coord3; + c_1 = e30; + let e34: vec2 = coord_3; let e40: vec4 = textureSampleGrad(tex1DArray, samp, e34.x, i32(e34.y), 4.0, 4.0); - c1 = e40; - let e45: vec2 = coord3; + c_1 = e40; + let e45: vec2 = coord_3; let e52: vec4 = textureSampleGrad(tex1DArray, samp, e45.x, i32(e45.y), 4.0, 4.0, 5); - c1 = e52; - let e55: vec2 = coord3; + c_1 = e52; + let e55: vec2 = coord_3; let e60: vec4 = textureSampleLevel(tex1DArray, samp, e55.x, i32(e55.y), 3.0); - c1 = e60; - let e64: vec2 = coord3; + c_1 = e60; + let e64: vec2 = coord_3; let e70: vec4 = textureSampleLevel(tex1DArray, samp, e64.x, i32(e64.y), 3.0, 5); - c1 = e70; - let e73: vec2 = coord3; + c_1 = e70; + let e73: vec2 = coord_3; let e78: vec4 = textureSample(tex1DArray, samp, e73.x, i32(e73.y), 5); - c1 = e78; - let e82: vec2 = coord3; + c_1 = e78; + let e82: vec2 = coord_3; let e88: vec4 = textureSampleBias(tex1DArray, samp, e82.x, i32(e82.y), 2.0, 5); - c1 = e88; + c_1 = e88; return; } -fn testTex2D(coord4: vec2) { - var coord5: vec2; - var c2: vec4; +fn testTex2D(coord_4: vec2) { + var coord_5: vec2; + var c_2: vec4; - coord5 = coord4; - let e18: vec2 = coord5; + coord_5 = coord_4; + let e18: vec2 = coord_5; let e19: vec4 = textureSample(tex2D, samp, e18); - c2 = e19; - let e22: vec2 = coord5; + c_2 = e19; + let e22: vec2 = coord_5; let e24: vec4 = textureSampleBias(tex2D, samp, e22, 2.0); - c2 = e24; - let e30: vec2 = coord5; + c_2 = e24; + let e30: vec2 = coord_5; let e35: vec4 = textureSampleGrad(tex2D, samp, e30, vec2(4.0), vec2(4.0)); - c2 = e35; - let e43: vec2 = coord5; + c_2 = e35; + let e43: vec2 = coord_5; let e50: vec4 = textureSampleGrad(tex2D, samp, e43, vec2(4.0), vec2(4.0), vec2(5, 5)); - c2 = e50; - let e53: vec2 = coord5; + c_2 = e50; + let e53: vec2 = coord_5; let e55: vec4 = textureSampleLevel(tex2D, samp, e53, 3.0); - c2 = e55; - let e60: vec2 = coord5; + c_2 = e55; + let e60: vec2 = coord_5; let e64: vec4 = textureSampleLevel(tex2D, samp, e60, 3.0, vec2(5, 5)); - c2 = e64; - let e68: vec2 = coord5; + c_2 = e64; + let e68: vec2 = coord_5; let e71: vec4 = textureSample(tex2D, samp, e68, vec2(5, 5)); - c2 = e71; - let e76: vec2 = coord5; + c_2 = e71; + let e76: vec2 = coord_5; let e80: vec4 = textureSampleBias(tex2D, samp, e76, 2.0, vec2(5, 5)); - c2 = e80; - let e81: vec2 = coord5; - let e84: vec2 = coord5; + c_2 = e80; + let e81: vec2 = coord_5; + let e84: vec2 = coord_5; let e86: vec3 = vec3(e84, 6.0); let e91: vec4 = textureSample(tex2D, samp, (e86.xy / vec2(e86.z))); - c2 = e91; - let e92: vec2 = coord5; - let e96: vec2 = coord5; + c_2 = e91; + let e92: vec2 = coord_5; + let e96: vec2 = coord_5; let e99: vec4 = vec4(e96, 0.0, 6.0); let e105: vec4 = textureSample(tex2D, samp, (e99.xyz / vec3(e99.w)).xy); - c2 = e105; - let e106: vec2 = coord5; - let e110: vec2 = coord5; + c_2 = e105; + let e106: vec2 = coord_5; + let e110: vec2 = coord_5; let e112: vec3 = vec3(e110, 6.0); let e118: vec4 = textureSampleBias(tex2D, samp, (e112.xy / vec2(e112.z)), 2.0); - c2 = e118; - let e119: vec2 = coord5; - let e124: vec2 = coord5; + c_2 = e118; + let e119: vec2 = coord_5; + let e124: vec2 = coord_5; let e127: vec4 = vec4(e124, 0.0, 6.0); let e134: vec4 = textureSampleBias(tex2D, samp, (e127.xyz / vec3(e127.w)).xy, 2.0); - c2 = e134; - let e135: vec2 = coord5; - let e142: vec2 = coord5; + c_2 = e134; + let e135: vec2 = coord_5; + let e142: vec2 = coord_5; let e144: vec3 = vec3(e142, 6.0); let e153: vec4 = textureSampleGrad(tex2D, samp, (e144.xy / vec2(e144.z)), vec2(4.0), vec2(4.0)); - c2 = e153; - let e154: vec2 = coord5; - let e162: vec2 = coord5; + c_2 = e153; + let e154: vec2 = coord_5; + let e162: vec2 = coord_5; let e165: vec4 = vec4(e162, 0.0, 6.0); let e175: vec4 = textureSampleGrad(tex2D, samp, (e165.xyz / vec3(e165.w)).xy, vec2(4.0), vec2(4.0)); - c2 = e175; - let e176: vec2 = coord5; - let e185: vec2 = coord5; + c_2 = e175; + let e176: vec2 = coord_5; + let e185: vec2 = coord_5; let e187: vec3 = vec3(e185, 6.0); let e198: vec4 = textureSampleGrad(tex2D, samp, (e187.xy / vec2(e187.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); - c2 = e198; - let e199: vec2 = coord5; - let e209: vec2 = coord5; + c_2 = e198; + let e199: vec2 = coord_5; + let e209: vec2 = coord_5; let e212: vec4 = vec4(e209, 0.0, 6.0); let e224: vec4 = textureSampleGrad(tex2D, samp, (e212.xyz / vec3(e212.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); - c2 = e224; - let e225: vec2 = coord5; - let e229: vec2 = coord5; + c_2 = e224; + let e225: vec2 = coord_5; + let e229: vec2 = coord_5; let e231: vec3 = vec3(e229, 6.0); let e237: vec4 = textureSampleLevel(tex2D, samp, (e231.xy / vec2(e231.z)), 3.0); - c2 = e237; - let e238: vec2 = coord5; - let e243: vec2 = coord5; + c_2 = e237; + let e238: vec2 = coord_5; + let e243: vec2 = coord_5; let e246: vec4 = vec4(e243, 0.0, 6.0); let e253: vec4 = textureSampleLevel(tex2D, samp, (e246.xyz / vec3(e246.w)).xy, 3.0); - c2 = e253; - let e254: vec2 = coord5; - let e260: vec2 = coord5; + c_2 = e253; + let e254: vec2 = coord_5; + let e260: vec2 = coord_5; let e262: vec3 = vec3(e260, 6.0); let e270: vec4 = textureSampleLevel(tex2D, samp, (e262.xy / vec2(e262.z)), 3.0, vec2(5, 5)); - c2 = e270; - let e271: vec2 = coord5; - let e278: vec2 = coord5; + c_2 = e270; + let e271: vec2 = coord_5; + let e278: vec2 = coord_5; let e281: vec4 = vec4(e278, 0.0, 6.0); let e290: vec4 = textureSampleLevel(tex2D, samp, (e281.xyz / vec3(e281.w)).xy, 3.0, vec2(5, 5)); - c2 = e290; - let e291: vec2 = coord5; - let e296: vec2 = coord5; + c_2 = e290; + let e291: vec2 = coord_5; + let e296: vec2 = coord_5; let e298: vec3 = vec3(e296, 6.0); let e305: vec4 = textureSample(tex2D, samp, (e298.xy / vec2(e298.z)), vec2(5, 5)); - c2 = e305; - let e306: vec2 = coord5; - let e312: vec2 = coord5; + c_2 = e305; + let e306: vec2 = coord_5; + let e312: vec2 = coord_5; let e315: vec4 = vec4(e312, 0.0, 6.0); let e323: vec4 = textureSample(tex2D, samp, (e315.xyz / vec3(e315.w)).xy, vec2(5, 5)); - c2 = e323; - let e324: vec2 = coord5; - let e330: vec2 = coord5; + c_2 = e323; + let e324: vec2 = coord_5; + let e330: vec2 = coord_5; let e332: vec3 = vec3(e330, 6.0); let e340: vec4 = textureSampleBias(tex2D, samp, (e332.xy / vec2(e332.z)), 2.0, vec2(5, 5)); - c2 = e340; - let e341: vec2 = coord5; - let e348: vec2 = coord5; + c_2 = e340; + let e341: vec2 = coord_5; + let e348: vec2 = coord_5; let e351: vec4 = vec4(e348, 0.0, 6.0); let e360: vec4 = textureSampleBias(tex2D, samp, (e351.xyz / vec3(e351.w)).xy, 2.0, vec2(5, 5)); - c2 = e360; + c_2 = e360; return; } -fn testTex2DShadow(coord6: vec2) { - var coord7: vec2; +fn testTex2DShadow(coord_6: vec2) { + var coord_7: vec2; var d: f32; - coord7 = coord6; - let e17: vec2 = coord7; - let e20: vec2 = coord7; + coord_7 = coord_6; + let e17: vec2 = coord_7; + let e20: vec2 = coord_7; let e22: vec3 = vec3(e20, 1.0); let e25: f32 = textureSampleCompare(tex2DShadow, sampShadow, e22.xy, e22.z); d = e25; - let e26: vec2 = coord7; - let e33: vec2 = coord7; + let e26: vec2 = coord_7; + let e33: vec2 = coord_7; let e35: vec3 = vec3(e33, 1.0); let e42: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e35.xy, e35.z); d = e42; - let e43: vec2 = coord7; - let e52: vec2 = coord7; + let e43: vec2 = coord_7; + let e52: vec2 = coord_7; let e54: vec3 = vec3(e52, 1.0); let e63: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e54.xy, e54.z, vec2(5, 5)); d = e63; - let e64: vec2 = coord7; - let e68: vec2 = coord7; + let e64: vec2 = coord_7; + let e68: vec2 = coord_7; let e70: vec3 = vec3(e68, 1.0); let e74: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e70.xy, e70.z); d = e74; - let e75: vec2 = coord7; - let e81: vec2 = coord7; + let e75: vec2 = coord_7; + let e81: vec2 = coord_7; let e83: vec3 = vec3(e81, 1.0); let e89: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e83.xy, e83.z, vec2(5, 5)); d = e89; - let e90: vec2 = coord7; - let e95: vec2 = coord7; + let e90: vec2 = coord_7; + let e95: vec2 = coord_7; let e97: vec3 = vec3(e95, 1.0); let e102: f32 = textureSampleCompare(tex2DShadow, sampShadow, e97.xy, e97.z, vec2(5, 5)); d = e102; - let e103: vec2 = coord7; - let e107: vec2 = coord7; + let e103: vec2 = coord_7; + let e107: vec2 = coord_7; let e110: vec4 = vec4(e107, 1.0, 6.0); let e114: vec3 = (e110.xyz / vec3(e110.w)); let e117: f32 = textureSampleCompare(tex2DShadow, sampShadow, e114.xy, e114.z); d = e117; - let e118: vec2 = coord7; - let e126: vec2 = coord7; + let e118: vec2 = coord_7; + let e126: vec2 = coord_7; let e129: vec4 = vec4(e126, 1.0, 6.0); let e137: vec3 = (e129.xyz / vec3(e129.w)); let e140: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e137.xy, e137.z); d = e140; - let e141: vec2 = coord7; - let e151: vec2 = coord7; + let e141: vec2 = coord_7; + let e151: vec2 = coord_7; let e154: vec4 = vec4(e151, 1.0, 6.0); let e164: vec3 = (e154.xyz / vec3(e154.w)); let e167: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e164.xy, e164.z, vec2(5, 5)); d = e167; - let e168: vec2 = coord7; - let e173: vec2 = coord7; + let e168: vec2 = coord_7; + let e173: vec2 = coord_7; let e176: vec4 = vec4(e173, 1.0, 6.0); let e181: vec3 = (e176.xyz / vec3(e176.w)); let e184: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e181.xy, e181.z); d = e184; - let e185: vec2 = coord7; - let e192: vec2 = coord7; + let e185: vec2 = coord_7; + let e192: vec2 = coord_7; let e195: vec4 = vec4(e192, 1.0, 6.0); let e202: vec3 = (e195.xyz / vec3(e195.w)); let e205: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e202.xy, e202.z, vec2(5, 5)); d = e205; - let e206: vec2 = coord7; - let e212: vec2 = coord7; + let e206: vec2 = coord_7; + let e212: vec2 = coord_7; let e215: vec4 = vec4(e212, 1.0, 6.0); let e221: vec3 = (e215.xyz / vec3(e215.w)); let e224: f32 = textureSampleCompare(tex2DShadow, sampShadow, e221.xy, e221.z, vec2(5, 5)); @@ -358,217 +358,217 @@ fn testTex2DShadow(coord6: vec2) { return; } -fn testTex2DArray(coord8: vec3) { - var coord9: vec3; - var c3: vec4; +fn testTex2DArray(coord_8: vec3) { + var coord_9: vec3; + var c_3: vec4; - coord9 = coord8; - let e18: vec3 = coord9; + coord_9 = coord_8; + let e18: vec3 = coord_9; let e22: vec4 = textureSample(tex2DArray, samp, e18.xy, i32(e18.z)); - c3 = e22; - let e25: vec3 = coord9; + c_3 = e22; + let e25: vec3 = coord_9; let e30: vec4 = textureSampleBias(tex2DArray, samp, e25.xy, i32(e25.z), 2.0); - c3 = e30; - let e36: vec3 = coord9; + c_3 = e30; + let e36: vec3 = coord_9; let e44: vec4 = textureSampleGrad(tex2DArray, samp, e36.xy, i32(e36.z), vec2(4.0), vec2(4.0)); - c3 = e44; - let e52: vec3 = coord9; + c_3 = e44; + let e52: vec3 = coord_9; let e62: vec4 = textureSampleGrad(tex2DArray, samp, e52.xy, i32(e52.z), vec2(4.0), vec2(4.0), vec2(5, 5)); - c3 = e62; - let e65: vec3 = coord9; + c_3 = e62; + let e65: vec3 = coord_9; let e70: vec4 = textureSampleLevel(tex2DArray, samp, e65.xy, i32(e65.z), 3.0); - c3 = e70; - let e75: vec3 = coord9; + c_3 = e70; + let e75: vec3 = coord_9; let e82: vec4 = textureSampleLevel(tex2DArray, samp, e75.xy, i32(e75.z), 3.0, vec2(5, 5)); - c3 = e82; - let e86: vec3 = coord9; + c_3 = e82; + let e86: vec3 = coord_9; let e92: vec4 = textureSample(tex2DArray, samp, e86.xy, i32(e86.z), vec2(5, 5)); - c3 = e92; - let e97: vec3 = coord9; + c_3 = e92; + let e97: vec3 = coord_9; let e104: vec4 = textureSampleBias(tex2DArray, samp, e97.xy, i32(e97.z), 2.0, vec2(5, 5)); - c3 = e104; + c_3 = e104; return; } -fn testTex2DArrayShadow(coord10: vec3) { - var coord11: vec3; - var d1: f32; +fn testTex2DArrayShadow(coord_10: vec3) { + var coord_11: vec3; + var d_1: f32; - coord11 = coord10; - let e17: vec3 = coord11; - let e20: vec3 = coord11; + coord_11 = coord_10; + let e17: vec3 = coord_11; + let e20: vec3 = coord_11; let e22: vec4 = vec4(e20, 1.0); let e27: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e22.xy, i32(e22.z), e22.w); - d1 = e27; - let e28: vec3 = coord11; - let e35: vec3 = coord11; + d_1 = e27; + let e28: vec3 = coord_11; + let e35: vec3 = coord_11; let e37: vec4 = vec4(e35, 1.0); let e46: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e37.xy, i32(e37.z), e37.w); - d1 = e46; - let e47: vec3 = coord11; - let e56: vec3 = coord11; + d_1 = e46; + let e47: vec3 = coord_11; + let e56: vec3 = coord_11; let e58: vec4 = vec4(e56, 1.0); let e69: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e58.xy, i32(e58.z), e58.w, vec2(5, 5)); - d1 = e69; - let e70: vec3 = coord11; - let e74: vec3 = coord11; + d_1 = e69; + let e70: vec3 = coord_11; + let e74: vec3 = coord_11; let e76: vec4 = vec4(e74, 1.0); let e82: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e76.xy, i32(e76.z), e76.w); - d1 = e82; - let e83: vec3 = coord11; - let e89: vec3 = coord11; + d_1 = e82; + let e83: vec3 = coord_11; + let e89: vec3 = coord_11; let e91: vec4 = vec4(e89, 1.0); let e99: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e91.xy, i32(e91.z), e91.w, vec2(5, 5)); - d1 = e99; - let e100: vec3 = coord11; - let e105: vec3 = coord11; + d_1 = e99; + let e100: vec3 = coord_11; + let e105: vec3 = coord_11; let e107: vec4 = vec4(e105, 1.0); let e114: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e107.xy, i32(e107.z), e107.w, vec2(5, 5)); - d1 = e114; + d_1 = e114; return; } -fn testTexCube(coord12: vec3) { - var coord13: vec3; - var c4: vec4; +fn testTexCube(coord_12: vec3) { + var coord_13: vec3; + var c_4: vec4; - coord13 = coord12; - let e18: vec3 = coord13; + coord_13 = coord_12; + let e18: vec3 = coord_13; let e19: vec4 = textureSample(texCube, samp, e18); - c4 = e19; - let e22: vec3 = coord13; + c_4 = e19; + let e22: vec3 = coord_13; let e24: vec4 = textureSampleBias(texCube, samp, e22, 2.0); - c4 = e24; - let e30: vec3 = coord13; + c_4 = e24; + let e30: vec3 = coord_13; let e35: vec4 = textureSampleGrad(texCube, samp, e30, vec3(4.0), vec3(4.0)); - c4 = e35; - let e38: vec3 = coord13; + c_4 = e35; + let e38: vec3 = coord_13; let e40: vec4 = textureSampleLevel(texCube, samp, e38, 3.0); - c4 = e40; - let e45: vec3 = coord13; + c_4 = e40; + let e45: vec3 = coord_13; let e49: vec4 = textureSampleLevel(texCube, samp, e45, 3.0, vec3(5, 5, 5)); - c4 = e49; - let e53: vec3 = coord13; + c_4 = e49; + let e53: vec3 = coord_13; let e56: vec4 = textureSample(texCube, samp, e53, vec3(5, 5, 5)); - c4 = e56; - let e61: vec3 = coord13; + c_4 = e56; + let e61: vec3 = coord_13; let e65: vec4 = textureSampleBias(texCube, samp, e61, 2.0, vec3(5, 5, 5)); - c4 = e65; + c_4 = e65; return; } -fn testTexCubeShadow(coord14: vec3) { - var coord15: vec3; - var d2: f32; +fn testTexCubeShadow(coord_14: vec3) { + var coord_15: vec3; + var d_2: f32; - coord15 = coord14; - let e17: vec3 = coord15; - let e20: vec3 = coord15; + coord_15 = coord_14; + let e17: vec3 = coord_15; + let e20: vec3 = coord_15; let e22: vec4 = vec4(e20, 1.0); let e25: f32 = textureSampleCompare(texCubeShadow, sampShadow, e22.xyz, e22.w); - d2 = e25; - let e26: vec3 = coord15; - let e33: vec3 = coord15; + d_2 = e25; + let e26: vec3 = coord_15; + let e33: vec3 = coord_15; let e35: vec4 = vec4(e33, 1.0); let e42: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e35.xyz, e35.w); - d2 = e42; - let e43: vec3 = coord15; - let e47: vec3 = coord15; + d_2 = e42; + let e43: vec3 = coord_15; + let e47: vec3 = coord_15; let e49: vec4 = vec4(e47, 1.0); let e53: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e49.xyz, e49.w); - d2 = e53; - let e54: vec3 = coord15; - let e60: vec3 = coord15; + d_2 = e53; + let e54: vec3 = coord_15; + let e60: vec3 = coord_15; let e62: vec4 = vec4(e60, 1.0); let e68: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e62.xyz, e62.w, vec3(5, 5, 5)); - d2 = e68; - let e69: vec3 = coord15; - let e74: vec3 = coord15; + d_2 = e68; + let e69: vec3 = coord_15; + let e74: vec3 = coord_15; let e76: vec4 = vec4(e74, 1.0); let e81: f32 = textureSampleCompare(texCubeShadow, sampShadow, e76.xyz, e76.w, vec3(5, 5, 5)); - d2 = e81; + d_2 = e81; return; } -fn testTexCubeArray(coord16: vec4) { - var coord17: vec4; - var c5: vec4; +fn testTexCubeArray(coord_16: vec4) { + var coord_17: vec4; + var c_5: vec4; - coord17 = coord16; - let e18: vec4 = coord17; + coord_17 = coord_16; + let e18: vec4 = coord_17; let e22: vec4 = textureSample(texCubeArray, samp, e18.xyz, i32(e18.w)); - c5 = e22; - let e25: vec4 = coord17; + c_5 = e22; + let e25: vec4 = coord_17; let e30: vec4 = textureSampleBias(texCubeArray, samp, e25.xyz, i32(e25.w), 2.0); - c5 = e30; - let e36: vec4 = coord17; + c_5 = e30; + let e36: vec4 = coord_17; let e44: vec4 = textureSampleGrad(texCubeArray, samp, e36.xyz, i32(e36.w), vec3(4.0), vec3(4.0)); - c5 = e44; - let e47: vec4 = coord17; + c_5 = e44; + let e47: vec4 = coord_17; let e52: vec4 = textureSampleLevel(texCubeArray, samp, e47.xyz, i32(e47.w), 3.0); - c5 = e52; - let e57: vec4 = coord17; + c_5 = e52; + let e57: vec4 = coord_17; let e64: vec4 = textureSampleLevel(texCubeArray, samp, e57.xyz, i32(e57.w), 3.0, vec3(5, 5, 5)); - c5 = e64; - let e68: vec4 = coord17; + c_5 = e64; + let e68: vec4 = coord_17; let e74: vec4 = textureSample(texCubeArray, samp, e68.xyz, i32(e68.w), vec3(5, 5, 5)); - c5 = e74; - let e79: vec4 = coord17; + c_5 = e74; + let e79: vec4 = coord_17; let e86: vec4 = textureSampleBias(texCubeArray, samp, e79.xyz, i32(e79.w), 2.0, vec3(5, 5, 5)); - c5 = e86; + c_5 = e86; return; } -fn testTexCubeArrayShadow(coord18: vec4) { - var coord19: vec4; - var d3: f32; +fn testTexCubeArrayShadow(coord_18: vec4) { + var coord_19: vec4; + var d_3: f32; - coord19 = coord18; - let e19: vec4 = coord19; + coord_19 = coord_18; + let e19: vec4 = coord_19; let e24: f32 = textureSampleCompare(texCubeArrayShadow, sampShadow, e19.xyz, i32(e19.w), 1.0); - d3 = e24; + d_3 = e24; return; } -fn testTex3D(coord20: vec3) { - var coord21: vec3; - var c6: vec4; +fn testTex3D(coord_20: vec3) { + var coord_21: vec3; + var c_6: vec4; - coord21 = coord20; - let e18: vec3 = coord21; + coord_21 = coord_20; + let e18: vec3 = coord_21; let e19: vec4 = textureSample(tex3D, samp, e18); - c6 = e19; - let e22: vec3 = coord21; + c_6 = e19; + let e22: vec3 = coord_21; let e24: vec4 = textureSampleBias(tex3D, samp, e22, 2.0); - c6 = e24; - let e30: vec3 = coord21; + c_6 = e24; + let e30: vec3 = coord_21; let e35: vec4 = textureSampleGrad(tex3D, samp, e30, vec3(4.0), vec3(4.0)); - c6 = e35; - let e43: vec3 = coord21; + c_6 = e35; + let e43: vec3 = coord_21; let e50: vec4 = textureSampleGrad(tex3D, samp, e43, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); - c6 = e50; - let e53: vec3 = coord21; + c_6 = e50; + let e53: vec3 = coord_21; let e55: vec4 = textureSampleLevel(tex3D, samp, e53, 3.0); - c6 = e55; - let e60: vec3 = coord21; + c_6 = e55; + let e60: vec3 = coord_21; let e64: vec4 = textureSampleLevel(tex3D, samp, e60, 3.0, vec3(5, 5, 5)); - c6 = e64; - let e68: vec3 = coord21; + c_6 = e64; + let e68: vec3 = coord_21; let e71: vec4 = textureSample(tex3D, samp, e68, vec3(5, 5, 5)); - c6 = e71; - let e76: vec3 = coord21; + c_6 = e71; + let e76: vec3 = coord_21; let e80: vec4 = textureSampleBias(tex3D, samp, e76, 2.0, vec3(5, 5, 5)); - c6 = e80; + c_6 = e80; return; } -fn main1() { +fn main_1() { return; } [[stage(fragment)]] fn main([[location(0)]] texcoord: vec4) { - texcoord1 = texcoord; - main1(); + texcoord_1 = texcoord; + main_1(); return; } diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index a21bbb6d6..27565be73 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -18,13 +18,13 @@ var r_sampler: sampler; [[stage(vertex)]] fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { - var tmp1: i32; - var tmp2: i32; + var tmp1_: i32; + var tmp2_: i32; - tmp1 = (i32(vertex_index) / 2); - tmp2 = (i32(vertex_index) & 1); - let e10: i32 = tmp1; - let e16: i32 = tmp2; + tmp1_ = (i32(vertex_index) / 2); + tmp2_ = (i32(vertex_index) & 1); + let e10: i32 = tmp1_; + let e16: i32 = tmp2_; let pos: vec4 = vec4(((f32(e10) * 4.0) - 1.0), ((f32(e16) * 4.0) - 1.0), 0.0, 1.0); let e27: vec4 = r_data.view[0]; let e31: vec4 = r_data.view[1]; diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index 1e56f90a5..ece461039 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -1,4 +1,4 @@ -fn main1() { +fn main_1() { var x: vec3 = vec3(2.0, 2.0, 2.0); let e3: vec3 = x; @@ -15,6 +15,6 @@ fn main1() { [[stage(fragment)]] fn main() { - main1(); + main_1(); return; } From 8e2c4fbef57b65d6fcc11bf097c7b8f04b81c0dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 9 Nov 2021 14:35:59 +0000 Subject: [PATCH 1433/2212] [glsl-in] Don't panic on UB integer operations (#1518) --- src/front/glsl/constants.rs | 71 ++++++++++++++++++++++--------------- 1 file changed, 43 insertions(+), 28 deletions(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 8718b96ff..f3eae9ac1 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -293,16 +293,6 @@ impl<'a> ConstantSolver<'a> { target_width: crate::Bytes, span: crate::Span, ) -> Result, ConstantSolvingError> { - fn inner_cast(value: ScalarValue) -> A { - match value { - ScalarValue::Sint(v) => A::from_i64(v), - ScalarValue::Uint(v) => A::from_u64(v), - ScalarValue::Float(v) => A::from_f64(v), - ScalarValue::Bool(v) => A::from_u64(v as u64), - } - .unwrap() - } - let mut inner = self.constants[constant].inner.clone(); match inner { @@ -312,10 +302,30 @@ impl<'a> ConstantSolver<'a> { } => { *width = target_width; *value = match kind { - ScalarKind::Sint => ScalarValue::Sint(inner_cast(*value)), - ScalarKind::Uint => ScalarValue::Uint(inner_cast(*value)), - ScalarKind::Float => ScalarValue::Float(inner_cast(*value)), - ScalarKind::Bool => ScalarValue::Bool(inner_cast::(*value) != 0), + ScalarKind::Sint => ScalarValue::Sint(match *value { + ScalarValue::Sint(v) => v, + ScalarValue::Uint(v) => v as i64, + ScalarValue::Float(v) => v as i64, + ScalarValue::Bool(v) => v as i64, + }), + ScalarKind::Uint => ScalarValue::Uint(match *value { + ScalarValue::Sint(v) => v as u64, + ScalarValue::Uint(v) => v, + ScalarValue::Float(v) => v as u64, + ScalarValue::Bool(v) => v as u64, + }), + ScalarKind::Float => ScalarValue::Float(match *value { + ScalarValue::Sint(v) => v as f64, + ScalarValue::Uint(v) => v as f64, + ScalarValue::Float(v) => v, + ScalarValue::Bool(v) => v as u64 as f64, + }), + ScalarKind::Bool => ScalarValue::Bool(match *value { + ScalarValue::Sint(v) => v != 0, + ScalarValue::Uint(v) => v != 0, + ScalarValue::Float(v) => v != 0.0, + ScalarValue::Bool(v) => v, + }), } } ConstantInner::Composite { @@ -408,31 +418,36 @@ impl<'a> ConstantSolver<'a> { _ => match (left_value, right_value) { (ScalarValue::Sint(a), ScalarValue::Sint(b)) => { ScalarValue::Sint(match op { - BinaryOperator::Add => a + b, - BinaryOperator::Subtract => a - b, - BinaryOperator::Multiply => a * b, - BinaryOperator::Divide => a / b, - BinaryOperator::Modulo => a % b, + BinaryOperator::Add => a.wrapping_add(b), + BinaryOperator::Subtract => a.wrapping_sub(b), + BinaryOperator::Multiply => a.wrapping_mul(b), + BinaryOperator::Divide => a.checked_div(b).unwrap_or(0), + BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0), BinaryOperator::And => a & b, BinaryOperator::ExclusiveOr => a ^ b, BinaryOperator::InclusiveOr => a | b, - BinaryOperator::ShiftLeft => a << b, - BinaryOperator::ShiftRight => a >> b, + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }) + } + (ScalarValue::Sint(a), ScalarValue::Uint(b)) => { + ScalarValue::Sint(match op { + BinaryOperator::ShiftLeft => a.wrapping_shl(b as u32), + BinaryOperator::ShiftRight => a.wrapping_shr(b as u32), _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), }) } (ScalarValue::Uint(a), ScalarValue::Uint(b)) => { ScalarValue::Uint(match op { - BinaryOperator::Add => a + b, - BinaryOperator::Subtract => a - b, - BinaryOperator::Multiply => a * b, - BinaryOperator::Divide => a / b, - BinaryOperator::Modulo => a % b, + BinaryOperator::Add => a.wrapping_add(b), + BinaryOperator::Subtract => a.wrapping_sub(b), + BinaryOperator::Multiply => a.wrapping_mul(b), + BinaryOperator::Divide => a.checked_div(b).unwrap_or(0), + BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0), BinaryOperator::And => a & b, BinaryOperator::ExclusiveOr => a ^ b, BinaryOperator::InclusiveOr => a | b, - BinaryOperator::ShiftLeft => a << b, - BinaryOperator::ShiftRight => a >> b, + BinaryOperator::ShiftLeft => a.wrapping_shl(b as u32), + BinaryOperator::ShiftRight => a.wrapping_shr(b as u32), _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), }) } From 8a1dbcb05080a039aa8f2cb54a96460d776786e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 9 Nov 2021 14:52:29 +0000 Subject: [PATCH 1434/2212] [spv-in] Always use `get_expr_handle` for expressions in image expressions (#1516) * [spv-in] Use `get_expr_handle` in `parse_image_write` * [spv-in] Use BlockContext directly instead of its fields * [spv-in] Use `get_expr_handle` for depth ref --- src/front/spv/image.rs | 97 ++++++++++++++++++++---------------------- src/front/spv/mod.rs | 9 +--- 2 files changed, 49 insertions(+), 57 deletions(-) diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 48b38f658..1df6cb5f9 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -1,7 +1,4 @@ -use crate::{ - arena::{Arena, Handle, UniqueArena}, - FunctionArgument, -}; +use crate::arena::{Arena, Handle, UniqueArena}; use super::{Error, LookupExpression, LookupHelper as _}; @@ -21,16 +18,14 @@ bitflags::bitflags! { } } -impl Arena { +impl<'function> super::BlockContext<'function> { fn get_image_expr_ty( &self, handle: Handle, - global_vars: &Arena, - arguments: &[FunctionArgument], ) -> Result, Error> { - match self[handle] { - crate::Expression::GlobalVariable(handle) => Ok(global_vars[handle].ty), - crate::Expression::FunctionArgument(i) => Ok(arguments[i as usize].ty), + match self.expressions[handle] { + crate::Expression::GlobalVariable(handle) => Ok(self.global_arena[handle].ty), + crate::Expression::FunctionArgument(i) => Ok(self.arguments[i as usize].ty), ref other => Err(Error::InvalidImageExpression(other.clone())), } } @@ -62,10 +57,9 @@ fn extract_image_coordinates( extra_coordinate: ExtraCoordinate, base: Handle, coordinate_ty: Handle, - type_arena: &UniqueArena, - expressions: &mut Arena, + ctx: &mut super::BlockContext, ) -> (Handle, Option>) { - let (given_size, kind) = match type_arena[coordinate_ty].inner { + let (given_size, kind) = match ctx.type_arena[coordinate_ty].inner { crate::TypeInner::Scalar { kind, .. } => (None, kind), crate::TypeInner::Vector { size, kind, .. } => (Some(size), kind), ref other => unreachable!("Unexpected texture coordinate {:?}", other), @@ -73,7 +67,7 @@ fn extract_image_coordinates( let required_size = image_dim.required_coordinate_size(); let required_ty = required_size.map(|size| { - type_arena + ctx.type_arena .get(&crate::Type { name: None, inner: crate::TypeInner::Vector { @@ -89,22 +83,23 @@ fn extract_image_coordinates( index: required_size.map_or(1, |size| size as u32), }; - let base_span = expressions.get_span(base); + let base_span = ctx.expressions.get_span(base); match extra_coordinate { ExtraCoordinate::ArrayLayer => { let extracted = match required_size { - None => { - expressions.append(crate::Expression::AccessIndex { base, index: 0 }, base_span) - } + None => ctx + .expressions + .append(crate::Expression::AccessIndex { base, index: 0 }, base_span), Some(size) => { let mut components = Vec::with_capacity(size as usize); for index in 0..size as u32 { - let comp = expressions + let comp = ctx + .expressions .append(crate::Expression::AccessIndex { base, index }, base_span); components.push(comp); } - expressions.append( + ctx.expressions.append( crate::Expression::Compose { ty: required_ty.unwrap(), components, @@ -113,8 +108,8 @@ fn extract_image_coordinates( ) } }; - let array_index_f32 = expressions.append(extra_expr, base_span); - let array_index = expressions.append( + let array_index_f32 = ctx.expressions.append(extra_expr, base_span); + let array_index = ctx.expressions.append( crate::Expression::As { kind: crate::ScalarKind::Sint, expr: array_index_f32, @@ -125,12 +120,13 @@ fn extract_image_coordinates( (extracted, Some(array_index)) } ExtraCoordinate::Projection => { - let projection = expressions.append(extra_expr, base_span); + let projection = ctx.expressions.append(extra_expr, base_span); let divided = match required_size { None => { - let temp = expressions + let temp = ctx + .expressions .append(crate::Expression::AccessIndex { base, index: 0 }, base_span); - expressions.append( + ctx.expressions.append( crate::Expression::Binary { op: crate::BinaryOperator::Divide, left: temp, @@ -142,9 +138,10 @@ fn extract_image_coordinates( Some(size) => { let mut components = Vec::with_capacity(size as usize); for index in 0..size as u32 { - let temp = expressions + let temp = ctx + .expressions .append(crate::Expression::AccessIndex { base, index }, base_span); - let comp = expressions.append( + let comp = ctx.expressions.append( crate::Expression::Binary { op: crate::BinaryOperator::Divide, left: temp, @@ -154,7 +151,7 @@ fn extract_image_coordinates( ); components.push(comp); } - expressions.append( + ctx.expressions.append( crate::Expression::Compose { ty: required_ty.unwrap(), components, @@ -176,7 +173,7 @@ fn extract_image_coordinates( pattern: [Sc::X, Sc::Y, Sc::Z, Sc::W], }, }; - (expressions.append(cut_expr, base_span), None) + (ctx.expressions.append(cut_expr, base_span), None) } } } @@ -257,10 +254,10 @@ impl> super::Parser { pub(super) fn parse_image_write( &mut self, words_left: u16, - type_arena: &UniqueArena, - global_arena: &Arena, - arguments: &[FunctionArgument], - expressions: &mut Arena, + ctx: &mut super::BlockContext, + emitter: &mut crate::front::Emitter, + block: &mut crate::Block, + body_idx: usize, ) -> Result { let image_id = self.next()?; let coordinate_id = self.next()?; @@ -277,11 +274,13 @@ impl> super::Parser { } let image_lexp = self.lookup_expression.lookup(image_id)?; - let image_ty = expressions.get_image_expr_ty(image_lexp.handle, global_arena, arguments)?; + let image_ty = ctx.get_image_expr_ty(image_lexp.handle)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; + let coord_handle = + self.get_expr_handle(coordinate_id, coord_lexp, ctx, emitter, block, body_idx); let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; - let (coordinate, array_index) = match type_arena[image_ty].inner { + let (coordinate, array_index) = match ctx.type_arena[image_ty].inner { crate::TypeInner::Image { dim, arrayed, @@ -293,21 +292,21 @@ impl> super::Parser { } else { ExtraCoordinate::Garbage }, - coord_lexp.handle, + coord_handle, coord_type_handle, - type_arena, - expressions, + ctx, ), _ => return Err(Error::InvalidImage(image_ty)), }; let value_lexp = self.lookup_expression.lookup(value_id)?; + let value = self.get_expr_handle(value_id, value_lexp, ctx, emitter, block, body_idx); Ok(crate::Statement::ImageStore { image: image_lexp.handle, coordinate, array_index, - value: value_lexp.handle, + value, }) } @@ -339,7 +338,9 @@ impl> super::Parser { match spirv::ImageOperands::from_bits_truncate(bit) { spirv::ImageOperands::LOD => { let lod_expr = self.next()?; - let lod_handle = self.lookup_expression.lookup(lod_expr)?.handle; + let lod_lexp = self.lookup_expression.lookup(lod_expr)?; + let lod_handle = + self.get_expr_handle(lod_expr, lod_lexp, ctx, emitter, block, body_idx); index = Some(lod_handle); words_left -= 1; } @@ -363,11 +364,7 @@ impl> super::Parser { // No need to call get_expr_handle here since only globals/arguments are // allowed as images and they are always in the root scope let image_lexp = self.lookup_expression.lookup(image_id)?; - let image_ty = ctx.expressions.get_image_expr_ty( - image_lexp.handle, - ctx.global_arena, - ctx.arguments, - )?; + let image_ty = ctx.get_image_expr_ty(image_lexp.handle)?; let coord_lexp = self.lookup_expression.lookup(coordinate_id)?; let coord_handle = @@ -387,8 +384,7 @@ impl> super::Parser { }, coord_handle, coord_type_handle, - ctx.type_arena, - ctx.expressions, + ctx, ), _ => return Err(Error::InvalidImage(image_ty)), }; @@ -571,13 +567,14 @@ impl> super::Parser { }, coord_handle, coord_type_handle, - ctx.type_arena, - ctx.expressions, + ctx, ), { match dref_id { Some(id) => { - let mut expr = self.lookup_expression.lookup(id)?.handle; + let expr_lexp = self.lookup_expression.lookup(id)?; + let mut expr = + self.get_expr_handle(id, expr_lexp, ctx, emitter, block, body_idx); if options.project { let required_size = dim.required_coordinate_size(); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3df39bde3..26f849bd2 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2144,13 +2144,8 @@ impl> Parser { } Op::ImageWrite => { let extra = inst.expect_at_least(4)?; - let stmt = self.parse_image_write( - extra, - ctx.type_arena, - ctx.global_arena, - ctx.arguments, - ctx.expressions, - )?; + let stmt = + self.parse_image_write(extra, ctx, &mut emitter, &mut block, body_idx)?; block.extend(emitter.finish(ctx.expressions)); block.push(stmt, span); emitter.start(ctx.expressions); From e26bff1b8da795cc41ef64ecf212cac012ff2edb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 7 Nov 2021 18:21:03 +0000 Subject: [PATCH 1435/2212] [glsl-in] Split constructor calls into two functions Improves code readability and removes nesting --- src/front/glsl/functions.rs | 507 ++++++++++++++++++------------------ 1 file changed, 252 insertions(+), 255 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index e8693fb20..5344ef25b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -54,294 +54,291 @@ impl Parser { match fc { FunctionCallKind::TypeConstructor(ty) => { - let h = if args.len() == 1 { - let expr_type = self.resolve_type(ctx, args[0].0, args[0].1)?; + if args.len() == 1 { + self.constructor_single(ctx, body, ty, args, meta).map(Some) + } else { + self.constructor_many(ctx, body, ty, args, meta).map(Some) + } + } + FunctionCallKind::Function(name) => { + self.function_call(ctx, stmt, body, name, args, raw_args, meta) + } + } + } - let vector_size = match *expr_type { - TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; + fn constructor_single( + &mut self, + ctx: &mut Context, + body: &mut Block, + ty: Handle, + args: Vec<(Handle, Span)>, + meta: Span, + ) -> Result> { + let expr_type = self.resolve_type(ctx, args[0].0, args[0].1)?; - // Special case: if casting from a bool, we need to use Select and not As. - match self.module.types[ty].inner.scalar_kind() { - Some(result_scalar_kind) - if expr_type.scalar_kind() == Some(ScalarKind::Bool) - && result_scalar_kind != ScalarKind::Bool => - { - let (condition, expr_meta) = args[0]; - let c0 = self.add_constant_value(result_scalar_kind, 0u64, meta); - let c1 = self.add_constant_value(result_scalar_kind, 1u64, meta); - let mut reject = - ctx.add_expression(Expression::Constant(c0), expr_meta, body); - let mut accept = - ctx.add_expression(Expression::Constant(c1), expr_meta, body); + let vector_size = match *expr_type { + TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; - ctx.implicit_splat(self, &mut reject, meta, vector_size)?; - ctx.implicit_splat(self, &mut accept, meta, vector_size)?; + // Special case: if casting from a bool, we need to use Select and not As. + match self.module.types[ty].inner.scalar_kind() { + Some(result_scalar_kind) + if expr_type.scalar_kind() == Some(ScalarKind::Bool) + && result_scalar_kind != ScalarKind::Bool => + { + let (condition, expr_meta) = args[0]; + let c0 = self.add_constant_value(result_scalar_kind, 0u64, meta); + let c1 = self.add_constant_value(result_scalar_kind, 1u64, meta); + let mut reject = ctx.add_expression(Expression::Constant(c0), expr_meta, body); + let mut accept = ctx.add_expression(Expression::Constant(c1), expr_meta, body); - let h = ctx.add_expression( - Expression::Select { - accept, - reject, - condition, + ctx.implicit_splat(self, &mut reject, meta, vector_size)?; + ctx.implicit_splat(self, &mut accept, meta, vector_size)?; + + let h = ctx.add_expression( + Expression::Select { + accept, + reject, + condition, + }, + expr_meta, + body, + ); + + return Ok(h); + } + _ => {} + } + + Ok(match self.module.types[ty].inner { + TypeInner::Vector { size, kind, width } if vector_size.is_none() => { + let (mut value, meta) = args[0]; + ctx.implicit_conversion(self, &mut value, meta, kind, width)?; + + ctx.add_expression(Expression::Splat { size, value }, meta, body) + } + TypeInner::Scalar { kind, width } => ctx.add_expression( + Expression::As { + kind, + expr: args[0].0, + convert: Some(width), + }, + args[0].1, + body, + ), + TypeInner::Vector { size, kind, width } => { + let mut expr = args[0].0; + + if vector_size.map_or(true, |s| s != size) { + expr = ctx.vector_resize(size, expr, args[0].1, body); + } + + ctx.add_expression( + Expression::As { + kind, + expr, + convert: Some(width), + }, + args[0].1, + body, + ) + } + TypeInner::Matrix { + columns, + rows, + width, + } => { + // TODO: casts + // `Expression::As` doesn't support matrix width + // casts so we need to do some extra work for casts + + let (mut value, meta) = args[0]; + ctx.implicit_conversion(self, &mut value, meta, ScalarKind::Float, width)?; + match *self.resolve_type(ctx, value, meta)? { + TypeInner::Scalar { .. } => { + // If a matrix is constructed with a single scalar value, then that + // value is used to initialize all the values along the diagonal of + // the matrix; the rest are given zeros. + let mut components = Vec::with_capacity(columns as usize); + let vector_ty = self.module.types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, }, - expr_meta, + }, + meta, + ); + let zero_constant = self.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width, + value: ScalarValue::Float(0.0), + }, + }, + meta, + ); + let zero = + ctx.add_expression(Expression::Constant(zero_constant), meta, body); + + for i in 0..columns as u32 { + components.push( + ctx.add_expression( + Expression::Compose { + ty: vector_ty, + components: (0..rows as u32) + .into_iter() + .map(|r| match r == i { + true => value, + false => zero, + }) + .collect(), + }, + meta, + body, + ), + ) + } + + ctx.add_expression(Expression::Compose { ty, components }, meta, body) + } + TypeInner::Matrix { rows: ori_rows, .. } => { + let mut components = Vec::new(); + + for n in 0..columns as u32 { + let mut vector = ctx.add_expression( + Expression::AccessIndex { + base: value, + index: n, + }, + meta, body, ); - return Ok(Some(h)); + if ori_rows != rows { + vector = ctx.vector_resize(rows, vector, meta, body); + } + + components.push(vector) } - _ => {} + + ctx.add_expression(Expression::Compose { ty, components }, meta, body) } + _ => { + let columns = iter::repeat(value).take(columns as usize).collect(); - match self.module.types[ty].inner { - TypeInner::Vector { size, kind, width } if vector_size.is_none() => { - let (mut value, meta) = args[0]; - ctx.implicit_conversion(self, &mut value, meta, kind, width)?; - - ctx.add_expression(Expression::Splat { size, value }, meta, body) - } - TypeInner::Scalar { kind, width } => ctx.add_expression( - Expression::As { - kind, - expr: args[0].0, - convert: Some(width), - }, - args[0].1, - body, - ), - TypeInner::Vector { size, kind, width } => { - let mut expr = args[0].0; - - if vector_size.map_or(true, |s| s != size) { - expr = ctx.vector_resize(size, expr, args[0].1, body); - } - - ctx.add_expression( - Expression::As { - kind, - expr, - convert: Some(width), - }, - args[0].1, - body, - ) - } - TypeInner::Matrix { - columns, - rows, - width, - } => { - // TODO: casts - // `Expression::As` doesn't support matrix width - // casts so we need to do some extra work for casts - - let (mut value, meta) = args[0]; - ctx.implicit_conversion( - self, - &mut value, - meta, - ScalarKind::Float, - width, - )?; - match *self.resolve_type(ctx, value, meta)? { - TypeInner::Scalar { .. } => { - // If a matrix is constructed with a single scalar value, then that - // value is used to initialize all the values along the diagonal of - // the matrix; the rest are given zeros. - let mut components = Vec::with_capacity(columns as usize); - let vector_ty = self.module.types.insert( - Type { - name: None, - inner: TypeInner::Vector { - size: rows, - kind: ScalarKind::Float, - width, - }, - }, - meta, - ); - let zero_constant = self.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width, - value: ScalarValue::Float(0.0), - }, - }, - meta, - ); - let zero = ctx.add_expression( - Expression::Constant(zero_constant), - meta, - body, - ); - - for i in 0..columns as u32 { - components.push( - ctx.add_expression( - Expression::Compose { - ty: vector_ty, - components: (0..rows as u32) - .into_iter() - .map(|r| match r == i { - true => value, - false => zero, - }) - .collect(), - }, - meta, - body, - ), - ) - } - - ctx.add_expression( - Expression::Compose { ty, components }, - meta, - body, - ) - } - TypeInner::Matrix { rows: ori_rows, .. } => { - let mut components = Vec::new(); - - for n in 0..columns as u32 { - let mut vector = ctx.add_expression( - Expression::AccessIndex { - base: value, - index: n, - }, - meta, - body, - ); - - if ori_rows != rows { - vector = ctx.vector_resize(rows, vector, meta, body); - } - - components.push(vector) - } - - ctx.add_expression( - Expression::Compose { ty, components }, - meta, - body, - ) - } - _ => { - let columns = - iter::repeat(value).take(columns as usize).collect(); - - ctx.add_expression( - Expression::Compose { - ty, - components: columns, - }, - meta, - body, - ) - } - } - } - TypeInner::Struct { .. } | TypeInner::Array { .. } => ctx.add_expression( + ctx.add_expression( Expression::Compose { ty, - components: args.into_iter().map(|arg| arg.0).collect(), + components: columns, }, meta, body, - ), - _ => { - self.errors.push(Error { - kind: ErrorKind::SemanticError("Bad type constructor".into()), - meta, - }); - - args[0].0 - } + ) } - } else { - let mut components = Vec::with_capacity(args.len()); + } + } + TypeInner::Struct { .. } | TypeInner::Array { .. } => ctx.add_expression( + Expression::Compose { + ty, + components: args.into_iter().map(|arg| arg.0).collect(), + }, + meta, + body, + ), + _ => { + self.errors.push(Error { + kind: ErrorKind::SemanticError("Bad type constructor".into()), + meta, + }); - match self.module.types[ty].inner { - TypeInner::Matrix { - columns, - rows, - width, - } => { - let mut flattened = - Vec::with_capacity(columns as usize * rows as usize); + args[0].0 + } + }) + } - for (mut arg, meta) in args.iter().copied() { - let scalar_components = - scalar_components(&self.module.types[ty].inner); - if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; - } + fn constructor_many( + &mut self, + ctx: &mut Context, + body: &mut Block, + ty: Handle, + args: Vec<(Handle, Span)>, + meta: Span, + ) -> Result> { + let mut components = Vec::with_capacity(args.len()); - match *self.resolve_type(ctx, arg, meta)? { - TypeInner::Vector { size, .. } => { - for i in 0..(size as u32) { - flattened.push(ctx.add_expression( - Expression::AccessIndex { - base: arg, - index: i, - }, - meta, - body, - )) - } - } - _ => flattened.push(arg), - } - } + match self.module.types[ty].inner { + TypeInner::Matrix { + columns, + rows, + width, + } => { + let mut flattened = Vec::with_capacity(columns as usize * rows as usize); - let ty = self.module.types.insert( - Type { - name: None, - inner: TypeInner::Vector { - size: rows, - kind: ScalarKind::Float, - width, - }, - }, - meta, - ); + for (mut arg, meta) in args.iter().copied() { + let scalar_components = scalar_components(&self.module.types[ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; + } - for chunk in flattened.chunks(rows as usize) { - components.push(ctx.add_expression( - Expression::Compose { - ty, - components: Vec::from(chunk), + match *self.resolve_type(ctx, arg, meta)? { + TypeInner::Vector { size, .. } => { + for i in 0..(size as u32) { + flattened.push(ctx.add_expression( + Expression::AccessIndex { + base: arg, + index: i, }, meta, body, )) } } - _ => { - for (mut arg, meta) in args.iter().copied() { - let scalar_components = - scalar_components(&self.module.types[ty].inner); - if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; - } + _ => flattened.push(arg), + } + } - components.push(arg) - } - } + let ty = self.module.types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, + }, + }, + meta, + ); + + for chunk in flattened.chunks(rows as usize) { + components.push(ctx.add_expression( + Expression::Compose { + ty, + components: Vec::from(chunk), + }, + meta, + body, + )) + } + } + _ => { + for (mut arg, meta) in args.iter().copied() { + let scalar_components = scalar_components(&self.module.types[ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; } - ctx.add_expression(Expression::Compose { ty, components }, meta, body) - }; - - Ok(Some(h)) - } - FunctionCallKind::Function(name) => { - self.function_call(ctx, stmt, body, name, args, raw_args, meta) + components.push(arg) + } } } + + Ok(ctx.add_expression(Expression::Compose { ty, components }, meta, body)) } #[allow(clippy::too_many_arguments)] From 7234d19d00707a1bef4674913bba4abda8321210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 7 Nov 2021 20:58:59 +0000 Subject: [PATCH 1436/2212] [glsl-in] Implement matrix to matrix constructor --- src/front/glsl/functions.rs | 324 +++++++++++++++-------- tests/out/wgsl/210-bevy-shader-vert.wgsl | 20 +- tests/out/wgsl/bevy-pbr-vert.wgsl | 22 +- 3 files changed, 235 insertions(+), 131 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 5344ef25b..42829cd41 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -55,7 +55,8 @@ impl Parser { match fc { FunctionCallKind::TypeConstructor(ty) => { if args.len() == 1 { - self.constructor_single(ctx, body, ty, args, meta).map(Some) + self.constructor_single(ctx, body, ty, args[0], meta) + .map(Some) } else { self.constructor_many(ctx, body, ty, args, meta).map(Some) } @@ -71,10 +72,10 @@ impl Parser { ctx: &mut Context, body: &mut Block, ty: Handle, - args: Vec<(Handle, Span)>, + (mut value, expr_meta): (Handle, Span), meta: Span, ) -> Result> { - let expr_type = self.resolve_type(ctx, args[0].0, args[0].1)?; + let expr_type = self.resolve_type(ctx, value, expr_meta)?; let vector_size = match *expr_type { TypeInner::Vector { size, .. } => Some(size), @@ -87,7 +88,6 @@ impl Parser { if expr_type.scalar_kind() == Some(ScalarKind::Bool) && result_scalar_kind != ScalarKind::Bool => { - let (condition, expr_meta) = args[0]; let c0 = self.add_constant_value(result_scalar_kind, 0u64, meta); let c1 = self.add_constant_value(result_scalar_kind, 1u64, meta); let mut reject = ctx.add_expression(Expression::Constant(c0), expr_meta, body); @@ -100,7 +100,7 @@ impl Parser { Expression::Select { accept, reject, - condition, + condition: value, }, expr_meta, body, @@ -113,7 +113,6 @@ impl Parser { Ok(match self.module.types[ty].inner { TypeInner::Vector { size, kind, width } if vector_size.is_none() => { - let (mut value, meta) = args[0]; ctx.implicit_conversion(self, &mut value, meta, kind, width)?; ctx.add_expression(Expression::Splat { size, value }, meta, body) @@ -121,26 +120,24 @@ impl Parser { TypeInner::Scalar { kind, width } => ctx.add_expression( Expression::As { kind, - expr: args[0].0, + expr: value, convert: Some(width), }, - args[0].1, + meta, body, ), TypeInner::Vector { size, kind, width } => { - let mut expr = args[0].0; - if vector_size.map_or(true, |s| s != size) { - expr = ctx.vector_resize(size, expr, args[0].1, body); + value = ctx.vector_resize(size, value, expr_meta, body); } ctx.add_expression( Expression::As { kind, - expr, + expr: value, convert: Some(width), }, - args[0].1, + meta, body, ) } @@ -148,105 +145,20 @@ impl Parser { columns, rows, width, - } => { - // TODO: casts - // `Expression::As` doesn't support matrix width - // casts so we need to do some extra work for casts - - let (mut value, meta) = args[0]; - ctx.implicit_conversion(self, &mut value, meta, ScalarKind::Float, width)?; - match *self.resolve_type(ctx, value, meta)? { - TypeInner::Scalar { .. } => { - // If a matrix is constructed with a single scalar value, then that - // value is used to initialize all the values along the diagonal of - // the matrix; the rest are given zeros. - let mut components = Vec::with_capacity(columns as usize); - let vector_ty = self.module.types.insert( - Type { - name: None, - inner: TypeInner::Vector { - size: rows, - kind: ScalarKind::Float, - width, - }, - }, - meta, - ); - let zero_constant = self.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width, - value: ScalarValue::Float(0.0), - }, - }, - meta, - ); - let zero = - ctx.add_expression(Expression::Constant(zero_constant), meta, body); - - for i in 0..columns as u32 { - components.push( - ctx.add_expression( - Expression::Compose { - ty: vector_ty, - components: (0..rows as u32) - .into_iter() - .map(|r| match r == i { - true => value, - false => zero, - }) - .collect(), - }, - meta, - body, - ), - ) - } - - ctx.add_expression(Expression::Compose { ty, components }, meta, body) - } - TypeInner::Matrix { rows: ori_rows, .. } => { - let mut components = Vec::new(); - - for n in 0..columns as u32 { - let mut vector = ctx.add_expression( - Expression::AccessIndex { - base: value, - index: n, - }, - meta, - body, - ); - - if ori_rows != rows { - vector = ctx.vector_resize(rows, vector, meta, body); - } - - components.push(vector) - } - - ctx.add_expression(Expression::Compose { ty, components }, meta, body) - } - _ => { - let columns = iter::repeat(value).take(columns as usize).collect(); - - ctx.add_expression( - Expression::Compose { - ty, - components: columns, - }, - meta, - body, - ) - } - } - } + } => self.matrix_one_arg( + ctx, + body, + ty, + columns, + rows, + width, + (value, expr_meta), + meta, + )?, TypeInner::Struct { .. } | TypeInner::Array { .. } => ctx.add_expression( Expression::Compose { ty, - components: args.into_iter().map(|arg| arg.0).collect(), + components: vec![value], }, meta, body, @@ -257,11 +169,203 @@ impl Parser { meta, }); - args[0].0 + value } }) } + #[allow(clippy::too_many_arguments)] + fn matrix_one_arg( + &mut self, + ctx: &mut Context, + body: &mut Block, + ty: Handle, + columns: crate::VectorSize, + rows: crate::VectorSize, + width: crate::Bytes, + (mut value, expr_meta): (Handle, Span), + meta: Span, + ) -> Result> { + let mut components = Vec::with_capacity(columns as usize); + // TODO: casts + // `Expression::As` doesn't support matrix width + // casts so we need to do some extra work for casts + + ctx.implicit_conversion(self, &mut value, expr_meta, ScalarKind::Float, width)?; + match *self.resolve_type(ctx, value, expr_meta)? { + TypeInner::Scalar { .. } => { + // If a matrix is constructed with a single scalar value, then that + // value is used to initialize all the values along the diagonal of + // the matrix; the rest are given zeros. + let vector_ty = self.module.types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, + }, + }, + meta, + ); + let zero_constant = self.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width, + value: ScalarValue::Float(0.0), + }, + }, + meta, + ); + let zero = ctx.add_expression(Expression::Constant(zero_constant), meta, body); + + for i in 0..columns as u32 { + components.push( + ctx.add_expression( + Expression::Compose { + ty: vector_ty, + components: (0..rows as u32) + .into_iter() + .map(|r| match r == i { + true => value, + false => zero, + }) + .collect(), + }, + meta, + body, + ), + ) + } + } + TypeInner::Matrix { + rows: ori_rows, + columns: ori_cols, + .. + } => { + // If a matrix is constructed from a matrix, then each component + // (column i, row j) in the result that has a corresponding component + // (column i, row j) in the argument will be initialized from there. All + // other components will be initialized to the identity matrix. + + let zero_constant = self.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width, + value: ScalarValue::Float(0.0), + }, + }, + meta, + ); + let zero = ctx.add_expression(Expression::Constant(zero_constant), meta, body); + let one_constant = self.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width, + value: ScalarValue::Float(1.0), + }, + }, + meta, + ); + let one = ctx.add_expression(Expression::Constant(one_constant), meta, body); + let vector_ty = self.module.types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, + }, + }, + meta, + ); + + for i in 0..columns as u32 { + if i < ori_cols as u32 { + use std::cmp::Ordering; + + let vector = ctx.add_expression( + Expression::AccessIndex { + base: value, + index: i, + }, + meta, + body, + ); + + components.push(match ori_rows.cmp(&rows) { + Ordering::Less => { + let components = (0..rows as u32) + .into_iter() + .map(|r| { + if r < ori_rows as u32 { + ctx.add_expression( + Expression::AccessIndex { + base: vector, + index: r, + }, + meta, + body, + ) + } else if r == i { + one + } else { + zero + } + }) + .collect(); + + ctx.add_expression( + Expression::Compose { + ty: vector_ty, + components, + }, + meta, + body, + ) + } + Ordering::Equal => vector, + Ordering::Greater => ctx.vector_resize(rows, vector, meta, body), + }) + } else { + let vec_constant = self.module.constants.fetch_or_append( + Constant { + name: None, + specialization: None, + inner: ConstantInner::Composite { + ty: vector_ty, + components: (0..rows as u32) + .into_iter() + .map(|r| match r == i { + true => one_constant, + false => zero_constant, + }) + .collect(), + }, + }, + meta, + ); + let vec = + ctx.add_expression(Expression::Constant(vec_constant), meta, body); + + components.push(vec) + } + } + } + _ => { + components = iter::repeat(value).take(columns as usize).collect(); + } + } + + Ok(ctx.add_expression(Expression::Compose { ty, components }, meta, body)) + } + fn constructor_many( &mut self, ctx: &mut Context, diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 29af6ada8..afe639d3a 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -32,16 +32,16 @@ fn main_1() { let e11: vec3 = Vertex_Normal_1; v_Normal = (e10 * vec4(e11, 1.0)).xyz; let e16: mat4x4 = global_1.Model; - let e24: vec3 = Vertex_Normal_1; - v_Normal = (mat3x3(e16[0].xyz, e16[1].xyz, e16[2].xyz) * e24); - let e26: mat4x4 = global_1.Model; - let e27: vec3 = Vertex_Position_1; - v_Position = (e26 * vec4(e27, 1.0)).xyz; - let e32: vec2 = Vertex_Uv_1; - v_Uv = e32; - let e34: mat4x4 = global.ViewProj; - let e35: vec3 = v_Position; - gl_Position = (e34 * vec4(e35, 1.0)); + let e26: vec3 = Vertex_Normal_1; + v_Normal = (mat3x3(e16[0].xyz, e16[1].xyz, e16[2].xyz) * e26); + let e28: mat4x4 = global_1.Model; + let e29: vec3 = Vertex_Position_1; + v_Position = (e28 * vec4(e29, 1.0)).xyz; + let e34: vec2 = Vertex_Uv_1; + v_Uv = e34; + let e36: mat4x4 = global.ViewProj; + let e37: vec3 = v_Position; + gl_Position = (e36 * vec4(e37, 1.0)); return; } diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index e448ca91f..01ed0b59f 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -39,17 +39,17 @@ fn main_1() { let e18: vec4 = world_position; v_WorldPosition = e18.xyz; let e20: mat4x4 = global_1.Model; - let e28: vec3 = Vertex_Normal_1; - v_WorldNormal = (mat3x3(e20[0].xyz, e20[1].xyz, e20[2].xyz) * e28); - let e30: vec2 = Vertex_Uv_1; - v_Uv = e30; - let e31: mat4x4 = global_1.Model; - let e39: vec4 = Vertex_Tangent_1; - let e42: vec4 = Vertex_Tangent_1; - v_WorldTangent = vec4((mat3x3(e31[0].xyz, e31[1].xyz, e31[2].xyz) * e39.xyz), e42.w); - let e46: mat4x4 = global.ViewProj; - let e47: vec4 = world_position; - gl_Position = (e46 * e47); + let e30: vec3 = Vertex_Normal_1; + v_WorldNormal = (mat3x3(e20[0].xyz, e20[1].xyz, e20[2].xyz) * e30); + let e32: vec2 = Vertex_Uv_1; + v_Uv = e32; + let e33: mat4x4 = global_1.Model; + let e43: vec4 = Vertex_Tangent_1; + let e46: vec4 = Vertex_Tangent_1; + v_WorldTangent = vec4((mat3x3(e33[0].xyz, e33[1].xyz, e33[2].xyz) * e43.xyz), e46.w); + let e50: mat4x4 = global.ViewProj; + let e51: vec4 = world_position; + gl_Position = (e50 * e51); return; } From c3c4ab75489813a6dd242270c9ebcc5bffdf168b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 7 Nov 2021 21:03:00 +0000 Subject: [PATCH 1437/2212] [glsl-in] Add test for matrix from matrix constructor --- tests/in/glsl/long-form-matrix.vert | 1 + tests/out/wgsl/long-form-matrix-vert.wgsl | 24 ++++++++++++----------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/tests/in/glsl/long-form-matrix.vert b/tests/in/glsl/long-form-matrix.vert index 93a4f2d7f..ab40baa84 100644 --- a/tests/in/glsl/long-form-matrix.vert +++ b/tests/in/glsl/long-form-matrix.vert @@ -5,6 +5,7 @@ void main() { // Sane ways to build a matrix mat2 splat = mat2(1); mat2 normal = mat2(vec2(1), vec2(2)); + mat2x4 from_matrix = mat2x4(mat3(1.0)); // This is a little bit weirder but still makes some sense // Since this matrix has 2 rows we take two numbers to make a column diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index 60f702df6..1de0a4f29 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -1,6 +1,7 @@ fn main_1() { var splat: mat2x2 = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); var normal: mat2x2 = mat2x2(vec2(1.0, 1.0), vec2(2.0, 2.0)); + var from_matrix: mat2x4 = mat2x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0)); var a: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); var b: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); var c: mat3x3 = mat3x3(vec3(1.0, 2.0, 3.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); @@ -10,17 +11,18 @@ fn main_1() { let e1: f32 = f32(1); let e9: vec2 = vec2(f32(1)); let e12: vec2 = vec2(f32(2)); - let e38: vec2 = vec2(f32(2), f32(3)); - let e53: vec3 = vec3(f32(1)); - let e56: vec3 = vec3(f32(1)); - let e73: vec2 = vec2(f32(2)); - let e77: vec3 = vec3(f32(1)); - let e80: vec3 = vec3(f32(1)); - let e97: vec2 = vec2(f32(2)); - let e100: vec4 = vec4(f32(1)); - let e103: vec2 = vec2(f32(2)); - let e106: vec4 = vec4(f32(1)); - let e109: vec4 = vec4(f32(1)); + let e26: mat3x3 = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); + let e58: vec2 = vec2(f32(2), f32(3)); + let e73: vec3 = vec3(f32(1)); + let e76: vec3 = vec3(f32(1)); + let e93: vec2 = vec2(f32(2)); + let e97: vec3 = vec3(f32(1)); + let e100: vec3 = vec3(f32(1)); + let e117: vec2 = vec2(f32(2)); + let e120: vec4 = vec4(f32(1)); + let e123: vec2 = vec2(f32(2)); + let e126: vec4 = vec4(f32(1)); + let e129: vec4 = vec4(f32(1)); } [[stage(vertex)]] From d168f15d8186c6f7eeefabd4ac6f63a0dc1224a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 10 Nov 2021 17:15:43 +0000 Subject: [PATCH 1438/2212] [glsl-in] Allow constructors from non-scalar to scalar (#1520) --- src/front/glsl/functions.rs | 45 ++++++++++++++++++++++------ tests/in/glsl/expressions.frag | 4 +++ tests/out/wgsl/expressions-frag.wgsl | 5 ++++ 3 files changed, 45 insertions(+), 9 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 42829cd41..1db1b4bc8 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -117,15 +117,42 @@ impl Parser { ctx.add_expression(Expression::Splat { size, value }, meta, body) } - TypeInner::Scalar { kind, width } => ctx.add_expression( - Expression::As { - kind, - expr: value, - convert: Some(width), - }, - meta, - body, - ), + TypeInner::Scalar { kind, width } => { + let mut expr = value; + if let TypeInner::Vector { .. } | TypeInner::Matrix { .. } = + *self.resolve_type(ctx, value, expr_meta)? + { + expr = ctx.add_expression( + Expression::AccessIndex { + base: expr, + index: 0, + }, + meta, + body, + ); + } + + if let TypeInner::Matrix { .. } = *self.resolve_type(ctx, value, expr_meta)? { + expr = ctx.add_expression( + Expression::AccessIndex { + base: expr, + index: 0, + }, + meta, + body, + ); + } + + ctx.add_expression( + Expression::As { + kind, + expr, + convert: Some(width), + }, + meta, + body, + ) + } TypeInner::Vector { size, kind, width } => { if vector_size.map_or(true, |s| s != size) { value = ctx.vector_resize(size, value, expr_meta, body); diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 105d6116d..f1a959f47 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -70,6 +70,10 @@ void testStructConstructor() { BST tree = BST(1); } +void testNonScalarToScalarConstructor() { + float f = float(mat2(1.0)); +} + void testArrayConstructor() { float tree[1] = float[1](0.0); } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 899978fbb..865b88cc7 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -180,6 +180,11 @@ fn testStructConstructor() { } +fn testNonScalarToScalarConstructor() { + var f: f32 = 1.0; + +} + fn testArrayConstructor() { var tree_1: array = array(0.0); From eda078d736a906b4267e4803db6b32e3162aac30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 10 Nov 2021 17:16:19 +0000 Subject: [PATCH 1439/2212] [glsl-in] Allow more operations as access bases (#1521) --- src/front/glsl/context.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 6729c6f79..dd2f73874 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -492,10 +492,10 @@ impl Context { parser.field_selection(self, ExprPos::Lhs == pos, body, base, field, meta)? } - HirExprKind::Constant(constant) if pos == ExprPos::Rhs => { + HirExprKind::Constant(constant) if pos != ExprPos::Lhs => { self.add_expression(Expression::Constant(constant), meta, body) } - HirExprKind::Binary { left, op, right } if pos == ExprPos::Rhs => { + HirExprKind::Binary { left, op, right } if pos != ExprPos::Lhs => { let (mut left, left_meta) = self.lower_expect_inner(stmt, parser, left, pos, body)?; let (mut right, right_meta) = @@ -599,7 +599,7 @@ impl Context { _ => self.add_expression(Expression::Binary { left, op, right }, meta, body), } } - HirExprKind::Unary { op, expr } if pos == ExprPos::Rhs => { + HirExprKind::Unary { op, expr } if pos != ExprPos::Lhs => { let expr = self.lower_expect_inner(stmt, parser, expr, pos, body)?.0; self.add_expression(Expression::Unary { op, expr }, meta, body) From e69a70bfb7b3dff1391d5189d5c68fb798c02040 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 10 Nov 2021 13:58:57 -0800 Subject: [PATCH 1440/2212] [spv-in] Permit pointers to runtime arrays only in StorageBuffer. (#1522) * [spv-in] Change shadow.spv test input to use StorageBuffer. The ecosystem around Naga will generally not be able to use Vulkan adapters that don't support the SPV_KHR_storage_buffer_storage_class (which was incorporated into SPIR-V 1.3), so we can assume it is present. Changing the test not to use runtime-sized arrays in the Uniform storage class will allow Naga to tighten up some validation checks. * [spv-in] Permit pointers to runtime arrays only in StorageBuffer. Fixes #1519. --- src/front/spv/error.rs | 2 ++ src/front/spv/mod.rs | 19 ++++++++++++++++++- tests/in/spv/shadow.spv | Bin 4764 -> 4812 bytes tests/out/ir/shadow.ron | 30 +++++++++++++++++++++++++----- 4 files changed, 45 insertions(+), 6 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 681710690..54109dd85 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -41,6 +41,8 @@ pub enum Error { UnsupportedControlFlow(spirv::Word), #[error("unsupported binary operator %{0}")] UnsupportedBinaryOperator(spirv::Word), + #[error("Naga supports OpTypeRuntimeArray in the StorageBuffer storage class only")] + UnsupportedRuntimeArrayStorageClass, #[error("unknown binary operator {0:?}")] UnknownBinaryOperator(spirv::Op), #[error("unknown relational function {0:?}")] diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 26f849bd2..fc5d2096b 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3881,7 +3881,8 @@ impl> Parser { let decor = self.future_decor.remove(&id); let base_lookup_ty = self.lookup_type.lookup(type_id)?; - let class = if let Some(class) = module.types[base_lookup_ty.handle].inner.pointer_class() { + let base_inner = &module.types[base_lookup_ty.handle].inner; + let class = if let Some(class) = base_inner.pointer_class() { class } else if self .lookup_storage_buffer_types @@ -3897,6 +3898,22 @@ impl> Parser { } }; + // We don't support pointers to runtime-sized arrays in the `Uniform` + // storage class with the `BufferBlock` decoration. Runtime-sized arrays + // should be in the StorageBuffer class. + if let crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } = *base_inner + { + match class { + crate::StorageClass::Storage { .. } => {} + _ => { + return Err(Error::UnsupportedRuntimeArrayStorageClass); + } + } + } + // Don't bother with pointer stuff for `Handle` types. let lookup_ty = if class == crate::StorageClass::Handle { base_lookup_ty.clone() diff --git a/tests/in/spv/shadow.spv b/tests/in/spv/shadow.spv index 265cf65fc08335dfb5180801283e218430a0fd67..b4dff9df6da1fbcacb844a01d1f89b9e5dbc140f 100644 GIT binary patch delta 358 zcmbQEdPdcinMs+Qfq{{Mfq|XjE|3HPK?WwU2p0o4LvTP?ythYCd~r#BQDS;(d{Svz zT51uTo1BwaT+Fah@-!2t2LlU3DoFe0mrReD6nTIw5Z4+goDQVZfEXmE0OV(Y*puI~ z$_s)-5}~3wU{P7Nct)PdwQQ(z^%= z+*m-&XyC^ QjEi6uxgfdCy`1)(03z`#`~Uy| diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 572ffe39f..13220b7ae 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -200,21 +200,33 @@ name: None, inner: Pointer( base: 19, - class: Uniform, + class: Storage( + access: ( + bits: 3, + ), + ), ), ), ( name: None, inner: Pointer( base: 18, - class: Uniform, + class: Storage( + access: ( + bits: 3, + ), + ), ), ), ( name: None, inner: Pointer( base: 17, - class: Uniform, + class: Storage( + access: ( + bits: 3, + ), + ), ), ), ( @@ -235,14 +247,22 @@ name: None, inner: Pointer( base: 4, - class: Uniform, + class: Storage( + access: ( + bits: 3, + ), + ), ), ), ( name: None, inner: Pointer( base: 1, - class: Uniform, + class: Storage( + access: ( + bits: 3, + ), + ), ), ), ( From 66c3499df8c9605bcb2267be3840d0fd3c86b351 Mon Sep 17 00:00:00 2001 From: Jay Oster Date: Sun, 14 Nov 2021 16:07:38 -0800 Subject: [PATCH 1441/2212] [spv-out] Fix scalar-times-matrix operations (#1524) --- src/back/spv/block.rs | 5 +- tests/in/operators.wgsl | 12 + tests/out/glsl/operators.main.Compute.glsl | 6 + tests/out/hlsl/operators.hlsl | 7 + tests/out/msl/operators.msl | 7 + tests/out/spv/operators.spvasm | 254 +++++++++++---------- tests/out/wgsl/operators.wgsl | 6 + 7 files changed, 176 insertions(+), 121 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index b827d157e..10e416cf1 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -346,6 +346,10 @@ impl<'w> BlockContext<'w> { (Dimension::Matrix, Dimension::Scalar { .. }) => { spirv::Op::MatrixTimesScalar } + (Dimension::Scalar, Dimension::Matrix { .. }) => { + preserve_order = false; + spirv::Op::MatrixTimesScalar + } (Dimension::Matrix, Dimension::Vector) => spirv::Op::MatrixTimesVector, (Dimension::Matrix, Dimension::Matrix) => spirv::Op::MatrixTimesMatrix, (Dimension::Vector, Dimension::Vector) @@ -356,7 +360,6 @@ impl<'w> BlockContext<'w> { } (Dimension::Vector, Dimension::Vector) | (Dimension::Scalar, Dimension::Scalar) => spirv::Op::IMul, - other => unimplemented!("Mul {:?}", other), }, crate::BinaryOperator::Divide => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) => spirv::Op::SDiv, diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 99eca092a..673bd55cd 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -57,6 +57,17 @@ fn modulo() { let d = vec3(1.0) % vec3(1.0); } +fn scalar_times_matrix() { + let model = mat4x4( + vec4(1.0, 0.0, 0.0, 0.0), + vec4(0.0, 1.0, 0.0, 0.0), + vec4(0.0, 0.0, 1.0, 0.0), + vec4(0.0, 0.0, 0.0, 1.0), + ); + + let assertion: mat4x4 = 2.0 * model; +} + [[stage(compute), workgroup_size(1)]] fn main() { let a = builtins(); @@ -65,4 +76,5 @@ fn main() { let d = bool_cast(v_f32_one.xyz); let e = constructors(); modulo(); + scalar_times_matrix(); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index ac6ecfa62..39a284352 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -56,6 +56,11 @@ void modulo() { vec3 d = (vec3(1.0) - vec3(1.0) * trunc(vec3(1.0) / vec3(1.0))); } +void scalar_times_matrix() { + mat4x4 model = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + mat4x4 assertion = (2.0 * model); +} + void main() { vec4 _e4 = builtins(); vec4 _e5 = splat(); @@ -63,6 +68,7 @@ void main() { vec3 _e8 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); float _e9 = constructors(); modulo(); + scalar_times_matrix(); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 1e35bb0a9..a359689f6 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -67,6 +67,12 @@ void modulo() float3 d = (float3(1.0.xxx) % float3(1.0.xxx)); } +void scalar_times_matrix() +{ + float4x4 model = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); + float4x4 assertion = mul(model, 2.0); +} + [numthreads(1, 1, 1)] void main() { @@ -76,5 +82,6 @@ void main() const float3 _e8 = bool_cast(float4(1.0, 1.0, 1.0, 1.0).xyz); const float _e9 = constructors(); modulo(); + scalar_times_matrix(); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 37cf121fb..f80197989 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -63,6 +63,12 @@ void modulo( metal::float3 d = metal::fmod(metal::float3(1.0), metal::float3(1.0)); } +void scalar_times_matrix( +) { + metal::float4x4 model = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); + metal::float4x4 assertion = 2.0 * model; +} + kernel void main_( ) { metal::float4 _e4 = builtins(); @@ -71,5 +77,6 @@ kernel void main_( metal::float3 _e8 = bool_cast(v_f32_one.xyz); float _e9 = constructors(); modulo(); + scalar_times_matrix(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 47aeab816..bc931da33 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 128 +; Bound: 139 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %119 "main" -OpExecutionMode %119 LocalSize 1 1 1 +OpEntryPoint GLCompute %129 "main" +OpExecutionMode %129 LocalSize 1 1 1 OpMemberDecorate %23 0 Offset 0 OpMemberDecorate %23 1 Offset 16 %2 = OpTypeVoid @@ -31,133 +31,147 @@ OpMemberDecorate %23 1 Offset 16 %21 = OpTypeVector %10 4 %22 = OpTypeVector %4 3 %23 = OpTypeStruct %19 %8 -%24 = OpConstantComposite %19 %3 %3 %3 %3 -%25 = OpConstantComposite %19 %5 %5 %5 %5 -%26 = OpConstantComposite %19 %6 %6 %6 %6 -%27 = OpConstantComposite %20 %7 %7 %7 %7 -%30 = OpTypeFunction %19 -%56 = OpTypeVector %4 2 -%72 = OpTypeFunction %8 -%79 = OpConstantNull %8 -%83 = OpTypeFunction %22 %22 -%85 = OpTypeVector %10 3 -%92 = OpTypePointer Function %23 -%95 = OpTypeFunction %4 -%99 = OpTypePointer Function %19 -%100 = OpTypePointer Function %4 -%102 = OpTypeInt 32 0 -%101 = OpConstant %102 0 -%107 = OpTypeFunction %2 -%111 = OpTypeVector %8 3 -%29 = OpFunction %19 None %30 -%28 = OpLabel -OpBranch %31 -%31 = OpLabel -%32 = OpSelect %8 %9 %7 %11 -%34 = OpCompositeConstruct %21 %9 %9 %9 %9 -%33 = OpSelect %19 %34 %24 %25 -%35 = OpCompositeConstruct %21 %12 %12 %12 %12 -%36 = OpSelect %19 %35 %25 %24 -%37 = OpExtInst %19 %1 FMix %25 %24 %26 -%39 = OpCompositeConstruct %19 %13 %13 %13 %13 -%38 = OpExtInst %19 %1 FMix %25 %24 %39 -%40 = OpCompositeExtract %8 %27 0 -%41 = OpBitcast %4 %40 -%42 = OpBitcast %19 %27 -%43 = OpConvertFToS %20 %25 -%44 = OpCompositeConstruct %20 %32 %32 %32 %32 -%45 = OpIAdd %20 %44 %43 -%46 = OpConvertSToF %19 %45 -%47 = OpFAdd %19 %46 %33 -%48 = OpFAdd %19 %47 %37 +%24 = OpTypeMatrix %19 4 +%25 = OpConstantComposite %19 %3 %3 %3 %3 +%26 = OpConstantComposite %19 %5 %5 %5 %5 +%27 = OpConstantComposite %19 %6 %6 %6 %6 +%28 = OpConstantComposite %20 %7 %7 %7 %7 +%31 = OpTypeFunction %19 +%57 = OpTypeVector %4 2 +%73 = OpTypeFunction %8 +%80 = OpConstantNull %8 +%84 = OpTypeFunction %22 %22 +%86 = OpTypeVector %10 3 +%93 = OpTypePointer Function %23 +%96 = OpTypeFunction %4 +%100 = OpTypePointer Function %19 +%101 = OpTypePointer Function %4 +%103 = OpTypeInt 32 0 +%102 = OpConstant %103 0 +%108 = OpTypeFunction %2 +%112 = OpTypeVector %8 3 +%30 = OpFunction %19 None %31 +%29 = OpLabel +OpBranch %32 +%32 = OpLabel +%33 = OpSelect %8 %9 %7 %11 +%35 = OpCompositeConstruct %21 %9 %9 %9 %9 +%34 = OpSelect %19 %35 %25 %26 +%36 = OpCompositeConstruct %21 %12 %12 %12 %12 +%37 = OpSelect %19 %36 %26 %25 +%38 = OpExtInst %19 %1 FMix %26 %25 %27 +%40 = OpCompositeConstruct %19 %13 %13 %13 %13 +%39 = OpExtInst %19 %1 FMix %26 %25 %40 +%41 = OpCompositeExtract %8 %28 0 +%42 = OpBitcast %4 %41 +%43 = OpBitcast %19 %28 +%44 = OpConvertFToS %20 %26 +%45 = OpCompositeConstruct %20 %33 %33 %33 %33 +%46 = OpIAdd %20 %45 %44 +%47 = OpConvertSToF %19 %46 +%48 = OpFAdd %19 %47 %34 %49 = OpFAdd %19 %48 %38 -%50 = OpCompositeConstruct %19 %41 %41 %41 %41 -%51 = OpFAdd %19 %49 %50 -%52 = OpFAdd %19 %51 %42 -OpReturnValue %52 +%50 = OpFAdd %19 %49 %39 +%51 = OpCompositeConstruct %19 %42 %42 %42 %42 +%52 = OpFAdd %19 %50 %51 +%53 = OpFAdd %19 %52 %43 +OpReturnValue %53 OpFunctionEnd -%54 = OpFunction %19 None %30 -%53 = OpLabel -OpBranch %55 -%55 = OpLabel -%57 = OpCompositeConstruct %56 %14 %14 -%58 = OpCompositeConstruct %56 %3 %3 -%59 = OpFAdd %56 %58 %57 -%60 = OpCompositeConstruct %56 %15 %15 -%61 = OpFSub %56 %59 %60 -%62 = OpCompositeConstruct %56 %16 %16 -%63 = OpFDiv %56 %61 %62 -%64 = OpCompositeConstruct %20 %17 %17 %17 %17 -%65 = OpCompositeConstruct %20 %18 %18 %18 %18 -%66 = OpSMod %20 %64 %65 -%67 = OpVectorShuffle %19 %63 %63 0 1 0 1 -%68 = OpConvertSToF %19 %66 -%69 = OpFAdd %19 %67 %68 -OpReturnValue %69 +%55 = OpFunction %19 None %31 +%54 = OpLabel +OpBranch %56 +%56 = OpLabel +%58 = OpCompositeConstruct %57 %14 %14 +%59 = OpCompositeConstruct %57 %3 %3 +%60 = OpFAdd %57 %59 %58 +%61 = OpCompositeConstruct %57 %15 %15 +%62 = OpFSub %57 %60 %61 +%63 = OpCompositeConstruct %57 %16 %16 +%64 = OpFDiv %57 %62 %63 +%65 = OpCompositeConstruct %20 %17 %17 %17 %17 +%66 = OpCompositeConstruct %20 %18 %18 %18 %18 +%67 = OpSMod %20 %65 %66 +%68 = OpVectorShuffle %19 %64 %64 0 1 0 1 +%69 = OpConvertSToF %19 %67 +%70 = OpFAdd %19 %68 %69 +OpReturnValue %70 OpFunctionEnd -%71 = OpFunction %8 None %72 -%70 = OpLabel -OpBranch %73 -%73 = OpLabel -%74 = OpLogicalNot %10 %9 -OpSelectionMerge %75 None -OpBranchConditional %74 %76 %77 -%76 = OpLabel -OpReturnValue %7 +%72 = OpFunction %8 None %73 +%71 = OpLabel +OpBranch %74 +%74 = OpLabel +%75 = OpLogicalNot %10 %9 +OpSelectionMerge %76 None +OpBranchConditional %75 %77 %78 %77 = OpLabel -%78 = OpNot %8 %7 -OpReturnValue %78 -%75 = OpLabel +OpReturnValue %7 +%78 = OpLabel +%79 = OpNot %8 %7 OpReturnValue %79 +%76 = OpLabel +OpReturnValue %80 OpFunctionEnd -%82 = OpFunction %22 None %83 -%81 = OpFunctionParameter %22 -%80 = OpLabel -OpBranch %84 -%84 = OpLabel -%86 = OpCompositeConstruct %22 %5 %5 %5 -%87 = OpFUnordNotEqual %85 %81 %86 -%88 = OpCompositeConstruct %22 %5 %5 %5 -%89 = OpCompositeConstruct %22 %3 %3 %3 -%90 = OpSelect %22 %87 %89 %88 -OpReturnValue %90 +%83 = OpFunction %22 None %84 +%82 = OpFunctionParameter %22 +%81 = OpLabel +OpBranch %85 +%85 = OpLabel +%87 = OpCompositeConstruct %22 %5 %5 %5 +%88 = OpFUnordNotEqual %86 %82 %87 +%89 = OpCompositeConstruct %22 %5 %5 %5 +%90 = OpCompositeConstruct %22 %3 %3 %3 +%91 = OpSelect %22 %88 %90 %89 +OpReturnValue %91 OpFunctionEnd -%94 = OpFunction %4 None %95 -%93 = OpLabel -%91 = OpVariable %92 Function -OpBranch %96 -%96 = OpLabel -%97 = OpCompositeConstruct %19 %3 %3 %3 %3 -%98 = OpCompositeConstruct %23 %97 %7 -OpStore %91 %98 -%103 = OpAccessChain %100 %91 %101 %101 -%104 = OpLoad %4 %103 -OpReturnValue %104 +%95 = OpFunction %4 None %96 +%94 = OpLabel +%92 = OpVariable %93 Function +OpBranch %97 +%97 = OpLabel +%98 = OpCompositeConstruct %19 %3 %3 %3 %3 +%99 = OpCompositeConstruct %23 %98 %7 +OpStore %92 %99 +%104 = OpAccessChain %101 %92 %102 %102 +%105 = OpLoad %4 %104 +OpReturnValue %105 OpFunctionEnd -%106 = OpFunction %2 None %107 -%105 = OpLabel -OpBranch %108 -%108 = OpLabel -%109 = OpSMod %8 %7 %7 -%110 = OpFMod %4 %3 %3 -%112 = OpCompositeConstruct %111 %7 %7 %7 -%113 = OpCompositeConstruct %111 %7 %7 %7 -%114 = OpSMod %111 %112 %113 -%115 = OpCompositeConstruct %22 %3 %3 %3 +%107 = OpFunction %2 None %108 +%106 = OpLabel +OpBranch %109 +%109 = OpLabel +%110 = OpSMod %8 %7 %7 +%111 = OpFMod %4 %3 %3 +%113 = OpCompositeConstruct %112 %7 %7 %7 +%114 = OpCompositeConstruct %112 %7 %7 %7 +%115 = OpSMod %112 %113 %114 %116 = OpCompositeConstruct %22 %3 %3 %3 -%117 = OpFMod %22 %115 %116 +%117 = OpCompositeConstruct %22 %3 %3 %3 +%118 = OpFMod %22 %116 %117 OpReturn OpFunctionEnd -%119 = OpFunction %2 None %107 -%118 = OpLabel -OpBranch %120 -%120 = OpLabel -%121 = OpFunctionCall %19 %29 -%122 = OpFunctionCall %19 %54 -%123 = OpFunctionCall %8 %71 -%124 = OpVectorShuffle %22 %24 %24 0 1 2 -%125 = OpFunctionCall %22 %82 %124 -%126 = OpFunctionCall %4 %94 -%127 = OpFunctionCall %2 %106 +%120 = OpFunction %2 None %108 +%119 = OpLabel +OpBranch %121 +%121 = OpLabel +%122 = OpCompositeConstruct %19 %3 %5 %5 %5 +%123 = OpCompositeConstruct %19 %5 %3 %5 %5 +%124 = OpCompositeConstruct %19 %5 %5 %3 %5 +%125 = OpCompositeConstruct %19 %5 %5 %5 %3 +%126 = OpCompositeConstruct %24 %122 %123 %124 %125 +%127 = OpMatrixTimesScalar %24 %126 %14 +OpReturn +OpFunctionEnd +%129 = OpFunction %2 None %108 +%128 = OpLabel +OpBranch %130 +%130 = OpLabel +%131 = OpFunctionCall %19 %30 +%132 = OpFunctionCall %19 %55 +%133 = OpFunctionCall %8 %72 +%134 = OpVectorShuffle %22 %25 %25 0 1 2 +%135 = OpFunctionCall %22 %83 %134 +%136 = OpFunctionCall %4 %95 +%137 = OpFunctionCall %2 %107 +%138 = OpFunctionCall %2 %120 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 17985a6c1..5c8b43a7c 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -53,6 +53,11 @@ fn modulo() { let d: vec3 = (vec3(1.0) % vec3(1.0)); } +fn scalar_times_matrix() { + let model: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + let assertion: mat4x4 = (2.0 * model); +} + [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { let e4: vec4 = builtins(); @@ -61,5 +66,6 @@ fn main() { let e8: vec3 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); let e9: f32 = constructors(); modulo(); + scalar_times_matrix(); return; } From 1dcde48d09245b81cc08b15b13a14281f75f7a0e Mon Sep 17 00:00:00 2001 From: Boris-Chengbiao Zhou Date: Mon, 15 Nov 2021 01:07:55 +0100 Subject: [PATCH 1442/2212] [valid] Check that switches have a default case (#1529) From the WGSL spec: "Each switch statement must have exactly one default clause." --- src/valid/function.rs | 6 ++++++ tests/in/control-flow.wgsl | 4 ++++ tests/out/glsl/control-flow.main.Compute.glsl | 6 ++++++ tests/out/hlsl/control-flow.hlsl | 9 +++++++++ tests/out/msl/control-flow.msl | 9 +++++++++ tests/out/wgsl/control-flow.wgsl | 6 ++++++ tests/wgsl-errors.rs | 20 +++++++++++++++++++ 7 files changed, 60 insertions(+) diff --git a/src/valid/function.rs b/src/valid/function.rs index 34c833db0..053b2d82d 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -106,6 +106,8 @@ pub enum FunctionError { InvalidSwitchType(Handle), #[error("Multiple `switch` cases for {0:?} are present")] ConflictingSwitchCase(i32), + #[error("The `switch` is missing a `default` case")] + MissingDefaultCase, #[error("Multiple `default` cases are present")] MultipleDefaultCases, #[error("The last `switch` case contains a `falltrough`")] @@ -471,6 +473,10 @@ impl super::Validator { } } } + if !default { + return Err(FunctionError::MissingDefaultCase + .with_span_static(span, "missing default case")); + } if let Some(case) = cases.last() { if case.fall_through { return Err(FunctionError::LastCaseFallTrough.with_span_static( diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index 5ca59817c..e875d63e8 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -36,6 +36,8 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { switch(0u) { case 0u: { } + default: { + } } // non-empty switch in last-statement-in-function position @@ -71,6 +73,7 @@ fn switch_case_break() { case 0: { break; } + default: {} } return; } @@ -81,6 +84,7 @@ fn loop_switch_continue(x: i32) { case 1: { continue; } + default: {} } } } diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index 2e5673b1d..dd0224e43 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -17,6 +17,8 @@ void switch_case_break() { switch(0) { case 0: break; + default: + break; } return; } @@ -26,6 +28,8 @@ void loop_switch_continue(int x) { switch(x) { case 1: continue; + default: + break; } } return; @@ -61,6 +65,8 @@ void main() { switch(0u) { case 0u: break; + default: + break; } int _e10 = pos; switch(_e10) { diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index 7922462e9..e65dbc75f 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -14,6 +14,9 @@ void switch_case_break() case 0: { break; } + default: { + break; + } } return; } @@ -25,6 +28,9 @@ void loop_switch_continue(int x) case 1: { continue; } + default: { + break; + } } } return; @@ -71,6 +77,9 @@ void main(uint3 global_id : SV_DispatchThreadID) case 0u: { break; } + default: { + break; + } } int _expr10 = pos; switch(_expr10) { diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index 8c3780024..bed973ead 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -19,6 +19,9 @@ void switch_case_break( case 0: { break; } + default: { + break; + } } return; } @@ -31,6 +34,9 @@ void loop_switch_continue( case 1: { continue; } + default: { + break; + } } } return; @@ -75,6 +81,9 @@ kernel void main_( case 0u: { break; } + default: { + break; + } } int _e10 = pos; switch(_e10) { diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index cdb3fc53c..a8824673f 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -11,6 +11,8 @@ fn switch_case_break() { case 0: { break; } + default: { + } } return; } @@ -21,6 +23,8 @@ fn loop_switch_continue(x: i32) { case 1: { continue; } + default: { + } } } return; @@ -59,6 +63,8 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { switch(0u) { case 0u: { } + default: { + } } let e10: i32 = pos; switch(e10) { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 4bf6b557a..2d1e0f79f 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -995,6 +995,7 @@ fn last_case_falltrough() { " fn test_falltrough() { switch(0) { + default: {} case 0: { fallthrough; } @@ -1009,3 +1010,22 @@ fn last_case_falltrough() { ) } } + +#[test] +fn missing_default_case() { + check_validation_error! { + " + fn test_missing_default_case() { + switch(0) { + case 0: {} + } + } + ": + Err( + naga::valid::ValidationError::Function { + error: naga::valid::FunctionError::MissingDefaultCase, + .. + }, + ) + } +} From 90daa9edfe9468db96ee6444395b71ea225465fc Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 14 Nov 2021 12:05:29 -0800 Subject: [PATCH 1443/2212] Forbid specializable constants as array lengths. Only the SPIR-V front end can produce such array types, and it seems that our back ends don't support this case well. --- src/valid/type.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/valid/type.rs b/src/valid/type.rs index a180831df..c052fa9b2 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -89,6 +89,8 @@ pub enum TypeError { InvalidArrayBaseType(Handle), #[error("The constant {0:?} can not be used for an array size")] InvalidArraySizeConstant(Handle), + #[error("The constant {0:?} is specialized, and cannot be used as an array size")] + UnsupportedSpecializedArrayLength(Handle), #[error("Array type {0:?} must have a length of one or more")] NonPositiveArrayLength(Handle), #[error("Array stride {stride} is smaller than the base element size {base_size}")] @@ -350,6 +352,19 @@ impl super::Validator { let sized_flag = match size { crate::ArraySize::Constant(const_handle) => { let length_is_positive = match constants.try_get(const_handle) { + Some(&crate::Constant { + specialization: Some(_), + .. + }) => { + // Many of our back ends don't seem to support + // specializable array lengths. If you want to try to make + // this work, be sure to address all uses of + // `Constant::to_array_length`, which ignores + // specialization. + return Err(TypeError::UnsupportedSpecializedArrayLength( + const_handle, + )); + } Some(&crate::Constant { inner: crate::ConstantInner::Scalar { From 3d6cbcf8a60eba97f6f2ddd4205a964ad4d458f7 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 14 Nov 2021 12:20:27 -0800 Subject: [PATCH 1444/2212] Remove IndexableLength::Specializable variant. Specializable constants are no longer permitted as array lengths, so this case should not arise in valid code. --- src/back/spv/index.rs | 4 ---- src/proc/index.rs | 10 +++++----- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 0fc4c3ffe..30ac58472 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -109,10 +109,6 @@ impl<'w> BlockContext<'w> { let length_id = self.write_runtime_array_length(sequence, block)?; Ok(MaybeKnown::Computed(length_id)) } - crate::proc::IndexableLength::Specializable(constant) => { - let length_id = self.writer.constant_ids[constant.index()]; - Ok(MaybeKnown::Computed(length_id)) - } } } diff --git a/src/proc/index.rs b/src/proc/index.rs index 69dd6c2bb..b6dd1e4b5 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -49,10 +49,6 @@ pub enum IndexableLength { /// Values of this type always have the given number of elements. Known(u32), - /// The value of the given specializable constant is the number of elements. - /// (Non-specializable constants are reported as `Known`.) - Specializable(crate::Handle), - /// The number of elements is determined at runtime. Dynamic, } @@ -65,7 +61,11 @@ impl crate::ArraySize { K { specialization: Some(_), .. - } => IndexableLength::Specializable(k), + } => { + // Specializable constants are not supported as array lengths. + // See valid::TypeError::UnsupportedSpecializedArrayLength. + return Err(ProcError::InvalidArraySizeConstant(k)); + } ref unspecialized => { let length = unspecialized .to_array_length() From ce18eba695530d6a03487b9692490f0190106f63 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 15 Nov 2021 22:46:00 -0800 Subject: [PATCH 1445/2212] Check that stores are permitted by the pointer's storage access. Fixes #1533. --- src/proc/mod.rs | 15 +++++++++ src/valid/function.rs | 18 +++++++++-- tests/in/bounds-check-zero.wgsl | 2 +- tests/out/spv/bounds-check-zero.spvasm | 1 - tests/wgsl-errors.rs | 42 ++++++++++++++++++++++++++ 5 files changed, 73 insertions(+), 5 deletions(-) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c9a66585c..4c906f6ee 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -184,6 +184,21 @@ impl super::TypeInner { } } +impl super::StorageClass { + pub fn access(self) -> crate::StorageAccess { + use crate::StorageAccess as Sa; + match self { + crate::StorageClass::Function + | crate::StorageClass::Private + | crate::StorageClass::WorkGroup => Sa::LOAD | Sa::STORE, + crate::StorageClass::Uniform => Sa::LOAD, + crate::StorageClass::Storage { access } => access, + crate::StorageClass::Handle => Sa::LOAD, + crate::StorageClass::PushConstant => Sa::LOAD, + } + } +} + impl super::MathFunction { pub fn argument_count(&self) -> usize { match *self { diff --git a/src/valid/function.rs b/src/valid/function.rs index 053b2d82d..c2f3cf97c 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -606,10 +606,12 @@ impl super::Validator { } _ => {} } - let good = match *context + + let pointer_ty = context .resolve_pointer_type(pointer) - .map_err(|e| e.with_span())? - { + .map_err(|e| e.with_span())?; + + let good = match *pointer_ty { Ti::Pointer { base, class: _ } => match context.types[base].inner { Ti::Atomic { kind, width } => *value_ty == Ti::Scalar { kind, width }, ref other => value_ty == other, @@ -634,6 +636,16 @@ impl super::Validator { .with_handle(pointer, context.expressions) .with_handle(value, context.expressions)); } + + if let Some(class) = pointer_ty.pointer_class() { + if !class.access().contains(crate::StorageAccess::STORE) { + return Err(FunctionError::InvalidStorePointer(pointer) + .with_span_static( + context.expressions.get_span(pointer), + "writing to this location is not permitted", + )); + } + } } S::ImageStore { image, diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl index 74811c12b..51602cbd6 100644 --- a/tests/in/bounds-check-zero.wgsl +++ b/tests/in/bounds-check-zero.wgsl @@ -7,7 +7,7 @@ struct Globals { m: mat3x4; }; -[[group(0), binding(0)]] var globals: Globals; +[[group(0), binding(0)]] var globals: Globals; fn index_array(i: i32) -> f32 { return globals.a[i]; diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index 156954c8a..eb3a2da42 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -14,7 +14,6 @@ OpMemberDecorate %9 1 Offset 48 OpMemberDecorate %9 2 Offset 64 OpMemberDecorate %9 2 ColMajor OpMemberDecorate %9 2 MatrixStride 16 -OpDecorate %10 NonWritable OpDecorate %10 DescriptorSet 0 OpDecorate %10 Binding 0 %2 = OpTypeVoid diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 2d1e0f79f..c85c113db 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1029,3 +1029,45 @@ fn missing_default_case() { ) } } + +#[test] +fn wrong_access_mode() { + // The assignments to `global.i` should be forbidden, because they are in + // variables whose access mode is `read`, not `read_write`. + check_validation_error! { + " + [[block]] + struct Globals { + i: i32; + }; + + [[group(0), binding(0)]] + var globals: Globals; + + fn store(v: i32) { + globals.i = v; + } + ", + " + [[block]] + struct Globals { + i: i32; + }; + + [[group(0), binding(0)]] + var globals: Globals; + + fn store(v: i32) { + globals.i = v; + } + ": + Err( + naga::valid::ValidationError::Function { + name, + error: naga::valid::FunctionError::InvalidStorePointer(_), + .. + }, + ) + if name == "store" + } +} From 30a0a37af0028f1cf489f9973065e63fc3c82046 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 16 Nov 2021 17:17:51 +0300 Subject: [PATCH 1446/2212] Update dependencies --- Cargo.toml | 6 +++--- tests/snapshots.rs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index eb2a84a4d..7e73d021c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,11 +49,11 @@ validate = [] [dev-dependencies] diff = "0.1" -ron = "0.6" +ron = "0.7" serde = { version = "1.0", features = ["derive"] } spirv = { version = "0.2", features = ["deserialize"] } -rspirv = "0.10" -env_logger = "0.8" +rspirv = "0.11" +env_logger = "0.9" [workspace] members = [".", "cli"] diff --git a/tests/snapshots.rs b/tests/snapshots.rs index c513dbb82..159e36c57 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -125,7 +125,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "serialize")] { if targets.contains(Targets::IR) { - let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); + let config = ron::ser::PrettyConfig::default().new_line("\n".to_string()); let string = ron::ser::to_string_pretty(module, config).unwrap(); fs::write(dest.join(format!("ir/{}.ron", name)), string).unwrap(); } @@ -138,7 +138,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "serialize")] { if targets.contains(Targets::ANALYSIS) { - let config = ron::ser::PrettyConfig::default().with_new_line("\n".to_string()); + let config = ron::ser::PrettyConfig::default().new_line("\n".to_string()); let string = ron::ser::to_string_pretty(&info, config).unwrap(); fs::write(dest.join(format!("analysis/{}.info.ron", name)), string).unwrap(); } From 38366e382fe95205644af460cc3af7d180ef3f63 Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Tue, 16 Nov 2021 17:06:00 +0100 Subject: [PATCH 1447/2212] Switch to rustc-hash See gfx-rs/rspirv#221 for the rationale behind this change --- Cargo.toml | 2 +- src/front/spv/mod.rs | 2 +- src/lib.rs | 9 ++------- 3 files changed, 4 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7e73d021c..44a7eaf7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ all-features = true bitflags = "1" bit-set = "0.5" codespan-reporting = { version = "0.11.0", optional = true } -fxhash = "0.2" +rustc-hash = "1.1.0" indexmap = "1.6" # 1.7 has MSRV 1.49 log = "0.4" num-traits = "0.2" diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index fc5d2096b..55a5691de 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -547,7 +547,7 @@ pub struct Parser { switch_cases: indexmap::IndexMap< spirv::Word, (BodyIndex, Vec), - std::hash::BuildHasherDefault, + std::hash::BuildHasherDefault, >, /// Tracks usage of builtins, used to cull unused builtins since they can diff --git a/src/lib.rs b/src/lib.rs index 6cda40f21..05506190e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -215,11 +215,6 @@ pub mod valid; pub use crate::arena::{Arena, Handle, Range, UniqueArena}; -use std::{ - collections::{HashMap, HashSet}, - hash::BuildHasherDefault, -}; - pub use crate::span::{Span, SpanContext, WithSpan}; #[cfg(feature = "deserialize")] use serde::Deserialize; @@ -230,9 +225,9 @@ use serde::Serialize; pub const BOOL_WIDTH: Bytes = 1; /// Hash map that is faster but not resilient to DoS attacks. -pub type FastHashMap = HashMap>; +pub type FastHashMap = rustc_hash::FxHashMap; /// Hash set that is faster but not resilient to DoS attacks. -pub type FastHashSet = HashSet>; +pub type FastHashSet = rustc_hash::FxHashSet; /// Map of expressions that have associated variable names pub(crate) type NamedExpressions = FastHashMap, String>; From 6a5b33fa2493022f0b51f5d1f5d10565247dedf6 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 17 Nov 2021 19:15:59 -0800 Subject: [PATCH 1448/2212] Move `BoundsCheckPolicy`/`Policies` into `proc`, from `back`. (#1537) --- cli/src/main.rs | 6 +- src/back/mod.rs | 111 ---------------------------------- src/back/spv/image.rs | 12 ++-- src/back/spv/index.rs | 23 ++----- src/back/spv/mod.rs | 5 +- src/proc/index.rs | 136 ++++++++++++++++++++++++++++++++++++++++++ src/proc/mod.rs | 2 +- tests/snapshots.rs | 4 +- 8 files changed, 157 insertions(+), 142 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 4330d882d..5f5d59f22 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -71,13 +71,13 @@ struct Args { /// Newtype so we can implement [`FromStr`] for `BoundsCheckPolicy`. #[derive(Debug, Clone, Copy)] -struct BoundsCheckPolicyArg(naga::back::BoundsCheckPolicy); +struct BoundsCheckPolicyArg(naga::proc::BoundsCheckPolicy); impl FromStr for BoundsCheckPolicyArg { type Err = String; fn from_str(s: &str) -> Result { - use naga::back::BoundsCheckPolicy; + use naga::proc::BoundsCheckPolicy; Ok(Self(match s.to_lowercase().as_str() { "restrict" => BoundsCheckPolicy::Restrict, "readzeroskipwrite" => BoundsCheckPolicy::ReadZeroSkipWrite, @@ -132,7 +132,7 @@ impl FromStr for GlslProfileArg { #[derive(Default)] struct Parameters { validation_flags: naga::valid::ValidationFlags, - bounds_check_policies: naga::back::BoundsCheckPolicies, + bounds_check_policies: naga::proc::BoundsCheckPolicies, entry_point: Option, keep_coordinate_space: bool, spv_block_ctx_dump_prefix: Option, diff --git a/src/back/mod.rs b/src/back/mod.rs index d2ebce38b..571289a79 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -123,117 +123,6 @@ impl<'a> FunctionCtx<'_> { } } -/// How should code generated by Naga do bounds checks? -/// -/// When a vector, matrix, or array index is out of bounds—either negative, or -/// greater than or equal to the number of elements in the type—WGSL requires -/// that some other index of the implementation's choice that is in bounds is -/// used instead. (There are no types with zero elements.) -/// -/// Similarly, when out-of-bounds coordinates, array indices, or sample indices -/// are presented to the WGSL `textureLoad` and `textureStore` operations, the -/// operation is redirected to do something safe. -/// -/// Different users of Naga will prefer different defaults: -/// -/// - When used as part of a WebGPU implementation, the WGSL specification -/// requires the `Restrict` behavior for array, vector, and matrix accesses, -/// and either the `Restrict` or `ReadZeroSkipWrite` behaviors for texture -/// accesses. -/// -/// - When used by the `wgpu` crate for native development, `wgpu` selects -/// `ReadZeroSkipWrite` as its default. -/// -/// - Naga's own default is `Unchanged`, so that shader translations -/// are as faithful to the original as possible. -/// -/// Sometimes the underlying hardware and drivers can perform bounds checks -/// themselves, in a way that performs better than the checks Naga would inject. -/// If you're using native checks like this, then having Naga inject its own -/// checks as well would be redundant, and the `Unchecked` policy is -/// appropriate. -#[derive(Clone, Copy, Debug)] -pub enum BoundsCheckPolicy { - /// Replace out-of-bounds indexes with some arbitrary in-bounds index. - /// - /// (This does not necessarily mean clamping. For example, interpreting the - /// index as unsigned and taking the minimum with the largest valid index - /// would also be a valid implementation. That would map negative indices to - /// the last element, not the first.) - Restrict, - - /// Out-of-bounds reads return zero, and writes have no effect. - ReadZeroSkipWrite, - - /// Naga adds no checks to indexing operations. Generate the fastest code - /// possible. This is the default for Naga, as a translator, but consumers - /// should consider defaulting to a safer behavior. - Unchecked, -} - -#[derive(Clone, Copy, Debug, Default)] -/// Policies for injecting bounds checks during code generation. -/// -/// For SPIR-V generation, see [`spv::Options::bounds_check_policies`]. -pub struct BoundsCheckPolicies { - /// How should the generated code handle array, vector, or matrix indices - /// that are out of range? - pub index: BoundsCheckPolicy, - - /// How should the generated code handle array, vector, or matrix indices - /// that are out of range, when those values live in a [`GlobalVariable`] in - /// the [`Storage`] or [`Uniform`] storage classes? - /// - /// Some graphics hardware provides "robust buffer access", a feature that - /// ensures that using a pointer cannot access memory outside the 'buffer' - /// that it was derived from. In Naga terms, this means that the hardware - /// ensures that pointers computed by applying [`Access`] and - /// [`AccessIndex`] expressions to a [`GlobalVariable`] whose [`class`] is - /// [`Storage`] or [`Uniform`] will never read or write memory outside that - /// global variable. - /// - /// When hardware offers such a feature, it is probably undesirable to have - /// Naga inject bounds checking code for such accesses, since the hardware - /// can probably provide the same protection more efficiently. However, - /// bounds checks are still needed on accesses to indexable values that do - /// not live in buffers, like local variables. - /// - /// So, this option provides a separate policy that applies only to accesses - /// to storage and uniform globals. When depending on hardware bounds - /// checking, this policy can be `Unchecked` to avoid unnecessary overhead. - /// - /// When special hardware support is not available, this should probably be - /// the same as `index_bounds_check_policy`. - /// - /// [`GlobalVariable`]: crate::GlobalVariable - /// [`class`]: crate::GlobalVariable::class - /// [`Restrict`]: crate::back::BoundsCheckPolicy::Restrict - /// [`ReadZeroSkipWrite`]: crate::back::BoundsCheckPolicy::ReadZeroSkipWrite - /// [`Access`]: crate::Expression::Access - /// [`AccessIndex`]: crate::Expression::AccessIndex - /// [`Storage`]: crate::StorageClass::Storage - /// [`Uniform`]: crate::StorageClass::Uniform - pub buffer: BoundsCheckPolicy, - - /// How should the generated code handle image texel references that are out - /// of range? - /// - /// This controls the behavior of [`ImageLoad`] expressions and - /// [`ImageStore`] statements when a coordinate, texture array index, level - /// of detail, or multisampled sample number is out of range. - /// - /// [`ImageLoad`]: crate::Expression::ImageLoad - /// [`ImageStore`]: crate::Statement::ImageStore - pub image: BoundsCheckPolicy, -} - -/// The default `BoundsCheckPolicy` is `Unchecked`. -impl Default for BoundsCheckPolicy { - fn default() -> Self { - BoundsCheckPolicy::Unchecked - } -} - impl crate::Expression { /// Returns the ref count, upon reaching which this expression /// should be considered for baking. diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 5966ee0ef..442045ed2 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -739,7 +739,7 @@ impl<'w> BlockContext<'w> { // Perform the access, according to the bounds check policy. let access_id = match self.writer.bounds_check_policies.image { - crate::back::BoundsCheckPolicy::Restrict => { + crate::proc::BoundsCheckPolicy::Restrict => { let (coords, level_id, sample_id) = self.write_restricted_coordinates( image_id, coordinates, @@ -749,7 +749,7 @@ impl<'w> BlockContext<'w> { )?; access.generate(&mut self.writer.id_gen, coords, level_id, sample_id, block) } - crate::back::BoundsCheckPolicy::ReadZeroSkipWrite => self + crate::proc::BoundsCheckPolicy::ReadZeroSkipWrite => self .write_conditional_image_access( image_id, coordinates, @@ -758,7 +758,7 @@ impl<'w> BlockContext<'w> { block, &access, )?, - crate::back::BoundsCheckPolicy::Unchecked => access.generate( + crate::proc::BoundsCheckPolicy::Unchecked => access.generate( &mut self.writer.id_gen, coordinates.value_id, level_id, @@ -1131,12 +1131,12 @@ impl<'w> BlockContext<'w> { let write = Store { image_id, value_id }; match self.writer.bounds_check_policies.image { - crate::back::BoundsCheckPolicy::Restrict => { + crate::proc::BoundsCheckPolicy::Restrict => { let (coords, _, _) = self.write_restricted_coordinates(image_id, coordinates, None, None, block)?; write.generate(&mut self.writer.id_gen, coords, None, None, block); } - crate::back::BoundsCheckPolicy::ReadZeroSkipWrite => { + crate::proc::BoundsCheckPolicy::ReadZeroSkipWrite => { self.write_conditional_image_access( image_id, coordinates, @@ -1146,7 +1146,7 @@ impl<'w> BlockContext<'w> { &write, )?; } - crate::back::BoundsCheckPolicy::Unchecked => { + crate::proc::BoundsCheckPolicy::Unchecked => { write.generate( &mut self.writer.id_gen, coordinates.value_id, diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 30ac58472..bd6619762 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -1,7 +1,7 @@ //! Bounds-checking for SPIR-V output. use super::{selection::Selection, Block, BlockContext, Error, IdGenerator, Instruction, Word}; -use crate::{arena::Handle, back::BoundsCheckPolicy}; +use crate::{arena::Handle, proc::BoundsCheckPolicy}; /// The results of emitting code for a left-hand-side expression. /// @@ -342,22 +342,11 @@ impl<'w> BlockContext<'w> { index: Handle, block: &mut Block, ) -> Result { - // Should this access be covered by `index_bounds_check_policy` or - // `buffer_bounds_check_policy`? - let is_buffer = match *self.fun_info[base].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Pointer { class, .. } - | crate::TypeInner::ValuePointer { class, .. } => match class { - crate::StorageClass::Storage { access: _ } | crate::StorageClass::Uniform => true, - _ => false, - }, - _ => false, - }; - - let policy = if is_buffer { - self.writer.bounds_check_policies.buffer - } else { - self.writer.bounds_check_policies.index - }; + let policy = self.writer.bounds_check_policies.choose_policy( + base, + &self.ir_module.types, + self.fun_info, + ); Ok(match policy { BoundsCheckPolicy::Restrict => self.write_restricted_index(base, index, block)?, diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 4eb75706b..d341e8df2 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -13,7 +13,8 @@ mod writer; pub use spirv::Capability; -use crate::{arena::Handle, back::BoundsCheckPolicies, proc::TypeResolution}; +use crate::arena::Handle; +use crate::proc::{BoundsCheckPolicies, TypeResolution}; use spirv::Word; use std::ops; @@ -604,7 +605,7 @@ impl Default for Options { lang_version: (1, 0), flags, capabilities: None, - bounds_check_policies: super::BoundsCheckPolicies::default(), + bounds_check_policies: crate::proc::BoundsCheckPolicies::default(), } } } diff --git a/src/proc/index.rs b/src/proc/index.rs index b6dd1e4b5..080be03cb 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -1,6 +1,142 @@ //! Definitions for index bounds checking. use super::ProcError; +use crate::valid; +use crate::{Handle, UniqueArena}; + +/// How should code generated by Naga do bounds checks? +/// +/// When a vector, matrix, or array index is out of bounds—either negative, or +/// greater than or equal to the number of elements in the type—WGSL requires +/// that some other index of the implementation's choice that is in bounds is +/// used instead. (There are no types with zero elements.) +/// +/// Similarly, when out-of-bounds coordinates, array indices, or sample indices +/// are presented to the WGSL `textureLoad` and `textureStore` operations, the +/// operation is redirected to do something safe. +/// +/// Different users of Naga will prefer different defaults: +/// +/// - When used as part of a WebGPU implementation, the WGSL specification +/// requires the `Restrict` behavior for array, vector, and matrix accesses, +/// and either the `Restrict` or `ReadZeroSkipWrite` behaviors for texture +/// accesses. +/// +/// - When used by the `wgpu` crate for native development, `wgpu` selects +/// `ReadZeroSkipWrite` as its default. +/// +/// - Naga's own default is `Unchecked`, so that shader translations +/// are as faithful to the original as possible. +/// +/// Sometimes the underlying hardware and drivers can perform bounds checks +/// themselves, in a way that performs better than the checks Naga would inject. +/// If you're using native checks like this, then having Naga inject its own +/// checks as well would be redundant, and the `Unchecked` policy is +/// appropriate. +#[derive(Clone, Copy, Debug)] +pub enum BoundsCheckPolicy { + /// Replace out-of-bounds indexes with some arbitrary in-bounds index. + /// + /// (This does not necessarily mean clamping. For example, interpreting the + /// index as unsigned and taking the minimum with the largest valid index + /// would also be a valid implementation. That would map negative indices to + /// the last element, not the first.) + Restrict, + + /// Out-of-bounds reads return zero, and writes have no effect. + ReadZeroSkipWrite, + + /// Naga adds no checks to indexing operations. Generate the fastest code + /// possible. This is the default for Naga, as a translator, but consumers + /// should consider defaulting to a safer behavior. + Unchecked, +} + +#[derive(Clone, Copy, Debug, Default)] +/// Policies for injecting bounds checks during code generation. +pub struct BoundsCheckPolicies { + /// How should the generated code handle array, vector, or matrix indices + /// that are out of range? + pub index: BoundsCheckPolicy, + + /// How should the generated code handle array, vector, or matrix indices + /// that are out of range, when those values live in a [`GlobalVariable`] in + /// the [`Storage`] or [`Uniform`] storage classes? + /// + /// Some graphics hardware provides "robust buffer access", a feature that + /// ensures that using a pointer cannot access memory outside the 'buffer' + /// that it was derived from. In Naga terms, this means that the hardware + /// ensures that pointers computed by applying [`Access`] and + /// [`AccessIndex`] expressions to a [`GlobalVariable`] whose [`class`] is + /// [`Storage`] or [`Uniform`] will never read or write memory outside that + /// global variable. + /// + /// When hardware offers such a feature, it is probably undesirable to have + /// Naga inject bounds checking code for such accesses, since the hardware + /// can probably provide the same protection more efficiently. However, + /// bounds checks are still needed on accesses to indexable values that do + /// not live in buffers, like local variables. + /// + /// So, this option provides a separate policy that applies only to accesses + /// to storage and uniform globals. When depending on hardware bounds + /// checking, this policy can be `Unchecked` to avoid unnecessary overhead. + /// + /// When special hardware support is not available, this should probably be + /// the same as `index_bounds_check_policy`. + /// + /// [`GlobalVariable`]: crate::GlobalVariable + /// [`class`]: crate::GlobalVariable::class + /// [`Restrict`]: crate::back::BoundsCheckPolicy::Restrict + /// [`ReadZeroSkipWrite`]: crate::back::BoundsCheckPolicy::ReadZeroSkipWrite + /// [`Access`]: crate::Expression::Access + /// [`AccessIndex`]: crate::Expression::AccessIndex + /// [`Storage`]: crate::StorageClass::Storage + /// [`Uniform`]: crate::StorageClass::Uniform + pub buffer: BoundsCheckPolicy, + + /// How should the generated code handle image texel references that are out + /// of range? + /// + /// This controls the behavior of [`ImageLoad`] expressions and + /// [`ImageStore`] statements when a coordinate, texture array index, level + /// of detail, or multisampled sample number is out of range. + /// + /// [`ImageLoad`]: crate::Expression::ImageLoad + /// [`ImageStore`]: crate::Statement::ImageStore + pub image: BoundsCheckPolicy, +} + +/// The default `BoundsCheckPolicy` is `Unchecked`. +impl Default for BoundsCheckPolicy { + fn default() -> Self { + BoundsCheckPolicy::Unchecked + } +} + +impl BoundsCheckPolicies { + /// Determine which policy applies to a load or store of `pointer`. + /// + /// See the documentation for [`BoundsCheckPolicy`] for details about + /// when each policy applies. + pub fn choose_policy( + &self, + pointer: Handle, + types: &UniqueArena, + info: &valid::FunctionInfo, + ) -> BoundsCheckPolicy { + let is_buffer = match info[pointer].ty.inner_with(types).pointer_class() { + Some(crate::StorageClass::Storage { access: _ }) + | Some(crate::StorageClass::Uniform) => true, + _ => false, + }; + + if is_buffer { + self.buffer + } else { + self.index + } + } +} impl crate::TypeInner { /// Return the length of a subscriptable type. diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 4c906f6ee..4c40d845d 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -8,7 +8,7 @@ mod typifier; use std::cmp::PartialEq; -pub use index::IndexableLength; +pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength}; pub use layouter::{Alignment, InvalidBaseType, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 159e36c57..eaae4f795 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -30,7 +30,7 @@ impl Default for BoundsCheckPolicyArg { } } -impl From for naga::back::BoundsCheckPolicy { +impl From for naga::proc::BoundsCheckPolicy { fn from(arg: BoundsCheckPolicyArg) -> Self { match arg { BoundsCheckPolicyArg::Restrict => Self::Restrict, @@ -220,7 +220,7 @@ fn write_output_spv( Some(params.spv.capabilities.clone()) }, - bounds_check_policies: naga::back::BoundsCheckPolicies { + bounds_check_policies: naga::proc::BoundsCheckPolicies { index: params.index_bounds_check_policy.into(), buffer: params.buffer_bounds_check_policy.into(), image: params.image_bounds_check_policy.into(), From 29571cc4cfbb28558948b1b31ad764f55b69f37b Mon Sep 17 00:00:00 2001 From: Layl Bongers <2385329-layl@users.noreply.gitlab.com> Date: Tue, 16 Nov 2021 22:54:22 +0100 Subject: [PATCH 1449/2212] Add multiview wgsl builtin --- src/back/wgsl/writer.rs | 1 + src/front/wgsl/conv.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 8fa8ea43f..05060acca 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1841,6 +1841,7 @@ fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { Bi::SampleIndex => Some("sample_index"), Bi::SampleMask => Some("sample_mask"), Bi::PrimitiveIndex => Some("primitive_index"), + Bi::ViewIndex => Some("view_index"), _ => None, } } diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index add465f18..6f2645467 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -20,6 +20,7 @@ pub fn map_built_in(word: &str, span: Span) -> Result> // vertex "vertex_index" => crate::BuiltIn::VertexIndex, "instance_index" => crate::BuiltIn::InstanceIndex, + "view_index" => crate::BuiltIn::ViewIndex, // fragment "front_facing" => crate::BuiltIn::FrontFacing, "frag_depth" => crate::BuiltIn::FragDepth, From 633f1b33772a5da6dc8a14b698570cb9077c9a75 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 18 Nov 2021 10:29:44 -0800 Subject: [PATCH 1450/2212] [wgsl-in] Don't be confused by pointers to globals. The WGSL front end knows that globals in the `Handle` storage class do not produce references, but it attempts to manage this in two places which trip over each other. As a consequence, referring to a `let` binding holding a pointer to a global flips the variable's type from WGSL `ptr` to WGSL reference, with bewildering consequences. --- src/front/wgsl/mod.rs | 18 +---- tests/in/pointers.wgsl | 17 +++++ tests/out/spv/pointers.spvasm | 139 ++++++++++++++++++++++------------ tests/out/wgsl/pointers.wgsl | 16 ++++ 4 files changed, 124 insertions(+), 66 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e2879c722..3c2dc29ef 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2143,23 +2143,7 @@ impl Parser { let _ = lexer.next(); self.pop_scope(lexer); - // Not all identifiers constitute references in WGSL. - let is_reference = match ctx.expressions[definition.handle] { - // `let`-bound identifiers don't evaluate to references: `let` - // declarations apply the Load Rule to their values. - crate::Expression::LocalVariable(_) => definition.is_reference, - // Global variables in the `Handle` storage class do not evaluate - // to references. - crate::Expression::GlobalVariable(global) => { - ctx.global_vars[global].class != crate::StorageClass::Handle - } - _ => false, - }; - - TypedExpression { - handle: definition.handle, - is_reference, - } + *definition } else if let Some(CalledFunction { result: Some(expr) }) = self.parse_function_call_inner(lexer, word, ctx.reborrow())? { diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl index d7148e8db..0612b8a47 100644 --- a/tests/in/pointers.wgsl +++ b/tests/in/pointers.wgsl @@ -14,3 +14,20 @@ fn index_dynamic_array(p: ptr, i: i32, v: u32) -> u32 { (*p).array[i] = v; return old; } + +[[group(0), binding(0)]] +var dynamic_array: DynamicArray; + +fn index_unsized(i: i32, v: u32) { + let p: ptr = &dynamic_array; + + let val = (*p).array[i]; + (*p).array[i] = val + v; +} + +fn index_dynamic_array(i: i32, v: u32) { + let p: ptr, read_write> = &dynamic_array.array; + + let val = (*p)[i]; + (*p)[i] = val + v; +} diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index b14aab93c..d49a053a0 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -1,23 +1,33 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 42 +; Bound: 65 OpCapability Shader OpCapability Linkage +OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpSource GLSL 450 OpMemberName %8 0 "array" OpName %8 "DynamicArray" -OpName %10 "v" -OpName %13 "f" -OpName %20 "p" -OpName %21 "i" -OpName %22 "v" -OpName %23 "index_dynamic_array" +OpName %12 "dynamic_array" +OpName %13 "v" +OpName %16 "f" +OpName %23 "p" +OpName %24 "i" +OpName %25 "v" +OpName %26 "index_dynamic_array" +OpName %46 "i" +OpName %47 "v" +OpName %48 "index_unsized" +OpName %57 "i" +OpName %58 "v" +OpName %59 "index_dynamic_array" OpDecorate %7 ArrayStride 4 OpDecorate %8 Block OpMemberDecorate %8 0 Offset 0 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -26,49 +36,80 @@ OpMemberDecorate %8 0 Offset 0 %7 = OpTypeRuntimeArray %6 %8 = OpTypeStruct %7 %9 = OpTypePointer Workgroup %8 -%11 = OpTypePointer Function %5 -%14 = OpTypeFunction %2 -%16 = OpTypePointer Function %4 -%17 = OpConstant %6 0 -%24 = OpTypeFunction %6 %9 %4 %6 -%26 = OpTypePointer Workgroup %7 -%27 = OpTypePointer Workgroup %6 -%30 = OpTypeBool -%32 = OpConstantNull %6 -%13 = OpFunction %2 None %14 -%12 = OpLabel -%10 = OpVariable %11 Function -OpBranch %15 +%10 = OpTypePointer StorageBuffer %8 +%11 = OpTypePointer StorageBuffer %7 +%12 = OpVariable %10 StorageBuffer +%14 = OpTypePointer Function %5 +%17 = OpTypeFunction %2 +%19 = OpTypePointer Function %4 +%20 = OpConstant %6 0 +%27 = OpTypeFunction %6 %9 %4 %6 +%29 = OpTypePointer Workgroup %7 +%30 = OpTypePointer Workgroup %6 +%33 = OpTypeBool +%35 = OpConstantNull %6 +%49 = OpTypeFunction %2 %4 %6 +%51 = OpTypePointer StorageBuffer %6 +%16 = OpFunction %2 None %17 %15 = OpLabel -%18 = OpAccessChain %16 %10 %17 -OpStore %18 %3 +%13 = OpVariable %14 Function +OpBranch %18 +%18 = OpLabel +%21 = OpAccessChain %19 %13 %20 +OpStore %21 %3 OpReturn OpFunctionEnd -%23 = OpFunction %6 None %24 -%20 = OpFunctionParameter %9 -%21 = OpFunctionParameter %4 -%22 = OpFunctionParameter %6 -%19 = OpLabel -OpBranch %25 -%25 = OpLabel -%28 = OpArrayLength %6 %20 0 -%29 = OpULessThan %30 %21 %28 -OpSelectionMerge %33 None -OpBranchConditional %29 %34 %33 -%34 = OpLabel -%31 = OpAccessChain %27 %20 %17 %21 -%35 = OpLoad %6 %31 -OpBranch %33 -%33 = OpLabel -%36 = OpPhi %6 %32 %25 %35 %34 -%37 = OpArrayLength %6 %20 0 -%38 = OpULessThan %30 %21 %37 -OpSelectionMerge %40 None -OpBranchConditional %38 %41 %40 -%41 = OpLabel -%39 = OpAccessChain %27 %20 %17 %21 -OpStore %39 %22 -OpBranch %40 -%40 = OpLabel -OpReturnValue %36 +%26 = OpFunction %6 None %27 +%23 = OpFunctionParameter %9 +%24 = OpFunctionParameter %4 +%25 = OpFunctionParameter %6 +%22 = OpLabel +OpBranch %28 +%28 = OpLabel +%31 = OpArrayLength %6 %23 0 +%32 = OpULessThan %33 %24 %31 +OpSelectionMerge %36 None +OpBranchConditional %32 %37 %36 +%37 = OpLabel +%34 = OpAccessChain %30 %23 %20 %24 +%38 = OpLoad %6 %34 +OpBranch %36 +%36 = OpLabel +%39 = OpPhi %6 %35 %28 %38 %37 +%40 = OpArrayLength %6 %23 0 +%41 = OpULessThan %33 %24 %40 +OpSelectionMerge %43 None +OpBranchConditional %41 %44 %43 +%44 = OpLabel +%42 = OpAccessChain %30 %23 %20 %24 +OpStore %42 %25 +OpBranch %43 +%43 = OpLabel +OpReturnValue %39 +OpFunctionEnd +%48 = OpFunction %2 None %49 +%46 = OpFunctionParameter %4 +%47 = OpFunctionParameter %6 +%45 = OpLabel +OpBranch %50 +%50 = OpLabel +%52 = OpAccessChain %51 %12 %20 %46 +%53 = OpLoad %6 %52 +%54 = OpIAdd %6 %53 %47 +%55 = OpAccessChain %51 %12 %20 %46 +OpStore %55 %54 +OpReturn +OpFunctionEnd +%59 = OpFunction %2 None %49 +%57 = OpFunctionParameter %4 +%58 = OpFunctionParameter %6 +%56 = OpLabel +OpBranch %60 +%60 = OpLabel +%61 = OpAccessChain %51 %12 %20 %57 +%62 = OpLoad %6 %61 +%63 = OpIAdd %6 %62 %58 +%64 = OpAccessChain %51 %12 %20 %57 +OpStore %64 %63 +OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index 0979097b9..153e5a6ac 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -3,6 +3,9 @@ struct DynamicArray { array_: [[stride(4)]] array; }; +[[group(0), binding(0)]] +var dynamic_array: DynamicArray; + fn f() { var v: vec2; @@ -17,3 +20,16 @@ fn index_dynamic_array(p: ptr, i: i32, v_1: u32) -> u32 return old; } +fn index_unsized(i_1: i32, v_2: u32) { + let val: u32 = dynamic_array.array_[i_1]; + dynamic_array.array_[i_1] = (val + v_2); + return; +} + +fn index_dynamic_array_1(i_2: i32, v_3: u32) { + let p_1: ptr, read_write> = (&dynamic_array.array_); + let val_1: u32 = (*p_1)[i_2]; + (*p_1)[i_2] = (val_1 + v_3); + return; +} + From cc930180d9e719bb18c1adbd238593d5839c368c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 10 Nov 2021 17:32:40 -0800 Subject: [PATCH 1451/2212] Tighten checks on pointers to unsized values, and pointer arguments. Pointers should not be `DATA`: they can never be stored in anything. (Function arguments are not storage; they're like `let` bindings.) Un-`SIZED` values may only live in the `Storage` storage class, so creating pointers to them in other storage classes is meaningless. The `ARGUMENT` flag should be set only on pointers in those storage classes that are permitted to be passed to functions. See comments in code for details. Fixes #1513. --- src/valid/function.rs | 21 +++--- src/valid/type.rs | 59 +++++++++++---- tests/in/pointers.wgsl | 6 -- tests/out/spv/pointers.spvasm | 138 ++++++++++++---------------------- tests/out/wgsl/pointers.wgsl | 20 ++--- tests/wgsl-errors.rs | 35 +++++++-- 6 files changed, 140 insertions(+), 139 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index c2f3cf97c..0254775ec 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -843,16 +843,6 @@ impl super::Validator { #[cfg(feature = "validate")] for (index, argument) in fun.arguments.iter().enumerate() { - if !self.types[argument.ty.index()] - .flags - .contains(super::TypeFlags::ARGUMENT) - { - return Err(FunctionError::InvalidArgumentType { - index, - name: argument.name.clone().unwrap_or_default(), - } - .with_span_handle(argument.ty, &module.types)); - } match module.types[argument.ty].inner.pointer_class() { Some(crate::StorageClass::Private) | Some(crate::StorageClass::Function) @@ -867,6 +857,17 @@ impl super::Validator { .with_span_handle(argument.ty, &module.types)) } } + // Check for the least informative error last. + if !self.types[argument.ty.index()] + .flags + .contains(super::TypeFlags::ARGUMENT) + { + return Err(FunctionError::InvalidArgumentType { + index, + name: argument.name.clone().unwrap_or_default(), + } + .with_span_handle(argument.ty, &module.types)); + } } self.valid_expression_set.clear(); diff --git a/src/valid/type.rs b/src/valid/type.rs index c052fa9b2..923e1b24f 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -83,6 +83,11 @@ pub enum TypeError { UnresolvedBase(Handle), #[error("Invalid type for pointer target {0:?}")] InvalidPointerBase(Handle), + #[error("Unsized types like {base:?} must be in the `Storage` storage class, not `{class:?}`")] + InvalidPointerToUnsized { + base: Handle, + class: crate::StorageClass, + }, #[error("Expected data type, found {0:?}")] InvalidData(Handle), #[error("Base type {0:?} for the array is invalid")] @@ -255,7 +260,9 @@ impl super::Validator { width as u32, ) } - Ti::Pointer { base, class: _ } => { + Ti::Pointer { base, class } => { + use crate::StorageClass as Sc; + if base >= handle { return Err(TypeError::UnresolvedBase(base)); } @@ -264,21 +271,45 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidPointerBase(base)); } - // Pointers to dynamically-sized arrays are needed, to serve as - // the type of an `AccessIndex` expression referring to a - // dynamically sized array appearing as the final member of a - // top-level `Struct`. But such pointers cannot be passed to - // functions, stored in variables, etc. So, we mark them as not - // `DATA`. - let data_flag = if base_info.flags.contains(TypeFlags::SIZED) { - TypeFlags::DATA | TypeFlags::ARGUMENT - } else if let crate::TypeInner::Struct { .. } = types[base].inner { - TypeFlags::DATA | TypeFlags::ARGUMENT - } else { - TypeFlags::empty() + + // Runtime-sized values can only live in the `Storage` storage + // class, so it's useless to have a pointer to such a type in + // any other class. + // + // Detecting this problem here prevents the definition of + // functions like: + // + // fn f(p: ptr) -> ... { ... } + // + // which would otherwise be permitted, but uncallable. (They + // may also present difficulties in code generation). + if !base_info.flags.contains(TypeFlags::SIZED) { + match class { + Sc::Storage { .. } => {} + _ => { + return Err(TypeError::InvalidPointerToUnsized { base, class }); + } + } + } + + // Pointers passed as arguments to user-defined functions must + // be in the `Function`, `Private`, or `Workgroup` storage + // class. We only mark pointers in those classes as `ARGUMENT`. + // + // `Validator::validate_function` actually checks the storage + // class of pointer arguments explicitly before checking the + // `ARGUMENT` flag, to give better error messages. But it seems + // best to set `ARGUMENT` accurately anyway. + let argument_flag = match class { + Sc::Function | Sc::Private | Sc::WorkGroup => TypeFlags::ARGUMENT, + Sc::Uniform | Sc::Storage { .. } | Sc::Handle | Sc::PushConstant => { + TypeFlags::empty() + } }; - TypeInfo::new(data_flag | TypeFlags::SIZED | TypeFlags::COPY, 0) + // Pointers cannot be stored in variables, structure members, or + // array elements, so we do not mark them as `DATA`. + TypeInfo::new(argument_flag | TypeFlags::SIZED | TypeFlags::COPY, 0) } Ti::ValuePointer { size: _, diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl index 0612b8a47..d21080d30 100644 --- a/tests/in/pointers.wgsl +++ b/tests/in/pointers.wgsl @@ -9,12 +9,6 @@ struct DynamicArray { array: array; }; -fn index_dynamic_array(p: ptr, i: i32, v: u32) -> u32 { - let old = (*p).array[i]; - (*p).array[i] = v; - return old; -} - [[group(0), binding(0)]] var dynamic_array: DynamicArray; diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index d49a053a0..698829fd5 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 65 +; Bound: 41 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -10,24 +10,20 @@ OpMemoryModel Logical GLSL450 OpSource GLSL 450 OpMemberName %8 0 "array" OpName %8 "DynamicArray" -OpName %12 "dynamic_array" -OpName %13 "v" -OpName %16 "f" -OpName %23 "p" -OpName %24 "i" -OpName %25 "v" -OpName %26 "index_dynamic_array" -OpName %46 "i" -OpName %47 "v" -OpName %48 "index_unsized" -OpName %57 "i" -OpName %58 "v" -OpName %59 "index_dynamic_array" +OpName %11 "dynamic_array" +OpName %12 "v" +OpName %15 "f" +OpName %22 "i" +OpName %23 "v" +OpName %24 "index_unsized" +OpName %33 "i" +OpName %34 "v" +OpName %35 "index_dynamic_array" OpDecorate %7 ArrayStride 4 OpDecorate %8 Block OpMemberDecorate %8 0 Offset 0 -OpDecorate %12 DescriptorSet 0 -OpDecorate %12 Binding 0 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -35,81 +31,47 @@ OpDecorate %12 Binding 0 %6 = OpTypeInt 32 0 %7 = OpTypeRuntimeArray %6 %8 = OpTypeStruct %7 -%9 = OpTypePointer Workgroup %8 -%10 = OpTypePointer StorageBuffer %8 -%11 = OpTypePointer StorageBuffer %7 -%12 = OpVariable %10 StorageBuffer -%14 = OpTypePointer Function %5 -%17 = OpTypeFunction %2 -%19 = OpTypePointer Function %4 -%20 = OpConstant %6 0 -%27 = OpTypeFunction %6 %9 %4 %6 -%29 = OpTypePointer Workgroup %7 -%30 = OpTypePointer Workgroup %6 -%33 = OpTypeBool -%35 = OpConstantNull %6 -%49 = OpTypeFunction %2 %4 %6 -%51 = OpTypePointer StorageBuffer %6 -%16 = OpFunction %2 None %17 -%15 = OpLabel -%13 = OpVariable %14 Function -OpBranch %18 -%18 = OpLabel -%21 = OpAccessChain %19 %13 %20 -OpStore %21 %3 +%9 = OpTypePointer StorageBuffer %8 +%10 = OpTypePointer StorageBuffer %7 +%11 = OpVariable %9 StorageBuffer +%13 = OpTypePointer Function %5 +%16 = OpTypeFunction %2 +%18 = OpTypePointer Function %4 +%19 = OpConstant %6 0 +%25 = OpTypeFunction %2 %4 %6 +%27 = OpTypePointer StorageBuffer %6 +%15 = OpFunction %2 None %16 +%14 = OpLabel +%12 = OpVariable %13 Function +OpBranch %17 +%17 = OpLabel +%20 = OpAccessChain %18 %12 %19 +OpStore %20 %3 OpReturn OpFunctionEnd -%26 = OpFunction %6 None %27 -%23 = OpFunctionParameter %9 -%24 = OpFunctionParameter %4 -%25 = OpFunctionParameter %6 -%22 = OpLabel -OpBranch %28 -%28 = OpLabel -%31 = OpArrayLength %6 %23 0 -%32 = OpULessThan %33 %24 %31 -OpSelectionMerge %36 None -OpBranchConditional %32 %37 %36 -%37 = OpLabel -%34 = OpAccessChain %30 %23 %20 %24 -%38 = OpLoad %6 %34 +%24 = OpFunction %2 None %25 +%22 = OpFunctionParameter %4 +%23 = OpFunctionParameter %6 +%21 = OpLabel +OpBranch %26 +%26 = OpLabel +%28 = OpAccessChain %27 %11 %19 %22 +%29 = OpLoad %6 %28 +%30 = OpIAdd %6 %29 %23 +%31 = OpAccessChain %27 %11 %19 %22 +OpStore %31 %30 +OpReturn +OpFunctionEnd +%35 = OpFunction %2 None %25 +%33 = OpFunctionParameter %4 +%34 = OpFunctionParameter %6 +%32 = OpLabel OpBranch %36 %36 = OpLabel -%39 = OpPhi %6 %35 %28 %38 %37 -%40 = OpArrayLength %6 %23 0 -%41 = OpULessThan %33 %24 %40 -OpSelectionMerge %43 None -OpBranchConditional %41 %44 %43 -%44 = OpLabel -%42 = OpAccessChain %30 %23 %20 %24 -OpStore %42 %25 -OpBranch %43 -%43 = OpLabel -OpReturnValue %39 -OpFunctionEnd -%48 = OpFunction %2 None %49 -%46 = OpFunctionParameter %4 -%47 = OpFunctionParameter %6 -%45 = OpLabel -OpBranch %50 -%50 = OpLabel -%52 = OpAccessChain %51 %12 %20 %46 -%53 = OpLoad %6 %52 -%54 = OpIAdd %6 %53 %47 -%55 = OpAccessChain %51 %12 %20 %46 -OpStore %55 %54 -OpReturn -OpFunctionEnd -%59 = OpFunction %2 None %49 -%57 = OpFunctionParameter %4 -%58 = OpFunctionParameter %6 -%56 = OpLabel -OpBranch %60 -%60 = OpLabel -%61 = OpAccessChain %51 %12 %20 %57 -%62 = OpLoad %6 %61 -%63 = OpIAdd %6 %62 %58 -%64 = OpAccessChain %51 %12 %20 %57 -OpStore %64 %63 +%37 = OpAccessChain %27 %11 %19 %33 +%38 = OpLoad %6 %37 +%39 = OpIAdd %6 %38 %34 +%40 = OpAccessChain %27 %11 %19 %33 +OpStore %40 %39 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index 153e5a6ac..5c3d0e1f8 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -14,22 +14,16 @@ fn f() { return; } -fn index_dynamic_array(p: ptr, i: i32, v_1: u32) -> u32 { - let old: u32 = (*p).array_[i]; - (*p).array_[i] = v_1; - return old; -} - -fn index_unsized(i_1: i32, v_2: u32) { - let val: u32 = dynamic_array.array_[i_1]; - dynamic_array.array_[i_1] = (val + v_2); +fn index_unsized(i: i32, v_1: u32) { + let val: u32 = dynamic_array.array_[i]; + dynamic_array.array_[i] = (val + v_1); return; } -fn index_dynamic_array_1(i_2: i32, v_3: u32) { - let p_1: ptr, read_write> = (&dynamic_array.array_); - let val_1: u32 = (*p_1)[i_2]; - (*p_1)[i_2] = (val_1 + v_3); +fn index_dynamic_array(i_1: i32, v_2: u32) { + let p: ptr, read_write> = (&dynamic_array.array_); + let val_1: u32 = (*p)[i_1]; + (*p)[i_1] = (val_1 + v_2); return; } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index c85c113db..0109245c0 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -662,7 +662,6 @@ fn invalid_structs() { fn invalid_functions() { check_validation_error! { "fn unacceptable_unsized(arg: array) { }", - "fn unacceptable_unsized(arg: ptr>) { }", " struct Unsized { data: array; }; fn unacceptable_unsized(arg: Unsized) { } @@ -678,19 +677,39 @@ fn invalid_functions() { if function_name == "unacceptable_unsized" && argument_name == "arg" } + // Pointer's storage class cannot hold unsized data. check_validation_error! { + "fn unacceptable_unsized(arg: ptr>) { }", " struct Unsized { data: array; }; - fn acceptable_pointer_to_unsized(arg: ptr) { } + fn unacceptable_unsized(arg: ptr) { } ": - Ok(_) + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::InvalidPointerToUnsized { + base: _, + class: naga::StorageClass::WorkGroup { .. }, + }, + .. + }) + } + + // Pointers of these storage classes cannot be passed as arguments. + check_validation_error! { + "fn unacceptable_ptr_class(arg: ptr>) { }": + Err(naga::valid::ValidationError::Function { + name: function_name, + error: naga::valid::FunctionError::InvalidArgumentPointerClass { + index: 0, + name: argument_name, + class: naga::StorageClass::Storage { .. }, + }, + .. + }) + if function_name == "unacceptable_ptr_class" && argument_name == "arg" } check_validation_error! { - " - struct Unsized { data: array; }; - fn unacceptable_uniform_class(arg: ptr) { } - ": + "fn unacceptable_ptr_class(arg: ptr) { }": Err(naga::valid::ValidationError::Function { name: function_name, error: naga::valid::FunctionError::InvalidArgumentPointerClass { @@ -700,7 +719,7 @@ fn invalid_functions() { }, .. }) - if function_name == "unacceptable_uniform_class" && argument_name == "arg" + if function_name == "unacceptable_ptr_class" && argument_name == "arg" } } From 7fd172515dd6348fd9b35b81366686c62e41d69c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 10 Nov 2021 21:31:57 -0800 Subject: [PATCH 1452/2212] [spv-out] Don't support arguments pointing to unsized types. Functions with such arguments could never have been called anyway, and now they are forbidden in validation. --- src/back/spv/index.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index bd6619762..f6b92b1d0 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -65,10 +65,6 @@ impl<'w> BlockContext<'w> { crate::Expression::GlobalVariable(handle) => { (self.writer.global_variables[handle.index()].id, index) } - crate::Expression::FunctionArgument(index) => { - let parameter_id = self.function.parameter_id(index); - (parameter_id, index) - } _ => return Err(Error::Validation("array length expression")), } } From ae0c7355ca5bef071e272961f720bcb733bf1c6c Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 24 Nov 2021 22:54:32 +0300 Subject: [PATCH 1453/2212] [wgsl] Remove IsInf and IsNan --- src/back/wgsl/mod.rs | 2 ++ src/back/wgsl/writer.rs | 3 +-- src/front/wgsl/conv.rs | 2 -- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index 3198e65b6..2d8392c62 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -17,6 +17,8 @@ pub enum Error { Unimplemented(String), // TODO: Error used only during development #[error("Unsupported math function: {0:?}")] UnsupportedMathFunction(crate::MathFunction), + #[error("Unsupported relational function: {0:?}")] + UnsupportedRelationalFunction(crate::RelationalFunction), } pub fn write_string( diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 05060acca..641c61e0a 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1624,11 +1624,10 @@ impl Writer { let fun_name = match fun { Rf::IsFinite => "isFinite", - Rf::IsInf => "isInf", - Rf::IsNan => "isNan", Rf::IsNormal => "isNormal", Rf::All => "all", Rf::Any => "any", + _ => return Err(Error::UnsupportedRelationalFunction(fun)), }; write!(self.out, "{}(", fun_name)?; diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 6f2645467..12d195ba6 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -136,8 +136,6 @@ pub fn map_relational_fun(word: &str) -> Option { "any" => Some(crate::RelationalFunction::Any), "all" => Some(crate::RelationalFunction::All), "isFinite" => Some(crate::RelationalFunction::IsFinite), - "isInf" => Some(crate::RelationalFunction::IsInf), - "isNan" => Some(crate::RelationalFunction::IsNan), "isNormal" => Some(crate::RelationalFunction::IsNormal), _ => None, } From cb6d3fa8156ac4ecad80224c517c875e9b0791e8 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 24 Nov 2021 17:59:36 +0300 Subject: [PATCH 1454/2212] [wgsl] Move backend keyword list into its own module --- src/back/wgsl/mod.rs | 1 - src/back/wgsl/writer.rs | 2 +- src/keywords/mod.rs | 2 + .../wgsl/keywords.rs => keywords/wgsl.rs} | 268 +++++++++--------- src/lib.rs | 1 + 5 files changed, 138 insertions(+), 136 deletions(-) create mode 100644 src/keywords/mod.rs rename src/{back/wgsl/keywords.rs => keywords/wgsl.rs} (94%) diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index 2d8392c62..2f35311e6 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -1,4 +1,3 @@ -mod keywords; mod writer; use thiserror::Error; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 641c61e0a..6d5b2016a 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -73,7 +73,7 @@ impl Writer { fn reset(&mut self, module: &Module) { self.names.clear(); self.namer - .reset(module, super::keywords::RESERVED, &[], &mut self.names); + .reset(module, crate::keywords::wgsl::RESERVED, &[], &mut self.names); self.named_expressions.clear(); self.ep_results.clear(); } diff --git a/src/keywords/mod.rs b/src/keywords/mod.rs new file mode 100644 index 000000000..67101a1c1 --- /dev/null +++ b/src/keywords/mod.rs @@ -0,0 +1,2 @@ +#[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] +pub mod wgsl; \ No newline at end of file diff --git a/src/back/wgsl/keywords.rs b/src/keywords/wgsl.rs similarity index 94% rename from src/back/wgsl/keywords.rs rename to src/keywords/wgsl.rs index f40ecd0ce..16e11ea3d 100644 --- a/src/back/wgsl/keywords.rs +++ b/src/keywords/wgsl.rs @@ -1,134 +1,134 @@ -// https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary -pub const RESERVED: &[&str] = &[ - // type-defining keywords - "array", - "atomic", - "bool", - "float32", - "int32", - "mat2x2", - "mat2x3", - "mat2x4", - "mat3x2", - "mat3x3", - "mat3x4", - "mat4x2", - "mat4x3", - "mat4x4", - "pointer", - "sampler", - "sampler_comparison", - "struct", - "texture_1d", - "texture_2d", - "texture_2d_array", - "texture_3d", - "texture_cube", - "texture_cube_array", - "texture_multisampled_2d", - "texture_storage_1d", - "texture_storage_2d", - "texture_storage_2d_array", - "texture_storage_3d", - "texture_depth_2d", - "texture_depth_2d_array", - "texture_depth_cube", - "texture_depth_cube_array", - "texture_depth_multisampled_2d", - "uint32", - "vec2", - "vec3", - "vec4", - // other keywords - "bitcast", - "block", - "break", - "case", - "continue", - "continuing", - "default", - "discard", - "else", - "else_if", - "enable", - "fallthrough", - "false", - "fn", - "for", - "function", - "if", - "let", - "loop", - "private", - "read", - "read_write", - "return", - "storage", - "switch", - "true", - "type", - "uniform", - "var", - "workgroup", - "write", - // image format keywords - "r8unorm", - "r8snorm", - "r8uint", - "r8sint", - "r16uint", - "r16sint", - "r16float", - "rg8unorm", - "rg8snorm", - "rg8uint", - "rg8sint", - "r32uint", - "r32sint", - "r32float", - "rg16uint", - "rg16sint", - "rg16float", - "rgba8unorm", - "rgba8unorm_srgb", - "rgba8snorm", - "rgba8uint", - "rgba8sint", - "bgra8unorm", - "bgra8unorm_srgb", - "rgb10a2unorm", - "rg11b10float", - "rg32uint", - "rg32sint", - "rg32float", - "rgba16uint", - "rgba16sint", - "rgba16float", - "rgba32uint", - "rgba32sint", - "rgba32float", - // reserved keywords - "asm", - "bf16", - "const", - "do", - "enum", - "f16", - "f64", - "handle", - "i8", - "i16", - "i64", - "mat", - "premerge", - "regardless", - "typedef", - "u8", - "u16", - "u64", - "unless", - "using", - "vec", - "void", - "while", -]; +// https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary +pub const RESERVED: &[&str] = &[ + // type-defining keywords + "array", + "atomic", + "bool", + "float32", + "int32", + "mat2x2", + "mat2x3", + "mat2x4", + "mat3x2", + "mat3x3", + "mat3x4", + "mat4x2", + "mat4x3", + "mat4x4", + "pointer", + "sampler", + "sampler_comparison", + "struct", + "texture_1d", + "texture_2d", + "texture_2d_array", + "texture_3d", + "texture_cube", + "texture_cube_array", + "texture_multisampled_2d", + "texture_storage_1d", + "texture_storage_2d", + "texture_storage_2d_array", + "texture_storage_3d", + "texture_depth_2d", + "texture_depth_2d_array", + "texture_depth_cube", + "texture_depth_cube_array", + "texture_depth_multisampled_2d", + "uint32", + "vec2", + "vec3", + "vec4", + // other keywords + "bitcast", + "block", + "break", + "case", + "continue", + "continuing", + "default", + "discard", + "else", + "else_if", + "enable", + "fallthrough", + "false", + "fn", + "for", + "function", + "if", + "let", + "loop", + "private", + "read", + "read_write", + "return", + "storage", + "switch", + "true", + "type", + "uniform", + "var", + "workgroup", + "write", + // image format keywords + "r8unorm", + "r8snorm", + "r8uint", + "r8sint", + "r16uint", + "r16sint", + "r16float", + "rg8unorm", + "rg8snorm", + "rg8uint", + "rg8sint", + "r32uint", + "r32sint", + "r32float", + "rg16uint", + "rg16sint", + "rg16float", + "rgba8unorm", + "rgba8unorm_srgb", + "rgba8snorm", + "rgba8uint", + "rgba8sint", + "bgra8unorm", + "bgra8unorm_srgb", + "rgb10a2unorm", + "rg11b10float", + "rg32uint", + "rg32sint", + "rg32float", + "rgba16uint", + "rgba16sint", + "rgba16float", + "rgba32uint", + "rgba32sint", + "rgba32float", + // reserved keywords + "asm", + "bf16", + "const", + "do", + "enum", + "f16", + "f64", + "handle", + "i8", + "i16", + "i64", + "mat", + "premerge", + "regardless", + "typedef", + "u8", + "u16", + "u64", + "unless", + "using", + "vec", + "void", + "while", +]; diff --git a/src/lib.rs b/src/lib.rs index 05506190e..d1a0e0ef2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -212,6 +212,7 @@ pub mod front; pub mod proc; mod span; pub mod valid; +pub(crate) mod keywords; pub use crate::arena::{Arena, Handle, Range, UniqueArena}; From 2107b205619dfa329214bfcbe1b6b5dd38445966 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 24 Nov 2021 16:28:23 +0300 Subject: [PATCH 1455/2212] [wgsl-in] Don't allow keywords to be used as identifiers --- src/back/wgsl/writer.rs | 8 ++- src/front/wgsl/mod.rs | 46 +++++++++++-- src/keywords/mod.rs | 4 +- src/lib.rs | 2 +- tests/in/access.wgsl | 2 +- tests/in/pointers.wgsl | 8 +-- tests/out/spv/pointers.spvasm | 2 +- tests/out/wgsl/access.wgsl | 2 +- tests/out/wgsl/pointers.wgsl | 8 +-- tests/wgsl-errors.rs | 126 +++++++++++++++++++++++++++++++--- 10 files changed, 176 insertions(+), 32 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 6d5b2016a..9b04346d0 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -72,8 +72,12 @@ impl Writer { fn reset(&mut self, module: &Module) { self.names.clear(); - self.namer - .reset(module, crate::keywords::wgsl::RESERVED, &[], &mut self.names); + self.namer.reset( + module, + crate::keywords::wgsl::RESERVED, + &[], + &mut self.names, + ); self.named_expressions.clear(); self.ep_results.clear(); } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 3c2dc29ef..60584c0f9 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -169,6 +169,7 @@ pub enum Error<'a> { Pointer(&'static str, Span), NotPointer(Span), NotReference(&'static str, Span), + ReservedKeyword(Span), Other, } @@ -431,6 +432,11 @@ impl<'a> Error<'a> { labels: vec![(span.clone(), "expression is a pointer".into())], notes: vec![], }, + Error::ReservedKeyword(ref name_span) => ParseError { + message: format!("Name `{}` is a reserved keyword", &source[name_span.clone()]), + labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], + notes: vec![], + }, Error::Other => ParseError { message: "other error".to_string(), labels: vec![], @@ -2079,15 +2085,18 @@ impl Parser { // Only set span if it's a named constant. Otherwise, the enclosing Expression should have // the span. - let span = NagaSpan::from(self.pop_scope(lexer)); + let span = self.pop_scope(lexer); let handle = if let Some(name) = register_name { + if crate::keywords::wgsl::RESERVED.contains(&name) { + return Err(Error::ReservedKeyword(span)); + } const_arena.append( crate::Constant { name: Some(name.to_string()), specialization: None, inner, }, - span, + NagaSpan::from(span), ) } else { const_arena.fetch_or_append( @@ -2701,15 +2710,17 @@ impl Parser { } let bind_span = self.pop_scope(lexer); - - let name = match lexer.next() { - (Token::Word(word), _) => word, + let (name, span) = match lexer.next() { + (Token::Word(word), span) => (word, span), (Token::Paren('}'), _) => { let span = Layouter::round_up(alignment, offset); return Ok((members, span)); } other => return Err(Error::Unexpected(other, ExpectedToken::FieldName)), }; + if crate::keywords::wgsl::RESERVED.contains(&name) { + return Err(Error::ReservedKeyword(span)); + } lexer.expect(Token::Separator(':'))?; let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; lexer.expect(Token::Separator(';'))?; @@ -3245,6 +3256,9 @@ impl Parser { let _ = lexer.next(); emitter.start(context.expressions); let (name, name_span) = lexer.next_ident_with_span()?; + if crate::keywords::wgsl::RESERVED.contains(&name) { + return Err(Error::ReservedKeyword(name_span)); + } let given_ty = if lexer.skip(Token::Separator(':')) { let (ty, _access) = self.parse_type_decl( lexer, @@ -3300,6 +3314,9 @@ impl Parser { } let (name, name_span) = lexer.next_ident_with_span()?; + if crate::keywords::wgsl::RESERVED.contains(&name) { + return Err(Error::ReservedKeyword(name_span)); + } let given_ty = if lexer.skip(Token::Separator(':')) { let (ty, _access) = self.parse_type_decl( lexer, @@ -3810,7 +3827,10 @@ impl Parser { self.push_scope(Scope::FunctionDecl, lexer); // read function name let mut lookup_ident = FastHashMap::default(); - let fun_name = lexer.next_ident()?; + let (fun_name, span) = lexer.next_ident_with_span()?; + if crate::keywords::wgsl::RESERVED.contains(&fun_name) { + return Err(Error::ReservedKeyword(span)); + } // populate initial expressions let mut expressions = Arena::new(); for (&name, expression) in lookup_global_expression.iter() { @@ -3845,6 +3865,9 @@ impl Parser { let mut binding = self.parse_varying_binding(lexer)?; let (param_name, param_name_span, param_type, _access) = self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; + if crate::keywords::wgsl::RESERVED.contains(¶m_name) { + return Err(Error::ReservedKeyword(param_name_span)); + } let param_index = arguments.len() as u32; let expression = expressions.append( crate::Expression::FunctionArgument(param_index), @@ -4016,7 +4039,10 @@ impl Parser { match lexer.next() { (Token::Separator(';'), _) => {} (Token::Word("struct"), _) => { - let name = lexer.next_ident()?; + let (name, span) = lexer.next_ident_with_span()?; + if crate::keywords::wgsl::RESERVED.contains(&name) { + return Err(Error::ReservedKeyword(span)); + } let (members, span) = self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?; let type_span = NagaSpan::from(lexer.span_from(start)); @@ -4048,6 +4074,9 @@ impl Parser { } (Token::Word("let"), _) => { let (name, name_span) = lexer.next_ident_with_span()?; + if crate::keywords::wgsl::RESERVED.contains(&name) { + return Err(Error::ReservedKeyword(name_span)); + } let given_ty = if lexer.skip(Token::Separator(':')) { let (ty, _access) = self.parse_type_decl( lexer, @@ -4093,6 +4122,9 @@ impl Parser { (Token::Word("var"), _) => { let pvar = self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; + if crate::keywords::wgsl::RESERVED.contains(&pvar.name) { + return Err(Error::ReservedKeyword(pvar.name_span)); + } let var_handle = module.global_variables.append( crate::GlobalVariable { name: Some(pvar.name.to_owned()), diff --git a/src/keywords/mod.rs b/src/keywords/mod.rs index 67101a1c1..4f959bcd0 100644 --- a/src/keywords/mod.rs +++ b/src/keywords/mod.rs @@ -1,2 +1,2 @@ -#[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] -pub mod wgsl; \ No newline at end of file +#[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] +pub mod wgsl; diff --git a/src/lib.rs b/src/lib.rs index d1a0e0ef2..eea9d2e93 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -209,10 +209,10 @@ mod arena; pub mod back; mod block; pub mod front; +pub mod keywords; pub mod proc; mod span; pub mod valid; -pub(crate) mod keywords; pub use crate::arena::{Arena, Handle, Range, UniqueArena}; diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 4a2228fa3..034d0d5ab 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -30,7 +30,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let a = bar.data[arrayLength(&bar.data) - 2u]; // test pointer types - let pointer: ptr = &bar.data[0]; + let data_pointer: ptr = &bar.data[0]; let foo_value = read_from_private(&foo); // test storage stores diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl index d21080d30..e3160774c 100644 --- a/tests/in/pointers.wgsl +++ b/tests/in/pointers.wgsl @@ -6,7 +6,7 @@ fn f() { [[block]] struct DynamicArray { - array: array; + arr: array; }; [[group(0), binding(0)]] @@ -15,12 +15,12 @@ var dynamic_array: DynamicArray; fn index_unsized(i: i32, v: u32) { let p: ptr = &dynamic_array; - let val = (*p).array[i]; - (*p).array[i] = val + v; + let val = (*p).arr[i]; + (*p).arr[i] = val + v; } fn index_dynamic_array(i: i32, v: u32) { - let p: ptr, read_write> = &dynamic_array.array; + let p: ptr, read_write> = &dynamic_array.arr; let val = (*p)[i]; (*p)[i] = val + v; diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index 698829fd5..661a8e2c2 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -8,7 +8,7 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpSource GLSL 450 -OpMemberName %8 0 "array" +OpMemberName %8 0 "arr" OpName %8 "DynamicArray" OpName %11 "dynamic_array" OpName %12 "v" diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index ad1666f9a..21efceff0 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -25,7 +25,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let arr: array,2> = bar.arr; let b: f32 = bar.matrix[3][0]; let a: i32 = bar.data[(arrayLength((&bar.data)) - 2u)]; - let pointer_: ptr = (&bar.data[0]); + let data_pointer: ptr = (&bar.data[0]); let e25: f32 = read_from_private((&foo_1)); bar.matrix[1][2] = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index 5c3d0e1f8..4bf53b8a8 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -1,6 +1,6 @@ [[block]] struct DynamicArray { - array_: [[stride(4)]] array; + arr: [[stride(4)]] array; }; [[group(0), binding(0)]] @@ -15,13 +15,13 @@ fn f() { } fn index_unsized(i: i32, v_1: u32) { - let val: u32 = dynamic_array.array_[i]; - dynamic_array.array_[i] = (val + v_1); + let val: u32 = dynamic_array.arr[i]; + dynamic_array.arr[i] = (val + v_1); return; } fn index_dynamic_array(i_1: i32, v_2: u32) { - let p: ptr, read_write> = (&dynamic_array.array_); + let p: ptr, read_write> = (&dynamic_array.arr); let val_1: u32 = (*p)[i_1]; (*p)[i_1] = (val_1 + v_2); return; diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 0109245c0..571a34962 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -114,18 +114,18 @@ fn negative_index() { fn bad_texture() { check( r#" - [[group(0), binding(0)]] var sampler : sampler; + [[group(0), binding(0)]] var sampler1 : sampler; [[stage(fragment)]] fn main() -> [[location(0)]] vec4 { let a = 3; - return textureSample(a, sampler, vec2(0.0)); + return textureSample(a, sampler1, vec2(0.0)); } "#, r#"error: expected an image, but found 'a' which is not an image ┌─ wgsl:7:38 │ -7 │ return textureSample(a, sampler, vec2(0.0)); +7 │ return textureSample(a, sampler1, vec2(0.0)); │ ^ not an image "#, @@ -154,12 +154,12 @@ fn bad_type_cast() { fn bad_texture_sample_type() { check( r#" - [[group(0), binding(0)]] var sampler : sampler; + [[group(0), binding(0)]] var sampler1 : sampler; [[group(0), binding(1)]] var texture : texture_2d; [[stage(fragment)]] fn main() -> [[location(0)]] vec4 { - return textureSample(texture, sampler, vec2(0.0)); + return textureSample(texture, sampler1, vec2(0.0)); } "#, r#"error: texture sample type must be one of f32, i32 or u32, but found bool @@ -327,13 +327,13 @@ fn unknown_type() { fn unknown_storage_format() { check( r#" - let storage: texture_storage_1d; + let storage1: texture_storage_1d; "#, r#"error: unknown storage format: 'rgba' - ┌─ wgsl:2:45 + ┌─ wgsl:2:46 │ -2 │ let storage: texture_storage_1d; - │ ^^^^ unknown storage format +2 │ let storage1: texture_storage_1d; + │ ^^^^ unknown storage format "#, ); @@ -531,6 +531,114 @@ fn postfix_pointers() { ); } +#[test] +fn reserved_keyword() { + // global var + check( + r#" + var bool: bool = true; + "#, + r###"error: Name ` bool: bool = true;` is a reserved keyword + ┌─ wgsl:2:16 + │ +2 │ var bool: bool = true; + │ ^^^^^^^^^^^^^^^^^^^ definition of ` bool: bool = true;` + +"###, + ); + + // global constant + check( + r#" + let break: bool = true; + fn foo() { + var foo = break; + } + "#, + r###"error: Name `break` is a reserved keyword + ┌─ wgsl:2:17 + │ +2 │ let break: bool = true; + │ ^^^^^ definition of `break` + +"###, + ); + + // local let + check( + r#" + fn foo() { + let atomic: f32 = 1.0; + } + "#, + r###"error: Name `atomic` is a reserved keyword + ┌─ wgsl:3:21 + │ +3 │ let atomic: f32 = 1.0; + │ ^^^^^^ definition of `atomic` + +"###, + ); + + // local var + check( + r#" + fn foo() { + var sampler: f32 = 1.0; + } + "#, + r###"error: Name `sampler` is a reserved keyword + ┌─ wgsl:3:21 + │ +3 │ var sampler: f32 = 1.0; + │ ^^^^^^^ definition of `sampler` + +"###, + ); + + // fn name + check( + r#" + fn break() {} + "#, + r###"error: Name `break` is a reserved keyword + ┌─ wgsl:2:16 + │ +2 │ fn break() {} + │ ^^^^^ definition of `break` + +"###, + ); + + // struct + check( + r#" + struct array {}; + "#, + r###"error: Name `array` is a reserved keyword + ┌─ wgsl:2:20 + │ +2 │ struct array {}; + │ ^^^^^ definition of `array` + +"###, + ); + + // struct member + check( + r#" + struct Foo { sampler: f32; }; + "#, + r###"error: Name `sampler` is a reserved keyword + ┌─ wgsl:2:26 + │ +2 │ struct Foo { sampler: f32; }; + │ ^^^^^^^ definition of `sampler` + +"###, + ); +} + macro_rules! check_validation_error { // We want to support an optional guard expression after the pattern, so // that we can check values we can't match against, like strings. From ddbc1c4b1f19d7942ee8c90594f177c1278191a6 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 23 Nov 2021 08:36:48 -0500 Subject: [PATCH 1456/2212] WGSL: use underscore prefix like the other backends --- src/back/wgsl/mod.rs | 2 - src/back/wgsl/writer.rs | 6 +- src/front/wgsl/lexer.rs | 12 +- src/front/wgsl/mod.rs | 6 + tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 12 +- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 24 +- tests/out/wgsl/210-bevy-shader-vert.wgsl | 38 +- tests/out/wgsl/246-collatz-comp.wgsl | 40 +- tests/out/wgsl/280-matrix-cast-vert.wgsl | 2 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 24 +- tests/out/wgsl/932-for-loop-if-vert.wgsl | 8 +- tests/out/wgsl/access.wgsl | 38 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 1042 ++++++++--------- tests/out/wgsl/bevy-pbr-vert.wgsl | 46 +- tests/out/wgsl/bits.wgsl | 120 +- tests/out/wgsl/bits_glsl-frag.wgsl | 120 +- tests/out/wgsl/boids.wgsl | 160 +-- tests/out/wgsl/bool-select-frag.wgsl | 30 +- tests/out/wgsl/clamp-splat-vert.wgsl | 8 +- tests/out/wgsl/collatz.wgsl | 30 +- tests/out/wgsl/constant-array-size-vert.wgsl | 20 +- tests/out/wgsl/control-flow.wgsl | 8 +- tests/out/wgsl/empty-global-name.wgsl | 4 +- tests/out/wgsl/expressions-frag.wgsl | 240 ++-- tests/out/wgsl/fma-frag.wgsl | 36 +- .../out/wgsl/global-constant-array-vert.wgsl | 2 +- tests/out/wgsl/interpolate.wgsl | 4 +- .../wgsl/inv-hyperbolic-trig-functions.wgsl | 12 +- tests/out/wgsl/long-form-matrix-vert.wgsl | 30 +- tests/out/wgsl/math-functions-vert.wgsl | 202 ++-- tests/out/wgsl/operators.wgsl | 14 +- tests/out/wgsl/prepostfix-frag.wgsl | 48 +- tests/out/wgsl/quad-vert.wgsl | 14 +- tests/out/wgsl/quad_glsl-frag.wgsl | 4 +- tests/out/wgsl/quad_glsl-vert.wgsl | 14 +- tests/out/wgsl/samplers-frag.wgsl | 892 +++++++------- tests/out/wgsl/shadow.wgsl | 30 +- tests/out/wgsl/skybox.wgsl | 22 +- tests/out/wgsl/swizzle_write-frag.wgsl | 18 +- tests/out/wgsl/texture-arg.wgsl | 8 +- tests/wgsl-errors.rs | 14 + 41 files changed, 1711 insertions(+), 1693 deletions(-) diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index 2f35311e6..6f02367e1 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -4,8 +4,6 @@ use thiserror::Error; pub use writer::Writer; -const BAKE_PREFIX: &str = "e"; - #[derive(Error, Debug)] pub enum Error { #[error(transparent)] diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 9b04346d0..7fb32f317 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -708,7 +708,7 @@ impl Writer { } } - Some(format!("{}{}", super::BAKE_PREFIX, handle.index())) + Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) } else { None } @@ -811,7 +811,7 @@ impl Writer { } => { write!(self.out, "{}", level)?; if let Some(expr) = result { - let name = format!("{}{}", super::BAKE_PREFIX, expr.index()); + let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); self.start_named_expr(module, expr, func_ctx, &name)?; self.named_expressions.insert(expr, name); } @@ -834,7 +834,7 @@ impl Writer { result, } => { write!(self.out, "{}", level)?; - let res_name = format!("{}{}", super::BAKE_PREFIX, result.index()); + let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); self.start_named_expr(module, result, func_ctx, &res_name)?; self.named_expressions.insert(result, res_name); diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 91f2a5ead..e74520541 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -336,7 +336,7 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { } } '0'..='9' => consume_number(input), - 'a'..='z' | 'A'..='Z' => { + '_' | 'a'..='z' | 'A'..='Z' => { let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); (Token::Word(word), rest) } @@ -514,16 +514,16 @@ impl<'a> Lexer<'a> { pub(super) fn next_ident_with_span(&mut self) -> Result<(&'a str, Span), Error<'a>> { match self.next() { + (Token::Word(word), span) if word.starts_with("__") => { + Err(Error::ReservedIdentifierPrefix(span)) + } (Token::Word(word), span) => Ok((word, span)), other => Err(Error::Unexpected(other, ExpectedToken::Identifier)), } } pub(super) fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { - match self.next() { - (Token::Word(word), _) => Ok(word), - other => Err(Error::Unexpected(other, ExpectedToken::Identifier)), - } + self.next_ident_with_span().map(|(word, _)| word) } /// Parses a generic scalar type, for example ``. @@ -655,7 +655,7 @@ fn test_tokens() { ); sub_test("No¾", &[Token::Word("No"), Token::Unknown('¾')]); sub_test("No好", &[Token::Word("No"), Token::Unknown('好')]); - sub_test("_No", &[Token::Unknown('_'), Token::Word("No")]); + sub_test("_No", &[Token::Word("_No")]); sub_test("\"\u{2}ПЀ\u{0}\"", &[Token::String("\u{2}ПЀ\u{0}")]); // https://github.com/gfx-rs/naga/issues/90 } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 60584c0f9..c47ffe8a4 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -148,6 +148,7 @@ pub enum Error<'a> { }, InvalidResolve(ResolveError), InvalidForInitializer(Span), + ReservedIdentifierPrefix(Span), UnknownStorageClass(Span), UnknownAttribute(Span), UnknownBuiltin(Span), @@ -337,6 +338,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "not an assignment or function call".into())], notes: vec![], }, + Error::ReservedIdentifierPrefix(ref bad_span) => ParseError { + message: format!("Identifier starts with a reserved prefix: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "invalid identifier".into())], + notes: vec![], + }, Error::UnknownStorageClass(ref bad_span) => ParseError { message: format!("unknown storage class: '{}'", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "unknown storage class".into())], diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index c4e736b46..87c68ec43 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -15,10 +15,10 @@ var global: ColorMaterial_color; fn main_1() { var color: vec4; - let e4: vec4 = global.Color; - color = e4; - let e6: vec4 = color; - o_Target = e6; + let _e4: vec4 = global.Color; + color = _e4; + let _e6: vec4 = color; + o_Target = _e6; return; } @@ -26,6 +26,6 @@ fn main_1() { fn main([[location(0)]] v_Uv: vec2) -> FragmentOutput { v_Uv_1 = v_Uv; main_1(); - let e9: vec4 = o_Target; - return FragmentOutput(e9); + let _e9: vec4 = o_Target; + return FragmentOutput(_e9); } diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 122ed9853..2c7f49a69 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -33,15 +33,15 @@ var gl_Position: vec4; fn main_1() { var position: vec3; - let e10: vec2 = Vertex_Uv_1; - v_Uv = e10; - let e11: vec3 = Vertex_Position_1; - let e12: vec2 = global_2.size; - position = (e11 * vec3(e12, 1.0)); - let e18: mat4x4 = global.ViewProj; - let e19: mat4x4 = global_1.Model; - let e21: vec3 = position; - gl_Position = ((e18 * e19) * vec4(e21, 1.0)); + let _e10: vec2 = Vertex_Uv_1; + v_Uv = _e10; + let _e11: vec3 = Vertex_Position_1; + let _e12: vec2 = global_2.size; + position = (_e11 * vec3(_e12, 1.0)); + let _e18: mat4x4 = global.ViewProj; + let _e19: mat4x4 = global_1.Model; + let _e21: vec3 = position; + gl_Position = ((_e18 * _e19) * vec4(_e21, 1.0)); return; } @@ -51,7 +51,7 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; main_1(); - let e21: vec2 = v_Uv; - let e23: vec4 = gl_Position; - return VertexOutput(e21, e23); + let _e21: vec2 = v_Uv; + let _e23: vec4 = gl_Position; + return VertexOutput(_e21, _e23); } diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index afe639d3a..42fc2398a 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -28,20 +28,20 @@ var global_1: Transform; var gl_Position: vec4; fn main_1() { - let e10: mat4x4 = global_1.Model; - let e11: vec3 = Vertex_Normal_1; - v_Normal = (e10 * vec4(e11, 1.0)).xyz; - let e16: mat4x4 = global_1.Model; - let e26: vec3 = Vertex_Normal_1; - v_Normal = (mat3x3(e16[0].xyz, e16[1].xyz, e16[2].xyz) * e26); - let e28: mat4x4 = global_1.Model; - let e29: vec3 = Vertex_Position_1; - v_Position = (e28 * vec4(e29, 1.0)).xyz; - let e34: vec2 = Vertex_Uv_1; - v_Uv = e34; - let e36: mat4x4 = global.ViewProj; - let e37: vec3 = v_Position; - gl_Position = (e36 * vec4(e37, 1.0)); + let _e10: mat4x4 = global_1.Model; + let _e11: vec3 = Vertex_Normal_1; + v_Normal = (_e10 * vec4(_e11, 1.0)).xyz; + let _e16: mat4x4 = global_1.Model; + let _e26: vec3 = Vertex_Normal_1; + v_Normal = (mat3x3(_e16[0].xyz, _e16[1].xyz, _e16[2].xyz) * _e26); + let _e28: mat4x4 = global_1.Model; + let _e29: vec3 = Vertex_Position_1; + v_Position = (_e28 * vec4(_e29, 1.0)).xyz; + let _e34: vec2 = Vertex_Uv_1; + v_Uv = _e34; + let _e36: mat4x4 = global.ViewProj; + let _e37: vec3 = v_Position; + gl_Position = (_e36 * vec4(_e37, 1.0)); return; } @@ -51,9 +51,9 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; main_1(); - let e23: vec3 = v_Position; - let e25: vec3 = v_Normal; - let e27: vec2 = v_Uv; - let e29: vec4 = gl_Position; - return VertexOutput(e23, e25, e27, e29); + let _e23: vec3 = v_Position; + let _e25: vec3 = v_Normal; + let _e27: vec2 = v_Uv; + let _e29: vec4 = gl_Position; + return VertexOutput(_e23, _e25, _e27, _e29); } diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 4451a7908..0d1b067af 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -13,42 +13,42 @@ fn collatz_iterations(n: u32) -> u32 { n_1 = n; loop { - let e7: u32 = n_1; - if (!((e7 != u32(1)))) { + let _e7: u32 = n_1; + if (!((_e7 != u32(1)))) { break; } { - let e14: u32 = n_1; - if (((f32(e14) % f32(2)) == f32(0))) { + let _e14: u32 = n_1; + if (((f32(_e14) % f32(2)) == f32(0))) { { - let e22: u32 = n_1; - n_1 = (e22 / u32(2)); + let _e22: u32 = n_1; + n_1 = (_e22 / u32(2)); } } else { { - let e27: u32 = n_1; - n_1 = ((u32(3) * e27) + u32(1)); + let _e27: u32 = n_1; + n_1 = ((u32(3) * _e27) + u32(1)); } } - let e33: u32 = i; - i = (e33 + 1u); + let _e33: u32 = i; + i = (_e33 + 1u); } } - let e36: u32 = i; - return e36; + let _e36: u32 = i; + return _e36; } fn main_1() { var index: u32; - let e3: vec3 = gl_GlobalInvocationID; - index = e3.x; - let e6: u32 = index; - let e8: u32 = index; - let e11: u32 = index; - let e13: u32 = global.indices[e11]; - let e14: u32 = collatz_iterations(e13); - global.indices[e6] = e14; + let _e3: vec3 = gl_GlobalInvocationID; + index = _e3.x; + let _e6: u32 = index; + let _e8: u32 = index; + let _e11: u32 = index; + let _e13: u32 = global.indices[_e11]; + let _e14: u32 = collatz_iterations(_e13); + global.indices[_e6] = _e14; return; } diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl index da13932f3..cae6ee450 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl @@ -1,7 +1,7 @@ fn main_1() { var a: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let e1: f32 = f32(1); + let _e1: f32 = f32(1); } [[stage(vertex)]] diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index bbd10113c..08d72d8b4 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -22,15 +22,15 @@ var frag_color: vec4; var gl_Position: vec4; fn main_1() { - let e7: vec4 = color_1; - frag_color = e7; - let e9: mat4x4 = global.view_matrix; - let e10: mat4x4 = global_1.world_matrix; - let e12: vec2 = position_1; - gl_Position = ((e9 * e10) * vec4(e12, 0.0, 1.0)); - let e18: vec4 = gl_Position; - let e20: vec4 = gl_Position; - gl_Position.z = ((e18.z + e20.w) / 2.0); + let _e7: vec4 = color_1; + frag_color = _e7; + let _e9: mat4x4 = global.view_matrix; + let _e10: mat4x4 = global_1.world_matrix; + let _e12: vec2 = position_1; + gl_Position = ((_e9 * _e10) * vec4(_e12, 0.0, 1.0)); + let _e18: vec4 = gl_Position; + let _e20: vec4 = gl_Position; + gl_Position.z = ((_e18.z + _e20.w) / 2.0); return; } @@ -39,7 +39,7 @@ fn main([[location(0)]] position: vec2, [[location(1)]] color: vec4) - position_1 = position; color_1 = color; main_1(); - let e15: vec4 = frag_color; - let e17: vec4 = gl_Position; - return VertexOutput(e15, e17); + let _e15: vec4 = frag_color; + let _e17: vec4 = gl_Position; + return VertexOutput(_e15, _e17); } diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl index 9af904e9a..9173cce46 100644 --- a/tests/out/wgsl/932-for-loop-if-vert.wgsl +++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl @@ -2,15 +2,15 @@ fn main_1() { var i: i32 = 0; loop { - let e2: i32 = i; - if (!((e2 < 1))) { + let _e2: i32 = i; + if (!((_e2 < 1))) { break; } { } continuing { - let e6: i32 = i; - i = (e6 + 1); + let _e6: i32 = i; + i = (_e6 + 1); } } return; diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 21efceff0..77cf0b64a 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -10,8 +10,8 @@ struct Bar { var bar: Bar; fn read_from_private(foo_2: ptr) -> f32 { - let e2: f32 = (*foo_2); - return e2; + let _e2: f32 = (*foo_2); + return _e2; } [[stage(vertex)]] @@ -26,7 +26,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { let b: f32 = bar.matrix[3][0]; let a: i32 = bar.data[(arrayLength((&bar.data)) - 2u)]; let data_pointer: ptr = (&bar.data[0]); - let e25: f32 = read_from_private((&foo_1)); + let _e25: f32 = read_from_private((&foo_1)); bar.matrix[1][2] = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); @@ -42,22 +42,22 @@ fn atomics() { var tmp: i32; let value_1: i32 = atomicLoad((&bar.atom)); - let e6: i32 = atomicAdd((&bar.atom), 5); - tmp = e6; - let e9: i32 = atomicSub((&bar.atom), 5); - tmp = e9; - let e12: i32 = atomicAnd((&bar.atom), 5); - tmp = e12; - let e15: i32 = atomicOr((&bar.atom), 5); - tmp = e15; - let e18: i32 = atomicXor((&bar.atom), 5); - tmp = e18; - let e21: i32 = atomicMin((&bar.atom), 5); - tmp = e21; - let e24: i32 = atomicMax((&bar.atom), 5); - tmp = e24; - let e27: i32 = atomicExchange((&bar.atom), 5); - tmp = e27; + let _e6: i32 = atomicAdd((&bar.atom), 5); + tmp = _e6; + let _e9: i32 = atomicSub((&bar.atom), 5); + tmp = _e9; + let _e12: i32 = atomicAnd((&bar.atom), 5); + tmp = _e12; + let _e15: i32 = atomicOr((&bar.atom), 5); + tmp = _e15; + let _e18: i32 = atomicXor((&bar.atom), 5); + tmp = _e18; + let _e21: i32 = atomicMin((&bar.atom), 5); + tmp = _e21; + let _e24: i32 = atomicMax((&bar.atom), 5); + tmp = _e24; + let _e27: i32 = atomicExchange((&bar.atom), 5); + tmp = _e27; atomicStore((&bar.atom), value_1); return; } diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index b9cc3ac3f..7bc307b89 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -104,13 +104,13 @@ fn pow5_(x: f32) -> f32 { var x2_: f32; x_1 = x; - let e42: f32 = x_1; - let e43: f32 = x_1; - x2_ = (e42 * e43); - let e46: f32 = x2_; - let e47: f32 = x2_; - let e49: f32 = x_1; - return ((e46 * e47) * e49); + let _e42: f32 = x_1; + let _e43: f32 = x_1; + x2_ = (_e42 * _e43); + let _e46: f32 = x2_; + let _e47: f32 = x2_; + let _e49: f32 = x_1; + return ((_e46 * _e47) * _e49); } fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 { @@ -122,20 +122,20 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 distanceSquare_1 = distanceSquare; inverseRangeSquared_1 = inverseRangeSquared; - let e44: f32 = distanceSquare_1; - let e45: f32 = inverseRangeSquared_1; - factor = (e44 * e45); - let e49: f32 = factor; - let e50: f32 = factor; - let e56: f32 = factor; - let e57: f32 = factor; - smoothFactor = clamp((1.0 - (e56 * e57)), 0.0, 1.0); - let e64: f32 = smoothFactor; - let e65: f32 = smoothFactor; - attenuation = (e64 * e65); - let e68: f32 = attenuation; - let e73: f32 = distanceSquare_1; - return ((e68 * 1.0) / max(e73, 0.0010000000474974513)); + let _e44: f32 = distanceSquare_1; + let _e45: f32 = inverseRangeSquared_1; + factor = (_e44 * _e45); + let _e49: f32 = factor; + let _e50: f32 = factor; + let _e56: f32 = factor; + let _e57: f32 = factor; + smoothFactor = clamp((1.0 - (_e56 * _e57)), 0.0, 1.0); + let _e64: f32 = smoothFactor; + let _e65: f32 = smoothFactor; + attenuation = (_e64 * _e65); + let _e68: f32 = attenuation; + let _e73: f32 = distanceSquare_1; + return ((_e68 * 1.0) / max(_e73, 0.0010000000474974513)); } fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { @@ -148,22 +148,22 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { roughness_1 = roughness; NoH_1 = NoH; - let e46: f32 = NoH_1; - let e47: f32 = NoH_1; - oneMinusNoHSquared = (1.0 - (e46 * e47)); - let e51: f32 = NoH_1; - let e52: f32 = roughness_1; - a = (e51 * e52); - let e55: f32 = roughness_1; - let e56: f32 = oneMinusNoHSquared; - let e57: f32 = a; - let e58: f32 = a; - k = (e55 / (e56 + (e57 * e58))); - let e63: f32 = k; - let e64: f32 = k; - d = ((e63 * e64) * (1.0 / 3.1415927410125732)); - let e70: f32 = d; - return e70; + let _e46: f32 = NoH_1; + let _e47: f32 = NoH_1; + oneMinusNoHSquared = (1.0 - (_e46 * _e47)); + let _e51: f32 = NoH_1; + let _e52: f32 = roughness_1; + a = (_e51 * _e52); + let _e55: f32 = roughness_1; + let _e56: f32 = oneMinusNoHSquared; + let _e57: f32 = a; + let _e58: f32 = a; + k = (_e55 / (_e56 + (_e57 * _e58))); + let _e63: f32 = k; + let _e64: f32 = k; + d = ((_e63 * _e64) * (1.0 / 3.1415927410125732)); + let _e70: f32 = d; + return _e70; } fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { @@ -178,38 +178,38 @@ fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { roughness_3 = roughness_2; NoV_1 = NoV; NoL_1 = NoL; - let e46: f32 = roughness_3; - let e47: f32 = roughness_3; - a2_ = (e46 * e47); - let e50: f32 = NoL_1; - let e51: f32 = NoV_1; - let e52: f32 = a2_; - let e53: f32 = NoV_1; - let e56: f32 = NoV_1; - let e58: f32 = a2_; - let e60: f32 = NoV_1; - let e61: f32 = a2_; - let e62: f32 = NoV_1; - let e65: f32 = NoV_1; - let e67: f32 = a2_; - lambdaV = (e50 * sqrt((((e60 - (e61 * e62)) * e65) + e67))); - let e72: f32 = NoV_1; - let e73: f32 = NoL_1; - let e74: f32 = a2_; - let e75: f32 = NoL_1; - let e78: f32 = NoL_1; - let e80: f32 = a2_; - let e82: f32 = NoL_1; - let e83: f32 = a2_; - let e84: f32 = NoL_1; - let e87: f32 = NoL_1; - let e89: f32 = a2_; - lambdaL = (e72 * sqrt((((e82 - (e83 * e84)) * e87) + e89))); - let e95: f32 = lambdaV; - let e96: f32 = lambdaL; - v = (0.5 / (e95 + e96)); - let e100: f32 = v; - return e100; + let _e46: f32 = roughness_3; + let _e47: f32 = roughness_3; + a2_ = (_e46 * _e47); + let _e50: f32 = NoL_1; + let _e51: f32 = NoV_1; + let _e52: f32 = a2_; + let _e53: f32 = NoV_1; + let _e56: f32 = NoV_1; + let _e58: f32 = a2_; + let _e60: f32 = NoV_1; + let _e61: f32 = a2_; + let _e62: f32 = NoV_1; + let _e65: f32 = NoV_1; + let _e67: f32 = a2_; + lambdaV = (_e50 * sqrt((((_e60 - (_e61 * _e62)) * _e65) + _e67))); + let _e72: f32 = NoV_1; + let _e73: f32 = NoL_1; + let _e74: f32 = a2_; + let _e75: f32 = NoL_1; + let _e78: f32 = NoL_1; + let _e80: f32 = a2_; + let _e82: f32 = NoL_1; + let _e83: f32 = a2_; + let _e84: f32 = NoL_1; + let _e87: f32 = NoL_1; + let _e89: f32 = a2_; + lambdaL = (_e72 * sqrt((((_e82 - (_e83 * _e84)) * _e87) + _e89))); + let _e95: f32 = lambdaV; + let _e96: f32 = lambdaL; + v = (0.5 / (_e95 + _e96)); + let _e100: f32 = v; + return _e100; } fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { @@ -218,11 +218,11 @@ fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { f90_1 = f90_; VoH_1 = VoH; - let e45: f32 = f90_1; - let e49: f32 = VoH_1; - let e52: f32 = VoH_1; - let e54: f32 = pow5_((1.0 - e52)); - return (f0_ + ((vec3(e45) - f0_) * e54)); + let _e45: f32 = f90_1; + let _e49: f32 = VoH_1; + let _e52: f32 = VoH_1; + let _e54: f32 = pow5_((1.0 - _e52)); + return (f0_ + ((vec3(_e45) - f0_) * _e54)); } fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 { @@ -233,13 +233,13 @@ fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 { f0_2 = f0_1; f90_3 = f90_2; VoH_3 = VoH_2; - let e46: f32 = f0_2; - let e47: f32 = f90_3; - let e48: f32 = f0_2; - let e51: f32 = VoH_3; - let e54: f32 = VoH_3; - let e56: f32 = pow5_((1.0 - e54)); - return (e46 + ((e47 - e48) * e56)); + let _e46: f32 = f0_2; + let _e47: f32 = f90_3; + let _e48: f32 = f0_2; + let _e51: f32 = VoH_3; + let _e54: f32 = VoH_3; + let _e56: f32 = pow5_((1.0 - _e54)); + return (_e46 + ((_e47 - _e48) * _e56)); } fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { @@ -249,14 +249,14 @@ fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { f0_4 = f0_3; LoH_1 = LoH; - let e49: vec3 = f0_4; - let e62: vec3 = f0_4; - f90_4 = clamp(dot(e62, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); - let e75: vec3 = f0_4; - let e76: f32 = f90_4; - let e77: f32 = LoH_1; - let e78: vec3 = F_Schlick(e75, e76, e77); - return e78; + let _e49: vec3 = f0_4; + let _e62: vec3 = f0_4; + f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); + let _e75: vec3 = f0_4; + let _e76: f32 = f90_4; + let _e77: f32 = LoH_1; + let _e78: vec3 = F_Schlick(_e75, _e76, _e77); + return _e78; } fn specular(f0_5: vec3, roughness_4: f32, h_1: vec3, NoV_2: f32, NoL_2: f32, NoH_2: f32, LoH_2: f32, specularIntensity: f32) -> vec3 { @@ -278,24 +278,24 @@ fn specular(f0_5: vec3, roughness_4: f32, h_1: vec3, NoV_2: f32, NoL_2 NoH_3 = NoH_2; LoH_3 = LoH_2; specularIntensity_1 = specularIntensity; - let e57: f32 = roughness_5; - let e58: f32 = NoH_3; - let e59: f32 = D_GGX(e57, e58, h_1); - D = e59; - let e64: f32 = roughness_5; - let e65: f32 = NoV_3; - let e66: f32 = NoL_3; - let e67: f32 = V_SmithGGXCorrelated(e64, e65, e66); - V = e67; - let e71: vec3 = f0_6; - let e72: f32 = LoH_3; - let e73: vec3 = fresnel(e71, e72); - F = e73; - let e75: f32 = specularIntensity_1; - let e76: f32 = D; - let e78: f32 = V; - let e80: vec3 = F; - return (((e75 * e76) * e78) * e80); + let _e57: f32 = roughness_5; + let _e58: f32 = NoH_3; + let _e59: f32 = D_GGX(_e57, _e58, h_1); + D = _e59; + let _e64: f32 = roughness_5; + let _e65: f32 = NoV_3; + let _e66: f32 = NoL_3; + let _e67: f32 = V_SmithGGXCorrelated(_e64, _e65, _e66); + V = _e67; + let _e71: vec3 = f0_6; + let _e72: f32 = LoH_3; + let _e73: vec3 = fresnel(_e71, _e72); + F = _e73; + let _e75: f32 = specularIntensity_1; + let _e76: f32 = D; + let _e78: f32 = V; + let _e80: vec3 = F; + return (((_e75 * _e76) * _e78) * _e80); } fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { @@ -311,21 +311,21 @@ fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { NoV_5 = NoV_4; NoL_5 = NoL_4; LoH_5 = LoH_4; - let e50: f32 = roughness_7; - let e52: f32 = LoH_5; - let e54: f32 = LoH_5; - f90_5 = (0.5 + (((2.0 * e50) * e52) * e54)); - let e62: f32 = f90_5; - let e63: f32 = NoL_5; - let e64: f32 = F_Schlick_1(1.0, e62, e63); - lightScatter = e64; - let e70: f32 = f90_5; - let e71: f32 = NoV_5; - let e72: f32 = F_Schlick_1(1.0, e70, e71); - viewScatter = e72; - let e74: f32 = lightScatter; - let e75: f32 = viewScatter; - return ((e74 * e75) * (1.0 / 3.1415927410125732)); + let _e50: f32 = roughness_7; + let _e52: f32 = LoH_5; + let _e54: f32 = LoH_5; + f90_5 = (0.5 + (((2.0 * _e50) * _e52) * _e54)); + let _e62: f32 = f90_5; + let _e63: f32 = NoL_5; + let _e64: f32 = F_Schlick_1(1.0, _e62, _e63); + lightScatter = _e64; + let _e70: f32 = f90_5; + let _e71: f32 = NoV_5; + let _e72: f32 = F_Schlick_1(1.0, _e70, _e71); + viewScatter = _e72; + let _e74: f32 = lightScatter; + let _e75: f32 = viewScatter; + return ((_e74 * _e75) * (1.0 / 3.1415927410125732)); } fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 { @@ -341,28 +341,28 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 f0_8 = f0_7; perceptual_roughness_1 = perceptual_roughness; NoV_7 = NoV_6; - let e62: f32 = perceptual_roughness_1; - let e64: vec4 = c0_; - let e66: vec4 = c1_; - r = ((vec4(e62) * e64) + e66); - let e69: vec4 = r; - let e71: vec4 = r; - let e76: f32 = NoV_7; - let e80: f32 = NoV_7; - let e83: vec4 = r; - let e85: vec4 = r; - let e90: f32 = NoV_7; - let e94: f32 = NoV_7; - let e98: vec4 = r; - let e101: vec4 = r; - a004_ = ((min((e83.x * e85.x), exp2((-(9.279999732971191) * e94))) * e98.x) + e101.y); - let e109: f32 = a004_; - let e112: vec4 = r; - AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(e109)) + e112.zw); - let e116: vec3 = f0_8; - let e117: vec2 = AB; - let e121: vec2 = AB; - return ((e116 * vec3(e117.x)) + vec3(e121.y)); + let _e62: f32 = perceptual_roughness_1; + let _e64: vec4 = c0_; + let _e66: vec4 = c1_; + r = ((vec4(_e62) * _e64) + _e66); + let _e69: vec4 = r; + let _e71: vec4 = r; + let _e76: f32 = NoV_7; + let _e80: f32 = NoV_7; + let _e83: vec4 = r; + let _e85: vec4 = r; + let _e90: f32 = NoV_7; + let _e94: f32 = NoV_7; + let _e98: vec4 = r; + let _e101: vec4 = r; + a004_ = ((min((_e83.x * _e85.x), exp2((-(9.279999732971191) * _e94))) * _e98.x) + _e101.y); + let _e109: f32 = a004_; + let _e112: vec4 = r; + AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(_e109)) + _e112.zw); + let _e116: vec3 = f0_8; + let _e117: vec2 = AB; + let _e121: vec2 = AB; + return ((_e116 * vec3(_e117.x)) + vec3(_e121.y)); } fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { @@ -370,20 +370,20 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { var clampedPerceptualRoughness: f32; perceptualRoughness_1 = perceptualRoughness; - let e45: f32 = perceptualRoughness_1; - clampedPerceptualRoughness = clamp(e45, 0.08900000154972076, 1.0); - let e50: f32 = clampedPerceptualRoughness; - let e51: f32 = clampedPerceptualRoughness; - return (e50 * e51); + let _e45: f32 = perceptualRoughness_1; + clampedPerceptualRoughness = clamp(_e45, 0.08900000154972076, 1.0); + let _e50: f32 = clampedPerceptualRoughness; + let _e51: f32 = clampedPerceptualRoughness; + return (_e50 * _e51); } fn reinhard(color: vec3) -> vec3 { var color_1: vec3; color_1 = color; - let e42: vec3 = color_1; - let e45: vec3 = color_1; - return (e42 / (vec3(1.0) + e45)); + let _e42: vec3 = color_1; + let _e45: vec3 = color_1; + return (_e42 / (vec3(1.0) + _e45)); } fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { @@ -393,22 +393,22 @@ fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { color_3 = color_2; max_white_1 = max_white; - let e44: vec3 = color_3; - let e47: vec3 = color_3; - let e48: f32 = max_white_1; - let e49: f32 = max_white_1; - numerator = (e44 * (vec3(1.0) + (e47 / vec3((e48 * e49))))); - let e56: vec3 = numerator; - let e59: vec3 = color_3; - return (e56 / (vec3(1.0) + e59)); + let _e44: vec3 = color_3; + let _e47: vec3 = color_3; + let _e48: f32 = max_white_1; + let _e49: f32 = max_white_1; + numerator = (_e44 * (vec3(1.0) + (_e47 / vec3((_e48 * _e49))))); + let _e56: vec3 = numerator; + let _e59: vec3 = color_3; + return (_e56 / (vec3(1.0) + _e59)); } fn luminance(v_1: vec3) -> f32 { var v_2: vec3; v_2 = v_1; - let e47: vec3 = v_2; - return dot(e47, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); + let _e47: vec3 = v_2; + return dot(_e47, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); } fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { @@ -418,13 +418,13 @@ fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { c_in_1 = c_in; l_out_1 = l_out; - let e45: vec3 = c_in_1; - let e46: f32 = luminance(e45); - l_in = e46; - let e48: vec3 = c_in_1; - let e49: f32 = l_out_1; - let e50: f32 = l_in; - return (e48 * (e49 / e50)); + let _e45: vec3 = c_in_1; + let _e46: f32 = luminance(_e45); + l_in = _e46; + let _e48: vec3 = c_in_1; + let _e49: f32 = l_out_1; + let _e50: f32 = l_in; + return (_e48 * (_e49 / _e50)); } fn reinhard_luminance(color_4: vec3) -> vec3 { @@ -433,16 +433,16 @@ fn reinhard_luminance(color_4: vec3) -> vec3 { var l_new: f32; color_5 = color_4; - let e43: vec3 = color_5; - let e44: f32 = luminance(e43); - l_old = e44; - let e46: f32 = l_old; - let e48: f32 = l_old; - l_new = (e46 / (1.0 + e48)); - let e54: vec3 = color_5; - let e55: f32 = l_new; - let e56: vec3 = change_luminance(e54, e55); - return e56; + let _e43: vec3 = color_5; + let _e44: f32 = luminance(_e43); + l_old = _e44; + let _e46: f32 = l_old; + let _e48: f32 = l_old; + l_new = (_e46 / (1.0 + _e48)); + let _e54: vec3 = color_5; + let _e55: f32 = l_new; + let _e56: vec3 = change_luminance(_e54, _e55); + return _e56; } fn reinhard_extended_luminance(color_6: vec3, max_white_l: f32) -> vec3 { @@ -454,21 +454,21 @@ fn reinhard_extended_luminance(color_6: vec3, max_white_l: f32) -> vec3 = color_7; - let e46: f32 = luminance(e45); - l_old_1 = e46; - let e48: f32 = l_old_1; - let e50: f32 = l_old_1; - let e51: f32 = max_white_l_1; - let e52: f32 = max_white_l_1; - numerator_1 = (e48 * (1.0 + (e50 / (e51 * e52)))); - let e58: f32 = numerator_1; - let e60: f32 = l_old_1; - l_new_1 = (e58 / (1.0 + e60)); - let e66: vec3 = color_7; - let e67: f32 = l_new_1; - let e68: vec3 = change_luminance(e66, e67); - return e68; + let _e45: vec3 = color_7; + let _e46: f32 = luminance(_e45); + l_old_1 = _e46; + let _e48: f32 = l_old_1; + let _e50: f32 = l_old_1; + let _e51: f32 = max_white_l_1; + let _e52: f32 = max_white_l_1; + numerator_1 = (_e48 * (1.0 + (_e50 / (_e51 * _e52)))); + let _e58: f32 = numerator_1; + let _e60: f32 = l_old_1; + l_new_1 = (_e58 / (1.0 + _e60)); + let _e66: vec3 = color_7; + let _e67: f32 = l_new_1; + let _e68: vec3 = change_luminance(_e66, _e67); + return _e68; } fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_1: vec3, R: vec3, F0_: vec3, diffuseColor: vec3) -> vec3 { @@ -506,123 +506,123 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ R_1 = R; F0_1 = F0_; diffuseColor_1 = diffuseColor; - let e56: PointLight = light_1; - let e59: vec3 = v_WorldPosition_1; - light_to_frag = (e56.pos.xyz - e59.xyz); - let e65: vec3 = light_to_frag; - let e66: vec3 = light_to_frag; - distance_square = dot(e65, e66); - let e70: PointLight = light_1; - let e73: f32 = distance_square; - let e74: PointLight = light_1; - let e77: f32 = getDistanceAttenuation(e73, e74.lightParams.x); - rangeAttenuation = e77; - let e79: f32 = roughness_9; - a_1 = e79; - let e81: PointLight = light_1; - radius = e81.lightParams.y; - let e87: vec3 = light_to_frag; - let e88: vec3 = R_1; - let e90: vec3 = R_1; - let e92: vec3 = light_to_frag; - centerToRay = ((dot(e87, e88) * e90) - e92); - let e95: vec3 = light_to_frag; - let e96: vec3 = centerToRay; - let e97: f32 = radius; - let e100: vec3 = centerToRay; - let e101: vec3 = centerToRay; - let e105: vec3 = centerToRay; - let e106: vec3 = centerToRay; - let e112: f32 = radius; - let e115: vec3 = centerToRay; - let e116: vec3 = centerToRay; - let e120: vec3 = centerToRay; - let e121: vec3 = centerToRay; - closestPoint = (e95 + (e96 * clamp((e112 * inverseSqrt(dot(e120, e121))), 0.0, 1.0))); - let e133: vec3 = closestPoint; - let e134: vec3 = closestPoint; - let e138: vec3 = closestPoint; - let e139: vec3 = closestPoint; - LspecLengthInverse = inverseSqrt(dot(e138, e139)); - let e143: f32 = a_1; - let e144: f32 = a_1; - let e145: f32 = radius; - let e148: f32 = LspecLengthInverse; - let e153: f32 = a_1; - let e154: f32 = radius; - let e157: f32 = LspecLengthInverse; - normalizationFactor = (e143 / clamp((e153 + ((e154 * 0.5) * e157)), 0.0, 1.0)); - let e165: f32 = normalizationFactor; - let e166: f32 = normalizationFactor; - specularIntensity_2 = (e165 * e166); - let e169: vec3 = closestPoint; - let e170: f32 = LspecLengthInverse; - L = (e169 * e170); - let e173: vec3 = L; - let e174: vec3 = V_2; - let e176: vec3 = L; - let e177: vec3 = V_2; - H = normalize((e176 + e177)); - let e183: vec3 = N_1; - let e184: vec3 = L; - let e190: vec3 = N_1; - let e191: vec3 = L; - NoL_6 = clamp(dot(e190, e191), 0.0, 1.0); - let e199: vec3 = N_1; - let e200: vec3 = H; - let e206: vec3 = N_1; - let e207: vec3 = H; - NoH_4 = clamp(dot(e206, e207), 0.0, 1.0); - let e215: vec3 = L; - let e216: vec3 = H; - let e222: vec3 = L; - let e223: vec3 = H; - LoH_6 = clamp(dot(e222, e223), 0.0, 1.0); - let e237: vec3 = F0_1; - let e238: f32 = roughness_9; - let e239: vec3 = H; - let e240: f32 = NdotV_1; - let e241: f32 = NoL_6; - let e242: f32 = NoH_4; - let e243: f32 = LoH_6; - let e244: f32 = specularIntensity_2; - let e245: vec3 = specular(e237, e238, e239, e240, e241, e242, e243, e244); - specular_1 = e245; - let e248: vec3 = light_to_frag; - L = normalize(e248); - let e250: vec3 = L; - let e251: vec3 = V_2; - let e253: vec3 = L; - let e254: vec3 = V_2; - H = normalize((e253 + e254)); - let e259: vec3 = N_1; - let e260: vec3 = L; - let e266: vec3 = N_1; - let e267: vec3 = L; - NoL_6 = clamp(dot(e266, e267), 0.0, 1.0); - let e274: vec3 = N_1; - let e275: vec3 = H; - let e281: vec3 = N_1; - let e282: vec3 = H; - NoH_4 = clamp(dot(e281, e282), 0.0, 1.0); - let e289: vec3 = L; - let e290: vec3 = H; - let e296: vec3 = L; - let e297: vec3 = H; - LoH_6 = clamp(dot(e296, e297), 0.0, 1.0); - let e302: vec3 = diffuseColor_1; - let e307: f32 = roughness_9; - let e308: f32 = NdotV_1; - let e309: f32 = NoL_6; - let e310: f32 = LoH_6; - let e311: f32 = Fd_Burley(e307, e308, e309, e310); - diffuse = (e302 * e311); - let e314: vec3 = diffuse; - let e315: vec3 = specular_1; - let e317: PointLight = light_1; - let e321: f32 = rangeAttenuation; - let e322: f32 = NoL_6; - return (((e314 + e315) * e317.color.xyz) * (e321 * e322)); + let _e56: PointLight = light_1; + let _e59: vec3 = v_WorldPosition_1; + light_to_frag = (_e56.pos.xyz - _e59.xyz); + let _e65: vec3 = light_to_frag; + let _e66: vec3 = light_to_frag; + distance_square = dot(_e65, _e66); + let _e70: PointLight = light_1; + let _e73: f32 = distance_square; + let _e74: PointLight = light_1; + let _e77: f32 = getDistanceAttenuation(_e73, _e74.lightParams.x); + rangeAttenuation = _e77; + let _e79: f32 = roughness_9; + a_1 = _e79; + let _e81: PointLight = light_1; + radius = _e81.lightParams.y; + let _e87: vec3 = light_to_frag; + let _e88: vec3 = R_1; + let _e90: vec3 = R_1; + let _e92: vec3 = light_to_frag; + centerToRay = ((dot(_e87, _e88) * _e90) - _e92); + let _e95: vec3 = light_to_frag; + let _e96: vec3 = centerToRay; + let _e97: f32 = radius; + let _e100: vec3 = centerToRay; + let _e101: vec3 = centerToRay; + let _e105: vec3 = centerToRay; + let _e106: vec3 = centerToRay; + let _e112: f32 = radius; + let _e115: vec3 = centerToRay; + let _e116: vec3 = centerToRay; + let _e120: vec3 = centerToRay; + let _e121: vec3 = centerToRay; + closestPoint = (_e95 + (_e96 * clamp((_e112 * inverseSqrt(dot(_e120, _e121))), 0.0, 1.0))); + let _e133: vec3 = closestPoint; + let _e134: vec3 = closestPoint; + let _e138: vec3 = closestPoint; + let _e139: vec3 = closestPoint; + LspecLengthInverse = inverseSqrt(dot(_e138, _e139)); + let _e143: f32 = a_1; + let _e144: f32 = a_1; + let _e145: f32 = radius; + let _e148: f32 = LspecLengthInverse; + let _e153: f32 = a_1; + let _e154: f32 = radius; + let _e157: f32 = LspecLengthInverse; + normalizationFactor = (_e143 / clamp((_e153 + ((_e154 * 0.5) * _e157)), 0.0, 1.0)); + let _e165: f32 = normalizationFactor; + let _e166: f32 = normalizationFactor; + specularIntensity_2 = (_e165 * _e166); + let _e169: vec3 = closestPoint; + let _e170: f32 = LspecLengthInverse; + L = (_e169 * _e170); + let _e173: vec3 = L; + let _e174: vec3 = V_2; + let _e176: vec3 = L; + let _e177: vec3 = V_2; + H = normalize((_e176 + _e177)); + let _e183: vec3 = N_1; + let _e184: vec3 = L; + let _e190: vec3 = N_1; + let _e191: vec3 = L; + NoL_6 = clamp(dot(_e190, _e191), 0.0, 1.0); + let _e199: vec3 = N_1; + let _e200: vec3 = H; + let _e206: vec3 = N_1; + let _e207: vec3 = H; + NoH_4 = clamp(dot(_e206, _e207), 0.0, 1.0); + let _e215: vec3 = L; + let _e216: vec3 = H; + let _e222: vec3 = L; + let _e223: vec3 = H; + LoH_6 = clamp(dot(_e222, _e223), 0.0, 1.0); + let _e237: vec3 = F0_1; + let _e238: f32 = roughness_9; + let _e239: vec3 = H; + let _e240: f32 = NdotV_1; + let _e241: f32 = NoL_6; + let _e242: f32 = NoH_4; + let _e243: f32 = LoH_6; + let _e244: f32 = specularIntensity_2; + let _e245: vec3 = specular(_e237, _e238, _e239, _e240, _e241, _e242, _e243, _e244); + specular_1 = _e245; + let _e248: vec3 = light_to_frag; + L = normalize(_e248); + let _e250: vec3 = L; + let _e251: vec3 = V_2; + let _e253: vec3 = L; + let _e254: vec3 = V_2; + H = normalize((_e253 + _e254)); + let _e259: vec3 = N_1; + let _e260: vec3 = L; + let _e266: vec3 = N_1; + let _e267: vec3 = L; + NoL_6 = clamp(dot(_e266, _e267), 0.0, 1.0); + let _e274: vec3 = N_1; + let _e275: vec3 = H; + let _e281: vec3 = N_1; + let _e282: vec3 = H; + NoH_4 = clamp(dot(_e281, _e282), 0.0, 1.0); + let _e289: vec3 = L; + let _e290: vec3 = H; + let _e296: vec3 = L; + let _e297: vec3 = H; + LoH_6 = clamp(dot(_e296, _e297), 0.0, 1.0); + let _e302: vec3 = diffuseColor_1; + let _e307: f32 = roughness_9; + let _e308: f32 = NdotV_1; + let _e309: f32 = NoL_6; + let _e310: f32 = LoH_6; + let _e311: f32 = Fd_Burley(_e307, _e308, _e309, _e310); + diffuse = (_e302 * _e311); + let _e314: vec3 = diffuse; + let _e315: vec3 = specular_1; + let _e317: PointLight = light_1; + let _e321: f32 = rangeAttenuation; + let _e322: f32 = NoL_6; + return (((_e314 + _e315) * _e317.color.xyz) * (_e321 * _e322)); } fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: vec3, view: vec3, R_2: vec3, F0_2: vec3, diffuseColor_2: vec3) -> vec3 { @@ -651,50 +651,50 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: R_3 = R_2; F0_3 = F0_2; diffuseColor_3 = diffuseColor_2; - let e56: DirectionalLight = light_3; - incident_light = e56.direction.xyz; - let e60: vec3 = incident_light; - let e61: vec3 = view_1; - let e63: vec3 = incident_light; - let e64: vec3 = view_1; - half_vector = normalize((e63 + e64)); - let e70: vec3 = normal_1; - let e71: vec3 = incident_light; - let e77: vec3 = normal_1; - let e78: vec3 = incident_light; - NoL_7 = clamp(dot(e77, e78), 0.0, 1.0); - let e86: vec3 = normal_1; - let e87: vec3 = half_vector; - let e93: vec3 = normal_1; - let e94: vec3 = half_vector; - NoH_5 = clamp(dot(e93, e94), 0.0, 1.0); - let e102: vec3 = incident_light; - let e103: vec3 = half_vector; - let e109: vec3 = incident_light; - let e110: vec3 = half_vector; - LoH_7 = clamp(dot(e109, e110), 0.0, 1.0); - let e116: vec3 = diffuseColor_3; - let e121: f32 = roughness_11; - let e122: f32 = NdotV_3; - let e123: f32 = NoL_7; - let e124: f32 = LoH_7; - let e125: f32 = Fd_Burley(e121, e122, e123, e124); - diffuse_1 = (e116 * e125); - let e138: vec3 = F0_3; - let e139: f32 = roughness_11; - let e140: vec3 = half_vector; - let e141: f32 = NdotV_3; - let e142: f32 = NoL_7; - let e143: f32 = NoH_5; - let e144: f32 = LoH_7; - let e145: f32 = specularIntensity_3; - let e146: vec3 = specular(e138, e139, e140, e141, e142, e143, e144, e145); - specular_2 = e146; - let e148: vec3 = specular_2; - let e149: vec3 = diffuse_1; - let e151: DirectionalLight = light_3; - let e155: f32 = NoL_7; - return (((e148 + e149) * e151.color.xyz) * e155); + let _e56: DirectionalLight = light_3; + incident_light = _e56.direction.xyz; + let _e60: vec3 = incident_light; + let _e61: vec3 = view_1; + let _e63: vec3 = incident_light; + let _e64: vec3 = view_1; + half_vector = normalize((_e63 + _e64)); + let _e70: vec3 = normal_1; + let _e71: vec3 = incident_light; + let _e77: vec3 = normal_1; + let _e78: vec3 = incident_light; + NoL_7 = clamp(dot(_e77, _e78), 0.0, 1.0); + let _e86: vec3 = normal_1; + let _e87: vec3 = half_vector; + let _e93: vec3 = normal_1; + let _e94: vec3 = half_vector; + NoH_5 = clamp(dot(_e93, _e94), 0.0, 1.0); + let _e102: vec3 = incident_light; + let _e103: vec3 = half_vector; + let _e109: vec3 = incident_light; + let _e110: vec3 = half_vector; + LoH_7 = clamp(dot(_e109, _e110), 0.0, 1.0); + let _e116: vec3 = diffuseColor_3; + let _e121: f32 = roughness_11; + let _e122: f32 = NdotV_3; + let _e123: f32 = NoL_7; + let _e124: f32 = LoH_7; + let _e125: f32 = Fd_Burley(_e121, _e122, _e123, _e124); + diffuse_1 = (_e116 * _e125); + let _e138: vec3 = F0_3; + let _e139: f32 = roughness_11; + let _e140: vec3 = half_vector; + let _e141: f32 = NdotV_3; + let _e142: f32 = NoL_7; + let _e143: f32 = NoH_5; + let _e144: f32 = LoH_7; + let _e145: f32 = specularIntensity_3; + let _e146: vec3 = specular(_e138, _e139, _e140, _e141, _e142, _e143, _e144, _e145); + specular_2 = _e146; + let _e148: vec3 = specular_2; + let _e149: vec3 = diffuse_1; + let _e151: DirectionalLight = light_3; + let _e155: f32 = NoL_7; + return (((_e148 + _e149) * _e151.color.xyz) * _e155); } fn main_1() { @@ -720,186 +720,186 @@ fn main_1() { var diffuse_ambient: vec3; var specular_ambient: vec3; - let e40: vec4 = global_3.base_color; - output_color = e40; - let e42: vec4 = output_color; - let e44: vec2 = v_Uv_1; - let e45: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, e44); - output_color = (e42 * e45); - let e48: vec2 = v_Uv_1; - let e49: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, e48); - metallic_roughness = e49; - let e51: f32 = global_5.metallic; - let e52: vec4 = metallic_roughness; - metallic = (e51 * e52.z); - let e56: f32 = global_4.perceptual_roughness; - let e57: vec4 = metallic_roughness; - perceptual_roughness_2 = (e56 * e57.y); - let e62: f32 = perceptual_roughness_2; - let e63: f32 = perceptualRoughnessToRoughness(e62); - roughness_12 = e63; - let e66: vec3 = v_WorldNormal_1; - N_2 = normalize(e66); - let e69: vec4 = v_WorldTangent_1; - let e71: vec4 = v_WorldTangent_1; - T = normalize(e71.xyz); - let e77: vec3 = N_2; - let e78: vec3 = T; - let e80: vec4 = v_WorldTangent_1; - B = (cross(e77, e78) * e80.w); - let e85: bool = gl_FrontFacing; - let e86: vec3 = N_2; - let e87: vec3 = N_2; - N_2 = select(-(e87), e86, e85); - let e90: bool = gl_FrontFacing; - let e91: vec3 = T; - let e92: vec3 = T; - T = select(-(e92), e91, e90); - let e95: bool = gl_FrontFacing; - let e96: vec3 = B; - let e97: vec3 = B; - B = select(-(e97), e96, e95); - let e100: vec3 = T; - let e101: vec3 = B; - let e102: vec3 = N_2; - TBN = mat3x3(vec3(e100.x, e100.y, e100.z), vec3(e101.x, e101.y, e101.z), vec3(e102.x, e102.y, e102.z)); - let e117: mat3x3 = TBN; - let e119: vec2 = v_Uv_1; - let e120: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e119); - let e128: vec2 = v_Uv_1; - let e129: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e128); - N_2 = (e117 * normalize(((e129.xyz * 2.0) - vec3(1.0)))); - let e139: vec2 = v_Uv_1; - let e140: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, e139); - occlusion = e140.x; - let e143: vec4 = global_7.emissive; - emissive = e143; - let e145: vec4 = emissive; - let e147: vec4 = emissive; - let e150: vec2 = v_Uv_1; - let e151: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, e150); - let e153: vec3 = (e147.xyz * e151.xyz); - emissive.x = e153.x; - emissive.y = e153.y; - emissive.z = e153.z; - let e160: vec4 = global_1.CameraPos; - let e162: vec3 = v_WorldPosition_1; - let e165: vec4 = global_1.CameraPos; - let e167: vec3 = v_WorldPosition_1; - V_3 = normalize((e165.xyz - e167.xyz)); - let e174: vec3 = N_2; - let e175: vec3 = V_3; - let e180: vec3 = N_2; - let e181: vec3 = V_3; - NdotV_4 = max(dot(e180, e181), 0.0010000000474974513); - let e187: f32 = global_6.reflectance; - let e189: f32 = global_6.reflectance; - let e192: f32 = metallic; - let e196: vec4 = output_color; - let e198: f32 = metallic; - F0_4 = (vec3((((0.1599999964237213 * e187) * e189) * (1.0 - e192))) + (e196.xyz * vec3(e198))); - let e203: vec4 = output_color; - let e206: f32 = metallic; - diffuseColor_4 = (e203.xyz * vec3((1.0 - e206))); - let e211: vec3 = V_3; - let e214: vec3 = V_3; - let e216: vec3 = N_2; - R_4 = reflect(-(e214), e216); + let _e40: vec4 = global_3.base_color; + output_color = _e40; + let _e42: vec4 = output_color; + let _e44: vec2 = v_Uv_1; + let _e45: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e44); + output_color = (_e42 * _e45); + let _e48: vec2 = v_Uv_1; + let _e49: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e48); + metallic_roughness = _e49; + let _e51: f32 = global_5.metallic; + let _e52: vec4 = metallic_roughness; + metallic = (_e51 * _e52.z); + let _e56: f32 = global_4.perceptual_roughness; + let _e57: vec4 = metallic_roughness; + perceptual_roughness_2 = (_e56 * _e57.y); + let _e62: f32 = perceptual_roughness_2; + let _e63: f32 = perceptualRoughnessToRoughness(_e62); + roughness_12 = _e63; + let _e66: vec3 = v_WorldNormal_1; + N_2 = normalize(_e66); + let _e69: vec4 = v_WorldTangent_1; + let _e71: vec4 = v_WorldTangent_1; + T = normalize(_e71.xyz); + let _e77: vec3 = N_2; + let _e78: vec3 = T; + let _e80: vec4 = v_WorldTangent_1; + B = (cross(_e77, _e78) * _e80.w); + let _e85: bool = gl_FrontFacing; + let _e86: vec3 = N_2; + let _e87: vec3 = N_2; + N_2 = select(-(_e87), _e86, _e85); + let _e90: bool = gl_FrontFacing; + let _e91: vec3 = T; + let _e92: vec3 = T; + T = select(-(_e92), _e91, _e90); + let _e95: bool = gl_FrontFacing; + let _e96: vec3 = B; + let _e97: vec3 = B; + B = select(-(_e97), _e96, _e95); + let _e100: vec3 = T; + let _e101: vec3 = B; + let _e102: vec3 = N_2; + TBN = mat3x3(vec3(_e100.x, _e100.y, _e100.z), vec3(_e101.x, _e101.y, _e101.z), vec3(_e102.x, _e102.y, _e102.z)); + let _e117: mat3x3 = TBN; + let _e119: vec2 = v_Uv_1; + let _e120: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e119); + let _e128: vec2 = v_Uv_1; + let _e129: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e128); + N_2 = (_e117 * normalize(((_e129.xyz * 2.0) - vec3(1.0)))); + let _e139: vec2 = v_Uv_1; + let _e140: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e139); + occlusion = _e140.x; + let _e143: vec4 = global_7.emissive; + emissive = _e143; + let _e145: vec4 = emissive; + let _e147: vec4 = emissive; + let _e150: vec2 = v_Uv_1; + let _e151: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e150); + let _e153: vec3 = (_e147.xyz * _e151.xyz); + emissive.x = _e153.x; + emissive.y = _e153.y; + emissive.z = _e153.z; + let _e160: vec4 = global_1.CameraPos; + let _e162: vec3 = v_WorldPosition_1; + let _e165: vec4 = global_1.CameraPos; + let _e167: vec3 = v_WorldPosition_1; + V_3 = normalize((_e165.xyz - _e167.xyz)); + let _e174: vec3 = N_2; + let _e175: vec3 = V_3; + let _e180: vec3 = N_2; + let _e181: vec3 = V_3; + NdotV_4 = max(dot(_e180, _e181), 0.0010000000474974513); + let _e187: f32 = global_6.reflectance; + let _e189: f32 = global_6.reflectance; + let _e192: f32 = metallic; + let _e196: vec4 = output_color; + let _e198: f32 = metallic; + F0_4 = (vec3((((0.1599999964237213 * _e187) * _e189) * (1.0 - _e192))) + (_e196.xyz * vec3(_e198))); + let _e203: vec4 = output_color; + let _e206: f32 = metallic; + diffuseColor_4 = (_e203.xyz * vec3((1.0 - _e206))); + let _e211: vec3 = V_3; + let _e214: vec3 = V_3; + let _e216: vec3 = N_2; + R_4 = reflect(-(_e214), _e216); loop { - let e224: i32 = i; - let e225: vec4 = global_2.NumLights; - let e229: i32 = i; - if (!(((e224 < i32(e225.x)) && (e229 < 10)))) { + let _e224: i32 = i; + let _e225: vec4 = global_2.NumLights; + let _e229: i32 = i; + if (!(((_e224 < i32(_e225.x)) && (_e229 < 10)))) { break; } { - let e236: vec3 = light_accum; - let e237: i32 = i; - let e247: i32 = i; - let e249: PointLight = global_2.PointLights[e247]; - let e250: f32 = roughness_12; - let e251: f32 = NdotV_4; - let e252: vec3 = N_2; - let e253: vec3 = V_3; - let e254: vec3 = R_4; - let e255: vec3 = F0_4; - let e256: vec3 = diffuseColor_4; - let e257: vec3 = point_light(e249, e250, e251, e252, e253, e254, e255, e256); - light_accum = (e236 + e257); + let _e236: vec3 = light_accum; + let _e237: i32 = i; + let _e247: i32 = i; + let _e249: PointLight = global_2.PointLights[_e247]; + let _e250: f32 = roughness_12; + let _e251: f32 = NdotV_4; + let _e252: vec3 = N_2; + let _e253: vec3 = V_3; + let _e254: vec3 = R_4; + let _e255: vec3 = F0_4; + let _e256: vec3 = diffuseColor_4; + let _e257: vec3 = point_light(_e249, _e250, _e251, _e252, _e253, _e254, _e255, _e256); + light_accum = (_e236 + _e257); } continuing { - let e233: i32 = i; - i = (e233 + 1); + let _e233: i32 = i; + i = (_e233 + 1); } } loop { - let e261: i32 = i_1; - let e262: vec4 = global_2.NumLights; - let e266: i32 = i_1; - if (!(((e261 < i32(e262.y)) && (e266 < 1)))) { + let _e261: i32 = i_1; + let _e262: vec4 = global_2.NumLights; + let _e266: i32 = i_1; + if (!(((_e261 < i32(_e262.y)) && (_e266 < 1)))) { break; } { - let e273: vec3 = light_accum; - let e274: i32 = i_1; - let e284: i32 = i_1; - let e286: DirectionalLight = global_2.DirectionalLights[e284]; - let e287: f32 = roughness_12; - let e288: f32 = NdotV_4; - let e289: vec3 = N_2; - let e290: vec3 = V_3; - let e291: vec3 = R_4; - let e292: vec3 = F0_4; - let e293: vec3 = diffuseColor_4; - let e294: vec3 = dir_light(e286, e287, e288, e289, e290, e291, e292, e293); - light_accum = (e273 + e294); + let _e273: vec3 = light_accum; + let _e274: i32 = i_1; + let _e284: i32 = i_1; + let _e286: DirectionalLight = global_2.DirectionalLights[_e284]; + let _e287: f32 = roughness_12; + let _e288: f32 = NdotV_4; + let _e289: vec3 = N_2; + let _e290: vec3 = V_3; + let _e291: vec3 = R_4; + let _e292: vec3 = F0_4; + let _e293: vec3 = diffuseColor_4; + let _e294: vec3 = dir_light(_e286, _e287, _e288, _e289, _e290, _e291, _e292, _e293); + light_accum = (_e273 + _e294); } continuing { - let e270: i32 = i_1; - i_1 = (e270 + 1); + let _e270: i32 = i_1; + i_1 = (_e270 + 1); } } - let e299: vec3 = diffuseColor_4; - let e301: f32 = NdotV_4; - let e302: vec3 = EnvBRDFApprox(e299, 1.0, e301); - diffuse_ambient = e302; - let e307: vec3 = F0_4; - let e308: f32 = perceptual_roughness_2; - let e309: f32 = NdotV_4; - let e310: vec3 = EnvBRDFApprox(e307, e308, e309); - specular_ambient = e310; - let e312: vec4 = output_color; - let e314: vec3 = light_accum; - output_color.x = e314.x; - output_color.y = e314.y; - output_color.z = e314.z; - let e321: vec4 = output_color; - let e323: vec4 = output_color; - let e325: vec3 = diffuse_ambient; - let e326: vec3 = specular_ambient; - let e328: vec4 = global_2.AmbientColor; - let e331: f32 = occlusion; - let e333: vec3 = (e323.xyz + (((e325 + e326) * e328.xyz) * e331)); - output_color.x = e333.x; - output_color.y = e333.y; - output_color.z = e333.z; - let e340: vec4 = output_color; - let e342: vec4 = output_color; - let e344: vec4 = emissive; - let e346: vec4 = output_color; - let e349: vec3 = (e342.xyz + (e344.xyz * e346.w)); - output_color.x = e349.x; - output_color.y = e349.y; - output_color.z = e349.z; - let e356: vec4 = output_color; - let e358: vec4 = output_color; - let e360: vec4 = output_color; - let e362: vec3 = reinhard_luminance(e360.xyz); - output_color.x = e362.x; - output_color.y = e362.y; - output_color.z = e362.z; - let e369: vec4 = output_color; - o_Target = e369; + let _e299: vec3 = diffuseColor_4; + let _e301: f32 = NdotV_4; + let _e302: vec3 = EnvBRDFApprox(_e299, 1.0, _e301); + diffuse_ambient = _e302; + let _e307: vec3 = F0_4; + let _e308: f32 = perceptual_roughness_2; + let _e309: f32 = NdotV_4; + let _e310: vec3 = EnvBRDFApprox(_e307, _e308, _e309); + specular_ambient = _e310; + let _e312: vec4 = output_color; + let _e314: vec3 = light_accum; + output_color.x = _e314.x; + output_color.y = _e314.y; + output_color.z = _e314.z; + let _e321: vec4 = output_color; + let _e323: vec4 = output_color; + let _e325: vec3 = diffuse_ambient; + let _e326: vec3 = specular_ambient; + let _e328: vec4 = global_2.AmbientColor; + let _e331: f32 = occlusion; + let _e333: vec3 = (_e323.xyz + (((_e325 + _e326) * _e328.xyz) * _e331)); + output_color.x = _e333.x; + output_color.y = _e333.y; + output_color.z = _e333.z; + let _e340: vec4 = output_color; + let _e342: vec4 = output_color; + let _e344: vec4 = emissive; + let _e346: vec4 = output_color; + let _e349: vec3 = (_e342.xyz + (_e344.xyz * _e346.w)); + output_color.x = _e349.x; + output_color.y = _e349.y; + output_color.z = _e349.z; + let _e356: vec4 = output_color; + let _e358: vec4 = output_color; + let _e360: vec4 = output_color; + let _e362: vec3 = reinhard_luminance(_e360.xyz); + output_color.x = _e362.x; + output_color.y = _e362.y; + output_color.z = _e362.z; + let _e369: vec4 = output_color; + o_Target = _e369; return; } @@ -911,6 +911,6 @@ fn main([[location(0)]] v_WorldPosition: vec3, [[location(1)]] v_WorldNorma v_WorldTangent_1 = v_WorldTangent; gl_FrontFacing = param; main_1(); - let e72: vec4 = o_Target; - return FragmentOutput(e72); + let _e72: vec4 = o_Target; + return FragmentOutput(_e72); } diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 01ed0b59f..c0bacfd19 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -33,23 +33,23 @@ var gl_Position: vec4; fn main_1() { var world_position: vec4; - let e12: mat4x4 = global_1.Model; - let e13: vec3 = Vertex_Position_1; - world_position = (e12 * vec4(e13, 1.0)); - let e18: vec4 = world_position; - v_WorldPosition = e18.xyz; - let e20: mat4x4 = global_1.Model; - let e30: vec3 = Vertex_Normal_1; - v_WorldNormal = (mat3x3(e20[0].xyz, e20[1].xyz, e20[2].xyz) * e30); - let e32: vec2 = Vertex_Uv_1; - v_Uv = e32; - let e33: mat4x4 = global_1.Model; - let e43: vec4 = Vertex_Tangent_1; - let e46: vec4 = Vertex_Tangent_1; - v_WorldTangent = vec4((mat3x3(e33[0].xyz, e33[1].xyz, e33[2].xyz) * e43.xyz), e46.w); - let e50: mat4x4 = global.ViewProj; - let e51: vec4 = world_position; - gl_Position = (e50 * e51); + let _e12: mat4x4 = global_1.Model; + let _e13: vec3 = Vertex_Position_1; + world_position = (_e12 * vec4(_e13, 1.0)); + let _e18: vec4 = world_position; + v_WorldPosition = _e18.xyz; + let _e20: mat4x4 = global_1.Model; + let _e30: vec3 = Vertex_Normal_1; + v_WorldNormal = (mat3x3(_e20[0].xyz, _e20[1].xyz, _e20[2].xyz) * _e30); + let _e32: vec2 = Vertex_Uv_1; + v_Uv = _e32; + let _e33: mat4x4 = global_1.Model; + let _e43: vec4 = Vertex_Tangent_1; + let _e46: vec4 = Vertex_Tangent_1; + v_WorldTangent = vec4((mat3x3(_e33[0].xyz, _e33[1].xyz, _e33[2].xyz) * _e43.xyz), _e46.w); + let _e50: mat4x4 = global.ViewProj; + let _e51: vec4 = world_position; + gl_Position = (_e50 * _e51); return; } @@ -60,10 +60,10 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Uv_1 = Vertex_Uv; Vertex_Tangent_1 = Vertex_Tangent; main_1(); - let e29: vec3 = v_WorldPosition; - let e31: vec3 = v_WorldNormal; - let e33: vec2 = v_Uv; - let e35: vec4 = v_WorldTangent; - let e37: vec4 = gl_Position; - return VertexOutput(e29, e31, e33, e35, e37); + let _e29: vec3 = v_WorldPosition; + let _e31: vec3 = v_WorldNormal; + let _e33: vec2 = v_Uv; + let _e35: vec4 = v_WorldTangent; + let _e37: vec4 = gl_Position; + return VertexOutput(_e29, _e31, _e33, _e35, _e37); } diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index c4054d8e3..306806ca9 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -19,65 +19,65 @@ fn main() { u4_ = vec4(0u); f2_ = vec2(0.0); f4_ = vec4(0.0); - let e28: vec4 = f4_; - u = pack4x8snorm(e28); - let e30: vec4 = f4_; - u = pack4x8unorm(e30); - let e32: vec2 = f2_; - u = pack2x16snorm(e32); - let e34: vec2 = f2_; - u = pack2x16unorm(e34); - let e36: vec2 = f2_; - u = pack2x16float(e36); - let e38: u32 = u; - f4_ = unpack4x8snorm(e38); - let e40: u32 = u; - f4_ = unpack4x8unorm(e40); - let e42: u32 = u; - f2_ = unpack2x16snorm(e42); - let e44: u32 = u; - f2_ = unpack2x16unorm(e44); - let e46: u32 = u; - f2_ = unpack2x16float(e46); - let e48: i32 = i; - let e49: i32 = i; - i = insertBits(e48, e49, 5u, 10u); - let e53: vec2 = i2_; - let e54: vec2 = i2_; - i2_ = insertBits(e53, e54, 5u, 10u); - let e58: vec3 = i3_; - let e59: vec3 = i3_; - i3_ = insertBits(e58, e59, 5u, 10u); - let e63: vec4 = i4_; - let e64: vec4 = i4_; - i4_ = insertBits(e63, e64, 5u, 10u); - let e68: u32 = u; - let e69: u32 = u; - u = insertBits(e68, e69, 5u, 10u); - let e73: vec2 = u2_; - let e74: vec2 = u2_; - u2_ = insertBits(e73, e74, 5u, 10u); - let e78: vec3 = u3_; - let e79: vec3 = u3_; - u3_ = insertBits(e78, e79, 5u, 10u); - let e83: vec4 = u4_; - let e84: vec4 = u4_; - u4_ = insertBits(e83, e84, 5u, 10u); - let e88: i32 = i; - i = extractBits(e88, 5u, 10u); - let e92: vec2 = i2_; - i2_ = extractBits(e92, 5u, 10u); - let e96: vec3 = i3_; - i3_ = extractBits(e96, 5u, 10u); - let e100: vec4 = i4_; - i4_ = extractBits(e100, 5u, 10u); - let e104: u32 = u; - u = extractBits(e104, 5u, 10u); - let e108: vec2 = u2_; - u2_ = extractBits(e108, 5u, 10u); - let e112: vec3 = u3_; - u3_ = extractBits(e112, 5u, 10u); - let e116: vec4 = u4_; - u4_ = extractBits(e116, 5u, 10u); + let _e28: vec4 = f4_; + u = pack4x8snorm(_e28); + let _e30: vec4 = f4_; + u = pack4x8unorm(_e30); + let _e32: vec2 = f2_; + u = pack2x16snorm(_e32); + let _e34: vec2 = f2_; + u = pack2x16unorm(_e34); + let _e36: vec2 = f2_; + u = pack2x16float(_e36); + let _e38: u32 = u; + f4_ = unpack4x8snorm(_e38); + let _e40: u32 = u; + f4_ = unpack4x8unorm(_e40); + let _e42: u32 = u; + f2_ = unpack2x16snorm(_e42); + let _e44: u32 = u; + f2_ = unpack2x16unorm(_e44); + let _e46: u32 = u; + f2_ = unpack2x16float(_e46); + let _e48: i32 = i; + let _e49: i32 = i; + i = insertBits(_e48, _e49, 5u, 10u); + let _e53: vec2 = i2_; + let _e54: vec2 = i2_; + i2_ = insertBits(_e53, _e54, 5u, 10u); + let _e58: vec3 = i3_; + let _e59: vec3 = i3_; + i3_ = insertBits(_e58, _e59, 5u, 10u); + let _e63: vec4 = i4_; + let _e64: vec4 = i4_; + i4_ = insertBits(_e63, _e64, 5u, 10u); + let _e68: u32 = u; + let _e69: u32 = u; + u = insertBits(_e68, _e69, 5u, 10u); + let _e73: vec2 = u2_; + let _e74: vec2 = u2_; + u2_ = insertBits(_e73, _e74, 5u, 10u); + let _e78: vec3 = u3_; + let _e79: vec3 = u3_; + u3_ = insertBits(_e78, _e79, 5u, 10u); + let _e83: vec4 = u4_; + let _e84: vec4 = u4_; + u4_ = insertBits(_e83, _e84, 5u, 10u); + let _e88: i32 = i; + i = extractBits(_e88, 5u, 10u); + let _e92: vec2 = i2_; + i2_ = extractBits(_e92, 5u, 10u); + let _e96: vec3 = i3_; + i3_ = extractBits(_e96, 5u, 10u); + let _e100: vec4 = i4_; + i4_ = extractBits(_e100, 5u, 10u); + let _e104: u32 = u; + u = extractBits(_e104, 5u, 10u); + let _e108: vec2 = u2_; + u2_ = extractBits(_e108, 5u, 10u); + let _e112: vec3 = u3_; + u3_ = extractBits(_e112, 5u, 10u); + let _e116: vec4 = u4_; + u4_ = extractBits(_e116, 5u, 10u); return; } diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 3efc01918..a555c9910 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -10,66 +10,66 @@ fn main_1() { var f2_: vec2 = vec2(0.0, 0.0); var f4_: vec4 = vec4(0.0, 0.0, 0.0, 0.0); - let e33: vec4 = f4_; - u = pack4x8snorm(e33); - let e36: vec4 = f4_; - u = pack4x8unorm(e36); - let e39: vec2 = f2_; - u = pack2x16unorm(e39); - let e42: vec2 = f2_; - u = pack2x16snorm(e42); - let e45: vec2 = f2_; - u = pack2x16float(e45); - let e48: u32 = u; - f4_ = unpack4x8snorm(e48); - let e51: u32 = u; - f4_ = unpack4x8unorm(e51); - let e54: u32 = u; - f2_ = unpack2x16snorm(e54); - let e57: u32 = u; - f2_ = unpack2x16unorm(e57); - let e60: u32 = u; - f2_ = unpack2x16float(e60); - let e66: i32 = i; - let e67: i32 = i; - i = insertBits(e66, e67, u32(5), u32(10)); - let e77: vec2 = i2_; - let e78: vec2 = i2_; - i2_ = insertBits(e77, e78, u32(5), u32(10)); - let e88: vec3 = i3_; - let e89: vec3 = i3_; - i3_ = insertBits(e88, e89, u32(5), u32(10)); - let e99: vec4 = i4_; - let e100: vec4 = i4_; - i4_ = insertBits(e99, e100, u32(5), u32(10)); - let e110: u32 = u; - let e111: u32 = u; - u = insertBits(e110, e111, u32(5), u32(10)); - let e121: vec2 = u2_; - let e122: vec2 = u2_; - u2_ = insertBits(e121, e122, u32(5), u32(10)); - let e132: vec3 = u3_; - let e133: vec3 = u3_; - u3_ = insertBits(e132, e133, u32(5), u32(10)); - let e143: vec4 = u4_; - let e144: vec4 = u4_; - u4_ = insertBits(e143, e144, u32(5), u32(10)); - let e153: i32 = i; - i = extractBits(e153, u32(5), u32(10)); - let e162: vec2 = i2_; - i2_ = extractBits(e162, u32(5), u32(10)); - let e171: vec3 = i3_; - i3_ = extractBits(e171, u32(5), u32(10)); - let e180: vec4 = i4_; - i4_ = extractBits(e180, u32(5), u32(10)); - let e189: u32 = u; - u = extractBits(e189, u32(5), u32(10)); - let e198: vec2 = u2_; - u2_ = extractBits(e198, u32(5), u32(10)); - let e207: vec3 = u3_; - u3_ = extractBits(e207, u32(5), u32(10)); - let e216: vec4 = u4_; - u4_ = extractBits(e216, u32(5), u32(10)); + let _e33: vec4 = f4_; + u = pack4x8snorm(_e33); + let _e36: vec4 = f4_; + u = pack4x8unorm(_e36); + let _e39: vec2 = f2_; + u = pack2x16unorm(_e39); + let _e42: vec2 = f2_; + u = pack2x16snorm(_e42); + let _e45: vec2 = f2_; + u = pack2x16float(_e45); + let _e48: u32 = u; + f4_ = unpack4x8snorm(_e48); + let _e51: u32 = u; + f4_ = unpack4x8unorm(_e51); + let _e54: u32 = u; + f2_ = unpack2x16snorm(_e54); + let _e57: u32 = u; + f2_ = unpack2x16unorm(_e57); + let _e60: u32 = u; + f2_ = unpack2x16float(_e60); + let _e66: i32 = i; + let _e67: i32 = i; + i = insertBits(_e66, _e67, u32(5), u32(10)); + let _e77: vec2 = i2_; + let _e78: vec2 = i2_; + i2_ = insertBits(_e77, _e78, u32(5), u32(10)); + let _e88: vec3 = i3_; + let _e89: vec3 = i3_; + i3_ = insertBits(_e88, _e89, u32(5), u32(10)); + let _e99: vec4 = i4_; + let _e100: vec4 = i4_; + i4_ = insertBits(_e99, _e100, u32(5), u32(10)); + let _e110: u32 = u; + let _e111: u32 = u; + u = insertBits(_e110, _e111, u32(5), u32(10)); + let _e121: vec2 = u2_; + let _e122: vec2 = u2_; + u2_ = insertBits(_e121, _e122, u32(5), u32(10)); + let _e132: vec3 = u3_; + let _e133: vec3 = u3_; + u3_ = insertBits(_e132, _e133, u32(5), u32(10)); + let _e143: vec4 = u4_; + let _e144: vec4 = u4_; + u4_ = insertBits(_e143, _e144, u32(5), u32(10)); + let _e153: i32 = i; + i = extractBits(_e153, u32(5), u32(10)); + let _e162: vec2 = i2_; + i2_ = extractBits(_e162, u32(5), u32(10)); + let _e171: vec3 = i3_; + i3_ = extractBits(_e171, u32(5), u32(10)); + let _e180: vec4 = i4_; + i4_ = extractBits(_e180, u32(5), u32(10)); + let _e189: u32 = u; + u = extractBits(_e189, u32(5), u32(10)); + let _e198: vec2 = u2_; + u2_ = extractBits(_e198, u32(5), u32(10)); + let _e207: vec3 = u3_; + u3_ = extractBits(_e207, u32(5), u32(10)); + let _e216: vec4 = u4_; + u4_ = extractBits(_e216, u32(5), u32(10)); return; } diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 902aa4edc..a0e5e8eab 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -45,109 +45,109 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { if ((index >= NUM_PARTICLES)) { return; } - let e10: vec2 = particlesSrc.particles[index].pos; - vPos = e10; - let e15: vec2 = particlesSrc.particles[index].vel; - vVel = e15; + let _e10: vec2 = particlesSrc.particles[index].pos; + vPos = _e10; + let _e15: vec2 = particlesSrc.particles[index].vel; + vVel = _e15; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); loop { - let e37: u32 = i; - if ((e37 >= NUM_PARTICLES)) { + let _e37: u32 = i; + if ((_e37 >= NUM_PARTICLES)) { break; } - let e39: u32 = i; - if ((e39 == index)) { + let _e39: u32 = i; + if ((_e39 == index)) { continue; } - let e42: u32 = i; - let e45: vec2 = particlesSrc.particles[e42].pos; - pos = e45; - let e47: u32 = i; - let e50: vec2 = particlesSrc.particles[e47].vel; - vel = e50; - let e51: vec2 = pos; - let e52: vec2 = vPos; - let e55: f32 = params.rule1Distance; - if ((distance(e51, e52) < e55)) { - let e57: vec2 = cMass; - let e58: vec2 = pos; - cMass = (e57 + e58); - let e60: i32 = cMassCount; - cMassCount = (e60 + 1); + let _e42: u32 = i; + let _e45: vec2 = particlesSrc.particles[_e42].pos; + pos = _e45; + let _e47: u32 = i; + let _e50: vec2 = particlesSrc.particles[_e47].vel; + vel = _e50; + let _e51: vec2 = pos; + let _e52: vec2 = vPos; + let _e55: f32 = params.rule1Distance; + if ((distance(_e51, _e52) < _e55)) { + let _e57: vec2 = cMass; + let _e58: vec2 = pos; + cMass = (_e57 + _e58); + let _e60: i32 = cMassCount; + cMassCount = (_e60 + 1); } - let e63: vec2 = pos; - let e64: vec2 = vPos; - let e67: f32 = params.rule2Distance; - if ((distance(e63, e64) < e67)) { - let e69: vec2 = colVel; - let e70: vec2 = pos; - let e71: vec2 = vPos; - colVel = (e69 - (e70 - e71)); + let _e63: vec2 = pos; + let _e64: vec2 = vPos; + let _e67: f32 = params.rule2Distance; + if ((distance(_e63, _e64) < _e67)) { + let _e69: vec2 = colVel; + let _e70: vec2 = pos; + let _e71: vec2 = vPos; + colVel = (_e69 - (_e70 - _e71)); } - let e74: vec2 = pos; - let e75: vec2 = vPos; - let e78: f32 = params.rule3Distance; - if ((distance(e74, e75) < e78)) { - let e80: vec2 = cVel; - let e81: vec2 = vel; - cVel = (e80 + e81); - let e83: i32 = cVelCount; - cVelCount = (e83 + 1); + let _e74: vec2 = pos; + let _e75: vec2 = vPos; + let _e78: f32 = params.rule3Distance; + if ((distance(_e74, _e75) < _e78)) { + let _e80: vec2 = cVel; + let _e81: vec2 = vel; + cVel = (_e80 + _e81); + let _e83: i32 = cVelCount; + cVelCount = (_e83 + 1); } continuing { - let e86: u32 = i; - i = (e86 + 1u); + let _e86: u32 = i; + i = (_e86 + 1u); } } - let e89: i32 = cMassCount; - if ((e89 > 0)) { - let e92: vec2 = cMass; - let e93: i32 = cMassCount; - let e97: vec2 = vPos; - cMass = ((e92 / vec2(f32(e93))) - e97); + let _e89: i32 = cMassCount; + if ((_e89 > 0)) { + let _e92: vec2 = cMass; + let _e93: i32 = cMassCount; + let _e97: vec2 = vPos; + cMass = ((_e92 / vec2(f32(_e93))) - _e97); } - let e99: i32 = cVelCount; - if ((e99 > 0)) { - let e102: vec2 = cVel; - let e103: i32 = cVelCount; - cVel = (e102 / vec2(f32(e103))); + let _e99: i32 = cVelCount; + if ((_e99 > 0)) { + let _e102: vec2 = cVel; + let _e103: i32 = cVelCount; + cVel = (_e102 / vec2(f32(_e103))); } - let e107: vec2 = vVel; - let e108: vec2 = cMass; - let e110: f32 = params.rule1Scale; - let e113: vec2 = colVel; - let e115: f32 = params.rule2Scale; - let e118: vec2 = cVel; - let e120: f32 = params.rule3Scale; - vVel = (((e107 + (e108 * e110)) + (e113 * e115)) + (e118 * e120)); - let e123: vec2 = vVel; - let e125: vec2 = vVel; - vVel = (normalize(e123) * clamp(length(e125), 0.0, 0.10000000149011612)); - let e131: vec2 = vPos; - let e132: vec2 = vVel; - let e134: f32 = params.deltaT; - vPos = (e131 + (e132 * e134)); - let e138: f32 = vPos.x; - if ((e138 < -1.0)) { + let _e107: vec2 = vVel; + let _e108: vec2 = cMass; + let _e110: f32 = params.rule1Scale; + let _e113: vec2 = colVel; + let _e115: f32 = params.rule2Scale; + let _e118: vec2 = cVel; + let _e120: f32 = params.rule3Scale; + vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); + let _e123: vec2 = vVel; + let _e125: vec2 = vVel; + vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.10000000149011612)); + let _e131: vec2 = vPos; + let _e132: vec2 = vVel; + let _e134: f32 = params.deltaT; + vPos = (_e131 + (_e132 * _e134)); + let _e138: f32 = vPos.x; + if ((_e138 < -1.0)) { vPos.x = 1.0; } - let e144: f32 = vPos.x; - if ((e144 > 1.0)) { + let _e144: f32 = vPos.x; + if ((_e144 > 1.0)) { vPos.x = -1.0; } - let e150: f32 = vPos.y; - if ((e150 < -1.0)) { + let _e150: f32 = vPos.y; + if ((_e150 < -1.0)) { vPos.y = 1.0; } - let e156: f32 = vPos.y; - if ((e156 > 1.0)) { + let _e156: f32 = vPos.y; + if ((_e156 > 1.0)) { vPos.y = -1.0; } - let e164: vec2 = vPos; - particlesDst.particles[index].pos = e164; - let e168: vec2 = vVel; - particlesDst.particles[index].vel = e168; + let _e164: vec2 = vPos; + particlesDst.particles[index].pos = _e164; + let _e168: vec2 = vVel; + particlesDst.particles[index].vel = _e168; return; } diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index f1c4890d0..7c5c3e91b 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -10,9 +10,9 @@ fn TevPerCompGT(a: f32, b: f32) -> f32 { a_1 = a; b_1 = b; - let e5: f32 = a_1; - let e6: f32 = b_1; - return select(0.0, 1.0, (e5 > e6)); + let _e5: f32 = a_1; + let _e6: f32 = b_1; + return select(0.0, 1.0, (_e5 > _e6)); } fn TevPerCompGT_1(a_2: vec3, b_2: vec3) -> vec3 { @@ -21,25 +21,25 @@ fn TevPerCompGT_1(a_2: vec3, b_2: vec3) -> vec3 { a_3 = a_2; b_3 = b_2; - let e7: vec3 = a_3; - let e8: vec3 = b_3; - return select(vec3(0.0), vec3(1.0), (e7 > e8)); + let _e7: vec3 = a_3; + let _e8: vec3 = b_3; + return select(vec3(0.0), vec3(1.0), (_e7 > _e8)); } fn main_1() { - let e1: vec4 = o_color; - let e11: vec3 = TevPerCompGT_1(vec3(3.0), vec3(5.0)); - o_color.x = e11.x; - o_color.y = e11.y; - o_color.z = e11.z; - let e23: f32 = TevPerCompGT(3.0, 5.0); - o_color.w = e23; + let _e1: vec4 = o_color; + let _e11: vec3 = TevPerCompGT_1(vec3(3.0), vec3(5.0)); + o_color.x = _e11.x; + o_color.y = _e11.y; + o_color.z = _e11.z; + let _e23: f32 = TevPerCompGT(3.0, 5.0); + o_color.w = _e23; return; } [[stage(fragment)]] fn main() -> FragmentOutput { main_1(); - let e3: vec4 = o_color; - return FragmentOutput(e3); + let _e3: vec4 = o_color; + return FragmentOutput(_e3); } diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index cfdb9a50b..5a25b56f4 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -6,8 +6,8 @@ var a_pos_1: vec2; var gl_Position: vec4; fn main_1() { - let e5: vec2 = a_pos_1; - gl_Position = vec4(clamp(e5, vec2(0.0), vec2(1.0)), 0.0, 1.0); + let _e5: vec2 = a_pos_1; + gl_Position = vec4(clamp(_e5, vec2(0.0), vec2(1.0)), 0.0, 1.0); return; } @@ -15,6 +15,6 @@ fn main_1() { fn main([[location(0)]] a_pos: vec2) -> VertexOutput { a_pos_1 = a_pos; main_1(); - let e5: vec4 = gl_Position; - return VertexOutput(e5); + let _e5: vec4 = gl_Position; + return VertexOutput(_e5); } diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index b17dbd045..e3bbb2cab 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -12,29 +12,29 @@ fn collatz_iterations(n_base: u32) -> u32 { n = n_base; loop { - let e5: u32 = n; - if ((e5 <= 1u)) { + let _e5: u32 = n; + if ((_e5 <= 1u)) { break; } - let e8: u32 = n; - if (((e8 % 2u) == 0u)) { - let e13: u32 = n; - n = (e13 / 2u); + let _e8: u32 = n; + if (((_e8 % 2u) == 0u)) { + let _e13: u32 = n; + n = (_e13 / 2u); } else { - let e17: u32 = n; - n = ((3u * e17) + 1u); + let _e17: u32 = n; + n = ((3u * _e17) + 1u); } - let e21: u32 = i; - i = (e21 + 1u); + let _e21: u32 = i; + i = (_e21 + 1u); } - let e24: u32 = i; - return e24; + let _e24: u32 = i; + return _e24; } [[stage(compute), workgroup_size(1, 1, 1)]] fn main([[builtin(global_invocation_id)]] global_id: vec3) { - let e8: u32 = v_indices.data[global_id.x]; - let e9: u32 = collatz_iterations(e8); - v_indices.data[global_id.x] = e9; + let _e8: u32 = v_indices.data[global_id.x]; + let _e9: u32 = collatz_iterations(_e8); + v_indices.data[global_id.x] = _e9; return; } diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 4fb8538b6..d512590bc 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -11,23 +11,23 @@ fn function_() -> vec4 { var i: i32 = 0; loop { - let e9: i32 = i; - if (!((e9 < 42))) { + let _e9: i32 = i; + if (!((_e9 < 42))) { break; } { - let e15: vec4 = sum; - let e16: i32 = i; - let e18: vec4 = global.vecs[e16]; - sum = (e15 + e18); + let _e15: vec4 = sum; + let _e16: i32 = i; + let _e18: vec4 = global.vecs[_e16]; + sum = (_e15 + _e18); } continuing { - let e12: i32 = i; - i = (e12 + 1); + let _e12: i32 = i; + i = (_e12 + 1); } } - let e20: vec4 = sum; - return e20; + let _e20: vec4 = sum; + return _e20; } fn main_1() { diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index a8824673f..612681df2 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -41,8 +41,8 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { pos = 1; } } - let e4: i32 = pos; - switch(e4) { + let _e4: i32 = pos; + switch(_e4) { case 1: { pos = 0; break; @@ -66,8 +66,8 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { default: { } } - let e10: i32 = pos; - switch(e10) { + let _e10: i32 = pos; + switch(_e10) { case 1: { pos = 0; break; diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index ae85915b3..00e438af3 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -7,8 +7,8 @@ struct type_1 { var unnamed: type_1; fn function_() { - let e8: i32 = unnamed.member; - unnamed.member = (e8 + 1); + let _e8: i32 = unnamed.member; + unnamed.member = (_e8 + 1); return; } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 865b88cc7..1f07ccfb0 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -12,14 +12,14 @@ fn testBinOpVecFloat(a: vec4, b: f32) { a_1 = a; b_1 = b; - let e5: vec4 = a_1; - v = (e5 * 2.0); - let e8: vec4 = a_1; - v = (e8 / vec4(2.0)); - let e12: vec4 = a_1; - v = (e12 + vec4(2.0)); - let e16: vec4 = a_1; - v = (e16 - vec4(2.0)); + let _e5: vec4 = a_1; + v = (_e5 * 2.0); + let _e8: vec4 = a_1; + v = (_e8 / vec4(2.0)); + let _e12: vec4 = a_1; + v = (_e12 + vec4(2.0)); + let _e16: vec4 = a_1; + v = (_e16 - vec4(2.0)); return; } @@ -30,18 +30,18 @@ fn testBinOpFloatVec(a_2: vec4, b_2: f32) { a_3 = a_2; b_3 = b_2; - let e5: vec4 = a_3; - let e6: f32 = b_3; - v_1 = (e5 * e6); - let e8: vec4 = a_3; - let e9: f32 = b_3; - v_1 = (e8 / vec4(e9)); - let e12: vec4 = a_3; - let e13: f32 = b_3; - v_1 = (e12 + vec4(e13)); - let e16: vec4 = a_3; - let e17: f32 = b_3; - v_1 = (e16 - vec4(e17)); + let _e5: vec4 = a_3; + let _e6: f32 = b_3; + v_1 = (_e5 * _e6); + let _e8: vec4 = a_3; + let _e9: f32 = b_3; + v_1 = (_e8 / vec4(_e9)); + let _e12: vec4 = a_3; + let _e13: f32 = b_3; + v_1 = (_e12 + vec4(_e13)); + let _e16: vec4 = a_3; + let _e17: f32 = b_3; + v_1 = (_e16 - vec4(_e17)); return; } @@ -52,33 +52,33 @@ fn testBinOpIVecInt(a_4: vec4, b_4: i32) { a_5 = a_4; b_5 = b_4; - let e5: vec4 = a_5; - let e6: i32 = b_5; - v_2 = (e5 * e6); - let e8: vec4 = a_5; - let e9: i32 = b_5; - v_2 = (e8 / vec4(e9)); - let e12: vec4 = a_5; - let e13: i32 = b_5; - v_2 = (e12 + vec4(e13)); - let e16: vec4 = a_5; - let e17: i32 = b_5; - v_2 = (e16 - vec4(e17)); - let e20: vec4 = a_5; - let e21: i32 = b_5; - v_2 = (e20 & vec4(e21)); - let e24: vec4 = a_5; - let e25: i32 = b_5; - v_2 = (e24 | vec4(e25)); - let e28: vec4 = a_5; - let e29: i32 = b_5; - v_2 = (e28 ^ vec4(e29)); - let e32: vec4 = a_5; - let e33: i32 = b_5; - v_2 = (e32 >> vec4(u32(e33))); - let e37: vec4 = a_5; - let e38: i32 = b_5; - v_2 = (e37 << vec4(u32(e38))); + let _e5: vec4 = a_5; + let _e6: i32 = b_5; + v_2 = (_e5 * _e6); + let _e8: vec4 = a_5; + let _e9: i32 = b_5; + v_2 = (_e8 / vec4(_e9)); + let _e12: vec4 = a_5; + let _e13: i32 = b_5; + v_2 = (_e12 + vec4(_e13)); + let _e16: vec4 = a_5; + let _e17: i32 = b_5; + v_2 = (_e16 - vec4(_e17)); + let _e20: vec4 = a_5; + let _e21: i32 = b_5; + v_2 = (_e20 & vec4(_e21)); + let _e24: vec4 = a_5; + let _e25: i32 = b_5; + v_2 = (_e24 | vec4(_e25)); + let _e28: vec4 = a_5; + let _e29: i32 = b_5; + v_2 = (_e28 ^ vec4(_e29)); + let _e32: vec4 = a_5; + let _e33: i32 = b_5; + v_2 = (_e32 >> vec4(u32(_e33))); + let _e37: vec4 = a_5; + let _e38: i32 = b_5; + v_2 = (_e37 << vec4(u32(_e38))); return; } @@ -89,24 +89,24 @@ fn testBinOpIntIVec(a_6: i32, b_6: vec4) { a_7 = a_6; b_7 = b_6; - let e5: i32 = a_7; - let e6: vec4 = b_7; - v_3 = (e5 * e6); - let e8: i32 = a_7; - let e9: vec4 = b_7; - v_3 = (vec4(e8) + e9); - let e12: i32 = a_7; - let e13: vec4 = b_7; - v_3 = (vec4(e12) - e13); - let e16: i32 = a_7; - let e17: vec4 = b_7; - v_3 = (vec4(e16) & e17); - let e20: i32 = a_7; - let e21: vec4 = b_7; - v_3 = (vec4(e20) | e21); - let e24: i32 = a_7; - let e25: vec4 = b_7; - v_3 = (vec4(e24) ^ e25); + let _e5: i32 = a_7; + let _e6: vec4 = b_7; + v_3 = (_e5 * _e6); + let _e8: i32 = a_7; + let _e9: vec4 = b_7; + v_3 = (vec4(_e8) + _e9); + let _e12: i32 = a_7; + let _e13: vec4 = b_7; + v_3 = (vec4(_e12) - _e13); + let _e16: i32 = a_7; + let _e17: vec4 = b_7; + v_3 = (vec4(_e16) & _e17); + let _e20: i32 = a_7; + let _e21: vec4 = b_7; + v_3 = (vec4(_e20) | _e21); + let _e24: i32 = a_7; + let _e25: vec4 = b_7; + v_3 = (vec4(_e24) ^ _e25); return; } @@ -117,33 +117,33 @@ fn testBinOpUVecUint(a_8: vec4, b_8: u32) { a_9 = a_8; b_9 = b_8; - let e5: vec4 = a_9; - let e6: u32 = b_9; - v_4 = (e5 * e6); - let e8: vec4 = a_9; - let e9: u32 = b_9; - v_4 = (e8 / vec4(e9)); - let e12: vec4 = a_9; - let e13: u32 = b_9; - v_4 = (e12 + vec4(e13)); - let e16: vec4 = a_9; - let e17: u32 = b_9; - v_4 = (e16 - vec4(e17)); - let e20: vec4 = a_9; - let e21: u32 = b_9; - v_4 = (e20 & vec4(e21)); - let e24: vec4 = a_9; - let e25: u32 = b_9; - v_4 = (e24 | vec4(e25)); - let e28: vec4 = a_9; - let e29: u32 = b_9; - v_4 = (e28 ^ vec4(e29)); - let e32: vec4 = a_9; - let e33: u32 = b_9; - v_4 = (e32 >> vec4(e33)); - let e36: vec4 = a_9; - let e37: u32 = b_9; - v_4 = (e36 << vec4(e37)); + let _e5: vec4 = a_9; + let _e6: u32 = b_9; + v_4 = (_e5 * _e6); + let _e8: vec4 = a_9; + let _e9: u32 = b_9; + v_4 = (_e8 / vec4(_e9)); + let _e12: vec4 = a_9; + let _e13: u32 = b_9; + v_4 = (_e12 + vec4(_e13)); + let _e16: vec4 = a_9; + let _e17: u32 = b_9; + v_4 = (_e16 - vec4(_e17)); + let _e20: vec4 = a_9; + let _e21: u32 = b_9; + v_4 = (_e20 & vec4(_e21)); + let _e24: vec4 = a_9; + let _e25: u32 = b_9; + v_4 = (_e24 | vec4(_e25)); + let _e28: vec4 = a_9; + let _e29: u32 = b_9; + v_4 = (_e28 ^ vec4(_e29)); + let _e32: vec4 = a_9; + let _e33: u32 = b_9; + v_4 = (_e32 >> vec4(_e33)); + let _e36: vec4 = a_9; + let _e37: u32 = b_9; + v_4 = (_e36 << vec4(_e37)); return; } @@ -154,24 +154,24 @@ fn testBinOpUintUVec(a_10: u32, b_10: vec4) { a_11 = a_10; b_11 = b_10; - let e5: u32 = a_11; - let e6: vec4 = b_11; - v_5 = (e5 * e6); - let e8: u32 = a_11; - let e9: vec4 = b_11; - v_5 = (vec4(e8) + e9); - let e12: u32 = a_11; - let e13: vec4 = b_11; - v_5 = (vec4(e12) - e13); - let e16: u32 = a_11; - let e17: vec4 = b_11; - v_5 = (vec4(e16) & e17); - let e20: u32 = a_11; - let e21: vec4 = b_11; - v_5 = (vec4(e20) | e21); - let e24: u32 = a_11; - let e25: vec4 = b_11; - v_5 = (vec4(e24) ^ e25); + let _e5: u32 = a_11; + let _e6: vec4 = b_11; + v_5 = (_e5 * _e6); + let _e8: u32 = a_11; + let _e9: vec4 = b_11; + v_5 = (vec4(_e8) + _e9); + let _e12: u32 = a_11; + let _e13: vec4 = b_11; + v_5 = (vec4(_e12) - _e13); + let _e16: u32 = a_11; + let _e17: vec4 = b_11; + v_5 = (vec4(_e16) & _e17); + let _e20: u32 = a_11; + let _e21: vec4 = b_11; + v_5 = (vec4(_e20) | _e21); + let _e24: u32 = a_11; + let _e25: vec4 = b_11; + v_5 = (vec4(_e24) ^ _e25); return; } @@ -197,17 +197,17 @@ fn privatePointer(a_12: ptr) { fn main_1() { var local: f32; - let e3: f32 = global; - local = e3; + let _e3: f32 = global; + local = _e3; privatePointer((&local)); - let e5: f32 = local; - global = e5; - let e6: vec4 = o_color; - let e9: vec4 = vec4(1.0); - o_color.x = e9.x; - o_color.y = e9.y; - o_color.z = e9.z; - o_color.w = e9.w; + let _e5: f32 = local; + global = _e5; + let _e6: vec4 = o_color; + let _e9: vec4 = vec4(1.0); + o_color.x = _e9.x; + o_color.y = _e9.y; + o_color.z = _e9.z; + o_color.w = _e9.w; return; } diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 9bab2da67..c9bd5af58 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -12,28 +12,28 @@ fn Fma(d: ptr, m: Mat4x3_, s: f32) { m_1 = m; s_1 = s; - let e6: Mat4x3_ = (*d); - let e8: Mat4x3_ = m_1; - let e10: f32 = s_1; - (*d).mx = (e6.mx + (e8.mx * e10)); - let e14: Mat4x3_ = (*d); - let e16: Mat4x3_ = m_1; - let e18: f32 = s_1; - (*d).my = (e14.my + (e16.my * e18)); - let e22: Mat4x3_ = (*d); - let e24: Mat4x3_ = m_1; - let e26: f32 = s_1; - (*d).mz = (e22.mz + (e24.mz * e26)); + let _e6: Mat4x3_ = (*d); + let _e8: Mat4x3_ = m_1; + let _e10: f32 = s_1; + (*d).mx = (_e6.mx + (_e8.mx * _e10)); + let _e14: Mat4x3_ = (*d); + let _e16: Mat4x3_ = m_1; + let _e18: f32 = s_1; + (*d).my = (_e14.my + (_e16.my * _e18)); + let _e22: Mat4x3_ = (*d); + let _e24: Mat4x3_ = m_1; + let _e26: f32 = s_1; + (*d).mz = (_e22.mz + (_e24.mz * _e26)); return; } fn main_1() { - let e1: vec4 = o_color; - let e4: vec4 = vec4(1.0); - o_color.x = e4.x; - o_color.y = e4.y; - o_color.z = e4.z; - o_color.w = e4.w; + let _e1: vec4 = o_color; + let _e4: vec4 = vec4(1.0); + o_color.x = _e4.x; + o_color.y = _e4.y; + o_color.z = _e4.z; + o_color.w = _e4.w; return; } diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index 8fade8ae0..2dc3b2fb9 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -3,7 +3,7 @@ var i: u32; fn main_1() { var local: array = array(1.0, 2.0); - let e2: u32 = i; + let _e2: u32 = i; } [[stage(vertex)]] diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index 91b935db1..db9252d70 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -21,8 +21,8 @@ fn main() -> FragmentInput { out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); out.perspective_centroid = 2197.0; out.perspective_sample = 2744.0; - let e30: FragmentInput = out; - return e30; + let _e30: FragmentInput = out; + return _e30; } [[stage(fragment)]] diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl index 370bab047..c04ddb7ef 100644 --- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -5,12 +5,12 @@ fn main_1() { var c: f32; var d: f32; - let e8: f32 = a; - b = log(e8 + sqrt(e8 * e8 + 1.0)); - let e10: f32 = a; - c = log(e10 + sqrt(e10 * e10 - 1.0)); - let e12: f32 = a; - d = 0.5 * log((1.0 + e12) / (1.0 - e12)); + let _e8: f32 = a; + b = log(_e8 + sqrt(_e8 * _e8 + 1.0)); + let _e10: f32 = a; + c = log(_e10 + sqrt(_e10 * _e10 - 1.0)); + let _e12: f32 = a; + d = 0.5 * log((1.0 + _e12) / (1.0 - _e12)); return; } diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index 1de0a4f29..366593720 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -8,21 +8,21 @@ fn main_1() { var d: mat3x3 = mat3x3(vec3(2.0, 2.0, 1.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); var e: mat4x4 = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); - let e1: f32 = f32(1); - let e9: vec2 = vec2(f32(1)); - let e12: vec2 = vec2(f32(2)); - let e26: mat3x3 = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); - let e58: vec2 = vec2(f32(2), f32(3)); - let e73: vec3 = vec3(f32(1)); - let e76: vec3 = vec3(f32(1)); - let e93: vec2 = vec2(f32(2)); - let e97: vec3 = vec3(f32(1)); - let e100: vec3 = vec3(f32(1)); - let e117: vec2 = vec2(f32(2)); - let e120: vec4 = vec4(f32(1)); - let e123: vec2 = vec2(f32(2)); - let e126: vec4 = vec4(f32(1)); - let e129: vec4 = vec4(f32(1)); + let _e1: f32 = f32(1); + let _e9: vec2 = vec2(f32(1)); + let _e12: vec2 = vec2(f32(2)); + let _e26: mat3x3 = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); + let _e58: vec2 = vec2(f32(2), f32(3)); + let _e73: vec3 = vec3(f32(1)); + let _e76: vec3 = vec3(f32(1)); + let _e93: vec2 = vec2(f32(2)); + let _e97: vec3 = vec3(f32(1)); + let _e100: vec3 = vec3(f32(1)); + let _e117: vec2 = vec2(f32(2)); + let _e120: vec4 = vec4(f32(1)); + let _e123: vec2 = vec2(f32(2)); + let _e126: vec4 = vec4(f32(1)); + let _e129: vec4 = vec4(f32(1)); } [[stage(vertex)]] diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index f7f3c26be..16f0bd003 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -43,107 +43,107 @@ fn main_1() { var distanceOut: f32; var stepOut: vec4; - let e6: vec4 = a; - let e7: vec4 = b; - let e8: vec4 = a; - let e9: vec4 = b; - m = mat4x4(vec4(e6.x, e6.y, e6.z, e6.w), vec4(e7.x, e7.y, e7.z, e7.w), vec4(e8.x, e8.y, e8.z, e8.w), vec4(e9.x, e9.y, e9.z, e9.w)); - let e35: vec4 = a; - ceilOut = ceil(e35); - let e39: vec4 = a; - roundOut = round(e39); - let e43: vec4 = a; - floorOut = floor(e43); - let e47: vec4 = a; - fractOut = fract(e47); - let e51: vec4 = a; - truncOut = trunc(e51); - let e55: vec4 = a; - sinOut = sin(e55); - let e59: vec4 = a; - absOut = abs(e59); - let e63: vec4 = a; - sqrtOut = sqrt(e63); - let e67: vec4 = a; - inversesqrtOut = inverseSqrt(e67); - let e71: vec4 = a; - expOut = exp(e71); - let e75: vec4 = a; - exp2Out = exp2(e75); - let e79: vec4 = a; - signOut = sign(e79); - let e83: mat4x4 = m; - transposeOut = transpose(e83); - let e87: vec4 = a; - normalizeOut = normalize(e87); - let e91: vec4 = a; - sinhOut = sinh(e91); - let e95: vec4 = a; - cosOut = cos(e95); - let e99: vec4 = a; - coshOut = cosh(e99); - let e103: vec4 = a; - tanOut = tan(e103); - let e107: vec4 = a; - tanhOut = tanh(e107); - let e111: vec4 = a; - acosOut = acos(e111); - let e115: vec4 = a; - asinOut = asin(e115); - let e119: vec4 = a; - logOut = log(e119); - let e123: vec4 = a; - log2Out = log2(e123); - let e127: vec4 = a; - lengthOut = length(e127); - let e131: mat4x4 = m; - determinantOut = determinant(e131); - let e135: i32 = i; - bitCountOut = countOneBits(e135); - let e139: i32 = i; - bitfieldReverseOut = reverseBits(e139); - let e142: vec4 = a; - let e144: vec4 = a; - atanOut = atan(e144.x); - let e148: vec4 = a; - let e150: vec4 = a; - let e152: vec4 = a; - let e154: vec4 = a; - atan2Out = atan2(e152.x, e154.y); - let e158: vec4 = a; - let e160: vec4 = b; - let e162: vec4 = a; - let e164: vec4 = b; - modOut = (e162.x % e164.x); - let e170: vec4 = a; - let e171: vec4 = b; - powOut = pow(e170, e171); - let e176: vec4 = a; - let e177: vec4 = b; - dotOut = dot(e176, e177); - let e182: vec4 = a; - let e183: vec4 = b; - maxOut = max(e182, e183); - let e188: vec4 = a; - let e189: vec4 = b; - minOut = min(e188, e189); - let e194: vec4 = a; - let e195: vec4 = b; - reflectOut = reflect(e194, e195); - let e198: vec4 = a; - let e200: vec4 = b; - let e202: vec4 = a; - let e204: vec4 = b; - crossOut = cross(e202.xyz, e204.xyz); - let e210: vec4 = a; - let e211: vec4 = b; - outerProductOut = outerProduct(e210, e211); - let e216: vec4 = a; - let e217: vec4 = b; - distanceOut = distance(e216, e217); - let e222: vec4 = a; - let e223: vec4 = b; - stepOut = step(e222, e223); + let _e6: vec4 = a; + let _e7: vec4 = b; + let _e8: vec4 = a; + let _e9: vec4 = b; + m = mat4x4(vec4(_e6.x, _e6.y, _e6.z, _e6.w), vec4(_e7.x, _e7.y, _e7.z, _e7.w), vec4(_e8.x, _e8.y, _e8.z, _e8.w), vec4(_e9.x, _e9.y, _e9.z, _e9.w)); + let _e35: vec4 = a; + ceilOut = ceil(_e35); + let _e39: vec4 = a; + roundOut = round(_e39); + let _e43: vec4 = a; + floorOut = floor(_e43); + let _e47: vec4 = a; + fractOut = fract(_e47); + let _e51: vec4 = a; + truncOut = trunc(_e51); + let _e55: vec4 = a; + sinOut = sin(_e55); + let _e59: vec4 = a; + absOut = abs(_e59); + let _e63: vec4 = a; + sqrtOut = sqrt(_e63); + let _e67: vec4 = a; + inversesqrtOut = inverseSqrt(_e67); + let _e71: vec4 = a; + expOut = exp(_e71); + let _e75: vec4 = a; + exp2Out = exp2(_e75); + let _e79: vec4 = a; + signOut = sign(_e79); + let _e83: mat4x4 = m; + transposeOut = transpose(_e83); + let _e87: vec4 = a; + normalizeOut = normalize(_e87); + let _e91: vec4 = a; + sinhOut = sinh(_e91); + let _e95: vec4 = a; + cosOut = cos(_e95); + let _e99: vec4 = a; + coshOut = cosh(_e99); + let _e103: vec4 = a; + tanOut = tan(_e103); + let _e107: vec4 = a; + tanhOut = tanh(_e107); + let _e111: vec4 = a; + acosOut = acos(_e111); + let _e115: vec4 = a; + asinOut = asin(_e115); + let _e119: vec4 = a; + logOut = log(_e119); + let _e123: vec4 = a; + log2Out = log2(_e123); + let _e127: vec4 = a; + lengthOut = length(_e127); + let _e131: mat4x4 = m; + determinantOut = determinant(_e131); + let _e135: i32 = i; + bitCountOut = countOneBits(_e135); + let _e139: i32 = i; + bitfieldReverseOut = reverseBits(_e139); + let _e142: vec4 = a; + let _e144: vec4 = a; + atanOut = atan(_e144.x); + let _e148: vec4 = a; + let _e150: vec4 = a; + let _e152: vec4 = a; + let _e154: vec4 = a; + atan2Out = atan2(_e152.x, _e154.y); + let _e158: vec4 = a; + let _e160: vec4 = b; + let _e162: vec4 = a; + let _e164: vec4 = b; + modOut = (_e162.x % _e164.x); + let _e170: vec4 = a; + let _e171: vec4 = b; + powOut = pow(_e170, _e171); + let _e176: vec4 = a; + let _e177: vec4 = b; + dotOut = dot(_e176, _e177); + let _e182: vec4 = a; + let _e183: vec4 = b; + maxOut = max(_e182, _e183); + let _e188: vec4 = a; + let _e189: vec4 = b; + minOut = min(_e188, _e189); + let _e194: vec4 = a; + let _e195: vec4 = b; + reflectOut = reflect(_e194, _e195); + let _e198: vec4 = a; + let _e200: vec4 = b; + let _e202: vec4 = a; + let _e204: vec4 = b; + crossOut = cross(_e202.xyz, _e204.xyz); + let _e210: vec4 = a; + let _e211: vec4 = b; + outerProductOut = outerProduct(_e210, _e211); + let _e216: vec4 = a; + let _e217: vec4 = b; + distanceOut = distance(_e216, _e217); + let _e222: vec4 = a; + let _e223: vec4 = b; + stepOut = step(_e222, _e223); return; } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 5c8b43a7c..ca012560d 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -42,8 +42,8 @@ fn constructors() -> f32 { var foo: Foo; foo = Foo(vec4(1.0), 1); - let e11: f32 = foo.a.x; - return e11; + let _e11: f32 = foo.a.x; + return _e11; } fn modulo() { @@ -60,11 +60,11 @@ fn scalar_times_matrix() { [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { - let e4: vec4 = builtins(); - let e5: vec4 = splat(); - let e6: i32 = unary(); - let e8: vec3 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); - let e9: f32 = constructors(); + let _e4: vec4 = builtins(); + let _e5: vec4 = splat(); + let _e6: i32 = unary(); + let _e8: vec3 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + let _e9: f32 = constructors(); modulo(); scalar_times_matrix(); return; diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index 9c4a4e831..c74990b45 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -6,30 +6,30 @@ fn main_1() { var mat_target: mat4x3; var mat_: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); - let e3: i32 = scalar; - scalar = (e3 + 1); - scalar_target = e3; - let e6: i32 = scalar; - let e8: i32 = (e6 - 1); - scalar = e8; - scalar_target = e8; - let e14: vec2 = vec_; - vec_ = (e14 - vec2(1u)); - vec_target = e14; - let e18: vec2 = vec_; - let e21: vec2 = (e18 + vec2(1u)); - vec_ = e21; - vec_target = e21; - let e24: f32 = f32(1); - let e32: mat4x3 = mat_; - let e34: vec3 = vec3(1.0); - mat_ = (e32 + mat4x3(e34, e34, e34, e34)); - mat_target = e32; - let e37: mat4x3 = mat_; - let e39: vec3 = vec3(1.0); - let e41: mat4x3 = (e37 - mat4x3(e39, e39, e39, e39)); - mat_ = e41; - mat_target = e41; + let _e3: i32 = scalar; + scalar = (_e3 + 1); + scalar_target = _e3; + let _e6: i32 = scalar; + let _e8: i32 = (_e6 - 1); + scalar = _e8; + scalar_target = _e8; + let _e14: vec2 = vec_; + vec_ = (_e14 - vec2(1u)); + vec_target = _e14; + let _e18: vec2 = vec_; + let _e21: vec2 = (_e18 + vec2(1u)); + vec_ = _e21; + vec_target = _e21; + let _e24: f32 = f32(1); + let _e32: mat4x3 = mat_; + let _e34: vec3 = vec3(1.0); + mat_ = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); + mat_target = _e32; + let _e37: mat4x3 = mat_; + let _e39: vec3 = vec3(1.0); + let _e41: mat4x3 = (_e37 - mat4x3(_e39, _e39, _e39, _e39)); + mat_ = _e41; + mat_target = _e41; return; } diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index 8bde11485..f1f30cbdf 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -14,10 +14,10 @@ var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0. var a_pos_1: vec2; fn main_1() { - let e12: vec2 = a_uv_1; - v_uv = e12; - let e13: vec2 = a_pos_1; - perVertexStruct.gl_Position = vec4(e13.x, e13.y, 0.0, 1.0); + let _e12: vec2 = a_uv_1; + v_uv = _e12; + let _e13: vec2 = a_pos_1; + perVertexStruct.gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); return; } @@ -26,7 +26,7 @@ fn main([[location(1)]] a_uv: vec2, [[location(0)]] a_pos: vec2) -> Ve a_uv_1 = a_uv; a_pos_1 = a_pos; main_1(); - let e7: vec2 = v_uv; - let e8: vec4 = perVertexStruct.gl_Position; - return VertexOutput(e7, e8); + let _e7: vec2 = v_uv; + let _e8: vec4 = perVertexStruct.gl_Position; + return VertexOutput(_e7, _e8); } diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 538112384..065acf280 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -14,6 +14,6 @@ fn main_1() { fn main([[location(0)]] v_uv: vec2) -> FragmentOutput { v_uv_1 = v_uv; main_1(); - let e7: vec4 = o_color; - return FragmentOutput(e7); + let _e7: vec4 = o_color; + return FragmentOutput(_e7); } diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index 1348b9a4a..1071db7eb 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -9,10 +9,10 @@ var v_uv: vec2; var gl_Position: vec4; fn main_1() { - let e4: vec2 = a_uv_1; - v_uv = e4; - let e6: vec2 = a_pos_1; - gl_Position = vec4((1.2000000476837158 * e6), 0.0, 1.0); + let _e4: vec2 = a_uv_1; + v_uv = _e4; + let _e6: vec2 = a_pos_1; + gl_Position = vec4((1.2000000476837158 * _e6), 0.0, 1.0); return; } @@ -21,7 +21,7 @@ fn main([[location(0)]] a_pos: vec2, [[location(1)]] a_uv: vec2) -> Ve a_pos_1 = a_pos; a_uv_1 = a_uv; main_1(); - let e14: vec2 = v_uv; - let e16: vec4 = gl_Position; - return VertexOutput(e14, e16); + let _e14: vec2 = v_uv; + let _e16: vec4 = gl_Position; + return VertexOutput(_e14, _e16); } diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 670db9f82..f11803f0d 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -33,110 +33,110 @@ fn testTex1D(coord: f32) { var c: vec4; coord_1 = coord; - let e18: f32 = coord_1; - let e19: vec4 = textureSample(tex1D, samp, e18); - c = e19; - let e22: f32 = coord_1; - let e24: vec4 = textureSampleBias(tex1D, samp, e22, 2.0); - c = e24; - let e28: f32 = coord_1; - let e31: vec4 = textureSampleGrad(tex1D, samp, e28, 4.0, 4.0); - c = e31; - let e36: f32 = coord_1; - let e40: vec4 = textureSampleGrad(tex1D, samp, e36, 4.0, 4.0, 5); - c = e40; - let e43: f32 = coord_1; - let e45: vec4 = textureSampleLevel(tex1D, samp, e43, 3.0); - c = e45; - let e49: f32 = coord_1; - let e52: vec4 = textureSampleLevel(tex1D, samp, e49, 3.0, 5); - c = e52; - let e55: f32 = coord_1; - let e57: vec4 = textureSample(tex1D, samp, e55, 5); - c = e57; - let e61: f32 = coord_1; - let e64: vec4 = textureSampleBias(tex1D, samp, e61, 2.0, 5); - c = e64; - let e65: f32 = coord_1; - let e68: f32 = coord_1; - let e70: vec2 = vec2(e68, 6.0); - let e74: vec4 = textureSample(tex1D, samp, (e70.x / e70.y)); - c = e74; - let e75: f32 = coord_1; - let e80: f32 = coord_1; - let e84: vec4 = vec4(e80, 0.0, 0.0, 6.0); - let e90: vec4 = textureSample(tex1D, samp, (e84.xyz / vec3(e84.w)).x); - c = e90; - let e91: f32 = coord_1; - let e95: f32 = coord_1; - let e97: vec2 = vec2(e95, 6.0); - let e102: vec4 = textureSampleBias(tex1D, samp, (e97.x / e97.y), 2.0); - c = e102; - let e103: f32 = coord_1; - let e109: f32 = coord_1; - let e113: vec4 = vec4(e109, 0.0, 0.0, 6.0); - let e120: vec4 = textureSampleBias(tex1D, samp, (e113.xyz / vec3(e113.w)).x, 2.0); - c = e120; - let e121: f32 = coord_1; - let e126: f32 = coord_1; - let e128: vec2 = vec2(e126, 6.0); - let e134: vec4 = textureSampleGrad(tex1D, samp, (e128.x / e128.y), 4.0, 4.0); - c = e134; - let e135: f32 = coord_1; - let e142: f32 = coord_1; - let e146: vec4 = vec4(e142, 0.0, 0.0, 6.0); - let e154: vec4 = textureSampleGrad(tex1D, samp, (e146.xyz / vec3(e146.w)).x, 4.0, 4.0); - c = e154; - let e155: f32 = coord_1; - let e161: f32 = coord_1; - let e163: vec2 = vec2(e161, 6.0); - let e170: vec4 = textureSampleGrad(tex1D, samp, (e163.x / e163.y), 4.0, 4.0, 5); - c = e170; - let e171: f32 = coord_1; - let e179: f32 = coord_1; - let e183: vec4 = vec4(e179, 0.0, 0.0, 6.0); - let e192: vec4 = textureSampleGrad(tex1D, samp, (e183.xyz / vec3(e183.w)).x, 4.0, 4.0, 5); - c = e192; - let e193: f32 = coord_1; - let e197: f32 = coord_1; - let e199: vec2 = vec2(e197, 6.0); - let e204: vec4 = textureSampleLevel(tex1D, samp, (e199.x / e199.y), 3.0); - c = e204; - let e205: f32 = coord_1; - let e211: f32 = coord_1; - let e215: vec4 = vec4(e211, 0.0, 0.0, 6.0); - let e222: vec4 = textureSampleLevel(tex1D, samp, (e215.xyz / vec3(e215.w)).x, 3.0); - c = e222; - let e223: f32 = coord_1; - let e228: f32 = coord_1; - let e230: vec2 = vec2(e228, 6.0); - let e236: vec4 = textureSampleLevel(tex1D, samp, (e230.x / e230.y), 3.0, 5); - c = e236; - let e237: f32 = coord_1; - let e244: f32 = coord_1; - let e248: vec4 = vec4(e244, 0.0, 0.0, 6.0); - let e256: vec4 = textureSampleLevel(tex1D, samp, (e248.xyz / vec3(e248.w)).x, 3.0, 5); - c = e256; - let e257: f32 = coord_1; - let e261: f32 = coord_1; - let e263: vec2 = vec2(e261, 6.0); - let e268: vec4 = textureSample(tex1D, samp, (e263.x / e263.y), 5); - c = e268; - let e269: f32 = coord_1; - let e275: f32 = coord_1; - let e279: vec4 = vec4(e275, 0.0, 0.0, 6.0); - let e286: vec4 = textureSample(tex1D, samp, (e279.xyz / vec3(e279.w)).x, 5); - c = e286; - let e287: f32 = coord_1; - let e292: f32 = coord_1; - let e294: vec2 = vec2(e292, 6.0); - let e300: vec4 = textureSampleBias(tex1D, samp, (e294.x / e294.y), 2.0, 5); - c = e300; - let e301: f32 = coord_1; - let e308: f32 = coord_1; - let e312: vec4 = vec4(e308, 0.0, 0.0, 6.0); - let e320: vec4 = textureSampleBias(tex1D, samp, (e312.xyz / vec3(e312.w)).x, 2.0, 5); - c = e320; + let _e18: f32 = coord_1; + let _e19: vec4 = textureSample(tex1D, samp, _e18); + c = _e19; + let _e22: f32 = coord_1; + let _e24: vec4 = textureSampleBias(tex1D, samp, _e22, 2.0); + c = _e24; + let _e28: f32 = coord_1; + let _e31: vec4 = textureSampleGrad(tex1D, samp, _e28, 4.0, 4.0); + c = _e31; + let _e36: f32 = coord_1; + let _e40: vec4 = textureSampleGrad(tex1D, samp, _e36, 4.0, 4.0, 5); + c = _e40; + let _e43: f32 = coord_1; + let _e45: vec4 = textureSampleLevel(tex1D, samp, _e43, 3.0); + c = _e45; + let _e49: f32 = coord_1; + let _e52: vec4 = textureSampleLevel(tex1D, samp, _e49, 3.0, 5); + c = _e52; + let _e55: f32 = coord_1; + let _e57: vec4 = textureSample(tex1D, samp, _e55, 5); + c = _e57; + let _e61: f32 = coord_1; + let _e64: vec4 = textureSampleBias(tex1D, samp, _e61, 2.0, 5); + c = _e64; + let _e65: f32 = coord_1; + let _e68: f32 = coord_1; + let _e70: vec2 = vec2(_e68, 6.0); + let _e74: vec4 = textureSample(tex1D, samp, (_e70.x / _e70.y)); + c = _e74; + let _e75: f32 = coord_1; + let _e80: f32 = coord_1; + let _e84: vec4 = vec4(_e80, 0.0, 0.0, 6.0); + let _e90: vec4 = textureSample(tex1D, samp, (_e84.xyz / vec3(_e84.w)).x); + c = _e90; + let _e91: f32 = coord_1; + let _e95: f32 = coord_1; + let _e97: vec2 = vec2(_e95, 6.0); + let _e102: vec4 = textureSampleBias(tex1D, samp, (_e97.x / _e97.y), 2.0); + c = _e102; + let _e103: f32 = coord_1; + let _e109: f32 = coord_1; + let _e113: vec4 = vec4(_e109, 0.0, 0.0, 6.0); + let _e120: vec4 = textureSampleBias(tex1D, samp, (_e113.xyz / vec3(_e113.w)).x, 2.0); + c = _e120; + let _e121: f32 = coord_1; + let _e126: f32 = coord_1; + let _e128: vec2 = vec2(_e126, 6.0); + let _e134: vec4 = textureSampleGrad(tex1D, samp, (_e128.x / _e128.y), 4.0, 4.0); + c = _e134; + let _e135: f32 = coord_1; + let _e142: f32 = coord_1; + let _e146: vec4 = vec4(_e142, 0.0, 0.0, 6.0); + let _e154: vec4 = textureSampleGrad(tex1D, samp, (_e146.xyz / vec3(_e146.w)).x, 4.0, 4.0); + c = _e154; + let _e155: f32 = coord_1; + let _e161: f32 = coord_1; + let _e163: vec2 = vec2(_e161, 6.0); + let _e170: vec4 = textureSampleGrad(tex1D, samp, (_e163.x / _e163.y), 4.0, 4.0, 5); + c = _e170; + let _e171: f32 = coord_1; + let _e179: f32 = coord_1; + let _e183: vec4 = vec4(_e179, 0.0, 0.0, 6.0); + let _e192: vec4 = textureSampleGrad(tex1D, samp, (_e183.xyz / vec3(_e183.w)).x, 4.0, 4.0, 5); + c = _e192; + let _e193: f32 = coord_1; + let _e197: f32 = coord_1; + let _e199: vec2 = vec2(_e197, 6.0); + let _e204: vec4 = textureSampleLevel(tex1D, samp, (_e199.x / _e199.y), 3.0); + c = _e204; + let _e205: f32 = coord_1; + let _e211: f32 = coord_1; + let _e215: vec4 = vec4(_e211, 0.0, 0.0, 6.0); + let _e222: vec4 = textureSampleLevel(tex1D, samp, (_e215.xyz / vec3(_e215.w)).x, 3.0); + c = _e222; + let _e223: f32 = coord_1; + let _e228: f32 = coord_1; + let _e230: vec2 = vec2(_e228, 6.0); + let _e236: vec4 = textureSampleLevel(tex1D, samp, (_e230.x / _e230.y), 3.0, 5); + c = _e236; + let _e237: f32 = coord_1; + let _e244: f32 = coord_1; + let _e248: vec4 = vec4(_e244, 0.0, 0.0, 6.0); + let _e256: vec4 = textureSampleLevel(tex1D, samp, (_e248.xyz / vec3(_e248.w)).x, 3.0, 5); + c = _e256; + let _e257: f32 = coord_1; + let _e261: f32 = coord_1; + let _e263: vec2 = vec2(_e261, 6.0); + let _e268: vec4 = textureSample(tex1D, samp, (_e263.x / _e263.y), 5); + c = _e268; + let _e269: f32 = coord_1; + let _e275: f32 = coord_1; + let _e279: vec4 = vec4(_e275, 0.0, 0.0, 6.0); + let _e286: vec4 = textureSample(tex1D, samp, (_e279.xyz / vec3(_e279.w)).x, 5); + c = _e286; + let _e287: f32 = coord_1; + let _e292: f32 = coord_1; + let _e294: vec2 = vec2(_e292, 6.0); + let _e300: vec4 = textureSampleBias(tex1D, samp, (_e294.x / _e294.y), 2.0, 5); + c = _e300; + let _e301: f32 = coord_1; + let _e308: f32 = coord_1; + let _e312: vec4 = vec4(_e308, 0.0, 0.0, 6.0); + let _e320: vec4 = textureSampleBias(tex1D, samp, (_e312.xyz / vec3(_e312.w)).x, 2.0, 5); + c = _e320; return; } @@ -145,30 +145,30 @@ fn testTex1DArray(coord_2: vec2) { var c_1: vec4; coord_3 = coord_2; - let e18: vec2 = coord_3; - let e22: vec4 = textureSample(tex1DArray, samp, e18.x, i32(e18.y)); - c_1 = e22; - let e25: vec2 = coord_3; - let e30: vec4 = textureSampleBias(tex1DArray, samp, e25.x, i32(e25.y), 2.0); - c_1 = e30; - let e34: vec2 = coord_3; - let e40: vec4 = textureSampleGrad(tex1DArray, samp, e34.x, i32(e34.y), 4.0, 4.0); - c_1 = e40; - let e45: vec2 = coord_3; - let e52: vec4 = textureSampleGrad(tex1DArray, samp, e45.x, i32(e45.y), 4.0, 4.0, 5); - c_1 = e52; - let e55: vec2 = coord_3; - let e60: vec4 = textureSampleLevel(tex1DArray, samp, e55.x, i32(e55.y), 3.0); - c_1 = e60; - let e64: vec2 = coord_3; - let e70: vec4 = textureSampleLevel(tex1DArray, samp, e64.x, i32(e64.y), 3.0, 5); - c_1 = e70; - let e73: vec2 = coord_3; - let e78: vec4 = textureSample(tex1DArray, samp, e73.x, i32(e73.y), 5); - c_1 = e78; - let e82: vec2 = coord_3; - let e88: vec4 = textureSampleBias(tex1DArray, samp, e82.x, i32(e82.y), 2.0, 5); - c_1 = e88; + let _e18: vec2 = coord_3; + let _e22: vec4 = textureSample(tex1DArray, samp, _e18.x, i32(_e18.y)); + c_1 = _e22; + let _e25: vec2 = coord_3; + let _e30: vec4 = textureSampleBias(tex1DArray, samp, _e25.x, i32(_e25.y), 2.0); + c_1 = _e30; + let _e34: vec2 = coord_3; + let _e40: vec4 = textureSampleGrad(tex1DArray, samp, _e34.x, i32(_e34.y), 4.0, 4.0); + c_1 = _e40; + let _e45: vec2 = coord_3; + let _e52: vec4 = textureSampleGrad(tex1DArray, samp, _e45.x, i32(_e45.y), 4.0, 4.0, 5); + c_1 = _e52; + let _e55: vec2 = coord_3; + let _e60: vec4 = textureSampleLevel(tex1DArray, samp, _e55.x, i32(_e55.y), 3.0); + c_1 = _e60; + let _e64: vec2 = coord_3; + let _e70: vec4 = textureSampleLevel(tex1DArray, samp, _e64.x, i32(_e64.y), 3.0, 5); + c_1 = _e70; + let _e73: vec2 = coord_3; + let _e78: vec4 = textureSample(tex1DArray, samp, _e73.x, i32(_e73.y), 5); + c_1 = _e78; + let _e82: vec2 = coord_3; + let _e88: vec4 = textureSampleBias(tex1DArray, samp, _e82.x, i32(_e82.y), 2.0, 5); + c_1 = _e88; return; } @@ -177,110 +177,110 @@ fn testTex2D(coord_4: vec2) { var c_2: vec4; coord_5 = coord_4; - let e18: vec2 = coord_5; - let e19: vec4 = textureSample(tex2D, samp, e18); - c_2 = e19; - let e22: vec2 = coord_5; - let e24: vec4 = textureSampleBias(tex2D, samp, e22, 2.0); - c_2 = e24; - let e30: vec2 = coord_5; - let e35: vec4 = textureSampleGrad(tex2D, samp, e30, vec2(4.0), vec2(4.0)); - c_2 = e35; - let e43: vec2 = coord_5; - let e50: vec4 = textureSampleGrad(tex2D, samp, e43, vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = e50; - let e53: vec2 = coord_5; - let e55: vec4 = textureSampleLevel(tex2D, samp, e53, 3.0); - c_2 = e55; - let e60: vec2 = coord_5; - let e64: vec4 = textureSampleLevel(tex2D, samp, e60, 3.0, vec2(5, 5)); - c_2 = e64; - let e68: vec2 = coord_5; - let e71: vec4 = textureSample(tex2D, samp, e68, vec2(5, 5)); - c_2 = e71; - let e76: vec2 = coord_5; - let e80: vec4 = textureSampleBias(tex2D, samp, e76, 2.0, vec2(5, 5)); - c_2 = e80; - let e81: vec2 = coord_5; - let e84: vec2 = coord_5; - let e86: vec3 = vec3(e84, 6.0); - let e91: vec4 = textureSample(tex2D, samp, (e86.xy / vec2(e86.z))); - c_2 = e91; - let e92: vec2 = coord_5; - let e96: vec2 = coord_5; - let e99: vec4 = vec4(e96, 0.0, 6.0); - let e105: vec4 = textureSample(tex2D, samp, (e99.xyz / vec3(e99.w)).xy); - c_2 = e105; - let e106: vec2 = coord_5; - let e110: vec2 = coord_5; - let e112: vec3 = vec3(e110, 6.0); - let e118: vec4 = textureSampleBias(tex2D, samp, (e112.xy / vec2(e112.z)), 2.0); - c_2 = e118; - let e119: vec2 = coord_5; - let e124: vec2 = coord_5; - let e127: vec4 = vec4(e124, 0.0, 6.0); - let e134: vec4 = textureSampleBias(tex2D, samp, (e127.xyz / vec3(e127.w)).xy, 2.0); - c_2 = e134; - let e135: vec2 = coord_5; - let e142: vec2 = coord_5; - let e144: vec3 = vec3(e142, 6.0); - let e153: vec4 = textureSampleGrad(tex2D, samp, (e144.xy / vec2(e144.z)), vec2(4.0), vec2(4.0)); - c_2 = e153; - let e154: vec2 = coord_5; - let e162: vec2 = coord_5; - let e165: vec4 = vec4(e162, 0.0, 6.0); - let e175: vec4 = textureSampleGrad(tex2D, samp, (e165.xyz / vec3(e165.w)).xy, vec2(4.0), vec2(4.0)); - c_2 = e175; - let e176: vec2 = coord_5; - let e185: vec2 = coord_5; - let e187: vec3 = vec3(e185, 6.0); - let e198: vec4 = textureSampleGrad(tex2D, samp, (e187.xy / vec2(e187.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = e198; - let e199: vec2 = coord_5; - let e209: vec2 = coord_5; - let e212: vec4 = vec4(e209, 0.0, 6.0); - let e224: vec4 = textureSampleGrad(tex2D, samp, (e212.xyz / vec3(e212.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = e224; - let e225: vec2 = coord_5; - let e229: vec2 = coord_5; - let e231: vec3 = vec3(e229, 6.0); - let e237: vec4 = textureSampleLevel(tex2D, samp, (e231.xy / vec2(e231.z)), 3.0); - c_2 = e237; - let e238: vec2 = coord_5; - let e243: vec2 = coord_5; - let e246: vec4 = vec4(e243, 0.0, 6.0); - let e253: vec4 = textureSampleLevel(tex2D, samp, (e246.xyz / vec3(e246.w)).xy, 3.0); - c_2 = e253; - let e254: vec2 = coord_5; - let e260: vec2 = coord_5; - let e262: vec3 = vec3(e260, 6.0); - let e270: vec4 = textureSampleLevel(tex2D, samp, (e262.xy / vec2(e262.z)), 3.0, vec2(5, 5)); - c_2 = e270; - let e271: vec2 = coord_5; - let e278: vec2 = coord_5; - let e281: vec4 = vec4(e278, 0.0, 6.0); - let e290: vec4 = textureSampleLevel(tex2D, samp, (e281.xyz / vec3(e281.w)).xy, 3.0, vec2(5, 5)); - c_2 = e290; - let e291: vec2 = coord_5; - let e296: vec2 = coord_5; - let e298: vec3 = vec3(e296, 6.0); - let e305: vec4 = textureSample(tex2D, samp, (e298.xy / vec2(e298.z)), vec2(5, 5)); - c_2 = e305; - let e306: vec2 = coord_5; - let e312: vec2 = coord_5; - let e315: vec4 = vec4(e312, 0.0, 6.0); - let e323: vec4 = textureSample(tex2D, samp, (e315.xyz / vec3(e315.w)).xy, vec2(5, 5)); - c_2 = e323; - let e324: vec2 = coord_5; - let e330: vec2 = coord_5; - let e332: vec3 = vec3(e330, 6.0); - let e340: vec4 = textureSampleBias(tex2D, samp, (e332.xy / vec2(e332.z)), 2.0, vec2(5, 5)); - c_2 = e340; - let e341: vec2 = coord_5; - let e348: vec2 = coord_5; - let e351: vec4 = vec4(e348, 0.0, 6.0); - let e360: vec4 = textureSampleBias(tex2D, samp, (e351.xyz / vec3(e351.w)).xy, 2.0, vec2(5, 5)); - c_2 = e360; + let _e18: vec2 = coord_5; + let _e19: vec4 = textureSample(tex2D, samp, _e18); + c_2 = _e19; + let _e22: vec2 = coord_5; + let _e24: vec4 = textureSampleBias(tex2D, samp, _e22, 2.0); + c_2 = _e24; + let _e30: vec2 = coord_5; + let _e35: vec4 = textureSampleGrad(tex2D, samp, _e30, vec2(4.0), vec2(4.0)); + c_2 = _e35; + let _e43: vec2 = coord_5; + let _e50: vec4 = textureSampleGrad(tex2D, samp, _e43, vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e50; + let _e53: vec2 = coord_5; + let _e55: vec4 = textureSampleLevel(tex2D, samp, _e53, 3.0); + c_2 = _e55; + let _e60: vec2 = coord_5; + let _e64: vec4 = textureSampleLevel(tex2D, samp, _e60, 3.0, vec2(5, 5)); + c_2 = _e64; + let _e68: vec2 = coord_5; + let _e71: vec4 = textureSample(tex2D, samp, _e68, vec2(5, 5)); + c_2 = _e71; + let _e76: vec2 = coord_5; + let _e80: vec4 = textureSampleBias(tex2D, samp, _e76, 2.0, vec2(5, 5)); + c_2 = _e80; + let _e81: vec2 = coord_5; + let _e84: vec2 = coord_5; + let _e86: vec3 = vec3(_e84, 6.0); + let _e91: vec4 = textureSample(tex2D, samp, (_e86.xy / vec2(_e86.z))); + c_2 = _e91; + let _e92: vec2 = coord_5; + let _e96: vec2 = coord_5; + let _e99: vec4 = vec4(_e96, 0.0, 6.0); + let _e105: vec4 = textureSample(tex2D, samp, (_e99.xyz / vec3(_e99.w)).xy); + c_2 = _e105; + let _e106: vec2 = coord_5; + let _e110: vec2 = coord_5; + let _e112: vec3 = vec3(_e110, 6.0); + let _e118: vec4 = textureSampleBias(tex2D, samp, (_e112.xy / vec2(_e112.z)), 2.0); + c_2 = _e118; + let _e119: vec2 = coord_5; + let _e124: vec2 = coord_5; + let _e127: vec4 = vec4(_e124, 0.0, 6.0); + let _e134: vec4 = textureSampleBias(tex2D, samp, (_e127.xyz / vec3(_e127.w)).xy, 2.0); + c_2 = _e134; + let _e135: vec2 = coord_5; + let _e142: vec2 = coord_5; + let _e144: vec3 = vec3(_e142, 6.0); + let _e153: vec4 = textureSampleGrad(tex2D, samp, (_e144.xy / vec2(_e144.z)), vec2(4.0), vec2(4.0)); + c_2 = _e153; + let _e154: vec2 = coord_5; + let _e162: vec2 = coord_5; + let _e165: vec4 = vec4(_e162, 0.0, 6.0); + let _e175: vec4 = textureSampleGrad(tex2D, samp, (_e165.xyz / vec3(_e165.w)).xy, vec2(4.0), vec2(4.0)); + c_2 = _e175; + let _e176: vec2 = coord_5; + let _e185: vec2 = coord_5; + let _e187: vec3 = vec3(_e185, 6.0); + let _e198: vec4 = textureSampleGrad(tex2D, samp, (_e187.xy / vec2(_e187.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e198; + let _e199: vec2 = coord_5; + let _e209: vec2 = coord_5; + let _e212: vec4 = vec4(_e209, 0.0, 6.0); + let _e224: vec4 = textureSampleGrad(tex2D, samp, (_e212.xyz / vec3(_e212.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e224; + let _e225: vec2 = coord_5; + let _e229: vec2 = coord_5; + let _e231: vec3 = vec3(_e229, 6.0); + let _e237: vec4 = textureSampleLevel(tex2D, samp, (_e231.xy / vec2(_e231.z)), 3.0); + c_2 = _e237; + let _e238: vec2 = coord_5; + let _e243: vec2 = coord_5; + let _e246: vec4 = vec4(_e243, 0.0, 6.0); + let _e253: vec4 = textureSampleLevel(tex2D, samp, (_e246.xyz / vec3(_e246.w)).xy, 3.0); + c_2 = _e253; + let _e254: vec2 = coord_5; + let _e260: vec2 = coord_5; + let _e262: vec3 = vec3(_e260, 6.0); + let _e270: vec4 = textureSampleLevel(tex2D, samp, (_e262.xy / vec2(_e262.z)), 3.0, vec2(5, 5)); + c_2 = _e270; + let _e271: vec2 = coord_5; + let _e278: vec2 = coord_5; + let _e281: vec4 = vec4(_e278, 0.0, 6.0); + let _e290: vec4 = textureSampleLevel(tex2D, samp, (_e281.xyz / vec3(_e281.w)).xy, 3.0, vec2(5, 5)); + c_2 = _e290; + let _e291: vec2 = coord_5; + let _e296: vec2 = coord_5; + let _e298: vec3 = vec3(_e296, 6.0); + let _e305: vec4 = textureSample(tex2D, samp, (_e298.xy / vec2(_e298.z)), vec2(5, 5)); + c_2 = _e305; + let _e306: vec2 = coord_5; + let _e312: vec2 = coord_5; + let _e315: vec4 = vec4(_e312, 0.0, 6.0); + let _e323: vec4 = textureSample(tex2D, samp, (_e315.xyz / vec3(_e315.w)).xy, vec2(5, 5)); + c_2 = _e323; + let _e324: vec2 = coord_5; + let _e330: vec2 = coord_5; + let _e332: vec3 = vec3(_e330, 6.0); + let _e340: vec4 = textureSampleBias(tex2D, samp, (_e332.xy / vec2(_e332.z)), 2.0, vec2(5, 5)); + c_2 = _e340; + let _e341: vec2 = coord_5; + let _e348: vec2 = coord_5; + let _e351: vec4 = vec4(_e348, 0.0, 6.0); + let _e360: vec4 = textureSampleBias(tex2D, samp, (_e351.xyz / vec3(_e351.w)).xy, 2.0, vec2(5, 5)); + c_2 = _e360; return; } @@ -289,72 +289,72 @@ fn testTex2DShadow(coord_6: vec2) { var d: f32; coord_7 = coord_6; - let e17: vec2 = coord_7; - let e20: vec2 = coord_7; - let e22: vec3 = vec3(e20, 1.0); - let e25: f32 = textureSampleCompare(tex2DShadow, sampShadow, e22.xy, e22.z); - d = e25; - let e26: vec2 = coord_7; - let e33: vec2 = coord_7; - let e35: vec3 = vec3(e33, 1.0); - let e42: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e35.xy, e35.z); - d = e42; - let e43: vec2 = coord_7; - let e52: vec2 = coord_7; - let e54: vec3 = vec3(e52, 1.0); - let e63: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e54.xy, e54.z, vec2(5, 5)); - d = e63; - let e64: vec2 = coord_7; - let e68: vec2 = coord_7; - let e70: vec3 = vec3(e68, 1.0); - let e74: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e70.xy, e70.z); - d = e74; - let e75: vec2 = coord_7; - let e81: vec2 = coord_7; - let e83: vec3 = vec3(e81, 1.0); - let e89: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e83.xy, e83.z, vec2(5, 5)); - d = e89; - let e90: vec2 = coord_7; - let e95: vec2 = coord_7; - let e97: vec3 = vec3(e95, 1.0); - let e102: f32 = textureSampleCompare(tex2DShadow, sampShadow, e97.xy, e97.z, vec2(5, 5)); - d = e102; - let e103: vec2 = coord_7; - let e107: vec2 = coord_7; - let e110: vec4 = vec4(e107, 1.0, 6.0); - let e114: vec3 = (e110.xyz / vec3(e110.w)); - let e117: f32 = textureSampleCompare(tex2DShadow, sampShadow, e114.xy, e114.z); - d = e117; - let e118: vec2 = coord_7; - let e126: vec2 = coord_7; - let e129: vec4 = vec4(e126, 1.0, 6.0); - let e137: vec3 = (e129.xyz / vec3(e129.w)); - let e140: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e137.xy, e137.z); - d = e140; - let e141: vec2 = coord_7; - let e151: vec2 = coord_7; - let e154: vec4 = vec4(e151, 1.0, 6.0); - let e164: vec3 = (e154.xyz / vec3(e154.w)); - let e167: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e164.xy, e164.z, vec2(5, 5)); - d = e167; - let e168: vec2 = coord_7; - let e173: vec2 = coord_7; - let e176: vec4 = vec4(e173, 1.0, 6.0); - let e181: vec3 = (e176.xyz / vec3(e176.w)); - let e184: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e181.xy, e181.z); - d = e184; - let e185: vec2 = coord_7; - let e192: vec2 = coord_7; - let e195: vec4 = vec4(e192, 1.0, 6.0); - let e202: vec3 = (e195.xyz / vec3(e195.w)); - let e205: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e202.xy, e202.z, vec2(5, 5)); - d = e205; - let e206: vec2 = coord_7; - let e212: vec2 = coord_7; - let e215: vec4 = vec4(e212, 1.0, 6.0); - let e221: vec3 = (e215.xyz / vec3(e215.w)); - let e224: f32 = textureSampleCompare(tex2DShadow, sampShadow, e221.xy, e221.z, vec2(5, 5)); - d = e224; + let _e17: vec2 = coord_7; + let _e20: vec2 = coord_7; + let _e22: vec3 = vec3(_e20, 1.0); + let _e25: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e22.xy, _e22.z); + d = _e25; + let _e26: vec2 = coord_7; + let _e33: vec2 = coord_7; + let _e35: vec3 = vec3(_e33, 1.0); + let _e42: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e35.xy, _e35.z); + d = _e42; + let _e43: vec2 = coord_7; + let _e52: vec2 = coord_7; + let _e54: vec3 = vec3(_e52, 1.0); + let _e63: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e54.xy, _e54.z, vec2(5, 5)); + d = _e63; + let _e64: vec2 = coord_7; + let _e68: vec2 = coord_7; + let _e70: vec3 = vec3(_e68, 1.0); + let _e74: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e70.xy, _e70.z); + d = _e74; + let _e75: vec2 = coord_7; + let _e81: vec2 = coord_7; + let _e83: vec3 = vec3(_e81, 1.0); + let _e89: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e83.xy, _e83.z, vec2(5, 5)); + d = _e89; + let _e90: vec2 = coord_7; + let _e95: vec2 = coord_7; + let _e97: vec3 = vec3(_e95, 1.0); + let _e102: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e97.xy, _e97.z, vec2(5, 5)); + d = _e102; + let _e103: vec2 = coord_7; + let _e107: vec2 = coord_7; + let _e110: vec4 = vec4(_e107, 1.0, 6.0); + let _e114: vec3 = (_e110.xyz / vec3(_e110.w)); + let _e117: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e114.xy, _e114.z); + d = _e117; + let _e118: vec2 = coord_7; + let _e126: vec2 = coord_7; + let _e129: vec4 = vec4(_e126, 1.0, 6.0); + let _e137: vec3 = (_e129.xyz / vec3(_e129.w)); + let _e140: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e137.xy, _e137.z); + d = _e140; + let _e141: vec2 = coord_7; + let _e151: vec2 = coord_7; + let _e154: vec4 = vec4(_e151, 1.0, 6.0); + let _e164: vec3 = (_e154.xyz / vec3(_e154.w)); + let _e167: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e164.xy, _e164.z, vec2(5, 5)); + d = _e167; + let _e168: vec2 = coord_7; + let _e173: vec2 = coord_7; + let _e176: vec4 = vec4(_e173, 1.0, 6.0); + let _e181: vec3 = (_e176.xyz / vec3(_e176.w)); + let _e184: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e181.xy, _e181.z); + d = _e184; + let _e185: vec2 = coord_7; + let _e192: vec2 = coord_7; + let _e195: vec4 = vec4(_e192, 1.0, 6.0); + let _e202: vec3 = (_e195.xyz / vec3(_e195.w)); + let _e205: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e202.xy, _e202.z, vec2(5, 5)); + d = _e205; + let _e206: vec2 = coord_7; + let _e212: vec2 = coord_7; + let _e215: vec4 = vec4(_e212, 1.0, 6.0); + let _e221: vec3 = (_e215.xyz / vec3(_e215.w)); + let _e224: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e221.xy, _e221.z, vec2(5, 5)); + d = _e224; return; } @@ -363,30 +363,30 @@ fn testTex2DArray(coord_8: vec3) { var c_3: vec4; coord_9 = coord_8; - let e18: vec3 = coord_9; - let e22: vec4 = textureSample(tex2DArray, samp, e18.xy, i32(e18.z)); - c_3 = e22; - let e25: vec3 = coord_9; - let e30: vec4 = textureSampleBias(tex2DArray, samp, e25.xy, i32(e25.z), 2.0); - c_3 = e30; - let e36: vec3 = coord_9; - let e44: vec4 = textureSampleGrad(tex2DArray, samp, e36.xy, i32(e36.z), vec2(4.0), vec2(4.0)); - c_3 = e44; - let e52: vec3 = coord_9; - let e62: vec4 = textureSampleGrad(tex2DArray, samp, e52.xy, i32(e52.z), vec2(4.0), vec2(4.0), vec2(5, 5)); - c_3 = e62; - let e65: vec3 = coord_9; - let e70: vec4 = textureSampleLevel(tex2DArray, samp, e65.xy, i32(e65.z), 3.0); - c_3 = e70; - let e75: vec3 = coord_9; - let e82: vec4 = textureSampleLevel(tex2DArray, samp, e75.xy, i32(e75.z), 3.0, vec2(5, 5)); - c_3 = e82; - let e86: vec3 = coord_9; - let e92: vec4 = textureSample(tex2DArray, samp, e86.xy, i32(e86.z), vec2(5, 5)); - c_3 = e92; - let e97: vec3 = coord_9; - let e104: vec4 = textureSampleBias(tex2DArray, samp, e97.xy, i32(e97.z), 2.0, vec2(5, 5)); - c_3 = e104; + let _e18: vec3 = coord_9; + let _e22: vec4 = textureSample(tex2DArray, samp, _e18.xy, i32(_e18.z)); + c_3 = _e22; + let _e25: vec3 = coord_9; + let _e30: vec4 = textureSampleBias(tex2DArray, samp, _e25.xy, i32(_e25.z), 2.0); + c_3 = _e30; + let _e36: vec3 = coord_9; + let _e44: vec4 = textureSampleGrad(tex2DArray, samp, _e36.xy, i32(_e36.z), vec2(4.0), vec2(4.0)); + c_3 = _e44; + let _e52: vec3 = coord_9; + let _e62: vec4 = textureSampleGrad(tex2DArray, samp, _e52.xy, i32(_e52.z), vec2(4.0), vec2(4.0), vec2(5, 5)); + c_3 = _e62; + let _e65: vec3 = coord_9; + let _e70: vec4 = textureSampleLevel(tex2DArray, samp, _e65.xy, i32(_e65.z), 3.0); + c_3 = _e70; + let _e75: vec3 = coord_9; + let _e82: vec4 = textureSampleLevel(tex2DArray, samp, _e75.xy, i32(_e75.z), 3.0, vec2(5, 5)); + c_3 = _e82; + let _e86: vec3 = coord_9; + let _e92: vec4 = textureSample(tex2DArray, samp, _e86.xy, i32(_e86.z), vec2(5, 5)); + c_3 = _e92; + let _e97: vec3 = coord_9; + let _e104: vec4 = textureSampleBias(tex2DArray, samp, _e97.xy, i32(_e97.z), 2.0, vec2(5, 5)); + c_3 = _e104; return; } @@ -395,36 +395,36 @@ fn testTex2DArrayShadow(coord_10: vec3) { var d_1: f32; coord_11 = coord_10; - let e17: vec3 = coord_11; - let e20: vec3 = coord_11; - let e22: vec4 = vec4(e20, 1.0); - let e27: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e22.xy, i32(e22.z), e22.w); - d_1 = e27; - let e28: vec3 = coord_11; - let e35: vec3 = coord_11; - let e37: vec4 = vec4(e35, 1.0); - let e46: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e37.xy, i32(e37.z), e37.w); - d_1 = e46; - let e47: vec3 = coord_11; - let e56: vec3 = coord_11; - let e58: vec4 = vec4(e56, 1.0); - let e69: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e58.xy, i32(e58.z), e58.w, vec2(5, 5)); - d_1 = e69; - let e70: vec3 = coord_11; - let e74: vec3 = coord_11; - let e76: vec4 = vec4(e74, 1.0); - let e82: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e76.xy, i32(e76.z), e76.w); - d_1 = e82; - let e83: vec3 = coord_11; - let e89: vec3 = coord_11; - let e91: vec4 = vec4(e89, 1.0); - let e99: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e91.xy, i32(e91.z), e91.w, vec2(5, 5)); - d_1 = e99; - let e100: vec3 = coord_11; - let e105: vec3 = coord_11; - let e107: vec4 = vec4(e105, 1.0); - let e114: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e107.xy, i32(e107.z), e107.w, vec2(5, 5)); - d_1 = e114; + let _e17: vec3 = coord_11; + let _e20: vec3 = coord_11; + let _e22: vec4 = vec4(_e20, 1.0); + let _e27: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e22.xy, i32(_e22.z), _e22.w); + d_1 = _e27; + let _e28: vec3 = coord_11; + let _e35: vec3 = coord_11; + let _e37: vec4 = vec4(_e35, 1.0); + let _e46: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e37.xy, i32(_e37.z), _e37.w); + d_1 = _e46; + let _e47: vec3 = coord_11; + let _e56: vec3 = coord_11; + let _e58: vec4 = vec4(_e56, 1.0); + let _e69: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e58.xy, i32(_e58.z), _e58.w, vec2(5, 5)); + d_1 = _e69; + let _e70: vec3 = coord_11; + let _e74: vec3 = coord_11; + let _e76: vec4 = vec4(_e74, 1.0); + let _e82: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e76.xy, i32(_e76.z), _e76.w); + d_1 = _e82; + let _e83: vec3 = coord_11; + let _e89: vec3 = coord_11; + let _e91: vec4 = vec4(_e89, 1.0); + let _e99: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e91.xy, i32(_e91.z), _e91.w, vec2(5, 5)); + d_1 = _e99; + let _e100: vec3 = coord_11; + let _e105: vec3 = coord_11; + let _e107: vec4 = vec4(_e105, 1.0); + let _e114: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e107.xy, i32(_e107.z), _e107.w, vec2(5, 5)); + d_1 = _e114; return; } @@ -433,27 +433,27 @@ fn testTexCube(coord_12: vec3) { var c_4: vec4; coord_13 = coord_12; - let e18: vec3 = coord_13; - let e19: vec4 = textureSample(texCube, samp, e18); - c_4 = e19; - let e22: vec3 = coord_13; - let e24: vec4 = textureSampleBias(texCube, samp, e22, 2.0); - c_4 = e24; - let e30: vec3 = coord_13; - let e35: vec4 = textureSampleGrad(texCube, samp, e30, vec3(4.0), vec3(4.0)); - c_4 = e35; - let e38: vec3 = coord_13; - let e40: vec4 = textureSampleLevel(texCube, samp, e38, 3.0); - c_4 = e40; - let e45: vec3 = coord_13; - let e49: vec4 = textureSampleLevel(texCube, samp, e45, 3.0, vec3(5, 5, 5)); - c_4 = e49; - let e53: vec3 = coord_13; - let e56: vec4 = textureSample(texCube, samp, e53, vec3(5, 5, 5)); - c_4 = e56; - let e61: vec3 = coord_13; - let e65: vec4 = textureSampleBias(texCube, samp, e61, 2.0, vec3(5, 5, 5)); - c_4 = e65; + let _e18: vec3 = coord_13; + let _e19: vec4 = textureSample(texCube, samp, _e18); + c_4 = _e19; + let _e22: vec3 = coord_13; + let _e24: vec4 = textureSampleBias(texCube, samp, _e22, 2.0); + c_4 = _e24; + let _e30: vec3 = coord_13; + let _e35: vec4 = textureSampleGrad(texCube, samp, _e30, vec3(4.0), vec3(4.0)); + c_4 = _e35; + let _e38: vec3 = coord_13; + let _e40: vec4 = textureSampleLevel(texCube, samp, _e38, 3.0); + c_4 = _e40; + let _e45: vec3 = coord_13; + let _e49: vec4 = textureSampleLevel(texCube, samp, _e45, 3.0, vec3(5, 5, 5)); + c_4 = _e49; + let _e53: vec3 = coord_13; + let _e56: vec4 = textureSample(texCube, samp, _e53, vec3(5, 5, 5)); + c_4 = _e56; + let _e61: vec3 = coord_13; + let _e65: vec4 = textureSampleBias(texCube, samp, _e61, 2.0, vec3(5, 5, 5)); + c_4 = _e65; return; } @@ -462,31 +462,31 @@ fn testTexCubeShadow(coord_14: vec3) { var d_2: f32; coord_15 = coord_14; - let e17: vec3 = coord_15; - let e20: vec3 = coord_15; - let e22: vec4 = vec4(e20, 1.0); - let e25: f32 = textureSampleCompare(texCubeShadow, sampShadow, e22.xyz, e22.w); - d_2 = e25; - let e26: vec3 = coord_15; - let e33: vec3 = coord_15; - let e35: vec4 = vec4(e33, 1.0); - let e42: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e35.xyz, e35.w); - d_2 = e42; - let e43: vec3 = coord_15; - let e47: vec3 = coord_15; - let e49: vec4 = vec4(e47, 1.0); - let e53: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e49.xyz, e49.w); - d_2 = e53; - let e54: vec3 = coord_15; - let e60: vec3 = coord_15; - let e62: vec4 = vec4(e60, 1.0); - let e68: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e62.xyz, e62.w, vec3(5, 5, 5)); - d_2 = e68; - let e69: vec3 = coord_15; - let e74: vec3 = coord_15; - let e76: vec4 = vec4(e74, 1.0); - let e81: f32 = textureSampleCompare(texCubeShadow, sampShadow, e76.xyz, e76.w, vec3(5, 5, 5)); - d_2 = e81; + let _e17: vec3 = coord_15; + let _e20: vec3 = coord_15; + let _e22: vec4 = vec4(_e20, 1.0); + let _e25: f32 = textureSampleCompare(texCubeShadow, sampShadow, _e22.xyz, _e22.w); + d_2 = _e25; + let _e26: vec3 = coord_15; + let _e33: vec3 = coord_15; + let _e35: vec4 = vec4(_e33, 1.0); + let _e42: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e35.xyz, _e35.w); + d_2 = _e42; + let _e43: vec3 = coord_15; + let _e47: vec3 = coord_15; + let _e49: vec4 = vec4(_e47, 1.0); + let _e53: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e49.xyz, _e49.w); + d_2 = _e53; + let _e54: vec3 = coord_15; + let _e60: vec3 = coord_15; + let _e62: vec4 = vec4(_e60, 1.0); + let _e68: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e62.xyz, _e62.w, vec3(5, 5, 5)); + d_2 = _e68; + let _e69: vec3 = coord_15; + let _e74: vec3 = coord_15; + let _e76: vec4 = vec4(_e74, 1.0); + let _e81: f32 = textureSampleCompare(texCubeShadow, sampShadow, _e76.xyz, _e76.w, vec3(5, 5, 5)); + d_2 = _e81; return; } @@ -495,27 +495,27 @@ fn testTexCubeArray(coord_16: vec4) { var c_5: vec4; coord_17 = coord_16; - let e18: vec4 = coord_17; - let e22: vec4 = textureSample(texCubeArray, samp, e18.xyz, i32(e18.w)); - c_5 = e22; - let e25: vec4 = coord_17; - let e30: vec4 = textureSampleBias(texCubeArray, samp, e25.xyz, i32(e25.w), 2.0); - c_5 = e30; - let e36: vec4 = coord_17; - let e44: vec4 = textureSampleGrad(texCubeArray, samp, e36.xyz, i32(e36.w), vec3(4.0), vec3(4.0)); - c_5 = e44; - let e47: vec4 = coord_17; - let e52: vec4 = textureSampleLevel(texCubeArray, samp, e47.xyz, i32(e47.w), 3.0); - c_5 = e52; - let e57: vec4 = coord_17; - let e64: vec4 = textureSampleLevel(texCubeArray, samp, e57.xyz, i32(e57.w), 3.0, vec3(5, 5, 5)); - c_5 = e64; - let e68: vec4 = coord_17; - let e74: vec4 = textureSample(texCubeArray, samp, e68.xyz, i32(e68.w), vec3(5, 5, 5)); - c_5 = e74; - let e79: vec4 = coord_17; - let e86: vec4 = textureSampleBias(texCubeArray, samp, e79.xyz, i32(e79.w), 2.0, vec3(5, 5, 5)); - c_5 = e86; + let _e18: vec4 = coord_17; + let _e22: vec4 = textureSample(texCubeArray, samp, _e18.xyz, i32(_e18.w)); + c_5 = _e22; + let _e25: vec4 = coord_17; + let _e30: vec4 = textureSampleBias(texCubeArray, samp, _e25.xyz, i32(_e25.w), 2.0); + c_5 = _e30; + let _e36: vec4 = coord_17; + let _e44: vec4 = textureSampleGrad(texCubeArray, samp, _e36.xyz, i32(_e36.w), vec3(4.0), vec3(4.0)); + c_5 = _e44; + let _e47: vec4 = coord_17; + let _e52: vec4 = textureSampleLevel(texCubeArray, samp, _e47.xyz, i32(_e47.w), 3.0); + c_5 = _e52; + let _e57: vec4 = coord_17; + let _e64: vec4 = textureSampleLevel(texCubeArray, samp, _e57.xyz, i32(_e57.w), 3.0, vec3(5, 5, 5)); + c_5 = _e64; + let _e68: vec4 = coord_17; + let _e74: vec4 = textureSample(texCubeArray, samp, _e68.xyz, i32(_e68.w), vec3(5, 5, 5)); + c_5 = _e74; + let _e79: vec4 = coord_17; + let _e86: vec4 = textureSampleBias(texCubeArray, samp, _e79.xyz, i32(_e79.w), 2.0, vec3(5, 5, 5)); + c_5 = _e86; return; } @@ -524,9 +524,9 @@ fn testTexCubeArrayShadow(coord_18: vec4) { var d_3: f32; coord_19 = coord_18; - let e19: vec4 = coord_19; - let e24: f32 = textureSampleCompare(texCubeArrayShadow, sampShadow, e19.xyz, i32(e19.w), 1.0); - d_3 = e24; + let _e19: vec4 = coord_19; + let _e24: f32 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e19.xyz, i32(_e19.w), 1.0); + d_3 = _e24; return; } @@ -535,30 +535,30 @@ fn testTex3D(coord_20: vec3) { var c_6: vec4; coord_21 = coord_20; - let e18: vec3 = coord_21; - let e19: vec4 = textureSample(tex3D, samp, e18); - c_6 = e19; - let e22: vec3 = coord_21; - let e24: vec4 = textureSampleBias(tex3D, samp, e22, 2.0); - c_6 = e24; - let e30: vec3 = coord_21; - let e35: vec4 = textureSampleGrad(tex3D, samp, e30, vec3(4.0), vec3(4.0)); - c_6 = e35; - let e43: vec3 = coord_21; - let e50: vec4 = textureSampleGrad(tex3D, samp, e43, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); - c_6 = e50; - let e53: vec3 = coord_21; - let e55: vec4 = textureSampleLevel(tex3D, samp, e53, 3.0); - c_6 = e55; - let e60: vec3 = coord_21; - let e64: vec4 = textureSampleLevel(tex3D, samp, e60, 3.0, vec3(5, 5, 5)); - c_6 = e64; - let e68: vec3 = coord_21; - let e71: vec4 = textureSample(tex3D, samp, e68, vec3(5, 5, 5)); - c_6 = e71; - let e76: vec3 = coord_21; - let e80: vec4 = textureSampleBias(tex3D, samp, e76, 2.0, vec3(5, 5, 5)); - c_6 = e80; + let _e18: vec3 = coord_21; + let _e19: vec4 = textureSample(tex3D, samp, _e18); + c_6 = _e19; + let _e22: vec3 = coord_21; + let _e24: vec4 = textureSampleBias(tex3D, samp, _e22, 2.0); + c_6 = _e24; + let _e30: vec3 = coord_21; + let _e35: vec4 = textureSampleGrad(tex3D, samp, _e30, vec3(4.0), vec3(4.0)); + c_6 = _e35; + let _e43: vec3 = coord_21; + let _e50: vec4 = textureSampleGrad(tex3D, samp, _e43, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + c_6 = _e50; + let _e53: vec3 = coord_21; + let _e55: vec4 = textureSampleLevel(tex3D, samp, _e53, 3.0); + c_6 = _e55; + let _e60: vec3 = coord_21; + let _e64: vec4 = textureSampleLevel(tex3D, samp, _e60, 3.0, vec3(5, 5, 5)); + c_6 = _e64; + let _e68: vec3 = coord_21; + let _e71: vec4 = textureSample(tex3D, samp, _e68, vec3(5, 5, 5)); + c_6 = _e71; + let _e76: vec3 = coord_21; + let _e80: vec4 = textureSampleBias(tex3D, samp, _e76, 2.0, vec3(5, 5, 5)); + c_6 = _e80; return; } diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 376b66d87..e6b3967d7 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -32,8 +32,8 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { } let flip_correction: vec2 = vec2(0.5, -0.5); let light_local: vec2 = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - let e26: f32 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); - return e26; + let _e26: f32 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); + return _e26; } [[stage(fragment)]] @@ -43,24 +43,24 @@ fn fs_main([[location(0)]] raw_normal: vec3, [[location(1)]] position: vec4 let normal: vec3 = normalize(raw_normal); loop { - let e12: u32 = i; - let e15: u32 = u_globals.num_lights.x; - if ((e12 >= min(e15, c_max_lights))) { + let _e12: u32 = i; + let _e15: u32 = u_globals.num_lights.x; + if ((_e12 >= min(_e15, c_max_lights))) { break; } - let e19: u32 = i; - let light: Light = s_lights.data[e19]; - let e22: u32 = i; - let e25: f32 = fetch_shadow(e22, (light.proj * position)); + let _e19: u32 = i; + let light: Light = s_lights.data[_e19]; + let _e22: u32 = i; + let _e25: f32 = fetch_shadow(_e22, (light.proj * position)); let light_dir: vec3 = normalize((light.pos.xyz - position.xyz)); let diffuse: f32 = max(0.0, dot(normal, light_dir)); - let e34: vec3 = color; - color = (e34 + ((e25 * diffuse) * light.color.xyz)); + let _e34: vec3 = color; + color = (_e34 + ((_e25 * diffuse) * light.color.xyz)); continuing { - let e40: u32 = i; - i = (e40 + 1u); + let _e40: u32 = i; + i = (_e40 + 1u); } } - let e43: vec3 = color; - return vec4(e43, 1.0); + let _e43: vec3 = color; + return vec4(_e43, 1.0); } diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index 27565be73..75460c49b 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -23,20 +23,20 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { tmp1_ = (i32(vertex_index) / 2); tmp2_ = (i32(vertex_index) & 1); - let e10: i32 = tmp1_; - let e16: i32 = tmp2_; - let pos: vec4 = vec4(((f32(e10) * 4.0) - 1.0), ((f32(e16) * 4.0) - 1.0), 0.0, 1.0); - let e27: vec4 = r_data.view[0]; - let e31: vec4 = r_data.view[1]; - let e35: vec4 = r_data.view[2]; - let inv_model_view: mat3x3 = transpose(mat3x3(e27.xyz, e31.xyz, e35.xyz)); - let e40: mat4x4 = r_data.proj_inv; - let unprojected: vec4 = (e40 * pos); + let _e10: i32 = tmp1_; + let _e16: i32 = tmp2_; + let pos: vec4 = vec4(((f32(_e10) * 4.0) - 1.0), ((f32(_e16) * 4.0) - 1.0), 0.0, 1.0); + let _e27: vec4 = r_data.view[0]; + let _e31: vec4 = r_data.view[1]; + let _e35: vec4 = r_data.view[2]; + let inv_model_view: mat3x3 = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); + let _e40: mat4x4 = r_data.proj_inv; + let unprojected: vec4 = (_e40 * pos); return VertexOutput(pos, (inv_model_view * unprojected.xyz)); } [[stage(fragment)]] fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 { - let e5: vec4 = textureSample(r_texture, r_sampler, in.uv); - return e5; + let _e5: vec4 = textureSample(r_texture, r_sampler, in.uv); + return _e5; } diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index ece461039..5be3815d5 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -1,15 +1,15 @@ fn main_1() { var x: vec3 = vec3(2.0, 2.0, 2.0); - let e3: vec3 = x; - let e8: vec2 = vec2(3.0, 4.0); - x.z = e8.x; - x.x = e8.y; - let e13: vec3 = x; - let e15: vec3 = x; - let e18: vec2 = (e15.xy * 5.0); - x.x = e18.x; - x.y = e18.y; + let _e3: vec3 = x; + let _e8: vec2 = vec2(3.0, 4.0); + x.z = _e8.x; + x.x = _e8.y; + let _e13: vec3 = x; + let _e15: vec3 = x; + let _e18: vec2 = (_e15.xy * 5.0); + x.x = _e18.x; + x.y = _e18.y; return; } diff --git a/tests/out/wgsl/texture-arg.wgsl b/tests/out/wgsl/texture-arg.wgsl index a013b1527..420b43780 100644 --- a/tests/out/wgsl/texture-arg.wgsl +++ b/tests/out/wgsl/texture-arg.wgsl @@ -4,12 +4,12 @@ var Texture: texture_2d; var Sampler: sampler; fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { - let e7: vec4 = textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); - return e7; + let _e7: vec4 = textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); + return _e7; } [[stage(fragment)]] fn main() -> [[location(0)]] vec4 { - let e2: vec4 = test(Texture, Sampler); - return e2; + let _e2: vec4 = test(Texture, Sampler); + return _e2; } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 571a34962..2ebef2c30 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -17,6 +17,20 @@ fn check(input: &str, snapshot: &str) { } } +#[test] +fn reserved_identifier_prefix() { + check( + "var __bad;", + r###"error: Identifier starts with a reserved prefix: '__bad' + ┌─ wgsl:1:5 + │ +1 │ var __bad; + │ ^^^^^ invalid identifier + +"###, + ); +} + #[test] fn function_without_identifier() { check( From 7c2fdf94c0e414e61b63747b7d99530a62473aa5 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 25 Nov 2021 02:11:41 +0300 Subject: [PATCH 1457/2212] [wgsl-out] Add double underscores as a reserved prefix --- src/back/wgsl/writer.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 7fb32f317..1fef5b53d 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -75,7 +75,8 @@ impl Writer { self.namer.reset( module, crate::keywords::wgsl::RESERVED, - &[], + // an identifier must not start with two underscore + &["__"], &mut self.names, ); self.named_expressions.clear(); From f4ba74544aa00b5c3d791eee60274026f8ad7abd Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 26 Nov 2021 11:29:35 -0500 Subject: [PATCH 1458/2212] Refactor snapshot test arguments to avoid checking for deserialize feature too often. We can safely assume that deserialize is enabled for all output tests. Supporting other modes of operation has low utility. This change also adds an option to skip the explicit types for WGSL output. --- cli/src/main.rs | 1 + src/back/wgsl/mod.rs | 5 +- src/back/wgsl/writer.rs | 34 +++- src/proc/index.rs | 5 + tests/in/access.param.ron | 1 - tests/in/bits.param.ron | 1 - tests/in/boids.param.ron | 1 - .../in/bounds-check-image-restrict.param.ron | 4 +- tests/in/bounds-check-image-rzsw.param.ron | 4 +- tests/in/bounds-check-zero.param.ron | 6 +- tests/in/extra.param.ron | 1 - tests/in/image.param.ron | 2 +- tests/in/interface.param.ron | 1 - tests/in/interpolate.param.ron | 1 - tests/in/pointers.param.ron | 4 +- tests/in/policy-mix.param.ron | 8 +- tests/in/quad.param.ron | 1 - tests/in/skybox.param.ron | 3 - tests/snapshots.rs | 184 +++++++----------- 19 files changed, 119 insertions(+), 148 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 5f5d59f22..56306a501 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -454,6 +454,7 @@ fn run() -> Result<(), Box> { "Generating wgsl output requires validation to \ succeed, and it failed in a previous step", ))?, + wgsl::WriterFlags::empty(), ) .unwrap_pretty(); fs::write(output_path, wgsl)?; diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index 6f02367e1..b934662e1 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -2,7 +2,7 @@ mod writer; use thiserror::Error; -pub use writer::Writer; +pub use writer::{Writer, WriterFlags}; #[derive(Error, Debug)] pub enum Error { @@ -21,8 +21,9 @@ pub enum Error { pub fn write_string( module: &crate::Module, info: &crate::valid::ModuleInfo, + flags: WriterFlags, ) -> Result { - let mut w = Writer::new(String::new()); + let mut w = Writer::new(String::new(), flags); w.write(module, info)?; let output = w.finish(); Ok(output) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 1fef5b53d..0f19f765b 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -51,8 +51,18 @@ enum Indirection { Reference, } +bitflags::bitflags! { + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + pub struct WriterFlags: u32 { + /// Always annotate the type information instead of inferring. + const EXPLICIT_TYPES = 0x1; + } +} + pub struct Writer { out: W, + flags: WriterFlags, names: crate::FastHashMap, namer: proc::Namer, named_expressions: crate::NamedExpressions, @@ -60,9 +70,10 @@ pub struct Writer { } impl Writer { - pub fn new(out: W) -> Self { + pub fn new(out: W, flags: WriterFlags) -> Self { Writer { out, + flags, names: crate::FastHashMap::default(), namer: proc::Namer::default(), named_expressions: crate::NamedExpressions::default(), @@ -1032,15 +1043,18 @@ impl Writer { name: &str, ) -> BackendResult { // Write variable name - write!(self.out, "let {}: ", name)?; - let ty = &func_ctx.info[handle].ty; - // Write variable type - match *ty { - proc::TypeResolution::Handle(handle) => { - self.write_type(module, handle)?; - } - proc::TypeResolution::Value(ref inner) => { - self.write_value_type(module, inner)?; + write!(self.out, "let {}", name)?; + if self.flags.contains(WriterFlags::EXPLICIT_TYPES) { + write!(self.out, ": ")?; + let ty = &func_ctx.info[handle].ty; + // Write variable type + match *ty { + proc::TypeResolution::Handle(handle) => { + self.write_type(module, handle)?; + } + proc::TypeResolution::Value(ref inner) => { + self.write_value_type(module, inner)?; + } } } diff --git a/src/proc/index.rs b/src/proc/index.rs index 080be03cb..27110cb5a 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -34,6 +34,7 @@ use crate::{Handle, UniqueArena}; /// checks as well would be redundant, and the `Unchecked` policy is /// appropriate. #[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum BoundsCheckPolicy { /// Replace out-of-bounds indexes with some arbitrary in-bounds index. /// @@ -53,10 +54,12 @@ pub enum BoundsCheckPolicy { } #[derive(Clone, Copy, Debug, Default)] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] /// Policies for injecting bounds checks during code generation. pub struct BoundsCheckPolicies { /// How should the generated code handle array, vector, or matrix indices /// that are out of range? + #[cfg_attr(feature = "deserialize", serde(default))] pub index: BoundsCheckPolicy, /// How should the generated code handle array, vector, or matrix indices @@ -92,6 +95,7 @@ pub struct BoundsCheckPolicies { /// [`AccessIndex`]: crate::Expression::AccessIndex /// [`Storage`]: crate::StorageClass::Storage /// [`Uniform`]: crate::StorageClass::Uniform + #[cfg_attr(feature = "deserialize", serde(default))] pub buffer: BoundsCheckPolicy, /// How should the generated code handle image texel references that are out @@ -103,6 +107,7 @@ pub struct BoundsCheckPolicies { /// /// [`ImageLoad`]: crate::Expression::ImageLoad /// [`ImageStore`]: crate::Statement::ImageStore + #[cfg_attr(feature = "deserialize", serde(default))] pub image: BoundsCheckPolicy, } diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 4cff7e55c..3e9214f47 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -4,7 +4,6 @@ debug: true, adjust_coordinate_space: false, ), - msl_custom: true, msl: ( lang_version: (2, 0), per_stage_map: ( diff --git a/tests/in/bits.param.ron b/tests/in/bits.param.ron index 3017db2d6..fb45784e5 100644 --- a/tests/in/bits.param.ron +++ b/tests/in/bits.param.ron @@ -1,5 +1,4 @@ ( - msl_custom: true, msl: ( lang_version: (1, 2), per_stage_map: ( diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index e17036fc9..91181f7dd 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -4,7 +4,6 @@ debug: true, adjust_coordinate_space: false, ), - msl_custom: true, msl: ( lang_version: (2, 0), per_stage_map: ( diff --git a/tests/in/bounds-check-image-restrict.param.ron b/tests/in/bounds-check-image-restrict.param.ron index 2baa4fa0b..d6af131df 100644 --- a/tests/in/bounds-check-image-restrict.param.ron +++ b/tests/in/bounds-check-image-restrict.param.ron @@ -1,5 +1,7 @@ ( - image_bounds_check_policy: Restrict, + bounds_check_policies: ( + image: Restrict, + ), spv: ( version: (1, 1), debug: true, diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/tests/in/bounds-check-image-rzsw.param.ron index 7bfacb741..2d00b645c 100644 --- a/tests/in/bounds-check-image-rzsw.param.ron +++ b/tests/in/bounds-check-image-rzsw.param.ron @@ -1,5 +1,7 @@ ( - image_bounds_check_policy: ReadZeroSkipWrite, + bounds_check_policies: ( + image: ReadZeroSkipWrite, + ), spv: ( version: (1, 1), debug: true, diff --git a/tests/in/bounds-check-zero.param.ron b/tests/in/bounds-check-zero.param.ron index 5bb269c91..3ca0053af 100644 --- a/tests/in/bounds-check-zero.param.ron +++ b/tests/in/bounds-check-zero.param.ron @@ -1,4 +1,6 @@ ( - index_bounds_check_policy: ReadZeroSkipWrite, - buffer_bounds_check_policy: ReadZeroSkipWrite, + bounds_check_policies: ( + index: ReadZeroSkipWrite, + buffer: ReadZeroSkipWrite, + ), ) diff --git a/tests/in/extra.param.ron b/tests/in/extra.param.ron index e08588bfa..c003cf469 100644 --- a/tests/in/extra.param.ron +++ b/tests/in/extra.param.ron @@ -3,7 +3,6 @@ spv: ( version: (1, 2), ), - msl_custom: true, msl: ( lang_version: (2, 2), per_stage_map: (), diff --git a/tests/in/image.param.ron b/tests/in/image.param.ron index 721b98fb2..76105e335 100644 --- a/tests/in/image.param.ron +++ b/tests/in/image.param.ron @@ -3,5 +3,5 @@ version: (1, 1), debug: true, ), - glsl_blacklist: ["depth_load", "levels_queries"] + glsl_exclude_list: ["depth_load", "levels_queries"] ) diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index 4e32d785c..d88b2ac14 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -7,7 +7,6 @@ clamp_frag_depth: true, separate_entry_points: true, ), - hlsl_custom: true, hlsl: ( shader_model: V5_1, binding_map: {}, diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index 8566e665c..cb08368c8 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -11,5 +11,4 @@ writer_flags: (bits: 0), binding_map: {}, ), - glsl_custom: true, ) diff --git a/tests/in/pointers.param.ron b/tests/in/pointers.param.ron index 10454c4d1..fee286e50 100644 --- a/tests/in/pointers.param.ron +++ b/tests/in/pointers.param.ron @@ -1,5 +1,7 @@ ( - index_bounds_check_policy: ReadZeroSkipWrite, + bounds_check_policies: ( + image: ReadZeroSkipWrite, + ), spv: ( version: (1, 2), debug: true, diff --git a/tests/in/policy-mix.param.ron b/tests/in/policy-mix.param.ron index 1387e5f60..9136eed38 100644 --- a/tests/in/policy-mix.param.ron +++ b/tests/in/policy-mix.param.ron @@ -1,7 +1,9 @@ ( - index_bounds_check_policy: Restrict, - buffer_bounds_check_policy: Unchecked, - image_bounds_check_policy: ReadZeroSkipWrite, + bounds_check_policies: ( + index: Restrict, + buffer: Unchecked, + image: ReadZeroSkipWrite, + ), spv: ( version: (1, 1), debug: true, diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index f346a2a67..acde3aed4 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -4,7 +4,6 @@ debug: true, adjust_coordinate_space: true, ), - glsl_custom: true, glsl: ( version: Embedded(300), writer_flags: (bits: 0), diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index dad0ab483..9c9bd1f30 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -5,7 +5,6 @@ debug: false, adjust_coordinate_space: false, ), - msl_custom: true, msl: ( lang_version: (2, 1), per_stage_map: ( @@ -37,7 +36,6 @@ spirv_cross_compatibility: false, fake_missing_bindings: false, ), - glsl_custom: true, glsl: ( version: Embedded(320), writer_flags: (bits: 0), @@ -46,7 +44,6 @@ (group: 0, binding: 1): 0, }, ), - hlsl_custom: true, hlsl: ( shader_model: V5_1, binding_map: { diff --git a/tests/snapshots.rs b/tests/snapshots.rs index eaae4f795..ce15b6e10 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -16,30 +16,6 @@ bitflags::bitflags! { } } -/// Twin of `naga::back::BoundsCheckPolicy`, always serializable. -#[derive(Clone, Copy, serde::Deserialize)] -enum BoundsCheckPolicyArg { - Restrict, - ReadZeroSkipWrite, - Unchecked, -} - -impl Default for BoundsCheckPolicyArg { - fn default() -> Self { - BoundsCheckPolicyArg::Unchecked - } -} - -impl From for naga::proc::BoundsCheckPolicy { - fn from(arg: BoundsCheckPolicyArg) -> Self { - match arg { - BoundsCheckPolicyArg::Restrict => Self::Restrict, - BoundsCheckPolicyArg::ReadZeroSkipWrite => Self::ReadZeroSkipWrite, - BoundsCheckPolicyArg::Unchecked => Self::Unchecked, - } - } -} - #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] #[derive(serde::Deserialize)] struct SpvOutVersion(u8, u8); @@ -67,44 +43,36 @@ struct SpirvOutParameters { separate_entry_points: bool, } +#[cfg_attr(not(feature = "wgsl-out"), allow(dead_code))] +#[derive(Default, serde::Deserialize)] +struct WgslOutParameters { + #[serde(default)] + explicit_types: bool, +} + +#[allow(dead_code)] #[derive(Default, serde::Deserialize)] struct Parameters { #[serde(default)] god_mode: bool, - - #[allow(dead_code)] + #[cfg(feature = "deserialize")] #[serde(default)] - index_bounds_check_policy: BoundsCheckPolicyArg, - #[allow(dead_code)] - #[serde(default)] - buffer_bounds_check_policy: BoundsCheckPolicyArg, - #[allow(dead_code)] - #[serde(default)] - image_bounds_check_policy: BoundsCheckPolicyArg, - #[cfg_attr(not(feature = "spv-out"), allow(dead_code))] + bounds_check_policies: naga::proc::BoundsCheckPolicies, #[serde(default)] spv: SpirvOutParameters, #[cfg(all(feature = "deserialize", feature = "msl-out"))] #[serde(default)] msl: naga::back::msl::Options, - #[cfg(all(not(feature = "deserialize"), feature = "msl-out"))] - #[serde(default)] - msl_custom: bool, #[cfg(all(feature = "deserialize", feature = "glsl-out"))] #[serde(default)] glsl: naga::back::glsl::Options, - #[cfg(all(not(feature = "deserialize"), feature = "glsl-out"))] #[serde(default)] - glsl_custom: bool, - #[cfg_attr(not(feature = "glsl-out"), allow(dead_code))] - #[serde(default)] - glsl_blacklist: naga::FastHashSet, + glsl_exclude_list: naga::FastHashSet, #[cfg(all(feature = "deserialize", feature = "hlsl-out"))] #[serde(default)] hlsl: naga::back::hlsl::Options, - #[cfg(all(not(feature = "deserialize"), feature = "hlsl-out"))] #[serde(default)] - hlsl_custom: bool, + wgsl: WgslOutParameters, } #[allow(dead_code, unused_variables)] @@ -144,23 +112,41 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { } } + if !cfg!(feature = "deserialize") { + println!( + "No access to parameters, skipping {} for {:?}", + name, targets + ); + return; + } + #[cfg(feature = "spv-out")] { if targets.contains(Targets::SPIRV) { - write_output_spv(module, &info, &dest, name, ¶ms); + write_output_spv( + module, + &info, + &dest, + name, + ¶ms.spv, + params.bounds_check_policies, + ); } } #[cfg(feature = "msl-out")] { if targets.contains(Targets::METAL) { - write_output_msl(module, &info, &dest, name, ¶ms); + write_output_msl(module, &info, &dest, name, ¶ms.msl); } } #[cfg(feature = "glsl-out")] { if targets.contains(Targets::GLSL) { for ep in module.entry_points.iter() { - write_output_glsl(module, &info, &dest, name, ep.stage, &ep.name, ¶ms); + if params.glsl_exclude_list.contains(&ep.name) { + return; + } + write_output_glsl(module, &info, &dest, name, ep.stage, &ep.name, ¶ms.glsl); } } } @@ -174,13 +160,13 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "hlsl-out")] { if targets.contains(Targets::HLSL) { - write_output_hlsl(module, &info, &dest, name, ¶ms); + write_output_hlsl(module, &info, &dest, name, ¶ms.hlsl); } } #[cfg(feature = "wgsl-out")] { if targets.contains(Targets::WGSL) { - write_output_wgsl(module, &info, &dest, name); + write_output_wgsl(module, &info, &dest, name, ¶ms.wgsl); } } } @@ -191,45 +177,36 @@ fn write_output_spv( info: &naga::valid::ModuleInfo, destination: &PathBuf, file_name: &str, - params: &Parameters, + params: &SpirvOutParameters, + bounds_check_policies: naga::proc::BoundsCheckPolicies, ) { use naga::back::spv; use rspirv::binary::Disassemble; println!("writing SPIR-V"); + let mut flags = spv::WriterFlags::LABEL_VARYINGS; - flags.set(spv::WriterFlags::DEBUG, params.spv.debug); + flags.set(spv::WriterFlags::DEBUG, params.debug); flags.set( spv::WriterFlags::ADJUST_COORDINATE_SPACE, - params.spv.adjust_coordinate_space, - ); - flags.set( - spv::WriterFlags::FORCE_POINT_SIZE, - params.spv.force_point_size, - ); - flags.set( - spv::WriterFlags::CLAMP_FRAG_DEPTH, - params.spv.clamp_frag_depth, + params.adjust_coordinate_space, ); + flags.set(spv::WriterFlags::FORCE_POINT_SIZE, params.force_point_size); + flags.set(spv::WriterFlags::CLAMP_FRAG_DEPTH, params.clamp_frag_depth); + let options = spv::Options { - lang_version: (params.spv.version.0, params.spv.version.1), + lang_version: (params.version.0, params.version.1), flags, - capabilities: if params.spv.capabilities.is_empty() { + capabilities: if params.capabilities.is_empty() { None } else { - Some(params.spv.capabilities.clone()) + Some(params.capabilities.clone()) }, - - bounds_check_policies: naga::proc::BoundsCheckPolicies { - index: params.index_bounds_check_policy.into(), - buffer: params.buffer_bounds_check_policy.into(), - image: params.image_bounds_check_policy.into(), - }, - + bounds_check_policies, ..spv::Options::default() }; - if params.spv.separate_entry_points { + if params.separate_entry_points { for ep in module.entry_points.iter() { let pipeline_options = spv::PipelineOptions { entry_point: ep.name.clone(), @@ -257,24 +234,12 @@ fn write_output_msl( info: &naga::valid::ModuleInfo, destination: &PathBuf, file_name: &str, - params: &Parameters, + options: &naga::back::msl::Options, ) { use naga::back::msl; println!("writing MSL"); - #[cfg_attr(feature = "deserialize", allow(unused_variables))] - let default_options = msl::Options::default(); - #[cfg(feature = "deserialize")] - let options = ¶ms.msl; - #[cfg(not(feature = "deserialize"))] - let options = if params.msl_custom { - println!("Skipping {}", destination.display()); - return; - } else { - &default_options - }; - let pipeline_options = msl::PipelineOptions { allow_point_size: true, }; @@ -299,28 +264,12 @@ fn write_output_glsl( file_name: &str, stage: naga::ShaderStage, ep_name: &str, - params: &Parameters, + options: &naga::back::glsl::Options, ) { use naga::back::glsl; println!("writing GLSL"); - #[cfg_attr(feature = "deserialize", allow(unused_variables))] - let default_options = glsl::Options::default(); - #[cfg(feature = "deserialize")] - let options = ¶ms.glsl; - #[cfg(not(feature = "deserialize"))] - let options = if params.glsl_custom { - println!("Skipping {}", destination.display()); - return; - } else { - &default_options - }; - - if params.glsl_blacklist.contains(ep_name) { - return; - } - let pipeline_options = glsl::PipelineOptions { shader_stage: stage, entry_point: ep_name.to_string(), @@ -344,25 +293,13 @@ fn write_output_hlsl( info: &naga::valid::ModuleInfo, destination: &PathBuf, file_name: &str, - params: &Parameters, + options: &naga::back::hlsl::Options, ) { use naga::back::hlsl; - use std::fmt::Write; + use std::fmt::Write as _; println!("writing HLSL"); - #[cfg_attr(feature = "deserialize", allow(unused_variables))] - let default_options = hlsl::Options::default(); - #[cfg(feature = "deserialize")] - let options = ¶ms.hlsl; - #[cfg(not(feature = "deserialize"))] - let options = if params.hlsl_custom { - println!("Skipping {}", destination.display()); - return; - } else { - &default_options - }; - let mut buffer = String::new(); let mut writer = hlsl::Writer::new(&mut buffer, options); let reflection_info = writer.write(module, info).expect("HLSL write failed"); @@ -435,12 +372,19 @@ fn write_output_wgsl( info: &naga::valid::ModuleInfo, destination: &PathBuf, file_name: &str, + params: &WgslOutParameters, ) { use naga::back::wgsl; println!("writing WGSL"); - let string = wgsl::write_string(module, info).expect("WGSL write failed"); + let mut flags = wgsl::WriterFlags::empty(); + flags.set( + wgsl::WriterFlags::EXPLICIT_TYPES, + params.explicit_types | true, + ); + + let string = wgsl::write_string(module, info, flags).expect("WGSL write failed"); fs::write(destination.join(format!("wgsl/{}.wgsl", file_name)), string).unwrap(); } @@ -652,7 +596,13 @@ fn convert_glsl_folder() { #[cfg(feature = "wgsl-out")] { let dest = PathBuf::from(root).join(BASE_DIR_OUT); - write_output_wgsl(&module, &info, &dest, &file_name.replace(".", "-")); + write_output_wgsl( + &module, + &info, + &dest, + &file_name.replace(".", "-"), + &WgslOutParameters::default(), + ); } } } From 74132ba9472bb760b13b94621b619449d365ea4d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 26 Nov 2021 11:32:00 -0500 Subject: [PATCH 1459/2212] Actually disable explicit types on most WGSL outputs --- tests/in/interface.param.ron | 3 + tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 6 +- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 16 +- tests/out/wgsl/210-bevy-shader-vert.wgsl | 26 +- tests/out/wgsl/246-collatz-comp.wgsl | 24 +- tests/out/wgsl/280-matrix-cast-vert.wgsl | 2 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 16 +- tests/out/wgsl/932-for-loop-if-vert.wgsl | 4 +- tests/out/wgsl/access.wgsl | 36 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 794 +++++++++--------- tests/out/wgsl/bevy-pbr-vert.wgsl | 32 +- tests/out/wgsl/bits.wgsl | 68 +- tests/out/wgsl/bits_glsl-frag.wgsl | 68 +- tests/out/wgsl/boids.wgsl | 106 +-- tests/out/wgsl/bool-select-frag.wgsl | 16 +- tests/out/wgsl/clamp-splat-vert.wgsl | 4 +- tests/out/wgsl/collatz.wgsl | 16 +- tests/out/wgsl/constant-array-size-vert.wgsl | 12 +- tests/out/wgsl/control-flow.wgsl | 4 +- tests/out/wgsl/empty-global-name.wgsl | 2 +- tests/out/wgsl/expressions-frag.wgsl | 152 ++-- tests/out/wgsl/fma-frag.wgsl | 22 +- .../out/wgsl/global-constant-array-vert.wgsl | 2 +- tests/out/wgsl/interpolate.wgsl | 2 +- .../wgsl/inv-hyperbolic-trig-functions.wgsl | 6 +- tests/out/wgsl/long-form-matrix-vert.wgsl | 30 +- tests/out/wgsl/math-functions-vert.wgsl | 122 +-- tests/out/wgsl/operators.wgsl | 46 +- tests/out/wgsl/pointers.wgsl | 8 +- tests/out/wgsl/prepostfix-frag.wgsl | 24 +- tests/out/wgsl/quad-vert.wgsl | 8 +- tests/out/wgsl/quad.wgsl | 4 +- tests/out/wgsl/quad_glsl-frag.wgsl | 2 +- tests/out/wgsl/quad_glsl-vert.wgsl | 8 +- tests/out/wgsl/samplers-frag.wgsl | 672 +++++++-------- tests/out/wgsl/shadow.wgsl | 30 +- tests/out/wgsl/skybox.wgsl | 20 +- tests/out/wgsl/standard.wgsl | 6 +- tests/out/wgsl/swizzle_write-frag.wgsl | 10 +- tests/out/wgsl/texture-arg.wgsl | 4 +- tests/snapshots.rs | 5 +- 41 files changed, 1219 insertions(+), 1219 deletions(-) diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index d88b2ac14..e2f2b32d5 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -13,4 +13,7 @@ fake_missing_bindings: false, special_constants_binding: Some((space: 1, register: 0)), ), + wgsl: ( + explicit_types: true, + ), ) diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index 87c68ec43..c578384da 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -15,9 +15,9 @@ var global: ColorMaterial_color; fn main_1() { var color: vec4; - let _e4: vec4 = global.Color; + let _e4 = global.Color; color = _e4; - let _e6: vec4 = color; + let _e6 = color; o_Target = _e6; return; } @@ -26,6 +26,6 @@ fn main_1() { fn main([[location(0)]] v_Uv: vec2) -> FragmentOutput { v_Uv_1 = v_Uv; main_1(); - let _e9: vec4 = o_Target; + let _e9 = o_Target; return FragmentOutput(_e9); } diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 2c7f49a69..61e6a013c 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -33,14 +33,14 @@ var gl_Position: vec4; fn main_1() { var position: vec3; - let _e10: vec2 = Vertex_Uv_1; + let _e10 = Vertex_Uv_1; v_Uv = _e10; - let _e11: vec3 = Vertex_Position_1; - let _e12: vec2 = global_2.size; + let _e11 = Vertex_Position_1; + let _e12 = global_2.size; position = (_e11 * vec3(_e12, 1.0)); - let _e18: mat4x4 = global.ViewProj; - let _e19: mat4x4 = global_1.Model; - let _e21: vec3 = position; + let _e18 = global.ViewProj; + let _e19 = global_1.Model; + let _e21 = position; gl_Position = ((_e18 * _e19) * vec4(_e21, 1.0)); return; } @@ -51,7 +51,7 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; main_1(); - let _e21: vec2 = v_Uv; - let _e23: vec4 = gl_Position; + let _e21 = v_Uv; + let _e23 = gl_Position; return VertexOutput(_e21, _e23); } diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 42fc2398a..2619b6064 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -28,19 +28,19 @@ var global_1: Transform; var gl_Position: vec4; fn main_1() { - let _e10: mat4x4 = global_1.Model; - let _e11: vec3 = Vertex_Normal_1; + let _e10 = global_1.Model; + let _e11 = Vertex_Normal_1; v_Normal = (_e10 * vec4(_e11, 1.0)).xyz; - let _e16: mat4x4 = global_1.Model; - let _e26: vec3 = Vertex_Normal_1; + let _e16 = global_1.Model; + let _e26 = Vertex_Normal_1; v_Normal = (mat3x3(_e16[0].xyz, _e16[1].xyz, _e16[2].xyz) * _e26); - let _e28: mat4x4 = global_1.Model; - let _e29: vec3 = Vertex_Position_1; + let _e28 = global_1.Model; + let _e29 = Vertex_Position_1; v_Position = (_e28 * vec4(_e29, 1.0)).xyz; - let _e34: vec2 = Vertex_Uv_1; + let _e34 = Vertex_Uv_1; v_Uv = _e34; - let _e36: mat4x4 = global.ViewProj; - let _e37: vec3 = v_Position; + let _e36 = global.ViewProj; + let _e37 = v_Position; gl_Position = (_e36 * vec4(_e37, 1.0)); return; } @@ -51,9 +51,9 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; main_1(); - let _e23: vec3 = v_Position; - let _e25: vec3 = v_Normal; - let _e27: vec2 = v_Uv; - let _e29: vec4 = gl_Position; + let _e23 = v_Position; + let _e25 = v_Normal; + let _e27 = v_Uv; + let _e29 = gl_Position; return VertexOutput(_e23, _e25, _e27, _e29); } diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 0d1b067af..e392695f7 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -13,41 +13,41 @@ fn collatz_iterations(n: u32) -> u32 { n_1 = n; loop { - let _e7: u32 = n_1; + let _e7 = n_1; if (!((_e7 != u32(1)))) { break; } { - let _e14: u32 = n_1; + let _e14 = n_1; if (((f32(_e14) % f32(2)) == f32(0))) { { - let _e22: u32 = n_1; + let _e22 = n_1; n_1 = (_e22 / u32(2)); } } else { { - let _e27: u32 = n_1; + let _e27 = n_1; n_1 = ((u32(3) * _e27) + u32(1)); } } - let _e33: u32 = i; + let _e33 = i; i = (_e33 + 1u); } } - let _e36: u32 = i; + let _e36 = i; return _e36; } fn main_1() { var index: u32; - let _e3: vec3 = gl_GlobalInvocationID; + let _e3 = gl_GlobalInvocationID; index = _e3.x; - let _e6: u32 = index; - let _e8: u32 = index; - let _e11: u32 = index; - let _e13: u32 = global.indices[_e11]; - let _e14: u32 = collatz_iterations(_e13); + let _e6 = index; + let _e8 = index; + let _e11 = index; + let _e13 = global.indices[_e11]; + let _e14 = collatz_iterations(_e13); global.indices[_e6] = _e14; return; } diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl index cae6ee450..8826e9e54 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl @@ -1,7 +1,7 @@ fn main_1() { var a: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let _e1: f32 = f32(1); + let _e1 = f32(1); } [[stage(vertex)]] diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index 08d72d8b4..febc5390f 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -22,14 +22,14 @@ var frag_color: vec4; var gl_Position: vec4; fn main_1() { - let _e7: vec4 = color_1; + let _e7 = color_1; frag_color = _e7; - let _e9: mat4x4 = global.view_matrix; - let _e10: mat4x4 = global_1.world_matrix; - let _e12: vec2 = position_1; + let _e9 = global.view_matrix; + let _e10 = global_1.world_matrix; + let _e12 = position_1; gl_Position = ((_e9 * _e10) * vec4(_e12, 0.0, 1.0)); - let _e18: vec4 = gl_Position; - let _e20: vec4 = gl_Position; + let _e18 = gl_Position; + let _e20 = gl_Position; gl_Position.z = ((_e18.z + _e20.w) / 2.0); return; } @@ -39,7 +39,7 @@ fn main([[location(0)]] position: vec2, [[location(1)]] color: vec4) - position_1 = position; color_1 = color; main_1(); - let _e15: vec4 = frag_color; - let _e17: vec4 = gl_Position; + let _e15 = frag_color; + let _e17 = gl_Position; return VertexOutput(_e15, _e17); } diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl index 9173cce46..f00782e9b 100644 --- a/tests/out/wgsl/932-for-loop-if-vert.wgsl +++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl @@ -2,14 +2,14 @@ fn main_1() { var i: i32 = 0; loop { - let _e2: i32 = i; + let _e2 = i; if (!((_e2 < 1))) { break; } { } continuing { - let _e6: i32 = i; + let _e6 = i; i = (_e6 + 1); } } diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 77cf0b64a..d56b4c570 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -10,7 +10,7 @@ struct Bar { var bar: Bar; fn read_from_private(foo_2: ptr) -> f32 { - let _e2: f32 = (*foo_2); + let _e2 = (*foo_2); return _e2; } @@ -19,21 +19,21 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { var foo_1: f32 = 0.0; var c: array; - let baz: f32 = foo_1; + let baz = foo_1; foo_1 = 1.0; - let matrix: mat4x4 = bar.matrix; - let arr: array,2> = bar.arr; - let b: f32 = bar.matrix[3][0]; - let a: i32 = bar.data[(arrayLength((&bar.data)) - 2u)]; - let data_pointer: ptr = (&bar.data[0]); - let _e25: f32 = read_from_private((&foo_1)); + let matrix = bar.matrix; + let arr = bar.arr; + let b = bar.matrix[3][0]; + let a = bar.data[(arrayLength((&bar.data)) - 2u)]; + let data_pointer = (&bar.data[0]); + let _e25 = read_from_private((&foo_1)); bar.matrix[1][2] = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); bar.data[1] = 1; c = array(a, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; - let value: i32 = c[vi]; + let value = c[vi]; return (matrix * vec4(vec4(value))); } @@ -41,22 +41,22 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { fn atomics() { var tmp: i32; - let value_1: i32 = atomicLoad((&bar.atom)); - let _e6: i32 = atomicAdd((&bar.atom), 5); + let value_1 = atomicLoad((&bar.atom)); + let _e6 = atomicAdd((&bar.atom), 5); tmp = _e6; - let _e9: i32 = atomicSub((&bar.atom), 5); + let _e9 = atomicSub((&bar.atom), 5); tmp = _e9; - let _e12: i32 = atomicAnd((&bar.atom), 5); + let _e12 = atomicAnd((&bar.atom), 5); tmp = _e12; - let _e15: i32 = atomicOr((&bar.atom), 5); + let _e15 = atomicOr((&bar.atom), 5); tmp = _e15; - let _e18: i32 = atomicXor((&bar.atom), 5); + let _e18 = atomicXor((&bar.atom), 5); tmp = _e18; - let _e21: i32 = atomicMin((&bar.atom), 5); + let _e21 = atomicMin((&bar.atom), 5); tmp = _e21; - let _e24: i32 = atomicMax((&bar.atom), 5); + let _e24 = atomicMax((&bar.atom), 5); tmp = _e24; - let _e27: i32 = atomicExchange((&bar.atom), 5); + let _e27 = atomicExchange((&bar.atom), 5); tmp = _e27; atomicStore((&bar.atom), value_1); return; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 7bc307b89..01b8120e6 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -104,12 +104,12 @@ fn pow5_(x: f32) -> f32 { var x2_: f32; x_1 = x; - let _e42: f32 = x_1; - let _e43: f32 = x_1; + let _e42 = x_1; + let _e43 = x_1; x2_ = (_e42 * _e43); - let _e46: f32 = x2_; - let _e47: f32 = x2_; - let _e49: f32 = x_1; + let _e46 = x2_; + let _e47 = x2_; + let _e49 = x_1; return ((_e46 * _e47) * _e49); } @@ -122,19 +122,19 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 distanceSquare_1 = distanceSquare; inverseRangeSquared_1 = inverseRangeSquared; - let _e44: f32 = distanceSquare_1; - let _e45: f32 = inverseRangeSquared_1; + let _e44 = distanceSquare_1; + let _e45 = inverseRangeSquared_1; factor = (_e44 * _e45); - let _e49: f32 = factor; - let _e50: f32 = factor; - let _e56: f32 = factor; - let _e57: f32 = factor; + let _e49 = factor; + let _e50 = factor; + let _e56 = factor; + let _e57 = factor; smoothFactor = clamp((1.0 - (_e56 * _e57)), 0.0, 1.0); - let _e64: f32 = smoothFactor; - let _e65: f32 = smoothFactor; + let _e64 = smoothFactor; + let _e65 = smoothFactor; attenuation = (_e64 * _e65); - let _e68: f32 = attenuation; - let _e73: f32 = distanceSquare_1; + let _e68 = attenuation; + let _e73 = distanceSquare_1; return ((_e68 * 1.0) / max(_e73, 0.0010000000474974513)); } @@ -148,21 +148,21 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { roughness_1 = roughness; NoH_1 = NoH; - let _e46: f32 = NoH_1; - let _e47: f32 = NoH_1; + let _e46 = NoH_1; + let _e47 = NoH_1; oneMinusNoHSquared = (1.0 - (_e46 * _e47)); - let _e51: f32 = NoH_1; - let _e52: f32 = roughness_1; + let _e51 = NoH_1; + let _e52 = roughness_1; a = (_e51 * _e52); - let _e55: f32 = roughness_1; - let _e56: f32 = oneMinusNoHSquared; - let _e57: f32 = a; - let _e58: f32 = a; + let _e55 = roughness_1; + let _e56 = oneMinusNoHSquared; + let _e57 = a; + let _e58 = a; k = (_e55 / (_e56 + (_e57 * _e58))); - let _e63: f32 = k; - let _e64: f32 = k; + let _e63 = k; + let _e64 = k; d = ((_e63 * _e64) * (1.0 / 3.1415927410125732)); - let _e70: f32 = d; + let _e70 = d; return _e70; } @@ -178,37 +178,37 @@ fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { roughness_3 = roughness_2; NoV_1 = NoV; NoL_1 = NoL; - let _e46: f32 = roughness_3; - let _e47: f32 = roughness_3; + let _e46 = roughness_3; + let _e47 = roughness_3; a2_ = (_e46 * _e47); - let _e50: f32 = NoL_1; - let _e51: f32 = NoV_1; - let _e52: f32 = a2_; - let _e53: f32 = NoV_1; - let _e56: f32 = NoV_1; - let _e58: f32 = a2_; - let _e60: f32 = NoV_1; - let _e61: f32 = a2_; - let _e62: f32 = NoV_1; - let _e65: f32 = NoV_1; - let _e67: f32 = a2_; + let _e50 = NoL_1; + let _e51 = NoV_1; + let _e52 = a2_; + let _e53 = NoV_1; + let _e56 = NoV_1; + let _e58 = a2_; + let _e60 = NoV_1; + let _e61 = a2_; + let _e62 = NoV_1; + let _e65 = NoV_1; + let _e67 = a2_; lambdaV = (_e50 * sqrt((((_e60 - (_e61 * _e62)) * _e65) + _e67))); - let _e72: f32 = NoV_1; - let _e73: f32 = NoL_1; - let _e74: f32 = a2_; - let _e75: f32 = NoL_1; - let _e78: f32 = NoL_1; - let _e80: f32 = a2_; - let _e82: f32 = NoL_1; - let _e83: f32 = a2_; - let _e84: f32 = NoL_1; - let _e87: f32 = NoL_1; - let _e89: f32 = a2_; + let _e72 = NoV_1; + let _e73 = NoL_1; + let _e74 = a2_; + let _e75 = NoL_1; + let _e78 = NoL_1; + let _e80 = a2_; + let _e82 = NoL_1; + let _e83 = a2_; + let _e84 = NoL_1; + let _e87 = NoL_1; + let _e89 = a2_; lambdaL = (_e72 * sqrt((((_e82 - (_e83 * _e84)) * _e87) + _e89))); - let _e95: f32 = lambdaV; - let _e96: f32 = lambdaL; + let _e95 = lambdaV; + let _e96 = lambdaL; v = (0.5 / (_e95 + _e96)); - let _e100: f32 = v; + let _e100 = v; return _e100; } @@ -218,10 +218,10 @@ fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { f90_1 = f90_; VoH_1 = VoH; - let _e45: f32 = f90_1; - let _e49: f32 = VoH_1; - let _e52: f32 = VoH_1; - let _e54: f32 = pow5_((1.0 - _e52)); + let _e45 = f90_1; + let _e49 = VoH_1; + let _e52 = VoH_1; + let _e54 = pow5_((1.0 - _e52)); return (f0_ + ((vec3(_e45) - f0_) * _e54)); } @@ -233,12 +233,12 @@ fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 { f0_2 = f0_1; f90_3 = f90_2; VoH_3 = VoH_2; - let _e46: f32 = f0_2; - let _e47: f32 = f90_3; - let _e48: f32 = f0_2; - let _e51: f32 = VoH_3; - let _e54: f32 = VoH_3; - let _e56: f32 = pow5_((1.0 - _e54)); + let _e46 = f0_2; + let _e47 = f90_3; + let _e48 = f0_2; + let _e51 = VoH_3; + let _e54 = VoH_3; + let _e56 = pow5_((1.0 - _e54)); return (_e46 + ((_e47 - _e48) * _e56)); } @@ -249,13 +249,13 @@ fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { f0_4 = f0_3; LoH_1 = LoH; - let _e49: vec3 = f0_4; - let _e62: vec3 = f0_4; + let _e49 = f0_4; + let _e62 = f0_4; f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); - let _e75: vec3 = f0_4; - let _e76: f32 = f90_4; - let _e77: f32 = LoH_1; - let _e78: vec3 = F_Schlick(_e75, _e76, _e77); + let _e75 = f0_4; + let _e76 = f90_4; + let _e77 = LoH_1; + let _e78 = F_Schlick(_e75, _e76, _e77); return _e78; } @@ -278,23 +278,23 @@ fn specular(f0_5: vec3, roughness_4: f32, h_1: vec3, NoV_2: f32, NoL_2 NoH_3 = NoH_2; LoH_3 = LoH_2; specularIntensity_1 = specularIntensity; - let _e57: f32 = roughness_5; - let _e58: f32 = NoH_3; - let _e59: f32 = D_GGX(_e57, _e58, h_1); + let _e57 = roughness_5; + let _e58 = NoH_3; + let _e59 = D_GGX(_e57, _e58, h_1); D = _e59; - let _e64: f32 = roughness_5; - let _e65: f32 = NoV_3; - let _e66: f32 = NoL_3; - let _e67: f32 = V_SmithGGXCorrelated(_e64, _e65, _e66); + let _e64 = roughness_5; + let _e65 = NoV_3; + let _e66 = NoL_3; + let _e67 = V_SmithGGXCorrelated(_e64, _e65, _e66); V = _e67; - let _e71: vec3 = f0_6; - let _e72: f32 = LoH_3; - let _e73: vec3 = fresnel(_e71, _e72); + let _e71 = f0_6; + let _e72 = LoH_3; + let _e73 = fresnel(_e71, _e72); F = _e73; - let _e75: f32 = specularIntensity_1; - let _e76: f32 = D; - let _e78: f32 = V; - let _e80: vec3 = F; + let _e75 = specularIntensity_1; + let _e76 = D; + let _e78 = V; + let _e80 = F; return (((_e75 * _e76) * _e78) * _e80); } @@ -311,20 +311,20 @@ fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { NoV_5 = NoV_4; NoL_5 = NoL_4; LoH_5 = LoH_4; - let _e50: f32 = roughness_7; - let _e52: f32 = LoH_5; - let _e54: f32 = LoH_5; + let _e50 = roughness_7; + let _e52 = LoH_5; + let _e54 = LoH_5; f90_5 = (0.5 + (((2.0 * _e50) * _e52) * _e54)); - let _e62: f32 = f90_5; - let _e63: f32 = NoL_5; - let _e64: f32 = F_Schlick_1(1.0, _e62, _e63); + let _e62 = f90_5; + let _e63 = NoL_5; + let _e64 = F_Schlick_1(1.0, _e62, _e63); lightScatter = _e64; - let _e70: f32 = f90_5; - let _e71: f32 = NoV_5; - let _e72: f32 = F_Schlick_1(1.0, _e70, _e71); + let _e70 = f90_5; + let _e71 = NoV_5; + let _e72 = F_Schlick_1(1.0, _e70, _e71); viewScatter = _e72; - let _e74: f32 = lightScatter; - let _e75: f32 = viewScatter; + let _e74 = lightScatter; + let _e75 = viewScatter; return ((_e74 * _e75) * (1.0 / 3.1415927410125732)); } @@ -341,27 +341,27 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 f0_8 = f0_7; perceptual_roughness_1 = perceptual_roughness; NoV_7 = NoV_6; - let _e62: f32 = perceptual_roughness_1; - let _e64: vec4 = c0_; - let _e66: vec4 = c1_; + let _e62 = perceptual_roughness_1; + let _e64 = c0_; + let _e66 = c1_; r = ((vec4(_e62) * _e64) + _e66); - let _e69: vec4 = r; - let _e71: vec4 = r; - let _e76: f32 = NoV_7; - let _e80: f32 = NoV_7; - let _e83: vec4 = r; - let _e85: vec4 = r; - let _e90: f32 = NoV_7; - let _e94: f32 = NoV_7; - let _e98: vec4 = r; - let _e101: vec4 = r; + let _e69 = r; + let _e71 = r; + let _e76 = NoV_7; + let _e80 = NoV_7; + let _e83 = r; + let _e85 = r; + let _e90 = NoV_7; + let _e94 = NoV_7; + let _e98 = r; + let _e101 = r; a004_ = ((min((_e83.x * _e85.x), exp2((-(9.279999732971191) * _e94))) * _e98.x) + _e101.y); - let _e109: f32 = a004_; - let _e112: vec4 = r; + let _e109 = a004_; + let _e112 = r; AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(_e109)) + _e112.zw); - let _e116: vec3 = f0_8; - let _e117: vec2 = AB; - let _e121: vec2 = AB; + let _e116 = f0_8; + let _e117 = AB; + let _e121 = AB; return ((_e116 * vec3(_e117.x)) + vec3(_e121.y)); } @@ -370,10 +370,10 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { var clampedPerceptualRoughness: f32; perceptualRoughness_1 = perceptualRoughness; - let _e45: f32 = perceptualRoughness_1; + let _e45 = perceptualRoughness_1; clampedPerceptualRoughness = clamp(_e45, 0.08900000154972076, 1.0); - let _e50: f32 = clampedPerceptualRoughness; - let _e51: f32 = clampedPerceptualRoughness; + let _e50 = clampedPerceptualRoughness; + let _e51 = clampedPerceptualRoughness; return (_e50 * _e51); } @@ -381,8 +381,8 @@ fn reinhard(color: vec3) -> vec3 { var color_1: vec3; color_1 = color; - let _e42: vec3 = color_1; - let _e45: vec3 = color_1; + let _e42 = color_1; + let _e45 = color_1; return (_e42 / (vec3(1.0) + _e45)); } @@ -393,13 +393,13 @@ fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { color_3 = color_2; max_white_1 = max_white; - let _e44: vec3 = color_3; - let _e47: vec3 = color_3; - let _e48: f32 = max_white_1; - let _e49: f32 = max_white_1; + let _e44 = color_3; + let _e47 = color_3; + let _e48 = max_white_1; + let _e49 = max_white_1; numerator = (_e44 * (vec3(1.0) + (_e47 / vec3((_e48 * _e49))))); - let _e56: vec3 = numerator; - let _e59: vec3 = color_3; + let _e56 = numerator; + let _e59 = color_3; return (_e56 / (vec3(1.0) + _e59)); } @@ -407,7 +407,7 @@ fn luminance(v_1: vec3) -> f32 { var v_2: vec3; v_2 = v_1; - let _e47: vec3 = v_2; + let _e47 = v_2; return dot(_e47, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); } @@ -418,12 +418,12 @@ fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { c_in_1 = c_in; l_out_1 = l_out; - let _e45: vec3 = c_in_1; - let _e46: f32 = luminance(_e45); + let _e45 = c_in_1; + let _e46 = luminance(_e45); l_in = _e46; - let _e48: vec3 = c_in_1; - let _e49: f32 = l_out_1; - let _e50: f32 = l_in; + let _e48 = c_in_1; + let _e49 = l_out_1; + let _e50 = l_in; return (_e48 * (_e49 / _e50)); } @@ -433,15 +433,15 @@ fn reinhard_luminance(color_4: vec3) -> vec3 { var l_new: f32; color_5 = color_4; - let _e43: vec3 = color_5; - let _e44: f32 = luminance(_e43); + let _e43 = color_5; + let _e44 = luminance(_e43); l_old = _e44; - let _e46: f32 = l_old; - let _e48: f32 = l_old; + let _e46 = l_old; + let _e48 = l_old; l_new = (_e46 / (1.0 + _e48)); - let _e54: vec3 = color_5; - let _e55: f32 = l_new; - let _e56: vec3 = change_luminance(_e54, _e55); + let _e54 = color_5; + let _e55 = l_new; + let _e56 = change_luminance(_e54, _e55); return _e56; } @@ -454,20 +454,20 @@ fn reinhard_extended_luminance(color_6: vec3, max_white_l: f32) -> vec3 = color_7; - let _e46: f32 = luminance(_e45); + let _e45 = color_7; + let _e46 = luminance(_e45); l_old_1 = _e46; - let _e48: f32 = l_old_1; - let _e50: f32 = l_old_1; - let _e51: f32 = max_white_l_1; - let _e52: f32 = max_white_l_1; + let _e48 = l_old_1; + let _e50 = l_old_1; + let _e51 = max_white_l_1; + let _e52 = max_white_l_1; numerator_1 = (_e48 * (1.0 + (_e50 / (_e51 * _e52)))); - let _e58: f32 = numerator_1; - let _e60: f32 = l_old_1; + let _e58 = numerator_1; + let _e60 = l_old_1; l_new_1 = (_e58 / (1.0 + _e60)); - let _e66: vec3 = color_7; - let _e67: f32 = l_new_1; - let _e68: vec3 = change_luminance(_e66, _e67); + let _e66 = color_7; + let _e67 = l_new_1; + let _e68 = change_luminance(_e66, _e67); return _e68; } @@ -506,122 +506,122 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ R_1 = R; F0_1 = F0_; diffuseColor_1 = diffuseColor; - let _e56: PointLight = light_1; - let _e59: vec3 = v_WorldPosition_1; + let _e56 = light_1; + let _e59 = v_WorldPosition_1; light_to_frag = (_e56.pos.xyz - _e59.xyz); - let _e65: vec3 = light_to_frag; - let _e66: vec3 = light_to_frag; + let _e65 = light_to_frag; + let _e66 = light_to_frag; distance_square = dot(_e65, _e66); - let _e70: PointLight = light_1; - let _e73: f32 = distance_square; - let _e74: PointLight = light_1; - let _e77: f32 = getDistanceAttenuation(_e73, _e74.lightParams.x); + let _e70 = light_1; + let _e73 = distance_square; + let _e74 = light_1; + let _e77 = getDistanceAttenuation(_e73, _e74.lightParams.x); rangeAttenuation = _e77; - let _e79: f32 = roughness_9; + let _e79 = roughness_9; a_1 = _e79; - let _e81: PointLight = light_1; + let _e81 = light_1; radius = _e81.lightParams.y; - let _e87: vec3 = light_to_frag; - let _e88: vec3 = R_1; - let _e90: vec3 = R_1; - let _e92: vec3 = light_to_frag; + let _e87 = light_to_frag; + let _e88 = R_1; + let _e90 = R_1; + let _e92 = light_to_frag; centerToRay = ((dot(_e87, _e88) * _e90) - _e92); - let _e95: vec3 = light_to_frag; - let _e96: vec3 = centerToRay; - let _e97: f32 = radius; - let _e100: vec3 = centerToRay; - let _e101: vec3 = centerToRay; - let _e105: vec3 = centerToRay; - let _e106: vec3 = centerToRay; - let _e112: f32 = radius; - let _e115: vec3 = centerToRay; - let _e116: vec3 = centerToRay; - let _e120: vec3 = centerToRay; - let _e121: vec3 = centerToRay; + let _e95 = light_to_frag; + let _e96 = centerToRay; + let _e97 = radius; + let _e100 = centerToRay; + let _e101 = centerToRay; + let _e105 = centerToRay; + let _e106 = centerToRay; + let _e112 = radius; + let _e115 = centerToRay; + let _e116 = centerToRay; + let _e120 = centerToRay; + let _e121 = centerToRay; closestPoint = (_e95 + (_e96 * clamp((_e112 * inverseSqrt(dot(_e120, _e121))), 0.0, 1.0))); - let _e133: vec3 = closestPoint; - let _e134: vec3 = closestPoint; - let _e138: vec3 = closestPoint; - let _e139: vec3 = closestPoint; + let _e133 = closestPoint; + let _e134 = closestPoint; + let _e138 = closestPoint; + let _e139 = closestPoint; LspecLengthInverse = inverseSqrt(dot(_e138, _e139)); - let _e143: f32 = a_1; - let _e144: f32 = a_1; - let _e145: f32 = radius; - let _e148: f32 = LspecLengthInverse; - let _e153: f32 = a_1; - let _e154: f32 = radius; - let _e157: f32 = LspecLengthInverse; + let _e143 = a_1; + let _e144 = a_1; + let _e145 = radius; + let _e148 = LspecLengthInverse; + let _e153 = a_1; + let _e154 = radius; + let _e157 = LspecLengthInverse; normalizationFactor = (_e143 / clamp((_e153 + ((_e154 * 0.5) * _e157)), 0.0, 1.0)); - let _e165: f32 = normalizationFactor; - let _e166: f32 = normalizationFactor; + let _e165 = normalizationFactor; + let _e166 = normalizationFactor; specularIntensity_2 = (_e165 * _e166); - let _e169: vec3 = closestPoint; - let _e170: f32 = LspecLengthInverse; + let _e169 = closestPoint; + let _e170 = LspecLengthInverse; L = (_e169 * _e170); - let _e173: vec3 = L; - let _e174: vec3 = V_2; - let _e176: vec3 = L; - let _e177: vec3 = V_2; + let _e173 = L; + let _e174 = V_2; + let _e176 = L; + let _e177 = V_2; H = normalize((_e176 + _e177)); - let _e183: vec3 = N_1; - let _e184: vec3 = L; - let _e190: vec3 = N_1; - let _e191: vec3 = L; + let _e183 = N_1; + let _e184 = L; + let _e190 = N_1; + let _e191 = L; NoL_6 = clamp(dot(_e190, _e191), 0.0, 1.0); - let _e199: vec3 = N_1; - let _e200: vec3 = H; - let _e206: vec3 = N_1; - let _e207: vec3 = H; + let _e199 = N_1; + let _e200 = H; + let _e206 = N_1; + let _e207 = H; NoH_4 = clamp(dot(_e206, _e207), 0.0, 1.0); - let _e215: vec3 = L; - let _e216: vec3 = H; - let _e222: vec3 = L; - let _e223: vec3 = H; + let _e215 = L; + let _e216 = H; + let _e222 = L; + let _e223 = H; LoH_6 = clamp(dot(_e222, _e223), 0.0, 1.0); - let _e237: vec3 = F0_1; - let _e238: f32 = roughness_9; - let _e239: vec3 = H; - let _e240: f32 = NdotV_1; - let _e241: f32 = NoL_6; - let _e242: f32 = NoH_4; - let _e243: f32 = LoH_6; - let _e244: f32 = specularIntensity_2; - let _e245: vec3 = specular(_e237, _e238, _e239, _e240, _e241, _e242, _e243, _e244); + let _e237 = F0_1; + let _e238 = roughness_9; + let _e239 = H; + let _e240 = NdotV_1; + let _e241 = NoL_6; + let _e242 = NoH_4; + let _e243 = LoH_6; + let _e244 = specularIntensity_2; + let _e245 = specular(_e237, _e238, _e239, _e240, _e241, _e242, _e243, _e244); specular_1 = _e245; - let _e248: vec3 = light_to_frag; + let _e248 = light_to_frag; L = normalize(_e248); - let _e250: vec3 = L; - let _e251: vec3 = V_2; - let _e253: vec3 = L; - let _e254: vec3 = V_2; + let _e250 = L; + let _e251 = V_2; + let _e253 = L; + let _e254 = V_2; H = normalize((_e253 + _e254)); - let _e259: vec3 = N_1; - let _e260: vec3 = L; - let _e266: vec3 = N_1; - let _e267: vec3 = L; + let _e259 = N_1; + let _e260 = L; + let _e266 = N_1; + let _e267 = L; NoL_6 = clamp(dot(_e266, _e267), 0.0, 1.0); - let _e274: vec3 = N_1; - let _e275: vec3 = H; - let _e281: vec3 = N_1; - let _e282: vec3 = H; + let _e274 = N_1; + let _e275 = H; + let _e281 = N_1; + let _e282 = H; NoH_4 = clamp(dot(_e281, _e282), 0.0, 1.0); - let _e289: vec3 = L; - let _e290: vec3 = H; - let _e296: vec3 = L; - let _e297: vec3 = H; + let _e289 = L; + let _e290 = H; + let _e296 = L; + let _e297 = H; LoH_6 = clamp(dot(_e296, _e297), 0.0, 1.0); - let _e302: vec3 = diffuseColor_1; - let _e307: f32 = roughness_9; - let _e308: f32 = NdotV_1; - let _e309: f32 = NoL_6; - let _e310: f32 = LoH_6; - let _e311: f32 = Fd_Burley(_e307, _e308, _e309, _e310); + let _e302 = diffuseColor_1; + let _e307 = roughness_9; + let _e308 = NdotV_1; + let _e309 = NoL_6; + let _e310 = LoH_6; + let _e311 = Fd_Burley(_e307, _e308, _e309, _e310); diffuse = (_e302 * _e311); - let _e314: vec3 = diffuse; - let _e315: vec3 = specular_1; - let _e317: PointLight = light_1; - let _e321: f32 = rangeAttenuation; - let _e322: f32 = NoL_6; + let _e314 = diffuse; + let _e315 = specular_1; + let _e317 = light_1; + let _e321 = rangeAttenuation; + let _e322 = NoL_6; return (((_e314 + _e315) * _e317.color.xyz) * (_e321 * _e322)); } @@ -651,49 +651,49 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: R_3 = R_2; F0_3 = F0_2; diffuseColor_3 = diffuseColor_2; - let _e56: DirectionalLight = light_3; + let _e56 = light_3; incident_light = _e56.direction.xyz; - let _e60: vec3 = incident_light; - let _e61: vec3 = view_1; - let _e63: vec3 = incident_light; - let _e64: vec3 = view_1; + let _e60 = incident_light; + let _e61 = view_1; + let _e63 = incident_light; + let _e64 = view_1; half_vector = normalize((_e63 + _e64)); - let _e70: vec3 = normal_1; - let _e71: vec3 = incident_light; - let _e77: vec3 = normal_1; - let _e78: vec3 = incident_light; + let _e70 = normal_1; + let _e71 = incident_light; + let _e77 = normal_1; + let _e78 = incident_light; NoL_7 = clamp(dot(_e77, _e78), 0.0, 1.0); - let _e86: vec3 = normal_1; - let _e87: vec3 = half_vector; - let _e93: vec3 = normal_1; - let _e94: vec3 = half_vector; + let _e86 = normal_1; + let _e87 = half_vector; + let _e93 = normal_1; + let _e94 = half_vector; NoH_5 = clamp(dot(_e93, _e94), 0.0, 1.0); - let _e102: vec3 = incident_light; - let _e103: vec3 = half_vector; - let _e109: vec3 = incident_light; - let _e110: vec3 = half_vector; + let _e102 = incident_light; + let _e103 = half_vector; + let _e109 = incident_light; + let _e110 = half_vector; LoH_7 = clamp(dot(_e109, _e110), 0.0, 1.0); - let _e116: vec3 = diffuseColor_3; - let _e121: f32 = roughness_11; - let _e122: f32 = NdotV_3; - let _e123: f32 = NoL_7; - let _e124: f32 = LoH_7; - let _e125: f32 = Fd_Burley(_e121, _e122, _e123, _e124); + let _e116 = diffuseColor_3; + let _e121 = roughness_11; + let _e122 = NdotV_3; + let _e123 = NoL_7; + let _e124 = LoH_7; + let _e125 = Fd_Burley(_e121, _e122, _e123, _e124); diffuse_1 = (_e116 * _e125); - let _e138: vec3 = F0_3; - let _e139: f32 = roughness_11; - let _e140: vec3 = half_vector; - let _e141: f32 = NdotV_3; - let _e142: f32 = NoL_7; - let _e143: f32 = NoH_5; - let _e144: f32 = LoH_7; - let _e145: f32 = specularIntensity_3; - let _e146: vec3 = specular(_e138, _e139, _e140, _e141, _e142, _e143, _e144, _e145); + let _e138 = F0_3; + let _e139 = roughness_11; + let _e140 = half_vector; + let _e141 = NdotV_3; + let _e142 = NoL_7; + let _e143 = NoH_5; + let _e144 = LoH_7; + let _e145 = specularIntensity_3; + let _e146 = specular(_e138, _e139, _e140, _e141, _e142, _e143, _e144, _e145); specular_2 = _e146; - let _e148: vec3 = specular_2; - let _e149: vec3 = diffuse_1; - let _e151: DirectionalLight = light_3; - let _e155: f32 = NoL_7; + let _e148 = specular_2; + let _e149 = diffuse_1; + let _e151 = light_3; + let _e155 = NoL_7; return (((_e148 + _e149) * _e151.color.xyz) * _e155); } @@ -720,185 +720,185 @@ fn main_1() { var diffuse_ambient: vec3; var specular_ambient: vec3; - let _e40: vec4 = global_3.base_color; + let _e40 = global_3.base_color; output_color = _e40; - let _e42: vec4 = output_color; - let _e44: vec2 = v_Uv_1; - let _e45: vec4 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e44); + let _e42 = output_color; + let _e44 = v_Uv_1; + let _e45 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e44); output_color = (_e42 * _e45); - let _e48: vec2 = v_Uv_1; - let _e49: vec4 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e48); + let _e48 = v_Uv_1; + let _e49 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e48); metallic_roughness = _e49; - let _e51: f32 = global_5.metallic; - let _e52: vec4 = metallic_roughness; + let _e51 = global_5.metallic; + let _e52 = metallic_roughness; metallic = (_e51 * _e52.z); - let _e56: f32 = global_4.perceptual_roughness; - let _e57: vec4 = metallic_roughness; + let _e56 = global_4.perceptual_roughness; + let _e57 = metallic_roughness; perceptual_roughness_2 = (_e56 * _e57.y); - let _e62: f32 = perceptual_roughness_2; - let _e63: f32 = perceptualRoughnessToRoughness(_e62); + let _e62 = perceptual_roughness_2; + let _e63 = perceptualRoughnessToRoughness(_e62); roughness_12 = _e63; - let _e66: vec3 = v_WorldNormal_1; + let _e66 = v_WorldNormal_1; N_2 = normalize(_e66); - let _e69: vec4 = v_WorldTangent_1; - let _e71: vec4 = v_WorldTangent_1; + let _e69 = v_WorldTangent_1; + let _e71 = v_WorldTangent_1; T = normalize(_e71.xyz); - let _e77: vec3 = N_2; - let _e78: vec3 = T; - let _e80: vec4 = v_WorldTangent_1; + let _e77 = N_2; + let _e78 = T; + let _e80 = v_WorldTangent_1; B = (cross(_e77, _e78) * _e80.w); - let _e85: bool = gl_FrontFacing; - let _e86: vec3 = N_2; - let _e87: vec3 = N_2; + let _e85 = gl_FrontFacing; + let _e86 = N_2; + let _e87 = N_2; N_2 = select(-(_e87), _e86, _e85); - let _e90: bool = gl_FrontFacing; - let _e91: vec3 = T; - let _e92: vec3 = T; + let _e90 = gl_FrontFacing; + let _e91 = T; + let _e92 = T; T = select(-(_e92), _e91, _e90); - let _e95: bool = gl_FrontFacing; - let _e96: vec3 = B; - let _e97: vec3 = B; + let _e95 = gl_FrontFacing; + let _e96 = B; + let _e97 = B; B = select(-(_e97), _e96, _e95); - let _e100: vec3 = T; - let _e101: vec3 = B; - let _e102: vec3 = N_2; + let _e100 = T; + let _e101 = B; + let _e102 = N_2; TBN = mat3x3(vec3(_e100.x, _e100.y, _e100.z), vec3(_e101.x, _e101.y, _e101.z), vec3(_e102.x, _e102.y, _e102.z)); - let _e117: mat3x3 = TBN; - let _e119: vec2 = v_Uv_1; - let _e120: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e119); - let _e128: vec2 = v_Uv_1; - let _e129: vec4 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e128); + let _e117 = TBN; + let _e119 = v_Uv_1; + let _e120 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e119); + let _e128 = v_Uv_1; + let _e129 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e128); N_2 = (_e117 * normalize(((_e129.xyz * 2.0) - vec3(1.0)))); - let _e139: vec2 = v_Uv_1; - let _e140: vec4 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e139); + let _e139 = v_Uv_1; + let _e140 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e139); occlusion = _e140.x; - let _e143: vec4 = global_7.emissive; + let _e143 = global_7.emissive; emissive = _e143; - let _e145: vec4 = emissive; - let _e147: vec4 = emissive; - let _e150: vec2 = v_Uv_1; - let _e151: vec4 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e150); - let _e153: vec3 = (_e147.xyz * _e151.xyz); + let _e145 = emissive; + let _e147 = emissive; + let _e150 = v_Uv_1; + let _e151 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e150); + let _e153 = (_e147.xyz * _e151.xyz); emissive.x = _e153.x; emissive.y = _e153.y; emissive.z = _e153.z; - let _e160: vec4 = global_1.CameraPos; - let _e162: vec3 = v_WorldPosition_1; - let _e165: vec4 = global_1.CameraPos; - let _e167: vec3 = v_WorldPosition_1; + let _e160 = global_1.CameraPos; + let _e162 = v_WorldPosition_1; + let _e165 = global_1.CameraPos; + let _e167 = v_WorldPosition_1; V_3 = normalize((_e165.xyz - _e167.xyz)); - let _e174: vec3 = N_2; - let _e175: vec3 = V_3; - let _e180: vec3 = N_2; - let _e181: vec3 = V_3; + let _e174 = N_2; + let _e175 = V_3; + let _e180 = N_2; + let _e181 = V_3; NdotV_4 = max(dot(_e180, _e181), 0.0010000000474974513); - let _e187: f32 = global_6.reflectance; - let _e189: f32 = global_6.reflectance; - let _e192: f32 = metallic; - let _e196: vec4 = output_color; - let _e198: f32 = metallic; + let _e187 = global_6.reflectance; + let _e189 = global_6.reflectance; + let _e192 = metallic; + let _e196 = output_color; + let _e198 = metallic; F0_4 = (vec3((((0.1599999964237213 * _e187) * _e189) * (1.0 - _e192))) + (_e196.xyz * vec3(_e198))); - let _e203: vec4 = output_color; - let _e206: f32 = metallic; + let _e203 = output_color; + let _e206 = metallic; diffuseColor_4 = (_e203.xyz * vec3((1.0 - _e206))); - let _e211: vec3 = V_3; - let _e214: vec3 = V_3; - let _e216: vec3 = N_2; + let _e211 = V_3; + let _e214 = V_3; + let _e216 = N_2; R_4 = reflect(-(_e214), _e216); loop { - let _e224: i32 = i; - let _e225: vec4 = global_2.NumLights; - let _e229: i32 = i; + let _e224 = i; + let _e225 = global_2.NumLights; + let _e229 = i; if (!(((_e224 < i32(_e225.x)) && (_e229 < 10)))) { break; } { - let _e236: vec3 = light_accum; - let _e237: i32 = i; - let _e247: i32 = i; - let _e249: PointLight = global_2.PointLights[_e247]; - let _e250: f32 = roughness_12; - let _e251: f32 = NdotV_4; - let _e252: vec3 = N_2; - let _e253: vec3 = V_3; - let _e254: vec3 = R_4; - let _e255: vec3 = F0_4; - let _e256: vec3 = diffuseColor_4; - let _e257: vec3 = point_light(_e249, _e250, _e251, _e252, _e253, _e254, _e255, _e256); + let _e236 = light_accum; + let _e237 = i; + let _e247 = i; + let _e249 = global_2.PointLights[_e247]; + let _e250 = roughness_12; + let _e251 = NdotV_4; + let _e252 = N_2; + let _e253 = V_3; + let _e254 = R_4; + let _e255 = F0_4; + let _e256 = diffuseColor_4; + let _e257 = point_light(_e249, _e250, _e251, _e252, _e253, _e254, _e255, _e256); light_accum = (_e236 + _e257); } continuing { - let _e233: i32 = i; + let _e233 = i; i = (_e233 + 1); } } loop { - let _e261: i32 = i_1; - let _e262: vec4 = global_2.NumLights; - let _e266: i32 = i_1; + let _e261 = i_1; + let _e262 = global_2.NumLights; + let _e266 = i_1; if (!(((_e261 < i32(_e262.y)) && (_e266 < 1)))) { break; } { - let _e273: vec3 = light_accum; - let _e274: i32 = i_1; - let _e284: i32 = i_1; - let _e286: DirectionalLight = global_2.DirectionalLights[_e284]; - let _e287: f32 = roughness_12; - let _e288: f32 = NdotV_4; - let _e289: vec3 = N_2; - let _e290: vec3 = V_3; - let _e291: vec3 = R_4; - let _e292: vec3 = F0_4; - let _e293: vec3 = diffuseColor_4; - let _e294: vec3 = dir_light(_e286, _e287, _e288, _e289, _e290, _e291, _e292, _e293); + let _e273 = light_accum; + let _e274 = i_1; + let _e284 = i_1; + let _e286 = global_2.DirectionalLights[_e284]; + let _e287 = roughness_12; + let _e288 = NdotV_4; + let _e289 = N_2; + let _e290 = V_3; + let _e291 = R_4; + let _e292 = F0_4; + let _e293 = diffuseColor_4; + let _e294 = dir_light(_e286, _e287, _e288, _e289, _e290, _e291, _e292, _e293); light_accum = (_e273 + _e294); } continuing { - let _e270: i32 = i_1; + let _e270 = i_1; i_1 = (_e270 + 1); } } - let _e299: vec3 = diffuseColor_4; - let _e301: f32 = NdotV_4; - let _e302: vec3 = EnvBRDFApprox(_e299, 1.0, _e301); + let _e299 = diffuseColor_4; + let _e301 = NdotV_4; + let _e302 = EnvBRDFApprox(_e299, 1.0, _e301); diffuse_ambient = _e302; - let _e307: vec3 = F0_4; - let _e308: f32 = perceptual_roughness_2; - let _e309: f32 = NdotV_4; - let _e310: vec3 = EnvBRDFApprox(_e307, _e308, _e309); + let _e307 = F0_4; + let _e308 = perceptual_roughness_2; + let _e309 = NdotV_4; + let _e310 = EnvBRDFApprox(_e307, _e308, _e309); specular_ambient = _e310; - let _e312: vec4 = output_color; - let _e314: vec3 = light_accum; + let _e312 = output_color; + let _e314 = light_accum; output_color.x = _e314.x; output_color.y = _e314.y; output_color.z = _e314.z; - let _e321: vec4 = output_color; - let _e323: vec4 = output_color; - let _e325: vec3 = diffuse_ambient; - let _e326: vec3 = specular_ambient; - let _e328: vec4 = global_2.AmbientColor; - let _e331: f32 = occlusion; - let _e333: vec3 = (_e323.xyz + (((_e325 + _e326) * _e328.xyz) * _e331)); + let _e321 = output_color; + let _e323 = output_color; + let _e325 = diffuse_ambient; + let _e326 = specular_ambient; + let _e328 = global_2.AmbientColor; + let _e331 = occlusion; + let _e333 = (_e323.xyz + (((_e325 + _e326) * _e328.xyz) * _e331)); output_color.x = _e333.x; output_color.y = _e333.y; output_color.z = _e333.z; - let _e340: vec4 = output_color; - let _e342: vec4 = output_color; - let _e344: vec4 = emissive; - let _e346: vec4 = output_color; - let _e349: vec3 = (_e342.xyz + (_e344.xyz * _e346.w)); + let _e340 = output_color; + let _e342 = output_color; + let _e344 = emissive; + let _e346 = output_color; + let _e349 = (_e342.xyz + (_e344.xyz * _e346.w)); output_color.x = _e349.x; output_color.y = _e349.y; output_color.z = _e349.z; - let _e356: vec4 = output_color; - let _e358: vec4 = output_color; - let _e360: vec4 = output_color; - let _e362: vec3 = reinhard_luminance(_e360.xyz); + let _e356 = output_color; + let _e358 = output_color; + let _e360 = output_color; + let _e362 = reinhard_luminance(_e360.xyz); output_color.x = _e362.x; output_color.y = _e362.y; output_color.z = _e362.z; - let _e369: vec4 = output_color; + let _e369 = output_color; o_Target = _e369; return; } @@ -911,6 +911,6 @@ fn main([[location(0)]] v_WorldPosition: vec3, [[location(1)]] v_WorldNorma v_WorldTangent_1 = v_WorldTangent; gl_FrontFacing = param; main_1(); - let _e72: vec4 = o_Target; + let _e72 = o_Target; return FragmentOutput(_e72); } diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index c0bacfd19..b8ba3337b 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -33,22 +33,22 @@ var gl_Position: vec4; fn main_1() { var world_position: vec4; - let _e12: mat4x4 = global_1.Model; - let _e13: vec3 = Vertex_Position_1; + let _e12 = global_1.Model; + let _e13 = Vertex_Position_1; world_position = (_e12 * vec4(_e13, 1.0)); - let _e18: vec4 = world_position; + let _e18 = world_position; v_WorldPosition = _e18.xyz; - let _e20: mat4x4 = global_1.Model; - let _e30: vec3 = Vertex_Normal_1; + let _e20 = global_1.Model; + let _e30 = Vertex_Normal_1; v_WorldNormal = (mat3x3(_e20[0].xyz, _e20[1].xyz, _e20[2].xyz) * _e30); - let _e32: vec2 = Vertex_Uv_1; + let _e32 = Vertex_Uv_1; v_Uv = _e32; - let _e33: mat4x4 = global_1.Model; - let _e43: vec4 = Vertex_Tangent_1; - let _e46: vec4 = Vertex_Tangent_1; + let _e33 = global_1.Model; + let _e43 = Vertex_Tangent_1; + let _e46 = Vertex_Tangent_1; v_WorldTangent = vec4((mat3x3(_e33[0].xyz, _e33[1].xyz, _e33[2].xyz) * _e43.xyz), _e46.w); - let _e50: mat4x4 = global.ViewProj; - let _e51: vec4 = world_position; + let _e50 = global.ViewProj; + let _e51 = world_position; gl_Position = (_e50 * _e51); return; } @@ -60,10 +60,10 @@ fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Norma Vertex_Uv_1 = Vertex_Uv; Vertex_Tangent_1 = Vertex_Tangent; main_1(); - let _e29: vec3 = v_WorldPosition; - let _e31: vec3 = v_WorldNormal; - let _e33: vec2 = v_Uv; - let _e35: vec4 = v_WorldTangent; - let _e37: vec4 = gl_Position; + let _e29 = v_WorldPosition; + let _e31 = v_WorldNormal; + let _e33 = v_Uv; + let _e35 = v_WorldTangent; + let _e37 = gl_Position; return VertexOutput(_e29, _e31, _e33, _e35, _e37); } diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index 306806ca9..75eb3a5f3 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -19,65 +19,65 @@ fn main() { u4_ = vec4(0u); f2_ = vec2(0.0); f4_ = vec4(0.0); - let _e28: vec4 = f4_; + let _e28 = f4_; u = pack4x8snorm(_e28); - let _e30: vec4 = f4_; + let _e30 = f4_; u = pack4x8unorm(_e30); - let _e32: vec2 = f2_; + let _e32 = f2_; u = pack2x16snorm(_e32); - let _e34: vec2 = f2_; + let _e34 = f2_; u = pack2x16unorm(_e34); - let _e36: vec2 = f2_; + let _e36 = f2_; u = pack2x16float(_e36); - let _e38: u32 = u; + let _e38 = u; f4_ = unpack4x8snorm(_e38); - let _e40: u32 = u; + let _e40 = u; f4_ = unpack4x8unorm(_e40); - let _e42: u32 = u; + let _e42 = u; f2_ = unpack2x16snorm(_e42); - let _e44: u32 = u; + let _e44 = u; f2_ = unpack2x16unorm(_e44); - let _e46: u32 = u; + let _e46 = u; f2_ = unpack2x16float(_e46); - let _e48: i32 = i; - let _e49: i32 = i; + let _e48 = i; + let _e49 = i; i = insertBits(_e48, _e49, 5u, 10u); - let _e53: vec2 = i2_; - let _e54: vec2 = i2_; + let _e53 = i2_; + let _e54 = i2_; i2_ = insertBits(_e53, _e54, 5u, 10u); - let _e58: vec3 = i3_; - let _e59: vec3 = i3_; + let _e58 = i3_; + let _e59 = i3_; i3_ = insertBits(_e58, _e59, 5u, 10u); - let _e63: vec4 = i4_; - let _e64: vec4 = i4_; + let _e63 = i4_; + let _e64 = i4_; i4_ = insertBits(_e63, _e64, 5u, 10u); - let _e68: u32 = u; - let _e69: u32 = u; + let _e68 = u; + let _e69 = u; u = insertBits(_e68, _e69, 5u, 10u); - let _e73: vec2 = u2_; - let _e74: vec2 = u2_; + let _e73 = u2_; + let _e74 = u2_; u2_ = insertBits(_e73, _e74, 5u, 10u); - let _e78: vec3 = u3_; - let _e79: vec3 = u3_; + let _e78 = u3_; + let _e79 = u3_; u3_ = insertBits(_e78, _e79, 5u, 10u); - let _e83: vec4 = u4_; - let _e84: vec4 = u4_; + let _e83 = u4_; + let _e84 = u4_; u4_ = insertBits(_e83, _e84, 5u, 10u); - let _e88: i32 = i; + let _e88 = i; i = extractBits(_e88, 5u, 10u); - let _e92: vec2 = i2_; + let _e92 = i2_; i2_ = extractBits(_e92, 5u, 10u); - let _e96: vec3 = i3_; + let _e96 = i3_; i3_ = extractBits(_e96, 5u, 10u); - let _e100: vec4 = i4_; + let _e100 = i4_; i4_ = extractBits(_e100, 5u, 10u); - let _e104: u32 = u; + let _e104 = u; u = extractBits(_e104, 5u, 10u); - let _e108: vec2 = u2_; + let _e108 = u2_; u2_ = extractBits(_e108, 5u, 10u); - let _e112: vec3 = u3_; + let _e112 = u3_; u3_ = extractBits(_e112, 5u, 10u); - let _e116: vec4 = u4_; + let _e116 = u4_; u4_ = extractBits(_e116, 5u, 10u); return; } diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index a555c9910..504adf8d7 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -10,65 +10,65 @@ fn main_1() { var f2_: vec2 = vec2(0.0, 0.0); var f4_: vec4 = vec4(0.0, 0.0, 0.0, 0.0); - let _e33: vec4 = f4_; + let _e33 = f4_; u = pack4x8snorm(_e33); - let _e36: vec4 = f4_; + let _e36 = f4_; u = pack4x8unorm(_e36); - let _e39: vec2 = f2_; + let _e39 = f2_; u = pack2x16unorm(_e39); - let _e42: vec2 = f2_; + let _e42 = f2_; u = pack2x16snorm(_e42); - let _e45: vec2 = f2_; + let _e45 = f2_; u = pack2x16float(_e45); - let _e48: u32 = u; + let _e48 = u; f4_ = unpack4x8snorm(_e48); - let _e51: u32 = u; + let _e51 = u; f4_ = unpack4x8unorm(_e51); - let _e54: u32 = u; + let _e54 = u; f2_ = unpack2x16snorm(_e54); - let _e57: u32 = u; + let _e57 = u; f2_ = unpack2x16unorm(_e57); - let _e60: u32 = u; + let _e60 = u; f2_ = unpack2x16float(_e60); - let _e66: i32 = i; - let _e67: i32 = i; + let _e66 = i; + let _e67 = i; i = insertBits(_e66, _e67, u32(5), u32(10)); - let _e77: vec2 = i2_; - let _e78: vec2 = i2_; + let _e77 = i2_; + let _e78 = i2_; i2_ = insertBits(_e77, _e78, u32(5), u32(10)); - let _e88: vec3 = i3_; - let _e89: vec3 = i3_; + let _e88 = i3_; + let _e89 = i3_; i3_ = insertBits(_e88, _e89, u32(5), u32(10)); - let _e99: vec4 = i4_; - let _e100: vec4 = i4_; + let _e99 = i4_; + let _e100 = i4_; i4_ = insertBits(_e99, _e100, u32(5), u32(10)); - let _e110: u32 = u; - let _e111: u32 = u; + let _e110 = u; + let _e111 = u; u = insertBits(_e110, _e111, u32(5), u32(10)); - let _e121: vec2 = u2_; - let _e122: vec2 = u2_; + let _e121 = u2_; + let _e122 = u2_; u2_ = insertBits(_e121, _e122, u32(5), u32(10)); - let _e132: vec3 = u3_; - let _e133: vec3 = u3_; + let _e132 = u3_; + let _e133 = u3_; u3_ = insertBits(_e132, _e133, u32(5), u32(10)); - let _e143: vec4 = u4_; - let _e144: vec4 = u4_; + let _e143 = u4_; + let _e144 = u4_; u4_ = insertBits(_e143, _e144, u32(5), u32(10)); - let _e153: i32 = i; + let _e153 = i; i = extractBits(_e153, u32(5), u32(10)); - let _e162: vec2 = i2_; + let _e162 = i2_; i2_ = extractBits(_e162, u32(5), u32(10)); - let _e171: vec3 = i3_; + let _e171 = i3_; i3_ = extractBits(_e171, u32(5), u32(10)); - let _e180: vec4 = i4_; + let _e180 = i4_; i4_ = extractBits(_e180, u32(5), u32(10)); - let _e189: u32 = u; + let _e189 = u; u = extractBits(_e189, u32(5), u32(10)); - let _e198: vec2 = u2_; + let _e198 = u2_; u2_ = extractBits(_e198, u32(5), u32(10)); - let _e207: vec3 = u3_; + let _e207 = u3_; u3_ = extractBits(_e207, u32(5), u32(10)); - let _e216: vec4 = u4_; + let _e216 = u4_; u4_ = extractBits(_e216, u32(5), u32(10)); return; } diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index a0e5e8eab..4dd4cd40e 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -41,113 +41,113 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { var vel: vec2; var i: u32 = 0u; - let index: u32 = global_invocation_id.x; + let index = global_invocation_id.x; if ((index >= NUM_PARTICLES)) { return; } - let _e10: vec2 = particlesSrc.particles[index].pos; + let _e10 = particlesSrc.particles[index].pos; vPos = _e10; - let _e15: vec2 = particlesSrc.particles[index].vel; + let _e15 = particlesSrc.particles[index].vel; vVel = _e15; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); loop { - let _e37: u32 = i; + let _e37 = i; if ((_e37 >= NUM_PARTICLES)) { break; } - let _e39: u32 = i; + let _e39 = i; if ((_e39 == index)) { continue; } - let _e42: u32 = i; - let _e45: vec2 = particlesSrc.particles[_e42].pos; + let _e42 = i; + let _e45 = particlesSrc.particles[_e42].pos; pos = _e45; - let _e47: u32 = i; - let _e50: vec2 = particlesSrc.particles[_e47].vel; + let _e47 = i; + let _e50 = particlesSrc.particles[_e47].vel; vel = _e50; - let _e51: vec2 = pos; - let _e52: vec2 = vPos; - let _e55: f32 = params.rule1Distance; + let _e51 = pos; + let _e52 = vPos; + let _e55 = params.rule1Distance; if ((distance(_e51, _e52) < _e55)) { - let _e57: vec2 = cMass; - let _e58: vec2 = pos; + let _e57 = cMass; + let _e58 = pos; cMass = (_e57 + _e58); - let _e60: i32 = cMassCount; + let _e60 = cMassCount; cMassCount = (_e60 + 1); } - let _e63: vec2 = pos; - let _e64: vec2 = vPos; - let _e67: f32 = params.rule2Distance; + let _e63 = pos; + let _e64 = vPos; + let _e67 = params.rule2Distance; if ((distance(_e63, _e64) < _e67)) { - let _e69: vec2 = colVel; - let _e70: vec2 = pos; - let _e71: vec2 = vPos; + let _e69 = colVel; + let _e70 = pos; + let _e71 = vPos; colVel = (_e69 - (_e70 - _e71)); } - let _e74: vec2 = pos; - let _e75: vec2 = vPos; - let _e78: f32 = params.rule3Distance; + let _e74 = pos; + let _e75 = vPos; + let _e78 = params.rule3Distance; if ((distance(_e74, _e75) < _e78)) { - let _e80: vec2 = cVel; - let _e81: vec2 = vel; + let _e80 = cVel; + let _e81 = vel; cVel = (_e80 + _e81); - let _e83: i32 = cVelCount; + let _e83 = cVelCount; cVelCount = (_e83 + 1); } continuing { - let _e86: u32 = i; + let _e86 = i; i = (_e86 + 1u); } } - let _e89: i32 = cMassCount; + let _e89 = cMassCount; if ((_e89 > 0)) { - let _e92: vec2 = cMass; - let _e93: i32 = cMassCount; - let _e97: vec2 = vPos; + let _e92 = cMass; + let _e93 = cMassCount; + let _e97 = vPos; cMass = ((_e92 / vec2(f32(_e93))) - _e97); } - let _e99: i32 = cVelCount; + let _e99 = cVelCount; if ((_e99 > 0)) { - let _e102: vec2 = cVel; - let _e103: i32 = cVelCount; + let _e102 = cVel; + let _e103 = cVelCount; cVel = (_e102 / vec2(f32(_e103))); } - let _e107: vec2 = vVel; - let _e108: vec2 = cMass; - let _e110: f32 = params.rule1Scale; - let _e113: vec2 = colVel; - let _e115: f32 = params.rule2Scale; - let _e118: vec2 = cVel; - let _e120: f32 = params.rule3Scale; + let _e107 = vVel; + let _e108 = cMass; + let _e110 = params.rule1Scale; + let _e113 = colVel; + let _e115 = params.rule2Scale; + let _e118 = cVel; + let _e120 = params.rule3Scale; vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); - let _e123: vec2 = vVel; - let _e125: vec2 = vVel; + let _e123 = vVel; + let _e125 = vVel; vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.10000000149011612)); - let _e131: vec2 = vPos; - let _e132: vec2 = vVel; - let _e134: f32 = params.deltaT; + let _e131 = vPos; + let _e132 = vVel; + let _e134 = params.deltaT; vPos = (_e131 + (_e132 * _e134)); - let _e138: f32 = vPos.x; + let _e138 = vPos.x; if ((_e138 < -1.0)) { vPos.x = 1.0; } - let _e144: f32 = vPos.x; + let _e144 = vPos.x; if ((_e144 > 1.0)) { vPos.x = -1.0; } - let _e150: f32 = vPos.y; + let _e150 = vPos.y; if ((_e150 < -1.0)) { vPos.y = 1.0; } - let _e156: f32 = vPos.y; + let _e156 = vPos.y; if ((_e156 > 1.0)) { vPos.y = -1.0; } - let _e164: vec2 = vPos; + let _e164 = vPos; particlesDst.particles[index].pos = _e164; - let _e168: vec2 = vVel; + let _e168 = vVel; particlesDst.particles[index].vel = _e168; return; } diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index 7c5c3e91b..1b0ce4b29 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -10,8 +10,8 @@ fn TevPerCompGT(a: f32, b: f32) -> f32 { a_1 = a; b_1 = b; - let _e5: f32 = a_1; - let _e6: f32 = b_1; + let _e5 = a_1; + let _e6 = b_1; return select(0.0, 1.0, (_e5 > _e6)); } @@ -21,18 +21,18 @@ fn TevPerCompGT_1(a_2: vec3, b_2: vec3) -> vec3 { a_3 = a_2; b_3 = b_2; - let _e7: vec3 = a_3; - let _e8: vec3 = b_3; + let _e7 = a_3; + let _e8 = b_3; return select(vec3(0.0), vec3(1.0), (_e7 > _e8)); } fn main_1() { - let _e1: vec4 = o_color; - let _e11: vec3 = TevPerCompGT_1(vec3(3.0), vec3(5.0)); + let _e1 = o_color; + let _e11 = TevPerCompGT_1(vec3(3.0), vec3(5.0)); o_color.x = _e11.x; o_color.y = _e11.y; o_color.z = _e11.z; - let _e23: f32 = TevPerCompGT(3.0, 5.0); + let _e23 = TevPerCompGT(3.0, 5.0); o_color.w = _e23; return; } @@ -40,6 +40,6 @@ fn main_1() { [[stage(fragment)]] fn main() -> FragmentOutput { main_1(); - let _e3: vec4 = o_color; + let _e3 = o_color; return FragmentOutput(_e3); } diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index 5a25b56f4..91df54d79 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -6,7 +6,7 @@ var a_pos_1: vec2; var gl_Position: vec4; fn main_1() { - let _e5: vec2 = a_pos_1; + let _e5 = a_pos_1; gl_Position = vec4(clamp(_e5, vec2(0.0), vec2(1.0)), 0.0, 1.0); return; } @@ -15,6 +15,6 @@ fn main_1() { fn main([[location(0)]] a_pos: vec2) -> VertexOutput { a_pos_1 = a_pos; main_1(); - let _e5: vec4 = gl_Position; + let _e5 = gl_Position; return VertexOutput(_e5); } diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index e3bbb2cab..a07b148fd 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -12,29 +12,29 @@ fn collatz_iterations(n_base: u32) -> u32 { n = n_base; loop { - let _e5: u32 = n; + let _e5 = n; if ((_e5 <= 1u)) { break; } - let _e8: u32 = n; + let _e8 = n; if (((_e8 % 2u) == 0u)) { - let _e13: u32 = n; + let _e13 = n; n = (_e13 / 2u); } else { - let _e17: u32 = n; + let _e17 = n; n = ((3u * _e17) + 1u); } - let _e21: u32 = i; + let _e21 = i; i = (_e21 + 1u); } - let _e24: u32 = i; + let _e24 = i; return _e24; } [[stage(compute), workgroup_size(1, 1, 1)]] fn main([[builtin(global_invocation_id)]] global_id: vec3) { - let _e8: u32 = v_indices.data[global_id.x]; - let _e9: u32 = collatz_iterations(_e8); + let _e8 = v_indices.data[global_id.x]; + let _e9 = collatz_iterations(_e8); v_indices.data[global_id.x] = _e9; return; } diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index d512590bc..268595b48 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -11,22 +11,22 @@ fn function_() -> vec4 { var i: i32 = 0; loop { - let _e9: i32 = i; + let _e9 = i; if (!((_e9 < 42))) { break; } { - let _e15: vec4 = sum; - let _e16: i32 = i; - let _e18: vec4 = global.vecs[_e16]; + let _e15 = sum; + let _e16 = i; + let _e18 = global.vecs[_e16]; sum = (_e15 + _e18); } continuing { - let _e12: i32 = i; + let _e12 = i; i = (_e12 + 1); } } - let _e20: vec4 = sum; + let _e20 = sum; return _e20; } diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index 612681df2..06b6f4865 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -41,7 +41,7 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { pos = 1; } } - let _e4: i32 = pos; + let _e4 = pos; switch(_e4) { case 1: { pos = 0; @@ -66,7 +66,7 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3) { default: { } } - let _e10: i32 = pos; + let _e10 = pos; switch(_e10) { case 1: { pos = 0; diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index 00e438af3..1732aaf0b 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -7,7 +7,7 @@ struct type_1 { var unnamed: type_1; fn function_() { - let _e8: i32 = unnamed.member; + let _e8 = unnamed.member; unnamed.member = (_e8 + 1); return; } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 1f07ccfb0..22354e38e 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -12,13 +12,13 @@ fn testBinOpVecFloat(a: vec4, b: f32) { a_1 = a; b_1 = b; - let _e5: vec4 = a_1; + let _e5 = a_1; v = (_e5 * 2.0); - let _e8: vec4 = a_1; + let _e8 = a_1; v = (_e8 / vec4(2.0)); - let _e12: vec4 = a_1; + let _e12 = a_1; v = (_e12 + vec4(2.0)); - let _e16: vec4 = a_1; + let _e16 = a_1; v = (_e16 - vec4(2.0)); return; } @@ -30,17 +30,17 @@ fn testBinOpFloatVec(a_2: vec4, b_2: f32) { a_3 = a_2; b_3 = b_2; - let _e5: vec4 = a_3; - let _e6: f32 = b_3; + let _e5 = a_3; + let _e6 = b_3; v_1 = (_e5 * _e6); - let _e8: vec4 = a_3; - let _e9: f32 = b_3; + let _e8 = a_3; + let _e9 = b_3; v_1 = (_e8 / vec4(_e9)); - let _e12: vec4 = a_3; - let _e13: f32 = b_3; + let _e12 = a_3; + let _e13 = b_3; v_1 = (_e12 + vec4(_e13)); - let _e16: vec4 = a_3; - let _e17: f32 = b_3; + let _e16 = a_3; + let _e17 = b_3; v_1 = (_e16 - vec4(_e17)); return; } @@ -52,32 +52,32 @@ fn testBinOpIVecInt(a_4: vec4, b_4: i32) { a_5 = a_4; b_5 = b_4; - let _e5: vec4 = a_5; - let _e6: i32 = b_5; + let _e5 = a_5; + let _e6 = b_5; v_2 = (_e5 * _e6); - let _e8: vec4 = a_5; - let _e9: i32 = b_5; + let _e8 = a_5; + let _e9 = b_5; v_2 = (_e8 / vec4(_e9)); - let _e12: vec4 = a_5; - let _e13: i32 = b_5; + let _e12 = a_5; + let _e13 = b_5; v_2 = (_e12 + vec4(_e13)); - let _e16: vec4 = a_5; - let _e17: i32 = b_5; + let _e16 = a_5; + let _e17 = b_5; v_2 = (_e16 - vec4(_e17)); - let _e20: vec4 = a_5; - let _e21: i32 = b_5; + let _e20 = a_5; + let _e21 = b_5; v_2 = (_e20 & vec4(_e21)); - let _e24: vec4 = a_5; - let _e25: i32 = b_5; + let _e24 = a_5; + let _e25 = b_5; v_2 = (_e24 | vec4(_e25)); - let _e28: vec4 = a_5; - let _e29: i32 = b_5; + let _e28 = a_5; + let _e29 = b_5; v_2 = (_e28 ^ vec4(_e29)); - let _e32: vec4 = a_5; - let _e33: i32 = b_5; + let _e32 = a_5; + let _e33 = b_5; v_2 = (_e32 >> vec4(u32(_e33))); - let _e37: vec4 = a_5; - let _e38: i32 = b_5; + let _e37 = a_5; + let _e38 = b_5; v_2 = (_e37 << vec4(u32(_e38))); return; } @@ -89,23 +89,23 @@ fn testBinOpIntIVec(a_6: i32, b_6: vec4) { a_7 = a_6; b_7 = b_6; - let _e5: i32 = a_7; - let _e6: vec4 = b_7; + let _e5 = a_7; + let _e6 = b_7; v_3 = (_e5 * _e6); - let _e8: i32 = a_7; - let _e9: vec4 = b_7; + let _e8 = a_7; + let _e9 = b_7; v_3 = (vec4(_e8) + _e9); - let _e12: i32 = a_7; - let _e13: vec4 = b_7; + let _e12 = a_7; + let _e13 = b_7; v_3 = (vec4(_e12) - _e13); - let _e16: i32 = a_7; - let _e17: vec4 = b_7; + let _e16 = a_7; + let _e17 = b_7; v_3 = (vec4(_e16) & _e17); - let _e20: i32 = a_7; - let _e21: vec4 = b_7; + let _e20 = a_7; + let _e21 = b_7; v_3 = (vec4(_e20) | _e21); - let _e24: i32 = a_7; - let _e25: vec4 = b_7; + let _e24 = a_7; + let _e25 = b_7; v_3 = (vec4(_e24) ^ _e25); return; } @@ -117,32 +117,32 @@ fn testBinOpUVecUint(a_8: vec4, b_8: u32) { a_9 = a_8; b_9 = b_8; - let _e5: vec4 = a_9; - let _e6: u32 = b_9; + let _e5 = a_9; + let _e6 = b_9; v_4 = (_e5 * _e6); - let _e8: vec4 = a_9; - let _e9: u32 = b_9; + let _e8 = a_9; + let _e9 = b_9; v_4 = (_e8 / vec4(_e9)); - let _e12: vec4 = a_9; - let _e13: u32 = b_9; + let _e12 = a_9; + let _e13 = b_9; v_4 = (_e12 + vec4(_e13)); - let _e16: vec4 = a_9; - let _e17: u32 = b_9; + let _e16 = a_9; + let _e17 = b_9; v_4 = (_e16 - vec4(_e17)); - let _e20: vec4 = a_9; - let _e21: u32 = b_9; + let _e20 = a_9; + let _e21 = b_9; v_4 = (_e20 & vec4(_e21)); - let _e24: vec4 = a_9; - let _e25: u32 = b_9; + let _e24 = a_9; + let _e25 = b_9; v_4 = (_e24 | vec4(_e25)); - let _e28: vec4 = a_9; - let _e29: u32 = b_9; + let _e28 = a_9; + let _e29 = b_9; v_4 = (_e28 ^ vec4(_e29)); - let _e32: vec4 = a_9; - let _e33: u32 = b_9; + let _e32 = a_9; + let _e33 = b_9; v_4 = (_e32 >> vec4(_e33)); - let _e36: vec4 = a_9; - let _e37: u32 = b_9; + let _e36 = a_9; + let _e37 = b_9; v_4 = (_e36 << vec4(_e37)); return; } @@ -154,23 +154,23 @@ fn testBinOpUintUVec(a_10: u32, b_10: vec4) { a_11 = a_10; b_11 = b_10; - let _e5: u32 = a_11; - let _e6: vec4 = b_11; + let _e5 = a_11; + let _e6 = b_11; v_5 = (_e5 * _e6); - let _e8: u32 = a_11; - let _e9: vec4 = b_11; + let _e8 = a_11; + let _e9 = b_11; v_5 = (vec4(_e8) + _e9); - let _e12: u32 = a_11; - let _e13: vec4 = b_11; + let _e12 = a_11; + let _e13 = b_11; v_5 = (vec4(_e12) - _e13); - let _e16: u32 = a_11; - let _e17: vec4 = b_11; + let _e16 = a_11; + let _e17 = b_11; v_5 = (vec4(_e16) & _e17); - let _e20: u32 = a_11; - let _e21: vec4 = b_11; + let _e20 = a_11; + let _e21 = b_11; v_5 = (vec4(_e20) | _e21); - let _e24: u32 = a_11; - let _e25: vec4 = b_11; + let _e24 = a_11; + let _e25 = b_11; v_5 = (vec4(_e24) ^ _e25); return; } @@ -197,13 +197,13 @@ fn privatePointer(a_12: ptr) { fn main_1() { var local: f32; - let _e3: f32 = global; + let _e3 = global; local = _e3; privatePointer((&local)); - let _e5: f32 = local; + let _e5 = local; global = _e5; - let _e6: vec4 = o_color; - let _e9: vec4 = vec4(1.0); + let _e6 = o_color; + let _e9 = vec4(1.0); o_color.x = _e9.x; o_color.y = _e9.y; o_color.z = _e9.z; diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index c9bd5af58..d125e1353 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -12,24 +12,24 @@ fn Fma(d: ptr, m: Mat4x3_, s: f32) { m_1 = m; s_1 = s; - let _e6: Mat4x3_ = (*d); - let _e8: Mat4x3_ = m_1; - let _e10: f32 = s_1; + let _e6 = (*d); + let _e8 = m_1; + let _e10 = s_1; (*d).mx = (_e6.mx + (_e8.mx * _e10)); - let _e14: Mat4x3_ = (*d); - let _e16: Mat4x3_ = m_1; - let _e18: f32 = s_1; + let _e14 = (*d); + let _e16 = m_1; + let _e18 = s_1; (*d).my = (_e14.my + (_e16.my * _e18)); - let _e22: Mat4x3_ = (*d); - let _e24: Mat4x3_ = m_1; - let _e26: f32 = s_1; + let _e22 = (*d); + let _e24 = m_1; + let _e26 = s_1; (*d).mz = (_e22.mz + (_e24.mz * _e26)); return; } fn main_1() { - let _e1: vec4 = o_color; - let _e4: vec4 = vec4(1.0); + let _e1 = o_color; + let _e4 = vec4(1.0); o_color.x = _e4.x; o_color.y = _e4.y; o_color.z = _e4.z; diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index 2dc3b2fb9..f94744eb9 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -3,7 +3,7 @@ var i: u32; fn main_1() { var local: array = array(1.0, 2.0); - let _e2: u32 = i; + let _e2 = i; } [[stage(vertex)]] diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index db9252d70..401c849e0 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -21,7 +21,7 @@ fn main() -> FragmentInput { out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); out.perspective_centroid = 2197.0; out.perspective_sample = 2744.0; - let _e30: FragmentInput = out; + let _e30 = out; return _e30; } diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl index c04ddb7ef..87ee33368 100644 --- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -5,11 +5,11 @@ fn main_1() { var c: f32; var d: f32; - let _e8: f32 = a; + let _e8 = a; b = log(_e8 + sqrt(_e8 * _e8 + 1.0)); - let _e10: f32 = a; + let _e10 = a; c = log(_e10 + sqrt(_e10 * _e10 - 1.0)); - let _e12: f32 = a; + let _e12 = a; d = 0.5 * log((1.0 + _e12) / (1.0 - _e12)); return; } diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index 366593720..b3056a9b5 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -8,21 +8,21 @@ fn main_1() { var d: mat3x3 = mat3x3(vec3(2.0, 2.0, 1.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); var e: mat4x4 = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); - let _e1: f32 = f32(1); - let _e9: vec2 = vec2(f32(1)); - let _e12: vec2 = vec2(f32(2)); - let _e26: mat3x3 = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); - let _e58: vec2 = vec2(f32(2), f32(3)); - let _e73: vec3 = vec3(f32(1)); - let _e76: vec3 = vec3(f32(1)); - let _e93: vec2 = vec2(f32(2)); - let _e97: vec3 = vec3(f32(1)); - let _e100: vec3 = vec3(f32(1)); - let _e117: vec2 = vec2(f32(2)); - let _e120: vec4 = vec4(f32(1)); - let _e123: vec2 = vec2(f32(2)); - let _e126: vec4 = vec4(f32(1)); - let _e129: vec4 = vec4(f32(1)); + let _e1 = f32(1); + let _e9 = vec2(f32(1)); + let _e12 = vec2(f32(2)); + let _e26 = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); + let _e58 = vec2(f32(2), f32(3)); + let _e73 = vec3(f32(1)); + let _e76 = vec3(f32(1)); + let _e93 = vec2(f32(2)); + let _e97 = vec3(f32(1)); + let _e100 = vec3(f32(1)); + let _e117 = vec2(f32(2)); + let _e120 = vec4(f32(1)); + let _e123 = vec2(f32(2)); + let _e126 = vec4(f32(1)); + let _e129 = vec4(f32(1)); } [[stage(vertex)]] diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 16f0bd003..b96147e74 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -43,106 +43,106 @@ fn main_1() { var distanceOut: f32; var stepOut: vec4; - let _e6: vec4 = a; - let _e7: vec4 = b; - let _e8: vec4 = a; - let _e9: vec4 = b; + let _e6 = a; + let _e7 = b; + let _e8 = a; + let _e9 = b; m = mat4x4(vec4(_e6.x, _e6.y, _e6.z, _e6.w), vec4(_e7.x, _e7.y, _e7.z, _e7.w), vec4(_e8.x, _e8.y, _e8.z, _e8.w), vec4(_e9.x, _e9.y, _e9.z, _e9.w)); - let _e35: vec4 = a; + let _e35 = a; ceilOut = ceil(_e35); - let _e39: vec4 = a; + let _e39 = a; roundOut = round(_e39); - let _e43: vec4 = a; + let _e43 = a; floorOut = floor(_e43); - let _e47: vec4 = a; + let _e47 = a; fractOut = fract(_e47); - let _e51: vec4 = a; + let _e51 = a; truncOut = trunc(_e51); - let _e55: vec4 = a; + let _e55 = a; sinOut = sin(_e55); - let _e59: vec4 = a; + let _e59 = a; absOut = abs(_e59); - let _e63: vec4 = a; + let _e63 = a; sqrtOut = sqrt(_e63); - let _e67: vec4 = a; + let _e67 = a; inversesqrtOut = inverseSqrt(_e67); - let _e71: vec4 = a; + let _e71 = a; expOut = exp(_e71); - let _e75: vec4 = a; + let _e75 = a; exp2Out = exp2(_e75); - let _e79: vec4 = a; + let _e79 = a; signOut = sign(_e79); - let _e83: mat4x4 = m; + let _e83 = m; transposeOut = transpose(_e83); - let _e87: vec4 = a; + let _e87 = a; normalizeOut = normalize(_e87); - let _e91: vec4 = a; + let _e91 = a; sinhOut = sinh(_e91); - let _e95: vec4 = a; + let _e95 = a; cosOut = cos(_e95); - let _e99: vec4 = a; + let _e99 = a; coshOut = cosh(_e99); - let _e103: vec4 = a; + let _e103 = a; tanOut = tan(_e103); - let _e107: vec4 = a; + let _e107 = a; tanhOut = tanh(_e107); - let _e111: vec4 = a; + let _e111 = a; acosOut = acos(_e111); - let _e115: vec4 = a; + let _e115 = a; asinOut = asin(_e115); - let _e119: vec4 = a; + let _e119 = a; logOut = log(_e119); - let _e123: vec4 = a; + let _e123 = a; log2Out = log2(_e123); - let _e127: vec4 = a; + let _e127 = a; lengthOut = length(_e127); - let _e131: mat4x4 = m; + let _e131 = m; determinantOut = determinant(_e131); - let _e135: i32 = i; + let _e135 = i; bitCountOut = countOneBits(_e135); - let _e139: i32 = i; + let _e139 = i; bitfieldReverseOut = reverseBits(_e139); - let _e142: vec4 = a; - let _e144: vec4 = a; + let _e142 = a; + let _e144 = a; atanOut = atan(_e144.x); - let _e148: vec4 = a; - let _e150: vec4 = a; - let _e152: vec4 = a; - let _e154: vec4 = a; + let _e148 = a; + let _e150 = a; + let _e152 = a; + let _e154 = a; atan2Out = atan2(_e152.x, _e154.y); - let _e158: vec4 = a; - let _e160: vec4 = b; - let _e162: vec4 = a; - let _e164: vec4 = b; + let _e158 = a; + let _e160 = b; + let _e162 = a; + let _e164 = b; modOut = (_e162.x % _e164.x); - let _e170: vec4 = a; - let _e171: vec4 = b; + let _e170 = a; + let _e171 = b; powOut = pow(_e170, _e171); - let _e176: vec4 = a; - let _e177: vec4 = b; + let _e176 = a; + let _e177 = b; dotOut = dot(_e176, _e177); - let _e182: vec4 = a; - let _e183: vec4 = b; + let _e182 = a; + let _e183 = b; maxOut = max(_e182, _e183); - let _e188: vec4 = a; - let _e189: vec4 = b; + let _e188 = a; + let _e189 = b; minOut = min(_e188, _e189); - let _e194: vec4 = a; - let _e195: vec4 = b; + let _e194 = a; + let _e195 = b; reflectOut = reflect(_e194, _e195); - let _e198: vec4 = a; - let _e200: vec4 = b; - let _e202: vec4 = a; - let _e204: vec4 = b; + let _e198 = a; + let _e200 = b; + let _e202 = a; + let _e204 = b; crossOut = cross(_e202.xyz, _e204.xyz); - let _e210: vec4 = a; - let _e211: vec4 = b; + let _e210 = a; + let _e211 = b; outerProductOut = outerProduct(_e210, _e211); - let _e216: vec4 = a; - let _e217: vec4 = b; + let _e216 = a; + let _e217 = b; distanceOut = distance(_e216, _e217); - let _e222: vec4 = a; - let _e223: vec4 = b; + let _e222 = a; + let _e223 = b; stepOut = step(_e222, _e223); return; } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index ca012560d..de5ec99f8 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -8,20 +8,20 @@ let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); let v_i32_one: vec4 = vec4(1, 1, 1, 1); fn builtins() -> vec4 { - let s1_: i32 = select(0, 1, true); - let s2_: vec4 = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); - let s3_: vec4 = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); - let m1_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - let m2_: vec4 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); - let b1_: f32 = bitcast(vec4(1, 1, 1, 1).x); - let b2_: vec4 = bitcast>(vec4(1, 1, 1, 1)); - let v_i32_zero: vec4 = vec4(vec4(0.0, 0.0, 0.0, 0.0)); + let s1_ = select(0, 1, true); + let s2_ = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); + let s3_ = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); + let m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); + let m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + let b1_ = bitcast(vec4(1, 1, 1, 1).x); + let b2_ = bitcast>(vec4(1, 1, 1, 1)); + let v_i32_zero = vec4(vec4(0.0, 0.0, 0.0, 0.0)); return (((((vec4((vec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } fn splat() -> vec4 { - let a: vec2 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); - let b: vec4 = (vec4(5) % vec4(2)); + let a = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + let b = (vec4(5) % vec4(2)); return (a.xyxy + vec4(b)); } @@ -34,7 +34,7 @@ fn unary() -> i32 { } fn bool_cast(x: vec3) -> vec3 { - let y: vec3 = vec3(x); + let y = vec3(x); return vec3(y); } @@ -42,29 +42,29 @@ fn constructors() -> f32 { var foo: Foo; foo = Foo(vec4(1.0), 1); - let _e11: f32 = foo.a.x; + let _e11 = foo.a.x; return _e11; } fn modulo() { - let a_1: i32 = (1 % 1); - let b_1: f32 = (1.0 % 1.0); - let c: vec3 = (vec3(1) % vec3(1)); - let d: vec3 = (vec3(1.0) % vec3(1.0)); + let a_1 = (1 % 1); + let b_1 = (1.0 % 1.0); + let c = (vec3(1) % vec3(1)); + let d = (vec3(1.0) % vec3(1.0)); } fn scalar_times_matrix() { - let model: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let assertion: mat4x4 = (2.0 * model); + let model = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + let assertion = (2.0 * model); } [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { - let _e4: vec4 = builtins(); - let _e5: vec4 = splat(); - let _e6: i32 = unary(); - let _e8: vec3 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); - let _e9: f32 = constructors(); + let _e4 = builtins(); + let _e5 = splat(); + let _e6 = unary(); + let _e8 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + let _e9 = constructors(); modulo(); scalar_times_matrix(); return; diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index 4bf53b8a8..c4c328fb4 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -9,20 +9,20 @@ var dynamic_array: DynamicArray; fn f() { var v: vec2; - let px: ptr = (&v.x); + let px = (&v.x); (*px) = 10; return; } fn index_unsized(i: i32, v_1: u32) { - let val: u32 = dynamic_array.arr[i]; + let val = dynamic_array.arr[i]; dynamic_array.arr[i] = (val + v_1); return; } fn index_dynamic_array(i_1: i32, v_2: u32) { - let p: ptr, read_write> = (&dynamic_array.arr); - let val_1: u32 = (*p)[i_1]; + let p = (&dynamic_array.arr); + let val_1 = (*p)[i_1]; (*p)[i_1] = (val_1 + v_2); return; } diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index c74990b45..54147d5a0 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -6,28 +6,28 @@ fn main_1() { var mat_target: mat4x3; var mat_: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); - let _e3: i32 = scalar; + let _e3 = scalar; scalar = (_e3 + 1); scalar_target = _e3; - let _e6: i32 = scalar; - let _e8: i32 = (_e6 - 1); + let _e6 = scalar; + let _e8 = (_e6 - 1); scalar = _e8; scalar_target = _e8; - let _e14: vec2 = vec_; + let _e14 = vec_; vec_ = (_e14 - vec2(1u)); vec_target = _e14; - let _e18: vec2 = vec_; - let _e21: vec2 = (_e18 + vec2(1u)); + let _e18 = vec_; + let _e21 = (_e18 + vec2(1u)); vec_ = _e21; vec_target = _e21; - let _e24: f32 = f32(1); - let _e32: mat4x3 = mat_; - let _e34: vec3 = vec3(1.0); + let _e24 = f32(1); + let _e32 = mat_; + let _e34 = vec3(1.0); mat_ = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); mat_target = _e32; - let _e37: mat4x3 = mat_; - let _e39: vec3 = vec3(1.0); - let _e41: mat4x3 = (_e37 - mat4x3(_e39, _e39, _e39, _e39)); + let _e37 = mat_; + let _e39 = vec3(1.0); + let _e41 = (_e37 - mat4x3(_e39, _e39, _e39, _e39)); mat_ = _e41; mat_target = _e41; return; diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index f1f30cbdf..cff7f2177 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -14,9 +14,9 @@ var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0. var a_pos_1: vec2; fn main_1() { - let _e12: vec2 = a_uv_1; + let _e12 = a_uv_1; v_uv = _e12; - let _e13: vec2 = a_pos_1; + let _e13 = a_pos_1; perVertexStruct.gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); return; } @@ -26,7 +26,7 @@ fn main([[location(1)]] a_uv: vec2, [[location(0)]] a_pos: vec2) -> Ve a_uv_1 = a_uv; a_pos_1 = a_pos; main_1(); - let _e7: vec2 = v_uv; - let _e8: vec4 = perVertexStruct.gl_Position; + let _e7 = v_uv; + let _e8 = perVertexStruct.gl_Position; return VertexOutput(_e7, _e8); } diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 0b8720927..2044b26b8 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -17,11 +17,11 @@ fn main([[location(0)]] pos: vec2, [[location(1)]] uv: vec2) -> Vertex [[stage(fragment)]] fn main_1([[location(0)]] uv_1: vec2) -> [[location(0)]] vec4 { - let color: vec4 = textureSample(u_texture, u_sampler, uv_1); + let color = textureSample(u_texture, u_sampler, uv_1); if ((color.w == 0.0)) { discard; } - let premultiplied: vec4 = (color.w * color); + let premultiplied = (color.w * color); return premultiplied; } diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 065acf280..6e9b6f1a8 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -14,6 +14,6 @@ fn main_1() { fn main([[location(0)]] v_uv: vec2) -> FragmentOutput { v_uv_1 = v_uv; main_1(); - let _e7: vec4 = o_color; + let _e7 = o_color; return FragmentOutput(_e7); } diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index 1071db7eb..8f878abe6 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -9,9 +9,9 @@ var v_uv: vec2; var gl_Position: vec4; fn main_1() { - let _e4: vec2 = a_uv_1; + let _e4 = a_uv_1; v_uv = _e4; - let _e6: vec2 = a_pos_1; + let _e6 = a_pos_1; gl_Position = vec4((1.2000000476837158 * _e6), 0.0, 1.0); return; } @@ -21,7 +21,7 @@ fn main([[location(0)]] a_pos: vec2, [[location(1)]] a_uv: vec2) -> Ve a_pos_1 = a_pos; a_uv_1 = a_uv; main_1(); - let _e14: vec2 = v_uv; - let _e16: vec4 = gl_Position; + let _e14 = v_uv; + let _e16 = gl_Position; return VertexOutput(_e14, _e16); } diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index f11803f0d..96e487caf 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -33,109 +33,109 @@ fn testTex1D(coord: f32) { var c: vec4; coord_1 = coord; - let _e18: f32 = coord_1; - let _e19: vec4 = textureSample(tex1D, samp, _e18); + let _e18 = coord_1; + let _e19 = textureSample(tex1D, samp, _e18); c = _e19; - let _e22: f32 = coord_1; - let _e24: vec4 = textureSampleBias(tex1D, samp, _e22, 2.0); + let _e22 = coord_1; + let _e24 = textureSampleBias(tex1D, samp, _e22, 2.0); c = _e24; - let _e28: f32 = coord_1; - let _e31: vec4 = textureSampleGrad(tex1D, samp, _e28, 4.0, 4.0); + let _e28 = coord_1; + let _e31 = textureSampleGrad(tex1D, samp, _e28, 4.0, 4.0); c = _e31; - let _e36: f32 = coord_1; - let _e40: vec4 = textureSampleGrad(tex1D, samp, _e36, 4.0, 4.0, 5); + let _e36 = coord_1; + let _e40 = textureSampleGrad(tex1D, samp, _e36, 4.0, 4.0, 5); c = _e40; - let _e43: f32 = coord_1; - let _e45: vec4 = textureSampleLevel(tex1D, samp, _e43, 3.0); + let _e43 = coord_1; + let _e45 = textureSampleLevel(tex1D, samp, _e43, 3.0); c = _e45; - let _e49: f32 = coord_1; - let _e52: vec4 = textureSampleLevel(tex1D, samp, _e49, 3.0, 5); + let _e49 = coord_1; + let _e52 = textureSampleLevel(tex1D, samp, _e49, 3.0, 5); c = _e52; - let _e55: f32 = coord_1; - let _e57: vec4 = textureSample(tex1D, samp, _e55, 5); + let _e55 = coord_1; + let _e57 = textureSample(tex1D, samp, _e55, 5); c = _e57; - let _e61: f32 = coord_1; - let _e64: vec4 = textureSampleBias(tex1D, samp, _e61, 2.0, 5); + let _e61 = coord_1; + let _e64 = textureSampleBias(tex1D, samp, _e61, 2.0, 5); c = _e64; - let _e65: f32 = coord_1; - let _e68: f32 = coord_1; - let _e70: vec2 = vec2(_e68, 6.0); - let _e74: vec4 = textureSample(tex1D, samp, (_e70.x / _e70.y)); + let _e65 = coord_1; + let _e68 = coord_1; + let _e70 = vec2(_e68, 6.0); + let _e74 = textureSample(tex1D, samp, (_e70.x / _e70.y)); c = _e74; - let _e75: f32 = coord_1; - let _e80: f32 = coord_1; - let _e84: vec4 = vec4(_e80, 0.0, 0.0, 6.0); - let _e90: vec4 = textureSample(tex1D, samp, (_e84.xyz / vec3(_e84.w)).x); + let _e75 = coord_1; + let _e80 = coord_1; + let _e84 = vec4(_e80, 0.0, 0.0, 6.0); + let _e90 = textureSample(tex1D, samp, (_e84.xyz / vec3(_e84.w)).x); c = _e90; - let _e91: f32 = coord_1; - let _e95: f32 = coord_1; - let _e97: vec2 = vec2(_e95, 6.0); - let _e102: vec4 = textureSampleBias(tex1D, samp, (_e97.x / _e97.y), 2.0); + let _e91 = coord_1; + let _e95 = coord_1; + let _e97 = vec2(_e95, 6.0); + let _e102 = textureSampleBias(tex1D, samp, (_e97.x / _e97.y), 2.0); c = _e102; - let _e103: f32 = coord_1; - let _e109: f32 = coord_1; - let _e113: vec4 = vec4(_e109, 0.0, 0.0, 6.0); - let _e120: vec4 = textureSampleBias(tex1D, samp, (_e113.xyz / vec3(_e113.w)).x, 2.0); + let _e103 = coord_1; + let _e109 = coord_1; + let _e113 = vec4(_e109, 0.0, 0.0, 6.0); + let _e120 = textureSampleBias(tex1D, samp, (_e113.xyz / vec3(_e113.w)).x, 2.0); c = _e120; - let _e121: f32 = coord_1; - let _e126: f32 = coord_1; - let _e128: vec2 = vec2(_e126, 6.0); - let _e134: vec4 = textureSampleGrad(tex1D, samp, (_e128.x / _e128.y), 4.0, 4.0); + let _e121 = coord_1; + let _e126 = coord_1; + let _e128 = vec2(_e126, 6.0); + let _e134 = textureSampleGrad(tex1D, samp, (_e128.x / _e128.y), 4.0, 4.0); c = _e134; - let _e135: f32 = coord_1; - let _e142: f32 = coord_1; - let _e146: vec4 = vec4(_e142, 0.0, 0.0, 6.0); - let _e154: vec4 = textureSampleGrad(tex1D, samp, (_e146.xyz / vec3(_e146.w)).x, 4.0, 4.0); + let _e135 = coord_1; + let _e142 = coord_1; + let _e146 = vec4(_e142, 0.0, 0.0, 6.0); + let _e154 = textureSampleGrad(tex1D, samp, (_e146.xyz / vec3(_e146.w)).x, 4.0, 4.0); c = _e154; - let _e155: f32 = coord_1; - let _e161: f32 = coord_1; - let _e163: vec2 = vec2(_e161, 6.0); - let _e170: vec4 = textureSampleGrad(tex1D, samp, (_e163.x / _e163.y), 4.0, 4.0, 5); + let _e155 = coord_1; + let _e161 = coord_1; + let _e163 = vec2(_e161, 6.0); + let _e170 = textureSampleGrad(tex1D, samp, (_e163.x / _e163.y), 4.0, 4.0, 5); c = _e170; - let _e171: f32 = coord_1; - let _e179: f32 = coord_1; - let _e183: vec4 = vec4(_e179, 0.0, 0.0, 6.0); - let _e192: vec4 = textureSampleGrad(tex1D, samp, (_e183.xyz / vec3(_e183.w)).x, 4.0, 4.0, 5); + let _e171 = coord_1; + let _e179 = coord_1; + let _e183 = vec4(_e179, 0.0, 0.0, 6.0); + let _e192 = textureSampleGrad(tex1D, samp, (_e183.xyz / vec3(_e183.w)).x, 4.0, 4.0, 5); c = _e192; - let _e193: f32 = coord_1; - let _e197: f32 = coord_1; - let _e199: vec2 = vec2(_e197, 6.0); - let _e204: vec4 = textureSampleLevel(tex1D, samp, (_e199.x / _e199.y), 3.0); + let _e193 = coord_1; + let _e197 = coord_1; + let _e199 = vec2(_e197, 6.0); + let _e204 = textureSampleLevel(tex1D, samp, (_e199.x / _e199.y), 3.0); c = _e204; - let _e205: f32 = coord_1; - let _e211: f32 = coord_1; - let _e215: vec4 = vec4(_e211, 0.0, 0.0, 6.0); - let _e222: vec4 = textureSampleLevel(tex1D, samp, (_e215.xyz / vec3(_e215.w)).x, 3.0); + let _e205 = coord_1; + let _e211 = coord_1; + let _e215 = vec4(_e211, 0.0, 0.0, 6.0); + let _e222 = textureSampleLevel(tex1D, samp, (_e215.xyz / vec3(_e215.w)).x, 3.0); c = _e222; - let _e223: f32 = coord_1; - let _e228: f32 = coord_1; - let _e230: vec2 = vec2(_e228, 6.0); - let _e236: vec4 = textureSampleLevel(tex1D, samp, (_e230.x / _e230.y), 3.0, 5); + let _e223 = coord_1; + let _e228 = coord_1; + let _e230 = vec2(_e228, 6.0); + let _e236 = textureSampleLevel(tex1D, samp, (_e230.x / _e230.y), 3.0, 5); c = _e236; - let _e237: f32 = coord_1; - let _e244: f32 = coord_1; - let _e248: vec4 = vec4(_e244, 0.0, 0.0, 6.0); - let _e256: vec4 = textureSampleLevel(tex1D, samp, (_e248.xyz / vec3(_e248.w)).x, 3.0, 5); + let _e237 = coord_1; + let _e244 = coord_1; + let _e248 = vec4(_e244, 0.0, 0.0, 6.0); + let _e256 = textureSampleLevel(tex1D, samp, (_e248.xyz / vec3(_e248.w)).x, 3.0, 5); c = _e256; - let _e257: f32 = coord_1; - let _e261: f32 = coord_1; - let _e263: vec2 = vec2(_e261, 6.0); - let _e268: vec4 = textureSample(tex1D, samp, (_e263.x / _e263.y), 5); + let _e257 = coord_1; + let _e261 = coord_1; + let _e263 = vec2(_e261, 6.0); + let _e268 = textureSample(tex1D, samp, (_e263.x / _e263.y), 5); c = _e268; - let _e269: f32 = coord_1; - let _e275: f32 = coord_1; - let _e279: vec4 = vec4(_e275, 0.0, 0.0, 6.0); - let _e286: vec4 = textureSample(tex1D, samp, (_e279.xyz / vec3(_e279.w)).x, 5); + let _e269 = coord_1; + let _e275 = coord_1; + let _e279 = vec4(_e275, 0.0, 0.0, 6.0); + let _e286 = textureSample(tex1D, samp, (_e279.xyz / vec3(_e279.w)).x, 5); c = _e286; - let _e287: f32 = coord_1; - let _e292: f32 = coord_1; - let _e294: vec2 = vec2(_e292, 6.0); - let _e300: vec4 = textureSampleBias(tex1D, samp, (_e294.x / _e294.y), 2.0, 5); + let _e287 = coord_1; + let _e292 = coord_1; + let _e294 = vec2(_e292, 6.0); + let _e300 = textureSampleBias(tex1D, samp, (_e294.x / _e294.y), 2.0, 5); c = _e300; - let _e301: f32 = coord_1; - let _e308: f32 = coord_1; - let _e312: vec4 = vec4(_e308, 0.0, 0.0, 6.0); - let _e320: vec4 = textureSampleBias(tex1D, samp, (_e312.xyz / vec3(_e312.w)).x, 2.0, 5); + let _e301 = coord_1; + let _e308 = coord_1; + let _e312 = vec4(_e308, 0.0, 0.0, 6.0); + let _e320 = textureSampleBias(tex1D, samp, (_e312.xyz / vec3(_e312.w)).x, 2.0, 5); c = _e320; return; } @@ -145,29 +145,29 @@ fn testTex1DArray(coord_2: vec2) { var c_1: vec4; coord_3 = coord_2; - let _e18: vec2 = coord_3; - let _e22: vec4 = textureSample(tex1DArray, samp, _e18.x, i32(_e18.y)); + let _e18 = coord_3; + let _e22 = textureSample(tex1DArray, samp, _e18.x, i32(_e18.y)); c_1 = _e22; - let _e25: vec2 = coord_3; - let _e30: vec4 = textureSampleBias(tex1DArray, samp, _e25.x, i32(_e25.y), 2.0); + let _e25 = coord_3; + let _e30 = textureSampleBias(tex1DArray, samp, _e25.x, i32(_e25.y), 2.0); c_1 = _e30; - let _e34: vec2 = coord_3; - let _e40: vec4 = textureSampleGrad(tex1DArray, samp, _e34.x, i32(_e34.y), 4.0, 4.0); + let _e34 = coord_3; + let _e40 = textureSampleGrad(tex1DArray, samp, _e34.x, i32(_e34.y), 4.0, 4.0); c_1 = _e40; - let _e45: vec2 = coord_3; - let _e52: vec4 = textureSampleGrad(tex1DArray, samp, _e45.x, i32(_e45.y), 4.0, 4.0, 5); + let _e45 = coord_3; + let _e52 = textureSampleGrad(tex1DArray, samp, _e45.x, i32(_e45.y), 4.0, 4.0, 5); c_1 = _e52; - let _e55: vec2 = coord_3; - let _e60: vec4 = textureSampleLevel(tex1DArray, samp, _e55.x, i32(_e55.y), 3.0); + let _e55 = coord_3; + let _e60 = textureSampleLevel(tex1DArray, samp, _e55.x, i32(_e55.y), 3.0); c_1 = _e60; - let _e64: vec2 = coord_3; - let _e70: vec4 = textureSampleLevel(tex1DArray, samp, _e64.x, i32(_e64.y), 3.0, 5); + let _e64 = coord_3; + let _e70 = textureSampleLevel(tex1DArray, samp, _e64.x, i32(_e64.y), 3.0, 5); c_1 = _e70; - let _e73: vec2 = coord_3; - let _e78: vec4 = textureSample(tex1DArray, samp, _e73.x, i32(_e73.y), 5); + let _e73 = coord_3; + let _e78 = textureSample(tex1DArray, samp, _e73.x, i32(_e73.y), 5); c_1 = _e78; - let _e82: vec2 = coord_3; - let _e88: vec4 = textureSampleBias(tex1DArray, samp, _e82.x, i32(_e82.y), 2.0, 5); + let _e82 = coord_3; + let _e88 = textureSampleBias(tex1DArray, samp, _e82.x, i32(_e82.y), 2.0, 5); c_1 = _e88; return; } @@ -177,109 +177,109 @@ fn testTex2D(coord_4: vec2) { var c_2: vec4; coord_5 = coord_4; - let _e18: vec2 = coord_5; - let _e19: vec4 = textureSample(tex2D, samp, _e18); + let _e18 = coord_5; + let _e19 = textureSample(tex2D, samp, _e18); c_2 = _e19; - let _e22: vec2 = coord_5; - let _e24: vec4 = textureSampleBias(tex2D, samp, _e22, 2.0); + let _e22 = coord_5; + let _e24 = textureSampleBias(tex2D, samp, _e22, 2.0); c_2 = _e24; - let _e30: vec2 = coord_5; - let _e35: vec4 = textureSampleGrad(tex2D, samp, _e30, vec2(4.0), vec2(4.0)); + let _e30 = coord_5; + let _e35 = textureSampleGrad(tex2D, samp, _e30, vec2(4.0), vec2(4.0)); c_2 = _e35; - let _e43: vec2 = coord_5; - let _e50: vec4 = textureSampleGrad(tex2D, samp, _e43, vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e43 = coord_5; + let _e50 = textureSampleGrad(tex2D, samp, _e43, vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e50; - let _e53: vec2 = coord_5; - let _e55: vec4 = textureSampleLevel(tex2D, samp, _e53, 3.0); + let _e53 = coord_5; + let _e55 = textureSampleLevel(tex2D, samp, _e53, 3.0); c_2 = _e55; - let _e60: vec2 = coord_5; - let _e64: vec4 = textureSampleLevel(tex2D, samp, _e60, 3.0, vec2(5, 5)); + let _e60 = coord_5; + let _e64 = textureSampleLevel(tex2D, samp, _e60, 3.0, vec2(5, 5)); c_2 = _e64; - let _e68: vec2 = coord_5; - let _e71: vec4 = textureSample(tex2D, samp, _e68, vec2(5, 5)); + let _e68 = coord_5; + let _e71 = textureSample(tex2D, samp, _e68, vec2(5, 5)); c_2 = _e71; - let _e76: vec2 = coord_5; - let _e80: vec4 = textureSampleBias(tex2D, samp, _e76, 2.0, vec2(5, 5)); + let _e76 = coord_5; + let _e80 = textureSampleBias(tex2D, samp, _e76, 2.0, vec2(5, 5)); c_2 = _e80; - let _e81: vec2 = coord_5; - let _e84: vec2 = coord_5; - let _e86: vec3 = vec3(_e84, 6.0); - let _e91: vec4 = textureSample(tex2D, samp, (_e86.xy / vec2(_e86.z))); + let _e81 = coord_5; + let _e84 = coord_5; + let _e86 = vec3(_e84, 6.0); + let _e91 = textureSample(tex2D, samp, (_e86.xy / vec2(_e86.z))); c_2 = _e91; - let _e92: vec2 = coord_5; - let _e96: vec2 = coord_5; - let _e99: vec4 = vec4(_e96, 0.0, 6.0); - let _e105: vec4 = textureSample(tex2D, samp, (_e99.xyz / vec3(_e99.w)).xy); + let _e92 = coord_5; + let _e96 = coord_5; + let _e99 = vec4(_e96, 0.0, 6.0); + let _e105 = textureSample(tex2D, samp, (_e99.xyz / vec3(_e99.w)).xy); c_2 = _e105; - let _e106: vec2 = coord_5; - let _e110: vec2 = coord_5; - let _e112: vec3 = vec3(_e110, 6.0); - let _e118: vec4 = textureSampleBias(tex2D, samp, (_e112.xy / vec2(_e112.z)), 2.0); + let _e106 = coord_5; + let _e110 = coord_5; + let _e112 = vec3(_e110, 6.0); + let _e118 = textureSampleBias(tex2D, samp, (_e112.xy / vec2(_e112.z)), 2.0); c_2 = _e118; - let _e119: vec2 = coord_5; - let _e124: vec2 = coord_5; - let _e127: vec4 = vec4(_e124, 0.0, 6.0); - let _e134: vec4 = textureSampleBias(tex2D, samp, (_e127.xyz / vec3(_e127.w)).xy, 2.0); + let _e119 = coord_5; + let _e124 = coord_5; + let _e127 = vec4(_e124, 0.0, 6.0); + let _e134 = textureSampleBias(tex2D, samp, (_e127.xyz / vec3(_e127.w)).xy, 2.0); c_2 = _e134; - let _e135: vec2 = coord_5; - let _e142: vec2 = coord_5; - let _e144: vec3 = vec3(_e142, 6.0); - let _e153: vec4 = textureSampleGrad(tex2D, samp, (_e144.xy / vec2(_e144.z)), vec2(4.0), vec2(4.0)); + let _e135 = coord_5; + let _e142 = coord_5; + let _e144 = vec3(_e142, 6.0); + let _e153 = textureSampleGrad(tex2D, samp, (_e144.xy / vec2(_e144.z)), vec2(4.0), vec2(4.0)); c_2 = _e153; - let _e154: vec2 = coord_5; - let _e162: vec2 = coord_5; - let _e165: vec4 = vec4(_e162, 0.0, 6.0); - let _e175: vec4 = textureSampleGrad(tex2D, samp, (_e165.xyz / vec3(_e165.w)).xy, vec2(4.0), vec2(4.0)); + let _e154 = coord_5; + let _e162 = coord_5; + let _e165 = vec4(_e162, 0.0, 6.0); + let _e175 = textureSampleGrad(tex2D, samp, (_e165.xyz / vec3(_e165.w)).xy, vec2(4.0), vec2(4.0)); c_2 = _e175; - let _e176: vec2 = coord_5; - let _e185: vec2 = coord_5; - let _e187: vec3 = vec3(_e185, 6.0); - let _e198: vec4 = textureSampleGrad(tex2D, samp, (_e187.xy / vec2(_e187.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e176 = coord_5; + let _e185 = coord_5; + let _e187 = vec3(_e185, 6.0); + let _e198 = textureSampleGrad(tex2D, samp, (_e187.xy / vec2(_e187.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e198; - let _e199: vec2 = coord_5; - let _e209: vec2 = coord_5; - let _e212: vec4 = vec4(_e209, 0.0, 6.0); - let _e224: vec4 = textureSampleGrad(tex2D, samp, (_e212.xyz / vec3(_e212.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e199 = coord_5; + let _e209 = coord_5; + let _e212 = vec4(_e209, 0.0, 6.0); + let _e224 = textureSampleGrad(tex2D, samp, (_e212.xyz / vec3(_e212.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e224; - let _e225: vec2 = coord_5; - let _e229: vec2 = coord_5; - let _e231: vec3 = vec3(_e229, 6.0); - let _e237: vec4 = textureSampleLevel(tex2D, samp, (_e231.xy / vec2(_e231.z)), 3.0); + let _e225 = coord_5; + let _e229 = coord_5; + let _e231 = vec3(_e229, 6.0); + let _e237 = textureSampleLevel(tex2D, samp, (_e231.xy / vec2(_e231.z)), 3.0); c_2 = _e237; - let _e238: vec2 = coord_5; - let _e243: vec2 = coord_5; - let _e246: vec4 = vec4(_e243, 0.0, 6.0); - let _e253: vec4 = textureSampleLevel(tex2D, samp, (_e246.xyz / vec3(_e246.w)).xy, 3.0); + let _e238 = coord_5; + let _e243 = coord_5; + let _e246 = vec4(_e243, 0.0, 6.0); + let _e253 = textureSampleLevel(tex2D, samp, (_e246.xyz / vec3(_e246.w)).xy, 3.0); c_2 = _e253; - let _e254: vec2 = coord_5; - let _e260: vec2 = coord_5; - let _e262: vec3 = vec3(_e260, 6.0); - let _e270: vec4 = textureSampleLevel(tex2D, samp, (_e262.xy / vec2(_e262.z)), 3.0, vec2(5, 5)); + let _e254 = coord_5; + let _e260 = coord_5; + let _e262 = vec3(_e260, 6.0); + let _e270 = textureSampleLevel(tex2D, samp, (_e262.xy / vec2(_e262.z)), 3.0, vec2(5, 5)); c_2 = _e270; - let _e271: vec2 = coord_5; - let _e278: vec2 = coord_5; - let _e281: vec4 = vec4(_e278, 0.0, 6.0); - let _e290: vec4 = textureSampleLevel(tex2D, samp, (_e281.xyz / vec3(_e281.w)).xy, 3.0, vec2(5, 5)); + let _e271 = coord_5; + let _e278 = coord_5; + let _e281 = vec4(_e278, 0.0, 6.0); + let _e290 = textureSampleLevel(tex2D, samp, (_e281.xyz / vec3(_e281.w)).xy, 3.0, vec2(5, 5)); c_2 = _e290; - let _e291: vec2 = coord_5; - let _e296: vec2 = coord_5; - let _e298: vec3 = vec3(_e296, 6.0); - let _e305: vec4 = textureSample(tex2D, samp, (_e298.xy / vec2(_e298.z)), vec2(5, 5)); + let _e291 = coord_5; + let _e296 = coord_5; + let _e298 = vec3(_e296, 6.0); + let _e305 = textureSample(tex2D, samp, (_e298.xy / vec2(_e298.z)), vec2(5, 5)); c_2 = _e305; - let _e306: vec2 = coord_5; - let _e312: vec2 = coord_5; - let _e315: vec4 = vec4(_e312, 0.0, 6.0); - let _e323: vec4 = textureSample(tex2D, samp, (_e315.xyz / vec3(_e315.w)).xy, vec2(5, 5)); + let _e306 = coord_5; + let _e312 = coord_5; + let _e315 = vec4(_e312, 0.0, 6.0); + let _e323 = textureSample(tex2D, samp, (_e315.xyz / vec3(_e315.w)).xy, vec2(5, 5)); c_2 = _e323; - let _e324: vec2 = coord_5; - let _e330: vec2 = coord_5; - let _e332: vec3 = vec3(_e330, 6.0); - let _e340: vec4 = textureSampleBias(tex2D, samp, (_e332.xy / vec2(_e332.z)), 2.0, vec2(5, 5)); + let _e324 = coord_5; + let _e330 = coord_5; + let _e332 = vec3(_e330, 6.0); + let _e340 = textureSampleBias(tex2D, samp, (_e332.xy / vec2(_e332.z)), 2.0, vec2(5, 5)); c_2 = _e340; - let _e341: vec2 = coord_5; - let _e348: vec2 = coord_5; - let _e351: vec4 = vec4(_e348, 0.0, 6.0); - let _e360: vec4 = textureSampleBias(tex2D, samp, (_e351.xyz / vec3(_e351.w)).xy, 2.0, vec2(5, 5)); + let _e341 = coord_5; + let _e348 = coord_5; + let _e351 = vec4(_e348, 0.0, 6.0); + let _e360 = textureSampleBias(tex2D, samp, (_e351.xyz / vec3(_e351.w)).xy, 2.0, vec2(5, 5)); c_2 = _e360; return; } @@ -289,71 +289,71 @@ fn testTex2DShadow(coord_6: vec2) { var d: f32; coord_7 = coord_6; - let _e17: vec2 = coord_7; - let _e20: vec2 = coord_7; - let _e22: vec3 = vec3(_e20, 1.0); - let _e25: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e22.xy, _e22.z); + let _e17 = coord_7; + let _e20 = coord_7; + let _e22 = vec3(_e20, 1.0); + let _e25 = textureSampleCompare(tex2DShadow, sampShadow, _e22.xy, _e22.z); d = _e25; - let _e26: vec2 = coord_7; - let _e33: vec2 = coord_7; - let _e35: vec3 = vec3(_e33, 1.0); - let _e42: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e35.xy, _e35.z); + let _e26 = coord_7; + let _e33 = coord_7; + let _e35 = vec3(_e33, 1.0); + let _e42 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e35.xy, _e35.z); d = _e42; - let _e43: vec2 = coord_7; - let _e52: vec2 = coord_7; - let _e54: vec3 = vec3(_e52, 1.0); - let _e63: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e54.xy, _e54.z, vec2(5, 5)); + let _e43 = coord_7; + let _e52 = coord_7; + let _e54 = vec3(_e52, 1.0); + let _e63 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e54.xy, _e54.z, vec2(5, 5)); d = _e63; - let _e64: vec2 = coord_7; - let _e68: vec2 = coord_7; - let _e70: vec3 = vec3(_e68, 1.0); - let _e74: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e70.xy, _e70.z); + let _e64 = coord_7; + let _e68 = coord_7; + let _e70 = vec3(_e68, 1.0); + let _e74 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e70.xy, _e70.z); d = _e74; - let _e75: vec2 = coord_7; - let _e81: vec2 = coord_7; - let _e83: vec3 = vec3(_e81, 1.0); - let _e89: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e83.xy, _e83.z, vec2(5, 5)); + let _e75 = coord_7; + let _e81 = coord_7; + let _e83 = vec3(_e81, 1.0); + let _e89 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e83.xy, _e83.z, vec2(5, 5)); d = _e89; - let _e90: vec2 = coord_7; - let _e95: vec2 = coord_7; - let _e97: vec3 = vec3(_e95, 1.0); - let _e102: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e97.xy, _e97.z, vec2(5, 5)); + let _e90 = coord_7; + let _e95 = coord_7; + let _e97 = vec3(_e95, 1.0); + let _e102 = textureSampleCompare(tex2DShadow, sampShadow, _e97.xy, _e97.z, vec2(5, 5)); d = _e102; - let _e103: vec2 = coord_7; - let _e107: vec2 = coord_7; - let _e110: vec4 = vec4(_e107, 1.0, 6.0); - let _e114: vec3 = (_e110.xyz / vec3(_e110.w)); - let _e117: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e114.xy, _e114.z); + let _e103 = coord_7; + let _e107 = coord_7; + let _e110 = vec4(_e107, 1.0, 6.0); + let _e114 = (_e110.xyz / vec3(_e110.w)); + let _e117 = textureSampleCompare(tex2DShadow, sampShadow, _e114.xy, _e114.z); d = _e117; - let _e118: vec2 = coord_7; - let _e126: vec2 = coord_7; - let _e129: vec4 = vec4(_e126, 1.0, 6.0); - let _e137: vec3 = (_e129.xyz / vec3(_e129.w)); - let _e140: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e137.xy, _e137.z); + let _e118 = coord_7; + let _e126 = coord_7; + let _e129 = vec4(_e126, 1.0, 6.0); + let _e137 = (_e129.xyz / vec3(_e129.w)); + let _e140 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e137.xy, _e137.z); d = _e140; - let _e141: vec2 = coord_7; - let _e151: vec2 = coord_7; - let _e154: vec4 = vec4(_e151, 1.0, 6.0); - let _e164: vec3 = (_e154.xyz / vec3(_e154.w)); - let _e167: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e164.xy, _e164.z, vec2(5, 5)); + let _e141 = coord_7; + let _e151 = coord_7; + let _e154 = vec4(_e151, 1.0, 6.0); + let _e164 = (_e154.xyz / vec3(_e154.w)); + let _e167 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e164.xy, _e164.z, vec2(5, 5)); d = _e167; - let _e168: vec2 = coord_7; - let _e173: vec2 = coord_7; - let _e176: vec4 = vec4(_e173, 1.0, 6.0); - let _e181: vec3 = (_e176.xyz / vec3(_e176.w)); - let _e184: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e181.xy, _e181.z); + let _e168 = coord_7; + let _e173 = coord_7; + let _e176 = vec4(_e173, 1.0, 6.0); + let _e181 = (_e176.xyz / vec3(_e176.w)); + let _e184 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e181.xy, _e181.z); d = _e184; - let _e185: vec2 = coord_7; - let _e192: vec2 = coord_7; - let _e195: vec4 = vec4(_e192, 1.0, 6.0); - let _e202: vec3 = (_e195.xyz / vec3(_e195.w)); - let _e205: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e202.xy, _e202.z, vec2(5, 5)); + let _e185 = coord_7; + let _e192 = coord_7; + let _e195 = vec4(_e192, 1.0, 6.0); + let _e202 = (_e195.xyz / vec3(_e195.w)); + let _e205 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e202.xy, _e202.z, vec2(5, 5)); d = _e205; - let _e206: vec2 = coord_7; - let _e212: vec2 = coord_7; - let _e215: vec4 = vec4(_e212, 1.0, 6.0); - let _e221: vec3 = (_e215.xyz / vec3(_e215.w)); - let _e224: f32 = textureSampleCompare(tex2DShadow, sampShadow, _e221.xy, _e221.z, vec2(5, 5)); + let _e206 = coord_7; + let _e212 = coord_7; + let _e215 = vec4(_e212, 1.0, 6.0); + let _e221 = (_e215.xyz / vec3(_e215.w)); + let _e224 = textureSampleCompare(tex2DShadow, sampShadow, _e221.xy, _e221.z, vec2(5, 5)); d = _e224; return; } @@ -363,29 +363,29 @@ fn testTex2DArray(coord_8: vec3) { var c_3: vec4; coord_9 = coord_8; - let _e18: vec3 = coord_9; - let _e22: vec4 = textureSample(tex2DArray, samp, _e18.xy, i32(_e18.z)); + let _e18 = coord_9; + let _e22 = textureSample(tex2DArray, samp, _e18.xy, i32(_e18.z)); c_3 = _e22; - let _e25: vec3 = coord_9; - let _e30: vec4 = textureSampleBias(tex2DArray, samp, _e25.xy, i32(_e25.z), 2.0); + let _e25 = coord_9; + let _e30 = textureSampleBias(tex2DArray, samp, _e25.xy, i32(_e25.z), 2.0); c_3 = _e30; - let _e36: vec3 = coord_9; - let _e44: vec4 = textureSampleGrad(tex2DArray, samp, _e36.xy, i32(_e36.z), vec2(4.0), vec2(4.0)); + let _e36 = coord_9; + let _e44 = textureSampleGrad(tex2DArray, samp, _e36.xy, i32(_e36.z), vec2(4.0), vec2(4.0)); c_3 = _e44; - let _e52: vec3 = coord_9; - let _e62: vec4 = textureSampleGrad(tex2DArray, samp, _e52.xy, i32(_e52.z), vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e52 = coord_9; + let _e62 = textureSampleGrad(tex2DArray, samp, _e52.xy, i32(_e52.z), vec2(4.0), vec2(4.0), vec2(5, 5)); c_3 = _e62; - let _e65: vec3 = coord_9; - let _e70: vec4 = textureSampleLevel(tex2DArray, samp, _e65.xy, i32(_e65.z), 3.0); + let _e65 = coord_9; + let _e70 = textureSampleLevel(tex2DArray, samp, _e65.xy, i32(_e65.z), 3.0); c_3 = _e70; - let _e75: vec3 = coord_9; - let _e82: vec4 = textureSampleLevel(tex2DArray, samp, _e75.xy, i32(_e75.z), 3.0, vec2(5, 5)); + let _e75 = coord_9; + let _e82 = textureSampleLevel(tex2DArray, samp, _e75.xy, i32(_e75.z), 3.0, vec2(5, 5)); c_3 = _e82; - let _e86: vec3 = coord_9; - let _e92: vec4 = textureSample(tex2DArray, samp, _e86.xy, i32(_e86.z), vec2(5, 5)); + let _e86 = coord_9; + let _e92 = textureSample(tex2DArray, samp, _e86.xy, i32(_e86.z), vec2(5, 5)); c_3 = _e92; - let _e97: vec3 = coord_9; - let _e104: vec4 = textureSampleBias(tex2DArray, samp, _e97.xy, i32(_e97.z), 2.0, vec2(5, 5)); + let _e97 = coord_9; + let _e104 = textureSampleBias(tex2DArray, samp, _e97.xy, i32(_e97.z), 2.0, vec2(5, 5)); c_3 = _e104; return; } @@ -395,35 +395,35 @@ fn testTex2DArrayShadow(coord_10: vec3) { var d_1: f32; coord_11 = coord_10; - let _e17: vec3 = coord_11; - let _e20: vec3 = coord_11; - let _e22: vec4 = vec4(_e20, 1.0); - let _e27: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e22.xy, i32(_e22.z), _e22.w); + let _e17 = coord_11; + let _e20 = coord_11; + let _e22 = vec4(_e20, 1.0); + let _e27 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e22.xy, i32(_e22.z), _e22.w); d_1 = _e27; - let _e28: vec3 = coord_11; - let _e35: vec3 = coord_11; - let _e37: vec4 = vec4(_e35, 1.0); - let _e46: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e37.xy, i32(_e37.z), _e37.w); + let _e28 = coord_11; + let _e35 = coord_11; + let _e37 = vec4(_e35, 1.0); + let _e46 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e37.xy, i32(_e37.z), _e37.w); d_1 = _e46; - let _e47: vec3 = coord_11; - let _e56: vec3 = coord_11; - let _e58: vec4 = vec4(_e56, 1.0); - let _e69: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e58.xy, i32(_e58.z), _e58.w, vec2(5, 5)); + let _e47 = coord_11; + let _e56 = coord_11; + let _e58 = vec4(_e56, 1.0); + let _e69 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e58.xy, i32(_e58.z), _e58.w, vec2(5, 5)); d_1 = _e69; - let _e70: vec3 = coord_11; - let _e74: vec3 = coord_11; - let _e76: vec4 = vec4(_e74, 1.0); - let _e82: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e76.xy, i32(_e76.z), _e76.w); + let _e70 = coord_11; + let _e74 = coord_11; + let _e76 = vec4(_e74, 1.0); + let _e82 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e76.xy, i32(_e76.z), _e76.w); d_1 = _e82; - let _e83: vec3 = coord_11; - let _e89: vec3 = coord_11; - let _e91: vec4 = vec4(_e89, 1.0); - let _e99: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e91.xy, i32(_e91.z), _e91.w, vec2(5, 5)); + let _e83 = coord_11; + let _e89 = coord_11; + let _e91 = vec4(_e89, 1.0); + let _e99 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e91.xy, i32(_e91.z), _e91.w, vec2(5, 5)); d_1 = _e99; - let _e100: vec3 = coord_11; - let _e105: vec3 = coord_11; - let _e107: vec4 = vec4(_e105, 1.0); - let _e114: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e107.xy, i32(_e107.z), _e107.w, vec2(5, 5)); + let _e100 = coord_11; + let _e105 = coord_11; + let _e107 = vec4(_e105, 1.0); + let _e114 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e107.xy, i32(_e107.z), _e107.w, vec2(5, 5)); d_1 = _e114; return; } @@ -433,26 +433,26 @@ fn testTexCube(coord_12: vec3) { var c_4: vec4; coord_13 = coord_12; - let _e18: vec3 = coord_13; - let _e19: vec4 = textureSample(texCube, samp, _e18); + let _e18 = coord_13; + let _e19 = textureSample(texCube, samp, _e18); c_4 = _e19; - let _e22: vec3 = coord_13; - let _e24: vec4 = textureSampleBias(texCube, samp, _e22, 2.0); + let _e22 = coord_13; + let _e24 = textureSampleBias(texCube, samp, _e22, 2.0); c_4 = _e24; - let _e30: vec3 = coord_13; - let _e35: vec4 = textureSampleGrad(texCube, samp, _e30, vec3(4.0), vec3(4.0)); + let _e30 = coord_13; + let _e35 = textureSampleGrad(texCube, samp, _e30, vec3(4.0), vec3(4.0)); c_4 = _e35; - let _e38: vec3 = coord_13; - let _e40: vec4 = textureSampleLevel(texCube, samp, _e38, 3.0); + let _e38 = coord_13; + let _e40 = textureSampleLevel(texCube, samp, _e38, 3.0); c_4 = _e40; - let _e45: vec3 = coord_13; - let _e49: vec4 = textureSampleLevel(texCube, samp, _e45, 3.0, vec3(5, 5, 5)); + let _e45 = coord_13; + let _e49 = textureSampleLevel(texCube, samp, _e45, 3.0, vec3(5, 5, 5)); c_4 = _e49; - let _e53: vec3 = coord_13; - let _e56: vec4 = textureSample(texCube, samp, _e53, vec3(5, 5, 5)); + let _e53 = coord_13; + let _e56 = textureSample(texCube, samp, _e53, vec3(5, 5, 5)); c_4 = _e56; - let _e61: vec3 = coord_13; - let _e65: vec4 = textureSampleBias(texCube, samp, _e61, 2.0, vec3(5, 5, 5)); + let _e61 = coord_13; + let _e65 = textureSampleBias(texCube, samp, _e61, 2.0, vec3(5, 5, 5)); c_4 = _e65; return; } @@ -462,30 +462,30 @@ fn testTexCubeShadow(coord_14: vec3) { var d_2: f32; coord_15 = coord_14; - let _e17: vec3 = coord_15; - let _e20: vec3 = coord_15; - let _e22: vec4 = vec4(_e20, 1.0); - let _e25: f32 = textureSampleCompare(texCubeShadow, sampShadow, _e22.xyz, _e22.w); + let _e17 = coord_15; + let _e20 = coord_15; + let _e22 = vec4(_e20, 1.0); + let _e25 = textureSampleCompare(texCubeShadow, sampShadow, _e22.xyz, _e22.w); d_2 = _e25; - let _e26: vec3 = coord_15; - let _e33: vec3 = coord_15; - let _e35: vec4 = vec4(_e33, 1.0); - let _e42: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e35.xyz, _e35.w); + let _e26 = coord_15; + let _e33 = coord_15; + let _e35 = vec4(_e33, 1.0); + let _e42 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e35.xyz, _e35.w); d_2 = _e42; - let _e43: vec3 = coord_15; - let _e47: vec3 = coord_15; - let _e49: vec4 = vec4(_e47, 1.0); - let _e53: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e49.xyz, _e49.w); + let _e43 = coord_15; + let _e47 = coord_15; + let _e49 = vec4(_e47, 1.0); + let _e53 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e49.xyz, _e49.w); d_2 = _e53; - let _e54: vec3 = coord_15; - let _e60: vec3 = coord_15; - let _e62: vec4 = vec4(_e60, 1.0); - let _e68: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e62.xyz, _e62.w, vec3(5, 5, 5)); + let _e54 = coord_15; + let _e60 = coord_15; + let _e62 = vec4(_e60, 1.0); + let _e68 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e62.xyz, _e62.w, vec3(5, 5, 5)); d_2 = _e68; - let _e69: vec3 = coord_15; - let _e74: vec3 = coord_15; - let _e76: vec4 = vec4(_e74, 1.0); - let _e81: f32 = textureSampleCompare(texCubeShadow, sampShadow, _e76.xyz, _e76.w, vec3(5, 5, 5)); + let _e69 = coord_15; + let _e74 = coord_15; + let _e76 = vec4(_e74, 1.0); + let _e81 = textureSampleCompare(texCubeShadow, sampShadow, _e76.xyz, _e76.w, vec3(5, 5, 5)); d_2 = _e81; return; } @@ -495,26 +495,26 @@ fn testTexCubeArray(coord_16: vec4) { var c_5: vec4; coord_17 = coord_16; - let _e18: vec4 = coord_17; - let _e22: vec4 = textureSample(texCubeArray, samp, _e18.xyz, i32(_e18.w)); + let _e18 = coord_17; + let _e22 = textureSample(texCubeArray, samp, _e18.xyz, i32(_e18.w)); c_5 = _e22; - let _e25: vec4 = coord_17; - let _e30: vec4 = textureSampleBias(texCubeArray, samp, _e25.xyz, i32(_e25.w), 2.0); + let _e25 = coord_17; + let _e30 = textureSampleBias(texCubeArray, samp, _e25.xyz, i32(_e25.w), 2.0); c_5 = _e30; - let _e36: vec4 = coord_17; - let _e44: vec4 = textureSampleGrad(texCubeArray, samp, _e36.xyz, i32(_e36.w), vec3(4.0), vec3(4.0)); + let _e36 = coord_17; + let _e44 = textureSampleGrad(texCubeArray, samp, _e36.xyz, i32(_e36.w), vec3(4.0), vec3(4.0)); c_5 = _e44; - let _e47: vec4 = coord_17; - let _e52: vec4 = textureSampleLevel(texCubeArray, samp, _e47.xyz, i32(_e47.w), 3.0); + let _e47 = coord_17; + let _e52 = textureSampleLevel(texCubeArray, samp, _e47.xyz, i32(_e47.w), 3.0); c_5 = _e52; - let _e57: vec4 = coord_17; - let _e64: vec4 = textureSampleLevel(texCubeArray, samp, _e57.xyz, i32(_e57.w), 3.0, vec3(5, 5, 5)); + let _e57 = coord_17; + let _e64 = textureSampleLevel(texCubeArray, samp, _e57.xyz, i32(_e57.w), 3.0, vec3(5, 5, 5)); c_5 = _e64; - let _e68: vec4 = coord_17; - let _e74: vec4 = textureSample(texCubeArray, samp, _e68.xyz, i32(_e68.w), vec3(5, 5, 5)); + let _e68 = coord_17; + let _e74 = textureSample(texCubeArray, samp, _e68.xyz, i32(_e68.w), vec3(5, 5, 5)); c_5 = _e74; - let _e79: vec4 = coord_17; - let _e86: vec4 = textureSampleBias(texCubeArray, samp, _e79.xyz, i32(_e79.w), 2.0, vec3(5, 5, 5)); + let _e79 = coord_17; + let _e86 = textureSampleBias(texCubeArray, samp, _e79.xyz, i32(_e79.w), 2.0, vec3(5, 5, 5)); c_5 = _e86; return; } @@ -524,8 +524,8 @@ fn testTexCubeArrayShadow(coord_18: vec4) { var d_3: f32; coord_19 = coord_18; - let _e19: vec4 = coord_19; - let _e24: f32 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e19.xyz, i32(_e19.w), 1.0); + let _e19 = coord_19; + let _e24 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e19.xyz, i32(_e19.w), 1.0); d_3 = _e24; return; } @@ -535,29 +535,29 @@ fn testTex3D(coord_20: vec3) { var c_6: vec4; coord_21 = coord_20; - let _e18: vec3 = coord_21; - let _e19: vec4 = textureSample(tex3D, samp, _e18); + let _e18 = coord_21; + let _e19 = textureSample(tex3D, samp, _e18); c_6 = _e19; - let _e22: vec3 = coord_21; - let _e24: vec4 = textureSampleBias(tex3D, samp, _e22, 2.0); + let _e22 = coord_21; + let _e24 = textureSampleBias(tex3D, samp, _e22, 2.0); c_6 = _e24; - let _e30: vec3 = coord_21; - let _e35: vec4 = textureSampleGrad(tex3D, samp, _e30, vec3(4.0), vec3(4.0)); + let _e30 = coord_21; + let _e35 = textureSampleGrad(tex3D, samp, _e30, vec3(4.0), vec3(4.0)); c_6 = _e35; - let _e43: vec3 = coord_21; - let _e50: vec4 = textureSampleGrad(tex3D, samp, _e43, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + let _e43 = coord_21; + let _e50 = textureSampleGrad(tex3D, samp, _e43, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); c_6 = _e50; - let _e53: vec3 = coord_21; - let _e55: vec4 = textureSampleLevel(tex3D, samp, _e53, 3.0); + let _e53 = coord_21; + let _e55 = textureSampleLevel(tex3D, samp, _e53, 3.0); c_6 = _e55; - let _e60: vec3 = coord_21; - let _e64: vec4 = textureSampleLevel(tex3D, samp, _e60, 3.0, vec3(5, 5, 5)); + let _e60 = coord_21; + let _e64 = textureSampleLevel(tex3D, samp, _e60, 3.0, vec3(5, 5, 5)); c_6 = _e64; - let _e68: vec3 = coord_21; - let _e71: vec4 = textureSample(tex3D, samp, _e68, vec3(5, 5, 5)); + let _e68 = coord_21; + let _e71 = textureSample(tex3D, samp, _e68, vec3(5, 5, 5)); c_6 = _e71; - let _e76: vec3 = coord_21; - let _e80: vec4 = textureSampleBias(tex3D, samp, _e76, 2.0, vec3(5, 5, 5)); + let _e76 = coord_21; + let _e80 = textureSampleBias(tex3D, samp, _e76, 2.0, vec3(5, 5, 5)); c_6 = _e80; return; } diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index e6b3967d7..c42d823e5 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -30,9 +30,9 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { if ((homogeneous_coords.w <= 0.0)) { return 1.0; } - let flip_correction: vec2 = vec2(0.5, -0.5); - let light_local: vec2 = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - let _e26: f32 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); + let flip_correction = vec2(0.5, -0.5); + let light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); + let _e26 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); return _e26; } @@ -41,26 +41,26 @@ fn fs_main([[location(0)]] raw_normal: vec3, [[location(1)]] position: vec4 var color: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i: u32 = 0u; - let normal: vec3 = normalize(raw_normal); + let normal = normalize(raw_normal); loop { - let _e12: u32 = i; - let _e15: u32 = u_globals.num_lights.x; + let _e12 = i; + let _e15 = u_globals.num_lights.x; if ((_e12 >= min(_e15, c_max_lights))) { break; } - let _e19: u32 = i; - let light: Light = s_lights.data[_e19]; - let _e22: u32 = i; - let _e25: f32 = fetch_shadow(_e22, (light.proj * position)); - let light_dir: vec3 = normalize((light.pos.xyz - position.xyz)); - let diffuse: f32 = max(0.0, dot(normal, light_dir)); - let _e34: vec3 = color; + let _e19 = i; + let light = s_lights.data[_e19]; + let _e22 = i; + let _e25 = fetch_shadow(_e22, (light.proj * position)); + let light_dir = normalize((light.pos.xyz - position.xyz)); + let diffuse = max(0.0, dot(normal, light_dir)); + let _e34 = color; color = (_e34 + ((_e25 * diffuse) * light.color.xyz)); continuing { - let _e40: u32 = i; + let _e40 = i; i = (_e40 + 1u); } } - let _e43: vec3 = color; + let _e43 = color; return vec4(_e43, 1.0); } diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index 75460c49b..749725507 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -23,20 +23,20 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { tmp1_ = (i32(vertex_index) / 2); tmp2_ = (i32(vertex_index) & 1); - let _e10: i32 = tmp1_; - let _e16: i32 = tmp2_; - let pos: vec4 = vec4(((f32(_e10) * 4.0) - 1.0), ((f32(_e16) * 4.0) - 1.0), 0.0, 1.0); - let _e27: vec4 = r_data.view[0]; - let _e31: vec4 = r_data.view[1]; - let _e35: vec4 = r_data.view[2]; - let inv_model_view: mat3x3 = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); - let _e40: mat4x4 = r_data.proj_inv; - let unprojected: vec4 = (_e40 * pos); + let _e10 = tmp1_; + let _e16 = tmp2_; + let pos = vec4(((f32(_e10) * 4.0) - 1.0), ((f32(_e16) * 4.0) - 1.0), 0.0, 1.0); + let _e27 = r_data.view[0]; + let _e31 = r_data.view[1]; + let _e35 = r_data.view[2]; + let inv_model_view = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); + let _e40 = r_data.proj_inv; + let unprojected = (_e40 * pos); return VertexOutput(pos, (inv_model_view * unprojected.xyz)); } [[stage(fragment)]] fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 { - let _e5: vec4 = textureSample(r_texture, r_sampler, in.uv); + let _e5 = textureSample(r_texture, r_sampler, in.uv); return _e5; } diff --git a/tests/out/wgsl/standard.wgsl b/tests/out/wgsl/standard.wgsl index 3aa0277df..c6a94c494 100644 --- a/tests/out/wgsl/standard.wgsl +++ b/tests/out/wgsl/standard.wgsl @@ -1,7 +1,7 @@ [[stage(fragment)]] fn derivatives([[builtin(position)]] foo: vec4) -> [[location(0)]] vec4 { - let x: vec4 = dpdx(foo); - let y: vec4 = dpdy(foo); - let z: vec4 = fwidth(foo); + let x = dpdx(foo); + let y = dpdy(foo); + let z = fwidth(foo); return ((x + y) * z); } diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index 5be3815d5..81888740a 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -1,13 +1,13 @@ fn main_1() { var x: vec3 = vec3(2.0, 2.0, 2.0); - let _e3: vec3 = x; - let _e8: vec2 = vec2(3.0, 4.0); + let _e3 = x; + let _e8 = vec2(3.0, 4.0); x.z = _e8.x; x.x = _e8.y; - let _e13: vec3 = x; - let _e15: vec3 = x; - let _e18: vec2 = (_e15.xy * 5.0); + let _e13 = x; + let _e15 = x; + let _e18 = (_e15.xy * 5.0); x.x = _e18.x; x.y = _e18.y; return; diff --git a/tests/out/wgsl/texture-arg.wgsl b/tests/out/wgsl/texture-arg.wgsl index 420b43780..2be8f185c 100644 --- a/tests/out/wgsl/texture-arg.wgsl +++ b/tests/out/wgsl/texture-arg.wgsl @@ -4,12 +4,12 @@ var Texture: texture_2d; var Sampler: sampler; fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { - let _e7: vec4 = textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); + let _e7 = textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); return _e7; } [[stage(fragment)]] fn main() -> [[location(0)]] vec4 { - let _e2: vec4 = test(Texture, Sampler); + let _e2 = test(Texture, Sampler); return _e2; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index ce15b6e10..cba289860 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -379,10 +379,7 @@ fn write_output_wgsl( println!("writing WGSL"); let mut flags = wgsl::WriterFlags::empty(); - flags.set( - wgsl::WriterFlags::EXPLICIT_TYPES, - params.explicit_types | true, - ); + flags.set(wgsl::WriterFlags::EXPLICIT_TYPES, params.explicit_types); let string = wgsl::write_string(module, info, flags).expect("WGSL write failed"); From daa61b5fcbc7fed43ead48f4f48d4c3a06b810a0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 26 Nov 2021 12:10:43 -0500 Subject: [PATCH 1460/2212] Fix shapshots to run without deserialize feature --- tests/snapshots.rs | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index cba289860..74a2b5cf2 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -1,3 +1,7 @@ +// A lot of the code can be unused based on configuration flags, +// the corresponding warnings aren't helpful. +#![allow(dead_code)] + use std::{fs, path::PathBuf}; const BASE_DIR_IN: &str = "tests/in"; @@ -16,7 +20,6 @@ bitflags::bitflags! { } } -#[cfg_attr(not(feature = "spv-out"), allow(dead_code))] #[derive(serde::Deserialize)] struct SpvOutVersion(u8, u8); impl Default for SpvOutVersion { @@ -25,7 +28,6 @@ impl Default for SpvOutVersion { } } -#[cfg_attr(not(feature = "spv-out"), allow(dead_code))] #[derive(Default, serde::Deserialize)] struct SpirvOutParameters { version: SpvOutVersion, @@ -43,14 +45,12 @@ struct SpirvOutParameters { separate_entry_points: bool, } -#[cfg_attr(not(feature = "wgsl-out"), allow(dead_code))] #[derive(Default, serde::Deserialize)] struct WgslOutParameters { #[serde(default)] explicit_types: bool, } -#[allow(dead_code)] #[derive(Default, serde::Deserialize)] struct Parameters { #[serde(default)] @@ -75,7 +75,7 @@ struct Parameters { wgsl: WgslOutParameters, } -#[allow(dead_code, unused_variables)] +#[allow(unused_variables)] fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let root = env!("CARGO_MANIFEST_DIR"); let params = match fs::read_to_string(format!("{}/{}/{}.param.ron", root, BASE_DIR_IN, name)) { @@ -112,15 +112,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { } } - if !cfg!(feature = "deserialize") { - println!( - "No access to parameters, skipping {} for {:?}", - name, targets - ); - return; - } - - #[cfg(feature = "spv-out")] + #[cfg(all(feature = "deserialize", feature = "spv-out"))] { if targets.contains(Targets::SPIRV) { write_output_spv( @@ -133,13 +125,13 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { ); } } - #[cfg(feature = "msl-out")] + #[cfg(all(feature = "deserialize", feature = "msl-out"))] { if targets.contains(Targets::METAL) { write_output_msl(module, &info, &dest, name, ¶ms.msl); } } - #[cfg(feature = "glsl-out")] + #[cfg(all(feature = "deserialize", feature = "glsl-out"))] { if targets.contains(Targets::GLSL) { for ep in module.entry_points.iter() { @@ -157,13 +149,13 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { fs::write(dest.join(format!("dot/{}.dot", name)), string).unwrap(); } } - #[cfg(feature = "hlsl-out")] + #[cfg(all(feature = "deserialize", feature = "hlsl-out"))] { if targets.contains(Targets::HLSL) { write_output_hlsl(module, &info, &dest, name, ¶ms.hlsl); } } - #[cfg(feature = "wgsl-out")] + #[cfg(all(feature = "deserialize", feature = "wgsl-out"))] { if targets.contains(Targets::WGSL) { write_output_wgsl(module, &info, &dest, name, ¶ms.wgsl); From 20b96ef47b22d2679f6f54878d16727ee9ba1dc8 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 26 Nov 2021 21:56:59 +0300 Subject: [PATCH 1461/2212] Avoid function name redefinition in tests --- tests/in/interpolate.wgsl | 4 ++-- tests/in/quad.wgsl | 4 ++-- tests/out/dot/quad.dot | 4 ++-- tests/out/hlsl/interpolate.hlsl | 12 ++++++------ tests/out/hlsl/interpolate.hlsl.config | 4 ++-- tests/out/hlsl/quad.hlsl | 12 ++++++------ tests/out/hlsl/quad.hlsl.config | 4 ++-- tests/out/msl/interpolate.msl | 12 ++++++------ tests/out/msl/quad.msl | 20 ++++++++++---------- tests/out/spv/interpolate.spvasm | 8 ++++---- tests/out/spv/quad.spvasm | 8 ++++---- tests/out/wgsl/interpolate.wgsl | 4 ++-- tests/out/wgsl/quad.wgsl | 4 ++-- 13 files changed, 50 insertions(+), 50 deletions(-) diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index ba134c943..9b869e343 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -12,7 +12,7 @@ struct FragmentInput { }; [[stage(vertex)]] -fn main() -> FragmentInput { +fn vert_main() -> FragmentInput { var out: FragmentInput; out.position = vec4(2.0, 4.0, 5.0, 6.0); @@ -28,4 +28,4 @@ fn main() -> FragmentInput { } [[stage(fragment)]] -fn main(val : FragmentInput) { } +fn frag_main(val : FragmentInput) { } diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 546622f39..4dd8e8a7d 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -7,7 +7,7 @@ struct VertexOutput { }; [[stage(vertex)]] -fn main( +fn vert_main( [[location(0)]] pos : vec2, [[location(1)]] uv : vec2, ) -> VertexOutput { @@ -19,7 +19,7 @@ fn main( [[group(0), binding(1)]] var u_sampler : sampler; [[stage(fragment)]] -fn main([[location(0)]] uv : vec2) -> [[location(0)]] vec4 { +fn frag_main([[location(0)]] uv : vec2) -> [[location(0)]] vec4 { let color = textureSample(u_texture, u_sampler, uv); if (color.a == 0.0) { discard; diff --git a/tests/out/dot/quad.dot b/tests/out/dot/quad.dot index 1318d9eb0..6225f7b9a 100644 --- a/tests/out/dot/quad.dot +++ b/tests/out/dot/quad.dot @@ -5,7 +5,7 @@ digraph Module { g1 [ shape=hexagon label="[2] Handle/'u_sampler'" ] } subgraph cluster_ep0 { - label="Vertex/'main'" + label="Vertex/'vert_main'" node [ style=filled ] ep0_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] ep0_e1 [ color="#8dd3c7" label="[2] Argument[0]" ] @@ -32,7 +32,7 @@ digraph Module { ep0_s2 -> ep0_e7 [ style=dotted ] } subgraph cluster_ep1 { - label="Fragment/'main'" + label="Fragment/'frag_main'" node [ style=filled ] ep1_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] ep1_e1 [ color="#ffffb3" label="[2] Global" ] diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index 7372b0f81..07e0090d7 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -10,7 +10,7 @@ struct FragmentInput { linear sample float perspective_sample : LOC6; }; -struct VertexOutput_main { +struct VertexOutput_vert_main { uint flat : LOC0; float linear_ : LOC1; float2 linear_centroid : LOC2; @@ -21,7 +21,7 @@ struct VertexOutput_main { float4 position : SV_Position; }; -struct FragmentInput_main { +struct FragmentInput_frag_main { uint flat_1 : LOC0; float linear_1 : LOC1; float2 linear_centroid_1 : LOC2; @@ -32,7 +32,7 @@ struct FragmentInput_main { float4 position_1 : SV_Position; }; -VertexOutput_main main() +VertexOutput_vert_main vert_main() { FragmentInput out_ = (FragmentInput)0; @@ -46,12 +46,12 @@ VertexOutput_main main() out_.perspective_sample = 2744.0; FragmentInput _expr30 = out_; const FragmentInput fragmentinput = _expr30; - const VertexOutput_main fragmentinput_1 = { fragmentinput.flat, fragmentinput.linear_, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position }; + const VertexOutput_vert_main fragmentinput_1 = { fragmentinput.flat, fragmentinput.linear_, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position }; return fragmentinput_1; } -void main_1(FragmentInput_main fragmentinput_main) +void frag_main(FragmentInput_frag_main fragmentinput_frag_main) { - FragmentInput val = { fragmentinput_main.position_1, fragmentinput_main.flat_1, fragmentinput_main.linear_1, fragmentinput_main.linear_centroid_1, fragmentinput_main.linear_sample_1, fragmentinput_main.perspective_1, fragmentinput_main.perspective_centroid_1, fragmentinput_main.perspective_sample_1 }; + FragmentInput val = { fragmentinput_frag_main.position_1, fragmentinput_frag_main.flat_1, fragmentinput_frag_main.linear_1, fragmentinput_frag_main.linear_centroid_1, fragmentinput_frag_main.linear_sample_1, fragmentinput_frag_main.perspective_1, fragmentinput_frag_main.perspective_centroid_1, fragmentinput_frag_main.perspective_sample_1 }; return; } diff --git a/tests/out/hlsl/interpolate.hlsl.config b/tests/out/hlsl/interpolate.hlsl.config index 5a8cb0c2e..e08910d1e 100644 --- a/tests/out/hlsl/interpolate.hlsl.config +++ b/tests/out/hlsl/interpolate.hlsl.config @@ -1,3 +1,3 @@ -vertex=(main:vs_5_1 ) -fragment=(main_1:ps_5_1 ) +vertex=(vert_main:vs_5_1 ) +fragment=(frag_main:ps_5_1 ) compute=() diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index 1a6c3caaf..ee1bc56ef 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -8,12 +8,12 @@ struct VertexOutput { Texture2D u_texture : register(t0); SamplerState u_sampler : register(s1); -struct VertexOutput_main { +struct VertexOutput_vert_main { float2 uv_2 : LOC0; float4 position : SV_Position; }; -struct FragmentInput_main { +struct FragmentInput_frag_main { float2 uv_3 : LOC0; }; @@ -24,16 +24,16 @@ VertexOutput ConstructVertexOutput(float2 arg0, float4 arg1) { return ret; } -VertexOutput_main main(float2 pos : LOC0, float2 uv : LOC1) +VertexOutput_vert_main vert_main(float2 pos : LOC0, float2 uv : LOC1) { const VertexOutput vertexoutput = ConstructVertexOutput(uv, float4((c_scale * pos), 0.0, 1.0)); - const VertexOutput_main vertexoutput_1 = { vertexoutput.uv, vertexoutput.position }; + const VertexOutput_vert_main vertexoutput_1 = { vertexoutput.uv, vertexoutput.position }; return vertexoutput_1; } -float4 main_1(FragmentInput_main fragmentinput_main) : SV_Target0 +float4 frag_main(FragmentInput_frag_main fragmentinput_frag_main) : SV_Target0 { - float2 uv_1 = fragmentinput_main.uv_3; + float2 uv_1 = fragmentinput_frag_main.uv_3; float4 color = u_texture.Sample(u_sampler, uv_1); if ((color.w == 0.0)) { discard; diff --git a/tests/out/hlsl/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config index 7678a4e57..7a37fc4b0 100644 --- a/tests/out/hlsl/quad.hlsl.config +++ b/tests/out/hlsl/quad.hlsl.config @@ -1,3 +1,3 @@ -vertex=(main:vs_5_1 ) -fragment=(main_1:ps_5_1 fs_extra:ps_5_1 ) +vertex=(vert_main:vs_5_1 ) +fragment=(frag_main:ps_5_1 fs_extra:ps_5_1 ) compute=() diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl index 24a259806..b92adb399 100644 --- a/tests/out/msl/interpolate.msl +++ b/tests/out/msl/interpolate.msl @@ -13,7 +13,7 @@ struct FragmentInput { float perspective_sample; }; -struct main_Output { +struct vert_mainOutput { metal::float4 position [[position]]; metal::uint flat [[user(loc0), flat]]; float linear [[user(loc1), center_no_perspective]]; @@ -23,7 +23,7 @@ struct main_Output { float perspective_centroid [[user(loc5), centroid_perspective]]; float perspective_sample [[user(loc6), sample_perspective]]; }; -vertex main_Output main_( +vertex vert_mainOutput vert_main( ) { FragmentInput out; out.position = metal::float4(2.0, 4.0, 5.0, 6.0); @@ -36,11 +36,11 @@ vertex main_Output main_( out.perspective_sample = 2744.0; FragmentInput _e30 = out; const auto _tmp = _e30; - return main_Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample }; + return vert_mainOutput { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample }; } -struct main_1Input { +struct frag_mainInput { metal::uint flat [[user(loc0), flat]]; float linear [[user(loc1), center_no_perspective]]; metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]]; @@ -49,8 +49,8 @@ struct main_1Input { float perspective_centroid [[user(loc5), centroid_perspective]]; float perspective_sample [[user(loc6), sample_perspective]]; }; -fragment void main_1( - main_1Input varyings_1 [[stage_in]] +fragment void frag_main( + frag_mainInput varyings_1 [[stage_in]] , metal::float4 position [[position]] ) { const FragmentInput val = { position, varyings_1.flat, varyings_1.linear, varyings_1.linear_centroid, varyings_1.linear_sample, varyings_1.perspective, varyings_1.perspective_centroid, varyings_1.perspective_sample }; diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl index b55036702..a99532b12 100644 --- a/tests/out/msl/quad.msl +++ b/tests/out/msl/quad.msl @@ -8,32 +8,32 @@ struct VertexOutput { metal::float4 position; }; -struct main_Input { +struct vert_mainInput { metal::float2 pos [[attribute(0)]]; metal::float2 uv [[attribute(1)]]; }; -struct main_Output { +struct vert_mainOutput { metal::float2 uv [[user(loc0), center_perspective]]; metal::float4 position [[position]]; }; -vertex main_Output main_( - main_Input varyings [[stage_in]] +vertex vert_mainOutput vert_main( + vert_mainInput varyings [[stage_in]] ) { const auto pos = varyings.pos; const auto uv = varyings.uv; const auto _tmp = VertexOutput {uv, metal::float4(c_scale * pos, 0.0, 1.0)}; - return main_Output { _tmp.uv, _tmp.position }; + return vert_mainOutput { _tmp.uv, _tmp.position }; } -struct main_1Input { +struct frag_mainInput { metal::float2 uv_1 [[user(loc0), center_perspective]]; }; -struct main_1Output { +struct frag_mainOutput { metal::float4 member_1 [[color(0)]]; }; -fragment main_1Output main_1( - main_1Input varyings_1 [[stage_in]] +fragment frag_mainOutput frag_main( + frag_mainInput varyings_1 [[stage_in]] , metal::texture2d u_texture [[user(fake0)]] , metal::sampler u_sampler [[user(fake0)]] ) { @@ -43,7 +43,7 @@ fragment main_1Output main_1( metal::discard_fragment(); } metal::float4 premultiplied = color.w * color; - return main_1Output { premultiplied }; + return frag_mainOutput { premultiplied }; } diff --git a/tests/out/spv/interpolate.spvasm b/tests/out/spv/interpolate.spvasm index fc888a7a1..496df463a 100644 --- a/tests/out/spv/interpolate.spvasm +++ b/tests/out/spv/interpolate.spvasm @@ -6,8 +6,8 @@ OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %45 "main" %29 %31 %33 %35 %37 %39 %40 %41 %42 -OpEntryPoint Fragment %108 "main" %87 %90 %93 %96 %99 %102 %104 %106 +OpEntryPoint Vertex %45 "vert_main" %29 %31 %33 %35 %37 %39 %40 %41 %42 +OpEntryPoint Fragment %108 "frag_main" %87 %90 %93 %96 %99 %102 %104 %106 OpExecutionMode %108 OriginUpperLeft OpSource GLSL 450 OpMemberName %25 0 "position" @@ -28,7 +28,7 @@ OpName %37 "linear_sample" OpName %39 "perspective" OpName %40 "perspective_centroid" OpName %41 "perspective_sample" -OpName %45 "main" +OpName %45 "vert_main" OpName %87 "position" OpName %90 "flat" OpName %93 "linear" @@ -37,7 +37,7 @@ OpName %99 "linear_sample" OpName %102 "perspective" OpName %104 "perspective_centroid" OpName %106 "perspective_sample" -OpName %108 "main" +OpName %108 "frag_main" OpMemberDecorate %25 0 Offset 0 OpMemberDecorate %25 1 Offset 16 OpMemberDecorate %25 2 Offset 20 diff --git a/tests/out/spv/quad.spvasm b/tests/out/spv/quad.spvasm index c3a70b0e1..bb0409d14 100644 --- a/tests/out/spv/quad.spvasm +++ b/tests/out/spv/quad.spvasm @@ -5,8 +5,8 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %27 "main" %18 %21 %23 %25 -OpEntryPoint Fragment %45 "main" %42 %44 +OpEntryPoint Vertex %27 "vert_main" %18 %21 %23 %25 +OpEntryPoint Fragment %45 "frag_main" %42 %44 OpEntryPoint Fragment %61 "fs_extra" %60 OpExecutionMode %45 OriginUpperLeft OpExecutionMode %61 OriginUpperLeft @@ -21,9 +21,9 @@ OpName %18 "pos" OpName %21 "uv" OpName %23 "uv" OpName %25 "position" -OpName %27 "main" +OpName %27 "vert_main" OpName %42 "uv" -OpName %45 "main" +OpName %45 "frag_main" OpName %61 "fs_extra" OpMemberDecorate %10 0 Offset 0 OpMemberDecorate %10 1 Offset 16 diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index 401c849e0..c98b74f64 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -10,7 +10,7 @@ struct FragmentInput { }; [[stage(vertex)]] -fn main() -> FragmentInput { +fn vert_main() -> FragmentInput { var out: FragmentInput; out.position = vec4(2.0, 4.0, 5.0, 6.0); @@ -26,6 +26,6 @@ fn main() -> FragmentInput { } [[stage(fragment)]] -fn main_1(val: FragmentInput) { +fn frag_main(val: FragmentInput) { return; } diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 2044b26b8..c5dcbdadc 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -11,12 +11,12 @@ var u_texture: texture_2d; var u_sampler: sampler; [[stage(vertex)]] -fn main([[location(0)]] pos: vec2, [[location(1)]] uv: vec2) -> VertexOutput { +fn vert_main([[location(0)]] pos: vec2, [[location(1)]] uv: vec2) -> VertexOutput { return VertexOutput(uv, vec4((c_scale * pos), 0.0, 1.0)); } [[stage(fragment)]] -fn main_1([[location(0)]] uv_1: vec2) -> [[location(0)]] vec4 { +fn frag_main([[location(0)]] uv_1: vec2) -> [[location(0)]] vec4 { let color = textureSample(u_texture, u_sampler, uv_1); if ((color.w == 0.0)) { discard; From dba6beb941aaf89436b57f14d6fc405da612e6e5 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Thu, 25 Nov 2021 01:36:57 +0300 Subject: [PATCH 1462/2212] [wgsl-in] Don't allow redefinition of module scope identifiers --- src/front/wgsl/mod.rs | 44 +++++++++- src/front/wgsl/tests.rs | 2 +- tests/in/globals.wgsl | 28 ++++--- tests/out/glsl/globals.main.Compute.glsl | 6 +- tests/out/hlsl/globals.hlsl | 9 +- tests/out/msl/globals.msl | 8 +- tests/out/spv/globals.spvasm | 47 ++++++----- tests/out/wgsl/globals.wgsl | 9 +- tests/wgsl-errors.rs | 101 +++++++++++++++++++++-- 9 files changed, 200 insertions(+), 54 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index c47ffe8a4..9dfc194f2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -171,6 +171,10 @@ pub enum Error<'a> { NotPointer(Span), NotReference(&'static str, Span), ReservedKeyword(Span), + Redefinition { + previous: Span, + current: Span, + }, Other, } @@ -188,7 +192,7 @@ impl<'a> Error<'a> { Token::Number { value, .. } => { format!("number ({})", value) } - Token::String(s) => format!("string literal ('{}')", s.to_string()), + Token::String(s) => format!("string literal ('{}')", s), Token::Word(s) => s.to_string(), Token::Operation(c) => format!("operation ('{}')", c), Token::LogicalOperation(c) => format!("logical operation ('{}')", c), @@ -439,10 +443,17 @@ impl<'a> Error<'a> { notes: vec![], }, Error::ReservedKeyword(ref name_span) => ParseError { - message: format!("Name `{}` is a reserved keyword", &source[name_span.clone()]), + message: format!("name `{}` is a reserved keyword", &source[name_span.clone()]), labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], notes: vec![], }, + Error::Redefinition { ref previous, ref current } => ParseError { + message: format!("redefinition of `{}`", &source[current.clone()]), + labels: vec![(current.clone(), format!("redefinition of `{}`", &source[current.clone()]).into()), + (previous.clone(), format!("previous definition of `{}`", &source[previous.clone()]).into()) + ], + notes: vec![], + }, Error::Other => ParseError { message: "other error".to_string(), labels: vec![], @@ -1204,6 +1215,7 @@ impl std::error::Error for ParseError { pub struct Parser { scopes: Vec<(Scope, usize)>, + module_scope_identifiers: FastHashMap, lookup_type: FastHashMap>, layouter: Layouter, } @@ -1212,6 +1224,7 @@ impl Parser { pub fn new() -> Self { Parser { scopes: Vec::new(), + module_scope_identifiers: FastHashMap::default(), lookup_type: FastHashMap::default(), layouter: Default::default(), } @@ -3837,6 +3850,15 @@ impl Parser { if crate::keywords::wgsl::RESERVED.contains(&fun_name) { return Err(Error::ReservedKeyword(span)); } + if let Some(entry) = self + .module_scope_identifiers + .insert(String::from(fun_name), span.clone()) + { + return Err(Error::Redefinition { + previous: entry, + current: span, + }); + } // populate initial expressions let mut expressions = Arena::new(); for (&name, expression) in lookup_global_expression.iter() { @@ -4083,6 +4105,15 @@ impl Parser { if crate::keywords::wgsl::RESERVED.contains(&name) { return Err(Error::ReservedKeyword(name_span)); } + if let Some(entry) = self + .module_scope_identifiers + .insert(String::from(name), name_span.clone()) + { + return Err(Error::Redefinition { + previous: entry, + current: name_span, + }); + } let given_ty = if lexer.skip(Token::Separator(':')) { let (ty, _access) = self.parse_type_decl( lexer, @@ -4131,6 +4162,15 @@ impl Parser { if crate::keywords::wgsl::RESERVED.contains(&pvar.name) { return Err(Error::ReservedKeyword(pvar.name_span)); } + if let Some(entry) = self + .module_scope_identifiers + .insert(String::from(pvar.name), pvar.name_span.clone()) + { + return Err(Error::Redefinition { + previous: entry, + current: pvar.name_span, + }); + } let var_handle = module.global_variables.append( crate::GlobalVariable { name: Some(pvar.name.to_owned()), diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index da1670c14..143432063 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -408,7 +408,7 @@ fn parse_array_length() { [[group(0), binding(1)]] var bar: array; - fn foo() { + fn baz() { var x: u32 = arrayLength(foo.data); var y: u32 = arrayLength(bar); } diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index f1b1a41f1..17d470f99 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -1,12 +1,16 @@ -// Global variable & constant declarations - -let Foo: bool = true; - -var wg : array; -var at: atomic; - -[[stage(compute), workgroup_size(1)]] -fn main() { - wg[3] = 1.0; - atomicStore(&at, 2u); -} +// Global variable & constant declarations + +let Foo: bool = true; + +var wg : array; +var at: atomic; + +[[stage(compute), workgroup_size(1)]] +fn main() { + wg[3] = 1.0; + atomicStore(&at, 2u); + + // Valid, Foo and at is in function scope + var Foo: f32 = 1.0; + var at: bool = true; +} diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index a0e999dc2..f38fde93e 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -7,12 +7,14 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; shared float wg[10]; -shared uint at; +shared uint at_1; void main() { + float Foo = 1.0; + bool at = true; wg[3] = 1.0; - at = 2u; + at_1 = 2u; return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 4bcb132fb..ef2ceb422 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -1,12 +1,15 @@ -static const bool Foo = true; +static const bool Foo_1 = true; groupshared float wg[10]; -groupshared uint at; +groupshared uint at_1; [numthreads(1, 1, 1)] void main() { + float Foo = 1.0; + bool at = true; + wg[3] = 1.0; - at = 2u; + at_1 = 2u; return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index a7693a0eb..c00b2a237 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -2,16 +2,18 @@ #include #include -constexpr constant bool Foo = true; +constexpr constant bool Foo_1 = true; struct type_2 { float inner[10u]; }; kernel void main_( threadgroup type_2& wg -, threadgroup metal::atomic_uint& at +, threadgroup metal::atomic_uint& at_1 ) { + float Foo = 1.0; + bool at = true; wg.inner[3] = 1.0; - metal::atomic_store_explicit(&at, 2u, metal::memory_order_relaxed); + metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index f44983e9b..942d5a73d 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 26 +; Bound: 31 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %18 "main" -OpExecutionMode %18 LocalSize 1 1 1 -OpDecorate %12 ArrayStride 4 +OpEntryPoint GLCompute %23 "main" +OpExecutionMode %23 LocalSize 1 1 1 +OpDecorate %13 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -18,22 +18,27 @@ OpDecorate %12 ArrayStride 4 %10 = OpTypeFloat 32 %9 = OpConstant %10 1.0 %11 = OpConstant %6 2 -%12 = OpTypeArray %10 %5 -%14 = OpTypePointer Workgroup %12 -%13 = OpVariable %14 Workgroup -%16 = OpTypePointer Workgroup %6 -%15 = OpVariable %16 Workgroup -%19 = OpTypeFunction %2 -%21 = OpTypePointer Workgroup %10 -%22 = OpConstant %6 3 -%24 = OpConstant %8 2 -%25 = OpConstant %6 256 -%18 = OpFunction %2 None %19 -%17 = OpLabel -OpBranch %20 -%20 = OpLabel -%23 = OpAccessChain %21 %13 %22 -OpStore %23 %9 -OpAtomicStore %15 %24 %25 %11 +%12 = OpConstantTrue %4 +%13 = OpTypeArray %10 %5 +%15 = OpTypePointer Workgroup %13 +%14 = OpVariable %15 Workgroup +%17 = OpTypePointer Workgroup %6 +%16 = OpVariable %17 Workgroup +%19 = OpTypePointer Function %10 +%21 = OpTypePointer Function %4 +%24 = OpTypeFunction %2 +%26 = OpTypePointer Workgroup %10 +%27 = OpConstant %6 3 +%29 = OpConstant %8 2 +%30 = OpConstant %6 256 +%23 = OpFunction %2 None %24 +%22 = OpLabel +%18 = OpVariable %19 Function %9 +%20 = OpVariable %21 Function %12 +OpBranch %25 +%25 = OpLabel +%28 = OpAccessChain %26 %14 %27 +OpStore %28 %9 +OpAtomicStore %16 %29 %30 %11 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 4eea757c9..06e1bdb1f 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -1,11 +1,14 @@ -let Foo: bool = true; +let Foo_1: bool = true; var wg: array; -var at: atomic; +var at_1: atomic; [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { + var Foo: f32 = 1.0; + var at: bool = true; + wg[3] = 1.0; - atomicStore((&at), 2u); + atomicStore((&at_1), 2u); return; } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 2ebef2c30..13b50109c 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -552,7 +552,7 @@ fn reserved_keyword() { r#" var bool: bool = true; "#, - r###"error: Name ` bool: bool = true;` is a reserved keyword + r###"error: name ` bool: bool = true;` is a reserved keyword ┌─ wgsl:2:16 │ 2 │ var bool: bool = true; @@ -569,7 +569,7 @@ fn reserved_keyword() { var foo = break; } "#, - r###"error: Name `break` is a reserved keyword + r###"error: name `break` is a reserved keyword ┌─ wgsl:2:17 │ 2 │ let break: bool = true; @@ -585,7 +585,7 @@ fn reserved_keyword() { let atomic: f32 = 1.0; } "#, - r###"error: Name `atomic` is a reserved keyword + r###"error: name `atomic` is a reserved keyword ┌─ wgsl:3:21 │ 3 │ let atomic: f32 = 1.0; @@ -601,7 +601,7 @@ fn reserved_keyword() { var sampler: f32 = 1.0; } "#, - r###"error: Name `sampler` is a reserved keyword + r###"error: name `sampler` is a reserved keyword ┌─ wgsl:3:21 │ 3 │ var sampler: f32 = 1.0; @@ -615,7 +615,7 @@ fn reserved_keyword() { r#" fn break() {} "#, - r###"error: Name `break` is a reserved keyword + r###"error: name `break` is a reserved keyword ┌─ wgsl:2:16 │ 2 │ fn break() {} @@ -629,7 +629,7 @@ fn reserved_keyword() { r#" struct array {}; "#, - r###"error: Name `array` is a reserved keyword + r###"error: name `array` is a reserved keyword ┌─ wgsl:2:20 │ 2 │ struct array {}; @@ -643,7 +643,7 @@ fn reserved_keyword() { r#" struct Foo { sampler: f32; }; "#, - r###"error: Name `sampler` is a reserved keyword + r###"error: name `sampler` is a reserved keyword ┌─ wgsl:2:26 │ 2 │ struct Foo { sampler: f32; }; @@ -653,6 +653,93 @@ fn reserved_keyword() { ); } +#[test] +fn module_scope_identifier_redefinition() { + // let + check( + r#" + let foo: bool = true; + let foo: bool = true; + "#, + r###"error: redefinition of `foo` + ┌─ wgsl:2:17 + │ +2 │ let foo: bool = true; + │ ^^^ previous definition of `foo` +3 │ let foo: bool = true; + │ ^^^ redefinition of `foo` + +"###, + ); + // var + check( + r#" + var foo: bool = true; + var foo: bool = true; + "#, + r###"error: redefinition of ` foo: bool = true;` + ┌─ wgsl:2:16 + │ +2 │ var foo: bool = true; + │ ^^^^^^^^^^^^^^^^^^ previous definition of ` foo: bool = true;` +3 │ var foo: bool = true; + │ ^^^^^^^^^^^^^^^^^^ redefinition of ` foo: bool = true;` + +"###, + ); + + // let and var + check( + r#" + var foo: bool = true; + let foo: bool = true; + "#, + r###"error: redefinition of `foo` + ┌─ wgsl:2:16 + │ +2 │ var foo: bool = true; + │ ^^^^^^^^^^^^^^^^^^ previous definition of ` foo: bool = true;` +3 │ let foo: bool = true; + │ ^^^ redefinition of `foo` + +"###, + ); + + // function + check( + r#"fn foo() {} + fn bar() {} + fn foo() {}"#, + r###"error: redefinition of `foo` + ┌─ wgsl:1:4 + │ +1 │ fn foo() {} + │ ^^^ previous definition of `foo` +2 │ fn bar() {} +3 │ fn foo() {} + │ ^^^ redefinition of `foo` + +"###, + ); + + // let and function + check( + r#" + let foo: bool = true; + fn foo() {} + "#, + r###"error: redefinition of `foo` + ┌─ wgsl:2:17 + │ +2 │ let foo: bool = true; + │ ^^^ previous definition of `foo` +3 │ fn foo() {} + │ ^^^ redefinition of `foo` + +"###, + ); +} + macro_rules! check_validation_error { // We want to support an optional guard expression after the pattern, so // that we can check values we can't match against, like strings. From 9fac7c48a62811b1ea435a5cdac6d00bf2befe92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 28 Nov 2021 16:27:51 +0000 Subject: [PATCH 1463/2212] glsl-in: Allow vector/matrix in vector constructor The glsl spec defines that vector constructors flatten their arguments and consume them in order, ignoring the remaining arguments if there are more than needed --- src/front/glsl/functions.rs | 92 ++++- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 10 +- tests/out/wgsl/210-bevy-shader-vert.wgsl | 24 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 6 +- tests/out/wgsl/bevy-pbr-vert.wgsl | 29 +- tests/out/wgsl/clamp-splat-vert.wgsl | 3 +- tests/out/wgsl/quad_glsl-vert.wgsl | 3 +- tests/out/wgsl/samplers-frag.wgsl | 384 +++++++++--------- 8 files changed, 314 insertions(+), 237 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 1db1b4bc8..acaa5c975 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -115,7 +115,20 @@ impl Parser { TypeInner::Vector { size, kind, width } if vector_size.is_none() => { ctx.implicit_conversion(self, &mut value, meta, kind, width)?; - ctx.add_expression(Expression::Splat { size, value }, meta, body) + if let TypeInner::Scalar { .. } = *self.resolve_type(ctx, value, expr_meta)? { + ctx.add_expression(Expression::Splat { size, value }, meta, body) + } else { + self.vector_constructor( + ctx, + body, + ty, + size, + kind, + width, + &[(value, expr_meta)], + meta, + )? + } } TypeInner::Scalar { kind, width } => { let mut expr = value; @@ -393,6 +406,68 @@ impl Parser { Ok(ctx.add_expression(Expression::Compose { ty, components }, meta, body)) } + #[allow(clippy::too_many_arguments)] + fn vector_constructor( + &mut self, + ctx: &mut Context, + body: &mut Block, + ty: Handle, + size: crate::VectorSize, + kind: ScalarKind, + width: crate::Bytes, + args: &[(Handle, Span)], + meta: Span, + ) -> Result> { + let mut components = Vec::with_capacity(size as usize); + + for (mut arg, expr_meta) in args.iter().copied() { + ctx.implicit_conversion(self, &mut arg, expr_meta, kind, width)?; + + if components.len() >= size as usize { + break; + } + + match *self.resolve_type(ctx, arg, expr_meta)? { + TypeInner::Scalar { .. } => components.push(arg), + TypeInner::Matrix { rows, columns, .. } => { + components.reserve(rows as usize * columns as usize); + for c in 0..(columns as u32) { + let base = ctx.add_expression( + Expression::AccessIndex { + base: arg, + index: c, + }, + expr_meta, + body, + ); + for r in 0..(rows as u32) { + components.push(ctx.add_expression( + Expression::AccessIndex { base, index: r }, + expr_meta, + body, + )) + } + } + } + TypeInner::Vector { size: ori_size, .. } => { + components.reserve(ori_size as usize); + for index in 0..(ori_size as u32) { + components.push(ctx.add_expression( + Expression::AccessIndex { base: arg, index }, + expr_meta, + body, + )) + } + } + _ => components.push(arg), + } + } + + components.truncate(size as usize); + + Ok(ctx.add_expression(Expression::Compose { ty, components }, meta, body)) + } + fn constructor_many( &mut self, ctx: &mut Context, @@ -457,15 +532,14 @@ impl Parser { )) } } + TypeInner::Vector { size, kind, width } => { + return self.vector_constructor(ctx, body, ty, size, kind, width, &args, meta) + } _ => { - for (mut arg, meta) in args.iter().copied() { - let scalar_components = scalar_components(&self.module.types[ty].inner); - if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; - } - - components.push(arg) - } + return Err(Error { + kind: ErrorKind::SemanticError("Constructor: Too many arguments".into()), + meta, + }) } } diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 61e6a013c..7db8c9925 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -37,11 +37,11 @@ fn main_1() { v_Uv = _e10; let _e11 = Vertex_Position_1; let _e12 = global_2.size; - position = (_e11 * vec3(_e12, 1.0)); - let _e18 = global.ViewProj; - let _e19 = global_1.Model; - let _e21 = position; - gl_Position = ((_e18 * _e19) * vec4(_e21, 1.0)); + position = (_e11 * vec3(_e12.x, _e12.y, 1.0)); + let _e20 = global.ViewProj; + let _e21 = global_1.Model; + let _e23 = position; + gl_Position = ((_e20 * _e21) * vec4(_e23.x, _e23.y, _e23.z, 1.0)); return; } diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 2619b6064..94ccaea3e 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -30,18 +30,18 @@ var gl_Position: vec4; fn main_1() { let _e10 = global_1.Model; let _e11 = Vertex_Normal_1; - v_Normal = (_e10 * vec4(_e11, 1.0)).xyz; - let _e16 = global_1.Model; - let _e26 = Vertex_Normal_1; - v_Normal = (mat3x3(_e16[0].xyz, _e16[1].xyz, _e16[2].xyz) * _e26); - let _e28 = global_1.Model; - let _e29 = Vertex_Position_1; - v_Position = (_e28 * vec4(_e29, 1.0)).xyz; - let _e34 = Vertex_Uv_1; - v_Uv = _e34; - let _e36 = global.ViewProj; - let _e37 = v_Position; - gl_Position = (_e36 * vec4(_e37, 1.0)); + v_Normal = (_e10 * vec4(_e11.x, _e11.y, _e11.z, 1.0)).xyz; + let _e19 = global_1.Model; + let _e29 = Vertex_Normal_1; + v_Normal = (mat3x3(_e19[0].xyz, _e19[1].xyz, _e19[2].xyz) * _e29); + let _e31 = global_1.Model; + let _e32 = Vertex_Position_1; + v_Position = (_e31 * vec4(_e32.x, _e32.y, _e32.z, 1.0)).xyz; + let _e40 = Vertex_Uv_1; + v_Uv = _e40; + let _e42 = global.ViewProj; + let _e43 = v_Position; + gl_Position = (_e42 * vec4(_e43.x, _e43.y, _e43.z, 1.0)); return; } diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index febc5390f..06fd0f486 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -27,10 +27,10 @@ fn main_1() { let _e9 = global.view_matrix; let _e10 = global_1.world_matrix; let _e12 = position_1; - gl_Position = ((_e9 * _e10) * vec4(_e12, 0.0, 1.0)); - let _e18 = gl_Position; + gl_Position = ((_e9 * _e10) * vec4(_e12.x, _e12.y, 0.0, 1.0)); let _e20 = gl_Position; - gl_Position.z = ((_e18.z + _e20.w) / 2.0); + let _e22 = gl_Position; + gl_Position.z = ((_e20.z + _e22.w) / 2.0); return; } diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index b8ba3337b..1863c9681 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -35,21 +35,22 @@ fn main_1() { let _e12 = global_1.Model; let _e13 = Vertex_Position_1; - world_position = (_e12 * vec4(_e13, 1.0)); - let _e18 = world_position; - v_WorldPosition = _e18.xyz; - let _e20 = global_1.Model; - let _e30 = Vertex_Normal_1; - v_WorldNormal = (mat3x3(_e20[0].xyz, _e20[1].xyz, _e20[2].xyz) * _e30); - let _e32 = Vertex_Uv_1; - v_Uv = _e32; - let _e33 = global_1.Model; - let _e43 = Vertex_Tangent_1; + world_position = (_e12 * vec4(_e13.x, _e13.y, _e13.z, 1.0)); + let _e21 = world_position; + v_WorldPosition = _e21.xyz; + let _e23 = global_1.Model; + let _e33 = Vertex_Normal_1; + v_WorldNormal = (mat3x3(_e23[0].xyz, _e23[1].xyz, _e23[2].xyz) * _e33); + let _e35 = Vertex_Uv_1; + v_Uv = _e35; + let _e36 = global_1.Model; let _e46 = Vertex_Tangent_1; - v_WorldTangent = vec4((mat3x3(_e33[0].xyz, _e33[1].xyz, _e33[2].xyz) * _e43.xyz), _e46.w); - let _e50 = global.ViewProj; - let _e51 = world_position; - gl_Position = (_e50 * _e51); + let _e48 = (mat3x3(_e36[0].xyz, _e36[1].xyz, _e36[2].xyz) * _e46.xyz); + let _e49 = Vertex_Tangent_1; + v_WorldTangent = vec4(_e48.x, _e48.y, _e48.z, _e49.w); + let _e56 = global.ViewProj; + let _e57 = world_position; + gl_Position = (_e56 * _e57); return; } diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index 91df54d79..15cf4abbe 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -7,7 +7,8 @@ var gl_Position: vec4; fn main_1() { let _e5 = a_pos_1; - gl_Position = vec4(clamp(_e5, vec2(0.0), vec2(1.0)), 0.0, 1.0); + let _e10 = clamp(_e5, vec2(0.0), vec2(1.0)); + gl_Position = vec4(_e10.x, _e10.y, 0.0, 1.0); return; } diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index 8f878abe6..5af301d95 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -12,7 +12,8 @@ fn main_1() { let _e4 = a_uv_1; v_uv = _e4; let _e6 = a_pos_1; - gl_Position = vec4((1.2000000476837158 * _e6), 0.0, 1.0); + let _e7 = (1.2000000476837158 * _e6); + gl_Position = vec4(_e7.x, _e7.y, 0.0, 1.0); return; } diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 96e487caf..a902c4e83 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -202,85 +202,85 @@ fn testTex2D(coord_4: vec2) { let _e80 = textureSampleBias(tex2D, samp, _e76, 2.0, vec2(5, 5)); c_2 = _e80; let _e81 = coord_5; - let _e84 = coord_5; - let _e86 = vec3(_e84, 6.0); - let _e91 = textureSample(tex2D, samp, (_e86.xy / vec2(_e86.z))); - c_2 = _e91; - let _e92 = coord_5; + let _e86 = coord_5; + let _e90 = vec3(_e86.x, _e86.y, 6.0); + let _e95 = textureSample(tex2D, samp, (_e90.xy / vec2(_e90.z))); + c_2 = _e95; let _e96 = coord_5; - let _e99 = vec4(_e96, 0.0, 6.0); - let _e105 = textureSample(tex2D, samp, (_e99.xyz / vec3(_e99.w)).xy); - c_2 = _e105; - let _e106 = coord_5; - let _e110 = coord_5; - let _e112 = vec3(_e110, 6.0); - let _e118 = textureSampleBias(tex2D, samp, (_e112.xy / vec2(_e112.z)), 2.0); - c_2 = _e118; - let _e119 = coord_5; - let _e124 = coord_5; - let _e127 = vec4(_e124, 0.0, 6.0); - let _e134 = textureSampleBias(tex2D, samp, (_e127.xyz / vec3(_e127.w)).xy, 2.0); - c_2 = _e134; - let _e135 = coord_5; - let _e142 = coord_5; - let _e144 = vec3(_e142, 6.0); - let _e153 = textureSampleGrad(tex2D, samp, (_e144.xy / vec2(_e144.z)), vec2(4.0), vec2(4.0)); - c_2 = _e153; - let _e154 = coord_5; - let _e162 = coord_5; - let _e165 = vec4(_e162, 0.0, 6.0); - let _e175 = textureSampleGrad(tex2D, samp, (_e165.xyz / vec3(_e165.w)).xy, vec2(4.0), vec2(4.0)); - c_2 = _e175; - let _e176 = coord_5; - let _e185 = coord_5; - let _e187 = vec3(_e185, 6.0); - let _e198 = textureSampleGrad(tex2D, samp, (_e187.xy / vec2(_e187.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = _e198; - let _e199 = coord_5; - let _e209 = coord_5; - let _e212 = vec4(_e209, 0.0, 6.0); - let _e224 = textureSampleGrad(tex2D, samp, (_e212.xyz / vec3(_e212.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = _e224; - let _e225 = coord_5; - let _e229 = coord_5; - let _e231 = vec3(_e229, 6.0); - let _e237 = textureSampleLevel(tex2D, samp, (_e231.xy / vec2(_e231.z)), 3.0); - c_2 = _e237; - let _e238 = coord_5; - let _e243 = coord_5; - let _e246 = vec4(_e243, 0.0, 6.0); - let _e253 = textureSampleLevel(tex2D, samp, (_e246.xyz / vec3(_e246.w)).xy, 3.0); - c_2 = _e253; - let _e254 = coord_5; - let _e260 = coord_5; - let _e262 = vec3(_e260, 6.0); - let _e270 = textureSampleLevel(tex2D, samp, (_e262.xy / vec2(_e262.z)), 3.0, vec2(5, 5)); - c_2 = _e270; - let _e271 = coord_5; - let _e278 = coord_5; - let _e281 = vec4(_e278, 0.0, 6.0); - let _e290 = textureSampleLevel(tex2D, samp, (_e281.xyz / vec3(_e281.w)).xy, 3.0, vec2(5, 5)); - c_2 = _e290; - let _e291 = coord_5; - let _e296 = coord_5; - let _e298 = vec3(_e296, 6.0); - let _e305 = textureSample(tex2D, samp, (_e298.xy / vec2(_e298.z)), vec2(5, 5)); - c_2 = _e305; - let _e306 = coord_5; - let _e312 = coord_5; - let _e315 = vec4(_e312, 0.0, 6.0); - let _e323 = textureSample(tex2D, samp, (_e315.xyz / vec3(_e315.w)).xy, vec2(5, 5)); - c_2 = _e323; + let _e102 = coord_5; + let _e107 = vec4(_e102.x, _e102.y, 0.0, 6.0); + let _e113 = textureSample(tex2D, samp, (_e107.xyz / vec3(_e107.w)).xy); + c_2 = _e113; + let _e114 = coord_5; + let _e120 = coord_5; + let _e124 = vec3(_e120.x, _e120.y, 6.0); + let _e130 = textureSampleBias(tex2D, samp, (_e124.xy / vec2(_e124.z)), 2.0); + c_2 = _e130; + let _e131 = coord_5; + let _e138 = coord_5; + let _e143 = vec4(_e138.x, _e138.y, 0.0, 6.0); + let _e150 = textureSampleBias(tex2D, samp, (_e143.xyz / vec3(_e143.w)).xy, 2.0); + c_2 = _e150; + let _e151 = coord_5; + let _e160 = coord_5; + let _e164 = vec3(_e160.x, _e160.y, 6.0); + let _e173 = textureSampleGrad(tex2D, samp, (_e164.xy / vec2(_e164.z)), vec2(4.0), vec2(4.0)); + c_2 = _e173; + let _e174 = coord_5; + let _e184 = coord_5; + let _e189 = vec4(_e184.x, _e184.y, 0.0, 6.0); + let _e199 = textureSampleGrad(tex2D, samp, (_e189.xyz / vec3(_e189.w)).xy, vec2(4.0), vec2(4.0)); + c_2 = _e199; + let _e200 = coord_5; + let _e211 = coord_5; + let _e215 = vec3(_e211.x, _e211.y, 6.0); + let _e226 = textureSampleGrad(tex2D, samp, (_e215.xy / vec2(_e215.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e226; + let _e227 = coord_5; + let _e239 = coord_5; + let _e244 = vec4(_e239.x, _e239.y, 0.0, 6.0); + let _e256 = textureSampleGrad(tex2D, samp, (_e244.xyz / vec3(_e244.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e256; + let _e257 = coord_5; + let _e263 = coord_5; + let _e267 = vec3(_e263.x, _e263.y, 6.0); + let _e273 = textureSampleLevel(tex2D, samp, (_e267.xy / vec2(_e267.z)), 3.0); + c_2 = _e273; + let _e274 = coord_5; + let _e281 = coord_5; + let _e286 = vec4(_e281.x, _e281.y, 0.0, 6.0); + let _e293 = textureSampleLevel(tex2D, samp, (_e286.xyz / vec3(_e286.w)).xy, 3.0); + c_2 = _e293; + let _e294 = coord_5; + let _e302 = coord_5; + let _e306 = vec3(_e302.x, _e302.y, 6.0); + let _e314 = textureSampleLevel(tex2D, samp, (_e306.xy / vec2(_e306.z)), 3.0, vec2(5, 5)); + c_2 = _e314; + let _e315 = coord_5; let _e324 = coord_5; - let _e330 = coord_5; - let _e332 = vec3(_e330, 6.0); - let _e340 = textureSampleBias(tex2D, samp, (_e332.xy / vec2(_e332.z)), 2.0, vec2(5, 5)); - c_2 = _e340; - let _e341 = coord_5; - let _e348 = coord_5; - let _e351 = vec4(_e348, 0.0, 6.0); - let _e360 = textureSampleBias(tex2D, samp, (_e351.xyz / vec3(_e351.w)).xy, 2.0, vec2(5, 5)); - c_2 = _e360; + let _e329 = vec4(_e324.x, _e324.y, 0.0, 6.0); + let _e338 = textureSampleLevel(tex2D, samp, (_e329.xyz / vec3(_e329.w)).xy, 3.0, vec2(5, 5)); + c_2 = _e338; + let _e339 = coord_5; + let _e346 = coord_5; + let _e350 = vec3(_e346.x, _e346.y, 6.0); + let _e357 = textureSample(tex2D, samp, (_e350.xy / vec2(_e350.z)), vec2(5, 5)); + c_2 = _e357; + let _e358 = coord_5; + let _e366 = coord_5; + let _e371 = vec4(_e366.x, _e366.y, 0.0, 6.0); + let _e379 = textureSample(tex2D, samp, (_e371.xyz / vec3(_e371.w)).xy, vec2(5, 5)); + c_2 = _e379; + let _e380 = coord_5; + let _e388 = coord_5; + let _e392 = vec3(_e388.x, _e388.y, 6.0); + let _e400 = textureSampleBias(tex2D, samp, (_e392.xy / vec2(_e392.z)), 2.0, vec2(5, 5)); + c_2 = _e400; + let _e401 = coord_5; + let _e410 = coord_5; + let _e415 = vec4(_e410.x, _e410.y, 0.0, 6.0); + let _e424 = textureSampleBias(tex2D, samp, (_e415.xyz / vec3(_e415.w)).xy, 2.0, vec2(5, 5)); + c_2 = _e424; return; } @@ -290,71 +290,71 @@ fn testTex2DShadow(coord_6: vec2) { coord_7 = coord_6; let _e17 = coord_7; - let _e20 = coord_7; - let _e22 = vec3(_e20, 1.0); - let _e25 = textureSampleCompare(tex2DShadow, sampShadow, _e22.xy, _e22.z); - d = _e25; - let _e26 = coord_7; - let _e33 = coord_7; - let _e35 = vec3(_e33, 1.0); - let _e42 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e35.xy, _e35.z); - d = _e42; - let _e43 = coord_7; - let _e52 = coord_7; - let _e54 = vec3(_e52, 1.0); - let _e63 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e54.xy, _e54.z, vec2(5, 5)); - d = _e63; - let _e64 = coord_7; - let _e68 = coord_7; - let _e70 = vec3(_e68, 1.0); - let _e74 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e70.xy, _e70.z); - d = _e74; - let _e75 = coord_7; - let _e81 = coord_7; - let _e83 = vec3(_e81, 1.0); - let _e89 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e83.xy, _e83.z, vec2(5, 5)); - d = _e89; - let _e90 = coord_7; - let _e95 = coord_7; - let _e97 = vec3(_e95, 1.0); - let _e102 = textureSampleCompare(tex2DShadow, sampShadow, _e97.xy, _e97.z, vec2(5, 5)); - d = _e102; - let _e103 = coord_7; - let _e107 = coord_7; - let _e110 = vec4(_e107, 1.0, 6.0); - let _e114 = (_e110.xyz / vec3(_e110.w)); - let _e117 = textureSampleCompare(tex2DShadow, sampShadow, _e114.xy, _e114.z); - d = _e117; - let _e118 = coord_7; - let _e126 = coord_7; - let _e129 = vec4(_e126, 1.0, 6.0); - let _e137 = (_e129.xyz / vec3(_e129.w)); - let _e140 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e137.xy, _e137.z); - d = _e140; - let _e141 = coord_7; - let _e151 = coord_7; - let _e154 = vec4(_e151, 1.0, 6.0); - let _e164 = (_e154.xyz / vec3(_e154.w)); - let _e167 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e164.xy, _e164.z, vec2(5, 5)); - d = _e167; - let _e168 = coord_7; + let _e22 = coord_7; + let _e26 = vec3(_e22.x, _e22.y, 1.0); + let _e29 = textureSampleCompare(tex2DShadow, sampShadow, _e26.xy, _e26.z); + d = _e29; + let _e30 = coord_7; + let _e39 = coord_7; + let _e43 = vec3(_e39.x, _e39.y, 1.0); + let _e50 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e43.xy, _e43.z); + d = _e50; + let _e51 = coord_7; + let _e62 = coord_7; + let _e66 = vec3(_e62.x, _e62.y, 1.0); + let _e75 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e66.xy, _e66.z, vec2(5, 5)); + d = _e75; + let _e76 = coord_7; + let _e82 = coord_7; + let _e86 = vec3(_e82.x, _e82.y, 1.0); + let _e90 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e86.xy, _e86.z); + d = _e90; + let _e91 = coord_7; + let _e99 = coord_7; + let _e103 = vec3(_e99.x, _e99.y, 1.0); + let _e109 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e103.xy, _e103.z, vec2(5, 5)); + d = _e109; + let _e110 = coord_7; + let _e117 = coord_7; + let _e121 = vec3(_e117.x, _e117.y, 1.0); + let _e126 = textureSampleCompare(tex2DShadow, sampShadow, _e121.xy, _e121.z, vec2(5, 5)); + d = _e126; + let _e127 = coord_7; + let _e133 = coord_7; + let _e138 = vec4(_e133.x, _e133.y, 1.0, 6.0); + let _e142 = (_e138.xyz / vec3(_e138.w)); + let _e145 = textureSampleCompare(tex2DShadow, sampShadow, _e142.xy, _e142.z); + d = _e145; + let _e146 = coord_7; + let _e156 = coord_7; + let _e161 = vec4(_e156.x, _e156.y, 1.0, 6.0); + let _e169 = (_e161.xyz / vec3(_e161.w)); + let _e172 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e169.xy, _e169.z); + d = _e172; let _e173 = coord_7; - let _e176 = vec4(_e173, 1.0, 6.0); - let _e181 = (_e176.xyz / vec3(_e176.w)); - let _e184 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e181.xy, _e181.z); - d = _e184; let _e185 = coord_7; - let _e192 = coord_7; - let _e195 = vec4(_e192, 1.0, 6.0); - let _e202 = (_e195.xyz / vec3(_e195.w)); - let _e205 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e202.xy, _e202.z, vec2(5, 5)); - d = _e205; - let _e206 = coord_7; - let _e212 = coord_7; - let _e215 = vec4(_e212, 1.0, 6.0); - let _e221 = (_e215.xyz / vec3(_e215.w)); - let _e224 = textureSampleCompare(tex2DShadow, sampShadow, _e221.xy, _e221.z, vec2(5, 5)); + let _e190 = vec4(_e185.x, _e185.y, 1.0, 6.0); + let _e200 = (_e190.xyz / vec3(_e190.w)); + let _e203 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e200.xy, _e200.z, vec2(5, 5)); + d = _e203; + let _e204 = coord_7; + let _e211 = coord_7; + let _e216 = vec4(_e211.x, _e211.y, 1.0, 6.0); + let _e221 = (_e216.xyz / vec3(_e216.w)); + let _e224 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e221.xy, _e221.z); d = _e224; + let _e225 = coord_7; + let _e234 = coord_7; + let _e239 = vec4(_e234.x, _e234.y, 1.0, 6.0); + let _e246 = (_e239.xyz / vec3(_e239.w)); + let _e249 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e246.xy, _e246.z, vec2(5, 5)); + d = _e249; + let _e250 = coord_7; + let _e258 = coord_7; + let _e263 = vec4(_e258.x, _e258.y, 1.0, 6.0); + let _e269 = (_e263.xyz / vec3(_e263.w)); + let _e272 = textureSampleCompare(tex2DShadow, sampShadow, _e269.xy, _e269.z, vec2(5, 5)); + d = _e272; return; } @@ -396,35 +396,35 @@ fn testTex2DArrayShadow(coord_10: vec3) { coord_11 = coord_10; let _e17 = coord_11; - let _e20 = coord_11; - let _e22 = vec4(_e20, 1.0); - let _e27 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e22.xy, i32(_e22.z), _e22.w); - d_1 = _e27; - let _e28 = coord_11; - let _e35 = coord_11; - let _e37 = vec4(_e35, 1.0); - let _e46 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e37.xy, i32(_e37.z), _e37.w); - d_1 = _e46; - let _e47 = coord_11; - let _e56 = coord_11; - let _e58 = vec4(_e56, 1.0); - let _e69 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e58.xy, i32(_e58.z), _e58.w, vec2(5, 5)); - d_1 = _e69; - let _e70 = coord_11; - let _e74 = coord_11; - let _e76 = vec4(_e74, 1.0); - let _e82 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e76.xy, i32(_e76.z), _e76.w); - d_1 = _e82; - let _e83 = coord_11; - let _e89 = coord_11; - let _e91 = vec4(_e89, 1.0); - let _e99 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e91.xy, i32(_e91.z), _e91.w, vec2(5, 5)); - d_1 = _e99; - let _e100 = coord_11; - let _e105 = coord_11; - let _e107 = vec4(_e105, 1.0); - let _e114 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e107.xy, i32(_e107.z), _e107.w, vec2(5, 5)); - d_1 = _e114; + let _e23 = coord_11; + let _e28 = vec4(_e23.x, _e23.y, _e23.z, 1.0); + let _e33 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e28.xy, i32(_e28.z), _e28.w); + d_1 = _e33; + let _e34 = coord_11; + let _e44 = coord_11; + let _e49 = vec4(_e44.x, _e44.y, _e44.z, 1.0); + let _e58 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e49.xy, i32(_e49.z), _e49.w); + d_1 = _e58; + let _e59 = coord_11; + let _e71 = coord_11; + let _e76 = vec4(_e71.x, _e71.y, _e71.z, 1.0); + let _e87 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e76.xy, i32(_e76.z), _e76.w, vec2(5, 5)); + d_1 = _e87; + let _e88 = coord_11; + let _e95 = coord_11; + let _e100 = vec4(_e95.x, _e95.y, _e95.z, 1.0); + let _e106 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e100.xy, i32(_e100.z), _e100.w); + d_1 = _e106; + let _e107 = coord_11; + let _e116 = coord_11; + let _e121 = vec4(_e116.x, _e116.y, _e116.z, 1.0); + let _e129 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e121.xy, i32(_e121.z), _e121.w, vec2(5, 5)); + d_1 = _e129; + let _e130 = coord_11; + let _e138 = coord_11; + let _e143 = vec4(_e138.x, _e138.y, _e138.z, 1.0); + let _e150 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e143.xy, i32(_e143.z), _e143.w, vec2(5, 5)); + d_1 = _e150; return; } @@ -463,30 +463,30 @@ fn testTexCubeShadow(coord_14: vec3) { coord_15 = coord_14; let _e17 = coord_15; - let _e20 = coord_15; - let _e22 = vec4(_e20, 1.0); - let _e25 = textureSampleCompare(texCubeShadow, sampShadow, _e22.xyz, _e22.w); - d_2 = _e25; - let _e26 = coord_15; - let _e33 = coord_15; - let _e35 = vec4(_e33, 1.0); - let _e42 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e35.xyz, _e35.w); - d_2 = _e42; - let _e43 = coord_15; - let _e47 = coord_15; - let _e49 = vec4(_e47, 1.0); - let _e53 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e49.xyz, _e49.w); - d_2 = _e53; - let _e54 = coord_15; - let _e60 = coord_15; - let _e62 = vec4(_e60, 1.0); - let _e68 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e62.xyz, _e62.w, vec3(5, 5, 5)); - d_2 = _e68; - let _e69 = coord_15; - let _e74 = coord_15; - let _e76 = vec4(_e74, 1.0); - let _e81 = textureSampleCompare(texCubeShadow, sampShadow, _e76.xyz, _e76.w, vec3(5, 5, 5)); - d_2 = _e81; + let _e23 = coord_15; + let _e28 = vec4(_e23.x, _e23.y, _e23.z, 1.0); + let _e31 = textureSampleCompare(texCubeShadow, sampShadow, _e28.xyz, _e28.w); + d_2 = _e31; + let _e32 = coord_15; + let _e42 = coord_15; + let _e47 = vec4(_e42.x, _e42.y, _e42.z, 1.0); + let _e54 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e47.xyz, _e47.w); + d_2 = _e54; + let _e55 = coord_15; + let _e62 = coord_15; + let _e67 = vec4(_e62.x, _e62.y, _e62.z, 1.0); + let _e71 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e67.xyz, _e67.w); + d_2 = _e71; + let _e72 = coord_15; + let _e81 = coord_15; + let _e86 = vec4(_e81.x, _e81.y, _e81.z, 1.0); + let _e92 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e86.xyz, _e86.w, vec3(5, 5, 5)); + d_2 = _e92; + let _e93 = coord_15; + let _e101 = coord_15; + let _e106 = vec4(_e101.x, _e101.y, _e101.z, 1.0); + let _e111 = textureSampleCompare(texCubeShadow, sampShadow, _e106.xyz, _e106.w, vec3(5, 5, 5)); + d_2 = _e111; return; } From 6fbd668bd3c41e5093706b758c8dba7614511cd7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 2 Dec 2021 13:07:51 -0500 Subject: [PATCH 1464/2212] Add missing GLSL tests --- .../glsl/interpolate.frag_main.Fragment.glsl | 25 +++++++++++ .../glsl/interpolate.vert_main.Vertex.glsl | 42 +++++++++++++++++++ tests/out/glsl/quad.frag_main.Fragment.glsl | 26 ++++++++++++ tests/out/glsl/quad.vert_main.Vertex.glsl | 23 ++++++++++ 4 files changed, 116 insertions(+) create mode 100644 tests/out/glsl/interpolate.frag_main.Fragment.glsl create mode 100644 tests/out/glsl/interpolate.vert_main.Vertex.glsl create mode 100644 tests/out/glsl/quad.frag_main.Fragment.glsl create mode 100644 tests/out/glsl/quad.vert_main.Vertex.glsl diff --git a/tests/out/glsl/interpolate.frag_main.Fragment.glsl b/tests/out/glsl/interpolate.frag_main.Fragment.glsl new file mode 100644 index 000000000..918e78b9c --- /dev/null +++ b/tests/out/glsl/interpolate.frag_main.Fragment.glsl @@ -0,0 +1,25 @@ +#version 400 core +struct FragmentInput { + vec4 position; + uint flat_; + float linear; + vec2 linear_centroid; + vec3 linear_sample; + vec4 perspective; + float perspective_centroid; + float perspective_sample; +}; + +flat in uint _vs2fs_location0; +noperspective in float _vs2fs_location1; +noperspective centroid in vec2 _vs2fs_location2; +noperspective sample in vec3 _vs2fs_location3; +smooth in vec4 _vs2fs_location4; +smooth centroid in float _vs2fs_location5; +smooth sample in float _vs2fs_location6; + +void main() { + FragmentInput val = FragmentInput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1, _vs2fs_location2, _vs2fs_location3, _vs2fs_location4, _vs2fs_location5, _vs2fs_location6); + return; +} + diff --git a/tests/out/glsl/interpolate.vert_main.Vertex.glsl b/tests/out/glsl/interpolate.vert_main.Vertex.glsl new file mode 100644 index 000000000..40d64ccf0 --- /dev/null +++ b/tests/out/glsl/interpolate.vert_main.Vertex.glsl @@ -0,0 +1,42 @@ +#version 400 core +struct FragmentInput { + vec4 position; + uint flat_; + float linear; + vec2 linear_centroid; + vec3 linear_sample; + vec4 perspective; + float perspective_centroid; + float perspective_sample; +}; + +flat out uint _vs2fs_location0; +noperspective out float _vs2fs_location1; +noperspective centroid out vec2 _vs2fs_location2; +noperspective sample out vec3 _vs2fs_location3; +smooth out vec4 _vs2fs_location4; +smooth centroid out float _vs2fs_location5; +smooth sample out float _vs2fs_location6; + +void main() { + FragmentInput out_; + out_.position = vec4(2.0, 4.0, 5.0, 6.0); + out_.flat_ = 8u; + out_.linear = 27.0; + out_.linear_centroid = vec2(64.0, 125.0); + out_.linear_sample = vec3(216.0, 343.0, 512.0); + out_.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + out_.perspective_centroid = 2197.0; + out_.perspective_sample = 2744.0; + FragmentInput _e30 = out_; + gl_Position = _e30.position; + _vs2fs_location0 = _e30.flat_; + _vs2fs_location1 = _e30.linear; + _vs2fs_location2 = _e30.linear_centroid; + _vs2fs_location3 = _e30.linear_sample; + _vs2fs_location4 = _e30.perspective; + _vs2fs_location5 = _e30.perspective_centroid; + _vs2fs_location6 = _e30.perspective_sample; + return; +} + diff --git a/tests/out/glsl/quad.frag_main.Fragment.glsl b/tests/out/glsl/quad.frag_main.Fragment.glsl new file mode 100644 index 000000000..b290ed5a0 --- /dev/null +++ b/tests/out/glsl/quad.frag_main.Fragment.glsl @@ -0,0 +1,26 @@ +#version 300 es + +precision highp float; +precision highp int; + +struct VertexOutput { + vec2 uv; + vec4 position; +}; + +uniform highp sampler2D _group_0_binding_0; + +smooth in vec2 _vs2fs_location0; +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + vec2 uv_1 = _vs2fs_location0; + vec4 color = texture(_group_0_binding_0, vec2(uv_1)); + if ((color.w == 0.0)) { + discard; + } + vec4 premultiplied = (color.w * color); + _fs2p_location0 = premultiplied; + return; +} + diff --git a/tests/out/glsl/quad.vert_main.Vertex.glsl b/tests/out/glsl/quad.vert_main.Vertex.glsl new file mode 100644 index 000000000..cda43f508 --- /dev/null +++ b/tests/out/glsl/quad.vert_main.Vertex.glsl @@ -0,0 +1,23 @@ +#version 300 es + +precision highp float; +precision highp int; + +struct VertexOutput { + vec2 uv; + vec4 position; +}; + +layout(location = 0) in vec2 _p2vs_location0; +layout(location = 1) in vec2 _p2vs_location1; +smooth out vec2 _vs2fs_location0; + +void main() { + vec2 pos = _p2vs_location0; + vec2 uv = _p2vs_location1; + VertexOutput _tmp_return = VertexOutput(uv, vec4((1.2000000476837158 * pos), 0.0, 1.0)); + _vs2fs_location0 = _tmp_return.uv; + gl_Position = _tmp_return.position; + return; +} + From c69f67660973a3bffa3b27c295f698dc4aa01524 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 4 Dec 2021 12:13:53 -0500 Subject: [PATCH 1465/2212] glsl: reflect textures without samplers --- src/back/glsl/mod.rs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c29bd174b..53f376a66 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2718,13 +2718,13 @@ impl<'a, W: Write> Writer<'a, W> { fn collect_reflection_info(&self) -> Result { use std::collections::hash_map::Entry; let info = self.info.get_entry_point(self.entry_point_idx as usize); - let mut mappings = crate::FastHashMap::default(); + let mut texture_mapping = crate::FastHashMap::default(); let mut uniforms = crate::FastHashMap::default(); for sampling in info.sampling_set.iter() { let tex_name = self.reflection_names_globals[&sampling.image].clone(); - match mappings.entry(tex_name) { + match texture_mapping.entry(tex_name) { Entry::Vacant(v) => { v.insert(TextureMapping { texture: sampling.image, @@ -2752,12 +2752,26 @@ impl<'a, W: Write> Writer<'a, W> { } _ => (), }, - _ => continue, + crate::TypeInner::Image { .. } => { + let tex_name = self.reflection_names_globals[&handle].clone(); + match texture_mapping.entry(tex_name) { + Entry::Vacant(v) => { + v.insert(TextureMapping { + texture: handle, + sampler: None, + }); + } + Entry::Occupied(_) => { + // already used with a sampler, do nothing + } + } + } + _ => {} } } Ok(ReflectionInfo { - texture_mapping: mappings, + texture_mapping, uniforms, }) } From 14719553a67a192af2035450461420af9cce4530 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 4 Dec 2021 21:54:55 +0000 Subject: [PATCH 1466/2212] glsl-in: fix pre/postfix ops on swizzles --- src/front/glsl/context.rs | 134 +++++++++++++------------ tests/in/glsl/swizzle_write.frag | 1 + tests/out/wgsl/swizzle_write-frag.wgsl | 4 + 3 files changed, 77 insertions(+), 62 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index dd2f73874..fa29b5ceb 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -418,6 +418,69 @@ impl Context { Ok((expr, meta)) } + fn lower_store( + &mut self, + pointer: Handle, + value: Handle, + meta: Span, + body: &mut Block, + ) { + if let Expression::Swizzle { + size, + mut vector, + pattern, + } = self.expressions[pointer] + { + // Stores to swizzled values are not directly supported, + // lower them as series of per-component stores. + let size = match size { + VectorSize::Bi => 2, + VectorSize::Tri => 3, + VectorSize::Quad => 4, + }; + + if let Expression::Load { pointer } = self.expressions[vector] { + vector = pointer; + } + + #[allow(clippy::needless_range_loop)] + for index in 0..size { + let dst = self.add_expression( + Expression::AccessIndex { + base: vector, + index: pattern[index].index(), + }, + meta, + body, + ); + let src = self.add_expression( + Expression::AccessIndex { + base: value, + index: index as u32, + }, + meta, + body, + ); + + self.emit_flush(body); + self.emit_start(); + + body.push( + Statement::Store { + pointer: dst, + value: src, + }, + meta, + ); + } + } else { + self.emit_flush(body); + self.emit_start(); + + body.push(Statement::Store { pointer, value }, meta); + } + } + /// Internal implementation of [`lower`](Self::lower) fn lower_inner( &mut self, @@ -694,68 +757,18 @@ impl Context { self.implicit_conversion(parser, &mut value, value_meta, kind, width)?; } - if let Expression::Swizzle { - size, - mut vector, - pattern, - } = self.expressions[pointer] - { - // Stores to swizzled values are not directly supported, - // lower them as series of per-component stores. - let size = match size { - VectorSize::Bi => 2, - VectorSize::Tri => 3, - VectorSize::Quad => 4, - }; - - if let Expression::Load { pointer } = self.expressions[vector] { - vector = pointer; - } - - #[allow(clippy::needless_range_loop)] - for index in 0..size { - let dst = self.add_expression( - Expression::AccessIndex { - base: vector, - index: pattern[index].index(), - }, - meta, - body, - ); - let src = self.add_expression( - Expression::AccessIndex { - base: value, - index: index as u32, - }, - meta, - body, - ); - - self.emit_flush(body); - self.emit_start(); - - body.push( - Statement::Store { - pointer: dst, - value: src, - }, - meta, - ); - } - } else { - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { pointer, value }, meta); - } + self.lower_store(pointer, value, meta, body); value } HirExprKind::PrePostfix { op, postfix, expr } if ExprPos::Lhs != pos => { - let pointer = self - .lower_expect_inner(stmt, parser, expr, ExprPos::Lhs, body)? - .0; - let left = self.add_expression(Expression::Load { pointer }, meta, body); + let (pointer, _) = + self.lower_expect_inner(stmt, parser, expr, ExprPos::Lhs, body)?; + let left = if let Expression::Swizzle { .. } = self.expressions[pointer] { + pointer + } else { + self.add_expression(Expression::Load { pointer }, meta, body) + }; let make_constant_inner = |kind, width| { let value = match kind { @@ -844,10 +857,7 @@ impl Context { let value = self.add_expression(Expression::Binary { op, left, right }, meta, body); - self.emit_flush(body); - self.emit_start(); - - body.push(Statement::Store { pointer, value }, meta); + self.lower_store(pointer, value, meta, body); if postfix { left diff --git a/tests/in/glsl/swizzle_write.frag b/tests/in/glsl/swizzle_write.frag index 9f11d7e5f..a554c94e1 100644 --- a/tests/in/glsl/swizzle_write.frag +++ b/tests/in/glsl/swizzle_write.frag @@ -5,4 +5,5 @@ void main() { vec3 x = vec3(2.0); x.zxy.xy = vec2(3.0, 4.0); x.rg *= 5.0; + x.zy++; } diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index 81888740a..48ca0a199 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -10,6 +10,10 @@ fn main_1() { let _e18 = (_e15.xy * 5.0); x.x = _e18.x; x.y = _e18.y; + let _e23 = x; + let _e27 = (_e23.zy + vec2(1.0)); + x.z = _e27.x; + x.y = _e27.y; return; } From 9cc2b730b7665faa7352547ed553e5d9828ea23f Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 6 Dec 2021 14:56:41 +0300 Subject: [PATCH 1467/2212] [glsl-out] Add note about supported GLSL versions --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b90bd9ee8..b1f23f3d1 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ SPIR-V | :white_check_mark: | spv-out | | WGSL | :ok: | wgsl-out | | Metal | :white_check_mark: | msl-out | | HLSL | :ok: | hlsl-out | Shader Model 5.0+ (DirectX 11+) | -GLSL | :ok: | glsl-out | | +GLSL | :ok: | glsl-out | GLSL 330+ and GLSL ES 300+ | AIR | | | | DXIL/DXIR | | | | DXBC | | | | From 6912cb35947c3b15d7a928b5e45daba2c3d7eeec Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 1 Oct 2021 10:01:02 -0700 Subject: [PATCH 1468/2212] [spv-out] Move ExpressionPointer to back::spv::block, remove pub. --- src/back/spv/block.rs | 26 +++++++++++++++++++++----- src/back/spv/index.rs | 19 ------------------- 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 10e416cf1..ea5bed85e 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1,11 +1,8 @@ //! Implementations for `BlockContext` methods. use super::{ - index::{BoundsCheckResult, ExpressionPointer}, - make_local, - selection::Selection, - Block, BlockContext, Dimension, Error, Instruction, LocalType, LookupType, LoopContext, - ResultMember, Writer, WriterFlags, + index::BoundsCheckResult, make_local, selection::Selection, Block, BlockContext, Dimension, + Error, Instruction, LocalType, LookupType, LoopContext, ResultMember, Writer, WriterFlags, }; use crate::{arena::Handle, proc::TypeResolution}; use spirv::Word; @@ -19,6 +16,25 @@ fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { } } +/// The results of emitting code for a left-hand-side expression. +/// +/// On success, `write_expression_pointer` returns one of these. +enum ExpressionPointer { + /// The pointer to the expression's value is available, as the value of the + /// expression with the given id. + Ready { pointer_id: Word }, + + /// The access expression must be conditional on the value of `condition`, a boolean + /// expression that is true if all indices are in bounds. If `condition` is true, then + /// `access` is an `OpAccessChain` instruction that will compute a pointer to the + /// expression's value. If `condition` is false, then executing `access` would be + /// undefined behavior. + Conditional { + condition: Word, + access: Instruction, + }, +} + impl Writer { // Flip Y coordinate to adjust for coordinate space difference // between SPIR-V and our IR. diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index f6b92b1d0..4192d3848 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -3,25 +3,6 @@ use super::{selection::Selection, Block, BlockContext, Error, IdGenerator, Instruction, Word}; use crate::{arena::Handle, proc::BoundsCheckPolicy}; -/// The results of emitting code for a left-hand-side expression. -/// -/// On success, `write_expression_pointer` returns one of these. -pub(super) enum ExpressionPointer { - /// The pointer to the expression's value is available, as the value of the - /// expression with the given id. - Ready { pointer_id: Word }, - - /// The access expression must be conditional on the value of `condition`, a boolean - /// expression that is true if all indices are in bounds. If `condition` is true, then - /// `access` is an `OpAccessChain` instruction that will compute a pointer to the - /// expression's value. If `condition` is false, then executing `access` would be - /// undefined behavior. - Conditional { - condition: Word, - access: Instruction, - }, -} - /// The results of performing a bounds check. /// /// On success, `write_bounds_check` returns a value of this type. From 89cc21ef43269f7319b21f895589897ef2f38ec5 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 1 Oct 2021 13:58:51 -0700 Subject: [PATCH 1469/2212] [spv-out] BlockContext::write_expression_pointer doc fix. --- src/back/spv/block.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index ea5bed85e..89f893a31 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -989,7 +989,7 @@ impl<'w> BlockContext<'w> { Ok(()) } - /// Build an `OpAccessChain` instruction for a left-hand-side expression. + /// Build an `OpAccessChain` instruction. /// /// Emit any needed bounds-checking expressions to `block`. /// From 840bbaffcce8b428b53a7260ed83f43dfcb04104 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 1 Oct 2021 10:07:31 -0700 Subject: [PATCH 1470/2212] [msl-out] Rename `put_dynamic_array_length`, make it take a global. --- src/back/msl/writer.rs | 99 ++++++++++++++++++++++++------------------ 1 file changed, 56 insertions(+), 43 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8b29ab2c9..2ce15e333 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -671,55 +671,57 @@ impl Writer { Ok(()) } - fn put_array_length( + /// Write the length of the dynamically sized array at the end of `handle`. + /// + /// `expr` must be the handle of a global variable whose final member is a dynamically + /// sized array. + fn put_dynamic_array_length( &mut self, - expr: Handle, + handle: Handle, context: &ExpressionContext, ) -> BackendResult { - let handle = match context.function.expressions[expr] { - crate::Expression::AccessIndex { base, .. } => { - match context.function.expressions[base] { - crate::Expression::GlobalVariable(handle) => handle, - _ => return Err(Error::Validation), - } - } + let global = &context.module.global_variables[handle]; + let members = match context.module.types[global.ty].inner { + crate::TypeInner::Struct { ref members, .. } => members, _ => return Err(Error::Validation), }; - let global = &context.module.global_variables[handle]; - if let crate::TypeInner::Struct { ref members, .. } = context.module.types[global.ty].inner - { - if let Some(&crate::StructMember { - offset, - ty: array_ty, - .. - }) = members.last() - { - let (span, stride) = match context.module.types[array_ty].inner { - crate::TypeInner::Array { base, stride, .. } => ( - context.module.types[base] - .inner - .span(&context.module.constants), - stride, - ), - _ => return Err(Error::Validation), - }; + let (offset, array_ty) = match members.last() { + Some(&crate::StructMember { offset, ty, .. }) => (offset, ty), + None => return Err(Error::Validation), + }; - write!( - self.out, - "(1 + (_buffer_sizes.size{idx} - {offset} - {span}) / {stride})", - idx = handle.index(), - offset = offset, - span = span, - stride = stride, - )?; - Ok(()) - } else { - Err(Error::Validation) - } - } else { - Err(Error::Validation) - } + let (span, stride) = match context.module.types[array_ty].inner { + crate::TypeInner::Array { base, stride, .. } => ( + context.module.types[base] + .inner + .span(&context.module.constants), + stride, + ), + _ => return Err(Error::Validation), + }; + + // When the stride length is larger than the span, the final element's stride of + // bytes would have padding following the value. But the buffer size in + // `buffer_sizes.sizeN` may not include this padding - it only needs to be large + // enough to hold the actual values' bytes. + // + // So subtract off the span to get a byte size that falls at the start or within + // the final element. Then divide by the stride size, to get one less than the + // length, and then add one. This works even if the buffer size does include the + // stride padding, since division rounds towards zero (MSL 2.4 §6.1). It will fail + // if there are zero elements in the array, but the WebGPU `validating shader binding` + // rules, together with draw-time validation when `minBindingSize` is zero, + // prevent that. + write!( + self.out, + "(1 + (_buffer_sizes.size{idx} - {offset} - {span}) / {stride})", + idx = handle.index(), + offset = offset, + span = span, + stride = stride, + )?; + Ok(()) } fn put_atomic_fetch( @@ -1265,7 +1267,18 @@ impl Writer { unreachable!() } crate::Expression::ArrayLength(expr) => { - self.put_array_length(expr, context)?; + // Find the global to which the array belongs. + let global = match context.function.expressions[expr] { + crate::Expression::AccessIndex { base, .. } => { + match context.function.expressions[base] { + crate::Expression::GlobalVariable(handle) => handle, + _ => return Err(Error::Validation), + } + } + _ => return Err(Error::Validation), + }; + + self.put_dynamic_array_length(global, context)?; } } Ok(()) From 17398e761fde304d1d0d8d48af2ee1327af0f3d1 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 1 Nov 2021 12:51:44 -0700 Subject: [PATCH 1471/2212] [msl-out] Move `Expression::Load` handling into its own function. No changes in behavior. --- src/back/msl/writer.rs | 118 ++++++++++++++++++++--------------------- 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 2ce15e333..7f7f569de 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -882,65 +882,7 @@ impl Writer { let name = &self.names[&name_key]; write!(self.out, "{}", name)?; } - crate::Expression::Load { pointer } => { - // Because packed vectors such as `packed_float3` cannot be directly multipied by - // matrices, we wrap them with `float3` on load. - let wrap_packed_vec_scalar_kind = match context.function.expressions[pointer] { - crate::Expression::AccessIndex { base, index } => { - let ty = match *context.resolve_type(base) { - crate::TypeInner::Pointer { base, .. } => { - &context.module.types[base].inner - } - ref ty => ty, - }; - match *ty { - crate::TypeInner::Struct { - ref members, span, .. - } => should_pack_struct_member( - members, - span, - index as usize, - context.module, - ), - _ => None, - } - } - _ => None, - }; - let is_atomic = match *context.resolve_type(pointer) { - crate::TypeInner::Pointer { base, .. } => { - match context.module.types[base].inner { - crate::TypeInner::Atomic { .. } => true, - _ => false, - } - } - _ => false, - }; - - if let Some(scalar_kind) = wrap_packed_vec_scalar_kind { - write!( - self.out, - "{}::{}3(", - NAMESPACE, - scalar_kind_string(scalar_kind) - )?; - self.put_expression(pointer, context, true)?; - write!(self.out, ")")?; - } else if is_atomic { - write!( - self.out, - "{}::atomic_load_explicit({}", - NAMESPACE, ATOMIC_REFERENCE - )?; - self.put_expression(pointer, context, true)?; - write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; - } else { - // We don't do any dereferencing with `*` here as pointer arguments to functions - // are done by `&` references and not `*` pointers. These do not need to be - // dereferenced. - self.put_expression(pointer, context, is_scoped)?; - } - } + crate::Expression::Load { pointer } => self.put_load(pointer, context, is_scoped)?, crate::Expression::ImageSample { image, sampler, @@ -1284,6 +1226,64 @@ impl Writer { Ok(()) } + fn put_load( + &mut self, + pointer: Handle, + context: &ExpressionContext, + is_scoped: bool, + ) -> BackendResult { + // Because packed vectors such as `packed_float3` cannot be directly multipied by + // matrices, we wrap them with `float3` on load. + let wrap_packed_vec_scalar_kind = match context.function.expressions[pointer] { + crate::Expression::AccessIndex { base, index } => { + let ty = match *context.resolve_type(base) { + crate::TypeInner::Pointer { base, .. } => &context.module.types[base].inner, + ref ty => ty, + }; + match *ty { + crate::TypeInner::Struct { + ref members, span, .. + } => should_pack_struct_member(members, span, index as usize, context.module), + _ => None, + } + } + _ => None, + }; + let is_atomic = match *context.resolve_type(pointer) { + crate::TypeInner::Pointer { base, .. } => match context.module.types[base].inner { + crate::TypeInner::Atomic { .. } => true, + _ => false, + }, + _ => false, + }; + + if let Some(scalar_kind) = wrap_packed_vec_scalar_kind { + write!( + self.out, + "{}::{}3(", + NAMESPACE, + scalar_kind_string(scalar_kind) + )?; + self.put_expression(pointer, context, true)?; + write!(self.out, ")")?; + } else if is_atomic { + write!( + self.out, + "{}::atomic_load_explicit({}", + NAMESPACE, ATOMIC_REFERENCE + )?; + self.put_expression(pointer, context, true)?; + write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; + } else { + // We don't do any dereferencing with `*` here as pointer arguments to functions + // are done by `&` references and not `*` pointers. These do not need to be + // dereferenced. + self.put_expression(pointer, context, is_scoped)?; + } + + Ok(()) + } + fn put_return_value( &mut self, level: back::Level, From 61e3af2989d272ba61e6925a972727ea4f2aa034 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 1 Nov 2021 17:07:25 -0700 Subject: [PATCH 1472/2212] [msl-out] Move `Statement::Store` handling into its own function. --- src/back/msl/writer.rs | 98 ++++++++++++++++++++++++------------------ 1 file changed, 55 insertions(+), 43 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7f7f569de..df8f388aa 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1587,49 +1587,7 @@ impl Writer { } } crate::Statement::Store { pointer, value } => { - let pointer_info = &context.expression.info[pointer]; - let (array_size, is_atomic) = - match *pointer_info.ty.inner_with(&context.expression.module.types) { - crate::TypeInner::Pointer { base, .. } => { - match context.expression.module.types[base].inner { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(ch), - .. - } => (Some(ch), false), - crate::TypeInner::Atomic { .. } => (None, true), - _ => (None, false), - } - } - _ => (None, false), - }; - - // we can't assign fixed-size arrays - if let Some(const_handle) = array_size { - let size = context.expression.module.constants[const_handle] - .to_array_length() - .unwrap(); - write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?; - self.put_expression(pointer, &context.expression, true)?; - write!(self.out, ".{}[_i] = ", WRAPPED_ARRAY_FIELD)?; - self.put_expression(value, &context.expression, true)?; - writeln!(self.out, ".{}[_i];", WRAPPED_ARRAY_FIELD)?; - } else if is_atomic { - write!( - self.out, - "{}{}::atomic_store_explicit({}", - level, NAMESPACE, ATOMIC_REFERENCE - )?; - self.put_expression(pointer, &context.expression, true)?; - write!(self.out, ", ")?; - self.put_expression(value, &context.expression, true)?; - writeln!(self.out, ", {}::memory_order_relaxed);", NAMESPACE)?; - } else { - write!(self.out, "{}", level)?; - self.put_expression(pointer, &context.expression, true)?; - write!(self.out, " = ")?; - self.put_expression(value, &context.expression, true)?; - writeln!(self.out, ";")?; - } + self.put_store(pointer, value, level, context)? } crate::Statement::ImageStore { image, @@ -1766,6 +1724,60 @@ impl Writer { Ok(()) } + fn put_store( + &mut self, + pointer: Handle, + value: Handle, + level: back::Level, + context: &StatementContext, + ) -> BackendResult { + let pointer_info = &context.expression.info[pointer]; + let (array_size, is_atomic) = + match *pointer_info.ty.inner_with(&context.expression.module.types) { + crate::TypeInner::Pointer { base, .. } => { + match context.expression.module.types[base].inner { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(ch), + .. + } => (Some(ch), false), + crate::TypeInner::Atomic { .. } => (None, true), + _ => (None, false), + } + } + _ => (None, false), + }; + + // we can't assign fixed-size arrays + if let Some(const_handle) = array_size { + let size = context.expression.module.constants[const_handle] + .to_array_length() + .unwrap(); + write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?; + self.put_expression(pointer, &context.expression, true)?; + write!(self.out, ".{}[_i] = ", WRAPPED_ARRAY_FIELD)?; + self.put_expression(value, &context.expression, true)?; + writeln!(self.out, ".{}[_i];", WRAPPED_ARRAY_FIELD)?; + } else if is_atomic { + write!( + self.out, + "{}{}::atomic_store_explicit({}", + level, NAMESPACE, ATOMIC_REFERENCE + )?; + self.put_expression(pointer, &context.expression, true)?; + write!(self.out, ", ")?; + self.put_expression(value, &context.expression, true)?; + writeln!(self.out, ", {}::memory_order_relaxed);", NAMESPACE)?; + } else { + write!(self.out, "{}", level)?; + self.put_expression(pointer, &context.expression, true)?; + write!(self.out, " = ")?; + self.put_expression(value, &context.expression, true)?; + writeln!(self.out, ";")?; + } + + Ok(()) + } + pub fn write( &mut self, module: &crate::Module, From e8f564dc834f69bd64beee650ca9b805772d418b Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 13 Nov 2021 13:58:45 -0800 Subject: [PATCH 1473/2212] [spv-out] Add comment about AccessIndex on non-pointer values. --- src/back/spv/block.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 89f893a31..eaa4b7990 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -226,6 +226,10 @@ impl<'w> BlockContext<'w> { | crate::TypeInner::Matrix { .. } | crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { + // We never need bounds checks here: dynamically sized arrays can + // only appear behind pointers, and are thus handled by the + // `is_intermediate` case above. Everything else's size is + // statically known and checked in validation. let id = self.gen_id(); let base_id = self.cached[base]; block.body.push(Instruction::composite_extract( From f51f468a47312608e8f4fc59c8f1e65ce37012de Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 19 Oct 2021 09:37:59 -0700 Subject: [PATCH 1474/2212] [msl-out] Implement index bounds check policies for non-texture accesses. --- cli/src/main.rs | 5 +- src/back/msl/mod.rs | 6 +- src/back/msl/writer.rs | 515 ++++++++++++++++++--- src/proc/index.rs | 185 +++++++- src/proc/mod.rs | 29 +- tests/in/bounds-check-restrict.param.ron | 6 + tests/in/bounds-check-restrict.wgsl | 73 +++ tests/in/bounds-check-zero.wgsl | 27 ++ tests/out/msl/bounds-check-restrict.msl | 163 +++++++ tests/out/msl/bounds-check-zero.msl | 177 +++++++ tests/out/msl/policy-mix.msl | 46 ++ tests/out/spv/bounds-check-restrict.spvasm | 238 ++++++++++ tests/out/spv/bounds-check-zero.spvasm | 462 +++++++++++------- tests/snapshots.rs | 20 +- 14 files changed, 1683 insertions(+), 269 deletions(-) create mode 100644 tests/in/bounds-check-restrict.param.ron create mode 100644 tests/in/bounds-check-restrict.wgsl create mode 100644 tests/out/msl/bounds-check-restrict.msl create mode 100644 tests/out/msl/bounds-check-zero.msl create mode 100644 tests/out/msl/policy-mix.msl create mode 100644 tests/out/spv/bounds-check-restrict.spvasm diff --git a/cli/src/main.rs b/cli/src/main.rs index 56306a501..b1a863ca2 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -335,6 +335,9 @@ fn run() -> Result<(), Box> { "metal" => { use naga::back::msl; + let mut options = params.msl.clone(); + options.bounds_check_policies = params.bounds_check_policies; + let pipeline_options = msl::PipelineOptions::default(); let (msl, _) = msl::write_string( &module, @@ -342,7 +345,7 @@ fn run() -> Result<(), Box> { "Generating metal output requires validation to \ succeed, and it failed in a previous step", ))?, - ¶ms.msl, + &options, &pipeline_options, ) .unwrap_pretty(); diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index ca7b9682c..4295ae0e9 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -23,7 +23,7 @@ For the result type, if it's a structure, we re-compose it with a temporary valu holding the result. !*/ -use crate::{arena::Handle, valid::ModuleInfo}; +use crate::{arena::Handle, proc::index, valid::ModuleInfo}; use std::{ fmt::{Error as FmtError, Write}, ops, @@ -177,6 +177,9 @@ pub struct Options { pub spirv_cross_compatibility: bool, /// Don't panic on missing bindings, instead generate invalid MSL. pub fake_missing_bindings: bool, + /// Bounds checking policies. + #[cfg_attr(feature = "deserialize", serde(default))] + pub bounds_check_policies: index::BoundsCheckPolicies, } impl Default for Options { @@ -187,6 +190,7 @@ impl Default for Options { inline_samplers: Vec::new(), spirv_cross_compatibility: false, fake_missing_bindings: true, + bounds_check_policies: index::BoundsCheckPolicies::default(), } } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index df8f388aa..ab50b1762 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2,9 +2,11 @@ use super::{sampler as sm, Error, LocationMode, Options, PipelineOptions, Transl use crate::{ arena::Handle, back, + proc::index, proc::{self, NameKey, TypeResolution}, valid, FastHashMap, FastHashSet, }; +use bit_set::BitSet; use std::{ fmt::{Display, Error as FmtError, Formatter, Write}, iter, @@ -450,12 +452,35 @@ struct ExpressionContext<'a> { info: &'a valid::FunctionInfo, module: &'a crate::Module, pipeline_options: &'a PipelineOptions, + policies: index::BoundsCheckPolicies, + + /// A bitset containing the `Expression` handle indexes of expressions used + /// as indices in `ReadZeroSkipWrite`-policy accesses. These may need to be + /// cached in temporary variables. See `index::find_checked_indexes` for + /// details. + guarded_indices: BitSet, } impl<'a> ExpressionContext<'a> { fn resolve_type(&self, handle: Handle) -> &'a crate::TypeInner { self.info[handle].ty.inner_with(&self.module.types) } + + fn choose_bounds_check_policy( + &self, + pointer: Handle, + ) -> index::BoundsCheckPolicy { + self.policies + .choose_policy(pointer, &self.module.types, self.info) + } + + fn access_needs_check( + &self, + base: Handle, + index: index::GuardedIndex, + ) -> Option { + index::access_needs_check(base, index, self.module, self.function, self.info) + } } struct StatementContext<'a> { @@ -671,11 +696,17 @@ impl Writer { Ok(()) } - /// Write the length of the dynamically sized array at the end of `handle`. + /// Write the maximum valid index of the dynamically sized array at the end of `handle`. /// - /// `expr` must be the handle of a global variable whose final member is a dynamically - /// sized array. - fn put_dynamic_array_length( + /// The 'maximum valid index' is simply one less than the array's length. + /// + /// This emits an expression of the form `a / b`, so the caller must + /// parenthesize its output if it will be applying operators of higher + /// precedence. + /// + /// `handle` must be the handle of a global variable whose final member is a + /// dynamically sized array. + fn put_dynamic_array_max_index( &mut self, handle: Handle, context: &ExpressionContext, @@ -715,7 +746,7 @@ impl Writer { // prevent that. write!( self.out, - "(1 + (_buffer_sizes.size{idx} - {offset} - {span}) / {stride})", + "(_buffer_sizes.size{idx} - {offset} - {span}) / {stride}", idx = handle.index(), offset = offset, span = span, @@ -743,6 +774,17 @@ impl Writer { Ok(()) } + /// Emit code for the expression `expr_handle`. + /// + /// The `is_scoped` argument is true if the surrounding operators have the + /// precedence of the comma operator, or lower. So, for example: + /// + /// - Pass `true` for `is_scoped` when writing function arguments, an + /// expression statement, an initializer expression, or anything already + /// wrapped in parenthesis. + /// + /// - Pass `false` if it is an operand of a `?:` operator, a `[]`, or really + /// almost anything else. fn put_expression( &mut self, expr_handle: Handle, @@ -763,62 +805,30 @@ impl Writer { let expression = &context.function.expressions[expr_handle]; log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { - crate::Expression::Access { base, index } => { - let accessing_wrapped_array = - match *context.info[base].ty.inner_with(&context.module.types) { - crate::TypeInner::Array { .. } => true, - crate::TypeInner::Pointer { - base: pointer_base, .. - } => match context.module.types[pointer_base].inner { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(_), - .. - } => true, - _ => false, - }, - _ => false, - }; + crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => { + // This is an acceptable place to generate a `ReadZeroSkipWrite` check. + // Since `put_bounds_checks` and `put_access_chain` handle an entire + // access chain at a time, recursing back through `put_expression` only + // for index expressions and the base object, we will never see intermediate + // `Access` or `AccessIndex` expressions here. + let policy = context.choose_bounds_check_policy(expr_handle); + if policy == index::BoundsCheckPolicy::ReadZeroSkipWrite + && self.put_bounds_checks( + expr_handle, + context, + back::Level(0), + if is_scoped { "" } else { "(" }, + )? + { + write!(self.out, " ? ")?; + self.put_access_chain(expr_handle, policy, context)?; + write!(self.out, " : 0")?; - self.put_expression(base, context, false)?; - if accessing_wrapped_array { - write!(self.out, ".{}", WRAPPED_ARRAY_FIELD)?; - } - write!(self.out, "[")?; - self.put_expression(index, context, true)?; - write!(self.out, "]")?; - } - crate::Expression::AccessIndex { base, index } => { - self.put_expression(base, context, false)?; - let base_res = &context.info[base].ty; - let mut resolved = base_res.inner_with(&context.module.types); - let base_ty_handle = match *resolved { - crate::TypeInner::Pointer { base, class: _ } => { - resolved = &context.module.types[base].inner; - Some(base) - } - _ => base_res.handle(), - }; - match *resolved { - crate::TypeInner::Struct { .. } => { - let base_ty = base_ty_handle.unwrap(); - let name = &self.names[&NameKey::StructMember(base_ty, index)]; - write!(self.out, ".{}", name)?; - } - crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => { - write!(self.out, ".{}", back::COMPONENTS[index as usize])?; - } - crate::TypeInner::Array { - size: crate::ArraySize::Constant(_), - .. - } => { - write!(self.out, ".{}[{}]", WRAPPED_ARRAY_FIELD, index)?; - } - crate::TypeInner::Array { .. } | crate::TypeInner::Matrix { .. } => { - write!(self.out, "[{}]", index)?; - } - _ => { - // unexpected indexing, should fail validation + if !is_scoped { + write!(self.out, ")")?; } + } else { + self.put_access_chain(expr_handle, policy, context)?; } } crate::Expression::Constant(handle) => { @@ -1220,20 +1230,325 @@ impl Writer { _ => return Err(Error::Validation), }; - self.put_dynamic_array_length(global, context)?; + if !is_scoped { + write!(self.out, "(")?; + } + write!(self.out, "1 + ")?; + self.put_dynamic_array_max_index(global, context)?; + if !is_scoped { + write!(self.out, ")")?; + } } } Ok(()) } + /// Write a `GuardedIndex` as a Metal expression. + fn put_index( + &mut self, + index: index::GuardedIndex, + context: &ExpressionContext, + is_scoped: bool, + ) -> BackendResult { + match index { + index::GuardedIndex::Expression(expr) => { + self.put_expression(expr, context, is_scoped)? + } + index::GuardedIndex::Known(value) => write!(self.out, "{}", value)?, + } + Ok(()) + } + + /// Emit an index bounds check condition for `chain`, if required. + /// + /// `chain` is a subtree of `Access` and `AccessIndex` expressions, + /// operating either on a pointer to a value, or on a value directly. If we cannot + /// statically determine that all indexing operations in `chain` are within + /// bounds, then write a conditional expression to check them dynamically, + /// and return true. All accesses in the chain are checked by the generated + /// expression. + /// + /// This assumes that the [`BoundsCheckPolicy`] for `chain` is [`ReadZeroSkipWrite`]. + /// + /// The text written is of the form: + /// + /// ```ignore + /// {level}{prefix}metal::uint(i) < 4 && metal::uint(j) < 10 + /// ``` + /// + /// where `{level}` and `{prefix}` are the arguments to this function. For [`Store`] + /// statements, presumably these arguments start an indented `if` statement; for + /// [`Load`] expressions, the caller is probably building up a ternary `?:` + /// expression. In either case, what is written is not a complete syntactic structure + /// in its own right, and the caller will have to finish it off if we return `true`. + /// + /// If no expression is written, return false. + /// + /// [`BoundsCheckPolicy`]: index::BoundsCheckPolicy + /// [`ReadZeroSkipWrite`]: index::BoundsCheckPolicy::ReadZeroSkipWrite + /// [`Store`]: crate::Statement::Store + /// [`Load`]: crate::Expression::Load + #[allow(unused_variables)] + fn put_bounds_checks( + &mut self, + mut chain: Handle, + context: &ExpressionContext, + level: back::Level, + prefix: &'static str, + ) -> Result { + let mut check_written = false; + + // Iterate over the access chain, handling each expression. + loop { + // Produce a `GuardedIndex`, so we can shared code between the + // `Access` and `AccessIndex` cases. + let (base, guarded_index) = match context.function.expressions[chain] { + crate::Expression::Access { base, index } => { + (base, Some(index::GuardedIndex::Expression(index))) + } + crate::Expression::AccessIndex { base, index } => { + // Don't try to check indices into structs. Validation already took + // care of them, and index::needs_guard doesn't handle that case. + let mut base_inner = context.info[base].ty.inner_with(&context.module.types); + if let crate::TypeInner::Pointer { base, .. } = *base_inner { + base_inner = &context.module.types[base].inner; + } + match *base_inner { + crate::TypeInner::Struct { .. } => (base, None), + _ => (base, Some(index::GuardedIndex::Known(index))), + } + } + _ => break, + }; + + if let Some(index) = guarded_index { + if let Some(length) = context.access_needs_check(base, index) { + if check_written { + write!(self.out, " && ")?; + } else { + write!(self.out, "{}{}", level, prefix)?; + check_written = true; + } + + // Check that the index falls within bounds. Do this with a single + // comparison, by casting the index to `uint` first, so that negative + // indices become large positive values. + write!(self.out, "{}::uint(", NAMESPACE)?; + self.put_index(index, context, true)?; + self.out.write_str(") < ")?; + match length { + index::IndexableLength::Known(value) => write!(self.out, "{}", value)?, + index::IndexableLength::Dynamic => { + let global = context + .function + .originating_global(base) + .ok_or(Error::Validation)?; + write!(self.out, "1 + ")?; + self.put_dynamic_array_max_index(global, context)? + } + } + } + } + + chain = base + } + + Ok(check_written) + } + + /// Write the access chain `chain`. + /// + /// `chain` is a subtree of [`Access`] and [`AccessIndex`] expressions, + /// operating either on a pointer to a value, or on a value directly. + /// + /// Generate bounds checks code only if `policy` is [`Restrict`]. The + /// [`ReadZeroSkipWrite`] policy requires checks before any accesses take place, so + /// that must be handled in the caller. + /// + /// Handle the entire chain, recursing back into `put_expression` only for index + /// expressions and the base expression that originates the pointer or composite value + /// being accessed. This allows `put_expression` to assume that any `Access` or + /// `AccessIndex` expressions it sees are the top of a chain, so it can emit + /// `ReadZeroSkipWrite` checks. + /// + /// [`Access`]: crate::Expression::Access + /// [`AccessIndex`]: crate::Expression::AccessIndex + /// [`Restrict`]: crate::proc::index::BoundsCheckPolicy::Restrict + /// [`ReadZeroSkipWrite`]: crate::proc::index::BoundsCheckPolicy::ReadZeroSkipWrite + fn put_access_chain( + &mut self, + chain: Handle, + policy: index::BoundsCheckPolicy, + context: &ExpressionContext, + ) -> BackendResult { + match context.function.expressions[chain] { + crate::Expression::Access { base, index } => { + let mut base_ty = context.info[base].ty.inner_with(&context.module.types); + + // Look through any pointers to see what we're really indexing. + if let crate::TypeInner::Pointer { base, class: _ } = *base_ty { + base_ty = &context.module.types[base].inner; + } + + self.put_subscripted_access_chain( + base, + base_ty, + index::GuardedIndex::Expression(index), + policy, + context, + )?; + } + crate::Expression::AccessIndex { base, index } => { + let base_resolution = &context.info[base].ty; + let mut base_ty = base_resolution.inner_with(&context.module.types); + let mut base_ty_handle = base_resolution.handle(); + + // Look through any pointers to see what we're really indexing. + if let crate::TypeInner::Pointer { base, class: _ } = *base_ty { + base_ty = &context.module.types[base].inner; + base_ty_handle = Some(base); + } + + // Handle structs and anything else that can use `.x` syntax here, so + // `put_subscripted_access_chain` won't have to handle the absurd case of + // indexing a struct with an expression. + match *base_ty { + crate::TypeInner::Struct { .. } => { + let base_ty = base_ty_handle.unwrap(); + self.put_access_chain(base, policy, context)?; + let name = &self.names[&NameKey::StructMember(base_ty, index)]; + write!(self.out, ".{}", name)?; + } + crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => { + self.put_access_chain(base, policy, context)?; + write!(self.out, ".{}", back::COMPONENTS[index as usize])?; + } + _ => { + self.put_subscripted_access_chain( + base, + base_ty, + index::GuardedIndex::Known(index), + policy, + context, + )?; + } + } + } + _ => self.put_expression(chain, context, false)?, + } + + Ok(()) + } + + /// Write a `[]`-style access of `base` by `index`. + /// + /// If `policy` is [`Restrict`], then generate code as needed to force all index + /// values within bounds. + /// + /// The `base_ty` argument must be the type we are actually indexing, like [`Array`] or + /// [`Vector`]. In other words, it's `base`'s type with any surrounding [`Pointer`] + /// removed. Our callers often already have this handy. + /// + /// This only emits `[]` expressions; it doesn't handle struct member accesses or + /// referencing vector components by name. + /// + /// [`Restrict`]: crate::proc::index::BoundsCheckPolicy::Restrict + /// [`Array`]: crate::TypeInner::Array + /// [`Vector`]: crate::TypeInner::Vector + /// [`Pointer`]: crate::TypeInner::Pointer + fn put_subscripted_access_chain( + &mut self, + base: Handle, + base_ty: &crate::TypeInner, + index: index::GuardedIndex, + policy: index::BoundsCheckPolicy, + context: &ExpressionContext, + ) -> BackendResult { + let accessing_wrapped_array = match *base_ty { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(_), + .. + } => true, + _ => false, + }; + + self.put_access_chain(base, policy, context)?; + if accessing_wrapped_array { + write!(self.out, ".{}", WRAPPED_ARRAY_FIELD)?; + } + write!(self.out, "[")?; + + // Decide whether this index needs to be clamped to fall within range. + let restriction_needed = if policy == index::BoundsCheckPolicy::Restrict { + context.access_needs_check(base, index) + } else { + None + }; + if let Some(limit) = restriction_needed { + write!(self.out, "{}::min(unsigned(", NAMESPACE)?; + self.put_index(index, context, true)?; + write!(self.out, "), ")?; + match limit { + index::IndexableLength::Known(limit) => { + write!(self.out, "{}u", limit - 1)?; + } + index::IndexableLength::Dynamic => { + let global = context + .function + .originating_global(base) + .ok_or(Error::Validation)?; + self.put_dynamic_array_max_index(global, context)?; + } + } + write!(self.out, ")")?; + } else { + self.put_index(index, context, true)?; + } + + write!(self.out, "]")?; + + Ok(()) + } + fn put_load( &mut self, pointer: Handle, context: &ExpressionContext, is_scoped: bool, + ) -> BackendResult { + // Since access chains never cross storage classes, we can just check the index + // bounds check policy once at the top. + let policy = context.choose_bounds_check_policy(pointer); + if policy == index::BoundsCheckPolicy::ReadZeroSkipWrite + && self.put_bounds_checks( + pointer, + context, + back::Level(0), + if is_scoped { "" } else { "(" }, + )? + { + write!(self.out, " ? ")?; + self.put_unchecked_load(pointer, policy, context)?; + write!(self.out, " : 0")?; + + if !is_scoped { + write!(self.out, ")")?; + } + } else { + self.put_unchecked_load(pointer, policy, context)?; + } + + Ok(()) + } + + fn put_unchecked_load( + &mut self, + pointer: Handle, + policy: index::BoundsCheckPolicy, + context: &ExpressionContext, ) -> BackendResult { // Because packed vectors such as `packed_float3` cannot be directly multipied by - // matrices, we wrap them with `float3` on load. + // matrices, we convert them to unpacked vectors like `float3` on load. let wrap_packed_vec_scalar_kind = match context.function.expressions[pointer] { crate::Expression::AccessIndex { base, index } => { let ty = match *context.resolve_type(base) { @@ -1264,7 +1579,7 @@ impl Writer { NAMESPACE, scalar_kind_string(scalar_kind) )?; - self.put_expression(pointer, context, true)?; + self.put_access_chain(pointer, policy, context)?; write!(self.out, ")")?; } else if is_atomic { write!( @@ -1272,13 +1587,13 @@ impl Writer { "{}::atomic_load_explicit({}", NAMESPACE, ATOMIC_REFERENCE )?; - self.put_expression(pointer, context, true)?; + self.put_access_chain(pointer, policy, context)?; write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; } else { // We don't do any dereferencing with `*` here as pointer arguments to functions // are done by `&` references and not `*` pointers. These do not need to be // dereferenced. - self.put_expression(pointer, context, is_scoped)?; + self.put_access_chain(pointer, policy, context)?; } Ok(()) @@ -1440,15 +1755,33 @@ impl Writer { } else if let Some(name) = context.expression.function.named_expressions.get(&handle) { - // Front end provides names for all variables at the start of writing. - // But we write them to step by step. We need to recache them - // Otherwise, we could accidentally write variable name instead of full expression. - // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. + // The `crate::Function::named_expressions` table holds + // expressions that should be saved in temporaries once they + // are `Emit`ted. We only add them to `self.named_expressions` + // when we reach the `Emit` that covers them, so that we don't + // try to use their names before we've actually initialized + // the temporary that holds them. + // + // Don't assume the names in `named_expressions` are unique, + // or even valid. Use the `Namer`. Some(self.namer.call(name)) } else { - let min_ref_count = - context.expression.function.expressions[handle].bake_ref_count(); - if min_ref_count <= info.ref_count { + // If this expression is an index that we're going to first compare + // against a limit, and then actually use as an index, then we may + // want to cache it in a temporary, to avoid evaluating it twice. + let bake = + if context.expression.guarded_indices.contains(handle.index()) { + true + } else { + // Expressions whose reference count is above the + // threshold should always be stored in temporaries. + let min_ref_count = context.expression.function.expressions + [handle] + .bake_ref_count(); + min_ref_count <= info.ref_count + }; + + if bake { Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) } else { None @@ -1730,6 +2063,28 @@ impl Writer { value: Handle, level: back::Level, context: &StatementContext, + ) -> BackendResult { + let policy = context.expression.choose_bounds_check_policy(pointer); + if policy == index::BoundsCheckPolicy::ReadZeroSkipWrite + && self.put_bounds_checks(pointer, &context.expression, level, "if (")? + { + writeln!(self.out, ") {{")?; + self.put_unchecked_store(pointer, value, policy, level.next(), context)?; + writeln!(self.out, "{}}}", level)?; + } else { + self.put_unchecked_store(pointer, value, policy, level, context)?; + } + + Ok(()) + } + + fn put_unchecked_store( + &mut self, + pointer: Handle, + value: Handle, + policy: index::BoundsCheckPolicy, + level: back::Level, + context: &StatementContext, ) -> BackendResult { let pointer_info = &context.expression.info[pointer]; let (array_size, is_atomic) = @@ -1753,7 +2108,7 @@ impl Writer { .to_array_length() .unwrap(); write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?; - self.put_expression(pointer, &context.expression, true)?; + self.put_access_chain(pointer, policy, &context.expression)?; write!(self.out, ".{}[_i] = ", WRAPPED_ARRAY_FIELD)?; self.put_expression(value, &context.expression, true)?; writeln!(self.out, ".{}[_i];", WRAPPED_ARRAY_FIELD)?; @@ -1763,13 +2118,13 @@ impl Writer { "{}{}::atomic_store_explicit({}", level, NAMESPACE, ATOMIC_REFERENCE )?; - self.put_expression(pointer, &context.expression, true)?; + self.put_access_chain(pointer, policy, &context.expression)?; write!(self.out, ", ")?; self.put_expression(value, &context.expression, true)?; writeln!(self.out, ", {}::memory_order_relaxed);", NAMESPACE)?; } else { write!(self.out, "{}", level)?; - self.put_expression(pointer, &context.expression, true)?; + self.put_access_chain(pointer, policy, &context.expression)?; write!(self.out, " = ")?; self.put_expression(value, &context.expression, true)?; writeln!(self.out, ";")?; @@ -2216,11 +2571,16 @@ impl Writer { writeln!(self.out, ";")?; } + let guarded_indices = + index::find_checked_indexes(module, fun, fun_info, options.bounds_check_policies); + let context = StatementContext { expression: ExpressionContext { function: fun, origin: FunctionOrigin::Handle(fun_handle), info: fun_info, + policies: options.bounds_check_policies, + guarded_indices, module, pipeline_options, }, @@ -2638,11 +2998,16 @@ impl Writer { writeln!(self.out, ";")?; } + let guarded_indices = + index::find_checked_indexes(module, fun, fun_info, options.bounds_check_policies); + let context = StatementContext { expression: ExpressionContext { function: fun, origin: FunctionOrigin::EntryPoint(ep_index as _), info: fun_info, + policies: options.bounds_check_policies, + guarded_indices, module, pipeline_options, }, @@ -2721,7 +3086,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 20528 (CI) - if !(15000..=25000).contains(&stack_size) { + if !(14000..=25000).contains(&stack_size) { panic!("`put_expression` stack size {} has changed!", stack_size); } } diff --git a/src/proc/index.rs b/src/proc/index.rs index 27110cb5a..15381c9d2 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -3,6 +3,7 @@ use super::ProcError; use crate::valid; use crate::{Handle, UniqueArena}; +use bit_set::BitSet; /// How should code generated by Naga do bounds checks? /// @@ -33,7 +34,8 @@ use crate::{Handle, UniqueArena}; /// If you're using native checks like this, then having Naga inject its own /// checks as well would be redundant, and the `Unchecked` policy is /// appropriate. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum BoundsCheckPolicy { /// Replace out-of-bounds indexes with some arbitrary in-bounds index. @@ -44,7 +46,12 @@ pub enum BoundsCheckPolicy { /// the last element, not the first.) Restrict, - /// Out-of-bounds reads return zero, and writes have no effect. + /// Out-of-bounds reads return zero, and writes have no effect. + /// + /// When applied to a chain of accesses, like `a[i][j].b[k]`, all index + /// expressions are evaluated, regardless of whether prior or later index + /// expressions were in bounds. But all the accesses per se are skipped + /// if any index is out of bounds. ReadZeroSkipWrite, /// Naga adds no checks to indexing operations. Generate the fastest code @@ -53,9 +60,10 @@ pub enum BoundsCheckPolicy { Unchecked, } -#[derive(Clone, Copy, Debug, Default)] -#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] /// Policies for injecting bounds checks during code generation. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct BoundsCheckPolicies { /// How should the generated code handle array, vector, or matrix indices /// that are out of range? @@ -119,26 +127,172 @@ impl Default for BoundsCheckPolicy { } impl BoundsCheckPolicies { - /// Determine which policy applies to a load or store of `pointer`. + /// Determine which policy applies to `access`. + /// + /// `access` is a subtree of `Access` and `AccessIndex` expressions, + /// operating either on a pointer to a value, or on a value directly. /// /// See the documentation for [`BoundsCheckPolicy`] for details about /// when each policy applies. pub fn choose_policy( &self, - pointer: Handle, + access: Handle, types: &UniqueArena, info: &valid::FunctionInfo, ) -> BoundsCheckPolicy { - let is_buffer = match info[pointer].ty.inner_with(types).pointer_class() { + match info[access].ty.inner_with(types).pointer_class() { Some(crate::StorageClass::Storage { access: _ }) - | Some(crate::StorageClass::Uniform) => true, - _ => false, - }; + | Some(crate::StorageClass::Uniform) => self.buffer, + // This covers other storage classes, but also accessing vectors and + // matrices by value, where no pointer is involved. + _ => self.index, + } + } +} - if is_buffer { - self.buffer - } else { - self.index +/// An index that may be statically known, or may need to be computed at runtime. +/// +/// This enum lets us handle both [`Access`] and [`AccessIndex`] expressions +/// with the same code. +/// +/// [`Access`]: crate::Expression::Access +/// [`AccessIndex`]: crate::Expression::AccessIndex +#[derive(Clone, Copy, Debug)] +pub enum GuardedIndex { + Known(u32), + Expression(Handle), +} + +/// Build a set of expressions used as indices, to cache in temporary variables when +/// emitted. +/// +/// Given the bounds-check policies `policies`, construct a `BitSet` containing the handle +/// indices of all the expressions in `function` that are ever used as guarded indices +/// under the [`ReadZeroSkipWrite`] policy. The `module` argument must be the module to +/// which `function` belongs, and `info` should be that function's analysis results. +/// +/// Such index expressions will be used twice in the generated code: first for the +/// comparison to see if the index is in bounds, and then for the access itself, should +/// the comparison succeed. To avoid computing the expressions twice, they should be +/// cached in temporary variables. +/// +/// Why do we need to build such a set before processing a function's statements? Whether +/// an expression needs to be cached depends on whether it appears as the [`index`] +/// operand of any [`Access`] expression, and on the index bounds check policies that +/// apply to those accesses. But [`Emit`] statements just identify a range of expressions +/// by index; there's no good way to tell what an expression is used for. The only way to +/// do it is to just iterate over all the expressions looking for relevant `Access` +/// expressions --- which is what this function does. +/// +/// Simple expressions like variable loads and constants don't make sense to cache: it's +/// no better than just re-evaluating them. But constants are not covered by `Emit` +/// statements, and `Load`s are always cached to ensure they occur at the right time, so +/// we don't bother filtering them out from this set. +/// +/// [`ReadZeroSkipWrite`]: BoundsCheckPolicy::ReadZeroSkipWrite +/// [`index`]: crate::Expression::Access::index +/// [`Access`]: crate::Expression::Access +/// [`Emit`]: crate::Statement::Emit +pub fn find_checked_indexes( + module: &crate::Module, + function: &crate::Function, + info: &crate::valid::FunctionInfo, + policies: BoundsCheckPolicies, +) -> BitSet { + use crate::Expression as Ex; + + let mut guarded_indices = BitSet::new(); + + // Don't bother scanning if we never need `ReadZeroSkipWrite`. + if policies.index == BoundsCheckPolicy::ReadZeroSkipWrite + || policies.buffer == BoundsCheckPolicy::ReadZeroSkipWrite + { + for (_handle, expr) in function.expressions.iter() { + // There's no need to handle `AccessIndex` expressions, as their + // indices never need to be cached. + if let Ex::Access { base, index } = *expr { + if policies.choose_policy(base, &module.types, info) + == BoundsCheckPolicy::ReadZeroSkipWrite + && access_needs_check( + base, + GuardedIndex::Expression(index), + module, + function, + info, + ) + .is_some() + { + guarded_indices.insert(index.index()); + } + } + } + } + + guarded_indices +} + +/// Determine whether `index` is statically known to be in bounds for `base`. +/// +/// If we can't be sure that the index is in bounds, return the limit within +/// which valid indices must fall. +/// +/// The return value is one of the following: +/// +/// - `Some(Known(n))` indicates that `n` is the largest valid index. +/// +/// - `Some(Computed(global))` indicates that the largest valid index is one +/// less than the length of the array that is the last member of the +/// struct held in `global`. +/// +/// - `None` indicates that the index need not be checked, either because it +/// is statically known to be in bounds, or because the applicable policy +/// is `Unchecked`. +/// +/// This function only handles subscriptable types: arrays, vectors, and +/// matrices. It does not handle struct member indices; those never require +/// run-time checks, so it's best to deal with them further up the call +/// chain. +pub fn access_needs_check( + base: Handle, + mut index: GuardedIndex, + module: &crate::Module, + function: &crate::Function, + info: &crate::valid::FunctionInfo, +) -> Option { + let base_inner = info[base].ty.inner_with(&module.types); + // Unwrap safety: `Err` here indicates unindexable base types and invalid + // length constants, but `access_needs_check` is only used by back ends, so + // validation should have caught those problems. + let length = base_inner.indexable_length(module).unwrap(); + index.try_resolve_to_constant(function, module); + if let (&GuardedIndex::Known(index), &IndexableLength::Known(length)) = (&index, &length) { + if index < length { + // Index is statically known to be in bounds, no check needed. + return None; + } + }; + + Some(length) +} + +impl GuardedIndex { + /// Make A `GuardedIndex::Known` from a `GuardedIndex::Expression` if possible. + /// + /// If the expression is a [`Constant`] whose value is a non-specialized, scalar + /// integer constant that can be converted to a `u32`, do so and return a + /// `GuardedIndex::Known`. Otherwise, return the `GuardedIndex::Expression` + /// unchanged. + /// + /// Return values that are already `Known` unchanged. + /// + /// [`Constant`]: crate::Expression::Constant + fn try_resolve_to_constant(&mut self, function: &crate::Function, module: &crate::Module) { + if let GuardedIndex::Expression(expr) = *self { + if let crate::Expression::Constant(handle) = function.expressions[expr] { + if let Some(value) = module.constants[handle].to_array_length() { + *self = GuardedIndex::Known(value); + } + } } } } @@ -149,6 +303,8 @@ impl crate::TypeInner { /// The `self` parameter should be a handle to a vector, matrix, or array /// type, a pointer to one of those, or a value pointer. Arrays may be /// fixed-size, dynamically sized, or sized by a specializable constant. + /// This function does not handle struct member references, as with + /// `AccessIndex`. /// /// The value returned is appropriate for bounds checks on subscripting. /// @@ -186,6 +342,7 @@ impl crate::TypeInner { /// /// This summarizes the length of vectors, matrices, and arrays in a way that is /// convenient for indexing and bounds-checking code. +#[derive(Debug)] pub enum IndexableLength { /// Values of this type always have the given number of elements. Known(u32), diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 4c40d845d..8344f934c 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,6 +1,6 @@ //! Module processing functionality. -mod index; +pub mod index; mod layouter; mod namer; mod terminator; @@ -313,6 +313,33 @@ impl crate::Expression { } } +impl crate::Function { + /// Return the global variable being accessed by the expression `pointer`. + /// + /// Assuming that `pointer` is a series of `Access` and `AccessIndex` + /// expressions that ultimately access some part of a `GlobalVariable`, + /// return a handle for that global. + /// + /// If the expression does not ultimately access a global variable, return + /// `None`. + pub fn originating_global( + &self, + mut pointer: crate::Handle, + ) -> Option> { + loop { + pointer = match self.expressions[pointer] { + crate::Expression::Access { base, .. } => base, + crate::Expression::AccessIndex { base, .. } => base, + crate::Expression::GlobalVariable(handle) => return Some(handle), + crate::Expression::LocalVariable(_) => return None, + crate::Expression::FunctionArgument(_) => return None, + // There are no other expressions that produce pointer values. + _ => unreachable!(), + } + } + } +} + impl crate::SampleLevel { pub fn implicit_derivatives(&self) -> bool { match *self { diff --git a/tests/in/bounds-check-restrict.param.ron b/tests/in/bounds-check-restrict.param.ron new file mode 100644 index 000000000..93c734c14 --- /dev/null +++ b/tests/in/bounds-check-restrict.param.ron @@ -0,0 +1,6 @@ +( + bounds_check_policies: ( + index: Restrict, + buffer: Restrict, + ), +) diff --git a/tests/in/bounds-check-restrict.wgsl b/tests/in/bounds-check-restrict.wgsl new file mode 100644 index 000000000..6f4ae998d --- /dev/null +++ b/tests/in/bounds-check-restrict.wgsl @@ -0,0 +1,73 @@ +// Tests for `naga::back::BoundsCheckPolicy::Restrict`. + +[[block]] +struct Globals { + a: array; + v: vec4; + m: mat3x4; + d: array; +}; + +[[group(0), binding(0)]] var globals: Globals; + +fn index_array(i: i32) -> f32 { + return globals.a[i]; +} + +fn index_dynamic_array(i: i32) -> f32 { + return globals.d[i]; +} + +fn index_vector(i: i32) -> f32 { + return globals.v[i]; +} + +fn index_vector_by_value(v: vec4, i: i32) -> f32 { + return v[i]; +} + +fn index_matrix(i: i32) -> vec4 { + return globals.m[i]; +} + +fn index_twice(i: i32, j: i32) -> f32 { + return globals.m[i][j]; +} + +fn index_expensive(i: i32) -> f32 { + return globals.a[i32(sin(f32(i) / 100.0) * 100.0)]; +} + +fn index_in_bounds() -> f32 { + return globals.a[9] + globals.v[3] + globals.m[2][3]; +} + +fn set_array(i: i32, v: f32) { + globals.a[i] = v; +} + +fn set_dynamic_array(i: i32, v: f32) { + globals.d[i] = v; +} + +fn set_vector(i: i32, v: f32) { + globals.v[i] = v; +} + +fn set_matrix(i: i32, v: vec4) { + globals.m[i] = v; +} + +fn set_index_twice(i: i32, j: i32, v: f32) { + globals.m[i][j] = v; +} + +fn set_expensive(i: i32, v: f32) { + globals.a[i32(sin(f32(i) / 100.0) * 100.0)] = v; +} + +fn set_in_bounds(v: f32) { + globals.a[9] = v; + globals.v[3] = v; + globals.m[2][3] = v; +} diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl index 51602cbd6..b4fbebcd7 100644 --- a/tests/in/bounds-check-zero.wgsl +++ b/tests/in/bounds-check-zero.wgsl @@ -5,6 +5,7 @@ struct Globals { a: array; v: vec4; m: mat3x4; + d: array; }; [[group(0), binding(0)]] var globals: Globals; @@ -13,6 +14,10 @@ fn index_array(i: i32) -> f32 { return globals.a[i]; } +fn index_dynamic_array(i: i32) -> f32 { + return globals.d[i]; +} + fn index_vector(i: i32) -> f32 { return globals.v[i]; } @@ -29,10 +34,22 @@ fn index_twice(i: i32, j: i32) -> f32 { return globals.m[i][j]; } +fn index_expensive(i: i32) -> f32 { + return globals.a[i32(sin(f32(i) / 100.0) * 100.0)]; +} + +fn index_in_bounds() -> f32 { + return globals.a[9] + globals.v[3] + globals.m[2][3]; +} + fn set_array(i: i32, v: f32) { globals.a[i] = v; } +fn set_dynamic_array(i: i32, v: f32) { + globals.d[i] = v; +} + fn set_vector(i: i32, v: f32) { globals.v[i] = v; } @@ -44,3 +61,13 @@ fn set_matrix(i: i32, v: vec4) { fn set_index_twice(i: i32, j: i32, v: f32) { globals.m[i][j] = v; } + +fn set_expensive(i: i32, v: f32) { + globals.a[i32(sin(f32(i) / 100.0) * 100.0)] = v; +} + +fn set_in_bounds(v: f32) { + globals.a[9] = v; + globals.v[3] = v; + globals.m[2][3] = v; +} diff --git a/tests/out/msl/bounds-check-restrict.msl b/tests/out/msl/bounds-check-restrict.msl new file mode 100644 index 000000000..16e432008 --- /dev/null +++ b/tests/out/msl/bounds-check-restrict.msl @@ -0,0 +1,163 @@ +// language: metal1.1 +#include +#include + +struct _mslBufferSizes { + metal::uint size0; +}; + +struct type_1 { + float inner[10]; +}; +typedef float type_4[1]; +struct Globals { + type_1 a; + char _pad1[8]; + metal::float4 v; + metal::float3x4 m; + type_4 d; +}; + +float index_array( + int i, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e4 = globals.a.inner[metal::min(unsigned(i), 9u)]; + return _e4; +} + +float index_dynamic_array( + int i_1, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e4 = globals.d[metal::min(unsigned(i_1), (_buffer_sizes.size0 - 112 - 4) / 4)]; + return _e4; +} + +float index_vector( + int i_2, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e4 = globals.v[metal::min(unsigned(i_2), 3u)]; + return _e4; +} + +float index_vector_by_value( + metal::float4 v, + int i_3 +) { + return v[metal::min(unsigned(i_3), 3u)]; +} + +metal::float4 index_matrix( + int i_4, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + metal::float4 _e4 = globals.m[metal::min(unsigned(i_4), 2u)]; + return _e4; +} + +float index_twice( + int i_5, + int j, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e6 = globals.m[metal::min(unsigned(i_5), 2u)][metal::min(unsigned(j), 3u)]; + return _e6; +} + +float index_expensive( + int i_6, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e11 = globals.a.inner[metal::min(unsigned(static_cast(metal::sin(static_cast(i_6) / 100.0) * 100.0)), 9u)]; + return _e11; +} + +float index_in_bounds( + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e4 = globals.a.inner[9]; + float _e8 = globals.v.w; + float _e15 = globals.m[2].w; + return (_e4 + _e8) + _e15; +} + +void set_array( + int i_7, + float v_1, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + globals.a.inner[metal::min(unsigned(i_7), 9u)] = v_1; + return; +} + +void set_dynamic_array( + int i_8, + float v_2, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + globals.d[metal::min(unsigned(i_8), (_buffer_sizes.size0 - 112 - 4) / 4)] = v_2; + return; +} + +void set_vector( + int i_9, + float v_3, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + globals.v[metal::min(unsigned(i_9), 3u)] = v_3; + return; +} + +void set_matrix( + int i_10, + metal::float4 v_4, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + globals.m[metal::min(unsigned(i_10), 2u)] = v_4; + return; +} + +void set_index_twice( + int i_11, + int j_1, + float v_5, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + globals.m[metal::min(unsigned(i_11), 2u)][metal::min(unsigned(j_1), 3u)] = v_5; + return; +} + +void set_expensive( + int i_12, + float v_6, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + globals.a.inner[metal::min(unsigned(static_cast(metal::sin(static_cast(i_12) / 100.0) * 100.0)), 9u)] = v_6; + return; +} + +void set_in_bounds( + float v_7, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + globals.a.inner[9] = v_7; + globals.v.w = v_7; + globals.m[2].w = v_7; + return; +} diff --git a/tests/out/msl/bounds-check-zero.msl b/tests/out/msl/bounds-check-zero.msl new file mode 100644 index 000000000..6fa661320 --- /dev/null +++ b/tests/out/msl/bounds-check-zero.msl @@ -0,0 +1,177 @@ +// language: metal1.1 +#include +#include + +struct _mslBufferSizes { + metal::uint size0; +}; + +struct type_1 { + float inner[10]; +}; +typedef float type_4[1]; +struct Globals { + type_1 a; + char _pad1[8]; + metal::float4 v; + metal::float3x4 m; + type_4 d; +}; + +float index_array( + int i, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e4 = metal::uint(i) < 10 ? globals.a.inner[i] : 0; + return _e4; +} + +float index_dynamic_array( + int i_1, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e4 = metal::uint(i_1) < 1 + (_buffer_sizes.size0 - 112 - 4) / 4 ? globals.d[i_1] : 0; + return _e4; +} + +float index_vector( + int i_2, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e4 = metal::uint(i_2) < 4 ? globals.v[i_2] : 0; + return _e4; +} + +float index_vector_by_value( + metal::float4 v, + int i_3 +) { + return metal::uint(i_3) < 4 ? v[i_3] : 0; +} + +metal::float4 index_matrix( + int i_4, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + metal::float4 _e4 = metal::uint(i_4) < 3 ? globals.m[i_4] : 0; + return _e4; +} + +float index_twice( + int i_5, + int j, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e6 = metal::uint(j) < 4 && metal::uint(i_5) < 3 ? globals.m[i_5][j] : 0; + return _e6; +} + +float index_expensive( + int i_6, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + int _e9 = static_cast(metal::sin(static_cast(i_6) / 100.0) * 100.0); + float _e11 = metal::uint(_e9) < 10 ? globals.a.inner[_e9] : 0; + return _e11; +} + +float index_in_bounds( + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + float _e4 = globals.a.inner[9]; + float _e8 = globals.v.w; + float _e15 = globals.m[2].w; + return (_e4 + _e8) + _e15; +} + +void set_array( + int i_7, + float v_1, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + if (metal::uint(i_7) < 10) { + globals.a.inner[i_7] = v_1; + } + return; +} + +void set_dynamic_array( + int i_8, + float v_2, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + if (metal::uint(i_8) < 1 + (_buffer_sizes.size0 - 112 - 4) / 4) { + globals.d[i_8] = v_2; + } + return; +} + +void set_vector( + int i_9, + float v_3, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + if (metal::uint(i_9) < 4) { + globals.v[i_9] = v_3; + } + return; +} + +void set_matrix( + int i_10, + metal::float4 v_4, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + if (metal::uint(i_10) < 3) { + globals.m[i_10] = v_4; + } + return; +} + +void set_index_twice( + int i_11, + int j_1, + float v_5, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + if (metal::uint(j_1) < 4 && metal::uint(i_11) < 3) { + globals.m[i_11][j_1] = v_5; + } + return; +} + +void set_expensive( + int i_12, + float v_6, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + int _e10 = static_cast(metal::sin(static_cast(i_12) / 100.0) * 100.0); + if (metal::uint(_e10) < 10) { + globals.a.inner[_e10] = v_6; + } + return; +} + +void set_in_bounds( + float v_7, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + globals.a.inner[9] = v_7; + globals.v.w = v_7; + globals.m[2].w = v_7; + return; +} diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl new file mode 100644 index 000000000..c3b5bb1dd --- /dev/null +++ b/tests/out/msl/policy-mix.msl @@ -0,0 +1,46 @@ +// language: metal1.1 +#include +#include + +struct type_1 { + metal::float4 inner[10]; +}; +struct InStorage { + type_1 a; +}; +struct type_2 { + metal::float4 inner[20]; +}; +struct InUniform { + type_2 a; +}; +struct type_5 { + float inner[30]; +}; +struct type_6 { + float inner[40]; +}; +struct type_9 { + metal::float4 inner[2]; +}; + +metal::float4 mock_function( + metal::int2 c, + int i, + int l, + constant InStorage& in_storage, + constant InUniform& in_uniform, + metal::texture2d_array image_2d_array, + threadgroup type_5 const& in_workgroup, + thread type_6 const& in_private +) { + type_9 in_function; + for(int _i=0; _i<2; ++_i) in_function.inner[_i] = type_9 {metal::float4(0.7070000171661377, 0.0, 0.0, 1.0), metal::float4(0.0, 0.7070000171661377, 0.0, 1.0)}.inner[_i]; + metal::float4 _e22 = in_storage.a.inner[i]; + metal::float4 _e25 = in_uniform.a.inner[i]; + metal::float4 _e27 = image_2d_array.read(metal::uint2(c), i, l); + float _e30 = in_workgroup.inner[metal::min(unsigned(i), 29u)]; + float _e34 = in_private.inner[metal::min(unsigned(i), 39u)]; + metal::float4 _e38 = in_function.inner[metal::min(unsigned(i), 1u)]; + return ((((_e22 + _e25) + _e27) + metal::float4(_e30)) + metal::float4(_e34)) + _e38; +} diff --git a/tests/out/spv/bounds-check-restrict.spvasm b/tests/out/spv/bounds-check-restrict.spvasm new file mode 100644 index 000000000..1f83ea976 --- /dev/null +++ b/tests/out/spv/bounds-check-restrict.spvasm @@ -0,0 +1,238 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 166 +OpCapability Shader +OpCapability Linkage +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpDecorate %10 ArrayStride 4 +OpDecorate %13 ArrayStride 4 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 1 Offset 48 +OpMemberDecorate %14 2 Offset 64 +OpMemberDecorate %14 2 ColMajor +OpMemberDecorate %14 2 MatrixStride 16 +OpMemberDecorate %14 3 Offset 112 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 0 +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 10 +%6 = OpTypeFloat 32 +%5 = OpConstant %6 100.0 +%7 = OpConstant %4 9 +%8 = OpConstant %4 3 +%9 = OpConstant %4 2 +%10 = OpTypeArray %6 %3 +%11 = OpTypeVector %6 4 +%12 = OpTypeMatrix %11 3 +%13 = OpTypeRuntimeArray %6 +%14 = OpTypeStruct %10 %11 %12 %13 +%16 = OpTypePointer StorageBuffer %14 +%15 = OpVariable %16 StorageBuffer +%20 = OpTypeFunction %6 %4 +%22 = OpTypePointer StorageBuffer %10 +%23 = OpTypePointer StorageBuffer %6 +%25 = OpTypeInt 32 0 +%24 = OpConstant %25 9 +%27 = OpConstant %25 0 +%34 = OpTypePointer StorageBuffer %13 +%36 = OpConstant %25 1 +%39 = OpConstant %25 3 +%46 = OpTypePointer StorageBuffer %11 +%47 = OpTypePointer StorageBuffer %6 +%55 = OpTypeFunction %6 %11 %4 +%62 = OpTypeFunction %11 %4 +%64 = OpTypePointer StorageBuffer %12 +%65 = OpTypePointer StorageBuffer %11 +%66 = OpConstant %25 2 +%74 = OpTypeFunction %6 %4 %4 +%94 = OpTypeFunction %6 +%108 = OpTypeFunction %2 %4 %6 +%132 = OpTypeFunction %2 %4 %11 +%141 = OpTypeFunction %2 %4 %4 %6 +%161 = OpTypeFunction %2 %6 +%19 = OpFunction %6 None %20 +%18 = OpFunctionParameter %4 +%17 = OpLabel +OpBranch %21 +%21 = OpLabel +%26 = OpExtInst %25 %1 UMin %18 %24 +%28 = OpAccessChain %23 %15 %27 %26 +%29 = OpLoad %6 %28 +OpReturnValue %29 +OpFunctionEnd +%32 = OpFunction %6 None %20 +%31 = OpFunctionParameter %4 +%30 = OpLabel +OpBranch %33 +%33 = OpLabel +%35 = OpArrayLength %25 %15 3 +%37 = OpISub %25 %35 %36 +%38 = OpExtInst %25 %1 UMin %31 %37 +%40 = OpAccessChain %23 %15 %39 %38 +%41 = OpLoad %6 %40 +OpReturnValue %41 +OpFunctionEnd +%44 = OpFunction %6 None %20 +%43 = OpFunctionParameter %4 +%42 = OpLabel +OpBranch %45 +%45 = OpLabel +%48 = OpExtInst %25 %1 UMin %43 %39 +%49 = OpAccessChain %47 %15 %36 %48 +%50 = OpLoad %6 %49 +OpReturnValue %50 +OpFunctionEnd +%54 = OpFunction %6 None %55 +%52 = OpFunctionParameter %11 +%53 = OpFunctionParameter %4 +%51 = OpLabel +OpBranch %56 +%56 = OpLabel +%57 = OpExtInst %25 %1 UMin %53 %39 +%58 = OpVectorExtractDynamic %6 %52 %57 +OpReturnValue %58 +OpFunctionEnd +%61 = OpFunction %11 None %62 +%60 = OpFunctionParameter %4 +%59 = OpLabel +OpBranch %63 +%63 = OpLabel +%67 = OpExtInst %25 %1 UMin %60 %66 +%68 = OpAccessChain %65 %15 %66 %67 +%69 = OpLoad %11 %68 +OpReturnValue %69 +OpFunctionEnd +%73 = OpFunction %6 None %74 +%71 = OpFunctionParameter %4 +%72 = OpFunctionParameter %4 +%70 = OpLabel +OpBranch %75 +%75 = OpLabel +%76 = OpExtInst %25 %1 UMin %72 %39 +%77 = OpExtInst %25 %1 UMin %71 %66 +%78 = OpAccessChain %47 %15 %66 %77 %76 +%79 = OpLoad %6 %78 +OpReturnValue %79 +OpFunctionEnd +%82 = OpFunction %6 None %20 +%81 = OpFunctionParameter %4 +%80 = OpLabel +OpBranch %83 +%83 = OpLabel +%84 = OpConvertSToF %6 %81 +%85 = OpFDiv %6 %84 %5 +%86 = OpExtInst %6 %1 Sin %85 +%87 = OpFMul %6 %86 %5 +%88 = OpConvertFToS %4 %87 +%89 = OpExtInst %25 %1 UMin %88 %24 +%90 = OpAccessChain %23 %15 %27 %89 +%91 = OpLoad %6 %90 +OpReturnValue %91 +OpFunctionEnd +%93 = OpFunction %6 None %94 +%92 = OpLabel +OpBranch %95 +%95 = OpLabel +%96 = OpAccessChain %23 %15 %27 %24 +%97 = OpLoad %6 %96 +%98 = OpAccessChain %47 %15 %36 %39 +%99 = OpLoad %6 %98 +%100 = OpFAdd %6 %97 %99 +%101 = OpAccessChain %47 %15 %66 %66 %39 +%102 = OpLoad %6 %101 +%103 = OpFAdd %6 %100 %102 +OpReturnValue %103 +OpFunctionEnd +%107 = OpFunction %2 None %108 +%105 = OpFunctionParameter %4 +%106 = OpFunctionParameter %6 +%104 = OpLabel +OpBranch %109 +%109 = OpLabel +%110 = OpExtInst %25 %1 UMin %105 %24 +%111 = OpAccessChain %23 %15 %27 %110 +OpStore %111 %106 +OpReturn +OpFunctionEnd +%115 = OpFunction %2 None %108 +%113 = OpFunctionParameter %4 +%114 = OpFunctionParameter %6 +%112 = OpLabel +OpBranch %116 +%116 = OpLabel +%117 = OpArrayLength %25 %15 3 +%118 = OpISub %25 %117 %36 +%119 = OpExtInst %25 %1 UMin %113 %118 +%120 = OpAccessChain %23 %15 %39 %119 +OpStore %120 %114 +OpReturn +OpFunctionEnd +%124 = OpFunction %2 None %108 +%122 = OpFunctionParameter %4 +%123 = OpFunctionParameter %6 +%121 = OpLabel +OpBranch %125 +%125 = OpLabel +%126 = OpExtInst %25 %1 UMin %122 %39 +%127 = OpAccessChain %47 %15 %36 %126 +OpStore %127 %123 +OpReturn +OpFunctionEnd +%131 = OpFunction %2 None %132 +%129 = OpFunctionParameter %4 +%130 = OpFunctionParameter %11 +%128 = OpLabel +OpBranch %133 +%133 = OpLabel +%134 = OpExtInst %25 %1 UMin %129 %66 +%135 = OpAccessChain %65 %15 %66 %134 +OpStore %135 %130 +OpReturn +OpFunctionEnd +%140 = OpFunction %2 None %141 +%137 = OpFunctionParameter %4 +%138 = OpFunctionParameter %4 +%139 = OpFunctionParameter %6 +%136 = OpLabel +OpBranch %142 +%142 = OpLabel +%143 = OpExtInst %25 %1 UMin %138 %39 +%144 = OpExtInst %25 %1 UMin %137 %66 +%145 = OpAccessChain %47 %15 %66 %144 %143 +OpStore %145 %139 +OpReturn +OpFunctionEnd +%149 = OpFunction %2 None %108 +%147 = OpFunctionParameter %4 +%148 = OpFunctionParameter %6 +%146 = OpLabel +OpBranch %150 +%150 = OpLabel +%151 = OpConvertSToF %6 %147 +%152 = OpFDiv %6 %151 %5 +%153 = OpExtInst %6 %1 Sin %152 +%154 = OpFMul %6 %153 %5 +%155 = OpConvertFToS %4 %154 +%156 = OpExtInst %25 %1 UMin %155 %24 +%157 = OpAccessChain %23 %15 %27 %156 +OpStore %157 %148 +OpReturn +OpFunctionEnd +%160 = OpFunction %2 None %161 +%159 = OpFunctionParameter %6 +%158 = OpLabel +OpBranch %162 +%162 = OpLabel +%163 = OpAccessChain %23 %15 %27 %24 +OpStore %163 %159 +%164 = OpAccessChain %47 %15 %36 %39 +OpStore %164 %159 +%165 = OpAccessChain %47 %15 %66 %66 %39 +OpStore %165 %159 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index eb3a2da42..82138feeb 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -1,204 +1,320 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 130 +; Bound: 209 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpDecorate %6 ArrayStride 4 -OpDecorate %9 Block -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 48 -OpMemberDecorate %9 2 Offset 64 -OpMemberDecorate %9 2 ColMajor -OpMemberDecorate %9 2 MatrixStride 16 -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 0 +OpDecorate %10 ArrayStride 4 +OpDecorate %13 ArrayStride 4 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 1 Offset 48 +OpMemberDecorate %14 2 Offset 64 +OpMemberDecorate %14 2 ColMajor +OpMemberDecorate %14 2 MatrixStride 16 +OpMemberDecorate %14 3 Offset 112 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 -%5 = OpTypeFloat 32 -%6 = OpTypeArray %5 %3 -%7 = OpTypeVector %5 4 -%8 = OpTypeMatrix %7 3 -%9 = OpTypeStruct %6 %7 %8 -%11 = OpTypePointer StorageBuffer %9 -%10 = OpVariable %11 StorageBuffer -%15 = OpTypeFunction %5 %4 -%17 = OpTypePointer StorageBuffer %6 -%18 = OpTypePointer StorageBuffer %5 -%20 = OpTypeInt 32 0 -%19 = OpConstant %20 10 -%22 = OpTypeBool -%23 = OpConstant %20 0 -%25 = OpConstantNull %5 -%34 = OpTypePointer StorageBuffer %7 -%35 = OpTypePointer StorageBuffer %5 -%36 = OpConstant %20 4 -%38 = OpConstant %20 1 -%40 = OpConstantNull %5 -%49 = OpTypeFunction %5 %7 %4 -%52 = OpConstantNull %5 -%60 = OpTypeFunction %7 %4 -%62 = OpTypePointer StorageBuffer %8 -%63 = OpTypePointer StorageBuffer %7 -%64 = OpConstant %20 3 -%66 = OpConstant %20 2 -%68 = OpConstantNull %7 -%77 = OpTypeFunction %5 %4 %4 -%83 = OpConstantNull %5 -%92 = OpTypeFunction %2 %4 %5 -%111 = OpTypeFunction %2 %4 %7 -%122 = OpTypeFunction %2 %4 %4 %5 -%14 = OpFunction %5 None %15 -%13 = OpFunctionParameter %4 -%12 = OpLabel -OpBranch %16 -%16 = OpLabel -%21 = OpULessThan %22 %13 %19 -OpSelectionMerge %26 None -OpBranchConditional %21 %27 %26 -%27 = OpLabel -%24 = OpAccessChain %18 %10 %23 %13 -%28 = OpLoad %5 %24 -OpBranch %26 -%26 = OpLabel -%29 = OpPhi %5 %25 %16 %28 %27 -OpReturnValue %29 +%6 = OpTypeFloat 32 +%5 = OpConstant %6 100.0 +%7 = OpConstant %4 9 +%8 = OpConstant %4 3 +%9 = OpConstant %4 2 +%10 = OpTypeArray %6 %3 +%11 = OpTypeVector %6 4 +%12 = OpTypeMatrix %11 3 +%13 = OpTypeRuntimeArray %6 +%14 = OpTypeStruct %10 %11 %12 %13 +%16 = OpTypePointer StorageBuffer %14 +%15 = OpVariable %16 StorageBuffer +%20 = OpTypeFunction %6 %4 +%22 = OpTypePointer StorageBuffer %10 +%23 = OpTypePointer StorageBuffer %6 +%25 = OpTypeInt 32 0 +%24 = OpConstant %25 10 +%27 = OpTypeBool +%28 = OpConstant %25 0 +%30 = OpConstantNull %6 +%39 = OpTypePointer StorageBuffer %13 +%42 = OpConstant %25 3 +%44 = OpConstantNull %6 +%53 = OpTypePointer StorageBuffer %11 +%54 = OpTypePointer StorageBuffer %6 +%55 = OpConstant %25 4 +%57 = OpConstant %25 1 +%59 = OpConstantNull %6 +%68 = OpTypeFunction %6 %11 %4 +%71 = OpConstantNull %6 +%79 = OpTypeFunction %11 %4 +%81 = OpTypePointer StorageBuffer %12 +%82 = OpTypePointer StorageBuffer %11 +%84 = OpConstant %25 2 +%86 = OpConstantNull %11 +%95 = OpTypeFunction %6 %4 %4 +%101 = OpConstantNull %6 +%117 = OpConstantNull %6 +%124 = OpTypeFunction %6 +%126 = OpConstant %25 9 +%139 = OpTypeFunction %2 %4 %6 +%168 = OpTypeFunction %2 %4 %11 +%179 = OpTypeFunction %2 %4 %4 %6 +%204 = OpTypeFunction %2 %6 +%19 = OpFunction %6 None %20 +%18 = OpFunctionParameter %4 +%17 = OpLabel +OpBranch %21 +%21 = OpLabel +%26 = OpULessThan %27 %18 %24 +OpSelectionMerge %31 None +OpBranchConditional %26 %32 %31 +%32 = OpLabel +%29 = OpAccessChain %23 %15 %28 %18 +%33 = OpLoad %6 %29 +OpBranch %31 +%31 = OpLabel +%34 = OpPhi %6 %30 %21 %33 %32 +OpReturnValue %34 OpFunctionEnd -%32 = OpFunction %5 None %15 -%31 = OpFunctionParameter %4 -%30 = OpLabel -OpBranch %33 -%33 = OpLabel -%37 = OpULessThan %22 %31 %36 -OpSelectionMerge %41 None -OpBranchConditional %37 %42 %41 -%42 = OpLabel -%39 = OpAccessChain %35 %10 %38 %31 -%43 = OpLoad %5 %39 -OpBranch %41 -%41 = OpLabel -%44 = OpPhi %5 %40 %33 %43 %42 -OpReturnValue %44 -OpFunctionEnd -%48 = OpFunction %5 None %49 -%46 = OpFunctionParameter %7 -%47 = OpFunctionParameter %4 +%37 = OpFunction %6 None %20 +%36 = OpFunctionParameter %4 +%35 = OpLabel +OpBranch %38 +%38 = OpLabel +%40 = OpArrayLength %25 %15 3 +%41 = OpULessThan %27 %36 %40 +OpSelectionMerge %45 None +OpBranchConditional %41 %46 %45 +%46 = OpLabel +%43 = OpAccessChain %23 %15 %42 %36 +%47 = OpLoad %6 %43 +OpBranch %45 %45 = OpLabel -OpBranch %50 -%50 = OpLabel -%51 = OpULessThan %22 %47 %36 -OpSelectionMerge %53 None -OpBranchConditional %51 %54 %53 -%54 = OpLabel -%55 = OpVectorExtractDynamic %5 %46 %47 -OpBranch %53 -%53 = OpLabel -%56 = OpPhi %5 %52 %50 %55 %54 -OpReturnValue %56 +%48 = OpPhi %6 %44 %38 %47 %46 +OpReturnValue %48 OpFunctionEnd -%59 = OpFunction %7 None %60 -%58 = OpFunctionParameter %4 -%57 = OpLabel -OpBranch %61 +%51 = OpFunction %6 None %20 +%50 = OpFunctionParameter %4 +%49 = OpLabel +OpBranch %52 +%52 = OpLabel +%56 = OpULessThan %27 %50 %55 +OpSelectionMerge %60 None +OpBranchConditional %56 %61 %60 %61 = OpLabel -%65 = OpULessThan %22 %58 %64 -OpSelectionMerge %69 None -OpBranchConditional %65 %70 %69 -%70 = OpLabel -%67 = OpAccessChain %63 %10 %66 %58 -%71 = OpLoad %7 %67 +%58 = OpAccessChain %54 %15 %57 %50 +%62 = OpLoad %6 %58 +OpBranch %60 +%60 = OpLabel +%63 = OpPhi %6 %59 %52 %62 %61 +OpReturnValue %63 +OpFunctionEnd +%67 = OpFunction %6 None %68 +%65 = OpFunctionParameter %11 +%66 = OpFunctionParameter %4 +%64 = OpLabel OpBranch %69 %69 = OpLabel -%72 = OpPhi %7 %68 %61 %71 %70 -OpReturnValue %72 -OpFunctionEnd -%76 = OpFunction %5 None %77 -%74 = OpFunctionParameter %4 -%75 = OpFunctionParameter %4 +%70 = OpULessThan %27 %66 %55 +OpSelectionMerge %72 None +OpBranchConditional %70 %73 %72 %73 = OpLabel -OpBranch %78 -%78 = OpLabel -%79 = OpULessThan %22 %75 %36 -%80 = OpULessThan %22 %74 %64 -%81 = OpLogicalAnd %22 %79 %80 -OpSelectionMerge %84 None -OpBranchConditional %81 %85 %84 -%85 = OpLabel -%82 = OpAccessChain %35 %10 %66 %74 %75 -%86 = OpLoad %5 %82 -OpBranch %84 -%84 = OpLabel -%87 = OpPhi %5 %83 %78 %86 %85 -OpReturnValue %87 +%74 = OpVectorExtractDynamic %6 %65 %66 +OpBranch %72 +%72 = OpLabel +%75 = OpPhi %6 %71 %69 %74 %73 +OpReturnValue %75 OpFunctionEnd -%91 = OpFunction %2 None %92 -%89 = OpFunctionParameter %4 -%90 = OpFunctionParameter %5 +%78 = OpFunction %11 None %79 +%77 = OpFunctionParameter %4 +%76 = OpLabel +OpBranch %80 +%80 = OpLabel +%83 = OpULessThan %27 %77 %42 +OpSelectionMerge %87 None +OpBranchConditional %83 %88 %87 %88 = OpLabel -OpBranch %93 -%93 = OpLabel -%94 = OpULessThan %22 %89 %19 -OpSelectionMerge %96 None -OpBranchConditional %94 %97 %96 -%97 = OpLabel -%95 = OpAccessChain %18 %10 %23 %89 -OpStore %95 %90 +%85 = OpAccessChain %82 %15 %84 %77 +%89 = OpLoad %11 %85 +OpBranch %87 +%87 = OpLabel +%90 = OpPhi %11 %86 %80 %89 %88 +OpReturnValue %90 +OpFunctionEnd +%94 = OpFunction %6 None %95 +%92 = OpFunctionParameter %4 +%93 = OpFunctionParameter %4 +%91 = OpLabel OpBranch %96 %96 = OpLabel -OpReturn -OpFunctionEnd -%101 = OpFunction %2 None %92 -%99 = OpFunctionParameter %4 -%100 = OpFunctionParameter %5 -%98 = OpLabel +%97 = OpULessThan %27 %93 %55 +%98 = OpULessThan %27 %92 %42 +%99 = OpLogicalAnd %27 %97 %98 +OpSelectionMerge %102 None +OpBranchConditional %99 %103 %102 +%103 = OpLabel +%100 = OpAccessChain %54 %15 %84 %92 %93 +%104 = OpLoad %6 %100 OpBranch %102 %102 = OpLabel -%103 = OpULessThan %22 %99 %36 -OpSelectionMerge %105 None -OpBranchConditional %103 %106 %105 +%105 = OpPhi %6 %101 %96 %104 %103 +OpReturnValue %105 +OpFunctionEnd +%108 = OpFunction %6 None %20 +%107 = OpFunctionParameter %4 %106 = OpLabel -%104 = OpAccessChain %35 %10 %38 %99 -OpStore %104 %100 -OpBranch %105 -%105 = OpLabel +OpBranch %109 +%109 = OpLabel +%110 = OpConvertSToF %6 %107 +%111 = OpFDiv %6 %110 %5 +%112 = OpExtInst %6 %1 Sin %111 +%113 = OpFMul %6 %112 %5 +%114 = OpConvertFToS %4 %113 +%115 = OpULessThan %27 %114 %24 +OpSelectionMerge %118 None +OpBranchConditional %115 %119 %118 +%119 = OpLabel +%116 = OpAccessChain %23 %15 %28 %114 +%120 = OpLoad %6 %116 +OpBranch %118 +%118 = OpLabel +%121 = OpPhi %6 %117 %109 %120 %119 +OpReturnValue %121 +OpFunctionEnd +%123 = OpFunction %6 None %124 +%122 = OpLabel +OpBranch %125 +%125 = OpLabel +%127 = OpAccessChain %23 %15 %28 %126 +%128 = OpLoad %6 %127 +%129 = OpAccessChain %54 %15 %57 %42 +%130 = OpLoad %6 %129 +%131 = OpFAdd %6 %128 %130 +%132 = OpAccessChain %54 %15 %84 %84 %42 +%133 = OpLoad %6 %132 +%134 = OpFAdd %6 %131 %133 +OpReturnValue %134 +OpFunctionEnd +%138 = OpFunction %2 None %139 +%136 = OpFunctionParameter %4 +%137 = OpFunctionParameter %6 +%135 = OpLabel +OpBranch %140 +%140 = OpLabel +%141 = OpULessThan %27 %136 %24 +OpSelectionMerge %143 None +OpBranchConditional %141 %144 %143 +%144 = OpLabel +%142 = OpAccessChain %23 %15 %28 %136 +OpStore %142 %137 +OpBranch %143 +%143 = OpLabel OpReturn OpFunctionEnd -%110 = OpFunction %2 None %111 -%108 = OpFunctionParameter %4 -%109 = OpFunctionParameter %7 -%107 = OpLabel -OpBranch %112 -%112 = OpLabel -%113 = OpULessThan %22 %108 %64 -OpSelectionMerge %115 None -OpBranchConditional %113 %116 %115 -%116 = OpLabel -%114 = OpAccessChain %63 %10 %66 %108 -OpStore %114 %109 -OpBranch %115 -%115 = OpLabel +%148 = OpFunction %2 None %139 +%146 = OpFunctionParameter %4 +%147 = OpFunctionParameter %6 +%145 = OpLabel +OpBranch %149 +%149 = OpLabel +%150 = OpArrayLength %25 %15 3 +%151 = OpULessThan %27 %146 %150 +OpSelectionMerge %153 None +OpBranchConditional %151 %154 %153 +%154 = OpLabel +%152 = OpAccessChain %23 %15 %42 %146 +OpStore %152 %147 +OpBranch %153 +%153 = OpLabel OpReturn OpFunctionEnd -%121 = OpFunction %2 None %122 -%118 = OpFunctionParameter %4 -%119 = OpFunctionParameter %4 -%120 = OpFunctionParameter %5 -%117 = OpLabel -OpBranch %123 -%123 = OpLabel -%124 = OpULessThan %22 %119 %36 -%125 = OpULessThan %22 %118 %64 -%126 = OpLogicalAnd %22 %124 %125 -OpSelectionMerge %128 None -OpBranchConditional %126 %129 %128 -%129 = OpLabel -%127 = OpAccessChain %35 %10 %66 %118 %119 -OpStore %127 %120 -OpBranch %128 -%128 = OpLabel +%158 = OpFunction %2 None %139 +%156 = OpFunctionParameter %4 +%157 = OpFunctionParameter %6 +%155 = OpLabel +OpBranch %159 +%159 = OpLabel +%160 = OpULessThan %27 %156 %55 +OpSelectionMerge %162 None +OpBranchConditional %160 %163 %162 +%163 = OpLabel +%161 = OpAccessChain %54 %15 %57 %156 +OpStore %161 %157 +OpBranch %162 +%162 = OpLabel +OpReturn +OpFunctionEnd +%167 = OpFunction %2 None %168 +%165 = OpFunctionParameter %4 +%166 = OpFunctionParameter %11 +%164 = OpLabel +OpBranch %169 +%169 = OpLabel +%170 = OpULessThan %27 %165 %42 +OpSelectionMerge %172 None +OpBranchConditional %170 %173 %172 +%173 = OpLabel +%171 = OpAccessChain %82 %15 %84 %165 +OpStore %171 %166 +OpBranch %172 +%172 = OpLabel +OpReturn +OpFunctionEnd +%178 = OpFunction %2 None %179 +%175 = OpFunctionParameter %4 +%176 = OpFunctionParameter %4 +%177 = OpFunctionParameter %6 +%174 = OpLabel +OpBranch %180 +%180 = OpLabel +%181 = OpULessThan %27 %176 %55 +%182 = OpULessThan %27 %175 %42 +%183 = OpLogicalAnd %27 %181 %182 +OpSelectionMerge %185 None +OpBranchConditional %183 %186 %185 +%186 = OpLabel +%184 = OpAccessChain %54 %15 %84 %175 %176 +OpStore %184 %177 +OpBranch %185 +%185 = OpLabel +OpReturn +OpFunctionEnd +%190 = OpFunction %2 None %139 +%188 = OpFunctionParameter %4 +%189 = OpFunctionParameter %6 +%187 = OpLabel +OpBranch %191 +%191 = OpLabel +%192 = OpConvertSToF %6 %188 +%193 = OpFDiv %6 %192 %5 +%194 = OpExtInst %6 %1 Sin %193 +%195 = OpFMul %6 %194 %5 +%196 = OpConvertFToS %4 %195 +%197 = OpULessThan %27 %196 %24 +OpSelectionMerge %199 None +OpBranchConditional %197 %200 %199 +%200 = OpLabel +%198 = OpAccessChain %23 %15 %28 %196 +OpStore %198 %189 +OpBranch %199 +%199 = OpLabel +OpReturn +OpFunctionEnd +%203 = OpFunction %2 None %204 +%202 = OpFunctionParameter %6 +%201 = OpLabel +OpBranch %205 +%205 = OpLabel +%206 = OpAccessChain %23 %15 %28 %126 +OpStore %206 %202 +%207 = OpAccessChain %54 %15 %57 %42 +OpStore %207 %202 +%208 = OpAccessChain %54 %15 %84 %84 %42 +OpStore %208 %202 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 74a2b5cf2..565f32619 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -82,6 +82,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { Ok(string) => ron::de::from_str(&string).expect("Couldn't parse param file"), Err(_) => Parameters::default(), }; + let capabilities = if params.god_mode { naga::valid::Capabilities::all() } else { @@ -128,7 +129,14 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(all(feature = "deserialize", feature = "msl-out"))] { if targets.contains(Targets::METAL) { - write_output_msl(module, &info, &dest, name, ¶ms.msl); + write_output_msl( + module, + &info, + &dest, + name, + ¶ms.msl, + params.bounds_check_policies, + ); } } #[cfg(all(feature = "deserialize", feature = "glsl-out"))] @@ -227,6 +235,7 @@ fn write_output_msl( destination: &PathBuf, file_name: &str, options: &naga::back::msl::Options, + bounds_check_policies: naga::proc::BoundsCheckPolicies, ) { use naga::back::msl; @@ -236,8 +245,10 @@ fn write_output_msl( allow_point_size: true, }; + let mut options = options.clone(); + options.bounds_check_policies = bounds_check_policies; let (string, tr_info) = - msl::write_string(module, info, options, &pipeline_options).expect("Metal write failed"); + msl::write_string(module, info, &options, &pipeline_options).expect("Metal write failed"); for (ep, result) in module.entry_points.iter().zip(tr_info.entry_point_names) { if let Err(error) = result { @@ -458,10 +469,11 @@ fn convert_wgsl() { "globals", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), - ("bounds-check-zero", Targets::SPIRV), + ("bounds-check-zero", Targets::SPIRV | Targets::METAL), + ("bounds-check-restrict", Targets::SPIRV | Targets::METAL), ("bounds-check-image-restrict", Targets::SPIRV), ("bounds-check-image-rzsw", Targets::SPIRV), - ("policy-mix", Targets::SPIRV), + ("policy-mix", Targets::SPIRV | Targets::METAL), ( "texture-arg", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From e200e44ede8c4f76d6c864017cd939b3227b20a7 Mon Sep 17 00:00:00 2001 From: Lain-dono Date: Sun, 12 Dec 2021 05:29:31 +0300 Subject: [PATCH 1475/2212] [spv-out] Fixing incorrect pack/unpack (#1587) * [spv-out] Fixing incorrect pack/unpack * [spv-out] Fixing incorrect pack/unpack: make tests happy * [spv-out] Fixing incorrect pack/unpack: remove unexpected newline --- src/back/spv/block.rs | 4 ++-- tests/out/spv/bits.spvasm | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index eaa4b7990..f751cba50 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -659,12 +659,12 @@ impl<'w> BlockContext<'w> { Mf::Pack4x8unorm => MathOp::Ext(spirv::GLOp::PackUnorm4x8), Mf::Pack4x8snorm => MathOp::Ext(spirv::GLOp::PackSnorm4x8), Mf::Pack2x16float => MathOp::Ext(spirv::GLOp::PackHalf2x16), - Mf::Pack2x16unorm => MathOp::Ext(spirv::GLOp::PackSnorm2x16), + Mf::Pack2x16unorm => MathOp::Ext(spirv::GLOp::PackUnorm2x16), Mf::Pack2x16snorm => MathOp::Ext(spirv::GLOp::PackSnorm2x16), Mf::Unpack4x8unorm => MathOp::Ext(spirv::GLOp::UnpackUnorm4x8), Mf::Unpack4x8snorm => MathOp::Ext(spirv::GLOp::UnpackSnorm4x8), Mf::Unpack2x16float => MathOp::Ext(spirv::GLOp::UnpackHalf2x16), - Mf::Unpack2x16unorm => MathOp::Ext(spirv::GLOp::UnpackSnorm2x16), + Mf::Unpack2x16unorm => MathOp::Ext(spirv::GLOp::UnpackUnorm2x16), Mf::Unpack2x16snorm => MathOp::Ext(spirv::GLOp::UnpackSnorm2x16), }; diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm index f7b838453..3ef507eb4 100644 --- a/tests/out/spv/bits.spvasm +++ b/tests/out/spv/bits.spvasm @@ -75,7 +75,7 @@ OpStore %27 %54 %56 = OpExtInst %6 %1 PackSnorm2x16 %55 OpStore %27 %56 %57 = OpLoad %17 %35 -%58 = OpExtInst %6 %1 PackSnorm2x16 %57 +%58 = OpExtInst %6 %1 PackUnorm2x16 %57 OpStore %27 %58 %59 = OpLoad %17 %35 %60 = OpExtInst %6 %1 PackHalf2x16 %59 @@ -90,7 +90,7 @@ OpStore %37 %64 %66 = OpExtInst %17 %1 UnpackSnorm2x16 %65 OpStore %35 %66 %67 = OpLoad %6 %27 -%68 = OpExtInst %17 %1 UnpackSnorm2x16 %67 +%68 = OpExtInst %17 %1 UnpackUnorm2x16 %67 OpStore %35 %68 %69 = OpLoad %6 %27 %70 = OpExtInst %17 %1 UnpackHalf2x16 %69 From c4b331acb44e8ffb6595030a16725ddb137c2dcb Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 12 Dec 2021 02:29:49 +0000 Subject: [PATCH 1476/2212] readme: list supported GLSL versions for glsl-in (#1586) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b1f23f3d1..46c79a296 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Front-end | Status | Feature | Notes | --------------- | ------------------ | ------- | ----- | SPIR-V (binary) | :white_check_mark: | spv-in | | WGSL | :white_check_mark: | wgsl-in | Fully validated | -GLSL | :ok: | glsl-in | | +GLSL | :ok: | glsl-in | GLSL 440+ | Back-end | Status | Feature | Notes | --------------- | ------------------ | -------- | ----- | From 8a2fbd360db96ff2f8b71ede917045d03afe38d4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 13 Dec 2021 11:46:23 -0800 Subject: [PATCH 1477/2212] [msl-out] Add log tracing for functions and entry points. --- src/back/msl/writer.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ab50b1762..7b0177964 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2470,6 +2470,12 @@ impl Writer { ) -> Result { let mut pass_through_globals = Vec::new(); for (fun_handle, fun) in module.functions.iter() { + log::trace!( + "function {:?}, handle {:?}", + fun.name.as_deref().unwrap_or("(anonymous)"), + fun_handle + ); + let fun_info = &mod_info[fun_handle]; pass_through_globals.clear(); let mut supports_array_length = false; @@ -2601,6 +2607,12 @@ impl Writer { let mut ep_error = None; let mut supports_array_length = false; + log::trace!( + "entry point {:?}, index {:?}", + fun.name.as_deref().unwrap_or("(anonymous)"), + ep_index + ); + // skip this entry point if any global bindings are missing, // or their types are incompatible. if !options.fake_missing_bindings { From 3867ef4f6cba6af0bbeec330c9379d7ade14e4ef Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 14 Dec 2021 18:01:42 -0800 Subject: [PATCH 1478/2212] [msl-out] Correctly construct out-of-bounds values for all types. --- src/back/msl/keywords.rs | 2 ++ src/back/msl/writer.rs | 33 +++++++++++++++++++++++++++-- src/proc/index.rs | 9 +++++--- tests/out/msl/bounds-check-zero.msl | 20 +++++++++++------ tests/out/msl/policy-mix.msl | 6 ++++++ 5 files changed, 58 insertions(+), 12 deletions(-) diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs index af4be8827..a62113c09 100644 --- a/src/back/msl/keywords.rs +++ b/src/back/msl/keywords.rs @@ -210,4 +210,6 @@ pub const RESERVED: &[&str] = &[ "M_2_SQRTPI", "M_SQRT2", "M_SQRT1_2", + // Naga utilities + "DefaultConstructible", ]; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7b0177964..3a917a356 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -822,7 +822,7 @@ impl Writer { { write!(self.out, " ? ")?; self.put_access_chain(expr_handle, policy, context)?; - write!(self.out, " : 0")?; + write!(self.out, " : DefaultConstructible()")?; if !is_scoped { write!(self.out, ")")?; @@ -1529,7 +1529,7 @@ impl Writer { { write!(self.out, " ? ")?; self.put_unchecked_load(pointer, policy, context)?; - write!(self.out, " : 0")?; + write!(self.out, " : DefaultConstructible()")?; if !is_scoped { write!(self.out, ")")?; @@ -2154,6 +2154,13 @@ impl Writer { writeln!(self.out, "#include ")?; writeln!(self.out)?; + if options + .bounds_check_policies + .contains(index::BoundsCheckPolicy::ReadZeroSkipWrite) + { + self.put_default_constructible()?; + } + { let mut indices = vec![]; for (handle, var) in module.global_variables.iter() { @@ -2181,6 +2188,28 @@ impl Writer { self.write_functions(module, info, options, pipeline_options) } + /// Write the definition for the `DefaultConstructible` class. + /// + /// The [`ReadZeroSkipWrite`] bounds check policy requires us to be able to + /// produce 'zero' values for any type, including structs, arrays, and so + /// on. We could do this by emitting default constructor applications, but + /// that would entail printing the name of the type, which is more trouble + /// than you'd think. Instead, we just construct this magic C++14 class that + /// can be converted to any type that can be default constructed, using + /// template parameter inference to detect which type is needed, so we don't + /// have to figure out the name. + /// + /// [`ReadZeroSkipWrite`]: index::BoundsCheckPolicy::ReadZeroSkipWrite + fn put_default_constructible(&mut self) -> BackendResult { + writeln!(self.out, "struct DefaultConstructible {{")?; + writeln!(self.out, " template")?; + writeln!(self.out, " operator T() && {{")?; + writeln!(self.out, " return T {{}};")?; + writeln!(self.out, " }}")?; + writeln!(self.out, "}};")?; + Ok(()) + } + fn write_type_defs(&mut self, module: &crate::Module) -> BackendResult { for (handle, ty) in module.types.iter() { if !ty.needs_alias() { diff --git a/src/proc/index.rs b/src/proc/index.rs index 15381c9d2..ae20cc5d6 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -148,6 +148,11 @@ impl BoundsCheckPolicies { _ => self.index, } } + + /// Return `true` if any of `self`'s policies are `policy`. + pub fn contains(&self, policy: BoundsCheckPolicy) -> bool { + self.index == policy || self.buffer == policy || self.image == policy + } } /// An index that may be statically known, or may need to be computed at runtime. @@ -204,9 +209,7 @@ pub fn find_checked_indexes( let mut guarded_indices = BitSet::new(); // Don't bother scanning if we never need `ReadZeroSkipWrite`. - if policies.index == BoundsCheckPolicy::ReadZeroSkipWrite - || policies.buffer == BoundsCheckPolicy::ReadZeroSkipWrite - { + if policies.contains(BoundsCheckPolicy::ReadZeroSkipWrite) { for (_handle, expr) in function.expressions.iter() { // There's no need to handle `AccessIndex` expressions, as their // indices never need to be cached. diff --git a/tests/out/msl/bounds-check-zero.msl b/tests/out/msl/bounds-check-zero.msl index 6fa661320..0662b3340 100644 --- a/tests/out/msl/bounds-check-zero.msl +++ b/tests/out/msl/bounds-check-zero.msl @@ -2,6 +2,12 @@ #include #include +struct DefaultConstructible { + template + operator T() && { + return T {}; + } +}; struct _mslBufferSizes { metal::uint size0; }; @@ -23,7 +29,7 @@ float index_array( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e4 = metal::uint(i) < 10 ? globals.a.inner[i] : 0; + float _e4 = metal::uint(i) < 10 ? globals.a.inner[i] : DefaultConstructible(); return _e4; } @@ -32,7 +38,7 @@ float index_dynamic_array( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e4 = metal::uint(i_1) < 1 + (_buffer_sizes.size0 - 112 - 4) / 4 ? globals.d[i_1] : 0; + float _e4 = metal::uint(i_1) < 1 + (_buffer_sizes.size0 - 112 - 4) / 4 ? globals.d[i_1] : DefaultConstructible(); return _e4; } @@ -41,7 +47,7 @@ float index_vector( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e4 = metal::uint(i_2) < 4 ? globals.v[i_2] : 0; + float _e4 = metal::uint(i_2) < 4 ? globals.v[i_2] : DefaultConstructible(); return _e4; } @@ -49,7 +55,7 @@ float index_vector_by_value( metal::float4 v, int i_3 ) { - return metal::uint(i_3) < 4 ? v[i_3] : 0; + return metal::uint(i_3) < 4 ? v[i_3] : DefaultConstructible(); } metal::float4 index_matrix( @@ -57,7 +63,7 @@ metal::float4 index_matrix( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - metal::float4 _e4 = metal::uint(i_4) < 3 ? globals.m[i_4] : 0; + metal::float4 _e4 = metal::uint(i_4) < 3 ? globals.m[i_4] : DefaultConstructible(); return _e4; } @@ -67,7 +73,7 @@ float index_twice( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e6 = metal::uint(j) < 4 && metal::uint(i_5) < 3 ? globals.m[i_5][j] : 0; + float _e6 = metal::uint(j) < 4 && metal::uint(i_5) < 3 ? globals.m[i_5][j] : DefaultConstructible(); return _e6; } @@ -77,7 +83,7 @@ float index_expensive( constant _mslBufferSizes& _buffer_sizes ) { int _e9 = static_cast(metal::sin(static_cast(i_6) / 100.0) * 100.0); - float _e11 = metal::uint(_e9) < 10 ? globals.a.inner[_e9] : 0; + float _e11 = metal::uint(_e9) < 10 ? globals.a.inner[_e9] : DefaultConstructible(); return _e11; } diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index c3b5bb1dd..06ed990be 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -2,6 +2,12 @@ #include #include +struct DefaultConstructible { + template + operator T() && { + return T {}; + } +}; struct type_1 { metal::float4 inner[10]; }; From 8ffd6ba929b4b93c9564f08fe8bb34b23fa72a6f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 8 Dec 2021 00:27:20 -0500 Subject: [PATCH 1479/2212] Remove top_level property of structs --- CHANGELOG.md | 6 +- src/back/glsl/mod.rs | 144 +++-- src/back/hlsl/writer.rs | 15 +- src/back/msl/writer.rs | 4 +- src/back/spv/block.rs | 4 +- src/back/spv/helpers.rs | 26 + src/back/spv/index.rs | 7 +- src/back/spv/mod.rs | 27 +- src/back/spv/writer.rs | 107 +++- src/back/wgsl/writer.rs | 13 +- src/front/glsl/functions.rs | 6 +- src/front/glsl/offset.rs | 12 +- src/front/glsl/parser/declarations.rs | 1 - src/front/glsl/parser/types.rs | 6 +- src/front/spv/function.rs | 1 - src/front/spv/mod.rs | 24 +- src/front/wgsl/mod.rs | 12 +- src/front/wgsl/tests.rs | 3 +- src/lib.rs | 14 +- src/proc/layouter.rs | 6 +- src/valid/interface.rs | 17 +- src/valid/type.rs | 20 +- tests/in/access.wgsl | 1 - tests/in/boids.wgsl | 2 - tests/in/bounds-check-restrict.wgsl | 1 - tests/in/bounds-check-zero.wgsl | 1 - tests/in/collatz.wgsl | 1 - tests/in/extra.wgsl | 1 - tests/in/pointers.wgsl | 1 - tests/in/policy-mix.wgsl | 2 - tests/in/shadow.wgsl | 2 - tests/in/skybox.wgsl | 1 - tests/out/glsl/access.atomics.Compute.glsl | 2 +- tests/out/glsl/access.foo.Vertex.glsl | 2 +- tests/out/glsl/boids.main.Compute.glsl | 10 +- .../glsl/interpolate.frag_main.Fragment.glsl | 1 - tests/out/glsl/interpolate.main.Fragment.glsl | 25 - tests/out/glsl/interpolate.main.Vertex.glsl | 42 -- .../glsl/interpolate.vert_main.Vertex.glsl | 1 - tests/out/glsl/operators.main.Compute.glsl | 1 - tests/out/glsl/quad-vert.main.Vertex.glsl | 22 +- tests/out/glsl/quad.frag_main.Fragment.glsl | 1 - tests/out/glsl/quad.fs_extra.Fragment.glsl | 1 - tests/out/glsl/quad.vert_main.Vertex.glsl | 1 - tests/out/glsl/shadow.fs_main.Fragment.glsl | 10 +- tests/out/glsl/skybox.fs_main.Fragment.glsl | 5 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 6 +- tests/out/ir/collatz.ron | 1 - tests/out/ir/shadow.ron | 3 - tests/out/spv/access.spvasm | 2 +- tests/out/spv/boids.spvasm | 545 +++++++++--------- tests/out/spv/bounds-check-restrict.spvasm | 2 +- tests/out/spv/bounds-check-zero.spvasm | 2 +- tests/out/spv/collatz.spvasm | 2 +- tests/out/spv/extra.spvasm | 1 - tests/out/spv/pointers.spvasm | 2 +- tests/out/spv/policy-mix.spvasm | 192 +++--- tests/out/spv/shadow.spvasm | 276 ++++----- tests/out/spv/skybox.spvasm | 182 +++--- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 1 - tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 3 - tests/out/wgsl/210-bevy-shader-vert.wgsl | 2 - tests/out/wgsl/246-collatz-comp.wgsl | 1 - .../wgsl/800-out-of-bounds-panic-vert.wgsl | 2 - tests/out/wgsl/896-push-constant-vert.wgsl | 1 - tests/out/wgsl/access.wgsl | 1 - tests/out/wgsl/bevy-pbr-frag.wgsl | 8 - tests/out/wgsl/bevy-pbr-vert.wgsl | 2 - tests/out/wgsl/boids.wgsl | 2 - tests/out/wgsl/collatz.wgsl | 1 - tests/out/wgsl/constant-array-size-vert.wgsl | 1 - tests/out/wgsl/empty-global-name.wgsl | 1 - tests/out/wgsl/extra.wgsl | 1 - tests/out/wgsl/pointers.wgsl | 1 - tests/out/wgsl/quad-vert.wgsl | 1 - tests/out/wgsl/shadow.wgsl | 2 - tests/out/wgsl/skybox.wgsl | 1 - tests/wgsl-errors.rs | 14 - 78 files changed, 888 insertions(+), 986 deletions(-) delete mode 100644 tests/out/glsl/interpolate.main.Fragment.glsl delete mode 100644 tests/out/glsl/interpolate.main.Vertex.glsl diff --git a/CHANGELOG.md b/CHANGELOG.md index 8439ecbc7..da938ff2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ # Change Log -## v0.7.1 (2021-10-12) +## v0.8 (TBD) + - WGSL-in: + - remove `[[block]]` attribute + +### v0.7.1 (2021-10-12) - implement casts from and to booleans in the backends ## v0.7 (2021-10-07) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 53f376a66..082fa685c 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -83,6 +83,33 @@ impl crate::AtomicFunction { } } +impl crate::StorageClass { + fn is_buffer(&self) -> bool { + match *self { + crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => true, + _ => false, + } + } +} + +//Note: similar to `back/spv/helpers.rs` +fn global_needs_wrapper(ir_module: &crate::Module, global_ty: Handle) -> bool { + match ir_module.types[global_ty].inner { + crate::TypeInner::Struct { + ref members, + span: _, + } => match ir_module.types[members.last().unwrap().ty].inner { + // Structs with dynamically sized arrays can't be copied and can't be wrapped. + crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } => false, + _ => true, + }, + _ => false, + } +} + /// glsl version #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -340,8 +367,6 @@ pub struct Writer<'a, W> { /// A map with all the names needed for writing the module /// (generated by a [`Namer`](crate::proc::Namer)) names: crate::FastHashMap, - /// A map with all the names needed for reflections - reflection_names_uniforms: crate::FastHashMap, String>, /// A map with the names of global variables needed for reflections reflection_names_globals: crate::FastHashMap, String>, /// The selected entry point @@ -397,7 +422,6 @@ impl<'a, W: Write> Writer<'a, W> { namer, features: FeaturesManager::new(), names, - reflection_names_uniforms: crate::FastHashMap::default(), reflection_names_globals: crate::FastHashMap::default(), entry_point: &module.entry_points[ep_idx], entry_point_idx: ep_idx as u16, @@ -489,27 +513,30 @@ impl<'a, W: Write> Writer<'a, W> { } } + let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); + // Write all structs // // This are always ordered because of the IR is structured in a way that you can't make a // struct without adding all of it's members first for (handle, ty) in self.module.types.iter() { if let TypeInner::Struct { ref members, .. } = ty.inner { - // No needed to write a struct that also should be written as a global variable - let is_global_struct = self - .module - .global_variables - .iter() - .any(|e| e.1.ty == handle); + let used_by_global = self.module.global_variables.iter().any(|(vh, var)| { + !ep_info[vh].is_empty() && var.class.is_buffer() && var.ty == handle + }); - if !is_global_struct { - self.write_struct(false, handle, members)? + let is_wrapped = global_needs_wrapper(self.module, handle); + // If it's a global non-wrapped struct, it will be printed + // with the corresponding global variable. + if !used_by_global || is_wrapped { + let name = &self.names[&NameKey::Type(handle)]; + write!(self.out, "struct {} ", name)?; + self.write_struct_body(handle, members)?; + writeln!(self.out, ";")?; } } } - let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); - // Write the globals // // We filter all globals that aren't used by the selected entry point as they might be @@ -748,12 +775,7 @@ impl<'a, W: Write> Writer<'a, W> { match self.module.types[ty].inner { // glsl has no pointer types so just write types as normal and loads are skipped TypeInner::Pointer { base, .. } => self.write_type(base), - TypeInner::Struct { - top_level: true, - ref members, - span: _, - } => self.write_struct(true, ty, members), - // glsl structs are written as just the struct name if it isn't a block + // glsl structs are written as just the struct name TypeInner::Struct { .. } => { // Get the struct name let name = &self.names[&NameKey::Type(ty)]; @@ -861,21 +883,46 @@ impl<'a, W: Write> Writer<'a, W> { // Trailing space is important if let Some(storage_class) = glsl_storage_class(global.class) { write!(self.out, "{} ", storage_class)?; - } else if let TypeInner::Struct { - top_level: true, .. - } = self.module.types[global.ty].inner - { - write!(self.out, "struct ")?; } - // Write the type - // `write_type` adds no leading or trailing spaces - self.write_type(global.ty)?; + // If struct is a block we need to write `block_name { members }` where `block_name` must be + // unique between blocks and structs so we add `_block_ID` where `ID` is a `IdGenerator` + // generated number so it's unique and `members` are the same as in a struct + + // Write the block name, it's just the struct name appended with `_block_ID` + let needs_wrapper = if global.class.is_buffer() { + let ty_name = &self.names[&NameKey::Type(global.ty)]; + let block_name = format!( + "{}_block_{}{:?}", + ty_name, + self.block_id.generate(), + self.entry_point.stage, + ); + write!(self.out, "{} ", block_name)?; + self.reflection_names_globals.insert(handle, block_name); + + let needs_wrapper = global_needs_wrapper(self.module, global.ty); + if needs_wrapper { + write!(self.out, "{{ ")?; + // Write the type + // `write_type` adds no leading or trailing spaces + self.write_type(global.ty)?; + } else if let crate::TypeInner::Struct { ref members, .. } = + self.module.types[global.ty].inner + { + self.write_struct_body(global.ty, members)?; + } + needs_wrapper + } else { + self.write_type(global.ty)?; + false + }; // Finally write the global name and end the global with a `;` and a newline // Leading space is important write!(self.out, " ")?; self.write_global_name(handle, global)?; + if let TypeInner::Array { size, .. } = self.module.types[global.ty].inner { self.write_array_size(size)?; } @@ -888,8 +935,12 @@ impl<'a, W: Write> Writer<'a, W> { self.write_zero_init_value(global.ty)?; } } - writeln!(self.out, ";")?; + if needs_wrapper { + write!(self.out, "; }}")?; + } + + writeln!(self.out, ";")?; Ok(()) } @@ -1283,9 +1334,8 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Ends in a newline - fn write_struct( + fn write_struct_body( &mut self, - block: bool, handle: Handle, members: &[crate::StructMember], ) -> BackendResult { @@ -1296,30 +1346,7 @@ impl<'a, W: Write> Writer<'a, W> { // | `members` is a semicolon separated list of `type name` // | `type` is the member type // | `name` is the member name - let name = &self.names[&NameKey::Type(handle)]; - - // If struct is a block we need to write `block_name { members }` where `block_name` must be - // unique between blocks and structs so we add `_block_ID` where `ID` is a `IdGenerator` - // generated number so it's unique and `members` are the same as in a struct - if block { - // Write the block name, it's just the struct name appended with `_block_ID` - let stage_postfix = match self.entry_point.stage { - ShaderStage::Vertex => "Vs", - ShaderStage::Fragment => "Fs", - ShaderStage::Compute => "Cs", - }; - let block_name = format!( - "{}_block_{}{}", - name, - self.block_id.generate(), - stage_postfix - ); - writeln!(self.out, "{} {{", block_name)?; - - self.reflection_names_uniforms.insert(handle, block_name); - } else { - writeln!(self.out, "struct {} {{", name)?; - } + writeln!(self.out, "{{")?; for (idx, member) in members.iter().enumerate() { // The indentation is only for readability @@ -1360,13 +1387,6 @@ impl<'a, W: Write> Writer<'a, W> { } write!(self.out, "}}")?; - - if !block { - writeln!(self.out, ";")?; - // Add a newline for readability - writeln!(self.out)?; - } - Ok(()) } @@ -2747,7 +2767,7 @@ impl<'a, W: Write> Writer<'a, W> { match self.module.types[var.ty].inner { crate::TypeInner::Struct { .. } => match var.class { crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => { - let name = self.reflection_names_uniforms[&var.ty].clone(); + let name = self.reflection_names_globals[&handle].clone(); uniforms.insert(handle, name); } _ => (), diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 6f05f1bd1..d8cfde3cd 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -152,12 +152,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write all structs for (handle, ty) in module.types.iter() { - if let TypeInner::Struct { - top_level, - ref members, - .. - } = ty.inner - { + if let TypeInner::Struct { ref members, .. } = ty.inner { if let Some(member) = members.last() { if let TypeInner::Array { size: crate::ArraySize::Dynamic, @@ -180,7 +175,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_struct( module, handle, - top_level, members, ep_result.map(|r| (r.0, Io::Output)), )?; @@ -703,7 +697,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { &mut self, module: &Module, handle: Handle, - _block: bool, members: &[crate::StructMember], shader_stage: Option<(ShaderStage, Io)>, ) -> BackendResult { @@ -1941,11 +1934,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let var = &module.global_variables[var_handle]; let (offset, stride) = match module.types[var.ty].inner { TypeInner::Array { stride, .. } => (0, stride), - TypeInner::Struct { - top_level: true, - ref members, - .. - } => { + TypeInner::Struct { ref members, .. } => { let last = members.last().unwrap(); let stride = match module.types[last.ty].inner { TypeInner::Array { stride, .. } => stride, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 3a917a356..51f892d78 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2652,9 +2652,7 @@ impl Writer { if let Some(ref br) = var.binding { let good = match options.per_stage_map[ep.stage].resources.get(br) { Some(target) => match module.types[var.ty].inner { - crate::TypeInner::Struct { - top_level: true, .. - } => target.buffer.is_some(), + crate::TypeInner::Struct { .. } => target.buffer.is_some(), crate::TypeInner::Image { .. } => target.texture.is_some(), crate::TypeInner::Sampler { .. } => target.sampler.is_some(), _ => false, diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index f751cba50..f0676f0d4 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -247,7 +247,7 @@ impl<'w> BlockContext<'w> { } } crate::Expression::GlobalVariable(handle) => { - self.writer.global_variables[handle.index()].id + self.writer.global_variables[handle.index()].access_id } crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], crate::Expression::Splat { size, value } => { @@ -1065,7 +1065,7 @@ impl<'w> BlockContext<'w> { } crate::Expression::GlobalVariable(handle) => { let gv = &self.writer.global_variables[handle.index()]; - break gv.id; + break gv.access_id; } crate::Expression::LocalVariable(variable) => { let local_var = &self.function.variables[&variable]; diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index aa7952ad2..4640ebf52 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -61,3 +61,29 @@ impl crate::StorageClass { } } } + +/// Return true if the global requires a type decorated with "Block". +// See `back::spv::GlobalVariable::access_id` for details. +pub fn global_needs_wrapper(ir_module: &crate::Module, var: &crate::GlobalVariable) -> bool { + match var.class { + crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => {} + _ => return false, + }; + match ir_module.types[var.ty].inner { + crate::TypeInner::Struct { + ref members, + span: _, + } => match members.last() { + Some(member) => match ir_module.types[member.ty].inner { + // Structs with dynamically sized arrays can't be copied and can't be wrapped. + crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } => false, + _ => true, + }, + None => false, + }, + _ => false, + } +} diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 4192d3848..c2b198048 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -43,9 +43,10 @@ impl<'w> BlockContext<'w> { let (structure_id, last_member_index) = match self.ir_function.expressions[array] { crate::Expression::AccessIndex { base, index } => { match self.ir_function.expressions[base] { - crate::Expression::GlobalVariable(handle) => { - (self.writer.global_variables[handle.index()].id, index) - } + crate::Expression::GlobalVariable(handle) => ( + self.writer.global_variables[handle.index()].access_id, + index, + ), _ => return Err(Error::Validation("array length expression")), } } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index d341e8df2..8dc574dfe 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -430,30 +430,49 @@ impl recyclable::Recyclable for CachedExpressions { } } +#[derive(Clone)] struct GlobalVariable { - /// Actual ID of the variable. - id: Word, + /// ID of the variable. Not really used. + var_id: Word, /// For `StorageClass::Handle` variables, this ID is recorded in the function /// prelude block (and reset before every function) as `OpLoad` of the variable. /// It is then used for all the global ops, such as `OpImageSample`. handle_id: Word, + /// Actual ID used to access this variable. + /// For wrapped buffer variables, this ID is `OpAccessChain` into the + /// wrapper. Otherwise, the same as `var_id`. + /// + /// Vulkan requires that globals in the `StorageBuffer` and `Uniform` storage + /// classes must be structs with the `Block` decoration, but WGSL and Naga IR + /// make no such requirement. So for such variables, we generate a wrapper struct + /// type with a single element of the type given by Naga, generate an + /// `OpAccessChain` for that member in the function prelude, and use that pointer + /// to refer to the global in the function body. This is the id of that access, + /// updated for each function in `write_function`. + access_id: Word, } impl GlobalVariable { fn dummy() -> Self { Self { - id: 0, + var_id: 0, handle_id: 0, + access_id: 0, } } fn new(id: Word) -> Self { - Self { id, handle_id: 0 } + Self { + var_id: id, + handle_id: 0, + access_id: 0, + } } /// Prepare `self` for use within a single function. fn reset_for_function(&mut self) { self.handle_id = 0; + self.access_id = 0; } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 73066c905..ea83a4203 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,5 +1,5 @@ use super::{ - helpers::{contains_builtin, map_storage_class}, + helpers::{contains_builtin, global_needs_wrapper, map_storage_class}, make_local, Block, BlockContext, CachedExpressions, EntryPointContext, Error, Function, FunctionArgument, GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, LogicalLayout, LookupFunctionType, LookupType, LoopContext, Options, PhysicalLayout, @@ -485,22 +485,46 @@ impl Writer { function.entry_point_context = Some(ep_context); } - // fill up the `GlobalVariable::handle_id` + // fill up the `GlobalVariable::access_id` for gv in self.global_variables.iter_mut() { gv.reset_for_function(); } for (handle, var) in ir_module.global_variables.iter() { - // Handle globals are pre-emitted and should be loaded automatically. - if info[handle].is_empty() || var.class != crate::StorageClass::Handle { + if info[handle].is_empty() { continue; } - let id = self.id_gen.next(); - let result_type_id = self.get_type_id(LookupType::Handle(var.ty)); - let gv = &mut self.global_variables[handle.index()]; - prelude - .body - .push(Instruction::load(result_type_id, id, gv.id, None)); - gv.handle_id = id; + + let mut gv = self.global_variables[handle.index()].clone(); + + // Handle globals are pre-emitted and should be loaded automatically. + if var.class == crate::StorageClass::Handle { + let var_type_id = self.get_type_id(LookupType::Handle(var.ty)); + let id = self.id_gen.next(); + prelude + .body + .push(Instruction::load(var_type_id, id, gv.var_id, None)); + gv.access_id = gv.var_id; + gv.handle_id = id; + } else if global_needs_wrapper(ir_module, var) { + let class = map_storage_class(var.class); + let pointer_type_id = self.get_pointer_id(&ir_module.types, var.ty, class)?; + let index_id = self.get_index_constant(0); + + let id = self.id_gen.next(); + prelude.body.push(Instruction::access_chain( + pointer_type_id, + id, + gv.var_id, + &[index_id], + )); + gv.access_id = id; + } else { + // by default, the variable ID is accessed as is + gv.access_id = gv.var_id; + }; + + // work around borrow checking in the presense of `self.xxx()` calls + self.global_variables[handle.index()] = gv; } // Create a `BlockContext` for generating SPIR-V for the function's @@ -818,14 +842,9 @@ impl Writer { } } crate::TypeInner::Struct { - top_level, ref members, span: _, } => { - if top_level { - self.decorate(id, Decoration::Block, &[]); - } - let mut member_ids = Vec::with_capacity(members.len()); for (index, member) in members.iter().enumerate() { if decorate_layout { @@ -1215,17 +1234,13 @@ impl Writer { &mut self, ir_module: &crate::Module, global_variable: &crate::GlobalVariable, - ) -> Result<(Instruction, Word), Error> { + ) -> Result { + use spirv::Decoration; + let id = self.id_gen.next(); - let class = map_storage_class(global_variable.class); - //self.check(class.required_capabilities())?; - let init_word = global_variable - .init - .map(|constant| self.constant_ids[constant.index()]); - let pointer_type_id = self.get_pointer_id(&ir_module.types, global_variable.ty, class)?; - let instruction = Instruction::variable(pointer_type_id, id, class, init_word); + //self.check(class.required_capabilities())?; if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = global_variable.name { @@ -1233,8 +1248,6 @@ impl Writer { } } - use spirv::Decoration; - let storage_access = match global_variable.class { crate::StorageClass::Storage { access } => Some(access), _ => match ir_module.types[global_variable.ty].inner { @@ -1259,8 +1272,43 @@ impl Writer { self.decorate(id, Decoration::Binding, &[res_binding.binding]); } - // TODO Initializer is optional and not (yet) included in the IR - Ok((instruction, id)) + let init_word = global_variable + .init + .map(|constant| self.constant_ids[constant.index()]); + let inner_type_id = self.get_type_id(LookupType::Handle(global_variable.ty)); + + // generate the wrapping structure if needed + let pointer_type_id = if global_needs_wrapper(ir_module, global_variable) { + let wrapper_type_id = self.id_gen.next(); + + self.decorate(wrapper_type_id, Decoration::Block, &[]); + self.annotations.push(Instruction::member_decorate( + wrapper_type_id, + 0, + Decoration::Offset, + &[0], + )); + Instruction::type_struct(wrapper_type_id, &[inner_type_id]) + .to_words(&mut self.logical_layout.declarations); + + let pointer_type_id = self.id_gen.next(); + Instruction::type_pointer(pointer_type_id, class, wrapper_type_id) + .to_words(&mut self.logical_layout.declarations); + + pointer_type_id + } else { + // This is a global variable in a Storage class. The only way it could + // have `global_needs_wrapper() == false` is if it has a runtime-sized array. + // In this case, we need to decorate it with Block. + if let crate::StorageClass::Storage { .. } = global_variable.class { + self.decorate(inner_type_id, Decoration::Block, &[]); + } + self.get_pointer_id(&ir_module.types, global_variable.ty, class)? + }; + + Instruction::variable(pointer_type_id, id, class, init_word) + .to_words(&mut self.logical_layout.declarations); + Ok(id) } fn get_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { @@ -1389,8 +1437,7 @@ impl Writer { GlobalVariable::dummy() } _ => { - let (instruction, id) = self.write_global_variable(ir_module, var)?; - instruction.to_words(&mut self.logical_layout.declarations); + let id = self.write_global_variable(ir_module, var)?; GlobalVariable::new(id) } }; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 0f19f765b..4d06b7a94 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -12,7 +12,6 @@ type BackendResult = Result<(), Error>; /// WGSL [attribute](https://gpuweb.github.io/gpuweb/wgsl/#attributes) enum Attribute { Binding(u32), - Block, BuiltIn(crate::BuiltIn), Group(u32), Interpolate(Option, Option), @@ -107,12 +106,11 @@ impl Writer { // Write all structs for (handle, ty) in module.types.iter() { if let TypeInner::Struct { - top_level, ref members, - .. + span: _, } = ty.inner { - self.write_struct(module, handle, top_level, members)?; + self.write_struct(module, handle, members)?; writeln!(self.out)?; } } @@ -358,7 +356,6 @@ impl Writer { for (index, attribute) in attributes.iter().enumerate() { match *attribute { - Attribute::Block => write!(self.out, "block")?, Attribute::Location(id) => write!(self.out, "location({})", id)?, Attribute::BuiltIn(builtin_attrib) => { if let Some(builtin) = builtin_str(builtin_attrib) { @@ -432,14 +429,8 @@ impl Writer { &mut self, module: &Module, handle: Handle, - block: bool, members: &[crate::StructMember], ) -> BackendResult { - if block { - self.write_attributes(&[Attribute::Block], false)?; - writeln!(self.out)?; - } - write!(self.out, "struct ")?; self.write_struct_name(module, handle)?; write!(self.out, " {{")?; diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index acaa5c975..0bc44b101 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1141,11 +1141,7 @@ impl Parser { let ty = self.module.types.insert( Type { name: None, - inner: TypeInner::Struct { - top_level: false, - members, - span, - }, + inner: TypeInner::Struct { members, span }, }, Default::default(), ); diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 7a7b5e2f6..dd8ecbfea 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -120,11 +120,7 @@ pub fn calculate_offset( (align, align * columns as u32) } - TypeInner::Struct { - ref members, - top_level, - .. - } => { + TypeInner::Struct { ref members, .. } => { let mut span = 0; let mut align = 0; let mut members = members.clone(); @@ -148,11 +144,7 @@ pub fn calculate_offset( ty = types.insert( Type { name, - inner: TypeInner::Struct { - top_level, - members, - span, - }, + inner: TypeInner::Struct { members, span }, }, ty_span, ); diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 2cb4f43e0..4911d0734 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -501,7 +501,6 @@ impl<'source> ParsingContext<'source> { Type { name: Some(ty_name), inner: TypeInner::Struct { - top_level: true, members: members.clone(), span, }, diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 7fc74e2dd..ad537e959 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -61,11 +61,7 @@ impl<'source> ParsingContext<'source> { let ty = parser.module.types.insert( Type { name: Some(ty_name.clone()), - inner: TypeInner::Struct { - top_level: false, - members, - span, - }, + inner: TypeInner::Struct { members, span }, }, meta, ); diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index d85c61438..23c47688e 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -488,7 +488,6 @@ impl> super::Parser { crate::Type { name: None, inner: crate::TypeInner::Struct { - top_level: false, members, span: 0xFFFF, // shouldn't matter }, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 55a5691de..cd1721bbd 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -160,11 +160,6 @@ impl crate::ImageDimension { type MemberIndex = u32; -#[derive(Clone, Debug, Default, PartialEq)] -struct Block { - buffer: bool, -} - bitflags::bitflags! { #[derive(Default)] struct DecorationFlags: u32 { @@ -200,7 +195,7 @@ struct Decoration { desc_set: Option, desc_index: Option, specialization: Option, - block: Option, + storage_buffer: bool, offset: Option, array_stride: Option, matrix_stride: Option, @@ -663,11 +658,8 @@ impl> Parser { inst.expect(base_words + 2)?; dec.desc_index = Some(self.next()?); } - spirv::Decoration::Block => { - dec.block = Some(Block { buffer: false }); - } spirv::Decoration::BufferBlock => { - dec.block = Some(Block { buffer: true }); + dec.storage_buffer = true; } spirv::Decoration::Offset => { inst.expect(base_words + 2)?; @@ -4022,7 +4014,9 @@ impl> Parser { inst.expect_at_least(2)?; let id = self.next()?; let parent_decor = self.future_decor.remove(&id); - let block_decor = parent_decor.as_ref().and_then(|decor| decor.block.clone()); + let is_storage_buffer = parent_decor + .as_ref() + .map_or(false, |decor| decor.storage_buffer); self.layouter .update(&module.types, &module.constants) @@ -4097,11 +4091,7 @@ impl> Parser { span = crate::front::align_up(span, alignment); - let inner = crate::TypeInner::Struct { - top_level: block_decor.is_some(), - span, - members, - }; + let inner = crate::TypeInner::Struct { span, members }; let ty_handle = module.types.insert( crate::Type { @@ -4111,7 +4101,7 @@ impl> Parser { self.span_from_with_op(start), ); - if block_decor == Some(Block { buffer: true }) { + if is_storage_buffer { self.lookup_storage_buffer_types .insert(ty_handle, storage_access); } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 9dfc194f2..0e39ee176 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -629,7 +629,6 @@ mod type_inner_tests { crate::Type { name: Some("MyType1".to_string()), inner: crate::TypeInner::Struct { - top_level: true, members: vec![], span: 0, }, @@ -640,7 +639,6 @@ mod type_inner_tests { crate::Type { name: Some("MyType2".to_string()), inner: crate::TypeInner::Struct { - top_level: true, members: vec![], span: 0, }, @@ -3981,7 +3979,6 @@ impl Parser { let mut binding = None; // Perspective is the default qualifier. let mut stage = None; - let mut is_block = false; let mut workgroup_size = [0u32; 3]; let mut early_depth_test = None; @@ -3995,9 +3992,6 @@ impl Parser { bind_index = Some(parse_non_negative_sint_literal(lexer, 4)?); lexer.expect(Token::Paren(')'))?; } - ("block", _) => { - is_block = true; - } ("group", _) => { lexer.expect(Token::Paren('('))?; bind_group = Some(parse_non_negative_sint_literal(lexer, 4)?); @@ -4077,11 +4071,7 @@ impl Parser { let ty = module.types.insert( crate::Type { name: Some(name.to_string()), - inner: crate::TypeInner::Struct { - top_level: is_block, - members, - span, - }, + inner: crate::TypeInner::Struct { members, span }, }, type_span, ); diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 143432063..f64ac3036 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -157,7 +157,7 @@ fn parse_type_cast() { fn parse_struct() { parse_str( " - [[block]] struct Foo { x: i32; }; + struct Foo { x: i32; }; struct Bar { [[size(16)]] x: vec2; [[align(16)]] y: f32; @@ -397,7 +397,6 @@ fn parse_struct_instantiation() { fn parse_array_length() { parse_str( " - [[block]] struct Foo { data: [[stride(4)]] array; }; // this is used as both input and output for convenience diff --git a/src/lib.rs b/src/lib.rs index eea9d2e93..a2d2ec15a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -627,11 +627,10 @@ pub enum TypeInner { /// An `Array` is [`SIZED`] unless its `size` is [`Dynamic`]. /// Dynamically-sized arrays may only appear in a few situations: /// - /// - They may appear as the last member of a [`Struct`] whose `top_level` - /// flag is set. + /// - They may appear as the last member of a [`Struct`]. /// /// - They may appear as the base type of a [`Pointer`]. An - /// [`AccessIndex`] expression referring to a top-level struct's final + /// [`AccessIndex`] expression referring to a struct's final /// unsized array member would have such a pointer type. However, such /// pointer types may only appear as the types of such intermediate /// expressions. They are not [`DATA`], and cannot be stored in @@ -655,20 +654,13 @@ pub enum TypeInner { /// `DATA` as well. /// /// Member types must be [`SIZED`], except for the final member of a - /// top-level struct, which may be a dynamically sized [`Array`]. The + /// struct, which may be a dynamically sized [`Array`]. The /// `Struct` type itself is `SIZED` when all its members are `SIZED`. /// - /// When `top_level` is true, this `Struct` represents the contents of a - /// buffer resource occupying a single binding slot in a shader's resource - /// interface. Top-level `Struct`s may not be used as members of any other - /// struct, or as array elements. - /// /// [`DATA`]: crate::valid::TypeFlags::DATA /// [`SIZED`]: crate::valid::TypeFlags::SIZED /// [`Array`]: TypeInner::Array Struct { - /// This struct serves as the type of a binding slot in a shader's resource interface. - top_level: bool, members: Vec, //TODO: should this be unaligned? span: u32, diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 5facecdac..5f6559f08 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -118,11 +118,7 @@ impl Layouter { return Err(InvalidBaseType(base)); }, }, - Ti::Struct { - top_level: _, - span, - ref members, - } => { + Ti::Struct { span, ref members } => { let mut alignment = Alignment::new(1).unwrap(); for member in members { alignment = if member.ty < ty_handle { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 68326b8a8..1fabe5f3b 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -298,11 +298,7 @@ impl VaryingContext<'_> { None => { match self.types[self.ty].inner { //TODO: check the member types - crate::TypeInner::Struct { - top_level: false, - ref members, - .. - } => { + crate::TypeInner::Struct { ref members, .. } => { for (index, member) in members.iter().enumerate() { self.ty = member.ty; let span_context = self.types.get_span_context(self.ty); @@ -346,10 +342,7 @@ impl super::Validator { return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); } } - ( - TypeFlags::DATA | TypeFlags::HOST_SHARED | TypeFlags::TOP_LEVEL, - true, - ) + (TypeFlags::DATA | TypeFlags::HOST_SHARED, true) } crate::StorageClass::Uniform => { if let Err((ty_handle, disalignment)) = type_info.uniform_layout { @@ -358,11 +351,7 @@ impl super::Validator { } } ( - TypeFlags::DATA - | TypeFlags::COPY - | TypeFlags::SIZED - | TypeFlags::HOST_SHARED - | TypeFlags::TOP_LEVEL, + TypeFlags::DATA | TypeFlags::COPY | TypeFlags::SIZED | TypeFlags::HOST_SHARED, true, ) } diff --git a/src/valid/type.rs b/src/valid/type.rs index 923e1b24f..cda1fa64a 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -47,9 +47,6 @@ bitflags::bitflags! { /// Can be used for host-shareable structures. const HOST_SHARED = 0x10; - /// This is a top-level host-shareable type. - const TOP_LEVEL = 0x20; - /// This type can be passed as a function argument. const ARGUMENT = 0x40; } @@ -113,8 +110,6 @@ pub enum TypeError { size: u32, span: u32, }, - #[error("The composite type contains a top-level structure")] - NestedTopLevel, } // Only makes sense if `flags.contains(HOST_SHARED)` @@ -330,9 +325,6 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { return Err(TypeError::InvalidArrayBaseType(base)); } - if base_info.flags.contains(TypeFlags::TOP_LEVEL) { - return Err(TypeError::NestedTopLevel); - } let base_size = types[base].inner.span(constants); if stride < base_size { @@ -443,11 +435,7 @@ impl super::Validator { storage_layout, } } - Ti::Struct { - top_level, - ref members, - span, - } => { + Ti::Struct { ref members, span } => { let mut ti = TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED @@ -467,9 +455,6 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); } - if base_info.flags.contains(TypeFlags::TOP_LEVEL) { - return Err(TypeError::NestedTopLevel); - } if !base_info.flags.contains(TypeFlags::HOST_SHARED) { if ti.uniform_layout.is_ok() { ti.uniform_layout = Err((member.ty, Disalignment::NonHostShareable)); @@ -535,9 +520,6 @@ impl super::Validator { } } } - if top_level { - ti.flags |= TypeFlags::TOP_LEVEL; - } let alignment = self.layouter[handle].alignment.get(); if span % alignment != 0 { diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 034d0d5ab..e8ef082fb 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -1,6 +1,5 @@ // This snapshot tests accessing various containers, dereferencing pointers. -[[block]] struct Bar { matrix: mat4x4; atom: atomic; diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 0f89f9a20..5e712ac56 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -5,7 +5,6 @@ struct Particle { vel : vec2; }; -[[block]] struct SimParams { deltaT : f32; rule1Distance : f32; @@ -16,7 +15,6 @@ struct SimParams { rule3Scale : f32; }; -[[block]] struct Particles { particles : [[stride(16)]] array; }; diff --git a/tests/in/bounds-check-restrict.wgsl b/tests/in/bounds-check-restrict.wgsl index 6f4ae998d..8550fd703 100644 --- a/tests/in/bounds-check-restrict.wgsl +++ b/tests/in/bounds-check-restrict.wgsl @@ -1,6 +1,5 @@ // Tests for `naga::back::BoundsCheckPolicy::Restrict`. -[[block]] struct Globals { a: array; v: vec4; diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl index b4fbebcd7..4838701c2 100644 --- a/tests/in/bounds-check-zero.wgsl +++ b/tests/in/bounds-check-zero.wgsl @@ -1,6 +1,5 @@ // Tests for `naga::back::BoundsCheckPolicy::ReadZeroSkipWrite`. -[[block]] struct Globals { a: array; v: vec4; diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index 1db3b9115..878b18d09 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -1,4 +1,3 @@ -[[block]] struct PrimeIndices { data: [[stride(4)]] array; }; // this is used as both input and output for convenience diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index 9f9acb033..fa8c466c4 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -1,4 +1,3 @@ -[[block]] struct PushConstants { index: u32; double: vec2; diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl index e3160774c..cf365f390 100644 --- a/tests/in/pointers.wgsl +++ b/tests/in/pointers.wgsl @@ -4,7 +4,6 @@ fn f() { *px = 10; } -[[block]] struct DynamicArray { arr: array; }; diff --git a/tests/in/policy-mix.wgsl b/tests/in/policy-mix.wgsl index e9b55709c..4dc1e1bce 100644 --- a/tests/in/policy-mix.wgsl +++ b/tests/in/policy-mix.wgsl @@ -2,13 +2,11 @@ // implemented separately. // Storage and Uniform storage classes -[[block]] struct InStorage { a: array, 10>; }; [[group(0), binding(0)]] var in_storage: InStorage; -[[block]] struct InUniform { a: array, 20>; }; diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index d1286273c..f17f7af39 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -1,4 +1,3 @@ -[[block]] struct Globals { num_lights: vec4; }; @@ -12,7 +11,6 @@ struct Light { color: vec4; }; -[[block]] struct Lights { data: [[stride(96)]] array; }; diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index 33a110840..b21624853 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -3,7 +3,6 @@ struct VertexOutput { [[location(0)]] uv: vec3; }; -[[block]] struct Data { proj_inv: mat4x4; view: mat4x4; diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 0145ad498..19414a449 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -5,7 +5,7 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; -layout(std430) buffer Bar_block_0Cs { +layout(std430) buffer Bar_block_0Compute { mat4x4 matrix; int atom; uvec2 arr[2]; diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index d4502b031..dfdf2c013 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -3,7 +3,7 @@ precision highp float; precision highp int; -layout(std430) buffer Bar_block_0Vs { +layout(std430) buffer Bar_block_0Vertex { mat4x4 matrix; int atom; uvec2 arr[2]; diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 51bf0101f..e68cdc27e 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -9,8 +9,7 @@ struct Particle { vec2 pos; vec2 vel; }; - -uniform SimParams_block_0Cs { +struct SimParams { float deltaT; float rule1Distance; float rule2Distance; @@ -18,13 +17,14 @@ uniform SimParams_block_0Cs { float rule1Scale; float rule2Scale; float rule3Scale; -} _group_0_binding_0; +}; +uniform SimParams_block_0Compute { SimParams _group_0_binding_0; }; -layout(std430) readonly buffer Particles_block_1Cs { +layout(std430) readonly buffer Particles_block_1Compute { Particle particles[]; } _group_0_binding_1; -layout(std430) buffer Particles_block_2Cs { +layout(std430) buffer Particles_block_2Compute { Particle particles[]; } _group_0_binding_2; diff --git a/tests/out/glsl/interpolate.frag_main.Fragment.glsl b/tests/out/glsl/interpolate.frag_main.Fragment.glsl index 918e78b9c..1f35aebe6 100644 --- a/tests/out/glsl/interpolate.frag_main.Fragment.glsl +++ b/tests/out/glsl/interpolate.frag_main.Fragment.glsl @@ -9,7 +9,6 @@ struct FragmentInput { float perspective_centroid; float perspective_sample; }; - flat in uint _vs2fs_location0; noperspective in float _vs2fs_location1; noperspective centroid in vec2 _vs2fs_location2; diff --git a/tests/out/glsl/interpolate.main.Fragment.glsl b/tests/out/glsl/interpolate.main.Fragment.glsl deleted file mode 100644 index 918e78b9c..000000000 --- a/tests/out/glsl/interpolate.main.Fragment.glsl +++ /dev/null @@ -1,25 +0,0 @@ -#version 400 core -struct FragmentInput { - vec4 position; - uint flat_; - float linear; - vec2 linear_centroid; - vec3 linear_sample; - vec4 perspective; - float perspective_centroid; - float perspective_sample; -}; - -flat in uint _vs2fs_location0; -noperspective in float _vs2fs_location1; -noperspective centroid in vec2 _vs2fs_location2; -noperspective sample in vec3 _vs2fs_location3; -smooth in vec4 _vs2fs_location4; -smooth centroid in float _vs2fs_location5; -smooth sample in float _vs2fs_location6; - -void main() { - FragmentInput val = FragmentInput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1, _vs2fs_location2, _vs2fs_location3, _vs2fs_location4, _vs2fs_location5, _vs2fs_location6); - return; -} - diff --git a/tests/out/glsl/interpolate.main.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl deleted file mode 100644 index 40d64ccf0..000000000 --- a/tests/out/glsl/interpolate.main.Vertex.glsl +++ /dev/null @@ -1,42 +0,0 @@ -#version 400 core -struct FragmentInput { - vec4 position; - uint flat_; - float linear; - vec2 linear_centroid; - vec3 linear_sample; - vec4 perspective; - float perspective_centroid; - float perspective_sample; -}; - -flat out uint _vs2fs_location0; -noperspective out float _vs2fs_location1; -noperspective centroid out vec2 _vs2fs_location2; -noperspective sample out vec3 _vs2fs_location3; -smooth out vec4 _vs2fs_location4; -smooth centroid out float _vs2fs_location5; -smooth sample out float _vs2fs_location6; - -void main() { - FragmentInput out_; - out_.position = vec4(2.0, 4.0, 5.0, 6.0); - out_.flat_ = 8u; - out_.linear = 27.0; - out_.linear_centroid = vec2(64.0, 125.0); - out_.linear_sample = vec3(216.0, 343.0, 512.0); - out_.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); - out_.perspective_centroid = 2197.0; - out_.perspective_sample = 2744.0; - FragmentInput _e30 = out_; - gl_Position = _e30.position; - _vs2fs_location0 = _e30.flat_; - _vs2fs_location1 = _e30.linear; - _vs2fs_location2 = _e30.linear_centroid; - _vs2fs_location3 = _e30.linear_sample; - _vs2fs_location4 = _e30.perspective; - _vs2fs_location5 = _e30.perspective_centroid; - _vs2fs_location6 = _e30.perspective_sample; - return; -} - diff --git a/tests/out/glsl/interpolate.vert_main.Vertex.glsl b/tests/out/glsl/interpolate.vert_main.Vertex.glsl index 40d64ccf0..588b72ac6 100644 --- a/tests/out/glsl/interpolate.vert_main.Vertex.glsl +++ b/tests/out/glsl/interpolate.vert_main.Vertex.glsl @@ -9,7 +9,6 @@ struct FragmentInput { float perspective_centroid; float perspective_sample; }; - flat out uint _vs2fs_location0; noperspective out float _vs2fs_location1; noperspective centroid out vec2 _vs2fs_location2; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 39a284352..9a9fa5c89 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -10,7 +10,6 @@ struct Foo { int b; }; - vec4 builtins() { int s1_ = (true ? 1 : 0); vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index 26df41767..d3c740e05 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -3,21 +3,21 @@ precision highp float; precision highp int; -struct type_9 { - vec2 member; - vec4 gen_gl_Position; -}; - -vec2 v_uv = vec2(0.0, 0.0); - -vec2 a_uv_1 = vec2(0.0, 0.0); - -struct gen_gl_PerVertex_block_0Vs { +struct gen_gl_PerVertex { vec4 gen_gl_Position; float gen_gl_PointSize; float gen_gl_ClipDistance[1]; float gen_gl_CullDistance[1]; -} perVertexStruct; +}; +struct type_9 { + vec2 member; + vec4 gen_gl_Position; +}; +vec2 v_uv = vec2(0.0, 0.0); + +vec2 a_uv_1 = vec2(0.0, 0.0); + +gen_gl_PerVertex perVertexStruct; vec2 a_pos_1 = vec2(0.0, 0.0); diff --git a/tests/out/glsl/quad.frag_main.Fragment.glsl b/tests/out/glsl/quad.frag_main.Fragment.glsl index b290ed5a0..637f890f7 100644 --- a/tests/out/glsl/quad.frag_main.Fragment.glsl +++ b/tests/out/glsl/quad.frag_main.Fragment.glsl @@ -7,7 +7,6 @@ struct VertexOutput { vec2 uv; vec4 position; }; - uniform highp sampler2D _group_0_binding_0; smooth in vec2 _vs2fs_location0; diff --git a/tests/out/glsl/quad.fs_extra.Fragment.glsl b/tests/out/glsl/quad.fs_extra.Fragment.glsl index 9770ffb60..932fa76ba 100644 --- a/tests/out/glsl/quad.fs_extra.Fragment.glsl +++ b/tests/out/glsl/quad.fs_extra.Fragment.glsl @@ -7,7 +7,6 @@ struct VertexOutput { vec2 uv; vec4 position; }; - layout(location = 0) out vec4 _fs2p_location0; void main() { diff --git a/tests/out/glsl/quad.vert_main.Vertex.glsl b/tests/out/glsl/quad.vert_main.Vertex.glsl index cda43f508..5a1f432b2 100644 --- a/tests/out/glsl/quad.vert_main.Vertex.glsl +++ b/tests/out/glsl/quad.vert_main.Vertex.glsl @@ -7,7 +7,6 @@ struct VertexOutput { vec2 uv; vec4 position; }; - layout(location = 0) in vec2 _p2vs_location0; layout(location = 1) in vec2 _p2vs_location1; smooth out vec2 _vs2fs_location0; diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 7220591b9..594b250ea 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -3,17 +3,17 @@ precision highp float; precision highp int; +struct Globals { + uvec4 num_lights; +}; struct Light { mat4x4 proj; vec4 pos; vec4 color; }; +uniform Globals_block_0Fragment { Globals _group_0_binding_0; }; -uniform Globals_block_0Fs { - uvec4 num_lights; -} _group_0_binding_0; - -layout(std430) readonly buffer Lights_block_1Fs { +layout(std430) readonly buffer Lights_block_1Fragment { Light data[]; } _group_0_binding_1; diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index 08b733b84..916ea2c8a 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -7,7 +7,10 @@ struct VertexOutput { vec4 position; vec3 uv; }; - +struct Data { + mat4x4 proj_inv; + mat4x4 view; +}; layout(binding = 0) uniform highp samplerCube _group_0_binding_1; layout(location = 0) smooth in vec3 _vs2fs_location0; diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index 06494a70f..f7490130a 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -7,11 +7,11 @@ struct VertexOutput { vec4 position; vec3 uv; }; - -layout(std140, binding = 0) uniform Data_block_0Vs { +struct Data { mat4x4 proj_inv; mat4x4 view; -} _group_0_binding_0; +}; +layout(std140, binding = 0) uniform Data_block_0Vertex { Data _group_0_binding_0; }; layout(location = 0) smooth out vec3 _vs2fs_location0; diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index bd2e15ee3..5fff82ee3 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -18,7 +18,6 @@ ( name: Some("PrimeIndices"), inner: Struct( - top_level: true, members: [ ( name: Some("data"), diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 13220b7ae..0356f1371 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -94,7 +94,6 @@ ( name: Some("Globals"), inner: Struct( - top_level: true, members: [ ( name: Some("num_lights"), @@ -138,7 +137,6 @@ ( name: Some("Light"), inner: Struct( - top_level: false, members: [ ( name: Some("proj"), @@ -173,7 +171,6 @@ ( name: Some("Lights"), inner: Struct( - top_level: true, members: [ ( name: Some("data"), diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 96127247a..cd6fea537 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -26,7 +26,6 @@ OpName %90 "tmp" OpName %92 "atomics" OpDecorate %24 ArrayStride 8 OpDecorate %25 ArrayStride 8 -OpDecorate %26 Block OpMemberDecorate %26 0 Offset 0 OpMemberDecorate %26 0 ColMajor OpMemberDecorate %26 0 MatrixStride 16 @@ -36,6 +35,7 @@ OpMemberDecorate %26 3 Offset 88 OpDecorate %29 ArrayStride 4 OpDecorate %30 DescriptorSet 0 OpDecorate %30 Binding 0 +OpDecorate %26 Block OpDecorate %42 BuiltIn VertexIndex OpDecorate %45 BuiltIn Position %2 = OpTypeVoid diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 12d0cf69a..c8f589488 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 203 +; Bound: 206 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %43 "main" %40 -OpExecutionMode %43 LocalSize 64 1 1 +OpEntryPoint GLCompute %44 "main" %41 +OpExecutionMode %44 LocalSize 64 1 1 OpSource GLSL 450 OpName %3 "NUM_PARTICLES" OpMemberName %16 0 "pos" @@ -24,23 +24,22 @@ OpName %17 "SimParams" OpMemberName %19 0 "particles" OpName %19 "Particles" OpName %21 "params" -OpName %23 "particlesSrc" -OpName %25 "particlesDst" -OpName %26 "vPos" -OpName %28 "vVel" -OpName %29 "cMass" -OpName %30 "cVel" -OpName %31 "colVel" -OpName %32 "cMassCount" -OpName %34 "cVelCount" -OpName %35 "pos" -OpName %36 "vel" -OpName %37 "i" -OpName %40 "global_invocation_id" -OpName %43 "main" +OpName %24 "particlesSrc" +OpName %26 "particlesDst" +OpName %27 "vPos" +OpName %29 "vVel" +OpName %30 "cMass" +OpName %31 "cVel" +OpName %32 "colVel" +OpName %33 "cMassCount" +OpName %35 "cVelCount" +OpName %36 "pos" +OpName %37 "vel" +OpName %38 "i" +OpName %41 "global_invocation_id" +OpName %44 "main" OpMemberDecorate %16 0 Offset 0 OpMemberDecorate %16 1 Offset 8 -OpDecorate %17 Block OpMemberDecorate %17 0 Offset 0 OpMemberDecorate %17 1 Offset 4 OpMemberDecorate %17 2 Offset 8 @@ -49,16 +48,19 @@ OpMemberDecorate %17 4 Offset 16 OpMemberDecorate %17 5 Offset 20 OpMemberDecorate %17 6 Offset 24 OpDecorate %18 ArrayStride 16 -OpDecorate %19 Block OpMemberDecorate %19 0 Offset 0 OpDecorate %21 DescriptorSet 0 OpDecorate %21 Binding 0 -OpDecorate %23 NonWritable -OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 1 -OpDecorate %25 DescriptorSet 0 -OpDecorate %25 Binding 2 -OpDecorate %40 BuiltIn GlobalInvocationId +OpDecorate %22 Block +OpMemberDecorate %22 0 Offset 0 +OpDecorate %24 NonWritable +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 1 +OpDecorate %19 Block +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 2 +OpDecorate %19 Block +OpDecorate %41 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 1500 @@ -78,253 +80,256 @@ OpDecorate %40 BuiltIn GlobalInvocationId %18 = OpTypeRuntimeArray %16 %19 = OpTypeStruct %18 %20 = OpTypeVector %4 3 -%22 = OpTypePointer Uniform %17 -%21 = OpVariable %22 Uniform -%24 = OpTypePointer StorageBuffer %19 -%23 = OpVariable %24 StorageBuffer -%25 = OpVariable %24 StorageBuffer -%27 = OpTypePointer Function %15 -%33 = OpTypePointer Function %8 -%38 = OpTypePointer Function %4 -%41 = OpTypePointer Input %20 -%40 = OpVariable %41 Input -%44 = OpTypeFunction %2 -%47 = OpTypeBool -%51 = OpTypePointer StorageBuffer %18 -%52 = OpTypePointer StorageBuffer %16 -%53 = OpTypePointer StorageBuffer %15 -%82 = OpTypePointer Uniform %6 -%96 = OpConstant %4 2 -%110 = OpConstant %4 3 -%145 = OpConstant %4 4 -%151 = OpConstant %4 5 -%157 = OpConstant %4 6 -%174 = OpTypePointer Function %6 -%43 = OpFunction %2 None %44 -%39 = OpLabel -%37 = OpVariable %38 Function %9 -%34 = OpVariable %33 Function %7 -%30 = OpVariable %27 Function -%26 = OpVariable %27 Function -%35 = OpVariable %27 Function -%31 = OpVariable %27 Function -%28 = OpVariable %27 Function -%36 = OpVariable %27 Function -%32 = OpVariable %33 Function %7 -%29 = OpVariable %27 Function -%42 = OpLoad %20 %40 -OpBranch %45 -%45 = OpLabel -%46 = OpCompositeExtract %4 %42 0 -%48 = OpUGreaterThanEqual %47 %46 %3 -OpSelectionMerge %49 None -OpBranchConditional %48 %50 %49 -%50 = OpLabel +%22 = OpTypeStruct %17 +%23 = OpTypePointer Uniform %22 +%21 = OpVariable %23 Uniform +%25 = OpTypePointer StorageBuffer %19 +%24 = OpVariable %25 StorageBuffer +%26 = OpVariable %25 StorageBuffer +%28 = OpTypePointer Function %15 +%34 = OpTypePointer Function %8 +%39 = OpTypePointer Function %4 +%42 = OpTypePointer Input %20 +%41 = OpVariable %42 Input +%45 = OpTypeFunction %2 +%46 = OpTypePointer Uniform %17 +%50 = OpTypeBool +%54 = OpTypePointer StorageBuffer %18 +%55 = OpTypePointer StorageBuffer %16 +%56 = OpTypePointer StorageBuffer %15 +%85 = OpTypePointer Uniform %6 +%99 = OpConstant %4 2 +%113 = OpConstant %4 3 +%148 = OpConstant %4 4 +%154 = OpConstant %4 5 +%160 = OpConstant %4 6 +%177 = OpTypePointer Function %6 +%44 = OpFunction %2 None %45 +%40 = OpLabel +%38 = OpVariable %39 Function %9 +%35 = OpVariable %34 Function %7 +%31 = OpVariable %28 Function +%27 = OpVariable %28 Function +%36 = OpVariable %28 Function +%32 = OpVariable %28 Function +%29 = OpVariable %28 Function +%37 = OpVariable %28 Function +%33 = OpVariable %34 Function %7 +%30 = OpVariable %28 Function +%43 = OpLoad %20 %41 +%47 = OpAccessChain %46 %21 %9 +OpBranch %48 +%48 = OpLabel +%49 = OpCompositeExtract %4 %43 0 +%51 = OpUGreaterThanEqual %50 %49 %3 +OpSelectionMerge %52 None +OpBranchConditional %51 %53 %52 +%53 = OpLabel OpReturn -%49 = OpLabel -%54 = OpAccessChain %53 %23 %9 %46 %9 -%55 = OpLoad %15 %54 -OpStore %26 %55 -%56 = OpAccessChain %53 %23 %9 %46 %11 -%57 = OpLoad %15 %56 -OpStore %28 %57 -%58 = OpCompositeConstruct %15 %5 %5 -OpStore %29 %58 -%59 = OpCompositeConstruct %15 %5 %5 -OpStore %30 %59 -%60 = OpCompositeConstruct %15 %5 %5 -OpStore %31 %60 -OpBranch %61 -%61 = OpLabel -OpLoopMerge %62 %64 None -OpBranch %63 -%63 = OpLabel -%65 = OpLoad %4 %37 -%66 = OpUGreaterThanEqual %47 %65 %3 -OpSelectionMerge %67 None -OpBranchConditional %66 %68 %67 -%68 = OpLabel -OpBranch %62 -%67 = OpLabel -%69 = OpLoad %4 %37 -%70 = OpIEqual %47 %69 %46 -OpSelectionMerge %71 None -OpBranchConditional %70 %72 %71 -%72 = OpLabel -OpBranch %64 -%71 = OpLabel -%73 = OpLoad %4 %37 -%74 = OpAccessChain %53 %23 %9 %73 %9 -%75 = OpLoad %15 %74 -OpStore %35 %75 -%76 = OpLoad %4 %37 -%77 = OpAccessChain %53 %23 %9 %76 %11 -%78 = OpLoad %15 %77 -OpStore %36 %78 -%79 = OpLoad %15 %35 -%80 = OpLoad %15 %26 -%81 = OpExtInst %6 %1 Distance %79 %80 -%83 = OpAccessChain %82 %21 %11 -%84 = OpLoad %6 %83 -%85 = OpFOrdLessThan %47 %81 %84 -OpSelectionMerge %86 None -OpBranchConditional %85 %87 %86 -%87 = OpLabel -%88 = OpLoad %15 %29 -%89 = OpLoad %15 %35 -%90 = OpFAdd %15 %88 %89 -OpStore %29 %90 -%91 = OpLoad %8 %32 -%92 = OpIAdd %8 %91 %10 -OpStore %32 %92 -OpBranch %86 -%86 = OpLabel -%93 = OpLoad %15 %35 -%94 = OpLoad %15 %26 -%95 = OpExtInst %6 %1 Distance %93 %94 -%97 = OpAccessChain %82 %21 %96 -%98 = OpLoad %6 %97 -%99 = OpFOrdLessThan %47 %95 %98 -OpSelectionMerge %100 None -OpBranchConditional %99 %101 %100 -%101 = OpLabel -%102 = OpLoad %15 %31 -%103 = OpLoad %15 %35 -%104 = OpLoad %15 %26 -%105 = OpFSub %15 %103 %104 -%106 = OpFSub %15 %102 %105 -OpStore %31 %106 -OpBranch %100 -%100 = OpLabel -%107 = OpLoad %15 %35 -%108 = OpLoad %15 %26 -%109 = OpExtInst %6 %1 Distance %107 %108 -%111 = OpAccessChain %82 %21 %110 -%112 = OpLoad %6 %111 -%113 = OpFOrdLessThan %47 %109 %112 -OpSelectionMerge %114 None -OpBranchConditional %113 %115 %114 -%115 = OpLabel -%116 = OpLoad %15 %30 -%117 = OpLoad %15 %36 -%118 = OpFAdd %15 %116 %117 -OpStore %30 %118 -%119 = OpLoad %8 %34 -%120 = OpIAdd %8 %119 %10 -OpStore %34 %120 -OpBranch %114 -%114 = OpLabel +%52 = OpLabel +%57 = OpAccessChain %56 %24 %9 %49 %9 +%58 = OpLoad %15 %57 +OpStore %27 %58 +%59 = OpAccessChain %56 %24 %9 %49 %11 +%60 = OpLoad %15 %59 +OpStore %29 %60 +%61 = OpCompositeConstruct %15 %5 %5 +OpStore %30 %61 +%62 = OpCompositeConstruct %15 %5 %5 +OpStore %31 %62 +%63 = OpCompositeConstruct %15 %5 %5 +OpStore %32 %63 OpBranch %64 %64 = OpLabel -%121 = OpLoad %4 %37 -%122 = OpIAdd %4 %121 %11 -OpStore %37 %122 -OpBranch %61 -%62 = OpLabel -%123 = OpLoad %8 %32 -%124 = OpSGreaterThan %47 %123 %7 -OpSelectionMerge %125 None -OpBranchConditional %124 %126 %125 -%126 = OpLabel -%127 = OpLoad %15 %29 -%128 = OpLoad %8 %32 -%129 = OpConvertSToF %6 %128 -%130 = OpCompositeConstruct %15 %129 %129 -%131 = OpFDiv %15 %127 %130 -%132 = OpLoad %15 %26 -%133 = OpFSub %15 %131 %132 -OpStore %29 %133 -OpBranch %125 -%125 = OpLabel -%134 = OpLoad %8 %34 -%135 = OpSGreaterThan %47 %134 %7 -OpSelectionMerge %136 None -OpBranchConditional %135 %137 %136 -%137 = OpLabel -%138 = OpLoad %15 %30 -%139 = OpLoad %8 %34 -%140 = OpConvertSToF %6 %139 -%141 = OpCompositeConstruct %15 %140 %140 -%142 = OpFDiv %15 %138 %141 -OpStore %30 %142 -OpBranch %136 -%136 = OpLabel -%143 = OpLoad %15 %28 -%144 = OpLoad %15 %29 -%146 = OpAccessChain %82 %21 %145 -%147 = OpLoad %6 %146 -%148 = OpVectorTimesScalar %15 %144 %147 -%149 = OpFAdd %15 %143 %148 -%150 = OpLoad %15 %31 -%152 = OpAccessChain %82 %21 %151 -%153 = OpLoad %6 %152 -%154 = OpVectorTimesScalar %15 %150 %153 -%155 = OpFAdd %15 %149 %154 -%156 = OpLoad %15 %30 -%158 = OpAccessChain %82 %21 %157 -%159 = OpLoad %6 %158 -%160 = OpVectorTimesScalar %15 %156 %159 -%161 = OpFAdd %15 %155 %160 -OpStore %28 %161 -%162 = OpLoad %15 %28 -%163 = OpExtInst %15 %1 Normalize %162 -%164 = OpLoad %15 %28 -%165 = OpExtInst %6 %1 Length %164 -%166 = OpExtInst %6 %1 FClamp %165 %5 %12 -%167 = OpVectorTimesScalar %15 %163 %166 -OpStore %28 %167 -%168 = OpLoad %15 %26 -%169 = OpLoad %15 %28 -%170 = OpAccessChain %82 %21 %9 -%171 = OpLoad %6 %170 -%172 = OpVectorTimesScalar %15 %169 %171 -%173 = OpFAdd %15 %168 %172 -OpStore %26 %173 -%175 = OpAccessChain %174 %26 %9 -%176 = OpLoad %6 %175 -%177 = OpFOrdLessThan %47 %176 %13 -OpSelectionMerge %178 None -OpBranchConditional %177 %179 %178 -%179 = OpLabel -%180 = OpAccessChain %174 %26 %9 -OpStore %180 %14 -OpBranch %178 -%178 = OpLabel -%181 = OpAccessChain %174 %26 %9 -%182 = OpLoad %6 %181 -%183 = OpFOrdGreaterThan %47 %182 %14 -OpSelectionMerge %184 None -OpBranchConditional %183 %185 %184 -%185 = OpLabel -%186 = OpAccessChain %174 %26 %9 -OpStore %186 %13 -OpBranch %184 -%184 = OpLabel -%187 = OpAccessChain %174 %26 %11 -%188 = OpLoad %6 %187 -%189 = OpFOrdLessThan %47 %188 %13 -OpSelectionMerge %190 None -OpBranchConditional %189 %191 %190 -%191 = OpLabel -%192 = OpAccessChain %174 %26 %11 -OpStore %192 %14 -OpBranch %190 -%190 = OpLabel -%193 = OpAccessChain %174 %26 %11 -%194 = OpLoad %6 %193 -%195 = OpFOrdGreaterThan %47 %194 %14 -OpSelectionMerge %196 None -OpBranchConditional %195 %197 %196 -%197 = OpLabel -%198 = OpAccessChain %174 %26 %11 -OpStore %198 %13 -OpBranch %196 -%196 = OpLabel -%199 = OpLoad %15 %26 -%200 = OpAccessChain %53 %25 %9 %46 %9 -OpStore %200 %199 -%201 = OpLoad %15 %28 -%202 = OpAccessChain %53 %25 %9 %46 %11 -OpStore %202 %201 +OpLoopMerge %65 %67 None +OpBranch %66 +%66 = OpLabel +%68 = OpLoad %4 %38 +%69 = OpUGreaterThanEqual %50 %68 %3 +OpSelectionMerge %70 None +OpBranchConditional %69 %71 %70 +%71 = OpLabel +OpBranch %65 +%70 = OpLabel +%72 = OpLoad %4 %38 +%73 = OpIEqual %50 %72 %49 +OpSelectionMerge %74 None +OpBranchConditional %73 %75 %74 +%75 = OpLabel +OpBranch %67 +%74 = OpLabel +%76 = OpLoad %4 %38 +%77 = OpAccessChain %56 %24 %9 %76 %9 +%78 = OpLoad %15 %77 +OpStore %36 %78 +%79 = OpLoad %4 %38 +%80 = OpAccessChain %56 %24 %9 %79 %11 +%81 = OpLoad %15 %80 +OpStore %37 %81 +%82 = OpLoad %15 %36 +%83 = OpLoad %15 %27 +%84 = OpExtInst %6 %1 Distance %82 %83 +%86 = OpAccessChain %85 %47 %11 +%87 = OpLoad %6 %86 +%88 = OpFOrdLessThan %50 %84 %87 +OpSelectionMerge %89 None +OpBranchConditional %88 %90 %89 +%90 = OpLabel +%91 = OpLoad %15 %30 +%92 = OpLoad %15 %36 +%93 = OpFAdd %15 %91 %92 +OpStore %30 %93 +%94 = OpLoad %8 %33 +%95 = OpIAdd %8 %94 %10 +OpStore %33 %95 +OpBranch %89 +%89 = OpLabel +%96 = OpLoad %15 %36 +%97 = OpLoad %15 %27 +%98 = OpExtInst %6 %1 Distance %96 %97 +%100 = OpAccessChain %85 %47 %99 +%101 = OpLoad %6 %100 +%102 = OpFOrdLessThan %50 %98 %101 +OpSelectionMerge %103 None +OpBranchConditional %102 %104 %103 +%104 = OpLabel +%105 = OpLoad %15 %32 +%106 = OpLoad %15 %36 +%107 = OpLoad %15 %27 +%108 = OpFSub %15 %106 %107 +%109 = OpFSub %15 %105 %108 +OpStore %32 %109 +OpBranch %103 +%103 = OpLabel +%110 = OpLoad %15 %36 +%111 = OpLoad %15 %27 +%112 = OpExtInst %6 %1 Distance %110 %111 +%114 = OpAccessChain %85 %47 %113 +%115 = OpLoad %6 %114 +%116 = OpFOrdLessThan %50 %112 %115 +OpSelectionMerge %117 None +OpBranchConditional %116 %118 %117 +%118 = OpLabel +%119 = OpLoad %15 %31 +%120 = OpLoad %15 %37 +%121 = OpFAdd %15 %119 %120 +OpStore %31 %121 +%122 = OpLoad %8 %35 +%123 = OpIAdd %8 %122 %10 +OpStore %35 %123 +OpBranch %117 +%117 = OpLabel +OpBranch %67 +%67 = OpLabel +%124 = OpLoad %4 %38 +%125 = OpIAdd %4 %124 %11 +OpStore %38 %125 +OpBranch %64 +%65 = OpLabel +%126 = OpLoad %8 %33 +%127 = OpSGreaterThan %50 %126 %7 +OpSelectionMerge %128 None +OpBranchConditional %127 %129 %128 +%129 = OpLabel +%130 = OpLoad %15 %30 +%131 = OpLoad %8 %33 +%132 = OpConvertSToF %6 %131 +%133 = OpCompositeConstruct %15 %132 %132 +%134 = OpFDiv %15 %130 %133 +%135 = OpLoad %15 %27 +%136 = OpFSub %15 %134 %135 +OpStore %30 %136 +OpBranch %128 +%128 = OpLabel +%137 = OpLoad %8 %35 +%138 = OpSGreaterThan %50 %137 %7 +OpSelectionMerge %139 None +OpBranchConditional %138 %140 %139 +%140 = OpLabel +%141 = OpLoad %15 %31 +%142 = OpLoad %8 %35 +%143 = OpConvertSToF %6 %142 +%144 = OpCompositeConstruct %15 %143 %143 +%145 = OpFDiv %15 %141 %144 +OpStore %31 %145 +OpBranch %139 +%139 = OpLabel +%146 = OpLoad %15 %29 +%147 = OpLoad %15 %30 +%149 = OpAccessChain %85 %47 %148 +%150 = OpLoad %6 %149 +%151 = OpVectorTimesScalar %15 %147 %150 +%152 = OpFAdd %15 %146 %151 +%153 = OpLoad %15 %32 +%155 = OpAccessChain %85 %47 %154 +%156 = OpLoad %6 %155 +%157 = OpVectorTimesScalar %15 %153 %156 +%158 = OpFAdd %15 %152 %157 +%159 = OpLoad %15 %31 +%161 = OpAccessChain %85 %47 %160 +%162 = OpLoad %6 %161 +%163 = OpVectorTimesScalar %15 %159 %162 +%164 = OpFAdd %15 %158 %163 +OpStore %29 %164 +%165 = OpLoad %15 %29 +%166 = OpExtInst %15 %1 Normalize %165 +%167 = OpLoad %15 %29 +%168 = OpExtInst %6 %1 Length %167 +%169 = OpExtInst %6 %1 FClamp %168 %5 %12 +%170 = OpVectorTimesScalar %15 %166 %169 +OpStore %29 %170 +%171 = OpLoad %15 %27 +%172 = OpLoad %15 %29 +%173 = OpAccessChain %85 %47 %9 +%174 = OpLoad %6 %173 +%175 = OpVectorTimesScalar %15 %172 %174 +%176 = OpFAdd %15 %171 %175 +OpStore %27 %176 +%178 = OpAccessChain %177 %27 %9 +%179 = OpLoad %6 %178 +%180 = OpFOrdLessThan %50 %179 %13 +OpSelectionMerge %181 None +OpBranchConditional %180 %182 %181 +%182 = OpLabel +%183 = OpAccessChain %177 %27 %9 +OpStore %183 %14 +OpBranch %181 +%181 = OpLabel +%184 = OpAccessChain %177 %27 %9 +%185 = OpLoad %6 %184 +%186 = OpFOrdGreaterThan %50 %185 %14 +OpSelectionMerge %187 None +OpBranchConditional %186 %188 %187 +%188 = OpLabel +%189 = OpAccessChain %177 %27 %9 +OpStore %189 %13 +OpBranch %187 +%187 = OpLabel +%190 = OpAccessChain %177 %27 %11 +%191 = OpLoad %6 %190 +%192 = OpFOrdLessThan %50 %191 %13 +OpSelectionMerge %193 None +OpBranchConditional %192 %194 %193 +%194 = OpLabel +%195 = OpAccessChain %177 %27 %11 +OpStore %195 %14 +OpBranch %193 +%193 = OpLabel +%196 = OpAccessChain %177 %27 %11 +%197 = OpLoad %6 %196 +%198 = OpFOrdGreaterThan %50 %197 %14 +OpSelectionMerge %199 None +OpBranchConditional %198 %200 %199 +%200 = OpLabel +%201 = OpAccessChain %177 %27 %11 +OpStore %201 %13 +OpBranch %199 +%199 = OpLabel +%202 = OpLoad %15 %27 +%203 = OpAccessChain %56 %26 %9 %49 %9 +OpStore %203 %202 +%204 = OpLoad %15 %29 +%205 = OpAccessChain %56 %26 %9 %49 %11 +OpStore %205 %204 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-restrict.spvasm b/tests/out/spv/bounds-check-restrict.spvasm index 1f83ea976..192712346 100644 --- a/tests/out/spv/bounds-check-restrict.spvasm +++ b/tests/out/spv/bounds-check-restrict.spvasm @@ -9,7 +9,6 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpDecorate %10 ArrayStride 4 OpDecorate %13 ArrayStride 4 -OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %14 1 Offset 48 OpMemberDecorate %14 2 Offset 64 @@ -18,6 +17,7 @@ OpMemberDecorate %14 2 MatrixStride 16 OpMemberDecorate %14 3 Offset 112 OpDecorate %15 DescriptorSet 0 OpDecorate %15 Binding 0 +OpDecorate %14 Block %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index 82138feeb..5e5aac07f 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -9,7 +9,6 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpDecorate %10 ArrayStride 4 OpDecorate %13 ArrayStride 4 -OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %14 1 Offset 48 OpMemberDecorate %14 2 Offset 64 @@ -18,6 +17,7 @@ OpMemberDecorate %14 2 MatrixStride 16 OpMemberDecorate %14 3 Offset 112 OpDecorate %15 DescriptorSet 0 OpDecorate %15 Binding 0 +OpDecorate %14 Block %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index fd2065bb5..bd2dd1f5f 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -19,10 +19,10 @@ OpName %18 "collatz_iterations" OpName %45 "global_id" OpName %48 "main" OpDecorate %8 ArrayStride 4 -OpDecorate %9 Block OpMemberDecorate %9 0 Offset 0 OpDecorate %11 DescriptorSet 0 OpDecorate %11 Binding 0 +OpDecorate %9 Block OpDecorate %45 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index 6f6f153a3..f17b286ac 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -9,7 +9,6 @@ OpCapability Geometry OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %25 "main" %17 %20 %23 OpExecutionMode %25 OriginUpperLeft -OpDecorate %10 Block OpMemberDecorate %10 0 Offset 0 OpMemberDecorate %10 1 Offset 16 OpMemberDecorate %12 0 Offset 0 diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index 661a8e2c2..968720f9d 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -20,10 +20,10 @@ OpName %33 "i" OpName %34 "v" OpName %35 "index_dynamic_array" OpDecorate %7 ArrayStride 4 -OpDecorate %8 Block OpMemberDecorate %8 0 Offset 0 OpDecorate %11 DescriptorSet 0 OpDecorate %11 Binding 0 +OpDecorate %8 Block %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index 1e34e65e6..685acfeaa 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 93 +; Bound: 99 OpCapability Shader OpCapability ImageQuery OpCapability Linkage @@ -14,20 +14,18 @@ OpName %15 "InStorage" OpMemberName %17 0 "a" OpName %17 "InUniform" OpName %23 "in_storage" -OpName %25 "in_uniform" -OpName %27 "image_2d_array" -OpName %29 "in_workgroup" -OpName %31 "in_private" -OpName %33 "in_function" -OpName %36 "c" -OpName %37 "i" -OpName %38 "l" -OpName %39 "mock_function" +OpName %26 "in_uniform" +OpName %29 "image_2d_array" +OpName %31 "in_workgroup" +OpName %33 "in_private" +OpName %35 "in_function" +OpName %38 "c" +OpName %39 "i" +OpName %40 "l" +OpName %41 "mock_function" OpDecorate %14 ArrayStride 16 -OpDecorate %15 Block OpMemberDecorate %15 0 Offset 0 OpDecorate %16 ArrayStride 16 -OpDecorate %17 Block OpMemberDecorate %17 0 Offset 0 OpDecorate %19 ArrayStride 4 OpDecorate %20 ArrayStride 4 @@ -35,10 +33,14 @@ OpDecorate %22 ArrayStride 16 OpDecorate %23 NonWritable OpDecorate %23 DescriptorSet 0 OpDecorate %23 Binding 0 -OpDecorate %25 DescriptorSet 0 -OpDecorate %25 Binding 1 -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 2 +OpDecorate %24 Block +OpMemberDecorate %24 0 Offset 0 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 1 +OpDecorate %27 Block +OpMemberDecorate %27 0 Offset 0 +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 2 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -60,81 +62,87 @@ OpDecorate %27 Binding 2 %20 = OpTypeArray %10 %7 %21 = OpTypeVector %4 2 %22 = OpTypeArray %13 %8 -%24 = OpTypePointer StorageBuffer %15 -%23 = OpVariable %24 StorageBuffer -%26 = OpTypePointer Uniform %17 -%25 = OpVariable %26 Uniform -%28 = OpTypePointer UniformConstant %18 -%27 = OpVariable %28 UniformConstant -%30 = OpTypePointer Workgroup %19 -%29 = OpVariable %30 Workgroup -%32 = OpTypePointer Private %20 -%31 = OpVariable %32 Private -%34 = OpTypePointer Function %22 -%40 = OpTypeFunction %13 %21 %4 %4 -%46 = OpTypePointer StorageBuffer %14 -%47 = OpTypePointer StorageBuffer %13 -%49 = OpTypeInt 32 0 -%48 = OpConstant %49 0 -%52 = OpTypePointer Uniform %16 -%53 = OpTypePointer Uniform %13 -%57 = OpTypeVector %4 3 -%59 = OpTypeBool -%60 = OpConstantNull %13 -%66 = OpTypeVector %59 3 -%73 = OpTypePointer Workgroup %10 -%74 = OpConstant %49 29 -%80 = OpTypePointer Private %10 -%81 = OpConstant %49 39 -%87 = OpTypePointer Function %13 -%88 = OpConstant %49 1 -%39 = OpFunction %13 None %40 -%36 = OpFunctionParameter %21 -%37 = OpFunctionParameter %4 -%38 = OpFunctionParameter %4 -%35 = OpLabel -%33 = OpVariable %34 Function -%41 = OpLoad %18 %27 -OpBranch %42 -%42 = OpLabel -%43 = OpCompositeConstruct %13 %9 %11 %11 %12 -%44 = OpCompositeConstruct %13 %11 %9 %11 %12 -%45 = OpCompositeConstruct %22 %43 %44 -OpStore %33 %45 -%50 = OpAccessChain %47 %23 %48 %37 -%51 = OpLoad %13 %50 -%54 = OpAccessChain %53 %25 %48 %37 -%55 = OpLoad %13 %54 -%56 = OpFAdd %13 %51 %55 -%58 = OpCompositeConstruct %57 %36 %37 -%61 = OpImageQueryLevels %4 %41 -%62 = OpULessThan %59 %38 %61 -OpSelectionMerge %63 None -OpBranchConditional %62 %64 %63 -%64 = OpLabel -%65 = OpImageQuerySizeLod %57 %41 %38 -%67 = OpULessThan %66 %58 %65 -%68 = OpAll %59 %67 -OpBranchConditional %68 %69 %63 +%24 = OpTypeStruct %15 +%25 = OpTypePointer StorageBuffer %24 +%23 = OpVariable %25 StorageBuffer +%27 = OpTypeStruct %17 +%28 = OpTypePointer Uniform %27 +%26 = OpVariable %28 Uniform +%30 = OpTypePointer UniformConstant %18 +%29 = OpVariable %30 UniformConstant +%32 = OpTypePointer Workgroup %19 +%31 = OpVariable %32 Workgroup +%34 = OpTypePointer Private %20 +%33 = OpVariable %34 Private +%36 = OpTypePointer Function %22 +%42 = OpTypeFunction %13 %21 %4 %4 +%43 = OpTypePointer StorageBuffer %15 +%45 = OpTypeInt 32 0 +%44 = OpConstant %45 0 +%47 = OpTypePointer Uniform %17 +%54 = OpTypePointer StorageBuffer %14 +%55 = OpTypePointer StorageBuffer %13 +%58 = OpTypePointer Uniform %16 +%59 = OpTypePointer Uniform %13 +%63 = OpTypeVector %4 3 +%65 = OpTypeBool +%66 = OpConstantNull %13 +%72 = OpTypeVector %65 3 +%79 = OpTypePointer Workgroup %10 +%80 = OpConstant %45 29 +%86 = OpTypePointer Private %10 +%87 = OpConstant %45 39 +%93 = OpTypePointer Function %13 +%94 = OpConstant %45 1 +%41 = OpFunction %13 None %42 +%38 = OpFunctionParameter %21 +%39 = OpFunctionParameter %4 +%40 = OpFunctionParameter %4 +%37 = OpLabel +%35 = OpVariable %36 Function +%46 = OpAccessChain %43 %23 %44 +%48 = OpAccessChain %47 %26 %44 +%49 = OpLoad %18 %29 +OpBranch %50 +%50 = OpLabel +%51 = OpCompositeConstruct %13 %9 %11 %11 %12 +%52 = OpCompositeConstruct %13 %11 %9 %11 %12 +%53 = OpCompositeConstruct %22 %51 %52 +OpStore %35 %53 +%56 = OpAccessChain %55 %46 %44 %39 +%57 = OpLoad %13 %56 +%60 = OpAccessChain %59 %48 %44 %39 +%61 = OpLoad %13 %60 +%62 = OpFAdd %13 %57 %61 +%64 = OpCompositeConstruct %63 %38 %39 +%67 = OpImageQueryLevels %4 %49 +%68 = OpULessThan %65 %40 %67 +OpSelectionMerge %69 None +OpBranchConditional %68 %70 %69 +%70 = OpLabel +%71 = OpImageQuerySizeLod %63 %49 %40 +%73 = OpULessThan %72 %64 %71 +%74 = OpAll %65 %73 +OpBranchConditional %74 %75 %69 +%75 = OpLabel +%76 = OpImageFetch %13 %49 %64 Lod %40 +OpBranch %69 %69 = OpLabel -%70 = OpImageFetch %13 %41 %58 Lod %38 -OpBranch %63 -%63 = OpLabel -%71 = OpPhi %13 %60 %42 %60 %64 %70 %69 -%72 = OpFAdd %13 %56 %71 -%75 = OpExtInst %49 %1 UMin %37 %74 -%76 = OpAccessChain %73 %29 %75 -%77 = OpLoad %10 %76 -%78 = OpCompositeConstruct %13 %77 %77 %77 %77 -%79 = OpFAdd %13 %72 %78 -%82 = OpExtInst %49 %1 UMin %37 %81 -%83 = OpAccessChain %80 %31 %82 -%84 = OpLoad %10 %83 -%85 = OpCompositeConstruct %13 %84 %84 %84 %84 -%86 = OpFAdd %13 %79 %85 -%89 = OpExtInst %49 %1 UMin %37 %88 -%90 = OpAccessChain %87 %33 %89 -%91 = OpLoad %13 %90 -%92 = OpFAdd %13 %86 %91 -OpReturnValue %92 +%77 = OpPhi %13 %66 %50 %66 %70 %76 %75 +%78 = OpFAdd %13 %62 %77 +%81 = OpExtInst %45 %1 UMin %39 %80 +%82 = OpAccessChain %79 %31 %81 +%83 = OpLoad %10 %82 +%84 = OpCompositeConstruct %13 %83 %83 %83 %83 +%85 = OpFAdd %13 %78 %84 +%88 = OpExtInst %45 %1 UMin %39 %87 +%89 = OpAccessChain %86 %33 %88 +%90 = OpLoad %10 %89 +%91 = OpCompositeConstruct %13 %90 %90 %90 %90 +%92 = OpFAdd %13 %85 %91 +%95 = OpExtInst %45 %1 UMin %39 %94 +%96 = OpAccessChain %93 %35 %95 +%97 = OpLoad %13 %96 +%98 = OpFAdd %13 %92 %97 +OpReturnValue %98 OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index a0554ed94..3d4f4119a 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 122 +; Bound: 125 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %77 "fs_main" %69 %72 %75 -OpExecutionMode %77 OriginUpperLeft +OpEntryPoint Fragment %79 "fs_main" %71 %74 %77 +OpExecutionMode %79 OriginUpperLeft OpSource GLSL 450 OpName %9 "c_max_lights" OpMemberName %14 0 "num_lights" @@ -20,18 +20,17 @@ OpMemberName %19 0 "data" OpName %19 "Lights" OpName %24 "c_ambient" OpName %25 "u_globals" -OpName %27 "s_lights" -OpName %29 "t_shadow" -OpName %31 "sampler_shadow" -OpName %34 "light_id" -OpName %35 "homogeneous_coords" -OpName %36 "fetch_shadow" -OpName %64 "color" -OpName %66 "i" -OpName %69 "raw_normal" -OpName %72 "position" -OpName %77 "fs_main" -OpDecorate %14 Block +OpName %28 "s_lights" +OpName %30 "t_shadow" +OpName %32 "sampler_shadow" +OpName %35 "light_id" +OpName %36 "homogeneous_coords" +OpName %37 "fetch_shadow" +OpName %66 "color" +OpName %68 "i" +OpName %71 "raw_normal" +OpName %74 "position" +OpName %79 "fs_main" OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %17 0 Offset 0 OpMemberDecorate %17 0 ColMajor @@ -39,20 +38,22 @@ OpMemberDecorate %17 0 MatrixStride 16 OpMemberDecorate %17 1 Offset 64 OpMemberDecorate %17 2 Offset 80 OpDecorate %18 ArrayStride 96 -OpDecorate %19 Block OpMemberDecorate %19 0 Offset 0 OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 0 -OpDecorate %27 NonWritable -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 1 -OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 2 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 3 -OpDecorate %69 Location 0 -OpDecorate %72 Location 1 -OpDecorate %75 Location 0 +OpDecorate %26 Block +OpMemberDecorate %26 0 Offset 0 +OpDecorate %28 NonWritable +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 1 +OpDecorate %19 Block +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 2 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 3 +OpDecorate %71 Location 0 +OpDecorate %74 Location 1 +OpDecorate %77 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 0.0 @@ -76,120 +77,123 @@ OpDecorate %75 Location 0 %22 = OpTypeVector %4 2 %23 = OpTypeVector %4 3 %24 = OpConstantComposite %23 %8 %8 %8 -%26 = OpTypePointer Uniform %14 -%25 = OpVariable %26 Uniform -%28 = OpTypePointer StorageBuffer %19 -%27 = OpVariable %28 StorageBuffer -%30 = OpTypePointer UniformConstant %20 -%29 = OpVariable %30 UniformConstant -%32 = OpTypePointer UniformConstant %21 -%31 = OpVariable %32 UniformConstant -%37 = OpTypeFunction %4 %10 %16 -%42 = OpTypeBool -%54 = OpTypeInt 32 1 -%59 = OpTypeSampledImage %20 -%65 = OpTypePointer Function %23 -%67 = OpTypePointer Function %10 -%70 = OpTypePointer Input %23 -%69 = OpVariable %70 Input -%73 = OpTypePointer Input %16 -%72 = OpVariable %73 Input -%76 = OpTypePointer Output %16 -%75 = OpVariable %76 Output -%78 = OpTypeFunction %2 -%88 = OpTypePointer Uniform %13 -%89 = OpTypePointer Uniform %10 -%96 = OpTypePointer StorageBuffer %18 -%98 = OpTypePointer StorageBuffer %17 -%36 = OpFunction %4 None %37 -%34 = OpFunctionParameter %10 -%35 = OpFunctionParameter %16 -%33 = OpLabel -%38 = OpLoad %20 %29 -%39 = OpLoad %21 %31 -OpBranch %40 -%40 = OpLabel -%41 = OpCompositeExtract %4 %35 3 -%43 = OpFOrdLessThanEqual %42 %41 %3 -OpSelectionMerge %44 None -OpBranchConditional %43 %45 %44 -%45 = OpLabel +%26 = OpTypeStruct %14 +%27 = OpTypePointer Uniform %26 +%25 = OpVariable %27 Uniform +%29 = OpTypePointer StorageBuffer %19 +%28 = OpVariable %29 StorageBuffer +%31 = OpTypePointer UniformConstant %20 +%30 = OpVariable %31 UniformConstant +%33 = OpTypePointer UniformConstant %21 +%32 = OpVariable %33 UniformConstant +%38 = OpTypeFunction %4 %10 %16 +%41 = OpTypePointer Uniform %14 +%44 = OpTypeBool +%56 = OpTypeInt 32 1 +%61 = OpTypeSampledImage %20 +%67 = OpTypePointer Function %23 +%69 = OpTypePointer Function %10 +%72 = OpTypePointer Input %23 +%71 = OpVariable %72 Input +%75 = OpTypePointer Input %16 +%74 = OpVariable %75 Input +%78 = OpTypePointer Output %16 +%77 = OpVariable %78 Output +%80 = OpTypeFunction %2 +%91 = OpTypePointer Uniform %13 +%92 = OpTypePointer Uniform %10 +%99 = OpTypePointer StorageBuffer %18 +%101 = OpTypePointer StorageBuffer %17 +%37 = OpFunction %4 None %38 +%35 = OpFunctionParameter %10 +%36 = OpFunctionParameter %16 +%34 = OpLabel +%39 = OpLoad %20 %30 +%40 = OpLoad %21 %32 +OpBranch %42 +%42 = OpLabel +%43 = OpCompositeExtract %4 %36 3 +%45 = OpFOrdLessThanEqual %44 %43 %3 +OpSelectionMerge %46 None +OpBranchConditional %45 %47 %46 +%47 = OpLabel OpReturnValue %5 -%44 = OpLabel -%46 = OpCompositeConstruct %22 %6 %7 -%47 = OpVectorShuffle %22 %35 %35 0 1 -%48 = OpFMul %22 %47 %46 -%49 = OpCompositeExtract %4 %35 3 -%50 = OpCompositeConstruct %22 %49 %49 -%51 = OpFDiv %22 %48 %50 -%52 = OpCompositeConstruct %22 %6 %6 -%53 = OpFAdd %22 %51 %52 -%55 = OpBitcast %54 %34 -%56 = OpCompositeExtract %4 %35 2 -%57 = OpCompositeExtract %4 %35 3 -%58 = OpFDiv %4 %56 %57 -%60 = OpConvertUToF %4 %55 -%61 = OpCompositeConstruct %23 %53 %60 -%62 = OpSampledImage %59 %38 %39 -%63 = OpImageSampleDrefExplicitLod %4 %62 %61 %58 Lod %3 -OpReturnValue %63 +%46 = OpLabel +%48 = OpCompositeConstruct %22 %6 %7 +%49 = OpVectorShuffle %22 %36 %36 0 1 +%50 = OpFMul %22 %49 %48 +%51 = OpCompositeExtract %4 %36 3 +%52 = OpCompositeConstruct %22 %51 %51 +%53 = OpFDiv %22 %50 %52 +%54 = OpCompositeConstruct %22 %6 %6 +%55 = OpFAdd %22 %53 %54 +%57 = OpBitcast %56 %35 +%58 = OpCompositeExtract %4 %36 2 +%59 = OpCompositeExtract %4 %36 3 +%60 = OpFDiv %4 %58 %59 +%62 = OpConvertUToF %4 %57 +%63 = OpCompositeConstruct %23 %55 %62 +%64 = OpSampledImage %61 %39 %40 +%65 = OpImageSampleDrefExplicitLod %4 %64 %63 %60 Lod %3 +OpReturnValue %65 OpFunctionEnd -%77 = OpFunction %2 None %78 -%68 = OpLabel -%64 = OpVariable %65 Function %24 -%66 = OpVariable %67 Function %11 -%71 = OpLoad %23 %69 -%74 = OpLoad %16 %72 -%79 = OpLoad %20 %29 -%80 = OpLoad %21 %31 -OpBranch %81 -%81 = OpLabel -%82 = OpExtInst %23 %1 Normalize %71 -OpBranch %83 -%83 = OpLabel -OpLoopMerge %84 %86 None -OpBranch %85 -%85 = OpLabel -%87 = OpLoad %10 %66 -%90 = OpAccessChain %89 %25 %11 %11 -%91 = OpLoad %10 %90 -%92 = OpExtInst %10 %1 UMin %91 %9 -%93 = OpUGreaterThanEqual %42 %87 %92 -OpSelectionMerge %94 None -OpBranchConditional %93 %95 %94 -%95 = OpLabel +%79 = OpFunction %2 None %80 +%70 = OpLabel +%66 = OpVariable %67 Function %24 +%68 = OpVariable %69 Function %11 +%73 = OpLoad %23 %71 +%76 = OpLoad %16 %74 +%81 = OpAccessChain %41 %25 %11 +%82 = OpLoad %20 %30 +%83 = OpLoad %21 %32 OpBranch %84 -%94 = OpLabel -%97 = OpLoad %10 %66 -%99 = OpAccessChain %98 %27 %11 %97 -%100 = OpLoad %17 %99 -%101 = OpLoad %10 %66 -%102 = OpCompositeExtract %15 %100 0 -%103 = OpMatrixTimesVector %16 %102 %74 -%104 = OpFunctionCall %4 %36 %101 %103 -%105 = OpCompositeExtract %16 %100 1 -%106 = OpVectorShuffle %23 %105 %105 0 1 2 -%107 = OpVectorShuffle %23 %74 %74 0 1 2 -%108 = OpFSub %23 %106 %107 -%109 = OpExtInst %23 %1 Normalize %108 -%110 = OpDot %4 %82 %109 -%111 = OpExtInst %4 %1 FMax %3 %110 -%112 = OpLoad %23 %64 -%113 = OpFMul %4 %104 %111 -%114 = OpCompositeExtract %16 %100 2 -%115 = OpVectorShuffle %23 %114 %114 0 1 2 -%116 = OpVectorTimesScalar %23 %115 %113 -%117 = OpFAdd %23 %112 %116 -OpStore %64 %117 +%84 = OpLabel +%85 = OpExtInst %23 %1 Normalize %73 OpBranch %86 %86 = OpLabel -%118 = OpLoad %10 %66 -%119 = OpIAdd %10 %118 %12 -OpStore %66 %119 -OpBranch %83 -%84 = OpLabel -%120 = OpLoad %23 %64 -%121 = OpCompositeConstruct %16 %120 %5 -OpStore %75 %121 +OpLoopMerge %87 %89 None +OpBranch %88 +%88 = OpLabel +%90 = OpLoad %10 %68 +%93 = OpAccessChain %92 %81 %11 %11 +%94 = OpLoad %10 %93 +%95 = OpExtInst %10 %1 UMin %94 %9 +%96 = OpUGreaterThanEqual %44 %90 %95 +OpSelectionMerge %97 None +OpBranchConditional %96 %98 %97 +%98 = OpLabel +OpBranch %87 +%97 = OpLabel +%100 = OpLoad %10 %68 +%102 = OpAccessChain %101 %28 %11 %100 +%103 = OpLoad %17 %102 +%104 = OpLoad %10 %68 +%105 = OpCompositeExtract %15 %103 0 +%106 = OpMatrixTimesVector %16 %105 %76 +%107 = OpFunctionCall %4 %37 %104 %106 +%108 = OpCompositeExtract %16 %103 1 +%109 = OpVectorShuffle %23 %108 %108 0 1 2 +%110 = OpVectorShuffle %23 %76 %76 0 1 2 +%111 = OpFSub %23 %109 %110 +%112 = OpExtInst %23 %1 Normalize %111 +%113 = OpDot %4 %85 %112 +%114 = OpExtInst %4 %1 FMax %3 %113 +%115 = OpLoad %23 %66 +%116 = OpFMul %4 %107 %114 +%117 = OpCompositeExtract %16 %103 2 +%118 = OpVectorShuffle %23 %117 %117 0 1 2 +%119 = OpVectorTimesScalar %23 %118 %116 +%120 = OpFAdd %23 %115 %119 +OpStore %66 %120 +OpBranch %89 +%89 = OpLabel +%121 = OpLoad %10 %68 +%122 = OpIAdd %10 %121 %12 +OpStore %68 %122 +OpBranch %86 +%87 = OpLabel +%123 = OpLoad %23 %66 +%124 = OpCompositeConstruct %16 %123 %5 +OpStore %77 %124 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/skybox.spvasm b/tests/out/spv/skybox.spvasm index 16e597cb8..278ec0bb3 100644 --- a/tests/out/spv/skybox.spvasm +++ b/tests/out/spv/skybox.spvasm @@ -1,16 +1,15 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 93 +; Bound: 96 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %36 "vs_main" %29 %32 %34 -OpEntryPoint Fragment %85 "fs_main" %78 %81 %84 -OpExecutionMode %85 OriginUpperLeft +OpEntryPoint Vertex %37 "vs_main" %30 %33 %35 +OpEntryPoint Fragment %88 "fs_main" %81 %84 %87 +OpExecutionMode %88 OriginUpperLeft OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 -OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %14 0 ColMajor OpMemberDecorate %14 0 MatrixStride 16 @@ -19,16 +18,18 @@ OpMemberDecorate %14 1 ColMajor OpMemberDecorate %14 1 MatrixStride 16 OpDecorate %19 DescriptorSet 0 OpDecorate %19 Binding 0 -OpDecorate %21 DescriptorSet 0 -OpDecorate %21 Binding 1 -OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 2 -OpDecorate %29 BuiltIn VertexIndex -OpDecorate %32 BuiltIn Position -OpDecorate %34 Location 0 -OpDecorate %78 BuiltIn FragCoord -OpDecorate %81 Location 0 +OpDecorate %20 Block +OpMemberDecorate %20 0 Offset 0 +OpDecorate %22 DescriptorSet 0 +OpDecorate %22 Binding 1 +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 2 +OpDecorate %30 BuiltIn VertexIndex +OpDecorate %33 BuiltIn Position +OpDecorate %35 Location 0 +OpDecorate %81 BuiltIn FragCoord OpDecorate %84 Location 0 +OpDecorate %87 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -46,88 +47,91 @@ OpDecorate %84 Location 0 %16 = OpTypeMatrix %11 3 %17 = OpTypeImage %7 Cube 0 0 0 1 Unknown %18 = OpTypeSampler -%20 = OpTypePointer Uniform %14 -%19 = OpVariable %20 Uniform -%22 = OpTypePointer UniformConstant %17 -%21 = OpVariable %22 UniformConstant -%24 = OpTypePointer UniformConstant %18 -%23 = OpVariable %24 UniformConstant -%26 = OpTypePointer Function %4 -%30 = OpTypePointer Input %15 -%29 = OpVariable %30 Input -%33 = OpTypePointer Output %10 -%32 = OpVariable %33 Output -%35 = OpTypePointer Output %11 -%34 = OpVariable %35 Output -%37 = OpTypeFunction %2 -%52 = OpTypePointer Uniform %13 -%53 = OpTypePointer Uniform %10 -%54 = OpConstant %15 0 -%55 = OpConstant %15 1 -%62 = OpConstant %15 2 -%79 = OpTypePointer Input %10 -%78 = OpVariable %79 Input -%82 = OpTypePointer Input %11 +%20 = OpTypeStruct %14 +%21 = OpTypePointer Uniform %20 +%19 = OpVariable %21 Uniform +%23 = OpTypePointer UniformConstant %17 +%22 = OpVariable %23 UniformConstant +%25 = OpTypePointer UniformConstant %18 +%24 = OpVariable %25 UniformConstant +%27 = OpTypePointer Function %4 +%31 = OpTypePointer Input %15 +%30 = OpVariable %31 Input +%34 = OpTypePointer Output %10 +%33 = OpVariable %34 Output +%36 = OpTypePointer Output %11 +%35 = OpVariable %36 Output +%38 = OpTypeFunction %2 +%39 = OpTypePointer Uniform %14 +%40 = OpConstant %15 0 +%56 = OpTypePointer Uniform %13 +%57 = OpTypePointer Uniform %10 +%58 = OpConstant %15 1 +%65 = OpConstant %15 2 +%82 = OpTypePointer Input %10 %81 = OpVariable %82 Input -%84 = OpVariable %33 Output -%90 = OpTypeSampledImage %17 -%36 = OpFunction %2 None %37 -%28 = OpLabel -%25 = OpVariable %26 Function -%27 = OpVariable %26 Function -%31 = OpLoad %15 %29 -OpBranch %38 -%38 = OpLabel -%39 = OpBitcast %4 %31 -%40 = OpSDiv %4 %39 %3 -OpStore %25 %40 -%41 = OpBitcast %4 %31 -%42 = OpBitwiseAnd %4 %41 %5 -OpStore %27 %42 -%43 = OpLoad %4 %25 -%44 = OpConvertSToF %7 %43 -%45 = OpFMul %7 %44 %6 -%46 = OpFSub %7 %45 %8 -%47 = OpLoad %4 %27 +%85 = OpTypePointer Input %11 +%84 = OpVariable %85 Input +%87 = OpVariable %34 Output +%93 = OpTypeSampledImage %17 +%37 = OpFunction %2 None %38 +%29 = OpLabel +%26 = OpVariable %27 Function +%28 = OpVariable %27 Function +%32 = OpLoad %15 %30 +%41 = OpAccessChain %39 %19 %40 +OpBranch %42 +%42 = OpLabel +%43 = OpBitcast %4 %32 +%44 = OpSDiv %4 %43 %3 +OpStore %26 %44 +%45 = OpBitcast %4 %32 +%46 = OpBitwiseAnd %4 %45 %5 +OpStore %28 %46 +%47 = OpLoad %4 %26 %48 = OpConvertSToF %7 %47 %49 = OpFMul %7 %48 %6 %50 = OpFSub %7 %49 %8 -%51 = OpCompositeConstruct %10 %46 %50 %9 %8 -%56 = OpAccessChain %53 %19 %55 %54 -%57 = OpLoad %10 %56 -%58 = OpVectorShuffle %11 %57 %57 0 1 2 -%59 = OpAccessChain %53 %19 %55 %55 +%51 = OpLoad %4 %28 +%52 = OpConvertSToF %7 %51 +%53 = OpFMul %7 %52 %6 +%54 = OpFSub %7 %53 %8 +%55 = OpCompositeConstruct %10 %50 %54 %9 %8 +%59 = OpAccessChain %57 %41 %58 %40 %60 = OpLoad %10 %59 %61 = OpVectorShuffle %11 %60 %60 0 1 2 -%63 = OpAccessChain %53 %19 %55 %62 -%64 = OpLoad %10 %63 -%65 = OpVectorShuffle %11 %64 %64 0 1 2 -%66 = OpCompositeConstruct %16 %58 %61 %65 -%67 = OpTranspose %16 %66 -%68 = OpAccessChain %52 %19 %54 -%69 = OpLoad %13 %68 -%70 = OpMatrixTimesVector %10 %69 %51 -%71 = OpVectorShuffle %11 %70 %70 0 1 2 -%72 = OpMatrixTimesVector %11 %67 %71 -%73 = OpCompositeConstruct %12 %51 %72 -%74 = OpCompositeExtract %10 %73 0 -OpStore %32 %74 -%75 = OpCompositeExtract %11 %73 1 -OpStore %34 %75 +%62 = OpAccessChain %57 %41 %58 %58 +%63 = OpLoad %10 %62 +%64 = OpVectorShuffle %11 %63 %63 0 1 2 +%66 = OpAccessChain %57 %41 %58 %65 +%67 = OpLoad %10 %66 +%68 = OpVectorShuffle %11 %67 %67 0 1 2 +%69 = OpCompositeConstruct %16 %61 %64 %68 +%70 = OpTranspose %16 %69 +%71 = OpAccessChain %56 %41 %40 +%72 = OpLoad %13 %71 +%73 = OpMatrixTimesVector %10 %72 %55 +%74 = OpVectorShuffle %11 %73 %73 0 1 2 +%75 = OpMatrixTimesVector %11 %70 %74 +%76 = OpCompositeConstruct %12 %55 %75 +%77 = OpCompositeExtract %10 %76 0 +OpStore %33 %77 +%78 = OpCompositeExtract %11 %76 1 +OpStore %35 %78 OpReturn OpFunctionEnd -%85 = OpFunction %2 None %37 -%76 = OpLabel -%80 = OpLoad %10 %78 -%83 = OpLoad %11 %81 -%77 = OpCompositeConstruct %12 %80 %83 -%86 = OpLoad %17 %21 -%87 = OpLoad %18 %23 -OpBranch %88 -%88 = OpLabel -%89 = OpCompositeExtract %11 %77 1 -%91 = OpSampledImage %90 %86 %87 -%92 = OpImageSampleImplicitLod %10 %91 %89 -OpStore %84 %92 +%88 = OpFunction %2 None %38 +%79 = OpLabel +%83 = OpLoad %10 %81 +%86 = OpLoad %11 %84 +%80 = OpCompositeConstruct %12 %83 %86 +%89 = OpLoad %17 %22 +%90 = OpLoad %18 %24 +OpBranch %91 +%91 = OpLabel +%92 = OpCompositeExtract %11 %80 1 +%94 = OpSampledImage %93 %89 %90 +%95 = OpImageSampleImplicitLod %10 %94 %92 +OpStore %87 %95 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index c578384da..e66de740d 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -1,4 +1,3 @@ -[[block]] struct ColorMaterial_color { Color: vec4; }; diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 7db8c9925..c368e38d9 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -1,14 +1,11 @@ -[[block]] struct Camera { ViewProj: mat4x4; }; -[[block]] struct Transform { Model: mat4x4; }; -[[block]] struct Sprite_size { size: vec2; }; diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 94ccaea3e..4f476b9f1 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -1,9 +1,7 @@ -[[block]] struct Camera { ViewProj: mat4x4; }; -[[block]] struct Transform { Model: mat4x4; }; diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index e392695f7..fc344ea50 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -1,4 +1,3 @@ -[[block]] struct PrimeIndices { indices: [[stride(4)]] array; }; diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index 06fd0f486..351482d7d 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -1,9 +1,7 @@ -[[block]] struct Globals { view_matrix: mat4x4; }; -[[block]] struct VertexPushConstants { world_matrix: mat4x4; }; diff --git a/tests/out/wgsl/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-vert.wgsl index 063f22a4f..dec43d8d4 100644 --- a/tests/out/wgsl/896-push-constant-vert.wgsl +++ b/tests/out/wgsl/896-push-constant-vert.wgsl @@ -1,4 +1,3 @@ -[[block]] struct PushConstants { example: f32; }; diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index d56b4c570..e43707715 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -1,4 +1,3 @@ -[[block]] struct Bar { matrix: mat4x4; atom: atomic; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 01b8120e6..f73f517d4 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -9,17 +9,14 @@ struct DirectionalLight { color: vec4; }; -[[block]] struct CameraViewProj { ViewProj: mat4x4; }; -[[block]] struct CameraPosition { CameraPos: vec4; }; -[[block]] struct Lights { AmbientColor: vec4; NumLights: vec4; @@ -27,27 +24,22 @@ struct Lights { DirectionalLights: [[stride(32)]] array; }; -[[block]] struct StandardMaterial_base_color { base_color: vec4; }; -[[block]] struct StandardMaterial_roughness { perceptual_roughness: f32; }; -[[block]] struct StandardMaterial_metallic { metallic: f32; }; -[[block]] struct StandardMaterial_reflectance { reflectance: f32; }; -[[block]] struct StandardMaterial_emissive { emissive: vec4; }; diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 1863c9681..34f836704 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -1,9 +1,7 @@ -[[block]] struct CameraViewProj { ViewProj: mat4x4; }; -[[block]] struct Transform { Model: mat4x4; }; diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 4dd4cd40e..6a5d4c269 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -3,7 +3,6 @@ struct Particle { vel: vec2; }; -[[block]] struct SimParams { deltaT: f32; rule1Distance: f32; @@ -14,7 +13,6 @@ struct SimParams { rule3Scale: f32; }; -[[block]] struct Particles { particles: [[stride(16)]] array; }; diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index a07b148fd..281df6fb7 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -1,4 +1,3 @@ -[[block]] struct PrimeIndices { data: [[stride(4)]] array; }; diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 268595b48..02d04dc52 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -1,4 +1,3 @@ -[[block]] struct Data { vecs: [[stride(16)]] array,42u>; }; diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index 1732aaf0b..f912dfdff 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -1,4 +1,3 @@ -[[block]] struct type_1 { member: i32; }; diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index 710519b8e..b9fbfb74c 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -1,4 +1,3 @@ -[[block]] struct PushConstants { index: u32; double: vec2; diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index c4c328fb4..df8e6553a 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -1,4 +1,3 @@ -[[block]] struct DynamicArray { arr: [[stride(4)]] array; }; diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index cff7f2177..b08aae9e6 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -1,4 +1,3 @@ -[[block]] struct gl_PerVertex { [[builtin(position)]] gl_Position: vec4; }; diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index c42d823e5..d27b0a895 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -1,4 +1,3 @@ -[[block]] struct Globals { num_lights: vec4; }; @@ -9,7 +8,6 @@ struct Light { color: vec4; }; -[[block]] struct Lights { data: [[stride(96)]] array; }; diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index 749725507..8b52c97da 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -3,7 +3,6 @@ struct VertexOutput { [[location(0)]] uv: vec3; }; -[[block]] struct Data { proj_inv: mat4x4; view: mat4x4; diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 13b50109c..7607359de 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -804,17 +804,6 @@ fn invalid_arrays() { }) } - check_validation_error! { - r#" - [[block]] struct Block { value: f32; }; - type Bad = array; - "#: - Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::NestedTopLevel, - .. - }) - } - check_validation_error! { r#" type Bad = [[stride(2)]] array; @@ -1154,7 +1143,6 @@ fn invalid_runtime_sized_arrays() { arr: array; }; - [[block]] struct Outer { legit: i32; unsized: Unsized; @@ -1264,7 +1252,6 @@ fn wrong_access_mode() { // variables whose access mode is `read`, not `read_write`. check_validation_error! { " - [[block]] struct Globals { i: i32; }; @@ -1277,7 +1264,6 @@ fn wrong_access_mode() { } ", " - [[block]] struct Globals { i: i32; }; From c64d5eff5006bc8cac9991efa4240536d5787c6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 15 Dec 2021 22:30:33 +0000 Subject: [PATCH 1480/2212] Support bitwise Or on booleans --- src/back/glsl/mod.rs | 13 +++++++++- src/back/spv/block.rs | 5 +++- src/valid/expression.rs | 12 ++++++++- tests/in/operators.wgsl | 5 ++++ tests/out/glsl/operators.main.Compute.glsl | 5 ++++ tests/out/hlsl/operators.hlsl | 6 +++++ tests/out/msl/operators.msl | 6 +++++ tests/out/spv/operators.spvasm | 30 ++++++++++++++-------- tests/out/wgsl/operators.wgsl | 5 ++++ 9 files changed, 73 insertions(+), 14 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 082fa685c..bb0f4c438 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2239,7 +2239,11 @@ impl<'a, W: Write> Writer<'a, W> { // comparison operations on vectors as they are implemented with // builtin functions. // Once again we wrap everything in parentheses to avoid precedence issues - Expression::Binary { op, left, right } => { + Expression::Binary { + mut op, + left, + right, + } => { // Holds `Some(function_name)` if the binary operation is // implemented as a function call use crate::{BinaryOperator as Bo, ScalarKind as Sk, TypeInner as Ti}; @@ -2276,6 +2280,13 @@ impl<'a, W: Write> Writer<'a, W> { Bo::Modulo => BinaryOperation::Modulo, _ => BinaryOperation::Other, }, + (Some(Sk::Bool), Some(Sk::Bool)) => match op { + Bo::InclusiveOr => { + op = crate::BinaryOperator::LogicalOr; + BinaryOperation::Other + } + _ => BinaryOperation::Other, + }, _ => BinaryOperation::Other, }, }; diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index f0676f0d4..ca05da4d3 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -435,7 +435,10 @@ impl<'w> BlockContext<'w> { }, crate::BinaryOperator::And => spirv::Op::BitwiseAnd, crate::BinaryOperator::ExclusiveOr => spirv::Op::BitwiseXor, - crate::BinaryOperator::InclusiveOr => spirv::Op::BitwiseOr, + crate::BinaryOperator::InclusiveOr => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalOr, + _ => spirv::Op::BitwiseOr, + }, crate::BinaryOperator::LogicalAnd => spirv::Op::LogicalAnd, crate::BinaryOperator::LogicalOr => spirv::Op::LogicalOr, crate::BinaryOperator::ShiftLeft => spirv::Op::ShiftLeftLogical, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index a9dab24cd..023bf018c 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -739,7 +739,17 @@ impl super::Validator { false } }, - Bo::And | Bo::ExclusiveOr | Bo::InclusiveOr => match *left_inner { + Bo::And | Bo::InclusiveOr => match *left_inner { + Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { + Sk::Bool | Sk::Sint | Sk::Uint => left_inner == right_inner, + Sk::Float => false, + }, + ref other => { + log::error!("Op {:?} left type {:?}", op, other); + false + } + }, + Bo::ExclusiveOr => match *left_inner { Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { Sk::Sint | Sk::Uint => left_inner == right_inner, Sk::Bool | Sk::Float => false, diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 673bd55cd..0c727eae2 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -68,6 +68,10 @@ fn scalar_times_matrix() { let assertion: mat4x4 = 2.0 * model; } +fn binary() { + let a = true | false; +} + [[stage(compute), workgroup_size(1)]] fn main() { let a = builtins(); @@ -77,4 +81,5 @@ fn main() { let e = constructors(); modulo(); scalar_times_matrix(); + binary(); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 9a9fa5c89..eb9dd8490 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -60,6 +60,10 @@ void scalar_times_matrix() { mat4x4 assertion = (2.0 * model); } +void binary() { + bool a_2 = (true || false); +} + void main() { vec4 _e4 = builtins(); vec4 _e5 = splat(); @@ -68,6 +72,7 @@ void main() { float _e9 = constructors(); modulo(); scalar_times_matrix(); + binary(); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index a359689f6..a3f7f8a08 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -73,6 +73,11 @@ void scalar_times_matrix() float4x4 assertion = mul(model, 2.0); } +void binary() +{ + bool a_2 = (true | false); +} + [numthreads(1, 1, 1)] void main() { @@ -83,5 +88,6 @@ void main() const float _e9 = constructors(); modulo(); scalar_times_matrix(); + binary(); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index f80197989..97b7490fe 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -69,6 +69,11 @@ void scalar_times_matrix( metal::float4x4 assertion = 2.0 * model; } +void binary( +) { + bool a_2 = true | false; +} + kernel void main_( ) { metal::float4 _e4 = builtins(); @@ -78,5 +83,6 @@ kernel void main_( float _e9 = constructors(); modulo(); scalar_times_matrix(); + binary(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index bc931da33..081bfbb23 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 139 +; Bound: 144 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %129 "main" -OpExecutionMode %129 LocalSize 1 1 1 +OpEntryPoint GLCompute %133 "main" +OpExecutionMode %133 LocalSize 1 1 1 OpMemberDecorate %23 0 Offset 0 OpMemberDecorate %23 1 Offset 16 %2 = OpTypeVoid @@ -165,13 +165,21 @@ OpFunctionEnd %128 = OpLabel OpBranch %130 %130 = OpLabel -%131 = OpFunctionCall %19 %30 -%132 = OpFunctionCall %19 %55 -%133 = OpFunctionCall %8 %72 -%134 = OpVectorShuffle %22 %25 %25 0 1 2 -%135 = OpFunctionCall %22 %83 %134 -%136 = OpFunctionCall %4 %95 -%137 = OpFunctionCall %2 %107 -%138 = OpFunctionCall %2 %120 +%131 = OpLogicalOr %10 %9 %12 +OpReturn +OpFunctionEnd +%133 = OpFunction %2 None %108 +%132 = OpLabel +OpBranch %134 +%134 = OpLabel +%135 = OpFunctionCall %19 %30 +%136 = OpFunctionCall %19 %55 +%137 = OpFunctionCall %8 %72 +%138 = OpVectorShuffle %22 %25 %25 0 1 2 +%139 = OpFunctionCall %22 %83 %138 +%140 = OpFunctionCall %4 %95 +%141 = OpFunctionCall %2 %107 +%142 = OpFunctionCall %2 %120 +%143 = OpFunctionCall %2 %129 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index de5ec99f8..37dd0bed9 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -58,6 +58,10 @@ fn scalar_times_matrix() { let assertion = (2.0 * model); } +fn binary() { + let a_2 = (true | false); +} + [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { let _e4 = builtins(); @@ -67,5 +71,6 @@ fn main() { let _e9 = constructors(); modulo(); scalar_times_matrix(); + binary(); return; } From 4334f0e6a9a9b6465812e56bda5b9c91cf96459c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 15 Dec 2021 22:38:32 +0000 Subject: [PATCH 1481/2212] Support bitwise And on booleans --- src/back/glsl/mod.rs | 4 +++ src/back/spv/block.rs | 5 +++- tests/in/operators.wgsl | 1 + tests/out/glsl/operators.main.Compute.glsl | 1 + tests/out/hlsl/operators.hlsl | 1 + tests/out/msl/operators.msl | 1 + tests/out/spv/operators.spvasm | 33 +++++++++++----------- tests/out/wgsl/operators.wgsl | 1 + 8 files changed, 30 insertions(+), 17 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index bb0f4c438..9bea98eb1 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2285,6 +2285,10 @@ impl<'a, W: Write> Writer<'a, W> { op = crate::BinaryOperator::LogicalOr; BinaryOperation::Other } + Bo::And => { + op = crate::BinaryOperator::LogicalAnd; + BinaryOperation::Other + } _ => BinaryOperation::Other, }, _ => BinaryOperation::Other, diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index ca05da4d3..a59f85453 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -433,7 +433,10 @@ impl<'w> BlockContext<'w> { Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThanEqual, _ => unimplemented!(), }, - crate::BinaryOperator::And => spirv::Op::BitwiseAnd, + crate::BinaryOperator::And => match left_ty_inner.scalar_kind() { + Some(crate::ScalarKind::Bool) => spirv::Op::LogicalAnd, + _ => spirv::Op::BitwiseAnd, + }, crate::BinaryOperator::ExclusiveOr => spirv::Op::BitwiseXor, crate::BinaryOperator::InclusiveOr => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Bool) => spirv::Op::LogicalOr, diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 0c727eae2..d6e5a25a5 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -70,6 +70,7 @@ fn scalar_times_matrix() { fn binary() { let a = true | false; + let b = true & false; } [[stage(compute), workgroup_size(1)]] diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index eb9dd8490..25308e527 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -62,6 +62,7 @@ void scalar_times_matrix() { void binary() { bool a_2 = (true || false); + bool b_2 = (true && false); } void main() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index a3f7f8a08..47b5a59a0 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -76,6 +76,7 @@ void scalar_times_matrix() void binary() { bool a_2 = (true | false); + bool b_2 = (true & false); } [numthreads(1, 1, 1)] diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 97b7490fe..07a5f1136 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -72,6 +72,7 @@ void scalar_times_matrix( void binary( ) { bool a_2 = true | false; + bool b_2 = true & false; } kernel void main_( diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 081bfbb23..4a16ee167 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 144 +; Bound: 145 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %133 "main" -OpExecutionMode %133 LocalSize 1 1 1 +OpEntryPoint GLCompute %134 "main" +OpExecutionMode %134 LocalSize 1 1 1 OpMemberDecorate %23 0 Offset 0 OpMemberDecorate %23 1 Offset 16 %2 = OpTypeVoid @@ -166,20 +166,21 @@ OpFunctionEnd OpBranch %130 %130 = OpLabel %131 = OpLogicalOr %10 %9 %12 +%132 = OpLogicalAnd %10 %9 %12 OpReturn OpFunctionEnd -%133 = OpFunction %2 None %108 -%132 = OpLabel -OpBranch %134 -%134 = OpLabel -%135 = OpFunctionCall %19 %30 -%136 = OpFunctionCall %19 %55 -%137 = OpFunctionCall %8 %72 -%138 = OpVectorShuffle %22 %25 %25 0 1 2 -%139 = OpFunctionCall %22 %83 %138 -%140 = OpFunctionCall %4 %95 -%141 = OpFunctionCall %2 %107 -%142 = OpFunctionCall %2 %120 -%143 = OpFunctionCall %2 %129 +%134 = OpFunction %2 None %108 +%133 = OpLabel +OpBranch %135 +%135 = OpLabel +%136 = OpFunctionCall %19 %30 +%137 = OpFunctionCall %19 %55 +%138 = OpFunctionCall %8 %72 +%139 = OpVectorShuffle %22 %25 %25 0 1 2 +%140 = OpFunctionCall %22 %83 %139 +%141 = OpFunctionCall %4 %95 +%142 = OpFunctionCall %2 %107 +%143 = OpFunctionCall %2 %120 +%144 = OpFunctionCall %2 %129 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 37dd0bed9..cc34bbe76 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -60,6 +60,7 @@ fn scalar_times_matrix() { fn binary() { let a_2 = (true | false); + let b_2 = (true & false); } [[stage(compute), workgroup_size(1, 1, 1)]] From 049b48b319fa60f9d376c1db33becf1169b17ae8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 15 Dec 2021 22:07:10 +0000 Subject: [PATCH 1482/2212] spv-in: Remove if when both branches are equal --- src/front/spv/mod.rs | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index cd1721bbd..5f4a7817e 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2769,9 +2769,16 @@ impl> Parser { get_expr_handle!(condition_id, lexp) }; + block.extend(emitter.finish(ctx.expressions)); + ctx.blocks.insert(block_id, block); + let body = &mut ctx.bodies[body_idx]; + body.data.push(BodyFragment::BlockId(block_id)); + let true_id = self.next()?; let false_id = self.next()?; + let same_target = true_id == false_id; + // Start a body block for the `accept` branch. let accept = ctx.bodies.len(); let mut accept_block = Body::with_parent(body_idx); @@ -2780,13 +2787,29 @@ impl> Parser { // merge or continue block, then put a `Break` or `Continue` // statement in this new body block. if let Some(info) = ctx.mergers.get(&true_id) { - merger(&mut accept_block, info) + merger( + match same_target { + true => &mut ctx.bodies[body_idx], + false => &mut accept_block, + }, + info, + ) } else { // Note the body index for the block we're branching to. - let prev = ctx.body_for_label.insert(true_id, accept); + let prev = ctx.body_for_label.insert( + true_id, + match same_target { + true => body_idx, + false => accept, + }, + ); debug_assert!(prev.is_none()); } + if same_target { + return Ok(()); + } + ctx.bodies.push(accept_block); // Handle the `reject` branch just like the `accept` block. @@ -2802,12 +2825,7 @@ impl> Parser { ctx.bodies.push(reject_block); - block.extend(emitter.finish(ctx.expressions)); - ctx.blocks.insert(block_id, block); let body = &mut ctx.bodies[body_idx]; - // Make sure the vector has space for at least two more allocations - body.data.reserve(2); - body.data.push(BodyFragment::BlockId(block_id)); body.data.push(BodyFragment::If { condition, accept, From 9c75f3cdcece9263eb19fb2c14fafbb92657fcf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 15 Dec 2021 21:11:48 +0000 Subject: [PATCH 1483/2212] glsl-in: Flatten entry point arguments The IR doesn't allow having structs has bindings for entry point input/output, so the glsl frontend must flatten them. Glsl defines that the locations are sequential from the block base location. --- src/front/glsl/functions.rs | 151 +++++++++++++++++++++----- tests/in/glsl/declarations.vert | 14 +++ tests/out/wgsl/declarations-vert.wgsl | 30 +++++ 3 files changed, 166 insertions(+), 29 deletions(-) create mode 100644 tests/in/glsl/declarations.vert create mode 100644 tests/out/wgsl/declarations-vert.wgsl diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 0bc44b101..95336a5d6 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1058,6 +1058,82 @@ impl Parser { }); } + /// Helper function for building the input/output interface of the entry point + /// + /// Calls `f` with the data of the entry point argument, flattening composite types + /// recursively + /// + /// The passed arguments to the callback are: + /// - The name + /// - The pointer expression to the global storage + /// - The handle to the type of the entry point argument + /// - The binding of the entry point argument + /// - The expression arena + fn arg_type_walker( + &self, + name: Option, + binding: crate::Binding, + pointer: Handle, + ty: Handle, + expressions: &mut Arena, + f: &mut impl FnMut( + Option, + Handle, + Handle, + crate::Binding, + &mut Arena, + ), + ) { + match self.module.types[ty].inner { + TypeInner::Struct { ref members, .. } => { + let mut location = match binding { + crate::Binding::Location { location, .. } => location, + _ => return, + }; + + for (i, member) in members.iter().enumerate() { + let member_pointer = expressions.append( + Expression::AccessIndex { + base: pointer, + index: i as u32, + }, + crate::Span::default(), + ); + + let binding = match member.binding.clone() { + Some(binding) => binding, + None => { + let interpolation = self.module.types[member.ty] + .inner + .scalar_kind() + .map(|kind| match kind { + ScalarKind::Float => crate::Interpolation::Perspective, + _ => crate::Interpolation::Flat, + }); + let binding = crate::Binding::Location { + location, + interpolation, + sampling: None, + }; + location += 1; + binding + } + }; + + self.arg_type_walker( + member.name.clone(), + binding, + member_pointer, + member.ty, + expressions, + f, + ) + } + } + _ => f(name, pointer, ty, binding, expressions), + } + } + pub(crate) fn add_entry_point( &mut self, function: Handle, @@ -1079,20 +1155,29 @@ impl Parser { continue; } - let ty = self.module.global_variables[arg.handle].ty; - let idx = arguments.len() as u32; - - arguments.push(FunctionArgument { - name: arg.name.clone(), - ty, - binding: Some(arg.binding.clone()), - }); - let pointer = expressions.append(Expression::GlobalVariable(arg.handle), Default::default()); - let value = expressions.append(Expression::FunctionArgument(idx), Default::default()); - body.push(Statement::Store { pointer, value }, Default::default()); + self.arg_type_walker( + arg.name.clone(), + arg.binding.clone(), + pointer, + self.module.global_variables[arg.handle].ty, + &mut expressions, + &mut |name, pointer, ty, binding, expressions| { + let idx = arguments.len() as u32; + + arguments.push(FunctionArgument { + name, + ty, + binding: Some(binding), + }); + + let value = + expressions.append(Expression::FunctionArgument(idx), Default::default()); + body.push(Statement::Store { pointer, value }, Default::default()); + }, + ) } body.extend_block(global_init_body); @@ -1115,26 +1200,34 @@ impl Parser { continue; } - let ty = self.module.global_variables[arg.handle].ty; - - members.push(StructMember { - name: arg.name.clone(), - ty, - binding: Some(arg.binding.clone()), - offset: span, - }); - - span += self.module.types[ty].inner.span(&self.module.constants); - let pointer = expressions.append(Expression::GlobalVariable(arg.handle), Default::default()); - let len = expressions.len(); - let load = expressions.append(Expression::Load { pointer }, Default::default()); - body.push( - Statement::Emit(expressions.range_from(len)), - Default::default(), - ); - components.push(load) + + self.arg_type_walker( + arg.name.clone(), + arg.binding.clone(), + pointer, + self.module.global_variables[arg.handle].ty, + &mut expressions, + &mut |name, pointer, ty, binding, expressions| { + members.push(StructMember { + name, + ty, + binding: Some(binding), + offset: span, + }); + + span += self.module.types[ty].inner.span(&self.module.constants); + + let len = expressions.len(); + let load = expressions.append(Expression::Load { pointer }, Default::default()); + body.push( + Statement::Emit(expressions.range_from(len)), + Default::default(), + ); + components.push(load) + }, + ) } let (ty, value) = if !components.is_empty() { diff --git a/tests/in/glsl/declarations.vert b/tests/in/glsl/declarations.vert new file mode 100644 index 000000000..e0c2ec6e8 --- /dev/null +++ b/tests/in/glsl/declarations.vert @@ -0,0 +1,14 @@ +#version 450 + +layout(location = 0) in VertexData { + vec2 position; + vec2 a; +} vert; + +layout(location = 0) out FragmentData { + vec2 position; + vec2 a; +} frag; + +void main() { +} diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl new file mode 100644 index 000000000..952ca9dca --- /dev/null +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -0,0 +1,30 @@ +struct VertexData { + position: vec2; + a: vec2; +}; + +struct FragmentData { + position: vec2; + a: vec2; +}; + +struct VertexOutput { + [[location(0)]] position: vec2; + [[location(1)]] a: vec2; +}; + +var vert: VertexData; +var frag: FragmentData; + +fn main_1() { +} + +[[stage(vertex)]] +fn main([[location(0)]] position: vec2, [[location(1)]] a: vec2) -> VertexOutput { + vert.position = position; + vert.a = a; + main_1(); + let _e17 = frag.position; + let _e19 = frag.a; + return VertexOutput(_e17, _e19); +} From cf0c31cc85e91e47b167235f250d184cfbcd0372 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 15 Dec 2021 21:35:19 +0000 Subject: [PATCH 1484/2212] spv-in: Allow branch weights in OpBranchConditional --- src/front/spv/mod.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 5f4a7817e..964409989 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2832,6 +2832,11 @@ impl> Parser { reject, }); + // Consume branch weights + for _ in 4..inst.wc { + let _ = self.next()?; + } + return Ok(()); } Op::Switch => { From 2a8d64fc592c60ee34924078e251c26ba2c60909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 16 Dec 2021 16:12:28 +0000 Subject: [PATCH 1485/2212] spv-in: Implement remaining sign agnostic ops --- src/front/spv/mod.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 964409989..132b49b62 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1834,7 +1834,7 @@ impl> Parser { inst.expect(4)?; parse_expr_op!(crate::UnaryOperator::Negate, UNARY)?; } - Op::IAdd | Op::ISub => { + Op::IAdd | Op::ISub | Op::IMul | Op::IEqual | Op::INotEqual => { inst.expect(5)?; let operator = map_binary_operator(inst.op)?; self.parse_expr_binary_op_sign_adjusted( @@ -1854,7 +1854,7 @@ impl> Parser { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Subtract, BINARY)?; } - Op::IMul | Op::FMul => { + Op::FMul => { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Multiply, BINARY)?; } @@ -2640,12 +2640,7 @@ impl> Parser { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::LogicalAnd, BINARY)?; } - Op::IEqual - | Op::INotEqual - | Op::SGreaterThan - | Op::SGreaterThanEqual - | Op::SLessThan - | Op::SLessThanEqual => { + Op::SGreaterThan | Op::SGreaterThanEqual | Op::SLessThan | Op::SLessThanEqual => { inst.expect(5)?; self.parse_expr_int_comparison( ctx, From 12baa1e909e63b8651291bd449e7d8449fe6f635 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 16 Dec 2021 17:03:53 +0000 Subject: [PATCH 1486/2212] spv-in: Implement OpCopyObject Treat it as a noop since the IR has no concept of copying objects --- src/front/spv/mod.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 132b49b62..d8dd3d8cc 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3124,6 +3124,24 @@ impl> Parser { log::warn!("Unsupported barrier execution scope: {}", exec_scope); } } + Op::CopyObject => { + inst.expect(4)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let operand_id = self.next()?; + + let lookup = self.lookup_expression.lookup(operand_id)?; + let handle = get_expr_handle!(operand_id, lookup); + + self.lookup_expression.insert( + result_id, + LookupExpression { + handle, + type_id: result_type_id, + block_id, + }, + ); + } _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } }; From 7bb886bf36d307d2865ed4c0989968a624e549a0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 16 Dec 2021 16:10:35 -0500 Subject: [PATCH 1487/2212] Enforce casting width better, fix IEqual/INotEqual in spv --- src/back/spv/writer.rs | 1 + src/front/spv/mod.rs | 43 +++++++++++++++++++++++++++++++++++------ src/valid/expression.rs | 20 +++++++++++++------ 3 files changed, 52 insertions(+), 12 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index ea83a4203..797e67e4e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -813,6 +813,7 @@ impl Writer { Entry::Vacant(e) => { let id = self.id_gen.next(); e.insert(id); + self.write_type_declaration_local(id, local); // If it's an image type, request SPIR-V capabilities here, so diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d8dd3d8cc..15afd82f3 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -499,6 +499,11 @@ struct BlockContext<'function> { parameter_sampling: &'function mut [image::SamplingFlags], } +enum SignAnchor { + Result, + Operand, +} + pub struct Parser { data: I, data_offset: usize, @@ -852,6 +857,7 @@ impl> Parser { /// A more complicated version of the binary op, /// where we force the operand to have the same type as the result. /// This is mostly needed for "i++" and "i--" coming from GLSL. + #[allow(clippy::too_many_arguments)] fn parse_expr_binary_op_sign_adjusted( &mut self, ctx: &mut BlockContext, @@ -860,6 +866,10 @@ impl> Parser { block_id: spirv::Word, body_idx: usize, op: crate::BinaryOperator, + // For arithmetic operations, we need the sign of operands to match the result. + // For boolean operations, however, the operands need to match the signs, but + // result is always different - a boolean. + anchor: SignAnchor, ) -> Result<(), Error> { let start = self.data_offset; let result_type_id = self.next()?; @@ -872,15 +882,20 @@ impl> Parser { let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); let p2_lexp = self.lookup_expression.lookup(p2_id)?; let right = self.get_expr_handle(p2_id, p2_lexp, ctx, emitter, block, body_idx); - let result_lookup_ty = self.lookup_type.lookup(result_type_id)?; - let kind = ctx.type_arena[result_lookup_ty.handle] + + let expected_type_id = match anchor { + SignAnchor::Result => result_type_id, + SignAnchor::Operand => p1_lexp.type_id, + }; + let expected_lookup_ty = self.lookup_type.lookup(expected_type_id)?; + let kind = ctx.type_arena[expected_lookup_ty.handle] .inner .scalar_kind() .unwrap(); let expr = crate::Expression::Binary { op, - left: if p1_lexp.type_id == result_type_id { + left: if p1_lexp.type_id == expected_type_id { left } else { ctx.expressions.append( @@ -892,7 +907,7 @@ impl> Parser { span, ) }, - right: if p2_lexp.type_id == result_type_id { + right: if p2_lexp.type_id == expected_type_id { right } else { ctx.expressions.append( @@ -1834,7 +1849,7 @@ impl> Parser { inst.expect(4)?; parse_expr_op!(crate::UnaryOperator::Negate, UNARY)?; } - Op::IAdd | Op::ISub | Op::IMul | Op::IEqual | Op::INotEqual => { + Op::IAdd | Op::ISub | Op::IMul => { inst.expect(5)?; let operator = map_binary_operator(inst.op)?; self.parse_expr_binary_op_sign_adjusted( @@ -1844,6 +1859,20 @@ impl> Parser { block_id, body_idx, operator, + SignAnchor::Result, + )?; + } + Op::IEqual | Op::INotEqual => { + inst.expect(5)?; + let operator = map_binary_operator(inst.op)?; + self.parse_expr_binary_op_sign_adjusted( + ctx, + &mut emitter, + &mut block, + block_id, + body_idx, + operator, + SignAnchor::Operand, )?; } Op::FAdd => { @@ -2400,7 +2429,9 @@ impl> Parser { let expr = crate::Expression::As { expr: get_expr_handle!(value_id, value_lexp), kind, - convert: if inst.op == Op::Bitcast { + convert: if kind == crate::ScalarKind::Bool { + Some(crate::BOOL_WIDTH) + } else if inst.op == Op::Bitcast { None } else { Some(width) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 023bf018c..21da06baa 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1331,12 +1331,20 @@ impl super::Validator { } ShaderStages::all() } - E::As { kind, convert, .. } => { - match convert { - Some(width) if !self.check_width(kind, width) => { - return Err(ExpressionError::InvalidCastArgument) - } - _ => {} + E::As { + expr, + kind, + convert, + } => { + let base_width = match *resolver.resolve(expr)? { + crate::TypeInner::Scalar { width, .. } + | crate::TypeInner::Vector { width, .. } + | crate::TypeInner::Matrix { width, .. } => width, + _ => return Err(ExpressionError::InvalidCastArgument), + }; + let width = convert.unwrap_or(base_width); + if !self.check_width(kind, width) { + return Err(ExpressionError::InvalidCastArgument); } ShaderStages::all() } From 6df9656e9687740be8214b64f7fcbf2fde46eab2 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 16 Dec 2021 16:13:38 -0500 Subject: [PATCH 1488/2212] spv-out: Force wrapping of push constant structs --- src/back/spv/helpers.rs | 4 +- tests/out/spv/extra.spvasm | 88 ++++++++++++++++++++------------------ 2 files changed, 49 insertions(+), 43 deletions(-) diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index 4640ebf52..b5c773046 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -66,7 +66,9 @@ impl crate::StorageClass { // See `back::spv::GlobalVariable::access_id` for details. pub fn global_needs_wrapper(ir_module: &crate::Module, var: &crate::GlobalVariable) -> bool { match var.class { - crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => {} + crate::StorageClass::Uniform + | crate::StorageClass::Storage { .. } + | crate::StorageClass::PushConstant => {} _ => return false, }; match ir_module.types[var.ty].inner { diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index f17b286ac..281ca0edf 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -1,21 +1,23 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 44 +; Bound: 46 OpCapability Shader OpCapability Float64 OpCapability Geometry %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %25 "main" %17 %20 %23 -OpExecutionMode %25 OriginUpperLeft +OpEntryPoint Fragment %26 "main" %18 %21 %24 +OpExecutionMode %26 OriginUpperLeft OpMemberDecorate %10 0 Offset 0 OpMemberDecorate %10 1 Offset 16 OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 -OpDecorate %17 Location 0 -OpDecorate %20 BuiltIn PrimitiveId -OpDecorate %23 Location 0 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpDecorate %18 Location 0 +OpDecorate %21 BuiltIn PrimitiveId +OpDecorate %24 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 2 @@ -27,43 +29,45 @@ OpDecorate %23 Location 0 %10 = OpTypeStruct %4 %8 %11 = OpTypeVector %7 4 %12 = OpTypeStruct %11 %4 -%14 = OpTypePointer PushConstant %10 -%13 = OpVariable %14 PushConstant -%18 = OpTypePointer Input %11 -%17 = OpVariable %18 Input -%21 = OpTypePointer Input %4 -%20 = OpVariable %21 Input -%24 = OpTypePointer Output %11 -%23 = OpVariable %24 Output -%26 = OpTypeFunction %2 -%30 = OpTypeBool -%36 = OpTypeVector %7 3 -%25 = OpFunction %2 None %26 -%15 = OpLabel -%19 = OpLoad %11 %17 -%22 = OpLoad %4 %20 -%16 = OpCompositeConstruct %12 %19 %22 -OpBranch %27 -%27 = OpLabel -%28 = OpCompositeExtract %4 %16 1 -%29 = OpUMod %4 %28 %3 -%31 = OpIEqual %30 %29 %5 -OpSelectionMerge %32 None -OpBranchConditional %31 %33 %34 -%33 = OpLabel -%35 = OpCompositeExtract %11 %16 0 -OpStore %23 %35 +%14 = OpTypeStruct %10 +%15 = OpTypePointer PushConstant %14 +%13 = OpVariable %15 PushConstant +%19 = OpTypePointer Input %11 +%18 = OpVariable %19 Input +%22 = OpTypePointer Input %4 +%21 = OpVariable %22 Input +%25 = OpTypePointer Output %11 +%24 = OpVariable %25 Output +%27 = OpTypeFunction %2 +%28 = OpTypePointer PushConstant %10 +%32 = OpTypeBool +%38 = OpTypeVector %7 3 +%26 = OpFunction %2 None %27 +%16 = OpLabel +%20 = OpLoad %11 %18 +%23 = OpLoad %4 %21 +%17 = OpCompositeConstruct %12 %20 %23 +OpBranch %29 +%29 = OpLabel +%30 = OpCompositeExtract %4 %17 1 +%31 = OpUMod %4 %30 %3 +%33 = OpIEqual %32 %31 %5 +OpSelectionMerge %34 None +OpBranchConditional %33 %35 %36 +%35 = OpLabel +%37 = OpCompositeExtract %11 %17 0 +OpStore %24 %37 +OpReturn +%36 = OpLabel +%39 = OpCompositeConstruct %38 %6 %6 %6 +%40 = OpCompositeExtract %11 %17 0 +%41 = OpVectorShuffle %38 %40 %40 0 1 2 +%42 = OpFSub %38 %39 %41 +%43 = OpCompositeExtract %11 %17 0 +%44 = OpCompositeExtract %7 %43 3 +%45 = OpCompositeConstruct %11 %42 %44 +OpStore %24 %45 OpReturn %34 = OpLabel -%37 = OpCompositeConstruct %36 %6 %6 %6 -%38 = OpCompositeExtract %11 %16 0 -%39 = OpVectorShuffle %36 %38 %38 0 1 2 -%40 = OpFSub %36 %37 %39 -%41 = OpCompositeExtract %11 %16 0 -%42 = OpCompositeExtract %7 %41 3 -%43 = OpCompositeConstruct %11 %40 %42 -OpStore %23 %43 -OpReturn -%32 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file From 322be0772e4fc92b4a0a2aae5efac5f84e2d500d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 16 Dec 2021 21:06:48 +0000 Subject: [PATCH 1489/2212] spv-in: Implement CompositeInsert for arrays Only adds support for unspecialized arrays --- src/front/spv/mod.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 15afd82f3..88917557a 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1091,6 +1091,7 @@ impl> Parser { selections: &[spirv::Word], type_arena: &UniqueArena, expressions: &mut Arena, + constants: &Arena, span: crate::Span, ) -> Result, Error> { let selection = match selections.first() { @@ -1107,7 +1108,29 @@ impl> Parser { .ok_or(Error::InvalidAccessType(root_type_id))?; (members.len(), child_member.type_id) } - // crate::TypeInner::Array //TODO? + crate::TypeInner::Array { size, .. } => { + let size = match size { + crate::ArraySize::Constant(handle) => match constants[handle] { + crate::Constant { + specialization: Some(_), + .. + } => return Err(Error::UnsupportedType(root_lookup.handle)), + ref unspecialized => unspecialized + .to_array_length() + .ok_or(Error::InvalidArraySize(handle))?, + }, + // A runtime sized array is not a composite type + crate::ArraySize::Dynamic => { + return Err(Error::InvalidAccessType(root_type_id)) + } + }; + + let child_type_id = root_lookup + .base_id + .ok_or(Error::InvalidAccessType(root_type_id))?; + + (size as usize, child_type_id) + } crate::TypeInner::Vector { size, .. } | crate::TypeInner::Matrix { columns: size, .. } => { let child_type_id = root_lookup @@ -1136,6 +1159,7 @@ impl> Parser { &selections[1..], type_arena, expressions, + constants, span, )?; @@ -1735,6 +1759,7 @@ impl> Parser { &selections, ctx.type_arena, ctx.expressions, + ctx.const_arena, span, )?; From 33c1daeceef9268a9502df0720d69c9aa9b464da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 4 Dec 2021 22:25:02 +0000 Subject: [PATCH 1490/2212] glsl-in: Cull the body of do while if needed --- src/front/glsl/parser/declarations.rs | 1 + src/front/glsl/parser/functions.rs | 16 +++++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 4911d0734..6a1cc2ddb 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -292,6 +292,7 @@ impl<'source> ParsingContext<'source> { parser, &mut context, &mut body, + &mut None, )?; parser.add_function(context, name, result, body, meta); diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index aec40357a..6483db052 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -325,7 +325,8 @@ impl<'source> ParsingContext<'source> { let mut loop_body = Block::new(); - self.parse_statement(parser, ctx, &mut loop_body, &mut None)?; + let mut terminator = None; + self.parse_statement(parser, ctx, &mut loop_body, &mut terminator)?; let mut stmt = ctx.stmt_ctx(); @@ -359,6 +360,10 @@ impl<'source> ParsingContext<'source> { crate::Span::default(), ); + if let Some(idx) = terminator { + loop_body.cull(idx..) + } + body.push( Statement::Loop { body: loop_body, @@ -481,7 +486,8 @@ impl<'source> ParsingContext<'source> { let mut block = Block::new(); ctx.push_scope(); - let meta = self.parse_compound_statement(meta, parser, ctx, &mut block)?; + let meta = + self.parse_compound_statement(meta, parser, ctx, &mut block, terminator)?; ctx.remove_current_scope(); @@ -511,8 +517,8 @@ impl<'source> ParsingContext<'source> { parser: &mut Parser, ctx: &mut Context, body: &mut Block, + terminator: &mut Option, ) -> Result { - let mut terminator = None; loop { if let Some(Token { meta: brace_meta, .. @@ -522,14 +528,14 @@ impl<'source> ParsingContext<'source> { break; } - let stmt = self.parse_statement(parser, ctx, body, &mut terminator)?; + let stmt = self.parse_statement(parser, ctx, body, terminator)?; if let Some(stmt_meta) = stmt { meta.subsume(stmt_meta); } } - if let Some(idx) = terminator { + if let Some(idx) = *terminator { body.cull(idx..) } From e1552fd9d500f1a928e18a93f4432ece13ab1e84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 17 Dec 2021 15:28:22 +0000 Subject: [PATCH 1491/2212] wgsl-in: Implement matrix construction from scalar --- src/front/wgsl/mod.rs | 62 ++++- tests/in/operators.wgsl | 12 + tests/out/glsl/operators.main.Compute.glsl | 6 +- tests/out/hlsl/operators.hlsl | 6 +- tests/out/msl/operators.msl | 6 +- tests/out/spv/operators.spvasm | 287 +++++++++++---------- tests/out/wgsl/operators.wgsl | 6 +- 7 files changed, 230 insertions(+), 155 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 0e39ee176..1b9ace3a0 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1981,15 +1981,15 @@ impl Parser { Ok(last_component) })?; + // We can't use the `TypeInner` returned by this because + // `resolve_type` borrows context mutably. + // Use it to insert into the right maps, + // and then grab it again immutably. + ctx.resolve_type(last_component)?; + let expr = if components.is_empty() && ty_resolution.inner_with(ctx.types).scalar_kind().is_some() { - // We can't use the `TypeInner` returned by this because - // `resolve_type` borrows context mutably. - // Use it to insert into the right maps, - // and then grab it again immutably. - ctx.resolve_type(last_component)?; - match ( ty_resolution.inner_with(ctx.types), ctx.typifier.get(last_component, ctx.types), @@ -2035,14 +2035,60 @@ impl Parser { } } } else { + components.push(last_component); + let mut compose_components = Vec::new(); + + if let ( + &crate::TypeInner::Matrix { + rows, + width, + columns, + }, + &crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + .. + }, + ) = ( + ty_resolution.inner_with(ctx.types), + ctx.typifier.get(last_component, ctx.types), + ) { + let vec_ty = ctx.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + width, + kind: crate::ScalarKind::Float, + size: rows, + }, + }, + Default::default(), + ); + + compose_components.reserve(columns as usize); + for vec_components in components.chunks(rows as usize) { + let handle = ctx.expressions.append( + crate::Expression::Compose { + ty: vec_ty, + components: Vec::from(vec_components), + }, + crate::Span::default(), + ); + compose_components.push(handle); + } + } else { + compose_components = components; + } + let ty = match ty_resolution { TypeResolution::Handle(handle) => handle, TypeResolution::Value(inner) => ctx .types .insert(crate::Type { name: None, inner }, Default::default()), }; - components.push(last_component); - crate::Expression::Compose { ty, components } + crate::Expression::Compose { + ty, + components: compose_components, + } }; let span = NagaSpan::from(self.pop_scope(lexer)); diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index d6e5a25a5..da18e3a46 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -46,6 +46,18 @@ struct Foo { fn constructors() -> f32 { var foo: Foo; foo = Foo(vec4(1.0), 1); + + let mat2comp = mat2x2( + 1.0, 0.0, + 0.0, 1.0, + ); + let mat4comp = mat4x4( + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ); + return foo.a.x; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 25308e527..10773041f 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -44,8 +44,10 @@ vec3 bool_cast(vec3 x) { float constructors() { Foo foo; foo = Foo(vec4(1.0), 1); - float _e11 = foo.a.x; - return _e11; + mat2x2 mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); + mat4x4 mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + float _e39 = foo.a.x; + return _e39; } void modulo() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 47b5a59a0..1a858a7e0 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -55,8 +55,10 @@ float constructors() Foo foo = (Foo)0; foo = ConstructFoo(float4(1.0.xxxx), 1); - float _expr11 = foo.a.x; - return _expr11; + float2x2 mat2comp = float2x2(float2(1.0, 0.0), float2(0.0, 1.0)); + float4x4 mat4comp = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); + float _expr39 = foo.a.x; + return _expr39; } void modulo() diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 07a5f1136..5aa0fb44c 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -51,8 +51,10 @@ float constructors( ) { Foo foo; foo = Foo {metal::float4(1.0), 1}; - float _e11 = foo.a.x; - return _e11; + metal::float2x2 mat2comp = metal::float2x2(metal::float2(1.0, 0.0), metal::float2(0.0, 1.0)); + metal::float4x4 mat4comp = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); + float _e39 = foo.a.x; + return _e39; } void modulo( diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 4a16ee167..0b8ee6e96 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 145 +; Bound: 154 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %134 "main" -OpExecutionMode %134 LocalSize 1 1 1 +OpEntryPoint GLCompute %143 "main" +OpExecutionMode %143 LocalSize 1 1 1 OpMemberDecorate %23 0 Offset 0 OpMemberDecorate %23 1 Offset 16 %2 = OpTypeVoid @@ -31,156 +31,165 @@ OpMemberDecorate %23 1 Offset 16 %21 = OpTypeVector %10 4 %22 = OpTypeVector %4 3 %23 = OpTypeStruct %19 %8 -%24 = OpTypeMatrix %19 4 -%25 = OpConstantComposite %19 %3 %3 %3 %3 -%26 = OpConstantComposite %19 %5 %5 %5 %5 -%27 = OpConstantComposite %19 %6 %6 %6 %6 -%28 = OpConstantComposite %20 %7 %7 %7 %7 -%31 = OpTypeFunction %19 -%57 = OpTypeVector %4 2 -%73 = OpTypeFunction %8 -%80 = OpConstantNull %8 -%84 = OpTypeFunction %22 %22 -%86 = OpTypeVector %10 3 -%93 = OpTypePointer Function %23 -%96 = OpTypeFunction %4 -%100 = OpTypePointer Function %19 -%101 = OpTypePointer Function %4 -%103 = OpTypeInt 32 0 -%102 = OpConstant %103 0 -%108 = OpTypeFunction %2 -%112 = OpTypeVector %8 3 -%30 = OpFunction %19 None %31 -%29 = OpLabel -OpBranch %32 -%32 = OpLabel -%33 = OpSelect %8 %9 %7 %11 -%35 = OpCompositeConstruct %21 %9 %9 %9 %9 -%34 = OpSelect %19 %35 %25 %26 -%36 = OpCompositeConstruct %21 %12 %12 %12 %12 -%37 = OpSelect %19 %36 %26 %25 -%38 = OpExtInst %19 %1 FMix %26 %25 %27 -%40 = OpCompositeConstruct %19 %13 %13 %13 %13 -%39 = OpExtInst %19 %1 FMix %26 %25 %40 -%41 = OpCompositeExtract %8 %28 0 -%42 = OpBitcast %4 %41 -%43 = OpBitcast %19 %28 -%44 = OpConvertFToS %20 %26 -%45 = OpCompositeConstruct %20 %33 %33 %33 %33 -%46 = OpIAdd %20 %45 %44 -%47 = OpConvertSToF %19 %46 -%48 = OpFAdd %19 %47 %34 -%49 = OpFAdd %19 %48 %38 -%50 = OpFAdd %19 %49 %39 -%51 = OpCompositeConstruct %19 %42 %42 %42 %42 -%52 = OpFAdd %19 %50 %51 -%53 = OpFAdd %19 %52 %43 -OpReturnValue %53 +%24 = OpTypeVector %4 2 +%25 = OpTypeMatrix %24 2 +%26 = OpTypeMatrix %19 4 +%27 = OpConstantComposite %19 %3 %3 %3 %3 +%28 = OpConstantComposite %19 %5 %5 %5 %5 +%29 = OpConstantComposite %19 %6 %6 %6 %6 +%30 = OpConstantComposite %20 %7 %7 %7 %7 +%33 = OpTypeFunction %19 +%74 = OpTypeFunction %8 +%81 = OpConstantNull %8 +%85 = OpTypeFunction %22 %22 +%87 = OpTypeVector %10 3 +%94 = OpTypePointer Function %23 +%97 = OpTypeFunction %4 +%109 = OpTypePointer Function %19 +%110 = OpTypePointer Function %4 +%112 = OpTypeInt 32 0 +%111 = OpConstant %112 0 +%117 = OpTypeFunction %2 +%121 = OpTypeVector %8 3 +%32 = OpFunction %19 None %33 +%31 = OpLabel +OpBranch %34 +%34 = OpLabel +%35 = OpSelect %8 %9 %7 %11 +%37 = OpCompositeConstruct %21 %9 %9 %9 %9 +%36 = OpSelect %19 %37 %27 %28 +%38 = OpCompositeConstruct %21 %12 %12 %12 %12 +%39 = OpSelect %19 %38 %28 %27 +%40 = OpExtInst %19 %1 FMix %28 %27 %29 +%42 = OpCompositeConstruct %19 %13 %13 %13 %13 +%41 = OpExtInst %19 %1 FMix %28 %27 %42 +%43 = OpCompositeExtract %8 %30 0 +%44 = OpBitcast %4 %43 +%45 = OpBitcast %19 %30 +%46 = OpConvertFToS %20 %28 +%47 = OpCompositeConstruct %20 %35 %35 %35 %35 +%48 = OpIAdd %20 %47 %46 +%49 = OpConvertSToF %19 %48 +%50 = OpFAdd %19 %49 %36 +%51 = OpFAdd %19 %50 %40 +%52 = OpFAdd %19 %51 %41 +%53 = OpCompositeConstruct %19 %44 %44 %44 %44 +%54 = OpFAdd %19 %52 %53 +%55 = OpFAdd %19 %54 %45 +OpReturnValue %55 OpFunctionEnd -%55 = OpFunction %19 None %31 -%54 = OpLabel -OpBranch %56 +%57 = OpFunction %19 None %33 %56 = OpLabel -%58 = OpCompositeConstruct %57 %14 %14 -%59 = OpCompositeConstruct %57 %3 %3 -%60 = OpFAdd %57 %59 %58 -%61 = OpCompositeConstruct %57 %15 %15 -%62 = OpFSub %57 %60 %61 -%63 = OpCompositeConstruct %57 %16 %16 -%64 = OpFDiv %57 %62 %63 -%65 = OpCompositeConstruct %20 %17 %17 %17 %17 -%66 = OpCompositeConstruct %20 %18 %18 %18 %18 -%67 = OpSMod %20 %65 %66 -%68 = OpVectorShuffle %19 %64 %64 0 1 0 1 -%69 = OpConvertSToF %19 %67 -%70 = OpFAdd %19 %68 %69 -OpReturnValue %70 +OpBranch %58 +%58 = OpLabel +%59 = OpCompositeConstruct %24 %14 %14 +%60 = OpCompositeConstruct %24 %3 %3 +%61 = OpFAdd %24 %60 %59 +%62 = OpCompositeConstruct %24 %15 %15 +%63 = OpFSub %24 %61 %62 +%64 = OpCompositeConstruct %24 %16 %16 +%65 = OpFDiv %24 %63 %64 +%66 = OpCompositeConstruct %20 %17 %17 %17 %17 +%67 = OpCompositeConstruct %20 %18 %18 %18 %18 +%68 = OpSMod %20 %66 %67 +%69 = OpVectorShuffle %19 %65 %65 0 1 0 1 +%70 = OpConvertSToF %19 %68 +%71 = OpFAdd %19 %69 %70 +OpReturnValue %71 OpFunctionEnd -%72 = OpFunction %8 None %73 -%71 = OpLabel -OpBranch %74 -%74 = OpLabel -%75 = OpLogicalNot %10 %9 -OpSelectionMerge %76 None -OpBranchConditional %75 %77 %78 -%77 = OpLabel -OpReturnValue %7 +%73 = OpFunction %8 None %74 +%72 = OpLabel +OpBranch %75 +%75 = OpLabel +%76 = OpLogicalNot %10 %9 +OpSelectionMerge %77 None +OpBranchConditional %76 %78 %79 %78 = OpLabel -%79 = OpNot %8 %7 -OpReturnValue %79 -%76 = OpLabel +OpReturnValue %7 +%79 = OpLabel +%80 = OpNot %8 %7 OpReturnValue %80 +%77 = OpLabel +OpReturnValue %81 OpFunctionEnd -%83 = OpFunction %22 None %84 -%82 = OpFunctionParameter %22 -%81 = OpLabel -OpBranch %85 -%85 = OpLabel -%87 = OpCompositeConstruct %22 %5 %5 %5 -%88 = OpFUnordNotEqual %86 %82 %87 -%89 = OpCompositeConstruct %22 %5 %5 %5 -%90 = OpCompositeConstruct %22 %3 %3 %3 -%91 = OpSelect %22 %88 %90 %89 -OpReturnValue %91 +%84 = OpFunction %22 None %85 +%83 = OpFunctionParameter %22 +%82 = OpLabel +OpBranch %86 +%86 = OpLabel +%88 = OpCompositeConstruct %22 %5 %5 %5 +%89 = OpFUnordNotEqual %87 %83 %88 +%90 = OpCompositeConstruct %22 %5 %5 %5 +%91 = OpCompositeConstruct %22 %3 %3 %3 +%92 = OpSelect %22 %89 %91 %90 +OpReturnValue %92 OpFunctionEnd -%95 = OpFunction %4 None %96 -%94 = OpLabel -%92 = OpVariable %93 Function -OpBranch %97 -%97 = OpLabel -%98 = OpCompositeConstruct %19 %3 %3 %3 %3 -%99 = OpCompositeConstruct %23 %98 %7 -OpStore %92 %99 -%104 = OpAccessChain %101 %92 %102 %102 -%105 = OpLoad %4 %104 -OpReturnValue %105 +%96 = OpFunction %4 None %97 +%95 = OpLabel +%93 = OpVariable %94 Function +OpBranch %98 +%98 = OpLabel +%99 = OpCompositeConstruct %19 %3 %3 %3 %3 +%100 = OpCompositeConstruct %23 %99 %7 +OpStore %93 %100 +%101 = OpCompositeConstruct %24 %3 %5 +%102 = OpCompositeConstruct %24 %5 %3 +%103 = OpCompositeConstruct %25 %101 %102 +%104 = OpCompositeConstruct %19 %3 %5 %5 %5 +%105 = OpCompositeConstruct %19 %5 %3 %5 %5 +%106 = OpCompositeConstruct %19 %5 %5 %3 %5 +%107 = OpCompositeConstruct %19 %5 %5 %5 %3 +%108 = OpCompositeConstruct %26 %104 %105 %106 %107 +%113 = OpAccessChain %110 %93 %111 %111 +%114 = OpLoad %4 %113 +OpReturnValue %114 OpFunctionEnd -%107 = OpFunction %2 None %108 -%106 = OpLabel -OpBranch %109 -%109 = OpLabel -%110 = OpSMod %8 %7 %7 -%111 = OpFMod %4 %3 %3 -%113 = OpCompositeConstruct %112 %7 %7 %7 -%114 = OpCompositeConstruct %112 %7 %7 %7 -%115 = OpSMod %112 %113 %114 -%116 = OpCompositeConstruct %22 %3 %3 %3 -%117 = OpCompositeConstruct %22 %3 %3 %3 -%118 = OpFMod %22 %116 %117 +%116 = OpFunction %2 None %117 +%115 = OpLabel +OpBranch %118 +%118 = OpLabel +%119 = OpSMod %8 %7 %7 +%120 = OpFMod %4 %3 %3 +%122 = OpCompositeConstruct %121 %7 %7 %7 +%123 = OpCompositeConstruct %121 %7 %7 %7 +%124 = OpSMod %121 %122 %123 +%125 = OpCompositeConstruct %22 %3 %3 %3 +%126 = OpCompositeConstruct %22 %3 %3 %3 +%127 = OpFMod %22 %125 %126 OpReturn OpFunctionEnd -%120 = OpFunction %2 None %108 -%119 = OpLabel -OpBranch %121 -%121 = OpLabel -%122 = OpCompositeConstruct %19 %3 %5 %5 %5 -%123 = OpCompositeConstruct %19 %5 %3 %5 %5 -%124 = OpCompositeConstruct %19 %5 %5 %3 %5 -%125 = OpCompositeConstruct %19 %5 %5 %5 %3 -%126 = OpCompositeConstruct %24 %122 %123 %124 %125 -%127 = OpMatrixTimesScalar %24 %126 %14 -OpReturn -OpFunctionEnd -%129 = OpFunction %2 None %108 +%129 = OpFunction %2 None %117 %128 = OpLabel OpBranch %130 %130 = OpLabel -%131 = OpLogicalOr %10 %9 %12 -%132 = OpLogicalAnd %10 %9 %12 +%131 = OpCompositeConstruct %19 %3 %5 %5 %5 +%132 = OpCompositeConstruct %19 %5 %3 %5 %5 +%133 = OpCompositeConstruct %19 %5 %5 %3 %5 +%134 = OpCompositeConstruct %19 %5 %5 %5 %3 +%135 = OpCompositeConstruct %26 %131 %132 %133 %134 +%136 = OpMatrixTimesScalar %26 %135 %14 OpReturn OpFunctionEnd -%134 = OpFunction %2 None %108 -%133 = OpLabel -OpBranch %135 -%135 = OpLabel -%136 = OpFunctionCall %19 %30 -%137 = OpFunctionCall %19 %55 -%138 = OpFunctionCall %8 %72 -%139 = OpVectorShuffle %22 %25 %25 0 1 2 -%140 = OpFunctionCall %22 %83 %139 -%141 = OpFunctionCall %4 %95 -%142 = OpFunctionCall %2 %107 -%143 = OpFunctionCall %2 %120 -%144 = OpFunctionCall %2 %129 +%138 = OpFunction %2 None %117 +%137 = OpLabel +OpBranch %139 +%139 = OpLabel +%140 = OpLogicalOr %10 %9 %12 +%141 = OpLogicalAnd %10 %9 %12 +OpReturn +OpFunctionEnd +%143 = OpFunction %2 None %117 +%142 = OpLabel +OpBranch %144 +%144 = OpLabel +%145 = OpFunctionCall %19 %32 +%146 = OpFunctionCall %19 %57 +%147 = OpFunctionCall %8 %73 +%148 = OpVectorShuffle %22 %27 %27 0 1 2 +%149 = OpFunctionCall %22 %84 %148 +%150 = OpFunctionCall %4 %96 +%151 = OpFunctionCall %2 %116 +%152 = OpFunctionCall %2 %129 +%153 = OpFunctionCall %2 %138 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index cc34bbe76..1920ccb3a 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -42,8 +42,10 @@ fn constructors() -> f32 { var foo: Foo; foo = Foo(vec4(1.0), 1); - let _e11 = foo.a.x; - return _e11; + let mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); + let mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + let _e39 = foo.a.x; + return _e39; } fn modulo() { From d13e9e3b83c1bb4a62fefca6e8fd614d524a4c2b Mon Sep 17 00:00:00 2001 From: Christofer Nolander Date: Fri, 17 Dec 2021 17:19:38 +0100 Subject: [PATCH 1492/2212] wgsl-in: correctly parse `else if` (#1611) * wgsl-in: correctly parse `else if` * wgsl-in: use early exit in `else if` parsing --- src/front/wgsl/mod.rs | 19 +++++++++++++------ src/front/wgsl/tests.rs | 2 +- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 1b9ace3a0..f9ef1b981 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3516,9 +3516,20 @@ impl Parser { lexer.expect(Token::Paren(')'))?; let accept = self.parse_block(lexer, context.reborrow(), false)?; + let mut elsif_stack = Vec::new(); let mut elseif_span_start = lexer.current_byte_offset(); - while lexer.skip(Token::Word("elseif")) { + let mut reject = loop { + if !lexer.skip(Token::Word("else")) { + break crate::Block::new(); + } + + if !lexer.skip(Token::Word("if")) { + // ... else { ... } + break self.parse_block(lexer, context.reborrow(), false)?; + } + + // ... else if (...) { ... } let mut sub_emitter = super::Emitter::default(); lexer.expect(Token::Paren('('))?; @@ -3537,12 +3548,8 @@ impl Parser { other_block, )); elseif_span_start = lexer.current_byte_offset(); - } - let mut reject = if lexer.skip(Token::Word("else")) { - self.parse_block(lexer, context.reborrow(), false)? - } else { - crate::Block::new() }; + let span_end = lexer.current_byte_offset(); // reverse-fold the else-if blocks //Note: we may consider uplifting this to the IR diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index f64ac3036..60c02c4e6 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -215,7 +215,7 @@ fn parse_if() { if (0 != 1) {} if (false) { return; - } elseif (true) { + } else if (true) { return; } else {} } From 75ce45d4f3108b256ae96069c87586c59fada839 Mon Sep 17 00:00:00 2001 From: Ashley Date: Tue, 9 Nov 2021 17:53:55 +0100 Subject: [PATCH 1493/2212] spv-in: fix support for degrees and radians conversion --- src/front/spv/mod.rs | 23 +++++++++++++---------- tests/in/spv/degrees.spv | Bin 0 -> 676 bytes tests/snapshots.rs | 23 +++++++---------------- 3 files changed, 20 insertions(+), 26 deletions(-) create mode 100644 tests/in/spv/degrees.spv diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 88917557a..cfdf1fe88 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2539,26 +2539,29 @@ impl> Parser { get_expr_handle!(arg_id, lexp) }; - let constant_handle = ctx.const_arena.fetch_or_append( + // constant expressions need to be excluded from the emitter + block.extend(emitter.finish(ctx.expressions)); + let const_value = match gl_op { + Glo::Radians => std::f64::consts::PI / 180.0, + Glo::Degrees => 180.0 / std::f64::consts::PI, + _ => unreachable!(), + }; + let const_handle = ctx.const_arena.fetch_or_append( crate::Constant { name: None, specialization: None, inner: crate::ConstantInner::Scalar { width: 4, - value: crate::ScalarValue::Float(match gl_op { - Glo::Radians => std::f64::consts::PI / 180.0, - Glo::Degrees => 180.0 / std::f64::consts::PI, - _ => unreachable!(), - }), + value: crate::ScalarValue::Float(const_value), }, }, - Default::default(), + crate::Span::default(), ); - let expr_handle = ctx.expressions.append( - crate::Expression::Constant(constant_handle), - Default::default(), + crate::Expression::Constant(const_handle), + crate::Span::default(), ); + emitter.start(ctx.expressions); self.lookup_expression.insert( result_id, diff --git a/tests/in/spv/degrees.spv b/tests/in/spv/degrees.spv new file mode 100644 index 0000000000000000000000000000000000000000..0e5eeab4801959135ed79998e86f119fe85e56dc GIT binary patch literal 676 zcmYk3%}N775QNL!tVRIyxB;rvB9#jNT@svvr5g$MnSAw8MqTYQrpUR71eX~1| z36<`yuAc6mO_QS)X-R9UYhUH*C@~{7v>fbcd_Nw3d=|sgvlA38r9p_MZ4IYpyynku z_?t%RUt;@XQReJoK69?_T=6t@E_H8do)`8rt(W{mJ}ob!mir!OFSDmU;AO;(a~) z()Z1|cVHgw;-L98li6|?v#>ih#_Ycs^9ID%u13qOSFWXJ!+>i#B5oRd2Y5gY_rb@S zmi>||Yub*fK|_ujdcwz=u6?+PyRh%J0T*%Sjp*O6ayE+GPQ}q9a=R7B+f2M2Z@Xtu SkDfel$Sk}yxj#>NVf+KmpC3H{ literal 0 HcmV?d00001 diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 565f32619..2d9363649 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -519,38 +519,29 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { #[cfg(feature = "spv-in")] #[test] -fn convert_spv_quad_vert() { +fn convert_spv_all() { convert_spv( "quad-vert", false, Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ); -} - -#[cfg(feature = "spv-in")] -#[test] -fn convert_spv_shadow() { convert_spv("shadow", true, Targets::IR | Targets::ANALYSIS); -} - -#[cfg(feature = "spv-in")] -#[test] -fn convert_spv_inverse_hyperbolic_trig_functions() { convert_spv( "inv-hyperbolic-trig-functions", true, Targets::HLSL | Targets::WGSL, ); -} - -#[cfg(feature = "spv-in")] -#[test] -fn convert_spv_empty_global_name() { convert_spv( "empty-global-name", true, Targets::HLSL | Targets::WGSL | Targets::METAL, ); + convert_spv( + "empty-global-name", + true, + Targets::HLSL | Targets::WGSL | Targets::METAL, + ); + convert_spv("degrees", false, Targets::empty()); } #[cfg(feature = "glsl-in")] From db98743a5a264d2573c5c33a78f4cff82db3116b Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 17 Dec 2021 17:23:51 -0800 Subject: [PATCH 1494/2212] [glsl-out] Don't return early from snapshot tests. --- tests/out/wgsl/image.wgsl | 78 +++++++++++++++++++-------------------- tests/snapshots.rs | 2 +- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 631ca5db0..0bc840088 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -35,71 +35,71 @@ var image_2d_depth: texture_depth_2d; [[stage(compute), workgroup_size(16, 1, 1)]] fn main([[builtin(local_invocation_id)]] local_id: vec3) { - let dim: vec2 = textureDimensions(image_storage_src); - let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); - let value1_: vec4 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); - let value2_: vec4 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); - let value4_: vec4 = textureLoad(image_storage_src, itc); - let value5_: vec4 = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); + let dim = textureDimensions(image_storage_src); + let itc = ((dim * vec2(local_id.xy)) % vec2(10, 20)); + let value1_ = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); + let value2_ = textureLoad(image_multisampled_src, itc, i32(local_id.z)); + let value4_ = textureLoad(image_storage_src, itc); + let value5_ = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); textureStore(image_dst, itc.x, (((value1_ + value2_) + value4_) + value5_)); return; } [[stage(compute), workgroup_size(16, 1, 1)]] fn depth_load([[builtin(local_invocation_id)]] local_id_1: vec3) { - let dim_1: vec2 = textureDimensions(image_storage_src); - let itc_1: vec2 = ((dim_1 * vec2(local_id_1.xy)) % vec2(10, 20)); - let val: f32 = textureLoad(image_depth_multisampled_src, itc_1, i32(local_id_1.z)); + let dim_1 = textureDimensions(image_storage_src); + let itc_1 = ((dim_1 * vec2(local_id_1.xy)) % vec2(10, 20)); + let val = textureLoad(image_depth_multisampled_src, itc_1, i32(local_id_1.z)); textureStore(image_dst, itc_1.x, vec4(u32(val))); return; } [[stage(vertex)]] fn queries() -> [[builtin(position)]] vec4 { - let dim_1d: i32 = textureDimensions(image_1d); - let dim_2d: vec2 = textureDimensions(image_2d); - let dim_2d_lod: vec2 = textureDimensions(image_2d, 1); - let dim_2d_array: vec2 = textureDimensions(image_2d_array); - let dim_2d_array_lod: vec2 = textureDimensions(image_2d_array, 1); - let dim_cube: vec2 = textureDimensions(image_cube); - let dim_cube_lod: vec2 = textureDimensions(image_cube, 1); - let dim_cube_array: vec2 = textureDimensions(image_cube_array); - let dim_cube_array_lod: vec2 = textureDimensions(image_cube_array, 1); - let dim_3d: vec3 = textureDimensions(image_3d); - let dim_3d_lod: vec3 = textureDimensions(image_3d, 1); - let sum: i32 = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); + let dim_1d = textureDimensions(image_1d); + let dim_2d = textureDimensions(image_2d); + let dim_2d_lod = textureDimensions(image_2d, 1); + let dim_2d_array = textureDimensions(image_2d_array); + let dim_2d_array_lod = textureDimensions(image_2d_array, 1); + let dim_cube = textureDimensions(image_cube); + let dim_cube_lod = textureDimensions(image_cube, 1); + let dim_cube_array = textureDimensions(image_cube_array); + let dim_cube_array_lod = textureDimensions(image_cube_array, 1); + let dim_3d = textureDimensions(image_3d); + let dim_3d_lod = textureDimensions(image_3d, 1); + let sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); return vec4(f32(sum)); } [[stage(vertex)]] fn levels_queries() -> [[builtin(position)]] vec4 { - let num_levels_2d: i32 = textureNumLevels(image_2d); - let num_levels_2d_array: i32 = textureNumLevels(image_2d_array); - let num_layers_2d: i32 = textureNumLayers(image_2d_array); - let num_levels_cube: i32 = textureNumLevels(image_cube); - let num_levels_cube_array: i32 = textureNumLevels(image_cube_array); - let num_layers_cube: i32 = textureNumLayers(image_cube_array); - let num_levels_3d: i32 = textureNumLevels(image_3d); - let num_samples_aa: i32 = textureNumSamples(image_aa); - let sum_1: i32 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); + let num_levels_2d = textureNumLevels(image_2d); + let num_levels_2d_array = textureNumLevels(image_2d_array); + let num_layers_2d = textureNumLayers(image_2d_array); + let num_levels_cube = textureNumLevels(image_cube); + let num_levels_cube_array = textureNumLevels(image_cube_array); + let num_layers_cube = textureNumLayers(image_cube_array); + let num_levels_3d = textureNumLevels(image_3d); + let num_samples_aa = textureNumSamples(image_aa); + let sum_1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); return vec4(f32(sum_1)); } [[stage(fragment)]] fn sample() -> [[location(0)]] vec4 { - let tc: vec2 = vec2(0.5); - let s1d: vec4 = textureSample(image_1d, sampler_reg, tc.x); - let s2d: vec4 = textureSample(image_2d, sampler_reg, tc); - let s2d_offset: vec4 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); - let s2d_level: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284); - let s2d_level_offset: vec4 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284, vec2(3, 1)); + let tc = vec2(0.5); + let s1d = textureSample(image_1d, sampler_reg, tc.x); + let s2d = textureSample(image_2d, sampler_reg, tc); + let s2d_offset = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); + let s2d_level = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284); + let s2d_level_offset = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284, vec2(3, 1)); return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); } [[stage(fragment)]] fn sample_comparison() -> [[location(0)]] f32 { - let tc_1: vec2 = vec2(0.5); - let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); - let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5); + let tc_1 = vec2(0.5); + let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); + let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5); return (s2d_depth + s2d_depth_level); } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 2d9363649..26d046445 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -144,7 +144,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { if targets.contains(Targets::GLSL) { for ep in module.entry_points.iter() { if params.glsl_exclude_list.contains(&ep.name) { - return; + continue; } write_output_glsl(module, &info, &dest, name, ep.stage, &ep.name, ¶ms.glsl); } From 8caa2bd87e2e4b3bc3ba6276f5bd898d601f1c7d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 15 Dec 2021 00:29:07 -0500 Subject: [PATCH 1495/2212] Gather operations --- src/back/dot/mod.rs | 7 +- src/back/glsl/mod.rs | 29 ++++--- src/back/hlsl/writer.rs | 34 +++++--- src/back/msl/writer.rs | 30 ++++++- src/back/spv/block.rs | 2 + src/back/spv/image.rs | 30 +++++-- src/back/spv/instructions.rs | 27 +++++++ src/back/wgsl/writer.rs | 49 ++++++++++++ src/front/glsl/builtins.rs | 1 + src/front/spv/image.rs | 1 + src/front/wgsl/mod.rs | 96 +++++++++++++++++++++++ src/lib.rs | 5 +- src/proc/typifier.rs | 18 +++++ src/valid/analyzer.rs | 1 + src/valid/expression.rs | 27 +++++++ tests/in/image.param.ron | 2 +- tests/in/image.wgsl | 19 +++++ tests/out/glsl/image.gather.Fragment.glsl | 22 ++++++ tests/out/hlsl/image.hlsl | 18 +++++ tests/out/hlsl/image.hlsl.config | 2 +- tests/out/ir/shadow.ron | 1 + tests/out/msl/image.msl | 32 ++++++++ tests/out/spv/image.spvasm | 54 ++++++++++++- tests/out/wgsl/image.wgsl | 18 +++++ 24 files changed, 484 insertions(+), 41 deletions(-) create mode 100644 tests/out/glsl/image.gather.Fragment.glsl diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index b63a16359..bee46704c 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -231,6 +231,7 @@ fn write_fun( E::ImageSample { image, sampler, + gather, coordinate, array_index, offset: _, @@ -260,7 +261,11 @@ fn write_fun( if let Some(expr) = depth_ref { edges.insert("depth_ref", expr); } - ("ImageSample".into(), 5) + let string = match gather { + Some(component) => Cow::Owned(format!("ImageGather{:?}", component)), + _ => Cow::Borrowed("ImageSample"), + }; + (string, 5) } E::ImageLoad { image, diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9bea98eb1..e32c803f0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1928,6 +1928,7 @@ impl<'a, W: Write> Writer<'a, W> { Expression::ImageSample { image, sampler: _, //TODO? + gather, coordinate, array_index, offset, @@ -1962,6 +1963,7 @@ impl<'a, W: Write> Writer<'a, W> { let workaround_lod_array_shadow_as_grad = (array_index.is_some() || dim == crate::ImageDimension::Cube) && depth_ref.is_some() + && gather.is_none() && !self .options .writer_flags @@ -1969,6 +1971,7 @@ impl<'a, W: Write> Writer<'a, W> { //Write the function to be used depending on the sample level let fun_name = match level { + crate::SampleLevel::Zero if gather.is_some() => "textureGather", crate::SampleLevel::Auto | crate::SampleLevel::Bias(_) => "texture", crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => { if workaround_lod_array_shadow_as_grad { @@ -2002,8 +2005,8 @@ impl<'a, W: Write> Writer<'a, W> { if array_index.is_some() { coord_dim += 1; } - let cube_array_shadow = coord_dim == 4; - if depth_ref.is_some() && !cube_array_shadow { + let merge_depth_ref = depth_ref.is_some() && gather.is_none() && coord_dim < 4; + if merge_depth_ref { coord_dim += 1; } @@ -2021,21 +2024,17 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ", ")?; self.write_expr(expr, ctx)?; } - if !cube_array_shadow { - if let Some(expr) = depth_ref { - write!(self.out, ", ")?; - self.write_expr(expr, ctx)?; - } + if merge_depth_ref { + write!(self.out, ", ")?; + self.write_expr(depth_ref.unwrap(), ctx)?; } if is_vec { write!(self.out, ")")?; } - if cube_array_shadow { - if let Some(expr) = depth_ref { - write!(self.out, ", ")?; - self.write_expr(expr, ctx)?; - } + if let (Some(expr), false) = (depth_ref, merge_depth_ref) { + write!(self.out, ", ")?; + self.write_expr(expr, ctx)?; } match level { @@ -2045,7 +2044,7 @@ impl<'a, W: Write> Writer<'a, W> { crate::SampleLevel::Zero => { if workaround_lod_array_shadow_as_grad { write!(self.out, ", vec2(0,0), vec2(0,0)")?; - } else { + } else if gather.is_none() { write!(self.out, ", 0.0")?; } } @@ -2082,6 +2081,10 @@ impl<'a, W: Write> Writer<'a, W> { } } + if let (Some(component), None) = (gather, depth_ref) { + write!(self.out, ", {}", component as usize)?; + } + // End the function write!(self.out, ")")? } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index d8cfde3cd..ca00d889c 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1594,6 +1594,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Expression::ImageSample { image, sampler, + gather, coordinate, array_index, offset, @@ -1601,23 +1602,30 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { depth_ref, } => { use crate::SampleLevel as Sl; + const COMPONENTS: [&str; 4] = ["", "Green", "Blue", "Alpha"]; - let texture_func = match level { - Sl::Auto => { - if depth_ref.is_some() { - "SampleCmp" - } else { - "Sample" - } - } - Sl::Zero => "SampleCmpLevelZero", - Sl::Exact(_) => "SampleLevel", - Sl::Bias(_) => "SampleBias", - Sl::Gradient { .. } => "SampleGrad", + let (base_str, component_str) = match gather { + Some(component) => ("Gather", COMPONENTS[component as usize]), + None => ("Sample", ""), + }; + let cmp_str = match depth_ref { + Some(_) => "Cmp", + None => "", + }; + let level_str = match level { + Sl::Zero if gather.is_none() => "LevelZero", + Sl::Auto | Sl::Zero => "", + Sl::Exact(_) => "Level", + Sl::Bias(_) => "Bias", + Sl::Gradient { .. } => "Grad", }; self.write_expr(module, image, func_ctx)?; - write!(self.out, ".{}(", texture_func)?; + write!( + self.out, + ".{}{}{}{}(", + base_str, cmp_str, component_str, level_str + )?; self.write_expr(module, sampler, func_ctx)?; write!(self.out, ", ")?; self.write_texture_coordinates( diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 51f892d78..1050f1434 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -896,18 +896,23 @@ impl Writer { crate::Expression::ImageSample { image, sampler, + gather, coordinate, array_index, offset, level, depth_ref, } => { - let op = match depth_ref { - Some(_) => "sample_compare", + let main_op = match gather { + Some(_) => "gather", None => "sample", }; + let comparison_op = match depth_ref { + Some(_) => "_compare", + None => "", + }; self.put_expression(image, context, false)?; - write!(self.out, ".{}(", op)?; + write!(self.out, ".{}{}(", main_op, comparison_op)?; self.put_expression(sampler, context, true)?; write!(self.out, ", ")?; self.put_expression(coordinate, context, true)?; @@ -931,6 +936,25 @@ impl Writer { }; write!(self.out, ", {}", coco)?; } + match gather { + None | Some(crate::SwizzleComponent::X) => {} + Some(component) => { + let is_cube_map = match *context.resolve_type(image) { + crate::TypeInner::Image { + dim: crate::ImageDimension::Cube, + .. + } => true, + _ => false, + }; + // Offset always comes before the gather, except + // in cube maps where it's not applicable + if offset.is_none() && !is_cube_map { + write!(self.out, ", int2(0)")?; + } + let letter = ['x', 'y', 'z', 'w'][component as usize]; + write!(self.out, ", {}::component::{}", NAMESPACE, letter)?; + } + } write!(self.out, ")")?; } crate::Expression::ImageLoad { diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index a59f85453..5f01ca028 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -891,6 +891,7 @@ impl<'w> BlockContext<'w> { crate::Expression::ImageSample { image, sampler, + gather, coordinate, array_index, offset, @@ -900,6 +901,7 @@ impl<'w> BlockContext<'w> { result_type_id, image, sampler, + gather, coordinate, array_index, offset, diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 442045ed2..443ef8c57 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -799,6 +799,7 @@ impl<'w> BlockContext<'w> { result_type_id: Word, image: Handle, sampler: Handle, + gather: Option, coordinate: Handle, array_index: Option>, offset: Option>, @@ -816,7 +817,7 @@ impl<'w> BlockContext<'w> { crate::TypeInner::Image { class: crate::ImageClass::Depth { .. }, .. - } => depth_ref.is_none(), + } => depth_ref.is_none() && gather.is_none(), _ => false, }; let sample_result_type_id = if needs_sub_access { @@ -853,8 +854,23 @@ impl<'w> BlockContext<'w> { let mut mask = spirv::ImageOperands::empty(); mask.set(spirv::ImageOperands::CONST_OFFSET, offset.is_some()); - let mut main_instruction = match level { - crate::SampleLevel::Zero => { + let mut main_instruction = match (level, gather) { + (_, Some(component)) => { + let component_id = self.get_index_constant(component as u32); + let mut inst = Instruction::image_gather( + sample_result_type_id, + id, + sampled_image_id, + coordinates_id, + component_id, + depth_id, + ); + if !mask.is_empty() { + inst.add_operand(mask.bits()); + } + inst + } + (crate::SampleLevel::Zero, None) => { let mut inst = Instruction::image_sample( sample_result_type_id, id, @@ -874,7 +890,7 @@ impl<'w> BlockContext<'w> { inst } - crate::SampleLevel::Auto => { + (crate::SampleLevel::Auto, None) => { let mut inst = Instruction::image_sample( sample_result_type_id, id, @@ -888,7 +904,7 @@ impl<'w> BlockContext<'w> { } inst } - crate::SampleLevel::Exact(lod_handle) => { + (crate::SampleLevel::Exact(lod_handle), None) => { let mut inst = Instruction::image_sample( sample_result_type_id, id, @@ -905,7 +921,7 @@ impl<'w> BlockContext<'w> { inst } - crate::SampleLevel::Bias(bias_handle) => { + (crate::SampleLevel::Bias(bias_handle), None) => { let mut inst = Instruction::image_sample( sample_result_type_id, id, @@ -922,7 +938,7 @@ impl<'w> BlockContext<'w> { inst } - crate::SampleLevel::Gradient { x, y } => { + (crate::SampleLevel::Gradient { x, y }, None) => { let mut inst = Instruction::image_sample( sample_result_type_id, id, diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 211c51a1e..79f54d450 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -569,6 +569,33 @@ impl super::Instruction { instruction } + pub(super) fn image_gather( + result_type_id: Word, + id: Word, + sampled_image: Word, + coordinates: Word, + component_id: Word, + depth_ref: Option, + ) -> Self { + let op = match depth_ref { + None => Op::ImageGather, + Some(_) => Op::ImageDrefGather, + }; + + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(sampled_image); + instruction.add_operand(coordinates); + if let Some(dref) = depth_ref { + instruction.add_operand(dref); + } else { + instruction.add_operand(component_id); + } + + instruction + } + pub(super) fn image_fetch_or_read( op: Op, result_type_id: Word, diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 4d06b7a94..6c226fe44 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1239,6 +1239,7 @@ impl Writer { Expression::ImageSample { image, sampler, + gather: None, coordinate, array_index, offset, @@ -1306,6 +1307,54 @@ impl Writer { write!(self.out, ")")?; } + Expression::ImageSample { + image, + sampler, + gather: Some(component), + coordinate, + array_index, + offset, + level: _, + depth_ref, + } => { + let suffix_cmp = match depth_ref { + Some(_) => "Compare", + None => "", + }; + + write!(self.out, "textureGather{}(", suffix_cmp)?; + match *func_ctx.info[image].ty.inner_with(&module.types) { + TypeInner::Image { + class: crate::ImageClass::Depth { multi: _ }, + .. + } => {} + _ => { + write!(self.out, "{}, ", component as u8)?; + } + } + self.write_expr(module, image, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, sampler, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, coordinate, func_ctx)?; + + if let Some(array_index) = array_index { + write!(self.out, ", ")?; + self.write_expr(module, array_index, func_ctx)?; + } + + if let Some(depth_ref) = depth_ref { + write!(self.out, ", ")?; + self.write_expr(module, depth_ref, func_ctx)?; + } + + if let Some(offset) = offset { + write!(self.out, ", ")?; + self.write_constant(module, offset)?; + } + + write!(self.out, ")")?; + } Expression::ImageQuery { image, query } => { use crate::ImageQuery as Iq; diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index ed220bc98..a7416ded2 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1930,6 +1930,7 @@ fn texture_call( Expression::ImageSample { image, sampler, + gather: None, //TODO coordinate: comps.coordinate, array_index, offset, diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 1df6cb5f9..e797a516a 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -606,6 +606,7 @@ impl> super::Parser { let expr = crate::Expression::ImageSample { image: si_lexp.image, sampler: si_lexp.sampler, + gather: None, //TODO coordinate, array_index, offset, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f9ef1b981..a58f63d42 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -148,6 +148,7 @@ pub enum Error<'a> { }, InvalidResolve(ResolveError), InvalidForInitializer(Span), + InvalidGatherComponent(Span, i32), ReservedIdentifierPrefix(Span), UnknownStorageClass(Span), UnknownAttribute(Span), @@ -342,6 +343,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "not an assignment or function call".into())], notes: vec![], }, + Error::InvalidGatherComponent(ref bad_span, component) => ParseError { + message: format!("textureGather component {} doesn't exist, must be 0, 1, 2, or 3", component), + labels: vec![(bad_span.clone(), "invalid component".into())], + notes: vec![], + }, Error::ReservedIdentifierPrefix(ref bad_span) => ParseError { message: format!("Identifier starts with a reserved prefix: '{}'", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "invalid identifier".into())], @@ -1648,6 +1654,7 @@ impl Parser { crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + gather: None, coordinate, array_index, offset, @@ -1681,6 +1688,7 @@ impl Parser { crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + gather: None, coordinate, array_index, offset, @@ -1714,6 +1722,7 @@ impl Parser { crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + gather: None, coordinate, array_index, offset, @@ -1749,6 +1758,7 @@ impl Parser { crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + gather: None, coordinate, array_index, offset, @@ -1782,6 +1792,7 @@ impl Parser { crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + gather: None, coordinate, array_index, offset, @@ -1815,6 +1826,91 @@ impl Parser { crate::Expression::ImageSample { image: sc.image, sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + gather: None, + coordinate, + array_index, + offset, + level: crate::SampleLevel::Zero, + depth_ref: Some(reference), + } + } + "textureGather" => { + let _ = lexer.next(); + lexer.open_arguments()?; + let component = if let ( + Token::Number { + value, + ty: NumberType::Sint, + width: None, + }, + span, + ) = lexer.peek() + { + let _ = lexer.next(); + lexer.expect(Token::Separator(','))?; + let index = get_i32_literal(value, span.clone())?; + *crate::SwizzleComponent::XYZW + .get(index as usize) + .ok_or(Error::InvalidGatherComponent(span, index))? + } else { + crate::SwizzleComponent::X + }; + let (image_name, image_span) = lexer.next_ident_with_span()?; + lexer.expect(Token::Separator(','))?; + let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let sc = ctx.prepare_sampling(image_name, image_span)?; + let array_index = if sc.arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; + let offset = if lexer.skip(Token::Separator(',')) { + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) + } else { + None + }; + lexer.close_arguments()?; + crate::Expression::ImageSample { + image: sc.image, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + gather: Some(component), + coordinate, + array_index, + offset, + level: crate::SampleLevel::Zero, + depth_ref: None, + } + } + "textureGatherCompare" => { + let _ = lexer.next(); + lexer.open_arguments()?; + let (image_name, image_span) = lexer.next_ident_with_span()?; + lexer.expect(Token::Separator(','))?; + let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + lexer.expect(Token::Separator(','))?; + let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; + let sc = ctx.prepare_sampling(image_name, image_span)?; + let array_index = if sc.arrayed { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; + lexer.expect(Token::Separator(','))?; + let reference = self.parse_general_expression(lexer, ctx.reborrow())?; + let offset = if lexer.skip(Token::Separator(',')) { + Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) + } else { + None + }; + lexer.close_arguments()?; + crate::Expression::ImageSample { + image: sc.image, + sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + gather: Some(crate::SwizzleComponent::X), coordinate, array_index, offset, diff --git a/src/lib.rs b/src/lib.rs index a2d2ec15a..7be2b5377 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -975,7 +975,7 @@ pub enum ImageQuery { /// Component selection for a vector swizzle. #[repr(u8)] -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] pub enum SwizzleComponent { @@ -1128,6 +1128,9 @@ pub enum Expression { ImageSample { image: Handle, sampler: Handle, + /// If Some(), this operation is a gather operation + /// on the selected component. + gather: Option, coordinate: Handle, array_index: Option>, offset: Option>, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index e1d2bd6b8..cf6035802 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -472,6 +472,24 @@ impl<'a> ResolveContext<'a> { return Err(ResolveError::InvalidPointer(pointer)); } }, + crate::Expression::ImageSample { + image, + gather: Some(_), + .. + } => match *past(image).inner_with(types) { + Ti::Image { class, .. } => TypeResolution::Value(Ti::Vector { + kind: match class { + crate::ImageClass::Sampled { kind, multi: _ } => kind, + _ => crate::ScalarKind::Float, + }, + width: 4, + size: crate::VectorSize::Quad, + }), + ref other => { + log::error!("Image type {:?}", other); + return Err(ResolveError::InvalidImage(image)); + } + }, crate::Expression::ImageSample { image, .. } | crate::Expression::ImageLoad { image, .. } => match *past(image).inner_with(types) { Ti::Image { class, .. } => TypeResolution::Value(match class { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index c581a5681..ab4d77c42 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -462,6 +462,7 @@ impl FunctionInfo { E::ImageSample { image, sampler, + gather: _, coordinate, array_index, offset: _, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 21da06baa..26ec967b1 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -99,6 +99,12 @@ pub enum ExpressionError { InvalidDepthReference(Handle), #[error("Depth sample level can only be Auto or Zero")] InvalidDepthSampleLevel, + #[error("Gather level can only be Zero")] + InvalidGatherLevel, + #[error("Gather component {0:?} doesn't exist in the image")] + InvalidGatherComponent(crate::SwizzleComponent), + #[error("Gather can't be done for image dimension {0:?}")] + InvalidGatherDimension(crate::ImageDimension), #[error("Sample level (exact) type {0:?} is not a scalar float")] InvalidSampleLevelExactType(Handle), #[error("Sample level (bias) type {0:?} is not a scalar float")] @@ -343,6 +349,7 @@ impl super::Validator { E::ImageSample { image, sampler, + gather, coordinate, array_index, offset, @@ -466,6 +473,26 @@ impl super::Validator { } } + if let Some(component) = gather { + match dim { + crate::ImageDimension::D2 | crate::ImageDimension::Cube => {} + crate::ImageDimension::D1 | crate::ImageDimension::D3 => { + return Err(ExpressionError::InvalidGatherDimension(dim)) + } + }; + let max_component = match class { + crate::ImageClass::Depth { .. } => crate::SwizzleComponent::X, + _ => crate::SwizzleComponent::W, + }; + if component > max_component { + return Err(ExpressionError::InvalidGatherComponent(component)); + } + match level { + crate::SampleLevel::Zero => {} + _ => return Err(ExpressionError::InvalidGatherLevel), + } + } + // check level properties match level { crate::SampleLevel::Auto => ShaderStages::FRAGMENT, diff --git a/tests/in/image.param.ron b/tests/in/image.param.ron index 76105e335..5b6d71def 100644 --- a/tests/in/image.param.ron +++ b/tests/in/image.param.ron @@ -3,5 +3,5 @@ version: (1, 1), debug: true, ), - glsl_exclude_list: ["depth_load", "levels_queries"] + glsl_exclude_list: ["depth_load", "depth_no_comparison", "levels_queries"] ) diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index e9fd4f0fa..8d27b8820 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -116,3 +116,22 @@ fn sample_comparison() -> [[location(0)]] f32 { let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc, dref); return s2d_depth + s2d_depth_level; } + +[[stage(fragment)]] +fn gather() -> [[location(0)]] vec4 { + let tc = vec2(0.5); + let dref = 0.5; + let s2d = textureGather(1, image_2d, sampler_reg, tc); + let s2d_offset = textureGather(3, image_2d, sampler_reg, tc, vec2(3, 1)); + let s2d_depth = textureGatherCompare(image_2d_depth, sampler_cmp, tc, dref); + let s2d_depth_offset = textureGatherCompare(image_2d_depth, sampler_cmp, tc, dref, vec2(3, 1)); + return s2d + s2d_offset + s2d_depth + s2d_depth_offset; +} + +[[stage(fragment)]] +fn depth_no_comparison() -> [[location(0)]] vec4 { + let tc = vec2(0.5); + let s2d = textureSample(image_2d_depth, sampler_reg, tc); + let s2d_gather = textureGather(image_2d_depth, sampler_reg, tc); + return s2d + s2d_gather; +} diff --git a/tests/out/glsl/image.gather.Fragment.glsl b/tests/out/glsl/image.gather.Fragment.glsl new file mode 100644 index 000000000..89961fcff --- /dev/null +++ b/tests/out/glsl/image.gather.Fragment.glsl @@ -0,0 +1,22 @@ +#version 310 es +#extension GL_EXT_texture_cube_map_array : require + +precision highp float; +precision highp int; + +uniform highp sampler2D _group_0_binding_1; + +uniform highp sampler2DShadow _group_1_binding_2; + +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + vec2 tc = vec2(0.5); + vec4 s2d = textureGather(_group_0_binding_1, vec2(tc), 1); + vec4 s2d_offset = textureGatherOffset(_group_0_binding_1, vec2(tc), ivec2(3, 1), 3); + vec4 s2d_depth = textureGather(_group_1_binding_2, vec2(tc), 0.5); + vec4 s2d_depth_offset = textureGatherOffset(_group_1_binding_2, vec2(tc), 0.5, ivec2(3, 1)); + _fs2p_location0 = (((s2d + s2d_offset) + s2d_depth) + s2d_depth_offset); + return; +} + diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 796c74841..1d36273f4 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -229,3 +229,21 @@ float sample_comparison() : SV_Target0 float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc_1, 0.5); return (s2d_depth + s2d_depth_level); } + +float4 gather() : SV_Target0 +{ + float2 tc_2 = float2(0.5.xx); + float4 s2d_1 = image_2d.GatherGreen(sampler_reg, tc_2); + float4 s2d_offset_1 = image_2d.GatherAlpha(sampler_reg, tc_2, int2(3, 1)); + float4 s2d_depth_1 = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5); + float4 s2d_depth_offset = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5, int2(3, 1)); + return (((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset); +} + +float4 depth_no_comparison() : SV_Target0 +{ + float2 tc_3 = float2(0.5.xx); + float s2d_2 = image_2d_depth.Sample(sampler_reg, tc_3); + float4 s2d_gather = image_2d_depth.Gather(sampler_reg, tc_3); + return (float4(s2d_2.xxxx) + s2d_gather); +} diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config index 28af7d931..ba8a24dd0 100644 --- a/tests/out/hlsl/image.hlsl.config +++ b/tests/out/hlsl/image.hlsl.config @@ -1,3 +1,3 @@ vertex=(queries:vs_5_1 levels_queries:vs_5_1 ) -fragment=(sample_:ps_5_1 sample_comparison:ps_5_1 ) +fragment=(sample_:ps_5_1 sample_comparison:ps_5_1 gather:ps_5_1 depth_no_comparison:ps_5_1 ) compute=(main:cs_5_1 depth_load:cs_5_1 ) diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 0356f1371..ab8c3eeb7 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -870,6 +870,7 @@ ImageSample( image: 4, sampler: 5, + gather: None, coordinate: 72, array_index: Some(74), offset: None, diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 449dc9c43..cbe68c649 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -122,3 +122,35 @@ fragment sample_comparisonOutput sample_comparison( float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); return sample_comparisonOutput { s2d_depth + s2d_depth_level }; } + + +struct gatherOutput { + metal::float4 member_6 [[color(0)]]; +}; +fragment gatherOutput gather( + metal::texture2d image_2d [[user(fake0)]] +, metal::sampler sampler_reg [[user(fake0)]] +, metal::sampler sampler_cmp [[user(fake0)]] +, metal::depth2d image_2d_depth [[user(fake0)]] +) { + metal::float2 tc_2 = metal::float2(0.5); + metal::float4 s2d_1 = image_2d.gather(sampler_reg, tc_2, int2(0), metal::component::y); + metal::float4 s2d_offset_1 = image_2d.gather(sampler_reg, tc_2, const_type_8_, metal::component::w); + metal::float4 s2d_depth_1 = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5); + metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, const_type_8_); + return gatherOutput { ((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset }; +} + + +struct depth_no_comparisonOutput { + metal::float4 member_7 [[color(0)]]; +}; +fragment depth_no_comparisonOutput depth_no_comparison( + metal::sampler sampler_reg [[user(fake0)]] +, metal::depth2d image_2d_depth [[user(fake0)]] +) { + metal::float2 tc_3 = metal::float2(0.5); + float s2d_2 = image_2d_depth.sample(sampler_reg, tc_3); + metal::float4 s2d_gather = image_2d_depth.gather(sampler_reg, tc_3); + return depth_no_comparisonOutput { metal::float4(s2d_2) + s2d_gather }; +} diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 9fc7d518e..82ab063c9 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 244 +; Bound: 280 OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D @@ -15,10 +15,14 @@ OpEntryPoint Vertex %128 "queries" %126 OpEntryPoint Vertex %176 "levels_queries" %175 OpEntryPoint Fragment %205 "sample" %204 OpEntryPoint Fragment %232 "sample_comparison" %230 +OpEntryPoint Fragment %246 "gather" %245 +OpEntryPoint Fragment %268 "depth_no_comparison" %267 OpExecutionMode %69 LocalSize 16 1 1 OpExecutionMode %107 LocalSize 16 1 1 OpExecutionMode %205 OriginUpperLeft OpExecutionMode %232 OriginUpperLeft +OpExecutionMode %246 OriginUpperLeft +OpExecutionMode %268 OriginUpperLeft OpSource GLSL 450 OpName %31 "image_mipmapped_src" OpName %33 "image_multisampled_src" @@ -45,6 +49,8 @@ OpName %128 "queries" OpName %176 "levels_queries" OpName %205 "sample" OpName %232 "sample_comparison" +OpName %246 "gather" +OpName %268 "depth_no_comparison" OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 0 OpDecorate %33 DescriptorSet 0 @@ -88,6 +94,8 @@ OpDecorate %126 BuiltIn Position OpDecorate %175 BuiltIn Position OpDecorate %204 Location 0 OpDecorate %230 Location 0 +OpDecorate %245 Location 0 +OpDecorate %267 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -170,6 +178,10 @@ OpDecorate %230 Location 0 %230 = OpVariable %231 Output %237 = OpTypeSampledImage %29 %242 = OpConstant %8 0.0 +%245 = OpVariable %127 Output +%255 = OpConstant %12 1 +%258 = OpConstant %12 3 +%267 = OpVariable %127 Output %69 = OpFunction %2 None %70 %65 = OpLabel %68 = OpLoad %18 %66 @@ -353,4 +365,44 @@ OpBranch %235 %243 = OpFAdd %8 %239 %241 OpStore %230 %243 OpReturn +OpFunctionEnd +%246 = OpFunction %2 None %70 +%244 = OpLabel +%247 = OpLoad %21 %47 +%248 = OpLoad %28 %59 +%249 = OpLoad %28 %61 +%250 = OpLoad %29 %63 +OpBranch %251 +%251 = OpLabel +%252 = OpCompositeConstruct %210 %7 %7 +%253 = OpSampledImage %216 %247 %248 +%254 = OpImageGather %27 %253 %252 %255 +%256 = OpSampledImage %216 %247 %248 +%257 = OpImageGather %27 %256 %252 %258 ConstOffset %30 +%259 = OpSampledImage %237 %250 %249 +%260 = OpImageDrefGather %27 %259 %252 %7 +%261 = OpSampledImage %237 %250 %249 +%262 = OpImageDrefGather %27 %261 %252 %7 ConstOffset %30 +%263 = OpFAdd %27 %254 %257 +%264 = OpFAdd %27 %263 %260 +%265 = OpFAdd %27 %264 %262 +OpStore %245 %265 +OpReturn +OpFunctionEnd +%268 = OpFunction %2 None %70 +%266 = OpLabel +%269 = OpLoad %28 %59 +%270 = OpLoad %29 %63 +OpBranch %271 +%271 = OpLabel +%272 = OpCompositeConstruct %210 %7 %7 +%273 = OpSampledImage %237 %270 %269 +%274 = OpImageSampleImplicitLod %27 %273 %272 +%275 = OpCompositeExtract %8 %274 0 +%276 = OpSampledImage %237 %270 %269 +%277 = OpImageGather %27 %276 %272 %136 +%278 = OpCompositeConstruct %27 %275 %275 %275 %275 +%279 = OpFAdd %27 %278 %277 +OpStore %267 %279 +OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 0bc840088..0a7eda004 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -103,3 +103,21 @@ fn sample_comparison() -> [[location(0)]] f32 { let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5); return (s2d_depth + s2d_depth_level); } + +[[stage(fragment)]] +fn gather() -> [[location(0)]] vec4 { + let tc_2 = vec2(0.5); + let s2d_1 = textureGather(1, image_2d, sampler_reg, tc_2); + let s2d_offset_1 = textureGather(3, image_2d, sampler_reg, tc_2, vec2(3, 1)); + let s2d_depth_1 = textureGatherCompare(image_2d_depth, sampler_cmp, tc_2, 0.5); + let s2d_depth_offset = textureGatherCompare(image_2d_depth, sampler_cmp, tc_2, 0.5, vec2(3, 1)); + return (((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset); +} + +[[stage(fragment)]] +fn depth_no_comparison() -> [[location(0)]] vec4 { + let tc_3 = vec2(0.5); + let s2d_2 = textureSample(image_2d_depth, sampler_reg, tc_3); + let s2d_gather = textureGather(image_2d_depth, sampler_reg, tc_3); + return (vec4(s2d_2) + s2d_gather); +} From c2328fea755b98fbc37987f2c0bf1ee23e1a55e5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 16 Dec 2021 19:05:20 -0500 Subject: [PATCH 1496/2212] Release v0.8 --- CHANGELOG.md | 36 +++++++++++++++++++++++++++++++++++- Cargo.toml | 4 ++-- tests/in/globals.wgsl | 32 ++++++++++++++++---------------- 3 files changed, 53 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da938ff2e..93ab09e9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,42 @@ # Change Log -## v0.8 (TBD) +## v0.8 (2021-12-18) + - development release for wgpu-0.12 + - lots of fixes in all parts + - validator: + - now gated by `validate` feature + - nicely detailed error messages with spans + - API: + - image gather operations - WGSL-in: - remove `[[block]]` attribute + - `elseif` is removed in favor of `else if` + - MSL-out: + - full out-of-bounds checking + +### v0.7.3 (2021-12-14) + - API: + - `view_index` builtin + - GLSL-out: + - reflect textures without samplers + - SPV-out: + - fix incorrect pack/unpack + +### v0.7.2 (2021-12-01) + - validator: + - check stores for proper pointer class + - HLSL-out: + - fix stores into `mat3` + - respect array strides + - SPV-out: + - fix multi-word constants + - WGSL-in: + - permit names starting with underscores + - SPV-in: + - cull unused builtins + - support empty debug labels + - GLSL-in: + - don't panic on invalid integer operations ### v0.7.1 (2021-10-12) - implement casts from and to booleans in the backends diff --git a/Cargo.toml b/Cargo.toml index 44a7eaf7a..b3eaa2416 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,11 +1,11 @@ [package] name = "naga" -version = "0.7.1" +version = "0.8.0" authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" homepage = "https://github.com/gfx-rs/naga" -repository = "https://github.com/gfx-rs/naga/tree/v0.7" +repository = "https://github.com/gfx-rs/naga/tree/v0.8" keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 17d470f99..87b25f6b6 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -1,16 +1,16 @@ -// Global variable & constant declarations - -let Foo: bool = true; - -var wg : array; -var at: atomic; - -[[stage(compute), workgroup_size(1)]] -fn main() { - wg[3] = 1.0; - atomicStore(&at, 2u); - - // Valid, Foo and at is in function scope - var Foo: f32 = 1.0; - var at: bool = true; -} +// Global variable & constant declarations + +let Foo: bool = true; + +var wg : array; +var at: atomic; + +[[stage(compute), workgroup_size(1)]] +fn main() { + wg[3] = 1.0; + atomicStore(&at, 2u); + + // Valid, Foo and at is in function scope + var Foo: f32 = 1.0; + var at: bool = true; +} From f9b348557a31053cd97156178c26f7d9f3205a7d Mon Sep 17 00:00:00 2001 From: Jonathan Behrens Date: Mon, 20 Dec 2021 14:48:54 -0500 Subject: [PATCH 1497/2212] Add FindLsb / FindMsb (#1473) * Add FindLsb / FindMsb * Fixes and tests for FindLsb/FindMsb * Add findLsb / findMsb as WGSL builtins * Fix tests * Fix incompatible type issue with MSL output * Requested changes * Test fewer cases of findLsb/findMsb --- src/back/glsl/mod.rs | 2 ++ src/back/hlsl/writer.rs | 2 ++ src/back/msl/writer.rs | 33 +++++++++++++++++++++++++++ src/back/spv/block.rs | 6 +++++ src/back/wgsl/writer.rs | 2 ++ src/front/glsl/builtins.rs | 5 +++- src/front/spv/mod.rs | 2 ++ src/front/wgsl/conv.rs | 2 ++ src/lib.rs | 2 ++ src/proc/mod.rs | 2 ++ src/proc/typifier.rs | 10 ++++++++ src/valid/expression.rs | 2 +- tests/in/bits.wgsl | 4 ++++ tests/in/glsl/bits_glsl.frag | 16 +++++++++++++ tests/out/glsl/bits.main.Compute.glsl | 8 +++++++ tests/out/msl/bits.msl | 8 +++++++ tests/out/spv/bits.spvasm | 14 +++++++++++- tests/out/wgsl/bits.wgsl | 8 +++++++ tests/out/wgsl/bits_glsl-frag.wgsl | 32 ++++++++++++++++++++++++++ 19 files changed, 157 insertions(+), 3 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index e32c803f0..34a22b524 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2485,6 +2485,8 @@ impl<'a, W: Write> Writer<'a, W> { Mf::ReverseBits => "bitfieldReverse", Mf::ExtractBits => "bitfieldExtract", Mf::InsertBits => "bitfieldInsert", + Mf::FindLsb => "findLSB", + Mf::FindMsb => "findMSB", // data packing Mf::Pack4x8snorm => "packSnorm4x8", Mf::Pack4x8unorm => "packUnorm4x8", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index ca00d889c..2f7b4e7ad 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1874,6 +1874,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // bits Mf::CountOneBits => Function::Regular("countbits"), Mf::ReverseBits => Function::Regular("reversebits"), + Mf::FindLsb => Function::Regular("firstbitlow"), + Mf::FindMsb => Function::Regular("firstbithigh"), _ => return Err(Error::Unimplemented(format!("write_expr_math {:?}", fun))), }; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 1050f1434..664b7ea2f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1099,6 +1099,21 @@ impl Writer { crate::TypeInner::Scalar { .. } => true, _ => false, }; + let argument_size_suffix = match *context.resolve_type(arg) { + crate::TypeInner::Vector { + size: crate::VectorSize::Bi, + .. + } => "2", + crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + .. + } => "3", + crate::TypeInner::Vector { + size: crate::VectorSize::Quad, + .. + } => "4", + _ => "", + }; let fun_name = match fun { // comparison @@ -1162,6 +1177,8 @@ impl Writer { Mf::ReverseBits => "reverse_bits", Mf::ExtractBits => "extract_bits", Mf::InsertBits => "insert_bits", + Mf::FindLsb => "", + Mf::FindMsb => "", // data packing Mf::Pack4x8snorm => "pack_float_to_unorm4x8", Mf::Pack4x8unorm => "pack_float_to_snorm4x8", @@ -1182,6 +1199,22 @@ impl Writer { write!(self.out, " - ")?; self.put_expression(arg1.unwrap(), context, false)?; write!(self.out, ")")?; + } else if fun == Mf::FindLsb { + write!( + self.out, + "(((1 + int{}({}::ctz(", + argument_size_suffix, NAMESPACE + )?; + self.put_expression(arg, context, true)?; + write!(self.out, "))) % 33) - 1)")?; + } else if fun == Mf::FindMsb { + write!( + self.out, + "(((1 + int{}({}::clz(", + argument_size_suffix, NAMESPACE + )?; + self.put_expression(arg, context, true)?; + write!(self.out, "))) % 33) - 1)")?; } else if fun == Mf::Unpack2x16float { write!(self.out, "float2(as_type(")?; self.put_expression(arg, context, false)?; diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 5f01ca028..aba92b9b8 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -662,6 +662,12 @@ impl<'w> BlockContext<'w> { arg2_id, arg3_id, )), + Mf::FindLsb => MathOp::Ext(spirv::GLOp::FindILsb), + Mf::FindMsb => MathOp::Ext(match arg_scalar_kind { + Some(crate::ScalarKind::Uint) => spirv::GLOp::FindUMsb, + Some(crate::ScalarKind::Sint) => spirv::GLOp::FindSMsb, + other => unimplemented!("Unexpected findMSB({:?})", other), + }), Mf::Pack4x8unorm => MathOp::Ext(spirv::GLOp::PackUnorm4x8), Mf::Pack4x8snorm => MathOp::Ext(spirv::GLOp::PackSnorm4x8), Mf::Pack2x16float => MathOp::Ext(spirv::GLOp::PackHalf2x16), diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 6c226fe44..dbff2db3c 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1566,6 +1566,8 @@ impl Writer { Mf::ReverseBits => Function::Regular("reverseBits"), Mf::ExtractBits => Function::Regular("extractBits"), Mf::InsertBits => Function::Regular("insertBits"), + Mf::FindLsb => Function::Regular("findLsb"), + Mf::FindMsb => Function::Regular("findMsb"), // data packing Mf::Pack4x8snorm => Function::Regular("pack4x8snorm"), Mf::Pack4x8unorm => Function::Regular("pack4x8unorm"), diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index a7416ded2..1a114a57b 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -630,12 +630,15 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module )) } } - "bitCount" | "bitfieldReverse" | "bitfieldExtract" | "bitfieldInsert" => { + "bitCount" | "bitfieldReverse" | "bitfieldExtract" | "bitfieldInsert" | "findLSB" + | "findMSB" => { let fun = match name { "bitCount" => MathFunction::CountOneBits, "bitfieldReverse" => MathFunction::ReverseBits, "bitfieldExtract" => MathFunction::ExtractBits, "bitfieldInsert" => MathFunction::InsertBits, + "findLSB" => MathFunction::FindLsb, + "findMSB" => MathFunction::FindMsb, _ => unreachable!(), }; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index cfdf1fe88..dc578374b 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2637,6 +2637,8 @@ impl> Parser { Glo::UnpackHalf2x16 => Mf::Unpack2x16float, Glo::UnpackUnorm2x16 => Mf::Unpack2x16unorm, Glo::UnpackSnorm2x16 => Mf::Unpack2x16snorm, + Glo::FindILsb => Mf::FindLsb, + Glo::FindUMsb | Glo::FindSMsb => Mf::FindMsb, _ => return Err(Error::UnsupportedExtInst(inst_id)), }; diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 12d195ba6..b93869071 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -199,6 +199,8 @@ pub fn map_standard_fun(word: &str) -> Option { "reverseBits" => Mf::ReverseBits, "extractBits" => Mf::ExtractBits, "insertBits" => Mf::InsertBits, + "findLsb" => Mf::FindLsb, + "findMsb" => Mf::FindMsb, // data packing "pack4x8snorm" => Mf::Pack4x8snorm, "pack4x8unorm" => Mf::Pack4x8unorm, diff --git a/src/lib.rs b/src/lib.rs index 7be2b5377..349ae21f9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -926,6 +926,8 @@ pub enum MathFunction { ReverseBits, ExtractBits, InsertBits, + FindLsb, + FindMsb, // data packing Pack4x8snorm, Pack4x8unorm, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 8344f934c..04ae4a594 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -262,6 +262,8 @@ impl super::MathFunction { Self::ReverseBits => 1, Self::ExtractBits => 3, Self::InsertBits => 4, + Self::FindLsb => 1, + Self::FindMsb => 1, // data packing Self::Pack4x8snorm => 1, Self::Pack4x8unorm => 1, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index cf6035802..270276243 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -803,6 +803,16 @@ impl<'a> ResolveContext<'a> { Mf::ReverseBits | Mf::ExtractBits | Mf::InsertBits => res_arg.clone(), + Mf::FindLsb | + Mf::FindMsb => match *res_arg.inner_with(types) { + Ti::Scalar { kind: _, width } => + TypeResolution::Value(Ti::Scalar { kind: crate::ScalarKind::Sint, width }), + Ti::Vector { size, kind: _, width } => + TypeResolution::Value(Ti::Vector { size, kind: crate::ScalarKind::Sint, width }), + ref other => return Err(ResolveError::IncompatibleOperands( + format!("{:?}({:?})", fun, other) + )), + }, // data packing Mf::Pack4x8snorm | Mf::Pack4x8unorm | diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 26ec967b1..29409a1bc 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1231,7 +1231,7 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } } - Mf::CountOneBits | Mf::ReverseBits => { + Mf::CountOneBits | Mf::ReverseBits | Mf::FindLsb | Mf::FindMsb => { if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } diff --git a/tests/in/bits.wgsl b/tests/in/bits.wgsl index 1834411f3..4bec623aa 100644 --- a/tests/in/bits.wgsl +++ b/tests/in/bits.wgsl @@ -36,4 +36,8 @@ fn main() { u2 = extractBits(u2, 5u, 10u); u3 = extractBits(u3, 5u, 10u); u4 = extractBits(u4, 5u, 10u); + i = findLsb(i); + i2 = findLsb(u2); + i3 = findMsb(i3); + i = findMsb(u); } diff --git a/tests/in/glsl/bits_glsl.frag b/tests/in/glsl/bits_glsl.frag index cd960ed86..807ca3216 100644 --- a/tests/in/glsl/bits_glsl.frag +++ b/tests/in/glsl/bits_glsl.frag @@ -37,4 +37,20 @@ void main() { u2 = bitfieldExtract(u2, 5, 10); u3 = bitfieldExtract(u3, 5, 10); u4 = bitfieldExtract(u4, 5, 10); + i = findLSB(i); + i2 = findLSB(i2); + i3 = findLSB(i3); + i4 = findLSB(i4); + i = findLSB(u); + i2 = findLSB(u2); + i3 = findLSB(u3); + i4 = findLSB(u4); + i = findMSB(i); + i2 = findMSB(i2); + i3 = findMSB(i3); + i4 = findMSB(i4); + i = findMSB(u); + i2 = findMSB(u2); + i3 = findMSB(u3); + i4 = findMSB(u4); } \ No newline at end of file diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl index 303cdbc44..dd44101be 100644 --- a/tests/out/glsl/bits.main.Compute.glsl +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -85,6 +85,14 @@ void main() { u3_ = bitfieldExtract(_e112, int(5u), int(10u)); uvec4 _e116 = u4_; u4_ = bitfieldExtract(_e116, int(5u), int(10u)); + int _e120 = i; + i = findLSB(_e120); + uvec2 _e122 = u2_; + i2_ = findLSB(_e122); + ivec3 _e124 = i3_; + i3_ = findMSB(_e124); + uint _e126 = u; + i = findMSB(_e126); return; } diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index 3067ab416..b0c76ff82 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -83,5 +83,13 @@ kernel void main_( u3_ = metal::extract_bits(_e112, 5u, 10u); metal::uint4 _e116 = u4_; u4_ = metal::extract_bits(_e116, 5u, 10u); + int _e120 = i; + i = (((1 + int(metal::ctz(_e120))) % 33) - 1); + metal::uint2 _e122 = u2_; + i2_ = (((1 + int2(metal::ctz(_e122))) % 33) - 1); + metal::int3 _e124 = i3_; + i3_ = (((1 + int3(metal::clz(_e124))) % 33) - 1); + metal::uint _e126 = u; + i = (((1 + int(metal::clz(_e126))) % 33) - 1); return; } diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm index 3ef507eb4..b224d04ab 100644 --- a/tests/out/spv/bits.spvasm +++ b/tests/out/spv/bits.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 111 +; Bound: 119 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -151,5 +151,17 @@ OpStore %31 %108 %109 = OpLoad %16 %33 %110 = OpBitFieldUExtract %16 %109 %9 %10 OpStore %33 %110 +%111 = OpLoad %4 %19 +%112 = OpExtInst %4 %1 FindILsb %111 +OpStore %19 %112 +%113 = OpLoad %14 %29 +%114 = OpExtInst %11 %1 FindILsb %113 +OpStore %21 %114 +%115 = OpLoad %12 %23 +%116 = OpExtInst %12 %1 FindSMsb %115 +OpStore %23 %116 +%117 = OpLoad %6 %27 +%118 = OpExtInst %4 %1 FindUMsb %117 +OpStore %19 %118 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index 75eb3a5f3..45037118b 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -79,5 +79,13 @@ fn main() { u3_ = extractBits(_e112, 5u, 10u); let _e116 = u4_; u4_ = extractBits(_e116, 5u, 10u); + let _e120 = i; + i = findLsb(_e120); + let _e122 = u2_; + i2_ = findLsb(_e122); + let _e124 = i3_; + i3_ = findMsb(_e124); + let _e126 = u; + i = findMsb(_e126); return; } diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 504adf8d7..29f77ca76 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -70,6 +70,38 @@ fn main_1() { u3_ = extractBits(_e207, u32(5), u32(10)); let _e216 = u4_; u4_ = extractBits(_e216, u32(5), u32(10)); + let _e223 = i; + i = findLsb(_e223); + let _e226 = i2_; + i2_ = findLsb(_e226); + let _e229 = i3_; + i3_ = findLsb(_e229); + let _e232 = i4_; + i4_ = findLsb(_e232); + let _e235 = u; + i = findLsb(_e235); + let _e238 = u2_; + i2_ = findLsb(_e238); + let _e241 = u3_; + i3_ = findLsb(_e241); + let _e244 = u4_; + i4_ = findLsb(_e244); + let _e247 = i; + i = findMsb(_e247); + let _e250 = i2_; + i2_ = findMsb(_e250); + let _e253 = i3_; + i3_ = findMsb(_e253); + let _e256 = i4_; + i4_ = findMsb(_e256); + let _e259 = u; + i = findMsb(_e259); + let _e262 = u2_; + i2_ = findMsb(_e262); + let _e265 = u3_; + i3_ = findMsb(_e265); + let _e268 = u4_; + i4_ = findMsb(_e268); return; } From 54178dede2a8b3f6304e3c71081db31189f786ee Mon Sep 17 00:00:00 2001 From: Jakob Hellermann Date: Tue, 21 Dec 2021 21:14:10 +0100 Subject: [PATCH 1498/2212] impl Clone for WithSpan (#1620) --- src/span.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/span.rs b/src/span.rs index dabcabdb0..6d541210b 100644 --- a/src/span.rs +++ b/src/span.rs @@ -73,7 +73,7 @@ impl From> for Span { pub type SpanContext = (Span, String); /// Wrapper class for [`Error`], augmenting it with a list of [`SpanContext`]s. -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WithSpan { inner: E, #[cfg(feature = "span")] From 924ab17b623eae38690c5cc96227f86ff5676285 Mon Sep 17 00:00:00 2001 From: Jay Oster Date: Wed, 22 Dec 2021 06:41:07 -0800 Subject: [PATCH 1499/2212] Fixes for `fma` function (#1580) * [hlsl-out] Write `mad` intrinsic for `fma` function - This should be enough because we only support f32 for now. - Adds a new test for WGSL functions, in the spirit of operators.wgsl. - Closes #1579 * Add FMA feature to glsl backend - I think this is right. Just iterate all known expressions in all functions and entry points to locate any `fma` function call. Should not need to walk the statement DAG. * Transform GLSL fma function into an airthmetic expression when necessary * Add tests for GLSL fma function tranformation * Remove the hazard comment from the webgl test input * Add helper method for fma function support checks * Address review comment --- src/back/glsl/features.rs | 33 +++++++++++++++++-- src/back/glsl/mod.rs | 29 +++++++++++++++- src/back/hlsl/writer.rs | 2 +- tests/in/functions-webgl.param.ron | 7 ++++ tests/in/functions-webgl.wgsl | 13 ++++++++ tests/in/functions.param.ron | 2 ++ tests/in/functions.wgsl | 15 +++++++++ .../out/glsl/functions-webgl.main.Vertex.glsl | 18 ++++++++++ tests/out/glsl/functions.main.Compute.glsl | 21 ++++++++++++ tests/out/hlsl/functions.hlsl | 15 +++++++++ tests/out/hlsl/functions.hlsl.config | 3 ++ tests/out/msl/functions.msl | 18 ++++++++++ tests/out/spv/functions.spvasm | 33 +++++++++++++++++++ tests/out/wgsl/functions.wgsl | 12 +++++++ tests/snapshots.rs | 5 +++ 15 files changed, 222 insertions(+), 4 deletions(-) create mode 100644 tests/in/functions-webgl.param.ron create mode 100644 tests/in/functions-webgl.wgsl create mode 100644 tests/in/functions.param.ron create mode 100644 tests/in/functions.wgsl create mode 100644 tests/out/glsl/functions-webgl.main.Vertex.glsl create mode 100644 tests/out/glsl/functions.main.Compute.glsl create mode 100644 tests/out/hlsl/functions.hlsl create mode 100644 tests/out/hlsl/functions.hlsl.config create mode 100644 tests/out/msl/functions.msl create mode 100644 tests/out/spv/functions.spvasm create mode 100644 tests/out/wgsl/functions.wgsl diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 74db74c70..0d7855899 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -1,7 +1,7 @@ use super::{BackendResult, Error, Version, Writer}; use crate::{ - Binding, Bytes, Handle, ImageClass, ImageDimension, Interpolation, Sampling, ScalarKind, - ShaderStage, StorageClass, StorageFormat, Type, TypeInner, + Binding, Bytes, Expression, Handle, ImageClass, ImageDimension, Interpolation, MathFunction, + Sampling, ScalarKind, ShaderStage, StorageClass, StorageFormat, Type, TypeInner, }; use std::fmt::Write; @@ -33,6 +33,8 @@ bitflags::bitflags! { /// Arrays with a dynamic length const DYNAMIC_ARRAY_SIZE = 1 << 16; const MULTI_VIEW = 1 << 17; + /// Adds support for fused multiply-add + const FMA = 1 << 18; } } @@ -98,6 +100,7 @@ impl FeaturesManager { check_feature!(SAMPLE_VARIABLES, 400, 300); check_feature!(DYNAMIC_ARRAY_SIZE, 430, 310); check_feature!(MULTI_VIEW, 140, 310); + check_feature!(FMA, 400, 310); // Return an error if there are missing features if missing.is_empty() { @@ -201,6 +204,11 @@ impl FeaturesManager { writeln!(out, "#extension GL_EXT_multiview : require")?; } + if self.0.contains(Features::FMA) && version.is_es() { + // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_gpu_shader5.txt + writeln!(out, "#extension GL_EXT_gpu_shader5 : require")?; + } + Ok(()) } } @@ -347,6 +355,27 @@ impl<'a, W> Writer<'a, W> { } } + if self.options.version.supports_fma_function() { + let has_fma = self + .module + .functions + .iter() + .flat_map(|(_, f)| f.expressions.iter()) + .chain( + self.module + .entry_points + .iter() + .flat_map(|e| e.function.expressions.iter()), + ) + .any(|(_, e)| match *e { + Expression::Math { fun, .. } if fun == MathFunction::Fma => true, + _ => false, + }); + if has_fma { + self.features.request(Features::FMA); + } + } + self.features.check_availability(self.options.version) } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 34a22b524..014cc34b4 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -160,6 +160,10 @@ impl Version { fn supports_std430_layout(&self) -> bool { *self >= Version::Desktop(430) || *self >= Version::Embedded(310) } + + fn supports_fma_function(&self) -> bool { + *self >= Version::Desktop(400) || *self >= Version::Embedded(310) + } } impl PartialOrd for Version { @@ -2471,7 +2475,30 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Refract => "refract", // computational Mf::Sign => "sign", - Mf::Fma => "fma", + Mf::Fma => { + if self.options.version.supports_fma_function() { + // Use the fma function when available + "fma" + } else { + // No fma support. Transform the function call into an arithmetic expression + write!(self.out, "(")?; + + self.write_expr(arg, ctx)?; + write!(self.out, " * ")?; + + let arg1 = + arg1.ok_or_else(|| Error::Custom("Missing fma arg1".to_owned()))?; + self.write_expr(arg1, ctx)?; + write!(self.out, " + ")?; + + let arg2 = + arg2.ok_or_else(|| Error::Custom("Missing fma arg2".to_owned()))?; + self.write_expr(arg2, ctx)?; + write!(self.out, ")")?; + + return Ok(()); + } + } Mf::Mix => "mix", Mf::Step => "step", Mf::SmoothStep => "smoothstep", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 2f7b4e7ad..0280b5058 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1862,7 +1862,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::Refract => Function::Regular("refract"), // computational Mf::Sign => Function::Regular("sign"), - Mf::Fma => Function::Regular("fma"), + Mf::Fma => Function::Regular("mad"), Mf::Mix => Function::Regular("lerp"), Mf::Step => Function::Regular("step"), Mf::SmoothStep => Function::Regular("smoothstep"), diff --git a/tests/in/functions-webgl.param.ron b/tests/in/functions-webgl.param.ron new file mode 100644 index 000000000..bc3dd4a8d --- /dev/null +++ b/tests/in/functions-webgl.param.ron @@ -0,0 +1,7 @@ +( + glsl: ( + version: Embedded(300), + writer_flags: (bits: 0), + binding_map: {}, + ), +) diff --git a/tests/in/functions-webgl.wgsl b/tests/in/functions-webgl.wgsl new file mode 100644 index 000000000..2ec56f88f --- /dev/null +++ b/tests/in/functions-webgl.wgsl @@ -0,0 +1,13 @@ +fn test_fma() -> vec2 { + let a = vec2(2.0, 2.0); + let b = vec2(0.5, 0.5); + let c = vec2(0.5, 0.5); + + return fma(a, b, c); +} + + +[[stage(vertex)]] +fn main() { + let a = test_fma(); +} diff --git a/tests/in/functions.param.ron b/tests/in/functions.param.ron new file mode 100644 index 000000000..72873dd66 --- /dev/null +++ b/tests/in/functions.param.ron @@ -0,0 +1,2 @@ +( +) diff --git a/tests/in/functions.wgsl b/tests/in/functions.wgsl new file mode 100644 index 000000000..e9d64a99f --- /dev/null +++ b/tests/in/functions.wgsl @@ -0,0 +1,15 @@ +fn test_fma() -> vec2 { + let a = vec2(2.0, 2.0); + let b = vec2(0.5, 0.5); + let c = vec2(0.5, 0.5); + + // Hazard: HLSL needs a different intrinsic function for f32 and f64 + // See: https://github.com/gfx-rs/naga/issues/1579 + return fma(a, b, c); +} + + +[[stage(compute), workgroup_size(1)]] +fn main() { + let a = test_fma(); +} diff --git a/tests/out/glsl/functions-webgl.main.Vertex.glsl b/tests/out/glsl/functions-webgl.main.Vertex.glsl new file mode 100644 index 000000000..3522f1a65 --- /dev/null +++ b/tests/out/glsl/functions-webgl.main.Vertex.glsl @@ -0,0 +1,18 @@ +#version 300 es + +precision highp float; +precision highp int; + + +vec2 test_fma() { + vec2 a = vec2(2.0, 2.0); + vec2 b = vec2(0.5, 0.5); + vec2 c = vec2(0.5, 0.5); + return (a * b + c); +} + +void main() { + vec2 _e0 = test_fma(); + return; +} + diff --git a/tests/out/glsl/functions.main.Compute.glsl b/tests/out/glsl/functions.main.Compute.glsl new file mode 100644 index 000000000..d3e7f7d17 --- /dev/null +++ b/tests/out/glsl/functions.main.Compute.glsl @@ -0,0 +1,21 @@ +#version 310 es +#extension GL_EXT_gpu_shader5 : require + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + + +vec2 test_fma() { + vec2 a = vec2(2.0, 2.0); + vec2 b = vec2(0.5, 0.5); + vec2 c = vec2(0.5, 0.5); + return fma(a, b, c); +} + +void main() { + vec2 _e0 = test_fma(); + return; +} + diff --git a/tests/out/hlsl/functions.hlsl b/tests/out/hlsl/functions.hlsl new file mode 100644 index 000000000..37a4ecfaf --- /dev/null +++ b/tests/out/hlsl/functions.hlsl @@ -0,0 +1,15 @@ + +float2 test_fma() +{ + float2 a = float2(2.0, 2.0); + float2 b = float2(0.5, 0.5); + float2 c = float2(0.5, 0.5); + return mad(a, b, c); +} + +[numthreads(1, 1, 1)] +void main() +{ + const float2 _e0 = test_fma(); + return; +} diff --git a/tests/out/hlsl/functions.hlsl.config b/tests/out/hlsl/functions.hlsl.config new file mode 100644 index 000000000..246c485cf --- /dev/null +++ b/tests/out/hlsl/functions.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(main:cs_5_1 ) diff --git a/tests/out/msl/functions.msl b/tests/out/msl/functions.msl new file mode 100644 index 000000000..6ace92f74 --- /dev/null +++ b/tests/out/msl/functions.msl @@ -0,0 +1,18 @@ +// language: metal1.1 +#include +#include + + +metal::float2 test_fma( +) { + metal::float2 a = metal::float2(2.0, 2.0); + metal::float2 b = metal::float2(0.5, 0.5); + metal::float2 c = metal::float2(0.5, 0.5); + return metal::fma(a, b, c); +} + +kernel void main_( +) { + metal::float2 _e0 = test_fma(); + return; +} diff --git a/tests/out/spv/functions.spvasm b/tests/out/spv/functions.spvasm new file mode 100644 index 000000000..9c1a62ae4 --- /dev/null +++ b/tests/out/spv/functions.spvasm @@ -0,0 +1,33 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 20 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %16 "main" +OpExecutionMode %16 LocalSize 1 1 1 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 2.0 +%5 = OpConstant %4 0.5 +%6 = OpTypeVector %4 2 +%9 = OpTypeFunction %6 +%17 = OpTypeFunction %2 +%8 = OpFunction %6 None %9 +%7 = OpLabel +OpBranch %10 +%10 = OpLabel +%11 = OpCompositeConstruct %6 %3 %3 +%12 = OpCompositeConstruct %6 %5 %5 +%13 = OpCompositeConstruct %6 %5 %5 +%14 = OpExtInst %6 %1 Fma %11 %12 %13 +OpReturnValue %14 +OpFunctionEnd +%16 = OpFunction %2 None %17 +%15 = OpLabel +OpBranch %18 +%18 = OpLabel +%19 = OpFunctionCall %6 %8 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/functions.wgsl b/tests/out/wgsl/functions.wgsl new file mode 100644 index 000000000..9b6b41a09 --- /dev/null +++ b/tests/out/wgsl/functions.wgsl @@ -0,0 +1,12 @@ +fn test_fma() -> vec2 { + let a = vec2(2.0, 2.0); + let b = vec2(0.5, 0.5); + let c = vec2(0.5, 0.5); + return fma(a, b, c); +} + +[[stage(compute), workgroup_size(1, 1, 1)]] +fn main() { + let _e0 = test_fma(); + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 26d046445..57179c5d5 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -443,6 +443,11 @@ fn convert_wgsl() { "operators", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ( + "functions", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + ), + ("functions-webgl", Targets::GLSL), ( "interpolate", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From 8df5421e2e9d33e092c19779adfdc42e7f8a74e6 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 24 Dec 2021 06:19:07 +0300 Subject: [PATCH 1500/2212] [glsl-out] Add stage postfix to generated global name (#1616) --- .gitignore | 1 + src/back/glsl/mod.rs | 25 ++++++++++++-- tests/out/glsl/access.atomics.Compute.glsl | 22 ++++++------ tests/out/glsl/access.foo.Vertex.glsl | 18 +++++----- tests/out/glsl/boids.main.Compute.glsl | 32 ++++++++--------- .../cubeArrayShadow.fragment.Fragment.glsl | 4 +-- tests/out/glsl/image.gather.Fragment.glsl | 12 +++---- tests/out/glsl/image.main.Compute.glsl | 22 ++++++------ tests/out/glsl/image.queries.Vertex.glsl | 34 +++++++++---------- tests/out/glsl/image.sample.Fragment.glsl | 14 ++++---- .../image.sample_comparison.Fragment.glsl | 6 ++-- tests/out/glsl/quad.frag_main.Fragment.glsl | 4 +-- tests/out/glsl/shadow.fs_main.Fragment.glsl | 12 +++---- tests/out/glsl/skybox.fs_main.Fragment.glsl | 4 +-- tests/out/glsl/skybox.vs_main.Vertex.glsl | 10 +++--- tests/out/glsl/texture-arg.main.Fragment.glsl | 4 +-- 16 files changed, 123 insertions(+), 101 deletions(-) diff --git a/.gitignore b/.gitignore index 40440d9b5..bb84f2e16 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ Cargo.lock /*.vert /*.frag /*.comp +/*.wgsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 014cc34b4..91e1c5762 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -305,6 +305,16 @@ impl fmt::Display for VaryingName<'_> { } } +impl ShaderStage { + fn to_str(self) -> &'static str { + match self { + ShaderStage::Compute => "cs", + ShaderStage::Fragment => "fs", + ShaderStage::Vertex => "vs", + } + } +} + /// Shorthand result used internally by the backend type BackendResult = Result; @@ -961,7 +971,12 @@ impl<'a, W: Write> Writer<'a, W> { ) -> String { match global.binding { Some(ref br) => { - format!("_group_{}_binding_{}", br.group, br.binding) + format!( + "_group_{}_binding_{}_{}", + br.group, + br.binding, + self.entry_point.stage.to_str() + ) } None => self.names[&NameKey::GlobalVariable(handle)].clone(), } @@ -974,7 +989,13 @@ impl<'a, W: Write> Writer<'a, W> { global: &crate::GlobalVariable, ) -> BackendResult { match global.binding { - Some(ref br) => write!(self.out, "_group_{}_binding_{}", br.group, br.binding)?, + Some(ref br) => write!( + self.out, + "_group_{}_binding_{}_{}", + br.group, + br.binding, + self.entry_point.stage.to_str() + )?, None => write!( self.out, "{}", diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 19414a449..fbc36cfce 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -10,7 +10,7 @@ layout(std430) buffer Bar_block_0Compute { int atom; uvec2 arr[2]; int data[]; -} _group_0_binding_0; +} _group_0_binding_0_cs; float read_from_private(inout float foo_2) { @@ -20,24 +20,24 @@ float read_from_private(inout float foo_2) { void main() { int tmp = 0; - int value = _group_0_binding_0.atom; - int _e6 = atomicAdd(_group_0_binding_0.atom, 5); + int value = _group_0_binding_0_cs.atom; + int _e6 = atomicAdd(_group_0_binding_0_cs.atom, 5); tmp = _e6; - int _e9 = atomicAdd(_group_0_binding_0.atom, -5); + int _e9 = atomicAdd(_group_0_binding_0_cs.atom, -5); tmp = _e9; - int _e12 = atomicAnd(_group_0_binding_0.atom, 5); + int _e12 = atomicAnd(_group_0_binding_0_cs.atom, 5); tmp = _e12; - int _e15 = atomicOr(_group_0_binding_0.atom, 5); + int _e15 = atomicOr(_group_0_binding_0_cs.atom, 5); tmp = _e15; - int _e18 = atomicXor(_group_0_binding_0.atom, 5); + int _e18 = atomicXor(_group_0_binding_0_cs.atom, 5); tmp = _e18; - int _e21 = atomicMin(_group_0_binding_0.atom, 5); + int _e21 = atomicMin(_group_0_binding_0_cs.atom, 5); tmp = _e21; - int _e24 = atomicMax(_group_0_binding_0.atom, 5); + int _e24 = atomicMax(_group_0_binding_0_cs.atom, 5); tmp = _e24; - int _e27 = atomicExchange(_group_0_binding_0.atom, 5); + int _e27 = atomicExchange(_group_0_binding_0_cs.atom, 5); tmp = _e27; - _group_0_binding_0.atom = value; + _group_0_binding_0_cs.atom = value; return; } diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index dfdf2c013..2f080d9f0 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -8,7 +8,7 @@ layout(std430) buffer Bar_block_0Vertex { int atom; uvec2 arr[2]; int data[]; -} _group_0_binding_0; +} _group_0_binding_0_vs; float read_from_private(inout float foo_2) { @@ -22,15 +22,15 @@ void main() { int c[5]; float baz = foo_1; foo_1 = 1.0; - mat4x4 matrix = _group_0_binding_0.matrix; - uvec2 arr[2] = _group_0_binding_0.arr; - float b = _group_0_binding_0.matrix[3][0]; - int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)]; + mat4x4 matrix = _group_0_binding_0_vs.matrix; + uvec2 arr[2] = _group_0_binding_0_vs.arr; + float b = _group_0_binding_0_vs.matrix[3][0]; + int a = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)]; float _e25 = read_from_private(foo_1); - _group_0_binding_0.matrix[1][2] = 1.0; - _group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); - _group_0_binding_0.arr = uvec2[2](uvec2(0u), uvec2(1u)); - _group_0_binding_0.data[1] = 1; + _group_0_binding_0_vs.matrix[1][2] = 1.0; + _group_0_binding_0_vs.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + _group_0_binding_0_vs.arr = uvec2[2](uvec2(0u), uvec2(1u)); + _group_0_binding_0_vs.data[1] = 1; c = int[5](a, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index e68cdc27e..5ebd69f5f 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -18,15 +18,15 @@ struct SimParams { float rule2Scale; float rule3Scale; }; -uniform SimParams_block_0Compute { SimParams _group_0_binding_0; }; +uniform SimParams_block_0Compute { SimParams _group_0_binding_0_cs; }; layout(std430) readonly buffer Particles_block_1Compute { Particle particles[]; -} _group_0_binding_1; +} _group_0_binding_1_cs; layout(std430) buffer Particles_block_2Compute { Particle particles[]; -} _group_0_binding_2; +} _group_0_binding_2_cs; void main() { @@ -45,9 +45,9 @@ void main() { if ((index >= 1500u)) { return; } - vec2 _e10 = _group_0_binding_1.particles[index].pos; + vec2 _e10 = _group_0_binding_1_cs.particles[index].pos; vPos = _e10; - vec2 _e15 = _group_0_binding_1.particles[index].vel; + vec2 _e15 = _group_0_binding_1_cs.particles[index].vel; vVel = _e15; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); @@ -68,14 +68,14 @@ void main() { continue; } uint _e42 = i; - vec2 _e45 = _group_0_binding_1.particles[_e42].pos; + vec2 _e45 = _group_0_binding_1_cs.particles[_e42].pos; pos = _e45; uint _e47 = i; - vec2 _e50 = _group_0_binding_1.particles[_e47].vel; + vec2 _e50 = _group_0_binding_1_cs.particles[_e47].vel; vel = _e50; vec2 _e51 = pos; vec2 _e52 = vPos; - float _e55 = _group_0_binding_0.rule1Distance; + float _e55 = _group_0_binding_0_cs.rule1Distance; if ((distance(_e51, _e52) < _e55)) { vec2 _e57 = cMass; vec2 _e58 = pos; @@ -85,7 +85,7 @@ void main() { } vec2 _e63 = pos; vec2 _e64 = vPos; - float _e67 = _group_0_binding_0.rule2Distance; + float _e67 = _group_0_binding_0_cs.rule2Distance; if ((distance(_e63, _e64) < _e67)) { vec2 _e69 = colVel; vec2 _e70 = pos; @@ -94,7 +94,7 @@ void main() { } vec2 _e74 = pos; vec2 _e75 = vPos; - float _e78 = _group_0_binding_0.rule3Distance; + float _e78 = _group_0_binding_0_cs.rule3Distance; if ((distance(_e74, _e75) < _e78)) { vec2 _e80 = cVel; vec2 _e81 = vel; @@ -118,18 +118,18 @@ void main() { } vec2 _e107 = vVel; vec2 _e108 = cMass; - float _e110 = _group_0_binding_0.rule1Scale; + float _e110 = _group_0_binding_0_cs.rule1Scale; vec2 _e113 = colVel; - float _e115 = _group_0_binding_0.rule2Scale; + float _e115 = _group_0_binding_0_cs.rule2Scale; vec2 _e118 = cVel; - float _e120 = _group_0_binding_0.rule3Scale; + float _e120 = _group_0_binding_0_cs.rule3Scale; vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); vec2 _e123 = vVel; vec2 _e125 = vVel; vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.10000000149011612)); vec2 _e131 = vPos; vec2 _e132 = vVel; - float _e134 = _group_0_binding_0.deltaT; + float _e134 = _group_0_binding_0_cs.deltaT; vPos = (_e131 + (_e132 * _e134)); float _e138 = vPos.x; if ((_e138 < -1.0)) { @@ -148,9 +148,9 @@ void main() { vPos.y = -1.0; } vec2 _e164 = vPos; - _group_0_binding_2.particles[index].pos = _e164; + _group_0_binding_2_cs.particles[index].pos = _e164; vec2 _e168 = vVel; - _group_0_binding_2.particles[index].vel = _e168; + _group_0_binding_2_cs.particles[index].vel = _e168; return; } diff --git a/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl b/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl index 57f819281..ac9bc6de4 100644 --- a/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl +++ b/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl @@ -4,13 +4,13 @@ precision highp float; precision highp int; -uniform highp samplerCubeArrayShadow _group_0_binding_4; +uniform highp samplerCubeArrayShadow _group_0_binding_4_fs; layout(location = 0) out vec4 _fs2p_location0; void main() { vec3 frag_ls = vec4(1.0, 1.0, 2.0, 1.0).xyz; - float a = texture(_group_0_binding_4, vec4(frag_ls, int(1)), 1.0); + float a = texture(_group_0_binding_4_fs, vec4(frag_ls, int(1)), 1.0); _fs2p_location0 = vec4(a, 1.0, 1.0, 1.0); return; } diff --git a/tests/out/glsl/image.gather.Fragment.glsl b/tests/out/glsl/image.gather.Fragment.glsl index 89961fcff..5a44544a2 100644 --- a/tests/out/glsl/image.gather.Fragment.glsl +++ b/tests/out/glsl/image.gather.Fragment.glsl @@ -4,18 +4,18 @@ precision highp float; precision highp int; -uniform highp sampler2D _group_0_binding_1; +uniform highp sampler2D _group_0_binding_1_fs; -uniform highp sampler2DShadow _group_1_binding_2; +uniform highp sampler2DShadow _group_1_binding_2_fs; layout(location = 0) out vec4 _fs2p_location0; void main() { vec2 tc = vec2(0.5); - vec4 s2d = textureGather(_group_0_binding_1, vec2(tc), 1); - vec4 s2d_offset = textureGatherOffset(_group_0_binding_1, vec2(tc), ivec2(3, 1), 3); - vec4 s2d_depth = textureGather(_group_1_binding_2, vec2(tc), 0.5); - vec4 s2d_depth_offset = textureGatherOffset(_group_1_binding_2, vec2(tc), 0.5, ivec2(3, 1)); + vec4 s2d = textureGather(_group_0_binding_1_fs, vec2(tc), 1); + vec4 s2d_offset = textureGatherOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 3); + vec4 s2d_depth = textureGather(_group_1_binding_2_fs, vec2(tc), 0.5); + vec4 s2d_depth_offset = textureGatherOffset(_group_1_binding_2_fs, vec2(tc), 0.5, ivec2(3, 1)); _fs2p_location0 = (((s2d + s2d_offset) + s2d_depth) + s2d_depth_offset); return; } diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl index be6b7ed97..3258e65aa 100644 --- a/tests/out/glsl/image.main.Compute.glsl +++ b/tests/out/glsl/image.main.Compute.glsl @@ -6,26 +6,26 @@ precision highp int; layout(local_size_x = 16, local_size_y = 1, local_size_z = 1) in; -uniform highp usampler2D _group_0_binding_0; +uniform highp usampler2D _group_0_binding_0_cs; -uniform highp usampler2DMS _group_0_binding_3; +uniform highp usampler2DMS _group_0_binding_3_cs; -layout(rgba8ui) readonly uniform highp uimage2D _group_0_binding_1; +layout(rgba8ui) readonly uniform highp uimage2D _group_0_binding_1_cs; -uniform highp usampler2DArray _group_0_binding_5; +uniform highp usampler2DArray _group_0_binding_5_cs; -layout(r32ui) writeonly uniform highp uimage2D _group_0_binding_2; +layout(r32ui) writeonly uniform highp uimage2D _group_0_binding_2_cs; void main() { uvec3 local_id = gl_LocalInvocationID; - ivec2 dim = imageSize(_group_0_binding_1).xy; + ivec2 dim = imageSize(_group_0_binding_1_cs).xy; ivec2 itc = ((dim * ivec2(local_id.xy)) % ivec2(10, 20)); - uvec4 value1_ = texelFetch(_group_0_binding_0, itc, int(local_id.z)); - uvec4 value2_ = texelFetch(_group_0_binding_3, itc, int(local_id.z)); - uvec4 value4_ = imageLoad(_group_0_binding_1, itc); - uvec4 value5_ = texelFetch(_group_0_binding_5, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); - imageStore(_group_0_binding_2, ivec2(itc.x, 0.0), (((value1_ + value2_) + value4_) + value5_)); + uvec4 value1_ = texelFetch(_group_0_binding_0_cs, itc, int(local_id.z)); + uvec4 value2_ = texelFetch(_group_0_binding_3_cs, itc, int(local_id.z)); + uvec4 value4_ = imageLoad(_group_0_binding_1_cs, itc); + uvec4 value5_ = texelFetch(_group_0_binding_5_cs, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); + imageStore(_group_0_binding_2_cs, ivec2(itc.x, 0.0), (((value1_ + value2_) + value4_) + value5_)); return; } diff --git a/tests/out/glsl/image.queries.Vertex.glsl b/tests/out/glsl/image.queries.Vertex.glsl index 8f89d2dad..e5ff9492a 100644 --- a/tests/out/glsl/image.queries.Vertex.glsl +++ b/tests/out/glsl/image.queries.Vertex.glsl @@ -4,31 +4,31 @@ precision highp float; precision highp int; -uniform highp sampler2D _group_0_binding_0; +uniform highp sampler2D _group_0_binding_0_vs; -uniform highp sampler2D _group_0_binding_1; +uniform highp sampler2D _group_0_binding_1_vs; -uniform highp sampler2DArray _group_0_binding_2; +uniform highp sampler2DArray _group_0_binding_2_vs; -uniform highp samplerCube _group_0_binding_3; +uniform highp samplerCube _group_0_binding_3_vs; -uniform highp samplerCubeArray _group_0_binding_4; +uniform highp samplerCubeArray _group_0_binding_4_vs; -uniform highp sampler3D _group_0_binding_5; +uniform highp sampler3D _group_0_binding_5_vs; void main() { - int dim_1d = textureSize(_group_0_binding_0, 0).x; - ivec2 dim_2d = textureSize(_group_0_binding_1, 0).xy; - ivec2 dim_2d_lod = textureSize(_group_0_binding_1, 1).xy; - ivec2 dim_2d_array = textureSize(_group_0_binding_2, 0).xy; - ivec2 dim_2d_array_lod = textureSize(_group_0_binding_2, 1).xy; - ivec2 dim_cube = textureSize(_group_0_binding_3, 0).xy; - ivec2 dim_cube_lod = textureSize(_group_0_binding_3, 1).xy; - ivec2 dim_cube_array = textureSize(_group_0_binding_4, 0).xy; - ivec2 dim_cube_array_lod = textureSize(_group_0_binding_4, 1).xy; - ivec3 dim_3d = textureSize(_group_0_binding_5, 0).xyz; - ivec3 dim_3d_lod = textureSize(_group_0_binding_5, 1).xyz; + int dim_1d = textureSize(_group_0_binding_0_vs, 0).x; + ivec2 dim_2d = textureSize(_group_0_binding_1_vs, 0).xy; + ivec2 dim_2d_lod = textureSize(_group_0_binding_1_vs, 1).xy; + ivec2 dim_2d_array = textureSize(_group_0_binding_2_vs, 0).xy; + ivec2 dim_2d_array_lod = textureSize(_group_0_binding_2_vs, 1).xy; + ivec2 dim_cube = textureSize(_group_0_binding_3_vs, 0).xy; + ivec2 dim_cube_lod = textureSize(_group_0_binding_3_vs, 1).xy; + ivec2 dim_cube_array = textureSize(_group_0_binding_4_vs, 0).xy; + ivec2 dim_cube_array_lod = textureSize(_group_0_binding_4_vs, 1).xy; + ivec3 dim_3d = textureSize(_group_0_binding_5_vs, 0).xyz; + ivec3 dim_3d_lod = textureSize(_group_0_binding_5_vs, 1).xyz; int sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); gl_Position = vec4(float(sum)); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/glsl/image.sample.Fragment.glsl b/tests/out/glsl/image.sample.Fragment.glsl index a0d7946d0..288e23350 100644 --- a/tests/out/glsl/image.sample.Fragment.glsl +++ b/tests/out/glsl/image.sample.Fragment.glsl @@ -4,19 +4,19 @@ precision highp float; precision highp int; -uniform highp sampler2D _group_0_binding_0; +uniform highp sampler2D _group_0_binding_0_fs; -uniform highp sampler2D _group_0_binding_1; +uniform highp sampler2D _group_0_binding_1_fs; layout(location = 0) out vec4 _fs2p_location0; void main() { vec2 tc = vec2(0.5); - vec4 s1d = texture(_group_0_binding_0, vec2(tc.x, 0.0)); - vec4 s2d = texture(_group_0_binding_1, vec2(tc)); - vec4 s2d_offset = textureOffset(_group_0_binding_1, vec2(tc), ivec2(3, 1)); - vec4 s2d_level = textureLod(_group_0_binding_1, vec2(tc), 2.299999952316284); - vec4 s2d_level_offset = textureLodOffset(_group_0_binding_1, vec2(tc), 2.299999952316284, ivec2(3, 1)); + vec4 s1d = texture(_group_0_binding_0_fs, vec2(tc.x, 0.0)); + vec4 s2d = texture(_group_0_binding_1_fs, vec2(tc)); + vec4 s2d_offset = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1)); + vec4 s2d_level = textureLod(_group_0_binding_1_fs, vec2(tc), 2.299999952316284); + vec4 s2d_level_offset = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.299999952316284, ivec2(3, 1)); _fs2p_location0 = ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); return; } diff --git a/tests/out/glsl/image.sample_comparison.Fragment.glsl b/tests/out/glsl/image.sample_comparison.Fragment.glsl index 4b52baac2..a1994e3a0 100644 --- a/tests/out/glsl/image.sample_comparison.Fragment.glsl +++ b/tests/out/glsl/image.sample_comparison.Fragment.glsl @@ -4,14 +4,14 @@ precision highp float; precision highp int; -uniform highp sampler2DShadow _group_1_binding_2; +uniform highp sampler2DShadow _group_1_binding_2_fs; layout(location = 0) out float _fs2p_location0; void main() { vec2 tc = vec2(0.5); - float s2d_depth = texture(_group_1_binding_2, vec3(tc, 0.5)); - float s2d_depth_level = textureLod(_group_1_binding_2, vec3(tc, 0.5), 0.0); + float s2d_depth = texture(_group_1_binding_2_fs, vec3(tc, 0.5)); + float s2d_depth_level = textureLod(_group_1_binding_2_fs, vec3(tc, 0.5), 0.0); _fs2p_location0 = (s2d_depth + s2d_depth_level); return; } diff --git a/tests/out/glsl/quad.frag_main.Fragment.glsl b/tests/out/glsl/quad.frag_main.Fragment.glsl index 637f890f7..e1902d9e3 100644 --- a/tests/out/glsl/quad.frag_main.Fragment.glsl +++ b/tests/out/glsl/quad.frag_main.Fragment.glsl @@ -7,14 +7,14 @@ struct VertexOutput { vec2 uv; vec4 position; }; -uniform highp sampler2D _group_0_binding_0; +uniform highp sampler2D _group_0_binding_0_fs; smooth in vec2 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { vec2 uv_1 = _vs2fs_location0; - vec4 color = texture(_group_0_binding_0, vec2(uv_1)); + vec4 color = texture(_group_0_binding_0_fs, vec2(uv_1)); if ((color.w == 0.0)) { discard; } diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 594b250ea..3d26dbfdb 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -11,13 +11,13 @@ struct Light { vec4 pos; vec4 color; }; -uniform Globals_block_0Fragment { Globals _group_0_binding_0; }; +uniform Globals_block_0Fragment { Globals _group_0_binding_0_fs; }; layout(std430) readonly buffer Lights_block_1Fragment { Light data[]; -} _group_0_binding_1; +} _group_0_binding_1_fs; -uniform highp sampler2DArrayShadow _group_0_binding_2; +uniform highp sampler2DArrayShadow _group_0_binding_2_fs; layout(location = 0) smooth in vec3 _vs2fs_location0; layout(location = 1) smooth in vec4 _vs2fs_location1; @@ -29,7 +29,7 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } vec2 flip_correction = vec2(0.5, -0.5); vec2 light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - float _e26 = textureGrad(_group_0_binding_2, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); + float _e26 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); return _e26; } @@ -47,12 +47,12 @@ void main() { } loop_init = false; uint _e12 = i; - uint _e15 = _group_0_binding_0.num_lights.x; + uint _e15 = _group_0_binding_0_fs.num_lights.x; if ((_e12 >= min(_e15, 10u))) { break; } uint _e19 = i; - Light light = _group_0_binding_1.data[_e19]; + Light light = _group_0_binding_1_fs.data[_e19]; uint _e22 = i; float _e25 = fetch_shadow(_e22, (light.proj * position)); vec3 light_dir = normalize((light.pos.xyz - position.xyz)); diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index 916ea2c8a..2b151db2a 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -11,14 +11,14 @@ struct Data { mat4x4 proj_inv; mat4x4 view; }; -layout(binding = 0) uniform highp samplerCube _group_0_binding_1; +layout(binding = 0) uniform highp samplerCube _group_0_binding_1_fs; layout(location = 0) smooth in vec3 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0); - vec4 _e5 = texture(_group_0_binding_1, vec3(in_.uv)); + vec4 _e5 = texture(_group_0_binding_1_fs, vec3(in_.uv)); _fs2p_location0 = _e5; return; } diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index f7490130a..115245a71 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -11,7 +11,7 @@ struct Data { mat4x4 proj_inv; mat4x4 view; }; -layout(std140, binding = 0) uniform Data_block_0Vertex { Data _group_0_binding_0; }; +layout(std140, binding = 0) uniform Data_block_0Vertex { Data _group_0_binding_0_vs; }; layout(location = 0) smooth out vec3 _vs2fs_location0; @@ -24,11 +24,11 @@ void main() { int _e10 = tmp1_; int _e16 = tmp2_; vec4 pos = vec4(((float(_e10) * 4.0) - 1.0), ((float(_e16) * 4.0) - 1.0), 0.0, 1.0); - vec4 _e27 = _group_0_binding_0.view[0]; - vec4 _e31 = _group_0_binding_0.view[1]; - vec4 _e35 = _group_0_binding_0.view[2]; + vec4 _e27 = _group_0_binding_0_vs.view[0]; + vec4 _e31 = _group_0_binding_0_vs.view[1]; + vec4 _e35 = _group_0_binding_0_vs.view[2]; mat3x3 inv_model_view = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); - mat4x4 _e40 = _group_0_binding_0.proj_inv; + mat4x4 _e40 = _group_0_binding_0_vs.proj_inv; vec4 unprojected = (_e40 * pos); VertexOutput _tmp_return = VertexOutput(pos, (inv_model_view * unprojected.xyz)); gl_Position = _tmp_return.position; diff --git a/tests/out/glsl/texture-arg.main.Fragment.glsl b/tests/out/glsl/texture-arg.main.Fragment.glsl index 3d46d1cd8..1ff2a9022 100644 --- a/tests/out/glsl/texture-arg.main.Fragment.glsl +++ b/tests/out/glsl/texture-arg.main.Fragment.glsl @@ -3,7 +3,7 @@ precision highp float; precision highp int; -uniform highp sampler2D _group_0_binding_0; +uniform highp sampler2D _group_0_binding_0_fs; layout(location = 0) out vec4 _fs2p_location0; @@ -13,7 +13,7 @@ vec4 test(highp sampler2D Passed_Texture) { } void main() { - vec4 _e2 = test(_group_0_binding_0); + vec4 _e2 = test(_group_0_binding_0_fs); _fs2p_location0 = _e2; return; } From 0d1fc2131fe11480d7cac63c90db0e3adc328995 Mon Sep 17 00:00:00 2001 From: Luke Street Date: Sun, 26 Dec 2021 19:29:33 -0500 Subject: [PATCH 1501/2212] [wgsl-in] Support radians/degrees builtin functions (#1627) --- src/back/glsl/mod.rs | 2 + src/back/hlsl/writer.rs | 2 + src/back/msl/writer.rs | 10 + src/back/spv/block.rs | 2 + src/back/wgsl/writer.rs | 2 + src/front/glsl/builtins.rs | 33 +-- src/front/spv/mod.rs | 259 +++++++----------- src/front/wgsl/conv.rs | 2 + src/lib.rs | 2 + src/proc/mod.rs | 2 + src/proc/typifier.rs | 2 + src/valid/expression.rs | 2 + tests/in/glsl/math-functions.vert | 51 ++-- tests/in/math-functions.param.ron | 2 + tests/in/math-functions.wgsl | 9 + .../out/glsl/math-functions.main.Vertex.glsl | 14 + tests/out/hlsl/math-functions.hlsl | 9 + tests/out/hlsl/math-functions.hlsl.config | 3 + tests/out/msl/math-functions.msl | 13 + tests/out/spv/math-functions.spvasm | 25 ++ tests/out/wgsl/math-functions-vert.wgsl | 7 + tests/out/wgsl/math-functions.wgsl | 8 + tests/snapshots.rs | 4 + 23 files changed, 258 insertions(+), 207 deletions(-) create mode 100644 tests/in/math-functions.param.ron create mode 100644 tests/in/math-functions.wgsl create mode 100644 tests/out/glsl/math-functions.main.Vertex.glsl create mode 100644 tests/out/hlsl/math-functions.hlsl create mode 100644 tests/out/hlsl/math-functions.hlsl.config create mode 100644 tests/out/msl/math-functions.msl create mode 100644 tests/out/spv/math-functions.spvasm create mode 100644 tests/out/wgsl/math-functions.wgsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 91e1c5762..ada2ea676 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2466,6 +2466,8 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Asinh => "asinh", Mf::Acosh => "acosh", Mf::Atanh => "atanh", + Mf::Radians => "radians", + Mf::Degrees => "degrees", // glsl doesn't have atan2 function // use two-argument variation of the atan function Mf::Atan2 => "atan", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 0280b5058..dd682d9cb 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1835,6 +1835,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::Asinh => Function::Asincosh { is_sin: true }, Mf::Acosh => Function::Asincosh { is_sin: false }, Mf::Atanh => Function::Atanh, + Mf::Radians => Function::Regular("radians"), + Mf::Degrees => Function::Regular("degrees"), // decomposition Mf::Ceil => Function::Regular("ceil"), Mf::Floor => Function::Regular("floor"), diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 664b7ea2f..dfb85c8d5 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1135,6 +1135,8 @@ impl Writer { Mf::Asinh => "asinh", Mf::Acosh => "acosh", Mf::Atanh => "atanh", + Mf::Radians => "", + Mf::Degrees => "", // decomposition Mf::Ceil => "ceil", Mf::Floor => "floor", @@ -1223,6 +1225,14 @@ impl Writer { write!(self.out, "as_type(half2(")?; self.put_expression(arg, context, false)?; write!(self.out, "))")?; + } else if fun == Mf::Radians { + write!(self.out, "((")?; + self.put_expression(arg, context, false)?; + write!(self.out, ") * 0.017453292519943295474)")?; + } else if fun == Mf::Degrees { + write!(self.out, "((")?; + self.put_expression(arg, context, false)?; + write!(self.out, ") * 57.295779513082322865)")?; } else { write!(self.out, "{}::{}", NAMESPACE, fun_name)?; self.put_call_parameters( diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index aba92b9b8..64eaadcc9 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -540,6 +540,8 @@ impl<'w> BlockContext<'w> { Mf::Asinh => MathOp::Ext(spirv::GLOp::Asinh), Mf::Acosh => MathOp::Ext(spirv::GLOp::Acosh), Mf::Atanh => MathOp::Ext(spirv::GLOp::Atanh), + Mf::Radians => MathOp::Ext(spirv::GLOp::Radians), + Mf::Degrees => MathOp::Ext(spirv::GLOp::Degrees), // decomposition Mf::Ceil => MathOp::Ext(spirv::GLOp::Ceil), Mf::Round => MathOp::Ext(spirv::GLOp::RoundEven), diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index dbff2db3c..59c7048c3 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1527,6 +1527,8 @@ impl Writer { Mf::Asinh => Function::Asincosh { is_sin: true }, Mf::Acosh => Function::Asincosh { is_sin: false }, Mf::Atanh => Function::Atanh, + Mf::Radians => Function::Regular("radians"), + Mf::Degrees => Function::Regular("degrees"), // decomposition Mf::Ceil => Function::Regular("ceil"), Mf::Floor => Function::Regular("floor"), diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 1a114a57b..c2c3e2902 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -4,9 +4,9 @@ use super::{ Error, ErrorKind, Parser, Result, }; use crate::{ - BinaryOperator, Block, Constant, ConstantInner, DerivativeAxis, Expression, Handle, ImageClass, + BinaryOperator, Block, Constant, DerivativeAxis, Expression, Handle, ImageClass, ImageDimension, ImageQuery, MathFunction, Module, RelationalFunction, SampleLevel, - ScalarKind as Sk, ScalarValue, Span, Type, TypeInner, VectorSize, + ScalarKind as Sk, Span, Type, TypeInner, VectorSize, }; impl Module { @@ -535,8 +535,8 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module "asinh" => MacroCall::MathFunction(MathFunction::Asinh), "acosh" => MacroCall::MathFunction(MathFunction::Acosh), "atanh" => MacroCall::MathFunction(MathFunction::Atanh), - "radians" => MacroCall::ConstMultiply(std::f64::consts::PI / 180.0), - "degrees" => MacroCall::ConstMultiply(180.0 / std::f64::consts::PI), + "radians" => MacroCall::MathFunction(MathFunction::Radians), + "degrees" => MacroCall::MathFunction(MathFunction::Degrees), "floatBitsToInt" => MacroCall::BitCast(Sk::Sint), "floatBitsToUint" => MacroCall::BitCast(Sk::Uint), "dFdx" | "dFdxFine" | "dFdxCoarse" => { @@ -1551,7 +1551,6 @@ pub enum MacroCall { Splatted(MathFunction, Option, usize), MixBoolean, Clamp(Option), - ConstMultiply(f64), BitCast(Sk), Derivate(DerivativeAxis), } @@ -1868,30 +1867,6 @@ impl MacroCall { body, )) } - MacroCall::ConstMultiply(value) => { - let constant = parser.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(value), - }, - }, - Span::default(), - ); - let right = - ctx.add_expression(Expression::Constant(constant), Span::default(), body); - Ok(ctx.add_expression( - Expression::Binary { - op: BinaryOperator::Multiply, - left: args[0], - right, - }, - Span::default(), - body, - )) - } MacroCall::BitCast(kind) => Ok(ctx.add_expression( Expression::As { expr: args[0], diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index dc578374b..d950b280c 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2531,162 +2531,115 @@ impl> Parser { let inst_id = self.next()?; let gl_op = Glo::from_u32(inst_id).ok_or(Error::UnsupportedExtInst(inst_id))?; - if gl_op == Glo::Radians || gl_op == Glo::Degrees { - inst.expect(base_wc + 1)?; - let arg = { - let arg_id = self.next()?; - let lexp = self.lookup_expression.lookup(arg_id)?; - get_expr_handle!(arg_id, lexp) - }; + let fun = match gl_op { + Glo::Round => Mf::Round, + Glo::RoundEven => Mf::Round, + Glo::Trunc => Mf::Trunc, + Glo::FAbs | Glo::SAbs => Mf::Abs, + Glo::FSign | Glo::SSign => Mf::Sign, + Glo::Floor => Mf::Floor, + Glo::Ceil => Mf::Ceil, + Glo::Fract => Mf::Fract, + Glo::Sin => Mf::Sin, + Glo::Cos => Mf::Cos, + Glo::Tan => Mf::Tan, + Glo::Asin => Mf::Asin, + Glo::Acos => Mf::Acos, + Glo::Atan => Mf::Atan, + Glo::Sinh => Mf::Sinh, + Glo::Cosh => Mf::Cosh, + Glo::Tanh => Mf::Tanh, + Glo::Atan2 => Mf::Atan2, + Glo::Asinh => Mf::Asinh, + Glo::Acosh => Mf::Acosh, + Glo::Atanh => Mf::Atanh, + Glo::Radians => Mf::Radians, + Glo::Degrees => Mf::Degrees, + Glo::Pow => Mf::Pow, + Glo::Exp => Mf::Exp, + Glo::Log => Mf::Log, + Glo::Exp2 => Mf::Exp2, + Glo::Log2 => Mf::Log2, + Glo::Sqrt => Mf::Sqrt, + Glo::InverseSqrt => Mf::InverseSqrt, + Glo::MatrixInverse => Mf::Inverse, + Glo::Determinant => Mf::Determinant, + Glo::Modf => Mf::Modf, + Glo::FMin | Glo::UMin | Glo::SMin | Glo::NMin => Mf::Min, + Glo::FMax | Glo::UMax | Glo::SMax | Glo::NMax => Mf::Max, + Glo::FClamp | Glo::UClamp | Glo::SClamp | Glo::NClamp => Mf::Clamp, + Glo::FMix => Mf::Mix, + Glo::Step => Mf::Step, + Glo::SmoothStep => Mf::SmoothStep, + Glo::Fma => Mf::Fma, + Glo::Frexp => Mf::Frexp, //TODO: FrexpStruct? + Glo::Ldexp => Mf::Ldexp, + Glo::Length => Mf::Length, + Glo::Distance => Mf::Distance, + Glo::Cross => Mf::Cross, + Glo::Normalize => Mf::Normalize, + Glo::FaceForward => Mf::FaceForward, + Glo::Reflect => Mf::Reflect, + Glo::Refract => Mf::Refract, + Glo::PackUnorm4x8 => Mf::Pack4x8unorm, + Glo::PackSnorm4x8 => Mf::Pack4x8snorm, + Glo::PackHalf2x16 => Mf::Pack2x16float, + Glo::PackUnorm2x16 => Mf::Pack2x16unorm, + Glo::PackSnorm2x16 => Mf::Pack2x16snorm, + Glo::UnpackUnorm4x8 => Mf::Unpack4x8unorm, + Glo::UnpackSnorm4x8 => Mf::Unpack4x8snorm, + Glo::UnpackHalf2x16 => Mf::Unpack2x16float, + Glo::UnpackUnorm2x16 => Mf::Unpack2x16unorm, + Glo::UnpackSnorm2x16 => Mf::Unpack2x16snorm, + Glo::FindILsb => Mf::FindLsb, + Glo::FindUMsb | Glo::FindSMsb => Mf::FindMsb, + _ => return Err(Error::UnsupportedExtInst(inst_id)), + }; - // constant expressions need to be excluded from the emitter - block.extend(emitter.finish(ctx.expressions)); - let const_value = match gl_op { - Glo::Radians => std::f64::consts::PI / 180.0, - Glo::Degrees => 180.0 / std::f64::consts::PI, - _ => unreachable!(), - }; - let const_handle = ctx.const_arena.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Float(const_value), - }, - }, - crate::Span::default(), - ); - let expr_handle = ctx.expressions.append( - crate::Expression::Constant(const_handle), - crate::Span::default(), - ); - emitter.start(ctx.expressions); - - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: ctx.expressions.append( - crate::Expression::Binary { - op: crate::BinaryOperator::Multiply, - left: arg, - right: expr_handle, - }, - span, - ), - type_id: result_type_id, - block_id, - }, - ); + let arg_count = fun.argument_count(); + inst.expect(base_wc + arg_count as u16)?; + let arg = { + let arg_id = self.next()?; + let lexp = self.lookup_expression.lookup(arg_id)?; + get_expr_handle!(arg_id, lexp) + }; + let arg1 = if arg_count > 1 { + let arg_id = self.next()?; + let lexp = self.lookup_expression.lookup(arg_id)?; + Some(get_expr_handle!(arg_id, lexp)) } else { - let fun = match gl_op { - Glo::Round => Mf::Round, - Glo::RoundEven => Mf::Round, - Glo::Trunc => Mf::Trunc, - Glo::FAbs | Glo::SAbs => Mf::Abs, - Glo::FSign | Glo::SSign => Mf::Sign, - Glo::Floor => Mf::Floor, - Glo::Ceil => Mf::Ceil, - Glo::Fract => Mf::Fract, - Glo::Sin => Mf::Sin, - Glo::Cos => Mf::Cos, - Glo::Tan => Mf::Tan, - Glo::Asin => Mf::Asin, - Glo::Acos => Mf::Acos, - Glo::Atan => Mf::Atan, - Glo::Sinh => Mf::Sinh, - Glo::Cosh => Mf::Cosh, - Glo::Tanh => Mf::Tanh, - Glo::Atan2 => Mf::Atan2, - Glo::Asinh => Mf::Asinh, - Glo::Acosh => Mf::Acosh, - Glo::Atanh => Mf::Atanh, - Glo::Pow => Mf::Pow, - Glo::Exp => Mf::Exp, - Glo::Log => Mf::Log, - Glo::Exp2 => Mf::Exp2, - Glo::Log2 => Mf::Log2, - Glo::Sqrt => Mf::Sqrt, - Glo::InverseSqrt => Mf::InverseSqrt, - Glo::MatrixInverse => Mf::Inverse, - Glo::Determinant => Mf::Determinant, - Glo::Modf => Mf::Modf, - Glo::FMin | Glo::UMin | Glo::SMin | Glo::NMin => Mf::Min, - Glo::FMax | Glo::UMax | Glo::SMax | Glo::NMax => Mf::Max, - Glo::FClamp | Glo::UClamp | Glo::SClamp | Glo::NClamp => Mf::Clamp, - Glo::FMix => Mf::Mix, - Glo::Step => Mf::Step, - Glo::SmoothStep => Mf::SmoothStep, - Glo::Fma => Mf::Fma, - Glo::Frexp => Mf::Frexp, //TODO: FrexpStruct? - Glo::Ldexp => Mf::Ldexp, - Glo::Length => Mf::Length, - Glo::Distance => Mf::Distance, - Glo::Cross => Mf::Cross, - Glo::Normalize => Mf::Normalize, - Glo::FaceForward => Mf::FaceForward, - Glo::Reflect => Mf::Reflect, - Glo::Refract => Mf::Refract, - Glo::PackUnorm4x8 => Mf::Pack4x8unorm, - Glo::PackSnorm4x8 => Mf::Pack4x8snorm, - Glo::PackHalf2x16 => Mf::Pack2x16float, - Glo::PackUnorm2x16 => Mf::Pack2x16unorm, - Glo::PackSnorm2x16 => Mf::Pack2x16snorm, - Glo::UnpackUnorm4x8 => Mf::Unpack4x8unorm, - Glo::UnpackSnorm4x8 => Mf::Unpack4x8snorm, - Glo::UnpackHalf2x16 => Mf::Unpack2x16float, - Glo::UnpackUnorm2x16 => Mf::Unpack2x16unorm, - Glo::UnpackSnorm2x16 => Mf::Unpack2x16snorm, - Glo::FindILsb => Mf::FindLsb, - Glo::FindUMsb | Glo::FindSMsb => Mf::FindMsb, - _ => return Err(Error::UnsupportedExtInst(inst_id)), - }; + None + }; + let arg2 = if arg_count > 2 { + let arg_id = self.next()?; + let lexp = self.lookup_expression.lookup(arg_id)?; + Some(get_expr_handle!(arg_id, lexp)) + } else { + None + }; + let arg3 = if arg_count > 3 { + let arg_id = self.next()?; + let lexp = self.lookup_expression.lookup(arg_id)?; + Some(get_expr_handle!(arg_id, lexp)) + } else { + None + }; - let arg_count = fun.argument_count(); - inst.expect(base_wc + arg_count as u16)?; - let arg = { - let arg_id = self.next()?; - let lexp = self.lookup_expression.lookup(arg_id)?; - get_expr_handle!(arg_id, lexp) - }; - let arg1 = if arg_count > 1 { - let arg_id = self.next()?; - let lexp = self.lookup_expression.lookup(arg_id)?; - Some(get_expr_handle!(arg_id, lexp)) - } else { - None - }; - let arg2 = if arg_count > 2 { - let arg_id = self.next()?; - let lexp = self.lookup_expression.lookup(arg_id)?; - Some(get_expr_handle!(arg_id, lexp)) - } else { - None - }; - let arg3 = if arg_count > 3 { - let arg_id = self.next()?; - let lexp = self.lookup_expression.lookup(arg_id)?; - Some(get_expr_handle!(arg_id, lexp)) - } else { - None - }; - - let expr = crate::Expression::Math { - fun, - arg, - arg1, - arg2, - arg3, - }; - self.lookup_expression.insert( - result_id, - LookupExpression { - handle: ctx.expressions.append(expr, span), - type_id: result_type_id, - block_id, - }, - ); - } + let expr = crate::Expression::Math { + fun, + arg, + arg1, + arg2, + arg3, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: ctx.expressions.append(expr, span), + type_id: result_type_id, + block_id, + }, + ); } // Relational and Logical Instructions Op::LogicalNot => { diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index b93869071..840dc2b05 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -160,6 +160,8 @@ pub fn map_standard_fun(word: &str) -> Option { "asin" => Mf::Asin, "atan" => Mf::Atan, "atan2" => Mf::Atan2, + "radians" => Mf::Radians, + "degrees" => Mf::Degrees, // decomposition "ceil" => Mf::Ceil, "floor" => Mf::Floor, diff --git a/src/lib.rs b/src/lib.rs index 349ae21f9..6e7083082 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -885,6 +885,8 @@ pub enum MathFunction { Asinh, Acosh, Atanh, + Radians, + Degrees, // decomposition Ceil, Floor, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 04ae4a594..13883df90 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -221,6 +221,8 @@ impl super::MathFunction { Self::Asinh => 1, Self::Acosh => 1, Self::Atanh => 1, + Self::Radians => 1, + Self::Degrees => 1, // decomposition Self::Ceil => 1, Self::Floor => 1, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 270276243..7a1d7a46e 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -701,6 +701,8 @@ impl<'a> ResolveContext<'a> { Mf::Asinh | Mf::Acosh | Mf::Atanh | + Mf::Radians | + Mf::Degrees | // decomposition Mf::Ceil | Mf::Floor | diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 29409a1bc..4e59a9ef4 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -987,6 +987,8 @@ impl super::Validator { | Mf::Asinh | Mf::Acosh | Mf::Atanh + | Mf::Radians + | Mf::Degrees | Mf::Ceil | Mf::Floor | Mf::Round diff --git a/tests/in/glsl/math-functions.vert b/tests/in/glsl/math-functions.vert index ff1851a69..dd8ab7cda 100644 --- a/tests/in/glsl/math-functions.vert +++ b/tests/in/glsl/math-functions.vert @@ -6,33 +6,33 @@ void main() { mat4 m = mat4(a, b, a, b); int i = 5; - vec4 ceilOut = ceil(a); - vec4 roundOut = round(a); - vec4 floorOut = floor(a); - vec4 fractOut = fract(a); - vec4 truncOut = trunc(a); - vec4 sinOut = sin(a); - vec4 absOut = abs(a); + vec4 ceilOut = ceil(a); + vec4 roundOut = round(a); + vec4 floorOut = floor(a); + vec4 fractOut = fract(a); + vec4 truncOut = trunc(a); + vec4 sinOut = sin(a); + vec4 absOut = abs(a); vec4 sqrtOut = sqrt(a); - vec4 inversesqrtOut = inversesqrt(a); - vec4 expOut = exp(a); - vec4 exp2Out = exp2(a); - vec4 signOut = sign(a); - mat4 transposeOut = transpose(m); + vec4 inversesqrtOut = inversesqrt(a); + vec4 expOut = exp(a); + vec4 exp2Out = exp2(a); + vec4 signOut = sign(a); + mat4 transposeOut = transpose(m); // TODO: support inverse function in wgsl output // mat4 inverseOut = inverse(m); - vec4 normalizeOut = normalize(a); - vec4 sinhOut = sinh(a); - vec4 cosOut = cos(a); - vec4 coshOut = cosh(a); - vec4 tanOut = tan(a); - vec4 tanhOut = tanh(a); - vec4 acosOut = acos(a); + vec4 normalizeOut = normalize(a); + vec4 sinhOut = sinh(a); + vec4 cosOut = cos(a); + vec4 coshOut = cosh(a); + vec4 tanOut = tan(a); + vec4 tanhOut = tanh(a); + vec4 acosOut = acos(a); vec4 asinOut = asin(a); - vec4 logOut = log(a); - vec4 log2Out = log2(a); - float lengthOut = length(a); - float determinantOut = determinant(m); + vec4 logOut = log(a); + vec4 log2Out = log2(a); + float lengthOut = length(a); + float determinantOut = determinant(m); int bitCountOut = bitCount(i); int bitfieldReverseOut = bitfieldReverse(i); float atanOut = atan(a.x); @@ -51,5 +51,6 @@ void main() { // vec4 modfOut = modf(a, b); // vec4 frexpOut = frexp(a, b); // float ldexpOut = ldexp(a.x, i); - -} \ No newline at end of file + vec4 rad = radians(a); + float deg = degrees(a.x); +} diff --git a/tests/in/math-functions.param.ron b/tests/in/math-functions.param.ron new file mode 100644 index 000000000..72873dd66 --- /dev/null +++ b/tests/in/math-functions.param.ron @@ -0,0 +1,2 @@ +( +) diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl new file mode 100644 index 000000000..90e5720c4 --- /dev/null +++ b/tests/in/math-functions.wgsl @@ -0,0 +1,9 @@ +[[stage(vertex)]] +fn main() { + let f = 1.0; + let v = vec4(0.0); + let a = degrees(f); + let b = radians(f); + let c = degrees(v); + let d = radians(v); +} diff --git a/tests/out/glsl/math-functions.main.Vertex.glsl b/tests/out/glsl/math-functions.main.Vertex.glsl new file mode 100644 index 000000000..b69069b38 --- /dev/null +++ b/tests/out/glsl/math-functions.main.Vertex.glsl @@ -0,0 +1,14 @@ +#version 310 es + +precision highp float; +precision highp int; + + +void main() { + vec4 v = vec4(0.0); + float a = degrees(1.0); + float b = radians(1.0); + vec4 c = degrees(v); + vec4 d = radians(v); +} + diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl new file mode 100644 index 000000000..5d869f7c9 --- /dev/null +++ b/tests/out/hlsl/math-functions.hlsl @@ -0,0 +1,9 @@ + +void main() +{ + float4 v = float4(0.0.xxxx); + float a = degrees(1.0); + float b = radians(1.0); + float4 c = degrees(v); + float4 d = radians(v); +} diff --git a/tests/out/hlsl/math-functions.hlsl.config b/tests/out/hlsl/math-functions.hlsl.config new file mode 100644 index 000000000..f72fafd91 --- /dev/null +++ b/tests/out/hlsl/math-functions.hlsl.config @@ -0,0 +1,3 @@ +vertex=(main:vs_5_1 ) +fragment=() +compute=() diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl new file mode 100644 index 000000000..42f8be358 --- /dev/null +++ b/tests/out/msl/math-functions.msl @@ -0,0 +1,13 @@ +// language: metal1.1 +#include +#include + + +vertex void main_( +) { + metal::float4 v = metal::float4(0.0); + float a = ((1.0) * 57.295779513082322865); + float b = ((1.0) * 0.017453292519943295474); + metal::float4 c = ((v) * 57.295779513082322865); + metal::float4 d = ((v) * 0.017453292519943295474); +} diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm new file mode 100644 index 000000000..738ac6a72 --- /dev/null +++ b/tests/out/spv/math-functions.spvasm @@ -0,0 +1,25 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 16 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %7 "main" +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.0 +%5 = OpConstant %4 0.0 +%8 = OpTypeFunction %2 +%10 = OpTypeVector %4 4 +%7 = OpFunction %2 None %8 +%6 = OpLabel +OpBranch %9 +%9 = OpLabel +%11 = OpCompositeConstruct %10 %5 %5 %5 %5 +%12 = OpExtInst %4 %1 Degrees %3 +%13 = OpExtInst %4 %1 Radians %3 +%14 = OpExtInst %10 %1 Degrees %11 +%15 = OpExtInst %10 %1 Radians %11 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index b96147e74..ee04f886d 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -42,6 +42,8 @@ fn main_1() { var outerProductOut: mat4x4; var distanceOut: f32; var stepOut: vec4; + var rad: vec4; + var deg: f32; let _e6 = a; let _e7 = b; @@ -144,6 +146,11 @@ fn main_1() { let _e222 = a; let _e223 = b; stepOut = step(_e222, _e223); + let _e227 = a; + rad = radians(_e227); + let _e230 = a; + let _e232 = a; + deg = degrees(_e232.x); return; } diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl new file mode 100644 index 000000000..53a293e51 --- /dev/null +++ b/tests/out/wgsl/math-functions.wgsl @@ -0,0 +1,8 @@ +[[stage(vertex)]] +fn main() { + let v = vec4(0.0); + let a = degrees(1.0); + let b = radians(1.0); + let c = degrees(v); + let d = radians(v); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 57179c5d5..ca007860a 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -484,6 +484,10 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ("cubeArrayShadow", Targets::GLSL), + ( + "math-functions", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL + ), ]; for &(name, targets) in inputs.iter() { From f2832b899954bdd82e8444beed5730749a31a589 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 26 Dec 2021 19:30:57 -0500 Subject: [PATCH 1502/2212] hlsl: support arrays of matrices (#1629) --- src/back/hlsl/writer.rs | 19 +- tests/in/access.wgsl | 1 + tests/out/glsl/access.atomics.Compute.glsl | 1 + tests/out/glsl/access.foo.Vertex.glsl | 1 + tests/out/hlsl/access.hlsl | 30 +-- tests/out/msl/access.msl | 26 +- tests/out/spv/access.spvasm | 297 +++++++++++---------- tests/out/wgsl/access.wgsl | 1 + 8 files changed, 191 insertions(+), 185 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index dd682d9cb..412e36d15 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -715,22 +715,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { stride: _, } => { // HLSL arrays are written as `type name[size]` - let (ty_name, vec_size) = match module.types[base].inner { - // Write scalar type by backend so as not to depend on the front-end implementation - // Name returned from frontend can be generated (type1, float1, etc.) - TypeInner::Scalar { kind, width } => (kind.to_hlsl_str(width)?, None), - // Similarly, write vector types directly. - TypeInner::Vector { size, kind, width } => { - (kind.to_hlsl_str(width)?, Some(size)) - } - _ => (self.names[&NameKey::Type(base)].as_str(), None), - }; - - // Write `type` and `name` - write!(self.out, "{}", ty_name)?; - if let Some(s) = vec_size { - write!(self.out, "{}", s as usize)?; + if let TypeInner::Matrix { .. } = module.types[base].inner { + write!(self.out, "row_major ")?; } + self.write_type(module, base)?; + // Write `name` write!( self.out, " {}", diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index e8ef082fb..ed088e7de 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -2,6 +2,7 @@ struct Bar { matrix: mat4x4; + matrix_array: array, 2>; atom: atomic; arr: [[stride(8)]] array, 2>; data: [[stride(8)]] array; diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index fbc36cfce..cca755cd6 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -7,6 +7,7 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; layout(std430) buffer Bar_block_0Compute { mat4x4 matrix; + mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; int data[]; diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index 2f080d9f0..9b24f6740 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -5,6 +5,7 @@ precision highp int; layout(std430) buffer Bar_block_0Vertex { mat4x4 matrix; + mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; int data[]; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 91b15a93c..aa89e7f90 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -22,9 +22,9 @@ float4 foo(uint vi : SV_VertexID) : SV_Position float baz = foo_1; foo_1 = 1.0; float4x4 matrix_ = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); - uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))}; + uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); - int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 8) - 2u)*8+88)); + int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); const float _e25 = read_from_private(foo_1); bar.Store(8+16+0, asuint(1.0)); { @@ -36,10 +36,10 @@ float4 foo(uint vi : SV_VertexID) : SV_Position } { uint2 _value2[2] = { uint2(0u.xx), uint2(1u.xx) }; - bar.Store2(72+0, asuint(_value2[0])); - bar.Store2(72+8, asuint(_value2[1])); + bar.Store2(104+0, asuint(_value2[0])); + bar.Store2(104+8, asuint(_value2[1])); } - bar.Store(8+88, asuint(1)); + bar.Store(8+120, asuint(1)); { int _result[5]={ a, int(b), 3, 4, 5 }; for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; @@ -54,23 +54,23 @@ void atomics() { int tmp = (int)0; - int value_1 = asint(bar.Load(64)); - int _e6; bar.InterlockedAdd(64, 5, _e6); + int value_1 = asint(bar.Load(96)); + int _e6; bar.InterlockedAdd(96, 5, _e6); tmp = _e6; - int _e9; bar.InterlockedAdd(64, -5, _e9); + int _e9; bar.InterlockedAdd(96, -5, _e9); tmp = _e9; - int _e12; bar.InterlockedAnd(64, 5, _e12); + int _e12; bar.InterlockedAnd(96, 5, _e12); tmp = _e12; - int _e15; bar.InterlockedOr(64, 5, _e15); + int _e15; bar.InterlockedOr(96, 5, _e15); tmp = _e15; - int _e18; bar.InterlockedXor(64, 5, _e18); + int _e18; bar.InterlockedXor(96, 5, _e18); tmp = _e18; - int _e21; bar.InterlockedMin(64, 5, _e21); + int _e21; bar.InterlockedMin(96, 5, _e21); tmp = _e21; - int _e24; bar.InterlockedMax(64, 5, _e24); + int _e24; bar.InterlockedMax(96, 5, _e24); tmp = _e24; - int _e27; bar.InterlockedExchange(64, 5, _e27); + int _e27; bar.InterlockedExchange(96, 5, _e27); tmp = _e27; - bar.Store(64, asuint(value_1)); + bar.Store(96, asuint(value_1)); return; } diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index fda0a3201..53897e1ad 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -6,18 +6,22 @@ struct _mslBufferSizes { metal::uint size0; }; -struct type_3 { +struct type_2 { + metal::float2x2 inner[2]; +}; +struct type_5 { metal::uint2 inner[2]; }; -typedef int type_5[1]; +typedef int type_7[1]; struct Bar { metal::float4x4 matrix; + type_2 matrix_array; metal::atomic_int atom; - char _pad2[4]; - type_3 arr; - type_5 data; + char _pad3[4]; + type_5 arr; + type_7 data; }; -struct type_11 { +struct type_13 { int inner[5]; }; @@ -39,19 +43,19 @@ vertex fooOutput foo( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo_1 = 0.0; - type_11 c; + type_13 c; float baz = foo_1; foo_1 = 1.0; metal::float4x4 matrix = bar.matrix; - type_3 arr = bar.arr; + type_5 arr = bar.arr; float b = bar.matrix[3].x; - int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 8) - 2u]; + int a = bar.data[(1 + (_buffer_sizes.size0 - 120 - 4) / 8) - 2u]; float _e25 = read_from_private(foo_1); bar.matrix[1].z = 1.0; bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); - for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; + for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_5 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; bar.data[1] = 1; - for(int _i=0; _i<5; ++_i) c.inner[_i] = type_11 {a, static_cast(b), 3, 4, 5}.inner[_i]; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type_13 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; return fooOutput { matrix * static_cast(metal::int4(value)) }; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index cd6fea537..6a599ad51 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,43 +1,48 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 115 +; Bound: 119 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %47 "foo" %42 %45 -OpEntryPoint GLCompute %92 "atomics" -OpExecutionMode %92 LocalSize 1 1 1 +OpEntryPoint Vertex %50 "foo" %45 %48 +OpEntryPoint GLCompute %96 "atomics" +OpExecutionMode %96 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %26 0 "matrix" -OpMemberName %26 1 "atom" -OpMemberName %26 2 "arr" -OpMemberName %26 3 "data" -OpName %26 "Bar" -OpName %30 "bar" -OpName %33 "foo" -OpName %34 "read_from_private" -OpName %38 "foo" -OpName %39 "c" -OpName %42 "vi" -OpName %47 "foo" -OpName %90 "tmp" -OpName %92 "atomics" -OpDecorate %24 ArrayStride 8 -OpDecorate %25 ArrayStride 8 -OpMemberDecorate %26 0 Offset 0 -OpMemberDecorate %26 0 ColMajor -OpMemberDecorate %26 0 MatrixStride 16 -OpMemberDecorate %26 1 Offset 64 -OpMemberDecorate %26 2 Offset 72 -OpMemberDecorate %26 3 Offset 88 -OpDecorate %29 ArrayStride 4 -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 0 -OpDecorate %26 Block -OpDecorate %42 BuiltIn VertexIndex -OpDecorate %45 BuiltIn Position +OpMemberName %29 0 "matrix" +OpMemberName %29 1 "matrix_array" +OpMemberName %29 2 "atom" +OpMemberName %29 3 "arr" +OpMemberName %29 4 "data" +OpName %29 "Bar" +OpName %33 "bar" +OpName %36 "foo" +OpName %37 "read_from_private" +OpName %41 "foo" +OpName %42 "c" +OpName %45 "vi" +OpName %50 "foo" +OpName %94 "tmp" +OpName %96 "atomics" +OpDecorate %25 ArrayStride 16 +OpDecorate %27 ArrayStride 8 +OpDecorate %28 ArrayStride 8 +OpMemberDecorate %29 0 Offset 0 +OpMemberDecorate %29 0 ColMajor +OpMemberDecorate %29 0 MatrixStride 16 +OpMemberDecorate %29 1 Offset 64 +OpMemberDecorate %29 1 ColMajor +OpMemberDecorate %29 1 MatrixStride 8 +OpMemberDecorate %29 2 Offset 96 +OpMemberDecorate %29 3 Offset 104 +OpMemberDecorate %29 4 Offset 120 +OpDecorate %32 ArrayStride 4 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 0 +OpDecorate %29 Block +OpDecorate %45 BuiltIn VertexIndex +OpDecorate %48 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -59,121 +64,125 @@ OpDecorate %45 BuiltIn Position %20 = OpConstant %4 42 %22 = OpTypeVector %6 4 %21 = OpTypeMatrix %22 4 -%23 = OpTypeVector %9 2 -%24 = OpTypeArray %23 %3 -%25 = OpTypeRuntimeArray %4 -%26 = OpTypeStruct %21 %4 %24 %25 -%27 = OpTypePointer Function %6 -%28 = OpTypePointer StorageBuffer %4 -%29 = OpTypeArray %4 %17 -%31 = OpTypePointer StorageBuffer %26 -%30 = OpVariable %31 StorageBuffer -%35 = OpTypeFunction %6 %27 -%40 = OpTypePointer Function %29 -%43 = OpTypePointer Input %9 -%42 = OpVariable %43 Input -%46 = OpTypePointer Output %22 -%45 = OpVariable %46 Output -%48 = OpTypeFunction %2 -%51 = OpTypePointer StorageBuffer %21 -%54 = OpTypePointer StorageBuffer %24 -%57 = OpTypePointer StorageBuffer %22 -%58 = OpTypePointer StorageBuffer %6 -%61 = OpTypePointer StorageBuffer %25 -%82 = OpTypePointer Function %4 -%86 = OpTypeVector %4 4 -%94 = OpTypePointer StorageBuffer %4 -%97 = OpConstant %9 64 -%34 = OpFunction %6 None %35 -%33 = OpFunctionParameter %27 -%32 = OpLabel -OpBranch %36 -%36 = OpLabel -%37 = OpLoad %6 %33 -OpReturnValue %37 +%24 = OpTypeVector %6 2 +%23 = OpTypeMatrix %24 2 +%25 = OpTypeArray %23 %3 +%26 = OpTypeVector %9 2 +%27 = OpTypeArray %26 %3 +%28 = OpTypeRuntimeArray %4 +%29 = OpTypeStruct %21 %25 %4 %27 %28 +%30 = OpTypePointer Function %6 +%31 = OpTypePointer StorageBuffer %4 +%32 = OpTypeArray %4 %17 +%34 = OpTypePointer StorageBuffer %29 +%33 = OpVariable %34 StorageBuffer +%38 = OpTypeFunction %6 %30 +%43 = OpTypePointer Function %32 +%46 = OpTypePointer Input %9 +%45 = OpVariable %46 Input +%49 = OpTypePointer Output %22 +%48 = OpVariable %49 Output +%51 = OpTypeFunction %2 +%54 = OpTypePointer StorageBuffer %21 +%57 = OpTypePointer StorageBuffer %27 +%60 = OpTypePointer StorageBuffer %22 +%61 = OpTypePointer StorageBuffer %6 +%64 = OpTypePointer StorageBuffer %28 +%67 = OpConstant %9 4 +%86 = OpTypePointer Function %4 +%90 = OpTypeVector %4 4 +%98 = OpTypePointer StorageBuffer %4 +%101 = OpConstant %9 64 +%37 = OpFunction %6 None %38 +%36 = OpFunctionParameter %30 +%35 = OpLabel +OpBranch %39 +%39 = OpLabel +%40 = OpLoad %6 %36 +OpReturnValue %40 OpFunctionEnd -%47 = OpFunction %2 None %48 -%41 = OpLabel -%38 = OpVariable %27 Function %5 -%39 = OpVariable %40 Function -%44 = OpLoad %9 %42 -OpBranch %49 -%49 = OpLabel -%50 = OpLoad %6 %38 -OpStore %38 %7 -%52 = OpAccessChain %51 %30 %15 -%53 = OpLoad %21 %52 -%55 = OpAccessChain %54 %30 %10 -%56 = OpLoad %24 %55 -%59 = OpAccessChain %58 %30 %15 %8 %15 -%60 = OpLoad %6 %59 -%62 = OpArrayLength %9 %30 3 -%63 = OpISub %9 %62 %10 -%64 = OpAccessChain %28 %30 %8 %63 -%65 = OpLoad %4 %64 -%66 = OpFunctionCall %6 %34 %38 -%67 = OpAccessChain %58 %30 %15 %16 %10 -OpStore %67 %7 -%68 = OpCompositeConstruct %22 %5 %5 %5 %5 -%69 = OpCompositeConstruct %22 %7 %7 %7 %7 -%70 = OpCompositeConstruct %22 %13 %13 %13 %13 -%71 = OpCompositeConstruct %22 %14 %14 %14 %14 -%72 = OpCompositeConstruct %21 %68 %69 %70 %71 -%73 = OpAccessChain %51 %30 %15 -OpStore %73 %72 -%74 = OpCompositeConstruct %23 %15 %15 -%75 = OpCompositeConstruct %23 %16 %16 -%76 = OpCompositeConstruct %24 %74 %75 -%77 = OpAccessChain %54 %30 %10 +%50 = OpFunction %2 None %51 +%44 = OpLabel +%41 = OpVariable %30 Function %5 +%42 = OpVariable %43 Function +%47 = OpLoad %9 %45 +OpBranch %52 +%52 = OpLabel +%53 = OpLoad %6 %41 +OpStore %41 %7 +%55 = OpAccessChain %54 %33 %15 +%56 = OpLoad %21 %55 +%58 = OpAccessChain %57 %33 %8 +%59 = OpLoad %27 %58 +%62 = OpAccessChain %61 %33 %15 %8 %15 +%63 = OpLoad %6 %62 +%65 = OpArrayLength %9 %33 4 +%66 = OpISub %9 %65 %10 +%68 = OpAccessChain %31 %33 %67 %66 +%69 = OpLoad %4 %68 +%70 = OpFunctionCall %6 %37 %41 +%71 = OpAccessChain %61 %33 %15 %16 %10 +OpStore %71 %7 +%72 = OpCompositeConstruct %22 %5 %5 %5 %5 +%73 = OpCompositeConstruct %22 %7 %7 %7 %7 +%74 = OpCompositeConstruct %22 %13 %13 %13 %13 +%75 = OpCompositeConstruct %22 %14 %14 %14 %14 +%76 = OpCompositeConstruct %21 %72 %73 %74 %75 +%77 = OpAccessChain %54 %33 %15 OpStore %77 %76 -%78 = OpAccessChain %28 %30 %8 %16 -OpStore %78 %12 -%79 = OpConvertFToS %4 %60 -%80 = OpCompositeConstruct %29 %65 %79 %18 %19 %17 -OpStore %39 %80 -%81 = OpIAdd %9 %44 %16 -%83 = OpAccessChain %82 %39 %81 -OpStore %83 %20 -%84 = OpAccessChain %82 %39 %44 -%85 = OpLoad %4 %84 -%87 = OpCompositeConstruct %86 %85 %85 %85 %85 -%88 = OpConvertSToF %22 %87 -%89 = OpMatrixTimesVector %22 %53 %88 -OpStore %45 %89 +%78 = OpCompositeConstruct %26 %15 %15 +%79 = OpCompositeConstruct %26 %16 %16 +%80 = OpCompositeConstruct %27 %78 %79 +%81 = OpAccessChain %57 %33 %8 +OpStore %81 %80 +%82 = OpAccessChain %31 %33 %67 %16 +OpStore %82 %12 +%83 = OpConvertFToS %4 %63 +%84 = OpCompositeConstruct %32 %69 %83 %18 %19 %17 +OpStore %42 %84 +%85 = OpIAdd %9 %47 %16 +%87 = OpAccessChain %86 %42 %85 +OpStore %87 %20 +%88 = OpAccessChain %86 %42 %47 +%89 = OpLoad %4 %88 +%91 = OpCompositeConstruct %90 %89 %89 %89 %89 +%92 = OpConvertSToF %22 %91 +%93 = OpMatrixTimesVector %22 %56 %92 +OpStore %48 %93 OpReturn OpFunctionEnd -%92 = OpFunction %2 None %48 -%91 = OpLabel -%90 = OpVariable %82 Function -OpBranch %93 -%93 = OpLabel -%95 = OpAccessChain %94 %30 %16 -%96 = OpAtomicLoad %4 %95 %12 %97 -%99 = OpAccessChain %94 %30 %16 -%98 = OpAtomicIAdd %4 %99 %12 %97 %17 -OpStore %90 %98 -%101 = OpAccessChain %94 %30 %16 -%100 = OpAtomicISub %4 %101 %12 %97 %17 -OpStore %90 %100 -%103 = OpAccessChain %94 %30 %16 -%102 = OpAtomicAnd %4 %103 %12 %97 %17 -OpStore %90 %102 -%105 = OpAccessChain %94 %30 %16 -%104 = OpAtomicOr %4 %105 %12 %97 %17 -OpStore %90 %104 -%107 = OpAccessChain %94 %30 %16 -%106 = OpAtomicXor %4 %107 %12 %97 %17 -OpStore %90 %106 -%109 = OpAccessChain %94 %30 %16 -%108 = OpAtomicSMin %4 %109 %12 %97 %17 -OpStore %90 %108 -%111 = OpAccessChain %94 %30 %16 -%110 = OpAtomicSMax %4 %111 %12 %97 %17 -OpStore %90 %110 -%113 = OpAccessChain %94 %30 %16 -%112 = OpAtomicExchange %4 %113 %12 %97 %17 -OpStore %90 %112 -%114 = OpAccessChain %94 %30 %16 -OpAtomicStore %114 %12 %97 %96 +%96 = OpFunction %2 None %51 +%95 = OpLabel +%94 = OpVariable %86 Function +OpBranch %97 +%97 = OpLabel +%99 = OpAccessChain %98 %33 %10 +%100 = OpAtomicLoad %4 %99 %12 %101 +%103 = OpAccessChain %98 %33 %10 +%102 = OpAtomicIAdd %4 %103 %12 %101 %17 +OpStore %94 %102 +%105 = OpAccessChain %98 %33 %10 +%104 = OpAtomicISub %4 %105 %12 %101 %17 +OpStore %94 %104 +%107 = OpAccessChain %98 %33 %10 +%106 = OpAtomicAnd %4 %107 %12 %101 %17 +OpStore %94 %106 +%109 = OpAccessChain %98 %33 %10 +%108 = OpAtomicOr %4 %109 %12 %101 %17 +OpStore %94 %108 +%111 = OpAccessChain %98 %33 %10 +%110 = OpAtomicXor %4 %111 %12 %101 %17 +OpStore %94 %110 +%113 = OpAccessChain %98 %33 %10 +%112 = OpAtomicSMin %4 %113 %12 %101 %17 +OpStore %94 %112 +%115 = OpAccessChain %98 %33 %10 +%114 = OpAtomicSMax %4 %115 %12 %101 %17 +OpStore %94 %114 +%117 = OpAccessChain %98 %33 %10 +%116 = OpAtomicExchange %4 %117 %12 %101 %17 +OpStore %94 %116 +%118 = OpAccessChain %98 %33 %10 +OpAtomicStore %118 %12 %101 %100 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index e43707715..ca5313a80 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -1,5 +1,6 @@ struct Bar { matrix: mat4x4; + matrix_array: [[stride(16)]] array,2>; atom: atomic; arr: [[stride(8)]] array,2>; data: [[stride(8)]] array; From 848ae3dc6e96a30c9459b1a11d7034eb422da533 Mon Sep 17 00:00:00 2001 From: Jeff Muizelaar Date: Sun, 26 Dec 2021 20:01:49 -0500 Subject: [PATCH 1503/2212] Turn on panic = "abort" by default (#1597) This reduces the size of a release naga binary on macOS from 3.5MB to 3.2MB. It's also the configuration we use for naga in Firefox. --- Cargo.toml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index b3eaa2416..fdbf8216a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,12 @@ petgraph = { version ="0.6", optional = true } pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } +[profile.release] +panic = "abort" + +[profile.dev] +panic = "abort" + [features] default = [] dot-out = [] From b1ab59925ddd1503ddb864367da3ae4823145051 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 26 Dec 2021 21:57:47 -0500 Subject: [PATCH 1504/2212] msl: fix packed float support (#1630) --- src/back/msl/writer.rs | 3 +- tests/in/globals.wgsl | 10 +++- tests/out/glsl/globals.main.Compute.glsl | 11 +++- tests/out/hlsl/globals.hlsl | 13 ++++- tests/out/msl/globals.msl | 12 +++- tests/out/spv/globals.spvasm | 72 +++++++++++++++--------- tests/out/wgsl/globals.wgsl | 14 ++++- tests/snapshots.rs | 2 +- 8 files changed, 97 insertions(+), 40 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index dfb85c8d5..38774a6d0 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2357,8 +2357,9 @@ impl Writer { Some(kind) => { writeln!( self.out, - "{}packed_{}3 {};", + "{}{}::packed_{}3 {};", back::INDENT, + NAMESPACE, scalar_kind_string(kind), member_name )?; diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 87b25f6b6..e215f039e 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -5,9 +5,17 @@ let Foo: bool = true; var wg : array; var at: atomic; +struct Foo { + v3: vec3; + // test packed vec3 + v1: f32; +}; +[[group(0), binding(1)]] +var alignment: Foo; + [[stage(compute), workgroup_size(1)]] fn main() { - wg[3] = 1.0; + wg[3] = alignment.v1; atomicStore(&at, 2u); // Valid, Foo and at is in function scope diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index f38fde93e..d6892df82 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -5,15 +5,22 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +struct Foo { + vec3 v3_; + float v1_; +}; shared float wg[10]; shared uint at_1; +layout(std430) readonly buffer Foo_block_0Compute { Foo _group_0_binding_1_cs; }; + void main() { - float Foo = 1.0; + float Foo_1 = 1.0; bool at = true; - wg[3] = 1.0; + float _e7 = _group_0_binding_1_cs.v1_; + wg[3] = _e7; at_1 = 2u; return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index ef2ceb422..0c9f1cae8 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -1,15 +1,22 @@ -static const bool Foo_1 = true; +static const bool Foo_2 = true; + +struct Foo { + float3 v3_; + float v1_; +}; groupshared float wg[10]; groupshared uint at_1; +ByteAddressBuffer alignment : register(t1); [numthreads(1, 1, 1)] void main() { - float Foo = 1.0; + float Foo_1 = 1.0; bool at = true; - wg[3] = 1.0; + float _expr7 = asfloat(alignment.Load(12)); + wg[3] = _expr7; at_1 = 2u; return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index c00b2a237..7aeb00250 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -2,18 +2,24 @@ #include #include -constexpr constant bool Foo_1 = true; +constexpr constant bool Foo_2 = true; struct type_2 { float inner[10u]; }; +struct Foo { + metal::packed_float3 v3_; + float v1_; +}; kernel void main_( threadgroup type_2& wg , threadgroup metal::atomic_uint& at_1 +, constant Foo& alignment [[user(fake0)]] ) { - float Foo = 1.0; + float Foo_1 = 1.0; bool at = true; - wg.inner[3] = 1.0; + float _e7 = alignment.v1_; + wg.inner[3] = _e7; metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 942d5a73d..45aec8c2f 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,13 +1,21 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 31 +; Bound: 43 OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %23 "main" -OpExecutionMode %23 LocalSize 1 1 1 +OpEntryPoint GLCompute %28 "main" +OpExecutionMode %28 LocalSize 1 1 1 OpDecorate %13 ArrayStride 4 +OpMemberDecorate %15 0 Offset 0 +OpMemberDecorate %15 1 Offset 12 +OpDecorate %20 NonWritable +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 1 +OpDecorate %21 Block +OpMemberDecorate %21 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -15,30 +23,42 @@ OpDecorate %13 ArrayStride 4 %5 = OpConstant %6 10 %8 = OpTypeInt 32 1 %7 = OpConstant %8 3 -%10 = OpTypeFloat 32 -%9 = OpConstant %10 1.0 -%11 = OpConstant %6 2 +%9 = OpConstant %6 2 +%11 = OpTypeFloat 32 +%10 = OpConstant %11 1.0 %12 = OpConstantTrue %4 -%13 = OpTypeArray %10 %5 -%15 = OpTypePointer Workgroup %13 -%14 = OpVariable %15 Workgroup -%17 = OpTypePointer Workgroup %6 +%13 = OpTypeArray %11 %5 +%14 = OpTypeVector %11 3 +%15 = OpTypeStruct %14 %11 +%17 = OpTypePointer Workgroup %13 %16 = OpVariable %17 Workgroup -%19 = OpTypePointer Function %10 -%21 = OpTypePointer Function %4 -%24 = OpTypeFunction %2 -%26 = OpTypePointer Workgroup %10 -%27 = OpConstant %6 3 -%29 = OpConstant %8 2 -%30 = OpConstant %6 256 -%23 = OpFunction %2 None %24 -%22 = OpLabel -%18 = OpVariable %19 Function %9 -%20 = OpVariable %21 Function %12 -OpBranch %25 -%25 = OpLabel -%28 = OpAccessChain %26 %14 %27 -OpStore %28 %9 -OpAtomicStore %16 %29 %30 %11 +%19 = OpTypePointer Workgroup %6 +%18 = OpVariable %19 Workgroup +%21 = OpTypeStruct %15 +%22 = OpTypePointer StorageBuffer %21 +%20 = OpVariable %22 StorageBuffer +%24 = OpTypePointer Function %11 +%26 = OpTypePointer Function %4 +%29 = OpTypeFunction %2 +%30 = OpTypePointer StorageBuffer %15 +%31 = OpConstant %6 0 +%34 = OpTypePointer Workgroup %11 +%35 = OpTypePointer StorageBuffer %11 +%36 = OpConstant %6 1 +%39 = OpConstant %6 3 +%41 = OpConstant %8 2 +%42 = OpConstant %6 256 +%28 = OpFunction %2 None %29 +%27 = OpLabel +%23 = OpVariable %24 Function %10 +%25 = OpVariable %26 Function %12 +%32 = OpAccessChain %30 %20 %31 +OpBranch %33 +%33 = OpLabel +%37 = OpAccessChain %35 %32 %36 +%38 = OpLoad %11 %37 +%40 = OpAccessChain %34 %16 %39 +OpStore %40 %38 +OpAtomicStore %18 %41 %42 %9 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 06e1bdb1f..cc514c1e4 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -1,14 +1,22 @@ -let Foo_1: bool = true; +struct Foo { + v3_: vec3; + v1_: f32; +}; + +let Foo_2: bool = true; var wg: array; var at_1: atomic; +[[group(0), binding(1)]] +var alignment: Foo; [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { - var Foo: f32 = 1.0; + var Foo_1: f32 = 1.0; var at: bool = true; - wg[3] = 1.0; + let _e7 = alignment.v1_; + wg[3] = _e7; atomicStore((&at_1), 2u); return; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index ca007860a..dbc86b682 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -486,7 +486,7 @@ fn convert_wgsl() { ("cubeArrayShadow", Targets::GLSL), ( "math-functions", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ]; From 5a26606a092e5120d07b842c10e5886d585f3b76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 28 Dec 2021 00:09:33 +0000 Subject: [PATCH 1505/2212] glsl-in: Fix using swizzle as out arguments (#1632) This worked at one point but because of some changes to the IR it was temporarily broken. --- src/front/glsl/functions.rs | 37 +++++++++++++++++++++++--- tests/in/glsl/swizzle_write.frag | 2 ++ tests/out/wgsl/swizzle_write-frag.wgsl | 13 +++++++++ 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 95336a5d6..fc9a0677e 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -756,8 +756,6 @@ impl Parser { // If the argument is to be passed as a pointer but the type of the // expression returns a vector it must mean that it was for example // swizzled and it must be spilled into a local before calling - // TODO: this part doesn't work because of #1385 once that's sorted out - // revisit this part. TypeInner::Vector { size, kind, width } => ( self.module.types.insert( Type { @@ -829,7 +827,40 @@ impl Parser { arguments.push(temp_expr); // Register the temporary local to be written back to it's original // place after the function call - proxy_writes.push((handle, temp_expr)); + if let Expression::Swizzle { + size, + mut vector, + pattern, + } = ctx.expressions[value] + { + if let Expression::Load { pointer } = ctx.expressions[vector] { + vector = pointer; + } + + for (i, component) in pattern.iter().take(size as usize).enumerate() { + let original = ctx.add_expression( + Expression::AccessIndex { + base: vector, + index: *component as u32, + }, + Span::default(), + body, + ); + + let temp = ctx.add_expression( + Expression::AccessIndex { + base: temp_expr, + index: i as u32, + }, + Span::default(), + body, + ); + + proxy_writes.push((original, temp)); + } + } else { + proxy_writes.push((handle, temp_expr)); + } continue; } diff --git a/tests/in/glsl/swizzle_write.frag b/tests/in/glsl/swizzle_write.frag index a554c94e1..c5a165590 100644 --- a/tests/in/glsl/swizzle_write.frag +++ b/tests/in/glsl/swizzle_write.frag @@ -1,9 +1,11 @@ #version 450 +void foo(inout vec2 p) {} void main() { vec3 x = vec3(2.0); x.zxy.xy = vec2(3.0, 4.0); x.rg *= 5.0; x.zy++; + foo(x.xz); } diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index 48ca0a199..04bbd7ec5 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -1,5 +1,10 @@ +fn foo(p: ptr>) { + return; +} + fn main_1() { var x: vec3 = vec3(2.0, 2.0, 2.0); + var local: vec2; let _e3 = x; let _e8 = vec2(3.0, 4.0); @@ -14,6 +19,14 @@ fn main_1() { let _e27 = (_e23.zy + vec2(1.0)); x.z = _e27.x; x.y = _e27.y; + let _e32 = x; + let _e34 = x; + local = _e34.xz; + foo((&local)); + let _e41 = local.x; + x.x = _e41; + let _e42 = local.y; + x.z = _e42; return; } From 2738ad80b97801ca4c6e34f0d8145b55292d986d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 28 Dec 2021 00:13:13 -0500 Subject: [PATCH 1506/2212] msl: fix packed vec access (#1634) --- src/back/msl/writer.rs | 111 +++++++++++++---------- tests/in/globals.wgsl | 1 + tests/out/glsl/globals.main.Compute.glsl | 2 + tests/out/hlsl/globals.hlsl | 2 + tests/out/msl/boids.msl | 2 +- tests/out/msl/globals.msl | 2 + tests/out/msl/shadow.msl | 2 +- tests/out/spv/globals.spvasm | 102 +++++++++++---------- tests/out/wgsl/globals.wgsl | 2 + 9 files changed, 130 insertions(+), 96 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 38774a6d0..55c0d5482 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -47,20 +47,20 @@ impl<'a> Display for TypeContext<'a> { // work around Metal toolchain bug with `uint` typedef crate::ScalarKind::Uint => write!(out, "{}::uint", NAMESPACE), _ => { - let kind_str = scalar_kind_string(kind); + let kind_str = kind.to_msl_name(); write!(out, "{}", kind_str) } } } crate::TypeInner::Atomic { kind, .. } => { - write!(out, "{}::atomic_{}", NAMESPACE, scalar_kind_string(kind)) + write!(out, "{}::atomic_{}", NAMESPACE, kind.to_msl_name()) } crate::TypeInner::Vector { size, kind, .. } => { write!( out, "{}::{}{}", NAMESPACE, - scalar_kind_string(kind), + kind.to_msl_name(), back::vector_size_str(size), ) } @@ -69,7 +69,7 @@ impl<'a> Display for TypeContext<'a> { out, "{}::{}{}x{}", NAMESPACE, - scalar_kind_string(crate::ScalarKind::Float), + crate::ScalarKind::Float.to_msl_name(), back::vector_size_str(columns), back::vector_size_str(rows), ) @@ -96,7 +96,7 @@ impl<'a> Display for TypeContext<'a> { Some(name) => name, None => return Ok(()), }; - write!(out, "{} {}&", class_name, scalar_kind_string(kind),) + write!(out, "{} {}&", class_name, kind.to_msl_name(),) } crate::TypeInner::ValuePointer { size: Some(size), @@ -113,7 +113,7 @@ impl<'a> Display for TypeContext<'a> { "{} {}::{}{}&", class_name, NAMESPACE, - scalar_kind_string(kind), + kind.to_msl_name(), back::vector_size_str(size), ) } @@ -178,7 +178,7 @@ impl<'a> Display for TypeContext<'a> { ("texture", "", format.into(), access) } }; - let base_name = scalar_kind_string(kind); + let base_name = kind.to_msl_name(); let array_str = if arrayed { "_array" } else { "" }; write!( out, @@ -316,12 +316,14 @@ pub struct Writer { struct_member_pads: FastHashSet<(Handle, u32)>, } -fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str { - match kind { - crate::ScalarKind::Float => "float", - crate::ScalarKind::Sint => "int", - crate::ScalarKind::Uint => "uint", - crate::ScalarKind::Bool => "bool", +impl crate::ScalarKind { + fn to_msl_name(self) -> &'static str { + match self { + Self::Float => "float", + Self::Sint => "int", + Self::Uint => "uint", + Self::Bool => "bool", + } } } @@ -481,6 +483,29 @@ impl<'a> ExpressionContext<'a> { ) -> Option { index::access_needs_check(base, index, self.module, self.function, self.info) } + + // Because packed vectors such as `packed_float3` cannot be directly loaded, + // we convert them to unpacked vectors like `float3` on load. + fn get_packed_vec_kind( + &self, + expr_handle: Handle, + ) -> Option { + match self.function.expressions[expr_handle] { + crate::Expression::AccessIndex { base, index } => { + let ty = match *self.resolve_type(base) { + crate::TypeInner::Pointer { base, .. } => &self.module.types[base].inner, + ref ty => ty, + }; + match *ty { + crate::TypeInner::Struct { + ref members, span, .. + } => should_pack_struct_member(members, span, index as usize, self.module), + _ => None, + } + } + _ => None, + } + } } struct StatementContext<'a> { @@ -652,7 +677,7 @@ impl Writer { ) -> BackendResult { match context.module.types[ty].inner { crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { - write!(self.out, "{}", scalar_kind_string(kind))?; + write!(self.out, "{}", kind.to_msl_name())?; self.put_call_parameters(components.iter().cloned(), context)?; } crate::TypeInner::Vector { size, kind, .. } => { @@ -660,7 +685,7 @@ impl Writer { self.out, "{}::{}{}", NAMESPACE, - scalar_kind_string(kind), + kind.to_msl_name(), back::vector_size_str(size) )?; self.put_call_parameters(components.iter().cloned(), context)?; @@ -671,7 +696,7 @@ impl Writer { self.out, "{}::{}{}x{}", NAMESPACE, - scalar_kind_string(kind), + kind.to_msl_name(), back::vector_size_str(columns), back::vector_size_str(rows) )?; @@ -845,7 +870,7 @@ impl Writer { crate::TypeInner::Scalar { kind, .. } => kind, _ => return Err(Error::Validation), }; - let scalar = scalar_kind_string(scalar_kind); + let scalar = scalar_kind.to_msl_name(); let size = back::vector_size_str(size); write!(self.out, "{}::{}{}(", NAMESPACE, scalar, size)?; @@ -1246,7 +1271,7 @@ impl Writer { kind, convert, } => { - let scalar = scalar_kind_string(kind); + let scalar = kind.to_msl_name(); let (src_kind, src_width) = match *context.resolve_type(expr) { crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Vector { kind, width, .. } => (kind, width), @@ -1487,7 +1512,15 @@ impl Writer { write!(self.out, ".{}", name)?; } crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => { - self.put_access_chain(base, policy, context)?; + let wrap_packed_vec_scalar_kind = context.get_packed_vec_kind(base); + //Note: this doesn't work for left-hand side + if let Some(scalar_kind) = wrap_packed_vec_scalar_kind { + write!(self.out, "{}::{}3(", NAMESPACE, scalar_kind.to_msl_name())?; + self.put_access_chain(base, policy, context)?; + write!(self.out, ")")?; + } else { + self.put_access_chain(base, policy, context)?; + } write!(self.out, ".{}", back::COMPONENTS[index as usize])?; } _ => { @@ -1614,23 +1647,7 @@ impl Writer { policy: index::BoundsCheckPolicy, context: &ExpressionContext, ) -> BackendResult { - // Because packed vectors such as `packed_float3` cannot be directly multipied by - // matrices, we convert them to unpacked vectors like `float3` on load. - let wrap_packed_vec_scalar_kind = match context.function.expressions[pointer] { - crate::Expression::AccessIndex { base, index } => { - let ty = match *context.resolve_type(base) { - crate::TypeInner::Pointer { base, .. } => &context.module.types[base].inner, - ref ty => ty, - }; - match *ty { - crate::TypeInner::Struct { - ref members, span, .. - } => should_pack_struct_member(members, span, index as usize, context.module), - _ => None, - } - } - _ => None, - }; + let wrap_packed_vec_scalar_kind = context.get_packed_vec_kind(pointer); let is_atomic = match *context.resolve_type(pointer) { crate::TypeInner::Pointer { base, .. } => match context.module.types[base].inner { crate::TypeInner::Atomic { .. } => true, @@ -1640,12 +1657,7 @@ impl Writer { }; if let Some(scalar_kind) = wrap_packed_vec_scalar_kind { - write!( - self.out, - "{}::{}3(", - NAMESPACE, - scalar_kind_string(scalar_kind) - )?; + write!(self.out, "{}::{}3(", NAMESPACE, scalar_kind.to_msl_name())?; self.put_access_chain(pointer, policy, context)?; write!(self.out, ")")?; } else if is_atomic { @@ -1761,15 +1773,22 @@ impl Writer { }; write!(self.out, "{}", ty_name)?; } + TypeResolution::Value(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + }) => { + // work around Metal toolchain bug with `uint` typedef + write!(self.out, "{}::uint", NAMESPACE)?; + } TypeResolution::Value(crate::TypeInner::Scalar { kind, .. }) => { - write!(self.out, "{}", scalar_kind_string(kind))?; + write!(self.out, "{}", kind.to_msl_name())?; } TypeResolution::Value(crate::TypeInner::Vector { size, kind, .. }) => { write!( self.out, "{}::{}{}", NAMESPACE, - scalar_kind_string(kind), + kind.to_msl_name(), back::vector_size_str(size) )?; } @@ -1778,7 +1797,7 @@ impl Writer { self.out, "{}::{}{}x{}", NAMESPACE, - scalar_kind_string(crate::ScalarKind::Float), + crate::ScalarKind::Float.to_msl_name(), back::vector_size_str(columns), back::vector_size_str(rows), )?; @@ -2360,7 +2379,7 @@ impl Writer { "{}{}::packed_{}3 {};", back::INDENT, NAMESPACE, - scalar_kind_string(kind), + kind.to_msl_name(), member_name )?; } diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index e215f039e..03f87ddfb 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -16,6 +16,7 @@ var alignment: Foo; [[stage(compute), workgroup_size(1)]] fn main() { wg[3] = alignment.v1; + wg[2] = alignment.v3.x; atomicStore(&at, 2u); // Valid, Foo and at is in function scope diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index d6892df82..cdc5e7260 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -21,6 +21,8 @@ void main() { bool at = true; float _e7 = _group_0_binding_1_cs.v1_; wg[3] = _e7; + float _e12 = _group_0_binding_1_cs.v3_.x; + wg[2] = _e12; at_1 = 2u; return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 0c9f1cae8..1e05d9fa7 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -17,6 +17,8 @@ void main() float _expr7 = asfloat(alignment.Load(12)); wg[3] = _expr7; + float _expr12 = asfloat(alignment.Load(0+0)); + wg[2] = _expr12; at_1 = 2u; return; } diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index 461602f88..b717466f9 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -45,7 +45,7 @@ kernel void main_( metal::float2 pos; metal::float2 vel; metal::uint i = 0u; - uint index = global_invocation_id.x; + metal::uint index = global_invocation_id.x; if (index >= NUM_PARTICLES) { return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 7aeb00250..636aa69c8 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -20,6 +20,8 @@ kernel void main_( bool at = true; float _e7 = alignment.v1_; wg.inner[3] = _e7; + float _e12 = metal::float3(alignment.v3_).x; + wg.inner[2] = _e12; metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); return; } diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 33475b841..54e918de4 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -63,7 +63,7 @@ fragment fs_mainOutput fs_main( } loop_init = false; metal::uint _e12 = i; - uint _e15 = u_globals.num_lights.x; + metal::uint _e15 = u_globals.num_lights.x; if (_e12 >= metal::min(_e15, c_max_lights)) { break; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 45aec8c2f..c9ec4c220 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,21 +1,21 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 43 +; Bound: 48 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %28 "main" -OpExecutionMode %28 LocalSize 1 1 1 -OpDecorate %13 ArrayStride 4 -OpMemberDecorate %15 0 Offset 0 -OpMemberDecorate %15 1 Offset 12 -OpDecorate %20 NonWritable -OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 1 -OpDecorate %21 Block -OpMemberDecorate %21 0 Offset 0 +OpEntryPoint GLCompute %29 "main" +OpExecutionMode %29 LocalSize 1 1 1 +OpDecorate %14 ArrayStride 4 +OpMemberDecorate %16 0 Offset 0 +OpMemberDecorate %16 1 Offset 12 +OpDecorate %21 NonWritable +OpDecorate %21 DescriptorSet 0 +OpDecorate %21 Binding 1 +OpDecorate %22 Block +OpMemberDecorate %22 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -23,42 +23,48 @@ OpMemberDecorate %21 0 Offset 0 %5 = OpConstant %6 10 %8 = OpTypeInt 32 1 %7 = OpConstant %8 3 -%9 = OpConstant %6 2 -%11 = OpTypeFloat 32 -%10 = OpConstant %11 1.0 -%12 = OpConstantTrue %4 -%13 = OpTypeArray %11 %5 -%14 = OpTypeVector %11 3 -%15 = OpTypeStruct %14 %11 -%17 = OpTypePointer Workgroup %13 -%16 = OpVariable %17 Workgroup -%19 = OpTypePointer Workgroup %6 -%18 = OpVariable %19 Workgroup -%21 = OpTypeStruct %15 -%22 = OpTypePointer StorageBuffer %21 -%20 = OpVariable %22 StorageBuffer -%24 = OpTypePointer Function %11 -%26 = OpTypePointer Function %4 -%29 = OpTypeFunction %2 -%30 = OpTypePointer StorageBuffer %15 -%31 = OpConstant %6 0 -%34 = OpTypePointer Workgroup %11 -%35 = OpTypePointer StorageBuffer %11 -%36 = OpConstant %6 1 -%39 = OpConstant %6 3 -%41 = OpConstant %8 2 -%42 = OpConstant %6 256 -%28 = OpFunction %2 None %29 -%27 = OpLabel -%23 = OpVariable %24 Function %10 -%25 = OpVariable %26 Function %12 -%32 = OpAccessChain %30 %20 %31 -OpBranch %33 -%33 = OpLabel -%37 = OpAccessChain %35 %32 %36 -%38 = OpLoad %11 %37 -%40 = OpAccessChain %34 %16 %39 -OpStore %40 %38 -OpAtomicStore %18 %41 %42 %9 +%9 = OpConstant %8 2 +%10 = OpConstant %6 2 +%12 = OpTypeFloat 32 +%11 = OpConstant %12 1.0 +%13 = OpConstantTrue %4 +%14 = OpTypeArray %12 %5 +%15 = OpTypeVector %12 3 +%16 = OpTypeStruct %15 %12 +%18 = OpTypePointer Workgroup %14 +%17 = OpVariable %18 Workgroup +%20 = OpTypePointer Workgroup %6 +%19 = OpVariable %20 Workgroup +%22 = OpTypeStruct %16 +%23 = OpTypePointer StorageBuffer %22 +%21 = OpVariable %23 StorageBuffer +%25 = OpTypePointer Function %12 +%27 = OpTypePointer Function %4 +%30 = OpTypeFunction %2 +%31 = OpTypePointer StorageBuffer %16 +%32 = OpConstant %6 0 +%35 = OpTypePointer Workgroup %12 +%36 = OpTypePointer StorageBuffer %12 +%37 = OpConstant %6 1 +%40 = OpConstant %6 3 +%42 = OpTypePointer StorageBuffer %15 +%43 = OpTypePointer StorageBuffer %12 +%47 = OpConstant %6 256 +%29 = OpFunction %2 None %30 +%28 = OpLabel +%24 = OpVariable %25 Function %11 +%26 = OpVariable %27 Function %13 +%33 = OpAccessChain %31 %21 %32 +OpBranch %34 +%34 = OpLabel +%38 = OpAccessChain %36 %33 %37 +%39 = OpLoad %12 %38 +%41 = OpAccessChain %35 %17 %40 +OpStore %41 %39 +%44 = OpAccessChain %43 %33 %32 %32 +%45 = OpLoad %12 %44 +%46 = OpAccessChain %35 %17 %10 +OpStore %46 %45 +OpAtomicStore %19 %9 %47 %10 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index cc514c1e4..a79623904 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -17,6 +17,8 @@ fn main() { let _e7 = alignment.v1_; wg[3] = _e7; + let _e12 = alignment.v3_.x; + wg[2] = _e12; atomicStore((&at_1), 2u); return; } From 1d0f484b37dec4828ce581a55a94d4706fe6d583 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 29 Dec 2021 01:16:56 +0000 Subject: [PATCH 1507/2212] glsl-in: fix composite constructors (#1631) * glsl-in: Remove unneeded mutability from reference * glsl-in: Fix composite constructors In the recent rework of the constructors it seems that the logic for composite types (arrays and structs) was accidentally removed by me. --- src/front/glsl/context.rs | 10 ++--- src/front/glsl/functions.rs | 61 +++++++++++++++++++++++---- tests/in/glsl/declarations.vert | 11 +++++ tests/out/wgsl/declarations-vert.wgsl | 8 ++++ 4 files changed, 77 insertions(+), 13 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index fa29b5ceb..eefef012b 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -881,7 +881,7 @@ impl Context { pub fn expr_scalar_components( &mut self, - parser: &mut Parser, + parser: &Parser, expr: Handle, meta: Span, ) -> Result> { @@ -891,7 +891,7 @@ impl Context { pub fn expr_power( &mut self, - parser: &mut Parser, + parser: &Parser, expr: Handle, meta: Span, ) -> Result> { @@ -921,7 +921,7 @@ impl Context { pub fn implicit_conversion( &mut self, - parser: &mut Parser, + parser: &Parser, expr: &mut Handle, meta: Span, kind: ScalarKind, @@ -941,7 +941,7 @@ impl Context { pub fn binary_implicit_conversion( &mut self, - parser: &mut Parser, + parser: &Parser, left: &mut Handle, left_meta: Span, right: &mut Handle, @@ -974,7 +974,7 @@ impl Context { pub fn implicit_splat( &mut self, - parser: &mut Parser, + parser: &Parser, expr: &mut Handle, meta: Span, vector_size: Option, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index fc9a0677e..14f30bdfb 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -195,14 +195,39 @@ impl Parser { (value, expr_meta), meta, )?, - TypeInner::Struct { .. } | TypeInner::Array { .. } => ctx.add_expression( - Expression::Compose { - ty, - components: vec![value], - }, - meta, - body, - ), + TypeInner::Struct { ref members, .. } => { + let scalar_components = members + .get(0) + .and_then(|member| scalar_components(&self.module.types[member.ty].inner)); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut value, expr_meta, kind, width)?; + } + + ctx.add_expression( + Expression::Compose { + ty, + components: vec![value], + }, + meta, + body, + ) + } + + TypeInner::Array { base, .. } => { + let scalar_components = scalar_components(&self.module.types[base].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut value, expr_meta, kind, width)?; + } + + ctx.add_expression( + Expression::Compose { + ty, + components: vec![value], + }, + meta, + body, + ) + } _ => { self.errors.push(Error { kind: ErrorKind::SemanticError("Bad type constructor".into()), @@ -535,6 +560,26 @@ impl Parser { TypeInner::Vector { size, kind, width } => { return self.vector_constructor(ctx, body, ty, size, kind, width, &args, meta) } + TypeInner::Array { base, .. } => { + for (mut arg, meta) in args.iter().copied() { + let scalar_components = scalar_components(&self.module.types[base].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; + } + + components.push(arg) + } + } + TypeInner::Struct { ref members, .. } => { + for ((mut arg, meta), member) in args.iter().copied().zip(members.iter()) { + let scalar_components = scalar_components(&self.module.types[member.ty].inner); + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; + } + + components.push(arg) + } + } _ => { return Err(Error { kind: ErrorKind::SemanticError("Constructor: Too many arguments".into()), diff --git a/tests/in/glsl/declarations.vert b/tests/in/glsl/declarations.vert index e0c2ec6e8..c8dab7795 100644 --- a/tests/in/glsl/declarations.vert +++ b/tests/in/glsl/declarations.vert @@ -10,5 +10,16 @@ layout(location = 0) out FragmentData { vec2 a; } frag; +struct TestStruct { + float a; + float b; +}; + + void main() { + const vec3 positions[2] = vec3[2]( + vec3(-1.0, 1.0, 0.0), + vec3(-1.0, -1.0, 0.0) + ); + const TestStruct strct = TestStruct( 1, 2 ); } diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index 952ca9dca..654a1cc2c 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -8,6 +8,11 @@ struct FragmentData { a: vec2; }; +struct TestStruct { + a: f32; + b: f32; +}; + struct VertexOutput { [[location(0)]] position: vec2; [[location(1)]] a: vec2; @@ -17,6 +22,9 @@ var vert: VertexData; var frag: FragmentData; fn main_1() { + var positions: array,2u> = array,2u>(vec3(-1.0, 1.0, 0.0), vec3(-1.0, -1.0, 0.0)); + var strct: TestStruct = TestStruct(1.0, 2.0); + } [[stage(vertex)]] From 6aca3e0b36f02e45cdc866396c0b64163e6aa7c5 Mon Sep 17 00:00:00 2001 From: Vinh Truong Date: Fri, 31 Dec 2021 18:44:54 +0200 Subject: [PATCH 1508/2212] Fix data packing functions on MSL (#1637) * Fix data packing functions on MSL `snorm` and `unorm` got mixed up. * Fix bits.msl --- src/back/msl/writer.rs | 8 ++++---- tests/out/msl/bits.msl | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 55c0d5482..3436ac0ec 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1207,10 +1207,10 @@ impl Writer { Mf::FindLsb => "", Mf::FindMsb => "", // data packing - Mf::Pack4x8snorm => "pack_float_to_unorm4x8", - Mf::Pack4x8unorm => "pack_float_to_snorm4x8", - Mf::Pack2x16snorm => "pack_float_to_unorm2x16", - Mf::Pack2x16unorm => "pack_float_to_snorm2x16", + Mf::Pack4x8snorm => "pack_float_to_snorm4x8", + Mf::Pack4x8unorm => "pack_float_to_unorm4x8", + Mf::Pack2x16snorm => "pack_float_to_snorm2x16", + Mf::Pack2x16unorm => "pack_float_to_unorm2x16", Mf::Pack2x16float => "", // data unpacking Mf::Unpack4x8snorm => "unpack_snorm4x8_to_float", diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index b0c76ff82..05574f717 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -24,13 +24,13 @@ kernel void main_( f2_ = metal::float2(0.0); f4_ = metal::float4(0.0); metal::float4 _e28 = f4_; - u = metal::pack_float_to_unorm4x8(_e28); + u = metal::pack_float_to_snorm4x8(_e28); metal::float4 _e30 = f4_; - u = metal::pack_float_to_snorm4x8(_e30); + u = metal::pack_float_to_unorm4x8(_e30); metal::float2 _e32 = f2_; - u = metal::pack_float_to_unorm2x16(_e32); + u = metal::pack_float_to_snorm2x16(_e32); metal::float2 _e34 = f2_; - u = metal::pack_float_to_snorm2x16(_e34); + u = metal::pack_float_to_unorm2x16(_e34); metal::float2 _e36 = f2_; u = as_type(half2(_e36)); metal::uint _e38 = u; From 8003e3e30abfcafb04a3f388750c6f001d125609 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 3 Jan 2022 12:41:20 -0500 Subject: [PATCH 1509/2212] Validate structure resource types --- src/valid/interface.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 1fabe5f3b..72c6561ab 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -355,13 +355,7 @@ impl super::Validator { true, ) } - crate::StorageClass::Handle => { - match types[var.ty].inner { - crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => {} - _ => return Err(GlobalVariableError::InvalidType), - }; - (TypeFlags::empty(), true) - } + crate::StorageClass::Handle => (TypeFlags::empty(), true), crate::StorageClass::Private | crate::StorageClass::WorkGroup => { (TypeFlags::DATA | TypeFlags::SIZED, false) } @@ -378,6 +372,16 @@ impl super::Validator { } }; + let is_handle = var.class == crate::StorageClass::Handle; + let good_type = match types[var.ty].inner { + crate::TypeInner::Struct { .. } => !is_handle, + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => is_handle, + _ => false, + }; + if is_resource && !good_type { + return Err(GlobalVariableError::InvalidType); + } + if !type_info.flags.contains(required_type_flags) { return Err(GlobalVariableError::MissingTypeFlags { seen: type_info.flags, From 79233ba5e5202abf23a7d084f500ed4c8fb4eb37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 3 Jan 2022 22:07:11 +0000 Subject: [PATCH 1510/2212] glsl-out: Fix array constants constructor --- src/back/glsl/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ada2ea676..eee1b34c2 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1343,6 +1343,9 @@ impl<'a, W: Write> Writer<'a, W> { // `type(components)` where `components` is a comma separated list of constants crate::ConstantInner::Composite { ty, ref components } => { self.write_type(ty)?; + if let TypeInner::Array { size, .. } = self.module.types[ty].inner { + self.write_array_size(size)?; + } write!(self.out, "(")?; // Write the comma separated constants From 32205e3097d2ae447e545eba3a1210df075f7c73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 3 Jan 2022 22:08:00 +0000 Subject: [PATCH 1511/2212] glsl-out: write array initializers --- src/back/glsl/mod.rs | 34 ++++++++++++++++++++++++++- tests/out/glsl/access.foo.Vertex.glsl | 2 +- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index eee1b34c2..09cb1d7f0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -90,6 +90,16 @@ impl crate::StorageClass { _ => false, } } + + /// Whether a variable with this storage class can be initialized + fn initializable(&self) -> bool { + match *self { + crate::StorageClass::WorkGroup + | crate::StorageClass::Uniform + | crate::StorageClass::Storage { .. } => false, + _ => true, + } + } } //Note: similar to `back/spv/helpers.rs` @@ -941,7 +951,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_array_size(size)?; } - if is_value_init_supported(self.module, global.ty) { + if global.class.initializable() && is_value_init_supported(self.module, global.ty) { write!(self.out, " = ")?; if let Some(init) = global.init { self.write_constant(init)?; @@ -2770,6 +2780,25 @@ impl<'a, W: Write> Writer<'a, W> { self.write_zero_init_scalar(crate::ScalarKind::Float)?; write!(self.out, ")")?; } + TypeInner::Array { base, size, .. } => { + let count = match size + .to_indexable_length(self.module) + .expect("Bad array size") + { + proc::IndexableLength::Known(count) => count, + proc::IndexableLength::Dynamic => return Ok(()), + }; + self.write_type(base)?; + self.write_array_size(size)?; + write!(self.out, "(")?; + for _ in 1..count { + self.write_zero_init_value(base)?; + write!(self.out, ", ")?; + } + // write last parameter without comma and space + self.write_zero_init_value(base)?; + write!(self.out, ")")?; + } _ => {} // TODO: } @@ -3054,6 +3083,9 @@ fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { fn is_value_init_supported(module: &crate::Module, ty: Handle) -> bool { match module.types[ty].inner { TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => true, + TypeInner::Array { base, size, .. } => { + size != crate::ArraySize::Dynamic && is_value_init_supported(module, base) + } _ => false, } } diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index 9b24f6740..efac04148 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -20,7 +20,7 @@ float read_from_private(inout float foo_2) { void main() { uint vi = uint(gl_VertexID); float foo_1 = 0.0; - int c[5]; + int c[5] = int[5](0, 0, 0, 0, 0); float baz = foo_1; foo_1 = 1.0; mat4x4 matrix = _group_0_binding_0_vs.matrix; From b9c489311263c43350b1c8c94cc2bca491bfe75d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 3 Jan 2022 22:37:01 +0000 Subject: [PATCH 1512/2212] glsl-out: Write struct initializers --- src/back/glsl/mod.rs | 14 ++++++++++++++ tests/out/glsl/interpolate.vert_main.Vertex.glsl | 2 +- tests/out/glsl/operators.main.Compute.glsl | 2 +- tests/out/glsl/quad-vert.main.Vertex.glsl | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 09cb1d7f0..d26dce9af 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2799,6 +2799,17 @@ impl<'a, W: Write> Writer<'a, W> { self.write_zero_init_value(base)?; write!(self.out, ")")?; } + TypeInner::Struct { ref members, .. } => { + let name = &self.names[&NameKey::Type(ty)]; + write!(self.out, "{}(", name)?; + for (i, member) in members.iter().enumerate() { + self.write_zero_init_value(member.ty)?; + if i != members.len().saturating_sub(1) { + write!(self.out, ", ")?; + } + } + write!(self.out, ")")?; + } _ => {} // TODO: } @@ -3086,6 +3097,9 @@ fn is_value_init_supported(module: &crate::Module, ty: Handle) -> b TypeInner::Array { base, size, .. } => { size != crate::ArraySize::Dynamic && is_value_init_supported(module, base) } + TypeInner::Struct { ref members, .. } => members + .iter() + .all(|member| is_value_init_supported(module, member.ty)), _ => false, } } diff --git a/tests/out/glsl/interpolate.vert_main.Vertex.glsl b/tests/out/glsl/interpolate.vert_main.Vertex.glsl index 588b72ac6..ea2920f86 100644 --- a/tests/out/glsl/interpolate.vert_main.Vertex.glsl +++ b/tests/out/glsl/interpolate.vert_main.Vertex.glsl @@ -18,7 +18,7 @@ smooth centroid out float _vs2fs_location5; smooth sample out float _vs2fs_location6; void main() { - FragmentInput out_; + FragmentInput out_ = FragmentInput(vec4(0.0, 0.0, 0.0, 0.0), 0u, 0.0, vec2(0.0, 0.0), vec3(0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), 0.0, 0.0); out_.position = vec4(2.0, 4.0, 5.0, 6.0); out_.flat_ = 8u; out_.linear = 27.0; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 10773041f..d4ad69104 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -42,7 +42,7 @@ vec3 bool_cast(vec3 x) { } float constructors() { - Foo foo; + Foo foo = Foo(vec4(0.0, 0.0, 0.0, 0.0), 0); foo = Foo(vec4(1.0), 1); mat2x2 mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); mat4x4 mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index d3c740e05..c5a98c7cd 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -17,7 +17,7 @@ vec2 v_uv = vec2(0.0, 0.0); vec2 a_uv_1 = vec2(0.0, 0.0); -gen_gl_PerVertex perVertexStruct; +gen_gl_PerVertex perVertexStruct = gen_gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), 1.0, float[1](0.0), float[1](0.0)); vec2 a_pos_1 = vec2(0.0, 0.0); From 743d058b49d019efd3f92d9bcc81b0ba3b0861f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 4 Jan 2022 13:48:13 +0000 Subject: [PATCH 1513/2212] glsl-out: Use constructors shorthand for zero init --- src/back/glsl/mod.rs | 16 ++-------------- tests/out/glsl/bits.main.Compute.glsl | 16 ++++++++-------- tests/out/glsl/boids.main.Compute.glsl | 14 +++++++------- tests/out/glsl/interpolate.vert_main.Vertex.glsl | 2 +- tests/out/glsl/operators.main.Compute.glsl | 2 +- tests/out/glsl/quad-vert.main.Vertex.glsl | 6 +++--- 6 files changed, 22 insertions(+), 34 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index d26dce9af..72b31d459 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2756,27 +2756,15 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Scalar { kind, .. } => { self.write_zero_init_scalar(kind)?; } - TypeInner::Vector { size, kind, .. } => { + TypeInner::Vector { kind, .. } => { self.write_value_type(inner)?; write!(self.out, "(")?; - for _ in 1..(size as usize) { - self.write_zero_init_scalar(kind)?; - write!(self.out, ", ")?; - } - // write last parameter without comma and space self.write_zero_init_scalar(kind)?; write!(self.out, ")")?; } - TypeInner::Matrix { columns, rows, .. } => { - let number_of_components = (columns as usize) * (rows as usize); + TypeInner::Matrix { .. } => { self.write_value_type(inner)?; write!(self.out, "(")?; - for _ in 1..number_of_components { - // IR supports only float matrix - self.write_zero_init_scalar(crate::ScalarKind::Float)?; - write!(self.out, ", ")?; - } - // write last parameter without comma and space self.write_zero_init_scalar(crate::ScalarKind::Float)?; write!(self.out, ")")?; } diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl index dd44101be..9cb276a9c 100644 --- a/tests/out/glsl/bits.main.Compute.glsl +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -8,15 +8,15 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; void main() { int i = 0; - ivec2 i2_ = ivec2(0, 0); - ivec3 i3_ = ivec3(0, 0, 0); - ivec4 i4_ = ivec4(0, 0, 0, 0); + ivec2 i2_ = ivec2(0); + ivec3 i3_ = ivec3(0); + ivec4 i4_ = ivec4(0); uint u = 0u; - uvec2 u2_ = uvec2(0u, 0u); - uvec3 u3_ = uvec3(0u, 0u, 0u); - uvec4 u4_ = uvec4(0u, 0u, 0u, 0u); - vec2 f2_ = vec2(0.0, 0.0); - vec4 f4_ = vec4(0.0, 0.0, 0.0, 0.0); + uvec2 u2_ = uvec2(0u); + uvec3 u3_ = uvec3(0u); + uvec4 u4_ = uvec4(0u); + vec2 f2_ = vec2(0.0); + vec4 f4_ = vec4(0.0); i2_ = ivec2(0); i3_ = ivec3(0); i4_ = ivec4(0); diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 5ebd69f5f..e438ded42 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -31,15 +31,15 @@ layout(std430) buffer Particles_block_2Compute { void main() { uvec3 global_invocation_id = gl_GlobalInvocationID; - vec2 vPos = vec2(0.0, 0.0); - vec2 vVel = vec2(0.0, 0.0); - vec2 cMass = vec2(0.0, 0.0); - vec2 cVel = vec2(0.0, 0.0); - vec2 colVel = vec2(0.0, 0.0); + vec2 vPos = vec2(0.0); + vec2 vVel = vec2(0.0); + vec2 cMass = vec2(0.0); + vec2 cVel = vec2(0.0); + vec2 colVel = vec2(0.0); int cMassCount = 0; int cVelCount = 0; - vec2 pos = vec2(0.0, 0.0); - vec2 vel = vec2(0.0, 0.0); + vec2 pos = vec2(0.0); + vec2 vel = vec2(0.0); uint i = 0u; uint index = global_invocation_id.x; if ((index >= 1500u)) { diff --git a/tests/out/glsl/interpolate.vert_main.Vertex.glsl b/tests/out/glsl/interpolate.vert_main.Vertex.glsl index ea2920f86..1c9ea718d 100644 --- a/tests/out/glsl/interpolate.vert_main.Vertex.glsl +++ b/tests/out/glsl/interpolate.vert_main.Vertex.glsl @@ -18,7 +18,7 @@ smooth centroid out float _vs2fs_location5; smooth sample out float _vs2fs_location6; void main() { - FragmentInput out_ = FragmentInput(vec4(0.0, 0.0, 0.0, 0.0), 0u, 0.0, vec2(0.0, 0.0), vec3(0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), 0.0, 0.0); + FragmentInput out_ = FragmentInput(vec4(0.0), 0u, 0.0, vec2(0.0), vec3(0.0), vec4(0.0), 0.0, 0.0); out_.position = vec4(2.0, 4.0, 5.0, 6.0); out_.flat_ = 8u; out_.linear = 27.0; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index d4ad69104..58dac4547 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -42,7 +42,7 @@ vec3 bool_cast(vec3 x) { } float constructors() { - Foo foo = Foo(vec4(0.0, 0.0, 0.0, 0.0), 0); + Foo foo = Foo(vec4(0.0), 0); foo = Foo(vec4(1.0), 1); mat2x2 mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); mat4x4 mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index c5a98c7cd..082196af5 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -13,13 +13,13 @@ struct type_9 { vec2 member; vec4 gen_gl_Position; }; -vec2 v_uv = vec2(0.0, 0.0); +vec2 v_uv = vec2(0.0); -vec2 a_uv_1 = vec2(0.0, 0.0); +vec2 a_uv_1 = vec2(0.0); gen_gl_PerVertex perVertexStruct = gen_gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), 1.0, float[1](0.0), float[1](0.0)); -vec2 a_pos_1 = vec2(0.0, 0.0); +vec2 a_pos_1 = vec2(0.0); layout(location = 1) in vec2 _p2vs_location1; layout(location = 0) in vec2 _p2vs_location0; From 9a0f1b395c9ba094c068bc59ff8704ec62bc8b8f Mon Sep 17 00:00:00 2001 From: Ibiyemi Abiodun Date: Tue, 4 Jan 2022 13:21:44 -0500 Subject: [PATCH 1514/2212] Add a way to emit errors with a path (#1640) * Add a way to emit errors with a path I am using `naga` in my build script to validate all of my shaders, and it would be nice to be able to display the file path inside of the diagnostic, so I added a method `emit_to_stderr_with_path` to `naga::front::wgsl::ParserError`. * change path to &str * fix rustfmt --- src/front/wgsl/mod.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index a58f63d42..93cdf2902 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1173,7 +1173,12 @@ impl ParseError { /// Emits a summary of the error to standard error stream. pub fn emit_to_stderr(&self, source: &str) { - let files = SimpleFile::new("wgsl", source); + self.emit_to_stderr_with_path(source, "wgsl") + } + + /// Emits a summary of the error to standard error stream. + pub fn emit_to_stderr_with_path(&self, source: &str, path: &str) { + let files = SimpleFile::new(path, source); let config = codespan_reporting::term::Config::default(); let writer = StandardStream::stderr(ColorChoice::Always); term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) From a1e8805360eb20587800dd56ff07f2fda108fed8 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 4 Jan 2022 11:42:52 -0800 Subject: [PATCH 1515/2212] Use ExpressionContext::resolve_type where appropriate. --- src/back/msl/writer.rs | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 3436ac0ec..ba75473f5 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -616,7 +616,7 @@ impl Writer { context: &ExpressionContext, ) -> BackendResult { // coordinates in IR are int, but Metal expects uint - let size_str = match *context.info[expr].ty.inner_with(&context.module.types) { + let size_str = match *context.resolve_type(expr) { crate::TypeInner::Scalar { .. } => "", crate::TypeInner::Vector { size, .. } => back::vector_size_str(size), _ => return Err(Error::Validation), @@ -1401,7 +1401,7 @@ impl Writer { crate::Expression::AccessIndex { base, index } => { // Don't try to check indices into structs. Validation already took // care of them, and index::needs_guard doesn't handle that case. - let mut base_inner = context.info[base].ty.inner_with(&context.module.types); + let mut base_inner = context.resolve_type(base); if let crate::TypeInner::Pointer { base, .. } = *base_inner { base_inner = &context.module.types[base].inner; } @@ -1475,7 +1475,7 @@ impl Writer { ) -> BackendResult { match context.function.expressions[chain] { crate::Expression::Access { base, index } => { - let mut base_ty = context.info[base].ty.inner_with(&context.module.types); + let mut base_ty = context.resolve_type(base); // Look through any pointers to see what we're really indexing. if let crate::TypeInner::Pointer { base, class: _ } = *base_ty { @@ -2172,21 +2172,20 @@ impl Writer { level: back::Level, context: &StatementContext, ) -> BackendResult { - let pointer_info = &context.expression.info[pointer]; - let (array_size, is_atomic) = - match *pointer_info.ty.inner_with(&context.expression.module.types) { - crate::TypeInner::Pointer { base, .. } => { - match context.expression.module.types[base].inner { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(ch), - .. - } => (Some(ch), false), - crate::TypeInner::Atomic { .. } => (None, true), - _ => (None, false), - } + let pointer_inner = context.expression.resolve_type(pointer); + let (array_size, is_atomic) = match *pointer_inner { + crate::TypeInner::Pointer { base, .. } => { + match context.expression.module.types[base].inner { + crate::TypeInner::Array { + size: crate::ArraySize::Constant(ch), + .. + } => (Some(ch), false), + crate::TypeInner::Atomic { .. } => (None, true), + _ => (None, false), } - _ => (None, false), - }; + } + _ => (None, false), + }; // we can't assign fixed-size arrays if let Some(const_handle) = array_size { From 53eeb654aafde4be239b99faff68f3521c465863 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 3 Jan 2022 17:34:55 -0800 Subject: [PATCH 1516/2212] [msl-out] Don't give level in texture1d accesses. Fixes #1642. Since 1d textures cannot have mipmaps, MSL requires that the `level` argument to texel accesses and dimension queries be a constexpr 0. For our purposes, just omit the level argument altogether. --- src/back/msl/writer.rs | 19 +- tests/in/image.wgsl | 6 +- tests/out/glsl/image.main.Compute.glsl | 5 +- tests/out/glsl/image.queries.Vertex.glsl | 1 + tests/out/hlsl/image.hlsl | 12 +- tests/out/msl/image.msl | 15 +- tests/out/spv/image.spvasm | 733 ++++++++++++----------- tests/out/wgsl/image.wgsl | 6 +- 8 files changed, 425 insertions(+), 372 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ba75473f5..55f72b630 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -582,7 +582,10 @@ impl Writer { match dim { crate::ImageDimension::D1 => { write!(self.out, "int(")?; - self.put_image_query(image, "width", level, context)?; + // Since 1D textures never have mipmaps, MSL requires that the + // `level` argument be a constexpr 0. It's simplest for us just + // to omit the level entirely. + self.put_image_query(image, "width", None, context)?; write!(self.out, ")")?; } crate::ImageDimension::D2 => { @@ -996,8 +999,18 @@ impl Writer { self.put_expression(expr, context, true)?; } if let Some(index) = index { - write!(self.out, ", ")?; - self.put_expression(index, context, true)?; + // Metal requires that the `level` argument to + // `texture1d::read` be a constexpr equal to zero. + if let crate::TypeInner::Image { + dim: crate::ImageDimension::D1, + .. + } = *context.resolve_type(image) + { + // The argument defaults to zero. + } else { + write!(self.out, ", ")?; + self.put_expression(index, context, true)? + } } write!(self.out, ")")?; } diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 8d27b8820..0e2a735c3 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -10,6 +10,8 @@ var image_storage_src: texture_storage_2d; var image_array_src: texture_2d_array; [[group(0), binding(6)]] var image_dup_src: texture_storage_1d; // for #1307 +[[group(0), binding(7)]] +var image_1d_src: texture_1d; [[group(0), binding(2)]] var image_dst: texture_storage_1d; @@ -25,7 +27,8 @@ fn main( let value2 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); let value4 = textureLoad(image_storage_src, itc); let value5 = textureLoad(image_array_src, itc, i32(local_id.z), i32(local_id.z) + 1); - textureStore(image_dst, itc.x, value1 + value2 + value4 + value5); + let value6 = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z)); + textureStore(image_dst, itc.x, value1 + value2 + value4 + value5 + value6); } [[stage(compute), workgroup_size(16, 1, 1)]] @@ -55,6 +58,7 @@ var image_aa: texture_multisampled_2d; [[stage(vertex)]] fn queries() -> [[builtin(position)]] vec4 { let dim_1d = textureDimensions(image_1d); + let dim_1d_lod = textureDimensions(image_1d, i32(dim_1d)); let dim_2d = textureDimensions(image_2d); let dim_2d_lod = textureDimensions(image_2d, 1); let dim_2d_array = textureDimensions(image_2d_array); diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl index 3258e65aa..08c6a32e9 100644 --- a/tests/out/glsl/image.main.Compute.glsl +++ b/tests/out/glsl/image.main.Compute.glsl @@ -14,6 +14,8 @@ layout(rgba8ui) readonly uniform highp uimage2D _group_0_binding_1_cs; uniform highp usampler2DArray _group_0_binding_5_cs; +uniform highp usampler2D _group_0_binding_7_cs; + layout(r32ui) writeonly uniform highp uimage2D _group_0_binding_2_cs; @@ -25,7 +27,8 @@ void main() { uvec4 value2_ = texelFetch(_group_0_binding_3_cs, itc, int(local_id.z)); uvec4 value4_ = imageLoad(_group_0_binding_1_cs, itc); uvec4 value5_ = texelFetch(_group_0_binding_5_cs, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); - imageStore(_group_0_binding_2_cs, ivec2(itc.x, 0.0), (((value1_ + value2_) + value4_) + value5_)); + uvec4 value6_ = texelFetch(_group_0_binding_7_cs, ivec2(int(local_id.x), 0.0), int(local_id.z)); + imageStore(_group_0_binding_2_cs, ivec2(itc.x, 0.0), ((((value1_ + value2_) + value4_) + value5_) + value6_)); return; } diff --git a/tests/out/glsl/image.queries.Vertex.glsl b/tests/out/glsl/image.queries.Vertex.glsl index e5ff9492a..d95faea9f 100644 --- a/tests/out/glsl/image.queries.Vertex.glsl +++ b/tests/out/glsl/image.queries.Vertex.glsl @@ -19,6 +19,7 @@ uniform highp sampler3D _group_0_binding_5_vs; void main() { int dim_1d = textureSize(_group_0_binding_0_vs, 0).x; + int dim_1d_lod = textureSize(_group_0_binding_0_vs, int(dim_1d)).x; ivec2 dim_2d = textureSize(_group_0_binding_1_vs, 0).xy; ivec2 dim_2d_lod = textureSize(_group_0_binding_1_vs, 1).xy; ivec2 dim_2d_array = textureSize(_group_0_binding_2_vs, 0).xy; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 1d36273f4..d75cf327b 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -5,6 +5,7 @@ Texture2DMS image_depth_multisampled_src : register(t4); RWTexture2D image_storage_src : register(u1); Texture2DArray image_array_src : register(t5); RWTexture1D image_dup_src : register(u6); +Texture1D image_1d_src : register(t7); RWTexture1D image_dst : register(u2); Texture1D image_1d : register(t0); Texture2D image_2d : register(t1); @@ -33,7 +34,8 @@ void main(uint3 local_id : SV_GroupThreadID) uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z)); uint4 value4_ = image_storage_src.Load(itc); uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); - image_dst[itc.x] = (((value1_ + value2_) + value4_) + value5_); + uint4 value6_ = image_1d_src.Load(int2(int(local_id.x), int(local_id.z))); + image_dst[itc.x] = ((((value1_ + value2_) + value4_) + value5_) + value6_); return; } @@ -54,6 +56,13 @@ int NagaDimensions1D(Texture1D tex) return ret.x; } +int NagaMipDimensions1D(Texture1D tex, uint mip_level) +{ + uint4 ret; + tex.GetDimensions(mip_level, ret.x, ret.y); + return ret.x; +} + int2 NagaDimensions2D(Texture2D tex) { uint4 ret; @@ -127,6 +136,7 @@ int3 NagaMipDimensions3D(Texture3D tex, uint mip_level) float4 queries() : SV_Position { int dim_1d = NagaDimensions1D(image_1d); + int dim_1d_lod = NagaMipDimensions1D(image_1d, int(dim_1d)); int2 dim_2d = NagaDimensions2D(image_2d); int2 dim_2d_lod = NagaMipDimensions2D(image_2d, 1); int2 dim_2d_array = NagaDimensions2DArray(image_2d_array); diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index cbe68c649..68d52340f 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -2,7 +2,7 @@ #include #include -constant metal::int2 const_type_8_ = {3, 1}; +constant metal::int2 const_type_9_ = {3, 1}; struct main_Input { }; @@ -12,6 +12,7 @@ kernel void main_( , metal::texture2d_ms image_multisampled_src [[user(fake0)]] , metal::texture2d image_storage_src [[user(fake0)]] , metal::texture2d_array image_array_src [[user(fake0)]] +, metal::texture1d image_1d_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { metal::int2 dim = int2(image_storage_src.get_width(), image_storage_src.get_height()); @@ -20,7 +21,8 @@ kernel void main_( metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); - image_dst.write(((value1_ + value2_) + value4_) + value5_, metal::uint(itc.x)); + metal::uint4 value6_ = image_1d_src.read(metal::uint(static_cast(local_id.x))); + image_dst.write((((value1_ + value2_) + value4_) + value5_) + value6_, metal::uint(itc.x)); return; } @@ -53,6 +55,7 @@ vertex queriesOutput queries( , metal::texture3d image_3d [[user(fake0)]] ) { int dim_1d = int(image_1d.get_width()); + int dim_1d_lod = int(image_1d.get_width()); metal::int2 dim_2d = int2(image_2d.get_width(), image_2d.get_height()); metal::int2 dim_2d_lod = int2(image_2d.get_width(1), image_2d.get_height(1)); metal::int2 dim_2d_array = int2(image_2d_array.get_width(), image_2d_array.get_height()); @@ -103,9 +106,9 @@ fragment sampleOutput sample( metal::float2 tc = metal::float2(0.5); metal::float4 s1d = image_1d.sample(sampler_reg, tc.x); metal::float4 s2d = image_2d.sample(sampler_reg, tc); - metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type_8_); + metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type_9_); metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); - metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_8_); + metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_9_); return sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset }; } @@ -135,9 +138,9 @@ fragment gatherOutput gather( ) { metal::float2 tc_2 = metal::float2(0.5); metal::float4 s2d_1 = image_2d.gather(sampler_reg, tc_2, int2(0), metal::component::y); - metal::float4 s2d_offset_1 = image_2d.gather(sampler_reg, tc_2, const_type_8_, metal::component::w); + metal::float4 s2d_offset_1 = image_2d.gather(sampler_reg, tc_2, const_type_9_, metal::component::w); metal::float4 s2d_depth_1 = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5); - metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, const_type_8_); + metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, const_type_9_); return gatherOutput { ((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset }; } diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 82ab063c9..3063cfb4e 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 280 +; Bound: 292 OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D @@ -9,93 +9,96 @@ OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %69 "main" %66 -OpEntryPoint GLCompute %107 "depth_load" %105 -OpEntryPoint Vertex %128 "queries" %126 -OpEntryPoint Vertex %176 "levels_queries" %175 -OpEntryPoint Fragment %205 "sample" %204 -OpEntryPoint Fragment %232 "sample_comparison" %230 -OpEntryPoint Fragment %246 "gather" %245 -OpEntryPoint Fragment %268 "depth_no_comparison" %267 -OpExecutionMode %69 LocalSize 16 1 1 -OpExecutionMode %107 LocalSize 16 1 1 -OpExecutionMode %205 OriginUpperLeft -OpExecutionMode %232 OriginUpperLeft -OpExecutionMode %246 OriginUpperLeft -OpExecutionMode %268 OriginUpperLeft +OpEntryPoint GLCompute %72 "main" %69 +OpEntryPoint GLCompute %117 "depth_load" %115 +OpEntryPoint Vertex %138 "queries" %136 +OpEntryPoint Vertex %188 "levels_queries" %187 +OpEntryPoint Fragment %217 "sample" %216 +OpEntryPoint Fragment %244 "sample_comparison" %242 +OpEntryPoint Fragment %258 "gather" %257 +OpEntryPoint Fragment %280 "depth_no_comparison" %279 +OpExecutionMode %72 LocalSize 16 1 1 +OpExecutionMode %117 LocalSize 16 1 1 +OpExecutionMode %217 OriginUpperLeft +OpExecutionMode %244 OriginUpperLeft +OpExecutionMode %258 OriginUpperLeft +OpExecutionMode %280 OriginUpperLeft OpSource GLSL 450 -OpName %31 "image_mipmapped_src" -OpName %33 "image_multisampled_src" -OpName %35 "image_depth_multisampled_src" -OpName %37 "image_storage_src" -OpName %39 "image_array_src" -OpName %41 "image_dup_src" -OpName %43 "image_dst" -OpName %45 "image_1d" -OpName %47 "image_2d" -OpName %49 "image_2d_array" -OpName %51 "image_cube" -OpName %53 "image_cube_array" -OpName %55 "image_3d" -OpName %57 "image_aa" -OpName %59 "sampler_reg" -OpName %61 "sampler_cmp" -OpName %63 "image_2d_depth" -OpName %66 "local_id" -OpName %69 "main" -OpName %105 "local_id" -OpName %107 "depth_load" -OpName %128 "queries" -OpName %176 "levels_queries" -OpName %205 "sample" -OpName %232 "sample_comparison" -OpName %246 "gather" -OpName %268 "depth_no_comparison" -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 0 -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 3 -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 4 -OpDecorate %37 NonWritable -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 1 -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 5 -OpDecorate %41 NonWritable -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 6 -OpDecorate %43 NonReadable -OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 2 -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 0 -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 1 -OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 2 -OpDecorate %51 DescriptorSet 0 -OpDecorate %51 Binding 3 -OpDecorate %53 DescriptorSet 0 -OpDecorate %53 Binding 4 -OpDecorate %55 DescriptorSet 0 -OpDecorate %55 Binding 5 -OpDecorate %57 DescriptorSet 0 -OpDecorate %57 Binding 6 -OpDecorate %59 DescriptorSet 1 -OpDecorate %59 Binding 0 -OpDecorate %61 DescriptorSet 1 -OpDecorate %61 Binding 1 -OpDecorate %63 DescriptorSet 1 -OpDecorate %63 Binding 2 -OpDecorate %66 BuiltIn LocalInvocationId -OpDecorate %105 BuiltIn LocalInvocationId -OpDecorate %126 BuiltIn Position -OpDecorate %175 BuiltIn Position -OpDecorate %204 Location 0 -OpDecorate %230 Location 0 -OpDecorate %245 Location 0 -OpDecorate %267 Location 0 +OpName %32 "image_mipmapped_src" +OpName %34 "image_multisampled_src" +OpName %36 "image_depth_multisampled_src" +OpName %38 "image_storage_src" +OpName %40 "image_array_src" +OpName %42 "image_dup_src" +OpName %44 "image_1d_src" +OpName %46 "image_dst" +OpName %48 "image_1d" +OpName %50 "image_2d" +OpName %52 "image_2d_array" +OpName %54 "image_cube" +OpName %56 "image_cube_array" +OpName %58 "image_3d" +OpName %60 "image_aa" +OpName %62 "sampler_reg" +OpName %64 "sampler_cmp" +OpName %66 "image_2d_depth" +OpName %69 "local_id" +OpName %72 "main" +OpName %115 "local_id" +OpName %117 "depth_load" +OpName %138 "queries" +OpName %188 "levels_queries" +OpName %217 "sample" +OpName %244 "sample_comparison" +OpName %258 "gather" +OpName %280 "depth_no_comparison" +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 0 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 3 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 4 +OpDecorate %38 NonWritable +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 1 +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 5 +OpDecorate %42 NonWritable +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 6 +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 7 +OpDecorate %46 NonReadable +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 2 +OpDecorate %48 DescriptorSet 0 +OpDecorate %48 Binding 0 +OpDecorate %50 DescriptorSet 0 +OpDecorate %50 Binding 1 +OpDecorate %52 DescriptorSet 0 +OpDecorate %52 Binding 2 +OpDecorate %54 DescriptorSet 0 +OpDecorate %54 Binding 3 +OpDecorate %56 DescriptorSet 0 +OpDecorate %56 Binding 4 +OpDecorate %58 DescriptorSet 0 +OpDecorate %58 Binding 5 +OpDecorate %60 DescriptorSet 0 +OpDecorate %60 Binding 6 +OpDecorate %62 DescriptorSet 1 +OpDecorate %62 Binding 0 +OpDecorate %64 DescriptorSet 1 +OpDecorate %64 Binding 1 +OpDecorate %66 DescriptorSet 1 +OpDecorate %66 Binding 2 +OpDecorate %69 BuiltIn LocalInvocationId +OpDecorate %115 BuiltIn LocalInvocationId +OpDecorate %136 BuiltIn Position +OpDecorate %187 BuiltIn Position +OpDecorate %216 Location 0 +OpDecorate %242 Location 0 +OpDecorate %257 Location 0 +OpDecorate %279 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -112,297 +115,309 @@ OpDecorate %267 Location 0 %15 = OpTypeImage %12 2D 0 0 0 2 Rgba8ui %16 = OpTypeImage %12 2D 0 1 0 1 Unknown %17 = OpTypeImage %12 1D 0 0 0 2 R32ui -%18 = OpTypeVector %12 3 -%19 = OpTypeVector %4 2 -%20 = OpTypeImage %8 1D 0 0 0 1 Unknown -%21 = OpTypeImage %8 2D 0 0 0 1 Unknown -%22 = OpTypeImage %8 2D 0 1 0 1 Unknown -%23 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%24 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%25 = OpTypeImage %8 3D 0 0 0 1 Unknown -%26 = OpTypeImage %8 2D 0 0 1 1 Unknown -%27 = OpTypeVector %8 4 -%28 = OpTypeSampler -%29 = OpTypeImage %8 2D 1 0 0 1 Unknown -%30 = OpConstantComposite %19 %10 %6 -%32 = OpTypePointer UniformConstant %11 -%31 = OpVariable %32 UniformConstant -%34 = OpTypePointer UniformConstant %13 -%33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %14 -%35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %15 -%37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %16 -%39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %17 -%41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %17 -%43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %20 -%45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %21 -%47 = OpVariable %48 UniformConstant -%50 = OpTypePointer UniformConstant %22 -%49 = OpVariable %50 UniformConstant -%52 = OpTypePointer UniformConstant %23 -%51 = OpVariable %52 UniformConstant -%54 = OpTypePointer UniformConstant %24 -%53 = OpVariable %54 UniformConstant -%56 = OpTypePointer UniformConstant %25 -%55 = OpVariable %56 UniformConstant -%58 = OpTypePointer UniformConstant %26 -%57 = OpVariable %58 UniformConstant -%60 = OpTypePointer UniformConstant %28 -%59 = OpVariable %60 UniformConstant -%62 = OpTypePointer UniformConstant %28 -%61 = OpVariable %62 UniformConstant -%64 = OpTypePointer UniformConstant %29 -%63 = OpVariable %64 UniformConstant -%67 = OpTypePointer Input %18 -%66 = OpVariable %67 Input -%70 = OpTypeFunction %2 -%78 = OpTypeVector %12 2 -%86 = OpTypeVector %12 4 -%97 = OpTypeVector %4 3 -%105 = OpVariable %67 Input -%127 = OpTypePointer Output %27 -%126 = OpVariable %127 Output -%136 = OpConstant %12 0 -%175 = OpVariable %127 Output -%204 = OpVariable %127 Output -%210 = OpTypeVector %8 2 -%213 = OpTypeSampledImage %20 -%216 = OpTypeSampledImage %21 -%231 = OpTypePointer Output %8 -%230 = OpVariable %231 Output -%237 = OpTypeSampledImage %29 -%242 = OpConstant %8 0.0 -%245 = OpVariable %127 Output -%255 = OpConstant %12 1 -%258 = OpConstant %12 3 -%267 = OpVariable %127 Output -%69 = OpFunction %2 None %70 -%65 = OpLabel -%68 = OpLoad %18 %66 -%71 = OpLoad %11 %31 -%72 = OpLoad %13 %33 -%73 = OpLoad %15 %37 -%74 = OpLoad %16 %39 -%75 = OpLoad %17 %43 -OpBranch %76 -%76 = OpLabel -%77 = OpImageQuerySize %19 %73 -%79 = OpVectorShuffle %78 %68 %68 0 1 -%80 = OpBitcast %19 %79 -%81 = OpIMul %19 %77 %80 -%82 = OpCompositeConstruct %19 %3 %5 -%83 = OpSMod %19 %81 %82 -%84 = OpCompositeExtract %12 %68 2 -%85 = OpBitcast %4 %84 -%87 = OpImageFetch %86 %71 %83 Lod %85 -%88 = OpCompositeExtract %12 %68 2 +%18 = OpTypeImage %12 1D 0 0 0 1 Unknown +%19 = OpTypeVector %12 3 +%20 = OpTypeVector %4 2 +%21 = OpTypeImage %8 1D 0 0 0 1 Unknown +%22 = OpTypeImage %8 2D 0 0 0 1 Unknown +%23 = OpTypeImage %8 2D 0 1 0 1 Unknown +%24 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%25 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%26 = OpTypeImage %8 3D 0 0 0 1 Unknown +%27 = OpTypeImage %8 2D 0 0 1 1 Unknown +%28 = OpTypeVector %8 4 +%29 = OpTypeSampler +%30 = OpTypeImage %8 2D 1 0 0 1 Unknown +%31 = OpConstantComposite %20 %10 %6 +%33 = OpTypePointer UniformConstant %11 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer UniformConstant %13 +%34 = OpVariable %35 UniformConstant +%37 = OpTypePointer UniformConstant %14 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %15 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %16 +%40 = OpVariable %41 UniformConstant +%43 = OpTypePointer UniformConstant %17 +%42 = OpVariable %43 UniformConstant +%45 = OpTypePointer UniformConstant %18 +%44 = OpVariable %45 UniformConstant +%47 = OpTypePointer UniformConstant %17 +%46 = OpVariable %47 UniformConstant +%49 = OpTypePointer UniformConstant %21 +%48 = OpVariable %49 UniformConstant +%51 = OpTypePointer UniformConstant %22 +%50 = OpVariable %51 UniformConstant +%53 = OpTypePointer UniformConstant %23 +%52 = OpVariable %53 UniformConstant +%55 = OpTypePointer UniformConstant %24 +%54 = OpVariable %55 UniformConstant +%57 = OpTypePointer UniformConstant %25 +%56 = OpVariable %57 UniformConstant +%59 = OpTypePointer UniformConstant %26 +%58 = OpVariable %59 UniformConstant +%61 = OpTypePointer UniformConstant %27 +%60 = OpVariable %61 UniformConstant +%63 = OpTypePointer UniformConstant %29 +%62 = OpVariable %63 UniformConstant +%65 = OpTypePointer UniformConstant %29 +%64 = OpVariable %65 UniformConstant +%67 = OpTypePointer UniformConstant %30 +%66 = OpVariable %67 UniformConstant +%70 = OpTypePointer Input %19 +%69 = OpVariable %70 Input +%73 = OpTypeFunction %2 +%82 = OpTypeVector %12 2 +%90 = OpTypeVector %12 4 +%101 = OpTypeVector %4 3 +%115 = OpVariable %70 Input +%137 = OpTypePointer Output %28 +%136 = OpVariable %137 Output +%146 = OpConstant %12 0 +%187 = OpVariable %137 Output +%216 = OpVariable %137 Output +%222 = OpTypeVector %8 2 +%225 = OpTypeSampledImage %21 +%228 = OpTypeSampledImage %22 +%243 = OpTypePointer Output %8 +%242 = OpVariable %243 Output +%249 = OpTypeSampledImage %30 +%254 = OpConstant %8 0.0 +%257 = OpVariable %137 Output +%267 = OpConstant %12 1 +%270 = OpConstant %12 3 +%279 = OpVariable %137 Output +%72 = OpFunction %2 None %73 +%68 = OpLabel +%71 = OpLoad %19 %69 +%74 = OpLoad %11 %32 +%75 = OpLoad %13 %34 +%76 = OpLoad %15 %38 +%77 = OpLoad %16 %40 +%78 = OpLoad %18 %44 +%79 = OpLoad %17 %46 +OpBranch %80 +%80 = OpLabel +%81 = OpImageQuerySize %20 %76 +%83 = OpVectorShuffle %82 %71 %71 0 1 +%84 = OpBitcast %20 %83 +%85 = OpIMul %20 %81 %84 +%86 = OpCompositeConstruct %20 %3 %5 +%87 = OpSMod %20 %85 %86 +%88 = OpCompositeExtract %12 %71 2 %89 = OpBitcast %4 %88 -%90 = OpImageFetch %86 %72 %83 Sample %89 -%91 = OpImageRead %86 %73 %83 -%92 = OpCompositeExtract %12 %68 2 +%91 = OpImageFetch %90 %74 %87 Lod %89 +%92 = OpCompositeExtract %12 %71 2 %93 = OpBitcast %4 %92 -%94 = OpCompositeExtract %12 %68 2 -%95 = OpBitcast %4 %94 -%96 = OpIAdd %4 %95 %6 -%98 = OpCompositeConstruct %97 %83 %93 -%99 = OpImageFetch %86 %74 %98 Lod %96 -%100 = OpCompositeExtract %4 %83 0 -%101 = OpIAdd %86 %87 %90 -%102 = OpIAdd %86 %101 %91 -%103 = OpIAdd %86 %102 %99 -OpImageWrite %75 %100 %103 +%94 = OpImageFetch %90 %75 %87 Sample %93 +%95 = OpImageRead %90 %76 %87 +%96 = OpCompositeExtract %12 %71 2 +%97 = OpBitcast %4 %96 +%98 = OpCompositeExtract %12 %71 2 +%99 = OpBitcast %4 %98 +%100 = OpIAdd %4 %99 %6 +%102 = OpCompositeConstruct %101 %87 %97 +%103 = OpImageFetch %90 %77 %102 Lod %100 +%104 = OpCompositeExtract %12 %71 0 +%105 = OpBitcast %4 %104 +%106 = OpCompositeExtract %12 %71 2 +%107 = OpBitcast %4 %106 +%108 = OpImageFetch %90 %78 %105 Lod %107 +%109 = OpCompositeExtract %4 %87 0 +%110 = OpIAdd %90 %91 %94 +%111 = OpIAdd %90 %110 %95 +%112 = OpIAdd %90 %111 %103 +%113 = OpIAdd %90 %112 %108 +OpImageWrite %79 %109 %113 OpReturn OpFunctionEnd -%107 = OpFunction %2 None %70 -%104 = OpLabel -%106 = OpLoad %18 %105 -%108 = OpLoad %14 %35 -%109 = OpLoad %15 %37 -%110 = OpLoad %17 %43 -OpBranch %111 -%111 = OpLabel -%112 = OpImageQuerySize %19 %109 -%113 = OpVectorShuffle %78 %106 %106 0 1 -%114 = OpBitcast %19 %113 -%115 = OpIMul %19 %112 %114 -%116 = OpCompositeConstruct %19 %3 %5 -%117 = OpSMod %19 %115 %116 -%118 = OpCompositeExtract %12 %106 2 -%119 = OpBitcast %4 %118 -%120 = OpImageFetch %27 %108 %117 Sample %119 -%121 = OpCompositeExtract %8 %120 0 -%122 = OpCompositeExtract %4 %117 0 -%123 = OpConvertFToU %12 %121 -%124 = OpCompositeConstruct %86 %123 %123 %123 %123 -OpImageWrite %110 %122 %124 +%117 = OpFunction %2 None %73 +%114 = OpLabel +%116 = OpLoad %19 %115 +%118 = OpLoad %14 %36 +%119 = OpLoad %15 %38 +%120 = OpLoad %17 %46 +OpBranch %121 +%121 = OpLabel +%122 = OpImageQuerySize %20 %119 +%123 = OpVectorShuffle %82 %116 %116 0 1 +%124 = OpBitcast %20 %123 +%125 = OpIMul %20 %122 %124 +%126 = OpCompositeConstruct %20 %3 %5 +%127 = OpSMod %20 %125 %126 +%128 = OpCompositeExtract %12 %116 2 +%129 = OpBitcast %4 %128 +%130 = OpImageFetch %28 %118 %127 Sample %129 +%131 = OpCompositeExtract %8 %130 0 +%132 = OpCompositeExtract %4 %127 0 +%133 = OpConvertFToU %12 %131 +%134 = OpCompositeConstruct %90 %133 %133 %133 %133 +OpImageWrite %120 %132 %134 OpReturn OpFunctionEnd -%128 = OpFunction %2 None %70 -%125 = OpLabel -%129 = OpLoad %20 %45 -%130 = OpLoad %21 %47 -%131 = OpLoad %22 %49 -%132 = OpLoad %23 %51 -%133 = OpLoad %24 %53 -%134 = OpLoad %25 %55 -OpBranch %135 +%138 = OpFunction %2 None %73 %135 = OpLabel -%137 = OpImageQuerySizeLod %4 %129 %136 -%138 = OpImageQuerySizeLod %19 %130 %136 -%139 = OpImageQuerySizeLod %19 %130 %6 -%140 = OpImageQuerySizeLod %97 %131 %136 -%141 = OpVectorShuffle %19 %140 %140 0 1 -%142 = OpImageQuerySizeLod %97 %131 %6 -%143 = OpVectorShuffle %19 %142 %142 0 1 -%144 = OpImageQuerySizeLod %19 %132 %136 -%145 = OpImageQuerySizeLod %19 %132 %6 -%146 = OpImageQuerySizeLod %97 %133 %136 -%147 = OpVectorShuffle %19 %146 %146 0 0 -%148 = OpImageQuerySizeLod %97 %133 %6 -%149 = OpVectorShuffle %19 %148 %148 0 0 -%150 = OpImageQuerySizeLod %97 %134 %136 -%151 = OpImageQuerySizeLod %97 %134 %6 -%152 = OpCompositeExtract %4 %138 1 -%153 = OpIAdd %4 %137 %152 -%154 = OpCompositeExtract %4 %139 1 -%155 = OpIAdd %4 %153 %154 -%156 = OpCompositeExtract %4 %141 1 -%157 = OpIAdd %4 %155 %156 -%158 = OpCompositeExtract %4 %143 1 -%159 = OpIAdd %4 %157 %158 -%160 = OpCompositeExtract %4 %144 1 -%161 = OpIAdd %4 %159 %160 -%162 = OpCompositeExtract %4 %145 1 -%163 = OpIAdd %4 %161 %162 -%164 = OpCompositeExtract %4 %147 1 -%165 = OpIAdd %4 %163 %164 -%166 = OpCompositeExtract %4 %149 1 +%139 = OpLoad %21 %48 +%140 = OpLoad %22 %50 +%141 = OpLoad %23 %52 +%142 = OpLoad %24 %54 +%143 = OpLoad %25 %56 +%144 = OpLoad %26 %58 +OpBranch %145 +%145 = OpLabel +%147 = OpImageQuerySizeLod %4 %139 %146 +%148 = OpBitcast %4 %147 +%149 = OpImageQuerySizeLod %4 %139 %148 +%150 = OpImageQuerySizeLod %20 %140 %146 +%151 = OpImageQuerySizeLod %20 %140 %6 +%152 = OpImageQuerySizeLod %101 %141 %146 +%153 = OpVectorShuffle %20 %152 %152 0 1 +%154 = OpImageQuerySizeLod %101 %141 %6 +%155 = OpVectorShuffle %20 %154 %154 0 1 +%156 = OpImageQuerySizeLod %20 %142 %146 +%157 = OpImageQuerySizeLod %20 %142 %6 +%158 = OpImageQuerySizeLod %101 %143 %146 +%159 = OpVectorShuffle %20 %158 %158 0 0 +%160 = OpImageQuerySizeLod %101 %143 %6 +%161 = OpVectorShuffle %20 %160 %160 0 0 +%162 = OpImageQuerySizeLod %101 %144 %146 +%163 = OpImageQuerySizeLod %101 %144 %6 +%164 = OpCompositeExtract %4 %150 1 +%165 = OpIAdd %4 %147 %164 +%166 = OpCompositeExtract %4 %151 1 %167 = OpIAdd %4 %165 %166 -%168 = OpCompositeExtract %4 %150 2 +%168 = OpCompositeExtract %4 %153 1 %169 = OpIAdd %4 %167 %168 -%170 = OpCompositeExtract %4 %151 2 +%170 = OpCompositeExtract %4 %155 1 %171 = OpIAdd %4 %169 %170 -%172 = OpConvertSToF %8 %171 -%173 = OpCompositeConstruct %27 %172 %172 %172 %172 -OpStore %126 %173 +%172 = OpCompositeExtract %4 %156 1 +%173 = OpIAdd %4 %171 %172 +%174 = OpCompositeExtract %4 %157 1 +%175 = OpIAdd %4 %173 %174 +%176 = OpCompositeExtract %4 %159 1 +%177 = OpIAdd %4 %175 %176 +%178 = OpCompositeExtract %4 %161 1 +%179 = OpIAdd %4 %177 %178 +%180 = OpCompositeExtract %4 %162 2 +%181 = OpIAdd %4 %179 %180 +%182 = OpCompositeExtract %4 %163 2 +%183 = OpIAdd %4 %181 %182 +%184 = OpConvertSToF %8 %183 +%185 = OpCompositeConstruct %28 %184 %184 %184 %184 +OpStore %136 %185 OpReturn OpFunctionEnd -%176 = OpFunction %2 None %70 -%174 = OpLabel -%177 = OpLoad %21 %47 -%178 = OpLoad %22 %49 -%179 = OpLoad %23 %51 -%180 = OpLoad %24 %53 -%181 = OpLoad %25 %55 -%182 = OpLoad %26 %57 -OpBranch %183 -%183 = OpLabel -%184 = OpImageQueryLevels %4 %177 -%185 = OpImageQueryLevels %4 %178 -%186 = OpImageQuerySizeLod %97 %178 %136 -%187 = OpCompositeExtract %4 %186 2 -%188 = OpImageQueryLevels %4 %179 -%189 = OpImageQueryLevels %4 %180 -%190 = OpImageQuerySizeLod %97 %180 %136 -%191 = OpCompositeExtract %4 %190 2 -%192 = OpImageQueryLevels %4 %181 -%193 = OpImageQuerySamples %4 %182 -%194 = OpIAdd %4 %187 %191 -%195 = OpIAdd %4 %194 %193 -%196 = OpIAdd %4 %195 %184 -%197 = OpIAdd %4 %196 %185 -%198 = OpIAdd %4 %197 %192 -%199 = OpIAdd %4 %198 %188 -%200 = OpIAdd %4 %199 %189 -%201 = OpConvertSToF %8 %200 -%202 = OpCompositeConstruct %27 %201 %201 %201 %201 -OpStore %175 %202 +%188 = OpFunction %2 None %73 +%186 = OpLabel +%189 = OpLoad %22 %50 +%190 = OpLoad %23 %52 +%191 = OpLoad %24 %54 +%192 = OpLoad %25 %56 +%193 = OpLoad %26 %58 +%194 = OpLoad %27 %60 +OpBranch %195 +%195 = OpLabel +%196 = OpImageQueryLevels %4 %189 +%197 = OpImageQueryLevels %4 %190 +%198 = OpImageQuerySizeLod %101 %190 %146 +%199 = OpCompositeExtract %4 %198 2 +%200 = OpImageQueryLevels %4 %191 +%201 = OpImageQueryLevels %4 %192 +%202 = OpImageQuerySizeLod %101 %192 %146 +%203 = OpCompositeExtract %4 %202 2 +%204 = OpImageQueryLevels %4 %193 +%205 = OpImageQuerySamples %4 %194 +%206 = OpIAdd %4 %199 %203 +%207 = OpIAdd %4 %206 %205 +%208 = OpIAdd %4 %207 %196 +%209 = OpIAdd %4 %208 %197 +%210 = OpIAdd %4 %209 %204 +%211 = OpIAdd %4 %210 %200 +%212 = OpIAdd %4 %211 %201 +%213 = OpConvertSToF %8 %212 +%214 = OpCompositeConstruct %28 %213 %213 %213 %213 +OpStore %187 %214 OpReturn OpFunctionEnd -%205 = OpFunction %2 None %70 -%203 = OpLabel -%206 = OpLoad %20 %45 -%207 = OpLoad %21 %47 -%208 = OpLoad %28 %59 -OpBranch %209 -%209 = OpLabel -%211 = OpCompositeConstruct %210 %7 %7 -%212 = OpCompositeExtract %8 %211 0 -%214 = OpSampledImage %213 %206 %208 -%215 = OpImageSampleImplicitLod %27 %214 %212 -%217 = OpSampledImage %216 %207 %208 -%218 = OpImageSampleImplicitLod %27 %217 %211 -%219 = OpSampledImage %216 %207 %208 -%220 = OpImageSampleImplicitLod %27 %219 %211 ConstOffset %30 -%221 = OpSampledImage %216 %207 %208 -%222 = OpImageSampleExplicitLod %27 %221 %211 Lod %9 -%223 = OpSampledImage %216 %207 %208 -%224 = OpImageSampleExplicitLod %27 %223 %211 Lod|ConstOffset %9 %30 -%225 = OpFAdd %27 %215 %218 -%226 = OpFAdd %27 %225 %220 -%227 = OpFAdd %27 %226 %222 -%228 = OpFAdd %27 %227 %224 -OpStore %204 %228 +%217 = OpFunction %2 None %73 +%215 = OpLabel +%218 = OpLoad %21 %48 +%219 = OpLoad %22 %50 +%220 = OpLoad %29 %62 +OpBranch %221 +%221 = OpLabel +%223 = OpCompositeConstruct %222 %7 %7 +%224 = OpCompositeExtract %8 %223 0 +%226 = OpSampledImage %225 %218 %220 +%227 = OpImageSampleImplicitLod %28 %226 %224 +%229 = OpSampledImage %228 %219 %220 +%230 = OpImageSampleImplicitLod %28 %229 %223 +%231 = OpSampledImage %228 %219 %220 +%232 = OpImageSampleImplicitLod %28 %231 %223 ConstOffset %31 +%233 = OpSampledImage %228 %219 %220 +%234 = OpImageSampleExplicitLod %28 %233 %223 Lod %9 +%235 = OpSampledImage %228 %219 %220 +%236 = OpImageSampleExplicitLod %28 %235 %223 Lod|ConstOffset %9 %31 +%237 = OpFAdd %28 %227 %230 +%238 = OpFAdd %28 %237 %232 +%239 = OpFAdd %28 %238 %234 +%240 = OpFAdd %28 %239 %236 +OpStore %216 %240 OpReturn OpFunctionEnd -%232 = OpFunction %2 None %70 -%229 = OpLabel -%233 = OpLoad %28 %61 -%234 = OpLoad %29 %63 -OpBranch %235 -%235 = OpLabel -%236 = OpCompositeConstruct %210 %7 %7 -%238 = OpSampledImage %237 %234 %233 -%239 = OpImageSampleDrefImplicitLod %8 %238 %236 %7 -%240 = OpSampledImage %237 %234 %233 -%241 = OpImageSampleDrefExplicitLod %8 %240 %236 %7 Lod %242 -%243 = OpFAdd %8 %239 %241 -OpStore %230 %243 +%244 = OpFunction %2 None %73 +%241 = OpLabel +%245 = OpLoad %29 %64 +%246 = OpLoad %30 %66 +OpBranch %247 +%247 = OpLabel +%248 = OpCompositeConstruct %222 %7 %7 +%250 = OpSampledImage %249 %246 %245 +%251 = OpImageSampleDrefImplicitLod %8 %250 %248 %7 +%252 = OpSampledImage %249 %246 %245 +%253 = OpImageSampleDrefExplicitLod %8 %252 %248 %7 Lod %254 +%255 = OpFAdd %8 %251 %253 +OpStore %242 %255 OpReturn OpFunctionEnd -%246 = OpFunction %2 None %70 -%244 = OpLabel -%247 = OpLoad %21 %47 -%248 = OpLoad %28 %59 -%249 = OpLoad %28 %61 -%250 = OpLoad %29 %63 -OpBranch %251 -%251 = OpLabel -%252 = OpCompositeConstruct %210 %7 %7 -%253 = OpSampledImage %216 %247 %248 -%254 = OpImageGather %27 %253 %252 %255 -%256 = OpSampledImage %216 %247 %248 -%257 = OpImageGather %27 %256 %252 %258 ConstOffset %30 -%259 = OpSampledImage %237 %250 %249 -%260 = OpImageDrefGather %27 %259 %252 %7 -%261 = OpSampledImage %237 %250 %249 -%262 = OpImageDrefGather %27 %261 %252 %7 ConstOffset %30 -%263 = OpFAdd %27 %254 %257 -%264 = OpFAdd %27 %263 %260 -%265 = OpFAdd %27 %264 %262 -OpStore %245 %265 +%258 = OpFunction %2 None %73 +%256 = OpLabel +%259 = OpLoad %22 %50 +%260 = OpLoad %29 %62 +%261 = OpLoad %29 %64 +%262 = OpLoad %30 %66 +OpBranch %263 +%263 = OpLabel +%264 = OpCompositeConstruct %222 %7 %7 +%265 = OpSampledImage %228 %259 %260 +%266 = OpImageGather %28 %265 %264 %267 +%268 = OpSampledImage %228 %259 %260 +%269 = OpImageGather %28 %268 %264 %270 ConstOffset %31 +%271 = OpSampledImage %249 %262 %261 +%272 = OpImageDrefGather %28 %271 %264 %7 +%273 = OpSampledImage %249 %262 %261 +%274 = OpImageDrefGather %28 %273 %264 %7 ConstOffset %31 +%275 = OpFAdd %28 %266 %269 +%276 = OpFAdd %28 %275 %272 +%277 = OpFAdd %28 %276 %274 +OpStore %257 %277 OpReturn OpFunctionEnd -%268 = OpFunction %2 None %70 -%266 = OpLabel -%269 = OpLoad %28 %59 -%270 = OpLoad %29 %63 -OpBranch %271 -%271 = OpLabel -%272 = OpCompositeConstruct %210 %7 %7 -%273 = OpSampledImage %237 %270 %269 -%274 = OpImageSampleImplicitLod %27 %273 %272 -%275 = OpCompositeExtract %8 %274 0 -%276 = OpSampledImage %237 %270 %269 -%277 = OpImageGather %27 %276 %272 %136 -%278 = OpCompositeConstruct %27 %275 %275 %275 %275 -%279 = OpFAdd %27 %278 %277 -OpStore %267 %279 +%280 = OpFunction %2 None %73 +%278 = OpLabel +%281 = OpLoad %29 %62 +%282 = OpLoad %30 %66 +OpBranch %283 +%283 = OpLabel +%284 = OpCompositeConstruct %222 %7 %7 +%285 = OpSampledImage %249 %282 %281 +%286 = OpImageSampleImplicitLod %28 %285 %284 +%287 = OpCompositeExtract %8 %286 0 +%288 = OpSampledImage %249 %282 %281 +%289 = OpImageGather %28 %288 %284 %146 +%290 = OpCompositeConstruct %28 %287 %287 %287 %287 +%291 = OpFAdd %28 %290 %289 +OpStore %279 %291 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 0a7eda004..ec40004e1 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -10,6 +10,8 @@ var image_storage_src: texture_storage_2d; var image_array_src: texture_2d_array; [[group(0), binding(6)]] var image_dup_src: texture_storage_1d; +[[group(0), binding(7)]] +var image_1d_src: texture_1d; [[group(0), binding(2)]] var image_dst: texture_storage_1d; [[group(0), binding(0)]] @@ -41,7 +43,8 @@ fn main([[builtin(local_invocation_id)]] local_id: vec3) { let value2_ = textureLoad(image_multisampled_src, itc, i32(local_id.z)); let value4_ = textureLoad(image_storage_src, itc); let value5_ = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); - textureStore(image_dst, itc.x, (((value1_ + value2_) + value4_) + value5_)); + let value6_ = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z)); + textureStore(image_dst, itc.x, ((((value1_ + value2_) + value4_) + value5_) + value6_)); return; } @@ -57,6 +60,7 @@ fn depth_load([[builtin(local_invocation_id)]] local_id_1: vec3) { [[stage(vertex)]] fn queries() -> [[builtin(position)]] vec4 { let dim_1d = textureDimensions(image_1d); + let dim_1d_lod = textureDimensions(image_1d, i32(dim_1d)); let dim_2d = textureDimensions(image_2d); let dim_2d_lod = textureDimensions(image_2d, 1); let dim_2d_array = textureDimensions(image_2d_array); From 09d35f363134920a9a477cefa32b29bb4416092b Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 5 Jan 2022 20:15:09 -0500 Subject: [PATCH 1517/2212] gl-out: skip unsized types if unused --- src/back/glsl/mod.rs | 88 ++++++++++++--------- tests/in/globals.wgsl | 7 ++ tests/out/glsl/globals.main.Compute.glsl | 8 +- tests/out/hlsl/globals.hlsl | 9 ++- tests/out/msl/globals.msl | 16 +++- tests/out/spv/globals.spvasm | 97 +++++++++++++----------- tests/out/wgsl/globals.wgsl | 14 +++- 7 files changed, 146 insertions(+), 93 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 72b31d459..239cb0a15 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -102,21 +102,30 @@ impl crate::StorageClass { } } -//Note: similar to `back/spv/helpers.rs` -fn global_needs_wrapper(ir_module: &crate::Module, global_ty: Handle) -> bool { - match ir_module.types[global_ty].inner { - crate::TypeInner::Struct { - ref members, - span: _, - } => match ir_module.types[members.last().unwrap().ty].inner { - // Structs with dynamically sized arrays can't be copied and can't be wrapped. - crate::TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } => false, - _ => true, - }, - _ => false, +#[derive(PartialEq)] +enum GlobalTypeKind<'a> { + WrappedStruct, + Unsized(&'a [crate::StructMember]), + Other, +} + +impl<'a> GlobalTypeKind<'a> { + //Note: similar to `back/spv/helpers.rs` + fn new(ir_module: &'a crate::Module, global_ty: Handle) -> Self { + match ir_module.types[global_ty].inner { + crate::TypeInner::Struct { + ref members, + span: _, + } => match ir_module.types[members.last().unwrap().ty].inner { + // Structs with dynamically sized arrays can't be copied and can't be wrapped. + crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } => Self::Unsized(members), + _ => Self::WrappedStruct, + }, + _ => Self::Other, + } } } @@ -545,14 +554,21 @@ impl<'a, W: Write> Writer<'a, W> { // struct without adding all of it's members first for (handle, ty) in self.module.types.iter() { if let TypeInner::Struct { ref members, .. } = ty.inner { - let used_by_global = self.module.global_variables.iter().any(|(vh, var)| { - !ep_info[vh].is_empty() && var.class.is_buffer() && var.ty == handle - }); - - let is_wrapped = global_needs_wrapper(self.module, handle); - // If it's a global non-wrapped struct, it will be printed - // with the corresponding global variable. - if !used_by_global || is_wrapped { + let generate_struct = match GlobalTypeKind::new(self.module, handle) { + GlobalTypeKind::WrappedStruct => true, + // If it's a global non-wrapped struct, it will be printed + // with the corresponding global variable. + GlobalTypeKind::Unsized(_) => false, + GlobalTypeKind::Other => { + let used_by_global = + self.module.global_variables.iter().any(|(vh, var)| { + !ep_info[vh].is_empty() && var.class.is_buffer() && var.ty == handle + }); + // If not used by a global, it's safe to just spew it here + !used_by_global + } + }; + if generate_struct { let name = &self.names[&NameKey::Type(handle)]; write!(self.out, "struct {} ", name)?; self.write_struct_body(handle, members)?; @@ -925,18 +941,22 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{} ", block_name)?; self.reflection_names_globals.insert(handle, block_name); - let needs_wrapper = global_needs_wrapper(self.module, global.ty); - if needs_wrapper { - write!(self.out, "{{ ")?; - // Write the type - // `write_type` adds no leading or trailing spaces - self.write_type(global.ty)?; - } else if let crate::TypeInner::Struct { ref members, .. } = - self.module.types[global.ty].inner - { - self.write_struct_body(global.ty, members)?; + match GlobalTypeKind::new(self.module, global.ty) { + GlobalTypeKind::WrappedStruct => { + write!(self.out, "{{ ")?; + // Write the type + // `write_type` adds no leading or trailing spaces + self.write_type(global.ty)?; + true + } + GlobalTypeKind::Unsized(members) => { + self.write_struct_body(global.ty, members)?; + false + } + GlobalTypeKind::Other => { + return Err(Error::Custom("Non-struct type of a buffer".to_string())); + } } - needs_wrapper } else { self.write_type(global.ty)?; false diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 03f87ddfb..6c9fc1c16 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -13,6 +13,13 @@ struct Foo { [[group(0), binding(1)]] var alignment: Foo; +struct Dummy { + arr: array>; +}; + +[[group(0), binding(2)]] +var dummy: Dummy; + [[stage(compute), workgroup_size(1)]] fn main() { wg[3] = alignment.v1; diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index cdc5e7260..4b5377951 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -19,10 +19,10 @@ layout(std430) readonly buffer Foo_block_0Compute { Foo _group_0_binding_1_cs; } void main() { float Foo_1 = 1.0; bool at = true; - float _e7 = _group_0_binding_1_cs.v1_; - wg[3] = _e7; - float _e12 = _group_0_binding_1_cs.v3_.x; - wg[2] = _e12; + float _e8 = _group_0_binding_1_cs.v1_; + wg[3] = _e8; + float _e13 = _group_0_binding_1_cs.v3_.x; + wg[2] = _e13; at_1 = 2u; return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 1e05d9fa7..41a114f5b 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -8,6 +8,7 @@ struct Foo { groupshared float wg[10]; groupshared uint at_1; ByteAddressBuffer alignment : register(t1); +ByteAddressBuffer dummy : register(t2); [numthreads(1, 1, 1)] void main() @@ -15,10 +16,10 @@ void main() float Foo_1 = 1.0; bool at = true; - float _expr7 = asfloat(alignment.Load(12)); - wg[3] = _expr7; - float _expr12 = asfloat(alignment.Load(0+0)); - wg[2] = _expr12; + float _expr8 = asfloat(alignment.Load(12)); + wg[3] = _expr8; + float _expr13 = asfloat(alignment.Load(0+0)); + wg[2] = _expr13; at_1 = 2u; return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 636aa69c8..f2c37b5ab 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -2,6 +2,10 @@ #include #include +struct _mslBufferSizes { + metal::uint size3; +}; + constexpr constant bool Foo_2 = true; struct type_2 { float inner[10u]; @@ -10,6 +14,10 @@ struct Foo { metal::packed_float3 v3_; float v1_; }; +typedef metal::float2 type_6[1]; +struct Dummy { + type_6 arr; +}; kernel void main_( threadgroup type_2& wg @@ -18,10 +26,10 @@ kernel void main_( ) { float Foo_1 = 1.0; bool at = true; - float _e7 = alignment.v1_; - wg.inner[3] = _e7; - float _e12 = metal::float3(alignment.v3_).x; - wg.inner[2] = _e12; + float _e8 = alignment.v1_; + wg.inner[3] = _e8; + float _e13 = metal::float3(alignment.v3_).x; + wg.inner[2] = _e13; metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index c9ec4c220..a11785e8c 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,21 +1,27 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 48 +; Bound: 53 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %29 "main" -OpExecutionMode %29 LocalSize 1 1 1 +OpEntryPoint GLCompute %34 "main" +OpExecutionMode %34 LocalSize 1 1 1 OpDecorate %14 ArrayStride 4 OpMemberDecorate %16 0 Offset 0 OpMemberDecorate %16 1 Offset 12 -OpDecorate %21 NonWritable -OpDecorate %21 DescriptorSet 0 -OpDecorate %21 Binding 1 -OpDecorate %22 Block -OpMemberDecorate %22 0 Offset 0 +OpDecorate %18 ArrayStride 8 +OpMemberDecorate %19 0 Offset 0 +OpDecorate %24 NonWritable +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 1 +OpDecorate %25 Block +OpMemberDecorate %25 0 Offset 0 +OpDecorate %27 NonWritable +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 2 +OpDecorate %19 Block %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -31,40 +37,45 @@ OpMemberDecorate %22 0 Offset 0 %14 = OpTypeArray %12 %5 %15 = OpTypeVector %12 3 %16 = OpTypeStruct %15 %12 -%18 = OpTypePointer Workgroup %14 -%17 = OpVariable %18 Workgroup -%20 = OpTypePointer Workgroup %6 -%19 = OpVariable %20 Workgroup -%22 = OpTypeStruct %16 -%23 = OpTypePointer StorageBuffer %22 -%21 = OpVariable %23 StorageBuffer -%25 = OpTypePointer Function %12 -%27 = OpTypePointer Function %4 -%30 = OpTypeFunction %2 -%31 = OpTypePointer StorageBuffer %16 -%32 = OpConstant %6 0 -%35 = OpTypePointer Workgroup %12 -%36 = OpTypePointer StorageBuffer %12 -%37 = OpConstant %6 1 -%40 = OpConstant %6 3 -%42 = OpTypePointer StorageBuffer %15 -%43 = OpTypePointer StorageBuffer %12 -%47 = OpConstant %6 256 -%29 = OpFunction %2 None %30 -%28 = OpLabel -%24 = OpVariable %25 Function %11 -%26 = OpVariable %27 Function %13 -%33 = OpAccessChain %31 %21 %32 -OpBranch %34 -%34 = OpLabel -%38 = OpAccessChain %36 %33 %37 -%39 = OpLoad %12 %38 -%41 = OpAccessChain %35 %17 %40 -OpStore %41 %39 -%44 = OpAccessChain %43 %33 %32 %32 -%45 = OpLoad %12 %44 -%46 = OpAccessChain %35 %17 %10 -OpStore %46 %45 -OpAtomicStore %19 %9 %47 %10 +%17 = OpTypeVector %12 2 +%18 = OpTypeRuntimeArray %17 +%19 = OpTypeStruct %18 +%21 = OpTypePointer Workgroup %14 +%20 = OpVariable %21 Workgroup +%23 = OpTypePointer Workgroup %6 +%22 = OpVariable %23 Workgroup +%25 = OpTypeStruct %16 +%26 = OpTypePointer StorageBuffer %25 +%24 = OpVariable %26 StorageBuffer +%28 = OpTypePointer StorageBuffer %19 +%27 = OpVariable %28 StorageBuffer +%30 = OpTypePointer Function %12 +%32 = OpTypePointer Function %4 +%35 = OpTypeFunction %2 +%36 = OpTypePointer StorageBuffer %16 +%37 = OpConstant %6 0 +%40 = OpTypePointer Workgroup %12 +%41 = OpTypePointer StorageBuffer %12 +%42 = OpConstant %6 1 +%45 = OpConstant %6 3 +%47 = OpTypePointer StorageBuffer %15 +%48 = OpTypePointer StorageBuffer %12 +%52 = OpConstant %6 256 +%34 = OpFunction %2 None %35 +%33 = OpLabel +%29 = OpVariable %30 Function %11 +%31 = OpVariable %32 Function %13 +%38 = OpAccessChain %36 %24 %37 +OpBranch %39 +%39 = OpLabel +%43 = OpAccessChain %41 %38 %42 +%44 = OpLoad %12 %43 +%46 = OpAccessChain %40 %20 %45 +OpStore %46 %44 +%49 = OpAccessChain %48 %38 %37 %37 +%50 = OpLoad %12 %49 +%51 = OpAccessChain %40 %20 %10 +OpStore %51 %50 +OpAtomicStore %22 %9 %52 %10 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index a79623904..c33296333 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -3,22 +3,28 @@ struct Foo { v1_: f32; }; +struct Dummy { + arr: [[stride(8)]] array>; +}; + let Foo_2: bool = true; var wg: array; var at_1: atomic; [[group(0), binding(1)]] var alignment: Foo; +[[group(0), binding(2)]] +var dummy: Dummy; [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { var Foo_1: f32 = 1.0; var at: bool = true; - let _e7 = alignment.v1_; - wg[3] = _e7; - let _e12 = alignment.v3_.x; - wg[2] = _e12; + let _e8 = alignment.v1_; + wg[3] = _e8; + let _e13 = alignment.v3_.x; + wg[2] = _e13; atomicStore((&at_1), 2u); return; } From e2fc32387b1014c22118bc204323eb2090c05814 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 7 Jan 2022 15:46:20 +0000 Subject: [PATCH 1518/2212] spv-in: more sign agnostic binary operations --- src/front/spv/convert.rs | 4 ++++ src/front/spv/mod.rs | 26 +++++++++++--------------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index ce9055152..bdc8a6d24 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -13,6 +13,7 @@ pub(super) fn map_binary_operator(word: spirv::Op) -> Result Ok(BinaryOperator::Multiply), Op::UDiv | Op::SDiv | Op::FDiv => Ok(BinaryOperator::Divide), Op::UMod | Op::SMod | Op::FMod => Ok(BinaryOperator::Modulo), + Op::SRem => Ok(BinaryOperator::Modulo), // Relational and Logical Instructions Op::IEqual | Op::FOrdEqual | Op::FUnordEqual | Op::LogicalEqual => { Ok(BinaryOperator::Equal) @@ -34,6 +35,9 @@ pub(super) fn map_binary_operator(word: spirv::Op) -> Result Ok(BinaryOperator::GreaterEqual), + Op::BitwiseOr => Ok(BinaryOperator::InclusiveOr), + Op::BitwiseXor => Ok(BinaryOperator::ExclusiveOr), + Op::BitwiseAnd => Ok(BinaryOperator::And), _ => Err(Error::UnknownBinaryOperator(word)), } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d950b280c..a4f2b509d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1874,7 +1874,15 @@ impl> Parser { inst.expect(4)?; parse_expr_op!(crate::UnaryOperator::Negate, UNARY)?; } - Op::IAdd | Op::ISub | Op::IMul => { + Op::IAdd + | Op::ISub + | Op::IMul + | Op::BitwiseOr + | Op::BitwiseXor + | Op::BitwiseAnd + | Op::SDiv + | Op::SMod + | Op::SRem => { inst.expect(5)?; let operator = map_binary_operator(inst.op)?; self.parse_expr_binary_op_sign_adjusted( @@ -1912,11 +1920,11 @@ impl> Parser { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Multiply, BINARY)?; } - Op::SDiv | Op::UDiv | Op::FDiv => { + Op::UDiv | Op::FDiv => { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Divide, BINARY)?; } - Op::SMod | Op::UMod | Op::FMod | Op::SRem | Op::FRem => { + Op::UMod | Op::FMod | Op::FRem => { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Modulo, BINARY)?; } @@ -2153,18 +2161,6 @@ impl> Parser { inst.expect(4)?; parse_expr_op!(crate::UnaryOperator::Not, UNARY)?; } - Op::BitwiseOr => { - inst.expect(5)?; - parse_expr_op!(crate::BinaryOperator::InclusiveOr, BINARY)?; - } - Op::BitwiseXor => { - inst.expect(5)?; - parse_expr_op!(crate::BinaryOperator::ExclusiveOr, BINARY)?; - } - Op::BitwiseAnd => { - inst.expect(5)?; - parse_expr_op!(crate::BinaryOperator::And, BINARY)?; - } Op::ShiftRightLogical => { inst.expect(5)?; //TODO: convert input and result to usigned From eeb3de6f867aa0eb59a83a4fac62c9184ea63f7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 7 Jan 2022 15:58:16 +0000 Subject: [PATCH 1519/2212] spv-in: sign agnostic unary operations --- src/front/spv/mod.rs | 71 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a4f2b509d..4de53aad0 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -854,6 +854,59 @@ impl> Parser { Ok(()) } + /// A more complicated version of the unary op, + /// where we force the operand to have the same type as the result. + fn parse_expr_unary_op_sign_adjusted( + &mut self, + ctx: &mut BlockContext, + emitter: &mut super::Emitter, + block: &mut crate::Block, + block_id: spirv::Word, + body_idx: usize, + op: crate::UnaryOperator, + ) -> Result<(), Error> { + let start = self.data_offset; + let result_type_id = self.next()?; + let result_id = self.next()?; + let p1_id = self.next()?; + let span = self.span_from_with_op(start); + + let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); + + let result_lookup_ty = self.lookup_type.lookup(result_type_id)?; + let kind = ctx.type_arena[result_lookup_ty.handle] + .inner + .scalar_kind() + .unwrap(); + + let expr = crate::Expression::Unary { + op, + expr: if p1_lexp.type_id == result_type_id { + left + } else { + ctx.expressions.append( + crate::Expression::As { + expr: left, + kind, + convert: None, + }, + span, + ) + }, + }; + + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: ctx.expressions.append(expr, span), + type_id: result_type_id, + block_id, + }, + ); + Ok(()) + } + /// A more complicated version of the binary op, /// where we force the operand to have the same type as the result. /// This is mostly needed for "i++" and "i--" coming from GLSL. @@ -1872,7 +1925,14 @@ impl> Parser { // Arithmetic Instructions +, -, *, /, % Op::SNegate | Op::FNegate => { inst.expect(4)?; - parse_expr_op!(crate::UnaryOperator::Negate, UNARY)?; + self.parse_expr_unary_op_sign_adjusted( + ctx, + &mut emitter, + &mut block, + block_id, + body_idx, + crate::UnaryOperator::Negate, + )?; } Op::IAdd | Op::ISub @@ -2159,7 +2219,14 @@ impl> Parser { // Bitwise instructions Op::Not => { inst.expect(4)?; - parse_expr_op!(crate::UnaryOperator::Not, UNARY)?; + self.parse_expr_unary_op_sign_adjusted( + ctx, + &mut emitter, + &mut block, + block_id, + body_idx, + crate::UnaryOperator::Not, + )?; } Op::ShiftRightLogical => { inst.expect(5)?; From a8929603acbb68236e795fc00ca2706ab0f57411 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 7 Jan 2022 15:07:55 +0000 Subject: [PATCH 1520/2212] spv-in: OpVectorInsertDynamic allow unsigned index --- src/front/spv/mod.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 4de53aad0..e1de8bdaf 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1687,7 +1687,24 @@ impl> Parser { let root_handle = get_expr_handle!(composite_id, root_lexp); let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; let index_lexp = self.lookup_expression.lookup(index_id)?; - let index_handle = get_expr_handle!(index_id, index_lexp); + let mut index_handle = get_expr_handle!(index_id, index_lexp); + let index_type = self.lookup_type.lookup(index_lexp.type_id)?.handle; + + // SPIR-V allows signed and unsigned indices but naga's is strict about + // types and since the `index_constants` are all signed integers, we need + // to cast the index to a signed integer if it's unsigned. + if let Some(crate::ScalarKind::Uint) = + ctx.type_arena[index_type].inner.scalar_kind() + { + index_handle = ctx.expressions.append( + crate::Expression::As { + expr: index_handle, + kind: crate::ScalarKind::Sint, + convert: None, + }, + span, + ) + } let num_components = match ctx.type_arena[root_type_lookup.handle].inner { crate::TypeInner::Vector { size, .. } => size as usize, From 70b5ddaaad46b68ffb4e298b1d10d920544d3ca0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 7 Jan 2022 20:09:42 +0000 Subject: [PATCH 1521/2212] spv-out: use OpFRem instead of OpFMod --- Cargo.toml | 2 +- src/back/spv/block.rs | 2 +- tests/out/spv/operators.spvasm | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fdbf8216a..5b06a4275 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ bitflags = "1" bit-set = "0.5" codespan-reporting = { version = "0.11.0", optional = true } rustc-hash = "1.1.0" -indexmap = "1.6" # 1.7 has MSRV 1.49 +indexmap = "~1.6" # 1.7 has MSRV 1.49 log = "0.4" num-traits = "0.2" spirv = { version = "0.2", optional = true } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 64eaadcc9..02f441885 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -390,7 +390,7 @@ impl<'w> BlockContext<'w> { crate::BinaryOperator::Modulo => match left_ty_inner.scalar_kind() { Some(crate::ScalarKind::Sint) => spirv::Op::SMod, Some(crate::ScalarKind::Uint) => spirv::Op::UMod, - Some(crate::ScalarKind::Float) => spirv::Op::FMod, + Some(crate::ScalarKind::Float) => spirv::Op::FRem, _ => unimplemented!(), }, crate::BinaryOperator::Equal => match left_ty_inner.scalar_kind() { diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 0b8ee6e96..514e9bfb8 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -149,13 +149,13 @@ OpFunctionEnd OpBranch %118 %118 = OpLabel %119 = OpSMod %8 %7 %7 -%120 = OpFMod %4 %3 %3 +%120 = OpFRem %4 %3 %3 %122 = OpCompositeConstruct %121 %7 %7 %7 %123 = OpCompositeConstruct %121 %7 %7 %7 %124 = OpSMod %121 %122 %123 %125 = OpCompositeConstruct %22 %3 %3 %3 %126 = OpCompositeConstruct %22 %3 %3 %3 -%127 = OpFMod %22 %125 %126 +%127 = OpFRem %22 %125 %126 OpReturn OpFunctionEnd %129 = OpFunction %2 None %117 From 298a8c30bd8b4500e852211956fbd293590d3a96 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Mon, 10 Jan 2022 16:04:59 +0300 Subject: [PATCH 1522/2212] [wgsl-in] Write a real type in type mismatch error --- .gitignore | 2 ++ src/front/wgsl/mod.rs | 29 ++++++++++++++++++++++++----- tests/wgsl-errors.rs | 42 +++++++++++++++++++++++++++++++++++------- 3 files changed, 61 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index bb84f2e16..df4cb1d39 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ Cargo.lock /*.frag /*.comp /*.wgsl +/*.hlsl +/*.txt diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 93cdf2902..6103cf619 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -164,7 +164,7 @@ pub enum Error<'a> { ZeroSizeOrAlign(Span), InconsistentBinding(Span), UnknownLocalFunction(Span), - InitializationTypeMismatch(Span, Handle), + InitializationTypeMismatch(Span, String), MissingType(Span), InvalidAtomicPointer(Span), InvalidAtomicOperandType(Span), @@ -414,7 +414,7 @@ impl<'a> Error<'a> { notes: vec![], }, Error::InitializationTypeMismatch(ref name_span, ref expected_ty) => ParseError { - message: format!("the type of `{}` is expected to be {:?}", &source[name_span.clone()], expected_ty), + message: format!("the type of `{}` is expected to be `{}`", &source[name_span.clone()], expected_ty), labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], notes: vec![], }, @@ -3453,7 +3453,10 @@ impl Parser { given_inner, expr_inner ); - return Err(Error::InitializationTypeMismatch(name_span, ty)); + return Err(Error::InitializationTypeMismatch( + name_span, + expr_inner.to_wgsl(context.types, context.constants), + )); } } block.extend(emitter.finish(context.expressions)); @@ -3518,7 +3521,8 @@ impl Parser { expr_inner ); return Err(Error::InitializationTypeMismatch( - name_span, ty, + name_span, + expr_inner.to_wgsl(context.types, context.constants), )); } ty @@ -4293,7 +4297,22 @@ impl Parser { crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty, }; if !type_match { - return Err(Error::InitializationTypeMismatch(name_span, explicit_ty)); + let exptected_inner_str = match con.inner { + crate::ConstantInner::Scalar { width, value } => { + crate::TypeInner::Scalar { + kind: value.scalar_kind(), + width, + } + .to_wgsl(&module.types, &module.constants) + } + crate::ConstantInner::Composite { .. } => module.types[explicit_ty] + .inner + .to_wgsl(&module.types, &module.constants), + }; + return Err(Error::InitializationTypeMismatch( + name_span, + exptected_inner_str, + )); } } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 7607359de..ac0d21688 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -461,7 +461,7 @@ fn let_type_mismatch() { r#" let x: i32 = 1.0; "#, - r#"error: the type of `x` is expected to be [1] + r#"error: the type of `x` is expected to be `f32` ┌─ wgsl:2:17 │ 2 │ let x: i32 = 1.0; @@ -469,20 +469,48 @@ fn let_type_mismatch() { "#, ); -} -#[test] -fn local_var_type_mismatch() { check( r#" fn foo() { - var x: f32 = 1; + let x: f32 = true; } "#, - r#"error: the type of `x` is expected to be [1] + r#"error: the type of `x` is expected to be `bool` ┌─ wgsl:3:21 │ -3 │ var x: f32 = 1; +3 │ let x: f32 = true; + │ ^ definition of `x` + +"#, + ); +} + +#[test] +fn var_type_mismatch() { + check( + r#" + let x: f32 = 1; + "#, + r#"error: the type of `x` is expected to be `i32` + ┌─ wgsl:2:17 + │ +2 │ let x: f32 = 1; + │ ^ definition of `x` + +"#, + ); + + check( + r#" + fn foo() { + var x: f32 = 1u32; + } + "#, + r#"error: the type of `x` is expected to be `u32` + ┌─ wgsl:3:21 + │ +3 │ var x: f32 = 1u32; │ ^ definition of `x` "#, From 7555df952e45969d82ac260caa49a1b7beacfe7e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 11 Jan 2022 09:30:14 -0500 Subject: [PATCH 1523/2212] Adjust the MSL stack size lower bound --- src/back/msl/writer.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 55f72b630..dd4e93b22 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3224,7 +3224,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 20528 (CI) - if !(14000..=25000).contains(&stack_size) { + if !(11000..=25000).contains(&stack_size) { panic!("`put_expression` stack size {} has changed!", stack_size); } } @@ -3239,7 +3239,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 19152 (CI) - if !(13000..=20000).contains(&stack_size) { + if !(11000..=20000).contains(&stack_size) { panic!("`put_block` stack size {} has changed!", stack_size); } } From c0b7ac7f542cc42ccac6f2ec3fc1fb01309cf4d7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 11 Jan 2022 10:56:41 -0500 Subject: [PATCH 1524/2212] WGSL: assignment binary operators --- src/front/wgsl/lexer.rs | 26 +++++++-- src/front/wgsl/mod.rs | 41 +++++++++++++- tests/in/operators.wgsl | 16 +++++- tests/out/glsl/operators.main.Compute.glsl | 34 +++++++++--- tests/out/hlsl/operators.hlsl | 36 ++++++++++--- tests/out/msl/operators.msl | 35 +++++++++--- tests/out/spv/operators.spvasm | 62 ++++++++++++++++------ tests/out/wgsl/operators.wgsl | 35 +++++++++--- 8 files changed, 237 insertions(+), 48 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index e74520541..be419fd42 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -322,7 +322,12 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { if next == Some('=') && !generic { (Token::LogicalOperation(cur), chars.as_str()) } else if next == Some(cur) && !generic { - (Token::ShiftOperation(cur), chars.as_str()) + input = chars.as_str(); + if chars.next() == Some('=') { + (Token::AssignmentOperation(cur), chars.as_str()) + } else { + (Token::ShiftOperation(cur), input) + } } else { (Token::Paren(cur), input) } @@ -356,14 +361,22 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { (Token::Trivia, chars.as_str()) } '-' => { - let og_chars = chars.as_str(); + let sub_input = chars.as_str(); match chars.next() { Some('>') => (Token::Arrow, chars.as_str()), Some('0'..='9') | Some('.') => consume_number(input), - _ => (Token::Operation(cur), og_chars), + Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), + _ => (Token::Operation(cur), sub_input), + } + } + '+' | '*' | '/' | '%' | '^' => { + input = chars.as_str(); + if chars.next() == Some('=') { + (Token::AssignmentOperation(cur), chars.as_str()) + } else { + (Token::Operation(cur), input) } } - '+' | '*' | '/' | '%' | '^' => (Token::Operation(cur), chars.as_str()), '!' | '~' => { input = chars.as_str(); if chars.next() == Some('=') { @@ -374,8 +387,11 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { } '=' | '&' | '|' => { input = chars.as_str(); - if chars.next() == Some(cur) { + let next = chars.next(); + if next == Some(cur) { (Token::LogicalOperation(cur), chars.as_str()) + } else if next == Some('=') { + (Token::AssignmentOperation(cur), chars.as_str()) } else { (Token::Operation(cur), input) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6103cf619..5b7c34355 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -68,6 +68,7 @@ pub enum Token<'a> { Operation(char), LogicalOperation(char), ShiftOperation(char), + AssignmentOperation(char), Arrow, Unknown(char), UnterminatedString, @@ -198,6 +199,8 @@ impl<'a> Error<'a> { Token::Operation(c) => format!("operation ('{}')", c), Token::LogicalOperation(c) => format!("logical operation ('{}')", c), Token::ShiftOperation(c) => format!("bitshift ('{}{}')", c, c), + Token::AssignmentOperation(c) if c=='<' || c=='>' => format!("bitshift ('{}{}=')", c, c), + Token::AssignmentOperation(c) => format!("operation ('{}=')", c), Token::Arrow => "->".to_string(), Token::Unknown(c) => format!("unknown ('{}')", c), Token::UnterminatedString => "unterminated string".to_string(), @@ -3308,6 +3311,8 @@ impl Parser { lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, 'out>, ) -> Result<(), Error<'a>> { + use crate::BinaryOperator as Bo; + let span_start = lexer.current_byte_offset(); context.emitter.start(context.expressions); let reference = self.parse_unary_expression(lexer, context.reborrow())?; @@ -3319,8 +3324,40 @@ impl Parser { span, )); } - lexer.expect(Token::Operation('='))?; - let value = self.parse_general_expression(lexer, context.reborrow())?; + + let value = match lexer.next() { + (Token::Operation('='), _) => { + self.parse_general_expression(lexer, context.reborrow())? + } + (Token::AssignmentOperation(c), span) => { + let op = match c { + '<' => Bo::ShiftLeft, + '>' => Bo::ShiftRight, + '+' => Bo::Add, + '-' => Bo::Subtract, + '*' => Bo::Multiply, + '/' => Bo::Divide, + '%' => Bo::Modulo, + '&' => Bo::And, + '|' => Bo::InclusiveOr, + '^' => Bo::ExclusiveOr, + //Note: `consume_token` shouldn't produce any other assignment ops + _ => unreachable!(), + }; + let left = context.expressions.append( + crate::Expression::Load { + pointer: reference.handle, + }, + NagaSpan::from(span_start..lexer.current_byte_offset()), + ); + let right = self.parse_general_expression(lexer, context.reborrow())?; + context + .expressions + .append(crate::Expression::Binary { op, left, right }, span.into()) + } + other => return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)), + }; + let span_end = lexer.current_byte_offset(); context .block diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index da18e3a46..a7aedb7f2 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -80,11 +80,22 @@ fn scalar_times_matrix() { let assertion: mat4x4 = 2.0 * model; } -fn binary() { +fn logical() { let a = true | false; let b = true & false; } +fn binary_assignment() { + var a = 1; + a += 1; + a -= 1; + a *= a; + a /= a; + a %= 1; + a ^= 0; + a &= 0; +} + [[stage(compute), workgroup_size(1)]] fn main() { let a = builtins(); @@ -94,5 +105,6 @@ fn main() { let e = constructors(); modulo(); scalar_times_matrix(); - binary(); + logical(); + binary_assignment(); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 58dac4547..1ca8db55f 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -23,9 +23,9 @@ vec4 builtins() { } vec4 splat() { - vec2 a = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + vec2 a_1 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); ivec4 b = (ivec4(5) % ivec4(2)); - return (a.xyxy + vec4(b)); + return (a_1.xyxy + vec4(b)); } int unary() { @@ -51,7 +51,7 @@ float constructors() { } void modulo() { - int a_1 = (1 % 1); + int a_2 = (1 % 1); float b_1 = (1.0 - 1.0 * trunc(1.0 / 1.0)); ivec3 c = (ivec3(1) % ivec3(1)); vec3 d = (vec3(1.0) - vec3(1.0) * trunc(vec3(1.0) / vec3(1.0))); @@ -62,11 +62,32 @@ void scalar_times_matrix() { mat4x4 assertion = (2.0 * model); } -void binary() { - bool a_2 = (true || false); +void logical() { + bool a_3 = (true || false); bool b_2 = (true && false); } +void binary_assignment() { + int a = 1; + int _e6 = a; + a = (_e6 + 1); + int _e9 = a; + a = (_e9 - 1); + int _e12 = a; + int _e13 = a; + a = (_e12 * _e13); + int _e15 = a; + int _e16 = a; + a = (_e15 / _e16); + int _e18 = a; + a = (_e18 % 1); + int _e21 = a; + a = (_e21 ^ 0); + int _e24 = a; + a = (_e24 & 0); + return; +} + void main() { vec4 _e4 = builtins(); vec4 _e5 = splat(); @@ -75,7 +96,8 @@ void main() { float _e9 = constructors(); modulo(); scalar_times_matrix(); - binary(); + logical(); + binary_assignment(); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 1a858a7e0..8f060d85b 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -23,9 +23,9 @@ float4 builtins() float4 splat() { - float2 a = (((float2(1.0.xx) + float2(2.0.xx)) - float2(3.0.xx)) / float2(4.0.xx)); + float2 a_1 = (((float2(1.0.xx) + float2(2.0.xx)) - float2(3.0.xx)) / float2(4.0.xx)); int4 b = (int4(5.xxxx) % int4(2.xxxx)); - return (a.xyxy + float4(b)); + return (a_1.xyxy + float4(b)); } int unary() @@ -63,7 +63,7 @@ float constructors() void modulo() { - int a_1 = (1 % 1); + int a_2 = (1 % 1); float b_1 = (1.0 % 1.0); int3 c = (int3(1.xxx) % int3(1.xxx)); float3 d = (float3(1.0.xxx) % float3(1.0.xxx)); @@ -75,12 +75,35 @@ void scalar_times_matrix() float4x4 assertion = mul(model, 2.0); } -void binary() +void logical() { - bool a_2 = (true | false); + bool a_3 = (true | false); bool b_2 = (true & false); } +void binary_assignment() +{ + int a = 1; + + int _expr6 = a; + a = (_expr6 + 1); + int _expr9 = a; + a = (_expr9 - 1); + int _expr12 = a; + int _expr13 = a; + a = (_expr12 * _expr13); + int _expr15 = a; + int _expr16 = a; + a = (_expr15 / _expr16); + int _expr18 = a; + a = (_expr18 % 1); + int _expr21 = a; + a = (_expr21 ^ 0); + int _expr24 = a; + a = (_expr24 & 0); + return; +} + [numthreads(1, 1, 1)] void main() { @@ -91,6 +114,7 @@ void main() const float _e9 = constructors(); modulo(); scalar_times_matrix(); - binary(); + logical(); + binary_assignment(); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 5aa0fb44c..7fa931624 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -26,9 +26,9 @@ metal::float4 builtins( metal::float4 splat( ) { - metal::float2 a = ((metal::float2(1.0) + metal::float2(2.0)) - metal::float2(3.0)) / metal::float2(4.0); + metal::float2 a_1 = ((metal::float2(1.0) + metal::float2(2.0)) - metal::float2(3.0)) / metal::float2(4.0); metal::int4 b = metal::int4(5) % metal::int4(2); - return a.xyxy + static_cast(b); + return a_1.xyxy + static_cast(b); } int unary( @@ -59,7 +59,7 @@ float constructors( void modulo( ) { - int a_1 = 1 % 1; + int a_2 = 1 % 1; float b_1 = metal::fmod(1.0, 1.0); metal::int3 c = metal::int3(1) % metal::int3(1); metal::float3 d = metal::fmod(metal::float3(1.0), metal::float3(1.0)); @@ -71,12 +71,34 @@ void scalar_times_matrix( metal::float4x4 assertion = 2.0 * model; } -void binary( +void logical( ) { - bool a_2 = true | false; + bool a_3 = true | false; bool b_2 = true & false; } +void binary_assignment( +) { + int a = 1; + int _e6 = a; + a = _e6 + 1; + int _e9 = a; + a = _e9 - 1; + int _e12 = a; + int _e13 = a; + a = _e12 * _e13; + int _e15 = a; + int _e16 = a; + a = _e15 / _e16; + int _e18 = a; + a = _e18 % 1; + int _e21 = a; + a = _e21 ^ 0; + int _e24 = a; + a = _e24 & 0; + return; +} + kernel void main_( ) { metal::float4 _e4 = builtins(); @@ -86,6 +108,7 @@ kernel void main_( float _e9 = constructors(); modulo(); scalar_times_matrix(); - binary(); + logical(); + binary_assignment(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 514e9bfb8..bd81edce3 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 154 +; Bound: 176 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %143 "main" -OpExecutionMode %143 LocalSize 1 1 1 +OpEntryPoint GLCompute %164 "main" +OpExecutionMode %164 LocalSize 1 1 1 OpMemberDecorate %23 0 Offset 0 OpMemberDecorate %23 1 Offset 16 %2 = OpTypeVoid @@ -51,6 +51,7 @@ OpMemberDecorate %23 1 Offset 16 %111 = OpConstant %112 0 %117 = OpTypeFunction %2 %121 = OpTypeVector %8 3 +%143 = OpTypePointer Function %8 %32 = OpFunction %19 None %33 %31 = OpLabel OpBranch %34 @@ -178,18 +179,49 @@ OpBranch %139 %141 = OpLogicalAnd %10 %9 %12 OpReturn OpFunctionEnd -%143 = OpFunction %2 None %117 -%142 = OpLabel -OpBranch %144 +%145 = OpFunction %2 None %117 %144 = OpLabel -%145 = OpFunctionCall %19 %32 -%146 = OpFunctionCall %19 %57 -%147 = OpFunctionCall %8 %73 -%148 = OpVectorShuffle %22 %27 %27 0 1 2 -%149 = OpFunctionCall %22 %84 %148 -%150 = OpFunctionCall %4 %96 -%151 = OpFunctionCall %2 %116 -%152 = OpFunctionCall %2 %129 -%153 = OpFunctionCall %2 %138 +%142 = OpVariable %143 Function %7 +OpBranch %146 +%146 = OpLabel +%147 = OpLoad %8 %142 +%148 = OpIAdd %8 %147 %7 +OpStore %142 %148 +%149 = OpLoad %8 %142 +%150 = OpISub %8 %149 %7 +OpStore %142 %150 +%151 = OpLoad %8 %142 +%152 = OpLoad %8 %142 +%153 = OpIMul %8 %151 %152 +OpStore %142 %153 +%154 = OpLoad %8 %142 +%155 = OpLoad %8 %142 +%156 = OpSDiv %8 %154 %155 +OpStore %142 %156 +%157 = OpLoad %8 %142 +%158 = OpSMod %8 %157 %7 +OpStore %142 %158 +%159 = OpLoad %8 %142 +%160 = OpBitwiseXor %8 %159 %11 +OpStore %142 %160 +%161 = OpLoad %8 %142 +%162 = OpBitwiseAnd %8 %161 %11 +OpStore %142 %162 +OpReturn +OpFunctionEnd +%164 = OpFunction %2 None %117 +%163 = OpLabel +OpBranch %165 +%165 = OpLabel +%166 = OpFunctionCall %19 %32 +%167 = OpFunctionCall %19 %57 +%168 = OpFunctionCall %8 %73 +%169 = OpVectorShuffle %22 %27 %27 0 1 2 +%170 = OpFunctionCall %22 %84 %169 +%171 = OpFunctionCall %4 %96 +%172 = OpFunctionCall %2 %116 +%173 = OpFunctionCall %2 %129 +%174 = OpFunctionCall %2 %138 +%175 = OpFunctionCall %2 %145 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 1920ccb3a..ee1ef36d6 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -20,9 +20,9 @@ fn builtins() -> vec4 { } fn splat() -> vec4 { - let a = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + let a_1 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); let b = (vec4(5) % vec4(2)); - return (a.xyxy + vec4(b)); + return (a_1.xyxy + vec4(b)); } fn unary() -> i32 { @@ -49,7 +49,7 @@ fn constructors() -> f32 { } fn modulo() { - let a_1 = (1 % 1); + let a_2 = (1 % 1); let b_1 = (1.0 % 1.0); let c = (vec3(1) % vec3(1)); let d = (vec3(1.0) % vec3(1.0)); @@ -60,11 +60,33 @@ fn scalar_times_matrix() { let assertion = (2.0 * model); } -fn binary() { - let a_2 = (true | false); +fn logical() { + let a_3 = (true | false); let b_2 = (true & false); } +fn binary_assignment() { + var a: i32 = 1; + + let _e6 = a; + a = (_e6 + 1); + let _e9 = a; + a = (_e9 - 1); + let _e12 = a; + let _e13 = a; + a = (_e12 * _e13); + let _e15 = a; + let _e16 = a; + a = (_e15 / _e16); + let _e18 = a; + a = (_e18 % 1); + let _e21 = a; + a = (_e21 ^ 0); + let _e24 = a; + a = (_e24 & 0); + return; +} + [[stage(compute), workgroup_size(1, 1, 1)]] fn main() { let _e4 = builtins(); @@ -74,6 +96,7 @@ fn main() { let _e9 = constructors(); modulo(); scalar_times_matrix(); - binary(); + logical(); + binary_assignment(); return; } From 9f376245928ccfeb2e2c64b0b63b08179634392a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20du=20Garreau?= Date: Wed, 12 Jan 2022 19:18:46 +0100 Subject: [PATCH 1525/2212] Don't pin `indexmap` version --- .github/workflows/pipeline.yml | 6 ++++++ Cargo.toml | 6 ++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index d7e652155..c92721c18 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -22,6 +22,12 @@ jobs: with: command: update args: -p bitflags --precise 1.2.1 + - uses: actions-rs/cargo@v1 + name: Downgrade indexmap to MSRV + if: ${{ matrix.rust }} == "1.43.0" + with: + command: update + args: -p indexmap --precise 1.6.2 - uses: actions-rs/cargo@v1 name: Default test with: diff --git a/Cargo.toml b/Cargo.toml index 5b06a4275..bb93b3b32 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,12 +15,14 @@ resolver = "2" all-features = true [dependencies] -# MSRV warning: bitflags 1.3 requires Rust-1.46 +# MSRV warnings: +# - bitflags 1.3 requires Rust-1.46 +# - indexmap 1.7 requires Rust-1.49 bitflags = "1" bit-set = "0.5" codespan-reporting = { version = "0.11.0", optional = true } rustc-hash = "1.1.0" -indexmap = "~1.6" # 1.7 has MSRV 1.49 +indexmap = "1.6" log = "0.4" num-traits = "0.2" spirv = { version = "0.2", optional = true } From 58b4fd0f570f2fe83f7f1a21fc7b59050cc9433f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 13:26:21 -0500 Subject: [PATCH 1526/2212] IR fuzz target with Arbitrary implementations --- Cargo.toml | 4 ++- fuzz/Cargo.toml | 8 +++++- fuzz/fuzz_targets/ir.rs | 10 ++++++++ fuzz/fuzz_targets/spv_parser.rs | 2 +- src/arena.rs | 42 +++++++++++++++++++++++++++--- src/block.rs | 1 + src/lib.rs | 45 +++++++++++++++++++++++++++++++++ src/span.rs | 1 + 8 files changed, 106 insertions(+), 7 deletions(-) create mode 100644 fuzz/fuzz_targets/ir.rs diff --git a/Cargo.toml b/Cargo.toml index bb93b3b32..a0dcec570 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,10 +14,12 @@ resolver = "2" [package.metadata.docs.rs] all-features = true -[dependencies] # MSRV warnings: # - bitflags 1.3 requires Rust-1.46 # - indexmap 1.7 requires Rust-1.49 + +[dependencies] +arbitrary = { version = "1", features = ["derive"], optional = true } bitflags = "1" bit-set = "0.5" codespan-reporting = { version = "0.11.0", optional = true } diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index ceb30ea55..06c3e5a96 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -14,7 +14,7 @@ libfuzzer-sys = "0.4" [dependencies.naga] path = ".." -features = ["spv-in", "wgsl-in", "glsl-in"] +features = ["arbitrary", "spv-in", "wgsl-in", "glsl-in", "validate"] # Prevent this from interfering with workspaces [workspace] @@ -37,3 +37,9 @@ name = "glsl_parser" path = "fuzz_targets/glsl_parser.rs" test = false doc = false + +[[bin]] +name = "ir" +path = "fuzz_targets/ir.rs" +test = false +doc = false diff --git a/fuzz/fuzz_targets/ir.rs b/fuzz/fuzz_targets/ir.rs new file mode 100644 index 000000000..86b7a6aa6 --- /dev/null +++ b/fuzz/fuzz_targets/ir.rs @@ -0,0 +1,10 @@ +#![no_main] +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|module: naga::Module| { + use naga::valid as v; + // Check if the module validates without errors. + //TODO: may also fuzz the flags and capabilities + let mut validator = v::Validator::new(v::ValidationFlags::all(), v::Capabilities::empty()); + let _result = validator.validate(&module); +}); diff --git a/fuzz/fuzz_targets/spv_parser.rs b/fuzz/fuzz_targets/spv_parser.rs index 3b8af0fbb..0fda11f43 100644 --- a/fuzz/fuzz_targets/spv_parser.rs +++ b/fuzz/fuzz_targets/spv_parser.rs @@ -1,6 +1,6 @@ #![no_main] use libfuzzer_sys::fuzz_target; -use naga::front::spv::{Parser, Options}; +use naga::front::spv::{Options, Parser}; fuzz_target!(|data: Vec| { // Ensure the parser can handle potentially malformed data without crashing. diff --git a/src/arena.rs b/src/arena.rs index 4884010d3..56f70e94d 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -17,6 +17,7 @@ use indexmap::set::IndexSet; any(feature = "serialize", feature = "deserialize"), serde(transparent) )] +#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct Handle { index: Index, #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))] @@ -110,6 +111,7 @@ impl Handle { any(feature = "serialize", feature = "deserialize"), serde(transparent) )] +#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct Range { inner: ops::Range, #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))] @@ -154,6 +156,7 @@ impl Iterator for Range { /// a reference to the stored item. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "serialize", serde(transparent))] +#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] #[cfg_attr(test, derive(PartialEq))] pub struct Arena { /// Values of this arena. @@ -543,8 +546,7 @@ impl ops::Index> for UniqueArena { #[cfg(feature = "serialize")] impl serde::Serialize for UniqueArena where - T: Eq + hash::Hash, - T: serde::Serialize, + T: Eq + hash::Hash + serde::Serialize, { fn serialize(&self, serializer: S) -> Result where @@ -557,8 +559,7 @@ where #[cfg(feature = "deserialize")] impl<'de, T> serde::Deserialize<'de> for UniqueArena where - T: Eq + hash::Hash, - T: serde::Deserialize<'de>, + T: Eq + hash::Hash + serde::Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where @@ -575,3 +576,36 @@ where }) } } + +//Note: largely borrowed from `HashSet` implementation +#[cfg(feature = "arbitrary")] +impl<'a, T> arbitrary::Arbitrary<'a> for UniqueArena +where + T: Eq + hash::Hash + arbitrary::Arbitrary<'a>, +{ + fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result { + let mut arena = Self::default(); + for elem in u.arbitrary_iter()? { + arena.set.insert(elem?); + #[cfg(feature = "span")] + arena.span_info.push(Span::UNDEFINED); + } + Ok(arena) + } + + fn arbitrary_take_rest(u: arbitrary::Unstructured<'a>) -> arbitrary::Result { + let mut arena = Self::default(); + for elem in u.arbitrary_take_rest_iter()? { + arena.set.insert(elem?); + #[cfg(feature = "span")] + arena.span_info.push(Span::UNDEFINED); + } + Ok(arena) + } + + #[inline] + fn size_hint(depth: usize) -> (usize, Option) { + let depth_hint = ::size_hint(depth); + arbitrary::size_hint::and(depth_hint, (0, None)) + } +} diff --git a/src/block.rs b/src/block.rs index 6a31301e1..e70202b8d 100644 --- a/src/block.rs +++ b/src/block.rs @@ -5,6 +5,7 @@ use std::ops::{Deref, DerefMut, RangeBounds}; #[derive(Debug, Clone, Default)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "serialize", serde(transparent))] +#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct Block { body: Vec, #[cfg(feature = "span")] diff --git a/src/lib.rs b/src/lib.rs index 6e7083082..d6e6aacd6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -217,6 +217,8 @@ pub mod valid; pub use crate::arena::{Arena, Handle, Range, UniqueArena}; pub use crate::span::{Span, SpanContext, WithSpan}; +#[cfg(feature = "arbitrary")] +use arbitrary::Arbitrary; #[cfg(feature = "deserialize")] use serde::Deserialize; #[cfg(feature = "serialize")] @@ -248,6 +250,7 @@ pub(crate) type NamedExpressions = FastHashMap, String>; #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct EarlyDepthTest { conservative: Option, } @@ -264,6 +267,7 @@ pub struct EarlyDepthTest { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ConservativeDepth { /// Shader may rewrite depth only with a value greater than calculated; GreaterEqual, @@ -279,6 +283,7 @@ pub enum ConservativeDepth { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[allow(missing_docs)] // The names are self evident pub enum ShaderStage { Vertex, @@ -290,6 +295,7 @@ pub enum ShaderStage { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum StorageClass { /// Function locals. Function, @@ -311,6 +317,7 @@ pub enum StorageClass { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum BuiltIn { Position, ViewIndex, @@ -345,6 +352,7 @@ pub type Bytes = u8; #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum VectorSize { /// 2D vector Bi = 2, @@ -359,6 +367,7 @@ pub enum VectorSize { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ScalarKind { /// Signed integer type. Sint, @@ -375,6 +384,7 @@ pub enum ScalarKind { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ArraySize { /// The array size is constant. Constant(Handle), @@ -386,6 +396,7 @@ pub enum ArraySize { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Interpolation { /// The value will be interpolated in a perspective-correct fashion. /// Also known as "smooth" in glsl. @@ -402,6 +413,7 @@ pub enum Interpolation { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Sampling { /// Interpolate the value at the center of the pixel. Center, @@ -421,6 +433,7 @@ pub enum Sampling { #[derive(Clone, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct StructMember { pub name: Option, /// Type of the field. @@ -435,6 +448,7 @@ pub struct StructMember { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ImageDimension { /// 1D image D1, @@ -450,6 +464,7 @@ bitflags::bitflags! { /// Flags describing an image. #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] + #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[derive(Default)] pub struct StorageAccess: u32 { /// Storage can be used as a source for load ops. @@ -463,6 +478,7 @@ bitflags::bitflags! { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum StorageFormat { // 8-bit formats R8Unorm, @@ -513,6 +529,7 @@ pub enum StorageFormat { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ImageClass { /// Regular sampled image. Sampled { @@ -540,6 +557,7 @@ pub enum ImageClass { #[derive(Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct Type { /// The name of the type, if any. pub name: Option, @@ -551,6 +569,7 @@ pub struct Type { #[derive(Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum TypeInner { /// Number of integral or floating-point kind. Scalar { kind: ScalarKind, width: Bytes }, @@ -680,6 +699,7 @@ pub enum TypeInner { #[derive(Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct Constant { pub name: Option, pub specialization: Option, @@ -690,6 +710,7 @@ pub struct Constant { #[derive(Debug, Clone, Copy, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ScalarValue { Sint(i64), Uint(u64), @@ -701,6 +722,7 @@ pub enum ScalarValue { #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ConstantInner { Scalar { width: Bytes, @@ -716,6 +738,7 @@ pub enum ConstantInner { #[derive(Clone, Debug, Eq, PartialEq, Hash)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Binding { /// Built-in shader variable. BuiltIn(BuiltIn), @@ -747,6 +770,7 @@ pub enum Binding { #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct ResourceBinding { /// The bind group index. pub group: u32, @@ -758,6 +782,7 @@ pub struct ResourceBinding { #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct GlobalVariable { /// Name of the variable, if any. pub name: Option, @@ -775,6 +800,7 @@ pub struct GlobalVariable { #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct LocalVariable { /// Name of the variable, if any. pub name: Option, @@ -788,6 +814,7 @@ pub struct LocalVariable { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum UnaryOperator { Negate, Not, @@ -797,6 +824,7 @@ pub enum UnaryOperator { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum BinaryOperator { Add, Subtract, @@ -827,6 +855,7 @@ pub enum BinaryOperator { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum AtomicFunction { Add, Subtract, @@ -842,6 +871,7 @@ pub enum AtomicFunction { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum DerivativeAxis { X, Y, @@ -852,6 +882,7 @@ pub enum DerivativeAxis { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum RelationalFunction { All, Any, @@ -865,6 +896,7 @@ pub enum RelationalFunction { #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum MathFunction { // comparison Abs, @@ -948,6 +980,7 @@ pub enum MathFunction { #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum SampleLevel { Auto, Zero, @@ -963,6 +996,7 @@ pub enum SampleLevel { #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ImageQuery { /// Get the size at the specified level. Size { @@ -982,6 +1016,7 @@ pub enum ImageQuery { #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum SwizzleComponent { /// X = 0, @@ -997,6 +1032,7 @@ bitflags::bitflags! { /// Memory barrier flags. #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] + #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[derive(Default)] pub struct Barrier: u32 { /// Barrier affects all `StorageClass::Storage` accesses. @@ -1013,6 +1049,7 @@ bitflags::bitflags! { #[cfg_attr(test, derive(PartialEq))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Expression { /// Array access with a computed index. /// @@ -1301,6 +1338,7 @@ pub use block::Block; #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum SwitchValue { Integer(i32), Default, @@ -1311,6 +1349,7 @@ pub enum SwitchValue { #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct SwitchCase { /// Value, upon which the case is considered true. pub value: SwitchValue, @@ -1327,6 +1366,7 @@ pub struct SwitchCase { #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Statement { /// Emit a range of expressions, visible to all statements that follow in this block. /// @@ -1470,6 +1510,7 @@ pub enum Statement { #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct FunctionArgument { /// Name of the argument, if any. pub name: Option, @@ -1483,6 +1524,7 @@ pub struct FunctionArgument { #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct FunctionResult { /// Type of the result. pub ty: Handle, @@ -1495,6 +1537,7 @@ pub struct FunctionResult { #[derive(Debug, Default)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct Function { /// Name of the function, if any. pub name: Option, @@ -1558,6 +1601,7 @@ pub struct Function { #[derive(Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct EntryPoint { /// Name of this entry point, visible externally. /// @@ -1587,6 +1631,7 @@ pub struct EntryPoint { #[derive(Debug, Default)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct Module { /// Storage for the types defined in this module. pub types: UniqueArena, diff --git a/src/span.rs b/src/span.rs index 6d541210b..51ea48101 100644 --- a/src/span.rs +++ b/src/span.rs @@ -3,6 +3,7 @@ use std::{error::Error, fmt, ops::Range}; /// A source code span, used for error reporting. #[derive(Clone, Copy, Debug, PartialEq, Default)] +#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct Span { start: u32, end: u32, From aedcc56b81d7fb0276f20d9b8890c39ebfc32e88 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 13:26:44 -0500 Subject: [PATCH 1527/2212] layouter: handle width=0 gracefully --- src/proc/layouter.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 5f6559f08..39e8177ee 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -74,7 +74,7 @@ impl Layouter { let layout = match ty.inner { Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => TypeLayout { size, - alignment: Alignment::new(width as u32).unwrap(), + alignment: Alignment::new(width as u32).ok_or(InvalidBaseType(ty_handle))?, }, Ti::Vector { size: vec_size, @@ -88,7 +88,7 @@ impl Layouter { } else { 2 }; - Alignment::new((count * width) as u32).unwrap() + Alignment::new((count * width) as u32).ok_or(InvalidBaseType(ty_handle))? }, }, Ti::Matrix { @@ -99,7 +99,7 @@ impl Layouter { size, alignment: { let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; - Alignment::new((count * width) as u32).unwrap() + Alignment::new((count * width) as u32).ok_or(InvalidBaseType(ty_handle))? }, }, Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { From bf0cb2b3a9f4278e2f3665621049500bae272c36 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 13:27:15 -0500 Subject: [PATCH 1528/2212] Fix multiplication overflow in span() computation --- src/proc/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 13883df90..00ec69c60 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -101,7 +101,7 @@ impl super::TypeInner { size, kind: _, width, - } => (size as u8 * width) as u32, + } => size as u32 * width as u32, // matrices are treated as arrays of aligned columns Self::Matrix { columns, From 003ea29a3a135f0c845de89aee3e739ddb6308ba Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 14:06:14 -0500 Subject: [PATCH 1529/2212] validate: check constant composite type --- src/valid/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 6b2c80475..f703bb916 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -240,7 +240,7 @@ impl Validator { } } crate::ConstantInner::Composite { ty, ref components } => { - match types[ty].inner { + match types.get_handle(ty).ok_or(ConstantError::InvalidType)?.inner { crate::TypeInner::Array { size: crate::ArraySize::Constant(size_handle), .. From a4ea9ce68de31567765147a406ff54beae634afb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 14:15:22 -0500 Subject: [PATCH 1530/2212] typifier: check local vars, global vars, and function arguments to exist --- src/proc/typifier.rs | 24 +++++++++++++++++++----- src/valid/function.rs | 8 +------- src/valid/mod.rs | 6 +++++- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 7a1d7a46e..6e237ee5a 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -189,10 +189,14 @@ pub enum ResolveError { FunctionNotDefined { name: String }, #[error("Function without return type")] FunctionReturnsVoid, - #[error("Type is not found in the given immutable arena")] - TypeNotFound, #[error("Incompatible operands: {0}")] IncompatibleOperands(String), + #[error("Local var {0:?} doesn't exist")] + LocalVariableNotFound(Handle), + #[error("Global var {0:?} doesn't exist")] + GlobalVariableNotFound(Handle), + #[error("Function argument {0} doesn't exist")] + FunctionArgumentNotFound(u32), } pub struct ResolveContext<'a> { @@ -430,10 +434,17 @@ impl<'a> ResolveContext<'a> { }, crate::Expression::Compose { ty, .. } => TypeResolution::Handle(ty), crate::Expression::FunctionArgument(index) => { - TypeResolution::Handle(self.arguments[index as usize].ty) + let arg = self + .arguments + .get(index as usize) + .ok_or(ResolveError::FunctionArgumentNotFound(index))?; + TypeResolution::Handle(arg.ty) } crate::Expression::GlobalVariable(h) => { - let var = &self.global_vars[h]; + let var = self + .global_vars + .try_get(h) + .ok_or(ResolveError::GlobalVariableNotFound(h))?; if var.class == crate::StorageClass::Handle { TypeResolution::Handle(var.ty) } else { @@ -444,7 +455,10 @@ impl<'a> ResolveContext<'a> { } } crate::Expression::LocalVariable(h) => { - let var = &self.local_vars[h]; + let var = self + .local_vars + .try_get(h) + .ok_or(ResolveError::LocalVariableNotFound(h))?; TypeResolution::Value(Ti::Pointer { base: var.ty, class: crate::StorageClass::Function, diff --git a/src/valid/function.rs b/src/valid/function.rs index 0254775ec..66f5965db 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -819,13 +819,7 @@ impl super::Validator { module: &crate::Module, mod_info: &ModuleInfo, ) -> Result> { - #[cfg(feature = "validate")] - let mut info = mod_info - .process_function(fun, module, self.flags) - .map_err(WithSpan::into_other)?; - - #[cfg(not(feature = "validate"))] - let info = mod_info.process_function(fun, module, self.flags)?; + let mut info = mod_info.process_function(fun, module, self.flags)?; #[cfg(feature = "validate")] for (var_handle, var) in fun.local_variables.iter() { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index f703bb916..a7e57a866 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -240,7 +240,11 @@ impl Validator { } } crate::ConstantInner::Composite { ty, ref components } => { - match types.get_handle(ty).ok_or(ConstantError::InvalidType)?.inner { + match types + .get_handle(ty) + .ok_or(ConstantError::InvalidType)? + .inner + { crate::TypeInner::Array { size: crate::ArraySize::Constant(size_handle), .. From c9f52bd651a11ddaf69128bb41a6bed2365d4938 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 14:27:39 -0500 Subject: [PATCH 1531/2212] validate: check global var type to be in range --- src/valid/interface.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 72c6561ab..5665aface 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -332,7 +332,10 @@ impl super::Validator { use super::TypeFlags; log::debug!("var {:?}", var); - let type_info = &self.types[var.ty.index()]; + let type_info = self + .types + .get(var.ty.index()) + .ok_or(GlobalVariableError::InvalidType)?; let (required_type_flags, is_resource) = match var.class { crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), From ee0cb0d5d3f46c2251b9fca3974811af0bf4bd73 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 14:30:06 -0500 Subject: [PATCH 1532/2212] layouter: handle width multiplication overflows --- src/proc/layouter.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 39e8177ee..d9b1f2f15 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -88,7 +88,7 @@ impl Layouter { } else { 2 }; - Alignment::new((count * width) as u32).ok_or(InvalidBaseType(ty_handle))? + Alignment::new(count * width as u32).ok_or(InvalidBaseType(ty_handle))? }, }, Ti::Matrix { @@ -99,7 +99,7 @@ impl Layouter { size, alignment: { let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; - Alignment::new((count * width) as u32).ok_or(InvalidBaseType(ty_handle))? + Alignment::new(count * width as u32).ok_or(InvalidBaseType(ty_handle))? }, }, Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { From fee69774a3c501d774e1f71263c2b44e087f2750 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 14:35:34 -0500 Subject: [PATCH 1533/2212] validate: check function argument type to be in range --- src/valid/function.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 66f5965db..411ef7ce1 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -837,7 +837,14 @@ impl super::Validator { #[cfg(feature = "validate")] for (index, argument) in fun.arguments.iter().enumerate() { - match module.types[argument.ty].inner.pointer_class() { + let ty = module.types.get_handle(argument.ty).ok_or( + FunctionError::InvalidArgumentType { + index, + name: argument.name.clone().unwrap_or_default(), + } + .with_span_handle(argument.ty, &module.types), + )?; + match ty.inner.pointer_class() { Some(crate::StorageClass::Private) | Some(crate::StorageClass::Function) | Some(crate::StorageClass::WorkGroup) From a069361bf419931376569bb95087510a8a648da7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 14:39:00 -0500 Subject: [PATCH 1534/2212] validate: check local var type to be in range --- src/valid/function.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 411ef7ce1..d0eeab1b5 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -786,12 +786,17 @@ impl super::Validator { constants: &Arena, ) -> Result<(), LocalVariableError> { log::debug!("var {:?}", var); - if !self.types[var.ty.index()] + let type_info = self + .types + .get(var.ty.index()) + .ok_or(LocalVariableError::InvalidType(var.ty))?; + if !type_info .flags .contains(super::TypeFlags::DATA | super::TypeFlags::SIZED) { return Err(LocalVariableError::InvalidType(var.ty)); } + if let Some(const_handle) = var.init { match constants[const_handle].inner { crate::ConstantInner::Scalar { width, ref value } => { From ab02ec79048bd902ccbfa304a5284cc07bc08898 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 16:27:28 -0500 Subject: [PATCH 1535/2212] layouter: rich and careful errors --- src/back/hlsl/storage.rs | 4 +-- src/back/msl/writer.rs | 17 ++++++------ src/front/glsl/functions.rs | 5 +++- src/front/glsl/types.rs | 10 +++---- src/front/spv/mod.rs | 4 +-- src/proc/layouter.rs | 54 +++++++++++++++++++++++++++++-------- src/proc/mod.rs | 24 +++++++++-------- src/valid/function.rs | 7 ++--- src/valid/mod.rs | 6 ++--- src/valid/type.rs | 7 +++-- 10 files changed, 90 insertions(+), 48 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index b235a061f..08909802b 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -148,7 +148,7 @@ impl super::Writer<'_, W> { } => { write!(self.out, "{{")?; let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.span(&module.constants); + let stride = module.types[base].inner.size(&module.constants).unwrap(); let iter = (0..count).map(|i| (TypeResolution::Handle(base), stride * i)); self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; write!(self.out, "}}")?; @@ -311,7 +311,7 @@ impl super::Writer<'_, W> { writeln!(self.out, ";")?; // then iterate the stores let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.span(&module.constants); + let stride = module.types[base].inner.size(&module.constants).unwrap(); for i in 0..count { self.temp_access_chain.push(SubAccess::Offset(i * stride)); let sv = StoreValue::TempIndex { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index dd4e93b22..9533e5076 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -349,7 +349,7 @@ fn should_pack_struct_member( } let ty_inner = &module.types[member.ty].inner; - let last_offset = member.offset + ty_inner.span(&module.constants); + let last_offset = member.offset + ty_inner.size(&module.constants).unwrap(); let next_offset = match members.get(index + 1) { Some(next) => next.offset, None => span, @@ -750,22 +750,23 @@ impl Writer { None => return Err(Error::Validation), }; - let (span, stride) = match context.module.types[array_ty].inner { + let (size, stride) = match context.module.types[array_ty].inner { crate::TypeInner::Array { base, stride, .. } => ( context.module.types[base] .inner - .span(&context.module.constants), + .size(&context.module.constants) + .unwrap(), stride, ), _ => return Err(Error::Validation), }; - // When the stride length is larger than the span, the final element's stride of + // When the stride length is larger than the size, the final element's stride of // bytes would have padding following the value. But the buffer size in // `buffer_sizes.sizeN` may not include this padding - it only needs to be large // enough to hold the actual values' bytes. // - // So subtract off the span to get a byte size that falls at the start or within + // So subtract off the size to get a byte size that falls at the start or within // the final element. Then divide by the stride size, to get one less than the // length, and then add one. This works even if the buffer size does include the // stride padding, since division rounds towards zero (MSL 2.4 §6.1). It will fail @@ -774,10 +775,10 @@ impl Writer { // prevent that. write!( self.out, - "(_buffer_sizes.size{idx} - {offset} - {span}) / {stride}", + "(_buffer_sizes.size{idx} - {offset} - {size}) / {stride}", idx = handle.index(), offset = offset, - span = span, + size = size, stride = stride, )?; Ok(()) @@ -2379,7 +2380,7 @@ impl Writer { writeln!(self.out, "{}char _pad{}[{}];", back::INDENT, index, pad)?; } let ty_inner = &module.types[member.ty].inner; - last_offset = member.offset + ty_inner.span(&module.constants); + last_offset = member.offset + ty_inner.size(&module.constants).unwrap(); let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 14f30bdfb..d565b0022 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1293,7 +1293,10 @@ impl Parser { offset: span, }); - span += self.module.types[ty].inner.span(&self.module.constants); + span += self.module.types[ty] + .inner + .size(&self.module.constants) + .unwrap(); let len = expressions.len(); let load = expressions.append(Expression::Load { pointer }, Default::default()); diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index e008ec382..106104378 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -262,14 +262,14 @@ impl Parser { array_specifier .map(|(size, size_meta)| { meta.subsume(size_meta); + let stride = self.module.types[base] + .inner + .size(&self.module.constants) + .unwrap(); self.module.types.insert( Type { name: None, - inner: TypeInner::Array { - base, - size, - stride: self.module.types[base].inner.span(&self.module.constants), - }, + inner: TypeInner::Array { base, size, stride }, }, meta, ) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e1de8bdaf..f6f7db14d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -4078,7 +4078,7 @@ impl> Parser { size: crate::ArraySize::Constant(length_const.handle), stride: match decor.array_stride { Some(stride) => stride.get(), - None => module.types[base].inner.span(&module.constants), + None => module.types[base].inner.size(&module.constants).unwrap(), }, }; self.lookup_type.insert( @@ -4115,7 +4115,7 @@ impl> Parser { size: crate::ArraySize::Dynamic, stride: match decor.array_stride { Some(stride) => stride.get(), - None => module.types[base].inner.span(&module.constants), + None => module.types[base].inner.size(&module.constants).unwrap(), }, }; self.lookup_type.insert( diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index d9b1f2f15..637257c17 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -30,8 +30,29 @@ impl ops::Index> for Layouter { } #[derive(Clone, Copy, Debug, PartialEq, thiserror::Error)] -#[error("Base type {0:?} is out of bounds")] -pub struct InvalidBaseType(pub Handle); +pub enum TypeLayoutError { + #[error("Array element type {0:?} doesn't exist")] + InvalidArrayElementType(Handle), + #[error("Struct member[{0}] type {1:?} doesn't exist")] + InvalidStructMemberType(u32, Handle), + #[error("Zero width is not supported")] + ZeroWidth, + #[error(transparent)] + Size(#[from] super::ProcError), +} + +#[derive(Clone, Copy, Debug, PartialEq, thiserror::Error)] +#[error("Error laying out type {ty:?}: {inner}")] +pub struct LayoutError { + pub ty: Handle, + pub inner: TypeLayoutError, +} + +impl TypeLayoutError { + fn with(self, ty: Handle) -> LayoutError { + LayoutError { ty, inner: self } + } +} impl Layouter { pub fn clear(&mut self) { @@ -62,19 +83,24 @@ impl Layouter { (start..start + span, alignment) } + #[allow(clippy::or_fun_call)] pub fn update( &mut self, types: &UniqueArena, constants: &Arena, - ) -> Result<(), InvalidBaseType> { + ) -> Result<(), LayoutError> { use crate::TypeInner as Ti; for (ty_handle, ty) in types.iter().skip(self.layouts.len()) { - let size = ty.inner.span(constants); + let size = ty + .inner + .size(constants) + .map_err(|error| TypeLayoutError::Size(error).with(ty_handle))?; let layout = match ty.inner { Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => TypeLayout { size, - alignment: Alignment::new(width as u32).ok_or(InvalidBaseType(ty_handle))?, + alignment: Alignment::new(width as u32) + .ok_or(TypeLayoutError::ZeroWidth.with(ty_handle))?, }, Ti::Vector { size: vec_size, @@ -88,7 +114,8 @@ impl Layouter { } else { 2 }; - Alignment::new(count * width as u32).ok_or(InvalidBaseType(ty_handle))? + Alignment::new(count * width as u32) + .ok_or(TypeLayoutError::ZeroWidth.with(ty_handle))? }, }, Ti::Matrix { @@ -99,7 +126,8 @@ impl Layouter { size, alignment: { let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; - Alignment::new(count * width as u32).ok_or(InvalidBaseType(ty_handle))? + Alignment::new(count * width as u32) + .ok_or(TypeLayoutError::ZeroWidth.with(ty_handle))? }, }, Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { @@ -115,16 +143,20 @@ impl Layouter { alignment: if base < ty_handle { self[base].alignment } else { - return Err(InvalidBaseType(base)); + return Err(TypeLayoutError::InvalidArrayElementType(base).with(ty_handle)); }, }, Ti::Struct { span, ref members } => { let mut alignment = Alignment::new(1).unwrap(); - for member in members { + for (index, member) in members.iter().enumerate() { alignment = if member.ty < ty_handle { alignment.max(self[member.ty].alignment) } else { - return Err(InvalidBaseType(member.ty)); + return Err(TypeLayoutError::InvalidStructMemberType( + index as u32, + member.ty, + ) + .with(ty_handle)); }; } TypeLayout { @@ -137,7 +169,7 @@ impl Layouter { alignment: Alignment::new(1).unwrap(), }, }; - debug_assert!(ty.inner.span(constants) <= layout.size); + debug_assert!(size <= layout.size); self.layouts.push(layout); } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 00ec69c60..79fd078ec 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -9,16 +9,16 @@ mod typifier; use std::cmp::PartialEq; pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength}; -pub use layouter::{Alignment, InvalidBaseType, Layouter, TypeLayout}; +pub use layouter::{Alignment, LayoutError, Layouter, TypeLayout, TypeLayoutError}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, TypeResolution}; -#[derive(Clone, Debug, thiserror::Error, PartialEq)] +#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq)] pub enum ProcError { - #[error("type is not indexable, and has no length (validation error)")] + #[error("Type is not indexable, and has no length (validation error)")] TypeNotIndexable, - #[error("array length is wrong kind of constant (validation error)")] + #[error("Array length {0:?} is wrong kind of constant (validation error)")] InvalidArraySizeConstant(crate::Handle), } @@ -94,8 +94,8 @@ impl super::TypeInner { } } - pub fn span(&self, constants: &super::Arena) -> u32 { - match *self { + pub fn size(&self, constants: &super::Arena) -> Result { + Ok(match *self { Self::Scalar { kind: _, width } | Self::Atomic { kind: _, width } => width as u32, Self::Vector { size, @@ -119,8 +119,10 @@ impl super::TypeInner { } => { let count = match size { super::ArraySize::Constant(handle) => { - // Bad array lengths will be caught during validation. - constants[handle].to_array_length().unwrap_or(1) + let constant = constants + .try_get(handle) + .ok_or(ProcError::InvalidArraySizeConstant(handle))?; + constant.to_array_length().unwrap_or(1) } // A dynamically-sized array has to have at least one element super::ArraySize::Dynamic => 1, @@ -129,7 +131,7 @@ impl super::TypeInner { } Self::Struct { span, .. } => span, Self::Image { .. } | Self::Sampler { .. } => 0, - } + }) } /// Return the canoncal form of `self`, or `None` if it's already in @@ -447,7 +449,7 @@ fn test_matrix_size() { rows: crate::VectorSize::Tri, width: 4 } - .span(&constants), - 48 + .size(&constants), + Ok(48), ); } diff --git a/src/valid/function.rs b/src/valid/function.rs index d0eeab1b5..491cee54b 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -824,6 +824,7 @@ impl super::Validator { module: &crate::Module, mod_info: &ModuleInfo, ) -> Result> { + #[cfg_attr(not(feature = "validate"), allow(unused_mut))] let mut info = mod_info.process_function(fun, module, self.flags)?; #[cfg(feature = "validate")] @@ -842,13 +843,13 @@ impl super::Validator { #[cfg(feature = "validate")] for (index, argument) in fun.arguments.iter().enumerate() { - let ty = module.types.get_handle(argument.ty).ok_or( + let ty = module.types.get_handle(argument.ty).ok_or_else(|| { FunctionError::InvalidArgumentType { index, name: argument.name.clone().unwrap_or_default(), } - .with_span_handle(argument.ty, &module.types), - )?; + .with_span_handle(argument.ty, &module.types) + })?; match ty.inner.pointer_class() { Some(crate::StorageClass::Private) | Some(crate::StorageClass::Function) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index a7e57a866..91807e002 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -10,7 +10,7 @@ use crate::arena::{Arena, UniqueArena}; use crate::{ arena::Handle, - proc::{InvalidBaseType, Layouter}, + proc::{LayoutError, Layouter}, FastHashSet, }; use bit_set::BitSet; @@ -127,7 +127,7 @@ pub enum ConstantError { #[derive(Clone, Debug, thiserror::Error)] pub enum ValidationError { #[error(transparent)] - Layouter(#[from] InvalidBaseType), + Layouter(#[from] LayoutError), #[error("Type {handle:?} '{name}' is invalid")] Type { handle: Handle, @@ -278,7 +278,7 @@ impl Validator { self.layouter .update(&module.types, &module.constants) .map_err(|e| { - let InvalidBaseType(handle) = e; + let handle = e.ty; ValidationError::from(e).with_span_handle(handle, &module.types) })?; diff --git a/src/valid/type.rs b/src/valid/type.rs index cda1fa64a..570e8efcc 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -326,7 +326,8 @@ impl super::Validator { return Err(TypeError::InvalidArrayBaseType(base)); } - let base_size = types[base].inner.span(constants); + //Note: `unwrap()` is fine, since `Layouter` goes first and calls it + let base_size = types[base].inner.size(constants).unwrap(); if stride < base_size { return Err(TypeError::InsufficientArrayStride { stride, base_size }); } @@ -478,7 +479,9 @@ impl super::Validator { }); } } - let base_size = types[member.ty].inner.span(constants); + + //Note: `unwrap()` is fine because `Layouter` goes first and checks this + let base_size = types[member.ty].inner.size(constants).unwrap(); min_offset = member.offset + base_size; if min_offset > span { return Err(TypeError::MemberOutOfBounds { From be7df0d2128b356b46874e056d9053aefee78190 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 16:45:09 -0500 Subject: [PATCH 1536/2212] analyzer: skip invalid expressions --- src/valid/analyzer.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index ab4d77c42..65d72572e 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -266,7 +266,10 @@ impl FunctionInfo { handle: Handle, global_use: GlobalUse, ) -> NonUniformResult { - let info = &mut self.expressions[handle.index()]; + //Note: if the expression doesn't exist, this function + // will return `None`, but the later validation of + // expressions should detect this and error properly. + let info = self.expressions.get_mut(handle.index())?; info.ref_count += 1; // mark the used global as read if let Some(global) = info.assignable_global { @@ -290,7 +293,8 @@ impl FunctionInfo { handle: Handle, assignable_global: &mut Option>, ) -> NonUniformResult { - let info = &mut self.expressions[handle.index()]; + //Note: similarly to `add_ref_impl`, this ignores invalid expressions. + let info = self.expressions.get_mut(handle.index())?; info.ref_count += 1; // propagate the assignable global up the chain, till it either hits // a value-type expression, or the assignment statement. @@ -629,7 +633,10 @@ impl FunctionInfo { S::Emit(ref range) => { let mut requirements = UniformityRequirements::empty(); for expr in range.clone() { - let req = self.expressions[expr.index()].uniformity.requirements; + let req = match self.expressions.get(expr.index()) { + Some(expr) => expr.uniformity.requirements, + None => UniformityRequirements::empty(), + }; #[cfg(feature = "validate")] if self .flags From 68b1ae1499b524c224157c87998f217faba32d10 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 18:27:43 -0500 Subject: [PATCH 1537/2212] typifier: handle forward expression dependencies --- src/front/mod.rs | 6 +- src/proc/typifier.rs | 192 +++++++++++++++++++++--------------------- src/valid/analyzer.rs | 9 +- 3 files changed, 109 insertions(+), 98 deletions(-) diff --git a/src/front/mod.rs b/src/front/mod.rs index 3264f0c35..80dfa87ac 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -94,7 +94,8 @@ impl Typifier { ) -> Result<(), ResolveError> { if self.resolutions.len() <= expr_handle.index() { for (eh, expr) in expressions.iter().skip(self.resolutions.len()) { - let resolution = ctx.resolve(expr, |h| &self.resolutions[h.index()])?; + //Note: the closure can't `Err` by construction + let resolution = ctx.resolve(expr, |h| Ok(&self.resolutions[h.index()]))?; log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); self.resolutions.push(resolution); } @@ -116,7 +117,8 @@ impl Typifier { self.grow(expr_handle, expressions, ctx) } else { let expr = &expressions[expr_handle]; - let resolution = ctx.resolve(expr, |h| &self.resolutions[h.index()])?; + //Note: the closure can't `Err` by construction + let resolution = ctx.resolve(expr, |h| Ok(&self.resolutions[h.index()]))?; self.resolutions[expr_handle.index()] = resolution; Ok(()) } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 6e237ee5a..220936df6 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -197,6 +197,8 @@ pub enum ResolveError { GlobalVariableNotFound(Handle), #[error("Function argument {0} doesn't exist")] FunctionArgumentNotFound(u32), + #[error("Expression {0:?} depends on expressions that follow")] + ExpressionForwardDependency(Handle), } pub struct ResolveContext<'a> { @@ -227,12 +229,12 @@ impl<'a> ResolveContext<'a> { pub fn resolve( &self, expr: &crate::Expression, - past: impl Fn(Handle) -> &'a TypeResolution, + past: impl Fn(Handle) -> Result<&'a TypeResolution, ResolveError>, ) -> Result { use crate::TypeInner as Ti; let types = self.types; Ok(match *expr { - crate::Expression::Access { base, .. } => match *past(base).inner_with(types) { + crate::Expression::Access { base, .. } => match *past(base)?.inner_with(types) { // Arrays and matrices can only be indexed dynamically behind a // pointer, but that's a validation error, not a type error, so // go ahead provide a type here. @@ -299,106 +301,108 @@ impl<'a> ResolveContext<'a> { }); } }, - crate::Expression::AccessIndex { base, index } => match *past(base).inner_with(types) { - Ti::Vector { size, kind, width } => { - if index >= size as u32 { - return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); - } - TypeResolution::Value(Ti::Scalar { kind, width }) - } - Ti::Matrix { - columns, - rows, - width, - } => { - if index >= columns as u32 { - return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); - } - TypeResolution::Value(crate::TypeInner::Vector { - size: rows, - kind: crate::ScalarKind::Float, - width, - }) - } - Ti::Array { base, .. } => TypeResolution::Handle(base), - Ti::Struct { ref members, .. } => { - let member = members - .get(index as usize) - .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; - TypeResolution::Handle(member.ty) - } - Ti::ValuePointer { - size: Some(size), - kind, - width, - class, - } => { - if index >= size as u32 { - return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); - } - TypeResolution::Value(Ti::ValuePointer { - size: None, - kind, - width, - class, - }) - } - Ti::Pointer { - base: ty_base, - class, - } => TypeResolution::Value(match types[ty_base].inner { - Ti::Array { base, .. } => Ti::Pointer { base, class }, + crate::Expression::AccessIndex { base, index } => { + match *past(base)?.inner_with(types) { Ti::Vector { size, kind, width } => { if index >= size as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } - Ti::ValuePointer { - size: None, - kind, - width, - class, - } + TypeResolution::Value(Ti::Scalar { kind, width }) } Ti::Matrix { - rows, columns, + rows, width, } => { if index >= columns as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); } - Ti::ValuePointer { - size: Some(rows), + TypeResolution::Value(crate::TypeInner::Vector { + size: rows, kind: crate::ScalarKind::Float, width, - class, - } + }) } + Ti::Array { base, .. } => TypeResolution::Handle(base), Ti::Struct { ref members, .. } => { let member = members .get(index as usize) .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; - Ti::Pointer { - base: member.ty, - class, - } + TypeResolution::Handle(member.ty) } + Ti::ValuePointer { + size: Some(size), + kind, + width, + class, + } => { + if index >= size as u32 { + return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); + } + TypeResolution::Value(Ti::ValuePointer { + size: None, + kind, + width, + class, + }) + } + Ti::Pointer { + base: ty_base, + class, + } => TypeResolution::Value(match types[ty_base].inner { + Ti::Array { base, .. } => Ti::Pointer { base, class }, + Ti::Vector { size, kind, width } => { + if index >= size as u32 { + return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); + } + Ti::ValuePointer { + size: None, + kind, + width, + class, + } + } + Ti::Matrix { + rows, + columns, + width, + } => { + if index >= columns as u32 { + return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); + } + Ti::ValuePointer { + size: Some(rows), + kind: crate::ScalarKind::Float, + width, + class, + } + } + Ti::Struct { ref members, .. } => { + let member = members + .get(index as usize) + .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; + Ti::Pointer { + base: member.ty, + class, + } + } + ref other => { + log::error!("Access index sub-type {:?}", other); + return Err(ResolveError::InvalidSubAccess { + ty: ty_base, + indexed: true, + }); + } + }), ref other => { - log::error!("Access index sub-type {:?}", other); - return Err(ResolveError::InvalidSubAccess { - ty: ty_base, + log::error!("Access index type {:?}", other); + return Err(ResolveError::InvalidAccess { + expr: base, indexed: true, }); } - }), - ref other => { - log::error!("Access index type {:?}", other); - return Err(ResolveError::InvalidAccess { - expr: base, - indexed: true, - }); } - }, + } crate::Expression::Constant(h) => match self.constants[h].inner { crate::ConstantInner::Scalar { width, ref value } => { TypeResolution::Value(Ti::Scalar { @@ -408,7 +412,7 @@ impl<'a> ResolveContext<'a> { } crate::ConstantInner::Composite { ty, components: _ } => TypeResolution::Handle(ty), }, - crate::Expression::Splat { size, value } => match *past(value).inner_with(types) { + crate::Expression::Splat { size, value } => match *past(value)?.inner_with(types) { Ti::Scalar { kind, width } => { TypeResolution::Value(Ti::Vector { size, kind, width }) } @@ -421,7 +425,7 @@ impl<'a> ResolveContext<'a> { size, vector, pattern: _, - } => match *past(vector).inner_with(types) { + } => match *past(vector)?.inner_with(types) { Ti::Vector { size: _, kind, @@ -464,7 +468,7 @@ impl<'a> ResolveContext<'a> { class: crate::StorageClass::Function, }) } - crate::Expression::Load { pointer } => match *past(pointer).inner_with(types) { + crate::Expression::Load { pointer } => match *past(pointer)?.inner_with(types) { Ti::Pointer { base, class: _ } => { if let Ti::Atomic { kind, width } = types[base].inner { TypeResolution::Value(Ti::Scalar { kind, width }) @@ -490,7 +494,7 @@ impl<'a> ResolveContext<'a> { image, gather: Some(_), .. - } => match *past(image).inner_with(types) { + } => match *past(image)?.inner_with(types) { Ti::Image { class, .. } => TypeResolution::Value(Ti::Vector { kind: match class { crate::ImageClass::Sampled { kind, multi: _ } => kind, @@ -505,7 +509,7 @@ impl<'a> ResolveContext<'a> { } }, crate::Expression::ImageSample { image, .. } - | crate::Expression::ImageLoad { image, .. } => match *past(image).inner_with(types) { + | crate::Expression::ImageLoad { image, .. } => match *past(image)?.inner_with(types) { Ti::Image { class, .. } => TypeResolution::Value(match class { crate::ImageClass::Depth { multi: _ } => Ti::Scalar { kind: crate::ScalarKind::Float, @@ -528,7 +532,7 @@ impl<'a> ResolveContext<'a> { } }, crate::Expression::ImageQuery { image, query } => TypeResolution::Value(match query { - crate::ImageQuery::Size { level: _ } => match *past(image).inner_with(types) { + crate::ImageQuery::Size { level: _ } => match *past(image)?.inner_with(types) { Ti::Image { dim, .. } => match dim { crate::ImageDimension::D1 => Ti::Scalar { kind: crate::ScalarKind::Sint, @@ -557,14 +561,14 @@ impl<'a> ResolveContext<'a> { width: 4, }, }), - crate::Expression::Unary { expr, .. } => past(expr).clone(), + crate::Expression::Unary { expr, .. } => past(expr)?.clone(), crate::Expression::Binary { op, left, right } => match op { crate::BinaryOperator::Add | crate::BinaryOperator::Subtract | crate::BinaryOperator::Divide - | crate::BinaryOperator::Modulo => past(left).clone(), + | crate::BinaryOperator::Modulo => past(left)?.clone(), crate::BinaryOperator::Multiply => { - let (res_left, res_right) = (past(left), past(right)); + let (res_left, res_right) = (past(left)?, past(right)?); match (res_left.inner_with(types), res_right.inner_with(types)) { ( &Ti::Matrix { @@ -623,7 +627,7 @@ impl<'a> ResolveContext<'a> { | crate::BinaryOperator::LogicalOr => { let kind = crate::ScalarKind::Bool; let width = crate::BOOL_WIDTH; - let inner = match *past(left).inner_with(types) { + let inner = match *past(left)?.inner_with(types) { Ti::Scalar { .. } => Ti::Scalar { kind, width }, Ti::Vector { size, .. } => Ti::Vector { size, kind, width }, ref other => { @@ -639,7 +643,7 @@ impl<'a> ResolveContext<'a> { | crate::BinaryOperator::ExclusiveOr | crate::BinaryOperator::InclusiveOr | crate::BinaryOperator::ShiftLeft - | crate::BinaryOperator::ShiftRight => past(left).clone(), + | crate::BinaryOperator::ShiftRight => past(left)?.clone(), }, crate::Expression::AtomicResult { kind, @@ -656,8 +660,8 @@ impl<'a> ResolveContext<'a> { TypeResolution::Value(Ti::Scalar { kind, width }) } } - crate::Expression::Select { accept, .. } => past(accept).clone(), - crate::Expression::Derivative { axis: _, expr } => past(expr).clone(), + crate::Expression::Select { accept, .. } => past(accept)?.clone(), + crate::Expression::Derivative { axis: _, expr } => past(expr)?.clone(), crate::Expression::Relational { fun, argument } => match fun { crate::RelationalFunction::All | crate::RelationalFunction::Any => { TypeResolution::Value(Ti::Scalar { @@ -668,7 +672,7 @@ impl<'a> ResolveContext<'a> { crate::RelationalFunction::IsNan | crate::RelationalFunction::IsInf | crate::RelationalFunction::IsFinite - | crate::RelationalFunction::IsNormal => match *past(argument).inner_with(types) { + | crate::RelationalFunction::IsNormal => match *past(argument)?.inner_with(types) { Ti::Scalar { .. } => TypeResolution::Value(Ti::Scalar { kind: crate::ScalarKind::Bool, width: crate::BOOL_WIDTH, @@ -694,7 +698,7 @@ impl<'a> ResolveContext<'a> { arg3: _, } => { use crate::MathFunction as Mf; - let res_arg = past(arg); + let res_arg = past(arg)?; match fun { // comparison Mf::Abs | @@ -748,7 +752,7 @@ impl<'a> ResolveContext<'a> { let arg1 = arg1.ok_or_else(|| ResolveError::IncompatibleOperands( format!("{:?}(_, None)", fun) ))?; - match (res_arg.inner_with(types), past(arg1).inner_with(types)) { + match (res_arg.inner_with(types), past(arg1)?.inner_with(types)) { (&Ti::Vector {kind: _, size: columns,width}, &Ti::Vector{ size: rows, .. }) => TypeResolution::Value(Ti::Matrix { columns, rows, width }), (left, right) => return Err(ResolveError::IncompatibleOperands( @@ -847,7 +851,7 @@ impl<'a> ResolveContext<'a> { expr, kind, convert, - } => match *past(expr).inner_with(types) { + } => match *past(expr)?.inner_with(types) { Ti::Scalar { kind: _, width } => TypeResolution::Value(Ti::Scalar { kind, width: convert.unwrap_or(width), diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 65d72572e..ee3ace7fd 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -10,7 +10,7 @@ use super::{CallError, ExpressionError, FunctionError, ModuleInfo, ShaderStages, use crate::span::{AddSpan as _, WithSpan}; use crate::{ arena::{Arena, Handle}, - proc::{ResolveContext, TypeResolution}, + proc::{ResolveContext, ResolveError, TypeResolution}, }; use std::ops; @@ -598,7 +598,12 @@ impl FunctionInfo { }, }; - let ty = resolve_context.resolve(expression, |h| &self.expressions[h.index()].ty)?; + let ty = resolve_context.resolve(expression, |h| { + self.expressions + .get(h.index()) + .map(|ei| &ei.ty) + .ok_or(ResolveError::ExpressionForwardDependency(h)) + })?; self.expressions[handle.index()] = ExpressionInfo { uniformity, ref_count: 0, From 0ec049fb9478420e1bed6a6e51b5c6b4ce86fb18 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 18:52:47 -0500 Subject: [PATCH 1538/2212] typifier: handle non-existing constants --- src/proc/typifier.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 220936df6..1ed0e8fda 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -197,6 +197,8 @@ pub enum ResolveError { GlobalVariableNotFound(Handle), #[error("Function argument {0} doesn't exist")] FunctionArgumentNotFound(u32), + #[error("Constant {0:?} doesn't exist")] + ConstantNotFound(Handle), #[error("Expression {0:?} depends on expressions that follow")] ExpressionForwardDependency(Handle), } @@ -403,15 +405,23 @@ impl<'a> ResolveContext<'a> { } } } - crate::Expression::Constant(h) => match self.constants[h].inner { - crate::ConstantInner::Scalar { width, ref value } => { - TypeResolution::Value(Ti::Scalar { - kind: value.scalar_kind(), - width, - }) + crate::Expression::Constant(h) => { + let constant = self + .constants + .try_get(h) + .ok_or(ResolveError::ConstantNotFound(h))?; + match constant.inner { + crate::ConstantInner::Scalar { width, ref value } => { + TypeResolution::Value(Ti::Scalar { + kind: value.scalar_kind(), + width, + }) + } + crate::ConstantInner::Composite { ty, components: _ } => { + TypeResolution::Handle(ty) + } } - crate::ConstantInner::Composite { ty, components: _ } => TypeResolution::Handle(ty), - }, + } crate::Expression::Splat { size, value } => match *past(value)?.inner_with(types) { Ti::Scalar { kind, width } => { TypeResolution::Value(Ti::Vector { size, kind, width }) From b12ed2cc9e2fb0aab858ed9281ad651340205b7f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 13 Jan 2022 18:57:57 -0500 Subject: [PATCH 1539/2212] Fix arbitrary for MSRV --- .github/workflows/pipeline.yml | 30 ++++++++++++++++++------- Cargo.toml | 41 +++++++++++++++++----------------- src/front/glsl/variables.rs | 27 +++++++++------------- src/front/spv/function.rs | 4 ++-- 4 files changed, 55 insertions(+), 47 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index c92721c18..d7f84efda 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -3,31 +3,45 @@ name: pipeline on: [push, pull_request] jobs: - test: - name: Test + test-msrv: + name: Test MSRV runs-on: ubuntu-latest - strategy: - matrix: - rust: ["1.43.0", nightly] steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: ${{ matrix.rust }} + toolchain: "1.43.0" override: true - uses: actions-rs/cargo@v1 name: Downgrade bitflags to MSRV - if: ${{ matrix.rust }} == "1.43.0" with: command: update args: -p bitflags --precise 1.2.1 - uses: actions-rs/cargo@v1 name: Downgrade indexmap to MSRV - if: ${{ matrix.rust }} == "1.43.0" with: command: update args: -p indexmap --precise 1.6.2 + - uses: actions-rs/cargo@v1 + name: Test all features + with: + # `cli` already enables most features, so let's add the rest, + # except for `arbitrary`, which requires Rust-1.51 + command: test + args: --workspace --features serialize,deserialize + - name: Check snapshots + run: git diff --exit-code -- tests/out + test: + name: Test Nightly + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly + override: true - uses: actions-rs/cargo@v1 name: Default test with: diff --git a/Cargo.toml b/Cargo.toml index a0dcec570..daaefb6c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,26 +14,6 @@ resolver = "2" [package.metadata.docs.rs] all-features = true -# MSRV warnings: -# - bitflags 1.3 requires Rust-1.46 -# - indexmap 1.7 requires Rust-1.49 - -[dependencies] -arbitrary = { version = "1", features = ["derive"], optional = true } -bitflags = "1" -bit-set = "0.5" -codespan-reporting = { version = "0.11.0", optional = true } -rustc-hash = "1.1.0" -indexmap = "1.6" -log = "0.4" -num-traits = "0.2" -spirv = { version = "0.2", optional = true } -thiserror = "1.0.21" -serde = { version = "1.0", features = ["derive"], optional = true } -petgraph = { version ="0.6", optional = true } -pp-rs = { version = "0.2.1", optional = true } -hexf-parse = { version = "0.2.1", optional = true } - [profile.release] panic = "abort" @@ -57,6 +37,27 @@ hlsl-out = [] span = ["codespan-reporting"] validate = [] +# MSRV warnings: +# - arbitrary 1.0.3 requires Rust-1.51 +# - bitflags 1.3 requires Rust-1.46 +# - indexmap 1.7 requires Rust-1.49 + +[dependencies] +arbitrary = { version = "1", features = ["derive"], optional = true } +bitflags = "1" +bit-set = "0.5" +codespan-reporting = { version = "0.11.0", optional = true } +rustc-hash = "1.1.0" +indexmap = "1.6" +log = "0.4" +num-traits = "0.2" +spirv = { version = "0.2", optional = true } +thiserror = "1.0.21" +serde = { version = "1.0", features = ["derive"], optional = true } +petgraph = { version ="0.6", optional = true } +pp-rs = { version = "0.2.1", optional = true } +hexf-parse = { version = "0.2.1", optional = true } + [dev-dependencies] diff = "0.1" ron = "0.7" diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index d4043c033..9a226916f 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -654,21 +654,14 @@ impl Parser { &mut self, ctx: &mut Context, body: &mut Block, - #[cfg_attr(not(feature = "glsl-validate"), allow(unused_variables))] - VarDeclaration { - qualifiers, - ty, - name, - init, - meta, - }: VarDeclaration, + decl: VarDeclaration, ) -> Result> { #[cfg(feature = "glsl-validate")] - if let Some(ref name) = name { + if let Some(ref name) = decl.name { if ctx.lookup_local_var_current_scope(name).is_some() { self.errors.push(Error { kind: ErrorKind::VariableAlreadyDeclared(name.clone()), - meta, + meta: decl.meta, }) } } @@ -676,7 +669,7 @@ impl Parser { let mut mutable = true; let mut precision = None; - for &(ref qualifier, meta) in qualifiers { + for &(ref qualifier, meta) in decl.qualifiers { match *qualifier { TypeQualifier::StorageQualifier(StorageQualifier::Const) => { if !mutable { @@ -707,15 +700,15 @@ impl Parser { let handle = ctx.locals.append( LocalVariable { - name: name.clone(), - ty, - init, + name: decl.name.clone(), + ty: decl.ty, + init: decl.init, }, - meta, + decl.meta, ); - let expr = ctx.add_expression(Expression::LocalVariable(handle), meta, body); + let expr = ctx.add_expression(Expression::LocalVariable(handle), decl.meta, body); - if let Some(name) = name { + if let Some(name) = decl.name { ctx.add_local_var(name, expr, mutable); } diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 23c47688e..efc785304 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -464,9 +464,9 @@ impl> super::Parser { *component = function.expressions.append(load_expr, span); } - match &members[..] { + match members[..] { [] => {} - [member] => { + [ref member] => { function.body.extend(emitter.finish(&function.expressions)); let span = function.expressions.get_span(components[0]); function.body.push( From d468e1512fe73f8c18e5c1f9c9d358d364e7f34c Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 14 Jan 2022 11:33:05 -0500 Subject: [PATCH 1540/2212] Introduce BadHandle error --- src/arena.rs | 14 ++++++++++-- src/back/spv/index.rs | 10 ++++++--- src/back/spv/mod.rs | 2 -- src/proc/index.rs | 49 +++++++++++++++++++++++------------------ src/proc/layouter.rs | 8 +++---- src/proc/mod.rs | 19 +++++----------- src/proc/typifier.rs | 25 +++++---------------- src/valid/expression.rs | 29 +++++++----------------- src/valid/function.rs | 16 ++++++-------- src/valid/type.rs | 23 ++++++++++--------- 10 files changed, 91 insertions(+), 104 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 56f70e94d..8b5ba84b4 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -8,6 +8,13 @@ type Index = NonZeroU32; use crate::Span; use indexmap::set::IndexSet; +#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq)] +#[error("Handle {index} of {kind} is either not present, or inaccessible yet")] +pub struct BadHandle { + pub kind: &'static str, + pub index: usize, +} + /// A strongly typed reference to an arena item. /// /// A `Handle` value can be used as an index into an [`Arena`] or [`UniqueArena`]. @@ -265,8 +272,11 @@ impl Arena { self.fetch_if_or_append(value, span, T::eq) } - pub fn try_get(&self, handle: Handle) -> Option<&T> { - self.data.get(handle.index()) + pub fn try_get(&self, handle: Handle) -> Result<&T, BadHandle> { + self.data.get(handle.index()).ok_or_else(|| BadHandle { + kind: std::any::type_name::(), + index: handle.index(), + }) } /// Get a mutable reference to an element in the arena. diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index c2b198048..8edde1f5f 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -79,14 +79,18 @@ impl<'w> BlockContext<'w> { block: &mut Block, ) -> Result, Error> { let sequence_ty = self.fun_info[sequence].ty.inner_with(&self.ir_module.types); - match sequence_ty.indexable_length(self.ir_module)? { - crate::proc::IndexableLength::Known(known_length) => { + match sequence_ty.indexable_length(self.ir_module) { + Ok(crate::proc::IndexableLength::Known(known_length)) => { Ok(MaybeKnown::Known(known_length)) } - crate::proc::IndexableLength::Dynamic => { + Ok(crate::proc::IndexableLength::Dynamic) => { let length_id = self.write_runtime_array_length(sequence, block)?; Ok(MaybeKnown::Computed(length_id)) } + Err(err) => { + log::error!("Sequence length for {:?} failed: {}", sequence, err); + Err(Error::Validation("indexable length")) + } } } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 8dc574dfe..469fa13d6 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -66,8 +66,6 @@ pub enum Error { FeatureNotImplemented(&'static str), #[error("module is not validated properly: {0}")] Validation(&'static str), - #[error(transparent)] - Proc(#[from] crate::proc::ProcError), } #[derive(Default)] diff --git a/src/proc/index.rs b/src/proc/index.rs index ae20cc5d6..e35537bd3 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -1,8 +1,6 @@ //! Definitions for index bounds checking. -use super::ProcError; -use crate::valid; -use crate::{Handle, UniqueArena}; +use crate::{valid, Handle, UniqueArena}; use bit_set::BitSet; /// How should code generated by Naga do bounds checks? @@ -300,6 +298,14 @@ impl GuardedIndex { } } +#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq)] +pub enum IndexableLengthError { + #[error("Type is not indexable, and has no length (validation error)")] + TypeNotIndexable, + #[error("Array length constant {0:?} is invalid")] + InvalidArrayLength(Handle), +} + impl crate::TypeInner { /// Return the length of a subscriptable type. /// @@ -312,7 +318,10 @@ impl crate::TypeInner { /// The value returned is appropriate for bounds checks on subscripting. /// /// Return an error if `self` does not describe a subscriptable type at all. - pub fn indexable_length(&self, module: &crate::Module) -> Result { + pub fn indexable_length( + &self, + module: &crate::Module, + ) -> Result { use crate::TypeInner as Ti; let known_length = match *self { Ti::Vector { size, .. } => size as _, @@ -332,10 +341,10 @@ impl crate::TypeInner { Ti::Vector { size, .. } => size as _, Ti::Matrix { columns, .. } => columns as _, Ti::Array { size, .. } => return size.to_indexable_length(module), - _ => return Err(ProcError::TypeNotIndexable), + _ => return Err(IndexableLengthError::TypeNotIndexable), } } - _ => return Err(ProcError::TypeNotIndexable), + _ => return Err(IndexableLengthError::TypeNotIndexable), }; Ok(IndexableLength::Known(known_length)) } @@ -355,25 +364,23 @@ pub enum IndexableLength { } impl crate::ArraySize { - pub fn to_indexable_length(self, module: &crate::Module) -> Result { - use crate::Constant as K; + pub fn to_indexable_length( + self, + module: &crate::Module, + ) -> Result { Ok(match self { - Self::Constant(k) => match module.constants[k] { - K { - specialization: Some(_), - .. - } => { + Self::Constant(k) => { + let constant = &module.constants[k]; + if constant.specialization.is_some() { // Specializable constants are not supported as array lengths. // See valid::TypeError::UnsupportedSpecializedArrayLength. - return Err(ProcError::InvalidArraySizeConstant(k)); + return Err(IndexableLengthError::InvalidArrayLength(k)); } - ref unspecialized => { - let length = unspecialized - .to_array_length() - .ok_or(ProcError::InvalidArraySizeConstant(k))?; - IndexableLength::Known(length) - } - }, + let length = constant + .to_array_length() + .ok_or(IndexableLengthError::InvalidArrayLength(k))?; + IndexableLength::Known(length) + } Self::Dynamic => IndexableLength::Dynamic, }) } diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 637257c17..1f3651d8e 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -1,4 +1,4 @@ -use crate::arena::{Arena, Handle, UniqueArena}; +use crate::arena::{Arena, BadHandle, Handle, UniqueArena}; use std::{num::NonZeroU32, ops}; pub type Alignment = NonZeroU32; @@ -37,8 +37,8 @@ pub enum TypeLayoutError { InvalidStructMemberType(u32, Handle), #[error("Zero width is not supported")] ZeroWidth, - #[error(transparent)] - Size(#[from] super::ProcError), + #[error("Array size is a bad handle")] + BadHandle(#[from] BadHandle), } #[derive(Clone, Copy, Debug, PartialEq, thiserror::Error)] @@ -95,7 +95,7 @@ impl Layouter { let size = ty .inner .size(constants) - .map_err(|error| TypeLayoutError::Size(error).with(ty_handle))?; + .map_err(|error| TypeLayoutError::BadHandle(error).with(ty_handle))?; let layout = match ty.inner { Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => TypeLayout { size, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 79fd078ec..015694a37 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -8,20 +8,12 @@ mod typifier; use std::cmp::PartialEq; -pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength}; +pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength, IndexableLengthError}; pub use layouter::{Alignment, LayoutError, Layouter, TypeLayout, TypeLayoutError}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, TypeResolution}; -#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq)] -pub enum ProcError { - #[error("Type is not indexable, and has no length (validation error)")] - TypeNotIndexable, - #[error("Array length {0:?} is wrong kind of constant (validation error)")] - InvalidArraySizeConstant(crate::Handle), -} - impl From for super::ScalarKind { fn from(format: super::StorageFormat) -> Self { use super::{ScalarKind as Sk, StorageFormat as Sf}; @@ -94,7 +86,10 @@ impl super::TypeInner { } } - pub fn size(&self, constants: &super::Arena) -> Result { + pub fn size( + &self, + constants: &super::Arena, + ) -> Result { Ok(match *self { Self::Scalar { kind: _, width } | Self::Atomic { kind: _, width } => width as u32, Self::Vector { @@ -119,9 +114,7 @@ impl super::TypeInner { } => { let count = match size { super::ArraySize::Constant(handle) => { - let constant = constants - .try_get(handle) - .ok_or(ProcError::InvalidArraySizeConstant(handle))?; + let constant = constants.try_get(handle)?; constant.to_array_length().unwrap_or(1) } // A dynamically-sized array has to have at least one element diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 1ed0e8fda..0879c1f6f 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -1,4 +1,4 @@ -use crate::arena::{Arena, Handle, UniqueArena}; +use crate::arena::{Arena, BadHandle, Handle, UniqueArena}; use thiserror::Error; @@ -162,6 +162,8 @@ impl crate::ConstantInner { #[derive(Clone, Debug, Error, PartialEq)] pub enum ResolveError { + #[error(transparent)] + BadHandle(#[from] BadHandle), #[error("Index {index} is out of bounds for expression {expr:?}")] OutOfBoundsIndex { expr: Handle, @@ -191,14 +193,8 @@ pub enum ResolveError { FunctionReturnsVoid, #[error("Incompatible operands: {0}")] IncompatibleOperands(String), - #[error("Local var {0:?} doesn't exist")] - LocalVariableNotFound(Handle), - #[error("Global var {0:?} doesn't exist")] - GlobalVariableNotFound(Handle), #[error("Function argument {0} doesn't exist")] FunctionArgumentNotFound(u32), - #[error("Constant {0:?} doesn't exist")] - ConstantNotFound(Handle), #[error("Expression {0:?} depends on expressions that follow")] ExpressionForwardDependency(Handle), } @@ -406,10 +402,7 @@ impl<'a> ResolveContext<'a> { } } crate::Expression::Constant(h) => { - let constant = self - .constants - .try_get(h) - .ok_or(ResolveError::ConstantNotFound(h))?; + let constant = self.constants.try_get(h)?; match constant.inner { crate::ConstantInner::Scalar { width, ref value } => { TypeResolution::Value(Ti::Scalar { @@ -455,10 +448,7 @@ impl<'a> ResolveContext<'a> { TypeResolution::Handle(arg.ty) } crate::Expression::GlobalVariable(h) => { - let var = self - .global_vars - .try_get(h) - .ok_or(ResolveError::GlobalVariableNotFound(h))?; + let var = self.global_vars.try_get(h)?; if var.class == crate::StorageClass::Handle { TypeResolution::Handle(var.ty) } else { @@ -469,10 +459,7 @@ impl<'a> ResolveContext<'a> { } } crate::Expression::LocalVariable(h) => { - let var = self - .local_vars - .try_get(h) - .ok_or(ResolveError::LocalVariableNotFound(h))?; + let var = self.local_vars.try_get(h)?; TypeResolution::Value(Ti::Pointer { base: var.ty, class: crate::StorageClass::Function, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 4e59a9ef4..80d3c8216 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -4,8 +4,8 @@ use super::{compose::validate_compose, FunctionInfo, ShaderStages, TypeFlags}; use crate::arena::UniqueArena; use crate::{ - arena::Handle, - proc::{ProcError, ResolveError}, + arena::{BadHandle, Handle}, + proc::{IndexableLengthError, ResolveError}, }; #[derive(Clone, Debug, thiserror::Error)] @@ -17,6 +17,8 @@ pub enum ExpressionError { NotInScope, #[error("Depends on {0:?}, which has not been processed yet")] ForwardDependency(Handle), + #[error(transparent)] + BadDependency(#[from] BadHandle), #[error("Base type {0:?} is not compatible with this expression")] InvalidBaseType(Handle), #[error("Accessing with index {0:?} can't be done")] @@ -27,12 +29,6 @@ pub enum ExpressionError { IndexMustBeConstant(Handle), #[error("Function argument {0:?} doesn't exist")] FunctionArgumentDoesntExist(u32), - #[error("Constant {0:?} doesn't exist")] - ConstantDoesntExist(Handle), - #[error("Global variable {0:?} doesn't exist")] - GlobalVarDoesntExist(Handle), - #[error("Local variable {0:?} doesn't exist")] - LocalVarDoesntExist(Handle), #[error("Loading of {0:?} can't be done")] InvalidPointerType(Handle), #[error("Array length of {0:?} can't be done")] @@ -46,7 +42,7 @@ pub enum ExpressionError { #[error(transparent)] Compose(#[from] super::ComposeError), #[error(transparent)] - Proc(#[from] ProcError), + IndexableLength(#[from] IndexableLengthError), #[error("Operation {0:?} can't work with {1:?}")] InvalidUnaryOperandType(crate::UnaryOperator, Handle), #[error("Operation {0:?} can't work with {1:?} and {2:?}")] @@ -266,10 +262,7 @@ impl super::Validator { ShaderStages::all() } E::Constant(handle) => { - let _ = module - .constants - .try_get(handle) - .ok_or(ExpressionError::ConstantDoesntExist(handle))?; + let _ = module.constants.try_get(handle)?; ShaderStages::all() } E::Splat { size: _, value } => match *resolver.resolve(value)? { @@ -319,17 +312,11 @@ impl super::Validator { ShaderStages::all() } E::GlobalVariable(handle) => { - let _ = module - .global_variables - .try_get(handle) - .ok_or(ExpressionError::GlobalVarDoesntExist(handle))?; + let _ = module.global_variables.try_get(handle)?; ShaderStages::all() } E::LocalVariable(handle) => { - let _ = function - .local_variables - .try_get(handle) - .ok_or(ExpressionError::LocalVarDoesntExist(handle))?; + let _ = function.local_variables.try_get(handle)?; ShaderStages::all() } E::Load { pointer } => { diff --git a/src/valid/function.rs b/src/valid/function.rs index 491cee54b..c6524872f 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -1,6 +1,6 @@ -use crate::arena::Handle; #[cfg(feature = "validate")] use crate::arena::{Arena, UniqueArena}; +use crate::arena::{BadHandle, Handle}; use super::{ analyzer::{UniformityDisruptor, UniformityRequirements}, @@ -16,8 +16,8 @@ use bit_set::BitSet; #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum CallError { - #[error("Bad function")] - InvalidFunction, + #[error(transparent)] + BadHandle(#[from] BadHandle), #[error("The callee is declared after the caller")] ForwardDeclaredFunction, #[error("Argument {index} expression is invalid")] @@ -67,6 +67,8 @@ pub enum LocalVariableError { #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum FunctionError { + #[error(transparent)] + BadHandle(#[from] BadHandle), #[error("Expression {handle:?} is invalid")] Expression { handle: Handle, @@ -121,8 +123,6 @@ pub enum FunctionError { pointer: Handle, value: Handle, }, - #[error("The expression {0:?} is currupted")] - InvalidExpression(Handle), #[error("Image store parameters are invalid")] InvalidImageStore(#[source] ExpressionError), #[error("Call to {function:?} is invalid")] @@ -201,9 +201,7 @@ impl<'a> BlockContext<'a> { &self, handle: Handle, ) -> Result<&'a crate::Expression, FunctionError> { - self.expressions - .try_get(handle) - .ok_or(FunctionError::InvalidExpression(handle)) + Ok(self.expressions.try_get(handle)?) } fn resolve_type_impl( @@ -256,7 +254,7 @@ impl super::Validator { let fun = context .functions .try_get(function) - .ok_or(CallError::InvalidFunction) + .map_err(CallError::BadHandle) .map_err(WithSpan::new)?; if fun.arguments.len() != arguments.len() { return Err(CallError::ArgumentCount { diff --git a/src/valid/type.rs b/src/valid/type.rs index 570e8efcc..b7240578c 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -1,6 +1,6 @@ use super::Capabilities; use crate::{ - arena::{Arena, Handle, UniqueArena}, + arena::{Arena, BadHandle, Handle, UniqueArena}, proc::Alignment, }; @@ -72,6 +72,8 @@ pub enum Disalignment { #[derive(Clone, Debug, thiserror::Error)] pub enum TypeError { + #[error(transparent)] + BadHandle(#[from] BadHandle), #[error("The {0:?} scalar width {1} is not supported")] InvalidWidth(crate::ScalarKind, crate::Bytes), #[error("The {0:?} scalar width {1} is not supported for an atomic")] @@ -375,11 +377,12 @@ impl super::Validator { let sized_flag = match size { crate::ArraySize::Constant(const_handle) => { - let length_is_positive = match constants.try_get(const_handle) { - Some(&crate::Constant { + let constant = constants.try_get(const_handle)?; + let length_is_positive = match *constant { + crate::Constant { specialization: Some(_), .. - }) => { + } => { // Many of our back ends don't seem to support // specializable array lengths. If you want to try to make // this work, be sure to address all uses of @@ -389,28 +392,28 @@ impl super::Validator { const_handle, )); } - Some(&crate::Constant { + crate::Constant { inner: crate::ConstantInner::Scalar { width: _, value: crate::ScalarValue::Uint(length), }, .. - }) => length > 0, + } => length > 0, // Accept a signed integer size to avoid // requiring an explicit uint // literal. Type inference should make // this unnecessary. - Some(&crate::Constant { + crate::Constant { inner: crate::ConstantInner::Scalar { width: _, value: crate::ScalarValue::Sint(length), }, .. - }) => length > 0, - other => { - log::warn!("Array size {:?}", other); + } => length > 0, + _ => { + log::warn!("Array size {:?}", constant); return Err(TypeError::InvalidArraySizeConstant(const_handle)); } }; From a89e248d6805f56ce71a7140990c2858d1ab12d5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 14 Jan 2022 12:41:55 -0500 Subject: [PATCH 1541/2212] layouter: let size() panic --- src/back/hlsl/storage.rs | 4 ++-- src/back/msl/writer.rs | 7 +++---- src/front/glsl/functions.rs | 5 +---- src/front/glsl/types.rs | 5 +---- src/front/spv/mod.rs | 4 ++-- src/proc/layouter.rs | 2 +- src/proc/mod.rs | 10 ++++++++-- src/valid/type.rs | 4 ++-- 8 files changed, 20 insertions(+), 21 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 08909802b..a66f3e139 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -148,7 +148,7 @@ impl super::Writer<'_, W> { } => { write!(self.out, "{{")?; let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.size(&module.constants).unwrap(); + let stride = module.types[base].inner.size(&module.constants); let iter = (0..count).map(|i| (TypeResolution::Handle(base), stride * i)); self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; write!(self.out, "}}")?; @@ -311,7 +311,7 @@ impl super::Writer<'_, W> { writeln!(self.out, ";")?; // then iterate the stores let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.size(&module.constants).unwrap(); + let stride = module.types[base].inner.size(&module.constants); for i in 0..count { self.temp_access_chain.push(SubAccess::Offset(i * stride)); let sv = StoreValue::TempIndex { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 9533e5076..2af88e240 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -349,7 +349,7 @@ fn should_pack_struct_member( } let ty_inner = &module.types[member.ty].inner; - let last_offset = member.offset + ty_inner.size(&module.constants).unwrap(); + let last_offset = member.offset + ty_inner.size(&module.constants); let next_offset = match members.get(index + 1) { Some(next) => next.offset, None => span, @@ -754,8 +754,7 @@ impl Writer { crate::TypeInner::Array { base, stride, .. } => ( context.module.types[base] .inner - .size(&context.module.constants) - .unwrap(), + .size(&context.module.constants), stride, ), _ => return Err(Error::Validation), @@ -2380,7 +2379,7 @@ impl Writer { writeln!(self.out, "{}char _pad{}[{}];", back::INDENT, index, pad)?; } let ty_inner = &module.types[member.ty].inner; - last_offset = member.offset + ty_inner.size(&module.constants).unwrap(); + last_offset = member.offset + ty_inner.size(&module.constants); let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index d565b0022..57142f412 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1293,10 +1293,7 @@ impl Parser { offset: span, }); - span += self.module.types[ty] - .inner - .size(&self.module.constants) - .unwrap(); + span += self.module.types[ty].inner.size(&self.module.constants); let len = expressions.len(); let load = expressions.append(Expression::Load { pointer }, Default::default()); diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 106104378..aee13c77f 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -262,10 +262,7 @@ impl Parser { array_specifier .map(|(size, size_meta)| { meta.subsume(size_meta); - let stride = self.module.types[base] - .inner - .size(&self.module.constants) - .unwrap(); + let stride = self.module.types[base].inner.size(&self.module.constants); self.module.types.insert( Type { name: None, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index f6f7db14d..ab669c705 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -4078,7 +4078,7 @@ impl> Parser { size: crate::ArraySize::Constant(length_const.handle), stride: match decor.array_stride { Some(stride) => stride.get(), - None => module.types[base].inner.size(&module.constants).unwrap(), + None => module.types[base].inner.size(&module.constants), }, }; self.lookup_type.insert( @@ -4115,7 +4115,7 @@ impl> Parser { size: crate::ArraySize::Dynamic, stride: match decor.array_stride { Some(stride) => stride.get(), - None => module.types[base].inner.size(&module.constants).unwrap(), + None => module.types[base].inner.size(&module.constants), }, }; self.lookup_type.insert( diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 1f3651d8e..2ce334492 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -94,7 +94,7 @@ impl Layouter { for (ty_handle, ty) in types.iter().skip(self.layouts.len()) { let size = ty .inner - .size(constants) + .try_size(constants) .map_err(|error| TypeLayoutError::BadHandle(error).with(ty_handle))?; let layout = match ty.inner { Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => TypeLayout { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 015694a37..c5bb1954b 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -86,7 +86,7 @@ impl super::TypeInner { } } - pub fn size( + pub fn try_size( &self, constants: &super::Arena, ) -> Result { @@ -127,6 +127,12 @@ impl super::TypeInner { }) } + /// Get the size of this type. Panics if the `constants` doesn't contain + /// a referenced handle. This may not happen in a properly validated IR module. + pub fn size(&self, constants: &super::Arena) -> u32 { + self.try_size(constants).unwrap() + } + /// Return the canoncal form of `self`, or `None` if it's already in /// canonical form. /// @@ -443,6 +449,6 @@ fn test_matrix_size() { width: 4 } .size(&constants), - Ok(48), + 48, ); } diff --git a/src/valid/type.rs b/src/valid/type.rs index b7240578c..7fc1a6466 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -329,7 +329,7 @@ impl super::Validator { } //Note: `unwrap()` is fine, since `Layouter` goes first and calls it - let base_size = types[base].inner.size(constants).unwrap(); + let base_size = types[base].inner.size(constants); if stride < base_size { return Err(TypeError::InsufficientArrayStride { stride, base_size }); } @@ -484,7 +484,7 @@ impl super::Validator { } //Note: `unwrap()` is fine because `Layouter` goes first and checks this - let base_size = types[member.ty].inner.size(constants).unwrap(); + let base_size = types[member.ty].inner.size(constants); min_offset = member.offset + base_size; if min_offset > span { return Err(TypeError::MemberOutOfBounds { From 955e02eb1782690ae35e2e6673a30f77a1cfd4b5 Mon Sep 17 00:00:00 2001 From: Noel Tautges Date: Fri, 14 Jan 2022 17:43:00 -0600 Subject: [PATCH 1542/2212] Ignore .vscode --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index df4cb1d39..e0e95c107 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ Cargo.lock .DS_Store .fuse_hidden* .idea +.vscode /*.dot /*.metal /*.metallib From b42bf8768ef4fbb65e4df9819a930fbcf0dee3a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 15 Jan 2022 14:49:38 +0000 Subject: [PATCH 1543/2212] glsl-out: Write correct argument name when skipping samplers --- src/back/glsl/mod.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 239cb0a15..707b25b05 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1178,12 +1178,13 @@ impl<'a, W: Write> Writer<'a, W> { }; let arguments: Vec<_> = arguments .iter() - .filter(|arg| match self.module.types[arg.ty].inner { + .enumerate() + .filter(|&(_, arg)| match self.module.types[arg.ty].inner { TypeInner::Sampler { .. } => false, _ => true, }) .collect(); - self.write_slice(&arguments, |this, i, arg| { + self.write_slice(&arguments, |this, _, &(i, arg)| { // Write the argument type match this.module.types[arg.ty].inner { // We treat images separately because they might require @@ -1221,7 +1222,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the argument name // The leading space is important - write!(this.out, " {}", &this.names[&ctx.argument_key(i)])?; + write!(this.out, " {}", &this.names[&ctx.argument_key(i as u32)])?; Ok(()) })?; From 91ca923553762fccd85aa3d7908eb09cb8ce402d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 15 Jan 2022 00:13:23 +0000 Subject: [PATCH 1544/2212] glsl-out: Add support for push constant emulation --- src/back/glsl/features.rs | 9 ++++++- src/back/glsl/mod.rs | 41 +++++++++++++++++++++--------- tests/in/functions-webgl.param.ron | 1 + tests/in/interpolate.param.ron | 1 + tests/in/quad.param.ron | 1 + tests/in/skybox.param.ron | 1 + 6 files changed, 41 insertions(+), 13 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 0d7855899..3f300ddf6 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -343,6 +343,8 @@ impl<'a, W> Writer<'a, W> { } } + let mut push_constant_used = false; + for (handle, global) in self.module.global_variables.iter() { if ep_info[handle].is_empty() { continue; @@ -350,7 +352,12 @@ impl<'a, W> Writer<'a, W> { match global.class { StorageClass::WorkGroup => self.features.request(Features::COMPUTE_SHADER), StorageClass::Storage { .. } => self.features.request(Features::BUFFER_STORAGE), - StorageClass::PushConstant => return Err(Error::PushConstantNotSupported), + StorageClass::PushConstant => { + if push_constant_used { + return Err(Error::MultiplePushConstants); + } + push_constant_used = true; + } _ => {} } } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 707b25b05..fd408d10a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -86,7 +86,9 @@ impl crate::AtomicFunction { impl crate::StorageClass { fn is_buffer(&self) -> bool { match *self { - crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => true, + crate::StorageClass::PushConstant + | crate::StorageClass::Uniform + | crate::StorageClass::Storage { .. } => true, _ => false, } } @@ -96,6 +98,7 @@ impl crate::StorageClass { match *self { crate::StorageClass::WorkGroup | crate::StorageClass::Uniform + | crate::StorageClass::PushConstant | crate::StorageClass::Storage { .. } => false, _ => true, } @@ -227,6 +230,8 @@ pub struct Options { pub writer_flags: WriterFlags, /// Map of resources association to binding locations. pub binding_map: BindingMap, + /// The binding to give the push constant buffer if it's present + pub push_constant_binding: u32, } impl Default for Options { @@ -235,6 +240,7 @@ impl Default for Options { version: Version::Embedded(310), writer_flags: WriterFlags::ADJUST_COORDINATE_SPACE, binding_map: BindingMap::default(), + push_constant_binding: 0, } } } @@ -257,6 +263,7 @@ pub struct PipelineOptions { pub struct ReflectionInfo { pub texture_mapping: crate::FastHashMap, pub uniforms: crate::FastHashMap, String>, + pub push_constant: Option, } /// Structure that connects a texture to a sampler or not @@ -348,10 +355,10 @@ pub enum Error { /// Contains the missing [`Features`](Features) #[error("The selected version doesn't support {0:?}")] MissingFeatures(Features), - /// [`StorageClass::PushConstant`](crate::StorageClass::PushConstant) was used and isn't - /// supported in the glsl backend - #[error("Push constants aren't supported")] - PushConstantNotSupported, + /// [`StorageClass::PushConstant`](crate::StorageClass::PushConstant) was used more than + /// once in the entry point which isn't supported + #[error("Multiple push constants aren't supported")] + MultiplePushConstants, /// The specified [`Version`](Version) isn't supported #[error("The specified version isn't supported")] VersionNotSupported, @@ -887,7 +894,13 @@ impl<'a, W: Write> Writer<'a, W> { global: &crate::GlobalVariable, ) -> BackendResult { if self.options.version.supports_explicit_locations() { - if let Some(ref br) = global.binding { + if let crate::StorageClass::PushConstant = global.class { + write!( + self.out, + "layout(std140, binding = {}) ", + self.options.push_constant_binding + )? + } else if let Some(ref br) = global.binding { match self.options.binding_map.get(br) { Some(binding) => { let layout = match global.class { @@ -898,7 +911,9 @@ impl<'a, W: Write> Writer<'a, W> { "std140, " } } - crate::StorageClass::Uniform => "std140, ", + crate::StorageClass::Uniform | crate::StorageClass::PushConstant => { + "std140, " + } _ => "", }; write!(self.out, "layout({}binding = {}) ", layout, binding)? @@ -2853,15 +2868,12 @@ impl<'a, W: Write> Writer<'a, W> { } /// Helper method used to produce the reflection info that's returned to the user - /// - /// It takes an iterator of [`Function`](crate::Function) references instead of - /// [`Handle`](crate::arena::Handle) because [`EntryPoint`](crate::EntryPoint) isn't in any - /// [`Arena`](crate::arena::Arena) and we need to traverse it fn collect_reflection_info(&self) -> Result { use std::collections::hash_map::Entry; let info = self.info.get_entry_point(self.entry_point_idx as usize); let mut texture_mapping = crate::FastHashMap::default(); let mut uniforms = crate::FastHashMap::default(); + let mut push_constant = None; for sampling in info.sampling_set.iter() { let tex_name = self.reflection_names_globals[&sampling.image].clone(); @@ -2892,6 +2904,10 @@ impl<'a, W: Write> Writer<'a, W> { let name = self.reflection_names_globals[&handle].clone(); uniforms.insert(handle, name); } + crate::StorageClass::PushConstant => { + let name = self.reflection_names_globals[&handle].clone(); + push_constant = Some(name) + } _ => (), }, crate::TypeInner::Image { .. } => { @@ -2915,6 +2931,7 @@ impl<'a, W: Write> Writer<'a, W> { Ok(ReflectionInfo { texture_mapping, uniforms, + push_constant, }) } } @@ -3022,7 +3039,7 @@ fn glsl_storage_class(class: crate::StorageClass) -> Option<&'static str> { Sc::Uniform => Some("uniform"), Sc::Handle => Some("uniform"), Sc::WorkGroup => Some("shared"), - Sc::PushConstant => None, + Sc::PushConstant => Some("uniform"), } } diff --git a/tests/in/functions-webgl.param.ron b/tests/in/functions-webgl.param.ron index bc3dd4a8d..1d84e945b 100644 --- a/tests/in/functions-webgl.param.ron +++ b/tests/in/functions-webgl.param.ron @@ -3,5 +3,6 @@ version: Embedded(300), writer_flags: (bits: 0), binding_map: {}, + push_constant_binding: 0, ), ) diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index cb08368c8..bfea94342 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -10,5 +10,6 @@ version: Desktop(400), writer_flags: (bits: 0), binding_map: {}, + push_constant_binding: 0, ), ) diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index acde3aed4..c969a84b2 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -8,5 +8,6 @@ version: Embedded(300), writer_flags: (bits: 0), binding_map: {}, + push_constant_binding: 0, ), ) diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 9c9bd1f30..ea040e4fb 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -43,6 +43,7 @@ (group: 0, binding: 0): 0, (group: 0, binding: 1): 0, }, + push_constant_binding: 0, ), hlsl: ( shader_model: V5_1, From a1840beb1a96c9a49980fe3efa8e2f3dcd88abe6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 16 Jan 2022 12:42:57 +0000 Subject: [PATCH 1545/2212] glsl-out: Add test for push constants --- tests/in/push-constants.param.ron | 9 ++++++++ tests/in/push-constants.wgsl | 13 +++++++++++ .../glsl/push-constants.main.Fragment.glsl | 23 +++++++++++++++++++ tests/snapshots.rs | 1 + 4 files changed, 46 insertions(+) create mode 100644 tests/in/push-constants.param.ron create mode 100644 tests/in/push-constants.wgsl create mode 100644 tests/out/glsl/push-constants.main.Fragment.glsl diff --git a/tests/in/push-constants.param.ron b/tests/in/push-constants.param.ron new file mode 100644 index 000000000..4e25193b0 --- /dev/null +++ b/tests/in/push-constants.param.ron @@ -0,0 +1,9 @@ +( + god_mode: true, + glsl: ( + version: Embedded(320), + writer_flags: (bits: 0), + binding_map: {}, + push_constant_binding: 4, + ), +) diff --git a/tests/in/push-constants.wgsl b/tests/in/push-constants.wgsl new file mode 100644 index 000000000..bb5b0e732 --- /dev/null +++ b/tests/in/push-constants.wgsl @@ -0,0 +1,13 @@ +struct PushConstants { + multiplier: f32; +}; +var pc: PushConstants; + +struct FragmentIn { + [[location(0)]] color: vec4; +}; + +[[stage(fragment)]] +fn main(in: FragmentIn) -> [[location(0)]] vec4 { + return in.color * pc.multiplier; +} diff --git a/tests/out/glsl/push-constants.main.Fragment.glsl b/tests/out/glsl/push-constants.main.Fragment.glsl new file mode 100644 index 000000000..3a9f896c3 --- /dev/null +++ b/tests/out/glsl/push-constants.main.Fragment.glsl @@ -0,0 +1,23 @@ +#version 320 es + +precision highp float; +precision highp int; + +struct PushConstants { + float multiplier; +}; +struct FragmentIn { + vec4 color; +}; +layout(std140, binding = 4) uniform PushConstants_block_0Fragment { PushConstants pc; }; + +layout(location = 0) smooth in vec4 _vs2fs_location0; +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + FragmentIn in_ = FragmentIn(_vs2fs_location0); + float _e4 = pc.multiplier; + _fs2p_location0 = (in_.color * _e4); + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index dbc86b682..dd3bd0ccc 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -439,6 +439,7 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::HLSL | Targets::WGSL | Targets::GLSL, ), ("extra", Targets::SPIRV | Targets::METAL | Targets::WGSL), + ("push-constants", Targets::GLSL), ( "operators", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From 76814a83a20391b690ecf4e4a455d8a5768ac3be Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 18 Jan 2022 15:17:59 -0500 Subject: [PATCH 1546/2212] msl: inject point size if needed --- src/back/msl/mod.rs | 10 +--- src/back/msl/writer.rs | 94 +++++++++++++++++++++++++----------- tests/in/interface.param.ron | 3 ++ tests/out/msl/interface.msl | 3 +- tests/snapshots.rs | 11 +++-- 5 files changed, 78 insertions(+), 43 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 4295ae0e9..311f5e374 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -196,7 +196,7 @@ impl Default for Options { } // A subset of options that are meant to be changed per pipeline. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct PipelineOptions { @@ -205,14 +205,6 @@ pub struct PipelineOptions { pub allow_point_size: bool, } -impl Default for PipelineOptions { - fn default() -> Self { - PipelineOptions { - allow_point_size: true, - } - } -} - impl Options { fn resolve_local_binding( &self, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 2af88e240..0e2f53a64 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -46,10 +46,7 @@ impl<'a> Display for TypeContext<'a> { match kind { // work around Metal toolchain bug with `uint` typedef crate::ScalarKind::Uint => write!(out, "{}::uint", NAMESPACE), - _ => { - let kind_str = kind.to_msl_name(); - write!(out, "{}", kind_str) - } + _ => write!(out, "{}", kind.to_msl_name()), } } crate::TypeInner::Atomic { kind, .. } => { @@ -96,7 +93,11 @@ impl<'a> Display for TypeContext<'a> { Some(name) => name, None => return Ok(()), }; - write!(out, "{} {}&", class_name, kind.to_msl_name(),) + write!(out, "{} ", class_name)?; + if kind == crate::ScalarKind::Uint { + write!(out, "{}::", NAMESPACE)?; + } + write!(out, "{}&", kind.to_msl_name()) } crate::TypeInner::ValuePointer { size: Some(size), @@ -1708,20 +1709,25 @@ impl Writer { self.put_expression(expr_handle, context, true)?; writeln!(self.out, ";")?; write!(self.out, "{}return {} {{", level, struct_name)?; + let mut is_first = true; + let mut has_point_size = false; + for (index, member) in members.iter().enumerate() { - if !context.pipeline_options.allow_point_size - && member.binding - == Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) - { - continue; - } - if member.binding - == Some(crate::Binding::BuiltIn(crate::BuiltIn::CullDistance)) - { - log::warn!("Ignoring CullDistance BuiltIn"); - continue; + match member.binding { + Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) => { + has_point_size = true; + if !context.pipeline_options.allow_point_size { + continue; + } + } + Some(crate::Binding::BuiltIn(crate::BuiltIn::CullDistance)) => { + log::warn!("Ignoring CullDistance built-in"); + continue; + } + _ => {} } + let comma = if is_first { "" } else { "," }; is_first = false; let name = &self.names[&NameKey::StructMember(result_ty, index as u32)]; @@ -1752,6 +1758,17 @@ impl Writer { write!(self.out, "{} {}.{}", comma, tmp, name)?; } } + + if let FunctionOrigin::EntryPoint(ep_index) = context.origin { + let stage = context.module.entry_points[ep_index as usize].stage; + if context.pipeline_options.allow_point_size + && stage == crate::ShaderStage::Vertex + && !has_point_size + { + // point size was injected and comes last + write!(self.out, ", 1.0")?; + } + } } _ => { write!(self.out, "{}return {} {{ ", level, struct_name)?; @@ -2874,6 +2891,7 @@ impl Writer { } writeln!(self.out, "struct {} {{", stage_out_name)?; + let mut has_point_size = false; for (name, ty, binding) in result_members { let ty_name = TypeContext { handle: ty, @@ -2883,19 +2901,27 @@ impl Writer { first_time: true, }; let binding = binding.ok_or(Error::Validation)?; - // Cull Distance is not supported in Metal. - // But we can't return UnsupportedBuiltIn error to user. - // Because otherwise we can't generate msl shader from any glslang SPIR-V shaders. - // glslang generates gl_PerVertex struct with gl_CullDistance builtin inside by default. - if *binding == crate::Binding::BuiltIn(crate::BuiltIn::CullDistance) { - log::warn!("Ignoring CullDistance BuiltIn"); - continue; - } - if !pipeline_options.allow_point_size - && *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize) - { - continue; + + match *binding { + // Point size is only supported in VS of pipelines with + // point primitive topology. + crate::Binding::BuiltIn(crate::BuiltIn::PointSize) => { + has_point_size = true; + if !pipeline_options.allow_point_size { + continue; + } + } + // Cull Distance is not supported in Metal. + // But we can't return UnsupportedBuiltIn error to user. + // Because otherwise we can't generate msl shader from any glslang SPIR-V shaders. + // glslang generates gl_PerVertex struct with gl_CullDistance builtin inside by default. + crate::Binding::BuiltIn(crate::BuiltIn::CullDistance) => { + log::warn!("Ignoring CullDistance BuiltIn"); + continue; + } + _ => {} } + let array_len = match module.types[ty].inner { crate::TypeInner::Array { size: crate::ArraySize::Constant(handle), @@ -2911,6 +2937,18 @@ impl Writer { } writeln!(self.out, ";")?; } + + if pipeline_options.allow_point_size + && ep.stage == crate::ShaderStage::Vertex + && !has_point_size + { + // inject the point size output last + writeln!( + self.out, + "{}float _point_size [[point_size]];", + back::INDENT + )?; + } writeln!(self.out, "}};")?; &stage_out_name } diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index e2f2b32d5..9cf311023 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -16,4 +16,7 @@ wgsl: ( explicit_types: true, ), + msl_pipeline: ( + allow_point_size: true, + ), ) diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 9dca449a6..f95620c37 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -21,6 +21,7 @@ struct vertex_Input { struct vertex_Output { metal::float4 position [[position]]; float varying [[user(loc1), center_perspective]]; + float _point_size [[point_size]]; }; vertex vertex_Output vertex_( vertex_Input varyings [[stage_in]] @@ -30,7 +31,7 @@ vertex vertex_Output vertex_( const auto color = varyings.color; metal::uint tmp = (vertex_index + instance_index) + color; const auto _tmp = VertexOutput {metal::float4(1.0), static_cast(tmp)}; - return vertex_Output { _tmp.position, _tmp.varying }; + return vertex_Output { _tmp.position, _tmp.varying, 1.0 }; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index dd3bd0ccc..56378e2ac 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -63,6 +63,9 @@ struct Parameters { #[cfg(all(feature = "deserialize", feature = "msl-out"))] #[serde(default)] msl: naga::back::msl::Options, + #[cfg(all(feature = "deserialize", feature = "msl-out"))] + #[serde(default)] + msl_pipeline: naga::back::msl::PipelineOptions, #[cfg(all(feature = "deserialize", feature = "glsl-out"))] #[serde(default)] glsl: naga::back::glsl::Options, @@ -135,6 +138,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { &dest, name, ¶ms.msl, + ¶ms.msl_pipeline, params.bounds_check_policies, ); } @@ -235,20 +239,17 @@ fn write_output_msl( destination: &PathBuf, file_name: &str, options: &naga::back::msl::Options, + pipeline_options: &naga::back::msl::PipelineOptions, bounds_check_policies: naga::proc::BoundsCheckPolicies, ) { use naga::back::msl; println!("writing MSL"); - let pipeline_options = msl::PipelineOptions { - allow_point_size: true, - }; - let mut options = options.clone(); options.bounds_check_policies = bounds_check_policies; let (string, tr_info) = - msl::write_string(module, info, &options, &pipeline_options).expect("Metal write failed"); + msl::write_string(module, info, &options, pipeline_options).expect("Metal write failed"); for (ep, result) in module.entry_points.iter().zip(tr_info.entry_point_names) { if let Err(error) = result { From adc6821751aaaedf24c2c316a1d7454ab7d75f5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Kocsis?= Date: Wed, 19 Jan 2022 20:48:04 +0100 Subject: [PATCH 1547/2212] implement block comments (#1675) --- src/front/wgsl/lexer.rs | 54 ++++++++++++++++++++++++++++++++++++++--- src/front/wgsl/mod.rs | 2 ++ 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index be419fd42..733041219 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -356,9 +356,47 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { (Token::UnterminatedString, quote_content) } } - '/' if chars.as_str().starts_with('/') => { - let _ = chars.position(|c| c == '\n' || c == '\r'); - (Token::Trivia, chars.as_str()) + '/' => { + input = chars.as_str(); + match chars.next() { + Some('/') => { + let _ = chars.position(|c| c == '\n' || c == '\r'); + (Token::Trivia, chars.as_str()) + } + Some('*') => { + input = chars.as_str(); + + let mut depth = 1; + let mut prev = '\0'; + + for c in &mut chars { + match (prev, c) { + ('*', '/') => { + prev = '\0'; + depth -= 1; + if depth == 0 { + break; + } + } + ('/', '*') => { + prev = '\0'; + depth += 1; + } + _ => { + prev = c; + } + } + } + + if depth > 0 { + (Token::UnterminatedBlockComment, input) + } else { + (Token::Trivia, chars.as_str()) + } + } + Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), + _ => (Token::Operation(cur), input), + } } '-' => { let sub_input = chars.as_str(); @@ -369,7 +407,7 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { _ => (Token::Operation(cur), sub_input), } } - '+' | '*' | '/' | '%' | '^' => { + '+' | '*' | '%' | '^' => { input = chars.as_str(); if chars.next() == Some('=') { (Token::AssignmentOperation(cur), chars.as_str()) @@ -673,6 +711,14 @@ fn test_tokens() { sub_test("No好", &[Token::Word("No"), Token::Unknown('好')]); sub_test("_No", &[Token::Word("_No")]); sub_test("\"\u{2}ПЀ\u{0}\"", &[Token::String("\u{2}ПЀ\u{0}")]); // https://github.com/gfx-rs/naga/issues/90 + sub_test( + "*/*/***/*//=/*****//", + &[ + Token::Operation('*'), + Token::AssignmentOperation('/'), + Token::Operation('/'), + ], + ); } #[test] diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5b7c34355..3e235f3d3 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -72,6 +72,7 @@ pub enum Token<'a> { Arrow, Unknown(char), UnterminatedString, + UnterminatedBlockComment, Trivia, End, } @@ -204,6 +205,7 @@ impl<'a> Error<'a> { Token::Arrow => "->".to_string(), Token::Unknown(c) => format!("unknown ('{}')", c), Token::UnterminatedString => "unterminated string".to_string(), + Token::UnterminatedBlockComment => "unterminated block comment".to_string(), Token::Trivia => "trivia".to_string(), Token::End => "end".to_string(), } From 4bd1efc34d6a54ed2f14ff6ec5fa77488f3df6b5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 19 Jan 2022 10:33:06 -0500 Subject: [PATCH 1548/2212] wgsl: declare attribtues with @ --- src/back/wgsl/writer.rs | 102 +++----- src/front/wgsl/lexer.rs | 16 +- src/front/wgsl/mod.rs | 237 +++++++----------- src/front/wgsl/tests.rs | 22 +- tests/in/access.wgsl | 12 +- tests/in/bits.wgsl | 2 +- tests/in/boids.wgsl | 12 +- tests/in/bounds-check-image-restrict.wgsl | 24 +- tests/in/bounds-check-image-rzsw.wgsl | 24 +- tests/in/bounds-check-restrict.wgsl | 2 +- tests/in/bounds-check-zero.wgsl | 2 +- tests/in/collatz.wgsl | 8 +- tests/in/control-flow.wgsl | 4 +- tests/in/cubeArrayShadow.wgsl | 8 +- tests/in/empty.wgsl | 2 +- tests/in/extra.wgsl | 8 +- tests/in/functions-webgl.wgsl | 2 +- tests/in/functions.wgsl | 2 +- tests/in/globals.wgsl | 6 +- tests/in/image.wgsl | 70 +++--- tests/in/interface.wgsl | 38 +-- tests/in/interpolate.wgsl | 20 +- tests/in/math-functions.wgsl | 2 +- tests/in/operators.wgsl | 2 +- tests/in/pointers.wgsl | 2 +- tests/in/policy-mix.wgsl | 6 +- tests/in/push-constants.wgsl | 6 +- tests/in/quad.wgsl | 22 +- tests/in/shadow.wgsl | 18 +- tests/in/skybox.wgsl | 18 +- tests/in/standard.wgsl | 4 +- tests/in/texture-arg.wgsl | 8 +- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 8 +- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 14 +- tests/out/wgsl/210-bevy-shader-vert.wgsl | 16 +- tests/out/wgsl/246-collatz-comp.wgsl | 8 +- tests/out/wgsl/277-casting-vert.wgsl | 2 +- tests/out/wgsl/280-matrix-cast-vert.wgsl | 2 +- tests/out/wgsl/484-preprocessor-if-vert.wgsl | 2 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 10 +- tests/out/wgsl/896-push-constant-vert.wgsl | 2 +- .../wgsl/900-implicit-conversions-vert.wgsl | 2 +- tests/out/wgsl/901-lhs-field-select-vert.wgsl | 2 +- .../out/wgsl/931-constant-emitting-vert.wgsl | 2 +- tests/out/wgsl/932-for-loop-if-vert.wgsl | 2 +- tests/out/wgsl/access.wgsl | 14 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 46 ++-- tests/out/wgsl/bevy-pbr-vert.wgsl | 18 +- tests/out/wgsl/binop-frag.wgsl | 2 +- tests/out/wgsl/bits.wgsl | 2 +- tests/out/wgsl/bits_glsl-frag.wgsl | 2 +- tests/out/wgsl/boids.wgsl | 12 +- tests/out/wgsl/bool-select-frag.wgsl | 4 +- tests/out/wgsl/clamp-splat-vert.wgsl | 6 +- tests/out/wgsl/collatz.wgsl | 8 +- tests/out/wgsl/constant-array-size-vert.wgsl | 6 +- tests/out/wgsl/control-flow.wgsl | 4 +- tests/out/wgsl/declarations-vert.wgsl | 8 +- tests/out/wgsl/empty-global-name.wgsl | 4 +- tests/out/wgsl/empty.wgsl | 2 +- tests/out/wgsl/expressions-frag.wgsl | 2 +- tests/out/wgsl/extra.wgsl | 8 +- tests/out/wgsl/fma-frag.wgsl | 2 +- tests/out/wgsl/functions.wgsl | 2 +- .../out/wgsl/global-constant-array-vert.wgsl | 2 +- tests/out/wgsl/globals.wgsl | 8 +- tests/out/wgsl/image.wgsl | 68 ++--- tests/out/wgsl/interface.wgsl | 22 +- tests/out/wgsl/interpolate.wgsl | 20 +- .../wgsl/inv-hyperbolic-trig-functions.wgsl | 2 +- tests/out/wgsl/long-form-matrix-vert.wgsl | 2 +- tests/out/wgsl/math-functions-vert.wgsl | 2 +- tests/out/wgsl/math-functions.wgsl | 2 +- tests/out/wgsl/operators.wgsl | 2 +- tests/out/wgsl/pointers.wgsl | 4 +- tests/out/wgsl/prepostfix-frag.wgsl | 2 +- tests/out/wgsl/quad-vert.wgsl | 10 +- tests/out/wgsl/quad.wgsl | 20 +- tests/out/wgsl/quad_glsl-frag.wgsl | 6 +- tests/out/wgsl/quad_glsl-vert.wgsl | 8 +- tests/out/wgsl/samplers-frag.wgsl | 32 +-- tests/out/wgsl/shadow.wgsl | 14 +- tests/out/wgsl/skybox.wgsl | 18 +- tests/out/wgsl/standard.wgsl | 4 +- tests/out/wgsl/swizzle_write-frag.wgsl | 2 +- tests/out/wgsl/texture-arg.wgsl | 8 +- tests/spirv-capabilities.rs | 22 +- tests/wgsl-errors.rs | 116 ++++----- 88 files changed, 618 insertions(+), 713 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 59c7048c3..60598fe90 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -159,7 +159,7 @@ impl Writer { ], }; - self.write_attributes(&attributes, false)?; + self.write_attributes(&attributes)?; // Add a newline after attribute writeln!(self.out)?; @@ -244,11 +244,10 @@ impl Writer { for (index, arg) in func.arguments.iter().enumerate() { // Write argument attribute if a binding is present if let Some(ref binding) = arg.binding { - self.write_attributes( - &map_binding_to_attribute(binding, module.types[arg.ty].inner.scalar_kind()), - false, - )?; - write!(self.out, " ")?; + self.write_attributes(&map_binding_to_attribute( + binding, + module.types[arg.ty].inner.scalar_kind(), + ))?; } // Write argument name let argument_name = match func_ctx.ty { @@ -275,10 +274,10 @@ impl Writer { if let Some(ref result) = func.result { write!(self.out, " -> ")?; if let Some(ref binding) = result.binding { - self.write_attributes( - &map_binding_to_attribute(binding, module.types[result.ty].inner.scalar_kind()), - true, - )?; + self.write_attributes(&map_binding_to_attribute( + binding, + module.types[result.ty].inner.scalar_kind(), + ))?; } self.write_type(module, result.ty)?; } @@ -331,62 +330,40 @@ impl Writer { } /// Helper method to write a attribute - /// - /// # Notes - /// Adds an extra space if required - fn write_attributes(&mut self, attributes: &[Attribute], extra_space: bool) -> BackendResult { - write!(self.out, "[[")?; - - let mut need_last_comma = true; - if let Some(last_attrib) = attributes.last() { - // We duplicate the logic a little, but this will help to avoid extra heap allocation - match *last_attrib { - Attribute::BuiltIn(builtin_attrib) => { - need_last_comma = builtin_str(builtin_attrib).is_some(); - } - Attribute::Interpolate(interpolation, sampling) => { - need_last_comma = (sampling.is_some() - && sampling != Some(crate::Sampling::Center)) - || (interpolation.is_some() - && interpolation != Some(crate::Interpolation::Perspective)) - } - _ => {} - } - } - - for (index, attribute) in attributes.iter().enumerate() { + fn write_attributes(&mut self, attributes: &[Attribute]) -> BackendResult { + for attribute in attributes { match *attribute { - Attribute::Location(id) => write!(self.out, "location({})", id)?, + Attribute::Location(id) => write!(self.out, "@location({}) ", id)?, Attribute::BuiltIn(builtin_attrib) => { if let Some(builtin) = builtin_str(builtin_attrib) { - write!(self.out, "builtin({})", builtin)?; + write!(self.out, "@builtin({}) ", builtin)?; } else { log::warn!("Unsupported builtin attribute: {:?}", builtin_attrib); } } Attribute::Stage(shader_stage) => { let stage_str = match shader_stage { - ShaderStage::Vertex => "stage(vertex)", - ShaderStage::Fragment => "stage(fragment)", - ShaderStage::Compute => "stage(compute)", + ShaderStage::Vertex => "vertex", + ShaderStage::Fragment => "fragment", + ShaderStage::Compute => "compute", }; - write!(self.out, "{}", stage_str)?; + write!(self.out, "@stage({}) ", stage_str)?; } - Attribute::Stride(stride) => write!(self.out, "stride({})", stride)?, + Attribute::Stride(stride) => write!(self.out, "@stride({}) ", stride)?, Attribute::WorkGroupSize(size) => { write!( self.out, - "workgroup_size({}, {}, {})", + "@workgroup_size({}, {}, {}) ", size[0], size[1], size[2] )?; } - Attribute::Binding(id) => write!(self.out, "binding({})", id)?, - Attribute::Group(id) => write!(self.out, "group({})", id)?, + Attribute::Binding(id) => write!(self.out, "@binding({}) ", id)?, + Attribute::Group(id) => write!(self.out, "@group({}) ", id)?, Attribute::Interpolate(interpolation, sampling) => { if sampling.is_some() && sampling != Some(crate::Sampling::Center) { write!( self.out, - "interpolate({}, {})", + "@interpolate({}, {}) ", interpolation_str( interpolation.unwrap_or(crate::Interpolation::Perspective) ), @@ -397,7 +374,7 @@ impl Writer { { write!( self.out, - "interpolate({})", + "@interpolate({}) ", interpolation_str( interpolation.unwrap_or(crate::Interpolation::Perspective) ) @@ -405,19 +382,7 @@ impl Writer { } } }; - - // Only write a comma if isn't the last element - if index + 1 != attributes.len() && need_last_comma { - // The leading space is for readability only - write!(self.out, ", ")?; - } } - - write!(self.out, "]]")?; - if extra_space { - write!(self.out, " ")?; - } - Ok(()) } @@ -447,10 +412,10 @@ impl Writer { // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; if let Some(ref binding) = member.binding { - self.write_attributes( - &map_binding_to_attribute(binding, module.types[member.ty].inner.scalar_kind()), - true, - )?; + self.write_attributes(&map_binding_to_attribute( + binding, + module.types[member.ty].inner.scalar_kind(), + ))?; } // Write struct member name and type let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; @@ -462,7 +427,7 @@ impl Writer { stride, } = module.types[member.ty].inner { - self.write_attributes(&[Attribute::Stride(stride)], true)?; + self.write_attributes(&[Attribute::Stride(stride)])?; } self.write_type(module, member.ty)?; write!(self.out, ";")?; @@ -1716,13 +1681,10 @@ impl Writer { ) -> BackendResult { // Write group and dinding attributes if present if let Some(ref binding) = global.binding { - self.write_attributes( - &[ - Attribute::Group(binding.group), - Attribute::Binding(binding.binding), - ], - false, - )?; + self.write_attributes(&[ + Attribute::Group(binding.group), + Attribute::Binding(binding.binding), + ])?; writeln!(self.out)?; } diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 733041219..99a2d4f85 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -315,7 +315,8 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { _ => (Token::Separator(cur), og_chars), } } - '(' | ')' | '{' | '}' => (Token::Paren(cur), chars.as_str()), + '@' => (Token::Attribute, chars.as_str()), + '(' | ')' | '{' | '}' | '[' | ']' => (Token::Paren(cur), chars.as_str()), '<' | '>' => { input = chars.as_str(); let next = chars.next(); @@ -332,14 +333,6 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { (Token::Paren(cur), input) } } - '[' | ']' => { - input = chars.as_str(); - if chars.next() == Some(cur) { - (Token::DoubleParen(cur), chars.as_str()) - } else { - (Token::Paren(cur), input) - } - } '0'..='9' => consume_number(input), '_' | 'a'..='z' | 'A'..='Z' => { let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); @@ -724,9 +717,9 @@ fn test_tokens() { #[test] fn test_variable_decl() { sub_test( - "[[ group(0 )]] var< uniform> texture: texture_multisampled_2d ;", + "@group(0 ) var< uniform> texture: texture_multisampled_2d ;", &[ - Token::DoubleParen('['), + Token::Attribute, Token::Word("group"), Token::Paren('('), Token::Number { @@ -735,7 +728,6 @@ fn test_variable_decl() { width: None, }, Token::Paren(')'), - Token::DoubleParen(']'), Token::Word("var"), Token::Paren('<'), Token::Word("uniform"), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 3e235f3d3..f7d65afc2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -57,7 +57,7 @@ pub enum Token<'a> { Separator(char), DoubleColon, Paren(char), - DoubleParen(char), + Attribute, Number { value: &'a str, ty: NumberType, @@ -89,11 +89,9 @@ pub enum ExpectedToken<'a> { Constant, /// Expected: constant, parenthesized expression, identifier PrimaryExpression, - /// Expected: ']]', ',' - AttributeSeparator, /// Expected: '}', identifier FieldName, - /// Expected: ']]', 'access', 'stride' + /// Expected: attribute for a type TypeAttribute, /// Expected: ';', '{', word Statement, @@ -103,8 +101,6 @@ pub enum ExpectedToken<'a> { WorkgroupSizeSeparator, /// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof GlobalItem, - /// Expected: ']]', 'size', 'align' - StructAttribute, } #[derive(Clone, Debug, Error)] @@ -168,6 +164,7 @@ pub enum Error<'a> { UnknownLocalFunction(Span), InitializationTypeMismatch(Span, String), MissingType(Span), + MissingAttribute(&'static str, Span), InvalidAtomicPointer(Span), InvalidAtomicOperandType(Span), Pointer(&'static str, Span), @@ -191,7 +188,7 @@ impl<'a> Error<'a> { Token::Separator(c) => format!("'{}'", c), Token::DoubleColon => "'::'".to_string(), Token::Paren(c) => format!("'{}'", c), - Token::DoubleParen(c) => format!("'{}{}'", c, c), + Token::Attribute => "@".to_string(), Token::Number { value, .. } => { format!("number ({})", value) } @@ -234,14 +231,12 @@ impl<'a> Error<'a> { ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), ExpectedToken::Constant => "constant".to_string(), ExpectedToken::PrimaryExpression => "expression".to_string(), - ExpectedToken::AttributeSeparator => "attribute separator (',') or an end of the attribute list (']]')".to_string(), ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(), - ExpectedToken::TypeAttribute => "type attribute ('stride') or an end of the attribute list (']]')".to_string(), + ExpectedToken::TypeAttribute => "type attribute ('stride')".to_string(), ExpectedToken::Statement => "statement".to_string(), ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), ExpectedToken::GlobalItem => "global item ('struct', 'let', 'var', 'type', ';', 'fn') or the end of the file".to_string(), - ExpectedToken::StructAttribute => "struct attribute ('size' or 'align') or an end of the attribute list (']]')".to_string(), }; ParseError { message: format!( @@ -428,6 +423,11 @@ impl<'a> Error<'a> { labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], notes: vec![], }, + Error::MissingAttribute(name, ref name_span) => ParseError { + message: format!("variable `{}` needs a '{}' attribute", &source[name_span.clone()], name), + labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], + notes: vec![], + }, Error::InvalidAtomicPointer(ref span) => ParseError { message: "atomic operation is done on a pointer to a non-atomic".to_string(), labels: vec![(span.clone(), "atomic pointer is invalid".into())], @@ -2830,51 +2830,23 @@ impl Parser { let (mut size, mut align) = (None, None); self.push_scope(Scope::Attribute, lexer); let mut bind_parser = BindingParser::default(); - if lexer.skip(Token::DoubleParen('[')) { - let mut ready = true; - loop { - match lexer.next() { - (Token::DoubleParen(']'), _) => { - break; - } - (Token::Separator(','), _) if !ready => { - ready = true; - } - (Token::Word(word), word_span) if ready => { - match word { - "size" => { - lexer.expect(Token::Paren('('))?; - let (value, span) = lexer.capture_span(|lexer| { - parse_non_negative_sint_literal(lexer, 4) - })?; - lexer.expect(Token::Paren(')'))?; - size = Some( - NonZeroU32::new(value) - .ok_or(Error::ZeroSizeOrAlign(span))?, - ); - } - "align" => { - lexer.expect(Token::Paren('('))?; - let (value, span) = lexer.capture_span(|lexer| { - parse_non_negative_sint_literal(lexer, 4) - })?; - lexer.expect(Token::Paren(')'))?; - align = Some( - NonZeroU32::new(value) - .ok_or(Error::ZeroSizeOrAlign(span))?, - ); - } - _ => bind_parser.parse(lexer, word, word_span)?, - } - ready = false; - } - other if ready => { - return Err(Error::Unexpected(other, ExpectedToken::StructAttribute)) - } - other => { - return Err(Error::Unexpected(other, ExpectedToken::AttributeSeparator)) - } + while lexer.skip(Token::Attribute) { + match lexer.next_ident_with_span()? { + ("size", _) => { + lexer.expect(Token::Paren('('))?; + let (value, span) = lexer + .capture_span(|lexer| parse_non_negative_sint_literal(lexer, 4))?; + lexer.expect(Token::Paren(')'))?; + size = Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign(span))?); } + ("align", _) => { + lexer.expect(Token::Paren('('))?; + let (value, span) = lexer + .capture_span(|lexer| parse_non_negative_sint_literal(lexer, 4))?; + lexer.expect(Token::Paren(')'))?; + align = Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign(span))?); + } + (word, word_span) => bind_parser.parse(lexer, word, word_span)?, } } @@ -3270,21 +3242,18 @@ impl Parser { self.push_scope(Scope::TypeDecl, lexer); let mut attribute = TypeAttributes::default(); - if lexer.skip(Token::DoubleParen('[')) { + while lexer.skip(Token::Attribute) { self.push_scope(Scope::Attribute, lexer); - loop { - match lexer.next() { - (Token::Word("stride"), _) => { - lexer.expect(Token::Paren('('))?; - let (stride, span) = lexer - .capture_span(|lexer| parse_non_negative_sint_literal(lexer, 4))?; - attribute.stride = - Some(NonZeroU32::new(stride).ok_or(Error::ZeroStride(span))?); - lexer.expect(Token::Paren(')'))?; - } - (Token::DoubleParen(']'), _) => break, - other => return Err(Error::Unexpected(other, ExpectedToken::TypeAttribute)), + match lexer.next() { + (Token::Word("stride"), _) => { + lexer.expect(Token::Paren('('))?; + let (stride, span) = + lexer.capture_span(|lexer| parse_non_negative_sint_literal(lexer, 4))?; + attribute.stride = + Some(NonZeroU32::new(stride).ok_or(Error::ZeroStride(span))?); + lexer.expect(Token::Paren(')'))?; } + other => return Err(Error::Unexpected(other, ExpectedToken::TypeAttribute)), } self.pop_scope(lexer); } @@ -4008,24 +3977,12 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, ) -> Result, Error<'a>> { + let mut bind_parser = BindingParser::default(); self.push_scope(Scope::Attribute, lexer); - if !lexer.skip(Token::DoubleParen('[')) { - self.pop_scope(lexer); - return Ok(None); - } - - let mut bind_parser = BindingParser::default(); - loop { + while lexer.skip(Token::Attribute) { let (word, span) = lexer.next_ident_with_span()?; bind_parser.parse(lexer, word, span)?; - match lexer.next() { - (Token::DoubleParen(']'), _) => { - break; - } - (Token::Separator(','), _) => {} - other => return Err(Error::Unexpected(other, ExpectedToken::AttributeSeparator)), - } } let span = self.pop_scope(lexer); @@ -4174,83 +4131,77 @@ impl Parser { ) -> Result> { // read attributes let mut binding = None; - // Perspective is the default qualifier. let mut stage = None; let mut workgroup_size = [0u32; 3]; let mut early_depth_test = None; + let (mut bind_index, mut bind_group) = (None, None); - if lexer.skip(Token::DoubleParen('[')) { - let (mut bind_index, mut bind_group) = (None, None); - self.push_scope(Scope::Attribute, lexer); - loop { - match lexer.next_ident_with_span()? { - ("binding", _) => { - lexer.expect(Token::Paren('('))?; - bind_index = Some(parse_non_negative_sint_literal(lexer, 4)?); - lexer.expect(Token::Paren(')'))?; + self.push_scope(Scope::Attribute, lexer); + while lexer.skip(Token::Attribute) { + match lexer.next_ident_with_span()? { + ("binding", _) => { + lexer.expect(Token::Paren('('))?; + bind_index = Some(parse_non_negative_sint_literal(lexer, 4)?); + lexer.expect(Token::Paren(')'))?; + } + ("group", _) => { + lexer.expect(Token::Paren('('))?; + bind_group = Some(parse_non_negative_sint_literal(lexer, 4)?); + lexer.expect(Token::Paren(')'))?; + } + ("stage", _) => { + lexer.expect(Token::Paren('('))?; + let (ident, ident_span) = lexer.next_ident_with_span()?; + stage = Some(conv::map_shader_stage(ident, ident_span)?); + lexer.expect(Token::Paren(')'))?; + } + ("workgroup_size", _) => { + lexer.expect(Token::Paren('('))?; + for (i, size) in workgroup_size.iter_mut().enumerate() { + *size = parse_generic_non_negative_int_literal(lexer, 4)?; + match lexer.next() { + (Token::Paren(')'), _) => break, + (Token::Separator(','), _) if i != 2 => (), + other => { + return Err(Error::Unexpected( + other, + ExpectedToken::WorkgroupSizeSeparator, + )) + } + } } - ("group", _) => { - lexer.expect(Token::Paren('('))?; - bind_group = Some(parse_non_negative_sint_literal(lexer, 4)?); - lexer.expect(Token::Paren(')'))?; + for size in workgroup_size.iter_mut() { + if *size == 0 { + *size = 1; + } } - ("stage", _) => { - lexer.expect(Token::Paren('('))?; + } + ("early_depth_test", _) => { + let conservative = if lexer.skip(Token::Paren('(')) { let (ident, ident_span) = lexer.next_ident_with_span()?; - stage = Some(conv::map_shader_stage(ident, ident_span)?); + let value = conv::map_conservative_depth(ident, ident_span)?; lexer.expect(Token::Paren(')'))?; - } - ("workgroup_size", _) => { - lexer.expect(Token::Paren('('))?; - for (i, size) in workgroup_size.iter_mut().enumerate() { - *size = parse_generic_non_negative_int_literal(lexer, 4)?; - match lexer.next() { - (Token::Paren(')'), _) => break, - (Token::Separator(','), _) if i != 2 => (), - other => { - return Err(Error::Unexpected( - other, - ExpectedToken::WorkgroupSizeSeparator, - )) - } - } - } - for size in workgroup_size.iter_mut() { - if *size == 0 { - *size = 1; - } - } - } - ("early_depth_test", _) => { - let conservative = if lexer.skip(Token::Paren('(')) { - let (ident, ident_span) = lexer.next_ident_with_span()?; - let value = conv::map_conservative_depth(ident, ident_span)?; - lexer.expect(Token::Paren(')'))?; - Some(value) - } else { - None - }; - early_depth_test = Some(crate::EarlyDepthTest { conservative }); - } - (_, word_span) => return Err(Error::UnknownAttribute(word_span)), - } - match lexer.next() { - (Token::DoubleParen(']'), _) => { - break; - } - (Token::Separator(','), _) => {} - other => { - return Err(Error::Unexpected(other, ExpectedToken::AttributeSeparator)) - } + Some(value) + } else { + None + }; + early_depth_test = Some(crate::EarlyDepthTest { conservative }); } + (_, word_span) => return Err(Error::UnknownAttribute(word_span)), } - if let (Some(group), Some(index)) = (bind_group, bind_index) { + } + + let attrib_scope = self.pop_scope(lexer); + match (bind_group, bind_index) { + (Some(group), Some(index)) => { binding = Some(crate::ResourceBinding { group, binding: index, }); } - self.pop_scope(lexer); + (Some(_), None) => return Err(Error::MissingAttribute("binding", attrib_scope)), + (None, Some(_)) => return Err(Error::MissingAttribute("group", attrib_scope)), + (None, None) => {} } // read items diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 60c02c4e6..bb415fa7c 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -159,9 +159,9 @@ fn parse_struct() { " struct Foo { x: i32; }; struct Bar { - [[size(16)]] x: vec2; - [[align(16)]] y: f32; - [[size(32), align(8)]] z: vec3; + @size(16) x: vec2; + @align(16) y: f32; + @size(32) @align(8) z: vec3; }; struct Empty {}; var s: Foo; @@ -384,7 +384,7 @@ fn parse_struct_instantiation() { b: vec3; }; - [[stage(fragment)]] + @stage(fragment) fn fs_main() { var foo: Foo = Foo(0.0, vec3(0.0, 1.0, 42.0)); } @@ -398,13 +398,13 @@ fn parse_array_length() { parse_str( " struct Foo { - data: [[stride(4)]] array; + data: @stride(4) array; }; // this is used as both input and output for convenience - [[group(0), binding(0)]] + @group(0) @binding(0) var foo: Foo; - [[group(0), binding(1)]] + @group(0) @binding(1) var bar: array; fn baz() { @@ -420,28 +420,28 @@ fn parse_array_length() { fn parse_storage_buffers() { parse_str( " - [[group(0), binding(0)]] + @group(0) @binding(0) var foo: array; ", ) .unwrap(); parse_str( " - [[group(0), binding(0)]] + @group(0) @binding(0) var foo: array; ", ) .unwrap(); parse_str( " - [[group(0), binding(0)]] + @group(0) @binding(0) var foo: array; ", ) .unwrap(); parse_str( " - [[group(0), binding(0)]] + @group(0) @binding(0) var foo: array; ", ) diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index ed088e7de..ce26cb8a4 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -4,19 +4,19 @@ struct Bar { matrix: mat4x4; matrix_array: array, 2>; atom: atomic; - arr: [[stride(8)]] array, 2>; - data: [[stride(8)]] array; + arr: @stride(8) array, 2>; + data: @stride(8) array; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var bar: Bar; fn read_from_private(foo: ptr) -> f32 { return *foo; } -[[stage(vertex)]] -fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { +@stage(vertex) +fn foo(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32 = 0.0; // We should check that backed doesn't skip this expression let baz: f32 = foo; @@ -47,7 +47,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { return matrix * vec4(vec4(value)); } -[[stage(compute), workgroup_size(1)]] +@stage(compute) @workgroup_size(1) fn atomics() { var tmp: i32; let value = atomicLoad(&bar.atom); diff --git a/tests/in/bits.wgsl b/tests/in/bits.wgsl index 4bec623aa..6851f243f 100644 --- a/tests/in/bits.wgsl +++ b/tests/in/bits.wgsl @@ -1,4 +1,4 @@ -[[stage(compute), workgroup_size(1)]] +@stage(compute) @workgroup_size(1) fn main() { var i = 0; var i2 = vec2(0); diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 5e712ac56..1cc54cfc4 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -16,16 +16,16 @@ struct SimParams { }; struct Particles { - particles : [[stride(16)]] array; + particles : @stride(16) array; }; -[[group(0), binding(0)]] var params : SimParams; -[[group(0), binding(1)]] var particlesSrc : Particles; -[[group(0), binding(2)]] var particlesDst : Particles; +@group(0) @binding(0) var params : SimParams; +@group(0) @binding(1) var particlesSrc : Particles; +@group(0) @binding(2) var particlesDst : Particles; // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp -[[stage(compute), workgroup_size(64)]] -fn main([[builtin(global_invocation_id)]] global_invocation_id : vec3) { +@stage(compute) @workgroup_size(64) +fn main(@builtin(global_invocation_id) global_invocation_id : vec3) { let index : u32 = global_invocation_id.x; if (index >= NUM_PARTICLES) { return; diff --git a/tests/in/bounds-check-image-restrict.wgsl b/tests/in/bounds-check-image-restrict.wgsl index e2f913183..d30845291 100644 --- a/tests/in/bounds-check-image-restrict.wgsl +++ b/tests/in/bounds-check-image-restrict.wgsl @@ -1,81 +1,81 @@ -[[group(0), binding(0)]] +@group(0) @binding(0) var image_1d: texture_1d; fn test_textureLoad_1d(coords: i32, level: i32) -> vec4 { return textureLoad(image_1d, coords, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_2d: texture_2d; fn test_textureLoad_2d(coords: vec2, level: i32) -> vec4 { return textureLoad(image_2d, coords, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_2d_array: texture_2d_array; fn test_textureLoad_2d_array(coords: vec2, index: i32, level: i32) -> vec4 { return textureLoad(image_2d_array, coords, index, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_3d: texture_3d; fn test_textureLoad_3d(coords: vec3, level: i32) -> vec4 { return textureLoad(image_3d, coords, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_multisampled_2d: texture_multisampled_2d; fn test_textureLoad_multisampled_2d(coords: vec2, sample: i32) -> vec4 { return textureLoad(image_multisampled_2d, coords, sample); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_depth_2d: texture_depth_2d; fn test_textureLoad_depth_2d(coords: vec2, level: i32) -> f32 { return textureLoad(image_depth_2d, coords, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_depth_2d_array: texture_depth_2d_array; fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> f32 { return textureLoad(image_depth_2d_array, coords, index, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_depth_multisampled_2d: texture_depth_multisampled_2d; fn test_textureLoad_depth_multisampled_2d(coords: vec2, sample: i32) -> f32 { return textureLoad(image_depth_multisampled_2d, coords, sample); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_storage_1d: texture_storage_1d; fn test_textureStore_1d(coords: i32, value: vec4) { textureStore(image_storage_1d, coords, value); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_storage_2d: texture_storage_2d; fn test_textureStore_2d(coords: vec2, value: vec4) { textureStore(image_storage_2d, coords, value); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_storage_2d_array: texture_storage_2d_array; fn test_textureStore_2d_array(coords: vec2, array_index: i32, value: vec4) { textureStore(image_storage_2d_array, coords, array_index, value); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_storage_3d: texture_storage_3d; fn test_textureStore_3d(coords: vec3, value: vec4) { diff --git a/tests/in/bounds-check-image-rzsw.wgsl b/tests/in/bounds-check-image-rzsw.wgsl index e2f913183..d30845291 100644 --- a/tests/in/bounds-check-image-rzsw.wgsl +++ b/tests/in/bounds-check-image-rzsw.wgsl @@ -1,81 +1,81 @@ -[[group(0), binding(0)]] +@group(0) @binding(0) var image_1d: texture_1d; fn test_textureLoad_1d(coords: i32, level: i32) -> vec4 { return textureLoad(image_1d, coords, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_2d: texture_2d; fn test_textureLoad_2d(coords: vec2, level: i32) -> vec4 { return textureLoad(image_2d, coords, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_2d_array: texture_2d_array; fn test_textureLoad_2d_array(coords: vec2, index: i32, level: i32) -> vec4 { return textureLoad(image_2d_array, coords, index, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_3d: texture_3d; fn test_textureLoad_3d(coords: vec3, level: i32) -> vec4 { return textureLoad(image_3d, coords, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_multisampled_2d: texture_multisampled_2d; fn test_textureLoad_multisampled_2d(coords: vec2, sample: i32) -> vec4 { return textureLoad(image_multisampled_2d, coords, sample); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_depth_2d: texture_depth_2d; fn test_textureLoad_depth_2d(coords: vec2, level: i32) -> f32 { return textureLoad(image_depth_2d, coords, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_depth_2d_array: texture_depth_2d_array; fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> f32 { return textureLoad(image_depth_2d_array, coords, index, level); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_depth_multisampled_2d: texture_depth_multisampled_2d; fn test_textureLoad_depth_multisampled_2d(coords: vec2, sample: i32) -> f32 { return textureLoad(image_depth_multisampled_2d, coords, sample); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_storage_1d: texture_storage_1d; fn test_textureStore_1d(coords: i32, value: vec4) { textureStore(image_storage_1d, coords, value); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_storage_2d: texture_storage_2d; fn test_textureStore_2d(coords: vec2, value: vec4) { textureStore(image_storage_2d, coords, value); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_storage_2d_array: texture_storage_2d_array; fn test_textureStore_2d_array(coords: vec2, array_index: i32, value: vec4) { textureStore(image_storage_2d_array, coords, array_index, value); } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_storage_3d: texture_storage_3d; fn test_textureStore_3d(coords: vec3, value: vec4) { diff --git a/tests/in/bounds-check-restrict.wgsl b/tests/in/bounds-check-restrict.wgsl index 8550fd703..fefcdec0c 100644 --- a/tests/in/bounds-check-restrict.wgsl +++ b/tests/in/bounds-check-restrict.wgsl @@ -7,7 +7,7 @@ struct Globals { d: array; }; -[[group(0), binding(0)]] var globals: Globals; +@group(0) @binding(0) var globals: Globals; fn index_array(i: i32) -> f32 { return globals.a[i]; diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl index 4838701c2..e1a05ac92 100644 --- a/tests/in/bounds-check-zero.wgsl +++ b/tests/in/bounds-check-zero.wgsl @@ -7,7 +7,7 @@ struct Globals { d: array; }; -[[group(0), binding(0)]] var globals: Globals; +@group(0) @binding(0) var globals: Globals; fn index_array(i: i32) -> f32 { return globals.a[i]; diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index 878b18d09..f4341c24a 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -1,8 +1,8 @@ struct PrimeIndices { - data: [[stride(4)]] array; + data: @stride(4) array; }; // this is used as both input and output for convenience -[[group(0), binding(0)]] +@group(0) @binding(0) var v_indices: PrimeIndices; // The Collatz Conjecture states that for any integer n: @@ -29,7 +29,7 @@ fn collatz_iterations(n_base: u32) -> u32 { return i; } -[[stage(compute), workgroup_size(1)]] -fn main([[builtin(global_invocation_id)]] global_id: vec3) { +@stage(compute) @workgroup_size(1) +fn main(@builtin(global_invocation_id) global_id: vec3) { v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); } diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index e875d63e8..9ce08fff7 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -1,5 +1,5 @@ -[[stage(compute), workgroup_size(1)]] -fn main([[builtin(global_invocation_id)]] global_id: vec3) { +@stage(compute) @workgroup_size(1) +fn main(@builtin(global_invocation_id) global_id: vec3) { //TODO: execution-only barrier? storageBarrier(); workgroupBarrier(); diff --git a/tests/in/cubeArrayShadow.wgsl b/tests/in/cubeArrayShadow.wgsl index a2a376564..aad2d5ae8 100644 --- a/tests/in/cubeArrayShadow.wgsl +++ b/tests/in/cubeArrayShadow.wgsl @@ -1,10 +1,10 @@ -[[group(0), binding(4)]] +@group(0) @binding(4) var point_shadow_textures: texture_depth_cube_array; -[[group(0), binding(5)]] +@group(0) @binding(5) var point_shadow_textures_sampler: sampler_comparison; -[[stage(fragment)]] -fn fragment() -> [[location(0)]] vec4 { +@stage(fragment) +fn fragment() -> @location(0) vec4 { let frag_ls = vec4(1., 1., 2., 1.).xyz; let a = textureSampleCompare(point_shadow_textures, point_shadow_textures_sampler, frag_ls, i32(1), 1.); diff --git a/tests/in/empty.wgsl b/tests/in/empty.wgsl index 9bd04d80c..862844479 100644 --- a/tests/in/empty.wgsl +++ b/tests/in/empty.wgsl @@ -1,2 +1,2 @@ -[[stage(compute), workgroup_size(1)]] +@stage(compute) @workgroup_size(1) fn main() {} diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index fa8c466c4..d728c56be 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -5,12 +5,12 @@ struct PushConstants { var pc: PushConstants; struct FragmentIn { - [[location(0)]] color: vec4; - [[builtin(primitive_index)]] primitive_index: u32; + @location(0) color: vec4; + @builtin(primitive_index) primitive_index: u32; }; -[[stage(fragment)]] -fn main(in: FragmentIn) -> [[location(0)]] vec4 { +@stage(fragment) +fn main(in: FragmentIn) -> @location(0) vec4 { if (in.primitive_index % 2u == 0u) { return in.color; } else { diff --git a/tests/in/functions-webgl.wgsl b/tests/in/functions-webgl.wgsl index 2ec56f88f..2e058ec72 100644 --- a/tests/in/functions-webgl.wgsl +++ b/tests/in/functions-webgl.wgsl @@ -7,7 +7,7 @@ fn test_fma() -> vec2 { } -[[stage(vertex)]] +@stage(vertex) fn main() { let a = test_fma(); } diff --git a/tests/in/functions.wgsl b/tests/in/functions.wgsl index e9d64a99f..71f736a2b 100644 --- a/tests/in/functions.wgsl +++ b/tests/in/functions.wgsl @@ -9,7 +9,7 @@ fn test_fma() -> vec2 { } -[[stage(compute), workgroup_size(1)]] +@stage(compute) @workgroup_size(1) fn main() { let a = test_fma(); } diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 6c9fc1c16..02c9e069a 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -10,17 +10,17 @@ struct Foo { // test packed vec3 v1: f32; }; -[[group(0), binding(1)]] +@group(0) @binding(1) var alignment: Foo; struct Dummy { arr: array>; }; -[[group(0), binding(2)]] +@group(0) @binding(2) var dummy: Dummy; -[[stage(compute), workgroup_size(1)]] +@stage(compute) @workgroup_size(1) fn main() { wg[3] = alignment.v1; wg[2] = alignment.v3.x; diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 0e2a735c3..d722fcf41 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -1,25 +1,25 @@ -[[group(0), binding(0)]] +@group(0) @binding(0) var image_mipmapped_src: texture_2d; -[[group(0), binding(3)]] +@group(0) @binding(3) var image_multisampled_src: texture_multisampled_2d; -[[group(0), binding(4)]] +@group(0) @binding(4) var image_depth_multisampled_src: texture_depth_multisampled_2d; -[[group(0), binding(1)]] +@group(0) @binding(1) var image_storage_src: texture_storage_2d; -[[group(0), binding(5)]] +@group(0) @binding(5) var image_array_src: texture_2d_array; -[[group(0), binding(6)]] +@group(0) @binding(6) var image_dup_src: texture_storage_1d; // for #1307 -[[group(0), binding(7)]] +@group(0) @binding(7) var image_1d_src: texture_1d; -[[group(0), binding(2)]] +@group(0) @binding(2) var image_dst: texture_storage_1d; -[[stage(compute), workgroup_size(16)]] +@stage(compute) @workgroup_size(16) fn main( - [[builtin(local_invocation_id)]] local_id: vec3, + @builtin(local_invocation_id) local_id: vec3, //TODO: https://github.com/gpuweb/gpuweb/issues/1590 - //[[builtin(workgroup_size)]] wg_size: vec3 + //@builtin(workgroup_size) wg_size: vec3 ) { let dim = textureDimensions(image_storage_src); let itc = dim * vec2(local_id.xy) % vec2(10, 20); @@ -31,8 +31,8 @@ fn main( textureStore(image_dst, itc.x, value1 + value2 + value4 + value5 + value6); } -[[stage(compute), workgroup_size(16, 1, 1)]] -fn depth_load([[builtin(local_invocation_id)]] local_id: vec3) { +@stage(compute) @workgroup_size(16, 1, 1) +fn depth_load(@builtin(local_invocation_id) local_id: vec3) { let dim: vec2 = textureDimensions(image_storage_src); let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); let val: f32 = textureLoad(image_depth_multisampled_src, itc, i32(local_id.z)); @@ -40,23 +40,23 @@ fn depth_load([[builtin(local_invocation_id)]] local_id: vec3) { return; } -[[group(0), binding(0)]] +@group(0) @binding(0) var image_1d: texture_1d; -[[group(0), binding(1)]] +@group(0) @binding(1) var image_2d: texture_2d; -[[group(0), binding(2)]] +@group(0) @binding(2) var image_2d_array: texture_2d_array; -[[group(0), binding(3)]] +@group(0) @binding(3) var image_cube: texture_cube; -[[group(0), binding(4)]] +@group(0) @binding(4) var image_cube_array: texture_cube_array; -[[group(0), binding(5)]] +@group(0) @binding(5) var image_3d: texture_3d; -[[group(0), binding(6)]] +@group(0) @binding(6) var image_aa: texture_multisampled_2d; -[[stage(vertex)]] -fn queries() -> [[builtin(position)]] vec4 { +@stage(vertex) +fn queries() -> @builtin(position) vec4 { let dim_1d = textureDimensions(image_1d); let dim_1d_lod = textureDimensions(image_1d, i32(dim_1d)); let dim_2d = textureDimensions(image_2d); @@ -76,8 +76,8 @@ fn queries() -> [[builtin(position)]] vec4 { return vec4(f32(sum)); } -[[stage(vertex)]] -fn levels_queries() -> [[builtin(position)]] vec4 { +@stage(vertex) +fn levels_queries() -> @builtin(position) vec4 { let num_levels_2d = textureNumLevels(image_2d); let num_levels_2d_array = textureNumLevels(image_2d_array); let num_layers_2d = textureNumLayers(image_2d_array); @@ -92,11 +92,11 @@ fn levels_queries() -> [[builtin(position)]] vec4 { return vec4(f32(sum)); } -[[group(1), binding(0)]] +@group(1) @binding(0) var sampler_reg: sampler; -[[stage(fragment)]] -fn sample() -> [[location(0)]] vec4 { +@stage(fragment) +fn sample() -> @location(0) vec4 { let tc = vec2(0.5); let level = 2.3; let s1d = textureSample(image_1d, sampler_reg, tc.x); @@ -107,13 +107,13 @@ fn sample() -> [[location(0)]] vec4 { return s1d + s2d + s2d_offset + s2d_level + s2d_level_offset; } -[[group(1), binding(1)]] +@group(1) @binding(1) var sampler_cmp: sampler_comparison; -[[group(1), binding(2)]] +@group(1) @binding(2) var image_2d_depth: texture_depth_2d; -[[stage(fragment)]] -fn sample_comparison() -> [[location(0)]] f32 { +@stage(fragment) +fn sample_comparison() -> @location(0) f32 { let tc = vec2(0.5); let dref = 0.5; let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc, dref); @@ -121,8 +121,8 @@ fn sample_comparison() -> [[location(0)]] f32 { return s2d_depth + s2d_depth_level; } -[[stage(fragment)]] -fn gather() -> [[location(0)]] vec4 { +@stage(fragment) +fn gather() -> @location(0) vec4 { let tc = vec2(0.5); let dref = 0.5; let s2d = textureGather(1, image_2d, sampler_reg, tc); @@ -132,8 +132,8 @@ fn gather() -> [[location(0)]] vec4 { return s2d + s2d_offset + s2d_depth + s2d_depth_offset; } -[[stage(fragment)]] -fn depth_no_comparison() -> [[location(0)]] vec4 { +@stage(fragment) +fn depth_no_comparison() -> @location(0) vec4 { let tc = vec2(0.5); let s2d = textureSample(image_2d_depth, sampler_reg, tc); let s2d_gather = textureGather(image_2d_depth, sampler_reg, tc); diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index 6b38a434e..f5946c13a 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -1,32 +1,32 @@ // Testing various parts of the pipeline interface: locations, built-ins, and entry points struct VertexOutput { - [[builtin(position)]] position: vec4; - [[location(1)]] varying: f32; + @builtin(position) position: vec4; + @location(1) varying: f32; }; -[[stage(vertex)]] +@stage(vertex) fn vertex( - [[builtin(vertex_index)]] vertex_index: u32, - [[builtin(instance_index)]] instance_index: u32, - [[location(10)]] color: u32, + @builtin(vertex_index) vertex_index: u32, + @builtin(instance_index) instance_index: u32, + @location(10) color: u32, ) -> VertexOutput { let tmp = vertex_index + instance_index + color; return VertexOutput(vec4(1.0), f32(tmp)); } struct FragmentOutput { - [[builtin(frag_depth)]] depth: f32; - [[builtin(sample_mask)]] sample_mask: u32; - [[location(0)]] color: f32; + @builtin(frag_depth) depth: f32; + @builtin(sample_mask) sample_mask: u32; + @location(0) color: f32; }; -[[stage(fragment)]] +@stage(fragment) fn fragment( in: VertexOutput, - [[builtin(front_facing)]] front_facing: bool, - [[builtin(sample_index)]] sample_index: u32, - [[builtin(sample_mask)]] sample_mask: u32, + @builtin(front_facing) front_facing: bool, + @builtin(sample_index) sample_index: u32, + @builtin(sample_mask) sample_mask: u32, ) -> FragmentOutput { let mask = sample_mask & (1u << sample_index); let color = select(0.0, 1.0, front_facing); @@ -35,13 +35,13 @@ fn fragment( var output: array; -[[stage(compute), workgroup_size(1)]] +@stage(compute) @workgroup_size(1) fn compute( - [[builtin(global_invocation_id)]] global_id: vec3, - [[builtin(local_invocation_id)]] local_id: vec3, - [[builtin(local_invocation_index)]] local_index: u32, - [[builtin(workgroup_id)]] wg_id: vec3, - [[builtin(num_workgroups)]] num_wgs: vec3, + @builtin(global_invocation_id) global_id: vec3, + @builtin(local_invocation_id) local_id: vec3, + @builtin(local_invocation_index) local_index: u32, + @builtin(workgroup_id) wg_id: vec3, + @builtin(num_workgroups) num_wgs: vec3, ) { output[0] = global_id.x + local_id.x + local_index + wg_id.x + num_wgs.x; } diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index 9b869e343..a3dea61e5 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -1,17 +1,17 @@ //TODO: merge with "interface"? struct FragmentInput { - [[builtin(position)]] position: vec4; - [[location(0), interpolate(flat)]] flat : u32; - [[location(1), interpolate(linear)]] linear : f32; - [[location(2), interpolate(linear, centroid)]] linear_centroid : vec2; - [[location(3), interpolate(linear, sample)]] linear_sample : vec3; - [[location(4), interpolate(perspective)]] perspective : vec4; - [[location(5), interpolate(perspective, centroid)]] perspective_centroid : f32; - [[location(6), interpolate(perspective, sample)]] perspective_sample : f32; + @builtin(position) position: vec4; + @location(0) @interpolate(flat) flat : u32; + @location(1) @interpolate(linear) linear : f32; + @location(2) @interpolate(linear, centroid) linear_centroid : vec2; + @location(3) @interpolate(linear, sample) linear_sample : vec3; + @location(4) @interpolate(perspective) perspective : vec4; + @location(5) @interpolate(perspective, centroid) perspective_centroid : f32; + @location(6) @interpolate(perspective, sample) perspective_sample : f32; }; -[[stage(vertex)]] +@stage(vertex) fn vert_main() -> FragmentInput { var out: FragmentInput; @@ -27,5 +27,5 @@ fn vert_main() -> FragmentInput { return out; } -[[stage(fragment)]] +@stage(fragment) fn frag_main(val : FragmentInput) { } diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index 90e5720c4..5d3a1f592 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -1,4 +1,4 @@ -[[stage(vertex)]] +@stage(vertex) fn main() { let f = 1.0; let v = vec4(0.0); diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index a7aedb7f2..5252d4031 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -96,7 +96,7 @@ fn binary_assignment() { a &= 0; } -[[stage(compute), workgroup_size(1)]] +@stage(compute) @workgroup_size(1) fn main() { let a = builtins(); let b = splat(); diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl index cf365f390..6eddb7795 100644 --- a/tests/in/pointers.wgsl +++ b/tests/in/pointers.wgsl @@ -8,7 +8,7 @@ struct DynamicArray { arr: array; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var dynamic_array: DynamicArray; fn index_unsized(i: i32, v: u32) { diff --git a/tests/in/policy-mix.wgsl b/tests/in/policy-mix.wgsl index 4dc1e1bce..fe05a3232 100644 --- a/tests/in/policy-mix.wgsl +++ b/tests/in/policy-mix.wgsl @@ -5,15 +5,15 @@ struct InStorage { a: array, 10>; }; -[[group(0), binding(0)]] var in_storage: InStorage; +@group(0) @binding(0) var in_storage: InStorage; struct InUniform { a: array, 20>; }; -[[group(0), binding(1)]] var in_uniform: InUniform; +@group(0) @binding(1) var in_uniform: InUniform; // Textures automatically land in the `handle` storage class. -[[group(0), binding(2)]] var image_2d_array: texture_2d_array; +@group(0) @binding(2) var image_2d_array: texture_2d_array; // None of the above. var in_workgroup: array; diff --git a/tests/in/push-constants.wgsl b/tests/in/push-constants.wgsl index bb5b0e732..d5b4cf99d 100644 --- a/tests/in/push-constants.wgsl +++ b/tests/in/push-constants.wgsl @@ -4,10 +4,10 @@ struct PushConstants { var pc: PushConstants; struct FragmentIn { - [[location(0)]] color: vec4; + @location(0) color: vec4; }; -[[stage(fragment)]] -fn main(in: FragmentIn) -> [[location(0)]] vec4 { +@stage(fragment) +fn main(in: FragmentIn) -> @location(0) vec4 { return in.color * pc.multiplier; } diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 4dd8e8a7d..48334cac1 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -2,24 +2,24 @@ let c_scale: f32 = 1.2; struct VertexOutput { - [[location(0)]] uv : vec2; - [[builtin(position)]] position : vec4; + @location(0) uv : vec2; + @builtin(position) position : vec4; }; -[[stage(vertex)]] +@stage(vertex) fn vert_main( - [[location(0)]] pos : vec2, - [[location(1)]] uv : vec2, + @location(0) pos : vec2, + @location(1) uv : vec2, ) -> VertexOutput { return VertexOutput(uv, vec4(c_scale * pos, 0.0, 1.0)); } // fragment -[[group(0), binding(0)]] var u_texture : texture_2d; -[[group(0), binding(1)]] var u_sampler : sampler; +@group(0) @binding(0) var u_texture : texture_2d; +@group(0) @binding(1) var u_sampler : sampler; -[[stage(fragment)]] -fn frag_main([[location(0)]] uv : vec2) -> [[location(0)]] vec4 { +@stage(fragment) +fn frag_main(@location(0) uv : vec2) -> @location(0) vec4 { let color = textureSample(u_texture, u_sampler, uv); if (color.a == 0.0) { discard; @@ -32,7 +32,7 @@ fn frag_main([[location(0)]] uv : vec2) -> [[location(0)]] vec4 { // We need to make sure that backends are successfully handling multiple entry points for the same shader stage. -[[stage(fragment)]] -fn fs_extra() -> [[location(0)]] vec4 { +@stage(fragment) +fn fs_extra() -> @location(0) vec4 { return vec4(0.0, 0.5, 0.0, 0.5); } diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index f17f7af39..367762d51 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -2,7 +2,7 @@ struct Globals { num_lights: vec4; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var u_globals: Globals; struct Light { @@ -12,14 +12,14 @@ struct Light { }; struct Lights { - data: [[stride(96)]] array; + data: @stride(96) array; }; -[[group(0), binding(1)]] +@group(0) @binding(1) var s_lights: Lights; -[[group(0), binding(2)]] +@group(0) @binding(2) var t_shadow: texture_depth_2d_array; -[[group(0), binding(3)]] +@group(0) @binding(3) var sampler_shadow: sampler_comparison; fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { @@ -34,11 +34,11 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); let c_max_lights: u32 = 10u; -[[stage(fragment)]] +@stage(fragment) fn fs_main( - [[location(0)]] raw_normal: vec3, - [[location(1)]] position: vec4 -) -> [[location(0)]] vec4 { + @location(0) raw_normal: vec3, + @location(1) position: vec4 +) -> @location(0) vec4 { let normal: vec3 = normalize(raw_normal); // accumulate color var color = c_ambient; diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index b21624853..afbc38718 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -1,17 +1,17 @@ struct VertexOutput { - [[builtin(position)]] position: vec4; - [[location(0)]] uv: vec3; + @builtin(position) position: vec4; + @location(0) uv: vec3; }; struct Data { proj_inv: mat4x4; view: mat4x4; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var r_data: Data; -[[stage(vertex)]] -fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { +@stage(vertex) +fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput { // hacky way to draw a large triangle var tmp1 = i32(vertex_index) / 2; var tmp2 = i32(vertex_index) & 1; @@ -27,12 +27,12 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { return VertexOutput(pos, inv_model_view * unprojected.xyz); } -[[group(0), binding(1)]] +@group(0) @binding(1) var r_texture: texture_cube; -[[group(0), binding(2)]] +@group(0) @binding(2) var r_sampler: sampler; -[[stage(fragment)]] -fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 { +@stage(fragment) +fn fs_main(in: VertexOutput) -> @location(0) vec4 { return textureSample(r_texture, r_sampler, in.uv); } diff --git a/tests/in/standard.wgsl b/tests/in/standard.wgsl index a9db49e78..9171db190 100644 --- a/tests/in/standard.wgsl +++ b/tests/in/standard.wgsl @@ -1,7 +1,7 @@ // Standard functions. -[[stage(fragment)]] -fn derivatives([[builtin(position)]] foo: vec4) -> [[location(0)]] vec4 { +@stage(fragment) +fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { let x = dpdx(foo); let y = dpdy(foo); let z = fwidth(foo); diff --git a/tests/in/texture-arg.wgsl b/tests/in/texture-arg.wgsl index af4c382be..70fd586f0 100644 --- a/tests/in/texture-arg.wgsl +++ b/tests/in/texture-arg.wgsl @@ -1,13 +1,13 @@ -[[group(0), binding(0)]] +@group(0) @binding(0) var Texture: texture_2d; -[[group(0), binding(1)]] +@group(0) @binding(1) var Sampler: sampler; fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { return textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); } -[[stage(fragment)]] -fn main() -> [[location(0)]] vec4 { +@stage(fragment) +fn main() -> @location(0) vec4 { return test(Texture, Sampler); } diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index e66de740d..cfb3ce6ce 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -3,12 +3,12 @@ struct ColorMaterial_color { }; struct FragmentOutput { - [[location(0)]] o_Target: vec4; + @location(0) o_Target: vec4; }; var v_Uv_1: vec2; var o_Target: vec4; -[[group(1), binding(0)]] +@group(1) @binding(0) var global: ColorMaterial_color; fn main_1() { @@ -21,8 +21,8 @@ fn main_1() { return; } -[[stage(fragment)]] -fn main([[location(0)]] v_Uv: vec2) -> FragmentOutput { +@stage(fragment) +fn main(@location(0) v_Uv: vec2) -> FragmentOutput { v_Uv_1 = v_Uv; main_1(); let _e9 = o_Target; diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index c368e38d9..18a6630f8 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -11,19 +11,19 @@ struct Sprite_size { }; struct VertexOutput { - [[location(0)]] v_Uv: vec2; - [[builtin(position)]] member: vec4; + @location(0) v_Uv: vec2; + @builtin(position) member: vec4; }; var Vertex_Position_1: vec3; var Vertex_Normal_1: vec3; var Vertex_Uv_1: vec2; var v_Uv: vec2; -[[group(0), binding(0)]] +@group(0) @binding(0) var global: Camera; -[[group(2), binding(0)]] +@group(2) @binding(0) var global_1: Transform; -[[group(2), binding(1)]] +@group(2) @binding(1) var global_2: Sprite_size; var gl_Position: vec4; @@ -42,8 +42,8 @@ fn main_1() { return; } -[[stage(vertex)]] -fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Normal: vec3, [[location(2)]] Vertex_Uv: vec2) -> VertexOutput { +@stage(vertex) +fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec3, @location(2) Vertex_Uv: vec2) -> VertexOutput { Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 4f476b9f1..a2ac6ba10 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -7,10 +7,10 @@ struct Transform { }; struct VertexOutput { - [[location(0)]] v_Position: vec3; - [[location(1)]] v_Normal: vec3; - [[location(2)]] v_Uv: vec2; - [[builtin(position)]] member: vec4; + @location(0) v_Position: vec3; + @location(1) v_Normal: vec3; + @location(2) v_Uv: vec2; + @builtin(position) member: vec4; }; var Vertex_Position_1: vec3; @@ -19,9 +19,9 @@ var Vertex_Uv_1: vec2; var v_Position: vec3; var v_Normal: vec3; var v_Uv: vec2; -[[group(0), binding(0)]] +@group(0) @binding(0) var global: Camera; -[[group(2), binding(0)]] +@group(2) @binding(0) var global_1: Transform; var gl_Position: vec4; @@ -43,8 +43,8 @@ fn main_1() { return; } -[[stage(vertex)]] -fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Normal: vec3, [[location(2)]] Vertex_Uv: vec2) -> VertexOutput { +@stage(vertex) +fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec3, @location(2) Vertex_Uv: vec2) -> VertexOutput { Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index fc344ea50..45d08357c 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -1,8 +1,8 @@ struct PrimeIndices { - indices: [[stride(4)]] array; + indices: @stride(4) array; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var global: PrimeIndices; var gl_GlobalInvocationID: vec3; @@ -51,8 +51,8 @@ fn main_1() { return; } -[[stage(compute), workgroup_size(1, 1, 1)]] -fn main([[builtin(global_invocation_id)]] param: vec3) { +@stage(compute) @workgroup_size(1, 1, 1) +fn main(@builtin(global_invocation_id) param: vec3) { gl_GlobalInvocationID = param; main_1(); return; diff --git a/tests/out/wgsl/277-casting-vert.wgsl b/tests/out/wgsl/277-casting-vert.wgsl index f05db0372..92ab6a516 100644 --- a/tests/out/wgsl/277-casting-vert.wgsl +++ b/tests/out/wgsl/277-casting-vert.wgsl @@ -3,7 +3,7 @@ fn main_1() { } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl index 8826e9e54..b5ee6454d 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl @@ -4,7 +4,7 @@ fn main_1() { let _e1 = f32(1); } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/484-preprocessor-if-vert.wgsl b/tests/out/wgsl/484-preprocessor-if-vert.wgsl index ebd8567c9..ea9cd03d5 100644 --- a/tests/out/wgsl/484-preprocessor-if-vert.wgsl +++ b/tests/out/wgsl/484-preprocessor-if-vert.wgsl @@ -2,7 +2,7 @@ fn main_1() { return; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index 351482d7d..b57fa3e0b 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -7,11 +7,11 @@ struct VertexPushConstants { }; struct VertexOutput { - [[location(0)]] frag_color: vec4; - [[builtin(position)]] member: vec4; + @location(0) frag_color: vec4; + @builtin(position) member: vec4; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var global: Globals; var global_1: VertexPushConstants; var position_1: vec2; @@ -32,8 +32,8 @@ fn main_1() { return; } -[[stage(vertex)]] -fn main([[location(0)]] position: vec2, [[location(1)]] color: vec4) -> VertexOutput { +@stage(vertex) +fn main(@location(0) position: vec2, @location(1) color: vec4) -> VertexOutput { position_1 = position; color_1 = color; main_1(); diff --git a/tests/out/wgsl/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-vert.wgsl index dec43d8d4..f7f2dcfb3 100644 --- a/tests/out/wgsl/896-push-constant-vert.wgsl +++ b/tests/out/wgsl/896-push-constant-vert.wgsl @@ -8,7 +8,7 @@ fn main_1() { return; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/900-implicit-conversions-vert.wgsl b/tests/out/wgsl/900-implicit-conversions-vert.wgsl index bb86b505f..90d97dfab 100644 --- a/tests/out/wgsl/900-implicit-conversions-vert.wgsl +++ b/tests/out/wgsl/900-implicit-conversions-vert.wgsl @@ -61,7 +61,7 @@ fn main_1() { return; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl index 13695097b..6aa3bedd2 100644 --- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl +++ b/tests/out/wgsl/901-lhs-field-select-vert.wgsl @@ -5,7 +5,7 @@ fn main_1() { return; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl index 0e3e656a7..515f41c62 100644 --- a/tests/out/wgsl/931-constant-emitting-vert.wgsl +++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl @@ -6,7 +6,7 @@ fn main_1() { return; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl index f00782e9b..9927e46b0 100644 --- a/tests/out/wgsl/932-for-loop-if-vert.wgsl +++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl @@ -16,7 +16,7 @@ fn main_1() { return; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index ca5313a80..2e4ee4142 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -1,12 +1,12 @@ struct Bar { matrix: mat4x4; - matrix_array: [[stride(16)]] array,2>; + matrix_array: @stride(16) array,2>; atom: atomic; - arr: [[stride(8)]] array,2>; - data: [[stride(8)]] array; + arr: @stride(8) array,2>; + data: @stride(8) array; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var bar: Bar; fn read_from_private(foo_2: ptr) -> f32 { @@ -14,8 +14,8 @@ fn read_from_private(foo_2: ptr) -> f32 { return _e2; } -[[stage(vertex)]] -fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { +@stage(vertex) +fn foo(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo_1: f32 = 0.0; var c: array; @@ -37,7 +37,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4 { return (matrix * vec4(vec4(value))); } -[[stage(compute), workgroup_size(1, 1, 1)]] +@stage(compute) @workgroup_size(1, 1, 1) fn atomics() { var tmp: i32; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index f73f517d4..fa947b893 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -20,8 +20,8 @@ struct CameraPosition { struct Lights { AmbientColor: vec4; NumLights: vec4; - PointLights: [[stride(48)]] array; - DirectionalLights: [[stride(32)]] array; + PointLights: @stride(48) array; + DirectionalLights: @stride(32) array; }; struct StandardMaterial_base_color { @@ -45,7 +45,7 @@ struct StandardMaterial_emissive { }; struct FragmentOutput { - [[location(0)]] o_Target: vec4; + @location(0) o_Target: vec4; }; var v_WorldPosition_1: vec3; @@ -53,41 +53,41 @@ var v_WorldNormal_1: vec3; var v_Uv_1: vec2; var v_WorldTangent_1: vec4; var o_Target: vec4; -[[group(0), binding(0)]] +@group(0) @binding(0) var global: CameraViewProj; -[[group(0), binding(1)]] +@group(0) @binding(1) var global_1: CameraPosition; -[[group(1), binding(0)]] +@group(1) @binding(0) var global_2: Lights; -[[group(3), binding(0)]] +@group(3) @binding(0) var global_3: StandardMaterial_base_color; -[[group(3), binding(1)]] +@group(3) @binding(1) var StandardMaterial_base_color_texture: texture_2d; -[[group(3), binding(2)]] +@group(3) @binding(2) var StandardMaterial_base_color_texture_sampler: sampler; -[[group(3), binding(3)]] +@group(3) @binding(3) var global_4: StandardMaterial_roughness; -[[group(3), binding(4)]] +@group(3) @binding(4) var global_5: StandardMaterial_metallic; -[[group(3), binding(5)]] +@group(3) @binding(5) var StandardMaterial_metallic_roughness_texture: texture_2d; -[[group(3), binding(6)]] +@group(3) @binding(6) var StandardMaterial_metallic_roughness_texture_sampler: sampler; -[[group(3), binding(7)]] +@group(3) @binding(7) var global_6: StandardMaterial_reflectance; -[[group(3), binding(8)]] +@group(3) @binding(8) var StandardMaterial_normal_map: texture_2d; -[[group(3), binding(9)]] +@group(3) @binding(9) var StandardMaterial_normal_map_sampler: sampler; -[[group(3), binding(10)]] +@group(3) @binding(10) var StandardMaterial_occlusion_texture: texture_2d; -[[group(3), binding(11)]] +@group(3) @binding(11) var StandardMaterial_occlusion_texture_sampler: sampler; -[[group(3), binding(12)]] +@group(3) @binding(12) var global_7: StandardMaterial_emissive; -[[group(3), binding(13)]] +@group(3) @binding(13) var StandardMaterial_emissive_texture: texture_2d; -[[group(3), binding(14)]] +@group(3) @binding(14) var StandardMaterial_emissive_texture_sampler: sampler; var gl_FrontFacing: bool; @@ -895,8 +895,8 @@ fn main_1() { return; } -[[stage(fragment)]] -fn main([[location(0)]] v_WorldPosition: vec3, [[location(1)]] v_WorldNormal: vec3, [[location(2)]] v_Uv: vec2, [[location(3)]] v_WorldTangent: vec4, [[builtin(front_facing)]] param: bool) -> FragmentOutput { +@stage(fragment) +fn main(@location(0) v_WorldPosition: vec3, @location(1) v_WorldNormal: vec3, @location(2) v_Uv: vec2, @location(3) v_WorldTangent: vec4, @builtin(front_facing) param: bool) -> FragmentOutput { v_WorldPosition_1 = v_WorldPosition; v_WorldNormal_1 = v_WorldNormal; v_Uv_1 = v_Uv; diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 34f836704..617537fad 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -7,11 +7,11 @@ struct Transform { }; struct VertexOutput { - [[location(0)]] v_WorldPosition: vec3; - [[location(1)]] v_WorldNormal: vec3; - [[location(2)]] v_Uv: vec2; - [[location(3)]] v_WorldTangent: vec4; - [[builtin(position)]] member: vec4; + @location(0) v_WorldPosition: vec3; + @location(1) v_WorldNormal: vec3; + @location(2) v_Uv: vec2; + @location(3) v_WorldTangent: vec4; + @builtin(position) member: vec4; }; var Vertex_Position_1: vec3; @@ -21,10 +21,10 @@ var Vertex_Tangent_1: vec4; var v_WorldPosition: vec3; var v_WorldNormal: vec3; var v_Uv: vec2; -[[group(0), binding(0)]] +@group(0) @binding(0) var global: CameraViewProj; var v_WorldTangent: vec4; -[[group(2), binding(0)]] +@group(2) @binding(0) var global_1: Transform; var gl_Position: vec4; @@ -52,8 +52,8 @@ fn main_1() { return; } -[[stage(vertex)]] -fn main([[location(0)]] Vertex_Position: vec3, [[location(1)]] Vertex_Normal: vec3, [[location(2)]] Vertex_Uv: vec2, [[location(3)]] Vertex_Tangent: vec4) -> VertexOutput { +@stage(vertex) +fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec3, @location(2) Vertex_Uv: vec2, @location(3) Vertex_Tangent: vec4) -> VertexOutput { Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; diff --git a/tests/out/wgsl/binop-frag.wgsl b/tests/out/wgsl/binop-frag.wgsl index 40e8c8216..8edf934b3 100644 --- a/tests/out/wgsl/binop-frag.wgsl +++ b/tests/out/wgsl/binop-frag.wgsl @@ -180,7 +180,7 @@ fn main1() { return; } -[[stage(fragment)]] +@stage(fragment) fn main() { main1(); return; diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index 45037118b..1af9b969d 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -1,4 +1,4 @@ -[[stage(compute), workgroup_size(1, 1, 1)]] +@stage(compute) @workgroup_size(1, 1, 1) fn main() { var i: i32 = 0; var i2_: vec2; diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 29f77ca76..8faa6e26e 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -105,7 +105,7 @@ fn main_1() { return; } -[[stage(fragment)]] +@stage(fragment) fn main() { main_1(); return; diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 6a5d4c269..7b1e9af1e 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -14,20 +14,20 @@ struct SimParams { }; struct Particles { - particles: [[stride(16)]] array; + particles: @stride(16) array; }; let NUM_PARTICLES: u32 = 1500u; -[[group(0), binding(0)]] +@group(0) @binding(0) var params: SimParams; -[[group(0), binding(1)]] +@group(0) @binding(1) var particlesSrc: Particles; -[[group(0), binding(2)]] +@group(0) @binding(2) var particlesDst: Particles; -[[stage(compute), workgroup_size(64, 1, 1)]] -fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) { +@stage(compute) @workgroup_size(64, 1, 1) +fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { var vPos: vec2; var vVel: vec2; var cMass: vec2; diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index 1b0ce4b29..c1d5502cf 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -1,5 +1,5 @@ struct FragmentOutput { - [[location(0)]] o_color: vec4; + @location(0) o_color: vec4; }; var o_color: vec4; @@ -37,7 +37,7 @@ fn main_1() { return; } -[[stage(fragment)]] +@stage(fragment) fn main() -> FragmentOutput { main_1(); let _e3 = o_color; diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index 15cf4abbe..953ea71cc 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -1,5 +1,5 @@ struct VertexOutput { - [[builtin(position)]] member: vec4; + @builtin(position) member: vec4; }; var a_pos_1: vec2; @@ -12,8 +12,8 @@ fn main_1() { return; } -[[stage(vertex)]] -fn main([[location(0)]] a_pos: vec2) -> VertexOutput { +@stage(vertex) +fn main(@location(0) a_pos: vec2) -> VertexOutput { a_pos_1 = a_pos; main_1(); let _e5 = gl_Position; diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index 281df6fb7..054ecf364 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -1,8 +1,8 @@ struct PrimeIndices { - data: [[stride(4)]] array; + data: @stride(4) array; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var v_indices: PrimeIndices; fn collatz_iterations(n_base: u32) -> u32 { @@ -30,8 +30,8 @@ fn collatz_iterations(n_base: u32) -> u32 { return _e24; } -[[stage(compute), workgroup_size(1, 1, 1)]] -fn main([[builtin(global_invocation_id)]] global_id: vec3) { +@stage(compute) @workgroup_size(1, 1, 1) +fn main(@builtin(global_invocation_id) global_id: vec3) { let _e8 = v_indices.data[global_id.x]; let _e9 = collatz_iterations(_e8); v_indices.data[global_id.x] = _e9; diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 02d04dc52..9a767c858 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -1,8 +1,8 @@ struct Data { - vecs: [[stride(16)]] array,42u>; + vecs: @stride(16) array,42u>; }; -[[group(1), binding(0)]] +@group(1) @binding(0) var global: Data; fn function_() -> vec4 { @@ -33,7 +33,7 @@ fn main_1() { return; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index 06b6f4865..fad5a45e8 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -30,8 +30,8 @@ fn loop_switch_continue(x: i32) { return; } -[[stage(compute), workgroup_size(1, 1, 1)]] -fn main([[builtin(global_invocation_id)]] global_id: vec3) { +@stage(compute) @workgroup_size(1, 1, 1) +fn main(@builtin(global_invocation_id) global_id: vec3) { var pos: i32; storageBarrier(); diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index 654a1cc2c..867315090 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -14,8 +14,8 @@ struct TestStruct { }; struct VertexOutput { - [[location(0)]] position: vec2; - [[location(1)]] a: vec2; + @location(0) position: vec2; + @location(1) a: vec2; }; var vert: VertexData; @@ -27,8 +27,8 @@ fn main_1() { } -[[stage(vertex)]] -fn main([[location(0)]] position: vec2, [[location(1)]] a: vec2) -> VertexOutput { +@stage(vertex) +fn main(@location(0) position: vec2, @location(1) a: vec2) -> VertexOutput { vert.position = position; vert.a = a; main_1(); diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index f912dfdff..1baaf03e2 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -2,7 +2,7 @@ struct type_1 { member: i32; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var unnamed: type_1; fn function_() { @@ -11,7 +11,7 @@ fn function_() { return; } -[[stage(compute), workgroup_size(64, 1, 1)]] +@stage(compute) @workgroup_size(64, 1, 1) fn main() { function_(); } diff --git a/tests/out/wgsl/empty.wgsl b/tests/out/wgsl/empty.wgsl index 1ee73b580..527a0d56c 100644 --- a/tests/out/wgsl/empty.wgsl +++ b/tests/out/wgsl/empty.wgsl @@ -1,4 +1,4 @@ -[[stage(compute), workgroup_size(1, 1, 1)]] +@stage(compute) @workgroup_size(1, 1, 1) fn main() { return; } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 22354e38e..86589b1af 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -211,7 +211,7 @@ fn main_1() { return; } -[[stage(fragment)]] +@stage(fragment) fn main() { main_1(); return; diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index b9fbfb74c..5dc44e463 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -4,14 +4,14 @@ struct PushConstants { }; struct FragmentIn { - [[location(0)]] color: vec4; - [[builtin(primitive_index)]] primitive_index: u32; + @location(0) color: vec4; + @builtin(primitive_index) primitive_index: u32; }; var pc: PushConstants; -[[stage(fragment)]] -fn main(in: FragmentIn) -> [[location(0)]] vec4 { +@stage(fragment) +fn main(in: FragmentIn) -> @location(0) vec4 { if (((in.primitive_index % 2u) == 0u)) { return in.color; } else { diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index d125e1353..543311de9 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -37,7 +37,7 @@ fn main_1() { return; } -[[stage(fragment)]] +@stage(fragment) fn main() { main_1(); return; diff --git a/tests/out/wgsl/functions.wgsl b/tests/out/wgsl/functions.wgsl index 9b6b41a09..5a53e38c6 100644 --- a/tests/out/wgsl/functions.wgsl +++ b/tests/out/wgsl/functions.wgsl @@ -5,7 +5,7 @@ fn test_fma() -> vec2 { return fma(a, b, c); } -[[stage(compute), workgroup_size(1, 1, 1)]] +@stage(compute) @workgroup_size(1, 1, 1) fn main() { let _e0 = test_fma(); return; diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index f94744eb9..117c2e57c 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -6,7 +6,7 @@ fn main_1() { let _e2 = i; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index c33296333..84705602a 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -4,19 +4,19 @@ struct Foo { }; struct Dummy { - arr: [[stride(8)]] array>; + arr: @stride(8) array>; }; let Foo_2: bool = true; var wg: array; var at_1: atomic; -[[group(0), binding(1)]] +@group(0) @binding(1) var alignment: Foo; -[[group(0), binding(2)]] +@group(0) @binding(2) var dummy: Dummy; -[[stage(compute), workgroup_size(1, 1, 1)]] +@stage(compute) @workgroup_size(1, 1, 1) fn main() { var Foo_1: f32 = 1.0; var at: bool = true; diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index ec40004e1..b2b2edffa 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -1,42 +1,42 @@ -[[group(0), binding(0)]] +@group(0) @binding(0) var image_mipmapped_src: texture_2d; -[[group(0), binding(3)]] +@group(0) @binding(3) var image_multisampled_src: texture_multisampled_2d; -[[group(0), binding(4)]] +@group(0) @binding(4) var image_depth_multisampled_src: texture_depth_multisampled_2d; -[[group(0), binding(1)]] +@group(0) @binding(1) var image_storage_src: texture_storage_2d; -[[group(0), binding(5)]] +@group(0) @binding(5) var image_array_src: texture_2d_array; -[[group(0), binding(6)]] +@group(0) @binding(6) var image_dup_src: texture_storage_1d; -[[group(0), binding(7)]] +@group(0) @binding(7) var image_1d_src: texture_1d; -[[group(0), binding(2)]] +@group(0) @binding(2) var image_dst: texture_storage_1d; -[[group(0), binding(0)]] +@group(0) @binding(0) var image_1d: texture_1d; -[[group(0), binding(1)]] +@group(0) @binding(1) var image_2d: texture_2d; -[[group(0), binding(2)]] +@group(0) @binding(2) var image_2d_array: texture_2d_array; -[[group(0), binding(3)]] +@group(0) @binding(3) var image_cube: texture_cube; -[[group(0), binding(4)]] +@group(0) @binding(4) var image_cube_array: texture_cube_array; -[[group(0), binding(5)]] +@group(0) @binding(5) var image_3d: texture_3d; -[[group(0), binding(6)]] +@group(0) @binding(6) var image_aa: texture_multisampled_2d; -[[group(1), binding(0)]] +@group(1) @binding(0) var sampler_reg: sampler; -[[group(1), binding(1)]] +@group(1) @binding(1) var sampler_cmp: sampler_comparison; -[[group(1), binding(2)]] +@group(1) @binding(2) var image_2d_depth: texture_depth_2d; -[[stage(compute), workgroup_size(16, 1, 1)]] -fn main([[builtin(local_invocation_id)]] local_id: vec3) { +@stage(compute) @workgroup_size(16, 1, 1) +fn main(@builtin(local_invocation_id) local_id: vec3) { let dim = textureDimensions(image_storage_src); let itc = ((dim * vec2(local_id.xy)) % vec2(10, 20)); let value1_ = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); @@ -48,8 +48,8 @@ fn main([[builtin(local_invocation_id)]] local_id: vec3) { return; } -[[stage(compute), workgroup_size(16, 1, 1)]] -fn depth_load([[builtin(local_invocation_id)]] local_id_1: vec3) { +@stage(compute) @workgroup_size(16, 1, 1) +fn depth_load(@builtin(local_invocation_id) local_id_1: vec3) { let dim_1 = textureDimensions(image_storage_src); let itc_1 = ((dim_1 * vec2(local_id_1.xy)) % vec2(10, 20)); let val = textureLoad(image_depth_multisampled_src, itc_1, i32(local_id_1.z)); @@ -57,8 +57,8 @@ fn depth_load([[builtin(local_invocation_id)]] local_id_1: vec3) { return; } -[[stage(vertex)]] -fn queries() -> [[builtin(position)]] vec4 { +@stage(vertex) +fn queries() -> @builtin(position) vec4 { let dim_1d = textureDimensions(image_1d); let dim_1d_lod = textureDimensions(image_1d, i32(dim_1d)); let dim_2d = textureDimensions(image_2d); @@ -75,8 +75,8 @@ fn queries() -> [[builtin(position)]] vec4 { return vec4(f32(sum)); } -[[stage(vertex)]] -fn levels_queries() -> [[builtin(position)]] vec4 { +@stage(vertex) +fn levels_queries() -> @builtin(position) vec4 { let num_levels_2d = textureNumLevels(image_2d); let num_levels_2d_array = textureNumLevels(image_2d_array); let num_layers_2d = textureNumLayers(image_2d_array); @@ -89,8 +89,8 @@ fn levels_queries() -> [[builtin(position)]] vec4 { return vec4(f32(sum_1)); } -[[stage(fragment)]] -fn sample() -> [[location(0)]] vec4 { +@stage(fragment) +fn sample() -> @location(0) vec4 { let tc = vec2(0.5); let s1d = textureSample(image_1d, sampler_reg, tc.x); let s2d = textureSample(image_2d, sampler_reg, tc); @@ -100,16 +100,16 @@ fn sample() -> [[location(0)]] vec4 { return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); } -[[stage(fragment)]] -fn sample_comparison() -> [[location(0)]] f32 { +@stage(fragment) +fn sample_comparison() -> @location(0) f32 { let tc_1 = vec2(0.5); let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5); return (s2d_depth + s2d_depth_level); } -[[stage(fragment)]] -fn gather() -> [[location(0)]] vec4 { +@stage(fragment) +fn gather() -> @location(0) vec4 { let tc_2 = vec2(0.5); let s2d_1 = textureGather(1, image_2d, sampler_reg, tc_2); let s2d_offset_1 = textureGather(3, image_2d, sampler_reg, tc_2, vec2(3, 1)); @@ -118,8 +118,8 @@ fn gather() -> [[location(0)]] vec4 { return (((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset); } -[[stage(fragment)]] -fn depth_no_comparison() -> [[location(0)]] vec4 { +@stage(fragment) +fn depth_no_comparison() -> @location(0) vec4 { let tc_3 = vec2(0.5); let s2d_2 = textureSample(image_2d_depth, sampler_reg, tc_3); let s2d_gather = textureGather(image_2d_depth, sampler_reg, tc_3); diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index f576915f3..7d40bb321 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -1,31 +1,31 @@ struct VertexOutput { - [[builtin(position)]] position: vec4; - [[location(1)]] varying: f32; + @builtin(position) position: vec4; + @location(1) varying: f32; }; struct FragmentOutput { - [[builtin(frag_depth)]] depth: f32; - [[builtin(sample_mask)]] sample_mask: u32; - [[location(0)]] color: f32; + @builtin(frag_depth) depth: f32; + @builtin(sample_mask) sample_mask: u32; + @location(0) color: f32; }; var output: array; -[[stage(vertex)]] -fn vertex([[builtin(vertex_index)]] vertex_index: u32, [[builtin(instance_index)]] instance_index: u32, [[location(10)]] color: u32) -> VertexOutput { +@stage(vertex) +fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) instance_index: u32, @location(10) color: u32) -> VertexOutput { let tmp: u32 = ((vertex_index + instance_index) + color); return VertexOutput(vec4(1.0), f32(tmp)); } -[[stage(fragment)]] -fn fragment(in: VertexOutput, [[builtin(front_facing)]] front_facing: bool, [[builtin(sample_index)]] sample_index: u32, [[builtin(sample_mask)]] sample_mask: u32) -> FragmentOutput { +@stage(fragment) +fn fragment(in: VertexOutput, @builtin(front_facing) front_facing: bool, @builtin(sample_index) sample_index: u32, @builtin(sample_mask) sample_mask: u32) -> FragmentOutput { let mask: u32 = (sample_mask & (1u << sample_index)); let color_1: f32 = select(0.0, 1.0, front_facing); return FragmentOutput(in.varying, mask, color_1); } -[[stage(compute), workgroup_size(1, 1, 1)]] -fn compute([[builtin(global_invocation_id)]] global_id: vec3, [[builtin(local_invocation_id)]] local_id: vec3, [[builtin(local_invocation_index)]] local_index: u32, [[builtin(workgroup_id)]] wg_id: vec3, [[builtin(num_workgroups)]] num_wgs: vec3) { +@stage(compute) @workgroup_size(1, 1, 1) +fn compute(@builtin(global_invocation_id) global_id: vec3, @builtin(local_invocation_id) local_id: vec3, @builtin(local_invocation_index) local_index: u32, @builtin(workgroup_id) wg_id: vec3, @builtin(num_workgroups) num_wgs: vec3) { output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x); return; } diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index c98b74f64..69ccd9630 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -1,15 +1,15 @@ struct FragmentInput { - [[builtin(position)]] position: vec4; - [[location(0)]] flat: u32; - [[location(1), interpolate(linear)]] linear: f32; - [[location(2), interpolate(linear, centroid)]] linear_centroid: vec2; - [[location(3), interpolate(linear, sample)]] linear_sample: vec3; - [[location(4)]] perspective: vec4; - [[location(5), interpolate(perspective, centroid)]] perspective_centroid: f32; - [[location(6), interpolate(perspective, sample)]] perspective_sample: f32; + @builtin(position) position: vec4; + @location(0) flat: u32; + @location(1) @interpolate(linear) linear: f32; + @location(2) @interpolate(linear, centroid) linear_centroid: vec2; + @location(3) @interpolate(linear, sample) linear_sample: vec3; + @location(4) perspective: vec4; + @location(5) @interpolate(perspective, centroid) perspective_centroid: f32; + @location(6) @interpolate(perspective, sample) perspective_sample: f32; }; -[[stage(vertex)]] +@stage(vertex) fn vert_main() -> FragmentInput { var out: FragmentInput; @@ -25,7 +25,7 @@ fn vert_main() -> FragmentInput { return _e30; } -[[stage(fragment)]] +@stage(fragment) fn frag_main(val: FragmentInput) { return; } diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl index 87ee33368..d1bd7724f 100644 --- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -14,7 +14,7 @@ fn main_1() { return; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); } diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index b3056a9b5..7b0958044 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -25,7 +25,7 @@ fn main_1() { let _e129 = vec4(f32(1)); } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index ee04f886d..3053f0240 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -154,7 +154,7 @@ fn main_1() { return; } -[[stage(vertex)]] +@stage(vertex) fn main() { main_1(); return; diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 53a293e51..c4ae1673a 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -1,4 +1,4 @@ -[[stage(vertex)]] +@stage(vertex) fn main() { let v = vec4(0.0); let a = degrees(1.0); diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index ee1ef36d6..53c1c1701 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -87,7 +87,7 @@ fn binary_assignment() { return; } -[[stage(compute), workgroup_size(1, 1, 1)]] +@stage(compute) @workgroup_size(1, 1, 1) fn main() { let _e4 = builtins(); let _e5 = splat(); diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index df8e6553a..0ac148e1c 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -1,8 +1,8 @@ struct DynamicArray { - arr: [[stride(4)]] array; + arr: @stride(4) array; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var dynamic_array: DynamicArray; fn f() { diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index 54147d5a0..e7a32ef74 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -33,7 +33,7 @@ fn main_1() { return; } -[[stage(fragment)]] +@stage(fragment) fn main() { main_1(); return; diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index b08aae9e6..eaec42913 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -1,10 +1,10 @@ struct gl_PerVertex { - [[builtin(position)]] gl_Position: vec4; + @builtin(position) gl_Position: vec4; }; struct VertexOutput { - [[location(0)]] member: vec2; - [[builtin(position)]] gl_Position: vec4; + @location(0) member: vec2; + @builtin(position) gl_Position: vec4; }; var v_uv: vec2; @@ -20,8 +20,8 @@ fn main_1() { return; } -[[stage(vertex)]] -fn main([[location(1)]] a_uv: vec2, [[location(0)]] a_pos: vec2) -> VertexOutput { +@stage(vertex) +fn main(@location(1) a_uv: vec2, @location(0) a_pos: vec2) -> VertexOutput { a_uv_1 = a_uv; a_pos_1 = a_pos; main_1(); diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index c5dcbdadc..0f6e3f56d 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -1,22 +1,22 @@ struct VertexOutput { - [[location(0)]] uv: vec2; - [[builtin(position)]] position: vec4; + @location(0) uv: vec2; + @builtin(position) position: vec4; }; let c_scale: f32 = 1.2000000476837158; -[[group(0), binding(0)]] +@group(0) @binding(0) var u_texture: texture_2d; -[[group(0), binding(1)]] +@group(0) @binding(1) var u_sampler: sampler; -[[stage(vertex)]] -fn vert_main([[location(0)]] pos: vec2, [[location(1)]] uv: vec2) -> VertexOutput { +@stage(vertex) +fn vert_main(@location(0) pos: vec2, @location(1) uv: vec2) -> VertexOutput { return VertexOutput(uv, vec4((c_scale * pos), 0.0, 1.0)); } -[[stage(fragment)]] -fn frag_main([[location(0)]] uv_1: vec2) -> [[location(0)]] vec4 { +@stage(fragment) +fn frag_main(@location(0) uv_1: vec2) -> @location(0) vec4 { let color = textureSample(u_texture, u_sampler, uv_1); if ((color.w == 0.0)) { discard; @@ -25,7 +25,7 @@ fn frag_main([[location(0)]] uv_1: vec2) -> [[location(0)]] vec4 { return premultiplied; } -[[stage(fragment)]] -fn fs_extra() -> [[location(0)]] vec4 { +@stage(fragment) +fn fs_extra() -> @location(0) vec4 { return vec4(0.0, 0.5, 0.0, 0.5); } diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 6e9b6f1a8..74276c9d6 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -1,5 +1,5 @@ struct FragmentOutput { - [[location(0)]] o_color: vec4; + @location(0) o_color: vec4; }; var v_uv_1: vec2; @@ -10,8 +10,8 @@ fn main_1() { return; } -[[stage(fragment)]] -fn main([[location(0)]] v_uv: vec2) -> FragmentOutput { +@stage(fragment) +fn main(@location(0) v_uv: vec2) -> FragmentOutput { v_uv_1 = v_uv; main_1(); let _e7 = o_color; diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index 5af301d95..470286a3c 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -1,6 +1,6 @@ struct VertexOutput { - [[location(0)]] v_uv: vec2; - [[builtin(position)]] member: vec4; + @location(0) v_uv: vec2; + @builtin(position) member: vec4; }; var a_pos_1: vec2; @@ -17,8 +17,8 @@ fn main_1() { return; } -[[stage(vertex)]] -fn main([[location(0)]] a_pos: vec2, [[location(1)]] a_uv: vec2) -> VertexOutput { +@stage(vertex) +fn main(@location(0) a_pos: vec2, @location(1) a_uv: vec2) -> VertexOutput { a_pos_1 = a_pos; a_uv_1 = a_uv; main_1(); diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index a902c4e83..f4ec16972 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -1,30 +1,30 @@ -[[group(1), binding(0)]] +@group(1) @binding(0) var tex1D: texture_1d; -[[group(1), binding(1)]] +@group(1) @binding(1) var tex1DArray: texture_1d_array; -[[group(1), binding(2)]] +@group(1) @binding(2) var tex2D: texture_2d; -[[group(1), binding(3)]] +@group(1) @binding(3) var tex2DArray: texture_2d_array; -[[group(1), binding(4)]] +@group(1) @binding(4) var texCube: texture_cube; -[[group(1), binding(5)]] +@group(1) @binding(5) var texCubeArray: texture_cube_array; -[[group(1), binding(6)]] +@group(1) @binding(6) var tex3D: texture_3d; -[[group(1), binding(7)]] +@group(1) @binding(7) var samp: sampler; -[[group(1), binding(12)]] +@group(1) @binding(12) var tex2DShadow: texture_depth_2d; -[[group(1), binding(13)]] +@group(1) @binding(13) var tex2DArrayShadow: texture_depth_2d_array; -[[group(1), binding(14)]] +@group(1) @binding(14) var texCubeShadow: texture_depth_cube; -[[group(1), binding(15)]] +@group(1) @binding(15) var texCubeArrayShadow: texture_depth_cube_array; -[[group(1), binding(16)]] +@group(1) @binding(16) var tex3DShadow: texture_3d; -[[group(1), binding(17)]] +@group(1) @binding(17) var sampShadow: sampler_comparison; var texcoord_1: vec4; @@ -566,8 +566,8 @@ fn main_1() { return; } -[[stage(fragment)]] -fn main([[location(0)]] texcoord: vec4) { +@stage(fragment) +fn main(@location(0) texcoord: vec4) { texcoord_1 = texcoord; main_1(); return; diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index d27b0a895..f6e9e50e6 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -9,19 +9,19 @@ struct Light { }; struct Lights { - data: [[stride(96)]] array; + data: @stride(96) array; }; let c_ambient: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); let c_max_lights: u32 = 10u; -[[group(0), binding(0)]] +@group(0) @binding(0) var u_globals: Globals; -[[group(0), binding(1)]] +@group(0) @binding(1) var s_lights: Lights; -[[group(0), binding(2)]] +@group(0) @binding(2) var t_shadow: texture_depth_2d_array; -[[group(0), binding(3)]] +@group(0) @binding(3) var sampler_shadow: sampler_comparison; fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { @@ -34,8 +34,8 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { return _e26; } -[[stage(fragment)]] -fn fs_main([[location(0)]] raw_normal: vec3, [[location(1)]] position: vec4) -> [[location(0)]] vec4 { +@stage(fragment) +fn fs_main(@location(0) raw_normal: vec3, @location(1) position: vec4) -> @location(0) vec4 { var color: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i: u32 = 0u; diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index 8b52c97da..93b5f06e5 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -1,6 +1,6 @@ struct VertexOutput { - [[builtin(position)]] position: vec4; - [[location(0)]] uv: vec3; + @builtin(position) position: vec4; + @location(0) uv: vec3; }; struct Data { @@ -8,15 +8,15 @@ struct Data { view: mat4x4; }; -[[group(0), binding(0)]] +@group(0) @binding(0) var r_data: Data; -[[group(0), binding(1)]] +@group(0) @binding(1) var r_texture: texture_cube; -[[group(0), binding(2)]] +@group(0) @binding(2) var r_sampler: sampler; -[[stage(vertex)]] -fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { +@stage(vertex) +fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput { var tmp1_: i32; var tmp2_: i32; @@ -34,8 +34,8 @@ fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput { return VertexOutput(pos, (inv_model_view * unprojected.xyz)); } -[[stage(fragment)]] -fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 { +@stage(fragment) +fn fs_main(in: VertexOutput) -> @location(0) vec4 { let _e5 = textureSample(r_texture, r_sampler, in.uv); return _e5; } diff --git a/tests/out/wgsl/standard.wgsl b/tests/out/wgsl/standard.wgsl index c6a94c494..ea6a13a47 100644 --- a/tests/out/wgsl/standard.wgsl +++ b/tests/out/wgsl/standard.wgsl @@ -1,5 +1,5 @@ -[[stage(fragment)]] -fn derivatives([[builtin(position)]] foo: vec4) -> [[location(0)]] vec4 { +@stage(fragment) +fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { let x = dpdx(foo); let y = dpdy(foo); let z = fwidth(foo); diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index 04bbd7ec5..5ca505041 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -30,7 +30,7 @@ fn main_1() { return; } -[[stage(fragment)]] +@stage(fragment) fn main() { main_1(); return; diff --git a/tests/out/wgsl/texture-arg.wgsl b/tests/out/wgsl/texture-arg.wgsl index 2be8f185c..49d398499 100644 --- a/tests/out/wgsl/texture-arg.wgsl +++ b/tests/out/wgsl/texture-arg.wgsl @@ -1,6 +1,6 @@ -[[group(0), binding(0)]] +@group(0) @binding(0) var Texture: texture_2d; -[[group(0), binding(1)]] +@group(0) @binding(1) var Sampler: sampler; fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { @@ -8,8 +8,8 @@ fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { return _e7; } -[[stage(fragment)]] -fn main() -> [[location(0)]] vec4 { +@stage(fragment) +fn main() -> @location(0) vec4 { let _e2 = test(Texture, Sampler); return _e2; } diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs index 0567c19f0..f7511571d 100644 --- a/tests/spirv-capabilities.rs +++ b/tests/spirv-capabilities.rs @@ -62,7 +62,7 @@ fn sampler1d() { require( &[Ca::Sampled1D], r#" - [[group(0), binding(0)]] + @group(0) @binding(0) var image_1d: texture_1d; "#, ); @@ -73,7 +73,7 @@ fn storage1d() { require( &[Ca::Image1D], r#" - [[group(0), binding(0)]] + @group(0) @binding(0) var image_1d: texture_storage_1d; "#, ); @@ -87,7 +87,7 @@ fn cube_array() { &[Ca::SampledCubeArray], &[Ca::ImageCubeArray], r#" - [[group(0), binding(0)]] + @group(0) @binding(0) var image_cube: texture_cube_array; "#, ); @@ -134,16 +134,16 @@ fn sample_rate_shading() { require( &[Ca::SampleRateShading], r#" - [[stage(fragment)]] - fn f([[location(0), interpolate(perspective, sample)]] x: f32) { } + @stage(fragment) + fn f(@location(0) @interpolate(perspective, sample) x: f32) { } "#, ); require( &[Ca::SampleRateShading], r#" - [[stage(fragment)]] - fn f([[builtin(sample_index)]] x: u32) { } + @stage(fragment) + fn f(@builtin(sample_index) x: u32) { } "#, ); } @@ -153,8 +153,8 @@ fn geometry() { require( &[Ca::Geometry], r#" - [[stage(fragment)]] - fn f([[builtin(primitive_index)]] x: u32) { } + @stage(fragment) + fn f(@builtin(primitive_index) x: u32) { } "#, ); } @@ -165,7 +165,7 @@ fn storage_image_formats() { &[Ca::Shader], &[Ca::StorageImageExtendedFormats], r#" - [[group(0), binding(0)]] + @group(0) @binding(0) var image_rg32f: texture_storage_2d; "#, ); @@ -173,7 +173,7 @@ fn storage_image_formats() { require( &[Ca::StorageImageExtendedFormats], r#" - [[group(0), binding(0)]] + @group(0) @binding(0) var image_rg32f: texture_storage_2d; "#, ); diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index ac0d21688..d6224ce8a 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -128,10 +128,10 @@ fn negative_index() { fn bad_texture() { check( r#" - [[group(0), binding(0)]] var sampler1 : sampler; + @group(0) @binding(0) var sampler1 : sampler; - [[stage(fragment)]] - fn main() -> [[location(0)]] vec4 { + @stage(fragment) + fn main() -> @location(0) vec4 { let a = 3; return textureSample(a, sampler1, vec2(0.0)); } @@ -168,19 +168,19 @@ fn bad_type_cast() { fn bad_texture_sample_type() { check( r#" - [[group(0), binding(0)]] var sampler1 : sampler; - [[group(0), binding(1)]] var texture : texture_2d; + @group(0) @binding(0) var sampler1 : sampler; + @group(0) @binding(1) var texture : texture_2d; - [[stage(fragment)]] - fn main() -> [[location(0)]] vec4 { + @stage(fragment) + fn main() -> @location(0) vec4 { return textureSample(texture, sampler1, vec2(0.0)); } "#, r#"error: texture sample type must be one of f32, i32 or u32, but found bool - ┌─ wgsl:3:63 + ┌─ wgsl:3:60 │ -3 │ [[group(0), binding(1)]] var texture : texture_2d; - │ ^^^^ must be one of f32, i32 or u32 +3 │ @group(0) @binding(1) var texture : texture_2d; + │ ^^^^ must be one of f32, i32 or u32 "#, ); @@ -208,13 +208,13 @@ fn bad_for_initializer() { fn unknown_storage_class() { check( r#" - [[group(0), binding(0)]] var texture: texture_2d; + @group(0) @binding(0) var texture: texture_2d; "#, r#"error: unknown storage class: 'bad' - ┌─ wgsl:2:42 + ┌─ wgsl:2:39 │ -2 │ [[group(0), binding(0)]] var texture: texture_2d; - │ ^^^ unknown storage class +2 │ @group(0) @binding(0) var texture: texture_2d; + │ ^^^ unknown storage class "#, ); @@ -224,14 +224,14 @@ fn unknown_storage_class() { fn unknown_attribute() { check( r#" - [[a]] + @a fn x() {} "#, r#"error: unknown attribute: 'a' - ┌─ wgsl:2:15 + ┌─ wgsl:2:14 │ -2 │ [[a]] - │ ^ unknown attribute +2 │ @a + │ ^ unknown attribute "#, ); @@ -241,13 +241,13 @@ fn unknown_attribute() { fn unknown_built_in() { check( r#" - fn x([[builtin(unknown_built_in)]] y: u32) {} + fn x(@builtin(unknown_built_in) y: u32) {} "#, r#"error: unknown builtin: 'unknown_built_in' - ┌─ wgsl:2:28 + ┌─ wgsl:2:27 │ -2 │ fn x([[builtin(unknown_built_in)]] y: u32) {} - │ ^^^^^^^^^^^^^^^^ unknown builtin +2 │ fn x(@builtin(unknown_built_in) y: u32) {} + │ ^^^^^^^^^^^^^^^^ unknown builtin "#, ); @@ -273,13 +273,13 @@ fn unknown_access() { fn unknown_shader_stage() { check( r#" - [[stage(geometry)]] fn main() {} + @stage(geometry) fn main() {} "#, r#"error: unknown shader stage: 'geometry' - ┌─ wgsl:2:21 + ┌─ wgsl:2:20 │ -2 │ [[stage(geometry)]] fn main() {} - │ ^^^^^^^^ unknown shader stage +2 │ @stage(geometry) fn main() {} + │ ^^^^^^^^ unknown shader stage "#, ); @@ -357,13 +357,13 @@ fn unknown_storage_format() { fn unknown_conservative_depth() { check( r#" - [[early_depth_test(abc)]] fn main() {} + @early_depth_test(abc) fn main() {} "#, r#"error: unknown conservative depth: 'abc' - ┌─ wgsl:2:32 + ┌─ wgsl:2:31 │ -2 │ [[early_depth_test(abc)]] fn main() {} - │ ^^^ unknown conservative depth +2 │ @early_depth_test(abc) fn main() {} + │ ^^^ unknown conservative depth "#, ); @@ -373,13 +373,13 @@ fn unknown_conservative_depth() { fn zero_array_stride() { check( r#" - type zero = [[stride(0)]] array; + type zero = @stride(0) array; "#, r#"error: array stride must not be zero - ┌─ wgsl:2:34 + ┌─ wgsl:2:33 │ -2 │ type zero = [[stride(0)]] array; - │ ^ array stride must not be zero +2 │ type zero = @stride(0) array; + │ ^ array stride must not be zero "#, ); @@ -390,14 +390,14 @@ fn struct_member_zero_size() { check( r#" struct Bar { - [[size(0)]] data: array; + @size(0) data: array; }; "#, r#"error: struct member size or alignment must not be 0 - ┌─ wgsl:3:24 + ┌─ wgsl:3:23 │ -3 │ [[size(0)]] data: array; - │ ^ struct member size or alignment must not be 0 +3 │ @size(0) data: array; + │ ^ struct member size or alignment must not be 0 "#, ); @@ -408,14 +408,14 @@ fn struct_member_zero_align() { check( r#" struct Bar { - [[align(0)]] data: array; + @align(0) data: array; }; "#, r#"error: struct member size or alignment must not be 0 - ┌─ wgsl:3:25 + ┌─ wgsl:3:24 │ -3 │ [[align(0)]] data: array; - │ ^ struct member size or alignment must not be 0 +3 │ @align(0) data: array; + │ ^ struct member size or alignment must not be 0 "#, ); @@ -425,13 +425,13 @@ fn struct_member_zero_align() { fn inconsistent_binding() { check( r#" - fn foo([[builtin(vertex_index), location(0)]] x: u32) {} + fn foo(@builtin(vertex_index) @location(0) x: u32) {} "#, r#"error: input/output binding is not consistent ┌─ wgsl:2:16 │ -2 │ fn foo([[builtin(vertex_index), location(0)]] x: u32) {} - │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ input/output binding is not consistent +2 │ fn foo(@builtin(vertex_index) @location(0) x: u32) {} + │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ input/output binding is not consistent "#, ); @@ -834,7 +834,7 @@ fn invalid_arrays() { check_validation_error! { r#" - type Bad = [[stride(2)]] array; + type Bad = @stride(2) array; "#: Err(naga::valid::ValidationError::Type { error: naga::valid::TypeError::InsufficientArrayStride { stride: 2, base_size: 4 }, @@ -971,8 +971,8 @@ fn pointer_type_equivalence() { fn missing_bindings() { check_validation_error! { " - [[stage(vertex)]] - fn vertex(input: vec4) -> [[location(0)]] vec4 { + @stage(vertex) + fn vertex(input: vec4) -> @location(0) vec4 { return input; } ": @@ -988,8 +988,8 @@ fn missing_bindings() { check_validation_error! { " - [[stage(vertex)]] - fn vertex([[location(0)]] input: vec4, more_input: f32) -> [[location(0)]] vec4 { + @stage(vertex) + fn vertex(@location(0) input: vec4, more_input: f32) -> @location(0) vec4 { return input + more_input; } ": @@ -1005,8 +1005,8 @@ fn missing_bindings() { check_validation_error! { " - [[stage(vertex)]] - fn vertex([[location(0)]] input: vec4) -> vec4 { + @stage(vertex) + fn vertex(@location(0) input: vec4) -> vec4 { return input; } ": @@ -1022,12 +1022,12 @@ fn missing_bindings() { check_validation_error! { " struct VertexIn { - [[location(0)]] pos: vec4; + @location(0) pos: vec4; uv: vec2; }; - [[stage(vertex)]] - fn vertex(input: VertexIn) -> [[location(0)]] vec4 { + @stage(vertex) + fn vertex(input: VertexIn) -> @location(0) vec4 { return input.pos; } ": @@ -1176,7 +1176,7 @@ fn invalid_runtime_sized_arrays() { unsized: Unsized; }; - [[group(0), binding(0)]] var outer: Outer; + @group(0) @binding(0) var outer: Outer; fn fetch(i: i32) -> f32 { return outer.unsized.arr[i]; @@ -1284,7 +1284,7 @@ fn wrong_access_mode() { i: i32; }; - [[group(0), binding(0)]] + @group(0) @binding(0) var globals: Globals; fn store(v: i32) { @@ -1296,7 +1296,7 @@ fn wrong_access_mode() { i: i32; }; - [[group(0), binding(0)]] + @group(0) @binding(0) var globals: Globals; fn store(v: i32) { From 8647e06b72a1087b03e1ac3c08bde13c6a6d78c1 Mon Sep 17 00:00:00 2001 From: francesco-cattoglio Date: Fri, 21 Jan 2022 16:34:44 +0100 Subject: [PATCH 1549/2212] glsl-out: Call proper memory barrier functions (#1680) * glsl-out: Call proper memory barrier functions * glsl-out: Change test for control flow * Removed two unnecessary calls --- src/back/glsl/mod.rs | 15 ++++++++++----- tests/out/glsl/control-flow.main.Compute.glsl | 6 ++++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index fd408d10a..a3d1bd42a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1771,13 +1771,18 @@ impl<'a, W: Write> Writer<'a, W> { // keyword which ceases all further processing in a fragment shader, it's called OpKill // in spir-v that's why it's called `Statement::Kill` Statement::Kill => writeln!(self.out, "{}discard;", level)?, - // Issue an execution or a memory barrier. + // Issue a memory barrier. Please note that to ensure visibility, + // OpenGL always requires a call to the `barrier()` function after a `memoryBarrier*()` Statement::Barrier(flags) => { - if flags.is_empty() { - writeln!(self.out, "{}barrier();", level)?; - } else { - writeln!(self.out, "{}groupMemoryBarrier();", level)?; + if flags.contains(crate::Barrier::STORAGE) { + writeln!(self.out, "{}memoryBarrierBuffer();", level)?; } + + if flags.contains(crate::Barrier::WORK_GROUP) { + writeln!(self.out, "{}memoryBarrierShared();", level)?; + } + + writeln!(self.out, "{}barrier();", level)?; } // Stores in glsl are just variable assignments written as `pointer = value;` Statement::Store { pointer, value } => { diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index dd0224e43..a5e103413 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -38,8 +38,10 @@ void loop_switch_continue(int x) { void main() { uvec3 global_id = gl_GlobalInvocationID; int pos = 0; - groupMemoryBarrier(); - groupMemoryBarrier(); + memoryBarrierBuffer(); + barrier(); + memoryBarrierShared(); + barrier(); switch(1) { default: pos = 1; From 81dc67402a743b4dc6b2d24c0d306cd18799238b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 18 Jan 2022 17:29:24 +0000 Subject: [PATCH 1550/2212] glsl-out: push constants use anonymous uniforms Previously this was done with UBOs but this posed some problems when integrating with wgpu (see https://github.com/gfx-rs/wgpu/pull/2400) --- src/back/glsl/mod.rs | 31 +++++-------------- tests/in/functions-webgl.param.ron | 1 - tests/in/interpolate.param.ron | 1 - tests/in/push-constants.param.ron | 1 - tests/in/quad.param.ron | 1 - tests/in/skybox.param.ron | 1 - .../glsl/push-constants.main.Fragment.glsl | 2 +- 7 files changed, 9 insertions(+), 29 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a3d1bd42a..99dd55154 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -86,9 +86,7 @@ impl crate::AtomicFunction { impl crate::StorageClass { fn is_buffer(&self) -> bool { match *self { - crate::StorageClass::PushConstant - | crate::StorageClass::Uniform - | crate::StorageClass::Storage { .. } => true, + crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => true, _ => false, } } @@ -230,8 +228,6 @@ pub struct Options { pub writer_flags: WriterFlags, /// Map of resources association to binding locations. pub binding_map: BindingMap, - /// The binding to give the push constant buffer if it's present - pub push_constant_binding: u32, } impl Default for Options { @@ -240,7 +236,6 @@ impl Default for Options { version: Version::Embedded(310), writer_flags: WriterFlags::ADJUST_COORDINATE_SPACE, binding_map: BindingMap::default(), - push_constant_binding: 0, } } } @@ -263,7 +258,6 @@ pub struct PipelineOptions { pub struct ReflectionInfo { pub texture_mapping: crate::FastHashMap, pub uniforms: crate::FastHashMap, String>, - pub push_constant: Option, } /// Structure that connects a texture to a sampler or not @@ -894,13 +888,7 @@ impl<'a, W: Write> Writer<'a, W> { global: &crate::GlobalVariable, ) -> BackendResult { if self.options.version.supports_explicit_locations() { - if let crate::StorageClass::PushConstant = global.class { - write!( - self.out, - "layout(std140, binding = {}) ", - self.options.push_constant_binding - )? - } else if let Some(ref br) = global.binding { + if let Some(ref br) = global.binding { match self.options.binding_map.get(br) { Some(binding) => { let layout = match global.class { @@ -911,9 +899,7 @@ impl<'a, W: Write> Writer<'a, W> { "std140, " } } - crate::StorageClass::Uniform | crate::StorageClass::PushConstant => { - "std140, " - } + crate::StorageClass::Uniform => "std140, ", _ => "", }; write!(self.out, "layout({}binding = {}) ", layout, binding)? @@ -977,6 +963,11 @@ impl<'a, W: Write> Writer<'a, W> { false }; + if let crate::StorageClass::PushConstant = global.class { + let global_name = self.get_global_name(handle, global); + self.reflection_names_globals.insert(handle, global_name); + } + // Finally write the global name and end the global with a `;` and a newline // Leading space is important write!(self.out, " ")?; @@ -2878,7 +2869,6 @@ impl<'a, W: Write> Writer<'a, W> { let info = self.info.get_entry_point(self.entry_point_idx as usize); let mut texture_mapping = crate::FastHashMap::default(); let mut uniforms = crate::FastHashMap::default(); - let mut push_constant = None; for sampling in info.sampling_set.iter() { let tex_name = self.reflection_names_globals[&sampling.image].clone(); @@ -2909,10 +2899,6 @@ impl<'a, W: Write> Writer<'a, W> { let name = self.reflection_names_globals[&handle].clone(); uniforms.insert(handle, name); } - crate::StorageClass::PushConstant => { - let name = self.reflection_names_globals[&handle].clone(); - push_constant = Some(name) - } _ => (), }, crate::TypeInner::Image { .. } => { @@ -2936,7 +2922,6 @@ impl<'a, W: Write> Writer<'a, W> { Ok(ReflectionInfo { texture_mapping, uniforms, - push_constant, }) } } diff --git a/tests/in/functions-webgl.param.ron b/tests/in/functions-webgl.param.ron index 1d84e945b..bc3dd4a8d 100644 --- a/tests/in/functions-webgl.param.ron +++ b/tests/in/functions-webgl.param.ron @@ -3,6 +3,5 @@ version: Embedded(300), writer_flags: (bits: 0), binding_map: {}, - push_constant_binding: 0, ), ) diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index bfea94342..cb08368c8 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -10,6 +10,5 @@ version: Desktop(400), writer_flags: (bits: 0), binding_map: {}, - push_constant_binding: 0, ), ) diff --git a/tests/in/push-constants.param.ron b/tests/in/push-constants.param.ron index 4e25193b0..0a35edeab 100644 --- a/tests/in/push-constants.param.ron +++ b/tests/in/push-constants.param.ron @@ -4,6 +4,5 @@ version: Embedded(320), writer_flags: (bits: 0), binding_map: {}, - push_constant_binding: 4, ), ) diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index c969a84b2..acde3aed4 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -8,6 +8,5 @@ version: Embedded(300), writer_flags: (bits: 0), binding_map: {}, - push_constant_binding: 0, ), ) diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index ea040e4fb..9c9bd1f30 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -43,7 +43,6 @@ (group: 0, binding: 0): 0, (group: 0, binding: 1): 0, }, - push_constant_binding: 0, ), hlsl: ( shader_model: V5_1, diff --git a/tests/out/glsl/push-constants.main.Fragment.glsl b/tests/out/glsl/push-constants.main.Fragment.glsl index 3a9f896c3..fa1be9f61 100644 --- a/tests/out/glsl/push-constants.main.Fragment.glsl +++ b/tests/out/glsl/push-constants.main.Fragment.glsl @@ -9,7 +9,7 @@ struct PushConstants { struct FragmentIn { vec4 color; }; -layout(std140, binding = 4) uniform PushConstants_block_0Fragment { PushConstants pc; }; +uniform PushConstants pc; layout(location = 0) smooth in vec4 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; From aea427fa9214870a79601349d20cd2e4ade3442a Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 24 Jan 2022 09:54:48 -0500 Subject: [PATCH 1551/2212] msl: add invariance if supported --- src/back/msl/mod.rs | 3 +-- src/back/msl/writer.rs | 20 ++++++++++++++------ tests/in/skybox.param.ron | 2 +- tests/out/msl/skybox.msl | 4 ++-- 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 311f5e374..8e26c7b16 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -381,11 +381,10 @@ impl ResolvedBinding { Ok(()) } - fn try_fmt_decorated(&self, out: &mut W, terminator: &str) -> Result<(), Error> { + fn try_fmt_decorated(&self, out: &mut W) -> Result<(), Error> { write!(out, " [[")?; self.try_fmt(out)?; write!(out, "]]")?; - write!(out, "{}", terminator)?; Ok(()) } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0e2f53a64..1c8103d84 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2862,7 +2862,7 @@ impl Writer { }; let resolved = options.resolve_local_binding(binding, in_mode)?; write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; - resolved.try_fmt_decorated(&mut self.out, "")?; + resolved.try_fmt_decorated(&mut self.out)?; writeln!(self.out, ";")?; } writeln!(self.out, "}};")?; @@ -2931,11 +2931,17 @@ impl Writer { }; let resolved = options.resolve_local_binding(binding, out_mode)?; write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; - resolved.try_fmt_decorated(&mut self.out, "")?; if let Some(array_len) = array_len { write!(self.out, " [{}]", array_len)?; } - writeln!(self.out, ";")?; + write!(self.out, " [[")?; + resolved.try_fmt(&mut self.out)?; + if options.lang_version >= (2, 3) + && *binding == crate::Binding::BuiltIn(crate::BuiltIn::Position) + { + write!(self.out, ", invariant")?; + } + writeln!(self.out, "]];")?; } if pipeline_options.allow_point_size @@ -2986,7 +2992,8 @@ impl Writer { ',' }; write!(self.out, "{} {} {}", separator, ty_name, name)?; - resolved.try_fmt_decorated(&mut self.out, "\n")?; + resolved.try_fmt_decorated(&mut self.out)?; + writeln!(self.out)?; } for (handle, var) in module.global_variables.iter() { let usage = fun_info[handle]; @@ -3026,7 +3033,7 @@ impl Writer { write!(self.out, "{} ", separator)?; tyvar.try_fmt(&mut self.out)?; if let Some(resolved) = resolved { - resolved.try_fmt_decorated(&mut self.out, "")?; + resolved.try_fmt_decorated(&mut self.out)?; } if let Some(value) = var.init { let coco = ConstantContext { @@ -3053,7 +3060,8 @@ impl Writer { "{} constant _mslBufferSizes& _buffer_sizes", separator, )?; - resolved.try_fmt_decorated(&mut self.out, "\n")?; + resolved.try_fmt_decorated(&mut self.out)?; + writeln!(self.out)?; } // end of the entry point argument list diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 9c9bd1f30..7471e4941 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -6,7 +6,7 @@ adjust_coordinate_space: false, ), msl: ( - lang_version: (2, 1), + lang_version: (2, 3), per_stage_map: ( vs: ( resources: { diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index ec7942cb4..d10b005a9 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -1,4 +1,4 @@ -// language: metal2.1 +// language: metal2.3 #include #include @@ -14,7 +14,7 @@ struct Data { struct vs_mainInput { }; struct vs_mainOutput { - metal::float4 position [[position]]; + metal::float4 position [[position, invariant]]; metal::float3 uv [[user(loc0), center_perspective]]; }; vertex vs_mainOutput vs_main( From f36cfb93dcd54ba1afea2b990b14e84982aeed5c Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Mon, 24 Jan 2022 10:09:24 -0500 Subject: [PATCH 1552/2212] glsl: floatBitsToUint spelling --- src/back/glsl/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 99dd55154..8ee675922 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2663,7 +2663,7 @@ impl<'a, W: Write> Writer<'a, W> { let source_kind = inner.scalar_kind().unwrap(); let conv_op = match (source_kind, target_kind) { (Sk::Float, Sk::Sint) => "floatBitsToInt", - (Sk::Float, Sk::Uint) => "floatBitsToUInt", + (Sk::Float, Sk::Uint) => "floatBitsToUint", (Sk::Sint, Sk::Float) => "intBitsToFloat", (Sk::Uint, Sk::Float) => "uintBitsToFloat", // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion From f61ac3e73e1ad7304bcf2bc02ddd493f72473758 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 24 Jan 2022 12:33:49 -0800 Subject: [PATCH 1553/2212] Document `proc::layouter`. Rename `TypeLayoutError` to `LayoutErrorInner`, for consistency. It makes no sense to have 'Type' in the name of one of the error types but not the other. The 'Inner' convention is used by the module types. Cite the layout rules in the WGSL spec, not a GitHub issue. --- src/proc/layouter.rs | 55 ++++++++++++++++++++++++++++++++++---------- src/proc/mod.rs | 2 +- 2 files changed, 44 insertions(+), 13 deletions(-) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 2ce334492..7c1f47438 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -3,7 +3,7 @@ use std::{num::NonZeroU32, ops}; pub type Alignment = NonZeroU32; -/// Alignment information for a type. +/// Size and alignment information for a type. #[derive(Clone, Copy, Debug, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] @@ -13,12 +13,19 @@ pub struct TypeLayout { } /// Helper processor that derives the sizes of all types. -/// It uses the default layout algorithm/table, described in -/// +/// +/// `Layouter` uses the default layout algorithm/table, described in +/// [WGSL §4.3.7, "Memory Layout"] +/// +/// A `Layouter` may be indexed by `Handle` values: `layouter[handle]` is the +/// layout of the type whose handle is `handle`. +/// +/// [WGSL §4.3.7, "Memory Layout"](https://gpuweb.github.io/gpuweb/wgsl/#memory-layouts) #[derive(Debug, Default)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Layouter { + /// Layouts for types in an arena, indexed by `Handle` index. layouts: Vec, } @@ -30,7 +37,7 @@ impl ops::Index> for Layouter { } #[derive(Clone, Copy, Debug, PartialEq, thiserror::Error)] -pub enum TypeLayoutError { +pub enum LayoutErrorInner { #[error("Array element type {0:?} doesn't exist")] InvalidArrayElementType(Handle), #[error("Struct member[{0}] type {1:?} doesn't exist")] @@ -45,20 +52,22 @@ pub enum TypeLayoutError { #[error("Error laying out type {ty:?}: {inner}")] pub struct LayoutError { pub ty: Handle, - pub inner: TypeLayoutError, + pub inner: LayoutErrorInner, } -impl TypeLayoutError { +impl LayoutErrorInner { fn with(self, ty: Handle) -> LayoutError { LayoutError { ty, inner: self } } } impl Layouter { + /// Remove all entries from this `Layouter`, retaining storage. pub fn clear(&mut self) { self.layouts.clear(); } + /// Round `offset` up to the nearest `alignment` boundary. pub fn round_up(alignment: Alignment, offset: u32) -> u32 { match offset & (alignment.get() - 1) { 0 => offset, @@ -66,6 +75,15 @@ impl Layouter { } } + /// Return the offset and span of a struct member. + /// + /// The member must fall at or after `offset`. The member's alignment and + /// size are `align` and `size` if given, defaulting to the values this + /// `Layouter` has previously determined for `ty`. + /// + /// The return value is the range of offsets within the containing struct to + /// reserve for this member, along with the alignment used. The containing + /// struct must have sufficient space and alignment to accommodate these. pub fn member_placement( &self, offset: u32, @@ -83,6 +101,19 @@ impl Layouter { (start..start + span, alignment) } + /// Extend this `Layouter` with layouts for any new entries in `types`. + /// + /// Ensure that every type in `types` has a corresponding [TypeLayout] in + /// [`self.layouts`]. + /// + /// Some front ends need to be able to compute layouts for existing types + /// while module construction is still in progress and new types are still + /// being added. This function assumes that the `TypeLayout` values already + /// present in `self.layouts` cover their corresponding entries in `types`, + /// and extends `self.layouts` as needed to cover the rest. Thus, a front + /// end can call this function at any time, passing its current type and + /// constant arenas, and then assume that layouts are available for all + /// types. #[allow(clippy::or_fun_call)] pub fn update( &mut self, @@ -95,12 +126,12 @@ impl Layouter { let size = ty .inner .try_size(constants) - .map_err(|error| TypeLayoutError::BadHandle(error).with(ty_handle))?; + .map_err(|error| LayoutErrorInner::BadHandle(error).with(ty_handle))?; let layout = match ty.inner { Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => TypeLayout { size, alignment: Alignment::new(width as u32) - .ok_or(TypeLayoutError::ZeroWidth.with(ty_handle))?, + .ok_or(LayoutErrorInner::ZeroWidth.with(ty_handle))?, }, Ti::Vector { size: vec_size, @@ -115,7 +146,7 @@ impl Layouter { 2 }; Alignment::new(count * width as u32) - .ok_or(TypeLayoutError::ZeroWidth.with(ty_handle))? + .ok_or(LayoutErrorInner::ZeroWidth.with(ty_handle))? }, }, Ti::Matrix { @@ -127,7 +158,7 @@ impl Layouter { alignment: { let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; Alignment::new(count * width as u32) - .ok_or(TypeLayoutError::ZeroWidth.with(ty_handle))? + .ok_or(LayoutErrorInner::ZeroWidth.with(ty_handle))? }, }, Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { @@ -143,7 +174,7 @@ impl Layouter { alignment: if base < ty_handle { self[base].alignment } else { - return Err(TypeLayoutError::InvalidArrayElementType(base).with(ty_handle)); + return Err(LayoutErrorInner::InvalidArrayElementType(base).with(ty_handle)); }, }, Ti::Struct { span, ref members } => { @@ -152,7 +183,7 @@ impl Layouter { alignment = if member.ty < ty_handle { alignment.max(self[member.ty].alignment) } else { - return Err(TypeLayoutError::InvalidStructMemberType( + return Err(LayoutErrorInner::InvalidStructMemberType( index as u32, member.ty, ) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c5bb1954b..47a99cff3 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -9,7 +9,7 @@ mod typifier; use std::cmp::PartialEq; pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength, IndexableLengthError}; -pub use layouter::{Alignment, LayoutError, Layouter, TypeLayout, TypeLayoutError}; +pub use layouter::{Alignment, LayoutError, LayoutErrorInner, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; pub use terminator::ensure_block_returns; pub use typifier::{ResolveContext, ResolveError, TypeResolution}; From 4c91abe5b31aa56865c908647501b60e7cdf4f41 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 21 Jan 2022 10:28:50 -0500 Subject: [PATCH 1554/2212] wgsl: remove stride --- CHANGELOG.md | 6 + src/back/wgsl/writer.rs | 17 +- src/front/glsl/mod.rs | 5 +- src/front/glsl/types.rs | 14 +- src/front/wgsl/mod.rs | 45 +-- src/front/wgsl/tests.rs | 2 +- src/proc/layouter.rs | 7 + src/valid/type.rs | 25 +- tests/in/access.wgsl | 14 +- tests/in/boids.wgsl | 2 +- tests/in/collatz.wgsl | 2 +- tests/in/shadow.wgsl | 2 +- tests/out/glsl/access.atomics.Compute.glsl | 5 +- tests/out/glsl/access.foo.Vertex.glsl | 11 +- tests/out/hlsl/access.hlsl | 10 +- tests/out/msl/access.msl | 23 +- tests/out/spv/access.spvasm | 313 ++++++++++--------- tests/out/wgsl/246-collatz-comp.wgsl | 2 +- tests/out/wgsl/access.wgsl | 18 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 4 +- tests/out/wgsl/boids.wgsl | 2 +- tests/out/wgsl/collatz.wgsl | 2 +- tests/out/wgsl/constant-array-size-vert.wgsl | 2 +- tests/out/wgsl/globals.wgsl | 2 +- tests/out/wgsl/pointers.wgsl | 2 +- tests/out/wgsl/shadow.wgsl | 2 +- tests/wgsl-errors.rs | 26 -- 27 files changed, 279 insertions(+), 286 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93ab09e9e..446cb4464 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Change Log +## v0.9 (TBD) + - WGSL: + - attributes are declared with `@attrib` instead of `[[attrib]]` + - `stride` attribute is removed + - block comments are supported + ## v0.8 (2021-12-18) - development release for wgpu-0.12 - lots of fixes in all parts diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 60598fe90..64a512c93 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -17,7 +17,6 @@ enum Attribute { Interpolate(Option, Option), Location(u32), Stage(ShaderStage), - Stride(u32), WorkGroupSize([u32; 3]), } @@ -349,7 +348,6 @@ impl Writer { }; write!(self.out, "@stage({}) ", stage_str)?; } - Attribute::Stride(stride) => write!(self.out, "@stride({}) ", stride)?, Attribute::WorkGroupSize(size) => { write!( self.out, @@ -420,15 +418,6 @@ impl Writer { // Write struct member name and type let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; write!(self.out, "{}: ", member_name)?; - // Write stride attribute for array struct member - if let TypeInner::Array { - base: _, - size: _, - stride, - } = module.types[member.ty].inner - { - self.write_attributes(&[Attribute::Stride(stride)])?; - } self.write_type(module, member.ty)?; write!(self.out, ";")?; writeln!(self.out)?; @@ -523,7 +512,11 @@ impl Writer { TypeInner::Atomic { kind, .. } => { write!(self.out, "atomic<{}>", scalar_kind_str(kind))?; } - TypeInner::Array { base, size, .. } => { + TypeInner::Array { + base, + size, + stride: _, + } => { // More info https://gpuweb.github.io/gpuweb/wgsl/#array-types // array -- Constant array // array -- Dynamic array diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 1d4c6c1a9..0712f4bd5 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -10,7 +10,7 @@ pub use ast::{Precision, Profile}; pub use error::{Error, ErrorKind, ExpectedToken}; pub use token::TokenValue; -use crate::{FastHashMap, FastHashSet, Handle, Module, ShaderStage, Span, Type}; +use crate::{proc::Layouter, FastHashMap, FastHashSet, Handle, Module, ShaderStage, Span, Type}; use ast::{EntryArg, FunctionDeclaration, GlobalLookup}; use parser::ParsingContext; @@ -166,6 +166,8 @@ pub struct Parser { entry_args: Vec, + layouter: Layouter, + errors: Vec, module: Module, @@ -179,6 +181,7 @@ impl Parser { self.lookup_type.clear(); self.global_variables.clear(); self.entry_args.clear(); + self.layouter.clear(); // This is necessary because if the last parsing errored out, the module // wouldn't have been swapped diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index aee13c77f..becc53ad6 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -259,10 +259,13 @@ impl Parser { mut meta: Span, array_specifier: Option<(ArraySize, Span)>, ) -> Handle { - array_specifier - .map(|(size, size_meta)| { + match array_specifier { + Some((size, size_meta)) => { meta.subsume(size_meta); - let stride = self.module.types[base].inner.size(&self.module.constants); + self.layouter + .update(&self.module.types, &self.module.constants) + .unwrap(); + let stride = self.layouter[base].to_stride(); self.module.types.insert( Type { name: None, @@ -270,7 +273,8 @@ impl Parser { }, meta, ) - }) - .unwrap_or(base) + } + None => base, + } } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f7d65afc2..756ce3849 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -158,7 +158,6 @@ pub enum Error<'a> { UnknownType(Span), UnknownStorageFormat(Span), UnknownConservativeDepth(Span), - ZeroStride(Span), ZeroSizeOrAlign(Span), InconsistentBinding(Span), UnknownLocalFunction(Span), @@ -232,7 +231,7 @@ impl<'a> Error<'a> { ExpectedToken::Constant => "constant".to_string(), ExpectedToken::PrimaryExpression => "expression".to_string(), ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(), - ExpectedToken::TypeAttribute => "type attribute ('stride')".to_string(), + ExpectedToken::TypeAttribute => "type attribute".to_string(), ExpectedToken::Statement => "statement".to_string(), ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), @@ -393,11 +392,6 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "unknown type".into())], notes: vec![], }, - Error::ZeroStride(ref bad_span) => ParseError { - message: "array stride must not be zero".to_string(), - labels: vec![(bad_span.clone(), "array stride must not be zero".into())], - notes: vec![], - }, Error::ZeroSizeOrAlign(ref bad_span) => ParseError { message: "struct member size or alignment must not be 0".to_string(), labels: vec![(bad_span.clone(), "struct member size or alignment must not be 0".into())], @@ -1048,7 +1042,9 @@ impl Composition { #[derive(Default)] struct TypeAttributes { - stride: Option, + // Although WGSL nas no type attributes at the moment, it had them in the past +// (`[[stride]]`) and may as well acquire some again in the future. +// Therefore, we are leaving the plumbing in for now. } #[derive(Clone, Debug, PartialEq)] @@ -2888,7 +2884,7 @@ impl Parser { fn parse_type_decl_impl<'a>( &mut self, lexer: &mut Lexer<'a>, - attribute: TypeAttributes, + _attribute: TypeAttributes, word: &'a str, type_arena: &mut UniqueArena, const_arena: &mut Arena, @@ -3024,15 +3020,11 @@ impl Parser { crate::ArraySize::Dynamic }; lexer.expect_generic_paren('>')?; - let stride = match attribute.stride { - Some(stride) => stride.get(), - None => { - self.layouter.update(type_arena, const_arena).unwrap(); - let layout = &self.layouter[base]; - Layouter::round_up(layout.alignment, layout.size) - } - }; + let stride = { + self.layouter.update(type_arena, const_arena).unwrap(); + self.layouter[base].to_stride() + }; crate::TypeInner::Array { base, size, stride } } "sampler" => crate::TypeInner::Sampler { comparison: false }, @@ -3240,22 +3232,11 @@ impl Parser { const_arena: &mut Arena, ) -> Result<(Handle, crate::StorageAccess), Error<'a>> { self.push_scope(Scope::TypeDecl, lexer); - let mut attribute = TypeAttributes::default(); + let attribute = TypeAttributes::default(); - while lexer.skip(Token::Attribute) { - self.push_scope(Scope::Attribute, lexer); - match lexer.next() { - (Token::Word("stride"), _) => { - lexer.expect(Token::Paren('('))?; - let (stride, span) = - lexer.capture_span(|lexer| parse_non_negative_sint_literal(lexer, 4))?; - attribute.stride = - Some(NonZeroU32::new(stride).ok_or(Error::ZeroStride(span))?); - lexer.expect(Token::Paren(')'))?; - } - other => return Err(Error::Unexpected(other, ExpectedToken::TypeAttribute)), - } - self.pop_scope(lexer); + if lexer.skip(Token::Attribute) { + let other = lexer.next(); + return Err(Error::Unexpected(other, ExpectedToken::TypeAttribute)); } let storage_access = crate::StorageAccess::default(); diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index bb415fa7c..4d5e047a6 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -398,7 +398,7 @@ fn parse_array_length() { parse_str( " struct Foo { - data: @stride(4) array; + data: array; }; // this is used as both input and output for convenience @group(0) @binding(0) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 7c1f47438..f03823a81 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -12,6 +12,13 @@ pub struct TypeLayout { pub alignment: Alignment, } +impl TypeLayout { + /// Produce the stride as if this type is a base of an array. + pub fn to_stride(&self) -> u32 { + Layouter::round_up(self.alignment, self.size) + } +} + /// Helper processor that derives the sizes of all types. /// /// `Layouter` uses the default layout algorithm/table, described in diff --git a/src/valid/type.rs b/src/valid/type.rs index 7fc1a6466..db68eac4c 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -97,8 +97,8 @@ pub enum TypeError { UnsupportedSpecializedArrayLength(Handle), #[error("Array type {0:?} must have a length of one or more")] NonPositiveArrayLength(Handle), - #[error("Array stride {stride} is smaller than the base element size {base_size}")] - InsufficientArrayStride { stride: u32, base_size: u32 }, + #[error("Array stride {stride} does not match the expected {expected}")] + InvalidArrayStride { stride: u32, expected: u32 }, #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] InvalidDynamicArray(String, Handle), #[error("Structure member[{index}] at {offset} overlaps the previous member")] @@ -328,19 +328,20 @@ impl super::Validator { return Err(TypeError::InvalidArrayBaseType(base)); } - //Note: `unwrap()` is fine, since `Layouter` goes first and calls it - let base_size = types[base].inner.size(constants); - if stride < base_size { - return Err(TypeError::InsufficientArrayStride { stride, base_size }); + let base_layout = self.layouter[base]; + let expected_stride = base_layout.to_stride(); + if stride != expected_stride { + return Err(TypeError::InvalidArrayStride { + stride, + expected: expected_stride, + }); } - let general_alignment = self.layouter[base].alignment; + let general_alignment = base_layout.alignment.get(); let uniform_layout = match base_info.uniform_layout { Ok(base_alignment) => { // combine the alignment requirements - let align = ((base_alignment.unwrap().get() - 1) - | (general_alignment.get() - 1)) - + 1; + let align = base_alignment.unwrap().get().max(general_alignment); if stride % align != 0 { Err(( handle, @@ -357,9 +358,7 @@ impl super::Validator { }; let storage_layout = match base_info.storage_layout { Ok(base_alignment) => { - let align = ((base_alignment.unwrap().get() - 1) - | (general_alignment.get() - 1)) - + 1; + let align = base_alignment.unwrap().get().max(general_alignment); if stride % align != 0 { Err(( handle, diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index ce26cb8a4..90c707359 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -1,11 +1,15 @@ // This snapshot tests accessing various containers, dereferencing pointers. +struct AlignedWrapper { + @align(8) value: i32; +}; + struct Bar { matrix: mat4x4; matrix_array: array, 2>; atom: atomic; - arr: @stride(8) array, 2>; - data: @stride(8) array; + arr: array, 2>; + data: array; }; @group(0) @binding(0) @@ -27,17 +31,17 @@ fn foo(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let arr = bar.arr; let index = 3u; let b = bar.matrix[index].x; - let a = bar.data[arrayLength(&bar.data) - 2u]; + let a = bar.data[arrayLength(&bar.data) - 2u].value; // test pointer types - let data_pointer: ptr = &bar.data[0]; + let data_pointer: ptr = &bar.data[0].value; let foo_value = read_from_private(&foo); // test storage stores bar.matrix[1].z = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); bar.arr = array, 2>(vec2(0u), vec2(1u)); - bar.data[1] = 1; + bar.data[1].value = 1; // test array indexing var c = array(a, i32(b), 3, 4, 5); diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 1cc54cfc4..6f44752c6 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -16,7 +16,7 @@ struct SimParams { }; struct Particles { - particles : @stride(16) array; + particles : array; }; @group(0) @binding(0) var params : SimParams; diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index f4341c24a..cf972a8ff 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -1,5 +1,5 @@ struct PrimeIndices { - data: @stride(4) array; + data: array; }; // this is used as both input and output for convenience @group(0) @binding(0) diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 367762d51..bbd0a3f68 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -12,7 +12,7 @@ struct Light { }; struct Lights { - data: @stride(96) array; + data: array; }; @group(0) @binding(1) diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index cca755cd6..632fa2666 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -5,12 +5,15 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +struct AlignedWrapper { + int value; +}; layout(std430) buffer Bar_block_0Compute { mat4x4 matrix; mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; - int data[]; + AlignedWrapper data[]; } _group_0_binding_0_cs; diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl index efac04148..3508015cf 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo.Vertex.glsl @@ -3,12 +3,15 @@ precision highp float; precision highp int; +struct AlignedWrapper { + int value; +}; layout(std430) buffer Bar_block_0Vertex { mat4x4 matrix; mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; - int data[]; + AlignedWrapper data[]; } _group_0_binding_0_vs; @@ -26,12 +29,12 @@ void main() { mat4x4 matrix = _group_0_binding_0_vs.matrix; uvec2 arr[2] = _group_0_binding_0_vs.arr; float b = _group_0_binding_0_vs.matrix[3][0]; - int a = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)]; - float _e25 = read_from_private(foo_1); + int a = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; + float _e27 = read_from_private(foo_1); _group_0_binding_0_vs.matrix[1][2] = 1.0; _group_0_binding_0_vs.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); _group_0_binding_0_vs.arr = uvec2[2](uvec2(0u), uvec2(1u)); - _group_0_binding_0_vs.data[1] = 1; + _group_0_binding_0_vs.data[1].value = 1; c = int[5](a, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index aa89e7f90..f79a6798b 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -1,4 +1,8 @@ +struct AlignedWrapper { + int value; +}; + RWByteAddressBuffer bar : register(u0); float read_from_private(inout float foo_2) @@ -24,8 +28,8 @@ float4 foo(uint vi : SV_VertexID) : SV_Position float4x4 matrix_ = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); - int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); - const float _e25 = read_from_private(foo_1); + int a = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); + const float _e27 = read_from_private(foo_1); bar.Store(8+16+0, asuint(1.0)); { float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx)); @@ -39,7 +43,7 @@ float4 foo(uint vi : SV_VertexID) : SV_Position bar.Store2(104+0, asuint(_value2[0])); bar.Store2(104+8, asuint(_value2[1])); } - bar.Store(8+120, asuint(1)); + bar.Store(0+8+120, asuint(1)); { int _result[5]={ a, int(b), 3, 4, 5 }; for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 53897e1ad..39033f3fd 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -6,19 +6,22 @@ struct _mslBufferSizes { metal::uint size0; }; -struct type_2 { +struct AlignedWrapper { + int value; +}; +struct type_3 { metal::float2x2 inner[2]; }; -struct type_5 { +struct type_6 { metal::uint2 inner[2]; }; -typedef int type_7[1]; +typedef AlignedWrapper type_7[1]; struct Bar { metal::float4x4 matrix; - type_2 matrix_array; + type_3 matrix_array; metal::atomic_int atom; char _pad3[4]; - type_5 arr; + type_6 arr; type_7 data; }; struct type_13 { @@ -47,14 +50,14 @@ vertex fooOutput foo( float baz = foo_1; foo_1 = 1.0; metal::float4x4 matrix = bar.matrix; - type_5 arr = bar.arr; + type_6 arr = bar.arr; float b = bar.matrix[3].x; - int a = bar.data[(1 + (_buffer_sizes.size0 - 120 - 4) / 8) - 2u]; - float _e25 = read_from_private(foo_1); + int a = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; + float _e27 = read_from_private(foo_1); bar.matrix[1].z = 1.0; bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); - for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_5 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; - bar.data[1] = 1; + for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_6 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; + bar.data[1].value = 1; for(int _i=0; _i<5; ++_i) c.inner[_i] = type_13 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 6a599ad51..bdd616040 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,48 +1,51 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 119 +; Bound: 121 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %50 "foo" %45 %48 -OpEntryPoint GLCompute %96 "atomics" -OpExecutionMode %96 LocalSize 1 1 1 +OpEntryPoint Vertex %51 "foo" %46 %49 +OpEntryPoint GLCompute %98 "atomics" +OpExecutionMode %98 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %29 0 "matrix" -OpMemberName %29 1 "matrix_array" -OpMemberName %29 2 "atom" -OpMemberName %29 3 "arr" -OpMemberName %29 4 "data" -OpName %29 "Bar" -OpName %33 "bar" -OpName %36 "foo" -OpName %37 "read_from_private" -OpName %41 "foo" -OpName %42 "c" -OpName %45 "vi" -OpName %50 "foo" -OpName %94 "tmp" -OpName %96 "atomics" -OpDecorate %25 ArrayStride 16 -OpDecorate %27 ArrayStride 8 +OpMemberName %21 0 "value" +OpName %21 "AlignedWrapper" +OpMemberName %30 0 "matrix" +OpMemberName %30 1 "matrix_array" +OpMemberName %30 2 "atom" +OpMemberName %30 3 "arr" +OpMemberName %30 4 "data" +OpName %30 "Bar" +OpName %34 "bar" +OpName %37 "foo" +OpName %38 "read_from_private" +OpName %42 "foo" +OpName %43 "c" +OpName %46 "vi" +OpName %51 "foo" +OpName %96 "tmp" +OpName %98 "atomics" +OpMemberDecorate %21 0 Offset 0 +OpDecorate %26 ArrayStride 16 OpDecorate %28 ArrayStride 8 -OpMemberDecorate %29 0 Offset 0 -OpMemberDecorate %29 0 ColMajor -OpMemberDecorate %29 0 MatrixStride 16 -OpMemberDecorate %29 1 Offset 64 -OpMemberDecorate %29 1 ColMajor -OpMemberDecorate %29 1 MatrixStride 8 -OpMemberDecorate %29 2 Offset 96 -OpMemberDecorate %29 3 Offset 104 -OpMemberDecorate %29 4 Offset 120 -OpDecorate %32 ArrayStride 4 -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 0 -OpDecorate %29 Block -OpDecorate %45 BuiltIn VertexIndex -OpDecorate %48 BuiltIn Position +OpDecorate %29 ArrayStride 8 +OpMemberDecorate %30 0 Offset 0 +OpMemberDecorate %30 0 ColMajor +OpMemberDecorate %30 0 MatrixStride 16 +OpMemberDecorate %30 1 Offset 64 +OpMemberDecorate %30 1 ColMajor +OpMemberDecorate %30 1 MatrixStride 8 +OpMemberDecorate %30 2 Offset 96 +OpMemberDecorate %30 3 Offset 104 +OpMemberDecorate %30 4 Offset 120 +OpDecorate %33 ArrayStride 4 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 0 +OpDecorate %30 Block +OpDecorate %46 BuiltIn VertexIndex +OpDecorate %49 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -62,127 +65,129 @@ OpDecorate %48 BuiltIn Position %18 = OpConstant %4 3 %19 = OpConstant %4 4 %20 = OpConstant %4 42 -%22 = OpTypeVector %6 4 -%21 = OpTypeMatrix %22 4 -%24 = OpTypeVector %6 2 -%23 = OpTypeMatrix %24 2 -%25 = OpTypeArray %23 %3 -%26 = OpTypeVector %9 2 -%27 = OpTypeArray %26 %3 -%28 = OpTypeRuntimeArray %4 -%29 = OpTypeStruct %21 %25 %4 %27 %28 -%30 = OpTypePointer Function %6 -%31 = OpTypePointer StorageBuffer %4 -%32 = OpTypeArray %4 %17 -%34 = OpTypePointer StorageBuffer %29 -%33 = OpVariable %34 StorageBuffer -%38 = OpTypeFunction %6 %30 -%43 = OpTypePointer Function %32 -%46 = OpTypePointer Input %9 -%45 = OpVariable %46 Input -%49 = OpTypePointer Output %22 -%48 = OpVariable %49 Output -%51 = OpTypeFunction %2 -%54 = OpTypePointer StorageBuffer %21 -%57 = OpTypePointer StorageBuffer %27 -%60 = OpTypePointer StorageBuffer %22 -%61 = OpTypePointer StorageBuffer %6 -%64 = OpTypePointer StorageBuffer %28 -%67 = OpConstant %9 4 -%86 = OpTypePointer Function %4 -%90 = OpTypeVector %4 4 -%98 = OpTypePointer StorageBuffer %4 -%101 = OpConstant %9 64 -%37 = OpFunction %6 None %38 -%36 = OpFunctionParameter %30 -%35 = OpLabel -OpBranch %39 -%39 = OpLabel -%40 = OpLoad %6 %36 -OpReturnValue %40 +%21 = OpTypeStruct %4 +%23 = OpTypeVector %6 4 +%22 = OpTypeMatrix %23 4 +%25 = OpTypeVector %6 2 +%24 = OpTypeMatrix %25 2 +%26 = OpTypeArray %24 %3 +%27 = OpTypeVector %9 2 +%28 = OpTypeArray %27 %3 +%29 = OpTypeRuntimeArray %21 +%30 = OpTypeStruct %22 %26 %4 %28 %29 +%31 = OpTypePointer Function %6 +%32 = OpTypePointer StorageBuffer %4 +%33 = OpTypeArray %4 %17 +%35 = OpTypePointer StorageBuffer %30 +%34 = OpVariable %35 StorageBuffer +%39 = OpTypeFunction %6 %31 +%44 = OpTypePointer Function %33 +%47 = OpTypePointer Input %9 +%46 = OpVariable %47 Input +%50 = OpTypePointer Output %23 +%49 = OpVariable %50 Output +%52 = OpTypeFunction %2 +%55 = OpTypePointer StorageBuffer %22 +%58 = OpTypePointer StorageBuffer %28 +%61 = OpTypePointer StorageBuffer %23 +%62 = OpTypePointer StorageBuffer %6 +%65 = OpTypePointer StorageBuffer %29 +%68 = OpTypePointer StorageBuffer %21 +%69 = OpConstant %9 4 +%88 = OpTypePointer Function %4 +%92 = OpTypeVector %4 4 +%100 = OpTypePointer StorageBuffer %4 +%103 = OpConstant %9 64 +%38 = OpFunction %6 None %39 +%37 = OpFunctionParameter %31 +%36 = OpLabel +OpBranch %40 +%40 = OpLabel +%41 = OpLoad %6 %37 +OpReturnValue %41 OpFunctionEnd -%50 = OpFunction %2 None %51 -%44 = OpLabel -%41 = OpVariable %30 Function %5 -%42 = OpVariable %43 Function -%47 = OpLoad %9 %45 -OpBranch %52 -%52 = OpLabel -%53 = OpLoad %6 %41 -OpStore %41 %7 -%55 = OpAccessChain %54 %33 %15 -%56 = OpLoad %21 %55 -%58 = OpAccessChain %57 %33 %8 -%59 = OpLoad %27 %58 -%62 = OpAccessChain %61 %33 %15 %8 %15 -%63 = OpLoad %6 %62 -%65 = OpArrayLength %9 %33 4 -%66 = OpISub %9 %65 %10 -%68 = OpAccessChain %31 %33 %67 %66 -%69 = OpLoad %4 %68 -%70 = OpFunctionCall %6 %37 %41 -%71 = OpAccessChain %61 %33 %15 %16 %10 -OpStore %71 %7 -%72 = OpCompositeConstruct %22 %5 %5 %5 %5 -%73 = OpCompositeConstruct %22 %7 %7 %7 %7 -%74 = OpCompositeConstruct %22 %13 %13 %13 %13 -%75 = OpCompositeConstruct %22 %14 %14 %14 %14 -%76 = OpCompositeConstruct %21 %72 %73 %74 %75 -%77 = OpAccessChain %54 %33 %15 -OpStore %77 %76 -%78 = OpCompositeConstruct %26 %15 %15 -%79 = OpCompositeConstruct %26 %16 %16 -%80 = OpCompositeConstruct %27 %78 %79 -%81 = OpAccessChain %57 %33 %8 -OpStore %81 %80 -%82 = OpAccessChain %31 %33 %67 %16 -OpStore %82 %12 -%83 = OpConvertFToS %4 %63 -%84 = OpCompositeConstruct %32 %69 %83 %18 %19 %17 -OpStore %42 %84 -%85 = OpIAdd %9 %47 %16 -%87 = OpAccessChain %86 %42 %85 -OpStore %87 %20 -%88 = OpAccessChain %86 %42 %47 -%89 = OpLoad %4 %88 -%91 = OpCompositeConstruct %90 %89 %89 %89 %89 -%92 = OpConvertSToF %22 %91 -%93 = OpMatrixTimesVector %22 %56 %92 -OpStore %48 %93 +%51 = OpFunction %2 None %52 +%45 = OpLabel +%42 = OpVariable %31 Function %5 +%43 = OpVariable %44 Function +%48 = OpLoad %9 %46 +OpBranch %53 +%53 = OpLabel +%54 = OpLoad %6 %42 +OpStore %42 %7 +%56 = OpAccessChain %55 %34 %15 +%57 = OpLoad %22 %56 +%59 = OpAccessChain %58 %34 %8 +%60 = OpLoad %28 %59 +%63 = OpAccessChain %62 %34 %15 %8 %15 +%64 = OpLoad %6 %63 +%66 = OpArrayLength %9 %34 4 +%67 = OpISub %9 %66 %10 +%70 = OpAccessChain %32 %34 %69 %67 %15 +%71 = OpLoad %4 %70 +%72 = OpFunctionCall %6 %38 %42 +%73 = OpAccessChain %62 %34 %15 %16 %10 +OpStore %73 %7 +%74 = OpCompositeConstruct %23 %5 %5 %5 %5 +%75 = OpCompositeConstruct %23 %7 %7 %7 %7 +%76 = OpCompositeConstruct %23 %13 %13 %13 %13 +%77 = OpCompositeConstruct %23 %14 %14 %14 %14 +%78 = OpCompositeConstruct %22 %74 %75 %76 %77 +%79 = OpAccessChain %55 %34 %15 +OpStore %79 %78 +%80 = OpCompositeConstruct %27 %15 %15 +%81 = OpCompositeConstruct %27 %16 %16 +%82 = OpCompositeConstruct %28 %80 %81 +%83 = OpAccessChain %58 %34 %8 +OpStore %83 %82 +%84 = OpAccessChain %32 %34 %69 %16 %15 +OpStore %84 %12 +%85 = OpConvertFToS %4 %64 +%86 = OpCompositeConstruct %33 %71 %85 %18 %19 %17 +OpStore %43 %86 +%87 = OpIAdd %9 %48 %16 +%89 = OpAccessChain %88 %43 %87 +OpStore %89 %20 +%90 = OpAccessChain %88 %43 %48 +%91 = OpLoad %4 %90 +%93 = OpCompositeConstruct %92 %91 %91 %91 %91 +%94 = OpConvertSToF %23 %93 +%95 = OpMatrixTimesVector %23 %57 %94 +OpStore %49 %95 OpReturn OpFunctionEnd -%96 = OpFunction %2 None %51 -%95 = OpLabel -%94 = OpVariable %86 Function -OpBranch %97 +%98 = OpFunction %2 None %52 %97 = OpLabel -%99 = OpAccessChain %98 %33 %10 -%100 = OpAtomicLoad %4 %99 %12 %101 -%103 = OpAccessChain %98 %33 %10 -%102 = OpAtomicIAdd %4 %103 %12 %101 %17 -OpStore %94 %102 -%105 = OpAccessChain %98 %33 %10 -%104 = OpAtomicISub %4 %105 %12 %101 %17 -OpStore %94 %104 -%107 = OpAccessChain %98 %33 %10 -%106 = OpAtomicAnd %4 %107 %12 %101 %17 -OpStore %94 %106 -%109 = OpAccessChain %98 %33 %10 -%108 = OpAtomicOr %4 %109 %12 %101 %17 -OpStore %94 %108 -%111 = OpAccessChain %98 %33 %10 -%110 = OpAtomicXor %4 %111 %12 %101 %17 -OpStore %94 %110 -%113 = OpAccessChain %98 %33 %10 -%112 = OpAtomicSMin %4 %113 %12 %101 %17 -OpStore %94 %112 -%115 = OpAccessChain %98 %33 %10 -%114 = OpAtomicSMax %4 %115 %12 %101 %17 -OpStore %94 %114 -%117 = OpAccessChain %98 %33 %10 -%116 = OpAtomicExchange %4 %117 %12 %101 %17 -OpStore %94 %116 -%118 = OpAccessChain %98 %33 %10 -OpAtomicStore %118 %12 %101 %100 +%96 = OpVariable %88 Function +OpBranch %99 +%99 = OpLabel +%101 = OpAccessChain %100 %34 %10 +%102 = OpAtomicLoad %4 %101 %12 %103 +%105 = OpAccessChain %100 %34 %10 +%104 = OpAtomicIAdd %4 %105 %12 %103 %17 +OpStore %96 %104 +%107 = OpAccessChain %100 %34 %10 +%106 = OpAtomicISub %4 %107 %12 %103 %17 +OpStore %96 %106 +%109 = OpAccessChain %100 %34 %10 +%108 = OpAtomicAnd %4 %109 %12 %103 %17 +OpStore %96 %108 +%111 = OpAccessChain %100 %34 %10 +%110 = OpAtomicOr %4 %111 %12 %103 %17 +OpStore %96 %110 +%113 = OpAccessChain %100 %34 %10 +%112 = OpAtomicXor %4 %113 %12 %103 %17 +OpStore %96 %112 +%115 = OpAccessChain %100 %34 %10 +%114 = OpAtomicSMin %4 %115 %12 %103 %17 +OpStore %96 %114 +%117 = OpAccessChain %100 %34 %10 +%116 = OpAtomicSMax %4 %117 %12 %103 %17 +OpStore %96 %116 +%119 = OpAccessChain %100 %34 %10 +%118 = OpAtomicExchange %4 %119 %12 %103 %17 +OpStore %96 %118 +%120 = OpAccessChain %100 %34 %10 +OpAtomicStore %120 %12 %103 %102 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 45d08357c..e983ee8de 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -1,5 +1,5 @@ struct PrimeIndices { - indices: @stride(4) array; + indices: array; }; @group(0) @binding(0) diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 2e4ee4142..28d29440f 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -1,9 +1,13 @@ +struct AlignedWrapper { + value: i32; +}; + struct Bar { matrix: mat4x4; - matrix_array: @stride(16) array,2>; + matrix_array: array,2>; atom: atomic; - arr: @stride(8) array,2>; - data: @stride(8) array; + arr: array,2>; + data: array; }; @group(0) @binding(0) @@ -24,13 +28,13 @@ fn foo(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let matrix = bar.matrix; let arr = bar.arr; let b = bar.matrix[3][0]; - let a = bar.data[(arrayLength((&bar.data)) - 2u)]; - let data_pointer = (&bar.data[0]); - let _e25 = read_from_private((&foo_1)); + let a = bar.data[(arrayLength((&bar.data)) - 2u)].value; + let data_pointer = (&bar.data[0].value); + let _e27 = read_from_private((&foo_1)); bar.matrix[1][2] = 1.0; bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); - bar.data[1] = 1; + bar.data[1].value = 1; c = array(a, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value = c[vi]; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index fa947b893..b5913a626 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -20,8 +20,8 @@ struct CameraPosition { struct Lights { AmbientColor: vec4; NumLights: vec4; - PointLights: @stride(48) array; - DirectionalLights: @stride(32) array; + PointLights: array; + DirectionalLights: array; }; struct StandardMaterial_base_color { diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 7b1e9af1e..b0f3180b2 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -14,7 +14,7 @@ struct SimParams { }; struct Particles { - particles: @stride(16) array; + particles: array; }; let NUM_PARTICLES: u32 = 1500u; diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index 054ecf364..b4fb82c46 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -1,5 +1,5 @@ struct PrimeIndices { - data: @stride(4) array; + data: array; }; @group(0) @binding(0) diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 9a767c858..26e32eda7 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -1,5 +1,5 @@ struct Data { - vecs: @stride(16) array,42u>; + vecs: array,42u>; }; @group(1) @binding(0) diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 84705602a..6184f987c 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -4,7 +4,7 @@ struct Foo { }; struct Dummy { - arr: @stride(8) array>; + arr: array>; }; let Foo_2: bool = true; diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index 0ac148e1c..e06ecb0b1 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -1,5 +1,5 @@ struct DynamicArray { - arr: @stride(4) array; + arr: array; }; @group(0) @binding(0) diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index f6e9e50e6..d1e2ace3e 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -9,7 +9,7 @@ struct Light { }; struct Lights { - data: @stride(96) array; + data: array; }; let c_ambient: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index d6224ce8a..a04b50b80 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -369,22 +369,6 @@ fn unknown_conservative_depth() { ); } -#[test] -fn zero_array_stride() { - check( - r#" - type zero = @stride(0) array; - "#, - r#"error: array stride must not be zero - ┌─ wgsl:2:33 - │ -2 │ type zero = @stride(0) array; - │ ^ array stride must not be zero - -"#, - ); -} - #[test] fn struct_member_zero_size() { check( @@ -832,16 +816,6 @@ fn invalid_arrays() { }) } - check_validation_error! { - r#" - type Bad = @stride(2) array; - "#: - Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::InsufficientArrayStride { stride: 2, base_size: 4 }, - .. - }) - } - check_validation_error! { "type Bad = array;", r#" From a782592af3c47c292db7f6548d9f34c36cea891f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 25 Jan 2022 11:21:14 -0500 Subject: [PATCH 1555/2212] msl: emit point size even when there is no struct --- src/back/msl/writer.rs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 1c8103d84..c05c47dc0 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1701,6 +1701,7 @@ impl Writer { ) -> BackendResult { match result_struct { Some(struct_name) => { + let mut has_point_size = false; let result_ty = context.function.result.as_ref().unwrap().ty; match context.module.types[result_ty].inner { crate::TypeInner::Struct { ref members, .. } => { @@ -1711,7 +1712,6 @@ impl Writer { write!(self.out, "{}return {} {{", level, struct_name)?; let mut is_first = true; - let mut has_point_size = false; for (index, member) in members.iter().enumerate() { match member.binding { @@ -1758,23 +1758,23 @@ impl Writer { write!(self.out, "{} {}.{}", comma, tmp, name)?; } } - - if let FunctionOrigin::EntryPoint(ep_index) = context.origin { - let stage = context.module.entry_points[ep_index as usize].stage; - if context.pipeline_options.allow_point_size - && stage == crate::ShaderStage::Vertex - && !has_point_size - { - // point size was injected and comes last - write!(self.out, ", 1.0")?; - } - } } _ => { write!(self.out, "{}return {} {{ ", level, struct_name)?; self.put_expression(expr_handle, context, true)?; } } + + if let FunctionOrigin::EntryPoint(ep_index) = context.origin { + let stage = context.module.entry_points[ep_index as usize].stage; + if context.pipeline_options.allow_point_size + && stage == crate::ShaderStage::Vertex + && !has_point_size + { + // point size was injected and comes last + write!(self.out, ", 1.0")?; + } + } write!(self.out, " }}")?; } None => { From f5d97cae84bb7b8c80c4691a7cd4f898ae8af6e7 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Tue, 25 Jan 2022 13:17:54 -0500 Subject: [PATCH 1556/2212] Adjust MSL version invariant needs --- src/back/msl/writer.rs | 2 +- tests/in/skybox.param.ron | 2 +- tests/out/msl/skybox.msl | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c05c47dc0..ff95e27a7 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2936,7 +2936,7 @@ impl Writer { } write!(self.out, " [[")?; resolved.try_fmt(&mut self.out)?; - if options.lang_version >= (2, 3) + if options.lang_version >= (2, 1) && *binding == crate::Binding::BuiltIn(crate::BuiltIn::Position) { write!(self.out, ", invariant")?; diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 7471e4941..9c9bd1f30 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -6,7 +6,7 @@ adjust_coordinate_space: false, ), msl: ( - lang_version: (2, 3), + lang_version: (2, 1), per_stage_map: ( vs: ( resources: { diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index d10b005a9..26b6812a4 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -1,4 +1,4 @@ -// language: metal2.3 +// language: metal2.1 #include #include From 6842db44321a2ee9cd13c09b55cc7fbc326194ae Mon Sep 17 00:00:00 2001 From: rhysd Date: Thu, 27 Jan 2022 21:50:00 +0900 Subject: [PATCH 1557/2212] cli: Support reading input from stdin --- cli/src/main.rs | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index b1a863ca2..9c43dc02b 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -1,7 +1,7 @@ #![allow(clippy::manual_strip)] #[allow(unused_imports)] use std::fs; -use std::{error::Error, fmt, path::Path, str::FromStr}; +use std::{error::Error, fmt, io::Read, path::Path, str::FromStr}; /// Translate shaders to different formats #[derive(argh::FromArgs, Debug, Clone)] @@ -60,13 +60,20 @@ struct Args { #[argh(switch)] keep_coordinate_space: bool, - /// the input file - #[argh(positional)] - input: String, + /// specify file path to process STDIN as + #[argh(option)] + stdin_file_path: Option, - /// the output file. If not specified, only validation will be performed + /// the input and output files. + /// + /// First positional argument is the input file. If not specified, the + /// input will be read from stdin. In the case, --stdin-file-path must also + /// be specified. + /// + /// The rest arguments are the output files. If not specified, only + /// validation will be performed. #[argh(positional)] - output: Vec, + files: Vec, } /// Newtype so we can implement [`FromStr`] for `BoundsCheckPolicy`. @@ -202,8 +209,21 @@ fn run() -> Result<(), Box> { // Parse commandline arguments let args: Args = argh::from_env(); - let input_path = Path::new(&args.input); - let output_paths = args.output; + let (input_path, input) = if let Some(path) = args.files.first() { + let path = Path::new(path); + (path, fs::read(path)?) + } else if let Some(path) = &args.stdin_file_path { + let mut input = vec![]; + std::io::stdin().lock().read_to_end(&mut input)?; + (Path::new(path), input) + } else { + return Err(CliError("Input file path is not specified").into()); + }; + let output_paths = if !args.files.is_empty() { + &args.files[1..] + } else { + &[] + }; // Update parameters from commandline arguments if let Some(bits) = args.validate { @@ -245,11 +265,10 @@ fn run() -> Result<(), Box> { .spv_block_ctx_dump_prefix .map(std::path::PathBuf::from), }; - let input = fs::read(input_path)?; naga::front::spv::parse_u8_slice(&input, &options).map(|m| (m, None))? } "wgsl" => { - let input = fs::read_to_string(input_path)?; + let input = String::from_utf8(input)?; let result = naga::front::wgsl::parse_str(&input); match result { Ok(v) => (v, Some(input)), @@ -260,7 +279,7 @@ fn run() -> Result<(), Box> { } } ext @ "vert" | ext @ "frag" | ext @ "comp" => { - let input = fs::read_to_string(input_path)?; + let input = String::from_utf8(input)?; let mut parser = naga::front::glsl::Parser::default(); ( From 0afa8fcb4fc690a060b3b8649d6e3b7d06d8ba1e Mon Sep 17 00:00:00 2001 From: rhysd Date: Fri, 28 Jan 2022 21:50:14 +0900 Subject: [PATCH 1558/2212] cli: Add --version flag --- cli/src/main.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cli/src/main.rs b/cli/src/main.rs index 9c43dc02b..062ea6d7f 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -64,6 +64,10 @@ struct Args { #[argh(option)] stdin_file_path: Option, + /// show version + #[argh(switch)] + version: bool, + /// the input and output files. /// /// First positional argument is the input file. If not specified, the @@ -209,6 +213,10 @@ fn run() -> Result<(), Box> { // Parse commandline arguments let args: Args = argh::from_env(); + if args.version { + println!("{}", env!("CARGO_PKG_VERSION")); + return Ok(()); + } let (input_path, input) = if let Some(path) = args.files.first() { let path = Path::new(path); (path, fs::read(path)?) From f98053aa3c58f2e35279b906ab334a6ca6fb6ff6 Mon Sep 17 00:00:00 2001 From: rhysd Date: Sat, 29 Jan 2022 21:49:51 +0900 Subject: [PATCH 1559/2212] cli: Include file path in WGSL parse error --- cli/src/main.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 062ea6d7f..76f950e48 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -281,7 +281,8 @@ fn run() -> Result<(), Box> { match result { Ok(v) => (v, Some(input)), Err(ref e) => { - e.emit_to_stderr(&input); + let path = input_path.to_string_lossy(); + e.emit_to_stderr_with_path(&input, &path); return Err(CliError("Could not parse WGSL").into()); } } From d6f8958b346676396db97053771b8d95684c47ee Mon Sep 17 00:00:00 2001 From: rhysd Date: Sat, 29 Jan 2022 21:31:06 +0900 Subject: [PATCH 1560/2212] wgsl: Do not make error output colorful when the terminal is dumb --- src/front/wgsl/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 756ce3849..6992886a6 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1181,7 +1181,7 @@ impl ParseError { pub fn emit_to_stderr_with_path(&self, source: &str, path: &str) { let files = SimpleFile::new(path, source); let config = codespan_reporting::term::Config::default(); - let writer = StandardStream::stderr(ColorChoice::Always); + let writer = StandardStream::stderr(ColorChoice::Auto); term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) .expect("cannot write error"); } From 2ddc8d1929a1c4586db75431eae7e8596bd165a9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 25 Jan 2022 18:29:02 -0500 Subject: [PATCH 1561/2212] Rename StorageClass to AddressSpace --- src/back/dot/mod.rs | 2 +- src/back/glsl/features.rs | 14 ++-- src/back/glsl/mod.rs | 70 ++++++++++---------- src/back/hlsl/help.rs | 4 +- src/back/hlsl/writer.rs | 48 +++++++------- src/back/msl/writer.rs | 66 +++++++++---------- src/back/spv/block.rs | 47 +++++++------- src/back/spv/helpers.rs | 28 ++++---- src/back/spv/image.rs | 18 ++--- src/back/spv/mod.rs | 16 ++--- src/back/spv/writer.rs | 40 ++++++------ src/back/wgsl/writer.rs | 70 ++++++++++---------- src/front/glsl/ast.rs | 6 +- src/front/glsl/context.rs | 12 ++-- src/front/glsl/functions.rs | 14 ++-- src/front/glsl/parser/declarations.rs | 6 +- src/front/glsl/parser/types.rs | 10 +-- src/front/glsl/variables.rs | 40 ++++++------ src/front/spv/convert.rs | 14 ++-- src/front/spv/mod.rs | 34 +++++----- src/front/wgsl/conv.rs | 16 ++--- src/front/wgsl/mod.rs | 34 +++++----- src/lib.rs | 34 +++++----- src/proc/index.rs | 14 ++-- src/proc/mod.rs | 28 ++++---- src/proc/typifier.rs | 46 ++++++------- src/valid/analyzer.rs | 20 +++--- src/valid/expression.rs | 4 +- src/valid/function.rs | 28 ++++---- src/valid/interface.rs | 30 ++++----- src/valid/mod.rs | 2 +- src/valid/type.rs | 30 ++++----- tests/out/analysis/collatz.info.ron | 16 ++--- tests/out/analysis/shadow.info.ron | 94 +++++++++++++-------------- tests/out/ir/collatz.ron | 2 +- tests/out/ir/shadow.ron | 42 ++++++------ tests/wgsl-errors.rs | 24 +++---- 37 files changed, 511 insertions(+), 512 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index bee46704c..b60c29990 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -484,7 +484,7 @@ pub fn write(module: &crate::Module, mod_info: Option<&ModuleInfo>) -> Result Writer<'a, W> { if ep_info[handle].is_empty() { continue; } - match global.class { - StorageClass::WorkGroup => self.features.request(Features::COMPUTE_SHADER), - StorageClass::Storage { .. } => self.features.request(Features::BUFFER_STORAGE), - StorageClass::PushConstant => { + match global.space { + AddressSpace::WorkGroup => self.features.request(Features::COMPUTE_SHADER), + AddressSpace::Storage { .. } => self.features.request(Features::BUFFER_STORAGE), + AddressSpace::PushConstant => { if push_constant_used { return Err(Error::MultiplePushConstants); } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 8ee675922..550fafc3b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -83,21 +83,21 @@ impl crate::AtomicFunction { } } -impl crate::StorageClass { +impl crate::AddressSpace { fn is_buffer(&self) -> bool { match *self { - crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => true, + crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } => true, _ => false, } } - /// Whether a variable with this storage class can be initialized + /// Whether a variable with this address space can be initialized fn initializable(&self) -> bool { match *self { - crate::StorageClass::WorkGroup - | crate::StorageClass::Uniform - | crate::StorageClass::PushConstant - | crate::StorageClass::Storage { .. } => false, + crate::AddressSpace::WorkGroup + | crate::AddressSpace::Uniform + | crate::AddressSpace::PushConstant + | crate::AddressSpace::Storage { .. } => false, _ => true, } } @@ -349,7 +349,7 @@ pub enum Error { /// Contains the missing [`Features`](Features) #[error("The selected version doesn't support {0:?}")] MissingFeatures(Features), - /// [`StorageClass::PushConstant`](crate::StorageClass::PushConstant) was used more than + /// [`AddressSpace::PushConstant`](crate::AddressSpace::PushConstant) was used more than /// once in the entry point which isn't supported #[error("Multiple push constants aren't supported")] MultiplePushConstants, @@ -563,7 +563,7 @@ impl<'a, W: Write> Writer<'a, W> { GlobalTypeKind::Other => { let used_by_global = self.module.global_variables.iter().any(|(vh, var)| { - !ep_info[vh].is_empty() && var.class.is_buffer() && var.ty == handle + !ep_info[vh].is_empty() && var.space.is_buffer() && var.ty == handle }); // If not used by a global, it's safe to just spew it here !used_by_global @@ -752,7 +752,7 @@ impl<'a, W: Write> Writer<'a, W> { size: None, kind, width, - class: _, + space: _, } => write!(self.out, "{}", glsl_scalar(kind, width)?.full)?, // Vectors are just `gvecN` where `g` is the scalar prefix and `N` is the vector size TypeInner::Vector { size, kind, width } @@ -760,7 +760,7 @@ impl<'a, W: Write> Writer<'a, W> { size: Some(size), kind, width, - class: _, + space: _, } => write!( self.out, "{}vec{}", @@ -891,22 +891,22 @@ impl<'a, W: Write> Writer<'a, W> { if let Some(ref br) = global.binding { match self.options.binding_map.get(br) { Some(binding) => { - let layout = match global.class { - crate::StorageClass::Storage { .. } => { + let layout = match global.space { + crate::AddressSpace::Storage { .. } => { if self.options.version.supports_std430_layout() { "std430, " } else { "std140, " } } - crate::StorageClass::Uniform => "std140, ", + crate::AddressSpace::Uniform => "std140, ", _ => "", }; write!(self.out, "layout({}binding = {}) ", layout, binding)? } None => { log::debug!("unassigned binding for {:?}", global.name); - if let crate::StorageClass::Storage { .. } = global.class { + if let crate::AddressSpace::Storage { .. } = global.space { if self.options.version.supports_std430_layout() { write!(self.out, "layout(std430) ")? } @@ -916,13 +916,13 @@ impl<'a, W: Write> Writer<'a, W> { } } - if let crate::StorageClass::Storage { access } = global.class { + if let crate::AddressSpace::Storage { access } = global.space { self.write_storage_access(access)?; } // Write the storage class // Trailing space is important - if let Some(storage_class) = glsl_storage_class(global.class) { + if let Some(storage_class) = glsl_storage_class(global.space) { write!(self.out, "{} ", storage_class)?; } @@ -931,7 +931,7 @@ impl<'a, W: Write> Writer<'a, W> { // generated number so it's unique and `members` are the same as in a struct // Write the block name, it's just the struct name appended with `_block_ID` - let needs_wrapper = if global.class.is_buffer() { + let needs_wrapper = if global.space.is_buffer() { let ty_name = &self.names[&NameKey::Type(global.ty)]; let block_name = format!( "{}_block_{}{:?}", @@ -963,7 +963,7 @@ impl<'a, W: Write> Writer<'a, W> { false }; - if let crate::StorageClass::PushConstant = global.class { + if let crate::AddressSpace::PushConstant = global.space { let global_name = self.get_global_name(handle, global); self.reflection_names_globals.insert(handle, global_name); } @@ -977,7 +977,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_array_size(size)?; } - if global.class.initializable() && is_value_init_supported(self.module, global.ty) { + if global.space.initializable() && is_value_init_supported(self.module, global.ty) { write!(self.out, " = ")?; if let Some(init) = global.init { self.write_constant(init)?; @@ -1472,7 +1472,7 @@ impl<'a, W: Write> Writer<'a, W> { Statement::Emit(ref range) => { for handle in range.clone() { let info = &ctx.info[handle]; - let ptr_class = info.ty.inner_with(&self.module.types).pointer_class(); + let ptr_class = info.ty.inner_with(&self.module.types).pointer_space(); let expr_name = if ptr_class.is_some() { // GLSL can't save a pointer-valued expression in a variable, // but we shouldn't ever need to: they should never be named expressions, @@ -1905,7 +1905,7 @@ impl<'a, W: Write> Writer<'a, W> { let base_ty_res = &ctx.info[base].ty; let mut resolved = base_ty_res.inner_with(&self.module.types); let base_ty_handle = match *resolved { - TypeInner::Pointer { base, class: _ } => { + TypeInner::Pointer { base, space: _ } => { resolved = &self.module.types[base].inner; Some(base) } @@ -2894,8 +2894,8 @@ impl<'a, W: Write> Writer<'a, W> { continue; } match self.module.types[var.ty].inner { - crate::TypeInner::Struct { .. } => match var.class { - crate::StorageClass::Uniform | crate::StorageClass::Storage { .. } => { + crate::TypeInner::Struct { .. } => match var.space { + crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } => { let name = self.reflection_names_globals[&handle].clone(); uniforms.insert(handle, name); } @@ -3018,18 +3018,18 @@ fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { } } -/// Helper function that returns the string corresponding to the storage class -fn glsl_storage_class(class: crate::StorageClass) -> Option<&'static str> { - use crate::StorageClass as Sc; +/// Helper function that returns the string corresponding to the address space +fn glsl_storage_class(space: crate::AddressSpace) -> Option<&'static str> { + use crate::AddressSpace as As; - match class { - Sc::Function => None, - Sc::Private => None, - Sc::Storage { .. } => Some("buffer"), - Sc::Uniform => Some("uniform"), - Sc::Handle => Some("uniform"), - Sc::WorkGroup => Some("shared"), - Sc::PushConstant => Some("uniform"), + match space { + As::Function => None, + As::Private => None, + As::Storage { .. } => Some("buffer"), + As::Uniform => Some("uniform"), + As::Handle => Some("uniform"), + As::WorkGroup => Some("shared"), + As::PushConstant => Some("uniform"), } } diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 4d9265d72..01dbb33e7 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -439,8 +439,8 @@ impl<'a, W: Write> super::Writer<'a, W> { } ref other => unreachable!("Array length of base {:?}", other), }; - let storage_access = match global_var.class { - crate::StorageClass::Storage { access } => access, + let storage_access = match global_var.space { + crate::AddressSpace::Storage { access } => access, _ => crate::StorageAccess::default(), }; let wal = WrappedArrayLength { diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 412e36d15..01a58cf3f 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -540,25 +540,25 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register - let register_ty = match global.class { - crate::StorageClass::Function => unreachable!("Function storage class"), - crate::StorageClass::Private => { + let register_ty = match global.space { + crate::AddressSpace::Function => unreachable!("Function address space"), + crate::AddressSpace::Private => { write!(self.out, "static ")?; self.write_type(module, global.ty)?; "" } - crate::StorageClass::WorkGroup => { + crate::AddressSpace::WorkGroup => { write!(self.out, "groupshared ")?; self.write_type(module, global.ty)?; "" } - crate::StorageClass::Uniform => { + crate::AddressSpace::Uniform => { // constant buffer declarations are expected to be inlined, e.g. // `cbuffer foo: register(b0) { field1: type1; }` write!(self.out, "cbuffer")?; "b" } - crate::StorageClass::Storage { access } => { + crate::AddressSpace::Storage { access } => { let (prefix, register) = if access.contains(crate::StorageAccess::STORE) { ("RW", "u") } else { @@ -567,7 +567,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "{}ByteAddressBuffer", prefix)?; register } - crate::StorageClass::Handle => { + crate::AddressSpace::Handle => { let register = match *inner { TypeInner::Sampler { .. } => "s", // all storage textures are UAV, unconditionally @@ -580,7 +580,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_type(module, global.ty)?; register } - crate::StorageClass::PushConstant => unimplemented!("Push constants"), + crate::AddressSpace::PushConstant => unimplemented!("Push constants"), }; let name = &self.names[&NameKey::GlobalVariable(handle)]; @@ -597,7 +597,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ", space{}", bt.space)?; } write!(self.out, ")")?; - } else if global.class == crate::StorageClass::Private { + } else if global.space == crate::AddressSpace::Private { write!(self.out, " = ")?; if let Some(init) = global.init { self.write_constant(module, init)?; @@ -606,7 +606,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - if global.class == crate::StorageClass::Uniform { + if global.space == crate::AddressSpace::Uniform { write!(self.out, " {{ ")?; self.write_type(module, global.ty)?; let name = &self.names[&NameKey::GlobalVariable(handle)]; @@ -1028,7 +1028,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Statement::Emit(ref range) => { for handle in range.clone() { let info = &func_ctx.info[handle]; - let ptr_class = info.ty.inner_with(&module.types).pointer_class(); + let ptr_class = info.ty.inner_with(&module.types).pointer_space(); let expr_name = if ptr_class.is_some() { // HLSL can't save a pointer-valued expression in a variable, // but we shouldn't ever need to: they should never be named expressions, @@ -1103,7 +1103,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Statement::Return { value: Some(expr) } => { let base_ty_res = &func_ctx.info[expr].ty; let mut resolved = base_ty_res.inner_with(&module.types); - if let TypeInner::Pointer { base, class: _ } = *resolved { + if let TypeInner::Pointer { base, space: _ } = *resolved { resolved = &module.types[base].inner; } @@ -1167,7 +1167,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { _ => None, }; - if let Some(crate::StorageClass::Storage { .. }) = ty_inner.pointer_class() { + if let Some(crate::AddressSpace::Storage { .. }) = ty_inner.pointer_space() { let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; self.write_storage_store( module, @@ -1512,10 +1512,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; } Expression::Access { base, index } => { - if let Some(crate::StorageClass::Storage { .. }) = func_ctx.info[expr] + if let Some(crate::AddressSpace::Storage { .. }) = func_ctx.info[expr] .ty .inner_with(&module.types) - .pointer_class() + .pointer_space() { // do nothing, the chain is written on `Load`/`Store` } else { @@ -1526,10 +1526,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Expression::AccessIndex { base, index } => { - if let Some(crate::StorageClass::Storage { .. }) = func_ctx.info[expr] + if let Some(crate::AddressSpace::Storage { .. }) = func_ctx.info[expr] .ty .inner_with(&module.types) - .pointer_class() + .pointer_space() { // do nothing, the chain is written on `Load`/`Store` } else { @@ -1538,7 +1538,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let base_ty_res = &func_ctx.info[base].ty; let mut resolved = base_ty_res.inner_with(&module.types); let base_ty_handle = match *resolved { - TypeInner::Pointer { base, class: _ } => { + TypeInner::Pointer { base, space: _ } => { resolved = &module.types[base].inner; Some(base) } @@ -1733,8 +1733,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ".x")?; } } - Expression::GlobalVariable(handle) => match module.global_variables[handle].class { - crate::StorageClass::Storage { .. } => {} + Expression::GlobalVariable(handle) => match module.global_variables[handle].space { + crate::AddressSpace::Storage { .. } => {} _ => { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{}", name)?; @@ -1747,9 +1747,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match func_ctx.info[pointer] .ty .inner_with(&module.types) - .pointer_class() + .pointer_space() { - Some(crate::StorageClass::Storage { .. }) => { + Some(crate::AddressSpace::Storage { .. }) => { let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; let result_ty = func_ctx.info[expr].ty.clone(); self.write_storage_load(module, var_handle, result_ty, func_ctx)?; @@ -1946,8 +1946,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { _ => unreachable!(), }; - let storage_access = match var.class { - crate::StorageClass::Storage { access } => access, + let storage_access = match var.space { + crate::AddressSpace::Storage { access } => access, _ => crate::StorageAccess::default(), }; let wrapped_array_length = WrappedArrayLength { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ff95e27a7..90db79f2f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -71,29 +71,29 @@ impl<'a> Display for TypeContext<'a> { back::vector_size_str(rows), ) } - crate::TypeInner::Pointer { base, class } => { + crate::TypeInner::Pointer { base, space } => { let sub = Self { handle: base, first_time: false, ..*self }; - let class_name = match class.to_msl_name() { + let space_name = match space.to_msl_name() { Some(name) => name, None => return Ok(()), }; - write!(out, "{} {}&", class_name, sub) + write!(out, "{} {}&", space_name, sub) } crate::TypeInner::ValuePointer { size: None, kind, width: _, - class, + space, } => { - let class_name = match class.to_msl_name() { + let space_name = match space.to_msl_name() { Some(name) => name, None => return Ok(()), }; - write!(out, "{} ", class_name)?; + write!(out, "{} ", space_name)?; if kind == crate::ScalarKind::Uint { write!(out, "{}::", NAMESPACE)?; } @@ -103,16 +103,16 @@ impl<'a> Display for TypeContext<'a> { size: Some(size), kind, width: _, - class, + space, } => { - let class_name = match class.to_msl_name() { + let space_name = match space.to_msl_name() { Some(name) => name, None => return Ok(()), }; write!( out, "{} {}::{}{}&", - class_name, + space_name, NAMESPACE, kind.to_msl_name(), back::vector_size_str(size), @@ -214,8 +214,8 @@ impl<'a> TypedGlobalVariable<'a> { let var = &self.module.global_variables[self.handle]; let name = &self.names[&NameKey::GlobalVariable(self.handle)]; - let storage_access = match var.class { - crate::StorageClass::Storage { access } => access, + let storage_access = match var.space { + crate::AddressSpace::Storage { access } => access, _ => match self.module.types[var.ty].inner { crate::TypeInner::Image { class: crate::ImageClass::Storage { access, .. }, @@ -232,10 +232,10 @@ impl<'a> TypedGlobalVariable<'a> { first_time: false, }; - let (space, access, reference) = match var.class.to_msl_name() { + let (space, access, reference) = match var.space.to_msl_name() { Some(space) if self.reference => { - let access = match var.class { - crate::StorageClass::Private | crate::StorageClass::WorkGroup + let access = match var.space { + crate::AddressSpace::Private | crate::AddressSpace::WorkGroup if !self.usage.contains(valid::GlobalUse::WRITE) => { "const" @@ -382,20 +382,20 @@ fn needs_array_length(ty: Handle, arena: &crate::UniqueArena bool { match *self { - crate::StorageClass::Uniform - | crate::StorageClass::Storage { .. } - | crate::StorageClass::Private - | crate::StorageClass::WorkGroup - | crate::StorageClass::PushConstant - | crate::StorageClass::Handle => true, - crate::StorageClass::Function => false, + crate::AddressSpace::Uniform + | crate::AddressSpace::Storage { .. } + | crate::AddressSpace::Private + | crate::AddressSpace::WorkGroup + | crate::AddressSpace::PushConstant + | crate::AddressSpace::Handle => true, + crate::AddressSpace::Function => false, } } @@ -1492,7 +1492,7 @@ impl Writer { let mut base_ty = context.resolve_type(base); // Look through any pointers to see what we're really indexing. - if let crate::TypeInner::Pointer { base, class: _ } = *base_ty { + if let crate::TypeInner::Pointer { base, space: _ } = *base_ty { base_ty = &context.module.types[base].inner; } @@ -1510,7 +1510,7 @@ impl Writer { let mut base_ty_handle = base_resolution.handle(); // Look through any pointers to see what we're really indexing. - if let crate::TypeInner::Pointer { base, class: _ } = *base_ty { + if let crate::TypeInner::Pointer { base, space: _ } = *base_ty { base_ty = &context.module.types[base].inner; base_ty_handle = Some(base); } @@ -1865,7 +1865,7 @@ impl Writer { let ptr_class = info .ty .inner_with(&context.expression.module.types) - .pointer_class(); + .pointer_space(); let expr_name = if ptr_class.is_some() { None // don't bake pointer expressions (just yet) } else if let Some(name) = @@ -2084,7 +2084,7 @@ impl Writer { if fun_info[handle].is_empty() { continue; } - if var.class.needs_pass_through() { + if var.space.needs_pass_through() { let name = &self.names[&NameKey::GlobalVariable(handle)]; if separate { write!(self.out, ", ")?; @@ -2626,7 +2626,7 @@ impl Writer { let mut supports_array_length = false; for (handle, var) in module.global_variables.iter() { if !fun_info[handle].is_empty() { - if var.class.needs_pass_through() { + if var.space.needs_pass_through() { pass_through_globals.push(handle); } supports_array_length |= needs_array_length(var.ty, &module.types); @@ -2780,7 +2780,7 @@ impl Writer { break; } } - if var.class == crate::StorageClass::PushConstant { + if var.space == crate::AddressSpace::PushConstant { if let Err(e) = options.resolve_push_constants(ep.stage) { ep_error = Some(e); break; @@ -2997,15 +2997,15 @@ impl Writer { } for (handle, var) in module.global_variables.iter() { let usage = fun_info[handle]; - if usage.is_empty() || var.class == crate::StorageClass::Private { + if usage.is_empty() || var.space == crate::AddressSpace::Private { continue; } // the resolves have already been checked for `!fake_missing_bindings` case - let resolved = match var.class { - crate::StorageClass::PushConstant => { + let resolved = match var.space { + crate::AddressSpace::PushConstant => { options.resolve_push_constants(ep.stage).ok() } - crate::StorageClass::WorkGroup => None, + crate::AddressSpace::WorkGroup => None, _ => options .resolve_resource_binding(ep.stage, var.binding.as_ref().unwrap()) .ok(), @@ -3074,7 +3074,7 @@ impl Writer { if usage.is_empty() { continue; } - if var.class == crate::StorageClass::Private { + if var.space == crate::AddressSpace::Private { let tyvar = TypedGlobalVariable { module, names: &self.names, diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 02f441885..a31525f4c 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -49,7 +49,7 @@ impl Writer { vector_size: None, kind: crate::ScalarKind::Float, width: 4, - pointer_class: Some(spirv::StorageClass::Output), + pointer_space: Some(spirv::StorageClass::Output), })); let index_y_id = self.get_index_constant(1); let access_id = self.id_gen.next(); @@ -64,7 +64,7 @@ impl Writer { vector_size: None, kind: crate::ScalarKind::Float, width: 4, - pointer_class: None, + pointer_space: None, })); let load_id = self.id_gen.next(); body.push(Instruction::load(float_type_id, load_id, access_id, None)); @@ -91,7 +91,7 @@ impl Writer { vector_size: None, kind: crate::ScalarKind::Float, width: 4, - pointer_class: None, + pointer_space: None, })); let value0_id = self.get_constant_scalar(crate::ScalarValue::Float(0.0), 4); let value1_id = self.get_constant_scalar(crate::ScalarValue::Float(1.0), 4); @@ -174,7 +174,7 @@ impl<'w> BlockContext<'w> { crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => true, crate::Expression::FunctionArgument(index) => { let arg = &self.ir_function.arguments[index as usize]; - self.ir_module.types[arg.ty].inner.pointer_class().is_some() + self.ir_module.types[arg.ty].inner.pointer_space().is_some() } // The chain rule: if this `Access...`'s `base` operand was @@ -601,7 +601,7 @@ impl<'w> BlockContext<'w> { vector_size: Some(size), kind, width, - pointer_class: None, + pointer_space: None, })); self.temp_list.clear(); self.temp_list.resize(size as usize, arg2_id); @@ -699,18 +699,18 @@ impl<'w> BlockContext<'w> { match self.write_expression_pointer(pointer, block)? { ExpressionPointer::Ready { pointer_id } => { let id = self.gen_id(); - let atomic_class = + let atomic_space = match *self.fun_info[pointer].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Pointer { base, class } => { + crate::TypeInner::Pointer { base, space } => { match self.ir_module.types[base].inner { - crate::TypeInner::Atomic { .. } => Some(class), + crate::TypeInner::Atomic { .. } => Some(space), _ => None, } } _ => None, }; - let instruction = if let Some(class) = atomic_class { - let (semantics, scope) = class.to_spirv_semantics_and_scope(); + let instruction = if let Some(space) = atomic_space { + let (semantics, scope) = space.to_spirv_semantics_and_scope(); let scope_constant_id = self.get_scope_constant(scope as u32); let semantics_id = self.get_index_constant(semantics.bits()); Instruction::atomic_load( @@ -797,7 +797,7 @@ impl<'w> BlockContext<'w> { vector_size: Some(size), kind: src_kind, width: src_width, - pointer_class: None, + pointer_space: None, })); let components = [zero_scalar_id; 4]; @@ -834,7 +834,7 @@ impl<'w> BlockContext<'w> { vector_size: Some(size), kind, width: dst_width, - pointer_class: None, + pointer_space: None, })); let components0 = [scalar0_id; 4]; let components1 = [scalar1_id; 4]; @@ -948,7 +948,7 @@ impl<'w> BlockContext<'w> { vector_size: Some(size), kind: crate::ScalarKind::Bool, width, - pointer_class: None, + pointer_space: None, })); let id = self.gen_id(); @@ -1368,20 +1368,20 @@ impl<'w> BlockContext<'w> { let value_id = self.cached[value]; match self.write_expression_pointer(pointer, &mut block)? { ExpressionPointer::Ready { pointer_id } => { - let atomic_class = match *self.fun_info[pointer] + let atomic_space = match *self.fun_info[pointer] .ty .inner_with(&self.ir_module.types) { - crate::TypeInner::Pointer { base, class } => { + crate::TypeInner::Pointer { base, space } => { match self.ir_module.types[base].inner { - crate::TypeInner::Atomic { .. } => Some(class), + crate::TypeInner::Atomic { .. } => Some(space), _ => None, } } _ => None, }; - let instruction = if let Some(class) = atomic_class { - let (semantics, scope) = class.to_spirv_semantics_and_scope(); + let instruction = if let Some(space) = atomic_space { + let (semantics, scope) = space.to_spirv_semantics_and_scope(); let scope_constant_id = self.get_scope_constant(scope as u32); let semantics_id = self.get_index_constant(semantics.bits()); Instruction::atomic_store( @@ -1465,11 +1465,12 @@ impl<'w> BlockContext<'w> { } }; - let class = match *self.fun_info[pointer].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Pointer { base: _, class } => class, - _ => unimplemented!(), - }; - let (semantics, scope) = class.to_spirv_semantics_and_scope(); + let space = self.fun_info[pointer] + .ty + .inner_with(&self.ir_module.types) + .pointer_space() + .unwrap(); + let (semantics, scope) = space.to_spirv_semantics_and_scope(); let scope_constant_id = self.get_scope_constant(scope as u32); let semantics_id = self.get_index_constant(semantics.bits()); let value_id = self.cached[value]; diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index b5c773046..cac21add0 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -20,15 +20,15 @@ pub(super) fn string_to_words(input: &str) -> Vec { words } -pub(super) fn map_storage_class(class: crate::StorageClass) -> spirv::StorageClass { - match class { - crate::StorageClass::Handle => spirv::StorageClass::UniformConstant, - crate::StorageClass::Function => spirv::StorageClass::Function, - crate::StorageClass::Private => spirv::StorageClass::Private, - crate::StorageClass::Storage { .. } => spirv::StorageClass::StorageBuffer, - crate::StorageClass::Uniform => spirv::StorageClass::Uniform, - crate::StorageClass::WorkGroup => spirv::StorageClass::Workgroup, - crate::StorageClass::PushConstant => spirv::StorageClass::PushConstant, +pub(super) fn map_storage_class(space: crate::AddressSpace) -> spirv::StorageClass { + match space { + crate::AddressSpace::Handle => spirv::StorageClass::UniformConstant, + crate::AddressSpace::Function => spirv::StorageClass::Function, + crate::AddressSpace::Private => spirv::StorageClass::Private, + crate::AddressSpace::Storage { .. } => spirv::StorageClass::StorageBuffer, + crate::AddressSpace::Uniform => spirv::StorageClass::Uniform, + crate::AddressSpace::WorkGroup => spirv::StorageClass::Workgroup, + crate::AddressSpace::PushConstant => spirv::StorageClass::PushConstant, } } @@ -49,7 +49,7 @@ pub(super) fn contains_builtin( } } -impl crate::StorageClass { +impl crate::AddressSpace { pub(super) fn to_spirv_semantics_and_scope(self) -> (spirv::MemorySemantics, spirv::Scope) { match self { Self::Storage { .. } => (spirv::MemorySemantics::UNIFORM_MEMORY, spirv::Scope::Device), @@ -65,10 +65,10 @@ impl crate::StorageClass { /// Return true if the global requires a type decorated with "Block". // See `back::spv::GlobalVariable::access_id` for details. pub fn global_needs_wrapper(ir_module: &crate::Module, var: &crate::GlobalVariable) -> bool { - match var.class { - crate::StorageClass::Uniform - | crate::StorageClass::Storage { .. } - | crate::StorageClass::PushConstant => {} + match var.space { + crate::AddressSpace::Uniform + | crate::AddressSpace::Storage { .. } + | crate::AddressSpace::PushConstant => {} _ => return false, }; match ir_module.types[var.ty].inner { diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 443ef8c57..31e37a77c 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -126,7 +126,7 @@ impl Load { vector_size: Some(crate::VectorSize::Quad), kind: crate::ScalarKind::Float, width: 4, - pointer_class: None, + pointer_space: None, })) } _ => result_type_id, @@ -318,7 +318,7 @@ impl<'w> BlockContext<'w> { vector_size: None, kind: component_kind, width: 4, - pointer_class: None, + pointer_space: None, })); let reconciled_id = self.gen_id(); @@ -336,7 +336,7 @@ impl<'w> BlockContext<'w> { vector_size: size, kind: component_kind, width: 4, - pointer_class: None, + pointer_space: None, })); // Schmear the coordinates and index together. @@ -505,7 +505,7 @@ impl<'w> BlockContext<'w> { vector_size: None, kind: crate::ScalarKind::Sint, width: 4, - pointer_class: None, + pointer_space: None, })); // If `level` is `Some`, clamp it to fall within bounds. This must @@ -593,7 +593,7 @@ impl<'w> BlockContext<'w> { vector_size: None, kind: crate::ScalarKind::Sint, width: 4, - pointer_class: None, + pointer_space: None, })); let null_id = access.out_of_bounds_value(self); @@ -661,7 +661,7 @@ impl<'w> BlockContext<'w> { vector_size: coordinates.size, kind: crate::ScalarKind::Bool, width: 1, - pointer_class: None, + pointer_space: None, })); let coords_conds_id = self.gen_id(); selection.block().body.push(Instruction::binary( @@ -825,7 +825,7 @@ impl<'w> BlockContext<'w> { vector_size: Some(crate::VectorSize::Quad), kind: crate::ScalarKind::Float, width: 4, - pointer_class: None, + pointer_space: None, })) } else { result_type_id @@ -1029,7 +1029,7 @@ impl<'w> BlockContext<'w> { vector_size, kind: crate::ScalarKind::Sint, width: 4, - pointer_class: None, + pointer_space: None, })) }; @@ -1097,7 +1097,7 @@ impl<'w> BlockContext<'w> { vector_size: Some(vec_size), kind: crate::ScalarKind::Sint, width: 4, - pointer_class: None, + pointer_space: None, })); let id_extended = self.gen_id(); let mut inst = Instruction::image_query( diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 469fa13d6..ba4875d81 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -267,7 +267,7 @@ enum LocalType { vector_size: Option, kind: crate::ScalarKind, width: crate::Bytes, - pointer_class: Option, + pointer_space: Option, }, /// A matrix of floating-point values. Matrix { @@ -333,14 +333,14 @@ fn make_local(inner: &crate::TypeInner) -> Option { vector_size: None, kind, width, - pointer_class: None, + pointer_space: None, } } crate::TypeInner::Vector { size, kind, width } => LocalType::Value { vector_size: Some(size), kind, width, - pointer_class: None, + pointer_space: None, }, crate::TypeInner::Matrix { columns, @@ -351,20 +351,20 @@ fn make_local(inner: &crate::TypeInner) -> Option { rows, width, }, - crate::TypeInner::Pointer { base, class } => LocalType::Pointer { + crate::TypeInner::Pointer { base, space } => LocalType::Pointer { base, - class: helpers::map_storage_class(class), + class: helpers::map_storage_class(space), }, crate::TypeInner::ValuePointer { size, kind, width, - class, + space, } => LocalType::Value { vector_size: size, kind, width, - pointer_class: Some(helpers::map_storage_class(class)), + pointer_space: Some(helpers::map_storage_class(space)), }, crate::TypeInner::Image { dim, @@ -432,7 +432,7 @@ impl recyclable::Recyclable for CachedExpressions { struct GlobalVariable { /// ID of the variable. Not really used. var_id: Word, - /// For `StorageClass::Handle` variables, this ID is recorded in the function + /// For `AddressSpace::Handle` variables, this ID is recorded in the function /// prelude block (and reset before every function) as `OpLoad` of the variable. /// It is then used for all the global ops, such as `OpImageSample`. handle_id: Word, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 797e67e4e..83253cc73 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -223,7 +223,7 @@ impl Writer { vector_size: None, kind: crate::ScalarKind::Uint, width: 4, - pointer_class: None, + pointer_space: None, }; self.get_type_id(local_type.into()) } @@ -233,7 +233,7 @@ impl Writer { vector_size: None, kind: crate::ScalarKind::Float, width: 4, - pointer_class: None, + pointer_space: None, }; self.get_type_id(local_type.into()) } @@ -243,7 +243,7 @@ impl Writer { vector_size: None, kind: crate::ScalarKind::Float, width: 4, - pointer_class: Some(class), + pointer_space: Some(class), }); if let Some(&id) = self.lookup_type.get(&lookup_type) { id @@ -262,7 +262,7 @@ impl Writer { vector_size: None, kind: crate::ScalarKind::Bool, width: 1, - pointer_class: None, + pointer_space: None, }; self.get_type_id(local_type.into()) } @@ -497,7 +497,7 @@ impl Writer { let mut gv = self.global_variables[handle.index()].clone(); // Handle globals are pre-emitted and should be loaded automatically. - if var.class == crate::StorageClass::Handle { + if var.space == crate::AddressSpace::Handle { let var_type_id = self.get_type_id(LookupType::Handle(var.ty)); let id = self.id_gen.next(); prelude @@ -506,7 +506,7 @@ impl Writer { gv.access_id = gv.var_id; gv.handle_id = id; } else if global_needs_wrapper(ir_module, var) { - let class = map_storage_class(var.class); + let class = map_storage_class(var.space); let pointer_type_id = self.get_pointer_id(&ir_module.types, var.ty, class)?; let index_id = self.get_index_constant(0); @@ -727,19 +727,19 @@ impl Writer { vector_size: None, kind, width, - pointer_class: None, + pointer_space: None, } => self.make_scalar(id, kind, width), LocalType::Value { vector_size: Some(size), kind, width, - pointer_class: None, + pointer_space: None, } => { let scalar_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size: None, kind, width, - pointer_class: None, + pointer_space: None, })); Instruction::type_vector(id, scalar_id, size) } @@ -752,7 +752,7 @@ impl Writer { vector_size: Some(rows), kind: crate::ScalarKind::Float, width, - pointer_class: None, + pointer_space: None, })); Instruction::type_matrix(id, vector_id, columns) } @@ -764,13 +764,13 @@ impl Writer { vector_size, kind, width, - pointer_class: Some(class), + pointer_space: Some(class), } => { let type_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size, kind, width, - pointer_class: None, + pointer_space: None, })); Instruction::type_pointer(id, class, type_id) } @@ -779,7 +779,7 @@ impl Writer { vector_size: None, kind: image.sampled_type, width: 4, - pointer_class: None, + pointer_space: None, }; let type_id = self.get_type_id(LookupType::Local(local_type)); Instruction::type_image(id, type_id, image.dim, image.flags, image.image_format) @@ -1018,7 +1018,7 @@ impl Writer { vector_size: None, kind: value.scalar_kind(), width, - pointer_class: None, + pointer_space: None, })); let (solo, pair); let instruction = match *value { @@ -1239,7 +1239,7 @@ impl Writer { use spirv::Decoration; let id = self.id_gen.next(); - let class = map_storage_class(global_variable.class); + let class = map_storage_class(global_variable.space); //self.check(class.required_capabilities())?; @@ -1249,8 +1249,8 @@ impl Writer { } } - let storage_access = match global_variable.class { - crate::StorageClass::Storage { access } => Some(access), + let storage_access = match global_variable.space { + crate::AddressSpace::Storage { access } => Some(access), _ => match ir_module.types[global_variable.ty].inner { crate::TypeInner::Image { class: crate::ImageClass::Storage { access, .. }, @@ -1301,7 +1301,7 @@ impl Writer { // This is a global variable in a Storage class. The only way it could // have `global_needs_wrapper() == false` is if it has a runtime-sized array. // In this case, we need to decorate it with Block. - if let crate::StorageClass::Storage { .. } = global_variable.class { + if let crate::AddressSpace::Storage { .. } = global_variable.space { self.decorate(inner_type_id, Decoration::Block, &[]); } self.get_pointer_id(&ir_module.types, global_variable.ty, class)? @@ -1359,8 +1359,8 @@ impl Writer { ir_module .global_variables .iter() - .any(|(_, var)| match var.class { - crate::StorageClass::Storage { .. } => true, + .any(|(_, var)| match var.space { + crate::AddressSpace::Storage { .. } => true, _ => false, }); let has_view_index = ir_module diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 64a512c93..4e4cd7046 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -546,16 +546,16 @@ impl Writer { back::vector_size_str(rows), )?; } - TypeInner::Pointer { base, class } => { - let (storage, maybe_access) = storage_class_str(class); - // Everything but `StorageClass::Handle` gives us a `storage` name, but + TypeInner::Pointer { base, space } => { + let (address, maybe_access) = address_space_str(space); + // Everything but `AddressSpace::Handle` gives us a `address` name, but // Naga IR never produces pointers to handles, so it doesn't matter much // how we write such a type. Just write it as the base type alone. - if let Some(class) = storage { - write!(self.out, "ptr<{}, ", class)?; + if let Some(space) = address { + write!(self.out, "ptr<{}, ", space)?; } self.write_type(module, base)?; - if storage.is_some() { + if address.is_some() { if let Some(access) = maybe_access { write!(self.out, ", {}", access)?; } @@ -566,18 +566,18 @@ impl Writer { size: None, kind, width: _, - class, + space, } => { - let (storage, maybe_access) = storage_class_str(class); - if let Some(class) = storage { - write!(self.out, "ptr<{}, {}", class, scalar_kind_str(kind))?; + let (address, maybe_access) = address_space_str(space); + if let Some(space) = address { + write!(self.out, "ptr<{}, {}", space, scalar_kind_str(kind))?; if let Some(access) = maybe_access { write!(self.out, ", {}", access)?; } write!(self.out, ">")?; } else { return Err(Error::Unimplemented(format!( - "ValuePointer to StorageClass::Handle {:?}", + "ValuePointer to AddressSpace::Handle {:?}", inner ))); } @@ -586,14 +586,14 @@ impl Writer { size: Some(size), kind, width: _, - class, + space, } => { - let (storage, maybe_access) = storage_class_str(class); - if let Some(class) = storage { + let (address, maybe_access) = address_space_str(space); + if let Some(space) = address { write!( self.out, "ptr<{}, vec{}<{}>", - class, + space, back::vector_size_str(size), scalar_kind_str(kind) )?; @@ -603,7 +603,7 @@ impl Writer { write!(self.out, ">")?; } else { return Err(Error::Unimplemented(format!( - "ValuePointer to StorageClass::Handle {:?}", + "ValuePointer to AddressSpace::Handle {:?}", inner ))); } @@ -935,7 +935,7 @@ impl Writer { /// /// - The plain form of `GlobalVariable(g)` is simply `g`, which is usually a /// reference to the global variable's storage. However, globals in the - /// `Handle` storage class are immutable, and `GlobalVariable` expressions for + /// `Handle` address space are immutable, and `GlobalVariable` expressions for /// those produce the value directly, not a pointer to it. Such /// `GlobalVariable` expressions are `Ordinary`. /// @@ -966,8 +966,8 @@ impl Writer { Ex::LocalVariable(_) => Indirection::Reference, Ex::GlobalVariable(handle) => { let global = &module.global_variables[handle]; - match global.class { - crate::StorageClass::Handle => Indirection::Ordinary, + match global.space { + crate::AddressSpace::Handle => Indirection::Ordinary, _ => Indirection::Reference, } } @@ -1165,7 +1165,7 @@ impl Writer { self.write_expr_with_indirection(module, base, func_ctx, indirection)?; let base_ty_handle = match *resolved { - TypeInner::Pointer { base, class: _ } => { + TypeInner::Pointer { base, space: _ } => { resolved = &module.types[base].inner; Some(base) } @@ -1681,11 +1681,11 @@ impl Writer { writeln!(self.out)?; } - // First write global name and storage class if supported + // First write global name and address space if supported write!(self.out, "var")?; - let (storage, maybe_access) = storage_class_str(global.class); - if let Some(class) = storage { - write!(self.out, "<{}", class)?; + let (address, maybe_access) = address_space_str(global.space); + if let Some(space) = address { + write!(self.out, "<{}", space)?; if let Some(access) = maybe_access { write!(self.out, ", {}", access)?; } @@ -1946,26 +1946,24 @@ fn sampling_str(sampling: crate::Sampling) -> &'static str { } } -fn storage_class_str( - storage_class: crate::StorageClass, -) -> (Option<&'static str>, Option<&'static str>) { - use crate::StorageClass as Sc; +fn address_space_str(space: crate::AddressSpace) -> (Option<&'static str>, Option<&'static str>) { + use crate::AddressSpace as As; ( - Some(match storage_class { - Sc::Private => "private", - Sc::Uniform => "uniform", - Sc::Storage { access } => { + Some(match space { + As::Private => "private", + As::Uniform => "uniform", + As::Storage { access } => { if access.contains(crate::StorageAccess::STORE) { return (Some("storage"), Some("read_write")); } else { "storage" } } - Sc::PushConstant => "push_constant", - Sc::WorkGroup => "workgroup", - Sc::Handle => return (None, None), - Sc::Function => "function", + As::PushConstant => "push_constant", + As::WorkGroup => "workgroup", + As::Handle => return (None, None), + As::Function => "function", }), None, ) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 36cd777dc..d269698b9 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -2,8 +2,8 @@ use std::fmt; use super::{builtins::MacroCall, context::ExprPos, Span}; use crate::{ - BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, Interpolation, - Sampling, StorageAccess, StorageClass, Type, UnaryOperator, + AddressSpace, BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, + Interpolation, Sampling, StorageAccess, Type, UnaryOperator, }; #[derive(Debug, Clone, Copy)] @@ -163,7 +163,7 @@ pub struct FunctionCall { #[derive(Debug, Clone, Copy, PartialEq)] pub enum StorageQualifier { - StorageClass(StorageClass), + AddressSpace(AddressSpace), Input, Output, Const, diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index eefef012b..6df233aa9 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -9,9 +9,9 @@ use super::{ }; use crate::{ front::{Emitter, Typifier}, - Arena, BinaryOperator, Block, Constant, Expression, FastHashMap, FunctionArgument, Handle, - LocalVariable, RelationalFunction, ScalarKind, ScalarValue, Span, Statement, StorageClass, - Type, TypeInner, VectorSize, + AddressSpace, Arena, BinaryOperator, Block, Constant, Expression, FastHashMap, + FunctionArgument, Handle, LocalVariable, RelationalFunction, ScalarKind, ScalarValue, Span, + Statement, Type, TypeInner, VectorSize, }; use std::{convert::TryFrom, ops::Index}; @@ -107,7 +107,7 @@ impl Context { let span = parser.module.global_variables.get_span(v); let res = ( self.expressions.append(Expression::GlobalVariable(v), span), - parser.module.global_variables[v].class != StorageClass::Handle, + parser.module.global_variables[v].space != AddressSpace::Handle, None, ); self.emit_start(); @@ -262,7 +262,7 @@ impl Context { name: None, inner: TypeInner::Pointer { base: arg.ty, - class: StorageClass::Function, + space: AddressSpace::Function, }, }, span, @@ -540,7 +540,7 @@ impl Context { if ExprPos::Rhs == pos { let resolved = parser.resolve_type(self, pointer, meta)?; - if resolved.pointer_class().is_some() { + if resolved.pointer_space().is_some() { return Ok(( Some(self.add_expression(Expression::Load { pointer }, meta, body)), meta, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 57142f412..d87892c08 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -7,9 +7,9 @@ use super::{ Parser, Result, }; use crate::{ - front::glsl::types::type_power, proc::ensure_block_returns, Arena, Block, Constant, - ConstantInner, EntryPoint, Expression, FastHashMap, Function, FunctionArgument, FunctionResult, - Handle, LocalVariable, ScalarKind, ScalarValue, Span, Statement, StorageClass, StructMember, + front::glsl::types::type_power, proc::ensure_block_returns, AddressSpace, Arena, Block, + Constant, ConstantInner, EntryPoint, Expression, FastHashMap, Function, FunctionArgument, + FunctionResult, Handle, LocalVariable, ScalarKind, ScalarValue, Span, Statement, StructMember, Type, TypeInner, }; use std::iter; @@ -811,10 +811,10 @@ impl Parser { ), handle, ), - // If the argument is a pointer whose storage class isn't `Function` an + // If the argument is a pointer whose address space isn't `Function` an // indirection trough a local variable is needed to align the storage // classes of the call argument and the overload parameter - TypeInner::Pointer { base, class } if class != StorageClass::Function => ( + TypeInner::Pointer { base, space } if space != AddressSpace::Function => ( base, ctx.add_expression( Expression::Load { pointer: handle }, @@ -826,8 +826,8 @@ impl Parser { size, kind, width, - class, - } if class != StorageClass::Function => { + space, + } if space != AddressSpace::Function => { let inner = match size { Some(size) => TypeInner::Vector { size, kind, width }, None => TypeInner::Scalar { kind, width }, diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 6a1cc2ddb..e53d3b10d 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -12,7 +12,7 @@ use crate::{ variables::{GlobalOrConstant, VarDeclaration}, Error, ErrorKind, Parser, Span, }, - Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StorageClass, StructMember, + AddressSpace, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StructMember, Type, TypeInner, }; @@ -480,7 +480,7 @@ impl<'source> ParsingContext<'source> { for &(ref qualifier, _) in qualifiers { match *qualifier { - TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(c)) => { + TypeQualifier::StorageQualifier(StorageQualifier::AddressSpace(c)) => { storage = Some(c) } TypeQualifier::Layout(l) => layout = Some(l), @@ -490,7 +490,7 @@ impl<'source> ParsingContext<'source> { let layout = match (layout, storage) { (Some(layout), _) => layout, - (None, Some(StorageClass::Storage { .. })) => StructLayout::Std430, + (None, Some(AddressSpace::Storage { .. })) => StructLayout::Std430, _ => StructLayout::Std140, }; diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index ad537e959..13cec5860 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -6,7 +6,7 @@ use crate::{ token::{Token, TokenValue}, Error, ErrorKind, Parser, Result, }, - ArraySize, Handle, Span, StorageClass, Type, TypeInner, + AddressSpace, ArraySize, Handle, Span, Type, TypeInner, }; impl<'source> ParsingContext<'source> { @@ -150,13 +150,13 @@ impl<'source> ParsingContext<'source> { TokenValue::In => TypeQualifier::StorageQualifier(StorageQualifier::Input), TokenValue::Out => TypeQualifier::StorageQualifier(StorageQualifier::Output), TokenValue::Uniform => TypeQualifier::StorageQualifier( - StorageQualifier::StorageClass(StorageClass::Uniform), + StorageQualifier::AddressSpace(AddressSpace::Uniform), ), TokenValue::Shared => TypeQualifier::StorageQualifier( - StorageQualifier::StorageClass(StorageClass::WorkGroup), + StorageQualifier::AddressSpace(AddressSpace::WorkGroup), ), TokenValue::Buffer => TypeQualifier::StorageQualifier( - StorageQualifier::StorageClass(StorageClass::Storage { + StorageQualifier::AddressSpace(AddressSpace::Storage { access: crate::StorageAccess::default(), }), ), @@ -237,7 +237,7 @@ impl<'source> ParsingContext<'source> { )); qualifiers.push(( TypeQualifier::StorageQualifier( - StorageQualifier::StorageClass(StorageClass::PushConstant), + StorageQualifier::AddressSpace(AddressSpace::PushConstant), ), token.meta, )); diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 9a226916f..482a01b84 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -5,8 +5,8 @@ use super::{ Parser, Result, Span, }; use crate::{ - Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, Interpolation, - LocalVariable, ResourceBinding, ScalarKind, ShaderStage, StorageAccess, StorageClass, + AddressSpace, Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, + Interpolation, LocalVariable, ResourceBinding, ScalarKind, ShaderStage, StorageAccess, SwizzleComponent, Type, TypeInner, VectorSize, }; @@ -69,7 +69,7 @@ impl Parser { let handle = self.module.global_variables.append( GlobalVariable { name: Some(name.into()), - class: StorageClass::Private, + space: AddressSpace::Private, binding: None, ty, init: None, @@ -412,7 +412,7 @@ impl Parser { meta, }: VarDeclaration, ) -> Result { - let mut storage = StorageQualifier::StorageClass(StorageClass::Private); + let mut storage = StorageQualifier::AddressSpace(AddressSpace::Private); let mut interpolation = None; let mut set = None; let mut binding = None; @@ -425,12 +425,12 @@ impl Parser { for &(ref qualifier, meta) in qualifiers { match *qualifier { TypeQualifier::StorageQualifier(s) => { - if StorageQualifier::StorageClass(StorageClass::PushConstant) == storage - && s == StorageQualifier::StorageClass(StorageClass::Uniform) + if StorageQualifier::AddressSpace(AddressSpace::PushConstant) == storage + && s == StorageQualifier::AddressSpace(AddressSpace::Uniform) { - // Ignore the Uniform qualifier if the class was already set to PushConstant + // Ignore the Uniform qualifier if the space was already set to PushConstant continue; - } else if StorageQualifier::StorageClass(StorageClass::Private) != storage { + } else if StorageQualifier::AddressSpace(AddressSpace::Private) != storage { self.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one storage qualifier per declaration".into(), @@ -501,7 +501,7 @@ impl Parser { } match storage { - StorageQualifier::StorageClass(StorageClass::PushConstant) => { + StorageQualifier::AddressSpace(AddressSpace::PushConstant) => { if set.is_some() { self.errors.push(Error { kind: ErrorKind::SemanticError( @@ -511,8 +511,8 @@ impl Parser { }) } } - StorageQualifier::StorageClass(StorageClass::Uniform) - | StorageQualifier::StorageClass(StorageClass::Storage { .. }) => { + StorageQualifier::AddressSpace(AddressSpace::Uniform) + | StorageQualifier::AddressSpace(AddressSpace::Storage { .. }) => { if binding.is_none() { self.errors.push(Error { kind: ErrorKind::SemanticError( @@ -557,7 +557,7 @@ impl Parser { let handle = self.module.global_variables.append( GlobalVariable { name: name.clone(), - class: StorageClass::Private, + space: AddressSpace::Private, binding: None, ty, init, @@ -607,16 +607,16 @@ impl Parser { return Ok(GlobalOrConstant::Constant(init)); } - let class = match self.module.types[ty].inner { - TypeInner::Image { .. } => StorageClass::Handle, - TypeInner::Sampler { .. } => StorageClass::Handle, + let space = match self.module.types[ty].inner { + TypeInner::Image { .. } => AddressSpace::Handle, + TypeInner::Sampler { .. } => AddressSpace::Handle, _ => { - if let StorageQualifier::StorageClass(StorageClass::Storage { .. }) = storage { - StorageClass::Storage { access } + if let StorageQualifier::AddressSpace(AddressSpace::Storage { .. }) = storage { + AddressSpace::Storage { access } } else { match storage { - StorageQualifier::StorageClass(class) => class, - _ => StorageClass::Private, + StorageQualifier::AddressSpace(space) => space, + _ => AddressSpace::Private, } } } @@ -625,7 +625,7 @@ impl Parser { let handle = self.module.global_variables.append( GlobalVariable { name: name.clone(), - class, + space, binding: binding.map(|binding| ResourceBinding { group: set.unwrap_or(0), binding, diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index bdc8a6d24..22283fff0 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -155,19 +155,19 @@ pub(super) fn map_storage_class(word: spirv::Word) -> Result Ec::Global(crate::StorageClass::Function), + Some(Sc::Function) => Ec::Global(crate::AddressSpace::Function), Some(Sc::Input) => Ec::Input, Some(Sc::Output) => Ec::Output, - Some(Sc::Private) => Ec::Global(crate::StorageClass::Private), - Some(Sc::UniformConstant) => Ec::Global(crate::StorageClass::Handle), - Some(Sc::StorageBuffer) => Ec::Global(crate::StorageClass::Storage { + Some(Sc::Private) => Ec::Global(crate::AddressSpace::Private), + Some(Sc::UniformConstant) => Ec::Global(crate::AddressSpace::Handle), + Some(Sc::StorageBuffer) => Ec::Global(crate::AddressSpace::Storage { //Note: this is restricted by decorations later access: crate::StorageAccess::all(), }), // we expect the `Storage` case to be filtered out before calling this function. - Some(Sc::Uniform) => Ec::Global(crate::StorageClass::Uniform), - Some(Sc::Workgroup) => Ec::Global(crate::StorageClass::WorkGroup), - Some(Sc::PushConstant) => Ec::Global(crate::StorageClass::PushConstant), + Some(Sc::Uniform) => Ec::Global(crate::AddressSpace::Uniform), + Some(Sc::Workgroup) => Ec::Global(crate::AddressSpace::WorkGroup), + Some(Sc::PushConstant) => Ec::Global(crate::AddressSpace::PushConstant), _ => return Err(Error::UnsupportedStorageClass(word)), }) } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index ab669c705..ff6df9ba4 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -330,7 +330,7 @@ enum LookupLoadOverride { #[derive(PartialEq)] enum ExtendedClass { - Global(crate::StorageClass), + Global(crate::AddressSpace), Input, Output, } @@ -4004,19 +4004,19 @@ impl> Parser { let decor = self.future_decor.remove(&id); let base_lookup_ty = self.lookup_type.lookup(type_id)?; let base_inner = &module.types[base_lookup_ty.handle].inner; - let class = if let Some(class) = base_inner.pointer_class() { - class + let space = if let Some(space) = base_inner.pointer_space() { + space } else if self .lookup_storage_buffer_types .contains_key(&base_lookup_ty.handle) { - crate::StorageClass::Storage { + crate::AddressSpace::Storage { access: crate::StorageAccess::default(), } } else { match map_storage_class(storage_class)? { - ExtendedClass::Global(class) => class, - ExtendedClass::Input | ExtendedClass::Output => crate::StorageClass::Private, + ExtendedClass::Global(space) => space, + ExtendedClass::Input | ExtendedClass::Output => crate::AddressSpace::Private, } }; @@ -4028,8 +4028,8 @@ impl> Parser { .. } = *base_inner { - match class { - crate::StorageClass::Storage { .. } => {} + match space { + crate::AddressSpace::Storage { .. } => {} _ => { return Err(Error::UnsupportedRuntimeArrayStorageClass); } @@ -4037,7 +4037,7 @@ impl> Parser { } // Don't bother with pointer stuff for `Handle` types. - let lookup_ty = if class == crate::StorageClass::Handle { + let lookup_ty = if space == crate::AddressSpace::Handle { base_lookup_ty.clone() } else { LookupType { @@ -4046,7 +4046,7 @@ impl> Parser { name: decor.and_then(|dec| dec.name), inner: crate::TypeInner::Pointer { base: base_lookup_ty.handle, - class, + space, }, }, self.span_from_with_op(start), @@ -4576,7 +4576,7 @@ impl> Parser { let original_ty = self.lookup_type.lookup(type_id)?.handle; let mut effective_ty = original_ty; - if let crate::TypeInner::Pointer { base, class: _ } = module.types[original_ty].inner { + if let crate::TypeInner::Pointer { base, space: _ } = module.types[original_ty].inner { effective_ty = base; }; if let crate::TypeInner::Image { @@ -4601,7 +4601,7 @@ impl> Parser { } let ext_class = match self.lookup_storage_buffer_types.get(&effective_ty) { - Some(&access) => ExtendedClass::Global(crate::StorageClass::Storage { access }), + Some(&access) => ExtendedClass::Global(crate::AddressSpace::Storage { access }), None => map_storage_class(storage_class)?, }; @@ -4617,14 +4617,14 @@ impl> Parser { } let (inner, var) = match ext_class { - ExtendedClass::Global(mut class) => { - if let crate::StorageClass::Storage { ref mut access } = class { + ExtendedClass::Global(mut space) => { + if let crate::AddressSpace::Storage { ref mut access } = space { *access &= dec.flags.to_storage_access(); } let var = crate::GlobalVariable { binding: dec.resource_binding(), name: dec.name, - class, + space, ty: effective_ty, init, }; @@ -4667,7 +4667,7 @@ impl> Parser { let var = crate::GlobalVariable { name: dec.name.clone(), - class: crate::StorageClass::Private, + space: crate::AddressSpace::Private, binding: None, ty: effective_ty, init: None, @@ -4745,7 +4745,7 @@ impl> Parser { let var = crate::GlobalVariable { name: dec.name, - class: crate::StorageClass::Private, + space: crate::AddressSpace::Private, binding: None, ty: effective_ty, init, diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 840dc2b05..e4cec50b3 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -1,16 +1,16 @@ use super::{Error, Span}; -pub fn map_storage_class(word: &str, span: Span) -> Result> { +pub fn map_address_space(word: &str, span: Span) -> Result> { match word { - "private" => Ok(crate::StorageClass::Private), - "workgroup" => Ok(crate::StorageClass::WorkGroup), - "uniform" => Ok(crate::StorageClass::Uniform), - "storage" => Ok(crate::StorageClass::Storage { + "private" => Ok(crate::AddressSpace::Private), + "workgroup" => Ok(crate::AddressSpace::WorkGroup), + "uniform" => Ok(crate::AddressSpace::Uniform), + "storage" => Ok(crate::AddressSpace::Storage { access: crate::StorageAccess::default(), }), - "push_constant" => Ok(crate::StorageClass::PushConstant), - "function" => Ok(crate::StorageClass::Function), - _ => Err(Error::UnknownStorageClass(span)), + "push_constant" => Ok(crate::AddressSpace::PushConstant), + "function" => Ok(crate::AddressSpace::Function), + _ => Err(Error::UnknownAddressSpace(span)), } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6992886a6..7745f76c2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -148,7 +148,7 @@ pub enum Error<'a> { InvalidForInitializer(Span), InvalidGatherComponent(Span, i32), ReservedIdentifierPrefix(Span), - UnknownStorageClass(Span), + UnknownAddressSpace(Span), UnknownAttribute(Span), UnknownBuiltin(Span), UnknownAccess(Span), @@ -352,9 +352,9 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "invalid identifier".into())], notes: vec![], }, - Error::UnknownStorageClass(ref bad_span) => ParseError { - message: format!("unknown storage class: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "unknown storage class".into())], + Error::UnknownAddressSpace(ref bad_span) => ParseError { + message: format!("unknown address space: '{}'", &source[bad_span.clone()]), + labels: vec![(bad_span.clone(), "unknown address space".into())], notes: vec![], }, Error::UnknownAttribute(ref bad_span) => ParseError { @@ -667,7 +667,7 @@ mod type_inner_tests { let ptr = crate::TypeInner::Pointer { base: mytype2, - class: crate::StorageClass::Storage { + space: crate::AddressSpace::Storage { access: crate::StorageAccess::default(), }, }; @@ -1135,7 +1135,7 @@ impl BindingParser { struct ParsedVariable<'a> { name: &'a str, name_span: Span, - class: Option, + space: Option, ty: Handle, init: Option>, } @@ -2545,7 +2545,7 @@ impl Parser { // An expression like `&*ptr` may generate no Naga IR at all, but WGSL requires // an error if `ptr` is not a pointer. So we have to type-check this ourselves. - if ctx.resolve_type(pointer)?.pointer_class().is_none() { + if ctx.resolve_type(pointer)?.pointer_space().is_none() { let span = ctx .expressions .get_span(pointer) @@ -2772,11 +2772,11 @@ impl Parser { const_arena: &mut Arena, ) -> Result, Error<'a>> { self.push_scope(Scope::VariableDecl, lexer); - let mut class = None; + let mut space = None; if lexer.skip(Token::Paren('<')) { let (class_str, span) = lexer.next_ident_with_span()?; - class = Some(match class_str { + space = Some(match class_str { "storage" => { let access = if lexer.skip(Token::Separator(',')) { lexer.next_storage_access()? @@ -2784,9 +2784,9 @@ impl Parser { // defaulting to `read` crate::StorageAccess::LOAD }; - crate::StorageClass::Storage { access } + crate::AddressSpace::Storage { access } } - _ => conv::map_storage_class(class_str, span)?, + _ => conv::map_address_space(class_str, span)?, }); lexer.expect(Token::Paren('>'))?; } @@ -2805,7 +2805,7 @@ impl Parser { Ok(ParsedVariable { name, name_span, - class, + space, ty, init, }) @@ -2996,10 +2996,10 @@ impl Parser { "ptr" => { lexer.expect_generic_paren('<')?; let (ident, span) = lexer.next_ident_with_span()?; - let mut class = conv::map_storage_class(ident, span)?; + let mut space = conv::map_address_space(ident, span)?; lexer.expect(Token::Separator(','))?; let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; - if let crate::StorageClass::Storage { ref mut access } = class { + if let crate::AddressSpace::Storage { ref mut access } = space { *access = if lexer.skip(Token::Separator(',')) { lexer.next_storage_access()? } else { @@ -3007,7 +3007,7 @@ impl Parser { }; } lexer.expect_generic_paren('>')?; - crate::TypeInner::Pointer { base, class } + crate::TypeInner::Pointer { base, space } } "array" => { lexer.expect_generic_paren('<')?; @@ -3998,7 +3998,7 @@ impl Parser { let (span, is_reference) = match *expression { crate::Expression::GlobalVariable(handle) => ( module.global_variables.get_span(handle), - module.global_variables[handle].class != crate::StorageClass::Handle, + module.global_variables[handle].space != crate::AddressSpace::Handle, ), crate::Expression::Constant(handle) => (module.constants.get_span(handle), false), _ => unreachable!(), @@ -4308,7 +4308,7 @@ impl Parser { let var_handle = module.global_variables.append( crate::GlobalVariable { name: Some(pvar.name.to_owned()), - class: pvar.class.unwrap_or(crate::StorageClass::Handle), + space: pvar.space.unwrap_or(crate::AddressSpace::Handle), binding: binding.take(), ty: pvar.ty, init: pvar.init, diff --git a/src/lib.rs b/src/lib.rs index d6e6aacd6..d75b6185b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -92,7 +92,7 @@ Naga's rules for when `Expression`s are evaluated are as follows: does not. - A `GlobalVariable` expression referring to a global in the - [`StorageClass::Handle`] storage class produces the value directly, not + [`AddressSpace::Handle`] address space produces the value directly, not a pointer. Such global variables hold opaque types like shaders or images, and cannot be assigned to. @@ -291,12 +291,12 @@ pub enum ShaderStage { Compute, } -/// Class of storage for variables. +/// Addressing space of variables. #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] -pub enum StorageClass { +pub enum AddressSpace { /// Function locals. Function, /// Private data, per invocation, mutable. @@ -615,7 +615,7 @@ pub enum TypeInner { /// [`AccessIndex`]: Expression::AccessIndex Pointer { base: Handle, - class: StorageClass, + space: AddressSpace, }, /// Pointer to a scalar or vector. @@ -634,7 +634,7 @@ pub enum TypeInner { size: Option, kind: ScalarKind, width: Bytes, - class: StorageClass, + space: AddressSpace, }, /// Homogenous list of elements. @@ -787,7 +787,7 @@ pub struct GlobalVariable { /// Name of the variable, if any. pub name: Option, /// How this variable is to be stored. - pub class: StorageClass, + pub space: AddressSpace, /// For resources, defines the binding point. pub binding: Option, /// The type of this variable. @@ -1035,9 +1035,9 @@ bitflags::bitflags! { #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[derive(Default)] pub struct Barrier: u32 { - /// Barrier affects all `StorageClass::Storage` accesses. + /// Barrier affects all `AddressSpace::Storage` accesses. const STORAGE = 0x1; - /// Barrier affects all `StorageClass::WorkGroup` accesses. + /// Barrier affects all `AddressSpace::WorkGroup` accesses. const WORK_GROUP = 0x2; } } @@ -1065,7 +1065,7 @@ pub enum Expression { /// Indexing a [`Matrix`] produces a [`Vector`]. /// /// Indexing a [`Pointer`] to any of the above produces a pointer to the - /// element/component type, in the same [`class`]. In the case of [`Array`], + /// element/component type, in the same [`space`]. In the case of [`Array`], /// the result is an actual [`Pointer`], but for vectors and matrices, there /// may not be any type in the arena representing the component's type, so /// those produce [`ValuePointer`] types equivalent to the appropriate @@ -1094,7 +1094,7 @@ pub enum Expression { /// [`Matrix`]: TypeInner::Matrix /// [`Array`]: TypeInner::Array /// [`Pointer`]: TypeInner::Pointer - /// [`class`]: TypeInner::Pointer::class + /// [`space`]: TypeInner::Pointer::space /// [`ValuePointer`]: TypeInner::ValuePointer /// [`Float`]: ScalarKind::Float Access { @@ -1139,16 +1139,16 @@ pub enum Expression { /// Reference a global variable. /// - /// If the given `GlobalVariable`'s [`class`] is [`StorageClass::Handle`], + /// If the given `GlobalVariable`'s [`space`] is [`AddressSpace::Handle`], /// then the variable stores some opaque type like a sampler or an image, /// and a `GlobalVariable` expression referring to it produces the /// variable's value directly. /// - /// For any other storage class, a `GlobalVariable` expression produces a + /// For any other address space, a `GlobalVariable` expression produces a /// pointer to the variable's value. You must use a [`Load`] expression to /// retrieve its value, or a [`Store`] statement to assign it a new value. /// - /// [`class`]: GlobalVariable::class + /// [`space`]: GlobalVariable::space /// [`Load`]: Expression::Load /// [`Store`]: Statement::Store GlobalVariable(Handle), @@ -1633,13 +1633,13 @@ pub struct EntryPoint { #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct Module { - /// Storage for the types defined in this module. + /// Arena for the types defined in this module. pub types: UniqueArena, - /// Storage for the constants defined in this module. + /// Arena for the constants defined in this module. pub constants: Arena, - /// Storage for the global variables defined in this module. + /// Arena for the global variables defined in this module. pub global_variables: Arena, - /// Storage for the functions defined in this module. + /// Arena for the functions defined in this module. /// /// Each function must appear in this arena strictly before all its callers. /// Recursion is not supported. diff --git a/src/proc/index.rs b/src/proc/index.rs index e35537bd3..c67188745 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -76,7 +76,7 @@ pub struct BoundsCheckPolicies { /// ensures that using a pointer cannot access memory outside the 'buffer' /// that it was derived from. In Naga terms, this means that the hardware /// ensures that pointers computed by applying [`Access`] and - /// [`AccessIndex`] expressions to a [`GlobalVariable`] whose [`class`] is + /// [`AccessIndex`] expressions to a [`GlobalVariable`] whose [`space`] is /// [`Storage`] or [`Uniform`] will never read or write memory outside that /// global variable. /// @@ -94,13 +94,13 @@ pub struct BoundsCheckPolicies { /// the same as `index_bounds_check_policy`. /// /// [`GlobalVariable`]: crate::GlobalVariable - /// [`class`]: crate::GlobalVariable::class + /// [`space`]: crate::GlobalVariable::space /// [`Restrict`]: crate::back::BoundsCheckPolicy::Restrict /// [`ReadZeroSkipWrite`]: crate::back::BoundsCheckPolicy::ReadZeroSkipWrite /// [`Access`]: crate::Expression::Access /// [`AccessIndex`]: crate::Expression::AccessIndex - /// [`Storage`]: crate::StorageClass::Storage - /// [`Uniform`]: crate::StorageClass::Uniform + /// [`Storage`]: crate::AddressSpace::Storage + /// [`Uniform`]: crate::AddressSpace::Uniform #[cfg_attr(feature = "deserialize", serde(default))] pub buffer: BoundsCheckPolicy, @@ -138,9 +138,9 @@ impl BoundsCheckPolicies { types: &UniqueArena, info: &valid::FunctionInfo, ) -> BoundsCheckPolicy { - match info[access].ty.inner_with(types).pointer_class() { - Some(crate::StorageClass::Storage { access: _ }) - | Some(crate::StorageClass::Uniform) => self.buffer, + match info[access].ty.inner_with(types).pointer_space() { + Some(crate::AddressSpace::Storage { access: _ }) + | Some(crate::AddressSpace::Uniform) => self.buffer, // This covers other storage classes, but also accessing vectors and // matrices by value, where no pointer is involved. _ => self.index, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 47a99cff3..8f3fe320a 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -78,10 +78,10 @@ impl super::TypeInner { } } - pub fn pointer_class(&self) -> Option { + pub fn pointer_space(&self) -> Option { match *self { - Self::Pointer { class, .. } => Some(class), - Self::ValuePointer { class, .. } => Some(class), + Self::Pointer { space, .. } => Some(space), + Self::ValuePointer { space, .. } => Some(space), _ => None, } } @@ -147,18 +147,18 @@ impl super::TypeInner { ) -> Option { use crate::TypeInner as Ti; match *self { - Ti::Pointer { base, class } => match types[base].inner { + Ti::Pointer { base, space } => match types[base].inner { Ti::Scalar { kind, width } => Some(Ti::ValuePointer { size: None, kind, width, - class, + space, }), Ti::Vector { size, kind, width } => Some(Ti::ValuePointer { size: Some(size), kind, width, - class, + space, }), _ => None, }, @@ -185,17 +185,17 @@ impl super::TypeInner { } } -impl super::StorageClass { +impl super::AddressSpace { pub fn access(self) -> crate::StorageAccess { use crate::StorageAccess as Sa; match self { - crate::StorageClass::Function - | crate::StorageClass::Private - | crate::StorageClass::WorkGroup => Sa::LOAD | Sa::STORE, - crate::StorageClass::Uniform => Sa::LOAD, - crate::StorageClass::Storage { access } => access, - crate::StorageClass::Handle => Sa::LOAD, - crate::StorageClass::PushConstant => Sa::LOAD, + crate::AddressSpace::Function + | crate::AddressSpace::Private + | crate::AddressSpace::WorkGroup => Sa::LOAD | Sa::STORE, + crate::AddressSpace::Uniform => Sa::LOAD, + crate::AddressSpace::Storage { access } => access, + crate::AddressSpace::Handle => Sa::LOAD, + crate::AddressSpace::PushConstant => Sa::LOAD, } } } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 0879c1f6f..f2ad51805 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -54,7 +54,7 @@ use thiserror::Error; /// }) /// ``` /// -/// and the type of an access to a pointer of storage class `class` to such a +/// and the type of an access to a pointer of address space `space` to such a /// matrix might be: /// /// ```ignore @@ -62,7 +62,7 @@ use thiserror::Error; /// size: Some(rows), /// kind: ScalarKind::Float, /// width, -/// class +/// space, /// }) /// ``` /// @@ -130,17 +130,17 @@ impl Clone for TypeResolution { columns, width, }, - Ti::Pointer { base, class } => Ti::Pointer { base, class }, + Ti::Pointer { base, space } => Ti::Pointer { base, space }, Ti::ValuePointer { size, kind, width, - class, + space, } => Ti::ValuePointer { size, kind, width, - class, + space, }, _ => unreachable!("Unexpected clone type: {:?}", v), }), @@ -251,16 +251,16 @@ impl<'a> ResolveContext<'a> { size: Some(_), kind, width, - class, + space, } => TypeResolution::Value(Ti::ValuePointer { size: None, kind, width, - class, + space, }), - Ti::Pointer { base, class } => { + Ti::Pointer { base, space } => { TypeResolution::Value(match types[base].inner { - Ti::Array { base, .. } => Ti::Pointer { base, class }, + Ti::Array { base, .. } => Ti::Pointer { base, space }, Ti::Vector { size: _, kind, @@ -269,7 +269,7 @@ impl<'a> ResolveContext<'a> { size: None, kind, width, - class, + space, }, // Matrices are only dynamically indexed behind a pointer Ti::Matrix { @@ -280,7 +280,7 @@ impl<'a> ResolveContext<'a> { kind: crate::ScalarKind::Float, size: Some(rows), width, - class, + space, }, ref other => { log::error!("Access sub-type {:?}", other); @@ -332,7 +332,7 @@ impl<'a> ResolveContext<'a> { size: Some(size), kind, width, - class, + space, } => { if index >= size as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); @@ -341,14 +341,14 @@ impl<'a> ResolveContext<'a> { size: None, kind, width, - class, + space, }) } Ti::Pointer { base: ty_base, - class, + space, } => TypeResolution::Value(match types[ty_base].inner { - Ti::Array { base, .. } => Ti::Pointer { base, class }, + Ti::Array { base, .. } => Ti::Pointer { base, space }, Ti::Vector { size, kind, width } => { if index >= size as u32 { return Err(ResolveError::OutOfBoundsIndex { expr: base, index }); @@ -357,7 +357,7 @@ impl<'a> ResolveContext<'a> { size: None, kind, width, - class, + space, } } Ti::Matrix { @@ -372,7 +372,7 @@ impl<'a> ResolveContext<'a> { size: Some(rows), kind: crate::ScalarKind::Float, width, - class, + space, } } Ti::Struct { ref members, .. } => { @@ -381,7 +381,7 @@ impl<'a> ResolveContext<'a> { .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?; Ti::Pointer { base: member.ty, - class, + space, } } ref other => { @@ -449,12 +449,12 @@ impl<'a> ResolveContext<'a> { } crate::Expression::GlobalVariable(h) => { let var = self.global_vars.try_get(h)?; - if var.class == crate::StorageClass::Handle { + if var.space == crate::AddressSpace::Handle { TypeResolution::Handle(var.ty) } else { TypeResolution::Value(Ti::Pointer { base: var.ty, - class: var.class, + space: var.space, }) } } @@ -462,11 +462,11 @@ impl<'a> ResolveContext<'a> { let var = self.local_vars.try_get(h)?; TypeResolution::Value(Ti::Pointer { base: var.ty, - class: crate::StorageClass::Function, + space: crate::AddressSpace::Function, }) } crate::Expression::Load { pointer } => match *past(pointer)?.inner_with(types) { - Ti::Pointer { base, class: _ } => { + Ti::Pointer { base, space: _ } => { if let Ti::Atomic { kind, width } = types[base].inner { TypeResolution::Value(Ti::Scalar { kind, width }) } else { @@ -477,7 +477,7 @@ impl<'a> ResolveContext<'a> { size, kind, width, - class: _, + space: _, } => TypeResolution::Value(match size { Some(size) => Ti::Vector { size, kind, width }, None => Ti::Scalar { kind, width }, diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index ee3ace7fd..b634c203c 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -434,21 +434,21 @@ impl FunctionInfo { requirements: UniformityRequirements::empty(), } } - // depends on the storage class + // depends on the address space E::GlobalVariable(gh) => { - use crate::StorageClass as Sc; + use crate::AddressSpace as As; assignable_global = Some(gh); let var = &resolve_context.global_vars[gh]; - let uniform = match var.class { + let uniform = match var.space { // local data is non-uniform - Sc::Function | Sc::Private => false, + As::Function | As::Private => false, // workgroup memory is exclusively accessed by the group - Sc::WorkGroup => true, + As::WorkGroup => true, // uniform data - Sc::Uniform | Sc::PushConstant => true, + As::Uniform | As::PushConstant => true, // storage data is only uniform when read-only - Sc::Storage { access } => !access.contains(crate::StorageAccess::STORE), - Sc::Handle => false, + As::Storage { access } => !access.contains(crate::StorageAccess::STORE), + As::Handle => false, }; Uniformity { non_uniform_result: if uniform { None } else { Some(handle) }, @@ -905,7 +905,7 @@ fn uniform_control_flow() { name: None, init: None, ty, - class: crate::StorageClass::Handle, + space: crate::AddressSpace::Handle, binding: None, }, Default::default(), @@ -916,7 +916,7 @@ fn uniform_control_flow() { init: None, ty, binding: None, - class: crate::StorageClass::Uniform, + space: crate::AddressSpace::Uniform, }, Default::default(), ); diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 80d3c8216..88b1c181d 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1042,12 +1042,12 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), }; let good = match *arg1_ty { - Ti::Pointer { base, class: _ } => module.types[base].inner == *arg_ty, + Ti::Pointer { base, space: _ } => module.types[base].inner == *arg_ty, Ti::ValuePointer { size, kind: Sk::Float, width, - class: _, + space: _, } => size == size0 && width == width0, _ => false, }; diff --git a/src/valid/function.rs b/src/valid/function.rs index c6524872f..df597052a 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -86,11 +86,11 @@ pub enum FunctionError { }, #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")] InvalidArgumentType { index: usize, name: String }, - #[error("Argument '{name}' at index {index} is a pointer of class {class:?}, which can't be passed into functions.")] - InvalidArgumentPointerClass { + #[error("Argument '{name}' at index {index} is a pointer of space {space:?}, which can't be passed into functions.")] + InvalidArgumentPointerSpace { index: usize, name: String, - class: crate::StorageClass, + space: crate::AddressSpace, }, #[error("There are instructions after `return`/`break`/`continue`")] InstructionsAfterReturn, @@ -610,7 +610,7 @@ impl super::Validator { .map_err(|e| e.with_span())?; let good = match *pointer_ty { - Ti::Pointer { base, class: _ } => match context.types[base].inner { + Ti::Pointer { base, space: _ } => match context.types[base].inner { Ti::Atomic { kind, width } => *value_ty == Ti::Scalar { kind, width }, ref other => value_ty == other, }, @@ -618,13 +618,13 @@ impl super::Validator { size: Some(size), kind, width, - class: _, + space: _, } => *value_ty == Ti::Vector { size, kind, width }, Ti::ValuePointer { size: None, kind, width, - class: _, + space: _, } => *value_ty == Ti::Scalar { kind, width }, _ => false, }; @@ -635,8 +635,8 @@ impl super::Validator { .with_handle(value, context.expressions)); } - if let Some(class) = pointer_ty.pointer_class() { - if !class.access().contains(crate::StorageAccess::STORE) { + if let Some(space) = pointer_ty.pointer_space() { + if !space.access().contains(crate::StorageAccess::STORE) { return Err(FunctionError::InvalidStorePointer(pointer) .with_span_static( context.expressions.get_span(pointer), @@ -848,16 +848,16 @@ impl super::Validator { } .with_span_handle(argument.ty, &module.types) })?; - match ty.inner.pointer_class() { - Some(crate::StorageClass::Private) - | Some(crate::StorageClass::Function) - | Some(crate::StorageClass::WorkGroup) + match ty.inner.pointer_space() { + Some(crate::AddressSpace::Private) + | Some(crate::AddressSpace::Function) + | Some(crate::AddressSpace::WorkGroup) | None => {} Some(other) => { - return Err(FunctionError::InvalidArgumentPointerClass { + return Err(FunctionError::InvalidArgumentPointerSpace { index, name: argument.name.clone().unwrap_or_default(), - class: other, + space: other, } .with_span_handle(argument.ty, &module.types)) } diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 5665aface..2cfaf5f67 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -337,9 +337,9 @@ impl super::Validator { .get(var.ty.index()) .ok_or(GlobalVariableError::InvalidType)?; - let (required_type_flags, is_resource) = match var.class { - crate::StorageClass::Function => return Err(GlobalVariableError::InvalidUsage), - crate::StorageClass::Storage { .. } => { + let (required_type_flags, is_resource) = match var.space { + crate::AddressSpace::Function => return Err(GlobalVariableError::InvalidUsage), + crate::AddressSpace::Storage { .. } => { if let Err((ty_handle, disalignment)) = type_info.storage_layout { if self.flags.contains(super::ValidationFlags::STRUCT_LAYOUTS) { return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); @@ -347,7 +347,7 @@ impl super::Validator { } (TypeFlags::DATA | TypeFlags::HOST_SHARED, true) } - crate::StorageClass::Uniform => { + crate::AddressSpace::Uniform => { if let Err((ty_handle, disalignment)) = type_info.uniform_layout { if self.flags.contains(super::ValidationFlags::STRUCT_LAYOUTS) { return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); @@ -358,11 +358,11 @@ impl super::Validator { true, ) } - crate::StorageClass::Handle => (TypeFlags::empty(), true), - crate::StorageClass::Private | crate::StorageClass::WorkGroup => { + crate::AddressSpace::Handle => (TypeFlags::empty(), true), + crate::AddressSpace::Private | crate::AddressSpace::WorkGroup => { (TypeFlags::DATA | TypeFlags::SIZED, false) } - crate::StorageClass::PushConstant => { + crate::AddressSpace::PushConstant => { if !self.capabilities.contains(Capabilities::PUSH_CONSTANT) { return Err(GlobalVariableError::UnsupportedCapability( Capabilities::PUSH_CONSTANT, @@ -375,7 +375,7 @@ impl super::Validator { } }; - let is_handle = var.class == crate::StorageClass::Handle; + let is_handle = var.space == crate::AddressSpace::Handle; let good_type = match types[var.ty].inner { crate::TypeInner::Struct { .. } => !is_handle, crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => is_handle, @@ -486,19 +486,19 @@ impl super::Validator { continue; } - let allowed_usage = match var.class { - crate::StorageClass::Function => unreachable!(), - crate::StorageClass::Uniform => GlobalUse::READ | GlobalUse::QUERY, - crate::StorageClass::Storage { access } => storage_usage(access), - crate::StorageClass::Handle => match module.types[var.ty].inner { + let allowed_usage = match var.space { + crate::AddressSpace::Function => unreachable!(), + crate::AddressSpace::Uniform => GlobalUse::READ | GlobalUse::QUERY, + crate::AddressSpace::Storage { access } => storage_usage(access), + crate::AddressSpace::Handle => match module.types[var.ty].inner { crate::TypeInner::Image { class: crate::ImageClass::Storage { access, .. }, .. } => storage_usage(access), _ => GlobalUse::READ | GlobalUse::QUERY, }, - crate::StorageClass::Private | crate::StorageClass::WorkGroup => GlobalUse::all(), - crate::StorageClass::PushConstant => GlobalUse::READ, + crate::AddressSpace::Private | crate::AddressSpace::WorkGroup => GlobalUse::all(), + crate::AddressSpace::PushConstant => GlobalUse::READ, }; if !allowed_usage.contains(usage) { log::warn!("\tUsage error for: {:?}", var); diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 91807e002..3101ba773 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -63,7 +63,7 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Capabilities: u8 { - /// Support for `StorageClass:PushConstant`. + /// Support for `AddressSpace:PushConstant`. const PUSH_CONSTANT = 0x1; /// Float values with width = 8. const FLOAT64 = 0x2; diff --git a/src/valid/type.rs b/src/valid/type.rs index db68eac4c..aae4fbd11 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -82,10 +82,10 @@ pub enum TypeError { UnresolvedBase(Handle), #[error("Invalid type for pointer target {0:?}")] InvalidPointerBase(Handle), - #[error("Unsized types like {base:?} must be in the `Storage` storage class, not `{class:?}`")] + #[error("Unsized types like {base:?} must be in the `Storage` address space, not `{space:?}`")] InvalidPointerToUnsized { base: Handle, - class: crate::StorageClass, + space: crate::AddressSpace, }, #[error("Expected data type, found {0:?}")] InvalidData(Handle), @@ -257,8 +257,8 @@ impl super::Validator { width as u32, ) } - Ti::Pointer { base, class } => { - use crate::StorageClass as Sc; + Ti::Pointer { base, space } => { + use crate::AddressSpace as As; if base >= handle { return Err(TypeError::UnresolvedBase(base)); @@ -270,8 +270,8 @@ impl super::Validator { } // Runtime-sized values can only live in the `Storage` storage - // class, so it's useless to have a pointer to such a type in - // any other class. + // space, so it's useless to have a pointer to such a type in + // any other space. // // Detecting this problem here prevents the definition of // functions like: @@ -281,25 +281,25 @@ impl super::Validator { // which would otherwise be permitted, but uncallable. (They // may also present difficulties in code generation). if !base_info.flags.contains(TypeFlags::SIZED) { - match class { - Sc::Storage { .. } => {} + match space { + As::Storage { .. } => {} _ => { - return Err(TypeError::InvalidPointerToUnsized { base, class }); + return Err(TypeError::InvalidPointerToUnsized { base, space }); } } } // Pointers passed as arguments to user-defined functions must // be in the `Function`, `Private`, or `Workgroup` storage - // class. We only mark pointers in those classes as `ARGUMENT`. + // space. We only mark pointers in those spaces as `ARGUMENT`. // // `Validator::validate_function` actually checks the storage - // class of pointer arguments explicitly before checking the + // space of pointer arguments explicitly before checking the // `ARGUMENT` flag, to give better error messages. But it seems // best to set `ARGUMENT` accurately anyway. - let argument_flag = match class { - Sc::Function | Sc::Private | Sc::WorkGroup => TypeFlags::ARGUMENT, - Sc::Uniform | Sc::Storage { .. } | Sc::Handle | Sc::PushConstant => { + let argument_flag = match space { + As::Function | As::Private | As::WorkGroup => TypeFlags::ARGUMENT, + As::Uniform | As::Storage { .. } | As::Handle | As::PushConstant => { TypeFlags::empty() } }; @@ -312,7 +312,7 @@ impl super::Validator { size: _, kind, width, - class: _, + space: _, } => { if !self.check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index c802c970c..cba89d576 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -32,7 +32,7 @@ assignable_global: Some(1), ty: Value(Pointer( base: 3, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -61,7 +61,7 @@ assignable_global: None, ty: Value(Pointer( base: 1, - class: Function, + space: Function, )), ), ( @@ -89,7 +89,7 @@ assignable_global: None, ty: Value(Pointer( base: 1, - class: Function, + space: Function, )), ), ( @@ -376,7 +376,7 @@ assignable_global: Some(1), ty: Value(Pointer( base: 3, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -405,7 +405,7 @@ assignable_global: Some(1), ty: Value(Pointer( base: 2, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -437,7 +437,7 @@ assignable_global: Some(1), ty: Value(Pointer( base: 1, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -455,7 +455,7 @@ assignable_global: Some(1), ty: Value(Pointer( base: 2, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -487,7 +487,7 @@ assignable_global: Some(1), ty: Value(Pointer( base: 1, - class: Storage( + space: Storage( access: ( bits: 3, ), diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 07bb11eeb..9f721bce9 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -55,7 +55,7 @@ assignable_global: Some(3), ty: Value(Pointer( base: 13, - class: Uniform, + space: Uniform, )), ), ( @@ -69,7 +69,7 @@ assignable_global: Some(6), ty: Value(Pointer( base: 2, - class: Private, + space: Private, )), ), ( @@ -83,7 +83,7 @@ assignable_global: Some(5), ty: Value(Pointer( base: 4, - class: Private, + space: Private, )), ), ( @@ -119,7 +119,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 20, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -137,7 +137,7 @@ assignable_global: Some(7), ty: Value(Pointer( base: 4, - class: Private, + space: Private, )), ), ( @@ -1121,7 +1121,7 @@ assignable_global: Some(3), ty: Value(Pointer( base: 13, - class: Uniform, + space: Uniform, )), ), ( @@ -1135,7 +1135,7 @@ assignable_global: Some(6), ty: Value(Pointer( base: 2, - class: Private, + space: Private, )), ), ( @@ -1149,7 +1149,7 @@ assignable_global: Some(5), ty: Value(Pointer( base: 4, - class: Private, + space: Private, )), ), ( @@ -1185,7 +1185,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 20, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -1203,7 +1203,7 @@ assignable_global: Some(7), ty: Value(Pointer( base: 4, - class: Private, + space: Private, )), ), ( @@ -1760,7 +1760,7 @@ assignable_global: None, ty: Value(Pointer( base: 2, - class: Function, + space: Function, )), ), ( @@ -1774,7 +1774,7 @@ assignable_global: None, ty: Value(Pointer( base: 3, - class: Function, + space: Function, )), ), ( @@ -1799,7 +1799,7 @@ assignable_global: Some(3), ty: Value(Pointer( base: 12, - class: Uniform, + space: Uniform, )), ), ( @@ -1815,7 +1815,7 @@ size: None, kind: Uint, width: 4, - class: Uniform, + space: Uniform, )), ), ( @@ -1893,7 +1893,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -1922,7 +1922,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 18, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -1940,7 +1940,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 17, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2028,7 +2028,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2057,7 +2057,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 18, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2075,7 +2075,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2095,7 +2095,7 @@ size: None, kind: Float, width: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2127,7 +2127,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2156,7 +2156,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 18, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2174,7 +2174,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2194,7 +2194,7 @@ size: None, kind: Float, width: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2226,7 +2226,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2255,7 +2255,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 18, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2273,7 +2273,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2293,7 +2293,7 @@ size: None, kind: Float, width: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2338,7 +2338,7 @@ size: None, kind: Float, width: 4, - class: Private, + space: Private, )), ), ( @@ -2368,7 +2368,7 @@ size: None, kind: Float, width: 4, - class: Private, + space: Private, )), ), ( @@ -2398,7 +2398,7 @@ size: None, kind: Float, width: 4, - class: Private, + space: Private, )), ), ( @@ -2501,7 +2501,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2530,7 +2530,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 18, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2548,7 +2548,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2568,7 +2568,7 @@ size: None, kind: Float, width: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2600,7 +2600,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2629,7 +2629,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 18, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2647,7 +2647,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2667,7 +2667,7 @@ size: None, kind: Float, width: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2699,7 +2699,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 19, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2728,7 +2728,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 18, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2746,7 +2746,7 @@ assignable_global: Some(4), ty: Value(Pointer( base: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2766,7 +2766,7 @@ size: None, kind: Float, width: 4, - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -2935,7 +2935,7 @@ assignable_global: Some(6), ty: Value(Pointer( base: 2, - class: Private, + space: Private, )), ), ( @@ -2960,7 +2960,7 @@ assignable_global: Some(5), ty: Value(Pointer( base: 4, - class: Private, + space: Private, )), ), ( @@ -2974,7 +2974,7 @@ assignable_global: Some(7), ty: Value(Pointer( base: 4, - class: Private, + space: Private, )), ), ( diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 5fff82ee3..5cf3c6b08 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -75,7 +75,7 @@ global_variables: [ ( name: Some("v_indices"), - class: Storage( + space: Storage( access: ( bits: 3, ), diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index ab8c3eeb7..128a4032e 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -73,14 +73,14 @@ name: None, inner: Pointer( base: 2, - class: Function, + space: Function, ), ), ( name: None, inner: Pointer( base: 3, - class: Function, + space: Function, ), ), ( @@ -109,21 +109,21 @@ name: None, inner: Pointer( base: 13, - class: Uniform, + space: Uniform, ), ), ( name: None, inner: Pointer( base: 12, - class: Uniform, + space: Uniform, ), ), ( name: None, inner: Pointer( base: 3, - class: Uniform, + space: Uniform, ), ), ( @@ -186,7 +186,7 @@ name: None, inner: Pointer( base: 20, - class: Storage( + space: Storage( access: ( bits: 0, ), @@ -197,7 +197,7 @@ name: None, inner: Pointer( base: 19, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -208,7 +208,7 @@ name: None, inner: Pointer( base: 18, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -219,7 +219,7 @@ name: None, inner: Pointer( base: 17, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -230,21 +230,21 @@ name: None, inner: Pointer( base: 4, - class: Private, + space: Private, ), ), ( name: None, inner: Pointer( base: 2, - class: Private, + space: Private, ), ), ( name: None, inner: Pointer( base: 4, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -255,7 +255,7 @@ name: None, inner: Pointer( base: 1, - class: Storage( + space: Storage( access: ( bits: 3, ), @@ -266,7 +266,7 @@ name: None, inner: Pointer( base: 1, - class: Private, + space: Private, ), ), ( @@ -607,7 +607,7 @@ global_variables: [ ( name: Some("t_shadow"), - class: Handle, + space: Handle, binding: Some(( group: 0, binding: 2, @@ -617,7 +617,7 @@ ), ( name: Some("sampler_shadow"), - class: Handle, + space: Handle, binding: Some(( group: 0, binding: 3, @@ -627,7 +627,7 @@ ), ( name: Some("u_globals"), - class: Uniform, + space: Uniform, binding: Some(( group: 0, binding: 0, @@ -637,7 +637,7 @@ ), ( name: Some("s_lights"), - class: Storage( + space: Storage( access: ( bits: 1, ), @@ -651,21 +651,21 @@ ), ( name: Some("in_position_fs"), - class: Private, + space: Private, binding: None, ty: 4, init: None, ), ( name: Some("in_normal_fs"), - class: Private, + space: Private, binding: None, ty: 2, init: None, ), ( name: Some("out_color_fs"), - class: Private, + space: Private, binding: None, ty: 4, init: None, diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index a04b50b80..934eea1b4 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -210,11 +210,11 @@ fn unknown_storage_class() { r#" @group(0) @binding(0) var texture: texture_2d; "#, - r#"error: unknown storage class: 'bad' + r#"error: unknown address space: 'bad' ┌─ wgsl:2:39 │ 2 │ @group(0) @binding(0) var texture: texture_2d; - │ ^^^ unknown storage class + │ ^^^ unknown address space "#, ); @@ -877,7 +877,7 @@ fn invalid_functions() { if function_name == "unacceptable_unsized" && argument_name == "arg" } - // Pointer's storage class cannot hold unsized data. + // Pointer's address space cannot hold unsized data. check_validation_error! { "fn unacceptable_unsized(arg: ptr>) { }", " @@ -887,7 +887,7 @@ fn invalid_functions() { Err(naga::valid::ValidationError::Type { error: naga::valid::TypeError::InvalidPointerToUnsized { base: _, - class: naga::StorageClass::WorkGroup { .. }, + space: naga::AddressSpace::WorkGroup { .. }, }, .. }) @@ -895,31 +895,31 @@ fn invalid_functions() { // Pointers of these storage classes cannot be passed as arguments. check_validation_error! { - "fn unacceptable_ptr_class(arg: ptr>) { }": + "fn unacceptable_ptr_space(arg: ptr>) { }": Err(naga::valid::ValidationError::Function { name: function_name, - error: naga::valid::FunctionError::InvalidArgumentPointerClass { + error: naga::valid::FunctionError::InvalidArgumentPointerSpace { index: 0, name: argument_name, - class: naga::StorageClass::Storage { .. }, + space: naga::AddressSpace::Storage { .. }, }, .. }) - if function_name == "unacceptable_ptr_class" && argument_name == "arg" + if function_name == "unacceptable_ptr_space" && argument_name == "arg" } check_validation_error! { - "fn unacceptable_ptr_class(arg: ptr) { }": + "fn unacceptable_ptr_space(arg: ptr) { }": Err(naga::valid::ValidationError::Function { name: function_name, - error: naga::valid::FunctionError::InvalidArgumentPointerClass { + error: naga::valid::FunctionError::InvalidArgumentPointerSpace { index: 0, name: argument_name, - class: naga::StorageClass::Uniform, + space: naga::AddressSpace::Uniform, }, .. }) - if function_name == "unacceptable_ptr_class" && argument_name == "arg" + if function_name == "unacceptable_ptr_space" && argument_name == "arg" } } From bb604fd6a3ad9cb9dbe2ff579be55d008e624b18 Mon Sep 17 00:00:00 2001 From: glalonde Date: Tue, 1 Feb 2022 16:37:09 -0800 Subject: [PATCH 1562/2212] Mitigation for MSL atomic bounds check. (#1703) [msl-out] Correct output for bounds-checked atomic accesses. --- src/back/msl/writer.rs | 20 ++++++++- tests/in/bounds-check-zero-atomic.param.ron | 6 +++ tests/in/bounds-check-zero-atomic.wgsl | 25 +++++++++++ tests/out/msl/bounds-check-zero-atomic.msl | 49 +++++++++++++++++++++ tests/snapshots.rs | 1 + 5 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 tests/in/bounds-check-zero-atomic.param.ron create mode 100644 tests/in/bounds-check-zero-atomic.wgsl create mode 100644 tests/out/msl/bounds-check-zero-atomic.msl diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 90db79f2f..f2fd1bd89 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -791,15 +791,33 @@ impl Writer { value: Handle, context: &ExpressionContext, ) -> BackendResult { + // If the pointer we're passing to the atomic operation needs to be conditional + // for `ReadZeroSkipWrite`, the condition needs to *surround* the atomic op, and + // the pointer operand should be unchecked. + let policy = context.choose_bounds_check_policy(pointer); + let checked = policy == index::BoundsCheckPolicy::ReadZeroSkipWrite + && self.put_bounds_checks(pointer, context, back::Level(0), "")?; + + // If requested and successfully put bounds checks, continue the ternary expression. + if checked { + write!(self.out, " ? ")?; + } + write!( self.out, "{}::atomic_fetch_{}_explicit({}", NAMESPACE, key, ATOMIC_REFERENCE )?; - self.put_expression(pointer, context, true)?; + self.put_access_chain(pointer, policy, context)?; write!(self.out, ", ")?; self.put_expression(value, context, true)?; write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; + + // Finish the ternary expression. + if checked { + write!(self.out, " : DefaultConstructible()")?; + } + Ok(()) } diff --git a/tests/in/bounds-check-zero-atomic.param.ron b/tests/in/bounds-check-zero-atomic.param.ron new file mode 100644 index 000000000..3ca0053af --- /dev/null +++ b/tests/in/bounds-check-zero-atomic.param.ron @@ -0,0 +1,6 @@ +( + bounds_check_policies: ( + index: ReadZeroSkipWrite, + buffer: ReadZeroSkipWrite, + ), +) diff --git a/tests/in/bounds-check-zero-atomic.wgsl b/tests/in/bounds-check-zero-atomic.wgsl new file mode 100644 index 000000000..ad4012dbf --- /dev/null +++ b/tests/in/bounds-check-zero-atomic.wgsl @@ -0,0 +1,25 @@ +// Tests for `naga::back::BoundsCheckPolicy::ReadZeroSkipWrite` for atomic types. + +// These are separate from `bounds-check-zero.wgsl because SPIR-V does not yet +// support `ReadZeroSkipWrite` for atomics. Once it does, the test files could +// be combined. + +struct Globals { + a: atomic; + b: array, 10>; + c: array>; +}; + +@group(0) @binding(0) var globals: Globals; + +fn fetch_add_atomic() -> u32 { + return atomicAdd(&globals.a, 1u); +} + +fn fetch_add_atomic_static_sized_array(i: i32) -> u32 { + return atomicAdd(&globals.b[i], 1u); +} + +fn fetch_add_atomic_dynamic_sized_array(i: i32) -> u32 { + return atomicAdd(&globals.c[i], 1u); +} diff --git a/tests/out/msl/bounds-check-zero-atomic.msl b/tests/out/msl/bounds-check-zero-atomic.msl new file mode 100644 index 000000000..d6911b1aa --- /dev/null +++ b/tests/out/msl/bounds-check-zero-atomic.msl @@ -0,0 +1,49 @@ +// language: metal1.1 +#include +#include + +struct DefaultConstructible { + template + operator T() && { + return T {}; + } +}; +struct _mslBufferSizes { + metal::uint size0; +}; + +struct type_1 { + metal::atomic_uint inner[10]; +}; +typedef metal::atomic_uint type_2[1]; +struct Globals { + metal::atomic_uint a; + type_1 b; + type_2 c; +}; + +metal::uint fetch_add_atomic( + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + metal::uint _e3 = metal::atomic_fetch_add_explicit(&globals.a, 1u, metal::memory_order_relaxed); + return _e3; +} + +metal::uint fetch_add_atomic_static_sized_array( + int i, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + metal::uint _e5 = metal::uint(i) < 10 ? metal::atomic_fetch_add_explicit(&globals.b.inner[i], 1u, metal::memory_order_relaxed) : DefaultConstructible(); + return _e5; +} + +metal::uint fetch_add_atomic_dynamic_sized_array( + int i_1, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + metal::uint _e5 = metal::uint(i_1) < 1 + (_buffer_sizes.size0 - 44 - 4) / 4 ? metal::atomic_fetch_add_explicit(&globals.c[i_1], 1u, metal::memory_order_relaxed) : DefaultConstructible(); + return _e5; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 56378e2ac..65439888f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -477,6 +477,7 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ("bounds-check-zero", Targets::SPIRV | Targets::METAL), + ("bounds-check-zero-atomic", Targets::METAL), ("bounds-check-restrict", Targets::SPIRV | Targets::METAL), ("bounds-check-image-restrict", Targets::SPIRV), ("bounds-check-image-rzsw", Targets::SPIRV), From 75692d37951cac928edf2b89edd06cd026750b42 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 21 Jan 2022 12:30:18 -0500 Subject: [PATCH 1563/2212] Allow non-structure buffer types --- src/back/hlsl/writer.rs | 30 +++-- src/back/msl/writer.rs | 41 ++++--- src/back/spv/helpers.rs | 3 +- src/valid/interface.rs | 20 ++-- tests/in/globals.wgsl | 9 +- tests/out/glsl/globals.main.Compute.glsl | 8 +- tests/out/hlsl/globals.hlsl | 9 +- tests/out/msl/globals.msl | 12 +- tests/out/spv/globals.spvasm | 141 +++++++++++++---------- tests/out/wgsl/globals.wgsl | 16 ++- 10 files changed, 158 insertions(+), 131 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 01a58cf3f..10e928c62 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -585,9 +585,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, " {}", name)?; - if let TypeInner::Array { size, .. } = module.types[global.ty].inner { - self.write_array_size(module, size)?; - } if let Some(ref binding) = global.binding { // this was already resolved earlier when we started evaluating an entry point. @@ -597,20 +594,31 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ", space{}", bt.space)?; } write!(self.out, ")")?; - } else if global.space == crate::AddressSpace::Private { - write!(self.out, " = ")?; - if let Some(init) = global.init { - self.write_constant(module, init)?; - } else { - self.write_default_init(module, global.ty)?; + } else { + // need to write the array size if the type was emitted with `write_type` + if let TypeInner::Array { size, .. } = module.types[global.ty].inner { + self.write_array_size(module, size)?; + } + if global.space == crate::AddressSpace::Private { + write!(self.out, " = ")?; + if let Some(init) = global.init { + self.write_constant(module, init)?; + } else { + self.write_default_init(module, global.ty)?; + } } } if global.space == crate::AddressSpace::Uniform { write!(self.out, " {{ ")?; self.write_type(module, global.ty)?; - let name = &self.names[&NameKey::GlobalVariable(handle)]; - writeln!(self.out, " {}; }}", name)?; + let sub_name = &self.names[&NameKey::GlobalVariable(handle)]; + write!(self.out, " {}", sub_name)?; + // need to write the array size if the type was emitted with `write_type` + if let TypeInner::Array { size, .. } = module.types[global.ty].inner { + self.write_array_size(module, size)?; + } + writeln!(self.out, "; }}")?; } else { writeln!(self.out, ";")?; } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index f2fd1bd89..13e570ba1 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -368,18 +368,25 @@ fn should_pack_struct_member( } fn needs_array_length(ty: Handle, arena: &crate::UniqueArena) -> bool { - if let crate::TypeInner::Struct { ref members, .. } = arena[ty].inner { - if let Some(member) = members.last() { - if let crate::TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } = arena[member.ty].inner - { - return true; + match arena[ty].inner { + crate::TypeInner::Struct { ref members, .. } => { + if let Some(member) = members.last() { + if let crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } = arena[member.ty].inner + { + return true; + } } + false } + crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } => true, + _ => false, } - false } impl crate::AddressSpace { @@ -741,16 +748,18 @@ impl Writer { context: &ExpressionContext, ) -> BackendResult { let global = &context.module.global_variables[handle]; - let members = match context.module.types[global.ty].inner { - crate::TypeInner::Struct { ref members, .. } => members, + let (offset, array_ty) = match context.module.types[global.ty].inner { + crate::TypeInner::Struct { ref members, .. } => match members.last() { + Some(&crate::StructMember { offset, ty, .. }) => (offset, ty), + None => return Err(Error::Validation), + }, + crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } => (0, global.ty), _ => return Err(Error::Validation), }; - let (offset, array_ty) = match members.last() { - Some(&crate::StructMember { offset, ty, .. }) => (offset, ty), - None => return Err(Error::Validation), - }; - let (size, stride) = match context.module.types[array_ty].inner { crate::TypeInner::Array { base, stride, .. } => ( context.module.types[base] diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index cac21add0..acde9504d 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -86,6 +86,7 @@ pub fn global_needs_wrapper(ir_module: &crate::Module, var: &crate::GlobalVariab }, None => false, }, - _ => false, + // if it's not a structure, let's wrap it to be able to put "Block" + _ => true, } } diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 2cfaf5f67..c322aac2b 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -358,7 +358,15 @@ impl super::Validator { true, ) } - crate::AddressSpace::Handle => (TypeFlags::empty(), true), + crate::AddressSpace::Handle => { + match types[var.ty].inner { + crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => {} + _ => { + return Err(GlobalVariableError::InvalidType); + } + }; + (TypeFlags::empty(), true) + } crate::AddressSpace::Private | crate::AddressSpace::WorkGroup => { (TypeFlags::DATA | TypeFlags::SIZED, false) } @@ -375,16 +383,6 @@ impl super::Validator { } }; - let is_handle = var.space == crate::AddressSpace::Handle; - let good_type = match types[var.ty].inner { - crate::TypeInner::Struct { .. } => !is_handle, - crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => is_handle, - _ => false, - }; - if is_resource && !good_type { - return Err(GlobalVariableError::InvalidType); - } - if !type_info.flags.contains(required_type_flags) { return Err(GlobalVariableError::MissingTypeFlags { seen: type_info.flags, diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 02c9e069a..23dabf1b1 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -13,12 +13,11 @@ struct Foo { @group(0) @binding(1) var alignment: Foo; -struct Dummy { - arr: array>; -}; - @group(0) @binding(2) -var dummy: Dummy; +var dummy: array>; + +@group(0) @binding(3) +var float_vecs: array, 20>; @stage(compute) @workgroup_size(1) fn main() { diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index 4b5377951..a40e6bbac 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -19,10 +19,10 @@ layout(std430) readonly buffer Foo_block_0Compute { Foo _group_0_binding_1_cs; } void main() { float Foo_1 = 1.0; bool at = true; - float _e8 = _group_0_binding_1_cs.v1_; - wg[3] = _e8; - float _e13 = _group_0_binding_1_cs.v3_.x; - wg[2] = _e13; + float _e9 = _group_0_binding_1_cs.v1_; + wg[3] = _e9; + float _e14 = _group_0_binding_1_cs.v3_.x; + wg[2] = _e14; at_1 = 2u; return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 41a114f5b..a6b91c952 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -9,6 +9,7 @@ groupshared float wg[10]; groupshared uint at_1; ByteAddressBuffer alignment : register(t1); ByteAddressBuffer dummy : register(t2); +cbuffer float_vecs : register(b3) { float4 float_vecs[20]; } [numthreads(1, 1, 1)] void main() @@ -16,10 +17,10 @@ void main() float Foo_1 = 1.0; bool at = true; - float _expr8 = asfloat(alignment.Load(12)); - wg[3] = _expr8; - float _expr13 = asfloat(alignment.Load(0+0)); - wg[2] = _expr13; + float _expr9 = asfloat(alignment.Load(12)); + wg[3] = _expr9; + float _expr14 = asfloat(alignment.Load(0+0)); + wg[2] = _expr14; at_1 = 2u; return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index f2c37b5ab..dde816076 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -15,8 +15,8 @@ struct Foo { float v1_; }; typedef metal::float2 type_6[1]; -struct Dummy { - type_6 arr; +struct type_8 { + metal::float4 inner[20]; }; kernel void main_( @@ -26,10 +26,10 @@ kernel void main_( ) { float Foo_1 = 1.0; bool at = true; - float _e8 = alignment.v1_; - wg.inner[3] = _e8; - float _e13 = metal::float3(alignment.v3_).x; - wg.inner[2] = _e13; + float _e9 = alignment.v1_; + wg.inner[3] = _e9; + float _e14 = metal::float3(alignment.v3_).x; + wg.inner[2] = _e14; metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index a11785e8c..ecc2805ef 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,81 +1,94 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 53 +; Bound: 61 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %34 "main" -OpExecutionMode %34 LocalSize 1 1 1 -OpDecorate %14 ArrayStride 4 -OpMemberDecorate %16 0 Offset 0 -OpMemberDecorate %16 1 Offset 12 -OpDecorate %18 ArrayStride 8 -OpMemberDecorate %19 0 Offset 0 -OpDecorate %24 NonWritable -OpDecorate %24 DescriptorSet 0 -OpDecorate %24 Binding 1 -OpDecorate %25 Block -OpMemberDecorate %25 0 Offset 0 -OpDecorate %27 NonWritable -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 2 -OpDecorate %19 Block +OpEntryPoint GLCompute %40 "main" +OpExecutionMode %40 LocalSize 1 1 1 +OpDecorate %15 ArrayStride 4 +OpMemberDecorate %17 0 Offset 0 +OpMemberDecorate %17 1 Offset 12 +OpDecorate %19 ArrayStride 8 +OpDecorate %21 ArrayStride 16 +OpDecorate %26 NonWritable +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 1 +OpDecorate %27 Block +OpMemberDecorate %27 0 Offset 0 +OpDecorate %29 NonWritable +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 2 +OpDecorate %30 Block +OpMemberDecorate %30 0 Offset 0 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 3 +OpDecorate %33 Block +OpMemberDecorate %33 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 %6 = OpTypeInt 32 0 %5 = OpConstant %6 10 %8 = OpTypeInt 32 1 -%7 = OpConstant %8 3 -%9 = OpConstant %8 2 -%10 = OpConstant %6 2 -%12 = OpTypeFloat 32 -%11 = OpConstant %12 1.0 -%13 = OpConstantTrue %4 -%14 = OpTypeArray %12 %5 -%15 = OpTypeVector %12 3 -%16 = OpTypeStruct %15 %12 -%17 = OpTypeVector %12 2 -%18 = OpTypeRuntimeArray %17 -%19 = OpTypeStruct %18 -%21 = OpTypePointer Workgroup %14 -%20 = OpVariable %21 Workgroup -%23 = OpTypePointer Workgroup %6 +%7 = OpConstant %8 20 +%9 = OpConstant %8 3 +%10 = OpConstant %8 2 +%11 = OpConstant %6 2 +%13 = OpTypeFloat 32 +%12 = OpConstant %13 1.0 +%14 = OpConstantTrue %4 +%15 = OpTypeArray %13 %5 +%16 = OpTypeVector %13 3 +%17 = OpTypeStruct %16 %13 +%18 = OpTypeVector %13 2 +%19 = OpTypeRuntimeArray %18 +%20 = OpTypeVector %13 4 +%21 = OpTypeArray %20 %7 +%23 = OpTypePointer Workgroup %15 %22 = OpVariable %23 Workgroup -%25 = OpTypeStruct %16 -%26 = OpTypePointer StorageBuffer %25 -%24 = OpVariable %26 StorageBuffer -%28 = OpTypePointer StorageBuffer %19 -%27 = OpVariable %28 StorageBuffer -%30 = OpTypePointer Function %12 -%32 = OpTypePointer Function %4 -%35 = OpTypeFunction %2 -%36 = OpTypePointer StorageBuffer %16 -%37 = OpConstant %6 0 -%40 = OpTypePointer Workgroup %12 -%41 = OpTypePointer StorageBuffer %12 -%42 = OpConstant %6 1 -%45 = OpConstant %6 3 -%47 = OpTypePointer StorageBuffer %15 -%48 = OpTypePointer StorageBuffer %12 -%52 = OpConstant %6 256 -%34 = OpFunction %2 None %35 -%33 = OpLabel -%29 = OpVariable %30 Function %11 -%31 = OpVariable %32 Function %13 -%38 = OpAccessChain %36 %24 %37 -OpBranch %39 +%25 = OpTypePointer Workgroup %6 +%24 = OpVariable %25 Workgroup +%27 = OpTypeStruct %17 +%28 = OpTypePointer StorageBuffer %27 +%26 = OpVariable %28 StorageBuffer +%30 = OpTypeStruct %19 +%31 = OpTypePointer StorageBuffer %30 +%29 = OpVariable %31 StorageBuffer +%33 = OpTypeStruct %21 +%34 = OpTypePointer Uniform %33 +%32 = OpVariable %34 Uniform +%36 = OpTypePointer Function %13 +%38 = OpTypePointer Function %4 +%41 = OpTypeFunction %2 +%42 = OpTypePointer StorageBuffer %17 +%43 = OpConstant %6 0 +%45 = OpTypePointer StorageBuffer %19 +%46 = OpTypePointer Uniform %21 +%48 = OpTypePointer Workgroup %13 +%49 = OpTypePointer StorageBuffer %13 +%50 = OpConstant %6 1 +%53 = OpConstant %6 3 +%55 = OpTypePointer StorageBuffer %16 +%56 = OpTypePointer StorageBuffer %13 +%60 = OpConstant %6 256 +%40 = OpFunction %2 None %41 %39 = OpLabel -%43 = OpAccessChain %41 %38 %42 -%44 = OpLoad %12 %43 -%46 = OpAccessChain %40 %20 %45 -OpStore %46 %44 -%49 = OpAccessChain %48 %38 %37 %37 -%50 = OpLoad %12 %49 -%51 = OpAccessChain %40 %20 %10 -OpStore %51 %50 -OpAtomicStore %22 %9 %52 %10 +%35 = OpVariable %36 Function %12 +%37 = OpVariable %38 Function %14 +%44 = OpAccessChain %42 %26 %43 +OpBranch %47 +%47 = OpLabel +%51 = OpAccessChain %49 %44 %50 +%52 = OpLoad %13 %51 +%54 = OpAccessChain %48 %22 %53 +OpStore %54 %52 +%57 = OpAccessChain %56 %44 %43 %43 +%58 = OpLoad %13 %57 +%59 = OpAccessChain %48 %22 %11 +OpStore %59 %58 +OpAtomicStore %24 %10 %60 %11 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 6184f987c..3196468c5 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -3,10 +3,6 @@ struct Foo { v1_: f32; }; -struct Dummy { - arr: array>; -}; - let Foo_2: bool = true; var wg: array; @@ -14,17 +10,19 @@ var at_1: atomic; @group(0) @binding(1) var alignment: Foo; @group(0) @binding(2) -var dummy: Dummy; +var dummy: array>; +@group(0) @binding(3) +var float_vecs: array,20>; @stage(compute) @workgroup_size(1, 1, 1) fn main() { var Foo_1: f32 = 1.0; var at: bool = true; - let _e8 = alignment.v1_; - wg[3] = _e8; - let _e13 = alignment.v3_.x; - wg[2] = _e13; + let _e9 = alignment.v1_; + wg[3] = _e9; + let _e14 = alignment.v3_.x; + wg[2] = _e14; atomicStore((&at_1), 2u); return; } From 9b89c5fa8996822b9d8b5021aae8e6388361c8f7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 2 Feb 2022 12:37:36 -0500 Subject: [PATCH 1564/2212] Improve error messages about address space --- src/arena.rs | 7 +++++-- src/valid/compose.rs | 10 ++++----- src/valid/expression.rs | 5 +++-- src/valid/function.rs | 8 ++----- src/valid/interface.rs | 46 +++++++++++++++++++++++++++-------------- src/valid/mod.rs | 10 ++++----- 6 files changed, 49 insertions(+), 37 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 8b5ba84b4..583e99eec 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -529,8 +529,11 @@ impl UniqueArena { } /// Return this arena's value at `handle`, if that is a valid handle. - pub fn get_handle(&self, handle: Handle) -> Option<&T> { - self.set.get_index(handle.index()) + pub fn get_handle(&self, handle: Handle) -> Result<&T, BadHandle> { + self.set.get_index(handle.index()).ok_or_else(|| BadHandle { + kind: std::any::type_name::(), + index: handle.index(), + }) } } diff --git a/src/valid/compose.rs b/src/valid/compose.rs index 23599b5a0..6e5c49922 100644 --- a/src/valid/compose.rs +++ b/src/valid/compose.rs @@ -4,13 +4,13 @@ use crate::{ proc::TypeResolution, }; -use crate::Handle; +use crate::arena::{BadHandle, Handle}; #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum ComposeError { - #[error("Compose type {0:?} doesn't exist")] - TypeDoesntExist(Handle), + #[error(transparent)] + BadHandle(#[from] BadHandle), #[error("Composing of type {0:?} can't be done")] Type(Handle), #[error("Composing expects {expected} components but {given} were given")] @@ -28,9 +28,7 @@ pub fn validate_compose( ) -> Result<(), ComposeError> { use crate::TypeInner as Ti; - let self_ty = type_arena - .get_handle(self_ty_handle) - .ok_or(ComposeError::TypeDoesntExist(self_ty_handle))?; + let self_ty = type_arena.get_handle(self_ty_handle)?; match self_ty.inner { // vectors are composed from scalars or other vectors Ti::Vector { size, kind, width } => { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 88b1c181d..f7a03abc0 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1383,10 +1383,11 @@ impl super::Validator { } E::ArrayLength(expr) => match *resolver.resolve(expr)? { Ti::Pointer { base, .. } => { - if let Some(&Ti::Array { + let base_ty = resolver.types.get_handle(base)?; + if let Ti::Array { size: crate::ArraySize::Dynamic, .. - }) = resolver.types.get_handle(base).map(|ty| &ty.inner) + } = base_ty.inner { ShaderStages::all() } else { diff --git a/src/valid/function.rs b/src/valid/function.rs index df597052a..4c1262ec7 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -841,12 +841,8 @@ impl super::Validator { #[cfg(feature = "validate")] for (index, argument) in fun.arguments.iter().enumerate() { - let ty = module.types.get_handle(argument.ty).ok_or_else(|| { - FunctionError::InvalidArgumentType { - index, - name: argument.name.clone().unwrap_or_default(), - } - .with_span_handle(argument.ty, &module.types) + let ty = module.types.get_handle(argument.ty).map_err(|err| { + FunctionError::from(err).with_span_handle(argument.ty, &module.types) })?; match ty.inner.pointer_space() { Some(crate::AddressSpace::Private) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index c322aac2b..360dbca1b 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -2,7 +2,7 @@ use super::{ analyzer::{FunctionInfo, GlobalUse}, Capabilities, Disalignment, FunctionError, ModuleInfo, }; -use crate::arena::{Handle, UniqueArena}; +use crate::arena::{BadHandle, Handle, UniqueArena}; use crate::span::{AddSpan as _, MapErrWithSpan as _, SpanProvider as _, WithSpan}; use bit_set::BitSet; @@ -12,10 +12,12 @@ const MAX_WORKGROUP_SIZE: u32 = 0x4000; #[derive(Clone, Debug, thiserror::Error)] pub enum GlobalVariableError { - #[error("Usage isn't compatible with the storage class")] - InvalidUsage, - #[error("Type isn't compatible with the storage class")] - InvalidType, + #[error(transparent)] + BadHandle(#[from] BadHandle), + #[error("Usage isn't compatible with address space {0:?}")] + InvalidUsage(crate::AddressSpace), + #[error("Type isn't compatible with with address space {0:?}")] + InvalidType(crate::AddressSpace), #[error("Type flags {seen:?} do not meet the required {required:?}")] MissingTypeFlags { required: super::TypeFlags, @@ -25,8 +27,12 @@ pub enum GlobalVariableError { UnsupportedCapability(Capabilities), #[error("Binding decoration is missing or not applicable")] InvalidBinding, - #[error("Alignment requirements for this storage class are not met by {0:?}")] - Alignment(Handle, #[source] Disalignment), + #[error("Alignment requirements for address space {0:?} are not met by {1:?}")] + Alignment( + crate::AddressSpace, + Handle, + #[source] Disalignment, + ), } #[derive(Clone, Debug, thiserror::Error)] @@ -332,17 +338,23 @@ impl super::Validator { use super::TypeFlags; log::debug!("var {:?}", var); - let type_info = self - .types - .get(var.ty.index()) - .ok_or(GlobalVariableError::InvalidType)?; + let type_info = self.types.get(var.ty.index()).ok_or_else(|| BadHandle { + kind: "type", + index: var.ty.index(), + })?; let (required_type_flags, is_resource) = match var.space { - crate::AddressSpace::Function => return Err(GlobalVariableError::InvalidUsage), + crate::AddressSpace::Function => { + return Err(GlobalVariableError::InvalidUsage(var.space)) + } crate::AddressSpace::Storage { .. } => { if let Err((ty_handle, disalignment)) = type_info.storage_layout { if self.flags.contains(super::ValidationFlags::STRUCT_LAYOUTS) { - return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); + return Err(GlobalVariableError::Alignment( + var.space, + ty_handle, + disalignment, + )); } } (TypeFlags::DATA | TypeFlags::HOST_SHARED, true) @@ -350,7 +362,11 @@ impl super::Validator { crate::AddressSpace::Uniform => { if let Err((ty_handle, disalignment)) = type_info.uniform_layout { if self.flags.contains(super::ValidationFlags::STRUCT_LAYOUTS) { - return Err(GlobalVariableError::Alignment(ty_handle, disalignment)); + return Err(GlobalVariableError::Alignment( + var.space, + ty_handle, + disalignment, + )); } } ( @@ -362,7 +378,7 @@ impl super::Validator { match types[var.ty].inner { crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => {} _ => { - return Err(GlobalVariableError::InvalidType); + return Err(GlobalVariableError::InvalidType(var.space)); } }; (TypeFlags::empty(), true) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 3101ba773..82ead2054 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -9,7 +9,7 @@ mod r#type; use crate::arena::{Arena, UniqueArena}; use crate::{ - arena::Handle, + arena::{BadHandle, Handle}, proc::{LayoutError, Layouter}, FastHashSet, }; @@ -114,6 +114,8 @@ pub struct Validator { #[derive(Clone, Debug, thiserror::Error)] pub enum ConstantError { + #[error(transparent)] + BadHandle(#[from] BadHandle), #[error("The type doesn't match the constant")] InvalidType, #[error("The component handle {0:?} can not be resolved")] @@ -240,11 +242,7 @@ impl Validator { } } crate::ConstantInner::Composite { ty, ref components } => { - match types - .get_handle(ty) - .ok_or(ConstantError::InvalidType)? - .inner - { + match types.get_handle(ty)?.inner { crate::TypeInner::Array { size: crate::ArraySize::Constant(size_handle), .. From f63003cd368a4fa94e3b45cdfdf441c9264a64fa Mon Sep 17 00:00:00 2001 From: Taylor Holliday Date: Thu, 3 Feb 2022 10:00:04 -0800 Subject: [PATCH 1565/2212] =?UTF-8?q?WGSL=20storage=20address=20space=20sh?= =?UTF-8?q?ould=20always=20correspond=20to=20MSL=20device=20add=E2=80=A6?= =?UTF-8?q?=20(#1711)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * WGSL storage address space should always correspond to MSL device address space. See MSL spec section 4.2. * Update baselines * Add error for storage address space if MSL version < 2. * Update default MSL version to 2.0. --- src/back/msl/mod.rs | 4 +++- src/back/msl/writer.rs | 8 ++++---- tests/out/msl/boids.msl | 2 +- tests/out/msl/bounds-check-restrict.msl | 2 +- tests/out/msl/bounds-check-zero-atomic.msl | 2 +- tests/out/msl/bounds-check-zero.msl | 2 +- tests/out/msl/collatz.msl | 2 +- tests/out/msl/control-flow.msl | 2 +- tests/out/msl/empty-global-name.msl | 2 +- tests/out/msl/empty.msl | 2 +- tests/out/msl/functions.msl | 2 +- tests/out/msl/globals.msl | 4 ++-- tests/out/msl/image.msl | 2 +- tests/out/msl/interface.msl | 2 +- tests/out/msl/interpolate.msl | 2 +- tests/out/msl/math-functions.msl | 2 +- tests/out/msl/operators.msl | 2 +- tests/out/msl/policy-mix.msl | 4 ++-- tests/out/msl/quad-vert.msl | 2 +- tests/out/msl/quad.msl | 2 +- tests/out/msl/shadow.msl | 4 ++-- tests/out/msl/standard.msl | 2 +- tests/out/msl/texture-arg.msl | 2 +- 23 files changed, 31 insertions(+), 29 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 8e26c7b16..b886d1573 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -141,6 +141,8 @@ pub enum Error { UnsupportedBuiltIn(crate::BuiltIn), #[error("capability {0:?} is not supported")] CapabilityNotSupported(crate::valid::Capabilities), + #[error("address space {0:?} is not supported for target MSL version")] + UnsupportedAddressSpace(crate::AddressSpace), } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -185,7 +187,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { Options { - lang_version: (1, 1), + lang_version: (2, 0), per_stage_map: PerStageMap::default(), inline_samplers: Vec::new(), spirv_cross_compatibility: false, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 13e570ba1..26afaae64 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -410,10 +410,7 @@ impl crate::AddressSpace { match self { Self::Handle => None, Self::Uniform | Self::PushConstant => Some("constant"), - Self::Storage { access } if access.contains(crate::StorageAccess::STORE) => { - Some("device") - } - Self::Storage { .. } => Some("constant"), + Self::Storage { .. } => Some("device"), Self::Private | Self::Function => Some("thread"), Self::WorkGroup => Some("threadgroup"), } @@ -3033,6 +3030,9 @@ impl Writer { options.resolve_push_constants(ep.stage).ok() } crate::AddressSpace::WorkGroup => None, + crate::AddressSpace::Storage { .. } if options.lang_version < (2, 0) => { + return Err(Error::UnsupportedAddressSpace(var.space)) + } _ => options .resolve_resource_binding(ep.stage, var.binding.as_ref().unwrap()) .ok(), diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index b717466f9..9f6048997 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -31,7 +31,7 @@ struct main_Input { kernel void main_( metal::uint3 global_invocation_id [[thread_position_in_grid]] , constant SimParams& params [[buffer(0)]] -, constant Particles& particlesSrc [[buffer(1)]] +, device Particles& particlesSrc [[buffer(1)]] , device Particles& particlesDst [[buffer(2)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(3)]] ) { diff --git a/tests/out/msl/bounds-check-restrict.msl b/tests/out/msl/bounds-check-restrict.msl index 16e432008..93bbf910b 100644 --- a/tests/out/msl/bounds-check-restrict.msl +++ b/tests/out/msl/bounds-check-restrict.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/bounds-check-zero-atomic.msl b/tests/out/msl/bounds-check-zero-atomic.msl index d6911b1aa..038bef6bf 100644 --- a/tests/out/msl/bounds-check-zero-atomic.msl +++ b/tests/out/msl/bounds-check-zero-atomic.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/bounds-check-zero.msl b/tests/out/msl/bounds-check-zero.msl index 0662b3340..b61e523aa 100644 --- a/tests/out/msl/bounds-check-zero.msl +++ b/tests/out/msl/bounds-check-zero.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index 22769a8a5..540ddbbb5 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index bed973ead..e0d2f0ceb 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/empty-global-name.msl b/tests/out/msl/empty-global-name.msl index efae101f4..3b9dfec5f 100644 --- a/tests/out/msl/empty-global-name.msl +++ b/tests/out/msl/empty-global-name.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/empty.msl b/tests/out/msl/empty.msl index ddc6b6bf1..c3bb1a71b 100644 --- a/tests/out/msl/empty.msl +++ b/tests/out/msl/empty.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/functions.msl b/tests/out/msl/functions.msl index 6ace92f74..11574c679 100644 --- a/tests/out/msl/functions.msl +++ b/tests/out/msl/functions.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index dde816076..c8c58b339 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include @@ -22,7 +22,7 @@ struct type_8 { kernel void main_( threadgroup type_2& wg , threadgroup metal::atomic_uint& at_1 -, constant Foo& alignment [[user(fake0)]] +, device Foo& alignment [[user(fake0)]] ) { float Foo_1 = 1.0; bool at = true; diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 68d52340f..7fe677664 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index f95620c37..6461aee75 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl index b92adb399..0f89a547b 100644 --- a/tests/out/msl/interpolate.msl +++ b/tests/out/msl/interpolate.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 42f8be358..ee0acbca8 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 7fa931624..eebd1e73b 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index 06ed990be..893c700ca 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include @@ -34,7 +34,7 @@ metal::float4 mock_function( metal::int2 c, int i, int l, - constant InStorage& in_storage, + device InStorage& in_storage, constant InUniform& in_uniform, metal::texture2d_array image_2d_array, threadgroup type_5 const& in_workgroup, diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index de1bfb598..87114a8d7 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl index a99532b12..a03d61bf5 100644 --- a/tests/out/msl/quad.msl +++ b/tests/out/msl/quad.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 54e918de4..d4868235a 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include @@ -46,7 +46,7 @@ struct fs_mainOutput { fragment fs_mainOutput fs_main( fs_mainInput varyings [[stage_in]] , constant Globals& u_globals [[user(fake0)]] -, constant Lights& s_lights [[user(fake0)]] +, device Lights& s_lights [[user(fake0)]] , metal::depth2d_array t_shadow [[user(fake0)]] , metal::sampler sampler_shadow [[user(fake0)]] ) { diff --git a/tests/out/msl/standard.msl b/tests/out/msl/standard.msl index cf7adc7d6..016425237 100644 --- a/tests/out/msl/standard.msl +++ b/tests/out/msl/standard.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include diff --git a/tests/out/msl/texture-arg.msl b/tests/out/msl/texture-arg.msl index 49533df9e..20e76207d 100644 --- a/tests/out/msl/texture-arg.msl +++ b/tests/out/msl/texture-arg.msl @@ -1,4 +1,4 @@ -// language: metal1.1 +// language: metal2.0 #include #include From 42bf3545c915670bd4515289de55d2b2dd7bba04 Mon Sep 17 00:00:00 2001 From: Noel Tautges Date: Thu, 3 Feb 2022 12:27:21 -0600 Subject: [PATCH 1566/2212] Standardize some docs (#1660) * Rewrite front/back doc summaries - Use line comments instead of block comments - Standardize language for each front/backend - Add reference link for each format - Minor punctuation changes * Add documentation for keywords module * Clarify contents of keywords module in summary * Refer to modules by their type name * Add basic summary for valid module * Adjust EarlyDepthTest and ConservativeDepth docs * Remove "in" from list * Adjust wording * Standardize format of docstrings * Adjust module links to be consistent with other links * Add summary for reserved keywords list * Remove extraneous doc spaces with `cargo fmt` * Correct spelling of whether and rewrite some lines * Fill out GLSL backend docs * Remove unnecessary link targets * Fill out DOT backend docs * Change module line comments to block comments * Remove unnecessary spaces * Fix mistake during rebasing --- cli/src/main.rs | 2 +- src/back/dot/mod.rs | 14 ++-- src/back/glsl/features.rs | 35 +++++---- src/back/glsl/mod.rs | 152 +++++++++++++++++++----------------- src/back/hlsl/help.rs | 52 ++++++------ src/back/hlsl/keywords.rs | 9 ++- src/back/hlsl/mod.rs | 51 ++++++------ src/back/hlsl/storage.rs | 8 +- src/back/mod.rs | 8 +- src/back/msl/mod.rs | 10 ++- src/back/spv/block.rs | 4 +- src/back/spv/image.rs | 4 +- src/back/spv/index.rs | 4 +- src/back/spv/mod.rs | 16 ++-- src/back/spv/recyclable.rs | 4 +- src/back/spv/selection.rs | 114 ++++++++++++++------------- src/back/wgsl/mod.rs | 6 ++ src/front/glsl/ast.rs | 14 ++-- src/front/glsl/error.rs | 20 ++--- src/front/glsl/mod.rs | 36 +++++---- src/front/glsl/offset.rs | 23 +++--- src/front/glsl/token.rs | 2 +- src/front/glsl/variables.rs | 10 +-- src/front/interpolator.rs | 4 +- src/front/mod.rs | 4 +- src/front/spv/mod.rs | 7 +- src/front/wgsl/mod.rs | 8 +- src/keywords/mod.rs | 4 + src/keywords/wgsl.rs | 7 ++ src/lib.rs | 37 +++++---- src/proc/index.rs | 4 +- src/proc/mod.rs | 4 +- src/span.rs | 2 +- src/valid/mod.rs | 4 + tests/spirv-capabilities.rs | 4 +- tests/wgsl-errors.rs | 4 +- 36 files changed, 393 insertions(+), 298 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 76f950e48..2f88e7feb 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -3,7 +3,7 @@ use std::fs; use std::{error::Error, fmt, io::Read, path::Path, str::FromStr}; -/// Translate shaders to different formats +/// Translate shaders to different formats. #[derive(argh::FromArgs, Debug, Clone)] struct Args { /// bitmask of the ValidationFlags to be used, use 0 to disable validation diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index b60c29990..f24d67df7 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -1,8 +1,11 @@ -/*! GraphViz (DOT) backend - * - * This backend writes a graph in the DOT format, for the ease - * of IR inspection and debugging. -!*/ +/*! +Backend for [DOT][dot] (Graphviz). + +This backend writes a graph in the DOT language, for the ease +of IR inspection and debugging. + +[dot]: https://graphviz.org/doc/info/lang.html +*/ use crate::{ arena::Handle, @@ -470,6 +473,7 @@ fn write_fun( Ok(()) } +/// Write shader module to a [`String`]. pub fn write(module: &crate::Module, mod_info: Option<&ModuleInfo>) -> Result { use std::fmt::Write as _; diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 3c454f168..cde597727 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -6,56 +6,57 @@ use crate::{ use std::fmt::Write; bitflags::bitflags! { - /// Structure used to encode a set of additions to glsl that aren't supported by all versions + /// Structure used to encode additions to GLSL that aren't supported by all versions. pub struct Features: u32 { - /// Buffer address space support + /// Buffer address space support. const BUFFER_STORAGE = 1; const ARRAY_OF_ARRAYS = 1 << 1; - /// 8 byte floats + /// 8 byte floats. const DOUBLE_TYPE = 1 << 2; - /// Includes support for more image formats + /// More image formats. const FULL_IMAGE_FORMATS = 1 << 3; const MULTISAMPLED_TEXTURES = 1 << 4; const MULTISAMPLED_TEXTURE_ARRAYS = 1 << 5; const CUBE_TEXTURES_ARRAY = 1 << 6; const COMPUTE_SHADER = 1 << 7; - /// Adds support for image load and early depth tests + /// Image load and early depth tests. const IMAGE_LOAD_STORE = 1 << 8; const CONSERVATIVE_DEPTH = 1 << 9; - /// Interpolation and auxiliary qualifiers. Perspective, Flat, and - /// Centroid are available in all GLSL versions we support. + /// Interpolation and auxiliary qualifiers. + /// + /// Perspective, Flat, and Centroid are available in all GLSL versions we support. const NOPERSPECTIVE_QUALIFIER = 1 << 11; const SAMPLE_QUALIFIER = 1 << 12; const CLIP_DISTANCE = 1 << 13; const CULL_DISTANCE = 1 << 14; - // Sample ID + /// Sample ID. const SAMPLE_VARIABLES = 1 << 15; - /// Arrays with a dynamic length + /// Arrays with a dynamic length. const DYNAMIC_ARRAY_SIZE = 1 << 16; const MULTI_VIEW = 1 << 17; - /// Adds support for fused multiply-add + /// Fused multiply-add. const FMA = 1 << 18; } } -/// Helper structure used to store the required [`Features`](Features) needed to output a +/// Helper structure used to store the required [`Features`] needed to output a /// [`Module`](crate::Module) /// /// Provides helper methods to check for availability and writing required extensions pub struct FeaturesManager(Features); impl FeaturesManager { - /// Creates a new [`FeaturesManager`](FeaturesManager) instance + /// Creates a new [`FeaturesManager`] instance pub fn new() -> Self { Self(Features::empty()) } - /// Adds to the list of required [`Features`](Features) + /// Adds to the list of required [`Features`] pub fn request(&mut self, features: Features) { self.0 |= features } - /// Checks that all required [`Features`](Features) are available for the specified + /// Checks that all required [`Features`] are available for the specified /// [`Version`](super::Version) otherwise returns an /// [`Error::MissingFeatures`](super::Error::MissingFeatures) pub fn check_availability(&self, version: Version) -> BackendResult { @@ -214,10 +215,10 @@ impl FeaturesManager { } impl<'a, W> Writer<'a, W> { - /// Helper method that searches the module for all the needed [`Features`](Features) + /// Helper method that searches the module for all the needed [`Features`] /// /// # Errors - /// If the version doesn't support any of the needed [`Features`](Features) a + /// If the version doesn't support any of the needed [`Features`] a /// [`Error::MissingFeatures`](super::Error::MissingFeatures) will be returned pub(super) fn collect_required_features(&mut self) -> BackendResult { let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); @@ -386,7 +387,7 @@ impl<'a, W> Writer<'a, W> { self.features.check_availability(self.options.version) } - /// Helper method that checks the [`Features`](Features) needed by a scalar + /// Helper method that checks the [`Features`] needed by a scalar fn scalar_required_features(&mut self, kind: ScalarKind, width: Bytes) { if kind == ScalarKind::Float && width == 8 { self.features.request(Features::DOUBLE_TYPE); diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 550fafc3b..7c4e1d7df 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1,22 +1,25 @@ -//! OpenGL shading language backend -//! -//! The main structure is [`Writer`](Writer), it maintains internal state that is used -//! to output a [`Module`](crate::Module) into glsl -//! -//! # Supported versions -//! ### Core -//! - 330 -//! - 400 -//! - 410 -//! - 420 -//! - 430 -//! - 450 -//! - 460 -//! -//! ### ES -//! - 300 -//! - 310 -//! +/*! +Backend for [GLSL][glsl] (OpenGL Shading Language). + +The main structure is [`Writer`], it maintains internal state that is used +to output a [`Module`](crate::Module) into glsl + +# Supported versions +### Core +- 330 +- 400 +- 410 +- 420 +- 430 +- 450 +- 460 + +### ES +- 300 +- 310 + +[glsl]: https://www.khronos.org/registry/OpenGL/index_gl.php +*/ // GLSL is mostly a superset of C but it also removes some parts of it this is a list of relevant // aspects for this backend. @@ -33,7 +36,7 @@ // `#extension name: behaviour` // Extensions provide increased features in a plugin fashion but they aren't required to be // supported hence why they are called extensions, that's why `behaviour` is used it specifies -// wether the extension is strictly required or if it should only be enabled if needed. In our case +// whether the extension is strictly required or if it should only be enabled if needed. In our case // when we use extensions we set behaviour to `require` always. // // The only thing that glsl removes that makes a difference are pointers. @@ -61,11 +64,12 @@ mod features; /// Contains a constant with a slice of all the reserved keywords RESERVED_KEYWORDS mod keywords; -/// List of supported core glsl versions +/// List of supported `core` GLSL versions. pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; -/// List of supported es glsl versions +/// List of supported `es` GLSL versions. pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; +/// Mapping between resources and bindings. pub type BindingMap = std::collections::BTreeMap; impl crate::AtomicFunction { @@ -130,14 +134,14 @@ impl<'a> GlobalTypeKind<'a> { } } -/// glsl version +/// A GLSL version. #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum Version { - /// `core` glsl + /// `core` GLSL. Desktop(u16), - /// `es` glsl + /// `es` GLSL. Embedded(u16), } @@ -206,10 +210,11 @@ impl fmt::Display for Version { } bitflags::bitflags! { + /// Configuration flags for the [`Writer`]. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct WriterFlags: u32 { - /// Flip output Y and extend Z from (0,1) to (-1,1). + /// Flip output Y and extend Z from (0, 1) to (-1, 1). const ADJUST_COORDINATE_SPACE = 0x1; /// Supports GL_EXT_texture_shadow_lod on the host, which provides /// additional functions on shadows and arrays of shadows. @@ -217,14 +222,14 @@ bitflags::bitflags! { } } -/// Structure that contains the configuration used in the [`Writer`](Writer) +/// Configuration used in the [`Writer`]. #[derive(Debug, Clone)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Options { - /// The glsl version to be used + /// The GLSL version to be used. pub version: Version, - /// Configuration flags for the writer. + /// Configuration flags for the [`Writer`]. pub writer_flags: WriterFlags, /// Map of resources association to binding locations. pub binding_map: BindingMap, @@ -240,40 +245,41 @@ impl Default for Options { } } -// A subset of options that are meant to be changed per pipeline. +/// A subset of options meant to be changed per pipeline. #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct PipelineOptions { - /// The stage of the entry point + /// The stage of the entry point. pub shader_stage: ShaderStage, - /// The name of the entry point + /// The name of the entry point. /// - /// If no entry point that matches is found a error will be thrown while creating a new instance - /// of [`Writer`](struct.Writer.html) + /// If no entry point that matches is found while creating a [`Writer`], a error will be thrown. pub entry_point: String, } -/// Structure that contains a reflection info +/// Reflection info for texture mappings and uniforms. pub struct ReflectionInfo { + /// Mapping between texture names and variables/samplers. pub texture_mapping: crate::FastHashMap, + /// Mapping between uniform variables and names. pub uniforms: crate::FastHashMap, String>, } -/// Structure that connects a texture to a sampler or not +/// Mapping between a texture and its sampler, if it exists. /// -/// glsl pre vulkan has no concept of separate textures and samplers instead everything is a -/// `gsamplerN` where `g` is the scalar type and `N` is the dimension, but naga uses separate textures -/// and samplers in the IR so the backend produces a [`HashMap`](crate::FastHashMap) with the texture name -/// as a key and a [`TextureMapping`](TextureMapping) as a value this way the user knows where to bind. +/// GLSL pre-Vulkan has no concept of separate textures and samplers. Instead, everything is a +/// `gsamplerN` where `g` is the scalar type and `N` is the dimension. But naga uses separate textures +/// and samplers in the IR, so the backend produces a [`FastHashMap`](crate::FastHashMap) with the texture name +/// as a key and a [`TextureMapping`] as a value. This way, the user knows where to bind. /// -/// [`Storage`](crate::ImageClass::Storage) images produce `gimageN` and don't have an associated sampler -/// so the [`sampler`](Self::sampler) field will be [`None`](std::option::Option::None) +/// [`Storage`](crate::ImageClass::Storage) images produce `gimageN` and don't have an associated sampler, +/// so the [`sampler`](Self::sampler) field will be [`None`]. #[derive(Debug, Clone)] pub struct TextureMapping { - /// Handle to the image global variable + /// Handle to the image global variable. pub texture: Handle, - /// Handle to the associated sampler global variable if it exists + /// Handle to the associated sampler global variable, if it exists. pub sampler: Option>, } @@ -338,88 +344,88 @@ impl ShaderStage { /// Shorthand result used internally by the backend type BackendResult = Result; -/// A glsl compilation error. +/// A GLSL compilation error. #[derive(Debug, Error)] pub enum Error { - /// A error occurred while writing to the output + /// A error occurred while writing to the output. #[error("Format error")] FmtError(#[from] FmtError), - /// The specified [`Version`](Version) doesn't have all required [`Features`](super) + /// The specified [`Version`] doesn't have all required [`Features`]. /// - /// Contains the missing [`Features`](Features) + /// Contains the missing [`Features`]. #[error("The selected version doesn't support {0:?}")] MissingFeatures(Features), /// [`AddressSpace::PushConstant`](crate::AddressSpace::PushConstant) was used more than - /// once in the entry point which isn't supported + /// once in the entry point, which isn't supported. #[error("Multiple push constants aren't supported")] MultiplePushConstants, - /// The specified [`Version`](Version) isn't supported + /// The specified [`Version`] isn't supported. #[error("The specified version isn't supported")] VersionNotSupported, - /// The entry point couldn't be found + /// The entry point couldn't be found. #[error("The requested entry point couldn't be found")] EntryPointNotFound, - /// A call was made to an unsupported external + /// A call was made to an unsupported external. #[error("A call was made to an unsupported external: {0}")] UnsupportedExternal(String), - /// A scalar with an unsupported width was requested + /// A scalar with an unsupported width was requested. #[error("A scalar with an unsupported width was requested: {0:?} {1:?}")] UnsupportedScalar(crate::ScalarKind, crate::Bytes), - /// A image was used with multiple samplers, this isn't supported + /// A image was used with multiple samplers, which isn't supported. #[error("A image was used with multiple samplers")] ImageMultipleSamplers, #[error("{0}")] Custom(String), } -/// Binary operation with a different logic on the GLSL side +/// Binary operation with a different logic on the GLSL side. enum BinaryOperation { /// Vector comparison should use the function like `greaterThan()`, etc. VectorCompare, - /// GLSL `%` is SPIR-V `OpUMod/OpSMod` and `mod()` is `OpFMod`, but [`BinaryOperator::Modulo`](crate::BinaryOperator::Modulo) is `OpFRem` + /// GLSL `%` is SPIR-V `OpUMod/OpSMod` and `mod()` is `OpFMod`, but [`BinaryOperator::Modulo`](crate::BinaryOperator::Modulo) is `OpFRem`. Modulo, - /// Any plain operation. No additional logic required + /// Any plain operation. No additional logic required. Other, } -/// Main structure of the glsl backend responsible for all code generation +/// Writer responsible for all code generation. pub struct Writer<'a, W> { // Inputs - /// The module being written + /// The module being written. module: &'a crate::Module, /// The module analysis. info: &'a valid::ModuleInfo, - /// The output writer + /// The output writer. out: W, - /// User defined configuration to be used + /// User defined configuration to be used. options: &'a Options, // Internal State - /// Features manager used to store all the needed features and write them + /// Features manager used to store all the needed features and write them. features: FeaturesManager, namer: proc::Namer, /// A map with all the names needed for writing the module - /// (generated by a [`Namer`](crate::proc::Namer)) + /// (generated by a [`Namer`](crate::proc::Namer)). names: crate::FastHashMap, - /// A map with the names of global variables needed for reflections + /// A map with the names of global variables needed for reflections. reflection_names_globals: crate::FastHashMap, String>, - /// The selected entry point + /// The selected entry point. entry_point: &'a crate::EntryPoint, - /// The index of the selected entry point + /// The index of the selected entry point. entry_point_idx: proc::EntryPointIndex, - /// Used to generate a unique number for blocks + /// A generator for unique block numbers. block_id: IdGenerator, - /// Set of expressions that have associated temporary variables + /// Set of expressions that have associated temporary variables. named_expressions: crate::NamedExpressions, } impl<'a, W: Write> Writer<'a, W> { - /// Creates a new [`Writer`](Writer) instance + /// Creates a new [`Writer`] instance. /// /// # Errors - /// - If the version specified isn't supported (or invalid) - /// - If the entry point couldn't be found on the module - /// - If the version specified doesn't support some used features + /// - If the version specified is invalid or supported. + /// - If the entry point couldn't be found in the module. + /// - If the version specified doesn't support some used features. pub fn new( out: W, module: &'a crate::Module, @@ -1988,7 +1994,7 @@ impl<'a, W: Write> Writer<'a, W> { Expression::Load { pointer } => self.write_expr(pointer, ctx)?, // `ImageSample` is a bit complicated compared to the rest of the IR. // - // First there are three variations depending wether the sample level is explicitly set, + // First there are three variations depending whether the sample level is explicitly set, // if it's automatic or it it's bias: // `texture(image, coordinate)` - Automatic sample level // `texture(image, coordinate, bias)` - Bias sample level diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 01dbb33e7..8c4b31e80 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -1,28 +1,30 @@ -//! Helpers for the hlsl backend -//! -//! Important note about `Expression::ImageQuery`/`Expression::ArrayLength` and hlsl backend: -//! -//! Due to implementation of `GetDimensions` function in hlsl () -//! backend can't work with it as an expression. -//! Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texure info and query function. -//! See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions. -//! This allowed to works with `Expression::ImageQuery` as expression and write wrapped function. -//! -//! For example: -//! ```wgsl -//! let dim_1d = textureDimensions(image_1d); -//! ``` -//! -//! ```hlsl -//! int NagaDimensions1D(Texture1D) -//! { -//! uint4 ret; -//! image_1d.GetDimensions(ret.x); -//! return ret.x; -//! } -//! -//! int dim_1d = NagaDimensions1D(image_1d); -//! ``` +/*! +Helpers for the hlsl backend + +Important note about `Expression::ImageQuery`/`Expression::ArrayLength` and hlsl backend: + +Due to implementation of `GetDimensions` function in hlsl () +backend can't work with it as an expression. +Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texure info and query function. +See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions. +This allowed to works with `Expression::ImageQuery` as expression and write wrapped function. + +For example: +```wgsl +let dim_1d = textureDimensions(image_1d); +``` + +```hlsl +int NagaDimensions1D(Texture1D) +{ + uint4 ret; + image_1d.GetDimensions(ret.x); + return ret.x; +} + +int dim_1d = NagaDimensions1D(image_1d); +``` +*/ use super::{super::FunctionCtx, BackendResult, Error}; use crate::{arena::Handle, proc::NameKey}; diff --git a/src/back/hlsl/keywords.rs b/src/back/hlsl/keywords.rs index e322c98af..7519b767a 100644 --- a/src/back/hlsl/keywords.rs +++ b/src/back/hlsl/keywords.rs @@ -1,6 +1,9 @@ -//! HLSL Reserved Words -//! - -//! - +/*! +HLSL Reserved Words +- +- +*/ + pub const RESERVED: &[&str] = &[ "AppendStructuredBuffer", "asm", diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 693b00182..6f6339d43 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -1,21 +1,25 @@ -//! HLSL shading language backend -//! -//! # Supported shader model versions: -//! - 5.0 -//! - 5.1 -//! - 6.0 -//! -//! All matrix construction/deconstruction is row based in HLSL. This means that when -//! we construct a matrix from column vectors, our matrix will be implicitly transposed. -//! The inverse transposition happens when we call `[0]` to get the zeroth column vector. -//! -//! Because all of our matrices are implicitly transposed, we flip arguments to `mul`. `mat * vec` -//! becomes `vec * mat`, etc. This acts as the inverse transpose making the results identical. -//! -//! The only time we don't get this implicit transposition is when reading matrices from Uniforms/Push Constants. -//! To deal with this, we add `row_major` to all declarations of matrices in Uniforms/Push Constants. -//! -//! Finally because all of our matrices are transposed, if you use `mat3x4`, it'll become `float4x3` in HLSL. +/*! +Backend for [HLSL][hlsl] (High-Level Shading Language). + +# Supported shader model versions: +- 5.0 +- 5.1 +- 6.0 + +All matrix construction/deconstruction is row based in HLSL. This means that when +we construct a matrix from column vectors, our matrix will be implicitly transposed. +The inverse transposition happens when we call `[0]` to get the zeroth column vector. + +Because all of our matrices are implicitly transposed, we flip arguments to `mul`. `mat * vec` +becomes `vec * mat`, etc. This acts as the inverse transpose making the results identical. + +The only time we don't get this implicit transposition is when reading matrices from Uniforms/Push Constants. +To deal with this, we add `row_major` to all declarations of matrices in Uniforms/Push Constants. + +Finally because all of our matrices are transposed, if you use `mat3x4`, it'll become `float4x3` in HLSL. + +[hlsl]: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl +*/ mod conv; mod help; @@ -92,7 +96,7 @@ pub enum EntryPointError { MissingBinding(crate::ResourceBinding), } -/// Structure that contains the configuration used in the [`Writer`](Writer) +/// Configuration used in the [`Writer`]. #[derive(Clone, Debug, Hash, PartialEq, Eq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] @@ -135,14 +139,15 @@ impl Options { } } -/// Structure that contains a reflection info +/// Reflection info for entry point names. #[derive(Default)] pub struct ReflectionInfo { - /// Mapping of the entry point names. Each item in the array - /// corresponds to an entry point index. The real entry point name may be different if one of the + /// Mapping of the entry point names. + /// + /// Each item in the array corresponds to an entry point index. The real entry point name may be different if one of the /// reserved words are used. /// - ///Note: Some entry points may fail translation because of missing bindings. + /// Note: Some entry points may fail translation because of missing bindings. pub entry_point_names: Vec>, } diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index a66f3e139..4abe66350 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -1,6 +1,8 @@ -//! Logic related to `ByteAddressBuffer` operations. -//! -//! HLSL backend uses byte address buffers for all storage buffers in IR. +/*! +Logic related to `ByteAddressBuffer` operations. + +HLSL backend uses byte address buffers for all storage buffers in IR. +*/ use super::{super::FunctionCtx, BackendResult, Error}; use crate::{ diff --git a/src/back/mod.rs b/src/back/mod.rs index 571289a79..d69c0463c 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -1,4 +1,6 @@ -//! Functions which export shader modules into binary and text formats. +/*! +Backend functions that export shader [`Module`](super::Module)s into binary and text formats. +*/ #[cfg(feature = "dot-out")] pub mod dot; @@ -202,9 +204,9 @@ impl crate::TypeInner { } impl crate::Statement { - /// Returns true if the statement directly terminates the current block + /// Returns true if the statement directly terminates the current block. /// - /// Used to decided wether case blocks require a explicit `break` + /// Used to decide whether case blocks require a explicit `break`. pub fn is_terminator(&self) -> bool { match *self { crate::Statement::Break diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index b886d1573..0a95e8cf9 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -1,4 +1,5 @@ -/*! Metal Shading Language (MSL) backend +/*! +Backend for [MSL][msl] (Metal Shading Language). ## Binding model @@ -21,7 +22,9 @@ pretend that MSL doesn't have all the restrictions it has. For the result type, if it's a structure, we re-compose it with a temporary value holding the result. -!*/ + +[msl]: https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf +*/ use crate::{arena::Handle, proc::index, valid::ModuleInfo}; use std::{ @@ -197,12 +200,13 @@ impl Default for Options { } } -// A subset of options that are meant to be changed per pipeline. +/// A subset of options that are meant to be changed per pipeline. #[derive(Debug, Default, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct PipelineOptions { /// Allow `BuiltIn::PointSize` in the vertex shader. + /// /// Metal doesn't like this for non-point primitive topologies. pub allow_point_size: bool, } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index a31525f4c..ab33acfc8 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1,4 +1,6 @@ -//! Implementations for `BlockContext` methods. +/*! +Implementations for `BlockContext` methods. +*/ use super::{ index::BoundsCheckResult, make_local, selection::Selection, Block, BlockContext, Dimension, diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 31e37a77c..bbfdf5c5b 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -1,4 +1,6 @@ -//! Generating SPIR-V for image operations. +/*! +Generating SPIR-V for image operations. +*/ use super::{ selection::{MergeTuple, Selection}, diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 8edde1f5f..c8f16e83a 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -1,4 +1,6 @@ -//! Bounds-checking for SPIR-V output. +/*! +Bounds-checking for SPIR-V output. +*/ use super::{selection::Selection, Block, BlockContext, Error, IdGenerator, Instruction, Word}; use crate::{arena::Handle, proc::BoundsCheckPolicy}; diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index ba4875d81..0d03527d6 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -1,5 +1,8 @@ -/*! Standard Portable Intermediate Representation (SPIR-V) backend -!*/ +/*! +Backend for [SPIR-V][spv] (Standard Portable Intermediate Representation). + +[spv]: https://www.khronos.org/registry/SPIR-V/ +*/ mod block; mod helpers; @@ -627,17 +630,16 @@ impl Default for Options { } } -// A subset of options that are meant to be changed per pipeline. +// A subset of options meant to be changed per pipeline. #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct PipelineOptions { - /// The stage of the entry point + /// The stage of the entry point. pub shader_stage: crate::ShaderStage, - /// The name of the entry point + /// The name of the entry point. /// - /// If no entry point that matches is found a error will be thrown while creating a new instance - /// of [`Writer`](struct.Writer.html) + /// If no entry point that matches is found while creating a [`Writer`], a error will be thrown. pub entry_point: String, } diff --git a/src/back/spv/recyclable.rs b/src/back/spv/recyclable.rs index e8813497f..6cedcd078 100644 --- a/src/back/spv/recyclable.rs +++ b/src/back/spv/recyclable.rs @@ -1,4 +1,6 @@ -//! Reusing collections' previous allocations. +/*! +Reusing collections' previous allocations. +*/ /// A value that can be reset to its initial state, retaining its current allocations. /// diff --git a/src/back/spv/selection.rs b/src/back/spv/selection.rs index 5922dedde..788b1f10a 100644 --- a/src/back/spv/selection.rs +++ b/src/back/spv/selection.rs @@ -1,59 +1,61 @@ -//! Generate SPIR-V conditional structures. -//! -//! Builders for `if` structures with `and`s. -//! -//! The types in this module track the information needed to emit SPIR-V code -//! for complex conditional structures, like those whose conditions involve -//! short-circuiting 'and' and 'or' structures. These track labels and can emit -//! `OpPhi` instructions to merge values produced along different paths. -//! -//! This currently only supports exactly the forms Naga uses, so it doesn't -//! support `or` or `else`, and only supports zero or one merged values. -//! -//! Naga needs to emit code roughly like this: -//! -//! ```ignore -//! -//! value = DEFAULT; -//! if COND1 && COND2 { -//! value = THEN_VALUE; -//! } -//! // use value -//! -//! ``` -//! -//! Assuming `ctx` and `block` are a mutable references to a [`BlockContext`] -//! and the current [`Block`], and `merge_type` is the SPIR-V type for the -//! merged value `value`, we can build SPIR-V for the code above like so: -//! -//! ```ignore -//! -//! let cond = Selection::start(block, merge_type); -//! // ... compute `cond1` ... -//! cond.if_true(ctx, cond1, DEFAULT); -//! // ... compute `cond2` ... -//! cond.if_true(ctx, cond2, DEFAULT); -//! // ... compute THEN_VALUE -//! let merged_value = cond.finish(ctx, THEN_VALUE); -//! -//! ``` -//! -//! After this, `merged_value` is either `DEFAULT` or `THEN_VALUE`, depending on -//! the path by which the merged block was reached. -//! -//! This takes care of writing all branch instructions, including an -//! `OpSelectionMerge` annotation in the header block; starting new blocks and -//! assigning them labels; and emitting the `OpPhi` that gathers together the -//! right sources for the merged values, for every path through the selection -//! construct. -//! -//! When there is no merged value to produce, you can pass `()` for `merge_type` -//! and the merge values. In this case no `OpPhi` instructions are produced, and -//! the `finish` method returns `()`. -//! -//! To enforce proper nesting, a `Selection` takes ownership of the `&mut Block` -//! pointer for the duration of its lifetime. To obtain the block for generating -//! code in the selection's body, call the `Selection::block` method. +/*! +Generate SPIR-V conditional structures. + +Builders for `if` structures with `and`s. + +The types in this module track the information needed to emit SPIR-V code +for complex conditional structures, like those whose conditions involve +short-circuiting 'and' and 'or' structures. These track labels and can emit +`OpPhi` instructions to merge values produced along different paths. + +This currently only supports exactly the forms Naga uses, so it doesn't +support `or` or `else`, and only supports zero or one merged values. + +Naga needs to emit code roughly like this: + +```ignore + + value = DEFAULT; + if COND1 && COND2 { + value = THEN_VALUE; + } + // use value + +``` + +Assuming `ctx` and `block` are a mutable references to a [`BlockContext`] +and the current [`Block`], and `merge_type` is the SPIR-V type for the +merged value `value`, we can build SPIR-V for the code above like so: + +```ignore + + let cond = Selection::start(block, merge_type); + // ... compute `cond1` ... + cond.if_true(ctx, cond1, DEFAULT); + // ... compute `cond2` ... + cond.if_true(ctx, cond2, DEFAULT); + // ... compute THEN_VALUE + let merged_value = cond.finish(ctx, THEN_VALUE); + +``` + +After this, `merged_value` is either `DEFAULT` or `THEN_VALUE`, depending on +the path by which the merged block was reached. + +This takes care of writing all branch instructions, including an +`OpSelectionMerge` annotation in the header block; starting new blocks and +assigning them labels; and emitting the `OpPhi` that gathers together the +right sources for the merged values, for every path through the selection +construct. + +When there is no merged value to produce, you can pass `()` for `merge_type` +and the merge values. In this case no `OpPhi` instructions are produced, and +the `finish` method returns `()`. + +To enforce proper nesting, a `Selection` takes ownership of the `&mut Block` +pointer for the duration of its lifetime. To obtain the block for generating +code in the selection's body, call the `Selection::block` method. +*/ use super::{Block, BlockContext, Instruction}; use spirv::Word; diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index b934662e1..0a705691c 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -1,3 +1,9 @@ +/*! +Backend for [WGSL][wgsl] (WebGPU Shading Language). + +[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html +*/ + mod writer; use thiserror::Error; diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index d269698b9..2594a76e8 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -23,8 +23,8 @@ pub struct GlobalLookup { #[derive(Debug, Clone)] pub struct ParameterInfo { pub qualifier: ParameterQualifier, - /// Wether the parameter should be treated as a depth image instead of a - /// sampled image + /// Whether the parameter should be treated as a depth image instead of a + /// sampled image. pub depth: bool, } @@ -62,10 +62,10 @@ pub struct Overload { #[derive(Debug, Default)] pub struct FunctionDeclaration { pub overloads: Vec, - /// Wether or not this function has the name of a builtin + /// Whether or not this function has the name of a builtin. pub builtin: bool, - /// In case [`builtin`](Self::builtin) is true, this field indicates wether - /// this function already has double overloads added or not, otherwise is unused + /// If [`builtin`](Self::builtin) is true, this field indicates whether + /// this function already has double overloads added or not. Otherwise, it is unused. pub double: bool, } @@ -176,7 +176,7 @@ pub enum StructLayout { } // TODO: Encode precision hints in the IR -/// A precision hint used in glsl declarations +/// A precision hint used in GLSL declarations. /// /// Precision hints can be used to either speed up shader execution or control /// the precision of arithmetic operations. @@ -229,7 +229,7 @@ impl ParameterQualifier { } } -/// The glsl profile used by a shader +/// The GLSL profile used by a shader. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Profile { /// The `core` profile, default when no profile is specified. diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 132a4208f..a06d3bfe0 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -17,22 +17,22 @@ fn join_with_comma(list: &[ExpectedToken]) -> String { string } -/// One of the expected tokens returned in [`InvalidToken`](ErrorKind::InvalidToken) +/// One of the expected tokens returned in [`InvalidToken`](ErrorKind::InvalidToken). #[derive(Debug, PartialEq)] pub enum ExpectedToken { - /// A specific token was expected + /// A specific token was expected. Token(TokenValue), - /// A type was expected + /// A type was expected. TypeName, - /// An identifier was expected + /// An identifier was expected. Identifier, - /// An integer literal was expected + /// An integer literal was expected. IntLiteral, - /// A float literal was expected + /// A float literal was expected. FloatLiteral, - /// A boolean literal was expected + /// A boolean literal was expected. BoolLiteral, - /// The end of file was expected + /// The end of file was expected. Eof, } impl From for ExpectedToken { @@ -54,7 +54,7 @@ impl std::fmt::Display for ExpectedToken { } } -/// Information about the cause of an error +/// Information about the cause of an error. #[derive(Debug, Error)] #[cfg_attr(test, derive(PartialEq))] pub enum ErrorKind { @@ -112,7 +112,7 @@ impl From for ErrorKind { } } -/// Error returned during shader parsing +/// Error returned during shader parsing. #[derive(Debug, Error)] #[error("{kind}")] #[cfg_attr(test, derive(PartialEq))] diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 0712f4bd5..ee5d68ded 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,10 +1,16 @@ -//! Front end for consuming the OpenGl Shading language (GLSL). -//! -//! To begin take a look at the documentation for the [`Parser`](Parser). -//! -//! # Supported versions -//! Currently only the versions 450 and 460 are supported and 440 is partially -//! supported, furthermore the vulkan flavor is assumed. +/*! +Frontend for [GLSL][glsl] (OpenGL Shading Language). + +To begin, take a look at the documentation for the [`Parser`](Parser). + +# Supported versions +## Vulkan +- 440 (partial) +- 450 +- 460 + +[glsl]: https://www.khronos.org/registry/OpenGL/index_gl.php +*/ pub use ast::{Precision, Profile}; pub use error::{Error, ErrorKind, ExpectedToken}; @@ -31,7 +37,7 @@ mod variables; type Result = std::result::Result; -/// Per shader options passed to [`parse`](Parser::parse) +/// Per-shader options passed to [`parse`](Parser::parse). /// /// The [`From`](From) trait is implemented for [`ShaderStage`](ShaderStage) to /// provide a quick way to create a Options instance. @@ -61,16 +67,16 @@ impl From for Options { } } -/// Additional information about the glsl shader +/// Additional information about the GLSL shader. /// -/// Stores additional information about the glsl shader which might not be +/// Stores additional information about the GLSL shader which might not be /// stored in the shader [`Module`](Module). #[derive(Debug)] pub struct ShaderMetadata { - /// The glsl version specified in the shader trought the use of the + /// The GLSL version specified in the shader trought the use of the /// `#version` preprocessor directive. pub version: u16, - /// The glsl profile specified in the shader trought the use of the + /// The GLSL profile specified in the shader trought the use of the /// `#version` preprocessor directive. pub profile: Profile, /// The shader stage in the pipeline, passed to the [`parse`](Parser::parse) @@ -80,8 +86,8 @@ pub struct ShaderMetadata { /// The workgroup size for compute shaders, defaults to `[1; 3]` for /// compute shaders and `[0; 3]` for non compute shaders. pub workgroup_size: [u32; 3], - /// Wether or not early fragment tests where requested by the shader, - /// defaults to `false`. + /// Whether or not early fragment tests where requested by the shader. + /// Defaults to `false`. pub early_fragment_tests: bool, /// The shader can request extensions via the @@ -118,7 +124,7 @@ impl Default for ShaderMetadata { } } -/// The `Parser` is the central structure of the glsl frontend. +/// The `Parser` is the central structure of the GLSL frontend. /// /// To instantiate a new `Parser` the [`Default`](Default) trait is used, so a /// call to the associated function [`Parser::default`](Parser::default) will diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index dd8ecbfea..56ee4ab14 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -1,13 +1,16 @@ -//! Module responsible for calculating the offset and span for types. -//! -//! There exists two types of layouts std140 and std430 (there's technically -//! two more layouts, shared and packed. Shared is not supported by spirv. Packed is -//! implementation dependent and for now it's just implemented as an alias to -//! std140). -//! -//! The OpenGl spec (the layout rules are defined by the OpenGl spec in section -//! 7.6.2.2 as opposed to the GLSL spec) uses the term basic machine units which are -//! equivalent to bytes. +/*! +Module responsible for calculating the offset and span for types. + +There exists two types of layouts std140 and std430 (there's technically +two more layouts, shared and packed. Shared is not supported by spirv. Packed is +implementation dependent and for now it's just implemented as an alias to +std140). + +The OpenGl spec (the layout rules are defined by the OpenGl spec in section +7.6.2.2 as opposed to the GLSL spec) uses the term basic machine units which are +equivalent to bytes. +*/ + use super::{ ast::StructLayout, error::{Error, ErrorKind}, diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index 148f105a1..e522f3f16 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -16,7 +16,7 @@ pub struct Token { pub meta: Span, } -/// A token passed from the lexing used in the parsing +/// A token passed from the lexing used in the parsing. /// /// This type is exported since it's returned in the /// [`InvalidToken`](super::ErrorKind::InvalidToken) error. diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 482a01b84..0cb11bcef 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -31,15 +31,15 @@ pub struct VarDeclaration<'a> { pub meta: Span, } -/// Information about a builtin used in [`add_builtin`](Parser::add_builtin) +/// Information about a builtin used in [`add_builtin`](Parser::add_builtin). struct BuiltInData { - /// The type of the builtin + /// The type of the builtin. inner: TypeInner, - /// The builtin class associated with + /// The associated builtin class. builtin: BuiltIn, - /// Wether it should be allowed to write to the builtin or not + /// Whether the builtin can be written to or not. mutable: bool, - /// The storage used for the builtin + /// The storage used for the builtin. storage: StorageQualifier, } diff --git a/src/front/interpolator.rs b/src/front/interpolator.rs index 491ca5a0b..0482d75a0 100644 --- a/src/front/interpolator.rs +++ b/src/front/interpolator.rs @@ -1,4 +1,6 @@ -//! Interpolation defaults. +/*! +Interpolation defaults. +*/ impl crate::Binding { /// Apply the usual default interpolation for `ty` to `binding`. diff --git a/src/front/mod.rs b/src/front/mod.rs index 80dfa87ac..d340dcad4 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -1,4 +1,6 @@ -//! Parsers which load shaders into memory. +/*! +Frontend parsers that consume binary and text shaders and load them into [`Module`](super::Module)s. +*/ mod interpolator; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index ff6df9ba4..893c60cca 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1,4 +1,5 @@ -/*! SPIR-V frontend +/*! +Frontend for [SPIR-V][spv] (Standard Portable Intermediate Representation). ## ID lookups @@ -23,7 +24,9 @@ Instead, we detect when such matrix is accessed in the `OpAccessChain`, and we generate a parallel expression that loads the value, but transposed. This value then gets used instead of `OpLoad` result later on. -!*/ +[spv]: https://www.khronos.org/registry/SPIR-V/ +*/ + mod convert; mod error; mod function; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7745f76c2..1b1cbacb0 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1,6 +1,8 @@ -//! Front end for consuming [WebGPU Shading Language][wgsl]. -//! -//! [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html +/*! +Frontend for [WGSL][wgsl] (WebGPU Shading Language). + +[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html +*/ mod conv; mod lexer; diff --git a/src/keywords/mod.rs b/src/keywords/mod.rs index 4f959bcd0..d54a1704f 100644 --- a/src/keywords/mod.rs +++ b/src/keywords/mod.rs @@ -1,2 +1,6 @@ +/*! +Lists of reserved keywords for each shading language with a [frontend][crate::front] or [backend][crate::back]. +*/ + #[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] pub mod wgsl; diff --git a/src/keywords/wgsl.rs b/src/keywords/wgsl.rs index 16e11ea3d..2ceb88300 100644 --- a/src/keywords/wgsl.rs +++ b/src/keywords/wgsl.rs @@ -1,4 +1,11 @@ +/*! +Reserved keywords for [WGSL][wgsl] (WebGPU Shading Language). + +[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html +*/ + // https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary +/// Reserved keywords. pub const RESERVED: &[&str] = &[ // type-defining keywords "array", diff --git a/src/lib.rs b/src/lib.rs index d75b6185b..f384c6ea1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -182,8 +182,7 @@ tree. [`Validator::validate`]: valid::Validator::validate [`ModuleInfo`]: valid::ModuleInfo - -!*/ +*/ // TODO: use `strip_prefix` instead when Rust 1.45 <= MSRV #![allow( @@ -235,18 +234,23 @@ pub type FastHashSet = rustc_hash::FxHashSet; /// Map of expressions that have associated variable names pub(crate) type NamedExpressions = FastHashMap, String>; -/// Early fragment tests. In a standard situation if a driver determines that it is possible to -/// switch on early depth test it will. Typical situations when early depth test is switched off: -/// - Calling ```discard``` in a shader. +/// Early fragment tests. +/// +/// In a standard situation, if a driver determines that it is possible to switch on early depth test, it will. +/// +/// Typical situations when early depth test is switched off: +/// - Calling `discard` in a shader. /// - Writing to the depth buffer, unless ConservativeDepth is enabled. /// -/// SPIR-V: ExecutionMode EarlyFragmentTests -/// In GLSL: layout(early_fragment_tests) in; -/// HLSL: Attribute earlydepthstencil +/// To use in a shader: +/// - GLSL: `layout(early_fragment_tests) in;` +/// - HLSL: `Attribute earlydepthstencil` +/// - SPIR-V: `ExecutionMode EarlyFragmentTests` /// /// For more, see: /// - /// - +/// - #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] @@ -256,20 +260,22 @@ pub struct EarlyDepthTest { } /// Enables adjusting depth without disabling early Z. /// -/// SPIR-V: ExecutionMode DepthGreater/DepthLess/DepthUnchanged -/// GLSL: layout (depth_) out float gl_FragDepth; -/// - ```depth_any``` option behaves as if the layout qualifier was not present. -/// HLSL: SV_Depth/SV_DepthGreaterEqual/SV_DepthLessEqual +/// To use in a shader: +/// - GLSL: `layout (depth_) out float gl_FragDepth;` +/// - `depth_any` option behaves as if the layout qualifier was not present. +/// - HLSL: `SV_DepthGreaterEqual`/`SV_DepthLessEqual`/`SV_Depth` +/// - SPIR-V: `ExecutionMode Depth` /// /// For more, see: /// - /// - +/// - #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ConservativeDepth { - /// Shader may rewrite depth only with a value greater than calculated; + /// Shader may rewrite depth only with a value greater than calculated. GreaterEqual, /// Shader may rewrite depth smaller than one that would have been written without the modification. @@ -474,7 +480,7 @@ bitflags::bitflags! { } } -// Storage image format. +/// Image storage format. #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] @@ -1333,7 +1339,7 @@ pub enum Expression { pub use block::Block; -/// The value of the switch case +/// The value of the switch case. // Clone is used only for error reporting and is not intended for end users #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -1521,6 +1527,7 @@ pub struct FunctionArgument { pub binding: Option, } +/// A function result. #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] diff --git a/src/proc/index.rs b/src/proc/index.rs index c67188745..a7cd94170 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -1,4 +1,6 @@ -//! Definitions for index bounds checking. +/*! +Definitions for index bounds checking. +*/ use crate::{valid, Handle, UniqueArena}; use bit_set::BitSet; diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 8f3fe320a..c62e58776 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,4 +1,6 @@ -//! Module processing functionality. +/*! +[`Module`](super::Module) processing functionality. +*/ pub mod index; mod layouter; diff --git a/src/span.rs b/src/span.rs index 51ea48101..f9fb11113 100644 --- a/src/span.rs +++ b/src/span.rs @@ -55,7 +55,7 @@ impl Span { } } - /// Check wether `self` was defined or is a default/unknown span + /// Check whether `self` was defined or is a default/unknown span pub fn is_defined(&self) -> bool { *self != Self::default() } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 82ead2054..1814b0be0 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -1,3 +1,7 @@ +/*! +Shader validator. +*/ + mod analyzer; mod compose; mod expression; diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs index f7511571d..83df32628 100644 --- a/tests/spirv-capabilities.rs +++ b/tests/spirv-capabilities.rs @@ -1,4 +1,6 @@ -//! Test SPIR-V backend capability checks. +/*! +Test SPIR-V backend capability checks. +*/ #![cfg(all(feature = "wgsl-in", feature = "spv-out"))] diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 934eea1b4..a5a0a5fc1 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1,4 +1,6 @@ -//! Tests for the WGSL front end. +/*! +Tests for the WGSL front end. +*/ #![cfg(feature = "wgsl-in")] fn check(input: &str, snapshot: &str) { From b235973d2e6e645fef346859b9a033aeba7360f5 Mon Sep 17 00:00:00 2001 From: francesco-cattoglio Date: Thu, 3 Feb 2022 20:03:43 +0100 Subject: [PATCH 1567/2212] Add support for `vecN` and `vecN` to `dot()` function (#1689) * Allow vecN and vecN in `dot()`, first changes * Added a test case * Fix the test * Changes to baking of expressions, incl args of integer dot product * Implemented requested changes for glsl backend * Added support for integer dot product on MSL backend * Removed outdated code for hlsl and wgls writers * Implement in spv backend * Commit modified outputs from running the tests * cargo fmt * Applied requested changes for both MSL and GLSL back * Changes to spv back * Committed all test output changes * Cargo fmt * Added a comment w.r.t. VK_KHR_shader_integer_dot_product * Implemented requested svp change * Minor change to test case This is because I wanted to highlight the fact that the correct id is used in the last sum of the integer dot product expression * Changed function signature since it could not fail, changed it to simply return `void` --- src/back/glsl/mod.rs | 92 +++++++++++++++++-- src/back/msl/writer.rs | 101 ++++++++++++++++++-- src/back/spv/block.rs | 97 ++++++++++++++++++-- src/lib.rs | 1 + src/valid/expression.rs | 23 ++++- tests/in/functions.wgsl | 14 +++ tests/out/glsl/functions.main.Compute.glsl | 14 +++ tests/out/hlsl/functions.hlsl | 13 +++ tests/out/msl/functions.msl | 15 +++ tests/out/spv/functions.spvasm | 102 +++++++++++++++++---- tests/out/wgsl/functions.wgsl | 12 +++ 11 files changed, 442 insertions(+), 42 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 7c4e1d7df..df1d6de14 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -417,6 +417,8 @@ pub struct Writer<'a, W> { block_id: IdGenerator, /// Set of expressions that have associated temporary variables. named_expressions: crate::NamedExpressions, + /// Set of expressions that need to be baked to avoid unnecessary repetition in output + need_bake_expressions: crate::NeedBakeExpressions, } impl<'a, W: Write> Writer<'a, W> { @@ -468,6 +470,7 @@ impl<'a, W: Write> Writer<'a, W> { block_id: IdGenerator::default(), named_expressions: crate::NamedExpressions::default(), + need_bake_expressions: crate::NeedBakeExpressions::default(), }; // Find all features required to print this module @@ -1000,6 +1003,45 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper method used to find which expressions of a given function require baking + /// + /// # Notes + /// Clears `need_bake_expressions` set before adding to it + fn update_expressions_to_bake(&mut self, func: &crate::Function, info: &valid::FunctionInfo) { + use crate::Expression; + self.need_bake_expressions.clear(); + for expr in func.expressions.iter() { + let expr_info = &info[expr.0]; + let min_ref_count = func.expressions[expr.0].bake_ref_count(); + if min_ref_count <= expr_info.ref_count { + self.need_bake_expressions.insert(expr.0); + } + // if the expression is a Dot product with integer arguments, + // then the args needs baking as well + if let ( + fun_handle, + &Expression::Math { + fun: crate::MathFunction::Dot, + arg, + arg1, + .. + }, + ) = expr + { + let inner = info[fun_handle].ty.inner_with(&self.module.types); + if let TypeInner::Scalar { kind, .. } = *inner { + match kind { + crate::ScalarKind::Sint | crate::ScalarKind::Uint => { + self.need_bake_expressions.insert(arg); + self.need_bake_expressions.insert(arg1.unwrap()); + } + _ => {} + } + } + } + } + } + /// Helper method used to get a name for a global /// /// Globals have different naming schemes depending on their binding: @@ -1151,6 +1193,7 @@ impl<'a, W: Write> Writer<'a, W> { }; self.named_expressions.clear(); + self.update_expressions_to_bake(func, info); // Write the function header // @@ -1401,6 +1444,33 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper method used to output a dot product as an arithmetic expression + /// + fn write_dot_product( + &mut self, + arg: Handle, + arg1: Handle, + size: usize, + ) -> BackendResult { + write!(self.out, "(")?; + + let arg0_name = &self.named_expressions[&arg]; + let arg1_name = &self.named_expressions[&arg1]; + + // This will print an extra '+' at the beginning but that is fine in glsl + for index in 0..size { + let component = back::COMPONENTS[index]; + write!( + self.out, + " + {}.{} * {}.{}", + arg0_name, component, arg1_name, component + )?; + } + + write!(self.out, ")")?; + Ok(()) + } + /// Helper method used to write structs /// /// # Notes @@ -1490,13 +1560,10 @@ impl<'a, W: Write> Writer<'a, W> { // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. Some(self.namer.call(name)) + } else if self.need_bake_expressions.contains(&handle) { + Some(format!("{}{}", super::BAKE_PREFIX, handle.index())) } else { - let min_ref_count = ctx.expressions[handle].bake_ref_count(); - if min_ref_count <= info.ref_count { - Some(format!("{}{}", super::BAKE_PREFIX, handle.index())) - } else { - None - } + None }; if let Some(name) = expr_name { @@ -2538,7 +2605,18 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Log2 => "log2", Mf::Pow => "pow", // geometry - Mf::Dot => "dot", + Mf::Dot => match *ctx.info[arg].ty.inner_with(&self.module.types) { + crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + .. + } => "dot", + crate::TypeInner::Vector { size, .. } => { + return self.write_dot_product(arg, arg1.unwrap(), size as usize) + } + _ => unreachable!( + "Correct TypeInner for dot product should be already validated" + ), + }, Mf::Outer => "outerProduct", Mf::Cross => "cross", Mf::Distance => "distance", diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 26afaae64..d1931e85c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -309,6 +309,8 @@ pub struct Writer { out: W, names: FastHashMap, named_expressions: crate::NamedExpressions, + /// Set of expressions that need to be baked to avoid unnecessary repetition in output + need_bake_expressions: crate::NeedBakeExpressions, namer: proc::Namer, #[cfg(test)] put_expression_stack_pointers: FastHashSet<*const ()>, @@ -526,6 +528,7 @@ impl Writer { out, names: FastHashMap::default(), named_expressions: crate::NamedExpressions::default(), + need_bake_expressions: crate::NeedBakeExpressions::default(), namer: proc::Namer::default(), #[cfg(test)] put_expression_stack_pointers: Default::default(), @@ -827,6 +830,33 @@ impl Writer { Ok(()) } + /// Emit code for the arithmetic expression of the dot product. + /// + fn put_dot_product( + &mut self, + arg: Handle, + arg1: Handle, + size: usize, + ) -> BackendResult { + write!(self.out, "(")?; + + let arg0_name = &self.named_expressions[&arg]; + let arg1_name = &self.named_expressions[&arg1]; + + // This will print an extra '+' at the beginning but that is fine in msl + for index in 0..size { + let component = back::COMPONENTS[index]; + write!( + self.out, + " + {}.{} * {}.{}", + arg0_name, component, arg1_name, component + )?; + } + + write!(self.out, ")")?; + Ok(()) + } + /// Emit code for the expression `expr_handle`. /// /// The `is_scoped` argument is true if the surrounding operators have the @@ -1216,7 +1246,18 @@ impl Writer { Mf::Log2 => "log2", Mf::Pow => "pow", // geometry - Mf::Dot => "dot", + Mf::Dot => match *context.resolve_type(arg) { + crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + .. + } => "dot", + crate::TypeInner::Vector { size, .. } => { + return self.put_dot_product(arg, arg1.unwrap(), size as usize) + } + _ => unreachable!( + "Correct TypeInner for dot product should be already validated" + ), + }, Mf::Outer => return Err(Error::UnsupportedCall(format!("{:?}", fun))), Mf::Cross => "cross", Mf::Distance => "distance", @@ -1810,6 +1851,55 @@ impl Writer { Ok(()) } + /// Helper method used to find which expressions of a given function require baking + /// + /// # Notes + /// This function overwrites the contents of `self.need_bake_expressions` + fn update_expressions_to_bake( + &mut self, + func: &crate::Function, + info: &valid::FunctionInfo, + context: &ExpressionContext, + ) { + use crate::Expression; + self.need_bake_expressions.clear(); + for expr in func.expressions.iter() { + // Expressions whose reference count is above the + // threshold should always be stored in temporaries. + let expr_info = &info[expr.0]; + let min_ref_count = func.expressions[expr.0].bake_ref_count(); + if min_ref_count <= expr_info.ref_count { + self.need_bake_expressions.insert(expr.0); + } + // if the expression is a Dot product with integer arguments, + // then the args needs baking as well + if let ( + fun_handle, + &Expression::Math { + fun: crate::MathFunction::Dot, + arg, + arg1, + .. + }, + ) = expr + { + use crate::TypeInner; + // check what kind of product this is depending + // on the resolve type of the Dot function itself + let inner = context.resolve_type(fun_handle); + if let TypeInner::Scalar { kind, .. } = *inner { + match kind { + crate::ScalarKind::Sint | crate::ScalarKind::Uint => { + self.need_bake_expressions.insert(arg); + self.need_bake_expressions.insert(arg1.unwrap()); + } + _ => {} + } + } + } + } + } + fn start_baking_expression( &mut self, handle: Handle, @@ -1913,12 +2003,7 @@ impl Writer { if context.expression.guarded_indices.contains(handle.index()) { true } else { - // Expressions whose reference count is above the - // threshold should always be stored in temporaries. - let min_ref_count = context.expression.function.expressions - [handle] - .bake_ref_count(); - min_ref_count <= info.ref_count + self.need_bake_expressions.contains(&handle) }; if bake { @@ -2763,6 +2848,7 @@ impl Writer { result_struct: None, }; self.named_expressions.clear(); + self.update_expressions_to_bake(fun, fun_info, &context.expression); self.put_block(back::Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; } @@ -3226,6 +3312,7 @@ impl Writer { result_struct: Some(&stage_out_name), }; self.named_expressions.clear(); + self.update_expressions_to_bake(fun, fun_info, &context.expression); self.put_block(back::Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; if ep_index + 1 != module.entry_points.len() { diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index ab33acfc8..c4ad83067 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -554,13 +554,34 @@ impl<'w> BlockContext<'w> { Mf::Frexp => MathOp::Ext(spirv::GLOp::Frexp), Mf::Ldexp => MathOp::Ext(spirv::GLOp::Ldexp), // geometry - Mf::Dot => MathOp::Custom(Instruction::binary( - spirv::Op::Dot, - result_type_id, - id, - arg0_id, - arg1_id, - )), + Mf::Dot => match *self.fun_info[arg].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + .. + } => MathOp::Custom(Instruction::binary( + spirv::Op::Dot, + result_type_id, + id, + arg0_id, + arg1_id, + )), + // TODO: consider using integer dot product if VK_KHR_shader_integer_dot_product is available + crate::TypeInner::Vector { size, .. } => { + self.write_dot_product( + id, + result_type_id, + arg0_id, + arg1_id, + size as u32, + block, + ); + self.cached[expr_handle] = id; + return Ok(()); + } + _ => unreachable!( + "Correct TypeInner for dot product should be already validated" + ), + }, Mf::Outer => MathOp::Custom(Instruction::binary( spirv::Op::OuterProduct, result_type_id, @@ -1122,6 +1143,68 @@ impl<'w> BlockContext<'w> { Ok(pointer) } + /// Build the instructions for the arithmetic expression of a dot product + fn write_dot_product( + &mut self, + result_id: Word, + result_type_id: Word, + arg0_id: Word, + arg1_id: Word, + size: u32, + block: &mut Block, + ) { + let const_null = self.gen_id(); + block + .body + .push(Instruction::constant_null(result_type_id, const_null)); + + let mut partial_sum = const_null; + let last_component = size - 1; + for index in 0..=last_component { + // compute the product of the current components + let a_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + result_type_id, + a_id, + arg0_id, + &[index], + )); + let b_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + result_type_id, + b_id, + arg1_id, + &[index], + )); + let prod_id = self.gen_id(); + block.body.push(Instruction::binary( + spirv::Op::IMul, + result_type_id, + prod_id, + a_id, + b_id, + )); + + // choose the id for the next sum, depending on current index + let id = if index == last_component { + result_id + } else { + self.gen_id() + }; + + // sum the computed product with the partial sum + block.body.push(Instruction::binary( + spirv::Op::IAdd, + result_type_id, + id, + partial_sum, + prod_id, + )); + // set the id of the result as the previous partial sum + partial_sum = id; + } + } + pub(super) fn write_block( &mut self, label_id: Word, diff --git a/src/lib.rs b/src/lib.rs index f384c6ea1..ca516b2bd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -233,6 +233,7 @@ pub type FastHashSet = rustc_hash::FxHashSet; /// Map of expressions that have associated variable names pub(crate) type NamedExpressions = FastHashMap, String>; +pub(crate) type NeedBakeExpressions = FastHashSet>; /// Early fragment tests. /// diff --git a/src/valid/expression.rs b/src/valid/expression.rs index f7a03abc0..1cba9e9e4 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1059,7 +1059,28 @@ impl super::Validator { )); } } - Mf::Dot | Mf::Outer | Mf::Cross | Mf::Reflect => { + Mf::Dot => { + let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), None, None) => ty1, + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + match *arg_ty { + Ti::Vector { + kind: Sk::Float, .. + } + | Ti::Vector { kind: Sk::Sint, .. } + | Ti::Vector { kind: Sk::Uint, .. } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + if arg1_ty != arg_ty { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + } + Mf::Outer | Mf::Cross | Mf::Reflect => { let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { (Some(ty1), None, None) => ty1, _ => return Err(ExpressionError::WrongArgumentCount(fun)), diff --git a/tests/in/functions.wgsl b/tests/in/functions.wgsl index 71f736a2b..6a15da1e3 100644 --- a/tests/in/functions.wgsl +++ b/tests/in/functions.wgsl @@ -8,8 +8,22 @@ fn test_fma() -> vec2 { return fma(a, b, c); } +fn test_integer_dot_product() -> i32 { + let a_2 = vec2(1); + let b_2 = vec2(1); + let c_2: i32 = dot(a_2, b_2); + + let a_3 = vec3(1u); + let b_3 = vec3(1u); + let c_3: u32 = dot(a_3, b_3); + + // test baking of arguments + let c_4: i32 = dot(vec4(4), vec4(2)); + return c_4; +} @stage(compute) @workgroup_size(1) fn main() { let a = test_fma(); + let b = test_integer_dot_product(); } diff --git a/tests/out/glsl/functions.main.Compute.glsl b/tests/out/glsl/functions.main.Compute.glsl index d3e7f7d17..07e4e7cde 100644 --- a/tests/out/glsl/functions.main.Compute.glsl +++ b/tests/out/glsl/functions.main.Compute.glsl @@ -14,8 +14,22 @@ vec2 test_fma() { return fma(a, b, c); } +int test_integer_dot_product() { + ivec2 a_2_ = ivec2(1); + ivec2 b_2_ = ivec2(1); + int c_2_ = ( + a_2_.x * b_2_.x + a_2_.y * b_2_.y); + uvec3 a_3_ = uvec3(1u); + uvec3 b_3_ = uvec3(1u); + uint c_3_ = ( + a_3_.x * b_3_.x + a_3_.y * b_3_.y + a_3_.z * b_3_.z); + ivec4 _e11 = ivec4(4); + ivec4 _e13 = ivec4(2); + int c_4_ = ( + _e11.x * _e13.x + _e11.y * _e13.y + _e11.z * _e13.z + _e11.w * _e13.w); + return c_4_; +} + void main() { vec2 _e0 = test_fma(); + int _e1 = test_integer_dot_product(); return; } diff --git a/tests/out/hlsl/functions.hlsl b/tests/out/hlsl/functions.hlsl index 37a4ecfaf..c1b420f22 100644 --- a/tests/out/hlsl/functions.hlsl +++ b/tests/out/hlsl/functions.hlsl @@ -7,9 +7,22 @@ float2 test_fma() return mad(a, b, c); } +int test_integer_dot_product() +{ + int2 a_2_ = int2(1.xx); + int2 b_2_ = int2(1.xx); + int c_2_ = dot(a_2_, b_2_); + uint3 a_3_ = uint3(1u.xxx); + uint3 b_3_ = uint3(1u.xxx); + uint c_3_ = dot(a_3_, b_3_); + int c_4_ = dot(int4(4.xxxx), int4(2.xxxx)); + return c_4_; +} + [numthreads(1, 1, 1)] void main() { const float2 _e0 = test_fma(); + const int _e1 = test_integer_dot_product(); return; } diff --git a/tests/out/msl/functions.msl b/tests/out/msl/functions.msl index 11574c679..73c5a9fa6 100644 --- a/tests/out/msl/functions.msl +++ b/tests/out/msl/functions.msl @@ -11,8 +11,23 @@ metal::float2 test_fma( return metal::fma(a, b, c); } +int test_integer_dot_product( +) { + metal::int2 a_2_ = metal::int2(1); + metal::int2 b_2_ = metal::int2(1); + int c_2_ = ( + a_2_.x * b_2_.x + a_2_.y * b_2_.y); + metal::uint3 a_3_ = metal::uint3(1u); + metal::uint3 b_3_ = metal::uint3(1u); + metal::uint c_3_ = ( + a_3_.x * b_3_.x + a_3_.y * b_3_.y + a_3_.z * b_3_.z); + metal::int4 _e11 = metal::int4(4); + metal::int4 _e13 = metal::int4(2); + int c_4_ = ( + _e11.x * _e13.x + _e11.y * _e13.y + _e11.z * _e13.z + _e11.w * _e13.w); + return c_4_; +} + kernel void main_( ) { metal::float2 _e0 = test_fma(); + int _e1 = test_integer_dot_product(); return; } diff --git a/tests/out/spv/functions.spvasm b/tests/out/spv/functions.spvasm index 9c1a62ae4..da2d240aa 100644 --- a/tests/out/spv/functions.spvasm +++ b/tests/out/spv/functions.spvasm @@ -1,33 +1,95 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 20 +; Bound: 79 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %16 "main" -OpExecutionMode %16 LocalSize 1 1 1 +OpEntryPoint GLCompute %74 "main" +OpExecutionMode %74 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 2.0 %5 = OpConstant %4 0.5 -%6 = OpTypeVector %4 2 -%9 = OpTypeFunction %6 -%17 = OpTypeFunction %2 -%8 = OpFunction %6 None %9 -%7 = OpLabel -OpBranch %10 -%10 = OpLabel -%11 = OpCompositeConstruct %6 %3 %3 -%12 = OpCompositeConstruct %6 %5 %5 -%13 = OpCompositeConstruct %6 %5 %5 -%14 = OpExtInst %6 %1 Fma %11 %12 %13 -OpReturnValue %14 +%7 = OpTypeInt 32 1 +%6 = OpConstant %7 1 +%9 = OpTypeInt 32 0 +%8 = OpConstant %9 1 +%10 = OpConstant %7 4 +%11 = OpConstant %7 2 +%12 = OpTypeVector %4 2 +%15 = OpTypeFunction %12 +%23 = OpTypeFunction %7 +%25 = OpTypeVector %7 2 +%37 = OpTypeVector %9 3 +%53 = OpTypeVector %7 4 +%75 = OpTypeFunction %2 +%29 = OpConstantNull %7 +%41 = OpConstantNull %9 +%57 = OpConstantNull %7 +%14 = OpFunction %12 None %15 +%13 = OpLabel +OpBranch %16 +%16 = OpLabel +%17 = OpCompositeConstruct %12 %3 %3 +%18 = OpCompositeConstruct %12 %5 %5 +%19 = OpCompositeConstruct %12 %5 %5 +%20 = OpExtInst %12 %1 Fma %17 %18 %19 +OpReturnValue %20 OpFunctionEnd -%16 = OpFunction %2 None %17 -%15 = OpLabel -OpBranch %18 -%18 = OpLabel -%19 = OpFunctionCall %6 %8 +%22 = OpFunction %7 None %23 +%21 = OpLabel +OpBranch %24 +%24 = OpLabel +%26 = OpCompositeConstruct %25 %6 %6 +%27 = OpCompositeConstruct %25 %6 %6 +%30 = OpCompositeExtract %7 %26 0 +%31 = OpCompositeExtract %7 %27 0 +%32 = OpIMul %7 %30 %31 +%33 = OpIAdd %7 %29 %32 +%34 = OpCompositeExtract %7 %26 1 +%35 = OpCompositeExtract %7 %27 1 +%36 = OpIMul %7 %34 %35 +%28 = OpIAdd %7 %33 %36 +%38 = OpCompositeConstruct %37 %8 %8 %8 +%39 = OpCompositeConstruct %37 %8 %8 %8 +%42 = OpCompositeExtract %9 %38 0 +%43 = OpCompositeExtract %9 %39 0 +%44 = OpIMul %9 %42 %43 +%45 = OpIAdd %9 %41 %44 +%46 = OpCompositeExtract %9 %38 1 +%47 = OpCompositeExtract %9 %39 1 +%48 = OpIMul %9 %46 %47 +%49 = OpIAdd %9 %45 %48 +%50 = OpCompositeExtract %9 %38 2 +%51 = OpCompositeExtract %9 %39 2 +%52 = OpIMul %9 %50 %51 +%40 = OpIAdd %9 %49 %52 +%54 = OpCompositeConstruct %53 %10 %10 %10 %10 +%55 = OpCompositeConstruct %53 %11 %11 %11 %11 +%58 = OpCompositeExtract %7 %54 0 +%59 = OpCompositeExtract %7 %55 0 +%60 = OpIMul %7 %58 %59 +%61 = OpIAdd %7 %57 %60 +%62 = OpCompositeExtract %7 %54 1 +%63 = OpCompositeExtract %7 %55 1 +%64 = OpIMul %7 %62 %63 +%65 = OpIAdd %7 %61 %64 +%66 = OpCompositeExtract %7 %54 2 +%67 = OpCompositeExtract %7 %55 2 +%68 = OpIMul %7 %66 %67 +%69 = OpIAdd %7 %65 %68 +%70 = OpCompositeExtract %7 %54 3 +%71 = OpCompositeExtract %7 %55 3 +%72 = OpIMul %7 %70 %71 +%56 = OpIAdd %7 %69 %72 +OpReturnValue %56 +OpFunctionEnd +%74 = OpFunction %2 None %75 +%73 = OpLabel +OpBranch %76 +%76 = OpLabel +%77 = OpFunctionCall %12 %14 +%78 = OpFunctionCall %7 %22 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/functions.wgsl b/tests/out/wgsl/functions.wgsl index 5a53e38c6..159daeb5b 100644 --- a/tests/out/wgsl/functions.wgsl +++ b/tests/out/wgsl/functions.wgsl @@ -5,8 +5,20 @@ fn test_fma() -> vec2 { return fma(a, b, c); } +fn test_integer_dot_product() -> i32 { + let a_2_ = vec2(1); + let b_2_ = vec2(1); + let c_2_ = dot(a_2_, b_2_); + let a_3_ = vec3(1u); + let b_3_ = vec3(1u); + let c_3_ = dot(a_3_, b_3_); + let c_4_ = dot(vec4(4), vec4(2)); + return c_4_; +} + @stage(compute) @workgroup_size(1, 1, 1) fn main() { let _e0 = test_fma(); + let _e1 = test_integer_dot_product(); return; } From 54c3f5190c705e4981099ea920e388d989d3fcfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 4 Feb 2022 19:21:16 +0000 Subject: [PATCH 1568/2212] glsl-in: Fix panic when culling nested block (#1714) Under certatin circumstances the parser would panic because of culling using an index out of bound, for example take the following code: ```glsl { x = 1; // Index 0 on nested block discard; // Index 1 on nested block } // Index 0 on block ``` The parser seeing this would attempt to cull the block using the start index of 1 which would be out of bound and panic. Now instead the nested block properly does it's internal culling and the outer block culls everything after the nested block only. --- src/front/glsl/parser/functions.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 6483db052..f684ada6c 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -486,12 +486,21 @@ impl<'source> ParsingContext<'source> { let mut block = Block::new(); ctx.push_scope(); - let meta = - self.parse_compound_statement(meta, parser, ctx, &mut block, terminator)?; + let mut block_terminator = None; + let meta = self.parse_compound_statement( + meta, + parser, + ctx, + &mut block, + &mut block_terminator, + )?; ctx.remove_current_scope(); body.push(Statement::Block(block), meta); + if block_terminator.is_some() { + terminator.get_or_insert(body.len()); + } meta } From f3e61530cf9345b488a05ccaa0bd2df1c8c4d4da Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 4 Feb 2022 11:31:35 -0800 Subject: [PATCH 1569/2212] Fix a few stray uses of "storage class". (#1712) --- src/back/msl/writer.rs | 11 +++++------ src/back/spv/index.rs | 2 +- src/back/spv/writer.rs | 7 ++++--- src/front/glsl/functions.rs | 6 +++--- src/proc/index.rs | 4 ++-- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index d1931e85c..3b29eaf56 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -392,10 +392,9 @@ fn needs_array_length(ty: Handle, arena: &crate::UniqueArena bool { match *self { crate::AddressSpace::Uniform @@ -1695,8 +1694,8 @@ impl Writer { context: &ExpressionContext, is_scoped: bool, ) -> BackendResult { - // Since access chains never cross storage classes, we can just check the index - // bounds check policy once at the top. + // Since access chains never cross between address spaces, we can just + // check the index bounds check policy once at the top. let policy = context.choose_bounds_check_policy(pointer); if policy == index::BoundsCheckPolicy::ReadZeroSkipWrite && self.put_bounds_checks( diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index c8f16e83a..fa36d2528 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -315,7 +315,7 @@ impl<'w> BlockContext<'w> { /// Emit code for bounds checks for an array, vector, or matrix access. /// /// This implements either `index_bounds_check_policy` or - /// `buffer_bounds_check_policy`, depending on the storage class of the + /// `buffer_bounds_check_policy`, depending on the address space of the /// pointer being accessed. /// /// Return a `BoundsCheckResult` indicating how the index should be diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 83253cc73..dad763b24 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1298,9 +1298,10 @@ impl Writer { pointer_type_id } else { - // This is a global variable in a Storage class. The only way it could - // have `global_needs_wrapper() == false` is if it has a runtime-sized array. - // In this case, we need to decorate it with Block. + // This is a global variable in the Storage address space. The only + // way it could have `global_needs_wrapper() == false` is if it has + // a runtime-sized array. In this case, we need to decorate it with + // Block. if let crate::AddressSpace::Storage { .. } = global_variable.space { self.decorate(inner_type_id, Decoration::Block, &[]); } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index d87892c08..3751e6374 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -811,9 +811,9 @@ impl Parser { ), handle, ), - // If the argument is a pointer whose address space isn't `Function` an - // indirection trough a local variable is needed to align the storage - // classes of the call argument and the overload parameter + // If the argument is a pointer whose address space isn't `Function`, an + // indirection through a local variable is needed to align the address + // spaces of the call argument and the overload parameter. TypeInner::Pointer { base, space } if space != AddressSpace::Function => ( base, ctx.add_expression( diff --git a/src/proc/index.rs b/src/proc/index.rs index a7cd94170..340862ebc 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -72,7 +72,7 @@ pub struct BoundsCheckPolicies { /// How should the generated code handle array, vector, or matrix indices /// that are out of range, when those values live in a [`GlobalVariable`] in - /// the [`Storage`] or [`Uniform`] storage classes? + /// the [`Storage`] or [`Uniform`] address spaces? /// /// Some graphics hardware provides "robust buffer access", a feature that /// ensures that using a pointer cannot access memory outside the 'buffer' @@ -143,7 +143,7 @@ impl BoundsCheckPolicies { match info[access].ty.inner_with(types).pointer_space() { Some(crate::AddressSpace::Storage { access: _ }) | Some(crate::AddressSpace::Uniform) => self.buffer, - // This covers other storage classes, but also accessing vectors and + // This covers other address spaces, but also accessing vectors and // matrices by value, where no pointer is involved. _ => self.index, } From ca58d413b78ea4873acde666f87c7e7d572411b9 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 4 Feb 2022 14:31:48 -0500 Subject: [PATCH 1570/2212] Move NeedBakeExpressions into backends (#1716) --- src/back/glsl/mod.rs | 14 +++++++------- src/back/mod.rs | 16 +++------------- src/back/msl/writer.rs | 6 +++--- src/lib.rs | 1 - 4 files changed, 13 insertions(+), 24 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index df1d6de14..38888957e 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -418,7 +418,7 @@ pub struct Writer<'a, W> { /// Set of expressions that have associated temporary variables. named_expressions: crate::NamedExpressions, /// Set of expressions that need to be baked to avoid unnecessary repetition in output - need_bake_expressions: crate::NeedBakeExpressions, + need_bake_expressions: back::NeedBakeExpressions, } impl<'a, W: Write> Writer<'a, W> { @@ -469,8 +469,8 @@ impl<'a, W: Write> Writer<'a, W> { entry_point_idx: ep_idx as u16, block_id: IdGenerator::default(), - named_expressions: crate::NamedExpressions::default(), - need_bake_expressions: crate::NeedBakeExpressions::default(), + named_expressions: Default::default(), + need_bake_expressions: Default::default(), }; // Find all features required to print this module @@ -1561,7 +1561,7 @@ impl<'a, W: Write> Writer<'a, W> { // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. Some(self.namer.call(name)) } else if self.need_bake_expressions.contains(&handle) { - Some(format!("{}{}", super::BAKE_PREFIX, handle.index())) + Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) } else { None }; @@ -1886,7 +1886,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { write!(self.out, "{}", level)?; if let Some(expr) = result { - let name = format!("{}{}", super::BAKE_PREFIX, expr.index()); + let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); let result = self.module.functions[function].result.as_ref().unwrap(); self.write_type(result.ty)?; write!(self.out, " {} = ", name)?; @@ -1914,7 +1914,7 @@ impl<'a, W: Write> Writer<'a, W> { result, } => { write!(self.out, "{}", level)?; - let res_name = format!("{}{}", super::BAKE_PREFIX, result.index()); + let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); let res_ty = ctx.info[result].ty.inner_with(&self.module.types); self.write_value_type(res_ty)?; write!(self.out, " {} = ", res_name)?; @@ -2478,7 +2478,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "(")?; self.write_expr(left, ctx)?; - write!(self.out, " {} ", super::binary_operation_str(op))?; + write!(self.out, " {} ", back::binary_operation_str(op))?; self.write_expr(right, ctx)?; write!(self.out, ")")?; diff --git a/src/back/mod.rs b/src/back/mod.rs index d69c0463c..9802e5acf 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -1,6 +1,7 @@ /*! Backend functions that export shader [`Module`](super::Module)s into binary and text formats. */ +#![allow(dead_code)] // can be dead if none of the enabled backends need it #[cfg(feature = "dot-out")] pub mod dot; @@ -15,25 +16,21 @@ pub mod spv; #[cfg(feature = "wgsl-out")] pub mod wgsl; -#[allow(dead_code)] const COMPONENTS: &[char] = &['x', 'y', 'z', 'w']; -#[allow(dead_code)] const INDENT: &str = " "; -#[allow(dead_code)] const BAKE_PREFIX: &str = "_e"; +type NeedBakeExpressions = crate::FastHashSet>; + #[derive(Clone, Copy)] -#[allow(dead_code)] struct Level(usize); -#[allow(dead_code)] impl Level { fn next(&self) -> Self { Level(self.0 + 1) } } -#[allow(dead_code)] impl std::fmt::Display for Level { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { (0..self.0).try_for_each(|_| formatter.write_str(INDENT)) @@ -43,7 +40,6 @@ impl std::fmt::Display for Level { /// Stores the current function type (either a regular function or an entry point) /// /// Also stores data needed to identify it (handle for a regular function or index for an entry point) -#[allow(dead_code)] enum FunctionType { /// A regular function and it's handle Function(crate::Handle), @@ -52,7 +48,6 @@ enum FunctionType { } /// Helper structure that stores data needed when writing the function -#[allow(dead_code)] struct FunctionCtx<'a> { /// The current function being written ty: FunctionType, @@ -64,7 +59,6 @@ struct FunctionCtx<'a> { named_expressions: &'a crate::NamedExpressions, } -#[allow(dead_code)] impl<'a> FunctionCtx<'_> { /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function fn name_key(&self, local: crate::Handle) -> crate::proc::NameKey { @@ -134,7 +128,6 @@ impl crate::Expression { /// See the [module-level documentation][emit] for details. /// /// [emit]: index.html#expression-evaluation-time - #[allow(dead_code)] fn bake_ref_count(&self) -> usize { match *self { // accesses are never cached, only loads are @@ -156,7 +149,6 @@ impl crate::Expression { /// Helper function that returns the string corresponding to the [`BinaryOperator`](crate::BinaryOperator) /// # Notes /// Used by `glsl-out`, `msl-out`, `wgsl-out`, `hlsl-out`. -#[allow(dead_code)] fn binary_operation_str(op: crate::BinaryOperator) -> &'static str { use crate::BinaryOperator as Bo; match op { @@ -184,7 +176,6 @@ fn binary_operation_str(op: crate::BinaryOperator) -> &'static str { /// Helper function that returns the string corresponding to the [`VectorSize`](crate::VectorSize) /// # Notes /// Used by `msl-out`, `wgsl-out`, `hlsl-out`. -#[allow(dead_code)] fn vector_size_str(size: crate::VectorSize) -> &'static str { match size { crate::VectorSize::Bi => "2", @@ -194,7 +185,6 @@ fn vector_size_str(size: crate::VectorSize) -> &'static str { } impl crate::TypeInner { - #[allow(unused)] fn is_handle(&self) -> bool { match *self { crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => true, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 3b29eaf56..8ebaf4982 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -310,7 +310,7 @@ pub struct Writer { names: FastHashMap, named_expressions: crate::NamedExpressions, /// Set of expressions that need to be baked to avoid unnecessary repetition in output - need_bake_expressions: crate::NeedBakeExpressions, + need_bake_expressions: back::NeedBakeExpressions, namer: proc::Namer, #[cfg(test)] put_expression_stack_pointers: FastHashSet<*const ()>, @@ -526,8 +526,8 @@ impl Writer { Writer { out, names: FastHashMap::default(), - named_expressions: crate::NamedExpressions::default(), - need_bake_expressions: crate::NeedBakeExpressions::default(), + named_expressions: Default::default(), + need_bake_expressions: Default::default(), namer: proc::Namer::default(), #[cfg(test)] put_expression_stack_pointers: Default::default(), diff --git a/src/lib.rs b/src/lib.rs index ca516b2bd..f384c6ea1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -233,7 +233,6 @@ pub type FastHashSet = rustc_hash::FxHashSet; /// Map of expressions that have associated variable names pub(crate) type NamedExpressions = FastHashMap, String>; -pub(crate) type NeedBakeExpressions = FastHashSet>; /// Early fragment tests. /// From 5f948e9b120a7a7e7d0f1b80b61a937ab886115a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 4 Feb 2022 20:05:49 +0000 Subject: [PATCH 1571/2212] glsl-in: texelFetch accept multisampled textures (#1715) --- src/front/glsl/builtins.rs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index c2c3e2902..d688ecad5 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -443,14 +443,20 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module } "texelFetch" => { // bits layout - // bit 0 - dim part 1 - 1D/2D - // bit 1 - array - // bit 2 - dim part 2 - 3D + // bit 0 - array + // bit 1 - multisample + // bits 2 trough 3 - dims // - // 0b100 is the latest since 3D arrayed images aren't allowed - for bits in 0..(0b101) { - let dim = bits & 0b1 | (bits & 0b100) >> 1; - let arrayed = bits & 0b10 == 0b10; + // 0b1000 is the latest since 3D images aren't allowed to be multisampled or arrayed + for bits in 0..=(0b1000) { + let arrayed = bits & 0b1 != 0; + let multi = bits & 0b10 != 0; + let dim = bits >> 2; + + // Multisampled 1d images don't exist + if dim == 0b00 && multi { + continue; + } let image = TypeInner::Image { dim: match dim { @@ -461,7 +467,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module arrayed, class: ImageClass::Sampled { kind: Sk::Float, - multi: false, + multi, }, }; From e621acc09d3b40ec27f1e2c4ff2ea614d6a76a1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 4 Feb 2022 20:06:49 +0000 Subject: [PATCH 1572/2212] glsl-in: Type qualifiers rework (#1713) The previous implementation had many issues, most importantly it didn't allow to implement (at least in a sane way) some future features like default qualifiers and format qualifiers. This implementations centralizes the qualifiers into a struct with a hashmap for layout qualifiers, error reporting is also centralized which means that `add_global_var` and `add_local_var` no longer need to duplicate effort and the ugly loop + match combo is gone. Finally some minor fixes are also done as part of this rework, like a default location being provided for input/outputs variables and layout qualifiers being allowed to be repeated (overwriting the previous one) like the spec defines. --- src/front/glsl/ast.rs | 129 ++++++++- src/front/glsl/parser.rs | 10 +- src/front/glsl/parser/declarations.rs | 80 +++--- src/front/glsl/parser/functions.rs | 4 +- src/front/glsl/parser/types.rs | 221 +++++++++------ src/front/glsl/variables.rs | 375 +++++++++----------------- tests/out/wgsl/expressions-frag.wgsl | 9 +- tests/out/wgsl/fma-frag.wgsl | 9 +- 8 files changed, 430 insertions(+), 407 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 2594a76e8..4c2054bfe 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -1,4 +1,4 @@ -use std::fmt; +use std::{borrow::Cow, fmt}; use super::{builtins::MacroCall, context::ExprPos, Span}; use crate::{ @@ -134,19 +134,118 @@ pub enum HirExprKind { }, } +#[derive(Debug, Hash, PartialEq, Eq)] +pub enum QualifierKey<'a> { + String(Cow<'a, str>), + /// Used for `std140` and `std430` layout qualifiers + Layout, +} + #[derive(Debug)] -pub enum TypeQualifier { - StorageQualifier(StorageQualifier), - Interpolation(Interpolation), - Set(u32), - Binding(u32), - Location(u32), - WorkGroupSize(usize, u32), - Sampling(Sampling), +pub enum QualifierValue { + None, + Uint(u32), Layout(StructLayout), - Precision(Precision), - EarlyFragmentTests, - StorageAccess(StorageAccess), +} + +#[derive(Debug, Default)] +pub struct TypeQualifiers<'a> { + pub span: Span, + pub storage: (StorageQualifier, Span), + pub interpolation: Option<(Interpolation, Span)>, + pub precision: Option<(Precision, Span)>, + pub sampling: Option<(Sampling, Span)>, + pub storage_acess: Option<(StorageAccess, Span)>, + pub layout_qualifiers: crate::FastHashMap, (QualifierValue, Span)>, +} + +impl<'a> TypeQualifiers<'a> { + /// Appends `errors` with errors for all unused qualifiers + pub fn unused_errors(&self, errors: &mut Vec) { + if let Some((_, meta)) = self.interpolation { + errors.push(super::Error { + kind: super::ErrorKind::SemanticError( + "Interpolation qualifiers can only be used in in/out variables".into(), + ), + meta, + }); + } + + if let Some((_, meta)) = self.sampling { + errors.push(super::Error { + kind: super::ErrorKind::SemanticError( + "Sampling qualifiers can only be used in in/out variables".into(), + ), + meta, + }); + } + + if let Some((_, meta)) = self.storage_acess { + errors.push(super::Error { + kind: super::ErrorKind::SemanticError( + "Memory qualifiers can only be used in storage variables".into(), + ), + meta, + }); + } + + for &(_, meta) in self.layout_qualifiers.values() { + errors.push(super::Error { + kind: super::ErrorKind::SemanticError("Unexpected qualifier".into()), + meta, + }); + } + } + + /// Removes the layout qualifier with `name`, if it exists and adds an error if it isn't + /// a [`QualifierValue::Uint`] + pub fn uint_layout_qualifier( + &mut self, + name: &'a str, + errors: &mut Vec, + ) -> Option { + match self + .layout_qualifiers + .remove(&QualifierKey::String(name.into())) + { + Some((QualifierValue::Uint(v), _)) => Some(v), + Some((_, meta)) => { + errors.push(super::Error { + kind: super::ErrorKind::SemanticError("Qualifier expects a uint value".into()), + meta, + }); + // Return a dummy value instead of `None` to differentiate from + // the qualifier not existing, since some parts might require the + // qualifier to exist and throwing another error that it doesn't + // exist would be unhelpful + Some(0) + } + _ => None, + } + } + + /// Removes the layout qualifier with `name`, if it exists and adds an error if it isn't + /// a [`QualifierValue::None`] + pub fn none_layout_qualifier(&mut self, name: &'a str, errors: &mut Vec) -> bool { + match self + .layout_qualifiers + .remove(&QualifierKey::String(name.into())) + { + Some((QualifierValue::None, _)) => true, + Some((_, meta)) => { + errors.push(super::Error { + kind: super::ErrorKind::SemanticError( + "Qualifier doesn't expect a value".into(), + ), + meta, + }); + // Return a `true` to since the qualifier is defined and adding + // another error for it not being defined would be unhelpful + true + } + _ => false, + } + } } #[derive(Debug, Clone)] @@ -169,6 +268,12 @@ pub enum StorageQualifier { Const, } +impl Default for StorageQualifier { + fn default() -> Self { + StorageQualifier::AddressSpace(AddressSpace::Function) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StructLayout { Std140, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2180b9b6e..852788793 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -1,5 +1,5 @@ use super::{ - ast::{FunctionKind, Profile, TypeQualifier}, + ast::{FunctionKind, Profile, TypeQualifiers}, context::{Context, ExprPos}, error::ExpectedToken, error::{Error, ErrorKind}, @@ -366,15 +366,15 @@ impl Parser { } } -pub struct DeclarationContext<'ctx> { - qualifiers: Vec<(TypeQualifier, Span)>, +pub struct DeclarationContext<'ctx, 'qualifiers> { + qualifiers: TypeQualifiers<'qualifiers>, external: bool, ctx: &'ctx mut Context, body: &'ctx mut Block, } -impl<'ctx> DeclarationContext<'ctx> { +impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { fn add_var( &mut self, parser: &mut Parser, @@ -384,7 +384,7 @@ impl<'ctx> DeclarationContext<'ctx> { meta: Span, ) -> Result> { let decl = VarDeclaration { - qualifiers: &self.qualifiers, + qualifiers: &mut self.qualifiers, ty, name: Some(name), init, diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index e53d3b10d..8171a11b7 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -1,8 +1,8 @@ use crate::{ front::glsl::{ ast::{ - GlobalLookup, GlobalLookupKind, Precision, StorageQualifier, StructLayout, - TypeQualifier, + GlobalLookup, GlobalLookupKind, Precision, QualifierKey, QualifierValue, + StorageQualifier, StructLayout, TypeQualifiers, }, context::{Context, ExprPos}, error::ExpectedToken, @@ -249,7 +249,7 @@ impl<'source> ParsingContext<'source> { // type_qualifier IDENTIFIER identifier_list SEMICOLON if self.peek_type_qualifier(parser) || self.peek_type_name(parser) { - let qualifiers = self.parse_type_qualifiers(parser)?; + let mut qualifiers = self.parse_type_qualifiers(parser)?; if self.peek_type_name(parser) { // This branch handles variables and function prototypes and if @@ -361,7 +361,7 @@ impl<'source> ParsingContext<'source> { parser, ctx, body, - &qualifiers, + &mut qualifiers, ty_name, token.meta, ) @@ -377,33 +377,28 @@ impl<'source> ParsingContext<'source> { } } TokenValue::Semicolon => { - let mut meta_all = token.meta; - for &(ref qualifier, meta) in qualifiers.iter() { - meta_all.subsume(meta); - match *qualifier { - TypeQualifier::WorkGroupSize(i, value) => { - parser.meta.workgroup_size[i] = value - } - TypeQualifier::EarlyFragmentTests => { - parser.meta.early_fragment_tests = true; - } - TypeQualifier::StorageQualifier(_) => { - // TODO: Maybe add some checks here - // This is needed because of cases like - // layout(early_fragment_tests) in; - } - _ => { - parser.errors.push(Error { - kind: ErrorKind::SemanticError( - "Qualifier not supported as standalone".into(), - ), - meta, - }); - } - } + if let Some(value) = + qualifiers.uint_layout_qualifier("local_size_x", &mut parser.errors) + { + parser.meta.workgroup_size[0] = value; + } + if let Some(value) = + qualifiers.uint_layout_qualifier("local_size_y", &mut parser.errors) + { + parser.meta.workgroup_size[1] = value; + } + if let Some(value) = + qualifiers.uint_layout_qualifier("local_size_z", &mut parser.errors) + { + parser.meta.workgroup_size[2] = value; } - Ok(Some(meta_all)) + parser.meta.early_fragment_tests |= qualifiers + .none_layout_qualifier("early_fragment_tests", &mut parser.errors); + + qualifiers.unused_errors(&mut parser.errors); + + Ok(Some(qualifiers.span)) } _ => Err(Error { kind: ErrorKind::InvalidToken( @@ -471,27 +466,22 @@ impl<'source> ParsingContext<'source> { parser: &mut Parser, ctx: &mut Context, body: &mut Block, - qualifiers: &[(TypeQualifier, Span)], + qualifiers: &mut TypeQualifiers, ty_name: String, meta: Span, ) -> Result { - let mut storage = None; - let mut layout = None; - - for &(ref qualifier, _) in qualifiers { - match *qualifier { - TypeQualifier::StorageQualifier(StorageQualifier::AddressSpace(c)) => { - storage = Some(c) + let layout = match qualifiers.layout_qualifiers.remove(&QualifierKey::Layout) { + Some((QualifierValue::Layout(l), _)) => l, + None => { + if let StorageQualifier::AddressSpace(AddressSpace::Storage { .. }) = + qualifiers.storage.0 + { + StructLayout::Std430 + } else { + StructLayout::Std140 } - TypeQualifier::Layout(l) => layout = Some(l), - _ => continue, } - } - - let layout = match (layout, storage) { - (Some(layout), _) => layout, - (None, Some(AddressSpace::Storage { .. })) => StructLayout::Std430, - _ => StructLayout::Std140, + _ => unreachable!(), }; let mut members = Vec::new(); diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index f684ada6c..35ecfa483 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -396,7 +396,7 @@ impl<'source> ParsingContext<'source> { if self.bump_if(parser, TokenValue::Semicolon).is_none() { let (expr, expr_meta) = if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { - let qualifiers = self.parse_type_qualifiers(parser)?; + let mut qualifiers = self.parse_type_qualifiers(parser)?; let (ty, mut meta) = self.parse_type_non_void(parser)?; let name = self.expect_ident(parser)?.0; @@ -407,7 +407,7 @@ impl<'source> ParsingContext<'source> { meta.subsume(end_meta); let decl = VarDeclaration { - qualifiers: &qualifiers, + qualifiers: &mut qualifiers, ty, name: Some(name), init: None, diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 13cec5860..3fb1f355c 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -1,6 +1,6 @@ use crate::{ front::glsl::{ - ast::{StorageQualifier, StructLayout, TypeQualifier}, + ast::{QualifierKey, QualifierValue, StorageQualifier, StructLayout, TypeQualifiers}, error::ExpectedToken, parser::ParsingContext, token::{Token, TokenValue}, @@ -128,11 +128,8 @@ impl<'source> ParsingContext<'source> { }) } - pub fn parse_type_qualifiers( - &mut self, - parser: &mut Parser, - ) -> Result> { - let mut qualifiers = Vec::new(); + pub fn parse_type_qualifiers<'a>(&mut self, parser: &mut Parser) -> Result> { + let mut qualifiers = TypeQualifiers::default(); while self.peek_type_qualifier(parser) { let token = self.bump(parser)?; @@ -143,31 +140,104 @@ impl<'source> ParsingContext<'source> { continue; } - qualifiers.push(( - match token.value { - TokenValue::Interpolation(i) => TypeQualifier::Interpolation(i), - TokenValue::Const => TypeQualifier::StorageQualifier(StorageQualifier::Const), - TokenValue::In => TypeQualifier::StorageQualifier(StorageQualifier::Input), - TokenValue::Out => TypeQualifier::StorageQualifier(StorageQualifier::Output), - TokenValue::Uniform => TypeQualifier::StorageQualifier( - StorageQualifier::AddressSpace(AddressSpace::Uniform), - ), - TokenValue::Shared => TypeQualifier::StorageQualifier( - StorageQualifier::AddressSpace(AddressSpace::WorkGroup), - ), - TokenValue::Buffer => TypeQualifier::StorageQualifier( - StorageQualifier::AddressSpace(AddressSpace::Storage { - access: crate::StorageAccess::default(), - }), - ), - TokenValue::Sampling(s) => TypeQualifier::Sampling(s), - TokenValue::PrecisionQualifier(p) => TypeQualifier::Precision(p), - TokenValue::StorageAccess(access) => TypeQualifier::StorageAccess(access), - TokenValue::Restrict => continue, - _ => unreachable!(), - }, - token.meta, - )) + qualifiers.span.subsume(token.meta); + + match token.value { + TokenValue::Interpolation(i) => { + if qualifiers.interpolation.is_some() { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "Cannot use more than one interpolation qualifier per declaration" + .into(), + ), + meta: token.meta, + }) + } + + qualifiers.interpolation = Some((i, token.meta)); + } + TokenValue::Const + | TokenValue::In + | TokenValue::Out + | TokenValue::Uniform + | TokenValue::Shared + | TokenValue::Buffer => { + let storage = match token.value { + TokenValue::Const => StorageQualifier::Const, + TokenValue::In => StorageQualifier::Input, + TokenValue::Out => StorageQualifier::Output, + TokenValue::Uniform => { + StorageQualifier::AddressSpace(AddressSpace::Uniform) + } + TokenValue::Shared => { + StorageQualifier::AddressSpace(AddressSpace::WorkGroup) + } + TokenValue::Buffer => { + StorageQualifier::AddressSpace(AddressSpace::Storage { + access: crate::StorageAccess::all(), + }) + } + _ => unreachable!(), + }; + + if StorageQualifier::AddressSpace(AddressSpace::Function) + != qualifiers.storage.0 + { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "Cannot use more than one storage qualifier per declaration".into(), + ), + meta: token.meta, + }); + } + + qualifiers.storage = (storage, token.meta); + } + TokenValue::Sampling(s) => { + if qualifiers.sampling.is_some() { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "Cannot use more than one sampling qualifier per declaration" + .into(), + ), + meta: token.meta, + }) + } + + qualifiers.sampling = Some((s, token.meta)); + } + TokenValue::PrecisionQualifier(p) => { + if qualifiers.interpolation.is_some() { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "Cannot use more than one precision qualifier per declaration" + .into(), + ), + meta: token.meta, + }) + } + + qualifiers.precision = Some((p, token.meta)); + } + TokenValue::StorageAccess(access) => { + let storage_access = qualifiers + .storage_acess + .get_or_insert((crate::StorageAccess::empty(), Span::default())); + if storage_access.0.contains(access) { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "The same memory qualifier can only be used once".into(), + ), + meta: token.meta, + }) + } + + storage_access.0 |= access; + storage_access.1.subsume(token.meta); + } + TokenValue::Restrict => continue, + _ => unreachable!(), + }; } Ok(qualifiers) @@ -176,11 +246,11 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id_list( &mut self, parser: &mut Parser, - qualifiers: &mut Vec<(TypeQualifier, Span)>, + qualifiers: &mut TypeQualifiers, ) -> Result<()> { self.expect(parser, TokenValue::LeftParen)?; loop { - self.parse_layout_qualifier_id(parser, qualifiers)?; + self.parse_layout_qualifier_id(parser, &mut qualifiers.layout_qualifiers)?; if self.bump_if(parser, TokenValue::Comma).is_some() { continue; @@ -188,7 +258,8 @@ impl<'source> ParsingContext<'source> { break; } - self.expect(parser, TokenValue::RightParen)?; + let token = self.expect(parser, TokenValue::RightParen)?; + qualifiers.span.subsume(token.meta); Ok(()) } @@ -196,7 +267,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id( &mut self, parser: &mut Parser, - qualifiers: &mut Vec<(TypeQualifier, Span)>, + qualifiers: &mut crate::FastHashMap, ) -> Result<()> { // layout_qualifier_id: // IDENTIFIER @@ -205,60 +276,38 @@ impl<'source> ParsingContext<'source> { let mut token = self.bump(parser)?; match token.value { TokenValue::Identifier(name) => { - if self.bump_if(parser, TokenValue::Assign).is_some() { - let (value, end_meta) = self.parse_uint_constant(parser)?; - token.meta.subsume(end_meta); + let (key, value) = match name.as_str() { + "std140" => ( + QualifierKey::Layout, + QualifierValue::Layout(StructLayout::Std140), + ), + "std430" => ( + QualifierKey::Layout, + QualifierValue::Layout(StructLayout::Std430), + ), + _ => { + let key = QualifierKey::String(name.into()); + let value = if self.bump_if(parser, TokenValue::Assign).is_some() { + let (value, end_meta) = match self.parse_uint_constant(parser) { + Ok(v) => v, + Err(e) => { + parser.errors.push(e); + (0, Span::default()) + } + }; + token.meta.subsume(end_meta); - qualifiers.push(( - match name.as_str() { - "location" => TypeQualifier::Location(value), - "set" => TypeQualifier::Set(value), - "binding" => TypeQualifier::Binding(value), - "local_size_x" => TypeQualifier::WorkGroupSize(0, value), - "local_size_y" => TypeQualifier::WorkGroupSize(1, value), - "local_size_z" => TypeQualifier::WorkGroupSize(2, value), - _ => { - parser.errors.push(Error { - kind: ErrorKind::UnknownLayoutQualifier(name), - meta: token.meta, - }); - return Ok(()); - } - }, - token.meta, - )) - } else { - qualifiers.push(( - match name.as_str() { - "push_constant" => { - qualifiers.push(( - TypeQualifier::Layout(StructLayout::Std430), - token.meta, - )); - qualifiers.push(( - TypeQualifier::StorageQualifier( - StorageQualifier::AddressSpace(AddressSpace::PushConstant), - ), - token.meta, - )); - return Ok(()); - } - "std140" => TypeQualifier::Layout(StructLayout::Std140), - "std430" => TypeQualifier::Layout(StructLayout::Std430), - "early_fragment_tests" => TypeQualifier::EarlyFragmentTests, - _ => { - parser.errors.push(Error { - kind: ErrorKind::UnknownLayoutQualifier(name), - meta: token.meta, - }); - return Ok(()); - } - }, - token.meta, - )); + QualifierValue::Uint(value) + } else { + QualifierValue::None + }; + + (key, value) + } }; + + qualifiers.insert(key, (value, token.meta)); } - // TODO: handle Shared? _ => parser.errors.push(Error { kind: ErrorKind::InvalidToken(token.value, vec![ExpectedToken::Identifier]), meta: token.meta, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 0cb11bcef..072b9f474 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -6,25 +6,12 @@ use super::{ }; use crate::{ AddressSpace, Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, - Interpolation, LocalVariable, ResourceBinding, ScalarKind, ShaderStage, StorageAccess, - SwizzleComponent, Type, TypeInner, VectorSize, + Interpolation, LocalVariable, ResourceBinding, ScalarKind, ShaderStage, SwizzleComponent, Type, + TypeInner, VectorSize, }; -macro_rules! qualifier_arm { - ($src:expr, $tgt:expr, $meta:expr, $msg:literal, $errors:expr $(,)?) => {{ - if $tgt.is_some() { - $errors.push(Error { - kind: ErrorKind::SemanticError($msg.into()), - meta: $meta, - }) - } - - $tgt = Some($src); - }}; -} - -pub struct VarDeclaration<'a> { - pub qualifiers: &'a [(TypeQualifier, Span)], +pub struct VarDeclaration<'a, 'key> { + pub qualifiers: &'a mut TypeQualifiers<'key>, pub ty: Handle, pub name: Option, pub init: Option>, @@ -412,242 +399,141 @@ impl Parser { meta, }: VarDeclaration, ) -> Result { - let mut storage = StorageQualifier::AddressSpace(AddressSpace::Private); - let mut interpolation = None; - let mut set = None; - let mut binding = None; - let mut location = None; - let mut sampling = None; - let mut layout = None; - let mut precision = None; - let mut access = StorageAccess::all(); - - for &(ref qualifier, meta) in qualifiers { - match *qualifier { - TypeQualifier::StorageQualifier(s) => { - if StorageQualifier::AddressSpace(AddressSpace::PushConstant) == storage - && s == StorageQualifier::AddressSpace(AddressSpace::Uniform) - { - // Ignore the Uniform qualifier if the space was already set to PushConstant - continue; - } else if StorageQualifier::AddressSpace(AddressSpace::Private) != storage { - self.errors.push(Error { - kind: ErrorKind::SemanticError( - "Cannot use more than one storage qualifier per declaration".into(), - ), - meta, - }); - } - - storage = s; - } - TypeQualifier::Interpolation(i) => qualifier_arm!( - i, - interpolation, - meta, - "Cannot use more than one interpolation qualifier per declaration", - self.errors - ), - TypeQualifier::Binding(r) => qualifier_arm!( - r, - binding, - meta, - "Cannot use more than one binding per declaration", - self.errors - ), - TypeQualifier::Set(s) => qualifier_arm!( - s, - set, - meta, - "Cannot use more than one binding per declaration", - self.errors - ), - TypeQualifier::Location(l) => qualifier_arm!( - l, - location, - meta, - "Cannot use more than one binding per declaration", - self.errors - ), - TypeQualifier::Sampling(s) => qualifier_arm!( - s, - sampling, - meta, - "Cannot use more than one sampling qualifier per declaration", - self.errors - ), - TypeQualifier::Layout(ref l) => qualifier_arm!( - l, - layout, - meta, - "Cannot use more than one layout qualifier per declaration", - self.errors - ), - TypeQualifier::Precision(ref p) => qualifier_arm!( - p, - precision, - meta, - "Cannot use more than one precision qualifier per declaration", - self.errors - ), - TypeQualifier::StorageAccess(a) => access &= a, - _ => { - self.errors.push(Error { - kind: ErrorKind::SemanticError("Qualifier not supported in globals".into()), - meta, - }); - } - } - } - - match storage { - StorageQualifier::AddressSpace(AddressSpace::PushConstant) => { - if set.is_some() { - self.errors.push(Error { - kind: ErrorKind::SemanticError( - "set cannot be used to decorate push constant".into(), - ), - meta, + let storage = qualifiers.storage.0; + let (ret, lookup) = match storage { + StorageQualifier::Input | StorageQualifier::Output => { + let input = storage == StorageQualifier::Input; + // TODO: glslang seems to use a counter for variables without + // explicit location (even if that causes collisions) + let location = qualifiers + .uint_layout_qualifier("location", &mut self.errors) + .unwrap_or(0); + let interpolation = qualifiers.interpolation.take().map(|(i, _)| i).or_else(|| { + let kind = self.module.types[ty].inner.scalar_kind()?; + Some(match kind { + ScalarKind::Float => Interpolation::Perspective, + _ => Interpolation::Flat, }) - } - } - StorageQualifier::AddressSpace(AddressSpace::Uniform) - | StorageQualifier::AddressSpace(AddressSpace::Storage { .. }) => { - if binding.is_none() { - self.errors.push(Error { - kind: ErrorKind::SemanticError( - "uniform/buffer blocks require layout(binding=X)".into(), - ), - meta, - }) - } - } - _ => { - if set.is_some() || binding.is_some() { - self.errors.push(Error { - kind: ErrorKind::SemanticError( - "set/binding can only be applied to uniform/buffer blocks".into(), - ), - meta, - }) - } - } - } + }); + let sampling = qualifiers.sampling.take().map(|(s, _)| s); - if (sampling.is_some() || interpolation.is_some()) && location.is_none() { - return Err(Error { - kind: ErrorKind::SemanticError( - "Sampling and interpolation qualifiers can only be used in in/out variables" - .into(), - ), - meta, - }); - } + let handle = self.module.global_variables.append( + GlobalVariable { + name: name.clone(), + space: AddressSpace::Private, + binding: None, + ty, + init, + }, + meta, + ); - if let Some(location) = location { - let input = storage == StorageQualifier::Input; - let interpolation = interpolation.or_else(|| { - let kind = self.module.types[ty].inner.scalar_kind()?; - Some(match kind { - ScalarKind::Float => Interpolation::Perspective, - _ => Interpolation::Flat, - }) - }); - - let handle = self.module.global_variables.append( - GlobalVariable { + let idx = self.entry_args.len(); + self.entry_args.push(EntryArg { name: name.clone(), - space: AddressSpace::Private, - binding: None, - ty, - init, - }, - meta, - ); + binding: Binding::Location { + location, + interpolation, + sampling, + }, + handle, + storage, + }); - let idx = self.entry_args.len(); - self.entry_args.push(EntryArg { - name: name.clone(), - binding: Binding::Location { - location, - interpolation, - sampling, - }, - handle, - storage, - }); - - if let Some(name) = name { let lookup = GlobalLookup { kind: GlobalLookupKind::Variable(handle), entry_arg: Some(idx), mutable: !input, }; - ctx.add_global(self, &name, lookup, body); - self.global_variables.push((name, lookup)); + (GlobalOrConstant::Global(handle), lookup) } + StorageQualifier::Const => { + let init = init.ok_or_else(|| Error { + kind: ErrorKind::SemanticError("const values must have an initializer".into()), + meta, + })?; - return Ok(GlobalOrConstant::Global(handle)); - } else if let StorageQualifier::Const = storage { - let init = init.ok_or_else(|| Error { - kind: ErrorKind::SemanticError("const values must have an initializer".into()), - meta, - })?; - if let Some(name) = name { let lookup = GlobalLookup { kind: GlobalLookupKind::Constant(init, ty), entry_arg: None, mutable: false, }; - ctx.add_global(self, &name, lookup, body); - self.global_variables.push((name, lookup)); + (GlobalOrConstant::Constant(init), lookup) } - return Ok(GlobalOrConstant::Constant(init)); - } - - let space = match self.module.types[ty].inner { - TypeInner::Image { .. } => AddressSpace::Handle, - TypeInner::Sampler { .. } => AddressSpace::Handle, - _ => { - if let StorageQualifier::AddressSpace(AddressSpace::Storage { .. }) = storage { - AddressSpace::Storage { access } - } else { - match storage { - StorageQualifier::AddressSpace(space) => space, - _ => AddressSpace::Private, + StorageQualifier::AddressSpace(mut space) => { + match space { + AddressSpace::Storage { ref mut access } => { + if let Some((restricted_access, _)) = qualifiers.storage_acess.take() { + access.remove(restricted_access); + } } - } + AddressSpace::Uniform => { + if let TypeInner::Image { .. } | TypeInner::Sampler { .. } = + self.module.types[ty].inner + { + space = AddressSpace::Handle + } else if qualifiers + .none_layout_qualifier("push_constant", &mut self.errors) + { + space = AddressSpace::PushConstant + } + } + AddressSpace::Function => space = AddressSpace::Private, + _ => {} + }; + + let binding = match space { + AddressSpace::Uniform | AddressSpace::Storage { .. } | AddressSpace::Handle => { + let binding = qualifiers.uint_layout_qualifier("binding", &mut self.errors); + if binding.is_none() { + self.errors.push(Error { + kind: ErrorKind::SemanticError( + "uniform/buffer blocks require layout(binding=X)".into(), + ), + meta, + }); + } + let set = qualifiers.uint_layout_qualifier("set", &mut self.errors); + binding.map(|binding| ResourceBinding { + group: set.unwrap_or(0), + binding, + }) + } + _ => None, + }; + + let handle = self.module.global_variables.append( + GlobalVariable { + name: name.clone(), + space, + binding, + ty, + init, + }, + meta, + ); + + let lookup = GlobalLookup { + kind: GlobalLookupKind::Variable(handle), + entry_arg: None, + mutable: true, + }; + + (GlobalOrConstant::Global(handle), lookup) } }; - let handle = self.module.global_variables.append( - GlobalVariable { - name: name.clone(), - space, - binding: binding.map(|binding| ResourceBinding { - group: set.unwrap_or(0), - binding, - }), - ty, - init, - }, - meta, - ); - if let Some(name) = name { - let lookup = GlobalLookup { - kind: GlobalLookupKind::Variable(handle), - entry_arg: None, - mutable: true, - }; ctx.add_global(self, &name, lookup, body); self.global_variables.push((name, lookup)); } - Ok(GlobalOrConstant::Global(handle)) + qualifiers.unused_errors(&mut self.errors); + + Ok(ret) } pub(crate) fn add_local_var( @@ -666,37 +552,18 @@ impl Parser { } } - let mut mutable = true; - let mut precision = None; - - for &(ref qualifier, meta) in decl.qualifiers { - match *qualifier { - TypeQualifier::StorageQualifier(StorageQualifier::Const) => { - if !mutable { - self.errors.push(Error { - kind: ErrorKind::SemanticError( - "Cannot use more than one constant qualifier per declaration" - .into(), - ), - meta, - }) - } - - mutable = false; - } - TypeQualifier::Precision(ref p) => qualifier_arm!( - p, - precision, - meta, - "Cannot use more than one precision qualifier per declaration", - self.errors - ), - _ => self.errors.push(Error { - kind: ErrorKind::SemanticError("Qualifier not supported in locals".into()), - meta, - }), + let storage = decl.qualifiers.storage; + let mutable = match storage.0 { + StorageQualifier::AddressSpace(AddressSpace::Function) => true, + StorageQualifier::Const => false, + _ => { + self.errors.push(Error { + kind: ErrorKind::SemanticError("Locals cannot have a storage qualifier".into()), + meta: storage.1, + }); + true } - } + }; let handle = ctx.locals.append( LocalVariable { @@ -712,6 +579,8 @@ impl Parser { ctx.add_local_var(name, expr, mutable); } + decl.qualifiers.unused_errors(&mut self.errors); + Ok(expr) } } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 86589b1af..0b3f7ad46 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -2,6 +2,10 @@ struct BST { data: i32; }; +struct FragmentOutput { + @location(0) o_color: vec4; +}; + var global: f32; var o_color: vec4; @@ -212,7 +216,8 @@ fn main_1() { } @stage(fragment) -fn main() { +fn main() -> FragmentOutput { main_1(); - return; + let _e5 = o_color; + return FragmentOutput(_e5); } diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 543311de9..8bd668674 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -4,6 +4,10 @@ struct Mat4x3_ { mz: vec4; }; +struct FragmentOutput { + @location(0) o_color: vec4; +}; + var o_color: vec4; fn Fma(d: ptr, m: Mat4x3_, s: f32) { @@ -38,7 +42,8 @@ fn main_1() { } @stage(fragment) -fn main() { +fn main() -> FragmentOutput { main_1(); - return; + let _e3 = o_color; + return FragmentOutput(_e3); } From 2a151216e3a9fe2532113e046eef8dd81648a58a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 4 Feb 2022 19:03:54 -0800 Subject: [PATCH 1573/2212] [msl-out] Always check whether _buffer_sizes arg is needed. The _buffer_sizes argument should be inserted regardless of whether or not ` `options.fake_missing_bindings` is set, so lift the computation of `supports_array_length` out of that conditional. --- src/back/msl/writer.rs | 9 +++++++-- tests/out/msl/collatz.msl | 1 + tests/out/msl/shadow.msl | 1 + 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8ebaf4982..7da11e6be 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2859,7 +2859,6 @@ impl Writer { let fun = &ep.function; let fun_info = mod_info.get_entry_point(ep_index); let mut ep_error = None; - let mut supports_array_length = false; log::trace!( "entry point {:?}, index {:?}", @@ -2867,6 +2866,13 @@ impl Writer { ep_index ); + // Is any global variable used by this entry point dynamically sized? + let supports_array_length = module + .global_variables + .iter() + .filter(|&(handle, _)| !fun_info[handle].is_empty()) + .any(|(_, var)| needs_array_length(var.ty, &module.types)); + // skip this entry point if any global bindings are missing, // or their types are incompatible. if !options.fake_missing_bindings { @@ -2895,7 +2901,6 @@ impl Writer { break; } } - supports_array_length |= needs_array_length(var.ty, &module.types); } if supports_array_length { if let Err(err) = options.resolve_sizes_buffer(ep.stage) { diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index 540ddbbb5..3a511481a 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -42,6 +42,7 @@ struct main_Input { kernel void main_( metal::uint3 global_id [[thread_position_in_grid]] , device PrimeIndices& v_indices [[user(fake0)]] +, constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { metal::uint _e8 = v_indices.data[global_id.x]; metal::uint _e9 = collatz_iterations(_e8); diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index d4868235a..f7978728d 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -49,6 +49,7 @@ fragment fs_mainOutput fs_main( , device Lights& s_lights [[user(fake0)]] , metal::depth2d_array t_shadow [[user(fake0)]] , metal::sampler sampler_shadow [[user(fake0)]] +, constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; From 0ce98d6411ddadd078aaf3b5b1fff0b17be3b867 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 4 Feb 2022 13:31:16 -0800 Subject: [PATCH 1574/2212] [msl-out][spv-out][glsl-out][hlsl-out] Fix ArraySize on globals. --- src/back/glsl/mod.rs | 6 + src/back/hlsl/help.rs | 1 + src/back/msl/writer.rs | 1 + src/back/spv/index.rs | 23 +++- src/back/spv/mod.rs | 15 ++- src/lib.rs | 3 +- tests/in/globals.wgsl | 1 + tests/out/glsl/globals.main.Compute.glsl | 3 + tests/out/hlsl/globals.hlsl | 8 ++ tests/out/msl/globals.msl | 3 + tests/out/spv/globals.spvasm | 158 ++++++++++++----------- tests/out/wgsl/globals.wgsl | 1 + 12 files changed, 140 insertions(+), 83 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 38888957e..20d003503 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -129,6 +129,12 @@ impl<'a> GlobalTypeKind<'a> { } => Self::Unsized(members), _ => Self::WrappedStruct, }, + // Naga IR permits globals to be dynamically sized arrays. Render + // these in GLSL as buffers. + crate::TypeInner::Array { + size: crate::ArraySize::Dynamic, + .. + } => Self::WrappedStruct, _ => Self::Other, } } diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 8c4b31e80..428df8afe 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -432,6 +432,7 @@ impl<'a, W: Write> super::Writer<'a, W> { match func_ctx.expressions[handle] { crate::Expression::ArrayLength(expr) => { let global_expr = match func_ctx.expressions[expr] { + crate::Expression::GlobalVariable(_) => expr, crate::Expression::AccessIndex { base, index: _ } => base, ref other => unreachable!("Array length of {:?}", other), }; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7da11e6be..f341a38ff 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1397,6 +1397,7 @@ impl Writer { _ => return Err(Error::Validation), } } + crate::Expression::GlobalVariable(handle) => handle, _ => return Err(Error::Validation), }; diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index fa36d2528..d2cbdf4d6 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -2,7 +2,10 @@ Bounds-checking for SPIR-V output. */ -use super::{selection::Selection, Block, BlockContext, Error, IdGenerator, Instruction, Word}; +use super::{ + helpers::global_needs_wrapper, selection::Selection, Block, BlockContext, Error, IdGenerator, + Instruction, Word, +}; use crate::{arena::Handle, proc::BoundsCheckPolicy}; /// The results of performing a bounds check. @@ -32,16 +35,18 @@ pub(super) enum MaybeKnown { impl<'w> BlockContext<'w> { /// Emit code to compute the length of a run-time array. /// - /// Given `array`, an expression referring to the final member of a struct, - /// where the member in question is a runtime-sized array, return the + /// Given `array`, an expression referring a runtime-sized array, return the /// instruction id for the array's length. pub(super) fn write_runtime_array_length( &mut self, array: Handle, block: &mut Block, ) -> Result { - // Look into the expression to find the value and type of the struct - // holding the dynamically-sized array. + // Naga IR permits runtime-sized arrays as global variables or as the + // final member of a struct that is a global variable. SPIR-V permits + // only the latter, so this back end wraps bare runtime-sized arrays + // in a made-up struct; see `helpers::global_needs_wrapper` and its uses. + // This code must handle both cases. let (structure_id, last_member_index) = match self.ir_function.expressions[array] { crate::Expression::AccessIndex { base, index } => { match self.ir_function.expressions[base] { @@ -52,6 +57,14 @@ impl<'w> BlockContext<'w> { _ => return Err(Error::Validation("array length expression")), } } + crate::Expression::GlobalVariable(handle) => { + let global = &self.ir_module.global_variables[handle]; + if !global_needs_wrapper(self.ir_module, global) { + return Err(Error::Validation("array length expression")); + } + + (self.writer.global_variables[handle.index()].var_id, 0) + } _ => return Err(Error::Validation("array length expression")), }; diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 0d03527d6..538147ed1 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -433,12 +433,25 @@ impl recyclable::Recyclable for CachedExpressions { #[derive(Clone)] struct GlobalVariable { - /// ID of the variable. Not really used. + /// ID of the OpVariable that declares the global. + /// + /// If you need the variable's value, use [`access_id`] instead of this + /// field. If we wrapped the Naga IR `GlobalVariable`'s type in a struct to + /// comply with Vulkan's requirements, then this points to the `OpVariable` + /// with the synthesized struct type, whereas `access_id` points to the + /// field of said struct that holds the variable's actual value. + /// + /// This is used to compute the `access_id` pointer in function prologues, + /// and used for `ArrayLength` expressions, which do need the struct. + /// + /// [`access_id`]: GlobalVariable::access_id var_id: Word, + /// For `AddressSpace::Handle` variables, this ID is recorded in the function /// prelude block (and reset before every function) as `OpLoad` of the variable. /// It is then used for all the global ops, such as `OpImageSample`. handle_id: Word, + /// Actual ID used to access this variable. /// For wrapped buffer variables, this ID is `OpAccessChain` into the /// wrapper. Otherwise, the same as `var_id`. diff --git a/src/lib.rs b/src/lib.rs index f384c6ea1..ac1118c06 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -652,7 +652,8 @@ pub enum TypeInner { /// An `Array` is [`SIZED`] unless its `size` is [`Dynamic`]. /// Dynamically-sized arrays may only appear in a few situations: /// - /// - They may appear as the last member of a [`Struct`]. + /// - They may appear as the type of a [`GlobalVariable`], or as the last + /// member of a [`Struct`]. /// /// - They may appear as the base type of a [`Pointer`]. An /// [`AccessIndex`] expression referring to a struct's final diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 23dabf1b1..e9f3fa77e 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -23,6 +23,7 @@ var float_vecs: array, 20>; fn main() { wg[3] = alignment.v1; wg[2] = alignment.v3.x; + wg[1] = f32(arrayLength(&dummy)); atomicStore(&at, 2u); // Valid, Foo and at is in function scope diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index a40e6bbac..46150907b 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -15,6 +15,8 @@ shared uint at_1; layout(std430) readonly buffer Foo_block_0Compute { Foo _group_0_binding_1_cs; }; +layout(std430) readonly buffer type_6_block_1Compute { vec2 _group_0_binding_2_cs[]; }; + void main() { float Foo_1 = 1.0; @@ -23,6 +25,7 @@ void main() { wg[3] = _e9; float _e14 = _group_0_binding_1_cs.v3_.x; wg[2] = _e14; + wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index a6b91c952..515ff1de6 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -11,6 +11,13 @@ ByteAddressBuffer alignment : register(t1); ByteAddressBuffer dummy : register(t2); cbuffer float_vecs : register(b3) { float4 float_vecs[20]; } +uint NagaBufferLength(ByteAddressBuffer buffer) +{ + uint ret; + buffer.GetDimensions(ret); + return ret; +} + [numthreads(1, 1, 1)] void main() { @@ -21,6 +28,7 @@ void main() wg[3] = _expr9; float _expr14 = asfloat(alignment.Load(0+0)); wg[2] = _expr14; + wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index c8c58b339..b56bc647d 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -23,6 +23,8 @@ kernel void main_( threadgroup type_2& wg , threadgroup metal::atomic_uint& at_1 , device Foo& alignment [[user(fake0)]] +, device type_6& dummy [[user(fake0)]] +, constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { float Foo_1 = 1.0; bool at = true; @@ -30,6 +32,7 @@ kernel void main_( wg.inner[3] = _e9; float _e14 = metal::float3(alignment.v3_).x; wg.inner[2] = _e14; + wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index ecc2805ef..bfba6116f 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,32 +1,32 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 61 +; Bound: 66 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %40 "main" -OpExecutionMode %40 LocalSize 1 1 1 -OpDecorate %15 ArrayStride 4 -OpMemberDecorate %17 0 Offset 0 -OpMemberDecorate %17 1 Offset 12 -OpDecorate %19 ArrayStride 8 -OpDecorate %21 ArrayStride 16 -OpDecorate %26 NonWritable -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 1 -OpDecorate %27 Block -OpMemberDecorate %27 0 Offset 0 -OpDecorate %29 NonWritable -OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 2 -OpDecorate %30 Block -OpMemberDecorate %30 0 Offset 0 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 3 -OpDecorate %33 Block -OpMemberDecorate %33 0 Offset 0 +OpEntryPoint GLCompute %41 "main" +OpExecutionMode %41 LocalSize 1 1 1 +OpDecorate %16 ArrayStride 4 +OpMemberDecorate %18 0 Offset 0 +OpMemberDecorate %18 1 Offset 12 +OpDecorate %20 ArrayStride 8 +OpDecorate %22 ArrayStride 16 +OpDecorate %27 NonWritable +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 1 +OpDecorate %28 Block +OpMemberDecorate %28 0 Offset 0 +OpDecorate %30 NonWritable +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 2 +OpDecorate %31 Block +OpMemberDecorate %31 0 Offset 0 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 3 +OpDecorate %34 Block +OpMemberDecorate %34 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -36,59 +36,65 @@ OpMemberDecorate %33 0 Offset 0 %7 = OpConstant %8 20 %9 = OpConstant %8 3 %10 = OpConstant %8 2 -%11 = OpConstant %6 2 -%13 = OpTypeFloat 32 -%12 = OpConstant %13 1.0 -%14 = OpConstantTrue %4 -%15 = OpTypeArray %13 %5 -%16 = OpTypeVector %13 3 -%17 = OpTypeStruct %16 %13 -%18 = OpTypeVector %13 2 -%19 = OpTypeRuntimeArray %18 -%20 = OpTypeVector %13 4 -%21 = OpTypeArray %20 %7 -%23 = OpTypePointer Workgroup %15 -%22 = OpVariable %23 Workgroup -%25 = OpTypePointer Workgroup %6 -%24 = OpVariable %25 Workgroup -%27 = OpTypeStruct %17 -%28 = OpTypePointer StorageBuffer %27 -%26 = OpVariable %28 StorageBuffer -%30 = OpTypeStruct %19 -%31 = OpTypePointer StorageBuffer %30 -%29 = OpVariable %31 StorageBuffer -%33 = OpTypeStruct %21 -%34 = OpTypePointer Uniform %33 -%32 = OpVariable %34 Uniform -%36 = OpTypePointer Function %13 -%38 = OpTypePointer Function %4 -%41 = OpTypeFunction %2 -%42 = OpTypePointer StorageBuffer %17 -%43 = OpConstant %6 0 -%45 = OpTypePointer StorageBuffer %19 -%46 = OpTypePointer Uniform %21 -%48 = OpTypePointer Workgroup %13 -%49 = OpTypePointer StorageBuffer %13 -%50 = OpConstant %6 1 -%53 = OpConstant %6 3 -%55 = OpTypePointer StorageBuffer %16 -%56 = OpTypePointer StorageBuffer %13 -%60 = OpConstant %6 256 -%40 = OpFunction %2 None %41 -%39 = OpLabel -%35 = OpVariable %36 Function %12 -%37 = OpVariable %38 Function %14 -%44 = OpAccessChain %42 %26 %43 -OpBranch %47 -%47 = OpLabel -%51 = OpAccessChain %49 %44 %50 -%52 = OpLoad %13 %51 -%54 = OpAccessChain %48 %22 %53 -OpStore %54 %52 -%57 = OpAccessChain %56 %44 %43 %43 -%58 = OpLoad %13 %57 -%59 = OpAccessChain %48 %22 %11 -OpStore %59 %58 -OpAtomicStore %24 %10 %60 %11 +%11 = OpConstant %8 1 +%12 = OpConstant %6 2 +%14 = OpTypeFloat 32 +%13 = OpConstant %14 1.0 +%15 = OpConstantTrue %4 +%16 = OpTypeArray %14 %5 +%17 = OpTypeVector %14 3 +%18 = OpTypeStruct %17 %14 +%19 = OpTypeVector %14 2 +%20 = OpTypeRuntimeArray %19 +%21 = OpTypeVector %14 4 +%22 = OpTypeArray %21 %7 +%24 = OpTypePointer Workgroup %16 +%23 = OpVariable %24 Workgroup +%26 = OpTypePointer Workgroup %6 +%25 = OpVariable %26 Workgroup +%28 = OpTypeStruct %18 +%29 = OpTypePointer StorageBuffer %28 +%27 = OpVariable %29 StorageBuffer +%31 = OpTypeStruct %20 +%32 = OpTypePointer StorageBuffer %31 +%30 = OpVariable %32 StorageBuffer +%34 = OpTypeStruct %22 +%35 = OpTypePointer Uniform %34 +%33 = OpVariable %35 Uniform +%37 = OpTypePointer Function %14 +%39 = OpTypePointer Function %4 +%42 = OpTypeFunction %2 +%43 = OpTypePointer StorageBuffer %18 +%44 = OpConstant %6 0 +%46 = OpTypePointer StorageBuffer %20 +%48 = OpTypePointer Uniform %22 +%50 = OpTypePointer Workgroup %14 +%51 = OpTypePointer StorageBuffer %14 +%52 = OpConstant %6 1 +%55 = OpConstant %6 3 +%57 = OpTypePointer StorageBuffer %17 +%58 = OpTypePointer StorageBuffer %14 +%65 = OpConstant %6 256 +%41 = OpFunction %2 None %42 +%40 = OpLabel +%36 = OpVariable %37 Function %13 +%38 = OpVariable %39 Function %15 +%45 = OpAccessChain %43 %27 %44 +%47 = OpAccessChain %46 %30 %44 +OpBranch %49 +%49 = OpLabel +%53 = OpAccessChain %51 %45 %52 +%54 = OpLoad %14 %53 +%56 = OpAccessChain %50 %23 %55 +OpStore %56 %54 +%59 = OpAccessChain %58 %45 %44 %44 +%60 = OpLoad %14 %59 +%61 = OpAccessChain %50 %23 %12 +OpStore %61 %60 +%62 = OpArrayLength %6 %30 0 +%63 = OpConvertUToF %14 %62 +%64 = OpAccessChain %50 %23 %52 +OpStore %64 %63 +OpAtomicStore %25 %10 %65 %12 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 3196468c5..f73c6c04d 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -23,6 +23,7 @@ fn main() { wg[3] = _e9; let _e14 = alignment.v3_.x; wg[2] = _e14; + wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); return; } From 8e2e39e4d8fa5bbb657c3b170b4f6607d703e284 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sat, 5 Feb 2022 23:58:01 -0500 Subject: [PATCH 1575/2212] msl: fix resource bindings for non-structures --- src/back/msl/writer.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index f341a38ff..4546309e9 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2884,10 +2884,9 @@ impl Writer { if let Some(ref br) = var.binding { let good = match options.per_stage_map[ep.stage].resources.get(br) { Some(target) => match module.types[var.ty].inner { - crate::TypeInner::Struct { .. } => target.buffer.is_some(), crate::TypeInner::Image { .. } => target.texture.is_some(), crate::TypeInner::Sampler { .. } => target.sampler.is_some(), - _ => false, + _ => target.buffer.is_some(), }, None => false, }; From 1f14f7ea2a17fcc9f1db75c6267cad7040ce9e3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 6 Feb 2022 18:07:55 +0000 Subject: [PATCH 1576/2212] glsl-in: Texture builtins fixes This one grew out of hand quick. Initially it was just replacing the bit loops with a function driving the declarations to make the code sharing better and support different scalar kinds. Now it includes a lot of fixes: - `textureSize` now also returns the array layers as the last component on the return (only for arrayed textures) - `textureSize` now supports multisampled textures - the `texture` family of functions now consumes a `vec3` coordinate vector for all 1D shadow textures - Shadow textures can use the bias version of `texture` functions (temporarily disabled since naga doesn't support it) - 3D textures can be used in `textureProj` - `sampler2DArrayShadow` can't be used in `textureLod` or in `texture` with bias - Cube textures cannot be used with offsets Updates the tests to cover all functions --- src/front/glsl/builtins.rs | 589 +++++++++---------- tests/in/glsl/samplers.frag | 81 ++- tests/out/wgsl/samplers-frag.wgsl | 947 ++++++++++++++++-------------- 3 files changed, 875 insertions(+), 742 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index d688ecad5..41c29ecb2 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -147,337 +147,219 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module | "textureProjLod" | "textureProjLodOffset" | "textureProjOffset" => { - // bits layout - // bits 0 through 1 - dims - // bit 2 - shadow - // bit 3 - array - // bit 4 - extra variant - // bit 5 - bias + let f = |kind, dim, arrayed, multi, shadow| { + for bits in 0..=0b11 { + let variant = bits & 0b1 != 0; + let bias = bits & 0b10 != 0; - for bits in 0..(0b1000000) { - let dim = bits & 0b11; - let shadow = bits & 0b100 == 0b100; - let arrayed = bits & 0b1000 == 0b1000; - let variant = bits & 0b10000 == 0b10000; - let bias = bits & 0b100000 == 0b100000; + let (proj, offset, level_type) = match name { + // texture(gsampler, gvec P, [float bias]); + "texture" => (false, false, TextureLevelType::None), + // textureGrad(gsampler, gvec P, gvec dPdx, gvec dPdy); + "textureGrad" => (false, false, TextureLevelType::Grad), + // textureGradOffset(gsampler, gvec P, gvec dPdx, gvec dPdy, ivec offset); + "textureGradOffset" => (false, true, TextureLevelType::Grad), + // textureLod(gsampler, gvec P, float lod); + "textureLod" => (false, false, TextureLevelType::Lod), + // textureLodOffset(gsampler, gvec P, float lod, ivec offset); + "textureLodOffset" => (false, true, TextureLevelType::Lod), + // textureOffset(gsampler, gvec+1 P, ivec offset, [float bias]); + "textureOffset" => (false, true, TextureLevelType::None), + // textureProj(gsampler, gvec+1 P, [float bias]); + "textureProj" => (true, false, TextureLevelType::None), + // textureProjGrad(gsampler, gvec+1 P, gvec dPdx, gvec dPdy); + "textureProjGrad" => (true, false, TextureLevelType::Grad), + // textureProjGradOffset(gsampler, gvec+1 P, gvec dPdx, gvec dPdy, ivec offset); + "textureProjGradOffset" => (true, true, TextureLevelType::Grad), + // textureProjLod(gsampler, gvec+1 P, float lod); + "textureProjLod" => (true, false, TextureLevelType::Lod), + // textureProjLodOffset(gsampler, gvec+1 P, gvec dPdx, gvec dPdy, ivec offset); + "textureProjLodOffset" => (true, true, TextureLevelType::Lod), + // textureProjOffset(gsampler, gvec+1 P, ivec offset, [float bias]); + "textureProjOffset" => (true, true, TextureLevelType::None), + _ => unreachable!(), + }; - let builtin = match name { - // texture(gsampler, gvec P, [float bias]); - "texture" => MacroCall::Texture { - proj: false, - offset: false, + let builtin = MacroCall::Texture { + proj, + offset, shadow, - level_type: TextureLevelType::None, - }, - // textureGrad(gsampler, gvec P, gvec dPdx, gvec dPdy); - "textureGrad" => MacroCall::Texture { - proj: false, - offset: false, - shadow, - level_type: TextureLevelType::Grad, - }, - // textureGradOffset(gsampler, gvec P, gvec dPdx, gvec dPdy, ivec offset); - "textureGradOffset" => MacroCall::Texture { - proj: false, - offset: true, - shadow, - level_type: TextureLevelType::Grad, - }, - // textureLod(gsampler, gvec P, float lod); - "textureLod" => MacroCall::Texture { - proj: false, - offset: false, - shadow, - level_type: TextureLevelType::Lod, - }, - // textureLodOffset(gsampler, gvec P, float lod, ivec offset); - "textureLodOffset" => MacroCall::Texture { - proj: false, - offset: true, - shadow, - level_type: TextureLevelType::Lod, - }, - // textureOffset(gsampler, gvec+1 P, ivec offset, [float bias]); - "textureOffset" => MacroCall::Texture { - proj: false, - offset: true, - shadow, - level_type: TextureLevelType::None, - }, - // textureProj(gsampler, gvec+1 P, [float bias]); - "textureProj" => MacroCall::Texture { - proj: true, - offset: false, - shadow, - level_type: TextureLevelType::None, - }, - // textureProjGrad(gsampler, gvec+1 P, gvec dPdx, gvec dPdy); - "textureProjGrad" => MacroCall::Texture { - proj: true, - offset: false, - shadow, - level_type: TextureLevelType::Grad, - }, - // textureProjGradOffset(gsampler, gvec+1 P, gvec dPdx, gvec dPdy, ivec offset); - "textureProjGradOffset" => MacroCall::Texture { - proj: true, - offset: true, - shadow, - level_type: TextureLevelType::Grad, - }, - // textureProjLod(gsampler, gvec+1 P, float lod); - "textureProjLod" => MacroCall::Texture { - proj: true, - offset: false, - shadow, - level_type: TextureLevelType::Lod, - }, - // textureProjLodOffset(gsampler, gvec+1 P, gvec dPdx, gvec dPdy, ivec offset); - "textureProjLodOffset" => MacroCall::Texture { - proj: true, - offset: true, - shadow, - level_type: TextureLevelType::Lod, - }, - // textureProjOffset(gsampler, gvec+1 P, ivec offset, [float bias]); - "textureProjOffset" => MacroCall::Texture { - proj: true, - offset: true, - shadow, - level_type: TextureLevelType::None, - }, - _ => unreachable!(), - }; + level_type, + }; - // Parse out the variant settings. - let proj = matches!(builtin, MacroCall::Texture { proj: true, .. }); - let grad = matches!( - builtin, - MacroCall::Texture { - level_type: TextureLevelType::Grad, - .. - } - ); - let lod = matches!( - builtin, - MacroCall::Texture { - level_type: TextureLevelType::Lod, - .. - } - ); - let offset = matches!(builtin, MacroCall::Texture { offset: true, .. }); + // Parse out the variant settings. + let grad = level_type == TextureLevelType::Grad; + let lod = level_type == TextureLevelType::Lod; - let supports_variant = proj && !shadow; - if variant && !supports_variant { - continue; - } - - let supports_bias = matches!( - builtin, - MacroCall::Texture { - level_type: TextureLevelType::None, - .. - } - ) && !shadow; - if bias && !supports_bias { - continue; - } - - // Proj doesn't work with arrayed, Cube or 3D samplers - if proj && (arrayed || dim == 0b10 || dim == 0b11) { - continue; - } - - // 3DArray and 3DShadow are not valid texture types - if dim == 0b11 && (arrayed || shadow) { - continue; - } - - // It seems that textureGradOffset(samplerCube) is not defined by GLSL for some reason... - if dim == 0b10 && grad && offset { - continue; - } - - let class = match shadow { - true => ImageClass::Depth { multi: false }, - false => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, - }; - - let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, - 0b10 => Dim::Cube, - _ => Dim::D3, - }, - arrayed, - class, - }; - - let num_coords_from_dim = (dim + 1).min(3); - let mut num_coords = num_coords_from_dim; - - if shadow && proj { - num_coords = 4; - } else if shadow { - num_coords += 1; - } else if proj { - if variant && num_coords == 4 { - // Normal form already has 4 components, no need to have a variant form. + let supports_variant = proj && !shadow; + if variant && !supports_variant { continue; - } else if variant { + } + + if bias && !matches!(level_type, TextureLevelType::None) { + continue; + } + + // Proj doesn't work with arrayed or Cube + if proj && (arrayed || dim == Dim::Cube) { + continue; + } + + // texture operations with offset are not supported for cube maps + if dim == Dim::Cube && offset { + continue; + } + + // sampler2DArrayShadow can't be used in textureLod or in texture with bias + if (lod || bias) && arrayed && shadow && dim == Dim::D2 { + continue; + } + + // TODO: glsl supports using bias with depth samplers but naga doesn't + if bias && shadow { + continue; + } + + let class = match shadow { + true => ImageClass::Depth { multi }, + false => ImageClass::Sampled { kind, multi }, + }; + + let image = TypeInner::Image { + dim, + arrayed, + class, + }; + + let dim_value = image_dims_to_coords_size(dim); + let num_coords_from_dim = (dim_value + 1).min(3); + let mut num_coords = num_coords_from_dim; + + if shadow && proj { num_coords = 4; - } else { + } else if dim == Dim::D1 && shadow { + num_coords = 3; + } else if shadow { num_coords += 1; + } else if proj { + if variant && num_coords == 4 { + // Normal form already has 4 components, no need to have a variant form. + continue; + } else if variant { + num_coords = 4; + } else { + num_coords += 1; + } } - } - num_coords += arrayed as usize; - - // Special case: texture(gsamplerCubeArrayShadow) kicks the shadow compare ref to a separate argument, - // since it would otherwise take five arguments. It also can't take a bias, nor can it be proj/grad/lod/offset - // (presumably because nobody asked for it, and implementation complexity?) - if num_coords >= 5 { - if lod || grad || offset || proj || bias { - continue; + if !(dim == Dim::D1 && shadow) { + num_coords += arrayed as usize; } - debug_assert!(dim == 0b10 && shadow && arrayed); - } - debug_assert!(num_coords <= 5); - let vector = make_coords_arg(num_coords, Sk::Float); - let mut args = vec![image, vector]; + // Special case: texture(gsamplerCubeArrayShadow) kicks the shadow compare ref to a separate argument, + // since it would otherwise take five arguments. It also can't take a bias, nor can it be proj/grad/lod/offset + // (presumably because nobody asked for it, and implementation complexity?) + if num_coords >= 5 { + if lod || grad || offset || proj || bias { + continue; + } + debug_assert!(dim == ImageDimension::Cube && shadow && arrayed); + } + debug_assert!(num_coords <= 5); - if num_coords == 5 { - args.push(TypeInner::Scalar { - kind: Sk::Float, - width, - }); - } + let vector = make_coords_arg(num_coords, Sk::Float); + let mut args = vec![image, vector]; - match builtin { - MacroCall::Texture { - level_type: TextureLevelType::Lod, - .. - } => { + if num_coords == 5 { args.push(TypeInner::Scalar { kind: Sk::Float, width, }); } - MacroCall::Texture { - level_type: TextureLevelType::Grad, - .. - } => { - args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); - args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); + + match level_type { + TextureLevelType::Lod => { + args.push(TypeInner::Scalar { + kind: Sk::Float, + width, + }); + } + TextureLevelType::Grad => { + args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); + args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); + } + _ => {} + }; + + if offset { + args.push(make_coords_arg(num_coords_from_dim, Sk::Sint)); } - _ => {} - }; - if offset { - args.push(make_coords_arg(num_coords_from_dim, Sk::Sint)); + if bias { + args.push(TypeInner::Scalar { + kind: Sk::Float, + width, + }); + } + + declaration + .overloads + .push(module.add_builtin(args, builtin)); } + }; - if bias { - args.push(TypeInner::Scalar { - kind: Sk::Float, - width, - }); - } - - declaration - .overloads - .push(module.add_builtin(args, builtin)); - } + texture_args_generator(TextureArgsOptions::SHADOW, f) } "textureSize" => { - // bits layout - // bits 0 trough 1 - dims - // bit 2 - shadow - // bit 3 - array - for bits in 0..(0b10000) { - let dim = bits & 0b11; - let shadow = bits & 0b100 == 0b100; - let arrayed = bits & 0b1000 == 0b1000; - - // Shadow, arrayed or both 3D images are not allowed - if (shadow || arrayed) && dim == 0b11 { - continue; - } - + let f = |kind, dim, arrayed, multi, shadow| { let class = match shadow { - true => ImageClass::Depth { multi: false }, - false => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, + true => ImageClass::Depth { multi }, + false => ImageClass::Sampled { kind, multi }, }; let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, - 0b10 => Dim::Cube, - _ => Dim::D3, - }, + dim, arrayed, class, }; - let args = vec![ - image, - TypeInner::Scalar { + let mut args = vec![image]; + + if !multi { + args.push(TypeInner::Scalar { kind: Sk::Sint, width, - }, - ]; + }) + } declaration .overloads - .push(module.add_builtin(args, MacroCall::TextureSize)) - } + .push(module.add_builtin(args, MacroCall::TextureSize { arrayed })) + }; + + texture_args_generator(TextureArgsOptions::all(), f) } "texelFetch" => { - // bits layout - // bit 0 - array - // bit 1 - multisample - // bits 2 trough 3 - dims - // - // 0b1000 is the latest since 3D images aren't allowed to be multisampled or arrayed - for bits in 0..=(0b1000) { - let arrayed = bits & 0b1 != 0; - let multi = bits & 0b10 != 0; - let dim = bits >> 2; - - // Multisampled 1d images don't exist - if dim == 0b00 && multi { - continue; + let f = |kind, dim, arrayed, multi, _| { + // Cube images aren't supported + if let Dim::Cube = dim { + return; } let image = TypeInner::Image { - dim: match dim { - 0b00 => Dim::D1, - 0b01 => Dim::D2, - _ => Dim::D3, - }, + dim, arrayed, - class: ImageClass::Sampled { - kind: Sk::Float, - multi, - }, + class: ImageClass::Sampled { kind, multi }, }; - let vector = match (dim, arrayed) { - (0b00, false) => TypeInner::Scalar { + let coordinates = match (dim, arrayed) { + (Dim::D1, false) => TypeInner::Scalar { kind: Sk::Sint, width, }, - (_, _) => { - let size = match dim + arrayed as u32 { + _ => { + let dim_value = image_dims_to_coords_size(dim); + let size = match dim_value + arrayed as usize { 1 => VectorSize::Bi, 2 => VectorSize::Tri, _ => VectorSize::Quad, @@ -493,7 +375,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module let args = vec![ image, - vector, + coordinates, TypeInner::Scalar { kind: Sk::Sint, width, @@ -503,7 +385,10 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module declaration .overloads .push(module.add_builtin(args, MacroCall::TexelFetch)) - } + }; + + // Don't generate shadow images since they aren't supported + texture_args_generator(TextureArgsOptions::MULTI, f) } "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" | "log" | "log2" | "radians" | "degrees" | "asinh" | "acosh" | "atanh" @@ -1546,7 +1431,9 @@ pub enum MacroCall { shadow: bool, level_type: TextureLevelType, }, - TextureSize, + TextureSize { + arrayed: bool, + }, TexelFetch, MathFunction(MathFunction), BitfieldExtract, @@ -1706,16 +1593,69 @@ impl MacroCall { texture_call(ctx, args[0], level, comps, texture_offset, body, meta) } - MacroCall::TextureSize => Ok(ctx.add_expression( - Expression::ImageQuery { - image: args[0], - query: ImageQuery::Size { - level: args.get(1).copied(), + + MacroCall::TextureSize { arrayed } => { + let mut expr = ctx.add_expression( + Expression::ImageQuery { + image: args[0], + query: ImageQuery::Size { + level: args.get(1).copied(), + }, }, - }, - Span::default(), - body, - )), + Span::default(), + body, + ); + + if arrayed { + let mut components = Vec::with_capacity(4); + + let size = match *parser.resolve_type(ctx, expr, meta)? { + TypeInner::Vector { size: ori_size, .. } => { + for index in 0..(ori_size as u32) { + components.push(ctx.add_expression( + Expression::AccessIndex { base: expr, index }, + Span::default(), + body, + )) + } + + match ori_size { + VectorSize::Bi => VectorSize::Tri, + _ => VectorSize::Quad, + } + } + _ => { + components.push(expr); + VectorSize::Bi + } + }; + + components.push(ctx.add_expression( + Expression::ImageQuery { + image: args[0], + query: ImageQuery::NumLayers, + }, + Span::default(), + body, + )); + + let ty = parser.module.types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size, + kind: crate::ScalarKind::Sint, + width: 4, + }, + }, + Span::default(), + ); + + expr = ctx.add_expression(Expression::Compose { components, ty }, meta, body) + } + + Ok(expr) + } MacroCall::TexelFetch => { let comps = parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; @@ -2099,3 +2039,64 @@ pub fn sampled_to_depth( }), }; } + +bitflags::bitflags! { + /// Influences the operation `texture_args_generator` + struct TextureArgsOptions: u32 { + /// Generates multisampled variants of images + const MULTI = 0; + /// Generates shadow variants of images + const SHADOW = 1; + } +} + +/// Helper function to generate the image components for texture/image builtins +/// +/// Calls the passed function `f` with: +/// ```text +/// f(ScalarKind, ImageDimension, arrayed, multi, shadow) +/// ``` +/// +/// `options` controls extra image variants generation like multisampling and depth, +/// see the struct documentation +fn texture_args_generator( + options: TextureArgsOptions, + mut f: impl FnMut(crate::ScalarKind, ImageDimension, bool, bool, bool), +) { + use crate::ImageDimension as Dim; + + for kind in [Sk::Float, Sk::Uint, Sk::Sint].iter().copied() { + for dim in [Dim::D1, Dim::D2, Dim::D3, Dim::Cube].iter().copied() { + for arrayed in [false, true].iter().copied() { + f(kind, dim, arrayed, false, false); + + // 3D images can't be neither arrayed nor shadow + // so we break out early, this way arrayed will always + // be false and we won't hit the shadow branch + if let Dim::D3 = dim { + break; + } + + if Dim::D2 == dim && options.contains(TextureArgsOptions::MULTI) { + // multisampling + f(kind, dim, arrayed, true, false); + } + + if Sk::Float == kind && options.contains(TextureArgsOptions::SHADOW) { + // shadow + f(kind, dim, arrayed, false, true); + } + } + } + } +} + +/// Helper functions used to convert from a image dimension into a integer representing the +/// number of components needed for the coordinates vector (0 means scalar instead of vector) +fn image_dims_to_coords_size(dim: ImageDimension) -> usize { + match dim { + ImageDimension::D1 => 0, + ImageDimension::D2 => 1, + _ => 2, + } +} diff --git a/tests/in/glsl/samplers.frag b/tests/in/glsl/samplers.frag index c3f6484c2..1a3421600 100644 --- a/tests/in/glsl/samplers.frag +++ b/tests/in/glsl/samplers.frag @@ -25,6 +25,9 @@ layout(set = 1, binding = 15) uniform textureCubeArray texCubeArrayShadow; layout(set = 1, binding = 16) uniform texture3D tex3DShadow; layout(set = 1, binding = 17) uniform samplerShadow sampShadow; +layout(binding = 18) uniform texture2DMS tex2DMS; +layout(binding = 19) uniform texture2DMSArray tex2DMSArray; + // Conventions for readability: // 1.0 = Shadow Ref // 2.0 = LOD Bias @@ -34,6 +37,7 @@ layout(set = 1, binding = 17) uniform samplerShadow sampShadow; // 6.0 = Proj W void testTex1D(in float coord) { + int size1D = textureSize(sampler1D(tex1D, samp), 0); vec4 c; c = texture(sampler1D(tex1D, samp), coord); c = texture(sampler1D(tex1D, samp), coord, 2.0); @@ -59,27 +63,35 @@ void testTex1D(in float coord) { c = textureProjOffset(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 5); c = textureProjOffset(sampler1D(tex1D, samp), vec2(coord, 6.0), 5, 2.0); c = textureProjOffset(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 5, 2.0); + c = texelFetch(sampler1D(tex1D, samp), int(coord), 3); + // c = texelFetchOffset(sampler1D(tex1D, samp), int(coord), 3, 5); } #if HAS_1D_DEPTH_TEXTURES void testTex1DShadow(float coord) { + int size1DShadow = textureSize(sampler1DShadow(tex1DShadow, sampShadow), 0); float d; - d = texture(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0)); - d = textureGrad(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 4.0, 4.0); - d = textureGradOffset(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 4.0, 4.0, 5); - d = textureLod(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 3.0); - d = textureLodOffset(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 3.0, 5); - d = textureOffset(sampler1DShadow(tex1DShadow, sampShadow), vec2(coord, 1.0), 5); + d = texture(sampler1DShadow(tex1DShadow, sampShadow), vec3(coord, 1.0, 1.0)); + // d = texture(sampler1DShadow(tex1DShadow, sampShadow), vec3(coord, 1.0, 1.0), 2.0); + d = textureGrad(sampler1DShadow(tex1DShadow, sampShadow), vec3(coord, 1.0, 1.0), 4.0, 4.0); + d = textureGradOffset(sampler1DShadow(tex1DShadow, sampShadow), vec3(coord, 1.0, 1.0), 4.0, 4.0, 5); + d = textureLod(sampler1DShadow(tex1DShadow, sampShadow), vec3(coord, 1.0, 1.0), 3.0); + d = textureLodOffset(sampler1DShadow(tex1DShadow, sampShadow), vec3(coord, 1.0, 1.0), 3.0, 5); + d = textureOffset(sampler1DShadow(tex1DShadow, sampShadow), vec3(coord, 1.0, 1.0), 5); + // d = textureOffset(sampler1DShadow(tex1DShadow, sampShadow), vec3(coord, 1.0, 1.0), 5, 2.0); d = textureProj(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0)); + // d = textureProj(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 2.0); d = textureProjGrad(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 4.0, 4.0); d = textureProjGradOffset(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 4.0, 4.0, 5); d = textureProjLod(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 3.0); d = textureProjLodOffset(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 3.0, 5); d = textureProjOffset(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 5); + // d = textureProjOffset(sampler1DShadow(tex1DShadow, sampShadow), vec4(coord, 0.0, 1.0, 6.0), 5, 2.0); } #endif void testTex1DArray(in vec2 coord) { + ivec2 size1DArray = textureSize(sampler1DArray(tex1DArray, samp), 0); vec4 c; c = texture(sampler1DArray(tex1DArray, samp), coord); c = texture(sampler1DArray(tex1DArray, samp), coord, 2.0); @@ -89,10 +101,13 @@ void testTex1DArray(in vec2 coord) { c = textureLodOffset(sampler1DArray(tex1DArray, samp), coord, 3.0, 5); c = textureOffset(sampler1DArray(tex1DArray, samp), coord, 5); c = textureOffset(sampler1DArray(tex1DArray, samp), coord, 5, 2.0); + c = texelFetch(sampler1DArray(tex1DArray, samp), ivec2(coord), 3); + // c = texelFetchOffset(sampler1DArray(tex1DArray, samp), ivec2(coord), 3, 5); } #if HAS_1D_DEPTH_TEXTURES void testTex1DArrayShadow(in vec2 coord) { + ivec2 size1DArrayShadow = textureSize(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), 0); float d; d = texture(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0)); d = textureGrad(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 4.0, 4.0); @@ -100,10 +115,12 @@ void testTex1DArrayShadow(in vec2 coord) { d = textureLod(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 3.0); d = textureLodOffset(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 3.0, 5); d = textureOffset(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 5); + // d = textureOffset(sampler1DArrayShadow(tex1DArrayShadow, sampShadow), vec3(coord, 1.0), 5, 2.0); } #endif void testTex2D(in vec2 coord) { + ivec2 size2D = textureSize(sampler2D(tex2D, samp), 0); vec4 c; c = texture(sampler2D(tex2D, samp), coord); c = texture(sampler2D(tex2D, samp), coord, 2.0); @@ -129,25 +146,33 @@ void testTex2D(in vec2 coord) { c = textureProjOffset(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), ivec2(5)); c = textureProjOffset(sampler2D(tex2D, samp), vec3(coord, 6.0), ivec2(5), 2.0); c = textureProjOffset(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), ivec2(5), 2.0); + c = texelFetch(sampler2D(tex2D, samp), ivec2(coord), 3); + // c = texelFetchOffset(sampler2D(tex2D, samp), ivec2(coord), 3, ivec2(5)); } void testTex2DShadow(vec2 coord) { + ivec2 size2DShadow = textureSize(sampler2DShadow(tex2DShadow, sampShadow), 0); float d; d = texture(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0)); + // d = texture(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), 2.0); d = textureGrad(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), vec2(4.0), vec2(4.0)); d = textureGradOffset(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), vec2(4.0), vec2(4.0), ivec2(5)); d = textureLod(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), 3.0); d = textureLodOffset(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), 3.0, ivec2(5)); d = textureOffset(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), ivec2(5)); + // d = textureOffset(sampler2DShadow(tex2DShadow, sampShadow), vec3(coord, 1.0), ivec2(5), 2.0); d = textureProj(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0)); + // d = textureProj(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), 2.0); d = textureProjGrad(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), vec2(4.0), vec2(4.0)); d = textureProjGradOffset(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), vec2(4.0), vec2(4.0), ivec2(5)); d = textureProjLod(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), 3.0); d = textureProjLodOffset(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), 3.0, ivec2(5)); d = textureProjOffset(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), ivec2(5)); + // d = textureProjOffset(sampler2DShadow(tex2DShadow, sampShadow), vec4(coord, 1.0, 6.0), ivec2(5), 2.0); } void testTex2DArray(in vec3 coord) { + ivec3 size2DArray = textureSize(sampler2DArray(tex2DArray, samp), 0); vec4 c; c = texture(sampler2DArray(tex2DArray, samp), coord); c = texture(sampler2DArray(tex2DArray, samp), coord, 2.0); @@ -157,68 +182,84 @@ void testTex2DArray(in vec3 coord) { c = textureLodOffset(sampler2DArray(tex2DArray, samp), coord, 3.0, ivec2(5)); c = textureOffset(sampler2DArray(tex2DArray, samp), coord, ivec2(5)); c = textureOffset(sampler2DArray(tex2DArray, samp), coord, ivec2(5), 2.0); + c = texelFetch(sampler2DArray(tex2DArray, samp), ivec3(coord), 3); + // c = texelFetchOffset(sampler2DArray(tex2DArray, samp), ivec3(coord), 3, ivec2(5)); } void testTex2DArrayShadow(in vec3 coord) { + ivec3 size2DArrayShadow = textureSize(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), 0); float d; d = texture(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0)); d = textureGrad(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), vec2(4.0), vec2(4.0)); d = textureGradOffset(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), vec2(4.0), vec2(4.0), ivec2(5)); - d = textureLod(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), 3.0); - d = textureLodOffset(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), 3.0, ivec2(5)); d = textureOffset(sampler2DArrayShadow(tex2DArrayShadow, sampShadow), vec4(coord, 1.0), ivec2(5)); } void testTexCube(in vec3 coord) { + ivec2 sizeCube = textureSize(samplerCube(texCube, samp), 0); vec4 c; c = texture(samplerCube(texCube, samp), coord); c = texture(samplerCube(texCube, samp), coord, 2.0); c = textureGrad(samplerCube(texCube, samp), coord, vec3(4.0), vec3(4.0)); c = textureLod(samplerCube(texCube, samp), coord, 3.0); - c = textureLodOffset(samplerCube(texCube, samp), coord, 3.0, ivec3(5)); - c = textureOffset(samplerCube(texCube, samp), coord, ivec3(5)); - c = textureOffset(samplerCube(texCube, samp), coord, ivec3(5), 2.0); } void testTexCubeShadow(in vec3 coord) { + ivec2 sizeCubeShadow = textureSize(samplerCubeShadow(texCubeShadow, sampShadow), 0); float d; d = texture(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0)); d = textureGrad(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0), vec3(4.0), vec3(4.0)); - d = textureLod(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0), 3.0); - d = textureLodOffset(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0), 3.0, ivec3(5)); - d = textureOffset(samplerCubeShadow(texCubeShadow, sampShadow), vec4(coord, 1.0), ivec3(5)); } void testTexCubeArray(in vec4 coord) { + ivec3 sizeCubeArray = textureSize(samplerCubeArray(texCubeArray, samp), 0); vec4 c; c = texture(samplerCubeArray(texCubeArray, samp), coord); c = texture(samplerCubeArray(texCubeArray, samp), coord, 2.0); c = textureGrad(samplerCubeArray(texCubeArray, samp), coord, vec3(4.0), vec3(4.0)); c = textureLod(samplerCubeArray(texCubeArray, samp), coord, 3.0); - c = textureLodOffset(samplerCubeArray(texCubeArray, samp), coord, 3.0, ivec3(5)); - c = textureOffset(samplerCubeArray(texCubeArray, samp), coord, ivec3(5)); - c = textureOffset(samplerCubeArray(texCubeArray, samp), coord, ivec3(5), 2.0); } void testTexCubeArrayShadow(in vec4 coord) { + ivec3 sizeCubeArrayShadow = textureSize(samplerCubeArrayShadow(texCubeArrayShadow, sampShadow), 0); float d; d = texture(samplerCubeArrayShadow(texCubeArrayShadow, sampShadow), coord, 1.0); // The rest of the variants aren't defined by GLSL. } void testTex3D(in vec3 coord) { + ivec3 size3D = textureSize(sampler3D(tex3D, samp), 0); vec4 c; c = texture(sampler3D(tex3D, samp), coord); c = texture(sampler3D(tex3D, samp), coord, 2.0); + c = textureProj(sampler3D(tex3D, samp), vec4(coord, 6.0)); + c = textureProj(sampler3D(tex3D, samp), vec4(coord, 6.0), 2.0); + c = textureProjOffset(sampler3D(tex3D, samp), vec4(coord, 6.0), ivec3(5)); + c = textureProjOffset(sampler3D(tex3D, samp), vec4(coord, 6.0), ivec3(5), 2.0); + c = textureProjLod(sampler3D(tex3D, samp), vec4(coord, 6.0), 3.0); + c = textureProjLodOffset(sampler3D(tex3D, samp), vec4(coord, 6.0), 3.0, ivec3(5)); + c = textureProjGrad(sampler3D(tex3D, samp), vec4(coord, 6.0), vec3(4.0), vec3(4.0)); + c = textureProjGradOffset(sampler3D(tex3D, samp), vec4(coord, 6.0), vec3(4.0), vec3(4.0), ivec3(5)); c = textureGrad(sampler3D(tex3D, samp), coord, vec3(4.0), vec3(4.0)); c = textureGradOffset(sampler3D(tex3D, samp), coord, vec3(4.0), vec3(4.0), ivec3(5)); c = textureLod(sampler3D(tex3D, samp), coord, 3.0); c = textureLodOffset(sampler3D(tex3D, samp), coord, 3.0, ivec3(5)); c = textureOffset(sampler3D(tex3D, samp), coord, ivec3(5)); c = textureOffset(sampler3D(tex3D, samp), coord, ivec3(5), 2.0); + c = texelFetch(sampler3D(tex3D, samp), ivec3(coord), 3); + // c = texelFetchOffset(sampler3D(tex3D, samp), ivec3(coord), 3, ivec3(5)); } -layout(location = 0) in vec4 texcoord; - -void main() { +void testTex2DMS(in vec2 coord) { + ivec2 size2DMS = textureSize(sampler2DMS(tex2DMS, samp)); + vec4 c; + c = texelFetch(sampler2DMS(tex2DMS, samp), ivec2(coord), 3); } + +void testTex2DMSArray(in vec3 coord) { + ivec3 size2DMSArray = textureSize(sampler2DMSArray(tex2DMSArray, samp)); + vec4 c; + c = texelFetch(sampler2DMSArray(tex2DMSArray, samp), ivec3(coord), 3); +} + +void main() {} diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index f4ec16972..3e5eb5955 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -26,539 +26,631 @@ var texCubeArrayShadow: texture_depth_cube_array; var tex3DShadow: texture_3d; @group(1) @binding(17) var sampShadow: sampler_comparison; -var texcoord_1: vec4; +@group(0) @binding(18) +var tex2DMS: texture_multisampled_2d; +@group(0) @binding(19) +var tex2DMSArray: texture_multisampled_2d_array; fn testTex1D(coord: f32) { var coord_1: f32; + var size1D: i32; var c: vec4; coord_1 = coord; - let _e18 = coord_1; - let _e19 = textureSample(tex1D, samp, _e18); - c = _e19; - let _e22 = coord_1; - let _e24 = textureSampleBias(tex1D, samp, _e22, 2.0); - c = _e24; + let _e20 = textureDimensions(tex1D, 0); + size1D = _e20; + let _e24 = coord_1; + let _e25 = textureSample(tex1D, samp, _e24); + c = _e25; let _e28 = coord_1; - let _e31 = textureSampleGrad(tex1D, samp, _e28, 4.0, 4.0); - c = _e31; - let _e36 = coord_1; - let _e40 = textureSampleGrad(tex1D, samp, _e36, 4.0, 4.0, 5); - c = _e40; - let _e43 = coord_1; - let _e45 = textureSampleLevel(tex1D, samp, _e43, 3.0); - c = _e45; + let _e30 = textureSampleBias(tex1D, samp, _e28, 2.0); + c = _e30; + let _e34 = coord_1; + let _e37 = textureSampleGrad(tex1D, samp, _e34, 4.0, 4.0); + c = _e37; + let _e42 = coord_1; + let _e46 = textureSampleGrad(tex1D, samp, _e42, 4.0, 4.0, 5); + c = _e46; let _e49 = coord_1; - let _e52 = textureSampleLevel(tex1D, samp, _e49, 3.0, 5); - c = _e52; + let _e51 = textureSampleLevel(tex1D, samp, _e49, 3.0); + c = _e51; let _e55 = coord_1; - let _e57 = textureSample(tex1D, samp, _e55, 5); - c = _e57; + let _e58 = textureSampleLevel(tex1D, samp, _e55, 3.0, 5); + c = _e58; let _e61 = coord_1; - let _e64 = textureSampleBias(tex1D, samp, _e61, 2.0, 5); - c = _e64; - let _e65 = coord_1; - let _e68 = coord_1; - let _e70 = vec2(_e68, 6.0); - let _e74 = textureSample(tex1D, samp, (_e70.x / _e70.y)); - c = _e74; - let _e75 = coord_1; - let _e80 = coord_1; - let _e84 = vec4(_e80, 0.0, 0.0, 6.0); - let _e90 = textureSample(tex1D, samp, (_e84.xyz / vec3(_e84.w)).x); - c = _e90; - let _e91 = coord_1; - let _e95 = coord_1; - let _e97 = vec2(_e95, 6.0); - let _e102 = textureSampleBias(tex1D, samp, (_e97.x / _e97.y), 2.0); - c = _e102; - let _e103 = coord_1; + let _e63 = textureSample(tex1D, samp, _e61, 5); + c = _e63; + let _e67 = coord_1; + let _e70 = textureSampleBias(tex1D, samp, _e67, 2.0, 5); + c = _e70; + let _e71 = coord_1; + let _e74 = coord_1; + let _e76 = vec2(_e74, 6.0); + let _e80 = textureSample(tex1D, samp, (_e76.x / _e76.y)); + c = _e80; + let _e81 = coord_1; + let _e86 = coord_1; + let _e90 = vec4(_e86, 0.0, 0.0, 6.0); + let _e96 = textureSample(tex1D, samp, (_e90.xyz / vec3(_e90.w)).x); + c = _e96; + let _e97 = coord_1; + let _e101 = coord_1; + let _e103 = vec2(_e101, 6.0); + let _e108 = textureSampleBias(tex1D, samp, (_e103.x / _e103.y), 2.0); + c = _e108; let _e109 = coord_1; - let _e113 = vec4(_e109, 0.0, 0.0, 6.0); - let _e120 = textureSampleBias(tex1D, samp, (_e113.xyz / vec3(_e113.w)).x, 2.0); - c = _e120; - let _e121 = coord_1; - let _e126 = coord_1; - let _e128 = vec2(_e126, 6.0); - let _e134 = textureSampleGrad(tex1D, samp, (_e128.x / _e128.y), 4.0, 4.0); - c = _e134; - let _e135 = coord_1; - let _e142 = coord_1; - let _e146 = vec4(_e142, 0.0, 0.0, 6.0); - let _e154 = textureSampleGrad(tex1D, samp, (_e146.xyz / vec3(_e146.w)).x, 4.0, 4.0); - c = _e154; - let _e155 = coord_1; + let _e115 = coord_1; + let _e119 = vec4(_e115, 0.0, 0.0, 6.0); + let _e126 = textureSampleBias(tex1D, samp, (_e119.xyz / vec3(_e119.w)).x, 2.0); + c = _e126; + let _e127 = coord_1; + let _e132 = coord_1; + let _e134 = vec2(_e132, 6.0); + let _e140 = textureSampleGrad(tex1D, samp, (_e134.x / _e134.y), 4.0, 4.0); + c = _e140; + let _e141 = coord_1; + let _e148 = coord_1; + let _e152 = vec4(_e148, 0.0, 0.0, 6.0); + let _e160 = textureSampleGrad(tex1D, samp, (_e152.xyz / vec3(_e152.w)).x, 4.0, 4.0); + c = _e160; let _e161 = coord_1; - let _e163 = vec2(_e161, 6.0); - let _e170 = textureSampleGrad(tex1D, samp, (_e163.x / _e163.y), 4.0, 4.0, 5); - c = _e170; - let _e171 = coord_1; - let _e179 = coord_1; - let _e183 = vec4(_e179, 0.0, 0.0, 6.0); - let _e192 = textureSampleGrad(tex1D, samp, (_e183.xyz / vec3(_e183.w)).x, 4.0, 4.0, 5); - c = _e192; - let _e193 = coord_1; - let _e197 = coord_1; - let _e199 = vec2(_e197, 6.0); - let _e204 = textureSampleLevel(tex1D, samp, (_e199.x / _e199.y), 3.0); - c = _e204; - let _e205 = coord_1; + let _e167 = coord_1; + let _e169 = vec2(_e167, 6.0); + let _e176 = textureSampleGrad(tex1D, samp, (_e169.x / _e169.y), 4.0, 4.0, 5); + c = _e176; + let _e177 = coord_1; + let _e185 = coord_1; + let _e189 = vec4(_e185, 0.0, 0.0, 6.0); + let _e198 = textureSampleGrad(tex1D, samp, (_e189.xyz / vec3(_e189.w)).x, 4.0, 4.0, 5); + c = _e198; + let _e199 = coord_1; + let _e203 = coord_1; + let _e205 = vec2(_e203, 6.0); + let _e210 = textureSampleLevel(tex1D, samp, (_e205.x / _e205.y), 3.0); + c = _e210; let _e211 = coord_1; - let _e215 = vec4(_e211, 0.0, 0.0, 6.0); - let _e222 = textureSampleLevel(tex1D, samp, (_e215.xyz / vec3(_e215.w)).x, 3.0); - c = _e222; - let _e223 = coord_1; - let _e228 = coord_1; - let _e230 = vec2(_e228, 6.0); - let _e236 = textureSampleLevel(tex1D, samp, (_e230.x / _e230.y), 3.0, 5); - c = _e236; - let _e237 = coord_1; - let _e244 = coord_1; - let _e248 = vec4(_e244, 0.0, 0.0, 6.0); - let _e256 = textureSampleLevel(tex1D, samp, (_e248.xyz / vec3(_e248.w)).x, 3.0, 5); - c = _e256; - let _e257 = coord_1; - let _e261 = coord_1; - let _e263 = vec2(_e261, 6.0); - let _e268 = textureSample(tex1D, samp, (_e263.x / _e263.y), 5); - c = _e268; - let _e269 = coord_1; + let _e217 = coord_1; + let _e221 = vec4(_e217, 0.0, 0.0, 6.0); + let _e228 = textureSampleLevel(tex1D, samp, (_e221.xyz / vec3(_e221.w)).x, 3.0); + c = _e228; + let _e229 = coord_1; + let _e234 = coord_1; + let _e236 = vec2(_e234, 6.0); + let _e242 = textureSampleLevel(tex1D, samp, (_e236.x / _e236.y), 3.0, 5); + c = _e242; + let _e243 = coord_1; + let _e250 = coord_1; + let _e254 = vec4(_e250, 0.0, 0.0, 6.0); + let _e262 = textureSampleLevel(tex1D, samp, (_e254.xyz / vec3(_e254.w)).x, 3.0, 5); + c = _e262; + let _e263 = coord_1; + let _e267 = coord_1; + let _e269 = vec2(_e267, 6.0); + let _e274 = textureSample(tex1D, samp, (_e269.x / _e269.y), 5); + c = _e274; let _e275 = coord_1; - let _e279 = vec4(_e275, 0.0, 0.0, 6.0); - let _e286 = textureSample(tex1D, samp, (_e279.xyz / vec3(_e279.w)).x, 5); - c = _e286; - let _e287 = coord_1; - let _e292 = coord_1; - let _e294 = vec2(_e292, 6.0); - let _e300 = textureSampleBias(tex1D, samp, (_e294.x / _e294.y), 2.0, 5); - c = _e300; - let _e301 = coord_1; - let _e308 = coord_1; - let _e312 = vec4(_e308, 0.0, 0.0, 6.0); - let _e320 = textureSampleBias(tex1D, samp, (_e312.xyz / vec3(_e312.w)).x, 2.0, 5); - c = _e320; + let _e281 = coord_1; + let _e285 = vec4(_e281, 0.0, 0.0, 6.0); + let _e292 = textureSample(tex1D, samp, (_e285.xyz / vec3(_e285.w)).x, 5); + c = _e292; + let _e293 = coord_1; + let _e298 = coord_1; + let _e300 = vec2(_e298, 6.0); + let _e306 = textureSampleBias(tex1D, samp, (_e300.x / _e300.y), 2.0, 5); + c = _e306; + let _e307 = coord_1; + let _e314 = coord_1; + let _e318 = vec4(_e314, 0.0, 0.0, 6.0); + let _e326 = textureSampleBias(tex1D, samp, (_e318.xyz / vec3(_e318.w)).x, 2.0, 5); + c = _e326; + let _e327 = coord_1; + let _e330 = coord_1; + let _e333 = textureLoad(tex1D, i32(_e330), 3); + c = _e333; return; } fn testTex1DArray(coord_2: vec2) { var coord_3: vec2; + var size1DArray: vec2; var c_1: vec4; coord_3 = coord_2; - let _e18 = coord_3; - let _e22 = textureSample(tex1DArray, samp, _e18.x, i32(_e18.y)); - c_1 = _e22; - let _e25 = coord_3; - let _e30 = textureSampleBias(tex1DArray, samp, _e25.x, i32(_e25.y), 2.0); + let _e20 = textureDimensions(tex1DArray, 0); + let _e21 = textureNumLayers(tex1DArray); + size1DArray = vec2(_e20, _e21); + let _e26 = coord_3; + let _e30 = textureSample(tex1DArray, samp, _e26.x, i32(_e26.y)); c_1 = _e30; - let _e34 = coord_3; - let _e40 = textureSampleGrad(tex1DArray, samp, _e34.x, i32(_e34.y), 4.0, 4.0); - c_1 = _e40; - let _e45 = coord_3; - let _e52 = textureSampleGrad(tex1DArray, samp, _e45.x, i32(_e45.y), 4.0, 4.0, 5); - c_1 = _e52; - let _e55 = coord_3; - let _e60 = textureSampleLevel(tex1DArray, samp, _e55.x, i32(_e55.y), 3.0); + let _e33 = coord_3; + let _e38 = textureSampleBias(tex1DArray, samp, _e33.x, i32(_e33.y), 2.0); + c_1 = _e38; + let _e42 = coord_3; + let _e48 = textureSampleGrad(tex1DArray, samp, _e42.x, i32(_e42.y), 4.0, 4.0); + c_1 = _e48; + let _e53 = coord_3; + let _e60 = textureSampleGrad(tex1DArray, samp, _e53.x, i32(_e53.y), 4.0, 4.0, 5); c_1 = _e60; - let _e64 = coord_3; - let _e70 = textureSampleLevel(tex1DArray, samp, _e64.x, i32(_e64.y), 3.0, 5); - c_1 = _e70; - let _e73 = coord_3; - let _e78 = textureSample(tex1DArray, samp, _e73.x, i32(_e73.y), 5); + let _e63 = coord_3; + let _e68 = textureSampleLevel(tex1DArray, samp, _e63.x, i32(_e63.y), 3.0); + c_1 = _e68; + let _e72 = coord_3; + let _e78 = textureSampleLevel(tex1DArray, samp, _e72.x, i32(_e72.y), 3.0, 5); c_1 = _e78; - let _e82 = coord_3; - let _e88 = textureSampleBias(tex1DArray, samp, _e82.x, i32(_e82.y), 2.0, 5); - c_1 = _e88; + let _e81 = coord_3; + let _e86 = textureSample(tex1DArray, samp, _e81.x, i32(_e81.y), 5); + c_1 = _e86; + let _e90 = coord_3; + let _e96 = textureSampleBias(tex1DArray, samp, _e90.x, i32(_e90.y), 2.0, 5); + c_1 = _e96; + let _e97 = coord_3; + let _e100 = coord_3; + let _e101 = vec2(_e100); + let _e105 = textureLoad(tex1DArray, _e101.x, _e101.y, 3); + c_1 = _e105; return; } fn testTex2D(coord_4: vec2) { var coord_5: vec2; + var size2D: vec2; var c_2: vec4; coord_5 = coord_4; - let _e18 = coord_5; - let _e19 = textureSample(tex2D, samp, _e18); - c_2 = _e19; - let _e22 = coord_5; - let _e24 = textureSampleBias(tex2D, samp, _e22, 2.0); - c_2 = _e24; - let _e30 = coord_5; - let _e35 = textureSampleGrad(tex2D, samp, _e30, vec2(4.0), vec2(4.0)); - c_2 = _e35; - let _e43 = coord_5; - let _e50 = textureSampleGrad(tex2D, samp, _e43, vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = _e50; - let _e53 = coord_5; - let _e55 = textureSampleLevel(tex2D, samp, _e53, 3.0); - c_2 = _e55; - let _e60 = coord_5; - let _e64 = textureSampleLevel(tex2D, samp, _e60, 3.0, vec2(5, 5)); - c_2 = _e64; - let _e68 = coord_5; - let _e71 = textureSample(tex2D, samp, _e68, vec2(5, 5)); - c_2 = _e71; - let _e76 = coord_5; - let _e80 = textureSampleBias(tex2D, samp, _e76, 2.0, vec2(5, 5)); - c_2 = _e80; - let _e81 = coord_5; - let _e86 = coord_5; - let _e90 = vec3(_e86.x, _e86.y, 6.0); - let _e95 = textureSample(tex2D, samp, (_e90.xy / vec2(_e90.z))); - c_2 = _e95; - let _e96 = coord_5; + let _e20 = textureDimensions(tex2D, 0); + size2D = _e20; + let _e24 = coord_5; + let _e25 = textureSample(tex2D, samp, _e24); + c_2 = _e25; + let _e28 = coord_5; + let _e30 = textureSampleBias(tex2D, samp, _e28, 2.0); + c_2 = _e30; + let _e36 = coord_5; + let _e41 = textureSampleGrad(tex2D, samp, _e36, vec2(4.0), vec2(4.0)); + c_2 = _e41; + let _e49 = coord_5; + let _e56 = textureSampleGrad(tex2D, samp, _e49, vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e56; + let _e59 = coord_5; + let _e61 = textureSampleLevel(tex2D, samp, _e59, 3.0); + c_2 = _e61; + let _e66 = coord_5; + let _e70 = textureSampleLevel(tex2D, samp, _e66, 3.0, vec2(5, 5)); + c_2 = _e70; + let _e74 = coord_5; + let _e77 = textureSample(tex2D, samp, _e74, vec2(5, 5)); + c_2 = _e77; + let _e82 = coord_5; + let _e86 = textureSampleBias(tex2D, samp, _e82, 2.0, vec2(5, 5)); + c_2 = _e86; + let _e87 = coord_5; + let _e92 = coord_5; + let _e96 = vec3(_e92.x, _e92.y, 6.0); + let _e101 = textureSample(tex2D, samp, (_e96.xy / vec2(_e96.z))); + c_2 = _e101; let _e102 = coord_5; - let _e107 = vec4(_e102.x, _e102.y, 0.0, 6.0); - let _e113 = textureSample(tex2D, samp, (_e107.xyz / vec3(_e107.w)).xy); - c_2 = _e113; - let _e114 = coord_5; + let _e108 = coord_5; + let _e113 = vec4(_e108.x, _e108.y, 0.0, 6.0); + let _e119 = textureSample(tex2D, samp, (_e113.xyz / vec3(_e113.w)).xy); + c_2 = _e119; let _e120 = coord_5; - let _e124 = vec3(_e120.x, _e120.y, 6.0); - let _e130 = textureSampleBias(tex2D, samp, (_e124.xy / vec2(_e124.z)), 2.0); - c_2 = _e130; - let _e131 = coord_5; - let _e138 = coord_5; - let _e143 = vec4(_e138.x, _e138.y, 0.0, 6.0); - let _e150 = textureSampleBias(tex2D, samp, (_e143.xyz / vec3(_e143.w)).xy, 2.0); - c_2 = _e150; - let _e151 = coord_5; - let _e160 = coord_5; - let _e164 = vec3(_e160.x, _e160.y, 6.0); - let _e173 = textureSampleGrad(tex2D, samp, (_e164.xy / vec2(_e164.z)), vec2(4.0), vec2(4.0)); - c_2 = _e173; - let _e174 = coord_5; - let _e184 = coord_5; - let _e189 = vec4(_e184.x, _e184.y, 0.0, 6.0); - let _e199 = textureSampleGrad(tex2D, samp, (_e189.xyz / vec3(_e189.w)).xy, vec2(4.0), vec2(4.0)); - c_2 = _e199; - let _e200 = coord_5; - let _e211 = coord_5; - let _e215 = vec3(_e211.x, _e211.y, 6.0); - let _e226 = textureSampleGrad(tex2D, samp, (_e215.xy / vec2(_e215.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = _e226; - let _e227 = coord_5; - let _e239 = coord_5; - let _e244 = vec4(_e239.x, _e239.y, 0.0, 6.0); - let _e256 = textureSampleGrad(tex2D, samp, (_e244.xyz / vec3(_e244.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = _e256; - let _e257 = coord_5; + let _e126 = coord_5; + let _e130 = vec3(_e126.x, _e126.y, 6.0); + let _e136 = textureSampleBias(tex2D, samp, (_e130.xy / vec2(_e130.z)), 2.0); + c_2 = _e136; + let _e137 = coord_5; + let _e144 = coord_5; + let _e149 = vec4(_e144.x, _e144.y, 0.0, 6.0); + let _e156 = textureSampleBias(tex2D, samp, (_e149.xyz / vec3(_e149.w)).xy, 2.0); + c_2 = _e156; + let _e157 = coord_5; + let _e166 = coord_5; + let _e170 = vec3(_e166.x, _e166.y, 6.0); + let _e179 = textureSampleGrad(tex2D, samp, (_e170.xy / vec2(_e170.z)), vec2(4.0), vec2(4.0)); + c_2 = _e179; + let _e180 = coord_5; + let _e190 = coord_5; + let _e195 = vec4(_e190.x, _e190.y, 0.0, 6.0); + let _e205 = textureSampleGrad(tex2D, samp, (_e195.xyz / vec3(_e195.w)).xy, vec2(4.0), vec2(4.0)); + c_2 = _e205; + let _e206 = coord_5; + let _e217 = coord_5; + let _e221 = vec3(_e217.x, _e217.y, 6.0); + let _e232 = textureSampleGrad(tex2D, samp, (_e221.xy / vec2(_e221.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e232; + let _e233 = coord_5; + let _e245 = coord_5; + let _e250 = vec4(_e245.x, _e245.y, 0.0, 6.0); + let _e262 = textureSampleGrad(tex2D, samp, (_e250.xyz / vec3(_e250.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e262; let _e263 = coord_5; - let _e267 = vec3(_e263.x, _e263.y, 6.0); - let _e273 = textureSampleLevel(tex2D, samp, (_e267.xy / vec2(_e267.z)), 3.0); - c_2 = _e273; - let _e274 = coord_5; - let _e281 = coord_5; - let _e286 = vec4(_e281.x, _e281.y, 0.0, 6.0); - let _e293 = textureSampleLevel(tex2D, samp, (_e286.xyz / vec3(_e286.w)).xy, 3.0); - c_2 = _e293; - let _e294 = coord_5; - let _e302 = coord_5; - let _e306 = vec3(_e302.x, _e302.y, 6.0); - let _e314 = textureSampleLevel(tex2D, samp, (_e306.xy / vec2(_e306.z)), 3.0, vec2(5, 5)); - c_2 = _e314; - let _e315 = coord_5; - let _e324 = coord_5; - let _e329 = vec4(_e324.x, _e324.y, 0.0, 6.0); - let _e338 = textureSampleLevel(tex2D, samp, (_e329.xyz / vec3(_e329.w)).xy, 3.0, vec2(5, 5)); - c_2 = _e338; - let _e339 = coord_5; - let _e346 = coord_5; - let _e350 = vec3(_e346.x, _e346.y, 6.0); - let _e357 = textureSample(tex2D, samp, (_e350.xy / vec2(_e350.z)), vec2(5, 5)); - c_2 = _e357; - let _e358 = coord_5; - let _e366 = coord_5; - let _e371 = vec4(_e366.x, _e366.y, 0.0, 6.0); - let _e379 = textureSample(tex2D, samp, (_e371.xyz / vec3(_e371.w)).xy, vec2(5, 5)); - c_2 = _e379; - let _e380 = coord_5; - let _e388 = coord_5; - let _e392 = vec3(_e388.x, _e388.y, 6.0); - let _e400 = textureSampleBias(tex2D, samp, (_e392.xy / vec2(_e392.z)), 2.0, vec2(5, 5)); - c_2 = _e400; - let _e401 = coord_5; - let _e410 = coord_5; - let _e415 = vec4(_e410.x, _e410.y, 0.0, 6.0); - let _e424 = textureSampleBias(tex2D, samp, (_e415.xyz / vec3(_e415.w)).xy, 2.0, vec2(5, 5)); - c_2 = _e424; + let _e269 = coord_5; + let _e273 = vec3(_e269.x, _e269.y, 6.0); + let _e279 = textureSampleLevel(tex2D, samp, (_e273.xy / vec2(_e273.z)), 3.0); + c_2 = _e279; + let _e280 = coord_5; + let _e287 = coord_5; + let _e292 = vec4(_e287.x, _e287.y, 0.0, 6.0); + let _e299 = textureSampleLevel(tex2D, samp, (_e292.xyz / vec3(_e292.w)).xy, 3.0); + c_2 = _e299; + let _e300 = coord_5; + let _e308 = coord_5; + let _e312 = vec3(_e308.x, _e308.y, 6.0); + let _e320 = textureSampleLevel(tex2D, samp, (_e312.xy / vec2(_e312.z)), 3.0, vec2(5, 5)); + c_2 = _e320; + let _e321 = coord_5; + let _e330 = coord_5; + let _e335 = vec4(_e330.x, _e330.y, 0.0, 6.0); + let _e344 = textureSampleLevel(tex2D, samp, (_e335.xyz / vec3(_e335.w)).xy, 3.0, vec2(5, 5)); + c_2 = _e344; + let _e345 = coord_5; + let _e352 = coord_5; + let _e356 = vec3(_e352.x, _e352.y, 6.0); + let _e363 = textureSample(tex2D, samp, (_e356.xy / vec2(_e356.z)), vec2(5, 5)); + c_2 = _e363; + let _e364 = coord_5; + let _e372 = coord_5; + let _e377 = vec4(_e372.x, _e372.y, 0.0, 6.0); + let _e385 = textureSample(tex2D, samp, (_e377.xyz / vec3(_e377.w)).xy, vec2(5, 5)); + c_2 = _e385; + let _e386 = coord_5; + let _e394 = coord_5; + let _e398 = vec3(_e394.x, _e394.y, 6.0); + let _e406 = textureSampleBias(tex2D, samp, (_e398.xy / vec2(_e398.z)), 2.0, vec2(5, 5)); + c_2 = _e406; + let _e407 = coord_5; + let _e416 = coord_5; + let _e421 = vec4(_e416.x, _e416.y, 0.0, 6.0); + let _e430 = textureSampleBias(tex2D, samp, (_e421.xyz / vec3(_e421.w)).xy, 2.0, vec2(5, 5)); + c_2 = _e430; + let _e431 = coord_5; + let _e434 = coord_5; + let _e437 = textureLoad(tex2D, vec2(_e434), 3); + c_2 = _e437; return; } fn testTex2DShadow(coord_6: vec2) { var coord_7: vec2; + var size2DShadow: vec2; var d: f32; coord_7 = coord_6; - let _e17 = coord_7; - let _e22 = coord_7; - let _e26 = vec3(_e22.x, _e22.y, 1.0); - let _e29 = textureSampleCompare(tex2DShadow, sampShadow, _e26.xy, _e26.z); - d = _e29; - let _e30 = coord_7; - let _e39 = coord_7; - let _e43 = vec3(_e39.x, _e39.y, 1.0); - let _e50 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e43.xy, _e43.z); - d = _e50; - let _e51 = coord_7; - let _e62 = coord_7; - let _e66 = vec3(_e62.x, _e62.y, 1.0); - let _e75 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e66.xy, _e66.z, vec2(5, 5)); - d = _e75; - let _e76 = coord_7; + let _e20 = textureDimensions(tex2DShadow, 0); + size2DShadow = _e20; + let _e23 = coord_7; + let _e28 = coord_7; + let _e32 = vec3(_e28.x, _e28.y, 1.0); + let _e35 = textureSampleCompare(tex2DShadow, sampShadow, _e32.xy, _e32.z); + d = _e35; + let _e36 = coord_7; + let _e45 = coord_7; + let _e49 = vec3(_e45.x, _e45.y, 1.0); + let _e56 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e49.xy, _e49.z); + d = _e56; + let _e57 = coord_7; + let _e68 = coord_7; + let _e72 = vec3(_e68.x, _e68.y, 1.0); + let _e81 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e72.xy, _e72.z, vec2(5, 5)); + d = _e81; let _e82 = coord_7; - let _e86 = vec3(_e82.x, _e82.y, 1.0); - let _e90 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e86.xy, _e86.z); - d = _e90; - let _e91 = coord_7; - let _e99 = coord_7; - let _e103 = vec3(_e99.x, _e99.y, 1.0); - let _e109 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e103.xy, _e103.z, vec2(5, 5)); - d = _e109; - let _e110 = coord_7; - let _e117 = coord_7; - let _e121 = vec3(_e117.x, _e117.y, 1.0); - let _e126 = textureSampleCompare(tex2DShadow, sampShadow, _e121.xy, _e121.z, vec2(5, 5)); - d = _e126; - let _e127 = coord_7; + let _e88 = coord_7; + let _e92 = vec3(_e88.x, _e88.y, 1.0); + let _e96 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e92.xy, _e92.z); + d = _e96; + let _e97 = coord_7; + let _e105 = coord_7; + let _e109 = vec3(_e105.x, _e105.y, 1.0); + let _e115 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e109.xy, _e109.z, vec2(5, 5)); + d = _e115; + let _e116 = coord_7; + let _e123 = coord_7; + let _e127 = vec3(_e123.x, _e123.y, 1.0); + let _e132 = textureSampleCompare(tex2DShadow, sampShadow, _e127.xy, _e127.z, vec2(5, 5)); + d = _e132; let _e133 = coord_7; - let _e138 = vec4(_e133.x, _e133.y, 1.0, 6.0); - let _e142 = (_e138.xyz / vec3(_e138.w)); - let _e145 = textureSampleCompare(tex2DShadow, sampShadow, _e142.xy, _e142.z); - d = _e145; - let _e146 = coord_7; - let _e156 = coord_7; - let _e161 = vec4(_e156.x, _e156.y, 1.0, 6.0); - let _e169 = (_e161.xyz / vec3(_e161.w)); - let _e172 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e169.xy, _e169.z); - d = _e172; - let _e173 = coord_7; - let _e185 = coord_7; - let _e190 = vec4(_e185.x, _e185.y, 1.0, 6.0); - let _e200 = (_e190.xyz / vec3(_e190.w)); - let _e203 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e200.xy, _e200.z, vec2(5, 5)); - d = _e203; - let _e204 = coord_7; - let _e211 = coord_7; - let _e216 = vec4(_e211.x, _e211.y, 1.0, 6.0); - let _e221 = (_e216.xyz / vec3(_e216.w)); - let _e224 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e221.xy, _e221.z); - d = _e224; - let _e225 = coord_7; - let _e234 = coord_7; - let _e239 = vec4(_e234.x, _e234.y, 1.0, 6.0); - let _e246 = (_e239.xyz / vec3(_e239.w)); - let _e249 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e246.xy, _e246.z, vec2(5, 5)); - d = _e249; - let _e250 = coord_7; - let _e258 = coord_7; - let _e263 = vec4(_e258.x, _e258.y, 1.0, 6.0); - let _e269 = (_e263.xyz / vec3(_e263.w)); - let _e272 = textureSampleCompare(tex2DShadow, sampShadow, _e269.xy, _e269.z, vec2(5, 5)); - d = _e272; + let _e139 = coord_7; + let _e144 = vec4(_e139.x, _e139.y, 1.0, 6.0); + let _e148 = (_e144.xyz / vec3(_e144.w)); + let _e151 = textureSampleCompare(tex2DShadow, sampShadow, _e148.xy, _e148.z); + d = _e151; + let _e152 = coord_7; + let _e162 = coord_7; + let _e167 = vec4(_e162.x, _e162.y, 1.0, 6.0); + let _e175 = (_e167.xyz / vec3(_e167.w)); + let _e178 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e175.xy, _e175.z); + d = _e178; + let _e179 = coord_7; + let _e191 = coord_7; + let _e196 = vec4(_e191.x, _e191.y, 1.0, 6.0); + let _e206 = (_e196.xyz / vec3(_e196.w)); + let _e209 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e206.xy, _e206.z, vec2(5, 5)); + d = _e209; + let _e210 = coord_7; + let _e217 = coord_7; + let _e222 = vec4(_e217.x, _e217.y, 1.0, 6.0); + let _e227 = (_e222.xyz / vec3(_e222.w)); + let _e230 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e227.xy, _e227.z); + d = _e230; + let _e231 = coord_7; + let _e240 = coord_7; + let _e245 = vec4(_e240.x, _e240.y, 1.0, 6.0); + let _e252 = (_e245.xyz / vec3(_e245.w)); + let _e255 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e252.xy, _e252.z, vec2(5, 5)); + d = _e255; + let _e256 = coord_7; + let _e264 = coord_7; + let _e269 = vec4(_e264.x, _e264.y, 1.0, 6.0); + let _e275 = (_e269.xyz / vec3(_e269.w)); + let _e278 = textureSampleCompare(tex2DShadow, sampShadow, _e275.xy, _e275.z, vec2(5, 5)); + d = _e278; return; } fn testTex2DArray(coord_8: vec3) { var coord_9: vec3; + var size2DArray: vec3; var c_3: vec4; coord_9 = coord_8; - let _e18 = coord_9; - let _e22 = textureSample(tex2DArray, samp, _e18.xy, i32(_e18.z)); - c_3 = _e22; - let _e25 = coord_9; - let _e30 = textureSampleBias(tex2DArray, samp, _e25.xy, i32(_e25.z), 2.0); - c_3 = _e30; - let _e36 = coord_9; - let _e44 = textureSampleGrad(tex2DArray, samp, _e36.xy, i32(_e36.z), vec2(4.0), vec2(4.0)); - c_3 = _e44; - let _e52 = coord_9; - let _e62 = textureSampleGrad(tex2DArray, samp, _e52.xy, i32(_e52.z), vec2(4.0), vec2(4.0), vec2(5, 5)); - c_3 = _e62; - let _e65 = coord_9; - let _e70 = textureSampleLevel(tex2DArray, samp, _e65.xy, i32(_e65.z), 3.0); - c_3 = _e70; + let _e20 = textureDimensions(tex2DArray, 0); + let _e23 = textureNumLayers(tex2DArray); + size2DArray = vec3(_e20.x, _e20.y, _e23); + let _e28 = coord_9; + let _e32 = textureSample(tex2DArray, samp, _e28.xy, i32(_e28.z)); + c_3 = _e32; + let _e35 = coord_9; + let _e40 = textureSampleBias(tex2DArray, samp, _e35.xy, i32(_e35.z), 2.0); + c_3 = _e40; + let _e46 = coord_9; + let _e54 = textureSampleGrad(tex2DArray, samp, _e46.xy, i32(_e46.z), vec2(4.0), vec2(4.0)); + c_3 = _e54; + let _e62 = coord_9; + let _e72 = textureSampleGrad(tex2DArray, samp, _e62.xy, i32(_e62.z), vec2(4.0), vec2(4.0), vec2(5, 5)); + c_3 = _e72; let _e75 = coord_9; - let _e82 = textureSampleLevel(tex2DArray, samp, _e75.xy, i32(_e75.z), 3.0, vec2(5, 5)); - c_3 = _e82; - let _e86 = coord_9; - let _e92 = textureSample(tex2DArray, samp, _e86.xy, i32(_e86.z), vec2(5, 5)); + let _e80 = textureSampleLevel(tex2DArray, samp, _e75.xy, i32(_e75.z), 3.0); + c_3 = _e80; + let _e85 = coord_9; + let _e92 = textureSampleLevel(tex2DArray, samp, _e85.xy, i32(_e85.z), 3.0, vec2(5, 5)); c_3 = _e92; - let _e97 = coord_9; - let _e104 = textureSampleBias(tex2DArray, samp, _e97.xy, i32(_e97.z), 2.0, vec2(5, 5)); - c_3 = _e104; + let _e96 = coord_9; + let _e102 = textureSample(tex2DArray, samp, _e96.xy, i32(_e96.z), vec2(5, 5)); + c_3 = _e102; + let _e107 = coord_9; + let _e114 = textureSampleBias(tex2DArray, samp, _e107.xy, i32(_e107.z), 2.0, vec2(5, 5)); + c_3 = _e114; + let _e115 = coord_9; + let _e118 = coord_9; + let _e119 = vec3(_e118); + let _e123 = textureLoad(tex2DArray, _e119.xy, _e119.z, 3); + c_3 = _e123; return; } fn testTex2DArrayShadow(coord_10: vec3) { var coord_11: vec3; + var size2DArrayShadow: vec3; var d_1: f32; coord_11 = coord_10; - let _e17 = coord_11; - let _e23 = coord_11; - let _e28 = vec4(_e23.x, _e23.y, _e23.z, 1.0); - let _e33 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e28.xy, i32(_e28.z), _e28.w); - d_1 = _e33; - let _e34 = coord_11; + let _e20 = textureDimensions(tex2DArrayShadow, 0); + let _e23 = textureNumLayers(tex2DArrayShadow); + size2DArrayShadow = vec3(_e20.x, _e20.y, _e23); + let _e27 = coord_11; + let _e33 = coord_11; + let _e38 = vec4(_e33.x, _e33.y, _e33.z, 1.0); + let _e43 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e38.xy, i32(_e38.z), _e38.w); + d_1 = _e43; let _e44 = coord_11; - let _e49 = vec4(_e44.x, _e44.y, _e44.z, 1.0); - let _e58 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e49.xy, i32(_e49.z), _e49.w); - d_1 = _e58; - let _e59 = coord_11; - let _e71 = coord_11; - let _e76 = vec4(_e71.x, _e71.y, _e71.z, 1.0); - let _e87 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e76.xy, i32(_e76.z), _e76.w, vec2(5, 5)); - d_1 = _e87; - let _e88 = coord_11; - let _e95 = coord_11; - let _e100 = vec4(_e95.x, _e95.y, _e95.z, 1.0); - let _e106 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e100.xy, i32(_e100.z), _e100.w); - d_1 = _e106; - let _e107 = coord_11; - let _e116 = coord_11; - let _e121 = vec4(_e116.x, _e116.y, _e116.z, 1.0); - let _e129 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e121.xy, i32(_e121.z), _e121.w, vec2(5, 5)); - d_1 = _e129; - let _e130 = coord_11; - let _e138 = coord_11; - let _e143 = vec4(_e138.x, _e138.y, _e138.z, 1.0); - let _e150 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e143.xy, i32(_e143.z), _e143.w, vec2(5, 5)); - d_1 = _e150; + let _e54 = coord_11; + let _e59 = vec4(_e54.x, _e54.y, _e54.z, 1.0); + let _e68 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e59.xy, i32(_e59.z), _e59.w); + d_1 = _e68; + let _e69 = coord_11; + let _e81 = coord_11; + let _e86 = vec4(_e81.x, _e81.y, _e81.z, 1.0); + let _e97 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e86.xy, i32(_e86.z), _e86.w, vec2(5, 5)); + d_1 = _e97; + let _e98 = coord_11; + let _e106 = coord_11; + let _e111 = vec4(_e106.x, _e106.y, _e106.z, 1.0); + let _e118 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e111.xy, i32(_e111.z), _e111.w, vec2(5, 5)); + d_1 = _e118; return; } fn testTexCube(coord_12: vec3) { var coord_13: vec3; + var sizeCube: vec2; var c_4: vec4; coord_13 = coord_12; - let _e18 = coord_13; - let _e19 = textureSample(texCube, samp, _e18); - c_4 = _e19; - let _e22 = coord_13; - let _e24 = textureSampleBias(texCube, samp, _e22, 2.0); - c_4 = _e24; - let _e30 = coord_13; - let _e35 = textureSampleGrad(texCube, samp, _e30, vec3(4.0), vec3(4.0)); - c_4 = _e35; - let _e38 = coord_13; - let _e40 = textureSampleLevel(texCube, samp, _e38, 3.0); - c_4 = _e40; - let _e45 = coord_13; - let _e49 = textureSampleLevel(texCube, samp, _e45, 3.0, vec3(5, 5, 5)); - c_4 = _e49; - let _e53 = coord_13; - let _e56 = textureSample(texCube, samp, _e53, vec3(5, 5, 5)); - c_4 = _e56; - let _e61 = coord_13; - let _e65 = textureSampleBias(texCube, samp, _e61, 2.0, vec3(5, 5, 5)); - c_4 = _e65; + let _e20 = textureDimensions(texCube, 0); + sizeCube = _e20; + let _e24 = coord_13; + let _e25 = textureSample(texCube, samp, _e24); + c_4 = _e25; + let _e28 = coord_13; + let _e30 = textureSampleBias(texCube, samp, _e28, 2.0); + c_4 = _e30; + let _e36 = coord_13; + let _e41 = textureSampleGrad(texCube, samp, _e36, vec3(4.0), vec3(4.0)); + c_4 = _e41; + let _e44 = coord_13; + let _e46 = textureSampleLevel(texCube, samp, _e44, 3.0); + c_4 = _e46; return; } fn testTexCubeShadow(coord_14: vec3) { var coord_15: vec3; + var sizeCubeShadow: vec2; var d_2: f32; coord_15 = coord_14; - let _e17 = coord_15; + let _e20 = textureDimensions(texCubeShadow, 0); + sizeCubeShadow = _e20; let _e23 = coord_15; - let _e28 = vec4(_e23.x, _e23.y, _e23.z, 1.0); - let _e31 = textureSampleCompare(texCubeShadow, sampShadow, _e28.xyz, _e28.w); - d_2 = _e31; - let _e32 = coord_15; - let _e42 = coord_15; - let _e47 = vec4(_e42.x, _e42.y, _e42.z, 1.0); - let _e54 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e47.xyz, _e47.w); - d_2 = _e54; - let _e55 = coord_15; - let _e62 = coord_15; - let _e67 = vec4(_e62.x, _e62.y, _e62.z, 1.0); - let _e71 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e67.xyz, _e67.w); - d_2 = _e71; - let _e72 = coord_15; - let _e81 = coord_15; - let _e86 = vec4(_e81.x, _e81.y, _e81.z, 1.0); - let _e92 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e86.xyz, _e86.w, vec3(5, 5, 5)); - d_2 = _e92; - let _e93 = coord_15; - let _e101 = coord_15; - let _e106 = vec4(_e101.x, _e101.y, _e101.z, 1.0); - let _e111 = textureSampleCompare(texCubeShadow, sampShadow, _e106.xyz, _e106.w, vec3(5, 5, 5)); - d_2 = _e111; + let _e29 = coord_15; + let _e34 = vec4(_e29.x, _e29.y, _e29.z, 1.0); + let _e37 = textureSampleCompare(texCubeShadow, sampShadow, _e34.xyz, _e34.w); + d_2 = _e37; + let _e38 = coord_15; + let _e48 = coord_15; + let _e53 = vec4(_e48.x, _e48.y, _e48.z, 1.0); + let _e60 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e53.xyz, _e53.w); + d_2 = _e60; return; } fn testTexCubeArray(coord_16: vec4) { var coord_17: vec4; + var sizeCubeArray: vec3; var c_5: vec4; coord_17 = coord_16; - let _e18 = coord_17; - let _e22 = textureSample(texCubeArray, samp, _e18.xyz, i32(_e18.w)); - c_5 = _e22; - let _e25 = coord_17; - let _e30 = textureSampleBias(texCubeArray, samp, _e25.xyz, i32(_e25.w), 2.0); - c_5 = _e30; - let _e36 = coord_17; - let _e44 = textureSampleGrad(texCubeArray, samp, _e36.xyz, i32(_e36.w), vec3(4.0), vec3(4.0)); - c_5 = _e44; - let _e47 = coord_17; - let _e52 = textureSampleLevel(texCubeArray, samp, _e47.xyz, i32(_e47.w), 3.0); - c_5 = _e52; + let _e20 = textureDimensions(texCubeArray, 0); + let _e23 = textureNumLayers(texCubeArray); + sizeCubeArray = vec3(_e20.x, _e20.y, _e23); + let _e28 = coord_17; + let _e32 = textureSample(texCubeArray, samp, _e28.xyz, i32(_e28.w)); + c_5 = _e32; + let _e35 = coord_17; + let _e40 = textureSampleBias(texCubeArray, samp, _e35.xyz, i32(_e35.w), 2.0); + c_5 = _e40; + let _e46 = coord_17; + let _e54 = textureSampleGrad(texCubeArray, samp, _e46.xyz, i32(_e46.w), vec3(4.0), vec3(4.0)); + c_5 = _e54; let _e57 = coord_17; - let _e64 = textureSampleLevel(texCubeArray, samp, _e57.xyz, i32(_e57.w), 3.0, vec3(5, 5, 5)); - c_5 = _e64; - let _e68 = coord_17; - let _e74 = textureSample(texCubeArray, samp, _e68.xyz, i32(_e68.w), vec3(5, 5, 5)); - c_5 = _e74; - let _e79 = coord_17; - let _e86 = textureSampleBias(texCubeArray, samp, _e79.xyz, i32(_e79.w), 2.0, vec3(5, 5, 5)); - c_5 = _e86; + let _e62 = textureSampleLevel(texCubeArray, samp, _e57.xyz, i32(_e57.w), 3.0); + c_5 = _e62; return; } fn testTexCubeArrayShadow(coord_18: vec4) { var coord_19: vec4; + var sizeCubeArrayShadow: vec3; var d_3: f32; coord_19 = coord_18; - let _e19 = coord_19; - let _e24 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e19.xyz, i32(_e19.w), 1.0); - d_3 = _e24; + let _e20 = textureDimensions(texCubeArrayShadow, 0); + let _e23 = textureNumLayers(texCubeArrayShadow); + sizeCubeArrayShadow = vec3(_e20.x, _e20.y, _e23); + let _e29 = coord_19; + let _e34 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e29.xyz, i32(_e29.w), 1.0); + d_3 = _e34; return; } fn testTex3D(coord_20: vec3) { var coord_21: vec3; + var size3D: vec3; var c_6: vec4; coord_21 = coord_20; - let _e18 = coord_21; - let _e19 = textureSample(tex3D, samp, _e18); - c_6 = _e19; - let _e22 = coord_21; - let _e24 = textureSampleBias(tex3D, samp, _e22, 2.0); - c_6 = _e24; - let _e30 = coord_21; - let _e35 = textureSampleGrad(tex3D, samp, _e30, vec3(4.0), vec3(4.0)); - c_6 = _e35; - let _e43 = coord_21; - let _e50 = textureSampleGrad(tex3D, samp, _e43, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); - c_6 = _e50; - let _e53 = coord_21; - let _e55 = textureSampleLevel(tex3D, samp, _e53, 3.0); - c_6 = _e55; - let _e60 = coord_21; - let _e64 = textureSampleLevel(tex3D, samp, _e60, 3.0, vec3(5, 5, 5)); - c_6 = _e64; - let _e68 = coord_21; - let _e71 = textureSample(tex3D, samp, _e68, vec3(5, 5, 5)); - c_6 = _e71; - let _e76 = coord_21; - let _e80 = textureSampleBias(tex3D, samp, _e76, 2.0, vec3(5, 5, 5)); - c_6 = _e80; + let _e20 = textureDimensions(tex3D, 0); + size3D = _e20; + let _e24 = coord_21; + let _e25 = textureSample(tex3D, samp, _e24); + c_6 = _e25; + let _e28 = coord_21; + let _e30 = textureSampleBias(tex3D, samp, _e28, 2.0); + c_6 = _e30; + let _e31 = coord_21; + let _e37 = coord_21; + let _e42 = vec4(_e37.x, _e37.y, _e37.z, 6.0); + let _e47 = textureSample(tex3D, samp, (_e42.xyz / vec3(_e42.w))); + c_6 = _e47; + let _e48 = coord_21; + let _e55 = coord_21; + let _e60 = vec4(_e55.x, _e55.y, _e55.z, 6.0); + let _e66 = textureSampleBias(tex3D, samp, (_e60.xyz / vec3(_e60.w)), 2.0); + c_6 = _e66; + let _e67 = coord_21; + let _e75 = coord_21; + let _e80 = vec4(_e75.x, _e75.y, _e75.z, 6.0); + let _e87 = textureSample(tex3D, samp, (_e80.xyz / vec3(_e80.w)), vec3(5, 5, 5)); + c_6 = _e87; + let _e88 = coord_21; + let _e97 = coord_21; + let _e102 = vec4(_e97.x, _e97.y, _e97.z, 6.0); + let _e110 = textureSampleBias(tex3D, samp, (_e102.xyz / vec3(_e102.w)), 2.0, vec3(5, 5, 5)); + c_6 = _e110; + let _e111 = coord_21; + let _e118 = coord_21; + let _e123 = vec4(_e118.x, _e118.y, _e118.z, 6.0); + let _e129 = textureSampleLevel(tex3D, samp, (_e123.xyz / vec3(_e123.w)), 3.0); + c_6 = _e129; + let _e130 = coord_21; + let _e139 = coord_21; + let _e144 = vec4(_e139.x, _e139.y, _e139.z, 6.0); + let _e152 = textureSampleLevel(tex3D, samp, (_e144.xyz / vec3(_e144.w)), 3.0, vec3(5, 5, 5)); + c_6 = _e152; + let _e153 = coord_21; + let _e163 = coord_21; + let _e168 = vec4(_e163.x, _e163.y, _e163.z, 6.0); + let _e177 = textureSampleGrad(tex3D, samp, (_e168.xyz / vec3(_e168.w)), vec3(4.0), vec3(4.0)); + c_6 = _e177; + let _e178 = coord_21; + let _e190 = coord_21; + let _e195 = vec4(_e190.x, _e190.y, _e190.z, 6.0); + let _e206 = textureSampleGrad(tex3D, samp, (_e195.xyz / vec3(_e195.w)), vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + c_6 = _e206; + let _e212 = coord_21; + let _e217 = textureSampleGrad(tex3D, samp, _e212, vec3(4.0), vec3(4.0)); + c_6 = _e217; + let _e225 = coord_21; + let _e232 = textureSampleGrad(tex3D, samp, _e225, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + c_6 = _e232; + let _e235 = coord_21; + let _e237 = textureSampleLevel(tex3D, samp, _e235, 3.0); + c_6 = _e237; + let _e242 = coord_21; + let _e246 = textureSampleLevel(tex3D, samp, _e242, 3.0, vec3(5, 5, 5)); + c_6 = _e246; + let _e250 = coord_21; + let _e253 = textureSample(tex3D, samp, _e250, vec3(5, 5, 5)); + c_6 = _e253; + let _e258 = coord_21; + let _e262 = textureSampleBias(tex3D, samp, _e258, 2.0, vec3(5, 5, 5)); + c_6 = _e262; + let _e263 = coord_21; + let _e266 = coord_21; + let _e269 = textureLoad(tex3D, vec3(_e266), 3); + c_6 = _e269; + return; +} + +fn testTex2DMS(coord_22: vec2) { + var coord_23: vec2; + var size2DMS: vec2; + var c_7: vec4; + + coord_23 = coord_22; + let _e18 = textureDimensions(tex2DMS); + size2DMS = _e18; + let _e21 = coord_23; + let _e24 = coord_23; + let _e27 = textureLoad(tex2DMS, vec2(_e24), 3); + c_7 = _e27; + return; +} + +fn testTex2DMSArray(coord_24: vec3) { + var coord_25: vec3; + var size2DMSArray: vec3; + var c_8: vec4; + + coord_25 = coord_24; + let _e18 = textureDimensions(tex2DMSArray); + let _e21 = textureNumLayers(tex2DMSArray); + size2DMSArray = vec3(_e18.x, _e18.y, _e21); + let _e25 = coord_25; + let _e28 = coord_25; + let _e29 = vec3(_e28); + let _e33 = textureLoad(tex2DMSArray, _e29.xy, _e29.z, 3); + c_8 = _e33; return; } @@ -567,8 +659,7 @@ fn main_1() { } @stage(fragment) -fn main(@location(0) texcoord: vec4) { - texcoord_1 = texcoord; +fn main() { main_1(); return; } From d40522329bd74bf49df05a80dd95d8712ea93b99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 12 Feb 2022 11:57:48 +0000 Subject: [PATCH 1577/2212] spv-in: align array stride for undecorated arrays --- src/front/spv/mod.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 893c60cca..95e8a7487 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -4076,12 +4076,15 @@ impl> Parser { let decor = self.future_decor.remove(&id).unwrap_or_default(); let base = self.lookup_type.lookup(type_id)?.handle; + self.layouter + .update(&module.types, &module.constants) + .unwrap(); let inner = crate::TypeInner::Array { base, size: crate::ArraySize::Constant(length_const.handle), stride: match decor.array_stride { Some(stride) => stride.get(), - None => module.types[base].inner.size(&module.constants), + None => self.layouter[base].to_stride(), }, }; self.lookup_type.insert( @@ -4113,12 +4116,15 @@ impl> Parser { let decor = self.future_decor.remove(&id).unwrap_or_default(); let base = self.lookup_type.lookup(type_id)?.handle; + self.layouter + .update(&module.types, &module.constants) + .unwrap(); let inner = crate::TypeInner::Array { base: self.lookup_type.lookup(type_id)?.handle, size: crate::ArraySize::Dynamic, stride: match decor.array_stride { Some(stride) => stride.get(), - None => module.types[base].inner.size(&module.constants), + None => self.layouter[base].to_stride(), }, }; self.lookup_type.insert( From c356b93962a7da1af2cca3bb017a405f9f50c5b3 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 15 Feb 2022 13:05:21 +0300 Subject: [PATCH 1578/2212] [wgsl-in] Optional parentheses for if and switch --- src/front/wgsl/mod.rs | 6 ------ src/front/wgsl/tests.rs | 39 ++++++++++++++++++++++++++++++++++++-- tests/in/boids.wgsl | 24 +++++++++++------------ tests/in/collatz.wgsl | 4 ++-- tests/in/control-flow.wgsl | 10 +++++----- tests/in/extra.wgsl | 2 +- tests/in/operators.wgsl | 2 +- tests/in/quad.wgsl | 2 +- tests/in/shadow.wgsl | 4 ++-- 9 files changed, 61 insertions(+), 32 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 1b1cbacb0..8b2172c88 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3602,14 +3602,12 @@ impl Parser { } "if" => { let _ = lexer.next(); - lexer.expect(Token::Paren('('))?; emitter.start(context.expressions); let condition = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), )?; block.extend(emitter.finish(context.expressions)); - lexer.expect(Token::Paren(')'))?; let accept = self.parse_block(lexer, context.reborrow(), false)?; @@ -3628,14 +3626,12 @@ impl Parser { // ... else if (...) { ... } let mut sub_emitter = super::Emitter::default(); - lexer.expect(Token::Paren('('))?; sub_emitter.start(context.expressions); let other_condition = self.parse_general_expression( lexer, context.as_expression(block, &mut sub_emitter), )?; let other_emit = sub_emitter.finish(context.expressions); - lexer.expect(Token::Paren(')'))?; let other_block = self.parse_block(lexer, context.reborrow(), false)?; elsif_stack.push(( elseif_span_start, @@ -3671,7 +3667,6 @@ impl Parser { "switch" => { let _ = lexer.next(); emitter.start(context.expressions); - lexer.expect(Token::Paren('('))?; let selector = self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), @@ -3681,7 +3676,6 @@ impl Parser { .as_expression(block, &mut emitter) .resolve_type(selector)? .scalar_kind(); - lexer.expect(Token::Paren(')'))?; block.extend(emitter.finish(context.expressions)); lexer.expect(Token::Paren('{'))?; let mut cases = Vec::new(); diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 4d5e047a6..a439eff4b 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -206,6 +206,26 @@ fn parse_statement() { #[test] fn parse_if() { + parse_str( + " + fn main() { + if true { + discard; + } else {} + if 0 != 1 {} + if false { + return; + } else if true { + return; + } else {} + } + ", + ) + .unwrap(); +} + +#[test] +fn parse_parentheses_if() { parse_str( " fn main() { @@ -231,11 +251,11 @@ fn parse_loop() { fn main() { var i: i32 = 0; loop { - if (i == 1) { break; } + if i == 1 { break; } continuing { i = 1; } } loop { - if (i == 0) { continue; } + if i == 0 { continue; } break; } } @@ -283,6 +303,21 @@ fn parse_switch() { .unwrap(); } +#[test] +fn parse_parentheses_switch() { + parse_str( + " + fn main() { + var pos: f32; + switch pos > 1.0 { + default: { pos = 3.0; } + } + } + ", + ) + .unwrap(); +} + #[test] fn parse_texture_load() { parse_str( diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 6f44752c6..c3106f1c6 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -27,7 +27,7 @@ struct Particles { @stage(compute) @workgroup_size(64) fn main(@builtin(global_invocation_id) global_invocation_id : vec3) { let index : u32 = global_invocation_id.x; - if (index >= NUM_PARTICLES) { + if index >= NUM_PARTICLES { return; } @@ -44,24 +44,24 @@ fn main(@builtin(global_invocation_id) global_invocation_id : vec3) { var vel : vec2; var i : u32 = 0u; loop { - if (i >= NUM_PARTICLES) { + if i >= NUM_PARTICLES { break; } - if (i == index) { + if i == index { continue; } pos = particlesSrc.particles[i].pos; vel = particlesSrc.particles[i].vel; - if (distance(pos, vPos) < params.rule1Distance) { + if distance(pos, vPos) < params.rule1Distance { cMass = cMass + pos; cMassCount = cMassCount + 1; } - if (distance(pos, vPos) < params.rule2Distance) { + if distance(pos, vPos) < params.rule2Distance { colVel = colVel - (pos - vPos); } - if (distance(pos, vPos) < params.rule3Distance) { + if distance(pos, vPos) < params.rule3Distance { cVel = cVel + vel; cVelCount = cVelCount + 1; } @@ -70,10 +70,10 @@ fn main(@builtin(global_invocation_id) global_invocation_id : vec3) { i = i + 1u; } } - if (cMassCount > 0) { + if cMassCount > 0 { cMass = cMass / f32(cMassCount) - vPos; } - if (cVelCount > 0) { + if cVelCount > 0 { cVel = cVel / f32(cVelCount); } @@ -88,16 +88,16 @@ fn main(@builtin(global_invocation_id) global_invocation_id : vec3) { vPos = vPos + (vVel * params.deltaT); // Wrap around boundary - if (vPos.x < -1.0) { + if vPos.x < -1.0 { vPos.x = 1.0; } - if (vPos.x > 1.0) { + if vPos.x > 1.0 { vPos.x = -1.0; } - if (vPos.y < -1.0) { + if vPos.y < -1.0 { vPos.y = 1.0; } - if (vPos.y > 1.0) { + if vPos.y > 1.0 { vPos.y = -1.0; } diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index cf972a8ff..7e2b13543 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -15,10 +15,10 @@ fn collatz_iterations(n_base: u32) -> u32 { var n = n_base; var i: u32 = 0u; loop { - if (n <= 1u) { + if n <= 1u { break; } - if (n % 2u == 0u) { + if n % 2u == 0u { n = n / 2u; } else { diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index 9ce08fff7..db87b320f 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -6,7 +6,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { var pos: i32; // switch without cases - switch (1) { + switch 1 { default: { pos = 1; } @@ -14,7 +14,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { // non-empty switch *not* in last-statement-in-function position // (return statements might be inserted into the switch cases otherwise) - switch (pos) { + switch pos { case 1: { pos = 0; break; @@ -41,7 +41,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { } // non-empty switch in last-statement-in-function position - switch (pos) { + switch pos { case 1: { pos = 0; break; @@ -61,7 +61,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { } fn switch_default_break(i: i32) { - switch (i) { + switch i { default: { break; } @@ -80,7 +80,7 @@ fn switch_case_break() { fn loop_switch_continue(x: i32) { loop { - switch (x) { + switch x { case 1: { continue; } diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index d728c56be..c96307806 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -11,7 +11,7 @@ struct FragmentIn { @stage(fragment) fn main(in: FragmentIn) -> @location(0) vec4 { - if (in.primitive_index % 2u == 0u) { + if in.primitive_index % 2u == 0u { return in.color; } else { return vec4(vec3(1.0) - in.color.rgb, in.color.a); diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 5252d4031..9d472294f 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -30,7 +30,7 @@ fn splat() -> vec4 { fn unary() -> i32 { let a = 1; - if (!true) { return a; } else { return ~a; }; + if !true { return a; } else { return ~a; }; } fn bool_cast(x: vec3) -> vec3 { diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 48334cac1..847de8630 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -21,7 +21,7 @@ fn vert_main( @stage(fragment) fn frag_main(@location(0) uv : vec2) -> @location(0) vec4 { let color = textureSample(u_texture, u_sampler, uv); - if (color.a == 0.0) { + if color.a == 0.0 { discard; } // forcing the expression here to be emitted in order to check the diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index bbd0a3f68..c50769d11 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -23,7 +23,7 @@ var t_shadow: texture_depth_2d_array; var sampler_shadow: sampler_comparison; fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { - if (homogeneous_coords.w <= 0.0) { + if homogeneous_coords.w <= 0.0 { return 1.0; } let flip_correction = vec2(0.5, -0.5); @@ -44,7 +44,7 @@ fn fs_main( var color = c_ambient; var i: u32 = 0u; loop { - if (i >= min(u_globals.num_lights.x, c_max_lights)) { + if i >= min(u_globals.num_lights.x, c_max_lights) { break; } let light = s_lights.data[i]; From e1e9848706a20c5eb1a435521c2fc04121c45eee Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 15 Feb 2022 13:06:55 +0300 Subject: [PATCH 1579/2212] [wgsl-out] Optional parentheses for if and switch --- src/back/wgsl/writer.rs | 8 +++---- tests/out/wgsl/246-collatz-comp.wgsl | 4 ++-- tests/out/wgsl/932-for-loop-if-vert.wgsl | 2 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 4 ++-- tests/out/wgsl/boids.wgsl | 24 ++++++++++---------- tests/out/wgsl/collatz.wgsl | 4 ++-- tests/out/wgsl/constant-array-size-vert.wgsl | 2 +- tests/out/wgsl/control-flow.wgsl | 14 ++++++------ tests/out/wgsl/extra.wgsl | 2 +- tests/out/wgsl/operators.wgsl | 2 +- tests/out/wgsl/quad.wgsl | 2 +- tests/out/wgsl/shadow.wgsl | 4 ++-- 12 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 4e4cd7046..fa32c6b6d 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -691,9 +691,9 @@ impl Writer { ref reject, } => { write!(self.out, "{}", level)?; - write!(self.out, "if (")?; + write!(self.out, "if ")?; self.write_expr(module, condition, func_ctx)?; - writeln!(self.out, ") {{")?; + writeln!(self.out, " {{")?; let l2 = level.next(); for sta in accept { @@ -845,9 +845,9 @@ impl Writer { } => { // Start the switch write!(self.out, "{}", level)?; - write!(self.out, "switch(")?; + write!(self.out, "switch ")?; self.write_expr(module, selector, func_ctx)?; - writeln!(self.out, ") {{")?; + writeln!(self.out, " {{")?; let type_postfix = match *func_ctx.info[selector].ty.inner_with(&module.types) { crate::TypeInner::Scalar { diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index e983ee8de..a990dd31b 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -13,12 +13,12 @@ fn collatz_iterations(n: u32) -> u32 { n_1 = n; loop { let _e7 = n_1; - if (!((_e7 != u32(1)))) { + if !((_e7 != u32(1))) { break; } { let _e14 = n_1; - if (((f32(_e14) % f32(2)) == f32(0))) { + if ((f32(_e14) % f32(2)) == f32(0)) { { let _e22 = n_1; n_1 = (_e22 / u32(2)); diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl index 9927e46b0..3bc7924b2 100644 --- a/tests/out/wgsl/932-for-loop-if-vert.wgsl +++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl @@ -3,7 +3,7 @@ fn main_1() { loop { let _e2 = i; - if (!((_e2 < 1))) { + if !((_e2 < 1)) { break; } { diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index b5913a626..bf12b515d 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -801,7 +801,7 @@ fn main_1() { let _e224 = i; let _e225 = global_2.NumLights; let _e229 = i; - if (!(((_e224 < i32(_e225.x)) && (_e229 < 10)))) { + if !(((_e224 < i32(_e225.x)) && (_e229 < 10))) { break; } { @@ -828,7 +828,7 @@ fn main_1() { let _e261 = i_1; let _e262 = global_2.NumLights; let _e266 = i_1; - if (!(((_e261 < i32(_e262.y)) && (_e266 < 1)))) { + if !(((_e261 < i32(_e262.y)) && (_e266 < 1))) { break; } { diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index b0f3180b2..1910535ab 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -40,7 +40,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { var i: u32 = 0u; let index = global_invocation_id.x; - if ((index >= NUM_PARTICLES)) { + if (index >= NUM_PARTICLES) { return; } let _e10 = particlesSrc.particles[index].pos; @@ -52,11 +52,11 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { colVel = vec2(0.0, 0.0); loop { let _e37 = i; - if ((_e37 >= NUM_PARTICLES)) { + if (_e37 >= NUM_PARTICLES) { break; } let _e39 = i; - if ((_e39 == index)) { + if (_e39 == index) { continue; } let _e42 = i; @@ -68,7 +68,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { let _e51 = pos; let _e52 = vPos; let _e55 = params.rule1Distance; - if ((distance(_e51, _e52) < _e55)) { + if (distance(_e51, _e52) < _e55) { let _e57 = cMass; let _e58 = pos; cMass = (_e57 + _e58); @@ -78,7 +78,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { let _e63 = pos; let _e64 = vPos; let _e67 = params.rule2Distance; - if ((distance(_e63, _e64) < _e67)) { + if (distance(_e63, _e64) < _e67) { let _e69 = colVel; let _e70 = pos; let _e71 = vPos; @@ -87,7 +87,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { let _e74 = pos; let _e75 = vPos; let _e78 = params.rule3Distance; - if ((distance(_e74, _e75) < _e78)) { + if (distance(_e74, _e75) < _e78) { let _e80 = cVel; let _e81 = vel; cVel = (_e80 + _e81); @@ -100,14 +100,14 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { } } let _e89 = cMassCount; - if ((_e89 > 0)) { + if (_e89 > 0) { let _e92 = cMass; let _e93 = cMassCount; let _e97 = vPos; cMass = ((_e92 / vec2(f32(_e93))) - _e97); } let _e99 = cVelCount; - if ((_e99 > 0)) { + if (_e99 > 0) { let _e102 = cVel; let _e103 = cVelCount; cVel = (_e102 / vec2(f32(_e103))); @@ -128,19 +128,19 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { let _e134 = params.deltaT; vPos = (_e131 + (_e132 * _e134)); let _e138 = vPos.x; - if ((_e138 < -1.0)) { + if (_e138 < -1.0) { vPos.x = 1.0; } let _e144 = vPos.x; - if ((_e144 > 1.0)) { + if (_e144 > 1.0) { vPos.x = -1.0; } let _e150 = vPos.y; - if ((_e150 < -1.0)) { + if (_e150 < -1.0) { vPos.y = 1.0; } let _e156 = vPos.y; - if ((_e156 > 1.0)) { + if (_e156 > 1.0) { vPos.y = -1.0; } let _e164 = vPos; diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index b4fb82c46..334a779e6 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -12,11 +12,11 @@ fn collatz_iterations(n_base: u32) -> u32 { n = n_base; loop { let _e5 = n; - if ((_e5 <= 1u)) { + if (_e5 <= 1u) { break; } let _e8 = n; - if (((_e8 % 2u) == 0u)) { + if ((_e8 % 2u) == 0u) { let _e13 = n; n = (_e13 / 2u); } else { diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 26e32eda7..f0d5474a2 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -11,7 +11,7 @@ fn function_() -> vec4 { loop { let _e9 = i; - if (!((_e9 < 42))) { + if !((_e9 < 42)) { break; } { diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index fad5a45e8..e31585d0b 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -1,5 +1,5 @@ fn switch_default_break(i: i32) { - switch(i) { + switch i { default: { break; } @@ -7,7 +7,7 @@ fn switch_default_break(i: i32) { } fn switch_case_break() { - switch(0) { + switch 0 { case 0: { break; } @@ -19,7 +19,7 @@ fn switch_case_break() { fn loop_switch_continue(x: i32) { loop { - switch(x) { + switch x { case 1: { continue; } @@ -36,13 +36,13 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { storageBarrier(); workgroupBarrier(); - switch(1) { + switch 1 { default: { pos = 1; } } let _e4 = pos; - switch(_e4) { + switch _e4 { case 1: { pos = 0; break; @@ -60,14 +60,14 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { pos = 3; } } - switch(0u) { + switch 0u { case 0u: { } default: { } } let _e10 = pos; - switch(_e10) { + switch _e10 { case 1: { pos = 0; break; diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index 5dc44e463..6db9c1923 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -12,7 +12,7 @@ var pc: PushConstants; @stage(fragment) fn main(in: FragmentIn) -> @location(0) vec4 { - if (((in.primitive_index % 2u) == 0u)) { + if ((in.primitive_index % 2u) == 0u) { return in.color; } else { return vec4((vec3(1.0) - in.color.xyz), in.color.w); diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 53c1c1701..eac31fec0 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -26,7 +26,7 @@ fn splat() -> vec4 { } fn unary() -> i32 { - if (!(true)) { + if !(true) { return 1; } else { return ~(1); diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 0f6e3f56d..641f2fd28 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -18,7 +18,7 @@ fn vert_main(@location(0) pos: vec2, @location(1) uv: vec2) -> VertexO @stage(fragment) fn frag_main(@location(0) uv_1: vec2) -> @location(0) vec4 { let color = textureSample(u_texture, u_sampler, uv_1); - if ((color.w == 0.0)) { + if (color.w == 0.0) { discard; } let premultiplied = (color.w * color); diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index d1e2ace3e..393003ad2 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -25,7 +25,7 @@ var t_shadow: texture_depth_2d_array; var sampler_shadow: sampler_comparison; fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { - if ((homogeneous_coords.w <= 0.0)) { + if (homogeneous_coords.w <= 0.0) { return 1.0; } let flip_correction = vec2(0.5, -0.5); @@ -43,7 +43,7 @@ fn fs_main(@location(0) raw_normal: vec3, @location(1) position: vec4) loop { let _e12 = i; let _e15 = u_globals.num_lights.x; - if ((_e12 >= min(_e15, c_max_lights))) { + if (_e12 >= min(_e15, c_max_lights)) { break; } let _e19 = i; From 771d62710c064b80e3dd27d7622a1c165f87c361 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 10 Feb 2022 11:44:41 -0800 Subject: [PATCH 1580/2212] [msl-out] Consolidate numeric type formatting. --- src/back/msl/writer.rs | 183 ++++++++++++++++------------------------ tests/out/msl/image.msl | 2 +- 2 files changed, 75 insertions(+), 110 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 4546309e9..acf787f40 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -25,6 +25,50 @@ const WRAPPED_ARRAY_FIELD: &str = "inner"; // Some more general handling of pointers is needed to be implemented here. const ATOMIC_REFERENCE: &str = "&"; +/// Write the Metal name for a Naga numeric type: scalar, vector, or matrix. +/// +/// The `sizes` slice determines whether this function writes a +/// scalar, vector, or matrix type: +/// +/// - An empty slice produces a scalar type. +/// - A one-element slice produces a vector type. +/// - A two element slice `[ROWS COLUMNS]` produces a matrix of the given size. +fn put_numeric_type( + out: &mut impl Write, + kind: crate::ScalarKind, + sizes: &[crate::VectorSize], +) -> Result<(), FmtError> { + match (kind, sizes) { + (crate::ScalarKind::Uint, &[]) => { + // Work around Metal compiler bug: scalar `uint` requires namespace. + write!(out, "{}::uint", NAMESPACE) + } + (kind, &[]) => { + write!(out, "{}", kind.to_msl_name()) + } + (kind, &[rows]) => { + write!( + out, + "{}::{}{}", + NAMESPACE, + kind.to_msl_name(), + back::vector_size_str(rows) + ) + } + (kind, &[rows, columns]) => { + write!( + out, + "{}::{}{}x{}", + NAMESPACE, + kind.to_msl_name(), + back::vector_size_str(columns), + back::vector_size_str(rows) + ) + } + (_, _) => Ok(()), // not meaningful + } +} + struct TypeContext<'a> { handle: Handle, arena: &'a crate::UniqueArena, @@ -42,34 +86,13 @@ impl<'a> Display for TypeContext<'a> { } match ty.inner { - crate::TypeInner::Scalar { kind, .. } => { - match kind { - // work around Metal toolchain bug with `uint` typedef - crate::ScalarKind::Uint => write!(out, "{}::uint", NAMESPACE), - _ => write!(out, "{}", kind.to_msl_name()), - } - } + crate::TypeInner::Scalar { kind, .. } => put_numeric_type(out, kind, &[]), crate::TypeInner::Atomic { kind, .. } => { write!(out, "{}::atomic_{}", NAMESPACE, kind.to_msl_name()) } - crate::TypeInner::Vector { size, kind, .. } => { - write!( - out, - "{}::{}{}", - NAMESPACE, - kind.to_msl_name(), - back::vector_size_str(size), - ) - } + crate::TypeInner::Vector { size, kind, .. } => put_numeric_type(out, kind, &[size]), crate::TypeInner::Matrix { columns, rows, .. } => { - write!( - out, - "{}::{}{}x{}", - NAMESPACE, - crate::ScalarKind::Float.to_msl_name(), - back::vector_size_str(columns), - back::vector_size_str(rows), - ) + put_numeric_type(out, crate::ScalarKind::Float, &[rows, columns]) } crate::TypeInner::Pointer { base, space } => { let sub = Self { @@ -84,39 +107,21 @@ impl<'a> Display for TypeContext<'a> { write!(out, "{} {}&", space_name, sub) } crate::TypeInner::ValuePointer { - size: None, + size, kind, width: _, space, } => { - let space_name = match space.to_msl_name() { - Some(name) => name, + match space.to_msl_name() { + Some(name) => write!(out, "{} ", name)?, None => return Ok(()), }; - write!(out, "{} ", space_name)?; - if kind == crate::ScalarKind::Uint { - write!(out, "{}::", NAMESPACE)?; - } - write!(out, "{}&", kind.to_msl_name()) - } - crate::TypeInner::ValuePointer { - size: Some(size), - kind, - width: _, - space, - } => { - let space_name = match space.to_msl_name() { - Some(name) => name, - None => return Ok(()), + match size { + Some(rows) => put_numeric_type(out, kind, &[rows])?, + None => put_numeric_type(out, kind, &[])?, }; - write!( - out, - "{} {}::{}{}&", - space_name, - NAMESPACE, - kind.to_msl_name(), - back::vector_size_str(size), - ) + + write!(out, "&") } crate::TypeInner::Array { base, .. } => { let sub = Self { @@ -626,12 +631,17 @@ impl Writer { context: &ExpressionContext, ) -> BackendResult { // coordinates in IR are int, but Metal expects uint - let size_str = match *context.resolve_type(expr) { - crate::TypeInner::Scalar { .. } => "", - crate::TypeInner::Vector { size, .. } => back::vector_size_str(size), + match *context.resolve_type(expr) { + crate::TypeInner::Scalar { .. } => { + put_numeric_type(&mut self.out, crate::ScalarKind::Uint, &[])? + } + crate::TypeInner::Vector { size, .. } => { + put_numeric_type(&mut self.out, crate::ScalarKind::Uint, &[size])? + } _ => return Err(Error::Validation), }; - write!(self.out, "{}::uint{}(", NAMESPACE, size_str)?; + + write!(self.out, "(")?; self.put_expression(expr, context, true)?; write!(self.out, ")")?; Ok(()) @@ -691,25 +701,11 @@ impl Writer { self.put_call_parameters(components.iter().cloned(), context)?; } crate::TypeInner::Vector { size, kind, .. } => { - write!( - self.out, - "{}::{}{}", - NAMESPACE, - kind.to_msl_name(), - back::vector_size_str(size) - )?; + put_numeric_type(&mut self.out, kind, &[size])?; self.put_call_parameters(components.iter().cloned(), context)?; } crate::TypeInner::Matrix { columns, rows, .. } => { - let kind = crate::ScalarKind::Float; - write!( - self.out, - "{}::{}{}x{}", - NAMESPACE, - kind.to_msl_name(), - back::vector_size_str(columns), - back::vector_size_str(rows) - )?; + put_numeric_type(&mut self.out, crate::ScalarKind::Float, &[rows, columns])?; self.put_call_parameters(components.iter().cloned(), context)?; } crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { @@ -927,10 +923,8 @@ impl Writer { crate::TypeInner::Scalar { kind, .. } => kind, _ => return Err(Error::Validation), }; - let scalar = scalar_kind.to_msl_name(); - let size = back::vector_size_str(size); - - write!(self.out, "{}::{}{}(", NAMESPACE, scalar, size)?; + put_numeric_type(&mut self.out, scalar_kind, &[size])?; + write!(self.out, "(")?; self.put_expression(value, context, true)?; write!(self.out, ")")?; } @@ -1349,7 +1343,6 @@ impl Writer { kind, convert, } => { - let scalar = kind.to_msl_name(); let (src_kind, src_width) = match *context.resolve_type(expr) { crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Vector { kind, width, .. } => (kind, width), @@ -1368,18 +1361,10 @@ impl Writer { write!(self.out, "{}<", op)?; match *context.resolve_type(expr) { crate::TypeInner::Vector { size, .. } => { - write!( - self.out, - "{}::{}{}", - NAMESPACE, - scalar, - back::vector_size_str(size) - )?; + put_numeric_type(&mut self.out, kind, &[size])? } - _ => { - write!(self.out, "{}", scalar)?; - } - } + _ => put_numeric_type(&mut self.out, kind, &[])?, + }; write!(self.out, ">(")?; self.put_expression(expr, context, true)?; write!(self.out, ")")?; @@ -1917,34 +1902,14 @@ impl Writer { }; write!(self.out, "{}", ty_name)?; } - TypeResolution::Value(crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - .. - }) => { - // work around Metal toolchain bug with `uint` typedef - write!(self.out, "{}::uint", NAMESPACE)?; - } TypeResolution::Value(crate::TypeInner::Scalar { kind, .. }) => { - write!(self.out, "{}", kind.to_msl_name())?; + put_numeric_type(&mut self.out, kind, &[])?; } TypeResolution::Value(crate::TypeInner::Vector { size, kind, .. }) => { - write!( - self.out, - "{}::{}{}", - NAMESPACE, - kind.to_msl_name(), - back::vector_size_str(size) - )?; + put_numeric_type(&mut self.out, kind, &[size])?; } TypeResolution::Value(crate::TypeInner::Matrix { columns, rows, .. }) => { - write!( - self.out, - "{}::{}{}x{}", - NAMESPACE, - crate::ScalarKind::Float.to_msl_name(), - back::vector_size_str(columns), - back::vector_size_str(rows), - )?; + put_numeric_type(&mut self.out, crate::ScalarKind::Float, &[rows, columns])?; } TypeResolution::Value(ref other) => { log::warn!("Type {:?} isn't a known local", other); //TEMP! diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 7fe677664..025f2a6a9 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -38,7 +38,7 @@ kernel void depth_load( metal::int2 dim_1 = int2(image_storage_src.get_width(), image_storage_src.get_height()); metal::int2 itc_1 = (dim_1 * static_cast(local_id_1.xy)) % metal::int2(10, 20); float val = image_depth_multisampled_src.read(metal::uint2(itc_1), static_cast(local_id_1.z)); - image_dst.write(metal::uint4(static_cast(val)), metal::uint(itc_1.x)); + image_dst.write(metal::uint4(static_cast(val)), metal::uint(itc_1.x)); return; } From 7d0644589755efefd7c6c7307ba59418f7af6f84 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 12 Jan 2022 16:03:15 -0800 Subject: [PATCH 1581/2212] [hlsl-out] Remove `MipLevelCoordinate` type. Validation insures that `ImageLoad` expressions always have an `index` operand when the image's type requires it, so there is no need for `MipLevelCoordinate::Zero`. This means that `Option>` serves adequately for this case. --- src/back/hlsl/help.rs | 24 +++++------------------- src/back/hlsl/writer.rs | 28 ++++++++++------------------ 2 files changed, 15 insertions(+), 37 deletions(-) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 428df8afe..91553a508 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -101,13 +101,6 @@ impl From for ImageQuery { } } -#[derive(Clone, Copy, PartialEq)] -pub(super) enum MipLevelCoordinate { - NotApplicable, - Zero, - Expression(Handle), -} - impl<'a, W: Write> super::Writer<'a, W> { pub(super) fn write_image_type( &mut self, @@ -497,13 +490,12 @@ impl<'a, W: Write> super::Writer<'a, W> { kind: &str, coordinate: Handle, array_index: Option>, - mip_level: MipLevelCoordinate, + mip_level: Option>, module: &crate::Module, func_ctx: &FunctionCtx, ) -> BackendResult { // HLSL expects the array index to be merged with the coordinate - let extra = array_index.is_some() as usize - + (mip_level != MipLevelCoordinate::NotApplicable) as usize; + let extra = array_index.is_some() as usize + (mip_level.is_some()) as usize; if extra == 0 { self.write_expr(module, coordinate, func_ctx)?; } else { @@ -518,15 +510,9 @@ impl<'a, W: Write> super::Writer<'a, W> { write!(self.out, ", ")?; self.write_expr(module, expr, func_ctx)?; } - match mip_level { - MipLevelCoordinate::NotApplicable => {} - MipLevelCoordinate::Zero => { - write!(self.out, ", 0")?; - } - MipLevelCoordinate::Expression(expr) => { - write!(self.out, ", ")?; - self.write_expr(module, expr, func_ctx)?; - } + if let Some(expr) = mip_level { + write!(self.out, ", ")?; + self.write_expr(module, expr, func_ctx)?; } write!(self.out, ")")?; } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 10e928c62..e2fccb0e1 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,5 +1,5 @@ use super::{ - help::{MipLevelCoordinate, WrappedArrayLength, WrappedConstructor, WrappedImageQuery}, + help::{WrappedArrayLength, WrappedConstructor, WrappedImageQuery}, storage::StoreValue, BackendResult, Error, Options, }; @@ -1629,7 +1629,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { "float", coordinate, array_index, - MipLevelCoordinate::NotApplicable, + None, module, func_ctx, )?; @@ -1697,27 +1697,19 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { index, } => { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-load - let (ms, storage) = match *func_ctx.info[image].ty.inner_with(&module.types) { + let (sample, mip_level) = match *func_ctx.info[image].ty.inner_with(&module.types) { TypeInner::Image { class, .. } => match class { - crate::ImageClass::Sampled { multi, .. } - | crate::ImageClass::Depth { multi } => (multi, false), - crate::ImageClass::Storage { .. } => (false, true), + crate::ImageClass::Sampled { multi: true, .. } + | crate::ImageClass::Depth { multi: true } => (index, None), + crate::ImageClass::Storage { .. } => (None, None), + _ => (None, index), }, - _ => (false, false), + _ => (None, None), }; self.write_expr(module, image, func_ctx)?; write!(self.out, ".Load(")?; - let mip_level = if ms || storage { - MipLevelCoordinate::NotApplicable - } else { - match index { - Some(expr) => MipLevelCoordinate::Expression(expr), - None => MipLevelCoordinate::Zero, - } - }; - self.write_texture_coordinates( "int", coordinate, @@ -1727,9 +1719,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { func_ctx, )?; - if ms { + if let Some(sample) = sample { write!(self.out, ", ")?; - self.write_expr(module, index.unwrap(), func_ctx)?; + self.write_expr(module, sample, func_ctx)?; } // close bracket for Load function From 75c86a6c3d1327618e7f2068e9a2e3b4eb32570f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 21 Dec 2021 17:02:51 -0800 Subject: [PATCH 1582/2212] [spv-out] Access trait doc fixes. --- src/back/spv/image.rs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index bbfdf5c5b..2ce3a30b4 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -35,16 +35,18 @@ struct ImageCoordinates { /// A trait for image access (load or store) code generators. /// -/// When generating code for `ImageLoad` and `ImageStore` expressions, the image -/// bounds checks policy can affect some operands of the image access -/// instruction (the coordinates, level of detail, and sample index), but other -/// aspects are unaffected: the image id, result type (if any), and the specific -/// SPIR-V instruction used. +/// Types implementing this trait hold information about an `ImageStore` or +/// `ImageLoad` operation that is not affected by the bounds check policy. The +/// `generate` method emits code for the access, given the results of bounds +/// checking. /// -/// This struct holds the latter category of information, saving us from passing -/// a half-dozen parameters along the various code paths. The parts that are -/// affected by bounds checks, are passed as parameters to the `generate` -/// method. +/// The [`image`] bounds checks policy affects access coordinates, level of +/// detail, and sample index, but never the image id, result type (if any), or +/// the specific SPIR-V instruction used. Types that implement this trait gather +/// together the latter category, so we don't have to plumb them through the +/// bounds-checking code. +/// +/// [`image`]: crate::proc::BoundsCheckPolicies::index trait Access { /// The Rust type that represents SPIR-V values and types for this access. /// From 763b0bcc90f55df50088be89d09c59ad269d3f37 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 22 Dec 2021 12:42:55 -0800 Subject: [PATCH 1583/2212] FunctionInfo doc fixes, more specific variable names. --- src/valid/analyzer.rs | 70 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 14 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index b634c203c..b95a8a348 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -199,17 +199,51 @@ pub struct FunctionInfo { pub uniformity: Uniformity, /// Function may kill the invocation. pub may_kill: bool, - /// Set of image-sampler pais used with sampling. + + /// All pairs of (texture, sampler) globals that may be used together in + /// sampling operations by this function and its callees. This includes + /// pairings that arise when this function passes textures and samplers as + /// arguments to its callees. + /// + /// This table does not include uses of textures and samplers passed as + /// arguments to this function itself, since we do not know which globals + /// those will be. However, this table *is* exhaustive when computed for an + /// entry point function: entry points never receive textures or samplers as + /// arguments, so all an entry point's sampling can be reported in terms of + /// globals. + /// + /// The GLSL back end uses this table to construct reflection info that + /// clients need to construct texture-combined sampler values. pub sampling_set: crate::FastHashSet, - /// Vector of global variable usages. + + /// How this function and its callees use this module's globals. /// - /// Each item corresponds to a global variable in the module. + /// This is indexed by `Handle` indices. However, + /// `FunctionInfo` implements `std::ops::Index>`, + /// so you can simply index this struct with a global handle to retrieve + /// its usage information. global_uses: Box<[GlobalUse]>, - /// Vector of expression infos. + + /// Information about each expression in this function's body. /// - /// Each item corresponds to an expression in the function. + /// This is indexed by `Handle` indices. However, `FunctionInfo` + /// implements `std::ops::Index>`, so you can simply + /// index this struct with an expression handle to retrieve its + /// `ExpressionInfo`. expressions: Box<[ExpressionInfo]>, - /// HashSet with information about sampling realized by the function + + /// All (texture, sampler) pairs that may be used together in sampling + /// operations by this function and its callees, whether they are accessed + /// as globals or passed as arguments. + /// + /// Participants are represented by [`GlobalVariable`] handles whenever + /// possible, and otherwise by indices of this function's arguments. + /// + /// When analyzing a function call, we combine this data about the callee + /// with the actual arguments being passed to produce the callers' own + /// `sampling_set` and `sampling` tables. + /// + /// [`GlobalVariable`]: crate::GlobalVariable sampling: crate::FastHashSet, } @@ -309,14 +343,15 @@ impl FunctionInfo { /// Inherit information from a called function. fn process_call( &mut self, - info: &Self, + callee: &Self, arguments: &[Handle], expression_arena: &Arena, ) -> Result> { - for key in info.sampling_set.iter() { - self.sampling_set.insert(key.clone()); - } - for sampling in info.sampling.iter() { + self.sampling_set + .extend(callee.sampling_set.iter().cloned()); + for sampling in callee.sampling.iter() { + // If the callee was passed the texture or sampler as an argument, + // we may now be able to determine which globals those referred to. let image_storage = match sampling.image { GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var), GlobalOrArgument::Argument(i) => { @@ -343,6 +378,10 @@ impl FunctionInfo { } }; + // If we've managed to pin both the image and sampler down to + // specific globals, record that in our `sampling_set`. Otherwise, + // record as much as we do know in our own `sampling` table, for our + // callers to sort out. match (image_storage, sampler_storage) { (GlobalOrArgument::Global(image), GlobalOrArgument::Global(sampler)) => { self.sampling_set.insert(SamplingKey { image, sampler }); @@ -352,12 +391,15 @@ impl FunctionInfo { } } } - for (mine, other) in self.global_uses.iter_mut().zip(info.global_uses.iter()) { + + // Inherit global use from our callees. + for (mine, other) in self.global_uses.iter_mut().zip(callee.global_uses.iter()) { *mine |= *other; } + Ok(FunctionUniformity { - result: info.uniformity.clone(), - exit: if info.may_kill { + result: callee.uniformity.clone(), + exit: if callee.may_kill { ExitFlags::MAY_KILL } else { ExitFlags::empty() From e904d2bfd62795f40e093b733ef910fb70e5af4a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 7 Feb 2022 14:10:28 -0800 Subject: [PATCH 1584/2212] [msl-out] Document why dot operator on ints requires baking. --- src/back/msl/writer.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index acf787f40..d0dea3ef1 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1856,8 +1856,12 @@ impl Writer { if min_ref_count <= expr_info.ref_count { self.need_bake_expressions.insert(expr.0); } - // if the expression is a Dot product with integer arguments, - // then the args needs baking as well + + // WGSL's `dot` function works on any `vecN` type, but Metal's only + // works on floating-point vectors, so we emit inline code for + // integer vector `dot` calls. But that code uses each argument `N` + // times, once for each component (see `put_dot_product`), so to + // avoid duplicated evaluation, we must bake integer operands. if let ( fun_handle, &Expression::Math { From 27cbce5b5d2adb5a55b3eeb99c8c2f11df83b2ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 5 Feb 2022 17:42:38 +0000 Subject: [PATCH 1585/2212] glsl-in: Add support for image declarations --- src/front/glsl/ast.rs | 3 ++ src/front/glsl/parser/types.rs | 87 +++++++++++++++++++++++++++------- src/front/glsl/types.rs | 51 ++++++++++++++++++++ src/front/glsl/variables.rs | 61 ++++++++++++++++++++---- 4 files changed, 176 insertions(+), 26 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 4c2054bfe..759cda38f 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -139,6 +139,8 @@ pub enum QualifierKey<'a> { String(Cow<'a, str>), /// Used for `std140` and `std430` layout qualifiers Layout, + /// Used for image formats + Format, } #[derive(Debug)] @@ -146,6 +148,7 @@ pub enum QualifierValue { None, Uint(u32), Layout(StructLayout), + Format(crate::StorageFormat), } #[derive(Debug, Default)] diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 3fb1f355c..0772596df 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -285,24 +285,28 @@ impl<'source> ParsingContext<'source> { QualifierKey::Layout, QualifierValue::Layout(StructLayout::Std430), ), - _ => { - let key = QualifierKey::String(name.into()); - let value = if self.bump_if(parser, TokenValue::Assign).is_some() { - let (value, end_meta) = match self.parse_uint_constant(parser) { - Ok(v) => v, - Err(e) => { - parser.errors.push(e); - (0, Span::default()) - } - }; - token.meta.subsume(end_meta); - - QualifierValue::Uint(value) + word => { + if let Some(format) = map_image_format(word) { + (QualifierKey::Format, QualifierValue::Format(format)) } else { - QualifierValue::None - }; + let key = QualifierKey::String(name.into()); + let value = if self.bump_if(parser, TokenValue::Assign).is_some() { + let (value, end_meta) = match self.parse_uint_constant(parser) { + Ok(v) => v, + Err(e) => { + parser.errors.push(e); + (0, Span::default()) + } + }; + token.meta.subsume(end_meta); - (key, value) + QualifierValue::Uint(value) + } else { + QualifierValue::None + }; + + (key, value) + } } }; @@ -326,3 +330,54 @@ impl<'source> ParsingContext<'source> { }) } } + +fn map_image_format(word: &str) -> Option { + let format = match word { + // float-image-format-qualifier: + "rgba32f" => crate::StorageFormat::Rgba32Float, + "rgba16f" => crate::StorageFormat::Rgba16Float, + "rg32f" => crate::StorageFormat::Rg32Float, + "rg16f" => crate::StorageFormat::Rg16Float, + "r11f_g11f_b10f" => crate::StorageFormat::Rg11b10Float, + "r32f" => crate::StorageFormat::R32Float, + "r16f" => crate::StorageFormat::R16Float, + "rgba16" => crate::StorageFormat::Rgba16Float, + "rgb10_a2" => crate::StorageFormat::Rgb10a2Unorm, + "rgba8" => crate::StorageFormat::Rgba8Unorm, + "rg16" => crate::StorageFormat::Rg16Float, + "rg8" => crate::StorageFormat::Rg8Unorm, + "r16" => crate::StorageFormat::R16Float, + "r8" => crate::StorageFormat::R8Unorm, + "rgba8_snorm" => crate::StorageFormat::Rgba8Snorm, + "rg8_snorm" => crate::StorageFormat::Rg8Snorm, + "r8_snorm" => crate::StorageFormat::R8Snorm, + // int-image-format-qualifier: + "rgba32i" => crate::StorageFormat::Rgba32Sint, + "rgba16i" => crate::StorageFormat::Rgba16Sint, + "rgba8i" => crate::StorageFormat::Rgba8Sint, + "rg32i" => crate::StorageFormat::Rg32Sint, + "rg16i" => crate::StorageFormat::Rg16Sint, + "rg8i" => crate::StorageFormat::Rg8Sint, + "r32i" => crate::StorageFormat::R32Sint, + "r16i" => crate::StorageFormat::R16Sint, + "r8i" => crate::StorageFormat::R8Sint, + // uint-image-format-qualifier: + "rgba32ui" => crate::StorageFormat::Rgba32Uint, + "rgba16ui" => crate::StorageFormat::Rgba16Uint, + "rgba8ui" => crate::StorageFormat::Rgba8Uint, + "rg32ui" => crate::StorageFormat::Rg32Uint, + "rg16ui" => crate::StorageFormat::Rg16Uint, + "rg8ui" => crate::StorageFormat::Rg8Uint, + "r32ui" => crate::StorageFormat::R32Uint, + "r16ui" => crate::StorageFormat::R16Uint, + "r8ui" => crate::StorageFormat::R8Uint, + // TODO: These next ones seem incorrect to me + // "rgba16_snorm" => crate::StorageFormat::Rgba16Float, + // "rg16_snorm" => crate::StorageFormat::Rg16Float, + // "r16_snorm" => crate::StorageFormat::R16Float, + // "rgb10_a2ui" => crate::StorageFormat::Rgb10a2Unorm, + _ => return None, + }; + + Some(format) +} diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index becc53ad6..425844cd6 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -150,9 +150,60 @@ pub fn parse_type(type_name: &str) -> Option { }) }; + let image_parse = |word: &str| { + let mut iter = word.split("image"); + + let texture_kind = |ty| { + Some(match ty { + "" => ScalarKind::Float, + "i" => ScalarKind::Sint, + "u" => ScalarKind::Uint, + _ => return None, + }) + }; + + let kind = iter.next()?; + let size = iter.next()?; + let kind = texture_kind(kind)?; + + let class = ImageClass::Storage { + format: match kind { + ScalarKind::Sint => crate::StorageFormat::Rgba32Sint, + ScalarKind::Uint => crate::StorageFormat::Rgba32Uint, + ScalarKind::Float => crate::StorageFormat::Rgba32Float, + ScalarKind::Bool => unreachable!(), + }, + access: crate::StorageAccess::all(), + }; + + // TODO: glsl support multisampled storage images, naga doesn't + let (dim, arrayed) = match size { + "1D" => (ImageDimension::D1, false), + "1DArray" => (ImageDimension::D1, true), + "2D" => (ImageDimension::D2, false), + "2DArray" => (ImageDimension::D2, true), + "3D" => (ImageDimension::D3, false), + // Naga doesn't support cube images and it's usefulness + // is questionable, so they won't be supported for now + // "Cube" => (ImageDimension::Cube, false), + // "CubeArray" => (ImageDimension::Cube, true), + _ => return None, + }; + + Some(Type { + name: None, + inner: TypeInner::Image { + dim, + arrayed, + class, + }, + }) + }; + vec_parse(word) .or_else(|| mat_parse(word)) .or_else(|| texture_parse(word)) + .or_else(|| image_parse(word)) } } } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 072b9f474..182097b74 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -393,7 +393,7 @@ impl Parser { body: &mut Block, VarDeclaration { qualifiers, - ty, + mut ty, name, init, meta, @@ -469,17 +469,58 @@ impl Parser { access.remove(restricted_access); } } - AddressSpace::Uniform => { - if let TypeInner::Image { .. } | TypeInner::Sampler { .. } = - self.module.types[ty].inner - { + AddressSpace::Uniform => match self.module.types[ty].inner { + TypeInner::Image { + class, + dim, + arrayed, + } => { + if let crate::ImageClass::Storage { + mut access, + mut format, + } = class + { + if let Some((restricted_access, _)) = + qualifiers.storage_acess.take() + { + access.remove(restricted_access); + } + + match qualifiers.layout_qualifiers.remove(&QualifierKey::Format) { + Some((QualifierValue::Format(f), _)) => format = f, + // TODO: glsl supports images without format qualifier + // if they are `writeonly` + None => self.errors.push(Error { + kind: ErrorKind::SemanticError( + "image types require a format layout qualifier".into(), + ), + meta, + }), + _ => unreachable!(), + } + + ty = self.module.types.insert( + Type { + name: None, + inner: TypeInner::Image { + dim, + arrayed, + class: crate::ImageClass::Storage { format, access }, + }, + }, + meta, + ); + } + space = AddressSpace::Handle - } else if qualifiers - .none_layout_qualifier("push_constant", &mut self.errors) - { - space = AddressSpace::PushConstant } - } + TypeInner::Sampler { .. } => space = AddressSpace::Handle, + _ => { + if qualifiers.none_layout_qualifier("push_constant", &mut self.errors) { + space = AddressSpace::PushConstant + } + } + }, AddressSpace::Function => space = AddressSpace::Private, _ => {} }; From 2ad4c13c983ea7532921237bc7ef4b18e3cab300 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 10 Feb 2022 20:26:14 +0000 Subject: [PATCH 1586/2212] Add support for image builtin functions --- src/front/glsl/ast.rs | 3 + src/front/glsl/builtins.rs | 273 +++++++++++++++++++++++---------- src/front/glsl/functions.rs | 67 +++++++- src/front/glsl/parser/types.rs | 80 +++++----- src/front/glsl/types.rs | 10 +- 5 files changed, 305 insertions(+), 128 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 759cda38f..dec73eed0 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -55,6 +55,9 @@ pub struct Overload { pub kind: FunctionKind, /// Wheter this function was already defined or is just a prototype pub defined: bool, + /// Wheter this overload is the one provided by the language or has + /// been redeclared by the user (builtins only) + pub internal: bool, /// Wheter or not this function returns void (nothing) pub void: bool, } diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 41c29ecb2..17eef6579 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -9,6 +9,16 @@ use crate::{ ScalarKind as Sk, Span, Type, TypeInner, VectorSize, }; +impl crate::ScalarKind { + fn dummy_storage_format(&self) -> crate::StorageFormat { + match *self { + Sk::Sint => crate::StorageFormat::R16Sint, + Sk::Uint => crate::StorageFormat::R16Uint, + _ => crate::StorageFormat::R16Float, + } + } +} + impl Module { /// Helper function, to create a function prototype for a builtin fn add_builtin(&mut self, args: Vec, builtin: MacroCall) -> Overload { @@ -34,6 +44,7 @@ impl Module { parameters_info, kind: FunctionKind::Macro(builtin), defined: false, + internal: true, void: false, } } @@ -231,8 +242,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module class, }; - let dim_value = image_dims_to_coords_size(dim); - let num_coords_from_dim = (dim_value + 1).min(3); + let num_coords_from_dim = image_dims_to_coords_size(dim).min(3); let mut num_coords = num_coords_from_dim; if shadow && proj { @@ -352,26 +362,8 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module class: ImageClass::Sampled { kind, multi }, }; - let coordinates = match (dim, arrayed) { - (Dim::D1, false) => TypeInner::Scalar { - kind: Sk::Sint, - width, - }, - _ => { - let dim_value = image_dims_to_coords_size(dim); - let size = match dim_value + arrayed as usize { - 1 => VectorSize::Bi, - 2 => VectorSize::Tri, - _ => VectorSize::Quad, - }; - - TypeInner::Vector { - size, - kind: Sk::Sint, - width, - } - } - }; + let dim_value = image_dims_to_coords_size(dim); + let coordinates = make_coords_arg(dim_value + arrayed as usize, Sk::Sint); let args = vec![ image, @@ -384,12 +376,122 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module declaration .overloads - .push(module.add_builtin(args, MacroCall::TexelFetch)) + .push(module.add_builtin(args, MacroCall::ImageLoad)) }; // Don't generate shadow images since they aren't supported texture_args_generator(TextureArgsOptions::MULTI, f) } + "imageSize" => { + let f = |kind: Sk, dim, arrayed, _, _| { + // Naga doesn't support cube images and it's usefulness + // is questionable, so they won't be supported for now + if dim == Dim::Cube { + return; + } + + let image = TypeInner::Image { + dim, + arrayed, + class: ImageClass::Storage { + format: kind.dummy_storage_format(), + access: crate::StorageAccess::empty(), + }, + }; + + declaration + .overloads + .push(module.add_builtin(vec![image], MacroCall::TextureSize { arrayed })) + }; + + texture_args_generator(TextureArgsOptions::empty(), f) + } + "imageLoad" => { + let f = |kind: Sk, dim, arrayed, _, _| { + // Naga doesn't support cube images and it's usefulness + // is questionable, so they won't be supported for now + if dim == Dim::Cube { + return; + } + + let image = TypeInner::Image { + dim, + arrayed, + class: ImageClass::Storage { + format: kind.dummy_storage_format(), + access: crate::StorageAccess::LOAD, + }, + }; + + let dim_value = image_dims_to_coords_size(dim); + let mut coord_size = dim_value + arrayed as usize; + // > Every OpenGL API call that operates on cubemap array + // > textures takes layer-faces, not array layers + // + // So this means that imageCubeArray only takes a three component + // vector coordinate and the third component is a layer index. + if Dim::Cube == dim && arrayed { + coord_size = 3 + } + let coordinates = make_coords_arg(coord_size, Sk::Sint); + + let args = vec![image, coordinates]; + + declaration + .overloads + .push(module.add_builtin(args, MacroCall::ImageLoad)) + }; + + // Don't generate shadow nor multisampled images since they aren't supported + texture_args_generator(TextureArgsOptions::empty(), f) + } + "imageStore" => { + let f = |kind: Sk, dim, arrayed, _, _| { + // Naga doesn't support cube images and it's usefulness + // is questionable, so they won't be supported for now + if dim == Dim::Cube { + return; + } + + let image = TypeInner::Image { + dim, + arrayed, + class: ImageClass::Storage { + format: kind.dummy_storage_format(), + access: crate::StorageAccess::STORE, + }, + }; + + let dim_value = image_dims_to_coords_size(dim); + let mut coord_size = dim_value + arrayed as usize; + // > Every OpenGL API call that operates on cubemap array + // > textures takes layer-faces, not array layers + // + // So this means that imageCubeArray only takes a three component + // vector coordinate and the third component is a layer index. + if Dim::Cube == dim && arrayed { + coord_size = 3 + } + let coordinates = make_coords_arg(coord_size, Sk::Sint); + + let args = vec![ + image, + coordinates, + TypeInner::Vector { + size: VectorSize::Quad, + kind, + width, + }, + ]; + + let mut overload = module.add_builtin(args, MacroCall::ImageStore); + overload.void = true; + declaration.overloads.push(overload) + }; + + // Don't generate shadow nor multisampled images since they aren't supported + texture_args_generator(TextureArgsOptions::empty(), f) + } "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" | "log" | "log2" | "radians" | "degrees" | "asinh" | "acosh" | "atanh" | "floatBitsToInt" | "floatBitsToUint" | "dFdx" | "dFdxFine" | "dFdxCoarse" | "dFdy" @@ -1244,6 +1346,7 @@ fn inject_common_builtin( ], kind: FunctionKind::Macro(fun), defined: false, + internal: true, void: false, }) } @@ -1434,7 +1537,8 @@ pub enum MacroCall { TextureSize { arrayed: bool, }, - TexelFetch, + ImageLoad, + ImageStore, MathFunction(MathFunction), BitfieldExtract, BitfieldInsert, @@ -1458,17 +1562,17 @@ impl MacroCall { body: &mut Block, args: &mut [Handle], meta: Span, - ) -> Result> { - match *self { + ) -> Result>> { + Ok(Some(match *self { MacroCall::Sampler => { ctx.samplers.insert(args[0], args[1]); - Ok(args[0]) + args[0] } MacroCall::SamplerShadow => { sampled_to_depth(&mut parser.module, ctx, args[0], meta, &mut parser.errors); parser.invalidate_expression(ctx, args[0], meta)?; ctx.samplers.insert(args[0], args[1]); - Ok(args[0]) + args[0] } MacroCall::Texture { proj, @@ -1591,7 +1695,7 @@ impl MacroCall { .map_or(SampleLevel::Auto, SampleLevel::Bias); } - texture_call(ctx, args[0], level, comps, texture_offset, body, meta) + texture_call(ctx, args[0], level, comps, texture_offset, body, meta)? } MacroCall::TextureSize { arrayed } => { @@ -1654,23 +1758,38 @@ impl MacroCall { expr = ctx.add_expression(Expression::Compose { components, ty }, meta, body) } - Ok(expr) + expr } - MacroCall::TexelFetch => { + MacroCall::ImageLoad => { let comps = parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; - Ok(ctx.add_expression( + ctx.add_expression( Expression::ImageLoad { image: args[0], coordinate: comps.coordinate, array_index: comps.array_index, - index: Some(args[2]), + index: args.get(2).copied(), }, Span::default(), body, - )) + ) } - MacroCall::MathFunction(fun) => Ok(ctx.add_expression( + MacroCall::ImageStore => { + let comps = + parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; + ctx.emit_flush(body); + body.push( + crate::Statement::ImageStore { + image: args[0], + coordinate: comps.coordinate, + array_index: comps.array_index, + value: args[2], + }, + meta, + ); + return Ok(None); + } + MacroCall::MathFunction(fun) => ctx.add_expression( Expression::Math { fun, arg: args[0], @@ -1680,7 +1799,7 @@ impl MacroCall { }, Span::default(), body, - )), + ), MacroCall::BitfieldInsert => { let conv_arg_2 = ctx.add_expression( Expression::As { @@ -1700,7 +1819,7 @@ impl MacroCall { Span::default(), body, ); - Ok(ctx.add_expression( + ctx.add_expression( Expression::Math { fun: MathFunction::InsertBits, arg: args[0], @@ -1710,7 +1829,7 @@ impl MacroCall { }, Span::default(), body, - )) + ) } MacroCall::BitfieldExtract => { let conv_arg_1 = ctx.add_expression( @@ -1731,7 +1850,7 @@ impl MacroCall { Span::default(), body, ); - Ok(ctx.add_expression( + ctx.add_expression( Expression::Math { fun: MathFunction::ExtractBits, arg: args[0], @@ -1741,17 +1860,17 @@ impl MacroCall { }, Span::default(), body, - )) + ) } - MacroCall::Relational(fun) => Ok(ctx.add_expression( + MacroCall::Relational(fun) => ctx.add_expression( Expression::Relational { fun, argument: args[0], }, Span::default(), body, - )), - MacroCall::Binary(op) => Ok(ctx.add_expression( + ), + MacroCall::Binary(op) => ctx.add_expression( Expression::Binary { op, left: args[0], @@ -1759,11 +1878,11 @@ impl MacroCall { }, Span::default(), body, - )), + ), MacroCall::Mod(size) => { ctx.implicit_splat(parser, &mut args[1], meta, size)?; - Ok(ctx.add_expression( + ctx.add_expression( Expression::Binary { op: BinaryOperator::Modulo, left: args[0], @@ -1771,12 +1890,12 @@ impl MacroCall { }, Span::default(), body, - )) + ) } MacroCall::Splatted(fun, size, i) => { ctx.implicit_splat(parser, &mut args[i], meta, size)?; - Ok(ctx.add_expression( + ctx.add_expression( Expression::Math { fun, arg: args[0], @@ -1786,9 +1905,9 @@ impl MacroCall { }, Span::default(), body, - )) + ) } - MacroCall::MixBoolean => Ok(ctx.add_expression( + MacroCall::MixBoolean => ctx.add_expression( Expression::Select { condition: args[2], accept: args[1], @@ -1796,12 +1915,12 @@ impl MacroCall { }, Span::default(), body, - )), + ), MacroCall::Clamp(size) => { ctx.implicit_splat(parser, &mut args[1], meta, size)?; ctx.implicit_splat(parser, &mut args[2], meta, size)?; - Ok(ctx.add_expression( + ctx.add_expression( Expression::Math { fun: MathFunction::Clamp, arg: args[0], @@ -1811,9 +1930,9 @@ impl MacroCall { }, Span::default(), body, - )) + ) } - MacroCall::BitCast(kind) => Ok(ctx.add_expression( + MacroCall::BitCast(kind) => ctx.add_expression( Expression::As { expr: args[0], kind, @@ -1821,16 +1940,16 @@ impl MacroCall { }, Span::default(), body, - )), - MacroCall::Derivate(axis) => Ok(ctx.add_expression( + ), + MacroCall::Derivate(axis) => ctx.add_expression( Expression::Derivative { axis, expr: args[0], }, Span::default(), body, - )), - } + ), + })) } } @@ -1910,9 +2029,10 @@ impl Parser { TypeInner::Vector { size, .. } => Some(size), _ => None, }; - let shadow = match class { - ImageClass::Depth { .. } => true, - _ => false, + let (shadow, storage) = match class { + ImageClass::Depth { .. } => (true, false), + ImageClass::Storage { .. } => (false, true), + _ => (false, false), }; let coordinate = match (image_size, coord_size) { @@ -1932,18 +2052,17 @@ impl Parser { let mut coord_index = image_size.map_or(1, |s| s as u32); - let array_index = match arrayed { - true => { - let index = coord_index; - coord_index += 1; + let array_index = if arrayed && !(storage && dim == ImageDimension::Cube) { + let index = coord_index; + coord_index += 1; - Some(ctx.add_expression( - Expression::AccessIndex { base: coord, index }, - Span::default(), - body, - )) - } - _ => None, + Some(ctx.add_expression( + Expression::AccessIndex { base: coord, index }, + Span::default(), + body, + )) + } else { + None }; let mut used_extra = false; let depth_ref = match shadow { @@ -2044,9 +2163,9 @@ bitflags::bitflags! { /// Influences the operation `texture_args_generator` struct TextureArgsOptions: u32 { /// Generates multisampled variants of images - const MULTI = 0; + const MULTI = 1 << 0; /// Generates shadow variants of images - const SHADOW = 1; + const SHADOW = 1 << 1; } } @@ -2092,11 +2211,11 @@ fn texture_args_generator( } /// Helper functions used to convert from a image dimension into a integer representing the -/// number of components needed for the coordinates vector (0 means scalar instead of vector) +/// number of components needed for the coordinates vector (1 means scalar instead of vector) fn image_dims_to_coords_size(dim: ImageDimension) -> usize { match dim { - ImageDimension::D1 => 0, - ImageDimension::D2 => 1, - _ => 2, + ImageDimension::D1 => 1, + ImageDimension::D2 => 2, + _ => 3, } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 3751e6374..f9c3177a7 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -674,8 +674,63 @@ impl Parser { let overload_param_ty = &self.module.types[*overload_parameter].inner; let call_arg_ty = self.resolve_type(ctx, call_argument.0, call_argument.1)?; - // If the types match there's no need to check for conversions so continue - if overload_param_ty == call_arg_ty { + // Storage images cannot be directly compared since while the access is part of the + // type in naga's IR, in glsl they are a qualifier and don't enter in the match as + // long as the access needed is satisfied. + if let ( + &TypeInner::Image { + class: + crate::ImageClass::Storage { + format: overload_format, + access: overload_access, + }, + dim: overload_dim, + arrayed: overload_arrayed, + }, + &TypeInner::Image { + class: + crate::ImageClass::Storage { + format: call_format, + access: call_access, + }, + dim: call_dim, + arrayed: call_arrayed, + }, + ) = (overload_param_ty, call_arg_ty) + { + // Images size must match otherwise the overload isn't what we want + let good_size = call_dim == overload_dim && call_arrayed == overload_arrayed; + // Glsl requires the formats to strictly match unless you are builtin + // function overload and have not been replaced, in which case we only + // check that the format scalar kind matches + let good_format = overload_format == call_format + || (overload.internal + && ScalarKind::from(overload_format) == ScalarKind::from(call_format)); + if !(good_size && good_format) { + continue 'outer; + } + + // While storage access mismatch is an error it isn't one that causes + // the overload matching to fail so we defer the error and consider + // that the images match exactly + if !call_access.contains(overload_access) { + self.errors.push(Error { + kind: ErrorKind::SemanticError( + format!( + "'{}': image needs {:?} access but only {:?} was provided", + name, overload_access, call_access + ) + .into(), + ), + meta, + }); + } + + // The images satisfy the conditions to be considered as an exact match + new_conversions[i] = Conversion::Exact; + continue; + } else if overload_param_ty == call_arg_ty { + // If the types match there's no need to check for conversions so continue new_conversions[i] = Conversion::Exact; continue; } @@ -957,9 +1012,9 @@ impl Parser { Ok(result) } - FunctionKind::Macro(builtin) => builtin - .call(self, ctx, body, arguments.as_mut_slice(), meta) - .map(Some), + FunctionKind::Macro(builtin) => { + builtin.call(self, ctx, body, arguments.as_mut_slice(), meta) + } } } @@ -1055,6 +1110,7 @@ impl Parser { parameters_info, kind: FunctionKind::Call(handle), defined: true, + internal: false, void, }); } @@ -1130,6 +1186,7 @@ impl Parser { parameters_info, kind: FunctionKind::Call(handle), defined: false, + internal: false, void, }); } diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 0772596df..47ad230d3 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -332,50 +332,52 @@ impl<'source> ParsingContext<'source> { } fn map_image_format(word: &str) -> Option { + use crate::StorageFormat as Sf; + let format = match word { // float-image-format-qualifier: - "rgba32f" => crate::StorageFormat::Rgba32Float, - "rgba16f" => crate::StorageFormat::Rgba16Float, - "rg32f" => crate::StorageFormat::Rg32Float, - "rg16f" => crate::StorageFormat::Rg16Float, - "r11f_g11f_b10f" => crate::StorageFormat::Rg11b10Float, - "r32f" => crate::StorageFormat::R32Float, - "r16f" => crate::StorageFormat::R16Float, - "rgba16" => crate::StorageFormat::Rgba16Float, - "rgb10_a2" => crate::StorageFormat::Rgb10a2Unorm, - "rgba8" => crate::StorageFormat::Rgba8Unorm, - "rg16" => crate::StorageFormat::Rg16Float, - "rg8" => crate::StorageFormat::Rg8Unorm, - "r16" => crate::StorageFormat::R16Float, - "r8" => crate::StorageFormat::R8Unorm, - "rgba8_snorm" => crate::StorageFormat::Rgba8Snorm, - "rg8_snorm" => crate::StorageFormat::Rg8Snorm, - "r8_snorm" => crate::StorageFormat::R8Snorm, + "rgba32f" => Sf::Rgba32Float, + "rgba16f" => Sf::Rgba16Float, + "rg32f" => Sf::Rg32Float, + "rg16f" => Sf::Rg16Float, + "r11f_g11f_b10f" => Sf::Rg11b10Float, + "r32f" => Sf::R32Float, + "r16f" => Sf::R16Float, + "rgba16" => Sf::Rgba16Float, + "rgb10_a2" => Sf::Rgb10a2Unorm, + "rgba8" => Sf::Rgba8Unorm, + "rg16" => Sf::Rg16Float, + "rg8" => Sf::Rg8Unorm, + "r16" => Sf::R16Float, + "r8" => Sf::R8Unorm, + "rgba8_snorm" => Sf::Rgba8Snorm, + "rg8_snorm" => Sf::Rg8Snorm, + "r8_snorm" => Sf::R8Snorm, // int-image-format-qualifier: - "rgba32i" => crate::StorageFormat::Rgba32Sint, - "rgba16i" => crate::StorageFormat::Rgba16Sint, - "rgba8i" => crate::StorageFormat::Rgba8Sint, - "rg32i" => crate::StorageFormat::Rg32Sint, - "rg16i" => crate::StorageFormat::Rg16Sint, - "rg8i" => crate::StorageFormat::Rg8Sint, - "r32i" => crate::StorageFormat::R32Sint, - "r16i" => crate::StorageFormat::R16Sint, - "r8i" => crate::StorageFormat::R8Sint, + "rgba32i" => Sf::Rgba32Sint, + "rgba16i" => Sf::Rgba16Sint, + "rgba8i" => Sf::Rgba8Sint, + "rg32i" => Sf::Rg32Sint, + "rg16i" => Sf::Rg16Sint, + "rg8i" => Sf::Rg8Sint, + "r32i" => Sf::R32Sint, + "r16i" => Sf::R16Sint, + "r8i" => Sf::R8Sint, // uint-image-format-qualifier: - "rgba32ui" => crate::StorageFormat::Rgba32Uint, - "rgba16ui" => crate::StorageFormat::Rgba16Uint, - "rgba8ui" => crate::StorageFormat::Rgba8Uint, - "rg32ui" => crate::StorageFormat::Rg32Uint, - "rg16ui" => crate::StorageFormat::Rg16Uint, - "rg8ui" => crate::StorageFormat::Rg8Uint, - "r32ui" => crate::StorageFormat::R32Uint, - "r16ui" => crate::StorageFormat::R16Uint, - "r8ui" => crate::StorageFormat::R8Uint, + "rgba32ui" => Sf::Rgba32Uint, + "rgba16ui" => Sf::Rgba16Uint, + "rgba8ui" => Sf::Rgba8Uint, + "rg32ui" => Sf::Rg32Uint, + "rg16ui" => Sf::Rg16Uint, + "rg8ui" => Sf::Rg8Uint, + "r32ui" => Sf::R32Uint, + "r16ui" => Sf::R16Uint, + "r8ui" => Sf::R8Uint, // TODO: These next ones seem incorrect to me - // "rgba16_snorm" => crate::StorageFormat::Rgba16Float, - // "rg16_snorm" => crate::StorageFormat::Rg16Float, - // "r16_snorm" => crate::StorageFormat::R16Float, - // "rgb10_a2ui" => crate::StorageFormat::Rgb10a2Unorm, + // "rgba16_snorm" => Sf::Rgba16Float, + // "rg16_snorm" => Sf::Rg16Float, + // "r16_snorm" => Sf::R16Float, + // "rgb10_a2ui" => Sf::Rgb10a2Unorm, _ => return None, }; diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 425844cd6..3900fe12d 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -164,15 +164,11 @@ pub fn parse_type(type_name: &str) -> Option { let kind = iter.next()?; let size = iter.next()?; - let kind = texture_kind(kind)?; + // TODO: Check that the texture format and the kind match + let _ = texture_kind(kind)?; let class = ImageClass::Storage { - format: match kind { - ScalarKind::Sint => crate::StorageFormat::Rgba32Sint, - ScalarKind::Uint => crate::StorageFormat::Rgba32Uint, - ScalarKind::Float => crate::StorageFormat::Rgba32Float, - ScalarKind::Bool => unreachable!(), - }, + format: crate::StorageFormat::R8Uint, access: crate::StorageAccess::all(), }; From 9e4f678c1360abf9ec3eed02f55662eb68ffe96b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 11 Feb 2022 23:27:44 +0000 Subject: [PATCH 1587/2212] glsl-in: Add tests for images --- tests/in/glsl/images.frag | 55 +++++++++++++++++ tests/out/wgsl/images-frag.wgsl | 102 ++++++++++++++++++++++++++++++++ 2 files changed, 157 insertions(+) create mode 100644 tests/in/glsl/images.frag create mode 100644 tests/out/wgsl/images-frag.wgsl diff --git a/tests/in/glsl/images.frag b/tests/in/glsl/images.frag new file mode 100644 index 000000000..41679b921 --- /dev/null +++ b/tests/in/glsl/images.frag @@ -0,0 +1,55 @@ +#version 460 core + +layout(rgba8, binding = 0) uniform image1D img1D; +layout(rgba8, binding = 1) uniform image2D img2D; +layout(rgba8, binding = 2) uniform image3D img3D; +// layout(rgba8, binding = 3) uniform imageCube imgCube; +layout(rgba8, binding = 4) uniform image1DArray img1DArray; +layout(rgba8, binding = 5) uniform image2DArray img2DArray; +// layout(rgba8, binding = 6) uniform imageCubeArray imgCubeArray; + +void testImg1D(in int coord) { + int size = imageSize(img1D); + vec4 c = imageLoad(img1D, coord); + imageStore(img1D, coord, vec4(2)); +} + +void testImg1DArray(in ivec2 coord) { + vec2 size = imageSize(img1DArray); + vec4 c = imageLoad(img1DArray, coord); + imageStore(img1DArray, coord, vec4(2)); +} + +void testImg2D(in ivec2 coord) { + vec2 size = imageSize(img2D); + vec4 c = imageLoad(img2D, coord); + imageStore(img2D, coord, vec4(2)); +} + +void testImg2DArray(in ivec3 coord) { + vec3 size = imageSize(img2DArray); + vec4 c = imageLoad(img2DArray, coord); + imageStore(img2DArray, coord, vec4(2)); +} + +void testImg3D(in ivec3 coord) { + vec3 size = imageSize(img3D); + vec4 c = imageLoad(img3D, coord); + imageStore(img3D, coord, vec4(2)); +} + +// Naga doesn't support cube images and it's usefulness +// is questionable, so they won't be supported for now +// void testImgCube(in ivec3 coord) { +// vec2 size = imageSize(imgCube); +// vec4 c = imageLoad(imgCube, coord); +// imageStore(imgCube, coord, vec4(2)); +// } +// +// void testImgCubeArray(in ivec3 coord) { +// vec3 size = imageSize(imgCubeArray); +// vec4 c = imageLoad(imgCubeArray, coord); +// imageStore(imgCubeArray, coord, vec4(2)); +// } + +void main() {} diff --git a/tests/out/wgsl/images-frag.wgsl b/tests/out/wgsl/images-frag.wgsl new file mode 100644 index 000000000..bd11927f0 --- /dev/null +++ b/tests/out/wgsl/images-frag.wgsl @@ -0,0 +1,102 @@ +@group(0) @binding(0) +var img1D: texture_storage_1d; +@group(0) @binding(1) +var img2D: texture_storage_2d; +@group(0) @binding(2) +var img3D: texture_storage_3d; +@group(0) @binding(4) +var img1DArray: texture_storage_1d_array; +@group(0) @binding(5) +var img2DArray: texture_storage_2d_array; + +fn testImg1D(coord: i32) { + var coord_1: i32; + var size: i32; + var c: vec4; + + coord_1 = coord; + let _e7 = textureDimensions(img1D); + size = _e7; + let _e10 = coord_1; + let _e11 = textureLoad(img1D, _e10); + c = _e11; + let _e17 = coord_1; + textureStore(img1D, _e17, vec4(f32(2))); + return; +} + +fn testImg1DArray(coord_2: vec2) { + var coord_3: vec2; + var size_1: vec2; + var c_1: vec4; + + coord_3 = coord_2; + let _e7 = textureDimensions(img1DArray); + let _e8 = textureNumLayers(img1DArray); + size_1 = vec2(vec2(_e7, _e8)); + let _e13 = coord_3; + let _e16 = textureLoad(img1DArray, _e13.x, _e13.y); + c_1 = _e16; + let _e22 = coord_3; + textureStore(img1DArray, _e22.x, _e22.y, vec4(f32(2))); + return; +} + +fn testImg2D(coord_4: vec2) { + var coord_5: vec2; + var size_2: vec2; + var c_2: vec4; + + coord_5 = coord_4; + let _e7 = textureDimensions(img2D); + size_2 = vec2(_e7); + let _e11 = coord_5; + let _e12 = textureLoad(img2D, _e11); + c_2 = _e12; + let _e18 = coord_5; + textureStore(img2D, _e18, vec4(f32(2))); + return; +} + +fn testImg2DArray(coord_6: vec3) { + var coord_7: vec3; + var size_3: vec3; + var c_3: vec4; + + coord_7 = coord_6; + let _e7 = textureDimensions(img2DArray); + let _e10 = textureNumLayers(img2DArray); + size_3 = vec3(vec3(_e7.x, _e7.y, _e10)); + let _e15 = coord_7; + let _e18 = textureLoad(img2DArray, _e15.xy, _e15.z); + c_3 = _e18; + let _e24 = coord_7; + textureStore(img2DArray, _e24.xy, _e24.z, vec4(f32(2))); + return; +} + +fn testImg3D(coord_8: vec3) { + var coord_9: vec3; + var size_4: vec3; + var c_4: vec4; + + coord_9 = coord_8; + let _e7 = textureDimensions(img3D); + size_4 = vec3(_e7); + let _e11 = coord_9; + let _e12 = textureLoad(img3D, _e11); + c_4 = _e12; + let _e18 = coord_9; + textureStore(img3D, _e18, vec4(f32(2))); + return; +} + +fn main_1() { + return; +} + +@stage(fragment) +fn main() { + main_1(); + return; +} From d0a4a193e372479024f789bcaf5f90bda305ca7f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 17 Feb 2022 09:09:28 -0500 Subject: [PATCH 1588/2212] Fix resetting WGSL parser --- src/front/wgsl/mod.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 8b2172c88..6d2f0fa46 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1242,6 +1242,13 @@ impl Parser { } } + fn reset(&mut self) { + self.scopes.clear(); + self.module_scope_identifiers.clear(); + self.lookup_type.clear(); + self.layouter.clear(); + } + fn push_scope(&mut self, scope: Scope, lexer: &Lexer<'_>) { self.scopes.push((scope, lexer.current_byte_offset())); } @@ -4344,9 +4351,7 @@ impl Parser { } pub fn parse(&mut self, source: &str) -> Result { - self.scopes.clear(); - self.lookup_type.clear(); - self.layouter.clear(); + self.reset(); let mut module = crate::Module::default(); let mut lexer = Lexer::new(source); From 231da54cd7348498fad7925512cd0104ca380d17 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 15 Feb 2022 19:00:00 -0500 Subject: [PATCH 1589/2212] Bincode support for naga-cli --- cli/Cargo.toml | 5 +++-- cli/src/main.rs | 5 +++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 36443d90f..ce12d0c06 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -14,8 +14,9 @@ name = "naga" path = "src/main.rs" [dependencies] -naga = { path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate"] } +naga = { path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate", "serialize", "deserialize"] } +bincode = "1" log = "0.4" codespan-reporting = "0.11" -env_logger = "0.8" +env_logger = "0.9" argh = "0.1.5" diff --git a/cli/src/main.rs b/cli/src/main.rs index 2f88e7feb..0f7f4fd6f 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -265,6 +265,7 @@ fn run() -> Result<(), Box> { .to_str() .ok_or(CliError("Input filename not valid unicode"))? { + "bin" => (bincode::deserialize(&input)?, None), "spv" => { let options = naga::front::spv::Options { adjust_coordinate_space: !params.keep_coordinate_space, @@ -360,6 +361,10 @@ fn run() -> Result<(), Box> { writeln!(file, "{:#?}", info)?; } } + "bin" => { + let file = fs::File::create(output_path)?; + bincode::serialize_into(file, &module)?; + } "metal" => { use naga::back::msl; From b05f648842f2c0bf10e28ecbb89c1bcf8114bb18 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 15 Feb 2022 19:23:30 -0500 Subject: [PATCH 1590/2212] bench: WGSL parsing --- Cargo.toml | 5 +++++ benches/criterion.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 benches/criterion.rs diff --git a/Cargo.toml b/Cargo.toml index daaefb6c5..b9abe27a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,10 @@ hlsl-out = [] span = ["codespan-reporting"] validate = [] +[[bench]] +name = "criterion" +harness = false + # MSRV warnings: # - arbitrary 1.0.3 requires Rust-1.51 # - bitflags 1.3 requires Rust-1.46 @@ -59,6 +63,7 @@ pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } [dev-dependencies] +criterion = { version = "0.3", features = ["html_reports"] } diff = "0.1" ron = "0.7" serde = { version = "1.0", features = ["derive"] } diff --git a/benches/criterion.rs b/benches/criterion.rs new file mode 100644 index 000000000..6c26ff731 --- /dev/null +++ b/benches/criterion.rs @@ -0,0 +1,46 @@ +use criterion::*; +use std::{fs, path::PathBuf}; + +fn gather_inputs(folder: &str, extension: &str) -> Vec { + let mut list = Vec::new(); + let read_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join(folder) + .read_dir() + .unwrap(); + for file_entry in read_dir { + match file_entry { + Ok(entry) => match entry.path().extension() { + Some(ostr) if &*ostr == extension => { + let input = fs::read_to_string(entry.path()).unwrap_or_default(); + list.push(input); + } + _ => continue, + }, + Err(e) => { + log::warn!("Skipping file: {:?}", e); + continue; + } + } + } + list +} + +fn frontends(c: &mut Criterion) { + let mut group = c.benchmark_group("tests/in"); + group.bench_function("wgsl", |b| { + let inputs = gather_inputs("tests/in", "wgsl"); + let mut parser = naga::front::wgsl::Parser::new(); + b.iter(move || { + for input in inputs.iter() { + parser.parse(input).unwrap(); + } + }); + }); +} + +fn validation(_c: &mut Criterion) {} + +fn backends(_c: &mut Criterion) {} + +criterion_group!(criterion, frontends, validation, backends,); +criterion_main!(criterion); From 5879f9ea7304365b7d5b4a77ff78bd9ffda305ba Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 15 Feb 2022 20:01:12 -0500 Subject: [PATCH 1591/2212] bench: glsl, spirv, and bincode inputs --- Cargo.toml | 1 + benches/criterion.rs | 66 ++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 61 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b9abe27a0..62d306c43 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -63,6 +63,7 @@ pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } [dev-dependencies] +bincode = "1" criterion = { version = "0.3", features = ["html_reports"] } diff = "0.1" ron = "0.7" diff --git a/benches/criterion.rs b/benches/criterion.rs index 6c26ff731..d4a429c03 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -1,7 +1,7 @@ use criterion::*; -use std::{fs, path::PathBuf}; +use std::{fs, path::PathBuf, slice}; -fn gather_inputs(folder: &str, extension: &str) -> Vec { +fn gather_inputs(folder: &str, extension: &str) -> Vec> { let mut list = Vec::new(); let read_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join(folder) @@ -11,8 +11,8 @@ fn gather_inputs(folder: &str, extension: &str) -> Vec { match file_entry { Ok(entry) => match entry.path().extension() { Some(ostr) if &*ostr == extension => { - let input = fs::read_to_string(entry.path()).unwrap_or_default(); - list.push(input); + let input = fs::read(entry.path()).unwrap_or_default(); + list.push(input.into_boxed_slice()); } _ => continue, }, @@ -25,17 +25,71 @@ fn gather_inputs(folder: &str, extension: &str) -> Vec { list } +fn parse_glsl(stage: naga::ShaderStage, inputs: &[Box<[u8]>]) { + let mut parser = naga::front::glsl::Parser::default(); + let options = naga::front::glsl::Options { + stage, + defines: Default::default(), + }; + for input in inputs.iter() { + let string = std::str::from_utf8(input).unwrap(); + parser.parse(&options, string).unwrap(); + } +} + fn frontends(c: &mut Criterion) { - let mut group = c.benchmark_group("tests/in"); + let mut group = c.benchmark_group("front"); + #[cfg(all(feature = "serialize", feature = "deserialize"))] + group.bench_function("bin", |b| { + let inputs_wgsl = gather_inputs("tests/in", "wgsl"); + let mut parser = naga::front::wgsl::Parser::new(); + let inputs_bin = inputs_wgsl + .iter() + .map(|input| { + let string = std::str::from_utf8(input).unwrap(); + let module = parser.parse(string).unwrap(); + bincode::serialize(&module).unwrap() + }) + .collect::>(); + b.iter(move || { + for input in inputs_bin.iter() { + bincode::deserialize::(input).unwrap(); + } + }); + }); + #[cfg(feature = "wgsl-in")] group.bench_function("wgsl", |b| { let inputs = gather_inputs("tests/in", "wgsl"); let mut parser = naga::front::wgsl::Parser::new(); b.iter(move || { for input in inputs.iter() { - parser.parse(input).unwrap(); + let string = std::str::from_utf8(input).unwrap(); + parser.parse(string).unwrap(); } }); }); + #[cfg(feature = "spv-in")] + group.bench_function("spv", |b| { + let inputs = gather_inputs("tests/in/spv", "spv"); + b.iter(move || { + let options = naga::front::spv::Options::default(); + for input in inputs.iter() { + let spv = + unsafe { slice::from_raw_parts(input.as_ptr() as *const u32, input.len() / 4) }; + let parser = naga::front::spv::Parser::new(spv.iter().cloned(), &options); + parser.parse().unwrap(); + } + }); + }); + #[cfg(feature = "glsl-in")] + group.bench_function("glsl", |b| { + let vert = gather_inputs("tests/in/glsl", "vert"); + b.iter(move || parse_glsl(naga::ShaderStage::Vertex, &vert)); + let frag = gather_inputs("tests/in/glsl", "frag"); + b.iter(move || parse_glsl(naga::ShaderStage::Vertex, &frag)); + //let comp = gather_inputs("tests/in/glsl", "comp"); + //b.iter(move || parse_glsl(naga::ShaderStage::Compute, &comp)); + }); } fn validation(_c: &mut Criterion) {} From 14b4a686c6c576a955a58755f9cbda426cb67523 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 15 Feb 2022 20:21:54 -0500 Subject: [PATCH 1592/2212] bench: validation --- benches/criterion.rs | 44 +++++++++++++++++++++++++++++++++++++++++++- src/valid/mod.rs | 13 +++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/benches/criterion.rs b/benches/criterion.rs index d4a429c03..153759bf9 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -87,12 +87,54 @@ fn frontends(c: &mut Criterion) { b.iter(move || parse_glsl(naga::ShaderStage::Vertex, &vert)); let frag = gather_inputs("tests/in/glsl", "frag"); b.iter(move || parse_glsl(naga::ShaderStage::Vertex, &frag)); + //TODO: hangs for some reason! //let comp = gather_inputs("tests/in/glsl", "comp"); //b.iter(move || parse_glsl(naga::ShaderStage::Compute, &comp)); }); } -fn validation(_c: &mut Criterion) {} +fn validation(c: &mut Criterion) { + #[cfg(feature = "wgsl-in")] + let inputs = { + let inputs_wgsl = gather_inputs("tests/in", "wgsl"); + let mut parser = naga::front::wgsl::Parser::new(); + inputs_wgsl + .iter() + .map(|input| { + let string = std::str::from_utf8(input).unwrap(); + parser.parse(string).unwrap() + }) + .collect::>() + }; + #[cfg(not(feature = "wgsl-in"))] + let inputs: Vec> = Vec::new(); + + let mut group = c.benchmark_group("valid"); + #[cfg(feature = "validate")] + group.bench_function("safe", |b| { + let mut validator = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ); + b.iter(|| { + for input in inputs.iter() { + validator.validate(input).unwrap(); + } + }); + }); + #[cfg(feature = "validate")] + group.bench_function("unsafe", |b| { + let mut validator = naga::valid::Validator::new( + naga::valid::ValidationFlags::empty(), + naga::valid::Capabilities::all(), + ); + b.iter(|| { + for input in inputs.iter() { + validator.validate(input).unwrap(); + } + }); + }); +} fn backends(_c: &mut Criterion) {} diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 1814b0be0..bc1a8dc6e 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -231,6 +231,17 @@ impl Validator { } } + /// Reset the validator internals + pub fn reset(&mut self) { + self.types.clear(); + self.layouter.clear(); + self.location_mask.clear(); + self.bind_group_masks.clear(); + self.select_cases.clear(); + self.valid_expression_list.clear(); + self.valid_expression_set.clear(); + } + #[cfg(feature = "validate")] fn validate_constant( &self, @@ -276,7 +287,9 @@ impl Validator { &mut self, module: &crate::Module, ) -> Result> { + self.reset(); self.reset_types(module.types.len()); + self.layouter .update(&module.types, &module.constants) .map_err(|e| { From c524a6beac85305585638b7745c9691e9f9ce4a5 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 15 Feb 2022 21:47:38 -0500 Subject: [PATCH 1593/2212] bench: backends --- benches/criterion.rs | 163 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 146 insertions(+), 17 deletions(-) diff --git a/benches/criterion.rs b/benches/criterion.rs index 153759bf9..4c3ead31b 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -39,7 +39,7 @@ fn parse_glsl(stage: naga::ShaderStage, inputs: &[Box<[u8]>]) { fn frontends(c: &mut Criterion) { let mut group = c.benchmark_group("front"); - #[cfg(all(feature = "serialize", feature = "deserialize"))] + #[cfg(all(feature = "wgsl-in", feature = "serialize", feature = "deserialize"))] group.bench_function("bin", |b| { let inputs_wgsl = gather_inputs("tests/in", "wgsl"); let mut parser = naga::front::wgsl::Parser::new(); @@ -93,22 +93,25 @@ fn frontends(c: &mut Criterion) { }); } -fn validation(c: &mut Criterion) { - #[cfg(feature = "wgsl-in")] - let inputs = { - let inputs_wgsl = gather_inputs("tests/in", "wgsl"); - let mut parser = naga::front::wgsl::Parser::new(); - inputs_wgsl - .iter() - .map(|input| { - let string = std::str::from_utf8(input).unwrap(); - parser.parse(string).unwrap() - }) - .collect::>() - }; - #[cfg(not(feature = "wgsl-in"))] - let inputs: Vec> = Vec::new(); +#[cfg(feature = "wgsl-in")] +fn gather_modules() -> Vec { + let inputs = gather_inputs("tests/in", "wgsl"); + let mut parser = naga::front::wgsl::Parser::new(); + inputs + .iter() + .map(|input| { + let string = std::str::from_utf8(input).unwrap(); + parser.parse(string).unwrap() + }) + .collect() +} +#[cfg(not(feature = "wgsl-in"))] +fn gather_modules() -> Vec { + Vec::new() +} +fn validation(c: &mut Criterion) { + let inputs = gather_modules(); let mut group = c.benchmark_group("valid"); #[cfg(feature = "validate")] group.bench_function("safe", |b| { @@ -136,7 +139,133 @@ fn validation(c: &mut Criterion) { }); } -fn backends(_c: &mut Criterion) {} +fn backends(c: &mut Criterion) { + #[cfg(feature = "validate")] + let inputs = { + let mut validator = naga::valid::Validator::new( + naga::valid::ValidationFlags::empty(), + naga::valid::Capabilities::empty(), + ); + let input_modules = gather_modules(); + input_modules + .into_iter() + .flat_map(|module| validator.validate(&module).ok().map(|info| (module, info))) + .collect::>() + }; + #[cfg(not(feature = "validate"))] + let inputs = Vec::<(naga::Module, naga::valid::ModuleInfo)>::new(); + + let mut group = c.benchmark_group("back"); + #[cfg(feature = "wgsl-out")] + group.bench_function("wgsl", |b| { + b.iter(|| { + let mut string = String::new(); + let flags = naga::back::wgsl::WriterFlags::empty(); + for &(ref module, ref info) in inputs.iter() { + let mut writer = naga::back::wgsl::Writer::new(&mut string, flags); + writer.write(module, info).unwrap(); + string.clear(); + } + }); + }); + + #[cfg(feature = "spv-out")] + group.bench_function("spv", |b| { + b.iter(|| { + let mut data = Vec::new(); + let options = naga::back::spv::Options::default(); + for &(ref module, ref info) in inputs.iter() { + let mut writer = naga::back::spv::Writer::new(&options).unwrap(); + writer.write(module, info, None, &mut data).unwrap(); + data.clear(); + } + }); + }); + #[cfg(feature = "spv-out")] + group.bench_function("spv-separate", |b| { + b.iter(|| { + let mut data = Vec::new(); + let options = naga::back::spv::Options::default(); + for &(ref module, ref info) in inputs.iter() { + let mut writer = naga::back::spv::Writer::new(&options).unwrap(); + for ep in module.entry_points.iter() { + let pipeline_options = naga::back::spv::PipelineOptions { + shader_stage: ep.stage, + entry_point: ep.name.clone(), + }; + writer + .write(module, info, Some(&pipeline_options), &mut data) + .unwrap(); + data.clear(); + } + } + }); + }); + + #[cfg(feature = "msl-out")] + group.bench_function("msl", |b| { + b.iter(|| { + let mut string = String::new(); + let options = naga::back::msl::Options::default(); + for &(ref module, ref info) in inputs.iter() { + let pipeline_options = naga::back::msl::PipelineOptions::default(); + let mut writer = naga::back::msl::Writer::new(&mut string); + writer + .write(module, info, &options, &pipeline_options) + .unwrap(); + string.clear(); + } + }); + }); + + #[cfg(feature = "hlsl-out")] + group.bench_function("hlsl", |b| { + b.iter(|| { + let options = naga::back::hlsl::Options::default(); + let mut string = String::new(); + for &(ref module, ref info) in inputs.iter() { + let mut writer = naga::back::hlsl::Writer::new(&mut string, &options); + let _ = writer.write(module, info); // may fail on unimplemented things + string.clear(); + } + }); + }); + + #[cfg(feature = "glsl-out")] + group.bench_function("glsl-separate", |b| { + b.iter(|| { + let mut string = String::new(); + let options = naga::back::glsl::Options { + version: naga::back::glsl::Version::Embedded(320), + writer_flags: naga::back::glsl::WriterFlags::empty(), + binding_map: Default::default(), + }; + for &(ref module, ref info) in inputs.iter() { + for ep in module.entry_points.iter() { + let pipeline_options = naga::back::glsl::PipelineOptions { + shader_stage: ep.stage, + entry_point: ep.name.clone(), + }; + match naga::back::glsl::Writer::new( + &mut string, + module, + info, + &options, + &pipeline_options, + ) { + Ok(mut writer) => { + let _ = writer.write(); // can error if unsupported + } + Err(_) => { + // missing features + } + }; + string.clear(); + } + } + }); + }); +} criterion_group!(criterion, frontends, validation, backends,); criterion_main!(criterion); From 91990298b30be204faeb91045acd2f018cd5a0ac Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 15 Feb 2022 22:07:45 -0500 Subject: [PATCH 1594/2212] Don't test on MSRV, just check --- .github/workflows/pipeline.yml | 6 ++++-- Cargo.toml | 2 +- Makefile | 4 ++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index d7f84efda..8f687e169 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -26,10 +26,12 @@ jobs: - uses: actions-rs/cargo@v1 name: Test all features with: + # we could use `test` but `criterion` is a dev dependency, + # and it doesn't build with our MSRV + command: check # `cli` already enables most features, so let's add the rest, # except for `arbitrary`, which requires Rust-1.51 - command: test - args: --workspace --features serialize,deserialize + args: --workspace - name: Check snapshots run: git diff --exit-code -- tests/out test: diff --git a/Cargo.toml b/Cargo.toml index 62d306c43..13a385d5d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,7 +64,7 @@ hexf-parse = { version = "0.2.1", optional = true } [dev-dependencies] bincode = "1" -criterion = { version = "0.3", features = ["html_reports"] } +criterion = { version = "0.3", features = [] } diff = "0.1" ron = "0.7" serde = { version = "1.0", features = ["derive"] } diff --git a/Makefile b/Makefile index 841f077a8..4622fdbb5 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,10 @@ all: clean: rm *.metal *.air *.metallib *.vert *.frag *.comp *.spv +bench: + #rm -Rf target/criterion + cargo bench + %.metal: $(SNAPSHOTS_BASE_IN)/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) cargo run --features wgsl-in,msl-out -- $< $@ From 8fd8e7d575661b6ad567bc277716142ff4867e47 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 17 Feb 2022 09:45:45 -0500 Subject: [PATCH 1595/2212] Address Jim's notes --- .github/workflows/pipeline.yml | 2 +- benches/criterion.rs | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 8f687e169..b19fd9a8b 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -29,7 +29,7 @@ jobs: # we could use `test` but `criterion` is a dev dependency, # and it doesn't build with our MSRV command: check - # `cli` already enables most features, so let's add the rest, + # `cli` already enables most features, # except for `arbitrary`, which requires Rust-1.51 args: --workspace - name: Check snapshots diff --git a/benches/criterion.rs b/benches/criterion.rs index 4c3ead31b..f239948e8 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -59,12 +59,15 @@ fn frontends(c: &mut Criterion) { }); #[cfg(feature = "wgsl-in")] group.bench_function("wgsl", |b| { - let inputs = gather_inputs("tests/in", "wgsl"); + let inputs_wgsl = gather_inputs("tests/in", "wgsl"); + let inputs = inputs_wgsl + .iter() + .map(|input| std::str::from_utf8(input).unwrap()) + .collect::>(); let mut parser = naga::front::wgsl::Parser::new(); b.iter(move || { - for input in inputs.iter() { - let string = std::str::from_utf8(input).unwrap(); - parser.parse(string).unwrap(); + for &input in inputs.iter() { + parser.parse(input).unwrap(); } }); }); From 07f9cf670c7cd47cc53dff33853dd30421543f7e Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 13 Jan 2022 09:51:22 -0800 Subject: [PATCH 1596/2212] Give `Expression::ImageLoad` separate `sample` and `level` operands. --- src/back/dot/mod.rs | 10 ++++--- src/back/glsl/mod.rs | 7 ++--- src/back/hlsl/writer.rs | 15 +++-------- src/back/msl/writer.rs | 11 +++++--- src/back/spv/block.rs | 15 ++++++++--- src/back/spv/image.rs | 18 ++++--------- src/back/wgsl/writer.rs | 5 ++-- src/front/glsl/builtins.rs | 20 +++++++++----- src/front/spv/image.rs | 10 ++++--- src/front/wgsl/mod.rs | 21 +++++++++------ src/lib.rs | 44 +++++++++++------------------- src/proc/mod.rs | 16 +++++++++++ src/valid/analyzer.rs | 9 ++++--- src/valid/expression.rs | 55 +++++++++++++++++++++----------------- 14 files changed, 141 insertions(+), 115 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index f24d67df7..523e48ce5 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -274,15 +274,19 @@ fn write_fun( image, coordinate, array_index, - index, + sample, + level, } => { edges.insert("image", image); edges.insert("coordinate", coordinate); if let Some(expr) = array_index { edges.insert("array_index", expr); } - if let Some(expr) = index { - edges.insert("index", expr); + if let Some(sample) = sample { + edges.insert("sample", sample); + } + if let Some(level) = level { + edges.insert("level", level); } ("ImageLoad".into(), 5) } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 20d003503..b765c0341 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2249,7 +2249,8 @@ impl<'a, W: Write> Writer<'a, W> { image, coordinate, array_index, - index, + sample, + level, } => { // This will only panic if the module is invalid let (dim, class) = match *ctx.info[image].ty.inner_with(&self.module.types) { @@ -2275,9 +2276,9 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ", ")?; self.write_texture_coordinates(coordinate, array_index, dim, ctx)?; - if let Some(index_expr) = index { + if let Some(sample_or_level) = sample.or(level) { write!(self.out, ", ")?; - self.write_expr(index_expr, ctx)?; + self.write_expr(sample_or_level, ctx)?; } write!(self.out, ")")?; } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index e2fccb0e1..35b76f3fc 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1694,19 +1694,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { image, coordinate, array_index, - index, + sample, + level, } => { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-load - let (sample, mip_level) = match *func_ctx.info[image].ty.inner_with(&module.types) { - TypeInner::Image { class, .. } => match class { - crate::ImageClass::Sampled { multi: true, .. } - | crate::ImageClass::Depth { multi: true } => (index, None), - crate::ImageClass::Storage { .. } => (None, None), - _ => (None, index), - }, - _ => (None, None), - }; - self.write_expr(module, image, func_ctx)?; write!(self.out, ".Load(")?; @@ -1714,7 +1705,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { "int", coordinate, array_index, - mip_level, + level, module, func_ctx, )?; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index d0dea3ef1..32e003c65 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1037,7 +1037,8 @@ impl Writer { image, coordinate, array_index, - index, + sample, + level, } => { self.put_expression(image, context, false)?; write!(self.out, ".read(")?; @@ -1046,7 +1047,11 @@ impl Writer { write!(self.out, ", ")?; self.put_expression(expr, context, true)?; } - if let Some(index) = index { + if let Some(sample) = sample { + write!(self.out, ", ")?; + self.put_expression(sample, context, true)? + } + if let Some(level) = level { // Metal requires that the `level` argument to // `texture1d::read` be a constexpr equal to zero. if let crate::TypeInner::Image { @@ -1057,7 +1062,7 @@ impl Writer { // The argument defaults to zero. } else { write!(self.out, ", ")?; - self.put_expression(index, context, true)? + self.put_expression(level, context, true)? } } write!(self.out, ")")?; diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index c4ad83067..0ab9c4a71 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -915,10 +915,17 @@ impl<'w> BlockContext<'w> { image, coordinate, array_index, - index, - } => { - self.write_image_load(result_type_id, image, coordinate, array_index, index, block)? - } + sample, + level, + } => self.write_image_load( + result_type_id, + image, + coordinate, + array_index, + level, + sample, + block, + )?, crate::Expression::ImageSample { image, sampler, diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 2ce3a30b4..1eb5ab3b9 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -709,13 +709,15 @@ impl<'w> BlockContext<'w> { /// Generate code for an `ImageLoad` expression. /// /// The arguments are the components of an `Expression::ImageLoad` variant. + #[allow(clippy::too_many_arguments)] pub(super) fn write_image_load( &mut self, result_type_id: Word, image: Handle, coordinate: Handle, array_index: Option>, - level_or_sample: Option>, + level: Option>, + sample: Option>, block: &mut Block, ) -> Result { let image_id = self.get_image_id(image); @@ -728,18 +730,8 @@ impl<'w> BlockContext<'w> { let access = Load::from_image_expr(self, image_id, image_class, result_type_id)?; let coordinates = self.write_image_coordinates(coordinate, array_index, block)?; - // Figure out what the `level_or_sample` operand really means. - let level_or_sample_id = level_or_sample.map(|i| self.cached[i]); - let (level_id, sample_id) = match image_class { - crate::ImageClass::Sampled { multi, .. } | crate::ImageClass::Depth { multi } => { - if multi { - (None, level_or_sample_id) - } else { - (level_or_sample_id, None) - } - } - crate::ImageClass::Storage { .. } => (None, None), - }; + let level_id = level.map(|expr| self.cached[expr]); + let sample_id = sample.map(|expr| self.cached[expr]); // Perform the access, according to the bounds check policy. let access_id = match self.writer.bounds_check_policies.image { diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index fa32c6b6d..d2eecd8cc 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1335,7 +1335,8 @@ impl Writer { image, coordinate, array_index, - index, + sample, + level, } => { write!(self.out, "textureLoad(")?; self.write_expr(module, image, func_ctx)?; @@ -1345,7 +1346,7 @@ impl Writer { write!(self.out, ", ")?; self.write_expr(module, array_index, func_ctx)?; } - if let Some(index) = index { + if let Some(index) = sample.or(level) { write!(self.out, ", ")?; self.write_expr(module, index, func_ctx)?; } diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 17eef6579..71e1f3be6 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -350,7 +350,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module texture_args_generator(TextureArgsOptions::all(), f) } "texelFetch" => { - let f = |kind, dim, arrayed, multi, _| { + let f = |kind, dim, arrayed, multi, _shadow| { // Cube images aren't supported if let Dim::Cube = dim { return; @@ -376,7 +376,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module declaration .overloads - .push(module.add_builtin(args, MacroCall::ImageLoad)) + .push(module.add_builtin(args, MacroCall::ImageLoad { multi })) }; // Don't generate shadow images since they aren't supported @@ -439,7 +439,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module declaration .overloads - .push(module.add_builtin(args, MacroCall::ImageLoad)) + .push(module.add_builtin(args, MacroCall::ImageLoad { multi: false })) }; // Don't generate shadow nor multisampled images since they aren't supported @@ -1537,7 +1537,9 @@ pub enum MacroCall { TextureSize { arrayed: bool, }, - ImageLoad, + ImageLoad { + multi: bool, + }, ImageStore, MathFunction(MathFunction), BitfieldExtract, @@ -1760,15 +1762,21 @@ impl MacroCall { expr } - MacroCall::ImageLoad => { + MacroCall::ImageLoad { multi } => { let comps = parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; + let (sample, level) = match (multi, args.get(2)) { + (_, None) => (None, None), + (true, Some(&arg)) => (Some(arg), None), + (false, Some(&arg)) => (None, Some(arg)), + }; ctx.add_expression( Expression::ImageLoad { image: args[0], coordinate: comps.coordinate, array_index: comps.array_index, - index: args.get(2).copied(), + sample, + level, }, Span::default(), body, diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index e797a516a..c45288ab1 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -332,7 +332,8 @@ impl> super::Parser { 0 }; - let mut index = None; + let mut sample = None; + let mut level = None; while image_ops != 0 { let bit = 1 << image_ops.trailing_zeros(); match spirv::ImageOperands::from_bits_truncate(bit) { @@ -341,13 +342,13 @@ impl> super::Parser { let lod_lexp = self.lookup_expression.lookup(lod_expr)?; let lod_handle = self.get_expr_handle(lod_expr, lod_lexp, ctx, emitter, block, body_idx); - index = Some(lod_handle); + level = Some(lod_handle); words_left -= 1; } spirv::ImageOperands::SAMPLE => { let sample_expr = self.next()?; let sample_handle = self.lookup_expression.lookup(sample_expr)?.handle; - index = Some(sample_handle); + sample = Some(sample_handle); words_left -= 1; } other => { @@ -393,7 +394,8 @@ impl> super::Parser { image: image_lexp.handle, coordinate, array_index, - index, + sample, + level, }; self.lookup_expression.insert( result_id, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6d2f0fa46..164d5aa70 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1953,20 +1953,25 @@ impl Parser { } else { None }; - let index = match class { - crate::ImageClass::Storage { .. } => None, - // it's the MSAA index for multi-sampled, and LOD for the others - crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } + let level = if class.is_mipmapped() { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None + }; + let sample = if class.is_multisampled() { + lexer.expect(Token::Separator(','))?; + Some(self.parse_general_expression(lexer, ctx.reborrow())?) + } else { + None }; lexer.close_arguments()?; crate::Expression::ImageLoad { image, coordinate, array_index, - index, + sample, + level, } } "textureDimensions" => { diff --git a/src/lib.rs b/src/lib.rs index ac1118c06..9873d2330 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1234,37 +1234,22 @@ pub enum Expression { /// [`Sint`]: ScalarKind::Sint array_index: Option>, - /// The sample within a particular texel. + /// A sample index, for multisampled [`Sampled`] and [`Depth`] images. /// - /// The meaning of this value depends on the [`class`] of `image`: - /// - /// - [`Storage`] images hold exactly one sample per texel, so `index` must - /// be `None`. - /// - /// - [`Depth`] and [`Sampled`] images may be multisampled or have - /// mipmaps, but not both. Which one is indicated by the variant's - /// [`multi`] field: - /// - /// - If `multi` is `true`, then the image has multiple samples per - /// texel, and `index` must be `Some(sample)`, where `sample` is - /// the index of the sample to retrieve. - /// - /// - If `multi` is `false`, then the image may have mipmaps. In - /// this case, `index` must be `Some(level)`, where `level` - /// identifies the level of detail. Even if the image has only the - /// full-sized version, `level` must still be present; its only - /// in-range value is zero. - /// - /// When `index` is `Some` the value must be a `Sint` scalar value. If - /// it identifes a level of detail, zero represents the full resolution - /// mipmap. - /// - /// [`class`]: TypeInner::Image::class /// [`Sampled`]: ImageClass::Sampled - /// [`Storage`]: ImageClass::Storage /// [`Depth`]: ImageClass::Depth - /// [`multi`]: ImageClass::Sampled::multi - index: Option>, + sample: Option>, + + /// A level of detail, for mipmapped images. + /// + /// This must be present when accessing non-multisampled + /// [`Sampled`] and [`Depth`] images, even if only the + /// full-resolution level is present (in which case the only + /// valid level is zero). + /// + /// [`Sampled`]: ImageClass::Sampled + /// [`Depth`]: ImageClass::Depth + level: Option>, }, /// Query information from an image. @@ -1476,7 +1461,8 @@ pub enum Statement { /// The `image`, `coordinate`, and `array_index` fields have the same /// meanings as the corresponding operands of an [`ImageLoad`] expression; /// see that documentation for details. Storing into multisampled images or - /// images with mipmaps is not supported, so there is no `index`operand. + /// images with mipmaps is not supported, so there are no `level` or + /// `sample` operands. /// /// This statement is a barrier for any operations on the corresponding /// [`Expression::GlobalVariable`] for this image. diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c62e58776..15cc3a7fc 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -441,6 +441,22 @@ impl super::SwizzleComponent { } } +impl super::ImageClass { + pub fn is_multisampled(self) -> bool { + match self { + crate::ImageClass::Sampled { multi, .. } | crate::ImageClass::Depth { multi } => multi, + crate::ImageClass::Storage { .. } => false, + } + } + + pub fn is_mipmapped(self) -> bool { + match self { + crate::ImageClass::Sampled { multi, .. } | crate::ImageClass::Depth { multi } => !multi, + crate::ImageClass::Storage { .. } => false, + } + } +} + #[test] fn test_matrix_size() { let constants = crate::Arena::new(); diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index b95a8a348..28a0f8a8a 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -557,16 +557,19 @@ impl FunctionInfo { image, coordinate, array_index, - index, + sample, + level, } => { let array_nur = array_index.and_then(|h| self.add_ref(h)); - let index_nur = index.and_then(|h| self.add_ref(h)); + let sample_nur = sample.and_then(|h| self.add_ref(h)); + let level_nur = level.and_then(|h| self.add_ref(h)); Uniformity { non_uniform_result: self .add_ref(image) .or(self.add_ref(coordinate)) .or(array_nur) - .or(index_nur), + .or(sample_nur) + .or(level_nur), requirements: UniformityRequirements::empty(), } } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 1cba9e9e4..7fb64ab98 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -75,11 +75,11 @@ pub enum ExpressionError { InvalidDerivative, #[error("Image array index parameter is misplaced")] InvalidImageArrayIndex, - #[error("Image other index parameter is misplaced")] + #[error("Inappropriate sample or level-of-detail index for texel access")] InvalidImageOtherIndex, #[error("Image array index type of {0:?} is not an integer scalar")] InvalidImageArrayIndexType(Handle), - #[error("Image other index type of {0:?} is not an integer scalar")] + #[error("Image sample or level-of-detail index's type of {0:?} is not an integer scalar")] InvalidImageOtherIndexType(Handle), #[error("Image coordinate type of {1:?} does not match dimension {0:?}")] InvalidImageCoordinateType(crate::ImageDimension, Handle), @@ -537,7 +537,8 @@ impl super::Validator { image, coordinate, array_index, - index, + sample, + level, } => { let ty = match function.expressions[image] { crate::Expression::GlobalVariable(var_handle) => { @@ -560,16 +561,9 @@ impl super::Validator { )) } }; - let needs_index = match class { - crate::ImageClass::Storage { .. } => false, - _ => true, - }; if arrayed != array_index.is_some() { return Err(ExpressionError::InvalidImageArrayIndex); } - if needs_index != index.is_some() { - return Err(ExpressionError::InvalidImageOtherIndex); - } if let Some(expr) = array_index { match *resolver.resolve(expr)? { Ti::Scalar { @@ -579,13 +573,30 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)), } } - if let Some(expr) = index { - match *resolver.resolve(expr)? { - Ti::Scalar { - kind: Sk::Sint, - width: _, - } => {} - _ => return Err(ExpressionError::InvalidImageOtherIndexType(expr)), + + match (sample, class.is_multisampled()) { + (None, false) => {} + (Some(sample), true) => { + if resolver.resolve(sample)?.scalar_kind() != Some(Sk::Sint) { + return Err(ExpressionError::InvalidImageOtherIndexType( + sample, + )); + } + } + _ => { + return Err(ExpressionError::InvalidImageOtherIndex); + } + } + + match (level, class.is_mipmapped()) { + (None, false) => {} + (Some(level), true) => { + if resolver.resolve(level)?.scalar_kind() != Some(Sk::Sint) { + return Err(ExpressionError::InvalidImageOtherIndexType(level)); + } + } + _ => { + return Err(ExpressionError::InvalidImageOtherIndex); } } } @@ -603,18 +614,12 @@ impl super::Validator { }; match module.types[ty].inner { Ti::Image { class, arrayed, .. } => { - let can_level = match class { - crate::ImageClass::Sampled { multi, .. } => !multi, - crate::ImageClass::Depth { multi } => !multi, - crate::ImageClass::Storage { .. } => false, - }; let good = match query { crate::ImageQuery::NumLayers => arrayed, crate::ImageQuery::Size { level: None } => true, crate::ImageQuery::Size { level: Some(_) } - | crate::ImageQuery::NumLevels => can_level, - //TODO: forbid on storage images - crate::ImageQuery::NumSamples => !can_level, + | crate::ImageQuery::NumLevels => class.is_mipmapped(), + crate::ImageQuery::NumSamples => class.is_multisampled(), }; if !good { return Err(ExpressionError::InvalidImageClass(class)); From 66d59eb7ac8fdfa4b842d312adb2215789a2df4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 18 Feb 2022 22:37:31 +0000 Subject: [PATCH 1597/2212] glsl-in: inject samplerCubeArray builtins on use Arrayed cube images require a special capabilities in some backends, so like how we already do with doubles, we now only inject them if a call uses one as an argument. This required some refractoring on the builtins handling of variations but now the interface is cleaner and adding new variations (if needed) should be easier. --- src/front/glsl/ast.rs | 22 +++- src/front/glsl/builtins.rs | 249 +++++++++++++++++++++--------------- src/front/glsl/functions.rs | 125 +++++++++--------- 3 files changed, 233 insertions(+), 163 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index dec73eed0..39264eeec 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -62,14 +62,26 @@ pub struct Overload { pub void: bool, } +bitflags::bitflags! { + /// Tracks the variations of the builtin already generated, this is needed because some + /// builtins overloads can't be generated unless explicitly used, since they might cause + /// uneeded capabilities to be requested + #[derive(Default)] + pub struct BuiltinVariations: u32 { + /// Request the standard overloads + const STANDARD = 1 << 0; + /// Request overloads that use the double type + const DOUBLE = 1 << 1; + /// Request overloads that use samplerCubeArray(Shadow) + const CUBE_TEXTURES_ARRAY = 1 << 2; + } +} + #[derive(Debug, Default)] pub struct FunctionDeclaration { pub overloads: Vec, - /// Whether or not this function has the name of a builtin. - pub builtin: bool, - /// If [`builtin`](Self::builtin) is true, this field indicates whether - /// this function already has double overloads added or not. Otherwise, it is unused. - pub double: bool, + /// Tracks the builtin overload variations that were already generated + pub variations: BuiltinVariations, } #[derive(Debug)] diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 71e1f3be6..fa99d6d54 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1,11 +1,14 @@ use super::{ - ast::{FunctionDeclaration, FunctionKind, Overload, ParameterInfo, ParameterQualifier}, + ast::{ + BuiltinVariations, FunctionDeclaration, FunctionKind, Overload, ParameterInfo, + ParameterQualifier, + }, context::Context, Error, ErrorKind, Parser, Result, }; use crate::{ BinaryOperator, Block, Constant, DerivativeAxis, Expression, Handle, ImageClass, - ImageDimension, ImageQuery, MathFunction, Module, RelationalFunction, SampleLevel, + ImageDimension as Dim, ImageQuery, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind as Sk, Span, Type, TypeInner, VectorSize, }; @@ -67,85 +70,30 @@ fn make_coords_arg(number_of_components: usize, kind: Sk) -> TypeInner { } } -/// Inject builtins into +/// Inject builtins into the declaration /// /// This is done to not add a large startup cost and not increase memory /// usage if it isn't needed. -/// -/// This version does not add builtins with arguments using the double type -/// [`inject_double_builtin`](inject_double_builtin) for builtins -/// using the double type -pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module, name: &str) { - use crate::ImageDimension as Dim; +pub fn inject_builtin( + declaration: &mut FunctionDeclaration, + module: &mut Module, + name: &str, + mut variations: BuiltinVariations, +) { + // Don't regeneate variations + variations.remove(declaration.variations); + declaration.variations |= variations; + + if variations.contains(BuiltinVariations::STANDARD) { + inject_standard_builtins(declaration, module, name) + } + + if variations.contains(BuiltinVariations::DOUBLE) { + inject_double_builtin(declaration, module, name) + } - declaration.builtin = true; let width = 4; match name { - "sampler1D" | "sampler1DArray" | "sampler2D" | "sampler2DArray" | "sampler2DMS" - | "sampler2DMSArray" | "sampler3D" | "samplerCube" | "samplerCubeArray" => { - declaration.overloads.push(module.add_builtin( - vec![ - TypeInner::Image { - dim: match name { - "sampler1D" | "sampler1DArray" => Dim::D1, - "sampler2D" | "sampler2DArray" | "sampler2DMS" | "sampler2DMSArray" => { - Dim::D2 - } - "sampler3D" => Dim::D3, - _ => Dim::Cube, - }, - arrayed: matches!( - name, - "sampler1DArray" - | "sampler2DArray" - | "sampler2DMSArray" - | "samplerCubeArray" - ), - class: ImageClass::Sampled { - kind: Sk::Float, - multi: matches!(name, "sampler2DMS" | "sampler2DMSArray"), - }, - }, - TypeInner::Sampler { comparison: false }, - ], - MacroCall::Sampler, - )) - } - "sampler1DShadow" - | "sampler1DArrayShadow" - | "sampler2DShadow" - | "sampler2DArrayShadow" - | "samplerCubeShadow" - | "samplerCubeArrayShadow" => { - let dim = match name { - "sampler1DShadow" | "sampler1DArrayShadow" => Dim::D1, - "sampler2DShadow" | "sampler2DArrayShadow" => Dim::D2, - _ => Dim::Cube, - }; - let arrayed = matches!( - name, - "sampler1DArrayShadow" | "sampler2DArrayShadow" | "samplerCubeArrayShadow" - ); - - for i in 0..2 { - let ty = TypeInner::Image { - dim, - arrayed, - class: match i { - 0 => ImageClass::Sampled { - kind: Sk::Float, - multi: false, - }, - _ => ImageClass::Depth { multi: false }, - }, - }; - - declaration.overloads.push(module.add_builtin( - vec![ty, TypeInner::Sampler { comparison: true }], - MacroCall::SamplerShadow, - )) - } - } "texture" | "textureGrad" | "textureGradOffset" @@ -273,7 +221,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module if lod || grad || offset || proj || bias { continue; } - debug_assert!(dim == ImageDimension::Cube && shadow && arrayed); + debug_assert!(dim == Dim::Cube && shadow && arrayed); } debug_assert!(num_coords <= 5); @@ -318,7 +266,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module } }; - texture_args_generator(TextureArgsOptions::SHADOW, f) + texture_args_generator(TextureArgsOptions::SHADOW | variations.into(), f) } "textureSize" => { let f = |kind, dim, arrayed, multi, shadow| { @@ -347,7 +295,10 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module .push(module.add_builtin(args, MacroCall::TextureSize { arrayed })) }; - texture_args_generator(TextureArgsOptions::all(), f) + texture_args_generator( + TextureArgsOptions::SHADOW | TextureArgsOptions::MULTI | variations.into(), + f, + ) } "texelFetch" => { let f = |kind, dim, arrayed, multi, _shadow| { @@ -380,7 +331,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module }; // Don't generate shadow images since they aren't supported - texture_args_generator(TextureArgsOptions::MULTI, f) + texture_args_generator(TextureArgsOptions::MULTI | variations.into(), f) } "imageSize" => { let f = |kind: Sk, dim, arrayed, _, _| { @@ -404,7 +355,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module .push(module.add_builtin(vec![image], MacroCall::TextureSize { arrayed })) }; - texture_args_generator(TextureArgsOptions::empty(), f) + texture_args_generator(variations.into(), f) } "imageLoad" => { let f = |kind: Sk, dim, arrayed, _, _| { @@ -443,7 +394,7 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module }; // Don't generate shadow nor multisampled images since they aren't supported - texture_args_generator(TextureArgsOptions::empty(), f) + texture_args_generator(variations.into(), f) } "imageStore" => { let f = |kind: Sk, dim, arrayed, _, _| { @@ -490,7 +441,84 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module }; // Don't generate shadow nor multisampled images since they aren't supported - texture_args_generator(TextureArgsOptions::empty(), f) + texture_args_generator(variations.into(), f) + } + _ => {} + } +} + +/// Injects the builtins into declaration that don't need any special variations +fn inject_standard_builtins( + declaration: &mut FunctionDeclaration, + module: &mut Module, + name: &str, +) { + let width = 4; + match name { + "sampler1D" | "sampler1DArray" | "sampler2D" | "sampler2DArray" | "sampler2DMS" + | "sampler2DMSArray" | "sampler3D" | "samplerCube" | "samplerCubeArray" => { + declaration.overloads.push(module.add_builtin( + vec![ + TypeInner::Image { + dim: match name { + "sampler1D" | "sampler1DArray" => Dim::D1, + "sampler2D" | "sampler2DArray" | "sampler2DMS" | "sampler2DMSArray" => { + Dim::D2 + } + "sampler3D" => Dim::D3, + _ => Dim::Cube, + }, + arrayed: matches!( + name, + "sampler1DArray" + | "sampler2DArray" + | "sampler2DMSArray" + | "samplerCubeArray" + ), + class: ImageClass::Sampled { + kind: Sk::Float, + multi: matches!(name, "sampler2DMS" | "sampler2DMSArray"), + }, + }, + TypeInner::Sampler { comparison: false }, + ], + MacroCall::Sampler, + )) + } + "sampler1DShadow" + | "sampler1DArrayShadow" + | "sampler2DShadow" + | "sampler2DArrayShadow" + | "samplerCubeShadow" + | "samplerCubeArrayShadow" => { + let dim = match name { + "sampler1DShadow" | "sampler1DArrayShadow" => Dim::D1, + "sampler2DShadow" | "sampler2DArrayShadow" => Dim::D2, + _ => Dim::Cube, + }; + let arrayed = matches!( + name, + "sampler1DArrayShadow" | "sampler2DArrayShadow" | "samplerCubeArrayShadow" + ); + + for i in 0..2 { + let ty = TypeInner::Image { + dim, + arrayed, + class: match i { + 0 => ImageClass::Sampled { + kind: Sk::Float, + multi: false, + }, + _ => ImageClass::Depth { multi: false }, + }, + }; + + declaration.overloads.push(module.add_builtin( + vec![ty, TypeInner::Sampler { comparison: true }], + MacroCall::SamplerShadow, + )) + } } "sin" | "exp" | "exp2" | "sinh" | "cos" | "cosh" | "tan" | "tanh" | "acos" | "asin" | "log" | "log2" | "radians" | "degrees" | "asinh" | "acosh" | "atanh" @@ -961,13 +989,8 @@ pub fn inject_builtin(declaration: &mut FunctionDeclaration, module: &mut Module } } -/// Double version of [`inject_builtin`](inject_builtin) -pub fn inject_double_builtin( - declaration: &mut FunctionDeclaration, - module: &mut Module, - name: &str, -) { - declaration.double = true; +/// Injects the builtins into declaration that need doubles +fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Module, name: &str) { let width = 8; match name { "abs" | "sign" => { @@ -1114,6 +1137,7 @@ pub fn inject_double_builtin( } } +/// Injects the builtins into declaration that can used either float or doubles fn inject_common_builtin( declaration: &mut FunctionDeclaration, module: &mut Module, @@ -1512,7 +1536,7 @@ fn inject_common_builtin( } } // The function isn't a builtin or we don't yet support it - _ => declaration.builtin = false, + _ => {} } } @@ -2028,10 +2052,10 @@ impl Parser { } = *self.resolve_type(ctx, image, meta)? { let image_size = match dim { - ImageDimension::D1 => None, - ImageDimension::D2 => Some(VectorSize::Bi), - ImageDimension::D3 => Some(VectorSize::Tri), - ImageDimension::Cube => Some(VectorSize::Tri), + Dim::D1 => None, + Dim::D2 => Some(VectorSize::Bi), + Dim::D3 => Some(VectorSize::Tri), + Dim::Cube => Some(VectorSize::Tri), }; let coord_size = match *self.resolve_type(ctx, coord, meta)? { TypeInner::Vector { size, .. } => Some(size), @@ -2060,7 +2084,7 @@ impl Parser { let mut coord_index = image_size.map_or(1, |s| s as u32); - let array_index = if arrayed && !(storage && dim == ImageDimension::Cube) { + let array_index = if arrayed && !(storage && dim == Dim::Cube) { let index = coord_index; coord_index += 1; @@ -2174,6 +2198,23 @@ bitflags::bitflags! { const MULTI = 1 << 0; /// Generates shadow variants of images const SHADOW = 1 << 1; + /// Generates standard images + const STANDARD = 1 << 2; + /// Generates cube arrayed images + const CUBE_ARRAY = 1 << 3; + } +} + +impl From for TextureArgsOptions { + fn from(variations: BuiltinVariations) -> Self { + let mut options = TextureArgsOptions::empty(); + if variations.contains(BuiltinVariations::STANDARD) { + options |= TextureArgsOptions::STANDARD + } + if variations.contains(BuiltinVariations::CUBE_TEXTURES_ARRAY) { + options |= TextureArgsOptions::CUBE_ARRAY + } + options } } @@ -2188,13 +2229,19 @@ bitflags::bitflags! { /// see the struct documentation fn texture_args_generator( options: TextureArgsOptions, - mut f: impl FnMut(crate::ScalarKind, ImageDimension, bool, bool, bool), + mut f: impl FnMut(crate::ScalarKind, Dim, bool, bool, bool), ) { - use crate::ImageDimension as Dim; - for kind in [Sk::Float, Sk::Uint, Sk::Sint].iter().copied() { for dim in [Dim::D1, Dim::D2, Dim::D3, Dim::Cube].iter().copied() { for arrayed in [false, true].iter().copied() { + if dim == Dim::Cube && arrayed { + if !options.contains(TextureArgsOptions::CUBE_ARRAY) { + continue; + } + } else if !options.contains(TextureArgsOptions::STANDARD) { + continue; + } + f(kind, dim, arrayed, false, false); // 3D images can't be neither arrayed nor shadow @@ -2220,10 +2267,10 @@ fn texture_args_generator( /// Helper functions used to convert from a image dimension into a integer representing the /// number of components needed for the coordinates vector (1 means scalar instead of vector) -fn image_dims_to_coords_size(dim: ImageDimension) -> usize { +fn image_dims_to_coords_size(dim: Dim) -> usize { match dim { - ImageDimension::D1 => 1, - ImageDimension::D2 => 2, + Dim::D1 => 1, + Dim::D2 => 2, _ => 3, } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index f9c3177a7..db58aa9b7 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1,6 +1,6 @@ use super::{ ast::*, - builtins::{inject_builtin, inject_double_builtin, sampled_to_depth}, + builtins::{inject_builtin, sampled_to_depth}, context::{Context, ExprPos, StmtContext}, error::{Error, ErrorKind}, types::scalar_components, @@ -602,26 +602,26 @@ impl Parser { raw_args: &[Handle], meta: Span, ) -> Result>> { - // If the name for the function hasn't yet been initialized check if any - // builtin can be injected. - if self.lookup_function.get(&name).is_none() { - let declaration = self.lookup_function.entry(name.clone()).or_default(); - inject_builtin(declaration, &mut self.module, &name); + // Grow the typifier to be able to index it later without needing + // to hold the context mutably + for &(expr, span) in args.iter() { + self.typifier_grow(ctx, expr, span)?; } - // Check if any argument uses a double type - let has_double = args - .iter() - .any(|&(expr, meta)| self.resolve_type(ctx, expr, meta).map_or(false, is_double)); + // Check if the passed arguments require any special variations + let mut variations = builtin_required_variations( + args.iter() + .map(|&(expr, _)| ctx.typifier.get(expr, &self.module.types)), + ); - // At this point a declaration is guaranteed - let declaration = self.lookup_function.get_mut(&name).unwrap(); + // Initiate the declaration if it wasn't previously initialized and inject builtins + let declaration = self.lookup_function.entry(name.clone()).or_insert_with(|| { + variations |= BuiltinVariations::STANDARD; + Default::default() + }); + inject_builtin(declaration, &mut self.module, &name, variations); - if declaration.builtin && !declaration.double && has_double { - inject_double_builtin(declaration, &mut self.module, &name); - } - - // Borrow again but without mutability + // Borrow again but without mutability, at this point a declaration is guaranteed let declaration = self.lookup_function.get(&name).unwrap(); // Possibly contains the overload to be used in the call @@ -1026,11 +1026,6 @@ impl Parser { mut body: Block, meta: Span, ) { - if self.lookup_function.get(&name).is_none() { - let declaration = self.lookup_function.entry(name.clone()).or_default(); - inject_builtin(declaration, &mut self.module, &name); - } - ensure_block_returns(&mut body); let void = result.is_none(); @@ -1041,7 +1036,16 @@ impl Parser { .. } = self; - let declaration = lookup_function.entry(name.clone()).or_default(); + // Check if the passed arguments require any special variations + let mut variations = + builtin_required_variations(ctx.parameters.iter().map(|&arg| &module.types[arg].inner)); + + // Initiate the declaration if it wasn't previously initialized and inject builtins + let declaration = lookup_function.entry(name.clone()).or_insert_with(|| { + variations |= BuiltinVariations::STANDARD; + Default::default() + }); + inject_builtin(declaration, module, &name, variations); let Context { expressions, @@ -1052,15 +1056,6 @@ impl Parser { .. } = ctx; - if declaration.builtin - && !declaration.double - && parameters - .iter() - .any(|ty| is_double(&module.types[*ty].inner)) - { - inject_double_builtin(declaration, module, &name); - } - let function = Function { name: Some(name), arguments, @@ -1122,11 +1117,6 @@ impl Parser { result: Option, meta: Span, ) { - if self.lookup_function.get(&name).is_none() { - let declaration = self.lookup_function.entry(name.clone()).or_default(); - inject_builtin(declaration, &mut self.module, &name); - } - let void = result.is_none(); let &mut Parser { @@ -1135,7 +1125,16 @@ impl Parser { .. } = self; - let declaration = lookup_function.entry(name.clone()).or_default(); + // Check if the passed arguments require any special variations + let mut variations = + builtin_required_variations(ctx.parameters.iter().map(|&arg| &module.types[arg].inner)); + + // Initiate the declaration if it wasn't previously initialized and inject builtins + let declaration = lookup_function.entry(name.clone()).or_insert_with(|| { + variations |= BuiltinVariations::STANDARD; + Default::default() + }); + inject_builtin(declaration, module, &name, variations); let Context { arguments, @@ -1144,15 +1143,6 @@ impl Parser { .. } = ctx; - if declaration.builtin - && !declaration.double - && parameters - .iter() - .any(|ty| is_double(&module.types[*ty].inner)) - { - inject_double_builtin(declaration, module, &name); - } - let function = Function { name: Some(name), arguments, @@ -1404,16 +1394,6 @@ impl Parser { } } -fn is_double(ty: &TypeInner) -> bool { - match *ty { - TypeInner::ValuePointer { kind, width, .. } - | TypeInner::Scalar { kind, width } - | TypeInner::Vector { kind, width, .. } => kind == ScalarKind::Float && width == 8, - TypeInner::Matrix { width, .. } => width == 8, - _ => false, - } -} - /// Helper enum containing the type of conversion need for a call #[derive(PartialEq, Eq, Clone, Copy, Debug)] enum Conversion { @@ -1498,3 +1478,34 @@ fn conversion(target: &TypeInner, source: &TypeInner) -> Option { }, ) } + +/// Helper method returning all the non standard builtin variations needed +/// to process the function call with the passed arguments +fn builtin_required_variations<'a>(args: impl Iterator) -> BuiltinVariations { + let mut variations = BuiltinVariations::empty(); + + for ty in args { + match *ty { + TypeInner::ValuePointer { kind, width, .. } + | TypeInner::Scalar { kind, width } + | TypeInner::Vector { kind, width, .. } => { + if kind == ScalarKind::Float && width == 8 { + variations |= BuiltinVariations::DOUBLE + } + } + TypeInner::Matrix { width, .. } => { + if width == 8 { + variations |= BuiltinVariations::DOUBLE + } + } + TypeInner::Image { dim, arrayed, .. } => { + if dim == crate::ImageDimension::Cube && arrayed { + variations |= BuiltinVariations::CUBE_TEXTURES_ARRAY + } + } + _ => {} + } + } + + variations +} From 9f62feee8733a2a12ba3133cabe7ab13e7d1ccf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 19 Feb 2022 10:03:11 +0000 Subject: [PATCH 1598/2212] glsl-in: inject sampler2DMSArray builtins on use --- src/front/glsl/ast.rs | 2 ++ src/front/glsl/builtins.rs | 20 +++++++++++++++++++- src/front/glsl/functions.rs | 10 +++++++++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 39264eeec..9f28b2bdd 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -74,6 +74,8 @@ bitflags::bitflags! { const DOUBLE = 1 << 1; /// Request overloads that use samplerCubeArray(Shadow) const CUBE_TEXTURES_ARRAY = 1 << 2; + /// Request overloads that use sampler2DMSArray + const D2_MULTI_TEXTURES_ARRAY = 1 << 3; } } diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index fa99d6d54..ea56c54f7 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -80,6 +80,12 @@ pub fn inject_builtin( name: &str, mut variations: BuiltinVariations, ) { + log::trace!( + "{} variations: {:?} {:?}", + name, + variations, + declaration.variations + ); // Don't regeneate variations variations.remove(declaration.variations); declaration.variations |= variations; @@ -2202,6 +2208,8 @@ bitflags::bitflags! { const STANDARD = 1 << 2; /// Generates cube arrayed images const CUBE_ARRAY = 1 << 3; + /// Generates cube arrayed images + const D2_MULTI_ARRAY = 1 << 4; } } @@ -2214,6 +2222,9 @@ impl From for TextureArgsOptions { if variations.contains(BuiltinVariations::CUBE_TEXTURES_ARRAY) { options |= TextureArgsOptions::CUBE_ARRAY } + if variations.contains(BuiltinVariations::D2_MULTI_TEXTURES_ARRAY) { + options |= TextureArgsOptions::D2_MULTI_ARRAY + } options } } @@ -2238,6 +2249,13 @@ fn texture_args_generator( if !options.contains(TextureArgsOptions::CUBE_ARRAY) { continue; } + } else if Dim::D2 == dim + && options.contains(TextureArgsOptions::MULTI) + && arrayed + && options.contains(TextureArgsOptions::D2_MULTI_ARRAY) + { + // multisampling for sampler2DMSArray + f(kind, dim, arrayed, true, false); } else if !options.contains(TextureArgsOptions::STANDARD) { continue; } @@ -2251,7 +2269,7 @@ fn texture_args_generator( break; } - if Dim::D2 == dim && options.contains(TextureArgsOptions::MULTI) { + if Dim::D2 == dim && options.contains(TextureArgsOptions::MULTI) && !arrayed { // multisampling f(kind, dim, arrayed, true, false); } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index db58aa9b7..9a53e5002 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1498,10 +1498,18 @@ fn builtin_required_variations<'a>(args: impl Iterator) -> variations |= BuiltinVariations::DOUBLE } } - TypeInner::Image { dim, arrayed, .. } => { + TypeInner::Image { + dim, + arrayed, + class, + } => { if dim == crate::ImageDimension::Cube && arrayed { variations |= BuiltinVariations::CUBE_TEXTURES_ARRAY } + + if dim == crate::ImageDimension::D2 && arrayed && class.is_multisampled() { + variations |= BuiltinVariations::D2_MULTI_TEXTURES_ARRAY + } } _ => {} } From 1ccfc8991ef706636a384397c897a618ae59bf58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 19 Feb 2022 10:04:11 +0000 Subject: [PATCH 1599/2212] glsl-in: Add test for conditional builtin inject --- tests/in/variations.glsl | 9 ++++++++ .../glsl/variations-glsl.main.Fragment.glsl | 21 +++++++++++++++++++ tests/snapshots.rs | 19 +++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 tests/in/variations.glsl create mode 100644 tests/out/glsl/variations-glsl.main.Fragment.glsl diff --git a/tests/in/variations.glsl b/tests/in/variations.glsl new file mode 100644 index 000000000..11904137f --- /dev/null +++ b/tests/in/variations.glsl @@ -0,0 +1,9 @@ +#version 460 core + +layout(set = 0, binding = 0) uniform textureCube texCube; +layout(set = 0, binding = 1) uniform sampler samp; + +void main() { + ivec2 sizeCube = textureSize(samplerCube(texCube, samp), 0); + float a = ceil(1.0); +} diff --git a/tests/out/glsl/variations-glsl.main.Fragment.glsl b/tests/out/glsl/variations-glsl.main.Fragment.glsl new file mode 100644 index 000000000..d42deaece --- /dev/null +++ b/tests/out/glsl/variations-glsl.main.Fragment.glsl @@ -0,0 +1,21 @@ +#version 310 es + +precision highp float; +precision highp int; + +uniform highp samplerCube _group_0_binding_0_fs; + + +void main_1() { + ivec2 sizeCube = ivec2(0); + float a = 0.0; + sizeCube = textureSize(_group_0_binding_0_fs, 0).xy; + a = ceil(1.0); + return; +} + +void main() { + main_1(); + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 65439888f..b1b205845 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -556,6 +556,25 @@ fn convert_spv_all() { convert_spv("degrees", false, Targets::empty()); } +#[cfg(feature = "glsl-in")] +#[test] +fn convert_glsl_variations_check() { + let root = env!("CARGO_MANIFEST_DIR"); + let file = fs::read_to_string(format!("{}/{}/variations.glsl", root, BASE_DIR_IN)) + .expect("Couldn't find glsl file"); + let mut parser = naga::front::glsl::Parser::default(); + let module = parser + .parse( + &naga::front::glsl::Options { + stage: naga::ShaderStage::Fragment, + defines: Default::default(), + }, + &file, + ) + .unwrap(); + check_targets(&module, "variations-glsl", Targets::GLSL); +} + #[cfg(feature = "glsl-in")] #[allow(unused_variables)] #[test] From 688ad474f71cce856a6dbd792dccbb3b702da477 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 21 Feb 2022 13:22:54 -0800 Subject: [PATCH 1600/2212] [msl-out] Write 'using metal::uint' at the top, to work around bug. (#1740) This lets us remove some special cases where `uint` must be fully qualified, even though other similar types are not. --- src/back/msl/keywords.rs | 1 + src/back/msl/writer.rs | 13 +++++----- tests/out/msl/access.msl | 6 +++-- tests/out/msl/bits.msl | 22 ++++++++-------- tests/out/msl/boids.msl | 20 ++++++++------- tests/out/msl/bounds-check-restrict.msl | 4 ++- tests/out/msl/bounds-check-zero-atomic.msl | 16 +++++++----- tests/out/msl/bounds-check-zero.msl | 30 ++++++++++++---------- tests/out/msl/collatz.msl | 30 ++++++++++++---------- tests/out/msl/control-flow.msl | 2 ++ tests/out/msl/empty-global-name.msl | 2 ++ tests/out/msl/empty.msl | 2 ++ tests/out/msl/extra.msl | 8 +++--- tests/out/msl/functions.msl | 4 ++- tests/out/msl/globals.msl | 4 ++- tests/out/msl/image.msl | 8 +++--- tests/out/msl/interface.msl | 24 +++++++++-------- tests/out/msl/interpolate.msl | 8 +++--- tests/out/msl/math-functions.msl | 2 ++ tests/out/msl/operators.msl | 2 ++ tests/out/msl/policy-mix.msl | 2 ++ tests/out/msl/quad-vert.msl | 2 ++ tests/out/msl/quad.msl | 2 ++ tests/out/msl/shadow.msl | 18 +++++++------ tests/out/msl/skybox.msl | 4 ++- tests/out/msl/standard.msl | 2 ++ tests/out/msl/texture-arg.msl | 2 ++ 27 files changed, 145 insertions(+), 95 deletions(-) diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs index a62113c09..7a66b94aa 100644 --- a/src/back/msl/keywords.rs +++ b/src/back/msl/keywords.rs @@ -18,6 +18,7 @@ pub const RESERVED: &[&str] = &[ "bool", "char", "int", + "uint", "long", "float", "double", diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 32e003c65..a99c9db2a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -39,10 +39,6 @@ fn put_numeric_type( sizes: &[crate::VectorSize], ) -> Result<(), FmtError> { match (kind, sizes) { - (crate::ScalarKind::Uint, &[]) => { - // Work around Metal compiler bug: scalar `uint` requires namespace. - write!(out, "{}::uint", NAMESPACE) - } (kind, &[]) => { write!(out, "{}", kind.to_msl_name()) } @@ -1434,7 +1430,7 @@ impl Writer { /// The text written is of the form: /// /// ```ignore - /// {level}{prefix}metal::uint(i) < 4 && metal::uint(j) < 10 + /// {level}{prefix}uint(i) < 4 && uint(j) < 10 /// ``` /// /// where `{level}` and `{prefix}` are the arguments to this function. For [`Store`] @@ -1494,7 +1490,7 @@ impl Writer { // Check that the index falls within bounds. Do this with a single // comparison, by casting the index to `uint` first, so that negative // indices become large positive values. - write!(self.out, "{}::uint(", NAMESPACE)?; + write!(self.out, "uint(")?; self.put_index(index, context, true)?; self.out.write_str(") < ")?; match length { @@ -2351,6 +2347,9 @@ impl Writer { writeln!(self.out, "#include ")?; writeln!(self.out, "#include ")?; writeln!(self.out)?; + // Work around Metal bug where `uint` is not available by default + writeln!(self.out, "using {}::uint;", NAMESPACE)?; + writeln!(self.out)?; if options .bounds_check_policies @@ -2372,7 +2371,7 @@ impl Writer { writeln!(self.out, "struct _mslBufferSizes {{")?; for idx in indices { - writeln!(self.out, "{}{}::uint size{};", back::INDENT, NAMESPACE, idx)?; + writeln!(self.out, "{}uint size{};", back::INDENT, idx)?; } writeln!(self.out, "}};")?; diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 39033f3fd..d4d80a50b 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -2,8 +2,10 @@ #include #include +using metal::uint; + struct _mslBufferSizes { - metal::uint size0; + uint size0; }; struct AlignedWrapper { @@ -41,7 +43,7 @@ struct fooOutput { metal::float4 member [[position]]; }; vertex fooOutput foo( - metal::uint vi [[vertex_id]] + uint vi [[vertex_id]] , device Bar& bar [[buffer(0)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index 05574f717..cc3a5660a 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + kernel void main_( ) { @@ -9,7 +11,7 @@ kernel void main_( metal::int2 i2_; metal::int3 i3_; metal::int4 i4_; - metal::uint u = 0u; + uint u = 0u; metal::uint2 u2_; metal::uint3 u3_; metal::uint4 u4_; @@ -33,15 +35,15 @@ kernel void main_( u = metal::pack_float_to_unorm2x16(_e34); metal::float2 _e36 = f2_; u = as_type(half2(_e36)); - metal::uint _e38 = u; + uint _e38 = u; f4_ = metal::unpack_snorm4x8_to_float(_e38); - metal::uint _e40 = u; + uint _e40 = u; f4_ = metal::unpack_unorm4x8_to_float(_e40); - metal::uint _e42 = u; + uint _e42 = u; f2_ = metal::unpack_snorm2x16_to_float(_e42); - metal::uint _e44 = u; + uint _e44 = u; f2_ = metal::unpack_unorm2x16_to_float(_e44); - metal::uint _e46 = u; + uint _e46 = u; f2_ = float2(as_type(_e46)); int _e48 = i; int _e49 = i; @@ -55,8 +57,8 @@ kernel void main_( metal::int4 _e63 = i4_; metal::int4 _e64 = i4_; i4_ = metal::insert_bits(_e63, _e64, 5u, 10u); - metal::uint _e68 = u; - metal::uint _e69 = u; + uint _e68 = u; + uint _e69 = u; u = metal::insert_bits(_e68, _e69, 5u, 10u); metal::uint2 _e73 = u2_; metal::uint2 _e74 = u2_; @@ -75,7 +77,7 @@ kernel void main_( i3_ = metal::extract_bits(_e96, 5u, 10u); metal::int4 _e100 = i4_; i4_ = metal::extract_bits(_e100, 5u, 10u); - metal::uint _e104 = u; + uint _e104 = u; u = metal::extract_bits(_e104, 5u, 10u); metal::uint2 _e108 = u2_; u2_ = metal::extract_bits(_e108, 5u, 10u); @@ -89,7 +91,7 @@ kernel void main_( i2_ = (((1 + int2(metal::ctz(_e122))) % 33) - 1); metal::int3 _e124 = i3_; i3_ = (((1 + int3(metal::clz(_e124))) % 33) - 1); - metal::uint _e126 = u; + uint _e126 = u; i = (((1 + int(metal::clz(_e126))) % 33) - 1); return; } diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index 9f6048997..d18d733ac 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -2,9 +2,11 @@ #include #include +using metal::uint; + struct _mslBufferSizes { - metal::uint size1; - metal::uint size2; + uint size1; + uint size2; }; constexpr constant unsigned NUM_PARTICLES = 1500u; @@ -44,8 +46,8 @@ kernel void main_( int cVelCount = 0; metal::float2 pos; metal::float2 vel; - metal::uint i = 0u; - metal::uint index = global_invocation_id.x; + uint i = 0u; + uint index = global_invocation_id.x; if (index >= NUM_PARTICLES) { return; } @@ -59,22 +61,22 @@ kernel void main_( bool loop_init = true; while(true) { if (!loop_init) { - metal::uint _e86 = i; + uint _e86 = i; i = _e86 + 1u; } loop_init = false; - metal::uint _e37 = i; + uint _e37 = i; if (_e37 >= NUM_PARTICLES) { break; } - metal::uint _e39 = i; + uint _e39 = i; if (_e39 == index) { continue; } - metal::uint _e42 = i; + uint _e42 = i; metal::float2 _e45 = particlesSrc.particles[_e42].pos; pos = _e45; - metal::uint _e47 = i; + uint _e47 = i; metal::float2 _e50 = particlesSrc.particles[_e47].vel; vel = _e50; metal::float2 _e51 = pos; diff --git a/tests/out/msl/bounds-check-restrict.msl b/tests/out/msl/bounds-check-restrict.msl index 93bbf910b..e82ebf814 100644 --- a/tests/out/msl/bounds-check-restrict.msl +++ b/tests/out/msl/bounds-check-restrict.msl @@ -2,8 +2,10 @@ #include #include +using metal::uint; + struct _mslBufferSizes { - metal::uint size0; + uint size0; }; struct type_1 { diff --git a/tests/out/msl/bounds-check-zero-atomic.msl b/tests/out/msl/bounds-check-zero-atomic.msl index 038bef6bf..c76ba1b54 100644 --- a/tests/out/msl/bounds-check-zero-atomic.msl +++ b/tests/out/msl/bounds-check-zero-atomic.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + struct DefaultConstructible { template operator T() && { @@ -9,7 +11,7 @@ struct DefaultConstructible { } }; struct _mslBufferSizes { - metal::uint size0; + uint size0; }; struct type_1 { @@ -22,28 +24,28 @@ struct Globals { type_2 c; }; -metal::uint fetch_add_atomic( +uint fetch_add_atomic( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - metal::uint _e3 = metal::atomic_fetch_add_explicit(&globals.a, 1u, metal::memory_order_relaxed); + uint _e3 = metal::atomic_fetch_add_explicit(&globals.a, 1u, metal::memory_order_relaxed); return _e3; } -metal::uint fetch_add_atomic_static_sized_array( +uint fetch_add_atomic_static_sized_array( int i, device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - metal::uint _e5 = metal::uint(i) < 10 ? metal::atomic_fetch_add_explicit(&globals.b.inner[i], 1u, metal::memory_order_relaxed) : DefaultConstructible(); + uint _e5 = uint(i) < 10 ? metal::atomic_fetch_add_explicit(&globals.b.inner[i], 1u, metal::memory_order_relaxed) : DefaultConstructible(); return _e5; } -metal::uint fetch_add_atomic_dynamic_sized_array( +uint fetch_add_atomic_dynamic_sized_array( int i_1, device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - metal::uint _e5 = metal::uint(i_1) < 1 + (_buffer_sizes.size0 - 44 - 4) / 4 ? metal::atomic_fetch_add_explicit(&globals.c[i_1], 1u, metal::memory_order_relaxed) : DefaultConstructible(); + uint _e5 = uint(i_1) < 1 + (_buffer_sizes.size0 - 44 - 4) / 4 ? metal::atomic_fetch_add_explicit(&globals.c[i_1], 1u, metal::memory_order_relaxed) : DefaultConstructible(); return _e5; } diff --git a/tests/out/msl/bounds-check-zero.msl b/tests/out/msl/bounds-check-zero.msl index b61e523aa..1a6bcc157 100644 --- a/tests/out/msl/bounds-check-zero.msl +++ b/tests/out/msl/bounds-check-zero.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + struct DefaultConstructible { template operator T() && { @@ -9,7 +11,7 @@ struct DefaultConstructible { } }; struct _mslBufferSizes { - metal::uint size0; + uint size0; }; struct type_1 { @@ -29,7 +31,7 @@ float index_array( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e4 = metal::uint(i) < 10 ? globals.a.inner[i] : DefaultConstructible(); + float _e4 = uint(i) < 10 ? globals.a.inner[i] : DefaultConstructible(); return _e4; } @@ -38,7 +40,7 @@ float index_dynamic_array( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e4 = metal::uint(i_1) < 1 + (_buffer_sizes.size0 - 112 - 4) / 4 ? globals.d[i_1] : DefaultConstructible(); + float _e4 = uint(i_1) < 1 + (_buffer_sizes.size0 - 112 - 4) / 4 ? globals.d[i_1] : DefaultConstructible(); return _e4; } @@ -47,7 +49,7 @@ float index_vector( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e4 = metal::uint(i_2) < 4 ? globals.v[i_2] : DefaultConstructible(); + float _e4 = uint(i_2) < 4 ? globals.v[i_2] : DefaultConstructible(); return _e4; } @@ -55,7 +57,7 @@ float index_vector_by_value( metal::float4 v, int i_3 ) { - return metal::uint(i_3) < 4 ? v[i_3] : DefaultConstructible(); + return uint(i_3) < 4 ? v[i_3] : DefaultConstructible(); } metal::float4 index_matrix( @@ -63,7 +65,7 @@ metal::float4 index_matrix( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - metal::float4 _e4 = metal::uint(i_4) < 3 ? globals.m[i_4] : DefaultConstructible(); + metal::float4 _e4 = uint(i_4) < 3 ? globals.m[i_4] : DefaultConstructible(); return _e4; } @@ -73,7 +75,7 @@ float index_twice( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e6 = metal::uint(j) < 4 && metal::uint(i_5) < 3 ? globals.m[i_5][j] : DefaultConstructible(); + float _e6 = uint(j) < 4 && uint(i_5) < 3 ? globals.m[i_5][j] : DefaultConstructible(); return _e6; } @@ -83,7 +85,7 @@ float index_expensive( constant _mslBufferSizes& _buffer_sizes ) { int _e9 = static_cast(metal::sin(static_cast(i_6) / 100.0) * 100.0); - float _e11 = metal::uint(_e9) < 10 ? globals.a.inner[_e9] : DefaultConstructible(); + float _e11 = uint(_e9) < 10 ? globals.a.inner[_e9] : DefaultConstructible(); return _e11; } @@ -103,7 +105,7 @@ void set_array( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - if (metal::uint(i_7) < 10) { + if (uint(i_7) < 10) { globals.a.inner[i_7] = v_1; } return; @@ -115,7 +117,7 @@ void set_dynamic_array( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - if (metal::uint(i_8) < 1 + (_buffer_sizes.size0 - 112 - 4) / 4) { + if (uint(i_8) < 1 + (_buffer_sizes.size0 - 112 - 4) / 4) { globals.d[i_8] = v_2; } return; @@ -127,7 +129,7 @@ void set_vector( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - if (metal::uint(i_9) < 4) { + if (uint(i_9) < 4) { globals.v[i_9] = v_3; } return; @@ -139,7 +141,7 @@ void set_matrix( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - if (metal::uint(i_10) < 3) { + if (uint(i_10) < 3) { globals.m[i_10] = v_4; } return; @@ -152,7 +154,7 @@ void set_index_twice( device Globals& globals, constant _mslBufferSizes& _buffer_sizes ) { - if (metal::uint(j_1) < 4 && metal::uint(i_11) < 3) { + if (uint(j_1) < 4 && uint(i_11) < 3) { globals.m[i_11][j_1] = v_5; } return; @@ -165,7 +167,7 @@ void set_expensive( constant _mslBufferSizes& _buffer_sizes ) { int _e10 = static_cast(metal::sin(static_cast(i_12) / 100.0) * 100.0); - if (metal::uint(_e10) < 10) { + if (uint(_e10) < 10) { globals.a.inner[_e10] = v_6; } return; diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index 3a511481a..a1a0788ad 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -2,38 +2,40 @@ #include #include +using metal::uint; + struct _mslBufferSizes { - metal::uint size0; + uint size0; }; -typedef metal::uint type_1[1]; +typedef uint type_1[1]; struct PrimeIndices { type_1 data; }; -metal::uint collatz_iterations( - metal::uint n_base +uint collatz_iterations( + uint n_base ) { - metal::uint n; - metal::uint i = 0u; + uint n; + uint i = 0u; n = n_base; while(true) { - metal::uint _e5 = n; + uint _e5 = n; if (_e5 <= 1u) { break; } - metal::uint _e8 = n; + uint _e8 = n; if ((_e8 % 2u) == 0u) { - metal::uint _e13 = n; + uint _e13 = n; n = _e13 / 2u; } else { - metal::uint _e17 = n; + uint _e17 = n; n = (3u * _e17) + 1u; } - metal::uint _e21 = i; + uint _e21 = i; i = _e21 + 1u; } - metal::uint _e24 = i; + uint _e24 = i; return _e24; } @@ -44,8 +46,8 @@ kernel void main_( , device PrimeIndices& v_indices [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - metal::uint _e8 = v_indices.data[global_id.x]; - metal::uint _e9 = collatz_iterations(_e8); + uint _e8 = v_indices.data[global_id.x]; + uint _e9 = collatz_iterations(_e8); v_indices.data[global_id.x] = _e9; return; } diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index e0d2f0ceb..8fb23b5b7 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + void switch_default_break( int i diff --git a/tests/out/msl/empty-global-name.msl b/tests/out/msl/empty-global-name.msl index 3b9dfec5f..6001dba93 100644 --- a/tests/out/msl/empty-global-name.msl +++ b/tests/out/msl/empty-global-name.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + struct type_1 { int member; }; diff --git a/tests/out/msl/empty.msl b/tests/out/msl/empty.msl index c3bb1a71b..4f8bf9f5e 100644 --- a/tests/out/msl/empty.msl +++ b/tests/out/msl/empty.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + kernel void main_( ) { diff --git a/tests/out/msl/extra.msl b/tests/out/msl/extra.msl index e13f0c2ac..867c7e5a0 100644 --- a/tests/out/msl/extra.msl +++ b/tests/out/msl/extra.msl @@ -2,14 +2,16 @@ #include #include +using metal::uint; + struct PushConstants { - metal::uint index; + uint index; char _pad1[12]; metal::float2 double_; }; struct FragmentIn { metal::float4 color; - metal::uint primitive_index; + uint primitive_index; }; struct main_Input { @@ -20,7 +22,7 @@ struct main_Output { }; fragment main_Output main_( main_Input varyings [[stage_in]] -, metal::uint primitive_index [[primitive_id]] +, uint primitive_index [[primitive_id]] ) { const FragmentIn in = { varyings.color, primitive_index }; if ((in.primitive_index % 2u) == 0u) { diff --git a/tests/out/msl/functions.msl b/tests/out/msl/functions.msl index 73c5a9fa6..31f57c656 100644 --- a/tests/out/msl/functions.msl +++ b/tests/out/msl/functions.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + metal::float2 test_fma( ) { @@ -18,7 +20,7 @@ int test_integer_dot_product( int c_2_ = ( + a_2_.x * b_2_.x + a_2_.y * b_2_.y); metal::uint3 a_3_ = metal::uint3(1u); metal::uint3 b_3_ = metal::uint3(1u); - metal::uint c_3_ = ( + a_3_.x * b_3_.x + a_3_.y * b_3_.y + a_3_.z * b_3_.z); + uint c_3_ = ( + a_3_.x * b_3_.x + a_3_.y * b_3_.y + a_3_.z * b_3_.z); metal::int4 _e11 = metal::int4(4); metal::int4 _e13 = metal::int4(2); int c_4_ = ( + _e11.x * _e13.x + _e11.y * _e13.y + _e11.z * _e13.z + _e11.w * _e13.w); diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index b56bc647d..8f4ce07ad 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -2,8 +2,10 @@ #include #include +using metal::uint; + struct _mslBufferSizes { - metal::uint size3; + uint size3; }; constexpr constant bool Foo_2 = true; diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 025f2a6a9..74d75ff7d 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + constant metal::int2 const_type_9_ = {3, 1}; struct main_Input { @@ -21,8 +23,8 @@ kernel void main_( metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); - metal::uint4 value6_ = image_1d_src.read(metal::uint(static_cast(local_id.x))); - image_dst.write((((value1_ + value2_) + value4_) + value5_) + value6_, metal::uint(itc.x)); + metal::uint4 value6_ = image_1d_src.read(uint(static_cast(local_id.x))); + image_dst.write((((value1_ + value2_) + value4_) + value5_) + value6_, uint(itc.x)); return; } @@ -38,7 +40,7 @@ kernel void depth_load( metal::int2 dim_1 = int2(image_storage_src.get_width(), image_storage_src.get_height()); metal::int2 itc_1 = (dim_1 * static_cast(local_id_1.xy)) % metal::int2(10, 20); float val = image_depth_multisampled_src.read(metal::uint2(itc_1), static_cast(local_id_1.z)); - image_dst.write(metal::uint4(static_cast(val)), metal::uint(itc_1.x)); + image_dst.write(metal::uint4(static_cast(val)), uint(itc_1.x)); return; } diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 6461aee75..dbc687198 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -2,21 +2,23 @@ #include #include +using metal::uint; + struct VertexOutput { metal::float4 position; float varying; }; struct FragmentOutput { float depth; - metal::uint sample_mask; + uint sample_mask; float color; }; struct type_4 { - metal::uint inner[1]; + uint inner[1]; }; struct vertex_Input { - metal::uint color [[attribute(10)]]; + uint color [[attribute(10)]]; }; struct vertex_Output { metal::float4 position [[position]]; @@ -25,11 +27,11 @@ struct vertex_Output { }; vertex vertex_Output vertex_( vertex_Input varyings [[stage_in]] -, metal::uint vertex_index [[vertex_id]] -, metal::uint instance_index [[instance_id]] +, uint vertex_index [[vertex_id]] +, uint instance_index [[instance_id]] ) { const auto color = varyings.color; - metal::uint tmp = (vertex_index + instance_index) + color; + uint tmp = (vertex_index + instance_index) + color; const auto _tmp = VertexOutput {metal::float4(1.0), static_cast(tmp)}; return vertex_Output { _tmp.position, _tmp.varying, 1.0 }; } @@ -40,18 +42,18 @@ struct fragment_Input { }; struct fragment_Output { float depth [[depth(any)]]; - metal::uint sample_mask [[sample_mask]]; + uint sample_mask [[sample_mask]]; float color [[color(0)]]; }; fragment fragment_Output fragment_( fragment_Input varyings_1 [[stage_in]] , metal::float4 position [[position]] , bool front_facing [[front_facing]] -, metal::uint sample_index [[sample_id]] -, metal::uint sample_mask [[sample_mask]] +, uint sample_index [[sample_id]] +, uint sample_mask [[sample_mask]] ) { const VertexOutput in = { position, varyings_1.varying }; - metal::uint mask = sample_mask & (1u << sample_index); + uint mask = sample_mask & (1u << sample_index); float color_1 = front_facing ? 1.0 : 0.0; const auto _tmp = FragmentOutput {in.varying, mask, color_1}; return fragment_Output { _tmp.depth, _tmp.sample_mask, _tmp.color }; @@ -63,7 +65,7 @@ struct compute_Input { kernel void compute_( metal::uint3 global_id [[thread_position_in_grid]] , metal::uint3 local_id [[thread_position_in_threadgroup]] -, metal::uint local_index [[thread_index_in_threadgroup]] +, uint local_index [[thread_index_in_threadgroup]] , metal::uint3 wg_id [[threadgroup_position_in_grid]] , metal::uint3 num_wgs [[threadgroups_per_grid]] , threadgroup type_4& output diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl index 0f89a547b..659b9d3d2 100644 --- a/tests/out/msl/interpolate.msl +++ b/tests/out/msl/interpolate.msl @@ -2,9 +2,11 @@ #include #include +using metal::uint; + struct FragmentInput { metal::float4 position; - metal::uint flat; + uint flat; float linear; metal::float2 linear_centroid; metal::float3 linear_sample; @@ -15,7 +17,7 @@ struct FragmentInput { struct vert_mainOutput { metal::float4 position [[position]]; - metal::uint flat [[user(loc0), flat]]; + uint flat [[user(loc0), flat]]; float linear [[user(loc1), center_no_perspective]]; metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]]; metal::float3 linear_sample [[user(loc3), sample_no_perspective]]; @@ -41,7 +43,7 @@ vertex vert_mainOutput vert_main( struct frag_mainInput { - metal::uint flat [[user(loc0), flat]]; + uint flat [[user(loc0), flat]]; float linear [[user(loc1), center_no_perspective]]; metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]]; metal::float3 linear_sample [[user(loc3), sample_no_perspective]]; diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index ee0acbca8..fe1fd5573 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + vertex void main_( ) { diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index eebd1e73b..1d76848a2 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + struct Foo { metal::float4 a; int b; diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index 893c700ca..9020c64fe 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + struct DefaultConstructible { template operator T() && { diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index 87114a8d7..ade1791db 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + struct type_5 { float inner[1u]; }; diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl index a03d61bf5..a6beb30b8 100644 --- a/tests/out/msl/quad.msl +++ b/tests/out/msl/quad.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + constexpr constant float c_scale = 1.2000000476837158; struct VertexOutput { metal::float2 uv; diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index f7978728d..58d03e957 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -2,8 +2,10 @@ #include #include +using metal::uint; + struct _mslBufferSizes { - metal::uint size1; + uint size1; }; constexpr constant unsigned c_max_lights = 10u; @@ -22,7 +24,7 @@ struct Lights { constant metal::float3 c_ambient = {0.05000000074505806, 0.05000000074505806, 0.05000000074505806}; float fetch_shadow( - metal::uint light_id, + uint light_id, metal::float4 homogeneous_coords, metal::depth2d_array t_shadow, metal::sampler sampler_shadow @@ -54,23 +56,23 @@ fragment fs_mainOutput fs_main( const auto raw_normal = varyings.raw_normal; const auto position = varyings.position; metal::float3 color = c_ambient; - metal::uint i = 0u; + uint i = 0u; metal::float3 normal = metal::normalize(raw_normal); bool loop_init = true; while(true) { if (!loop_init) { - metal::uint _e40 = i; + uint _e40 = i; i = _e40 + 1u; } loop_init = false; - metal::uint _e12 = i; - metal::uint _e15 = u_globals.num_lights.x; + uint _e12 = i; + uint _e15 = u_globals.num_lights.x; if (_e12 >= metal::min(_e15, c_max_lights)) { break; } - metal::uint _e19 = i; + uint _e19 = i; Light light = s_lights.data[_e19]; - metal::uint _e22 = i; + uint _e22 = i; float _e25 = fetch_shadow(_e22, light.proj * position, t_shadow, sampler_shadow); metal::float3 light_dir = metal::normalize(light.pos.xyz - position.xyz); float diffuse = metal::max(0.0, metal::dot(normal, light_dir)); diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index 26b6812a4..b6e2ce5b1 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + struct VertexOutput { metal::float4 position; metal::float3 uv; @@ -18,7 +20,7 @@ struct vs_mainOutput { metal::float3 uv [[user(loc0), center_perspective]]; }; vertex vs_mainOutput vs_main( - metal::uint vertex_index [[vertex_id]] + uint vertex_index [[vertex_id]] , constant Data& r_data [[buffer(0)]] ) { int tmp1_; diff --git a/tests/out/msl/standard.msl b/tests/out/msl/standard.msl index 016425237..d21930c06 100644 --- a/tests/out/msl/standard.msl +++ b/tests/out/msl/standard.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + struct derivativesInput { }; diff --git a/tests/out/msl/texture-arg.msl b/tests/out/msl/texture-arg.msl index 20e76207d..ba0be05e1 100644 --- a/tests/out/msl/texture-arg.msl +++ b/tests/out/msl/texture-arg.msl @@ -2,6 +2,8 @@ #include #include +using metal::uint; + metal::float4 test( metal::texture2d Passed_Texture, From 679087bd9c9d443f842cee9db4bb02ef29ce0c38 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 21 Feb 2022 15:08:14 -0800 Subject: [PATCH 1601/2212] [msl-out] Bounds checks for `ImageLoad` and `ImageStore`. (#1730) --- src/back/msl/keywords.rs | 1 + src/back/msl/writer.rs | 494 ++++++++++++++++-- src/proc/index.rs | 80 ++- tests/out/msl/bounds-check-image-restrict.msl | 122 +++++ tests/out/msl/bounds-check-image-rzsw.msl | 131 +++++ tests/out/msl/image.msl | 24 +- tests/out/msl/policy-mix.msl | 2 +- tests/snapshots.rs | 7 +- 8 files changed, 767 insertions(+), 94 deletions(-) create mode 100644 tests/out/msl/bounds-check-image-restrict.msl create mode 100644 tests/out/msl/bounds-check-image-rzsw.msl diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs index 7a66b94aa..a3a9c52dc 100644 --- a/src/back/msl/keywords.rs +++ b/src/back/msl/keywords.rs @@ -213,4 +213,5 @@ pub const RESERVED: &[&str] = &[ "M_SQRT1_2", // Naga utilities "DefaultConstructible", + "clamped_lod_e", ]; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a99c9db2a..4fb233a3c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -65,6 +65,9 @@ fn put_numeric_type( } } +/// Prefix for cached clamped level-of-detail values for `ImageLoad` expressions. +const CLAMPED_LOD_LOAD_PREFIX: &str = "clamped_lod_e"; + struct TypeContext<'a> { handle: Handle, arena: &'a crate::UniqueArena, @@ -455,6 +458,37 @@ enum FunctionOrigin { EntryPoint(proc::EntryPointIndex), } +/// A level of detail argument. +/// +/// When [`BoundsCheckPolicy::Restrict`] applies to an [`ImageLoad`] access, we +/// save the clamped level of detail in a temporary variable whose name is based +/// on the handle of the `ImageLoad` expression. But for other policies, we just +/// use the expression directly. +/// +/// [`BoundsCheckPolicy::Restrict`]: index::BoundsCheckPolicy::Restrict +/// [`ImageLoad`]: crate::Expression::ImageLoad +#[derive(Clone, Copy)] +enum LevelOfDetail { + Direct(Handle), + Restricted(Handle), +} + +/// Values needed to select a particular texel for [`ImageLoad`] and [`ImageStore`]. +/// +/// When this is used in code paths unconcerned with the `Restrict` bounds check +/// policy, the `LevelOfDetail` enum introduces an unneeded match, since `level` +/// will always be either `None` or `Some(Direct(_))`. But this turns out not to +/// be too awkward. If that changes, we can revisit. +/// +/// [`ImageLoad`]: crate::Expression::ImageLoad +/// [`ImageStore`]: crate::Statement::ImageStore +struct TexelAddress { + coordinate: Handle, + array_index: Option>, + sample: Option>, + level: Option, +} + struct ExpressionContext<'a> { function: &'a crate::Function, origin: FunctionOrigin, @@ -475,6 +509,21 @@ impl<'a> ExpressionContext<'a> { self.info[handle].ty.inner_with(&self.module.types) } + /// Return true if calls to `image`'s `read` and `write` methods should supply a level of detail. + /// + /// Only mipmapped images need to specify a level of detail. Since 1D + /// textures cannot have mipmaps, MSL requires that the level argument to + /// texture1d queries and accesses must be a constexpr 0. It's easiest + /// just to omit the level entirely for 1D textures. + fn image_needs_lod(&self, image: Handle) -> bool { + let image_ty = self.resolve_type(image); + if let crate::TypeInner::Image { dim, class, .. } = *image_ty { + class.is_mipmapped() && dim != crate::ImageDimension::D1 + } else { + false + } + } + fn choose_bounds_check_policy( &self, pointer: Handle, @@ -559,17 +608,31 @@ impl Writer { Ok(()) } + fn put_level_of_detail( + &mut self, + level: LevelOfDetail, + context: &ExpressionContext, + ) -> BackendResult { + match level { + LevelOfDetail::Direct(expr) => self.put_expression(expr, context, true)?, + LevelOfDetail::Restricted(load) => { + write!(self.out, "{}{}", CLAMPED_LOD_LOAD_PREFIX, load.index())? + } + } + Ok(()) + } + fn put_image_query( &mut self, image: Handle, query: &str, - level: Option>, + level: Option, context: &ExpressionContext, ) -> BackendResult { self.put_expression(image, context, false)?; write!(self.out, ".get_{}(", query)?; - if let Some(expr) = level { - self.put_expression(expr, context, true)?; + if let Some(level) = level { + self.put_level_of_detail(level, context)?; } write!(self.out, ")")?; Ok(()) @@ -578,7 +641,8 @@ impl Writer { fn put_image_size_query( &mut self, image: Handle, - level: Option>, + level: Option, + kind: crate::ScalarKind, context: &ExpressionContext, ) -> BackendResult { //Note: MSL only has separate width/height/depth queries, @@ -587,24 +651,31 @@ impl Writer { crate::TypeInner::Image { dim, .. } => dim, ref other => unreachable!("Unexpected type {:?}", other), }; + let coordinate_type = kind.to_msl_name(); match dim { crate::ImageDimension::D1 => { - write!(self.out, "int(")?; // Since 1D textures never have mipmaps, MSL requires that the // `level` argument be a constexpr 0. It's simplest for us just - // to omit the level entirely. - self.put_image_query(image, "width", None, context)?; - write!(self.out, ")")?; + // to pass `None` and omit the level entirely. + if kind == crate::ScalarKind::Uint { + // No need to construct a vector. No cast needed. + self.put_image_query(image, "width", None, context)?; + } else { + // There's no definition for `int` in the `metal` namespace. + write!(self.out, "int(")?; + self.put_image_query(image, "width", None, context)?; + write!(self.out, ")")?; + } } crate::ImageDimension::D2 => { - write!(self.out, "int2(")?; + write!(self.out, "{}::{}2(", NAMESPACE, coordinate_type)?; self.put_image_query(image, "width", level, context)?; write!(self.out, ", ")?; self.put_image_query(image, "height", level, context)?; write!(self.out, ")")?; } crate::ImageDimension::D3 => { - write!(self.out, "int3(")?; + write!(self.out, "{}::{}3(", NAMESPACE, coordinate_type)?; self.put_image_query(image, "width", level, context)?; write!(self.out, ", ")?; self.put_image_query(image, "height", level, context)?; @@ -613,7 +684,7 @@ impl Writer { write!(self.out, ")")?; } crate::ImageDimension::Cube => { - write!(self.out, "int2(")?; + write!(self.out, "{}::{}2(", NAMESPACE, coordinate_type)?; self.put_image_query(image, "width", level, context)?; write!(self.out, ")")?; } @@ -621,7 +692,7 @@ impl Writer { Ok(()) } - fn put_storage_image_coordinate( + fn put_cast_to_uint_scalar_or_vector( &mut self, expr: Handle, context: &ExpressionContext, @@ -649,13 +720,7 @@ impl Writer { level: crate::SampleLevel, context: &ExpressionContext, ) -> BackendResult { - let has_levels = match *context.resolve_type(image) { - crate::TypeInner::Image { - dim: crate::ImageDimension::D1, - .. - } => false, - _ => true, - }; + let has_levels = context.image_needs_lod(image); match level { crate::SampleLevel::Auto => {} crate::SampleLevel::Zero => { @@ -685,6 +750,275 @@ impl Writer { Ok(()) } + fn put_image_coordinate_limits( + &mut self, + image: Handle, + level: Option, + context: &ExpressionContext, + ) -> BackendResult { + self.put_image_size_query(image, level, crate::ScalarKind::Uint, context)?; + write!(self.out, " - 1")?; + Ok(()) + } + + /// General function for writing restricted image indexes. + /// + /// This is used to produce restricted mip levels, array indices, and sample + /// indices for [`ImageLoad`] and [`ImageStore`] accesses under the + /// [`Restrict`] bounds check policy. + /// + /// This function writes an expression of the form: + /// + /// ```ignore + /// + /// metal::min(uint(INDEX), IMAGE.LIMIT_METHOD() - 1) + /// + /// ``` + /// + /// [`ImageLoad`]: crate::Expression::ImageLoad + /// [`ImageStore`]: crate::Statement::ImageStore + /// [`Restrict`]: index::BoundsCheckPolicy::Restrict + fn put_restricted_scalar_image_index( + &mut self, + image: Handle, + index: Handle, + limit_method: &str, + context: &ExpressionContext, + ) -> BackendResult { + write!(self.out, "{}::min(uint(", NAMESPACE)?; + self.put_expression(index, context, true)?; + write!(self.out, "), ")?; + self.put_expression(image, context, false)?; + write!(self.out, ".{}() - 1)", limit_method)?; + Ok(()) + } + + fn put_restricted_texel_address( + &mut self, + image: Handle, + address: &TexelAddress, + context: &ExpressionContext, + ) -> BackendResult { + // Write the coordinate. + write!(self.out, "{}::min(", NAMESPACE)?; + self.put_cast_to_uint_scalar_or_vector(address.coordinate, context)?; + write!(self.out, ", ")?; + self.put_image_coordinate_limits(image, address.level, context)?; + write!(self.out, ")")?; + + // Write the array index, if present. + if let Some(array_index) = address.array_index { + write!(self.out, ", ")?; + self.put_restricted_scalar_image_index(image, array_index, "get_array_size", context)?; + } + + // Write the sample index, if present. + if let Some(sample) = address.sample { + write!(self.out, ", ")?; + self.put_restricted_scalar_image_index(image, sample, "get_num_samples", context)?; + } + + // The level of detail should be clamped and cached by + // `put_cache_restricted_level`, so we don't need to clamp it here. + if let Some(level) = address.level { + write!(self.out, ", ")?; + self.put_level_of_detail(level, context)?; + } + + Ok(()) + } + + /// Write an expression that is true if the given image access is in bounds. + fn put_image_access_bounds_check( + &mut self, + image: Handle, + address: &TexelAddress, + context: &ExpressionContext, + ) -> BackendResult { + let mut conjunction = ""; + + // First, check the level of detail. Only if that is in bounds can we + // use it to find the appropriate bounds for the coordinates. + let level = if let Some(level) = address.level { + write!(self.out, "uint(")?; + self.put_level_of_detail(level, context)?; + write!(self.out, ") < ")?; + self.put_expression(image, context, true)?; + write!(self.out, ".get_num_mip_levels()")?; + conjunction = " && "; + Some(level) + } else { + None + }; + + // Check sample index, if present. + if let Some(sample) = address.sample { + write!(self.out, "uint(")?; + self.put_expression(sample, context, true)?; + write!(self.out, ") < ")?; + self.put_expression(image, context, true)?; + write!(self.out, ".get_num_samples()")?; + conjunction = " && "; + } + + // Check array index, if present. + if let Some(array_index) = address.array_index { + write!(self.out, "{}uint(", conjunction)?; + self.put_expression(array_index, context, true)?; + write!(self.out, ") < ")?; + self.put_expression(image, context, true)?; + write!(self.out, ".get_array_size()")?; + conjunction = " && "; + } + + // Finally, check if the coordinates are within bounds. + let coord_is_vector = match *context.resolve_type(address.coordinate) { + crate::TypeInner::Vector { .. } => true, + _ => false, + }; + write!(self.out, "{}", conjunction)?; + if coord_is_vector { + write!(self.out, "{}::all(", NAMESPACE)?; + } + self.put_cast_to_uint_scalar_or_vector(address.coordinate, context)?; + write!(self.out, " < ")?; + self.put_image_size_query(image, level, crate::ScalarKind::Uint, context)?; + if coord_is_vector { + write!(self.out, ")")?; + } + + Ok(()) + } + + fn put_image_load( + &mut self, + load: Handle, + image: Handle, + mut address: TexelAddress, + context: &ExpressionContext, + ) -> BackendResult { + match context.policies.image { + proc::BoundsCheckPolicy::Restrict => { + // Use the cached restricted level of detail, if any. Omit the + // level altogether for 1D textures. + if address.level.is_some() { + address.level = if context.image_needs_lod(image) { + Some(LevelOfDetail::Restricted(load)) + } else { + None + } + } + + self.put_expression(image, context, false)?; + write!(self.out, ".read(")?; + self.put_restricted_texel_address(image, &address, context)?; + write!(self.out, ")")?; + } + proc::BoundsCheckPolicy::ReadZeroSkipWrite => { + write!(self.out, "(")?; + self.put_image_access_bounds_check(image, &address, context)?; + write!(self.out, " ? ")?; + self.put_unchecked_image_load(image, &address, context)?; + write!(self.out, ": DefaultConstructible())")?; + } + proc::BoundsCheckPolicy::Unchecked => { + self.put_unchecked_image_load(image, &address, context)?; + } + } + + Ok(()) + } + + fn put_unchecked_image_load( + &mut self, + image: Handle, + address: &TexelAddress, + context: &ExpressionContext, + ) -> BackendResult { + self.put_expression(image, context, false)?; + write!(self.out, ".read(")?; + // coordinates in IR are int, but Metal expects uint + self.put_cast_to_uint_scalar_or_vector(address.coordinate, context)?; + if let Some(expr) = address.array_index { + write!(self.out, ", ")?; + self.put_expression(expr, context, true)?; + } + if let Some(sample) = address.sample { + write!(self.out, ", ")?; + self.put_expression(sample, context, true)?; + } + if let Some(level) = address.level { + if context.image_needs_lod(image) { + write!(self.out, ", ")?; + self.put_level_of_detail(level, context)?; + } + } + write!(self.out, ")")?; + + Ok(()) + } + + fn put_image_store( + &mut self, + level: back::Level, + image: Handle, + address: &TexelAddress, + value: Handle, + context: &StatementContext, + ) -> BackendResult { + match context.expression.policies.image { + proc::BoundsCheckPolicy::Restrict => { + // We don't have a restricted level value, because we don't + // support writes to mipmapped textures. + debug_assert!(address.level.is_none()); + + write!(self.out, "{}", level)?; + self.put_expression(image, &context.expression, false)?; + write!(self.out, ".write(")?; + self.put_expression(value, &context.expression, true)?; + write!(self.out, ", ")?; + self.put_restricted_texel_address(image, address, &context.expression)?; + writeln!(self.out, ");")?; + } + proc::BoundsCheckPolicy::ReadZeroSkipWrite => { + write!(self.out, "{}if (", level)?; + self.put_image_access_bounds_check(image, address, &context.expression)?; + writeln!(self.out, ") {{")?; + self.put_unchecked_image_store(level.next(), image, address, value, context)?; + writeln!(self.out, "{}}}", level)?; + } + proc::BoundsCheckPolicy::Unchecked => { + self.put_unchecked_image_store(level, image, address, value, context)?; + } + } + + Ok(()) + } + + fn put_unchecked_image_store( + &mut self, + level: back::Level, + image: Handle, + address: &TexelAddress, + value: Handle, + context: &StatementContext, + ) -> BackendResult { + write!(self.out, "{}", level)?; + self.put_expression(image, &context.expression, false)?; + write!(self.out, ".write(")?; + self.put_expression(value, &context.expression, true)?; + write!(self.out, ", ")?; + // coordinates in IR are int, but Metal expects uint + self.put_cast_to_uint_scalar_or_vector(address.coordinate, &context.expression)?; + if let Some(expr) = address.array_index { + write!(self.out, ", ")?; + self.put_expression(expr, &context.expression, true)?; + } + writeln!(self.out, ");")?; + + Ok(()) + } + fn put_compose( &mut self, ty: Handle, @@ -1036,38 +1370,24 @@ impl Writer { sample, level, } => { - self.put_expression(image, context, false)?; - write!(self.out, ".read(")?; - self.put_storage_image_coordinate(coordinate, context)?; - if let Some(expr) = array_index { - write!(self.out, ", ")?; - self.put_expression(expr, context, true)?; - } - if let Some(sample) = sample { - write!(self.out, ", ")?; - self.put_expression(sample, context, true)? - } - if let Some(level) = level { - // Metal requires that the `level` argument to - // `texture1d::read` be a constexpr equal to zero. - if let crate::TypeInner::Image { - dim: crate::ImageDimension::D1, - .. - } = *context.resolve_type(image) - { - // The argument defaults to zero. - } else { - write!(self.out, ", ")?; - self.put_expression(level, context, true)? - } - } - write!(self.out, ")")?; + let address = TexelAddress { + coordinate, + array_index, + sample, + level: level.map(LevelOfDetail::Direct), + }; + self.put_image_load(expr_handle, image, address, context)?; } //Note: for all the queries, the signed integers are expected, // so a conversion is needed. crate::Expression::ImageQuery { image, query } => match query { crate::ImageQuery::Size { level } => { - self.put_image_size_query(image, level, context)?; + self.put_image_size_query( + image, + level.map(LevelOfDetail::Direct), + crate::ScalarKind::Sint, + context, + )?; } crate::ImageQuery::NumLevels => { write!(self.out, "int(")?; @@ -1928,6 +2248,57 @@ impl Writer { Ok(()) } + /// Cache a clamped level of detail value, if necessary. + /// + /// [`ImageLoad`] accesses covered by [`BoundsCheckPolicy::Restrict`] use a + /// properly clamped level of detail value both in the access itself, and + /// for fetching the size of the requested MIP level, needed to clamp the + /// coordinates. To avoid recomputing this clamped level of detail, we cache + /// it in a temporary variable, as part of the [`Emit`] statement covering + /// the [`ImageLoad`] expression. + /// + /// [`ImageLoad`]: crate::Expression::ImageLoad + /// [`BoundsCheckPolicy::Restrict`]: index::BoundsCheckPolicy::Restrict + /// [`Emit`]: crate::Statement::Emit + fn put_cache_restricted_level( + &mut self, + load: Handle, + image: Handle, + mip_level: Option>, + indent: back::Level, + context: &StatementContext, + ) -> BackendResult { + // Does this image access actually require (or even permit) a + // level-of-detail, and does the policy require us to restrict it? + let level_of_detail = match mip_level { + Some(level) => level, + None => return Ok(()), + }; + + if context.expression.policies.image != index::BoundsCheckPolicy::Restrict + || !context.expression.image_needs_lod(image) + { + return Ok(()); + } + + write!( + self.out, + "{}uint {}{} = ", + indent, + CLAMPED_LOD_LOAD_PREFIX, + load.index(), + )?; + self.put_restricted_scalar_image_index( + image, + level_of_detail, + "get_num_mip_levels", + &context.expression, + )?; + writeln!(self.out, ";")?; + + Ok(()) + } + fn put_block( &mut self, level: back::Level, @@ -1945,6 +2316,19 @@ impl Writer { match *statement { crate::Statement::Emit(ref range) => { for handle in range.clone() { + // `ImageLoad` expressions covered by the `Restrict` bounds check policy + // may need to cache a clamped version of their level-of-detail argument. + if let crate::Expression::ImageLoad { + image, + level: mip_level, + .. + } = context.expression.function.expressions[handle] + { + self.put_cache_restricted_level( + handle, image, mip_level, level, context, + )?; + } + let info = &context.expression.info[handle]; let ptr_class = info .ty @@ -2123,17 +2507,13 @@ impl Writer { array_index, value, } => { - write!(self.out, "{}", level)?; - self.put_expression(image, &context.expression, false)?; - write!(self.out, ".write(")?; - self.put_expression(value, &context.expression, true)?; - write!(self.out, ", ")?; - self.put_storage_image_coordinate(coordinate, &context.expression)?; - if let Some(expr) = array_index { - write!(self.out, ", ")?; - self.put_expression(expr, &context.expression, true)?; - } - writeln!(self.out, ");")?; + let address = TexelAddress { + coordinate, + array_index, + sample: None, + level: None, + }; + self.put_image_store(level, image, &address, value, context)? } crate::Statement::Call { function, diff --git a/src/proc/index.rs b/src/proc/index.rs index 340862ebc..b0939b0e7 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -178,26 +178,39 @@ pub enum GuardedIndex { /// /// Such index expressions will be used twice in the generated code: first for the /// comparison to see if the index is in bounds, and then for the access itself, should -/// the comparison succeed. To avoid computing the expressions twice, they should be -/// cached in temporary variables. +/// the comparison succeed. To avoid computing the expressions twice, the generated code +/// should cache them in temporary variables. /// -/// Why do we need to build such a set before processing a function's statements? Whether -/// an expression needs to be cached depends on whether it appears as the [`index`] -/// operand of any [`Access`] expression, and on the index bounds check policies that -/// apply to those accesses. But [`Emit`] statements just identify a range of expressions -/// by index; there's no good way to tell what an expression is used for. The only way to -/// do it is to just iterate over all the expressions looking for relevant `Access` -/// expressions --- which is what this function does. +/// Why do we need to build such a set in advance, instead of just processing access +/// expressions as we encounter them? Whether an expression needs to be cached depends on +/// whether it appears as something like the [`index`] operand of an [`Access`] expression +/// or the [`level`] operand of an [`ImageLoad`] expression, and on the index bounds check +/// policies that apply to those accesses. But [`Emit`] statements just identify a range +/// of expressions by index; there's no good way to tell what an expression is used +/// for. The only way to do it is to just iterate over all the expressions looking for +/// relevant `Access` expressions --- which is what this function does. /// /// Simple expressions like variable loads and constants don't make sense to cache: it's /// no better than just re-evaluating them. But constants are not covered by `Emit` /// statements, and `Load`s are always cached to ensure they occur at the right time, so /// we don't bother filtering them out from this set. /// +/// Fortunately, we don't need to deal with [`ImageStore`] statements here. When we emit +/// code for a statement, the writer isn't in the middle of an expression, so we can just +/// emit declarations for temporaries, initialized appropriately. +/// +/// None of these concerns apply for SPIR-V output, since it's easy to just reuse an +/// instruction ID in two places; that has the same semantics as a temporary variable, and +/// it's inherent in the design of SPIR-V. This function is more useful for text-based +/// back ends. +/// /// [`ReadZeroSkipWrite`]: BoundsCheckPolicy::ReadZeroSkipWrite /// [`index`]: crate::Expression::Access::index /// [`Access`]: crate::Expression::Access +/// [`level`]: crate::Expression::ImageLoad::level +/// [`ImageLoad`]: crate::Expression::ImageLoad /// [`Emit`]: crate::Statement::Emit +/// [`ImageStore`]: crate::Statement::ImageStore pub fn find_checked_indexes( module: &crate::Module, function: &crate::Function, @@ -213,20 +226,43 @@ pub fn find_checked_indexes( for (_handle, expr) in function.expressions.iter() { // There's no need to handle `AccessIndex` expressions, as their // indices never need to be cached. - if let Ex::Access { base, index } = *expr { - if policies.choose_policy(base, &module.types, info) - == BoundsCheckPolicy::ReadZeroSkipWrite - && access_needs_check( - base, - GuardedIndex::Expression(index), - module, - function, - info, - ) - .is_some() - { - guarded_indices.insert(index.index()); + match *expr { + Ex::Access { base, index } => { + if policies.choose_policy(base, &module.types, info) + == BoundsCheckPolicy::ReadZeroSkipWrite + && access_needs_check( + base, + GuardedIndex::Expression(index), + module, + function, + info, + ) + .is_some() + { + guarded_indices.insert(index.index()); + } } + Ex::ImageLoad { + coordinate, + array_index, + sample, + level, + .. + } => { + if policies.image == BoundsCheckPolicy::ReadZeroSkipWrite { + guarded_indices.insert(coordinate.index()); + if let Some(array_index) = array_index { + guarded_indices.insert(array_index.index()); + } + if let Some(sample) = sample { + guarded_indices.insert(sample.index()); + } + if let Some(level) = level { + guarded_indices.insert(level.index()); + } + } + } + _ => {} } } } diff --git a/tests/out/msl/bounds-check-image-restrict.msl b/tests/out/msl/bounds-check-image-restrict.msl new file mode 100644 index 000000000..1eb6f2331 --- /dev/null +++ b/tests/out/msl/bounds-check-image-restrict.msl @@ -0,0 +1,122 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + + +metal::float4 test_textureLoad_1d( + int coords, + int level, + metal::texture1d image_1d +) { + metal::float4 _e3 = image_1d.read(metal::min(uint(coords), image_1d.get_width() - 1)); + return _e3; +} + +metal::float4 test_textureLoad_2d( + metal::int2 coords_1, + int level_1, + metal::texture2d image_2d +) { + uint clamped_lod_e4 = metal::min(uint(level_1), image_2d.get_num_mip_levels() - 1); + metal::float4 _e4 = image_2d.read(metal::min(metal::uint2(coords_1), metal::uint2(image_2d.get_width(clamped_lod_e4), image_2d.get_height(clamped_lod_e4)) - 1), clamped_lod_e4); + return _e4; +} + +metal::float4 test_textureLoad_2d_array( + metal::int2 coords_2, + int index, + int level_2, + metal::texture2d_array image_2d_array +) { + uint clamped_lod_e6 = metal::min(uint(level_2), image_2d_array.get_num_mip_levels() - 1); + metal::float4 _e6 = image_2d_array.read(metal::min(metal::uint2(coords_2), metal::uint2(image_2d_array.get_width(clamped_lod_e6), image_2d_array.get_height(clamped_lod_e6)) - 1), metal::min(uint(index), image_2d_array.get_array_size() - 1), clamped_lod_e6); + return _e6; +} + +metal::float4 test_textureLoad_3d( + metal::int3 coords_3, + int level_3, + metal::texture3d image_3d +) { + uint clamped_lod_e6 = metal::min(uint(level_3), image_3d.get_num_mip_levels() - 1); + metal::float4 _e6 = image_3d.read(metal::min(metal::uint3(coords_3), metal::uint3(image_3d.get_width(clamped_lod_e6), image_3d.get_height(clamped_lod_e6), image_3d.get_depth(clamped_lod_e6)) - 1), clamped_lod_e6); + return _e6; +} + +metal::float4 test_textureLoad_multisampled_2d( + metal::int2 coords_4, + int sample, + metal::texture2d_ms image_multisampled_2d +) { + metal::float4 _e7 = image_multisampled_2d.read(metal::min(metal::uint2(coords_4), metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height()) - 1), metal::min(uint(sample), image_multisampled_2d.get_num_samples() - 1)); + return _e7; +} + +float test_textureLoad_depth_2d( + metal::int2 coords_5, + int level_4, + metal::depth2d image_depth_2d +) { + uint clamped_lod_e8 = metal::min(uint(level_4), image_depth_2d.get_num_mip_levels() - 1); + float _e8 = image_depth_2d.read(metal::min(metal::uint2(coords_5), metal::uint2(image_depth_2d.get_width(clamped_lod_e8), image_depth_2d.get_height(clamped_lod_e8)) - 1), clamped_lod_e8); + return _e8; +} + +float test_textureLoad_depth_2d_array( + metal::int2 coords_6, + int index_1, + int level_5, + metal::depth2d_array image_depth_2d_array +) { + uint clamped_lod_e10 = metal::min(uint(level_5), image_depth_2d_array.get_num_mip_levels() - 1); + float _e10 = image_depth_2d_array.read(metal::min(metal::uint2(coords_6), metal::uint2(image_depth_2d_array.get_width(clamped_lod_e10), image_depth_2d_array.get_height(clamped_lod_e10)) - 1), metal::min(uint(index_1), image_depth_2d_array.get_array_size() - 1), clamped_lod_e10); + return _e10; +} + +float test_textureLoad_depth_multisampled_2d( + metal::int2 coords_7, + int sample_1, + metal::depth2d_ms image_depth_multisampled_2d +) { + float _e10 = image_depth_multisampled_2d.read(metal::min(metal::uint2(coords_7), metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height()) - 1), metal::min(uint(sample_1), image_depth_multisampled_2d.get_num_samples() - 1)); + return _e10; +} + +void test_textureStore_1d( + int coords_8, + metal::float4 value, + metal::texture1d image_storage_1d +) { + image_storage_1d.write(value, metal::min(uint(coords_8), image_storage_1d.get_width() - 1)); + return; +} + +void test_textureStore_2d( + metal::int2 coords_9, + metal::float4 value_1, + metal::texture2d image_storage_2d +) { + image_storage_2d.write(value_1, metal::min(metal::uint2(coords_9), metal::uint2(image_storage_2d.get_width(), image_storage_2d.get_height()) - 1)); + return; +} + +void test_textureStore_2d_array( + metal::int2 coords_10, + int array_index, + metal::float4 value_2, + metal::texture2d_array image_storage_2d_array +) { + image_storage_2d_array.write(value_2, metal::min(metal::uint2(coords_10), metal::uint2(image_storage_2d_array.get_width(), image_storage_2d_array.get_height()) - 1), metal::min(uint(array_index), image_storage_2d_array.get_array_size() - 1)); + return; +} + +void test_textureStore_3d( + metal::int3 coords_11, + metal::float4 value_3, + metal::texture3d image_storage_3d +) { + image_storage_3d.write(value_3, metal::min(metal::uint3(coords_11), metal::uint3(image_storage_3d.get_width(), image_storage_3d.get_height(), image_storage_3d.get_depth()) - 1)); + return; +} diff --git a/tests/out/msl/bounds-check-image-rzsw.msl b/tests/out/msl/bounds-check-image-rzsw.msl new file mode 100644 index 000000000..6acb1046a --- /dev/null +++ b/tests/out/msl/bounds-check-image-rzsw.msl @@ -0,0 +1,131 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct DefaultConstructible { + template + operator T() && { + return T {}; + } +}; + +metal::float4 test_textureLoad_1d( + int coords, + int level, + metal::texture1d image_1d +) { + metal::float4 _e3 = (uint(level) < image_1d.get_num_mip_levels() && uint(coords) < image_1d.get_width() ? image_1d.read(uint(coords)): DefaultConstructible()); + return _e3; +} + +metal::float4 test_textureLoad_2d( + metal::int2 coords_1, + int level_1, + metal::texture2d image_2d +) { + metal::float4 _e4 = (uint(level_1) < image_2d.get_num_mip_levels() && metal::all(metal::uint2(coords_1) < metal::uint2(image_2d.get_width(level_1), image_2d.get_height(level_1))) ? image_2d.read(metal::uint2(coords_1), level_1): DefaultConstructible()); + return _e4; +} + +metal::float4 test_textureLoad_2d_array( + metal::int2 coords_2, + int index, + int level_2, + metal::texture2d_array image_2d_array +) { + metal::float4 _e6 = (uint(level_2) < image_2d_array.get_num_mip_levels() && uint(index) < image_2d_array.get_array_size() && metal::all(metal::uint2(coords_2) < metal::uint2(image_2d_array.get_width(level_2), image_2d_array.get_height(level_2))) ? image_2d_array.read(metal::uint2(coords_2), index, level_2): DefaultConstructible()); + return _e6; +} + +metal::float4 test_textureLoad_3d( + metal::int3 coords_3, + int level_3, + metal::texture3d image_3d +) { + metal::float4 _e6 = (uint(level_3) < image_3d.get_num_mip_levels() && metal::all(metal::uint3(coords_3) < metal::uint3(image_3d.get_width(level_3), image_3d.get_height(level_3), image_3d.get_depth(level_3))) ? image_3d.read(metal::uint3(coords_3), level_3): DefaultConstructible()); + return _e6; +} + +metal::float4 test_textureLoad_multisampled_2d( + metal::int2 coords_4, + int sample, + metal::texture2d_ms image_multisampled_2d +) { + metal::float4 _e7 = (uint(sample) < image_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_4) < metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height())) ? image_multisampled_2d.read(metal::uint2(coords_4), sample): DefaultConstructible()); + return _e7; +} + +float test_textureLoad_depth_2d( + metal::int2 coords_5, + int level_4, + metal::depth2d image_depth_2d +) { + float _e8 = (uint(level_4) < image_depth_2d.get_num_mip_levels() && metal::all(metal::uint2(coords_5) < metal::uint2(image_depth_2d.get_width(level_4), image_depth_2d.get_height(level_4))) ? image_depth_2d.read(metal::uint2(coords_5), level_4): DefaultConstructible()); + return _e8; +} + +float test_textureLoad_depth_2d_array( + metal::int2 coords_6, + int index_1, + int level_5, + metal::depth2d_array image_depth_2d_array +) { + float _e10 = (uint(level_5) < image_depth_2d_array.get_num_mip_levels() && uint(index_1) < image_depth_2d_array.get_array_size() && metal::all(metal::uint2(coords_6) < metal::uint2(image_depth_2d_array.get_width(level_5), image_depth_2d_array.get_height(level_5))) ? image_depth_2d_array.read(metal::uint2(coords_6), index_1, level_5): DefaultConstructible()); + return _e10; +} + +float test_textureLoad_depth_multisampled_2d( + metal::int2 coords_7, + int sample_1, + metal::depth2d_ms image_depth_multisampled_2d +) { + float _e10 = (uint(sample_1) < image_depth_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_7) < metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height())) ? image_depth_multisampled_2d.read(metal::uint2(coords_7), sample_1): DefaultConstructible()); + return _e10; +} + +void test_textureStore_1d( + int coords_8, + metal::float4 value, + metal::texture1d image_storage_1d +) { + if (uint(coords_8) < image_storage_1d.get_width()) { + image_storage_1d.write(value, uint(coords_8)); + } + return; +} + +void test_textureStore_2d( + metal::int2 coords_9, + metal::float4 value_1, + metal::texture2d image_storage_2d +) { + if (metal::all(metal::uint2(coords_9) < metal::uint2(image_storage_2d.get_width(), image_storage_2d.get_height()))) { + image_storage_2d.write(value_1, metal::uint2(coords_9)); + } + return; +} + +void test_textureStore_2d_array( + metal::int2 coords_10, + int array_index, + metal::float4 value_2, + metal::texture2d_array image_storage_2d_array +) { + if (uint(array_index) < image_storage_2d_array.get_array_size() && metal::all(metal::uint2(coords_10) < metal::uint2(image_storage_2d_array.get_width(), image_storage_2d_array.get_height()))) { + image_storage_2d_array.write(value_2, metal::uint2(coords_10), array_index); + } + return; +} + +void test_textureStore_3d( + metal::int3 coords_11, + metal::float4 value_3, + metal::texture3d image_storage_3d +) { + if (metal::all(metal::uint3(coords_11) < metal::uint3(image_storage_3d.get_width(), image_storage_3d.get_height(), image_storage_3d.get_depth()))) { + image_storage_3d.write(value_3, metal::uint3(coords_11)); + } + return; +} diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 74d75ff7d..5bfd943e3 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -17,7 +17,7 @@ kernel void main_( , metal::texture1d image_1d_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 dim = int2(image_storage_src.get_width(), image_storage_src.get_height()); + metal::int2 dim = metal::int2(image_storage_src.get_width(), image_storage_src.get_height()); metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); @@ -37,7 +37,7 @@ kernel void depth_load( , metal::texture2d image_storage_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 dim_1 = int2(image_storage_src.get_width(), image_storage_src.get_height()); + metal::int2 dim_1 = metal::int2(image_storage_src.get_width(), image_storage_src.get_height()); metal::int2 itc_1 = (dim_1 * static_cast(local_id_1.xy)) % metal::int2(10, 20); float val = image_depth_multisampled_src.read(metal::uint2(itc_1), static_cast(local_id_1.z)); image_dst.write(metal::uint4(static_cast(val)), uint(itc_1.x)); @@ -58,16 +58,16 @@ vertex queriesOutput queries( ) { int dim_1d = int(image_1d.get_width()); int dim_1d_lod = int(image_1d.get_width()); - metal::int2 dim_2d = int2(image_2d.get_width(), image_2d.get_height()); - metal::int2 dim_2d_lod = int2(image_2d.get_width(1), image_2d.get_height(1)); - metal::int2 dim_2d_array = int2(image_2d_array.get_width(), image_2d_array.get_height()); - metal::int2 dim_2d_array_lod = int2(image_2d_array.get_width(1), image_2d_array.get_height(1)); - metal::int2 dim_cube = int2(image_cube.get_width()); - metal::int2 dim_cube_lod = int2(image_cube.get_width(1)); - metal::int2 dim_cube_array = int2(image_cube_array.get_width()); - metal::int2 dim_cube_array_lod = int2(image_cube_array.get_width(1)); - metal::int3 dim_3d = int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()); - metal::int3 dim_3d_lod = int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)); + metal::int2 dim_2d = metal::int2(image_2d.get_width(), image_2d.get_height()); + metal::int2 dim_2d_lod = metal::int2(image_2d.get_width(1), image_2d.get_height(1)); + metal::int2 dim_2d_array = metal::int2(image_2d_array.get_width(), image_2d_array.get_height()); + metal::int2 dim_2d_array_lod = metal::int2(image_2d_array.get_width(1), image_2d_array.get_height(1)); + metal::int2 dim_cube = metal::int2(image_cube.get_width()); + metal::int2 dim_cube_lod = metal::int2(image_cube.get_width(1)); + metal::int2 dim_cube_array = metal::int2(image_cube_array.get_width()); + metal::int2 dim_cube_array_lod = metal::int2(image_cube_array.get_width(1)); + metal::int3 dim_3d = metal::int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()); + metal::int3 dim_3d_lod = metal::int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)); int sum = (((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z; return queriesOutput { metal::float4(static_cast(sum)) }; } diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index 9020c64fe..8b4ba9911 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -46,7 +46,7 @@ metal::float4 mock_function( for(int _i=0; _i<2; ++_i) in_function.inner[_i] = type_9 {metal::float4(0.7070000171661377, 0.0, 0.0, 1.0), metal::float4(0.0, 0.7070000171661377, 0.0, 1.0)}.inner[_i]; metal::float4 _e22 = in_storage.a.inner[i]; metal::float4 _e25 = in_uniform.a.inner[i]; - metal::float4 _e27 = image_2d_array.read(metal::uint2(c), i, l); + metal::float4 _e27 = (uint(l) < image_2d_array.get_num_mip_levels() && uint(i) < image_2d_array.get_array_size() && metal::all(metal::uint2(c) < metal::uint2(image_2d_array.get_width(l), image_2d_array.get_height(l))) ? image_2d_array.read(metal::uint2(c), i, l): DefaultConstructible()); float _e30 = in_workgroup.inner[metal::min(unsigned(i), 29u)]; float _e34 = in_private.inner[metal::min(unsigned(i), 39u)]; metal::float4 _e38 = in_function.inner[metal::min(unsigned(i), 1u)]; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b1b205845..279a79c70 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -479,8 +479,11 @@ fn convert_wgsl() { ("bounds-check-zero", Targets::SPIRV | Targets::METAL), ("bounds-check-zero-atomic", Targets::METAL), ("bounds-check-restrict", Targets::SPIRV | Targets::METAL), - ("bounds-check-image-restrict", Targets::SPIRV), - ("bounds-check-image-rzsw", Targets::SPIRV), + ( + "bounds-check-image-restrict", + Targets::SPIRV | Targets::METAL, + ), + ("bounds-check-image-rzsw", Targets::SPIRV | Targets::METAL), ("policy-mix", Targets::SPIRV | Targets::METAL), ( "texture-arg", From a45b9a6cc691a671aa24a32114b51c5acae02420 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 22 Feb 2022 01:40:00 -0500 Subject: [PATCH 1602/2212] wgsl: update find msb/lsb names (#1735) --- CHANGELOG.md | 3 +++ src/back/wgsl/writer.rs | 4 ++-- src/front/wgsl/conv.rs | 4 ++-- tests/in/bits.wgsl | 8 ++++---- tests/out/wgsl/bits.wgsl | 8 ++++---- tests/out/wgsl/bits_glsl-frag.wgsl | 32 +++++++++++++++--------------- 6 files changed, 31 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 446cb4464..df475b0c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ - attributes are declared with `@attrib` instead of `[[attrib]]` - `stride` attribute is removed - block comments are supported + - renames: + - `findLsb` -> `firstTrailingBit` + - `findMsb` -> `firstLeadingBit` ## v0.8 (2021-12-18) - development release for wgpu-0.12 diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index d2eecd8cc..2d4b0150b 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1527,8 +1527,8 @@ impl Writer { Mf::ReverseBits => Function::Regular("reverseBits"), Mf::ExtractBits => Function::Regular("extractBits"), Mf::InsertBits => Function::Regular("insertBits"), - Mf::FindLsb => Function::Regular("findLsb"), - Mf::FindMsb => Function::Regular("findMsb"), + Mf::FindLsb => Function::Regular("firstTrailingBit"), + Mf::FindMsb => Function::Regular("firstLeadingBit"), // data packing Mf::Pack4x8snorm => Function::Regular("pack4x8snorm"), Mf::Pack4x8unorm => Function::Regular("pack4x8unorm"), diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index e4cec50b3..a4cf149a2 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -201,8 +201,8 @@ pub fn map_standard_fun(word: &str) -> Option { "reverseBits" => Mf::ReverseBits, "extractBits" => Mf::ExtractBits, "insertBits" => Mf::InsertBits, - "findLsb" => Mf::FindLsb, - "findMsb" => Mf::FindMsb, + "firstTrailingBit" => Mf::FindLsb, + "firstLeadingBit" => Mf::FindMsb, // data packing "pack4x8snorm" => Mf::Pack4x8snorm, "pack4x8unorm" => Mf::Pack4x8unorm, diff --git a/tests/in/bits.wgsl b/tests/in/bits.wgsl index 6851f243f..9de7de547 100644 --- a/tests/in/bits.wgsl +++ b/tests/in/bits.wgsl @@ -36,8 +36,8 @@ fn main() { u2 = extractBits(u2, 5u, 10u); u3 = extractBits(u3, 5u, 10u); u4 = extractBits(u4, 5u, 10u); - i = findLsb(i); - i2 = findLsb(u2); - i3 = findMsb(i3); - i = findMsb(u); + i = firstTrailingBit(i); + i2 = firstTrailingBit(u2); + i3 = firstLeadingBit(i3); + i = firstLeadingBit(u); } diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index 1af9b969d..60cf9cc9e 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -80,12 +80,12 @@ fn main() { let _e116 = u4_; u4_ = extractBits(_e116, 5u, 10u); let _e120 = i; - i = findLsb(_e120); + i = firstTrailingBit(_e120); let _e122 = u2_; - i2_ = findLsb(_e122); + i2_ = firstTrailingBit(_e122); let _e124 = i3_; - i3_ = findMsb(_e124); + i3_ = firstLeadingBit(_e124); let _e126 = u; - i = findMsb(_e126); + i = firstLeadingBit(_e126); return; } diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 8faa6e26e..41d259914 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -71,37 +71,37 @@ fn main_1() { let _e216 = u4_; u4_ = extractBits(_e216, u32(5), u32(10)); let _e223 = i; - i = findLsb(_e223); + i = firstTrailingBit(_e223); let _e226 = i2_; - i2_ = findLsb(_e226); + i2_ = firstTrailingBit(_e226); let _e229 = i3_; - i3_ = findLsb(_e229); + i3_ = firstTrailingBit(_e229); let _e232 = i4_; - i4_ = findLsb(_e232); + i4_ = firstTrailingBit(_e232); let _e235 = u; - i = findLsb(_e235); + i = firstTrailingBit(_e235); let _e238 = u2_; - i2_ = findLsb(_e238); + i2_ = firstTrailingBit(_e238); let _e241 = u3_; - i3_ = findLsb(_e241); + i3_ = firstTrailingBit(_e241); let _e244 = u4_; - i4_ = findLsb(_e244); + i4_ = firstTrailingBit(_e244); let _e247 = i; - i = findMsb(_e247); + i = firstLeadingBit(_e247); let _e250 = i2_; - i2_ = findMsb(_e250); + i2_ = firstLeadingBit(_e250); let _e253 = i3_; - i3_ = findMsb(_e253); + i3_ = firstLeadingBit(_e253); let _e256 = i4_; - i4_ = findMsb(_e256); + i4_ = firstLeadingBit(_e256); let _e259 = u; - i = findMsb(_e259); + i = firstLeadingBit(_e259); let _e262 = u2_; - i2_ = findMsb(_e262); + i2_ = firstLeadingBit(_e262); let _e265 = u3_; - i3_ = findMsb(_e265); + i3_ = firstLeadingBit(_e265); let _e268 = u4_; - i4_ = findMsb(_e268); + i4_ = firstLeadingBit(_e268); return; } From 419a6c69f9a49713b041a2c1c973129ee190caf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 22 Feb 2022 16:47:36 +0000 Subject: [PATCH 1603/2212] spv-out: Use OpImageQuerySize for MS images --- src/back/spv/image.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 1eb5ab3b9..06eb21cb9 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -1030,7 +1030,9 @@ impl<'w> BlockContext<'w> { }; let (query_op, level_id) = match class { - Ic::Storage { .. } => (spirv::Op::ImageQuerySize, None), + Ic::Sampled { multi: true, .. } + | Ic::Depth { multi: true } + | Ic::Storage { .. } => (spirv::Op::ImageQuerySize, None), _ => { let level_id = match level { Some(expr) => self.cached[expr], From 98e7add6a2ff1fe83b44f0aa1c01da20967f45a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 22 Feb 2022 16:26:37 +0000 Subject: [PATCH 1604/2212] glsl-out: texture function fixes - samplerCubeShadow requires vec3 gradients - Bias must be written after offset - sampler1D hack on GLES requires vec2 gradients - textureSize doesn't accept a lod argument for MS samplers - sampler1DArray hack on GLES requires a y component on imageLoad --- src/back/glsl/mod.rs | 73 +- tests/in/image.wgsl | 5 + tests/out/glsl/image.queries.Vertex.glsl | 3 + tests/out/glsl/image.sample.Fragment.glsl | 1 + .../image.sample_comparison.Fragment.glsl | 3 + tests/out/glsl/shadow.fs_main.Fragment.glsl | 2 +- tests/out/hlsl/image.hlsl | 11 + tests/out/msl/image.msl | 5 + tests/out/spv/image.spvasm | 679 +++++++++--------- tests/out/wgsl/image.wgsl | 5 + 10 files changed, 435 insertions(+), 352 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b765c0341..76c528782 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2192,7 +2192,11 @@ impl<'a, W: Write> Writer<'a, W> { // Zero needs level set to 0 crate::SampleLevel::Zero => { if workaround_lod_array_shadow_as_grad { - write!(self.out, ", vec2(0,0), vec2(0,0)")?; + let vec_dim = match dim { + crate::ImageDimension::Cube => 3, + _ => 2, + }; + write!(self.out, ", vec{}(0.0), vec{}(0.0)", vec_dim, vec_dim)?; } else if gather.is_none() { write!(self.out, ", 0.0")?; } @@ -2207,15 +2211,25 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(expr, ctx)?; } } - crate::SampleLevel::Bias(expr) => { - write!(self.out, ", ")?; - self.write_expr(expr, ctx)?; + crate::SampleLevel::Bias(_) => { + // This needs to be done after the offset writing } crate::SampleLevel::Gradient { x, y } => { - write!(self.out, ", ")?; - self.write_expr(x, ctx)?; - write!(self.out, ", ")?; - self.write_expr(y, ctx)?; + // If we are using sampler2D to replace sampler1D, we also + // need to make sure to use vec2 gradients + if tex_1d_hack { + write!(self.out, ", vec2(")?; + self.write_expr(x, ctx)?; + write!(self.out, ", 0.0)")?; + write!(self.out, ", vec2(")?; + self.write_expr(y, ctx)?; + write!(self.out, ", 0.0)")?; + } else { + write!(self.out, ", ")?; + self.write_expr(x, ctx)?; + write!(self.out, ", ")?; + self.write_expr(y, ctx)?; + } } } @@ -2230,6 +2244,12 @@ impl<'a, W: Write> Writer<'a, W> { } } + // Bias is always the last argument + if let crate::SampleLevel::Bias(expr) = level { + write!(self.out, ", ")?; + self.write_expr(expr, ctx)?; + } + if let (Some(component), None) = (gather, depth_ref) { write!(self.out, ", {}", component as usize)?; } @@ -2307,14 +2327,16 @@ impl<'a, W: Write> Writer<'a, W> { match query { crate::ImageQuery::Size { level } => { match class { - ImageClass::Sampled { .. } | ImageClass::Depth { .. } => { + ImageClass::Sampled { multi, .. } | ImageClass::Depth { multi } => { write!(self.out, "textureSize(")?; self.write_expr(image, ctx)?; - write!(self.out, ", ")?; if let Some(expr) = level { + write!(self.out, ", ")?; self.write_expr(expr, ctx)?; - } else { - write!(self.out, "0")?; + } else if !multi { + // All textureSize calls requires an lod argument + // except for multisampled samplers + write!(self.out, ", 0")?; } } ImageClass::Storage { .. } => { @@ -2339,8 +2361,14 @@ impl<'a, W: Write> Writer<'a, W> { }; write!(self.out, "{}(", fun_name)?; self.write_expr(image, ctx)?; + // All textureSize calls requires an lod argument + // except for multisampled samplers + if class.is_multisampled() { + write!(self.out, ", 0")?; + } + write!(self.out, ")")?; if components != 1 || self.options.version.is_es() { - write!(self.out, ", 0).{}", back::COMPONENTS[components])?; + write!(self.out, ".{}", back::COMPONENTS[components])?; } } crate::ImageQuery::NumSamples => { @@ -2808,22 +2836,27 @@ impl<'a, W: Write> Writer<'a, W> { ) -> Result<(), Error> { use crate::ImageDimension as IDim; + let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es(); match array_index { Some(layer_expr) => { - let tex_coord_type = match dim { - IDim::D1 => "ivec2", - IDim::D2 => "ivec3", - IDim::D3 => "ivec4", - IDim::Cube => "ivec4", + let tex_coord_size = match dim { + IDim::D1 => 2, + IDim::D2 => 3, + IDim::D3 => 4, + IDim::Cube => 4, }; - write!(self.out, "{}(", tex_coord_type)?; + write!(self.out, "ivec{}(", tex_coord_size + tex_1d_hack as u8)?; self.write_expr(coordinate, ctx)?; write!(self.out, ", ")?; + // If we are replacing sampler1D with sampler2D we also need + // to add another zero to the coordinates vector for the y component + if tex_1d_hack { + write!(self.out, "0, ")?; + } self.write_expr(layer_expr, ctx)?; write!(self.out, ")")?; } None => { - let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es(); if tex_1d_hack { write!(self.out, "ivec2(")?; } diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index d722fcf41..5fd0eec13 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -69,6 +69,7 @@ fn queries() -> @builtin(position) vec4 { let dim_cube_array_lod = textureDimensions(image_cube_array, 1); let dim_3d = textureDimensions(image_3d); let dim_3d_lod = textureDimensions(image_3d, 1); + let dim_2s_ms = textureDimensions(image_aa); let sum = dim_1d + dim_2d.y + dim_2d_lod.y + dim_2d_array.y + dim_2d_array_lod.y + dim_cube.y + dim_cube_lod.y + dim_cube_array.y + dim_cube_array_lod.y + @@ -104,6 +105,7 @@ fn sample() -> @location(0) vec4 { let s2d_offset = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); let s2d_level = textureSampleLevel(image_2d, sampler_reg, tc, level); let s2d_level_offset = textureSampleLevel(image_2d, sampler_reg, tc, level, vec2(3, 1)); + let s2d_bias_offset = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); return s1d + s2d + s2d_offset + s2d_level + s2d_level_offset; } @@ -111,6 +113,8 @@ fn sample() -> @location(0) vec4 { var sampler_cmp: sampler_comparison; @group(1) @binding(2) var image_2d_depth: texture_depth_2d; +@group(1) @binding(3) +var image_cube_depth: texture_depth_cube; @stage(fragment) fn sample_comparison() -> @location(0) f32 { @@ -118,6 +122,7 @@ fn sample_comparison() -> @location(0) f32 { let dref = 0.5; let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc, dref); let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc, dref); + let scube_depth_level = textureSampleCompareLevel(image_cube_depth, sampler_cmp, vec3(0.5), dref); return s2d_depth + s2d_depth_level; } diff --git a/tests/out/glsl/image.queries.Vertex.glsl b/tests/out/glsl/image.queries.Vertex.glsl index d95faea9f..dfafa041b 100644 --- a/tests/out/glsl/image.queries.Vertex.glsl +++ b/tests/out/glsl/image.queries.Vertex.glsl @@ -16,6 +16,8 @@ uniform highp samplerCubeArray _group_0_binding_4_vs; uniform highp sampler3D _group_0_binding_5_vs; +uniform highp sampler2DMS _group_0_binding_6_vs; + void main() { int dim_1d = textureSize(_group_0_binding_0_vs, 0).x; @@ -30,6 +32,7 @@ void main() { ivec2 dim_cube_array_lod = textureSize(_group_0_binding_4_vs, 1).xy; ivec3 dim_3d = textureSize(_group_0_binding_5_vs, 0).xyz; ivec3 dim_3d_lod = textureSize(_group_0_binding_5_vs, 1).xyz; + ivec2 dim_2s_ms = textureSize(_group_0_binding_6_vs).xy; int sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); gl_Position = vec4(float(sum)); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/glsl/image.sample.Fragment.glsl b/tests/out/glsl/image.sample.Fragment.glsl index 288e23350..5ebec0fc4 100644 --- a/tests/out/glsl/image.sample.Fragment.glsl +++ b/tests/out/glsl/image.sample.Fragment.glsl @@ -17,6 +17,7 @@ void main() { vec4 s2d_offset = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1)); vec4 s2d_level = textureLod(_group_0_binding_1_fs, vec2(tc), 2.299999952316284); vec4 s2d_level_offset = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.299999952316284, ivec2(3, 1)); + vec4 s2d_bias_offset = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 2.0); _fs2p_location0 = ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); return; } diff --git a/tests/out/glsl/image.sample_comparison.Fragment.glsl b/tests/out/glsl/image.sample_comparison.Fragment.glsl index a1994e3a0..ab7fda49f 100644 --- a/tests/out/glsl/image.sample_comparison.Fragment.glsl +++ b/tests/out/glsl/image.sample_comparison.Fragment.glsl @@ -6,12 +6,15 @@ precision highp int; uniform highp sampler2DShadow _group_1_binding_2_fs; +uniform highp samplerCubeShadow _group_1_binding_3_fs; + layout(location = 0) out float _fs2p_location0; void main() { vec2 tc = vec2(0.5); float s2d_depth = texture(_group_1_binding_2_fs, vec3(tc, 0.5)); float s2d_depth_level = textureLod(_group_1_binding_2_fs, vec3(tc, 0.5), 0.0); + float scube_depth_level = textureGrad(_group_1_binding_3_fs, vec4(vec3(0.5), 0.5), vec3(0.0), vec3(0.0)); _fs2p_location0 = (s2d_depth + s2d_depth_level); return; } diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 3d26dbfdb..3e5562a71 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -29,7 +29,7 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } vec2 flip_correction = vec2(0.5, -0.5); vec2 light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - float _e26 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0,0), vec2(0,0)); + float _e26 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0.0), vec2(0.0)); return _e26; } diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index d75cf327b..840352ff9 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -17,6 +17,7 @@ Texture2DMS image_aa : register(t6); SamplerState sampler_reg : register(s0, space1); SamplerComparisonState sampler_cmp : register(s1, space1); Texture2D image_2d_depth : register(t2, space1); +TextureCube image_cube_depth : register(t3, space1); int2 NagaRWDimensions2D(RWTexture2D tex) { @@ -133,6 +134,13 @@ int3 NagaMipDimensions3D(Texture3D tex, uint mip_level) return ret.xyz; } +int2 NagaMSDimensions2D(Texture2DMS tex) +{ + uint4 ret; + tex.GetDimensions(ret.x, ret.y, ret.z); + return ret.xy; +} + float4 queries() : SV_Position { int dim_1d = NagaDimensions1D(image_1d); @@ -147,6 +155,7 @@ float4 queries() : SV_Position int2 dim_cube_array_lod = NagaMipDimensionsCubeArray(image_cube_array, 1); int3 dim_3d = NagaDimensions3D(image_3d); int3 dim_3d_lod = NagaMipDimensions3D(image_3d, 1); + int2 dim_2s_ms = NagaMSDimensions2D(image_aa); int sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); return float4(float(sum).xxxx); } @@ -229,6 +238,7 @@ float4 sample_() : SV_Target0 float4 s2d_offset = image_2d.Sample(sampler_reg, tc, int2(3, 1)); float4 s2d_level = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284); float4 s2d_level_offset = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284, int2(3, 1)); + float4 s2d_bias_offset = image_2d.SampleBias(sampler_reg, tc, 2.0, int2(3, 1)); return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); } @@ -237,6 +247,7 @@ float sample_comparison() : SV_Target0 float2 tc_1 = float2(0.5.xx); float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc_1, 0.5); float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc_1, 0.5); + float scube_depth_level = image_cube_depth.SampleCmpLevelZero(sampler_cmp, float3(0.5.xxx), 0.5); return (s2d_depth + s2d_depth_level); } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 5bfd943e3..e3aaafa9e 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -55,6 +55,7 @@ vertex queriesOutput queries( , metal::texturecube image_cube [[user(fake0)]] , metal::texturecube_array image_cube_array [[user(fake0)]] , metal::texture3d image_3d [[user(fake0)]] +, metal::texture2d_ms image_aa [[user(fake0)]] ) { int dim_1d = int(image_1d.get_width()); int dim_1d_lod = int(image_1d.get_width()); @@ -68,6 +69,7 @@ vertex queriesOutput queries( metal::int2 dim_cube_array_lod = metal::int2(image_cube_array.get_width(1)); metal::int3 dim_3d = metal::int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()); metal::int3 dim_3d_lod = metal::int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)); + metal::int2 dim_2s_ms = metal::int2(image_aa.get_width(), image_aa.get_height()); int sum = (((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z; return queriesOutput { metal::float4(static_cast(sum)) }; } @@ -111,6 +113,7 @@ fragment sampleOutput sample( metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type_9_); metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_9_); + metal::float4 s2d_bias_offset = image_2d.sample(sampler_reg, tc, metal::bias(2.0), const_type_9_); return sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset }; } @@ -121,10 +124,12 @@ struct sample_comparisonOutput { fragment sample_comparisonOutput sample_comparison( metal::sampler sampler_cmp [[user(fake0)]] , metal::depth2d image_2d_depth [[user(fake0)]] +, metal::depthcube image_cube_depth [[user(fake0)]] ) { metal::float2 tc_1 = metal::float2(0.5); float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); + float scube_depth_level = image_cube_depth.sample_compare(sampler_cmp, metal::float3(0.5), 0.5); return sample_comparisonOutput { s2d_depth + s2d_depth_level }; } diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 3063cfb4e..f44df535b 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 292 +; Bound: 306 OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D @@ -9,96 +9,99 @@ OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %72 "main" %69 -OpEntryPoint GLCompute %117 "depth_load" %115 -OpEntryPoint Vertex %138 "queries" %136 -OpEntryPoint Vertex %188 "levels_queries" %187 -OpEntryPoint Fragment %217 "sample" %216 -OpEntryPoint Fragment %244 "sample_comparison" %242 -OpEntryPoint Fragment %258 "gather" %257 -OpEntryPoint Fragment %280 "depth_no_comparison" %279 -OpExecutionMode %72 LocalSize 16 1 1 -OpExecutionMode %117 LocalSize 16 1 1 -OpExecutionMode %217 OriginUpperLeft -OpExecutionMode %244 OriginUpperLeft -OpExecutionMode %258 OriginUpperLeft -OpExecutionMode %280 OriginUpperLeft +OpEntryPoint GLCompute %76 "main" %73 +OpEntryPoint GLCompute %121 "depth_load" %119 +OpEntryPoint Vertex %142 "queries" %140 +OpEntryPoint Vertex %194 "levels_queries" %193 +OpEntryPoint Fragment %223 "sample" %222 +OpEntryPoint Fragment %252 "sample_comparison" %250 +OpEntryPoint Fragment %272 "gather" %271 +OpEntryPoint Fragment %294 "depth_no_comparison" %293 +OpExecutionMode %76 LocalSize 16 1 1 +OpExecutionMode %121 LocalSize 16 1 1 +OpExecutionMode %223 OriginUpperLeft +OpExecutionMode %252 OriginUpperLeft +OpExecutionMode %272 OriginUpperLeft +OpExecutionMode %294 OriginUpperLeft OpSource GLSL 450 -OpName %32 "image_mipmapped_src" -OpName %34 "image_multisampled_src" -OpName %36 "image_depth_multisampled_src" -OpName %38 "image_storage_src" -OpName %40 "image_array_src" -OpName %42 "image_dup_src" -OpName %44 "image_1d_src" -OpName %46 "image_dst" -OpName %48 "image_1d" -OpName %50 "image_2d" -OpName %52 "image_2d_array" -OpName %54 "image_cube" -OpName %56 "image_cube_array" -OpName %58 "image_3d" -OpName %60 "image_aa" -OpName %62 "sampler_reg" -OpName %64 "sampler_cmp" -OpName %66 "image_2d_depth" -OpName %69 "local_id" -OpName %72 "main" -OpName %115 "local_id" -OpName %117 "depth_load" -OpName %138 "queries" -OpName %188 "levels_queries" -OpName %217 "sample" -OpName %244 "sample_comparison" -OpName %258 "gather" -OpName %280 "depth_no_comparison" -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 0 +OpName %34 "image_mipmapped_src" +OpName %36 "image_multisampled_src" +OpName %38 "image_depth_multisampled_src" +OpName %40 "image_storage_src" +OpName %42 "image_array_src" +OpName %44 "image_dup_src" +OpName %46 "image_1d_src" +OpName %48 "image_dst" +OpName %50 "image_1d" +OpName %52 "image_2d" +OpName %54 "image_2d_array" +OpName %56 "image_cube" +OpName %58 "image_cube_array" +OpName %60 "image_3d" +OpName %62 "image_aa" +OpName %64 "sampler_reg" +OpName %66 "sampler_cmp" +OpName %68 "image_2d_depth" +OpName %70 "image_cube_depth" +OpName %73 "local_id" +OpName %76 "main" +OpName %119 "local_id" +OpName %121 "depth_load" +OpName %142 "queries" +OpName %194 "levels_queries" +OpName %223 "sample" +OpName %252 "sample_comparison" +OpName %272 "gather" +OpName %294 "depth_no_comparison" OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 3 +OpDecorate %34 Binding 0 OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 4 -OpDecorate %38 NonWritable +OpDecorate %36 Binding 3 OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 1 +OpDecorate %38 Binding 4 +OpDecorate %40 NonWritable OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 5 -OpDecorate %42 NonWritable +OpDecorate %40 Binding 1 OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 6 +OpDecorate %42 Binding 5 +OpDecorate %44 NonWritable OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 7 -OpDecorate %46 NonReadable +OpDecorate %44 Binding 6 OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 2 +OpDecorate %46 Binding 7 +OpDecorate %48 NonReadable OpDecorate %48 DescriptorSet 0 -OpDecorate %48 Binding 0 +OpDecorate %48 Binding 2 OpDecorate %50 DescriptorSet 0 -OpDecorate %50 Binding 1 +OpDecorate %50 Binding 0 OpDecorate %52 DescriptorSet 0 -OpDecorate %52 Binding 2 +OpDecorate %52 Binding 1 OpDecorate %54 DescriptorSet 0 -OpDecorate %54 Binding 3 +OpDecorate %54 Binding 2 OpDecorate %56 DescriptorSet 0 -OpDecorate %56 Binding 4 +OpDecorate %56 Binding 3 OpDecorate %58 DescriptorSet 0 -OpDecorate %58 Binding 5 +OpDecorate %58 Binding 4 OpDecorate %60 DescriptorSet 0 -OpDecorate %60 Binding 6 -OpDecorate %62 DescriptorSet 1 -OpDecorate %62 Binding 0 +OpDecorate %60 Binding 5 +OpDecorate %62 DescriptorSet 0 +OpDecorate %62 Binding 6 OpDecorate %64 DescriptorSet 1 -OpDecorate %64 Binding 1 +OpDecorate %64 Binding 0 OpDecorate %66 DescriptorSet 1 -OpDecorate %66 Binding 2 -OpDecorate %69 BuiltIn LocalInvocationId -OpDecorate %115 BuiltIn LocalInvocationId -OpDecorate %136 BuiltIn Position -OpDecorate %187 BuiltIn Position -OpDecorate %216 Location 0 -OpDecorate %242 Location 0 -OpDecorate %257 Location 0 -OpDecorate %279 Location 0 +OpDecorate %66 Binding 1 +OpDecorate %68 DescriptorSet 1 +OpDecorate %68 Binding 2 +OpDecorate %70 DescriptorSet 1 +OpDecorate %70 Binding 3 +OpDecorate %73 BuiltIn LocalInvocationId +OpDecorate %119 BuiltIn LocalInvocationId +OpDecorate %140 BuiltIn Position +OpDecorate %193 BuiltIn Position +OpDecorate %222 Location 0 +OpDecorate %250 Location 0 +OpDecorate %271 Location 0 +OpDecorate %293 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -108,30 +111,30 @@ OpDecorate %279 Location 0 %7 = OpConstant %8 0.5 %9 = OpConstant %8 2.3 %10 = OpConstant %4 3 -%12 = OpTypeInt 32 0 -%11 = OpTypeImage %12 2D 0 0 0 1 Unknown -%13 = OpTypeImage %12 2D 0 0 1 1 Unknown -%14 = OpTypeImage %8 2D 1 0 1 1 Unknown -%15 = OpTypeImage %12 2D 0 0 0 2 Rgba8ui -%16 = OpTypeImage %12 2D 0 1 0 1 Unknown -%17 = OpTypeImage %12 1D 0 0 0 2 R32ui -%18 = OpTypeImage %12 1D 0 0 0 1 Unknown -%19 = OpTypeVector %12 3 -%20 = OpTypeVector %4 2 -%21 = OpTypeImage %8 1D 0 0 0 1 Unknown -%22 = OpTypeImage %8 2D 0 0 0 1 Unknown -%23 = OpTypeImage %8 2D 0 1 0 1 Unknown -%24 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%25 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%26 = OpTypeImage %8 3D 0 0 0 1 Unknown -%27 = OpTypeImage %8 2D 0 0 1 1 Unknown -%28 = OpTypeVector %8 4 -%29 = OpTypeSampler -%30 = OpTypeImage %8 2D 1 0 0 1 Unknown -%31 = OpConstantComposite %20 %10 %6 -%33 = OpTypePointer UniformConstant %11 -%32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %13 +%11 = OpConstant %8 2.0 +%13 = OpTypeInt 32 0 +%12 = OpTypeImage %13 2D 0 0 0 1 Unknown +%14 = OpTypeImage %13 2D 0 0 1 1 Unknown +%15 = OpTypeImage %8 2D 1 0 1 1 Unknown +%16 = OpTypeImage %13 2D 0 0 0 2 Rgba8ui +%17 = OpTypeImage %13 2D 0 1 0 1 Unknown +%18 = OpTypeImage %13 1D 0 0 0 2 R32ui +%19 = OpTypeImage %13 1D 0 0 0 1 Unknown +%20 = OpTypeVector %13 3 +%21 = OpTypeVector %4 2 +%22 = OpTypeImage %8 1D 0 0 0 1 Unknown +%23 = OpTypeImage %8 2D 0 0 0 1 Unknown +%24 = OpTypeImage %8 2D 0 1 0 1 Unknown +%25 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%26 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%27 = OpTypeImage %8 3D 0 0 0 1 Unknown +%28 = OpTypeImage %8 2D 0 0 1 1 Unknown +%29 = OpTypeVector %8 4 +%30 = OpTypeSampler +%31 = OpTypeImage %8 2D 1 0 0 1 Unknown +%32 = OpTypeImage %8 Cube 1 0 0 1 Unknown +%33 = OpConstantComposite %21 %10 %6 +%35 = OpTypePointer UniformConstant %12 %34 = OpVariable %35 UniformConstant %37 = OpTypePointer UniformConstant %14 %36 = OpVariable %37 UniformConstant @@ -143,9 +146,9 @@ OpDecorate %279 Location 0 %42 = OpVariable %43 UniformConstant %45 = OpTypePointer UniformConstant %18 %44 = OpVariable %45 UniformConstant -%47 = OpTypePointer UniformConstant %17 +%47 = OpTypePointer UniformConstant %19 %46 = OpVariable %47 UniformConstant -%49 = OpTypePointer UniformConstant %21 +%49 = OpTypePointer UniformConstant %18 %48 = OpVariable %49 UniformConstant %51 = OpTypePointer UniformConstant %22 %50 = OpVariable %51 UniformConstant @@ -159,265 +162,279 @@ OpDecorate %279 Location 0 %58 = OpVariable %59 UniformConstant %61 = OpTypePointer UniformConstant %27 %60 = OpVariable %61 UniformConstant -%63 = OpTypePointer UniformConstant %29 +%63 = OpTypePointer UniformConstant %28 %62 = OpVariable %63 UniformConstant -%65 = OpTypePointer UniformConstant %29 +%65 = OpTypePointer UniformConstant %30 %64 = OpVariable %65 UniformConstant %67 = OpTypePointer UniformConstant %30 %66 = OpVariable %67 UniformConstant -%70 = OpTypePointer Input %19 -%69 = OpVariable %70 Input -%73 = OpTypeFunction %2 -%82 = OpTypeVector %12 2 -%90 = OpTypeVector %12 4 -%101 = OpTypeVector %4 3 -%115 = OpVariable %70 Input -%137 = OpTypePointer Output %28 -%136 = OpVariable %137 Output -%146 = OpConstant %12 0 -%187 = OpVariable %137 Output -%216 = OpVariable %137 Output -%222 = OpTypeVector %8 2 -%225 = OpTypeSampledImage %21 -%228 = OpTypeSampledImage %22 -%243 = OpTypePointer Output %8 -%242 = OpVariable %243 Output -%249 = OpTypeSampledImage %30 -%254 = OpConstant %8 0.0 -%257 = OpVariable %137 Output -%267 = OpConstant %12 1 -%270 = OpConstant %12 3 -%279 = OpVariable %137 Output -%72 = OpFunction %2 None %73 -%68 = OpLabel -%71 = OpLoad %19 %69 -%74 = OpLoad %11 %32 -%75 = OpLoad %13 %34 -%76 = OpLoad %15 %38 -%77 = OpLoad %16 %40 -%78 = OpLoad %18 %44 -%79 = OpLoad %17 %46 -OpBranch %80 -%80 = OpLabel -%81 = OpImageQuerySize %20 %76 -%83 = OpVectorShuffle %82 %71 %71 0 1 -%84 = OpBitcast %20 %83 -%85 = OpIMul %20 %81 %84 -%86 = OpCompositeConstruct %20 %3 %5 -%87 = OpSMod %20 %85 %86 -%88 = OpCompositeExtract %12 %71 2 -%89 = OpBitcast %4 %88 -%91 = OpImageFetch %90 %74 %87 Lod %89 -%92 = OpCompositeExtract %12 %71 2 +%69 = OpTypePointer UniformConstant %31 +%68 = OpVariable %69 UniformConstant +%71 = OpTypePointer UniformConstant %32 +%70 = OpVariable %71 UniformConstant +%74 = OpTypePointer Input %20 +%73 = OpVariable %74 Input +%77 = OpTypeFunction %2 +%86 = OpTypeVector %13 2 +%94 = OpTypeVector %13 4 +%105 = OpTypeVector %4 3 +%119 = OpVariable %74 Input +%141 = OpTypePointer Output %29 +%140 = OpVariable %141 Output +%151 = OpConstant %13 0 +%193 = OpVariable %141 Output +%222 = OpVariable %141 Output +%228 = OpTypeVector %8 2 +%231 = OpTypeSampledImage %22 +%234 = OpTypeSampledImage %23 +%251 = OpTypePointer Output %8 +%250 = OpVariable %251 Output +%258 = OpTypeSampledImage %31 +%263 = OpConstant %8 0.0 +%264 = OpTypeVector %8 3 +%266 = OpTypeSampledImage %32 +%271 = OpVariable %141 Output +%281 = OpConstant %13 1 +%284 = OpConstant %13 3 +%293 = OpVariable %141 Output +%76 = OpFunction %2 None %77 +%72 = OpLabel +%75 = OpLoad %20 %73 +%78 = OpLoad %12 %34 +%79 = OpLoad %14 %36 +%80 = OpLoad %16 %40 +%81 = OpLoad %17 %42 +%82 = OpLoad %19 %46 +%83 = OpLoad %18 %48 +OpBranch %84 +%84 = OpLabel +%85 = OpImageQuerySize %21 %80 +%87 = OpVectorShuffle %86 %75 %75 0 1 +%88 = OpBitcast %21 %87 +%89 = OpIMul %21 %85 %88 +%90 = OpCompositeConstruct %21 %3 %5 +%91 = OpSMod %21 %89 %90 +%92 = OpCompositeExtract %13 %75 2 %93 = OpBitcast %4 %92 -%94 = OpImageFetch %90 %75 %87 Sample %93 -%95 = OpImageRead %90 %76 %87 -%96 = OpCompositeExtract %12 %71 2 +%95 = OpImageFetch %94 %78 %91 Lod %93 +%96 = OpCompositeExtract %13 %75 2 %97 = OpBitcast %4 %96 -%98 = OpCompositeExtract %12 %71 2 -%99 = OpBitcast %4 %98 -%100 = OpIAdd %4 %99 %6 -%102 = OpCompositeConstruct %101 %87 %97 -%103 = OpImageFetch %90 %77 %102 Lod %100 -%104 = OpCompositeExtract %12 %71 0 -%105 = OpBitcast %4 %104 -%106 = OpCompositeExtract %12 %71 2 -%107 = OpBitcast %4 %106 -%108 = OpImageFetch %90 %78 %105 Lod %107 -%109 = OpCompositeExtract %4 %87 0 -%110 = OpIAdd %90 %91 %94 -%111 = OpIAdd %90 %110 %95 -%112 = OpIAdd %90 %111 %103 -%113 = OpIAdd %90 %112 %108 -OpImageWrite %79 %109 %113 +%98 = OpImageFetch %94 %79 %91 Sample %97 +%99 = OpImageRead %94 %80 %91 +%100 = OpCompositeExtract %13 %75 2 +%101 = OpBitcast %4 %100 +%102 = OpCompositeExtract %13 %75 2 +%103 = OpBitcast %4 %102 +%104 = OpIAdd %4 %103 %6 +%106 = OpCompositeConstruct %105 %91 %101 +%107 = OpImageFetch %94 %81 %106 Lod %104 +%108 = OpCompositeExtract %13 %75 0 +%109 = OpBitcast %4 %108 +%110 = OpCompositeExtract %13 %75 2 +%111 = OpBitcast %4 %110 +%112 = OpImageFetch %94 %82 %109 Lod %111 +%113 = OpCompositeExtract %4 %91 0 +%114 = OpIAdd %94 %95 %98 +%115 = OpIAdd %94 %114 %99 +%116 = OpIAdd %94 %115 %107 +%117 = OpIAdd %94 %116 %112 +OpImageWrite %83 %113 %117 OpReturn OpFunctionEnd -%117 = OpFunction %2 None %73 -%114 = OpLabel -%116 = OpLoad %19 %115 -%118 = OpLoad %14 %36 -%119 = OpLoad %15 %38 -%120 = OpLoad %17 %46 -OpBranch %121 -%121 = OpLabel -%122 = OpImageQuerySize %20 %119 -%123 = OpVectorShuffle %82 %116 %116 0 1 -%124 = OpBitcast %20 %123 -%125 = OpIMul %20 %122 %124 -%126 = OpCompositeConstruct %20 %3 %5 -%127 = OpSMod %20 %125 %126 -%128 = OpCompositeExtract %12 %116 2 -%129 = OpBitcast %4 %128 -%130 = OpImageFetch %28 %118 %127 Sample %129 -%131 = OpCompositeExtract %8 %130 0 -%132 = OpCompositeExtract %4 %127 0 -%133 = OpConvertFToU %12 %131 -%134 = OpCompositeConstruct %90 %133 %133 %133 %133 -OpImageWrite %120 %132 %134 +%121 = OpFunction %2 None %77 +%118 = OpLabel +%120 = OpLoad %20 %119 +%122 = OpLoad %15 %38 +%123 = OpLoad %16 %40 +%124 = OpLoad %18 %48 +OpBranch %125 +%125 = OpLabel +%126 = OpImageQuerySize %21 %123 +%127 = OpVectorShuffle %86 %120 %120 0 1 +%128 = OpBitcast %21 %127 +%129 = OpIMul %21 %126 %128 +%130 = OpCompositeConstruct %21 %3 %5 +%131 = OpSMod %21 %129 %130 +%132 = OpCompositeExtract %13 %120 2 +%133 = OpBitcast %4 %132 +%134 = OpImageFetch %29 %122 %131 Sample %133 +%135 = OpCompositeExtract %8 %134 0 +%136 = OpCompositeExtract %4 %131 0 +%137 = OpConvertFToU %13 %135 +%138 = OpCompositeConstruct %94 %137 %137 %137 %137 +OpImageWrite %124 %136 %138 OpReturn OpFunctionEnd -%138 = OpFunction %2 None %73 -%135 = OpLabel -%139 = OpLoad %21 %48 -%140 = OpLoad %22 %50 -%141 = OpLoad %23 %52 -%142 = OpLoad %24 %54 -%143 = OpLoad %25 %56 -%144 = OpLoad %26 %58 -OpBranch %145 -%145 = OpLabel -%147 = OpImageQuerySizeLod %4 %139 %146 -%148 = OpBitcast %4 %147 -%149 = OpImageQuerySizeLod %4 %139 %148 -%150 = OpImageQuerySizeLod %20 %140 %146 -%151 = OpImageQuerySizeLod %20 %140 %6 -%152 = OpImageQuerySizeLod %101 %141 %146 -%153 = OpVectorShuffle %20 %152 %152 0 1 -%154 = OpImageQuerySizeLod %101 %141 %6 -%155 = OpVectorShuffle %20 %154 %154 0 1 -%156 = OpImageQuerySizeLod %20 %142 %146 -%157 = OpImageQuerySizeLod %20 %142 %6 -%158 = OpImageQuerySizeLod %101 %143 %146 -%159 = OpVectorShuffle %20 %158 %158 0 0 -%160 = OpImageQuerySizeLod %101 %143 %6 -%161 = OpVectorShuffle %20 %160 %160 0 0 -%162 = OpImageQuerySizeLod %101 %144 %146 -%163 = OpImageQuerySizeLod %101 %144 %6 -%164 = OpCompositeExtract %4 %150 1 -%165 = OpIAdd %4 %147 %164 -%166 = OpCompositeExtract %4 %151 1 -%167 = OpIAdd %4 %165 %166 -%168 = OpCompositeExtract %4 %153 1 -%169 = OpIAdd %4 %167 %168 +%142 = OpFunction %2 None %77 +%139 = OpLabel +%143 = OpLoad %22 %50 +%144 = OpLoad %23 %52 +%145 = OpLoad %24 %54 +%146 = OpLoad %25 %56 +%147 = OpLoad %26 %58 +%148 = OpLoad %27 %60 +%149 = OpLoad %28 %62 +OpBranch %150 +%150 = OpLabel +%152 = OpImageQuerySizeLod %4 %143 %151 +%153 = OpBitcast %4 %152 +%154 = OpImageQuerySizeLod %4 %143 %153 +%155 = OpImageQuerySizeLod %21 %144 %151 +%156 = OpImageQuerySizeLod %21 %144 %6 +%157 = OpImageQuerySizeLod %105 %145 %151 +%158 = OpVectorShuffle %21 %157 %157 0 1 +%159 = OpImageQuerySizeLod %105 %145 %6 +%160 = OpVectorShuffle %21 %159 %159 0 1 +%161 = OpImageQuerySizeLod %21 %146 %151 +%162 = OpImageQuerySizeLod %21 %146 %6 +%163 = OpImageQuerySizeLod %105 %147 %151 +%164 = OpVectorShuffle %21 %163 %163 0 0 +%165 = OpImageQuerySizeLod %105 %147 %6 +%166 = OpVectorShuffle %21 %165 %165 0 0 +%167 = OpImageQuerySizeLod %105 %148 %151 +%168 = OpImageQuerySizeLod %105 %148 %6 +%169 = OpImageQuerySize %21 %149 %170 = OpCompositeExtract %4 %155 1 -%171 = OpIAdd %4 %169 %170 +%171 = OpIAdd %4 %152 %170 %172 = OpCompositeExtract %4 %156 1 %173 = OpIAdd %4 %171 %172 -%174 = OpCompositeExtract %4 %157 1 +%174 = OpCompositeExtract %4 %158 1 %175 = OpIAdd %4 %173 %174 -%176 = OpCompositeExtract %4 %159 1 +%176 = OpCompositeExtract %4 %160 1 %177 = OpIAdd %4 %175 %176 %178 = OpCompositeExtract %4 %161 1 %179 = OpIAdd %4 %177 %178 -%180 = OpCompositeExtract %4 %162 2 +%180 = OpCompositeExtract %4 %162 1 %181 = OpIAdd %4 %179 %180 -%182 = OpCompositeExtract %4 %163 2 +%182 = OpCompositeExtract %4 %164 1 %183 = OpIAdd %4 %181 %182 -%184 = OpConvertSToF %8 %183 -%185 = OpCompositeConstruct %28 %184 %184 %184 %184 -OpStore %136 %185 +%184 = OpCompositeExtract %4 %166 1 +%185 = OpIAdd %4 %183 %184 +%186 = OpCompositeExtract %4 %167 2 +%187 = OpIAdd %4 %185 %186 +%188 = OpCompositeExtract %4 %168 2 +%189 = OpIAdd %4 %187 %188 +%190 = OpConvertSToF %8 %189 +%191 = OpCompositeConstruct %29 %190 %190 %190 %190 +OpStore %140 %191 OpReturn OpFunctionEnd -%188 = OpFunction %2 None %73 -%186 = OpLabel -%189 = OpLoad %22 %50 -%190 = OpLoad %23 %52 -%191 = OpLoad %24 %54 -%192 = OpLoad %25 %56 -%193 = OpLoad %26 %58 -%194 = OpLoad %27 %60 -OpBranch %195 -%195 = OpLabel -%196 = OpImageQueryLevels %4 %189 -%197 = OpImageQueryLevels %4 %190 -%198 = OpImageQuerySizeLod %101 %190 %146 -%199 = OpCompositeExtract %4 %198 2 -%200 = OpImageQueryLevels %4 %191 -%201 = OpImageQueryLevels %4 %192 -%202 = OpImageQuerySizeLod %101 %192 %146 -%203 = OpCompositeExtract %4 %202 2 -%204 = OpImageQueryLevels %4 %193 -%205 = OpImageQuerySamples %4 %194 -%206 = OpIAdd %4 %199 %203 -%207 = OpIAdd %4 %206 %205 -%208 = OpIAdd %4 %207 %196 -%209 = OpIAdd %4 %208 %197 -%210 = OpIAdd %4 %209 %204 -%211 = OpIAdd %4 %210 %200 -%212 = OpIAdd %4 %211 %201 -%213 = OpConvertSToF %8 %212 -%214 = OpCompositeConstruct %28 %213 %213 %213 %213 -OpStore %187 %214 +%194 = OpFunction %2 None %77 +%192 = OpLabel +%195 = OpLoad %23 %52 +%196 = OpLoad %24 %54 +%197 = OpLoad %25 %56 +%198 = OpLoad %26 %58 +%199 = OpLoad %27 %60 +%200 = OpLoad %28 %62 +OpBranch %201 +%201 = OpLabel +%202 = OpImageQueryLevels %4 %195 +%203 = OpImageQueryLevels %4 %196 +%204 = OpImageQuerySizeLod %105 %196 %151 +%205 = OpCompositeExtract %4 %204 2 +%206 = OpImageQueryLevels %4 %197 +%207 = OpImageQueryLevels %4 %198 +%208 = OpImageQuerySizeLod %105 %198 %151 +%209 = OpCompositeExtract %4 %208 2 +%210 = OpImageQueryLevels %4 %199 +%211 = OpImageQuerySamples %4 %200 +%212 = OpIAdd %4 %205 %209 +%213 = OpIAdd %4 %212 %211 +%214 = OpIAdd %4 %213 %202 +%215 = OpIAdd %4 %214 %203 +%216 = OpIAdd %4 %215 %210 +%217 = OpIAdd %4 %216 %206 +%218 = OpIAdd %4 %217 %207 +%219 = OpConvertSToF %8 %218 +%220 = OpCompositeConstruct %29 %219 %219 %219 %219 +OpStore %193 %220 OpReturn OpFunctionEnd -%217 = OpFunction %2 None %73 -%215 = OpLabel -%218 = OpLoad %21 %48 -%219 = OpLoad %22 %50 -%220 = OpLoad %29 %62 -OpBranch %221 +%223 = OpFunction %2 None %77 %221 = OpLabel -%223 = OpCompositeConstruct %222 %7 %7 -%224 = OpCompositeExtract %8 %223 0 -%226 = OpSampledImage %225 %218 %220 -%227 = OpImageSampleImplicitLod %28 %226 %224 -%229 = OpSampledImage %228 %219 %220 -%230 = OpImageSampleImplicitLod %28 %229 %223 -%231 = OpSampledImage %228 %219 %220 -%232 = OpImageSampleImplicitLod %28 %231 %223 ConstOffset %31 -%233 = OpSampledImage %228 %219 %220 -%234 = OpImageSampleExplicitLod %28 %233 %223 Lod %9 -%235 = OpSampledImage %228 %219 %220 -%236 = OpImageSampleExplicitLod %28 %235 %223 Lod|ConstOffset %9 %31 -%237 = OpFAdd %28 %227 %230 -%238 = OpFAdd %28 %237 %232 -%239 = OpFAdd %28 %238 %234 -%240 = OpFAdd %28 %239 %236 -OpStore %216 %240 +%224 = OpLoad %22 %50 +%225 = OpLoad %23 %52 +%226 = OpLoad %30 %64 +OpBranch %227 +%227 = OpLabel +%229 = OpCompositeConstruct %228 %7 %7 +%230 = OpCompositeExtract %8 %229 0 +%232 = OpSampledImage %231 %224 %226 +%233 = OpImageSampleImplicitLod %29 %232 %230 +%235 = OpSampledImage %234 %225 %226 +%236 = OpImageSampleImplicitLod %29 %235 %229 +%237 = OpSampledImage %234 %225 %226 +%238 = OpImageSampleImplicitLod %29 %237 %229 ConstOffset %33 +%239 = OpSampledImage %234 %225 %226 +%240 = OpImageSampleExplicitLod %29 %239 %229 Lod %9 +%241 = OpSampledImage %234 %225 %226 +%242 = OpImageSampleExplicitLod %29 %241 %229 Lod|ConstOffset %9 %33 +%243 = OpSampledImage %234 %225 %226 +%244 = OpImageSampleImplicitLod %29 %243 %229 Bias|ConstOffset %11 %33 +%245 = OpFAdd %29 %233 %236 +%246 = OpFAdd %29 %245 %238 +%247 = OpFAdd %29 %246 %240 +%248 = OpFAdd %29 %247 %242 +OpStore %222 %248 OpReturn OpFunctionEnd -%244 = OpFunction %2 None %73 -%241 = OpLabel -%245 = OpLoad %29 %64 -%246 = OpLoad %30 %66 -OpBranch %247 -%247 = OpLabel -%248 = OpCompositeConstruct %222 %7 %7 -%250 = OpSampledImage %249 %246 %245 -%251 = OpImageSampleDrefImplicitLod %8 %250 %248 %7 -%252 = OpSampledImage %249 %246 %245 -%253 = OpImageSampleDrefExplicitLod %8 %252 %248 %7 Lod %254 -%255 = OpFAdd %8 %251 %253 -OpStore %242 %255 -OpReturn -OpFunctionEnd -%258 = OpFunction %2 None %73 +%252 = OpFunction %2 None %77 +%249 = OpLabel +%253 = OpLoad %30 %66 +%254 = OpLoad %31 %68 +%255 = OpLoad %32 %70 +OpBranch %256 %256 = OpLabel -%259 = OpLoad %22 %50 -%260 = OpLoad %29 %62 -%261 = OpLoad %29 %64 -%262 = OpLoad %30 %66 -OpBranch %263 -%263 = OpLabel -%264 = OpCompositeConstruct %222 %7 %7 -%265 = OpSampledImage %228 %259 %260 -%266 = OpImageGather %28 %265 %264 %267 -%268 = OpSampledImage %228 %259 %260 -%269 = OpImageGather %28 %268 %264 %270 ConstOffset %31 -%271 = OpSampledImage %249 %262 %261 -%272 = OpImageDrefGather %28 %271 %264 %7 -%273 = OpSampledImage %249 %262 %261 -%274 = OpImageDrefGather %28 %273 %264 %7 ConstOffset %31 -%275 = OpFAdd %28 %266 %269 -%276 = OpFAdd %28 %275 %272 -%277 = OpFAdd %28 %276 %274 -OpStore %257 %277 +%257 = OpCompositeConstruct %228 %7 %7 +%259 = OpSampledImage %258 %254 %253 +%260 = OpImageSampleDrefImplicitLod %8 %259 %257 %7 +%261 = OpSampledImage %258 %254 %253 +%262 = OpImageSampleDrefExplicitLod %8 %261 %257 %7 Lod %263 +%265 = OpCompositeConstruct %264 %7 %7 %7 +%267 = OpSampledImage %266 %255 %253 +%268 = OpImageSampleDrefExplicitLod %8 %267 %265 %7 Lod %263 +%269 = OpFAdd %8 %260 %262 +OpStore %250 %269 OpReturn OpFunctionEnd -%280 = OpFunction %2 None %73 -%278 = OpLabel -%281 = OpLoad %29 %62 -%282 = OpLoad %30 %66 -OpBranch %283 -%283 = OpLabel -%284 = OpCompositeConstruct %222 %7 %7 -%285 = OpSampledImage %249 %282 %281 -%286 = OpImageSampleImplicitLod %28 %285 %284 -%287 = OpCompositeExtract %8 %286 0 -%288 = OpSampledImage %249 %282 %281 -%289 = OpImageGather %28 %288 %284 %146 -%290 = OpCompositeConstruct %28 %287 %287 %287 %287 -%291 = OpFAdd %28 %290 %289 -OpStore %279 %291 +%272 = OpFunction %2 None %77 +%270 = OpLabel +%273 = OpLoad %23 %52 +%274 = OpLoad %30 %64 +%275 = OpLoad %30 %66 +%276 = OpLoad %31 %68 +OpBranch %277 +%277 = OpLabel +%278 = OpCompositeConstruct %228 %7 %7 +%279 = OpSampledImage %234 %273 %274 +%280 = OpImageGather %29 %279 %278 %281 +%282 = OpSampledImage %234 %273 %274 +%283 = OpImageGather %29 %282 %278 %284 ConstOffset %33 +%285 = OpSampledImage %258 %276 %275 +%286 = OpImageDrefGather %29 %285 %278 %7 +%287 = OpSampledImage %258 %276 %275 +%288 = OpImageDrefGather %29 %287 %278 %7 ConstOffset %33 +%289 = OpFAdd %29 %280 %283 +%290 = OpFAdd %29 %289 %286 +%291 = OpFAdd %29 %290 %288 +OpStore %271 %291 +OpReturn +OpFunctionEnd +%294 = OpFunction %2 None %77 +%292 = OpLabel +%295 = OpLoad %30 %64 +%296 = OpLoad %31 %68 +OpBranch %297 +%297 = OpLabel +%298 = OpCompositeConstruct %228 %7 %7 +%299 = OpSampledImage %258 %296 %295 +%300 = OpImageSampleImplicitLod %29 %299 %298 +%301 = OpCompositeExtract %8 %300 0 +%302 = OpSampledImage %258 %296 %295 +%303 = OpImageGather %29 %302 %298 %151 +%304 = OpCompositeConstruct %29 %301 %301 %301 %301 +%305 = OpFAdd %29 %304 %303 +OpStore %293 %305 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index b2b2edffa..4db74e0eb 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -34,6 +34,8 @@ var sampler_reg: sampler; var sampler_cmp: sampler_comparison; @group(1) @binding(2) var image_2d_depth: texture_depth_2d; +@group(1) @binding(3) +var image_cube_depth: texture_depth_cube; @stage(compute) @workgroup_size(16, 1, 1) fn main(@builtin(local_invocation_id) local_id: vec3) { @@ -71,6 +73,7 @@ fn queries() -> @builtin(position) vec4 { let dim_cube_array_lod = textureDimensions(image_cube_array, 1); let dim_3d = textureDimensions(image_3d); let dim_3d_lod = textureDimensions(image_3d, 1); + let dim_2s_ms = textureDimensions(image_aa); let sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); return vec4(f32(sum)); } @@ -97,6 +100,7 @@ fn sample() -> @location(0) vec4 { let s2d_offset = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); let s2d_level = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284); let s2d_level_offset = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284, vec2(3, 1)); + let s2d_bias_offset = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); } @@ -105,6 +109,7 @@ fn sample_comparison() -> @location(0) f32 { let tc_1 = vec2(0.5); let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5); + let scube_depth_level = textureSampleCompareLevel(image_cube_depth, sampler_cmp, vec3(0.5), 0.5); return (s2d_depth + s2d_depth_level); } From 72e197fc1b8588641f352a36de95ee80e84a9302 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 26 Feb 2022 11:55:10 -0800 Subject: [PATCH 1605/2212] [wgsl-in] Use unwrap_or to placate Clippy. --- src/front/wgsl/lexer.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 99a2d4f85..70b50a995 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -9,7 +9,7 @@ fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { } fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { - let pos = input.find(|c| !what(c)).unwrap_or_else(|| input.len()); + let pos = input.find(|c| !what(c)).unwrap_or(input.len()); input.split_at(pos) } @@ -261,7 +261,7 @@ fn consume_number(input: &str) -> (Token, &str) { let pos = working_substr .find(|c| !what(c)) - .unwrap_or_else(|| working_substr.len()); + .unwrap_or(working_substr.len()); let (value, rest) = input.split_at(pos + minus_offset + hex_offset); // NOTE: This code can use string slicing, From e6c202dc70f9c78302666a8874fdc7cc263b28ce Mon Sep 17 00:00:00 2001 From: Shota Hamada <22081383+maku693@users.noreply.github.com> Date: Sun, 27 Feb 2022 16:31:04 +0900 Subject: [PATCH 1606/2212] Fix typo --- src/valid/interface.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 360dbca1b..9b3393e5e 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -16,7 +16,7 @@ pub enum GlobalVariableError { BadHandle(#[from] BadHandle), #[error("Usage isn't compatible with address space {0:?}")] InvalidUsage(crate::AddressSpace), - #[error("Type isn't compatible with with address space {0:?}")] + #[error("Type isn't compatible with address space {0:?}")] InvalidType(crate::AddressSpace), #[error("Type flags {seen:?} do not meet the required {required:?}")] MissingTypeFlags { From f24018dc362fc1b1e2f6ca80cb33ceb513695de5 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 26 Feb 2022 09:14:49 -0800 Subject: [PATCH 1607/2212] [wgsl-in] Remove unused field Token::Number::width. --- src/front/wgsl/lexer.rs | 6 ------ src/front/wgsl/mod.rs | 35 +++++-------------------------- src/front/wgsl/number_literals.rs | 15 +++++-------- 3 files changed, 10 insertions(+), 46 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 70b50a995..d3a00e011 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -286,7 +286,6 @@ fn consume_number(input: &str) -> (Token, &str) { } else { NumberType::Sint }, - width: None, }, rest, ) @@ -664,7 +663,6 @@ fn test_tokens() { Token::Number { value: "92", ty: NumberType::Sint, - width: None, }, Token::Word("No"), ], @@ -675,12 +673,10 @@ fn test_tokens() { Token::Number { value: "2", ty: NumberType::Uint, - width: None, }, Token::Number { value: "3", ty: NumberType::Sint, - width: None, }, Token::Word("o"), ], @@ -691,7 +687,6 @@ fn test_tokens() { Token::Number { value: "2.4", ty: NumberType::Float, - width: None, }, Token::Word("f44po"), ], @@ -725,7 +720,6 @@ fn test_variable_decl() { Token::Number { value: "0", ty: NumberType::Sint, - width: None, }, Token::Paren(')'), Token::Word("var"), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 164d5aa70..2271a915d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -60,11 +60,7 @@ pub enum Token<'a> { DoubleColon, Paren(char), Attribute, - Number { - value: &'a str, - ty: NumberType, - width: Option, - }, + Number { value: &'a str, ty: NumberType }, String(&'a str), Word(&'a str), Operation(char), @@ -1266,18 +1262,10 @@ impl Parser { fn get_constant_inner<'a>( word: &'a str, ty: NumberType, - width: Option, token_span: TokenSpan<'a>, ) -> Result> { let span = token_span.1; - if let Some(width) = width { - if width != 4 { - // Only 32-bit literals supported by the spec and naga for now! - return Err(Error::BadScalarWidth(span, width)); - } - } - let value = match ty { NumberType::Sint => { get_i32_literal(word, span).map(|val| crate::ScalarValue::Sint(val as i64))? @@ -1290,25 +1278,13 @@ impl Parser { } }; - Ok(crate::ConstantInner::Scalar { - value, - width: width.unwrap_or(4), - }) + Ok(crate::ConstantInner::Scalar { value, width: 4 }) } fn parse_switch_value<'a>(lexer: &mut Lexer<'a>, uint: bool) -> Result> { let token_span = lexer.next(); let word = match token_span.0 { - Token::Number { value, width, .. } => { - if let Some(width) = width { - if width != 4 { - // Only 32-bit literals supported by the spec and naga for now! - return Err(Error::BadScalarWidth(token_span.1, width)); - } - } - - value - } + Token::Number { value, .. } => value, _ => return Err(Error::Unexpected(token_span, ExpectedToken::Integer)), }; @@ -1856,7 +1832,6 @@ impl Parser { Token::Number { value, ty: NumberType::Sint, - width: None, }, span, ) = lexer.peek() @@ -2223,8 +2198,8 @@ impl Parser { let inner = match first_token_span { (Token::Word("true"), _) => crate::ConstantInner::boolean(true), (Token::Word("false"), _) => crate::ConstantInner::boolean(false), - (Token::Number { value, ty, width }, _) => { - Self::get_constant_inner(value, ty, width, first_token_span)? + (Token::Number { value, ty }, _) => { + Self::get_constant_inner(value, ty, first_token_span)? } (Token::Word(name), name_span) => { // look for an existing constant first diff --git a/src/front/wgsl/number_literals.rs b/src/front/wgsl/number_literals.rs index 9279989e9..6691ab2d0 100644 --- a/src/front/wgsl/number_literals.rs +++ b/src/front/wgsl/number_literals.rs @@ -85,10 +85,9 @@ pub(super) fn _parse_uint_literal<'a>( Token::Number { value, ty: NumberType::Uint, - width: token_width, }, span, - ) if token_width.unwrap_or(4) == width => get_u32_literal(value, span), + ) => get_u32_literal(value, span), other => Err(Error::Unexpected( other, ExpectedToken::Number { @@ -117,10 +116,9 @@ pub(super) fn parse_non_negative_sint_literal<'a>( Token::Number { value, ty: NumberType::Sint, - width: token_width, }, span, - ) if token_width.unwrap_or(4) == width => { + ) => { let i32_val = get_i32_literal(value, span.clone())?; u32::try_from(i32_val).map_err(|_| Error::NegativeInt(span)) } @@ -153,10 +151,9 @@ pub(super) fn parse_generic_non_negative_int_literal<'a>( Token::Number { value, ty: NumberType::Sint, - width: token_width, }, span, - ) if token_width.unwrap_or(4) == width => { + ) => { let i32_val = get_i32_literal(value, span.clone())?; u32::try_from(i32_val).map_err(|_| Error::NegativeInt(span)) } @@ -164,10 +161,9 @@ pub(super) fn parse_generic_non_negative_int_literal<'a>( Token::Number { value, ty: NumberType::Uint, - width: token_width, }, span, - ) if token_width.unwrap_or(4) == width => get_u32_literal(value, span), + ) => get_u32_literal(value, span), other => Err(Error::Unexpected( other, ExpectedToken::Number { @@ -194,10 +190,9 @@ pub(super) fn _parse_float_literal<'a>( Token::Number { value, ty: NumberType::Float, - width: token_width, }, span, - ) if token_width.unwrap_or(4) == width => get_f32_literal(value, span), + ) => get_f32_literal(value, span), other => Err(Error::Unexpected( other, ExpectedToken::Number { From 62f267a140a78d72937a4d15953d9be9b8bc21b6 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 26 Feb 2022 09:50:39 -0800 Subject: [PATCH 1608/2212] [wgsl-in] consume_number: Check uint_suffix flag at top of match. This makes it unnecessary to check that field in every other pattern in the match. --- src/front/wgsl/lexer.rs | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index d3a00e011..bdebb74d6 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -96,10 +96,12 @@ fn consume_number(input: &str) -> (Token, &str) { let mut what = |c| { match state { + NumberLexerState { + uint_suffix: true, .. + } => return false, // Scanning is done once we've reached a type suffix. NumberLexerState { hex, digit_state: NLDigitState::Nothing, - uint_suffix: false, .. } => match c { '0' => { @@ -121,7 +123,6 @@ fn consume_number(input: &str) -> (Token, &str) { NumberLexerState { hex, digit_state: NLDigitState::LeadingZero, - uint_suffix: false, .. } => match c { '0' => { @@ -153,7 +154,6 @@ fn consume_number(input: &str) -> (Token, &str) { NumberLexerState { hex, digit_state: NLDigitState::DigitBeforeDot, - uint_suffix: false, .. } => match c { '0'..='9' => { @@ -181,7 +181,6 @@ fn consume_number(input: &str) -> (Token, &str) { NumberLexerState { hex, digit_state: NLDigitState::OnlyDot, - uint_suffix: false, .. } => match c { '0'..='9' => { @@ -196,13 +195,11 @@ fn consume_number(input: &str) -> (Token, &str) { NumberLexerState { hex, digit_state: NLDigitState::DigitsThenDot, - uint_suffix: false, .. } | NumberLexerState { hex, digit_state: NLDigitState::DigitAfterDot, - uint_suffix: false, .. } => match c { '0'..='9' => { @@ -222,7 +219,6 @@ fn consume_number(input: &str) -> (Token, &str) { NumberLexerState { digit_state: NLDigitState::Exponent, - uint_suffix: false, .. } => match c { '0'..='9' => { @@ -236,12 +232,10 @@ fn consume_number(input: &str) -> (Token, &str) { NumberLexerState { digit_state: NLDigitState::SignAfterExponent, - uint_suffix: false, .. } | NumberLexerState { digit_state: NLDigitState::DigitAfterExponent, - uint_suffix: false, .. } => match c { '0'..='9' => { @@ -249,10 +243,6 @@ fn consume_number(input: &str) -> (Token, &str) { } _ => return false, }, - - NumberLexerState { - uint_suffix: true, .. - } => return false, // Scanning is done once we've reached a type suffix. } // No match branch has rejected this yet, so we are still in a number literal From d449d2e665b75dc32ff61ea0969473eaaaf52fe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 24 Feb 2022 17:05:49 +0000 Subject: [PATCH 1609/2212] glsl-in: Add support for texelFetchOffset --- src/front/glsl/builtins.rs | 9 +++++++-- tests/in/glsl/samplers.frag | 10 +++++----- tests/out/wgsl/samplers-frag.wgsl | 22 ++++++++++++++++++++++ 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index ea56c54f7..dedaf93dc 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -306,7 +306,8 @@ pub fn inject_builtin( f, ) } - "texelFetch" => { + "texelFetch" | "texelFetchOffset" => { + let offset = "texelFetchOffset" == name; let f = |kind, dim, arrayed, multi, _shadow| { // Cube images aren't supported if let Dim::Cube = dim { @@ -322,7 +323,7 @@ pub fn inject_builtin( let dim_value = image_dims_to_coords_size(dim); let coordinates = make_coords_arg(dim_value + arrayed as usize, Sk::Sint); - let args = vec![ + let mut args = vec![ image, coordinates, TypeInner::Scalar { @@ -331,6 +332,10 @@ pub fn inject_builtin( }, ]; + if offset { + args.push(make_coords_arg(dim_value, Sk::Sint)); + } + declaration .overloads .push(module.add_builtin(args, MacroCall::ImageLoad { multi })) diff --git a/tests/in/glsl/samplers.frag b/tests/in/glsl/samplers.frag index 1a3421600..a1a438db9 100644 --- a/tests/in/glsl/samplers.frag +++ b/tests/in/glsl/samplers.frag @@ -64,7 +64,7 @@ void testTex1D(in float coord) { c = textureProjOffset(sampler1D(tex1D, samp), vec2(coord, 6.0), 5, 2.0); c = textureProjOffset(sampler1D(tex1D, samp), vec4(coord, 0.0, 0.0, 6.0), 5, 2.0); c = texelFetch(sampler1D(tex1D, samp), int(coord), 3); - // c = texelFetchOffset(sampler1D(tex1D, samp), int(coord), 3, 5); + c = texelFetchOffset(sampler1D(tex1D, samp), int(coord), 3, 5); } #if HAS_1D_DEPTH_TEXTURES @@ -102,7 +102,7 @@ void testTex1DArray(in vec2 coord) { c = textureOffset(sampler1DArray(tex1DArray, samp), coord, 5); c = textureOffset(sampler1DArray(tex1DArray, samp), coord, 5, 2.0); c = texelFetch(sampler1DArray(tex1DArray, samp), ivec2(coord), 3); - // c = texelFetchOffset(sampler1DArray(tex1DArray, samp), ivec2(coord), 3, 5); + c = texelFetchOffset(sampler1DArray(tex1DArray, samp), ivec2(coord), 3, 5); } #if HAS_1D_DEPTH_TEXTURES @@ -147,7 +147,7 @@ void testTex2D(in vec2 coord) { c = textureProjOffset(sampler2D(tex2D, samp), vec3(coord, 6.0), ivec2(5), 2.0); c = textureProjOffset(sampler2D(tex2D, samp), vec4(coord, 0.0, 6.0), ivec2(5), 2.0); c = texelFetch(sampler2D(tex2D, samp), ivec2(coord), 3); - // c = texelFetchOffset(sampler2D(tex2D, samp), ivec2(coord), 3, ivec2(5)); + c = texelFetchOffset(sampler2D(tex2D, samp), ivec2(coord), 3, ivec2(5)); } void testTex2DShadow(vec2 coord) { @@ -183,7 +183,7 @@ void testTex2DArray(in vec3 coord) { c = textureOffset(sampler2DArray(tex2DArray, samp), coord, ivec2(5)); c = textureOffset(sampler2DArray(tex2DArray, samp), coord, ivec2(5), 2.0); c = texelFetch(sampler2DArray(tex2DArray, samp), ivec3(coord), 3); - // c = texelFetchOffset(sampler2DArray(tex2DArray, samp), ivec3(coord), 3, ivec2(5)); + c = texelFetchOffset(sampler2DArray(tex2DArray, samp), ivec3(coord), 3, ivec2(5)); } void testTex2DArrayShadow(in vec3 coord) { @@ -247,7 +247,7 @@ void testTex3D(in vec3 coord) { c = textureOffset(sampler3D(tex3D, samp), coord, ivec3(5)); c = textureOffset(sampler3D(tex3D, samp), coord, ivec3(5), 2.0); c = texelFetch(sampler3D(tex3D, samp), ivec3(coord), 3); - // c = texelFetchOffset(sampler3D(tex3D, samp), ivec3(coord), 3, ivec3(5)); + c = texelFetchOffset(sampler3D(tex3D, samp), ivec3(coord), 3, ivec3(5)); } void testTex2DMS(in vec2 coord) { diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 3e5eb5955..3b967fe7a 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -147,6 +147,10 @@ fn testTex1D(coord: f32) { let _e330 = coord_1; let _e333 = textureLoad(tex1D, i32(_e330), 3); c = _e333; + let _e334 = coord_1; + let _e338 = coord_1; + let _e342 = textureLoad(tex1D, i32(_e338), 3); + c = _e342; return; } @@ -188,6 +192,11 @@ fn testTex1DArray(coord_2: vec2) { let _e101 = vec2(_e100); let _e105 = textureLoad(tex1DArray, _e101.x, _e101.y, 3); c_1 = _e105; + let _e106 = coord_3; + let _e110 = coord_3; + let _e111 = vec2(_e110); + let _e116 = textureLoad(tex1DArray, _e111.x, _e111.y, 3); + c_1 = _e116; return; } @@ -307,6 +316,10 @@ fn testTex2D(coord_4: vec2) { let _e434 = coord_5; let _e437 = textureLoad(tex2D, vec2(_e434), 3); c_2 = _e437; + let _e438 = coord_5; + let _e443 = coord_5; + let _e448 = textureLoad(tex2D, vec2(_e443), 3); + c_2 = _e448; return; } @@ -425,6 +438,11 @@ fn testTex2DArray(coord_8: vec3) { let _e119 = vec3(_e118); let _e123 = textureLoad(tex2DArray, _e119.xy, _e119.z, 3); c_3 = _e123; + let _e124 = coord_9; + let _e129 = coord_9; + let _e130 = vec3(_e129); + let _e136 = textureLoad(tex2DArray, _e130.xy, _e130.z, 3); + c_3 = _e136; return; } @@ -619,6 +637,10 @@ fn testTex3D(coord_20: vec3) { let _e266 = coord_21; let _e269 = textureLoad(tex3D, vec3(_e266), 3); c_6 = _e269; + let _e270 = coord_21; + let _e275 = coord_21; + let _e280 = textureLoad(tex3D, vec3(_e275), 3); + c_6 = _e280; return; } From 7f485d262b90987d6ae51e1e1cc3e304bd12dec6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 2 Mar 2022 17:25:57 +0000 Subject: [PATCH 1610/2212] glsl-in: Fix matrix comparisons --- src/front/glsl/context.rs | 108 ++++++++++++++++++++++++++- tests/in/glsl/expressions.frag | 10 +++ tests/out/wgsl/expressions-frag.wgsl | 28 ++++++- 3 files changed, 143 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 6df233aa9..ce00a3b18 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -579,8 +579,112 @@ impl Context { let right_inner = self.typifier.get(right, &parser.module.types); match (left_inner, right_inner) { - (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) - | (&TypeInner::Matrix { .. }, &TypeInner::Matrix { .. }) => match op { + ( + &TypeInner::Matrix { + columns: left_columns, + rows: left_rows, + .. + }, + &TypeInner::Matrix { + columns: right_columns, + rows: right_rows, + .. + }, + ) => { + // Check that the two arguments have the same dimensions + if left_columns != right_columns || left_rows != right_rows { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + format!( + "Cannot apply operation to {:?} and {:?}", + left_inner, right_inner + ) + .into(), + ), + meta, + }) + } + + match op { + BinaryOperator::Equal | BinaryOperator::NotEqual => { + // Naga IR doesn't support matrix comparisons so we need to + // compare the columns individually and then fold them together + // + // The folding is done using a logical and for equality and + // a logical or for inequality + let equals = op == BinaryOperator::Equal; + + let (op, combine, fun) = match equals { + true => ( + BinaryOperator::Equal, + BinaryOperator::LogicalAnd, + RelationalFunction::All, + ), + false => ( + BinaryOperator::NotEqual, + BinaryOperator::LogicalOr, + RelationalFunction::Any, + ), + }; + + let mut root = None; + + for index in 0..left_columns as u32 { + // Get the column vectors + let left_vector = self.add_expression( + Expression::AccessIndex { base: left, index }, + meta, + body, + ); + let right_vector = self.add_expression( + Expression::AccessIndex { base: right, index }, + meta, + body, + ); + + let argument = self.expressions.append( + Expression::Binary { + op, + left: left_vector, + right: right_vector, + }, + meta, + ); + + // The result of comparing two vectors is a boolean vector + // so use a relational function like all to get a single + // boolean value + let compare = self.add_expression( + Expression::Relational { fun, argument }, + meta, + body, + ); + + // Fold the result + root = Some(match root { + Some(right) => self.add_expression( + Expression::Binary { + op: combine, + left: compare, + right, + }, + meta, + body, + ), + None => compare, + }); + } + + root.unwrap() + } + _ => self.add_expression( + Expression::Binary { left, op, right }, + meta, + body, + ), + } + } + (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) => match op { BinaryOperator::Equal | BinaryOperator::NotEqual => { let equals = op == BinaryOperator::Equal; diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index f1a959f47..37e9fe78c 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -62,6 +62,16 @@ void testBinOpUintUVec(uint a, uvec4 b) { v = a ^ b; } +void testBinOpMatMat(mat3 a, mat3 b) { + mat3 v; + bool c; + v = a * b; + v = a + b; + v = a - b; + c = a == b; + c = a != b; +} + void testStructConstructor() { struct BST { int data; diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 0b3f7ad46..e9c5fdb16 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -179,6 +179,32 @@ fn testBinOpUintUVec(a_10: u32, b_10: vec4) { return; } +fn testBinOpMatMat(a_12: mat3x3, b_12: mat3x3) { + var a_13: mat3x3; + var b_13: mat3x3; + var v_6: mat3x3; + var c: bool; + + a_13 = a_12; + b_13 = b_12; + let _e6 = a_13; + let _e7 = b_13; + v_6 = (_e6 * _e7); + let _e9 = a_13; + let _e10 = b_13; + v_6 = (_e9 + _e10); + let _e12 = a_13; + let _e13 = b_13; + v_6 = (_e12 - _e13); + let _e15 = a_13; + let _e16 = b_13; + c = (all((_e15[2] == _e16[2])) && (all((_e15[1] == _e16[1])) && all((_e15[0] == _e16[0])))); + let _e31 = a_13; + let _e32 = b_13; + c = (any((_e31[2] != _e32[2])) || (any((_e31[1] != _e32[1])) || any((_e31[0] != _e32[0])))); + return; +} + fn testStructConstructor() { var tree: BST = BST(1); @@ -194,7 +220,7 @@ fn testArrayConstructor() { } -fn privatePointer(a_12: ptr) { +fn privatePointer(a_14: ptr) { return; } From 48320db507bd9362aa9009dabfb3bbe01f4cfa26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 2 Mar 2022 21:43:41 +0000 Subject: [PATCH 1611/2212] glsl-in: Fix matrix by matrix division --- src/front/glsl/context.rs | 59 ++++++++++++++++++++++++++-- tests/in/glsl/expressions.frag | 1 + tests/out/wgsl/expressions-frag.wgsl | 29 ++++++++------ 3 files changed, 73 insertions(+), 16 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index ce00a3b18..ed6b2bc5d 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -583,16 +583,19 @@ impl Context { &TypeInner::Matrix { columns: left_columns, rows: left_rows, - .. + width: left_width, }, &TypeInner::Matrix { columns: right_columns, rows: right_rows, - .. + width: right_width, }, ) => { // Check that the two arguments have the same dimensions - if left_columns != right_columns || left_rows != right_rows { + if left_columns != right_columns + || left_rows != right_rows + || left_width != right_width + { parser.errors.push(Error { kind: ErrorKind::SemanticError( format!( @@ -606,6 +609,56 @@ impl Context { } match op { + BinaryOperator::Divide => { + // Naga IR doesn't support matrix division so we need to + // divide the columns individually and reassemble the matrix + let mut components = Vec::with_capacity(left_columns as usize); + + for index in 0..left_columns as u32 { + // Get the column vectors + let left_vector = self.add_expression( + Expression::AccessIndex { base: left, index }, + meta, + body, + ); + let right_vector = self.add_expression( + Expression::AccessIndex { base: right, index }, + meta, + body, + ); + + // Divide the vectors + let column = self.expressions.append( + Expression::Binary { + op, + left: left_vector, + right: right_vector, + }, + meta, + ); + + components.push(column) + } + + // Rebuild the matrix from the divided vectors + self.expressions.append( + Expression::Compose { + ty: parser.module.types.insert( + Type { + name: None, + inner: TypeInner::Matrix { + columns: left_columns, + rows: left_rows, + width: left_width, + }, + }, + Span::default(), + ), + components, + }, + meta, + ) + } BinaryOperator::Equal | BinaryOperator::NotEqual => { // Naga IR doesn't support matrix comparisons so we need to // compare the columns individually and then fold them together diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 37e9fe78c..29fb29009 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -65,6 +65,7 @@ void testBinOpUintUVec(uint a, uvec4 b) { void testBinOpMatMat(mat3 a, mat3 b) { mat3 v; bool c; + v = a / b; v = a * b; v = a + b; v = a - b; diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index e9c5fdb16..e7a77ff74 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -189,19 +189,22 @@ fn testBinOpMatMat(a_12: mat3x3, b_12: mat3x3) { b_13 = b_12; let _e6 = a_13; let _e7 = b_13; - v_6 = (_e6 * _e7); - let _e9 = a_13; - let _e10 = b_13; - v_6 = (_e9 + _e10); - let _e12 = a_13; - let _e13 = b_13; - v_6 = (_e12 - _e13); - let _e15 = a_13; - let _e16 = b_13; - c = (all((_e15[2] == _e16[2])) && (all((_e15[1] == _e16[1])) && all((_e15[0] == _e16[0])))); - let _e31 = a_13; - let _e32 = b_13; - c = (any((_e31[2] != _e32[2])) || (any((_e31[1] != _e32[1])) || any((_e31[0] != _e32[0])))); + v_6 = mat3x3((_e6[0] / _e7[0]), (_e6[1] / _e7[1]), (_e6[2] / _e7[2])); + let _e18 = a_13; + let _e19 = b_13; + v_6 = (_e18 * _e19); + let _e21 = a_13; + let _e22 = b_13; + v_6 = (_e21 + _e22); + let _e24 = a_13; + let _e25 = b_13; + v_6 = (_e24 - _e25); + let _e27 = a_13; + let _e28 = b_13; + c = (all((_e27[2] == _e28[2])) && (all((_e27[1] == _e28[1])) && all((_e27[0] == _e28[0])))); + let _e43 = a_13; + let _e44 = b_13; + c = (any((_e43[2] != _e44[2])) || (any((_e43[1] != _e44[1])) || any((_e43[0] != _e44[0])))); return; } From af8dd4b3bd941f3876788b6eccf353b39dbc9b43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 2 Mar 2022 22:06:54 +0000 Subject: [PATCH 1612/2212] glsl-in: Fix matrix by scalar operations --- src/front/glsl/context.rs | 183 +++++++++++++++++++++++++++ tests/in/glsl/expressions.frag | 20 +++ tests/out/wgsl/expressions-frag.wgsl | 61 ++++++++- 3 files changed, 263 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index ed6b2bc5d..781c9c767 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -816,6 +816,189 @@ impl Context { self.add_expression(Expression::Binary { left, op, right }, meta, body) } }, + ( + &TypeInner::Scalar { + width: left_width, .. + }, + &TypeInner::Matrix { + rows, + columns, + width: right_width, + }, + ) => { + // Check that the two arguments have the same width + if left_width != right_width { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + format!( + "Cannot apply operation to {:?} and {:?}", + left_inner, right_inner + ) + .into(), + ), + meta, + }) + } + + match op { + BinaryOperator::Divide + | BinaryOperator::Add + | BinaryOperator::Subtract => { + // Naga IR doesn't support all matrix by scalar operations so + // we need for some to turn the scalar into a vector by + // splatting it and then for each column vector apply the + // operation and finally reconstruct the matrix + let scalar_vector = self.add_expression( + Expression::Splat { + size: rows, + value: left, + }, + meta, + body, + ); + + let mut components = Vec::with_capacity(columns as usize); + + for index in 0..columns as u32 { + // Get the column vector + let matrix_column = self.add_expression( + Expression::AccessIndex { base: right, index }, + meta, + body, + ); + + // Apply the operation to the splatted vector and + // the column vector + let column = self.expressions.append( + Expression::Binary { + op, + left: scalar_vector, + right: matrix_column, + }, + meta, + ); + + components.push(column) + } + + // Rebuild the matrix from the operation result vectors + self.expressions.append( + Expression::Compose { + ty: parser.module.types.insert( + Type { + name: None, + inner: TypeInner::Matrix { + columns, + rows, + width: left_width, + }, + }, + Span::default(), + ), + components, + }, + meta, + ) + } + _ => self.add_expression( + Expression::Binary { left, op, right }, + meta, + body, + ), + } + } + ( + &TypeInner::Matrix { + rows, + columns, + width: left_width, + }, + &TypeInner::Scalar { + width: right_width, .. + }, + ) => { + // Check that the two arguments have the same width + if left_width != right_width { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + format!( + "Cannot apply operation to {:?} and {:?}", + left_inner, right_inner + ) + .into(), + ), + meta, + }) + } + + match op { + BinaryOperator::Divide + | BinaryOperator::Add + | BinaryOperator::Subtract => { + // Naga IR doesn't support all matrix by scalar operations so + // we need for some to turn the scalar into a vector by + // splatting it and then for each column vector apply the + // operation and finally reconstruct the matrix + + let scalar_vector = self.add_expression( + Expression::Splat { + size: rows, + value: right, + }, + meta, + body, + ); + + let mut components = Vec::with_capacity(columns as usize); + + for index in 0..columns as u32 { + // Get the column vector + let matrix_column = self.add_expression( + Expression::AccessIndex { base: left, index }, + meta, + body, + ); + + // Apply the operation to the splatted vector and + // the column vector + let column = self.expressions.append( + Expression::Binary { + op, + left: matrix_column, + right: scalar_vector, + }, + meta, + ); + + components.push(column) + } + + // Rebuild the matrix from the operation result vectors + self.expressions.append( + Expression::Compose { + ty: parser.module.types.insert( + Type { + name: None, + inner: TypeInner::Matrix { + columns, + rows, + width: left_width, + }, + }, + Span::default(), + ), + components, + }, + meta, + ) + } + _ => self.add_expression( + Expression::Binary { left, op, right }, + meta, + body, + ), + } + } _ => self.add_expression(Expression::Binary { left, op, right }, meta, body), } } diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 29fb29009..1448d54d8 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -73,6 +73,26 @@ void testBinOpMatMat(mat3 a, mat3 b) { c = a != b; } +void testBinOpMatFloat(float a, mat3 b) { + mat3 v; + v = a / b; + v = a * b; + v = a + b; + v = a - b; + + v = b / a; + v = b * a; + v = b + a; + v = b - a; +} + +void testUnaryOpMat(mat3 a) { + mat3 v; + v = -a; + v = --a; + v = a--; +} + void testStructConstructor() { struct BST { int data; diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index e7a77ff74..6ed532f02 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -208,6 +208,65 @@ fn testBinOpMatMat(a_12: mat3x3, b_12: mat3x3) { return; } +fn testBinOpMatFloat(a_14: f32, b_14: mat3x3) { + var a_15: f32; + var b_15: mat3x3; + var v_7: mat3x3; + + a_15 = a_14; + b_15 = b_14; + let _e5 = a_15; + let _e6 = b_15; + let _e7 = vec3(_e5); + v_7 = mat3x3((_e7 / _e6[0]), (_e7 / _e6[1]), (_e7 / _e6[2])); + let _e15 = a_15; + let _e16 = b_15; + v_7 = (_e15 * _e16); + let _e18 = a_15; + let _e19 = b_15; + let _e20 = vec3(_e18); + v_7 = mat3x3((_e20 + _e19[0]), (_e20 + _e19[1]), (_e20 + _e19[2])); + let _e28 = a_15; + let _e29 = b_15; + let _e30 = vec3(_e28); + v_7 = mat3x3((_e30 - _e29[0]), (_e30 - _e29[1]), (_e30 - _e29[2])); + let _e38 = b_15; + let _e39 = a_15; + let _e40 = vec3(_e39); + v_7 = mat3x3((_e38[0] / _e40), (_e38[1] / _e40), (_e38[2] / _e40)); + let _e48 = b_15; + let _e49 = a_15; + v_7 = (_e48 * _e49); + let _e51 = b_15; + let _e52 = a_15; + let _e53 = vec3(_e52); + v_7 = mat3x3((_e51[0] + _e53), (_e51[1] + _e53), (_e51[2] + _e53)); + let _e61 = b_15; + let _e62 = a_15; + let _e63 = vec3(_e62); + v_7 = mat3x3((_e61[0] - _e63), (_e61[1] - _e63), (_e61[2] - _e63)); + return; +} + +fn testUnaryOpMat(a_16: mat3x3) { + var a_17: mat3x3; + var v_8: mat3x3; + + a_17 = a_16; + let _e3 = a_17; + v_8 = -(_e3); + let _e5 = a_17; + let _e7 = vec3(1.0); + let _e9 = (_e5 - mat3x3(_e7, _e7, _e7)); + a_17 = _e9; + v_8 = _e9; + let _e10 = a_17; + let _e12 = vec3(1.0); + a_17 = (_e10 - mat3x3(_e12, _e12, _e12)); + v_8 = _e10; + return; +} + fn testStructConstructor() { var tree: BST = BST(1); @@ -223,7 +282,7 @@ fn testArrayConstructor() { } -fn privatePointer(a_14: ptr) { +fn privatePointer(a_18: ptr) { return; } From 51e66eceb20d6e3ba6c53b99c1a53d15ecb542dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 3 Mar 2022 16:11:23 +0000 Subject: [PATCH 1613/2212] glsl-in: Allow backtracking in the parser --- src/front/glsl/error.rs | 5 ++ src/front/glsl/parser.rs | 71 ++++++++++++++++++++------- src/front/glsl/parser/declarations.rs | 19 +++---- 3 files changed, 64 insertions(+), 31 deletions(-) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index a06d3bfe0..cd0577a6e 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -104,6 +104,11 @@ pub enum ErrorKind { /// An error was returned by the preprocessor. #[error("{0:?}")] PreprocessorError(PreprocessorError), + /// The parser entered an illegal state and exited + /// + /// This obviously is a bug and as such should be reported in the github issue tracker + #[error("Internal error: {0}")] + InternalError(&'static str), } impl From for ErrorKind { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 852788793..c159e80ee 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -21,6 +21,8 @@ mod types; pub struct ParsingContext<'source> { lexer: Peekable>, + /// Used to store tokens already consumed by the parser but that need to be backtracked + backtracked_token: Option, last_meta: Span, } @@ -28,10 +30,32 @@ impl<'source> ParsingContext<'source> { pub fn new(lexer: Lexer<'source>) -> Self { ParsingContext { lexer: lexer.peekable(), + backtracked_token: None, last_meta: Span::default(), } } + /// Helper method for backtracking from a consumed token + /// + /// This method should always be used instead of assigning to `backtracked_token` since + /// it validates that backtracking hasn't ocurred more than one time in a row + /// + /// # Panics + /// - If the parser already backtracked without bumping in between + pub fn backtrack(&mut self, token: Token) -> Result<()> { + // This should never happen + if let Some(ref prev_token) = self.backtracked_token { + return Err(Error { + kind: ErrorKind::InternalError("The parser tried to backtrack twice in a row"), + meta: prev_token.meta, + }); + } + + self.backtracked_token = Some(token); + + Ok(()) + } + pub fn expect_ident(&mut self, parser: &mut Parser) -> Result<(String, Span)> { let token = self.bump(parser)?; @@ -59,6 +83,11 @@ impl<'source> ParsingContext<'source> { pub fn next(&mut self, parser: &mut Parser) -> Option { loop { + if let Some(token) = self.backtracked_token.take() { + self.last_meta = token.meta; + break Some(token); + } + let res = self.lexer.next()?; match res.kind { @@ -94,30 +123,34 @@ impl<'source> ParsingContext<'source> { } pub fn peek(&mut self, parser: &mut Parser) -> Option<&Token> { - match self.lexer.peek()?.kind { - LexerResultKind::Token(_) => { - let res = self.lexer.peek()?; - - match res.kind { - LexerResultKind::Token(ref token) => Some(token), - _ => unreachable!(), - } + loop { + if let Some(ref token) = self.backtracked_token { + break Some(token); } - LexerResultKind::Error(_) | LexerResultKind::Directive(_) => { - let res = self.lexer.next()?; - match res.kind { - LexerResultKind::Directive(directive) => { - parser.handle_directive(directive, res.meta) + match self.lexer.peek()?.kind { + LexerResultKind::Token(_) => { + let res = self.lexer.peek()?; + + match res.kind { + LexerResultKind::Token(ref token) => break Some(token), + _ => unreachable!(), } - LexerResultKind::Error(error) => parser.errors.push(Error { - kind: ErrorKind::PreprocessorError(error), - meta: res.meta, - }), - _ => unreachable!(), } + LexerResultKind::Error(_) | LexerResultKind::Directive(_) => { + let res = self.lexer.next()?; - self.peek(parser) + match res.kind { + LexerResultKind::Directive(directive) => { + parser.handle_directive(directive, res.meta) + } + LexerResultKind::Error(error) => parser.errors.push(Error { + kind: ErrorKind::PreprocessorError(error), + meta: res.meta, + }), + _ => unreachable!(), + } + } } } } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 8171a11b7..acc200ba2 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -121,7 +121,6 @@ impl<'source> ParsingContext<'source> { &mut self, parser: &mut Parser, ty: Handle, - mut fallthrough: Option, ctx: &mut DeclarationContext, ) -> Result<()> { // init_declarator_list: @@ -139,20 +138,15 @@ impl<'source> ParsingContext<'source> { // fully_specified_type IDENTIFIER EQUAL initializer // Consume any leading comma, e.g. this is valid: `float, a=1;` - if fallthrough - .as_ref() - .or_else(|| self.peek(parser)) - .filter(|t| t.value == TokenValue::Comma) - .is_some() + if self + .peek(parser) + .map_or(false, |t| t.value == TokenValue::Comma) { - fallthrough.take().or_else(|| self.next(parser)); + self.next(parser); } loop { - let token = fallthrough - .take() - .ok_or(ErrorKind::EndOfFile) - .or_else(|_| self.bump(parser))?; + let token = self.bump(parser)?; let name = match token.value { TokenValue::Semicolon => break, TokenValue::Identifier(name) => name, @@ -339,7 +333,8 @@ impl<'source> ParsingContext<'source> { body, }; - self.parse_init_declarator_list(parser, ty, Some(token_fallthrough), &mut ctx)?; + self.backtrack(token_fallthrough)?; + self.parse_init_declarator_list(parser, ty, &mut ctx)?; } else { parser.errors.push(Error { kind: ErrorKind::SemanticError("Declaration cannot have void type".into()), From a2bcdda81ce5b31dc669724b93eecadef088b7ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 3 Mar 2022 16:32:06 +0000 Subject: [PATCH 1614/2212] glsl-in: Fix freestanding constructor parsing --- src/front/glsl/parser/functions.rs | 27 +++++++++++++++++++-------- tests/in/glsl/expressions.frag | 4 ++++ tests/out/wgsl/expressions-frag.wgsl | 4 ++++ 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 35ecfa483..797e48dea 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -42,17 +42,28 @@ impl<'source> ParsingContext<'source> { body: &mut Block, terminator: &mut Option, ) -> Result> { - // TODO: This prevents snippets like the following from working - // ```glsl - // vec4(1.0); - // ``` - // But this would require us to add lookahead to also support - // declarations and since this statement is very unlikely and most - // likely an error, for now we don't support it - if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { + // Type qualifiers always identify a declaration statement + if self.peek_type_qualifier(parser) { return self.parse_declaration(parser, ctx, body, false); } + // Type names can identify either declaration statements or type constructors + // depending on wether the token following the type name is a `(` (LeftParen) + if self.peek_type_name(parser) { + // Start by consuming the type name so that we can peek the token after it + let token = self.bump(parser)?; + // Peek the next token and check if it's a `(` (LeftParen) if so the statement + // is a constructor, otherwise it's a declaration. We need to do the check + // beforehand and not in the if since we will backtrack before the if + let declaration = TokenValue::LeftParen != self.expect_peek(parser)?.value; + + self.backtrack(token)?; + + if declaration { + return self.parse_declaration(parser, ctx, body, false); + } + } + let new_break = || { let mut block = Block::new(); block.push(Statement::Break, crate::Span::default()); diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 1448d54d8..66a5c0f25 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -109,6 +109,10 @@ void testArrayConstructor() { float tree[1] = float[1](0.0); } +void testFreestandingConstructor() { + vec4(1.0); +} + float global; void privatePointer(inout float a) {} diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 6ed532f02..434d24b6a 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -282,6 +282,10 @@ fn testArrayConstructor() { } +fn testFreestandingConstructor() { + return; +} + fn privatePointer(a_18: ptr) { return; } From f054aa94f4b842b504c8de90cbd8e7d2a2af3922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 3 Mar 2022 17:20:18 +0000 Subject: [PATCH 1615/2212] glsl-in: Support arrays as input/output types Like it was already done for structs, arrays are flattened and each element is attributed a location that is it's index + the array base location. --- src/front/glsl/functions.rs | 53 +++++++++++++++++++++++++++ tests/in/glsl/declarations.vert | 5 +++ tests/out/wgsl/declarations-vert.wgsl | 21 +++++++++-- 3 files changed, 75 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 9a53e5002..a6dd97e99 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1208,6 +1208,59 @@ impl Parser { ), ) { match self.module.types[ty].inner { + TypeInner::Array { + base, + size: crate::ArraySize::Constant(constant), + .. + } => { + let mut location = match binding { + crate::Binding::Location { location, .. } => location, + _ => return, + }; + + // TODO: Better error reporting + // right now we just don't walk the array if the size isn't known at + // compile time and let validation catch it + let size = match self.module.constants[constant].to_array_length() { + Some(val) => val, + None => return f(name, pointer, ty, binding, expressions), + }; + + let interpolation = + self.module.types[base] + .inner + .scalar_kind() + .map(|kind| match kind { + ScalarKind::Float => crate::Interpolation::Perspective, + _ => crate::Interpolation::Flat, + }); + + for index in 0..size { + let member_pointer = expressions.append( + Expression::AccessIndex { + base: pointer, + index, + }, + crate::Span::default(), + ); + + let binding = crate::Binding::Location { + location, + interpolation, + sampling: None, + }; + location += 1; + + self.arg_type_walker( + name.clone(), + binding, + member_pointer, + base, + expressions, + f, + ) + } + } TypeInner::Struct { ref members, .. } => { let mut location = match binding { crate::Binding::Location { location, .. } => location, diff --git a/tests/in/glsl/declarations.vert b/tests/in/glsl/declarations.vert index c8dab7795..4d2054caa 100644 --- a/tests/in/glsl/declarations.vert +++ b/tests/in/glsl/declarations.vert @@ -10,6 +10,9 @@ layout(location = 0) out FragmentData { vec2 a; } frag; +layout(location = 2) in vec4 in_array[2]; +layout(location = 2) out vec4 out_array[2]; + struct TestStruct { float a; float b; @@ -22,4 +25,6 @@ void main() { vec3(-1.0, -1.0, 0.0) ); const TestStruct strct = TestStruct( 1, 2 ); + const vec4 from_input_array = in_array[1]; + out_array[0] = vec4(2.0); } diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index 867315090..cc5d9c932 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -16,23 +16,36 @@ struct TestStruct { struct VertexOutput { @location(0) position: vec2; @location(1) a: vec2; + @location(2) out_array: vec4; + @location(3) out_array_1: vec4; }; var vert: VertexData; var frag: FragmentData; +var in_array_2: array,2u>; +var out_array: array,2u>; fn main_1() { var positions: array,2u> = array,2u>(vec3(-1.0, 1.0, 0.0), vec3(-1.0, -1.0, 0.0)); var strct: TestStruct = TestStruct(1.0, 2.0); + var from_input_array: vec4; + let _e32 = in_array_2; + from_input_array = _e32[1]; + out_array[0] = vec4(2.0); + return; } @stage(vertex) -fn main(@location(0) position: vec2, @location(1) a: vec2) -> VertexOutput { +fn main(@location(0) position: vec2, @location(1) a: vec2, @location(2) in_array: vec4, @location(3) in_array_1: vec4) -> VertexOutput { vert.position = position; vert.a = a; + in_array_2[0] = in_array; + in_array_2[1] = in_array_1; main_1(); - let _e17 = frag.position; - let _e19 = frag.a; - return VertexOutput(_e17, _e19); + let _e26 = frag.position; + let _e28 = frag.a; + let _e31 = out_array[0]; + let _e33 = out_array[1]; + return VertexOutput(_e26, _e28, _e31, _e33); } From fe3d945a5817135266931db6a205641f7049a778 Mon Sep 17 00:00:00 2001 From: Vincent Isambart Date: Sat, 5 Mar 2022 06:42:11 +0900 Subject: [PATCH 1616/2212] Not operator depending on expression type --- src/back/hlsl/writer.rs | 15 +++++++++++++-- src/back/msl/writer.rs | 10 ++++++++-- tests/out/hlsl/operators.hlsl | 2 +- tests/out/msl/operators.msl | 2 +- 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 35b76f3fc..fce74ee91 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1751,10 +1751,21 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Expression::Unary { op, expr } => { + use crate::{ScalarKind as Sk, UnaryOperator as Uo}; // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators let op_str = match op { - crate::UnaryOperator::Negate => "-", - crate::UnaryOperator::Not => "!", + Uo::Negate => "-", + Uo::Not => match *func_ctx.info[expr].ty.inner_with(&module.types) { + TypeInner::Scalar { kind: Sk::Sint, .. } => "~", + TypeInner::Scalar { kind: Sk::Uint, .. } => "~", + TypeInner::Scalar { kind: Sk::Bool, .. } => "!", + ref other => { + return Err(Error::Custom(format!( + "Cannot apply not to type {:?}", + other + ))) + } + }, }; write!(self.out, "{}", op_str)?; self.write_expr(module, expr, func_ctx)?; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 4fb233a3c..cd86d9883 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1406,9 +1406,15 @@ impl Writer { } }, crate::Expression::Unary { op, expr } => { + use crate::{ScalarKind as Sk, UnaryOperator as Uo}; let op_str = match op { - crate::UnaryOperator::Negate => "-", - crate::UnaryOperator::Not => "!", + Uo::Negate => "-", + Uo::Not => match *context.resolve_type(expr) { + crate::TypeInner::Scalar { kind: Sk::Sint, .. } => "~", + crate::TypeInner::Scalar { kind: Sk::Uint, .. } => "~", + crate::TypeInner::Scalar { kind: Sk::Bool, .. } => "!", + _ => return Err(Error::Validation), + }, }; write!(self.out, "{}", op_str)?; self.put_expression(expr, context, false)?; diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 8f060d85b..3204dd3b1 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -33,7 +33,7 @@ int unary() if (!true) { return 1; } else { - return !1; + return ~1; } } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 1d76848a2..09871e528 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -38,7 +38,7 @@ int unary( if (!true) { return 1; } else { - return !1; + return ~1; } } From 79845371d3916b08689da374533c280246f6efc0 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 6 Mar 2022 09:08:40 -0800 Subject: [PATCH 1617/2212] msl: qualify read-only storage with const --- src/back/msl/writer.rs | 39 ++-- tests/in/access.param.ron | 6 + tests/in/access.wgsl | 19 +- tests/in/globals.wgsl | 3 +- tests/out/glsl/access.atomics.Compute.glsl | 4 +- tests/out/glsl/access.foo_frag.Fragment.glsl | 32 +++ ...ertex.glsl => access.foo_vert.Vertex.glsl} | 16 +- tests/out/glsl/globals.main.Compute.glsl | 3 +- tests/out/hlsl/access.hlsl | 33 ++-- tests/out/hlsl/access.hlsl.config | 4 +- tests/out/hlsl/globals.hlsl | 3 +- tests/out/msl/access.msl | 39 ++-- tests/out/msl/boids.msl | 2 +- tests/out/msl/bounds-check-restrict.msl | 14 +- tests/out/msl/bounds-check-zero.msl | 14 +- tests/out/msl/globals.msl | 3 +- tests/out/msl/policy-mix.msl | 2 +- tests/out/msl/shadow.msl | 2 +- tests/out/spv/access.spvasm | 183 ++++++++++-------- tests/out/spv/globals.spvasm | 166 ++++++++-------- tests/out/wgsl/access.wgsl | 27 +-- tests/out/wgsl/globals.wgsl | 3 +- 22 files changed, 354 insertions(+), 263 deletions(-) create mode 100644 tests/out/glsl/access.foo_frag.Fragment.glsl rename tests/out/glsl/{access.foo.Vertex.glsl => access.foo_vert.Vertex.glsl} (67%) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index cd86d9883..c04abe01a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -238,13 +238,12 @@ impl<'a> TypedGlobalVariable<'a> { let (space, access, reference) = match var.space.to_msl_name() { Some(space) if self.reference => { - let access = match var.space { - crate::AddressSpace::Private | crate::AddressSpace::WorkGroup - if !self.usage.contains(valid::GlobalUse::WRITE) => - { - "const" - } - _ => "", + let access = if var.space.needs_access_qualifier() + && !self.usage.contains(valid::GlobalUse::WRITE) + { + "const" + } else { + "" }; (space, access, "&") } @@ -401,13 +400,25 @@ impl crate::AddressSpace { /// passed through any functions called from the entry point. fn needs_pass_through(&self) -> bool { match *self { - crate::AddressSpace::Uniform - | crate::AddressSpace::Storage { .. } - | crate::AddressSpace::Private - | crate::AddressSpace::WorkGroup - | crate::AddressSpace::PushConstant - | crate::AddressSpace::Handle => true, - crate::AddressSpace::Function => false, + Self::Uniform + | Self::Storage { .. } + | Self::Private + | Self::WorkGroup + | Self::PushConstant + | Self::Handle => true, + Self::Function => false, + } + } + + /// Returns true if the address space may need a "const" qualifier. + fn needs_access_qualifier(&self) -> bool { + match *self { + //Note: we are ignoring the storage access here, and instead + // rely on the actual use of a global by functions. This means we + // may end up with "const" even if the binding is read-write, + // and that should be OK. + Self::Storage { .. } | Self::Private | Self::WorkGroup => true, + Self::Uniform | Self::PushConstant | Self::Handle | Self::Function => false, } } diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 3e9214f47..84595754e 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -8,6 +8,12 @@ lang_version: (2, 0), per_stage_map: ( vs: ( + resources: { + (group: 0, binding: 0): (buffer: Some(0), mutable: false), + }, + sizes_buffer: Some(24), + ), + fs: ( resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: true), }, diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 90c707359..d68a74ca0 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -20,7 +20,7 @@ fn read_from_private(foo: ptr) -> f32 { } @stage(vertex) -fn foo(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { +fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32 = 0.0; // We should check that backed doesn't skip this expression let baz: f32 = foo; @@ -37,12 +37,6 @@ fn foo(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let data_pointer: ptr = &bar.data[0].value; let foo_value = read_from_private(&foo); - // test storage stores - bar.matrix[1].z = 1.0; - bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); - bar.arr = array, 2>(vec2(0u), vec2(1u)); - bar.data[1].value = 1; - // test array indexing var c = array(a, i32(b), 3, 4, 5); c[vi + 1u] = 42; @@ -51,6 +45,17 @@ fn foo(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { return matrix * vec4(vec4(value)); } +@stage(fragment) +fn foo_frag() -> @location(0) vec4 { + // test storage stores + bar.matrix[1].z = 1.0; + bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + bar.arr = array, 2>(vec2(0u), vec2(1u)); + bar.data[1].value = 1; + + return vec4(0.0); +} + @stage(compute) @workgroup_size(1) fn atomics() { var tmp: i32; diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index e9f3fa77e..7e5b72501 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -11,7 +11,7 @@ struct Foo { v1: f32; }; @group(0) @binding(1) -var alignment: Foo; +var alignment: Foo; @group(0) @binding(2) var dummy: array>; @@ -23,6 +23,7 @@ var float_vecs: array, 20>; fn main() { wg[3] = alignment.v1; wg[2] = alignment.v3.x; + alignment.v1 = 4.0; wg[1] = f32(arrayLength(&dummy)); atomicStore(&at, 2u); diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 632fa2666..d1fddc7e1 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -17,8 +17,8 @@ layout(std430) buffer Bar_block_0Compute { } _group_0_binding_0_cs; -float read_from_private(inout float foo_2) { - float _e2 = foo_2; +float read_from_private(inout float foo_1) { + float _e2 = foo_1; return _e2; } diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl new file mode 100644 index 000000000..ab14704b0 --- /dev/null +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -0,0 +1,32 @@ +#version 310 es + +precision highp float; +precision highp int; + +struct AlignedWrapper { + int value; +}; +layout(std430) buffer Bar_block_0Fragment { + mat4x4 matrix; + mat2x2 matrix_array[2]; + int atom; + uvec2 arr[2]; + AlignedWrapper data[]; +} _group_0_binding_0_fs; + +layout(location = 0) out vec4 _fs2p_location0; + +float read_from_private(inout float foo_1) { + float _e2 = foo_1; + return _e2; +} + +void main() { + _group_0_binding_0_fs.matrix[1][2] = 1.0; + _group_0_binding_0_fs.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + _group_0_binding_0_fs.arr = uvec2[2](uvec2(0u), uvec2(1u)); + _group_0_binding_0_fs.data[1].value = 1; + _fs2p_location0 = vec4(0.0); + return; +} + diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl similarity index 67% rename from tests/out/glsl/access.foo.Vertex.glsl rename to tests/out/glsl/access.foo_vert.Vertex.glsl index 3508015cf..05fd49321 100644 --- a/tests/out/glsl/access.foo.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -15,26 +15,22 @@ layout(std430) buffer Bar_block_0Vertex { } _group_0_binding_0_vs; -float read_from_private(inout float foo_2) { - float _e2 = foo_2; +float read_from_private(inout float foo_1) { + float _e2 = foo_1; return _e2; } void main() { uint vi = uint(gl_VertexID); - float foo_1 = 0.0; + float foo = 0.0; int c[5] = int[5](0, 0, 0, 0, 0); - float baz = foo_1; - foo_1 = 1.0; + float baz = foo; + foo = 1.0; mat4x4 matrix = _group_0_binding_0_vs.matrix; uvec2 arr[2] = _group_0_binding_0_vs.arr; float b = _group_0_binding_0_vs.matrix[3][0]; int a = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; - float _e27 = read_from_private(foo_1); - _group_0_binding_0_vs.matrix[1][2] = 1.0; - _group_0_binding_0_vs.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); - _group_0_binding_0_vs.arr = uvec2[2](uvec2(0u), uvec2(1u)); - _group_0_binding_0_vs.data[1].value = 1; + float _e27 = read_from_private(foo); c = int[5](a, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index 46150907b..61513e8af 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -13,7 +13,7 @@ shared float wg[10]; shared uint at_1; -layout(std430) readonly buffer Foo_block_0Compute { Foo _group_0_binding_1_cs; }; +layout(std430) buffer Foo_block_0Compute { Foo _group_0_binding_1_cs; }; layout(std430) readonly buffer type_6_block_1Compute { vec2 _group_0_binding_2_cs[]; }; @@ -25,6 +25,7 @@ void main() { wg[3] = _e9; float _e14 = _group_0_binding_1_cs.v3_.x; wg[2] = _e14; + _group_0_binding_1_cs.v1_ = 4.0; wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; return; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index f79a6798b..91ffd5293 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -5,9 +5,9 @@ struct AlignedWrapper { RWByteAddressBuffer bar : register(u0); -float read_from_private(inout float foo_2) +float read_from_private(inout float foo_1) { - float _expr2 = foo_2; + float _expr2 = foo_1; return _expr2; } @@ -18,18 +18,29 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer) return ret; } -float4 foo(uint vi : SV_VertexID) : SV_Position +float4 foo_vert(uint vi : SV_VertexID) : SV_Position { - float foo_1 = 0.0; + float foo = 0.0; int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; - float baz = foo_1; - foo_1 = 1.0; + float baz = foo; + foo = 1.0; float4x4 matrix_ = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); int a = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); - const float _e27 = read_from_private(foo_1); + const float _e27 = read_from_private(foo); + { + int _result[5]={ a, int(b), 3, 4, 5 }; + for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; + } + c[(vi + 1u)] = 42; + int value = c[vi]; + return mul(float4(int4(value.xxxx)), matrix_); +} + +float4 foo_frag() : SV_Target0 +{ bar.Store(8+16+0, asuint(1.0)); { float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx)); @@ -44,13 +55,7 @@ float4 foo(uint vi : SV_VertexID) : SV_Position bar.Store2(104+8, asuint(_value2[1])); } bar.Store(0+8+120, asuint(1)); - { - int _result[5]={ a, int(b), 3, 4, 5 }; - for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; - } - c[(vi + 1u)] = 42; - int value = c[vi]; - return mul(float4(int4(value.xxxx)), matrix_); + return float4(0.0.xxxx); } [numthreads(1, 1, 1)] diff --git a/tests/out/hlsl/access.hlsl.config b/tests/out/hlsl/access.hlsl.config index 49dcb6821..f6a8845ad 100644 --- a/tests/out/hlsl/access.hlsl.config +++ b/tests/out/hlsl/access.hlsl.config @@ -1,3 +1,3 @@ -vertex=(foo:vs_5_1 ) -fragment=() +vertex=(foo_vert:vs_5_1 ) +fragment=(foo_frag:ps_5_1 ) compute=(atomics:cs_5_1 ) diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 515ff1de6..d540235ba 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -7,7 +7,7 @@ struct Foo { groupshared float wg[10]; groupshared uint at_1; -ByteAddressBuffer alignment : register(t1); +RWByteAddressBuffer alignment : register(u1); ByteAddressBuffer dummy : register(t2); cbuffer float_vecs : register(b3) { float4 float_vecs[20]; } @@ -28,6 +28,7 @@ void main() wg[3] = _expr9; float _expr14 = asfloat(alignment.Load(0+0)); wg[2] = _expr14; + alignment.Store(12, asuint(4.0)); wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; return; diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index d4d80a50b..0a1c0cfb2 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -31,39 +31,50 @@ struct type_13 { }; float read_from_private( - thread float& foo_2 + thread float& foo_1 ) { - float _e2 = foo_2; + float _e2 = foo_1; return _e2; } -struct fooInput { +struct foo_vertInput { }; -struct fooOutput { +struct foo_vertOutput { metal::float4 member [[position]]; }; -vertex fooOutput foo( +vertex foo_vertOutput foo_vert( uint vi [[vertex_id]] -, device Bar& bar [[buffer(0)]] +, device Bar const& bar [[buffer(0)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - float foo_1 = 0.0; + float foo = 0.0; type_13 c; - float baz = foo_1; - foo_1 = 1.0; + float baz = foo; + foo = 1.0; metal::float4x4 matrix = bar.matrix; type_6 arr = bar.arr; float b = bar.matrix[3].x; int a = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; - float _e27 = read_from_private(foo_1); + float _e27 = read_from_private(foo); + for(int _i=0; _i<5; ++_i) c.inner[_i] = type_13 {a, static_cast(b), 3, 4, 5}.inner[_i]; + c.inner[vi + 1u] = 42; + int value = c.inner[vi]; + return foo_vertOutput { matrix * static_cast(metal::int4(value)) }; +} + + +struct foo_fragOutput { + metal::float4 member_1 [[color(0)]]; +}; +fragment foo_fragOutput foo_frag( + device Bar& bar [[buffer(0)]] +, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] +) { bar.matrix[1].z = 1.0; bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_6 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; bar.data[1].value = 1; - for(int _i=0; _i<5; ++_i) c.inner[_i] = type_13 {a, static_cast(b), 3, 4, 5}.inner[_i]; - c.inner[vi + 1u] = 42; - int value = c.inner[vi]; - return fooOutput { matrix * static_cast(metal::int4(value)) }; + return foo_fragOutput { metal::float4(0.0) }; } diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index d18d733ac..bcd80ca05 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -33,7 +33,7 @@ struct main_Input { kernel void main_( metal::uint3 global_invocation_id [[thread_position_in_grid]] , constant SimParams& params [[buffer(0)]] -, device Particles& particlesSrc [[buffer(1)]] +, device Particles const& particlesSrc [[buffer(1)]] , device Particles& particlesDst [[buffer(2)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(3)]] ) { diff --git a/tests/out/msl/bounds-check-restrict.msl b/tests/out/msl/bounds-check-restrict.msl index e82ebf814..a614e5924 100644 --- a/tests/out/msl/bounds-check-restrict.msl +++ b/tests/out/msl/bounds-check-restrict.msl @@ -22,7 +22,7 @@ struct Globals { float index_array( int i, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e4 = globals.a.inner[metal::min(unsigned(i), 9u)]; @@ -31,7 +31,7 @@ float index_array( float index_dynamic_array( int i_1, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e4 = globals.d[metal::min(unsigned(i_1), (_buffer_sizes.size0 - 112 - 4) / 4)]; @@ -40,7 +40,7 @@ float index_dynamic_array( float index_vector( int i_2, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e4 = globals.v[metal::min(unsigned(i_2), 3u)]; @@ -56,7 +56,7 @@ float index_vector_by_value( metal::float4 index_matrix( int i_4, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { metal::float4 _e4 = globals.m[metal::min(unsigned(i_4), 2u)]; @@ -66,7 +66,7 @@ metal::float4 index_matrix( float index_twice( int i_5, int j, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e6 = globals.m[metal::min(unsigned(i_5), 2u)][metal::min(unsigned(j), 3u)]; @@ -75,7 +75,7 @@ float index_twice( float index_expensive( int i_6, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e11 = globals.a.inner[metal::min(unsigned(static_cast(metal::sin(static_cast(i_6) / 100.0) * 100.0)), 9u)]; @@ -83,7 +83,7 @@ float index_expensive( } float index_in_bounds( - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e4 = globals.a.inner[9]; diff --git a/tests/out/msl/bounds-check-zero.msl b/tests/out/msl/bounds-check-zero.msl index 1a6bcc157..b45550d5a 100644 --- a/tests/out/msl/bounds-check-zero.msl +++ b/tests/out/msl/bounds-check-zero.msl @@ -28,7 +28,7 @@ struct Globals { float index_array( int i, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e4 = uint(i) < 10 ? globals.a.inner[i] : DefaultConstructible(); @@ -37,7 +37,7 @@ float index_array( float index_dynamic_array( int i_1, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e4 = uint(i_1) < 1 + (_buffer_sizes.size0 - 112 - 4) / 4 ? globals.d[i_1] : DefaultConstructible(); @@ -46,7 +46,7 @@ float index_dynamic_array( float index_vector( int i_2, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e4 = uint(i_2) < 4 ? globals.v[i_2] : DefaultConstructible(); @@ -62,7 +62,7 @@ float index_vector_by_value( metal::float4 index_matrix( int i_4, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { metal::float4 _e4 = uint(i_4) < 3 ? globals.m[i_4] : DefaultConstructible(); @@ -72,7 +72,7 @@ metal::float4 index_matrix( float index_twice( int i_5, int j, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e6 = uint(j) < 4 && uint(i_5) < 3 ? globals.m[i_5][j] : DefaultConstructible(); @@ -81,7 +81,7 @@ float index_twice( float index_expensive( int i_6, - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { int _e9 = static_cast(metal::sin(static_cast(i_6) / 100.0) * 100.0); @@ -90,7 +90,7 @@ float index_expensive( } float index_in_bounds( - device Globals& globals, + device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { float _e4 = globals.a.inner[9]; diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 8f4ce07ad..14fbc152a 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -25,7 +25,7 @@ kernel void main_( threadgroup type_2& wg , threadgroup metal::atomic_uint& at_1 , device Foo& alignment [[user(fake0)]] -, device type_6& dummy [[user(fake0)]] +, device type_6 const& dummy [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { float Foo_1 = 1.0; @@ -34,6 +34,7 @@ kernel void main_( wg.inner[3] = _e9; float _e14 = metal::float3(alignment.v3_).x; wg.inner[2] = _e14; + alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); return; diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index 8b4ba9911..b6b9b942b 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -36,7 +36,7 @@ metal::float4 mock_function( metal::int2 c, int i, int l, - device InStorage& in_storage, + device InStorage const& in_storage, constant InUniform& in_uniform, metal::texture2d_array image_2d_array, threadgroup type_5 const& in_workgroup, diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 58d03e957..5bdd3ba97 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -48,7 +48,7 @@ struct fs_mainOutput { fragment fs_mainOutput fs_main( fs_mainInput varyings [[stage_in]] , constant Globals& u_globals [[user(fake0)]] -, device Lights& s_lights [[user(fake0)]] +, device Lights const& s_lights [[user(fake0)]] , metal::depth2d_array t_shadow [[user(fake0)]] , metal::sampler sampler_shadow [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index bdd616040..21e4f513e 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,14 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 121 +; Bound: 126 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %51 "foo" %46 %49 -OpEntryPoint GLCompute %98 "atomics" -OpExecutionMode %98 LocalSize 1 1 1 +OpEntryPoint Vertex %51 "foo_vert" %46 %49 +OpEntryPoint Fragment %86 "foo_frag" %85 +OpEntryPoint GLCompute %103 "atomics" +OpExecutionMode %86 OriginUpperLeft +OpExecutionMode %103 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %21 0 "value" OpName %21 "AlignedWrapper" @@ -24,9 +26,10 @@ OpName %38 "read_from_private" OpName %42 "foo" OpName %43 "c" OpName %46 "vi" -OpName %51 "foo" -OpName %96 "tmp" -OpName %98 "atomics" +OpName %51 "foo_vert" +OpName %86 "foo_frag" +OpName %101 "tmp" +OpName %103 "atomics" OpMemberDecorate %21 0 Offset 0 OpDecorate %26 ArrayStride 16 OpDecorate %28 ArrayStride 8 @@ -46,6 +49,7 @@ OpDecorate %34 Binding 0 OpDecorate %30 Block OpDecorate %46 BuiltIn VertexIndex OpDecorate %49 BuiltIn Position +OpDecorate %85 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -56,15 +60,15 @@ OpDecorate %49 BuiltIn Position %8 = OpConstant %9 3 %10 = OpConstant %9 2 %11 = OpConstant %4 0 -%12 = OpConstant %4 1 -%13 = OpConstant %6 2.0 -%14 = OpConstant %6 3.0 -%15 = OpConstant %9 0 -%16 = OpConstant %9 1 -%17 = OpConstant %4 5 -%18 = OpConstant %4 3 -%19 = OpConstant %4 4 -%20 = OpConstant %4 42 +%12 = OpConstant %4 5 +%13 = OpConstant %4 3 +%14 = OpConstant %4 4 +%15 = OpConstant %9 1 +%16 = OpConstant %4 42 +%17 = OpConstant %4 1 +%18 = OpConstant %6 2.0 +%19 = OpConstant %6 3.0 +%20 = OpConstant %9 0 %21 = OpTypeStruct %4 %23 = OpTypeVector %6 4 %22 = OpTypeMatrix %23 4 @@ -77,7 +81,7 @@ OpDecorate %49 BuiltIn Position %30 = OpTypeStruct %22 %26 %4 %28 %29 %31 = OpTypePointer Function %6 %32 = OpTypePointer StorageBuffer %4 -%33 = OpTypeArray %4 %17 +%33 = OpTypeArray %4 %12 %35 = OpTypePointer StorageBuffer %30 %34 = OpVariable %35 StorageBuffer %39 = OpTypeFunction %6 %31 @@ -94,10 +98,11 @@ OpDecorate %49 BuiltIn Position %65 = OpTypePointer StorageBuffer %29 %68 = OpTypePointer StorageBuffer %21 %69 = OpConstant %9 4 -%88 = OpTypePointer Function %4 -%92 = OpTypeVector %4 4 -%100 = OpTypePointer StorageBuffer %4 -%103 = OpConstant %9 64 +%76 = OpTypePointer Function %4 +%80 = OpTypeVector %4 4 +%85 = OpVariable %50 Output +%105 = OpTypePointer StorageBuffer %4 +%108 = OpConstant %9 64 %38 = OpFunction %6 None %39 %37 = OpFunctionParameter %31 %36 = OpLabel @@ -115,79 +120,87 @@ OpBranch %53 %53 = OpLabel %54 = OpLoad %6 %42 OpStore %42 %7 -%56 = OpAccessChain %55 %34 %15 +%56 = OpAccessChain %55 %34 %20 %57 = OpLoad %22 %56 %59 = OpAccessChain %58 %34 %8 %60 = OpLoad %28 %59 -%63 = OpAccessChain %62 %34 %15 %8 %15 +%63 = OpAccessChain %62 %34 %20 %8 %20 %64 = OpLoad %6 %63 %66 = OpArrayLength %9 %34 4 %67 = OpISub %9 %66 %10 -%70 = OpAccessChain %32 %34 %69 %67 %15 +%70 = OpAccessChain %32 %34 %69 %67 %20 %71 = OpLoad %4 %70 %72 = OpFunctionCall %6 %38 %42 -%73 = OpAccessChain %62 %34 %15 %16 %10 -OpStore %73 %7 -%74 = OpCompositeConstruct %23 %5 %5 %5 %5 -%75 = OpCompositeConstruct %23 %7 %7 %7 %7 -%76 = OpCompositeConstruct %23 %13 %13 %13 %13 -%77 = OpCompositeConstruct %23 %14 %14 %14 %14 -%78 = OpCompositeConstruct %22 %74 %75 %76 %77 -%79 = OpAccessChain %55 %34 %15 -OpStore %79 %78 -%80 = OpCompositeConstruct %27 %15 %15 -%81 = OpCompositeConstruct %27 %16 %16 -%82 = OpCompositeConstruct %28 %80 %81 -%83 = OpAccessChain %58 %34 %8 -OpStore %83 %82 -%84 = OpAccessChain %32 %34 %69 %16 %15 -OpStore %84 %12 -%85 = OpConvertFToS %4 %64 -%86 = OpCompositeConstruct %33 %71 %85 %18 %19 %17 -OpStore %43 %86 -%87 = OpIAdd %9 %48 %16 -%89 = OpAccessChain %88 %43 %87 -OpStore %89 %20 -%90 = OpAccessChain %88 %43 %48 -%91 = OpLoad %4 %90 -%93 = OpCompositeConstruct %92 %91 %91 %91 %91 -%94 = OpConvertSToF %23 %93 -%95 = OpMatrixTimesVector %23 %57 %94 -OpStore %49 %95 +%73 = OpConvertFToS %4 %64 +%74 = OpCompositeConstruct %33 %71 %73 %13 %14 %12 +OpStore %43 %74 +%75 = OpIAdd %9 %48 %15 +%77 = OpAccessChain %76 %43 %75 +OpStore %77 %16 +%78 = OpAccessChain %76 %43 %48 +%79 = OpLoad %4 %78 +%81 = OpCompositeConstruct %80 %79 %79 %79 %79 +%82 = OpConvertSToF %23 %81 +%83 = OpMatrixTimesVector %23 %57 %82 +OpStore %49 %83 OpReturn OpFunctionEnd -%98 = OpFunction %2 None %52 -%97 = OpLabel -%96 = OpVariable %88 Function -OpBranch %99 -%99 = OpLabel -%101 = OpAccessChain %100 %34 %10 -%102 = OpAtomicLoad %4 %101 %12 %103 -%105 = OpAccessChain %100 %34 %10 -%104 = OpAtomicIAdd %4 %105 %12 %103 %17 -OpStore %96 %104 -%107 = OpAccessChain %100 %34 %10 -%106 = OpAtomicISub %4 %107 %12 %103 %17 -OpStore %96 %106 -%109 = OpAccessChain %100 %34 %10 -%108 = OpAtomicAnd %4 %109 %12 %103 %17 -OpStore %96 %108 -%111 = OpAccessChain %100 %34 %10 -%110 = OpAtomicOr %4 %111 %12 %103 %17 -OpStore %96 %110 -%113 = OpAccessChain %100 %34 %10 -%112 = OpAtomicXor %4 %113 %12 %103 %17 -OpStore %96 %112 -%115 = OpAccessChain %100 %34 %10 -%114 = OpAtomicSMin %4 %115 %12 %103 %17 -OpStore %96 %114 -%117 = OpAccessChain %100 %34 %10 -%116 = OpAtomicSMax %4 %117 %12 %103 %17 -OpStore %96 %116 -%119 = OpAccessChain %100 %34 %10 -%118 = OpAtomicExchange %4 %119 %12 %103 %17 -OpStore %96 %118 -%120 = OpAccessChain %100 %34 %10 -OpAtomicStore %120 %12 %103 %102 +%86 = OpFunction %2 None %52 +%84 = OpLabel +OpBranch %87 +%87 = OpLabel +%88 = OpAccessChain %62 %34 %20 %15 %10 +OpStore %88 %7 +%89 = OpCompositeConstruct %23 %5 %5 %5 %5 +%90 = OpCompositeConstruct %23 %7 %7 %7 %7 +%91 = OpCompositeConstruct %23 %18 %18 %18 %18 +%92 = OpCompositeConstruct %23 %19 %19 %19 %19 +%93 = OpCompositeConstruct %22 %89 %90 %91 %92 +%94 = OpAccessChain %55 %34 %20 +OpStore %94 %93 +%95 = OpCompositeConstruct %27 %20 %20 +%96 = OpCompositeConstruct %27 %15 %15 +%97 = OpCompositeConstruct %28 %95 %96 +%98 = OpAccessChain %58 %34 %8 +OpStore %98 %97 +%99 = OpAccessChain %32 %34 %69 %15 %20 +OpStore %99 %17 +%100 = OpCompositeConstruct %23 %5 %5 %5 %5 +OpStore %85 %100 +OpReturn +OpFunctionEnd +%103 = OpFunction %2 None %52 +%102 = OpLabel +%101 = OpVariable %76 Function +OpBranch %104 +%104 = OpLabel +%106 = OpAccessChain %105 %34 %10 +%107 = OpAtomicLoad %4 %106 %17 %108 +%110 = OpAccessChain %105 %34 %10 +%109 = OpAtomicIAdd %4 %110 %17 %108 %12 +OpStore %101 %109 +%112 = OpAccessChain %105 %34 %10 +%111 = OpAtomicISub %4 %112 %17 %108 %12 +OpStore %101 %111 +%114 = OpAccessChain %105 %34 %10 +%113 = OpAtomicAnd %4 %114 %17 %108 %12 +OpStore %101 %113 +%116 = OpAccessChain %105 %34 %10 +%115 = OpAtomicOr %4 %116 %17 %108 %12 +OpStore %101 %115 +%118 = OpAccessChain %105 %34 %10 +%117 = OpAtomicXor %4 %118 %17 %108 %12 +OpStore %101 %117 +%120 = OpAccessChain %105 %34 %10 +%119 = OpAtomicSMin %4 %120 %17 %108 %12 +OpStore %101 %119 +%122 = OpAccessChain %105 %34 %10 +%121 = OpAtomicSMax %4 %122 %17 %108 %12 +OpStore %101 %121 +%124 = OpAccessChain %105 %34 %10 +%123 = OpAtomicExchange %4 %124 %17 %108 %12 +OpStore %101 %123 +%125 = OpAccessChain %105 %34 %10 +OpAtomicStore %125 %17 %108 %107 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index bfba6116f..e70ef7ca3 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,32 +1,31 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 66 +; Bound: 68 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %41 "main" -OpExecutionMode %41 LocalSize 1 1 1 -OpDecorate %16 ArrayStride 4 -OpMemberDecorate %18 0 Offset 0 -OpMemberDecorate %18 1 Offset 12 -OpDecorate %20 ArrayStride 8 -OpDecorate %22 ArrayStride 16 -OpDecorate %27 NonWritable -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 1 -OpDecorate %28 Block -OpMemberDecorate %28 0 Offset 0 -OpDecorate %30 NonWritable -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 2 -OpDecorate %31 Block -OpMemberDecorate %31 0 Offset 0 -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 3 -OpDecorate %34 Block -OpMemberDecorate %34 0 Offset 0 +OpEntryPoint GLCompute %42 "main" +OpExecutionMode %42 LocalSize 1 1 1 +OpDecorate %17 ArrayStride 4 +OpMemberDecorate %19 0 Offset 0 +OpMemberDecorate %19 1 Offset 12 +OpDecorate %21 ArrayStride 8 +OpDecorate %23 ArrayStride 16 +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 1 +OpDecorate %29 Block +OpMemberDecorate %29 0 Offset 0 +OpDecorate %31 NonWritable +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 2 +OpDecorate %32 Block +OpMemberDecorate %32 0 Offset 0 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 3 +OpDecorate %35 Block +OpMemberDecorate %35 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -36,65 +35,68 @@ OpMemberDecorate %34 0 Offset 0 %7 = OpConstant %8 20 %9 = OpConstant %8 3 %10 = OpConstant %8 2 -%11 = OpConstant %8 1 -%12 = OpConstant %6 2 -%14 = OpTypeFloat 32 -%13 = OpConstant %14 1.0 -%15 = OpConstantTrue %4 -%16 = OpTypeArray %14 %5 -%17 = OpTypeVector %14 3 -%18 = OpTypeStruct %17 %14 -%19 = OpTypeVector %14 2 -%20 = OpTypeRuntimeArray %19 -%21 = OpTypeVector %14 4 -%22 = OpTypeArray %21 %7 -%24 = OpTypePointer Workgroup %16 -%23 = OpVariable %24 Workgroup -%26 = OpTypePointer Workgroup %6 -%25 = OpVariable %26 Workgroup -%28 = OpTypeStruct %18 -%29 = OpTypePointer StorageBuffer %28 -%27 = OpVariable %29 StorageBuffer -%31 = OpTypeStruct %20 -%32 = OpTypePointer StorageBuffer %31 -%30 = OpVariable %32 StorageBuffer -%34 = OpTypeStruct %22 -%35 = OpTypePointer Uniform %34 -%33 = OpVariable %35 Uniform -%37 = OpTypePointer Function %14 -%39 = OpTypePointer Function %4 -%42 = OpTypeFunction %2 -%43 = OpTypePointer StorageBuffer %18 -%44 = OpConstant %6 0 -%46 = OpTypePointer StorageBuffer %20 -%48 = OpTypePointer Uniform %22 -%50 = OpTypePointer Workgroup %14 -%51 = OpTypePointer StorageBuffer %14 -%52 = OpConstant %6 1 -%55 = OpConstant %6 3 -%57 = OpTypePointer StorageBuffer %17 -%58 = OpTypePointer StorageBuffer %14 -%65 = OpConstant %6 256 -%41 = OpFunction %2 None %42 -%40 = OpLabel -%36 = OpVariable %37 Function %13 -%38 = OpVariable %39 Function %15 -%45 = OpAccessChain %43 %27 %44 -%47 = OpAccessChain %46 %30 %44 -OpBranch %49 -%49 = OpLabel -%53 = OpAccessChain %51 %45 %52 -%54 = OpLoad %14 %53 -%56 = OpAccessChain %50 %23 %55 -OpStore %56 %54 -%59 = OpAccessChain %58 %45 %44 %44 -%60 = OpLoad %14 %59 -%61 = OpAccessChain %50 %23 %12 -OpStore %61 %60 -%62 = OpArrayLength %6 %30 0 -%63 = OpConvertUToF %14 %62 -%64 = OpAccessChain %50 %23 %52 -OpStore %64 %63 -OpAtomicStore %25 %10 %65 %12 +%12 = OpTypeFloat 32 +%11 = OpConstant %12 4.0 +%13 = OpConstant %8 1 +%14 = OpConstant %6 2 +%15 = OpConstant %12 1.0 +%16 = OpConstantTrue %4 +%17 = OpTypeArray %12 %5 +%18 = OpTypeVector %12 3 +%19 = OpTypeStruct %18 %12 +%20 = OpTypeVector %12 2 +%21 = OpTypeRuntimeArray %20 +%22 = OpTypeVector %12 4 +%23 = OpTypeArray %22 %7 +%25 = OpTypePointer Workgroup %17 +%24 = OpVariable %25 Workgroup +%27 = OpTypePointer Workgroup %6 +%26 = OpVariable %27 Workgroup +%29 = OpTypeStruct %19 +%30 = OpTypePointer StorageBuffer %29 +%28 = OpVariable %30 StorageBuffer +%32 = OpTypeStruct %21 +%33 = OpTypePointer StorageBuffer %32 +%31 = OpVariable %33 StorageBuffer +%35 = OpTypeStruct %23 +%36 = OpTypePointer Uniform %35 +%34 = OpVariable %36 Uniform +%38 = OpTypePointer Function %12 +%40 = OpTypePointer Function %4 +%43 = OpTypeFunction %2 +%44 = OpTypePointer StorageBuffer %19 +%45 = OpConstant %6 0 +%47 = OpTypePointer StorageBuffer %21 +%49 = OpTypePointer Uniform %23 +%51 = OpTypePointer Workgroup %12 +%52 = OpTypePointer StorageBuffer %12 +%53 = OpConstant %6 1 +%56 = OpConstant %6 3 +%58 = OpTypePointer StorageBuffer %18 +%59 = OpTypePointer StorageBuffer %12 +%67 = OpConstant %6 256 +%42 = OpFunction %2 None %43 +%41 = OpLabel +%37 = OpVariable %38 Function %15 +%39 = OpVariable %40 Function %16 +%46 = OpAccessChain %44 %28 %45 +%48 = OpAccessChain %47 %31 %45 +OpBranch %50 +%50 = OpLabel +%54 = OpAccessChain %52 %46 %53 +%55 = OpLoad %12 %54 +%57 = OpAccessChain %51 %24 %56 +OpStore %57 %55 +%60 = OpAccessChain %59 %46 %45 %45 +%61 = OpLoad %12 %60 +%62 = OpAccessChain %51 %24 %14 +OpStore %62 %61 +%63 = OpAccessChain %52 %46 %53 +OpStore %63 %11 +%64 = OpArrayLength %6 %31 0 +%65 = OpConvertUToF %12 %64 +%66 = OpAccessChain %51 %24 %53 +OpStore %66 %65 +OpAtomicStore %26 %10 %67 %14 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 28d29440f..1080002ef 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -13,34 +13,39 @@ struct Bar { @group(0) @binding(0) var bar: Bar; -fn read_from_private(foo_2: ptr) -> f32 { - let _e2 = (*foo_2); +fn read_from_private(foo_1: ptr) -> f32 { + let _e2 = (*foo_1); return _e2; } @stage(vertex) -fn foo(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { - var foo_1: f32 = 0.0; +fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { + var foo: f32 = 0.0; var c: array; - let baz = foo_1; - foo_1 = 1.0; + let baz = foo; + foo = 1.0; let matrix = bar.matrix; let arr = bar.arr; let b = bar.matrix[3][0]; let a = bar.data[(arrayLength((&bar.data)) - 2u)].value; let data_pointer = (&bar.data[0].value); - let _e27 = read_from_private((&foo_1)); - bar.matrix[1][2] = 1.0; - bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); - bar.arr = array,2>(vec2(0u), vec2(1u)); - bar.data[1].value = 1; + let _e27 = read_from_private((&foo)); c = array(a, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value = c[vi]; return (matrix * vec4(vec4(value))); } +@stage(fragment) +fn foo_frag() -> @location(0) vec4 { + bar.matrix[1][2] = 1.0; + bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + bar.arr = array,2>(vec2(0u), vec2(1u)); + bar.data[1].value = 1; + return vec4(0.0); +} + @stage(compute) @workgroup_size(1, 1, 1) fn atomics() { var tmp: i32; diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index f73c6c04d..d1ab5cbf1 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -8,7 +8,7 @@ let Foo_2: bool = true; var wg: array; var at_1: atomic; @group(0) @binding(1) -var alignment: Foo; +var alignment: Foo; @group(0) @binding(2) var dummy: array>; @group(0) @binding(3) @@ -23,6 +23,7 @@ fn main() { wg[3] = _e9; let _e14 = alignment.v3_.x; wg[2] = _e14; + alignment.v1_ = 4.0; wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); return; From c84aa775790682f2e4ed28440bc681b09808d0cb Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 8 Mar 2022 07:07:30 -0800 Subject: [PATCH 1618/2212] [msl-out] Properly rename entry point arguments for struct members. (#1766) --- src/back/msl/writer.rs | 92 ++++++++++--- tests/in/interface.wgsl | 14 ++ tests/out/hlsl/interface.hlsl | 16 +++ tests/out/hlsl/interface.hlsl.config | 2 +- tests/out/msl/interface.msl | 24 ++++ tests/out/spv/interface.compute.spvasm | 103 ++++++++------- tests/out/spv/interface.fragment.spvasm | 123 +++++++++--------- tests/out/spv/interface.vertex.spvasm | 101 +++++++------- .../spv/interface.vertex_two_structs.spvasm | 68 ++++++++++ tests/out/wgsl/interface.wgsl | 16 +++ 10 files changed, 383 insertions(+), 176 deletions(-) create mode 100644 tests/out/spv/interface.vertex_two_structs.spvasm diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c04abe01a..076a37bd1 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3288,9 +3288,6 @@ impl Writer { writeln!(self.out)?; - let stage_out_name = format!("{}Output", fun_name); - let stage_in_name = format!("{}Input", fun_name); - let (em_str, in_mode, out_mode) = match ep.stage { crate::ShaderStage::Vertex => ( "vertex", @@ -3307,35 +3304,44 @@ impl Writer { } }; - let mut argument_members = Vec::new(); + // List all the Naga `EntryPoint`'s `Function`'s arguments, + // flattening structs into their members. In Metal, we will pass + // each of these values to the entry point as a separate argument— + // except for the varyings, handled next. + let mut flattened_arguments = Vec::new(); for (arg_index, arg) in fun.arguments.iter().enumerate() { match module.types[arg.ty].inner { crate::TypeInner::Struct { ref members, .. } => { for (member_index, member) in members.iter().enumerate() { - argument_members.push(( - NameKey::StructMember(arg.ty, member_index as u32), + let member_index = member_index as u32; + flattened_arguments.push(( + NameKey::StructMember(arg.ty, member_index), member.ty, member.binding.as_ref(), - )) + )); } } - _ => argument_members.push(( + _ => flattened_arguments.push(( NameKey::EntryPointArgument(ep_index as _, arg_index as u32), arg.ty, arg.binding.as_ref(), )), } } + + // Identify the varyings among the argument values, and emit a + // struct type named `Input` to hold them. + let stage_in_name = format!("{}Input", fun_name); let varyings_member_name = self.namer.call("varyings"); - let mut varying_count = 0; - if !argument_members.is_empty() { + let mut has_varyings = false; + if !flattened_arguments.is_empty() { writeln!(self.out, "struct {} {{", stage_in_name)?; - for &(ref name_key, ty, binding) in argument_members.iter() { + for &(ref name_key, ty, binding) in flattened_arguments.iter() { let binding = match binding { Some(ref binding @ &crate::Binding::Location { .. }) => binding, _ => continue, }; - varying_count += 1; + has_varyings = true; let name = &self.names[name_key]; let ty_name = TypeContext { handle: ty, @@ -3352,6 +3358,9 @@ impl Writer { writeln!(self.out, "}};")?; } + // Define a struct type named for the return value, if any, named + // `Output`. + let stage_out_name = format!("{}Output", fun_name); let result_member_name = self.namer.call("member"); let result_type_name = match fun.result { Some(ref result) => { @@ -3444,10 +3453,14 @@ impl Writer { } None => "void", }; - writeln!(self.out, "{} {} {}(", em_str, result_type_name, fun_name)?; + // Write the entry point function's name, and begin its argument list. + writeln!(self.out, "{} {} {}(", em_str, result_type_name, fun_name)?; let mut is_first_argument = true; - if varying_count != 0 { + + // If we have produced a struct holding the `EntryPoint`'s + // `Function`'s arguments' varyings, pass that struct first. + if has_varyings { writeln!( self.out, " {} {} [[stage_in]]", @@ -3455,12 +3468,31 @@ impl Writer { )?; is_first_argument = false; } - for &(ref name_key, ty, binding) in argument_members.iter() { + + // Then pass the remaining arguments not included in the varyings + // struct. + // + // Since `Namer.reset` wasn't expecting struct members to be + // suddenly injected into the normal namespace like this, + // `self.names` doesn't keep them distinct from other variables. + // Generate fresh names for these arguments, and remember the + // mapping. + let mut flattened_member_names = FastHashMap::default(); + for &(ref name_key, ty, binding) in flattened_arguments.iter() { let binding = match binding { Some(ref binding @ &crate::Binding::BuiltIn(..)) => binding, _ => continue, }; - let name = &self.names[name_key]; + let name = if let NameKey::StructMember(ty, index) = *name_key { + // We should always insert a fresh entry here, but use + // `or_insert` to get a reference to the `String` we just + // inserted. + flattened_member_names + .entry(NameKey::StructMember(ty, index)) + .or_insert_with(|| self.namer.call(&self.names[name_key])) + } else { + &self.names[name_key] + }; let ty_name = TypeContext { handle: ty, arena: &module.types, @@ -3479,6 +3511,11 @@ impl Writer { resolved.try_fmt_decorated(&mut self.out)?; writeln!(self.out)?; } + + // Those global variables used by this entry point and its callees + // get passed as arguments. `Private` globals are an exception, they + // don't outlive this invocation, so we declare them below as locals + // within the entry point. for (handle, var) in module.global_variables.iter() { let usage = fun_info[handle]; if usage.is_empty() || var.space == crate::AddressSpace::Private { @@ -3534,6 +3571,8 @@ impl Writer { writeln!(self.out)?; } + // If this entry uses any variable-length arrays, their sizes are + // passed as a final struct-typed argument. if supports_array_length { // this is checked earlier let resolved = options.resolve_sizes_buffer(ep.stage).unwrap(); @@ -3603,7 +3642,16 @@ impl Writer { } } - // Now refactor the inputs in a way that the rest of the code expects + // Now take the arguments that we gathered into structs, and the + // structs that we flattened into arguments, and emit local + // variables with initializers that put everything back the way the + // body code expects. + // + // If we had to generate fresh names for struct members passed as + // arguments, be sure to use those names when rebuilding the struct. + // + // "Each day, I change some zeros to ones, and some ones to zeros. + // The rest, I leave alone." for (arg_index, arg) in fun.arguments.iter().enumerate() { let arg_name = &self.names[&NameKey::EntryPointArgument(ep_index as _, arg_index as u32)]; @@ -3618,8 +3666,14 @@ impl Writer { arg_name )?; for (member_index, member) in members.iter().enumerate() { - let name = - &self.names[&NameKey::StructMember(arg.ty, member_index as u32)]; + let key = NameKey::StructMember(arg.ty, member_index as u32); + // If it's not in the varying struct, then we should + // have passed it as its own argument and assigned + // it a new name. + let name = match member.binding { + Some(crate::Binding::BuiltIn(_)) => &flattened_member_names[&key], + _ => &self.names[&key], + }; if member_index != 0 { write!(self.out, ", ")?; } diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index f5946c13a..737529552 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -45,3 +45,17 @@ fn compute( ) { output[0] = global_id.x + local_id.x + local_index + wg_id.x + num_wgs.x; } + +struct Input1 { + @builtin(vertex_index) index: u32; +}; + +struct Input2 { + @builtin(instance_index) index: u32; +}; + +@stage(vertex) +fn vertex_two_structs(in1: Input1, in2: Input2) -> @builtin(position) vec4 { + var index = 2u; + return vec4(f32(in1.index), f32(in2.index), f32(index), 0.0); +} diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 99ed31acd..9ccafc340 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -16,6 +16,14 @@ struct FragmentOutput { linear float color : SV_Target0; }; +struct Input1_ { + uint index : SV_VertexID; +}; + +struct Input2_ { + uint index : SV_InstanceID; +}; + groupshared uint output[1]; struct VertexOutput_vertex { @@ -72,3 +80,11 @@ void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThr output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x); return; } + +float4 vertex_two_structs(Input1_ in1_, Input2_ in2_) : SV_Position +{ + uint index = 2u; + + uint _expr9 = index; + return float4(float((_NagaConstants.base_vertex + in1_.index)), float((_NagaConstants.base_instance + in2_.index)), float(_expr9), 0.0); +} diff --git a/tests/out/hlsl/interface.hlsl.config b/tests/out/hlsl/interface.hlsl.config index cec1fc2b9..d7e51aecf 100644 --- a/tests/out/hlsl/interface.hlsl.config +++ b/tests/out/hlsl/interface.hlsl.config @@ -1,3 +1,3 @@ -vertex=(vertex:vs_5_1 ) +vertex=(vertex:vs_5_1 vertex_two_structs:vs_5_1 ) fragment=(fragment:ps_5_1 ) compute=(compute:cs_5_1 ) diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index dbc687198..00789692c 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -16,6 +16,12 @@ struct FragmentOutput { struct type_4 { uint inner[1]; }; +struct Input1_ { + uint index; +}; +struct Input2_ { + uint index; +}; struct vertex_Input { uint color [[attribute(10)]]; @@ -73,3 +79,21 @@ kernel void compute_( output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x; return; } + + +struct vertex_two_structsInput { +}; +struct vertex_two_structsOutput { + metal::float4 member_3 [[position]]; + float _point_size [[point_size]]; +}; +vertex vertex_two_structsOutput vertex_two_structs( + uint index_1 [[vertex_id]] +, uint index_2 [[instance_id]] +) { + const Input1_ in1_ = { index_1 }; + const Input2_ in2_ = { index_2 }; + uint index = 2u; + uint _e9 = index; + return vertex_two_structsOutput { metal::float4(static_cast(in1_.index), static_cast(in2_.index), static_cast(_e9), 0.0), 1.0 }; +} diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index 91397f159..6c1dac372 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -1,23 +1,25 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 46 +; Bound: 49 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %32 "compute" %20 %23 %25 %28 %30 -OpExecutionMode %32 LocalSize 1 1 1 -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 16 +OpEntryPoint GLCompute %35 "compute" %23 %26 %28 %31 %33 +OpExecutionMode %35 LocalSize 1 1 1 OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 4 -OpMemberDecorate %13 2 Offset 8 -OpDecorate %15 ArrayStride 4 -OpDecorate %20 BuiltIn GlobalInvocationId -OpDecorate %23 BuiltIn LocalInvocationId -OpDecorate %25 BuiltIn LocalInvocationIndex -OpDecorate %28 BuiltIn WorkgroupId -OpDecorate %30 BuiltIn NumWorkgroups +OpMemberDecorate %13 1 Offset 16 +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 1 Offset 4 +OpMemberDecorate %14 2 Offset 8 +OpDecorate %16 ArrayStride 4 +OpMemberDecorate %18 0 Offset 0 +OpMemberDecorate %19 0 Offset 0 +OpDecorate %23 BuiltIn GlobalInvocationId +OpDecorate %26 BuiltIn LocalInvocationId +OpDecorate %28 BuiltIn LocalInvocationIndex +OpDecorate %31 BuiltIn WorkgroupId +OpDecorate %33 BuiltIn NumWorkgroups %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -27,42 +29,45 @@ OpDecorate %30 BuiltIn NumWorkgroups %9 = OpTypeInt 32 1 %8 = OpConstant %9 1 %10 = OpConstant %9 0 -%11 = OpTypeVector %4 4 -%12 = OpTypeStruct %11 %4 -%13 = OpTypeStruct %4 %6 %4 -%14 = OpTypeBool -%15 = OpTypeArray %6 %8 -%16 = OpTypeVector %6 3 -%18 = OpTypePointer Workgroup %15 -%17 = OpVariable %18 Workgroup -%21 = OpTypePointer Input %16 -%20 = OpVariable %21 Input -%23 = OpVariable %21 Input -%26 = OpTypePointer Input %6 -%25 = OpVariable %26 Input -%28 = OpVariable %21 Input -%30 = OpVariable %21 Input -%33 = OpTypeFunction %2 -%35 = OpTypePointer Workgroup %6 -%44 = OpConstant %6 0 -%32 = OpFunction %2 None %33 -%19 = OpLabel -%22 = OpLoad %16 %20 -%24 = OpLoad %16 %23 -%27 = OpLoad %6 %25 -%29 = OpLoad %16 %28 -%31 = OpLoad %16 %30 -OpBranch %34 -%34 = OpLabel -%36 = OpCompositeExtract %6 %22 0 -%37 = OpCompositeExtract %6 %24 0 -%38 = OpIAdd %6 %36 %37 -%39 = OpIAdd %6 %38 %27 -%40 = OpCompositeExtract %6 %29 0 +%11 = OpConstant %6 2 +%12 = OpTypeVector %4 4 +%13 = OpTypeStruct %12 %4 +%14 = OpTypeStruct %4 %6 %4 +%15 = OpTypeBool +%16 = OpTypeArray %6 %8 +%17 = OpTypeVector %6 3 +%18 = OpTypeStruct %6 +%19 = OpTypeStruct %6 +%21 = OpTypePointer Workgroup %16 +%20 = OpVariable %21 Workgroup +%24 = OpTypePointer Input %17 +%23 = OpVariable %24 Input +%26 = OpVariable %24 Input +%29 = OpTypePointer Input %6 +%28 = OpVariable %29 Input +%31 = OpVariable %24 Input +%33 = OpVariable %24 Input +%36 = OpTypeFunction %2 +%38 = OpTypePointer Workgroup %6 +%47 = OpConstant %6 0 +%35 = OpFunction %2 None %36 +%22 = OpLabel +%25 = OpLoad %17 %23 +%27 = OpLoad %17 %26 +%30 = OpLoad %6 %28 +%32 = OpLoad %17 %31 +%34 = OpLoad %17 %33 +OpBranch %37 +%37 = OpLabel +%39 = OpCompositeExtract %6 %25 0 +%40 = OpCompositeExtract %6 %27 0 %41 = OpIAdd %6 %39 %40 -%42 = OpCompositeExtract %6 %31 0 -%43 = OpIAdd %6 %41 %42 -%45 = OpAccessChain %35 %17 %44 -OpStore %45 %43 +%42 = OpIAdd %6 %41 %30 +%43 = OpCompositeExtract %6 %32 0 +%44 = OpIAdd %6 %42 %43 +%45 = OpCompositeExtract %6 %34 0 +%46 = OpIAdd %6 %44 %45 +%48 = OpAccessChain %38 %20 %47 +OpStore %48 %46 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 5e7b97af1..60e270e1c 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -1,28 +1,30 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 51 +; Bound: 54 OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %38 "fragment" %19 %22 %25 %28 %31 %33 %35 %37 -OpExecutionMode %38 OriginUpperLeft -OpExecutionMode %38 DepthReplacing -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 16 +OpEntryPoint Fragment %41 "fragment" %22 %25 %28 %31 %34 %36 %38 %40 +OpExecutionMode %41 OriginUpperLeft +OpExecutionMode %41 DepthReplacing OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 4 -OpMemberDecorate %13 2 Offset 8 -OpDecorate %15 ArrayStride 4 -OpDecorate %19 BuiltIn FragCoord -OpDecorate %22 Location 1 -OpDecorate %25 BuiltIn FrontFacing -OpDecorate %28 BuiltIn SampleId -OpDecorate %31 BuiltIn SampleMask -OpDecorate %33 BuiltIn FragDepth -OpDecorate %35 BuiltIn SampleMask -OpDecorate %37 Location 0 +OpMemberDecorate %13 1 Offset 16 +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 1 Offset 4 +OpMemberDecorate %14 2 Offset 8 +OpDecorate %16 ArrayStride 4 +OpMemberDecorate %18 0 Offset 0 +OpMemberDecorate %19 0 Offset 0 +OpDecorate %22 BuiltIn FragCoord +OpDecorate %25 Location 1 +OpDecorate %28 BuiltIn FrontFacing +OpDecorate %31 BuiltIn SampleId +OpDecorate %34 BuiltIn SampleMask +OpDecorate %36 BuiltIn FragDepth +OpDecorate %38 BuiltIn SampleMask +OpDecorate %40 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -32,50 +34,53 @@ OpDecorate %37 Location 0 %9 = OpTypeInt 32 1 %8 = OpConstant %9 1 %10 = OpConstant %9 0 -%11 = OpTypeVector %4 4 -%12 = OpTypeStruct %11 %4 -%13 = OpTypeStruct %4 %6 %4 -%14 = OpTypeBool -%15 = OpTypeArray %6 %8 -%16 = OpTypeVector %6 3 -%20 = OpTypePointer Input %11 -%19 = OpVariable %20 Input -%23 = OpTypePointer Input %4 +%11 = OpConstant %6 2 +%12 = OpTypeVector %4 4 +%13 = OpTypeStruct %12 %4 +%14 = OpTypeStruct %4 %6 %4 +%15 = OpTypeBool +%16 = OpTypeArray %6 %8 +%17 = OpTypeVector %6 3 +%18 = OpTypeStruct %6 +%19 = OpTypeStruct %6 +%23 = OpTypePointer Input %12 %22 = OpVariable %23 Input -%26 = OpTypePointer Input %14 +%26 = OpTypePointer Input %4 %25 = OpVariable %26 Input -%29 = OpTypePointer Input %6 +%29 = OpTypePointer Input %15 %28 = OpVariable %29 Input -%31 = OpVariable %29 Input -%34 = OpTypePointer Output %4 -%33 = OpVariable %34 Output -%36 = OpTypePointer Output %6 -%35 = OpVariable %36 Output -%37 = OpVariable %34 Output -%39 = OpTypeFunction %2 -%38 = OpFunction %2 None %39 -%17 = OpLabel -%21 = OpLoad %11 %19 -%24 = OpLoad %4 %22 -%18 = OpCompositeConstruct %12 %21 %24 -%27 = OpLoad %14 %25 -%30 = OpLoad %6 %28 -%32 = OpLoad %6 %31 -OpBranch %40 -%40 = OpLabel -%41 = OpShiftLeftLogical %6 %5 %30 -%42 = OpBitwiseAnd %6 %32 %41 -%43 = OpSelect %4 %27 %3 %7 -%44 = OpCompositeExtract %4 %18 1 -%45 = OpCompositeConstruct %13 %44 %42 %43 -%46 = OpCompositeExtract %4 %45 0 -OpStore %33 %46 -%47 = OpLoad %4 %33 -%48 = OpExtInst %4 %1 FClamp %47 %7 %3 -OpStore %33 %48 -%49 = OpCompositeExtract %6 %45 1 -OpStore %35 %49 -%50 = OpCompositeExtract %4 %45 2 -OpStore %37 %50 +%32 = OpTypePointer Input %6 +%31 = OpVariable %32 Input +%34 = OpVariable %32 Input +%37 = OpTypePointer Output %4 +%36 = OpVariable %37 Output +%39 = OpTypePointer Output %6 +%38 = OpVariable %39 Output +%40 = OpVariable %37 Output +%42 = OpTypeFunction %2 +%41 = OpFunction %2 None %42 +%20 = OpLabel +%24 = OpLoad %12 %22 +%27 = OpLoad %4 %25 +%21 = OpCompositeConstruct %13 %24 %27 +%30 = OpLoad %15 %28 +%33 = OpLoad %6 %31 +%35 = OpLoad %6 %34 +OpBranch %43 +%43 = OpLabel +%44 = OpShiftLeftLogical %6 %5 %33 +%45 = OpBitwiseAnd %6 %35 %44 +%46 = OpSelect %4 %30 %3 %7 +%47 = OpCompositeExtract %4 %21 1 +%48 = OpCompositeConstruct %14 %47 %45 %46 +%49 = OpCompositeExtract %4 %48 0 +OpStore %36 %49 +%50 = OpLoad %4 %36 +%51 = OpExtInst %4 %1 FClamp %50 %7 %3 +OpStore %36 %51 +%52 = OpCompositeExtract %6 %48 1 +OpStore %38 %52 +%53 = OpCompositeExtract %4 %48 2 +OpStore %40 %53 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index c51a4d563..e42d243e9 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -1,24 +1,26 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 41 +; Bound: 44 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %31 "vertex" %18 %21 %23 %25 %27 %29 -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 16 +OpEntryPoint Vertex %34 "vertex" %21 %24 %26 %28 %30 %32 OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 4 -OpMemberDecorate %13 2 Offset 8 -OpDecorate %15 ArrayStride 4 -OpDecorate %18 BuiltIn VertexIndex -OpDecorate %21 BuiltIn InstanceIndex -OpDecorate %23 Location 10 -OpDecorate %23 Flat -OpDecorate %25 BuiltIn Position -OpDecorate %27 Location 1 -OpDecorate %29 BuiltIn PointSize +OpMemberDecorate %13 1 Offset 16 +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 1 Offset 4 +OpMemberDecorate %14 2 Offset 8 +OpDecorate %16 ArrayStride 4 +OpMemberDecorate %18 0 Offset 0 +OpMemberDecorate %19 0 Offset 0 +OpDecorate %21 BuiltIn VertexIndex +OpDecorate %24 BuiltIn InstanceIndex +OpDecorate %26 Location 10 +OpDecorate %26 Flat +OpDecorate %28 BuiltIn Position +OpDecorate %30 Location 1 +OpDecorate %32 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -28,39 +30,42 @@ OpDecorate %29 BuiltIn PointSize %9 = OpTypeInt 32 1 %8 = OpConstant %9 1 %10 = OpConstant %9 0 -%11 = OpTypeVector %4 4 -%12 = OpTypeStruct %11 %4 -%13 = OpTypeStruct %4 %6 %4 -%14 = OpTypeBool -%15 = OpTypeArray %6 %8 -%16 = OpTypeVector %6 3 -%19 = OpTypePointer Input %6 -%18 = OpVariable %19 Input -%21 = OpVariable %19 Input -%23 = OpVariable %19 Input -%26 = OpTypePointer Output %11 -%25 = OpVariable %26 Output -%28 = OpTypePointer Output %4 -%27 = OpVariable %28 Output -%30 = OpTypePointer Output %4 -%29 = OpVariable %30 Output -%32 = OpTypeFunction %2 -%31 = OpFunction %2 None %32 -%17 = OpLabel -%20 = OpLoad %6 %18 -%22 = OpLoad %6 %21 -%24 = OpLoad %6 %23 -OpStore %29 %3 -OpBranch %33 -%33 = OpLabel -%34 = OpIAdd %6 %20 %22 -%35 = OpIAdd %6 %34 %24 -%36 = OpCompositeConstruct %11 %3 %3 %3 %3 -%37 = OpConvertUToF %4 %35 -%38 = OpCompositeConstruct %12 %36 %37 -%39 = OpCompositeExtract %11 %38 0 -OpStore %25 %39 -%40 = OpCompositeExtract %4 %38 1 -OpStore %27 %40 +%11 = OpConstant %6 2 +%12 = OpTypeVector %4 4 +%13 = OpTypeStruct %12 %4 +%14 = OpTypeStruct %4 %6 %4 +%15 = OpTypeBool +%16 = OpTypeArray %6 %8 +%17 = OpTypeVector %6 3 +%18 = OpTypeStruct %6 +%19 = OpTypeStruct %6 +%22 = OpTypePointer Input %6 +%21 = OpVariable %22 Input +%24 = OpVariable %22 Input +%26 = OpVariable %22 Input +%29 = OpTypePointer Output %12 +%28 = OpVariable %29 Output +%31 = OpTypePointer Output %4 +%30 = OpVariable %31 Output +%33 = OpTypePointer Output %4 +%32 = OpVariable %33 Output +%35 = OpTypeFunction %2 +%34 = OpFunction %2 None %35 +%20 = OpLabel +%23 = OpLoad %6 %21 +%25 = OpLoad %6 %24 +%27 = OpLoad %6 %26 +OpStore %32 %3 +OpBranch %36 +%36 = OpLabel +%37 = OpIAdd %6 %23 %25 +%38 = OpIAdd %6 %37 %27 +%39 = OpCompositeConstruct %12 %3 %3 %3 %3 +%40 = OpConvertUToF %4 %38 +%41 = OpCompositeConstruct %13 %39 %40 +%42 = OpCompositeExtract %12 %41 0 +OpStore %28 %42 +%43 = OpCompositeExtract %4 %41 1 +OpStore %30 %43 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm new file mode 100644 index 000000000..919bbeef6 --- /dev/null +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -0,0 +1,68 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 45 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %34 "vertex_two_structs" %24 %28 %30 %32 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 1 Offset 16 +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 1 Offset 4 +OpMemberDecorate %14 2 Offset 8 +OpDecorate %16 ArrayStride 4 +OpMemberDecorate %18 0 Offset 0 +OpMemberDecorate %19 0 Offset 0 +OpDecorate %24 BuiltIn VertexIndex +OpDecorate %28 BuiltIn InstanceIndex +OpDecorate %30 BuiltIn Position +OpDecorate %32 BuiltIn PointSize +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.0 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 1 +%7 = OpConstant %4 0.0 +%9 = OpTypeInt 32 1 +%8 = OpConstant %9 1 +%10 = OpConstant %9 0 +%11 = OpConstant %6 2 +%12 = OpTypeVector %4 4 +%13 = OpTypeStruct %12 %4 +%14 = OpTypeStruct %4 %6 %4 +%15 = OpTypeBool +%16 = OpTypeArray %6 %8 +%17 = OpTypeVector %6 3 +%18 = OpTypeStruct %6 +%19 = OpTypeStruct %6 +%21 = OpTypePointer Function %6 +%25 = OpTypePointer Input %6 +%24 = OpVariable %25 Input +%28 = OpVariable %25 Input +%31 = OpTypePointer Output %12 +%30 = OpVariable %31 Output +%33 = OpTypePointer Output %4 +%32 = OpVariable %33 Output +%35 = OpTypeFunction %2 +%36 = OpTypePointer Workgroup %16 +%34 = OpFunction %2 None %35 +%22 = OpLabel +%20 = OpVariable %21 Function %11 +%26 = OpLoad %6 %24 +%23 = OpCompositeConstruct %18 %26 +%29 = OpLoad %6 %28 +%27 = OpCompositeConstruct %19 %29 +OpStore %32 %3 +OpBranch %37 +%37 = OpLabel +%38 = OpCompositeExtract %6 %23 0 +%39 = OpConvertUToF %4 %38 +%40 = OpCompositeExtract %6 %27 0 +%41 = OpConvertUToF %4 %40 +%42 = OpLoad %6 %20 +%43 = OpConvertUToF %4 %42 +%44 = OpCompositeConstruct %12 %39 %41 %43 %7 +OpStore %30 %44 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index 7d40bb321..ad24717f3 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -9,6 +9,14 @@ struct FragmentOutput { @location(0) color: f32; }; +struct Input1_ { + @builtin(vertex_index) index: u32; +}; + +struct Input2_ { + @builtin(instance_index) index: u32; +}; + var output: array; @stage(vertex) @@ -29,3 +37,11 @@ fn compute(@builtin(global_invocation_id) global_id: vec3, @builtin(local_i output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x); return; } + +@stage(vertex) +fn vertex_two_structs(in1_: Input1_, in2_: Input2_) -> @builtin(position) vec4 { + var index: u32 = 2u; + + let _e9: u32 = index; + return vec4(f32(in1_.index), f32(in2_.index), f32(_e9), 0.0); +} From 1d3fb26ffde13f512869092c9724d3cd9bfe2eb7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 8 Mar 2022 20:02:20 -0800 Subject: [PATCH 1619/2212] Actually test push constants to be used (#1767) --- src/back/msl/writer.rs | 5 +- tests/in/extra.param.ron | 6 +- tests/in/extra.wgsl | 2 +- tests/out/msl/extra.msl | 4 +- tests/out/spv/extra.spvasm | 112 +++++++++++++++++++------------------ tests/out/wgsl/extra.wgsl | 3 +- 6 files changed, 72 insertions(+), 60 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 076a37bd1..3fd0355a3 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -418,7 +418,10 @@ impl crate::AddressSpace { // may end up with "const" even if the binding is read-write, // and that should be OK. Self::Storage { .. } | Self::Private | Self::WorkGroup => true, - Self::Uniform | Self::PushConstant | Self::Handle | Self::Function => false, + // These translate to `constant` address space, no need for qualifiers. + Self::Uniform | Self::PushConstant => false, + // Not applicable. + Self::Handle | Self::Function => false, } } diff --git a/tests/in/extra.param.ron b/tests/in/extra.param.ron index c003cf469..ba9e08759 100644 --- a/tests/in/extra.param.ron +++ b/tests/in/extra.param.ron @@ -5,7 +5,11 @@ ), msl: ( lang_version: (2, 2), - per_stage_map: (), + per_stage_map: ( + fs: ( + push_constant_buffer: Some(1), + ), + ), inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index c96307806..e8a858cc1 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -11,7 +11,7 @@ struct FragmentIn { @stage(fragment) fn main(in: FragmentIn) -> @location(0) vec4 { - if in.primitive_index % 2u == 0u { + if in.primitive_index == pc.index { return in.color; } else { return vec4(vec3(1.0) - in.color.rgb, in.color.a); diff --git a/tests/out/msl/extra.msl b/tests/out/msl/extra.msl index 867c7e5a0..8288dfad9 100644 --- a/tests/out/msl/extra.msl +++ b/tests/out/msl/extra.msl @@ -23,9 +23,11 @@ struct main_Output { fragment main_Output main_( main_Input varyings [[stage_in]] , uint primitive_index [[primitive_id]] +, constant PushConstants& pc [[buffer(1)]] ) { const FragmentIn in = { varyings.color, primitive_index }; - if ((in.primitive_index % 2u) == 0u) { + uint _e4 = pc.index; + if (in.primitive_index == _e4) { return main_Output { in.color }; } else { return main_Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) }; diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index 281ca0edf..bf0f92e7b 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -1,73 +1,75 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 46 +; Bound: 48 OpCapability Shader OpCapability Float64 OpCapability Geometry %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %26 "main" %18 %21 %24 -OpExecutionMode %26 OriginUpperLeft +OpEntryPoint Fragment %24 "main" %16 %19 %22 +OpExecutionMode %24 OriginUpperLeft +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %8 1 Offset 16 OpMemberDecorate %10 0 Offset 0 OpMemberDecorate %10 1 Offset 16 +OpDecorate %12 Block OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 16 -OpDecorate %14 Block -OpMemberDecorate %14 0 Offset 0 -OpDecorate %18 Location 0 -OpDecorate %21 BuiltIn PrimitiveId -OpDecorate %24 Location 0 +OpDecorate %16 Location 0 +OpDecorate %19 BuiltIn PrimitiveId +OpDecorate %22 Location 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpConstant %4 2 -%5 = OpConstant %4 0 -%7 = OpTypeFloat 32 -%6 = OpConstant %7 1.0 -%9 = OpTypeFloat 64 -%8 = OpTypeVector %9 2 -%10 = OpTypeStruct %4 %8 -%11 = OpTypeVector %7 4 -%12 = OpTypeStruct %11 %4 -%14 = OpTypeStruct %10 -%15 = OpTypePointer PushConstant %14 -%13 = OpVariable %15 PushConstant -%19 = OpTypePointer Input %11 -%18 = OpVariable %19 Input -%22 = OpTypePointer Input %4 -%21 = OpVariable %22 Input -%25 = OpTypePointer Output %11 -%24 = OpVariable %25 Output -%27 = OpTypeFunction %2 -%28 = OpTypePointer PushConstant %10 -%32 = OpTypeBool -%38 = OpTypeVector %7 3 -%26 = OpFunction %2 None %27 -%16 = OpLabel -%20 = OpLoad %11 %18 -%23 = OpLoad %4 %21 -%17 = OpCompositeConstruct %12 %20 %23 +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.0 +%5 = OpTypeInt 32 0 +%7 = OpTypeFloat 64 +%6 = OpTypeVector %7 2 +%8 = OpTypeStruct %5 %6 +%9 = OpTypeVector %4 4 +%10 = OpTypeStruct %9 %5 +%12 = OpTypeStruct %8 +%13 = OpTypePointer PushConstant %12 +%11 = OpVariable %13 PushConstant +%17 = OpTypePointer Input %9 +%16 = OpVariable %17 Input +%20 = OpTypePointer Input %5 +%19 = OpVariable %20 Input +%23 = OpTypePointer Output %9 +%22 = OpVariable %23 Output +%25 = OpTypeFunction %2 +%26 = OpTypePointer PushConstant %8 +%27 = OpConstant %5 0 +%31 = OpTypePointer PushConstant %5 +%34 = OpTypeBool +%40 = OpTypeVector %4 3 +%24 = OpFunction %2 None %25 +%14 = OpLabel +%18 = OpLoad %9 %16 +%21 = OpLoad %5 %19 +%15 = OpCompositeConstruct %10 %18 %21 +%28 = OpAccessChain %26 %11 %27 OpBranch %29 %29 = OpLabel -%30 = OpCompositeExtract %4 %17 1 -%31 = OpUMod %4 %30 %3 -%33 = OpIEqual %32 %31 %5 -OpSelectionMerge %34 None -OpBranchConditional %33 %35 %36 -%35 = OpLabel -%37 = OpCompositeExtract %11 %17 0 -OpStore %24 %37 +%30 = OpCompositeExtract %5 %15 1 +%32 = OpAccessChain %31 %28 %27 +%33 = OpLoad %5 %32 +%35 = OpIEqual %34 %30 %33 +OpSelectionMerge %36 None +OpBranchConditional %35 %37 %38 +%37 = OpLabel +%39 = OpCompositeExtract %9 %15 0 +OpStore %22 %39 +OpReturn +%38 = OpLabel +%41 = OpCompositeConstruct %40 %3 %3 %3 +%42 = OpCompositeExtract %9 %15 0 +%43 = OpVectorShuffle %40 %42 %42 0 1 2 +%44 = OpFSub %40 %41 %43 +%45 = OpCompositeExtract %9 %15 0 +%46 = OpCompositeExtract %4 %45 3 +%47 = OpCompositeConstruct %9 %44 %46 +OpStore %22 %47 OpReturn %36 = OpLabel -%39 = OpCompositeConstruct %38 %6 %6 %6 -%40 = OpCompositeExtract %11 %17 0 -%41 = OpVectorShuffle %38 %40 %40 0 1 2 -%42 = OpFSub %38 %39 %41 -%43 = OpCompositeExtract %11 %17 0 -%44 = OpCompositeExtract %7 %43 3 -%45 = OpCompositeConstruct %11 %42 %44 -OpStore %24 %45 -OpReturn -%34 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index 6db9c1923..e1aaa9c01 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -12,7 +12,8 @@ var pc: PushConstants; @stage(fragment) fn main(in: FragmentIn) -> @location(0) vec4 { - if ((in.primitive_index % 2u) == 0u) { + let _e4 = pc.index; + if (in.primitive_index == _e4) { return in.color; } else { return vec4((vec3(1.0) - in.color.xyz), in.color.w); From 8344951ebe3988723ba7844f64f1e7312b51fefb Mon Sep 17 00:00:00 2001 From: hatoo Date: Wed, 9 Mar 2022 16:59:03 +0900 Subject: [PATCH 1620/2212] [glsl-out] Write constant sized array type for uniform --- src/back/glsl/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 76c528782..c8dabbe58 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -135,6 +135,12 @@ impl<'a> GlobalTypeKind<'a> { size: crate::ArraySize::Dynamic, .. } => Self::WrappedStruct, + // Naga IR permits globals to be constant sized arrays. Render + // these in GLSL as uniforms. + crate::TypeInner::Array { + size: crate::ArraySize::Constant(..), + .. + } => Self::WrappedStruct, _ => Self::Other, } } From ae282703e2b8de92b03586e35f7013709c0887c6 Mon Sep 17 00:00:00 2001 From: hatoo Date: Wed, 9 Mar 2022 17:01:56 +0900 Subject: [PATCH 1621/2212] Update test case from wgpu's shadow example --- tests/in/shadow.wgsl | 116 +++- tests/out/glsl/shadow.fs_main.Fragment.glsl | 60 +- ...adow.fs_main_without_storage.Fragment.glsl | 79 +++ tests/out/glsl/shadow.vs_bake.Vertex.glsl | 38 ++ tests/out/glsl/shadow.vs_main.Vertex.glsl | 51 ++ tests/out/hlsl/shadow.hlsl | 133 +++- tests/out/hlsl/shadow.hlsl.config | 4 +- tests/out/msl/shadow.msl | 170 ++++- tests/out/spv/shadow.spvasm | 613 ++++++++++++------ tests/out/wgsl/shadow.wgsl | 118 +++- 10 files changed, 1063 insertions(+), 319 deletions(-) create mode 100644 tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl create mode 100644 tests/out/glsl/shadow.vs_bake.Vertex.glsl create mode 100644 tests/out/glsl/shadow.vs_main.Vertex.glsl diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index c50769d11..088608378 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -1,61 +1,115 @@ struct Globals { + view_proj: mat4x4; num_lights: vec4; }; -@group(0) @binding(0) +@group(0) +@binding(0) var u_globals: Globals; +struct Entity { + world: mat4x4; + color: vec4; +}; + +@group(1) +@binding(0) +var u_entity: Entity; + +@stage(vertex) +fn vs_bake(@location(0) position: vec4) -> @builtin(position) vec4 { + return u_globals.view_proj * u_entity.world * vec4(position); +} + +struct VertexOutput { + @builtin(position) proj_position: vec4; + @location(0) world_normal: vec3; + @location(1) world_position: vec4; +}; + +@stage(vertex) +fn vs_main( + @location(0) position: vec4, + @location(1) normal: vec4, +) -> VertexOutput { + let w = u_entity.world; + let world_pos = u_entity.world * vec4(position); + var out: VertexOutput; + out.world_normal = mat3x3(w.x.xyz, w.y.xyz, w.z.xyz) * vec3(normal.xyz); + out.world_position = world_pos; + out.proj_position = u_globals.view_proj * world_pos; + return out; +} + +// fragment shader + struct Light { proj: mat4x4; pos: vec4; color: vec4; }; -struct Lights { - data: array; -}; - -@group(0) @binding(1) -var s_lights: Lights; -@group(0) @binding(2) +@group(0) +@binding(1) +var s_lights: array; +@group(0) +@binding(1) +var u_lights: array; // Used when storage types are not supported +@group(0) +@binding(2) var t_shadow: texture_depth_2d_array; -@group(0) @binding(3) +@group(0) +@binding(3) var sampler_shadow: sampler_comparison; fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { - if homogeneous_coords.w <= 0.0 { + if (homogeneous_coords.w <= 0.0) { return 1.0; } + // compensate for the Y-flip difference between the NDC and texture coordinates let flip_correction = vec2(0.5, -0.5); - let light_local = homogeneous_coords.xy * flip_correction / homogeneous_coords.w + vec2(0.5, 0.5); - return textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z / homogeneous_coords.w); + // compute texture coordinates for shadow lookup + let proj_correction = 1.0 / homogeneous_coords.w; + let light_local = homogeneous_coords.xy * flip_correction * proj_correction + vec2(0.5, 0.5); + // do the lookup, using HW PCF and comparison + return textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z * proj_correction); } let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); let c_max_lights: u32 = 10u; @stage(fragment) -fn fs_main( - @location(0) raw_normal: vec3, - @location(1) position: vec4 -) -> @location(0) vec4 { - let normal: vec3 = normalize(raw_normal); +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + let normal = normalize(in.world_normal); // accumulate color - var color = c_ambient; - var i: u32 = 0u; - loop { - if i >= min(u_globals.num_lights.x, c_max_lights) { - break; - } - let light = s_lights.data[i]; - let shadow = fetch_shadow(i, light.proj * position); - let light_dir = normalize(light.pos.xyz - position.xyz); + var color: vec3 = c_ambient; + for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i += 1u) { + let light = s_lights[i]; + // project into the light space + let shadow = fetch_shadow(i, light.proj * in.world_position); + // compute Lambertian diffuse term + let light_dir = normalize(light.pos.xyz - in.world_position.xyz); let diffuse = max(0.0, dot(normal, light_dir)); - color = color + shadow * diffuse * light.color.xyz; - continuing { - i = i + 1u; - } + // add light contribution + color += shadow * diffuse * light.color.xyz; } // multiply the light by material color - return vec4(color, 1.0); + return vec4(color, 1.0) * u_entity.color; +} + +// The fragment entrypoint used when storage buffers are not available for the lights +@stage(fragment) +fn fs_main_without_storage(in: VertexOutput) -> @location(0) vec4 { + let normal = normalize(in.world_normal); + var color: vec3 = c_ambient; + for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i += 1u) { + // This line is the only difference from the entrypoint above. It uses the lights + // uniform instead of the lights storage buffer + let light = u_lights[i]; + let shadow = fetch_shadow(i, light.proj * in.world_position); + let light_dir = normalize(light.pos.xyz - in.world_position.xyz); + let diffuse = max(0.0, dot(normal, light_dir)); + color += shadow * diffuse * light.color.xyz; + } + return vec4(color, 1.0) * u_entity.color; } diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 3e5562a71..fef409f10 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -4,8 +4,18 @@ precision highp float; precision highp int; struct Globals { + mat4x4 view_proj; uvec4 num_lights; }; +struct Entity { + mat4x4 world; + vec4 color; +}; +struct VertexOutput { + vec4 proj_position; + vec3 world_normal; + vec4 world_position; +}; struct Light { mat4x4 proj; vec4 pos; @@ -13,9 +23,9 @@ struct Light { }; uniform Globals_block_0Fragment { Globals _group_0_binding_0_fs; }; -layout(std430) readonly buffer Lights_block_1Fragment { - Light data[]; -} _group_0_binding_1_fs; +uniform Entity_block_1Fragment { Entity _group_1_binding_0_fs; }; + +layout(std430) readonly buffer type_6_block_2Fragment { Light _group_0_binding_1_fs[]; }; uniform highp sampler2DArrayShadow _group_0_binding_2_fs; @@ -28,40 +38,42 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { return 1.0; } vec2 flip_correction = vec2(0.5, -0.5); - vec2 light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - float _e26 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z / homogeneous_coords.w)), vec2(0.0), vec2(0.0)); - return _e26; + float proj_correction = (1.0 / homogeneous_coords.w); + vec2 light_local = (((homogeneous_coords.xy * flip_correction) * proj_correction) + vec2(0.5, 0.5)); + float _e28 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z * proj_correction)), vec2(0.0), vec2(0.0)); + return _e28; } void main() { - vec3 raw_normal = _vs2fs_location0; - vec4 position = _vs2fs_location1; + VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); vec3 color = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i = 0u; - vec3 normal = normalize(raw_normal); + vec3 normal_1 = normalize(in_.world_normal); bool loop_init = true; while(true) { if (!loop_init) { - uint _e40 = i; - i = (_e40 + 1u); + uint _e20 = i; + i = (_e20 + 1u); } loop_init = false; - uint _e12 = i; - uint _e15 = _group_0_binding_0_fs.num_lights.x; - if ((_e12 >= min(_e15, 10u))) { + uint _e14 = i; + uint _e17 = _group_0_binding_0_fs.num_lights.x; + if ((_e14 < min(_e17, 10u))) { + } else { break; } - uint _e19 = i; - Light light = _group_0_binding_1_fs.data[_e19]; - uint _e22 = i; - float _e25 = fetch_shadow(_e22, (light.proj * position)); - vec3 light_dir = normalize((light.pos.xyz - position.xyz)); - float diffuse = max(0.0, dot(normal, light_dir)); - vec3 _e34 = color; - color = (_e34 + ((_e25 * diffuse) * light.color.xyz)); + uint _e23 = i; + Light light = _group_0_binding_1_fs[_e23]; + uint _e26 = i; + float _e30 = fetch_shadow(_e26, (light.proj * in_.world_position)); + vec3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); + float diffuse = max(0.0, dot(normal_1, light_dir)); + vec3 _e40 = color; + color = (_e40 + ((_e30 * diffuse) * light.color.xyz)); } - vec3 _e43 = color; - _fs2p_location0 = vec4(_e43, 1.0); + vec3 _e46 = color; + vec4 _e50 = _group_1_binding_0_fs.color; + _fs2p_location0 = (vec4(_e46, 1.0) * _e50); return; } diff --git a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl new file mode 100644 index 000000000..43f02cae1 --- /dev/null +++ b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl @@ -0,0 +1,79 @@ +#version 310 es + +precision highp float; +precision highp int; + +struct Globals { + mat4x4 view_proj; + uvec4 num_lights; +}; +struct Entity { + mat4x4 world; + vec4 color; +}; +struct VertexOutput { + vec4 proj_position; + vec3 world_normal; + vec4 world_position; +}; +struct Light { + mat4x4 proj; + vec4 pos; + vec4 color; +}; +uniform Globals_block_0Fragment { Globals _group_0_binding_0_fs; }; + +uniform Entity_block_1Fragment { Entity _group_1_binding_0_fs; }; + +uniform type_7_block_2Fragment { Light _group_0_binding_1_fs[10]; }; + +uniform highp sampler2DArrayShadow _group_0_binding_2_fs; + +layout(location = 0) smooth in vec3 _vs2fs_location0; +layout(location = 1) smooth in vec4 _vs2fs_location1; +layout(location = 0) out vec4 _fs2p_location0; + +float fetch_shadow(uint light_id, vec4 homogeneous_coords) { + if ((homogeneous_coords.w <= 0.0)) { + return 1.0; + } + vec2 flip_correction = vec2(0.5, -0.5); + float proj_correction = (1.0 / homogeneous_coords.w); + vec2 light_local = (((homogeneous_coords.xy * flip_correction) * proj_correction) + vec2(0.5, 0.5)); + float _e28 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z * proj_correction)), vec2(0.0), vec2(0.0)); + return _e28; +} + +void main() { + VertexOutput in_1 = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); + vec3 color_1 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + uint i_1 = 0u; + vec3 normal_1 = normalize(in_1.world_normal); + bool loop_init = true; + while(true) { + if (!loop_init) { + uint _e20 = i_1; + i_1 = (_e20 + 1u); + } + loop_init = false; + uint _e14 = i_1; + uint _e17 = _group_0_binding_0_fs.num_lights.x; + if ((_e14 < min(_e17, 10u))) { + } else { + break; + } + uint _e23 = i_1; + Light light = _group_0_binding_1_fs[_e23]; + uint _e26 = i_1; + float _e30 = fetch_shadow(_e26, (light.proj * in_1.world_position)); + vec3 light_dir = normalize((light.pos.xyz - in_1.world_position.xyz)); + float diffuse = max(0.0, dot(normal_1, light_dir)); + vec3 _e40 = color_1; + color_1 = (_e40 + ((_e30 * diffuse) * light.color.xyz)); + } + vec3 _e46 = color_1; + vec4 _e50 = _group_1_binding_0_fs.color; + _fs2p_location0 = (vec4(_e46, 1.0) * _e50); + return; +} + diff --git a/tests/out/glsl/shadow.vs_bake.Vertex.glsl b/tests/out/glsl/shadow.vs_bake.Vertex.glsl new file mode 100644 index 000000000..6f6812a25 --- /dev/null +++ b/tests/out/glsl/shadow.vs_bake.Vertex.glsl @@ -0,0 +1,38 @@ +#version 310 es + +precision highp float; +precision highp int; + +struct Globals { + mat4x4 view_proj; + uvec4 num_lights; +}; +struct Entity { + mat4x4 world; + vec4 color; +}; +struct VertexOutput { + vec4 proj_position; + vec3 world_normal; + vec4 world_position; +}; +struct Light { + mat4x4 proj; + vec4 pos; + vec4 color; +}; +uniform Globals_block_0Vertex { Globals _group_0_binding_0_vs; }; + +uniform Entity_block_1Vertex { Entity _group_1_binding_0_vs; }; + +layout(location = 0) in ivec4 _p2vs_location0; + +void main() { + ivec4 position = _p2vs_location0; + mat4x4 _e4 = _group_0_binding_0_vs.view_proj; + mat4x4 _e6 = _group_1_binding_0_vs.world; + gl_Position = ((_e4 * _e6) * vec4(position)); + gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); + return; +} + diff --git a/tests/out/glsl/shadow.vs_main.Vertex.glsl b/tests/out/glsl/shadow.vs_main.Vertex.glsl new file mode 100644 index 000000000..a2e09ceec --- /dev/null +++ b/tests/out/glsl/shadow.vs_main.Vertex.glsl @@ -0,0 +1,51 @@ +#version 310 es + +precision highp float; +precision highp int; + +struct Globals { + mat4x4 view_proj; + uvec4 num_lights; +}; +struct Entity { + mat4x4 world; + vec4 color; +}; +struct VertexOutput { + vec4 proj_position; + vec3 world_normal; + vec4 world_position; +}; +struct Light { + mat4x4 proj; + vec4 pos; + vec4 color; +}; +uniform Globals_block_0Vertex { Globals _group_0_binding_0_vs; }; + +uniform Entity_block_1Vertex { Entity _group_1_binding_0_vs; }; + +layout(location = 0) in ivec4 _p2vs_location0; +layout(location = 1) in ivec4 _p2vs_location1; +layout(location = 0) smooth out vec3 _vs2fs_location0; +layout(location = 1) smooth out vec4 _vs2fs_location1; + +void main() { + ivec4 position_1 = _p2vs_location0; + ivec4 normal = _p2vs_location1; + VertexOutput out_ = VertexOutput(vec4(0.0), vec3(0.0), vec4(0.0)); + mat4x4 w = _group_1_binding_0_vs.world; + mat4x4 _e7 = _group_1_binding_0_vs.world; + vec4 world_pos = (_e7 * vec4(position_1)); + out_.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); + out_.world_position = world_pos; + mat4x4 _e25 = _group_0_binding_0_vs.view_proj; + out_.proj_position = (_e25 * world_pos); + VertexOutput _e27 = out_; + gl_Position = _e27.proj_position; + _vs2fs_location0 = _e27.world_normal; + _vs2fs_location1 = _e27.world_position; + gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); + return; +} + diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index e0d509c72..5b0ef63fa 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -2,9 +2,21 @@ static const float3 c_ambient = float3(0.05000000074505806, 0.05000000074505806, static const uint c_max_lights = 10; struct Globals { + row_major float4x4 view_proj; uint4 num_lights; }; +struct Entity { + row_major float4x4 world; + float4 color; +}; + +struct VertexOutput { + float4 proj_position : SV_Position; + linear float3 world_normal : LOC0; + linear float4 world_position : LOC1; +}; + struct Light { row_major float4x4 proj; float4 pos; @@ -12,13 +24,28 @@ struct Light { }; cbuffer u_globals : register(b0) { Globals u_globals; } +cbuffer u_entity : register(b0, space1) { Entity u_entity; } ByteAddressBuffer s_lights : register(t1); +cbuffer u_lights : register(b1) { Light u_lights[10]; } Texture2DArray t_shadow : register(t2); SamplerComparisonState sampler_shadow : register(s3); +struct VertexOutput_vs_main { + float3 world_normal : LOC0; + float4 world_position : LOC1; + float4 proj_position : SV_Position; +}; + struct FragmentInput_fs_main { - float3 raw_normal_1 : LOC0; - float4 position_1 : LOC1; + float3 world_normal_1 : LOC0; + float4 world_position_1 : LOC1; + float4 proj_position_1 : SV_Position; +}; + +struct FragmentInput_fs_main_without_storage { + float3 world_normal_2 : LOC0; + float4 world_position_2 : LOC1; + float4 proj_position_2 : SV_Position; }; float fetch_shadow(uint light_id, float4 homogeneous_coords) @@ -27,40 +54,100 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords) return 1.0; } float2 flip_correction = float2(0.5, -0.5); - float2 light_local = (((homogeneous_coords.xy * flip_correction) / float2(homogeneous_coords.w.xx)) + float2(0.5, 0.5)); - float _expr26 = t_shadow.SampleCmpLevelZero(sampler_shadow, float3(light_local, int(light_id)), (homogeneous_coords.z / homogeneous_coords.w)); - return _expr26; + float proj_correction = (1.0 / homogeneous_coords.w); + float2 light_local = (((homogeneous_coords.xy * flip_correction) * proj_correction) + float2(0.5, 0.5)); + float _expr28 = t_shadow.SampleCmpLevelZero(sampler_shadow, float3(light_local, int(light_id)), (homogeneous_coords.z * proj_correction)); + return _expr28; +} + +float4 vs_bake(int4 position : LOC0) : SV_Position +{ + float4x4 _expr4 = u_globals.view_proj; + float4x4 _expr6 = u_entity.world; + return mul(float4(position), mul(_expr6, _expr4)); +} + +VertexOutput_vs_main vs_main(int4 position_1 : LOC0, int4 normal : LOC1) +{ + VertexOutput out_ = (VertexOutput)0; + + float4x4 w = u_entity.world; + float4x4 _expr7 = u_entity.world; + float4 world_pos = mul(float4(position_1), _expr7); + out_.world_normal = mul(float3(normal.xyz), float3x3(w[0].xyz, w[1].xyz, w[2].xyz)); + out_.world_position = world_pos; + float4x4 _expr25 = u_globals.view_proj; + out_.proj_position = mul(world_pos, _expr25); + VertexOutput _expr27 = out_; + const VertexOutput vertexoutput = _expr27; + const VertexOutput_vs_main vertexoutput_1 = { vertexoutput.world_normal, vertexoutput.world_position, vertexoutput.proj_position }; + return vertexoutput_1; } float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { - float3 raw_normal = fragmentinput_fs_main.raw_normal_1; - float4 position = fragmentinput_fs_main.position_1; + VertexOutput in_ = { fragmentinput_fs_main.proj_position_1, fragmentinput_fs_main.world_normal_1, fragmentinput_fs_main.world_position_1 }; float3 color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i = 0u; - float3 normal = normalize(raw_normal); + float3 normal_1 = normalize(in_.world_normal); bool loop_init = true; while(true) { if (!loop_init) { - uint _expr40 = i; - i = (_expr40 + 1u); + uint _expr20 = i; + i = (_expr20 + 1u); } loop_init = false; - uint _expr12 = i; - uint _expr15 = u_globals.num_lights.x; - if ((_expr12 >= min(_expr15, c_max_lights))) { + uint _expr14 = i; + uint _expr17 = u_globals.num_lights.x; + if ((_expr14 < min(_expr17, c_max_lights))) { + } else { break; } - uint _expr19 = i; - Light light = {float4x4(asfloat(s_lights.Load4(_expr19*96+0+0+0)), asfloat(s_lights.Load4(_expr19*96+0+0+16)), asfloat(s_lights.Load4(_expr19*96+0+0+32)), asfloat(s_lights.Load4(_expr19*96+0+0+48))), asfloat(s_lights.Load4(_expr19*96+0+64)), asfloat(s_lights.Load4(_expr19*96+0+80))}; - uint _expr22 = i; - const float _e25 = fetch_shadow(_expr22, mul(position, light.proj)); - float3 light_dir = normalize((light.pos.xyz - position.xyz)); - float diffuse = max(0.0, dot(normal, light_dir)); - float3 _expr34 = color; - color = (_expr34 + ((_e25 * diffuse) * light.color.xyz)); + uint _expr23 = i; + Light light = {float4x4(asfloat(s_lights.Load4(_expr23*96+0+0)), asfloat(s_lights.Load4(_expr23*96+0+16)), asfloat(s_lights.Load4(_expr23*96+0+32)), asfloat(s_lights.Load4(_expr23*96+0+48))), asfloat(s_lights.Load4(_expr23*96+64)), asfloat(s_lights.Load4(_expr23*96+80))}; + uint _expr26 = i; + const float _e30 = fetch_shadow(_expr26, mul(in_.world_position, light.proj)); + float3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); + float diffuse = max(0.0, dot(normal_1, light_dir)); + float3 _expr40 = color; + color = (_expr40 + ((_e30 * diffuse) * light.color.xyz)); } - float3 _expr43 = color; - return float4(_expr43, 1.0); + float3 _expr46 = color; + float4 _expr50 = u_entity.color; + return (float4(_expr46, 1.0) * _expr50); +} + +float4 fs_main_without_storage(FragmentInput_fs_main_without_storage fragmentinput_fs_main_without_storage) : SV_Target0 +{ + VertexOutput in_1 = { fragmentinput_fs_main_without_storage.proj_position_2, fragmentinput_fs_main_without_storage.world_normal_2, fragmentinput_fs_main_without_storage.world_position_2 }; + float3 color_1 = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + uint i_1 = 0u; + + float3 normal_2 = normalize(in_1.world_normal); + bool loop_init_1 = true; + while(true) { + if (!loop_init_1) { + uint _expr20 = i_1; + i_1 = (_expr20 + 1u); + } + loop_init_1 = false; + uint _expr14 = i_1; + uint _expr17 = u_globals.num_lights.x; + if ((_expr14 < min(_expr17, c_max_lights))) { + } else { + break; + } + uint _expr23 = i_1; + Light light_1 = u_lights[_expr23]; + uint _expr26 = i_1; + const float _e30 = fetch_shadow(_expr26, mul(in_1.world_position, light_1.proj)); + float3 light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); + float diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); + float3 _expr40 = color_1; + color_1 = (_expr40 + ((_e30 * diffuse_1) * light_1.color.xyz)); + } + float3 _expr46 = color_1; + float4 _expr50 = u_entity.color; + return (float4(_expr46, 1.0) * _expr50); } diff --git a/tests/out/hlsl/shadow.hlsl.config b/tests/out/hlsl/shadow.hlsl.config index b9f047558..2ed1c8fd7 100644 --- a/tests/out/hlsl/shadow.hlsl.config +++ b/tests/out/hlsl/shadow.hlsl.config @@ -1,3 +1,3 @@ -vertex=() -fragment=(fs_main:ps_5_1 ) +vertex=(vs_bake:vs_5_1 vs_main:vs_5_1 ) +fragment=(fs_main:ps_5_1 fs_main_without_storage:ps_5_1 ) compute=() diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 5bdd3ba97..26af57fd2 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -5,21 +5,31 @@ using metal::uint; struct _mslBufferSizes { - uint size1; + uint size2; }; constexpr constant unsigned c_max_lights = 10u; struct Globals { + metal::float4x4 view_proj; metal::uint4 num_lights; }; +struct Entity { + metal::float4x4 world; + metal::float4 color; +}; +struct VertexOutput { + metal::float4 proj_position; + metal::float3 world_normal; + metal::float4 world_position; +}; struct Light { metal::float4x4 proj; metal::float4 pos; metal::float4 color; }; -typedef Light type_3[1]; -struct Lights { - type_3 data; +typedef Light type_6[1]; +struct type_7 { + Light inner[10]; }; constant metal::float3 c_ambient = {0.05000000074505806, 0.05000000074505806, 0.05000000074505806}; @@ -33,52 +43,152 @@ float fetch_shadow( return 1.0; } metal::float2 flip_correction = metal::float2(0.5, -0.5); - metal::float2 light_local = ((homogeneous_coords.xy * flip_correction) / metal::float2(homogeneous_coords.w)) + metal::float2(0.5, 0.5); - float _e26 = t_shadow.sample_compare(sampler_shadow, light_local, static_cast(light_id), homogeneous_coords.z / homogeneous_coords.w); - return _e26; + float proj_correction = 1.0 / homogeneous_coords.w; + metal::float2 light_local = ((homogeneous_coords.xy * flip_correction) * proj_correction) + metal::float2(0.5, 0.5); + float _e28 = t_shadow.sample_compare(sampler_shadow, light_local, static_cast(light_id), homogeneous_coords.z * proj_correction); + return _e28; } +struct vs_bakeInput { + metal::int4 position [[attribute(0)]]; +}; +struct vs_bakeOutput { + metal::float4 member [[position]]; +}; +vertex vs_bakeOutput vs_bake( + vs_bakeInput varyings [[stage_in]] +, constant Globals& u_globals [[user(fake0)]] +, constant Entity& u_entity [[user(fake0)]] +) { + const auto position = varyings.position; + metal::float4x4 _e4 = u_globals.view_proj; + metal::float4x4 _e6 = u_entity.world; + return vs_bakeOutput { (_e4 * _e6) * static_cast(position) }; +} + + +struct vs_mainInput { + metal::int4 position_1 [[attribute(0)]]; + metal::int4 normal [[attribute(1)]]; +}; +struct vs_mainOutput { + metal::float4 proj_position [[position]]; + metal::float3 world_normal [[user(loc0), center_perspective]]; + metal::float4 world_position [[user(loc1), center_perspective]]; +}; +vertex vs_mainOutput vs_main( + vs_mainInput varyings_1 [[stage_in]] +, constant Globals& u_globals [[user(fake0)]] +, constant Entity& u_entity [[user(fake0)]] +) { + const auto position_1 = varyings_1.position_1; + const auto normal = varyings_1.normal; + VertexOutput out; + metal::float4x4 w = u_entity.world; + metal::float4x4 _e7 = u_entity.world; + metal::float4 world_pos = _e7 * static_cast(position_1); + out.world_normal = metal::float3x3(w[0].xyz, w[1].xyz, w[2].xyz) * static_cast(normal.xyz); + out.world_position = world_pos; + metal::float4x4 _e25 = u_globals.view_proj; + out.proj_position = _e25 * world_pos; + VertexOutput _e27 = out; + const auto _tmp = _e27; + return vs_mainOutput { _tmp.proj_position, _tmp.world_normal, _tmp.world_position }; +} + + struct fs_mainInput { - metal::float3 raw_normal [[user(loc0), center_perspective]]; - metal::float4 position [[user(loc1), center_perspective]]; + metal::float3 world_normal [[user(loc0), center_perspective]]; + metal::float4 world_position [[user(loc1), center_perspective]]; }; struct fs_mainOutput { - metal::float4 member [[color(0)]]; + metal::float4 member_2 [[color(0)]]; }; fragment fs_mainOutput fs_main( - fs_mainInput varyings [[stage_in]] + fs_mainInput varyings_2 [[stage_in]] +, metal::float4 proj_position [[position]] , constant Globals& u_globals [[user(fake0)]] -, device Lights const& s_lights [[user(fake0)]] +, constant Entity& u_entity [[user(fake0)]] +, device type_6 const& s_lights [[user(fake0)]] , metal::depth2d_array t_shadow [[user(fake0)]] , metal::sampler sampler_shadow [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - const auto raw_normal = varyings.raw_normal; - const auto position = varyings.position; + const VertexOutput in = { proj_position, varyings_2.world_normal, varyings_2.world_position }; metal::float3 color = c_ambient; uint i = 0u; - metal::float3 normal = metal::normalize(raw_normal); + metal::float3 normal_1 = metal::normalize(in.world_normal); bool loop_init = true; while(true) { if (!loop_init) { - uint _e40 = i; - i = _e40 + 1u; + uint _e20 = i; + i = _e20 + 1u; } loop_init = false; - uint _e12 = i; - uint _e15 = u_globals.num_lights.x; - if (_e12 >= metal::min(_e15, c_max_lights)) { + uint _e14 = i; + uint _e17 = u_globals.num_lights.x; + if (_e14 < metal::min(_e17, c_max_lights)) { + } else { break; } - uint _e19 = i; - Light light = s_lights.data[_e19]; - uint _e22 = i; - float _e25 = fetch_shadow(_e22, light.proj * position, t_shadow, sampler_shadow); - metal::float3 light_dir = metal::normalize(light.pos.xyz - position.xyz); - float diffuse = metal::max(0.0, metal::dot(normal, light_dir)); - metal::float3 _e34 = color; - color = _e34 + ((_e25 * diffuse) * light.color.xyz); + uint _e23 = i; + Light light = s_lights[_e23]; + uint _e26 = i; + float _e30 = fetch_shadow(_e26, light.proj * in.world_position, t_shadow, sampler_shadow); + metal::float3 light_dir = metal::normalize(light.pos.xyz - in.world_position.xyz); + float diffuse = metal::max(0.0, metal::dot(normal_1, light_dir)); + metal::float3 _e40 = color; + color = _e40 + ((_e30 * diffuse) * light.color.xyz); } - metal::float3 _e43 = color; - return fs_mainOutput { metal::float4(_e43, 1.0) }; + metal::float3 _e46 = color; + metal::float4 _e50 = u_entity.color; + return fs_mainOutput { metal::float4(_e46, 1.0) * _e50 }; +} + + +struct fs_main_without_storageInput { + metal::float3 world_normal [[user(loc0), center_perspective]]; + metal::float4 world_position [[user(loc1), center_perspective]]; +}; +struct fs_main_without_storageOutput { + metal::float4 member_3 [[color(0)]]; +}; +fragment fs_main_without_storageOutput fs_main_without_storage( + fs_main_without_storageInput varyings_3 [[stage_in]] +, metal::float4 proj_position_1 [[position]] +, constant Globals& u_globals [[user(fake0)]] +, constant Entity& u_entity [[user(fake0)]] +, constant type_7& u_lights [[user(fake0)]] +, metal::depth2d_array t_shadow [[user(fake0)]] +, metal::sampler sampler_shadow [[user(fake0)]] +) { + const VertexOutput in_1 = { proj_position_1, varyings_3.world_normal, varyings_3.world_position }; + metal::float3 color_1 = c_ambient; + uint i_1 = 0u; + metal::float3 normal_2 = metal::normalize(in_1.world_normal); + bool loop_init_1 = true; + while(true) { + if (!loop_init_1) { + uint _e20 = i_1; + i_1 = _e20 + 1u; + } + loop_init_1 = false; + uint _e14 = i_1; + uint _e17 = u_globals.num_lights.x; + if (_e14 < metal::min(_e17, c_max_lights)) { + } else { + break; + } + uint _e23 = i_1; + Light light_1 = u_lights.inner[_e23]; + uint _e26 = i_1; + float _e30 = fetch_shadow(_e26, light_1.proj * in_1.world_position, t_shadow, sampler_shadow); + metal::float3 light_dir_1 = metal::normalize(light_1.pos.xyz - in_1.world_position.xyz); + float diffuse_1 = metal::max(0.0, metal::dot(normal_2, light_dir_1)); + metal::float3 _e40 = color_1; + color_1 = _e40 + ((_e30 * diffuse_1) * light_1.color.xyz); + } + metal::float3 _e46 = color_1; + metal::float4 _e50 = u_entity.color; + return fs_main_without_storageOutput { metal::float4(_e46, 1.0) * _e50 }; } diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index 3d4f4119a..a6be5de2d 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,199 +1,444 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 125 +; Bound: 279 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %79 "fs_main" %71 %74 %77 -OpExecutionMode %79 OriginUpperLeft +OpEntryPoint Vertex %86 "vs_bake" %81 %84 +OpEntryPoint Vertex %114 "vs_main" %106 %108 %110 %111 %113 +OpEntryPoint Fragment %165 "fs_main" %156 %159 %162 %164 +OpEntryPoint Fragment %229 "fs_main_without_storage" %222 %224 %226 %228 +OpExecutionMode %165 OriginUpperLeft +OpExecutionMode %229 OriginUpperLeft OpSource GLSL 450 -OpName %9 "c_max_lights" -OpMemberName %14 0 "num_lights" -OpName %14 "Globals" -OpMemberName %17 0 "proj" -OpMemberName %17 1 "pos" -OpMemberName %17 2 "color" -OpName %17 "Light" -OpMemberName %19 0 "data" -OpName %19 "Lights" -OpName %24 "c_ambient" -OpName %25 "u_globals" -OpName %28 "s_lights" -OpName %30 "t_shadow" -OpName %32 "sampler_shadow" -OpName %35 "light_id" -OpName %36 "homogeneous_coords" -OpName %37 "fetch_shadow" -OpName %66 "color" -OpName %68 "i" -OpName %71 "raw_normal" -OpName %74 "position" -OpName %79 "fs_main" -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %17 0 Offset 0 -OpMemberDecorate %17 0 ColMajor -OpMemberDecorate %17 0 MatrixStride 16 -OpMemberDecorate %17 1 Offset 64 -OpMemberDecorate %17 2 Offset 80 -OpDecorate %18 ArrayStride 96 +OpName %11 "c_max_lights" +OpMemberName %18 0 "view_proj" +OpMemberName %18 1 "num_lights" +OpName %18 "Globals" +OpMemberName %19 0 "world" +OpMemberName %19 1 "color" +OpName %19 "Entity" +OpMemberName %22 0 "proj_position" +OpMemberName %22 1 "world_normal" +OpMemberName %22 2 "world_position" +OpName %22 "VertexOutput" +OpMemberName %24 0 "proj" +OpMemberName %24 1 "pos" +OpMemberName %24 2 "color" +OpName %24 "Light" +OpName %30 "c_ambient" +OpName %31 "u_globals" +OpName %34 "u_entity" +OpName %37 "s_lights" +OpName %40 "u_lights" +OpName %43 "t_shadow" +OpName %45 "sampler_shadow" +OpName %48 "light_id" +OpName %49 "homogeneous_coords" +OpName %50 "fetch_shadow" +OpName %81 "position" +OpName %86 "vs_bake" +OpName %103 "out" +OpName %106 "position" +OpName %108 "normal" +OpName %110 "proj_position" +OpName %111 "world_normal" +OpName %113 "world_position" +OpName %114 "vs_main" +OpName %151 "color" +OpName %152 "i" +OpName %156 "proj_position" +OpName %159 "world_normal" +OpName %162 "world_position" +OpName %165 "fs_main" +OpName %218 "color" +OpName %219 "i" +OpName %222 "proj_position" +OpName %224 "world_normal" +OpName %226 "world_position" +OpName %229 "fs_main_without_storage" +OpMemberDecorate %18 0 Offset 0 +OpMemberDecorate %18 0 ColMajor +OpMemberDecorate %18 0 MatrixStride 16 +OpMemberDecorate %18 1 Offset 64 OpMemberDecorate %19 0 Offset 0 -OpDecorate %25 DescriptorSet 0 -OpDecorate %25 Binding 0 -OpDecorate %26 Block -OpMemberDecorate %26 0 Offset 0 -OpDecorate %28 NonWritable -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 1 -OpDecorate %19 Block -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 2 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 3 -OpDecorate %71 Location 0 -OpDecorate %74 Location 1 -OpDecorate %77 Location 0 +OpMemberDecorate %19 0 ColMajor +OpMemberDecorate %19 0 MatrixStride 16 +OpMemberDecorate %19 1 Offset 64 +OpMemberDecorate %22 0 Offset 0 +OpMemberDecorate %22 1 Offset 16 +OpMemberDecorate %22 2 Offset 32 +OpMemberDecorate %24 0 Offset 0 +OpMemberDecorate %24 0 ColMajor +OpMemberDecorate %24 0 MatrixStride 16 +OpMemberDecorate %24 1 Offset 64 +OpMemberDecorate %24 2 Offset 80 +OpDecorate %25 ArrayStride 96 +OpDecorate %26 ArrayStride 96 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 0 +OpDecorate %32 Block +OpMemberDecorate %32 0 Offset 0 +OpDecorate %34 DescriptorSet 1 +OpDecorate %34 Binding 0 +OpDecorate %35 Block +OpMemberDecorate %35 0 Offset 0 +OpDecorate %37 NonWritable +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 1 +OpDecorate %38 Block +OpMemberDecorate %38 0 Offset 0 +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 1 +OpDecorate %41 Block +OpMemberDecorate %41 0 Offset 0 +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 2 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 3 +OpDecorate %81 Location 0 +OpDecorate %81 Flat +OpDecorate %84 BuiltIn Position +OpDecorate %106 Location 0 +OpDecorate %106 Flat +OpDecorate %108 Location 1 +OpDecorate %108 Flat +OpDecorate %110 BuiltIn Position +OpDecorate %111 Location 0 +OpDecorate %113 Location 1 +OpDecorate %156 BuiltIn FragCoord +OpDecorate %159 Location 0 +OpDecorate %162 Location 1 +OpDecorate %164 Location 0 +OpDecorate %222 BuiltIn FragCoord +OpDecorate %224 Location 0 +OpDecorate %226 Location 1 +OpDecorate %228 Location 0 %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 0.0 -%5 = OpConstant %4 1.0 -%6 = OpConstant %4 0.5 -%7 = OpConstant %4 -0.5 -%8 = OpConstant %4 0.05 -%10 = OpTypeInt 32 0 -%9 = OpConstant %10 10 -%11 = OpConstant %10 0 -%12 = OpConstant %10 1 -%13 = OpTypeVector %10 4 -%14 = OpTypeStruct %13 -%16 = OpTypeVector %4 4 +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 10 +%6 = OpTypeFloat 32 +%5 = OpConstant %6 0.0 +%7 = OpConstant %6 1.0 +%8 = OpConstant %6 0.5 +%9 = OpConstant %6 -0.5 +%10 = OpConstant %6 0.05 +%12 = OpTypeInt 32 0 +%11 = OpConstant %12 10 +%13 = OpConstant %12 0 +%14 = OpConstant %12 1 +%16 = OpTypeVector %6 4 %15 = OpTypeMatrix %16 4 -%17 = OpTypeStruct %15 %16 %16 -%18 = OpTypeRuntimeArray %17 -%19 = OpTypeStruct %18 -%20 = OpTypeImage %4 2D 1 1 0 1 Unknown -%21 = OpTypeSampler -%22 = OpTypeVector %4 2 -%23 = OpTypeVector %4 3 -%24 = OpConstantComposite %23 %8 %8 %8 -%26 = OpTypeStruct %14 -%27 = OpTypePointer Uniform %26 -%25 = OpVariable %27 Uniform -%29 = OpTypePointer StorageBuffer %19 -%28 = OpVariable %29 StorageBuffer -%31 = OpTypePointer UniformConstant %20 -%30 = OpVariable %31 UniformConstant -%33 = OpTypePointer UniformConstant %21 -%32 = OpVariable %33 UniformConstant -%38 = OpTypeFunction %4 %10 %16 -%41 = OpTypePointer Uniform %14 -%44 = OpTypeBool -%56 = OpTypeInt 32 1 -%61 = OpTypeSampledImage %20 -%67 = OpTypePointer Function %23 -%69 = OpTypePointer Function %10 -%72 = OpTypePointer Input %23 -%71 = OpVariable %72 Input -%75 = OpTypePointer Input %16 -%74 = OpVariable %75 Input -%78 = OpTypePointer Output %16 -%77 = OpVariable %78 Output -%80 = OpTypeFunction %2 -%91 = OpTypePointer Uniform %13 -%92 = OpTypePointer Uniform %10 -%99 = OpTypePointer StorageBuffer %18 -%101 = OpTypePointer StorageBuffer %17 -%37 = OpFunction %4 None %38 -%35 = OpFunctionParameter %10 -%36 = OpFunctionParameter %16 -%34 = OpLabel -%39 = OpLoad %20 %30 -%40 = OpLoad %21 %32 -OpBranch %42 -%42 = OpLabel -%43 = OpCompositeExtract %4 %36 3 -%45 = OpFOrdLessThanEqual %44 %43 %3 -OpSelectionMerge %46 None -OpBranchConditional %45 %47 %46 +%17 = OpTypeVector %12 4 +%18 = OpTypeStruct %15 %17 +%19 = OpTypeStruct %15 %16 +%20 = OpTypeVector %4 4 +%21 = OpTypeVector %6 3 +%22 = OpTypeStruct %16 %21 %16 +%23 = OpTypeMatrix %21 3 +%24 = OpTypeStruct %15 %16 %16 +%25 = OpTypeRuntimeArray %24 +%26 = OpTypeArray %24 %3 +%27 = OpTypeImage %6 2D 1 1 0 1 Unknown +%28 = OpTypeSampler +%29 = OpTypeVector %6 2 +%30 = OpConstantComposite %21 %10 %10 %10 +%32 = OpTypeStruct %18 +%33 = OpTypePointer Uniform %32 +%31 = OpVariable %33 Uniform +%35 = OpTypeStruct %19 +%36 = OpTypePointer Uniform %35 +%34 = OpVariable %36 Uniform +%38 = OpTypeStruct %25 +%39 = OpTypePointer StorageBuffer %38 +%37 = OpVariable %39 StorageBuffer +%41 = OpTypeStruct %26 +%42 = OpTypePointer Uniform %41 +%40 = OpVariable %42 Uniform +%44 = OpTypePointer UniformConstant %27 +%43 = OpVariable %44 UniformConstant +%46 = OpTypePointer UniformConstant %28 +%45 = OpVariable %46 UniformConstant +%51 = OpTypeFunction %6 %12 %16 +%54 = OpTypePointer Uniform %19 +%55 = OpTypePointer Uniform %18 +%56 = OpTypePointer Uniform %26 +%57 = OpTypePointer StorageBuffer %25 +%60 = OpTypeBool +%75 = OpTypeSampledImage %27 +%82 = OpTypePointer Input %20 +%81 = OpVariable %82 Input +%85 = OpTypePointer Output %16 +%84 = OpVariable %85 Output +%87 = OpTypeFunction %2 +%91 = OpTypePointer Uniform %15 +%99 = OpTypePointer Output %6 +%104 = OpTypePointer Function %22 +%106 = OpVariable %82 Input +%108 = OpVariable %82 Input +%110 = OpVariable %85 Output +%112 = OpTypePointer Output %21 +%111 = OpVariable %112 Output +%113 = OpVariable %85 Output +%124 = OpTypePointer Function %21 +%132 = OpTypeVector %4 3 +%137 = OpTypePointer Function %16 +%138 = OpConstant %12 2 +%153 = OpTypePointer Function %12 +%157 = OpTypePointer Input %16 +%156 = OpVariable %157 Input +%160 = OpTypePointer Input %21 +%159 = OpVariable %160 Input +%162 = OpVariable %157 Input +%164 = OpVariable %85 Output +%179 = OpTypePointer Uniform %17 +%180 = OpTypePointer Uniform %12 +%188 = OpTypePointer StorageBuffer %24 +%214 = OpTypePointer Uniform %16 +%222 = OpVariable %157 Input +%224 = OpVariable %160 Input +%226 = OpVariable %157 Input +%228 = OpVariable %85 Output +%250 = OpTypePointer Uniform %24 +%50 = OpFunction %6 None %51 +%48 = OpFunctionParameter %12 +%49 = OpFunctionParameter %16 %47 = OpLabel -OpReturnValue %5 -%46 = OpLabel -%48 = OpCompositeConstruct %22 %6 %7 -%49 = OpVectorShuffle %22 %36 %36 0 1 -%50 = OpFMul %22 %49 %48 -%51 = OpCompositeExtract %4 %36 3 -%52 = OpCompositeConstruct %22 %51 %51 -%53 = OpFDiv %22 %50 %52 -%54 = OpCompositeConstruct %22 %6 %6 -%55 = OpFAdd %22 %53 %54 -%57 = OpBitcast %56 %35 -%58 = OpCompositeExtract %4 %36 2 -%59 = OpCompositeExtract %4 %36 3 -%60 = OpFDiv %4 %58 %59 -%62 = OpConvertUToF %4 %57 -%63 = OpCompositeConstruct %23 %55 %62 -%64 = OpSampledImage %61 %39 %40 -%65 = OpImageSampleDrefExplicitLod %4 %64 %63 %60 Lod %3 -OpReturnValue %65 +%52 = OpLoad %27 %43 +%53 = OpLoad %28 %45 +OpBranch %58 +%58 = OpLabel +%59 = OpCompositeExtract %6 %49 3 +%61 = OpFOrdLessThanEqual %60 %59 %5 +OpSelectionMerge %62 None +OpBranchConditional %61 %63 %62 +%63 = OpLabel +OpReturnValue %7 +%62 = OpLabel +%64 = OpCompositeConstruct %29 %8 %9 +%65 = OpCompositeExtract %6 %49 3 +%66 = OpFDiv %6 %7 %65 +%67 = OpVectorShuffle %29 %49 %49 0 1 +%68 = OpFMul %29 %67 %64 +%69 = OpVectorTimesScalar %29 %68 %66 +%70 = OpCompositeConstruct %29 %8 %8 +%71 = OpFAdd %29 %69 %70 +%72 = OpBitcast %4 %48 +%73 = OpCompositeExtract %6 %49 2 +%74 = OpFMul %6 %73 %66 +%76 = OpConvertUToF %6 %72 +%77 = OpCompositeConstruct %21 %71 %76 +%78 = OpSampledImage %75 %52 %53 +%79 = OpImageSampleDrefExplicitLod %6 %78 %77 %74 Lod %5 +OpReturnValue %79 OpFunctionEnd -%79 = OpFunction %2 None %80 -%70 = OpLabel -%66 = OpVariable %67 Function %24 -%68 = OpVariable %69 Function %11 -%73 = OpLoad %23 %71 -%76 = OpLoad %16 %74 -%81 = OpAccessChain %41 %25 %11 -%82 = OpLoad %20 %30 -%83 = OpLoad %21 %32 -OpBranch %84 -%84 = OpLabel -%85 = OpExtInst %23 %1 Normalize %73 -OpBranch %86 -%86 = OpLabel -OpLoopMerge %87 %89 None -OpBranch %88 -%88 = OpLabel -%90 = OpLoad %10 %68 -%93 = OpAccessChain %92 %81 %11 %11 -%94 = OpLoad %10 %93 -%95 = OpExtInst %10 %1 UMin %94 %9 -%96 = OpUGreaterThanEqual %44 %90 %95 -OpSelectionMerge %97 None -OpBranchConditional %96 %98 %97 -%98 = OpLabel -OpBranch %87 -%97 = OpLabel -%100 = OpLoad %10 %68 -%102 = OpAccessChain %101 %28 %11 %100 -%103 = OpLoad %17 %102 -%104 = OpLoad %10 %68 -%105 = OpCompositeExtract %15 %103 0 -%106 = OpMatrixTimesVector %16 %105 %76 -%107 = OpFunctionCall %4 %37 %104 %106 -%108 = OpCompositeExtract %16 %103 1 -%109 = OpVectorShuffle %23 %108 %108 0 1 2 -%110 = OpVectorShuffle %23 %76 %76 0 1 2 -%111 = OpFSub %23 %109 %110 -%112 = OpExtInst %23 %1 Normalize %111 -%113 = OpDot %4 %85 %112 -%114 = OpExtInst %4 %1 FMax %3 %113 -%115 = OpLoad %23 %66 -%116 = OpFMul %4 %107 %114 -%117 = OpCompositeExtract %16 %103 2 -%118 = OpVectorShuffle %23 %117 %117 0 1 2 -%119 = OpVectorTimesScalar %23 %118 %116 -%120 = OpFAdd %23 %115 %119 -OpStore %66 %120 -OpBranch %89 -%89 = OpLabel -%121 = OpLoad %10 %68 -%122 = OpIAdd %10 %121 %12 -OpStore %68 %122 -OpBranch %86 -%87 = OpLabel -%123 = OpLoad %23 %66 -%124 = OpCompositeConstruct %16 %123 %5 -OpStore %77 %124 +%86 = OpFunction %2 None %87 +%80 = OpLabel +%83 = OpLoad %20 %81 +%88 = OpAccessChain %55 %31 %13 +%89 = OpAccessChain %54 %34 %13 +OpBranch %90 +%90 = OpLabel +%92 = OpAccessChain %91 %88 %13 +%93 = OpLoad %15 %92 +%94 = OpAccessChain %91 %89 %13 +%95 = OpLoad %15 %94 +%96 = OpMatrixTimesMatrix %15 %93 %95 +%97 = OpConvertSToF %16 %83 +%98 = OpMatrixTimesVector %16 %96 %97 +OpStore %84 %98 +%100 = OpAccessChain %99 %84 %14 +%101 = OpLoad %6 %100 +%102 = OpFNegate %6 %101 +OpStore %100 %102 +OpReturn +OpFunctionEnd +%114 = OpFunction %2 None %87 +%105 = OpLabel +%103 = OpVariable %104 Function +%107 = OpLoad %20 %106 +%109 = OpLoad %20 %108 +%115 = OpAccessChain %55 %31 %13 +%116 = OpAccessChain %54 %34 %13 +OpBranch %117 +%117 = OpLabel +%118 = OpAccessChain %91 %116 %13 +%119 = OpLoad %15 %118 +%120 = OpAccessChain %91 %116 %13 +%121 = OpLoad %15 %120 +%122 = OpConvertSToF %16 %107 +%123 = OpMatrixTimesVector %16 %121 %122 +%125 = OpCompositeExtract %16 %119 0 +%126 = OpVectorShuffle %21 %125 %125 0 1 2 +%127 = OpCompositeExtract %16 %119 1 +%128 = OpVectorShuffle %21 %127 %127 0 1 2 +%129 = OpCompositeExtract %16 %119 2 +%130 = OpVectorShuffle %21 %129 %129 0 1 2 +%131 = OpCompositeConstruct %23 %126 %128 %130 +%133 = OpVectorShuffle %132 %109 %109 0 1 2 +%134 = OpConvertSToF %21 %133 +%135 = OpMatrixTimesVector %21 %131 %134 +%136 = OpAccessChain %124 %103 %14 +OpStore %136 %135 +%139 = OpAccessChain %137 %103 %138 +OpStore %139 %123 +%140 = OpAccessChain %91 %115 %13 +%141 = OpLoad %15 %140 +%142 = OpMatrixTimesVector %16 %141 %123 +%143 = OpAccessChain %137 %103 %13 +OpStore %143 %142 +%144 = OpLoad %22 %103 +%145 = OpCompositeExtract %16 %144 0 +OpStore %110 %145 +%146 = OpAccessChain %99 %110 %14 +%147 = OpLoad %6 %146 +%148 = OpFNegate %6 %147 +OpStore %146 %148 +%149 = OpCompositeExtract %21 %144 1 +OpStore %111 %149 +%150 = OpCompositeExtract %16 %144 2 +OpStore %113 %150 +OpReturn +OpFunctionEnd +%165 = OpFunction %2 None %87 +%154 = OpLabel +%151 = OpVariable %124 Function %30 +%152 = OpVariable %153 Function %13 +%158 = OpLoad %16 %156 +%161 = OpLoad %21 %159 +%163 = OpLoad %16 %162 +%155 = OpCompositeConstruct %22 %158 %161 %163 +%166 = OpAccessChain %55 %31 %13 +%167 = OpAccessChain %54 %34 %13 +%168 = OpAccessChain %57 %37 %13 +%169 = OpLoad %27 %43 +%170 = OpLoad %28 %45 +OpBranch %171 +%171 = OpLabel +%172 = OpCompositeExtract %21 %155 1 +%173 = OpExtInst %21 %1 Normalize %172 +OpBranch %174 +%174 = OpLabel +OpLoopMerge %175 %177 None +OpBranch %176 +%176 = OpLabel +%178 = OpLoad %12 %152 +%181 = OpAccessChain %180 %166 %14 %13 +%182 = OpLoad %12 %181 +%183 = OpExtInst %12 %1 UMin %182 %11 +%184 = OpULessThan %60 %178 %183 +OpSelectionMerge %185 None +OpBranchConditional %184 %185 %186 +%186 = OpLabel +OpBranch %175 +%185 = OpLabel +%187 = OpLoad %12 %152 +%189 = OpAccessChain %188 %168 %187 +%190 = OpLoad %24 %189 +%191 = OpLoad %12 %152 +%192 = OpCompositeExtract %15 %190 0 +%193 = OpCompositeExtract %16 %155 2 +%194 = OpMatrixTimesVector %16 %192 %193 +%195 = OpFunctionCall %6 %50 %191 %194 +%196 = OpCompositeExtract %16 %190 1 +%197 = OpVectorShuffle %21 %196 %196 0 1 2 +%198 = OpCompositeExtract %16 %155 2 +%199 = OpVectorShuffle %21 %198 %198 0 1 2 +%200 = OpFSub %21 %197 %199 +%201 = OpExtInst %21 %1 Normalize %200 +%202 = OpDot %6 %173 %201 +%203 = OpExtInst %6 %1 FMax %5 %202 +%204 = OpLoad %21 %151 +%205 = OpFMul %6 %195 %203 +%206 = OpCompositeExtract %16 %190 2 +%207 = OpVectorShuffle %21 %206 %206 0 1 2 +%208 = OpVectorTimesScalar %21 %207 %205 +%209 = OpFAdd %21 %204 %208 +OpStore %151 %209 +OpBranch %177 +%177 = OpLabel +%210 = OpLoad %12 %152 +%211 = OpIAdd %12 %210 %14 +OpStore %152 %211 +OpBranch %174 +%175 = OpLabel +%212 = OpLoad %21 %151 +%213 = OpCompositeConstruct %16 %212 %7 +%215 = OpAccessChain %214 %167 %14 +%216 = OpLoad %16 %215 +%217 = OpFMul %16 %213 %216 +OpStore %164 %217 +OpReturn +OpFunctionEnd +%229 = OpFunction %2 None %87 +%220 = OpLabel +%218 = OpVariable %124 Function %30 +%219 = OpVariable %153 Function %13 +%223 = OpLoad %16 %222 +%225 = OpLoad %21 %224 +%227 = OpLoad %16 %226 +%221 = OpCompositeConstruct %22 %223 %225 %227 +%230 = OpAccessChain %55 %31 %13 +%231 = OpAccessChain %54 %34 %13 +%232 = OpAccessChain %56 %40 %13 +%233 = OpLoad %27 %43 +%234 = OpLoad %28 %45 +OpBranch %235 +%235 = OpLabel +%236 = OpCompositeExtract %21 %221 1 +%237 = OpExtInst %21 %1 Normalize %236 +OpBranch %238 +%238 = OpLabel +OpLoopMerge %239 %241 None +OpBranch %240 +%240 = OpLabel +%242 = OpLoad %12 %219 +%243 = OpAccessChain %180 %230 %14 %13 +%244 = OpLoad %12 %243 +%245 = OpExtInst %12 %1 UMin %244 %11 +%246 = OpULessThan %60 %242 %245 +OpSelectionMerge %247 None +OpBranchConditional %246 %247 %248 +%248 = OpLabel +OpBranch %239 +%247 = OpLabel +%249 = OpLoad %12 %219 +%251 = OpAccessChain %250 %232 %249 +%252 = OpLoad %24 %251 +%253 = OpLoad %12 %219 +%254 = OpCompositeExtract %15 %252 0 +%255 = OpCompositeExtract %16 %221 2 +%256 = OpMatrixTimesVector %16 %254 %255 +%257 = OpFunctionCall %6 %50 %253 %256 +%258 = OpCompositeExtract %16 %252 1 +%259 = OpVectorShuffle %21 %258 %258 0 1 2 +%260 = OpCompositeExtract %16 %221 2 +%261 = OpVectorShuffle %21 %260 %260 0 1 2 +%262 = OpFSub %21 %259 %261 +%263 = OpExtInst %21 %1 Normalize %262 +%264 = OpDot %6 %237 %263 +%265 = OpExtInst %6 %1 FMax %5 %264 +%266 = OpLoad %21 %218 +%267 = OpFMul %6 %257 %265 +%268 = OpCompositeExtract %16 %252 2 +%269 = OpVectorShuffle %21 %268 %268 0 1 2 +%270 = OpVectorTimesScalar %21 %269 %267 +%271 = OpFAdd %21 %266 %270 +OpStore %218 %271 +OpBranch %241 +%241 = OpLabel +%272 = OpLoad %12 %219 +%273 = OpIAdd %12 %272 %14 +OpStore %219 %273 +OpBranch %238 +%239 = OpLabel +%274 = OpLoad %21 %218 +%275 = OpCompositeConstruct %16 %274 %7 +%276 = OpAccessChain %214 %231 %14 +%277 = OpLoad %16 %276 +%278 = OpFMul %16 %275 %277 +OpStore %228 %278 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 393003ad2..a94295422 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -1,24 +1,36 @@ struct Globals { + view_proj: mat4x4; num_lights: vec4; }; +struct Entity { + world: mat4x4; + color: vec4; +}; + +struct VertexOutput { + @builtin(position) proj_position: vec4; + @location(0) world_normal: vec3; + @location(1) world_position: vec4; +}; + struct Light { proj: mat4x4; pos: vec4; color: vec4; }; -struct Lights { - data: array; -}; - let c_ambient: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); let c_max_lights: u32 = 10u; @group(0) @binding(0) var u_globals: Globals; +@group(1) @binding(0) +var u_entity: Entity; @group(0) @binding(1) -var s_lights: Lights; +var s_lights: array; +@group(0) @binding(1) +var u_lights: array; @group(0) @binding(2) var t_shadow: texture_depth_2d_array; @group(0) @binding(3) @@ -29,36 +41,92 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { return 1.0; } let flip_correction = vec2(0.5, -0.5); - let light_local = (((homogeneous_coords.xy * flip_correction) / vec2(homogeneous_coords.w)) + vec2(0.5, 0.5)); - let _e26 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z / homogeneous_coords.w)); - return _e26; + let proj_correction = (1.0 / homogeneous_coords.w); + let light_local = (((homogeneous_coords.xy * flip_correction) * proj_correction) + vec2(0.5, 0.5)); + let _e28 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z * proj_correction)); + return _e28; +} + +@stage(vertex) +fn vs_bake(@location(0) position: vec4) -> @builtin(position) vec4 { + let _e4 = u_globals.view_proj; + let _e6 = u_entity.world; + return ((_e4 * _e6) * vec4(position)); +} + +@stage(vertex) +fn vs_main(@location(0) position_1: vec4, @location(1) normal: vec4) -> VertexOutput { + var out: VertexOutput; + + let w = u_entity.world; + let _e7 = u_entity.world; + let world_pos = (_e7 * vec4(position_1)); + out.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); + out.world_position = world_pos; + let _e25 = u_globals.view_proj; + out.proj_position = (_e25 * world_pos); + let _e27 = out; + return _e27; } @stage(fragment) -fn fs_main(@location(0) raw_normal: vec3, @location(1) position: vec4) -> @location(0) vec4 { +fn fs_main(in: VertexOutput) -> @location(0) vec4 { var color: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i: u32 = 0u; - let normal = normalize(raw_normal); + let normal_1 = normalize(in.world_normal); loop { - let _e12 = i; - let _e15 = u_globals.num_lights.x; - if (_e12 >= min(_e15, c_max_lights)) { + let _e14 = i; + let _e17 = u_globals.num_lights.x; + if (_e14 < min(_e17, c_max_lights)) { + } else { break; } - let _e19 = i; - let light = s_lights.data[_e19]; - let _e22 = i; - let _e25 = fetch_shadow(_e22, (light.proj * position)); - let light_dir = normalize((light.pos.xyz - position.xyz)); - let diffuse = max(0.0, dot(normal, light_dir)); - let _e34 = color; - color = (_e34 + ((_e25 * diffuse) * light.color.xyz)); + let _e23 = i; + let light = s_lights[_e23]; + let _e26 = i; + let _e30 = fetch_shadow(_e26, (light.proj * in.world_position)); + let light_dir = normalize((light.pos.xyz - in.world_position.xyz)); + let diffuse = max(0.0, dot(normal_1, light_dir)); + let _e40 = color; + color = (_e40 + ((_e30 * diffuse) * light.color.xyz)); continuing { - let _e40 = i; - i = (_e40 + 1u); + let _e20 = i; + i = (_e20 + 1u); } } - let _e43 = color; - return vec4(_e43, 1.0); + let _e46 = color; + let _e50 = u_entity.color; + return (vec4(_e46, 1.0) * _e50); +} + +@stage(fragment) +fn fs_main_without_storage(in_1: VertexOutput) -> @location(0) vec4 { + var color_1: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + var i_1: u32 = 0u; + + let normal_2 = normalize(in_1.world_normal); + loop { + let _e14 = i_1; + let _e17 = u_globals.num_lights.x; + if (_e14 < min(_e17, c_max_lights)) { + } else { + break; + } + let _e23 = i_1; + let light_1 = u_lights[_e23]; + let _e26 = i_1; + let _e30 = fetch_shadow(_e26, (light_1.proj * in_1.world_position)); + let light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); + let diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); + let _e40 = color_1; + color_1 = (_e40 + ((_e30 * diffuse_1) * light_1.color.xyz)); + continuing { + let _e20 = i_1; + i_1 = (_e20 + 1u); + } + } + let _e46 = color_1; + let _e50 = u_entity.color; + return (vec4(_e46, 1.0) * _e50); } From 7f4c01784c6bbf589d514cf0dabc699c11bfaa29 Mon Sep 17 00:00:00 2001 From: hatoo Date: Fri, 11 Mar 2022 15:17:02 +0900 Subject: [PATCH 1622/2212] Remove `vs_bake` entry point from `tests/in/shadow.wgsl` This entry point isn't useful for testing. --- tests/in/shadow.wgsl | 2 + tests/out/glsl/shadow.vs_bake.Vertex.glsl | 38 -- tests/out/glsl/shadow.vs_main.Vertex.glsl | 4 +- tests/out/hlsl/shadow.hlsl | 11 +- tests/out/hlsl/shadow.hlsl.config | 2 +- tests/out/msl/shadow.msl | 40 +- tests/out/spv/shadow.spvasm | 559 ++++++++++------------ tests/out/wgsl/shadow.wgsl | 11 +- 8 files changed, 285 insertions(+), 382 deletions(-) delete mode 100644 tests/out/glsl/shadow.vs_bake.Vertex.glsl diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 088608378..0b64b2f8d 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -16,10 +16,12 @@ struct Entity { @binding(0) var u_entity: Entity; +/* Not useful for testing @stage(vertex) fn vs_bake(@location(0) position: vec4) -> @builtin(position) vec4 { return u_globals.view_proj * u_entity.world * vec4(position); } +*/ struct VertexOutput { @builtin(position) proj_position: vec4; diff --git a/tests/out/glsl/shadow.vs_bake.Vertex.glsl b/tests/out/glsl/shadow.vs_bake.Vertex.glsl deleted file mode 100644 index 6f6812a25..000000000 --- a/tests/out/glsl/shadow.vs_bake.Vertex.glsl +++ /dev/null @@ -1,38 +0,0 @@ -#version 310 es - -precision highp float; -precision highp int; - -struct Globals { - mat4x4 view_proj; - uvec4 num_lights; -}; -struct Entity { - mat4x4 world; - vec4 color; -}; -struct VertexOutput { - vec4 proj_position; - vec3 world_normal; - vec4 world_position; -}; -struct Light { - mat4x4 proj; - vec4 pos; - vec4 color; -}; -uniform Globals_block_0Vertex { Globals _group_0_binding_0_vs; }; - -uniform Entity_block_1Vertex { Entity _group_1_binding_0_vs; }; - -layout(location = 0) in ivec4 _p2vs_location0; - -void main() { - ivec4 position = _p2vs_location0; - mat4x4 _e4 = _group_0_binding_0_vs.view_proj; - mat4x4 _e6 = _group_1_binding_0_vs.world; - gl_Position = ((_e4 * _e6) * vec4(position)); - gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); - return; -} - diff --git a/tests/out/glsl/shadow.vs_main.Vertex.glsl b/tests/out/glsl/shadow.vs_main.Vertex.glsl index a2e09ceec..dce8b2f7d 100644 --- a/tests/out/glsl/shadow.vs_main.Vertex.glsl +++ b/tests/out/glsl/shadow.vs_main.Vertex.glsl @@ -31,12 +31,12 @@ layout(location = 0) smooth out vec3 _vs2fs_location0; layout(location = 1) smooth out vec4 _vs2fs_location1; void main() { - ivec4 position_1 = _p2vs_location0; + ivec4 position = _p2vs_location0; ivec4 normal = _p2vs_location1; VertexOutput out_ = VertexOutput(vec4(0.0), vec3(0.0), vec4(0.0)); mat4x4 w = _group_1_binding_0_vs.world; mat4x4 _e7 = _group_1_binding_0_vs.world; - vec4 world_pos = (_e7 * vec4(position_1)); + vec4 world_pos = (_e7 * vec4(position)); out_.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); out_.world_position = world_pos; mat4x4 _e25 = _group_0_binding_0_vs.view_proj; diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 5b0ef63fa..aca4edda3 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -60,20 +60,13 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords) return _expr28; } -float4 vs_bake(int4 position : LOC0) : SV_Position -{ - float4x4 _expr4 = u_globals.view_proj; - float4x4 _expr6 = u_entity.world; - return mul(float4(position), mul(_expr6, _expr4)); -} - -VertexOutput_vs_main vs_main(int4 position_1 : LOC0, int4 normal : LOC1) +VertexOutput_vs_main vs_main(int4 position : LOC0, int4 normal : LOC1) { VertexOutput out_ = (VertexOutput)0; float4x4 w = u_entity.world; float4x4 _expr7 = u_entity.world; - float4 world_pos = mul(float4(position_1), _expr7); + float4 world_pos = mul(float4(position), _expr7); out_.world_normal = mul(float3(normal.xyz), float3x3(w[0].xyz, w[1].xyz, w[2].xyz)); out_.world_position = world_pos; float4x4 _expr25 = u_globals.view_proj; diff --git a/tests/out/hlsl/shadow.hlsl.config b/tests/out/hlsl/shadow.hlsl.config index 2ed1c8fd7..40d109c83 100644 --- a/tests/out/hlsl/shadow.hlsl.config +++ b/tests/out/hlsl/shadow.hlsl.config @@ -1,3 +1,3 @@ -vertex=(vs_bake:vs_5_1 vs_main:vs_5_1 ) +vertex=(vs_main:vs_5_1 ) fragment=(fs_main:ps_5_1 fs_main_without_storage:ps_5_1 ) compute=() diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 26af57fd2..5286b0bd0 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -49,26 +49,8 @@ float fetch_shadow( return _e28; } -struct vs_bakeInput { - metal::int4 position [[attribute(0)]]; -}; -struct vs_bakeOutput { - metal::float4 member [[position]]; -}; -vertex vs_bakeOutput vs_bake( - vs_bakeInput varyings [[stage_in]] -, constant Globals& u_globals [[user(fake0)]] -, constant Entity& u_entity [[user(fake0)]] -) { - const auto position = varyings.position; - metal::float4x4 _e4 = u_globals.view_proj; - metal::float4x4 _e6 = u_entity.world; - return vs_bakeOutput { (_e4 * _e6) * static_cast(position) }; -} - - struct vs_mainInput { - metal::int4 position_1 [[attribute(0)]]; + metal::int4 position [[attribute(0)]]; metal::int4 normal [[attribute(1)]]; }; struct vs_mainOutput { @@ -77,16 +59,16 @@ struct vs_mainOutput { metal::float4 world_position [[user(loc1), center_perspective]]; }; vertex vs_mainOutput vs_main( - vs_mainInput varyings_1 [[stage_in]] + vs_mainInput varyings [[stage_in]] , constant Globals& u_globals [[user(fake0)]] , constant Entity& u_entity [[user(fake0)]] ) { - const auto position_1 = varyings_1.position_1; - const auto normal = varyings_1.normal; + const auto position = varyings.position; + const auto normal = varyings.normal; VertexOutput out; metal::float4x4 w = u_entity.world; metal::float4x4 _e7 = u_entity.world; - metal::float4 world_pos = _e7 * static_cast(position_1); + metal::float4 world_pos = _e7 * static_cast(position); out.world_normal = metal::float3x3(w[0].xyz, w[1].xyz, w[2].xyz) * static_cast(normal.xyz); out.world_position = world_pos; metal::float4x4 _e25 = u_globals.view_proj; @@ -102,10 +84,10 @@ struct fs_mainInput { metal::float4 world_position [[user(loc1), center_perspective]]; }; struct fs_mainOutput { - metal::float4 member_2 [[color(0)]]; + metal::float4 member_1 [[color(0)]]; }; fragment fs_mainOutput fs_main( - fs_mainInput varyings_2 [[stage_in]] + fs_mainInput varyings_1 [[stage_in]] , metal::float4 proj_position [[position]] , constant Globals& u_globals [[user(fake0)]] , constant Entity& u_entity [[user(fake0)]] @@ -114,7 +96,7 @@ fragment fs_mainOutput fs_main( , metal::sampler sampler_shadow [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - const VertexOutput in = { proj_position, varyings_2.world_normal, varyings_2.world_position }; + const VertexOutput in = { proj_position, varyings_1.world_normal, varyings_1.world_position }; metal::float3 color = c_ambient; uint i = 0u; metal::float3 normal_1 = metal::normalize(in.world_normal); @@ -151,10 +133,10 @@ struct fs_main_without_storageInput { metal::float4 world_position [[user(loc1), center_perspective]]; }; struct fs_main_without_storageOutput { - metal::float4 member_3 [[color(0)]]; + metal::float4 member_2 [[color(0)]]; }; fragment fs_main_without_storageOutput fs_main_without_storage( - fs_main_without_storageInput varyings_3 [[stage_in]] + fs_main_without_storageInput varyings_2 [[stage_in]] , metal::float4 proj_position_1 [[position]] , constant Globals& u_globals [[user(fake0)]] , constant Entity& u_entity [[user(fake0)]] @@ -162,7 +144,7 @@ fragment fs_main_without_storageOutput fs_main_without_storage( , metal::depth2d_array t_shadow [[user(fake0)]] , metal::sampler sampler_shadow [[user(fake0)]] ) { - const VertexOutput in_1 = { proj_position_1, varyings_3.world_normal, varyings_3.world_position }; + const VertexOutput in_1 = { proj_position_1, varyings_2.world_normal, varyings_2.world_position }; metal::float3 color_1 = c_ambient; uint i_1 = 0u; metal::float3 normal_2 = metal::normalize(in_1.world_normal); diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index a6be5de2d..aeb85c96b 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,17 +1,16 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 279 +; Bound: 261 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %86 "vs_bake" %81 %84 -OpEntryPoint Vertex %114 "vs_main" %106 %108 %110 %111 %113 -OpEntryPoint Fragment %165 "fs_main" %156 %159 %162 %164 -OpEntryPoint Fragment %229 "fs_main_without_storage" %222 %224 %226 %228 -OpExecutionMode %165 OriginUpperLeft -OpExecutionMode %229 OriginUpperLeft +OpEntryPoint Vertex %93 "vs_main" %83 %86 %88 %90 %92 +OpEntryPoint Fragment %147 "fs_main" %138 %141 %144 %146 +OpEntryPoint Fragment %211 "fs_main_without_storage" %204 %206 %208 %210 +OpExecutionMode %147 OriginUpperLeft +OpExecutionMode %211 OriginUpperLeft OpSource GLSL 450 OpName %11 "c_max_lights" OpMemberName %18 0 "view_proj" @@ -20,10 +19,10 @@ OpName %18 "Globals" OpMemberName %19 0 "world" OpMemberName %19 1 "color" OpName %19 "Entity" -OpMemberName %22 0 "proj_position" -OpMemberName %22 1 "world_normal" -OpMemberName %22 2 "world_position" -OpName %22 "VertexOutput" +OpMemberName %21 0 "proj_position" +OpMemberName %21 1 "world_normal" +OpMemberName %21 2 "world_position" +OpName %21 "VertexOutput" OpMemberName %24 0 "proj" OpMemberName %24 1 "pos" OpMemberName %24 2 "color" @@ -38,27 +37,25 @@ OpName %45 "sampler_shadow" OpName %48 "light_id" OpName %49 "homogeneous_coords" OpName %50 "fetch_shadow" -OpName %81 "position" -OpName %86 "vs_bake" -OpName %103 "out" -OpName %106 "position" -OpName %108 "normal" -OpName %110 "proj_position" -OpName %111 "world_normal" -OpName %113 "world_position" -OpName %114 "vs_main" -OpName %151 "color" -OpName %152 "i" -OpName %156 "proj_position" -OpName %159 "world_normal" -OpName %162 "world_position" -OpName %165 "fs_main" -OpName %218 "color" -OpName %219 "i" -OpName %222 "proj_position" -OpName %224 "world_normal" -OpName %226 "world_position" -OpName %229 "fs_main_without_storage" +OpName %80 "out" +OpName %83 "position" +OpName %86 "normal" +OpName %88 "proj_position" +OpName %90 "world_normal" +OpName %92 "world_position" +OpName %93 "vs_main" +OpName %133 "color" +OpName %134 "i" +OpName %138 "proj_position" +OpName %141 "world_normal" +OpName %144 "world_position" +OpName %147 "fs_main" +OpName %200 "color" +OpName %201 "i" +OpName %204 "proj_position" +OpName %206 "world_normal" +OpName %208 "world_position" +OpName %211 "fs_main_without_storage" OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %18 0 ColMajor OpMemberDecorate %18 0 MatrixStride 16 @@ -67,9 +64,9 @@ OpMemberDecorate %19 0 Offset 0 OpMemberDecorate %19 0 ColMajor OpMemberDecorate %19 0 MatrixStride 16 OpMemberDecorate %19 1 Offset 64 -OpMemberDecorate %22 0 Offset 0 -OpMemberDecorate %22 1 Offset 16 -OpMemberDecorate %22 2 Offset 32 +OpMemberDecorate %21 0 Offset 0 +OpMemberDecorate %21 1 Offset 16 +OpMemberDecorate %21 2 Offset 32 OpMemberDecorate %24 0 Offset 0 OpMemberDecorate %24 0 ColMajor OpMemberDecorate %24 0 MatrixStride 16 @@ -98,24 +95,21 @@ OpDecorate %43 DescriptorSet 0 OpDecorate %43 Binding 2 OpDecorate %45 DescriptorSet 0 OpDecorate %45 Binding 3 -OpDecorate %81 Location 0 -OpDecorate %81 Flat -OpDecorate %84 BuiltIn Position -OpDecorate %106 Location 0 -OpDecorate %106 Flat -OpDecorate %108 Location 1 -OpDecorate %108 Flat -OpDecorate %110 BuiltIn Position -OpDecorate %111 Location 0 -OpDecorate %113 Location 1 -OpDecorate %156 BuiltIn FragCoord -OpDecorate %159 Location 0 -OpDecorate %162 Location 1 -OpDecorate %164 Location 0 -OpDecorate %222 BuiltIn FragCoord -OpDecorate %224 Location 0 -OpDecorate %226 Location 1 -OpDecorate %228 Location 0 +OpDecorate %83 Location 0 +OpDecorate %83 Flat +OpDecorate %86 Location 1 +OpDecorate %86 Flat +OpDecorate %88 BuiltIn Position +OpDecorate %90 Location 0 +OpDecorate %92 Location 1 +OpDecorate %138 BuiltIn FragCoord +OpDecorate %141 Location 0 +OpDecorate %144 Location 1 +OpDecorate %146 Location 0 +OpDecorate %204 BuiltIn FragCoord +OpDecorate %206 Location 0 +OpDecorate %208 Location 1 +OpDecorate %210 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -134,17 +128,17 @@ OpDecorate %228 Location 0 %17 = OpTypeVector %12 4 %18 = OpTypeStruct %15 %17 %19 = OpTypeStruct %15 %16 -%20 = OpTypeVector %4 4 -%21 = OpTypeVector %6 3 -%22 = OpTypeStruct %16 %21 %16 -%23 = OpTypeMatrix %21 3 +%20 = OpTypeVector %6 3 +%21 = OpTypeStruct %16 %20 %16 +%22 = OpTypeVector %4 4 +%23 = OpTypeMatrix %20 3 %24 = OpTypeStruct %15 %16 %16 %25 = OpTypeRuntimeArray %24 %26 = OpTypeArray %24 %3 %27 = OpTypeImage %6 2D 1 1 0 1 Unknown %28 = OpTypeSampler %29 = OpTypeVector %6 2 -%30 = OpConstantComposite %21 %10 %10 %10 +%30 = OpConstantComposite %20 %10 %10 %10 %32 = OpTypeStruct %18 %33 = OpTypePointer Uniform %32 %31 = OpVariable %33 Uniform @@ -168,40 +162,38 @@ OpDecorate %228 Location 0 %57 = OpTypePointer StorageBuffer %25 %60 = OpTypeBool %75 = OpTypeSampledImage %27 -%82 = OpTypePointer Input %20 -%81 = OpVariable %82 Input -%85 = OpTypePointer Output %16 -%84 = OpVariable %85 Output -%87 = OpTypeFunction %2 -%91 = OpTypePointer Uniform %15 -%99 = OpTypePointer Output %6 -%104 = OpTypePointer Function %22 -%106 = OpVariable %82 Input -%108 = OpVariable %82 Input -%110 = OpVariable %85 Output -%112 = OpTypePointer Output %21 -%111 = OpVariable %112 Output -%113 = OpVariable %85 Output -%124 = OpTypePointer Function %21 -%132 = OpTypeVector %4 3 -%137 = OpTypePointer Function %16 -%138 = OpConstant %12 2 -%153 = OpTypePointer Function %12 -%157 = OpTypePointer Input %16 -%156 = OpVariable %157 Input -%160 = OpTypePointer Input %21 -%159 = OpVariable %160 Input -%162 = OpVariable %157 Input -%164 = OpVariable %85 Output -%179 = OpTypePointer Uniform %17 -%180 = OpTypePointer Uniform %12 -%188 = OpTypePointer StorageBuffer %24 -%214 = OpTypePointer Uniform %16 -%222 = OpVariable %157 Input -%224 = OpVariable %160 Input -%226 = OpVariable %157 Input -%228 = OpVariable %85 Output -%250 = OpTypePointer Uniform %24 +%81 = OpTypePointer Function %21 +%84 = OpTypePointer Input %22 +%83 = OpVariable %84 Input +%86 = OpVariable %84 Input +%89 = OpTypePointer Output %16 +%88 = OpVariable %89 Output +%91 = OpTypePointer Output %20 +%90 = OpVariable %91 Output +%92 = OpVariable %89 Output +%94 = OpTypeFunction %2 +%98 = OpTypePointer Uniform %15 +%105 = OpTypePointer Function %20 +%113 = OpTypeVector %4 3 +%118 = OpTypePointer Function %16 +%119 = OpConstant %12 2 +%127 = OpTypePointer Output %6 +%135 = OpTypePointer Function %12 +%139 = OpTypePointer Input %16 +%138 = OpVariable %139 Input +%142 = OpTypePointer Input %20 +%141 = OpVariable %142 Input +%144 = OpVariable %139 Input +%146 = OpVariable %89 Output +%161 = OpTypePointer Uniform %17 +%162 = OpTypePointer Uniform %12 +%170 = OpTypePointer StorageBuffer %24 +%196 = OpTypePointer Uniform %16 +%204 = OpVariable %139 Input +%206 = OpVariable %142 Input +%208 = OpVariable %139 Input +%210 = OpVariable %89 Output +%232 = OpTypePointer Uniform %24 %50 = OpFunction %6 None %51 %48 = OpFunctionParameter %12 %49 = OpFunctionParameter %16 @@ -229,216 +221,195 @@ OpReturnValue %7 %73 = OpCompositeExtract %6 %49 2 %74 = OpFMul %6 %73 %66 %76 = OpConvertUToF %6 %72 -%77 = OpCompositeConstruct %21 %71 %76 +%77 = OpCompositeConstruct %20 %71 %76 %78 = OpSampledImage %75 %52 %53 %79 = OpImageSampleDrefExplicitLod %6 %78 %77 %74 Lod %5 OpReturnValue %79 OpFunctionEnd -%86 = OpFunction %2 None %87 -%80 = OpLabel -%83 = OpLoad %20 %81 -%88 = OpAccessChain %55 %31 %13 -%89 = OpAccessChain %54 %34 %13 -OpBranch %90 -%90 = OpLabel -%92 = OpAccessChain %91 %88 %13 -%93 = OpLoad %15 %92 -%94 = OpAccessChain %91 %89 %13 -%95 = OpLoad %15 %94 -%96 = OpMatrixTimesMatrix %15 %93 %95 -%97 = OpConvertSToF %16 %83 -%98 = OpMatrixTimesVector %16 %96 %97 -OpStore %84 %98 -%100 = OpAccessChain %99 %84 %14 -%101 = OpLoad %6 %100 -%102 = OpFNegate %6 %101 -OpStore %100 %102 +%93 = OpFunction %2 None %94 +%82 = OpLabel +%80 = OpVariable %81 Function +%85 = OpLoad %22 %83 +%87 = OpLoad %22 %86 +%95 = OpAccessChain %55 %31 %13 +%96 = OpAccessChain %54 %34 %13 +OpBranch %97 +%97 = OpLabel +%99 = OpAccessChain %98 %96 %13 +%100 = OpLoad %15 %99 +%101 = OpAccessChain %98 %96 %13 +%102 = OpLoad %15 %101 +%103 = OpConvertSToF %16 %85 +%104 = OpMatrixTimesVector %16 %102 %103 +%106 = OpCompositeExtract %16 %100 0 +%107 = OpVectorShuffle %20 %106 %106 0 1 2 +%108 = OpCompositeExtract %16 %100 1 +%109 = OpVectorShuffle %20 %108 %108 0 1 2 +%110 = OpCompositeExtract %16 %100 2 +%111 = OpVectorShuffle %20 %110 %110 0 1 2 +%112 = OpCompositeConstruct %23 %107 %109 %111 +%114 = OpVectorShuffle %113 %87 %87 0 1 2 +%115 = OpConvertSToF %20 %114 +%116 = OpMatrixTimesVector %20 %112 %115 +%117 = OpAccessChain %105 %80 %14 +OpStore %117 %116 +%120 = OpAccessChain %118 %80 %119 +OpStore %120 %104 +%121 = OpAccessChain %98 %95 %13 +%122 = OpLoad %15 %121 +%123 = OpMatrixTimesVector %16 %122 %104 +%124 = OpAccessChain %118 %80 %13 +OpStore %124 %123 +%125 = OpLoad %21 %80 +%126 = OpCompositeExtract %16 %125 0 +OpStore %88 %126 +%128 = OpAccessChain %127 %88 %14 +%129 = OpLoad %6 %128 +%130 = OpFNegate %6 %129 +OpStore %128 %130 +%131 = OpCompositeExtract %20 %125 1 +OpStore %90 %131 +%132 = OpCompositeExtract %16 %125 2 +OpStore %92 %132 OpReturn OpFunctionEnd -%114 = OpFunction %2 None %87 -%105 = OpLabel -%103 = OpVariable %104 Function -%107 = OpLoad %20 %106 -%109 = OpLoad %20 %108 -%115 = OpAccessChain %55 %31 %13 -%116 = OpAccessChain %54 %34 %13 -OpBranch %117 -%117 = OpLabel -%118 = OpAccessChain %91 %116 %13 -%119 = OpLoad %15 %118 -%120 = OpAccessChain %91 %116 %13 -%121 = OpLoad %15 %120 -%122 = OpConvertSToF %16 %107 -%123 = OpMatrixTimesVector %16 %121 %122 -%125 = OpCompositeExtract %16 %119 0 -%126 = OpVectorShuffle %21 %125 %125 0 1 2 -%127 = OpCompositeExtract %16 %119 1 -%128 = OpVectorShuffle %21 %127 %127 0 1 2 -%129 = OpCompositeExtract %16 %119 2 -%130 = OpVectorShuffle %21 %129 %129 0 1 2 -%131 = OpCompositeConstruct %23 %126 %128 %130 -%133 = OpVectorShuffle %132 %109 %109 0 1 2 -%134 = OpConvertSToF %21 %133 -%135 = OpMatrixTimesVector %21 %131 %134 -%136 = OpAccessChain %124 %103 %14 -OpStore %136 %135 -%139 = OpAccessChain %137 %103 %138 -OpStore %139 %123 -%140 = OpAccessChain %91 %115 %13 -%141 = OpLoad %15 %140 -%142 = OpMatrixTimesVector %16 %141 %123 -%143 = OpAccessChain %137 %103 %13 -OpStore %143 %142 -%144 = OpLoad %22 %103 -%145 = OpCompositeExtract %16 %144 0 -OpStore %110 %145 -%146 = OpAccessChain %99 %110 %14 -%147 = OpLoad %6 %146 -%148 = OpFNegate %6 %147 -OpStore %146 %148 -%149 = OpCompositeExtract %21 %144 1 -OpStore %111 %149 -%150 = OpCompositeExtract %16 %144 2 -OpStore %113 %150 +%147 = OpFunction %2 None %94 +%136 = OpLabel +%133 = OpVariable %105 Function %30 +%134 = OpVariable %135 Function %13 +%140 = OpLoad %16 %138 +%143 = OpLoad %20 %141 +%145 = OpLoad %16 %144 +%137 = OpCompositeConstruct %21 %140 %143 %145 +%148 = OpAccessChain %55 %31 %13 +%149 = OpAccessChain %54 %34 %13 +%150 = OpAccessChain %57 %37 %13 +%151 = OpLoad %27 %43 +%152 = OpLoad %28 %45 +OpBranch %153 +%153 = OpLabel +%154 = OpCompositeExtract %20 %137 1 +%155 = OpExtInst %20 %1 Normalize %154 +OpBranch %156 +%156 = OpLabel +OpLoopMerge %157 %159 None +OpBranch %158 +%158 = OpLabel +%160 = OpLoad %12 %134 +%163 = OpAccessChain %162 %148 %14 %13 +%164 = OpLoad %12 %163 +%165 = OpExtInst %12 %1 UMin %164 %11 +%166 = OpULessThan %60 %160 %165 +OpSelectionMerge %167 None +OpBranchConditional %166 %167 %168 +%168 = OpLabel +OpBranch %157 +%167 = OpLabel +%169 = OpLoad %12 %134 +%171 = OpAccessChain %170 %150 %169 +%172 = OpLoad %24 %171 +%173 = OpLoad %12 %134 +%174 = OpCompositeExtract %15 %172 0 +%175 = OpCompositeExtract %16 %137 2 +%176 = OpMatrixTimesVector %16 %174 %175 +%177 = OpFunctionCall %6 %50 %173 %176 +%178 = OpCompositeExtract %16 %172 1 +%179 = OpVectorShuffle %20 %178 %178 0 1 2 +%180 = OpCompositeExtract %16 %137 2 +%181 = OpVectorShuffle %20 %180 %180 0 1 2 +%182 = OpFSub %20 %179 %181 +%183 = OpExtInst %20 %1 Normalize %182 +%184 = OpDot %6 %155 %183 +%185 = OpExtInst %6 %1 FMax %5 %184 +%186 = OpLoad %20 %133 +%187 = OpFMul %6 %177 %185 +%188 = OpCompositeExtract %16 %172 2 +%189 = OpVectorShuffle %20 %188 %188 0 1 2 +%190 = OpVectorTimesScalar %20 %189 %187 +%191 = OpFAdd %20 %186 %190 +OpStore %133 %191 +OpBranch %159 +%159 = OpLabel +%192 = OpLoad %12 %134 +%193 = OpIAdd %12 %192 %14 +OpStore %134 %193 +OpBranch %156 +%157 = OpLabel +%194 = OpLoad %20 %133 +%195 = OpCompositeConstruct %16 %194 %7 +%197 = OpAccessChain %196 %149 %14 +%198 = OpLoad %16 %197 +%199 = OpFMul %16 %195 %198 +OpStore %146 %199 OpReturn OpFunctionEnd -%165 = OpFunction %2 None %87 -%154 = OpLabel -%151 = OpVariable %124 Function %30 -%152 = OpVariable %153 Function %13 -%158 = OpLoad %16 %156 -%161 = OpLoad %21 %159 -%163 = OpLoad %16 %162 -%155 = OpCompositeConstruct %22 %158 %161 %163 -%166 = OpAccessChain %55 %31 %13 -%167 = OpAccessChain %54 %34 %13 -%168 = OpAccessChain %57 %37 %13 -%169 = OpLoad %27 %43 -%170 = OpLoad %28 %45 -OpBranch %171 -%171 = OpLabel -%172 = OpCompositeExtract %21 %155 1 -%173 = OpExtInst %21 %1 Normalize %172 -OpBranch %174 -%174 = OpLabel -OpLoopMerge %175 %177 None -OpBranch %176 -%176 = OpLabel -%178 = OpLoad %12 %152 -%181 = OpAccessChain %180 %166 %14 %13 -%182 = OpLoad %12 %181 -%183 = OpExtInst %12 %1 UMin %182 %11 -%184 = OpULessThan %60 %178 %183 -OpSelectionMerge %185 None -OpBranchConditional %184 %185 %186 -%186 = OpLabel -OpBranch %175 -%185 = OpLabel -%187 = OpLoad %12 %152 -%189 = OpAccessChain %188 %168 %187 -%190 = OpLoad %24 %189 -%191 = OpLoad %12 %152 -%192 = OpCompositeExtract %15 %190 0 -%193 = OpCompositeExtract %16 %155 2 -%194 = OpMatrixTimesVector %16 %192 %193 -%195 = OpFunctionCall %6 %50 %191 %194 -%196 = OpCompositeExtract %16 %190 1 -%197 = OpVectorShuffle %21 %196 %196 0 1 2 -%198 = OpCompositeExtract %16 %155 2 -%199 = OpVectorShuffle %21 %198 %198 0 1 2 -%200 = OpFSub %21 %197 %199 -%201 = OpExtInst %21 %1 Normalize %200 -%202 = OpDot %6 %173 %201 -%203 = OpExtInst %6 %1 FMax %5 %202 -%204 = OpLoad %21 %151 -%205 = OpFMul %6 %195 %203 -%206 = OpCompositeExtract %16 %190 2 -%207 = OpVectorShuffle %21 %206 %206 0 1 2 -%208 = OpVectorTimesScalar %21 %207 %205 -%209 = OpFAdd %21 %204 %208 -OpStore %151 %209 -OpBranch %177 -%177 = OpLabel -%210 = OpLoad %12 %152 -%211 = OpIAdd %12 %210 %14 -OpStore %152 %211 -OpBranch %174 -%175 = OpLabel -%212 = OpLoad %21 %151 -%213 = OpCompositeConstruct %16 %212 %7 -%215 = OpAccessChain %214 %167 %14 -%216 = OpLoad %16 %215 -%217 = OpFMul %16 %213 %216 -OpStore %164 %217 -OpReturn -OpFunctionEnd -%229 = OpFunction %2 None %87 +%211 = OpFunction %2 None %94 +%202 = OpLabel +%200 = OpVariable %105 Function %30 +%201 = OpVariable %135 Function %13 +%205 = OpLoad %16 %204 +%207 = OpLoad %20 %206 +%209 = OpLoad %16 %208 +%203 = OpCompositeConstruct %21 %205 %207 %209 +%212 = OpAccessChain %55 %31 %13 +%213 = OpAccessChain %54 %34 %13 +%214 = OpAccessChain %56 %40 %13 +%215 = OpLoad %27 %43 +%216 = OpLoad %28 %45 +OpBranch %217 +%217 = OpLabel +%218 = OpCompositeExtract %20 %203 1 +%219 = OpExtInst %20 %1 Normalize %218 +OpBranch %220 %220 = OpLabel -%218 = OpVariable %124 Function %30 -%219 = OpVariable %153 Function %13 -%223 = OpLoad %16 %222 -%225 = OpLoad %21 %224 -%227 = OpLoad %16 %226 -%221 = OpCompositeConstruct %22 %223 %225 %227 -%230 = OpAccessChain %55 %31 %13 -%231 = OpAccessChain %54 %34 %13 -%232 = OpAccessChain %56 %40 %13 -%233 = OpLoad %27 %43 -%234 = OpLoad %28 %45 -OpBranch %235 -%235 = OpLabel -%236 = OpCompositeExtract %21 %221 1 -%237 = OpExtInst %21 %1 Normalize %236 -OpBranch %238 -%238 = OpLabel -OpLoopMerge %239 %241 None -OpBranch %240 -%240 = OpLabel -%242 = OpLoad %12 %219 -%243 = OpAccessChain %180 %230 %14 %13 -%244 = OpLoad %12 %243 -%245 = OpExtInst %12 %1 UMin %244 %11 -%246 = OpULessThan %60 %242 %245 -OpSelectionMerge %247 None -OpBranchConditional %246 %247 %248 -%248 = OpLabel -OpBranch %239 -%247 = OpLabel -%249 = OpLoad %12 %219 -%251 = OpAccessChain %250 %232 %249 -%252 = OpLoad %24 %251 -%253 = OpLoad %12 %219 -%254 = OpCompositeExtract %15 %252 0 -%255 = OpCompositeExtract %16 %221 2 -%256 = OpMatrixTimesVector %16 %254 %255 -%257 = OpFunctionCall %6 %50 %253 %256 -%258 = OpCompositeExtract %16 %252 1 -%259 = OpVectorShuffle %21 %258 %258 0 1 2 -%260 = OpCompositeExtract %16 %221 2 -%261 = OpVectorShuffle %21 %260 %260 0 1 2 -%262 = OpFSub %21 %259 %261 -%263 = OpExtInst %21 %1 Normalize %262 -%264 = OpDot %6 %237 %263 -%265 = OpExtInst %6 %1 FMax %5 %264 -%266 = OpLoad %21 %218 -%267 = OpFMul %6 %257 %265 -%268 = OpCompositeExtract %16 %252 2 -%269 = OpVectorShuffle %21 %268 %268 0 1 2 -%270 = OpVectorTimesScalar %21 %269 %267 -%271 = OpFAdd %21 %266 %270 -OpStore %218 %271 -OpBranch %241 -%241 = OpLabel -%272 = OpLoad %12 %219 -%273 = OpIAdd %12 %272 %14 -OpStore %219 %273 -OpBranch %238 -%239 = OpLabel -%274 = OpLoad %21 %218 -%275 = OpCompositeConstruct %16 %274 %7 -%276 = OpAccessChain %214 %231 %14 -%277 = OpLoad %16 %276 -%278 = OpFMul %16 %275 %277 -OpStore %228 %278 +OpLoopMerge %221 %223 None +OpBranch %222 +%222 = OpLabel +%224 = OpLoad %12 %201 +%225 = OpAccessChain %162 %212 %14 %13 +%226 = OpLoad %12 %225 +%227 = OpExtInst %12 %1 UMin %226 %11 +%228 = OpULessThan %60 %224 %227 +OpSelectionMerge %229 None +OpBranchConditional %228 %229 %230 +%230 = OpLabel +OpBranch %221 +%229 = OpLabel +%231 = OpLoad %12 %201 +%233 = OpAccessChain %232 %214 %231 +%234 = OpLoad %24 %233 +%235 = OpLoad %12 %201 +%236 = OpCompositeExtract %15 %234 0 +%237 = OpCompositeExtract %16 %203 2 +%238 = OpMatrixTimesVector %16 %236 %237 +%239 = OpFunctionCall %6 %50 %235 %238 +%240 = OpCompositeExtract %16 %234 1 +%241 = OpVectorShuffle %20 %240 %240 0 1 2 +%242 = OpCompositeExtract %16 %203 2 +%243 = OpVectorShuffle %20 %242 %242 0 1 2 +%244 = OpFSub %20 %241 %243 +%245 = OpExtInst %20 %1 Normalize %244 +%246 = OpDot %6 %219 %245 +%247 = OpExtInst %6 %1 FMax %5 %246 +%248 = OpLoad %20 %200 +%249 = OpFMul %6 %239 %247 +%250 = OpCompositeExtract %16 %234 2 +%251 = OpVectorShuffle %20 %250 %250 0 1 2 +%252 = OpVectorTimesScalar %20 %251 %249 +%253 = OpFAdd %20 %248 %252 +OpStore %200 %253 +OpBranch %223 +%223 = OpLabel +%254 = OpLoad %12 %201 +%255 = OpIAdd %12 %254 %14 +OpStore %201 %255 +OpBranch %220 +%221 = OpLabel +%256 = OpLoad %20 %200 +%257 = OpCompositeConstruct %16 %256 %7 +%258 = OpAccessChain %196 %213 %14 +%259 = OpLoad %16 %258 +%260 = OpFMul %16 %257 %259 +OpStore %210 %260 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index a94295422..a5dbb554e 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -48,19 +48,12 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { } @stage(vertex) -fn vs_bake(@location(0) position: vec4) -> @builtin(position) vec4 { - let _e4 = u_globals.view_proj; - let _e6 = u_entity.world; - return ((_e4 * _e6) * vec4(position)); -} - -@stage(vertex) -fn vs_main(@location(0) position_1: vec4, @location(1) normal: vec4) -> VertexOutput { +fn vs_main(@location(0) position: vec4, @location(1) normal: vec4) -> VertexOutput { var out: VertexOutput; let w = u_entity.world; let _e7 = u_entity.world; - let world_pos = (_e7 * vec4(position_1)); + let world_pos = (_e7 * vec4(position)); out.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); out.world_position = world_pos; let _e25 = u_globals.view_proj; From 816fa347ad7afa6053fc7ea49d521239d1cdb899 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Sun, 13 Mar 2022 00:48:10 +0300 Subject: [PATCH 1623/2212] [wgsl-in] Uses commas to separate struct members instead of semicolons --- src/front/wgsl/mod.rs | 18 +++++++---- src/front/wgsl/tests.rs | 14 ++++----- tests/in/access.wgsl | 12 ++++---- tests/in/boids.wgsl | 20 ++++++------ tests/in/bounds-check-restrict.wgsl | 8 ++--- tests/in/bounds-check-zero-atomic.wgsl | 6 ++-- tests/in/bounds-check-zero.wgsl | 8 ++--- tests/in/collatz.wgsl | 2 +- tests/in/extra.wgsl | 8 ++--- tests/in/globals.wgsl | 4 +-- tests/in/interface.wgsl | 14 ++++----- tests/in/interpolate.wgsl | 16 +++++----- tests/in/operators.wgsl | 4 +-- tests/in/pointers.wgsl | 2 +- tests/in/policy-mix.wgsl | 4 +-- tests/in/push-constants.wgsl | 4 +-- tests/in/quad.wgsl | 4 +-- tests/in/shadow.wgsl | 20 ++++++------ tests/in/skybox.wgsl | 8 ++--- tests/wgsl-errors.rs | 42 +++++++++++++------------- 20 files changed, 112 insertions(+), 106 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2271a915d..3f2348b98 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2811,7 +2811,14 @@ impl Parser { let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; - loop { + let mut ready = true; + while !lexer.skip(Token::Paren('}')) { + if !ready { + return Err(Error::Unexpected( + lexer.next(), + ExpectedToken::Token(Token::Separator(',')), + )); + } let (mut size, mut align) = (None, None); self.push_scope(Scope::Attribute, lexer); let mut bind_parser = BindingParser::default(); @@ -2838,10 +2845,6 @@ impl Parser { let bind_span = self.pop_scope(lexer); let (name, span) = match lexer.next() { (Token::Word(word), span) => (word, span), - (Token::Paren('}'), _) => { - let span = Layouter::round_up(alignment, offset); - return Ok((members, span)); - } other => return Err(Error::Unexpected(other, ExpectedToken::FieldName)), }; if crate::keywords::wgsl::RESERVED.contains(&name) { @@ -2849,7 +2852,7 @@ impl Parser { } lexer.expect(Token::Separator(':'))?; let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; - lexer.expect(Token::Separator(';'))?; + ready = lexer.skip(Token::Separator(',')); self.layouter.update(type_arena, const_arena).unwrap(); @@ -2868,6 +2871,9 @@ impl Parser { offset: range.start, }); } + + let span = Layouter::round_up(alignment, offset); + Ok((members, span)) } fn parse_type_decl_impl<'a>( diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index a439eff4b..906311248 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -157,11 +157,11 @@ fn parse_type_cast() { fn parse_struct() { parse_str( " - struct Foo { x: i32; }; + struct Foo { x: i32 }; struct Bar { - @size(16) x: vec2; - @align(16) y: f32; - @size(32) @align(8) z: vec3; + @size(16) x: vec2, + @align(16) y: f32, + @size(32) @align(8) z: vec3, }; struct Empty {}; var s: Foo; @@ -415,8 +415,8 @@ fn parse_struct_instantiation() { parse_str( " struct Foo { - a: f32; - b: vec3; + a: f32, + b: vec3, }; @stage(fragment) @@ -433,7 +433,7 @@ fn parse_array_length() { parse_str( " struct Foo { - data: array; + data: array }; // this is used as both input and output for convenience @group(0) @binding(0) diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index d68a74ca0..390a018b1 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -1,15 +1,15 @@ // This snapshot tests accessing various containers, dereferencing pointers. struct AlignedWrapper { - @align(8) value: i32; + @align(8) value: i32 }; struct Bar { - matrix: mat4x4; - matrix_array: array, 2>; - atom: atomic; - arr: array, 2>; - data: array; + matrix: mat4x4, + matrix_array: array, 2>, + atom: atomic, + arr: array, 2>, + data: array, }; @group(0) @binding(0) diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index c3106f1c6..2655f2783 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -1,22 +1,22 @@ let NUM_PARTICLES: u32 = 1500u; struct Particle { - pos : vec2; - vel : vec2; + pos : vec2, + vel : vec2, }; struct SimParams { - deltaT : f32; - rule1Distance : f32; - rule2Distance : f32; - rule3Distance : f32; - rule1Scale : f32; - rule2Scale : f32; - rule3Scale : f32; + deltaT : f32, + rule1Distance : f32, + rule2Distance : f32, + rule3Distance : f32, + rule1Scale : f32, + rule2Scale : f32, + rule3Scale : f32, }; struct Particles { - particles : array; + particles : array }; @group(0) @binding(0) var params : SimParams; diff --git a/tests/in/bounds-check-restrict.wgsl b/tests/in/bounds-check-restrict.wgsl index fefcdec0c..d88be39fb 100644 --- a/tests/in/bounds-check-restrict.wgsl +++ b/tests/in/bounds-check-restrict.wgsl @@ -1,10 +1,10 @@ // Tests for `naga::back::BoundsCheckPolicy::Restrict`. struct Globals { - a: array; - v: vec4; - m: mat3x4; - d: array; + a: array, + v: vec4, + m: mat3x4, + d: array, }; @group(0) @binding(0) var globals: Globals; diff --git a/tests/in/bounds-check-zero-atomic.wgsl b/tests/in/bounds-check-zero-atomic.wgsl index ad4012dbf..c64cc8bd0 100644 --- a/tests/in/bounds-check-zero-atomic.wgsl +++ b/tests/in/bounds-check-zero-atomic.wgsl @@ -5,9 +5,9 @@ // be combined. struct Globals { - a: atomic; - b: array, 10>; - c: array>; + a: atomic, + b: array, 10>, + c: array>, }; @group(0) @binding(0) var globals: Globals; diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl index e1a05ac92..1dbfd9cb5 100644 --- a/tests/in/bounds-check-zero.wgsl +++ b/tests/in/bounds-check-zero.wgsl @@ -1,10 +1,10 @@ // Tests for `naga::back::BoundsCheckPolicy::ReadZeroSkipWrite`. struct Globals { - a: array; - v: vec4; - m: mat3x4; - d: array; + a: array, + v: vec4, + m: mat3x4, + d: array, }; @group(0) @binding(0) var globals: Globals; diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index 7e2b13543..15a9d4605 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -1,5 +1,5 @@ struct PrimeIndices { - data: array; + data: array }; // this is used as both input and output for convenience @group(0) @binding(0) diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index e8a858cc1..6dcecd553 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -1,12 +1,12 @@ struct PushConstants { - index: u32; - double: vec2; + index: u32, + double: vec2, }; var pc: PushConstants; struct FragmentIn { - @location(0) color: vec4; - @builtin(primitive_index) primitive_index: u32; + @location(0) color: vec4, + @builtin(primitive_index) primitive_index: u32, }; @stage(fragment) diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 7e5b72501..ed8c40a70 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -6,9 +6,9 @@ var wg : array; var at: atomic; struct Foo { - v3: vec3; + v3: vec3, // test packed vec3 - v1: f32; + v1: f32, }; @group(0) @binding(1) var alignment: Foo; diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index 737529552..d2cf84023 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -1,8 +1,8 @@ // Testing various parts of the pipeline interface: locations, built-ins, and entry points struct VertexOutput { - @builtin(position) position: vec4; - @location(1) varying: f32; + @builtin(position) position: vec4, + @location(1) varying: f32, }; @stage(vertex) @@ -16,9 +16,9 @@ fn vertex( } struct FragmentOutput { - @builtin(frag_depth) depth: f32; - @builtin(sample_mask) sample_mask: u32; - @location(0) color: f32; + @builtin(frag_depth) depth: f32, + @builtin(sample_mask) sample_mask: u32, + @location(0) color: f32, }; @stage(fragment) @@ -47,11 +47,11 @@ fn compute( } struct Input1 { - @builtin(vertex_index) index: u32; + @builtin(vertex_index) index: u32, }; struct Input2 { - @builtin(instance_index) index: u32; + @builtin(instance_index) index: u32, }; @stage(vertex) diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index a3dea61e5..1cb723945 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -1,14 +1,14 @@ //TODO: merge with "interface"? struct FragmentInput { - @builtin(position) position: vec4; - @location(0) @interpolate(flat) flat : u32; - @location(1) @interpolate(linear) linear : f32; - @location(2) @interpolate(linear, centroid) linear_centroid : vec2; - @location(3) @interpolate(linear, sample) linear_sample : vec3; - @location(4) @interpolate(perspective) perspective : vec4; - @location(5) @interpolate(perspective, centroid) perspective_centroid : f32; - @location(6) @interpolate(perspective, sample) perspective_sample : f32; + @builtin(position) position: vec4, + @location(0) @interpolate(flat) flat : u32, + @location(1) @interpolate(linear) linear : f32, + @location(2) @interpolate(linear, centroid) linear_centroid : vec2, + @location(3) @interpolate(linear, sample) linear_sample : vec3, + @location(4) @interpolate(perspective) perspective : vec4, + @location(5) @interpolate(perspective, centroid) perspective_centroid : f32, + @location(6) @interpolate(perspective, sample) perspective_sample : f32, }; @stage(vertex) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 9d472294f..23dbf734c 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -39,8 +39,8 @@ fn bool_cast(x: vec3) -> vec3 { } struct Foo { - a: vec4; - b: i32; + a: vec4, + b: i32, }; fn constructors() -> f32 { diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl index 6eddb7795..cf07d5dbf 100644 --- a/tests/in/pointers.wgsl +++ b/tests/in/pointers.wgsl @@ -5,7 +5,7 @@ fn f() { } struct DynamicArray { - arr: array; + arr: array }; @group(0) @binding(0) diff --git a/tests/in/policy-mix.wgsl b/tests/in/policy-mix.wgsl index fe05a3232..a29556a5b 100644 --- a/tests/in/policy-mix.wgsl +++ b/tests/in/policy-mix.wgsl @@ -3,12 +3,12 @@ // Storage and Uniform storage classes struct InStorage { - a: array, 10>; + a: array, 10> }; @group(0) @binding(0) var in_storage: InStorage; struct InUniform { - a: array, 20>; + a: array, 20> }; @group(0) @binding(1) var in_uniform: InUniform; diff --git a/tests/in/push-constants.wgsl b/tests/in/push-constants.wgsl index d5b4cf99d..4a55ed20a 100644 --- a/tests/in/push-constants.wgsl +++ b/tests/in/push-constants.wgsl @@ -1,10 +1,10 @@ struct PushConstants { - multiplier: f32; + multiplier: f32 }; var pc: PushConstants; struct FragmentIn { - @location(0) color: vec4; + @location(0) color: vec4 }; @stage(fragment) diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 847de8630..37b543397 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -2,8 +2,8 @@ let c_scale: f32 = 1.2; struct VertexOutput { - @location(0) uv : vec2; - @builtin(position) position : vec4; + @location(0) uv : vec2, + @builtin(position) position : vec4, }; @stage(vertex) diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 0b64b2f8d..37e17877c 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -1,6 +1,6 @@ struct Globals { - view_proj: mat4x4; - num_lights: vec4; + view_proj: mat4x4, + num_lights: vec4, }; @group(0) @@ -8,8 +8,8 @@ struct Globals { var u_globals: Globals; struct Entity { - world: mat4x4; - color: vec4; + world: mat4x4, + color: vec4, }; @group(1) @@ -24,9 +24,9 @@ fn vs_bake(@location(0) position: vec4) -> @builtin(position) vec4 { */ struct VertexOutput { - @builtin(position) proj_position: vec4; - @location(0) world_normal: vec3; - @location(1) world_position: vec4; + @builtin(position) proj_position: vec4, + @location(0) world_normal: vec3, + @location(1) world_position: vec4, }; @stage(vertex) @@ -46,9 +46,9 @@ fn vs_main( // fragment shader struct Light { - proj: mat4x4; - pos: vec4; - color: vec4; + proj: mat4x4, + pos: vec4, + color: vec4, }; @group(0) diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index afbc38718..06e5a07aa 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -1,11 +1,11 @@ struct VertexOutput { - @builtin(position) position: vec4; - @location(0) uv: vec3; + @builtin(position) position: vec4, + @location(0) uv: vec3, }; struct Data { - proj_inv: mat4x4; - view: mat4x4; + proj_inv: mat4x4, + view: mat4x4, }; @group(0) @binding(0) var r_data: Data; diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index a5a0a5fc1..bde6da336 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -376,13 +376,13 @@ fn struct_member_zero_size() { check( r#" struct Bar { - @size(0) data: array; + @size(0) data: array }; "#, r#"error: struct member size or alignment must not be 0 ┌─ wgsl:3:23 │ -3 │ @size(0) data: array; +3 │ @size(0) data: array │ ^ struct member size or alignment must not be 0 "#, @@ -394,13 +394,13 @@ fn struct_member_zero_align() { check( r#" struct Bar { - @align(0) data: array; + @align(0) data: array }; "#, r#"error: struct member size or alignment must not be 0 ┌─ wgsl:3:24 │ -3 │ @align(0) data: array; +3 │ @align(0) data: array │ ^ struct member size or alignment must not be 0 "#, @@ -542,7 +542,7 @@ fn postfix_pointers() { check( r#" - struct S { m: i32; }; + struct S { m: i32 }; fn main() { var s: S = S(42); let ps = &s; @@ -655,12 +655,12 @@ fn reserved_keyword() { // struct member check( r#" - struct Foo { sampler: f32; }; + struct Foo { sampler: f32 }; "#, r###"error: name `sampler` is a reserved keyword ┌─ wgsl:2:26 │ -2 │ struct Foo { sampler: f32; }; +2 │ struct Foo { sampler: f32 }; │ ^^^^^^^ definition of `sampler` "###, @@ -843,8 +843,8 @@ fn invalid_arrays() { #[test] fn invalid_structs() { check_validation_error! { - "struct Bad { data: sampler; };", - "struct Bad { data: texture_2d; };": + "struct Bad { data: sampler };", + "struct Bad { data: texture_2d };": Err(naga::valid::ValidationError::Type { error: naga::valid::TypeError::InvalidData(_), .. @@ -852,7 +852,7 @@ fn invalid_structs() { } check_validation_error! { - "struct Bad { data: array; other: f32; };": + "struct Bad { data: array, other: f32, };": Err(naga::valid::ValidationError::Type { error: naga::valid::TypeError::InvalidDynamicArray(_, _), .. @@ -865,7 +865,7 @@ fn invalid_functions() { check_validation_error! { "fn unacceptable_unsized(arg: array) { }", " - struct Unsized { data: array; }; + struct Unsized { data: array }; fn unacceptable_unsized(arg: Unsized) { } ": Err(naga::valid::ValidationError::Function { @@ -883,7 +883,7 @@ fn invalid_functions() { check_validation_error! { "fn unacceptable_unsized(arg: ptr>) { }", " - struct Unsized { data: array; }; + struct Unsized { data: array }; fn unacceptable_unsized(arg: ptr) { } ": Err(naga::valid::ValidationError::Type { @@ -998,8 +998,8 @@ fn missing_bindings() { check_validation_error! { " struct VertexIn { - @location(0) pos: vec4; - uv: vec2; + @location(0) pos: vec4, + uv: vec2 }; @stage(vertex) @@ -1088,7 +1088,7 @@ fn valid_access() { fn invalid_local_vars() { check_validation_error! { " - struct Unsized { data: array; }; + struct Unsized { data: array }; fn local_ptr_dynamic_array(okay: ptr) { var not_okay: ptr> = &(*okay).data; } @@ -1144,12 +1144,12 @@ fn invalid_runtime_sized_arrays() { check_validation_error! { " struct Unsized { - arr: array; + arr: array }; struct Outer { - legit: i32; - unsized: Unsized; + legit: i32, + unsized: Unsized }; @group(0) @binding(0) var outer: Outer; @@ -1187,7 +1187,7 @@ fn select() { } ", " - struct S { member: i32; }; + struct S { member: i32 }; fn select_structs(which: bool) -> S { var x: S = S(1); var y: S = S(2); @@ -1257,7 +1257,7 @@ fn wrong_access_mode() { check_validation_error! { " struct Globals { - i: i32; + i: i32 }; @group(0) @binding(0) @@ -1269,7 +1269,7 @@ fn wrong_access_mode() { ", " struct Globals { - i: i32; + i: i32 }; @group(0) @binding(0) From b5761d96113129ae6ddf82c8d6aa8050abc66b39 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Sun, 13 Mar 2022 00:51:08 +0300 Subject: [PATCH 1624/2212] [wgsl-out] Uses commas to separate struct members instead of semicolons --- src/back/wgsl/writer.rs | 2 +- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 4 +-- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 10 +++--- tests/out/wgsl/210-bevy-shader-vert.wgsl | 12 +++---- tests/out/wgsl/246-collatz-comp.wgsl | 2 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 8 ++--- tests/out/wgsl/896-push-constant-vert.wgsl | 2 +- tests/out/wgsl/access.wgsl | 12 +++---- tests/out/wgsl/bevy-pbr-frag.wgsl | 34 +++++++++---------- tests/out/wgsl/bevy-pbr-vert.wgsl | 14 ++++---- tests/out/wgsl/boids.wgsl | 20 +++++------ tests/out/wgsl/bool-select-frag.wgsl | 2 +- tests/out/wgsl/clamp-splat-vert.wgsl | 2 +- tests/out/wgsl/collatz.wgsl | 2 +- tests/out/wgsl/constant-array-size-vert.wgsl | 2 +- tests/out/wgsl/declarations-vert.wgsl | 20 +++++------ tests/out/wgsl/empty-global-name.wgsl | 2 +- tests/out/wgsl/expressions-frag.wgsl | 4 +-- tests/out/wgsl/extra.wgsl | 8 ++--- tests/out/wgsl/fma-frag.wgsl | 8 ++--- tests/out/wgsl/globals.wgsl | 4 +-- tests/out/wgsl/interface.wgsl | 14 ++++---- tests/out/wgsl/interpolate.wgsl | 16 ++++----- tests/out/wgsl/operators.wgsl | 4 +-- tests/out/wgsl/pointers.wgsl | 2 +- tests/out/wgsl/quad-vert.wgsl | 6 ++-- tests/out/wgsl/quad.wgsl | 4 +-- tests/out/wgsl/quad_glsl-frag.wgsl | 2 +- tests/out/wgsl/quad_glsl-vert.wgsl | 4 +-- tests/out/wgsl/shadow.wgsl | 20 +++++------ tests/out/wgsl/skybox.wgsl | 8 ++--- 31 files changed, 127 insertions(+), 127 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 2d4b0150b..9315e6375 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -419,7 +419,7 @@ impl Writer { let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; write!(self.out, "{}: ", member_name)?; self.write_type(module, member.ty)?; - write!(self.out, ";")?; + write!(self.out, ",")?; writeln!(self.out)?; } diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index cfb3ce6ce..3c7aaf1d1 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -1,9 +1,9 @@ struct ColorMaterial_color { - Color: vec4; + Color: vec4, }; struct FragmentOutput { - @location(0) o_Target: vec4; + @location(0) o_Target: vec4, }; var v_Uv_1: vec2; diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 18a6630f8..b6e70957c 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -1,18 +1,18 @@ struct Camera { - ViewProj: mat4x4; + ViewProj: mat4x4, }; struct Transform { - Model: mat4x4; + Model: mat4x4, }; struct Sprite_size { - size: vec2; + size: vec2, }; struct VertexOutput { - @location(0) v_Uv: vec2; - @builtin(position) member: vec4; + @location(0) v_Uv: vec2, + @builtin(position) member: vec4, }; var Vertex_Position_1: vec3; diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index a2ac6ba10..d7a177cb3 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -1,16 +1,16 @@ struct Camera { - ViewProj: mat4x4; + ViewProj: mat4x4, }; struct Transform { - Model: mat4x4; + Model: mat4x4, }; struct VertexOutput { - @location(0) v_Position: vec3; - @location(1) v_Normal: vec3; - @location(2) v_Uv: vec2; - @builtin(position) member: vec4; + @location(0) v_Position: vec3, + @location(1) v_Normal: vec3, + @location(2) v_Uv: vec2, + @builtin(position) member: vec4, }; var Vertex_Position_1: vec3; diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index a990dd31b..994c028d1 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -1,5 +1,5 @@ struct PrimeIndices { - indices: array; + indices: array, }; @group(0) @binding(0) diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index b57fa3e0b..a3aca9082 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -1,14 +1,14 @@ struct Globals { - view_matrix: mat4x4; + view_matrix: mat4x4, }; struct VertexPushConstants { - world_matrix: mat4x4; + world_matrix: mat4x4, }; struct VertexOutput { - @location(0) frag_color: vec4; - @builtin(position) member: vec4; + @location(0) frag_color: vec4, + @builtin(position) member: vec4, }; @group(0) @binding(0) diff --git a/tests/out/wgsl/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-vert.wgsl index f7f2dcfb3..89e7cee2b 100644 --- a/tests/out/wgsl/896-push-constant-vert.wgsl +++ b/tests/out/wgsl/896-push-constant-vert.wgsl @@ -1,5 +1,5 @@ struct PushConstants { - example: f32; + example: f32, }; var c: PushConstants; diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 1080002ef..cab0428e9 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -1,13 +1,13 @@ struct AlignedWrapper { - value: i32; + value: i32, }; struct Bar { - matrix: mat4x4; - matrix_array: array,2>; - atom: atomic; - arr: array,2>; - data: array; + matrix: mat4x4, + matrix_array: array,2>, + atom: atomic, + arr: array,2>, + data: array, }; @group(0) @binding(0) diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index bf12b515d..d8ef7b2dd 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -1,51 +1,51 @@ struct PointLight { - pos: vec4; - color: vec4; - lightParams: vec4; + pos: vec4, + color: vec4, + lightParams: vec4, }; struct DirectionalLight { - direction: vec4; - color: vec4; + direction: vec4, + color: vec4, }; struct CameraViewProj { - ViewProj: mat4x4; + ViewProj: mat4x4, }; struct CameraPosition { - CameraPos: vec4; + CameraPos: vec4, }; struct Lights { - AmbientColor: vec4; - NumLights: vec4; - PointLights: array; - DirectionalLights: array; + AmbientColor: vec4, + NumLights: vec4, + PointLights: array, + DirectionalLights: array, }; struct StandardMaterial_base_color { - base_color: vec4; + base_color: vec4, }; struct StandardMaterial_roughness { - perceptual_roughness: f32; + perceptual_roughness: f32, }; struct StandardMaterial_metallic { - metallic: f32; + metallic: f32, }; struct StandardMaterial_reflectance { - reflectance: f32; + reflectance: f32, }; struct StandardMaterial_emissive { - emissive: vec4; + emissive: vec4, }; struct FragmentOutput { - @location(0) o_Target: vec4; + @location(0) o_Target: vec4, }; var v_WorldPosition_1: vec3; diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 617537fad..13c7cb935 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -1,17 +1,17 @@ struct CameraViewProj { - ViewProj: mat4x4; + ViewProj: mat4x4, }; struct Transform { - Model: mat4x4; + Model: mat4x4, }; struct VertexOutput { - @location(0) v_WorldPosition: vec3; - @location(1) v_WorldNormal: vec3; - @location(2) v_Uv: vec2; - @location(3) v_WorldTangent: vec4; - @builtin(position) member: vec4; + @location(0) v_WorldPosition: vec3, + @location(1) v_WorldNormal: vec3, + @location(2) v_Uv: vec2, + @location(3) v_WorldTangent: vec4, + @builtin(position) member: vec4, }; var Vertex_Position_1: vec3; diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 1910535ab..bc908aa67 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -1,20 +1,20 @@ struct Particle { - pos: vec2; - vel: vec2; + pos: vec2, + vel: vec2, }; struct SimParams { - deltaT: f32; - rule1Distance: f32; - rule2Distance: f32; - rule3Distance: f32; - rule1Scale: f32; - rule2Scale: f32; - rule3Scale: f32; + deltaT: f32, + rule1Distance: f32, + rule2Distance: f32, + rule3Distance: f32, + rule1Scale: f32, + rule2Scale: f32, + rule3Scale: f32, }; struct Particles { - particles: array; + particles: array, }; let NUM_PARTICLES: u32 = 1500u; diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index c1d5502cf..f44a4416e 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -1,5 +1,5 @@ struct FragmentOutput { - @location(0) o_color: vec4; + @location(0) o_color: vec4, }; var o_color: vec4; diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index 953ea71cc..fd0b8eaf6 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -1,5 +1,5 @@ struct VertexOutput { - @builtin(position) member: vec4; + @builtin(position) member: vec4, }; var a_pos_1: vec2; diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index 334a779e6..37e530c0c 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -1,5 +1,5 @@ struct PrimeIndices { - data: array; + data: array, }; @group(0) @binding(0) diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index f0d5474a2..bf4830dc9 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -1,5 +1,5 @@ struct Data { - vecs: array,42u>; + vecs: array,42u>, }; @group(1) @binding(0) diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index cc5d9c932..ba1cdd58d 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -1,23 +1,23 @@ struct VertexData { - position: vec2; - a: vec2; + position: vec2, + a: vec2, }; struct FragmentData { - position: vec2; - a: vec2; + position: vec2, + a: vec2, }; struct TestStruct { - a: f32; - b: f32; + a: f32, + b: f32, }; struct VertexOutput { - @location(0) position: vec2; - @location(1) a: vec2; - @location(2) out_array: vec4; - @location(3) out_array_1: vec4; + @location(0) position: vec2, + @location(1) a: vec2, + @location(2) out_array: vec4, + @location(3) out_array_1: vec4, }; var vert: VertexData; diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index 1baaf03e2..81334fc8f 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -1,5 +1,5 @@ struct type_1 { - member: i32; + member: i32, }; @group(0) @binding(0) diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 434d24b6a..f487aae83 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -1,9 +1,9 @@ struct BST { - data: i32; + data: i32, }; struct FragmentOutput { - @location(0) o_color: vec4; + @location(0) o_color: vec4, }; var global: f32; diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index e1aaa9c01..98b6bc883 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -1,11 +1,11 @@ struct PushConstants { - index: u32; - double: vec2; + index: u32, + double: vec2, }; struct FragmentIn { - @location(0) color: vec4; - @builtin(primitive_index) primitive_index: u32; + @location(0) color: vec4, + @builtin(primitive_index) primitive_index: u32, }; var pc: PushConstants; diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 8bd668674..3d094d41c 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -1,11 +1,11 @@ struct Mat4x3_ { - mx: vec4; - my: vec4; - mz: vec4; + mx: vec4, + my: vec4, + mz: vec4, }; struct FragmentOutput { - @location(0) o_color: vec4; + @location(0) o_color: vec4, }; var o_color: vec4; diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index d1ab5cbf1..4d60fe89b 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -1,6 +1,6 @@ struct Foo { - v3_: vec3; - v1_: f32; + v3_: vec3, + v1_: f32, }; let Foo_2: bool = true; diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index ad24717f3..9da63f631 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -1,20 +1,20 @@ struct VertexOutput { - @builtin(position) position: vec4; - @location(1) varying: f32; + @builtin(position) position: vec4, + @location(1) varying: f32, }; struct FragmentOutput { - @builtin(frag_depth) depth: f32; - @builtin(sample_mask) sample_mask: u32; - @location(0) color: f32; + @builtin(frag_depth) depth: f32, + @builtin(sample_mask) sample_mask: u32, + @location(0) color: f32, }; struct Input1_ { - @builtin(vertex_index) index: u32; + @builtin(vertex_index) index: u32, }; struct Input2_ { - @builtin(instance_index) index: u32; + @builtin(instance_index) index: u32, }; var output: array; diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index 69ccd9630..a74b65741 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -1,12 +1,12 @@ struct FragmentInput { - @builtin(position) position: vec4; - @location(0) flat: u32; - @location(1) @interpolate(linear) linear: f32; - @location(2) @interpolate(linear, centroid) linear_centroid: vec2; - @location(3) @interpolate(linear, sample) linear_sample: vec3; - @location(4) perspective: vec4; - @location(5) @interpolate(perspective, centroid) perspective_centroid: f32; - @location(6) @interpolate(perspective, sample) perspective_sample: f32; + @builtin(position) position: vec4, + @location(0) flat: u32, + @location(1) @interpolate(linear) linear: f32, + @location(2) @interpolate(linear, centroid) linear_centroid: vec2, + @location(3) @interpolate(linear, sample) linear_sample: vec3, + @location(4) perspective: vec4, + @location(5) @interpolate(perspective, centroid) perspective_centroid: f32, + @location(6) @interpolate(perspective, sample) perspective_sample: f32, }; @stage(vertex) diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index eac31fec0..5beefb4d4 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -1,6 +1,6 @@ struct Foo { - a: vec4; - b: i32; + a: vec4, + b: i32, }; let v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index e06ecb0b1..035e05292 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -1,5 +1,5 @@ struct DynamicArray { - arr: array; + arr: array, }; @group(0) @binding(0) diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index eaec42913..7f598d03f 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -1,10 +1,10 @@ struct gl_PerVertex { - @builtin(position) gl_Position: vec4; + @builtin(position) gl_Position: vec4, }; struct VertexOutput { - @location(0) member: vec2; - @builtin(position) gl_Position: vec4; + @location(0) member: vec2, + @builtin(position) gl_Position: vec4, }; var v_uv: vec2; diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 641f2fd28..01c21bf15 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -1,6 +1,6 @@ struct VertexOutput { - @location(0) uv: vec2; - @builtin(position) position: vec4; + @location(0) uv: vec2, + @builtin(position) position: vec4, }; let c_scale: f32 = 1.2000000476837158; diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 74276c9d6..49dbe9242 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -1,5 +1,5 @@ struct FragmentOutput { - @location(0) o_color: vec4; + @location(0) o_color: vec4, }; var v_uv_1: vec2; diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index 470286a3c..a029b3d43 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -1,6 +1,6 @@ struct VertexOutput { - @location(0) v_uv: vec2; - @builtin(position) member: vec4; + @location(0) v_uv: vec2, + @builtin(position) member: vec4, }; var a_pos_1: vec2; diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index a5dbb554e..41fc7eba2 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -1,23 +1,23 @@ struct Globals { - view_proj: mat4x4; - num_lights: vec4; + view_proj: mat4x4, + num_lights: vec4, }; struct Entity { - world: mat4x4; - color: vec4; + world: mat4x4, + color: vec4, }; struct VertexOutput { - @builtin(position) proj_position: vec4; - @location(0) world_normal: vec3; - @location(1) world_position: vec4; + @builtin(position) proj_position: vec4, + @location(0) world_normal: vec3, + @location(1) world_position: vec4, }; struct Light { - proj: mat4x4; - pos: vec4; - color: vec4; + proj: mat4x4, + pos: vec4, + color: vec4, }; let c_ambient: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index 93b5f06e5..32c2c52d2 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -1,11 +1,11 @@ struct VertexOutput { - @builtin(position) position: vec4; - @location(0) uv: vec3; + @builtin(position) position: vec4, + @location(0) uv: vec3, }; struct Data { - proj_inv: mat4x4; - view: mat4x4; + proj_inv: mat4x4, + view: mat4x4, }; @group(0) @binding(0) From f90e563c281cfc71c794e0426ebcced9e3999202 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Sun, 13 Mar 2022 00:53:34 +0300 Subject: [PATCH 1625/2212] update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index df475b0c1..3406481f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## v0.9 (TBD) - WGSL: + - commas are used to separate struct members intead of semicolons - attributes are declared with `@attrib` instead of `[[attrib]]` - `stride` attribute is removed - block comments are supported From e66a66a7638374922db9a0c02c84e98b397eacae Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Sat, 19 Mar 2022 12:03:57 +0100 Subject: [PATCH 1626/2212] [spv-out] fix wrong MatrixStride for matCx2 and mat2xR --- src/back/spv/writer.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index dad763b24..9da968d8a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -871,12 +871,12 @@ impl Writer { ref other => other, }; if let crate::TypeInner::Matrix { - columns, - rows: _, + columns: _, + rows, width, } = *member_array_subty_inner { - let byte_stride = match columns { + let byte_stride = match rows { crate::VectorSize::Bi => 2 * width, crate::VectorSize::Tri | crate::VectorSize::Quad => 4 * width, }; From 05f050fad485763bf7bf6e1ad4206007b52bc345 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sun, 20 Mar 2022 21:31:55 +0100 Subject: [PATCH 1627/2212] insert padding between struct members --- src/back/hlsl/writer.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index fce74ee91..e082927e7 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -712,7 +712,20 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let struct_name = &self.names[&NameKey::Type(handle)]; writeln!(self.out, "struct {} {{", struct_name)?; + let mut last_offset = 0; for (index, member) in members.iter().enumerate() { + if member.binding.is_none() && member.offset > last_offset { + // using int as padding should work as long as the backend + // doesn't support a type that's less than 4 bytes in size + // (Error::UnsupportedScalar catches this) + let padding = (member.offset - last_offset) / 4; + for i in 0..padding { + writeln!(self.out, "{}int _pad{}_{};", back::INDENT, index, i)?; + } + } + let ty_inner = &module.types[member.ty].inner; + last_offset = member.offset + ty_inner.size(&module.constants); + // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; From cf992a9a95026d8da2f4847e4884e6c0efbba1db Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 22 Mar 2022 11:22:29 +0100 Subject: [PATCH 1628/2212] [wgsl-in] implement while loop --- src/front/wgsl/mod.rs | 34 ++++++++++++++++++++++++++++++++++ src/front/wgsl/tests.rs | 28 +++++++++++++++++++++++++++- tests/in/collatz.wgsl | 5 +---- tests/out/hlsl/collatz.hlsl | 3 ++- tests/out/ir/collatz.ron | 6 +++--- tests/out/msl/collatz.msl | 3 ++- tests/out/spv/collatz.spvasm | 4 ++-- tests/out/wgsl/collatz.wgsl | 3 ++- 8 files changed, 73 insertions(+), 13 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 3f2348b98..977797a25 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3743,6 +3743,40 @@ impl Parser { Some(crate::Statement::Loop { body, continuing }) } + "while" => { + let _ = lexer.next(); + let mut body = crate::Block::new(); + + let (condition, span) = lexer.capture_span(|lexer| { + emitter.start(context.expressions); + let condition = self.parse_general_expression( + lexer, + context.as_expression(&mut body, &mut emitter), + )?; + lexer.expect(Token::Paren('{'))?; + body.extend(emitter.finish(context.expressions)); + Ok(condition) + })?; + let mut reject = crate::Block::new(); + reject.push(crate::Statement::Break, NagaSpan::default()); + body.push( + crate::Statement::If { + condition, + accept: crate::Block::new(), + reject, + }, + NagaSpan::from(span), + ); + + while !lexer.skip(Token::Paren('}')) { + self.parse_statement(lexer, context.reborrow(), &mut body, false)?; + } + + Some(crate::Statement::Loop { + body, + continuing: crate::Block::new(), + }) + } "for" => { let _ = lexer.next(); lexer.expect(Token::Paren('('))?; diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 906311248..1ccff93e8 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -262,6 +262,32 @@ fn parse_loop() { ", ) .unwrap(); + parse_str( + " + fn main() { + var found: bool = false; + var i: i32 = 0; + while !found { + if i == 10 { + found = true; + } + + i = i + 1; + } + } + ", + ) + .unwrap(); + parse_str( + " + fn main() { + while true { + break; + } + } + ", + ) + .unwrap(); parse_str( " fn main() { @@ -418,7 +444,7 @@ fn parse_struct_instantiation() { a: f32, b: vec3, }; - + @stage(fragment) fn fs_main() { var foo: Foo = Foo(0.0, vec3(0.0, 1.0, 42.0)); diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index 15a9d4605..377c0f844 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -14,10 +14,7 @@ var v_indices: PrimeIndices; fn collatz_iterations(n_base: u32) -> u32 { var n = n_base; var i: u32 = 0u; - loop { - if n <= 1u { - break; - } + while n > 1u { if n % 2u == 0u { n = n / 2u; } diff --git a/tests/out/hlsl/collatz.hlsl b/tests/out/hlsl/collatz.hlsl index babae9c90..d74efad89 100644 --- a/tests/out/hlsl/collatz.hlsl +++ b/tests/out/hlsl/collatz.hlsl @@ -9,7 +9,8 @@ uint collatz_iterations(uint n_base) n = n_base; while(true) { uint _expr5 = n; - if ((_expr5 <= 1u)) { + if ((_expr5 > 1u)) { + } else { break; } uint _expr8 = n; diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 5cf3c6b08..50860b2cb 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -125,7 +125,7 @@ ), Constant(2), Binary( - op: LessEqual, + op: Greater, left: 6, right: 7, ), @@ -199,10 +199,10 @@ )), If( condition: 8, - accept: [ + accept: [], + reject: [ Break, ], - reject: [], ), Emit(( start: 8, diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index a1a0788ad..e0f8ece62 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -21,7 +21,8 @@ uint collatz_iterations( n = n_base; while(true) { uint _e5 = n; - if (_e5 <= 1u) { + if (_e5 > 1u) { + } else { break; } uint _e8 = n; diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index bd2dd1f5f..2980ef830 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -57,9 +57,9 @@ OpLoopMerge %22 %24 None OpBranch %23 %23 = OpLabel %25 = OpLoad %4 %13 -%27 = OpULessThanEqual %26 %25 %5 +%27 = OpUGreaterThan %26 %25 %5 OpSelectionMerge %28 None -OpBranchConditional %27 %29 %28 +OpBranchConditional %27 %28 %29 %29 = OpLabel OpBranch %22 %28 = OpLabel diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index 37e530c0c..7b0a134fd 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -12,7 +12,8 @@ fn collatz_iterations(n_base: u32) -> u32 { n = n_base; loop { let _e5 = n; - if (_e5 <= 1u) { + if (_e5 > 1u) { + } else { break; } let _e8 = n; From b568bfbbdfbf534dbf0566cc9e11b43715af4d88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 17 Mar 2022 23:01:00 +0000 Subject: [PATCH 1629/2212] glsl-in: Fix memory qualifiers being inverted Adds some documentation to better explain how the memory qualifier works troughout the parser and some storage textures tests. --- src/front/glsl/ast.rs | 2 + src/front/glsl/lex.rs | 4 +- src/front/glsl/parser/types.rs | 10 +-- src/front/glsl/token.rs | 6 +- src/front/glsl/variables.rs | 10 ++- tests/in/glsl/images.frag | 18 +++++ tests/out/wgsl/images-frag.wgsl | 116 ++++++++++++++++++++++---------- 7 files changed, 115 insertions(+), 51 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 9f28b2bdd..0d5041306 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -175,6 +175,8 @@ pub struct TypeQualifiers<'a> { pub interpolation: Option<(Interpolation, Span)>, pub precision: Option<(Precision, Span)>, pub sampling: Option<(Sampling, Span)>, + /// Memory qualifiers used in the declaration to set the storage access to be used + /// in declarations that support it (storage images and buffers) pub storage_acess: Option<(StorageAccess, Span)>, pub layout_qualifiers: crate::FastHashMap, (QualifierValue, Span)>, } diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index a96f6a701..e3fac8ccc 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -84,8 +84,8 @@ impl<'a> Iterator for Lexer<'a> { "mediump" => TokenValue::PrecisionQualifier(Precision::Medium), "lowp" => TokenValue::PrecisionQualifier(Precision::Low), "restrict" => TokenValue::Restrict, - "readonly" => TokenValue::StorageAccess(StorageAccess::LOAD), - "writeonly" => TokenValue::StorageAccess(StorageAccess::STORE), + "readonly" => TokenValue::MemoryQualifier(StorageAccess::LOAD), + "writeonly" => TokenValue::MemoryQualifier(StorageAccess::STORE), // values "true" => TokenValue::BoolConstant(true), "false" => TokenValue::BoolConstant(false), diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 47ad230d3..7163ab4bc 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -122,7 +122,7 @@ impl<'source> ParsingContext<'source> { | TokenValue::Shared | TokenValue::Buffer | TokenValue::Restrict - | TokenValue::StorageAccess(_) + | TokenValue::MemoryQualifier(_) | TokenValue::Layout => true, _ => false, }) @@ -219,11 +219,11 @@ impl<'source> ParsingContext<'source> { qualifiers.precision = Some((p, token.meta)); } - TokenValue::StorageAccess(access) => { + TokenValue::MemoryQualifier(access) => { let storage_access = qualifiers .storage_acess - .get_or_insert((crate::StorageAccess::empty(), Span::default())); - if storage_access.0.contains(access) { + .get_or_insert((crate::StorageAccess::all(), Span::default())); + if !storage_access.0.contains(!access) { parser.errors.push(Error { kind: ErrorKind::SemanticError( "The same memory qualifier can only be used once".into(), @@ -232,7 +232,7 @@ impl<'source> ParsingContext<'source> { }) } - storage_access.0 |= access; + storage_access.0 &= access; storage_access.1.subsume(token.meta); } TokenValue::Restrict => continue, diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index e522f3f16..ff185e016 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -38,7 +38,11 @@ pub enum TokenValue { Shared, Restrict, - StorageAccess(crate::StorageAccess), + /// A `glsl` memory qualifier such as `writeonly` + /// + /// The associated [`crate::StorageAccess`] is the access being allowed + /// (for example `writeonly` has an associated value of [`crate::StorageAccess::STORE`]) + MemoryQualifier(crate::StorageAccess), Interpolation(Interpolation), Sampling(Sampling), diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 182097b74..fb5f3b362 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -465,8 +465,8 @@ impl Parser { StorageQualifier::AddressSpace(mut space) => { match space { AddressSpace::Storage { ref mut access } => { - if let Some((restricted_access, _)) = qualifiers.storage_acess.take() { - access.remove(restricted_access); + if let Some((allowed_access, _)) = qualifiers.storage_acess.take() { + *access = allowed_access; } } AddressSpace::Uniform => match self.module.types[ty].inner { @@ -480,10 +480,8 @@ impl Parser { mut format, } = class { - if let Some((restricted_access, _)) = - qualifiers.storage_acess.take() - { - access.remove(restricted_access); + if let Some((allowed_access, _)) = qualifiers.storage_acess.take() { + access = allowed_access; } match qualifiers.layout_qualifiers.remove(&QualifierKey::Format) { diff --git a/tests/in/glsl/images.frag b/tests/in/glsl/images.frag index 41679b921..f2aeea23d 100644 --- a/tests/in/glsl/images.frag +++ b/tests/in/glsl/images.frag @@ -8,6 +8,10 @@ layout(rgba8, binding = 4) uniform image1DArray img1DArray; layout(rgba8, binding = 5) uniform image2DArray img2DArray; // layout(rgba8, binding = 6) uniform imageCubeArray imgCubeArray; +layout(rgba8, binding = 7) readonly uniform image2D imgReadOnly; +layout(rgba8, binding = 8) writeonly uniform image2D imgWriteOnly; +layout(rgba8, binding = 9) writeonly readonly uniform image2D imgWriteReadOnly; + void testImg1D(in int coord) { int size = imageSize(img1D); vec4 c = imageLoad(img1D, coord); @@ -52,4 +56,18 @@ void testImg3D(in ivec3 coord) { // imageStore(imgCubeArray, coord, vec4(2)); // } +void testImgReadOnly(in ivec2 coord) { + vec2 size = imageSize(img2D); + vec4 c = imageLoad(imgReadOnly, coord); +} + +void testImgWriteOnly(in ivec2 coord) { + vec2 size = imageSize(img2D); + imageStore(imgWriteOnly, coord, vec4(2)); +} + +void testImgWriteReadOnly(in ivec2 coord) { + vec2 size = imageSize(imgWriteReadOnly); +} + void main() {} diff --git a/tests/out/wgsl/images-frag.wgsl b/tests/out/wgsl/images-frag.wgsl index bd11927f0..4ced4cdbf 100644 --- a/tests/out/wgsl/images-frag.wgsl +++ b/tests/out/wgsl/images-frag.wgsl @@ -8,6 +8,12 @@ var img3D: texture_storage_3d; var img1DArray: texture_storage_1d_array; @group(0) @binding(5) var img2DArray: texture_storage_2d_array; +@group(0) @binding(7) +var imgReadOnly: texture_storage_2d; +@group(0) @binding(8) +var imgWriteOnly: texture_storage_2d; +@group(0) @binding(9) +var imgWriteReadOnly: texture_storage_2d; fn testImg1D(coord: i32) { var coord_1: i32; @@ -15,13 +21,13 @@ fn testImg1D(coord: i32) { var c: vec4; coord_1 = coord; - let _e7 = textureDimensions(img1D); - size = _e7; - let _e10 = coord_1; - let _e11 = textureLoad(img1D, _e10); - c = _e11; - let _e17 = coord_1; - textureStore(img1D, _e17, vec4(f32(2))); + let _e10 = textureDimensions(img1D); + size = _e10; + let _e13 = coord_1; + let _e14 = textureLoad(img1D, _e13); + c = _e14; + let _e20 = coord_1; + textureStore(img1D, _e20, vec4(f32(2))); return; } @@ -31,14 +37,14 @@ fn testImg1DArray(coord_2: vec2) { var c_1: vec4; coord_3 = coord_2; - let _e7 = textureDimensions(img1DArray); - let _e8 = textureNumLayers(img1DArray); - size_1 = vec2(vec2(_e7, _e8)); - let _e13 = coord_3; - let _e16 = textureLoad(img1DArray, _e13.x, _e13.y); - c_1 = _e16; - let _e22 = coord_3; - textureStore(img1DArray, _e22.x, _e22.y, vec4(f32(2))); + let _e10 = textureDimensions(img1DArray); + let _e11 = textureNumLayers(img1DArray); + size_1 = vec2(vec2(_e10, _e11)); + let _e16 = coord_3; + let _e19 = textureLoad(img1DArray, _e16.x, _e16.y); + c_1 = _e19; + let _e25 = coord_3; + textureStore(img1DArray, _e25.x, _e25.y, vec4(f32(2))); return; } @@ -48,13 +54,13 @@ fn testImg2D(coord_4: vec2) { var c_2: vec4; coord_5 = coord_4; - let _e7 = textureDimensions(img2D); - size_2 = vec2(_e7); - let _e11 = coord_5; - let _e12 = textureLoad(img2D, _e11); - c_2 = _e12; - let _e18 = coord_5; - textureStore(img2D, _e18, vec4(f32(2))); + let _e10 = textureDimensions(img2D); + size_2 = vec2(_e10); + let _e14 = coord_5; + let _e15 = textureLoad(img2D, _e14); + c_2 = _e15; + let _e21 = coord_5; + textureStore(img2D, _e21, vec4(f32(2))); return; } @@ -64,14 +70,14 @@ fn testImg2DArray(coord_6: vec3) { var c_3: vec4; coord_7 = coord_6; - let _e7 = textureDimensions(img2DArray); - let _e10 = textureNumLayers(img2DArray); - size_3 = vec3(vec3(_e7.x, _e7.y, _e10)); - let _e15 = coord_7; - let _e18 = textureLoad(img2DArray, _e15.xy, _e15.z); - c_3 = _e18; - let _e24 = coord_7; - textureStore(img2DArray, _e24.xy, _e24.z, vec4(f32(2))); + let _e10 = textureDimensions(img2DArray); + let _e13 = textureNumLayers(img2DArray); + size_3 = vec3(vec3(_e10.x, _e10.y, _e13)); + let _e18 = coord_7; + let _e21 = textureLoad(img2DArray, _e18.xy, _e18.z); + c_3 = _e21; + let _e27 = coord_7; + textureStore(img2DArray, _e27.xy, _e27.z, vec4(f32(2))); return; } @@ -81,13 +87,49 @@ fn testImg3D(coord_8: vec3) { var c_4: vec4; coord_9 = coord_8; - let _e7 = textureDimensions(img3D); - size_4 = vec3(_e7); - let _e11 = coord_9; - let _e12 = textureLoad(img3D, _e11); - c_4 = _e12; - let _e18 = coord_9; - textureStore(img3D, _e18, vec4(f32(2))); + let _e10 = textureDimensions(img3D); + size_4 = vec3(_e10); + let _e14 = coord_9; + let _e15 = textureLoad(img3D, _e14); + c_4 = _e15; + let _e21 = coord_9; + textureStore(img3D, _e21, vec4(f32(2))); + return; +} + +fn testImgReadOnly(coord_10: vec2) { + var coord_11: vec2; + var size_5: vec2; + var c_5: vec4; + + coord_11 = coord_10; + let _e10 = textureDimensions(img2D); + size_5 = vec2(_e10); + let _e14 = coord_11; + let _e15 = textureLoad(imgReadOnly, _e14); + c_5 = _e15; + return; +} + +fn testImgWriteOnly(coord_12: vec2) { + var coord_13: vec2; + var size_6: vec2; + + coord_13 = coord_12; + let _e10 = textureDimensions(img2D); + size_6 = vec2(_e10); + let _e17 = coord_13; + textureStore(imgWriteOnly, _e17, vec4(f32(2))); + return; +} + +fn testImgWriteReadOnly(coord_14: vec2) { + var coord_15: vec2; + var size_7: vec2; + + coord_15 = coord_14; + let _e10 = textureDimensions(imgWriteReadOnly); + size_7 = vec2(_e10); return; } From 54ef2e39a0c550084e4e221c7c71b97f62e94244 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 18 Mar 2022 22:21:57 +0000 Subject: [PATCH 1630/2212] glsl-in: Allow multiple array specifiers --- src/front/glsl/parser/declarations.rs | 15 ++--- src/front/glsl/parser/functions.rs | 10 ++- src/front/glsl/parser/types.rs | 94 +++++++++++++++++---------- src/front/glsl/types.rs | 29 +-------- tests/in/glsl/declarations.vert | 4 ++ tests/out/wgsl/declarations-vert.wgsl | 22 +++++-- 6 files changed, 92 insertions(+), 82 deletions(-) diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index acc200ba2..d39245d8d 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -120,7 +120,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_init_declarator_list( &mut self, parser: &mut Parser, - ty: Handle, + mut ty: Handle, ctx: &mut DeclarationContext, ) -> Result<()> { // init_declarator_list: @@ -169,8 +169,7 @@ impl<'source> ParsingContext<'source> { // parse an array specifier if it exists // NOTE: unlike other parse methods this one doesn't expect an array specifier and // returns Ok(None) rather than an error if there is not one - let array_specifier = self.parse_array_specifier(parser)?; - let ty = parser.maybe_array(ty, meta, array_specifier); + self.parse_array_specifier(parser, &mut meta, &mut ty)?; let init = self .bump_if(parser, TokenValue::Assign) @@ -463,7 +462,7 @@ impl<'source> ParsingContext<'source> { body: &mut Block, qualifiers: &mut TypeQualifiers, ty_name: String, - meta: Span, + mut meta: Span, ) -> Result { let layout = match qualifiers.layout_qualifiers.remove(&QualifierKey::Layout) { Some((QualifierValue::Layout(l), _)) => l, @@ -498,8 +497,7 @@ impl<'source> ParsingContext<'source> { let name = match token.value { TokenValue::Semicolon => None, TokenValue::Identifier(name) => { - let array_specifier = self.parse_array_specifier(parser)?; - ty = parser.maybe_array(ty, token.meta, array_specifier); + self.parse_array_specifier(parser, &mut meta, &mut ty)?; self.expect(parser, TokenValue::Semicolon)?; @@ -561,13 +559,12 @@ impl<'source> ParsingContext<'source> { loop { // TODO: type_qualifier - let (ty, mut meta) = self.parse_type_non_void(parser)?; + let (mut ty, mut meta) = self.parse_type_non_void(parser)?; let (name, end_meta) = self.expect_ident(parser)?; meta.subsume(end_meta); - let array_specifier = self.parse_array_specifier(parser)?; - let ty = parser.maybe_array(ty, meta, array_specifier); + self.parse_array_specifier(parser, &mut meta, &mut ty)?; self.expect(parser, TokenValue::Semicolon)?; diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 797e48dea..ce6f56d8e 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -575,7 +575,7 @@ impl<'source> ParsingContext<'source> { loop { if self.peek_type_name(parser) || self.peek_parameter_qualifier(parser) { let qualifier = self.parse_parameter_qualifier(parser); - let ty = self.parse_type_non_void(parser)?.0; + let mut ty = self.parse_type_non_void(parser)?.0; match self.expect_peek(parser)?.value { TokenValue::Comma => { @@ -584,12 +584,10 @@ impl<'source> ParsingContext<'source> { continue; } TokenValue::Identifier(_) => { - let name_meta = self.expect_ident(parser)?; + let mut name = self.expect_ident(parser)?; + self.parse_array_specifier(parser, &mut name.1, &mut ty)?; - let array_specifier = self.parse_array_specifier(parser)?; - let ty = parser.maybe_array(ty, name_meta.1, array_specifier); - - context.add_function_arg(parser, body, Some(name_meta), ty, qualifier); + context.add_function_arg(parser, body, Some(name), ty, qualifier); if self.bump_if(parser, TokenValue::Comma).is_some() { continue; diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 7163ab4bc..acf0df484 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -10,45 +10,76 @@ use crate::{ }; impl<'source> ParsingContext<'source> { - /// Parses an optional array_specifier returning `Ok(None)` if there is no - /// LeftBracket + /// Parses an optional array_specifier returning wether or not it's present + /// and modifying the type handle if it exists pub fn parse_array_specifier( &mut self, parser: &mut Parser, - ) -> Result> { - if let Some(Token { mut meta, .. }) = self.bump_if(parser, TokenValue::LeftBracket) { - if let Some(Token { meta: end_meta, .. }) = - self.bump_if(parser, TokenValue::RightBracket) - { - meta.subsume(end_meta); - return Ok(Some((ArraySize::Dynamic, meta))); - } + span: &mut Span, + ty: &mut Handle, + ) -> Result<()> { + while self.parse_array_specifier_single(parser, span, ty)? {} + Ok(()) + } - let (value, span) = self.parse_uint_constant(parser)?; - let constant = parser.module.constants.fetch_or_append( - crate::Constant { + /// Implementation of [`Self::parse_array_specifier`] for a single array_specifier + fn parse_array_specifier_single( + &mut self, + parser: &mut Parser, + span: &mut Span, + ty: &mut Handle, + ) -> Result { + if self.bump_if(parser, TokenValue::LeftBracket).is_some() { + let size = + if let Some(Token { meta, .. }) = self.bump_if(parser, TokenValue::RightBracket) { + span.subsume(meta); + ArraySize::Dynamic + } else { + let (value, constant_span) = self.parse_uint_constant(parser)?; + let constant = parser.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(value as u64), + }, + }, + constant_span, + ); + let end_span = self.expect(parser, TokenValue::RightBracket)?.meta; + span.subsume(end_span); + ArraySize::Constant(constant) + }; + + parser + .layouter + .update(&parser.module.types, &parser.module.constants) + .unwrap(); + let stride = parser.layouter[*ty].to_stride(); + *ty = parser.module.types.insert( + Type { name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(value as u64), + inner: TypeInner::Array { + base: *ty, + size, + stride, }, }, - span, + *span, ); - let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; - meta.subsume(end_meta); - Ok(Some((ArraySize::Constant(constant), meta))) + + Ok(true) } else { - Ok(None) + Ok(false) } } pub fn parse_type(&mut self, parser: &mut Parser) -> Result<(Option>, Span)> { let token = self.bump(parser)?; - let handle = match token.value { - TokenValue::Void => None, - TokenValue::TypeName(ty) => Some(parser.module.types.insert(ty, token.meta)), + let mut handle = match token.value { + TokenValue::Void => return Ok((None, token.meta)), + TokenValue::TypeName(ty) => parser.module.types.insert(ty, token.meta), TokenValue::Struct => { let mut meta = token.meta; let ty_name = self.expect_ident(parser)?.0; @@ -66,10 +97,10 @@ impl<'source> ParsingContext<'source> { meta, ); parser.lookup_type.insert(ty_name, ty); - Some(ty) + ty } TokenValue::Identifier(ident) => match parser.lookup_type.get(&ident) { - Some(ty) => Some(*ty), + Some(ty) => *ty, None => { return Err(Error { kind: ErrorKind::UnknownType(ident), @@ -92,12 +123,9 @@ impl<'source> ParsingContext<'source> { } }; - let token_meta = token.meta; - let array_specifier = self.parse_array_specifier(parser)?; - let handle = handle.map(|ty| parser.maybe_array(ty, token_meta, array_specifier)); - let mut meta = array_specifier.map_or(token_meta, |(_, meta)| meta); - meta.subsume(token_meta); - Ok((handle, meta)) + let mut span = token.meta; + self.parse_array_specifier(parser, &mut span, &mut handle)?; + Ok((Some(handle), span)) } pub fn parse_type_non_void(&mut self, parser: &mut Parser) -> Result<(Handle, Span)> { diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 3900fe12d..cf38f9d73 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,7 +1,7 @@ use super::{constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, Span}; use crate::{ - proc::ResolveContext, ArraySize, Bytes, Constant, Expression, Handle, ImageClass, - ImageDimension, ScalarKind, Type, TypeInner, VectorSize, + proc::ResolveContext, Bytes, Constant, Expression, Handle, ImageClass, ImageDimension, + ScalarKind, Type, TypeInner, VectorSize, }; pub fn parse_type(type_name: &str) -> Option { @@ -299,29 +299,4 @@ impl Parser { meta, }) } - - pub(crate) fn maybe_array( - &mut self, - base: Handle, - mut meta: Span, - array_specifier: Option<(ArraySize, Span)>, - ) -> Handle { - match array_specifier { - Some((size, size_meta)) => { - meta.subsume(size_meta); - self.layouter - .update(&self.module.types, &self.module.constants) - .unwrap(); - let stride = self.layouter[base].to_stride(); - self.module.types.insert( - Type { - name: None, - inner: TypeInner::Array { base, size, stride }, - }, - meta, - ) - } - None => base, - } - } } diff --git a/tests/in/glsl/declarations.vert b/tests/in/glsl/declarations.vert index 4d2054caa..75122bc46 100644 --- a/tests/in/glsl/declarations.vert +++ b/tests/in/glsl/declarations.vert @@ -18,6 +18,8 @@ struct TestStruct { float b; }; +float array_2d[2][2]; +float array_toomanyd[2][2][2][2][2][2][2]; void main() { const vec3 positions[2] = vec3[2]( @@ -26,5 +28,7 @@ void main() { ); const TestStruct strct = TestStruct( 1, 2 ); const vec4 from_input_array = in_array[1]; + const float a = array_2d[0][0]; + const float b = array_toomanyd[0][0][0][0][0][0][0]; out_array[0] = vec4(2.0); } diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index ba1cdd58d..42de93fd8 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -24,14 +24,22 @@ var vert: VertexData; var frag: FragmentData; var in_array_2: array,2u>; var out_array: array,2u>; +var array_2d: array,2u>; +var array_toomanyd: array,2u>,2u>,2u>,2u>,2u>,2u>; fn main_1() { var positions: array,2u> = array,2u>(vec3(-1.0, 1.0, 0.0), vec3(-1.0, -1.0, 0.0)); var strct: TestStruct = TestStruct(1.0, 2.0); var from_input_array: vec4; + var a_1: f32; + var b: f32; - let _e32 = in_array_2; - from_input_array = _e32[1]; + let _e34 = in_array_2; + from_input_array = _e34[1]; + let _e39 = array_2d; + a_1 = _e39[0][0]; + let _e50 = array_toomanyd; + b = _e50[0][0][0][0][0][0][0]; out_array[0] = vec4(2.0); return; } @@ -43,9 +51,9 @@ fn main(@location(0) position: vec2, @location(1) a: vec2, @location(2 in_array_2[0] = in_array; in_array_2[1] = in_array_1; main_1(); - let _e26 = frag.position; - let _e28 = frag.a; - let _e31 = out_array[0]; - let _e33 = out_array[1]; - return VertexOutput(_e26, _e28, _e31, _e33); + let _e30 = frag.position; + let _e32 = frag.a; + let _e35 = out_array[0]; + let _e37 = out_array[1]; + return VertexOutput(_e30, _e32, _e35, _e37); } From 3c313564ac8cf933e9cbf05048656044dbfc0b7b Mon Sep 17 00:00:00 2001 From: Pu Xingyu Date: Sun, 27 Mar 2022 13:35:08 +0800 Subject: [PATCH 1631/2212] wgsl-in: Make semicolon after struct decl optional --- src/front/wgsl/mod.rs | 1 - src/front/wgsl/tests.rs | 8 +++--- tests/in/access.wgsl | 4 +-- tests/in/boids.wgsl | 6 ++--- tests/in/bounds-check-restrict.wgsl | 2 +- tests/in/bounds-check-zero-atomic.wgsl | 2 +- tests/in/bounds-check-zero.wgsl | 2 +- tests/in/collatz.wgsl | 2 +- tests/in/extra.wgsl | 4 +-- tests/in/globals.wgsl | 2 +- tests/in/interface.wgsl | 8 +++--- tests/in/interpolate.wgsl | 2 +- tests/in/operators.wgsl | 2 +- tests/in/pointers.wgsl | 2 +- tests/in/policy-mix.wgsl | 4 +-- tests/in/push-constants.wgsl | 4 +-- tests/in/quad.wgsl | 2 +- tests/in/shadow.wgsl | 8 +++--- tests/in/skybox.wgsl | 4 +-- tests/wgsl-errors.rs | 36 +++++++++++++------------- 20 files changed, 52 insertions(+), 53 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 977797a25..30f2864bf 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -4228,7 +4228,6 @@ impl Parser { type_span, ); self.lookup_type.insert(name.to_owned(), ty); - lexer.expect(Token::Separator(';'))?; } (Token::Word("type"), _) => { let name = lexer.next_ident()?; diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 1ccff93e8..281bd21f6 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -157,13 +157,13 @@ fn parse_type_cast() { fn parse_struct() { parse_str( " - struct Foo { x: i32 }; + struct Foo { x: i32 } struct Bar { @size(16) x: vec2, @align(16) y: f32, @size(32) @align(8) z: vec3, }; - struct Empty {}; + struct Empty {} var s: Foo; ", ) @@ -443,7 +443,7 @@ fn parse_struct_instantiation() { struct Foo { a: f32, b: vec3, - }; + } @stage(fragment) fn fs_main() { @@ -460,7 +460,7 @@ fn parse_array_length() { " struct Foo { data: array - }; // this is used as both input and output for convenience + } // this is used as both input and output for convenience @group(0) @binding(0) var foo: Foo; diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 390a018b1..7c96367ac 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -2,7 +2,7 @@ struct AlignedWrapper { @align(8) value: i32 -}; +} struct Bar { matrix: mat4x4, @@ -10,7 +10,7 @@ struct Bar { atom: atomic, arr: array, 2>, data: array, -}; +} @group(0) @binding(0) var bar: Bar; diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 2655f2783..7194d4878 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -3,7 +3,7 @@ let NUM_PARTICLES: u32 = 1500u; struct Particle { pos : vec2, vel : vec2, -}; +} struct SimParams { deltaT : f32, @@ -13,11 +13,11 @@ struct SimParams { rule1Scale : f32, rule2Scale : f32, rule3Scale : f32, -}; +} struct Particles { particles : array -}; +} @group(0) @binding(0) var params : SimParams; @group(0) @binding(1) var particlesSrc : Particles; diff --git a/tests/in/bounds-check-restrict.wgsl b/tests/in/bounds-check-restrict.wgsl index d88be39fb..2b7208355 100644 --- a/tests/in/bounds-check-restrict.wgsl +++ b/tests/in/bounds-check-restrict.wgsl @@ -5,7 +5,7 @@ struct Globals { v: vec4, m: mat3x4, d: array, -}; +} @group(0) @binding(0) var globals: Globals; diff --git a/tests/in/bounds-check-zero-atomic.wgsl b/tests/in/bounds-check-zero-atomic.wgsl index c64cc8bd0..3cdbea14a 100644 --- a/tests/in/bounds-check-zero-atomic.wgsl +++ b/tests/in/bounds-check-zero-atomic.wgsl @@ -8,7 +8,7 @@ struct Globals { a: atomic, b: array, 10>, c: array>, -}; +} @group(0) @binding(0) var globals: Globals; diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl index 1dbfd9cb5..010f46ec3 100644 --- a/tests/in/bounds-check-zero.wgsl +++ b/tests/in/bounds-check-zero.wgsl @@ -5,7 +5,7 @@ struct Globals { v: vec4, m: mat3x4, d: array, -}; +} @group(0) @binding(0) var globals: Globals; diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index 377c0f844..b2d990732 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -1,6 +1,6 @@ struct PrimeIndices { data: array -}; // this is used as both input and output for convenience +} // this is used as both input and output for convenience @group(0) @binding(0) var v_indices: PrimeIndices; diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index 6dcecd553..a0130da17 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -1,13 +1,13 @@ struct PushConstants { index: u32, double: vec2, -}; +} var pc: PushConstants; struct FragmentIn { @location(0) color: vec4, @builtin(primitive_index) primitive_index: u32, -}; +} @stage(fragment) fn main(in: FragmentIn) -> @location(0) vec4 { diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index ed8c40a70..0dff3f8e7 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -9,7 +9,7 @@ struct Foo { v3: vec3, // test packed vec3 v1: f32, -}; +} @group(0) @binding(1) var alignment: Foo; diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index d2cf84023..3655ba9b8 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -3,7 +3,7 @@ struct VertexOutput { @builtin(position) position: vec4, @location(1) varying: f32, -}; +} @stage(vertex) fn vertex( @@ -19,7 +19,7 @@ struct FragmentOutput { @builtin(frag_depth) depth: f32, @builtin(sample_mask) sample_mask: u32, @location(0) color: f32, -}; +} @stage(fragment) fn fragment( @@ -48,11 +48,11 @@ fn compute( struct Input1 { @builtin(vertex_index) index: u32, -}; +} struct Input2 { @builtin(instance_index) index: u32, -}; +} @stage(vertex) fn vertex_two_structs(in1: Input1, in2: Input2) -> @builtin(position) vec4 { diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index 1cb723945..86753a83e 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -9,7 +9,7 @@ struct FragmentInput { @location(4) @interpolate(perspective) perspective : vec4, @location(5) @interpolate(perspective, centroid) perspective_centroid : f32, @location(6) @interpolate(perspective, sample) perspective_sample : f32, -}; +} @stage(vertex) fn vert_main() -> FragmentInput { diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 23dbf734c..4af87d48e 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -41,7 +41,7 @@ fn bool_cast(x: vec3) -> vec3 { struct Foo { a: vec4, b: i32, -}; +} fn constructors() -> f32 { var foo: Foo; diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl index cf07d5dbf..bfd88c946 100644 --- a/tests/in/pointers.wgsl +++ b/tests/in/pointers.wgsl @@ -6,7 +6,7 @@ fn f() { struct DynamicArray { arr: array -}; +} @group(0) @binding(0) var dynamic_array: DynamicArray; diff --git a/tests/in/policy-mix.wgsl b/tests/in/policy-mix.wgsl index a29556a5b..f1fb72389 100644 --- a/tests/in/policy-mix.wgsl +++ b/tests/in/policy-mix.wgsl @@ -4,12 +4,12 @@ // Storage and Uniform storage classes struct InStorage { a: array, 10> -}; +} @group(0) @binding(0) var in_storage: InStorage; struct InUniform { a: array, 20> -}; +} @group(0) @binding(1) var in_uniform: InUniform; // Textures automatically land in the `handle` storage class. diff --git a/tests/in/push-constants.wgsl b/tests/in/push-constants.wgsl index 4a55ed20a..e0bf46758 100644 --- a/tests/in/push-constants.wgsl +++ b/tests/in/push-constants.wgsl @@ -1,11 +1,11 @@ struct PushConstants { multiplier: f32 -}; +} var pc: PushConstants; struct FragmentIn { @location(0) color: vec4 -}; +} @stage(fragment) fn main(in: FragmentIn) -> @location(0) vec4 { diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 37b543397..590ba0e4c 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -4,7 +4,7 @@ let c_scale: f32 = 1.2; struct VertexOutput { @location(0) uv : vec2, @builtin(position) position : vec4, -}; +} @stage(vertex) fn vert_main( diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 37e17877c..af46ec0d4 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -1,7 +1,7 @@ struct Globals { view_proj: mat4x4, num_lights: vec4, -}; +} @group(0) @binding(0) @@ -10,7 +10,7 @@ var u_globals: Globals; struct Entity { world: mat4x4, color: vec4, -}; +} @group(1) @binding(0) @@ -27,7 +27,7 @@ struct VertexOutput { @builtin(position) proj_position: vec4, @location(0) world_normal: vec3, @location(1) world_position: vec4, -}; +} @stage(vertex) fn vs_main( @@ -49,7 +49,7 @@ struct Light { proj: mat4x4, pos: vec4, color: vec4, -}; +} @group(0) @binding(1) diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index 06e5a07aa..0b589c7f5 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -1,12 +1,12 @@ struct VertexOutput { @builtin(position) position: vec4, @location(0) uv: vec3, -}; +} struct Data { proj_inv: mat4x4, view: mat4x4, -}; +} @group(0) @binding(0) var r_data: Data; diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index bde6da336..7e6b3578e 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -377,7 +377,7 @@ fn struct_member_zero_size() { r#" struct Bar { @size(0) data: array - }; + } "#, r#"error: struct member size or alignment must not be 0 ┌─ wgsl:3:23 @@ -395,7 +395,7 @@ fn struct_member_zero_align() { r#" struct Bar { @align(0) data: array - }; + } "#, r#"error: struct member size or alignment must not be 0 ┌─ wgsl:3:24 @@ -641,12 +641,12 @@ fn reserved_keyword() { // struct check( r#" - struct array {}; + struct array {} "#, r###"error: name `array` is a reserved keyword ┌─ wgsl:2:20 │ -2 │ struct array {}; +2 │ struct array {} │ ^^^^^ definition of `array` "###, @@ -655,12 +655,12 @@ fn reserved_keyword() { // struct member check( r#" - struct Foo { sampler: f32 }; + struct Foo { sampler: f32 } "#, r###"error: name `sampler` is a reserved keyword ┌─ wgsl:2:26 │ -2 │ struct Foo { sampler: f32 }; +2 │ struct Foo { sampler: f32 } │ ^^^^^^^ definition of `sampler` "###, @@ -843,8 +843,8 @@ fn invalid_arrays() { #[test] fn invalid_structs() { check_validation_error! { - "struct Bad { data: sampler };", - "struct Bad { data: texture_2d };": + "struct Bad { data: sampler }", + "struct Bad { data: texture_2d }": Err(naga::valid::ValidationError::Type { error: naga::valid::TypeError::InvalidData(_), .. @@ -852,7 +852,7 @@ fn invalid_structs() { } check_validation_error! { - "struct Bad { data: array, other: f32, };": + "struct Bad { data: array, other: f32, }": Err(naga::valid::ValidationError::Type { error: naga::valid::TypeError::InvalidDynamicArray(_, _), .. @@ -865,7 +865,7 @@ fn invalid_functions() { check_validation_error! { "fn unacceptable_unsized(arg: array) { }", " - struct Unsized { data: array }; + struct Unsized { data: array } fn unacceptable_unsized(arg: Unsized) { } ": Err(naga::valid::ValidationError::Function { @@ -883,7 +883,7 @@ fn invalid_functions() { check_validation_error! { "fn unacceptable_unsized(arg: ptr>) { }", " - struct Unsized { data: array }; + struct Unsized { data: array } fn unacceptable_unsized(arg: ptr) { } ": Err(naga::valid::ValidationError::Type { @@ -1000,7 +1000,7 @@ fn missing_bindings() { struct VertexIn { @location(0) pos: vec4, uv: vec2 - }; + } @stage(vertex) fn vertex(input: VertexIn) -> @location(0) vec4 { @@ -1088,7 +1088,7 @@ fn valid_access() { fn invalid_local_vars() { check_validation_error! { " - struct Unsized { data: array }; + struct Unsized { data: array } fn local_ptr_dynamic_array(okay: ptr) { var not_okay: ptr> = &(*okay).data; } @@ -1145,12 +1145,12 @@ fn invalid_runtime_sized_arrays() { " struct Unsized { arr: array - }; + } struct Outer { legit: i32, unsized: Unsized - }; + } @group(0) @binding(0) var outer: Outer; @@ -1187,7 +1187,7 @@ fn select() { } ", " - struct S { member: i32 }; + struct S { member: i32 } fn select_structs(which: bool) -> S { var x: S = S(1); var y: S = S(2); @@ -1258,7 +1258,7 @@ fn wrong_access_mode() { " struct Globals { i: i32 - }; + } @group(0) @binding(0) var globals: Globals; @@ -1270,7 +1270,7 @@ fn wrong_access_mode() { " struct Globals { i: i32 - }; + } @group(0) @binding(0) var globals: Globals; From b17e6cfe43bcd1bf7982bd3c09ea728c2c72f60f Mon Sep 17 00:00:00 2001 From: Pu Xingyu Date: Sun, 27 Mar 2022 14:56:34 +0800 Subject: [PATCH 1632/2212] wgsl-out: Do not output semicolon after struct decl --- src/back/wgsl/writer.rs | 2 +- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 4 ++-- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 8 +++---- tests/out/wgsl/210-bevy-shader-vert.wgsl | 6 ++--- tests/out/wgsl/246-collatz-comp.wgsl | 2 +- .../wgsl/800-out-of-bounds-panic-vert.wgsl | 6 ++--- tests/out/wgsl/896-push-constant-vert.wgsl | 2 +- tests/out/wgsl/access.wgsl | 4 ++-- tests/out/wgsl/bevy-pbr-frag.wgsl | 22 +++++++++---------- tests/out/wgsl/bevy-pbr-vert.wgsl | 6 ++--- tests/out/wgsl/boids.wgsl | 6 ++--- tests/out/wgsl/bool-select-frag.wgsl | 2 +- tests/out/wgsl/clamp-splat-vert.wgsl | 2 +- tests/out/wgsl/collatz.wgsl | 2 +- tests/out/wgsl/constant-array-size-vert.wgsl | 2 +- tests/out/wgsl/declarations-vert.wgsl | 8 +++---- tests/out/wgsl/empty-global-name.wgsl | 2 +- tests/out/wgsl/expressions-frag.wgsl | 4 ++-- tests/out/wgsl/extra.wgsl | 4 ++-- tests/out/wgsl/fma-frag.wgsl | 4 ++-- tests/out/wgsl/globals.wgsl | 2 +- tests/out/wgsl/interface.wgsl | 8 +++---- tests/out/wgsl/interpolate.wgsl | 2 +- tests/out/wgsl/operators.wgsl | 2 +- tests/out/wgsl/pointers.wgsl | 2 +- tests/out/wgsl/quad-vert.wgsl | 4 ++-- tests/out/wgsl/quad.wgsl | 2 +- tests/out/wgsl/quad_glsl-frag.wgsl | 2 +- tests/out/wgsl/quad_glsl-vert.wgsl | 2 +- tests/out/wgsl/shadow.wgsl | 8 +++---- tests/out/wgsl/skybox.wgsl | 4 ++-- 31 files changed, 68 insertions(+), 68 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 9315e6375..a85ade071 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -423,7 +423,7 @@ impl Writer { writeln!(self.out)?; } - write!(self.out, "}};")?; + write!(self.out, "}}")?; writeln!(self.out)?; diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index 3c7aaf1d1..e9f9c92a6 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -1,10 +1,10 @@ struct ColorMaterial_color { Color: vec4, -}; +} struct FragmentOutput { @location(0) o_Target: vec4, -}; +} var v_Uv_1: vec2; var o_Target: vec4; diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index b6e70957c..cec816f8a 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -1,19 +1,19 @@ struct Camera { ViewProj: mat4x4, -}; +} struct Transform { Model: mat4x4, -}; +} struct Sprite_size { size: vec2, -}; +} struct VertexOutput { @location(0) v_Uv: vec2, @builtin(position) member: vec4, -}; +} var Vertex_Position_1: vec3; var Vertex_Normal_1: vec3; diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index d7a177cb3..454a426cd 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -1,17 +1,17 @@ struct Camera { ViewProj: mat4x4, -}; +} struct Transform { Model: mat4x4, -}; +} struct VertexOutput { @location(0) v_Position: vec3, @location(1) v_Normal: vec3, @location(2) v_Uv: vec2, @builtin(position) member: vec4, -}; +} var Vertex_Position_1: vec3; var Vertex_Normal_1: vec3; diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 994c028d1..03e6f1356 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -1,6 +1,6 @@ struct PrimeIndices { indices: array, -}; +} @group(0) @binding(0) var global: PrimeIndices; diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index a3aca9082..c0c1581db 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -1,15 +1,15 @@ struct Globals { view_matrix: mat4x4, -}; +} struct VertexPushConstants { world_matrix: mat4x4, -}; +} struct VertexOutput { @location(0) frag_color: vec4, @builtin(position) member: vec4, -}; +} @group(0) @binding(0) var global: Globals; diff --git a/tests/out/wgsl/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-vert.wgsl index 89e7cee2b..f4892e00d 100644 --- a/tests/out/wgsl/896-push-constant-vert.wgsl +++ b/tests/out/wgsl/896-push-constant-vert.wgsl @@ -1,6 +1,6 @@ struct PushConstants { example: f32, -}; +} var c: PushConstants; diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index cab0428e9..1e07fc933 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -1,6 +1,6 @@ struct AlignedWrapper { value: i32, -}; +} struct Bar { matrix: mat4x4, @@ -8,7 +8,7 @@ struct Bar { atom: atomic, arr: array,2>, data: array, -}; +} @group(0) @binding(0) var bar: Bar; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index d8ef7b2dd..5d0445075 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -2,51 +2,51 @@ struct PointLight { pos: vec4, color: vec4, lightParams: vec4, -}; +} struct DirectionalLight { direction: vec4, color: vec4, -}; +} struct CameraViewProj { ViewProj: mat4x4, -}; +} struct CameraPosition { CameraPos: vec4, -}; +} struct Lights { AmbientColor: vec4, NumLights: vec4, PointLights: array, DirectionalLights: array, -}; +} struct StandardMaterial_base_color { base_color: vec4, -}; +} struct StandardMaterial_roughness { perceptual_roughness: f32, -}; +} struct StandardMaterial_metallic { metallic: f32, -}; +} struct StandardMaterial_reflectance { reflectance: f32, -}; +} struct StandardMaterial_emissive { emissive: vec4, -}; +} struct FragmentOutput { @location(0) o_Target: vec4, -}; +} var v_WorldPosition_1: vec3; var v_WorldNormal_1: vec3; diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 13c7cb935..124914c13 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -1,10 +1,10 @@ struct CameraViewProj { ViewProj: mat4x4, -}; +} struct Transform { Model: mat4x4, -}; +} struct VertexOutput { @location(0) v_WorldPosition: vec3, @@ -12,7 +12,7 @@ struct VertexOutput { @location(2) v_Uv: vec2, @location(3) v_WorldTangent: vec4, @builtin(position) member: vec4, -}; +} var Vertex_Position_1: vec3; var Vertex_Normal_1: vec3; diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index bc908aa67..e166308ed 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -1,7 +1,7 @@ struct Particle { pos: vec2, vel: vec2, -}; +} struct SimParams { deltaT: f32, @@ -11,11 +11,11 @@ struct SimParams { rule1Scale: f32, rule2Scale: f32, rule3Scale: f32, -}; +} struct Particles { particles: array, -}; +} let NUM_PARTICLES: u32 = 1500u; diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index f44a4416e..ac22cfa89 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -1,6 +1,6 @@ struct FragmentOutput { @location(0) o_color: vec4, -}; +} var o_color: vec4; diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index fd0b8eaf6..227f49aab 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -1,6 +1,6 @@ struct VertexOutput { @builtin(position) member: vec4, -}; +} var a_pos_1: vec2; var gl_Position: vec4; diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index 7b0a134fd..e81b1fa1c 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -1,6 +1,6 @@ struct PrimeIndices { data: array, -}; +} @group(0) @binding(0) var v_indices: PrimeIndices; diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index bf4830dc9..2408f8104 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -1,6 +1,6 @@ struct Data { vecs: array,42u>, -}; +} @group(1) @binding(0) var global: Data; diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index 42de93fd8..cfd2528f3 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -1,24 +1,24 @@ struct VertexData { position: vec2, a: vec2, -}; +} struct FragmentData { position: vec2, a: vec2, -}; +} struct TestStruct { a: f32, b: f32, -}; +} struct VertexOutput { @location(0) position: vec2, @location(1) a: vec2, @location(2) out_array: vec4, @location(3) out_array_1: vec4, -}; +} var vert: VertexData; var frag: FragmentData; diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index 81334fc8f..8d6d3f9a0 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -1,6 +1,6 @@ struct type_1 { member: i32, -}; +} @group(0) @binding(0) var unnamed: type_1; diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index f487aae83..30d6b30fc 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -1,10 +1,10 @@ struct BST { data: i32, -}; +} struct FragmentOutput { @location(0) o_color: vec4, -}; +} var global: f32; var o_color: vec4; diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index 98b6bc883..0090ffad0 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -1,12 +1,12 @@ struct PushConstants { index: u32, double: vec2, -}; +} struct FragmentIn { @location(0) color: vec4, @builtin(primitive_index) primitive_index: u32, -}; +} var pc: PushConstants; diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 3d094d41c..3c2233abf 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -2,11 +2,11 @@ struct Mat4x3_ { mx: vec4, my: vec4, mz: vec4, -}; +} struct FragmentOutput { @location(0) o_color: vec4, -}; +} var o_color: vec4; diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 4d60fe89b..2437556f2 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -1,7 +1,7 @@ struct Foo { v3_: vec3, v1_: f32, -}; +} let Foo_2: bool = true; diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index 9da63f631..d2584caab 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -1,21 +1,21 @@ struct VertexOutput { @builtin(position) position: vec4, @location(1) varying: f32, -}; +} struct FragmentOutput { @builtin(frag_depth) depth: f32, @builtin(sample_mask) sample_mask: u32, @location(0) color: f32, -}; +} struct Input1_ { @builtin(vertex_index) index: u32, -}; +} struct Input2_ { @builtin(instance_index) index: u32, -}; +} var output: array; diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index a74b65741..ca3db022b 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -7,7 +7,7 @@ struct FragmentInput { @location(4) perspective: vec4, @location(5) @interpolate(perspective, centroid) perspective_centroid: f32, @location(6) @interpolate(perspective, sample) perspective_sample: f32, -}; +} @stage(vertex) fn vert_main() -> FragmentInput { diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 5beefb4d4..d8e1a4267 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -1,7 +1,7 @@ struct Foo { a: vec4, b: i32, -}; +} let v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl index 035e05292..5269e16f7 100644 --- a/tests/out/wgsl/pointers.wgsl +++ b/tests/out/wgsl/pointers.wgsl @@ -1,6 +1,6 @@ struct DynamicArray { arr: array, -}; +} @group(0) @binding(0) var dynamic_array: DynamicArray; diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index 7f598d03f..b56803725 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -1,11 +1,11 @@ struct gl_PerVertex { @builtin(position) gl_Position: vec4, -}; +} struct VertexOutput { @location(0) member: vec2, @builtin(position) gl_Position: vec4, -}; +} var v_uv: vec2; var a_uv_1: vec2; diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 01c21bf15..5b565a281 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -1,7 +1,7 @@ struct VertexOutput { @location(0) uv: vec2, @builtin(position) position: vec4, -}; +} let c_scale: f32 = 1.2000000476837158; diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 49dbe9242..58cde6e33 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -1,6 +1,6 @@ struct FragmentOutput { @location(0) o_color: vec4, -}; +} var v_uv_1: vec2; var o_color: vec4; diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index a029b3d43..6fd0b186e 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -1,7 +1,7 @@ struct VertexOutput { @location(0) v_uv: vec2, @builtin(position) member: vec4, -}; +} var a_pos_1: vec2; var a_uv_1: vec2; diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 41fc7eba2..2b0747df3 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -1,24 +1,24 @@ struct Globals { view_proj: mat4x4, num_lights: vec4, -}; +} struct Entity { world: mat4x4, color: vec4, -}; +} struct VertexOutput { @builtin(position) proj_position: vec4, @location(0) world_normal: vec3, @location(1) world_position: vec4, -}; +} struct Light { proj: mat4x4, pos: vec4, color: vec4, -}; +} let c_ambient: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); let c_max_lights: u32 = 10u; diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index 32c2c52d2..e40793757 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -1,12 +1,12 @@ struct VertexOutput { @builtin(position) position: vec4, @location(0) uv: vec3, -}; +} struct Data { proj_inv: mat4x4, view: mat4x4, -}; +} @group(0) @binding(0) var r_data: Data; From d62c0838a6717c5132261adba46122f57433f4f4 Mon Sep 17 00:00:00 2001 From: Pu Xingyu Date: Sun, 27 Mar 2022 14:59:00 +0800 Subject: [PATCH 1633/2212] Update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3406481f3..3a7dd30bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## v0.9 (TBD) - WGSL: + - semicolon after struct declaration are now optional - commas are used to separate struct members intead of semicolons - attributes are declared with `@attrib` instead of `[[attrib]]` - `stride` attribute is removed From 9dddfeec37dbd9c55fb6ada97d1db5bb708b5bd8 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 22 Mar 2022 16:07:54 +0100 Subject: [PATCH 1634/2212] [wgsl-in] implement increment and decrement --- src/front/wgsl/lexer.rs | 11 +++- src/front/wgsl/mod.rs | 73 ++++++++++++++++++++-- tests/in/operators.wgsl | 2 + tests/in/shadow.wgsl | 4 +- tests/out/glsl/operators.main.Compute.glsl | 4 ++ tests/out/hlsl/operators.hlsl | 4 ++ tests/out/msl/operators.msl | 4 ++ tests/out/spv/operators.spvasm | 40 +++++++----- tests/out/wgsl/operators.wgsl | 4 ++ 9 files changed, 122 insertions(+), 24 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index bdebb74d6..93286f588 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -385,11 +385,20 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { match chars.next() { Some('>') => (Token::Arrow, chars.as_str()), Some('0'..='9') | Some('.') => consume_number(input), + Some('-') => (Token::DecrementOperation, chars.as_str()), Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), _ => (Token::Operation(cur), sub_input), } } - '+' | '*' | '%' | '^' => { + '+' => { + input = chars.as_str(); + match chars.next() { + Some('+') => (Token::IncrementOperation, chars.as_str()), + Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), + _ => (Token::Operation(cur), input), + } + } + '*' | '%' | '^' => { input = chars.as_str(); if chars.next() == Some('=') { (Token::AssignmentOperation(cur), chars.as_str()) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 30f2864bf..7d30dfb36 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -67,6 +67,8 @@ pub enum Token<'a> { LogicalOperation(char), ShiftOperation(char), AssignmentOperation(char), + IncrementOperation, + DecrementOperation, Arrow, Unknown(char), UnterminatedString, @@ -142,6 +144,7 @@ pub enum Error<'a> { kind: crate::ScalarKind, width: u8, }, + BadIncrDecrReferenceType(Span), InvalidResolve(ResolveError), InvalidForInitializer(Span), InvalidGatherComponent(Span, i32), @@ -196,6 +199,8 @@ impl<'a> Error<'a> { Token::ShiftOperation(c) => format!("bitshift ('{}{}')", c, c), Token::AssignmentOperation(c) if c=='<' || c=='>' => format!("bitshift ('{}{}=')", c, c), Token::AssignmentOperation(c) => format!("operation ('{}=')", c), + Token::IncrementOperation => "increment operation".to_string(), + Token::DecrementOperation => "decrement operation".to_string(), Token::Arrow => "->".to_string(), Token::Unknown(c) => format!("unknown ('{}')", c), Token::UnterminatedString => "unterminated string".to_string(), @@ -317,6 +322,11 @@ impl<'a> Error<'a> { labels: vec![(span.clone(), "must be one of f32, i32 or u32".into())], notes: vec![], }, + Error::BadIncrDecrReferenceType(ref span) => ParseError { + message: "increment/decrement operation requires reference type to be one of i32 or u32".to_string(), + labels: vec![(span.clone(), "must be a reference type of i32 or u32".into())], + notes: vec![], + }, Error::BadTexture(ref bad_span) => ParseError { message: format!("expected an image, but found '{}' which is not an image", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "not an image".into())], @@ -3252,7 +3262,7 @@ impl Parser { Ok((handle, storage_access)) } - /// Parse a assignment statement + /// Parse an assignment statement (will also parse increment and decrement statements) fn parse_assignment_statement<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, @@ -3264,11 +3274,11 @@ impl Parser { context.emitter.start(context.expressions); let reference = self.parse_unary_expression(lexer, context.reborrow())?; // The left hand side of an assignment must be a reference. + let lhs_span = span_start..lexer.current_byte_offset(); if !reference.is_reference { - let span = span_start..lexer.current_byte_offset(); return Err(Error::NotReference( "the left-hand side of an assignment", - span, + lhs_span, )); } @@ -3295,13 +3305,68 @@ impl Parser { crate::Expression::Load { pointer: reference.handle, }, - NagaSpan::from(span_start..lexer.current_byte_offset()), + lhs_span.into(), ); let right = self.parse_general_expression(lexer, context.reborrow())?; context .expressions .append(crate::Expression::Binary { op, left, right }, span.into()) } + (op @ Token::IncrementOperation | op @ Token::DecrementOperation, op_span) => { + let op = match op { + Token::IncrementOperation => Bo::Add, + Token::DecrementOperation => Bo::Subtract, + _ => unreachable!(), + }; + + // prepare the typifier, but work around mutable borrowing... + let _ = context.resolve_type(reference.handle)?; + + let ty = context.typifier.get(reference.handle, context.types); + let constant_inner = match ty.canonical_form(context.types) { + Some(crate::TypeInner::ValuePointer { + size: None, + kind, + width, + space: _, + }) => crate::ConstantInner::Scalar { + width, + value: match kind { + crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), + crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), + _ => { + return Err(Error::BadIncrDecrReferenceType(lhs_span)); + } + }, + }, + _ => { + return Err(Error::BadIncrDecrReferenceType(lhs_span)); + } + }; + let constant = context.constants.append( + crate::Constant { + name: None, + specialization: None, + inner: constant_inner, + }, + crate::Span::default(), + ); + + let left = context.expressions.append( + crate::Expression::Load { + pointer: reference.handle, + }, + lhs_span.into(), + ); + let right = context.interrupt_emitter( + crate::Expression::Constant(constant), + crate::Span::default(), + ); + context.expressions.append( + crate::Expression::Binary { op, left, right }, + op_span.into(), + ) + } other => return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)), }; diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 4af87d48e..996f528d4 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -94,6 +94,8 @@ fn binary_assignment() { a %= 1; a ^= 0; a &= 0; + a++; + a--; } @stage(compute) @workgroup_size(1) diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index af46ec0d4..bce4720cf 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -85,7 +85,7 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { let normal = normalize(in.world_normal); // accumulate color var color: vec3 = c_ambient; - for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i += 1u) { + for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i++) { let light = s_lights[i]; // project into the light space let shadow = fetch_shadow(i, light.proj * in.world_position); @@ -104,7 +104,7 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { fn fs_main_without_storage(in: VertexOutput) -> @location(0) vec4 { let normal = normalize(in.world_normal); var color: vec3 = c_ambient; - for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i += 1u) { + for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i++) { // This line is the only difference from the entrypoint above. It uses the lights // uniform instead of the lights storage buffer let light = u_lights[i]; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 1ca8db55f..f8a24579b 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -85,6 +85,10 @@ void binary_assignment() { a = (_e21 ^ 0); int _e24 = a; a = (_e24 & 0); + int _e27 = a; + a = (_e27 + 1); + int _e30 = a; + a = (_e30 - 1); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 3204dd3b1..327269054 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -101,6 +101,10 @@ void binary_assignment() a = (_expr21 ^ 0); int _expr24 = a; a = (_expr24 & 0); + int _expr27 = a; + a = (_expr27 + 1); + int _expr30 = a; + a = (_expr30 - 1); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 09871e528..0170f43ea 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -98,6 +98,10 @@ void binary_assignment( a = _e21 ^ 0; int _e24 = a; a = _e24 & 0; + int _e27 = a; + a = _e27 + 1; + int _e30 = a; + a = _e30 - 1; return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index bd81edce3..22376a350 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 176 +; Bound: 180 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %164 "main" -OpExecutionMode %164 LocalSize 1 1 1 +OpEntryPoint GLCompute %168 "main" +OpExecutionMode %168 LocalSize 1 1 1 OpMemberDecorate %23 0 Offset 0 OpMemberDecorate %23 1 Offset 16 %2 = OpTypeVoid @@ -207,21 +207,27 @@ OpStore %142 %160 %161 = OpLoad %8 %142 %162 = OpBitwiseAnd %8 %161 %11 OpStore %142 %162 +%163 = OpLoad %8 %142 +%164 = OpIAdd %8 %163 %7 +OpStore %142 %164 +%165 = OpLoad %8 %142 +%166 = OpISub %8 %165 %7 +OpStore %142 %166 OpReturn OpFunctionEnd -%164 = OpFunction %2 None %117 -%163 = OpLabel -OpBranch %165 -%165 = OpLabel -%166 = OpFunctionCall %19 %32 -%167 = OpFunctionCall %19 %57 -%168 = OpFunctionCall %8 %73 -%169 = OpVectorShuffle %22 %27 %27 0 1 2 -%170 = OpFunctionCall %22 %84 %169 -%171 = OpFunctionCall %4 %96 -%172 = OpFunctionCall %2 %116 -%173 = OpFunctionCall %2 %129 -%174 = OpFunctionCall %2 %138 -%175 = OpFunctionCall %2 %145 +%168 = OpFunction %2 None %117 +%167 = OpLabel +OpBranch %169 +%169 = OpLabel +%170 = OpFunctionCall %19 %32 +%171 = OpFunctionCall %19 %57 +%172 = OpFunctionCall %8 %73 +%173 = OpVectorShuffle %22 %27 %27 0 1 2 +%174 = OpFunctionCall %22 %84 %173 +%175 = OpFunctionCall %4 %96 +%176 = OpFunctionCall %2 %116 +%177 = OpFunctionCall %2 %129 +%178 = OpFunctionCall %2 %138 +%179 = OpFunctionCall %2 %145 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index d8e1a4267..33e0ab198 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -84,6 +84,10 @@ fn binary_assignment() { a = (_e21 ^ 0); let _e24 = a; a = (_e24 & 0); + let _e27 = a; + a = (_e27 + 1); + let _e30 = a; + a = (_e30 - 1); return; } From 800fc7471f14ae2fb63d1948be92e5c01615a3ee Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 22 Mar 2022 16:37:06 +0100 Subject: [PATCH 1635/2212] fix msrv incompatibility --- src/front/wgsl/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7d30dfb36..f0b4b32c8 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3312,12 +3312,13 @@ impl Parser { .expressions .append(crate::Expression::Binary { op, left, right }, span.into()) } - (op @ Token::IncrementOperation | op @ Token::DecrementOperation, op_span) => { - let op = match op { + token @ (Token::IncrementOperation, _) | token @ (Token::DecrementOperation, _) => { + let op = match token.0 { Token::IncrementOperation => Bo::Add, Token::DecrementOperation => Bo::Subtract, _ => unreachable!(), }; + let op_span = token.1; // prepare the typifier, but work around mutable borrowing... let _ = context.resolve_type(reference.handle)?; From 767d970312d57e353169184f42f93ae06cf903e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 27 Mar 2022 21:44:28 +0100 Subject: [PATCH 1636/2212] glsl-in: Resume expression emit after imageStore This wasn't done before which caused the frontend to crash if anything appeared after it. --- src/front/glsl/builtins.rs | 1 + tests/in/glsl/images.frag | 2 +- tests/out/wgsl/images-frag.wgsl | 10 +++++----- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index dedaf93dc..6561af9d2 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1830,6 +1830,7 @@ impl MacroCall { }, meta, ); + ctx.emit_start(); return Ok(None); } MacroCall::MathFunction(fun) => ctx.add_expression( diff --git a/tests/in/glsl/images.frag b/tests/in/glsl/images.frag index f2aeea23d..b8d7622bc 100644 --- a/tests/in/glsl/images.frag +++ b/tests/in/glsl/images.frag @@ -14,8 +14,8 @@ layout(rgba8, binding = 9) writeonly readonly uniform image2D imgWriteReadOnly; void testImg1D(in int coord) { int size = imageSize(img1D); - vec4 c = imageLoad(img1D, coord); imageStore(img1D, coord, vec4(2)); + vec4 c = imageLoad(img1D, coord); } void testImg1DArray(in ivec2 coord) { diff --git a/tests/out/wgsl/images-frag.wgsl b/tests/out/wgsl/images-frag.wgsl index 4ced4cdbf..18e508255 100644 --- a/tests/out/wgsl/images-frag.wgsl +++ b/tests/out/wgsl/images-frag.wgsl @@ -23,11 +23,11 @@ fn testImg1D(coord: i32) { coord_1 = coord; let _e10 = textureDimensions(img1D); size = _e10; - let _e13 = coord_1; - let _e14 = textureLoad(img1D, _e13); - c = _e14; - let _e20 = coord_1; - textureStore(img1D, _e20, vec4(f32(2))); + let _e16 = coord_1; + textureStore(img1D, _e16, vec4(f32(2))); + let _e21 = coord_1; + let _e22 = textureLoad(img1D, _e21); + c = _e22; return; } From a48faf543f432a4392c40b9bf4c8a111e3ead312 Mon Sep 17 00:00:00 2001 From: Jonathan Behrens Date: Sun, 27 Mar 2022 15:27:50 -0400 Subject: [PATCH 1637/2212] Add glsl barrier function --- src/front/glsl/builtins.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 6561af9d2..8fa0ab9d5 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -995,6 +995,9 @@ fn inject_standard_builtins( .push(module.add_builtin(args, MacroCall::Clamp(size))) } } + "barrier" => declaration + .overloads + .push(module.add_builtin(Vec::new(), MacroCall::Barrier)), // Add common builtins with floats _ => inject_common_builtin(declaration, module, name, 4), } @@ -1587,6 +1590,7 @@ pub enum MacroCall { Clamp(Option), BitCast(Sk), Derivate(DerivativeAxis), + Barrier, } impl MacroCall { @@ -1993,6 +1997,11 @@ impl MacroCall { Span::default(), body, ), + MacroCall::Barrier => { + ctx.emit_flush(body); + body.push(crate::Statement::Barrier(crate::Barrier::all()), meta); + return Ok(None); + } })) } } From 26537c1a6042e906f278eda5eb40aa331dfa21fa Mon Sep 17 00:00:00 2001 From: Jonathan Behrens Date: Sun, 27 Mar 2022 17:40:39 -0400 Subject: [PATCH 1638/2212] Call ctx.emit_start after flushing --- src/front/glsl/builtins.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 8fa0ab9d5..f06980b9b 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1999,6 +1999,7 @@ impl MacroCall { ), MacroCall::Barrier => { ctx.emit_flush(body); + ctx.emit_start(); body.push(crate::Statement::Barrier(crate::Barrier::all()), meta); return Ok(None); } From 21f89b65e4e9012281232d2cb1f66b85bef75f0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 27 Mar 2022 22:11:30 +0100 Subject: [PATCH 1639/2212] glsl-in: use forced conversions for vector/matrix constructors The spec defines that for vector and matrix constructors all arguments should use the same conversions as scalar constructors (forced conversions) --- src/front/glsl/context.rs | 19 +++++++++++++++++++ src/front/glsl/functions.rs | 11 ++++------- tests/in/glsl/expressions.frag | 5 +++++ tests/out/wgsl/expressions-frag.wgsl | 11 ++++++++++- 4 files changed, 38 insertions(+), 8 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 781c9c767..5675775db 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -1279,6 +1279,25 @@ impl Context { Ok(()) } + pub fn forced_conversion( + &mut self, + parser: &Parser, + expr: &mut Handle, + meta: Span, + kind: ScalarKind, + width: crate::Bytes, + ) -> Result<()> { + if let Some((expr_scalar_kind, expr_width)) = + self.expr_scalar_components(parser, *expr, meta)? + { + if expr_scalar_kind != kind || expr_width != width { + self.conversion(expr, meta, kind, width)?; + } + } + + Ok(()) + } + pub fn binary_implicit_conversion( &mut self, parser: &Parser, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index a6dd97e99..5989a8bbd 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -113,7 +113,7 @@ impl Parser { Ok(match self.module.types[ty].inner { TypeInner::Vector { size, kind, width } if vector_size.is_none() => { - ctx.implicit_conversion(self, &mut value, meta, kind, width)?; + ctx.forced_conversion(self, &mut value, expr_meta, kind, width)?; if let TypeInner::Scalar { .. } = *self.resolve_type(ctx, value, expr_meta)? { ctx.add_expression(Expression::Splat { size, value }, meta, body) @@ -256,7 +256,7 @@ impl Parser { // `Expression::As` doesn't support matrix width // casts so we need to do some extra work for casts - ctx.implicit_conversion(self, &mut value, expr_meta, ScalarKind::Float, width)?; + ctx.forced_conversion(self, &mut value, expr_meta, ScalarKind::Float, width)?; match *self.resolve_type(ctx, value, expr_meta)? { TypeInner::Scalar { .. } => { // If a matrix is constructed with a single scalar value, then that @@ -446,7 +446,7 @@ impl Parser { let mut components = Vec::with_capacity(size as usize); for (mut arg, expr_meta) in args.iter().copied() { - ctx.implicit_conversion(self, &mut arg, expr_meta, kind, width)?; + ctx.forced_conversion(self, &mut arg, expr_meta, kind, width)?; if components.len() >= size as usize { break; @@ -512,10 +512,7 @@ impl Parser { let mut flattened = Vec::with_capacity(columns as usize * rows as usize); for (mut arg, meta) in args.iter().copied() { - let scalar_components = scalar_components(&self.module.types[ty].inner); - if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; - } + ctx.forced_conversion(self, &mut arg, meta, ScalarKind::Float, width)?; match *self.resolve_type(ctx, arg, meta)? { TypeInner::Vector { size, .. } => { diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 66a5c0f25..777b0b973 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -113,6 +113,11 @@ void testFreestandingConstructor() { vec4(1.0); } +void testNonImplicitCastVectorCast() { + uint a = 1; + ivec4 b = ivec4(a); +} + float global; void privatePointer(inout float a) {} diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 30d6b30fc..fee7c4c98 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -286,7 +286,16 @@ fn testFreestandingConstructor() { return; } -fn privatePointer(a_18: ptr) { +fn testNonImplicitCastVectorCast() { + var a_18: u32 = 1u; + var b_16: vec4; + + let _e3 = a_18; + b_16 = vec4(i32(_e3)); + return; +} + +fn privatePointer(a_19: ptr) { return; } From 4146cb24d0ea596ce983f176a37ffe18e1b6784a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 18 Mar 2022 22:10:35 +0000 Subject: [PATCH 1640/2212] glsl-in: Allow nested accesses in lhs positions Also fixes access to runtime sized arrays behind named blocks --- src/front/glsl/ast.rs | 2 + src/front/glsl/context.rs | 78 ++++++++++++++++++--------- src/front/glsl/variables.rs | 38 +++++++++---- tests/in/glsl/buffer.frag | 22 ++++++++ tests/out/wgsl/bevy-pbr-frag.wgsl | 26 ++++----- tests/out/wgsl/buffer-frag.wgsl | 37 +++++++++++++ tests/out/wgsl/declarations-vert.wgsl | 12 ++--- tests/out/wgsl/fma-frag.wgsl | 18 +++---- 8 files changed, 168 insertions(+), 65 deletions(-) create mode 100644 tests/in/glsl/buffer.frag create mode 100644 tests/out/wgsl/buffer-frag.wgsl diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 0d5041306..95faed6e7 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -97,7 +97,9 @@ pub struct EntryArg { #[derive(Debug, Clone)] pub struct VariableReference { pub expr: Handle, + /// Wether the variable is of a pointer type (and needs loading) or not pub load: bool, + /// Wether the value of the variable can be changed or not pub mutable: bool, pub constant: Option<(Handle, Handle)>, pub entry_arg: Option, diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 5675775db..eeee39386 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -16,7 +16,7 @@ use crate::{ use std::{convert::TryFrom, ops::Index}; /// The position at which an expression is, used while lowering -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum ExprPos { /// The expression is in the left hand side of an assignment Lhs, @@ -24,18 +24,18 @@ pub enum ExprPos { Rhs, /// The expression is an array being indexed, needed to allow constant /// arrays to be dinamically indexed - ArrayBase { + AccessBase { /// The index is a constant constant_index: bool, }, } impl ExprPos { - /// Returns an lhs position if the current position is lhs otherwise ArrayBase - fn maybe_array_base(&self, constant_index: bool) -> Self { + /// Returns an lhs position if the current position is lhs otherwise AccessBase + fn maybe_access_base(&self, constant_index: bool) -> Self { match *self { ExprPos::Lhs => *self, - _ => ExprPos::ArrayBase { constant_index }, + _ => ExprPos::AccessBase { constant_index }, } } } @@ -492,6 +492,8 @@ impl Context { ) -> Result<(Option>, Span)> { let HirExpr { ref kind, meta } = stmt.hir_exprs[expr]; + log::debug!("Lowering {:?}", expr); + let handle = match *kind { HirExprKind::Access { base, index } => { let (index, index_meta) = @@ -508,7 +510,7 @@ impl Context { stmt, parser, base, - pos.maybe_array_base(maybe_constant_index.is_some()), + pos.maybe_access_base(maybe_constant_index.is_some()), body, )? .0; @@ -551,18 +553,20 @@ impl Context { pointer } HirExprKind::Select { base, ref field } => { - let base = self.lower_expect_inner(stmt, parser, base, pos, body)?.0; + let base = self + .lower_expect_inner(stmt, parser, base, pos.maybe_access_base(true), body)? + .0; - parser.field_selection(self, ExprPos::Lhs == pos, body, base, field, meta)? + parser.field_selection(self, pos, body, base, field, meta)? } HirExprKind::Constant(constant) if pos != ExprPos::Lhs => { self.add_expression(Expression::Constant(constant), meta, body) } HirExprKind::Binary { left, op, right } if pos != ExprPos::Lhs => { let (mut left, left_meta) = - self.lower_expect_inner(stmt, parser, left, pos, body)?; + self.lower_expect_inner(stmt, parser, left, ExprPos::Rhs, body)?; let (mut right, right_meta) = - self.lower_expect_inner(stmt, parser, right, pos, body)?; + self.lower_expect_inner(stmt, parser, right, ExprPos::Rhs, body)?; match op { BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self @@ -1003,7 +1007,9 @@ impl Context { } } HirExprKind::Unary { op, expr } if pos != ExprPos::Lhs => { - let expr = self.lower_expect_inner(stmt, parser, expr, pos, body)?.0; + let expr = self + .lower_expect_inner(stmt, parser, expr, ExprPos::Rhs, body)? + .0; self.add_expression(Expression::Unary { op, expr }, meta, body) } @@ -1020,20 +1026,29 @@ impl Context { var.expr } - ExprPos::ArrayBase { - constant_index: false, - } => { - if let Some((constant, ty)) = var.constant { - let local = self.locals.append( - LocalVariable { - name: None, - ty, - init: Some(constant), - }, - Span::default(), - ); + ExprPos::AccessBase { constant_index } => { + // If the index isn't constant all accesses backed by a constant base need + // to be done trough a proxy local variable, since constants have a non + // pointer type which is required for dynamic indexing + if !constant_index { + if let Some((constant, ty)) = var.constant { + let local = self.locals.append( + LocalVariable { + name: None, + ty, + init: Some(constant), + }, + Span::default(), + ); - self.add_expression(Expression::LocalVariable(local), Span::default(), body) + self.add_expression( + Expression::LocalVariable(local), + Span::default(), + body, + ) + } else { + var.expr + } } else { var.expr } @@ -1091,9 +1106,12 @@ impl Context { let (mut value, value_meta) = self.lower_expect_inner(stmt, parser, value, ExprPos::Rhs, body)?; - let scalar_components = self.expr_scalar_components(parser, pointer, ptr_meta)?; + let ty = match *parser.resolve_type(self, pointer, ptr_meta)? { + TypeInner::Pointer { base, .. } => &parser.module.types[base].inner, + ref ty => ty, + }; - if let Some((kind, width)) = scalar_components { + if let Some((kind, width)) = scalar_components(ty) { self.implicit_conversion(parser, &mut value, value_meta, kind, width)?; } @@ -1216,6 +1234,14 @@ impl Context { } }; + log::trace!( + "Lowered {:?}\n\tKind = {:?}\n\tPos = {:?}\n\tResult = {:?}", + expr, + kind, + pos, + handle + ); + Ok((Some(handle), meta)) } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index fb5f3b362..4b69abc05 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -1,6 +1,6 @@ use super::{ ast::*, - context::Context, + context::{Context, ExprPos}, error::{Error, ErrorKind}, Parser, Result, Span, }; @@ -231,7 +231,7 @@ impl Parser { pub(crate) fn field_selection( &mut self, ctx: &mut Context, - lhs: bool, + pos: ExprPos, body: &mut Block, expression: Handle, name: &str, @@ -250,14 +250,21 @@ impl Parser { kind: ErrorKind::UnknownField(name.into()), meta, })?; - Ok(ctx.add_expression( + let pointer = ctx.add_expression( Expression::AccessIndex { base: expression, index: index as u32, }, meta, body, - )) + ); + + Ok(match pos { + ExprPos::Rhs if is_pointer => { + ctx.add_expression(Expression::Load { pointer }, meta, body) + } + _ => pointer, + }) } // swizzles (xyzw, rgba, stpq) TypeInner::Vector { size, .. } => { @@ -277,7 +284,7 @@ impl Parser { .or_else(|| check_swizzle_components("stpq")); if let Some(components) = components { - if lhs { + if let ExprPos::Lhs = pos { let not_unique = (1..components.len()) .any(|i| components[i..].contains(&components[i - 1])); if not_unique { @@ -315,14 +322,23 @@ impl Parser { } let size = match components.len() { + // Swizzles with just one component are accesses and not swizzles 1 => { - // only single element swizzle, like pos.y, just return that component. - if lhs { - // Because of possible nested swizzles, like pos.xy.x, we have to unwrap the potential load expr. - if let Expression::Load { ref pointer } = ctx[expression] { - expression = *pointer; + match pos { + // If the position is in the right hand side and the base + // vector is a pointer, load it, otherwise the swizzle would + // produce a pointer + ExprPos::Rhs if is_pointer => { + expression = ctx.add_expression( + Expression::Load { + pointer: expression, + }, + meta, + body, + ); } - } + _ => {} + }; return Ok(ctx.add_expression( Expression::AccessIndex { base: expression, diff --git a/tests/in/glsl/buffer.frag b/tests/in/glsl/buffer.frag new file mode 100644 index 000000000..dc50aae2e --- /dev/null +++ b/tests/in/glsl/buffer.frag @@ -0,0 +1,22 @@ +#version 450 + +layout(set = 0, binding = 0) buffer testBufferBlock { + uint[] data; +} testBuffer; + +layout(set = 0, binding = 1) writeonly buffer testBufferWriteOnlyBlock { + uint[] data; +} testBufferWriteOnly; + +layout(set = 0, binding = 2) readonly buffer testBufferReadOnlyBlock { + uint[] data; +} testBufferReadOnly; + +void main() { + uint a = testBuffer.data[0]; + testBuffer.data[1] = 2; + + testBufferWriteOnly.data[1] = 2; + + uint b = testBufferReadOnly.data[0]; +} diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 5d0445075..a1f49dd16 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -498,21 +498,21 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ R_1 = R; F0_1 = F0_; diffuseColor_1 = diffuseColor; - let _e56 = light_1; + let _e57 = light_1.pos; let _e59 = v_WorldPosition_1; - light_to_frag = (_e56.pos.xyz - _e59.xyz); + light_to_frag = (_e57.xyz - _e59.xyz); let _e65 = light_to_frag; let _e66 = light_to_frag; distance_square = dot(_e65, _e66); - let _e70 = light_1; + let _e71 = light_1.lightParams; let _e73 = distance_square; - let _e74 = light_1; - let _e77 = getDistanceAttenuation(_e73, _e74.lightParams.x); + let _e75 = light_1.lightParams; + let _e77 = getDistanceAttenuation(_e73, _e75.x); rangeAttenuation = _e77; let _e79 = roughness_9; a_1 = _e79; - let _e81 = light_1; - radius = _e81.lightParams.y; + let _e82 = light_1.lightParams; + radius = _e82.y; let _e87 = light_to_frag; let _e88 = R_1; let _e90 = R_1; @@ -611,10 +611,10 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ diffuse = (_e302 * _e311); let _e314 = diffuse; let _e315 = specular_1; - let _e317 = light_1; + let _e318 = light_1.color; let _e321 = rangeAttenuation; let _e322 = NoL_6; - return (((_e314 + _e315) * _e317.color.xyz) * (_e321 * _e322)); + return (((_e314 + _e315) * _e318.xyz) * (_e321 * _e322)); } fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: vec3, view: vec3, R_2: vec3, F0_2: vec3, diffuseColor_2: vec3) -> vec3 { @@ -643,8 +643,8 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: R_3 = R_2; F0_3 = F0_2; diffuseColor_3 = diffuseColor_2; - let _e56 = light_3; - incident_light = _e56.direction.xyz; + let _e57 = light_3.direction; + incident_light = _e57.xyz; let _e60 = incident_light; let _e61 = view_1; let _e63 = incident_light; @@ -684,9 +684,9 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: specular_2 = _e146; let _e148 = specular_2; let _e149 = diffuse_1; - let _e151 = light_3; + let _e152 = light_3.color; let _e155 = NoL_7; - return (((_e148 + _e149) * _e151.color.xyz) * _e155); + return (((_e148 + _e149) * _e152.xyz) * _e155); } fn main_1() { diff --git a/tests/out/wgsl/buffer-frag.wgsl b/tests/out/wgsl/buffer-frag.wgsl new file mode 100644 index 000000000..455fbb7af --- /dev/null +++ b/tests/out/wgsl/buffer-frag.wgsl @@ -0,0 +1,37 @@ +struct testBufferBlock { + data: array, +} + +struct testBufferWriteOnlyBlock { + data: array, +} + +struct testBufferReadOnlyBlock { + data: array, +} + +@group(0) @binding(0) +var testBuffer: testBufferBlock; +@group(0) @binding(1) +var testBufferWriteOnly: testBufferWriteOnlyBlock; +@group(0) @binding(2) +var testBufferReadOnly: testBufferReadOnlyBlock; + +fn main_1() { + var a: u32; + var b: u32; + + let _e12 = testBuffer.data[0]; + a = _e12; + testBuffer.data[1] = u32(2); + testBufferWriteOnly.data[1] = u32(2); + let _e27 = testBufferReadOnly.data[0]; + b = _e27; + return; +} + +@stage(fragment) +fn main() { + main_1(); + return; +} diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index cfd2528f3..0c5feecb6 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -34,12 +34,12 @@ fn main_1() { var a_1: f32; var b: f32; - let _e34 = in_array_2; - from_input_array = _e34[1]; - let _e39 = array_2d; - a_1 = _e39[0][0]; - let _e50 = array_toomanyd; - b = _e50[0][0][0][0][0][0][0]; + let _e35 = in_array_2[1]; + from_input_array = _e35; + let _e41 = array_2d[0][0]; + a_1 = _e41; + let _e57 = array_toomanyd[0][0][0][0][0][0][0]; + b = _e57; out_array[0] = vec4(2.0); return; } diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 3c2233abf..2019e48ad 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -16,18 +16,18 @@ fn Fma(d: ptr, m: Mat4x3_, s: f32) { m_1 = m; s_1 = s; - let _e6 = (*d); - let _e8 = m_1; + let _e7 = (*d).mx; + let _e9 = m_1.mx; let _e10 = s_1; - (*d).mx = (_e6.mx + (_e8.mx * _e10)); - let _e14 = (*d); - let _e16 = m_1; + (*d).mx = (_e7 + (_e9 * _e10)); + let _e15 = (*d).my; + let _e17 = m_1.my; let _e18 = s_1; - (*d).my = (_e14.my + (_e16.my * _e18)); - let _e22 = (*d); - let _e24 = m_1; + (*d).my = (_e15 + (_e17 * _e18)); + let _e23 = (*d).mz; + let _e25 = m_1.mz; let _e26 = s_1; - (*d).mz = (_e22.mz + (_e24.mz * _e26)); + (*d).mz = (_e23 + (_e25 * _e26)); return; } From 012f2a6b2e9328e93939429705fdf9102d9f69b7 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 28 Mar 2022 07:24:09 +0200 Subject: [PATCH 1641/2212] Merge pull request #1784 from teoxoy/patch-2 [hlsl-out] fix matrix not being declared as transposed --- src/back/hlsl/mod.rs | 3 +- src/back/hlsl/storage.rs | 33 ++- src/back/hlsl/writer.rs | 2 +- tests/in/access.wgsl | 6 +- tests/out/glsl/access.atomics.Compute.glsl | 2 +- tests/out/glsl/access.foo_frag.Fragment.glsl | 4 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 6 +- tests/out/hlsl/access.hlsl | 14 +- tests/out/msl/access.msl | 8 +- tests/out/spv/access.spvasm | 284 ++++++++++--------- tests/out/wgsl/access.wgsl | 6 +- 11 files changed, 188 insertions(+), 180 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 6f6339d43..8f3134bb1 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -16,7 +16,8 @@ becomes `vec * mat`, etc. This acts as the inverse transpose making the results The only time we don't get this implicit transposition is when reading matrices from Uniforms/Push Constants. To deal with this, we add `row_major` to all declarations of matrices in Uniforms/Push Constants. -Finally because all of our matrices are transposed, if you use `mat3x4`, it'll become `float4x3` in HLSL. +Finally because all of our matrices are transposed, if you use `mat3x4`, it'll become `float3x4` in HLSL +(HLSL has inverted col/row notation). [hlsl]: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl */ diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 4abe66350..cab351aa5 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -122,19 +122,19 @@ impl super::Writer<'_, W> { self.out, "{}{}x{}(", crate::ScalarKind::Float.to_hlsl_str(width)?, - rows as u8, columns as u8, + rows as u8, )?; // Note: Matrices containing vec3s, due to padding, act like they contain vec4s. - let padded_columns = match columns { + let padded_rows = match rows { crate::VectorSize::Tri => 4, - columns => columns as u32, + rows => rows as u32, }; - let row_stride = width as u32 * padded_columns; - let iter = (0..rows as u32).map(|i| { + let row_stride = width as u32 * padded_rows; + let iter = (0..columns as u32).map(|i| { let ty_inner = crate::TypeInner::Vector { - size: columns, + size: rows, kind: crate::ScalarKind::Float, width, }; @@ -261,8 +261,8 @@ impl super::Writer<'_, W> { "{}{}{}x{} {}{} = ", level.next(), crate::ScalarKind::Float.to_hlsl_str(width)?, - rows as u8, columns as u8, + rows as u8, STORE_TEMP_NAME, depth, )?; @@ -270,18 +270,18 @@ impl super::Writer<'_, W> { writeln!(self.out, ";")?; // Note: Matrices containing vec3s, due to padding, act like they contain vec4s. - let padded_columns = match columns { + let padded_rows = match rows { crate::VectorSize::Tri => 4, - columns => columns as u32, + rows => rows as u32, }; - let row_stride = width as u32 * padded_columns; + let row_stride = width as u32 * padded_rows; // then iterate the stores - for i in 0..rows as u32 { + for i in 0..columns as u32 { self.temp_access_chain .push(SubAccess::Offset(i * row_stride)); let ty_inner = crate::TypeInner::Vector { - size: columns, + size: rows, kind: crate::ScalarKind::Float, width, }; @@ -401,8 +401,13 @@ impl super::Writer<'_, W> { crate::TypeInner::Vector { width, .. } => Parent::Array { stride: width as u32, }, - crate::TypeInner::Matrix { rows, width, .. } => Parent::Array { - stride: width as u32 * if rows > crate::VectorSize::Bi { 4 } else { 2 }, + crate::TypeInner::Matrix { columns, width, .. } => Parent::Array { + stride: width as u32 + * if columns > crate::VectorSize::Bi { + 4 + } else { + 2 + }, }, _ => unreachable!(), }, diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index e082927e7..66a1fc57a 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -838,8 +838,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.out, "{}{}x{}", crate::ScalarKind::Float.to_hlsl_str(width)?, - back::vector_size_str(rows), back::vector_size_str(columns), + back::vector_size_str(rows), )?; } TypeInner::Image { diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 7c96367ac..5ba29d90d 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -5,7 +5,7 @@ struct AlignedWrapper { } struct Bar { - matrix: mat4x4, + matrix: mat4x3, matrix_array: array, 2>, atom: atomic, arr: array, 2>, @@ -42,14 +42,14 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { c[vi + 1u] = 42; let value = c[vi]; - return matrix * vec4(vec4(value)); + return vec4(matrix * vec4(vec4(value)), 2.0); } @stage(fragment) fn foo_frag() -> @location(0) vec4 { // test storage stores bar.matrix[1].z = 1.0; - bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + bar.matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); bar.arr = array, 2>(vec2(0u), vec2(1u)); bar.data[1].value = 1; diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index d1fddc7e1..5edd19fea 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -9,7 +9,7 @@ struct AlignedWrapper { int value; }; layout(std430) buffer Bar_block_0Compute { - mat4x4 matrix; + mat4x3 matrix; mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index ab14704b0..63b40b7ab 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -7,7 +7,7 @@ struct AlignedWrapper { int value; }; layout(std430) buffer Bar_block_0Fragment { - mat4x4 matrix; + mat4x3 matrix; mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; @@ -23,7 +23,7 @@ float read_from_private(inout float foo_1) { void main() { _group_0_binding_0_fs.matrix[1][2] = 1.0; - _group_0_binding_0_fs.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + _group_0_binding_0_fs.matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); _group_0_binding_0_fs.arr = uvec2[2](uvec2(0u), uvec2(1u)); _group_0_binding_0_fs.data[1].value = 1; _fs2p_location0 = vec4(0.0); diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index 05fd49321..f1fb3e09a 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -7,7 +7,7 @@ struct AlignedWrapper { int value; }; layout(std430) buffer Bar_block_0Vertex { - mat4x4 matrix; + mat4x3 matrix; mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; @@ -26,7 +26,7 @@ void main() { int c[5] = int[5](0, 0, 0, 0, 0); float baz = foo; foo = 1.0; - mat4x4 matrix = _group_0_binding_0_vs.matrix; + mat4x3 matrix = _group_0_binding_0_vs.matrix; uvec2 arr[2] = _group_0_binding_0_vs.arr; float b = _group_0_binding_0_vs.matrix[3][0]; int a = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; @@ -34,7 +34,7 @@ void main() { c = int[5](a, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; - gl_Position = (matrix * vec4(ivec4(value))); + gl_Position = vec4((matrix * vec4(ivec4(value))), 2.0); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; } diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 91ffd5293..8af92afdd 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -25,7 +25,7 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position float baz = foo; foo = 1.0; - float4x4 matrix_ = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))); + float4x3 matrix_ = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); int a = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); @@ -36,18 +36,18 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position } c[(vi + 1u)] = 42; int value = c[vi]; - return mul(float4(int4(value.xxxx)), matrix_); + return float4(mul(float4(int4(value.xxxx)), matrix_), 2.0); } float4 foo_frag() : SV_Target0 { bar.Store(8+16+0, asuint(1.0)); { - float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx)); - bar.Store4(0+0, asuint(_value2[0])); - bar.Store4(0+16, asuint(_value2[1])); - bar.Store4(0+32, asuint(_value2[2])); - bar.Store4(0+48, asuint(_value2[3])); + float4x3 _value2 = float4x3(float3(0.0.xxx), float3(1.0.xxx), float3(2.0.xxx), float3(3.0.xxx)); + bar.Store3(0+0, asuint(_value2[0])); + bar.Store3(0+16, asuint(_value2[1])); + bar.Store3(0+32, asuint(_value2[2])); + bar.Store3(0+48, asuint(_value2[3])); } { uint2 _value2[2] = { uint2(0u.xx), uint2(1u.xx) }; diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 0a1c0cfb2..dbdad72e1 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -19,7 +19,7 @@ struct type_6 { }; typedef AlignedWrapper type_7[1]; struct Bar { - metal::float4x4 matrix; + metal::float4x3 matrix; type_3 matrix_array; metal::atomic_int atom; char _pad3[4]; @@ -51,7 +51,7 @@ vertex foo_vertOutput foo_vert( type_13 c; float baz = foo; foo = 1.0; - metal::float4x4 matrix = bar.matrix; + metal::float4x3 matrix = bar.matrix; type_6 arr = bar.arr; float b = bar.matrix[3].x; int a = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; @@ -59,7 +59,7 @@ vertex foo_vertOutput foo_vert( for(int _i=0; _i<5; ++_i) c.inner[_i] = type_13 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; - return foo_vertOutput { matrix * static_cast(metal::int4(value)) }; + return foo_vertOutput { metal::float4(matrix * static_cast(metal::int4(value)), 2.0) }; } @@ -71,7 +71,7 @@ fragment foo_fragOutput foo_frag( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { bar.matrix[1].z = 1.0; - bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0)); + bar.matrix = metal::float4x3(metal::float3(0.0), metal::float3(1.0), metal::float3(2.0), metal::float3(3.0)); for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_6 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; bar.data[1].value = 1; return foo_fragOutput { metal::float4(0.0) }; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 21e4f513e..a78c50237 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 126 +; Bound: 128 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %51 "foo_vert" %46 %49 -OpEntryPoint Fragment %86 "foo_frag" %85 -OpEntryPoint GLCompute %103 "atomics" -OpExecutionMode %86 OriginUpperLeft -OpExecutionMode %103 LocalSize 1 1 1 +OpEntryPoint Vertex %52 "foo_vert" %47 %50 +OpEntryPoint Fragment %88 "foo_frag" %87 +OpEntryPoint GLCompute %105 "atomics" +OpExecutionMode %88 OriginUpperLeft +OpExecutionMode %105 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %21 0 "value" OpName %21 "AlignedWrapper" @@ -20,16 +20,16 @@ OpMemberName %30 2 "atom" OpMemberName %30 3 "arr" OpMemberName %30 4 "data" OpName %30 "Bar" -OpName %34 "bar" -OpName %37 "foo" -OpName %38 "read_from_private" -OpName %42 "foo" -OpName %43 "c" -OpName %46 "vi" -OpName %51 "foo_vert" -OpName %86 "foo_frag" -OpName %101 "tmp" -OpName %103 "atomics" +OpName %35 "bar" +OpName %38 "foo" +OpName %39 "read_from_private" +OpName %43 "foo" +OpName %44 "c" +OpName %47 "vi" +OpName %52 "foo_vert" +OpName %88 "foo_frag" +OpName %103 "tmp" +OpName %105 "atomics" OpMemberDecorate %21 0 Offset 0 OpDecorate %26 ArrayStride 16 OpDecorate %28 ArrayStride 8 @@ -43,13 +43,13 @@ OpMemberDecorate %30 1 MatrixStride 8 OpMemberDecorate %30 2 Offset 96 OpMemberDecorate %30 3 Offset 104 OpMemberDecorate %30 4 Offset 120 -OpDecorate %33 ArrayStride 4 -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 0 +OpDecorate %34 ArrayStride 4 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 0 OpDecorate %30 Block -OpDecorate %46 BuiltIn VertexIndex -OpDecorate %49 BuiltIn Position -OpDecorate %85 Location 0 +OpDecorate %47 BuiltIn VertexIndex +OpDecorate %50 BuiltIn Position +OpDecorate %87 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -65,12 +65,12 @@ OpDecorate %85 Location 0 %14 = OpConstant %4 4 %15 = OpConstant %9 1 %16 = OpConstant %4 42 -%17 = OpConstant %4 1 -%18 = OpConstant %6 2.0 +%17 = OpConstant %6 2.0 +%18 = OpConstant %4 1 %19 = OpConstant %6 3.0 %20 = OpConstant %9 0 %21 = OpTypeStruct %4 -%23 = OpTypeVector %6 4 +%23 = OpTypeVector %6 3 %22 = OpTypeMatrix %23 4 %25 = OpTypeVector %6 2 %24 = OpTypeMatrix %25 2 @@ -80,127 +80,129 @@ OpDecorate %85 Location 0 %29 = OpTypeRuntimeArray %21 %30 = OpTypeStruct %22 %26 %4 %28 %29 %31 = OpTypePointer Function %6 -%32 = OpTypePointer StorageBuffer %4 -%33 = OpTypeArray %4 %12 -%35 = OpTypePointer StorageBuffer %30 -%34 = OpVariable %35 StorageBuffer -%39 = OpTypeFunction %6 %31 -%44 = OpTypePointer Function %33 -%47 = OpTypePointer Input %9 -%46 = OpVariable %47 Input -%50 = OpTypePointer Output %23 -%49 = OpVariable %50 Output -%52 = OpTypeFunction %2 -%55 = OpTypePointer StorageBuffer %22 -%58 = OpTypePointer StorageBuffer %28 -%61 = OpTypePointer StorageBuffer %23 -%62 = OpTypePointer StorageBuffer %6 -%65 = OpTypePointer StorageBuffer %29 -%68 = OpTypePointer StorageBuffer %21 -%69 = OpConstant %9 4 -%76 = OpTypePointer Function %4 -%80 = OpTypeVector %4 4 -%85 = OpVariable %50 Output -%105 = OpTypePointer StorageBuffer %4 -%108 = OpConstant %9 64 -%38 = OpFunction %6 None %39 -%37 = OpFunctionParameter %31 -%36 = OpLabel -OpBranch %40 -%40 = OpLabel -%41 = OpLoad %6 %37 -OpReturnValue %41 +%32 = OpTypeVector %6 4 +%33 = OpTypePointer StorageBuffer %4 +%34 = OpTypeArray %4 %12 +%36 = OpTypePointer StorageBuffer %30 +%35 = OpVariable %36 StorageBuffer +%40 = OpTypeFunction %6 %31 +%45 = OpTypePointer Function %34 +%48 = OpTypePointer Input %9 +%47 = OpVariable %48 Input +%51 = OpTypePointer Output %32 +%50 = OpVariable %51 Output +%53 = OpTypeFunction %2 +%56 = OpTypePointer StorageBuffer %22 +%59 = OpTypePointer StorageBuffer %28 +%62 = OpTypePointer StorageBuffer %23 +%63 = OpTypePointer StorageBuffer %6 +%66 = OpTypePointer StorageBuffer %29 +%69 = OpTypePointer StorageBuffer %21 +%70 = OpConstant %9 4 +%77 = OpTypePointer Function %4 +%81 = OpTypeVector %4 4 +%87 = OpVariable %51 Output +%107 = OpTypePointer StorageBuffer %4 +%110 = OpConstant %9 64 +%39 = OpFunction %6 None %40 +%38 = OpFunctionParameter %31 +%37 = OpLabel +OpBranch %41 +%41 = OpLabel +%42 = OpLoad %6 %38 +OpReturnValue %42 OpFunctionEnd -%51 = OpFunction %2 None %52 -%45 = OpLabel -%42 = OpVariable %31 Function %5 -%43 = OpVariable %44 Function -%48 = OpLoad %9 %46 -OpBranch %53 -%53 = OpLabel -%54 = OpLoad %6 %42 -OpStore %42 %7 -%56 = OpAccessChain %55 %34 %20 -%57 = OpLoad %22 %56 -%59 = OpAccessChain %58 %34 %8 -%60 = OpLoad %28 %59 -%63 = OpAccessChain %62 %34 %20 %8 %20 -%64 = OpLoad %6 %63 -%66 = OpArrayLength %9 %34 4 -%67 = OpISub %9 %66 %10 -%70 = OpAccessChain %32 %34 %69 %67 %20 -%71 = OpLoad %4 %70 -%72 = OpFunctionCall %6 %38 %42 -%73 = OpConvertFToS %4 %64 -%74 = OpCompositeConstruct %33 %71 %73 %13 %14 %12 -OpStore %43 %74 -%75 = OpIAdd %9 %48 %15 -%77 = OpAccessChain %76 %43 %75 -OpStore %77 %16 -%78 = OpAccessChain %76 %43 %48 -%79 = OpLoad %4 %78 -%81 = OpCompositeConstruct %80 %79 %79 %79 %79 -%82 = OpConvertSToF %23 %81 -%83 = OpMatrixTimesVector %23 %57 %82 -OpStore %49 %83 +%52 = OpFunction %2 None %53 +%46 = OpLabel +%43 = OpVariable %31 Function %5 +%44 = OpVariable %45 Function +%49 = OpLoad %9 %47 +OpBranch %54 +%54 = OpLabel +%55 = OpLoad %6 %43 +OpStore %43 %7 +%57 = OpAccessChain %56 %35 %20 +%58 = OpLoad %22 %57 +%60 = OpAccessChain %59 %35 %8 +%61 = OpLoad %28 %60 +%64 = OpAccessChain %63 %35 %20 %8 %20 +%65 = OpLoad %6 %64 +%67 = OpArrayLength %9 %35 4 +%68 = OpISub %9 %67 %10 +%71 = OpAccessChain %33 %35 %70 %68 %20 +%72 = OpLoad %4 %71 +%73 = OpFunctionCall %6 %39 %43 +%74 = OpConvertFToS %4 %65 +%75 = OpCompositeConstruct %34 %72 %74 %13 %14 %12 +OpStore %44 %75 +%76 = OpIAdd %9 %49 %15 +%78 = OpAccessChain %77 %44 %76 +OpStore %78 %16 +%79 = OpAccessChain %77 %44 %49 +%80 = OpLoad %4 %79 +%82 = OpCompositeConstruct %81 %80 %80 %80 %80 +%83 = OpConvertSToF %32 %82 +%84 = OpMatrixTimesVector %23 %58 %83 +%85 = OpCompositeConstruct %32 %84 %17 +OpStore %50 %85 OpReturn OpFunctionEnd -%86 = OpFunction %2 None %52 -%84 = OpLabel -OpBranch %87 -%87 = OpLabel -%88 = OpAccessChain %62 %34 %20 %15 %10 -OpStore %88 %7 -%89 = OpCompositeConstruct %23 %5 %5 %5 %5 -%90 = OpCompositeConstruct %23 %7 %7 %7 %7 -%91 = OpCompositeConstruct %23 %18 %18 %18 %18 -%92 = OpCompositeConstruct %23 %19 %19 %19 %19 -%93 = OpCompositeConstruct %22 %89 %90 %91 %92 -%94 = OpAccessChain %55 %34 %20 -OpStore %94 %93 -%95 = OpCompositeConstruct %27 %20 %20 -%96 = OpCompositeConstruct %27 %15 %15 -%97 = OpCompositeConstruct %28 %95 %96 -%98 = OpAccessChain %58 %34 %8 -OpStore %98 %97 -%99 = OpAccessChain %32 %34 %69 %15 %20 -OpStore %99 %17 -%100 = OpCompositeConstruct %23 %5 %5 %5 %5 -OpStore %85 %100 +%88 = OpFunction %2 None %53 +%86 = OpLabel +OpBranch %89 +%89 = OpLabel +%90 = OpAccessChain %63 %35 %20 %15 %10 +OpStore %90 %7 +%91 = OpCompositeConstruct %23 %5 %5 %5 +%92 = OpCompositeConstruct %23 %7 %7 %7 +%93 = OpCompositeConstruct %23 %17 %17 %17 +%94 = OpCompositeConstruct %23 %19 %19 %19 +%95 = OpCompositeConstruct %22 %91 %92 %93 %94 +%96 = OpAccessChain %56 %35 %20 +OpStore %96 %95 +%97 = OpCompositeConstruct %27 %20 %20 +%98 = OpCompositeConstruct %27 %15 %15 +%99 = OpCompositeConstruct %28 %97 %98 +%100 = OpAccessChain %59 %35 %8 +OpStore %100 %99 +%101 = OpAccessChain %33 %35 %70 %15 %20 +OpStore %101 %18 +%102 = OpCompositeConstruct %32 %5 %5 %5 %5 +OpStore %87 %102 OpReturn OpFunctionEnd -%103 = OpFunction %2 None %52 -%102 = OpLabel -%101 = OpVariable %76 Function -OpBranch %104 +%105 = OpFunction %2 None %53 %104 = OpLabel -%106 = OpAccessChain %105 %34 %10 -%107 = OpAtomicLoad %4 %106 %17 %108 -%110 = OpAccessChain %105 %34 %10 -%109 = OpAtomicIAdd %4 %110 %17 %108 %12 -OpStore %101 %109 -%112 = OpAccessChain %105 %34 %10 -%111 = OpAtomicISub %4 %112 %17 %108 %12 -OpStore %101 %111 -%114 = OpAccessChain %105 %34 %10 -%113 = OpAtomicAnd %4 %114 %17 %108 %12 -OpStore %101 %113 -%116 = OpAccessChain %105 %34 %10 -%115 = OpAtomicOr %4 %116 %17 %108 %12 -OpStore %101 %115 -%118 = OpAccessChain %105 %34 %10 -%117 = OpAtomicXor %4 %118 %17 %108 %12 -OpStore %101 %117 -%120 = OpAccessChain %105 %34 %10 -%119 = OpAtomicSMin %4 %120 %17 %108 %12 -OpStore %101 %119 -%122 = OpAccessChain %105 %34 %10 -%121 = OpAtomicSMax %4 %122 %17 %108 %12 -OpStore %101 %121 -%124 = OpAccessChain %105 %34 %10 -%123 = OpAtomicExchange %4 %124 %17 %108 %12 -OpStore %101 %123 -%125 = OpAccessChain %105 %34 %10 -OpAtomicStore %125 %17 %108 %107 +%103 = OpVariable %77 Function +OpBranch %106 +%106 = OpLabel +%108 = OpAccessChain %107 %35 %10 +%109 = OpAtomicLoad %4 %108 %18 %110 +%112 = OpAccessChain %107 %35 %10 +%111 = OpAtomicIAdd %4 %112 %18 %110 %12 +OpStore %103 %111 +%114 = OpAccessChain %107 %35 %10 +%113 = OpAtomicISub %4 %114 %18 %110 %12 +OpStore %103 %113 +%116 = OpAccessChain %107 %35 %10 +%115 = OpAtomicAnd %4 %116 %18 %110 %12 +OpStore %103 %115 +%118 = OpAccessChain %107 %35 %10 +%117 = OpAtomicOr %4 %118 %18 %110 %12 +OpStore %103 %117 +%120 = OpAccessChain %107 %35 %10 +%119 = OpAtomicXor %4 %120 %18 %110 %12 +OpStore %103 %119 +%122 = OpAccessChain %107 %35 %10 +%121 = OpAtomicSMin %4 %122 %18 %110 %12 +OpStore %103 %121 +%124 = OpAccessChain %107 %35 %10 +%123 = OpAtomicSMax %4 %124 %18 %110 %12 +OpStore %103 %123 +%126 = OpAccessChain %107 %35 %10 +%125 = OpAtomicExchange %4 %126 %18 %110 %12 +OpStore %103 %125 +%127 = OpAccessChain %107 %35 %10 +OpAtomicStore %127 %18 %110 %109 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 1e07fc933..38f0c4512 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -3,7 +3,7 @@ struct AlignedWrapper { } struct Bar { - matrix: mat4x4, + matrix: mat4x3, matrix_array: array,2>, atom: atomic, arr: array,2>, @@ -34,13 +34,13 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { c = array(a, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value = c[vi]; - return (matrix * vec4(vec4(value))); + return vec4((matrix * vec4(vec4(value))), 2.0); } @stage(fragment) fn foo_frag() -> @location(0) vec4 { bar.matrix[1][2] = 1.0; - bar.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0)); + bar.matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); bar.data[1].value = 1; return vec4(0.0); From cfcf625019188f88431d7abc44d5505eead8f4b5 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 30 Mar 2022 07:51:54 +0200 Subject: [PATCH 1642/2212] [wgsl-in] Constructor improvements (#1790) * add support for zero value constructors and constructors that infer their type from their parameters * address comments * extract constructor machinery into new module * fix doc link --- src/front/wgsl/construction.rs | 649 +++++++++++++++++++++ src/front/wgsl/mod.rs | 277 ++++----- tests/in/operators.wgsl | 15 + tests/out/glsl/operators.main.Compute.glsl | 18 +- tests/out/hlsl/operators.hlsl | 21 +- tests/out/msl/operators.msl | 30 +- tests/out/spv/operators.spvasm | 427 ++++++++------ tests/out/wgsl/operators.wgsl | 18 +- tests/wgsl-errors.rs | 76 ++- 9 files changed, 1174 insertions(+), 357 deletions(-) create mode 100644 src/front/wgsl/construction.rs diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/construction.rs new file mode 100644 index 000000000..7916caa62 --- /dev/null +++ b/src/front/wgsl/construction.rs @@ -0,0 +1,649 @@ +use crate::{ + proc::TypeResolution, Arena, ArraySize, Bytes, Constant, ConstantInner, Expression, Handle, + ScalarKind, ScalarValue, Span as NagaSpan, Type, TypeInner, UniqueArena, VectorSize, +}; + +use super::{Error, ExpressionContext, Lexer, Parser, Scope, Span, Token}; + +/// Represents the type of the constructor +/// +/// Vectors, Matrices and Arrays can have partial type information +/// which later gets inferred from the constructor parameters +enum ConstructorType { + Scalar { + kind: ScalarKind, + width: Bytes, + }, + PartialVector { + size: VectorSize, + }, + Vector { + size: VectorSize, + kind: ScalarKind, + width: Bytes, + }, + PartialMatrix { + columns: VectorSize, + rows: VectorSize, + }, + Matrix { + columns: VectorSize, + rows: VectorSize, + width: Bytes, + }, + PartialArray, + Array { + base: Handle, + size: ArraySize, + stride: u32, + }, + Struct(Handle), +} + +impl ConstructorType { + fn to_type_resolution(&self) -> Option { + Some(match *self { + ConstructorType::Scalar { kind, width } => { + TypeResolution::Value(TypeInner::Scalar { kind, width }) + } + ConstructorType::Vector { size, kind, width } => { + TypeResolution::Value(TypeInner::Vector { size, kind, width }) + } + ConstructorType::Matrix { + columns, + rows, + width, + } => TypeResolution::Value(TypeInner::Matrix { + columns, + rows, + width, + }), + ConstructorType::Array { base, size, stride } => { + TypeResolution::Value(TypeInner::Array { base, size, stride }) + } + ConstructorType::Struct(handle) => TypeResolution::Handle(handle), + _ => return None, + }) + } +} + +impl ConstructorType { + fn to_error_string(&self, types: &UniqueArena, constants: &Arena) -> String { + match *self { + ConstructorType::Scalar { kind, width } => kind.to_wgsl(width), + ConstructorType::PartialVector { size } => { + format!("vec{}", size as u32,) + } + ConstructorType::Vector { size, kind, width } => { + format!("vec{}<{}>", size as u32, kind.to_wgsl(width)) + } + ConstructorType::PartialMatrix { columns, rows } => { + format!("mat{}x{}", columns as u32, rows as u32,) + } + ConstructorType::Matrix { + columns, + rows, + width, + } => { + format!( + "mat{}x{}<{}>", + columns as u32, + rows as u32, + ScalarKind::Float.to_wgsl(width) + ) + } + ConstructorType::PartialArray => "array".to_string(), + ConstructorType::Array { base, size, .. } => { + format!( + "array<{}, {}>", + types[base].name.as_deref().unwrap_or("?"), + match size { + ArraySize::Constant(size) => { + constants[size] + .to_array_length() + .map(|len| len.to_string()) + .unwrap_or_else(|| "?".to_string()) + } + _ => unreachable!(), + } + ) + } + ConstructorType::Struct(handle) => types[handle] + .name + .clone() + .unwrap_or_else(|| "?".to_string()), + } + } +} + +fn parse_constructor_type<'a>( + parser: &mut Parser, + lexer: &mut Lexer<'a>, + word: &'a str, + type_arena: &mut UniqueArena, + const_arena: &mut Arena, +) -> Result, Error<'a>> { + if let Some((kind, width)) = super::conv::get_scalar_type(word) { + return Ok(Some(ConstructorType::Scalar { kind, width })); + } + + let partial = match word { + "vec2" => ConstructorType::PartialVector { + size: VectorSize::Bi, + }, + "vec3" => ConstructorType::PartialVector { + size: VectorSize::Tri, + }, + "vec4" => ConstructorType::PartialVector { + size: VectorSize::Quad, + }, + "mat2x2" => ConstructorType::PartialMatrix { + columns: VectorSize::Bi, + rows: VectorSize::Bi, + }, + "mat2x3" => ConstructorType::PartialMatrix { + columns: VectorSize::Bi, + rows: VectorSize::Tri, + }, + "mat2x4" => ConstructorType::PartialMatrix { + columns: VectorSize::Bi, + rows: VectorSize::Quad, + }, + "mat3x2" => ConstructorType::PartialMatrix { + columns: VectorSize::Tri, + rows: VectorSize::Bi, + }, + "mat3x3" => ConstructorType::PartialMatrix { + columns: VectorSize::Tri, + rows: VectorSize::Tri, + }, + "mat3x4" => ConstructorType::PartialMatrix { + columns: VectorSize::Tri, + rows: VectorSize::Quad, + }, + "mat4x2" => ConstructorType::PartialMatrix { + columns: VectorSize::Quad, + rows: VectorSize::Bi, + }, + "mat4x3" => ConstructorType::PartialMatrix { + columns: VectorSize::Quad, + rows: VectorSize::Tri, + }, + "mat4x4" => ConstructorType::PartialMatrix { + columns: VectorSize::Quad, + rows: VectorSize::Quad, + }, + "array" => ConstructorType::PartialArray, + _ => return Ok(None), + }; + + // parse component type if present + match (lexer.peek().0, partial) { + (Token::Paren('<'), ConstructorType::PartialVector { size }) => { + let (kind, width) = lexer.next_scalar_generic()?; + Ok(Some(ConstructorType::Vector { size, kind, width })) + } + (Token::Paren('<'), ConstructorType::PartialMatrix { columns, rows }) => { + let (_, width) = lexer.next_scalar_generic()?; + Ok(Some(ConstructorType::Matrix { + columns, + rows, + width, + })) + } + (Token::Paren('<'), ConstructorType::PartialArray) => { + lexer.expect_generic_paren('<')?; + let base = parser + .parse_type_decl(lexer, None, type_arena, const_arena)? + .0; + let size = if lexer.skip(Token::Separator(',')) { + let const_handle = parser.parse_const_expression(lexer, type_arena, const_arena)?; + ArraySize::Constant(const_handle) + } else { + ArraySize::Dynamic + }; + lexer.expect_generic_paren('>')?; + + let stride = { + parser.layouter.update(type_arena, const_arena).unwrap(); + parser.layouter[base].to_stride() + }; + + Ok(Some(ConstructorType::Array { base, size, stride })) + } + (_, partial) => Ok(Some(partial)), + } +} + +/// Expects [`Scope::PrimaryExpr`] scope on top; if returning Some(_), pops it. +pub(super) fn parse_construction<'a>( + parser: &mut Parser, + lexer: &mut Lexer<'a>, + type_name: &'a str, + type_span: Span, + mut ctx: ExpressionContext<'a, '_, '_>, +) -> Result>, Error<'a>> { + assert_eq!( + parser.scopes.last().map(|&(ref scope, _)| scope.clone()), + Some(Scope::PrimaryExpr) + ); + let dst_ty = match parser.lookup_type.get(type_name) { + Some(&handle) => ConstructorType::Struct(handle), + None => match parse_constructor_type(parser, lexer, type_name, ctx.types, ctx.constants)? { + Some(inner) => inner, + None => { + match parser.parse_type_decl_impl( + lexer, + super::TypeAttributes::default(), + type_name, + ctx.types, + ctx.constants, + )? { + Some(_) => { + return Err(Error::TypeNotConstructible(type_span)); + } + None => return Ok(None), + } + } + }, + }; + + lexer.open_arguments()?; + + let mut components = Vec::new(); + let mut spans = Vec::new(); + + if lexer.peek().0 == Token::Paren(')') { + let _ = lexer.next(); + } else { + while components.is_empty() || lexer.next_argument()? { + let (component, span) = lexer + .capture_span(|lexer| parser.parse_general_expression(lexer, ctx.reborrow()))?; + components.push(component); + spans.push(span); + } + } + + enum Components<'a> { + None, + One { + component: Handle, + span: Span, + ty: &'a TypeInner, + }, + Many { + components: Vec>, + spans: Vec, + first_component_ty: &'a TypeInner, + }, + } + + impl<'a> Components<'a> { + fn into_components_vec(self) -> Vec> { + match self { + Components::None => vec![], + Components::One { component, .. } => vec![component], + Components::Many { components, .. } => components, + } + } + } + + let components = match *components.as_slice() { + [] => Components::None, + [component] => { + ctx.resolve_type(component)?; + Components::One { + component, + span: spans[0].clone(), + ty: ctx.typifier.get(component, ctx.types), + } + } + [component, ..] => { + ctx.resolve_type(component)?; + Components::Many { + components, + spans, + first_component_ty: ctx.typifier.get(component, ctx.types), + } + } + }; + + let expr = match (components, dst_ty) { + // Empty constructor + (Components::None, dst_ty) => { + let ty = match dst_ty.to_type_resolution() { + Some(TypeResolution::Handle(handle)) => handle, + Some(TypeResolution::Value(inner)) => ctx + .types + .insert(Type { name: None, inner }, Default::default()), + None => return Err(Error::TypeNotInferrable(type_span)), + }; + + return match ctx.create_zero_value_constant(ty) { + Some(constant) => { + let span = parser.pop_scope(lexer); + Ok(Some(ctx.interrupt_emitter( + Expression::Constant(constant), + span.into(), + ))) + } + None => Err(Error::TypeNotConstructible(type_span)), + }; + } + + // Scalar constructor & conversion (scalar -> scalar) + ( + Components::One { + component, + ty: &TypeInner::Scalar { .. }, + .. + }, + ConstructorType::Scalar { kind, width }, + ) => Expression::As { + expr: component, + kind, + convert: Some(width), + }, + + // Vector conversion (vector -> vector) + ( + Components::One { + component, + ty: &TypeInner::Vector { size: src_size, .. }, + .. + }, + ConstructorType::Vector { + size: dst_size, + kind: dst_kind, + width: dst_width, + }, + ) if dst_size == src_size => Expression::As { + expr: component, + kind: dst_kind, + convert: Some(dst_width), + }, + + // Matrix conversion (matrix -> matrix) + ( + Components::One { + component, + ty: + &TypeInner::Matrix { + columns: src_columns, + rows: src_rows, + .. + }, + .. + }, + ConstructorType::Matrix { + columns: dst_columns, + rows: dst_rows, + width: dst_width, + }, + ) if dst_columns == src_columns && dst_rows == src_rows => Expression::As { + expr: component, + kind: ScalarKind::Float, + convert: Some(dst_width), + }, + + // Vector constructor (splat) - infer type + ( + Components::One { + component, + ty: &TypeInner::Scalar { .. }, + .. + }, + ConstructorType::PartialVector { size }, + ) => Expression::Splat { + size, + value: component, + }, + + // Vector constructor (splat) + ( + Components::One { + component, + ty: + &TypeInner::Scalar { + kind: src_kind, + width: src_width, + .. + }, + .. + }, + ConstructorType::Vector { + size, + kind: dst_kind, + width: dst_width, + }, + ) if dst_kind == src_kind || dst_width == src_width => Expression::Splat { + size, + value: component, + }, + + // Vector constructor (by elements) + ( + Components::Many { + components, + first_component_ty: &TypeInner::Scalar { kind, width }, + .. + }, + ConstructorType::PartialVector { size }, + ) + | ( + Components::Many { + components, + first_component_ty: &TypeInner::Vector { kind, width, .. }, + .. + }, + ConstructorType::PartialVector { size }, + ) + | ( + Components::Many { + components, + first_component_ty: &TypeInner::Scalar { .. }, + .. + }, + ConstructorType::Vector { size, width, kind }, + ) + | ( + Components::Many { + components, + first_component_ty: &TypeInner::Vector { .. }, + .. + }, + ConstructorType::Vector { size, width, kind }, + ) => { + let ty = ctx.types.insert( + Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }, + Default::default(), + ); + Expression::Compose { ty, components } + } + + // Matrix constructor (by elements) + ( + Components::Many { + components, + first_component_ty: &TypeInner::Scalar { width, .. }, + .. + }, + ConstructorType::PartialMatrix { columns, rows }, + ) + | ( + Components::Many { + components, + first_component_ty: &TypeInner::Scalar { .. }, + .. + }, + ConstructorType::Matrix { + columns, + rows, + width, + }, + ) => { + let vec_ty = ctx.types.insert( + Type { + name: None, + inner: TypeInner::Vector { + width, + kind: ScalarKind::Float, + size: rows, + }, + }, + Default::default(), + ); + + let components = components + .chunks(rows as usize) + .map(|vec_components| { + ctx.expressions.append( + Expression::Compose { + ty: vec_ty, + components: Vec::from(vec_components), + }, + Default::default(), + ) + }) + .collect(); + + let ty = ctx.types.insert( + Type { + name: None, + inner: TypeInner::Matrix { + columns, + rows, + width, + }, + }, + Default::default(), + ); + Expression::Compose { ty, components } + } + + // Matrix constructor (by columns) + ( + Components::Many { + components, + first_component_ty: &TypeInner::Vector { width, .. }, + .. + }, + ConstructorType::PartialMatrix { columns, rows }, + ) + | ( + Components::Many { + components, + first_component_ty: &TypeInner::Vector { .. }, + .. + }, + ConstructorType::Matrix { + columns, + rows, + width, + }, + ) => { + let ty = ctx.types.insert( + Type { + name: None, + inner: TypeInner::Matrix { + columns, + rows, + width, + }, + }, + Default::default(), + ); + Expression::Compose { ty, components } + } + + // Array constructor - infer type + (components, ConstructorType::PartialArray) => { + let components = components.into_components_vec(); + + let base = match ctx.typifier[components[0]].clone() { + TypeResolution::Handle(ty) => ty, + TypeResolution::Value(inner) => ctx + .types + .insert(Type { name: None, inner }, Default::default()), + }; + + let size = Constant { + name: None, + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Uint(components.len() as u64), + }, + }; + + let inner = TypeInner::Array { + base, + size: ArraySize::Constant(ctx.constants.append(size, Default::default())), + stride: { + parser.layouter.update(ctx.types, ctx.constants).unwrap(); + parser.layouter[base].to_stride() + }, + }; + + let ty = ctx + .types + .insert(Type { name: None, inner }, Default::default()); + + Expression::Compose { ty, components } + } + + // Array constructor + (components, ConstructorType::Array { base, size, stride }) => { + let components = components.into_components_vec(); + let inner = TypeInner::Array { base, size, stride }; + let ty = ctx + .types + .insert(Type { name: None, inner }, Default::default()); + Expression::Compose { ty, components } + } + + // Struct constructor + (components, ConstructorType::Struct(ty)) => Expression::Compose { + ty, + components: components.into_components_vec(), + }, + + // ERRORS + + // Bad conversion (type cast) + ( + Components::One { + span, ty: src_ty, .. + }, + dst_ty, + ) => { + return Err(Error::BadTypeCast { + span, + from_type: src_ty.to_wgsl(ctx.types, ctx.constants), + to_type: dst_ty.to_error_string(ctx.types, ctx.constants), + }); + } + + // Too many parameters for scalar constructor + (Components::Many { spans, .. }, ConstructorType::Scalar { .. }) => { + return Err(Error::UnexpectedComponents(Span { + start: spans[1].start, + end: spans.last().unwrap().end, + })); + } + + // Parameters are of the wrong type for vector or matrix constructor + (Components::Many { spans, .. }, ConstructorType::Vector { .. }) + | (Components::Many { spans, .. }, ConstructorType::Matrix { .. }) + | (Components::Many { spans, .. }, ConstructorType::PartialVector { .. }) + | (Components::Many { spans, .. }, ConstructorType::PartialMatrix { .. }) => { + return Err(Error::InvalidConstructorComponentType(spans[0].clone(), 0)); + } + }; + + let span = NagaSpan::from(parser.pop_scope(lexer)); + Ok(Some(ctx.expressions.append(expr, span))) +} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f0b4b32c8..cd1f445c9 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -4,6 +4,7 @@ Frontend for [WGSL][wgsl] (WebGPU Shading Language). [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html */ +mod construction; mod conv; mod lexer; mod number_literals; @@ -124,6 +125,7 @@ pub enum BadFloatError { #[derive(Clone, Debug)] pub enum Error<'a> { Unexpected(TokenSpan<'a>, ExpectedToken<'a>), + UnexpectedComponents(Span), BadU32(Span, BadIntError), BadI32(Span, BadIntError), /// A negative signed integer literal where both signed and unsigned, @@ -148,6 +150,7 @@ pub enum Error<'a> { InvalidResolve(ResolveError), InvalidForInitializer(Span), InvalidGatherComponent(Span, i32), + InvalidConstructorComponentType(Span, i32), ReservedIdentifierPrefix(Span), UnknownAddressSpace(Span), UnknownAttribute(Span), @@ -162,6 +165,8 @@ pub enum Error<'a> { ZeroSizeOrAlign(Span), InconsistentBinding(Span), UnknownLocalFunction(Span), + TypeNotConstructible(Span), + TypeNotInferrable(Span), InitializationTypeMismatch(Span, String), MissingType(Span), MissingAttribute(&'static str, Span), @@ -253,6 +258,11 @@ impl<'a> Error<'a> { notes: vec![], } }, + Error::UnexpectedComponents(ref bad_span) => ParseError { + message: "unexpected components".to_string(), + labels: vec![(bad_span.clone(), "unexpected components".into())], + notes: vec![], + }, Error::BadU32(ref bad_span, ref err) => ParseError { message: format!( "expected unsigned integer literal, found `{}`", @@ -355,6 +365,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "invalid component".into())], notes: vec![], }, + Error::InvalidConstructorComponentType(ref bad_span, component) => ParseError { + message: format!("invalid type for constructor component at index [{}]", component), + labels: vec![(bad_span.clone(), "invalid component type".into())], + notes: vec![], + }, Error::ReservedIdentifierPrefix(ref bad_span) => ParseError { message: format!("Identifier starts with a reserved prefix: '{}'", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "invalid identifier".into())], @@ -415,6 +430,16 @@ impl<'a> Error<'a> { labels: vec![(span.clone(), "unknown local function".into())], notes: vec![], }, + Error::TypeNotConstructible(ref span) => ParseError { + message: format!("type `{}` is not constructible", &source[span.clone()]), + labels: vec![(span.clone(), "type is not constructible".into())], + notes: vec![], + }, + Error::TypeNotInferrable(ref span) => ParseError { + message: "type can't be inferred".to_string(), + labels: vec![(span.clone(), "type can't be inferred".into())], + notes: vec![], + }, Error::InitializationTypeMismatch(ref name_span, ref expected_ty) => ParseError { message: format!("the type of `{}` is expected to be `{}`", &source[name_span.clone()], expected_ty), labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], @@ -969,6 +994,98 @@ impl<'a> ExpressionContext<'a, '_, '_> { expr.handle } } + + /// Creates a zero value constant of type `ty` + /// + /// Returns `None` if the given `ty` is not a constructible type + fn create_zero_value_constant( + &mut self, + ty: Handle, + ) -> Option> { + let inner = match self.types[ty].inner { + crate::TypeInner::Scalar { kind, width } => { + let value = match kind { + crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), + crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), + crate::ScalarKind::Float => crate::ScalarValue::Float(0.), + crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), + }; + crate::ConstantInner::Scalar { width, value } + } + crate::TypeInner::Vector { size, kind, width } => { + let scalar_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { width, kind }, + }, + Default::default(), + ); + let component = self.create_zero_value_constant(scalar_ty); + crate::ConstantInner::Composite { + ty, + components: (0..size as u8).map(|_| component).collect::>()?, + } + } + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + let vec_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + width, + kind: crate::ScalarKind::Float, + size: rows, + }, + }, + Default::default(), + ); + let component = self.create_zero_value_constant(vec_ty); + crate::ConstantInner::Composite { + ty, + components: (0..columns as u8) + .map(|_| component) + .collect::>()?, + } + } + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(size), + .. + } => { + let component = self.create_zero_value_constant(base); + crate::ConstantInner::Composite { + ty, + components: (0..self.constants[size].to_array_length().unwrap()) + .map(|_| component) + .collect::>()?, + } + } + crate::TypeInner::Struct { ref members, .. } => { + let members = members.clone(); + crate::ConstantInner::Composite { + ty, + components: members + .iter() + .map(|member| self.create_zero_value_constant(member.ty)) + .collect::>()?, + } + } + _ => return None, + }; + + let constant = self.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + crate::Span::default(), + ); + Some(constant) + } } /// A Naga [`Expression`] handle, with WGSL type information. @@ -2044,158 +2161,6 @@ impl Parser { })) } - /// Expects [`Scope::PrimaryExpr`] scope on top; if returning Some(_), pops it. - fn parse_construction<'a>( - &mut self, - lexer: &mut Lexer<'a>, - type_name: &'a str, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - assert_eq!( - self.scopes.last().map(|&(ref scope, _)| scope.clone()), - Some(Scope::PrimaryExpr) - ); - let ty_resolution = match self.lookup_type.get(type_name) { - Some(&handle) => TypeResolution::Handle(handle), - None => match self.parse_type_decl_impl( - lexer, - TypeAttributes::default(), - type_name, - ctx.types, - ctx.constants, - )? { - Some(inner) => TypeResolution::Value(inner), - None => return Ok(None), - }, - }; - - let mut components = Vec::new(); - let (last_component, arguments_span) = lexer.capture_span(|lexer| { - lexer.open_arguments()?; - let mut last_component = self.parse_general_expression(lexer, ctx.reborrow())?; - - while lexer.next_argument()? { - components.push(last_component); - last_component = self.parse_general_expression(lexer, ctx.reborrow())?; - } - - Ok(last_component) - })?; - - // We can't use the `TypeInner` returned by this because - // `resolve_type` borrows context mutably. - // Use it to insert into the right maps, - // and then grab it again immutably. - ctx.resolve_type(last_component)?; - - let expr = if components.is_empty() - && ty_resolution.inner_with(ctx.types).scalar_kind().is_some() - { - match ( - ty_resolution.inner_with(ctx.types), - ctx.typifier.get(last_component, ctx.types), - ) { - ( - &crate::TypeInner::Vector { - size, kind, width, .. - }, - &crate::TypeInner::Scalar { - kind: arg_kind, - width: arg_width, - .. - }, - ) if arg_kind == kind && arg_width == width => crate::Expression::Splat { - size, - value: last_component, - }, - ( - &crate::TypeInner::Scalar { kind, width, .. }, - &crate::TypeInner::Scalar { .. }, - ) - | ( - &crate::TypeInner::Vector { kind, width, .. }, - &crate::TypeInner::Vector { .. }, - ) => crate::Expression::As { - expr: last_component, - kind, - convert: Some(width), - }, - (&crate::TypeInner::Matrix { width, .. }, &crate::TypeInner::Matrix { .. }) => { - crate::Expression::As { - expr: last_component, - kind: crate::ScalarKind::Float, - convert: Some(width), - } - } - (to_type, from_type) => { - return Err(Error::BadTypeCast { - span: arguments_span, - from_type: from_type.to_wgsl(ctx.types, ctx.constants), - to_type: to_type.to_wgsl(ctx.types, ctx.constants), - }); - } - } - } else { - components.push(last_component); - let mut compose_components = Vec::new(); - - if let ( - &crate::TypeInner::Matrix { - rows, - width, - columns, - }, - &crate::TypeInner::Scalar { - kind: crate::ScalarKind::Float, - .. - }, - ) = ( - ty_resolution.inner_with(ctx.types), - ctx.typifier.get(last_component, ctx.types), - ) { - let vec_ty = ctx.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Vector { - width, - kind: crate::ScalarKind::Float, - size: rows, - }, - }, - Default::default(), - ); - - compose_components.reserve(columns as usize); - for vec_components in components.chunks(rows as usize) { - let handle = ctx.expressions.append( - crate::Expression::Compose { - ty: vec_ty, - components: Vec::from(vec_components), - }, - crate::Span::default(), - ); - compose_components.push(handle); - } - } else { - compose_components = components; - } - - let ty = match ty_resolution { - TypeResolution::Handle(handle) => handle, - TypeResolution::Value(inner) => ctx - .types - .insert(crate::Type { name: None, inner }, Default::default()), - }; - crate::Expression::Compose { - ty, - components: compose_components, - } - }; - - let span = NagaSpan::from(self.pop_scope(lexer)); - Ok(Some(ctx.expressions.append(expr, span))) - } - fn parse_const_expression_impl<'a>( &mut self, first_token_span: TokenSpan<'a>, @@ -2325,7 +2290,13 @@ impl Parser { TypedExpression::non_reference(expr) } else { let _ = lexer.next(); - if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow())? { + if let Some(expr) = construction::parse_construction( + self, + lexer, + word, + span.clone(), + ctx.reborrow(), + )? { TypedExpression::non_reference(expr) } else { return Err(Error::UnknownIdent(span, word)); diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 996f528d4..5ad2a2a2b 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -58,6 +58,21 @@ fn constructors() -> f32 { 0.0, 0.0, 0.0, 1.0, ); + // zero value constructors + var _ = bool(); + var _ = i32(); + var _ = u32(); + var _ = f32(); + var _ = vec2(); + var _ = mat2x2(); + var _ = array(); + var _ = Foo(); + + // constructors that infer their type from their parameters + var _ = vec2(0u); + var _ = mat2x2(vec2(0.), vec2(0.)); + var _ = array(0, 1, 2, 3); + return foo.a.x; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index f8a24579b..76486c837 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -43,11 +43,25 @@ vec3 bool_cast(vec3 x) { float constructors() { Foo foo = Foo(vec4(0.0), 0); + bool unnamed = false; + int unnamed_1 = 0; + uint unnamed_2 = 0u; + float unnamed_3 = 0.0; + uvec2 unnamed_4 = uvec2(0u, 0u); + mat2x2 unnamed_5 = mat2x2(vec2(0.0, 0.0), vec2(0.0, 0.0)); + Foo unnamed_6[3] = Foo[3](Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0)); + Foo unnamed_7 = Foo(vec4(0.0, 0.0, 0.0, 0.0), 0); + uvec2 unnamed_8 = uvec2(0u); + mat2x2 unnamed_9 = mat2x2(0.0); + int unnamed_10[4] = int[4](0, 0, 0, 0); foo = Foo(vec4(1.0), 1); mat2x2 mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); mat4x4 mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - float _e39 = foo.a.x; - return _e39; + unnamed_8 = uvec2(0u); + unnamed_9 = mat2x2(vec2(0.0), vec2(0.0)); + unnamed_10 = int[4](0, 1, 2, 3); + float _e70 = foo.a.x; + return _e70; } void modulo() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 327269054..08aed4f93 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -53,12 +53,29 @@ Foo ConstructFoo(float4 arg0, int arg1) { float constructors() { Foo foo = (Foo)0; + bool unnamed = false; + int unnamed_1 = 0; + uint unnamed_2 = 0u; + float unnamed_3 = 0.0; + uint2 unnamed_4 = uint2(0u, 0u); + float2x2 unnamed_5 = float2x2(float2(0.0, 0.0), float2(0.0, 0.0)); + Foo unnamed_6[3] = { { float4(0.0, 0.0, 0.0, 0.0), 0 }, { float4(0.0, 0.0, 0.0, 0.0), 0 }, { float4(0.0, 0.0, 0.0, 0.0), 0 } }; + Foo unnamed_7 = { float4(0.0, 0.0, 0.0, 0.0), 0 }; + uint2 unnamed_8 = (uint2)0; + float2x2 unnamed_9 = (float2x2)0; + int unnamed_10[4] = {(int)0,(int)0,(int)0,(int)0}; foo = ConstructFoo(float4(1.0.xxxx), 1); float2x2 mat2comp = float2x2(float2(1.0, 0.0), float2(0.0, 1.0)); float4x4 mat4comp = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); - float _expr39 = foo.a.x; - return _expr39; + unnamed_8 = uint2(0u.xx); + unnamed_9 = float2x2(float2(0.0.xx), float2(0.0.xx)); + { + int _result[4]={ 0, 1, 2, 3 }; + for(int _i=0; _i<4; ++_i) unnamed_10[_i] = _result[_i]; + } + float _expr70 = foo.a.x; + return _expr70; } void modulo() diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 0170f43ea..65a5f61c4 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -8,10 +8,22 @@ struct Foo { metal::float4 a; int b; }; +struct type_12 { + Foo inner[3]; +}; +struct type_13 { + int inner[4u]; +}; constant metal::float4 v_f32_one = {1.0, 1.0, 1.0, 1.0}; constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0}; constant metal::float4 v_f32_half = {0.5, 0.5, 0.5, 0.5}; constant metal::int4 v_i32_one = {1, 1, 1, 1}; +constant metal::uint2 const_type_11_ = {0u, 0u}; +constant metal::float2 const_type_6_ = {0.0, 0.0}; +constant metal::float2x2 const_type_7_ = {const_type_6_, const_type_6_}; +constant metal::float4 const_type = {0.0, 0.0, 0.0, 0.0}; +constant Foo const_Foo = {const_type, 0}; +constant type_12 const_type_12_ = {const_Foo, const_Foo, const_Foo}; metal::float4 builtins( ) { @@ -52,11 +64,25 @@ metal::float3 bool_cast( float constructors( ) { Foo foo; + bool unnamed = false; + int unnamed_1 = 0; + uint unnamed_2 = 0u; + float unnamed_3 = 0.0; + metal::uint2 unnamed_4 = const_type_11_; + metal::float2x2 unnamed_5 = const_type_7_; + type_12 unnamed_6 = const_type_12_; + Foo unnamed_7 = const_Foo; + metal::uint2 unnamed_8; + metal::float2x2 unnamed_9; + type_13 unnamed_10; foo = Foo {metal::float4(1.0), 1}; metal::float2x2 mat2comp = metal::float2x2(metal::float2(1.0, 0.0), metal::float2(0.0, 1.0)); metal::float4x4 mat4comp = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); - float _e39 = foo.a.x; - return _e39; + unnamed_8 = metal::uint2(0u); + unnamed_9 = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); + for(int _i=0; _i<4; ++_i) unnamed_10.inner[_i] = type_13 {0, 1, 2, 3}.inner[_i]; + float _e70 = foo.a.x; + return _e70; } void modulo( diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 22376a350..be03133c9 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,14 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 180 +; Bound: 214 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %168 "main" -OpExecutionMode %168 LocalSize 1 1 1 -OpMemberDecorate %23 0 Offset 0 -OpMemberDecorate %23 1 Offset 16 +OpEntryPoint GLCompute %202 "main" +OpExecutionMode %202 LocalSize 1 1 1 +OpMemberDecorate %27 0 Offset 0 +OpMemberDecorate %27 1 Offset 16 +OpDecorate %32 ArrayStride 32 +OpDecorate %33 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -26,208 +28,245 @@ OpMemberDecorate %23 1 Offset 16 %16 = OpConstant %4 4.0 %17 = OpConstant %8 5 %18 = OpConstant %8 2 -%19 = OpTypeVector %4 4 -%20 = OpTypeVector %8 4 -%21 = OpTypeVector %10 4 -%22 = OpTypeVector %4 3 -%23 = OpTypeStruct %19 %8 -%24 = OpTypeVector %4 2 -%25 = OpTypeMatrix %24 2 -%26 = OpTypeMatrix %19 4 -%27 = OpConstantComposite %19 %3 %3 %3 %3 -%28 = OpConstantComposite %19 %5 %5 %5 %5 -%29 = OpConstantComposite %19 %6 %6 %6 %6 -%30 = OpConstantComposite %20 %7 %7 %7 %7 -%33 = OpTypeFunction %19 -%74 = OpTypeFunction %8 -%81 = OpConstantNull %8 -%85 = OpTypeFunction %22 %22 -%87 = OpTypeVector %10 3 -%94 = OpTypePointer Function %23 -%97 = OpTypeFunction %4 -%109 = OpTypePointer Function %19 -%110 = OpTypePointer Function %4 -%112 = OpTypeInt 32 0 -%111 = OpConstant %112 0 -%117 = OpTypeFunction %2 -%121 = OpTypeVector %8 3 -%143 = OpTypePointer Function %8 -%32 = OpFunction %19 None %33 -%31 = OpLabel -OpBranch %34 -%34 = OpLabel -%35 = OpSelect %8 %9 %7 %11 -%37 = OpCompositeConstruct %21 %9 %9 %9 %9 -%36 = OpSelect %19 %37 %27 %28 -%38 = OpCompositeConstruct %21 %12 %12 %12 %12 -%39 = OpSelect %19 %38 %28 %27 -%40 = OpExtInst %19 %1 FMix %28 %27 %29 -%42 = OpCompositeConstruct %19 %13 %13 %13 %13 -%41 = OpExtInst %19 %1 FMix %28 %27 %42 -%43 = OpCompositeExtract %8 %30 0 -%44 = OpBitcast %4 %43 -%45 = OpBitcast %19 %30 -%46 = OpConvertFToS %20 %28 -%47 = OpCompositeConstruct %20 %35 %35 %35 %35 -%48 = OpIAdd %20 %47 %46 -%49 = OpConvertSToF %19 %48 -%50 = OpFAdd %19 %49 %36 -%51 = OpFAdd %19 %50 %40 -%52 = OpFAdd %19 %51 %41 -%53 = OpCompositeConstruct %19 %44 %44 %44 %44 -%54 = OpFAdd %19 %52 %53 -%55 = OpFAdd %19 %54 %45 -OpReturnValue %55 +%20 = OpTypeInt 32 0 +%19 = OpConstant %20 0 +%21 = OpConstant %8 3 +%22 = OpConstant %20 4 +%23 = OpTypeVector %4 4 +%24 = OpTypeVector %8 4 +%25 = OpTypeVector %10 4 +%26 = OpTypeVector %4 3 +%27 = OpTypeStruct %23 %8 +%28 = OpTypeVector %4 2 +%29 = OpTypeMatrix %28 2 +%30 = OpTypeMatrix %23 4 +%31 = OpTypeVector %20 2 +%32 = OpTypeArray %27 %21 +%33 = OpTypeArray %8 %22 +%34 = OpConstantComposite %23 %3 %3 %3 %3 +%35 = OpConstantComposite %23 %5 %5 %5 %5 +%36 = OpConstantComposite %23 %6 %6 %6 %6 +%37 = OpConstantComposite %24 %7 %7 %7 %7 +%38 = OpConstantComposite %31 %19 %19 +%39 = OpConstantComposite %28 %5 %5 +%40 = OpConstantComposite %29 %39 %39 +%41 = OpConstantComposite %23 %5 %5 %5 %5 +%42 = OpConstantComposite %27 %41 %11 +%43 = OpConstantComposite %32 %42 %42 %42 +%46 = OpTypeFunction %23 +%87 = OpTypeFunction %8 +%94 = OpConstantNull %8 +%98 = OpTypeFunction %26 %26 +%100 = OpTypeVector %10 3 +%107 = OpTypePointer Function %27 +%109 = OpTypePointer Function %10 +%111 = OpTypePointer Function %8 +%113 = OpTypePointer Function %20 +%115 = OpTypePointer Function %4 +%117 = OpTypePointer Function %31 +%119 = OpTypePointer Function %29 +%121 = OpTypePointer Function %32 +%126 = OpTypePointer Function %33 +%129 = OpTypeFunction %4 +%146 = OpTypePointer Function %23 +%147 = OpTypePointer Function %4 +%152 = OpTypeFunction %2 +%156 = OpTypeVector %8 3 +%45 = OpFunction %23 None %46 +%44 = OpLabel +OpBranch %47 +%47 = OpLabel +%48 = OpSelect %8 %9 %7 %11 +%50 = OpCompositeConstruct %25 %9 %9 %9 %9 +%49 = OpSelect %23 %50 %34 %35 +%51 = OpCompositeConstruct %25 %12 %12 %12 %12 +%52 = OpSelect %23 %51 %35 %34 +%53 = OpExtInst %23 %1 FMix %35 %34 %36 +%55 = OpCompositeConstruct %23 %13 %13 %13 %13 +%54 = OpExtInst %23 %1 FMix %35 %34 %55 +%56 = OpCompositeExtract %8 %37 0 +%57 = OpBitcast %4 %56 +%58 = OpBitcast %23 %37 +%59 = OpConvertFToS %24 %35 +%60 = OpCompositeConstruct %24 %48 %48 %48 %48 +%61 = OpIAdd %24 %60 %59 +%62 = OpConvertSToF %23 %61 +%63 = OpFAdd %23 %62 %49 +%64 = OpFAdd %23 %63 %53 +%65 = OpFAdd %23 %64 %54 +%66 = OpCompositeConstruct %23 %57 %57 %57 %57 +%67 = OpFAdd %23 %65 %66 +%68 = OpFAdd %23 %67 %58 +OpReturnValue %68 OpFunctionEnd -%57 = OpFunction %19 None %33 -%56 = OpLabel -OpBranch %58 -%58 = OpLabel -%59 = OpCompositeConstruct %24 %14 %14 -%60 = OpCompositeConstruct %24 %3 %3 -%61 = OpFAdd %24 %60 %59 -%62 = OpCompositeConstruct %24 %15 %15 -%63 = OpFSub %24 %61 %62 -%64 = OpCompositeConstruct %24 %16 %16 -%65 = OpFDiv %24 %63 %64 -%66 = OpCompositeConstruct %20 %17 %17 %17 %17 -%67 = OpCompositeConstruct %20 %18 %18 %18 %18 -%68 = OpSMod %20 %66 %67 -%69 = OpVectorShuffle %19 %65 %65 0 1 0 1 -%70 = OpConvertSToF %19 %68 -%71 = OpFAdd %19 %69 %70 -OpReturnValue %71 +%70 = OpFunction %23 None %46 +%69 = OpLabel +OpBranch %71 +%71 = OpLabel +%72 = OpCompositeConstruct %28 %14 %14 +%73 = OpCompositeConstruct %28 %3 %3 +%74 = OpFAdd %28 %73 %72 +%75 = OpCompositeConstruct %28 %15 %15 +%76 = OpFSub %28 %74 %75 +%77 = OpCompositeConstruct %28 %16 %16 +%78 = OpFDiv %28 %76 %77 +%79 = OpCompositeConstruct %24 %17 %17 %17 %17 +%80 = OpCompositeConstruct %24 %18 %18 %18 %18 +%81 = OpSMod %24 %79 %80 +%82 = OpVectorShuffle %23 %78 %78 0 1 0 1 +%83 = OpConvertSToF %23 %81 +%84 = OpFAdd %23 %82 %83 +OpReturnValue %84 OpFunctionEnd -%73 = OpFunction %8 None %74 -%72 = OpLabel -OpBranch %75 -%75 = OpLabel -%76 = OpLogicalNot %10 %9 -OpSelectionMerge %77 None -OpBranchConditional %76 %78 %79 -%78 = OpLabel +%86 = OpFunction %8 None %87 +%85 = OpLabel +OpBranch %88 +%88 = OpLabel +%89 = OpLogicalNot %10 %9 +OpSelectionMerge %90 None +OpBranchConditional %89 %91 %92 +%91 = OpLabel OpReturnValue %7 -%79 = OpLabel -%80 = OpNot %8 %7 -OpReturnValue %80 -%77 = OpLabel -OpReturnValue %81 +%92 = OpLabel +%93 = OpNot %8 %7 +OpReturnValue %93 +%90 = OpLabel +OpReturnValue %94 OpFunctionEnd -%84 = OpFunction %22 None %85 -%83 = OpFunctionParameter %22 -%82 = OpLabel -OpBranch %86 -%86 = OpLabel -%88 = OpCompositeConstruct %22 %5 %5 %5 -%89 = OpFUnordNotEqual %87 %83 %88 -%90 = OpCompositeConstruct %22 %5 %5 %5 -%91 = OpCompositeConstruct %22 %3 %3 %3 -%92 = OpSelect %22 %89 %91 %90 -OpReturnValue %92 -OpFunctionEnd -%96 = OpFunction %4 None %97 +%97 = OpFunction %26 None %98 +%96 = OpFunctionParameter %26 %95 = OpLabel -%93 = OpVariable %94 Function -OpBranch %98 -%98 = OpLabel -%99 = OpCompositeConstruct %19 %3 %3 %3 %3 -%100 = OpCompositeConstruct %23 %99 %7 -OpStore %93 %100 -%101 = OpCompositeConstruct %24 %3 %5 -%102 = OpCompositeConstruct %24 %5 %3 -%103 = OpCompositeConstruct %25 %101 %102 -%104 = OpCompositeConstruct %19 %3 %5 %5 %5 -%105 = OpCompositeConstruct %19 %5 %3 %5 %5 -%106 = OpCompositeConstruct %19 %5 %5 %3 %5 -%107 = OpCompositeConstruct %19 %5 %5 %5 %3 -%108 = OpCompositeConstruct %26 %104 %105 %106 %107 -%113 = OpAccessChain %110 %93 %111 %111 -%114 = OpLoad %4 %113 -OpReturnValue %114 +OpBranch %99 +%99 = OpLabel +%101 = OpCompositeConstruct %26 %5 %5 %5 +%102 = OpFUnordNotEqual %100 %96 %101 +%103 = OpCompositeConstruct %26 %5 %5 %5 +%104 = OpCompositeConstruct %26 %3 %3 %3 +%105 = OpSelect %26 %102 %104 %103 +OpReturnValue %105 OpFunctionEnd -%116 = OpFunction %2 None %117 -%115 = OpLabel -OpBranch %118 -%118 = OpLabel -%119 = OpSMod %8 %7 %7 -%120 = OpFRem %4 %3 %3 -%122 = OpCompositeConstruct %121 %7 %7 %7 -%123 = OpCompositeConstruct %121 %7 %7 %7 -%124 = OpSMod %121 %122 %123 -%125 = OpCompositeConstruct %22 %3 %3 %3 -%126 = OpCompositeConstruct %22 %3 %3 %3 -%127 = OpFRem %22 %125 %126 -OpReturn -OpFunctionEnd -%129 = OpFunction %2 None %117 -%128 = OpLabel +%128 = OpFunction %4 None %129 +%127 = OpLabel +%123 = OpVariable %117 Function +%118 = OpVariable %119 Function %40 +%112 = OpVariable %113 Function %19 +%106 = OpVariable %107 Function +%124 = OpVariable %119 Function +%120 = OpVariable %121 Function %43 +%114 = OpVariable %115 Function %5 +%108 = OpVariable %109 Function %12 +%125 = OpVariable %126 Function +%122 = OpVariable %107 Function %42 +%116 = OpVariable %117 Function %38 +%110 = OpVariable %111 Function %11 OpBranch %130 %130 = OpLabel -%131 = OpCompositeConstruct %19 %3 %5 %5 %5 -%132 = OpCompositeConstruct %19 %5 %3 %5 %5 -%133 = OpCompositeConstruct %19 %5 %5 %3 %5 -%134 = OpCompositeConstruct %19 %5 %5 %5 %3 -%135 = OpCompositeConstruct %26 %131 %132 %133 %134 -%136 = OpMatrixTimesScalar %26 %135 %14 +%131 = OpCompositeConstruct %23 %3 %3 %3 %3 +%132 = OpCompositeConstruct %27 %131 %7 +OpStore %106 %132 +%133 = OpCompositeConstruct %28 %3 %5 +%134 = OpCompositeConstruct %28 %5 %3 +%135 = OpCompositeConstruct %29 %133 %134 +%136 = OpCompositeConstruct %23 %3 %5 %5 %5 +%137 = OpCompositeConstruct %23 %5 %3 %5 %5 +%138 = OpCompositeConstruct %23 %5 %5 %3 %5 +%139 = OpCompositeConstruct %23 %5 %5 %5 %3 +%140 = OpCompositeConstruct %30 %136 %137 %138 %139 +%141 = OpCompositeConstruct %31 %19 %19 +OpStore %123 %141 +%142 = OpCompositeConstruct %28 %5 %5 +%143 = OpCompositeConstruct %28 %5 %5 +%144 = OpCompositeConstruct %29 %142 %143 +OpStore %124 %144 +%145 = OpCompositeConstruct %33 %11 %7 %18 %21 +OpStore %125 %145 +%148 = OpAccessChain %147 %106 %19 %19 +%149 = OpLoad %4 %148 +OpReturnValue %149 +OpFunctionEnd +%151 = OpFunction %2 None %152 +%150 = OpLabel +OpBranch %153 +%153 = OpLabel +%154 = OpSMod %8 %7 %7 +%155 = OpFRem %4 %3 %3 +%157 = OpCompositeConstruct %156 %7 %7 %7 +%158 = OpCompositeConstruct %156 %7 %7 %7 +%159 = OpSMod %156 %157 %158 +%160 = OpCompositeConstruct %26 %3 %3 %3 +%161 = OpCompositeConstruct %26 %3 %3 %3 +%162 = OpFRem %26 %160 %161 OpReturn OpFunctionEnd -%138 = OpFunction %2 None %117 -%137 = OpLabel -OpBranch %139 -%139 = OpLabel -%140 = OpLogicalOr %10 %9 %12 -%141 = OpLogicalAnd %10 %9 %12 +%164 = OpFunction %2 None %152 +%163 = OpLabel +OpBranch %165 +%165 = OpLabel +%166 = OpCompositeConstruct %23 %3 %5 %5 %5 +%167 = OpCompositeConstruct %23 %5 %3 %5 %5 +%168 = OpCompositeConstruct %23 %5 %5 %3 %5 +%169 = OpCompositeConstruct %23 %5 %5 %5 %3 +%170 = OpCompositeConstruct %30 %166 %167 %168 %169 +%171 = OpMatrixTimesScalar %30 %170 %14 OpReturn OpFunctionEnd -%145 = OpFunction %2 None %117 -%144 = OpLabel -%142 = OpVariable %143 Function %7 -OpBranch %146 -%146 = OpLabel -%147 = OpLoad %8 %142 -%148 = OpIAdd %8 %147 %7 -OpStore %142 %148 -%149 = OpLoad %8 %142 -%150 = OpISub %8 %149 %7 -OpStore %142 %150 -%151 = OpLoad %8 %142 -%152 = OpLoad %8 %142 -%153 = OpIMul %8 %151 %152 -OpStore %142 %153 -%154 = OpLoad %8 %142 -%155 = OpLoad %8 %142 -%156 = OpSDiv %8 %154 %155 -OpStore %142 %156 -%157 = OpLoad %8 %142 -%158 = OpSMod %8 %157 %7 -OpStore %142 %158 -%159 = OpLoad %8 %142 -%160 = OpBitwiseXor %8 %159 %11 -OpStore %142 %160 -%161 = OpLoad %8 %142 -%162 = OpBitwiseAnd %8 %161 %11 -OpStore %142 %162 -%163 = OpLoad %8 %142 -%164 = OpIAdd %8 %163 %7 -OpStore %142 %164 -%165 = OpLoad %8 %142 -%166 = OpISub %8 %165 %7 -OpStore %142 %166 +%173 = OpFunction %2 None %152 +%172 = OpLabel +OpBranch %174 +%174 = OpLabel +%175 = OpLogicalOr %10 %9 %12 +%176 = OpLogicalAnd %10 %9 %12 OpReturn OpFunctionEnd -%168 = OpFunction %2 None %117 -%167 = OpLabel -OpBranch %169 -%169 = OpLabel -%170 = OpFunctionCall %19 %32 -%171 = OpFunctionCall %19 %57 -%172 = OpFunctionCall %8 %73 -%173 = OpVectorShuffle %22 %27 %27 0 1 2 -%174 = OpFunctionCall %22 %84 %173 -%175 = OpFunctionCall %4 %96 -%176 = OpFunctionCall %2 %116 -%177 = OpFunctionCall %2 %129 -%178 = OpFunctionCall %2 %138 -%179 = OpFunctionCall %2 %145 +%179 = OpFunction %2 None %152 +%178 = OpLabel +%177 = OpVariable %111 Function %7 +OpBranch %180 +%180 = OpLabel +%181 = OpLoad %8 %177 +%182 = OpIAdd %8 %181 %7 +OpStore %177 %182 +%183 = OpLoad %8 %177 +%184 = OpISub %8 %183 %7 +OpStore %177 %184 +%185 = OpLoad %8 %177 +%186 = OpLoad %8 %177 +%187 = OpIMul %8 %185 %186 +OpStore %177 %187 +%188 = OpLoad %8 %177 +%189 = OpLoad %8 %177 +%190 = OpSDiv %8 %188 %189 +OpStore %177 %190 +%191 = OpLoad %8 %177 +%192 = OpSMod %8 %191 %7 +OpStore %177 %192 +%193 = OpLoad %8 %177 +%194 = OpBitwiseXor %8 %193 %11 +OpStore %177 %194 +%195 = OpLoad %8 %177 +%196 = OpBitwiseAnd %8 %195 %11 +OpStore %177 %196 +%197 = OpLoad %8 %177 +%198 = OpIAdd %8 %197 %7 +OpStore %177 %198 +%199 = OpLoad %8 %177 +%200 = OpISub %8 %199 %7 +OpStore %177 %200 +OpReturn +OpFunctionEnd +%202 = OpFunction %2 None %152 +%201 = OpLabel +OpBranch %203 +%203 = OpLabel +%204 = OpFunctionCall %23 %45 +%205 = OpFunctionCall %23 %70 +%206 = OpFunctionCall %8 %86 +%207 = OpVectorShuffle %26 %34 %34 0 1 2 +%208 = OpFunctionCall %26 %97 %207 +%209 = OpFunctionCall %4 %128 +%210 = OpFunctionCall %2 %151 +%211 = OpFunctionCall %2 %164 +%212 = OpFunctionCall %2 %173 +%213 = OpFunctionCall %2 %179 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 33e0ab198..d2ce23857 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -40,12 +40,26 @@ fn bool_cast(x: vec3) -> vec3 { fn constructors() -> f32 { var foo: Foo; + var unnamed: bool = false; + var unnamed_1: i32 = 0; + var unnamed_2: u32 = 0u; + var unnamed_3: f32 = 0.0; + var unnamed_4: vec2 = vec2(0u, 0u); + var unnamed_5: mat2x2 = mat2x2(vec2(0.0, 0.0), vec2(0.0, 0.0)); + var unnamed_6: array = array(Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0)); + var unnamed_7: Foo = Foo(vec4(0.0, 0.0, 0.0, 0.0), 0); + var unnamed_8: vec2; + var unnamed_9: mat2x2; + var unnamed_10: array; foo = Foo(vec4(1.0), 1); let mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); let mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let _e39 = foo.a.x; - return _e39; + unnamed_8 = vec2(0u); + unnamed_9 = mat2x2(vec2(0.0), vec2(0.0)); + unnamed_10 = array(0, 1, 2, 3); + let _e70 = foo.a.x; + return _e70; } fn modulo() { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 7e6b3578e..71ed5ac91 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -157,10 +157,82 @@ fn bad_type_cast() { } "#, r#"error: cannot cast a vec2 to a i32 - ┌─ wgsl:3:27 + ┌─ wgsl:3:28 │ 3 │ return i32(vec2(0.0)); - │ ^^^^^^^^^^^^^^^^ cannot cast a vec2 to a i32 + │ ^^^^^^^^^^^^^^ cannot cast a vec2 to a i32 + +"#, + ); +} + +#[test] +fn type_not_constructible() { + check( + r#" + fn x() { + var _ = atomic(0); + } + "#, + r#"error: type `atomic` is not constructible + ┌─ wgsl:3:25 + │ +3 │ var _ = atomic(0); + │ ^^^^^^ type is not constructible + +"#, + ); +} + +#[test] +fn type_not_inferrable() { + check( + r#" + fn x() { + var _ = vec2(); + } + "#, + r#"error: type can't be inferred + ┌─ wgsl:3:25 + │ +3 │ var _ = vec2(); + │ ^^^^ type can't be inferred + +"#, + ); +} + +#[test] +fn unexpected_constructor_parameters() { + check( + r#" + fn x() { + var _ = i32(0, 1); + } + "#, + r#"error: unexpected components + ┌─ wgsl:3:31 + │ +3 │ var _ = i32(0, 1); + │ ^^ unexpected components + +"#, + ); +} + +#[test] +fn constructor_parameter_type_mismatch() { + check( + r#" + fn x() { + var _ = mat2x2(array(0, 1), vec2(2, 3)); + } + "#, + r#"error: invalid type for constructor component at index [0] + ┌─ wgsl:3:37 + │ +3 │ var _ = mat2x2(array(0, 1), vec2(2, 3)); + │ ^^^^^^^^^^^ invalid component type "#, ); From 6bbba0d0d509f9fe96814473f2369ddc19f230d1 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 30 Mar 2022 21:31:26 +0300 Subject: [PATCH 1643/2212] [wgsl] Rename smoothStep to smoothstep (#1800) --- CHANGELOG.md | 1 + src/back/wgsl/writer.rs | 2 +- src/front/wgsl/conv.rs | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a7dd30bd..49d0bcbe3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - renames: - `findLsb` -> `firstTrailingBit` - `findMsb` -> `firstLeadingBit` + - `smoothStep` -> `smoothstep` ## v0.8 (2021-12-18) - development release for wgpu-0.12 diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index a85ade071..57779e42f 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1517,7 +1517,7 @@ impl Writer { Mf::Fma => Function::Regular("fma"), Mf::Mix => Function::Regular("mix"), Mf::Step => Function::Regular("step"), - Mf::SmoothStep => Function::Regular("smoothStep"), + Mf::SmoothStep => Function::Regular("smoothstep"), Mf::Sqrt => Function::Regular("sqrt"), Mf::InverseSqrt => Function::Regular("inverseSqrt"), Mf::Transpose => Function::Regular("transpose"), diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index a4cf149a2..3039d98fe 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -191,7 +191,7 @@ pub fn map_standard_fun(word: &str) -> Option { "fma" => Mf::Fma, "mix" => Mf::Mix, "step" => Mf::Step, - "smoothStep" => Mf::SmoothStep, + "smoothstep" => Mf::SmoothStep, "sqrt" => Mf::Sqrt, "inverseSqrt" => Mf::InverseSqrt, "transpose" => Mf::Transpose, From 43cd0eceddfac4c44c9a4fc4e9d156dfd1abba57 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 30 Mar 2022 21:32:01 +0300 Subject: [PATCH 1644/2212] [wgsl] Make colon in case optional (#1801) --- src/front/wgsl/mod.rs | 4 ++-- src/front/wgsl/tests.rs | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index cd1f445c9..e73faf68b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3722,7 +3722,7 @@ impl Parser { break value; } } else { - lexer.expect(Token::Separator(':'))?; + lexer.skip(Token::Separator(':')); break value; } cases.push(crate::SwitchCase { @@ -3742,7 +3742,7 @@ impl Parser { }); } (Token::Word("default"), _) => { - lexer.expect(Token::Separator(':'))?; + lexer.skip(Token::Separator(':')); let (fall_through, body) = self.parse_switch_case_body(lexer, context.reborrow())?; cases.push(crate::SwitchCase { diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 281bd21f6..ffbe89936 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -329,6 +329,24 @@ fn parse_switch() { .unwrap(); } +#[test] +fn parse_switch_optional_colon_in_case() { + parse_str( + " + fn main() { + var pos: f32; + switch (3) { + case 0, 1 { pos = 0.0; } + case 2 { pos = 1.0; fallthrough; } + case 3 {} + default { pos = 3.0; } + } + } + ", + ) + .unwrap(); +} + #[test] fn parse_parentheses_switch() { parse_str( From 2db49b6998a6159552a2bcb4395fae1664332e60 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Sun, 10 Apr 2022 07:35:28 +0200 Subject: [PATCH 1645/2212] validate uniform address space layout constraints (#1812) --- src/valid/type.rs | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/valid/type.rs b/src/valid/type.rs index aae4fbd11..6eaa689d6 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -4,6 +4,8 @@ use crate::{ proc::Alignment, }; +const UNIFORM_MIN_ALIGNMENT: Alignment = unsafe { Alignment::new_unchecked(16) }; + bitflags::bitflags! { /// Flags associated with [`Type`]s by [`Validator`]. /// @@ -64,6 +66,12 @@ pub enum Disalignment { offset: u32, alignment: u32, }, + #[error("The struct member[{index}] offset {offset} must be at least {expected}")] + MemberOffsetAfterStruct { + index: u32, + offset: u32, + expected: u32, + }, #[error("The struct member[{index}] is not statically sized")] UnsizedMember { index: u32 }, #[error("The type is not host-shareable")] @@ -341,7 +349,11 @@ impl super::Validator { let uniform_layout = match base_info.uniform_layout { Ok(base_alignment) => { // combine the alignment requirements - let align = base_alignment.unwrap().get().max(general_alignment); + let align = base_alignment + .unwrap() + .get() + .max(general_alignment) + .max(UNIFORM_MIN_ALIGNMENT.get()); if stride % align != 0 { Err(( handle, @@ -448,8 +460,12 @@ impl super::Validator { | TypeFlags::ARGUMENT, 1, ); + ti.uniform_layout = Ok(Some(UNIFORM_MIN_ALIGNMENT)); + let mut min_offset = 0; + let mut prev_struct_data: Option<(u32, u32)> = None; + for (i, member) in members.iter().enumerate() { if member.ty >= handle { return Err(TypeError::UnresolvedBase(member.ty)); @@ -509,6 +525,29 @@ impl super::Validator { handle, ); + // Validate rule: If a structure member itself has a structure type S, + // then the number of bytes between the start of that member and + // the start of any following member must be at least roundUp(16, SizeOf(S)). + if let Some((span, offset)) = prev_struct_data { + let diff = member.offset - offset; + let min = crate::valid::Layouter::round_up(UNIFORM_MIN_ALIGNMENT, span); + if diff < min { + ti.uniform_layout = Err(( + handle, + Disalignment::MemberOffsetAfterStruct { + index: i as u32, + offset: member.offset, + expected: offset + min, + }, + )); + } + }; + + prev_struct_data = match types[member.ty].inner { + crate::TypeInner::Struct { span, .. } => Some((span, member.offset)), + _ => None, + }; + // The last field may be an unsized array. if !base_info.flags.contains(TypeFlags::SIZED) { let is_array = match types[member.ty].inner { From a3d968e79527b805a7639a4c4db4fa024c16a8c7 Mon Sep 17 00:00:00 2001 From: Noel Tautges Date: Sun, 10 Apr 2022 00:36:36 -0500 Subject: [PATCH 1646/2212] [hlsl-out] Don't output interpolation modifier if it's the default (#1809) * hlsl-out: don't output interpolation modifier if it's the default (linear/`Interpolation::Perspective`) * Remove linear interpolation modifiers from HLSL output tests --- src/back/hlsl/conv.rs | 12 +++++++----- src/back/hlsl/writer.rs | 4 +++- tests/out/hlsl/interface.hlsl | 4 ++-- tests/out/hlsl/interpolate.hlsl | 6 +++--- tests/out/hlsl/quad-vert.hlsl | 2 +- tests/out/hlsl/quad.hlsl | 2 +- tests/out/hlsl/shadow.hlsl | 4 ++-- tests/out/hlsl/skybox.hlsl | 2 +- 8 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index eb6515f9c..978b07388 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -111,12 +111,14 @@ impl crate::BuiltIn { } impl crate::Interpolation { - /// Helper function that returns the string corresponding to the HLSL interpolation qualifier - pub(super) fn to_hlsl_str(self) -> &'static str { + /// Return the string corresponding to the HLSL interpolation qualifier. + pub(super) fn to_hlsl_str(self) -> Option<&'static str> { match self { - Self::Perspective => "linear", - Self::Linear => "noperspective", - Self::Flat => "nointerpolation", + // Would be "linear", but it's the default interpolation in SM4 and up + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-struct#interpolation-modifiers-introduced-in-shader-model-4 + Self::Perspective => None, + Self::Linear => Some("noperspective"), + Self::Flat => Some("nointerpolation"), } } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 66a1fc57a..9d6214f29 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -758,7 +758,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }) = member.binding { if let Some(interpolation) = interpolation { - write!(self.out, "{} ", interpolation.to_hlsl_str())? + if let Some(string) = interpolation.to_hlsl_str() { + write!(self.out, "{} ", string)? + } } if let Some(sampling) = sampling { diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 9ccafc340..37098b4da 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -7,13 +7,13 @@ ConstantBuffer _NagaConstants: register(b0, space1); struct VertexOutput { float4 position : SV_Position; - linear float varying : LOC1; + float varying : LOC1; }; struct FragmentOutput { float depth : SV_Depth; uint sample_mask : SV_Coverage; - linear float color : SV_Target0; + float color : SV_Target0; }; struct Input1_ { diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index 07e0090d7..b45de9447 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -5,9 +5,9 @@ struct FragmentInput { noperspective float linear_ : LOC1; noperspective centroid float2 linear_centroid : LOC2; noperspective sample float3 linear_sample : LOC3; - linear float4 perspective : LOC4; - linear centroid float perspective_centroid : LOC5; - linear sample float perspective_sample : LOC6; + float4 perspective : LOC4; + centroid float perspective_centroid : LOC5; + sample float perspective_sample : LOC6; }; struct VertexOutput_vert_main { diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 7b926b106..a02dde77f 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -7,7 +7,7 @@ struct gl_PerVertex { }; struct type_9 { - linear float2 member : LOC0; + float2 member : LOC0; float4 gl_Position : SV_Position; }; diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index ee1bc56ef..d4f7ed54b 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -1,7 +1,7 @@ static const float c_scale = 1.2000000476837158; struct VertexOutput { - linear float2 uv : LOC0; + float2 uv : LOC0; float4 position : SV_Position; }; diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index aca4edda3..b66713092 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -13,8 +13,8 @@ struct Entity { struct VertexOutput { float4 proj_position : SV_Position; - linear float3 world_normal : LOC0; - linear float4 world_position : LOC1; + float3 world_normal : LOC0; + float4 world_position : LOC1; }; struct Light { diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 3988369cf..3664c497c 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -7,7 +7,7 @@ ConstantBuffer _NagaConstants: register(b1); struct VertexOutput { float4 position : SV_Position; - linear float3 uv : LOC0; + float3 uv : LOC0; }; struct Data { From fa44d9d5369378be47cc12fe407651d01992a2ea Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 11 Apr 2022 06:42:02 +0200 Subject: [PATCH 1647/2212] [glsl-in] error on a `matCx2` used with the std140 layout (#1806) --- src/front/glsl/error.rs | 6 ++++++ src/front/glsl/offset.rs | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index cd0577a6e..e1418f1e5 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -94,6 +94,12 @@ pub enum ErrorKind { /// prioritize work. #[error("Unknown layout qualifier: {0}")] UnknownLayoutQualifier(String), + /// Unsupported matrix of the form matCx2 + /// + /// Our IR expects matrices of the form matCx2 to have a stride of 8 however + /// matrices in the std140 layout have a stride of at least 16 + #[error("unsupported matrix of the form matCx2 in std140 block layout")] + UnsupportedMatrixTypeInStd140, /// A variable with the same name already exists in the current scope. #[cfg(feature = "glsl-validate")] #[error("Variable already declared: {0}")] diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 56ee4ab14..9c89b5d2c 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -121,6 +121,14 @@ pub fn calculate_offset( align = align_up(align, 16); } + // See comment on the error kind + if StructLayout::Std140 == layout && rows == crate::VectorSize::Bi { + errors.push(Error { + kind: ErrorKind::UnsupportedMatrixTypeInStd140, + meta, + }); + } + (align, align * columns as u32) } TypeInner::Struct { ref members, .. } => { From d3957c1186f508767c7a2949193d7db86ef34913 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 23 Mar 2022 18:58:19 +0100 Subject: [PATCH 1648/2212] implement invariant attribute --- src/back/glsl/features.rs | 2 +- src/back/glsl/mod.rs | 15 +++- src/back/hlsl/writer.rs | 76 ++++++++++++++----- src/back/mod.rs | 4 +- src/back/msl/mod.rs | 37 ++++++--- src/back/msl/writer.rs | 42 +++++----- src/back/spv/helpers.rs | 2 +- src/back/spv/writer.rs | 31 ++++++-- src/back/wgsl/writer.rs | 32 +++++--- src/front/glsl/ast.rs | 10 +++ src/front/glsl/lex.rs | 1 + src/front/glsl/parser/declarations.rs | 8 ++ src/front/glsl/parser/types.rs | 18 ++++- src/front/glsl/token.rs | 1 + src/front/glsl/variables.rs | 24 +++++- src/front/spv/function.rs | 11 +-- src/front/spv/mod.rs | 22 ++++-- src/front/wgsl/mod.rs | 20 ++++- src/lib.rs | 6 +- src/proc/mod.rs | 2 +- src/valid/analyzer.rs | 2 +- src/valid/interface.rs | 2 +- tests/in/interface.param.ron | 7 ++ tests/in/interface.wgsl | 4 +- tests/out/hlsl/interface.hlsl | 8 +- tests/out/hlsl/interpolate.hlsl | 24 +++--- tests/out/ir/collatz.ron | 5 +- tests/out/msl/interface.msl | 8 +- tests/out/msl/skybox.msl | 2 +- tests/out/spv/interface.fragment.spvasm | 1 + tests/out/spv/interface.vertex.spvasm | 1 + .../spv/interface.vertex_two_structs.spvasm | 1 + tests/out/wgsl/interface.wgsl | 4 +- 33 files changed, 316 insertions(+), 117 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index cde597727..345d51436 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -404,7 +404,7 @@ impl<'a, W> Writer<'a, W> { _ => { if let Some(binding) = binding { match *binding { - Binding::BuiltIn(builtin) => match builtin { + Binding::BuiltIn { built_in, .. } => match built_in { crate::BuiltIn::ClipDistance => { self.features.request(Features::CLIP_DISTANCE) } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c8dabbe58..1e3f0d058 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -336,7 +336,7 @@ impl fmt::Display for VaryingName<'_> { }; write!(f, "_{}_location{}", prefix, location,) } - crate::Binding::BuiltIn(built_in) => { + crate::Binding::BuiltIn { built_in, .. } => { write!(f, "{}", glsl_built_in(built_in, self.output)) } } @@ -1122,6 +1122,13 @@ impl<'a, W: Write> Writer<'a, W> { interpolation, sampling, }) => (location, interpolation, sampling), + Some(&crate::Binding::BuiltIn { + built_in, + invariant: true, + }) => { + writeln!(self.out, "invariant {};", glsl_built_in(built_in, output))?; + return Ok(()); + } _ => return Ok(()), }; @@ -1772,8 +1779,10 @@ impl<'a, W: Write> Writer<'a, W> { for (index, member) in members.iter().enumerate() { // TODO: handle builtin in better way - if let Some(crate::Binding::BuiltIn(builtin)) = - member.binding + if let Some(crate::Binding::BuiltIn { + built_in: builtin, + .. + }) = member.binding { match builtin { crate::BuiltIn::ClipDistance diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 9d6214f29..5516f94a2 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -60,7 +60,7 @@ impl InterfaceKey { fn new(binding: Option<&crate::Binding>) -> Self { match binding { Some(&crate::Binding::Location { location, .. }) => Self::Location(location), - Some(&crate::Binding::BuiltIn(bi)) => Self::BuiltIn(bi), + Some(&crate::Binding::BuiltIn { built_in, .. }) => Self::BuiltIn(built_in), None => Self::Other, } } @@ -301,6 +301,36 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(super::ReflectionInfo { entry_point_names }) } + fn write_modifier(&mut self, binding: &crate::Binding) -> BackendResult { + match *binding { + crate::Binding::BuiltIn { + invariant: true, .. + } => { + write!(self.out, "precise ")?; + } + crate::Binding::Location { + interpolation, + sampling, + .. + } => { + if let Some(interpolation) = interpolation { + if let Some(string) = interpolation.to_hlsl_str() { + write!(self.out, "{} ", string)? + } + } + + if let Some(sampling) = sampling { + if let Some(string) = sampling.to_hlsl_str() { + write!(self.out, "{} ", string)? + } + } + } + _ => {} + } + + Ok(()) + } + //TODO: we could force fragment outputs to always go through `entry_point_io.output` path // if they are struct, so that the `stage` argument here could be omitted. fn write_semantic( @@ -309,7 +339,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { stage: Option<(ShaderStage, Io)>, ) -> BackendResult { match *binding { - crate::Binding::BuiltIn(builtin) => { + crate::Binding::BuiltIn { + built_in: builtin, .. + } => { let builtin_str = builtin.to_hlsl_str()?; write!(self.out, " : {}", builtin_str)?; } @@ -341,6 +373,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, " {{")?; for m in members.iter() { write!(self.out, "{}", back::INDENT)?; + if let Some(ref binding) = m.binding { + self.write_modifier(binding)?; + } self.write_type(module, m.ty)?; write!(self.out, " {}", &m.name)?; if let Some(ref binding) = m.binding { @@ -750,24 +785,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_array_size(module, size)?; } _ => { - // Write interpolation modifier before type - if let Some(crate::Binding::Location { - interpolation, - sampling, - .. - }) = member.binding - { - if let Some(interpolation) = interpolation { - if let Some(string) = interpolation.to_hlsl_str() { - write!(self.out, "{} ", string)? - } - } - - if let Some(sampling) = sampling { - if let Some(string) = sampling.to_hlsl_str() { - write!(self.out, "{} ", string)? - } - } + // Write modifier before type + if let Some(ref binding) = member.binding { + self.write_modifier(binding)?; } if let TypeInner::Matrix { .. } = module.types[member.ty].inner { @@ -887,6 +907,22 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { func_ctx: &back::FunctionCtx<'_>, ) -> BackendResult { // Function Declaration Syntax - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-function-syntax + + // Write modifier + if let Some(crate::FunctionResult { + binding: + Some( + ref binding @ crate::Binding::BuiltIn { + invariant: true, .. + }, + ), + .. + }) = func.result + { + self.write_modifier(binding)?; + } + + // Write return type if let Some(ref result) = func.result { match func_ctx.ty { back::FunctionType::Function(_) => { diff --git a/src/back/mod.rs b/src/back/mod.rs index 9802e5acf..0dc010f1b 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -96,14 +96,14 @@ impl<'a> FunctionCtx<'_> { match self.expressions[expression] { crate::Expression::FunctionArgument(arg_index) => { return match ep_function.arguments[arg_index as usize].binding { - Some(crate::Binding::BuiltIn(bi)) => Some(bi), + Some(crate::Binding::BuiltIn { built_in: bi, .. }) => Some(bi), _ => built_in, }; } crate::Expression::AccessIndex { base, index } => { match *self.info[base].ty.inner_with(&module.types) { crate::TypeInner::Struct { ref members, .. } => { - if let Some(crate::Binding::BuiltIn(bi)) = + if let Some(crate::Binding::BuiltIn { built_in: bi, .. }) = members[index as usize].binding { built_in = Some(bi); diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 0a95e8cf9..22dba510f 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -100,7 +100,10 @@ impl ops::Index for PerStageMap { } enum ResolvedBinding { - BuiltIn(crate::BuiltIn), + BuiltIn { + built_in: crate::BuiltIn, + invariant: bool, + }, Attribute(u32), Color(u32), User { @@ -146,6 +149,8 @@ pub enum Error { CapabilityNotSupported(crate::valid::Capabilities), #[error("address space {0:?} is not supported for target MSL version")] UnsupportedAddressSpace(crate::AddressSpace), + #[error("attribute '{0}' is not supported for target MSL version")] + UnsupportedAttribute(String), } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -218,7 +223,19 @@ impl Options { mode: LocationMode, ) -> Result { match *binding { - crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)), + crate::Binding::BuiltIn { + built_in, + invariant, + } => { + if invariant && self.lang_version < (2, 1) { + return Err(Error::UnsupportedAttribute("invariant".to_string())); + } + + Ok(ResolvedBinding::BuiltIn { + built_in, + invariant, + }) + } crate::Binding::Location { location, interpolation, @@ -328,8 +345,12 @@ impl ResolvedBinding { } fn try_fmt(&self, out: &mut W) -> Result<(), Error> { + write!(out, " [[")?; match *self { - Self::BuiltIn(built_in) => { + Self::BuiltIn { + built_in, + invariant, + } => { use crate::BuiltIn as Bi; let name = match built_in { Bi::Position => "position", @@ -358,6 +379,10 @@ impl ResolvedBinding { } }; write!(out, "{}", name)?; + + if invariant { + write!(out, ", invariant")?; + } } Self::Attribute(index) => write!(out, "attribute({})", index)?, Self::Color(index) => write!(out, "color({})", index)?, @@ -384,12 +409,6 @@ impl ResolvedBinding { } } } - Ok(()) - } - - fn try_fmt_decorated(&self, out: &mut W) -> Result<(), Error> { - write!(out, " [[")?; - self.try_fmt(out)?; write!(out, "]]")?; Ok(()) } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 3fd0355a3..ebfe7c834 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2106,13 +2106,19 @@ impl Writer { for (index, member) in members.iter().enumerate() { match member.binding { - Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) => { + Some(crate::Binding::BuiltIn { + built_in: crate::BuiltIn::PointSize, + .. + }) => { has_point_size = true; if !context.pipeline_options.allow_point_size { continue; } } - Some(crate::Binding::BuiltIn(crate::BuiltIn::CullDistance)) => { + Some(crate::Binding::BuiltIn { + built_in: crate::BuiltIn::CullDistance, + .. + }) => { log::warn!("Ignoring CullDistance built-in"); continue; } @@ -3355,7 +3361,7 @@ impl Writer { }; let resolved = options.resolve_local_binding(binding, in_mode)?; write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; - resolved.try_fmt_decorated(&mut self.out)?; + resolved.try_fmt(&mut self.out)?; writeln!(self.out, ";")?; } writeln!(self.out, "}};")?; @@ -3401,7 +3407,10 @@ impl Writer { match *binding { // Point size is only supported in VS of pipelines with // point primitive topology. - crate::Binding::BuiltIn(crate::BuiltIn::PointSize) => { + crate::Binding::BuiltIn { + built_in: crate::BuiltIn::PointSize, + .. + } => { has_point_size = true; if !pipeline_options.allow_point_size { continue; @@ -3411,7 +3420,10 @@ impl Writer { // But we can't return UnsupportedBuiltIn error to user. // Because otherwise we can't generate msl shader from any glslang SPIR-V shaders. // glslang generates gl_PerVertex struct with gl_CullDistance builtin inside by default. - crate::Binding::BuiltIn(crate::BuiltIn::CullDistance) => { + crate::Binding::BuiltIn { + built_in: crate::BuiltIn::CullDistance, + .. + } => { log::warn!("Ignoring CullDistance BuiltIn"); continue; } @@ -3430,14 +3442,8 @@ impl Writer { if let Some(array_len) = array_len { write!(self.out, " [{}]", array_len)?; } - write!(self.out, " [[")?; resolved.try_fmt(&mut self.out)?; - if options.lang_version >= (2, 1) - && *binding == crate::Binding::BuiltIn(crate::BuiltIn::Position) - { - write!(self.out, ", invariant")?; - } - writeln!(self.out, "]];")?; + writeln!(self.out, ";")?; } if pipeline_options.allow_point_size @@ -3483,7 +3489,7 @@ impl Writer { let mut flattened_member_names = FastHashMap::default(); for &(ref name_key, ty, binding) in flattened_arguments.iter() { let binding = match binding { - Some(ref binding @ &crate::Binding::BuiltIn(..)) => binding, + Some(ref binding @ &crate::Binding::BuiltIn { .. }) => binding, _ => continue, }; let name = if let NameKey::StructMember(ty, index) = *name_key { @@ -3511,7 +3517,7 @@ impl Writer { ',' }; write!(self.out, "{} {} {}", separator, ty_name, name)?; - resolved.try_fmt_decorated(&mut self.out)?; + resolved.try_fmt(&mut self.out)?; writeln!(self.out)?; } @@ -3560,7 +3566,7 @@ impl Writer { write!(self.out, "{} ", separator)?; tyvar.try_fmt(&mut self.out)?; if let Some(resolved) = resolved { - resolved.try_fmt_decorated(&mut self.out)?; + resolved.try_fmt(&mut self.out)?; } if let Some(value) = var.init { let coco = ConstantContext { @@ -3589,7 +3595,7 @@ impl Writer { "{} constant _mslBufferSizes& _buffer_sizes", separator, )?; - resolved.try_fmt_decorated(&mut self.out)?; + resolved.try_fmt(&mut self.out)?; writeln!(self.out)?; } @@ -3674,7 +3680,9 @@ impl Writer { // have passed it as its own argument and assigned // it a new name. let name = match member.binding { - Some(crate::Binding::BuiltIn(_)) => &flattened_member_names[&key], + Some(crate::Binding::BuiltIn { .. }) => { + &flattened_member_names[&key] + } _ => &self.names[&key], }; if member_index != 0 { diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index acde9504d..5580fec2c 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -38,7 +38,7 @@ pub(super) fn contains_builtin( arena: &UniqueArena, built_in: crate::BuiltIn, ) -> bool { - if let Some(&crate::Binding::BuiltIn(bi)) = binding { + if let Some(&crate::Binding::BuiltIn { built_in: bi, .. }) = binding { bi == built_in } else if let crate::TypeInner::Struct { ref members, .. } = arena[ty].inner { members diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 9da968d8a..88d70345f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -398,8 +398,11 @@ impl Writer { let mut has_point_size = false; let class = spirv::StorageClass::Output; if let Some(ref binding) = result.binding { - has_point_size |= - *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); + has_point_size |= *binding + == crate::Binding::BuiltIn { + built_in: crate::BuiltIn::PointSize, + invariant: false, + }; let type_id = self.get_type_id(LookupType::Handle(result.ty)); let varying_id = self.write_varying(ir_module, class, None, result.ty, binding)?; @@ -416,8 +419,11 @@ impl Writer { let type_id = self.get_type_id(LookupType::Handle(member.ty)); let name = member.name.as_ref().map(AsRef::as_ref); let binding = member.binding.as_ref().unwrap(); - has_point_size |= - *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); + has_point_size |= *binding + == crate::Binding::BuiltIn { + built_in: crate::BuiltIn::PointSize, + invariant: false, + }; let varying_id = self.write_varying(ir_module, class, name, member.ty, binding)?; iface.varying_ids.push(varying_id); @@ -1174,7 +1180,10 @@ impl Writer { } } } - crate::Binding::BuiltIn(built_in) => { + crate::Binding::BuiltIn { + built_in, + invariant, + } => { use crate::BuiltIn as Bi; let built_in = match built_in { Bi::Position => { @@ -1225,6 +1234,10 @@ impl Writer { }; self.decorate(id, Decoration::BuiltIn, &[built_in as u32]); + + if invariant { + self.decorate(id, Decoration::Invariant, &[]); + } } } @@ -1352,7 +1365,13 @@ impl Writer { crate::TypeInner::Struct { ref members, .. } => members.iter().any(|member| { has_view_index_check(ir_module, member.binding.as_ref(), member.ty) }), - _ => binding == Some(&crate::Binding::BuiltIn(crate::BuiltIn::ViewIndex)), + _ => { + binding + == Some(&crate::Binding::BuiltIn { + built_in: crate::BuiltIn::ViewIndex, + invariant: false, + }) + } } } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 57779e42f..1b0366572 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -14,6 +14,7 @@ enum Attribute { Binding(u32), BuiltIn(crate::BuiltIn), Group(u32), + Invariant, Interpolate(Option, Option), Location(u32), Stage(ShaderStage), @@ -357,6 +358,7 @@ impl Writer { } Attribute::Binding(id) => write!(self.out, "@binding({}) ", id)?, Attribute::Group(id) => write!(self.out, "@group({}) ", id)?, + Attribute::Invariant => write!(self.out, "@invariant ")?, Attribute::Interpolate(interpolation, sampling) => { if sampling.is_some() && sampling != Some(crate::Sampling::Center) { write!( @@ -400,9 +402,9 @@ impl Writer { writeln!(self.out)?; for (index, member) in members.iter().enumerate() { // Skip struct member with unsupported built in - if let Some(crate::Binding::BuiltIn(builtin)) = member.binding { - if builtin_str(builtin).is_none() { - log::warn!("Skip member with unsupported builtin {:?}", builtin); + if let Some(crate::Binding::BuiltIn { built_in, .. }) = member.binding { + if builtin_str(built_in).is_none() { + log::warn!("Skip member with unsupported builtin {:?}", built_in); continue; } } @@ -1745,13 +1747,13 @@ impl Writer { // Write the comma separated constants for (index, constant) in components.iter().enumerate() { - if let Some(&crate::Binding::BuiltIn(builtin)) = + if let Some(&crate::Binding::BuiltIn { built_in, .. }) = members.and_then(|members| members.get(index)?.binding.as_ref()) { - if builtin_str(builtin).is_none() { + if builtin_str(built_in).is_none() { log::warn!( "Skip constant for struct member with unsupported builtin {:?}", - builtin + built_in ); continue; } @@ -1975,7 +1977,16 @@ fn map_binding_to_attribute( scalar_kind: Option, ) -> Vec { match *binding { - crate::Binding::BuiltIn(built_in) => vec![Attribute::BuiltIn(built_in)], + crate::Binding::BuiltIn { + built_in, + invariant, + } => { + if invariant { + vec![Attribute::BuiltIn(built_in), Attribute::Invariant] + } else { + vec![Attribute::BuiltIn(built_in)] + } + } crate::Binding::Location { location, interpolation, @@ -2006,9 +2017,10 @@ fn access_to_unsupported_builtin( { // Let's check that we try to access a struct member with unsupported built-in and skip it. if let TypeInner::Struct { ref members, .. } = module.types[pointer_base_handle].inner { - if let Some(crate::Binding::BuiltIn(builtin)) = members[index as usize].binding { - if builtin_str(builtin).is_none() { - log::warn!("Skip component with unsupported builtin {:?}", builtin); + if let Some(crate::Binding::BuiltIn { built_in, .. }) = members[index as usize].binding + { + if builtin_str(built_in).is_none() { + log::warn!("Skip component with unsupported builtin {:?}", built_in); return true; } } diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 95faed6e7..81314676e 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -174,6 +174,7 @@ pub enum QualifierValue { pub struct TypeQualifiers<'a> { pub span: Span, pub storage: (StorageQualifier, Span), + pub invariant: Option, pub interpolation: Option<(Interpolation, Span)>, pub precision: Option<(Precision, Span)>, pub sampling: Option<(Sampling, Span)>, @@ -186,6 +187,15 @@ pub struct TypeQualifiers<'a> { impl<'a> TypeQualifiers<'a> { /// Appends `errors` with errors for all unused qualifiers pub fn unused_errors(&self, errors: &mut Vec) { + if let Some(meta) = self.invariant { + errors.push(super::Error { + kind: super::ErrorKind::SemanticError( + "Invariant qualifier can only be used in in/out variables".into(), + ), + meta, + }); + } + if let Some((_, meta)) = self.interpolation { errors.push(super::Error { kind: super::ErrorKind::SemanticError( diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs index e3fac8ccc..1b59a9bf3 100644 --- a/src/front/glsl/lex.rs +++ b/src/front/glsl/lex.rs @@ -72,6 +72,7 @@ impl<'a> Iterator for Lexer<'a> { "uniform" => TokenValue::Uniform, "buffer" => TokenValue::Buffer, "shared" => TokenValue::Shared, + "invariant" => TokenValue::Invariant, "flat" => TokenValue::Interpolation(crate::Interpolation::Flat), "noperspective" => TokenValue::Interpolation(crate::Interpolation::Linear), "smooth" => TokenValue::Interpolation(crate::Interpolation::Perspective), diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index d39245d8d..d484c48f1 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -361,6 +361,14 @@ impl<'source> ParsingContext<'source> { ) .map(Some) } else { + if qualifiers.invariant.take().is_some() { + parser.make_variable_invariant(ctx, body, &ty_name, token.meta); + + qualifiers.unused_errors(&mut parser.errors); + self.expect(parser, TokenValue::Semicolon)?; + return Ok(Some(qualifiers.span)); + } + //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index acf0df484..0a1c6c2b1 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -140,7 +140,8 @@ impl<'source> ParsingContext<'source> { pub fn peek_type_qualifier(&mut self, parser: &mut Parser) -> bool { self.peek(parser).map_or(false, |t| match t.value { - TokenValue::Interpolation(_) + TokenValue::Invariant + | TokenValue::Interpolation(_) | TokenValue::Sampling(_) | TokenValue::PrecisionQualifier(_) | TokenValue::Const @@ -171,6 +172,19 @@ impl<'source> ParsingContext<'source> { qualifiers.span.subsume(token.meta); match token.value { + TokenValue::Invariant => { + if qualifiers.invariant.is_some() { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "Cannot use more than one invariant qualifier per declaration" + .into(), + ), + meta: token.meta, + }) + } + + qualifiers.invariant = Some(token.meta); + } TokenValue::Interpolation(i) => { if qualifiers.interpolation.is_some() { parser.errors.push(Error { @@ -235,7 +249,7 @@ impl<'source> ParsingContext<'source> { qualifiers.sampling = Some((s, token.meta)); } TokenValue::PrecisionQualifier(p) => { - if qualifiers.interpolation.is_some() { + if qualifiers.precision.is_some() { parser.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one precision qualifier per declaration" diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs index ff185e016..74f10cbf8 100644 --- a/src/front/glsl/token.rs +++ b/src/front/glsl/token.rs @@ -44,6 +44,7 @@ pub enum TokenValue { /// (for example `writeonly` has an associated value of [`crate::StorageAccess::STORE`]) MemoryQualifier(crate::StorageAccess), + Invariant, Interpolation(Interpolation), Sampling(Sampling), Precision, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 4b69abc05..02995e2bb 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -67,7 +67,10 @@ impl Parser { let idx = self.entry_args.len(); self.entry_args.push(EntryArg { name: None, - binding: Binding::BuiltIn(data.builtin), + binding: Binding::BuiltIn { + built_in: data.builtin, + invariant: false, + }, handle, storage: data.storage, }); @@ -228,6 +231,25 @@ impl Parser { self.add_builtin(ctx, body, name, data, meta) } + pub(crate) fn make_variable_invariant( + &mut self, + ctx: &mut Context, + body: &mut Block, + name: &str, + meta: Span, + ) { + if let Some(var) = self.lookup_variable(ctx, body, name, meta) { + if let Some(index) = var.entry_arg { + if let Binding::BuiltIn { built_in, .. } = self.entry_args[index].binding { + self.entry_args[index].binding = Binding::BuiltIn { + built_in, + invariant: built_in == BuiltIn::Position, + }; + } + } + } + } + pub(crate) fn field_selection( &mut self, ctx: &mut Context, diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index efc785304..b8e6c6615 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -377,9 +377,9 @@ impl> super::Parser { } => { for (index, sm) in sub_members.iter().enumerate() { match sm.binding { - Some(crate::Binding::BuiltIn(builtin)) => { + Some(crate::Binding::BuiltIn { built_in, .. }) => { // Cull unused builtins to preserve performances - if !self.builtin_usage.contains(&builtin) { + if !self.builtin_usage.contains(&built_in) { continue; } } @@ -414,9 +414,10 @@ impl> super::Parser { for (member_index, member) in members.iter().enumerate() { match member.binding { - Some(crate::Binding::BuiltIn(crate::BuiltIn::Position)) - if self.options.adjust_coordinate_space => - { + Some(crate::Binding::BuiltIn { + built_in: crate::BuiltIn::Position, + .. + }) if self.options.adjust_coordinate_space => { let mut emitter = Emitter::default(); emitter.start(&function.expressions); let global_expr = components[member_index]; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 95e8a7487..03235661e 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -203,6 +203,7 @@ struct Decoration { array_stride: Option, matrix_stride: Option, matrix_major: Option, + invariant: bool, interpolation: Option, sampling: Option, flags: DecorationFlags, @@ -232,8 +233,12 @@ impl Decoration { Decoration { built_in: Some(built_in), location: None, + invariant, .. - } => map_builtin(built_in).map(crate::Binding::BuiltIn), + } => map_builtin(built_in).map(|built_in| crate::Binding::BuiltIn { + built_in, + invariant: invariant && built_in == crate::BuiltIn::Position, + }), Decoration { built_in: None, location: Some(location), @@ -681,6 +686,9 @@ impl> Parser { inst.expect(base_words + 2)?; dec.matrix_stride = NonZeroU32::new(self.next()?); } + spirv::Decoration::Invariant => { + dec.invariant = true; + } spirv::Decoration::NoPerspective => { dec.interpolation = Some(crate::Interpolation::Linear); } @@ -1467,10 +1475,10 @@ impl> Parser { span, ); - if let Some(crate::Binding::BuiltIn(builtin)) = + if let Some(crate::Binding::BuiltIn { built_in, .. }) = members[index as usize].binding { - self.builtin_usage.insert(builtin); + self.builtin_usage.insert(built_in); } AccessExpression { @@ -4642,7 +4650,7 @@ impl> Parser { ExtendedClass::Input => { let mut binding = dec.io_binding()?; let mut unsigned_ty = effective_ty; - if let crate::Binding::BuiltIn(built_in) = binding { + if let crate::Binding::BuiltIn { built_in, .. } = binding { let needs_inner_uint = match built_in { crate::BuiltIn::BaseInstance | crate::BuiltIn::BaseVertex @@ -4695,7 +4703,7 @@ impl> Parser { // For output interface blocks, this would be a structure. let mut binding = dec.io_binding().ok(); let init = match binding { - Some(crate::Binding::BuiltIn(built_in)) => { + Some(crate::Binding::BuiltIn { built_in, .. }) => { match null::generate_default_built_in( Some(built_in), effective_ty, @@ -4718,7 +4726,9 @@ impl> Parser { .iter() .map(|member| { let built_in = match member.binding { - Some(crate::Binding::BuiltIn(built_in)) => Some(built_in), + Some(crate::Binding::BuiltIn { built_in, .. }) => { + Some(built_in) + } _ => None, }; (built_in, member.ty) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index e73faf68b..a41f21733 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1196,6 +1196,7 @@ struct BindingParser { built_in: Option, interpolation: Option, sampling: Option, + invariant: bool, } impl BindingParser { @@ -1227,6 +1228,7 @@ impl BindingParser { } lexer.expect(Token::Paren(')'))?; } + "invariant" => self.invariant = true, _ => return Err(Error::UnknownAttribute(name_span)), } Ok(()) @@ -1238,9 +1240,10 @@ impl BindingParser { self.built_in, self.interpolation, self.sampling, + self.invariant, ) { - (None, None, None, None) => Ok(None), - (Some(location), None, interpolation, sampling) => { + (None, None, None, None, false) => Ok(None), + (Some(location), None, interpolation, sampling, false) => { // Before handing over the completed `Module`, we call // `apply_default_interpolation` to ensure that the interpolation and // sampling have been explicitly specified on all vertex shader output and fragment @@ -1251,8 +1254,17 @@ impl BindingParser { sampling, })) } - (None, Some(bi), None, None) => Ok(Some(crate::Binding::BuiltIn(bi))), - (_, _, _, _) => Err(Error::InconsistentBinding(span)), + (None, Some(crate::BuiltIn::Position), None, None, true) => { + Ok(Some(crate::Binding::BuiltIn { + built_in: crate::BuiltIn::Position, + invariant: true, + })) + } + (None, Some(built_in), None, None, false) => Ok(Some(crate::Binding::BuiltIn { + built_in, + invariant: false, + })), + (_, _, _, _, _) => Err(Error::InconsistentBinding(span)), } } } diff --git a/src/lib.rs b/src/lib.rs index 9873d2330..a90673895 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -748,7 +748,11 @@ pub enum ConstantInner { #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Binding { /// Built-in shader variable. - BuiltIn(BuiltIn), + BuiltIn { + built_in: BuiltIn, + /// can only be `true` for [`BuiltIn::Position`] + invariant: bool, + }, /// Indexed location. /// diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 15cc3a7fc..4e11a24e1 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -390,7 +390,7 @@ impl crate::Constant { impl crate::Binding { pub fn to_built_in(&self) -> Option { match *self { - Self::BuiltIn(bi) => Some(bi), + crate::Binding::BuiltIn { built_in, .. } => Some(built_in), Self::Location { .. } => None, } } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 28a0f8a8a..7a31c3260 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -455,7 +455,7 @@ impl FunctionInfo { E::FunctionArgument(index) => { let arg = &resolve_context.arguments[index as usize]; let uniform = match arg.binding { - Some(crate::Binding::BuiltIn(built_in)) => match built_in { + Some(crate::Binding::BuiltIn { built_in, .. }) => match built_in { // per-polygon built-ins are uniform crate::BuiltIn::FrontFacing // per-work-group built-ins are uniform diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 9b3393e5e..eb2471a7b 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -115,7 +115,7 @@ impl VaryingContext<'_> { let ty_inner = &self.types[self.ty].inner; match *binding { - crate::Binding::BuiltIn(built_in) => { + crate::Binding::BuiltIn { built_in, .. } => { let bit = 1 << built_in as u32; if self.built_in_mask & bit != 0 { return Err(VaryingError::DuplicateBuiltIn(built_in)); diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index 9cf311023..eeb45b0d7 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -16,6 +16,13 @@ wgsl: ( explicit_types: true, ), + msl: ( + lang_version: (2, 1), + per_stage_map: (), + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + ), msl_pipeline: ( allow_point_size: true, ), diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index 3655ba9b8..812afc51a 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -1,7 +1,7 @@ // Testing various parts of the pipeline interface: locations, built-ins, and entry points struct VertexOutput { - @builtin(position) position: vec4, + @builtin(position) @invariant position: vec4, @location(1) varying: f32, } @@ -55,7 +55,7 @@ struct Input2 { } @stage(vertex) -fn vertex_two_structs(in1: Input1, in2: Input2) -> @builtin(position) vec4 { +fn vertex_two_structs(in1: Input1, in2: Input2) -> @builtin(position) @invariant vec4 { var index = 2u; return vec4(f32(in1.index), f32(in2.index), f32(index), 0.0); } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 37098b4da..8737a5c70 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -6,7 +6,7 @@ struct NagaConstants { ConstantBuffer _NagaConstants: register(b0, space1); struct VertexOutput { - float4 position : SV_Position; + precise float4 position : SV_Position; float varying : LOC1; }; @@ -28,12 +28,12 @@ groupshared uint output[1]; struct VertexOutput_vertex { float varying : LOC1; - float4 position : SV_Position; + precise float4 position : SV_Position; }; struct FragmentInput_fragment { float varying_1 : LOC1; - float4 position_1 : SV_Position; + precise float4 position_1 : SV_Position; bool front_facing_1 : SV_IsFrontFace; uint sample_index_1 : SV_SampleIndex; uint sample_mask_1 : SV_Coverage; @@ -81,7 +81,7 @@ void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThr return; } -float4 vertex_two_structs(Input1_ in1_, Input2_ in2_) : SV_Position +precise float4 vertex_two_structs(Input1_ in1_, Input2_ in2_) : SV_Position { uint index = 2u; diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index b45de9447..e9308f256 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -11,24 +11,24 @@ struct FragmentInput { }; struct VertexOutput_vert_main { - uint flat : LOC0; - float linear_ : LOC1; - float2 linear_centroid : LOC2; - float3 linear_sample : LOC3; + nointerpolation uint flat : LOC0; + noperspective float linear_ : LOC1; + noperspective centroid float2 linear_centroid : LOC2; + noperspective sample float3 linear_sample : LOC3; float4 perspective : LOC4; - float perspective_centroid : LOC5; - float perspective_sample : LOC6; + centroid float perspective_centroid : LOC5; + sample float perspective_sample : LOC6; float4 position : SV_Position; }; struct FragmentInput_frag_main { - uint flat_1 : LOC0; - float linear_1 : LOC1; - float2 linear_centroid_1 : LOC2; - float3 linear_sample_1 : LOC3; + nointerpolation uint flat_1 : LOC0; + noperspective float linear_1 : LOC1; + noperspective centroid float2 linear_centroid_1 : LOC2; + noperspective sample float3 linear_sample_1 : LOC3; float4 perspective_1 : LOC4; - float perspective_centroid_1 : LOC5; - float perspective_sample_1 : LOC6; + centroid float perspective_centroid_1 : LOC5; + sample float perspective_sample_1 : LOC6; float4 position_1 : SV_Position; }; diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 50860b2cb..a4d86445b 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -284,7 +284,10 @@ ( name: Some("global_id"), ty: 4, - binding: Some(BuiltIn(GlobalInvocationId)), + binding: Some(BuiltIn( + built_in: GlobalInvocationId, + invariant: false, + )), ), ], result: None, diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 00789692c..a44d62002 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal2.1 #include #include @@ -27,7 +27,7 @@ struct vertex_Input { uint color [[attribute(10)]]; }; struct vertex_Output { - metal::float4 position [[position]]; + metal::float4 position [[position, invariant]]; float varying [[user(loc1), center_perspective]]; float _point_size [[point_size]]; }; @@ -53,7 +53,7 @@ struct fragment_Output { }; fragment fragment_Output fragment_( fragment_Input varyings_1 [[stage_in]] -, metal::float4 position [[position]] +, metal::float4 position [[position, invariant]] , bool front_facing [[front_facing]] , uint sample_index [[sample_id]] , uint sample_mask [[sample_mask]] @@ -84,7 +84,7 @@ kernel void compute_( struct vertex_two_structsInput { }; struct vertex_two_structsOutput { - metal::float4 member_3 [[position]]; + metal::float4 member_3 [[position, invariant]]; float _point_size [[point_size]]; }; vertex vertex_two_structsOutput vertex_two_structs( diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index b6e2ce5b1..bf8725043 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -16,7 +16,7 @@ struct Data { struct vs_mainInput { }; struct vs_mainOutput { - metal::float4 position [[position, invariant]]; + metal::float4 position [[position]]; metal::float3 uv [[user(loc0), center_perspective]]; }; vertex vs_mainOutput vs_main( diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 60e270e1c..7dc246b00 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -18,6 +18,7 @@ OpDecorate %16 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 OpDecorate %22 BuiltIn FragCoord +OpDecorate %22 Invariant OpDecorate %25 Location 1 OpDecorate %28 BuiltIn FrontFacing OpDecorate %31 BuiltIn SampleId diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index e42d243e9..de082608d 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -19,6 +19,7 @@ OpDecorate %24 BuiltIn InstanceIndex OpDecorate %26 Location 10 OpDecorate %26 Flat OpDecorate %28 BuiltIn Position +OpDecorate %28 Invariant OpDecorate %30 Location 1 OpDecorate %32 BuiltIn PointSize %2 = OpTypeVoid diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index 919bbeef6..ea5313db0 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -17,6 +17,7 @@ OpMemberDecorate %19 0 Offset 0 OpDecorate %24 BuiltIn VertexIndex OpDecorate %28 BuiltIn InstanceIndex OpDecorate %30 BuiltIn Position +OpDecorate %30 Invariant OpDecorate %32 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeFloat 32 diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index d2584caab..fdc2a77ec 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -1,5 +1,5 @@ struct VertexOutput { - @builtin(position) position: vec4, + @builtin(position) @invariant position: vec4, @location(1) varying: f32, } @@ -39,7 +39,7 @@ fn compute(@builtin(global_invocation_id) global_id: vec3, @builtin(local_i } @stage(vertex) -fn vertex_two_structs(in1_: Input1_, in2_: Input2_) -> @builtin(position) vec4 { +fn vertex_two_structs(in1_: Input1_, in2_: Input2_) -> @builtin(position) @invariant vec4 { var index: u32 = 2u; let _e9: u32 = index; From 6ee1fd4929f7f6a8e663a74ddc6b69b653e3ffa1 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 23 Mar 2022 19:09:57 +0100 Subject: [PATCH 1649/2212] fix MSL issue --- src/back/msl/mod.rs | 2 +- tests/out/msl/interface.msl | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 22dba510f..d049b72f4 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -233,7 +233,7 @@ impl Options { Ok(ResolvedBinding::BuiltIn { built_in, - invariant, + invariant: invariant && matches!(mode, LocationMode::FragmentOutput), }) } crate::Binding::Location { diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index a44d62002..17b4e928d 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -27,7 +27,7 @@ struct vertex_Input { uint color [[attribute(10)]]; }; struct vertex_Output { - metal::float4 position [[position, invariant]]; + metal::float4 position [[position]]; float varying [[user(loc1), center_perspective]]; float _point_size [[point_size]]; }; @@ -53,7 +53,7 @@ struct fragment_Output { }; fragment fragment_Output fragment_( fragment_Input varyings_1 [[stage_in]] -, metal::float4 position [[position, invariant]] +, metal::float4 position [[position]] , bool front_facing [[front_facing]] , uint sample_index [[sample_id]] , uint sample_mask [[sample_mask]] @@ -84,7 +84,7 @@ kernel void compute_( struct vertex_two_structsInput { }; struct vertex_two_structsOutput { - metal::float4 member_3 [[position, invariant]]; + metal::float4 member_3 [[position]]; float _point_size [[point_size]]; }; vertex vertex_two_structsOutput vertex_two_structs( From 5ba2d4d07920cce0ab83f019593e9516f3cdd6c4 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 8 Apr 2022 18:02:39 +0200 Subject: [PATCH 1650/2212] [spv-in] error on unsupported matrix stride --- src/front/spv/error.rs | 7 +++++++ src/front/spv/mod.rs | 20 ++++++++------------ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 54109dd85..3877590c4 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -43,6 +43,13 @@ pub enum Error { UnsupportedBinaryOperator(spirv::Word), #[error("Naga supports OpTypeRuntimeArray in the StorageBuffer storage class only")] UnsupportedRuntimeArrayStorageClass, + #[error("unsupported matrix stride {stride} for a {columns}x{rows} matrix with scalar width={width}")] + UnsupportedMatrixStride { + stride: u32, + columns: u8, + rows: u8, + width: u8, + }, #[error("unknown binary operator {0:?}")] UnknownBinaryOperator(spirv::Op), #[error("unknown relational function {0:?}")] diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 03235661e..9c963fa04 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -4208,19 +4208,15 @@ impl> Parser { } = *inner { if let Some(stride) = decor.matrix_stride { - let rounded_rows = if rows > crate::VectorSize::Bi { - 4 - } else { - rows as u32 - }; - if stride.get() != rounded_rows * (width as u32) { - log::warn!( - "Unexpected matrix stride {} for an {}x{} matrix with scalar width={}", - stride.get(), - columns as u8, - rows as u8, + let aligned_rows = if rows > crate::VectorSize::Bi { 4 } else { 2 }; + let expected_stride = aligned_rows * width as u32; + if stride.get() != expected_stride { + return Err(Error::UnsupportedMatrixStride { + stride: stride.get(), + columns: columns as u8, + rows: rows as u8, width, - ); + }); } } } From 7aaac25fbf64c0f77f0e2deba2963293f3632dad Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 11 Apr 2022 07:29:11 +0200 Subject: [PATCH 1651/2212] [hlsl-out] fix matCx2 translation for uniform buffers (#1802) * [hlsl-out] fix matCx2 translation * fix msl validation (warning: unused variable) * fix msl buffer declaration * address comments --- src/back/hlsl/help.rs | 414 ++++++++++++++- src/back/hlsl/mod.rs | 11 + src/back/hlsl/writer.rs | 226 ++++++++- tests/in/access.param.ron | 1 + tests/in/access.wgsl | 37 ++ tests/out/glsl/access.atomics.Compute.glsl | 39 +- tests/out/glsl/access.foo_frag.Fragment.glsl | 7 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 63 ++- tests/out/hlsl/access.hlsl | 131 ++++- tests/out/msl/access.msl | 102 +++- tests/out/spv/access.spvasm | 507 ++++++++++++------- tests/out/wgsl/access.wgsl | 97 +++- 12 files changed, 1344 insertions(+), 291 deletions(-) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 91553a508..c652a1d6e 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -48,6 +48,12 @@ pub(super) struct WrappedConstructor { pub(super) ty: Handle, } +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) struct WrappedStructMatrixAccess { + pub(super) ty: Handle, + pub(super) index: u32, +} + /// HLSL backend requires its own `ImageQuery` enum. /// /// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function. @@ -393,13 +399,39 @@ impl<'a, W: Write> super::Writer<'a, W> { INDENT, struct_name, RETURN_VARIABLE_NAME )?; for i in 0..members.len() as u32 { + let member = &members[i as usize]; + let field_name = &self.names[&NameKey::StructMember(constructor.ty, i)]; - //TODO: handle arrays? - writeln!( - self.out, - "{}{}.{} = {}{};", - INDENT, RETURN_VARIABLE_NAME, field_name, ARGUMENT_VARIABLE_NAME, i, - )?; + + match module.types[member.ty].inner { + crate::TypeInner::Matrix { + columns, + rows: crate::VectorSize::Bi, + .. + } if member.binding.is_none() => { + for j in 0..columns as u8 { + writeln!( + self.out, + "{}{}.{}_{} = {}{}[{}];", + INDENT, + RETURN_VARIABLE_NAME, + field_name, + j, + ARGUMENT_VARIABLE_NAME, + i, + j + )?; + } + } + _ => { + //TODO: handle arrays? + writeln!( + self.out, + "{}{}.{} = {}{};", + INDENT, RETURN_VARIABLE_NAME, field_name, ARGUMENT_VARIABLE_NAME, i, + )?; + } + } } // Write return value @@ -413,6 +445,335 @@ impl<'a, W: Write> super::Writer<'a, W> { Ok(()) } + pub(super) fn write_wrapped_struct_matrix_get_function_name( + &mut self, + access: WrappedStructMatrixAccess, + ) -> BackendResult { + let name = &self.names[&NameKey::Type(access.ty)]; + let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; + write!(self.out, "GetMat{}On{}", field_name, name)?; + Ok(()) + } + + /// Writes a function used to get a matCx2 from within a structure. + pub(super) fn write_wrapped_struct_matrix_get_function( + &mut self, + module: &crate::Module, + access: WrappedStructMatrixAccess, + ) -> BackendResult { + use crate::back::INDENT; + + const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj"; + + // Write function return type and name + let member = match module.types[access.ty].inner { + crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], + _ => unreachable!(), + }; + let ret_ty = &module.types[member.ty].inner; + self.write_value_type(module, ret_ty)?; + write!(self.out, " ")?; + self.write_wrapped_struct_matrix_get_function_name(access)?; + + // Write function parameters + write!(self.out, "(")?; + let struct_name = &self.names[&NameKey::Type(access.ty)]; + write!( + self.out, + "{} {}", + struct_name, STRUCT_ARGUMENT_VARIABLE_NAME + )?; + + // Write function body + writeln!(self.out, ") {{")?; + + // Write return value + write!(self.out, "{}return ", INDENT)?; + self.write_value_type(module, ret_ty)?; + write!(self.out, "(")?; + let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; + match module.types[member.ty].inner { + crate::TypeInner::Matrix { columns, .. } => { + for i in 0..columns as u8 { + if i != 0 { + write!(self.out, ", ")?; + } + write!( + self.out, + "{}.{}_{}", + STRUCT_ARGUMENT_VARIABLE_NAME, field_name, i + )?; + } + } + _ => unreachable!(), + } + writeln!(self.out, ");")?; + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + + Ok(()) + } + + pub(super) fn write_wrapped_struct_matrix_set_function_name( + &mut self, + access: WrappedStructMatrixAccess, + ) -> BackendResult { + let name = &self.names[&NameKey::Type(access.ty)]; + let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; + write!(self.out, "SetMat{}On{}", field_name, name)?; + Ok(()) + } + + /// Writes a function used to set a matCx2 from within a structure. + pub(super) fn write_wrapped_struct_matrix_set_function( + &mut self, + module: &crate::Module, + access: WrappedStructMatrixAccess, + ) -> BackendResult { + use crate::back::INDENT; + + const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj"; + const MATRIX_ARGUMENT_VARIABLE_NAME: &str = "mat"; + + // Write function return type and name + write!(self.out, "void ")?; + self.write_wrapped_struct_matrix_set_function_name(access)?; + + // Write function parameters + write!(self.out, "(")?; + let struct_name = &self.names[&NameKey::Type(access.ty)]; + write!( + self.out, + "{} {}, ", + struct_name, STRUCT_ARGUMENT_VARIABLE_NAME + )?; + let member = match module.types[access.ty].inner { + crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], + _ => unreachable!(), + }; + self.write_type(module, member.ty)?; + write!(self.out, " {}", MATRIX_ARGUMENT_VARIABLE_NAME)?; + // Write function body + writeln!(self.out, ") {{")?; + + let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; + + match module.types[member.ty].inner { + crate::TypeInner::Matrix { columns, .. } => { + for i in 0..columns as u8 { + writeln!( + self.out, + "{}{}.{}_{} = {}[{}];", + INDENT, + STRUCT_ARGUMENT_VARIABLE_NAME, + field_name, + i, + MATRIX_ARGUMENT_VARIABLE_NAME, + i + )?; + } + } + _ => unreachable!(), + } + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + + Ok(()) + } + + pub(super) fn write_wrapped_struct_matrix_set_vec_function_name( + &mut self, + access: WrappedStructMatrixAccess, + ) -> BackendResult { + let name = &self.names[&NameKey::Type(access.ty)]; + let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; + write!(self.out, "SetMatVec{}On{}", field_name, name)?; + Ok(()) + } + + /// Writes a function used to set a vec2 on a matCx2 from within a structure. + pub(super) fn write_wrapped_struct_matrix_set_vec_function( + &mut self, + module: &crate::Module, + access: WrappedStructMatrixAccess, + ) -> BackendResult { + use crate::back::INDENT; + + const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj"; + const VECTOR_ARGUMENT_VARIABLE_NAME: &str = "vec"; + const MATRIX_INDEX_ARGUMENT_VARIABLE_NAME: &str = "mat_idx"; + + // Write function return type and name + write!(self.out, "void ")?; + self.write_wrapped_struct_matrix_set_vec_function_name(access)?; + + // Write function parameters + write!(self.out, "(")?; + let struct_name = &self.names[&NameKey::Type(access.ty)]; + write!( + self.out, + "{} {}, ", + struct_name, STRUCT_ARGUMENT_VARIABLE_NAME + )?; + let member = match module.types[access.ty].inner { + crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], + _ => unreachable!(), + }; + let vec_ty = match module.types[member.ty].inner { + crate::TypeInner::Matrix { rows, width, .. } => crate::TypeInner::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }, + _ => unreachable!(), + }; + self.write_value_type(module, &vec_ty)?; + write!( + self.out, + " {}, uint {}", + VECTOR_ARGUMENT_VARIABLE_NAME, MATRIX_INDEX_ARGUMENT_VARIABLE_NAME + )?; + + // Write function body + writeln!(self.out, ") {{")?; + + writeln!( + self.out, + "{}switch({}) {{", + INDENT, MATRIX_INDEX_ARGUMENT_VARIABLE_NAME + )?; + + let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; + + match module.types[member.ty].inner { + crate::TypeInner::Matrix { columns, .. } => { + for i in 0..columns as u8 { + writeln!( + self.out, + "{}case {}: {}.{}_{} = {};", + INDENT, + i, + STRUCT_ARGUMENT_VARIABLE_NAME, + field_name, + i, + VECTOR_ARGUMENT_VARIABLE_NAME + )?; + } + } + _ => unreachable!(), + } + + writeln!(self.out, "{}}}", INDENT)?; + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + + Ok(()) + } + + pub(super) fn write_wrapped_struct_matrix_set_scalar_function_name( + &mut self, + access: WrappedStructMatrixAccess, + ) -> BackendResult { + let name = &self.names[&NameKey::Type(access.ty)]; + let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; + write!(self.out, "SetMatScalar{}On{}", field_name, name)?; + Ok(()) + } + + /// Writes a function used to set a float on a matCx2 from within a structure. + pub(super) fn write_wrapped_struct_matrix_set_scalar_function( + &mut self, + module: &crate::Module, + access: WrappedStructMatrixAccess, + ) -> BackendResult { + use crate::back::INDENT; + + const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj"; + const SCALAR_ARGUMENT_VARIABLE_NAME: &str = "scalar"; + const MATRIX_INDEX_ARGUMENT_VARIABLE_NAME: &str = "mat_idx"; + const VECTOR_INDEX_ARGUMENT_VARIABLE_NAME: &str = "vec_idx"; + + // Write function return type and name + write!(self.out, "void ")?; + self.write_wrapped_struct_matrix_set_scalar_function_name(access)?; + + // Write function parameters + write!(self.out, "(")?; + let struct_name = &self.names[&NameKey::Type(access.ty)]; + write!( + self.out, + "{} {}, ", + struct_name, STRUCT_ARGUMENT_VARIABLE_NAME + )?; + let member = match module.types[access.ty].inner { + crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], + _ => unreachable!(), + }; + let scalar_ty = match module.types[member.ty].inner { + crate::TypeInner::Matrix { width, .. } => crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width, + }, + _ => unreachable!(), + }; + self.write_value_type(module, &scalar_ty)?; + write!( + self.out, + " {}, uint {}, uint {}", + SCALAR_ARGUMENT_VARIABLE_NAME, + MATRIX_INDEX_ARGUMENT_VARIABLE_NAME, + VECTOR_INDEX_ARGUMENT_VARIABLE_NAME + )?; + + // Write function body + writeln!(self.out, ") {{")?; + + writeln!( + self.out, + "{}switch({}) {{", + INDENT, MATRIX_INDEX_ARGUMENT_VARIABLE_NAME + )?; + + let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; + + match module.types[member.ty].inner { + crate::TypeInner::Matrix { columns, .. } => { + for i in 0..columns as u8 { + writeln!( + self.out, + "{}case {}: {}.{}_{}[{}] = {};", + INDENT, + i, + STRUCT_ARGUMENT_VARIABLE_NAME, + field_name, + i, + VECTOR_INDEX_ARGUMENT_VARIABLE_NAME, + SCALAR_ARGUMENT_VARIABLE_NAME + )?; + } + } + _ => unreachable!(), + } + + writeln!(self.out, "{}}}", INDENT)?; + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + + Ok(()) + } + /// Helper function that write wrapped function for `Expression::ImageQuery` and `Expression::ArrayLength` /// /// @@ -478,6 +839,47 @@ impl<'a, W: Write> super::Writer<'a, W> { self.wrapped.constructors.insert(constructor); } } + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s + // (see top level module docs for details). + // + // The functions injected here are required to get the matrix accesses working. + crate::Expression::AccessIndex { base, index } => { + let base_ty_res = &func_ctx.info[base].ty; + let mut resolved = base_ty_res.inner_with(&module.types); + let base_ty_handle = match *resolved { + crate::TypeInner::Pointer { base, .. } => { + resolved = &module.types[base].inner; + Some(base) + } + _ => base_ty_res.handle(), + }; + if let crate::TypeInner::Struct { ref members, .. } = *resolved { + let member = &members[index as usize]; + + match module.types[member.ty].inner { + crate::TypeInner::Matrix { + rows: crate::VectorSize::Bi, + .. + } if member.binding.is_none() => { + let ty = base_ty_handle.unwrap(); + let access = WrappedStructMatrixAccess { ty, index }; + + if !self.wrapped.struct_matrix_access.contains(&access) { + self.write_wrapped_struct_matrix_get_function(module, access)?; + self.write_wrapped_struct_matrix_set_function(module, access)?; + self.write_wrapped_struct_matrix_set_vec_function( + module, access, + )?; + self.write_wrapped_struct_matrix_set_scalar_function( + module, access, + )?; + self.wrapped.struct_matrix_access.insert(access); + } + } + _ => {} + } + } + } _ => {} }; } diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 8f3134bb1..3ab88409f 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -6,6 +6,8 @@ Backend for [HLSL][hlsl] (High-Level Shading Language). - 5.1 - 6.0 +# General Matrix Note + All matrix construction/deconstruction is row based in HLSL. This means that when we construct a matrix from column vectors, our matrix will be implicitly transposed. The inverse transposition happens when we call `[0]` to get the zeroth column vector. @@ -19,6 +21,13 @@ To deal with this, we add `row_major` to all declarations of matrices in Uniform Finally because all of our matrices are transposed, if you use `mat3x4`, it'll become `float3x4` in HLSL (HLSL has inverted col/row notation). +# Matrix struct member of the form `matCx2` Note + +Struct member matrices of the form `matCx2` are translated to a sequence of C `vec2`s due to +differences in alignment between WGSL and HLSL for uniform buffers. + +Accesses to these matrices are handled by injected functions. + [hlsl]: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl */ @@ -169,6 +178,7 @@ struct Wrapped { array_lengths: crate::FastHashSet, image_queries: crate::FastHashSet, constructors: crate::FastHashSet, + struct_matrix_access: crate::FastHashSet, } impl Wrapped { @@ -176,6 +186,7 @@ impl Wrapped { self.array_lengths.clear(); self.image_queries.clear(); self.constructors.clear(); + self.struct_matrix_access.clear(); } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 5516f94a2..b514d1155 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1,5 +1,5 @@ use super::{ - help::{WrappedArrayLength, WrappedConstructor, WrappedImageQuery}, + help::{WrappedArrayLength, WrappedConstructor, WrappedImageQuery, WrappedStructMatrixAccess}, storage::StoreValue, BackendResult, Error, Options, }; @@ -784,6 +784,28 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write [size] self.write_array_size(module, size)?; } + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s + // (see top level module docs for details). + TypeInner::Matrix { + rows, + columns, + width, + } if member.binding.is_none() && rows == crate::VectorSize::Bi => { + let vec_ty = crate::TypeInner::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }; + let field_name_key = NameKey::StructMember(handle, index as u32); + + for i in 0..columns as u8 { + if i != 0 { + write!(self.out, "; ")?; + } + self.write_value_type(module, &vec_ty)?; + write!(self.out, " {}_{}", &self.names[&field_name_key], i)?; + } + } _ => { // Write modifier before type if let Some(ref binding) = member.binding { @@ -1253,11 +1275,175 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, "[_i] = _result[_i];")?; writeln!(self.out, "{}}}", level)?; } else { + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s + // (see top level module docs for details). + // + // We handle matrix Stores here directly (including sub accesses for Vectors and Scalars). + // Loads are handled by `Expression::AccessIndex` (since sub accesses work fine for Loads). + struct MatrixAccess { + base: Handle, + index: u32, + } + enum Index { + Expression(Handle), + Static(u32), + } + + let get_members = |expr: Handle| { + let base_ty_res = &func_ctx.info[expr].ty; + let resolved = base_ty_res.inner_with(&module.types); + match *resolved { + TypeInner::Pointer { base, .. } => match module.types[base].inner { + TypeInner::Struct { ref members, .. } => Some(members), + _ => None, + }, + _ => None, + } + }; + + let mut matrix = None; + let mut vector = None; + let mut scalar = None; + + let mut current_expr = pointer; + for _ in 0..3 { + let resolved = func_ctx.info[current_expr].ty.inner_with(&module.types); + + match (resolved, &func_ctx.expressions[current_expr]) { + ( + &TypeInner::Pointer { base: ty, .. }, + &crate::Expression::AccessIndex { base, index }, + ) if matches!( + module.types[ty].inner, + TypeInner::Matrix { + rows: crate::VectorSize::Bi, + .. + } + ) && get_members(base) + .map(|members| members[index as usize].binding.is_none()) + == Some(true) => + { + matrix = Some(MatrixAccess { base, index }); + break; + } + ( + &TypeInner::ValuePointer { + size: Some(crate::VectorSize::Bi), + .. + }, + &crate::Expression::Access { base, index }, + ) => { + vector = Some(Index::Expression(index)); + current_expr = base; + } + ( + &TypeInner::ValuePointer { + size: Some(crate::VectorSize::Bi), + .. + }, + &crate::Expression::AccessIndex { base, index }, + ) => { + vector = Some(Index::Static(index)); + current_expr = base; + } + ( + &TypeInner::ValuePointer { size: None, .. }, + &crate::Expression::Access { base, index }, + ) => { + scalar = Some(Index::Expression(index)); + current_expr = base; + } + ( + &TypeInner::ValuePointer { size: None, .. }, + &crate::Expression::AccessIndex { base, index }, + ) => { + scalar = Some(Index::Static(index)); + current_expr = base; + } + _ => break, + } + } + write!(self.out, "{}", level)?; - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, " = ")?; - self.write_expr(module, value, func_ctx)?; - writeln!(self.out, ";")? + + if let Some(MatrixAccess { index, base }) = matrix { + let base_ty_res = &func_ctx.info[base].ty; + let resolved = base_ty_res.inner_with(&module.types); + let ty = match *resolved { + TypeInner::Pointer { base, .. } => base, + _ => base_ty_res.handle().unwrap(), + }; + + if let Some(Index::Static(vec_index)) = vector { + self.write_expr(module, base, func_ctx)?; + write!( + self.out, + ".{}_{}", + &self.names[&NameKey::StructMember(ty, index)], + vec_index + )?; + + if let Some(scalar_index) = scalar { + write!(self.out, "[")?; + match scalar_index { + Index::Static(index) => { + write!(self.out, "{}", index)?; + } + Index::Expression(index) => { + self.write_expr(module, index, func_ctx)?; + } + } + write!(self.out, "]")?; + } + + write!(self.out, " = ")?; + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ";")?; + } else { + let access = WrappedStructMatrixAccess { ty, index }; + match (&vector, &scalar) { + (&Some(_), &Some(_)) => { + self.write_wrapped_struct_matrix_set_scalar_function_name( + access, + )?; + } + (&Some(_), &None) => { + self.write_wrapped_struct_matrix_set_vec_function_name(access)?; + } + (&None, _) => { + self.write_wrapped_struct_matrix_set_function_name(access)?; + } + } + + write!(self.out, "(")?; + self.write_expr(module, base, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + + if let Some(Index::Expression(vec_index)) = vector { + write!(self.out, ", ")?; + self.write_expr(module, vec_index, func_ctx)?; + + if let Some(scalar_index) = scalar { + write!(self.out, ", ")?; + match scalar_index { + Index::Static(index) => { + write!(self.out, "{}", index)?; + } + Index::Expression(index) => { + self.write_expr(module, index, func_ctx)?; + } + } + } + } + writeln!(self.out, ");")?; + } + } else { + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, " = ")?; + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ";")? + } } } Statement::Loop { @@ -1592,8 +1778,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { { // do nothing, the chain is written on `Load`/`Store` } else { - self.write_expr(module, base, func_ctx)?; - let base_ty_res = &func_ctx.info[base].ty; let mut resolved = base_ty_res.inner_with(&module.types); let base_ty_handle = match *resolved { @@ -1604,6 +1788,34 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { _ => base_ty_res.handle(), }; + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s + // (see top level module docs for details). + // + // We handle matrix reconstruction here for Loads. + // Stores are handled directly by `Statement::Store`. + if let TypeInner::Struct { ref members, .. } = *resolved { + let member = &members[index as usize]; + + match module.types[member.ty].inner { + TypeInner::Matrix { + rows: crate::VectorSize::Bi, + .. + } if member.binding.is_none() => { + let ty = base_ty_handle.unwrap(); + self.write_wrapped_struct_matrix_get_function_name( + WrappedStructMatrixAccess { ty, index }, + )?; + write!(self.out, "(")?; + self.write_expr(module, base, func_ctx)?; + write!(self.out, ")")?; + return Ok(()); + } + _ => {} + } + }; + + self.write_expr(module, base, func_ctx)?; + match *resolved { TypeInner::Vector { .. } => { // Write vector access as a swizzle diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 84595754e..57cb7a632 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -10,6 +10,7 @@ vs: ( resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: false), + (group: 0, binding: 1): (buffer: Some(1), mutable: false), }, sizes_buffer: Some(24), ), diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 5ba29d90d..a034fdda7 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -15,6 +15,41 @@ struct Bar { @group(0) @binding(0) var bar: Bar; +struct Baz { + m: mat3x2, +} + +@group(0) @binding(1) +var baz: Baz; + +fn test_matrix_within_struct_accesses() { + var idx = 9; + + idx--; + + // loads + var _ = baz.m; + var _ = baz.m[0]; + var _ = baz.m[idx]; + var _ = baz.m[0][1]; + var _ = baz.m[0][idx]; + var _ = baz.m[idx][1]; + var _ = baz.m[idx][idx]; + + var t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); + + idx++; + + // stores + t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); + t.m[0] = vec2(9.0); + t.m[idx] = vec2(90.0); + t.m[0][1] = 10.0; + t.m[0][idx] = 20.0; + t.m[idx][1] = 30.0; + t.m[idx][idx] = 40.0; +} + fn read_from_private(foo: ptr) -> f32 { return *foo; } @@ -26,6 +61,8 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let baz: f32 = foo; foo = 1.0; + test_matrix_within_struct_accesses(); + // test storage loads let matrix = bar.matrix; let arr = bar.arr; diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 5edd19fea..ff67b1b98 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -8,6 +8,9 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; struct AlignedWrapper { int value; }; +struct Baz { + mat3x2 m; +}; layout(std430) buffer Bar_block_0Compute { mat4x3 matrix; mat2x2 matrix_array[2]; @@ -18,29 +21,29 @@ layout(std430) buffer Bar_block_0Compute { float read_from_private(inout float foo_1) { - float _e2 = foo_1; - return _e2; + float _e3 = foo_1; + return _e3; } void main() { int tmp = 0; int value = _group_0_binding_0_cs.atom; - int _e6 = atomicAdd(_group_0_binding_0_cs.atom, 5); - tmp = _e6; - int _e9 = atomicAdd(_group_0_binding_0_cs.atom, -5); - tmp = _e9; - int _e12 = atomicAnd(_group_0_binding_0_cs.atom, 5); - tmp = _e12; - int _e15 = atomicOr(_group_0_binding_0_cs.atom, 5); - tmp = _e15; - int _e18 = atomicXor(_group_0_binding_0_cs.atom, 5); - tmp = _e18; - int _e21 = atomicMin(_group_0_binding_0_cs.atom, 5); - tmp = _e21; - int _e24 = atomicMax(_group_0_binding_0_cs.atom, 5); - tmp = _e24; - int _e27 = atomicExchange(_group_0_binding_0_cs.atom, 5); - tmp = _e27; + int _e7 = atomicAdd(_group_0_binding_0_cs.atom, 5); + tmp = _e7; + int _e10 = atomicAdd(_group_0_binding_0_cs.atom, -5); + tmp = _e10; + int _e13 = atomicAnd(_group_0_binding_0_cs.atom, 5); + tmp = _e13; + int _e16 = atomicOr(_group_0_binding_0_cs.atom, 5); + tmp = _e16; + int _e19 = atomicXor(_group_0_binding_0_cs.atom, 5); + tmp = _e19; + int _e22 = atomicMin(_group_0_binding_0_cs.atom, 5); + tmp = _e22; + int _e25 = atomicMax(_group_0_binding_0_cs.atom, 5); + tmp = _e25; + int _e28 = atomicExchange(_group_0_binding_0_cs.atom, 5); + tmp = _e28; _group_0_binding_0_cs.atom = value; return; } diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index 63b40b7ab..b7c62d40e 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -6,6 +6,9 @@ precision highp int; struct AlignedWrapper { int value; }; +struct Baz { + mat3x2 m; +}; layout(std430) buffer Bar_block_0Fragment { mat4x3 matrix; mat2x2 matrix_array[2]; @@ -17,8 +20,8 @@ layout(std430) buffer Bar_block_0Fragment { layout(location = 0) out vec4 _fs2p_location0; float read_from_private(inout float foo_1) { - float _e2 = foo_1; - return _e2; + float _e3 = foo_1; + return _e3; } void main() { diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index f1fb3e09a..b01479c24 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -6,6 +6,9 @@ precision highp int; struct AlignedWrapper { int value; }; +struct Baz { + mat3x2 m; +}; layout(std430) buffer Bar_block_0Vertex { mat4x3 matrix; mat2x2 matrix_array[2]; @@ -14,23 +17,75 @@ layout(std430) buffer Bar_block_0Vertex { AlignedWrapper data[]; } _group_0_binding_0_vs; +uniform Baz_block_1Vertex { Baz _group_0_binding_1_vs; }; + + +void test_matrix_within_struct_accesses() { + int idx = 9; + mat3x2 unnamed = mat3x2(0.0); + vec2 unnamed_1 = vec2(0.0); + vec2 unnamed_2 = vec2(0.0); + float unnamed_3 = 0.0; + float unnamed_4 = 0.0; + float unnamed_5 = 0.0; + float unnamed_6 = 0.0; + Baz t = Baz(mat3x2(0.0)); + int _e4 = idx; + idx = (_e4 - 1); + mat3x2 _e8 = _group_0_binding_1_vs.m; + unnamed = _e8; + vec2 _e13 = _group_0_binding_1_vs.m[0]; + unnamed_1 = _e13; + int _e16 = idx; + vec2 _e18 = _group_0_binding_1_vs.m[_e16]; + unnamed_2 = _e18; + float _e25 = _group_0_binding_1_vs.m[0][1]; + unnamed_3 = _e25; + int _e30 = idx; + float _e32 = _group_0_binding_1_vs.m[0][_e30]; + unnamed_4 = _e32; + int _e35 = idx; + float _e39 = _group_0_binding_1_vs.m[_e35][1]; + unnamed_5 = _e39; + int _e42 = idx; + int _e44 = idx; + float _e46 = _group_0_binding_1_vs.m[_e42][_e44]; + unnamed_6 = _e46; + t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); + int _e57 = idx; + idx = (_e57 + 1); + t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); + t.m[0] = vec2(9.0); + int _e74 = idx; + t.m[_e74] = vec2(90.0); + t.m[0][1] = 10.0; + int _e87 = idx; + t.m[0][_e87] = 20.0; + int _e91 = idx; + t.m[_e91][1] = 30.0; + int _e97 = idx; + int _e99 = idx; + t.m[_e97][_e99] = 40.0; + return; +} float read_from_private(inout float foo_1) { - float _e2 = foo_1; - return _e2; + float _e3 = foo_1; + return _e3; } void main() { uint vi = uint(gl_VertexID); float foo = 0.0; int c[5] = int[5](0, 0, 0, 0, 0); - float baz = foo; + float baz_1 = foo; foo = 1.0; + test_matrix_within_struct_accesses(); mat4x3 matrix = _group_0_binding_0_vs.matrix; uvec2 arr[2] = _group_0_binding_0_vs.arr; float b = _group_0_binding_0_vs.matrix[3][0]; int a = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; - float _e27 = read_from_private(foo); + float _e28 = read_from_private(foo); c = int[5](a, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 8af92afdd..7f63c78d8 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -3,12 +3,102 @@ struct AlignedWrapper { int value; }; +struct Baz { + float2 m_0; float2 m_1; float2 m_2; +}; + RWByteAddressBuffer bar : register(u0); +cbuffer baz : register(b1) { Baz baz; } + +float3x2 GetMatmOnBaz(Baz obj) { + return float3x2(obj.m_0, obj.m_1, obj.m_2); +} + +void SetMatmOnBaz(Baz obj, float3x2 mat) { + obj.m_0 = mat[0]; + obj.m_1 = mat[1]; + obj.m_2 = mat[2]; +} + +void SetMatVecmOnBaz(Baz obj, float2 vec, uint mat_idx) { + switch(mat_idx) { + case 0: obj.m_0 = vec; + case 1: obj.m_1 = vec; + case 2: obj.m_2 = vec; + } +} + +void SetMatScalarmOnBaz(Baz obj, float scalar, uint mat_idx, uint vec_idx) { + switch(mat_idx) { + case 0: obj.m_0[vec_idx] = scalar; + case 1: obj.m_1[vec_idx] = scalar; + case 2: obj.m_2[vec_idx] = scalar; + } +} + +Baz ConstructBaz(float3x2 arg0) { + Baz ret; + ret.m_0 = arg0[0]; + ret.m_1 = arg0[1]; + ret.m_2 = arg0[2]; + return ret; +} + +void test_matrix_within_struct_accesses() +{ + int idx = 9; + float3x2 unnamed = (float3x2)0; + float2 unnamed_1 = (float2)0; + float2 unnamed_2 = (float2)0; + float unnamed_3 = (float)0; + float unnamed_4 = (float)0; + float unnamed_5 = (float)0; + float unnamed_6 = (float)0; + Baz t = (Baz)0; + + int _expr4 = idx; + idx = (_expr4 - 1); + float3x2 _expr8 = GetMatmOnBaz(baz); + unnamed = _expr8; + float2 _expr13 = GetMatmOnBaz(baz)[0]; + unnamed_1 = _expr13; + int _expr16 = idx; + float2 _expr18 = GetMatmOnBaz(baz)[_expr16]; + unnamed_2 = _expr18; + float _expr25 = GetMatmOnBaz(baz)[0][1]; + unnamed_3 = _expr25; + int _expr30 = idx; + float _expr32 = GetMatmOnBaz(baz)[0][_expr30]; + unnamed_4 = _expr32; + int _expr35 = idx; + float _expr39 = GetMatmOnBaz(baz)[_expr35][1]; + unnamed_5 = _expr39; + int _expr42 = idx; + int _expr44 = idx; + float _expr46 = GetMatmOnBaz(baz)[_expr42][_expr44]; + unnamed_6 = _expr46; + t = ConstructBaz(float3x2(float2(1.0.xx), float2(2.0.xx), float2(3.0.xx))); + int _expr57 = idx; + idx = (_expr57 + 1); + SetMatmOnBaz(t, float3x2(float2(6.0.xx), float2(5.0.xx), float2(4.0.xx))); + t.m_0 = float2(9.0.xx); + int _expr74 = idx; + SetMatVecmOnBaz(t, float2(90.0.xx), _expr74); + t.m_0[1] = 10.0; + int _expr87 = idx; + t.m_0[_expr87] = 20.0; + int _expr91 = idx; + SetMatScalarmOnBaz(t, 30.0, _expr91, 1); + int _expr97 = idx; + int _expr99 = idx; + SetMatScalarmOnBaz(t, 40.0, _expr97, _expr99); + return; +} float read_from_private(inout float foo_1) { - float _expr2 = foo_1; - return _expr2; + float _expr3 = foo_1; + return _expr3; } uint NagaBufferLengthRW(RWByteAddressBuffer buffer) @@ -23,13 +113,14 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position float foo = 0.0; int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; - float baz = foo; + float baz_1 = foo; foo = 1.0; + test_matrix_within_struct_accesses(); float4x3 matrix_ = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); int a = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); - const float _e27 = read_from_private(foo); + const float _e28 = read_from_private(foo); { int _result[5]={ a, int(b), 3, 4, 5 }; for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; @@ -64,22 +155,22 @@ void atomics() int tmp = (int)0; int value_1 = asint(bar.Load(96)); - int _e6; bar.InterlockedAdd(96, 5, _e6); - tmp = _e6; - int _e9; bar.InterlockedAdd(96, -5, _e9); - tmp = _e9; - int _e12; bar.InterlockedAnd(96, 5, _e12); - tmp = _e12; - int _e15; bar.InterlockedOr(96, 5, _e15); - tmp = _e15; - int _e18; bar.InterlockedXor(96, 5, _e18); - tmp = _e18; - int _e21; bar.InterlockedMin(96, 5, _e21); - tmp = _e21; - int _e24; bar.InterlockedMax(96, 5, _e24); - tmp = _e24; - int _e27; bar.InterlockedExchange(96, 5, _e27); - tmp = _e27; + int _e7; bar.InterlockedAdd(96, 5, _e7); + tmp = _e7; + int _e10; bar.InterlockedAdd(96, -5, _e10); + tmp = _e10; + int _e13; bar.InterlockedAnd(96, 5, _e13); + tmp = _e13; + int _e16; bar.InterlockedOr(96, 5, _e16); + tmp = _e16; + int _e19; bar.InterlockedXor(96, 5, _e19); + tmp = _e19; + int _e22; bar.InterlockedMin(96, 5, _e22); + tmp = _e22; + int _e25; bar.InterlockedMax(96, 5, _e25); + tmp = _e25; + int _e28; bar.InterlockedExchange(96, 5, _e28); + tmp = _e28; bar.Store(96, asuint(value_1)); return; } diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index dbdad72e1..0f3b5cb12 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -26,15 +26,69 @@ struct Bar { type_6 arr; type_7 data; }; -struct type_13 { +struct Baz { + metal::float3x2 m; +}; +struct type_15 { int inner[5]; }; +void test_matrix_within_struct_accesses( + constant Baz& baz +) { + int idx = 9; + metal::float3x2 unnamed; + metal::float2 unnamed_1; + metal::float2 unnamed_2; + float unnamed_3; + float unnamed_4; + float unnamed_5; + float unnamed_6; + Baz t; + int _e4 = idx; + idx = _e4 - 1; + metal::float3x2 _e8 = baz.m; + unnamed = _e8; + metal::float2 _e13 = baz.m[0]; + unnamed_1 = _e13; + int _e16 = idx; + metal::float2 _e18 = baz.m[_e16]; + unnamed_2 = _e18; + float _e25 = baz.m[0].y; + unnamed_3 = _e25; + int _e30 = idx; + float _e32 = baz.m[0][_e30]; + unnamed_4 = _e32; + int _e35 = idx; + float _e39 = baz.m[_e35].y; + unnamed_5 = _e39; + int _e42 = idx; + int _e44 = idx; + float _e46 = baz.m[_e42][_e44]; + unnamed_6 = _e46; + t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; + int _e57 = idx; + idx = _e57 + 1; + t.m = metal::float3x2(metal::float2(6.0), metal::float2(5.0), metal::float2(4.0)); + t.m[0] = metal::float2(9.0); + int _e74 = idx; + t.m[_e74] = metal::float2(90.0); + t.m[0].y = 10.0; + int _e87 = idx; + t.m[0][_e87] = 20.0; + int _e91 = idx; + t.m[_e91].y = 30.0; + int _e97 = idx; + int _e99 = idx; + t.m[_e97][_e99] = 40.0; + return; +} + float read_from_private( thread float& foo_1 ) { - float _e2 = foo_1; - return _e2; + float _e3 = foo_1; + return _e3; } struct foo_vertInput { @@ -45,18 +99,20 @@ struct foo_vertOutput { vertex foo_vertOutput foo_vert( uint vi [[vertex_id]] , device Bar const& bar [[buffer(0)]] +, constant Baz& baz [[buffer(1)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo = 0.0; - type_13 c; - float baz = foo; + type_15 c; + float baz_1 = foo; foo = 1.0; + test_matrix_within_struct_accesses(baz); metal::float4x3 matrix = bar.matrix; type_6 arr = bar.arr; float b = bar.matrix[3].x; int a = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; - float _e27 = read_from_private(foo); - for(int _i=0; _i<5; ++_i) c.inner[_i] = type_13 {a, static_cast(b), 3, 4, 5}.inner[_i]; + float _e28 = read_from_private(foo); + for(int _i=0; _i<5; ++_i) c.inner[_i] = type_15 {a, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; return foo_vertOutput { metal::float4(matrix * static_cast(metal::int4(value)), 2.0) }; @@ -84,22 +140,22 @@ kernel void atomics( ) { int tmp; int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); - int _e6 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e6; - int _e9 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e9; - int _e12 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e12; - int _e15 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e15; - int _e18 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e18; - int _e21 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e21; - int _e24 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e24; - int _e27 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e27; + int _e7 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e7; + int _e10 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e10; + int _e13 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e13; + int _e16 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e16; + int _e19 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e19; + int _e22 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e22; + int _e25 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e25; + int _e28 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e28; metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index a78c50237..0f8959390 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,208 +1,333 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 128 +; Bound: 213 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %52 "foo_vert" %47 %50 -OpEntryPoint Fragment %88 "foo_frag" %87 -OpEntryPoint GLCompute %105 "atomics" -OpExecutionMode %88 OriginUpperLeft -OpExecutionMode %105 LocalSize 1 1 1 +OpEntryPoint Vertex %137 "foo_vert" %132 %135 +OpEntryPoint Fragment %173 "foo_frag" %172 +OpEntryPoint GLCompute %190 "atomics" +OpExecutionMode %173 OriginUpperLeft +OpExecutionMode %190 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %21 0 "value" -OpName %21 "AlignedWrapper" -OpMemberName %30 0 "matrix" -OpMemberName %30 1 "matrix_array" -OpMemberName %30 2 "atom" -OpMemberName %30 3 "arr" -OpMemberName %30 4 "data" -OpName %30 "Bar" -OpName %35 "bar" -OpName %38 "foo" -OpName %39 "read_from_private" -OpName %43 "foo" -OpName %44 "c" -OpName %47 "vi" -OpName %52 "foo_vert" -OpName %88 "foo_frag" -OpName %103 "tmp" -OpName %105 "atomics" -OpMemberDecorate %21 0 Offset 0 -OpDecorate %26 ArrayStride 16 -OpDecorate %28 ArrayStride 8 -OpDecorate %29 ArrayStride 8 -OpMemberDecorate %30 0 Offset 0 -OpMemberDecorate %30 0 ColMajor -OpMemberDecorate %30 0 MatrixStride 16 -OpMemberDecorate %30 1 Offset 64 -OpMemberDecorate %30 1 ColMajor -OpMemberDecorate %30 1 MatrixStride 8 -OpMemberDecorate %30 2 Offset 96 -OpMemberDecorate %30 3 Offset 104 -OpMemberDecorate %30 4 Offset 120 -OpDecorate %34 ArrayStride 4 -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 0 -OpDecorate %30 Block -OpDecorate %47 BuiltIn VertexIndex -OpDecorate %50 BuiltIn Position -OpDecorate %87 Location 0 +OpMemberName %31 0 "value" +OpName %31 "AlignedWrapper" +OpMemberName %40 0 "matrix" +OpMemberName %40 1 "matrix_array" +OpMemberName %40 2 "atom" +OpMemberName %40 3 "arr" +OpMemberName %40 4 "data" +OpName %40 "Bar" +OpMemberName %42 0 "m" +OpName %42 "Baz" +OpName %47 "bar" +OpName %49 "baz" +OpName %52 "idx" +OpName %54 "_" +OpName %56 "_" +OpName %58 "_" +OpName %59 "_" +OpName %60 "_" +OpName %61 "_" +OpName %62 "_" +OpName %63 "t" +OpName %66 "test_matrix_within_struct_accesses" +OpName %123 "foo" +OpName %124 "read_from_private" +OpName %128 "foo" +OpName %129 "c" +OpName %132 "vi" +OpName %137 "foo_vert" +OpName %173 "foo_frag" +OpName %188 "tmp" +OpName %190 "atomics" +OpMemberDecorate %31 0 Offset 0 +OpDecorate %36 ArrayStride 16 +OpDecorate %38 ArrayStride 8 +OpDecorate %39 ArrayStride 8 +OpMemberDecorate %40 0 Offset 0 +OpMemberDecorate %40 0 ColMajor +OpMemberDecorate %40 0 MatrixStride 16 +OpMemberDecorate %40 1 Offset 64 +OpMemberDecorate %40 1 ColMajor +OpMemberDecorate %40 1 MatrixStride 8 +OpMemberDecorate %40 2 Offset 96 +OpMemberDecorate %40 3 Offset 104 +OpMemberDecorate %40 4 Offset 120 +OpMemberDecorate %42 0 Offset 0 +OpMemberDecorate %42 0 ColMajor +OpMemberDecorate %42 0 MatrixStride 8 +OpDecorate %46 ArrayStride 4 +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 0 +OpDecorate %40 Block +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 1 +OpDecorate %50 Block +OpMemberDecorate %50 0 Offset 0 +OpDecorate %132 BuiltIn VertexIndex +OpDecorate %135 BuiltIn Position +OpDecorate %172 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 -%6 = OpTypeFloat 32 -%5 = OpConstant %6 0.0 -%7 = OpConstant %6 1.0 -%9 = OpTypeInt 32 0 -%8 = OpConstant %9 3 -%10 = OpConstant %9 2 -%11 = OpConstant %4 0 -%12 = OpConstant %4 5 -%13 = OpConstant %4 3 -%14 = OpConstant %4 4 -%15 = OpConstant %9 1 -%16 = OpConstant %4 42 -%17 = OpConstant %6 2.0 -%18 = OpConstant %4 1 -%19 = OpConstant %6 3.0 -%20 = OpConstant %9 0 -%21 = OpTypeStruct %4 -%23 = OpTypeVector %6 3 -%22 = OpTypeMatrix %23 4 -%25 = OpTypeVector %6 2 -%24 = OpTypeMatrix %25 2 -%26 = OpTypeArray %24 %3 -%27 = OpTypeVector %9 2 -%28 = OpTypeArray %27 %3 -%29 = OpTypeRuntimeArray %21 -%30 = OpTypeStruct %22 %26 %4 %28 %29 -%31 = OpTypePointer Function %6 -%32 = OpTypeVector %6 4 -%33 = OpTypePointer StorageBuffer %4 -%34 = OpTypeArray %4 %12 -%36 = OpTypePointer StorageBuffer %30 -%35 = OpVariable %36 StorageBuffer -%40 = OpTypeFunction %6 %31 -%45 = OpTypePointer Function %34 -%48 = OpTypePointer Input %9 -%47 = OpVariable %48 Input -%51 = OpTypePointer Output %32 -%50 = OpVariable %51 Output -%53 = OpTypeFunction %2 -%56 = OpTypePointer StorageBuffer %22 -%59 = OpTypePointer StorageBuffer %28 -%62 = OpTypePointer StorageBuffer %23 -%63 = OpTypePointer StorageBuffer %6 -%66 = OpTypePointer StorageBuffer %29 -%69 = OpTypePointer StorageBuffer %21 -%70 = OpConstant %9 4 -%77 = OpTypePointer Function %4 -%81 = OpTypeVector %4 4 -%87 = OpVariable %51 Output -%107 = OpTypePointer StorageBuffer %4 -%110 = OpConstant %9 64 -%39 = OpFunction %6 None %40 -%38 = OpFunctionParameter %31 -%37 = OpLabel -OpBranch %41 -%41 = OpLabel -%42 = OpLoad %6 %38 -OpReturnValue %42 -OpFunctionEnd -%52 = OpFunction %2 None %53 -%46 = OpLabel -%43 = OpVariable %31 Function %5 -%44 = OpVariable %45 Function -%49 = OpLoad %9 %47 -OpBranch %54 -%54 = OpLabel -%55 = OpLoad %6 %43 -OpStore %43 %7 -%57 = OpAccessChain %56 %35 %20 -%58 = OpLoad %22 %57 -%60 = OpAccessChain %59 %35 %8 -%61 = OpLoad %28 %60 -%64 = OpAccessChain %63 %35 %20 %8 %20 -%65 = OpLoad %6 %64 -%67 = OpArrayLength %9 %35 4 -%68 = OpISub %9 %67 %10 -%71 = OpAccessChain %33 %35 %70 %68 %20 -%72 = OpLoad %4 %71 -%73 = OpFunctionCall %6 %39 %43 -%74 = OpConvertFToS %4 %65 -%75 = OpCompositeConstruct %34 %72 %74 %13 %14 %12 -OpStore %44 %75 -%76 = OpIAdd %9 %49 %15 -%78 = OpAccessChain %77 %44 %76 -OpStore %78 %16 -%79 = OpAccessChain %77 %44 %49 -%80 = OpLoad %4 %79 -%82 = OpCompositeConstruct %81 %80 %80 %80 %80 -%83 = OpConvertSToF %32 %82 -%84 = OpMatrixTimesVector %23 %58 %83 -%85 = OpCompositeConstruct %32 %84 %17 -OpStore %50 %85 +%5 = OpConstant %4 9 +%6 = OpConstant %4 1 +%7 = OpConstant %4 0 +%9 = OpTypeFloat 32 +%8 = OpConstant %9 1.0 +%10 = OpConstant %9 2.0 +%11 = OpConstant %9 3.0 +%12 = OpConstant %9 6.0 +%13 = OpConstant %9 5.0 +%14 = OpConstant %9 4.0 +%15 = OpConstant %9 9.0 +%16 = OpConstant %9 90.0 +%17 = OpConstant %9 10.0 +%18 = OpConstant %9 20.0 +%19 = OpConstant %9 30.0 +%20 = OpConstant %9 40.0 +%21 = OpConstant %9 0.0 +%23 = OpTypeInt 32 0 +%22 = OpConstant %23 3 +%24 = OpConstant %23 2 +%25 = OpConstant %4 5 +%26 = OpConstant %4 3 +%27 = OpConstant %4 4 +%28 = OpConstant %23 1 +%29 = OpConstant %4 42 +%30 = OpConstant %23 0 +%31 = OpTypeStruct %4 +%33 = OpTypeVector %9 3 +%32 = OpTypeMatrix %33 4 +%35 = OpTypeVector %9 2 +%34 = OpTypeMatrix %35 2 +%36 = OpTypeArray %34 %3 +%37 = OpTypeVector %23 2 +%38 = OpTypeArray %37 %3 +%39 = OpTypeRuntimeArray %31 +%40 = OpTypeStruct %32 %36 %4 %38 %39 +%41 = OpTypeMatrix %35 3 +%42 = OpTypeStruct %41 +%43 = OpTypePointer Function %9 +%44 = OpTypeVector %9 4 +%45 = OpTypePointer StorageBuffer %4 +%46 = OpTypeArray %4 %25 +%48 = OpTypePointer StorageBuffer %40 +%47 = OpVariable %48 StorageBuffer +%50 = OpTypeStruct %42 +%51 = OpTypePointer Uniform %50 +%49 = OpVariable %51 Uniform +%53 = OpTypePointer Function %4 +%55 = OpTypePointer Function %41 +%57 = OpTypePointer Function %35 +%64 = OpTypePointer Function %42 +%67 = OpTypeFunction %2 +%68 = OpTypePointer Uniform %42 +%73 = OpTypePointer Uniform %41 +%76 = OpTypePointer Uniform %35 +%82 = OpTypePointer Uniform %9 +%107 = OpTypePointer Function %35 +%113 = OpTypePointer Function %9 +%125 = OpTypeFunction %9 %43 +%130 = OpTypePointer Function %46 +%133 = OpTypePointer Input %23 +%132 = OpVariable %133 Input +%136 = OpTypePointer Output %44 +%135 = OpVariable %136 Output +%142 = OpTypePointer StorageBuffer %32 +%145 = OpTypePointer StorageBuffer %38 +%148 = OpTypePointer StorageBuffer %33 +%149 = OpTypePointer StorageBuffer %9 +%152 = OpTypePointer StorageBuffer %39 +%155 = OpTypePointer StorageBuffer %31 +%156 = OpConstant %23 4 +%166 = OpTypeVector %4 4 +%172 = OpVariable %136 Output +%192 = OpTypePointer StorageBuffer %4 +%195 = OpConstant %23 64 +%66 = OpFunction %2 None %67 +%65 = OpLabel +%61 = OpVariable %43 Function +%58 = OpVariable %57 Function +%52 = OpVariable %53 Function %5 +%62 = OpVariable %43 Function +%59 = OpVariable %43 Function +%54 = OpVariable %55 Function +%63 = OpVariable %64 Function +%60 = OpVariable %43 Function +%56 = OpVariable %57 Function +%69 = OpAccessChain %68 %49 %30 +OpBranch %70 +%70 = OpLabel +%71 = OpLoad %4 %52 +%72 = OpISub %4 %71 %6 +OpStore %52 %72 +%74 = OpAccessChain %73 %69 %30 +%75 = OpLoad %41 %74 +OpStore %54 %75 +%77 = OpAccessChain %76 %69 %30 %30 +%78 = OpLoad %35 %77 +OpStore %56 %78 +%79 = OpLoad %4 %52 +%80 = OpAccessChain %76 %69 %30 %79 +%81 = OpLoad %35 %80 +OpStore %58 %81 +%83 = OpAccessChain %82 %69 %30 %30 %28 +%84 = OpLoad %9 %83 +OpStore %59 %84 +%85 = OpLoad %4 %52 +%86 = OpAccessChain %82 %69 %30 %30 %85 +%87 = OpLoad %9 %86 +OpStore %60 %87 +%88 = OpLoad %4 %52 +%89 = OpAccessChain %82 %69 %30 %88 %28 +%90 = OpLoad %9 %89 +OpStore %61 %90 +%91 = OpLoad %4 %52 +%92 = OpLoad %4 %52 +%93 = OpAccessChain %82 %69 %30 %91 %92 +%94 = OpLoad %9 %93 +OpStore %62 %94 +%95 = OpCompositeConstruct %35 %8 %8 +%96 = OpCompositeConstruct %35 %10 %10 +%97 = OpCompositeConstruct %35 %11 %11 +%98 = OpCompositeConstruct %41 %95 %96 %97 +%99 = OpCompositeConstruct %42 %98 +OpStore %63 %99 +%100 = OpLoad %4 %52 +%101 = OpIAdd %4 %100 %6 +OpStore %52 %101 +%102 = OpCompositeConstruct %35 %12 %12 +%103 = OpCompositeConstruct %35 %13 %13 +%104 = OpCompositeConstruct %35 %14 %14 +%105 = OpCompositeConstruct %41 %102 %103 %104 +%106 = OpAccessChain %55 %63 %30 +OpStore %106 %105 +%108 = OpCompositeConstruct %35 %15 %15 +%109 = OpAccessChain %107 %63 %30 %30 +OpStore %109 %108 +%110 = OpLoad %4 %52 +%111 = OpCompositeConstruct %35 %16 %16 +%112 = OpAccessChain %107 %63 %30 %110 +OpStore %112 %111 +%114 = OpAccessChain %113 %63 %30 %30 %28 +OpStore %114 %17 +%115 = OpLoad %4 %52 +%116 = OpAccessChain %113 %63 %30 %30 %115 +OpStore %116 %18 +%117 = OpLoad %4 %52 +%118 = OpAccessChain %113 %63 %30 %117 %28 +OpStore %118 %19 +%119 = OpLoad %4 %52 +%120 = OpLoad %4 %52 +%121 = OpAccessChain %113 %63 %30 %119 %120 +OpStore %121 %20 OpReturn OpFunctionEnd -%88 = OpFunction %2 None %53 -%86 = OpLabel -OpBranch %89 -%89 = OpLabel -%90 = OpAccessChain %63 %35 %20 %15 %10 -OpStore %90 %7 -%91 = OpCompositeConstruct %23 %5 %5 %5 -%92 = OpCompositeConstruct %23 %7 %7 %7 -%93 = OpCompositeConstruct %23 %17 %17 %17 -%94 = OpCompositeConstruct %23 %19 %19 %19 -%95 = OpCompositeConstruct %22 %91 %92 %93 %94 -%96 = OpAccessChain %56 %35 %20 -OpStore %96 %95 -%97 = OpCompositeConstruct %27 %20 %20 -%98 = OpCompositeConstruct %27 %15 %15 -%99 = OpCompositeConstruct %28 %97 %98 -%100 = OpAccessChain %59 %35 %8 -OpStore %100 %99 -%101 = OpAccessChain %33 %35 %70 %15 %20 -OpStore %101 %18 -%102 = OpCompositeConstruct %32 %5 %5 %5 %5 -OpStore %87 %102 +%124 = OpFunction %9 None %125 +%123 = OpFunctionParameter %43 +%122 = OpLabel +OpBranch %126 +%126 = OpLabel +%127 = OpLoad %9 %123 +OpReturnValue %127 +OpFunctionEnd +%137 = OpFunction %2 None %67 +%131 = OpLabel +%128 = OpVariable %43 Function %21 +%129 = OpVariable %130 Function +%134 = OpLoad %23 %132 +%138 = OpAccessChain %68 %49 %30 +OpBranch %139 +%139 = OpLabel +%140 = OpLoad %9 %128 +OpStore %128 %8 +%141 = OpFunctionCall %2 %66 +%143 = OpAccessChain %142 %47 %30 +%144 = OpLoad %32 %143 +%146 = OpAccessChain %145 %47 %22 +%147 = OpLoad %38 %146 +%150 = OpAccessChain %149 %47 %30 %22 %30 +%151 = OpLoad %9 %150 +%153 = OpArrayLength %23 %47 4 +%154 = OpISub %23 %153 %24 +%157 = OpAccessChain %45 %47 %156 %154 %30 +%158 = OpLoad %4 %157 +%159 = OpFunctionCall %9 %124 %128 +%160 = OpConvertFToS %4 %151 +%161 = OpCompositeConstruct %46 %158 %160 %26 %27 %25 +OpStore %129 %161 +%162 = OpIAdd %23 %134 %28 +%163 = OpAccessChain %53 %129 %162 +OpStore %163 %29 +%164 = OpAccessChain %53 %129 %134 +%165 = OpLoad %4 %164 +%167 = OpCompositeConstruct %166 %165 %165 %165 %165 +%168 = OpConvertSToF %44 %167 +%169 = OpMatrixTimesVector %33 %144 %168 +%170 = OpCompositeConstruct %44 %169 %10 +OpStore %135 %170 OpReturn OpFunctionEnd -%105 = OpFunction %2 None %53 -%104 = OpLabel -%103 = OpVariable %77 Function -OpBranch %106 -%106 = OpLabel -%108 = OpAccessChain %107 %35 %10 -%109 = OpAtomicLoad %4 %108 %18 %110 -%112 = OpAccessChain %107 %35 %10 -%111 = OpAtomicIAdd %4 %112 %18 %110 %12 -OpStore %103 %111 -%114 = OpAccessChain %107 %35 %10 -%113 = OpAtomicISub %4 %114 %18 %110 %12 -OpStore %103 %113 -%116 = OpAccessChain %107 %35 %10 -%115 = OpAtomicAnd %4 %116 %18 %110 %12 -OpStore %103 %115 -%118 = OpAccessChain %107 %35 %10 -%117 = OpAtomicOr %4 %118 %18 %110 %12 -OpStore %103 %117 -%120 = OpAccessChain %107 %35 %10 -%119 = OpAtomicXor %4 %120 %18 %110 %12 -OpStore %103 %119 -%122 = OpAccessChain %107 %35 %10 -%121 = OpAtomicSMin %4 %122 %18 %110 %12 -OpStore %103 %121 -%124 = OpAccessChain %107 %35 %10 -%123 = OpAtomicSMax %4 %124 %18 %110 %12 -OpStore %103 %123 -%126 = OpAccessChain %107 %35 %10 -%125 = OpAtomicExchange %4 %126 %18 %110 %12 -OpStore %103 %125 -%127 = OpAccessChain %107 %35 %10 -OpAtomicStore %127 %18 %110 %109 +%173 = OpFunction %2 None %67 +%171 = OpLabel +OpBranch %174 +%174 = OpLabel +%175 = OpAccessChain %149 %47 %30 %28 %24 +OpStore %175 %8 +%176 = OpCompositeConstruct %33 %21 %21 %21 +%177 = OpCompositeConstruct %33 %8 %8 %8 +%178 = OpCompositeConstruct %33 %10 %10 %10 +%179 = OpCompositeConstruct %33 %11 %11 %11 +%180 = OpCompositeConstruct %32 %176 %177 %178 %179 +%181 = OpAccessChain %142 %47 %30 +OpStore %181 %180 +%182 = OpCompositeConstruct %37 %30 %30 +%183 = OpCompositeConstruct %37 %28 %28 +%184 = OpCompositeConstruct %38 %182 %183 +%185 = OpAccessChain %145 %47 %22 +OpStore %185 %184 +%186 = OpAccessChain %45 %47 %156 %28 %30 +OpStore %186 %6 +%187 = OpCompositeConstruct %44 %21 %21 %21 %21 +OpStore %172 %187 +OpReturn +OpFunctionEnd +%190 = OpFunction %2 None %67 +%189 = OpLabel +%188 = OpVariable %53 Function +OpBranch %191 +%191 = OpLabel +%193 = OpAccessChain %192 %47 %24 +%194 = OpAtomicLoad %4 %193 %6 %195 +%197 = OpAccessChain %192 %47 %24 +%196 = OpAtomicIAdd %4 %197 %6 %195 %25 +OpStore %188 %196 +%199 = OpAccessChain %192 %47 %24 +%198 = OpAtomicISub %4 %199 %6 %195 %25 +OpStore %188 %198 +%201 = OpAccessChain %192 %47 %24 +%200 = OpAtomicAnd %4 %201 %6 %195 %25 +OpStore %188 %200 +%203 = OpAccessChain %192 %47 %24 +%202 = OpAtomicOr %4 %203 %6 %195 %25 +OpStore %188 %202 +%205 = OpAccessChain %192 %47 %24 +%204 = OpAtomicXor %4 %205 %6 %195 %25 +OpStore %188 %204 +%207 = OpAccessChain %192 %47 %24 +%206 = OpAtomicSMin %4 %207 %6 %195 %25 +OpStore %188 %206 +%209 = OpAccessChain %192 %47 %24 +%208 = OpAtomicSMax %4 %209 %6 %195 %25 +OpStore %188 %208 +%211 = OpAccessChain %192 %47 %24 +%210 = OpAtomicExchange %4 %211 %6 %195 %25 +OpStore %188 %210 +%212 = OpAccessChain %192 %47 %24 +OpAtomicStore %212 %6 %195 %194 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 38f0c4512..53cd3c4ac 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -10,12 +10,68 @@ struct Bar { data: array, } +struct Baz { + m: mat3x2, +} + @group(0) @binding(0) var bar: Bar; +@group(0) @binding(1) +var baz: Baz; + +fn test_matrix_within_struct_accesses() { + var idx: i32 = 9; + var unnamed: mat3x2; + var unnamed_1: vec2; + var unnamed_2: vec2; + var unnamed_3: f32; + var unnamed_4: f32; + var unnamed_5: f32; + var unnamed_6: f32; + var t: Baz; + + let _e4 = idx; + idx = (_e4 - 1); + let _e8 = baz.m; + unnamed = _e8; + let _e13 = baz.m[0]; + unnamed_1 = _e13; + let _e16 = idx; + let _e18 = baz.m[_e16]; + unnamed_2 = _e18; + let _e25 = baz.m[0][1]; + unnamed_3 = _e25; + let _e30 = idx; + let _e32 = baz.m[0][_e30]; + unnamed_4 = _e32; + let _e35 = idx; + let _e39 = baz.m[_e35][1]; + unnamed_5 = _e39; + let _e42 = idx; + let _e44 = idx; + let _e46 = baz.m[_e42][_e44]; + unnamed_6 = _e46; + t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); + let _e57 = idx; + idx = (_e57 + 1); + t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); + t.m[0] = vec2(9.0); + let _e74 = idx; + t.m[_e74] = vec2(90.0); + t.m[0][1] = 10.0; + let _e87 = idx; + t.m[0][_e87] = 20.0; + let _e91 = idx; + t.m[_e91][1] = 30.0; + let _e97 = idx; + let _e99 = idx; + t.m[_e97][_e99] = 40.0; + return; +} fn read_from_private(foo_1: ptr) -> f32 { - let _e2 = (*foo_1); - return _e2; + let _e3 = (*foo_1); + return _e3; } @stage(vertex) @@ -23,14 +79,15 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32 = 0.0; var c: array; - let baz = foo; + let baz_1 = foo; foo = 1.0; + test_matrix_within_struct_accesses(); let matrix = bar.matrix; let arr = bar.arr; let b = bar.matrix[3][0]; let a = bar.data[(arrayLength((&bar.data)) - 2u)].value; let data_pointer = (&bar.data[0].value); - let _e27 = read_from_private((&foo)); + let _e28 = read_from_private((&foo)); c = array(a, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value = c[vi]; @@ -51,22 +108,22 @@ fn atomics() { var tmp: i32; let value_1 = atomicLoad((&bar.atom)); - let _e6 = atomicAdd((&bar.atom), 5); - tmp = _e6; - let _e9 = atomicSub((&bar.atom), 5); - tmp = _e9; - let _e12 = atomicAnd((&bar.atom), 5); - tmp = _e12; - let _e15 = atomicOr((&bar.atom), 5); - tmp = _e15; - let _e18 = atomicXor((&bar.atom), 5); - tmp = _e18; - let _e21 = atomicMin((&bar.atom), 5); - tmp = _e21; - let _e24 = atomicMax((&bar.atom), 5); - tmp = _e24; - let _e27 = atomicExchange((&bar.atom), 5); - tmp = _e27; + let _e7 = atomicAdd((&bar.atom), 5); + tmp = _e7; + let _e10 = atomicSub((&bar.atom), 5); + tmp = _e10; + let _e13 = atomicAnd((&bar.atom), 5); + tmp = _e13; + let _e16 = atomicOr((&bar.atom), 5); + tmp = _e16; + let _e19 = atomicXor((&bar.atom), 5); + tmp = _e19; + let _e22 = atomicMin((&bar.atom), 5); + tmp = _e22; + let _e25 = atomicMax((&bar.atom), 5); + tmp = _e25; + let _e28 = atomicExchange((&bar.atom), 5); + tmp = _e28; atomicStore((&bar.atom), value_1); return; } From 8f5d8f61a82edd49750aeae757c94133a6481c26 Mon Sep 17 00:00:00 2001 From: Shohei Jinno <18493164+sjinno@users.noreply.github.com> Date: Mon, 11 Apr 2022 11:22:04 -0700 Subject: [PATCH 1652/2212] glsl-in: better errors for bad constant expression (#1501) Co-authored-by: JCapucho --- src/front/glsl/constants.rs | 2 +- src/front/glsl/parser.rs | 1 + src/front/glsl/parser/declarations.rs | 22 +++++++++++++++++----- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index f3eae9ac1..ea8112308 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -57,7 +57,7 @@ pub enum ConstantSolvingError { SplatScalarOnly, #[error("Can only swizzle vector constants")] SwizzleVectorOnly, - #[error("Not implemented: {0}")] + #[error("Not implemented as constant expression: {0}")] NotImplemented(String), } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index c159e80ee..92b812569 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -401,6 +401,7 @@ impl Parser { pub struct DeclarationContext<'ctx, 'qualifiers> { qualifiers: TypeQualifiers<'qualifiers>, + /// Indicates a global declaration external: bool, ctx: &'ctx mut Context, diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index d484c48f1..33ae48ce2 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -189,11 +189,23 @@ impl<'source> ParsingContext<'source> { }) .transpose()?; - // TODO: Should we try to make constants here? - // This is mostly a hack because we don't yet support adding - // bodies to entry points for variable initialization - let maybe_constant = - init.and_then(|(root, meta)| parser.solve_constant(ctx.ctx, root, meta).ok()); + // If the declaration has an initializer try to make a constant out of it, + // this is only strictly needed for global constant declarations (and if the + // initializer can't be made a constant it should throw an error) but we also + // try to do it for all other types of declarations. + let maybe_constant = if let Some((root, meta)) = init { + let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; + + match parser.solve_constant(ctx.ctx, root, meta) { + Ok(res) => Some(res), + // If the declaration is external (global scope) and is constant qualified + // then the initializer must be a constant expression + Err(err) if ctx.external && is_const => return Err(err), + _ => None, + } + } else { + None + }; let pointer = ctx.add_var(parser, ty, name, maybe_constant, meta)?; From b21634ac613b8ff3714407f7e8a2c3b58ab32fef Mon Sep 17 00:00:00 2001 From: Shohei Jinno <18493164+sjinno@users.noreply.github.com> Date: Mon, 11 Apr 2022 12:02:34 -0700 Subject: [PATCH 1653/2212] [glsl-in] Implement `MathFunction::Clamp` (#1502) * Implement Clamp function. * Fix the return error type. Change `ConstantSolvingError::InvalidMathArg` to `ConstantSolvingError::NotImplemented` for the clamp function with the input of unimplemented types. Unimplemented types: - vec2 - vec3 - vec4 * [glsl-in] Add helpers that implement the glsl's `max` and `min` functions. Co-authored-by: JCapucho * Fix grammar. Co-authored-by: JCapucho --- src/front/glsl/constants.rs | 95 ++++++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index ea8112308..e53737085 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -164,12 +164,20 @@ impl<'a> ConstantSolver<'a> { self.binary_op(op, left_constant, right_constant, span) } - Expression::Math { fun, arg, arg1, .. } => { + Expression::Math { + fun, + arg, + arg1, + arg2, + .. + } => { let arg = self.solve(arg)?; let arg1 = arg1.map(|arg| self.solve(arg)).transpose()?; + let arg2 = arg2.map(|arg| self.solve(arg)).transpose()?; let const0 = &self.constants[arg].inner; let const1 = arg1.map(|arg| &self.constants[arg].inner); + let const2 = arg2.map(|arg| &self.constants[arg].inner); match fun { crate::MathFunction::Pow => { @@ -201,6 +209,49 @@ impl<'a> ConstantSolver<'a> { let inner = ConstantInner::Scalar { width, value }; Ok(self.register_constant(inner, span)) } + crate::MathFunction::Clamp => { + let (value, width) = match (const0, const1.unwrap(), const2.unwrap()) { + ( + &ConstantInner::Scalar { + width, + value: value0, + }, + &ConstantInner::Scalar { value: value1, .. }, + &ConstantInner::Scalar { value: value2, .. }, + ) => ( + match (value0, value1, value2) { + ( + ScalarValue::Sint(a), + ScalarValue::Sint(b), + ScalarValue::Sint(c), + ) => ScalarValue::Sint(a.max(b).min(c)), + ( + ScalarValue::Uint(a), + ScalarValue::Uint(b), + ScalarValue::Uint(c), + ) => ScalarValue::Uint(a.max(b).min(c)), + ( + ScalarValue::Float(a), + ScalarValue::Float(b), + ScalarValue::Float(c), + ) => { + ScalarValue::Float(glsl_float_min(glsl_float_max(a, b), c)) + } + _ => return Err(ConstantSolvingError::InvalidMathArg), + }, + width, + ), + _ => { + return Err(ConstantSolvingError::NotImplemented(format!( + "{:?} applied to vector values", + fun + ))) + } + }; + + let inner = ConstantInner::Scalar { width, value }; + Ok(self.register_constant(inner, span)) + } _ => Err(ConstantSolvingError::NotImplemented(format!("{:?}", fun))), } } @@ -506,6 +557,48 @@ impl<'a> ConstantSolver<'a> { } } +/// Helper function to implement the GLSL `max` function for floats. +/// +/// While Rust does provide a `f64::max` method, it has a different behavior than the +/// GLSL `max` for NaNs. In Rust, if any of the arguments is a NaN, then the other +/// is returned. +/// +/// This leads to different results in the following example +/// ``` +/// use std::cmp::max; +/// std::f64::NAN.max(1.0); +/// ``` +/// +/// Rust will return `1.0` while GLSL should return NaN. +fn glsl_float_max(x: f64, y: f64) -> f64 { + if x < y { + y + } else { + x + } +} + +/// Helper function to implement the GLSL `min` function for floats. +/// +/// While Rust does provide a `f64::min` method, it has a different behavior than the +/// GLSL `min` for NaNs. In Rust, if any of the arguments is a NaN, then the other +/// is returned. +/// +/// This leads to different results in the following example +/// ``` +/// use std::cmp::min; +/// std::f64::NAN.min(1.0); +/// ``` +/// +/// Rust will return `1.0` while GLSL should return NaN. +fn glsl_float_min(x: f64, y: f64) -> f64 { + if y < x { + y + } else { + x + } +} + #[cfg(test)] mod tests { use std::vec; From 954c1f6f4bede2f6a60c92d51f98fe0d1ee5cf83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 12 Apr 2022 00:53:03 +0100 Subject: [PATCH 1654/2212] glsl-in: Add tests for constants NaN handling (#1817) --- src/front/glsl/constants.rs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index e53737085..0c7c4ed6a 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -234,9 +234,7 @@ impl<'a> ConstantSolver<'a> { ScalarValue::Float(a), ScalarValue::Float(b), ScalarValue::Float(c), - ) => { - ScalarValue::Float(glsl_float_min(glsl_float_max(a, b), c)) - } + ) => ScalarValue::Float(glsl_float_clamp(a, b, c)), _ => return Err(ConstantSolvingError::InvalidMathArg), }, width, @@ -599,6 +597,15 @@ fn glsl_float_min(x: f64, y: f64) -> f64 { } } +/// Helper function to implement the GLSL `clamp` function for floats. +/// +/// While Rust does provide a `f64::clamp` method, it requires a version of rust +/// above our MSRV and it also panics if either `min` or `max` are `NaN`s which +/// is not the behavior specified by the glsl specification. +fn glsl_float_clamp(value: f64, min: f64, max: f64) -> f64 { + glsl_float_min(glsl_float_max(value, min), max) +} + #[cfg(test)] mod tests { use std::vec; @@ -610,6 +617,19 @@ mod tests { use super::ConstantSolver; + #[test] + fn nan_handling() { + assert!(super::glsl_float_max(f64::NAN, 2.0).is_nan()); + assert!(!super::glsl_float_max(2.0, f64::NAN).is_nan()); + + assert!(super::glsl_float_min(f64::NAN, 2.0).is_nan()); + assert!(!super::glsl_float_min(2.0, f64::NAN).is_nan()); + + assert!(super::glsl_float_clamp(f64::NAN, 1.0, 2.0).is_nan()); + assert!(!super::glsl_float_clamp(1.0, f64::NAN, 2.0).is_nan()); + assert!(!super::glsl_float_clamp(1.0, 2.0, f64::NAN).is_nan()); + } + #[test] fn unary_op() { let mut types = UniqueArena::new(); From 1f797fdc2f79252029bbc40c86a0be07486f08bf Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sun, 10 Apr 2022 12:35:04 +0200 Subject: [PATCH 1655/2212] add more packed vec3 load/stores to test --- tests/in/globals.wgsl | 8 ++ tests/out/glsl/globals.main.Compute.glsl | 12 ++ tests/out/hlsl/globals.hlsl | 12 ++ tests/out/msl/globals.msl | 12 ++ tests/out/spv/globals.spvasm | 166 +++++++++++++---------- tests/out/wgsl/globals.wgsl | 12 ++ 6 files changed, 152 insertions(+), 70 deletions(-) diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 0dff3f8e7..3979910f5 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -23,10 +23,18 @@ var float_vecs: array, 20>; fn main() { wg[3] = alignment.v1; wg[2] = alignment.v3.x; + var _ = alignment.v3; + var _ = alignment.v3.zx; alignment.v1 = 4.0; wg[1] = f32(arrayLength(&dummy)); atomicStore(&at, 2u); + alignment.v3 = vec3(1.0); + var idx = 1; + alignment.v3.x = 1.0; + alignment.v3[0] = 2.0; + alignment.v3[idx] = 3.0; + // Valid, Foo and at is in function scope var Foo: f32 = 1.0; var at: bool = true; diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index 61513e8af..b23c60f3d 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -19,15 +19,27 @@ layout(std430) readonly buffer type_6_block_1Compute { vec2 _group_0_binding_2_c void main() { + vec3 unnamed = vec3(0.0); + vec2 unnamed_1 = vec2(0.0); + int idx = 1; float Foo_1 = 1.0; bool at = true; float _e9 = _group_0_binding_1_cs.v1_; wg[3] = _e9; float _e14 = _group_0_binding_1_cs.v3_.x; wg[2] = _e14; + vec3 _e16 = _group_0_binding_1_cs.v3_; + unnamed = _e16; + vec3 _e19 = _group_0_binding_1_cs.v3_; + unnamed_1 = _e19.zx; _group_0_binding_1_cs.v1_ = 4.0; wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; + _group_0_binding_1_cs.v3_ = vec3(1.0); + _group_0_binding_1_cs.v3_.x = 1.0; + _group_0_binding_1_cs.v3_.x = 2.0; + int _e42 = idx; + _group_0_binding_1_cs.v3_[_e42] = 3.0; return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index d540235ba..c5d5b167a 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -21,6 +21,9 @@ uint NagaBufferLength(ByteAddressBuffer buffer) [numthreads(1, 1, 1)] void main() { + float3 unnamed = (float3)0; + float2 unnamed_1 = (float2)0; + int idx = 1; float Foo_1 = 1.0; bool at = true; @@ -28,8 +31,17 @@ void main() wg[3] = _expr9; float _expr14 = asfloat(alignment.Load(0+0)); wg[2] = _expr14; + float3 _expr16 = asfloat(alignment.Load3(0)); + unnamed = _expr16; + float3 _expr19 = asfloat(alignment.Load3(0)); + unnamed_1 = _expr19.zx; alignment.Store(12, asuint(4.0)); wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; + alignment.Store3(0, asuint(float3(1.0.xxx))); + alignment.Store(0+0, asuint(1.0)); + alignment.Store(0+0, asuint(2.0)); + int _expr42 = idx; + alignment.Store(_expr42*4+0, asuint(3.0)); return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 14fbc152a..3a83c3226 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -28,14 +28,26 @@ kernel void main_( , device type_6 const& dummy [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { + metal::float3 unnamed; + metal::float2 unnamed_1; + int idx = 1; float Foo_1 = 1.0; bool at = true; float _e9 = alignment.v1_; wg.inner[3] = _e9; float _e14 = metal::float3(alignment.v3_).x; wg.inner[2] = _e14; + metal::float3 _e16 = metal::float3(alignment.v3_); + unnamed = _e16; + metal::float3 _e19 = metal::float3(alignment.v3_); + unnamed_1 = _e19.zx; alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); + alignment.v3_ = metal::float3(1.0); + metal::float3(alignment.v3_).x = 1.0; + metal::float3(alignment.v3_).x = 2.0; + int _e42 = idx; + alignment.v3_[_e42] = 3.0; return; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index e70ef7ca3..59783eb33 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,31 +1,31 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 68 +; Bound: 88 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %42 "main" -OpExecutionMode %42 LocalSize 1 1 1 -OpDecorate %17 ArrayStride 4 -OpMemberDecorate %19 0 Offset 0 -OpMemberDecorate %19 1 Offset 12 -OpDecorate %21 ArrayStride 8 -OpDecorate %23 ArrayStride 16 -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 1 -OpDecorate %29 Block -OpMemberDecorate %29 0 Offset 0 -OpDecorate %31 NonWritable +OpEntryPoint GLCompute %51 "main" +OpExecutionMode %51 LocalSize 1 1 1 +OpDecorate %20 ArrayStride 4 +OpMemberDecorate %22 0 Offset 0 +OpMemberDecorate %22 1 Offset 12 +OpDecorate %24 ArrayStride 8 +OpDecorate %26 ArrayStride 16 OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 2 +OpDecorate %31 Binding 1 OpDecorate %32 Block OpMemberDecorate %32 0 Offset 0 +OpDecorate %34 NonWritable OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 3 +OpDecorate %34 Binding 2 OpDecorate %35 Block OpMemberDecorate %35 0 Offset 0 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 3 +OpDecorate %38 Block +OpMemberDecorate %38 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -40,63 +40,89 @@ OpMemberDecorate %35 0 Offset 0 %13 = OpConstant %8 1 %14 = OpConstant %6 2 %15 = OpConstant %12 1.0 -%16 = OpConstantTrue %4 -%17 = OpTypeArray %12 %5 -%18 = OpTypeVector %12 3 -%19 = OpTypeStruct %18 %12 -%20 = OpTypeVector %12 2 -%21 = OpTypeRuntimeArray %20 -%22 = OpTypeVector %12 4 -%23 = OpTypeArray %22 %7 -%25 = OpTypePointer Workgroup %17 -%24 = OpVariable %25 Workgroup -%27 = OpTypePointer Workgroup %6 -%26 = OpVariable %27 Workgroup -%29 = OpTypeStruct %19 -%30 = OpTypePointer StorageBuffer %29 -%28 = OpVariable %30 StorageBuffer -%32 = OpTypeStruct %21 +%16 = OpConstant %8 0 +%17 = OpConstant %12 2.0 +%18 = OpConstant %12 3.0 +%19 = OpConstantTrue %4 +%20 = OpTypeArray %12 %5 +%21 = OpTypeVector %12 3 +%22 = OpTypeStruct %21 %12 +%23 = OpTypeVector %12 2 +%24 = OpTypeRuntimeArray %23 +%25 = OpTypeVector %12 4 +%26 = OpTypeArray %25 %7 +%28 = OpTypePointer Workgroup %20 +%27 = OpVariable %28 Workgroup +%30 = OpTypePointer Workgroup %6 +%29 = OpVariable %30 Workgroup +%32 = OpTypeStruct %22 %33 = OpTypePointer StorageBuffer %32 %31 = OpVariable %33 StorageBuffer -%35 = OpTypeStruct %23 -%36 = OpTypePointer Uniform %35 -%34 = OpVariable %36 Uniform -%38 = OpTypePointer Function %12 -%40 = OpTypePointer Function %4 -%43 = OpTypeFunction %2 -%44 = OpTypePointer StorageBuffer %19 -%45 = OpConstant %6 0 -%47 = OpTypePointer StorageBuffer %21 -%49 = OpTypePointer Uniform %23 -%51 = OpTypePointer Workgroup %12 -%52 = OpTypePointer StorageBuffer %12 -%53 = OpConstant %6 1 -%56 = OpConstant %6 3 -%58 = OpTypePointer StorageBuffer %18 -%59 = OpTypePointer StorageBuffer %12 -%67 = OpConstant %6 256 -%42 = OpFunction %2 None %43 -%41 = OpLabel -%37 = OpVariable %38 Function %15 -%39 = OpVariable %40 Function %16 -%46 = OpAccessChain %44 %28 %45 -%48 = OpAccessChain %47 %31 %45 -OpBranch %50 +%35 = OpTypeStruct %24 +%36 = OpTypePointer StorageBuffer %35 +%34 = OpVariable %36 StorageBuffer +%38 = OpTypeStruct %26 +%39 = OpTypePointer Uniform %38 +%37 = OpVariable %39 Uniform +%41 = OpTypePointer Function %21 +%43 = OpTypePointer Function %23 +%45 = OpTypePointer Function %8 +%47 = OpTypePointer Function %12 +%49 = OpTypePointer Function %4 +%52 = OpTypeFunction %2 +%53 = OpTypePointer StorageBuffer %22 +%54 = OpConstant %6 0 +%56 = OpTypePointer StorageBuffer %24 +%58 = OpTypePointer Uniform %26 +%60 = OpTypePointer Workgroup %12 +%61 = OpTypePointer StorageBuffer %12 +%62 = OpConstant %6 1 +%65 = OpConstant %6 3 +%67 = OpTypePointer StorageBuffer %21 +%68 = OpTypePointer StorageBuffer %12 +%81 = OpConstant %6 256 +%51 = OpFunction %2 None %52 %50 = OpLabel -%54 = OpAccessChain %52 %46 %53 -%55 = OpLoad %12 %54 -%57 = OpAccessChain %51 %24 %56 -OpStore %57 %55 -%60 = OpAccessChain %59 %46 %45 %45 -%61 = OpLoad %12 %60 -%62 = OpAccessChain %51 %24 %14 -OpStore %62 %61 -%63 = OpAccessChain %52 %46 %53 -OpStore %63 %11 -%64 = OpArrayLength %6 %31 0 -%65 = OpConvertUToF %12 %64 -%66 = OpAccessChain %51 %24 %53 -OpStore %66 %65 -OpAtomicStore %26 %10 %67 %14 +%48 = OpVariable %49 Function %19 +%42 = OpVariable %43 Function +%46 = OpVariable %47 Function %15 +%40 = OpVariable %41 Function +%44 = OpVariable %45 Function %13 +%55 = OpAccessChain %53 %31 %54 +%57 = OpAccessChain %56 %34 %54 +OpBranch %59 +%59 = OpLabel +%63 = OpAccessChain %61 %55 %62 +%64 = OpLoad %12 %63 +%66 = OpAccessChain %60 %27 %65 +OpStore %66 %64 +%69 = OpAccessChain %68 %55 %54 %54 +%70 = OpLoad %12 %69 +%71 = OpAccessChain %60 %27 %14 +OpStore %71 %70 +%72 = OpAccessChain %67 %55 %54 +%73 = OpLoad %21 %72 +OpStore %40 %73 +%74 = OpAccessChain %67 %55 %54 +%75 = OpLoad %21 %74 +%76 = OpVectorShuffle %23 %75 %75 2 0 +OpStore %42 %76 +%77 = OpAccessChain %61 %55 %62 +OpStore %77 %11 +%78 = OpArrayLength %6 %34 0 +%79 = OpConvertUToF %12 %78 +%80 = OpAccessChain %60 %27 %62 +OpStore %80 %79 +OpAtomicStore %29 %10 %81 %14 +%82 = OpCompositeConstruct %21 %15 %15 %15 +%83 = OpAccessChain %67 %55 %54 +OpStore %83 %82 +%84 = OpAccessChain %68 %55 %54 %54 +OpStore %84 %15 +%85 = OpAccessChain %68 %55 %54 %54 +OpStore %85 %17 +%86 = OpLoad %8 %44 +%87 = OpAccessChain %68 %55 %54 %86 +OpStore %87 %18 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 2437556f2..acbdd6cd5 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -16,6 +16,9 @@ var float_vecs: array,20>; @stage(compute) @workgroup_size(1, 1, 1) fn main() { + var unnamed: vec3; + var unnamed_1: vec2; + var idx: i32 = 1; var Foo_1: f32 = 1.0; var at: bool = true; @@ -23,8 +26,17 @@ fn main() { wg[3] = _e9; let _e14 = alignment.v3_.x; wg[2] = _e14; + let _e16 = alignment.v3_; + unnamed = _e16; + let _e19 = alignment.v3_; + unnamed_1 = _e19.zx; alignment.v1_ = 4.0; wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); + alignment.v3_ = vec3(1.0); + alignment.v3_.x = 1.0; + alignment.v3_.x = 2.0; + let _e42 = idx; + alignment.v3_[_e42] = 3.0; return; } From 1688a767bb42c9a9a8c942c3619bf5d171b4111d Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sun, 10 Apr 2022 19:22:56 +0200 Subject: [PATCH 1656/2212] fix packed vec3 stores --- src/back/msl/writer.rs | 23 +++++++---------------- tests/out/msl/globals.msl | 10 +++++----- 2 files changed, 12 insertions(+), 21 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ebfe7c834..7a0bbc4fe 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -554,8 +554,6 @@ impl<'a> ExpressionContext<'a> { index::access_needs_check(base, index, self.module, self.function, self.info) } - // Because packed vectors such as `packed_float3` cannot be directly loaded, - // we convert them to unpacked vectors like `float3` on load. fn get_packed_vec_kind( &self, expr_handle: Handle, @@ -1917,16 +1915,14 @@ impl Writer { write!(self.out, ".{}", name)?; } crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => { - let wrap_packed_vec_scalar_kind = context.get_packed_vec_kind(base); - //Note: this doesn't work for left-hand side - if let Some(scalar_kind) = wrap_packed_vec_scalar_kind { - write!(self.out, "{}::{}3(", NAMESPACE, scalar_kind.to_msl_name())?; - self.put_access_chain(base, policy, context)?; - write!(self.out, ")")?; + self.put_access_chain(base, policy, context)?; + // Prior to Metal v2.1 component access for packed vectors wasn't available + // however array indexing is + if context.get_packed_vec_kind(base).is_some() { + write!(self.out, "[{}]", index)?; } else { - self.put_access_chain(base, policy, context)?; + write!(self.out, ".{}", back::COMPONENTS[index as usize])?; } - write!(self.out, ".{}", back::COMPONENTS[index as usize])?; } _ => { self.put_subscripted_access_chain( @@ -2052,7 +2048,6 @@ impl Writer { policy: index::BoundsCheckPolicy, context: &ExpressionContext, ) -> BackendResult { - let wrap_packed_vec_scalar_kind = context.get_packed_vec_kind(pointer); let is_atomic = match *context.resolve_type(pointer) { crate::TypeInner::Pointer { base, .. } => match context.module.types[base].inner { crate::TypeInner::Atomic { .. } => true, @@ -2061,11 +2056,7 @@ impl Writer { _ => false, }; - if let Some(scalar_kind) = wrap_packed_vec_scalar_kind { - write!(self.out, "{}::{}3(", NAMESPACE, scalar_kind.to_msl_name())?; - self.put_access_chain(pointer, policy, context)?; - write!(self.out, ")")?; - } else if is_atomic { + if is_atomic { write!( self.out, "{}::atomic_load_explicit({}", diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 3a83c3226..704193d69 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -35,18 +35,18 @@ kernel void main_( bool at = true; float _e9 = alignment.v1_; wg.inner[3] = _e9; - float _e14 = metal::float3(alignment.v3_).x; + float _e14 = alignment.v3_[0]; wg.inner[2] = _e14; - metal::float3 _e16 = metal::float3(alignment.v3_); + metal::float3 _e16 = alignment.v3_; unnamed = _e16; - metal::float3 _e19 = metal::float3(alignment.v3_); + metal::float3 _e19 = alignment.v3_; unnamed_1 = _e19.zx; alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); alignment.v3_ = metal::float3(1.0); - metal::float3(alignment.v3_).x = 1.0; - metal::float3(alignment.v3_).x = 2.0; + alignment.v3_[0] = 1.0; + alignment.v3_[0] = 2.0; int _e42 = idx; alignment.v3_[_e42] = 3.0; return; From d7f4c340a7d9f02e4c790e64574965be670c03a1 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sun, 10 Apr 2022 21:26:52 +0200 Subject: [PATCH 1657/2212] add matrix vector multiplication test --- tests/in/globals.wgsl | 4 + tests/out/glsl/globals.main.Compute.glsl | 5 +- tests/out/hlsl/globals.hlsl | 5 +- tests/out/msl/globals.msl | 7 +- tests/out/spv/globals.spvasm | 214 ++++++++++++----------- tests/out/wgsl/globals.wgsl | 5 +- 6 files changed, 134 insertions(+), 106 deletions(-) diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 3979910f5..ce5b6a09d 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -35,6 +35,10 @@ fn main() { alignment.v3[0] = 2.0; alignment.v3[idx] = 3.0; + let m = mat3x3(); + let _ = alignment.v3 * m; + let _ = m * alignment.v3; + // Valid, Foo and at is in function scope var Foo: f32 = 1.0; var at: bool = true; diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index b23c60f3d..d40508136 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -40,6 +40,9 @@ void main() { _group_0_binding_1_cs.v3_.x = 2.0; int _e42 = idx; _group_0_binding_1_cs.v3_[_e42] = 3.0; - return; + vec3 _e47 = _group_0_binding_1_cs.v3_; + vec3 unnamed_2 = (_e47 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + vec3 _e50 = _group_0_binding_1_cs.v3_; + vec3 unnamed_3 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * _e50); } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index c5d5b167a..1f3620d14 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -43,5 +43,8 @@ void main() alignment.Store(0+0, asuint(2.0)); int _expr42 = idx; alignment.Store(_expr42*4+0, asuint(3.0)); - return; + float3 _expr47 = asfloat(alignment.Load3(0)); + float3 unnamed_2 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), _expr47); + float3 _expr50 = asfloat(alignment.Load3(0)); + float3 unnamed_3 = mul(_expr50, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 704193d69..3b93d27e3 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -20,6 +20,8 @@ typedef metal::float2 type_6[1]; struct type_8 { metal::float4 inner[20]; }; +constant metal::float3 const_type_4_ = {0.0, 0.0, 0.0}; +constant metal::float3x3 const_type_10_ = {const_type_4_, const_type_4_, const_type_4_}; kernel void main_( threadgroup type_2& wg @@ -49,5 +51,8 @@ kernel void main_( alignment.v3_[0] = 2.0; int _e42 = idx; alignment.v3_[_e42] = 3.0; - return; + metal::float3 _e47 = alignment.v3_; + metal::float3 unnamed_2 = _e47 * const_type_10_; + metal::float3 _e50 = alignment.v3_; + metal::float3 unnamed_3 = const_type_10_ * _e50; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 59783eb33..148479931 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,31 +1,31 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 88 +; Bound: 98 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %51 "main" -OpExecutionMode %51 LocalSize 1 1 1 -OpDecorate %20 ArrayStride 4 -OpMemberDecorate %22 0 Offset 0 -OpMemberDecorate %22 1 Offset 12 -OpDecorate %24 ArrayStride 8 -OpDecorate %26 ArrayStride 16 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 1 -OpDecorate %32 Block -OpMemberDecorate %32 0 Offset 0 -OpDecorate %34 NonWritable -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 2 -OpDecorate %35 Block -OpMemberDecorate %35 0 Offset 0 -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 3 -OpDecorate %38 Block -OpMemberDecorate %38 0 Offset 0 +OpEntryPoint GLCompute %55 "main" +OpExecutionMode %55 LocalSize 1 1 1 +OpDecorate %21 ArrayStride 4 +OpMemberDecorate %23 0 Offset 0 +OpMemberDecorate %23 1 Offset 12 +OpDecorate %25 ArrayStride 8 +OpDecorate %27 ArrayStride 16 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 1 +OpDecorate %36 Block +OpMemberDecorate %36 0 Offset 0 +OpDecorate %38 NonWritable +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 2 +OpDecorate %39 Block +OpMemberDecorate %39 0 Offset 0 +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 3 +OpDecorate %42 Block +OpMemberDecorate %42 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -43,86 +43,96 @@ OpMemberDecorate %38 0 Offset 0 %16 = OpConstant %8 0 %17 = OpConstant %12 2.0 %18 = OpConstant %12 3.0 -%19 = OpConstantTrue %4 -%20 = OpTypeArray %12 %5 -%21 = OpTypeVector %12 3 -%22 = OpTypeStruct %21 %12 -%23 = OpTypeVector %12 2 -%24 = OpTypeRuntimeArray %23 -%25 = OpTypeVector %12 4 -%26 = OpTypeArray %25 %7 -%28 = OpTypePointer Workgroup %20 -%27 = OpVariable %28 Workgroup -%30 = OpTypePointer Workgroup %6 -%29 = OpVariable %30 Workgroup -%32 = OpTypeStruct %22 -%33 = OpTypePointer StorageBuffer %32 -%31 = OpVariable %33 StorageBuffer -%35 = OpTypeStruct %24 -%36 = OpTypePointer StorageBuffer %35 -%34 = OpVariable %36 StorageBuffer -%38 = OpTypeStruct %26 -%39 = OpTypePointer Uniform %38 -%37 = OpVariable %39 Uniform -%41 = OpTypePointer Function %21 -%43 = OpTypePointer Function %23 -%45 = OpTypePointer Function %8 -%47 = OpTypePointer Function %12 -%49 = OpTypePointer Function %4 -%52 = OpTypeFunction %2 -%53 = OpTypePointer StorageBuffer %22 -%54 = OpConstant %6 0 -%56 = OpTypePointer StorageBuffer %24 -%58 = OpTypePointer Uniform %26 -%60 = OpTypePointer Workgroup %12 -%61 = OpTypePointer StorageBuffer %12 -%62 = OpConstant %6 1 -%65 = OpConstant %6 3 -%67 = OpTypePointer StorageBuffer %21 -%68 = OpTypePointer StorageBuffer %12 -%81 = OpConstant %6 256 -%51 = OpFunction %2 None %52 -%50 = OpLabel -%48 = OpVariable %49 Function %19 -%42 = OpVariable %43 Function -%46 = OpVariable %47 Function %15 -%40 = OpVariable %41 Function -%44 = OpVariable %45 Function %13 -%55 = OpAccessChain %53 %31 %54 -%57 = OpAccessChain %56 %34 %54 -OpBranch %59 -%59 = OpLabel -%63 = OpAccessChain %61 %55 %62 -%64 = OpLoad %12 %63 -%66 = OpAccessChain %60 %27 %65 -OpStore %66 %64 -%69 = OpAccessChain %68 %55 %54 %54 -%70 = OpLoad %12 %69 -%71 = OpAccessChain %60 %27 %14 -OpStore %71 %70 -%72 = OpAccessChain %67 %55 %54 -%73 = OpLoad %21 %72 -OpStore %40 %73 -%74 = OpAccessChain %67 %55 %54 -%75 = OpLoad %21 %74 -%76 = OpVectorShuffle %23 %75 %75 2 0 -OpStore %42 %76 -%77 = OpAccessChain %61 %55 %62 -OpStore %77 %11 -%78 = OpArrayLength %6 %34 0 -%79 = OpConvertUToF %12 %78 -%80 = OpAccessChain %60 %27 %62 -OpStore %80 %79 -OpAtomicStore %29 %10 %81 %14 -%82 = OpCompositeConstruct %21 %15 %15 %15 -%83 = OpAccessChain %67 %55 %54 -OpStore %83 %82 -%84 = OpAccessChain %68 %55 %54 %54 -OpStore %84 %15 -%85 = OpAccessChain %68 %55 %54 %54 -OpStore %85 %17 -%86 = OpLoad %8 %44 -%87 = OpAccessChain %68 %55 %54 %86 -OpStore %87 %18 +%19 = OpConstant %12 0.0 +%20 = OpConstantTrue %4 +%21 = OpTypeArray %12 %5 +%22 = OpTypeVector %12 3 +%23 = OpTypeStruct %22 %12 +%24 = OpTypeVector %12 2 +%25 = OpTypeRuntimeArray %24 +%26 = OpTypeVector %12 4 +%27 = OpTypeArray %26 %7 +%28 = OpTypeMatrix %22 3 +%29 = OpConstantComposite %22 %19 %19 %19 +%30 = OpConstantComposite %28 %29 %29 %29 +%32 = OpTypePointer Workgroup %21 +%31 = OpVariable %32 Workgroup +%34 = OpTypePointer Workgroup %6 +%33 = OpVariable %34 Workgroup +%36 = OpTypeStruct %23 +%37 = OpTypePointer StorageBuffer %36 +%35 = OpVariable %37 StorageBuffer +%39 = OpTypeStruct %25 +%40 = OpTypePointer StorageBuffer %39 +%38 = OpVariable %40 StorageBuffer +%42 = OpTypeStruct %27 +%43 = OpTypePointer Uniform %42 +%41 = OpVariable %43 Uniform +%45 = OpTypePointer Function %22 +%47 = OpTypePointer Function %24 +%49 = OpTypePointer Function %8 +%51 = OpTypePointer Function %12 +%53 = OpTypePointer Function %4 +%56 = OpTypeFunction %2 +%57 = OpTypePointer StorageBuffer %23 +%58 = OpConstant %6 0 +%60 = OpTypePointer StorageBuffer %25 +%62 = OpTypePointer Uniform %27 +%64 = OpTypePointer Workgroup %12 +%65 = OpTypePointer StorageBuffer %12 +%66 = OpConstant %6 1 +%69 = OpConstant %6 3 +%71 = OpTypePointer StorageBuffer %22 +%72 = OpTypePointer StorageBuffer %12 +%85 = OpConstant %6 256 +%55 = OpFunction %2 None %56 +%54 = OpLabel +%52 = OpVariable %53 Function %20 +%46 = OpVariable %47 Function +%50 = OpVariable %51 Function %15 +%44 = OpVariable %45 Function +%48 = OpVariable %49 Function %13 +%59 = OpAccessChain %57 %35 %58 +%61 = OpAccessChain %60 %38 %58 +OpBranch %63 +%63 = OpLabel +%67 = OpAccessChain %65 %59 %66 +%68 = OpLoad %12 %67 +%70 = OpAccessChain %64 %31 %69 +OpStore %70 %68 +%73 = OpAccessChain %72 %59 %58 %58 +%74 = OpLoad %12 %73 +%75 = OpAccessChain %64 %31 %14 +OpStore %75 %74 +%76 = OpAccessChain %71 %59 %58 +%77 = OpLoad %22 %76 +OpStore %44 %77 +%78 = OpAccessChain %71 %59 %58 +%79 = OpLoad %22 %78 +%80 = OpVectorShuffle %24 %79 %79 2 0 +OpStore %46 %80 +%81 = OpAccessChain %65 %59 %66 +OpStore %81 %11 +%82 = OpArrayLength %6 %38 0 +%83 = OpConvertUToF %12 %82 +%84 = OpAccessChain %64 %31 %66 +OpStore %84 %83 +OpAtomicStore %33 %10 %85 %14 +%86 = OpCompositeConstruct %22 %15 %15 %15 +%87 = OpAccessChain %71 %59 %58 +OpStore %87 %86 +%88 = OpAccessChain %72 %59 %58 %58 +OpStore %88 %15 +%89 = OpAccessChain %72 %59 %58 %58 +OpStore %89 %17 +%90 = OpLoad %8 %48 +%91 = OpAccessChain %72 %59 %58 %90 +OpStore %91 %18 +%92 = OpAccessChain %71 %59 %58 +%93 = OpLoad %22 %92 +%94 = OpVectorTimesMatrix %22 %93 %30 +%95 = OpAccessChain %71 %59 %58 +%96 = OpLoad %22 %95 +%97 = OpMatrixTimesVector %22 %30 %96 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index acbdd6cd5..72213db1d 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -38,5 +38,8 @@ fn main() { alignment.v3_.x = 2.0; let _e42 = idx; alignment.v3_[_e42] = 3.0; - return; + let _e47 = alignment.v3_; + let unnamed_2 = (_e47 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let _e50 = alignment.v3_; + let unnamed_3 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * _e50); } From 32cdb272304c54debb8e8b78bf213f3e91500120 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 11 Apr 2022 13:43:28 +0200 Subject: [PATCH 1658/2212] add better tests for msl packed vec3 --- tests/in/globals.wgsl | 41 ++++-- tests/out/glsl/globals.main.Compute.glsl | 39 +++-- tests/out/hlsl/globals.hlsl | 42 ++++-- tests/out/msl/globals.msl | 43 ++++-- tests/out/spv/globals.spvasm | 179 ++++++++++++----------- tests/out/wgsl/globals.wgsl | 40 +++-- 6 files changed, 225 insertions(+), 159 deletions(-) diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index ce5b6a09d..86a41569d 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -19,25 +19,42 @@ var dummy: array>; @group(0) @binding(3) var float_vecs: array, 20>; -@stage(compute) @workgroup_size(1) -fn main() { - wg[3] = alignment.v1; - wg[2] = alignment.v3.x; - var _ = alignment.v3; - var _ = alignment.v3.zx; - alignment.v1 = 4.0; - wg[1] = f32(arrayLength(&dummy)); - atomicStore(&at, 2u); +fn test_msl_packed_vec3_as_arg(arg: vec3) {} +fn test_msl_packed_vec3() { + // stores alignment.v3 = vec3(1.0); var idx = 1; alignment.v3.x = 1.0; alignment.v3[0] = 2.0; alignment.v3[idx] = 3.0; - let m = mat3x3(); - let _ = alignment.v3 * m; - let _ = m * alignment.v3; + // force load to happen here + let data = alignment; + + // loads + let _ = data.v3; + let _ = data.v3.zx; + test_msl_packed_vec3_as_arg(data.v3); + + // matrix vector multiplication + let _ = data.v3 * mat3x3(); + let _ = mat3x3() * data.v3; + + // scalar vector multiplication + let _ = data.v3 * 2.0; + let _ = 2.0 * data.v3; +} + +@stage(compute) @workgroup_size(1) +fn main() { + test_msl_packed_vec3(); + + wg[3] = alignment.v1; + wg[2] = alignment.v3.x; + alignment.v1 = 4.0; + wg[1] = f32(arrayLength(&dummy)); + atomicStore(&at, 2u); // Valid, Foo and at is in function scope var Foo: f32 = 1.0; diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index d40508136..0db8ee14b 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -18,31 +18,38 @@ layout(std430) buffer Foo_block_0Compute { Foo _group_0_binding_1_cs; }; layout(std430) readonly buffer type_6_block_1Compute { vec2 _group_0_binding_2_cs[]; }; -void main() { - vec3 unnamed = vec3(0.0); - vec2 unnamed_1 = vec2(0.0); +void test_msl_packed_vec3_as_arg(vec3 arg) { + return; +} + +void test_msl_packed_vec3_() { int idx = 1; + _group_0_binding_1_cs.v3_ = vec3(1.0); + _group_0_binding_1_cs.v3_.x = 1.0; + _group_0_binding_1_cs.v3_.x = 2.0; + int _e19 = idx; + _group_0_binding_1_cs.v3_[_e19] = 3.0; + Foo data = _group_0_binding_1_cs; + vec3 unnamed = data.v3_; + vec2 unnamed_1 = data.v3_.zx; + test_msl_packed_vec3_as_arg(data.v3_); + vec3 unnamed_2 = (data.v3_ * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + vec3 unnamed_3 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * data.v3_); + vec3 unnamed_4 = (data.v3_ * 2.0); + vec3 unnamed_5 = (2.0 * data.v3_); +} + +void main() { float Foo_1 = 1.0; bool at = true; + test_msl_packed_vec3_(); float _e9 = _group_0_binding_1_cs.v1_; wg[3] = _e9; float _e14 = _group_0_binding_1_cs.v3_.x; wg[2] = _e14; - vec3 _e16 = _group_0_binding_1_cs.v3_; - unnamed = _e16; - vec3 _e19 = _group_0_binding_1_cs.v3_; - unnamed_1 = _e19.zx; _group_0_binding_1_cs.v1_ = 4.0; wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; - _group_0_binding_1_cs.v3_ = vec3(1.0); - _group_0_binding_1_cs.v3_.x = 1.0; - _group_0_binding_1_cs.v3_.x = 2.0; - int _e42 = idx; - _group_0_binding_1_cs.v3_[_e42] = 3.0; - vec3 _e47 = _group_0_binding_1_cs.v3_; - vec3 unnamed_2 = (_e47 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - vec3 _e50 = _group_0_binding_1_cs.v3_; - vec3 unnamed_3 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * _e50); + return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 1f3620d14..7844ddf35 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -11,6 +11,30 @@ RWByteAddressBuffer alignment : register(u1); ByteAddressBuffer dummy : register(t2); cbuffer float_vecs : register(b3) { float4 float_vecs[20]; } +void test_msl_packed_vec3_as_arg(float3 arg) +{ + return; +} + +void test_msl_packed_vec3_() +{ + int idx = 1; + + alignment.Store3(0, asuint(float3(1.0.xxx))); + alignment.Store(0+0, asuint(1.0)); + alignment.Store(0+0, asuint(2.0)); + int _expr19 = idx; + alignment.Store(_expr19*4+0, asuint(3.0)); + Foo data = {asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))}; + float3 unnamed = data.v3_; + float2 unnamed_1 = data.v3_.zx; + test_msl_packed_vec3_as_arg(data.v3_); + float3 unnamed_2 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), data.v3_); + float3 unnamed_3 = mul(data.v3_, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3 unnamed_4 = (data.v3_ * 2.0); + float3 unnamed_5 = (2.0 * data.v3_); +} + uint NagaBufferLength(ByteAddressBuffer buffer) { uint ret; @@ -21,30 +45,16 @@ uint NagaBufferLength(ByteAddressBuffer buffer) [numthreads(1, 1, 1)] void main() { - float3 unnamed = (float3)0; - float2 unnamed_1 = (float2)0; - int idx = 1; float Foo_1 = 1.0; bool at = true; + test_msl_packed_vec3_(); float _expr9 = asfloat(alignment.Load(12)); wg[3] = _expr9; float _expr14 = asfloat(alignment.Load(0+0)); wg[2] = _expr14; - float3 _expr16 = asfloat(alignment.Load3(0)); - unnamed = _expr16; - float3 _expr19 = asfloat(alignment.Load3(0)); - unnamed_1 = _expr19.zx; alignment.Store(12, asuint(4.0)); wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; - alignment.Store3(0, asuint(float3(1.0.xxx))); - alignment.Store(0+0, asuint(1.0)); - alignment.Store(0+0, asuint(2.0)); - int _expr42 = idx; - alignment.Store(_expr42*4+0, asuint(3.0)); - float3 _expr47 = asfloat(alignment.Load3(0)); - float3 unnamed_2 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), _expr47); - float3 _expr50 = asfloat(alignment.Load3(0)); - float3 unnamed_3 = mul(_expr50, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 3b93d27e3..3fde9269b 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -23,6 +23,31 @@ struct type_8 { constant metal::float3 const_type_4_ = {0.0, 0.0, 0.0}; constant metal::float3x3 const_type_10_ = {const_type_4_, const_type_4_, const_type_4_}; +void test_msl_packed_vec3_as_arg( + metal::float3 arg +) { + return; +} + +void test_msl_packed_vec3_( + device Foo& alignment +) { + int idx = 1; + alignment.v3_ = metal::float3(1.0); + alignment.v3_[0] = 1.0; + alignment.v3_[0] = 2.0; + int _e19 = idx; + alignment.v3_[_e19] = 3.0; + Foo data = alignment; + metal::float3 unnamed = data.v3_; + metal::float2 unnamed_1 = data.v3_.zx; + test_msl_packed_vec3_as_arg(data.v3_); + metal::float3 unnamed_2 = data.v3_ * const_type_10_; + metal::float3 unnamed_3 = const_type_10_ * data.v3_; + metal::float3 unnamed_4 = data.v3_ * 2.0; + metal::float3 unnamed_5 = 2.0 * data.v3_; +} + kernel void main_( threadgroup type_2& wg , threadgroup metal::atomic_uint& at_1 @@ -30,29 +55,15 @@ kernel void main_( , device type_6 const& dummy [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - metal::float3 unnamed; - metal::float2 unnamed_1; - int idx = 1; float Foo_1 = 1.0; bool at = true; + test_msl_packed_vec3_(alignment); float _e9 = alignment.v1_; wg.inner[3] = _e9; float _e14 = alignment.v3_[0]; wg.inner[2] = _e14; - metal::float3 _e16 = alignment.v3_; - unnamed = _e16; - metal::float3 _e19 = alignment.v3_; - unnamed_1 = _e19.zx; alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); - alignment.v3_ = metal::float3(1.0); - alignment.v3_[0] = 1.0; - alignment.v3_[0] = 2.0; - int _e42 = idx; - alignment.v3_[_e42] = 3.0; - metal::float3 _e47 = alignment.v3_; - metal::float3 unnamed_2 = _e47 * const_type_10_; - metal::float3 _e50 = alignment.v3_; - metal::float3 unnamed_3 = const_type_10_ * _e50; + return; } diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 148479931..395096db3 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 98 +; Bound: 107 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %55 "main" -OpExecutionMode %55 LocalSize 1 1 1 +OpEntryPoint GLCompute %87 "main" +OpExecutionMode %87 LocalSize 1 1 1 OpDecorate %21 ArrayStride 4 OpMemberDecorate %23 0 Offset 0 OpMemberDecorate %23 1 Offset 12 @@ -33,27 +33,27 @@ OpMemberDecorate %42 0 Offset 0 %5 = OpConstant %6 10 %8 = OpTypeInt 32 1 %7 = OpConstant %8 20 -%9 = OpConstant %8 3 -%10 = OpConstant %8 2 -%12 = OpTypeFloat 32 -%11 = OpConstant %12 4.0 -%13 = OpConstant %8 1 -%14 = OpConstant %6 2 -%15 = OpConstant %12 1.0 -%16 = OpConstant %8 0 -%17 = OpConstant %12 2.0 -%18 = OpConstant %12 3.0 -%19 = OpConstant %12 0.0 +%10 = OpTypeFloat 32 +%9 = OpConstant %10 1.0 +%11 = OpConstant %8 1 +%12 = OpConstant %8 0 +%13 = OpConstant %10 2.0 +%14 = OpConstant %10 3.0 +%15 = OpConstant %10 0.0 +%16 = OpConstant %8 3 +%17 = OpConstant %8 2 +%18 = OpConstant %10 4.0 +%19 = OpConstant %6 2 %20 = OpConstantTrue %4 -%21 = OpTypeArray %12 %5 -%22 = OpTypeVector %12 3 -%23 = OpTypeStruct %22 %12 -%24 = OpTypeVector %12 2 +%21 = OpTypeArray %10 %5 +%22 = OpTypeVector %10 3 +%23 = OpTypeStruct %22 %10 +%24 = OpTypeVector %10 2 %25 = OpTypeRuntimeArray %24 -%26 = OpTypeVector %12 4 +%26 = OpTypeVector %10 4 %27 = OpTypeArray %26 %7 %28 = OpTypeMatrix %22 3 -%29 = OpConstantComposite %22 %19 %19 %19 +%29 = OpConstantComposite %22 %15 %15 %15 %30 = OpConstantComposite %28 %29 %29 %29 %32 = OpTypePointer Workgroup %21 %31 = OpVariable %32 Workgroup @@ -68,71 +68,84 @@ OpMemberDecorate %42 0 Offset 0 %42 = OpTypeStruct %27 %43 = OpTypePointer Uniform %42 %41 = OpVariable %43 Uniform -%45 = OpTypePointer Function %22 -%47 = OpTypePointer Function %24 -%49 = OpTypePointer Function %8 -%51 = OpTypePointer Function %12 -%53 = OpTypePointer Function %4 +%47 = OpTypeFunction %2 %22 +%48 = OpTypePointer StorageBuffer %23 +%49 = OpTypePointer StorageBuffer %25 +%50 = OpTypePointer Uniform %27 +%53 = OpTypePointer Function %8 %56 = OpTypeFunction %2 -%57 = OpTypePointer StorageBuffer %23 -%58 = OpConstant %6 0 -%60 = OpTypePointer StorageBuffer %25 -%62 = OpTypePointer Uniform %27 -%64 = OpTypePointer Workgroup %12 -%65 = OpTypePointer StorageBuffer %12 -%66 = OpConstant %6 1 -%69 = OpConstant %6 3 -%71 = OpTypePointer StorageBuffer %22 -%72 = OpTypePointer StorageBuffer %12 -%85 = OpConstant %6 256 +%57 = OpConstant %6 0 +%60 = OpTypePointer StorageBuffer %22 +%63 = OpTypePointer StorageBuffer %10 +%83 = OpTypePointer Function %10 +%85 = OpTypePointer Function %4 +%92 = OpTypePointer Workgroup %10 +%93 = OpTypePointer StorageBuffer %10 +%94 = OpConstant %6 1 +%97 = OpConstant %6 3 +%106 = OpConstant %6 256 +%46 = OpFunction %2 None %47 +%45 = OpFunctionParameter %22 +%44 = OpLabel +OpBranch %51 +%51 = OpLabel +OpReturn +OpFunctionEnd %55 = OpFunction %2 None %56 %54 = OpLabel -%52 = OpVariable %53 Function %20 -%46 = OpVariable %47 Function -%50 = OpVariable %51 Function %15 -%44 = OpVariable %45 Function -%48 = OpVariable %49 Function %13 -%59 = OpAccessChain %57 %35 %58 -%61 = OpAccessChain %60 %38 %58 -OpBranch %63 -%63 = OpLabel -%67 = OpAccessChain %65 %59 %66 -%68 = OpLoad %12 %67 -%70 = OpAccessChain %64 %31 %69 -OpStore %70 %68 -%73 = OpAccessChain %72 %59 %58 %58 -%74 = OpLoad %12 %73 -%75 = OpAccessChain %64 %31 %14 -OpStore %75 %74 -%76 = OpAccessChain %71 %59 %58 -%77 = OpLoad %22 %76 -OpStore %44 %77 -%78 = OpAccessChain %71 %59 %58 -%79 = OpLoad %22 %78 -%80 = OpVectorShuffle %24 %79 %79 2 0 -OpStore %46 %80 -%81 = OpAccessChain %65 %59 %66 -OpStore %81 %11 -%82 = OpArrayLength %6 %38 0 -%83 = OpConvertUToF %12 %82 -%84 = OpAccessChain %64 %31 %66 -OpStore %84 %83 -OpAtomicStore %33 %10 %85 %14 -%86 = OpCompositeConstruct %22 %15 %15 %15 -%87 = OpAccessChain %71 %59 %58 -OpStore %87 %86 -%88 = OpAccessChain %72 %59 %58 %58 -OpStore %88 %15 -%89 = OpAccessChain %72 %59 %58 %58 -OpStore %89 %17 -%90 = OpLoad %8 %48 -%91 = OpAccessChain %72 %59 %58 %90 -OpStore %91 %18 -%92 = OpAccessChain %71 %59 %58 -%93 = OpLoad %22 %92 -%94 = OpVectorTimesMatrix %22 %93 %30 -%95 = OpAccessChain %71 %59 %58 -%96 = OpLoad %22 %95 -%97 = OpMatrixTimesVector %22 %30 %96 +%52 = OpVariable %53 Function %11 +%58 = OpAccessChain %48 %35 %57 +OpBranch %59 +%59 = OpLabel +%61 = OpCompositeConstruct %22 %9 %9 %9 +%62 = OpAccessChain %60 %58 %57 +OpStore %62 %61 +%64 = OpAccessChain %63 %58 %57 %57 +OpStore %64 %9 +%65 = OpAccessChain %63 %58 %57 %57 +OpStore %65 %13 +%66 = OpLoad %8 %52 +%67 = OpAccessChain %63 %58 %57 %66 +OpStore %67 %14 +%68 = OpLoad %23 %58 +%69 = OpCompositeExtract %22 %68 0 +%70 = OpCompositeExtract %22 %68 0 +%71 = OpVectorShuffle %24 %70 %70 2 0 +%72 = OpCompositeExtract %22 %68 0 +%73 = OpFunctionCall %2 %46 %72 +%74 = OpCompositeExtract %22 %68 0 +%75 = OpVectorTimesMatrix %22 %74 %30 +%76 = OpCompositeExtract %22 %68 0 +%77 = OpMatrixTimesVector %22 %30 %76 +%78 = OpCompositeExtract %22 %68 0 +%79 = OpVectorTimesScalar %22 %78 %13 +%80 = OpCompositeExtract %22 %68 0 +%81 = OpVectorTimesScalar %22 %80 %13 +OpReturn +OpFunctionEnd +%87 = OpFunction %2 None %56 +%86 = OpLabel +%82 = OpVariable %83 Function %9 +%84 = OpVariable %85 Function %20 +%88 = OpAccessChain %48 %35 %57 +%89 = OpAccessChain %49 %38 %57 +OpBranch %90 +%90 = OpLabel +%91 = OpFunctionCall %2 %55 +%95 = OpAccessChain %93 %88 %94 +%96 = OpLoad %10 %95 +%98 = OpAccessChain %92 %31 %97 +OpStore %98 %96 +%99 = OpAccessChain %63 %88 %57 %57 +%100 = OpLoad %10 %99 +%101 = OpAccessChain %92 %31 %19 +OpStore %101 %100 +%102 = OpAccessChain %93 %88 %94 +OpStore %102 %18 +%103 = OpArrayLength %6 %38 0 +%104 = OpConvertUToF %10 %103 +%105 = OpAccessChain %92 %31 %94 +OpStore %105 %104 +OpAtomicStore %33 %17 %106 %19 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 72213db1d..7c9ca8056 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -14,32 +14,40 @@ var dummy: array>; @group(0) @binding(3) var float_vecs: array,20>; +fn test_msl_packed_vec3_as_arg(arg: vec3) { + return; +} + +fn test_msl_packed_vec3_() { + var idx: i32 = 1; + + alignment.v3_ = vec3(1.0); + alignment.v3_.x = 1.0; + alignment.v3_.x = 2.0; + let _e19 = idx; + alignment.v3_[_e19] = 3.0; + let data = alignment; + let unnamed = data.v3_; + let unnamed_1 = data.v3_.zx; + test_msl_packed_vec3_as_arg(data.v3_); + let unnamed_2 = (data.v3_ * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_3 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * data.v3_); + let unnamed_4 = (data.v3_ * 2.0); + let unnamed_5 = (2.0 * data.v3_); +} + @stage(compute) @workgroup_size(1, 1, 1) fn main() { - var unnamed: vec3; - var unnamed_1: vec2; - var idx: i32 = 1; var Foo_1: f32 = 1.0; var at: bool = true; + test_msl_packed_vec3_(); let _e9 = alignment.v1_; wg[3] = _e9; let _e14 = alignment.v3_.x; wg[2] = _e14; - let _e16 = alignment.v3_; - unnamed = _e16; - let _e19 = alignment.v3_; - unnamed_1 = _e19.zx; alignment.v1_ = 4.0; wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); - alignment.v3_ = vec3(1.0); - alignment.v3_.x = 1.0; - alignment.v3_.x = 2.0; - let _e42 = idx; - alignment.v3_[_e42] = 3.0; - let _e47 = alignment.v3_; - let unnamed_2 = (_e47 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let _e50 = alignment.v3_; - let unnamed_3 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * _e50); + return; } From 0e77d26241b2429e1bc4f4ef443e6911ac7fd5a1 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 11 Apr 2022 15:36:52 +0200 Subject: [PATCH 1659/2212] cast packed vec3's to vec3 for expressions that require it --- src/back/msl/writer.rs | 45 ++++++++++++++++++++++++++++++++++++--- tests/out/msl/globals.msl | 6 +++--- 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7a0bbc4fe..e1f69055b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1275,7 +1275,7 @@ impl Writer { vector, pattern, } => { - self.put_expression(vector, context, false)?; + self.put_wrapped_expression_for_packed_vec3_access(vector, context, false)?; write!(self.out, ".")?; for &sc in pattern[..size as usize].iter() { write!(self.out, "{}", back::COMPONENTS[sc as usize])?; @@ -1447,9 +1447,31 @@ impl Writer { if !is_scoped { write!(self.out, "(")?; } - self.put_expression(left, context, false)?; + + // Cast packed vector if necessary + // Packed vector - matrix multiplications are not supported in MSL + if op == crate::BinaryOperator::Multiply + && matches!( + context.resolve_type(right), + &crate::TypeInner::Matrix { .. } + ) + { + self.put_wrapped_expression_for_packed_vec3_access(left, context, false)?; + } else { + self.put_expression(left, context, false)?; + } + write!(self.out, " {} ", op_str)?; - self.put_expression(right, context, false)?; + + // See comment above + if op == crate::BinaryOperator::Multiply + && matches!(context.resolve_type(left), &crate::TypeInner::Matrix { .. }) + { + self.put_wrapped_expression_for_packed_vec3_access(right, context, false)?; + } else { + self.put_expression(right, context, false)?; + } + if !is_scoped { write!(self.out, ")")?; } @@ -1738,6 +1760,23 @@ impl Writer { Ok(()) } + /// Used by expressions like Swizzle and Binary since they need packed_vec3's to be casted to a vec3 + fn put_wrapped_expression_for_packed_vec3_access( + &mut self, + expr_handle: Handle, + context: &ExpressionContext, + is_scoped: bool, + ) -> BackendResult { + if let Some(scalar_kind) = context.get_packed_vec_kind(expr_handle) { + write!(self.out, "{}::{}3(", NAMESPACE, scalar_kind.to_msl_name())?; + self.put_expression(expr_handle, context, is_scoped)?; + write!(self.out, ")")?; + } else { + self.put_expression(expr_handle, context, is_scoped)?; + } + Ok(()) + } + /// Write a `GuardedIndex` as a Metal expression. fn put_index( &mut self, diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 3fde9269b..504e41d57 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -40,10 +40,10 @@ void test_msl_packed_vec3_( alignment.v3_[_e19] = 3.0; Foo data = alignment; metal::float3 unnamed = data.v3_; - metal::float2 unnamed_1 = data.v3_.zx; + metal::float2 unnamed_1 = metal::float3(data.v3_).zx; test_msl_packed_vec3_as_arg(data.v3_); - metal::float3 unnamed_2 = data.v3_ * const_type_10_; - metal::float3 unnamed_3 = const_type_10_ * data.v3_; + metal::float3 unnamed_2 = metal::float3(data.v3_) * const_type_10_; + metal::float3 unnamed_3 = const_type_10_ * metal::float3(data.v3_); metal::float3 unnamed_4 = data.v3_ * 2.0; metal::float3 unnamed_5 = 2.0 * data.v3_; } From bd62887a1366475224f4e7eeffde76be321b32b7 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 05:34:06 +0200 Subject: [PATCH 1660/2212] [hlsl-out] Add more padding when necessary (#1814) * [hlsl-out] add padding at the end of structs and after struct members of type matrix and array (when necessary) * use wrapped constructor fn for constants * add array as fn arg test * fix glsl array fn arg * add wrapped constructor for arrays * [glsl-out] support multidimensional arrays * address comments --- src/back/glsl/mod.rs | 47 +- src/back/hlsl/conv.rs | 75 +++ src/back/hlsl/help.rs | 182 ++++-- src/back/hlsl/storage.rs | 2 +- src/back/hlsl/writer.rs | 95 ++- tests/in/access.wgsl | 6 + tests/in/padding.param.ron | 22 + tests/in/padding.wgsl | 33 + tests/out/glsl/access.atomics.Compute.glsl | 4 + tests/out/glsl/access.foo_frag.Fragment.glsl | 4 + tests/out/glsl/access.foo_vert.Vertex.glsl | 31 +- tests/out/glsl/padding.vertex.Vertex.glsl | 36 ++ tests/out/hlsl/access.hlsl | 55 +- tests/out/hlsl/operators.hlsl | 27 +- tests/out/hlsl/padding.hlsl | 43 ++ tests/out/hlsl/padding.hlsl.config | 3 + tests/out/hlsl/quad-vert.hlsl | 16 +- tests/out/msl/access.msl | 45 +- tests/out/msl/padding.msl | 38 ++ tests/out/spv/access.spvasm | 607 ++++++++++--------- tests/out/spv/padding.spvasm | 99 +++ tests/out/wgsl/access.wgsl | 31 +- tests/out/wgsl/padding.wgsl | 33 + tests/snapshots.rs | 4 + 24 files changed, 1088 insertions(+), 450 deletions(-) create mode 100644 tests/in/padding.param.ron create mode 100644 tests/in/padding.wgsl create mode 100644 tests/out/glsl/padding.vertex.Vertex.glsl create mode 100644 tests/out/hlsl/padding.hlsl create mode 100644 tests/out/hlsl/padding.hlsl.config create mode 100644 tests/out/msl/padding.msl create mode 100644 tests/out/spv/padding.spvasm create mode 100644 tests/out/wgsl/padding.wgsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 1e3f0d058..6e8387c00 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -727,7 +727,11 @@ impl<'a, W: Write> Writer<'a, W> { self.collect_reflection_info() } - fn write_array_size(&mut self, size: crate::ArraySize) -> BackendResult { + fn write_array_size( + &mut self, + base: Handle, + size: crate::ArraySize, + ) -> BackendResult { write!(self.out, "[")?; // Write the array size @@ -751,6 +755,16 @@ impl<'a, W: Write> Writer<'a, W> { } write!(self.out, "]")?; + + if let TypeInner::Array { + base: next_base, + size: next_size, + .. + } = self.module.types[base].inner + { + self.write_array_size(next_base, next_size)?; + } + Ok(()) } @@ -807,7 +821,7 @@ impl<'a, W: Write> Writer<'a, W> { // GLSL arrays are written as `type name[size]` // Current code is written arrays only as `[size]` // Base `type` and `name` should be written outside - TypeInner::Array { size, .. } => self.write_array_size(size)?, + TypeInner::Array { base, size, .. } => self.write_array_size(base, size)?, // Panic if either Image, Sampler, Pointer, or a Struct is being written // // Write all variants instead of `_` so that if new variants are added a @@ -994,8 +1008,8 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, " ")?; self.write_global_name(handle, global)?; - if let TypeInner::Array { size, .. } = self.module.types[global.ty].inner { - self.write_array_size(size)?; + if let TypeInner::Array { base, size, .. } = self.module.types[global.ty].inner { + self.write_array_size(base, size)?; } if global.space.initializable() && is_value_init_supported(self.module, global.ty) { @@ -1298,6 +1312,11 @@ impl<'a, W: Write> Writer<'a, W> { // The leading space is important write!(this.out, " {}", &this.names[&ctx.argument_key(i as u32)])?; + // Write array size + if let TypeInner::Array { base, size, .. } = this.module.types[arg.ty].inner { + this.write_array_size(base, size)?; + } + Ok(()) })?; @@ -1356,8 +1375,8 @@ impl<'a, W: Write> Writer<'a, W> { // The leading space is important write!(self.out, " {}", self.names[&ctx.name_key(handle)])?; // Write size for array type - if let TypeInner::Array { size, .. } = self.module.types[local.ty].inner { - self.write_array_size(size)?; + if let TypeInner::Array { base, size, .. } = self.module.types[local.ty].inner { + self.write_array_size(base, size)?; } // Write the local initializer if needed if let Some(init) = local.init { @@ -1448,8 +1467,8 @@ impl<'a, W: Write> Writer<'a, W> { // `type(components)` where `components` is a comma separated list of constants crate::ConstantInner::Composite { ty, ref components } => { self.write_type(ty)?; - if let TypeInner::Array { size, .. } = self.module.types[ty].inner { - self.write_array_size(size)?; + if let TypeInner::Array { base, size, .. } = self.module.types[ty].inner { + self.write_array_size(base, size)?; } write!(self.out, "(")?; @@ -1525,7 +1544,7 @@ impl<'a, W: Write> Writer<'a, W> { &self.names[&NameKey::StructMember(handle, idx as u32)] )?; // Write [size] - self.write_array_size(size)?; + self.write_array_size(base, size)?; // Newline is important writeln!(self.out, ";")?; } @@ -2056,8 +2075,8 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(ty)?; let resolved = ctx.info[expr].ty.inner_with(&self.module.types); - if let TypeInner::Array { size, .. } = *resolved { - self.write_array_size(size)?; + if let TypeInner::Array { base, size, .. } = *resolved { + self.write_array_size(base, size)?; } write!(self.out, "(")?; @@ -2909,8 +2928,8 @@ impl<'a, W: Write> Writer<'a, W> { let resolved = base_ty_res.inner_with(&self.module.types); write!(self.out, " {}", name)?; - if let TypeInner::Array { size, .. } = *resolved { - self.write_array_size(size)?; + if let TypeInner::Array { base, size, .. } = *resolved { + self.write_array_size(base, size)?; } write!(self.out, " = ")?; self.write_expr(handle, ctx)?; @@ -2948,7 +2967,7 @@ impl<'a, W: Write> Writer<'a, W> { proc::IndexableLength::Dynamic => return Ok(()), }; self.write_type(base)?; - self.write_array_size(size)?; + self.write_array_size(base, size)?; write!(self.out, "(")?; for _ in 1..count { self.write_zero_init_value(base)?; diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 978b07388..547b7632f 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; + use super::Error; impl crate::ScalarKind { @@ -35,6 +37,79 @@ impl crate::TypeInner { _ => false, } } + + pub(super) fn try_size_hlsl( + &self, + types: &crate::UniqueArena, + constants: &crate::Arena, + ) -> Result { + Ok(match *self { + Self::Matrix { + columns, + rows, + width, + } => { + let aligned_rows = if rows > crate::VectorSize::Bi { 4 } else { 2 }; + let stride = aligned_rows * width as u32; + let last_row_size = rows as u32 * width as u32; + ((columns as u32 - 1) * stride) + last_row_size + } + Self::Array { base, size, stride } => { + let count = match size { + crate::ArraySize::Constant(handle) => { + let constant = constants.try_get(handle)?; + constant.to_array_length().unwrap_or(1) + } + // A dynamically-sized array has to have at least one element + crate::ArraySize::Dynamic => 1, + }; + let last_el_size = types[base].inner.try_size_hlsl(types, constants)?; + ((count - 1) * stride) + last_el_size + } + _ => self.try_size(constants)?, + }) + } + + /// Used to generate the name of the wrapped type constructor + pub(super) fn hlsl_type_id<'a>( + &self, + base: crate::Handle, + types: &crate::UniqueArena, + constants: &crate::Arena, + names: &'a crate::FastHashMap, + ) -> Result, Error> { + Ok(match types[base].inner { + crate::TypeInner::Scalar { kind, width } => Cow::Borrowed(kind.to_hlsl_str(width)?), + crate::TypeInner::Vector { size, kind, width } => Cow::Owned(format!( + "{}{}", + kind.to_hlsl_str(width)?, + crate::back::vector_size_str(size) + )), + crate::TypeInner::Matrix { + columns, + rows, + width, + } => Cow::Owned(format!( + "{}{}x{}", + crate::ScalarKind::Float.to_hlsl_str(width)?, + crate::back::vector_size_str(columns), + crate::back::vector_size_str(rows), + )), + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(size), + .. + } => Cow::Owned(format!( + "array{}_{}_", + constants[size].to_array_length().unwrap(), + self.hlsl_type_id(base, types, constants, names)? + )), + crate::TypeInner::Struct { .. } => { + Cow::Borrowed(&names[&crate::proc::NameKey::Type(base)]) + } + _ => unreachable!(), + }) + } } impl crate::StorageFormat { diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index c652a1d6e..78e87cbd4 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -26,7 +26,7 @@ int dim_1d = NagaDimensions1D(image_1d); ``` */ -use super::{super::FunctionCtx, BackendResult, Error}; +use super::{super::FunctionCtx, BackendResult}; use crate::{arena::Handle, proc::NameKey}; use std::fmt::Write; @@ -350,9 +350,15 @@ impl<'a, W: Write> super::Writer<'a, W> { pub(super) fn write_wrapped_constructor_function_name( &mut self, + module: &crate::Module, constructor: WrappedConstructor, ) -> BackendResult { - let name = &self.names[&NameKey::Type(constructor.ty)]; + let name = module.types[constructor.ty].inner.hlsl_type_id( + constructor.ty, + &module.types, + &module.constants, + &self.names, + )?; write!(self.out, "Construct{}", name)?; Ok(()) } @@ -369,69 +375,114 @@ impl<'a, W: Write> super::Writer<'a, W> { const RETURN_VARIABLE_NAME: &str = "ret"; // Write function return type and name - let struct_name = &self.names[&NameKey::Type(constructor.ty)]; - write!(self.out, "{} ", struct_name)?; - self.write_wrapped_constructor_function_name(constructor)?; + self.write_type(module, constructor.ty)?; + write!(self.out, " ")?; + self.write_wrapped_constructor_function_name(module, constructor)?; // Write function parameters write!(self.out, "(")?; - let members = match module.types[constructor.ty].inner { - crate::TypeInner::Struct { ref members, .. } => members, - _ => return Err(Error::Unimplemented("non-struct constructor".to_string())), - }; - for (i, member) in members.iter().enumerate() { + + let mut write_arg = |i, ty| -> BackendResult { if i != 0 { write!(self.out, ", ")?; } - self.write_type(module, member.ty)?; + self.write_type(module, ty)?; write!(self.out, " {}{}", ARGUMENT_VARIABLE_NAME, i)?; - if let crate::TypeInner::Array { size, .. } = module.types[member.ty].inner { - self.write_array_size(module, size)?; + if let crate::TypeInner::Array { base, size, .. } = module.types[ty].inner { + self.write_array_size(module, base, size)?; } + Ok(()) + }; + + match module.types[constructor.ty].inner { + crate::TypeInner::Struct { ref members, .. } => { + for (i, member) in members.iter().enumerate() { + write_arg(i, member.ty)?; + } + } + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(size), + .. + } => { + let count = module.constants[size].to_array_length().unwrap(); + for i in 0..count as usize { + write_arg(i, base)?; + } + } + _ => unreachable!(), + }; + + write!(self.out, ")")?; + + if let crate::TypeInner::Array { base, size, .. } = module.types[constructor.ty].inner { + self.write_array_size(module, base, size)?; } + // Write function body - writeln!(self.out, ") {{")?; + writeln!(self.out, " {{")?; - let struct_name = &self.names[&NameKey::Type(constructor.ty)]; - writeln!( - self.out, - "{}{} {};", - INDENT, struct_name, RETURN_VARIABLE_NAME - )?; - for i in 0..members.len() as u32 { - let member = &members[i as usize]; + match module.types[constructor.ty].inner { + crate::TypeInner::Struct { ref members, .. } => { + let struct_name = &self.names[&NameKey::Type(constructor.ty)]; + writeln!( + self.out, + "{}{} {};", + INDENT, struct_name, RETURN_VARIABLE_NAME + )?; + for (i, member) in members.iter().enumerate() { + let field_name = &self.names[&NameKey::StructMember(constructor.ty, i as u32)]; - let field_name = &self.names[&NameKey::StructMember(constructor.ty, i)]; - - match module.types[member.ty].inner { - crate::TypeInner::Matrix { - columns, - rows: crate::VectorSize::Bi, - .. - } if member.binding.is_none() => { - for j in 0..columns as u8 { - writeln!( - self.out, - "{}{}.{}_{} = {}{}[{}];", - INDENT, - RETURN_VARIABLE_NAME, - field_name, - j, - ARGUMENT_VARIABLE_NAME, - i, - j - )?; + match module.types[member.ty].inner { + crate::TypeInner::Matrix { + columns, + rows: crate::VectorSize::Bi, + .. + } if member.binding.is_none() => { + for j in 0..columns as u8 { + writeln!( + self.out, + "{}{}.{}_{} = {}{}[{}];", + INDENT, + RETURN_VARIABLE_NAME, + field_name, + j, + ARGUMENT_VARIABLE_NAME, + i, + j + )?; + } + } + _ => { + writeln!( + self.out, + "{}{}.{} = {}{};", + INDENT, RETURN_VARIABLE_NAME, field_name, ARGUMENT_VARIABLE_NAME, i, + )?; + } } } - _ => { - //TODO: handle arrays? - writeln!( - self.out, - "{}{}.{} = {}{};", - INDENT, RETURN_VARIABLE_NAME, field_name, ARGUMENT_VARIABLE_NAME, i, - )?; - } } + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(size), + .. + } => { + write!(self.out, "{}", INDENT)?; + self.write_type(module, base)?; + write!(self.out, " {}", RETURN_VARIABLE_NAME)?; + self.write_array_size(module, base, crate::ArraySize::Constant(size))?; + write!(self.out, " = {{ ")?; + let count = module.constants[size].to_array_length().unwrap(); + for i in 0..count { + if i != 0 { + write!(self.out, ", ")?; + } + write!(self.out, "{}{}", ARGUMENT_VARIABLE_NAME, i)?; + } + writeln!(self.out, " }};",)?; + } + _ => unreachable!(), } // Write return value @@ -831,7 +882,9 @@ impl<'a, W: Write> super::Writer<'a, W> { } crate::Expression::Compose { ty, components: _ } => { let constructor = match module.types[ty].inner { - crate::TypeInner::Struct { .. } => WrappedConstructor { ty }, + crate::TypeInner::Struct { .. } | crate::TypeInner::Array { .. } => { + WrappedConstructor { ty } + } _ => continue, }; if !self.wrapped.constructors.contains(&constructor) { @@ -887,6 +940,33 @@ impl<'a, W: Write> super::Writer<'a, W> { Ok(()) } + pub(super) fn write_wrapped_constructor_function_for_constant( + &mut self, + module: &crate::Module, + constant: &crate::Constant, + ) -> BackendResult { + if let crate::ConstantInner::Composite { ty, ref components } = constant.inner { + match module.types[ty].inner { + crate::TypeInner::Struct { .. } | crate::TypeInner::Array { .. } => { + let constructor = WrappedConstructor { ty }; + if !self.wrapped.constructors.contains(&constructor) { + self.write_wrapped_constructor_function(module, constructor)?; + self.wrapped.constructors.insert(constructor); + } + } + _ => {} + } + for constant in components { + self.write_wrapped_constructor_function_for_constant( + module, + &module.constants[*constant], + )?; + } + } + + Ok(()) + } + pub(super) fn write_texture_coordinates( &mut self, kind: &str, diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index cab351aa5..cea989dee 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -307,7 +307,7 @@ impl super::Writer<'_, W> { self.write_value_type(module, &module.types[base].inner)?; let depth = level.next().0; write!(self.out, " {}{}", STORE_TEMP_NAME, depth)?; - self.write_array_size(module, crate::ArraySize::Constant(const_handle))?; + self.write_array_size(module, base, crate::ArraySize::Constant(const_handle))?; write!(self.out, " = ")?; self.write_store_value(module, &value, func_ctx)?; writeln!(self.out, ";")?; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index b514d1155..b3e61e7f5 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -152,7 +152,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write all structs for (handle, ty) in module.types.iter() { - if let TypeInner::Struct { ref members, .. } = ty.inner { + if let TypeInner::Struct { ref members, span } = ty.inner { if let Some(member) = members.last() { if let TypeInner::Array { size: crate::ArraySize::Dynamic, @@ -176,12 +176,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { module, handle, members, + span, ep_result.map(|r| (r.0, Io::Output)), )?; writeln!(self.out)?; } } + // Write wrapped constructor functions used in constants + for (_, constant) in module.constants.iter() { + self.write_wrapped_constructor_function_for_constant(module, constant)?; + } + // Write all globals for (ty, _) in module.global_variables.iter() { self.write_global(module, ty)?; @@ -525,8 +531,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let arg_name = &self.names[&NameKey::EntryPointArgument(ep_index, arg_index as u32)]; write!(self.out, " {}", arg_name)?; match module.types[arg.ty].inner { - TypeInner::Array { size, .. } => { - self.write_array_size(module, size)?; + TypeInner::Array { base, size, .. } => { + self.write_array_size(module, base, size)?; let fake_member = fake_iter.next().unwrap(); writeln!(self.out, " = {}.{};", ep_input.arg_name, fake_member.name)?; } @@ -631,8 +637,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; } else { // need to write the array size if the type was emitted with `write_type` - if let TypeInner::Array { size, .. } = module.types[global.ty].inner { - self.write_array_size(module, size)?; + if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner { + self.write_array_size(module, base, size)?; } if global.space == crate::AddressSpace::Private { write!(self.out, " = ")?; @@ -650,8 +656,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let sub_name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, " {}", sub_name)?; // need to write the array size if the type was emitted with `write_type` - if let TypeInner::Array { size, .. } = module.types[global.ty].inner { - self.write_array_size(module, size)?; + if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner { + self.write_array_size(module, base, size)?; } writeln!(self.out, "; }}")?; } else { @@ -713,6 +719,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { pub(super) fn write_array_size( &mut self, module: &Module, + base: Handle, size: crate::ArraySize, ) -> BackendResult { write!(self.out, "[")?; @@ -729,6 +736,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } write!(self.out, "]")?; + + if let TypeInner::Array { + base: next_base, + size: next_size, + .. + } = module.types[base].inner + { + self.write_array_size(module, next_base, next_size)?; + } + Ok(()) } @@ -741,6 +758,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { module: &Module, handle: Handle, members: &[crate::StructMember], + span: u32, shader_stage: Option<(ShaderStage, Io)>, ) -> BackendResult { // Write struct name @@ -759,7 +777,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } let ty_inner = &module.types[member.ty].inner; - last_offset = member.offset + ty_inner.size(&module.constants); + last_offset = member.offset + + ty_inner + .try_size_hlsl(&module.types, &module.constants) + .unwrap(); // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; @@ -782,7 +803,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { &self.names[&NameKey::StructMember(handle, index as u32)] )?; // Write [size] - self.write_array_size(module, size)?; + self.write_array_size(module, base, size)?; } // We treat matrices of the form `matCx2` as a sequence of C `vec2`s // (see top level module docs for details). @@ -832,6 +853,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, ";")?; } + // add padding at the end since sizes of types don't get rounded up to their alignment in HLSL + if members.last().unwrap().binding.is_none() && span > last_offset { + let padding = (span - last_offset) / 4; + for i in 0..padding { + writeln!(self.out, "{}int _end_pad_{};", back::INDENT, i)?; + } + } + writeln!(self.out, "}};")?; Ok(()) } @@ -904,8 +933,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // HLSL arrays are written as `type name[size]` // Current code is written arrays only as `[size]` // Base `type` and `name` should be written outside - TypeInner::Array { size, .. } => { - self.write_array_size(module, size)?; + TypeInner::Array { base, size, .. } => { + self.write_array_size(module, base, size)?; } _ => { return Err(Error::Unimplemented(format!( @@ -989,8 +1018,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write argument name. Space is important. write!(self.out, " {}", argument_name)?; - if let TypeInner::Array { size, .. } = module.types[arg.ty].inner { - self.write_array_size(module, size)?; + if let TypeInner::Array { base, size, .. } = module.types[arg.ty].inner { + self.write_array_size(module, base, size)?; } } } @@ -1009,8 +1038,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)]; write!(self.out, " {}", argument_name)?; - if let TypeInner::Array { size, .. } = module.types[arg.ty].inner { - self.write_array_size(module, size)?; + if let TypeInner::Array { base, size, .. } = module.types[arg.ty].inner { + self.write_array_size(module, base, size)?; } if let Some(ref binding) = arg.binding { @@ -1053,8 +1082,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_type(module, local.ty)?; write!(self.out, " {}", self.names[&func_ctx.name_key(handle)])?; // Write size for array type - if let TypeInner::Array { size, .. } = module.types[local.ty].inner { - self.write_array_size(module, size)?; + if let TypeInner::Array { base, size, .. } = module.types[local.ty].inner { + self.write_array_size(module, base, size)?; } write!(self.out, " = ")?; @@ -1706,19 +1735,19 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::Compose { ty, ref components } => { - let (brace_open, brace_close) = match module.types[ty].inner { - TypeInner::Struct { .. } => { - self.write_wrapped_constructor_function_name(WrappedConstructor { ty })?; - ("(", ")") + match module.types[ty].inner { + TypeInner::Struct { .. } | TypeInner::Array { .. } => { + self.write_wrapped_constructor_function_name( + module, + WrappedConstructor { ty }, + )?; } - TypeInner::Array { .. } => ("{ ", " }"), _ => { self.write_type(module, ty)?; - ("(", ")") } }; - write!(self.out, "{}", brace_open)?; + write!(self.out, "(")?; for (index, &component) in components.iter().enumerate() { if index != 0 { @@ -1728,7 +1757,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, component, func_ctx)?; } - write!(self.out, "{}", brace_close)?; + write!(self.out, ")")?; } // All of the multiplication can be expressed as `mul`, // except vector * vector, which needs to use the "*" operator. @@ -2324,15 +2353,15 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ty: Handle, components: &[Handle], ) -> BackendResult { - let (open_b, close_b) = match module.types[ty].inner { - TypeInner::Array { .. } | TypeInner::Struct { .. } => ("{ ", " }"), + match module.types[ty].inner { + TypeInner::Struct { .. } | TypeInner::Array { .. } => { + self.write_wrapped_constructor_function_name(module, WrappedConstructor { ty })?; + } _ => { - // We should write type only for non struct/array constants self.write_type(module, ty)?; - ("(", ")") } }; - write!(self.out, "{}", open_b)?; + write!(self.out, "(")?; for (index, constant) in components.iter().enumerate() { self.write_constant(module, *constant)?; // Only write a comma if isn't the last element @@ -2341,7 +2370,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ", ")?; } } - write!(self.out, "{}", close_b)?; + write!(self.out, ")")?; Ok(()) } @@ -2392,8 +2421,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, " {}", name)?; // If rhs is a array type, we should write array size - if let TypeInner::Array { size, .. } = *resolved { - self.write_array_size(module, size)?; + if let TypeInner::Array { base, size, .. } = *resolved { + self.write_array_size(module, base, size)?; } write!(self.out, " = ")?; self.write_expr(module, handle, ctx)?; diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index a034fdda7..e64ef2152 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -54,6 +54,10 @@ fn read_from_private(foo: ptr) -> f32 { return *foo; } +fn test_arr_as_arg(a: array, 5>) -> f32 { + return a[4][9]; +} + @stage(vertex) fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32 = 0.0; @@ -79,6 +83,8 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { c[vi + 1u] = 42; let value = c[vi]; + var _ = test_arr_as_arg(array, 5>()); + return vec4(matrix * vec4(vec4(value)), 2.0); } diff --git a/tests/in/padding.param.ron b/tests/in/padding.param.ron new file mode 100644 index 000000000..9e20176ba --- /dev/null +++ b/tests/in/padding.param.ron @@ -0,0 +1,22 @@ +( + spv: ( + version: (1, 1), + debug: true, + adjust_coordinate_space: false, + ), + msl: ( + lang_version: (2, 0), + per_stage_map: ( + vs: ( + resources: { + (group: 0, binding: 0): (buffer: Some(0), mutable: false), + (group: 0, binding: 1): (buffer: Some(1), mutable: false), + (group: 0, binding: 2): (buffer: Some(2), mutable: false), + }, + ), + ), + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + ), +) diff --git a/tests/in/padding.wgsl b/tests/in/padding.wgsl new file mode 100644 index 000000000..0ff60f393 --- /dev/null +++ b/tests/in/padding.wgsl @@ -0,0 +1,33 @@ +struct S { + a: vec3, +} + +struct Test { + a: S, + b: f32, // offset: 16 +} + +struct Test2 { + a: array, 2>, + b: f32, // offset: 32 +} + +struct Test3 { + a: mat4x3, + b: f32, // offset: 64 +} + +@group(0) @binding(0) +var input: Test; + +@group(0) @binding(1) +var input2: Test2; + +@group(0) @binding(2) +var input3: Test3; + + +@stage(vertex) +fn vertex() -> @builtin(position) vec4 { + return vec4(1.0) * input.b * input2.b * input3.b; +} \ No newline at end of file diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index ff67b1b98..2b92925a0 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -25,6 +25,10 @@ float read_from_private(inout float foo_1) { return _e3; } +float test_arr_as_arg(float a[5][10]) { + return a[4][9]; +} + void main() { int tmp = 0; int value = _group_0_binding_0_cs.atom; diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index b7c62d40e..e07dad7a0 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -24,6 +24,10 @@ float read_from_private(inout float foo_1) { return _e3; } +float test_arr_as_arg(float a[5][10]) { + return a[4][9]; +} + void main() { _group_0_binding_0_fs.matrix[1][2] = 1.0; _group_0_binding_0_fs.matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index b01479c24..c545e4428 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -22,35 +22,35 @@ uniform Baz_block_1Vertex { Baz _group_0_binding_1_vs; }; void test_matrix_within_struct_accesses() { int idx = 9; - mat3x2 unnamed = mat3x2(0.0); - vec2 unnamed_1 = vec2(0.0); + mat3x2 unnamed_1 = mat3x2(0.0); vec2 unnamed_2 = vec2(0.0); - float unnamed_3 = 0.0; + vec2 unnamed_3 = vec2(0.0); float unnamed_4 = 0.0; float unnamed_5 = 0.0; float unnamed_6 = 0.0; + float unnamed_7 = 0.0; Baz t = Baz(mat3x2(0.0)); int _e4 = idx; idx = (_e4 - 1); mat3x2 _e8 = _group_0_binding_1_vs.m; - unnamed = _e8; + unnamed_1 = _e8; vec2 _e13 = _group_0_binding_1_vs.m[0]; - unnamed_1 = _e13; + unnamed_2 = _e13; int _e16 = idx; vec2 _e18 = _group_0_binding_1_vs.m[_e16]; - unnamed_2 = _e18; + unnamed_3 = _e18; float _e25 = _group_0_binding_1_vs.m[0][1]; - unnamed_3 = _e25; + unnamed_4 = _e25; int _e30 = idx; float _e32 = _group_0_binding_1_vs.m[0][_e30]; - unnamed_4 = _e32; + unnamed_5 = _e32; int _e35 = idx; float _e39 = _group_0_binding_1_vs.m[_e35][1]; - unnamed_5 = _e39; + unnamed_6 = _e39; int _e42 = idx; int _e44 = idx; float _e46 = _group_0_binding_1_vs.m[_e42][_e44]; - unnamed_6 = _e46; + unnamed_7 = _e46; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); int _e57 = idx; idx = (_e57 + 1); @@ -74,21 +74,28 @@ float read_from_private(inout float foo_1) { return _e3; } +float test_arr_as_arg(float a[5][10]) { + return a[4][9]; +} + void main() { uint vi = uint(gl_VertexID); float foo = 0.0; int c[5] = int[5](0, 0, 0, 0, 0); + float unnamed = 0.0; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); mat4x3 matrix = _group_0_binding_0_vs.matrix; uvec2 arr[2] = _group_0_binding_0_vs.arr; float b = _group_0_binding_0_vs.matrix[3][0]; - int a = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; + int a_1 = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; float _e28 = read_from_private(foo); - c = int[5](a, int(b), 3, 4, 5); + c = int[5](a_1, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; + float _e42 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + unnamed = _e42; gl_Position = vec4((matrix * vec4(ivec4(value))), 2.0); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; diff --git a/tests/out/glsl/padding.vertex.Vertex.glsl b/tests/out/glsl/padding.vertex.Vertex.glsl new file mode 100644 index 000000000..21a231a37 --- /dev/null +++ b/tests/out/glsl/padding.vertex.Vertex.glsl @@ -0,0 +1,36 @@ +#version 310 es + +precision highp float; +precision highp int; + +struct S { + vec3 a; +}; +struct Test { + S a; + float b; +}; +struct Test2_ { + vec3 a[2]; + float b; +}; +struct Test3_ { + mat4x3 a; + float b; +}; +uniform Test_block_0Vertex { Test _group_0_binding_0_vs; }; + +uniform Test2__block_1Vertex { Test2_ _group_0_binding_1_vs; }; + +uniform Test3__block_2Vertex { Test3_ _group_0_binding_2_vs; }; + + +void main() { + float _e6 = _group_0_binding_0_vs.b; + float _e9 = _group_0_binding_1_vs.b; + float _e12 = _group_0_binding_2_vs.b; + gl_Position = (((vec4(1.0) * _e6) * _e9) * _e12); + gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); + return; +} + diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 7f63c78d8..4a807a49f 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -1,12 +1,23 @@ struct AlignedWrapper { int value; + int _end_pad_0; }; struct Baz { float2 m_0; float2 m_1; float2 m_2; }; +float Constructarray10_float_(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5, float arg6, float arg7, float arg8, float arg9)[10] { + float ret[10] = { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 }; + return ret; +} + +float Constructarray5_array10_float__(float arg0[10], float arg1[10], float arg2[10], float arg3[10], float arg4[10])[5][10] { + float ret[5][10] = { arg0, arg1, arg2, arg3, arg4 }; + return ret; +} + RWByteAddressBuffer bar : register(u0); cbuffer baz : register(b1) { Baz baz; } @@ -47,36 +58,36 @@ Baz ConstructBaz(float3x2 arg0) { void test_matrix_within_struct_accesses() { int idx = 9; - float3x2 unnamed = (float3x2)0; - float2 unnamed_1 = (float2)0; + float3x2 unnamed_1 = (float3x2)0; float2 unnamed_2 = (float2)0; - float unnamed_3 = (float)0; + float2 unnamed_3 = (float2)0; float unnamed_4 = (float)0; float unnamed_5 = (float)0; float unnamed_6 = (float)0; + float unnamed_7 = (float)0; Baz t = (Baz)0; int _expr4 = idx; idx = (_expr4 - 1); float3x2 _expr8 = GetMatmOnBaz(baz); - unnamed = _expr8; + unnamed_1 = _expr8; float2 _expr13 = GetMatmOnBaz(baz)[0]; - unnamed_1 = _expr13; + unnamed_2 = _expr13; int _expr16 = idx; float2 _expr18 = GetMatmOnBaz(baz)[_expr16]; - unnamed_2 = _expr18; + unnamed_3 = _expr18; float _expr25 = GetMatmOnBaz(baz)[0][1]; - unnamed_3 = _expr25; + unnamed_4 = _expr25; int _expr30 = idx; float _expr32 = GetMatmOnBaz(baz)[0][_expr30]; - unnamed_4 = _expr32; + unnamed_5 = _expr32; int _expr35 = idx; float _expr39 = GetMatmOnBaz(baz)[_expr35][1]; - unnamed_5 = _expr39; + unnamed_6 = _expr39; int _expr42 = idx; int _expr44 = idx; float _expr46 = GetMatmOnBaz(baz)[_expr42][_expr44]; - unnamed_6 = _expr46; + unnamed_7 = _expr46; t = ConstructBaz(float3x2(float2(1.0.xx), float2(2.0.xx), float2(3.0.xx))); int _expr57 = idx; idx = (_expr57 + 1); @@ -101,6 +112,11 @@ float read_from_private(inout float foo_1) return _expr3; } +float test_arr_as_arg(float a[5][10]) +{ + return a[4][9]; +} + uint NagaBufferLengthRW(RWByteAddressBuffer buffer) { uint ret; @@ -108,10 +124,16 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer) return ret; } +int Constructarray5_int_(int arg0, int arg1, int arg2, int arg3, int arg4)[5] { + int ret[5] = { arg0, arg1, arg2, arg3, arg4 }; + return ret; +} + float4 foo_vert(uint vi : SV_VertexID) : SV_Position { float foo = 0.0; int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; + float unnamed = (float)0; float baz_1 = foo; foo = 1.0; @@ -119,17 +141,24 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position float4x3 matrix_ = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); - int a = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); + int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); const float _e28 = read_from_private(foo); { - int _result[5]={ a, int(b), 3, 4, 5 }; + int _result[5]=Constructarray5_int_(a_1, int(b), 3, 4, 5); for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; } c[(vi + 1u)] = 42; int value = c[vi]; + const float _e42 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + unnamed = _e42; return float4(mul(float4(int4(value.xxxx)), matrix_), 2.0); } +uint2 Constructarray2_uint2_(uint2 arg0, uint2 arg1)[2] { + uint2 ret[2] = { arg0, arg1 }; + return ret; +} + float4 foo_frag() : SV_Target0 { bar.Store(8+16+0, asuint(1.0)); @@ -141,7 +170,7 @@ float4 foo_frag() : SV_Target0 bar.Store3(0+48, asuint(_value2[3])); } { - uint2 _value2[2] = { uint2(0u.xx), uint2(1u.xx) }; + uint2 _value2[2] = Constructarray2_uint2_(uint2(0u.xx), uint2(1u.xx)); bar.Store2(104+0, asuint(_value2[0])); bar.Store2(104+8, asuint(_value2[1])); } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 08aed4f93..984d519f9 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -6,8 +6,23 @@ static const int4 v_i32_one = int4(1, 1, 1, 1); struct Foo { float4 a; int b; + int _end_pad_0; + int _end_pad_1; + int _end_pad_2; }; +Foo ConstructFoo(float4 arg0, int arg1) { + Foo ret; + ret.a = arg0; + ret.b = arg1; + return ret; +} + +Foo Constructarray3_Foo_(Foo arg0, Foo arg1, Foo arg2)[3] { + Foo ret[3] = { arg0, arg1, arg2 }; + return ret; +} + float4 builtins() { int s1_ = (true ? 1 : 0); @@ -43,10 +58,8 @@ float3 bool_cast(float3 x) return float3(y); } -Foo ConstructFoo(float4 arg0, int arg1) { - Foo ret; - ret.a = arg0; - ret.b = arg1; +int Constructarray4_int_(int arg0, int arg1, int arg2, int arg3)[4] { + int ret[4] = { arg0, arg1, arg2, arg3 }; return ret; } @@ -59,8 +72,8 @@ float constructors() float unnamed_3 = 0.0; uint2 unnamed_4 = uint2(0u, 0u); float2x2 unnamed_5 = float2x2(float2(0.0, 0.0), float2(0.0, 0.0)); - Foo unnamed_6[3] = { { float4(0.0, 0.0, 0.0, 0.0), 0 }, { float4(0.0, 0.0, 0.0, 0.0), 0 }, { float4(0.0, 0.0, 0.0, 0.0), 0 } }; - Foo unnamed_7 = { float4(0.0, 0.0, 0.0, 0.0), 0 }; + Foo unnamed_6[3] = Constructarray3_Foo_(ConstructFoo(float4(0.0, 0.0, 0.0, 0.0), 0), ConstructFoo(float4(0.0, 0.0, 0.0, 0.0), 0), ConstructFoo(float4(0.0, 0.0, 0.0, 0.0), 0)); + Foo unnamed_7 = ConstructFoo(float4(0.0, 0.0, 0.0, 0.0), 0); uint2 unnamed_8 = (uint2)0; float2x2 unnamed_9 = (float2x2)0; int unnamed_10[4] = {(int)0,(int)0,(int)0,(int)0}; @@ -71,7 +84,7 @@ float constructors() unnamed_8 = uint2(0u.xx); unnamed_9 = float2x2(float2(0.0.xx), float2(0.0.xx)); { - int _result[4]={ 0, 1, 2, 3 }; + int _result[4]=Constructarray4_int_(0, 1, 2, 3); for(int _i=0; _i<4; ++_i) unnamed_10[_i] = _result[_i]; } float _expr70 = foo.a.x; diff --git a/tests/out/hlsl/padding.hlsl b/tests/out/hlsl/padding.hlsl new file mode 100644 index 000000000..2bf074c06 --- /dev/null +++ b/tests/out/hlsl/padding.hlsl @@ -0,0 +1,43 @@ + +struct S { + float3 a; + int _end_pad_0; +}; + +struct Test { + S a; + float b; + int _end_pad_0; + int _end_pad_1; + int _end_pad_2; +}; + +struct Test2_ { + float3 a[2]; + int _pad1_0; + float b; + int _end_pad_0; + int _end_pad_1; + int _end_pad_2; +}; + +struct Test3_ { + row_major float4x3 a; + int _pad1_0; + float b; + int _end_pad_0; + int _end_pad_1; + int _end_pad_2; +}; + +cbuffer input : register(b0) { Test input; } +cbuffer input2_ : register(b1) { Test2_ input2_; } +cbuffer input3_ : register(b2) { Test3_ input3_; } + +float4 vertex() : SV_Position +{ + float _expr6 = input.b; + float _expr9 = input2_.b; + float _expr12 = input3_.b; + return (((float4(1.0.xxxx) * _expr6) * _expr9) * _expr12); +} diff --git a/tests/out/hlsl/padding.hlsl.config b/tests/out/hlsl/padding.hlsl.config new file mode 100644 index 000000000..875a4fa4a --- /dev/null +++ b/tests/out/hlsl/padding.hlsl.config @@ -0,0 +1,3 @@ +vertex=(vertex:vs_5_1 ) +fragment=() +compute=() diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index a02dde77f..9f5e08200 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -11,9 +11,23 @@ struct type_9 { float4 gl_Position : SV_Position; }; +float Constructarray1_float_(float arg0)[1] { + float ret[1] = { arg0 }; + return ret; +} + +gl_PerVertex Constructgl_PerVertex(float4 arg0, float arg1, float arg2[1], float arg3[1]) { + gl_PerVertex ret; + ret.gl_Position = arg0; + ret.gl_PointSize = arg1; + ret.gl_ClipDistance = arg2; + ret.gl_CullDistance = arg3; + return ret; +} + static float2 v_uv = (float2)0; static float2 a_uv_1 = (float2)0; -static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, { 0.0 }, { 0.0 } }; +static gl_PerVertex perVertexStruct = Constructgl_PerVertex(float4(0.0, 0.0, 0.0, 1.0), 1.0, Constructarray1_float_(0.0), Constructarray1_float_(0.0)); static float2 a_pos_1 = (float2)0; struct VertexOutput_main { diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 0f3b5cb12..a791ee6ab 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -29,43 +29,51 @@ struct Bar { struct Baz { metal::float3x2 m; }; -struct type_15 { +struct type_12 { + float inner[10]; +}; +struct type_13 { + type_12 inner[5]; +}; +struct type_17 { int inner[5]; }; +constant type_12 const_type_12_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; +constant type_13 const_type_13_ = {const_type_12_, const_type_12_, const_type_12_, const_type_12_, const_type_12_}; void test_matrix_within_struct_accesses( constant Baz& baz ) { int idx = 9; - metal::float3x2 unnamed; - metal::float2 unnamed_1; + metal::float3x2 unnamed_1; metal::float2 unnamed_2; - float unnamed_3; + metal::float2 unnamed_3; float unnamed_4; float unnamed_5; float unnamed_6; + float unnamed_7; Baz t; int _e4 = idx; idx = _e4 - 1; metal::float3x2 _e8 = baz.m; - unnamed = _e8; + unnamed_1 = _e8; metal::float2 _e13 = baz.m[0]; - unnamed_1 = _e13; + unnamed_2 = _e13; int _e16 = idx; metal::float2 _e18 = baz.m[_e16]; - unnamed_2 = _e18; + unnamed_3 = _e18; float _e25 = baz.m[0].y; - unnamed_3 = _e25; + unnamed_4 = _e25; int _e30 = idx; float _e32 = baz.m[0][_e30]; - unnamed_4 = _e32; + unnamed_5 = _e32; int _e35 = idx; float _e39 = baz.m[_e35].y; - unnamed_5 = _e39; + unnamed_6 = _e39; int _e42 = idx; int _e44 = idx; float _e46 = baz.m[_e42][_e44]; - unnamed_6 = _e46; + unnamed_7 = _e46; t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; int _e57 = idx; idx = _e57 + 1; @@ -91,6 +99,12 @@ float read_from_private( return _e3; } +float test_arr_as_arg( + type_13 a +) { + return a.inner[4].inner[9]; +} + struct foo_vertInput { }; struct foo_vertOutput { @@ -103,18 +117,21 @@ vertex foo_vertOutput foo_vert( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo = 0.0; - type_15 c; + type_17 c; + float unnamed; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); metal::float4x3 matrix = bar.matrix; type_6 arr = bar.arr; float b = bar.matrix[3].x; - int a = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; + int a_1 = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; float _e28 = read_from_private(foo); - for(int _i=0; _i<5; ++_i) c.inner[_i] = type_15 {a, static_cast(b), 3, 4, 5}.inner[_i]; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type_17 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; + float _e42 = test_arr_as_arg(const_type_13_); + unnamed = _e42; return foo_vertOutput { metal::float4(matrix * static_cast(metal::int4(value)), 2.0) }; } diff --git a/tests/out/msl/padding.msl b/tests/out/msl/padding.msl new file mode 100644 index 000000000..23aef3581 --- /dev/null +++ b/tests/out/msl/padding.msl @@ -0,0 +1,38 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct S { + metal::float3 a; +}; +struct Test { + S a; + float b; +}; +struct type_2 { + metal::float3 inner[2]; +}; +struct Test2_ { + type_2 a; + float b; +}; +struct Test3_ { + metal::float4x3 a; + float b; +}; + +struct vertex_Output { + metal::float4 member [[position]]; +}; +vertex vertex_Output vertex_( + constant Test& input [[buffer(0)]] +, constant Test2_& input2_ [[buffer(1)]] +, constant Test3_& input3_ [[buffer(2)]] +) { + float _e6 = input.b; + float _e9 = input2_.b; + float _e12 = input3_.b; + return vertex_Output { ((metal::float4(1.0) * _e6) * _e9) * _e12 }; +} diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 0f8959390..41d9c1eda 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,75 +1,80 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 213 +; Bound: 227 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %137 "foo_vert" %132 %135 -OpEntryPoint Fragment %173 "foo_frag" %172 -OpEntryPoint GLCompute %190 "atomics" -OpExecutionMode %173 OriginUpperLeft -OpExecutionMode %190 LocalSize 1 1 1 +OpEntryPoint Vertex %150 "foo_vert" %145 %148 +OpEntryPoint Fragment %187 "foo_frag" %186 +OpEntryPoint GLCompute %204 "atomics" +OpExecutionMode %187 OriginUpperLeft +OpExecutionMode %204 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %31 0 "value" -OpName %31 "AlignedWrapper" -OpMemberName %40 0 "matrix" -OpMemberName %40 1 "matrix_array" -OpMemberName %40 2 "atom" -OpMemberName %40 3 "arr" -OpMemberName %40 4 "data" -OpName %40 "Bar" -OpMemberName %42 0 "m" -OpName %42 "Baz" -OpName %47 "bar" -OpName %49 "baz" -OpName %52 "idx" -OpName %54 "_" -OpName %56 "_" -OpName %58 "_" +OpMemberName %32 0 "value" +OpName %32 "AlignedWrapper" +OpMemberName %41 0 "matrix" +OpMemberName %41 1 "matrix_array" +OpMemberName %41 2 "atom" +OpMemberName %41 3 "arr" +OpMemberName %41 4 "data" +OpName %41 "Bar" +OpMemberName %43 0 "m" +OpName %43 "Baz" +OpName %52 "bar" +OpName %54 "baz" +OpName %57 "idx" OpName %59 "_" -OpName %60 "_" OpName %61 "_" -OpName %62 "_" -OpName %63 "t" -OpName %66 "test_matrix_within_struct_accesses" -OpName %123 "foo" -OpName %124 "read_from_private" +OpName %63 "_" +OpName %64 "_" +OpName %65 "_" +OpName %66 "_" +OpName %67 "_" +OpName %68 "t" +OpName %71 "test_matrix_within_struct_accesses" OpName %128 "foo" -OpName %129 "c" -OpName %132 "vi" -OpName %137 "foo_vert" -OpName %173 "foo_frag" -OpName %188 "tmp" -OpName %190 "atomics" -OpMemberDecorate %31 0 Offset 0 -OpDecorate %36 ArrayStride 16 -OpDecorate %38 ArrayStride 8 +OpName %129 "read_from_private" +OpName %134 "a" +OpName %135 "test_arr_as_arg" +OpName %140 "foo" +OpName %141 "c" +OpName %143 "_" +OpName %145 "vi" +OpName %150 "foo_vert" +OpName %187 "foo_frag" +OpName %202 "tmp" +OpName %204 "atomics" +OpMemberDecorate %32 0 Offset 0 +OpDecorate %37 ArrayStride 16 OpDecorate %39 ArrayStride 8 -OpMemberDecorate %40 0 Offset 0 -OpMemberDecorate %40 0 ColMajor -OpMemberDecorate %40 0 MatrixStride 16 -OpMemberDecorate %40 1 Offset 64 -OpMemberDecorate %40 1 ColMajor -OpMemberDecorate %40 1 MatrixStride 8 -OpMemberDecorate %40 2 Offset 96 -OpMemberDecorate %40 3 Offset 104 -OpMemberDecorate %40 4 Offset 120 -OpMemberDecorate %42 0 Offset 0 -OpMemberDecorate %42 0 ColMajor -OpMemberDecorate %42 0 MatrixStride 8 -OpDecorate %46 ArrayStride 4 -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 0 -OpDecorate %40 Block -OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 1 -OpDecorate %50 Block -OpMemberDecorate %50 0 Offset 0 -OpDecorate %132 BuiltIn VertexIndex -OpDecorate %135 BuiltIn Position -OpDecorate %172 Location 0 +OpDecorate %40 ArrayStride 8 +OpMemberDecorate %41 0 Offset 0 +OpMemberDecorate %41 0 ColMajor +OpMemberDecorate %41 0 MatrixStride 16 +OpMemberDecorate %41 1 Offset 64 +OpMemberDecorate %41 1 ColMajor +OpMemberDecorate %41 1 MatrixStride 8 +OpMemberDecorate %41 2 Offset 96 +OpMemberDecorate %41 3 Offset 104 +OpMemberDecorate %41 4 Offset 120 +OpMemberDecorate %43 0 Offset 0 +OpMemberDecorate %43 0 ColMajor +OpMemberDecorate %43 0 MatrixStride 8 +OpDecorate %45 ArrayStride 4 +OpDecorate %46 ArrayStride 40 +OpDecorate %49 ArrayStride 4 +OpDecorate %52 DescriptorSet 0 +OpDecorate %52 Binding 0 +OpDecorate %41 Block +OpDecorate %54 DescriptorSet 0 +OpDecorate %54 Binding 1 +OpDecorate %55 Block +OpMemberDecorate %55 0 Offset 0 +OpDecorate %145 BuiltIn VertexIndex +OpDecorate %148 BuiltIn Position +OpDecorate %186 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -89,245 +94,263 @@ OpDecorate %172 Location 0 %18 = OpConstant %9 20.0 %19 = OpConstant %9 30.0 %20 = OpConstant %9 40.0 -%21 = OpConstant %9 0.0 -%23 = OpTypeInt 32 0 -%22 = OpConstant %23 3 -%24 = OpConstant %23 2 -%25 = OpConstant %4 5 -%26 = OpConstant %4 3 -%27 = OpConstant %4 4 -%28 = OpConstant %23 1 -%29 = OpConstant %4 42 -%30 = OpConstant %23 0 -%31 = OpTypeStruct %4 -%33 = OpTypeVector %9 3 -%32 = OpTypeMatrix %33 4 -%35 = OpTypeVector %9 2 -%34 = OpTypeMatrix %35 2 -%36 = OpTypeArray %34 %3 -%37 = OpTypeVector %23 2 -%38 = OpTypeArray %37 %3 -%39 = OpTypeRuntimeArray %31 -%40 = OpTypeStruct %32 %36 %4 %38 %39 -%41 = OpTypeMatrix %35 3 -%42 = OpTypeStruct %41 -%43 = OpTypePointer Function %9 -%44 = OpTypeVector %9 4 -%45 = OpTypePointer StorageBuffer %4 -%46 = OpTypeArray %4 %25 -%48 = OpTypePointer StorageBuffer %40 -%47 = OpVariable %48 StorageBuffer -%50 = OpTypeStruct %42 -%51 = OpTypePointer Uniform %50 -%49 = OpVariable %51 Uniform -%53 = OpTypePointer Function %4 -%55 = OpTypePointer Function %41 -%57 = OpTypePointer Function %35 -%64 = OpTypePointer Function %42 -%67 = OpTypeFunction %2 -%68 = OpTypePointer Uniform %42 -%73 = OpTypePointer Uniform %41 -%76 = OpTypePointer Uniform %35 -%82 = OpTypePointer Uniform %9 -%107 = OpTypePointer Function %35 -%113 = OpTypePointer Function %9 -%125 = OpTypeFunction %9 %43 -%130 = OpTypePointer Function %46 -%133 = OpTypePointer Input %23 -%132 = OpVariable %133 Input -%136 = OpTypePointer Output %44 -%135 = OpVariable %136 Output -%142 = OpTypePointer StorageBuffer %32 -%145 = OpTypePointer StorageBuffer %38 -%148 = OpTypePointer StorageBuffer %33 -%149 = OpTypePointer StorageBuffer %9 -%152 = OpTypePointer StorageBuffer %39 -%155 = OpTypePointer StorageBuffer %31 -%156 = OpConstant %23 4 -%166 = OpTypeVector %4 4 -%172 = OpVariable %136 Output -%192 = OpTypePointer StorageBuffer %4 -%195 = OpConstant %23 64 -%66 = OpFunction %2 None %67 -%65 = OpLabel -%61 = OpVariable %43 Function -%58 = OpVariable %57 Function -%52 = OpVariable %53 Function %5 -%62 = OpVariable %43 Function -%59 = OpVariable %43 Function -%54 = OpVariable %55 Function -%63 = OpVariable %64 Function -%60 = OpVariable %43 Function -%56 = OpVariable %57 Function -%69 = OpAccessChain %68 %49 %30 -OpBranch %70 +%21 = OpConstant %4 10 +%22 = OpConstant %4 5 +%23 = OpConstant %4 4 +%24 = OpConstant %9 0.0 +%26 = OpTypeInt 32 0 +%25 = OpConstant %26 3 +%27 = OpConstant %26 2 +%28 = OpConstant %4 3 +%29 = OpConstant %26 1 +%30 = OpConstant %4 42 +%31 = OpConstant %26 0 +%32 = OpTypeStruct %4 +%34 = OpTypeVector %9 3 +%33 = OpTypeMatrix %34 4 +%36 = OpTypeVector %9 2 +%35 = OpTypeMatrix %36 2 +%37 = OpTypeArray %35 %3 +%38 = OpTypeVector %26 2 +%39 = OpTypeArray %38 %3 +%40 = OpTypeRuntimeArray %32 +%41 = OpTypeStruct %33 %37 %4 %39 %40 +%42 = OpTypeMatrix %36 3 +%43 = OpTypeStruct %42 +%44 = OpTypePointer Function %9 +%45 = OpTypeArray %9 %21 +%46 = OpTypeArray %45 %22 +%47 = OpTypeVector %9 4 +%48 = OpTypePointer StorageBuffer %4 +%49 = OpTypeArray %4 %22 +%50 = OpConstantComposite %45 %24 %24 %24 %24 %24 %24 %24 %24 %24 %24 +%51 = OpConstantComposite %46 %50 %50 %50 %50 %50 +%53 = OpTypePointer StorageBuffer %41 +%52 = OpVariable %53 StorageBuffer +%55 = OpTypeStruct %43 +%56 = OpTypePointer Uniform %55 +%54 = OpVariable %56 Uniform +%58 = OpTypePointer Function %4 +%60 = OpTypePointer Function %42 +%62 = OpTypePointer Function %36 +%69 = OpTypePointer Function %43 +%72 = OpTypeFunction %2 +%73 = OpTypePointer Uniform %43 +%78 = OpTypePointer Uniform %42 +%81 = OpTypePointer Uniform %36 +%87 = OpTypePointer Uniform %9 +%112 = OpTypePointer Function %36 +%118 = OpTypePointer Function %9 +%130 = OpTypeFunction %9 %44 +%136 = OpTypeFunction %9 %46 +%142 = OpTypePointer Function %49 +%146 = OpTypePointer Input %26 +%145 = OpVariable %146 Input +%149 = OpTypePointer Output %47 +%148 = OpVariable %149 Output +%155 = OpTypePointer StorageBuffer %33 +%158 = OpTypePointer StorageBuffer %39 +%161 = OpTypePointer StorageBuffer %34 +%162 = OpTypePointer StorageBuffer %9 +%165 = OpTypePointer StorageBuffer %40 +%168 = OpTypePointer StorageBuffer %32 +%169 = OpConstant %26 4 +%180 = OpTypeVector %4 4 +%186 = OpVariable %149 Output +%206 = OpTypePointer StorageBuffer %4 +%209 = OpConstant %26 64 +%71 = OpFunction %2 None %72 %70 = OpLabel -%71 = OpLoad %4 %52 -%72 = OpISub %4 %71 %6 -OpStore %52 %72 -%74 = OpAccessChain %73 %69 %30 -%75 = OpLoad %41 %74 -OpStore %54 %75 -%77 = OpAccessChain %76 %69 %30 %30 -%78 = OpLoad %35 %77 -OpStore %56 %78 -%79 = OpLoad %4 %52 -%80 = OpAccessChain %76 %69 %30 %79 -%81 = OpLoad %35 %80 -OpStore %58 %81 -%83 = OpAccessChain %82 %69 %30 %30 %28 -%84 = OpLoad %9 %83 -OpStore %59 %84 -%85 = OpLoad %4 %52 -%86 = OpAccessChain %82 %69 %30 %30 %85 -%87 = OpLoad %9 %86 -OpStore %60 %87 -%88 = OpLoad %4 %52 -%89 = OpAccessChain %82 %69 %30 %88 %28 -%90 = OpLoad %9 %89 -OpStore %61 %90 -%91 = OpLoad %4 %52 -%92 = OpLoad %4 %52 -%93 = OpAccessChain %82 %69 %30 %91 %92 -%94 = OpLoad %9 %93 -OpStore %62 %94 -%95 = OpCompositeConstruct %35 %8 %8 -%96 = OpCompositeConstruct %35 %10 %10 -%97 = OpCompositeConstruct %35 %11 %11 -%98 = OpCompositeConstruct %41 %95 %96 %97 -%99 = OpCompositeConstruct %42 %98 -OpStore %63 %99 -%100 = OpLoad %4 %52 -%101 = OpIAdd %4 %100 %6 -OpStore %52 %101 -%102 = OpCompositeConstruct %35 %12 %12 -%103 = OpCompositeConstruct %35 %13 %13 -%104 = OpCompositeConstruct %35 %14 %14 -%105 = OpCompositeConstruct %41 %102 %103 %104 -%106 = OpAccessChain %55 %63 %30 -OpStore %106 %105 -%108 = OpCompositeConstruct %35 %15 %15 -%109 = OpAccessChain %107 %63 %30 %30 -OpStore %109 %108 -%110 = OpLoad %4 %52 -%111 = OpCompositeConstruct %35 %16 %16 -%112 = OpAccessChain %107 %63 %30 %110 -OpStore %112 %111 -%114 = OpAccessChain %113 %63 %30 %30 %28 -OpStore %114 %17 -%115 = OpLoad %4 %52 -%116 = OpAccessChain %113 %63 %30 %30 %115 -OpStore %116 %18 -%117 = OpLoad %4 %52 -%118 = OpAccessChain %113 %63 %30 %117 %28 -OpStore %118 %19 -%119 = OpLoad %4 %52 -%120 = OpLoad %4 %52 -%121 = OpAccessChain %113 %63 %30 %119 %120 -OpStore %121 %20 +%66 = OpVariable %44 Function +%63 = OpVariable %62 Function +%57 = OpVariable %58 Function %5 +%67 = OpVariable %44 Function +%64 = OpVariable %44 Function +%59 = OpVariable %60 Function +%68 = OpVariable %69 Function +%65 = OpVariable %44 Function +%61 = OpVariable %62 Function +%74 = OpAccessChain %73 %54 %31 +OpBranch %75 +%75 = OpLabel +%76 = OpLoad %4 %57 +%77 = OpISub %4 %76 %6 +OpStore %57 %77 +%79 = OpAccessChain %78 %74 %31 +%80 = OpLoad %42 %79 +OpStore %59 %80 +%82 = OpAccessChain %81 %74 %31 %31 +%83 = OpLoad %36 %82 +OpStore %61 %83 +%84 = OpLoad %4 %57 +%85 = OpAccessChain %81 %74 %31 %84 +%86 = OpLoad %36 %85 +OpStore %63 %86 +%88 = OpAccessChain %87 %74 %31 %31 %29 +%89 = OpLoad %9 %88 +OpStore %64 %89 +%90 = OpLoad %4 %57 +%91 = OpAccessChain %87 %74 %31 %31 %90 +%92 = OpLoad %9 %91 +OpStore %65 %92 +%93 = OpLoad %4 %57 +%94 = OpAccessChain %87 %74 %31 %93 %29 +%95 = OpLoad %9 %94 +OpStore %66 %95 +%96 = OpLoad %4 %57 +%97 = OpLoad %4 %57 +%98 = OpAccessChain %87 %74 %31 %96 %97 +%99 = OpLoad %9 %98 +OpStore %67 %99 +%100 = OpCompositeConstruct %36 %8 %8 +%101 = OpCompositeConstruct %36 %10 %10 +%102 = OpCompositeConstruct %36 %11 %11 +%103 = OpCompositeConstruct %42 %100 %101 %102 +%104 = OpCompositeConstruct %43 %103 +OpStore %68 %104 +%105 = OpLoad %4 %57 +%106 = OpIAdd %4 %105 %6 +OpStore %57 %106 +%107 = OpCompositeConstruct %36 %12 %12 +%108 = OpCompositeConstruct %36 %13 %13 +%109 = OpCompositeConstruct %36 %14 %14 +%110 = OpCompositeConstruct %42 %107 %108 %109 +%111 = OpAccessChain %60 %68 %31 +OpStore %111 %110 +%113 = OpCompositeConstruct %36 %15 %15 +%114 = OpAccessChain %112 %68 %31 %31 +OpStore %114 %113 +%115 = OpLoad %4 %57 +%116 = OpCompositeConstruct %36 %16 %16 +%117 = OpAccessChain %112 %68 %31 %115 +OpStore %117 %116 +%119 = OpAccessChain %118 %68 %31 %31 %29 +OpStore %119 %17 +%120 = OpLoad %4 %57 +%121 = OpAccessChain %118 %68 %31 %31 %120 +OpStore %121 %18 +%122 = OpLoad %4 %57 +%123 = OpAccessChain %118 %68 %31 %122 %29 +OpStore %123 %19 +%124 = OpLoad %4 %57 +%125 = OpLoad %4 %57 +%126 = OpAccessChain %118 %68 %31 %124 %125 +OpStore %126 %20 OpReturn OpFunctionEnd -%124 = OpFunction %9 None %125 -%123 = OpFunctionParameter %43 -%122 = OpLabel -OpBranch %126 -%126 = OpLabel -%127 = OpLoad %9 %123 -OpReturnValue %127 -OpFunctionEnd -%137 = OpFunction %2 None %67 +%129 = OpFunction %9 None %130 +%128 = OpFunctionParameter %44 +%127 = OpLabel +OpBranch %131 %131 = OpLabel -%128 = OpVariable %43 Function %21 -%129 = OpVariable %130 Function -%134 = OpLoad %23 %132 -%138 = OpAccessChain %68 %49 %30 -OpBranch %139 -%139 = OpLabel -%140 = OpLoad %9 %128 -OpStore %128 %8 -%141 = OpFunctionCall %2 %66 -%143 = OpAccessChain %142 %47 %30 -%144 = OpLoad %32 %143 -%146 = OpAccessChain %145 %47 %22 -%147 = OpLoad %38 %146 -%150 = OpAccessChain %149 %47 %30 %22 %30 -%151 = OpLoad %9 %150 -%153 = OpArrayLength %23 %47 4 -%154 = OpISub %23 %153 %24 -%157 = OpAccessChain %45 %47 %156 %154 %30 -%158 = OpLoad %4 %157 -%159 = OpFunctionCall %9 %124 %128 -%160 = OpConvertFToS %4 %151 -%161 = OpCompositeConstruct %46 %158 %160 %26 %27 %25 -OpStore %129 %161 -%162 = OpIAdd %23 %134 %28 -%163 = OpAccessChain %53 %129 %162 -OpStore %163 %29 -%164 = OpAccessChain %53 %129 %134 -%165 = OpLoad %4 %164 -%167 = OpCompositeConstruct %166 %165 %165 %165 %165 -%168 = OpConvertSToF %44 %167 -%169 = OpMatrixTimesVector %33 %144 %168 -%170 = OpCompositeConstruct %44 %169 %10 -OpStore %135 %170 +%132 = OpLoad %9 %128 +OpReturnValue %132 +OpFunctionEnd +%135 = OpFunction %9 None %136 +%134 = OpFunctionParameter %46 +%133 = OpLabel +OpBranch %137 +%137 = OpLabel +%138 = OpCompositeExtract %45 %134 4 +%139 = OpCompositeExtract %9 %138 9 +OpReturnValue %139 +OpFunctionEnd +%150 = OpFunction %2 None %72 +%144 = OpLabel +%140 = OpVariable %44 Function %24 +%141 = OpVariable %142 Function +%143 = OpVariable %44 Function +%147 = OpLoad %26 %145 +%151 = OpAccessChain %73 %54 %31 +OpBranch %152 +%152 = OpLabel +%153 = OpLoad %9 %140 +OpStore %140 %8 +%154 = OpFunctionCall %2 %71 +%156 = OpAccessChain %155 %52 %31 +%157 = OpLoad %33 %156 +%159 = OpAccessChain %158 %52 %25 +%160 = OpLoad %39 %159 +%163 = OpAccessChain %162 %52 %31 %25 %31 +%164 = OpLoad %9 %163 +%166 = OpArrayLength %26 %52 4 +%167 = OpISub %26 %166 %27 +%170 = OpAccessChain %48 %52 %169 %167 %31 +%171 = OpLoad %4 %170 +%172 = OpFunctionCall %9 %129 %140 +%173 = OpConvertFToS %4 %164 +%174 = OpCompositeConstruct %49 %171 %173 %28 %23 %22 +OpStore %141 %174 +%175 = OpIAdd %26 %147 %29 +%176 = OpAccessChain %58 %141 %175 +OpStore %176 %30 +%177 = OpAccessChain %58 %141 %147 +%178 = OpLoad %4 %177 +%179 = OpFunctionCall %9 %135 %51 +OpStore %143 %179 +%181 = OpCompositeConstruct %180 %178 %178 %178 %178 +%182 = OpConvertSToF %47 %181 +%183 = OpMatrixTimesVector %34 %157 %182 +%184 = OpCompositeConstruct %47 %183 %10 +OpStore %148 %184 OpReturn OpFunctionEnd -%173 = OpFunction %2 None %67 -%171 = OpLabel -OpBranch %174 -%174 = OpLabel -%175 = OpAccessChain %149 %47 %30 %28 %24 -OpStore %175 %8 -%176 = OpCompositeConstruct %33 %21 %21 %21 -%177 = OpCompositeConstruct %33 %8 %8 %8 -%178 = OpCompositeConstruct %33 %10 %10 %10 -%179 = OpCompositeConstruct %33 %11 %11 %11 -%180 = OpCompositeConstruct %32 %176 %177 %178 %179 -%181 = OpAccessChain %142 %47 %30 -OpStore %181 %180 -%182 = OpCompositeConstruct %37 %30 %30 -%183 = OpCompositeConstruct %37 %28 %28 -%184 = OpCompositeConstruct %38 %182 %183 -%185 = OpAccessChain %145 %47 %22 -OpStore %185 %184 -%186 = OpAccessChain %45 %47 %156 %28 %30 -OpStore %186 %6 -%187 = OpCompositeConstruct %44 %21 %21 %21 %21 -OpStore %172 %187 +%187 = OpFunction %2 None %72 +%185 = OpLabel +OpBranch %188 +%188 = OpLabel +%189 = OpAccessChain %162 %52 %31 %29 %27 +OpStore %189 %8 +%190 = OpCompositeConstruct %34 %24 %24 %24 +%191 = OpCompositeConstruct %34 %8 %8 %8 +%192 = OpCompositeConstruct %34 %10 %10 %10 +%193 = OpCompositeConstruct %34 %11 %11 %11 +%194 = OpCompositeConstruct %33 %190 %191 %192 %193 +%195 = OpAccessChain %155 %52 %31 +OpStore %195 %194 +%196 = OpCompositeConstruct %38 %31 %31 +%197 = OpCompositeConstruct %38 %29 %29 +%198 = OpCompositeConstruct %39 %196 %197 +%199 = OpAccessChain %158 %52 %25 +OpStore %199 %198 +%200 = OpAccessChain %48 %52 %169 %29 %31 +OpStore %200 %6 +%201 = OpCompositeConstruct %47 %24 %24 %24 %24 +OpStore %186 %201 OpReturn OpFunctionEnd -%190 = OpFunction %2 None %67 -%189 = OpLabel -%188 = OpVariable %53 Function -OpBranch %191 -%191 = OpLabel -%193 = OpAccessChain %192 %47 %24 -%194 = OpAtomicLoad %4 %193 %6 %195 -%197 = OpAccessChain %192 %47 %24 -%196 = OpAtomicIAdd %4 %197 %6 %195 %25 -OpStore %188 %196 -%199 = OpAccessChain %192 %47 %24 -%198 = OpAtomicISub %4 %199 %6 %195 %25 -OpStore %188 %198 -%201 = OpAccessChain %192 %47 %24 -%200 = OpAtomicAnd %4 %201 %6 %195 %25 -OpStore %188 %200 -%203 = OpAccessChain %192 %47 %24 -%202 = OpAtomicOr %4 %203 %6 %195 %25 -OpStore %188 %202 -%205 = OpAccessChain %192 %47 %24 -%204 = OpAtomicXor %4 %205 %6 %195 %25 -OpStore %188 %204 -%207 = OpAccessChain %192 %47 %24 -%206 = OpAtomicSMin %4 %207 %6 %195 %25 -OpStore %188 %206 -%209 = OpAccessChain %192 %47 %24 -%208 = OpAtomicSMax %4 %209 %6 %195 %25 -OpStore %188 %208 -%211 = OpAccessChain %192 %47 %24 -%210 = OpAtomicExchange %4 %211 %6 %195 %25 -OpStore %188 %210 -%212 = OpAccessChain %192 %47 %24 -OpAtomicStore %212 %6 %195 %194 +%204 = OpFunction %2 None %72 +%203 = OpLabel +%202 = OpVariable %58 Function +OpBranch %205 +%205 = OpLabel +%207 = OpAccessChain %206 %52 %27 +%208 = OpAtomicLoad %4 %207 %6 %209 +%211 = OpAccessChain %206 %52 %27 +%210 = OpAtomicIAdd %4 %211 %6 %209 %22 +OpStore %202 %210 +%213 = OpAccessChain %206 %52 %27 +%212 = OpAtomicISub %4 %213 %6 %209 %22 +OpStore %202 %212 +%215 = OpAccessChain %206 %52 %27 +%214 = OpAtomicAnd %4 %215 %6 %209 %22 +OpStore %202 %214 +%217 = OpAccessChain %206 %52 %27 +%216 = OpAtomicOr %4 %217 %6 %209 %22 +OpStore %202 %216 +%219 = OpAccessChain %206 %52 %27 +%218 = OpAtomicXor %4 %219 %6 %209 %22 +OpStore %202 %218 +%221 = OpAccessChain %206 %52 %27 +%220 = OpAtomicSMin %4 %221 %6 %209 %22 +OpStore %202 %220 +%223 = OpAccessChain %206 %52 %27 +%222 = OpAtomicSMax %4 %223 %6 %209 %22 +OpStore %202 %222 +%225 = OpAccessChain %206 %52 %27 +%224 = OpAtomicExchange %4 %225 %6 %209 %22 +OpStore %202 %224 +%226 = OpAccessChain %206 %52 %27 +OpAtomicStore %226 %6 %209 %208 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/padding.spvasm b/tests/out/spv/padding.spvasm new file mode 100644 index 000000000..d262f4b08 --- /dev/null +++ b/tests/out/spv/padding.spvasm @@ -0,0 +1,99 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 50 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %27 "vertex" %25 +OpSource GLSL 450 +OpMemberName %8 0 "a" +OpName %8 "S" +OpMemberName %9 0 "a" +OpMemberName %9 1 "b" +OpName %9 "Test" +OpMemberName %11 0 "a" +OpMemberName %11 1 "b" +OpName %11 "Test2" +OpMemberName %13 0 "a" +OpMemberName %13 1 "b" +OpName %13 "Test3" +OpName %15 "input" +OpName %18 "input2" +OpName %21 "input3" +OpName %27 "vertex" +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 16 +OpDecorate %10 ArrayStride 16 +OpMemberDecorate %11 0 Offset 0 +OpMemberDecorate %11 1 Offset 32 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 0 ColMajor +OpMemberDecorate %13 0 MatrixStride 16 +OpMemberDecorate %13 1 Offset 64 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 0 +OpDecorate %16 Block +OpMemberDecorate %16 0 Offset 0 +OpDecorate %18 DescriptorSet 0 +OpDecorate %18 Binding 1 +OpDecorate %19 Block +OpMemberDecorate %19 0 Offset 0 +OpDecorate %21 DescriptorSet 0 +OpDecorate %21 Binding 2 +OpDecorate %22 Block +OpMemberDecorate %22 0 Offset 0 +OpDecorate %25 BuiltIn Position +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 2 +%6 = OpTypeFloat 32 +%5 = OpConstant %6 1.0 +%7 = OpTypeVector %6 3 +%8 = OpTypeStruct %7 +%9 = OpTypeStruct %8 %6 +%10 = OpTypeArray %7 %3 +%11 = OpTypeStruct %10 %6 +%12 = OpTypeMatrix %7 4 +%13 = OpTypeStruct %12 %6 +%14 = OpTypeVector %6 4 +%16 = OpTypeStruct %9 +%17 = OpTypePointer Uniform %16 +%15 = OpVariable %17 Uniform +%19 = OpTypeStruct %11 +%20 = OpTypePointer Uniform %19 +%18 = OpVariable %20 Uniform +%22 = OpTypeStruct %13 +%23 = OpTypePointer Uniform %22 +%21 = OpVariable %23 Uniform +%26 = OpTypePointer Output %14 +%25 = OpVariable %26 Output +%28 = OpTypeFunction %2 +%29 = OpTypePointer Uniform %9 +%31 = OpTypeInt 32 0 +%30 = OpConstant %31 0 +%33 = OpTypePointer Uniform %11 +%35 = OpTypePointer Uniform %13 +%39 = OpTypePointer Uniform %6 +%40 = OpConstant %31 1 +%27 = OpFunction %2 None %28 +%24 = OpLabel +%32 = OpAccessChain %29 %15 %30 +%34 = OpAccessChain %33 %18 %30 +%36 = OpAccessChain %35 %21 %30 +OpBranch %37 +%37 = OpLabel +%38 = OpCompositeConstruct %14 %5 %5 %5 %5 +%41 = OpAccessChain %39 %32 %40 +%42 = OpLoad %6 %41 +%43 = OpVectorTimesScalar %14 %38 %42 +%44 = OpAccessChain %39 %34 %40 +%45 = OpLoad %6 %44 +%46 = OpVectorTimesScalar %14 %43 %45 +%47 = OpAccessChain %39 %36 %40 +%48 = OpLoad %6 %47 +%49 = OpVectorTimesScalar %14 %46 %48 +OpStore %25 %49 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 53cd3c4ac..b6fc1921f 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -21,36 +21,36 @@ var baz: Baz; fn test_matrix_within_struct_accesses() { var idx: i32 = 9; - var unnamed: mat3x2; - var unnamed_1: vec2; + var unnamed_1: mat3x2; var unnamed_2: vec2; - var unnamed_3: f32; + var unnamed_3: vec2; var unnamed_4: f32; var unnamed_5: f32; var unnamed_6: f32; + var unnamed_7: f32; var t: Baz; let _e4 = idx; idx = (_e4 - 1); let _e8 = baz.m; - unnamed = _e8; + unnamed_1 = _e8; let _e13 = baz.m[0]; - unnamed_1 = _e13; + unnamed_2 = _e13; let _e16 = idx; let _e18 = baz.m[_e16]; - unnamed_2 = _e18; + unnamed_3 = _e18; let _e25 = baz.m[0][1]; - unnamed_3 = _e25; + unnamed_4 = _e25; let _e30 = idx; let _e32 = baz.m[0][_e30]; - unnamed_4 = _e32; + unnamed_5 = _e32; let _e35 = idx; let _e39 = baz.m[_e35][1]; - unnamed_5 = _e39; + unnamed_6 = _e39; let _e42 = idx; let _e44 = idx; let _e46 = baz.m[_e42][_e44]; - unnamed_6 = _e46; + unnamed_7 = _e46; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); let _e57 = idx; idx = (_e57 + 1); @@ -74,10 +74,15 @@ fn read_from_private(foo_1: ptr) -> f32 { return _e3; } +fn test_arr_as_arg(a: array,5>) -> f32 { + return a[4][9]; +} + @stage(vertex) fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32 = 0.0; var c: array; + var unnamed: f32; let baz_1 = foo; foo = 1.0; @@ -85,12 +90,14 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let matrix = bar.matrix; let arr = bar.arr; let b = bar.matrix[3][0]; - let a = bar.data[(arrayLength((&bar.data)) - 2u)].value; + let a_1 = bar.data[(arrayLength((&bar.data)) - 2u)].value; let data_pointer = (&bar.data[0].value); let _e28 = read_from_private((&foo)); - c = array(a, i32(b), 3, 4, 5); + c = array(a_1, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value = c[vi]; + let _e42 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + unnamed = _e42; return vec4((matrix * vec4(vec4(value))), 2.0); } diff --git a/tests/out/wgsl/padding.wgsl b/tests/out/wgsl/padding.wgsl new file mode 100644 index 000000000..1d3495477 --- /dev/null +++ b/tests/out/wgsl/padding.wgsl @@ -0,0 +1,33 @@ +struct S { + a: vec3, +} + +struct Test { + a: S, + b: f32, +} + +struct Test2_ { + a: array,2>, + b: f32, +} + +struct Test3_ { + a: mat4x3, + b: f32, +} + +@group(0) @binding(0) +var input: Test; +@group(0) @binding(1) +var input2_: Test2_; +@group(0) @binding(2) +var input3_: Test3_; + +@stage(vertex) +fn vertex() -> @builtin(position) vec4 { + let _e6 = input.b; + let _e9 = input2_.b; + let _e12 = input3_.b; + return (((vec4(1.0) * _e6) * _e9) * _e12); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 279a79c70..0726a4846 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -458,6 +458,10 @@ fn convert_wgsl() { "access", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ( + "padding", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + ), ("pointers", Targets::SPIRV | Targets::WGSL), ( "control-flow", From 8afa5fe5e304c1e32234f93e876423768e291b8e Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 11 Apr 2022 23:54:55 -0700 Subject: [PATCH 1661/2212] [glsl-out] Document and flatten `back::glsl::Writer::write_varying`. --- src/back/glsl/mod.rs | 178 +++++++++++++++++++++++++------------------ 1 file changed, 105 insertions(+), 73 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 6e8387c00..5ec9f4f61 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1116,94 +1116,126 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } - /// Writes the varying declaration. + /// Write a GLSL global that will carry a Naga entry point's argument or return value. + /// + /// A Naga entry point's arguments and return value are rendered in GLSL as + /// variables at global scope with the `in` and `out` storage qualifiers. + /// The code we generate for `main` loads from all the `in` globals into + /// appropriately named locals. Before it returns, `main` assigns the + /// components of its return value into all the `out` globals. + /// + /// This function writes a declaration for one such GLSL global, + /// representing a value passed into or returned from [`self.entry_point`] + /// that has a [`Location`] binding. The global's name is generated based on + /// the location index and the shader stages being connected; see + /// [`VaryingName`]. This means we don't need to know the names of + /// arguments, just their types and bindings. + /// + /// Emit nothing for entry point arguments or return values with [`BuiltIn`] + /// bindings; `main` will read from or assign to the appropriate GLSL + /// special variable; these are pre-declared. As an exception, we do declare + /// `gl_Position` or `gl_FragCoord` with the `invariant` qualifier if + /// needed. + /// + /// Use `output` together with [`self.entry_point.stage`] to determine which + /// shader stages are being connected, and choose the `in` or `out` storage + /// qualifier. + /// + /// [`self.entry_point`]: Writer::entry_point + /// [`self.entry_point.stage`]: crate::EntryPoint::stage + /// [`Location`]: crate::Binding::Location + /// [`BuiltIn`]: crate::Binding::BuiltIn fn write_varying( &mut self, binding: Option<&crate::Binding>, ty: Handle, output: bool, ) -> Result<(), Error> { - match self.module.types[ty].inner { - crate::TypeInner::Struct { ref members, .. } => { - for member in members { - self.write_varying(member.binding.as_ref(), member.ty, output)?; - } + // For a struct, emit a separate global for each member with a binding. + if let crate::TypeInner::Struct { ref members, .. } = self.module.types[ty].inner { + for member in members { + self.write_varying(member.binding.as_ref(), member.ty, output)?; } - _ => { - let (location, interpolation, sampling) = match binding { - Some(&crate::Binding::Location { - location, - interpolation, - sampling, - }) => (location, interpolation, sampling), - Some(&crate::Binding::BuiltIn { - built_in, - invariant: true, - }) => { - writeln!(self.out, "invariant {};", glsl_built_in(built_in, output))?; - return Ok(()); - } - _ => return Ok(()), - }; + return Ok(()); + } - // Write the interpolation modifier if needed - // - // We ignore all interpolation and auxiliary modifiers that aren't used in fragment - // shaders' input globals or vertex shaders' output globals. - let emit_interpolation_and_auxiliary = match self.entry_point.stage { - ShaderStage::Vertex => output, - ShaderStage::Fragment => !output, - _ => false, - }; + let binding = match binding { + None => return Ok(()), + Some(binding) => binding, + }; - // Write the I/O locations, if allowed - if self.options.version.supports_explicit_locations() - || !emit_interpolation_and_auxiliary - { - write!(self.out, "layout(location = {}) ", location)?; + let (location, interpolation, sampling) = match *binding { + crate::Binding::Location { + location, + interpolation, + sampling, + } => (location, interpolation, sampling), + crate::Binding::BuiltIn { + built_in, + invariant, + } => { + if invariant { + writeln!(self.out, "invariant {};", glsl_built_in(built_in, output))?; } + return Ok(()); + } + }; - // Write the interpolation qualifier. - if let Some(interp) = interpolation { - if emit_interpolation_and_auxiliary { - write!(self.out, "{} ", glsl_interpolation(interp))?; - } - } + // Write the interpolation modifier if needed + // + // We ignore all interpolation and auxiliary modifiers that aren't used in fragment + // shaders' input globals or vertex shaders' output globals. + let emit_interpolation_and_auxiliary = match self.entry_point.stage { + ShaderStage::Vertex => output, + ShaderStage::Fragment => !output, + _ => false, + }; - // Write the sampling auxiliary qualifier. - // - // Before GLSL 4.2, the `centroid` and `sample` qualifiers were required to appear - // immediately before the `in` / `out` qualifier, so we'll just follow that rule - // here, regardless of the version. - if let Some(sampling) = sampling { - if emit_interpolation_and_auxiliary { - if let Some(qualifier) = glsl_sampling(sampling) { - write!(self.out, "{} ", qualifier)?; - } - } - } + // Write the I/O locations, if allowed + if self.options.version.supports_explicit_locations() || !emit_interpolation_and_auxiliary { + write!(self.out, "layout(location = {}) ", location)?; + } - // Write the input/output qualifier. - write!(self.out, "{} ", if output { "out" } else { "in" })?; - - // Write the type - // `write_type` adds no leading or trailing spaces - self.write_type(ty)?; - - // Finally write the global name and end the global with a `;` and a newline - // Leading space is important - let vname = VaryingName { - binding: &crate::Binding::Location { - location, - interpolation: None, - sampling: None, - }, - stage: self.entry_point.stage, - output, - }; - writeln!(self.out, " {};", vname)?; + // Write the interpolation qualifier. + if let Some(interp) = interpolation { + if emit_interpolation_and_auxiliary { + write!(self.out, "{} ", glsl_interpolation(interp))?; } } + + // Write the sampling auxiliary qualifier. + // + // Before GLSL 4.2, the `centroid` and `sample` qualifiers were required to appear + // immediately before the `in` / `out` qualifier, so we'll just follow that rule + // here, regardless of the version. + if let Some(sampling) = sampling { + if emit_interpolation_and_auxiliary { + if let Some(qualifier) = glsl_sampling(sampling) { + write!(self.out, "{} ", qualifier)?; + } + } + } + + // Write the input/output qualifier. + write!(self.out, "{} ", if output { "out" } else { "in" })?; + + // Write the type + // `write_type` adds no leading or trailing spaces + self.write_type(ty)?; + + // Finally write the global name and end the global with a `;` and a newline + // Leading space is important + let vname = VaryingName { + binding: &crate::Binding::Location { + location, + interpolation: None, + sampling: None, + }, + stage: self.entry_point.stage, + output, + }; + writeln!(self.out, " {};", vname)?; + Ok(()) } From 4e4d918d399b50e76613a5f6b34eacce768eb896 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Apr 2022 12:55:00 -0700 Subject: [PATCH 1662/2212] [msl-out] Introduce finer distinctions to `LocationMode`. Distinguish between vertex shader outputs and fragment shader inputs. This change should have no visible effect. --- src/back/msl/mod.rs | 54 +++++++++++++++++++++++++++++------------- src/back/msl/writer.rs | 4 ++-- 2 files changed, 39 insertions(+), 19 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index d049b72f4..d0be7dba3 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -165,11 +165,29 @@ pub enum EntryPointError { MissingSizesBuffer, } +/// Points in the MSL code where we might emit a pipeline input or output. +/// +/// Note that, even though vertex shaders' outputs are always fragment +/// shaders' inputs, we still need to distinguish `VertexOutput` and +/// `FragmentInput`, since there are certain differences in the way +/// [`ResolvedBinding`s] are represented on either side. +/// +/// [`ResolvedBinding`s]: ResolvedBinding #[derive(Clone, Copy, Debug)] enum LocationMode { + /// Input to the vertex shader. VertexInput, + + /// Output from the vertex shader. + VertexOutput, + + /// Input to the fragment shader. + FragmentInput, + + /// Output from the fragment shader. FragmentOutput, - Intermediate, + + /// Compute shader input or output. Uniform, } @@ -243,22 +261,24 @@ impl Options { } => match mode { LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(location)), LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(location)), - LocationMode::Intermediate => Ok(ResolvedBinding::User { - prefix: if self.spirv_cross_compatibility { - "locn" - } else { - "loc" - }, - index: location, - interpolation: { - // unwrap: The verifier ensures that vertex shader outputs and fragment - // shader inputs always have fully specified interpolation, and that - // sampling is `None` only for Flat interpolation. - let interpolation = interpolation.unwrap(); - let sampling = sampling.unwrap_or(crate::Sampling::Center); - Some(ResolvedInterpolation::from_binding(interpolation, sampling)) - }, - }), + LocationMode::VertexOutput | LocationMode::FragmentInput => { + Ok(ResolvedBinding::User { + prefix: if self.spirv_cross_compatibility { + "locn" + } else { + "loc" + }, + index: location, + interpolation: { + // unwrap: The verifier ensures that vertex shader outputs and fragment + // shader inputs always have fully specified interpolation, and that + // sampling is `None` only for Flat interpolation. + let interpolation = interpolation.unwrap(); + let sampling = sampling.unwrap_or(crate::Sampling::Center); + Some(ResolvedInterpolation::from_binding(interpolation, sampling)) + }, + }) + } LocationMode::Uniform => { log::error!( "Unexpected Binding::Location({}) for the Uniform mode", diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e1f69055b..9d591b6eb 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3331,11 +3331,11 @@ impl Writer { crate::ShaderStage::Vertex => ( "vertex", LocationMode::VertexInput, - LocationMode::Intermediate, + LocationMode::VertexOutput, ), crate::ShaderStage::Fragment { .. } => ( "fragment", - LocationMode::Intermediate, + LocationMode::FragmentInput, LocationMode::FragmentOutput, ), crate::ShaderStage::Compute { .. } => { From 78975f25dac3cba5b45c832c1282324aaf165c5f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Apr 2022 12:57:00 -0700 Subject: [PATCH 1663/2212] [msl-out] Permit `invariant` qualifier on vertex shader outputs. --- src/back/msl/mod.rs | 4 +++- tests/out/msl/interface.msl | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index d0be7dba3..e4b323e68 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -249,9 +249,11 @@ impl Options { return Err(Error::UnsupportedAttribute("invariant".to_string())); } + // The 'invariant' attribute can only appear on vertex + // shader outputs, but not fragment shader inputs. Ok(ResolvedBinding::BuiltIn { built_in, - invariant: invariant && matches!(mode, LocationMode::FragmentOutput), + invariant: invariant && matches!(mode, LocationMode::VertexOutput), }) } crate::Binding::Location { diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 17b4e928d..28bba917f 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -27,7 +27,7 @@ struct vertex_Input { uint color [[attribute(10)]]; }; struct vertex_Output { - metal::float4 position [[position]]; + metal::float4 position [[position, invariant]]; float varying [[user(loc1), center_perspective]]; float _point_size [[point_size]]; }; @@ -84,7 +84,7 @@ kernel void compute_( struct vertex_two_structsInput { }; struct vertex_two_structsOutput { - metal::float4 member_3 [[position]]; + metal::float4 member_3 [[position, invariant]]; float _point_size [[point_size]]; }; vertex vertex_two_structsOutput vertex_two_structs( From 170faab6db5dcada1271d1d72b3be1d21c91c8a6 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 13 Apr 2022 14:57:05 -0700 Subject: [PATCH 1664/2212] Move `invariant` bit from `Binding::Builtin` to `Builtin::Position`. (#1822) Use the type system to enforce the rule that the invariant attribute may only appear on `Position` builtins. --- src/back/glsl/features.rs | 2 +- src/back/glsl/mod.rs | 17 +++----- src/back/hlsl/conv.rs | 2 +- src/back/hlsl/writer.rs | 16 +++----- src/back/mod.rs | 4 +- src/back/msl/mod.rs | 41 ++++++++----------- src/back/msl/writer.rs | 20 ++------- src/back/spv/block.rs | 2 +- src/back/spv/helpers.rs | 2 +- src/back/spv/writer.rs | 37 +++++------------ src/back/wgsl/writer.rs | 16 +++----- src/front/glsl/variables.rs | 18 ++++---- src/front/spv/convert.rs | 4 +- src/front/spv/function.rs | 9 ++-- src/front/spv/mod.rs | 15 +++---- src/front/spv/null.rs | 2 +- src/front/wgsl/conv.rs | 2 +- src/front/wgsl/mod.rs | 16 ++++---- src/lib.rs | 8 +--- src/proc/mod.rs | 2 +- src/valid/analyzer.rs | 2 +- src/valid/interface.rs | 27 +++++++----- tests/out/ir/collatz.ron | 5 +-- tests/out/spv/interface.fragment.spvasm | 2 +- tests/out/spv/interface.vertex.spvasm | 2 +- .../spv/interface.vertex_two_structs.spvasm | 2 +- 26 files changed, 107 insertions(+), 168 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 345d51436..408046fc8 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -404,7 +404,7 @@ impl<'a, W> Writer<'a, W> { _ => { if let Some(binding) = binding { match *binding { - Binding::BuiltIn { built_in, .. } => match built_in { + Binding::BuiltIn(built_in) => match built_in { crate::BuiltIn::ClipDistance => { self.features.request(Features::CLIP_DISTANCE) } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5ec9f4f61..b5750fb94 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -336,7 +336,7 @@ impl fmt::Display for VaryingName<'_> { }; write!(f, "_{}_location{}", prefix, location,) } - crate::Binding::BuiltIn { built_in, .. } => { + crate::Binding::BuiltIn(built_in) => { write!(f, "{}", glsl_built_in(built_in, self.output)) } } @@ -1170,11 +1170,8 @@ impl<'a, W: Write> Writer<'a, W> { interpolation, sampling, } => (location, interpolation, sampling), - crate::Binding::BuiltIn { - built_in, - invariant, - } => { - if invariant { + crate::Binding::BuiltIn(built_in) => { + if let crate::BuiltIn::Position { invariant: true } = built_in { writeln!(self.out, "invariant {};", glsl_built_in(built_in, output))?; } return Ok(()); @@ -1830,10 +1827,8 @@ impl<'a, W: Write> Writer<'a, W> { for (index, member) in members.iter().enumerate() { // TODO: handle builtin in better way - if let Some(crate::Binding::BuiltIn { - built_in: builtin, - .. - }) = member.binding + if let Some(crate::Binding::BuiltIn(builtin)) = + member.binding { match builtin { crate::BuiltIn::ClipDistance @@ -3170,7 +3165,7 @@ fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { use crate::BuiltIn as Bi; match built_in { - Bi::Position => { + Bi::Position { .. } => { if output { "gl_Position" } else { diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 547b7632f..d799c0b98 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -151,7 +151,7 @@ impl crate::StorageFormat { impl crate::BuiltIn { pub(super) fn to_hlsl_str(self) -> Result<&'static str, Error> { Ok(match self { - Self::Position => "SV_Position", + Self::Position { .. } => "SV_Position", // vertex Self::ClipDistance => "SV_ClipDistance", Self::CullDistance => "SV_CullDistance", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index b3e61e7f5..3338c652a 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -60,7 +60,7 @@ impl InterfaceKey { fn new(binding: Option<&crate::Binding>) -> Self { match binding { Some(&crate::Binding::Location { location, .. }) => Self::Location(location), - Some(&crate::Binding::BuiltIn { built_in, .. }) => Self::BuiltIn(built_in), + Some(&crate::Binding::BuiltIn(built_in)) => Self::BuiltIn(built_in), None => Self::Other, } } @@ -309,9 +309,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { fn write_modifier(&mut self, binding: &crate::Binding) -> BackendResult { match *binding { - crate::Binding::BuiltIn { - invariant: true, .. - } => { + crate::Binding::BuiltIn(crate::BuiltIn::Position { invariant: true }) => { write!(self.out, "precise ")?; } crate::Binding::Location { @@ -345,9 +343,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { stage: Option<(ShaderStage, Io)>, ) -> BackendResult { match *binding { - crate::Binding::BuiltIn { - built_in: builtin, .. - } => { + crate::Binding::BuiltIn(builtin) => { let builtin_str = builtin.to_hlsl_str()?; write!(self.out, " : {}", builtin_str)?; } @@ -963,9 +959,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if let Some(crate::FunctionResult { binding: Some( - ref binding @ crate::Binding::BuiltIn { - invariant: true, .. - }, + ref binding @ crate::Binding::BuiltIn(crate::BuiltIn::Position { + invariant: true, + }), ), .. }) = func.result diff --git a/src/back/mod.rs b/src/back/mod.rs index 0dc010f1b..9802e5acf 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -96,14 +96,14 @@ impl<'a> FunctionCtx<'_> { match self.expressions[expression] { crate::Expression::FunctionArgument(arg_index) => { return match ep_function.arguments[arg_index as usize].binding { - Some(crate::Binding::BuiltIn { built_in: bi, .. }) => Some(bi), + Some(crate::Binding::BuiltIn(bi)) => Some(bi), _ => built_in, }; } crate::Expression::AccessIndex { base, index } => { match *self.info[base].ty.inner_with(&module.types) { crate::TypeInner::Struct { ref members, .. } => { - if let Some(crate::Binding::BuiltIn { built_in: bi, .. }) = + if let Some(crate::Binding::BuiltIn(bi)) = members[index as usize].binding { built_in = Some(bi); diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index e4b323e68..28cff0476 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -100,10 +100,7 @@ impl ops::Index for PerStageMap { } enum ResolvedBinding { - BuiltIn { - built_in: crate::BuiltIn, - invariant: bool, - }, + BuiltIn(crate::BuiltIn), Attribute(u32), Color(u32), User { @@ -241,20 +238,20 @@ impl Options { mode: LocationMode, ) -> Result { match *binding { - crate::Binding::BuiltIn { - built_in, - invariant, - } => { - if invariant && self.lang_version < (2, 1) { - return Err(Error::UnsupportedAttribute("invariant".to_string())); + crate::Binding::BuiltIn(mut built_in) => { + if let crate::BuiltIn::Position { ref mut invariant } = built_in { + if *invariant && self.lang_version < (2, 1) { + return Err(Error::UnsupportedAttribute("invariant".to_string())); + } + + // The 'invariant' attribute may only appear on vertex + // shader outputs, not fragment shader inputs. + if !matches!(mode, LocationMode::VertexOutput) { + *invariant = false; + } } - // The 'invariant' attribute can only appear on vertex - // shader outputs, but not fragment shader inputs. - Ok(ResolvedBinding::BuiltIn { - built_in, - invariant: invariant && matches!(mode, LocationMode::VertexOutput), - }) + Ok(ResolvedBinding::BuiltIn(built_in)) } crate::Binding::Location { location, @@ -369,13 +366,11 @@ impl ResolvedBinding { fn try_fmt(&self, out: &mut W) -> Result<(), Error> { write!(out, " [[")?; match *self { - Self::BuiltIn { - built_in, - invariant, - } => { + Self::BuiltIn(built_in) => { use crate::BuiltIn as Bi; let name = match built_in { - Bi::Position => "position", + Bi::Position { invariant: false } => "position", + Bi::Position { invariant: true } => "position, invariant", // vertex Bi::BaseInstance => "base_instance", Bi::BaseVertex => "base_vertex", @@ -401,10 +396,6 @@ impl ResolvedBinding { } }; write!(out, "{}", name)?; - - if invariant { - write!(out, ", invariant")?; - } } Self::Attribute(index) => write!(out, "attribute({})", index)?, Self::Color(index) => write!(out, "color({})", index)?, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 9d591b6eb..3d1a10972 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2136,19 +2136,13 @@ impl Writer { for (index, member) in members.iter().enumerate() { match member.binding { - Some(crate::Binding::BuiltIn { - built_in: crate::BuiltIn::PointSize, - .. - }) => { + Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) => { has_point_size = true; if !context.pipeline_options.allow_point_size { continue; } } - Some(crate::Binding::BuiltIn { - built_in: crate::BuiltIn::CullDistance, - .. - }) => { + Some(crate::Binding::BuiltIn(crate::BuiltIn::CullDistance)) => { log::warn!("Ignoring CullDistance built-in"); continue; } @@ -3437,10 +3431,7 @@ impl Writer { match *binding { // Point size is only supported in VS of pipelines with // point primitive topology. - crate::Binding::BuiltIn { - built_in: crate::BuiltIn::PointSize, - .. - } => { + crate::Binding::BuiltIn(crate::BuiltIn::PointSize) => { has_point_size = true; if !pipeline_options.allow_point_size { continue; @@ -3450,10 +3441,7 @@ impl Writer { // But we can't return UnsupportedBuiltIn error to user. // Because otherwise we can't generate msl shader from any glslang SPIR-V shaders. // glslang generates gl_PerVertex struct with gl_CullDistance builtin inside by default. - crate::Binding::BuiltIn { - built_in: crate::BuiltIn::CullDistance, - .. - } => { + crate::Binding::BuiltIn(crate::BuiltIn::CullDistance) => { log::warn!("Ignoring CullDistance BuiltIn"); continue; } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 0ab9c4a71..15bd07bea 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -144,7 +144,7 @@ impl Writer { body.push(Instruction::store(res_member.id, member_value_id, None)); match res_member.built_in { - Some(crate::BuiltIn::Position) + Some(crate::BuiltIn::Position { .. }) if self.flags.contains(WriterFlags::ADJUST_COORDINATE_SPACE) => { self.write_epilogue_position_y_flip(res_member.id, body)?; diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index 5580fec2c..acde9504d 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -38,7 +38,7 @@ pub(super) fn contains_builtin( arena: &UniqueArena, built_in: crate::BuiltIn, ) -> bool { - if let Some(&crate::Binding::BuiltIn { built_in: bi, .. }) = binding { + if let Some(&crate::Binding::BuiltIn(bi)) = binding { bi == built_in } else if let crate::TypeInner::Struct { ref members, .. } = arena[ty].inner { members diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 88d70345f..19d788b8a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -398,11 +398,8 @@ impl Writer { let mut has_point_size = false; let class = spirv::StorageClass::Output; if let Some(ref binding) = result.binding { - has_point_size |= *binding - == crate::Binding::BuiltIn { - built_in: crate::BuiltIn::PointSize, - invariant: false, - }; + has_point_size |= + *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); let type_id = self.get_type_id(LookupType::Handle(result.ty)); let varying_id = self.write_varying(ir_module, class, None, result.ty, binding)?; @@ -419,11 +416,8 @@ impl Writer { let type_id = self.get_type_id(LookupType::Handle(member.ty)); let name = member.name.as_ref().map(AsRef::as_ref); let binding = member.binding.as_ref().unwrap(); - has_point_size |= *binding - == crate::Binding::BuiltIn { - built_in: crate::BuiltIn::PointSize, - invariant: false, - }; + has_point_size |= + *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); let varying_id = self.write_varying(ir_module, class, name, member.ty, binding)?; iface.varying_ids.push(varying_id); @@ -1180,13 +1174,14 @@ impl Writer { } } } - crate::Binding::BuiltIn { - built_in, - invariant, - } => { + crate::Binding::BuiltIn(built_in) => { use crate::BuiltIn as Bi; let built_in = match built_in { - Bi::Position => { + Bi::Position { invariant } => { + if invariant { + self.decorate(id, Decoration::Invariant, &[]); + } + if class == spirv::StorageClass::Output { BuiltIn::Position } else { @@ -1234,10 +1229,6 @@ impl Writer { }; self.decorate(id, Decoration::BuiltIn, &[built_in as u32]); - - if invariant { - self.decorate(id, Decoration::Invariant, &[]); - } } } @@ -1365,13 +1356,7 @@ impl Writer { crate::TypeInner::Struct { ref members, .. } => members.iter().any(|member| { has_view_index_check(ir_module, member.binding.as_ref(), member.ty) }), - _ => { - binding - == Some(&crate::Binding::BuiltIn { - built_in: crate::BuiltIn::ViewIndex, - invariant: false, - }) - } + _ => binding == Some(&crate::Binding::BuiltIn(crate::BuiltIn::ViewIndex)), } } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 1b0366572..ef93192d0 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -402,7 +402,7 @@ impl Writer { writeln!(self.out)?; for (index, member) in members.iter().enumerate() { // Skip struct member with unsupported built in - if let Some(crate::Binding::BuiltIn { built_in, .. }) = member.binding { + if let Some(crate::Binding::BuiltIn(built_in)) = member.binding { if builtin_str(built_in).is_none() { log::warn!("Skip member with unsupported builtin {:?}", built_in); continue; @@ -1747,7 +1747,7 @@ impl Writer { // Write the comma separated constants for (index, constant) in components.iter().enumerate() { - if let Some(&crate::Binding::BuiltIn { built_in, .. }) = + if let Some(&crate::Binding::BuiltIn(built_in)) = members.and_then(|members| members.get(index)?.binding.as_ref()) { if builtin_str(built_in).is_none() { @@ -1849,7 +1849,7 @@ fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { match built_in { Bi::VertexIndex => Some("vertex_index"), Bi::InstanceIndex => Some("instance_index"), - Bi::Position => Some("position"), + Bi::Position { .. } => Some("position"), Bi::FrontFacing => Some("front_facing"), Bi::FragDepth => Some("frag_depth"), Bi::LocalInvocationId => Some("local_invocation_id"), @@ -1977,11 +1977,8 @@ fn map_binding_to_attribute( scalar_kind: Option, ) -> Vec { match *binding { - crate::Binding::BuiltIn { - built_in, - invariant, - } => { - if invariant { + crate::Binding::BuiltIn(built_in) => { + if let crate::BuiltIn::Position { invariant: true } = built_in { vec![Attribute::BuiltIn(built_in), Attribute::Invariant] } else { vec![Attribute::BuiltIn(built_in)] @@ -2017,8 +2014,7 @@ fn access_to_unsupported_builtin( { // Let's check that we try to access a struct member with unsupported built-in and skip it. if let TypeInner::Struct { ref members, .. } = module.types[pointer_base_handle].inner { - if let Some(crate::Binding::BuiltIn { built_in, .. }) = members[index as usize].binding - { + if let Some(crate::Binding::BuiltIn(built_in)) = members[index as usize].binding { if builtin_str(built_in).is_none() { log::warn!("Skip component with unsupported builtin {:?}", built_in); return true; diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 02995e2bb..0e446a9a7 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -67,10 +67,7 @@ impl Parser { let idx = self.entry_args.len(); self.entry_args.push(EntryArg { name: None, - binding: Binding::BuiltIn { - built_in: data.builtin, - invariant: false, - }, + binding: Binding::BuiltIn(data.builtin), handle, storage: data.storage, }); @@ -120,7 +117,7 @@ impl Parser { kind: ScalarKind::Float, width: 4, }, - builtin: BuiltIn::Position, + builtin: BuiltIn::Position { invariant: false }, mutable: true, storage: StorageQualifier::Output, }, @@ -130,7 +127,7 @@ impl Parser { kind: ScalarKind::Float, width: 4, }, - builtin: BuiltIn::Position, + builtin: BuiltIn::Position { invariant: false }, mutable: false, storage: StorageQualifier::Input, }, @@ -240,11 +237,10 @@ impl Parser { ) { if let Some(var) = self.lookup_variable(ctx, body, name, meta) { if let Some(index) = var.entry_arg { - if let Binding::BuiltIn { built_in, .. } = self.entry_args[index].binding { - self.entry_args[index].binding = Binding::BuiltIn { - built_in, - invariant: built_in == BuiltIn::Position, - }; + if let Binding::BuiltIn(BuiltIn::Position { ref mut invariant }) = + self.entry_args[index].binding + { + *invariant = true; } } } diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 22283fff0..9ffc3880d 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -121,10 +121,10 @@ pub(super) fn map_width(word: spirv::Word) -> Result { .map_err(|_| Error::InvalidTypeWidth(word)) } -pub(super) fn map_builtin(word: spirv::Word) -> Result { +pub(super) fn map_builtin(word: spirv::Word, invariant: bool) -> Result { use spirv::BuiltIn as Bi; Ok(match spirv::BuiltIn::from_u32(word) { - Some(Bi::Position) | Some(Bi::FragCoord) => crate::BuiltIn::Position, + Some(Bi::Position) | Some(Bi::FragCoord) => crate::BuiltIn::Position { invariant }, Some(Bi::ViewIndex) => crate::BuiltIn::ViewIndex, // vertex Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index b8e6c6615..c57695601 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -377,7 +377,7 @@ impl> super::Parser { } => { for (index, sm) in sub_members.iter().enumerate() { match sm.binding { - Some(crate::Binding::BuiltIn { built_in, .. }) => { + Some(crate::Binding::BuiltIn(built_in)) => { // Cull unused builtins to preserve performances if !self.builtin_usage.contains(&built_in) { continue; @@ -414,10 +414,9 @@ impl> super::Parser { for (member_index, member) in members.iter().enumerate() { match member.binding { - Some(crate::Binding::BuiltIn { - built_in: crate::BuiltIn::Position, - .. - }) if self.options.adjust_coordinate_space => { + Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { .. })) + if self.options.adjust_coordinate_space => + { let mut emitter = Emitter::default(); emitter.start(&function.expressions); let global_expr = components[member_index]; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 9c963fa04..6c270dcbb 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -235,10 +235,7 @@ impl Decoration { location: None, invariant, .. - } => map_builtin(built_in).map(|built_in| crate::Binding::BuiltIn { - built_in, - invariant: invariant && built_in == crate::BuiltIn::Position, - }), + } => Ok(crate::Binding::BuiltIn(map_builtin(built_in, invariant)?)), Decoration { built_in: None, location: Some(location), @@ -1475,7 +1472,7 @@ impl> Parser { span, ); - if let Some(crate::Binding::BuiltIn { built_in, .. }) = + if let Some(crate::Binding::BuiltIn(built_in)) = members[index as usize].binding { self.builtin_usage.insert(built_in); @@ -4646,7 +4643,7 @@ impl> Parser { ExtendedClass::Input => { let mut binding = dec.io_binding()?; let mut unsigned_ty = effective_ty; - if let crate::Binding::BuiltIn { built_in, .. } = binding { + if let crate::Binding::BuiltIn(built_in) = binding { let needs_inner_uint = match built_in { crate::BuiltIn::BaseInstance | crate::BuiltIn::BaseVertex @@ -4699,7 +4696,7 @@ impl> Parser { // For output interface blocks, this would be a structure. let mut binding = dec.io_binding().ok(); let init = match binding { - Some(crate::Binding::BuiltIn { built_in, .. }) => { + Some(crate::Binding::BuiltIn(built_in)) => { match null::generate_default_built_in( Some(built_in), effective_ty, @@ -4722,9 +4719,7 @@ impl> Parser { .iter() .map(|member| { let built_in = match member.binding { - Some(crate::Binding::BuiltIn { built_in, .. }) => { - Some(built_in) - } + Some(crate::Binding::BuiltIn(built_in)) => Some(built_in), _ => None, }; (built_in, member.ty) diff --git a/src/front/spv/null.rs b/src/front/spv/null.rs index 5d40dfa91..b0a8579a2 100644 --- a/src/front/spv/null.rs +++ b/src/front/spv/null.rs @@ -121,7 +121,7 @@ pub fn generate_default_built_in( span: crate::Span, ) -> Result, Error> { let inner = match built_in { - Some(crate::BuiltIn::Position) => { + Some(crate::BuiltIn::Position { .. }) => { let zero = constant_arena.fetch_or_append( crate::Constant { name: None, diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 3039d98fe..6d4dd954a 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -16,7 +16,7 @@ pub fn map_address_space(word: &str, span: Span) -> Result Result> { Ok(match word { - "position" => crate::BuiltIn::Position, + "position" => crate::BuiltIn::Position { invariant: false }, // vertex "vertex_index" => crate::BuiltIn::VertexIndex, "instance_index" => crate::BuiltIn::InstanceIndex, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index a41f21733..511f6b66f 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1254,16 +1254,14 @@ impl BindingParser { sampling, })) } - (None, Some(crate::BuiltIn::Position), None, None, true) => { - Ok(Some(crate::Binding::BuiltIn { - built_in: crate::BuiltIn::Position, - invariant: true, - })) + (None, Some(crate::BuiltIn::Position { .. }), None, None, invariant) => { + Ok(Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { + invariant, + }))) + } + (None, Some(built_in), None, None, false) => { + Ok(Some(crate::Binding::BuiltIn(built_in))) } - (None, Some(built_in), None, None, false) => Ok(Some(crate::Binding::BuiltIn { - built_in, - invariant: false, - })), (_, _, _, _, _) => Err(Error::InconsistentBinding(span)), } } diff --git a/src/lib.rs b/src/lib.rs index a90673895..5ab1449fd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -325,7 +325,7 @@ pub enum AddressSpace { #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum BuiltIn { - Position, + Position { invariant: bool }, ViewIndex, // vertex BaseInstance, @@ -748,11 +748,7 @@ pub enum ConstantInner { #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Binding { /// Built-in shader variable. - BuiltIn { - built_in: BuiltIn, - /// can only be `true` for [`BuiltIn::Position`] - invariant: bool, - }, + BuiltIn(BuiltIn), /// Indexed location. /// diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 4e11a24e1..bc15268f4 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -390,7 +390,7 @@ impl crate::Constant { impl crate::Binding { pub fn to_built_in(&self) -> Option { match *self { - crate::Binding::BuiltIn { built_in, .. } => Some(built_in), + crate::Binding::BuiltIn(built_in) => Some(built_in), Self::Location { .. } => None, } } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 7a31c3260..28a0f8a8a 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -455,7 +455,7 @@ impl FunctionInfo { E::FunctionArgument(index) => { let arg = &resolve_context.arguments[index as usize]; let uniform = match arg.binding { - Some(crate::Binding::BuiltIn { built_in, .. }) => match built_in { + Some(crate::Binding::BuiltIn(built_in)) => match built_in { // per-polygon built-ins are uniform crate::BuiltIn::FrontFacing // per-work-group built-ins are uniform diff --git a/src/valid/interface.rs b/src/valid/interface.rs index eb2471a7b..edaf7cca8 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -103,7 +103,7 @@ struct VaryingContext<'a> { output: bool, types: &'a UniqueArena, location_mask: &'a mut BitSet, - built_in_mask: u32, + built_ins: &'a mut crate::FastHashSet, capabilities: Capabilities, } @@ -115,12 +115,19 @@ impl VaryingContext<'_> { let ty_inner = &self.types[self.ty].inner; match *binding { - crate::Binding::BuiltIn { built_in, .. } => { - let bit = 1 << built_in as u32; - if self.built_in_mask & bit != 0 { + crate::Binding::BuiltIn(built_in) => { + // Ignore the `invariant` field for the sake of duplicate checks, + // but use the original in error messages. + let canonical = if let crate::BuiltIn::Position { .. } = built_in { + crate::BuiltIn::Position { invariant: false } + } else { + built_in + }; + + if self.built_ins.contains(&canonical) { return Err(VaryingError::DuplicateBuiltIn(built_in)); } - self.built_in_mask |= bit; + self.built_ins.insert(canonical); let width = 4; let (visible, type_good) = match built_in { @@ -153,7 +160,7 @@ impl VaryingContext<'_> { width, }, ), - Bi::Position => ( + Bi::Position { .. } => ( match self.stage { St::Vertex => self.output, St::Fragment => !self.output, @@ -457,7 +464,7 @@ impl super::Validator { } self.location_mask.clear(); - let mut argument_built_ins = 0; + let mut argument_built_ins = crate::FastHashSet::default(); // TODO: add span info to function arguments for (index, fa) in ep.function.arguments.iter().enumerate() { let mut ctx = VaryingContext { @@ -466,23 +473,23 @@ impl super::Validator { output: false, types: &module.types, location_mask: &mut self.location_mask, - built_in_mask: argument_built_ins, + built_ins: &mut argument_built_ins, capabilities: self.capabilities, }; ctx.validate(fa.binding.as_ref()) .map_err_inner(|e| EntryPointError::Argument(index as u32, e).with_span())?; - argument_built_ins = ctx.built_in_mask; } self.location_mask.clear(); if let Some(ref fr) = ep.function.result { + let mut result_built_ins = crate::FastHashSet::default(); let mut ctx = VaryingContext { ty: fr.ty, stage: ep.stage, output: true, types: &module.types, location_mask: &mut self.location_mask, - built_in_mask: 0, + built_ins: &mut result_built_ins, capabilities: self.capabilities, }; ctx.validate(fr.binding.as_ref()) diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index a4d86445b..50860b2cb 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -284,10 +284,7 @@ ( name: Some("global_id"), ty: 4, - binding: Some(BuiltIn( - built_in: GlobalInvocationId, - invariant: false, - )), + binding: Some(BuiltIn(GlobalInvocationId)), ), ], result: None, diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 7dc246b00..154747e5f 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -17,8 +17,8 @@ OpMemberDecorate %14 2 Offset 8 OpDecorate %16 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 -OpDecorate %22 BuiltIn FragCoord OpDecorate %22 Invariant +OpDecorate %22 BuiltIn FragCoord OpDecorate %25 Location 1 OpDecorate %28 BuiltIn FrontFacing OpDecorate %31 BuiltIn SampleId diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index de082608d..645077ca2 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -18,8 +18,8 @@ OpDecorate %21 BuiltIn VertexIndex OpDecorate %24 BuiltIn InstanceIndex OpDecorate %26 Location 10 OpDecorate %26 Flat -OpDecorate %28 BuiltIn Position OpDecorate %28 Invariant +OpDecorate %28 BuiltIn Position OpDecorate %30 Location 1 OpDecorate %32 BuiltIn PointSize %2 = OpTypeVoid diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index ea5313db0..190f391c3 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -16,8 +16,8 @@ OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 OpDecorate %24 BuiltIn VertexIndex OpDecorate %28 BuiltIn InstanceIndex -OpDecorate %30 BuiltIn Position OpDecorate %30 Invariant +OpDecorate %30 BuiltIn Position OpDecorate %32 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeFloat 32 From f11d27af6f7b7c8ffa5fee5f34add227e6e1c689 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 14 Apr 2022 09:36:53 -0700 Subject: [PATCH 1665/2212] Reject empty struct types. (#1826) --- src/lib.rs | 2 ++ src/valid/type.rs | 6 ++++++ tests/wgsl-errors.rs | 8 ++++++++ 3 files changed, 16 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 5ab1449fd..f82e88b4b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -676,6 +676,8 @@ pub enum TypeInner { /// User-defined structure. /// + /// There must always be at least one member. + /// /// A `Struct` type is [`DATA`], and the types of its members must be /// `DATA` as well. /// diff --git a/src/valid/type.rs b/src/valid/type.rs index 6eaa689d6..236fde99a 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -120,6 +120,8 @@ pub enum TypeError { size: u32, span: u32, }, + #[error("Structure types must have at least one member")] + EmptyStruct, } // Only makes sense if `flags.contains(HOST_SHARED)` @@ -451,6 +453,10 @@ impl super::Validator { } } Ti::Struct { ref members, span } => { + if members.is_empty() { + return Err(TypeError::EmptyStruct); + } + let mut ti = TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 71ed5ac91..9f341ff45 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -930,6 +930,14 @@ fn invalid_structs() { .. }) } + + check_validation_error! { + "struct Empty {}": + Err(naga::valid::ValidationError::Type { + error: naga::valid::TypeError::EmptyStruct, + .. + }) + } } #[test] From 438a7509679333573415595c35ef0a8f566a6470 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Apr 2022 18:27:56 -0700 Subject: [PATCH 1666/2212] Introduce TypeInner::is_dynamically_sized helper function. Use it in HLSL and GLSL back ends. --- src/back/glsl/mod.rs | 28 ++++++++++------------------ src/back/hlsl/writer.rs | 16 +++++++--------- src/proc/mod.rs | 12 ++++++++++++ 3 files changed, 29 insertions(+), 27 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b5750fb94..75cec00a6 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -570,27 +570,19 @@ impl<'a, W: Write> Writer<'a, W> { let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); - // Write all structs + // Write struct types. // - // This are always ordered because of the IR is structured in a way that you can't make a - // struct without adding all of it's members first + // This are always ordered because the IR is structured in a way that + // you can't make a struct without adding all of its members first. for (handle, ty) in self.module.types.iter() { if let TypeInner::Struct { ref members, .. } = ty.inner { - let generate_struct = match GlobalTypeKind::new(self.module, handle) { - GlobalTypeKind::WrappedStruct => true, - // If it's a global non-wrapped struct, it will be printed - // with the corresponding global variable. - GlobalTypeKind::Unsized(_) => false, - GlobalTypeKind::Other => { - let used_by_global = - self.module.global_variables.iter().any(|(vh, var)| { - !ep_info[vh].is_empty() && var.space.is_buffer() && var.ty == handle - }); - // If not used by a global, it's safe to just spew it here - !used_by_global - } - }; - if generate_struct { + // Structures ending with runtime-sized arrays can only be + // rendered as shader storage blocks in GLSL, not stand-alone + // struct types. + if !self.module.types[members.last().unwrap().ty] + .inner + .is_dynamically_sized(&self.module.types) + { let name = &self.names[&NameKey::Type(handle)]; write!(self.out, "struct {} ", name)?; self.write_struct_body(handle, members)?; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 3338c652a..28b1445bf 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -153,15 +153,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write all structs for (handle, ty) in module.types.iter() { if let TypeInner::Struct { ref members, span } = ty.inner { - if let Some(member) = members.last() { - if let TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } = module.types[member.ty].inner - { - // unsized arrays can only be in storage buffers, for which we use `ByteAddressBuffer` anyway. - continue; - } + if module.types[members.last().unwrap().ty] + .inner + .is_dynamically_sized(&module.types) + { + // unsized arrays can only be in storage buffers, + // for which we use `ByteAddressBuffer` anyway. + continue; } let ep_result = ep_results.iter().find(|e| { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index bc15268f4..f18bcd961 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -185,6 +185,18 @@ impl super::TypeInner { let right = rhs.canonical_form(types); left.as_ref().unwrap_or(self) == right.as_ref().unwrap_or(rhs) } + + pub fn is_dynamically_sized(&self, types: &crate::UniqueArena) -> bool { + use crate::TypeInner as Ti; + match *self { + Ti::Array { size, .. } => size == crate::ArraySize::Dynamic, + Ti::Struct { ref members, .. } => members + .last() + .map(|last| types[last.ty].inner.is_dynamically_sized(types)) + .unwrap_or(false), + _ => false, + } + } } impl super::AddressSpace { From 896e884802a7b14bd3dd25f91715fdb316a24ba6 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Apr 2022 18:28:47 -0700 Subject: [PATCH 1667/2212] [glsl-out] Use exhaustive match in AddressSpace::initializable. No change in behavior. Exhaustive matches aid error detection, and are clearer when the number of match arms isn't excessive. --- src/back/glsl/mod.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 75cec00a6..48d9313ba 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -98,11 +98,12 @@ impl crate::AddressSpace { /// Whether a variable with this address space can be initialized fn initializable(&self) -> bool { match *self { + crate::AddressSpace::Function | crate::AddressSpace::Private => true, crate::AddressSpace::WorkGroup | crate::AddressSpace::Uniform - | crate::AddressSpace::PushConstant - | crate::AddressSpace::Storage { .. } => false, - _ => true, + | crate::AddressSpace::Storage { .. } + | crate::AddressSpace::Handle + | crate::AddressSpace::PushConstant => false, } } } From cf1869016f681898da8069304515742cb3d8b4cf Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Apr 2022 18:31:28 -0700 Subject: [PATCH 1668/2212] [glsl-out] Rename `glsl_storage_class` to `glsl_storage_qualifier`. "Storage qualifier" is the term used in the GLSL ES specification. --- src/back/glsl/mod.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 48d9313ba..119fe2e10 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -948,10 +948,8 @@ impl<'a, W: Write> Writer<'a, W> { self.write_storage_access(access)?; } - // Write the storage class - // Trailing space is important - if let Some(storage_class) = glsl_storage_class(global.space) { - write!(self.out, "{} ", storage_class)?; + if let Some(storage_qualifier) = glsl_storage_qualifier(global.space) { + write!(self.out, "{} ", storage_qualifier)?; } // If struct is a block we need to write `block_name { members }` where `block_name` must be @@ -3197,7 +3195,7 @@ fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { } /// Helper function that returns the string corresponding to the address space -fn glsl_storage_class(space: crate::AddressSpace) -> Option<&'static str> { +fn glsl_storage_qualifier(space: crate::AddressSpace) -> Option<&'static str> { use crate::AddressSpace as As; match space { From 5d631d9e2dd02d203014c15df372338bc112cbb5 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Apr 2022 18:34:10 -0700 Subject: [PATCH 1669/2212] [glsl-out] Generate GLSL for arbitrary global types, per Naga IR. Delete `GlobalTypeKind`. Break out `Writer::write_global`'s code into two new functions, `write_simple_global` and `write_interface_block`. This introduces some repeated code, but the way we need to produce interface blocks and normal globals are sufficiently different that I think it's clearer overall to just separate them entirely. Much of the details are handled by their callees. Loosen the interface block code to support arbitrary types. --- src/back/glsl/mod.rs | 166 ++++++++++++++++++++++--------------------- 1 file changed, 84 insertions(+), 82 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 119fe2e10..47cbd920f 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -108,45 +108,6 @@ impl crate::AddressSpace { } } -#[derive(PartialEq)] -enum GlobalTypeKind<'a> { - WrappedStruct, - Unsized(&'a [crate::StructMember]), - Other, -} - -impl<'a> GlobalTypeKind<'a> { - //Note: similar to `back/spv/helpers.rs` - fn new(ir_module: &'a crate::Module, global_ty: Handle) -> Self { - match ir_module.types[global_ty].inner { - crate::TypeInner::Struct { - ref members, - span: _, - } => match ir_module.types[members.last().unwrap().ty].inner { - // Structs with dynamically sized arrays can't be copied and can't be wrapped. - crate::TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } => Self::Unsized(members), - _ => Self::WrappedStruct, - }, - // Naga IR permits globals to be dynamically sized arrays. Render - // these in GLSL as buffers. - crate::TypeInner::Array { - size: crate::ArraySize::Dynamic, - .. - } => Self::WrappedStruct, - // Naga IR permits globals to be constant sized arrays. Render - // these in GLSL as uniforms. - crate::TypeInner::Array { - size: crate::ArraySize::Constant(..), - .. - } => Self::WrappedStruct, - _ => Self::Other, - } - } -} - /// A GLSL version. #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -952,50 +913,34 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{} ", storage_qualifier)?; } - // If struct is a block we need to write `block_name { members }` where `block_name` must be - // unique between blocks and structs so we add `_block_ID` where `ID` is a `IdGenerator` - // generated number so it's unique and `members` are the same as in a struct - - // Write the block name, it's just the struct name appended with `_block_ID` - let needs_wrapper = if global.space.is_buffer() { - let ty_name = &self.names[&NameKey::Type(global.ty)]; - let block_name = format!( - "{}_block_{}{:?}", - ty_name, - self.block_id.generate(), - self.entry_point.stage, - ); - write!(self.out, "{} ", block_name)?; - self.reflection_names_globals.insert(handle, block_name); - - match GlobalTypeKind::new(self.module, global.ty) { - GlobalTypeKind::WrappedStruct => { - write!(self.out, "{{ ")?; - // Write the type - // `write_type` adds no leading or trailing spaces - self.write_type(global.ty)?; - true - } - GlobalTypeKind::Unsized(members) => { - self.write_struct_body(global.ty, members)?; - false - } - GlobalTypeKind::Other => { - return Err(Error::Custom("Non-struct type of a buffer".to_string())); - } + match global.space { + crate::AddressSpace::Private => { + self.write_simple_global(handle, global)?; } - } else { - self.write_type(global.ty)?; - false - }; - - if let crate::AddressSpace::PushConstant = global.space { - let global_name = self.get_global_name(handle, global); - self.reflection_names_globals.insert(handle, global_name); + crate::AddressSpace::WorkGroup => { + self.write_simple_global(handle, global)?; + } + crate::AddressSpace::PushConstant => { + self.write_simple_global(handle, global)?; + } + crate::AddressSpace::Uniform | crate::AddressSpace::Handle => { + self.write_interface_block(handle, global)?; + } + crate::AddressSpace::Storage { .. } => { + self.write_interface_block(handle, global)?; + } + crate::AddressSpace::Function => unreachable!(), } - // Finally write the global name and end the global with a `;` and a newline - // Leading space is important + Ok(()) + } + + fn write_simple_global( + &mut self, + handle: Handle, + global: &crate::GlobalVariable, + ) -> BackendResult { + self.write_type(global.ty)?; write!(self.out, " ")?; self.write_global_name(handle, global)?; @@ -1012,11 +957,68 @@ impl<'a, W: Write> Writer<'a, W> { } } - if needs_wrapper { - write!(self.out, "; }}")?; + writeln!(self.out, ";")?; + + if let crate::AddressSpace::PushConstant = global.space { + let global_name = self.get_global_name(handle, global); + self.reflection_names_globals.insert(handle, global_name); + } + + Ok(()) + } + + /// Write an interface block for a single Naga global. + /// + /// Write `block_name { members }`. Since `block_name` must be unique + /// between blocks and structs, we add `_block_ID` where `ID` is a + /// `IdGenerator` generated number. Write `members` in the same way we write + /// a struct's members. + fn write_interface_block( + &mut self, + handle: Handle, + global: &crate::GlobalVariable, + ) -> BackendResult { + // Write the block name, it's just the struct name appended with `_block_ID` + let ty_name = &self.names[&NameKey::Type(global.ty)]; + let block_name = format!( + "{}_block_{}{:?}", + ty_name, + self.block_id.generate(), + self.entry_point.stage, + ); + write!(self.out, "{} ", block_name)?; + self.reflection_names_globals.insert(handle, block_name); + + match self.module.types[global.ty].inner { + crate::TypeInner::Struct { ref members, .. } + if self.module.types[members.last().unwrap().ty] + .inner + .is_dynamically_sized(&self.module.types) => + { + // Structs with dynamically sized arrays must have their + // members lifted up as members of the interface block. GLSL + // can't write such struct types anyway. + self.write_struct_body(global.ty, members)?; + write!(self.out, " ")?; + self.write_global_name(handle, global)?; + } + _ => { + // A global of any other type is written as the sole member + // of the interface block. Since the interface block is + // anonymous, this becomes visible in the global scope. + write!(self.out, "{{ ")?; + self.write_type(global.ty)?; + write!(self.out, " ")?; + self.write_global_name(handle, global)?; + if let TypeInner::Array { base, size, .. } = self.module.types[global.ty].inner { + self.write_array_size(base, size)?; + } + write!(self.out, "; }}")?; + } } writeln!(self.out, ";")?; + Ok(()) } From 27d0fee2e7cd4b7e21b05f083f5d0277acddd98c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Apr 2022 18:54:42 -0700 Subject: [PATCH 1670/2212] More tests for non-struct global types. --- src/back/glsl/mod.rs | 6 +- tests/in/globals.wgsl | 6 + tests/out/glsl/globals.main.Compute.glsl | 22 +- tests/out/hlsl/globals.hlsl | 19 +- tests/out/msl/globals.msl | 20 +- tests/out/spv/globals.spvasm | 262 +++++++++++++---------- tests/out/wgsl/globals.wgsl | 20 +- 7 files changed, 214 insertions(+), 141 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 47cbd920f..c4d66afd6 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -923,13 +923,17 @@ impl<'a, W: Write> Writer<'a, W> { crate::AddressSpace::PushConstant => { self.write_simple_global(handle, global)?; } - crate::AddressSpace::Uniform | crate::AddressSpace::Handle => { + crate::AddressSpace::Uniform => { self.write_interface_block(handle, global)?; } crate::AddressSpace::Storage { .. } => { self.write_interface_block(handle, global)?; } + // A global variable in the `Function` address space is a + // contradiction in terms. crate::AddressSpace::Function => unreachable!(), + // Textures and samplers are handled directly in `Writer::write`. + crate::AddressSpace::Handle => unreachable!(), } Ok(()) diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 86a41569d..573c1575c 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -19,6 +19,9 @@ var dummy: array>; @group(0) @binding(3) var float_vecs: array, 20>; +@group(0) @binding(4) +var global_vec: vec4; + fn test_msl_packed_vec3_as_arg(arg: vec3) {} fn test_msl_packed_vec3() { @@ -50,6 +53,9 @@ fn test_msl_packed_vec3() { fn main() { test_msl_packed_vec3(); + wg[6] = global_vec.x; + wg[5] = dummy[1].y; + wg[4] = float_vecs[0].w; wg[3] = alignment.v1; wg[2] = alignment.v3.x; alignment.v1 = 4.0; diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index 0db8ee14b..785a3d1e1 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -17,6 +17,10 @@ layout(std430) buffer Foo_block_0Compute { Foo _group_0_binding_1_cs; }; layout(std430) readonly buffer type_6_block_1Compute { vec2 _group_0_binding_2_cs[]; }; +uniform type_8_block_2Compute { vec4 _group_0_binding_3_cs[20]; }; + +uniform type_7_block_3Compute { vec4 _group_0_binding_4_cs; }; + void test_msl_packed_vec3_as_arg(vec3 arg) { return; @@ -27,8 +31,8 @@ void test_msl_packed_vec3_() { _group_0_binding_1_cs.v3_ = vec3(1.0); _group_0_binding_1_cs.v3_.x = 1.0; _group_0_binding_1_cs.v3_.x = 2.0; - int _e19 = idx; - _group_0_binding_1_cs.v3_[_e19] = 3.0; + int _e20 = idx; + _group_0_binding_1_cs.v3_[_e20] = 3.0; Foo data = _group_0_binding_1_cs; vec3 unnamed = data.v3_; vec2 unnamed_1 = data.v3_.zx; @@ -43,10 +47,16 @@ void main() { float Foo_1 = 1.0; bool at = true; test_msl_packed_vec3_(); - float _e9 = _group_0_binding_1_cs.v1_; - wg[3] = _e9; - float _e14 = _group_0_binding_1_cs.v3_.x; - wg[2] = _e14; + float _e10 = _group_0_binding_4_cs.x; + wg[6] = _e10; + float _e16 = _group_0_binding_2_cs[1].y; + wg[5] = _e16; + float _e22 = _group_0_binding_3_cs[0].w; + wg[4] = _e22; + float _e26 = _group_0_binding_1_cs.v1_; + wg[3] = _e26; + float _e31 = _group_0_binding_1_cs.v3_.x; + wg[2] = _e31; _group_0_binding_1_cs.v1_ = 4.0; wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 7844ddf35..abf543ff6 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -10,6 +10,7 @@ groupshared uint at_1; RWByteAddressBuffer alignment : register(u1); ByteAddressBuffer dummy : register(t2); cbuffer float_vecs : register(b3) { float4 float_vecs[20]; } +cbuffer global_vec : register(b4) { float4 global_vec; } void test_msl_packed_vec3_as_arg(float3 arg) { @@ -23,8 +24,8 @@ void test_msl_packed_vec3_() alignment.Store3(0, asuint(float3(1.0.xxx))); alignment.Store(0+0, asuint(1.0)); alignment.Store(0+0, asuint(2.0)); - int _expr19 = idx; - alignment.Store(_expr19*4+0, asuint(3.0)); + int _expr20 = idx; + alignment.Store(_expr20*4+0, asuint(3.0)); Foo data = {asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))}; float3 unnamed = data.v3_; float2 unnamed_1 = data.v3_.zx; @@ -49,10 +50,16 @@ void main() bool at = true; test_msl_packed_vec3_(); - float _expr9 = asfloat(alignment.Load(12)); - wg[3] = _expr9; - float _expr14 = asfloat(alignment.Load(0+0)); - wg[2] = _expr14; + float _expr10 = global_vec.x; + wg[6] = _expr10; + float _expr16 = asfloat(dummy.Load(4+8)); + wg[5] = _expr16; + float _expr22 = float_vecs[0].w; + wg[4] = _expr22; + float _expr26 = asfloat(alignment.Load(12)); + wg[3] = _expr26; + float _expr31 = asfloat(alignment.Load(0+0)); + wg[2] = _expr31; alignment.Store(12, asuint(4.0)); wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 504e41d57..3c83f67dd 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -36,8 +36,8 @@ void test_msl_packed_vec3_( alignment.v3_ = metal::float3(1.0); alignment.v3_[0] = 1.0; alignment.v3_[0] = 2.0; - int _e19 = idx; - alignment.v3_[_e19] = 3.0; + int _e20 = idx; + alignment.v3_[_e20] = 3.0; Foo data = alignment; metal::float3 unnamed = data.v3_; metal::float2 unnamed_1 = metal::float3(data.v3_).zx; @@ -53,15 +53,23 @@ kernel void main_( , threadgroup metal::atomic_uint& at_1 , device Foo& alignment [[user(fake0)]] , device type_6 const& dummy [[user(fake0)]] +, constant type_8& float_vecs [[user(fake0)]] +, constant metal::float4& global_vec [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { float Foo_1 = 1.0; bool at = true; test_msl_packed_vec3_(alignment); - float _e9 = alignment.v1_; - wg.inner[3] = _e9; - float _e14 = alignment.v3_[0]; - wg.inner[2] = _e14; + float _e10 = global_vec.x; + wg.inner[6] = _e10; + float _e16 = dummy[1].y; + wg.inner[5] = _e16; + float _e22 = float_vecs.inner[0].w; + wg.inner[4] = _e22; + float _e26 = alignment.v1_; + wg.inner[3] = _e26; + float _e31 = alignment.v3_[0]; + wg.inner[2] = _e31; alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 395096db3..07e6da2a7 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,31 +1,35 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 107 +; Bound: 130 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %87 "main" -OpExecutionMode %87 LocalSize 1 1 1 -OpDecorate %21 ArrayStride 4 -OpMemberDecorate %23 0 Offset 0 -OpMemberDecorate %23 1 Offset 12 -OpDecorate %25 ArrayStride 8 -OpDecorate %27 ArrayStride 16 -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 1 -OpDecorate %36 Block -OpMemberDecorate %36 0 Offset 0 -OpDecorate %38 NonWritable +OpEntryPoint GLCompute %94 "main" +OpExecutionMode %94 LocalSize 1 1 1 +OpDecorate %24 ArrayStride 4 +OpMemberDecorate %26 0 Offset 0 +OpMemberDecorate %26 1 Offset 12 +OpDecorate %28 ArrayStride 8 +OpDecorate %30 ArrayStride 16 OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 2 +OpDecorate %38 Binding 1 OpDecorate %39 Block OpMemberDecorate %39 0 Offset 0 +OpDecorate %41 NonWritable OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 3 +OpDecorate %41 Binding 2 OpDecorate %42 Block OpMemberDecorate %42 0 Offset 0 +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 3 +OpDecorate %45 Block +OpMemberDecorate %45 0 Offset 0 +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 4 +OpDecorate %48 Block +OpMemberDecorate %48 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -40,112 +44,138 @@ OpMemberDecorate %42 0 Offset 0 %13 = OpConstant %10 2.0 %14 = OpConstant %10 3.0 %15 = OpConstant %10 0.0 -%16 = OpConstant %8 3 -%17 = OpConstant %8 2 -%18 = OpConstant %10 4.0 -%19 = OpConstant %6 2 -%20 = OpConstantTrue %4 -%21 = OpTypeArray %10 %5 -%22 = OpTypeVector %10 3 -%23 = OpTypeStruct %22 %10 -%24 = OpTypeVector %10 2 -%25 = OpTypeRuntimeArray %24 -%26 = OpTypeVector %10 4 -%27 = OpTypeArray %26 %7 -%28 = OpTypeMatrix %22 3 -%29 = OpConstantComposite %22 %15 %15 %15 -%30 = OpConstantComposite %28 %29 %29 %29 -%32 = OpTypePointer Workgroup %21 -%31 = OpVariable %32 Workgroup -%34 = OpTypePointer Workgroup %6 -%33 = OpVariable %34 Workgroup -%36 = OpTypeStruct %23 -%37 = OpTypePointer StorageBuffer %36 -%35 = OpVariable %37 StorageBuffer -%39 = OpTypeStruct %25 +%16 = OpConstant %8 6 +%17 = OpConstant %8 5 +%18 = OpConstant %8 4 +%19 = OpConstant %8 3 +%20 = OpConstant %8 2 +%21 = OpConstant %10 4.0 +%22 = OpConstant %6 2 +%23 = OpConstantTrue %4 +%24 = OpTypeArray %10 %5 +%25 = OpTypeVector %10 3 +%26 = OpTypeStruct %25 %10 +%27 = OpTypeVector %10 2 +%28 = OpTypeRuntimeArray %27 +%29 = OpTypeVector %10 4 +%30 = OpTypeArray %29 %7 +%31 = OpTypeMatrix %25 3 +%32 = OpConstantComposite %25 %15 %15 %15 +%33 = OpConstantComposite %31 %32 %32 %32 +%35 = OpTypePointer Workgroup %24 +%34 = OpVariable %35 Workgroup +%37 = OpTypePointer Workgroup %6 +%36 = OpVariable %37 Workgroup +%39 = OpTypeStruct %26 %40 = OpTypePointer StorageBuffer %39 %38 = OpVariable %40 StorageBuffer -%42 = OpTypeStruct %27 -%43 = OpTypePointer Uniform %42 -%41 = OpVariable %43 Uniform -%47 = OpTypeFunction %2 %22 -%48 = OpTypePointer StorageBuffer %23 -%49 = OpTypePointer StorageBuffer %25 -%50 = OpTypePointer Uniform %27 -%53 = OpTypePointer Function %8 -%56 = OpTypeFunction %2 -%57 = OpConstant %6 0 -%60 = OpTypePointer StorageBuffer %22 -%63 = OpTypePointer StorageBuffer %10 -%83 = OpTypePointer Function %10 -%85 = OpTypePointer Function %4 -%92 = OpTypePointer Workgroup %10 -%93 = OpTypePointer StorageBuffer %10 -%94 = OpConstant %6 1 -%97 = OpConstant %6 3 -%106 = OpConstant %6 256 -%46 = OpFunction %2 None %47 -%45 = OpFunctionParameter %22 -%44 = OpLabel -OpBranch %51 -%51 = OpLabel +%42 = OpTypeStruct %28 +%43 = OpTypePointer StorageBuffer %42 +%41 = OpVariable %43 StorageBuffer +%45 = OpTypeStruct %30 +%46 = OpTypePointer Uniform %45 +%44 = OpVariable %46 Uniform +%48 = OpTypeStruct %29 +%49 = OpTypePointer Uniform %48 +%47 = OpVariable %49 Uniform +%53 = OpTypeFunction %2 %25 +%54 = OpTypePointer StorageBuffer %26 +%55 = OpTypePointer StorageBuffer %28 +%56 = OpTypePointer Uniform %29 +%57 = OpTypePointer Uniform %30 +%60 = OpTypePointer Function %8 +%63 = OpTypeFunction %2 +%64 = OpConstant %6 0 +%67 = OpTypePointer StorageBuffer %25 +%70 = OpTypePointer StorageBuffer %10 +%90 = OpTypePointer Function %10 +%92 = OpTypePointer Function %4 +%101 = OpTypePointer Workgroup %10 +%102 = OpTypePointer Uniform %10 +%105 = OpConstant %6 6 +%107 = OpTypePointer StorageBuffer %27 +%108 = OpConstant %6 1 +%111 = OpConstant %6 5 +%113 = OpConstant %6 3 +%116 = OpConstant %6 4 +%118 = OpTypePointer StorageBuffer %10 +%129 = OpConstant %6 256 +%52 = OpFunction %2 None %53 +%51 = OpFunctionParameter %25 +%50 = OpLabel +OpBranch %58 +%58 = OpLabel OpReturn OpFunctionEnd -%55 = OpFunction %2 None %56 -%54 = OpLabel -%52 = OpVariable %53 Function %11 -%58 = OpAccessChain %48 %35 %57 -OpBranch %59 -%59 = OpLabel -%61 = OpCompositeConstruct %22 %9 %9 %9 -%62 = OpAccessChain %60 %58 %57 -OpStore %62 %61 -%64 = OpAccessChain %63 %58 %57 %57 -OpStore %64 %9 -%65 = OpAccessChain %63 %58 %57 %57 -OpStore %65 %13 -%66 = OpLoad %8 %52 -%67 = OpAccessChain %63 %58 %57 %66 -OpStore %67 %14 -%68 = OpLoad %23 %58 -%69 = OpCompositeExtract %22 %68 0 -%70 = OpCompositeExtract %22 %68 0 -%71 = OpVectorShuffle %24 %70 %70 2 0 -%72 = OpCompositeExtract %22 %68 0 -%73 = OpFunctionCall %2 %46 %72 -%74 = OpCompositeExtract %22 %68 0 -%75 = OpVectorTimesMatrix %22 %74 %30 -%76 = OpCompositeExtract %22 %68 0 -%77 = OpMatrixTimesVector %22 %30 %76 -%78 = OpCompositeExtract %22 %68 0 -%79 = OpVectorTimesScalar %22 %78 %13 -%80 = OpCompositeExtract %22 %68 0 -%81 = OpVectorTimesScalar %22 %80 %13 +%62 = OpFunction %2 None %63 +%61 = OpLabel +%59 = OpVariable %60 Function %11 +%65 = OpAccessChain %54 %38 %64 +OpBranch %66 +%66 = OpLabel +%68 = OpCompositeConstruct %25 %9 %9 %9 +%69 = OpAccessChain %67 %65 %64 +OpStore %69 %68 +%71 = OpAccessChain %70 %65 %64 %64 +OpStore %71 %9 +%72 = OpAccessChain %70 %65 %64 %64 +OpStore %72 %13 +%73 = OpLoad %8 %59 +%74 = OpAccessChain %70 %65 %64 %73 +OpStore %74 %14 +%75 = OpLoad %26 %65 +%76 = OpCompositeExtract %25 %75 0 +%77 = OpCompositeExtract %25 %75 0 +%78 = OpVectorShuffle %27 %77 %77 2 0 +%79 = OpCompositeExtract %25 %75 0 +%80 = OpFunctionCall %2 %52 %79 +%81 = OpCompositeExtract %25 %75 0 +%82 = OpVectorTimesMatrix %25 %81 %33 +%83 = OpCompositeExtract %25 %75 0 +%84 = OpMatrixTimesVector %25 %33 %83 +%85 = OpCompositeExtract %25 %75 0 +%86 = OpVectorTimesScalar %25 %85 %13 +%87 = OpCompositeExtract %25 %75 0 +%88 = OpVectorTimesScalar %25 %87 %13 OpReturn OpFunctionEnd -%87 = OpFunction %2 None %56 -%86 = OpLabel -%82 = OpVariable %83 Function %9 -%84 = OpVariable %85 Function %20 -%88 = OpAccessChain %48 %35 %57 -%89 = OpAccessChain %49 %38 %57 -OpBranch %90 -%90 = OpLabel -%91 = OpFunctionCall %2 %55 -%95 = OpAccessChain %93 %88 %94 -%96 = OpLoad %10 %95 -%98 = OpAccessChain %92 %31 %97 -OpStore %98 %96 -%99 = OpAccessChain %63 %88 %57 %57 -%100 = OpLoad %10 %99 -%101 = OpAccessChain %92 %31 %19 -OpStore %101 %100 -%102 = OpAccessChain %93 %88 %94 -OpStore %102 %18 -%103 = OpArrayLength %6 %38 0 -%104 = OpConvertUToF %10 %103 -%105 = OpAccessChain %92 %31 %94 -OpStore %105 %104 -OpAtomicStore %33 %17 %106 %19 +%94 = OpFunction %2 None %63 +%93 = OpLabel +%89 = OpVariable %90 Function %9 +%91 = OpVariable %92 Function %23 +%95 = OpAccessChain %54 %38 %64 +%96 = OpAccessChain %55 %41 %64 +%97 = OpAccessChain %57 %44 %64 +%98 = OpAccessChain %56 %47 %64 +OpBranch %99 +%99 = OpLabel +%100 = OpFunctionCall %2 %62 +%103 = OpAccessChain %102 %98 %64 +%104 = OpLoad %10 %103 +%106 = OpAccessChain %101 %34 %105 +OpStore %106 %104 +%109 = OpAccessChain %70 %96 %108 %108 +%110 = OpLoad %10 %109 +%112 = OpAccessChain %101 %34 %111 +OpStore %112 %110 +%114 = OpAccessChain %102 %97 %64 %113 +%115 = OpLoad %10 %114 +%117 = OpAccessChain %101 %34 %116 +OpStore %117 %115 +%119 = OpAccessChain %118 %95 %108 +%120 = OpLoad %10 %119 +%121 = OpAccessChain %101 %34 %113 +OpStore %121 %120 +%122 = OpAccessChain %70 %95 %64 %64 +%123 = OpLoad %10 %122 +%124 = OpAccessChain %101 %34 %22 +OpStore %124 %123 +%125 = OpAccessChain %118 %95 %108 +OpStore %125 %21 +%126 = OpArrayLength %6 %41 0 +%127 = OpConvertUToF %10 %126 +%128 = OpAccessChain %101 %34 %108 +OpStore %128 %127 +OpAtomicStore %36 %20 %129 %22 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 7c9ca8056..73b436ddd 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -13,6 +13,8 @@ var alignment: Foo; var dummy: array>; @group(0) @binding(3) var float_vecs: array,20>; +@group(0) @binding(4) +var global_vec: vec4; fn test_msl_packed_vec3_as_arg(arg: vec3) { return; @@ -24,8 +26,8 @@ fn test_msl_packed_vec3_() { alignment.v3_ = vec3(1.0); alignment.v3_.x = 1.0; alignment.v3_.x = 2.0; - let _e19 = idx; - alignment.v3_[_e19] = 3.0; + let _e20 = idx; + alignment.v3_[_e20] = 3.0; let data = alignment; let unnamed = data.v3_; let unnamed_1 = data.v3_.zx; @@ -42,10 +44,16 @@ fn main() { var at: bool = true; test_msl_packed_vec3_(); - let _e9 = alignment.v1_; - wg[3] = _e9; - let _e14 = alignment.v3_.x; - wg[2] = _e14; + let _e10 = global_vec.x; + wg[6] = _e10; + let _e16 = dummy[1].y; + wg[5] = _e16; + let _e22 = float_vecs[0].w; + wg[4] = _e22; + let _e26 = alignment.v1_; + wg[3] = _e26; + let _e31 = alignment.v3_.x; + wg[2] = _e31; alignment.v1_ = 4.0; wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); From 1a0a48fd69a12d1e5f204f0c5e4094c689103643 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 8 Apr 2022 16:15:39 -0700 Subject: [PATCH 1671/2212] [spv-out] Decorate array and struct type layouts unconditionally. Remove the `decorate_layout` variable, which is unconditionally set to `true` anyway. --- src/back/spv/writer.rs | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 19d788b8a..cf6093370 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -799,8 +799,6 @@ impl Writer { handle: Handle, ) -> Result { let ty = &arena[handle]; - let decorate_layout = true; //TODO? - let id = if let Some(local) = make_local(&ty.inner) { // This type can be represented as a `LocalType`, so check if we've // already written an instruction for it. If not, do so now, with @@ -829,9 +827,7 @@ impl Writer { let id = self.id_gen.next(); let instruction = match ty.inner { crate::TypeInner::Array { base, size, stride } => { - if decorate_layout { - self.decorate(id, Decoration::ArrayStride, &[stride]); - } + self.decorate(id, Decoration::ArrayStride, &[stride]); let type_id = self.get_type_id(LookupType::Handle(base)); match size { @@ -848,14 +844,12 @@ impl Writer { } => { let mut member_ids = Vec::with_capacity(members.len()); for (index, member) in members.iter().enumerate() { - if decorate_layout { - self.annotations.push(Instruction::member_decorate( - id, - index as u32, - Decoration::Offset, - &[member.offset], - )); - } + self.annotations.push(Instruction::member_decorate( + id, + index as u32, + Decoration::Offset, + &[member.offset], + )); if self.flags.contains(WriterFlags::DEBUG) { if let Some(ref name) = member.name { From 97fffccac7da222a09b3a32bee031c88f993fbbc Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 8 Apr 2022 16:42:00 -0700 Subject: [PATCH 1672/2212] [spv-out] Emit required decorations on wrapper struct types, too. Fixes #1810. --- src/back/spv/helpers.rs | 16 +++++- src/back/spv/writer.rs | 119 +++++++++++++++++++++++----------------- 2 files changed, 84 insertions(+), 51 deletions(-) diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index acde9504d..60f86c691 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -62,7 +62,21 @@ impl crate::AddressSpace { } } -/// Return true if the global requires a type decorated with "Block". +/// Return true if the global requires a type decorated with `Block`. +/// +/// Vulkan spec v1.3 §15.6.2, "Descriptor Set Interface", says: +/// +/// > Variables identified with the `Uniform` storage class are used to +/// > access transparent buffer backed resources. Such variables must +/// > be: +/// > +/// > - typed as `OpTypeStruct`, or an array of this type, +/// > +/// > - identified with a `Block` or `BufferBlock` decoration, and +/// > +/// > - laid out explicitly using the `Offset`, `ArrayStride`, and +/// > `MatrixStride` decorations as specified in §15.6.4, "Offset +/// > and Stride Assignment." // See `back::spv::GlobalVariable::access_id` for details. pub fn global_needs_wrapper(ir_module: &crate::Module, var: &crate::GlobalVariable) -> bool { match var.space { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index cf6093370..cc0c47085 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -844,50 +844,7 @@ impl Writer { } => { let mut member_ids = Vec::with_capacity(members.len()); for (index, member) in members.iter().enumerate() { - self.annotations.push(Instruction::member_decorate( - id, - index as u32, - Decoration::Offset, - &[member.offset], - )); - - if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = member.name { - self.debugs - .push(Instruction::member_name(id, index as u32, name)); - } - } - - // The matrix decorations also go on arrays of matrices, - // so lets check this first. - let member_array_subty_inner = match arena[member.ty].inner { - crate::TypeInner::Array { base, .. } => &arena[base].inner, - ref other => other, - }; - if let crate::TypeInner::Matrix { - columns: _, - rows, - width, - } = *member_array_subty_inner - { - let byte_stride = match rows { - crate::VectorSize::Bi => 2 * width, - crate::VectorSize::Tri | crate::VectorSize::Quad => 4 * width, - }; - self.annotations.push(Instruction::member_decorate( - id, - index as u32, - Decoration::ColMajor, - &[], - )); - self.annotations.push(Instruction::member_decorate( - id, - index as u32, - Decoration::MatrixStride, - &[byte_stride as u32], - )); - } - + self.decorate_struct_member(id, index, member, arena)?; let member_id = self.get_type_id(LookupType::Handle(member.ty)); member_ids.push(member_id); } @@ -1281,12 +1238,14 @@ impl Writer { let wrapper_type_id = self.id_gen.next(); self.decorate(wrapper_type_id, Decoration::Block, &[]); - self.annotations.push(Instruction::member_decorate( - wrapper_type_id, - 0, - Decoration::Offset, - &[0], - )); + let member = crate::StructMember { + name: None, + ty: global_variable.ty, + binding: None, + offset: 0, + }; + self.decorate_struct_member(wrapper_type_id, 0, &member, &ir_module.types)?; + Instruction::type_struct(wrapper_type_id, &[inner_type_id]) .to_words(&mut self.logical_layout.declarations); @@ -1311,6 +1270,66 @@ impl Writer { Ok(id) } + /// Write the necessary decorations for a struct member. + /// + /// Emit decorations for the `index`'th member of the struct type + /// designated by `struct_id`, described by `member`. + fn decorate_struct_member( + &mut self, + struct_id: Word, + index: usize, + member: &crate::StructMember, + arena: &UniqueArena, + ) -> Result<(), Error> { + use spirv::Decoration; + + self.annotations.push(Instruction::member_decorate( + struct_id, + index as u32, + Decoration::Offset, + &[member.offset], + )); + + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = member.name { + self.debugs + .push(Instruction::member_name(struct_id, index as u32, name)); + } + } + + // Matrices and arrays of matrices both require decorations, + // so "see through" an array to determine if they're needed. + let member_array_subty_inner = match arena[member.ty].inner { + crate::TypeInner::Array { base, .. } => &arena[base].inner, + ref other => other, + }; + if let crate::TypeInner::Matrix { + columns: _, + rows, + width, + } = *member_array_subty_inner + { + let byte_stride = match rows { + crate::VectorSize::Bi => 2 * width, + crate::VectorSize::Tri | crate::VectorSize::Quad => 4 * width, + }; + self.annotations.push(Instruction::member_decorate( + struct_id, + index as u32, + Decoration::ColMajor, + &[], + )); + self.annotations.push(Instruction::member_decorate( + struct_id, + index as u32, + Decoration::MatrixStride, + &[byte_stride as u32], + )); + } + + Ok(()) + } + fn get_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word { match self .lookup_function_type From bdbf821c3247742f0fa069636d03937b8166c7aa Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Apr 2022 19:02:37 -0700 Subject: [PATCH 1673/2212] Test matrix-typed uniform globals. --- tests/in/globals.wgsl | 5 +- tests/out/glsl/globals.main.Compute.glsl | 27 ++- tests/out/hlsl/globals.hlsl | 26 ++- tests/out/msl/globals.msl | 32 +-- tests/out/spv/globals.spvasm | 278 ++++++++++++----------- tests/out/wgsl/globals.wgsl | 27 ++- 6 files changed, 211 insertions(+), 184 deletions(-) diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 573c1575c..a4467eae7 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -22,6 +22,9 @@ var float_vecs: array, 20>; @group(0) @binding(4) var global_vec: vec4; +@group(0) @binding(5) +var global_mat: mat4x4; + fn test_msl_packed_vec3_as_arg(arg: vec3) {} fn test_msl_packed_vec3() { @@ -53,7 +56,7 @@ fn test_msl_packed_vec3() { fn main() { test_msl_packed_vec3(); - wg[6] = global_vec.x; + wg[6] = (global_mat * global_vec).x; wg[5] = dummy[1].y; wg[4] = float_vecs[0].w; wg[3] = alignment.v1; diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index 785a3d1e1..40066567f 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -21,6 +21,8 @@ uniform type_8_block_2Compute { vec4 _group_0_binding_3_cs[20]; }; uniform type_7_block_3Compute { vec4 _group_0_binding_4_cs; }; +uniform type_9_block_4Compute { mat4x4 _group_0_binding_5_cs; }; + void test_msl_packed_vec3_as_arg(vec3 arg) { return; @@ -31,8 +33,8 @@ void test_msl_packed_vec3_() { _group_0_binding_1_cs.v3_ = vec3(1.0); _group_0_binding_1_cs.v3_.x = 1.0; _group_0_binding_1_cs.v3_.x = 2.0; - int _e20 = idx; - _group_0_binding_1_cs.v3_[_e20] = 3.0; + int _e21 = idx; + _group_0_binding_1_cs.v3_[_e21] = 3.0; Foo data = _group_0_binding_1_cs; vec3 unnamed = data.v3_; vec2 unnamed_1 = data.v3_.zx; @@ -47,16 +49,17 @@ void main() { float Foo_1 = 1.0; bool at = true; test_msl_packed_vec3_(); - float _e10 = _group_0_binding_4_cs.x; - wg[6] = _e10; - float _e16 = _group_0_binding_2_cs[1].y; - wg[5] = _e16; - float _e22 = _group_0_binding_3_cs[0].w; - wg[4] = _e22; - float _e26 = _group_0_binding_1_cs.v1_; - wg[3] = _e26; - float _e31 = _group_0_binding_1_cs.v3_.x; - wg[2] = _e31; + mat4x4 _e10 = _group_0_binding_5_cs; + vec4 _e11 = _group_0_binding_4_cs; + wg[6] = (_e10 * _e11).x; + float _e19 = _group_0_binding_2_cs[1].y; + wg[5] = _e19; + float _e25 = _group_0_binding_3_cs[0].w; + wg[4] = _e25; + float _e29 = _group_0_binding_1_cs.v1_; + wg[3] = _e29; + float _e34 = _group_0_binding_1_cs.v3_.x; + wg[2] = _e34; _group_0_binding_1_cs.v1_ = 4.0; wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index abf543ff6..cb9e1b4bb 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -11,6 +11,7 @@ RWByteAddressBuffer alignment : register(u1); ByteAddressBuffer dummy : register(t2); cbuffer float_vecs : register(b3) { float4 float_vecs[20]; } cbuffer global_vec : register(b4) { float4 global_vec; } +cbuffer global_mat : register(b5) { float4x4 global_mat; } void test_msl_packed_vec3_as_arg(float3 arg) { @@ -24,8 +25,8 @@ void test_msl_packed_vec3_() alignment.Store3(0, asuint(float3(1.0.xxx))); alignment.Store(0+0, asuint(1.0)); alignment.Store(0+0, asuint(2.0)); - int _expr20 = idx; - alignment.Store(_expr20*4+0, asuint(3.0)); + int _expr21 = idx; + alignment.Store(_expr21*4+0, asuint(3.0)); Foo data = {asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))}; float3 unnamed = data.v3_; float2 unnamed_1 = data.v3_.zx; @@ -50,16 +51,17 @@ void main() bool at = true; test_msl_packed_vec3_(); - float _expr10 = global_vec.x; - wg[6] = _expr10; - float _expr16 = asfloat(dummy.Load(4+8)); - wg[5] = _expr16; - float _expr22 = float_vecs[0].w; - wg[4] = _expr22; - float _expr26 = asfloat(alignment.Load(12)); - wg[3] = _expr26; - float _expr31 = asfloat(alignment.Load(0+0)); - wg[2] = _expr31; + float4x4 _expr10 = global_mat; + float4 _expr11 = global_vec; + wg[6] = mul(_expr11, _expr10).x; + float _expr19 = asfloat(dummy.Load(4+8)); + wg[5] = _expr19; + float _expr25 = float_vecs[0].w; + wg[4] = _expr25; + float _expr29 = asfloat(alignment.Load(12)); + wg[3] = _expr29; + float _expr34 = asfloat(alignment.Load(0+0)); + wg[2] = _expr34; alignment.Store(12, asuint(4.0)); wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 3c83f67dd..b02d6056d 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -21,7 +21,7 @@ struct type_8 { metal::float4 inner[20]; }; constant metal::float3 const_type_4_ = {0.0, 0.0, 0.0}; -constant metal::float3x3 const_type_10_ = {const_type_4_, const_type_4_, const_type_4_}; +constant metal::float3x3 const_type_11_ = {const_type_4_, const_type_4_, const_type_4_}; void test_msl_packed_vec3_as_arg( metal::float3 arg @@ -36,14 +36,14 @@ void test_msl_packed_vec3_( alignment.v3_ = metal::float3(1.0); alignment.v3_[0] = 1.0; alignment.v3_[0] = 2.0; - int _e20 = idx; - alignment.v3_[_e20] = 3.0; + int _e21 = idx; + alignment.v3_[_e21] = 3.0; Foo data = alignment; metal::float3 unnamed = data.v3_; metal::float2 unnamed_1 = metal::float3(data.v3_).zx; test_msl_packed_vec3_as_arg(data.v3_); - metal::float3 unnamed_2 = metal::float3(data.v3_) * const_type_10_; - metal::float3 unnamed_3 = const_type_10_ * metal::float3(data.v3_); + metal::float3 unnamed_2 = metal::float3(data.v3_) * const_type_11_; + metal::float3 unnamed_3 = const_type_11_ * metal::float3(data.v3_); metal::float3 unnamed_4 = data.v3_ * 2.0; metal::float3 unnamed_5 = 2.0 * data.v3_; } @@ -55,21 +55,23 @@ kernel void main_( , device type_6 const& dummy [[user(fake0)]] , constant type_8& float_vecs [[user(fake0)]] , constant metal::float4& global_vec [[user(fake0)]] +, constant metal::float4x4& global_mat [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { float Foo_1 = 1.0; bool at = true; test_msl_packed_vec3_(alignment); - float _e10 = global_vec.x; - wg.inner[6] = _e10; - float _e16 = dummy[1].y; - wg.inner[5] = _e16; - float _e22 = float_vecs.inner[0].w; - wg.inner[4] = _e22; - float _e26 = alignment.v1_; - wg.inner[3] = _e26; - float _e31 = alignment.v3_[0]; - wg.inner[2] = _e31; + metal::float4x4 _e10 = global_mat; + metal::float4 _e11 = global_vec; + wg.inner[6] = (_e10 * _e11).x; + float _e19 = dummy[1].y; + wg.inner[5] = _e19; + float _e25 = float_vecs.inner[0].w; + wg.inner[4] = _e25; + float _e29 = alignment.v1_; + wg.inner[3] = _e29; + float _e34 = alignment.v3_[0]; + wg.inner[2] = _e34; alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 07e6da2a7..8109c3ebf 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,35 +1,41 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 130 +; Bound: 138 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %94 "main" -OpExecutionMode %94 LocalSize 1 1 1 +OpEntryPoint GLCompute %99 "main" +OpExecutionMode %99 LocalSize 1 1 1 OpDecorate %24 ArrayStride 4 OpMemberDecorate %26 0 Offset 0 OpMemberDecorate %26 1 Offset 12 OpDecorate %28 ArrayStride 8 OpDecorate %30 ArrayStride 16 -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 1 -OpDecorate %39 Block -OpMemberDecorate %39 0 Offset 0 -OpDecorate %41 NonWritable -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 2 -OpDecorate %42 Block -OpMemberDecorate %42 0 Offset 0 -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 3 -OpDecorate %45 Block -OpMemberDecorate %45 0 Offset 0 -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 4 -OpDecorate %48 Block -OpMemberDecorate %48 0 Offset 0 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 1 +OpDecorate %40 Block +OpMemberDecorate %40 0 Offset 0 +OpDecorate %42 NonWritable +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 2 +OpDecorate %43 Block +OpMemberDecorate %43 0 Offset 0 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 3 +OpDecorate %46 Block +OpMemberDecorate %46 0 Offset 0 +OpDecorate %48 DescriptorSet 0 +OpDecorate %48 Binding 4 +OpDecorate %49 Block +OpMemberDecorate %49 0 Offset 0 +OpDecorate %51 DescriptorSet 0 +OpDecorate %51 Binding 5 +OpDecorate %52 Block +OpMemberDecorate %52 0 Offset 0 +OpMemberDecorate %52 0 ColMajor +OpMemberDecorate %52 0 MatrixStride 16 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -59,123 +65,131 @@ OpMemberDecorate %48 0 Offset 0 %28 = OpTypeRuntimeArray %27 %29 = OpTypeVector %10 4 %30 = OpTypeArray %29 %7 -%31 = OpTypeMatrix %25 3 -%32 = OpConstantComposite %25 %15 %15 %15 -%33 = OpConstantComposite %31 %32 %32 %32 -%35 = OpTypePointer Workgroup %24 -%34 = OpVariable %35 Workgroup -%37 = OpTypePointer Workgroup %6 -%36 = OpVariable %37 Workgroup -%39 = OpTypeStruct %26 -%40 = OpTypePointer StorageBuffer %39 -%38 = OpVariable %40 StorageBuffer -%42 = OpTypeStruct %28 -%43 = OpTypePointer StorageBuffer %42 -%41 = OpVariable %43 StorageBuffer -%45 = OpTypeStruct %30 -%46 = OpTypePointer Uniform %45 -%44 = OpVariable %46 Uniform -%48 = OpTypeStruct %29 -%49 = OpTypePointer Uniform %48 -%47 = OpVariable %49 Uniform -%53 = OpTypeFunction %2 %25 -%54 = OpTypePointer StorageBuffer %26 -%55 = OpTypePointer StorageBuffer %28 -%56 = OpTypePointer Uniform %29 -%57 = OpTypePointer Uniform %30 -%60 = OpTypePointer Function %8 -%63 = OpTypeFunction %2 -%64 = OpConstant %6 0 -%67 = OpTypePointer StorageBuffer %25 -%70 = OpTypePointer StorageBuffer %10 -%90 = OpTypePointer Function %10 -%92 = OpTypePointer Function %4 -%101 = OpTypePointer Workgroup %10 -%102 = OpTypePointer Uniform %10 -%105 = OpConstant %6 6 -%107 = OpTypePointer StorageBuffer %27 -%108 = OpConstant %6 1 -%111 = OpConstant %6 5 -%113 = OpConstant %6 3 -%116 = OpConstant %6 4 -%118 = OpTypePointer StorageBuffer %10 -%129 = OpConstant %6 256 -%52 = OpFunction %2 None %53 -%51 = OpFunctionParameter %25 -%50 = OpLabel -OpBranch %58 -%58 = OpLabel +%31 = OpTypeMatrix %29 4 +%32 = OpTypeMatrix %25 3 +%33 = OpConstantComposite %25 %15 %15 %15 +%34 = OpConstantComposite %32 %33 %33 %33 +%36 = OpTypePointer Workgroup %24 +%35 = OpVariable %36 Workgroup +%38 = OpTypePointer Workgroup %6 +%37 = OpVariable %38 Workgroup +%40 = OpTypeStruct %26 +%41 = OpTypePointer StorageBuffer %40 +%39 = OpVariable %41 StorageBuffer +%43 = OpTypeStruct %28 +%44 = OpTypePointer StorageBuffer %43 +%42 = OpVariable %44 StorageBuffer +%46 = OpTypeStruct %30 +%47 = OpTypePointer Uniform %46 +%45 = OpVariable %47 Uniform +%49 = OpTypeStruct %29 +%50 = OpTypePointer Uniform %49 +%48 = OpVariable %50 Uniform +%52 = OpTypeStruct %31 +%53 = OpTypePointer Uniform %52 +%51 = OpVariable %53 Uniform +%57 = OpTypeFunction %2 %25 +%58 = OpTypePointer StorageBuffer %28 +%59 = OpTypePointer Uniform %29 +%60 = OpTypePointer StorageBuffer %26 +%61 = OpTypePointer Uniform %30 +%62 = OpTypePointer Uniform %31 +%65 = OpTypePointer Function %8 +%68 = OpTypeFunction %2 +%69 = OpConstant %6 0 +%72 = OpTypePointer StorageBuffer %25 +%75 = OpTypePointer StorageBuffer %10 +%95 = OpTypePointer Function %10 +%97 = OpTypePointer Function %4 +%107 = OpTypePointer Workgroup %10 +%112 = OpConstant %6 6 +%114 = OpTypePointer StorageBuffer %27 +%115 = OpConstant %6 1 +%118 = OpConstant %6 5 +%120 = OpTypePointer Uniform %10 +%121 = OpConstant %6 3 +%124 = OpConstant %6 4 +%126 = OpTypePointer StorageBuffer %10 +%137 = OpConstant %6 256 +%56 = OpFunction %2 None %57 +%55 = OpFunctionParameter %25 +%54 = OpLabel +OpBranch %63 +%63 = OpLabel OpReturn OpFunctionEnd -%62 = OpFunction %2 None %63 -%61 = OpLabel -%59 = OpVariable %60 Function %11 -%65 = OpAccessChain %54 %38 %64 -OpBranch %66 +%67 = OpFunction %2 None %68 %66 = OpLabel -%68 = OpCompositeConstruct %25 %9 %9 %9 -%69 = OpAccessChain %67 %65 %64 -OpStore %69 %68 -%71 = OpAccessChain %70 %65 %64 %64 -OpStore %71 %9 -%72 = OpAccessChain %70 %65 %64 %64 -OpStore %72 %13 -%73 = OpLoad %8 %59 -%74 = OpAccessChain %70 %65 %64 %73 -OpStore %74 %14 -%75 = OpLoad %26 %65 -%76 = OpCompositeExtract %25 %75 0 -%77 = OpCompositeExtract %25 %75 0 -%78 = OpVectorShuffle %27 %77 %77 2 0 -%79 = OpCompositeExtract %25 %75 0 -%80 = OpFunctionCall %2 %52 %79 -%81 = OpCompositeExtract %25 %75 0 -%82 = OpVectorTimesMatrix %25 %81 %33 -%83 = OpCompositeExtract %25 %75 0 -%84 = OpMatrixTimesVector %25 %33 %83 -%85 = OpCompositeExtract %25 %75 0 -%86 = OpVectorTimesScalar %25 %85 %13 -%87 = OpCompositeExtract %25 %75 0 -%88 = OpVectorTimesScalar %25 %87 %13 +%64 = OpVariable %65 Function %11 +%70 = OpAccessChain %60 %39 %69 +OpBranch %71 +%71 = OpLabel +%73 = OpCompositeConstruct %25 %9 %9 %9 +%74 = OpAccessChain %72 %70 %69 +OpStore %74 %73 +%76 = OpAccessChain %75 %70 %69 %69 +OpStore %76 %9 +%77 = OpAccessChain %75 %70 %69 %69 +OpStore %77 %13 +%78 = OpLoad %8 %64 +%79 = OpAccessChain %75 %70 %69 %78 +OpStore %79 %14 +%80 = OpLoad %26 %70 +%81 = OpCompositeExtract %25 %80 0 +%82 = OpCompositeExtract %25 %80 0 +%83 = OpVectorShuffle %27 %82 %82 2 0 +%84 = OpCompositeExtract %25 %80 0 +%85 = OpFunctionCall %2 %56 %84 +%86 = OpCompositeExtract %25 %80 0 +%87 = OpVectorTimesMatrix %25 %86 %34 +%88 = OpCompositeExtract %25 %80 0 +%89 = OpMatrixTimesVector %25 %34 %88 +%90 = OpCompositeExtract %25 %80 0 +%91 = OpVectorTimesScalar %25 %90 %13 +%92 = OpCompositeExtract %25 %80 0 +%93 = OpVectorTimesScalar %25 %92 %13 OpReturn OpFunctionEnd -%94 = OpFunction %2 None %63 -%93 = OpLabel -%89 = OpVariable %90 Function %9 -%91 = OpVariable %92 Function %23 -%95 = OpAccessChain %54 %38 %64 -%96 = OpAccessChain %55 %41 %64 -%97 = OpAccessChain %57 %44 %64 -%98 = OpAccessChain %56 %47 %64 -OpBranch %99 -%99 = OpLabel -%100 = OpFunctionCall %2 %62 -%103 = OpAccessChain %102 %98 %64 -%104 = OpLoad %10 %103 -%106 = OpAccessChain %101 %34 %105 -OpStore %106 %104 -%109 = OpAccessChain %70 %96 %108 %108 -%110 = OpLoad %10 %109 -%112 = OpAccessChain %101 %34 %111 -OpStore %112 %110 -%114 = OpAccessChain %102 %97 %64 %113 -%115 = OpLoad %10 %114 -%117 = OpAccessChain %101 %34 %116 -OpStore %117 %115 -%119 = OpAccessChain %118 %95 %108 -%120 = OpLoad %10 %119 -%121 = OpAccessChain %101 %34 %113 -OpStore %121 %120 -%122 = OpAccessChain %70 %95 %64 %64 +%99 = OpFunction %2 None %68 +%98 = OpLabel +%94 = OpVariable %95 Function %9 +%96 = OpVariable %97 Function %23 +%100 = OpAccessChain %60 %39 %69 +%101 = OpAccessChain %58 %42 %69 +%102 = OpAccessChain %61 %45 %69 +%103 = OpAccessChain %59 %48 %69 +%104 = OpAccessChain %62 %51 %69 +OpBranch %105 +%105 = OpLabel +%106 = OpFunctionCall %2 %67 +%108 = OpLoad %31 %104 +%109 = OpLoad %29 %103 +%110 = OpMatrixTimesVector %29 %108 %109 +%111 = OpCompositeExtract %10 %110 0 +%113 = OpAccessChain %107 %35 %112 +OpStore %113 %111 +%116 = OpAccessChain %75 %101 %115 %115 +%117 = OpLoad %10 %116 +%119 = OpAccessChain %107 %35 %118 +OpStore %119 %117 +%122 = OpAccessChain %120 %102 %69 %121 %123 = OpLoad %10 %122 -%124 = OpAccessChain %101 %34 %22 -OpStore %124 %123 -%125 = OpAccessChain %118 %95 %108 -OpStore %125 %21 -%126 = OpArrayLength %6 %41 0 -%127 = OpConvertUToF %10 %126 -%128 = OpAccessChain %101 %34 %108 -OpStore %128 %127 -OpAtomicStore %36 %20 %129 %22 +%125 = OpAccessChain %107 %35 %124 +OpStore %125 %123 +%127 = OpAccessChain %126 %100 %115 +%128 = OpLoad %10 %127 +%129 = OpAccessChain %107 %35 %121 +OpStore %129 %128 +%130 = OpAccessChain %75 %100 %69 %69 +%131 = OpLoad %10 %130 +%132 = OpAccessChain %107 %35 %22 +OpStore %132 %131 +%133 = OpAccessChain %126 %100 %115 +OpStore %133 %21 +%134 = OpArrayLength %6 %42 0 +%135 = OpConvertUToF %10 %134 +%136 = OpAccessChain %107 %35 %115 +OpStore %136 %135 +OpAtomicStore %37 %20 %137 %22 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 73b436ddd..0060e40bf 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -15,6 +15,8 @@ var dummy: array>; var float_vecs: array,20>; @group(0) @binding(4) var global_vec: vec4; +@group(0) @binding(5) +var global_mat: mat4x4; fn test_msl_packed_vec3_as_arg(arg: vec3) { return; @@ -26,8 +28,8 @@ fn test_msl_packed_vec3_() { alignment.v3_ = vec3(1.0); alignment.v3_.x = 1.0; alignment.v3_.x = 2.0; - let _e20 = idx; - alignment.v3_[_e20] = 3.0; + let _e21 = idx; + alignment.v3_[_e21] = 3.0; let data = alignment; let unnamed = data.v3_; let unnamed_1 = data.v3_.zx; @@ -44,16 +46,17 @@ fn main() { var at: bool = true; test_msl_packed_vec3_(); - let _e10 = global_vec.x; - wg[6] = _e10; - let _e16 = dummy[1].y; - wg[5] = _e16; - let _e22 = float_vecs[0].w; - wg[4] = _e22; - let _e26 = alignment.v1_; - wg[3] = _e26; - let _e31 = alignment.v3_.x; - wg[2] = _e31; + let _e10 = global_mat; + let _e11 = global_vec; + wg[6] = (_e10 * _e11).x; + let _e19 = dummy[1].y; + wg[5] = _e19; + let _e25 = float_vecs[0].w; + wg[4] = _e25; + let _e29 = alignment.v1_; + wg[3] = _e29; + let _e34 = alignment.v3_.x; + wg[2] = _e34; alignment.v1_ = 4.0; wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); From dd75579d7c61c5e8de5e0ff28e06442ad34605f2 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 14 Apr 2022 22:00:13 +0200 Subject: [PATCH 1674/2212] fix typos --- CHANGELOG.md | 4 ++-- cli/src/main.rs | 4 ++-- src/back/glsl/mod.rs | 2 +- src/back/hlsl/help.rs | 2 +- src/back/hlsl/writer.rs | 4 ++-- src/back/mod.rs | 2 +- src/back/spv/writer.rs | 4 ++-- src/back/wgsl/writer.rs | 4 ++-- src/front/glsl/ast.rs | 14 +++++++------- src/front/glsl/context.rs | 2 +- src/front/glsl/error.rs | 2 +- src/front/glsl/functions.rs | 4 ++-- src/front/glsl/mod.rs | 6 +++--- src/front/glsl/parser/declarations.rs | 4 ++-- src/front/glsl/parser/types.rs | 2 +- src/front/glsl/variables.rs | 5 +++-- src/front/mod.rs | 2 +- src/front/spv/mod.rs | 4 ++-- src/front/wgsl/mod.rs | 4 ++-- src/proc/mod.rs | 2 +- src/valid/analyzer.rs | 2 +- src/valid/interface.rs | 2 +- 22 files changed, 41 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 49d0bcbe3..aef49154e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## v0.9 (TBD) - WGSL: - semicolon after struct declaration are now optional - - commas are used to separate struct members intead of semicolons + - commas are used to separate struct members instead of semicolons - attributes are declared with `@attrib` instead of `[[attrib]]` - `stride` attribute is removed - block comments are supported @@ -57,7 +57,7 @@ - development release for wgpu-0.11 - API: - bit extraction and packing functions - - hyperbolic trigonometry functionss + - hyperbolic trigonometry functions - validation is gated by a cargo feature - `view_index` builtin - separate bounds checking policies for locals/buffers/textures diff --git a/cli/src/main.rs b/cli/src/main.rs index 0f7f4fd6f..c5e40c7a3 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -49,7 +49,7 @@ struct Args { #[argh(option)] profile: Option, - /// the shader model to use if targeting HSLS + /// the shader model to use if targeting HLSL /// /// May be `50`, 51`, or `60` #[argh(option)] @@ -474,7 +474,7 @@ fn run() -> Result<(), Box> { .write( &module, info.as_ref().ok_or(CliError( - "Generating hsls output requires validation to \ + "Generating hlsl output requires validation to \ succeed, and it failed in a previous step", ))?, ) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c4d66afd6..f052b3bec 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -677,7 +677,7 @@ impl<'a, W: Write> Writer<'a, W> { // Add newline at the end of file writeln!(self.out)?; - // Collect all relection info and return it to the user + // Collect all reflection info and return it to the user self.collect_reflection_info() } diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 78e87cbd4..7612457b1 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -5,7 +5,7 @@ Important note about `Expression::ImageQuery`/`Expression::ArrayLength` and hlsl Due to implementation of `GetDimensions` function in hlsl () backend can't work with it as an expression. -Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texure info and query function. +Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texture info and query function. See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions. This allowed to works with `Expression::ImageQuery` as expression and write wrapped function. diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 28b1445bf..4f3c88049 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -900,7 +900,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // The IR supports only float matrix // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-matrix - // Because of the implicit transpose all matrices have in HLSL, we need to tranpose the size as well. + // Because of the implicit transpose all matrices have in HLSL, we need to transpose the size as well. write!( self.out, "{}{}x{}", @@ -1212,7 +1212,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } if let TypeInner::Struct { .. } = *resolved { - // We can safery unwrap here, since we now we working with struct + // We can safely unwrap here, since we now we working with struct let ty = base_ty_res.handle().unwrap(); let struct_name = &self.names[&NameKey::Type(ty)]; let variable_name = self.namer.call(&struct_name.to_lowercase()); diff --git a/src/back/mod.rs b/src/back/mod.rs index 9802e5acf..0c48e6a55 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -124,7 +124,7 @@ impl crate::Expression { /// should be considered for baking. /// /// Note: we have to cache any expressions that depend on the control flow, - /// or otherwise they may be moved into a non-uniform contol flow, accidentally. + /// or otherwise they may be moved into a non-uniform control flow, accidentally. /// See the [module-level documentation][emit] for details. /// /// [emit]: index.html#expression-evaluation-time diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index cc0c47085..77c909014 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -132,7 +132,7 @@ impl Writer { /// If nothing in `capabilities` appears in the available capabilities /// specified in the [`Options`] from which this `Writer` was created, /// return an error. The `what` string is used in the error message to - /// explain what provoked the requirement. (If no available capabilites were + /// explain what provoked the requirement. (If no available capabilities were /// given, assume everything is available.) /// /// The first acceptable capability will be added to this `Writer`'s @@ -523,7 +523,7 @@ impl Writer { gv.access_id = gv.var_id; }; - // work around borrow checking in the presense of `self.xxx()` calls + // work around borrow checking in the presence of `self.xxx()` calls self.global_variables[handle.index()] = gv; } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index ef93192d0..b2284f457 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -198,7 +198,7 @@ impl Writer { Ok(()) } - /// Helper method used to write stuct name + /// Helper method used to write struct name /// /// # Notes /// Adds no trailing or leading whitespace @@ -1675,7 +1675,7 @@ impl Writer { global: &crate::GlobalVariable, handle: Handle, ) -> BackendResult { - // Write group and dinding attributes if present + // Write group and binding attributes if present if let Some(ref binding) = global.binding { self.write_attributes(&[ Attribute::Group(binding.group), diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 81314676e..64d3faea2 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -33,7 +33,7 @@ pub struct ParameterInfo { pub enum FunctionKind { /// The function is user defined Call(Handle), - /// The function is a buitin + /// The function is a builtin Macro(MacroCall), } @@ -53,19 +53,19 @@ pub struct Overload { pub parameters_info: Vec, /// How the function is implemented pub kind: FunctionKind, - /// Wheter this function was already defined or is just a prototype + /// Whether this function was already defined or is just a prototype pub defined: bool, - /// Wheter this overload is the one provided by the language or has + /// Whether this overload is the one provided by the language or has /// been redeclared by the user (builtins only) pub internal: bool, - /// Wheter or not this function returns void (nothing) + /// Whether or not this function returns void (nothing) pub void: bool, } bitflags::bitflags! { /// Tracks the variations of the builtin already generated, this is needed because some /// builtins overloads can't be generated unless explicitly used, since they might cause - /// uneeded capabilities to be requested + /// unneeded capabilities to be requested #[derive(Default)] pub struct BuiltinVariations: u32 { /// Request the standard overloads @@ -180,7 +180,7 @@ pub struct TypeQualifiers<'a> { pub sampling: Option<(Sampling, Span)>, /// Memory qualifiers used in the declaration to set the storage access to be used /// in declarations that support it (storage images and buffers) - pub storage_acess: Option<(StorageAccess, Span)>, + pub storage_access: Option<(StorageAccess, Span)>, pub layout_qualifiers: crate::FastHashMap, (QualifierValue, Span)>, } @@ -214,7 +214,7 @@ impl<'a> TypeQualifiers<'a> { }); } - if let Some((_, meta)) = self.storage_acess { + if let Some((_, meta)) = self.storage_access { errors.push(super::Error { kind: super::ErrorKind::SemanticError( "Memory qualifiers can only be used in storage variables".into(), diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index eeee39386..45d645ec2 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -23,7 +23,7 @@ pub enum ExprPos { /// The expression is in the right hand side of an assignment Rhs, /// The expression is an array being indexed, needed to allow constant - /// arrays to be dinamically indexed + /// arrays to be dynamically indexed AccessBase { /// The index is a constant constant_index: bool, diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index e1418f1e5..c9ea102fa 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -84,7 +84,7 @@ pub enum ErrorKind { /// A reference to a type that wasn't declared was used. #[error("Unknown type: {0}")] UnknownType(String), - /// A reference to a non existant member of a type was made. + /// A reference to a non existent member of a type was made. #[error("Unknown field: {0}")] UnknownField(String), /// An unknown layout qualifier was used. diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 5989a8bbd..1cc225b80 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -772,7 +772,7 @@ impl Parser { }; // Check if the best parameter corresponds to the current selected overload - // to pass to the next comparation, if this isn't true mark it as ambiguous + // to pass to the next comparison, if this isn't true mark it as ambiguous match best_arg { true => match superior { Some(false) => ambiguous = true, @@ -812,7 +812,7 @@ impl Parser { None => { ambiguous = true; // Assign the new overload, this helps ensures that in this case of - // amiguity the parsing won't end immediately and allow for further + // ambiguity the parsing won't end immediately and allow for further // collection of errors. maybe_overload = Some(overload); } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index ee5d68ded..eee12064e 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -73,10 +73,10 @@ impl From for Options { /// stored in the shader [`Module`](Module). #[derive(Debug)] pub struct ShaderMetadata { - /// The GLSL version specified in the shader trought the use of the + /// The GLSL version specified in the shader trough the use of the /// `#version` preprocessor directive. pub version: u16, - /// The GLSL profile specified in the shader trought the use of the + /// The GLSL profile specified in the shader trough the use of the /// `#version` preprocessor directive. pub profile: Profile, /// The shader stage in the pipeline, passed to the [`parse`](Parser::parse) @@ -230,7 +230,7 @@ impl Parser { /// /// # Notes /// - /// Following an unsuccessful parsing the state of the returned infomration + /// Following an unsuccessful parsing the state of the returned information /// is undefined, it might contain only partial information about the /// current shader, the previous shader or both. pub fn metadata(&self) -> &ShaderMetadata { diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 33ae48ce2..bc5a8c4f9 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -323,13 +323,13 @@ impl<'source> ParsingContext<'source> { }), }; } - // Pass the token to the init_declator_list parser + // Pass the token to the init_declarator_list parser _ => Token { value: TokenValue::Identifier(name), meta: token.meta, }, }, - // Pass the token to the init_declator_list parser + // Pass the token to the init_declarator_list parser _ => token, }; diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 0a1c6c2b1..7a7757c9c 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -263,7 +263,7 @@ impl<'source> ParsingContext<'source> { } TokenValue::MemoryQualifier(access) => { let storage_access = qualifiers - .storage_acess + .storage_access .get_or_insert((crate::StorageAccess::all(), Span::default())); if !storage_access.0.contains(!access) { parser.errors.push(Error { diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 0e446a9a7..8375e1674 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -499,7 +499,7 @@ impl Parser { StorageQualifier::AddressSpace(mut space) => { match space { AddressSpace::Storage { ref mut access } => { - if let Some((allowed_access, _)) = qualifiers.storage_acess.take() { + if let Some((allowed_access, _)) = qualifiers.storage_access.take() { *access = allowed_access; } } @@ -514,7 +514,8 @@ impl Parser { mut format, } = class { - if let Some((allowed_access, _)) = qualifiers.storage_acess.take() { + if let Some((allowed_access, _)) = qualifiers.storage_access.take() + { access = allowed_access; } diff --git a/src/front/mod.rs b/src/front/mod.rs index d340dcad4..dde28d7b5 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -105,7 +105,7 @@ impl Typifier { Ok(()) } - /// Invalidates the cached type resolution for `epxr_handle` forcing a recomputation + /// Invalidates the cached type resolution for `expr_handle` forcing a recomputation /// /// If the type of the expression hasn't yet been calculated a /// [`grow`](Self::grow) is performed instead diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 6c270dcbb..3f96cae05 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2849,7 +2849,7 @@ impl> Parser { // we can treat it as an extension of the current `Body`. // // NOTE: it's possible that another branch was already made to this block - // setting the body index in which case it SHOULD NOT be overriden. + // setting the body index in which case it SHOULD NOT be overridden. // For example a switch with falltrough, the OpSwitch will set the body to // the respective case and the case may branch to another case in which case // the body index shouldn't be changed @@ -3015,7 +3015,7 @@ impl> Parser { // others will be empty falltrough so that they all execute the same body // without duplicating code. // - // Since `switch_cases` is an indexmap the order of insertation is preserved + // Since `switch_cases` is an indexmap the order of insertion is preserved // this is needed because spir-v defines falltrough order in the switch // instruction. let mut cases = Vec::with_capacity((inst.wc as usize - 3) / 2); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 511f6b66f..59c019063 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -4337,7 +4337,7 @@ impl Parser { crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty, }; if !type_match { - let exptected_inner_str = match con.inner { + let expected_inner_str = match con.inner { crate::ConstantInner::Scalar { width, value } => { crate::TypeInner::Scalar { kind: value.scalar_kind(), @@ -4351,7 +4351,7 @@ impl Parser { }; return Err(Error::InitializationTypeMismatch( name_span, - exptected_inner_str, + expected_inner_str, )); } } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index f18bcd961..65fb06fd2 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -135,7 +135,7 @@ impl super::TypeInner { self.try_size(constants).unwrap() } - /// Return the canoncal form of `self`, or `None` if it's already in + /// Return the canonical form of `self`, or `None` if it's already in /// canonical form. /// /// Certain types have multiple representations in `TypeInner`. This diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 28a0f8a8a..d9c27d451 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -219,7 +219,7 @@ pub struct FunctionInfo { /// How this function and its callees use this module's globals. /// /// This is indexed by `Handle` indices. However, - /// `FunctionInfo` implements `std::ops::Index>`, + /// `FunctionInfo` implements `std::ops::Index>`, /// so you can simply index this struct with a global handle to retrieve /// its usage information. global_uses: Box<[GlobalUse]>, diff --git a/src/valid/interface.rs b/src/valid/interface.rs index edaf7cca8..d1bfe009e 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -79,7 +79,7 @@ pub enum EntryPointError { Argument(u32, #[source] VaryingError), #[error(transparent)] Result(#[from] VaryingError), - #[error("Location {location} onterpolation of an integer has to be flat")] + #[error("Location {location} interpolation of an integer has to be flat")] InvalidIntegerInterpolation { location: u32 }, #[error(transparent)] Function(#[from] FunctionError), From ba58ef5176c576527a26719d02bd8ce4b42d1bd2 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 14 Apr 2022 10:15:29 -0700 Subject: [PATCH 1675/2212] Document Naga's promises around validation and panics. --- src/valid/mod.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index bc1a8dc6e..89314294f 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -33,6 +33,21 @@ pub use r#type::{Disalignment, TypeError, TypeFlags}; bitflags::bitflags! { /// Validation flags. + /// + /// If you are working with trusted shaders, then you may be able + /// to save some time by skipping validation. + /// + /// If you do not perform full validation, invalid shaders may + /// cause Naga to panic. If you do perform full validation and + /// [`Validator::validate`] returns `Ok`, then Naga promises that + /// code generation will either succeed or return an error; it + /// should never panic. + /// + /// The default value for `ValidationFlags` is + /// `ValidationFlags::all()`. If Naga's `"validate"` feature is + /// enabled, this requests full validation; otherwise, this + /// requests no validation. (The `"validate"` feature is disabled + /// by default.) #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ValidationFlags: u8 { From 6427a661f713c3b4518d753c4f582bafc5dd4c0b Mon Sep 17 00:00:00 2001 From: Jakob Hellermann Date: Fri, 15 Apr 2022 11:13:39 +0200 Subject: [PATCH 1676/2212] add methods on the error types for reusability in wgsl-analyzer (#1827) --- src/front/wgsl/mod.rs | 10 ++++++++++ src/span.rs | 6 +++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 59c019063..854c3f51c 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1287,6 +1287,16 @@ pub struct ParseError { } impl ParseError { + pub fn labels(&self) -> impl Iterator + ExactSizeIterator + '_ { + self.labels + .iter() + .map(|&(ref span, ref msg)| (span.clone(), msg.as_ref())) + } + + pub fn message(&self) -> &str { + &self.message + } + fn diagnostic(&self) -> Diagnostic<()> { let diagnostic = Diagnostic::error() .with_message(self.message.to_string()) diff --git a/src/span.rs b/src/span.rs index f9fb11113..000d09c32 100644 --- a/src/span.rs +++ b/src/span.rs @@ -124,8 +124,12 @@ impl WithSpan { self.inner } + pub fn as_inner(&self) -> &E { + &self.inner + } + /// Iterator over stored [`SpanContext`]s. - pub fn spans(&self) -> impl Iterator { + pub fn spans(&self) -> impl Iterator + ExactSizeIterator { #[cfg(feature = "span")] return self.spans.iter(); #[cfg(not(feature = "span"))] From e4c017cb7c473dda09bac26b6332cd99681dfd87 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 15:50:10 +0200 Subject: [PATCH 1677/2212] add more tests for operators --- src/valid/expression.rs | 1 - tests/in/operators.wgsl | 218 +++++-- tests/out/glsl/operators.main.Compute.glsl | 171 +++++- tests/out/hlsl/operators.hlsl | 177 ++++-- tests/out/msl/operators.msl | 181 ++++-- tests/out/spv/operators.spvasm | 679 ++++++++++++++------- tests/out/wgsl/operators.wgsl | 171 +++++- 7 files changed, 1193 insertions(+), 405 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 7fb64ab98..bde272dfe 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -670,7 +670,6 @@ impl super::Validator { Some(Sk::Uint) | Some(Sk::Sint) | Some(Sk::Float) => true, Some(Sk::Bool) | None => false, }; - //TODO: should we be more restrictive here? I.e. expect scalar only to the left. let types_match = match (left_inner, right_inner) { (&Ti::Scalar { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) | (&Ti::Vector { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 5ad2a2a2b..8522e830c 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -28,11 +28,6 @@ fn splat() -> vec4 { return a.xyxy + vec4(b); } -fn unary() -> i32 { - let a = 1; - if !true { return a; } else { return ~a; }; -} - fn bool_cast(x: vec3) -> vec3 { let y = vec3(x); return vec3(y); @@ -76,52 +71,203 @@ fn constructors() -> f32 { return foo.a.x; } -fn modulo() { - // Modulo operator on float scalar or vector must be converted to mod function for GLSL - let a = 1 % 1; - let b = 1.0 % 1.0; - let c = vec3(1) % vec3(1); - let d = vec3(1.0) % vec3(1.0); -} - -fn scalar_times_matrix() { - let model = mat4x4( - vec4(1.0, 0.0, 0.0, 0.0), - vec4(0.0, 1.0, 0.0, 0.0), - vec4(0.0, 0.0, 1.0, 0.0), - vec4(0.0, 0.0, 0.0, 1.0), - ); - - let assertion: mat4x4 = 2.0 * model; -} - fn logical() { - let a = true | false; - let b = true & false; + // unary + let _ = !true; + // let _ = !vec2(true); + + // binary + let _ = true || false; + let _ = true && false; + let _ = true | false; + let _ = vec3(true) | vec3(false); + let _ = true & false; + let _ = vec4(true) & vec4(false); } -fn binary_assignment() { +fn arithmetic() { + // unary + let _ = -1; + let _ = -1.0; + let _ = -vec2(1); + let _ = -vec2(1.0); + + // binary + // Addition + let _ = 2 + 1; + let _ = 2u + 1u; + let _ = 2.0 + 1.0; + let _ = vec2(2) + vec2(1); + let _ = vec3(2u) + vec3(1u); + let _ = vec4(2.0) + vec4(1.0); + + // Subtraction + let _ = 2 - 1; + let _ = 2u - 1u; + let _ = 2.0 - 1.0; + let _ = vec2(2) - vec2(1); + let _ = vec3(2u) - vec3(1u); + let _ = vec4(2.0) - vec4(1.0); + + // Multiplication + let _ = 2 * 1; + let _ = 2u * 1u; + let _ = 2.0 * 1.0; + let _ = vec2(2) * vec2(1); + let _ = vec3(2u) * vec3(1u); + let _ = vec4(2.0) * vec4(1.0); + + // Division + let _ = 2 / 1; + let _ = 2u / 1u; + let _ = 2.0 / 1.0; + let _ = vec2(2) / vec2(1); + let _ = vec3(2u) / vec3(1u); + let _ = vec4(2.0) / vec4(1.0); + + // Remainder + let _ = 2 % 1; + let _ = 2u % 1u; + let _ = 2.0 % 1.0; + let _ = vec2(2) % vec2(1); + let _ = vec3(2u) % vec3(1u); + let _ = vec4(2.0) % vec4(1.0); + + // Binary arithmetic expressions with mixed scalar and vector operands + let _ = vec2(2) + 1; + let _ = 2 + vec2(1); + + let _ = vec2(2) - 1; + let _ = 2 - vec2(1); + + let _ = vec2(2) * 1; + let _ = 2 * vec2(1); + + let _ = vec2(2) / 1; + let _ = 2 / vec2(1); + + let _ = vec2(2) % 1; + let _ = 2 % vec2(1); + + // Matrix arithmetic + // let _ = mat3x3() + mat3x3(); + // let _ = mat3x3() - mat3x3(); + + let _ = mat3x3() * 1.0; + let _ = 2.0 * mat3x3(); + + let _ = mat4x3() * vec4(1.0); + let _ = vec3(2.0) * mat4x3(); + + let _ = mat4x3() * mat3x4(); +} + +fn bit() { + // unary + let _ = ~1; + let _ = ~1u; + // let _ = ~vec2(1); + // let _ = ~vec3(1u); + + // binary + let _ = 2 | 1; + let _ = 2u | 1u; + let _ = vec2(2) | vec2(1); + let _ = vec3(2u) | vec3(1u); + + let _ = 2 & 1; + let _ = 2u & 1u; + let _ = vec2(2) & vec2(1); + let _ = vec3(2u) & vec3(1u); + + let _ = 2 ^ 1; + let _ = 2u ^ 1u; + let _ = vec2(2) ^ vec2(1); + let _ = vec3(2u) ^ vec3(1u); + + let _ = 2 << 1u; + let _ = 2u << 1u; + let _ = vec2(2) << vec2(1u); + let _ = vec3(2u) << vec3(1u); + + let _ = 2 >> 1u; + let _ = 2u >> 1u; + let _ = vec2(2) >> vec2(1u); + let _ = vec3(2u) >> vec3(1u); +} + +fn comparison() { + let _ = 2 == 1; + let _ = 2u == 1u; + let _ = 2.0 == 1.0; + let _ = vec2(2) == vec2(1); + let _ = vec3(2u) == vec3(1u); + let _ = vec4(2.0) == vec4(1.0); + + let _ = 2 != 1; + let _ = 2u != 1u; + let _ = 2.0 != 1.0; + let _ = vec2(2) != vec2(1); + let _ = vec3(2u) != vec3(1u); + let _ = vec4(2.0) != vec4(1.0); + + let _ = 2 < 1; + let _ = 2u < 1u; + let _ = 2.0 < 1.0; + let _ = vec2(2) < vec2(1); + let _ = vec3(2u) < vec3(1u); + let _ = vec4(2.0) < vec4(1.0); + + let _ = 2 <= 1; + let _ = 2u <= 1u; + let _ = 2.0 <= 1.0; + let _ = vec2(2) <= vec2(1); + let _ = vec3(2u) <= vec3(1u); + let _ = vec4(2.0) <= vec4(1.0); + + let _ = 2 > 1; + let _ = 2u > 1u; + let _ = 2.0 > 1.0; + let _ = vec2(2) > vec2(1); + let _ = vec3(2u) > vec3(1u); + let _ = vec4(2.0) > vec4(1.0); + + let _ = 2 >= 1; + let _ = 2u >= 1u; + let _ = 2.0 >= 1.0; + let _ = vec2(2) >= vec2(1); + let _ = vec3(2u) >= vec3(1u); + let _ = vec4(2.0) >= vec4(1.0); +} + +fn assignment() { var a = 1; + a += 1; a -= 1; a *= a; a /= a; a %= 1; - a ^= 0; a &= 0; + a |= 0; + a ^= 0; + a <<= 2u; + a >>= 1u; + a++; a--; } @stage(compute) @workgroup_size(1) fn main() { - let a = builtins(); - let b = splat(); - let c = unary(); - let d = bool_cast(v_f32_one.xyz); - let e = constructors(); - modulo(); - scalar_times_matrix(); + let _ = builtins(); + let _ = splat(); + let _ = bool_cast(v_f32_one.xyz); + let _ = constructors(); + logical(); - binary_assignment(); + arithmetic(); + bit(); + comparison(); + assignment(); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 76486c837..1f8bdcc9b 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -28,14 +28,6 @@ vec4 splat() { return (a_1.xyxy + vec4(b)); } -int unary() { - if ((! true)) { - return 1; - } else { - return (~ 1); - } -} - vec3 bool_cast(vec3 x) { bvec3 y = bvec3(x); return vec3(y); @@ -64,24 +56,131 @@ float constructors() { return _e70; } -void modulo() { - int a_2 = (1 % 1); - float b_1 = (1.0 - 1.0 * trunc(1.0 / 1.0)); - ivec3 c = (ivec3(1) % ivec3(1)); - vec3 d = (vec3(1.0) - vec3(1.0) * trunc(vec3(1.0) / vec3(1.0))); -} - -void scalar_times_matrix() { - mat4x4 model = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - mat4x4 assertion = (2.0 * model); -} - void logical() { - bool a_3 = (true || false); - bool b_2 = (true && false); + bool unnamed_11 = (! true); + bool unnamed_12 = (true || false); + bool unnamed_13 = (true && false); + bool unnamed_14 = (true || false); + bvec3 unnamed_15 = (bvec3(true) | bvec3(false)); + bool unnamed_16 = (true && false); + bvec4 unnamed_17 = (bvec4(true) & bvec4(false)); } -void binary_assignment() { +void arithmetic() { + ivec2 unnamed_18 = (- ivec2(1)); + vec2 unnamed_19 = (- vec2(1.0)); + int unnamed_20 = (2 + 1); + uint unnamed_21 = (2u + 1u); + float unnamed_22 = (2.0 + 1.0); + ivec2 unnamed_23 = (ivec2(2) + ivec2(1)); + uvec3 unnamed_24 = (uvec3(2u) + uvec3(1u)); + vec4 unnamed_25 = (vec4(2.0) + vec4(1.0)); + int unnamed_26 = (2 - 1); + uint unnamed_27 = (2u - 1u); + float unnamed_28 = (2.0 - 1.0); + ivec2 unnamed_29 = (ivec2(2) - ivec2(1)); + uvec3 unnamed_30 = (uvec3(2u) - uvec3(1u)); + vec4 unnamed_31 = (vec4(2.0) - vec4(1.0)); + int unnamed_32 = (2 * 1); + uint unnamed_33 = (2u * 1u); + float unnamed_34 = (2.0 * 1.0); + ivec2 unnamed_35 = (ivec2(2) * ivec2(1)); + uvec3 unnamed_36 = (uvec3(2u) * uvec3(1u)); + vec4 unnamed_37 = (vec4(2.0) * vec4(1.0)); + int unnamed_38 = (2 / 1); + uint unnamed_39 = (2u / 1u); + float unnamed_40 = (2.0 / 1.0); + ivec2 unnamed_41 = (ivec2(2) / ivec2(1)); + uvec3 unnamed_42 = (uvec3(2u) / uvec3(1u)); + vec4 unnamed_43 = (vec4(2.0) / vec4(1.0)); + int unnamed_44 = (2 % 1); + uint unnamed_45 = (2u % 1u); + float unnamed_46 = (2.0 - 1.0 * trunc(2.0 / 1.0)); + ivec2 unnamed_47 = (ivec2(2) % ivec2(1)); + uvec3 unnamed_48 = (uvec3(2u) % uvec3(1u)); + vec4 unnamed_49 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); + ivec2 unnamed_50 = (ivec2(2) + ivec2(1)); + ivec2 unnamed_51 = (ivec2(2) + ivec2(1)); + ivec2 unnamed_52 = (ivec2(2) - ivec2(1)); + ivec2 unnamed_53 = (ivec2(2) - ivec2(1)); + ivec2 unnamed_54 = (ivec2(2) * 1); + ivec2 unnamed_55 = (2 * ivec2(1)); + ivec2 unnamed_56 = (ivec2(2) / ivec2(1)); + ivec2 unnamed_57 = (ivec2(2) / ivec2(1)); + ivec2 unnamed_58 = (ivec2(2) % ivec2(1)); + ivec2 unnamed_59 = (ivec2(2) % ivec2(1)); + mat3x3 unnamed_60 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + mat3x3 unnamed_61 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + vec3 unnamed_62 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + vec4 unnamed_63 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_64 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); +} + +void bit() { + int unnamed_65 = (~ 1); + uint unnamed_66 = (~ 1u); + int unnamed_67 = (2 | 1); + uint unnamed_68 = (2u | 1u); + ivec2 unnamed_69 = (ivec2(2) | ivec2(1)); + uvec3 unnamed_70 = (uvec3(2u) | uvec3(1u)); + int unnamed_71 = (2 & 1); + uint unnamed_72 = (2u & 1u); + ivec2 unnamed_73 = (ivec2(2) & ivec2(1)); + uvec3 unnamed_74 = (uvec3(2u) & uvec3(1u)); + int unnamed_75 = (2 ^ 1); + uint unnamed_76 = (2u ^ 1u); + ivec2 unnamed_77 = (ivec2(2) ^ ivec2(1)); + uvec3 unnamed_78 = (uvec3(2u) ^ uvec3(1u)); + int unnamed_79 = (2 << 1u); + uint unnamed_80 = (2u << 1u); + ivec2 unnamed_81 = (ivec2(2) << uvec2(1u)); + uvec3 unnamed_82 = (uvec3(2u) << uvec3(1u)); + int unnamed_83 = (2 >> 1u); + uint unnamed_84 = (2u >> 1u); + ivec2 unnamed_85 = (ivec2(2) >> uvec2(1u)); + uvec3 unnamed_86 = (uvec3(2u) >> uvec3(1u)); +} + +void comparison() { + bool unnamed_87 = (2 == 1); + bool unnamed_88 = (2u == 1u); + bool unnamed_89 = (2.0 == 1.0); + bvec2 unnamed_90 = equal(ivec2(2), ivec2(1)); + bvec3 unnamed_91 = equal(uvec3(2u), uvec3(1u)); + bvec4 unnamed_92 = equal(vec4(2.0), vec4(1.0)); + bool unnamed_93 = (2 != 1); + bool unnamed_94 = (2u != 1u); + bool unnamed_95 = (2.0 != 1.0); + bvec2 unnamed_96 = notEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_97 = notEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_98 = notEqual(vec4(2.0), vec4(1.0)); + bool unnamed_99 = (2 < 1); + bool unnamed_100 = (2u < 1u); + bool unnamed_101 = (2.0 < 1.0); + bvec2 unnamed_102 = lessThan(ivec2(2), ivec2(1)); + bvec3 unnamed_103 = lessThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_104 = lessThan(vec4(2.0), vec4(1.0)); + bool unnamed_105 = (2 <= 1); + bool unnamed_106 = (2u <= 1u); + bool unnamed_107 = (2.0 <= 1.0); + bvec2 unnamed_108 = lessThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_109 = lessThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_110 = lessThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_111 = (2 > 1); + bool unnamed_112 = (2u > 1u); + bool unnamed_113 = (2.0 > 1.0); + bvec2 unnamed_114 = greaterThan(ivec2(2), ivec2(1)); + bvec3 unnamed_115 = greaterThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_116 = greaterThan(vec4(2.0), vec4(1.0)); + bool unnamed_117 = (2 >= 1); + bool unnamed_118 = (2u >= 1u); + bool unnamed_119 = (2.0 >= 1.0); + bvec2 unnamed_120 = greaterThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_121 = greaterThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_122 = greaterThanEqual(vec4(2.0), vec4(1.0)); +} + +void assignment() { int a = 1; int _e6 = a; a = (_e6 + 1); @@ -96,26 +195,32 @@ void binary_assignment() { int _e18 = a; a = (_e18 % 1); int _e21 = a; - a = (_e21 ^ 0); + a = (_e21 & 0); int _e24 = a; - a = (_e24 & 0); + a = (_e24 | 0); int _e27 = a; - a = (_e27 + 1); + a = (_e27 ^ 0); int _e30 = a; - a = (_e30 - 1); + a = (_e30 << 2u); + int _e33 = a; + a = (_e33 >> 1u); + int _e36 = a; + a = (_e36 + 1); + int _e39 = a; + a = (_e39 - 1); return; } void main() { vec4 _e4 = builtins(); vec4 _e5 = splat(); - int _e6 = unary(); - vec3 _e8 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); - float _e9 = constructors(); - modulo(); - scalar_times_matrix(); + vec3 _e7 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + float _e8 = constructors(); logical(); - binary_assignment(); + arithmetic(); + bit(); + comparison(); + assignment(); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 984d519f9..ec4af04b9 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -43,15 +43,6 @@ float4 splat() return (a_1.xyxy + float4(b)); } -int unary() -{ - if (!true) { - return 1; - } else { - return ~1; - } -} - float3 bool_cast(float3 x) { bool3 y = bool3(x); @@ -91,27 +82,135 @@ float constructors() return _expr70; } -void modulo() -{ - int a_2 = (1 % 1); - float b_1 = (1.0 % 1.0); - int3 c = (int3(1.xxx) % int3(1.xxx)); - float3 d = (float3(1.0.xxx) % float3(1.0.xxx)); -} - -void scalar_times_matrix() -{ - float4x4 model = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); - float4x4 assertion = mul(model, 2.0); -} - void logical() { - bool a_3 = (true | false); - bool b_2 = (true & false); + bool unnamed_11 = !true; + bool unnamed_12 = (true || false); + bool unnamed_13 = (true && false); + bool unnamed_14 = (true | false); + bool3 unnamed_15 = (bool3(true.xxx) | bool3(false.xxx)); + bool unnamed_16 = (true & false); + bool4 unnamed_17 = (bool4(true.xxxx) & bool4(false.xxxx)); } -void binary_assignment() +void arithmetic() +{ + int2 unnamed_18 = -int2(1.xx); + float2 unnamed_19 = -float2(1.0.xx); + int unnamed_20 = (2 + 1); + uint unnamed_21 = (2u + 1u); + float unnamed_22 = (2.0 + 1.0); + int2 unnamed_23 = (int2(2.xx) + int2(1.xx)); + uint3 unnamed_24 = (uint3(2u.xxx) + uint3(1u.xxx)); + float4 unnamed_25 = (float4(2.0.xxxx) + float4(1.0.xxxx)); + int unnamed_26 = (2 - 1); + uint unnamed_27 = (2u - 1u); + float unnamed_28 = (2.0 - 1.0); + int2 unnamed_29 = (int2(2.xx) - int2(1.xx)); + uint3 unnamed_30 = (uint3(2u.xxx) - uint3(1u.xxx)); + float4 unnamed_31 = (float4(2.0.xxxx) - float4(1.0.xxxx)); + int unnamed_32 = (2 * 1); + uint unnamed_33 = (2u * 1u); + float unnamed_34 = (2.0 * 1.0); + int2 unnamed_35 = (int2(2.xx) * int2(1.xx)); + uint3 unnamed_36 = (uint3(2u.xxx) * uint3(1u.xxx)); + float4 unnamed_37 = (float4(2.0.xxxx) * float4(1.0.xxxx)); + int unnamed_38 = (2 / 1); + uint unnamed_39 = (2u / 1u); + float unnamed_40 = (2.0 / 1.0); + int2 unnamed_41 = (int2(2.xx) / int2(1.xx)); + uint3 unnamed_42 = (uint3(2u.xxx) / uint3(1u.xxx)); + float4 unnamed_43 = (float4(2.0.xxxx) / float4(1.0.xxxx)); + int unnamed_44 = (2 % 1); + uint unnamed_45 = (2u % 1u); + float unnamed_46 = (2.0 % 1.0); + int2 unnamed_47 = (int2(2.xx) % int2(1.xx)); + uint3 unnamed_48 = (uint3(2u.xxx) % uint3(1u.xxx)); + float4 unnamed_49 = (float4(2.0.xxxx) % float4(1.0.xxxx)); + int2 unnamed_50 = (int2(2.xx) + int2(1.xx)); + int2 unnamed_51 = (int2(2.xx) + int2(1.xx)); + int2 unnamed_52 = (int2(2.xx) - int2(1.xx)); + int2 unnamed_53 = (int2(2.xx) - int2(1.xx)); + int2 unnamed_54 = (int2(2.xx) * 1); + int2 unnamed_55 = (2 * int2(1.xx)); + int2 unnamed_56 = (int2(2.xx) / int2(1.xx)); + int2 unnamed_57 = (int2(2.xx) / int2(1.xx)); + int2 unnamed_58 = (int2(2.xx) % int2(1.xx)); + int2 unnamed_59 = (int2(2.xx) % int2(1.xx)); + float3x3 unnamed_60 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_61 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); + float3 unnamed_62 = mul(float4(1.0.xxxx), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float4 unnamed_63 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), float3(2.0.xxx)); + float3x3 unnamed_64 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); +} + +void bit() +{ + int unnamed_65 = ~1; + uint unnamed_66 = ~1u; + int unnamed_67 = (2 | 1); + uint unnamed_68 = (2u | 1u); + int2 unnamed_69 = (int2(2.xx) | int2(1.xx)); + uint3 unnamed_70 = (uint3(2u.xxx) | uint3(1u.xxx)); + int unnamed_71 = (2 & 1); + uint unnamed_72 = (2u & 1u); + int2 unnamed_73 = (int2(2.xx) & int2(1.xx)); + uint3 unnamed_74 = (uint3(2u.xxx) & uint3(1u.xxx)); + int unnamed_75 = (2 ^ 1); + uint unnamed_76 = (2u ^ 1u); + int2 unnamed_77 = (int2(2.xx) ^ int2(1.xx)); + uint3 unnamed_78 = (uint3(2u.xxx) ^ uint3(1u.xxx)); + int unnamed_79 = (2 << 1u); + uint unnamed_80 = (2u << 1u); + int2 unnamed_81 = (int2(2.xx) << uint2(1u.xx)); + uint3 unnamed_82 = (uint3(2u.xxx) << uint3(1u.xxx)); + int unnamed_83 = (2 >> 1u); + uint unnamed_84 = (2u >> 1u); + int2 unnamed_85 = (int2(2.xx) >> uint2(1u.xx)); + uint3 unnamed_86 = (uint3(2u.xxx) >> uint3(1u.xxx)); +} + +void comparison() +{ + bool unnamed_87 = (2 == 1); + bool unnamed_88 = (2u == 1u); + bool unnamed_89 = (2.0 == 1.0); + bool2 unnamed_90 = (int2(2.xx) == int2(1.xx)); + bool3 unnamed_91 = (uint3(2u.xxx) == uint3(1u.xxx)); + bool4 unnamed_92 = (float4(2.0.xxxx) == float4(1.0.xxxx)); + bool unnamed_93 = (2 != 1); + bool unnamed_94 = (2u != 1u); + bool unnamed_95 = (2.0 != 1.0); + bool2 unnamed_96 = (int2(2.xx) != int2(1.xx)); + bool3 unnamed_97 = (uint3(2u.xxx) != uint3(1u.xxx)); + bool4 unnamed_98 = (float4(2.0.xxxx) != float4(1.0.xxxx)); + bool unnamed_99 = (2 < 1); + bool unnamed_100 = (2u < 1u); + bool unnamed_101 = (2.0 < 1.0); + bool2 unnamed_102 = (int2(2.xx) < int2(1.xx)); + bool3 unnamed_103 = (uint3(2u.xxx) < uint3(1u.xxx)); + bool4 unnamed_104 = (float4(2.0.xxxx) < float4(1.0.xxxx)); + bool unnamed_105 = (2 <= 1); + bool unnamed_106 = (2u <= 1u); + bool unnamed_107 = (2.0 <= 1.0); + bool2 unnamed_108 = (int2(2.xx) <= int2(1.xx)); + bool3 unnamed_109 = (uint3(2u.xxx) <= uint3(1u.xxx)); + bool4 unnamed_110 = (float4(2.0.xxxx) <= float4(1.0.xxxx)); + bool unnamed_111 = (2 > 1); + bool unnamed_112 = (2u > 1u); + bool unnamed_113 = (2.0 > 1.0); + bool2 unnamed_114 = (int2(2.xx) > int2(1.xx)); + bool3 unnamed_115 = (uint3(2u.xxx) > uint3(1u.xxx)); + bool4 unnamed_116 = (float4(2.0.xxxx) > float4(1.0.xxxx)); + bool unnamed_117 = (2 >= 1); + bool unnamed_118 = (2u >= 1u); + bool unnamed_119 = (2.0 >= 1.0); + bool2 unnamed_120 = (int2(2.xx) >= int2(1.xx)); + bool3 unnamed_121 = (uint3(2u.xxx) >= uint3(1u.xxx)); + bool4 unnamed_122 = (float4(2.0.xxxx) >= float4(1.0.xxxx)); +} + +void assignment() { int a = 1; @@ -128,13 +227,19 @@ void binary_assignment() int _expr18 = a; a = (_expr18 % 1); int _expr21 = a; - a = (_expr21 ^ 0); + a = (_expr21 & 0); int _expr24 = a; - a = (_expr24 & 0); + a = (_expr24 | 0); int _expr27 = a; - a = (_expr27 + 1); + a = (_expr27 ^ 0); int _expr30 = a; - a = (_expr30 - 1); + a = (_expr30 << 2u); + int _expr33 = a; + a = (_expr33 >> 1u); + int _expr36 = a; + a = (_expr36 + 1); + int _expr39 = a; + a = (_expr39 - 1); return; } @@ -143,12 +248,12 @@ void main() { const float4 _e4 = builtins(); const float4 _e5 = splat(); - const int _e6 = unary(); - const float3 _e8 = bool_cast(float4(1.0, 1.0, 1.0, 1.0).xyz); - const float _e9 = constructors(); - modulo(); - scalar_times_matrix(); + const float3 _e7 = bool_cast(float4(1.0, 1.0, 1.0, 1.0).xyz); + const float _e8 = constructors(); logical(); - binary_assignment(); + arithmetic(); + bit(); + comparison(); + assignment(); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 65a5f61c4..e71b196d9 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -24,6 +24,10 @@ constant metal::float2x2 const_type_7_ = {const_type_6_, const_type_6_}; constant metal::float4 const_type = {0.0, 0.0, 0.0, 0.0}; constant Foo const_Foo = {const_type, 0}; constant type_12 const_type_12_ = {const_Foo, const_Foo, const_Foo}; +constant metal::float3 const_type_4_ = {0.0, 0.0, 0.0}; +constant metal::float3x3 const_type_14_ = {const_type_4_, const_type_4_, const_type_4_}; +constant metal::float4x3 const_type_15_ = {const_type_4_, const_type_4_, const_type_4_, const_type_4_}; +constant metal::float3x4 const_type_16_ = {const_type, const_type, const_type}; metal::float4 builtins( ) { @@ -45,15 +49,6 @@ metal::float4 splat( return a_1.xyxy + static_cast(b); } -int unary( -) { - if (!true) { - return 1; - } else { - return ~1; - } -} - metal::float3 bool_cast( metal::float3 x ) { @@ -85,27 +80,135 @@ float constructors( return _e70; } -void modulo( -) { - int a_2 = 1 % 1; - float b_1 = metal::fmod(1.0, 1.0); - metal::int3 c = metal::int3(1) % metal::int3(1); - metal::float3 d = metal::fmod(metal::float3(1.0), metal::float3(1.0)); -} - -void scalar_times_matrix( -) { - metal::float4x4 model = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); - metal::float4x4 assertion = 2.0 * model; -} - void logical( ) { - bool a_3 = true | false; - bool b_2 = true & false; + bool unnamed_11 = !true; + bool unnamed_12 = true || false; + bool unnamed_13 = true && false; + bool unnamed_14 = true | false; + metal::bool3 unnamed_15 = metal::bool3(true) | metal::bool3(false); + bool unnamed_16 = true & false; + metal::bool4 unnamed_17 = metal::bool4(true) & metal::bool4(false); } -void binary_assignment( +void arithmetic( +) { + metal::int2 unnamed_18 = -metal::int2(1); + metal::float2 unnamed_19 = -metal::float2(1.0); + int unnamed_20 = 2 + 1; + uint unnamed_21 = 2u + 1u; + float unnamed_22 = 2.0 + 1.0; + metal::int2 unnamed_23 = metal::int2(2) + metal::int2(1); + metal::uint3 unnamed_24 = metal::uint3(2u) + metal::uint3(1u); + metal::float4 unnamed_25 = metal::float4(2.0) + metal::float4(1.0); + int unnamed_26 = 2 - 1; + uint unnamed_27 = 2u - 1u; + float unnamed_28 = 2.0 - 1.0; + metal::int2 unnamed_29 = metal::int2(2) - metal::int2(1); + metal::uint3 unnamed_30 = metal::uint3(2u) - metal::uint3(1u); + metal::float4 unnamed_31 = metal::float4(2.0) - metal::float4(1.0); + int unnamed_32 = 2 * 1; + uint unnamed_33 = 2u * 1u; + float unnamed_34 = 2.0 * 1.0; + metal::int2 unnamed_35 = metal::int2(2) * metal::int2(1); + metal::uint3 unnamed_36 = metal::uint3(2u) * metal::uint3(1u); + metal::float4 unnamed_37 = metal::float4(2.0) * metal::float4(1.0); + int unnamed_38 = 2 / 1; + uint unnamed_39 = 2u / 1u; + float unnamed_40 = 2.0 / 1.0; + metal::int2 unnamed_41 = metal::int2(2) / metal::int2(1); + metal::uint3 unnamed_42 = metal::uint3(2u) / metal::uint3(1u); + metal::float4 unnamed_43 = metal::float4(2.0) / metal::float4(1.0); + int unnamed_44 = 2 % 1; + uint unnamed_45 = 2u % 1u; + float unnamed_46 = metal::fmod(2.0, 1.0); + metal::int2 unnamed_47 = metal::int2(2) % metal::int2(1); + metal::uint3 unnamed_48 = metal::uint3(2u) % metal::uint3(1u); + metal::float4 unnamed_49 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); + metal::int2 unnamed_50 = metal::int2(2) + metal::int2(1); + metal::int2 unnamed_51 = metal::int2(2) + metal::int2(1); + metal::int2 unnamed_52 = metal::int2(2) - metal::int2(1); + metal::int2 unnamed_53 = metal::int2(2) - metal::int2(1); + metal::int2 unnamed_54 = metal::int2(2) * 1; + metal::int2 unnamed_55 = 2 * metal::int2(1); + metal::int2 unnamed_56 = metal::int2(2) / metal::int2(1); + metal::int2 unnamed_57 = metal::int2(2) / metal::int2(1); + metal::int2 unnamed_58 = metal::int2(2) % metal::int2(1); + metal::int2 unnamed_59 = metal::int2(2) % metal::int2(1); + metal::float3x3 unnamed_60 = const_type_14_ * 1.0; + metal::float3x3 unnamed_61 = 2.0 * const_type_14_; + metal::float3 unnamed_62 = const_type_15_ * metal::float4(1.0); + metal::float4 unnamed_63 = metal::float3(2.0) * const_type_15_; + metal::float3x3 unnamed_64 = const_type_15_ * const_type_16_; +} + +void bit( +) { + int unnamed_65 = ~1; + uint unnamed_66 = ~1u; + int unnamed_67 = 2 | 1; + uint unnamed_68 = 2u | 1u; + metal::int2 unnamed_69 = metal::int2(2) | metal::int2(1); + metal::uint3 unnamed_70 = metal::uint3(2u) | metal::uint3(1u); + int unnamed_71 = 2 & 1; + uint unnamed_72 = 2u & 1u; + metal::int2 unnamed_73 = metal::int2(2) & metal::int2(1); + metal::uint3 unnamed_74 = metal::uint3(2u) & metal::uint3(1u); + int unnamed_75 = 2 ^ 1; + uint unnamed_76 = 2u ^ 1u; + metal::int2 unnamed_77 = metal::int2(2) ^ metal::int2(1); + metal::uint3 unnamed_78 = metal::uint3(2u) ^ metal::uint3(1u); + int unnamed_79 = 2 << 1u; + uint unnamed_80 = 2u << 1u; + metal::int2 unnamed_81 = metal::int2(2) << metal::uint2(1u); + metal::uint3 unnamed_82 = metal::uint3(2u) << metal::uint3(1u); + int unnamed_83 = 2 >> 1u; + uint unnamed_84 = 2u >> 1u; + metal::int2 unnamed_85 = metal::int2(2) >> metal::uint2(1u); + metal::uint3 unnamed_86 = metal::uint3(2u) >> metal::uint3(1u); +} + +void comparison( +) { + bool unnamed_87 = 2 == 1; + bool unnamed_88 = 2u == 1u; + bool unnamed_89 = 2.0 == 1.0; + metal::bool2 unnamed_90 = metal::int2(2) == metal::int2(1); + metal::bool3 unnamed_91 = metal::uint3(2u) == metal::uint3(1u); + metal::bool4 unnamed_92 = metal::float4(2.0) == metal::float4(1.0); + bool unnamed_93 = 2 != 1; + bool unnamed_94 = 2u != 1u; + bool unnamed_95 = 2.0 != 1.0; + metal::bool2 unnamed_96 = metal::int2(2) != metal::int2(1); + metal::bool3 unnamed_97 = metal::uint3(2u) != metal::uint3(1u); + metal::bool4 unnamed_98 = metal::float4(2.0) != metal::float4(1.0); + bool unnamed_99 = 2 < 1; + bool unnamed_100 = 2u < 1u; + bool unnamed_101 = 2.0 < 1.0; + metal::bool2 unnamed_102 = metal::int2(2) < metal::int2(1); + metal::bool3 unnamed_103 = metal::uint3(2u) < metal::uint3(1u); + metal::bool4 unnamed_104 = metal::float4(2.0) < metal::float4(1.0); + bool unnamed_105 = 2 <= 1; + bool unnamed_106 = 2u <= 1u; + bool unnamed_107 = 2.0 <= 1.0; + metal::bool2 unnamed_108 = metal::int2(2) <= metal::int2(1); + metal::bool3 unnamed_109 = metal::uint3(2u) <= metal::uint3(1u); + metal::bool4 unnamed_110 = metal::float4(2.0) <= metal::float4(1.0); + bool unnamed_111 = 2 > 1; + bool unnamed_112 = 2u > 1u; + bool unnamed_113 = 2.0 > 1.0; + metal::bool2 unnamed_114 = metal::int2(2) > metal::int2(1); + metal::bool3 unnamed_115 = metal::uint3(2u) > metal::uint3(1u); + metal::bool4 unnamed_116 = metal::float4(2.0) > metal::float4(1.0); + bool unnamed_117 = 2 >= 1; + bool unnamed_118 = 2u >= 1u; + bool unnamed_119 = 2.0 >= 1.0; + metal::bool2 unnamed_120 = metal::int2(2) >= metal::int2(1); + metal::bool3 unnamed_121 = metal::uint3(2u) >= metal::uint3(1u); + metal::bool4 unnamed_122 = metal::float4(2.0) >= metal::float4(1.0); +} + +void assignment( ) { int a = 1; int _e6 = a; @@ -121,13 +224,19 @@ void binary_assignment( int _e18 = a; a = _e18 % 1; int _e21 = a; - a = _e21 ^ 0; + a = _e21 & 0; int _e24 = a; - a = _e24 & 0; + a = _e24 | 0; int _e27 = a; - a = _e27 + 1; + a = _e27 ^ 0; int _e30 = a; - a = _e30 - 1; + a = _e30 << 2u; + int _e33 = a; + a = _e33 >> 1u; + int _e36 = a; + a = _e36 + 1; + int _e39 = a; + a = _e39 - 1; return; } @@ -135,12 +244,12 @@ kernel void main_( ) { metal::float4 _e4 = builtins(); metal::float4 _e5 = splat(); - int _e6 = unary(); - metal::float3 _e8 = bool_cast(v_f32_one.xyz); - float _e9 = constructors(); - modulo(); - scalar_times_matrix(); + metal::float3 _e7 = bool_cast(v_f32_one.xyz); + float _e8 = constructors(); logical(); - binary_assignment(); + arithmetic(); + bit(); + comparison(); + assignment(); return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index be03133c9..1c95c2711 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 214 +; Bound: 434 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %202 "main" -OpExecutionMode %202 LocalSize 1 1 1 -OpMemberDecorate %27 0 Offset 0 -OpMemberDecorate %27 1 Offset 16 -OpDecorate %32 ArrayStride 32 -OpDecorate %33 ArrayStride 4 +OpEntryPoint GLCompute %422 "main" +OpExecutionMode %422 LocalSize 1 1 1 +OpMemberDecorate %31 0 Offset 0 +OpMemberDecorate %31 1 Offset 16 +OpDecorate %36 ArrayStride 32 +OpDecorate %37 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -32,241 +32,460 @@ OpDecorate %33 ArrayStride 4 %19 = OpConstant %20 0 %21 = OpConstant %8 3 %22 = OpConstant %20 4 -%23 = OpTypeVector %4 4 -%24 = OpTypeVector %8 4 -%25 = OpTypeVector %10 4 -%26 = OpTypeVector %4 3 -%27 = OpTypeStruct %23 %8 -%28 = OpTypeVector %4 2 -%29 = OpTypeMatrix %28 2 -%30 = OpTypeMatrix %23 4 -%31 = OpTypeVector %20 2 -%32 = OpTypeArray %27 %21 -%33 = OpTypeArray %8 %22 -%34 = OpConstantComposite %23 %3 %3 %3 %3 -%35 = OpConstantComposite %23 %5 %5 %5 %5 -%36 = OpConstantComposite %23 %6 %6 %6 %6 -%37 = OpConstantComposite %24 %7 %7 %7 %7 -%38 = OpConstantComposite %31 %19 %19 -%39 = OpConstantComposite %28 %5 %5 -%40 = OpConstantComposite %29 %39 %39 -%41 = OpConstantComposite %23 %5 %5 %5 %5 -%42 = OpConstantComposite %27 %41 %11 -%43 = OpConstantComposite %32 %42 %42 %42 -%46 = OpTypeFunction %23 -%87 = OpTypeFunction %8 -%94 = OpConstantNull %8 -%98 = OpTypeFunction %26 %26 -%100 = OpTypeVector %10 3 -%107 = OpTypePointer Function %27 -%109 = OpTypePointer Function %10 -%111 = OpTypePointer Function %8 -%113 = OpTypePointer Function %20 -%115 = OpTypePointer Function %4 -%117 = OpTypePointer Function %31 -%119 = OpTypePointer Function %29 -%121 = OpTypePointer Function %32 -%126 = OpTypePointer Function %33 -%129 = OpTypeFunction %4 -%146 = OpTypePointer Function %23 -%147 = OpTypePointer Function %4 -%152 = OpTypeFunction %2 -%156 = OpTypeVector %8 3 -%45 = OpFunction %23 None %46 -%44 = OpLabel -OpBranch %47 -%47 = OpLabel -%48 = OpSelect %8 %9 %7 %11 -%50 = OpCompositeConstruct %25 %9 %9 %9 %9 -%49 = OpSelect %23 %50 %34 %35 -%51 = OpCompositeConstruct %25 %12 %12 %12 %12 -%52 = OpSelect %23 %51 %35 %34 -%53 = OpExtInst %23 %1 FMix %35 %34 %36 -%55 = OpCompositeConstruct %23 %13 %13 %13 %13 -%54 = OpExtInst %23 %1 FMix %35 %34 %55 -%56 = OpCompositeExtract %8 %37 0 -%57 = OpBitcast %4 %56 -%58 = OpBitcast %23 %37 -%59 = OpConvertFToS %24 %35 -%60 = OpCompositeConstruct %24 %48 %48 %48 %48 -%61 = OpIAdd %24 %60 %59 -%62 = OpConvertSToF %23 %61 -%63 = OpFAdd %23 %62 %49 -%64 = OpFAdd %23 %63 %53 -%65 = OpFAdd %23 %64 %54 -%66 = OpCompositeConstruct %23 %57 %57 %57 %57 -%67 = OpFAdd %23 %65 %66 -%68 = OpFAdd %23 %67 %58 -OpReturnValue %68 +%23 = OpConstant %8 4294967295 +%24 = OpConstant %4 -1.0 +%25 = OpConstant %20 2 +%26 = OpConstant %20 1 +%27 = OpTypeVector %4 4 +%28 = OpTypeVector %8 4 +%29 = OpTypeVector %10 4 +%30 = OpTypeVector %4 3 +%31 = OpTypeStruct %27 %8 +%32 = OpTypeVector %4 2 +%33 = OpTypeMatrix %32 2 +%34 = OpTypeMatrix %27 4 +%35 = OpTypeVector %20 2 +%36 = OpTypeArray %31 %21 +%37 = OpTypeArray %8 %22 +%38 = OpTypeMatrix %30 3 +%39 = OpTypeMatrix %30 4 +%40 = OpTypeMatrix %27 3 +%41 = OpConstantComposite %27 %3 %3 %3 %3 +%42 = OpConstantComposite %27 %5 %5 %5 %5 +%43 = OpConstantComposite %27 %6 %6 %6 %6 +%44 = OpConstantComposite %28 %7 %7 %7 %7 +%45 = OpConstantComposite %35 %19 %19 +%46 = OpConstantComposite %32 %5 %5 +%47 = OpConstantComposite %33 %46 %46 +%48 = OpConstantComposite %27 %5 %5 %5 %5 +%49 = OpConstantComposite %31 %48 %11 +%50 = OpConstantComposite %36 %49 %49 %49 +%51 = OpConstantComposite %30 %5 %5 %5 +%52 = OpConstantComposite %38 %51 %51 %51 +%53 = OpConstantComposite %39 %51 %51 %51 %51 +%54 = OpConstantComposite %40 %48 %48 %48 +%57 = OpTypeFunction %27 +%99 = OpTypeFunction %30 %30 +%101 = OpTypeVector %10 3 +%108 = OpTypePointer Function %31 +%110 = OpTypePointer Function %10 +%112 = OpTypePointer Function %8 +%114 = OpTypePointer Function %20 +%116 = OpTypePointer Function %4 +%118 = OpTypePointer Function %35 +%120 = OpTypePointer Function %33 +%122 = OpTypePointer Function %36 +%127 = OpTypePointer Function %37 +%130 = OpTypeFunction %4 +%147 = OpTypePointer Function %27 +%148 = OpTypePointer Function %4 +%153 = OpTypeFunction %2 +%169 = OpTypeVector %8 2 +%180 = OpTypeVector %20 3 +%323 = OpTypeVector %10 2 +%56 = OpFunction %27 None %57 +%55 = OpLabel +OpBranch %58 +%58 = OpLabel +%59 = OpSelect %8 %9 %7 %11 +%61 = OpCompositeConstruct %29 %9 %9 %9 %9 +%60 = OpSelect %27 %61 %41 %42 +%62 = OpCompositeConstruct %29 %12 %12 %12 %12 +%63 = OpSelect %27 %62 %42 %41 +%64 = OpExtInst %27 %1 FMix %42 %41 %43 +%66 = OpCompositeConstruct %27 %13 %13 %13 %13 +%65 = OpExtInst %27 %1 FMix %42 %41 %66 +%67 = OpCompositeExtract %8 %44 0 +%68 = OpBitcast %4 %67 +%69 = OpBitcast %27 %44 +%70 = OpConvertFToS %28 %42 +%71 = OpCompositeConstruct %28 %59 %59 %59 %59 +%72 = OpIAdd %28 %71 %70 +%73 = OpConvertSToF %27 %72 +%74 = OpFAdd %27 %73 %60 +%75 = OpFAdd %27 %74 %64 +%76 = OpFAdd %27 %75 %65 +%77 = OpCompositeConstruct %27 %68 %68 %68 %68 +%78 = OpFAdd %27 %76 %77 +%79 = OpFAdd %27 %78 %69 +OpReturnValue %79 OpFunctionEnd -%70 = OpFunction %23 None %46 -%69 = OpLabel -OpBranch %71 -%71 = OpLabel -%72 = OpCompositeConstruct %28 %14 %14 -%73 = OpCompositeConstruct %28 %3 %3 -%74 = OpFAdd %28 %73 %72 -%75 = OpCompositeConstruct %28 %15 %15 -%76 = OpFSub %28 %74 %75 -%77 = OpCompositeConstruct %28 %16 %16 -%78 = OpFDiv %28 %76 %77 -%79 = OpCompositeConstruct %24 %17 %17 %17 %17 -%80 = OpCompositeConstruct %24 %18 %18 %18 %18 -%81 = OpSMod %24 %79 %80 -%82 = OpVectorShuffle %23 %78 %78 0 1 0 1 -%83 = OpConvertSToF %23 %81 -%84 = OpFAdd %23 %82 %83 -OpReturnValue %84 +%81 = OpFunction %27 None %57 +%80 = OpLabel +OpBranch %82 +%82 = OpLabel +%83 = OpCompositeConstruct %32 %14 %14 +%84 = OpCompositeConstruct %32 %3 %3 +%85 = OpFAdd %32 %84 %83 +%86 = OpCompositeConstruct %32 %15 %15 +%87 = OpFSub %32 %85 %86 +%88 = OpCompositeConstruct %32 %16 %16 +%89 = OpFDiv %32 %87 %88 +%90 = OpCompositeConstruct %28 %17 %17 %17 %17 +%91 = OpCompositeConstruct %28 %18 %18 %18 %18 +%92 = OpSMod %28 %90 %91 +%93 = OpVectorShuffle %27 %89 %89 0 1 0 1 +%94 = OpConvertSToF %27 %92 +%95 = OpFAdd %27 %93 %94 +OpReturnValue %95 OpFunctionEnd -%86 = OpFunction %8 None %87 -%85 = OpLabel -OpBranch %88 -%88 = OpLabel -%89 = OpLogicalNot %10 %9 -OpSelectionMerge %90 None -OpBranchConditional %89 %91 %92 -%91 = OpLabel -OpReturnValue %7 -%92 = OpLabel -%93 = OpNot %8 %7 -OpReturnValue %93 -%90 = OpLabel -OpReturnValue %94 +%98 = OpFunction %30 None %99 +%97 = OpFunctionParameter %30 +%96 = OpLabel +OpBranch %100 +%100 = OpLabel +%102 = OpCompositeConstruct %30 %5 %5 %5 +%103 = OpFUnordNotEqual %101 %97 %102 +%104 = OpCompositeConstruct %30 %5 %5 %5 +%105 = OpCompositeConstruct %30 %3 %3 %3 +%106 = OpSelect %30 %103 %105 %104 +OpReturnValue %106 OpFunctionEnd -%97 = OpFunction %26 None %98 -%96 = OpFunctionParameter %26 -%95 = OpLabel -OpBranch %99 -%99 = OpLabel -%101 = OpCompositeConstruct %26 %5 %5 %5 -%102 = OpFUnordNotEqual %100 %96 %101 -%103 = OpCompositeConstruct %26 %5 %5 %5 -%104 = OpCompositeConstruct %26 %3 %3 %3 -%105 = OpSelect %26 %102 %104 %103 -OpReturnValue %105 -OpFunctionEnd -%128 = OpFunction %4 None %129 -%127 = OpLabel -%123 = OpVariable %117 Function -%118 = OpVariable %119 Function %40 -%112 = OpVariable %113 Function %19 -%106 = OpVariable %107 Function -%124 = OpVariable %119 Function -%120 = OpVariable %121 Function %43 -%114 = OpVariable %115 Function %5 -%108 = OpVariable %109 Function %12 -%125 = OpVariable %126 Function -%122 = OpVariable %107 Function %42 -%116 = OpVariable %117 Function %38 -%110 = OpVariable %111 Function %11 -OpBranch %130 -%130 = OpLabel -%131 = OpCompositeConstruct %23 %3 %3 %3 %3 -%132 = OpCompositeConstruct %27 %131 %7 -OpStore %106 %132 -%133 = OpCompositeConstruct %28 %3 %5 -%134 = OpCompositeConstruct %28 %5 %3 -%135 = OpCompositeConstruct %29 %133 %134 -%136 = OpCompositeConstruct %23 %3 %5 %5 %5 -%137 = OpCompositeConstruct %23 %5 %3 %5 %5 -%138 = OpCompositeConstruct %23 %5 %5 %3 %5 -%139 = OpCompositeConstruct %23 %5 %5 %5 %3 -%140 = OpCompositeConstruct %30 %136 %137 %138 %139 -%141 = OpCompositeConstruct %31 %19 %19 -OpStore %123 %141 -%142 = OpCompositeConstruct %28 %5 %5 -%143 = OpCompositeConstruct %28 %5 %5 -%144 = OpCompositeConstruct %29 %142 %143 -OpStore %124 %144 -%145 = OpCompositeConstruct %33 %11 %7 %18 %21 +%129 = OpFunction %4 None %130 +%128 = OpLabel +%124 = OpVariable %118 Function +%119 = OpVariable %120 Function %47 +%113 = OpVariable %114 Function %19 +%107 = OpVariable %108 Function +%125 = OpVariable %120 Function +%121 = OpVariable %122 Function %50 +%115 = OpVariable %116 Function %5 +%109 = OpVariable %110 Function %12 +%126 = OpVariable %127 Function +%123 = OpVariable %108 Function %49 +%117 = OpVariable %118 Function %45 +%111 = OpVariable %112 Function %11 +OpBranch %131 +%131 = OpLabel +%132 = OpCompositeConstruct %27 %3 %3 %3 %3 +%133 = OpCompositeConstruct %31 %132 %7 +OpStore %107 %133 +%134 = OpCompositeConstruct %32 %3 %5 +%135 = OpCompositeConstruct %32 %5 %3 +%136 = OpCompositeConstruct %33 %134 %135 +%137 = OpCompositeConstruct %27 %3 %5 %5 %5 +%138 = OpCompositeConstruct %27 %5 %3 %5 %5 +%139 = OpCompositeConstruct %27 %5 %5 %3 %5 +%140 = OpCompositeConstruct %27 %5 %5 %5 %3 +%141 = OpCompositeConstruct %34 %137 %138 %139 %140 +%142 = OpCompositeConstruct %35 %19 %19 +OpStore %124 %142 +%143 = OpCompositeConstruct %32 %5 %5 +%144 = OpCompositeConstruct %32 %5 %5 +%145 = OpCompositeConstruct %33 %143 %144 OpStore %125 %145 -%148 = OpAccessChain %147 %106 %19 %19 -%149 = OpLoad %4 %148 -OpReturnValue %149 +%146 = OpCompositeConstruct %37 %11 %7 %18 %21 +OpStore %126 %146 +%149 = OpAccessChain %148 %107 %19 %19 +%150 = OpLoad %4 %149 +OpReturnValue %150 OpFunctionEnd -%151 = OpFunction %2 None %152 -%150 = OpLabel -OpBranch %153 -%153 = OpLabel -%154 = OpSMod %8 %7 %7 -%155 = OpFRem %4 %3 %3 -%157 = OpCompositeConstruct %156 %7 %7 %7 -%158 = OpCompositeConstruct %156 %7 %7 %7 -%159 = OpSMod %156 %157 %158 -%160 = OpCompositeConstruct %26 %3 %3 %3 -%161 = OpCompositeConstruct %26 %3 %3 %3 -%162 = OpFRem %26 %160 %161 +%152 = OpFunction %2 None %153 +%151 = OpLabel +OpBranch %154 +%154 = OpLabel +%155 = OpLogicalNot %10 %9 +%156 = OpLogicalOr %10 %9 %12 +%157 = OpLogicalAnd %10 %9 %12 +%158 = OpLogicalOr %10 %9 %12 +%159 = OpCompositeConstruct %101 %9 %9 %9 +%160 = OpCompositeConstruct %101 %12 %12 %12 +%161 = OpLogicalOr %101 %159 %160 +%162 = OpLogicalAnd %10 %9 %12 +%163 = OpCompositeConstruct %29 %9 %9 %9 %9 +%164 = OpCompositeConstruct %29 %12 %12 %12 %12 +%165 = OpLogicalAnd %29 %163 %164 OpReturn OpFunctionEnd -%164 = OpFunction %2 None %152 -%163 = OpLabel -OpBranch %165 -%165 = OpLabel -%166 = OpCompositeConstruct %23 %3 %5 %5 %5 -%167 = OpCompositeConstruct %23 %5 %3 %5 %5 -%168 = OpCompositeConstruct %23 %5 %5 %3 %5 -%169 = OpCompositeConstruct %23 %5 %5 %5 %3 -%170 = OpCompositeConstruct %30 %166 %167 %168 %169 -%171 = OpMatrixTimesScalar %30 %170 %14 +%167 = OpFunction %2 None %153 +%166 = OpLabel +OpBranch %168 +%168 = OpLabel +%170 = OpCompositeConstruct %169 %7 %7 +%171 = OpSNegate %169 %170 +%172 = OpCompositeConstruct %32 %3 %3 +%173 = OpFNegate %32 %172 +%174 = OpIAdd %8 %18 %7 +%175 = OpIAdd %20 %25 %26 +%176 = OpFAdd %4 %14 %3 +%177 = OpCompositeConstruct %169 %18 %18 +%178 = OpCompositeConstruct %169 %7 %7 +%179 = OpIAdd %169 %177 %178 +%181 = OpCompositeConstruct %180 %25 %25 %25 +%182 = OpCompositeConstruct %180 %26 %26 %26 +%183 = OpIAdd %180 %181 %182 +%184 = OpCompositeConstruct %27 %14 %14 %14 %14 +%185 = OpCompositeConstruct %27 %3 %3 %3 %3 +%186 = OpFAdd %27 %184 %185 +%187 = OpISub %8 %18 %7 +%188 = OpISub %20 %25 %26 +%189 = OpFSub %4 %14 %3 +%190 = OpCompositeConstruct %169 %18 %18 +%191 = OpCompositeConstruct %169 %7 %7 +%192 = OpISub %169 %190 %191 +%193 = OpCompositeConstruct %180 %25 %25 %25 +%194 = OpCompositeConstruct %180 %26 %26 %26 +%195 = OpISub %180 %193 %194 +%196 = OpCompositeConstruct %27 %14 %14 %14 %14 +%197 = OpCompositeConstruct %27 %3 %3 %3 %3 +%198 = OpFSub %27 %196 %197 +%199 = OpIMul %8 %18 %7 +%200 = OpIMul %20 %25 %26 +%201 = OpFMul %4 %14 %3 +%202 = OpCompositeConstruct %169 %18 %18 +%203 = OpCompositeConstruct %169 %7 %7 +%204 = OpIMul %169 %202 %203 +%205 = OpCompositeConstruct %180 %25 %25 %25 +%206 = OpCompositeConstruct %180 %26 %26 %26 +%207 = OpIMul %180 %205 %206 +%208 = OpCompositeConstruct %27 %14 %14 %14 %14 +%209 = OpCompositeConstruct %27 %3 %3 %3 %3 +%210 = OpFMul %27 %208 %209 +%211 = OpSDiv %8 %18 %7 +%212 = OpUDiv %20 %25 %26 +%213 = OpFDiv %4 %14 %3 +%214 = OpCompositeConstruct %169 %18 %18 +%215 = OpCompositeConstruct %169 %7 %7 +%216 = OpSDiv %169 %214 %215 +%217 = OpCompositeConstruct %180 %25 %25 %25 +%218 = OpCompositeConstruct %180 %26 %26 %26 +%219 = OpUDiv %180 %217 %218 +%220 = OpCompositeConstruct %27 %14 %14 %14 %14 +%221 = OpCompositeConstruct %27 %3 %3 %3 %3 +%222 = OpFDiv %27 %220 %221 +%223 = OpSMod %8 %18 %7 +%224 = OpUMod %20 %25 %26 +%225 = OpFRem %4 %14 %3 +%226 = OpCompositeConstruct %169 %18 %18 +%227 = OpCompositeConstruct %169 %7 %7 +%228 = OpSMod %169 %226 %227 +%229 = OpCompositeConstruct %180 %25 %25 %25 +%230 = OpCompositeConstruct %180 %26 %26 %26 +%231 = OpUMod %180 %229 %230 +%232 = OpCompositeConstruct %27 %14 %14 %14 %14 +%233 = OpCompositeConstruct %27 %3 %3 %3 %3 +%234 = OpFRem %27 %232 %233 +%235 = OpCompositeConstruct %169 %18 %18 +%236 = OpCompositeConstruct %169 %7 %7 +%237 = OpIAdd %169 %235 %236 +%238 = OpCompositeConstruct %169 %7 %7 +%239 = OpCompositeConstruct %169 %18 %18 +%240 = OpIAdd %169 %239 %238 +%241 = OpCompositeConstruct %169 %18 %18 +%242 = OpCompositeConstruct %169 %7 %7 +%243 = OpISub %169 %241 %242 +%244 = OpCompositeConstruct %169 %7 %7 +%245 = OpCompositeConstruct %169 %18 %18 +%246 = OpISub %169 %245 %244 +%247 = OpCompositeConstruct %169 %18 %18 +%248 = OpVectorTimesScalar %169 %247 %7 +%249 = OpCompositeConstruct %169 %7 %7 +%250 = OpVectorTimesScalar %169 %249 %18 +%251 = OpCompositeConstruct %169 %18 %18 +%252 = OpCompositeConstruct %169 %7 %7 +%253 = OpSDiv %169 %251 %252 +%254 = OpCompositeConstruct %169 %7 %7 +%255 = OpCompositeConstruct %169 %18 %18 +%256 = OpSDiv %169 %255 %254 +%257 = OpCompositeConstruct %169 %18 %18 +%258 = OpCompositeConstruct %169 %7 %7 +%259 = OpSMod %169 %257 %258 +%260 = OpCompositeConstruct %169 %7 %7 +%261 = OpCompositeConstruct %169 %18 %18 +%262 = OpSMod %169 %261 %260 +%263 = OpMatrixTimesScalar %38 %52 %3 +%264 = OpMatrixTimesScalar %38 %52 %14 +%265 = OpCompositeConstruct %27 %3 %3 %3 %3 +%266 = OpMatrixTimesVector %30 %53 %265 +%267 = OpCompositeConstruct %30 %14 %14 %14 +%268 = OpVectorTimesMatrix %27 %267 %53 +%269 = OpMatrixTimesMatrix %38 %53 %54 OpReturn OpFunctionEnd -%173 = OpFunction %2 None %152 -%172 = OpLabel -OpBranch %174 -%174 = OpLabel -%175 = OpLogicalOr %10 %9 %12 -%176 = OpLogicalAnd %10 %9 %12 +%271 = OpFunction %2 None %153 +%270 = OpLabel +OpBranch %272 +%272 = OpLabel +%273 = OpNot %8 %7 +%274 = OpNot %20 %26 +%275 = OpBitwiseOr %8 %18 %7 +%276 = OpBitwiseOr %20 %25 %26 +%277 = OpCompositeConstruct %169 %18 %18 +%278 = OpCompositeConstruct %169 %7 %7 +%279 = OpBitwiseOr %169 %277 %278 +%280 = OpCompositeConstruct %180 %25 %25 %25 +%281 = OpCompositeConstruct %180 %26 %26 %26 +%282 = OpBitwiseOr %180 %280 %281 +%283 = OpBitwiseAnd %8 %18 %7 +%284 = OpBitwiseAnd %20 %25 %26 +%285 = OpCompositeConstruct %169 %18 %18 +%286 = OpCompositeConstruct %169 %7 %7 +%287 = OpBitwiseAnd %169 %285 %286 +%288 = OpCompositeConstruct %180 %25 %25 %25 +%289 = OpCompositeConstruct %180 %26 %26 %26 +%290 = OpBitwiseAnd %180 %288 %289 +%291 = OpBitwiseXor %8 %18 %7 +%292 = OpBitwiseXor %20 %25 %26 +%293 = OpCompositeConstruct %169 %18 %18 +%294 = OpCompositeConstruct %169 %7 %7 +%295 = OpBitwiseXor %169 %293 %294 +%296 = OpCompositeConstruct %180 %25 %25 %25 +%297 = OpCompositeConstruct %180 %26 %26 %26 +%298 = OpBitwiseXor %180 %296 %297 +%299 = OpShiftLeftLogical %8 %18 %26 +%300 = OpShiftLeftLogical %20 %25 %26 +%301 = OpCompositeConstruct %169 %18 %18 +%302 = OpCompositeConstruct %35 %26 %26 +%303 = OpShiftLeftLogical %169 %301 %302 +%304 = OpCompositeConstruct %180 %25 %25 %25 +%305 = OpCompositeConstruct %180 %26 %26 %26 +%306 = OpShiftLeftLogical %180 %304 %305 +%307 = OpShiftRightArithmetic %8 %18 %26 +%308 = OpShiftRightLogical %20 %25 %26 +%309 = OpCompositeConstruct %169 %18 %18 +%310 = OpCompositeConstruct %35 %26 %26 +%311 = OpShiftRightArithmetic %169 %309 %310 +%312 = OpCompositeConstruct %180 %25 %25 %25 +%313 = OpCompositeConstruct %180 %26 %26 %26 +%314 = OpShiftRightLogical %180 %312 %313 OpReturn OpFunctionEnd -%179 = OpFunction %2 None %152 -%178 = OpLabel -%177 = OpVariable %111 Function %7 -OpBranch %180 -%180 = OpLabel -%181 = OpLoad %8 %177 -%182 = OpIAdd %8 %181 %7 -OpStore %177 %182 -%183 = OpLoad %8 %177 -%184 = OpISub %8 %183 %7 -OpStore %177 %184 -%185 = OpLoad %8 %177 -%186 = OpLoad %8 %177 -%187 = OpIMul %8 %185 %186 -OpStore %177 %187 -%188 = OpLoad %8 %177 -%189 = OpLoad %8 %177 -%190 = OpSDiv %8 %188 %189 -OpStore %177 %190 -%191 = OpLoad %8 %177 -%192 = OpSMod %8 %191 %7 -OpStore %177 %192 -%193 = OpLoad %8 %177 -%194 = OpBitwiseXor %8 %193 %11 -OpStore %177 %194 -%195 = OpLoad %8 %177 -%196 = OpBitwiseAnd %8 %195 %11 -OpStore %177 %196 -%197 = OpLoad %8 %177 -%198 = OpIAdd %8 %197 %7 -OpStore %177 %198 -%199 = OpLoad %8 %177 -%200 = OpISub %8 %199 %7 -OpStore %177 %200 +%316 = OpFunction %2 None %153 +%315 = OpLabel +OpBranch %317 +%317 = OpLabel +%318 = OpIEqual %10 %18 %7 +%319 = OpIEqual %10 %25 %26 +%320 = OpFOrdEqual %10 %14 %3 +%321 = OpCompositeConstruct %169 %18 %18 +%322 = OpCompositeConstruct %169 %7 %7 +%324 = OpIEqual %323 %321 %322 +%325 = OpCompositeConstruct %180 %25 %25 %25 +%326 = OpCompositeConstruct %180 %26 %26 %26 +%327 = OpIEqual %101 %325 %326 +%328 = OpCompositeConstruct %27 %14 %14 %14 %14 +%329 = OpCompositeConstruct %27 %3 %3 %3 %3 +%330 = OpFOrdEqual %29 %328 %329 +%331 = OpINotEqual %10 %18 %7 +%332 = OpINotEqual %10 %25 %26 +%333 = OpFOrdNotEqual %10 %14 %3 +%334 = OpCompositeConstruct %169 %18 %18 +%335 = OpCompositeConstruct %169 %7 %7 +%336 = OpINotEqual %323 %334 %335 +%337 = OpCompositeConstruct %180 %25 %25 %25 +%338 = OpCompositeConstruct %180 %26 %26 %26 +%339 = OpINotEqual %101 %337 %338 +%340 = OpCompositeConstruct %27 %14 %14 %14 %14 +%341 = OpCompositeConstruct %27 %3 %3 %3 %3 +%342 = OpFOrdNotEqual %29 %340 %341 +%343 = OpSLessThan %10 %18 %7 +%344 = OpULessThan %10 %25 %26 +%345 = OpFOrdLessThan %10 %14 %3 +%346 = OpCompositeConstruct %169 %18 %18 +%347 = OpCompositeConstruct %169 %7 %7 +%348 = OpSLessThan %323 %346 %347 +%349 = OpCompositeConstruct %180 %25 %25 %25 +%350 = OpCompositeConstruct %180 %26 %26 %26 +%351 = OpULessThan %101 %349 %350 +%352 = OpCompositeConstruct %27 %14 %14 %14 %14 +%353 = OpCompositeConstruct %27 %3 %3 %3 %3 +%354 = OpFOrdLessThan %29 %352 %353 +%355 = OpSLessThanEqual %10 %18 %7 +%356 = OpULessThanEqual %10 %25 %26 +%357 = OpFOrdLessThanEqual %10 %14 %3 +%358 = OpCompositeConstruct %169 %18 %18 +%359 = OpCompositeConstruct %169 %7 %7 +%360 = OpSLessThanEqual %323 %358 %359 +%361 = OpCompositeConstruct %180 %25 %25 %25 +%362 = OpCompositeConstruct %180 %26 %26 %26 +%363 = OpULessThanEqual %101 %361 %362 +%364 = OpCompositeConstruct %27 %14 %14 %14 %14 +%365 = OpCompositeConstruct %27 %3 %3 %3 %3 +%366 = OpFOrdLessThanEqual %29 %364 %365 +%367 = OpSGreaterThan %10 %18 %7 +%368 = OpUGreaterThan %10 %25 %26 +%369 = OpFOrdGreaterThan %10 %14 %3 +%370 = OpCompositeConstruct %169 %18 %18 +%371 = OpCompositeConstruct %169 %7 %7 +%372 = OpSGreaterThan %323 %370 %371 +%373 = OpCompositeConstruct %180 %25 %25 %25 +%374 = OpCompositeConstruct %180 %26 %26 %26 +%375 = OpUGreaterThan %101 %373 %374 +%376 = OpCompositeConstruct %27 %14 %14 %14 %14 +%377 = OpCompositeConstruct %27 %3 %3 %3 %3 +%378 = OpFOrdGreaterThan %29 %376 %377 +%379 = OpSGreaterThanEqual %10 %18 %7 +%380 = OpUGreaterThanEqual %10 %25 %26 +%381 = OpFOrdGreaterThanEqual %10 %14 %3 +%382 = OpCompositeConstruct %169 %18 %18 +%383 = OpCompositeConstruct %169 %7 %7 +%384 = OpSGreaterThanEqual %323 %382 %383 +%385 = OpCompositeConstruct %180 %25 %25 %25 +%386 = OpCompositeConstruct %180 %26 %26 %26 +%387 = OpUGreaterThanEqual %101 %385 %386 +%388 = OpCompositeConstruct %27 %14 %14 %14 %14 +%389 = OpCompositeConstruct %27 %3 %3 %3 %3 +%390 = OpFOrdGreaterThanEqual %29 %388 %389 OpReturn OpFunctionEnd -%202 = OpFunction %2 None %152 -%201 = OpLabel -OpBranch %203 -%203 = OpLabel -%204 = OpFunctionCall %23 %45 -%205 = OpFunctionCall %23 %70 -%206 = OpFunctionCall %8 %86 -%207 = OpVectorShuffle %26 %34 %34 0 1 2 -%208 = OpFunctionCall %26 %97 %207 -%209 = OpFunctionCall %4 %128 -%210 = OpFunctionCall %2 %151 -%211 = OpFunctionCall %2 %164 -%212 = OpFunctionCall %2 %173 -%213 = OpFunctionCall %2 %179 +%393 = OpFunction %2 None %153 +%392 = OpLabel +%391 = OpVariable %112 Function %7 +OpBranch %394 +%394 = OpLabel +%395 = OpLoad %8 %391 +%396 = OpIAdd %8 %395 %7 +OpStore %391 %396 +%397 = OpLoad %8 %391 +%398 = OpISub %8 %397 %7 +OpStore %391 %398 +%399 = OpLoad %8 %391 +%400 = OpLoad %8 %391 +%401 = OpIMul %8 %399 %400 +OpStore %391 %401 +%402 = OpLoad %8 %391 +%403 = OpLoad %8 %391 +%404 = OpSDiv %8 %402 %403 +OpStore %391 %404 +%405 = OpLoad %8 %391 +%406 = OpSMod %8 %405 %7 +OpStore %391 %406 +%407 = OpLoad %8 %391 +%408 = OpBitwiseAnd %8 %407 %11 +OpStore %391 %408 +%409 = OpLoad %8 %391 +%410 = OpBitwiseOr %8 %409 %11 +OpStore %391 %410 +%411 = OpLoad %8 %391 +%412 = OpBitwiseXor %8 %411 %11 +OpStore %391 %412 +%413 = OpLoad %8 %391 +%414 = OpShiftLeftLogical %8 %413 %25 +OpStore %391 %414 +%415 = OpLoad %8 %391 +%416 = OpShiftRightArithmetic %8 %415 %26 +OpStore %391 %416 +%417 = OpLoad %8 %391 +%418 = OpIAdd %8 %417 %7 +OpStore %391 %418 +%419 = OpLoad %8 %391 +%420 = OpISub %8 %419 %7 +OpStore %391 %420 +OpReturn +OpFunctionEnd +%422 = OpFunction %2 None %153 +%421 = OpLabel +OpBranch %423 +%423 = OpLabel +%424 = OpFunctionCall %27 %56 +%425 = OpFunctionCall %27 %81 +%426 = OpVectorShuffle %30 %41 %41 0 1 2 +%427 = OpFunctionCall %30 %98 %426 +%428 = OpFunctionCall %4 %129 +%429 = OpFunctionCall %2 %152 +%430 = OpFunctionCall %2 %167 +%431 = OpFunctionCall %2 %271 +%432 = OpFunctionCall %2 %316 +%433 = OpFunctionCall %2 %393 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index d2ce23857..297b75240 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -25,14 +25,6 @@ fn splat() -> vec4 { return (a_1.xyxy + vec4(b)); } -fn unary() -> i32 { - if !(true) { - return 1; - } else { - return ~(1); - } -} - fn bool_cast(x: vec3) -> vec3 { let y = vec3(x); return vec3(y); @@ -62,24 +54,131 @@ fn constructors() -> f32 { return _e70; } -fn modulo() { - let a_2 = (1 % 1); - let b_1 = (1.0 % 1.0); - let c = (vec3(1) % vec3(1)); - let d = (vec3(1.0) % vec3(1.0)); -} - -fn scalar_times_matrix() { - let model = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let assertion = (2.0 * model); -} - fn logical() { - let a_3 = (true | false); - let b_2 = (true & false); + let unnamed_11 = !(true); + let unnamed_12 = (true || false); + let unnamed_13 = (true && false); + let unnamed_14 = (true | false); + let unnamed_15 = (vec3(true) | vec3(false)); + let unnamed_16 = (true & false); + let unnamed_17 = (vec4(true) & vec4(false)); } -fn binary_assignment() { +fn arithmetic() { + let unnamed_18 = -(vec2(1)); + let unnamed_19 = -(vec2(1.0)); + let unnamed_20 = (2 + 1); + let unnamed_21 = (2u + 1u); + let unnamed_22 = (2.0 + 1.0); + let unnamed_23 = (vec2(2) + vec2(1)); + let unnamed_24 = (vec3(2u) + vec3(1u)); + let unnamed_25 = (vec4(2.0) + vec4(1.0)); + let unnamed_26 = (2 - 1); + let unnamed_27 = (2u - 1u); + let unnamed_28 = (2.0 - 1.0); + let unnamed_29 = (vec2(2) - vec2(1)); + let unnamed_30 = (vec3(2u) - vec3(1u)); + let unnamed_31 = (vec4(2.0) - vec4(1.0)); + let unnamed_32 = (2 * 1); + let unnamed_33 = (2u * 1u); + let unnamed_34 = (2.0 * 1.0); + let unnamed_35 = (vec2(2) * vec2(1)); + let unnamed_36 = (vec3(2u) * vec3(1u)); + let unnamed_37 = (vec4(2.0) * vec4(1.0)); + let unnamed_38 = (2 / 1); + let unnamed_39 = (2u / 1u); + let unnamed_40 = (2.0 / 1.0); + let unnamed_41 = (vec2(2) / vec2(1)); + let unnamed_42 = (vec3(2u) / vec3(1u)); + let unnamed_43 = (vec4(2.0) / vec4(1.0)); + let unnamed_44 = (2 % 1); + let unnamed_45 = (2u % 1u); + let unnamed_46 = (2.0 % 1.0); + let unnamed_47 = (vec2(2) % vec2(1)); + let unnamed_48 = (vec3(2u) % vec3(1u)); + let unnamed_49 = (vec4(2.0) % vec4(1.0)); + let unnamed_50 = (vec2(2) + vec2(1)); + let unnamed_51 = (vec2(2) + vec2(1)); + let unnamed_52 = (vec2(2) - vec2(1)); + let unnamed_53 = (vec2(2) - vec2(1)); + let unnamed_54 = (vec2(2) * 1); + let unnamed_55 = (2 * vec2(1)); + let unnamed_56 = (vec2(2) / vec2(1)); + let unnamed_57 = (vec2(2) / vec2(1)); + let unnamed_58 = (vec2(2) % vec2(1)); + let unnamed_59 = (vec2(2) % vec2(1)); + let unnamed_60 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + let unnamed_61 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_62 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + let unnamed_63 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_64 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); +} + +fn bit() { + let unnamed_65 = ~(1); + let unnamed_66 = ~(1u); + let unnamed_67 = (2 | 1); + let unnamed_68 = (2u | 1u); + let unnamed_69 = (vec2(2) | vec2(1)); + let unnamed_70 = (vec3(2u) | vec3(1u)); + let unnamed_71 = (2 & 1); + let unnamed_72 = (2u & 1u); + let unnamed_73 = (vec2(2) & vec2(1)); + let unnamed_74 = (vec3(2u) & vec3(1u)); + let unnamed_75 = (2 ^ 1); + let unnamed_76 = (2u ^ 1u); + let unnamed_77 = (vec2(2) ^ vec2(1)); + let unnamed_78 = (vec3(2u) ^ vec3(1u)); + let unnamed_79 = (2 << 1u); + let unnamed_80 = (2u << 1u); + let unnamed_81 = (vec2(2) << vec2(1u)); + let unnamed_82 = (vec3(2u) << vec3(1u)); + let unnamed_83 = (2 >> 1u); + let unnamed_84 = (2u >> 1u); + let unnamed_85 = (vec2(2) >> vec2(1u)); + let unnamed_86 = (vec3(2u) >> vec3(1u)); +} + +fn comparison() { + let unnamed_87 = (2 == 1); + let unnamed_88 = (2u == 1u); + let unnamed_89 = (2.0 == 1.0); + let unnamed_90 = (vec2(2) == vec2(1)); + let unnamed_91 = (vec3(2u) == vec3(1u)); + let unnamed_92 = (vec4(2.0) == vec4(1.0)); + let unnamed_93 = (2 != 1); + let unnamed_94 = (2u != 1u); + let unnamed_95 = (2.0 != 1.0); + let unnamed_96 = (vec2(2) != vec2(1)); + let unnamed_97 = (vec3(2u) != vec3(1u)); + let unnamed_98 = (vec4(2.0) != vec4(1.0)); + let unnamed_99 = (2 < 1); + let unnamed_100 = (2u < 1u); + let unnamed_101 = (2.0 < 1.0); + let unnamed_102 = (vec2(2) < vec2(1)); + let unnamed_103 = (vec3(2u) < vec3(1u)); + let unnamed_104 = (vec4(2.0) < vec4(1.0)); + let unnamed_105 = (2 <= 1); + let unnamed_106 = (2u <= 1u); + let unnamed_107 = (2.0 <= 1.0); + let unnamed_108 = (vec2(2) <= vec2(1)); + let unnamed_109 = (vec3(2u) <= vec3(1u)); + let unnamed_110 = (vec4(2.0) <= vec4(1.0)); + let unnamed_111 = (2 > 1); + let unnamed_112 = (2u > 1u); + let unnamed_113 = (2.0 > 1.0); + let unnamed_114 = (vec2(2) > vec2(1)); + let unnamed_115 = (vec3(2u) > vec3(1u)); + let unnamed_116 = (vec4(2.0) > vec4(1.0)); + let unnamed_117 = (2 >= 1); + let unnamed_118 = (2u >= 1u); + let unnamed_119 = (2.0 >= 1.0); + let unnamed_120 = (vec2(2) >= vec2(1)); + let unnamed_121 = (vec3(2u) >= vec3(1u)); + let unnamed_122 = (vec4(2.0) >= vec4(1.0)); +} + +fn assignment() { var a: i32 = 1; let _e6 = a; @@ -95,13 +194,19 @@ fn binary_assignment() { let _e18 = a; a = (_e18 % 1); let _e21 = a; - a = (_e21 ^ 0); + a = (_e21 & 0); let _e24 = a; - a = (_e24 & 0); + a = (_e24 | 0); let _e27 = a; - a = (_e27 + 1); + a = (_e27 ^ 0); let _e30 = a; - a = (_e30 - 1); + a = (_e30 << 2u); + let _e33 = a; + a = (_e33 >> 1u); + let _e36 = a; + a = (_e36 + 1); + let _e39 = a; + a = (_e39 - 1); return; } @@ -109,12 +214,12 @@ fn binary_assignment() { fn main() { let _e4 = builtins(); let _e5 = splat(); - let _e6 = unary(); - let _e8 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); - let _e9 = constructors(); - modulo(); - scalar_times_matrix(); + let _e7 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + let _e8 = constructors(); logical(); - binary_assignment(); + arithmetic(); + bit(); + comparison(); + assignment(); return; } From 4366e656097a6f9ae7ab4086ff0511186fea1821 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 15:52:32 +0200 Subject: [PATCH 1678/2212] add support for unary vector operators --- src/back/glsl/mod.rs | 11 +- src/back/hlsl/writer.rs | 11 +- src/back/msl/writer.rs | 7 +- tests/in/operators.wgsl | 6 +- tests/out/glsl/operators.main.Compute.glsl | 217 ++++---- tests/out/hlsl/operators.hlsl | 217 ++++---- tests/out/msl/operators.msl | 217 ++++---- tests/out/spv/operators.spvasm | 602 +++++++++++---------- tests/out/wgsl/operators.wgsl | 217 ++++---- 9 files changed, 764 insertions(+), 741 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index f052b3bec..95d804689 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2457,10 +2457,13 @@ impl<'a, W: Write> Writer<'a, W> { "({} ", match op { Uo::Negate => "-", - Uo::Not => match *ctx.info[expr].ty.inner_with(&self.module.types) { - TypeInner::Scalar { kind: Sk::Sint, .. } => "~", - TypeInner::Scalar { kind: Sk::Uint, .. } => "~", - TypeInner::Scalar { kind: Sk::Bool, .. } => "!", + Uo::Not => match ctx.info[expr] + .ty + .inner_with(&self.module.types) + .scalar_kind() + { + Some(Sk::Sint) | Some(Sk::Uint) => "~", + Some(Sk::Bool) => "!", ref other => return Err(Error::Custom(format!( "Cannot apply not to type {:?}", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 4f3c88049..a0992b0a2 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2041,10 +2041,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators let op_str = match op { Uo::Negate => "-", - Uo::Not => match *func_ctx.info[expr].ty.inner_with(&module.types) { - TypeInner::Scalar { kind: Sk::Sint, .. } => "~", - TypeInner::Scalar { kind: Sk::Uint, .. } => "~", - TypeInner::Scalar { kind: Sk::Bool, .. } => "!", + Uo::Not => match func_ctx.info[expr] + .ty + .inner_with(&module.types) + .scalar_kind() + { + Some(Sk::Sint) | Some(Sk::Uint) => "~", + Some(Sk::Bool) => "!", ref other => { return Err(Error::Custom(format!( "Cannot apply not to type {:?}", diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 3d1a10972..982742c7a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1421,10 +1421,9 @@ impl Writer { use crate::{ScalarKind as Sk, UnaryOperator as Uo}; let op_str = match op { Uo::Negate => "-", - Uo::Not => match *context.resolve_type(expr) { - crate::TypeInner::Scalar { kind: Sk::Sint, .. } => "~", - crate::TypeInner::Scalar { kind: Sk::Uint, .. } => "~", - crate::TypeInner::Scalar { kind: Sk::Bool, .. } => "!", + Uo::Not => match context.resolve_type(expr).scalar_kind() { + Some(Sk::Sint) | Some(Sk::Uint) => "~", + Some(Sk::Bool) => "!", _ => return Err(Error::Validation), }, }; diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 8522e830c..31ca1f740 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -74,7 +74,7 @@ fn constructors() -> f32 { fn logical() { // unary let _ = !true; - // let _ = !vec2(true); + let _ = !vec2(true); // binary let _ = true || false; @@ -166,8 +166,8 @@ fn bit() { // unary let _ = ~1; let _ = ~1u; - // let _ = ~vec2(1); - // let _ = ~vec3(1u); + let _ = ~vec2(1); + let _ = ~vec3(1u); // binary let _ = 2 | 1; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 1f8bdcc9b..2aeb893a9 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -58,126 +58,129 @@ float constructors() { void logical() { bool unnamed_11 = (! true); - bool unnamed_12 = (true || false); - bool unnamed_13 = (true && false); - bool unnamed_14 = (true || false); - bvec3 unnamed_15 = (bvec3(true) | bvec3(false)); - bool unnamed_16 = (true && false); - bvec4 unnamed_17 = (bvec4(true) & bvec4(false)); + bvec2 unnamed_12 = (! bvec2(true)); + bool unnamed_13 = (true || false); + bool unnamed_14 = (true && false); + bool unnamed_15 = (true || false); + bvec3 unnamed_16 = (bvec3(true) | bvec3(false)); + bool unnamed_17 = (true && false); + bvec4 unnamed_18 = (bvec4(true) & bvec4(false)); } void arithmetic() { - ivec2 unnamed_18 = (- ivec2(1)); - vec2 unnamed_19 = (- vec2(1.0)); - int unnamed_20 = (2 + 1); - uint unnamed_21 = (2u + 1u); - float unnamed_22 = (2.0 + 1.0); - ivec2 unnamed_23 = (ivec2(2) + ivec2(1)); - uvec3 unnamed_24 = (uvec3(2u) + uvec3(1u)); - vec4 unnamed_25 = (vec4(2.0) + vec4(1.0)); - int unnamed_26 = (2 - 1); - uint unnamed_27 = (2u - 1u); - float unnamed_28 = (2.0 - 1.0); - ivec2 unnamed_29 = (ivec2(2) - ivec2(1)); - uvec3 unnamed_30 = (uvec3(2u) - uvec3(1u)); - vec4 unnamed_31 = (vec4(2.0) - vec4(1.0)); - int unnamed_32 = (2 * 1); - uint unnamed_33 = (2u * 1u); - float unnamed_34 = (2.0 * 1.0); - ivec2 unnamed_35 = (ivec2(2) * ivec2(1)); - uvec3 unnamed_36 = (uvec3(2u) * uvec3(1u)); - vec4 unnamed_37 = (vec4(2.0) * vec4(1.0)); - int unnamed_38 = (2 / 1); - uint unnamed_39 = (2u / 1u); - float unnamed_40 = (2.0 / 1.0); - ivec2 unnamed_41 = (ivec2(2) / ivec2(1)); - uvec3 unnamed_42 = (uvec3(2u) / uvec3(1u)); - vec4 unnamed_43 = (vec4(2.0) / vec4(1.0)); - int unnamed_44 = (2 % 1); - uint unnamed_45 = (2u % 1u); - float unnamed_46 = (2.0 - 1.0 * trunc(2.0 / 1.0)); - ivec2 unnamed_47 = (ivec2(2) % ivec2(1)); - uvec3 unnamed_48 = (uvec3(2u) % uvec3(1u)); - vec4 unnamed_49 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); - ivec2 unnamed_50 = (ivec2(2) + ivec2(1)); + ivec2 unnamed_19 = (- ivec2(1)); + vec2 unnamed_20 = (- vec2(1.0)); + int unnamed_21 = (2 + 1); + uint unnamed_22 = (2u + 1u); + float unnamed_23 = (2.0 + 1.0); + ivec2 unnamed_24 = (ivec2(2) + ivec2(1)); + uvec3 unnamed_25 = (uvec3(2u) + uvec3(1u)); + vec4 unnamed_26 = (vec4(2.0) + vec4(1.0)); + int unnamed_27 = (2 - 1); + uint unnamed_28 = (2u - 1u); + float unnamed_29 = (2.0 - 1.0); + ivec2 unnamed_30 = (ivec2(2) - ivec2(1)); + uvec3 unnamed_31 = (uvec3(2u) - uvec3(1u)); + vec4 unnamed_32 = (vec4(2.0) - vec4(1.0)); + int unnamed_33 = (2 * 1); + uint unnamed_34 = (2u * 1u); + float unnamed_35 = (2.0 * 1.0); + ivec2 unnamed_36 = (ivec2(2) * ivec2(1)); + uvec3 unnamed_37 = (uvec3(2u) * uvec3(1u)); + vec4 unnamed_38 = (vec4(2.0) * vec4(1.0)); + int unnamed_39 = (2 / 1); + uint unnamed_40 = (2u / 1u); + float unnamed_41 = (2.0 / 1.0); + ivec2 unnamed_42 = (ivec2(2) / ivec2(1)); + uvec3 unnamed_43 = (uvec3(2u) / uvec3(1u)); + vec4 unnamed_44 = (vec4(2.0) / vec4(1.0)); + int unnamed_45 = (2 % 1); + uint unnamed_46 = (2u % 1u); + float unnamed_47 = (2.0 - 1.0 * trunc(2.0 / 1.0)); + ivec2 unnamed_48 = (ivec2(2) % ivec2(1)); + uvec3 unnamed_49 = (uvec3(2u) % uvec3(1u)); + vec4 unnamed_50 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); ivec2 unnamed_51 = (ivec2(2) + ivec2(1)); - ivec2 unnamed_52 = (ivec2(2) - ivec2(1)); + ivec2 unnamed_52 = (ivec2(2) + ivec2(1)); ivec2 unnamed_53 = (ivec2(2) - ivec2(1)); - ivec2 unnamed_54 = (ivec2(2) * 1); - ivec2 unnamed_55 = (2 * ivec2(1)); - ivec2 unnamed_56 = (ivec2(2) / ivec2(1)); + ivec2 unnamed_54 = (ivec2(2) - ivec2(1)); + ivec2 unnamed_55 = (ivec2(2) * 1); + ivec2 unnamed_56 = (2 * ivec2(1)); ivec2 unnamed_57 = (ivec2(2) / ivec2(1)); - ivec2 unnamed_58 = (ivec2(2) % ivec2(1)); + ivec2 unnamed_58 = (ivec2(2) / ivec2(1)); ivec2 unnamed_59 = (ivec2(2) % ivec2(1)); - mat3x3 unnamed_60 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - mat3x3 unnamed_61 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - vec3 unnamed_62 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - vec4 unnamed_63 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_64 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + ivec2 unnamed_60 = (ivec2(2) % ivec2(1)); + mat3x3 unnamed_61 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + mat3x3 unnamed_62 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + vec3 unnamed_63 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + vec4 unnamed_64 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_65 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } void bit() { - int unnamed_65 = (~ 1); - uint unnamed_66 = (~ 1u); - int unnamed_67 = (2 | 1); - uint unnamed_68 = (2u | 1u); - ivec2 unnamed_69 = (ivec2(2) | ivec2(1)); - uvec3 unnamed_70 = (uvec3(2u) | uvec3(1u)); - int unnamed_71 = (2 & 1); - uint unnamed_72 = (2u & 1u); - ivec2 unnamed_73 = (ivec2(2) & ivec2(1)); - uvec3 unnamed_74 = (uvec3(2u) & uvec3(1u)); - int unnamed_75 = (2 ^ 1); - uint unnamed_76 = (2u ^ 1u); - ivec2 unnamed_77 = (ivec2(2) ^ ivec2(1)); - uvec3 unnamed_78 = (uvec3(2u) ^ uvec3(1u)); - int unnamed_79 = (2 << 1u); - uint unnamed_80 = (2u << 1u); - ivec2 unnamed_81 = (ivec2(2) << uvec2(1u)); - uvec3 unnamed_82 = (uvec3(2u) << uvec3(1u)); - int unnamed_83 = (2 >> 1u); - uint unnamed_84 = (2u >> 1u); - ivec2 unnamed_85 = (ivec2(2) >> uvec2(1u)); - uvec3 unnamed_86 = (uvec3(2u) >> uvec3(1u)); + int unnamed_66 = (~ 1); + uint unnamed_67 = (~ 1u); + ivec2 unnamed_68 = (~ ivec2(1)); + uvec3 unnamed_69 = (~ uvec3(1u)); + int unnamed_70 = (2 | 1); + uint unnamed_71 = (2u | 1u); + ivec2 unnamed_72 = (ivec2(2) | ivec2(1)); + uvec3 unnamed_73 = (uvec3(2u) | uvec3(1u)); + int unnamed_74 = (2 & 1); + uint unnamed_75 = (2u & 1u); + ivec2 unnamed_76 = (ivec2(2) & ivec2(1)); + uvec3 unnamed_77 = (uvec3(2u) & uvec3(1u)); + int unnamed_78 = (2 ^ 1); + uint unnamed_79 = (2u ^ 1u); + ivec2 unnamed_80 = (ivec2(2) ^ ivec2(1)); + uvec3 unnamed_81 = (uvec3(2u) ^ uvec3(1u)); + int unnamed_82 = (2 << 1u); + uint unnamed_83 = (2u << 1u); + ivec2 unnamed_84 = (ivec2(2) << uvec2(1u)); + uvec3 unnamed_85 = (uvec3(2u) << uvec3(1u)); + int unnamed_86 = (2 >> 1u); + uint unnamed_87 = (2u >> 1u); + ivec2 unnamed_88 = (ivec2(2) >> uvec2(1u)); + uvec3 unnamed_89 = (uvec3(2u) >> uvec3(1u)); } void comparison() { - bool unnamed_87 = (2 == 1); - bool unnamed_88 = (2u == 1u); - bool unnamed_89 = (2.0 == 1.0); - bvec2 unnamed_90 = equal(ivec2(2), ivec2(1)); - bvec3 unnamed_91 = equal(uvec3(2u), uvec3(1u)); - bvec4 unnamed_92 = equal(vec4(2.0), vec4(1.0)); - bool unnamed_93 = (2 != 1); - bool unnamed_94 = (2u != 1u); - bool unnamed_95 = (2.0 != 1.0); - bvec2 unnamed_96 = notEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_97 = notEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_98 = notEqual(vec4(2.0), vec4(1.0)); - bool unnamed_99 = (2 < 1); - bool unnamed_100 = (2u < 1u); - bool unnamed_101 = (2.0 < 1.0); - bvec2 unnamed_102 = lessThan(ivec2(2), ivec2(1)); - bvec3 unnamed_103 = lessThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_104 = lessThan(vec4(2.0), vec4(1.0)); - bool unnamed_105 = (2 <= 1); - bool unnamed_106 = (2u <= 1u); - bool unnamed_107 = (2.0 <= 1.0); - bvec2 unnamed_108 = lessThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_109 = lessThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_110 = lessThanEqual(vec4(2.0), vec4(1.0)); - bool unnamed_111 = (2 > 1); - bool unnamed_112 = (2u > 1u); - bool unnamed_113 = (2.0 > 1.0); - bvec2 unnamed_114 = greaterThan(ivec2(2), ivec2(1)); - bvec3 unnamed_115 = greaterThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_116 = greaterThan(vec4(2.0), vec4(1.0)); - bool unnamed_117 = (2 >= 1); - bool unnamed_118 = (2u >= 1u); - bool unnamed_119 = (2.0 >= 1.0); - bvec2 unnamed_120 = greaterThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_121 = greaterThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_122 = greaterThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_90 = (2 == 1); + bool unnamed_91 = (2u == 1u); + bool unnamed_92 = (2.0 == 1.0); + bvec2 unnamed_93 = equal(ivec2(2), ivec2(1)); + bvec3 unnamed_94 = equal(uvec3(2u), uvec3(1u)); + bvec4 unnamed_95 = equal(vec4(2.0), vec4(1.0)); + bool unnamed_96 = (2 != 1); + bool unnamed_97 = (2u != 1u); + bool unnamed_98 = (2.0 != 1.0); + bvec2 unnamed_99 = notEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_100 = notEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_101 = notEqual(vec4(2.0), vec4(1.0)); + bool unnamed_102 = (2 < 1); + bool unnamed_103 = (2u < 1u); + bool unnamed_104 = (2.0 < 1.0); + bvec2 unnamed_105 = lessThan(ivec2(2), ivec2(1)); + bvec3 unnamed_106 = lessThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_107 = lessThan(vec4(2.0), vec4(1.0)); + bool unnamed_108 = (2 <= 1); + bool unnamed_109 = (2u <= 1u); + bool unnamed_110 = (2.0 <= 1.0); + bvec2 unnamed_111 = lessThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_112 = lessThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_113 = lessThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_114 = (2 > 1); + bool unnamed_115 = (2u > 1u); + bool unnamed_116 = (2.0 > 1.0); + bvec2 unnamed_117 = greaterThan(ivec2(2), ivec2(1)); + bvec3 unnamed_118 = greaterThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_119 = greaterThan(vec4(2.0), vec4(1.0)); + bool unnamed_120 = (2 >= 1); + bool unnamed_121 = (2u >= 1u); + bool unnamed_122 = (2.0 >= 1.0); + bvec2 unnamed_123 = greaterThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_124 = greaterThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_125 = greaterThanEqual(vec4(2.0), vec4(1.0)); } void assignment() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index ec4af04b9..5275cbe3b 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -85,129 +85,132 @@ float constructors() void logical() { bool unnamed_11 = !true; - bool unnamed_12 = (true || false); - bool unnamed_13 = (true && false); - bool unnamed_14 = (true | false); - bool3 unnamed_15 = (bool3(true.xxx) | bool3(false.xxx)); - bool unnamed_16 = (true & false); - bool4 unnamed_17 = (bool4(true.xxxx) & bool4(false.xxxx)); + bool2 unnamed_12 = !bool2(true.xx); + bool unnamed_13 = (true || false); + bool unnamed_14 = (true && false); + bool unnamed_15 = (true | false); + bool3 unnamed_16 = (bool3(true.xxx) | bool3(false.xxx)); + bool unnamed_17 = (true & false); + bool4 unnamed_18 = (bool4(true.xxxx) & bool4(false.xxxx)); } void arithmetic() { - int2 unnamed_18 = -int2(1.xx); - float2 unnamed_19 = -float2(1.0.xx); - int unnamed_20 = (2 + 1); - uint unnamed_21 = (2u + 1u); - float unnamed_22 = (2.0 + 1.0); - int2 unnamed_23 = (int2(2.xx) + int2(1.xx)); - uint3 unnamed_24 = (uint3(2u.xxx) + uint3(1u.xxx)); - float4 unnamed_25 = (float4(2.0.xxxx) + float4(1.0.xxxx)); - int unnamed_26 = (2 - 1); - uint unnamed_27 = (2u - 1u); - float unnamed_28 = (2.0 - 1.0); - int2 unnamed_29 = (int2(2.xx) - int2(1.xx)); - uint3 unnamed_30 = (uint3(2u.xxx) - uint3(1u.xxx)); - float4 unnamed_31 = (float4(2.0.xxxx) - float4(1.0.xxxx)); - int unnamed_32 = (2 * 1); - uint unnamed_33 = (2u * 1u); - float unnamed_34 = (2.0 * 1.0); - int2 unnamed_35 = (int2(2.xx) * int2(1.xx)); - uint3 unnamed_36 = (uint3(2u.xxx) * uint3(1u.xxx)); - float4 unnamed_37 = (float4(2.0.xxxx) * float4(1.0.xxxx)); - int unnamed_38 = (2 / 1); - uint unnamed_39 = (2u / 1u); - float unnamed_40 = (2.0 / 1.0); - int2 unnamed_41 = (int2(2.xx) / int2(1.xx)); - uint3 unnamed_42 = (uint3(2u.xxx) / uint3(1u.xxx)); - float4 unnamed_43 = (float4(2.0.xxxx) / float4(1.0.xxxx)); - int unnamed_44 = (2 % 1); - uint unnamed_45 = (2u % 1u); - float unnamed_46 = (2.0 % 1.0); - int2 unnamed_47 = (int2(2.xx) % int2(1.xx)); - uint3 unnamed_48 = (uint3(2u.xxx) % uint3(1u.xxx)); - float4 unnamed_49 = (float4(2.0.xxxx) % float4(1.0.xxxx)); - int2 unnamed_50 = (int2(2.xx) + int2(1.xx)); + int2 unnamed_19 = -int2(1.xx); + float2 unnamed_20 = -float2(1.0.xx); + int unnamed_21 = (2 + 1); + uint unnamed_22 = (2u + 1u); + float unnamed_23 = (2.0 + 1.0); + int2 unnamed_24 = (int2(2.xx) + int2(1.xx)); + uint3 unnamed_25 = (uint3(2u.xxx) + uint3(1u.xxx)); + float4 unnamed_26 = (float4(2.0.xxxx) + float4(1.0.xxxx)); + int unnamed_27 = (2 - 1); + uint unnamed_28 = (2u - 1u); + float unnamed_29 = (2.0 - 1.0); + int2 unnamed_30 = (int2(2.xx) - int2(1.xx)); + uint3 unnamed_31 = (uint3(2u.xxx) - uint3(1u.xxx)); + float4 unnamed_32 = (float4(2.0.xxxx) - float4(1.0.xxxx)); + int unnamed_33 = (2 * 1); + uint unnamed_34 = (2u * 1u); + float unnamed_35 = (2.0 * 1.0); + int2 unnamed_36 = (int2(2.xx) * int2(1.xx)); + uint3 unnamed_37 = (uint3(2u.xxx) * uint3(1u.xxx)); + float4 unnamed_38 = (float4(2.0.xxxx) * float4(1.0.xxxx)); + int unnamed_39 = (2 / 1); + uint unnamed_40 = (2u / 1u); + float unnamed_41 = (2.0 / 1.0); + int2 unnamed_42 = (int2(2.xx) / int2(1.xx)); + uint3 unnamed_43 = (uint3(2u.xxx) / uint3(1u.xxx)); + float4 unnamed_44 = (float4(2.0.xxxx) / float4(1.0.xxxx)); + int unnamed_45 = (2 % 1); + uint unnamed_46 = (2u % 1u); + float unnamed_47 = (2.0 % 1.0); + int2 unnamed_48 = (int2(2.xx) % int2(1.xx)); + uint3 unnamed_49 = (uint3(2u.xxx) % uint3(1u.xxx)); + float4 unnamed_50 = (float4(2.0.xxxx) % float4(1.0.xxxx)); int2 unnamed_51 = (int2(2.xx) + int2(1.xx)); - int2 unnamed_52 = (int2(2.xx) - int2(1.xx)); + int2 unnamed_52 = (int2(2.xx) + int2(1.xx)); int2 unnamed_53 = (int2(2.xx) - int2(1.xx)); - int2 unnamed_54 = (int2(2.xx) * 1); - int2 unnamed_55 = (2 * int2(1.xx)); - int2 unnamed_56 = (int2(2.xx) / int2(1.xx)); + int2 unnamed_54 = (int2(2.xx) - int2(1.xx)); + int2 unnamed_55 = (int2(2.xx) * 1); + int2 unnamed_56 = (2 * int2(1.xx)); int2 unnamed_57 = (int2(2.xx) / int2(1.xx)); - int2 unnamed_58 = (int2(2.xx) % int2(1.xx)); + int2 unnamed_58 = (int2(2.xx) / int2(1.xx)); int2 unnamed_59 = (int2(2.xx) % int2(1.xx)); - float3x3 unnamed_60 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_61 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); - float3 unnamed_62 = mul(float4(1.0.xxxx), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float4 unnamed_63 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), float3(2.0.xxx)); - float3x3 unnamed_64 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + int2 unnamed_60 = (int2(2.xx) % int2(1.xx)); + float3x3 unnamed_61 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_62 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); + float3 unnamed_63 = mul(float4(1.0.xxxx), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float4 unnamed_64 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), float3(2.0.xxx)); + float3x3 unnamed_65 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); } void bit() { - int unnamed_65 = ~1; - uint unnamed_66 = ~1u; - int unnamed_67 = (2 | 1); - uint unnamed_68 = (2u | 1u); - int2 unnamed_69 = (int2(2.xx) | int2(1.xx)); - uint3 unnamed_70 = (uint3(2u.xxx) | uint3(1u.xxx)); - int unnamed_71 = (2 & 1); - uint unnamed_72 = (2u & 1u); - int2 unnamed_73 = (int2(2.xx) & int2(1.xx)); - uint3 unnamed_74 = (uint3(2u.xxx) & uint3(1u.xxx)); - int unnamed_75 = (2 ^ 1); - uint unnamed_76 = (2u ^ 1u); - int2 unnamed_77 = (int2(2.xx) ^ int2(1.xx)); - uint3 unnamed_78 = (uint3(2u.xxx) ^ uint3(1u.xxx)); - int unnamed_79 = (2 << 1u); - uint unnamed_80 = (2u << 1u); - int2 unnamed_81 = (int2(2.xx) << uint2(1u.xx)); - uint3 unnamed_82 = (uint3(2u.xxx) << uint3(1u.xxx)); - int unnamed_83 = (2 >> 1u); - uint unnamed_84 = (2u >> 1u); - int2 unnamed_85 = (int2(2.xx) >> uint2(1u.xx)); - uint3 unnamed_86 = (uint3(2u.xxx) >> uint3(1u.xxx)); + int unnamed_66 = ~1; + uint unnamed_67 = ~1u; + int2 unnamed_68 = ~int2(1.xx); + uint3 unnamed_69 = ~uint3(1u.xxx); + int unnamed_70 = (2 | 1); + uint unnamed_71 = (2u | 1u); + int2 unnamed_72 = (int2(2.xx) | int2(1.xx)); + uint3 unnamed_73 = (uint3(2u.xxx) | uint3(1u.xxx)); + int unnamed_74 = (2 & 1); + uint unnamed_75 = (2u & 1u); + int2 unnamed_76 = (int2(2.xx) & int2(1.xx)); + uint3 unnamed_77 = (uint3(2u.xxx) & uint3(1u.xxx)); + int unnamed_78 = (2 ^ 1); + uint unnamed_79 = (2u ^ 1u); + int2 unnamed_80 = (int2(2.xx) ^ int2(1.xx)); + uint3 unnamed_81 = (uint3(2u.xxx) ^ uint3(1u.xxx)); + int unnamed_82 = (2 << 1u); + uint unnamed_83 = (2u << 1u); + int2 unnamed_84 = (int2(2.xx) << uint2(1u.xx)); + uint3 unnamed_85 = (uint3(2u.xxx) << uint3(1u.xxx)); + int unnamed_86 = (2 >> 1u); + uint unnamed_87 = (2u >> 1u); + int2 unnamed_88 = (int2(2.xx) >> uint2(1u.xx)); + uint3 unnamed_89 = (uint3(2u.xxx) >> uint3(1u.xxx)); } void comparison() { - bool unnamed_87 = (2 == 1); - bool unnamed_88 = (2u == 1u); - bool unnamed_89 = (2.0 == 1.0); - bool2 unnamed_90 = (int2(2.xx) == int2(1.xx)); - bool3 unnamed_91 = (uint3(2u.xxx) == uint3(1u.xxx)); - bool4 unnamed_92 = (float4(2.0.xxxx) == float4(1.0.xxxx)); - bool unnamed_93 = (2 != 1); - bool unnamed_94 = (2u != 1u); - bool unnamed_95 = (2.0 != 1.0); - bool2 unnamed_96 = (int2(2.xx) != int2(1.xx)); - bool3 unnamed_97 = (uint3(2u.xxx) != uint3(1u.xxx)); - bool4 unnamed_98 = (float4(2.0.xxxx) != float4(1.0.xxxx)); - bool unnamed_99 = (2 < 1); - bool unnamed_100 = (2u < 1u); - bool unnamed_101 = (2.0 < 1.0); - bool2 unnamed_102 = (int2(2.xx) < int2(1.xx)); - bool3 unnamed_103 = (uint3(2u.xxx) < uint3(1u.xxx)); - bool4 unnamed_104 = (float4(2.0.xxxx) < float4(1.0.xxxx)); - bool unnamed_105 = (2 <= 1); - bool unnamed_106 = (2u <= 1u); - bool unnamed_107 = (2.0 <= 1.0); - bool2 unnamed_108 = (int2(2.xx) <= int2(1.xx)); - bool3 unnamed_109 = (uint3(2u.xxx) <= uint3(1u.xxx)); - bool4 unnamed_110 = (float4(2.0.xxxx) <= float4(1.0.xxxx)); - bool unnamed_111 = (2 > 1); - bool unnamed_112 = (2u > 1u); - bool unnamed_113 = (2.0 > 1.0); - bool2 unnamed_114 = (int2(2.xx) > int2(1.xx)); - bool3 unnamed_115 = (uint3(2u.xxx) > uint3(1u.xxx)); - bool4 unnamed_116 = (float4(2.0.xxxx) > float4(1.0.xxxx)); - bool unnamed_117 = (2 >= 1); - bool unnamed_118 = (2u >= 1u); - bool unnamed_119 = (2.0 >= 1.0); - bool2 unnamed_120 = (int2(2.xx) >= int2(1.xx)); - bool3 unnamed_121 = (uint3(2u.xxx) >= uint3(1u.xxx)); - bool4 unnamed_122 = (float4(2.0.xxxx) >= float4(1.0.xxxx)); + bool unnamed_90 = (2 == 1); + bool unnamed_91 = (2u == 1u); + bool unnamed_92 = (2.0 == 1.0); + bool2 unnamed_93 = (int2(2.xx) == int2(1.xx)); + bool3 unnamed_94 = (uint3(2u.xxx) == uint3(1u.xxx)); + bool4 unnamed_95 = (float4(2.0.xxxx) == float4(1.0.xxxx)); + bool unnamed_96 = (2 != 1); + bool unnamed_97 = (2u != 1u); + bool unnamed_98 = (2.0 != 1.0); + bool2 unnamed_99 = (int2(2.xx) != int2(1.xx)); + bool3 unnamed_100 = (uint3(2u.xxx) != uint3(1u.xxx)); + bool4 unnamed_101 = (float4(2.0.xxxx) != float4(1.0.xxxx)); + bool unnamed_102 = (2 < 1); + bool unnamed_103 = (2u < 1u); + bool unnamed_104 = (2.0 < 1.0); + bool2 unnamed_105 = (int2(2.xx) < int2(1.xx)); + bool3 unnamed_106 = (uint3(2u.xxx) < uint3(1u.xxx)); + bool4 unnamed_107 = (float4(2.0.xxxx) < float4(1.0.xxxx)); + bool unnamed_108 = (2 <= 1); + bool unnamed_109 = (2u <= 1u); + bool unnamed_110 = (2.0 <= 1.0); + bool2 unnamed_111 = (int2(2.xx) <= int2(1.xx)); + bool3 unnamed_112 = (uint3(2u.xxx) <= uint3(1u.xxx)); + bool4 unnamed_113 = (float4(2.0.xxxx) <= float4(1.0.xxxx)); + bool unnamed_114 = (2 > 1); + bool unnamed_115 = (2u > 1u); + bool unnamed_116 = (2.0 > 1.0); + bool2 unnamed_117 = (int2(2.xx) > int2(1.xx)); + bool3 unnamed_118 = (uint3(2u.xxx) > uint3(1u.xxx)); + bool4 unnamed_119 = (float4(2.0.xxxx) > float4(1.0.xxxx)); + bool unnamed_120 = (2 >= 1); + bool unnamed_121 = (2u >= 1u); + bool unnamed_122 = (2.0 >= 1.0); + bool2 unnamed_123 = (int2(2.xx) >= int2(1.xx)); + bool3 unnamed_124 = (uint3(2u.xxx) >= uint3(1u.xxx)); + bool4 unnamed_125 = (float4(2.0.xxxx) >= float4(1.0.xxxx)); } void assignment() diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index e71b196d9..87a10ee44 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -83,129 +83,132 @@ float constructors( void logical( ) { bool unnamed_11 = !true; - bool unnamed_12 = true || false; - bool unnamed_13 = true && false; - bool unnamed_14 = true | false; - metal::bool3 unnamed_15 = metal::bool3(true) | metal::bool3(false); - bool unnamed_16 = true & false; - metal::bool4 unnamed_17 = metal::bool4(true) & metal::bool4(false); + metal::bool2 unnamed_12 = !metal::bool2(true); + bool unnamed_13 = true || false; + bool unnamed_14 = true && false; + bool unnamed_15 = true | false; + metal::bool3 unnamed_16 = metal::bool3(true) | metal::bool3(false); + bool unnamed_17 = true & false; + metal::bool4 unnamed_18 = metal::bool4(true) & metal::bool4(false); } void arithmetic( ) { - metal::int2 unnamed_18 = -metal::int2(1); - metal::float2 unnamed_19 = -metal::float2(1.0); - int unnamed_20 = 2 + 1; - uint unnamed_21 = 2u + 1u; - float unnamed_22 = 2.0 + 1.0; - metal::int2 unnamed_23 = metal::int2(2) + metal::int2(1); - metal::uint3 unnamed_24 = metal::uint3(2u) + metal::uint3(1u); - metal::float4 unnamed_25 = metal::float4(2.0) + metal::float4(1.0); - int unnamed_26 = 2 - 1; - uint unnamed_27 = 2u - 1u; - float unnamed_28 = 2.0 - 1.0; - metal::int2 unnamed_29 = metal::int2(2) - metal::int2(1); - metal::uint3 unnamed_30 = metal::uint3(2u) - metal::uint3(1u); - metal::float4 unnamed_31 = metal::float4(2.0) - metal::float4(1.0); - int unnamed_32 = 2 * 1; - uint unnamed_33 = 2u * 1u; - float unnamed_34 = 2.0 * 1.0; - metal::int2 unnamed_35 = metal::int2(2) * metal::int2(1); - metal::uint3 unnamed_36 = metal::uint3(2u) * metal::uint3(1u); - metal::float4 unnamed_37 = metal::float4(2.0) * metal::float4(1.0); - int unnamed_38 = 2 / 1; - uint unnamed_39 = 2u / 1u; - float unnamed_40 = 2.0 / 1.0; - metal::int2 unnamed_41 = metal::int2(2) / metal::int2(1); - metal::uint3 unnamed_42 = metal::uint3(2u) / metal::uint3(1u); - metal::float4 unnamed_43 = metal::float4(2.0) / metal::float4(1.0); - int unnamed_44 = 2 % 1; - uint unnamed_45 = 2u % 1u; - float unnamed_46 = metal::fmod(2.0, 1.0); - metal::int2 unnamed_47 = metal::int2(2) % metal::int2(1); - metal::uint3 unnamed_48 = metal::uint3(2u) % metal::uint3(1u); - metal::float4 unnamed_49 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); - metal::int2 unnamed_50 = metal::int2(2) + metal::int2(1); + metal::int2 unnamed_19 = -metal::int2(1); + metal::float2 unnamed_20 = -metal::float2(1.0); + int unnamed_21 = 2 + 1; + uint unnamed_22 = 2u + 1u; + float unnamed_23 = 2.0 + 1.0; + metal::int2 unnamed_24 = metal::int2(2) + metal::int2(1); + metal::uint3 unnamed_25 = metal::uint3(2u) + metal::uint3(1u); + metal::float4 unnamed_26 = metal::float4(2.0) + metal::float4(1.0); + int unnamed_27 = 2 - 1; + uint unnamed_28 = 2u - 1u; + float unnamed_29 = 2.0 - 1.0; + metal::int2 unnamed_30 = metal::int2(2) - metal::int2(1); + metal::uint3 unnamed_31 = metal::uint3(2u) - metal::uint3(1u); + metal::float4 unnamed_32 = metal::float4(2.0) - metal::float4(1.0); + int unnamed_33 = 2 * 1; + uint unnamed_34 = 2u * 1u; + float unnamed_35 = 2.0 * 1.0; + metal::int2 unnamed_36 = metal::int2(2) * metal::int2(1); + metal::uint3 unnamed_37 = metal::uint3(2u) * metal::uint3(1u); + metal::float4 unnamed_38 = metal::float4(2.0) * metal::float4(1.0); + int unnamed_39 = 2 / 1; + uint unnamed_40 = 2u / 1u; + float unnamed_41 = 2.0 / 1.0; + metal::int2 unnamed_42 = metal::int2(2) / metal::int2(1); + metal::uint3 unnamed_43 = metal::uint3(2u) / metal::uint3(1u); + metal::float4 unnamed_44 = metal::float4(2.0) / metal::float4(1.0); + int unnamed_45 = 2 % 1; + uint unnamed_46 = 2u % 1u; + float unnamed_47 = metal::fmod(2.0, 1.0); + metal::int2 unnamed_48 = metal::int2(2) % metal::int2(1); + metal::uint3 unnamed_49 = metal::uint3(2u) % metal::uint3(1u); + metal::float4 unnamed_50 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); metal::int2 unnamed_51 = metal::int2(2) + metal::int2(1); - metal::int2 unnamed_52 = metal::int2(2) - metal::int2(1); + metal::int2 unnamed_52 = metal::int2(2) + metal::int2(1); metal::int2 unnamed_53 = metal::int2(2) - metal::int2(1); - metal::int2 unnamed_54 = metal::int2(2) * 1; - metal::int2 unnamed_55 = 2 * metal::int2(1); - metal::int2 unnamed_56 = metal::int2(2) / metal::int2(1); + metal::int2 unnamed_54 = metal::int2(2) - metal::int2(1); + metal::int2 unnamed_55 = metal::int2(2) * 1; + metal::int2 unnamed_56 = 2 * metal::int2(1); metal::int2 unnamed_57 = metal::int2(2) / metal::int2(1); - metal::int2 unnamed_58 = metal::int2(2) % metal::int2(1); + metal::int2 unnamed_58 = metal::int2(2) / metal::int2(1); metal::int2 unnamed_59 = metal::int2(2) % metal::int2(1); - metal::float3x3 unnamed_60 = const_type_14_ * 1.0; - metal::float3x3 unnamed_61 = 2.0 * const_type_14_; - metal::float3 unnamed_62 = const_type_15_ * metal::float4(1.0); - metal::float4 unnamed_63 = metal::float3(2.0) * const_type_15_; - metal::float3x3 unnamed_64 = const_type_15_ * const_type_16_; + metal::int2 unnamed_60 = metal::int2(2) % metal::int2(1); + metal::float3x3 unnamed_61 = const_type_14_ * 1.0; + metal::float3x3 unnamed_62 = 2.0 * const_type_14_; + metal::float3 unnamed_63 = const_type_15_ * metal::float4(1.0); + metal::float4 unnamed_64 = metal::float3(2.0) * const_type_15_; + metal::float3x3 unnamed_65 = const_type_15_ * const_type_16_; } void bit( ) { - int unnamed_65 = ~1; - uint unnamed_66 = ~1u; - int unnamed_67 = 2 | 1; - uint unnamed_68 = 2u | 1u; - metal::int2 unnamed_69 = metal::int2(2) | metal::int2(1); - metal::uint3 unnamed_70 = metal::uint3(2u) | metal::uint3(1u); - int unnamed_71 = 2 & 1; - uint unnamed_72 = 2u & 1u; - metal::int2 unnamed_73 = metal::int2(2) & metal::int2(1); - metal::uint3 unnamed_74 = metal::uint3(2u) & metal::uint3(1u); - int unnamed_75 = 2 ^ 1; - uint unnamed_76 = 2u ^ 1u; - metal::int2 unnamed_77 = metal::int2(2) ^ metal::int2(1); - metal::uint3 unnamed_78 = metal::uint3(2u) ^ metal::uint3(1u); - int unnamed_79 = 2 << 1u; - uint unnamed_80 = 2u << 1u; - metal::int2 unnamed_81 = metal::int2(2) << metal::uint2(1u); - metal::uint3 unnamed_82 = metal::uint3(2u) << metal::uint3(1u); - int unnamed_83 = 2 >> 1u; - uint unnamed_84 = 2u >> 1u; - metal::int2 unnamed_85 = metal::int2(2) >> metal::uint2(1u); - metal::uint3 unnamed_86 = metal::uint3(2u) >> metal::uint3(1u); + int unnamed_66 = ~1; + uint unnamed_67 = ~1u; + metal::int2 unnamed_68 = ~metal::int2(1); + metal::uint3 unnamed_69 = ~metal::uint3(1u); + int unnamed_70 = 2 | 1; + uint unnamed_71 = 2u | 1u; + metal::int2 unnamed_72 = metal::int2(2) | metal::int2(1); + metal::uint3 unnamed_73 = metal::uint3(2u) | metal::uint3(1u); + int unnamed_74 = 2 & 1; + uint unnamed_75 = 2u & 1u; + metal::int2 unnamed_76 = metal::int2(2) & metal::int2(1); + metal::uint3 unnamed_77 = metal::uint3(2u) & metal::uint3(1u); + int unnamed_78 = 2 ^ 1; + uint unnamed_79 = 2u ^ 1u; + metal::int2 unnamed_80 = metal::int2(2) ^ metal::int2(1); + metal::uint3 unnamed_81 = metal::uint3(2u) ^ metal::uint3(1u); + int unnamed_82 = 2 << 1u; + uint unnamed_83 = 2u << 1u; + metal::int2 unnamed_84 = metal::int2(2) << metal::uint2(1u); + metal::uint3 unnamed_85 = metal::uint3(2u) << metal::uint3(1u); + int unnamed_86 = 2 >> 1u; + uint unnamed_87 = 2u >> 1u; + metal::int2 unnamed_88 = metal::int2(2) >> metal::uint2(1u); + metal::uint3 unnamed_89 = metal::uint3(2u) >> metal::uint3(1u); } void comparison( ) { - bool unnamed_87 = 2 == 1; - bool unnamed_88 = 2u == 1u; - bool unnamed_89 = 2.0 == 1.0; - metal::bool2 unnamed_90 = metal::int2(2) == metal::int2(1); - metal::bool3 unnamed_91 = metal::uint3(2u) == metal::uint3(1u); - metal::bool4 unnamed_92 = metal::float4(2.0) == metal::float4(1.0); - bool unnamed_93 = 2 != 1; - bool unnamed_94 = 2u != 1u; - bool unnamed_95 = 2.0 != 1.0; - metal::bool2 unnamed_96 = metal::int2(2) != metal::int2(1); - metal::bool3 unnamed_97 = metal::uint3(2u) != metal::uint3(1u); - metal::bool4 unnamed_98 = metal::float4(2.0) != metal::float4(1.0); - bool unnamed_99 = 2 < 1; - bool unnamed_100 = 2u < 1u; - bool unnamed_101 = 2.0 < 1.0; - metal::bool2 unnamed_102 = metal::int2(2) < metal::int2(1); - metal::bool3 unnamed_103 = metal::uint3(2u) < metal::uint3(1u); - metal::bool4 unnamed_104 = metal::float4(2.0) < metal::float4(1.0); - bool unnamed_105 = 2 <= 1; - bool unnamed_106 = 2u <= 1u; - bool unnamed_107 = 2.0 <= 1.0; - metal::bool2 unnamed_108 = metal::int2(2) <= metal::int2(1); - metal::bool3 unnamed_109 = metal::uint3(2u) <= metal::uint3(1u); - metal::bool4 unnamed_110 = metal::float4(2.0) <= metal::float4(1.0); - bool unnamed_111 = 2 > 1; - bool unnamed_112 = 2u > 1u; - bool unnamed_113 = 2.0 > 1.0; - metal::bool2 unnamed_114 = metal::int2(2) > metal::int2(1); - metal::bool3 unnamed_115 = metal::uint3(2u) > metal::uint3(1u); - metal::bool4 unnamed_116 = metal::float4(2.0) > metal::float4(1.0); - bool unnamed_117 = 2 >= 1; - bool unnamed_118 = 2u >= 1u; - bool unnamed_119 = 2.0 >= 1.0; - metal::bool2 unnamed_120 = metal::int2(2) >= metal::int2(1); - metal::bool3 unnamed_121 = metal::uint3(2u) >= metal::uint3(1u); - metal::bool4 unnamed_122 = metal::float4(2.0) >= metal::float4(1.0); + bool unnamed_90 = 2 == 1; + bool unnamed_91 = 2u == 1u; + bool unnamed_92 = 2.0 == 1.0; + metal::bool2 unnamed_93 = metal::int2(2) == metal::int2(1); + metal::bool3 unnamed_94 = metal::uint3(2u) == metal::uint3(1u); + metal::bool4 unnamed_95 = metal::float4(2.0) == metal::float4(1.0); + bool unnamed_96 = 2 != 1; + bool unnamed_97 = 2u != 1u; + bool unnamed_98 = 2.0 != 1.0; + metal::bool2 unnamed_99 = metal::int2(2) != metal::int2(1); + metal::bool3 unnamed_100 = metal::uint3(2u) != metal::uint3(1u); + metal::bool4 unnamed_101 = metal::float4(2.0) != metal::float4(1.0); + bool unnamed_102 = 2 < 1; + bool unnamed_103 = 2u < 1u; + bool unnamed_104 = 2.0 < 1.0; + metal::bool2 unnamed_105 = metal::int2(2) < metal::int2(1); + metal::bool3 unnamed_106 = metal::uint3(2u) < metal::uint3(1u); + metal::bool4 unnamed_107 = metal::float4(2.0) < metal::float4(1.0); + bool unnamed_108 = 2 <= 1; + bool unnamed_109 = 2u <= 1u; + bool unnamed_110 = 2.0 <= 1.0; + metal::bool2 unnamed_111 = metal::int2(2) <= metal::int2(1); + metal::bool3 unnamed_112 = metal::uint3(2u) <= metal::uint3(1u); + metal::bool4 unnamed_113 = metal::float4(2.0) <= metal::float4(1.0); + bool unnamed_114 = 2 > 1; + bool unnamed_115 = 2u > 1u; + bool unnamed_116 = 2.0 > 1.0; + metal::bool2 unnamed_117 = metal::int2(2) > metal::int2(1); + metal::bool3 unnamed_118 = metal::uint3(2u) > metal::uint3(1u); + metal::bool4 unnamed_119 = metal::float4(2.0) > metal::float4(1.0); + bool unnamed_120 = 2 >= 1; + bool unnamed_121 = 2u >= 1u; + bool unnamed_122 = 2.0 >= 1.0; + metal::bool2 unnamed_123 = metal::int2(2) >= metal::int2(1); + metal::bool3 unnamed_124 = metal::uint3(2u) >= metal::uint3(1u); + metal::bool4 unnamed_125 = metal::float4(2.0) >= metal::float4(1.0); } void assignment( diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 1c95c2711..d3d9919ce 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 434 +; Bound: 440 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %422 "main" -OpExecutionMode %422 LocalSize 1 1 1 +OpEntryPoint GLCompute %428 "main" +OpExecutionMode %428 LocalSize 1 1 1 OpMemberDecorate %31 0 Offset 0 OpMemberDecorate %31 1 Offset 16 OpDecorate %36 ArrayStride 32 @@ -80,9 +80,9 @@ OpDecorate %37 ArrayStride 4 %147 = OpTypePointer Function %27 %148 = OpTypePointer Function %4 %153 = OpTypeFunction %2 -%169 = OpTypeVector %8 2 -%180 = OpTypeVector %20 3 -%323 = OpTypeVector %10 2 +%156 = OpTypeVector %10 2 +%172 = OpTypeVector %8 2 +%183 = OpTypeVector %20 3 %56 = OpFunction %27 None %57 %55 = OpLabel OpBranch %58 @@ -185,307 +185,313 @@ OpFunctionEnd OpBranch %154 %154 = OpLabel %155 = OpLogicalNot %10 %9 -%156 = OpLogicalOr %10 %9 %12 -%157 = OpLogicalAnd %10 %9 %12 -%158 = OpLogicalOr %10 %9 %12 -%159 = OpCompositeConstruct %101 %9 %9 %9 -%160 = OpCompositeConstruct %101 %12 %12 %12 -%161 = OpLogicalOr %101 %159 %160 -%162 = OpLogicalAnd %10 %9 %12 -%163 = OpCompositeConstruct %29 %9 %9 %9 %9 -%164 = OpCompositeConstruct %29 %12 %12 %12 %12 -%165 = OpLogicalAnd %29 %163 %164 +%157 = OpCompositeConstruct %156 %9 %9 +%158 = OpLogicalNot %156 %157 +%159 = OpLogicalOr %10 %9 %12 +%160 = OpLogicalAnd %10 %9 %12 +%161 = OpLogicalOr %10 %9 %12 +%162 = OpCompositeConstruct %101 %9 %9 %9 +%163 = OpCompositeConstruct %101 %12 %12 %12 +%164 = OpLogicalOr %101 %162 %163 +%165 = OpLogicalAnd %10 %9 %12 +%166 = OpCompositeConstruct %29 %9 %9 %9 %9 +%167 = OpCompositeConstruct %29 %12 %12 %12 %12 +%168 = OpLogicalAnd %29 %166 %167 OpReturn OpFunctionEnd -%167 = OpFunction %2 None %153 -%166 = OpLabel -OpBranch %168 -%168 = OpLabel -%170 = OpCompositeConstruct %169 %7 %7 -%171 = OpSNegate %169 %170 -%172 = OpCompositeConstruct %32 %3 %3 -%173 = OpFNegate %32 %172 -%174 = OpIAdd %8 %18 %7 -%175 = OpIAdd %20 %25 %26 -%176 = OpFAdd %4 %14 %3 -%177 = OpCompositeConstruct %169 %18 %18 -%178 = OpCompositeConstruct %169 %7 %7 -%179 = OpIAdd %169 %177 %178 -%181 = OpCompositeConstruct %180 %25 %25 %25 -%182 = OpCompositeConstruct %180 %26 %26 %26 -%183 = OpIAdd %180 %181 %182 -%184 = OpCompositeConstruct %27 %14 %14 %14 %14 -%185 = OpCompositeConstruct %27 %3 %3 %3 %3 -%186 = OpFAdd %27 %184 %185 -%187 = OpISub %8 %18 %7 -%188 = OpISub %20 %25 %26 -%189 = OpFSub %4 %14 %3 -%190 = OpCompositeConstruct %169 %18 %18 -%191 = OpCompositeConstruct %169 %7 %7 -%192 = OpISub %169 %190 %191 -%193 = OpCompositeConstruct %180 %25 %25 %25 -%194 = OpCompositeConstruct %180 %26 %26 %26 -%195 = OpISub %180 %193 %194 -%196 = OpCompositeConstruct %27 %14 %14 %14 %14 -%197 = OpCompositeConstruct %27 %3 %3 %3 %3 -%198 = OpFSub %27 %196 %197 -%199 = OpIMul %8 %18 %7 -%200 = OpIMul %20 %25 %26 -%201 = OpFMul %4 %14 %3 -%202 = OpCompositeConstruct %169 %18 %18 -%203 = OpCompositeConstruct %169 %7 %7 -%204 = OpIMul %169 %202 %203 -%205 = OpCompositeConstruct %180 %25 %25 %25 -%206 = OpCompositeConstruct %180 %26 %26 %26 -%207 = OpIMul %180 %205 %206 -%208 = OpCompositeConstruct %27 %14 %14 %14 %14 -%209 = OpCompositeConstruct %27 %3 %3 %3 %3 -%210 = OpFMul %27 %208 %209 -%211 = OpSDiv %8 %18 %7 -%212 = OpUDiv %20 %25 %26 -%213 = OpFDiv %4 %14 %3 -%214 = OpCompositeConstruct %169 %18 %18 -%215 = OpCompositeConstruct %169 %7 %7 -%216 = OpSDiv %169 %214 %215 -%217 = OpCompositeConstruct %180 %25 %25 %25 -%218 = OpCompositeConstruct %180 %26 %26 %26 -%219 = OpUDiv %180 %217 %218 -%220 = OpCompositeConstruct %27 %14 %14 %14 %14 -%221 = OpCompositeConstruct %27 %3 %3 %3 %3 -%222 = OpFDiv %27 %220 %221 -%223 = OpSMod %8 %18 %7 -%224 = OpUMod %20 %25 %26 -%225 = OpFRem %4 %14 %3 -%226 = OpCompositeConstruct %169 %18 %18 -%227 = OpCompositeConstruct %169 %7 %7 -%228 = OpSMod %169 %226 %227 -%229 = OpCompositeConstruct %180 %25 %25 %25 -%230 = OpCompositeConstruct %180 %26 %26 %26 -%231 = OpUMod %180 %229 %230 -%232 = OpCompositeConstruct %27 %14 %14 %14 %14 -%233 = OpCompositeConstruct %27 %3 %3 %3 %3 -%234 = OpFRem %27 %232 %233 -%235 = OpCompositeConstruct %169 %18 %18 -%236 = OpCompositeConstruct %169 %7 %7 -%237 = OpIAdd %169 %235 %236 -%238 = OpCompositeConstruct %169 %7 %7 -%239 = OpCompositeConstruct %169 %18 %18 -%240 = OpIAdd %169 %239 %238 -%241 = OpCompositeConstruct %169 %18 %18 -%242 = OpCompositeConstruct %169 %7 %7 -%243 = OpISub %169 %241 %242 -%244 = OpCompositeConstruct %169 %7 %7 -%245 = OpCompositeConstruct %169 %18 %18 -%246 = OpISub %169 %245 %244 -%247 = OpCompositeConstruct %169 %18 %18 -%248 = OpVectorTimesScalar %169 %247 %7 -%249 = OpCompositeConstruct %169 %7 %7 -%250 = OpVectorTimesScalar %169 %249 %18 -%251 = OpCompositeConstruct %169 %18 %18 -%252 = OpCompositeConstruct %169 %7 %7 -%253 = OpSDiv %169 %251 %252 -%254 = OpCompositeConstruct %169 %7 %7 -%255 = OpCompositeConstruct %169 %18 %18 -%256 = OpSDiv %169 %255 %254 -%257 = OpCompositeConstruct %169 %18 %18 -%258 = OpCompositeConstruct %169 %7 %7 -%259 = OpSMod %169 %257 %258 -%260 = OpCompositeConstruct %169 %7 %7 -%261 = OpCompositeConstruct %169 %18 %18 -%262 = OpSMod %169 %261 %260 -%263 = OpMatrixTimesScalar %38 %52 %3 -%264 = OpMatrixTimesScalar %38 %52 %14 -%265 = OpCompositeConstruct %27 %3 %3 %3 %3 -%266 = OpMatrixTimesVector %30 %53 %265 -%267 = OpCompositeConstruct %30 %14 %14 %14 -%268 = OpVectorTimesMatrix %27 %267 %53 -%269 = OpMatrixTimesMatrix %38 %53 %54 +%170 = OpFunction %2 None %153 +%169 = OpLabel +OpBranch %171 +%171 = OpLabel +%173 = OpCompositeConstruct %172 %7 %7 +%174 = OpSNegate %172 %173 +%175 = OpCompositeConstruct %32 %3 %3 +%176 = OpFNegate %32 %175 +%177 = OpIAdd %8 %18 %7 +%178 = OpIAdd %20 %25 %26 +%179 = OpFAdd %4 %14 %3 +%180 = OpCompositeConstruct %172 %18 %18 +%181 = OpCompositeConstruct %172 %7 %7 +%182 = OpIAdd %172 %180 %181 +%184 = OpCompositeConstruct %183 %25 %25 %25 +%185 = OpCompositeConstruct %183 %26 %26 %26 +%186 = OpIAdd %183 %184 %185 +%187 = OpCompositeConstruct %27 %14 %14 %14 %14 +%188 = OpCompositeConstruct %27 %3 %3 %3 %3 +%189 = OpFAdd %27 %187 %188 +%190 = OpISub %8 %18 %7 +%191 = OpISub %20 %25 %26 +%192 = OpFSub %4 %14 %3 +%193 = OpCompositeConstruct %172 %18 %18 +%194 = OpCompositeConstruct %172 %7 %7 +%195 = OpISub %172 %193 %194 +%196 = OpCompositeConstruct %183 %25 %25 %25 +%197 = OpCompositeConstruct %183 %26 %26 %26 +%198 = OpISub %183 %196 %197 +%199 = OpCompositeConstruct %27 %14 %14 %14 %14 +%200 = OpCompositeConstruct %27 %3 %3 %3 %3 +%201 = OpFSub %27 %199 %200 +%202 = OpIMul %8 %18 %7 +%203 = OpIMul %20 %25 %26 +%204 = OpFMul %4 %14 %3 +%205 = OpCompositeConstruct %172 %18 %18 +%206 = OpCompositeConstruct %172 %7 %7 +%207 = OpIMul %172 %205 %206 +%208 = OpCompositeConstruct %183 %25 %25 %25 +%209 = OpCompositeConstruct %183 %26 %26 %26 +%210 = OpIMul %183 %208 %209 +%211 = OpCompositeConstruct %27 %14 %14 %14 %14 +%212 = OpCompositeConstruct %27 %3 %3 %3 %3 +%213 = OpFMul %27 %211 %212 +%214 = OpSDiv %8 %18 %7 +%215 = OpUDiv %20 %25 %26 +%216 = OpFDiv %4 %14 %3 +%217 = OpCompositeConstruct %172 %18 %18 +%218 = OpCompositeConstruct %172 %7 %7 +%219 = OpSDiv %172 %217 %218 +%220 = OpCompositeConstruct %183 %25 %25 %25 +%221 = OpCompositeConstruct %183 %26 %26 %26 +%222 = OpUDiv %183 %220 %221 +%223 = OpCompositeConstruct %27 %14 %14 %14 %14 +%224 = OpCompositeConstruct %27 %3 %3 %3 %3 +%225 = OpFDiv %27 %223 %224 +%226 = OpSMod %8 %18 %7 +%227 = OpUMod %20 %25 %26 +%228 = OpFRem %4 %14 %3 +%229 = OpCompositeConstruct %172 %18 %18 +%230 = OpCompositeConstruct %172 %7 %7 +%231 = OpSMod %172 %229 %230 +%232 = OpCompositeConstruct %183 %25 %25 %25 +%233 = OpCompositeConstruct %183 %26 %26 %26 +%234 = OpUMod %183 %232 %233 +%235 = OpCompositeConstruct %27 %14 %14 %14 %14 +%236 = OpCompositeConstruct %27 %3 %3 %3 %3 +%237 = OpFRem %27 %235 %236 +%238 = OpCompositeConstruct %172 %18 %18 +%239 = OpCompositeConstruct %172 %7 %7 +%240 = OpIAdd %172 %238 %239 +%241 = OpCompositeConstruct %172 %7 %7 +%242 = OpCompositeConstruct %172 %18 %18 +%243 = OpIAdd %172 %242 %241 +%244 = OpCompositeConstruct %172 %18 %18 +%245 = OpCompositeConstruct %172 %7 %7 +%246 = OpISub %172 %244 %245 +%247 = OpCompositeConstruct %172 %7 %7 +%248 = OpCompositeConstruct %172 %18 %18 +%249 = OpISub %172 %248 %247 +%250 = OpCompositeConstruct %172 %18 %18 +%251 = OpVectorTimesScalar %172 %250 %7 +%252 = OpCompositeConstruct %172 %7 %7 +%253 = OpVectorTimesScalar %172 %252 %18 +%254 = OpCompositeConstruct %172 %18 %18 +%255 = OpCompositeConstruct %172 %7 %7 +%256 = OpSDiv %172 %254 %255 +%257 = OpCompositeConstruct %172 %7 %7 +%258 = OpCompositeConstruct %172 %18 %18 +%259 = OpSDiv %172 %258 %257 +%260 = OpCompositeConstruct %172 %18 %18 +%261 = OpCompositeConstruct %172 %7 %7 +%262 = OpSMod %172 %260 %261 +%263 = OpCompositeConstruct %172 %7 %7 +%264 = OpCompositeConstruct %172 %18 %18 +%265 = OpSMod %172 %264 %263 +%266 = OpMatrixTimesScalar %38 %52 %3 +%267 = OpMatrixTimesScalar %38 %52 %14 +%268 = OpCompositeConstruct %27 %3 %3 %3 %3 +%269 = OpMatrixTimesVector %30 %53 %268 +%270 = OpCompositeConstruct %30 %14 %14 %14 +%271 = OpVectorTimesMatrix %27 %270 %53 +%272 = OpMatrixTimesMatrix %38 %53 %54 OpReturn OpFunctionEnd -%271 = OpFunction %2 None %153 -%270 = OpLabel -OpBranch %272 -%272 = OpLabel -%273 = OpNot %8 %7 -%274 = OpNot %20 %26 -%275 = OpBitwiseOr %8 %18 %7 -%276 = OpBitwiseOr %20 %25 %26 -%277 = OpCompositeConstruct %169 %18 %18 -%278 = OpCompositeConstruct %169 %7 %7 -%279 = OpBitwiseOr %169 %277 %278 -%280 = OpCompositeConstruct %180 %25 %25 %25 -%281 = OpCompositeConstruct %180 %26 %26 %26 -%282 = OpBitwiseOr %180 %280 %281 -%283 = OpBitwiseAnd %8 %18 %7 -%284 = OpBitwiseAnd %20 %25 %26 -%285 = OpCompositeConstruct %169 %18 %18 -%286 = OpCompositeConstruct %169 %7 %7 -%287 = OpBitwiseAnd %169 %285 %286 -%288 = OpCompositeConstruct %180 %25 %25 %25 -%289 = OpCompositeConstruct %180 %26 %26 %26 -%290 = OpBitwiseAnd %180 %288 %289 -%291 = OpBitwiseXor %8 %18 %7 -%292 = OpBitwiseXor %20 %25 %26 -%293 = OpCompositeConstruct %169 %18 %18 -%294 = OpCompositeConstruct %169 %7 %7 -%295 = OpBitwiseXor %169 %293 %294 -%296 = OpCompositeConstruct %180 %25 %25 %25 -%297 = OpCompositeConstruct %180 %26 %26 %26 -%298 = OpBitwiseXor %180 %296 %297 -%299 = OpShiftLeftLogical %8 %18 %26 -%300 = OpShiftLeftLogical %20 %25 %26 -%301 = OpCompositeConstruct %169 %18 %18 -%302 = OpCompositeConstruct %35 %26 %26 -%303 = OpShiftLeftLogical %169 %301 %302 -%304 = OpCompositeConstruct %180 %25 %25 %25 -%305 = OpCompositeConstruct %180 %26 %26 %26 -%306 = OpShiftLeftLogical %180 %304 %305 -%307 = OpShiftRightArithmetic %8 %18 %26 -%308 = OpShiftRightLogical %20 %25 %26 -%309 = OpCompositeConstruct %169 %18 %18 -%310 = OpCompositeConstruct %35 %26 %26 -%311 = OpShiftRightArithmetic %169 %309 %310 -%312 = OpCompositeConstruct %180 %25 %25 %25 -%313 = OpCompositeConstruct %180 %26 %26 %26 -%314 = OpShiftRightLogical %180 %312 %313 +%274 = OpFunction %2 None %153 +%273 = OpLabel +OpBranch %275 +%275 = OpLabel +%276 = OpNot %8 %7 +%277 = OpNot %20 %26 +%278 = OpCompositeConstruct %172 %7 %7 +%279 = OpNot %172 %278 +%280 = OpCompositeConstruct %183 %26 %26 %26 +%281 = OpNot %183 %280 +%282 = OpBitwiseOr %8 %18 %7 +%283 = OpBitwiseOr %20 %25 %26 +%284 = OpCompositeConstruct %172 %18 %18 +%285 = OpCompositeConstruct %172 %7 %7 +%286 = OpBitwiseOr %172 %284 %285 +%287 = OpCompositeConstruct %183 %25 %25 %25 +%288 = OpCompositeConstruct %183 %26 %26 %26 +%289 = OpBitwiseOr %183 %287 %288 +%290 = OpBitwiseAnd %8 %18 %7 +%291 = OpBitwiseAnd %20 %25 %26 +%292 = OpCompositeConstruct %172 %18 %18 +%293 = OpCompositeConstruct %172 %7 %7 +%294 = OpBitwiseAnd %172 %292 %293 +%295 = OpCompositeConstruct %183 %25 %25 %25 +%296 = OpCompositeConstruct %183 %26 %26 %26 +%297 = OpBitwiseAnd %183 %295 %296 +%298 = OpBitwiseXor %8 %18 %7 +%299 = OpBitwiseXor %20 %25 %26 +%300 = OpCompositeConstruct %172 %18 %18 +%301 = OpCompositeConstruct %172 %7 %7 +%302 = OpBitwiseXor %172 %300 %301 +%303 = OpCompositeConstruct %183 %25 %25 %25 +%304 = OpCompositeConstruct %183 %26 %26 %26 +%305 = OpBitwiseXor %183 %303 %304 +%306 = OpShiftLeftLogical %8 %18 %26 +%307 = OpShiftLeftLogical %20 %25 %26 +%308 = OpCompositeConstruct %172 %18 %18 +%309 = OpCompositeConstruct %35 %26 %26 +%310 = OpShiftLeftLogical %172 %308 %309 +%311 = OpCompositeConstruct %183 %25 %25 %25 +%312 = OpCompositeConstruct %183 %26 %26 %26 +%313 = OpShiftLeftLogical %183 %311 %312 +%314 = OpShiftRightArithmetic %8 %18 %26 +%315 = OpShiftRightLogical %20 %25 %26 +%316 = OpCompositeConstruct %172 %18 %18 +%317 = OpCompositeConstruct %35 %26 %26 +%318 = OpShiftRightArithmetic %172 %316 %317 +%319 = OpCompositeConstruct %183 %25 %25 %25 +%320 = OpCompositeConstruct %183 %26 %26 %26 +%321 = OpShiftRightLogical %183 %319 %320 OpReturn OpFunctionEnd -%316 = OpFunction %2 None %153 -%315 = OpLabel -OpBranch %317 -%317 = OpLabel -%318 = OpIEqual %10 %18 %7 -%319 = OpIEqual %10 %25 %26 -%320 = OpFOrdEqual %10 %14 %3 -%321 = OpCompositeConstruct %169 %18 %18 -%322 = OpCompositeConstruct %169 %7 %7 -%324 = OpIEqual %323 %321 %322 -%325 = OpCompositeConstruct %180 %25 %25 %25 -%326 = OpCompositeConstruct %180 %26 %26 %26 -%327 = OpIEqual %101 %325 %326 -%328 = OpCompositeConstruct %27 %14 %14 %14 %14 -%329 = OpCompositeConstruct %27 %3 %3 %3 %3 -%330 = OpFOrdEqual %29 %328 %329 -%331 = OpINotEqual %10 %18 %7 -%332 = OpINotEqual %10 %25 %26 -%333 = OpFOrdNotEqual %10 %14 %3 -%334 = OpCompositeConstruct %169 %18 %18 -%335 = OpCompositeConstruct %169 %7 %7 -%336 = OpINotEqual %323 %334 %335 -%337 = OpCompositeConstruct %180 %25 %25 %25 -%338 = OpCompositeConstruct %180 %26 %26 %26 -%339 = OpINotEqual %101 %337 %338 -%340 = OpCompositeConstruct %27 %14 %14 %14 %14 -%341 = OpCompositeConstruct %27 %3 %3 %3 %3 -%342 = OpFOrdNotEqual %29 %340 %341 -%343 = OpSLessThan %10 %18 %7 -%344 = OpULessThan %10 %25 %26 -%345 = OpFOrdLessThan %10 %14 %3 -%346 = OpCompositeConstruct %169 %18 %18 -%347 = OpCompositeConstruct %169 %7 %7 -%348 = OpSLessThan %323 %346 %347 -%349 = OpCompositeConstruct %180 %25 %25 %25 -%350 = OpCompositeConstruct %180 %26 %26 %26 -%351 = OpULessThan %101 %349 %350 -%352 = OpCompositeConstruct %27 %14 %14 %14 %14 -%353 = OpCompositeConstruct %27 %3 %3 %3 %3 -%354 = OpFOrdLessThan %29 %352 %353 -%355 = OpSLessThanEqual %10 %18 %7 -%356 = OpULessThanEqual %10 %25 %26 -%357 = OpFOrdLessThanEqual %10 %14 %3 -%358 = OpCompositeConstruct %169 %18 %18 -%359 = OpCompositeConstruct %169 %7 %7 -%360 = OpSLessThanEqual %323 %358 %359 -%361 = OpCompositeConstruct %180 %25 %25 %25 -%362 = OpCompositeConstruct %180 %26 %26 %26 -%363 = OpULessThanEqual %101 %361 %362 -%364 = OpCompositeConstruct %27 %14 %14 %14 %14 -%365 = OpCompositeConstruct %27 %3 %3 %3 %3 -%366 = OpFOrdLessThanEqual %29 %364 %365 -%367 = OpSGreaterThan %10 %18 %7 -%368 = OpUGreaterThan %10 %25 %26 -%369 = OpFOrdGreaterThan %10 %14 %3 -%370 = OpCompositeConstruct %169 %18 %18 -%371 = OpCompositeConstruct %169 %7 %7 -%372 = OpSGreaterThan %323 %370 %371 -%373 = OpCompositeConstruct %180 %25 %25 %25 -%374 = OpCompositeConstruct %180 %26 %26 %26 -%375 = OpUGreaterThan %101 %373 %374 -%376 = OpCompositeConstruct %27 %14 %14 %14 %14 -%377 = OpCompositeConstruct %27 %3 %3 %3 %3 -%378 = OpFOrdGreaterThan %29 %376 %377 -%379 = OpSGreaterThanEqual %10 %18 %7 -%380 = OpUGreaterThanEqual %10 %25 %26 -%381 = OpFOrdGreaterThanEqual %10 %14 %3 -%382 = OpCompositeConstruct %169 %18 %18 -%383 = OpCompositeConstruct %169 %7 %7 -%384 = OpSGreaterThanEqual %323 %382 %383 -%385 = OpCompositeConstruct %180 %25 %25 %25 -%386 = OpCompositeConstruct %180 %26 %26 %26 -%387 = OpUGreaterThanEqual %101 %385 %386 -%388 = OpCompositeConstruct %27 %14 %14 %14 %14 -%389 = OpCompositeConstruct %27 %3 %3 %3 %3 -%390 = OpFOrdGreaterThanEqual %29 %388 %389 +%323 = OpFunction %2 None %153 +%322 = OpLabel +OpBranch %324 +%324 = OpLabel +%325 = OpIEqual %10 %18 %7 +%326 = OpIEqual %10 %25 %26 +%327 = OpFOrdEqual %10 %14 %3 +%328 = OpCompositeConstruct %172 %18 %18 +%329 = OpCompositeConstruct %172 %7 %7 +%330 = OpIEqual %156 %328 %329 +%331 = OpCompositeConstruct %183 %25 %25 %25 +%332 = OpCompositeConstruct %183 %26 %26 %26 +%333 = OpIEqual %101 %331 %332 +%334 = OpCompositeConstruct %27 %14 %14 %14 %14 +%335 = OpCompositeConstruct %27 %3 %3 %3 %3 +%336 = OpFOrdEqual %29 %334 %335 +%337 = OpINotEqual %10 %18 %7 +%338 = OpINotEqual %10 %25 %26 +%339 = OpFOrdNotEqual %10 %14 %3 +%340 = OpCompositeConstruct %172 %18 %18 +%341 = OpCompositeConstruct %172 %7 %7 +%342 = OpINotEqual %156 %340 %341 +%343 = OpCompositeConstruct %183 %25 %25 %25 +%344 = OpCompositeConstruct %183 %26 %26 %26 +%345 = OpINotEqual %101 %343 %344 +%346 = OpCompositeConstruct %27 %14 %14 %14 %14 +%347 = OpCompositeConstruct %27 %3 %3 %3 %3 +%348 = OpFOrdNotEqual %29 %346 %347 +%349 = OpSLessThan %10 %18 %7 +%350 = OpULessThan %10 %25 %26 +%351 = OpFOrdLessThan %10 %14 %3 +%352 = OpCompositeConstruct %172 %18 %18 +%353 = OpCompositeConstruct %172 %7 %7 +%354 = OpSLessThan %156 %352 %353 +%355 = OpCompositeConstruct %183 %25 %25 %25 +%356 = OpCompositeConstruct %183 %26 %26 %26 +%357 = OpULessThan %101 %355 %356 +%358 = OpCompositeConstruct %27 %14 %14 %14 %14 +%359 = OpCompositeConstruct %27 %3 %3 %3 %3 +%360 = OpFOrdLessThan %29 %358 %359 +%361 = OpSLessThanEqual %10 %18 %7 +%362 = OpULessThanEqual %10 %25 %26 +%363 = OpFOrdLessThanEqual %10 %14 %3 +%364 = OpCompositeConstruct %172 %18 %18 +%365 = OpCompositeConstruct %172 %7 %7 +%366 = OpSLessThanEqual %156 %364 %365 +%367 = OpCompositeConstruct %183 %25 %25 %25 +%368 = OpCompositeConstruct %183 %26 %26 %26 +%369 = OpULessThanEqual %101 %367 %368 +%370 = OpCompositeConstruct %27 %14 %14 %14 %14 +%371 = OpCompositeConstruct %27 %3 %3 %3 %3 +%372 = OpFOrdLessThanEqual %29 %370 %371 +%373 = OpSGreaterThan %10 %18 %7 +%374 = OpUGreaterThan %10 %25 %26 +%375 = OpFOrdGreaterThan %10 %14 %3 +%376 = OpCompositeConstruct %172 %18 %18 +%377 = OpCompositeConstruct %172 %7 %7 +%378 = OpSGreaterThan %156 %376 %377 +%379 = OpCompositeConstruct %183 %25 %25 %25 +%380 = OpCompositeConstruct %183 %26 %26 %26 +%381 = OpUGreaterThan %101 %379 %380 +%382 = OpCompositeConstruct %27 %14 %14 %14 %14 +%383 = OpCompositeConstruct %27 %3 %3 %3 %3 +%384 = OpFOrdGreaterThan %29 %382 %383 +%385 = OpSGreaterThanEqual %10 %18 %7 +%386 = OpUGreaterThanEqual %10 %25 %26 +%387 = OpFOrdGreaterThanEqual %10 %14 %3 +%388 = OpCompositeConstruct %172 %18 %18 +%389 = OpCompositeConstruct %172 %7 %7 +%390 = OpSGreaterThanEqual %156 %388 %389 +%391 = OpCompositeConstruct %183 %25 %25 %25 +%392 = OpCompositeConstruct %183 %26 %26 %26 +%393 = OpUGreaterThanEqual %101 %391 %392 +%394 = OpCompositeConstruct %27 %14 %14 %14 %14 +%395 = OpCompositeConstruct %27 %3 %3 %3 %3 +%396 = OpFOrdGreaterThanEqual %29 %394 %395 OpReturn OpFunctionEnd -%393 = OpFunction %2 None %153 -%392 = OpLabel -%391 = OpVariable %112 Function %7 -OpBranch %394 -%394 = OpLabel -%395 = OpLoad %8 %391 -%396 = OpIAdd %8 %395 %7 -OpStore %391 %396 -%397 = OpLoad %8 %391 -%398 = OpISub %8 %397 %7 -OpStore %391 %398 -%399 = OpLoad %8 %391 -%400 = OpLoad %8 %391 -%401 = OpIMul %8 %399 %400 -OpStore %391 %401 -%402 = OpLoad %8 %391 -%403 = OpLoad %8 %391 -%404 = OpSDiv %8 %402 %403 -OpStore %391 %404 -%405 = OpLoad %8 %391 -%406 = OpSMod %8 %405 %7 -OpStore %391 %406 -%407 = OpLoad %8 %391 -%408 = OpBitwiseAnd %8 %407 %11 -OpStore %391 %408 -%409 = OpLoad %8 %391 -%410 = OpBitwiseOr %8 %409 %11 -OpStore %391 %410 -%411 = OpLoad %8 %391 -%412 = OpBitwiseXor %8 %411 %11 -OpStore %391 %412 -%413 = OpLoad %8 %391 -%414 = OpShiftLeftLogical %8 %413 %25 -OpStore %391 %414 -%415 = OpLoad %8 %391 -%416 = OpShiftRightArithmetic %8 %415 %26 -OpStore %391 %416 -%417 = OpLoad %8 %391 -%418 = OpIAdd %8 %417 %7 -OpStore %391 %418 -%419 = OpLoad %8 %391 -%420 = OpISub %8 %419 %7 -OpStore %391 %420 +%399 = OpFunction %2 None %153 +%398 = OpLabel +%397 = OpVariable %112 Function %7 +OpBranch %400 +%400 = OpLabel +%401 = OpLoad %8 %397 +%402 = OpIAdd %8 %401 %7 +OpStore %397 %402 +%403 = OpLoad %8 %397 +%404 = OpISub %8 %403 %7 +OpStore %397 %404 +%405 = OpLoad %8 %397 +%406 = OpLoad %8 %397 +%407 = OpIMul %8 %405 %406 +OpStore %397 %407 +%408 = OpLoad %8 %397 +%409 = OpLoad %8 %397 +%410 = OpSDiv %8 %408 %409 +OpStore %397 %410 +%411 = OpLoad %8 %397 +%412 = OpSMod %8 %411 %7 +OpStore %397 %412 +%413 = OpLoad %8 %397 +%414 = OpBitwiseAnd %8 %413 %11 +OpStore %397 %414 +%415 = OpLoad %8 %397 +%416 = OpBitwiseOr %8 %415 %11 +OpStore %397 %416 +%417 = OpLoad %8 %397 +%418 = OpBitwiseXor %8 %417 %11 +OpStore %397 %418 +%419 = OpLoad %8 %397 +%420 = OpShiftLeftLogical %8 %419 %25 +OpStore %397 %420 +%421 = OpLoad %8 %397 +%422 = OpShiftRightArithmetic %8 %421 %26 +OpStore %397 %422 +%423 = OpLoad %8 %397 +%424 = OpIAdd %8 %423 %7 +OpStore %397 %424 +%425 = OpLoad %8 %397 +%426 = OpISub %8 %425 %7 +OpStore %397 %426 OpReturn OpFunctionEnd -%422 = OpFunction %2 None %153 -%421 = OpLabel -OpBranch %423 -%423 = OpLabel -%424 = OpFunctionCall %27 %56 -%425 = OpFunctionCall %27 %81 -%426 = OpVectorShuffle %30 %41 %41 0 1 2 -%427 = OpFunctionCall %30 %98 %426 -%428 = OpFunctionCall %4 %129 -%429 = OpFunctionCall %2 %152 -%430 = OpFunctionCall %2 %167 -%431 = OpFunctionCall %2 %271 -%432 = OpFunctionCall %2 %316 -%433 = OpFunctionCall %2 %393 +%428 = OpFunction %2 None %153 +%427 = OpLabel +OpBranch %429 +%429 = OpLabel +%430 = OpFunctionCall %27 %56 +%431 = OpFunctionCall %27 %81 +%432 = OpVectorShuffle %30 %41 %41 0 1 2 +%433 = OpFunctionCall %30 %98 %432 +%434 = OpFunctionCall %4 %129 +%435 = OpFunctionCall %2 %152 +%436 = OpFunctionCall %2 %170 +%437 = OpFunctionCall %2 %274 +%438 = OpFunctionCall %2 %323 +%439 = OpFunctionCall %2 %399 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 297b75240..ca9877b66 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -56,126 +56,129 @@ fn constructors() -> f32 { fn logical() { let unnamed_11 = !(true); - let unnamed_12 = (true || false); - let unnamed_13 = (true && false); - let unnamed_14 = (true | false); - let unnamed_15 = (vec3(true) | vec3(false)); - let unnamed_16 = (true & false); - let unnamed_17 = (vec4(true) & vec4(false)); + let unnamed_12 = !(vec2(true)); + let unnamed_13 = (true || false); + let unnamed_14 = (true && false); + let unnamed_15 = (true | false); + let unnamed_16 = (vec3(true) | vec3(false)); + let unnamed_17 = (true & false); + let unnamed_18 = (vec4(true) & vec4(false)); } fn arithmetic() { - let unnamed_18 = -(vec2(1)); - let unnamed_19 = -(vec2(1.0)); - let unnamed_20 = (2 + 1); - let unnamed_21 = (2u + 1u); - let unnamed_22 = (2.0 + 1.0); - let unnamed_23 = (vec2(2) + vec2(1)); - let unnamed_24 = (vec3(2u) + vec3(1u)); - let unnamed_25 = (vec4(2.0) + vec4(1.0)); - let unnamed_26 = (2 - 1); - let unnamed_27 = (2u - 1u); - let unnamed_28 = (2.0 - 1.0); - let unnamed_29 = (vec2(2) - vec2(1)); - let unnamed_30 = (vec3(2u) - vec3(1u)); - let unnamed_31 = (vec4(2.0) - vec4(1.0)); - let unnamed_32 = (2 * 1); - let unnamed_33 = (2u * 1u); - let unnamed_34 = (2.0 * 1.0); - let unnamed_35 = (vec2(2) * vec2(1)); - let unnamed_36 = (vec3(2u) * vec3(1u)); - let unnamed_37 = (vec4(2.0) * vec4(1.0)); - let unnamed_38 = (2 / 1); - let unnamed_39 = (2u / 1u); - let unnamed_40 = (2.0 / 1.0); - let unnamed_41 = (vec2(2) / vec2(1)); - let unnamed_42 = (vec3(2u) / vec3(1u)); - let unnamed_43 = (vec4(2.0) / vec4(1.0)); - let unnamed_44 = (2 % 1); - let unnamed_45 = (2u % 1u); - let unnamed_46 = (2.0 % 1.0); - let unnamed_47 = (vec2(2) % vec2(1)); - let unnamed_48 = (vec3(2u) % vec3(1u)); - let unnamed_49 = (vec4(2.0) % vec4(1.0)); - let unnamed_50 = (vec2(2) + vec2(1)); + let unnamed_19 = -(vec2(1)); + let unnamed_20 = -(vec2(1.0)); + let unnamed_21 = (2 + 1); + let unnamed_22 = (2u + 1u); + let unnamed_23 = (2.0 + 1.0); + let unnamed_24 = (vec2(2) + vec2(1)); + let unnamed_25 = (vec3(2u) + vec3(1u)); + let unnamed_26 = (vec4(2.0) + vec4(1.0)); + let unnamed_27 = (2 - 1); + let unnamed_28 = (2u - 1u); + let unnamed_29 = (2.0 - 1.0); + let unnamed_30 = (vec2(2) - vec2(1)); + let unnamed_31 = (vec3(2u) - vec3(1u)); + let unnamed_32 = (vec4(2.0) - vec4(1.0)); + let unnamed_33 = (2 * 1); + let unnamed_34 = (2u * 1u); + let unnamed_35 = (2.0 * 1.0); + let unnamed_36 = (vec2(2) * vec2(1)); + let unnamed_37 = (vec3(2u) * vec3(1u)); + let unnamed_38 = (vec4(2.0) * vec4(1.0)); + let unnamed_39 = (2 / 1); + let unnamed_40 = (2u / 1u); + let unnamed_41 = (2.0 / 1.0); + let unnamed_42 = (vec2(2) / vec2(1)); + let unnamed_43 = (vec3(2u) / vec3(1u)); + let unnamed_44 = (vec4(2.0) / vec4(1.0)); + let unnamed_45 = (2 % 1); + let unnamed_46 = (2u % 1u); + let unnamed_47 = (2.0 % 1.0); + let unnamed_48 = (vec2(2) % vec2(1)); + let unnamed_49 = (vec3(2u) % vec3(1u)); + let unnamed_50 = (vec4(2.0) % vec4(1.0)); let unnamed_51 = (vec2(2) + vec2(1)); - let unnamed_52 = (vec2(2) - vec2(1)); + let unnamed_52 = (vec2(2) + vec2(1)); let unnamed_53 = (vec2(2) - vec2(1)); - let unnamed_54 = (vec2(2) * 1); - let unnamed_55 = (2 * vec2(1)); - let unnamed_56 = (vec2(2) / vec2(1)); + let unnamed_54 = (vec2(2) - vec2(1)); + let unnamed_55 = (vec2(2) * 1); + let unnamed_56 = (2 * vec2(1)); let unnamed_57 = (vec2(2) / vec2(1)); - let unnamed_58 = (vec2(2) % vec2(1)); + let unnamed_58 = (vec2(2) / vec2(1)); let unnamed_59 = (vec2(2) % vec2(1)); - let unnamed_60 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - let unnamed_61 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_62 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - let unnamed_63 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_64 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + let unnamed_60 = (vec2(2) % vec2(1)); + let unnamed_61 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + let unnamed_62 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_63 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + let unnamed_64 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_65 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } fn bit() { - let unnamed_65 = ~(1); - let unnamed_66 = ~(1u); - let unnamed_67 = (2 | 1); - let unnamed_68 = (2u | 1u); - let unnamed_69 = (vec2(2) | vec2(1)); - let unnamed_70 = (vec3(2u) | vec3(1u)); - let unnamed_71 = (2 & 1); - let unnamed_72 = (2u & 1u); - let unnamed_73 = (vec2(2) & vec2(1)); - let unnamed_74 = (vec3(2u) & vec3(1u)); - let unnamed_75 = (2 ^ 1); - let unnamed_76 = (2u ^ 1u); - let unnamed_77 = (vec2(2) ^ vec2(1)); - let unnamed_78 = (vec3(2u) ^ vec3(1u)); - let unnamed_79 = (2 << 1u); - let unnamed_80 = (2u << 1u); - let unnamed_81 = (vec2(2) << vec2(1u)); - let unnamed_82 = (vec3(2u) << vec3(1u)); - let unnamed_83 = (2 >> 1u); - let unnamed_84 = (2u >> 1u); - let unnamed_85 = (vec2(2) >> vec2(1u)); - let unnamed_86 = (vec3(2u) >> vec3(1u)); + let unnamed_66 = ~(1); + let unnamed_67 = ~(1u); + let unnamed_68 = !(vec2(1)); + let unnamed_69 = !(vec3(1u)); + let unnamed_70 = (2 | 1); + let unnamed_71 = (2u | 1u); + let unnamed_72 = (vec2(2) | vec2(1)); + let unnamed_73 = (vec3(2u) | vec3(1u)); + let unnamed_74 = (2 & 1); + let unnamed_75 = (2u & 1u); + let unnamed_76 = (vec2(2) & vec2(1)); + let unnamed_77 = (vec3(2u) & vec3(1u)); + let unnamed_78 = (2 ^ 1); + let unnamed_79 = (2u ^ 1u); + let unnamed_80 = (vec2(2) ^ vec2(1)); + let unnamed_81 = (vec3(2u) ^ vec3(1u)); + let unnamed_82 = (2 << 1u); + let unnamed_83 = (2u << 1u); + let unnamed_84 = (vec2(2) << vec2(1u)); + let unnamed_85 = (vec3(2u) << vec3(1u)); + let unnamed_86 = (2 >> 1u); + let unnamed_87 = (2u >> 1u); + let unnamed_88 = (vec2(2) >> vec2(1u)); + let unnamed_89 = (vec3(2u) >> vec3(1u)); } fn comparison() { - let unnamed_87 = (2 == 1); - let unnamed_88 = (2u == 1u); - let unnamed_89 = (2.0 == 1.0); - let unnamed_90 = (vec2(2) == vec2(1)); - let unnamed_91 = (vec3(2u) == vec3(1u)); - let unnamed_92 = (vec4(2.0) == vec4(1.0)); - let unnamed_93 = (2 != 1); - let unnamed_94 = (2u != 1u); - let unnamed_95 = (2.0 != 1.0); - let unnamed_96 = (vec2(2) != vec2(1)); - let unnamed_97 = (vec3(2u) != vec3(1u)); - let unnamed_98 = (vec4(2.0) != vec4(1.0)); - let unnamed_99 = (2 < 1); - let unnamed_100 = (2u < 1u); - let unnamed_101 = (2.0 < 1.0); - let unnamed_102 = (vec2(2) < vec2(1)); - let unnamed_103 = (vec3(2u) < vec3(1u)); - let unnamed_104 = (vec4(2.0) < vec4(1.0)); - let unnamed_105 = (2 <= 1); - let unnamed_106 = (2u <= 1u); - let unnamed_107 = (2.0 <= 1.0); - let unnamed_108 = (vec2(2) <= vec2(1)); - let unnamed_109 = (vec3(2u) <= vec3(1u)); - let unnamed_110 = (vec4(2.0) <= vec4(1.0)); - let unnamed_111 = (2 > 1); - let unnamed_112 = (2u > 1u); - let unnamed_113 = (2.0 > 1.0); - let unnamed_114 = (vec2(2) > vec2(1)); - let unnamed_115 = (vec3(2u) > vec3(1u)); - let unnamed_116 = (vec4(2.0) > vec4(1.0)); - let unnamed_117 = (2 >= 1); - let unnamed_118 = (2u >= 1u); - let unnamed_119 = (2.0 >= 1.0); - let unnamed_120 = (vec2(2) >= vec2(1)); - let unnamed_121 = (vec3(2u) >= vec3(1u)); - let unnamed_122 = (vec4(2.0) >= vec4(1.0)); + let unnamed_90 = (2 == 1); + let unnamed_91 = (2u == 1u); + let unnamed_92 = (2.0 == 1.0); + let unnamed_93 = (vec2(2) == vec2(1)); + let unnamed_94 = (vec3(2u) == vec3(1u)); + let unnamed_95 = (vec4(2.0) == vec4(1.0)); + let unnamed_96 = (2 != 1); + let unnamed_97 = (2u != 1u); + let unnamed_98 = (2.0 != 1.0); + let unnamed_99 = (vec2(2) != vec2(1)); + let unnamed_100 = (vec3(2u) != vec3(1u)); + let unnamed_101 = (vec4(2.0) != vec4(1.0)); + let unnamed_102 = (2 < 1); + let unnamed_103 = (2u < 1u); + let unnamed_104 = (2.0 < 1.0); + let unnamed_105 = (vec2(2) < vec2(1)); + let unnamed_106 = (vec3(2u) < vec3(1u)); + let unnamed_107 = (vec4(2.0) < vec4(1.0)); + let unnamed_108 = (2 <= 1); + let unnamed_109 = (2u <= 1u); + let unnamed_110 = (2.0 <= 1.0); + let unnamed_111 = (vec2(2) <= vec2(1)); + let unnamed_112 = (vec3(2u) <= vec3(1u)); + let unnamed_113 = (vec4(2.0) <= vec4(1.0)); + let unnamed_114 = (2 > 1); + let unnamed_115 = (2u > 1u); + let unnamed_116 = (2.0 > 1.0); + let unnamed_117 = (vec2(2) > vec2(1)); + let unnamed_118 = (vec3(2u) > vec3(1u)); + let unnamed_119 = (vec4(2.0) > vec4(1.0)); + let unnamed_120 = (2 >= 1); + let unnamed_121 = (2u >= 1u); + let unnamed_122 = (2.0 >= 1.0); + let unnamed_123 = (vec2(2) >= vec2(1)); + let unnamed_124 = (vec3(2u) >= vec3(1u)); + let unnamed_125 = (vec4(2.0) >= vec4(1.0)); } fn assignment() { From 4ea7dc33816895da76a96e30d0a940339ea747be Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 15:53:55 +0200 Subject: [PATCH 1679/2212] [spv-out] add support for matrix add and sub --- src/back/spv/block.rs | 98 +++++ tests/in/operators.wgsl | 4 +- tests/out/glsl/operators.main.Compute.glsl | 132 +++---- tests/out/hlsl/operators.hlsl | 132 +++---- tests/out/msl/operators.msl | 132 +++---- tests/out/spv/operators.spvasm | 404 +++++++++++---------- tests/out/wgsl/operators.wgsl | 132 +++---- 7 files changed, 580 insertions(+), 454 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 15bd07bea..b22eb56ae 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -346,6 +346,26 @@ impl<'w> BlockContext<'w> { crate::ScalarKind::Float => spirv::Op::FAdd, _ => spirv::Op::IAdd, }, + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + self.write_matrix_matrix_column_op( + block, + id, + result_type_id, + left_id, + right_id, + columns, + rows, + width, + spirv::Op::FAdd, + ); + + self.cached[expr_handle] = id; + return Ok(()); + } _ => unimplemented!(), }, crate::BinaryOperator::Subtract => match *left_ty_inner { @@ -354,6 +374,26 @@ impl<'w> BlockContext<'w> { crate::ScalarKind::Float => spirv::Op::FSub, _ => spirv::Op::ISub, }, + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + self.write_matrix_matrix_column_op( + block, + id, + result_type_id, + left_id, + right_id, + columns, + rows, + width, + spirv::Op::FSub, + ); + + self.cached[expr_handle] = id; + return Ok(()); + } _ => unimplemented!(), }, crate::BinaryOperator::Multiply => match (left_dimension, right_dimension) { @@ -1150,6 +1190,64 @@ impl<'w> BlockContext<'w> { Ok(pointer) } + /// Build the instructions for matrix - matrix column operations + #[allow(clippy::too_many_arguments)] + fn write_matrix_matrix_column_op( + &mut self, + block: &mut Block, + result_id: Word, + result_type_id: Word, + left_id: Word, + right_id: Word, + columns: crate::VectorSize, + rows: crate::VectorSize, + width: u8, + op: spirv::Op, + ) { + self.temp_list.clear(); + + let vector_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(rows), + kind: crate::ScalarKind::Float, + width, + pointer_space: None, + })); + + for index in 0..columns as u32 { + let column_id_left = self.gen_id(); + let column_id_right = self.gen_id(); + let column_id_res = self.gen_id(); + + block.body.push(Instruction::composite_extract( + vector_type_id, + column_id_left, + left_id, + &[index], + )); + block.body.push(Instruction::composite_extract( + vector_type_id, + column_id_right, + right_id, + &[index], + )); + block.body.push(Instruction::binary( + op, + vector_type_id, + column_id_res, + column_id_left, + column_id_right, + )); + + self.temp_list.push(column_id_res); + } + + block.body.push(Instruction::composite_construct( + result_type_id, + result_id, + &self.temp_list, + )); + } + /// Build the instructions for the arithmetic expression of a dot product fn write_dot_product( &mut self, diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 31ca1f740..205895dd4 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -150,8 +150,8 @@ fn arithmetic() { let _ = 2 % vec2(1); // Matrix arithmetic - // let _ = mat3x3() + mat3x3(); - // let _ = mat3x3() - mat3x3(); + let _ = mat3x3() + mat3x3(); + let _ = mat3x3() - mat3x3(); let _ = mat3x3() * 1.0; let _ = 2.0 * mat3x3(); diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 2aeb893a9..dc741b1eb 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -110,77 +110,79 @@ void arithmetic() { ivec2 unnamed_58 = (ivec2(2) / ivec2(1)); ivec2 unnamed_59 = (ivec2(2) % ivec2(1)); ivec2 unnamed_60 = (ivec2(2) % ivec2(1)); - mat3x3 unnamed_61 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - mat3x3 unnamed_62 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - vec3 unnamed_63 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - vec4 unnamed_64 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_65 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + mat3x3 unnamed_61 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_62 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_63 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + mat3x3 unnamed_64 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + vec3 unnamed_65 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + vec4 unnamed_66 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_67 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } void bit() { - int unnamed_66 = (~ 1); - uint unnamed_67 = (~ 1u); - ivec2 unnamed_68 = (~ ivec2(1)); - uvec3 unnamed_69 = (~ uvec3(1u)); - int unnamed_70 = (2 | 1); - uint unnamed_71 = (2u | 1u); - ivec2 unnamed_72 = (ivec2(2) | ivec2(1)); - uvec3 unnamed_73 = (uvec3(2u) | uvec3(1u)); - int unnamed_74 = (2 & 1); - uint unnamed_75 = (2u & 1u); - ivec2 unnamed_76 = (ivec2(2) & ivec2(1)); - uvec3 unnamed_77 = (uvec3(2u) & uvec3(1u)); - int unnamed_78 = (2 ^ 1); - uint unnamed_79 = (2u ^ 1u); - ivec2 unnamed_80 = (ivec2(2) ^ ivec2(1)); - uvec3 unnamed_81 = (uvec3(2u) ^ uvec3(1u)); - int unnamed_82 = (2 << 1u); - uint unnamed_83 = (2u << 1u); - ivec2 unnamed_84 = (ivec2(2) << uvec2(1u)); - uvec3 unnamed_85 = (uvec3(2u) << uvec3(1u)); - int unnamed_86 = (2 >> 1u); - uint unnamed_87 = (2u >> 1u); - ivec2 unnamed_88 = (ivec2(2) >> uvec2(1u)); - uvec3 unnamed_89 = (uvec3(2u) >> uvec3(1u)); + int unnamed_68 = (~ 1); + uint unnamed_69 = (~ 1u); + ivec2 unnamed_70 = (~ ivec2(1)); + uvec3 unnamed_71 = (~ uvec3(1u)); + int unnamed_72 = (2 | 1); + uint unnamed_73 = (2u | 1u); + ivec2 unnamed_74 = (ivec2(2) | ivec2(1)); + uvec3 unnamed_75 = (uvec3(2u) | uvec3(1u)); + int unnamed_76 = (2 & 1); + uint unnamed_77 = (2u & 1u); + ivec2 unnamed_78 = (ivec2(2) & ivec2(1)); + uvec3 unnamed_79 = (uvec3(2u) & uvec3(1u)); + int unnamed_80 = (2 ^ 1); + uint unnamed_81 = (2u ^ 1u); + ivec2 unnamed_82 = (ivec2(2) ^ ivec2(1)); + uvec3 unnamed_83 = (uvec3(2u) ^ uvec3(1u)); + int unnamed_84 = (2 << 1u); + uint unnamed_85 = (2u << 1u); + ivec2 unnamed_86 = (ivec2(2) << uvec2(1u)); + uvec3 unnamed_87 = (uvec3(2u) << uvec3(1u)); + int unnamed_88 = (2 >> 1u); + uint unnamed_89 = (2u >> 1u); + ivec2 unnamed_90 = (ivec2(2) >> uvec2(1u)); + uvec3 unnamed_91 = (uvec3(2u) >> uvec3(1u)); } void comparison() { - bool unnamed_90 = (2 == 1); - bool unnamed_91 = (2u == 1u); - bool unnamed_92 = (2.0 == 1.0); - bvec2 unnamed_93 = equal(ivec2(2), ivec2(1)); - bvec3 unnamed_94 = equal(uvec3(2u), uvec3(1u)); - bvec4 unnamed_95 = equal(vec4(2.0), vec4(1.0)); - bool unnamed_96 = (2 != 1); - bool unnamed_97 = (2u != 1u); - bool unnamed_98 = (2.0 != 1.0); - bvec2 unnamed_99 = notEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_100 = notEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_101 = notEqual(vec4(2.0), vec4(1.0)); - bool unnamed_102 = (2 < 1); - bool unnamed_103 = (2u < 1u); - bool unnamed_104 = (2.0 < 1.0); - bvec2 unnamed_105 = lessThan(ivec2(2), ivec2(1)); - bvec3 unnamed_106 = lessThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_107 = lessThan(vec4(2.0), vec4(1.0)); - bool unnamed_108 = (2 <= 1); - bool unnamed_109 = (2u <= 1u); - bool unnamed_110 = (2.0 <= 1.0); - bvec2 unnamed_111 = lessThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_112 = lessThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_113 = lessThanEqual(vec4(2.0), vec4(1.0)); - bool unnamed_114 = (2 > 1); - bool unnamed_115 = (2u > 1u); - bool unnamed_116 = (2.0 > 1.0); - bvec2 unnamed_117 = greaterThan(ivec2(2), ivec2(1)); - bvec3 unnamed_118 = greaterThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_119 = greaterThan(vec4(2.0), vec4(1.0)); - bool unnamed_120 = (2 >= 1); - bool unnamed_121 = (2u >= 1u); - bool unnamed_122 = (2.0 >= 1.0); - bvec2 unnamed_123 = greaterThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_124 = greaterThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_125 = greaterThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_92 = (2 == 1); + bool unnamed_93 = (2u == 1u); + bool unnamed_94 = (2.0 == 1.0); + bvec2 unnamed_95 = equal(ivec2(2), ivec2(1)); + bvec3 unnamed_96 = equal(uvec3(2u), uvec3(1u)); + bvec4 unnamed_97 = equal(vec4(2.0), vec4(1.0)); + bool unnamed_98 = (2 != 1); + bool unnamed_99 = (2u != 1u); + bool unnamed_100 = (2.0 != 1.0); + bvec2 unnamed_101 = notEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_102 = notEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_103 = notEqual(vec4(2.0), vec4(1.0)); + bool unnamed_104 = (2 < 1); + bool unnamed_105 = (2u < 1u); + bool unnamed_106 = (2.0 < 1.0); + bvec2 unnamed_107 = lessThan(ivec2(2), ivec2(1)); + bvec3 unnamed_108 = lessThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_109 = lessThan(vec4(2.0), vec4(1.0)); + bool unnamed_110 = (2 <= 1); + bool unnamed_111 = (2u <= 1u); + bool unnamed_112 = (2.0 <= 1.0); + bvec2 unnamed_113 = lessThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_114 = lessThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_115 = lessThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_116 = (2 > 1); + bool unnamed_117 = (2u > 1u); + bool unnamed_118 = (2.0 > 1.0); + bvec2 unnamed_119 = greaterThan(ivec2(2), ivec2(1)); + bvec3 unnamed_120 = greaterThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_121 = greaterThan(vec4(2.0), vec4(1.0)); + bool unnamed_122 = (2 >= 1); + bool unnamed_123 = (2u >= 1u); + bool unnamed_124 = (2.0 >= 1.0); + bvec2 unnamed_125 = greaterThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_126 = greaterThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_127 = greaterThanEqual(vec4(2.0), vec4(1.0)); } void assignment() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 5275cbe3b..e640cfaff 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -138,79 +138,81 @@ void arithmetic() int2 unnamed_58 = (int2(2.xx) / int2(1.xx)); int2 unnamed_59 = (int2(2.xx) % int2(1.xx)); int2 unnamed_60 = (int2(2.xx) % int2(1.xx)); - float3x3 unnamed_61 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_62 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); - float3 unnamed_63 = mul(float4(1.0.xxxx), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float4 unnamed_64 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), float3(2.0.xxx)); - float3x3 unnamed_65 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_61 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_62 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_63 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_64 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); + float3 unnamed_65 = mul(float4(1.0.xxxx), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float4 unnamed_66 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), float3(2.0.xxx)); + float3x3 unnamed_67 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); } void bit() { - int unnamed_66 = ~1; - uint unnamed_67 = ~1u; - int2 unnamed_68 = ~int2(1.xx); - uint3 unnamed_69 = ~uint3(1u.xxx); - int unnamed_70 = (2 | 1); - uint unnamed_71 = (2u | 1u); - int2 unnamed_72 = (int2(2.xx) | int2(1.xx)); - uint3 unnamed_73 = (uint3(2u.xxx) | uint3(1u.xxx)); - int unnamed_74 = (2 & 1); - uint unnamed_75 = (2u & 1u); - int2 unnamed_76 = (int2(2.xx) & int2(1.xx)); - uint3 unnamed_77 = (uint3(2u.xxx) & uint3(1u.xxx)); - int unnamed_78 = (2 ^ 1); - uint unnamed_79 = (2u ^ 1u); - int2 unnamed_80 = (int2(2.xx) ^ int2(1.xx)); - uint3 unnamed_81 = (uint3(2u.xxx) ^ uint3(1u.xxx)); - int unnamed_82 = (2 << 1u); - uint unnamed_83 = (2u << 1u); - int2 unnamed_84 = (int2(2.xx) << uint2(1u.xx)); - uint3 unnamed_85 = (uint3(2u.xxx) << uint3(1u.xxx)); - int unnamed_86 = (2 >> 1u); - uint unnamed_87 = (2u >> 1u); - int2 unnamed_88 = (int2(2.xx) >> uint2(1u.xx)); - uint3 unnamed_89 = (uint3(2u.xxx) >> uint3(1u.xxx)); + int unnamed_68 = ~1; + uint unnamed_69 = ~1u; + int2 unnamed_70 = ~int2(1.xx); + uint3 unnamed_71 = ~uint3(1u.xxx); + int unnamed_72 = (2 | 1); + uint unnamed_73 = (2u | 1u); + int2 unnamed_74 = (int2(2.xx) | int2(1.xx)); + uint3 unnamed_75 = (uint3(2u.xxx) | uint3(1u.xxx)); + int unnamed_76 = (2 & 1); + uint unnamed_77 = (2u & 1u); + int2 unnamed_78 = (int2(2.xx) & int2(1.xx)); + uint3 unnamed_79 = (uint3(2u.xxx) & uint3(1u.xxx)); + int unnamed_80 = (2 ^ 1); + uint unnamed_81 = (2u ^ 1u); + int2 unnamed_82 = (int2(2.xx) ^ int2(1.xx)); + uint3 unnamed_83 = (uint3(2u.xxx) ^ uint3(1u.xxx)); + int unnamed_84 = (2 << 1u); + uint unnamed_85 = (2u << 1u); + int2 unnamed_86 = (int2(2.xx) << uint2(1u.xx)); + uint3 unnamed_87 = (uint3(2u.xxx) << uint3(1u.xxx)); + int unnamed_88 = (2 >> 1u); + uint unnamed_89 = (2u >> 1u); + int2 unnamed_90 = (int2(2.xx) >> uint2(1u.xx)); + uint3 unnamed_91 = (uint3(2u.xxx) >> uint3(1u.xxx)); } void comparison() { - bool unnamed_90 = (2 == 1); - bool unnamed_91 = (2u == 1u); - bool unnamed_92 = (2.0 == 1.0); - bool2 unnamed_93 = (int2(2.xx) == int2(1.xx)); - bool3 unnamed_94 = (uint3(2u.xxx) == uint3(1u.xxx)); - bool4 unnamed_95 = (float4(2.0.xxxx) == float4(1.0.xxxx)); - bool unnamed_96 = (2 != 1); - bool unnamed_97 = (2u != 1u); - bool unnamed_98 = (2.0 != 1.0); - bool2 unnamed_99 = (int2(2.xx) != int2(1.xx)); - bool3 unnamed_100 = (uint3(2u.xxx) != uint3(1u.xxx)); - bool4 unnamed_101 = (float4(2.0.xxxx) != float4(1.0.xxxx)); - bool unnamed_102 = (2 < 1); - bool unnamed_103 = (2u < 1u); - bool unnamed_104 = (2.0 < 1.0); - bool2 unnamed_105 = (int2(2.xx) < int2(1.xx)); - bool3 unnamed_106 = (uint3(2u.xxx) < uint3(1u.xxx)); - bool4 unnamed_107 = (float4(2.0.xxxx) < float4(1.0.xxxx)); - bool unnamed_108 = (2 <= 1); - bool unnamed_109 = (2u <= 1u); - bool unnamed_110 = (2.0 <= 1.0); - bool2 unnamed_111 = (int2(2.xx) <= int2(1.xx)); - bool3 unnamed_112 = (uint3(2u.xxx) <= uint3(1u.xxx)); - bool4 unnamed_113 = (float4(2.0.xxxx) <= float4(1.0.xxxx)); - bool unnamed_114 = (2 > 1); - bool unnamed_115 = (2u > 1u); - bool unnamed_116 = (2.0 > 1.0); - bool2 unnamed_117 = (int2(2.xx) > int2(1.xx)); - bool3 unnamed_118 = (uint3(2u.xxx) > uint3(1u.xxx)); - bool4 unnamed_119 = (float4(2.0.xxxx) > float4(1.0.xxxx)); - bool unnamed_120 = (2 >= 1); - bool unnamed_121 = (2u >= 1u); - bool unnamed_122 = (2.0 >= 1.0); - bool2 unnamed_123 = (int2(2.xx) >= int2(1.xx)); - bool3 unnamed_124 = (uint3(2u.xxx) >= uint3(1u.xxx)); - bool4 unnamed_125 = (float4(2.0.xxxx) >= float4(1.0.xxxx)); + bool unnamed_92 = (2 == 1); + bool unnamed_93 = (2u == 1u); + bool unnamed_94 = (2.0 == 1.0); + bool2 unnamed_95 = (int2(2.xx) == int2(1.xx)); + bool3 unnamed_96 = (uint3(2u.xxx) == uint3(1u.xxx)); + bool4 unnamed_97 = (float4(2.0.xxxx) == float4(1.0.xxxx)); + bool unnamed_98 = (2 != 1); + bool unnamed_99 = (2u != 1u); + bool unnamed_100 = (2.0 != 1.0); + bool2 unnamed_101 = (int2(2.xx) != int2(1.xx)); + bool3 unnamed_102 = (uint3(2u.xxx) != uint3(1u.xxx)); + bool4 unnamed_103 = (float4(2.0.xxxx) != float4(1.0.xxxx)); + bool unnamed_104 = (2 < 1); + bool unnamed_105 = (2u < 1u); + bool unnamed_106 = (2.0 < 1.0); + bool2 unnamed_107 = (int2(2.xx) < int2(1.xx)); + bool3 unnamed_108 = (uint3(2u.xxx) < uint3(1u.xxx)); + bool4 unnamed_109 = (float4(2.0.xxxx) < float4(1.0.xxxx)); + bool unnamed_110 = (2 <= 1); + bool unnamed_111 = (2u <= 1u); + bool unnamed_112 = (2.0 <= 1.0); + bool2 unnamed_113 = (int2(2.xx) <= int2(1.xx)); + bool3 unnamed_114 = (uint3(2u.xxx) <= uint3(1u.xxx)); + bool4 unnamed_115 = (float4(2.0.xxxx) <= float4(1.0.xxxx)); + bool unnamed_116 = (2 > 1); + bool unnamed_117 = (2u > 1u); + bool unnamed_118 = (2.0 > 1.0); + bool2 unnamed_119 = (int2(2.xx) > int2(1.xx)); + bool3 unnamed_120 = (uint3(2u.xxx) > uint3(1u.xxx)); + bool4 unnamed_121 = (float4(2.0.xxxx) > float4(1.0.xxxx)); + bool unnamed_122 = (2 >= 1); + bool unnamed_123 = (2u >= 1u); + bool unnamed_124 = (2.0 >= 1.0); + bool2 unnamed_125 = (int2(2.xx) >= int2(1.xx)); + bool3 unnamed_126 = (uint3(2u.xxx) >= uint3(1u.xxx)); + bool4 unnamed_127 = (float4(2.0.xxxx) >= float4(1.0.xxxx)); } void assignment() diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 87a10ee44..573bad182 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -136,79 +136,81 @@ void arithmetic( metal::int2 unnamed_58 = metal::int2(2) / metal::int2(1); metal::int2 unnamed_59 = metal::int2(2) % metal::int2(1); metal::int2 unnamed_60 = metal::int2(2) % metal::int2(1); - metal::float3x3 unnamed_61 = const_type_14_ * 1.0; - metal::float3x3 unnamed_62 = 2.0 * const_type_14_; - metal::float3 unnamed_63 = const_type_15_ * metal::float4(1.0); - metal::float4 unnamed_64 = metal::float3(2.0) * const_type_15_; - metal::float3x3 unnamed_65 = const_type_15_ * const_type_16_; + metal::float3x3 unnamed_61 = const_type_14_ + const_type_14_; + metal::float3x3 unnamed_62 = const_type_14_ - const_type_14_; + metal::float3x3 unnamed_63 = const_type_14_ * 1.0; + metal::float3x3 unnamed_64 = 2.0 * const_type_14_; + metal::float3 unnamed_65 = const_type_15_ * metal::float4(1.0); + metal::float4 unnamed_66 = metal::float3(2.0) * const_type_15_; + metal::float3x3 unnamed_67 = const_type_15_ * const_type_16_; } void bit( ) { - int unnamed_66 = ~1; - uint unnamed_67 = ~1u; - metal::int2 unnamed_68 = ~metal::int2(1); - metal::uint3 unnamed_69 = ~metal::uint3(1u); - int unnamed_70 = 2 | 1; - uint unnamed_71 = 2u | 1u; - metal::int2 unnamed_72 = metal::int2(2) | metal::int2(1); - metal::uint3 unnamed_73 = metal::uint3(2u) | metal::uint3(1u); - int unnamed_74 = 2 & 1; - uint unnamed_75 = 2u & 1u; - metal::int2 unnamed_76 = metal::int2(2) & metal::int2(1); - metal::uint3 unnamed_77 = metal::uint3(2u) & metal::uint3(1u); - int unnamed_78 = 2 ^ 1; - uint unnamed_79 = 2u ^ 1u; - metal::int2 unnamed_80 = metal::int2(2) ^ metal::int2(1); - metal::uint3 unnamed_81 = metal::uint3(2u) ^ metal::uint3(1u); - int unnamed_82 = 2 << 1u; - uint unnamed_83 = 2u << 1u; - metal::int2 unnamed_84 = metal::int2(2) << metal::uint2(1u); - metal::uint3 unnamed_85 = metal::uint3(2u) << metal::uint3(1u); - int unnamed_86 = 2 >> 1u; - uint unnamed_87 = 2u >> 1u; - metal::int2 unnamed_88 = metal::int2(2) >> metal::uint2(1u); - metal::uint3 unnamed_89 = metal::uint3(2u) >> metal::uint3(1u); + int unnamed_68 = ~1; + uint unnamed_69 = ~1u; + metal::int2 unnamed_70 = ~metal::int2(1); + metal::uint3 unnamed_71 = ~metal::uint3(1u); + int unnamed_72 = 2 | 1; + uint unnamed_73 = 2u | 1u; + metal::int2 unnamed_74 = metal::int2(2) | metal::int2(1); + metal::uint3 unnamed_75 = metal::uint3(2u) | metal::uint3(1u); + int unnamed_76 = 2 & 1; + uint unnamed_77 = 2u & 1u; + metal::int2 unnamed_78 = metal::int2(2) & metal::int2(1); + metal::uint3 unnamed_79 = metal::uint3(2u) & metal::uint3(1u); + int unnamed_80 = 2 ^ 1; + uint unnamed_81 = 2u ^ 1u; + metal::int2 unnamed_82 = metal::int2(2) ^ metal::int2(1); + metal::uint3 unnamed_83 = metal::uint3(2u) ^ metal::uint3(1u); + int unnamed_84 = 2 << 1u; + uint unnamed_85 = 2u << 1u; + metal::int2 unnamed_86 = metal::int2(2) << metal::uint2(1u); + metal::uint3 unnamed_87 = metal::uint3(2u) << metal::uint3(1u); + int unnamed_88 = 2 >> 1u; + uint unnamed_89 = 2u >> 1u; + metal::int2 unnamed_90 = metal::int2(2) >> metal::uint2(1u); + metal::uint3 unnamed_91 = metal::uint3(2u) >> metal::uint3(1u); } void comparison( ) { - bool unnamed_90 = 2 == 1; - bool unnamed_91 = 2u == 1u; - bool unnamed_92 = 2.0 == 1.0; - metal::bool2 unnamed_93 = metal::int2(2) == metal::int2(1); - metal::bool3 unnamed_94 = metal::uint3(2u) == metal::uint3(1u); - metal::bool4 unnamed_95 = metal::float4(2.0) == metal::float4(1.0); - bool unnamed_96 = 2 != 1; - bool unnamed_97 = 2u != 1u; - bool unnamed_98 = 2.0 != 1.0; - metal::bool2 unnamed_99 = metal::int2(2) != metal::int2(1); - metal::bool3 unnamed_100 = metal::uint3(2u) != metal::uint3(1u); - metal::bool4 unnamed_101 = metal::float4(2.0) != metal::float4(1.0); - bool unnamed_102 = 2 < 1; - bool unnamed_103 = 2u < 1u; - bool unnamed_104 = 2.0 < 1.0; - metal::bool2 unnamed_105 = metal::int2(2) < metal::int2(1); - metal::bool3 unnamed_106 = metal::uint3(2u) < metal::uint3(1u); - metal::bool4 unnamed_107 = metal::float4(2.0) < metal::float4(1.0); - bool unnamed_108 = 2 <= 1; - bool unnamed_109 = 2u <= 1u; - bool unnamed_110 = 2.0 <= 1.0; - metal::bool2 unnamed_111 = metal::int2(2) <= metal::int2(1); - metal::bool3 unnamed_112 = metal::uint3(2u) <= metal::uint3(1u); - metal::bool4 unnamed_113 = metal::float4(2.0) <= metal::float4(1.0); - bool unnamed_114 = 2 > 1; - bool unnamed_115 = 2u > 1u; - bool unnamed_116 = 2.0 > 1.0; - metal::bool2 unnamed_117 = metal::int2(2) > metal::int2(1); - metal::bool3 unnamed_118 = metal::uint3(2u) > metal::uint3(1u); - metal::bool4 unnamed_119 = metal::float4(2.0) > metal::float4(1.0); - bool unnamed_120 = 2 >= 1; - bool unnamed_121 = 2u >= 1u; - bool unnamed_122 = 2.0 >= 1.0; - metal::bool2 unnamed_123 = metal::int2(2) >= metal::int2(1); - metal::bool3 unnamed_124 = metal::uint3(2u) >= metal::uint3(1u); - metal::bool4 unnamed_125 = metal::float4(2.0) >= metal::float4(1.0); + bool unnamed_92 = 2 == 1; + bool unnamed_93 = 2u == 1u; + bool unnamed_94 = 2.0 == 1.0; + metal::bool2 unnamed_95 = metal::int2(2) == metal::int2(1); + metal::bool3 unnamed_96 = metal::uint3(2u) == metal::uint3(1u); + metal::bool4 unnamed_97 = metal::float4(2.0) == metal::float4(1.0); + bool unnamed_98 = 2 != 1; + bool unnamed_99 = 2u != 1u; + bool unnamed_100 = 2.0 != 1.0; + metal::bool2 unnamed_101 = metal::int2(2) != metal::int2(1); + metal::bool3 unnamed_102 = metal::uint3(2u) != metal::uint3(1u); + metal::bool4 unnamed_103 = metal::float4(2.0) != metal::float4(1.0); + bool unnamed_104 = 2 < 1; + bool unnamed_105 = 2u < 1u; + bool unnamed_106 = 2.0 < 1.0; + metal::bool2 unnamed_107 = metal::int2(2) < metal::int2(1); + metal::bool3 unnamed_108 = metal::uint3(2u) < metal::uint3(1u); + metal::bool4 unnamed_109 = metal::float4(2.0) < metal::float4(1.0); + bool unnamed_110 = 2 <= 1; + bool unnamed_111 = 2u <= 1u; + bool unnamed_112 = 2.0 <= 1.0; + metal::bool2 unnamed_113 = metal::int2(2) <= metal::int2(1); + metal::bool3 unnamed_114 = metal::uint3(2u) <= metal::uint3(1u); + metal::bool4 unnamed_115 = metal::float4(2.0) <= metal::float4(1.0); + bool unnamed_116 = 2 > 1; + bool unnamed_117 = 2u > 1u; + bool unnamed_118 = 2.0 > 1.0; + metal::bool2 unnamed_119 = metal::int2(2) > metal::int2(1); + metal::bool3 unnamed_120 = metal::uint3(2u) > metal::uint3(1u); + metal::bool4 unnamed_121 = metal::float4(2.0) > metal::float4(1.0); + bool unnamed_122 = 2 >= 1; + bool unnamed_123 = 2u >= 1u; + bool unnamed_124 = 2.0 >= 1.0; + metal::bool2 unnamed_125 = metal::int2(2) >= metal::int2(1); + metal::bool3 unnamed_126 = metal::uint3(2u) >= metal::uint3(1u); + metal::bool4 unnamed_127 = metal::float4(2.0) >= metal::float4(1.0); } void assignment( diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index d3d9919ce..294f48cc9 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 440 +; Bound: 460 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %428 "main" -OpExecutionMode %428 LocalSize 1 1 1 +OpEntryPoint GLCompute %448 "main" +OpExecutionMode %448 LocalSize 1 1 1 OpMemberDecorate %31 0 Offset 0 OpMemberDecorate %31 1 Offset 16 OpDecorate %36 ArrayStride 32 @@ -295,203 +295,223 @@ OpBranch %171 %263 = OpCompositeConstruct %172 %7 %7 %264 = OpCompositeConstruct %172 %18 %18 %265 = OpSMod %172 %264 %263 -%266 = OpMatrixTimesScalar %38 %52 %3 -%267 = OpMatrixTimesScalar %38 %52 %14 -%268 = OpCompositeConstruct %27 %3 %3 %3 %3 -%269 = OpMatrixTimesVector %30 %53 %268 -%270 = OpCompositeConstruct %30 %14 %14 %14 -%271 = OpVectorTimesMatrix %27 %270 %53 -%272 = OpMatrixTimesMatrix %38 %53 %54 +%267 = OpCompositeExtract %30 %52 0 +%268 = OpCompositeExtract %30 %52 0 +%269 = OpFAdd %30 %267 %268 +%270 = OpCompositeExtract %30 %52 1 +%271 = OpCompositeExtract %30 %52 1 +%272 = OpFAdd %30 %270 %271 +%273 = OpCompositeExtract %30 %52 2 +%274 = OpCompositeExtract %30 %52 2 +%275 = OpFAdd %30 %273 %274 +%266 = OpCompositeConstruct %38 %269 %272 %275 +%277 = OpCompositeExtract %30 %52 0 +%278 = OpCompositeExtract %30 %52 0 +%279 = OpFSub %30 %277 %278 +%280 = OpCompositeExtract %30 %52 1 +%281 = OpCompositeExtract %30 %52 1 +%282 = OpFSub %30 %280 %281 +%283 = OpCompositeExtract %30 %52 2 +%284 = OpCompositeExtract %30 %52 2 +%285 = OpFSub %30 %283 %284 +%276 = OpCompositeConstruct %38 %279 %282 %285 +%286 = OpMatrixTimesScalar %38 %52 %3 +%287 = OpMatrixTimesScalar %38 %52 %14 +%288 = OpCompositeConstruct %27 %3 %3 %3 %3 +%289 = OpMatrixTimesVector %30 %53 %288 +%290 = OpCompositeConstruct %30 %14 %14 %14 +%291 = OpVectorTimesMatrix %27 %290 %53 +%292 = OpMatrixTimesMatrix %38 %53 %54 OpReturn OpFunctionEnd -%274 = OpFunction %2 None %153 -%273 = OpLabel -OpBranch %275 -%275 = OpLabel -%276 = OpNot %8 %7 -%277 = OpNot %20 %26 -%278 = OpCompositeConstruct %172 %7 %7 -%279 = OpNot %172 %278 -%280 = OpCompositeConstruct %183 %26 %26 %26 -%281 = OpNot %183 %280 -%282 = OpBitwiseOr %8 %18 %7 -%283 = OpBitwiseOr %20 %25 %26 -%284 = OpCompositeConstruct %172 %18 %18 -%285 = OpCompositeConstruct %172 %7 %7 -%286 = OpBitwiseOr %172 %284 %285 -%287 = OpCompositeConstruct %183 %25 %25 %25 -%288 = OpCompositeConstruct %183 %26 %26 %26 -%289 = OpBitwiseOr %183 %287 %288 -%290 = OpBitwiseAnd %8 %18 %7 -%291 = OpBitwiseAnd %20 %25 %26 -%292 = OpCompositeConstruct %172 %18 %18 -%293 = OpCompositeConstruct %172 %7 %7 -%294 = OpBitwiseAnd %172 %292 %293 -%295 = OpCompositeConstruct %183 %25 %25 %25 -%296 = OpCompositeConstruct %183 %26 %26 %26 -%297 = OpBitwiseAnd %183 %295 %296 -%298 = OpBitwiseXor %8 %18 %7 -%299 = OpBitwiseXor %20 %25 %26 -%300 = OpCompositeConstruct %172 %18 %18 -%301 = OpCompositeConstruct %172 %7 %7 -%302 = OpBitwiseXor %172 %300 %301 -%303 = OpCompositeConstruct %183 %25 %25 %25 -%304 = OpCompositeConstruct %183 %26 %26 %26 -%305 = OpBitwiseXor %183 %303 %304 -%306 = OpShiftLeftLogical %8 %18 %26 -%307 = OpShiftLeftLogical %20 %25 %26 -%308 = OpCompositeConstruct %172 %18 %18 -%309 = OpCompositeConstruct %35 %26 %26 -%310 = OpShiftLeftLogical %172 %308 %309 -%311 = OpCompositeConstruct %183 %25 %25 %25 -%312 = OpCompositeConstruct %183 %26 %26 %26 -%313 = OpShiftLeftLogical %183 %311 %312 -%314 = OpShiftRightArithmetic %8 %18 %26 -%315 = OpShiftRightLogical %20 %25 %26 -%316 = OpCompositeConstruct %172 %18 %18 -%317 = OpCompositeConstruct %35 %26 %26 -%318 = OpShiftRightArithmetic %172 %316 %317 -%319 = OpCompositeConstruct %183 %25 %25 %25 -%320 = OpCompositeConstruct %183 %26 %26 %26 -%321 = OpShiftRightLogical %183 %319 %320 -OpReturn -OpFunctionEnd -%323 = OpFunction %2 None %153 -%322 = OpLabel -OpBranch %324 -%324 = OpLabel -%325 = OpIEqual %10 %18 %7 -%326 = OpIEqual %10 %25 %26 -%327 = OpFOrdEqual %10 %14 %3 +%294 = OpFunction %2 None %153 +%293 = OpLabel +OpBranch %295 +%295 = OpLabel +%296 = OpNot %8 %7 +%297 = OpNot %20 %26 +%298 = OpCompositeConstruct %172 %7 %7 +%299 = OpNot %172 %298 +%300 = OpCompositeConstruct %183 %26 %26 %26 +%301 = OpNot %183 %300 +%302 = OpBitwiseOr %8 %18 %7 +%303 = OpBitwiseOr %20 %25 %26 +%304 = OpCompositeConstruct %172 %18 %18 +%305 = OpCompositeConstruct %172 %7 %7 +%306 = OpBitwiseOr %172 %304 %305 +%307 = OpCompositeConstruct %183 %25 %25 %25 +%308 = OpCompositeConstruct %183 %26 %26 %26 +%309 = OpBitwiseOr %183 %307 %308 +%310 = OpBitwiseAnd %8 %18 %7 +%311 = OpBitwiseAnd %20 %25 %26 +%312 = OpCompositeConstruct %172 %18 %18 +%313 = OpCompositeConstruct %172 %7 %7 +%314 = OpBitwiseAnd %172 %312 %313 +%315 = OpCompositeConstruct %183 %25 %25 %25 +%316 = OpCompositeConstruct %183 %26 %26 %26 +%317 = OpBitwiseAnd %183 %315 %316 +%318 = OpBitwiseXor %8 %18 %7 +%319 = OpBitwiseXor %20 %25 %26 +%320 = OpCompositeConstruct %172 %18 %18 +%321 = OpCompositeConstruct %172 %7 %7 +%322 = OpBitwiseXor %172 %320 %321 +%323 = OpCompositeConstruct %183 %25 %25 %25 +%324 = OpCompositeConstruct %183 %26 %26 %26 +%325 = OpBitwiseXor %183 %323 %324 +%326 = OpShiftLeftLogical %8 %18 %26 +%327 = OpShiftLeftLogical %20 %25 %26 %328 = OpCompositeConstruct %172 %18 %18 -%329 = OpCompositeConstruct %172 %7 %7 -%330 = OpIEqual %156 %328 %329 +%329 = OpCompositeConstruct %35 %26 %26 +%330 = OpShiftLeftLogical %172 %328 %329 %331 = OpCompositeConstruct %183 %25 %25 %25 %332 = OpCompositeConstruct %183 %26 %26 %26 -%333 = OpIEqual %101 %331 %332 -%334 = OpCompositeConstruct %27 %14 %14 %14 %14 -%335 = OpCompositeConstruct %27 %3 %3 %3 %3 -%336 = OpFOrdEqual %29 %334 %335 -%337 = OpINotEqual %10 %18 %7 -%338 = OpINotEqual %10 %25 %26 -%339 = OpFOrdNotEqual %10 %14 %3 -%340 = OpCompositeConstruct %172 %18 %18 -%341 = OpCompositeConstruct %172 %7 %7 -%342 = OpINotEqual %156 %340 %341 -%343 = OpCompositeConstruct %183 %25 %25 %25 -%344 = OpCompositeConstruct %183 %26 %26 %26 -%345 = OpINotEqual %101 %343 %344 -%346 = OpCompositeConstruct %27 %14 %14 %14 %14 -%347 = OpCompositeConstruct %27 %3 %3 %3 %3 -%348 = OpFOrdNotEqual %29 %346 %347 -%349 = OpSLessThan %10 %18 %7 -%350 = OpULessThan %10 %25 %26 -%351 = OpFOrdLessThan %10 %14 %3 -%352 = OpCompositeConstruct %172 %18 %18 -%353 = OpCompositeConstruct %172 %7 %7 -%354 = OpSLessThan %156 %352 %353 -%355 = OpCompositeConstruct %183 %25 %25 %25 -%356 = OpCompositeConstruct %183 %26 %26 %26 -%357 = OpULessThan %101 %355 %356 -%358 = OpCompositeConstruct %27 %14 %14 %14 %14 -%359 = OpCompositeConstruct %27 %3 %3 %3 %3 -%360 = OpFOrdLessThan %29 %358 %359 -%361 = OpSLessThanEqual %10 %18 %7 -%362 = OpULessThanEqual %10 %25 %26 -%363 = OpFOrdLessThanEqual %10 %14 %3 -%364 = OpCompositeConstruct %172 %18 %18 -%365 = OpCompositeConstruct %172 %7 %7 -%366 = OpSLessThanEqual %156 %364 %365 -%367 = OpCompositeConstruct %183 %25 %25 %25 -%368 = OpCompositeConstruct %183 %26 %26 %26 -%369 = OpULessThanEqual %101 %367 %368 -%370 = OpCompositeConstruct %27 %14 %14 %14 %14 -%371 = OpCompositeConstruct %27 %3 %3 %3 %3 -%372 = OpFOrdLessThanEqual %29 %370 %371 -%373 = OpSGreaterThan %10 %18 %7 -%374 = OpUGreaterThan %10 %25 %26 -%375 = OpFOrdGreaterThan %10 %14 %3 -%376 = OpCompositeConstruct %172 %18 %18 -%377 = OpCompositeConstruct %172 %7 %7 -%378 = OpSGreaterThan %156 %376 %377 -%379 = OpCompositeConstruct %183 %25 %25 %25 -%380 = OpCompositeConstruct %183 %26 %26 %26 -%381 = OpUGreaterThan %101 %379 %380 -%382 = OpCompositeConstruct %27 %14 %14 %14 %14 -%383 = OpCompositeConstruct %27 %3 %3 %3 %3 -%384 = OpFOrdGreaterThan %29 %382 %383 -%385 = OpSGreaterThanEqual %10 %18 %7 -%386 = OpUGreaterThanEqual %10 %25 %26 -%387 = OpFOrdGreaterThanEqual %10 %14 %3 -%388 = OpCompositeConstruct %172 %18 %18 -%389 = OpCompositeConstruct %172 %7 %7 -%390 = OpSGreaterThanEqual %156 %388 %389 -%391 = OpCompositeConstruct %183 %25 %25 %25 -%392 = OpCompositeConstruct %183 %26 %26 %26 -%393 = OpUGreaterThanEqual %101 %391 %392 -%394 = OpCompositeConstruct %27 %14 %14 %14 %14 -%395 = OpCompositeConstruct %27 %3 %3 %3 %3 -%396 = OpFOrdGreaterThanEqual %29 %394 %395 +%333 = OpShiftLeftLogical %183 %331 %332 +%334 = OpShiftRightArithmetic %8 %18 %26 +%335 = OpShiftRightLogical %20 %25 %26 +%336 = OpCompositeConstruct %172 %18 %18 +%337 = OpCompositeConstruct %35 %26 %26 +%338 = OpShiftRightArithmetic %172 %336 %337 +%339 = OpCompositeConstruct %183 %25 %25 %25 +%340 = OpCompositeConstruct %183 %26 %26 %26 +%341 = OpShiftRightLogical %183 %339 %340 OpReturn OpFunctionEnd -%399 = OpFunction %2 None %153 -%398 = OpLabel -%397 = OpVariable %112 Function %7 -OpBranch %400 -%400 = OpLabel -%401 = OpLoad %8 %397 -%402 = OpIAdd %8 %401 %7 -OpStore %397 %402 -%403 = OpLoad %8 %397 -%404 = OpISub %8 %403 %7 -OpStore %397 %404 -%405 = OpLoad %8 %397 -%406 = OpLoad %8 %397 -%407 = OpIMul %8 %405 %406 -OpStore %397 %407 -%408 = OpLoad %8 %397 -%409 = OpLoad %8 %397 -%410 = OpSDiv %8 %408 %409 -OpStore %397 %410 -%411 = OpLoad %8 %397 -%412 = OpSMod %8 %411 %7 -OpStore %397 %412 -%413 = OpLoad %8 %397 -%414 = OpBitwiseAnd %8 %413 %11 -OpStore %397 %414 -%415 = OpLoad %8 %397 -%416 = OpBitwiseOr %8 %415 %11 -OpStore %397 %416 -%417 = OpLoad %8 %397 -%418 = OpBitwiseXor %8 %417 %11 -OpStore %397 %418 -%419 = OpLoad %8 %397 -%420 = OpShiftLeftLogical %8 %419 %25 -OpStore %397 %420 -%421 = OpLoad %8 %397 -%422 = OpShiftRightArithmetic %8 %421 %26 -OpStore %397 %422 -%423 = OpLoad %8 %397 -%424 = OpIAdd %8 %423 %7 -OpStore %397 %424 -%425 = OpLoad %8 %397 -%426 = OpISub %8 %425 %7 -OpStore %397 %426 +%343 = OpFunction %2 None %153 +%342 = OpLabel +OpBranch %344 +%344 = OpLabel +%345 = OpIEqual %10 %18 %7 +%346 = OpIEqual %10 %25 %26 +%347 = OpFOrdEqual %10 %14 %3 +%348 = OpCompositeConstruct %172 %18 %18 +%349 = OpCompositeConstruct %172 %7 %7 +%350 = OpIEqual %156 %348 %349 +%351 = OpCompositeConstruct %183 %25 %25 %25 +%352 = OpCompositeConstruct %183 %26 %26 %26 +%353 = OpIEqual %101 %351 %352 +%354 = OpCompositeConstruct %27 %14 %14 %14 %14 +%355 = OpCompositeConstruct %27 %3 %3 %3 %3 +%356 = OpFOrdEqual %29 %354 %355 +%357 = OpINotEqual %10 %18 %7 +%358 = OpINotEqual %10 %25 %26 +%359 = OpFOrdNotEqual %10 %14 %3 +%360 = OpCompositeConstruct %172 %18 %18 +%361 = OpCompositeConstruct %172 %7 %7 +%362 = OpINotEqual %156 %360 %361 +%363 = OpCompositeConstruct %183 %25 %25 %25 +%364 = OpCompositeConstruct %183 %26 %26 %26 +%365 = OpINotEqual %101 %363 %364 +%366 = OpCompositeConstruct %27 %14 %14 %14 %14 +%367 = OpCompositeConstruct %27 %3 %3 %3 %3 +%368 = OpFOrdNotEqual %29 %366 %367 +%369 = OpSLessThan %10 %18 %7 +%370 = OpULessThan %10 %25 %26 +%371 = OpFOrdLessThan %10 %14 %3 +%372 = OpCompositeConstruct %172 %18 %18 +%373 = OpCompositeConstruct %172 %7 %7 +%374 = OpSLessThan %156 %372 %373 +%375 = OpCompositeConstruct %183 %25 %25 %25 +%376 = OpCompositeConstruct %183 %26 %26 %26 +%377 = OpULessThan %101 %375 %376 +%378 = OpCompositeConstruct %27 %14 %14 %14 %14 +%379 = OpCompositeConstruct %27 %3 %3 %3 %3 +%380 = OpFOrdLessThan %29 %378 %379 +%381 = OpSLessThanEqual %10 %18 %7 +%382 = OpULessThanEqual %10 %25 %26 +%383 = OpFOrdLessThanEqual %10 %14 %3 +%384 = OpCompositeConstruct %172 %18 %18 +%385 = OpCompositeConstruct %172 %7 %7 +%386 = OpSLessThanEqual %156 %384 %385 +%387 = OpCompositeConstruct %183 %25 %25 %25 +%388 = OpCompositeConstruct %183 %26 %26 %26 +%389 = OpULessThanEqual %101 %387 %388 +%390 = OpCompositeConstruct %27 %14 %14 %14 %14 +%391 = OpCompositeConstruct %27 %3 %3 %3 %3 +%392 = OpFOrdLessThanEqual %29 %390 %391 +%393 = OpSGreaterThan %10 %18 %7 +%394 = OpUGreaterThan %10 %25 %26 +%395 = OpFOrdGreaterThan %10 %14 %3 +%396 = OpCompositeConstruct %172 %18 %18 +%397 = OpCompositeConstruct %172 %7 %7 +%398 = OpSGreaterThan %156 %396 %397 +%399 = OpCompositeConstruct %183 %25 %25 %25 +%400 = OpCompositeConstruct %183 %26 %26 %26 +%401 = OpUGreaterThan %101 %399 %400 +%402 = OpCompositeConstruct %27 %14 %14 %14 %14 +%403 = OpCompositeConstruct %27 %3 %3 %3 %3 +%404 = OpFOrdGreaterThan %29 %402 %403 +%405 = OpSGreaterThanEqual %10 %18 %7 +%406 = OpUGreaterThanEqual %10 %25 %26 +%407 = OpFOrdGreaterThanEqual %10 %14 %3 +%408 = OpCompositeConstruct %172 %18 %18 +%409 = OpCompositeConstruct %172 %7 %7 +%410 = OpSGreaterThanEqual %156 %408 %409 +%411 = OpCompositeConstruct %183 %25 %25 %25 +%412 = OpCompositeConstruct %183 %26 %26 %26 +%413 = OpUGreaterThanEqual %101 %411 %412 +%414 = OpCompositeConstruct %27 %14 %14 %14 %14 +%415 = OpCompositeConstruct %27 %3 %3 %3 %3 +%416 = OpFOrdGreaterThanEqual %29 %414 %415 OpReturn OpFunctionEnd -%428 = OpFunction %2 None %153 -%427 = OpLabel -OpBranch %429 -%429 = OpLabel -%430 = OpFunctionCall %27 %56 -%431 = OpFunctionCall %27 %81 -%432 = OpVectorShuffle %30 %41 %41 0 1 2 -%433 = OpFunctionCall %30 %98 %432 -%434 = OpFunctionCall %4 %129 -%435 = OpFunctionCall %2 %152 -%436 = OpFunctionCall %2 %170 -%437 = OpFunctionCall %2 %274 -%438 = OpFunctionCall %2 %323 -%439 = OpFunctionCall %2 %399 +%419 = OpFunction %2 None %153 +%418 = OpLabel +%417 = OpVariable %112 Function %7 +OpBranch %420 +%420 = OpLabel +%421 = OpLoad %8 %417 +%422 = OpIAdd %8 %421 %7 +OpStore %417 %422 +%423 = OpLoad %8 %417 +%424 = OpISub %8 %423 %7 +OpStore %417 %424 +%425 = OpLoad %8 %417 +%426 = OpLoad %8 %417 +%427 = OpIMul %8 %425 %426 +OpStore %417 %427 +%428 = OpLoad %8 %417 +%429 = OpLoad %8 %417 +%430 = OpSDiv %8 %428 %429 +OpStore %417 %430 +%431 = OpLoad %8 %417 +%432 = OpSMod %8 %431 %7 +OpStore %417 %432 +%433 = OpLoad %8 %417 +%434 = OpBitwiseAnd %8 %433 %11 +OpStore %417 %434 +%435 = OpLoad %8 %417 +%436 = OpBitwiseOr %8 %435 %11 +OpStore %417 %436 +%437 = OpLoad %8 %417 +%438 = OpBitwiseXor %8 %437 %11 +OpStore %417 %438 +%439 = OpLoad %8 %417 +%440 = OpShiftLeftLogical %8 %439 %25 +OpStore %417 %440 +%441 = OpLoad %8 %417 +%442 = OpShiftRightArithmetic %8 %441 %26 +OpStore %417 %442 +%443 = OpLoad %8 %417 +%444 = OpIAdd %8 %443 %7 +OpStore %417 %444 +%445 = OpLoad %8 %417 +%446 = OpISub %8 %445 %7 +OpStore %417 %446 +OpReturn +OpFunctionEnd +%448 = OpFunction %2 None %153 +%447 = OpLabel +OpBranch %449 +%449 = OpLabel +%450 = OpFunctionCall %27 %56 +%451 = OpFunctionCall %27 %81 +%452 = OpVectorShuffle %30 %41 %41 0 1 2 +%453 = OpFunctionCall %30 %98 %452 +%454 = OpFunctionCall %4 %129 +%455 = OpFunctionCall %2 %152 +%456 = OpFunctionCall %2 %170 +%457 = OpFunctionCall %2 %294 +%458 = OpFunctionCall %2 %343 +%459 = OpFunctionCall %2 %419 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index ca9877b66..c504b2f84 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -108,77 +108,79 @@ fn arithmetic() { let unnamed_58 = (vec2(2) / vec2(1)); let unnamed_59 = (vec2(2) % vec2(1)); let unnamed_60 = (vec2(2) % vec2(1)); - let unnamed_61 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - let unnamed_62 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_63 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - let unnamed_64 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_65 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + let unnamed_61 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_62 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_63 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + let unnamed_64 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_65 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + let unnamed_66 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_67 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } fn bit() { - let unnamed_66 = ~(1); - let unnamed_67 = ~(1u); - let unnamed_68 = !(vec2(1)); - let unnamed_69 = !(vec3(1u)); - let unnamed_70 = (2 | 1); - let unnamed_71 = (2u | 1u); - let unnamed_72 = (vec2(2) | vec2(1)); - let unnamed_73 = (vec3(2u) | vec3(1u)); - let unnamed_74 = (2 & 1); - let unnamed_75 = (2u & 1u); - let unnamed_76 = (vec2(2) & vec2(1)); - let unnamed_77 = (vec3(2u) & vec3(1u)); - let unnamed_78 = (2 ^ 1); - let unnamed_79 = (2u ^ 1u); - let unnamed_80 = (vec2(2) ^ vec2(1)); - let unnamed_81 = (vec3(2u) ^ vec3(1u)); - let unnamed_82 = (2 << 1u); - let unnamed_83 = (2u << 1u); - let unnamed_84 = (vec2(2) << vec2(1u)); - let unnamed_85 = (vec3(2u) << vec3(1u)); - let unnamed_86 = (2 >> 1u); - let unnamed_87 = (2u >> 1u); - let unnamed_88 = (vec2(2) >> vec2(1u)); - let unnamed_89 = (vec3(2u) >> vec3(1u)); + let unnamed_68 = ~(1); + let unnamed_69 = ~(1u); + let unnamed_70 = !(vec2(1)); + let unnamed_71 = !(vec3(1u)); + let unnamed_72 = (2 | 1); + let unnamed_73 = (2u | 1u); + let unnamed_74 = (vec2(2) | vec2(1)); + let unnamed_75 = (vec3(2u) | vec3(1u)); + let unnamed_76 = (2 & 1); + let unnamed_77 = (2u & 1u); + let unnamed_78 = (vec2(2) & vec2(1)); + let unnamed_79 = (vec3(2u) & vec3(1u)); + let unnamed_80 = (2 ^ 1); + let unnamed_81 = (2u ^ 1u); + let unnamed_82 = (vec2(2) ^ vec2(1)); + let unnamed_83 = (vec3(2u) ^ vec3(1u)); + let unnamed_84 = (2 << 1u); + let unnamed_85 = (2u << 1u); + let unnamed_86 = (vec2(2) << vec2(1u)); + let unnamed_87 = (vec3(2u) << vec3(1u)); + let unnamed_88 = (2 >> 1u); + let unnamed_89 = (2u >> 1u); + let unnamed_90 = (vec2(2) >> vec2(1u)); + let unnamed_91 = (vec3(2u) >> vec3(1u)); } fn comparison() { - let unnamed_90 = (2 == 1); - let unnamed_91 = (2u == 1u); - let unnamed_92 = (2.0 == 1.0); - let unnamed_93 = (vec2(2) == vec2(1)); - let unnamed_94 = (vec3(2u) == vec3(1u)); - let unnamed_95 = (vec4(2.0) == vec4(1.0)); - let unnamed_96 = (2 != 1); - let unnamed_97 = (2u != 1u); - let unnamed_98 = (2.0 != 1.0); - let unnamed_99 = (vec2(2) != vec2(1)); - let unnamed_100 = (vec3(2u) != vec3(1u)); - let unnamed_101 = (vec4(2.0) != vec4(1.0)); - let unnamed_102 = (2 < 1); - let unnamed_103 = (2u < 1u); - let unnamed_104 = (2.0 < 1.0); - let unnamed_105 = (vec2(2) < vec2(1)); - let unnamed_106 = (vec3(2u) < vec3(1u)); - let unnamed_107 = (vec4(2.0) < vec4(1.0)); - let unnamed_108 = (2 <= 1); - let unnamed_109 = (2u <= 1u); - let unnamed_110 = (2.0 <= 1.0); - let unnamed_111 = (vec2(2) <= vec2(1)); - let unnamed_112 = (vec3(2u) <= vec3(1u)); - let unnamed_113 = (vec4(2.0) <= vec4(1.0)); - let unnamed_114 = (2 > 1); - let unnamed_115 = (2u > 1u); - let unnamed_116 = (2.0 > 1.0); - let unnamed_117 = (vec2(2) > vec2(1)); - let unnamed_118 = (vec3(2u) > vec3(1u)); - let unnamed_119 = (vec4(2.0) > vec4(1.0)); - let unnamed_120 = (2 >= 1); - let unnamed_121 = (2u >= 1u); - let unnamed_122 = (2.0 >= 1.0); - let unnamed_123 = (vec2(2) >= vec2(1)); - let unnamed_124 = (vec3(2u) >= vec3(1u)); - let unnamed_125 = (vec4(2.0) >= vec4(1.0)); + let unnamed_92 = (2 == 1); + let unnamed_93 = (2u == 1u); + let unnamed_94 = (2.0 == 1.0); + let unnamed_95 = (vec2(2) == vec2(1)); + let unnamed_96 = (vec3(2u) == vec3(1u)); + let unnamed_97 = (vec4(2.0) == vec4(1.0)); + let unnamed_98 = (2 != 1); + let unnamed_99 = (2u != 1u); + let unnamed_100 = (2.0 != 1.0); + let unnamed_101 = (vec2(2) != vec2(1)); + let unnamed_102 = (vec3(2u) != vec3(1u)); + let unnamed_103 = (vec4(2.0) != vec4(1.0)); + let unnamed_104 = (2 < 1); + let unnamed_105 = (2u < 1u); + let unnamed_106 = (2.0 < 1.0); + let unnamed_107 = (vec2(2) < vec2(1)); + let unnamed_108 = (vec3(2u) < vec3(1u)); + let unnamed_109 = (vec4(2.0) < vec4(1.0)); + let unnamed_110 = (2 <= 1); + let unnamed_111 = (2u <= 1u); + let unnamed_112 = (2.0 <= 1.0); + let unnamed_113 = (vec2(2) <= vec2(1)); + let unnamed_114 = (vec3(2u) <= vec3(1u)); + let unnamed_115 = (vec4(2.0) <= vec4(1.0)); + let unnamed_116 = (2 > 1); + let unnamed_117 = (2u > 1u); + let unnamed_118 = (2.0 > 1.0); + let unnamed_119 = (vec2(2) > vec2(1)); + let unnamed_120 = (vec3(2u) > vec3(1u)); + let unnamed_121 = (vec4(2.0) > vec4(1.0)); + let unnamed_122 = (2 >= 1); + let unnamed_123 = (2u >= 1u); + let unnamed_124 = (2.0 >= 1.0); + let unnamed_125 = (vec2(2) >= vec2(1)); + let unnamed_126 = (vec3(2u) >= vec3(1u)); + let unnamed_127 = (vec4(2.0) >= vec4(1.0)); } fn assignment() { From 6e6daad4d4471f22356b8248c2c03595112a5d6b Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 16:14:53 +0200 Subject: [PATCH 1680/2212] [hlsl-out] fix bool splat --- src/back/hlsl/writer.rs | 4 +- tests/out/hlsl/access.hlsl | 16 ++-- tests/out/hlsl/boids.hlsl | 4 +- tests/out/hlsl/functions.hlsl | 10 +-- tests/out/hlsl/globals.hlsl | 2 +- tests/out/hlsl/image.hlsl | 18 ++-- tests/out/hlsl/interface.hlsl | 2 +- tests/out/hlsl/math-functions.hlsl | 2 +- tests/out/hlsl/operators.hlsl | 136 ++++++++++++++--------------- tests/out/hlsl/padding.hlsl | 2 +- 10 files changed, 97 insertions(+), 99 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index a0992b0a2..62a07f4e5 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2286,11 +2286,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { crate::VectorSize::Tri => "xxx", crate::VectorSize::Quad => "xxxx", }; - let resolved = func_ctx.info[expr].ty.inner_with(&module.types); - self.write_value_type(module, resolved)?; write!(self.out, "(")?; self.write_expr(module, value, func_ctx)?; - write!(self.out, ".{})", number_of_components)? + write!(self.out, ").{}", number_of_components)? } Expression::Select { condition, diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 4a807a49f..21b9da81a 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -88,13 +88,13 @@ void test_matrix_within_struct_accesses() int _expr44 = idx; float _expr46 = GetMatmOnBaz(baz)[_expr42][_expr44]; unnamed_7 = _expr46; - t = ConstructBaz(float3x2(float2(1.0.xx), float2(2.0.xx), float2(3.0.xx))); + t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); int _expr57 = idx; idx = (_expr57 + 1); - SetMatmOnBaz(t, float3x2(float2(6.0.xx), float2(5.0.xx), float2(4.0.xx))); - t.m_0 = float2(9.0.xx); + SetMatmOnBaz(t, float3x2((6.0).xx, (5.0).xx, (4.0).xx)); + t.m_0 = (9.0).xx; int _expr74 = idx; - SetMatVecmOnBaz(t, float2(90.0.xx), _expr74); + SetMatVecmOnBaz(t, (90.0).xx, _expr74); t.m_0[1] = 10.0; int _expr87 = idx; t.m_0[_expr87] = 20.0; @@ -151,7 +151,7 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position int value = c[vi]; const float _e42 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); unnamed = _e42; - return float4(mul(float4(int4(value.xxxx)), matrix_), 2.0); + return float4(mul(float4((value).xxxx), matrix_), 2.0); } uint2 Constructarray2_uint2_(uint2 arg0, uint2 arg1)[2] { @@ -163,19 +163,19 @@ float4 foo_frag() : SV_Target0 { bar.Store(8+16+0, asuint(1.0)); { - float4x3 _value2 = float4x3(float3(0.0.xxx), float3(1.0.xxx), float3(2.0.xxx), float3(3.0.xxx)); + float4x3 _value2 = float4x3((0.0).xxx, (1.0).xxx, (2.0).xxx, (3.0).xxx); bar.Store3(0+0, asuint(_value2[0])); bar.Store3(0+16, asuint(_value2[1])); bar.Store3(0+32, asuint(_value2[2])); bar.Store3(0+48, asuint(_value2[3])); } { - uint2 _value2[2] = Constructarray2_uint2_(uint2(0u.xx), uint2(1u.xx)); + uint2 _value2[2] = Constructarray2_uint2_((0u).xx, (1u).xx); bar.Store2(104+0, asuint(_value2[0])); bar.Store2(104+8, asuint(_value2[1])); } bar.Store(0+8+120, asuint(1)); - return float4(0.0.xxxx); + return (0.0).xxxx; } [numthreads(1, 1, 1)] diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index 34798d5e3..5fea9fc17 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -100,13 +100,13 @@ void main(uint3 global_invocation_id : SV_DispatchThreadID) float2 _expr92 = cMass; int _expr93 = cMassCount; float2 _expr97 = vPos; - cMass = ((_expr92 / float2(float(_expr93).xx)) - _expr97); + cMass = ((_expr92 / (float(_expr93)).xx) - _expr97); } int _expr99 = cVelCount; if ((_expr99 > 0)) { float2 _expr102 = cVel; int _expr103 = cVelCount; - cVel = (_expr102 / float2(float(_expr103).xx)); + cVel = (_expr102 / (float(_expr103)).xx); } float2 _expr107 = vVel; float2 _expr108 = cMass; diff --git a/tests/out/hlsl/functions.hlsl b/tests/out/hlsl/functions.hlsl index c1b420f22..04a340415 100644 --- a/tests/out/hlsl/functions.hlsl +++ b/tests/out/hlsl/functions.hlsl @@ -9,13 +9,13 @@ float2 test_fma() int test_integer_dot_product() { - int2 a_2_ = int2(1.xx); - int2 b_2_ = int2(1.xx); + int2 a_2_ = (1).xx; + int2 b_2_ = (1).xx; int c_2_ = dot(a_2_, b_2_); - uint3 a_3_ = uint3(1u.xxx); - uint3 b_3_ = uint3(1u.xxx); + uint3 a_3_ = (1u).xxx; + uint3 b_3_ = (1u).xxx; uint c_3_ = dot(a_3_, b_3_); - int c_4_ = dot(int4(4.xxxx), int4(2.xxxx)); + int c_4_ = dot((4).xxxx, (2).xxxx); return c_4_; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index cb9e1b4bb..ba5e7e7fb 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -22,7 +22,7 @@ void test_msl_packed_vec3_() { int idx = 1; - alignment.Store3(0, asuint(float3(1.0.xxx))); + alignment.Store3(0, asuint((1.0).xxx)); alignment.Store(0+0, asuint(1.0)); alignment.Store(0+0, asuint(2.0)); int _expr21 = idx; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 840352ff9..d7a6f5c0f 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -46,7 +46,7 @@ void depth_load(uint3 local_id_1 : SV_GroupThreadID) int2 dim_1 = NagaRWDimensions2D(image_storage_src); int2 itc_1 = ((dim_1 * int2(local_id_1.xy)) % int2(10, 20)); float val = image_depth_multisampled_src.Load(itc_1, int(local_id_1.z)).x; - image_dst[itc_1.x] = uint4(uint(val).xxxx); + image_dst[itc_1.x] = (uint(val)).xxxx; return; } @@ -157,7 +157,7 @@ float4 queries() : SV_Position int3 dim_3d_lod = NagaMipDimensions3D(image_3d, 1); int2 dim_2s_ms = NagaMSDimensions2D(image_aa); int sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); - return float4(float(sum).xxxx); + return (float(sum)).xxxx; } int NagaNumLevels2D(Texture2D tex) @@ -227,12 +227,12 @@ float4 levels_queries() : SV_Position int num_levels_3d = NagaNumLevels3D(image_3d); int num_samples_aa = NagaMSNumSamples2D(image_aa); int sum_1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); - return float4(float(sum_1).xxxx); + return (float(sum_1)).xxxx; } float4 sample_() : SV_Target0 { - float2 tc = float2(0.5.xx); + float2 tc = (0.5).xx; float4 s1d = image_1d.Sample(sampler_reg, tc.x); float4 s2d = image_2d.Sample(sampler_reg, tc); float4 s2d_offset = image_2d.Sample(sampler_reg, tc, int2(3, 1)); @@ -244,16 +244,16 @@ float4 sample_() : SV_Target0 float sample_comparison() : SV_Target0 { - float2 tc_1 = float2(0.5.xx); + float2 tc_1 = (0.5).xx; float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc_1, 0.5); float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc_1, 0.5); - float scube_depth_level = image_cube_depth.SampleCmpLevelZero(sampler_cmp, float3(0.5.xxx), 0.5); + float scube_depth_level = image_cube_depth.SampleCmpLevelZero(sampler_cmp, (0.5).xxx, 0.5); return (s2d_depth + s2d_depth_level); } float4 gather() : SV_Target0 { - float2 tc_2 = float2(0.5.xx); + float2 tc_2 = (0.5).xx; float4 s2d_1 = image_2d.GatherGreen(sampler_reg, tc_2); float4 s2d_offset_1 = image_2d.GatherAlpha(sampler_reg, tc_2, int2(3, 1)); float4 s2d_depth_1 = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5); @@ -263,8 +263,8 @@ float4 gather() : SV_Target0 float4 depth_no_comparison() : SV_Target0 { - float2 tc_3 = float2(0.5.xx); + float2 tc_3 = (0.5).xx; float s2d_2 = image_2d_depth.Sample(sampler_reg, tc_3); float4 s2d_gather = image_2d_depth.Gather(sampler_reg, tc_3); - return (float4(s2d_2.xxxx) + s2d_gather); + return ((s2d_2).xxxx + s2d_gather); } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 8737a5c70..23a2d05d0 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -49,7 +49,7 @@ VertexOutput ConstructVertexOutput(float4 arg0, float arg1) { VertexOutput_vertex vertex(uint vertex_index : SV_VertexID, uint instance_index : SV_InstanceID, uint color : LOC10) { uint tmp = (((_NagaConstants.base_vertex + vertex_index) + (_NagaConstants.base_instance + instance_index)) + color); - const VertexOutput vertexoutput = ConstructVertexOutput(float4(1.0.xxxx), float(tmp)); + const VertexOutput vertexoutput = ConstructVertexOutput((1.0).xxxx, float(tmp)); const VertexOutput_vertex vertexoutput_1 = { vertexoutput.varying, vertexoutput.position }; return vertexoutput_1; } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index 5d869f7c9..584c4c4ff 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -1,7 +1,7 @@ void main() { - float4 v = float4(0.0.xxxx); + float4 v = (0.0).xxxx; float a = degrees(1.0); float b = radians(1.0); float4 c = degrees(v); diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index e640cfaff..c6e03def9 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -33,13 +33,13 @@ float4 builtins() float b1_ = float(int4(1, 1, 1, 1).x); float4 b2_ = float4(int4(1, 1, 1, 1)); int4 v_i32_zero = int4(float4(0.0, 0.0, 0.0, 0.0)); - return (((((float4((int4(s1_.xxxx) + v_i32_zero)) + s2_) + m1_) + m2_) + float4(b1_.xxxx)) + b2_); + return (((((float4(((s1_).xxxx + v_i32_zero)) + s2_) + m1_) + m2_) + (b1_).xxxx) + b2_); } float4 splat() { - float2 a_1 = (((float2(1.0.xx) + float2(2.0.xx)) - float2(3.0.xx)) / float2(4.0.xx)); - int4 b = (int4(5.xxxx) % int4(2.xxxx)); + float2 a_1 = ((((1.0).xx + (2.0).xx) - (3.0).xx) / (4.0).xx); + int4 b = ((5).xxxx % (2).xxxx); return (a_1.xyxy + float4(b)); } @@ -69,11 +69,11 @@ float constructors() float2x2 unnamed_9 = (float2x2)0; int unnamed_10[4] = {(int)0,(int)0,(int)0,(int)0}; - foo = ConstructFoo(float4(1.0.xxxx), 1); + foo = ConstructFoo((1.0).xxxx, 1); float2x2 mat2comp = float2x2(float2(1.0, 0.0), float2(0.0, 1.0)); float4x4 mat4comp = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); - unnamed_8 = uint2(0u.xx); - unnamed_9 = float2x2(float2(0.0.xx), float2(0.0.xx)); + unnamed_8 = (0u).xx; + unnamed_9 = float2x2((0.0).xx, (0.0).xx); { int _result[4]=Constructarray4_int_(0, 1, 2, 3); for(int _i=0; _i<4; ++_i) unnamed_10[_i] = _result[_i]; @@ -85,65 +85,65 @@ float constructors() void logical() { bool unnamed_11 = !true; - bool2 unnamed_12 = !bool2(true.xx); + bool2 unnamed_12 = !(true).xx; bool unnamed_13 = (true || false); bool unnamed_14 = (true && false); bool unnamed_15 = (true | false); - bool3 unnamed_16 = (bool3(true.xxx) | bool3(false.xxx)); + bool3 unnamed_16 = ((true).xxx | (false).xxx); bool unnamed_17 = (true & false); - bool4 unnamed_18 = (bool4(true.xxxx) & bool4(false.xxxx)); + bool4 unnamed_18 = ((true).xxxx & (false).xxxx); } void arithmetic() { - int2 unnamed_19 = -int2(1.xx); - float2 unnamed_20 = -float2(1.0.xx); + int2 unnamed_19 = -(1).xx; + float2 unnamed_20 = -(1.0).xx; int unnamed_21 = (2 + 1); uint unnamed_22 = (2u + 1u); float unnamed_23 = (2.0 + 1.0); - int2 unnamed_24 = (int2(2.xx) + int2(1.xx)); - uint3 unnamed_25 = (uint3(2u.xxx) + uint3(1u.xxx)); - float4 unnamed_26 = (float4(2.0.xxxx) + float4(1.0.xxxx)); + int2 unnamed_24 = ((2).xx + (1).xx); + uint3 unnamed_25 = ((2u).xxx + (1u).xxx); + float4 unnamed_26 = ((2.0).xxxx + (1.0).xxxx); int unnamed_27 = (2 - 1); uint unnamed_28 = (2u - 1u); float unnamed_29 = (2.0 - 1.0); - int2 unnamed_30 = (int2(2.xx) - int2(1.xx)); - uint3 unnamed_31 = (uint3(2u.xxx) - uint3(1u.xxx)); - float4 unnamed_32 = (float4(2.0.xxxx) - float4(1.0.xxxx)); + int2 unnamed_30 = ((2).xx - (1).xx); + uint3 unnamed_31 = ((2u).xxx - (1u).xxx); + float4 unnamed_32 = ((2.0).xxxx - (1.0).xxxx); int unnamed_33 = (2 * 1); uint unnamed_34 = (2u * 1u); float unnamed_35 = (2.0 * 1.0); - int2 unnamed_36 = (int2(2.xx) * int2(1.xx)); - uint3 unnamed_37 = (uint3(2u.xxx) * uint3(1u.xxx)); - float4 unnamed_38 = (float4(2.0.xxxx) * float4(1.0.xxxx)); + int2 unnamed_36 = ((2).xx * (1).xx); + uint3 unnamed_37 = ((2u).xxx * (1u).xxx); + float4 unnamed_38 = ((2.0).xxxx * (1.0).xxxx); int unnamed_39 = (2 / 1); uint unnamed_40 = (2u / 1u); float unnamed_41 = (2.0 / 1.0); - int2 unnamed_42 = (int2(2.xx) / int2(1.xx)); - uint3 unnamed_43 = (uint3(2u.xxx) / uint3(1u.xxx)); - float4 unnamed_44 = (float4(2.0.xxxx) / float4(1.0.xxxx)); + int2 unnamed_42 = ((2).xx / (1).xx); + uint3 unnamed_43 = ((2u).xxx / (1u).xxx); + float4 unnamed_44 = ((2.0).xxxx / (1.0).xxxx); int unnamed_45 = (2 % 1); uint unnamed_46 = (2u % 1u); float unnamed_47 = (2.0 % 1.0); - int2 unnamed_48 = (int2(2.xx) % int2(1.xx)); - uint3 unnamed_49 = (uint3(2u.xxx) % uint3(1u.xxx)); - float4 unnamed_50 = (float4(2.0.xxxx) % float4(1.0.xxxx)); - int2 unnamed_51 = (int2(2.xx) + int2(1.xx)); - int2 unnamed_52 = (int2(2.xx) + int2(1.xx)); - int2 unnamed_53 = (int2(2.xx) - int2(1.xx)); - int2 unnamed_54 = (int2(2.xx) - int2(1.xx)); - int2 unnamed_55 = (int2(2.xx) * 1); - int2 unnamed_56 = (2 * int2(1.xx)); - int2 unnamed_57 = (int2(2.xx) / int2(1.xx)); - int2 unnamed_58 = (int2(2.xx) / int2(1.xx)); - int2 unnamed_59 = (int2(2.xx) % int2(1.xx)); - int2 unnamed_60 = (int2(2.xx) % int2(1.xx)); + int2 unnamed_48 = ((2).xx % (1).xx); + uint3 unnamed_49 = ((2u).xxx % (1u).xxx); + float4 unnamed_50 = ((2.0).xxxx % (1.0).xxxx); + int2 unnamed_51 = ((2).xx + (1).xx); + int2 unnamed_52 = ((2).xx + (1).xx); + int2 unnamed_53 = ((2).xx - (1).xx); + int2 unnamed_54 = ((2).xx - (1).xx); + int2 unnamed_55 = ((2).xx * 1); + int2 unnamed_56 = (2 * (1).xx); + int2 unnamed_57 = ((2).xx / (1).xx); + int2 unnamed_58 = ((2).xx / (1).xx); + int2 unnamed_59 = ((2).xx % (1).xx); + int2 unnamed_60 = ((2).xx % (1).xx); float3x3 unnamed_61 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); float3x3 unnamed_62 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); float3x3 unnamed_63 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); float3x3 unnamed_64 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); - float3 unnamed_65 = mul(float4(1.0.xxxx), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float4 unnamed_66 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), float3(2.0.xxx)); + float3 unnamed_65 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float4 unnamed_66 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); float3x3 unnamed_67 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); } @@ -151,28 +151,28 @@ void bit() { int unnamed_68 = ~1; uint unnamed_69 = ~1u; - int2 unnamed_70 = ~int2(1.xx); - uint3 unnamed_71 = ~uint3(1u.xxx); + int2 unnamed_70 = ~(1).xx; + uint3 unnamed_71 = ~(1u).xxx; int unnamed_72 = (2 | 1); uint unnamed_73 = (2u | 1u); - int2 unnamed_74 = (int2(2.xx) | int2(1.xx)); - uint3 unnamed_75 = (uint3(2u.xxx) | uint3(1u.xxx)); + int2 unnamed_74 = ((2).xx | (1).xx); + uint3 unnamed_75 = ((2u).xxx | (1u).xxx); int unnamed_76 = (2 & 1); uint unnamed_77 = (2u & 1u); - int2 unnamed_78 = (int2(2.xx) & int2(1.xx)); - uint3 unnamed_79 = (uint3(2u.xxx) & uint3(1u.xxx)); + int2 unnamed_78 = ((2).xx & (1).xx); + uint3 unnamed_79 = ((2u).xxx & (1u).xxx); int unnamed_80 = (2 ^ 1); uint unnamed_81 = (2u ^ 1u); - int2 unnamed_82 = (int2(2.xx) ^ int2(1.xx)); - uint3 unnamed_83 = (uint3(2u.xxx) ^ uint3(1u.xxx)); + int2 unnamed_82 = ((2).xx ^ (1).xx); + uint3 unnamed_83 = ((2u).xxx ^ (1u).xxx); int unnamed_84 = (2 << 1u); uint unnamed_85 = (2u << 1u); - int2 unnamed_86 = (int2(2.xx) << uint2(1u.xx)); - uint3 unnamed_87 = (uint3(2u.xxx) << uint3(1u.xxx)); + int2 unnamed_86 = ((2).xx << (1u).xx); + uint3 unnamed_87 = ((2u).xxx << (1u).xxx); int unnamed_88 = (2 >> 1u); uint unnamed_89 = (2u >> 1u); - int2 unnamed_90 = (int2(2.xx) >> uint2(1u.xx)); - uint3 unnamed_91 = (uint3(2u.xxx) >> uint3(1u.xxx)); + int2 unnamed_90 = ((2).xx >> (1u).xx); + uint3 unnamed_91 = ((2u).xxx >> (1u).xxx); } void comparison() @@ -180,39 +180,39 @@ void comparison() bool unnamed_92 = (2 == 1); bool unnamed_93 = (2u == 1u); bool unnamed_94 = (2.0 == 1.0); - bool2 unnamed_95 = (int2(2.xx) == int2(1.xx)); - bool3 unnamed_96 = (uint3(2u.xxx) == uint3(1u.xxx)); - bool4 unnamed_97 = (float4(2.0.xxxx) == float4(1.0.xxxx)); + bool2 unnamed_95 = ((2).xx == (1).xx); + bool3 unnamed_96 = ((2u).xxx == (1u).xxx); + bool4 unnamed_97 = ((2.0).xxxx == (1.0).xxxx); bool unnamed_98 = (2 != 1); bool unnamed_99 = (2u != 1u); bool unnamed_100 = (2.0 != 1.0); - bool2 unnamed_101 = (int2(2.xx) != int2(1.xx)); - bool3 unnamed_102 = (uint3(2u.xxx) != uint3(1u.xxx)); - bool4 unnamed_103 = (float4(2.0.xxxx) != float4(1.0.xxxx)); + bool2 unnamed_101 = ((2).xx != (1).xx); + bool3 unnamed_102 = ((2u).xxx != (1u).xxx); + bool4 unnamed_103 = ((2.0).xxxx != (1.0).xxxx); bool unnamed_104 = (2 < 1); bool unnamed_105 = (2u < 1u); bool unnamed_106 = (2.0 < 1.0); - bool2 unnamed_107 = (int2(2.xx) < int2(1.xx)); - bool3 unnamed_108 = (uint3(2u.xxx) < uint3(1u.xxx)); - bool4 unnamed_109 = (float4(2.0.xxxx) < float4(1.0.xxxx)); + bool2 unnamed_107 = ((2).xx < (1).xx); + bool3 unnamed_108 = ((2u).xxx < (1u).xxx); + bool4 unnamed_109 = ((2.0).xxxx < (1.0).xxxx); bool unnamed_110 = (2 <= 1); bool unnamed_111 = (2u <= 1u); bool unnamed_112 = (2.0 <= 1.0); - bool2 unnamed_113 = (int2(2.xx) <= int2(1.xx)); - bool3 unnamed_114 = (uint3(2u.xxx) <= uint3(1u.xxx)); - bool4 unnamed_115 = (float4(2.0.xxxx) <= float4(1.0.xxxx)); + bool2 unnamed_113 = ((2).xx <= (1).xx); + bool3 unnamed_114 = ((2u).xxx <= (1u).xxx); + bool4 unnamed_115 = ((2.0).xxxx <= (1.0).xxxx); bool unnamed_116 = (2 > 1); bool unnamed_117 = (2u > 1u); bool unnamed_118 = (2.0 > 1.0); - bool2 unnamed_119 = (int2(2.xx) > int2(1.xx)); - bool3 unnamed_120 = (uint3(2u.xxx) > uint3(1u.xxx)); - bool4 unnamed_121 = (float4(2.0.xxxx) > float4(1.0.xxxx)); + bool2 unnamed_119 = ((2).xx > (1).xx); + bool3 unnamed_120 = ((2u).xxx > (1u).xxx); + bool4 unnamed_121 = ((2.0).xxxx > (1.0).xxxx); bool unnamed_122 = (2 >= 1); bool unnamed_123 = (2u >= 1u); bool unnamed_124 = (2.0 >= 1.0); - bool2 unnamed_125 = (int2(2.xx) >= int2(1.xx)); - bool3 unnamed_126 = (uint3(2u.xxx) >= uint3(1u.xxx)); - bool4 unnamed_127 = (float4(2.0.xxxx) >= float4(1.0.xxxx)); + bool2 unnamed_125 = ((2).xx >= (1).xx); + bool3 unnamed_126 = ((2u).xxx >= (1u).xxx); + bool4 unnamed_127 = ((2.0).xxxx >= (1.0).xxxx); } void assignment() diff --git a/tests/out/hlsl/padding.hlsl b/tests/out/hlsl/padding.hlsl index 2bf074c06..008863777 100644 --- a/tests/out/hlsl/padding.hlsl +++ b/tests/out/hlsl/padding.hlsl @@ -39,5 +39,5 @@ float4 vertex() : SV_Position float _expr6 = input.b; float _expr9 = input2_.b; float _expr12 = input3_.b; - return (((float4(1.0.xxxx) * _expr6) * _expr9) * _expr12); + return ((((1.0).xxxx * _expr6) * _expr9) * _expr12); } From 2cda40396ac53fd38697053ae150d1733e8730d7 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 16:33:43 +0200 Subject: [PATCH 1681/2212] comment out problematic negative int --- tests/in/operators.wgsl | 3 +- tests/out/spv/operators.spvasm | 945 ++++++++++++++++----------------- 2 files changed, 474 insertions(+), 474 deletions(-) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 205895dd4..c69cfbfad 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -87,7 +87,8 @@ fn logical() { fn arithmetic() { // unary - let _ = -1; + // TODO: uncomment when we get the changes from https://github.com/gfx-rs/rspirv/pull/231 + // let _ = -1; let _ = -1.0; let _ = -vec2(1); let _ = -vec2(1.0); diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 294f48cc9..277b0038f 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 460 +; Bound: 459 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %448 "main" -OpExecutionMode %448 LocalSize 1 1 1 -OpMemberDecorate %31 0 Offset 0 -OpMemberDecorate %31 1 Offset 16 -OpDecorate %36 ArrayStride 32 -OpDecorate %37 ArrayStride 4 +OpEntryPoint GLCompute %447 "main" +OpExecutionMode %447 LocalSize 1 1 1 +OpMemberDecorate %30 0 Offset 0 +OpMemberDecorate %30 1 Offset 16 +OpDecorate %35 ArrayStride 32 +OpDecorate %36 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -32,486 +32,485 @@ OpDecorate %37 ArrayStride 4 %19 = OpConstant %20 0 %21 = OpConstant %8 3 %22 = OpConstant %20 4 -%23 = OpConstant %8 4294967295 -%24 = OpConstant %4 -1.0 -%25 = OpConstant %20 2 -%26 = OpConstant %20 1 -%27 = OpTypeVector %4 4 -%28 = OpTypeVector %8 4 -%29 = OpTypeVector %10 4 -%30 = OpTypeVector %4 3 -%31 = OpTypeStruct %27 %8 -%32 = OpTypeVector %4 2 -%33 = OpTypeMatrix %32 2 -%34 = OpTypeMatrix %27 4 -%35 = OpTypeVector %20 2 -%36 = OpTypeArray %31 %21 -%37 = OpTypeArray %8 %22 -%38 = OpTypeMatrix %30 3 -%39 = OpTypeMatrix %30 4 -%40 = OpTypeMatrix %27 3 -%41 = OpConstantComposite %27 %3 %3 %3 %3 -%42 = OpConstantComposite %27 %5 %5 %5 %5 -%43 = OpConstantComposite %27 %6 %6 %6 %6 -%44 = OpConstantComposite %28 %7 %7 %7 %7 -%45 = OpConstantComposite %35 %19 %19 -%46 = OpConstantComposite %32 %5 %5 -%47 = OpConstantComposite %33 %46 %46 -%48 = OpConstantComposite %27 %5 %5 %5 %5 -%49 = OpConstantComposite %31 %48 %11 -%50 = OpConstantComposite %36 %49 %49 %49 -%51 = OpConstantComposite %30 %5 %5 %5 -%52 = OpConstantComposite %38 %51 %51 %51 -%53 = OpConstantComposite %39 %51 %51 %51 %51 -%54 = OpConstantComposite %40 %48 %48 %48 -%57 = OpTypeFunction %27 -%99 = OpTypeFunction %30 %30 -%101 = OpTypeVector %10 3 -%108 = OpTypePointer Function %31 -%110 = OpTypePointer Function %10 -%112 = OpTypePointer Function %8 -%114 = OpTypePointer Function %20 -%116 = OpTypePointer Function %4 -%118 = OpTypePointer Function %35 -%120 = OpTypePointer Function %33 -%122 = OpTypePointer Function %36 -%127 = OpTypePointer Function %37 -%130 = OpTypeFunction %4 -%147 = OpTypePointer Function %27 -%148 = OpTypePointer Function %4 -%153 = OpTypeFunction %2 -%156 = OpTypeVector %10 2 -%172 = OpTypeVector %8 2 -%183 = OpTypeVector %20 3 -%56 = OpFunction %27 None %57 -%55 = OpLabel -OpBranch %58 -%58 = OpLabel -%59 = OpSelect %8 %9 %7 %11 -%61 = OpCompositeConstruct %29 %9 %9 %9 %9 -%60 = OpSelect %27 %61 %41 %42 -%62 = OpCompositeConstruct %29 %12 %12 %12 %12 -%63 = OpSelect %27 %62 %42 %41 -%64 = OpExtInst %27 %1 FMix %42 %41 %43 -%66 = OpCompositeConstruct %27 %13 %13 %13 %13 -%65 = OpExtInst %27 %1 FMix %42 %41 %66 -%67 = OpCompositeExtract %8 %44 0 -%68 = OpBitcast %4 %67 -%69 = OpBitcast %27 %44 -%70 = OpConvertFToS %28 %42 -%71 = OpCompositeConstruct %28 %59 %59 %59 %59 -%72 = OpIAdd %28 %71 %70 -%73 = OpConvertSToF %27 %72 -%74 = OpFAdd %27 %73 %60 -%75 = OpFAdd %27 %74 %64 -%76 = OpFAdd %27 %75 %65 -%77 = OpCompositeConstruct %27 %68 %68 %68 %68 -%78 = OpFAdd %27 %76 %77 -%79 = OpFAdd %27 %78 %69 -OpReturnValue %79 +%23 = OpConstant %4 -1.0 +%24 = OpConstant %20 2 +%25 = OpConstant %20 1 +%26 = OpTypeVector %4 4 +%27 = OpTypeVector %8 4 +%28 = OpTypeVector %10 4 +%29 = OpTypeVector %4 3 +%30 = OpTypeStruct %26 %8 +%31 = OpTypeVector %4 2 +%32 = OpTypeMatrix %31 2 +%33 = OpTypeMatrix %26 4 +%34 = OpTypeVector %20 2 +%35 = OpTypeArray %30 %21 +%36 = OpTypeArray %8 %22 +%37 = OpTypeMatrix %29 3 +%38 = OpTypeMatrix %29 4 +%39 = OpTypeMatrix %26 3 +%40 = OpConstantComposite %26 %3 %3 %3 %3 +%41 = OpConstantComposite %26 %5 %5 %5 %5 +%42 = OpConstantComposite %26 %6 %6 %6 %6 +%43 = OpConstantComposite %27 %7 %7 %7 %7 +%44 = OpConstantComposite %34 %19 %19 +%45 = OpConstantComposite %31 %5 %5 +%46 = OpConstantComposite %32 %45 %45 +%47 = OpConstantComposite %26 %5 %5 %5 %5 +%48 = OpConstantComposite %30 %47 %11 +%49 = OpConstantComposite %35 %48 %48 %48 +%50 = OpConstantComposite %29 %5 %5 %5 +%51 = OpConstantComposite %37 %50 %50 %50 +%52 = OpConstantComposite %38 %50 %50 %50 %50 +%53 = OpConstantComposite %39 %47 %47 %47 +%56 = OpTypeFunction %26 +%98 = OpTypeFunction %29 %29 +%100 = OpTypeVector %10 3 +%107 = OpTypePointer Function %30 +%109 = OpTypePointer Function %10 +%111 = OpTypePointer Function %8 +%113 = OpTypePointer Function %20 +%115 = OpTypePointer Function %4 +%117 = OpTypePointer Function %34 +%119 = OpTypePointer Function %32 +%121 = OpTypePointer Function %35 +%126 = OpTypePointer Function %36 +%129 = OpTypeFunction %4 +%146 = OpTypePointer Function %26 +%147 = OpTypePointer Function %4 +%152 = OpTypeFunction %2 +%155 = OpTypeVector %10 2 +%171 = OpTypeVector %8 2 +%182 = OpTypeVector %20 3 +%55 = OpFunction %26 None %56 +%54 = OpLabel +OpBranch %57 +%57 = OpLabel +%58 = OpSelect %8 %9 %7 %11 +%60 = OpCompositeConstruct %28 %9 %9 %9 %9 +%59 = OpSelect %26 %60 %40 %41 +%61 = OpCompositeConstruct %28 %12 %12 %12 %12 +%62 = OpSelect %26 %61 %41 %40 +%63 = OpExtInst %26 %1 FMix %41 %40 %42 +%65 = OpCompositeConstruct %26 %13 %13 %13 %13 +%64 = OpExtInst %26 %1 FMix %41 %40 %65 +%66 = OpCompositeExtract %8 %43 0 +%67 = OpBitcast %4 %66 +%68 = OpBitcast %26 %43 +%69 = OpConvertFToS %27 %41 +%70 = OpCompositeConstruct %27 %58 %58 %58 %58 +%71 = OpIAdd %27 %70 %69 +%72 = OpConvertSToF %26 %71 +%73 = OpFAdd %26 %72 %59 +%74 = OpFAdd %26 %73 %63 +%75 = OpFAdd %26 %74 %64 +%76 = OpCompositeConstruct %26 %67 %67 %67 %67 +%77 = OpFAdd %26 %75 %76 +%78 = OpFAdd %26 %77 %68 +OpReturnValue %78 OpFunctionEnd -%81 = OpFunction %27 None %57 -%80 = OpLabel -OpBranch %82 -%82 = OpLabel -%83 = OpCompositeConstruct %32 %14 %14 -%84 = OpCompositeConstruct %32 %3 %3 -%85 = OpFAdd %32 %84 %83 -%86 = OpCompositeConstruct %32 %15 %15 -%87 = OpFSub %32 %85 %86 -%88 = OpCompositeConstruct %32 %16 %16 -%89 = OpFDiv %32 %87 %88 -%90 = OpCompositeConstruct %28 %17 %17 %17 %17 -%91 = OpCompositeConstruct %28 %18 %18 %18 %18 -%92 = OpSMod %28 %90 %91 -%93 = OpVectorShuffle %27 %89 %89 0 1 0 1 -%94 = OpConvertSToF %27 %92 -%95 = OpFAdd %27 %93 %94 -OpReturnValue %95 +%80 = OpFunction %26 None %56 +%79 = OpLabel +OpBranch %81 +%81 = OpLabel +%82 = OpCompositeConstruct %31 %14 %14 +%83 = OpCompositeConstruct %31 %3 %3 +%84 = OpFAdd %31 %83 %82 +%85 = OpCompositeConstruct %31 %15 %15 +%86 = OpFSub %31 %84 %85 +%87 = OpCompositeConstruct %31 %16 %16 +%88 = OpFDiv %31 %86 %87 +%89 = OpCompositeConstruct %27 %17 %17 %17 %17 +%90 = OpCompositeConstruct %27 %18 %18 %18 %18 +%91 = OpSMod %27 %89 %90 +%92 = OpVectorShuffle %26 %88 %88 0 1 0 1 +%93 = OpConvertSToF %26 %91 +%94 = OpFAdd %26 %92 %93 +OpReturnValue %94 OpFunctionEnd -%98 = OpFunction %30 None %99 -%97 = OpFunctionParameter %30 -%96 = OpLabel -OpBranch %100 -%100 = OpLabel -%102 = OpCompositeConstruct %30 %5 %5 %5 -%103 = OpFUnordNotEqual %101 %97 %102 -%104 = OpCompositeConstruct %30 %5 %5 %5 -%105 = OpCompositeConstruct %30 %3 %3 %3 -%106 = OpSelect %30 %103 %105 %104 -OpReturnValue %106 +%97 = OpFunction %29 None %98 +%96 = OpFunctionParameter %29 +%95 = OpLabel +OpBranch %99 +%99 = OpLabel +%101 = OpCompositeConstruct %29 %5 %5 %5 +%102 = OpFUnordNotEqual %100 %96 %101 +%103 = OpCompositeConstruct %29 %5 %5 %5 +%104 = OpCompositeConstruct %29 %3 %3 %3 +%105 = OpSelect %29 %102 %104 %103 +OpReturnValue %105 OpFunctionEnd -%129 = OpFunction %4 None %130 -%128 = OpLabel -%124 = OpVariable %118 Function -%119 = OpVariable %120 Function %47 -%113 = OpVariable %114 Function %19 -%107 = OpVariable %108 Function -%125 = OpVariable %120 Function -%121 = OpVariable %122 Function %50 -%115 = OpVariable %116 Function %5 -%109 = OpVariable %110 Function %12 -%126 = OpVariable %127 Function -%123 = OpVariable %108 Function %49 -%117 = OpVariable %118 Function %45 -%111 = OpVariable %112 Function %11 -OpBranch %131 -%131 = OpLabel -%132 = OpCompositeConstruct %27 %3 %3 %3 %3 -%133 = OpCompositeConstruct %31 %132 %7 -OpStore %107 %133 -%134 = OpCompositeConstruct %32 %3 %5 -%135 = OpCompositeConstruct %32 %5 %3 -%136 = OpCompositeConstruct %33 %134 %135 -%137 = OpCompositeConstruct %27 %3 %5 %5 %5 -%138 = OpCompositeConstruct %27 %5 %3 %5 %5 -%139 = OpCompositeConstruct %27 %5 %5 %3 %5 -%140 = OpCompositeConstruct %27 %5 %5 %5 %3 -%141 = OpCompositeConstruct %34 %137 %138 %139 %140 -%142 = OpCompositeConstruct %35 %19 %19 -OpStore %124 %142 -%143 = OpCompositeConstruct %32 %5 %5 -%144 = OpCompositeConstruct %32 %5 %5 -%145 = OpCompositeConstruct %33 %143 %144 +%128 = OpFunction %4 None %129 +%127 = OpLabel +%123 = OpVariable %117 Function +%118 = OpVariable %119 Function %46 +%112 = OpVariable %113 Function %19 +%106 = OpVariable %107 Function +%124 = OpVariable %119 Function +%120 = OpVariable %121 Function %49 +%114 = OpVariable %115 Function %5 +%108 = OpVariable %109 Function %12 +%125 = OpVariable %126 Function +%122 = OpVariable %107 Function %48 +%116 = OpVariable %117 Function %44 +%110 = OpVariable %111 Function %11 +OpBranch %130 +%130 = OpLabel +%131 = OpCompositeConstruct %26 %3 %3 %3 %3 +%132 = OpCompositeConstruct %30 %131 %7 +OpStore %106 %132 +%133 = OpCompositeConstruct %31 %3 %5 +%134 = OpCompositeConstruct %31 %5 %3 +%135 = OpCompositeConstruct %32 %133 %134 +%136 = OpCompositeConstruct %26 %3 %5 %5 %5 +%137 = OpCompositeConstruct %26 %5 %3 %5 %5 +%138 = OpCompositeConstruct %26 %5 %5 %3 %5 +%139 = OpCompositeConstruct %26 %5 %5 %5 %3 +%140 = OpCompositeConstruct %33 %136 %137 %138 %139 +%141 = OpCompositeConstruct %34 %19 %19 +OpStore %123 %141 +%142 = OpCompositeConstruct %31 %5 %5 +%143 = OpCompositeConstruct %31 %5 %5 +%144 = OpCompositeConstruct %32 %142 %143 +OpStore %124 %144 +%145 = OpCompositeConstruct %36 %11 %7 %18 %21 OpStore %125 %145 -%146 = OpCompositeConstruct %37 %11 %7 %18 %21 -OpStore %126 %146 -%149 = OpAccessChain %148 %107 %19 %19 -%150 = OpLoad %4 %149 -OpReturnValue %150 +%148 = OpAccessChain %147 %106 %19 %19 +%149 = OpLoad %4 %148 +OpReturnValue %149 OpFunctionEnd -%152 = OpFunction %2 None %153 -%151 = OpLabel -OpBranch %154 -%154 = OpLabel -%155 = OpLogicalNot %10 %9 -%157 = OpCompositeConstruct %156 %9 %9 -%158 = OpLogicalNot %156 %157 -%159 = OpLogicalOr %10 %9 %12 -%160 = OpLogicalAnd %10 %9 %12 -%161 = OpLogicalOr %10 %9 %12 -%162 = OpCompositeConstruct %101 %9 %9 %9 -%163 = OpCompositeConstruct %101 %12 %12 %12 -%164 = OpLogicalOr %101 %162 %163 -%165 = OpLogicalAnd %10 %9 %12 -%166 = OpCompositeConstruct %29 %9 %9 %9 %9 -%167 = OpCompositeConstruct %29 %12 %12 %12 %12 -%168 = OpLogicalAnd %29 %166 %167 +%151 = OpFunction %2 None %152 +%150 = OpLabel +OpBranch %153 +%153 = OpLabel +%154 = OpLogicalNot %10 %9 +%156 = OpCompositeConstruct %155 %9 %9 +%157 = OpLogicalNot %155 %156 +%158 = OpLogicalOr %10 %9 %12 +%159 = OpLogicalAnd %10 %9 %12 +%160 = OpLogicalOr %10 %9 %12 +%161 = OpCompositeConstruct %100 %9 %9 %9 +%162 = OpCompositeConstruct %100 %12 %12 %12 +%163 = OpLogicalOr %100 %161 %162 +%164 = OpLogicalAnd %10 %9 %12 +%165 = OpCompositeConstruct %28 %9 %9 %9 %9 +%166 = OpCompositeConstruct %28 %12 %12 %12 %12 +%167 = OpLogicalAnd %28 %165 %166 OpReturn OpFunctionEnd -%170 = OpFunction %2 None %153 -%169 = OpLabel -OpBranch %171 -%171 = OpLabel -%173 = OpCompositeConstruct %172 %7 %7 -%174 = OpSNegate %172 %173 -%175 = OpCompositeConstruct %32 %3 %3 -%176 = OpFNegate %32 %175 -%177 = OpIAdd %8 %18 %7 -%178 = OpIAdd %20 %25 %26 -%179 = OpFAdd %4 %14 %3 -%180 = OpCompositeConstruct %172 %18 %18 -%181 = OpCompositeConstruct %172 %7 %7 -%182 = OpIAdd %172 %180 %181 -%184 = OpCompositeConstruct %183 %25 %25 %25 -%185 = OpCompositeConstruct %183 %26 %26 %26 -%186 = OpIAdd %183 %184 %185 -%187 = OpCompositeConstruct %27 %14 %14 %14 %14 -%188 = OpCompositeConstruct %27 %3 %3 %3 %3 -%189 = OpFAdd %27 %187 %188 -%190 = OpISub %8 %18 %7 -%191 = OpISub %20 %25 %26 -%192 = OpFSub %4 %14 %3 -%193 = OpCompositeConstruct %172 %18 %18 -%194 = OpCompositeConstruct %172 %7 %7 -%195 = OpISub %172 %193 %194 -%196 = OpCompositeConstruct %183 %25 %25 %25 -%197 = OpCompositeConstruct %183 %26 %26 %26 -%198 = OpISub %183 %196 %197 -%199 = OpCompositeConstruct %27 %14 %14 %14 %14 -%200 = OpCompositeConstruct %27 %3 %3 %3 %3 -%201 = OpFSub %27 %199 %200 -%202 = OpIMul %8 %18 %7 -%203 = OpIMul %20 %25 %26 -%204 = OpFMul %4 %14 %3 -%205 = OpCompositeConstruct %172 %18 %18 -%206 = OpCompositeConstruct %172 %7 %7 -%207 = OpIMul %172 %205 %206 -%208 = OpCompositeConstruct %183 %25 %25 %25 -%209 = OpCompositeConstruct %183 %26 %26 %26 -%210 = OpIMul %183 %208 %209 -%211 = OpCompositeConstruct %27 %14 %14 %14 %14 -%212 = OpCompositeConstruct %27 %3 %3 %3 %3 -%213 = OpFMul %27 %211 %212 -%214 = OpSDiv %8 %18 %7 -%215 = OpUDiv %20 %25 %26 -%216 = OpFDiv %4 %14 %3 -%217 = OpCompositeConstruct %172 %18 %18 -%218 = OpCompositeConstruct %172 %7 %7 -%219 = OpSDiv %172 %217 %218 -%220 = OpCompositeConstruct %183 %25 %25 %25 -%221 = OpCompositeConstruct %183 %26 %26 %26 -%222 = OpUDiv %183 %220 %221 -%223 = OpCompositeConstruct %27 %14 %14 %14 %14 -%224 = OpCompositeConstruct %27 %3 %3 %3 %3 -%225 = OpFDiv %27 %223 %224 -%226 = OpSMod %8 %18 %7 -%227 = OpUMod %20 %25 %26 -%228 = OpFRem %4 %14 %3 -%229 = OpCompositeConstruct %172 %18 %18 -%230 = OpCompositeConstruct %172 %7 %7 -%231 = OpSMod %172 %229 %230 -%232 = OpCompositeConstruct %183 %25 %25 %25 -%233 = OpCompositeConstruct %183 %26 %26 %26 -%234 = OpUMod %183 %232 %233 -%235 = OpCompositeConstruct %27 %14 %14 %14 %14 -%236 = OpCompositeConstruct %27 %3 %3 %3 %3 -%237 = OpFRem %27 %235 %236 -%238 = OpCompositeConstruct %172 %18 %18 -%239 = OpCompositeConstruct %172 %7 %7 -%240 = OpIAdd %172 %238 %239 -%241 = OpCompositeConstruct %172 %7 %7 -%242 = OpCompositeConstruct %172 %18 %18 -%243 = OpIAdd %172 %242 %241 -%244 = OpCompositeConstruct %172 %18 %18 -%245 = OpCompositeConstruct %172 %7 %7 -%246 = OpISub %172 %244 %245 -%247 = OpCompositeConstruct %172 %7 %7 -%248 = OpCompositeConstruct %172 %18 %18 -%249 = OpISub %172 %248 %247 -%250 = OpCompositeConstruct %172 %18 %18 -%251 = OpVectorTimesScalar %172 %250 %7 -%252 = OpCompositeConstruct %172 %7 %7 -%253 = OpVectorTimesScalar %172 %252 %18 -%254 = OpCompositeConstruct %172 %18 %18 -%255 = OpCompositeConstruct %172 %7 %7 -%256 = OpSDiv %172 %254 %255 -%257 = OpCompositeConstruct %172 %7 %7 -%258 = OpCompositeConstruct %172 %18 %18 -%259 = OpSDiv %172 %258 %257 -%260 = OpCompositeConstruct %172 %18 %18 -%261 = OpCompositeConstruct %172 %7 %7 -%262 = OpSMod %172 %260 %261 -%263 = OpCompositeConstruct %172 %7 %7 -%264 = OpCompositeConstruct %172 %18 %18 -%265 = OpSMod %172 %264 %263 -%267 = OpCompositeExtract %30 %52 0 -%268 = OpCompositeExtract %30 %52 0 -%269 = OpFAdd %30 %267 %268 -%270 = OpCompositeExtract %30 %52 1 -%271 = OpCompositeExtract %30 %52 1 -%272 = OpFAdd %30 %270 %271 -%273 = OpCompositeExtract %30 %52 2 -%274 = OpCompositeExtract %30 %52 2 -%275 = OpFAdd %30 %273 %274 -%266 = OpCompositeConstruct %38 %269 %272 %275 -%277 = OpCompositeExtract %30 %52 0 -%278 = OpCompositeExtract %30 %52 0 -%279 = OpFSub %30 %277 %278 -%280 = OpCompositeExtract %30 %52 1 -%281 = OpCompositeExtract %30 %52 1 -%282 = OpFSub %30 %280 %281 -%283 = OpCompositeExtract %30 %52 2 -%284 = OpCompositeExtract %30 %52 2 -%285 = OpFSub %30 %283 %284 -%276 = OpCompositeConstruct %38 %279 %282 %285 -%286 = OpMatrixTimesScalar %38 %52 %3 -%287 = OpMatrixTimesScalar %38 %52 %14 -%288 = OpCompositeConstruct %27 %3 %3 %3 %3 -%289 = OpMatrixTimesVector %30 %53 %288 -%290 = OpCompositeConstruct %30 %14 %14 %14 -%291 = OpVectorTimesMatrix %27 %290 %53 -%292 = OpMatrixTimesMatrix %38 %53 %54 +%169 = OpFunction %2 None %152 +%168 = OpLabel +OpBranch %170 +%170 = OpLabel +%172 = OpCompositeConstruct %171 %7 %7 +%173 = OpSNegate %171 %172 +%174 = OpCompositeConstruct %31 %3 %3 +%175 = OpFNegate %31 %174 +%176 = OpIAdd %8 %18 %7 +%177 = OpIAdd %20 %24 %25 +%178 = OpFAdd %4 %14 %3 +%179 = OpCompositeConstruct %171 %18 %18 +%180 = OpCompositeConstruct %171 %7 %7 +%181 = OpIAdd %171 %179 %180 +%183 = OpCompositeConstruct %182 %24 %24 %24 +%184 = OpCompositeConstruct %182 %25 %25 %25 +%185 = OpIAdd %182 %183 %184 +%186 = OpCompositeConstruct %26 %14 %14 %14 %14 +%187 = OpCompositeConstruct %26 %3 %3 %3 %3 +%188 = OpFAdd %26 %186 %187 +%189 = OpISub %8 %18 %7 +%190 = OpISub %20 %24 %25 +%191 = OpFSub %4 %14 %3 +%192 = OpCompositeConstruct %171 %18 %18 +%193 = OpCompositeConstruct %171 %7 %7 +%194 = OpISub %171 %192 %193 +%195 = OpCompositeConstruct %182 %24 %24 %24 +%196 = OpCompositeConstruct %182 %25 %25 %25 +%197 = OpISub %182 %195 %196 +%198 = OpCompositeConstruct %26 %14 %14 %14 %14 +%199 = OpCompositeConstruct %26 %3 %3 %3 %3 +%200 = OpFSub %26 %198 %199 +%201 = OpIMul %8 %18 %7 +%202 = OpIMul %20 %24 %25 +%203 = OpFMul %4 %14 %3 +%204 = OpCompositeConstruct %171 %18 %18 +%205 = OpCompositeConstruct %171 %7 %7 +%206 = OpIMul %171 %204 %205 +%207 = OpCompositeConstruct %182 %24 %24 %24 +%208 = OpCompositeConstruct %182 %25 %25 %25 +%209 = OpIMul %182 %207 %208 +%210 = OpCompositeConstruct %26 %14 %14 %14 %14 +%211 = OpCompositeConstruct %26 %3 %3 %3 %3 +%212 = OpFMul %26 %210 %211 +%213 = OpSDiv %8 %18 %7 +%214 = OpUDiv %20 %24 %25 +%215 = OpFDiv %4 %14 %3 +%216 = OpCompositeConstruct %171 %18 %18 +%217 = OpCompositeConstruct %171 %7 %7 +%218 = OpSDiv %171 %216 %217 +%219 = OpCompositeConstruct %182 %24 %24 %24 +%220 = OpCompositeConstruct %182 %25 %25 %25 +%221 = OpUDiv %182 %219 %220 +%222 = OpCompositeConstruct %26 %14 %14 %14 %14 +%223 = OpCompositeConstruct %26 %3 %3 %3 %3 +%224 = OpFDiv %26 %222 %223 +%225 = OpSMod %8 %18 %7 +%226 = OpUMod %20 %24 %25 +%227 = OpFRem %4 %14 %3 +%228 = OpCompositeConstruct %171 %18 %18 +%229 = OpCompositeConstruct %171 %7 %7 +%230 = OpSMod %171 %228 %229 +%231 = OpCompositeConstruct %182 %24 %24 %24 +%232 = OpCompositeConstruct %182 %25 %25 %25 +%233 = OpUMod %182 %231 %232 +%234 = OpCompositeConstruct %26 %14 %14 %14 %14 +%235 = OpCompositeConstruct %26 %3 %3 %3 %3 +%236 = OpFRem %26 %234 %235 +%237 = OpCompositeConstruct %171 %18 %18 +%238 = OpCompositeConstruct %171 %7 %7 +%239 = OpIAdd %171 %237 %238 +%240 = OpCompositeConstruct %171 %7 %7 +%241 = OpCompositeConstruct %171 %18 %18 +%242 = OpIAdd %171 %241 %240 +%243 = OpCompositeConstruct %171 %18 %18 +%244 = OpCompositeConstruct %171 %7 %7 +%245 = OpISub %171 %243 %244 +%246 = OpCompositeConstruct %171 %7 %7 +%247 = OpCompositeConstruct %171 %18 %18 +%248 = OpISub %171 %247 %246 +%249 = OpCompositeConstruct %171 %18 %18 +%250 = OpVectorTimesScalar %171 %249 %7 +%251 = OpCompositeConstruct %171 %7 %7 +%252 = OpVectorTimesScalar %171 %251 %18 +%253 = OpCompositeConstruct %171 %18 %18 +%254 = OpCompositeConstruct %171 %7 %7 +%255 = OpSDiv %171 %253 %254 +%256 = OpCompositeConstruct %171 %7 %7 +%257 = OpCompositeConstruct %171 %18 %18 +%258 = OpSDiv %171 %257 %256 +%259 = OpCompositeConstruct %171 %18 %18 +%260 = OpCompositeConstruct %171 %7 %7 +%261 = OpSMod %171 %259 %260 +%262 = OpCompositeConstruct %171 %7 %7 +%263 = OpCompositeConstruct %171 %18 %18 +%264 = OpSMod %171 %263 %262 +%266 = OpCompositeExtract %29 %51 0 +%267 = OpCompositeExtract %29 %51 0 +%268 = OpFAdd %29 %266 %267 +%269 = OpCompositeExtract %29 %51 1 +%270 = OpCompositeExtract %29 %51 1 +%271 = OpFAdd %29 %269 %270 +%272 = OpCompositeExtract %29 %51 2 +%273 = OpCompositeExtract %29 %51 2 +%274 = OpFAdd %29 %272 %273 +%265 = OpCompositeConstruct %37 %268 %271 %274 +%276 = OpCompositeExtract %29 %51 0 +%277 = OpCompositeExtract %29 %51 0 +%278 = OpFSub %29 %276 %277 +%279 = OpCompositeExtract %29 %51 1 +%280 = OpCompositeExtract %29 %51 1 +%281 = OpFSub %29 %279 %280 +%282 = OpCompositeExtract %29 %51 2 +%283 = OpCompositeExtract %29 %51 2 +%284 = OpFSub %29 %282 %283 +%275 = OpCompositeConstruct %37 %278 %281 %284 +%285 = OpMatrixTimesScalar %37 %51 %3 +%286 = OpMatrixTimesScalar %37 %51 %14 +%287 = OpCompositeConstruct %26 %3 %3 %3 %3 +%288 = OpMatrixTimesVector %29 %52 %287 +%289 = OpCompositeConstruct %29 %14 %14 %14 +%290 = OpVectorTimesMatrix %26 %289 %52 +%291 = OpMatrixTimesMatrix %37 %52 %53 OpReturn OpFunctionEnd -%294 = OpFunction %2 None %153 -%293 = OpLabel -OpBranch %295 -%295 = OpLabel -%296 = OpNot %8 %7 -%297 = OpNot %20 %26 -%298 = OpCompositeConstruct %172 %7 %7 -%299 = OpNot %172 %298 -%300 = OpCompositeConstruct %183 %26 %26 %26 -%301 = OpNot %183 %300 -%302 = OpBitwiseOr %8 %18 %7 -%303 = OpBitwiseOr %20 %25 %26 -%304 = OpCompositeConstruct %172 %18 %18 -%305 = OpCompositeConstruct %172 %7 %7 -%306 = OpBitwiseOr %172 %304 %305 -%307 = OpCompositeConstruct %183 %25 %25 %25 -%308 = OpCompositeConstruct %183 %26 %26 %26 -%309 = OpBitwiseOr %183 %307 %308 -%310 = OpBitwiseAnd %8 %18 %7 -%311 = OpBitwiseAnd %20 %25 %26 -%312 = OpCompositeConstruct %172 %18 %18 -%313 = OpCompositeConstruct %172 %7 %7 -%314 = OpBitwiseAnd %172 %312 %313 -%315 = OpCompositeConstruct %183 %25 %25 %25 -%316 = OpCompositeConstruct %183 %26 %26 %26 -%317 = OpBitwiseAnd %183 %315 %316 -%318 = OpBitwiseXor %8 %18 %7 -%319 = OpBitwiseXor %20 %25 %26 -%320 = OpCompositeConstruct %172 %18 %18 -%321 = OpCompositeConstruct %172 %7 %7 -%322 = OpBitwiseXor %172 %320 %321 -%323 = OpCompositeConstruct %183 %25 %25 %25 -%324 = OpCompositeConstruct %183 %26 %26 %26 -%325 = OpBitwiseXor %183 %323 %324 -%326 = OpShiftLeftLogical %8 %18 %26 -%327 = OpShiftLeftLogical %20 %25 %26 -%328 = OpCompositeConstruct %172 %18 %18 -%329 = OpCompositeConstruct %35 %26 %26 -%330 = OpShiftLeftLogical %172 %328 %329 -%331 = OpCompositeConstruct %183 %25 %25 %25 -%332 = OpCompositeConstruct %183 %26 %26 %26 -%333 = OpShiftLeftLogical %183 %331 %332 -%334 = OpShiftRightArithmetic %8 %18 %26 -%335 = OpShiftRightLogical %20 %25 %26 -%336 = OpCompositeConstruct %172 %18 %18 -%337 = OpCompositeConstruct %35 %26 %26 -%338 = OpShiftRightArithmetic %172 %336 %337 -%339 = OpCompositeConstruct %183 %25 %25 %25 -%340 = OpCompositeConstruct %183 %26 %26 %26 -%341 = OpShiftRightLogical %183 %339 %340 +%293 = OpFunction %2 None %152 +%292 = OpLabel +OpBranch %294 +%294 = OpLabel +%295 = OpNot %8 %7 +%296 = OpNot %20 %25 +%297 = OpCompositeConstruct %171 %7 %7 +%298 = OpNot %171 %297 +%299 = OpCompositeConstruct %182 %25 %25 %25 +%300 = OpNot %182 %299 +%301 = OpBitwiseOr %8 %18 %7 +%302 = OpBitwiseOr %20 %24 %25 +%303 = OpCompositeConstruct %171 %18 %18 +%304 = OpCompositeConstruct %171 %7 %7 +%305 = OpBitwiseOr %171 %303 %304 +%306 = OpCompositeConstruct %182 %24 %24 %24 +%307 = OpCompositeConstruct %182 %25 %25 %25 +%308 = OpBitwiseOr %182 %306 %307 +%309 = OpBitwiseAnd %8 %18 %7 +%310 = OpBitwiseAnd %20 %24 %25 +%311 = OpCompositeConstruct %171 %18 %18 +%312 = OpCompositeConstruct %171 %7 %7 +%313 = OpBitwiseAnd %171 %311 %312 +%314 = OpCompositeConstruct %182 %24 %24 %24 +%315 = OpCompositeConstruct %182 %25 %25 %25 +%316 = OpBitwiseAnd %182 %314 %315 +%317 = OpBitwiseXor %8 %18 %7 +%318 = OpBitwiseXor %20 %24 %25 +%319 = OpCompositeConstruct %171 %18 %18 +%320 = OpCompositeConstruct %171 %7 %7 +%321 = OpBitwiseXor %171 %319 %320 +%322 = OpCompositeConstruct %182 %24 %24 %24 +%323 = OpCompositeConstruct %182 %25 %25 %25 +%324 = OpBitwiseXor %182 %322 %323 +%325 = OpShiftLeftLogical %8 %18 %25 +%326 = OpShiftLeftLogical %20 %24 %25 +%327 = OpCompositeConstruct %171 %18 %18 +%328 = OpCompositeConstruct %34 %25 %25 +%329 = OpShiftLeftLogical %171 %327 %328 +%330 = OpCompositeConstruct %182 %24 %24 %24 +%331 = OpCompositeConstruct %182 %25 %25 %25 +%332 = OpShiftLeftLogical %182 %330 %331 +%333 = OpShiftRightArithmetic %8 %18 %25 +%334 = OpShiftRightLogical %20 %24 %25 +%335 = OpCompositeConstruct %171 %18 %18 +%336 = OpCompositeConstruct %34 %25 %25 +%337 = OpShiftRightArithmetic %171 %335 %336 +%338 = OpCompositeConstruct %182 %24 %24 %24 +%339 = OpCompositeConstruct %182 %25 %25 %25 +%340 = OpShiftRightLogical %182 %338 %339 OpReturn OpFunctionEnd -%343 = OpFunction %2 None %153 -%342 = OpLabel -OpBranch %344 -%344 = OpLabel -%345 = OpIEqual %10 %18 %7 -%346 = OpIEqual %10 %25 %26 -%347 = OpFOrdEqual %10 %14 %3 -%348 = OpCompositeConstruct %172 %18 %18 -%349 = OpCompositeConstruct %172 %7 %7 -%350 = OpIEqual %156 %348 %349 -%351 = OpCompositeConstruct %183 %25 %25 %25 -%352 = OpCompositeConstruct %183 %26 %26 %26 -%353 = OpIEqual %101 %351 %352 -%354 = OpCompositeConstruct %27 %14 %14 %14 %14 -%355 = OpCompositeConstruct %27 %3 %3 %3 %3 -%356 = OpFOrdEqual %29 %354 %355 -%357 = OpINotEqual %10 %18 %7 -%358 = OpINotEqual %10 %25 %26 -%359 = OpFOrdNotEqual %10 %14 %3 -%360 = OpCompositeConstruct %172 %18 %18 -%361 = OpCompositeConstruct %172 %7 %7 -%362 = OpINotEqual %156 %360 %361 -%363 = OpCompositeConstruct %183 %25 %25 %25 -%364 = OpCompositeConstruct %183 %26 %26 %26 -%365 = OpINotEqual %101 %363 %364 -%366 = OpCompositeConstruct %27 %14 %14 %14 %14 -%367 = OpCompositeConstruct %27 %3 %3 %3 %3 -%368 = OpFOrdNotEqual %29 %366 %367 -%369 = OpSLessThan %10 %18 %7 -%370 = OpULessThan %10 %25 %26 -%371 = OpFOrdLessThan %10 %14 %3 -%372 = OpCompositeConstruct %172 %18 %18 -%373 = OpCompositeConstruct %172 %7 %7 -%374 = OpSLessThan %156 %372 %373 -%375 = OpCompositeConstruct %183 %25 %25 %25 -%376 = OpCompositeConstruct %183 %26 %26 %26 -%377 = OpULessThan %101 %375 %376 -%378 = OpCompositeConstruct %27 %14 %14 %14 %14 -%379 = OpCompositeConstruct %27 %3 %3 %3 %3 -%380 = OpFOrdLessThan %29 %378 %379 -%381 = OpSLessThanEqual %10 %18 %7 -%382 = OpULessThanEqual %10 %25 %26 -%383 = OpFOrdLessThanEqual %10 %14 %3 -%384 = OpCompositeConstruct %172 %18 %18 -%385 = OpCompositeConstruct %172 %7 %7 -%386 = OpSLessThanEqual %156 %384 %385 -%387 = OpCompositeConstruct %183 %25 %25 %25 -%388 = OpCompositeConstruct %183 %26 %26 %26 -%389 = OpULessThanEqual %101 %387 %388 -%390 = OpCompositeConstruct %27 %14 %14 %14 %14 -%391 = OpCompositeConstruct %27 %3 %3 %3 %3 -%392 = OpFOrdLessThanEqual %29 %390 %391 -%393 = OpSGreaterThan %10 %18 %7 -%394 = OpUGreaterThan %10 %25 %26 -%395 = OpFOrdGreaterThan %10 %14 %3 -%396 = OpCompositeConstruct %172 %18 %18 -%397 = OpCompositeConstruct %172 %7 %7 -%398 = OpSGreaterThan %156 %396 %397 -%399 = OpCompositeConstruct %183 %25 %25 %25 -%400 = OpCompositeConstruct %183 %26 %26 %26 -%401 = OpUGreaterThan %101 %399 %400 -%402 = OpCompositeConstruct %27 %14 %14 %14 %14 -%403 = OpCompositeConstruct %27 %3 %3 %3 %3 -%404 = OpFOrdGreaterThan %29 %402 %403 -%405 = OpSGreaterThanEqual %10 %18 %7 -%406 = OpUGreaterThanEqual %10 %25 %26 -%407 = OpFOrdGreaterThanEqual %10 %14 %3 -%408 = OpCompositeConstruct %172 %18 %18 -%409 = OpCompositeConstruct %172 %7 %7 -%410 = OpSGreaterThanEqual %156 %408 %409 -%411 = OpCompositeConstruct %183 %25 %25 %25 -%412 = OpCompositeConstruct %183 %26 %26 %26 -%413 = OpUGreaterThanEqual %101 %411 %412 -%414 = OpCompositeConstruct %27 %14 %14 %14 %14 -%415 = OpCompositeConstruct %27 %3 %3 %3 %3 -%416 = OpFOrdGreaterThanEqual %29 %414 %415 +%342 = OpFunction %2 None %152 +%341 = OpLabel +OpBranch %343 +%343 = OpLabel +%344 = OpIEqual %10 %18 %7 +%345 = OpIEqual %10 %24 %25 +%346 = OpFOrdEqual %10 %14 %3 +%347 = OpCompositeConstruct %171 %18 %18 +%348 = OpCompositeConstruct %171 %7 %7 +%349 = OpIEqual %155 %347 %348 +%350 = OpCompositeConstruct %182 %24 %24 %24 +%351 = OpCompositeConstruct %182 %25 %25 %25 +%352 = OpIEqual %100 %350 %351 +%353 = OpCompositeConstruct %26 %14 %14 %14 %14 +%354 = OpCompositeConstruct %26 %3 %3 %3 %3 +%355 = OpFOrdEqual %28 %353 %354 +%356 = OpINotEqual %10 %18 %7 +%357 = OpINotEqual %10 %24 %25 +%358 = OpFOrdNotEqual %10 %14 %3 +%359 = OpCompositeConstruct %171 %18 %18 +%360 = OpCompositeConstruct %171 %7 %7 +%361 = OpINotEqual %155 %359 %360 +%362 = OpCompositeConstruct %182 %24 %24 %24 +%363 = OpCompositeConstruct %182 %25 %25 %25 +%364 = OpINotEqual %100 %362 %363 +%365 = OpCompositeConstruct %26 %14 %14 %14 %14 +%366 = OpCompositeConstruct %26 %3 %3 %3 %3 +%367 = OpFOrdNotEqual %28 %365 %366 +%368 = OpSLessThan %10 %18 %7 +%369 = OpULessThan %10 %24 %25 +%370 = OpFOrdLessThan %10 %14 %3 +%371 = OpCompositeConstruct %171 %18 %18 +%372 = OpCompositeConstruct %171 %7 %7 +%373 = OpSLessThan %155 %371 %372 +%374 = OpCompositeConstruct %182 %24 %24 %24 +%375 = OpCompositeConstruct %182 %25 %25 %25 +%376 = OpULessThan %100 %374 %375 +%377 = OpCompositeConstruct %26 %14 %14 %14 %14 +%378 = OpCompositeConstruct %26 %3 %3 %3 %3 +%379 = OpFOrdLessThan %28 %377 %378 +%380 = OpSLessThanEqual %10 %18 %7 +%381 = OpULessThanEqual %10 %24 %25 +%382 = OpFOrdLessThanEqual %10 %14 %3 +%383 = OpCompositeConstruct %171 %18 %18 +%384 = OpCompositeConstruct %171 %7 %7 +%385 = OpSLessThanEqual %155 %383 %384 +%386 = OpCompositeConstruct %182 %24 %24 %24 +%387 = OpCompositeConstruct %182 %25 %25 %25 +%388 = OpULessThanEqual %100 %386 %387 +%389 = OpCompositeConstruct %26 %14 %14 %14 %14 +%390 = OpCompositeConstruct %26 %3 %3 %3 %3 +%391 = OpFOrdLessThanEqual %28 %389 %390 +%392 = OpSGreaterThan %10 %18 %7 +%393 = OpUGreaterThan %10 %24 %25 +%394 = OpFOrdGreaterThan %10 %14 %3 +%395 = OpCompositeConstruct %171 %18 %18 +%396 = OpCompositeConstruct %171 %7 %7 +%397 = OpSGreaterThan %155 %395 %396 +%398 = OpCompositeConstruct %182 %24 %24 %24 +%399 = OpCompositeConstruct %182 %25 %25 %25 +%400 = OpUGreaterThan %100 %398 %399 +%401 = OpCompositeConstruct %26 %14 %14 %14 %14 +%402 = OpCompositeConstruct %26 %3 %3 %3 %3 +%403 = OpFOrdGreaterThan %28 %401 %402 +%404 = OpSGreaterThanEqual %10 %18 %7 +%405 = OpUGreaterThanEqual %10 %24 %25 +%406 = OpFOrdGreaterThanEqual %10 %14 %3 +%407 = OpCompositeConstruct %171 %18 %18 +%408 = OpCompositeConstruct %171 %7 %7 +%409 = OpSGreaterThanEqual %155 %407 %408 +%410 = OpCompositeConstruct %182 %24 %24 %24 +%411 = OpCompositeConstruct %182 %25 %25 %25 +%412 = OpUGreaterThanEqual %100 %410 %411 +%413 = OpCompositeConstruct %26 %14 %14 %14 %14 +%414 = OpCompositeConstruct %26 %3 %3 %3 %3 +%415 = OpFOrdGreaterThanEqual %28 %413 %414 OpReturn OpFunctionEnd -%419 = OpFunction %2 None %153 -%418 = OpLabel -%417 = OpVariable %112 Function %7 -OpBranch %420 -%420 = OpLabel -%421 = OpLoad %8 %417 -%422 = OpIAdd %8 %421 %7 -OpStore %417 %422 -%423 = OpLoad %8 %417 -%424 = OpISub %8 %423 %7 -OpStore %417 %424 -%425 = OpLoad %8 %417 -%426 = OpLoad %8 %417 -%427 = OpIMul %8 %425 %426 -OpStore %417 %427 -%428 = OpLoad %8 %417 -%429 = OpLoad %8 %417 -%430 = OpSDiv %8 %428 %429 -OpStore %417 %430 -%431 = OpLoad %8 %417 -%432 = OpSMod %8 %431 %7 -OpStore %417 %432 -%433 = OpLoad %8 %417 -%434 = OpBitwiseAnd %8 %433 %11 -OpStore %417 %434 -%435 = OpLoad %8 %417 -%436 = OpBitwiseOr %8 %435 %11 -OpStore %417 %436 -%437 = OpLoad %8 %417 -%438 = OpBitwiseXor %8 %437 %11 -OpStore %417 %438 -%439 = OpLoad %8 %417 -%440 = OpShiftLeftLogical %8 %439 %25 -OpStore %417 %440 -%441 = OpLoad %8 %417 -%442 = OpShiftRightArithmetic %8 %441 %26 -OpStore %417 %442 -%443 = OpLoad %8 %417 -%444 = OpIAdd %8 %443 %7 -OpStore %417 %444 -%445 = OpLoad %8 %417 -%446 = OpISub %8 %445 %7 -OpStore %417 %446 +%418 = OpFunction %2 None %152 +%417 = OpLabel +%416 = OpVariable %111 Function %7 +OpBranch %419 +%419 = OpLabel +%420 = OpLoad %8 %416 +%421 = OpIAdd %8 %420 %7 +OpStore %416 %421 +%422 = OpLoad %8 %416 +%423 = OpISub %8 %422 %7 +OpStore %416 %423 +%424 = OpLoad %8 %416 +%425 = OpLoad %8 %416 +%426 = OpIMul %8 %424 %425 +OpStore %416 %426 +%427 = OpLoad %8 %416 +%428 = OpLoad %8 %416 +%429 = OpSDiv %8 %427 %428 +OpStore %416 %429 +%430 = OpLoad %8 %416 +%431 = OpSMod %8 %430 %7 +OpStore %416 %431 +%432 = OpLoad %8 %416 +%433 = OpBitwiseAnd %8 %432 %11 +OpStore %416 %433 +%434 = OpLoad %8 %416 +%435 = OpBitwiseOr %8 %434 %11 +OpStore %416 %435 +%436 = OpLoad %8 %416 +%437 = OpBitwiseXor %8 %436 %11 +OpStore %416 %437 +%438 = OpLoad %8 %416 +%439 = OpShiftLeftLogical %8 %438 %24 +OpStore %416 %439 +%440 = OpLoad %8 %416 +%441 = OpShiftRightArithmetic %8 %440 %25 +OpStore %416 %441 +%442 = OpLoad %8 %416 +%443 = OpIAdd %8 %442 %7 +OpStore %416 %443 +%444 = OpLoad %8 %416 +%445 = OpISub %8 %444 %7 +OpStore %416 %445 OpReturn OpFunctionEnd -%448 = OpFunction %2 None %153 -%447 = OpLabel -OpBranch %449 -%449 = OpLabel -%450 = OpFunctionCall %27 %56 -%451 = OpFunctionCall %27 %81 -%452 = OpVectorShuffle %30 %41 %41 0 1 2 -%453 = OpFunctionCall %30 %98 %452 -%454 = OpFunctionCall %4 %129 -%455 = OpFunctionCall %2 %152 -%456 = OpFunctionCall %2 %170 -%457 = OpFunctionCall %2 %294 -%458 = OpFunctionCall %2 %343 -%459 = OpFunctionCall %2 %419 +%447 = OpFunction %2 None %152 +%446 = OpLabel +OpBranch %448 +%448 = OpLabel +%449 = OpFunctionCall %26 %55 +%450 = OpFunctionCall %26 %80 +%451 = OpVectorShuffle %29 %40 %40 0 1 2 +%452 = OpFunctionCall %29 %97 %451 +%453 = OpFunctionCall %4 %128 +%454 = OpFunctionCall %2 %151 +%455 = OpFunctionCall %2 %169 +%456 = OpFunctionCall %2 %293 +%457 = OpFunctionCall %2 %342 +%458 = OpFunctionCall %2 %418 OpReturn OpFunctionEnd \ No newline at end of file From 95b84c44038da50689868e4bf25a9270e7903165 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 17:27:12 +0200 Subject: [PATCH 1682/2212] [spv-out] add support for int vector scalar mult --- src/back/spv/block.rs | 82 +++++- tests/out/spv/operators.spvasm | 442 +++++++++++++++++---------------- 2 files changed, 291 insertions(+), 233 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index b22eb56ae..ce5592ab6 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -337,7 +337,7 @@ impl<'w> BlockContext<'w> { let left_dimension = get_dimension(left_ty_inner); let right_dimension = get_dimension(right_ty_inner); - let mut preserve_order = true; + let mut reverse_operands = false; let spirv_op = match op { crate::BinaryOperator::Add => match *left_ty_inner { @@ -397,19 +397,36 @@ impl<'w> BlockContext<'w> { _ => unimplemented!(), }, crate::BinaryOperator::Multiply => match (left_dimension, right_dimension) { - (Dimension::Scalar, Dimension::Vector { .. }) => { - preserve_order = false; - spirv::Op::VectorTimesScalar + (Dimension::Scalar, Dimension::Vector) => { + self.write_vector_scalar_mult( + block, + id, + result_type_id, + right_id, + left_id, + right_ty_inner, + ); + + self.cached[expr_handle] = id; + return Ok(()); } - (Dimension::Vector, Dimension::Scalar { .. }) => { - spirv::Op::VectorTimesScalar + (Dimension::Vector, Dimension::Scalar) => { + self.write_vector_scalar_mult( + block, + id, + result_type_id, + left_id, + right_id, + left_ty_inner, + ); + + self.cached[expr_handle] = id; + return Ok(()); } (Dimension::Vector, Dimension::Matrix) => spirv::Op::VectorTimesMatrix, - (Dimension::Matrix, Dimension::Scalar { .. }) => { - spirv::Op::MatrixTimesScalar - } - (Dimension::Scalar, Dimension::Matrix { .. }) => { - preserve_order = false; + (Dimension::Matrix, Dimension::Scalar) => spirv::Op::MatrixTimesScalar, + (Dimension::Scalar, Dimension::Matrix) => { + reverse_operands = true; spirv::Op::MatrixTimesScalar } (Dimension::Matrix, Dimension::Vector) => spirv::Op::MatrixTimesVector, @@ -498,8 +515,8 @@ impl<'w> BlockContext<'w> { spirv_op, result_type_id, id, - if preserve_order { left_id } else { right_id }, - if preserve_order { right_id } else { left_id }, + if reverse_operands { right_id } else { left_id }, + if reverse_operands { left_id } else { right_id }, )); id } @@ -1248,6 +1265,45 @@ impl<'w> BlockContext<'w> { )); } + /// Build the instructions for vector - scalar multiplication + fn write_vector_scalar_mult( + &mut self, + block: &mut Block, + result_id: Word, + result_type_id: Word, + vector_id: Word, + scalar_id: Word, + vector: &crate::TypeInner, + ) { + let (size, kind) = match *vector { + crate::TypeInner::Vector { size, kind, .. } => (size, kind), + _ => unreachable!(), + }; + + let (op, operand_id) = match kind { + crate::ScalarKind::Float => (spirv::Op::VectorTimesScalar, scalar_id), + _ => { + let operand_id = self.gen_id(); + self.temp_list.clear(); + self.temp_list.resize(size as usize, scalar_id); + block.body.push(Instruction::composite_construct( + result_type_id, + operand_id, + &self.temp_list, + )); + (spirv::Op::IMul, operand_id) + } + }; + + block.body.push(Instruction::binary( + op, + result_type_id, + result_id, + vector_id, + operand_id, + )); + } + /// Build the instructions for the arithmetic expression of a dot product fn write_dot_product( &mut self, diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 277b0038f..7d4b79d76 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 459 +; Bound: 461 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %447 "main" -OpExecutionMode %447 LocalSize 1 1 1 +OpEntryPoint GLCompute %449 "main" +OpExecutionMode %449 LocalSize 1 1 1 OpMemberDecorate %30 0 Offset 0 OpMemberDecorate %30 1 Offset 16 OpDecorate %35 ArrayStride 32 @@ -279,238 +279,240 @@ OpBranch %170 %247 = OpCompositeConstruct %171 %18 %18 %248 = OpISub %171 %247 %246 %249 = OpCompositeConstruct %171 %18 %18 -%250 = OpVectorTimesScalar %171 %249 %7 %251 = OpCompositeConstruct %171 %7 %7 -%252 = OpVectorTimesScalar %171 %251 %18 -%253 = OpCompositeConstruct %171 %18 %18 -%254 = OpCompositeConstruct %171 %7 %7 -%255 = OpSDiv %171 %253 %254 +%250 = OpIMul %171 %249 %251 +%252 = OpCompositeConstruct %171 %7 %7 +%254 = OpCompositeConstruct %171 %18 %18 +%253 = OpIMul %171 %252 %254 +%255 = OpCompositeConstruct %171 %18 %18 %256 = OpCompositeConstruct %171 %7 %7 -%257 = OpCompositeConstruct %171 %18 %18 -%258 = OpSDiv %171 %257 %256 +%257 = OpSDiv %171 %255 %256 +%258 = OpCompositeConstruct %171 %7 %7 %259 = OpCompositeConstruct %171 %18 %18 -%260 = OpCompositeConstruct %171 %7 %7 -%261 = OpSMod %171 %259 %260 +%260 = OpSDiv %171 %259 %258 +%261 = OpCompositeConstruct %171 %18 %18 %262 = OpCompositeConstruct %171 %7 %7 -%263 = OpCompositeConstruct %171 %18 %18 -%264 = OpSMod %171 %263 %262 -%266 = OpCompositeExtract %29 %51 0 -%267 = OpCompositeExtract %29 %51 0 -%268 = OpFAdd %29 %266 %267 -%269 = OpCompositeExtract %29 %51 1 -%270 = OpCompositeExtract %29 %51 1 -%271 = OpFAdd %29 %269 %270 -%272 = OpCompositeExtract %29 %51 2 -%273 = OpCompositeExtract %29 %51 2 -%274 = OpFAdd %29 %272 %273 -%265 = OpCompositeConstruct %37 %268 %271 %274 -%276 = OpCompositeExtract %29 %51 0 -%277 = OpCompositeExtract %29 %51 0 -%278 = OpFSub %29 %276 %277 -%279 = OpCompositeExtract %29 %51 1 -%280 = OpCompositeExtract %29 %51 1 -%281 = OpFSub %29 %279 %280 -%282 = OpCompositeExtract %29 %51 2 -%283 = OpCompositeExtract %29 %51 2 -%284 = OpFSub %29 %282 %283 -%275 = OpCompositeConstruct %37 %278 %281 %284 -%285 = OpMatrixTimesScalar %37 %51 %3 -%286 = OpMatrixTimesScalar %37 %51 %14 -%287 = OpCompositeConstruct %26 %3 %3 %3 %3 -%288 = OpMatrixTimesVector %29 %52 %287 -%289 = OpCompositeConstruct %29 %14 %14 %14 -%290 = OpVectorTimesMatrix %26 %289 %52 -%291 = OpMatrixTimesMatrix %37 %52 %53 +%263 = OpSMod %171 %261 %262 +%264 = OpCompositeConstruct %171 %7 %7 +%265 = OpCompositeConstruct %171 %18 %18 +%266 = OpSMod %171 %265 %264 +%268 = OpCompositeExtract %29 %51 0 +%269 = OpCompositeExtract %29 %51 0 +%270 = OpFAdd %29 %268 %269 +%271 = OpCompositeExtract %29 %51 1 +%272 = OpCompositeExtract %29 %51 1 +%273 = OpFAdd %29 %271 %272 +%274 = OpCompositeExtract %29 %51 2 +%275 = OpCompositeExtract %29 %51 2 +%276 = OpFAdd %29 %274 %275 +%267 = OpCompositeConstruct %37 %270 %273 %276 +%278 = OpCompositeExtract %29 %51 0 +%279 = OpCompositeExtract %29 %51 0 +%280 = OpFSub %29 %278 %279 +%281 = OpCompositeExtract %29 %51 1 +%282 = OpCompositeExtract %29 %51 1 +%283 = OpFSub %29 %281 %282 +%284 = OpCompositeExtract %29 %51 2 +%285 = OpCompositeExtract %29 %51 2 +%286 = OpFSub %29 %284 %285 +%277 = OpCompositeConstruct %37 %280 %283 %286 +%287 = OpMatrixTimesScalar %37 %51 %3 +%288 = OpMatrixTimesScalar %37 %51 %14 +%289 = OpCompositeConstruct %26 %3 %3 %3 %3 +%290 = OpMatrixTimesVector %29 %52 %289 +%291 = OpCompositeConstruct %29 %14 %14 %14 +%292 = OpVectorTimesMatrix %26 %291 %52 +%293 = OpMatrixTimesMatrix %37 %52 %53 OpReturn OpFunctionEnd -%293 = OpFunction %2 None %152 -%292 = OpLabel -OpBranch %294 +%295 = OpFunction %2 None %152 %294 = OpLabel -%295 = OpNot %8 %7 -%296 = OpNot %20 %25 -%297 = OpCompositeConstruct %171 %7 %7 -%298 = OpNot %171 %297 -%299 = OpCompositeConstruct %182 %25 %25 %25 -%300 = OpNot %182 %299 -%301 = OpBitwiseOr %8 %18 %7 -%302 = OpBitwiseOr %20 %24 %25 -%303 = OpCompositeConstruct %171 %18 %18 -%304 = OpCompositeConstruct %171 %7 %7 -%305 = OpBitwiseOr %171 %303 %304 -%306 = OpCompositeConstruct %182 %24 %24 %24 -%307 = OpCompositeConstruct %182 %25 %25 %25 -%308 = OpBitwiseOr %182 %306 %307 -%309 = OpBitwiseAnd %8 %18 %7 -%310 = OpBitwiseAnd %20 %24 %25 -%311 = OpCompositeConstruct %171 %18 %18 -%312 = OpCompositeConstruct %171 %7 %7 -%313 = OpBitwiseAnd %171 %311 %312 -%314 = OpCompositeConstruct %182 %24 %24 %24 -%315 = OpCompositeConstruct %182 %25 %25 %25 -%316 = OpBitwiseAnd %182 %314 %315 -%317 = OpBitwiseXor %8 %18 %7 -%318 = OpBitwiseXor %20 %24 %25 -%319 = OpCompositeConstruct %171 %18 %18 -%320 = OpCompositeConstruct %171 %7 %7 -%321 = OpBitwiseXor %171 %319 %320 -%322 = OpCompositeConstruct %182 %24 %24 %24 -%323 = OpCompositeConstruct %182 %25 %25 %25 -%324 = OpBitwiseXor %182 %322 %323 -%325 = OpShiftLeftLogical %8 %18 %25 -%326 = OpShiftLeftLogical %20 %24 %25 -%327 = OpCompositeConstruct %171 %18 %18 -%328 = OpCompositeConstruct %34 %25 %25 -%329 = OpShiftLeftLogical %171 %327 %328 -%330 = OpCompositeConstruct %182 %24 %24 %24 -%331 = OpCompositeConstruct %182 %25 %25 %25 -%332 = OpShiftLeftLogical %182 %330 %331 -%333 = OpShiftRightArithmetic %8 %18 %25 -%334 = OpShiftRightLogical %20 %24 %25 -%335 = OpCompositeConstruct %171 %18 %18 -%336 = OpCompositeConstruct %34 %25 %25 -%337 = OpShiftRightArithmetic %171 %335 %336 -%338 = OpCompositeConstruct %182 %24 %24 %24 -%339 = OpCompositeConstruct %182 %25 %25 %25 -%340 = OpShiftRightLogical %182 %338 %339 +OpBranch %296 +%296 = OpLabel +%297 = OpNot %8 %7 +%298 = OpNot %20 %25 +%299 = OpCompositeConstruct %171 %7 %7 +%300 = OpNot %171 %299 +%301 = OpCompositeConstruct %182 %25 %25 %25 +%302 = OpNot %182 %301 +%303 = OpBitwiseOr %8 %18 %7 +%304 = OpBitwiseOr %20 %24 %25 +%305 = OpCompositeConstruct %171 %18 %18 +%306 = OpCompositeConstruct %171 %7 %7 +%307 = OpBitwiseOr %171 %305 %306 +%308 = OpCompositeConstruct %182 %24 %24 %24 +%309 = OpCompositeConstruct %182 %25 %25 %25 +%310 = OpBitwiseOr %182 %308 %309 +%311 = OpBitwiseAnd %8 %18 %7 +%312 = OpBitwiseAnd %20 %24 %25 +%313 = OpCompositeConstruct %171 %18 %18 +%314 = OpCompositeConstruct %171 %7 %7 +%315 = OpBitwiseAnd %171 %313 %314 +%316 = OpCompositeConstruct %182 %24 %24 %24 +%317 = OpCompositeConstruct %182 %25 %25 %25 +%318 = OpBitwiseAnd %182 %316 %317 +%319 = OpBitwiseXor %8 %18 %7 +%320 = OpBitwiseXor %20 %24 %25 +%321 = OpCompositeConstruct %171 %18 %18 +%322 = OpCompositeConstruct %171 %7 %7 +%323 = OpBitwiseXor %171 %321 %322 +%324 = OpCompositeConstruct %182 %24 %24 %24 +%325 = OpCompositeConstruct %182 %25 %25 %25 +%326 = OpBitwiseXor %182 %324 %325 +%327 = OpShiftLeftLogical %8 %18 %25 +%328 = OpShiftLeftLogical %20 %24 %25 +%329 = OpCompositeConstruct %171 %18 %18 +%330 = OpCompositeConstruct %34 %25 %25 +%331 = OpShiftLeftLogical %171 %329 %330 +%332 = OpCompositeConstruct %182 %24 %24 %24 +%333 = OpCompositeConstruct %182 %25 %25 %25 +%334 = OpShiftLeftLogical %182 %332 %333 +%335 = OpShiftRightArithmetic %8 %18 %25 +%336 = OpShiftRightLogical %20 %24 %25 +%337 = OpCompositeConstruct %171 %18 %18 +%338 = OpCompositeConstruct %34 %25 %25 +%339 = OpShiftRightArithmetic %171 %337 %338 +%340 = OpCompositeConstruct %182 %24 %24 %24 +%341 = OpCompositeConstruct %182 %25 %25 %25 +%342 = OpShiftRightLogical %182 %340 %341 OpReturn OpFunctionEnd -%342 = OpFunction %2 None %152 -%341 = OpLabel -OpBranch %343 +%344 = OpFunction %2 None %152 %343 = OpLabel -%344 = OpIEqual %10 %18 %7 -%345 = OpIEqual %10 %24 %25 -%346 = OpFOrdEqual %10 %14 %3 -%347 = OpCompositeConstruct %171 %18 %18 -%348 = OpCompositeConstruct %171 %7 %7 -%349 = OpIEqual %155 %347 %348 -%350 = OpCompositeConstruct %182 %24 %24 %24 -%351 = OpCompositeConstruct %182 %25 %25 %25 -%352 = OpIEqual %100 %350 %351 -%353 = OpCompositeConstruct %26 %14 %14 %14 %14 -%354 = OpCompositeConstruct %26 %3 %3 %3 %3 -%355 = OpFOrdEqual %28 %353 %354 -%356 = OpINotEqual %10 %18 %7 -%357 = OpINotEqual %10 %24 %25 -%358 = OpFOrdNotEqual %10 %14 %3 -%359 = OpCompositeConstruct %171 %18 %18 -%360 = OpCompositeConstruct %171 %7 %7 -%361 = OpINotEqual %155 %359 %360 -%362 = OpCompositeConstruct %182 %24 %24 %24 -%363 = OpCompositeConstruct %182 %25 %25 %25 -%364 = OpINotEqual %100 %362 %363 -%365 = OpCompositeConstruct %26 %14 %14 %14 %14 -%366 = OpCompositeConstruct %26 %3 %3 %3 %3 -%367 = OpFOrdNotEqual %28 %365 %366 -%368 = OpSLessThan %10 %18 %7 -%369 = OpULessThan %10 %24 %25 -%370 = OpFOrdLessThan %10 %14 %3 -%371 = OpCompositeConstruct %171 %18 %18 -%372 = OpCompositeConstruct %171 %7 %7 -%373 = OpSLessThan %155 %371 %372 -%374 = OpCompositeConstruct %182 %24 %24 %24 -%375 = OpCompositeConstruct %182 %25 %25 %25 -%376 = OpULessThan %100 %374 %375 -%377 = OpCompositeConstruct %26 %14 %14 %14 %14 -%378 = OpCompositeConstruct %26 %3 %3 %3 %3 -%379 = OpFOrdLessThan %28 %377 %378 -%380 = OpSLessThanEqual %10 %18 %7 -%381 = OpULessThanEqual %10 %24 %25 -%382 = OpFOrdLessThanEqual %10 %14 %3 -%383 = OpCompositeConstruct %171 %18 %18 -%384 = OpCompositeConstruct %171 %7 %7 -%385 = OpSLessThanEqual %155 %383 %384 -%386 = OpCompositeConstruct %182 %24 %24 %24 -%387 = OpCompositeConstruct %182 %25 %25 %25 -%388 = OpULessThanEqual %100 %386 %387 -%389 = OpCompositeConstruct %26 %14 %14 %14 %14 -%390 = OpCompositeConstruct %26 %3 %3 %3 %3 -%391 = OpFOrdLessThanEqual %28 %389 %390 -%392 = OpSGreaterThan %10 %18 %7 -%393 = OpUGreaterThan %10 %24 %25 -%394 = OpFOrdGreaterThan %10 %14 %3 -%395 = OpCompositeConstruct %171 %18 %18 -%396 = OpCompositeConstruct %171 %7 %7 -%397 = OpSGreaterThan %155 %395 %396 -%398 = OpCompositeConstruct %182 %24 %24 %24 -%399 = OpCompositeConstruct %182 %25 %25 %25 -%400 = OpUGreaterThan %100 %398 %399 -%401 = OpCompositeConstruct %26 %14 %14 %14 %14 -%402 = OpCompositeConstruct %26 %3 %3 %3 %3 -%403 = OpFOrdGreaterThan %28 %401 %402 -%404 = OpSGreaterThanEqual %10 %18 %7 -%405 = OpUGreaterThanEqual %10 %24 %25 -%406 = OpFOrdGreaterThanEqual %10 %14 %3 -%407 = OpCompositeConstruct %171 %18 %18 -%408 = OpCompositeConstruct %171 %7 %7 -%409 = OpSGreaterThanEqual %155 %407 %408 -%410 = OpCompositeConstruct %182 %24 %24 %24 -%411 = OpCompositeConstruct %182 %25 %25 %25 -%412 = OpUGreaterThanEqual %100 %410 %411 -%413 = OpCompositeConstruct %26 %14 %14 %14 %14 -%414 = OpCompositeConstruct %26 %3 %3 %3 %3 -%415 = OpFOrdGreaterThanEqual %28 %413 %414 +OpBranch %345 +%345 = OpLabel +%346 = OpIEqual %10 %18 %7 +%347 = OpIEqual %10 %24 %25 +%348 = OpFOrdEqual %10 %14 %3 +%349 = OpCompositeConstruct %171 %18 %18 +%350 = OpCompositeConstruct %171 %7 %7 +%351 = OpIEqual %155 %349 %350 +%352 = OpCompositeConstruct %182 %24 %24 %24 +%353 = OpCompositeConstruct %182 %25 %25 %25 +%354 = OpIEqual %100 %352 %353 +%355 = OpCompositeConstruct %26 %14 %14 %14 %14 +%356 = OpCompositeConstruct %26 %3 %3 %3 %3 +%357 = OpFOrdEqual %28 %355 %356 +%358 = OpINotEqual %10 %18 %7 +%359 = OpINotEqual %10 %24 %25 +%360 = OpFOrdNotEqual %10 %14 %3 +%361 = OpCompositeConstruct %171 %18 %18 +%362 = OpCompositeConstruct %171 %7 %7 +%363 = OpINotEqual %155 %361 %362 +%364 = OpCompositeConstruct %182 %24 %24 %24 +%365 = OpCompositeConstruct %182 %25 %25 %25 +%366 = OpINotEqual %100 %364 %365 +%367 = OpCompositeConstruct %26 %14 %14 %14 %14 +%368 = OpCompositeConstruct %26 %3 %3 %3 %3 +%369 = OpFOrdNotEqual %28 %367 %368 +%370 = OpSLessThan %10 %18 %7 +%371 = OpULessThan %10 %24 %25 +%372 = OpFOrdLessThan %10 %14 %3 +%373 = OpCompositeConstruct %171 %18 %18 +%374 = OpCompositeConstruct %171 %7 %7 +%375 = OpSLessThan %155 %373 %374 +%376 = OpCompositeConstruct %182 %24 %24 %24 +%377 = OpCompositeConstruct %182 %25 %25 %25 +%378 = OpULessThan %100 %376 %377 +%379 = OpCompositeConstruct %26 %14 %14 %14 %14 +%380 = OpCompositeConstruct %26 %3 %3 %3 %3 +%381 = OpFOrdLessThan %28 %379 %380 +%382 = OpSLessThanEqual %10 %18 %7 +%383 = OpULessThanEqual %10 %24 %25 +%384 = OpFOrdLessThanEqual %10 %14 %3 +%385 = OpCompositeConstruct %171 %18 %18 +%386 = OpCompositeConstruct %171 %7 %7 +%387 = OpSLessThanEqual %155 %385 %386 +%388 = OpCompositeConstruct %182 %24 %24 %24 +%389 = OpCompositeConstruct %182 %25 %25 %25 +%390 = OpULessThanEqual %100 %388 %389 +%391 = OpCompositeConstruct %26 %14 %14 %14 %14 +%392 = OpCompositeConstruct %26 %3 %3 %3 %3 +%393 = OpFOrdLessThanEqual %28 %391 %392 +%394 = OpSGreaterThan %10 %18 %7 +%395 = OpUGreaterThan %10 %24 %25 +%396 = OpFOrdGreaterThan %10 %14 %3 +%397 = OpCompositeConstruct %171 %18 %18 +%398 = OpCompositeConstruct %171 %7 %7 +%399 = OpSGreaterThan %155 %397 %398 +%400 = OpCompositeConstruct %182 %24 %24 %24 +%401 = OpCompositeConstruct %182 %25 %25 %25 +%402 = OpUGreaterThan %100 %400 %401 +%403 = OpCompositeConstruct %26 %14 %14 %14 %14 +%404 = OpCompositeConstruct %26 %3 %3 %3 %3 +%405 = OpFOrdGreaterThan %28 %403 %404 +%406 = OpSGreaterThanEqual %10 %18 %7 +%407 = OpUGreaterThanEqual %10 %24 %25 +%408 = OpFOrdGreaterThanEqual %10 %14 %3 +%409 = OpCompositeConstruct %171 %18 %18 +%410 = OpCompositeConstruct %171 %7 %7 +%411 = OpSGreaterThanEqual %155 %409 %410 +%412 = OpCompositeConstruct %182 %24 %24 %24 +%413 = OpCompositeConstruct %182 %25 %25 %25 +%414 = OpUGreaterThanEqual %100 %412 %413 +%415 = OpCompositeConstruct %26 %14 %14 %14 %14 +%416 = OpCompositeConstruct %26 %3 %3 %3 %3 +%417 = OpFOrdGreaterThanEqual %28 %415 %416 OpReturn OpFunctionEnd -%418 = OpFunction %2 None %152 -%417 = OpLabel -%416 = OpVariable %111 Function %7 -OpBranch %419 +%420 = OpFunction %2 None %152 %419 = OpLabel -%420 = OpLoad %8 %416 -%421 = OpIAdd %8 %420 %7 -OpStore %416 %421 -%422 = OpLoad %8 %416 -%423 = OpISub %8 %422 %7 -OpStore %416 %423 -%424 = OpLoad %8 %416 -%425 = OpLoad %8 %416 -%426 = OpIMul %8 %424 %425 -OpStore %416 %426 -%427 = OpLoad %8 %416 -%428 = OpLoad %8 %416 -%429 = OpSDiv %8 %427 %428 -OpStore %416 %429 -%430 = OpLoad %8 %416 -%431 = OpSMod %8 %430 %7 -OpStore %416 %431 -%432 = OpLoad %8 %416 -%433 = OpBitwiseAnd %8 %432 %11 -OpStore %416 %433 -%434 = OpLoad %8 %416 -%435 = OpBitwiseOr %8 %434 %11 -OpStore %416 %435 -%436 = OpLoad %8 %416 -%437 = OpBitwiseXor %8 %436 %11 -OpStore %416 %437 -%438 = OpLoad %8 %416 -%439 = OpShiftLeftLogical %8 %438 %24 -OpStore %416 %439 -%440 = OpLoad %8 %416 -%441 = OpShiftRightArithmetic %8 %440 %25 -OpStore %416 %441 -%442 = OpLoad %8 %416 -%443 = OpIAdd %8 %442 %7 -OpStore %416 %443 -%444 = OpLoad %8 %416 -%445 = OpISub %8 %444 %7 -OpStore %416 %445 +%418 = OpVariable %111 Function %7 +OpBranch %421 +%421 = OpLabel +%422 = OpLoad %8 %418 +%423 = OpIAdd %8 %422 %7 +OpStore %418 %423 +%424 = OpLoad %8 %418 +%425 = OpISub %8 %424 %7 +OpStore %418 %425 +%426 = OpLoad %8 %418 +%427 = OpLoad %8 %418 +%428 = OpIMul %8 %426 %427 +OpStore %418 %428 +%429 = OpLoad %8 %418 +%430 = OpLoad %8 %418 +%431 = OpSDiv %8 %429 %430 +OpStore %418 %431 +%432 = OpLoad %8 %418 +%433 = OpSMod %8 %432 %7 +OpStore %418 %433 +%434 = OpLoad %8 %418 +%435 = OpBitwiseAnd %8 %434 %11 +OpStore %418 %435 +%436 = OpLoad %8 %418 +%437 = OpBitwiseOr %8 %436 %11 +OpStore %418 %437 +%438 = OpLoad %8 %418 +%439 = OpBitwiseXor %8 %438 %11 +OpStore %418 %439 +%440 = OpLoad %8 %418 +%441 = OpShiftLeftLogical %8 %440 %24 +OpStore %418 %441 +%442 = OpLoad %8 %418 +%443 = OpShiftRightArithmetic %8 %442 %25 +OpStore %418 %443 +%444 = OpLoad %8 %418 +%445 = OpIAdd %8 %444 %7 +OpStore %418 %445 +%446 = OpLoad %8 %418 +%447 = OpISub %8 %446 %7 +OpStore %418 %447 OpReturn OpFunctionEnd -%447 = OpFunction %2 None %152 -%446 = OpLabel -OpBranch %448 +%449 = OpFunction %2 None %152 %448 = OpLabel -%449 = OpFunctionCall %26 %55 -%450 = OpFunctionCall %26 %80 -%451 = OpVectorShuffle %29 %40 %40 0 1 2 -%452 = OpFunctionCall %29 %97 %451 -%453 = OpFunctionCall %4 %128 -%454 = OpFunctionCall %2 %151 -%455 = OpFunctionCall %2 %169 -%456 = OpFunctionCall %2 %293 -%457 = OpFunctionCall %2 %342 -%458 = OpFunctionCall %2 %418 +OpBranch %450 +%450 = OpLabel +%451 = OpFunctionCall %26 %55 +%452 = OpFunctionCall %26 %80 +%453 = OpVectorShuffle %29 %40 %40 0 1 2 +%454 = OpFunctionCall %29 %97 %453 +%455 = OpFunctionCall %4 %128 +%456 = OpFunctionCall %2 %151 +%457 = OpFunctionCall %2 %169 +%458 = OpFunctionCall %2 %295 +%459 = OpFunctionCall %2 %344 +%460 = OpFunctionCall %2 %420 OpReturn OpFunctionEnd \ No newline at end of file From d3b37dcdb16089776ff5eeebeea6e85f3fd76956 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 17:28:05 +0200 Subject: [PATCH 1683/2212] add tests for remaining vector - scalar ops --- tests/in/operators.wgsl | 20 + tests/out/glsl/operators.main.Compute.glsl | 170 ++++--- tests/out/hlsl/operators.hlsl | 170 ++++--- tests/out/msl/operators.msl | 170 ++++--- tests/out/spv/operators.spvasm | 524 ++++++++++++--------- tests/out/wgsl/operators.wgsl | 170 ++++--- 6 files changed, 691 insertions(+), 533 deletions(-) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index c69cfbfad..54949f419 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -137,18 +137,38 @@ fn arithmetic() { // Binary arithmetic expressions with mixed scalar and vector operands let _ = vec2(2) + 1; let _ = 2 + vec2(1); + let _ = vec2(2u) + 1u; + let _ = 2u + vec2(1u); + let _ = vec2(2.0) + 1.0; + let _ = 2.0 + vec2(1.0); let _ = vec2(2) - 1; let _ = 2 - vec2(1); + let _ = vec2(2u) - 1u; + let _ = 2u - vec2(1u); + let _ = vec2(2.0) - 1.0; + let _ = 2.0 - vec2(1.0); let _ = vec2(2) * 1; let _ = 2 * vec2(1); + let _ = vec2(2u) * 1u; + let _ = 2u * vec2(1u); + let _ = vec2(2.0) * 1.0; + let _ = 2.0 * vec2(1.0); let _ = vec2(2) / 1; let _ = 2 / vec2(1); + let _ = vec2(2u) / 1u; + let _ = 2u / vec2(1u); + let _ = vec2(2.0) / 1.0; + let _ = 2.0 / vec2(1.0); let _ = vec2(2) % 1; let _ = 2 % vec2(1); + let _ = vec2(2u) % 1u; + let _ = 2u % vec2(1u); + let _ = vec2(2.0) % 1.0; + let _ = 2.0 % vec2(1.0); // Matrix arithmetic let _ = mat3x3() + mat3x3(); diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index dc741b1eb..464dc9776 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -102,87 +102,107 @@ void arithmetic() { vec4 unnamed_50 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); ivec2 unnamed_51 = (ivec2(2) + ivec2(1)); ivec2 unnamed_52 = (ivec2(2) + ivec2(1)); - ivec2 unnamed_53 = (ivec2(2) - ivec2(1)); - ivec2 unnamed_54 = (ivec2(2) - ivec2(1)); - ivec2 unnamed_55 = (ivec2(2) * 1); - ivec2 unnamed_56 = (2 * ivec2(1)); - ivec2 unnamed_57 = (ivec2(2) / ivec2(1)); - ivec2 unnamed_58 = (ivec2(2) / ivec2(1)); - ivec2 unnamed_59 = (ivec2(2) % ivec2(1)); - ivec2 unnamed_60 = (ivec2(2) % ivec2(1)); - mat3x3 unnamed_61 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_62 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_63 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - mat3x3 unnamed_64 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - vec3 unnamed_65 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - vec4 unnamed_66 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_67 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + uvec2 unnamed_53 = (uvec2(2u) + uvec2(1u)); + uvec2 unnamed_54 = (uvec2(2u) + uvec2(1u)); + vec2 unnamed_55 = (vec2(2.0) + vec2(1.0)); + vec2 unnamed_56 = (vec2(2.0) + vec2(1.0)); + ivec2 unnamed_57 = (ivec2(2) - ivec2(1)); + ivec2 unnamed_58 = (ivec2(2) - ivec2(1)); + uvec2 unnamed_59 = (uvec2(2u) - uvec2(1u)); + uvec2 unnamed_60 = (uvec2(2u) - uvec2(1u)); + vec2 unnamed_61 = (vec2(2.0) - vec2(1.0)); + vec2 unnamed_62 = (vec2(2.0) - vec2(1.0)); + ivec2 unnamed_63 = (ivec2(2) * 1); + ivec2 unnamed_64 = (2 * ivec2(1)); + uvec2 unnamed_65 = (uvec2(2u) * 1u); + uvec2 unnamed_66 = (2u * uvec2(1u)); + vec2 unnamed_67 = (vec2(2.0) * 1.0); + vec2 unnamed_68 = (2.0 * vec2(1.0)); + ivec2 unnamed_69 = (ivec2(2) / ivec2(1)); + ivec2 unnamed_70 = (ivec2(2) / ivec2(1)); + uvec2 unnamed_71 = (uvec2(2u) / uvec2(1u)); + uvec2 unnamed_72 = (uvec2(2u) / uvec2(1u)); + vec2 unnamed_73 = (vec2(2.0) / vec2(1.0)); + vec2 unnamed_74 = (vec2(2.0) / vec2(1.0)); + ivec2 unnamed_75 = (ivec2(2) % ivec2(1)); + ivec2 unnamed_76 = (ivec2(2) % ivec2(1)); + uvec2 unnamed_77 = (uvec2(2u) % uvec2(1u)); + uvec2 unnamed_78 = (uvec2(2u) % uvec2(1u)); + vec2 unnamed_79 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + vec2 unnamed_80 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + mat3x3 unnamed_81 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_82 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_83 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + mat3x3 unnamed_84 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + vec3 unnamed_85 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + vec4 unnamed_86 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_87 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } void bit() { - int unnamed_68 = (~ 1); - uint unnamed_69 = (~ 1u); - ivec2 unnamed_70 = (~ ivec2(1)); - uvec3 unnamed_71 = (~ uvec3(1u)); - int unnamed_72 = (2 | 1); - uint unnamed_73 = (2u | 1u); - ivec2 unnamed_74 = (ivec2(2) | ivec2(1)); - uvec3 unnamed_75 = (uvec3(2u) | uvec3(1u)); - int unnamed_76 = (2 & 1); - uint unnamed_77 = (2u & 1u); - ivec2 unnamed_78 = (ivec2(2) & ivec2(1)); - uvec3 unnamed_79 = (uvec3(2u) & uvec3(1u)); - int unnamed_80 = (2 ^ 1); - uint unnamed_81 = (2u ^ 1u); - ivec2 unnamed_82 = (ivec2(2) ^ ivec2(1)); - uvec3 unnamed_83 = (uvec3(2u) ^ uvec3(1u)); - int unnamed_84 = (2 << 1u); - uint unnamed_85 = (2u << 1u); - ivec2 unnamed_86 = (ivec2(2) << uvec2(1u)); - uvec3 unnamed_87 = (uvec3(2u) << uvec3(1u)); - int unnamed_88 = (2 >> 1u); - uint unnamed_89 = (2u >> 1u); - ivec2 unnamed_90 = (ivec2(2) >> uvec2(1u)); - uvec3 unnamed_91 = (uvec3(2u) >> uvec3(1u)); + int unnamed_88 = (~ 1); + uint unnamed_89 = (~ 1u); + ivec2 unnamed_90 = (~ ivec2(1)); + uvec3 unnamed_91 = (~ uvec3(1u)); + int unnamed_92 = (2 | 1); + uint unnamed_93 = (2u | 1u); + ivec2 unnamed_94 = (ivec2(2) | ivec2(1)); + uvec3 unnamed_95 = (uvec3(2u) | uvec3(1u)); + int unnamed_96 = (2 & 1); + uint unnamed_97 = (2u & 1u); + ivec2 unnamed_98 = (ivec2(2) & ivec2(1)); + uvec3 unnamed_99 = (uvec3(2u) & uvec3(1u)); + int unnamed_100 = (2 ^ 1); + uint unnamed_101 = (2u ^ 1u); + ivec2 unnamed_102 = (ivec2(2) ^ ivec2(1)); + uvec3 unnamed_103 = (uvec3(2u) ^ uvec3(1u)); + int unnamed_104 = (2 << 1u); + uint unnamed_105 = (2u << 1u); + ivec2 unnamed_106 = (ivec2(2) << uvec2(1u)); + uvec3 unnamed_107 = (uvec3(2u) << uvec3(1u)); + int unnamed_108 = (2 >> 1u); + uint unnamed_109 = (2u >> 1u); + ivec2 unnamed_110 = (ivec2(2) >> uvec2(1u)); + uvec3 unnamed_111 = (uvec3(2u) >> uvec3(1u)); } void comparison() { - bool unnamed_92 = (2 == 1); - bool unnamed_93 = (2u == 1u); - bool unnamed_94 = (2.0 == 1.0); - bvec2 unnamed_95 = equal(ivec2(2), ivec2(1)); - bvec3 unnamed_96 = equal(uvec3(2u), uvec3(1u)); - bvec4 unnamed_97 = equal(vec4(2.0), vec4(1.0)); - bool unnamed_98 = (2 != 1); - bool unnamed_99 = (2u != 1u); - bool unnamed_100 = (2.0 != 1.0); - bvec2 unnamed_101 = notEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_102 = notEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_103 = notEqual(vec4(2.0), vec4(1.0)); - bool unnamed_104 = (2 < 1); - bool unnamed_105 = (2u < 1u); - bool unnamed_106 = (2.0 < 1.0); - bvec2 unnamed_107 = lessThan(ivec2(2), ivec2(1)); - bvec3 unnamed_108 = lessThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_109 = lessThan(vec4(2.0), vec4(1.0)); - bool unnamed_110 = (2 <= 1); - bool unnamed_111 = (2u <= 1u); - bool unnamed_112 = (2.0 <= 1.0); - bvec2 unnamed_113 = lessThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_114 = lessThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_115 = lessThanEqual(vec4(2.0), vec4(1.0)); - bool unnamed_116 = (2 > 1); - bool unnamed_117 = (2u > 1u); - bool unnamed_118 = (2.0 > 1.0); - bvec2 unnamed_119 = greaterThan(ivec2(2), ivec2(1)); - bvec3 unnamed_120 = greaterThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_121 = greaterThan(vec4(2.0), vec4(1.0)); - bool unnamed_122 = (2 >= 1); - bool unnamed_123 = (2u >= 1u); - bool unnamed_124 = (2.0 >= 1.0); - bvec2 unnamed_125 = greaterThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_126 = greaterThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_127 = greaterThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_112 = (2 == 1); + bool unnamed_113 = (2u == 1u); + bool unnamed_114 = (2.0 == 1.0); + bvec2 unnamed_115 = equal(ivec2(2), ivec2(1)); + bvec3 unnamed_116 = equal(uvec3(2u), uvec3(1u)); + bvec4 unnamed_117 = equal(vec4(2.0), vec4(1.0)); + bool unnamed_118 = (2 != 1); + bool unnamed_119 = (2u != 1u); + bool unnamed_120 = (2.0 != 1.0); + bvec2 unnamed_121 = notEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_122 = notEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_123 = notEqual(vec4(2.0), vec4(1.0)); + bool unnamed_124 = (2 < 1); + bool unnamed_125 = (2u < 1u); + bool unnamed_126 = (2.0 < 1.0); + bvec2 unnamed_127 = lessThan(ivec2(2), ivec2(1)); + bvec3 unnamed_128 = lessThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_129 = lessThan(vec4(2.0), vec4(1.0)); + bool unnamed_130 = (2 <= 1); + bool unnamed_131 = (2u <= 1u); + bool unnamed_132 = (2.0 <= 1.0); + bvec2 unnamed_133 = lessThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_134 = lessThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_135 = lessThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_136 = (2 > 1); + bool unnamed_137 = (2u > 1u); + bool unnamed_138 = (2.0 > 1.0); + bvec2 unnamed_139 = greaterThan(ivec2(2), ivec2(1)); + bvec3 unnamed_140 = greaterThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_141 = greaterThan(vec4(2.0), vec4(1.0)); + bool unnamed_142 = (2 >= 1); + bool unnamed_143 = (2u >= 1u); + bool unnamed_144 = (2.0 >= 1.0); + bvec2 unnamed_145 = greaterThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_146 = greaterThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_147 = greaterThanEqual(vec4(2.0), vec4(1.0)); } void assignment() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index c6e03def9..b23d47799 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -130,89 +130,109 @@ void arithmetic() float4 unnamed_50 = ((2.0).xxxx % (1.0).xxxx); int2 unnamed_51 = ((2).xx + (1).xx); int2 unnamed_52 = ((2).xx + (1).xx); - int2 unnamed_53 = ((2).xx - (1).xx); - int2 unnamed_54 = ((2).xx - (1).xx); - int2 unnamed_55 = ((2).xx * 1); - int2 unnamed_56 = (2 * (1).xx); - int2 unnamed_57 = ((2).xx / (1).xx); - int2 unnamed_58 = ((2).xx / (1).xx); - int2 unnamed_59 = ((2).xx % (1).xx); - int2 unnamed_60 = ((2).xx % (1).xx); - float3x3 unnamed_61 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_62 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_63 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_64 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); - float3 unnamed_65 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float4 unnamed_66 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); - float3x3 unnamed_67 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + uint2 unnamed_53 = ((2u).xx + (1u).xx); + uint2 unnamed_54 = ((2u).xx + (1u).xx); + float2 unnamed_55 = ((2.0).xx + (1.0).xx); + float2 unnamed_56 = ((2.0).xx + (1.0).xx); + int2 unnamed_57 = ((2).xx - (1).xx); + int2 unnamed_58 = ((2).xx - (1).xx); + uint2 unnamed_59 = ((2u).xx - (1u).xx); + uint2 unnamed_60 = ((2u).xx - (1u).xx); + float2 unnamed_61 = ((2.0).xx - (1.0).xx); + float2 unnamed_62 = ((2.0).xx - (1.0).xx); + int2 unnamed_63 = ((2).xx * 1); + int2 unnamed_64 = (2 * (1).xx); + uint2 unnamed_65 = ((2u).xx * 1u); + uint2 unnamed_66 = (2u * (1u).xx); + float2 unnamed_67 = ((2.0).xx * 1.0); + float2 unnamed_68 = (2.0 * (1.0).xx); + int2 unnamed_69 = ((2).xx / (1).xx); + int2 unnamed_70 = ((2).xx / (1).xx); + uint2 unnamed_71 = ((2u).xx / (1u).xx); + uint2 unnamed_72 = ((2u).xx / (1u).xx); + float2 unnamed_73 = ((2.0).xx / (1.0).xx); + float2 unnamed_74 = ((2.0).xx / (1.0).xx); + int2 unnamed_75 = ((2).xx % (1).xx); + int2 unnamed_76 = ((2).xx % (1).xx); + uint2 unnamed_77 = ((2u).xx % (1u).xx); + uint2 unnamed_78 = ((2u).xx % (1u).xx); + float2 unnamed_79 = ((2.0).xx % (1.0).xx); + float2 unnamed_80 = ((2.0).xx % (1.0).xx); + float3x3 unnamed_81 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_82 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_83 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_84 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); + float3 unnamed_85 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float4 unnamed_86 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); + float3x3 unnamed_87 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); } void bit() { - int unnamed_68 = ~1; - uint unnamed_69 = ~1u; - int2 unnamed_70 = ~(1).xx; - uint3 unnamed_71 = ~(1u).xxx; - int unnamed_72 = (2 | 1); - uint unnamed_73 = (2u | 1u); - int2 unnamed_74 = ((2).xx | (1).xx); - uint3 unnamed_75 = ((2u).xxx | (1u).xxx); - int unnamed_76 = (2 & 1); - uint unnamed_77 = (2u & 1u); - int2 unnamed_78 = ((2).xx & (1).xx); - uint3 unnamed_79 = ((2u).xxx & (1u).xxx); - int unnamed_80 = (2 ^ 1); - uint unnamed_81 = (2u ^ 1u); - int2 unnamed_82 = ((2).xx ^ (1).xx); - uint3 unnamed_83 = ((2u).xxx ^ (1u).xxx); - int unnamed_84 = (2 << 1u); - uint unnamed_85 = (2u << 1u); - int2 unnamed_86 = ((2).xx << (1u).xx); - uint3 unnamed_87 = ((2u).xxx << (1u).xxx); - int unnamed_88 = (2 >> 1u); - uint unnamed_89 = (2u >> 1u); - int2 unnamed_90 = ((2).xx >> (1u).xx); - uint3 unnamed_91 = ((2u).xxx >> (1u).xxx); + int unnamed_88 = ~1; + uint unnamed_89 = ~1u; + int2 unnamed_90 = ~(1).xx; + uint3 unnamed_91 = ~(1u).xxx; + int unnamed_92 = (2 | 1); + uint unnamed_93 = (2u | 1u); + int2 unnamed_94 = ((2).xx | (1).xx); + uint3 unnamed_95 = ((2u).xxx | (1u).xxx); + int unnamed_96 = (2 & 1); + uint unnamed_97 = (2u & 1u); + int2 unnamed_98 = ((2).xx & (1).xx); + uint3 unnamed_99 = ((2u).xxx & (1u).xxx); + int unnamed_100 = (2 ^ 1); + uint unnamed_101 = (2u ^ 1u); + int2 unnamed_102 = ((2).xx ^ (1).xx); + uint3 unnamed_103 = ((2u).xxx ^ (1u).xxx); + int unnamed_104 = (2 << 1u); + uint unnamed_105 = (2u << 1u); + int2 unnamed_106 = ((2).xx << (1u).xx); + uint3 unnamed_107 = ((2u).xxx << (1u).xxx); + int unnamed_108 = (2 >> 1u); + uint unnamed_109 = (2u >> 1u); + int2 unnamed_110 = ((2).xx >> (1u).xx); + uint3 unnamed_111 = ((2u).xxx >> (1u).xxx); } void comparison() { - bool unnamed_92 = (2 == 1); - bool unnamed_93 = (2u == 1u); - bool unnamed_94 = (2.0 == 1.0); - bool2 unnamed_95 = ((2).xx == (1).xx); - bool3 unnamed_96 = ((2u).xxx == (1u).xxx); - bool4 unnamed_97 = ((2.0).xxxx == (1.0).xxxx); - bool unnamed_98 = (2 != 1); - bool unnamed_99 = (2u != 1u); - bool unnamed_100 = (2.0 != 1.0); - bool2 unnamed_101 = ((2).xx != (1).xx); - bool3 unnamed_102 = ((2u).xxx != (1u).xxx); - bool4 unnamed_103 = ((2.0).xxxx != (1.0).xxxx); - bool unnamed_104 = (2 < 1); - bool unnamed_105 = (2u < 1u); - bool unnamed_106 = (2.0 < 1.0); - bool2 unnamed_107 = ((2).xx < (1).xx); - bool3 unnamed_108 = ((2u).xxx < (1u).xxx); - bool4 unnamed_109 = ((2.0).xxxx < (1.0).xxxx); - bool unnamed_110 = (2 <= 1); - bool unnamed_111 = (2u <= 1u); - bool unnamed_112 = (2.0 <= 1.0); - bool2 unnamed_113 = ((2).xx <= (1).xx); - bool3 unnamed_114 = ((2u).xxx <= (1u).xxx); - bool4 unnamed_115 = ((2.0).xxxx <= (1.0).xxxx); - bool unnamed_116 = (2 > 1); - bool unnamed_117 = (2u > 1u); - bool unnamed_118 = (2.0 > 1.0); - bool2 unnamed_119 = ((2).xx > (1).xx); - bool3 unnamed_120 = ((2u).xxx > (1u).xxx); - bool4 unnamed_121 = ((2.0).xxxx > (1.0).xxxx); - bool unnamed_122 = (2 >= 1); - bool unnamed_123 = (2u >= 1u); - bool unnamed_124 = (2.0 >= 1.0); - bool2 unnamed_125 = ((2).xx >= (1).xx); - bool3 unnamed_126 = ((2u).xxx >= (1u).xxx); - bool4 unnamed_127 = ((2.0).xxxx >= (1.0).xxxx); + bool unnamed_112 = (2 == 1); + bool unnamed_113 = (2u == 1u); + bool unnamed_114 = (2.0 == 1.0); + bool2 unnamed_115 = ((2).xx == (1).xx); + bool3 unnamed_116 = ((2u).xxx == (1u).xxx); + bool4 unnamed_117 = ((2.0).xxxx == (1.0).xxxx); + bool unnamed_118 = (2 != 1); + bool unnamed_119 = (2u != 1u); + bool unnamed_120 = (2.0 != 1.0); + bool2 unnamed_121 = ((2).xx != (1).xx); + bool3 unnamed_122 = ((2u).xxx != (1u).xxx); + bool4 unnamed_123 = ((2.0).xxxx != (1.0).xxxx); + bool unnamed_124 = (2 < 1); + bool unnamed_125 = (2u < 1u); + bool unnamed_126 = (2.0 < 1.0); + bool2 unnamed_127 = ((2).xx < (1).xx); + bool3 unnamed_128 = ((2u).xxx < (1u).xxx); + bool4 unnamed_129 = ((2.0).xxxx < (1.0).xxxx); + bool unnamed_130 = (2 <= 1); + bool unnamed_131 = (2u <= 1u); + bool unnamed_132 = (2.0 <= 1.0); + bool2 unnamed_133 = ((2).xx <= (1).xx); + bool3 unnamed_134 = ((2u).xxx <= (1u).xxx); + bool4 unnamed_135 = ((2.0).xxxx <= (1.0).xxxx); + bool unnamed_136 = (2 > 1); + bool unnamed_137 = (2u > 1u); + bool unnamed_138 = (2.0 > 1.0); + bool2 unnamed_139 = ((2).xx > (1).xx); + bool3 unnamed_140 = ((2u).xxx > (1u).xxx); + bool4 unnamed_141 = ((2.0).xxxx > (1.0).xxxx); + bool unnamed_142 = (2 >= 1); + bool unnamed_143 = (2u >= 1u); + bool unnamed_144 = (2.0 >= 1.0); + bool2 unnamed_145 = ((2).xx >= (1).xx); + bool3 unnamed_146 = ((2u).xxx >= (1u).xxx); + bool4 unnamed_147 = ((2.0).xxxx >= (1.0).xxxx); } void assignment() diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 573bad182..02a9fd6f7 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -128,89 +128,109 @@ void arithmetic( metal::float4 unnamed_50 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); metal::int2 unnamed_51 = metal::int2(2) + metal::int2(1); metal::int2 unnamed_52 = metal::int2(2) + metal::int2(1); - metal::int2 unnamed_53 = metal::int2(2) - metal::int2(1); - metal::int2 unnamed_54 = metal::int2(2) - metal::int2(1); - metal::int2 unnamed_55 = metal::int2(2) * 1; - metal::int2 unnamed_56 = 2 * metal::int2(1); - metal::int2 unnamed_57 = metal::int2(2) / metal::int2(1); - metal::int2 unnamed_58 = metal::int2(2) / metal::int2(1); - metal::int2 unnamed_59 = metal::int2(2) % metal::int2(1); - metal::int2 unnamed_60 = metal::int2(2) % metal::int2(1); - metal::float3x3 unnamed_61 = const_type_14_ + const_type_14_; - metal::float3x3 unnamed_62 = const_type_14_ - const_type_14_; - metal::float3x3 unnamed_63 = const_type_14_ * 1.0; - metal::float3x3 unnamed_64 = 2.0 * const_type_14_; - metal::float3 unnamed_65 = const_type_15_ * metal::float4(1.0); - metal::float4 unnamed_66 = metal::float3(2.0) * const_type_15_; - metal::float3x3 unnamed_67 = const_type_15_ * const_type_16_; + metal::uint2 unnamed_53 = metal::uint2(2u) + metal::uint2(1u); + metal::uint2 unnamed_54 = metal::uint2(2u) + metal::uint2(1u); + metal::float2 unnamed_55 = metal::float2(2.0) + metal::float2(1.0); + metal::float2 unnamed_56 = metal::float2(2.0) + metal::float2(1.0); + metal::int2 unnamed_57 = metal::int2(2) - metal::int2(1); + metal::int2 unnamed_58 = metal::int2(2) - metal::int2(1); + metal::uint2 unnamed_59 = metal::uint2(2u) - metal::uint2(1u); + metal::uint2 unnamed_60 = metal::uint2(2u) - metal::uint2(1u); + metal::float2 unnamed_61 = metal::float2(2.0) - metal::float2(1.0); + metal::float2 unnamed_62 = metal::float2(2.0) - metal::float2(1.0); + metal::int2 unnamed_63 = metal::int2(2) * 1; + metal::int2 unnamed_64 = 2 * metal::int2(1); + metal::uint2 unnamed_65 = metal::uint2(2u) * 1u; + metal::uint2 unnamed_66 = 2u * metal::uint2(1u); + metal::float2 unnamed_67 = metal::float2(2.0) * 1.0; + metal::float2 unnamed_68 = 2.0 * metal::float2(1.0); + metal::int2 unnamed_69 = metal::int2(2) / metal::int2(1); + metal::int2 unnamed_70 = metal::int2(2) / metal::int2(1); + metal::uint2 unnamed_71 = metal::uint2(2u) / metal::uint2(1u); + metal::uint2 unnamed_72 = metal::uint2(2u) / metal::uint2(1u); + metal::float2 unnamed_73 = metal::float2(2.0) / metal::float2(1.0); + metal::float2 unnamed_74 = metal::float2(2.0) / metal::float2(1.0); + metal::int2 unnamed_75 = metal::int2(2) % metal::int2(1); + metal::int2 unnamed_76 = metal::int2(2) % metal::int2(1); + metal::uint2 unnamed_77 = metal::uint2(2u) % metal::uint2(1u); + metal::uint2 unnamed_78 = metal::uint2(2u) % metal::uint2(1u); + metal::float2 unnamed_79 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + metal::float2 unnamed_80 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + metal::float3x3 unnamed_81 = const_type_14_ + const_type_14_; + metal::float3x3 unnamed_82 = const_type_14_ - const_type_14_; + metal::float3x3 unnamed_83 = const_type_14_ * 1.0; + metal::float3x3 unnamed_84 = 2.0 * const_type_14_; + metal::float3 unnamed_85 = const_type_15_ * metal::float4(1.0); + metal::float4 unnamed_86 = metal::float3(2.0) * const_type_15_; + metal::float3x3 unnamed_87 = const_type_15_ * const_type_16_; } void bit( ) { - int unnamed_68 = ~1; - uint unnamed_69 = ~1u; - metal::int2 unnamed_70 = ~metal::int2(1); - metal::uint3 unnamed_71 = ~metal::uint3(1u); - int unnamed_72 = 2 | 1; - uint unnamed_73 = 2u | 1u; - metal::int2 unnamed_74 = metal::int2(2) | metal::int2(1); - metal::uint3 unnamed_75 = metal::uint3(2u) | metal::uint3(1u); - int unnamed_76 = 2 & 1; - uint unnamed_77 = 2u & 1u; - metal::int2 unnamed_78 = metal::int2(2) & metal::int2(1); - metal::uint3 unnamed_79 = metal::uint3(2u) & metal::uint3(1u); - int unnamed_80 = 2 ^ 1; - uint unnamed_81 = 2u ^ 1u; - metal::int2 unnamed_82 = metal::int2(2) ^ metal::int2(1); - metal::uint3 unnamed_83 = metal::uint3(2u) ^ metal::uint3(1u); - int unnamed_84 = 2 << 1u; - uint unnamed_85 = 2u << 1u; - metal::int2 unnamed_86 = metal::int2(2) << metal::uint2(1u); - metal::uint3 unnamed_87 = metal::uint3(2u) << metal::uint3(1u); - int unnamed_88 = 2 >> 1u; - uint unnamed_89 = 2u >> 1u; - metal::int2 unnamed_90 = metal::int2(2) >> metal::uint2(1u); - metal::uint3 unnamed_91 = metal::uint3(2u) >> metal::uint3(1u); + int unnamed_88 = ~1; + uint unnamed_89 = ~1u; + metal::int2 unnamed_90 = ~metal::int2(1); + metal::uint3 unnamed_91 = ~metal::uint3(1u); + int unnamed_92 = 2 | 1; + uint unnamed_93 = 2u | 1u; + metal::int2 unnamed_94 = metal::int2(2) | metal::int2(1); + metal::uint3 unnamed_95 = metal::uint3(2u) | metal::uint3(1u); + int unnamed_96 = 2 & 1; + uint unnamed_97 = 2u & 1u; + metal::int2 unnamed_98 = metal::int2(2) & metal::int2(1); + metal::uint3 unnamed_99 = metal::uint3(2u) & metal::uint3(1u); + int unnamed_100 = 2 ^ 1; + uint unnamed_101 = 2u ^ 1u; + metal::int2 unnamed_102 = metal::int2(2) ^ metal::int2(1); + metal::uint3 unnamed_103 = metal::uint3(2u) ^ metal::uint3(1u); + int unnamed_104 = 2 << 1u; + uint unnamed_105 = 2u << 1u; + metal::int2 unnamed_106 = metal::int2(2) << metal::uint2(1u); + metal::uint3 unnamed_107 = metal::uint3(2u) << metal::uint3(1u); + int unnamed_108 = 2 >> 1u; + uint unnamed_109 = 2u >> 1u; + metal::int2 unnamed_110 = metal::int2(2) >> metal::uint2(1u); + metal::uint3 unnamed_111 = metal::uint3(2u) >> metal::uint3(1u); } void comparison( ) { - bool unnamed_92 = 2 == 1; - bool unnamed_93 = 2u == 1u; - bool unnamed_94 = 2.0 == 1.0; - metal::bool2 unnamed_95 = metal::int2(2) == metal::int2(1); - metal::bool3 unnamed_96 = metal::uint3(2u) == metal::uint3(1u); - metal::bool4 unnamed_97 = metal::float4(2.0) == metal::float4(1.0); - bool unnamed_98 = 2 != 1; - bool unnamed_99 = 2u != 1u; - bool unnamed_100 = 2.0 != 1.0; - metal::bool2 unnamed_101 = metal::int2(2) != metal::int2(1); - metal::bool3 unnamed_102 = metal::uint3(2u) != metal::uint3(1u); - metal::bool4 unnamed_103 = metal::float4(2.0) != metal::float4(1.0); - bool unnamed_104 = 2 < 1; - bool unnamed_105 = 2u < 1u; - bool unnamed_106 = 2.0 < 1.0; - metal::bool2 unnamed_107 = metal::int2(2) < metal::int2(1); - metal::bool3 unnamed_108 = metal::uint3(2u) < metal::uint3(1u); - metal::bool4 unnamed_109 = metal::float4(2.0) < metal::float4(1.0); - bool unnamed_110 = 2 <= 1; - bool unnamed_111 = 2u <= 1u; - bool unnamed_112 = 2.0 <= 1.0; - metal::bool2 unnamed_113 = metal::int2(2) <= metal::int2(1); - metal::bool3 unnamed_114 = metal::uint3(2u) <= metal::uint3(1u); - metal::bool4 unnamed_115 = metal::float4(2.0) <= metal::float4(1.0); - bool unnamed_116 = 2 > 1; - bool unnamed_117 = 2u > 1u; - bool unnamed_118 = 2.0 > 1.0; - metal::bool2 unnamed_119 = metal::int2(2) > metal::int2(1); - metal::bool3 unnamed_120 = metal::uint3(2u) > metal::uint3(1u); - metal::bool4 unnamed_121 = metal::float4(2.0) > metal::float4(1.0); - bool unnamed_122 = 2 >= 1; - bool unnamed_123 = 2u >= 1u; - bool unnamed_124 = 2.0 >= 1.0; - metal::bool2 unnamed_125 = metal::int2(2) >= metal::int2(1); - metal::bool3 unnamed_126 = metal::uint3(2u) >= metal::uint3(1u); - metal::bool4 unnamed_127 = metal::float4(2.0) >= metal::float4(1.0); + bool unnamed_112 = 2 == 1; + bool unnamed_113 = 2u == 1u; + bool unnamed_114 = 2.0 == 1.0; + metal::bool2 unnamed_115 = metal::int2(2) == metal::int2(1); + metal::bool3 unnamed_116 = metal::uint3(2u) == metal::uint3(1u); + metal::bool4 unnamed_117 = metal::float4(2.0) == metal::float4(1.0); + bool unnamed_118 = 2 != 1; + bool unnamed_119 = 2u != 1u; + bool unnamed_120 = 2.0 != 1.0; + metal::bool2 unnamed_121 = metal::int2(2) != metal::int2(1); + metal::bool3 unnamed_122 = metal::uint3(2u) != metal::uint3(1u); + metal::bool4 unnamed_123 = metal::float4(2.0) != metal::float4(1.0); + bool unnamed_124 = 2 < 1; + bool unnamed_125 = 2u < 1u; + bool unnamed_126 = 2.0 < 1.0; + metal::bool2 unnamed_127 = metal::int2(2) < metal::int2(1); + metal::bool3 unnamed_128 = metal::uint3(2u) < metal::uint3(1u); + metal::bool4 unnamed_129 = metal::float4(2.0) < metal::float4(1.0); + bool unnamed_130 = 2 <= 1; + bool unnamed_131 = 2u <= 1u; + bool unnamed_132 = 2.0 <= 1.0; + metal::bool2 unnamed_133 = metal::int2(2) <= metal::int2(1); + metal::bool3 unnamed_134 = metal::uint3(2u) <= metal::uint3(1u); + metal::bool4 unnamed_135 = metal::float4(2.0) <= metal::float4(1.0); + bool unnamed_136 = 2 > 1; + bool unnamed_137 = 2u > 1u; + bool unnamed_138 = 2.0 > 1.0; + metal::bool2 unnamed_139 = metal::int2(2) > metal::int2(1); + metal::bool3 unnamed_140 = metal::uint3(2u) > metal::uint3(1u); + metal::bool4 unnamed_141 = metal::float4(2.0) > metal::float4(1.0); + bool unnamed_142 = 2 >= 1; + bool unnamed_143 = 2u >= 1u; + bool unnamed_144 = 2.0 >= 1.0; + metal::bool2 unnamed_145 = metal::int2(2) >= metal::int2(1); + metal::bool3 unnamed_146 = metal::uint3(2u) >= metal::uint3(1u); + metal::bool4 unnamed_147 = metal::float4(2.0) >= metal::float4(1.0); } void assignment( diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 7d4b79d76..8801c2f24 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 461 +; Bound: 519 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %449 "main" -OpExecutionMode %449 LocalSize 1 1 1 +OpEntryPoint GLCompute %507 "main" +OpExecutionMode %507 LocalSize 1 1 1 OpMemberDecorate %30 0 Offset 0 OpMemberDecorate %30 1 Offset 16 OpDecorate %35 ArrayStride 32 @@ -272,247 +272,305 @@ OpBranch %170 %240 = OpCompositeConstruct %171 %7 %7 %241 = OpCompositeConstruct %171 %18 %18 %242 = OpIAdd %171 %241 %240 -%243 = OpCompositeConstruct %171 %18 %18 -%244 = OpCompositeConstruct %171 %7 %7 -%245 = OpISub %171 %243 %244 -%246 = OpCompositeConstruct %171 %7 %7 -%247 = OpCompositeConstruct %171 %18 %18 -%248 = OpISub %171 %247 %246 -%249 = OpCompositeConstruct %171 %18 %18 -%251 = OpCompositeConstruct %171 %7 %7 -%250 = OpIMul %171 %249 %251 -%252 = OpCompositeConstruct %171 %7 %7 -%254 = OpCompositeConstruct %171 %18 %18 -%253 = OpIMul %171 %252 %254 +%243 = OpCompositeConstruct %34 %24 %24 +%244 = OpCompositeConstruct %34 %25 %25 +%245 = OpIAdd %34 %243 %244 +%246 = OpCompositeConstruct %34 %25 %25 +%247 = OpCompositeConstruct %34 %24 %24 +%248 = OpIAdd %34 %247 %246 +%249 = OpCompositeConstruct %31 %14 %14 +%250 = OpCompositeConstruct %31 %3 %3 +%251 = OpFAdd %31 %249 %250 +%252 = OpCompositeConstruct %31 %3 %3 +%253 = OpCompositeConstruct %31 %14 %14 +%254 = OpFAdd %31 %253 %252 %255 = OpCompositeConstruct %171 %18 %18 %256 = OpCompositeConstruct %171 %7 %7 -%257 = OpSDiv %171 %255 %256 +%257 = OpISub %171 %255 %256 %258 = OpCompositeConstruct %171 %7 %7 %259 = OpCompositeConstruct %171 %18 %18 -%260 = OpSDiv %171 %259 %258 -%261 = OpCompositeConstruct %171 %18 %18 -%262 = OpCompositeConstruct %171 %7 %7 -%263 = OpSMod %171 %261 %262 -%264 = OpCompositeConstruct %171 %7 %7 -%265 = OpCompositeConstruct %171 %18 %18 -%266 = OpSMod %171 %265 %264 -%268 = OpCompositeExtract %29 %51 0 -%269 = OpCompositeExtract %29 %51 0 -%270 = OpFAdd %29 %268 %269 -%271 = OpCompositeExtract %29 %51 1 -%272 = OpCompositeExtract %29 %51 1 -%273 = OpFAdd %29 %271 %272 -%274 = OpCompositeExtract %29 %51 2 -%275 = OpCompositeExtract %29 %51 2 -%276 = OpFAdd %29 %274 %275 -%267 = OpCompositeConstruct %37 %270 %273 %276 -%278 = OpCompositeExtract %29 %51 0 -%279 = OpCompositeExtract %29 %51 0 -%280 = OpFSub %29 %278 %279 -%281 = OpCompositeExtract %29 %51 1 -%282 = OpCompositeExtract %29 %51 1 -%283 = OpFSub %29 %281 %282 -%284 = OpCompositeExtract %29 %51 2 -%285 = OpCompositeExtract %29 %51 2 -%286 = OpFSub %29 %284 %285 -%277 = OpCompositeConstruct %37 %280 %283 %286 -%287 = OpMatrixTimesScalar %37 %51 %3 -%288 = OpMatrixTimesScalar %37 %51 %14 -%289 = OpCompositeConstruct %26 %3 %3 %3 %3 -%290 = OpMatrixTimesVector %29 %52 %289 -%291 = OpCompositeConstruct %29 %14 %14 %14 -%292 = OpVectorTimesMatrix %26 %291 %52 -%293 = OpMatrixTimesMatrix %37 %52 %53 +%260 = OpISub %171 %259 %258 +%261 = OpCompositeConstruct %34 %24 %24 +%262 = OpCompositeConstruct %34 %25 %25 +%263 = OpISub %34 %261 %262 +%264 = OpCompositeConstruct %34 %25 %25 +%265 = OpCompositeConstruct %34 %24 %24 +%266 = OpISub %34 %265 %264 +%267 = OpCompositeConstruct %31 %14 %14 +%268 = OpCompositeConstruct %31 %3 %3 +%269 = OpFSub %31 %267 %268 +%270 = OpCompositeConstruct %31 %3 %3 +%271 = OpCompositeConstruct %31 %14 %14 +%272 = OpFSub %31 %271 %270 +%273 = OpCompositeConstruct %171 %18 %18 +%275 = OpCompositeConstruct %171 %7 %7 +%274 = OpIMul %171 %273 %275 +%276 = OpCompositeConstruct %171 %7 %7 +%278 = OpCompositeConstruct %171 %18 %18 +%277 = OpIMul %171 %276 %278 +%279 = OpCompositeConstruct %34 %24 %24 +%281 = OpCompositeConstruct %34 %25 %25 +%280 = OpIMul %34 %279 %281 +%282 = OpCompositeConstruct %34 %25 %25 +%284 = OpCompositeConstruct %34 %24 %24 +%283 = OpIMul %34 %282 %284 +%285 = OpCompositeConstruct %31 %14 %14 +%286 = OpVectorTimesScalar %31 %285 %3 +%287 = OpCompositeConstruct %31 %3 %3 +%288 = OpVectorTimesScalar %31 %287 %14 +%289 = OpCompositeConstruct %171 %18 %18 +%290 = OpCompositeConstruct %171 %7 %7 +%291 = OpSDiv %171 %289 %290 +%292 = OpCompositeConstruct %171 %7 %7 +%293 = OpCompositeConstruct %171 %18 %18 +%294 = OpSDiv %171 %293 %292 +%295 = OpCompositeConstruct %34 %24 %24 +%296 = OpCompositeConstruct %34 %25 %25 +%297 = OpUDiv %34 %295 %296 +%298 = OpCompositeConstruct %34 %25 %25 +%299 = OpCompositeConstruct %34 %24 %24 +%300 = OpUDiv %34 %299 %298 +%301 = OpCompositeConstruct %31 %14 %14 +%302 = OpCompositeConstruct %31 %3 %3 +%303 = OpFDiv %31 %301 %302 +%304 = OpCompositeConstruct %31 %3 %3 +%305 = OpCompositeConstruct %31 %14 %14 +%306 = OpFDiv %31 %305 %304 +%307 = OpCompositeConstruct %171 %18 %18 +%308 = OpCompositeConstruct %171 %7 %7 +%309 = OpSMod %171 %307 %308 +%310 = OpCompositeConstruct %171 %7 %7 +%311 = OpCompositeConstruct %171 %18 %18 +%312 = OpSMod %171 %311 %310 +%313 = OpCompositeConstruct %34 %24 %24 +%314 = OpCompositeConstruct %34 %25 %25 +%315 = OpUMod %34 %313 %314 +%316 = OpCompositeConstruct %34 %25 %25 +%317 = OpCompositeConstruct %34 %24 %24 +%318 = OpUMod %34 %317 %316 +%319 = OpCompositeConstruct %31 %14 %14 +%320 = OpCompositeConstruct %31 %3 %3 +%321 = OpFRem %31 %319 %320 +%322 = OpCompositeConstruct %31 %3 %3 +%323 = OpCompositeConstruct %31 %14 %14 +%324 = OpFRem %31 %323 %322 +%326 = OpCompositeExtract %29 %51 0 +%327 = OpCompositeExtract %29 %51 0 +%328 = OpFAdd %29 %326 %327 +%329 = OpCompositeExtract %29 %51 1 +%330 = OpCompositeExtract %29 %51 1 +%331 = OpFAdd %29 %329 %330 +%332 = OpCompositeExtract %29 %51 2 +%333 = OpCompositeExtract %29 %51 2 +%334 = OpFAdd %29 %332 %333 +%325 = OpCompositeConstruct %37 %328 %331 %334 +%336 = OpCompositeExtract %29 %51 0 +%337 = OpCompositeExtract %29 %51 0 +%338 = OpFSub %29 %336 %337 +%339 = OpCompositeExtract %29 %51 1 +%340 = OpCompositeExtract %29 %51 1 +%341 = OpFSub %29 %339 %340 +%342 = OpCompositeExtract %29 %51 2 +%343 = OpCompositeExtract %29 %51 2 +%344 = OpFSub %29 %342 %343 +%335 = OpCompositeConstruct %37 %338 %341 %344 +%345 = OpMatrixTimesScalar %37 %51 %3 +%346 = OpMatrixTimesScalar %37 %51 %14 +%347 = OpCompositeConstruct %26 %3 %3 %3 %3 +%348 = OpMatrixTimesVector %29 %52 %347 +%349 = OpCompositeConstruct %29 %14 %14 %14 +%350 = OpVectorTimesMatrix %26 %349 %52 +%351 = OpMatrixTimesMatrix %37 %52 %53 OpReturn OpFunctionEnd -%295 = OpFunction %2 None %152 -%294 = OpLabel -OpBranch %296 -%296 = OpLabel -%297 = OpNot %8 %7 -%298 = OpNot %20 %25 -%299 = OpCompositeConstruct %171 %7 %7 -%300 = OpNot %171 %299 -%301 = OpCompositeConstruct %182 %25 %25 %25 -%302 = OpNot %182 %301 -%303 = OpBitwiseOr %8 %18 %7 -%304 = OpBitwiseOr %20 %24 %25 -%305 = OpCompositeConstruct %171 %18 %18 -%306 = OpCompositeConstruct %171 %7 %7 -%307 = OpBitwiseOr %171 %305 %306 -%308 = OpCompositeConstruct %182 %24 %24 %24 -%309 = OpCompositeConstruct %182 %25 %25 %25 -%310 = OpBitwiseOr %182 %308 %309 -%311 = OpBitwiseAnd %8 %18 %7 -%312 = OpBitwiseAnd %20 %24 %25 -%313 = OpCompositeConstruct %171 %18 %18 -%314 = OpCompositeConstruct %171 %7 %7 -%315 = OpBitwiseAnd %171 %313 %314 -%316 = OpCompositeConstruct %182 %24 %24 %24 -%317 = OpCompositeConstruct %182 %25 %25 %25 -%318 = OpBitwiseAnd %182 %316 %317 -%319 = OpBitwiseXor %8 %18 %7 -%320 = OpBitwiseXor %20 %24 %25 -%321 = OpCompositeConstruct %171 %18 %18 -%322 = OpCompositeConstruct %171 %7 %7 -%323 = OpBitwiseXor %171 %321 %322 -%324 = OpCompositeConstruct %182 %24 %24 %24 -%325 = OpCompositeConstruct %182 %25 %25 %25 -%326 = OpBitwiseXor %182 %324 %325 -%327 = OpShiftLeftLogical %8 %18 %25 -%328 = OpShiftLeftLogical %20 %24 %25 -%329 = OpCompositeConstruct %171 %18 %18 -%330 = OpCompositeConstruct %34 %25 %25 -%331 = OpShiftLeftLogical %171 %329 %330 -%332 = OpCompositeConstruct %182 %24 %24 %24 -%333 = OpCompositeConstruct %182 %25 %25 %25 -%334 = OpShiftLeftLogical %182 %332 %333 -%335 = OpShiftRightArithmetic %8 %18 %25 -%336 = OpShiftRightLogical %20 %24 %25 -%337 = OpCompositeConstruct %171 %18 %18 -%338 = OpCompositeConstruct %34 %25 %25 -%339 = OpShiftRightArithmetic %171 %337 %338 -%340 = OpCompositeConstruct %182 %24 %24 %24 -%341 = OpCompositeConstruct %182 %25 %25 %25 -%342 = OpShiftRightLogical %182 %340 %341 +%353 = OpFunction %2 None %152 +%352 = OpLabel +OpBranch %354 +%354 = OpLabel +%355 = OpNot %8 %7 +%356 = OpNot %20 %25 +%357 = OpCompositeConstruct %171 %7 %7 +%358 = OpNot %171 %357 +%359 = OpCompositeConstruct %182 %25 %25 %25 +%360 = OpNot %182 %359 +%361 = OpBitwiseOr %8 %18 %7 +%362 = OpBitwiseOr %20 %24 %25 +%363 = OpCompositeConstruct %171 %18 %18 +%364 = OpCompositeConstruct %171 %7 %7 +%365 = OpBitwiseOr %171 %363 %364 +%366 = OpCompositeConstruct %182 %24 %24 %24 +%367 = OpCompositeConstruct %182 %25 %25 %25 +%368 = OpBitwiseOr %182 %366 %367 +%369 = OpBitwiseAnd %8 %18 %7 +%370 = OpBitwiseAnd %20 %24 %25 +%371 = OpCompositeConstruct %171 %18 %18 +%372 = OpCompositeConstruct %171 %7 %7 +%373 = OpBitwiseAnd %171 %371 %372 +%374 = OpCompositeConstruct %182 %24 %24 %24 +%375 = OpCompositeConstruct %182 %25 %25 %25 +%376 = OpBitwiseAnd %182 %374 %375 +%377 = OpBitwiseXor %8 %18 %7 +%378 = OpBitwiseXor %20 %24 %25 +%379 = OpCompositeConstruct %171 %18 %18 +%380 = OpCompositeConstruct %171 %7 %7 +%381 = OpBitwiseXor %171 %379 %380 +%382 = OpCompositeConstruct %182 %24 %24 %24 +%383 = OpCompositeConstruct %182 %25 %25 %25 +%384 = OpBitwiseXor %182 %382 %383 +%385 = OpShiftLeftLogical %8 %18 %25 +%386 = OpShiftLeftLogical %20 %24 %25 +%387 = OpCompositeConstruct %171 %18 %18 +%388 = OpCompositeConstruct %34 %25 %25 +%389 = OpShiftLeftLogical %171 %387 %388 +%390 = OpCompositeConstruct %182 %24 %24 %24 +%391 = OpCompositeConstruct %182 %25 %25 %25 +%392 = OpShiftLeftLogical %182 %390 %391 +%393 = OpShiftRightArithmetic %8 %18 %25 +%394 = OpShiftRightLogical %20 %24 %25 +%395 = OpCompositeConstruct %171 %18 %18 +%396 = OpCompositeConstruct %34 %25 %25 +%397 = OpShiftRightArithmetic %171 %395 %396 +%398 = OpCompositeConstruct %182 %24 %24 %24 +%399 = OpCompositeConstruct %182 %25 %25 %25 +%400 = OpShiftRightLogical %182 %398 %399 OpReturn OpFunctionEnd -%344 = OpFunction %2 None %152 -%343 = OpLabel -OpBranch %345 -%345 = OpLabel -%346 = OpIEqual %10 %18 %7 -%347 = OpIEqual %10 %24 %25 -%348 = OpFOrdEqual %10 %14 %3 -%349 = OpCompositeConstruct %171 %18 %18 -%350 = OpCompositeConstruct %171 %7 %7 -%351 = OpIEqual %155 %349 %350 -%352 = OpCompositeConstruct %182 %24 %24 %24 -%353 = OpCompositeConstruct %182 %25 %25 %25 -%354 = OpIEqual %100 %352 %353 -%355 = OpCompositeConstruct %26 %14 %14 %14 %14 -%356 = OpCompositeConstruct %26 %3 %3 %3 %3 -%357 = OpFOrdEqual %28 %355 %356 -%358 = OpINotEqual %10 %18 %7 -%359 = OpINotEqual %10 %24 %25 -%360 = OpFOrdNotEqual %10 %14 %3 -%361 = OpCompositeConstruct %171 %18 %18 -%362 = OpCompositeConstruct %171 %7 %7 -%363 = OpINotEqual %155 %361 %362 -%364 = OpCompositeConstruct %182 %24 %24 %24 -%365 = OpCompositeConstruct %182 %25 %25 %25 -%366 = OpINotEqual %100 %364 %365 -%367 = OpCompositeConstruct %26 %14 %14 %14 %14 -%368 = OpCompositeConstruct %26 %3 %3 %3 %3 -%369 = OpFOrdNotEqual %28 %367 %368 -%370 = OpSLessThan %10 %18 %7 -%371 = OpULessThan %10 %24 %25 -%372 = OpFOrdLessThan %10 %14 %3 -%373 = OpCompositeConstruct %171 %18 %18 -%374 = OpCompositeConstruct %171 %7 %7 -%375 = OpSLessThan %155 %373 %374 -%376 = OpCompositeConstruct %182 %24 %24 %24 -%377 = OpCompositeConstruct %182 %25 %25 %25 -%378 = OpULessThan %100 %376 %377 -%379 = OpCompositeConstruct %26 %14 %14 %14 %14 -%380 = OpCompositeConstruct %26 %3 %3 %3 %3 -%381 = OpFOrdLessThan %28 %379 %380 -%382 = OpSLessThanEqual %10 %18 %7 -%383 = OpULessThanEqual %10 %24 %25 -%384 = OpFOrdLessThanEqual %10 %14 %3 -%385 = OpCompositeConstruct %171 %18 %18 -%386 = OpCompositeConstruct %171 %7 %7 -%387 = OpSLessThanEqual %155 %385 %386 -%388 = OpCompositeConstruct %182 %24 %24 %24 -%389 = OpCompositeConstruct %182 %25 %25 %25 -%390 = OpULessThanEqual %100 %388 %389 -%391 = OpCompositeConstruct %26 %14 %14 %14 %14 -%392 = OpCompositeConstruct %26 %3 %3 %3 %3 -%393 = OpFOrdLessThanEqual %28 %391 %392 -%394 = OpSGreaterThan %10 %18 %7 -%395 = OpUGreaterThan %10 %24 %25 -%396 = OpFOrdGreaterThan %10 %14 %3 -%397 = OpCompositeConstruct %171 %18 %18 -%398 = OpCompositeConstruct %171 %7 %7 -%399 = OpSGreaterThan %155 %397 %398 -%400 = OpCompositeConstruct %182 %24 %24 %24 -%401 = OpCompositeConstruct %182 %25 %25 %25 -%402 = OpUGreaterThan %100 %400 %401 -%403 = OpCompositeConstruct %26 %14 %14 %14 %14 -%404 = OpCompositeConstruct %26 %3 %3 %3 %3 -%405 = OpFOrdGreaterThan %28 %403 %404 -%406 = OpSGreaterThanEqual %10 %18 %7 -%407 = OpUGreaterThanEqual %10 %24 %25 -%408 = OpFOrdGreaterThanEqual %10 %14 %3 -%409 = OpCompositeConstruct %171 %18 %18 -%410 = OpCompositeConstruct %171 %7 %7 -%411 = OpSGreaterThanEqual %155 %409 %410 -%412 = OpCompositeConstruct %182 %24 %24 %24 -%413 = OpCompositeConstruct %182 %25 %25 %25 -%414 = OpUGreaterThanEqual %100 %412 %413 -%415 = OpCompositeConstruct %26 %14 %14 %14 %14 -%416 = OpCompositeConstruct %26 %3 %3 %3 %3 -%417 = OpFOrdGreaterThanEqual %28 %415 %416 +%402 = OpFunction %2 None %152 +%401 = OpLabel +OpBranch %403 +%403 = OpLabel +%404 = OpIEqual %10 %18 %7 +%405 = OpIEqual %10 %24 %25 +%406 = OpFOrdEqual %10 %14 %3 +%407 = OpCompositeConstruct %171 %18 %18 +%408 = OpCompositeConstruct %171 %7 %7 +%409 = OpIEqual %155 %407 %408 +%410 = OpCompositeConstruct %182 %24 %24 %24 +%411 = OpCompositeConstruct %182 %25 %25 %25 +%412 = OpIEqual %100 %410 %411 +%413 = OpCompositeConstruct %26 %14 %14 %14 %14 +%414 = OpCompositeConstruct %26 %3 %3 %3 %3 +%415 = OpFOrdEqual %28 %413 %414 +%416 = OpINotEqual %10 %18 %7 +%417 = OpINotEqual %10 %24 %25 +%418 = OpFOrdNotEqual %10 %14 %3 +%419 = OpCompositeConstruct %171 %18 %18 +%420 = OpCompositeConstruct %171 %7 %7 +%421 = OpINotEqual %155 %419 %420 +%422 = OpCompositeConstruct %182 %24 %24 %24 +%423 = OpCompositeConstruct %182 %25 %25 %25 +%424 = OpINotEqual %100 %422 %423 +%425 = OpCompositeConstruct %26 %14 %14 %14 %14 +%426 = OpCompositeConstruct %26 %3 %3 %3 %3 +%427 = OpFOrdNotEqual %28 %425 %426 +%428 = OpSLessThan %10 %18 %7 +%429 = OpULessThan %10 %24 %25 +%430 = OpFOrdLessThan %10 %14 %3 +%431 = OpCompositeConstruct %171 %18 %18 +%432 = OpCompositeConstruct %171 %7 %7 +%433 = OpSLessThan %155 %431 %432 +%434 = OpCompositeConstruct %182 %24 %24 %24 +%435 = OpCompositeConstruct %182 %25 %25 %25 +%436 = OpULessThan %100 %434 %435 +%437 = OpCompositeConstruct %26 %14 %14 %14 %14 +%438 = OpCompositeConstruct %26 %3 %3 %3 %3 +%439 = OpFOrdLessThan %28 %437 %438 +%440 = OpSLessThanEqual %10 %18 %7 +%441 = OpULessThanEqual %10 %24 %25 +%442 = OpFOrdLessThanEqual %10 %14 %3 +%443 = OpCompositeConstruct %171 %18 %18 +%444 = OpCompositeConstruct %171 %7 %7 +%445 = OpSLessThanEqual %155 %443 %444 +%446 = OpCompositeConstruct %182 %24 %24 %24 +%447 = OpCompositeConstruct %182 %25 %25 %25 +%448 = OpULessThanEqual %100 %446 %447 +%449 = OpCompositeConstruct %26 %14 %14 %14 %14 +%450 = OpCompositeConstruct %26 %3 %3 %3 %3 +%451 = OpFOrdLessThanEqual %28 %449 %450 +%452 = OpSGreaterThan %10 %18 %7 +%453 = OpUGreaterThan %10 %24 %25 +%454 = OpFOrdGreaterThan %10 %14 %3 +%455 = OpCompositeConstruct %171 %18 %18 +%456 = OpCompositeConstruct %171 %7 %7 +%457 = OpSGreaterThan %155 %455 %456 +%458 = OpCompositeConstruct %182 %24 %24 %24 +%459 = OpCompositeConstruct %182 %25 %25 %25 +%460 = OpUGreaterThan %100 %458 %459 +%461 = OpCompositeConstruct %26 %14 %14 %14 %14 +%462 = OpCompositeConstruct %26 %3 %3 %3 %3 +%463 = OpFOrdGreaterThan %28 %461 %462 +%464 = OpSGreaterThanEqual %10 %18 %7 +%465 = OpUGreaterThanEqual %10 %24 %25 +%466 = OpFOrdGreaterThanEqual %10 %14 %3 +%467 = OpCompositeConstruct %171 %18 %18 +%468 = OpCompositeConstruct %171 %7 %7 +%469 = OpSGreaterThanEqual %155 %467 %468 +%470 = OpCompositeConstruct %182 %24 %24 %24 +%471 = OpCompositeConstruct %182 %25 %25 %25 +%472 = OpUGreaterThanEqual %100 %470 %471 +%473 = OpCompositeConstruct %26 %14 %14 %14 %14 +%474 = OpCompositeConstruct %26 %3 %3 %3 %3 +%475 = OpFOrdGreaterThanEqual %28 %473 %474 OpReturn OpFunctionEnd -%420 = OpFunction %2 None %152 -%419 = OpLabel -%418 = OpVariable %111 Function %7 -OpBranch %421 -%421 = OpLabel -%422 = OpLoad %8 %418 -%423 = OpIAdd %8 %422 %7 -OpStore %418 %423 -%424 = OpLoad %8 %418 -%425 = OpISub %8 %424 %7 -OpStore %418 %425 -%426 = OpLoad %8 %418 -%427 = OpLoad %8 %418 -%428 = OpIMul %8 %426 %427 -OpStore %418 %428 -%429 = OpLoad %8 %418 -%430 = OpLoad %8 %418 -%431 = OpSDiv %8 %429 %430 -OpStore %418 %431 -%432 = OpLoad %8 %418 -%433 = OpSMod %8 %432 %7 -OpStore %418 %433 -%434 = OpLoad %8 %418 -%435 = OpBitwiseAnd %8 %434 %11 -OpStore %418 %435 -%436 = OpLoad %8 %418 -%437 = OpBitwiseOr %8 %436 %11 -OpStore %418 %437 -%438 = OpLoad %8 %418 -%439 = OpBitwiseXor %8 %438 %11 -OpStore %418 %439 -%440 = OpLoad %8 %418 -%441 = OpShiftLeftLogical %8 %440 %24 -OpStore %418 %441 -%442 = OpLoad %8 %418 -%443 = OpShiftRightArithmetic %8 %442 %25 -OpStore %418 %443 -%444 = OpLoad %8 %418 -%445 = OpIAdd %8 %444 %7 -OpStore %418 %445 -%446 = OpLoad %8 %418 -%447 = OpISub %8 %446 %7 -OpStore %418 %447 +%478 = OpFunction %2 None %152 +%477 = OpLabel +%476 = OpVariable %111 Function %7 +OpBranch %479 +%479 = OpLabel +%480 = OpLoad %8 %476 +%481 = OpIAdd %8 %480 %7 +OpStore %476 %481 +%482 = OpLoad %8 %476 +%483 = OpISub %8 %482 %7 +OpStore %476 %483 +%484 = OpLoad %8 %476 +%485 = OpLoad %8 %476 +%486 = OpIMul %8 %484 %485 +OpStore %476 %486 +%487 = OpLoad %8 %476 +%488 = OpLoad %8 %476 +%489 = OpSDiv %8 %487 %488 +OpStore %476 %489 +%490 = OpLoad %8 %476 +%491 = OpSMod %8 %490 %7 +OpStore %476 %491 +%492 = OpLoad %8 %476 +%493 = OpBitwiseAnd %8 %492 %11 +OpStore %476 %493 +%494 = OpLoad %8 %476 +%495 = OpBitwiseOr %8 %494 %11 +OpStore %476 %495 +%496 = OpLoad %8 %476 +%497 = OpBitwiseXor %8 %496 %11 +OpStore %476 %497 +%498 = OpLoad %8 %476 +%499 = OpShiftLeftLogical %8 %498 %24 +OpStore %476 %499 +%500 = OpLoad %8 %476 +%501 = OpShiftRightArithmetic %8 %500 %25 +OpStore %476 %501 +%502 = OpLoad %8 %476 +%503 = OpIAdd %8 %502 %7 +OpStore %476 %503 +%504 = OpLoad %8 %476 +%505 = OpISub %8 %504 %7 +OpStore %476 %505 OpReturn OpFunctionEnd -%449 = OpFunction %2 None %152 -%448 = OpLabel -OpBranch %450 -%450 = OpLabel -%451 = OpFunctionCall %26 %55 -%452 = OpFunctionCall %26 %80 -%453 = OpVectorShuffle %29 %40 %40 0 1 2 -%454 = OpFunctionCall %29 %97 %453 -%455 = OpFunctionCall %4 %128 -%456 = OpFunctionCall %2 %151 -%457 = OpFunctionCall %2 %169 -%458 = OpFunctionCall %2 %295 -%459 = OpFunctionCall %2 %344 -%460 = OpFunctionCall %2 %420 +%507 = OpFunction %2 None %152 +%506 = OpLabel +OpBranch %508 +%508 = OpLabel +%509 = OpFunctionCall %26 %55 +%510 = OpFunctionCall %26 %80 +%511 = OpVectorShuffle %29 %40 %40 0 1 2 +%512 = OpFunctionCall %29 %97 %511 +%513 = OpFunctionCall %4 %128 +%514 = OpFunctionCall %2 %151 +%515 = OpFunctionCall %2 %169 +%516 = OpFunctionCall %2 %353 +%517 = OpFunctionCall %2 %402 +%518 = OpFunctionCall %2 %478 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index c504b2f84..262042296 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -100,87 +100,107 @@ fn arithmetic() { let unnamed_50 = (vec4(2.0) % vec4(1.0)); let unnamed_51 = (vec2(2) + vec2(1)); let unnamed_52 = (vec2(2) + vec2(1)); - let unnamed_53 = (vec2(2) - vec2(1)); - let unnamed_54 = (vec2(2) - vec2(1)); - let unnamed_55 = (vec2(2) * 1); - let unnamed_56 = (2 * vec2(1)); - let unnamed_57 = (vec2(2) / vec2(1)); - let unnamed_58 = (vec2(2) / vec2(1)); - let unnamed_59 = (vec2(2) % vec2(1)); - let unnamed_60 = (vec2(2) % vec2(1)); - let unnamed_61 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_62 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_63 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - let unnamed_64 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_65 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - let unnamed_66 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_67 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + let unnamed_53 = (vec2(2u) + vec2(1u)); + let unnamed_54 = (vec2(2u) + vec2(1u)); + let unnamed_55 = (vec2(2.0) + vec2(1.0)); + let unnamed_56 = (vec2(2.0) + vec2(1.0)); + let unnamed_57 = (vec2(2) - vec2(1)); + let unnamed_58 = (vec2(2) - vec2(1)); + let unnamed_59 = (vec2(2u) - vec2(1u)); + let unnamed_60 = (vec2(2u) - vec2(1u)); + let unnamed_61 = (vec2(2.0) - vec2(1.0)); + let unnamed_62 = (vec2(2.0) - vec2(1.0)); + let unnamed_63 = (vec2(2) * 1); + let unnamed_64 = (2 * vec2(1)); + let unnamed_65 = (vec2(2u) * 1u); + let unnamed_66 = (2u * vec2(1u)); + let unnamed_67 = (vec2(2.0) * 1.0); + let unnamed_68 = (2.0 * vec2(1.0)); + let unnamed_69 = (vec2(2) / vec2(1)); + let unnamed_70 = (vec2(2) / vec2(1)); + let unnamed_71 = (vec2(2u) / vec2(1u)); + let unnamed_72 = (vec2(2u) / vec2(1u)); + let unnamed_73 = (vec2(2.0) / vec2(1.0)); + let unnamed_74 = (vec2(2.0) / vec2(1.0)); + let unnamed_75 = (vec2(2) % vec2(1)); + let unnamed_76 = (vec2(2) % vec2(1)); + let unnamed_77 = (vec2(2u) % vec2(1u)); + let unnamed_78 = (vec2(2u) % vec2(1u)); + let unnamed_79 = (vec2(2.0) % vec2(1.0)); + let unnamed_80 = (vec2(2.0) % vec2(1.0)); + let unnamed_81 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_82 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_83 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + let unnamed_84 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_85 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + let unnamed_86 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_87 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } fn bit() { - let unnamed_68 = ~(1); - let unnamed_69 = ~(1u); - let unnamed_70 = !(vec2(1)); - let unnamed_71 = !(vec3(1u)); - let unnamed_72 = (2 | 1); - let unnamed_73 = (2u | 1u); - let unnamed_74 = (vec2(2) | vec2(1)); - let unnamed_75 = (vec3(2u) | vec3(1u)); - let unnamed_76 = (2 & 1); - let unnamed_77 = (2u & 1u); - let unnamed_78 = (vec2(2) & vec2(1)); - let unnamed_79 = (vec3(2u) & vec3(1u)); - let unnamed_80 = (2 ^ 1); - let unnamed_81 = (2u ^ 1u); - let unnamed_82 = (vec2(2) ^ vec2(1)); - let unnamed_83 = (vec3(2u) ^ vec3(1u)); - let unnamed_84 = (2 << 1u); - let unnamed_85 = (2u << 1u); - let unnamed_86 = (vec2(2) << vec2(1u)); - let unnamed_87 = (vec3(2u) << vec3(1u)); - let unnamed_88 = (2 >> 1u); - let unnamed_89 = (2u >> 1u); - let unnamed_90 = (vec2(2) >> vec2(1u)); - let unnamed_91 = (vec3(2u) >> vec3(1u)); + let unnamed_88 = ~(1); + let unnamed_89 = ~(1u); + let unnamed_90 = !(vec2(1)); + let unnamed_91 = !(vec3(1u)); + let unnamed_92 = (2 | 1); + let unnamed_93 = (2u | 1u); + let unnamed_94 = (vec2(2) | vec2(1)); + let unnamed_95 = (vec3(2u) | vec3(1u)); + let unnamed_96 = (2 & 1); + let unnamed_97 = (2u & 1u); + let unnamed_98 = (vec2(2) & vec2(1)); + let unnamed_99 = (vec3(2u) & vec3(1u)); + let unnamed_100 = (2 ^ 1); + let unnamed_101 = (2u ^ 1u); + let unnamed_102 = (vec2(2) ^ vec2(1)); + let unnamed_103 = (vec3(2u) ^ vec3(1u)); + let unnamed_104 = (2 << 1u); + let unnamed_105 = (2u << 1u); + let unnamed_106 = (vec2(2) << vec2(1u)); + let unnamed_107 = (vec3(2u) << vec3(1u)); + let unnamed_108 = (2 >> 1u); + let unnamed_109 = (2u >> 1u); + let unnamed_110 = (vec2(2) >> vec2(1u)); + let unnamed_111 = (vec3(2u) >> vec3(1u)); } fn comparison() { - let unnamed_92 = (2 == 1); - let unnamed_93 = (2u == 1u); - let unnamed_94 = (2.0 == 1.0); - let unnamed_95 = (vec2(2) == vec2(1)); - let unnamed_96 = (vec3(2u) == vec3(1u)); - let unnamed_97 = (vec4(2.0) == vec4(1.0)); - let unnamed_98 = (2 != 1); - let unnamed_99 = (2u != 1u); - let unnamed_100 = (2.0 != 1.0); - let unnamed_101 = (vec2(2) != vec2(1)); - let unnamed_102 = (vec3(2u) != vec3(1u)); - let unnamed_103 = (vec4(2.0) != vec4(1.0)); - let unnamed_104 = (2 < 1); - let unnamed_105 = (2u < 1u); - let unnamed_106 = (2.0 < 1.0); - let unnamed_107 = (vec2(2) < vec2(1)); - let unnamed_108 = (vec3(2u) < vec3(1u)); - let unnamed_109 = (vec4(2.0) < vec4(1.0)); - let unnamed_110 = (2 <= 1); - let unnamed_111 = (2u <= 1u); - let unnamed_112 = (2.0 <= 1.0); - let unnamed_113 = (vec2(2) <= vec2(1)); - let unnamed_114 = (vec3(2u) <= vec3(1u)); - let unnamed_115 = (vec4(2.0) <= vec4(1.0)); - let unnamed_116 = (2 > 1); - let unnamed_117 = (2u > 1u); - let unnamed_118 = (2.0 > 1.0); - let unnamed_119 = (vec2(2) > vec2(1)); - let unnamed_120 = (vec3(2u) > vec3(1u)); - let unnamed_121 = (vec4(2.0) > vec4(1.0)); - let unnamed_122 = (2 >= 1); - let unnamed_123 = (2u >= 1u); - let unnamed_124 = (2.0 >= 1.0); - let unnamed_125 = (vec2(2) >= vec2(1)); - let unnamed_126 = (vec3(2u) >= vec3(1u)); - let unnamed_127 = (vec4(2.0) >= vec4(1.0)); + let unnamed_112 = (2 == 1); + let unnamed_113 = (2u == 1u); + let unnamed_114 = (2.0 == 1.0); + let unnamed_115 = (vec2(2) == vec2(1)); + let unnamed_116 = (vec3(2u) == vec3(1u)); + let unnamed_117 = (vec4(2.0) == vec4(1.0)); + let unnamed_118 = (2 != 1); + let unnamed_119 = (2u != 1u); + let unnamed_120 = (2.0 != 1.0); + let unnamed_121 = (vec2(2) != vec2(1)); + let unnamed_122 = (vec3(2u) != vec3(1u)); + let unnamed_123 = (vec4(2.0) != vec4(1.0)); + let unnamed_124 = (2 < 1); + let unnamed_125 = (2u < 1u); + let unnamed_126 = (2.0 < 1.0); + let unnamed_127 = (vec2(2) < vec2(1)); + let unnamed_128 = (vec3(2u) < vec3(1u)); + let unnamed_129 = (vec4(2.0) < vec4(1.0)); + let unnamed_130 = (2 <= 1); + let unnamed_131 = (2u <= 1u); + let unnamed_132 = (2.0 <= 1.0); + let unnamed_133 = (vec2(2) <= vec2(1)); + let unnamed_134 = (vec3(2u) <= vec3(1u)); + let unnamed_135 = (vec4(2.0) <= vec4(1.0)); + let unnamed_136 = (2 > 1); + let unnamed_137 = (2u > 1u); + let unnamed_138 = (2.0 > 1.0); + let unnamed_139 = (vec2(2) > vec2(1)); + let unnamed_140 = (vec3(2u) > vec3(1u)); + let unnamed_141 = (vec4(2.0) > vec4(1.0)); + let unnamed_142 = (2 >= 1); + let unnamed_143 = (2u >= 1u); + let unnamed_144 = (2.0 >= 1.0); + let unnamed_145 = (vec2(2) >= vec2(1)); + let unnamed_146 = (vec3(2u) >= vec3(1u)); + let unnamed_147 = (vec4(2.0) >= vec4(1.0)); } fn assignment() { From 7f4e07e5cd4dbc534e91cba894b90495c01d1de4 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 13 Apr 2022 15:05:22 +0200 Subject: [PATCH 1684/2212] [glsl-out] add support for boolean vector `~`, `|` and `&` ops --- src/back/glsl/mod.rs | 94 ++++++++++++++-------- tests/out/glsl/operators.main.Compute.glsl | 6 +- 2 files changed, 63 insertions(+), 37 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 95d804689..a0cb077fb 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -356,6 +356,8 @@ pub enum Error { enum BinaryOperation { /// Vector comparison should use the function like `greaterThan()`, etc. VectorCompare, + /// Vector component wise operation; used to polyfill unsupported ops like `|` and `&` for `bvecN`'s + VectorComponentWise, /// GLSL `%` is SPIR-V `OpUMod/OpSMod` and `mod()` is `OpFMod`, but [`BinaryOperator::Modulo`](crate::BinaryOperator::Modulo) is `OpFRem`. Modulo, /// Any plain operation. No additional logic required. @@ -2452,26 +2454,30 @@ impl<'a, W: Write> Writer<'a, W> { Expression::Unary { op, expr } => { use crate::{ScalarKind as Sk, UnaryOperator as Uo}; - write!( - self.out, - "({} ", - match op { - Uo::Negate => "-", - Uo::Not => match ctx.info[expr] - .ty - .inner_with(&self.module.types) - .scalar_kind() - { - Some(Sk::Sint) | Some(Sk::Uint) => "~", - Some(Sk::Bool) => "!", - ref other => - return Err(Error::Custom(format!( - "Cannot apply not to type {:?}", - other - ))), - }, + let ty = ctx.info[expr].ty.inner_with(&self.module.types); + + match *ty { + TypeInner::Vector { kind: Sk::Bool, .. } => { + write!(self.out, "not(")?; } - )?; + _ => { + let operator = match op { + Uo::Negate => "-", + Uo::Not => match ty.scalar_kind() { + Some(Sk::Sint) | Some(Sk::Uint) => "~", + Some(Sk::Bool) => "!", + ref other => { + return Err(Error::Custom(format!( + "Cannot apply not to type {:?}", + other + ))) + } + }, + }; + + write!(self.out, "({} ", operator)?; + } + } self.write_expr(expr, ctx)?; @@ -2494,27 +2500,22 @@ impl<'a, W: Write> Writer<'a, W> { let right_inner = ctx.info[right].ty.inner_with(&self.module.types); let function = match (left_inner, right_inner) { - ( - &Ti::Vector { - kind: left_kind, .. - }, - &Ti::Vector { - kind: right_kind, .. - }, - ) => match op { + (&Ti::Vector { kind, .. }, &Ti::Vector { .. }) => match op { Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual | Bo::Equal | Bo::NotEqual => BinaryOperation::VectorCompare, - Bo::Modulo => match (left_kind, right_kind) { - (Sk::Float, _) | (_, Sk::Float) => match op { - Bo::Modulo => BinaryOperation::Modulo, - _ => BinaryOperation::Other, - }, - _ => BinaryOperation::Other, - }, + Bo::Modulo if kind == Sk::Float => BinaryOperation::Modulo, + Bo::And if kind == Sk::Bool => { + op = crate::BinaryOperator::LogicalAnd; + BinaryOperation::VectorComponentWise + } + Bo::InclusiveOr if kind == Sk::Bool => { + op = crate::BinaryOperator::LogicalOr; + BinaryOperation::VectorComponentWise + } _ => BinaryOperation::Other, }, _ => match (left_inner.scalar_kind(), right_inner.scalar_kind()) { @@ -2554,6 +2555,31 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(right, ctx)?; write!(self.out, ")")?; } + BinaryOperation::VectorComponentWise => { + self.write_value_type(left_inner)?; + write!(self.out, "(")?; + + let size = match *left_inner { + Ti::Vector { size, .. } => size, + _ => unreachable!(), + }; + + for i in 0..size as usize { + if i != 0 { + write!(self.out, ", ")?; + } + + self.write_expr(left, ctx)?; + write!(self.out, ".{}", back::COMPONENTS[i])?; + + write!(self.out, " {} ", back::binary_operation_str(op))?; + + self.write_expr(right, ctx)?; + write!(self.out, ".{}", back::COMPONENTS[i])?; + } + + write!(self.out, ")")?; + } BinaryOperation::Modulo => { write!(self.out, "(")?; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 464dc9776..0000a2828 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -58,13 +58,13 @@ float constructors() { void logical() { bool unnamed_11 = (! true); - bvec2 unnamed_12 = (! bvec2(true)); + bvec2 unnamed_12 = not(bvec2(true)); bool unnamed_13 = (true || false); bool unnamed_14 = (true && false); bool unnamed_15 = (true || false); - bvec3 unnamed_16 = (bvec3(true) | bvec3(false)); + bvec3 unnamed_16 = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); bool unnamed_17 = (true && false); - bvec4 unnamed_18 = (bvec4(true) & bvec4(false)); + bvec4 unnamed_18 = bvec4(bvec4(true).x && bvec4(false).x, bvec4(true).y && bvec4(false).y, bvec4(true).z && bvec4(false).z, bvec4(true).w && bvec4(false).w); } void arithmetic() { From 8584507fb6cd9a0d52b474b32f79a66114bd0aba Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 14 Apr 2022 11:28:06 +0200 Subject: [PATCH 1685/2212] [glsl-out] remove redundant space from unary ops --- src/back/glsl/mod.rs | 2 +- tests/out/glsl/operators.main.Compute.glsl | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a0cb077fb..a7ef4462f 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2475,7 +2475,7 @@ impl<'a, W: Write> Writer<'a, W> { }, }; - write!(self.out, "({} ", operator)?; + write!(self.out, "({}", operator)?; } } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 0000a2828..bf7a7d847 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -57,7 +57,7 @@ float constructors() { } void logical() { - bool unnamed_11 = (! true); + bool unnamed_11 = (!true); bvec2 unnamed_12 = not(bvec2(true)); bool unnamed_13 = (true || false); bool unnamed_14 = (true && false); @@ -68,8 +68,8 @@ void logical() { } void arithmetic() { - ivec2 unnamed_19 = (- ivec2(1)); - vec2 unnamed_20 = (- vec2(1.0)); + ivec2 unnamed_19 = (-ivec2(1)); + vec2 unnamed_20 = (-vec2(1.0)); int unnamed_21 = (2 + 1); uint unnamed_22 = (2u + 1u); float unnamed_23 = (2.0 + 1.0); @@ -140,10 +140,10 @@ void arithmetic() { } void bit() { - int unnamed_88 = (~ 1); - uint unnamed_89 = (~ 1u); - ivec2 unnamed_90 = (~ ivec2(1)); - uvec3 unnamed_91 = (~ uvec3(1u)); + int unnamed_88 = (~1); + uint unnamed_89 = (~1u); + ivec2 unnamed_90 = (~ivec2(1)); + uvec3 unnamed_91 = (~uvec3(1u)); int unnamed_92 = (2 | 1); uint unnamed_93 = (2u | 1u); ivec2 unnamed_94 = (ivec2(2) | ivec2(1)); From c93a5ede71c6cbbc85706af94061862b39202b24 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Fri, 15 Apr 2022 13:21:34 +0200 Subject: [PATCH 1686/2212] update `hlsl-out` status in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 46c79a296..f6a6581c6 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Back-end | Status | Feature | Notes | SPIR-V | :white_check_mark: | spv-out | | WGSL | :ok: | wgsl-out | | Metal | :white_check_mark: | msl-out | | -HLSL | :ok: | hlsl-out | Shader Model 5.0+ (DirectX 11+) | +HLSL | :white_check_mark: | hlsl-out | Shader Model 5.0+ (DirectX 11+) | GLSL | :ok: | glsl-out | GLSL 330+ and GLSL ES 300+ | AIR | | | | DXIL/DXIR | | | | From fbb77aa0dcbbc72b47c3a1e213c658b93bccbcf6 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 15 Apr 2022 12:54:15 +0300 Subject: [PATCH 1687/2212] [wgsl-in] Update entry point stage attributes --- src/front/wgsl/conv.rs | 9 --------- src/front/wgsl/mod.rs | 13 ++++++++----- src/front/wgsl/tests.rs | 2 +- tests/in/access.wgsl | 6 +++--- tests/in/bits.wgsl | 2 +- tests/in/boids.wgsl | 2 +- tests/in/collatz.wgsl | 2 +- tests/in/control-flow.wgsl | 2 +- tests/in/cubeArrayShadow.wgsl | 2 +- tests/in/empty.wgsl | 2 +- tests/in/extra.wgsl | 2 +- tests/in/functions-webgl.wgsl | 2 +- tests/in/functions.wgsl | 2 +- tests/in/globals.wgsl | 2 +- tests/in/image.wgsl | 16 ++++++++-------- tests/in/interface.wgsl | 8 ++++---- tests/in/interpolate.wgsl | 4 ++-- tests/in/math-functions.wgsl | 2 +- tests/in/operators.wgsl | 2 +- tests/in/padding.wgsl | 4 ++-- tests/in/push-constants.wgsl | 2 +- tests/in/quad.wgsl | 6 +++--- tests/in/shadow.wgsl | 8 ++++---- tests/in/skybox.wgsl | 4 ++-- tests/in/standard.wgsl | 2 +- tests/in/texture-arg.wgsl | 2 +- tests/spirv-capabilities.rs | 6 +++--- tests/wgsl-errors.rs | 28 ++++++---------------------- 28 files changed, 61 insertions(+), 83 deletions(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 6d4dd954a..c1bbb8971 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -38,15 +38,6 @@ pub fn map_built_in(word: &str, span: Span) -> Result> }) } -pub fn map_shader_stage(word: &str, span: Span) -> Result> { - match word { - "vertex" => Ok(crate::ShaderStage::Vertex), - "fragment" => Ok(crate::ShaderStage::Fragment), - "compute" => Ok(crate::ShaderStage::Compute), - _ => Err(Error::UnknownShaderStage(span)), - } -} - pub fn map_interpolation(word: &str, span: Span) -> Result> { match word { "linear" => Ok(crate::Interpolation::Linear), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 854c3f51c..b78f9bd60 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -4210,11 +4210,14 @@ impl Parser { bind_group = Some(parse_non_negative_sint_literal(lexer, 4)?); lexer.expect(Token::Paren(')'))?; } - ("stage", _) => { - lexer.expect(Token::Paren('('))?; - let (ident, ident_span) = lexer.next_ident_with_span()?; - stage = Some(conv::map_shader_stage(ident, ident_span)?); - lexer.expect(Token::Paren(')'))?; + ("vertex", _) => { + stage = Some(crate::ShaderStage::Vertex); + } + ("fragment", _) => { + stage = Some(crate::ShaderStage::Fragment); + } + ("compute", _) => { + stage = Some(crate::ShaderStage::Compute); } ("workgroup_size", _) => { lexer.expect(Token::Paren('('))?; diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index ffbe89936..1f7e451f9 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -463,7 +463,7 @@ fn parse_struct_instantiation() { b: vec3, } - @stage(fragment) + @fragment fn fs_main() { var foo: Foo = Foo(0.0, vec3(0.0, 1.0, 42.0)); } diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index e64ef2152..64e91c944 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -58,7 +58,7 @@ fn test_arr_as_arg(a: array, 5>) -> f32 { return a[4][9]; } -@stage(vertex) +@vertex fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32 = 0.0; // We should check that backed doesn't skip this expression @@ -88,7 +88,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { return vec4(matrix * vec4(vec4(value)), 2.0); } -@stage(fragment) +@fragment fn foo_frag() -> @location(0) vec4 { // test storage stores bar.matrix[1].z = 1.0; @@ -99,7 +99,7 @@ fn foo_frag() -> @location(0) vec4 { return vec4(0.0); } -@stage(compute) @workgroup_size(1) +@compute @workgroup_size(1) fn atomics() { var tmp: i32; let value = atomicLoad(&bar.atom); diff --git a/tests/in/bits.wgsl b/tests/in/bits.wgsl index 9de7de547..24101d993 100644 --- a/tests/in/bits.wgsl +++ b/tests/in/bits.wgsl @@ -1,4 +1,4 @@ -@stage(compute) @workgroup_size(1) +@compute @workgroup_size(1) fn main() { var i = 0; var i2 = vec2(0); diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 7194d4878..31bbc85bb 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -24,7 +24,7 @@ struct Particles { @group(0) @binding(2) var particlesDst : Particles; // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp -@stage(compute) @workgroup_size(64) +@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) global_invocation_id : vec3) { let index : u32 = global_invocation_id.x; if index >= NUM_PARTICLES { diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl index b2d990732..ebfc41b6f 100644 --- a/tests/in/collatz.wgsl +++ b/tests/in/collatz.wgsl @@ -26,7 +26,7 @@ fn collatz_iterations(n_base: u32) -> u32 { return i; } -@stage(compute) @workgroup_size(1) +@compute @workgroup_size(1) fn main(@builtin(global_invocation_id) global_id: vec3) { v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); } diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index db87b320f..f059eeeb8 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -1,4 +1,4 @@ -@stage(compute) @workgroup_size(1) +@compute @workgroup_size(1) fn main(@builtin(global_invocation_id) global_id: vec3) { //TODO: execution-only barrier? storageBarrier(); diff --git a/tests/in/cubeArrayShadow.wgsl b/tests/in/cubeArrayShadow.wgsl index aad2d5ae8..78b884558 100644 --- a/tests/in/cubeArrayShadow.wgsl +++ b/tests/in/cubeArrayShadow.wgsl @@ -3,7 +3,7 @@ var point_shadow_textures: texture_depth_cube_array; @group(0) @binding(5) var point_shadow_textures_sampler: sampler_comparison; -@stage(fragment) +@fragment fn fragment() -> @location(0) vec4 { let frag_ls = vec4(1., 1., 2., 1.).xyz; let a = textureSampleCompare(point_shadow_textures, point_shadow_textures_sampler, frag_ls, i32(1), 1.); diff --git a/tests/in/empty.wgsl b/tests/in/empty.wgsl index 862844479..b4af5cb41 100644 --- a/tests/in/empty.wgsl +++ b/tests/in/empty.wgsl @@ -1,2 +1,2 @@ -@stage(compute) @workgroup_size(1) +@compute @workgroup_size(1) fn main() {} diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index a0130da17..ef68f4aa8 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -9,7 +9,7 @@ struct FragmentIn { @builtin(primitive_index) primitive_index: u32, } -@stage(fragment) +@fragment fn main(in: FragmentIn) -> @location(0) vec4 { if in.primitive_index == pc.index { return in.color; diff --git a/tests/in/functions-webgl.wgsl b/tests/in/functions-webgl.wgsl index 2e058ec72..9192f6868 100644 --- a/tests/in/functions-webgl.wgsl +++ b/tests/in/functions-webgl.wgsl @@ -7,7 +7,7 @@ fn test_fma() -> vec2 { } -@stage(vertex) +@vertex fn main() { let a = test_fma(); } diff --git a/tests/in/functions.wgsl b/tests/in/functions.wgsl index 6a15da1e3..23e4b0400 100644 --- a/tests/in/functions.wgsl +++ b/tests/in/functions.wgsl @@ -22,7 +22,7 @@ fn test_integer_dot_product() -> i32 { return c_4; } -@stage(compute) @workgroup_size(1) +@compute @workgroup_size(1) fn main() { let a = test_fma(); let b = test_integer_dot_product(); diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index a4467eae7..6e571e271 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -52,7 +52,7 @@ fn test_msl_packed_vec3() { let _ = 2.0 * data.v3; } -@stage(compute) @workgroup_size(1) +@compute @workgroup_size(1) fn main() { test_msl_packed_vec3(); diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 5fd0eec13..cc7746ea4 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -15,7 +15,7 @@ var image_1d_src: texture_1d; @group(0) @binding(2) var image_dst: texture_storage_1d; -@stage(compute) @workgroup_size(16) +@compute @workgroup_size(16) fn main( @builtin(local_invocation_id) local_id: vec3, //TODO: https://github.com/gpuweb/gpuweb/issues/1590 @@ -31,7 +31,7 @@ fn main( textureStore(image_dst, itc.x, value1 + value2 + value4 + value5 + value6); } -@stage(compute) @workgroup_size(16, 1, 1) +@compute @workgroup_size(16, 1, 1) fn depth_load(@builtin(local_invocation_id) local_id: vec3) { let dim: vec2 = textureDimensions(image_storage_src); let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); @@ -55,7 +55,7 @@ var image_3d: texture_3d; @group(0) @binding(6) var image_aa: texture_multisampled_2d; -@stage(vertex) +@vertex fn queries() -> @builtin(position) vec4 { let dim_1d = textureDimensions(image_1d); let dim_1d_lod = textureDimensions(image_1d, i32(dim_1d)); @@ -77,7 +77,7 @@ fn queries() -> @builtin(position) vec4 { return vec4(f32(sum)); } -@stage(vertex) +@vertex fn levels_queries() -> @builtin(position) vec4 { let num_levels_2d = textureNumLevels(image_2d); let num_levels_2d_array = textureNumLevels(image_2d_array); @@ -96,7 +96,7 @@ fn levels_queries() -> @builtin(position) vec4 { @group(1) @binding(0) var sampler_reg: sampler; -@stage(fragment) +@fragment fn sample() -> @location(0) vec4 { let tc = vec2(0.5); let level = 2.3; @@ -116,7 +116,7 @@ var image_2d_depth: texture_depth_2d; @group(1) @binding(3) var image_cube_depth: texture_depth_cube; -@stage(fragment) +@fragment fn sample_comparison() -> @location(0) f32 { let tc = vec2(0.5); let dref = 0.5; @@ -126,7 +126,7 @@ fn sample_comparison() -> @location(0) f32 { return s2d_depth + s2d_depth_level; } -@stage(fragment) +@fragment fn gather() -> @location(0) vec4 { let tc = vec2(0.5); let dref = 0.5; @@ -137,7 +137,7 @@ fn gather() -> @location(0) vec4 { return s2d + s2d_offset + s2d_depth + s2d_depth_offset; } -@stage(fragment) +@fragment fn depth_no_comparison() -> @location(0) vec4 { let tc = vec2(0.5); let s2d = textureSample(image_2d_depth, sampler_reg, tc); diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index 812afc51a..9bf713199 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -5,7 +5,7 @@ struct VertexOutput { @location(1) varying: f32, } -@stage(vertex) +@vertex fn vertex( @builtin(vertex_index) vertex_index: u32, @builtin(instance_index) instance_index: u32, @@ -21,7 +21,7 @@ struct FragmentOutput { @location(0) color: f32, } -@stage(fragment) +@fragment fn fragment( in: VertexOutput, @builtin(front_facing) front_facing: bool, @@ -35,7 +35,7 @@ fn fragment( var output: array; -@stage(compute) @workgroup_size(1) +@compute @workgroup_size(1) fn compute( @builtin(global_invocation_id) global_id: vec3, @builtin(local_invocation_id) local_id: vec3, @@ -54,7 +54,7 @@ struct Input2 { @builtin(instance_index) index: u32, } -@stage(vertex) +@vertex fn vertex_two_structs(in1: Input1, in2: Input2) -> @builtin(position) @invariant vec4 { var index = 2u; return vec4(f32(in1.index), f32(in2.index), f32(index), 0.0); diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index 86753a83e..071891ee7 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -11,7 +11,7 @@ struct FragmentInput { @location(6) @interpolate(perspective, sample) perspective_sample : f32, } -@stage(vertex) +@vertex fn vert_main() -> FragmentInput { var out: FragmentInput; @@ -27,5 +27,5 @@ fn vert_main() -> FragmentInput { return out; } -@stage(fragment) +@fragment fn frag_main(val : FragmentInput) { } diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index 5d3a1f592..a298a5e2b 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -1,4 +1,4 @@ -@stage(vertex) +@vertex fn main() { let f = 1.0; let v = vec4(0.0); diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 54949f419..f62329499 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -279,7 +279,7 @@ fn assignment() { a--; } -@stage(compute) @workgroup_size(1) +@compute @workgroup_size(1) fn main() { let _ = builtins(); let _ = splat(); diff --git a/tests/in/padding.wgsl b/tests/in/padding.wgsl index 0ff60f393..13331edf8 100644 --- a/tests/in/padding.wgsl +++ b/tests/in/padding.wgsl @@ -27,7 +27,7 @@ var input2: Test2; var input3: Test3; -@stage(vertex) +@vertex fn vertex() -> @builtin(position) vec4 { return vec4(1.0) * input.b * input2.b * input3.b; -} \ No newline at end of file +} diff --git a/tests/in/push-constants.wgsl b/tests/in/push-constants.wgsl index e0bf46758..cc8c4ab02 100644 --- a/tests/in/push-constants.wgsl +++ b/tests/in/push-constants.wgsl @@ -7,7 +7,7 @@ struct FragmentIn { @location(0) color: vec4 } -@stage(fragment) +@fragment fn main(in: FragmentIn) -> @location(0) vec4 { return in.color * pc.multiplier; } diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index 590ba0e4c..f2c85f095 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -6,7 +6,7 @@ struct VertexOutput { @builtin(position) position : vec4, } -@stage(vertex) +@vertex fn vert_main( @location(0) pos : vec2, @location(1) uv : vec2, @@ -18,7 +18,7 @@ fn vert_main( @group(0) @binding(0) var u_texture : texture_2d; @group(0) @binding(1) var u_sampler : sampler; -@stage(fragment) +@fragment fn frag_main(@location(0) uv : vec2) -> @location(0) vec4 { let color = textureSample(u_texture, u_sampler, uv); if color.a == 0.0 { @@ -32,7 +32,7 @@ fn frag_main(@location(0) uv : vec2) -> @location(0) vec4 { // We need to make sure that backends are successfully handling multiple entry points for the same shader stage. -@stage(fragment) +@fragment fn fs_extra() -> @location(0) vec4 { return vec4(0.0, 0.5, 0.0, 0.5); } diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index bce4720cf..575018863 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -17,7 +17,7 @@ struct Entity { var u_entity: Entity; /* Not useful for testing -@stage(vertex) +@vertex fn vs_bake(@location(0) position: vec4) -> @builtin(position) vec4 { return u_globals.view_proj * u_entity.world * vec4(position); } @@ -29,7 +29,7 @@ struct VertexOutput { @location(1) world_position: vec4, } -@stage(vertex) +@vertex fn vs_main( @location(0) position: vec4, @location(1) normal: vec4, @@ -80,7 +80,7 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); let c_max_lights: u32 = 10u; -@stage(fragment) +@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4 { let normal = normalize(in.world_normal); // accumulate color @@ -100,7 +100,7 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { } // The fragment entrypoint used when storage buffers are not available for the lights -@stage(fragment) +@fragment fn fs_main_without_storage(in: VertexOutput) -> @location(0) vec4 { let normal = normalize(in.world_normal); var color: vec3 = c_ambient; diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index 0b589c7f5..f4cc37a44 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -10,7 +10,7 @@ struct Data { @group(0) @binding(0) var r_data: Data; -@stage(vertex) +@vertex fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput { // hacky way to draw a large triangle var tmp1 = i32(vertex_index) / 2; @@ -32,7 +32,7 @@ var r_texture: texture_cube; @group(0) @binding(2) var r_sampler: sampler; -@stage(fragment) +@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4 { return textureSample(r_texture, r_sampler, in.uv); } diff --git a/tests/in/standard.wgsl b/tests/in/standard.wgsl index 9171db190..5b40b683a 100644 --- a/tests/in/standard.wgsl +++ b/tests/in/standard.wgsl @@ -1,6 +1,6 @@ // Standard functions. -@stage(fragment) +@fragment fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { let x = dpdx(foo); let y = dpdy(foo); diff --git a/tests/in/texture-arg.wgsl b/tests/in/texture-arg.wgsl index 70fd586f0..3b1bbe680 100644 --- a/tests/in/texture-arg.wgsl +++ b/tests/in/texture-arg.wgsl @@ -7,7 +7,7 @@ fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { return textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); } -@stage(fragment) +@fragment fn main() -> @location(0) vec4 { return test(Texture, Sampler); } diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs index 83df32628..409768910 100644 --- a/tests/spirv-capabilities.rs +++ b/tests/spirv-capabilities.rs @@ -136,7 +136,7 @@ fn sample_rate_shading() { require( &[Ca::SampleRateShading], r#" - @stage(fragment) + @fragment fn f(@location(0) @interpolate(perspective, sample) x: f32) { } "#, ); @@ -144,7 +144,7 @@ fn sample_rate_shading() { require( &[Ca::SampleRateShading], r#" - @stage(fragment) + @fragment fn f(@builtin(sample_index) x: u32) { } "#, ); @@ -155,7 +155,7 @@ fn geometry() { require( &[Ca::Geometry], r#" - @stage(fragment) + @fragment fn f(@builtin(primitive_index) x: u32) { } "#, ); diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 9f341ff45..4ccfa29bf 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -132,7 +132,7 @@ fn bad_texture() { r#" @group(0) @binding(0) var sampler1 : sampler; - @stage(fragment) + @fragment fn main() -> @location(0) vec4 { let a = 3; return textureSample(a, sampler1, vec2(0.0)); @@ -245,7 +245,7 @@ fn bad_texture_sample_type() { @group(0) @binding(0) var sampler1 : sampler; @group(0) @binding(1) var texture : texture_2d; - @stage(fragment) + @fragment fn main() -> @location(0) vec4 { return textureSample(texture, sampler1, vec2(0.0)); } @@ -343,22 +343,6 @@ fn unknown_access() { ); } -#[test] -fn unknown_shader_stage() { - check( - r#" - @stage(geometry) fn main() {} - "#, - r#"error: unknown shader stage: 'geometry' - ┌─ wgsl:2:20 - │ -2 │ @stage(geometry) fn main() {} - │ ^^^^^^^^ unknown shader stage - -"#, - ); -} - #[test] fn unknown_ident() { check( @@ -1027,7 +1011,7 @@ fn pointer_type_equivalence() { fn missing_bindings() { check_validation_error! { " - @stage(vertex) + @vertex fn vertex(input: vec4) -> @location(0) vec4 { return input; } @@ -1044,7 +1028,7 @@ fn missing_bindings() { check_validation_error! { " - @stage(vertex) + @vertex fn vertex(@location(0) input: vec4, more_input: f32) -> @location(0) vec4 { return input + more_input; } @@ -1061,7 +1045,7 @@ fn missing_bindings() { check_validation_error! { " - @stage(vertex) + @vertex fn vertex(@location(0) input: vec4) -> vec4 { return input; } @@ -1082,7 +1066,7 @@ fn missing_bindings() { uv: vec2 } - @stage(vertex) + @vertex fn vertex(input: VertexIn) -> @location(0) vec4 { return input.pos; } From 172072501490c877d1efddeb653e0a74107b900c Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 15 Apr 2022 12:55:38 +0300 Subject: [PATCH 1688/2212] [wgsl-out] Update entry point stage attributes --- src/back/wgsl/writer.rs | 2 +- tests/out/wgsl/210-bevy-2d-shader-frag.wgsl | 2 +- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 2 +- tests/out/wgsl/210-bevy-shader-vert.wgsl | 2 +- tests/out/wgsl/246-collatz-comp.wgsl | 2 +- tests/out/wgsl/277-casting-vert.wgsl | 2 +- tests/out/wgsl/280-matrix-cast-vert.wgsl | 2 +- tests/out/wgsl/484-preprocessor-if-vert.wgsl | 2 +- tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl | 2 +- tests/out/wgsl/896-push-constant-vert.wgsl | 2 +- .../out/wgsl/900-implicit-conversions-vert.wgsl | 2 +- tests/out/wgsl/901-lhs-field-select-vert.wgsl | 2 +- tests/out/wgsl/931-constant-emitting-vert.wgsl | 2 +- tests/out/wgsl/932-for-loop-if-vert.wgsl | 2 +- tests/out/wgsl/access.wgsl | 6 +++--- tests/out/wgsl/bevy-pbr-frag.wgsl | 2 +- tests/out/wgsl/bevy-pbr-vert.wgsl | 2 +- tests/out/wgsl/binop-frag.wgsl | 2 +- tests/out/wgsl/bits.wgsl | 2 +- tests/out/wgsl/bits_glsl-frag.wgsl | 2 +- tests/out/wgsl/boids.wgsl | 2 +- tests/out/wgsl/bool-select-frag.wgsl | 2 +- tests/out/wgsl/buffer-frag.wgsl | 2 +- tests/out/wgsl/clamp-splat-vert.wgsl | 2 +- tests/out/wgsl/collatz.wgsl | 2 +- tests/out/wgsl/constant-array-size-vert.wgsl | 2 +- tests/out/wgsl/control-flow.wgsl | 2 +- tests/out/wgsl/declarations-vert.wgsl | 2 +- tests/out/wgsl/empty-global-name.wgsl | 2 +- tests/out/wgsl/empty.wgsl | 2 +- tests/out/wgsl/expressions-frag.wgsl | 2 +- tests/out/wgsl/extra.wgsl | 2 +- tests/out/wgsl/fma-frag.wgsl | 2 +- tests/out/wgsl/functions.wgsl | 2 +- tests/out/wgsl/global-constant-array-vert.wgsl | 2 +- tests/out/wgsl/globals.wgsl | 2 +- tests/out/wgsl/image.wgsl | 16 ++++++++-------- tests/out/wgsl/images-frag.wgsl | 2 +- tests/out/wgsl/interface.wgsl | 8 ++++---- tests/out/wgsl/interpolate.wgsl | 4 ++-- .../out/wgsl/inv-hyperbolic-trig-functions.wgsl | 2 +- tests/out/wgsl/long-form-matrix-vert.wgsl | 2 +- tests/out/wgsl/math-functions-vert.wgsl | 2 +- tests/out/wgsl/math-functions.wgsl | 2 +- tests/out/wgsl/operators.wgsl | 2 +- tests/out/wgsl/padding.wgsl | 2 +- tests/out/wgsl/prepostfix-frag.wgsl | 2 +- tests/out/wgsl/quad-vert.wgsl | 2 +- tests/out/wgsl/quad.wgsl | 6 +++--- tests/out/wgsl/quad_glsl-frag.wgsl | 2 +- tests/out/wgsl/quad_glsl-vert.wgsl | 2 +- tests/out/wgsl/samplers-frag.wgsl | 2 +- tests/out/wgsl/shadow.wgsl | 6 +++--- tests/out/wgsl/skybox.wgsl | 4 ++-- tests/out/wgsl/standard.wgsl | 2 +- tests/out/wgsl/swizzle_write-frag.wgsl | 2 +- tests/out/wgsl/texture-arg.wgsl | 2 +- 57 files changed, 75 insertions(+), 75 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index b2284f457..ddceadea9 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -347,7 +347,7 @@ impl Writer { ShaderStage::Fragment => "fragment", ShaderStage::Compute => "compute", }; - write!(self.out, "@stage({}) ", stage_str)?; + write!(self.out, "@{} ", stage_str)?; } Attribute::WorkGroupSize(size) => { write!( diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl index e9f9c92a6..a800b0f85 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl @@ -21,7 +21,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main(@location(0) v_Uv: vec2) -> FragmentOutput { v_Uv_1 = v_Uv; main_1(); diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index cec816f8a..365fa3470 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -42,7 +42,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec3, @location(2) Vertex_Uv: vec2) -> VertexOutput { Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 454a426cd..f7932979b 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -43,7 +43,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec3, @location(2) Vertex_Uv: vec2) -> VertexOutput { Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 03e6f1356..d54814615 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -51,7 +51,7 @@ fn main_1() { return; } -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn main(@builtin(global_invocation_id) param: vec3) { gl_GlobalInvocationID = param; main_1(); diff --git a/tests/out/wgsl/277-casting-vert.wgsl b/tests/out/wgsl/277-casting-vert.wgsl index 92ab6a516..3405a8b4c 100644 --- a/tests/out/wgsl/277-casting-vert.wgsl +++ b/tests/out/wgsl/277-casting-vert.wgsl @@ -3,7 +3,7 @@ fn main_1() { } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl index b5ee6454d..b9c5ec5a3 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl @@ -4,7 +4,7 @@ fn main_1() { let _e1 = f32(1); } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/484-preprocessor-if-vert.wgsl b/tests/out/wgsl/484-preprocessor-if-vert.wgsl index ea9cd03d5..58eb963ce 100644 --- a/tests/out/wgsl/484-preprocessor-if-vert.wgsl +++ b/tests/out/wgsl/484-preprocessor-if-vert.wgsl @@ -2,7 +2,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index c0c1581db..d749d5a1f 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -32,7 +32,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main(@location(0) position: vec2, @location(1) color: vec4) -> VertexOutput { position_1 = position; color_1 = color; diff --git a/tests/out/wgsl/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-vert.wgsl index f4892e00d..eec2204e0 100644 --- a/tests/out/wgsl/896-push-constant-vert.wgsl +++ b/tests/out/wgsl/896-push-constant-vert.wgsl @@ -8,7 +8,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/900-implicit-conversions-vert.wgsl b/tests/out/wgsl/900-implicit-conversions-vert.wgsl index 90d97dfab..7e5749c82 100644 --- a/tests/out/wgsl/900-implicit-conversions-vert.wgsl +++ b/tests/out/wgsl/900-implicit-conversions-vert.wgsl @@ -61,7 +61,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl index 6aa3bedd2..ec22e1d57 100644 --- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl +++ b/tests/out/wgsl/901-lhs-field-select-vert.wgsl @@ -5,7 +5,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl index 515f41c62..8634d13d6 100644 --- a/tests/out/wgsl/931-constant-emitting-vert.wgsl +++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl @@ -6,7 +6,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl index 3bc7924b2..2d599cca8 100644 --- a/tests/out/wgsl/932-for-loop-if-vert.wgsl +++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl @@ -16,7 +16,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index b6fc1921f..0381f76f8 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -78,7 +78,7 @@ fn test_arr_as_arg(a: array,5>) -> f32 { return a[4][9]; } -@stage(vertex) +@vertex fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32 = 0.0; var c: array; @@ -101,7 +101,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { return vec4((matrix * vec4(vec4(value))), 2.0); } -@stage(fragment) +@fragment fn foo_frag() -> @location(0) vec4 { bar.matrix[1][2] = 1.0; bar.matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); @@ -110,7 +110,7 @@ fn foo_frag() -> @location(0) vec4 { return vec4(0.0); } -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn atomics() { var tmp: i32; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index a1f49dd16..b1000381d 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -895,7 +895,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main(@location(0) v_WorldPosition: vec3, @location(1) v_WorldNormal: vec3, @location(2) v_Uv: vec2, @location(3) v_WorldTangent: vec4, @builtin(front_facing) param: bool) -> FragmentOutput { v_WorldPosition_1 = v_WorldPosition; v_WorldNormal_1 = v_WorldNormal; diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index 124914c13..ac13dcdfd 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -52,7 +52,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec3, @location(2) Vertex_Uv: vec2, @location(3) Vertex_Tangent: vec4) -> VertexOutput { Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; diff --git a/tests/out/wgsl/binop-frag.wgsl b/tests/out/wgsl/binop-frag.wgsl index 8edf934b3..e61d2e0fb 100644 --- a/tests/out/wgsl/binop-frag.wgsl +++ b/tests/out/wgsl/binop-frag.wgsl @@ -180,7 +180,7 @@ fn main1() { return; } -@stage(fragment) +@fragment fn main() { main1(); return; diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index 60cf9cc9e..a7c3b01e4 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -1,4 +1,4 @@ -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn main() { var i: i32 = 0; var i2_: vec2; diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 41d259914..977e1ba5b 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -105,7 +105,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index e166308ed..fd143f79f 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -26,7 +26,7 @@ var particlesSrc: Particles; @group(0) @binding(2) var particlesDst: Particles; -@stage(compute) @workgroup_size(64, 1, 1) +@compute @workgroup_size(64, 1, 1) fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { var vPos: vec2; var vVel: vec2; diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index ac22cfa89..4f0e218ee 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -37,7 +37,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main() -> FragmentOutput { main_1(); let _e3 = o_color; diff --git a/tests/out/wgsl/buffer-frag.wgsl b/tests/out/wgsl/buffer-frag.wgsl index 455fbb7af..4f561b427 100644 --- a/tests/out/wgsl/buffer-frag.wgsl +++ b/tests/out/wgsl/buffer-frag.wgsl @@ -30,7 +30,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index 227f49aab..deeea02ef 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -12,7 +12,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main(@location(0) a_pos: vec2) -> VertexOutput { a_pos_1 = a_pos; main_1(); diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index e81b1fa1c..ea16c7961 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -31,7 +31,7 @@ fn collatz_iterations(n_base: u32) -> u32 { return _e24; } -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn main(@builtin(global_invocation_id) global_id: vec3) { let _e8 = v_indices.data[global_id.x]; let _e9 = collatz_iterations(_e8); diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 2408f8104..16acd616e 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -33,7 +33,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index e31585d0b..55ad20ce2 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -30,7 +30,7 @@ fn loop_switch_continue(x: i32) { return; } -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn main(@builtin(global_invocation_id) global_id: vec3) { var pos: i32; diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index 0c5feecb6..555407e46 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -44,7 +44,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main(@location(0) position: vec2, @location(1) a: vec2, @location(2) in_array: vec4, @location(3) in_array_1: vec4) -> VertexOutput { vert.position = position; vert.a = a; diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index 8d6d3f9a0..59eb9fbbc 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -11,7 +11,7 @@ fn function_() { return; } -@stage(compute) @workgroup_size(64, 1, 1) +@compute @workgroup_size(64, 1, 1) fn main() { function_(); } diff --git a/tests/out/wgsl/empty.wgsl b/tests/out/wgsl/empty.wgsl index 527a0d56c..9d1c6ac9d 100644 --- a/tests/out/wgsl/empty.wgsl +++ b/tests/out/wgsl/empty.wgsl @@ -1,4 +1,4 @@ -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn main() { return; } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index fee7c4c98..a4153c01e 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -316,7 +316,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main() -> FragmentOutput { main_1(); let _e5 = o_color; diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index 0090ffad0..34a2e176c 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -10,7 +10,7 @@ struct FragmentIn { var pc: PushConstants; -@stage(fragment) +@fragment fn main(in: FragmentIn) -> @location(0) vec4 { let _e4 = pc.index; if (in.primitive_index == _e4) { diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 2019e48ad..2361221f1 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -41,7 +41,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main() -> FragmentOutput { main_1(); let _e3 = o_color; diff --git a/tests/out/wgsl/functions.wgsl b/tests/out/wgsl/functions.wgsl index 159daeb5b..62faf0e06 100644 --- a/tests/out/wgsl/functions.wgsl +++ b/tests/out/wgsl/functions.wgsl @@ -16,7 +16,7 @@ fn test_integer_dot_product() -> i32 { return c_4_; } -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn main() { let _e0 = test_fma(); let _e1 = test_integer_dot_product(); diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index 117c2e57c..6ef3214e7 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -6,7 +6,7 @@ fn main_1() { let _e2 = i; } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 0060e40bf..42f39a097 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -40,7 +40,7 @@ fn test_msl_packed_vec3_() { let unnamed_5 = (2.0 * data.v3_); } -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn main() { var Foo_1: f32 = 1.0; var at: bool = true; diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 4db74e0eb..6903548c0 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -37,7 +37,7 @@ var image_2d_depth: texture_depth_2d; @group(1) @binding(3) var image_cube_depth: texture_depth_cube; -@stage(compute) @workgroup_size(16, 1, 1) +@compute @workgroup_size(16, 1, 1) fn main(@builtin(local_invocation_id) local_id: vec3) { let dim = textureDimensions(image_storage_src); let itc = ((dim * vec2(local_id.xy)) % vec2(10, 20)); @@ -50,7 +50,7 @@ fn main(@builtin(local_invocation_id) local_id: vec3) { return; } -@stage(compute) @workgroup_size(16, 1, 1) +@compute @workgroup_size(16, 1, 1) fn depth_load(@builtin(local_invocation_id) local_id_1: vec3) { let dim_1 = textureDimensions(image_storage_src); let itc_1 = ((dim_1 * vec2(local_id_1.xy)) % vec2(10, 20)); @@ -59,7 +59,7 @@ fn depth_load(@builtin(local_invocation_id) local_id_1: vec3) { return; } -@stage(vertex) +@vertex fn queries() -> @builtin(position) vec4 { let dim_1d = textureDimensions(image_1d); let dim_1d_lod = textureDimensions(image_1d, i32(dim_1d)); @@ -78,7 +78,7 @@ fn queries() -> @builtin(position) vec4 { return vec4(f32(sum)); } -@stage(vertex) +@vertex fn levels_queries() -> @builtin(position) vec4 { let num_levels_2d = textureNumLevels(image_2d); let num_levels_2d_array = textureNumLevels(image_2d_array); @@ -92,7 +92,7 @@ fn levels_queries() -> @builtin(position) vec4 { return vec4(f32(sum_1)); } -@stage(fragment) +@fragment fn sample() -> @location(0) vec4 { let tc = vec2(0.5); let s1d = textureSample(image_1d, sampler_reg, tc.x); @@ -104,7 +104,7 @@ fn sample() -> @location(0) vec4 { return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); } -@stage(fragment) +@fragment fn sample_comparison() -> @location(0) f32 { let tc_1 = vec2(0.5); let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); @@ -113,7 +113,7 @@ fn sample_comparison() -> @location(0) f32 { return (s2d_depth + s2d_depth_level); } -@stage(fragment) +@fragment fn gather() -> @location(0) vec4 { let tc_2 = vec2(0.5); let s2d_1 = textureGather(1, image_2d, sampler_reg, tc_2); @@ -123,7 +123,7 @@ fn gather() -> @location(0) vec4 { return (((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset); } -@stage(fragment) +@fragment fn depth_no_comparison() -> @location(0) vec4 { let tc_3 = vec2(0.5); let s2d_2 = textureSample(image_2d_depth, sampler_reg, tc_3); diff --git a/tests/out/wgsl/images-frag.wgsl b/tests/out/wgsl/images-frag.wgsl index 18e508255..7be742365 100644 --- a/tests/out/wgsl/images-frag.wgsl +++ b/tests/out/wgsl/images-frag.wgsl @@ -137,7 +137,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index fdc2a77ec..b3e30b92d 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -19,26 +19,26 @@ struct Input2_ { var output: array; -@stage(vertex) +@vertex fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) instance_index: u32, @location(10) color: u32) -> VertexOutput { let tmp: u32 = ((vertex_index + instance_index) + color); return VertexOutput(vec4(1.0), f32(tmp)); } -@stage(fragment) +@fragment fn fragment(in: VertexOutput, @builtin(front_facing) front_facing: bool, @builtin(sample_index) sample_index: u32, @builtin(sample_mask) sample_mask: u32) -> FragmentOutput { let mask: u32 = (sample_mask & (1u << sample_index)); let color_1: f32 = select(0.0, 1.0, front_facing); return FragmentOutput(in.varying, mask, color_1); } -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn compute(@builtin(global_invocation_id) global_id: vec3, @builtin(local_invocation_id) local_id: vec3, @builtin(local_invocation_index) local_index: u32, @builtin(workgroup_id) wg_id: vec3, @builtin(num_workgroups) num_wgs: vec3) { output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x); return; } -@stage(vertex) +@vertex fn vertex_two_structs(in1_: Input1_, in2_: Input2_) -> @builtin(position) @invariant vec4 { var index: u32 = 2u; diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index ca3db022b..5e489a62d 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -9,7 +9,7 @@ struct FragmentInput { @location(6) @interpolate(perspective, sample) perspective_sample: f32, } -@stage(vertex) +@vertex fn vert_main() -> FragmentInput { var out: FragmentInput; @@ -25,7 +25,7 @@ fn vert_main() -> FragmentInput { return _e30; } -@stage(fragment) +@fragment fn frag_main(val: FragmentInput) { return; } diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl index d1bd7724f..e7bee8d85 100644 --- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -14,7 +14,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main() { main_1(); } diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index 7b0958044..aaf6cb0eb 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -25,7 +25,7 @@ fn main_1() { let _e129 = vec4(f32(1)); } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 3053f0240..610adb40a 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -154,7 +154,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main() { main_1(); return; diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index c4ae1673a..c87270742 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -1,4 +1,4 @@ -@stage(vertex) +@vertex fn main() { let v = vec4(0.0); let a = degrees(1.0); diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 262042296..19660d36d 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -235,7 +235,7 @@ fn assignment() { return; } -@stage(compute) @workgroup_size(1, 1, 1) +@compute @workgroup_size(1, 1, 1) fn main() { let _e4 = builtins(); let _e5 = splat(); diff --git a/tests/out/wgsl/padding.wgsl b/tests/out/wgsl/padding.wgsl index 1d3495477..06955f174 100644 --- a/tests/out/wgsl/padding.wgsl +++ b/tests/out/wgsl/padding.wgsl @@ -24,7 +24,7 @@ var input2_: Test2_; @group(0) @binding(2) var input3_: Test3_; -@stage(vertex) +@vertex fn vertex() -> @builtin(position) vec4 { let _e6 = input.b; let _e9 = input2_.b; diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index e7a32ef74..549ac805e 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -33,7 +33,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index b56803725..fec0c94af 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -20,7 +20,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main(@location(1) a_uv: vec2, @location(0) a_pos: vec2) -> VertexOutput { a_uv_1 = a_uv; a_pos_1 = a_pos; diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 5b565a281..98a4c6106 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -10,12 +10,12 @@ var u_texture: texture_2d; @group(0) @binding(1) var u_sampler: sampler; -@stage(vertex) +@vertex fn vert_main(@location(0) pos: vec2, @location(1) uv: vec2) -> VertexOutput { return VertexOutput(uv, vec4((c_scale * pos), 0.0, 1.0)); } -@stage(fragment) +@fragment fn frag_main(@location(0) uv_1: vec2) -> @location(0) vec4 { let color = textureSample(u_texture, u_sampler, uv_1); if (color.w == 0.0) { @@ -25,7 +25,7 @@ fn frag_main(@location(0) uv_1: vec2) -> @location(0) vec4 { return premultiplied; } -@stage(fragment) +@fragment fn fs_extra() -> @location(0) vec4 { return vec4(0.0, 0.5, 0.0, 0.5); } diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl index 58cde6e33..e90e5640d 100644 --- a/tests/out/wgsl/quad_glsl-frag.wgsl +++ b/tests/out/wgsl/quad_glsl-frag.wgsl @@ -10,7 +10,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main(@location(0) v_uv: vec2) -> FragmentOutput { v_uv_1 = v_uv; main_1(); diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index 6fd0b186e..ea4d77401 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -17,7 +17,7 @@ fn main_1() { return; } -@stage(vertex) +@vertex fn main(@location(0) a_pos: vec2, @location(1) a_uv: vec2) -> VertexOutput { a_pos_1 = a_pos; a_uv_1 = a_uv; diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 3b967fe7a..3ab0bc0c0 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -680,7 +680,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 2b0747df3..8bb6b5813 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -47,7 +47,7 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { return _e28; } -@stage(vertex) +@vertex fn vs_main(@location(0) position: vec4, @location(1) normal: vec4) -> VertexOutput { var out: VertexOutput; @@ -62,7 +62,7 @@ fn vs_main(@location(0) position: vec4, @location(1) normal: vec4) -> return _e27; } -@stage(fragment) +@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4 { var color: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i: u32 = 0u; @@ -93,7 +93,7 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { return (vec4(_e46, 1.0) * _e50); } -@stage(fragment) +@fragment fn fs_main_without_storage(in_1: VertexOutput) -> @location(0) vec4 { var color_1: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i_1: u32 = 0u; diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index e40793757..c9be90196 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -15,7 +15,7 @@ var r_texture: texture_cube; @group(0) @binding(2) var r_sampler: sampler; -@stage(vertex) +@vertex fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput { var tmp1_: i32; var tmp2_: i32; @@ -34,7 +34,7 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput { return VertexOutput(pos, (inv_model_view * unprojected.xyz)); } -@stage(fragment) +@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4 { let _e5 = textureSample(r_texture, r_sampler, in.uv); return _e5; diff --git a/tests/out/wgsl/standard.wgsl b/tests/out/wgsl/standard.wgsl index ea6a13a47..a121d6f9a 100644 --- a/tests/out/wgsl/standard.wgsl +++ b/tests/out/wgsl/standard.wgsl @@ -1,4 +1,4 @@ -@stage(fragment) +@fragment fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { let x = dpdx(foo); let y = dpdy(foo); diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index 5ca505041..1a57a2e3a 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -30,7 +30,7 @@ fn main_1() { return; } -@stage(fragment) +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/texture-arg.wgsl b/tests/out/wgsl/texture-arg.wgsl index 49d398499..09924d5eb 100644 --- a/tests/out/wgsl/texture-arg.wgsl +++ b/tests/out/wgsl/texture-arg.wgsl @@ -8,7 +8,7 @@ fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { return _e7; } -@stage(fragment) +@fragment fn main() -> @location(0) vec4 { let _e2 = test(Texture, Sampler); return _e2; From 33085863b77c1e62dfb09d641462aac0f7830e7c Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sat, 16 Apr 2022 12:05:40 +0200 Subject: [PATCH 1689/2212] update msrv to 1.56 --- .github/workflows/pipeline.yml | 20 +++----------------- Cargo.toml | 6 +----- README.md | 14 +------------- 3 files changed, 5 insertions(+), 35 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index b19fd9a8b..a54d9a891 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -11,27 +11,13 @@ jobs: - uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: "1.43.0" + toolchain: "1.56.0" override: true - - uses: actions-rs/cargo@v1 - name: Downgrade bitflags to MSRV - with: - command: update - args: -p bitflags --precise 1.2.1 - - uses: actions-rs/cargo@v1 - name: Downgrade indexmap to MSRV - with: - command: update - args: -p indexmap --precise 1.6.2 - uses: actions-rs/cargo@v1 name: Test all features with: - # we could use `test` but `criterion` is a dev dependency, - # and it doesn't build with our MSRV - command: check - # `cli` already enables most features, - # except for `arbitrary`, which requires Rust-1.51 - args: --workspace + command: test + args: --all-features --workspace - name: Check snapshots run: git diff --exit-code -- tests/out test: diff --git a/Cargo.toml b/Cargo.toml index 13a385d5d..abeee9fb5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] resolver = "2" +rust-version = "1.56" [package.metadata.docs.rs] all-features = true @@ -41,11 +42,6 @@ validate = [] name = "criterion" harness = false -# MSRV warnings: -# - arbitrary 1.0.3 requires Rust-1.51 -# - bitflags 1.3 requires Rust-1.46 -# - indexmap 1.7 requires Rust-1.49 - [dependencies] arbitrary = { version = "1", features = ["derive"], optional = true } bitflags = "1" diff --git a/README.md b/README.md index f6a6581c6..939eb91e1 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Crates.io](https://img.shields.io/crates/v/naga.svg?label=naga)](https://crates.io/crates/naga) [![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga) [![Build Status](https://github.com/gfx-rs/naga/workflows/pipeline/badge.svg)](https://github.com/gfx-rs/naga/actions) -![MSRV](https://img.shields.io/badge/rustc-1.43+-blue.svg) +![MSRV](https://img.shields.io/badge/rustc-1.56+-blue.svg) [![codecov.io](https://codecov.io/gh/gfx-rs/naga/branch/master/graph/badge.svg?token=9VOKYO8BM2)](https://codecov.io/gh/gfx-rs/naga) The shader translation library for the needs of [wgpu](https://github.com/gfx-rs/wgpu) and [gfx-rs](https://github.com/gfx-rs/gfx) projects. @@ -66,15 +66,3 @@ make validate-dot # for dot files, requires GraphViz installed make validate-wgsl # for WGSL shaders make validate-hlsl # for HLSL shaders. Note: this Make target makes use of the "sh" shell. This is not the default shell in Windows. ``` - -## MSRV - -The `naga` codebase's MSRV is 1.43. However some newer versions of our dependencies have newer MSRVs than that. Here are a list of all known MSRV breaking dependencies and the versions that hold to MSRV. - -- `bitflags`: `>1.3` have an MSRV of 1.46. `<=1.2` has an MSRV of 1.43 or earlier. - -If you want to use `naga` with `1.43` add the following to your Cargo.toml dependency list even if you don't use bitflags yourself: - -```toml -bitflags = "<1.3" -``` From c942a9011bd72b292b1d969b26bf982d3c5295fc Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sat, 16 Apr 2022 12:55:23 +0200 Subject: [PATCH 1690/2212] update doc of clamp fn --- src/front/glsl/constants.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 0c7c4ed6a..3e4bc8b5b 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -599,9 +599,9 @@ fn glsl_float_min(x: f64, y: f64) -> f64 { /// Helper function to implement the GLSL `clamp` function for floats. /// -/// While Rust does provide a `f64::clamp` method, it requires a version of rust -/// above our MSRV and it also panics if either `min` or `max` are `NaN`s which -/// is not the behavior specified by the glsl specification. +/// While Rust does provide a `f64::clamp` method, it panics if either +/// `min` or `max` are `NaN`s which is not the behavior specified by +/// the glsl specification. fn glsl_float_clamp(value: f64, min: f64, max: f64) -> f64 { glsl_float_min(glsl_float_max(value, min), max) } From ef387f73a613a7b580a1ac7a1974c325e26d0f7e Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 16 Apr 2022 22:22:34 -0700 Subject: [PATCH 1691/2212] [hlsl-out] Emit `row_major` qualifier on matrix uniform globals. Fixes #1836. --- src/back/hlsl/writer.rs | 6 ++++++ tests/out/hlsl/globals.hlsl | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 62a07f4e5..f22f6091b 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -646,6 +646,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if global.space == crate::AddressSpace::Uniform { write!(self.out, " {{ ")?; + // Even though Naga IR matrices are column-major, we must describe + // matrices passed from the CPU as being in row-major order. See + // the module-level comments for details. + if let TypeInner::Matrix { .. } = module.types[global.ty].inner { + write!(self.out, "row_major ")?; + } self.write_type(module, global.ty)?; let sub_name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, " {}", sub_name)?; diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index ba5e7e7fb..7b12afdf5 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -11,7 +11,7 @@ RWByteAddressBuffer alignment : register(u1); ByteAddressBuffer dummy : register(t2); cbuffer float_vecs : register(b3) { float4 float_vecs[20]; } cbuffer global_vec : register(b4) { float4 global_vec; } -cbuffer global_mat : register(b5) { float4x4 global_mat; } +cbuffer global_mat : register(b5) { row_major float4x4 global_mat; } void test_msl_packed_vec3_as_arg(float3 arg) { From 7ce98dcc7d7ec541597d1759aa28a321976574c1 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Sun, 17 Apr 2022 09:39:54 +0200 Subject: [PATCH 1692/2212] Make use of new language features (#1841) * use strip_prefix * make fn const (resolving TODO) * make use of nested OR patterns in match arms * warn on clippy::missing_const_for_fn * constify functions * ignore clippy::missing_const_for_fn for into_inner functions --- cli/src/main.rs | 4 +- src/arena.rs | 9 +++-- src/back/glsl/features.rs | 2 +- src/back/glsl/mod.rs | 24 ++++++------ src/back/hlsl/conv.rs | 12 +++--- src/back/hlsl/mod.rs | 6 +-- src/back/hlsl/writer.rs | 2 +- src/back/mod.rs | 16 ++++---- src/back/msl/mod.rs | 4 +- src/back/msl/sampler.rs | 10 ++--- src/back/msl/writer.rs | 14 +++---- src/back/spv/block.rs | 4 +- src/back/spv/helpers.rs | 6 ++- src/back/spv/instructions.rs | 6 +-- src/back/spv/layout.rs | 4 +- src/back/spv/mod.rs | 6 +-- src/back/spv/writer.rs | 2 +- src/back/wgsl/mod.rs | 2 +- src/back/wgsl/writer.rs | 16 ++++---- src/block.rs | 2 +- src/front/glsl/ast.rs | 4 +- src/front/glsl/builtins.rs | 6 +-- src/front/glsl/context.rs | 4 +- src/front/glsl/functions.rs | 4 +- src/front/glsl/mod.rs | 2 +- src/front/glsl/parser/declarations.rs | 6 +-- src/front/glsl/parser/expressions.rs | 2 +- src/front/glsl/types.rs | 4 +- src/front/interpolator.rs | 2 +- src/front/mod.rs | 6 +-- src/front/spv/convert.rs | 10 +++-- src/front/spv/mod.rs | 10 ++--- src/front/spv/null.rs | 2 +- src/front/wgsl/construction.rs | 34 ++++++----------- src/front/wgsl/lexer.rs | 35 +++++------------ src/front/wgsl/mod.rs | 23 +++++------- src/lib.rs | 10 ++--- src/proc/index.rs | 5 ++- src/proc/layouter.rs | 6 +-- src/proc/mod.rs | 22 +++++------ src/proc/terminator.rs | 20 +++++----- src/proc/typifier.rs | 4 +- src/span.rs | 7 ++-- src/valid/analyzer.rs | 14 +++---- src/valid/expression.rs | 54 +++++++++++++++------------ src/valid/function.rs | 10 +++-- src/valid/mod.rs | 4 +- src/valid/type.rs | 6 +-- 48 files changed, 221 insertions(+), 246 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index c5e40c7a3..30732764d 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -288,7 +288,7 @@ fn run() -> Result<(), Box> { } } } - ext @ "vert" | ext @ "frag" | ext @ "comp" => { + ext @ ("vert" | "frag" | "comp") => { let input = String::from_utf8(input)?; let mut parser = naga::front::glsl::Parser::default(); @@ -429,7 +429,7 @@ fn run() -> Result<(), Box> { fs::write(output_path, bytes.as_slice())?; } - stage @ "vert" | stage @ "frag" | stage @ "comp" => { + stage @ ("vert" | "frag" | "comp") => { use naga::back::glsl; let pipeline_options = glsl::PipelineOptions { diff --git a/src/arena.rs b/src/arena.rs index 583e99eec..77f425d1f 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -81,7 +81,7 @@ impl Handle { marker: PhantomData, }; - pub(crate) fn new(index: Index) -> Self { + pub(crate) const fn new(index: Index) -> Self { Handle { index, marker: PhantomData, @@ -89,7 +89,7 @@ impl Handle { } /// Returns the zero-based index of this handle. - pub fn index(self) -> usize { + pub const fn index(self) -> usize { let index = self.index.get() - 1; index as usize } @@ -106,7 +106,7 @@ impl Handle { } /// Convert a `usize` index into a `Handle`, without range checks. - unsafe fn from_usize_unchecked(index: usize) -> Self { + const unsafe fn from_usize_unchecked(index: usize) -> Self { Handle::new(Index::new_unchecked((index + 1) as u32)) } } @@ -187,7 +187,7 @@ impl fmt::Debug for Arena { impl Arena { /// Create a new arena with no initial capacity allocated. - pub fn new() -> Self { + pub const fn new() -> Self { Arena { data: Vec::new(), #[cfg(feature = "span")] @@ -196,6 +196,7 @@ impl Arena { } /// Extracts the inner vector. + #[allow(clippy::missing_const_for_fn)] // ignore due to requirement of #![feature(const_precise_live_drops)] pub fn into_inner(self) -> Vec { self.data } diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 408046fc8..61f019682 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -47,7 +47,7 @@ pub struct FeaturesManager(Features); impl FeaturesManager { /// Creates a new [`FeaturesManager`] instance - pub fn new() -> Self { + pub const fn new() -> Self { Self(Features::empty()) } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a7ef4462f..4d3c834fc 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -73,7 +73,7 @@ pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; pub type BindingMap = std::collections::BTreeMap; impl crate::AtomicFunction { - fn to_glsl(self) -> &'static str { + const fn to_glsl(self) -> &'static str { match self { Self::Add | Self::Subtract => "Add", Self::And => "And", @@ -88,7 +88,7 @@ impl crate::AtomicFunction { } impl crate::AddressSpace { - fn is_buffer(&self) -> bool { + const fn is_buffer(&self) -> bool { match *self { crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } => true, _ => false, @@ -96,7 +96,7 @@ impl crate::AddressSpace { } /// Whether a variable with this address space can be initialized - fn initializable(&self) -> bool { + const fn initializable(&self) -> bool { match *self { crate::AddressSpace::Function | crate::AddressSpace::Private => true, crate::AddressSpace::WorkGroup @@ -121,7 +121,7 @@ pub enum Version { impl Version { /// Returns true if self is `Version::Embedded` (i.e. is a es version) - fn is_es(&self) -> bool { + const fn is_es(&self) -> bool { match *self { Version::Desktop(_) => false, Version::Embedded(_) => true, @@ -306,7 +306,7 @@ impl fmt::Display for VaryingName<'_> { } impl ShaderStage { - fn to_str(self) -> &'static str { + const fn to_str(self) -> &'static str { match self { ShaderStage::Compute => "cs", ShaderStage::Fragment => "fs", @@ -3153,7 +3153,7 @@ struct ScalarString<'a> { /// /// # Errors /// If a [`Float`](crate::ScalarKind::Float) with an width that isn't 4 or 8 -fn glsl_scalar( +const fn glsl_scalar( kind: crate::ScalarKind, width: crate::Bytes, ) -> Result, Error> { @@ -3187,7 +3187,7 @@ fn glsl_scalar( } /// Helper function that returns the glsl variable name for a builtin -fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { +const fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { use crate::BuiltIn as Bi; match built_in { @@ -3230,7 +3230,7 @@ fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { } /// Helper function that returns the string corresponding to the address space -fn glsl_storage_qualifier(space: crate::AddressSpace) -> Option<&'static str> { +const fn glsl_storage_qualifier(space: crate::AddressSpace) -> Option<&'static str> { use crate::AddressSpace as As; match space { @@ -3245,7 +3245,7 @@ fn glsl_storage_qualifier(space: crate::AddressSpace) -> Option<&'static str> { } /// Helper function that returns the string corresponding to the glsl interpolation qualifier -fn glsl_interpolation(interpolation: crate::Interpolation) -> &'static str { +const fn glsl_interpolation(interpolation: crate::Interpolation) -> &'static str { use crate::Interpolation as I; match interpolation { @@ -3256,7 +3256,7 @@ fn glsl_interpolation(interpolation: crate::Interpolation) -> &'static str { } /// Return the GLSL auxiliary qualifier for the given sampling value. -fn glsl_sampling(sampling: crate::Sampling) -> Option<&'static str> { +const fn glsl_sampling(sampling: crate::Sampling) -> Option<&'static str> { use crate::Sampling as S; match sampling { @@ -3267,7 +3267,7 @@ fn glsl_sampling(sampling: crate::Sampling) -> Option<&'static str> { } /// Helper function that returns the glsl dimension string of [`ImageDimension`](crate::ImageDimension) -fn glsl_dimension(dim: crate::ImageDimension) -> &'static str { +const fn glsl_dimension(dim: crate::ImageDimension) -> &'static str { use crate::ImageDimension as IDim; match dim { @@ -3279,7 +3279,7 @@ fn glsl_dimension(dim: crate::ImageDimension) -> &'static str { } /// Helper function that returns the glsl storage format string of [`StorageFormat`](crate::StorageFormat) -fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { +const fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { use crate::StorageFormat as Sf; match format { diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index d799c0b98..b63d63577 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -15,7 +15,7 @@ impl crate::ScalarKind { /// Helper function that returns scalar related strings /// /// - pub(super) fn to_hlsl_str(self, width: crate::Bytes) -> Result<&'static str, Error> { + pub(super) const fn to_hlsl_str(self, width: crate::Bytes) -> Result<&'static str, Error> { match self { Self::Sint => Ok("int"), Self::Uint => Ok("uint"), @@ -31,7 +31,7 @@ impl crate::ScalarKind { } impl crate::TypeInner { - pub(super) fn is_matrix(&self) -> bool { + pub(super) const fn is_matrix(&self) -> bool { match *self { Self::Matrix { .. } => true, _ => false, @@ -113,7 +113,7 @@ impl crate::TypeInner { } impl crate::StorageFormat { - pub(super) fn to_hlsl_str(self) -> &'static str { + pub(super) const fn to_hlsl_str(self) -> &'static str { match self { Self::R16Float => "float", Self::R8Unorm => "unorm float", @@ -187,7 +187,7 @@ impl crate::BuiltIn { impl crate::Interpolation { /// Return the string corresponding to the HLSL interpolation qualifier. - pub(super) fn to_hlsl_str(self) -> Option<&'static str> { + pub(super) const fn to_hlsl_str(self) -> Option<&'static str> { match self { // Would be "linear", but it's the default interpolation in SM4 and up // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-struct#interpolation-modifiers-introduced-in-shader-model-4 @@ -200,7 +200,7 @@ impl crate::Interpolation { impl crate::Sampling { /// Return the HLSL auxiliary qualifier for the given sampling value. - pub(super) fn to_hlsl_str(self) -> Option<&'static str> { + pub(super) const fn to_hlsl_str(self) -> Option<&'static str> { match self { Self::Center => None, Self::Centroid => Some("centroid"), @@ -211,7 +211,7 @@ impl crate::Sampling { impl crate::AtomicFunction { /// Return the HLSL suffix for the `InterlockedXxx` method. - pub(super) fn to_hlsl_suffix(self) -> &'static str { + pub(super) const fn to_hlsl_suffix(self) -> &'static str { match self { Self::Add | Self::Subtract => "Add", Self::And => "And", diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 3ab88409f..f51d49db3 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -65,7 +65,7 @@ pub enum ShaderModel { } impl ShaderModel { - pub fn to_str(self) -> &'static str { + pub const fn to_str(self) -> &'static str { match self { Self::V5_0 => "5_0", Self::V5_1 => "5_1", @@ -75,7 +75,7 @@ impl ShaderModel { } impl crate::ShaderStage { - pub fn to_hlsl_str(self) -> &'static str { + pub const fn to_hlsl_str(self) -> &'static str { match self { Self::Vertex => "vs", Self::Fragment => "ps", @@ -85,7 +85,7 @@ impl crate::ShaderStage { } impl crate::ImageDimension { - fn to_hlsl_str(self) -> &'static str { + const fn to_hlsl_str(self) -> &'static str { match self { Self::D1 => "1D", Self::D2 => "2D", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index f22f6091b..9285687ba 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -57,7 +57,7 @@ enum InterfaceKey { } impl InterfaceKey { - fn new(binding: Option<&crate::Binding>) -> Self { + const fn new(binding: Option<&crate::Binding>) -> Self { match binding { Some(&crate::Binding::Location { location, .. }) => Self::Location(location), Some(&crate::Binding::BuiltIn(built_in)) => Self::BuiltIn(built_in), diff --git a/src/back/mod.rs b/src/back/mod.rs index 0c48e6a55..daec79a8c 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -26,7 +26,7 @@ type NeedBakeExpressions = crate::FastHashSet>; struct Level(usize); impl Level { - fn next(&self) -> Self { + const fn next(&self) -> Self { Level(self.0 + 1) } } @@ -61,7 +61,7 @@ struct FunctionCtx<'a> { impl<'a> FunctionCtx<'_> { /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function - fn name_key(&self, local: crate::Handle) -> crate::proc::NameKey { + const fn name_key(&self, local: crate::Handle) -> crate::proc::NameKey { match self.ty { FunctionType::Function(handle) => crate::proc::NameKey::FunctionLocal(handle, local), FunctionType::EntryPoint(idx) => crate::proc::NameKey::EntryPointLocal(idx, local), @@ -72,7 +72,7 @@ impl<'a> FunctionCtx<'_> { /// /// # Panics /// - If the function arguments are less or equal to `arg` - fn argument_key(&self, arg: u32) -> crate::proc::NameKey { + const fn argument_key(&self, arg: u32) -> crate::proc::NameKey { match self.ty { FunctionType::Function(handle) => crate::proc::NameKey::FunctionArgument(handle, arg), FunctionType::EntryPoint(ep_index) => { @@ -128,7 +128,7 @@ impl crate::Expression { /// See the [module-level documentation][emit] for details. /// /// [emit]: index.html#expression-evaluation-time - fn bake_ref_count(&self) -> usize { + const fn bake_ref_count(&self) -> usize { match *self { // accesses are never cached, only loads are crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => !0, @@ -149,7 +149,7 @@ impl crate::Expression { /// Helper function that returns the string corresponding to the [`BinaryOperator`](crate::BinaryOperator) /// # Notes /// Used by `glsl-out`, `msl-out`, `wgsl-out`, `hlsl-out`. -fn binary_operation_str(op: crate::BinaryOperator) -> &'static str { +const fn binary_operation_str(op: crate::BinaryOperator) -> &'static str { use crate::BinaryOperator as Bo; match op { Bo::Add => "+", @@ -176,7 +176,7 @@ fn binary_operation_str(op: crate::BinaryOperator) -> &'static str { /// Helper function that returns the string corresponding to the [`VectorSize`](crate::VectorSize) /// # Notes /// Used by `msl-out`, `wgsl-out`, `hlsl-out`. -fn vector_size_str(size: crate::VectorSize) -> &'static str { +const fn vector_size_str(size: crate::VectorSize) -> &'static str { match size { crate::VectorSize::Bi => "2", crate::VectorSize::Tri => "3", @@ -185,7 +185,7 @@ fn vector_size_str(size: crate::VectorSize) -> &'static str { } impl crate::TypeInner { - fn is_handle(&self) -> bool { + const fn is_handle(&self) -> bool { match *self { crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => true, _ => false, @@ -197,7 +197,7 @@ impl crate::Statement { /// Returns true if the statement directly terminates the current block. /// /// Used to decide whether case blocks require a explicit `break`. - pub fn is_terminator(&self) -> bool { + pub const fn is_terminator(&self) -> bool { match *self { crate::Statement::Break | crate::Statement::Continue diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 28cff0476..2ba436491 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -305,7 +305,7 @@ impl Options { } } - fn resolve_push_constants( + const fn resolve_push_constants( &self, stage: crate::ShaderStage, ) -> Result { @@ -428,7 +428,7 @@ impl ResolvedBinding { } impl ResolvedInterpolation { - fn from_binding(interpolation: crate::Interpolation, sampling: crate::Sampling) -> Self { + const fn from_binding(interpolation: crate::Interpolation, sampling: crate::Sampling) -> Self { use crate::Interpolation as I; use crate::Sampling as S; diff --git a/src/back/msl/sampler.rs b/src/back/msl/sampler.rs index c603fac1b..3b95fa378 100644 --- a/src/back/msl/sampler.rs +++ b/src/back/msl/sampler.rs @@ -19,7 +19,7 @@ impl Default for Coord { } impl Coord { - pub fn as_str(&self) -> &'static str { + pub const fn as_str(&self) -> &'static str { match *self { Self::Normalized => "normalized", Self::Pixel => "pixel", @@ -45,7 +45,7 @@ impl Default for Address { } impl Address { - pub fn as_str(&self) -> &'static str { + pub const fn as_str(&self) -> &'static str { match *self { Self::Repeat => "repeat", Self::MirroredRepeat => "mirrored_repeat", @@ -72,7 +72,7 @@ impl Default for BorderColor { } impl BorderColor { - pub fn as_str(&self) -> &'static str { + pub const fn as_str(&self) -> &'static str { match *self { Self::TransparentBlack => "transparent_black", Self::OpaqueBlack => "opaque_black", @@ -90,7 +90,7 @@ pub enum Filter { } impl Filter { - pub fn as_str(&self) -> &'static str { + pub const fn as_str(&self) -> &'static str { match *self { Self::Nearest => "nearest", Self::Linear => "linear", @@ -125,7 +125,7 @@ impl Default for CompareFunc { } impl CompareFunc { - pub fn as_str(&self) -> &'static str { + pub const fn as_str(&self) -> &'static str { match *self { Self::Never => "never", Self::Less => "less", diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 982742c7a..65cf23656 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -323,7 +323,7 @@ pub struct Writer { } impl crate::ScalarKind { - fn to_msl_name(self) -> &'static str { + const fn to_msl_name(self) -> &'static str { match self { Self::Float => "float", Self::Sint => "int", @@ -333,7 +333,7 @@ impl crate::ScalarKind { } } -fn separate(need_separator: bool) -> &'static str { +const fn separate(need_separator: bool) -> &'static str { if need_separator { "," } else { @@ -398,7 +398,7 @@ impl crate::AddressSpace { /// Returns true if global variables in this address space are /// passed in function arguments. These arguments need to be /// passed through any functions called from the entry point. - fn needs_pass_through(&self) -> bool { + const fn needs_pass_through(&self) -> bool { match *self { Self::Uniform | Self::Storage { .. } @@ -411,7 +411,7 @@ impl crate::AddressSpace { } /// Returns true if the address space may need a "const" qualifier. - fn needs_access_qualifier(&self) -> bool { + const fn needs_access_qualifier(&self) -> bool { match *self { //Note: we are ignoring the storage access here, and instead // rely on the actual use of a global by functions. This means we @@ -425,7 +425,7 @@ impl crate::AddressSpace { } } - fn to_msl_name(self) -> Option<&'static str> { + const fn to_msl_name(self) -> Option<&'static str> { match self { Self::Handle => None, Self::Uniform | Self::PushConstant => Some("constant"), @@ -438,7 +438,7 @@ impl crate::AddressSpace { impl crate::Type { // Returns `true` if we need to emit an alias for this type. - fn needs_alias(&self) -> bool { + const fn needs_alias(&self) -> bool { use crate::TypeInner as Ti; match self.inner { @@ -459,7 +459,7 @@ impl crate::Type { impl crate::Constant { // Returns `true` if we need to emit an alias for this constant. - fn needs_alias(&self) -> bool { + const fn needs_alias(&self) -> bool { match self.inner { crate::ConstantInner::Scalar { .. } => self.name.is_some(), crate::ConstantInner::Composite { .. } => true, diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index ce5592ab6..c40ed4fbe 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -453,7 +453,7 @@ impl<'w> BlockContext<'w> { _ => unimplemented!(), }, crate::BinaryOperator::Equal => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { + Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint) => { spirv::Op::IEqual } Some(crate::ScalarKind::Float) => spirv::Op::FOrdEqual, @@ -461,7 +461,7 @@ impl<'w> BlockContext<'w> { _ => unimplemented!(), }, crate::BinaryOperator::NotEqual => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { + Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint) => { spirv::Op::INotEqual } Some(crate::ScalarKind::Float) => spirv::Op::FOrdNotEqual, diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index 60f86c691..1ef0db191 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -20,7 +20,7 @@ pub(super) fn string_to_words(input: &str) -> Vec { words } -pub(super) fn map_storage_class(space: crate::AddressSpace) -> spirv::StorageClass { +pub(super) const fn map_storage_class(space: crate::AddressSpace) -> spirv::StorageClass { match space { crate::AddressSpace::Handle => spirv::StorageClass::UniformConstant, crate::AddressSpace::Function => spirv::StorageClass::Function, @@ -50,7 +50,9 @@ pub(super) fn contains_builtin( } impl crate::AddressSpace { - pub(super) fn to_spirv_semantics_and_scope(self) -> (spirv::MemorySemantics, spirv::Scope) { + pub(super) const fn to_spirv_semantics_and_scope( + self, + ) -> (spirv::MemorySemantics, spirv::Scope) { match self { Self::Storage { .. } => (spirv::MemorySemantics::UNIFORM_MEMORY, spirv::Scope::Device), Self::WorkGroup => ( diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 79f54d450..9ec1deb0b 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -502,7 +502,7 @@ impl super::Instruction { instruction } - pub(super) fn function_end() -> Self { + pub(super) const fn function_end() -> Self { Self::new(Op::FunctionEnd) } @@ -906,11 +906,11 @@ impl super::Instruction { instruction } - pub(super) fn kill() -> Self { + pub(super) const fn kill() -> Self { Self::new(Op::Kill) } - pub(super) fn return_void() -> Self { + pub(super) const fn return_void() -> Self { Self::new(Op::Return) } diff --git a/src/back/spv/layout.rs b/src/back/spv/layout.rs index 95d154cd7..39117a3d2 100644 --- a/src/back/spv/layout.rs +++ b/src/back/spv/layout.rs @@ -6,7 +6,7 @@ use std::iter; const GENERATOR: Word = 28; impl PhysicalLayout { - pub(super) fn new(version: Word) -> Self { + pub(super) const fn new(version: Word) -> Self { PhysicalLayout { magic_number: MAGIC_NUMBER, version, @@ -72,7 +72,7 @@ impl super::recyclable::Recyclable for LogicalLayout { } impl Instruction { - pub(super) fn new(op: Op) -> Self { + pub(super) const fn new(op: Op) -> Self { Instruction { op, wc: 1, // Always start at 1 for the first word (OP + WC), diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 538147ed1..3ae577e79 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -104,7 +104,7 @@ struct TerminatedBlock { } impl Block { - fn new(label_id: Word) -> Self { + const fn new(label_id: Word) -> Self { Block { label_id, body: Vec::new(), @@ -467,7 +467,7 @@ struct GlobalVariable { } impl GlobalVariable { - fn dummy() -> Self { + const fn dummy() -> Self { Self { var_id: 0, handle_id: 0, @@ -475,7 +475,7 @@ impl GlobalVariable { } } - fn new(id: Word) -> Self { + const fn new(id: Word) -> Self { Self { var_id: id, handle_id: 0, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 77c909014..dd1cc58c8 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1551,7 +1551,7 @@ impl Writer { } /// Return the set of capabilities the last module written used. - pub fn get_capabilities_used(&self) -> &crate::FastHashSet { + pub const fn get_capabilities_used(&self) -> &crate::FastHashSet { &self.capabilities_used } } diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs index 0a705691c..d731b1ca0 100644 --- a/src/back/wgsl/mod.rs +++ b/src/back/wgsl/mod.rs @@ -36,7 +36,7 @@ pub fn write_string( } impl crate::AtomicFunction { - fn to_wgsl(self) -> &'static str { + const fn to_wgsl(self) -> &'static str { match self { Self::Add => "Add", Self::Subtract => "Sub", diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index ddceadea9..7666f8044 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1843,7 +1843,7 @@ impl Writer { } } -fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { +const fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { use crate::BuiltIn as Bi; match built_in { @@ -1866,7 +1866,7 @@ fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { } } -fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { +const fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { use crate::ImageDimension as IDim; match dim { @@ -1877,7 +1877,7 @@ fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { } } -fn scalar_kind_str(kind: crate::ScalarKind) -> &'static str { +const fn scalar_kind_str(kind: crate::ScalarKind) -> &'static str { use crate::ScalarKind as Sk; match kind { @@ -1888,7 +1888,7 @@ fn scalar_kind_str(kind: crate::ScalarKind) -> &'static str { } } -fn storage_format_str(format: crate::StorageFormat) -> &'static str { +const fn storage_format_str(format: crate::StorageFormat) -> &'static str { use crate::StorageFormat as Sf; match format { @@ -1928,7 +1928,7 @@ fn storage_format_str(format: crate::StorageFormat) -> &'static str { } /// Helper function that returns the string corresponding to the WGSL interpolation qualifier -fn interpolation_str(interpolation: crate::Interpolation) -> &'static str { +const fn interpolation_str(interpolation: crate::Interpolation) -> &'static str { use crate::Interpolation as I; match interpolation { @@ -1939,7 +1939,7 @@ fn interpolation_str(interpolation: crate::Interpolation) -> &'static str { } /// Return the WGSL auxiliary qualifier for the given sampling value. -fn sampling_str(sampling: crate::Sampling) -> &'static str { +const fn sampling_str(sampling: crate::Sampling) -> &'static str { use crate::Sampling as S; match sampling { @@ -1949,7 +1949,9 @@ fn sampling_str(sampling: crate::Sampling) -> &'static str { } } -fn address_space_str(space: crate::AddressSpace) -> (Option<&'static str>, Option<&'static str>) { +const fn address_space_str( + space: crate::AddressSpace, +) -> (Option<&'static str>, Option<&'static str>) { use crate::AddressSpace as As; ( diff --git a/src/block.rs b/src/block.rs index e70202b8d..ba4c95ab3 100644 --- a/src/block.rs +++ b/src/block.rs @@ -14,7 +14,7 @@ pub struct Block { } impl Block { - pub fn new() -> Self { + pub const fn new() -> Self { Self { body: Vec::new(), #[cfg(feature = "span")] diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 64d3faea2..dc47647dc 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -352,7 +352,7 @@ pub enum ParameterQualifier { impl ParameterQualifier { /// Returns true if the argument should be passed as a lhs expression - pub fn is_lhs(&self) -> bool { + pub const fn is_lhs(&self) -> bool { match *self { ParameterQualifier::Out | ParameterQualifier::InOut => true, _ => false, @@ -360,7 +360,7 @@ impl ParameterQualifier { } /// Converts from a parameter qualifier into a [`ExprPos`](ExprPos) - pub fn as_pos(&self) -> ExprPos { + pub const fn as_pos(&self) -> ExprPos { match *self { ParameterQualifier::Out | ParameterQualifier::InOut => ExprPos::Lhs, _ => ExprPos::Rhs, diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index f06980b9b..6e6148138 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -13,7 +13,7 @@ use crate::{ }; impl crate::ScalarKind { - fn dummy_storage_format(&self) -> crate::StorageFormat { + const fn dummy_storage_format(&self) -> crate::StorageFormat { match *self { Sk::Sint => crate::StorageFormat::R16Sint, Sk::Uint => crate::StorageFormat::R16Uint, @@ -53,7 +53,7 @@ impl Module { } } -fn make_coords_arg(number_of_components: usize, kind: Sk) -> TypeInner { +const fn make_coords_arg(number_of_components: usize, kind: Sk) -> TypeInner { let width = 4; match number_of_components { @@ -2301,7 +2301,7 @@ fn texture_args_generator( /// Helper functions used to convert from a image dimension into a integer representing the /// number of components needed for the coordinates vector (1 means scalar instead of vector) -fn image_dims_to_coords_size(dim: Dim) -> usize { +const fn image_dims_to_coords_size(dim: Dim) -> usize { match dim { Dim::D1 => 1, Dim::D2 => 2, diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 45d645ec2..c0b4bd95f 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -32,7 +32,7 @@ pub enum ExprPos { impl ExprPos { /// Returns an lhs position if the current position is lhs otherwise AccessBase - fn maybe_access_base(&self, constant_index: bool) -> Self { + const fn maybe_access_base(&self, constant_index: bool) -> Self { match *self { ExprPos::Lhs => *self, _ => ExprPos::AccessBase { constant_index }, @@ -1414,7 +1414,7 @@ pub struct StmtContext { } impl StmtContext { - fn new() -> Self { + const fn new() -> Self { StmtContext { hir_exprs: Arena::new(), } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 1cc225b80..a9e8fd417 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1521,9 +1521,9 @@ fn conversion(target: &TypeInner, source: &TypeInner) -> Option { // A conversion from a float to a double is special ((Float, 8), (Float, 4)) => Conversion::FloatToDouble, // A conversion from an integer to a float is special - ((Float, 4), (Sint, _)) | ((Float, 4), (Uint, _)) => Conversion::IntToFloat, + ((Float, 4), (Sint | Uint, _)) => Conversion::IntToFloat, // A conversion from an integer to a double is special - ((Float, 8), (Sint, _)) | ((Float, 8), (Uint, _)) => Conversion::IntToDouble, + ((Float, 8), (Sint | Uint, _)) => Conversion::IntToDouble, _ => Conversion::Other, }, ) diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index eee12064e..2d9645ab6 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -233,7 +233,7 @@ impl Parser { /// Following an unsuccessful parsing the state of the returned information /// is undefined, it might contain only partial information about the /// current shader, the previous shader or both. - pub fn metadata(&self) -> &ShaderMetadata { + pub const fn metadata(&self) -> &ShaderMetadata { &self.meta } } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index bc5a8c4f9..18a6ceb2e 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -451,11 +451,7 @@ impl<'source> ParsingContext<'source> { match parser.module.types[ty].inner { TypeInner::Scalar { - kind: ScalarKind::Float, - .. - } - | TypeInner::Scalar { - kind: ScalarKind::Sint, + kind: ScalarKind::Float | ScalarKind::Sint, .. } => {} _ => parser.errors.push(Error { diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 3f1d0fd39..44f9ea9d0 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -507,7 +507,7 @@ impl<'source> ParsingContext<'source> { } } -fn binding_power(value: &TokenValue) -> Option<(u8, u8)> { +const fn binding_power(value: &TokenValue) -> Option<(u8, u8)> { Some(match *value { TokenValue::LogicalOr => (1, 2), TokenValue::LogicalXor => (3, 4), diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index cf38f9d73..6a197cceb 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -204,7 +204,7 @@ pub fn parse_type(type_name: &str) -> Option { } } -pub fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, Bytes)> { +pub const fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, Bytes)> { match *ty { TypeInner::Scalar { kind, width } => Some((kind, width)), TypeInner::Vector { kind, width, .. } => Some((kind, width)), @@ -214,7 +214,7 @@ pub fn scalar_components(ty: &TypeInner) -> Option<(ScalarKind, Bytes)> { } } -pub fn type_power(kind: ScalarKind, width: Bytes) -> Option { +pub const fn type_power(kind: ScalarKind, width: Bytes) -> Option { Some(match kind { ScalarKind::Sint => 0, ScalarKind::Uint => 1, diff --git a/src/front/interpolator.rs b/src/front/interpolator.rs index 0482d75a0..96f5db6ff 100644 --- a/src/front/interpolator.rs +++ b/src/front/interpolator.rs @@ -50,7 +50,7 @@ impl crate::Binding { *interpolation = Some(crate::Interpolation::Perspective); *sampling = Some(crate::Sampling::Center); } - Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => { + Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint) => { *interpolation = Some(crate::Interpolation::Flat); *sampling = None; } diff --git a/src/front/mod.rs b/src/front/mod.rs index dde28d7b5..fb6bef75e 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -55,7 +55,7 @@ impl Emitter { #[allow(dead_code)] impl super::ConstantInner { - fn boolean(value: bool) -> Self { + const fn boolean(value: bool) -> Self { Self::Scalar { width: super::BOOL_WIDTH, value: super::ScalarValue::Bool(value), @@ -70,7 +70,7 @@ pub struct Typifier { } impl Typifier { - pub fn new() -> Self { + pub const fn new() -> Self { Typifier { resolutions: Vec::new(), } @@ -147,6 +147,6 @@ impl ops::Index> for Typifier { /// assert_eq!(334, align_up(333, 2)); /// assert_eq!(384, align_up(257, 128)); /// ``` -pub fn align_up(value: u32, align: u32) -> u32 { +pub const fn align_up(value: u32, align: u32) -> u32 { ((value.wrapping_sub(1)) & !(align - 1)).wrapping_add(align) } diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 9ffc3880d..b555833ed 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -2,7 +2,7 @@ use super::error::Error; use num_traits::cast::FromPrimitive; use std::convert::TryInto; -pub(super) fn map_binary_operator(word: spirv::Op) -> Result { +pub(super) const fn map_binary_operator(word: spirv::Op) -> Result { use crate::BinaryOperator; use spirv::Op; @@ -42,7 +42,9 @@ pub(super) fn map_binary_operator(word: spirv::Op) -> Result Result { +pub(super) const fn map_relational_fun( + word: spirv::Op, +) -> Result { use crate::RelationalFunction as Rf; use spirv::Op; @@ -57,7 +59,7 @@ pub(super) fn map_relational_fun(word: spirv::Op) -> Result Result { +pub(super) const fn map_vector_size(word: spirv::Word) -> Result { match word { 2 => Ok(crate::VectorSize::Bi), 3 => Ok(crate::VectorSize::Tri), @@ -124,7 +126,7 @@ pub(super) fn map_width(word: spirv::Word) -> Result { pub(super) fn map_builtin(word: spirv::Word, invariant: bool) -> Result { use spirv::BuiltIn as Bi; Ok(match spirv::BuiltIn::from_u32(word) { - Some(Bi::Position) | Some(Bi::FragCoord) => crate::BuiltIn::Position { invariant }, + Some(Bi::Position | Bi::FragCoord) => crate::BuiltIn::Position { invariant }, Some(Bi::ViewIndex) => crate::BuiltIn::ViewIndex, // vertex Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 3f96cae05..141970e6f 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -89,7 +89,7 @@ pub struct Instruction { } impl Instruction { - fn expect(self, count: u16) -> Result<(), Error> { + const fn expect(self, count: u16) -> Result<(), Error> { if self.wc == count { Ok(()) } else { @@ -105,7 +105,7 @@ impl Instruction { } impl crate::TypeInner { - fn can_comparison_sample(&self) -> bool { + const fn can_comparison_sample(&self) -> bool { match *self { crate::TypeInner::Image { class: @@ -151,7 +151,7 @@ impl LookupHelper for FastHashMap { } impl crate::ImageDimension { - fn required_coordinate_size(&self) -> Option { + const fn required_coordinate_size(&self) -> Option { match *self { crate::ImageDimension::D1 => None, crate::ImageDimension::D2 => Some(crate::VectorSize::Bi), @@ -217,7 +217,7 @@ impl Decoration { } } - fn resource_binding(&self) -> Option { + const fn resource_binding(&self) -> Option { match *self { Decoration { desc_set: Some(group), @@ -408,7 +408,7 @@ struct Body { impl Body { /// Creates a new empty `Body` with the specified `parent` - pub fn with_parent(parent: usize) -> Self { + pub const fn with_parent(parent: usize) -> Self { Body { parent, data: Vec::new(), diff --git a/src/front/spv/null.rs b/src/front/spv/null.rs index b0a8579a2..ca62b8454 100644 --- a/src/front/spv/null.rs +++ b/src/front/spv/null.rs @@ -1,7 +1,7 @@ use super::Error; use crate::arena::{Arena, Handle, UniqueArena}; -fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { +const fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { crate::ConstantInner::Scalar { width, value: match kind { diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/construction.rs index 7916caa62..281116d3f 100644 --- a/src/front/wgsl/construction.rs +++ b/src/front/wgsl/construction.rs @@ -41,7 +41,7 @@ enum ConstructorType { } impl ConstructorType { - fn to_type_resolution(&self) -> Option { + const fn to_type_resolution(&self) -> Option { Some(match *self { ConstructorType::Scalar { kind, width } => { TypeResolution::Value(TypeInner::Scalar { kind, width }) @@ -425,7 +425,8 @@ pub(super) fn parse_construction<'a>( ( Components::Many { components, - first_component_ty: &TypeInner::Scalar { kind, width }, + first_component_ty: + &TypeInner::Scalar { kind, width } | &TypeInner::Vector { kind, width, .. }, .. }, ConstructorType::PartialVector { size }, @@ -433,23 +434,7 @@ pub(super) fn parse_construction<'a>( | ( Components::Many { components, - first_component_ty: &TypeInner::Vector { kind, width, .. }, - .. - }, - ConstructorType::PartialVector { size }, - ) - | ( - Components::Many { - components, - first_component_ty: &TypeInner::Scalar { .. }, - .. - }, - ConstructorType::Vector { size, width, kind }, - ) - | ( - Components::Many { - components, - first_component_ty: &TypeInner::Vector { .. }, + first_component_ty: &TypeInner::Scalar { .. } | &TypeInner::Vector { .. }, .. }, ConstructorType::Vector { size, width, kind }, @@ -636,10 +621,13 @@ pub(super) fn parse_construction<'a>( } // Parameters are of the wrong type for vector or matrix constructor - (Components::Many { spans, .. }, ConstructorType::Vector { .. }) - | (Components::Many { spans, .. }, ConstructorType::Matrix { .. }) - | (Components::Many { spans, .. }, ConstructorType::PartialVector { .. }) - | (Components::Many { spans, .. }, ConstructorType::PartialMatrix { .. }) => { + ( + Components::Many { spans, .. }, + ConstructorType::Vector { .. } + | ConstructorType::Matrix { .. } + | ConstructorType::PartialVector { .. } + | ConstructorType::PartialMatrix { .. }, + ) => { return Err(Error::InvalidConstructorComponentType(spans[0].clone(), 0)); } }; diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 93286f588..140e4eab0 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -1,13 +1,5 @@ use super::{conv, Error, ExpectedToken, NumberType, Span, Token, TokenSpan}; -fn _consume_str<'a>(input: &'a str, what: &str) -> Option<&'a str> { - if input.starts_with(what) { - Some(&input[what.len()..]) - } else { - None - } -} - fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { let pos = input.find(|c| !what(c)).unwrap_or(input.len()); input.split_at(pos) @@ -17,8 +9,8 @@ fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { /// Returns whether the prefix was present and could therefore be skipped, /// the remaining str and the number of *bytes* skipped. pub fn try_skip_prefix<'a, 'b>(input: &'a str, prefix: &'b str) -> (bool, &'a str, usize) { - if input.starts_with(prefix) { - (true, &input[prefix.len()..], prefix.len()) + if let Some(rem) = input.strip_prefix(prefix) { + (true, rem, prefix.len()) } else { (false, input, 0) } @@ -194,12 +186,7 @@ fn consume_number(input: &str) -> (Token, &str) { NumberLexerState { hex, - digit_state: NLDigitState::DigitsThenDot, - .. - } - | NumberLexerState { - hex, - digit_state: NLDigitState::DigitAfterDot, + digit_state: NLDigitState::DigitsThenDot | NLDigitState::DigitAfterDot, .. } => match c { '0'..='9' => { @@ -231,11 +218,7 @@ fn consume_number(input: &str) -> (Token, &str) { }, NumberLexerState { - digit_state: NLDigitState::SignAfterExponent, - .. - } - | NumberLexerState { - digit_state: NLDigitState::DigitAfterExponent, + digit_state: NLDigitState::SignAfterExponent | NLDigitState::DigitAfterExponent, .. } => match c { '0'..='9' => { @@ -384,7 +367,7 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { let sub_input = chars.as_str(); match chars.next() { Some('>') => (Token::Arrow, chars.as_str()), - Some('0'..='9') | Some('.') => consume_number(input), + Some('0'..='9' | '.') => consume_number(input), Some('-') => (Token::DecrementOperation, chars.as_str()), Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), _ => (Token::Operation(cur), sub_input), @@ -440,14 +423,14 @@ pub(super) struct Lexer<'a> { } impl<'a> Lexer<'a> { - pub(super) fn new(input: &'a str) -> Self { + pub(super) const fn new(input: &'a str) -> Self { Lexer { input, source: input, } } - pub(super) fn _leftover_span(&self) -> Span { + pub(super) const fn _leftover_span(&self) -> Span { self.source.len() - self.input.len()..self.source.len() } @@ -477,11 +460,11 @@ impl<'a> Lexer<'a> { (token, rest) } - pub(super) fn current_byte_offset(&self) -> usize { + pub(super) const fn current_byte_offset(&self) -> usize { self.source.len() - self.input.len() } - pub(super) fn span_from(&self, offset: usize) -> Span { + pub(super) const fn span_from(&self, offset: usize) -> Span { offset..self.current_byte_offset() } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b78f9bd60..2ea486309 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -502,7 +502,7 @@ impl<'a> Error<'a> { } impl crate::StorageFormat { - fn to_wgsl(self) -> &'static str { + const fn to_wgsl(self) -> &'static str { use crate::StorageFormat as Sf; match self { Sf::R8Unorm => "r8unorm", @@ -1107,7 +1107,7 @@ struct TypedExpression { } impl TypedExpression { - fn non_reference(handle: Handle) -> TypedExpression { + const fn non_reference(handle: Handle) -> TypedExpression { TypedExpression { handle, is_reference: false, @@ -1121,8 +1121,7 @@ enum Composition { } impl Composition { - //TODO: could be `const fn` once MSRV allows - fn letter_component(letter: char) -> Option { + const fn letter_component(letter: char) -> Option { use crate::SwizzleComponent as Sc; match letter { 'x' | 'r' => Some(Sc::X), @@ -1234,7 +1233,7 @@ impl BindingParser { Ok(()) } - fn finish<'a>(self, span: Span) -> Result, Error<'a>> { + const fn finish<'a>(self, span: Span) -> Result, Error<'a>> { match ( self.location, self.built_in, @@ -2285,9 +2284,7 @@ impl Parser { self.pop_scope(lexer); expr } - token @ (Token::Word("true"), _) - | token @ (Token::Word("false"), _) - | token @ (Token::Number { .. }, _) => { + token @ (Token::Word("true" | "false") | Token::Number { .. }, _) => { let _ = lexer.next(); let const_handle = self.parse_const_expression_impl(token, lexer, None, ctx.types, ctx.constants)?; @@ -2512,7 +2509,7 @@ impl Parser { let span = NagaSpan::from(self.peek_scope(lexer)); TypedExpression::non_reference(ctx.expressions.append(expr, span)) } - Token::Operation('!') | Token::Operation('~') => { + Token::Operation('!' | '~') => { let _ = lexer.next(); let unloaded_expr = self.parse_unary_expression(lexer, ctx.reborrow())?; let expr = ctx.apply_load_rule(unloaded_expr); @@ -3175,7 +3172,7 @@ impl Parser { })) } - fn check_texture_sample_type( + const fn check_texture_sample_type( kind: crate::ScalarKind, width: u8, span: Span, @@ -3183,7 +3180,7 @@ impl Parser { use crate::ScalarKind::*; // Validate according to https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type match (kind, width) { - (Float, 4) | (Sint, 4) | (Uint, 4) => Ok(()), + (Float | Sint | Uint, 4) => Ok(()), _ => Err(Error::BadTextureSampleType { span, kind, width }), } } @@ -3303,7 +3300,7 @@ impl Parser { .expressions .append(crate::Expression::Binary { op, left, right }, span.into()) } - token @ (Token::IncrementOperation, _) | token @ (Token::DecrementOperation, _) => { + token @ (Token::IncrementOperation | Token::DecrementOperation, _) => { let op = match token.0 { Token::IncrementOperation => Bo::Add, Token::DecrementOperation => Bo::Subtract, @@ -4460,7 +4457,7 @@ pub struct StringErrorBuffer { } impl StringErrorBuffer { - pub fn new() -> Self { + pub const fn new() -> Self { Self { buf: Vec::new() } } diff --git a/src/lib.rs b/src/lib.rs index f82e88b4b..d5d4d59c0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -184,23 +184,19 @@ tree. [`ModuleInfo`]: valid::ModuleInfo */ -// TODO: use `strip_prefix` instead when Rust 1.45 <= MSRV #![allow( - renamed_and_removed_lints, - unknown_lints, // requires Rust 1.51 clippy::new_without_default, clippy::unneeded_field_pattern, clippy::match_like_matches_macro, - clippy::manual_strip, - clippy::if_same_then_else, - clippy::unknown_clippy_lints, + clippy::if_same_then_else )] #![warn( trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_qualifications, - clippy::pattern_type_mismatch + clippy::pattern_type_mismatch, + clippy::missing_const_for_fn )] #![deny(clippy::panic)] diff --git a/src/proc/index.rs b/src/proc/index.rs index b0939b0e7..643cb2432 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -141,8 +141,9 @@ impl BoundsCheckPolicies { info: &valid::FunctionInfo, ) -> BoundsCheckPolicy { match info[access].ty.inner_with(types).pointer_space() { - Some(crate::AddressSpace::Storage { access: _ }) - | Some(crate::AddressSpace::Uniform) => self.buffer, + Some(crate::AddressSpace::Storage { access: _ } | crate::AddressSpace::Uniform) => { + self.buffer + } // This covers other address spaces, but also accessing vectors and // matrices by value, where no pointer is involved. _ => self.index, diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index f03823a81..1b517e434 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -14,7 +14,7 @@ pub struct TypeLayout { impl TypeLayout { /// Produce the stride as if this type is a base of an array. - pub fn to_stride(&self) -> u32 { + pub const fn to_stride(&self) -> u32 { Layouter::round_up(self.alignment, self.size) } } @@ -63,7 +63,7 @@ pub struct LayoutError { } impl LayoutErrorInner { - fn with(self, ty: Handle) -> LayoutError { + const fn with(self, ty: Handle) -> LayoutError { LayoutError { ty, inner: self } } } @@ -75,7 +75,7 @@ impl Layouter { } /// Round `offset` up to the nearest `alignment` boundary. - pub fn round_up(alignment: Alignment, offset: u32) -> u32 { + pub const fn round_up(alignment: Alignment, offset: u32) -> u32 { match offset & (alignment.get() - 1) { 0 => offset, other => offset + alignment.get() - other, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 65fb06fd2..eab9c53da 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -57,7 +57,7 @@ impl From for super::ScalarKind { } impl super::ScalarValue { - pub fn scalar_kind(&self) -> super::ScalarKind { + pub const fn scalar_kind(&self) -> super::ScalarKind { match *self { Self::Uint(_) => super::ScalarKind::Uint, Self::Sint(_) => super::ScalarKind::Sint, @@ -70,7 +70,7 @@ impl super::ScalarValue { pub const POINTER_SPAN: u32 = 4; impl super::TypeInner { - pub fn scalar_kind(&self) -> Option { + pub const fn scalar_kind(&self) -> Option { match *self { super::TypeInner::Scalar { kind, .. } | super::TypeInner::Vector { kind, .. } => { Some(kind) @@ -80,7 +80,7 @@ impl super::TypeInner { } } - pub fn pointer_space(&self) -> Option { + pub const fn pointer_space(&self) -> Option { match *self { Self::Pointer { space, .. } => Some(space), Self::ValuePointer { space, .. } => Some(space), @@ -215,7 +215,7 @@ impl super::AddressSpace { } impl super::MathFunction { - pub fn argument_count(&self) -> usize { + pub const fn argument_count(&self) -> usize { match *self { // comparison Self::Abs => 1, @@ -299,7 +299,7 @@ impl super::MathFunction { impl crate::Expression { /// Returns true if the expression is considered emitted at the start of a function. - pub fn needs_pre_emit(&self) -> bool { + pub const fn needs_pre_emit(&self) -> bool { match *self { Self::Constant(_) | Self::FunctionArgument(_) @@ -360,7 +360,7 @@ impl crate::Function { } impl crate::SampleLevel { - pub fn implicit_derivatives(&self) -> bool { + pub const fn implicit_derivatives(&self) -> bool { match *self { Self::Auto | Self::Bias(_) => true, Self::Zero | Self::Exact(_) | Self::Gradient { .. } => false, @@ -400,7 +400,7 @@ impl crate::Constant { } impl crate::Binding { - pub fn to_built_in(&self) -> Option { + pub const fn to_built_in(&self) -> Option { match *self { crate::Binding::BuiltIn(built_in) => Some(built_in), Self::Location { .. } => None, @@ -435,7 +435,7 @@ impl std::hash::Hash for crate::ScalarValue { impl super::SwizzleComponent { pub const XYZW: [Self; 4] = [Self::X, Self::Y, Self::Z, Self::W]; - pub fn index(&self) -> u32 { + pub const fn index(&self) -> u32 { match *self { Self::X => 0, Self::Y => 1, @@ -443,7 +443,7 @@ impl super::SwizzleComponent { Self::W => 3, } } - pub fn from_index(idx: u32) -> Self { + pub const fn from_index(idx: u32) -> Self { match idx { 0 => Self::X, 1 => Self::Y, @@ -454,14 +454,14 @@ impl super::SwizzleComponent { } impl super::ImageClass { - pub fn is_multisampled(self) -> bool { + pub const fn is_multisampled(self) -> bool { match self { crate::ImageClass::Sampled { multi, .. } | crate::ImageClass::Depth { multi } => multi, crate::ImageClass::Storage { .. } => false, } } - pub fn is_mipmapped(self) -> bool { + pub const fn is_mipmapped(self) -> bool { match self { crate::ImageClass::Sampled { multi, .. } | crate::ImageClass::Depth { multi } => !multi, crate::ImageClass::Storage { .. } => false, diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index 83034a82a..5915616cc 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -28,17 +28,15 @@ pub fn ensure_block_returns(block: &mut crate::Block) { } } } - Some(&mut S::Emit(_)) - | Some(&mut S::Break) - | Some(&mut S::Continue) - | Some(&mut S::Return { .. }) - | Some(&mut S::Kill) => (), - Some(&mut S::Loop { .. }) - | Some(&mut S::Store { .. }) - | Some(&mut S::ImageStore { .. }) - | Some(&mut S::Call { .. }) - | Some(&mut S::Atomic { .. }) - | Some(&mut S::Barrier(_)) + Some(&mut (S::Emit(_) | S::Break | S::Continue | S::Return { .. } | S::Kill)) => (), + Some( + &mut (S::Loop { .. } + | S::Store { .. } + | S::ImageStore { .. } + | S::Call { .. } + | S::Atomic { .. } + | S::Barrier(_)), + ) | None => block.push(S::Return { value: None }, Default::default()), } } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index f2ad51805..58e67b019 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -97,7 +97,7 @@ pub enum TypeResolution { } impl TypeResolution { - pub fn handle(&self) -> Option> { + pub const fn handle(&self) -> Option> { match *self { Self::Handle(handle) => Some(handle), Self::Value(_) => None, @@ -149,7 +149,7 @@ impl Clone for TypeResolution { } impl crate::ConstantInner { - pub fn resolve_type(&self) -> TypeResolution { + pub const fn resolve_type(&self) -> TypeResolution { match *self { Self::Scalar { width, ref value } => TypeResolution::Value(crate::TypeInner::Scalar { kind: value.scalar_kind(), diff --git a/src/span.rs b/src/span.rs index 000d09c32..0c60ee005 100644 --- a/src/span.rs +++ b/src/span.rs @@ -14,7 +14,7 @@ impl Span { /// Creates a new `Span` from a range of byte indices /// /// Note: end is exclusive, it doesn't belong to the `Span` - pub fn new(start: u32, end: u32) -> Self { + pub const fn new(start: u32, end: u32) -> Self { Span { start, end } } @@ -111,7 +111,7 @@ where impl WithSpan { /// Create a new [`WithSpan`] from an [`Error`], containing no spans. - pub fn new(inner: E) -> Self { + pub const fn new(inner: E) -> Self { Self { inner, #[cfg(feature = "span")] @@ -120,11 +120,12 @@ impl WithSpan { } /// Reverse of [`Self::new`], discards span information and returns an inner error. + #[allow(clippy::missing_const_for_fn)] // ignore due to requirement of #![feature(const_precise_live_drops)] pub fn into_inner(self) -> E { self.inner } - pub fn as_inner(&self) -> &E { + pub const fn as_inner(&self) -> &E { &self.inner } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index d9c27d451..cb75ddb1e 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -50,7 +50,7 @@ pub struct Uniformity { } impl Uniformity { - fn new() -> Self { + const fn new() -> Self { Uniformity { non_uniform_result: None, requirements: UniformityRequirements::empty(), @@ -94,7 +94,7 @@ impl ops::BitOr for FunctionUniformity { } impl FunctionUniformity { - fn new() -> Self { + const fn new() -> Self { FunctionUniformity { result: Uniformity::new(), exit: ExitFlags::empty(), @@ -102,7 +102,7 @@ impl FunctionUniformity { } /// Returns a disruptor based on the stored exit flags, if any. - fn exit_disruptor(&self) -> Option { + const fn exit_disruptor(&self) -> Option { if self.exit.contains(ExitFlags::MAY_RETURN) { Some(UniformityDisruptor::Return) } else if self.exit.contains(ExitFlags::MAY_KILL) { @@ -146,7 +146,7 @@ pub struct ExpressionInfo { } impl ExpressionInfo { - fn new() -> Self { + const fn new() -> Self { ExpressionInfo { uniformity: Uniformity::new(), ref_count: 0, @@ -169,7 +169,7 @@ enum GlobalOrArgument { } impl crate::Expression { - fn to_global_or_argument(&self) -> Result { + const fn to_global_or_argument(&self) -> Result { Ok(match *self { crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), @@ -248,10 +248,10 @@ pub struct FunctionInfo { } impl FunctionInfo { - pub fn global_variable_count(&self) -> usize { + pub const fn global_variable_count(&self) -> usize { self.global_uses.len() } - pub fn expression_count(&self) -> usize { + pub const fn expression_count(&self) -> usize { self.expressions.len() } pub fn dominates_global_use(&self, other: &Self) -> bool { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index bde272dfe..bfa3b0b83 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -173,11 +173,7 @@ impl super::Validator { match *resolver.resolve(index)? { //TODO: only allow one of these Ti::Scalar { - kind: Sk::Sint, - width: _, - } - | Ti::Scalar { - kind: Sk::Uint, + kind: Sk::Sint | Sk::Uint, width: _, } => {} ref other => { @@ -633,8 +629,7 @@ impl super::Validator { use crate::UnaryOperator as Uo; let inner = resolver.resolve(expr)?; match (op, inner.scalar_kind()) { - (_, Some(Sk::Sint)) - | (_, Some(Sk::Bool)) + (_, Some(Sk::Sint | Sk::Bool)) //TODO: restrict Negate for bools? | (Uo::Negate, Some(Sk::Float)) | (Uo::Not, Some(Sk::Uint)) => {} @@ -667,7 +662,7 @@ impl super::Validator { }, Bo::Multiply => { let kind_match = match left_inner.scalar_kind() { - Some(Sk::Uint) | Some(Sk::Sint) | Some(Sk::Float) => true, + Some(Sk::Uint | Sk::Sint | Sk::Float) => true, Some(Sk::Bool) | None => false, }; let types_match = match (left_inner, right_inner) { @@ -1070,10 +1065,9 @@ impl super::Validator { }; match *arg_ty { Ti::Vector { - kind: Sk::Float, .. - } - | Ti::Vector { kind: Sk::Sint, .. } - | Ti::Vector { kind: Sk::Uint, .. } => {} + kind: Sk::Float | Sk::Sint | Sk::Uint, + .. + } => {} _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } if arg1_ty != arg_ty { @@ -1250,10 +1244,14 @@ impl super::Validator { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { - Ti::Scalar { kind: Sk::Sint, .. } - | Ti::Scalar { kind: Sk::Uint, .. } - | Ti::Vector { kind: Sk::Sint, .. } - | Ti::Vector { kind: Sk::Uint, .. } => {} + Ti::Scalar { + kind: Sk::Sint | Sk::Uint, + .. + } + | Ti::Vector { + kind: Sk::Sint | Sk::Uint, + .. + } => {} _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } } @@ -1263,10 +1261,14 @@ impl super::Validator { _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; match *arg_ty { - Ti::Scalar { kind: Sk::Sint, .. } - | Ti::Scalar { kind: Sk::Uint, .. } - | Ti::Vector { kind: Sk::Sint, .. } - | Ti::Vector { kind: Sk::Uint, .. } => {} + Ti::Scalar { + kind: Sk::Sint | Sk::Uint, + .. + } + | Ti::Vector { + kind: Sk::Sint | Sk::Uint, + .. + } => {} _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } if arg1_ty != arg_ty { @@ -1303,10 +1305,14 @@ impl super::Validator { _ => return Err(ExpressionError::WrongArgumentCount(fun)), }; match *arg_ty { - Ti::Scalar { kind: Sk::Sint, .. } - | Ti::Scalar { kind: Sk::Uint, .. } - | Ti::Vector { kind: Sk::Sint, .. } - | Ti::Vector { kind: Sk::Uint, .. } => {} + Ti::Scalar { + kind: Sk::Sint | Sk::Uint, + .. + } + | Ti::Vector { + kind: Sk::Sint | Sk::Uint, + .. + } => {} _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } match *arg1_ty { diff --git a/src/valid/function.rs b/src/valid/function.rs index 4c1262ec7..39f82ba4b 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -193,7 +193,7 @@ impl<'a> BlockContext<'a> { } } - fn with_abilities(&self, abilities: ControlFlowAbility) -> Self { + const fn with_abilities(&self, abilities: ControlFlowAbility) -> Self { BlockContext { abilities, ..*self } } @@ -845,9 +845,11 @@ impl super::Validator { FunctionError::from(err).with_span_handle(argument.ty, &module.types) })?; match ty.inner.pointer_space() { - Some(crate::AddressSpace::Private) - | Some(crate::AddressSpace::Function) - | Some(crate::AddressSpace::WorkGroup) + Some( + crate::AddressSpace::Private + | crate::AddressSpace::Function + | crate::AddressSpace::WorkGroup, + ) | None => {} Some(other) => { return Err(FunctionError::InvalidArgumentPointerSpace { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 89314294f..8e0227408 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -190,7 +190,7 @@ pub enum ValidationError { impl crate::TypeInner { #[cfg(feature = "validate")] - fn is_sized(&self) -> bool { + const fn is_sized(&self) -> bool { match *self { Self::Scalar { .. } | Self::Vector { .. } @@ -209,7 +209,7 @@ impl crate::TypeInner { /// Return the `ImageDimension` for which `self` is an appropriate coordinate. #[cfg(feature = "validate")] - fn image_storage_coordinates(&self) -> Option { + const fn image_storage_coordinates(&self) -> Option { match *self { Self::Scalar { kind: crate::ScalarKind::Sint, diff --git a/src/valid/type.rs b/src/valid/type.rs index 236fde99a..f4f47aec5 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -163,7 +163,7 @@ pub(super) struct TypeInfo { } impl TypeInfo { - fn dummy() -> Self { + const fn dummy() -> Self { TypeInfo { flags: TypeFlags::empty(), uniform_layout: Ok(None), @@ -171,7 +171,7 @@ impl TypeInfo { } } - fn new(flags: TypeFlags, align: u32) -> Self { + const fn new(flags: TypeFlags, align: u32) -> Self { let alignment = Alignment::new(align); TypeInfo { flags, @@ -182,7 +182,7 @@ impl TypeInfo { } impl super::Validator { - pub(super) fn check_width(&self, kind: crate::ScalarKind, width: crate::Bytes) -> bool { + pub(super) const fn check_width(&self, kind: crate::ScalarKind, width: crate::Bytes) -> bool { match kind { crate::ScalarKind::Bool => width == crate::BOOL_WIDTH, crate::ScalarKind::Float => { From dc075e66e3d54b0a4f2650c021271eba2ee71177 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Sun, 17 Apr 2022 15:56:54 +0200 Subject: [PATCH 1693/2212] [wgsl-in] Update reserved keywords (#1847) --- src/keywords/wgsl.rs | 402 +++++++++++++++--- tests/in/access.wgsl | 12 +- tests/in/bounds-check-image-restrict.wgsl | 8 +- tests/in/bounds-check-image-rzsw.wgsl | 8 +- tests/in/extra.wgsl | 8 +- tests/in/image.wgsl | 4 +- tests/in/interface.wgsl | 10 +- tests/in/interpolate.wgsl | 24 +- tests/in/padding.wgsl | 4 +- tests/in/push-constants.wgsl | 4 +- tests/in/shadow.wgsl | 26 +- tests/in/skybox.wgsl | 4 +- tests/out/glsl/access.atomics.Compute.glsl | 2 +- tests/out/glsl/access.foo_frag.Fragment.glsl | 6 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 8 +- ...lsl => image.texture_sample.Fragment.glsl} | 0 ...e.texture_sample_comparison.Fragment.glsl} | 0 .../glsl/interpolate.frag_main.Fragment.glsl | 4 +- .../glsl/interpolate.vert_main.Vertex.glsl | 28 +- .../glsl/push-constants.main.Fragment.glsl | 4 +- tests/out/glsl/shadow.fs_main.Fragment.glsl | 8 +- ...adow.fs_main_without_storage.Fragment.glsl | 8 +- tests/out/glsl/shadow.vs_main.Vertex.glsl | 10 +- tests/out/glsl/skybox.fs_main.Fragment.glsl | 4 +- tests/out/hlsl/access.hlsl | 4 +- tests/out/hlsl/image.hlsl | 4 +- tests/out/hlsl/image.hlsl.config | 2 +- tests/out/hlsl/interface.hlsl | 18 +- tests/out/hlsl/interpolate.hlsl | 36 +- tests/out/hlsl/padding.hlsl | 4 +- tests/out/hlsl/shadow.hlsl | 26 +- tests/out/hlsl/skybox.hlsl | 4 +- tests/out/msl/access.msl | 12 +- tests/out/msl/bounds-check-image-restrict.msl | 8 +- tests/out/msl/bounds-check-image-rzsw.msl | 8 +- tests/out/msl/extra.msl | 8 +- tests/out/msl/image.msl | 12 +- tests/out/msl/interface.msl | 16 +- tests/out/msl/interpolate.msl | 36 +- tests/out/msl/padding.msl | 4 +- tests/out/msl/shadow.msl | 26 +- tests/out/msl/skybox.msl | 4 +- tests/out/spv/access.spvasm | 2 +- .../spv/bounds-check-image-restrict.spvasm | 4 +- tests/out/spv/bounds-check-image-rzsw.spvasm | 4 +- tests/out/spv/image.spvasm | 8 +- tests/out/spv/interpolate.spvasm | 14 +- tests/out/spv/padding.spvasm | 2 +- tests/out/spv/shadow.spvasm | 2 +- tests/out/wgsl/access.wgsl | 12 +- tests/out/wgsl/extra.wgsl | 8 +- tests/out/wgsl/image.wgsl | 4 +- tests/out/wgsl/interface.wgsl | 10 +- tests/out/wgsl/interpolate.wgsl | 24 +- tests/out/wgsl/padding.wgsl | 4 +- tests/out/wgsl/shadow.wgsl | 26 +- tests/out/wgsl/skybox.wgsl | 4 +- tests/wgsl-errors.rs | 26 +- 58 files changed, 637 insertions(+), 345 deletions(-) rename tests/out/glsl/{image.sample.Fragment.glsl => image.texture_sample.Fragment.glsl} (100%) rename tests/out/glsl/{image.sample_comparison.Fragment.glsl => image.texture_sample_comparison.Fragment.glsl} (100%) diff --git a/src/keywords/wgsl.rs b/src/keywords/wgsl.rs index 2ceb88300..36a8a55a1 100644 --- a/src/keywords/wgsl.rs +++ b/src/keywords/wgsl.rs @@ -1,18 +1,18 @@ /*! -Reserved keywords for [WGSL][wgsl] (WebGPU Shading Language). +Keywords for [WGSL][wgsl] (WebGPU Shading Language). [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html */ // https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary -/// Reserved keywords. pub const RESERVED: &[&str] = &[ - // type-defining keywords + // type-defining "array", "atomic", "bool", - "float32", - "int32", + "f32", + "f16", + "i32", "mat2x2", "mat2x3", "mat2x4", @@ -22,7 +22,8 @@ pub const RESERVED: &[&str] = &[ "mat4x2", "mat4x3", "mat4x4", - "pointer", + "override", + "ptr", "sampler", "sampler_comparison", "struct", @@ -42,21 +43,20 @@ pub const RESERVED: &[&str] = &[ "texture_depth_cube", "texture_depth_cube_array", "texture_depth_multisampled_2d", - "uint32", + "u32", "vec2", "vec3", "vec4", - // other keywords + // other "bitcast", - "block", "break", "case", + "const", "continue", "continuing", "default", "discard", "else", - "else_if", "enable", "fallthrough", "false", @@ -67,8 +67,6 @@ pub const RESERVED: &[&str] = &[ "let", "loop", "private", - "read", - "read_write", "return", "storage", "switch", @@ -76,66 +74,360 @@ pub const RESERVED: &[&str] = &[ "type", "uniform", "var", + "while", "workgroup", - "write", - // image format keywords - "r8unorm", - "r8snorm", - "r8uint", - "r8sint", - "r16uint", - "r16sint", - "r16float", - "rg8unorm", - "rg8snorm", - "rg8uint", - "rg8sint", - "r32uint", - "r32sint", - "r32float", - "rg16uint", - "rg16sint", - "rg16float", - "rgba8unorm", - "rgba8unorm_srgb", - "rgba8snorm", - "rgba8uint", - "rgba8sint", - "bgra8unorm", - "bgra8unorm_srgb", - "rgb10a2unorm", - "rg11b10float", - "rg32uint", - "rg32sint", - "rg32float", - "rgba16uint", - "rgba16sint", - "rgba16float", - "rgba32uint", - "rgba32sint", - "rgba32float", - // reserved keywords + // reserved + "AppendStructuredBuffer", + "BlendState", + "Buffer", + "ByteAddressBuffer", + "CompileShader", + "ComputeShader", + "ConsumeStructuredBuffer", + "DepthStencilState", + "DepthStencilView", + "DomainShader", + "GeometryShader", + "Hullshader", + "InputPatch", + "LineStream", + "NULL", + "OutputPatch", + "PixelShader", + "PointStream", + "RWBuffer", + "RWByteAddressBuffer", + "RWStructuredBuffer", + "RWTexture1D", + "RWTexture1DArray", + "RWTexture2D", + "RWTexture2DArray", + "RWTexture3D", + "RasterizerState", + "RenderTargetView", + "SamplerComparisonState", + "SamplerState", + "Self", + "StructuredBuffer", + "Texture1D", + "Texture1DArray", + "Texture2D", + "Texture2DArray", + "Texture2DMS", + "Texture2DMSArray", + "Texture3D", + "TextureCube", + "TextureCubeArray", + "TriangleStream", + "VertexShader", + "abstract", + "active", + "alignas", + "alignof", + "as", "asm", + "asm_fragment", + "async", + "atomic_uint", + "attribute", + "auto", + "await", + "become", "bf16", - "const", + "buffer", + "cast", + "catch", + "cbuffer", + "centroid", + "char", + "class", + "co_await", + "co_return", + "co_yield", + "coherent", + "column_major", + "common", + "compile", + "compile_fragment", + "concept", + "const_cast", + "consteval", + "constexpr", + "constinit", + "crate", + "debugger", + "decltype", + "delete", + "demote", + "demote_to_helper", "do", + "dword", + "dynamic_cast", "enum", - "f16", + "explicit", + "export", + "extends", + "extern", + "external", "f64", + "filter", + "final", + "finally", + "fixed", + "flat", + "friend", + "from", + "fvec2", + "fvec3", + "fvec4", + "fxgroup", + "get", + "goto", + "groupshared", "handle", - "i8", + "highp", + "hvec2", + "hvec3", + "hvec4", "i16", "i64", + "i8", + "iimage1D", + "iimage1DArray", + "iimage2D", + "iimage2DArray", + "iimage2DMS", + "iimage2DMSArray", + "iimage2DRect", + "iimage3D", + "iimageBuffer", + "iimageCube", + "iimageCubeArray", + "image1D", + "image1DArray", + "image2D", + "image2DArray", + "image2DMS", + "image2DMSArray", + "image2DRect", + "image3D", + "imageBuffer", + "imageCube", + "imageCubeArray", + "impl", + "implements", + "import", + "in", + "inline", + "inout", + "input", + "instanceof", + "interface", + "invariant", + "isampler1D", + "isampler1DArray", + "isampler2D", + "isampler2DArray", + "isampler2DMS", + "isampler2DMSArray", + "isampler2DRect", + "isampler3D", + "isamplerBuffer", + "isamplerCube", + "isamplerCubeArray", + "isubpassInput", + "isubpassInputMS", + "itexture1D", + "itexture1DArray", + "itexture2D", + "itexture2DArray", + "itexture2DMS", + "itexture2DMSArray", + "itexture2DRect", + "itexture3D", + "itextureBuffer", + "itextureCube", + "itextureCubeArray", + "layout", + "line", + "lineadj", + "linear", + "lowp", + "macro", + "macro_rules", "mat", + "match", + "matrix", + "mediump", + "meta", + "mod", + "module", + "move", + "mut", + "mutable", + "namespace", + "new", + "nil", + "noexcept", + "noinline", + "nointerpolation", + "noperspective", + "null", + "nullptr", + "of", + "operator", + "out", + "output", + "package", + "packoffset", + "partition", + "pass", + "patch", + "pixelfragment", + "point", + "precise", + "precision", "premerge", + "priv", + "protected", + "pub", + "public", + "readonly", + "ref", "regardless", + "register", + "reinterpret_cast", + "requires", + "resource", + "restrict", + "row_major", + "samper", + "sample", + "sampler1D", + "sampler1DArray", + "sampler1DArrayShadow", + "sampler1DShadow", + "sampler2D", + "sampler2DArray", + "sampler2DArrayShadow", + "sampler2DMS", + "sampler2DMSArray", + "sampler2DRect", + "sampler2DRectShadow", + "sampler2DShadow", + "sampler3D", + "sampler3DRect", + "samplerBuffer", + "samplerCube", + "samplerCubeArray", + "samplerCubeArrayShadow", + "samplerCubeShadow", + "samplerShadow", + "self", + "set", + "shared", + "signed", + "sizeof", + "smooth", + "snorm", + "stateblock", + "stateblock_state", + "static", + "static_assert", + "static_cast", + "std", + "string", + "subpassInput", + "subpassInputMS", + "subroutine", + "super", + "superp", + "target", + "tbuffer", + "technique", + "technique10", + "technique11", + "template", + "texture", + "texture1D", + "texture1DArray", + "texture2D", + "texture2DArray", + "texture2DMS", + "texture2DMSArray", + "texture2DRect", + "texture3D", + "textureBuffer", + "textureCube", + "textureCubeArray", + "this", + "thread_local", + "throw", + "trait", + "triangle", + "triangleadj", + "try", "typedef", - "u8", + "typeid", + "typename", + "typeof", "u16", "u64", + "u8", + "uimage1D", + "uimage1DArray", + "uimage2D", + "uimage2DArray", + "uimage2DMS", + "uimage2DMSArray", + "uimage2DRect", + "uimage3D", + "uimageBuffer", + "uimageCube", + "uimageCubeArray", + "union", "unless", + "unorm", + "unsafe", + "unsigned", + "unsized", + "usampler1D", + "usampler1DArray", + "usampler2D", + "usampler2DArray", + "usampler2DMS", + "usampler2DMSArray", + "usampler2DRect", + "usampler3D", + "usamplerBuffer", + "usamplerCube", + "usamplerCubeArray", + "use", "using", + "usubpassInput", + "usubpassInputMS", + "utexture1D", + "utexture1DArray", + "utexture2D", + "utexture2DArray", + "utexture2DMS", + "utexture2DMSArray", + "utexture2DRect", + "utexture3D", + "utextureBuffer", + "utextureCube", + "utextureCubeArray", + "varying", "vec", + "vector", + "vertexfragment", + "virtual", "void", - "while", + "volatile", + "wchar_t", + "wgsl", + "where", + "with", + "writeonly", + "yield", ]; diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 64e91c944..4ad05f201 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -5,7 +5,7 @@ struct AlignedWrapper { } struct Bar { - matrix: mat4x3, + _matrix: mat4x3, matrix_array: array, 2>, atom: atomic, arr: array, 2>, @@ -68,10 +68,10 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { test_matrix_within_struct_accesses(); // test storage loads - let matrix = bar.matrix; + let _matrix = bar._matrix; let arr = bar.arr; let index = 3u; - let b = bar.matrix[index].x; + let b = bar._matrix[index].x; let a = bar.data[arrayLength(&bar.data) - 2u].value; // test pointer types @@ -85,14 +85,14 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var _ = test_arr_as_arg(array, 5>()); - return vec4(matrix * vec4(vec4(value)), 2.0); + return vec4(_matrix * vec4(vec4(value)), 2.0); } @fragment fn foo_frag() -> @location(0) vec4 { // test storage stores - bar.matrix[1].z = 1.0; - bar.matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); + bar._matrix[1].z = 1.0; + bar._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); bar.arr = array, 2>(vec2(0u), vec2(1u)); bar.data[1].value = 1; diff --git a/tests/in/bounds-check-image-restrict.wgsl b/tests/in/bounds-check-image-restrict.wgsl index d30845291..3be562ff2 100644 --- a/tests/in/bounds-check-image-restrict.wgsl +++ b/tests/in/bounds-check-image-restrict.wgsl @@ -29,8 +29,8 @@ fn test_textureLoad_3d(coords: vec3, level: i32) -> vec4 { @group(0) @binding(0) var image_multisampled_2d: texture_multisampled_2d; -fn test_textureLoad_multisampled_2d(coords: vec2, sample: i32) -> vec4 { - return textureLoad(image_multisampled_2d, coords, sample); +fn test_textureLoad_multisampled_2d(coords: vec2, _sample: i32) -> vec4 { + return textureLoad(image_multisampled_2d, coords, _sample); } @group(0) @binding(0) @@ -50,8 +50,8 @@ fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> @group(0) @binding(0) var image_depth_multisampled_2d: texture_depth_multisampled_2d; -fn test_textureLoad_depth_multisampled_2d(coords: vec2, sample: i32) -> f32 { - return textureLoad(image_depth_multisampled_2d, coords, sample); +fn test_textureLoad_depth_multisampled_2d(coords: vec2, _sample: i32) -> f32 { + return textureLoad(image_depth_multisampled_2d, coords, _sample); } @group(0) @binding(0) diff --git a/tests/in/bounds-check-image-rzsw.wgsl b/tests/in/bounds-check-image-rzsw.wgsl index d30845291..3be562ff2 100644 --- a/tests/in/bounds-check-image-rzsw.wgsl +++ b/tests/in/bounds-check-image-rzsw.wgsl @@ -29,8 +29,8 @@ fn test_textureLoad_3d(coords: vec3, level: i32) -> vec4 { @group(0) @binding(0) var image_multisampled_2d: texture_multisampled_2d; -fn test_textureLoad_multisampled_2d(coords: vec2, sample: i32) -> vec4 { - return textureLoad(image_multisampled_2d, coords, sample); +fn test_textureLoad_multisampled_2d(coords: vec2, _sample: i32) -> vec4 { + return textureLoad(image_multisampled_2d, coords, _sample); } @group(0) @binding(0) @@ -50,8 +50,8 @@ fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> @group(0) @binding(0) var image_depth_multisampled_2d: texture_depth_multisampled_2d; -fn test_textureLoad_depth_multisampled_2d(coords: vec2, sample: i32) -> f32 { - return textureLoad(image_depth_multisampled_2d, coords, sample); +fn test_textureLoad_depth_multisampled_2d(coords: vec2, _sample: i32) -> f32 { + return textureLoad(image_depth_multisampled_2d, coords, _sample); } @group(0) @binding(0) diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index ef68f4aa8..5ce69c14f 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -10,10 +10,10 @@ struct FragmentIn { } @fragment -fn main(in: FragmentIn) -> @location(0) vec4 { - if in.primitive_index == pc.index { - return in.color; +fn main(_in: FragmentIn) -> @location(0) vec4 { + if _in.primitive_index == pc.index { + return _in.color; } else { - return vec4(vec3(1.0) - in.color.rgb, in.color.a); + return vec4(vec3(1.0) - _in.color.rgb, _in.color.a); } } diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index cc7746ea4..e1fb11a40 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -97,7 +97,7 @@ fn levels_queries() -> @builtin(position) vec4 { var sampler_reg: sampler; @fragment -fn sample() -> @location(0) vec4 { +fn texture_sample() -> @location(0) vec4 { let tc = vec2(0.5); let level = 2.3; let s1d = textureSample(image_1d, sampler_reg, tc.x); @@ -117,7 +117,7 @@ var image_2d_depth: texture_depth_2d; var image_cube_depth: texture_depth_cube; @fragment -fn sample_comparison() -> @location(0) f32 { +fn texture_sample_comparison() -> @location(0) f32 { let tc = vec2(0.5); let dref = 0.5; let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc, dref); diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index 9bf713199..e4316a244 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -2,7 +2,7 @@ struct VertexOutput { @builtin(position) @invariant position: vec4, - @location(1) varying: f32, + @location(1) _varying: f32, } @vertex @@ -23,17 +23,17 @@ struct FragmentOutput { @fragment fn fragment( - in: VertexOutput, + _in: VertexOutput, @builtin(front_facing) front_facing: bool, @builtin(sample_index) sample_index: u32, @builtin(sample_mask) sample_mask: u32, ) -> FragmentOutput { let mask = sample_mask & (1u << sample_index); let color = select(0.0, 1.0, front_facing); - return FragmentOutput(in.varying, mask, color); + return FragmentOutput(_in._varying, mask, color); } -var output: array; +var _output: array; @compute @workgroup_size(1) fn compute( @@ -43,7 +43,7 @@ fn compute( @builtin(workgroup_id) wg_id: vec3, @builtin(num_workgroups) num_wgs: vec3, ) { - output[0] = global_id.x + local_id.x + local_index + wg_id.x + num_wgs.x; + _output[0] = global_id.x + local_id.x + local_index + wg_id.x + num_wgs.x; } struct Input1 { diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index 071891ee7..6b8837903 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -2,8 +2,8 @@ struct FragmentInput { @builtin(position) position: vec4, - @location(0) @interpolate(flat) flat : u32, - @location(1) @interpolate(linear) linear : f32, + @location(0) @interpolate(flat) _flat : u32, + @location(1) @interpolate(linear) _linear : f32, @location(2) @interpolate(linear, centroid) linear_centroid : vec2, @location(3) @interpolate(linear, sample) linear_sample : vec3, @location(4) @interpolate(perspective) perspective : vec4, @@ -13,18 +13,18 @@ struct FragmentInput { @vertex fn vert_main() -> FragmentInput { - var out: FragmentInput; + var _out: FragmentInput; - out.position = vec4(2.0, 4.0, 5.0, 6.0); - out.flat = 8u; - out.linear = 27.0; - out.linear_centroid = vec2(64.0, 125.0); - out.linear_sample = vec3(216.0, 343.0, 512.0); - out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); - out.perspective_centroid = 2197.0; - out.perspective_sample = 2744.0; + _out.position = vec4(2.0, 4.0, 5.0, 6.0); + _out._flat = 8u; + _out._linear = 27.0; + _out.linear_centroid = vec2(64.0, 125.0); + _out.linear_sample = vec3(216.0, 343.0, 512.0); + _out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + _out.perspective_centroid = 2197.0; + _out.perspective_sample = 2744.0; - return out; + return _out; } @fragment diff --git a/tests/in/padding.wgsl b/tests/in/padding.wgsl index 13331edf8..24c764c17 100644 --- a/tests/in/padding.wgsl +++ b/tests/in/padding.wgsl @@ -18,7 +18,7 @@ struct Test3 { } @group(0) @binding(0) -var input: Test; +var input1: Test; @group(0) @binding(1) var input2: Test2; @@ -29,5 +29,5 @@ var input3: Test3; @vertex fn vertex() -> @builtin(position) vec4 { - return vec4(1.0) * input.b * input2.b * input3.b; + return vec4(1.0) * input1.b * input2.b * input3.b; } diff --git a/tests/in/push-constants.wgsl b/tests/in/push-constants.wgsl index cc8c4ab02..44152e561 100644 --- a/tests/in/push-constants.wgsl +++ b/tests/in/push-constants.wgsl @@ -8,6 +8,6 @@ struct FragmentIn { } @fragment -fn main(in: FragmentIn) -> @location(0) vec4 { - return in.color * pc.multiplier; +fn main(_in: FragmentIn) -> @location(0) vec4 { + return _in.color * pc.multiplier; } diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 575018863..61c63d0dc 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -36,11 +36,11 @@ fn vs_main( ) -> VertexOutput { let w = u_entity.world; let world_pos = u_entity.world * vec4(position); - var out: VertexOutput; - out.world_normal = mat3x3(w.x.xyz, w.y.xyz, w.z.xyz) * vec3(normal.xyz); - out.world_position = world_pos; - out.proj_position = u_globals.view_proj * world_pos; - return out; + var _out: VertexOutput; + _out.world_normal = mat3x3(w.x.xyz, w.y.xyz, w.z.xyz) * vec3(normal.xyz); + _out.world_position = world_pos; + _out.proj_position = u_globals.view_proj * world_pos; + return _out; } // fragment shader @@ -81,16 +81,16 @@ let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); let c_max_lights: u32 = 10u; @fragment -fn fs_main(in: VertexOutput) -> @location(0) vec4 { - let normal = normalize(in.world_normal); +fn fs_main(_in: VertexOutput) -> @location(0) vec4 { + let normal = normalize(_in.world_normal); // accumulate color var color: vec3 = c_ambient; for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i++) { let light = s_lights[i]; // project into the light space - let shadow = fetch_shadow(i, light.proj * in.world_position); + let shadow = fetch_shadow(i, light.proj * _in.world_position); // compute Lambertian diffuse term - let light_dir = normalize(light.pos.xyz - in.world_position.xyz); + let light_dir = normalize(light.pos.xyz - _in.world_position.xyz); let diffuse = max(0.0, dot(normal, light_dir)); // add light contribution color += shadow * diffuse * light.color.xyz; @@ -101,15 +101,15 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { // The fragment entrypoint used when storage buffers are not available for the lights @fragment -fn fs_main_without_storage(in: VertexOutput) -> @location(0) vec4 { - let normal = normalize(in.world_normal); +fn fs_main_without_storage(_in: VertexOutput) -> @location(0) vec4 { + let normal = normalize(_in.world_normal); var color: vec3 = c_ambient; for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i++) { // This line is the only difference from the entrypoint above. It uses the lights // uniform instead of the lights storage buffer let light = u_lights[i]; - let shadow = fetch_shadow(i, light.proj * in.world_position); - let light_dir = normalize(light.pos.xyz - in.world_position.xyz); + let shadow = fetch_shadow(i, light.proj * _in.world_position); + let light_dir = normalize(light.pos.xyz - _in.world_position.xyz); let diffuse = max(0.0, dot(normal, light_dir)); color += shadow * diffuse * light.color.xyz; } diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index f4cc37a44..5d36951c6 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -33,6 +33,6 @@ var r_texture: texture_cube; var r_sampler: sampler; @fragment -fn fs_main(in: VertexOutput) -> @location(0) vec4 { - return textureSample(r_texture, r_sampler, in.uv); +fn fs_main(_in: VertexOutput) -> @location(0) vec4 { + return textureSample(r_texture, r_sampler, _in.uv); } diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 2b92925a0..1a8668a82 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -12,7 +12,7 @@ struct Baz { mat3x2 m; }; layout(std430) buffer Bar_block_0Compute { - mat4x3 matrix; + mat4x3 _matrix; mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index e07dad7a0..df6ac6770 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -10,7 +10,7 @@ struct Baz { mat3x2 m; }; layout(std430) buffer Bar_block_0Fragment { - mat4x3 matrix; + mat4x3 _matrix; mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; @@ -29,8 +29,8 @@ float test_arr_as_arg(float a[5][10]) { } void main() { - _group_0_binding_0_fs.matrix[1][2] = 1.0; - _group_0_binding_0_fs.matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); + _group_0_binding_0_fs._matrix[1][2] = 1.0; + _group_0_binding_0_fs._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); _group_0_binding_0_fs.arr = uvec2[2](uvec2(0u), uvec2(1u)); _group_0_binding_0_fs.data[1].value = 1; _fs2p_location0 = vec4(0.0); diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index c545e4428..267dc2cea 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -10,7 +10,7 @@ struct Baz { mat3x2 m; }; layout(std430) buffer Bar_block_0Vertex { - mat4x3 matrix; + mat4x3 _matrix; mat2x2 matrix_array[2]; int atom; uvec2 arr[2]; @@ -86,9 +86,9 @@ void main() { float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); - mat4x3 matrix = _group_0_binding_0_vs.matrix; + mat4x3 _matrix = _group_0_binding_0_vs._matrix; uvec2 arr[2] = _group_0_binding_0_vs.arr; - float b = _group_0_binding_0_vs.matrix[3][0]; + float b = _group_0_binding_0_vs._matrix[3][0]; int a_1 = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; float _e28 = read_from_private(foo); c = int[5](a_1, int(b), 3, 4, 5); @@ -96,7 +96,7 @@ void main() { int value = c[vi]; float _e42 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); unnamed = _e42; - gl_Position = vec4((matrix * vec4(ivec4(value))), 2.0); + gl_Position = vec4((_matrix * vec4(ivec4(value))), 2.0); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; } diff --git a/tests/out/glsl/image.sample.Fragment.glsl b/tests/out/glsl/image.texture_sample.Fragment.glsl similarity index 100% rename from tests/out/glsl/image.sample.Fragment.glsl rename to tests/out/glsl/image.texture_sample.Fragment.glsl diff --git a/tests/out/glsl/image.sample_comparison.Fragment.glsl b/tests/out/glsl/image.texture_sample_comparison.Fragment.glsl similarity index 100% rename from tests/out/glsl/image.sample_comparison.Fragment.glsl rename to tests/out/glsl/image.texture_sample_comparison.Fragment.glsl diff --git a/tests/out/glsl/interpolate.frag_main.Fragment.glsl b/tests/out/glsl/interpolate.frag_main.Fragment.glsl index 1f35aebe6..d1662da49 100644 --- a/tests/out/glsl/interpolate.frag_main.Fragment.glsl +++ b/tests/out/glsl/interpolate.frag_main.Fragment.glsl @@ -1,8 +1,8 @@ #version 400 core struct FragmentInput { vec4 position; - uint flat_; - float linear; + uint _flat; + float _linear; vec2 linear_centroid; vec3 linear_sample; vec4 perspective; diff --git a/tests/out/glsl/interpolate.vert_main.Vertex.glsl b/tests/out/glsl/interpolate.vert_main.Vertex.glsl index 1c9ea718d..5155e7852 100644 --- a/tests/out/glsl/interpolate.vert_main.Vertex.glsl +++ b/tests/out/glsl/interpolate.vert_main.Vertex.glsl @@ -1,8 +1,8 @@ #version 400 core struct FragmentInput { vec4 position; - uint flat_; - float linear; + uint _flat; + float _linear; vec2 linear_centroid; vec3 linear_sample; vec4 perspective; @@ -18,19 +18,19 @@ smooth centroid out float _vs2fs_location5; smooth sample out float _vs2fs_location6; void main() { - FragmentInput out_ = FragmentInput(vec4(0.0), 0u, 0.0, vec2(0.0), vec3(0.0), vec4(0.0), 0.0, 0.0); - out_.position = vec4(2.0, 4.0, 5.0, 6.0); - out_.flat_ = 8u; - out_.linear = 27.0; - out_.linear_centroid = vec2(64.0, 125.0); - out_.linear_sample = vec3(216.0, 343.0, 512.0); - out_.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); - out_.perspective_centroid = 2197.0; - out_.perspective_sample = 2744.0; - FragmentInput _e30 = out_; + FragmentInput _out = FragmentInput(vec4(0.0), 0u, 0.0, vec2(0.0), vec3(0.0), vec4(0.0), 0.0, 0.0); + _out.position = vec4(2.0, 4.0, 5.0, 6.0); + _out._flat = 8u; + _out._linear = 27.0; + _out.linear_centroid = vec2(64.0, 125.0); + _out.linear_sample = vec3(216.0, 343.0, 512.0); + _out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + _out.perspective_centroid = 2197.0; + _out.perspective_sample = 2744.0; + FragmentInput _e30 = _out; gl_Position = _e30.position; - _vs2fs_location0 = _e30.flat_; - _vs2fs_location1 = _e30.linear; + _vs2fs_location0 = _e30._flat; + _vs2fs_location1 = _e30._linear; _vs2fs_location2 = _e30.linear_centroid; _vs2fs_location3 = _e30.linear_sample; _vs2fs_location4 = _e30.perspective; diff --git a/tests/out/glsl/push-constants.main.Fragment.glsl b/tests/out/glsl/push-constants.main.Fragment.glsl index fa1be9f61..d092ee05f 100644 --- a/tests/out/glsl/push-constants.main.Fragment.glsl +++ b/tests/out/glsl/push-constants.main.Fragment.glsl @@ -15,9 +15,9 @@ layout(location = 0) smooth in vec4 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { - FragmentIn in_ = FragmentIn(_vs2fs_location0); + FragmentIn _in = FragmentIn(_vs2fs_location0); float _e4 = pc.multiplier; - _fs2p_location0 = (in_.color * _e4); + _fs2p_location0 = (_in.color * _e4); return; } diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index fef409f10..fca6f9faa 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -45,10 +45,10 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } void main() { - VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); + VertexOutput _in = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); vec3 color = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i = 0u; - vec3 normal_1 = normalize(in_.world_normal); + vec3 normal_1 = normalize(_in.world_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -65,8 +65,8 @@ void main() { uint _e23 = i; Light light = _group_0_binding_1_fs[_e23]; uint _e26 = i; - float _e30 = fetch_shadow(_e26, (light.proj * in_.world_position)); - vec3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); + float _e30 = fetch_shadow(_e26, (light.proj * _in.world_position)); + vec3 light_dir = normalize((light.pos.xyz - _in.world_position.xyz)); float diffuse = max(0.0, dot(normal_1, light_dir)); vec3 _e40 = color; color = (_e40 + ((_e30 * diffuse) * light.color.xyz)); diff --git a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl index 43f02cae1..4fc36ae9e 100644 --- a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl @@ -45,10 +45,10 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } void main() { - VertexOutput in_1 = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); + VertexOutput _in_1 = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); vec3 color_1 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i_1 = 0u; - vec3 normal_1 = normalize(in_1.world_normal); + vec3 normal_1 = normalize(_in_1.world_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -65,8 +65,8 @@ void main() { uint _e23 = i_1; Light light = _group_0_binding_1_fs[_e23]; uint _e26 = i_1; - float _e30 = fetch_shadow(_e26, (light.proj * in_1.world_position)); - vec3 light_dir = normalize((light.pos.xyz - in_1.world_position.xyz)); + float _e30 = fetch_shadow(_e26, (light.proj * _in_1.world_position)); + vec3 light_dir = normalize((light.pos.xyz - _in_1.world_position.xyz)); float diffuse = max(0.0, dot(normal_1, light_dir)); vec3 _e40 = color_1; color_1 = (_e40 + ((_e30 * diffuse) * light.color.xyz)); diff --git a/tests/out/glsl/shadow.vs_main.Vertex.glsl b/tests/out/glsl/shadow.vs_main.Vertex.glsl index dce8b2f7d..8c2aff6a3 100644 --- a/tests/out/glsl/shadow.vs_main.Vertex.glsl +++ b/tests/out/glsl/shadow.vs_main.Vertex.glsl @@ -33,15 +33,15 @@ layout(location = 1) smooth out vec4 _vs2fs_location1; void main() { ivec4 position = _p2vs_location0; ivec4 normal = _p2vs_location1; - VertexOutput out_ = VertexOutput(vec4(0.0), vec3(0.0), vec4(0.0)); + VertexOutput _out = VertexOutput(vec4(0.0), vec3(0.0), vec4(0.0)); mat4x4 w = _group_1_binding_0_vs.world; mat4x4 _e7 = _group_1_binding_0_vs.world; vec4 world_pos = (_e7 * vec4(position)); - out_.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); - out_.world_position = world_pos; + _out.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); + _out.world_position = world_pos; mat4x4 _e25 = _group_0_binding_0_vs.view_proj; - out_.proj_position = (_e25 * world_pos); - VertexOutput _e27 = out_; + _out.proj_position = (_e25 * world_pos); + VertexOutput _e27 = _out; gl_Position = _e27.proj_position; _vs2fs_location0 = _e27.world_normal; _vs2fs_location1 = _e27.world_position; diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index 2b151db2a..77d686530 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -17,8 +17,8 @@ layout(location = 0) smooth in vec3 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { - VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0); - vec4 _e5 = texture(_group_0_binding_1_fs, vec3(in_.uv)); + VertexOutput _in = VertexOutput(gl_FragCoord, _vs2fs_location0); + vec4 _e5 = texture(_group_0_binding_1_fs, vec3(_in.uv)); _fs2p_location0 = _e5; return; } diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 21b9da81a..b94bc16bc 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -138,7 +138,7 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); - float4x3 matrix_ = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); + float4x3 _matrix = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); @@ -151,7 +151,7 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position int value = c[vi]; const float _e42 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); unnamed = _e42; - return float4(mul(float4((value).xxxx), matrix_), 2.0); + return float4(mul(float4((value).xxxx), _matrix), 2.0); } uint2 Constructarray2_uint2_(uint2 arg0, uint2 arg1)[2] { diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index d7a6f5c0f..a21e308da 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -230,7 +230,7 @@ float4 levels_queries() : SV_Position return (float(sum_1)).xxxx; } -float4 sample_() : SV_Target0 +float4 texture_sample() : SV_Target0 { float2 tc = (0.5).xx; float4 s1d = image_1d.Sample(sampler_reg, tc.x); @@ -242,7 +242,7 @@ float4 sample_() : SV_Target0 return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); } -float sample_comparison() : SV_Target0 +float texture_sample_comparison() : SV_Target0 { float2 tc_1 = (0.5).xx; float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc_1, 0.5); diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config index ba8a24dd0..8194e213f 100644 --- a/tests/out/hlsl/image.hlsl.config +++ b/tests/out/hlsl/image.hlsl.config @@ -1,3 +1,3 @@ vertex=(queries:vs_5_1 levels_queries:vs_5_1 ) -fragment=(sample_:ps_5_1 sample_comparison:ps_5_1 gather:ps_5_1 depth_no_comparison:ps_5_1 ) +fragment=(texture_sample:ps_5_1 texture_sample_comparison:ps_5_1 gather:ps_5_1 depth_no_comparison:ps_5_1 ) compute=(main:cs_5_1 depth_load:cs_5_1 ) diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 23a2d05d0..7cf1c67cb 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -7,7 +7,7 @@ ConstantBuffer _NagaConstants: register(b0, space1); struct VertexOutput { precise float4 position : SV_Position; - float varying : LOC1; + float _varying : LOC1; }; struct FragmentOutput { @@ -24,15 +24,15 @@ struct Input2_ { uint index : SV_InstanceID; }; -groupshared uint output[1]; +groupshared uint _output[1]; struct VertexOutput_vertex { - float varying : LOC1; + float _varying : LOC1; precise float4 position : SV_Position; }; struct FragmentInput_fragment { - float varying_1 : LOC1; + float _varying_1 : LOC1; precise float4 position_1 : SV_Position; bool front_facing_1 : SV_IsFrontFace; uint sample_index_1 : SV_SampleIndex; @@ -42,7 +42,7 @@ struct FragmentInput_fragment { VertexOutput ConstructVertexOutput(float4 arg0, float arg1) { VertexOutput ret; ret.position = arg0; - ret.varying = arg1; + ret._varying = arg1; return ret; } @@ -50,7 +50,7 @@ VertexOutput_vertex vertex(uint vertex_index : SV_VertexID, uint instance_index { uint tmp = (((_NagaConstants.base_vertex + vertex_index) + (_NagaConstants.base_instance + instance_index)) + color); const VertexOutput vertexoutput = ConstructVertexOutput((1.0).xxxx, float(tmp)); - const VertexOutput_vertex vertexoutput_1 = { vertexoutput.varying, vertexoutput.position }; + const VertexOutput_vertex vertexoutput_1 = { vertexoutput._varying, vertexoutput.position }; return vertexoutput_1; } @@ -64,20 +64,20 @@ FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) { FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) { - VertexOutput in_ = { fragmentinput_fragment.position_1, fragmentinput_fragment.varying_1 }; + VertexOutput _in = { fragmentinput_fragment.position_1, fragmentinput_fragment._varying_1 }; bool front_facing = fragmentinput_fragment.front_facing_1; uint sample_index = fragmentinput_fragment.sample_index_1; uint sample_mask = fragmentinput_fragment.sample_mask_1; uint mask = (sample_mask & (1u << sample_index)); float color_1 = (front_facing ? 1.0 : 0.0); - const FragmentOutput fragmentoutput = ConstructFragmentOutput(in_.varying, mask, color_1); + const FragmentOutput fragmentoutput = ConstructFragmentOutput(_in._varying, mask, color_1); return fragmentoutput; } [numthreads(1, 1, 1)] void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThreadID, uint local_index : SV_GroupIndex, uint3 wg_id : SV_GroupID, uint3 num_wgs : SV_GroupID) { - output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x); + _output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x); return; } diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index e9308f256..44d63239f 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -1,8 +1,8 @@ struct FragmentInput { float4 position : SV_Position; - nointerpolation uint flat : LOC0; - noperspective float linear_ : LOC1; + nointerpolation uint _flat : LOC0; + noperspective float _linear : LOC1; noperspective centroid float2 linear_centroid : LOC2; noperspective sample float3 linear_sample : LOC3; float4 perspective : LOC4; @@ -11,8 +11,8 @@ struct FragmentInput { }; struct VertexOutput_vert_main { - nointerpolation uint flat : LOC0; - noperspective float linear_ : LOC1; + nointerpolation uint _flat : LOC0; + noperspective float _linear : LOC1; noperspective centroid float2 linear_centroid : LOC2; noperspective sample float3 linear_sample : LOC3; float4 perspective : LOC4; @@ -22,8 +22,8 @@ struct VertexOutput_vert_main { }; struct FragmentInput_frag_main { - nointerpolation uint flat_1 : LOC0; - noperspective float linear_1 : LOC1; + nointerpolation uint _flat_1 : LOC0; + noperspective float _linear_1 : LOC1; noperspective centroid float2 linear_centroid_1 : LOC2; noperspective sample float3 linear_sample_1 : LOC3; float4 perspective_1 : LOC4; @@ -34,24 +34,24 @@ struct FragmentInput_frag_main { VertexOutput_vert_main vert_main() { - FragmentInput out_ = (FragmentInput)0; + FragmentInput _out = (FragmentInput)0; - out_.position = float4(2.0, 4.0, 5.0, 6.0); - out_.flat = 8u; - out_.linear_ = 27.0; - out_.linear_centroid = float2(64.0, 125.0); - out_.linear_sample = float3(216.0, 343.0, 512.0); - out_.perspective = float4(729.0, 1000.0, 1331.0, 1728.0); - out_.perspective_centroid = 2197.0; - out_.perspective_sample = 2744.0; - FragmentInput _expr30 = out_; + _out.position = float4(2.0, 4.0, 5.0, 6.0); + _out._flat = 8u; + _out._linear = 27.0; + _out.linear_centroid = float2(64.0, 125.0); + _out.linear_sample = float3(216.0, 343.0, 512.0); + _out.perspective = float4(729.0, 1000.0, 1331.0, 1728.0); + _out.perspective_centroid = 2197.0; + _out.perspective_sample = 2744.0; + FragmentInput _expr30 = _out; const FragmentInput fragmentinput = _expr30; - const VertexOutput_vert_main fragmentinput_1 = { fragmentinput.flat, fragmentinput.linear_, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position }; + const VertexOutput_vert_main fragmentinput_1 = { fragmentinput._flat, fragmentinput._linear, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position }; return fragmentinput_1; } void frag_main(FragmentInput_frag_main fragmentinput_frag_main) { - FragmentInput val = { fragmentinput_frag_main.position_1, fragmentinput_frag_main.flat_1, fragmentinput_frag_main.linear_1, fragmentinput_frag_main.linear_centroid_1, fragmentinput_frag_main.linear_sample_1, fragmentinput_frag_main.perspective_1, fragmentinput_frag_main.perspective_centroid_1, fragmentinput_frag_main.perspective_sample_1 }; + FragmentInput val = { fragmentinput_frag_main.position_1, fragmentinput_frag_main._flat_1, fragmentinput_frag_main._linear_1, fragmentinput_frag_main.linear_centroid_1, fragmentinput_frag_main.linear_sample_1, fragmentinput_frag_main.perspective_1, fragmentinput_frag_main.perspective_centroid_1, fragmentinput_frag_main.perspective_sample_1 }; return; } diff --git a/tests/out/hlsl/padding.hlsl b/tests/out/hlsl/padding.hlsl index 008863777..f833b936c 100644 --- a/tests/out/hlsl/padding.hlsl +++ b/tests/out/hlsl/padding.hlsl @@ -30,13 +30,13 @@ struct Test3_ { int _end_pad_2; }; -cbuffer input : register(b0) { Test input; } +cbuffer input1_ : register(b0) { Test input1_; } cbuffer input2_ : register(b1) { Test2_ input2_; } cbuffer input3_ : register(b2) { Test3_ input3_; } float4 vertex() : SV_Position { - float _expr6 = input.b; + float _expr6 = input1_.b; float _expr9 = input2_.b; float _expr12 = input3_.b; return ((((1.0).xxxx * _expr6) * _expr9) * _expr12); diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index b66713092..4635f9f28 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -62,16 +62,16 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords) VertexOutput_vs_main vs_main(int4 position : LOC0, int4 normal : LOC1) { - VertexOutput out_ = (VertexOutput)0; + VertexOutput _out = (VertexOutput)0; float4x4 w = u_entity.world; float4x4 _expr7 = u_entity.world; float4 world_pos = mul(float4(position), _expr7); - out_.world_normal = mul(float3(normal.xyz), float3x3(w[0].xyz, w[1].xyz, w[2].xyz)); - out_.world_position = world_pos; + _out.world_normal = mul(float3(normal.xyz), float3x3(w[0].xyz, w[1].xyz, w[2].xyz)); + _out.world_position = world_pos; float4x4 _expr25 = u_globals.view_proj; - out_.proj_position = mul(world_pos, _expr25); - VertexOutput _expr27 = out_; + _out.proj_position = mul(world_pos, _expr25); + VertexOutput _expr27 = _out; const VertexOutput vertexoutput = _expr27; const VertexOutput_vs_main vertexoutput_1 = { vertexoutput.world_normal, vertexoutput.world_position, vertexoutput.proj_position }; return vertexoutput_1; @@ -79,11 +79,11 @@ VertexOutput_vs_main vs_main(int4 position : LOC0, int4 normal : LOC1) float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { - VertexOutput in_ = { fragmentinput_fs_main.proj_position_1, fragmentinput_fs_main.world_normal_1, fragmentinput_fs_main.world_position_1 }; + VertexOutput _in = { fragmentinput_fs_main.proj_position_1, fragmentinput_fs_main.world_normal_1, fragmentinput_fs_main.world_position_1 }; float3 color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i = 0u; - float3 normal_1 = normalize(in_.world_normal); + float3 normal_1 = normalize(_in.world_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -100,8 +100,8 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 uint _expr23 = i; Light light = {float4x4(asfloat(s_lights.Load4(_expr23*96+0+0)), asfloat(s_lights.Load4(_expr23*96+0+16)), asfloat(s_lights.Load4(_expr23*96+0+32)), asfloat(s_lights.Load4(_expr23*96+0+48))), asfloat(s_lights.Load4(_expr23*96+64)), asfloat(s_lights.Load4(_expr23*96+80))}; uint _expr26 = i; - const float _e30 = fetch_shadow(_expr26, mul(in_.world_position, light.proj)); - float3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); + const float _e30 = fetch_shadow(_expr26, mul(_in.world_position, light.proj)); + float3 light_dir = normalize((light.pos.xyz - _in.world_position.xyz)); float diffuse = max(0.0, dot(normal_1, light_dir)); float3 _expr40 = color; color = (_expr40 + ((_e30 * diffuse) * light.color.xyz)); @@ -113,11 +113,11 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 float4 fs_main_without_storage(FragmentInput_fs_main_without_storage fragmentinput_fs_main_without_storage) : SV_Target0 { - VertexOutput in_1 = { fragmentinput_fs_main_without_storage.proj_position_2, fragmentinput_fs_main_without_storage.world_normal_2, fragmentinput_fs_main_without_storage.world_position_2 }; + VertexOutput _in_1 = { fragmentinput_fs_main_without_storage.proj_position_2, fragmentinput_fs_main_without_storage.world_normal_2, fragmentinput_fs_main_without_storage.world_position_2 }; float3 color_1 = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i_1 = 0u; - float3 normal_2 = normalize(in_1.world_normal); + float3 normal_2 = normalize(_in_1.world_normal); bool loop_init_1 = true; while(true) { if (!loop_init_1) { @@ -134,8 +134,8 @@ float4 fs_main_without_storage(FragmentInput_fs_main_without_storage fragmentinp uint _expr23 = i_1; Light light_1 = u_lights[_expr23]; uint _expr26 = i_1; - const float _e30 = fetch_shadow(_expr26, mul(in_1.world_position, light_1.proj)); - float3 light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); + const float _e30 = fetch_shadow(_expr26, mul(_in_1.world_position, light_1.proj)); + float3 light_dir_1 = normalize((light_1.pos.xyz - _in_1.world_position.xyz)); float diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); float3 _expr40 = color_1; color_1 = (_expr40 + ((_e30 * diffuse_1) * light_1.color.xyz)); diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 3664c497c..6e119903d 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -59,7 +59,7 @@ VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { - VertexOutput in_ = { fragmentinput_fs_main.position_1, fragmentinput_fs_main.uv_1 }; - float4 _expr5 = r_texture.Sample(r_sampler, in_.uv); + VertexOutput _in = { fragmentinput_fs_main.position_1, fragmentinput_fs_main.uv_1 }; + float4 _expr5 = r_texture.Sample(r_sampler, _in.uv); return _expr5; } diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index a791ee6ab..8ba6750c7 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -19,7 +19,7 @@ struct type_6 { }; typedef AlignedWrapper type_7[1]; struct Bar { - metal::float4x3 matrix; + metal::float4x3 _matrix; type_3 matrix_array; metal::atomic_int atom; char _pad3[4]; @@ -122,9 +122,9 @@ vertex foo_vertOutput foo_vert( float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); - metal::float4x3 matrix = bar.matrix; + metal::float4x3 _matrix = bar._matrix; type_6 arr = bar.arr; - float b = bar.matrix[3].x; + float b = bar._matrix[3].x; int a_1 = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; float _e28 = read_from_private(foo); for(int _i=0; _i<5; ++_i) c.inner[_i] = type_17 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; @@ -132,7 +132,7 @@ vertex foo_vertOutput foo_vert( int value = c.inner[vi]; float _e42 = test_arr_as_arg(const_type_13_); unnamed = _e42; - return foo_vertOutput { metal::float4(matrix * static_cast(metal::int4(value)), 2.0) }; + return foo_vertOutput { metal::float4(_matrix * static_cast(metal::int4(value)), 2.0) }; } @@ -143,8 +143,8 @@ fragment foo_fragOutput foo_frag( device Bar& bar [[buffer(0)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - bar.matrix[1].z = 1.0; - bar.matrix = metal::float4x3(metal::float3(0.0), metal::float3(1.0), metal::float3(2.0), metal::float3(3.0)); + bar._matrix[1].z = 1.0; + bar._matrix = metal::float4x3(metal::float3(0.0), metal::float3(1.0), metal::float3(2.0), metal::float3(3.0)); for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_6 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; bar.data[1].value = 1; return foo_fragOutput { metal::float4(0.0) }; diff --git a/tests/out/msl/bounds-check-image-restrict.msl b/tests/out/msl/bounds-check-image-restrict.msl index 1eb6f2331..6a4548475 100644 --- a/tests/out/msl/bounds-check-image-restrict.msl +++ b/tests/out/msl/bounds-check-image-restrict.msl @@ -47,10 +47,10 @@ metal::float4 test_textureLoad_3d( metal::float4 test_textureLoad_multisampled_2d( metal::int2 coords_4, - int sample, + int _sample, metal::texture2d_ms image_multisampled_2d ) { - metal::float4 _e7 = image_multisampled_2d.read(metal::min(metal::uint2(coords_4), metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height()) - 1), metal::min(uint(sample), image_multisampled_2d.get_num_samples() - 1)); + metal::float4 _e7 = image_multisampled_2d.read(metal::min(metal::uint2(coords_4), metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height()) - 1), metal::min(uint(_sample), image_multisampled_2d.get_num_samples() - 1)); return _e7; } @@ -77,10 +77,10 @@ float test_textureLoad_depth_2d_array( float test_textureLoad_depth_multisampled_2d( metal::int2 coords_7, - int sample_1, + int _sample_1, metal::depth2d_ms image_depth_multisampled_2d ) { - float _e10 = image_depth_multisampled_2d.read(metal::min(metal::uint2(coords_7), metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height()) - 1), metal::min(uint(sample_1), image_depth_multisampled_2d.get_num_samples() - 1)); + float _e10 = image_depth_multisampled_2d.read(metal::min(metal::uint2(coords_7), metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height()) - 1), metal::min(uint(_sample_1), image_depth_multisampled_2d.get_num_samples() - 1)); return _e10; } diff --git a/tests/out/msl/bounds-check-image-rzsw.msl b/tests/out/msl/bounds-check-image-rzsw.msl index 6acb1046a..78bef45ee 100644 --- a/tests/out/msl/bounds-check-image-rzsw.msl +++ b/tests/out/msl/bounds-check-image-rzsw.msl @@ -50,10 +50,10 @@ metal::float4 test_textureLoad_3d( metal::float4 test_textureLoad_multisampled_2d( metal::int2 coords_4, - int sample, + int _sample, metal::texture2d_ms image_multisampled_2d ) { - metal::float4 _e7 = (uint(sample) < image_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_4) < metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height())) ? image_multisampled_2d.read(metal::uint2(coords_4), sample): DefaultConstructible()); + metal::float4 _e7 = (uint(_sample) < image_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_4) < metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height())) ? image_multisampled_2d.read(metal::uint2(coords_4), _sample): DefaultConstructible()); return _e7; } @@ -78,10 +78,10 @@ float test_textureLoad_depth_2d_array( float test_textureLoad_depth_multisampled_2d( metal::int2 coords_7, - int sample_1, + int _sample_1, metal::depth2d_ms image_depth_multisampled_2d ) { - float _e10 = (uint(sample_1) < image_depth_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_7) < metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height())) ? image_depth_multisampled_2d.read(metal::uint2(coords_7), sample_1): DefaultConstructible()); + float _e10 = (uint(_sample_1) < image_depth_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_7) < metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height())) ? image_depth_multisampled_2d.read(metal::uint2(coords_7), _sample_1): DefaultConstructible()); return _e10; } diff --git a/tests/out/msl/extra.msl b/tests/out/msl/extra.msl index 8288dfad9..683b074f2 100644 --- a/tests/out/msl/extra.msl +++ b/tests/out/msl/extra.msl @@ -25,11 +25,11 @@ fragment main_Output main_( , uint primitive_index [[primitive_id]] , constant PushConstants& pc [[buffer(1)]] ) { - const FragmentIn in = { varyings.color, primitive_index }; + const FragmentIn _in = { varyings.color, primitive_index }; uint _e4 = pc.index; - if (in.primitive_index == _e4) { - return main_Output { in.color }; + if (_in.primitive_index == _e4) { + return main_Output { _in.color }; } else { - return main_Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) }; + return main_Output { metal::float4(metal::float3(1.0) - _in.color.xyz, _in.color.w) }; } } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index e3aaafa9e..16839dfbe 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -99,10 +99,10 @@ vertex levels_queriesOutput levels_queries( } -struct sampleOutput { +struct texture_sampleOutput { metal::float4 member_4 [[color(0)]]; }; -fragment sampleOutput sample( +fragment texture_sampleOutput texture_sample( metal::texture1d image_1d [[user(fake0)]] , metal::texture2d image_2d [[user(fake0)]] , metal::sampler sampler_reg [[user(fake0)]] @@ -114,14 +114,14 @@ fragment sampleOutput sample( metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_9_); metal::float4 s2d_bias_offset = image_2d.sample(sampler_reg, tc, metal::bias(2.0), const_type_9_); - return sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset }; + return texture_sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset }; } -struct sample_comparisonOutput { +struct texture_sample_comparisonOutput { float member_5 [[color(0)]]; }; -fragment sample_comparisonOutput sample_comparison( +fragment texture_sample_comparisonOutput texture_sample_comparison( metal::sampler sampler_cmp [[user(fake0)]] , metal::depth2d image_2d_depth [[user(fake0)]] , metal::depthcube image_cube_depth [[user(fake0)]] @@ -130,7 +130,7 @@ fragment sample_comparisonOutput sample_comparison( float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); float scube_depth_level = image_cube_depth.sample_compare(sampler_cmp, metal::float3(0.5), 0.5); - return sample_comparisonOutput { s2d_depth + s2d_depth_level }; + return texture_sample_comparisonOutput { s2d_depth + s2d_depth_level }; } diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 28bba917f..7cb6a401f 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -6,7 +6,7 @@ using metal::uint; struct VertexOutput { metal::float4 position; - float varying; + float _varying; }; struct FragmentOutput { float depth; @@ -28,7 +28,7 @@ struct vertex_Input { }; struct vertex_Output { metal::float4 position [[position, invariant]]; - float varying [[user(loc1), center_perspective]]; + float _varying [[user(loc1), center_perspective]]; float _point_size [[point_size]]; }; vertex vertex_Output vertex_( @@ -39,12 +39,12 @@ vertex vertex_Output vertex_( const auto color = varyings.color; uint tmp = (vertex_index + instance_index) + color; const auto _tmp = VertexOutput {metal::float4(1.0), static_cast(tmp)}; - return vertex_Output { _tmp.position, _tmp.varying, 1.0 }; + return vertex_Output { _tmp.position, _tmp._varying, 1.0 }; } struct fragment_Input { - float varying [[user(loc1), center_perspective]]; + float _varying [[user(loc1), center_perspective]]; }; struct fragment_Output { float depth [[depth(any)]]; @@ -58,10 +58,10 @@ fragment fragment_Output fragment_( , uint sample_index [[sample_id]] , uint sample_mask [[sample_mask]] ) { - const VertexOutput in = { position, varyings_1.varying }; + const VertexOutput _in = { position, varyings_1._varying }; uint mask = sample_mask & (1u << sample_index); float color_1 = front_facing ? 1.0 : 0.0; - const auto _tmp = FragmentOutput {in.varying, mask, color_1}; + const auto _tmp = FragmentOutput {_in._varying, mask, color_1}; return fragment_Output { _tmp.depth, _tmp.sample_mask, _tmp.color }; } @@ -74,9 +74,9 @@ kernel void compute_( , uint local_index [[thread_index_in_threadgroup]] , metal::uint3 wg_id [[threadgroup_position_in_grid]] , metal::uint3 num_wgs [[threadgroups_per_grid]] -, threadgroup type_4& output +, threadgroup type_4& _output ) { - output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x; + _output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x; return; } diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl index 659b9d3d2..cefc07ab9 100644 --- a/tests/out/msl/interpolate.msl +++ b/tests/out/msl/interpolate.msl @@ -6,8 +6,8 @@ using metal::uint; struct FragmentInput { metal::float4 position; - uint flat; - float linear; + uint _flat; + float _linear; metal::float2 linear_centroid; metal::float3 linear_sample; metal::float4 perspective; @@ -17,8 +17,8 @@ struct FragmentInput { struct vert_mainOutput { metal::float4 position [[position]]; - uint flat [[user(loc0), flat]]; - float linear [[user(loc1), center_no_perspective]]; + uint _flat [[user(loc0), flat]]; + float _linear [[user(loc1), center_no_perspective]]; metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]]; metal::float3 linear_sample [[user(loc3), sample_no_perspective]]; metal::float4 perspective [[user(loc4), center_perspective]]; @@ -27,24 +27,24 @@ struct vert_mainOutput { }; vertex vert_mainOutput vert_main( ) { - FragmentInput out; - out.position = metal::float4(2.0, 4.0, 5.0, 6.0); - out.flat = 8u; - out.linear = 27.0; - out.linear_centroid = metal::float2(64.0, 125.0); - out.linear_sample = metal::float3(216.0, 343.0, 512.0); - out.perspective = metal::float4(729.0, 1000.0, 1331.0, 1728.0); - out.perspective_centroid = 2197.0; - out.perspective_sample = 2744.0; - FragmentInput _e30 = out; + FragmentInput _out; + _out.position = metal::float4(2.0, 4.0, 5.0, 6.0); + _out._flat = 8u; + _out._linear = 27.0; + _out.linear_centroid = metal::float2(64.0, 125.0); + _out.linear_sample = metal::float3(216.0, 343.0, 512.0); + _out.perspective = metal::float4(729.0, 1000.0, 1331.0, 1728.0); + _out.perspective_centroid = 2197.0; + _out.perspective_sample = 2744.0; + FragmentInput _e30 = _out; const auto _tmp = _e30; - return vert_mainOutput { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample }; + return vert_mainOutput { _tmp.position, _tmp._flat, _tmp._linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample }; } struct frag_mainInput { - uint flat [[user(loc0), flat]]; - float linear [[user(loc1), center_no_perspective]]; + uint _flat [[user(loc0), flat]]; + float _linear [[user(loc1), center_no_perspective]]; metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]]; metal::float3 linear_sample [[user(loc3), sample_no_perspective]]; metal::float4 perspective [[user(loc4), center_perspective]]; @@ -55,6 +55,6 @@ fragment void frag_main( frag_mainInput varyings_1 [[stage_in]] , metal::float4 position [[position]] ) { - const FragmentInput val = { position, varyings_1.flat, varyings_1.linear, varyings_1.linear_centroid, varyings_1.linear_sample, varyings_1.perspective, varyings_1.perspective_centroid, varyings_1.perspective_sample }; + const FragmentInput val = { position, varyings_1._flat, varyings_1._linear, varyings_1.linear_centroid, varyings_1.linear_sample, varyings_1.perspective, varyings_1.perspective_centroid, varyings_1.perspective_sample }; return; } diff --git a/tests/out/msl/padding.msl b/tests/out/msl/padding.msl index 23aef3581..90b2c2eb1 100644 --- a/tests/out/msl/padding.msl +++ b/tests/out/msl/padding.msl @@ -27,11 +27,11 @@ struct vertex_Output { metal::float4 member [[position]]; }; vertex vertex_Output vertex_( - constant Test& input [[buffer(0)]] + constant Test& input1_ [[buffer(0)]] , constant Test2_& input2_ [[buffer(1)]] , constant Test3_& input3_ [[buffer(2)]] ) { - float _e6 = input.b; + float _e6 = input1_.b; float _e9 = input2_.b; float _e12 = input3_.b; return vertex_Output { ((metal::float4(1.0) * _e6) * _e9) * _e12 }; diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 5286b0bd0..ba723742a 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -65,15 +65,15 @@ vertex vs_mainOutput vs_main( ) { const auto position = varyings.position; const auto normal = varyings.normal; - VertexOutput out; + VertexOutput _out; metal::float4x4 w = u_entity.world; metal::float4x4 _e7 = u_entity.world; metal::float4 world_pos = _e7 * static_cast(position); - out.world_normal = metal::float3x3(w[0].xyz, w[1].xyz, w[2].xyz) * static_cast(normal.xyz); - out.world_position = world_pos; + _out.world_normal = metal::float3x3(w[0].xyz, w[1].xyz, w[2].xyz) * static_cast(normal.xyz); + _out.world_position = world_pos; metal::float4x4 _e25 = u_globals.view_proj; - out.proj_position = _e25 * world_pos; - VertexOutput _e27 = out; + _out.proj_position = _e25 * world_pos; + VertexOutput _e27 = _out; const auto _tmp = _e27; return vs_mainOutput { _tmp.proj_position, _tmp.world_normal, _tmp.world_position }; } @@ -96,10 +96,10 @@ fragment fs_mainOutput fs_main( , metal::sampler sampler_shadow [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - const VertexOutput in = { proj_position, varyings_1.world_normal, varyings_1.world_position }; + const VertexOutput _in = { proj_position, varyings_1.world_normal, varyings_1.world_position }; metal::float3 color = c_ambient; uint i = 0u; - metal::float3 normal_1 = metal::normalize(in.world_normal); + metal::float3 normal_1 = metal::normalize(_in.world_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -116,8 +116,8 @@ fragment fs_mainOutput fs_main( uint _e23 = i; Light light = s_lights[_e23]; uint _e26 = i; - float _e30 = fetch_shadow(_e26, light.proj * in.world_position, t_shadow, sampler_shadow); - metal::float3 light_dir = metal::normalize(light.pos.xyz - in.world_position.xyz); + float _e30 = fetch_shadow(_e26, light.proj * _in.world_position, t_shadow, sampler_shadow); + metal::float3 light_dir = metal::normalize(light.pos.xyz - _in.world_position.xyz); float diffuse = metal::max(0.0, metal::dot(normal_1, light_dir)); metal::float3 _e40 = color; color = _e40 + ((_e30 * diffuse) * light.color.xyz); @@ -144,10 +144,10 @@ fragment fs_main_without_storageOutput fs_main_without_storage( , metal::depth2d_array t_shadow [[user(fake0)]] , metal::sampler sampler_shadow [[user(fake0)]] ) { - const VertexOutput in_1 = { proj_position_1, varyings_2.world_normal, varyings_2.world_position }; + const VertexOutput _in_1 = { proj_position_1, varyings_2.world_normal, varyings_2.world_position }; metal::float3 color_1 = c_ambient; uint i_1 = 0u; - metal::float3 normal_2 = metal::normalize(in_1.world_normal); + metal::float3 normal_2 = metal::normalize(_in_1.world_normal); bool loop_init_1 = true; while(true) { if (!loop_init_1) { @@ -164,8 +164,8 @@ fragment fs_main_without_storageOutput fs_main_without_storage( uint _e23 = i_1; Light light_1 = u_lights.inner[_e23]; uint _e26 = i_1; - float _e30 = fetch_shadow(_e26, light_1.proj * in_1.world_position, t_shadow, sampler_shadow); - metal::float3 light_dir_1 = metal::normalize(light_1.pos.xyz - in_1.world_position.xyz); + float _e30 = fetch_shadow(_e26, light_1.proj * _in_1.world_position, t_shadow, sampler_shadow); + metal::float3 light_dir_1 = metal::normalize(light_1.pos.xyz - _in_1.world_position.xyz); float diffuse_1 = metal::max(0.0, metal::dot(normal_2, light_dir_1)); metal::float3 _e40 = color_1; color_1 = _e40 + ((_e30 * diffuse_1) * light_1.color.xyz); diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index bf8725043..f6b8c006f 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -60,7 +60,7 @@ fragment fs_mainOutput fs_main( metal::min_filter::linear, metal::coord::normalized ); - const VertexOutput in = { position, varyings_1.uv }; - metal::float4 _e5 = r_texture.sample(r_sampler, in.uv); + const VertexOutput _in = { position, varyings_1.uv }; + metal::float4 _e5 = r_texture.sample(r_sampler, _in.uv); return fs_mainOutput { _e5 }; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 41d9c1eda..a50474190 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -14,7 +14,7 @@ OpExecutionMode %204 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %32 0 "value" OpName %32 "AlignedWrapper" -OpMemberName %41 0 "matrix" +OpMemberName %41 0 "_matrix" OpMemberName %41 1 "matrix_array" OpMemberName %41 2 "atom" OpMemberName %41 3 "arr" diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index 6a6ae6388..fe3bf1759 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -36,7 +36,7 @@ OpName %92 "coords" OpName %93 "level" OpName %94 "test_textureLoad_3d" OpName %107 "coords" -OpName %108 "sample" +OpName %108 "_sample" OpName %109 "test_textureLoad_multisampled_2d" OpName %121 "coords" OpName %122 "level" @@ -46,7 +46,7 @@ OpName %138 "index" OpName %139 "level" OpName %140 "test_textureLoad_depth_2d_array" OpName %155 "coords" -OpName %156 "sample" +OpName %156 "_sample" OpName %157 "test_textureLoad_depth_multisampled_2d" OpName %170 "coords" OpName %171 "value" diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index 5716cca40..981355a41 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -36,7 +36,7 @@ OpName %103 "coords" OpName %104 "level" OpName %105 "test_textureLoad_3d" OpName %121 "coords" -OpName %122 "sample" +OpName %122 "_sample" OpName %123 "test_textureLoad_multisampled_2d" OpName %138 "coords" OpName %139 "level" @@ -46,7 +46,7 @@ OpName %158 "index" OpName %159 "level" OpName %160 "test_textureLoad_depth_2d_array" OpName %178 "coords" -OpName %179 "sample" +OpName %179 "_sample" OpName %180 "test_textureLoad_depth_multisampled_2d" OpName %196 "coords" OpName %197 "value" diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index f44df535b..89192b737 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -13,8 +13,8 @@ OpEntryPoint GLCompute %76 "main" %73 OpEntryPoint GLCompute %121 "depth_load" %119 OpEntryPoint Vertex %142 "queries" %140 OpEntryPoint Vertex %194 "levels_queries" %193 -OpEntryPoint Fragment %223 "sample" %222 -OpEntryPoint Fragment %252 "sample_comparison" %250 +OpEntryPoint Fragment %223 "texture_sample" %222 +OpEntryPoint Fragment %252 "texture_sample_comparison" %250 OpEntryPoint Fragment %272 "gather" %271 OpEntryPoint Fragment %294 "depth_no_comparison" %293 OpExecutionMode %76 LocalSize 16 1 1 @@ -49,8 +49,8 @@ OpName %119 "local_id" OpName %121 "depth_load" OpName %142 "queries" OpName %194 "levels_queries" -OpName %223 "sample" -OpName %252 "sample_comparison" +OpName %223 "texture_sample" +OpName %252 "texture_sample_comparison" OpName %272 "gather" OpName %294 "depth_no_comparison" OpDecorate %34 DescriptorSet 0 diff --git a/tests/out/spv/interpolate.spvasm b/tests/out/spv/interpolate.spvasm index 496df463a..7c48cb646 100644 --- a/tests/out/spv/interpolate.spvasm +++ b/tests/out/spv/interpolate.spvasm @@ -11,18 +11,18 @@ OpEntryPoint Fragment %108 "frag_main" %87 %90 %93 %96 %99 %102 %104 %106 OpExecutionMode %108 OriginUpperLeft OpSource GLSL 450 OpMemberName %25 0 "position" -OpMemberName %25 1 "flat" -OpMemberName %25 2 "linear" +OpMemberName %25 1 "_flat" +OpMemberName %25 2 "_linear" OpMemberName %25 3 "linear_centroid" OpMemberName %25 4 "linear_sample" OpMemberName %25 5 "perspective" OpMemberName %25 6 "perspective_centroid" OpMemberName %25 7 "perspective_sample" OpName %25 "FragmentInput" -OpName %26 "out" +OpName %26 "_out" OpName %29 "position" -OpName %31 "flat" -OpName %33 "linear" +OpName %31 "_flat" +OpName %33 "_linear" OpName %35 "linear_centroid" OpName %37 "linear_sample" OpName %39 "perspective" @@ -30,8 +30,8 @@ OpName %40 "perspective_centroid" OpName %41 "perspective_sample" OpName %45 "vert_main" OpName %87 "position" -OpName %90 "flat" -OpName %93 "linear" +OpName %90 "_flat" +OpName %93 "_linear" OpName %96 "linear_centroid" OpName %99 "linear_sample" OpName %102 "perspective" diff --git a/tests/out/spv/padding.spvasm b/tests/out/spv/padding.spvasm index d262f4b08..44ec6a4d1 100644 --- a/tests/out/spv/padding.spvasm +++ b/tests/out/spv/padding.spvasm @@ -18,7 +18,7 @@ OpName %11 "Test2" OpMemberName %13 0 "a" OpMemberName %13 1 "b" OpName %13 "Test3" -OpName %15 "input" +OpName %15 "input1" OpName %18 "input2" OpName %21 "input3" OpName %27 "vertex" diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index aeb85c96b..9e42405fb 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -37,7 +37,7 @@ OpName %45 "sampler_shadow" OpName %48 "light_id" OpName %49 "homogeneous_coords" OpName %50 "fetch_shadow" -OpName %80 "out" +OpName %80 "_out" OpName %83 "position" OpName %86 "normal" OpName %88 "proj_position" diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 0381f76f8..0fd4b7fd3 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -3,7 +3,7 @@ struct AlignedWrapper { } struct Bar { - matrix: mat4x3, + _matrix: mat4x3, matrix_array: array,2>, atom: atomic, arr: array,2>, @@ -87,9 +87,9 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); - let matrix = bar.matrix; + let _matrix = bar._matrix; let arr = bar.arr; - let b = bar.matrix[3][0]; + let b = bar._matrix[3][0]; let a_1 = bar.data[(arrayLength((&bar.data)) - 2u)].value; let data_pointer = (&bar.data[0].value); let _e28 = read_from_private((&foo)); @@ -98,13 +98,13 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let value = c[vi]; let _e42 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); unnamed = _e42; - return vec4((matrix * vec4(vec4(value))), 2.0); + return vec4((_matrix * vec4(vec4(value))), 2.0); } @fragment fn foo_frag() -> @location(0) vec4 { - bar.matrix[1][2] = 1.0; - bar.matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); + bar._matrix[1][2] = 1.0; + bar._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); bar.data[1].value = 1; return vec4(0.0); diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index 34a2e176c..a4542763b 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -11,11 +11,11 @@ struct FragmentIn { var pc: PushConstants; @fragment -fn main(in: FragmentIn) -> @location(0) vec4 { +fn main(_in: FragmentIn) -> @location(0) vec4 { let _e4 = pc.index; - if (in.primitive_index == _e4) { - return in.color; + if (_in.primitive_index == _e4) { + return _in.color; } else { - return vec4((vec3(1.0) - in.color.xyz), in.color.w); + return vec4((vec3(1.0) - _in.color.xyz), _in.color.w); } } diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 6903548c0..062876f22 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -93,7 +93,7 @@ fn levels_queries() -> @builtin(position) vec4 { } @fragment -fn sample() -> @location(0) vec4 { +fn texture_sample() -> @location(0) vec4 { let tc = vec2(0.5); let s1d = textureSample(image_1d, sampler_reg, tc.x); let s2d = textureSample(image_2d, sampler_reg, tc); @@ -105,7 +105,7 @@ fn sample() -> @location(0) vec4 { } @fragment -fn sample_comparison() -> @location(0) f32 { +fn texture_sample_comparison() -> @location(0) f32 { let tc_1 = vec2(0.5); let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5); diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index b3e30b92d..eda7d72de 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -1,6 +1,6 @@ struct VertexOutput { @builtin(position) @invariant position: vec4, - @location(1) varying: f32, + @location(1) _varying: f32, } struct FragmentOutput { @@ -17,7 +17,7 @@ struct Input2_ { @builtin(instance_index) index: u32, } -var output: array; +var _output: array; @vertex fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) instance_index: u32, @location(10) color: u32) -> VertexOutput { @@ -26,15 +26,15 @@ fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) ins } @fragment -fn fragment(in: VertexOutput, @builtin(front_facing) front_facing: bool, @builtin(sample_index) sample_index: u32, @builtin(sample_mask) sample_mask: u32) -> FragmentOutput { +fn fragment(_in: VertexOutput, @builtin(front_facing) front_facing: bool, @builtin(sample_index) sample_index: u32, @builtin(sample_mask) sample_mask: u32) -> FragmentOutput { let mask: u32 = (sample_mask & (1u << sample_index)); let color_1: f32 = select(0.0, 1.0, front_facing); - return FragmentOutput(in.varying, mask, color_1); + return FragmentOutput(_in._varying, mask, color_1); } @compute @workgroup_size(1, 1, 1) fn compute(@builtin(global_invocation_id) global_id: vec3, @builtin(local_invocation_id) local_id: vec3, @builtin(local_invocation_index) local_index: u32, @builtin(workgroup_id) wg_id: vec3, @builtin(num_workgroups) num_wgs: vec3) { - output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x); + _output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x); return; } diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index 5e489a62d..dbccb1ac8 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -1,7 +1,7 @@ struct FragmentInput { @builtin(position) position: vec4, - @location(0) flat: u32, - @location(1) @interpolate(linear) linear: f32, + @location(0) _flat: u32, + @location(1) @interpolate(linear) _linear: f32, @location(2) @interpolate(linear, centroid) linear_centroid: vec2, @location(3) @interpolate(linear, sample) linear_sample: vec3, @location(4) perspective: vec4, @@ -11,17 +11,17 @@ struct FragmentInput { @vertex fn vert_main() -> FragmentInput { - var out: FragmentInput; + var _out: FragmentInput; - out.position = vec4(2.0, 4.0, 5.0, 6.0); - out.flat = 8u; - out.linear = 27.0; - out.linear_centroid = vec2(64.0, 125.0); - out.linear_sample = vec3(216.0, 343.0, 512.0); - out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); - out.perspective_centroid = 2197.0; - out.perspective_sample = 2744.0; - let _e30 = out; + _out.position = vec4(2.0, 4.0, 5.0, 6.0); + _out._flat = 8u; + _out._linear = 27.0; + _out.linear_centroid = vec2(64.0, 125.0); + _out.linear_sample = vec3(216.0, 343.0, 512.0); + _out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + _out.perspective_centroid = 2197.0; + _out.perspective_sample = 2744.0; + let _e30 = _out; return _e30; } diff --git a/tests/out/wgsl/padding.wgsl b/tests/out/wgsl/padding.wgsl index 06955f174..4f2b8d4b7 100644 --- a/tests/out/wgsl/padding.wgsl +++ b/tests/out/wgsl/padding.wgsl @@ -18,7 +18,7 @@ struct Test3_ { } @group(0) @binding(0) -var input: Test; +var input1_: Test; @group(0) @binding(1) var input2_: Test2_; @group(0) @binding(2) @@ -26,7 +26,7 @@ var input3_: Test3_; @vertex fn vertex() -> @builtin(position) vec4 { - let _e6 = input.b; + let _e6 = input1_.b; let _e9 = input2_.b; let _e12 = input3_.b; return (((vec4(1.0) * _e6) * _e9) * _e12); diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 8bb6b5813..653264454 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -49,25 +49,25 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { @vertex fn vs_main(@location(0) position: vec4, @location(1) normal: vec4) -> VertexOutput { - var out: VertexOutput; + var _out: VertexOutput; let w = u_entity.world; let _e7 = u_entity.world; let world_pos = (_e7 * vec4(position)); - out.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); - out.world_position = world_pos; + _out.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); + _out.world_position = world_pos; let _e25 = u_globals.view_proj; - out.proj_position = (_e25 * world_pos); - let _e27 = out; + _out.proj_position = (_e25 * world_pos); + let _e27 = _out; return _e27; } @fragment -fn fs_main(in: VertexOutput) -> @location(0) vec4 { +fn fs_main(_in: VertexOutput) -> @location(0) vec4 { var color: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i: u32 = 0u; - let normal_1 = normalize(in.world_normal); + let normal_1 = normalize(_in.world_normal); loop { let _e14 = i; let _e17 = u_globals.num_lights.x; @@ -78,8 +78,8 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { let _e23 = i; let light = s_lights[_e23]; let _e26 = i; - let _e30 = fetch_shadow(_e26, (light.proj * in.world_position)); - let light_dir = normalize((light.pos.xyz - in.world_position.xyz)); + let _e30 = fetch_shadow(_e26, (light.proj * _in.world_position)); + let light_dir = normalize((light.pos.xyz - _in.world_position.xyz)); let diffuse = max(0.0, dot(normal_1, light_dir)); let _e40 = color; color = (_e40 + ((_e30 * diffuse) * light.color.xyz)); @@ -94,11 +94,11 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { } @fragment -fn fs_main_without_storage(in_1: VertexOutput) -> @location(0) vec4 { +fn fs_main_without_storage(_in_1: VertexOutput) -> @location(0) vec4 { var color_1: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i_1: u32 = 0u; - let normal_2 = normalize(in_1.world_normal); + let normal_2 = normalize(_in_1.world_normal); loop { let _e14 = i_1; let _e17 = u_globals.num_lights.x; @@ -109,8 +109,8 @@ fn fs_main_without_storage(in_1: VertexOutput) -> @location(0) vec4 { let _e23 = i_1; let light_1 = u_lights[_e23]; let _e26 = i_1; - let _e30 = fetch_shadow(_e26, (light_1.proj * in_1.world_position)); - let light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); + let _e30 = fetch_shadow(_e26, (light_1.proj * _in_1.world_position)); + let light_dir_1 = normalize((light_1.pos.xyz - _in_1.world_position.xyz)); let diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); let _e40 = color_1; color_1 = (_e40 + ((_e30 * diffuse_1) * light_1.color.xyz)); diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index c9be90196..f759f48de 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -35,7 +35,7 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput { } @fragment -fn fs_main(in: VertexOutput) -> @location(0) vec4 { - let _e5 = textureSample(r_texture, r_sampler, in.uv); +fn fs_main(_in: VertexOutput) -> @location(0) vec4 { + let _e5 = textureSample(r_texture, r_sampler, _in.uv); return _e5; } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 4ccfa29bf..caf855e1b 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1012,8 +1012,8 @@ fn missing_bindings() { check_validation_error! { " @vertex - fn vertex(input: vec4) -> @location(0) vec4 { - return input; + fn vertex(_input: vec4) -> @location(0) vec4 { + return _input; } ": Err(naga::valid::ValidationError::EntryPoint { @@ -1029,8 +1029,8 @@ fn missing_bindings() { check_validation_error! { " @vertex - fn vertex(@location(0) input: vec4, more_input: f32) -> @location(0) vec4 { - return input + more_input; + fn vertex(@location(0) _input: vec4, more_input: f32) -> @location(0) vec4 { + return _input + more_input; } ": Err(naga::valid::ValidationError::EntryPoint { @@ -1046,8 +1046,8 @@ fn missing_bindings() { check_validation_error! { " @vertex - fn vertex(@location(0) input: vec4) -> vec4 { - return input; + fn vertex(@location(0) _input: vec4) -> vec4 { + return _input; } ": Err(naga::valid::ValidationError::EntryPoint { @@ -1067,8 +1067,8 @@ fn missing_bindings() { } @vertex - fn vertex(input: VertexIn) -> @location(0) vec4 { - return input.pos; + fn vertex(_input: VertexIn) -> @location(0) vec4 { + return _input.pos; } ": Err(naga::valid::ValidationError::EntryPoint { @@ -1213,13 +1213,13 @@ fn invalid_runtime_sized_arrays() { struct Outer { legit: i32, - unsized: Unsized + _unsized: Unsized } @group(0) @binding(0) var outer: Outer; fn fetch(i: i32) -> f32 { - return outer.unsized.arr[i]; + return outer._unsized.arr[i]; } ": Err(naga::valid::ValidationError::Type { @@ -1227,7 +1227,7 @@ fn invalid_runtime_sized_arrays() { error: naga::valid::TypeError::InvalidDynamicArray(member_name, _), .. }) - if struct_name == "Outer" && member_name == "unsized" + if struct_name == "Outer" && member_name == "_unsized" } } @@ -1238,8 +1238,8 @@ fn select() { fn select_pointers(which: bool) -> i32 { var x: i32 = 1; var y: i32 = 2; - let ptr = select(&x, &y, which); - return *ptr; + let p = select(&x, &y, which); + return *p; } ", " From 88fff4c028ccfeced4111cf10fa8ee0ce42c8cd1 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sat, 16 Apr 2022 15:06:00 +0200 Subject: [PATCH 1694/2212] add minimal-versions check to CI --- .github/workflows/pipeline.yml | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index a54d9a891..a4b4bc186 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -4,7 +4,7 @@ on: [push, pull_request] jobs: test-msrv: - name: Test MSRV + name: Test MSRV and dependencies minimal-versions runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -13,11 +13,12 @@ jobs: profile: minimal toolchain: "1.56.0" override: true - - uses: actions-rs/cargo@v1 - name: Test all features - with: - command: test - args: --all-features --workspace + - uses: taiki-e/install-action@cargo-hack + - uses: taiki-e/install-action@cargo-minimal-versions + # nightly is only used by cargo-minimal-versions to regenerate the lock file + - run: rustup toolchain add nightly --no-self-update + - name: Test all features + run: cargo minimal-versions test --all-features --workspace - name: Check snapshots run: git diff --exit-code -- tests/out test: From bddfc34299fb47ebaeda40549892ffa70f9ed3e3 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sat, 16 Apr 2022 15:09:56 +0200 Subject: [PATCH 1695/2212] fix minimal-versions of dependencies --- Cargo.toml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index abeee9fb5..39e51cf68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,9 +43,13 @@ name = "criterion" harness = false [dependencies] -arbitrary = { version = "1", features = ["derive"], optional = true } -bitflags = "1" +arbitrary = { version = "1.0.2", features = ["derive"], optional = true } +bitflags = "1.0.4" bit-set = "0.5" +termcolor = "1.0.4" +# remove termcolor dep when updating to the next version of codespan-reporting +# termcolor minimum version was wrong and was fixed in +# https://github.com/brendanzab/codespan/commit/e99c867339a877731437e7ee6a903a3d03b5439e codespan-reporting = { version = "0.11.0", optional = true } rustc-hash = "1.1.0" indexmap = "1.6" @@ -53,7 +57,7 @@ log = "0.4" num-traits = "0.2" spirv = { version = "0.2", optional = true } thiserror = "1.0.21" -serde = { version = "1.0", features = ["derive"], optional = true } +serde = { version = "1.0.103", features = ["derive"], optional = true } petgraph = { version ="0.6", optional = true } pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } From 743c8aa387cbfbd3c47e6097c8c2694b3f6ad0a0 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sun, 17 Apr 2022 19:46:48 +0200 Subject: [PATCH 1696/2212] update lexer to match more unicode characters --- Cargo.toml | 3 +- src/front/wgsl/lexer.rs | 65 ++++++++++++++++++++++++++++++++++------- 2 files changed, 57 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 39e51cf68..f65cefbcf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ serialize = ["serde", "indexmap/serde-1"] deserialize = ["serde", "indexmap/serde-1"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] -wgsl-in = ["codespan-reporting", "hexf-parse"] +wgsl-in = ["codespan-reporting", "hexf-parse", "unicode-id"] wgsl-out = [] hlsl-out = [] span = ["codespan-reporting"] @@ -61,6 +61,7 @@ serde = { version = "1.0.103", features = ["derive"], optional = true } petgraph = { version ="0.6", optional = true } pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } +unicode-id = { version = "0.3", optional = true } [dev-dependencies] bincode = "1" diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 140e4eab0..5203b9ba3 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -306,10 +306,6 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { } } '0'..='9' => consume_number(input), - '_' | 'a'..='z' | 'A'..='Z' => { - let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_'); - (Token::Word(word), rest) - } '"' => { let mut iter = chars.as_str().splitn(2, '"'); @@ -325,7 +321,7 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { input = chars.as_str(); match chars.next() { Some('/') => { - let _ = chars.position(|c| c == '\n' || c == '\r'); + let _ = chars.position(is_comment_end); (Token::Trivia, chars.as_str()) } Some('*') => { @@ -408,14 +404,51 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { (Token::Operation(cur), input) } } - ' ' | '\n' | '\r' | '\t' => { - let (_, rest) = consume_any(input, |c| c == ' ' || c == '\n' || c == '\r' || c == '\t'); + _ if is_blankspace(cur) => { + let (_, rest) = consume_any(input, is_blankspace); (Token::Trivia, rest) } + _ if is_word_start(cur) => { + let (word, rest) = consume_any(input, is_word_part); + (Token::Word(word), rest) + } _ => (Token::Unknown(cur), chars.as_str()), } } +/// Returns whether or not a char is a comment end +/// (Unicode Pattern_White_Space excluding U+0020, U+0009, U+200E and U+200F) +const fn is_comment_end(c: char) -> bool { + match c { + '\u{000a}'..='\u{000d}' | '\u{0085}' | '\u{2028}' | '\u{2029}' => true, + _ => false, + } +} + +/// Returns whether or not a char is a blankspace (Unicode Pattern_White_Space) +const fn is_blankspace(c: char) -> bool { + match c { + '\u{0020}' + | '\u{0009}'..='\u{000d}' + | '\u{0085}' + | '\u{200e}' + | '\u{200f}' + | '\u{2028}' + | '\u{2029}' => true, + _ => false, + } +} + +/// Returns whether or not a char is a word start (Unicode XID_Start + '_') +fn is_word_start(c: char) -> bool { + c == '_' || unicode_id::UnicodeID::is_id_start(c) +} + +/// Returns whether or not a char is a word part (Unicode XID_Continue) +fn is_word_part(c: char) -> bool { + unicode_id::UnicodeID::is_id_continue(c) +} + #[derive(Clone)] pub(super) struct Lexer<'a> { input: &'a str, @@ -674,11 +707,23 @@ fn test_tokens() { ], ); sub_test( - "æNoø", - &[Token::Unknown('æ'), Token::Word("No"), Token::Unknown('ø')], + "Δέλτα réflexion Кызыл 𐰓𐰏𐰇 朝焼け سلام 검정 שָׁלוֹם गुलाबी փիրուզ", + &[ + Token::Word("Δέλτα"), + Token::Word("réflexion"), + Token::Word("Кызыл"), + Token::Word("𐰓𐰏𐰇"), + Token::Word("朝焼け"), + Token::Word("سلام"), + Token::Word("검정"), + Token::Word("שָׁלוֹם"), + Token::Word("गुलाबी"), + Token::Word("փիրուզ"), + ], ); + sub_test("æNoø", &[Token::Word("æNoø")]); sub_test("No¾", &[Token::Word("No"), Token::Unknown('¾')]); - sub_test("No好", &[Token::Word("No"), Token::Unknown('好')]); + sub_test("No好", &[Token::Word("No好")]); sub_test("_No", &[Token::Word("_No")]); sub_test("\"\u{2}ПЀ\u{0}\"", &[Token::String("\u{2}ПЀ\u{0}")]); // https://github.com/gfx-rs/naga/issues/90 sub_test( From 340bfcc33a09146953c0b554638c05b4f61d8f65 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sun, 17 Apr 2022 19:54:34 +0200 Subject: [PATCH 1697/2212] remove unused code --- src/front/wgsl/lexer.rs | 22 +--------------------- src/front/wgsl/mod.rs | 6 ------ 2 files changed, 1 insertion(+), 27 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 5203b9ba3..095648e6a 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -271,15 +271,7 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { None => return (Token::End, input), }; match cur { - ':' => { - input = chars.as_str(); - if chars.next() == Some(':') { - (Token::DoubleColon, chars.as_str()) - } else { - (Token::Separator(cur), input) - } - } - ';' | ',' => (Token::Separator(cur), chars.as_str()), + ':' | ';' | ',' => (Token::Separator(cur), chars.as_str()), '.' => { let og_chars = chars.as_str(); match chars.next() { @@ -306,17 +298,6 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { } } '0'..='9' => consume_number(input), - '"' => { - let mut iter = chars.as_str().splitn(2, '"'); - - // splitn returns an iterator with at least one element, so unwrapping is fine - let quote_content = iter.next().unwrap(); - if let Some(rest) = iter.next() { - (Token::String(quote_content), rest) - } else { - (Token::UnterminatedString, quote_content) - } - } '/' => { input = chars.as_str(); match chars.next() { @@ -725,7 +706,6 @@ fn test_tokens() { sub_test("No¾", &[Token::Word("No"), Token::Unknown('¾')]); sub_test("No好", &[Token::Word("No好")]); sub_test("_No", &[Token::Word("_No")]); - sub_test("\"\u{2}ПЀ\u{0}\"", &[Token::String("\u{2}ПЀ\u{0}")]); // https://github.com/gfx-rs/naga/issues/90 sub_test( "*/*/***/*//=/*****//", &[ diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2ea486309..2bd20c1b3 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -58,11 +58,9 @@ pub enum NumberType { #[derive(Copy, Clone, Debug, PartialEq)] pub enum Token<'a> { Separator(char), - DoubleColon, Paren(char), Attribute, Number { value: &'a str, ty: NumberType }, - String(&'a str), Word(&'a str), Operation(char), LogicalOperation(char), @@ -72,7 +70,6 @@ pub enum Token<'a> { DecrementOperation, Arrow, Unknown(char), - UnterminatedString, UnterminatedBlockComment, Trivia, End, @@ -191,13 +188,11 @@ impl<'a> Error<'a> { ExpectedToken::Token(token) => { match token { Token::Separator(c) => format!("'{}'", c), - Token::DoubleColon => "'::'".to_string(), Token::Paren(c) => format!("'{}'", c), Token::Attribute => "@".to_string(), Token::Number { value, .. } => { format!("number ({})", value) } - Token::String(s) => format!("string literal ('{}')", s), Token::Word(s) => s.to_string(), Token::Operation(c) => format!("operation ('{}')", c), Token::LogicalOperation(c) => format!("logical operation ('{}')", c), @@ -208,7 +203,6 @@ impl<'a> Error<'a> { Token::DecrementOperation => "decrement operation".to_string(), Token::Arrow => "->".to_string(), Token::Unknown(c) => format!("unknown ('{}')", c), - Token::UnterminatedString => "unterminated string".to_string(), Token::UnterminatedBlockComment => "unterminated block comment".to_string(), Token::Trivia => "trivia".to_string(), Token::End => "end".to_string(), From 90b3c18faea19d1a534d6215db686ca4e2028081 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sun, 17 Apr 2022 19:59:33 +0200 Subject: [PATCH 1698/2212] fix being able to match `~=` as LogicalOperation --- src/front/wgsl/lexer.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 095648e6a..2ecafb96a 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -366,7 +366,8 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { (Token::Operation(cur), input) } } - '!' | '~' => { + '~' => (Token::Operation(cur), chars.as_str()), + '!' => { input = chars.as_str(); if chars.next() == Some('=') { (Token::LogicalOperation(cur), chars.as_str()) From 0e2bb0194b029c388a70403d36a82d5fc774d307 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sun, 17 Apr 2022 20:02:18 +0200 Subject: [PATCH 1699/2212] refactor consume_token fn body --- src/front/wgsl/lexer.rs | 95 ++++++++++++++++++----------------------- src/front/wgsl/mod.rs | 2 - 2 files changed, 41 insertions(+), 56 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 2ecafb96a..2b2c2e144 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -264,11 +264,11 @@ fn consume_number(input: &str) -> (Token, &str) { ) } -fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { +fn consume_token(input: &str, generic: bool) -> (Token<'_>, &str) { let mut chars = input.chars(); let cur = match chars.next() { Some(c) => c, - None => return (Token::End, input), + None => return (Token::End, ""), }; match cur { ':' | ';' | ',' => (Token::Separator(cur), chars.as_str()), @@ -282,108 +282,95 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) { '@' => (Token::Attribute, chars.as_str()), '(' | ')' | '{' | '}' | '[' | ']' => (Token::Paren(cur), chars.as_str()), '<' | '>' => { - input = chars.as_str(); - let next = chars.next(); - if next == Some('=') && !generic { - (Token::LogicalOperation(cur), chars.as_str()) - } else if next == Some(cur) && !generic { - input = chars.as_str(); - if chars.next() == Some('=') { - (Token::AssignmentOperation(cur), chars.as_str()) - } else { - (Token::ShiftOperation(cur), input) + let og_chars = chars.as_str(); + match chars.next() { + Some('=') if !generic => (Token::LogicalOperation(cur), chars.as_str()), + Some(c) if c == cur && !generic => { + let og_chars = chars.as_str(); + match chars.next() { + Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), + _ => (Token::ShiftOperation(cur), og_chars), + } } - } else { - (Token::Paren(cur), input) + _ => (Token::Paren(cur), og_chars), } } '0'..='9' => consume_number(input), '/' => { - input = chars.as_str(); + let og_chars = chars.as_str(); match chars.next() { Some('/') => { let _ = chars.position(is_comment_end); (Token::Trivia, chars.as_str()) } Some('*') => { - input = chars.as_str(); - let mut depth = 1; - let mut prev = '\0'; + let mut prev = None; for c in &mut chars { match (prev, c) { - ('*', '/') => { - prev = '\0'; + (Some('*'), '/') => { + prev = None; depth -= 1; if depth == 0 { - break; + return (Token::Trivia, chars.as_str()); } } - ('/', '*') => { - prev = '\0'; + (Some('/'), '*') => { + prev = None; depth += 1; } _ => { - prev = c; + prev = Some(c); } } } - if depth > 0 { - (Token::UnterminatedBlockComment, input) - } else { - (Token::Trivia, chars.as_str()) - } + (Token::End, "") } Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), - _ => (Token::Operation(cur), input), + _ => (Token::Operation(cur), og_chars), } } '-' => { - let sub_input = chars.as_str(); + let og_chars = chars.as_str(); match chars.next() { Some('>') => (Token::Arrow, chars.as_str()), Some('0'..='9' | '.') => consume_number(input), Some('-') => (Token::DecrementOperation, chars.as_str()), Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), - _ => (Token::Operation(cur), sub_input), + _ => (Token::Operation(cur), og_chars), } } '+' => { - input = chars.as_str(); + let og_chars = chars.as_str(); match chars.next() { Some('+') => (Token::IncrementOperation, chars.as_str()), Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), - _ => (Token::Operation(cur), input), + _ => (Token::Operation(cur), og_chars), } } '*' | '%' | '^' => { - input = chars.as_str(); - if chars.next() == Some('=') { - (Token::AssignmentOperation(cur), chars.as_str()) - } else { - (Token::Operation(cur), input) + let og_chars = chars.as_str(); + match chars.next() { + Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), + _ => (Token::Operation(cur), og_chars), } } '~' => (Token::Operation(cur), chars.as_str()), - '!' => { - input = chars.as_str(); - if chars.next() == Some('=') { - (Token::LogicalOperation(cur), chars.as_str()) - } else { - (Token::Operation(cur), input) + '=' | '!' => { + let og_chars = chars.as_str(); + match chars.next() { + Some('=') => (Token::LogicalOperation(cur), chars.as_str()), + _ => (Token::Operation(cur), og_chars), } } - '=' | '&' | '|' => { - input = chars.as_str(); - let next = chars.next(); - if next == Some(cur) { - (Token::LogicalOperation(cur), chars.as_str()) - } else if next == Some('=') { - (Token::AssignmentOperation(cur), chars.as_str()) - } else { - (Token::Operation(cur), input) + '&' | '|' => { + let og_chars = chars.as_str(); + match chars.next() { + Some(c) if c == cur => (Token::LogicalOperation(cur), chars.as_str()), + Some('=') => (Token::AssignmentOperation(cur), chars.as_str()), + _ => (Token::Operation(cur), og_chars), } } _ if is_blankspace(cur) => { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2bd20c1b3..c7f5abb2d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -70,7 +70,6 @@ pub enum Token<'a> { DecrementOperation, Arrow, Unknown(char), - UnterminatedBlockComment, Trivia, End, } @@ -203,7 +202,6 @@ impl<'a> Error<'a> { Token::DecrementOperation => "decrement operation".to_string(), Token::Arrow => "->".to_string(), Token::Unknown(c) => format!("unknown ('{}')", c), - Token::UnterminatedBlockComment => "unterminated block comment".to_string(), Token::Trivia => "trivia".to_string(), Token::End => "end".to_string(), } From 94467c770fe9a0a6d451bdcbf05040e5ca0a0be5 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 18 Apr 2022 11:12:50 +0200 Subject: [PATCH 1700/2212] fix bitflags min version --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index f65cefbcf..2e0cca822 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,7 +44,7 @@ harness = false [dependencies] arbitrary = { version = "1.0.2", features = ["derive"], optional = true } -bitflags = "1.0.4" +bitflags = "1.0.5" bit-set = "0.5" termcolor = "1.0.4" # remove termcolor dep when updating to the next version of codespan-reporting From 0aa6b6902b931afe1d8aaa4ef3e90bfe98538ead Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 17 Apr 2022 14:56:37 -0700 Subject: [PATCH 1701/2212] [hlsl-out] Flesh out matrix handling documentation. --- src/back/hlsl/mod.rs | 99 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 85 insertions(+), 14 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index f51d49db3..7ecfc0fc9 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -6,29 +6,100 @@ Backend for [HLSL][hlsl] (High-Level Shading Language). - 5.1 - 6.0 -# General Matrix Note +# Layout of values in `uniform` buffers -All matrix construction/deconstruction is row based in HLSL. This means that when -we construct a matrix from column vectors, our matrix will be implicitly transposed. -The inverse transposition happens when we call `[0]` to get the zeroth column vector. +WGSL's ["Internal Layout of Values"][ilov] rules specify how each WGSL +type should be stored in `uniform` and `storage` buffers. The HLSL we +generate must access values in that form, even when it is not what +HLSL would use normally. -Because all of our matrices are implicitly transposed, we flip arguments to `mul`. `mat * vec` -becomes `vec * mat`, etc. This acts as the inverse transpose making the results identical. +The rules described here only apply to WGSL `uniform` variables. WGSL +`storage` buffers are translated as HLSL `ByteAddressBuffers`, for +which we generate `Load` and `Store` method calls with explicit byte +offsets. WGSL pipeline inputs must be scalars or vectors; they cannot +be matrices, which is where the interesting problems arise. -The only time we don't get this implicit transposition is when reading matrices from Uniforms/Push Constants. -To deal with this, we add `row_major` to all declarations of matrices in Uniforms/Push Constants. +## Row- and column-major ordering for matrices -Finally because all of our matrices are transposed, if you use `mat3x4`, it'll become `float3x4` in HLSL -(HLSL has inverted col/row notation). +WGSL specifies that matrices in uniform buffers are stored in +column-major order. This matches HLSL's default, so one might expect +things to be straightforward. Unfortunately, WGSL and HLSL disagree on +what indexing a matrix means: in WGSL, `m[i]` retrieves the `i`'th +*column* of `m`, whereas in HLSL it retrieves the `i`'th *row*. We +want to avoid translating `m[i]` into some complicated reassembly of a +vector from individually fetched components, so this is a problem. -# Matrix struct member of the form `matCx2` Note +However, with a bit of trickery, it is possible to use HLSL's `m[i]` +as the translation of WGSL's `m[i]`: -Struct member matrices of the form `matCx2` are translated to a sequence of C `vec2`s due to -differences in alignment between WGSL and HLSL for uniform buffers. +- We declare all matrices in uniform buffers in HLSL with the + `row_major` qualifier, and transpose the row and column counts: a + WGSL `mat3x4`, say, becomes an HLSL `row_major float3x4`. (Note + that WGSL and HLSL type names put the row and column in reverse + order.) Since the HLSL type is the transpose of how WebGPU directs + the user to store the data, HLSL will load all matrices transposed. -Accesses to these matrices are handled by injected functions. +- Since matrices are transposed, an HLSL indexing expression retrieves + the "columns" of the intended WGSL value, as desired. + +- For vector-matrix multiplication, since `mul(transpose(m), v)` is + equivalent to `mul(v, m)` (note the reversal of the arguments), and + `mul(v, transpose(m))` is equivalent to `mul(m, v)`, we can + translate WGSL `m * v` and `v * m` to HLSL by simply reversing the + arguments to `mul`. + +## Padding in two-row matrices + +An HLSL `row_major floatKx2` matrix has padding between its rows that +the WGSL `matKx2` matrix it represents does not. HLSL stores all +matrix rows [aligned on 16-byte boundaries][16bb], whereas WGSL says +that the columns of a `matKx2` need only be [aligned as required +for `vec2`][ilov], which is [eight-byte alignment][8bb]. + +To compensate for this, any time a `matKx2` appears in a WGSL +`uniform` variable, whether directly as the variable's type or as a +struct member, we actually emit `K` separate `float2` members, and +assemble/disassemble the matrix from its columns (in WGSL; rows in +HLSL) upon load and store. + +For example, the following WGSL struct type: + +```ignore +struct Baz { + m: mat3x2, +} +``` + +is rendered as the HLSL struct type: + +```ignore +struct Baz { + float2 m_0; float2 m_1; float2 m_2; +}; +``` + +The `wrapped_struct_matrix` functions in `help.rs` generate HLSL +helper functions to access such members, converting between the stored +form and the HLSL matrix types appropriately. For example, for reading +the member `m` of the `Baz` struct above, we emit: + +```ignore +float3x2 GetMatmOnBaz(Baz obj) { + return float3x2(obj.m_0, obj.m_1, obj.m_2); +} +``` + +We also emit an analogous `Set` function, as well as functions for +accessing individual columns by dynamic index. + +At present, we do not generate correct HLSL when `matCx2` us used +directly as the type of a WGSL `uniform` global ([#1837]). [hlsl]: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl +[ilov]: https://gpuweb.github.io/gpuweb/wgsl/#internal-value-layout +[16bb]: https://github.com/microsoft/DirectXShaderCompiler/wiki/Buffer-Packing#constant-buffer-packing +[8bb]: https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size +[#1837]: https://github.com/gfx-rs/naga/issues/1837 */ mod conv; From 850565243d1d0d03215f13246c94d63e1d4c51cd Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 18 Apr 2022 21:51:38 +0200 Subject: [PATCH 1702/2212] replace unicode-id with unicode-xid --- Cargo.toml | 7 +++++-- src/front/wgsl/lexer.rs | 4 ++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2e0cca822..76e30f9cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ serialize = ["serde", "indexmap/serde-1"] deserialize = ["serde", "indexmap/serde-1"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] -wgsl-in = ["codespan-reporting", "hexf-parse", "unicode-id"] +wgsl-in = ["codespan-reporting", "hexf-parse", "unicode-xid"] wgsl-out = [] hlsl-out = [] span = ["codespan-reporting"] @@ -61,7 +61,10 @@ serde = { version = "1.0.103", features = ["derive"], optional = true } petgraph = { version ="0.6", optional = true } pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } -unicode-id = { version = "0.3", optional = true } +# update unicode-xid to the next version since it has been updated to unicode v14 +# (but has no release that includes it yet) +# https://github.com/unicode-rs/unicode-xid/pull/27 +unicode-xid = { version = "0.2.2", optional = true } [dev-dependencies] bincode = "1" diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 2b2c2e144..91986d552 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -410,12 +410,12 @@ const fn is_blankspace(c: char) -> bool { /// Returns whether or not a char is a word start (Unicode XID_Start + '_') fn is_word_start(c: char) -> bool { - c == '_' || unicode_id::UnicodeID::is_id_start(c) + c == '_' || unicode_xid::UnicodeXID::is_xid_start(c) } /// Returns whether or not a char is a word part (Unicode XID_Continue) fn is_word_part(c: char) -> bool { - unicode_id::UnicodeID::is_id_continue(c) + unicode_xid::UnicodeXID::is_xid_continue(c) } #[derive(Clone)] From ad28396851aa4229d228b16594bba7a3fd8d84a3 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Tue, 19 Apr 2022 14:23:07 -0400 Subject: [PATCH 1703/2212] Implement Binding Arrays (#1845) --- src/back/glsl/mod.rs | 3 +- src/back/hlsl/mod.rs | 3 + src/back/hlsl/writer.rs | 44 +- src/back/msl/mod.rs | 11 + src/back/msl/writer.rs | 94 ++++- src/back/spv/block.rs | 130 +++++- src/back/spv/image.rs | 3 + src/back/spv/mod.rs | 27 ++ src/back/spv/recyclable.rs | 7 + src/back/spv/writer.rs | 73 +++- src/back/wgsl/writer.rs | 16 + src/front/wgsl/mod.rs | 162 ++++--- src/lib.rs | 2 + src/proc/index.rs | 2 +- src/proc/layouter.rs | 2 +- src/proc/mod.rs | 2 +- src/proc/namer.rs | 2 +- src/proc/typifier.rs | 2 + src/valid/analyzer.rs | 115 ++++- src/valid/expression.rs | 83 +++- src/valid/function.rs | 25 +- src/valid/interface.rs | 11 +- src/valid/mod.rs | 11 +- src/valid/type.rs | 1 + tests/in/binding-arrays.param.ron | 39 ++ tests/in/binding-arrays.wgsl | 108 +++++ tests/out/hlsl/binding-arrays.hlsl | 183 ++++++++ tests/out/hlsl/binding-arrays.hlsl.config | 3 + tests/out/msl/binding-arrays.msl | 160 +++++++ tests/out/spv/binding-arrays.spvasm | 487 ++++++++++++++++++++++ tests/out/wgsl/binding-arrays.wgsl | 170 ++++++++ tests/snapshots.rs | 9 + 32 files changed, 1853 insertions(+), 137 deletions(-) create mode 100644 tests/in/binding-arrays.param.ron create mode 100644 tests/in/binding-arrays.wgsl create mode 100644 tests/out/hlsl/binding-arrays.hlsl create mode 100644 tests/out/hlsl/binding-arrays.hlsl.config create mode 100644 tests/out/msl/binding-arrays.msl create mode 100644 tests/out/spv/binding-arrays.spvasm create mode 100644 tests/out/wgsl/binding-arrays.wgsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 4d3c834fc..699348f05 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -785,7 +785,8 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Pointer { .. } | TypeInner::Struct { .. } | TypeInner::Image { .. } - | TypeInner::Sampler { .. } => { + | TypeInner::Sampler { .. } + | TypeInner::BindingArray { .. } => { return Err(Error::Custom(format!("Unable to write type {:?}", inner))) } } diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 7ecfc0fc9..db027f776 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -119,6 +119,8 @@ use crate::proc; pub struct BindTarget { pub space: u8, pub register: u32, + /// If the binding is an unsized binding array, this overrides the size. + pub binding_array_size: Option, } // Using `BTreeMap` instead of `HashMap` so that we can hash itself. @@ -214,6 +216,7 @@ impl Options { None if self.fake_missing_bindings => Ok(BindTarget { space: res_binding.group as u8, register: res_binding.binding, + binding_array_size: None, }), None => Err(EntryPointError::MissingBinding(res_binding.clone())), } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 9285687ba..97a141e42 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -603,7 +603,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { register } crate::AddressSpace::Handle => { - let register = match *inner { + let handle_ty = match *inner { + TypeInner::BindingArray { ref base, .. } => &module.types[*base].inner, + _ => inner, + }; + + let register = match *handle_ty { TypeInner::Sampler { .. } => "s", // all storage textures are UAV, unconditionally TypeInner::Image { @@ -624,6 +629,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if let Some(ref binding) = global.binding { // this was already resolved earlier when we started evaluating an entry point. let bt = self.options.resolve_resource_binding(binding).unwrap(); + + // need to write the binding array size if the type was emitted with `write_type` + if let TypeInner::BindingArray { base, size, .. } = module.types[global.ty].inner { + if let Some(overridden_size) = bt.binding_array_size { + write!(self.out, "[{}]", overridden_size)?; + } else { + self.write_array_size(module, base, size)?; + } + } + write!(self.out, " : register({}{}", register_ty, bt.register)?; if bt.space != 0 { write!(self.out, ", space{}", bt.space)?; @@ -732,7 +747,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let size = module.constants[const_handle].to_array_length().unwrap(); write!(self.out, "{}", size)?; } - crate::ArraySize::Dynamic => unreachable!(), + crate::ArraySize::Dynamic => {} } write!(self.out, "]")?; @@ -874,7 +889,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *inner { TypeInner::Struct { .. } => write!(self.out, "{}", self.names[&NameKey::Type(ty)])?, // hlsl array has the size separated from the base type - TypeInner::Array { base, .. } => self.write_type(module, base)?, + TypeInner::Array { base, .. } | TypeInner::BindingArray { base, .. } => { + self.write_type(module, base)? + } ref other => self.write_value_type(module, other)?, } @@ -933,7 +950,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // HLSL arrays are written as `type name[size]` // Current code is written arrays only as `[size]` // Base `type` and `name` should be written outside - TypeInner::Array { base, size, .. } => { + TypeInner::Array { base, size, .. } | TypeInner::BindingArray { base, size } => { self.write_array_size(module, base, size)?; } _ => { @@ -1793,9 +1810,27 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { { // do nothing, the chain is written on `Load`/`Store` } else { + let base_ty_res = &func_ctx.info[base].ty; + let resolved = base_ty_res.inner_with(&module.types); + + let non_uniform_qualifier = match *resolved { + TypeInner::BindingArray { .. } => { + let uniformity = &func_ctx.info[index].uniformity; + + uniformity.non_uniform_result.is_some() + } + _ => false, + }; + self.write_expr(module, base, func_ctx)?; write!(self.out, "[")?; + if non_uniform_qualifier { + write!(self.out, "NonUniformResourceIndex(")?; + } self.write_expr(module, index, func_ctx)?; + if non_uniform_qualifier { + write!(self.out, ")")?; + } write!(self.out, "]")?; } } @@ -1852,6 +1887,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } TypeInner::Matrix { .. } | TypeInner::Array { .. } + | TypeInner::BindingArray { .. } | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, TypeInner::Struct { .. } => { // This will never panic in case the type is a `Struct`, this is not true diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 2ba436491..a8ed2dd0d 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -57,6 +57,8 @@ pub struct BindTarget { pub buffer: Option, pub texture: Option, pub sampler: Option, + /// If the binding is an unsized binding array, this overrides the size. + pub binding_array_size: Option, pub mutable: bool, } @@ -319,6 +321,7 @@ impl Options { buffer: Some(slot), texture: None, sampler: None, + binding_array_size: None, mutable: false, })), None if self.fake_missing_bindings => Ok(ResolvedBinding::User { @@ -340,6 +343,7 @@ impl Options { buffer: Some(slot), texture: None, sampler: None, + binding_array_size: None, mutable: false, })), None if self.fake_missing_bindings => Ok(ResolvedBinding::User { @@ -363,6 +367,13 @@ impl ResolvedBinding { } } + const fn as_bind_target(&self) -> Option<&BindTarget> { + match *self { + Self::Resource(ref target) => Some(target), + _ => None, + } + } + fn try_fmt(&self, out: &mut W) -> Result<(), Error> { write!(out, " [[")?; match *self { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 65cf23656..e365f70d4 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -70,15 +70,16 @@ const CLAMPED_LOD_LOAD_PREFIX: &str = "clamped_lod_e"; struct TypeContext<'a> { handle: Handle, - arena: &'a crate::UniqueArena, + module: &'a crate::Module, names: &'a FastHashMap, access: crate::StorageAccess, + binding: Option<&'a super::ResolvedBinding>, first_time: bool, } impl<'a> Display for TypeContext<'a> { fn fmt(&self, out: &mut Formatter<'_>) -> Result<(), FmtError> { - let ty = &self.arena[self.handle]; + let ty = &self.module.types[self.handle]; if ty.needs_alias() && !self.first_time { let name = &self.names[&NameKey::Type(self.handle)]; return write!(out, "{}", name); @@ -201,6 +202,39 @@ impl<'a> Display for TypeContext<'a> { crate::TypeInner::Sampler { comparison: _ } => { write!(out, "{}::sampler", NAMESPACE) } + crate::TypeInner::BindingArray { base, size } => { + let base_tyname = Self { + handle: base, + first_time: false, + ..*self + }; + + if let Some(&super::ResolvedBinding::Resource(super::BindTarget { + binding_array_size: Some(override_size), + .. + })) = self.binding + { + write!( + out, + "{}::array<{}, {}>", + NAMESPACE, base_tyname, override_size + ) + } else if let crate::ArraySize::Constant(size) = size { + let constant_ctx = ConstantContext { + handle: size, + arena: &self.module.constants, + names: self.names, + first_time: false, + }; + write!( + out, + "{}::array<{}, {}>", + NAMESPACE, base_tyname, constant_ctx + ) + } else { + unreachable!("metal requires all arrays be constant sized"); + } + } } } } @@ -210,6 +244,7 @@ struct TypedGlobalVariable<'a> { names: &'a FastHashMap, handle: Handle, usage: valid::GlobalUse, + binding: Option<&'a super::ResolvedBinding>, reference: bool, } @@ -225,14 +260,24 @@ impl<'a> TypedGlobalVariable<'a> { class: crate::ImageClass::Storage { access, .. }, .. } => access, + crate::TypeInner::BindingArray { base, .. } => { + match self.module.types[base].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Storage { access, .. }, + .. + } => access, + _ => crate::StorageAccess::default(), + } + } _ => crate::StorageAccess::default(), }, }; let ty_name = TypeContext { handle: var.ty, - arena: &self.module.types, + module: self.module, names: self.names, access: storage_access, + binding: self.binding, first_time: false, }; @@ -452,7 +497,7 @@ impl crate::Type { // composite types are better to be aliased, regardless of the name Ti::Struct { .. } | Ti::Array { .. } => true, // handle types may be different, depending on the global var access, so we always inline them - Ti::Image { .. } | Ti::Sampler { .. } => false, + Ti::Image { .. } | Ti::Sampler { .. } | Ti::BindingArray { .. } => false, } } } @@ -2269,9 +2314,10 @@ impl Writer { TypeResolution::Handle(ty_handle) => { let ty_name = TypeContext { handle: ty_handle, - arena: &context.module.types, + module: context.module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; write!(self.out, "{}", ty_name)?; @@ -2863,9 +2909,10 @@ impl Writer { } => { let base_name = TypeContext { handle: base, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; @@ -2926,9 +2973,10 @@ impl Writer { None => { let base_name = TypeContext { handle: member.ty, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; writeln!( @@ -2956,9 +3004,10 @@ impl Writer { _ => { let ty_name = TypeContext { handle, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: true, }; writeln!(self.out, "typedef {} {};", ty_name, name)?; @@ -3015,9 +3064,10 @@ impl Writer { let name = &self.names[&NameKey::Constant(handle)]; let ty_name = TypeContext { handle: ty, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; write!(self.out, "constant {} {} = {{", ty_name, name,)?; @@ -3150,9 +3200,10 @@ impl Writer { Some(ref result) => { let ty_name = TypeContext { handle: result.ty, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; write!(self.out, "{}", ty_name)?; @@ -3167,9 +3218,10 @@ impl Writer { let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; let param_type_name = TypeContext { handle: arg.ty, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; let separator = separate( @@ -3192,6 +3244,7 @@ impl Writer { names: &self.names, handle, usage: fun_info[handle], + binding: None, reference: true, }; let separator = @@ -3214,9 +3267,10 @@ impl Writer { for (local_handle, local) in fun.local_variables.iter() { let ty_name = TypeContext { handle: local.ty, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; @@ -3377,9 +3431,10 @@ impl Writer { let name = &self.names[name_key]; let ty_name = TypeContext { handle: ty, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; let resolved = options.resolve_local_binding(binding, in_mode)?; @@ -3420,9 +3475,10 @@ impl Writer { for (name, ty, binding) in result_members { let ty_name = TypeContext { handle: ty, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: true, }; let binding = binding.ok_or(Error::Validation)?; @@ -3521,9 +3577,10 @@ impl Writer { }; let ty_name = TypeContext { handle: ty, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; let resolved = options.resolve_local_binding(binding, in_mode)?; @@ -3572,6 +3629,7 @@ impl Writer { names: &self.names, handle, usage, + binding: resolved.as_ref(), reference: true, }; let separator = if is_first_argument { @@ -3632,6 +3690,7 @@ impl Writer { names: &self.names, handle, usage, + binding: None, reference: false, }; write!(self.out, "{}", back::INDENT)?; @@ -3733,9 +3792,10 @@ impl Writer { let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; let ty_name = TypeContext { handle: local.ty, - arena: &module.types, + module, names: &self.names, access: crate::StorageAccess::empty(), + binding: None, first_time: false, }; write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; @@ -3855,7 +3915,7 @@ fn test_stack_size() { let stack_size = addresses.end - addresses.start; // check the size (in debug only) // last observed macOS value: 19152 (CI) - if !(11000..=20000).contains(&stack_size) { + if !(9500..=20000).contains(&stack_size) { panic!("`put_block` stack size {} has changed!", stack_size); } } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index c40ed4fbe..1bce7d271 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -173,7 +173,14 @@ impl<'w> BlockContext<'w> { /// thing in one fell swoop. fn is_intermediate(&self, expr_handle: Handle) -> bool { match self.ir_function.expressions[expr_handle] { - crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => true, + crate::Expression::GlobalVariable(handle) => { + let ty = self.ir_module.global_variables[handle].ty; + match self.ir_module.types[ty].inner { + crate::TypeInner::BindingArray { .. } => false, + _ => true, + } + } + crate::Expression::LocalVariable(_) => true, crate::Expression::FunctionArgument(index) => { let arg = &self.ir_function.arguments[index as usize]; self.ir_module.types[arg.ty].inner.pointer_space().is_some() @@ -200,9 +207,53 @@ impl<'w> BlockContext<'w> { 0 } crate::Expression::Access { base, index } => { - let base_ty = self.fun_info[base].ty.inner_with(&self.ir_module.types); - match *base_ty { - crate::TypeInner::Vector { .. } => (), + let base_ty_inner = self.fun_info[base].ty.inner_with(&self.ir_module.types); + match *base_ty_inner { + crate::TypeInner::Vector { .. } => { + self.write_vector_access(expr_handle, base, index, block)? + } + crate::TypeInner::BindingArray { + base: binding_type, .. + } => { + let binding_array_false_pointer = LookupType::Local(LocalType::Pointer { + base: binding_type, + class: spirv::StorageClass::UniformConstant, + }); + + let result_id = match self.write_expression_pointer( + expr_handle, + block, + Some(binding_array_false_pointer), + )? { + ExpressionPointer::Ready { pointer_id } => pointer_id, + ExpressionPointer::Conditional { .. } => { + return Err(Error::FeatureNotImplemented( + "Texture array out-of-bounds handling", + )); + } + }; + + let binding_type_id = self.get_type_id(LookupType::Handle(binding_type)); + + let load_id = self.gen_id(); + block.body.push(Instruction::load( + binding_type_id, + load_id, + result_id, + None, + )); + + if self.fun_info[index].uniformity.non_uniform_result.is_some() { + self.writer.require_any( + "NonUniformEXT", + &[spirv::Capability::ShaderNonUniform], + )?; + self.writer.use_extension("SPV_EXT_descriptor_indexing"); + self.writer + .decorate(load_id, spirv::Decoration::NonUniform, &[]); + } + load_id + } ref other => { log::error!( "Unable to access base {:?} of type {:?}", @@ -213,9 +264,7 @@ impl<'w> BlockContext<'w> { "only vectors may be dynamically indexed by value", )); } - }; - - self.write_vector_access(expr_handle, base, index, block)? + } } crate::Expression::AccessIndex { base, index: _ } if self.is_intermediate(base) => { // See `is_intermediate`; we'll handle this later in @@ -242,6 +291,39 @@ impl<'w> BlockContext<'w> { )); id } + crate::TypeInner::BindingArray { + base: binding_type, .. + } => { + let binding_array_false_pointer = LookupType::Local(LocalType::Pointer { + base: binding_type, + class: spirv::StorageClass::UniformConstant, + }); + + let result_id = match self.write_expression_pointer( + expr_handle, + block, + Some(binding_array_false_pointer), + )? { + ExpressionPointer::Ready { pointer_id } => pointer_id, + ExpressionPointer::Conditional { .. } => { + return Err(Error::FeatureNotImplemented( + "Texture array out-of-bounds handling", + )); + } + }; + + let binding_type_id = self.get_type_id(LookupType::Handle(binding_type)); + + let load_id = self.gen_id(); + block.body.push(Instruction::load( + binding_type_id, + load_id, + result_id, + None, + )); + + load_id + } ref other => { log::error!("Unable to access index of {:?}", other); return Err(Error::FeatureNotImplemented("access index for type")); @@ -776,7 +858,7 @@ impl<'w> BlockContext<'w> { } crate::Expression::LocalVariable(variable) => self.function.variables[&variable].id, crate::Expression::Load { pointer } => { - match self.write_expression_pointer(pointer, block)? { + match self.write_expression_pointer(pointer, block, None)? { ExpressionPointer::Ready { pointer_id } => { let id = self.gen_id(); let atomic_space = @@ -1100,15 +1182,26 @@ impl<'w> BlockContext<'w> { /// /// Emit any needed bounds-checking expressions to `block`. /// + /// Some cases we need to generate a different return type than what the IR gives us. + /// This is because pointers to binding arrays don't exist in the IR, but we need to + /// create them to create an access chain in SPIRV. + /// /// On success, the return value is an [`ExpressionPointer`] value; see the /// documentation for that type. fn write_expression_pointer( &mut self, mut expr_handle: Handle, block: &mut Block, + return_type_override: Option, ) -> Result { let result_lookup_ty = match self.fun_info[expr_handle].ty { - TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), + TypeResolution::Handle(ty_handle) => match return_type_override { + // We use the return type override as a special case for binding arrays as the OpAccessChain + // needs to return a pointer, but indexing into a binding array just gives you the type of + // the binding in the IR. + Some(ty) => ty, + None => LookupType::Handle(ty_handle), + }, TypeResolution::Value(ref inner) => LookupType::Local(make_local(inner).unwrap()), }; let result_type_id = self.get_type_id(result_lookup_ty); @@ -1612,7 +1705,7 @@ impl<'w> BlockContext<'w> { } crate::Statement::Store { pointer, value } => { let value_id = self.cached[value]; - match self.write_expression_pointer(pointer, &mut block)? { + match self.write_expression_pointer(pointer, &mut block, None)? { ExpressionPointer::Ready { pointer_id } => { let atomic_space = match *self.fun_info[pointer] .ty @@ -1702,14 +1795,15 @@ impl<'w> BlockContext<'w> { self.cached[result] = id; - let pointer_id = match self.write_expression_pointer(pointer, &mut block)? { - ExpressionPointer::Ready { pointer_id } => pointer_id, - ExpressionPointer::Conditional { .. } => { - return Err(Error::FeatureNotImplemented( - "Atomics out-of-bounds handling", - )); - } - }; + let pointer_id = + match self.write_expression_pointer(pointer, &mut block, None)? { + ExpressionPointer::Ready { pointer_id } => pointer_id, + ExpressionPointer::Conditional { .. } => { + return Err(Error::FeatureNotImplemented( + "Atomics out-of-bounds handling", + )); + } + }; let space = self.fun_info[pointer] .ty diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 06eb21cb9..e070cd617 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -365,6 +365,9 @@ impl<'w> BlockContext<'w> { crate::Expression::FunctionArgument(i) => { self.function.parameters[i as usize].handle_id } + crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => { + self.cached[expr_handle] + } ref other => unreachable!("Unexpected image expression {:?}", other), }; diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 3ae577e79..544f5ca4f 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -287,6 +287,14 @@ enum LocalType { image_type_id: Word, }, Sampler, + PointerToBindingArray { + base: Handle, + size: u64, + }, + BindingArray { + base: Handle, + size: u64, + }, } /// A type encountered during SPIR-V generation. @@ -567,6 +575,9 @@ pub struct Writer { /// that. capabilities_used: crate::FastHashSet, + /// The set of spirv extensions used. + extensions_used: crate::FastHashSet<&'static str>, + debugs: Vec, annotations: Vec, flags: WriterFlags, @@ -579,6 +590,7 @@ pub struct Writer { constant_ids: Vec, cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>, global_variables: Vec, + binding_map: BindingMap, // Cached expressions are only meaningful within a BlockContext, but we // retain the table here between functions to save heap allocations. @@ -607,6 +619,17 @@ bitflags::bitflags! { } } +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct BindingInfo { + /// If the binding is an unsized binding array, this overrides the size. + pub binding_array_size: Option, +} + +// Using `BTreeMap` instead of `HashMap` so that we can hash itself. +pub type BindingMap = std::collections::BTreeMap; + #[derive(Debug, Clone)] pub struct Options { /// (Major, Minor) target version of the SPIR-V. @@ -615,6 +638,9 @@ pub struct Options { /// Configuration flags for the writer. pub flags: WriterFlags, + /// Map of resources to information about the binding. + pub binding_map: BindingMap, + /// If given, the set of capabilities modules are allowed to use. Code that /// requires capabilities beyond these is rejected with an error. /// @@ -637,6 +663,7 @@ impl Default for Options { Options { lang_version: (1, 0), flags, + binding_map: BindingMap::default(), capabilities: None, bounds_check_policies: crate::proc::BoundsCheckPolicies::default(), } diff --git a/src/back/spv/recyclable.rs b/src/back/spv/recyclable.rs index 6cedcd078..49f3a0274 100644 --- a/src/back/spv/recyclable.rs +++ b/src/back/spv/recyclable.rs @@ -51,3 +51,10 @@ impl Recyclable for std::collections::HashSet { self } } + +impl Recyclable for std::collections::BTreeMap { + fn recycle(mut self) -> Self { + self.clear(); + self + } +} diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index dd1cc58c8..a629d5beb 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -7,6 +7,7 @@ use super::{ }; use crate::{ arena::{Handle, UniqueArena}, + back::spv::BindingInfo, proc::TypeResolution, valid::{FunctionInfo, ModuleInfo}, }; @@ -59,6 +60,7 @@ impl Writer { id_gen, capabilities_available: options.capabilities.clone(), capabilities_used, + extensions_used: crate::FastHashSet::default(), debugs: vec![], annotations: vec![], flags: options.flags, @@ -70,6 +72,7 @@ impl Writer { constant_ids: Vec::new(), cached_constants: crate::FastHashMap::default(), global_variables: Vec::new(), + binding_map: options.binding_map.clone(), saved_cached: CachedExpressions::default(), gl450_ext_inst_id, temp_list: Vec::new(), @@ -100,6 +103,7 @@ impl Writer { flags: self.flags, bounds_check_policies: self.bounds_check_policies, capabilities_available: take(&mut self.capabilities_available), + binding_map: take(&mut self.binding_map), // Initialized afresh: id_gen, @@ -108,6 +112,7 @@ impl Writer { // Recycled: capabilities_used: take(&mut self.capabilities_used).recycle(), + extensions_used: take(&mut self.extensions_used).recycle(), physical_layout: self.physical_layout.clone().recycle(), logical_layout: take(&mut self.logical_layout).recycle(), debugs: take(&mut self.debugs).recycle(), @@ -168,6 +173,11 @@ impl Writer { } } + /// Indicate that the code uses the given extension. + pub(super) fn use_extension(&mut self, extension: &'static str) { + self.extensions_used.insert(extension); + } + pub(super) fn get_type_id(&mut self, lookup_ty: LookupType) -> Word { match self.lookup_type.entry(lookup_ty) { Entry::Occupied(e) => *e.get(), @@ -267,7 +277,7 @@ impl Writer { self.get_type_id(local_type.into()) } - fn decorate(&mut self, id: Word, decoration: spirv::Decoration, operands: &[Word]) { + pub(super) fn decorate(&mut self, id: Word, decoration: spirv::Decoration, operands: &[Word]) { self.annotations .push(Instruction::decorate(id, decoration, operands)); } @@ -497,7 +507,14 @@ impl Writer { let mut gv = self.global_variables[handle.index()].clone(); // Handle globals are pre-emitted and should be loaded automatically. - if var.space == crate::AddressSpace::Handle { + // + // Any that are binding arrays we skip as we cannot load the array, we must load the result after indexing. + let is_binding_array = match ir_module.types[var.ty].inner { + crate::TypeInner::BindingArray { .. } => true, + _ => false, + }; + + if var.space == crate::AddressSpace::Handle && !is_binding_array { let var_type_id = self.get_type_id(LookupType::Handle(var.ty)); let id = self.id_gen.next(); prelude @@ -788,6 +805,16 @@ impl Writer { LocalType::SampledImage { image_type_id } => { Instruction::type_sampled_image(id, image_type_id) } + LocalType::BindingArray { base, size } => { + let inner_ty = self.get_type_id(LookupType::Handle(base)); + let scalar_id = self.get_constant_scalar(crate::ScalarValue::Uint(size), 4); + Instruction::type_array(id, inner_ty, scalar_id) + } + LocalType::PointerToBindingArray { base, size } => { + let inner_ty = + self.get_type_id(LookupType::Local(LocalType::BindingArray { base, size })); + Instruction::type_pointer(id, spirv::StorageClass::UniformConstant, inner_ty) + } }; instruction.to_words(&mut self.logical_layout.declarations); @@ -838,6 +865,16 @@ impl Writer { crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), } } + crate::TypeInner::BindingArray { base, size } => { + let type_id = self.get_type_id(LookupType::Handle(base)); + match size { + crate::ArraySize::Constant(const_handle) => { + let length_id = self.constant_ids[const_handle.index()]; + Instruction::type_array(id, type_id, length_id) + } + crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), + } + } crate::TypeInner::Struct { ref members, span: _, @@ -1223,15 +1260,34 @@ impl Writer { } } + let mut substitute_inner_type_lookup = None; if let Some(ref res_binding) = global_variable.binding { self.decorate(id, Decoration::DescriptorSet, &[res_binding.group]); self.decorate(id, Decoration::Binding, &[res_binding.binding]); - } + + if let Some(&BindingInfo { + binding_array_size: Some(remapped_binding_array_size), + }) = self.binding_map.get(res_binding) + { + if let crate::TypeInner::BindingArray { base, .. } = + ir_module.types[global_variable.ty].inner + { + substitute_inner_type_lookup = + Some(LookupType::Local(LocalType::PointerToBindingArray { + base, + size: remapped_binding_array_size as u64, + })) + } + } else { + } + }; let init_word = global_variable .init .map(|constant| self.constant_ids[constant.index()]); - let inner_type_id = self.get_type_id(LookupType::Handle(global_variable.ty)); + let inner_type_id = self.get_type_id( + substitute_inner_type_lookup.unwrap_or(LookupType::Handle(global_variable.ty)), + ); // generate the wrapping structure if needed let pointer_type_id = if global_needs_wrapper(ir_module, global_variable) { @@ -1262,7 +1318,11 @@ impl Writer { if let crate::AddressSpace::Storage { .. } = global_variable.space { self.decorate(inner_type_id, Decoration::Block, &[]); } - self.get_pointer_id(&ir_module.types, global_variable.ty, class)? + if substitute_inner_type_lookup.is_some() { + inner_type_id + } else { + self.get_pointer_id(&ir_module.types, global_variable.ty, class)? + } }; Instruction::variable(pointer_type_id, id, class, init_word) @@ -1493,6 +1553,9 @@ impl Writer { for capability in self.capabilities_used.iter() { Instruction::capability(*capability).to_words(&mut self.logical_layout.capabilities); } + for extension in self.extensions_used.iter() { + Instruction::extension(extension).to_words(&mut self.logical_layout.extensions); + } if ir_module.entry_points.is_empty() { // SPIR-V doesn't like modules without entry points Instruction::capability(spirv::Capability::Linkage) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 7666f8044..f21d82c40 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -535,6 +535,21 @@ impl Writer { } write!(self.out, ">")?; } + TypeInner::BindingArray { base, size } => { + // More info https://github.com/gpuweb/gpuweb/issues/2105 + write!(self.out, "binding_array<")?; + match size { + crate::ArraySize::Constant(handle) => { + self.write_type(module, base)?; + write!(self.out, ",")?; + self.write_constant(module, handle)?; + } + crate::ArraySize::Dynamic => { + self.write_type(module, base)?; + } + } + write!(self.out, ">")?; + } TypeInner::Matrix { columns, rows, @@ -1181,6 +1196,7 @@ impl Writer { } TypeInner::Matrix { .. } | TypeInner::Array { .. } + | TypeInner::BindingArray { .. } | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, TypeInner::Struct { .. } => { // This will never panic in case the type is a `Struct`, this is not true diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index c7f5abb2d..610c8c5f8 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -580,9 +580,9 @@ impl crate::TypeInner { match size { crate::ArraySize::Constant(size) => { let size = constants[size].name.as_deref().unwrap_or("unknown"); - format!("{}[{}]", base, size) + format!("array<{}, {}>", base, size) } - crate::ArraySize::Dynamic => format!("{}[]", base), + crate::ArraySize::Dynamic => format!("array<{}>", base), } } Ti::Struct { .. } => { @@ -634,6 +634,17 @@ impl crate::TypeInner { ) } Ti::Sampler { .. } => "sampler".to_string(), + Ti::BindingArray { base, size, .. } => { + let member_type = &types[base]; + let base = member_type.name.as_deref().unwrap_or("unknown"); + match size { + crate::ArraySize::Constant(size) => { + let size = constants[size].name.as_deref().unwrap_or("unknown"); + format!("binding_array<{}, {}>", base, size) + } + crate::ArraySize::Dynamic => format!("binding_array<{}>", base), + } + } } } } @@ -681,7 +692,7 @@ mod type_inner_tests { stride: 4, size: crate::ArraySize::Constant(c), }; - assert_eq!(array.to_wgsl(&types, &constants), "MyType1[C]"); + assert_eq!(array.to_wgsl(&types, &constants), "array"); let mat = crate::TypeInner::Matrix { rows: crate::VectorSize::Quad, @@ -727,6 +738,15 @@ mod type_inner_tests { img3.to_wgsl(&types, &constants), "texture_depth_multisampled_2d" ); + + let array = crate::TypeInner::BindingArray { + base: mytype1, + size: crate::ArraySize::Constant(c), + }; + assert_eq!( + array.to_wgsl(&types, &constants), + "binding_array" + ); } } @@ -865,10 +885,9 @@ impl<'a> ExpressionContext<'a, '_, '_> { fn prepare_sampling( &mut self, - image_name: &'a str, + image: Handle, span: Span, ) -> Result> { - let image = self.lookup_ident.lookup(image_name, span.clone())?.handle; Ok(SamplingContext { image, arrayed: match *self.resolve_type(image)? { @@ -1762,12 +1781,13 @@ impl Parser { "textureSample" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; + let (image, image_span) = + self.parse_general_expression_with_span(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, image_span)?; + let sc = ctx.prepare_sampling(image, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -1782,7 +1802,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + sampler: sampler_expr, gather: None, coordinate, array_index, @@ -1794,12 +1814,13 @@ impl Parser { "textureSampleLevel" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; + let (image, image_span) = + self.parse_general_expression_with_span(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, image_span)?; + let sc = ctx.prepare_sampling(image, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -1816,7 +1837,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + sampler: sampler_expr, gather: None, coordinate, array_index, @@ -1828,12 +1849,13 @@ impl Parser { "textureSampleBias" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; + let (image, image_span) = + self.parse_general_expression_with_span(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, image_span)?; + let sc = ctx.prepare_sampling(image, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -1850,7 +1872,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + sampler: sampler_expr, gather: None, coordinate, array_index, @@ -1862,12 +1884,13 @@ impl Parser { "textureSampleGrad" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; + let (image, image_span) = + self.parse_general_expression_with_span(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, image_span)?; + let sc = ctx.prepare_sampling(image, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -1886,7 +1909,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + sampler: sampler_expr, gather: None, coordinate, array_index, @@ -1898,12 +1921,13 @@ impl Parser { "textureSampleCompare" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; + let (image, image_span) = + self.parse_general_expression_with_span(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, image_span)?; + let sc = ctx.prepare_sampling(image, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -1920,7 +1944,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + sampler: sampler_expr, gather: None, coordinate, array_index, @@ -1932,12 +1956,13 @@ impl Parser { "textureSampleCompareLevel" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; + let (image, image_span) = + self.parse_general_expression_with_span(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, image_span)?; + let sc = ctx.prepare_sampling(image, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -1954,7 +1979,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + sampler: sampler_expr, gather: None, coordinate, array_index, @@ -1983,12 +2008,13 @@ impl Parser { } else { crate::SwizzleComponent::X }; - let (image_name, image_span) = lexer.next_ident_with_span()?; + let (image, image_span) = + self.parse_general_expression_with_span(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, image_span)?; + let sc = ctx.prepare_sampling(image, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -2003,7 +2029,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + sampler: sampler_expr, gather: Some(component), coordinate, array_index, @@ -2015,12 +2041,13 @@ impl Parser { "textureGatherCompare" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; + let (image, image_span) = + self.parse_general_expression_with_span(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; - let (sampler_name, sampler_span) = lexer.next_ident_with_span()?; + let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image_name, image_span)?; + let sc = ctx.prepare_sampling(image, image_span)?; let array_index = if sc.arrayed { lexer.expect(Token::Separator(','))?; Some(self.parse_general_expression(lexer, ctx.reborrow())?) @@ -2037,7 +2064,7 @@ impl Parser { lexer.close_arguments()?; crate::Expression::ImageSample { image: sc.image, - sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle, + sampler: sampler_expr, gather: Some(crate::SwizzleComponent::X), coordinate, array_index, @@ -2049,11 +2076,8 @@ impl Parser { "textureLoad" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx - .lookup_ident - .lookup(image_name, image_span.clone())? - .handle; + let (image, image_span) = + self.parse_general_expression_with_span(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(','))?; let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; let (class, arrayed) = match *ctx.resolve_type(image)? { @@ -2090,8 +2114,7 @@ impl Parser { "textureDimensions" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle; + let image = self.parse_general_expression(lexer, ctx.reborrow())?; let level = if lexer.skip(Token::Separator(',')) { let expr = self.parse_general_expression(lexer, ctx.reborrow())?; Some(expr) @@ -2107,8 +2130,7 @@ impl Parser { "textureNumLevels" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle; + let image = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::ImageQuery { image, @@ -2118,8 +2140,7 @@ impl Parser { "textureNumLayers" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle; + let image = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::ImageQuery { image, @@ -2129,8 +2150,7 @@ impl Parser { "textureNumSamples" => { let _ = lexer.next(); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle; + let image = self.parse_general_expression(lexer, ctx.reborrow())?; lexer.close_arguments()?; crate::Expression::ImageQuery { image, @@ -2271,7 +2291,8 @@ impl Parser { let expr = match lexer.peek() { (Token::Paren('('), _) => { let _ = lexer.next(); - let expr = self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; + let (expr, _span) = + self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; self.pop_scope(lexer); expr @@ -2658,12 +2679,21 @@ impl Parser { ) } + fn parse_general_expression_with_span<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result<(Handle, Span), Error<'a>> { + let (expr, span) = self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; + Ok((ctx.apply_load_rule(expr), span)) + } + fn parse_general_expression<'a>( &mut self, lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { - let expr = self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; + let (expr, _span) = self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; Ok(ctx.apply_load_rule(expr)) } @@ -2671,7 +2701,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, - ) -> Result> { + ) -> Result<(TypedExpression, Span), Error<'a>> { self.push_scope(Scope::GeneralExpr, lexer); // logical_or_expression let handle = context.parse_binary_op( @@ -2728,8 +2758,7 @@ impl Parser { ) }, )?; - self.pop_scope(lexer); - Ok(handle) + Ok((handle, self.pop_scope(lexer))) } fn parse_variable_ident_decl<'a>( @@ -3012,6 +3041,20 @@ impl Parser { }; crate::TypeInner::Array { base, size, stride } } + "binding_array" => { + lexer.expect_generic_paren('<')?; + let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let size = if lexer.skip(Token::Separator(',')) { + let const_handle = + self.parse_const_expression(lexer, type_arena, const_arena)?; + crate::ArraySize::Constant(const_handle) + } else { + crate::ArraySize::Dynamic + }; + lexer.expect_generic_paren('>')?; + + crate::TypeInner::BindingArray { base, size } + } "sampler" => crate::TypeInner::Sampler { comparison: false }, "sampler_comparison" => crate::TypeInner::Sampler { comparison: true }, "texture_1d" => { @@ -3936,13 +3979,10 @@ impl Parser { let _ = lexer.next(); emitter.start(context.expressions); lexer.open_arguments()?; - let (image_name, image_span) = lexer.next_ident_with_span()?; - let image = context - .lookup_ident - .lookup(image_name, image_span.clone())? - .handle; - lexer.expect(Token::Separator(','))?; let mut expr_context = context.as_expression(block, &mut emitter); + let (image, image_span) = self + .parse_general_expression_with_span(lexer, expr_context.reborrow())?; + lexer.expect(Token::Separator(','))?; let arrayed = match *expr_context.resolve_type(image)? { crate::TypeInner::Image { arrayed, .. } => arrayed, _ => return Err(Error::BadTexture(image_span)), diff --git a/src/lib.rs b/src/lib.rs index d5d4d59c0..fa632b29b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -698,6 +698,8 @@ pub enum TypeInner { }, /// Can be used to sample values from images. Sampler { comparison: bool }, + /// Array of bindings + BindingArray { base: Handle, size: ArraySize }, } /// Constant value. diff --git a/src/proc/index.rs b/src/proc/index.rs index 643cb2432..ead07052b 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -365,7 +365,7 @@ impl crate::TypeInner { let known_length = match *self { Ti::Vector { size, .. } => size as _, Ti::Matrix { columns, .. } => columns as _, - Ti::Array { size, .. } => { + Ti::Array { size, .. } | Ti::BindingArray { size, .. } => { return size.to_indexable_length(module); } Ti::ValuePointer { diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 1b517e434..598afba92 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -202,7 +202,7 @@ impl Layouter { alignment, } } - Ti::Image { .. } | Ti::Sampler { .. } => TypeLayout { + Ti::Image { .. } | Ti::Sampler { .. } | Ti::BindingArray { .. } => TypeLayout { size, alignment: Alignment::new(1).unwrap(), }, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index eab9c53da..ebda58d1e 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -125,7 +125,7 @@ impl super::TypeInner { count * stride } Self::Struct { span, .. } => span, - Self::Image { .. } | Self::Sampler { .. } => 0, + Self::Image { .. } | Self::Sampler { .. } | Self::BindingArray { .. } => 0, }) } diff --git a/src/proc/namer.rs b/src/proc/namer.rs index b613060ac..3f4af4788 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -97,7 +97,7 @@ impl Namer { *count += 1; // Add the suffix. This may fit in base's existing allocation. let mut suffixed = base.into_owned(); - write!(&mut suffixed, "{}{}", SEPARATOR, *count).unwrap(); + write!(suffixed, "{}{}", SEPARATOR, *count).unwrap(); suffixed } None => { diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 58e67b019..9f3f2a494 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -291,6 +291,7 @@ impl<'a> ResolveContext<'a> { } }) } + Ti::BindingArray { base, .. } => TypeResolution::Handle(base), ref other => { log::error!("Access type {:?}", other); return Err(ResolveError::InvalidAccess { @@ -392,6 +393,7 @@ impl<'a> ResolveContext<'a> { }); } }), + Ti::BindingArray { base, .. } => TypeResolution::Handle(base), ref other => { log::error!("Access index type {:?}", other); return Err(ResolveError::InvalidAccess { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index cb75ddb1e..932e8b0f8 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -168,11 +168,19 @@ enum GlobalOrArgument { Argument(u32), } -impl crate::Expression { - const fn to_global_or_argument(&self) -> Result { - Ok(match *self { +impl GlobalOrArgument { + fn from_expression( + expression_arena: &Arena, + expression: Handle, + ) -> Result { + Ok(match expression_arena[expression] { crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i), + crate::Expression::Access { base, .. } + | crate::Expression::AccessIndex { base, .. } => match expression_arena[base] { + crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var), + _ => return Err(ExpressionError::ExpectedGlobalOrArgument), + }, _ => return Err(ExpressionError::ExpectedGlobalOrArgument), }) } @@ -356,12 +364,12 @@ impl FunctionInfo { GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var), GlobalOrArgument::Argument(i) => { let handle = arguments[i as usize]; - expression_arena[handle] - .to_global_or_argument() - .map_err(|error| { + GlobalOrArgument::from_expression(expression_arena, handle).map_err( + |error| { FunctionError::Expression { handle, error } .with_span_handle(handle, expression_arena) - })? + }, + )? } }; @@ -369,12 +377,12 @@ impl FunctionInfo { GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var), GlobalOrArgument::Argument(i) => { let handle = arguments[i as usize]; - expression_arena[handle] - .to_global_or_argument() - .map_err(|error| { + GlobalOrArgument::from_expression(expression_arena, handle).map_err( + |error| { FunctionError::Expression { handle, error } .with_span_handle(handle, expression_arena) - })? + }, + )? } }; @@ -417,17 +425,73 @@ impl FunctionInfo { expression_arena: &Arena, other_functions: &[FunctionInfo], resolve_context: &ResolveContext, + capabilities: super::Capabilities, ) -> Result<(), ExpressionError> { use crate::{Expression as E, SampleLevel as Sl}; let mut assignable_global = None; let uniformity = match *expression { - E::Access { base, index } => Uniformity { - non_uniform_result: self - .add_assignable_ref(base, &mut assignable_global) - .or(self.add_ref(index)), - requirements: UniformityRequirements::empty(), - }, + E::Access { base, index } => { + let base_ty = self[base].ty.inner_with(resolve_context.types); + + // build up the caps needed if this is indexed non-uniformly + let mut needed_caps = super::Capabilities::empty(); + let is_binding_array = match *base_ty { + crate::TypeInner::BindingArray { + base: array_element_ty_handle, + .. + } => { + // these are nasty aliases, but these idents are too long and break rustfmt + let ub_st = super::Capabilities::UNIFORM_BUFFER_AND_STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING; + let st_sb = super::Capabilities::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING; + let sampler = super::Capabilities::SAMPLER_NON_UNIFORM_INDEXING; + + // We're a binding array, so lets use the type of _what_ we are array of to determine if we can non-uniformly index it. + let array_element_ty = + &resolve_context.types[array_element_ty_handle].inner; + + needed_caps |= match *array_element_ty { + // If we're an image, use the appropriate limit. + crate::TypeInner::Image { class, .. } => match class { + crate::ImageClass::Storage { .. } => ub_st, + _ => st_sb, + }, + crate::TypeInner::Sampler { .. } => sampler, + // If we're anything but an image, assume we're a buffer and use the address space. + _ => { + if let E::GlobalVariable(global_handle) = expression_arena[base] { + let global = &resolve_context.global_vars[global_handle]; + match global.space { + crate::AddressSpace::Uniform => ub_st, + crate::AddressSpace::Storage { .. } => st_sb, + _ => unreachable!(), + } + } else { + unreachable!() + } + } + }; + + true + } + _ => false, + }; + + if self[index].uniformity.non_uniform_result.is_some() + && !capabilities.contains(needed_caps) + && is_binding_array + { + return Err(ExpressionError::MissingCapabilities(needed_caps)); + } + + let _ = (); + Uniformity { + non_uniform_result: self + .add_assignable_ref(base, &mut assignable_global) + .or(self.add_ref(index)), + requirements: UniformityRequirements::empty(), + } + } E::AccessIndex { base, .. } => Uniformity { non_uniform_result: self.add_assignable_ref(base, &mut assignable_global), requirements: UniformityRequirements::empty(), @@ -515,8 +579,8 @@ impl FunctionInfo { level, depth_ref, } => { - let image_storage = expression_arena[image].to_global_or_argument()?; - let sampler_storage = expression_arena[sampler].to_global_or_argument()?; + let image_storage = GlobalOrArgument::from_expression(expression_arena, image)?; + let sampler_storage = GlobalOrArgument::from_expression(expression_arena, sampler)?; match (image_storage, sampler_storage) { (GlobalOrArgument::Global(image), GlobalOrArgument::Global(sampler)) => { @@ -870,6 +934,7 @@ impl ModuleInfo { fun: &crate::Function, module: &crate::Module, flags: ValidationFlags, + capabilities: super::Capabilities, ) -> Result> { let mut info = FunctionInfo { flags, @@ -897,6 +962,7 @@ impl ModuleInfo { &fun.expressions, &self.functions, &resolve_context, + capabilities, ) { return Err(FunctionError::Expression { handle, error } .with_span_handle(handle, &fun.expressions)); @@ -1015,8 +1081,15 @@ fn uniform_control_flow() { arguments: &[], }; for (handle, expression) in expressions.iter() { - info.process_expression(handle, expression, &expressions, &[], &resolve_context) - .unwrap(); + info.process_expression( + handle, + expression, + &expressions, + &[], + &resolve_context, + super::Capabilities::empty(), + ) + .unwrap(); } assert_eq!(info[non_uniform_global_expr].ref_count, 1); assert_eq!(info[uniform_global_expr].ref_count, 1); diff --git a/src/valid/expression.rs b/src/valid/expression.rs index bfa3b0b83..9d6b85271 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -65,6 +65,8 @@ pub enum ExpressionError { ExpectedGlobalOrArgument, #[error("Calling an undeclared function {0:?}")] CallToUndeclaredFunction(Handle), + #[error("Needs to be an binding array instead of {0:?}")] + ExpectedBindingArrayType(Handle), #[error("Needs to be an image instead of {0:?}")] ExpectedImageType(Handle), #[error("Needs to be an image instead of {0:?}")] @@ -115,6 +117,8 @@ pub enum ExpressionError { InvalidArgumentType(crate::MathFunction, u32, Handle), #[error("Atomic result type can't be {0:?} of {1} bytes")] InvalidAtomicResultType(crate::ScalarKind, crate::Bytes), + #[error("Shader requires capability {0:?}")] + MissingCapabilities(super::Capabilities), } #[cfg(feature = "validate")] @@ -164,7 +168,9 @@ impl super::Validator { let dynamic_indexing_restricted = match *base_type { Ti::Vector { .. } => false, Ti::Matrix { .. } | Ti::Array { .. } => true, - Ti::Pointer { .. } | Ti::ValuePointer { size: Some(_), .. } => false, + Ti::Pointer { .. } + | Ti::ValuePointer { size: Some(_), .. } + | Ti::BindingArray { .. } => false, ref other => { log::error!("Indexing of {:?}", other); return Err(ExpressionError::InvalidBaseType(base)); @@ -235,7 +241,7 @@ impl super::Validator { size: crate::ArraySize::Constant(handle), .. } => module.constants[handle].to_array_length().unwrap(), - Ti::Array { .. } => !0, // can't statically know, but need run-time checks + Ti::Array { .. } | Ti::BindingArray { .. } => !0, // can't statically know, but need run-time checks Ti::Pointer { base, .. } if top_level => { resolve_index_limit(module, top, &module.types[base].inner, false)? } @@ -345,13 +351,50 @@ impl super::Validator { module.global_variables[var_handle].ty } crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, + crate::Expression::Access { base, .. } + | crate::Expression::AccessIndex { base, .. } => { + match function.expressions[base] { + crate::Expression::GlobalVariable(var_handle) => { + let array_ty = module.global_variables[var_handle].ty; + + match module.types[array_ty].inner { + Ti::BindingArray { base, .. } => base, + _ => { + return Err(ExpressionError::ExpectedBindingArrayType( + array_ty, + )) + } + } + } + _ => return Err(ExpressionError::ExpectedGlobalVariable), + } + } _ => return Err(ExpressionError::ExpectedGlobalVariable), }; + let sampler_ty = match function.expressions[sampler] { crate::Expression::GlobalVariable(var_handle) => { module.global_variables[var_handle].ty } crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, + crate::Expression::Access { base, .. } + | crate::Expression::AccessIndex { base, .. } => { + match function.expressions[base] { + crate::Expression::GlobalVariable(var_handle) => { + let array_ty = module.global_variables[var_handle].ty; + + match module.types[array_ty].inner { + Ti::BindingArray { base, .. } => base, + _ => { + return Err(ExpressionError::ExpectedBindingArrayType( + array_ty, + )) + } + } + } + _ => return Err(ExpressionError::ExpectedGlobalVariable), + } + } _ => return Err(ExpressionError::ExpectedGlobalVariable), }; let comparison = match module.types[sampler_ty].inner { @@ -541,6 +584,24 @@ impl super::Validator { module.global_variables[var_handle].ty } crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, + crate::Expression::Access { base, .. } + | crate::Expression::AccessIndex { base, .. } => { + match function.expressions[base] { + crate::Expression::GlobalVariable(var_handle) => { + let array_ty = module.global_variables[var_handle].ty; + + match module.types[array_ty].inner { + Ti::BindingArray { base, .. } => base, + _ => { + return Err(ExpressionError::ExpectedBindingArrayType( + array_ty, + )) + } + } + } + _ => return Err(ExpressionError::ExpectedGlobalVariable), + } + } _ => return Err(ExpressionError::ExpectedGlobalVariable), }; match module.types[ty].inner { @@ -606,6 +667,24 @@ impl super::Validator { module.global_variables[var_handle].ty } crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, + crate::Expression::Access { base, .. } + | crate::Expression::AccessIndex { base, .. } => { + match function.expressions[base] { + crate::Expression::GlobalVariable(var_handle) => { + let array_ty = module.global_variables[var_handle].ty; + + match module.types[array_ty].inner { + Ti::BindingArray { base, .. } => base, + _ => { + return Err(ExpressionError::ExpectedBindingArrayType( + array_ty, + )) + } + } + } + _ => return Err(ExpressionError::ExpectedGlobalVariable), + } + } _ => return Err(ExpressionError::ExpectedGlobalVariable), }; match module.types[ty].inner { diff --git a/src/valid/function.rs b/src/valid/function.rs index 39f82ba4b..151952750 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -657,6 +657,21 @@ impl super::Validator { crate::Expression::GlobalVariable(var_handle) => { &context.global_vars[var_handle] } + // We're looking at a binding index situation, so punch through the index and look at the global behind it. + crate::Expression::Access { base, .. } + | crate::Expression::AccessIndex { base, .. } => { + match *context.get_expression(base).map_err(|e| e.with_span())? { + crate::Expression::GlobalVariable(var_handle) => { + &context.global_vars[var_handle] + } + _ => { + return Err(FunctionError::InvalidImageStore( + ExpressionError::ExpectedGlobalVariable, + ) + .with_span_handle(image, context.expressions)) + } + } + } _ => { return Err(FunctionError::InvalidImageStore( ExpressionError::ExpectedGlobalVariable, @@ -665,7 +680,13 @@ impl super::Validator { } }; - let value_ty = match context.types[var.ty].inner { + // Punch through a binding array to get the underlying type + let global_ty = match context.types[var.ty].inner { + Ti::BindingArray { base, .. } => &context.types[base].inner, + ref inner => inner, + }; + + let value_ty = match *global_ty { Ti::Image { class, arrayed, @@ -823,7 +844,7 @@ impl super::Validator { mod_info: &ModuleInfo, ) -> Result> { #[cfg_attr(not(feature = "validate"), allow(unused_mut))] - let mut info = mod_info.process_function(fun, module, self.flags)?; + let mut info = mod_info.process_function(fun, module, self.flags, self.capabilities)?; #[cfg(feature = "validate")] for (var_handle, var) in fun.local_variables.iter() { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index d1bfe009e..50c2fe1e9 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -383,7 +383,9 @@ impl super::Validator { } crate::AddressSpace::Handle => { match types[var.ty].inner { - crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => {} + crate::TypeInner::Image { .. } + | crate::TypeInner::Sampler { .. } + | crate::TypeInner::BindingArray { .. } => {} _ => { return Err(GlobalVariableError::InvalidType(var.space)); } @@ -512,6 +514,13 @@ impl super::Validator { crate::AddressSpace::Uniform => GlobalUse::READ | GlobalUse::QUERY, crate::AddressSpace::Storage { access } => storage_usage(access), crate::AddressSpace::Handle => match module.types[var.ty].inner { + crate::TypeInner::BindingArray { base, .. } => match module.types[base].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Storage { access, .. }, + .. + } => storage_usage(access), + _ => GlobalUse::READ | GlobalUse::QUERY, + }, crate::TypeInner::Image { class: crate::ImageClass::Storage { access, .. }, .. diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 8e0227408..77b92152b 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -88,6 +88,12 @@ bitflags::bitflags! { const FLOAT64 = 0x2; /// Support for `Builtin:PrimitiveIndex`. const PRIMITIVE_INDEX = 0x4; + /// Support for non-uniform indexing of sampled textures and storage buffer arrays. + const SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING = 0x8; + /// Support for non-uniform indexing of uniform buffers and storage texture arrays. + const UNIFORM_BUFFER_AND_STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING = 0x10; + /// Support for non-uniform indexing of samplers. + const SAMPLER_NON_UNIFORM_INDEXING = 0x11; } } @@ -203,7 +209,10 @@ impl crate::TypeInner { | Self::Pointer { .. } | Self::ValuePointer { .. } | Self::Struct { .. } => true, - Self::Array { .. } | Self::Image { .. } | Self::Sampler { .. } => false, + Self::Array { .. } + | Self::Image { .. } + | Self::Sampler { .. } + | Self::BindingArray { .. } => false, } } diff --git a/src/valid/type.rs b/src/valid/type.rs index f4f47aec5..7c80adf76 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -580,6 +580,7 @@ impl super::Validator { ti } Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::new(TypeFlags::ARGUMENT, 0), + Ti::BindingArray { .. } => TypeInfo::new(TypeFlags::empty(), 0), }) } } diff --git a/tests/in/binding-arrays.param.ron b/tests/in/binding-arrays.param.ron new file mode 100644 index 000000000..b2f1dabaa --- /dev/null +++ b/tests/in/binding-arrays.param.ron @@ -0,0 +1,39 @@ +( + god_mode: true, + hlsl: ( + shader_model: V5_1, + binding_map: { + (group: 0, binding: 0): (space: 0, register: 0, binding_array_size: Some(10)), + (group: 0, binding: 1): (space: 1, register: 0), + (group: 0, binding: 2): (space: 2, register: 0), + (group: 0, binding: 3): (space: 3, register: 0), + (group: 0, binding: 4): (space: 4, register: 0), + (group: 0, binding: 5): (space: 5, register: 0), + (group: 0, binding: 6): (space: 6, register: 0), + (group: 0, binding: 7): (space: 7, register: 0), + (group: 0, binding: 8): (space: 8, register: 0), + }, + fake_missing_bindings: true, + special_constants_binding: None, + ), + msl: ( + lang_version: (2, 0), + per_stage_map: ( + fs: ( + resources: { + (group: 0, binding: 0): (texture: Some(0), binding_array_size: Some(10), mutable: false), + }, + sizes_buffer: None, + ) + ), + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: true, + ), + spv: ( + version: (1, 1), + binding_map: { + (group: 0, binding: 0): (binding_array_size: Some(10)), + }, + ) +) diff --git a/tests/in/binding-arrays.wgsl b/tests/in/binding-arrays.wgsl new file mode 100644 index 000000000..491621f51 --- /dev/null +++ b/tests/in/binding-arrays.wgsl @@ -0,0 +1,108 @@ +struct UniformIndex { + index: u32 +}; + +@group(0) @binding(0) +var texture_array_unbounded: binding_array>; +@group(0) @binding(1) +var texture_array_bounded: binding_array, 5>; +@group(0) @binding(2) +var texture_array_2darray: binding_array, 5>; +@group(0) @binding(3) +var texture_array_multisampled: binding_array, 5>; +@group(0) @binding(4) +var texture_array_depth: binding_array; +@group(0) @binding(5) +var texture_array_storage: binding_array, 5>; +@group(0) @binding(6) +var samp: binding_array; +@group(0) @binding(7) +var samp_comp: binding_array; +@group(0) @binding(8) +var uni: UniformIndex; + +struct FragmentIn { + @location(0) index: u32, +}; + +@fragment +fn main(fragment_in: FragmentIn) -> @location(0) vec4 { + let uniform_index = uni.index; + let non_uniform_index = fragment_in.index; + + var i1 = 0; + var i2 = vec2(0); + var v1 = 0.0; + var v4 = vec4(0.0); + + // This example is arranged in the order of the texture definitions in the wgsl spec + // + // The first function uses texture_array_unbounded, the rest use texture_array_bounded to make sure + // they both show up in the output. Functions that need depth use texture_array_2darray. + // + // We only test 2D f32 textures here as the machinery for binding indexing doesn't care about + // texture format or texture dimension. + + let uv = vec2(0.0); + let pix = vec2(0); + + i2 += textureDimensions(texture_array_unbounded[0]); + i2 += textureDimensions(texture_array_unbounded[uniform_index]); + i2 += textureDimensions(texture_array_unbounded[non_uniform_index]); + + v4 += textureGather(0, texture_array_bounded[0], samp[0], uv); + v4 += textureGather(0, texture_array_bounded[uniform_index], samp[uniform_index], uv); + v4 += textureGather(0, texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); + + v4 += textureGatherCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + v4 += textureGatherCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + v4 += textureGatherCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + + v4 += textureLoad(texture_array_unbounded[0], pix, 0); + v4 += textureLoad(texture_array_unbounded[uniform_index], pix, 0); + v4 += textureLoad(texture_array_unbounded[non_uniform_index], pix, 0); + + i1 += textureNumLayers(texture_array_2darray[0]); + i1 += textureNumLayers(texture_array_2darray[uniform_index]); + i1 += textureNumLayers(texture_array_2darray[non_uniform_index]); + + i1 += textureNumLevels(texture_array_bounded[0]); + i1 += textureNumLevels(texture_array_bounded[uniform_index]); + i1 += textureNumLevels(texture_array_bounded[non_uniform_index]); + + i1 += textureNumSamples(texture_array_multisampled[0]); + i1 += textureNumSamples(texture_array_multisampled[uniform_index]); + i1 += textureNumSamples(texture_array_multisampled[non_uniform_index]); + + v4 += textureSample(texture_array_bounded[0], samp[0], uv); + v4 += textureSample(texture_array_bounded[uniform_index], samp[uniform_index], uv); + v4 += textureSample(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); + + v4 += textureSampleBias(texture_array_bounded[0], samp[0], uv, 0.0); + v4 += textureSampleBias(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + v4 += textureSampleBias(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); + + v1 += textureSampleCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + v1 += textureSampleCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + v1 += textureSampleCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + + v1 += textureSampleCompareLevel(texture_array_depth[0], samp_comp[0], uv, 0.0); + v1 += textureSampleCompareLevel(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + v1 += textureSampleCompareLevel(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + + v4 += textureSampleGrad(texture_array_bounded[0], samp[0], uv, uv, uv); + v4 += textureSampleGrad(texture_array_bounded[uniform_index], samp[uniform_index], uv, uv, uv); + v4 += textureSampleGrad(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, uv, uv); + + v4 += textureSampleLevel(texture_array_bounded[0], samp[0], uv, 0.0); + v4 += textureSampleLevel(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + v4 += textureSampleLevel(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); + + textureStore(texture_array_storage[0], pix, v4); + textureStore(texture_array_storage[uniform_index], pix, v4); + textureStore(texture_array_storage[non_uniform_index], pix, v4); + + let v2 = vec2(i2 + vec2(i1)); + + return v4 + vec4(v2.x, v2.y, v2.x, v2.y) + v1; +} diff --git a/tests/out/hlsl/binding-arrays.hlsl b/tests/out/hlsl/binding-arrays.hlsl new file mode 100644 index 000000000..f01d67329 --- /dev/null +++ b/tests/out/hlsl/binding-arrays.hlsl @@ -0,0 +1,183 @@ + +struct UniformIndex { + uint index; +}; + +struct FragmentIn { + nointerpolation uint index : LOC0; +}; + +Texture2D texture_array_unbounded[10] : register(t0); +Texture2D texture_array_bounded[5] : register(t0, space1); +Texture2DArray texture_array_2darray[5] : register(t0, space2); +Texture2DMS texture_array_multisampled[5] : register(t0, space3); +Texture2D texture_array_depth[5] : register(t0, space4); +RWTexture2D texture_array_storage[5] : register(u0, space5); +SamplerState samp[5] : register(s0, space6); +SamplerComparisonState samp_comp[5] : register(s0, space7); +cbuffer uni : register(b0, space8) { UniformIndex uni; } + +struct FragmentInput_main { + nointerpolation uint index : LOC0; +}; + +int2 NagaDimensions2D(Texture2D tex) +{ + uint4 ret; + tex.GetDimensions(0, ret.x, ret.y, ret.z); + return ret.xy; +} + +int NagaNumLayers2DArray(Texture2DArray tex) +{ + uint4 ret; + tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); + return ret.w; +} + +int NagaNumLevels2D(Texture2D tex) +{ + uint4 ret; + tex.GetDimensions(0, ret.x, ret.y, ret.z); + return ret.z; +} + +int NagaMSNumSamples2D(Texture2DMS tex) +{ + uint4 ret; + tex.GetDimensions(ret.x, ret.y, ret.z); + return ret.z; +} + +float4 main(FragmentInput_main fragmentinput_main) : SV_Target0 +{ + FragmentIn fragment_in = { fragmentinput_main.index }; + int i1_ = 0; + int2 i2_ = (int2)0; + float v1_ = 0.0; + float4 v4_ = (float4)0; + + uint uniform_index = uni.index; + uint non_uniform_index = fragment_in.index; + i2_ = (0).xx; + v4_ = (0.0).xxxx; + float2 uv = (0.0).xx; + int2 pix = (0).xx; + int2 _expr27 = i2_; + i2_ = (_expr27 + NagaDimensions2D(texture_array_unbounded[0])); + int2 _expr32 = i2_; + i2_ = (_expr32 + NagaDimensions2D(texture_array_unbounded[uniform_index])); + int2 _expr36 = i2_; + i2_ = (_expr36 + NagaDimensions2D(texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)])); + float4 _expr40 = v4_; + float4 _expr45 = texture_array_bounded[0].Gather(samp[0], uv); + v4_ = (_expr40 + _expr45); + float4 _expr47 = v4_; + float4 _expr50 = texture_array_bounded[uniform_index].Gather(samp[uniform_index], uv); + v4_ = (_expr47 + _expr50); + float4 _expr52 = v4_; + float4 _expr55 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Gather(samp[NonUniformResourceIndex(non_uniform_index)], uv); + v4_ = (_expr52 + _expr55); + float4 _expr57 = v4_; + float4 _expr63 = texture_array_depth[0].GatherCmp(samp_comp[0], uv, 0.0); + v4_ = (_expr57 + _expr63); + float4 _expr65 = v4_; + float4 _expr69 = texture_array_depth[uniform_index].GatherCmp(samp_comp[uniform_index], uv, 0.0); + v4_ = (_expr65 + _expr69); + float4 _expr71 = v4_; + float4 _expr75 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].GatherCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + v4_ = (_expr71 + _expr75); + float4 _expr77 = v4_; + float4 _expr81 = texture_array_unbounded[0].Load(int3(pix, 0)); + v4_ = (_expr77 + _expr81); + float4 _expr83 = v4_; + float4 _expr86 = texture_array_unbounded[uniform_index].Load(int3(pix, 0)); + v4_ = (_expr83 + _expr86); + float4 _expr88 = v4_; + float4 _expr91 = texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)].Load(int3(pix, 0)); + v4_ = (_expr88 + _expr91); + int _expr93 = i1_; + i1_ = (_expr93 + NagaNumLayers2DArray(texture_array_2darray[0])); + int _expr98 = i1_; + i1_ = (_expr98 + NagaNumLayers2DArray(texture_array_2darray[uniform_index])); + int _expr102 = i1_; + i1_ = (_expr102 + NagaNumLayers2DArray(texture_array_2darray[NonUniformResourceIndex(non_uniform_index)])); + int _expr106 = i1_; + i1_ = (_expr106 + NagaNumLevels2D(texture_array_bounded[0])); + int _expr111 = i1_; + i1_ = (_expr111 + NagaNumLevels2D(texture_array_bounded[uniform_index])); + int _expr115 = i1_; + i1_ = (_expr115 + NagaNumLevels2D(texture_array_bounded[NonUniformResourceIndex(non_uniform_index)])); + int _expr119 = i1_; + i1_ = (_expr119 + NagaMSNumSamples2D(texture_array_multisampled[0])); + int _expr124 = i1_; + i1_ = (_expr124 + NagaMSNumSamples2D(texture_array_multisampled[uniform_index])); + int _expr128 = i1_; + i1_ = (_expr128 + NagaMSNumSamples2D(texture_array_multisampled[NonUniformResourceIndex(non_uniform_index)])); + float4 _expr132 = v4_; + float4 _expr137 = texture_array_bounded[0].Sample(samp[0], uv); + v4_ = (_expr132 + _expr137); + float4 _expr139 = v4_; + float4 _expr142 = texture_array_bounded[uniform_index].Sample(samp[uniform_index], uv); + v4_ = (_expr139 + _expr142); + float4 _expr144 = v4_; + float4 _expr147 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Sample(samp[NonUniformResourceIndex(non_uniform_index)], uv); + v4_ = (_expr144 + _expr147); + float4 _expr149 = v4_; + float4 _expr155 = texture_array_bounded[0].SampleBias(samp[0], uv, 0.0); + v4_ = (_expr149 + _expr155); + float4 _expr157 = v4_; + float4 _expr161 = texture_array_bounded[uniform_index].SampleBias(samp[uniform_index], uv, 0.0); + v4_ = (_expr157 + _expr161); + float4 _expr163 = v4_; + float4 _expr167 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleBias(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + v4_ = (_expr163 + _expr167); + float _expr169 = v1_; + float _expr175 = texture_array_depth[0].SampleCmp(samp_comp[0], uv, 0.0); + v1_ = (_expr169 + _expr175); + float _expr177 = v1_; + float _expr181 = texture_array_depth[uniform_index].SampleCmp(samp_comp[uniform_index], uv, 0.0); + v1_ = (_expr177 + _expr181); + float _expr183 = v1_; + float _expr187 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + v1_ = (_expr183 + _expr187); + float _expr189 = v1_; + float _expr195 = texture_array_depth[0].SampleCmpLevelZero(samp_comp[0], uv, 0.0); + v1_ = (_expr189 + _expr195); + float _expr197 = v1_; + float _expr201 = texture_array_depth[uniform_index].SampleCmpLevelZero(samp_comp[uniform_index], uv, 0.0); + v1_ = (_expr197 + _expr201); + float _expr203 = v1_; + float _expr207 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmpLevelZero(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + v1_ = (_expr203 + _expr207); + float4 _expr209 = v4_; + float4 _expr214 = texture_array_bounded[0].SampleGrad(samp[0], uv, uv, uv); + v4_ = (_expr209 + _expr214); + float4 _expr216 = v4_; + float4 _expr219 = texture_array_bounded[uniform_index].SampleGrad(samp[uniform_index], uv, uv, uv); + v4_ = (_expr216 + _expr219); + float4 _expr221 = v4_; + float4 _expr224 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleGrad(samp[NonUniformResourceIndex(non_uniform_index)], uv, uv, uv); + v4_ = (_expr221 + _expr224); + float4 _expr226 = v4_; + float4 _expr232 = texture_array_bounded[0].SampleLevel(samp[0], uv, 0.0); + v4_ = (_expr226 + _expr232); + float4 _expr234 = v4_; + float4 _expr238 = texture_array_bounded[uniform_index].SampleLevel(samp[uniform_index], uv, 0.0); + v4_ = (_expr234 + _expr238); + float4 _expr240 = v4_; + float4 _expr244 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleLevel(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + v4_ = (_expr240 + _expr244); + float4 _expr248 = v4_; + texture_array_storage[0][pix] = _expr248; + float4 _expr250 = v4_; + texture_array_storage[uniform_index][pix] = _expr250; + float4 _expr252 = v4_; + texture_array_storage[NonUniformResourceIndex(non_uniform_index)][pix] = _expr252; + int2 _expr253 = i2_; + int _expr254 = i1_; + float2 v2_ = float2((_expr253 + (_expr254).xx)); + float4 _expr258 = v4_; + float _expr265 = v1_; + return ((_expr258 + float4(v2_.x, v2_.y, v2_.x, v2_.y)) + (_expr265).xxxx); +} diff --git a/tests/out/hlsl/binding-arrays.hlsl.config b/tests/out/hlsl/binding-arrays.hlsl.config new file mode 100644 index 000000000..98453a04e --- /dev/null +++ b/tests/out/hlsl/binding-arrays.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=(main:ps_5_1 ) +compute=() diff --git a/tests/out/msl/binding-arrays.msl b/tests/out/msl/binding-arrays.msl new file mode 100644 index 000000000..7291e77f2 --- /dev/null +++ b/tests/out/msl/binding-arrays.msl @@ -0,0 +1,160 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct UniformIndex { + uint index; +}; +struct FragmentIn { + uint index; +}; + +struct main_Input { + uint index [[user(loc0), flat]]; +}; +struct main_Output { + metal::float4 member [[color(0)]]; +}; +fragment main_Output main_( + main_Input varyings [[stage_in]] +, metal::array, 10> texture_array_unbounded [[texture(0)]] +, metal::array, 5> texture_array_bounded [[user(fake0)]] +, metal::array, 5> texture_array_2darray [[user(fake0)]] +, metal::array, 5> texture_array_multisampled [[user(fake0)]] +, metal::array, 5> texture_array_depth [[user(fake0)]] +, metal::array, 5> texture_array_storage [[user(fake0)]] +, metal::array samp [[user(fake0)]] +, metal::array samp_comp [[user(fake0)]] +, constant UniformIndex& uni [[user(fake0)]] +) { + const FragmentIn fragment_in = { varyings.index }; + int i1_ = 0; + metal::int2 i2_; + float v1_ = 0.0; + metal::float4 v4_; + uint uniform_index = uni.index; + uint non_uniform_index = fragment_in.index; + i2_ = metal::int2(0); + v4_ = metal::float4(0.0); + metal::float2 uv = metal::float2(0.0); + metal::int2 pix = metal::int2(0); + metal::int2 _e27 = i2_; + i2_ = _e27 + metal::int2(texture_array_unbounded[0].get_width(), texture_array_unbounded[0].get_height()); + metal::int2 _e32 = i2_; + i2_ = _e32 + metal::int2(texture_array_unbounded[uniform_index].get_width(), texture_array_unbounded[uniform_index].get_height()); + metal::int2 _e36 = i2_; + i2_ = _e36 + metal::int2(texture_array_unbounded[non_uniform_index].get_width(), texture_array_unbounded[non_uniform_index].get_height()); + metal::float4 _e40 = v4_; + metal::float4 _e45 = texture_array_bounded[0].gather(samp[0], uv); + v4_ = _e40 + _e45; + metal::float4 _e47 = v4_; + metal::float4 _e50 = texture_array_bounded[uniform_index].gather(samp[uniform_index], uv); + v4_ = _e47 + _e50; + metal::float4 _e52 = v4_; + metal::float4 _e55 = texture_array_bounded[non_uniform_index].gather(samp[non_uniform_index], uv); + v4_ = _e52 + _e55; + metal::float4 _e57 = v4_; + metal::float4 _e63 = texture_array_depth[0].gather_compare(samp_comp[0], uv, 0.0); + v4_ = _e57 + _e63; + metal::float4 _e65 = v4_; + metal::float4 _e69 = texture_array_depth[uniform_index].gather_compare(samp_comp[uniform_index], uv, 0.0); + v4_ = _e65 + _e69; + metal::float4 _e71 = v4_; + metal::float4 _e75 = texture_array_depth[non_uniform_index].gather_compare(samp_comp[non_uniform_index], uv, 0.0); + v4_ = _e71 + _e75; + metal::float4 _e77 = v4_; + metal::float4 _e81 = texture_array_unbounded[0].read(metal::uint2(pix), 0); + v4_ = _e77 + _e81; + metal::float4 _e83 = v4_; + metal::float4 _e86 = texture_array_unbounded[uniform_index].read(metal::uint2(pix), 0); + v4_ = _e83 + _e86; + metal::float4 _e88 = v4_; + metal::float4 _e91 = texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0); + v4_ = _e88 + _e91; + int _e93 = i1_; + i1_ = _e93 + int(texture_array_2darray[0].get_array_size()); + int _e98 = i1_; + i1_ = _e98 + int(texture_array_2darray[uniform_index].get_array_size()); + int _e102 = i1_; + i1_ = _e102 + int(texture_array_2darray[non_uniform_index].get_array_size()); + int _e106 = i1_; + i1_ = _e106 + int(texture_array_bounded[0].get_num_mip_levels()); + int _e111 = i1_; + i1_ = _e111 + int(texture_array_bounded[uniform_index].get_num_mip_levels()); + int _e115 = i1_; + i1_ = _e115 + int(texture_array_bounded[non_uniform_index].get_num_mip_levels()); + int _e119 = i1_; + i1_ = _e119 + int(texture_array_multisampled[0].get_num_samples()); + int _e124 = i1_; + i1_ = _e124 + int(texture_array_multisampled[uniform_index].get_num_samples()); + int _e128 = i1_; + i1_ = _e128 + int(texture_array_multisampled[non_uniform_index].get_num_samples()); + metal::float4 _e132 = v4_; + metal::float4 _e137 = texture_array_bounded[0].sample(samp[0], uv); + v4_ = _e132 + _e137; + metal::float4 _e139 = v4_; + metal::float4 _e142 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv); + v4_ = _e139 + _e142; + metal::float4 _e144 = v4_; + metal::float4 _e147 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv); + v4_ = _e144 + _e147; + metal::float4 _e149 = v4_; + metal::float4 _e155 = texture_array_bounded[0].sample(samp[0], uv, metal::bias(0.0)); + v4_ = _e149 + _e155; + metal::float4 _e157 = v4_; + metal::float4 _e161 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::bias(0.0)); + v4_ = _e157 + _e161; + metal::float4 _e163 = v4_; + metal::float4 _e167 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::bias(0.0)); + v4_ = _e163 + _e167; + float _e169 = v1_; + float _e175 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); + v1_ = _e169 + _e175; + float _e177 = v1_; + float _e181 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); + v1_ = _e177 + _e181; + float _e183 = v1_; + float _e187 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); + v1_ = _e183 + _e187; + float _e189 = v1_; + float _e195 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); + v1_ = _e189 + _e195; + float _e197 = v1_; + float _e201 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); + v1_ = _e197 + _e201; + float _e203 = v1_; + float _e207 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); + v1_ = _e203 + _e207; + metal::float4 _e209 = v4_; + metal::float4 _e214 = texture_array_bounded[0].sample(samp[0], uv, metal::gradient2d(uv, uv)); + v4_ = _e209 + _e214; + metal::float4 _e216 = v4_; + metal::float4 _e219 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::gradient2d(uv, uv)); + v4_ = _e216 + _e219; + metal::float4 _e221 = v4_; + metal::float4 _e224 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::gradient2d(uv, uv)); + v4_ = _e221 + _e224; + metal::float4 _e226 = v4_; + metal::float4 _e232 = texture_array_bounded[0].sample(samp[0], uv, metal::level(0.0)); + v4_ = _e226 + _e232; + metal::float4 _e234 = v4_; + metal::float4 _e238 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::level(0.0)); + v4_ = _e234 + _e238; + metal::float4 _e240 = v4_; + metal::float4 _e244 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::level(0.0)); + v4_ = _e240 + _e244; + metal::float4 _e248 = v4_; + texture_array_storage[0].write(_e248, metal::uint2(pix)); + metal::float4 _e250 = v4_; + texture_array_storage[uniform_index].write(_e250, metal::uint2(pix)); + metal::float4 _e252 = v4_; + texture_array_storage[non_uniform_index].write(_e252, metal::uint2(pix)); + metal::int2 _e253 = i2_; + int _e254 = i1_; + metal::float2 v2_ = static_cast(_e253 + metal::int2(_e254)); + metal::float4 _e258 = v4_; + float _e265 = v1_; + return main_Output { (_e258 + metal::float4(v2_.x, v2_.y, v2_.x, v2_.y)) + metal::float4(_e265) }; +} diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm new file mode 100644 index 000000000..71f13c3d9 --- /dev/null +++ b/tests/out/spv/binding-arrays.spvasm @@ -0,0 +1,487 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 382 +OpCapability Shader +OpCapability ImageQuery +OpCapability ShaderNonUniform +OpExtension "SPV_EXT_descriptor_indexing" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %63 "main" %58 %61 +OpExecutionMode %63 OriginUpperLeft +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %24 0 Offset 0 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 0 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 1 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 2 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 3 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 4 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 5 +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 6 +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 7 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 8 +OpDecorate %46 Block +OpMemberDecorate %46 0 Offset 0 +OpDecorate %58 Location 0 +OpDecorate %58 Flat +OpDecorate %61 Location 0 +OpDecorate %91 NonUniform +OpDecorate %114 NonUniform +OpDecorate %116 NonUniform +OpDecorate %141 NonUniform +OpDecorate %143 NonUniform +OpDecorate %159 NonUniform +OpDecorate %178 NonUniform +OpDecorate %194 NonUniform +OpDecorate %210 NonUniform +OpDecorate %231 NonUniform +OpDecorate %233 NonUniform +OpDecorate %255 NonUniform +OpDecorate %257 NonUniform +OpDecorate %279 NonUniform +OpDecorate %281 NonUniform +OpDecorate %303 NonUniform +OpDecorate %305 NonUniform +OpDecorate %327 NonUniform +OpDecorate %329 NonUniform +OpDecorate %351 NonUniform +OpDecorate %353 NonUniform +OpDecorate %365 NonUniform +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 5 +%5 = OpConstant %4 0 +%7 = OpTypeFloat 32 +%6 = OpConstant %7 0.0 +%8 = OpTypeInt 32 0 +%9 = OpTypeStruct %8 +%10 = OpTypeImage %7 2D 0 0 0 1 Unknown +%11 = OpTypeRuntimeArray %10 +%12 = OpTypeArray %10 %3 +%13 = OpTypeImage %7 2D 0 1 0 1 Unknown +%14 = OpTypeArray %13 %3 +%15 = OpTypeImage %7 2D 0 0 1 1 Unknown +%16 = OpTypeArray %15 %3 +%17 = OpTypeImage %7 2D 1 0 0 1 Unknown +%18 = OpTypeArray %17 %3 +%19 = OpTypeImage %7 2D 0 0 0 2 Rgba32f +%20 = OpTypeArray %19 %3 +%21 = OpTypeSampler +%22 = OpTypeArray %21 %3 +%23 = OpTypeArray %21 %3 +%24 = OpTypeStruct %8 +%25 = OpTypeVector %7 4 +%26 = OpTypeVector %4 2 +%30 = OpConstant %8 10 +%29 = OpTypeArray %10 %30 +%28 = OpTypePointer UniformConstant %29 +%27 = OpVariable %28 UniformConstant +%32 = OpTypePointer UniformConstant %12 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %14 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %16 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %18 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %20 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %22 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %23 +%43 = OpVariable %44 UniformConstant +%46 = OpTypeStruct %9 +%47 = OpTypePointer Uniform %46 +%45 = OpVariable %47 Uniform +%49 = OpTypePointer Function %4 +%51 = OpTypePointer Function %26 +%53 = OpTypePointer Function %7 +%55 = OpTypePointer Function %25 +%59 = OpTypePointer Input %8 +%58 = OpVariable %59 Input +%62 = OpTypePointer Output %25 +%61 = OpVariable %62 Output +%64 = OpTypeFunction %2 +%65 = OpTypePointer Uniform %9 +%66 = OpConstant %8 0 +%69 = OpTypePointer Uniform %8 +%75 = OpTypeVector %7 2 +%79 = OpTypePointer UniformConstant %10 +%97 = OpTypePointer UniformConstant %21 +%100 = OpTypeSampledImage %10 +%121 = OpTypePointer UniformConstant %17 +%124 = OpTypePointer UniformConstant %21 +%127 = OpTypeSampledImage %17 +%163 = OpTypePointer UniformConstant %13 +%166 = OpTypeVector %4 3 +%198 = OpTypePointer UniformConstant %15 +%357 = OpTypePointer UniformConstant %19 +%63 = OpFunction %2 None %64 +%56 = OpLabel +%50 = OpVariable %51 Function +%54 = OpVariable %55 Function +%48 = OpVariable %49 Function %5 +%52 = OpVariable %53 Function %6 +%60 = OpLoad %8 %58 +%57 = OpCompositeConstruct %24 %60 +%67 = OpAccessChain %65 %45 %66 +OpBranch %68 +%68 = OpLabel +%70 = OpAccessChain %69 %67 %66 +%71 = OpLoad %8 %70 +%72 = OpCompositeExtract %8 %57 0 +%73 = OpCompositeConstruct %26 %5 %5 +OpStore %50 %73 +%74 = OpCompositeConstruct %25 %6 %6 %6 %6 +OpStore %54 %74 +%76 = OpCompositeConstruct %75 %6 %6 +%77 = OpCompositeConstruct %26 %5 %5 +%78 = OpLoad %26 %50 +%80 = OpAccessChain %79 %27 %66 +%81 = OpLoad %10 %80 +%82 = OpImageQuerySizeLod %26 %81 %66 +%83 = OpIAdd %26 %78 %82 +OpStore %50 %83 +%84 = OpLoad %26 %50 +%85 = OpAccessChain %79 %27 %71 +%86 = OpLoad %10 %85 +%87 = OpImageQuerySizeLod %26 %86 %66 +%88 = OpIAdd %26 %84 %87 +OpStore %50 %88 +%89 = OpLoad %26 %50 +%90 = OpAccessChain %79 %27 %72 +%91 = OpLoad %10 %90 +%92 = OpImageQuerySizeLod %26 %91 %66 +%93 = OpIAdd %26 %89 %92 +OpStore %50 %93 +%94 = OpLoad %25 %54 +%95 = OpAccessChain %79 %31 %66 +%96 = OpLoad %10 %95 +%98 = OpAccessChain %97 %41 %66 +%99 = OpLoad %21 %98 +%101 = OpSampledImage %100 %96 %99 +%102 = OpImageGather %25 %101 %76 %66 +%103 = OpFAdd %25 %94 %102 +OpStore %54 %103 +%104 = OpLoad %25 %54 +%105 = OpAccessChain %79 %31 %71 +%106 = OpLoad %10 %105 +%107 = OpAccessChain %97 %41 %71 +%108 = OpLoad %21 %107 +%109 = OpSampledImage %100 %106 %108 +%110 = OpImageGather %25 %109 %76 %66 +%111 = OpFAdd %25 %104 %110 +OpStore %54 %111 +%112 = OpLoad %25 %54 +%113 = OpAccessChain %79 %31 %72 +%114 = OpLoad %10 %113 +%115 = OpAccessChain %97 %41 %72 +%116 = OpLoad %21 %115 +%117 = OpSampledImage %100 %114 %116 +%118 = OpImageGather %25 %117 %76 %66 +%119 = OpFAdd %25 %112 %118 +OpStore %54 %119 +%120 = OpLoad %25 %54 +%122 = OpAccessChain %121 %37 %66 +%123 = OpLoad %17 %122 +%125 = OpAccessChain %124 %43 %66 +%126 = OpLoad %21 %125 +%128 = OpSampledImage %127 %123 %126 +%129 = OpImageDrefGather %25 %128 %76 %6 +%130 = OpFAdd %25 %120 %129 +OpStore %54 %130 +%131 = OpLoad %25 %54 +%132 = OpAccessChain %121 %37 %71 +%133 = OpLoad %17 %132 +%134 = OpAccessChain %124 %43 %71 +%135 = OpLoad %21 %134 +%136 = OpSampledImage %127 %133 %135 +%137 = OpImageDrefGather %25 %136 %76 %6 +%138 = OpFAdd %25 %131 %137 +OpStore %54 %138 +%139 = OpLoad %25 %54 +%140 = OpAccessChain %121 %37 %72 +%141 = OpLoad %17 %140 +%142 = OpAccessChain %124 %43 %72 +%143 = OpLoad %21 %142 +%144 = OpSampledImage %127 %141 %143 +%145 = OpImageDrefGather %25 %144 %76 %6 +%146 = OpFAdd %25 %139 %145 +OpStore %54 %146 +%147 = OpLoad %25 %54 +%148 = OpAccessChain %79 %27 %66 +%149 = OpLoad %10 %148 +%150 = OpImageFetch %25 %149 %77 Lod %5 +%151 = OpFAdd %25 %147 %150 +OpStore %54 %151 +%152 = OpLoad %25 %54 +%153 = OpAccessChain %79 %27 %71 +%154 = OpLoad %10 %153 +%155 = OpImageFetch %25 %154 %77 Lod %5 +%156 = OpFAdd %25 %152 %155 +OpStore %54 %156 +%157 = OpLoad %25 %54 +%158 = OpAccessChain %79 %27 %72 +%159 = OpLoad %10 %158 +%160 = OpImageFetch %25 %159 %77 Lod %5 +%161 = OpFAdd %25 %157 %160 +OpStore %54 %161 +%162 = OpLoad %4 %48 +%164 = OpAccessChain %163 %33 %66 +%165 = OpLoad %13 %164 +%167 = OpImageQuerySizeLod %166 %165 %66 +%168 = OpCompositeExtract %4 %167 2 +%169 = OpIAdd %4 %162 %168 +OpStore %48 %169 +%170 = OpLoad %4 %48 +%171 = OpAccessChain %163 %33 %71 +%172 = OpLoad %13 %171 +%173 = OpImageQuerySizeLod %166 %172 %66 +%174 = OpCompositeExtract %4 %173 2 +%175 = OpIAdd %4 %170 %174 +OpStore %48 %175 +%176 = OpLoad %4 %48 +%177 = OpAccessChain %163 %33 %72 +%178 = OpLoad %13 %177 +%179 = OpImageQuerySizeLod %166 %178 %66 +%180 = OpCompositeExtract %4 %179 2 +%181 = OpIAdd %4 %176 %180 +OpStore %48 %181 +%182 = OpLoad %4 %48 +%183 = OpAccessChain %79 %31 %66 +%184 = OpLoad %10 %183 +%185 = OpImageQueryLevels %4 %184 +%186 = OpIAdd %4 %182 %185 +OpStore %48 %186 +%187 = OpLoad %4 %48 +%188 = OpAccessChain %79 %31 %71 +%189 = OpLoad %10 %188 +%190 = OpImageQueryLevels %4 %189 +%191 = OpIAdd %4 %187 %190 +OpStore %48 %191 +%192 = OpLoad %4 %48 +%193 = OpAccessChain %79 %31 %72 +%194 = OpLoad %10 %193 +%195 = OpImageQueryLevels %4 %194 +%196 = OpIAdd %4 %192 %195 +OpStore %48 %196 +%197 = OpLoad %4 %48 +%199 = OpAccessChain %198 %35 %66 +%200 = OpLoad %15 %199 +%201 = OpImageQuerySamples %4 %200 +%202 = OpIAdd %4 %197 %201 +OpStore %48 %202 +%203 = OpLoad %4 %48 +%204 = OpAccessChain %198 %35 %71 +%205 = OpLoad %15 %204 +%206 = OpImageQuerySamples %4 %205 +%207 = OpIAdd %4 %203 %206 +OpStore %48 %207 +%208 = OpLoad %4 %48 +%209 = OpAccessChain %198 %35 %72 +%210 = OpLoad %15 %209 +%211 = OpImageQuerySamples %4 %210 +%212 = OpIAdd %4 %208 %211 +OpStore %48 %212 +%213 = OpLoad %25 %54 +%214 = OpAccessChain %79 %31 %66 +%215 = OpLoad %10 %214 +%216 = OpAccessChain %97 %41 %66 +%217 = OpLoad %21 %216 +%218 = OpSampledImage %100 %215 %217 +%219 = OpImageSampleImplicitLod %25 %218 %76 +%220 = OpFAdd %25 %213 %219 +OpStore %54 %220 +%221 = OpLoad %25 %54 +%222 = OpAccessChain %79 %31 %71 +%223 = OpLoad %10 %222 +%224 = OpAccessChain %97 %41 %71 +%225 = OpLoad %21 %224 +%226 = OpSampledImage %100 %223 %225 +%227 = OpImageSampleImplicitLod %25 %226 %76 +%228 = OpFAdd %25 %221 %227 +OpStore %54 %228 +%229 = OpLoad %25 %54 +%230 = OpAccessChain %79 %31 %72 +%231 = OpLoad %10 %230 +%232 = OpAccessChain %97 %41 %72 +%233 = OpLoad %21 %232 +%234 = OpSampledImage %100 %231 %233 +%235 = OpImageSampleImplicitLod %25 %234 %76 +%236 = OpFAdd %25 %229 %235 +OpStore %54 %236 +%237 = OpLoad %25 %54 +%238 = OpAccessChain %79 %31 %66 +%239 = OpLoad %10 %238 +%240 = OpAccessChain %97 %41 %66 +%241 = OpLoad %21 %240 +%242 = OpSampledImage %100 %239 %241 +%243 = OpImageSampleImplicitLod %25 %242 %76 Bias %6 +%244 = OpFAdd %25 %237 %243 +OpStore %54 %244 +%245 = OpLoad %25 %54 +%246 = OpAccessChain %79 %31 %71 +%247 = OpLoad %10 %246 +%248 = OpAccessChain %97 %41 %71 +%249 = OpLoad %21 %248 +%250 = OpSampledImage %100 %247 %249 +%251 = OpImageSampleImplicitLod %25 %250 %76 Bias %6 +%252 = OpFAdd %25 %245 %251 +OpStore %54 %252 +%253 = OpLoad %25 %54 +%254 = OpAccessChain %79 %31 %72 +%255 = OpLoad %10 %254 +%256 = OpAccessChain %97 %41 %72 +%257 = OpLoad %21 %256 +%258 = OpSampledImage %100 %255 %257 +%259 = OpImageSampleImplicitLod %25 %258 %76 Bias %6 +%260 = OpFAdd %25 %253 %259 +OpStore %54 %260 +%261 = OpLoad %7 %52 +%262 = OpAccessChain %121 %37 %66 +%263 = OpLoad %17 %262 +%264 = OpAccessChain %124 %43 %66 +%265 = OpLoad %21 %264 +%266 = OpSampledImage %127 %263 %265 +%267 = OpImageSampleDrefImplicitLod %7 %266 %76 %6 +%268 = OpFAdd %7 %261 %267 +OpStore %52 %268 +%269 = OpLoad %7 %52 +%270 = OpAccessChain %121 %37 %71 +%271 = OpLoad %17 %270 +%272 = OpAccessChain %124 %43 %71 +%273 = OpLoad %21 %272 +%274 = OpSampledImage %127 %271 %273 +%275 = OpImageSampleDrefImplicitLod %7 %274 %76 %6 +%276 = OpFAdd %7 %269 %275 +OpStore %52 %276 +%277 = OpLoad %7 %52 +%278 = OpAccessChain %121 %37 %72 +%279 = OpLoad %17 %278 +%280 = OpAccessChain %124 %43 %72 +%281 = OpLoad %21 %280 +%282 = OpSampledImage %127 %279 %281 +%283 = OpImageSampleDrefImplicitLod %7 %282 %76 %6 +%284 = OpFAdd %7 %277 %283 +OpStore %52 %284 +%285 = OpLoad %7 %52 +%286 = OpAccessChain %121 %37 %66 +%287 = OpLoad %17 %286 +%288 = OpAccessChain %124 %43 %66 +%289 = OpLoad %21 %288 +%290 = OpSampledImage %127 %287 %289 +%291 = OpImageSampleDrefExplicitLod %7 %290 %76 %6 Lod %6 +%292 = OpFAdd %7 %285 %291 +OpStore %52 %292 +%293 = OpLoad %7 %52 +%294 = OpAccessChain %121 %37 %71 +%295 = OpLoad %17 %294 +%296 = OpAccessChain %124 %43 %71 +%297 = OpLoad %21 %296 +%298 = OpSampledImage %127 %295 %297 +%299 = OpImageSampleDrefExplicitLod %7 %298 %76 %6 Lod %6 +%300 = OpFAdd %7 %293 %299 +OpStore %52 %300 +%301 = OpLoad %7 %52 +%302 = OpAccessChain %121 %37 %72 +%303 = OpLoad %17 %302 +%304 = OpAccessChain %124 %43 %72 +%305 = OpLoad %21 %304 +%306 = OpSampledImage %127 %303 %305 +%307 = OpImageSampleDrefExplicitLod %7 %306 %76 %6 Lod %6 +%308 = OpFAdd %7 %301 %307 +OpStore %52 %308 +%309 = OpLoad %25 %54 +%310 = OpAccessChain %79 %31 %66 +%311 = OpLoad %10 %310 +%312 = OpAccessChain %97 %41 %66 +%313 = OpLoad %21 %312 +%314 = OpSampledImage %100 %311 %313 +%315 = OpImageSampleExplicitLod %25 %314 %76 Grad %76 %76 +%316 = OpFAdd %25 %309 %315 +OpStore %54 %316 +%317 = OpLoad %25 %54 +%318 = OpAccessChain %79 %31 %71 +%319 = OpLoad %10 %318 +%320 = OpAccessChain %97 %41 %71 +%321 = OpLoad %21 %320 +%322 = OpSampledImage %100 %319 %321 +%323 = OpImageSampleExplicitLod %25 %322 %76 Grad %76 %76 +%324 = OpFAdd %25 %317 %323 +OpStore %54 %324 +%325 = OpLoad %25 %54 +%326 = OpAccessChain %79 %31 %72 +%327 = OpLoad %10 %326 +%328 = OpAccessChain %97 %41 %72 +%329 = OpLoad %21 %328 +%330 = OpSampledImage %100 %327 %329 +%331 = OpImageSampleExplicitLod %25 %330 %76 Grad %76 %76 +%332 = OpFAdd %25 %325 %331 +OpStore %54 %332 +%333 = OpLoad %25 %54 +%334 = OpAccessChain %79 %31 %66 +%335 = OpLoad %10 %334 +%336 = OpAccessChain %97 %41 %66 +%337 = OpLoad %21 %336 +%338 = OpSampledImage %100 %335 %337 +%339 = OpImageSampleExplicitLod %25 %338 %76 Lod %6 +%340 = OpFAdd %25 %333 %339 +OpStore %54 %340 +%341 = OpLoad %25 %54 +%342 = OpAccessChain %79 %31 %71 +%343 = OpLoad %10 %342 +%344 = OpAccessChain %97 %41 %71 +%345 = OpLoad %21 %344 +%346 = OpSampledImage %100 %343 %345 +%347 = OpImageSampleExplicitLod %25 %346 %76 Lod %6 +%348 = OpFAdd %25 %341 %347 +OpStore %54 %348 +%349 = OpLoad %25 %54 +%350 = OpAccessChain %79 %31 %72 +%351 = OpLoad %10 %350 +%352 = OpAccessChain %97 %41 %72 +%353 = OpLoad %21 %352 +%354 = OpSampledImage %100 %351 %353 +%355 = OpImageSampleExplicitLod %25 %354 %76 Lod %6 +%356 = OpFAdd %25 %349 %355 +OpStore %54 %356 +%358 = OpAccessChain %357 %39 %66 +%359 = OpLoad %19 %358 +%360 = OpLoad %25 %54 +OpImageWrite %359 %77 %360 +%361 = OpAccessChain %357 %39 %71 +%362 = OpLoad %19 %361 +%363 = OpLoad %25 %54 +OpImageWrite %362 %77 %363 +%364 = OpAccessChain %357 %39 %72 +%365 = OpLoad %19 %364 +%366 = OpLoad %25 %54 +OpImageWrite %365 %77 %366 +%367 = OpLoad %26 %50 +%368 = OpLoad %4 %48 +%369 = OpCompositeConstruct %26 %368 %368 +%370 = OpIAdd %26 %367 %369 +%371 = OpConvertSToF %75 %370 +%372 = OpLoad %25 %54 +%373 = OpCompositeExtract %7 %371 0 +%374 = OpCompositeExtract %7 %371 1 +%375 = OpCompositeExtract %7 %371 0 +%376 = OpCompositeExtract %7 %371 1 +%377 = OpCompositeConstruct %25 %373 %374 %375 %376 +%378 = OpFAdd %25 %372 %377 +%379 = OpLoad %7 %52 +%380 = OpCompositeConstruct %25 %379 %379 %379 %379 +%381 = OpFAdd %25 %378 %380 +OpStore %61 %381 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/binding-arrays.wgsl b/tests/out/wgsl/binding-arrays.wgsl new file mode 100644 index 000000000..0760aef72 --- /dev/null +++ b/tests/out/wgsl/binding-arrays.wgsl @@ -0,0 +1,170 @@ +struct UniformIndex { + index: u32, +} + +struct FragmentIn { + @location(0) index: u32, +} + +@group(0) @binding(0) +var texture_array_unbounded: binding_array>; +@group(0) @binding(1) +var texture_array_bounded: binding_array,5>; +@group(0) @binding(2) +var texture_array_2darray: binding_array,5>; +@group(0) @binding(3) +var texture_array_multisampled: binding_array,5>; +@group(0) @binding(4) +var texture_array_depth: binding_array; +@group(0) @binding(5) +var texture_array_storage: binding_array,5>; +@group(0) @binding(6) +var samp: binding_array; +@group(0) @binding(7) +var samp_comp: binding_array; +@group(0) @binding(8) +var uni: UniformIndex; + +@fragment +fn main(fragment_in: FragmentIn) -> @location(0) vec4 { + var i1_: i32 = 0; + var i2_: vec2; + var v1_: f32 = 0.0; + var v4_: vec4; + + let uniform_index = uni.index; + let non_uniform_index = fragment_in.index; + i2_ = vec2(0); + v4_ = vec4(0.0); + let uv = vec2(0.0); + let pix = vec2(0); + let _e27 = i2_; + let _e30 = textureDimensions(texture_array_unbounded[0]); + i2_ = (_e27 + _e30); + let _e32 = i2_; + let _e34 = textureDimensions(texture_array_unbounded[uniform_index]); + i2_ = (_e32 + _e34); + let _e36 = i2_; + let _e38 = textureDimensions(texture_array_unbounded[non_uniform_index]); + i2_ = (_e36 + _e38); + let _e40 = v4_; + let _e45 = textureGather(0, texture_array_bounded[0], samp[0], uv); + v4_ = (_e40 + _e45); + let _e47 = v4_; + let _e50 = textureGather(0, texture_array_bounded[uniform_index], samp[uniform_index], uv); + v4_ = (_e47 + _e50); + let _e52 = v4_; + let _e55 = textureGather(0, texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); + v4_ = (_e52 + _e55); + let _e57 = v4_; + let _e63 = textureGatherCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + v4_ = (_e57 + _e63); + let _e65 = v4_; + let _e69 = textureGatherCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + v4_ = (_e65 + _e69); + let _e71 = v4_; + let _e75 = textureGatherCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + v4_ = (_e71 + _e75); + let _e77 = v4_; + let _e81 = textureLoad(texture_array_unbounded[0], pix, 0); + v4_ = (_e77 + _e81); + let _e83 = v4_; + let _e86 = textureLoad(texture_array_unbounded[uniform_index], pix, 0); + v4_ = (_e83 + _e86); + let _e88 = v4_; + let _e91 = textureLoad(texture_array_unbounded[non_uniform_index], pix, 0); + v4_ = (_e88 + _e91); + let _e93 = i1_; + let _e96 = textureNumLayers(texture_array_2darray[0]); + i1_ = (_e93 + _e96); + let _e98 = i1_; + let _e100 = textureNumLayers(texture_array_2darray[uniform_index]); + i1_ = (_e98 + _e100); + let _e102 = i1_; + let _e104 = textureNumLayers(texture_array_2darray[non_uniform_index]); + i1_ = (_e102 + _e104); + let _e106 = i1_; + let _e109 = textureNumLevels(texture_array_bounded[0]); + i1_ = (_e106 + _e109); + let _e111 = i1_; + let _e113 = textureNumLevels(texture_array_bounded[uniform_index]); + i1_ = (_e111 + _e113); + let _e115 = i1_; + let _e117 = textureNumLevels(texture_array_bounded[non_uniform_index]); + i1_ = (_e115 + _e117); + let _e119 = i1_; + let _e122 = textureNumSamples(texture_array_multisampled[0]); + i1_ = (_e119 + _e122); + let _e124 = i1_; + let _e126 = textureNumSamples(texture_array_multisampled[uniform_index]); + i1_ = (_e124 + _e126); + let _e128 = i1_; + let _e130 = textureNumSamples(texture_array_multisampled[non_uniform_index]); + i1_ = (_e128 + _e130); + let _e132 = v4_; + let _e137 = textureSample(texture_array_bounded[0], samp[0], uv); + v4_ = (_e132 + _e137); + let _e139 = v4_; + let _e142 = textureSample(texture_array_bounded[uniform_index], samp[uniform_index], uv); + v4_ = (_e139 + _e142); + let _e144 = v4_; + let _e147 = textureSample(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); + v4_ = (_e144 + _e147); + let _e149 = v4_; + let _e155 = textureSampleBias(texture_array_bounded[0], samp[0], uv, 0.0); + v4_ = (_e149 + _e155); + let _e157 = v4_; + let _e161 = textureSampleBias(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + v4_ = (_e157 + _e161); + let _e163 = v4_; + let _e167 = textureSampleBias(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); + v4_ = (_e163 + _e167); + let _e169 = v1_; + let _e175 = textureSampleCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + v1_ = (_e169 + _e175); + let _e177 = v1_; + let _e181 = textureSampleCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + v1_ = (_e177 + _e181); + let _e183 = v1_; + let _e187 = textureSampleCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + v1_ = (_e183 + _e187); + let _e189 = v1_; + let _e195 = textureSampleCompareLevel(texture_array_depth[0], samp_comp[0], uv, 0.0); + v1_ = (_e189 + _e195); + let _e197 = v1_; + let _e201 = textureSampleCompareLevel(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + v1_ = (_e197 + _e201); + let _e203 = v1_; + let _e207 = textureSampleCompareLevel(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + v1_ = (_e203 + _e207); + let _e209 = v4_; + let _e214 = textureSampleGrad(texture_array_bounded[0], samp[0], uv, uv, uv); + v4_ = (_e209 + _e214); + let _e216 = v4_; + let _e219 = textureSampleGrad(texture_array_bounded[uniform_index], samp[uniform_index], uv, uv, uv); + v4_ = (_e216 + _e219); + let _e221 = v4_; + let _e224 = textureSampleGrad(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, uv, uv); + v4_ = (_e221 + _e224); + let _e226 = v4_; + let _e232 = textureSampleLevel(texture_array_bounded[0], samp[0], uv, 0.0); + v4_ = (_e226 + _e232); + let _e234 = v4_; + let _e238 = textureSampleLevel(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + v4_ = (_e234 + _e238); + let _e240 = v4_; + let _e244 = textureSampleLevel(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); + v4_ = (_e240 + _e244); + let _e248 = v4_; + textureStore(texture_array_storage[0], pix, _e248); + let _e250 = v4_; + textureStore(texture_array_storage[uniform_index], pix, _e250); + let _e252 = v4_; + textureStore(texture_array_storage[non_uniform_index], pix, _e252); + let _e253 = i2_; + let _e254 = i1_; + let v2_ = vec2((_e253 + vec2(_e254))); + let _e258 = v4_; + let _e265 = v1_; + return ((_e258 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e265)); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 0726a4846..727149d98 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -43,6 +43,9 @@ struct SpirvOutParameters { clamp_frag_depth: bool, #[serde(default)] separate_entry_points: bool, + #[serde(default)] + #[cfg(all(feature = "deserialize", feature = "spv-out"))] + binding_map: naga::back::spv::BindingMap, } #[derive(Default, serde::Deserialize)] @@ -207,6 +210,7 @@ fn write_output_spv( Some(params.capabilities.clone()) }, bounds_check_policies, + binding_map: params.binding_map.clone(), ..spv::Options::default() }; @@ -498,6 +502,11 @@ fn convert_wgsl() { "math-functions", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ("cubeArrayShadow", Targets::GLSL), + ( + "binding-arrays", + Targets::WGSL | Targets::HLSL | Targets::METAL | Targets::SPIRV, + ), ]; for &(name, targets) in inputs.iter() { From 1aa9154964238af8c692cf521ff90e1f2395e147 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Mon, 25 Apr 2022 00:17:51 -0400 Subject: [PATCH 1704/2212] Binding arrays play nice with bounds checks (#1855) --- src/back/msl/writer.rs | 23 +- src/proc/index.rs | 21 +- tests/in/binding-arrays.param.ron | 5 + tests/out/msl/binding-arrays.msl | 24 +- tests/out/spv/binding-arrays.spvasm | 542 ++++++++++++++++------------ tests/snapshots.rs | 4 +- 6 files changed, 362 insertions(+), 257 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index e365f70d4..836985846 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1270,13 +1270,14 @@ impl Writer { let expression = &context.function.expressions[expr_handle]; log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { - crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => { + crate::Expression::Access { base, .. } + | crate::Expression::AccessIndex { base, .. } => { // This is an acceptable place to generate a `ReadZeroSkipWrite` check. // Since `put_bounds_checks` and `put_access_chain` handle an entire // access chain at a time, recursing back through `put_expression` only // for index expressions and the base object, we will never see intermediate // `Access` or `AccessIndex` expressions here. - let policy = context.choose_bounds_check_policy(expr_handle); + let policy = context.choose_bounds_check_policy(base); if policy == index::BoundsCheckPolicy::ReadZeroSkipWrite && self.put_bounds_checks( expr_handle, @@ -3339,11 +3340,19 @@ impl Writer { } if let Some(ref br) = var.binding { let good = match options.per_stage_map[ep.stage].resources.get(br) { - Some(target) => match module.types[var.ty].inner { - crate::TypeInner::Image { .. } => target.texture.is_some(), - crate::TypeInner::Sampler { .. } => target.sampler.is_some(), - _ => target.buffer.is_some(), - }, + Some(target) => { + let binding_ty = match module.types[var.ty].inner { + crate::TypeInner::BindingArray { base, .. } => { + &module.types[base].inner + } + ref ty => ty, + }; + match *binding_ty { + crate::TypeInner::Image { .. } => target.texture.is_some(), + crate::TypeInner::Sampler { .. } => target.sampler.is_some(), + _ => target.buffer.is_some(), + } + } None => false, }; if !good { diff --git a/src/proc/index.rs b/src/proc/index.rs index ead07052b..3fea79ec0 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -117,6 +117,10 @@ pub struct BoundsCheckPolicies { /// [`ImageStore`]: crate::Statement::ImageStore #[cfg_attr(feature = "deserialize", serde(default))] pub image: BoundsCheckPolicy, + + /// How should the generated code handle binding array indexes that are out of bounds. + #[cfg_attr(feature = "deserialize", serde(default))] + pub binding_array: BoundsCheckPolicy, } /// The default `BoundsCheckPolicy` is `Unchecked`. @@ -127,20 +131,27 @@ impl Default for BoundsCheckPolicy { } impl BoundsCheckPolicies { - /// Determine which policy applies to `access`. + /// Determine which policy applies to `base`. /// - /// `access` is a subtree of `Access` and `AccessIndex` expressions, - /// operating either on a pointer to a value, or on a value directly. + /// `base` is the "base" expression (the expression being indexed) of a `Access` + /// and `AccessIndex` expression. This is either a pointer, a value, being directly + /// indexed, or a binding array. /// /// See the documentation for [`BoundsCheckPolicy`] for details about /// when each policy applies. pub fn choose_policy( &self, - access: Handle, + base: Handle, types: &UniqueArena, info: &valid::FunctionInfo, ) -> BoundsCheckPolicy { - match info[access].ty.inner_with(types).pointer_space() { + let ty = info[base].ty.inner_with(types); + + if let crate::TypeInner::BindingArray { .. } = *ty { + return self.binding_array; + } + + match ty.pointer_space() { Some(crate::AddressSpace::Storage { access: _ } | crate::AddressSpace::Uniform) => { self.buffer } diff --git a/tests/in/binding-arrays.param.ron b/tests/in/binding-arrays.param.ron index b2f1dabaa..2d3e15263 100644 --- a/tests/in/binding-arrays.param.ron +++ b/tests/in/binding-arrays.param.ron @@ -35,5 +35,10 @@ binding_map: { (group: 0, binding: 0): (binding_array_size: Some(10)), }, + ), + bounds_check_policies: ( + index: ReadZeroSkipWrite, + buffer: ReadZeroSkipWrite, + image: ReadZeroSkipWrite, ) ) diff --git a/tests/out/msl/binding-arrays.msl b/tests/out/msl/binding-arrays.msl index 7291e77f2..62e0bb6b1 100644 --- a/tests/out/msl/binding-arrays.msl +++ b/tests/out/msl/binding-arrays.msl @@ -4,6 +4,12 @@ using metal::uint; +struct DefaultConstructible { + template + operator T() && { + return T {}; + } +}; struct UniformIndex { uint index; }; @@ -65,13 +71,13 @@ fragment main_Output main_( metal::float4 _e75 = texture_array_depth[non_uniform_index].gather_compare(samp_comp[non_uniform_index], uv, 0.0); v4_ = _e71 + _e75; metal::float4 _e77 = v4_; - metal::float4 _e81 = texture_array_unbounded[0].read(metal::uint2(pix), 0); + metal::float4 _e81 = (uint(0) < texture_array_unbounded[0].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[0].get_width(0), texture_array_unbounded[0].get_height(0))) ? texture_array_unbounded[0].read(metal::uint2(pix), 0): DefaultConstructible()); v4_ = _e77 + _e81; metal::float4 _e83 = v4_; - metal::float4 _e86 = texture_array_unbounded[uniform_index].read(metal::uint2(pix), 0); + metal::float4 _e86 = (uint(0) < texture_array_unbounded[uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[uniform_index].get_width(0), texture_array_unbounded[uniform_index].get_height(0))) ? texture_array_unbounded[uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); v4_ = _e83 + _e86; metal::float4 _e88 = v4_; - metal::float4 _e91 = texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0); + metal::float4 _e91 = (uint(0) < texture_array_unbounded[non_uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[non_uniform_index].get_width(0), texture_array_unbounded[non_uniform_index].get_height(0))) ? texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); v4_ = _e88 + _e91; int _e93 = i1_; i1_ = _e93 + int(texture_array_2darray[0].get_array_size()); @@ -146,11 +152,17 @@ fragment main_Output main_( metal::float4 _e244 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::level(0.0)); v4_ = _e240 + _e244; metal::float4 _e248 = v4_; - texture_array_storage[0].write(_e248, metal::uint2(pix)); + if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[0].get_width(), texture_array_storage[0].get_height()))) { + texture_array_storage[0].write(_e248, metal::uint2(pix)); + } metal::float4 _e250 = v4_; - texture_array_storage[uniform_index].write(_e250, metal::uint2(pix)); + if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[uniform_index].get_width(), texture_array_storage[uniform_index].get_height()))) { + texture_array_storage[uniform_index].write(_e250, metal::uint2(pix)); + } metal::float4 _e252 = v4_; - texture_array_storage[non_uniform_index].write(_e252, metal::uint2(pix)); + if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[non_uniform_index].get_width(), texture_array_storage[non_uniform_index].get_height()))) { + texture_array_storage[non_uniform_index].write(_e252, metal::uint2(pix)); + } metal::int2 _e253 = i2_; int _e254 = i1_; metal::float2 v2_ = static_cast(_e253 + metal::int2(_e254)); diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 71f13c3d9..f68a755cc 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 382 +; Bound: 429 OpCapability Shader OpCapability ImageQuery OpCapability ShaderNonUniform @@ -40,23 +40,23 @@ OpDecorate %114 NonUniform OpDecorate %116 NonUniform OpDecorate %141 NonUniform OpDecorate %143 NonUniform -OpDecorate %159 NonUniform -OpDecorate %178 NonUniform -OpDecorate %194 NonUniform +OpDecorate %181 NonUniform OpDecorate %210 NonUniform -OpDecorate %231 NonUniform -OpDecorate %233 NonUniform -OpDecorate %255 NonUniform -OpDecorate %257 NonUniform -OpDecorate %279 NonUniform -OpDecorate %281 NonUniform -OpDecorate %303 NonUniform -OpDecorate %305 NonUniform -OpDecorate %327 NonUniform -OpDecorate %329 NonUniform -OpDecorate %351 NonUniform -OpDecorate %353 NonUniform -OpDecorate %365 NonUniform +OpDecorate %226 NonUniform +OpDecorate %242 NonUniform +OpDecorate %263 NonUniform +OpDecorate %265 NonUniform +OpDecorate %287 NonUniform +OpDecorate %289 NonUniform +OpDecorate %311 NonUniform +OpDecorate %313 NonUniform +OpDecorate %335 NonUniform +OpDecorate %337 NonUniform +OpDecorate %359 NonUniform +OpDecorate %361 NonUniform +OpDecorate %383 NonUniform +OpDecorate %385 NonUniform +OpDecorate %407 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 5 @@ -122,10 +122,15 @@ OpDecorate %365 NonUniform %121 = OpTypePointer UniformConstant %17 %124 = OpTypePointer UniformConstant %21 %127 = OpTypeSampledImage %17 -%163 = OpTypePointer UniformConstant %13 -%166 = OpTypeVector %4 3 -%198 = OpTypePointer UniformConstant %15 -%357 = OpTypePointer UniformConstant %19 +%150 = OpTypeBool +%151 = OpConstantNull %25 +%157 = OpTypeVector %150 2 +%167 = OpConstantNull %25 +%182 = OpConstantNull %25 +%195 = OpTypePointer UniformConstant %13 +%198 = OpTypeVector %4 3 +%230 = OpTypePointer UniformConstant %15 +%389 = OpTypePointer UniformConstant %19 %63 = OpFunction %2 None %64 %56 = OpLabel %50 = OpVariable %51 Function @@ -221,267 +226,330 @@ OpStore %54 %146 %147 = OpLoad %25 %54 %148 = OpAccessChain %79 %27 %66 %149 = OpLoad %10 %148 -%150 = OpImageFetch %25 %149 %77 Lod %5 -%151 = OpFAdd %25 %147 %150 -OpStore %54 %151 -%152 = OpLoad %25 %54 -%153 = OpAccessChain %79 %27 %71 -%154 = OpLoad %10 %153 -%155 = OpImageFetch %25 %154 %77 Lod %5 -%156 = OpFAdd %25 %152 %155 -OpStore %54 %156 -%157 = OpLoad %25 %54 -%158 = OpAccessChain %79 %27 %72 -%159 = OpLoad %10 %158 -%160 = OpImageFetch %25 %159 %77 Lod %5 -%161 = OpFAdd %25 %157 %160 -OpStore %54 %161 -%162 = OpLoad %4 %48 -%164 = OpAccessChain %163 %33 %66 -%165 = OpLoad %13 %164 -%167 = OpImageQuerySizeLod %166 %165 %66 -%168 = OpCompositeExtract %4 %167 2 -%169 = OpIAdd %4 %162 %168 -OpStore %48 %169 -%170 = OpLoad %4 %48 -%171 = OpAccessChain %163 %33 %71 -%172 = OpLoad %13 %171 -%173 = OpImageQuerySizeLod %166 %172 %66 -%174 = OpCompositeExtract %4 %173 2 -%175 = OpIAdd %4 %170 %174 -OpStore %48 %175 -%176 = OpLoad %4 %48 -%177 = OpAccessChain %163 %33 %72 -%178 = OpLoad %13 %177 -%179 = OpImageQuerySizeLod %166 %178 %66 -%180 = OpCompositeExtract %4 %179 2 -%181 = OpIAdd %4 %176 %180 -OpStore %48 %181 -%182 = OpLoad %4 %48 -%183 = OpAccessChain %79 %31 %66 -%184 = OpLoad %10 %183 -%185 = OpImageQueryLevels %4 %184 -%186 = OpIAdd %4 %182 %185 -OpStore %48 %186 -%187 = OpLoad %4 %48 -%188 = OpAccessChain %79 %31 %71 -%189 = OpLoad %10 %188 -%190 = OpImageQueryLevels %4 %189 -%191 = OpIAdd %4 %187 %190 -OpStore %48 %191 -%192 = OpLoad %4 %48 -%193 = OpAccessChain %79 %31 %72 -%194 = OpLoad %10 %193 -%195 = OpImageQueryLevels %4 %194 -%196 = OpIAdd %4 %192 %195 -OpStore %48 %196 -%197 = OpLoad %4 %48 -%199 = OpAccessChain %198 %35 %66 -%200 = OpLoad %15 %199 -%201 = OpImageQuerySamples %4 %200 -%202 = OpIAdd %4 %197 %201 -OpStore %48 %202 -%203 = OpLoad %4 %48 -%204 = OpAccessChain %198 %35 %71 -%205 = OpLoad %15 %204 -%206 = OpImageQuerySamples %4 %205 -%207 = OpIAdd %4 %203 %206 +%152 = OpImageQueryLevels %4 %149 +%153 = OpULessThan %150 %5 %152 +OpSelectionMerge %154 None +OpBranchConditional %153 %155 %154 +%155 = OpLabel +%156 = OpImageQuerySizeLod %26 %149 %5 +%158 = OpULessThan %157 %77 %156 +%159 = OpAll %150 %158 +OpBranchConditional %159 %160 %154 +%160 = OpLabel +%161 = OpImageFetch %25 %149 %77 Lod %5 +OpBranch %154 +%154 = OpLabel +%162 = OpPhi %25 %151 %68 %151 %155 %161 %160 +%163 = OpFAdd %25 %147 %162 +OpStore %54 %163 +%164 = OpLoad %25 %54 +%165 = OpAccessChain %79 %27 %71 +%166 = OpLoad %10 %165 +%168 = OpImageQueryLevels %4 %166 +%169 = OpULessThan %150 %5 %168 +OpSelectionMerge %170 None +OpBranchConditional %169 %171 %170 +%171 = OpLabel +%172 = OpImageQuerySizeLod %26 %166 %5 +%173 = OpULessThan %157 %77 %172 +%174 = OpAll %150 %173 +OpBranchConditional %174 %175 %170 +%175 = OpLabel +%176 = OpImageFetch %25 %166 %77 Lod %5 +OpBranch %170 +%170 = OpLabel +%177 = OpPhi %25 %167 %154 %167 %171 %176 %175 +%178 = OpFAdd %25 %164 %177 +OpStore %54 %178 +%179 = OpLoad %25 %54 +%180 = OpAccessChain %79 %27 %72 +%181 = OpLoad %10 %180 +%183 = OpImageQueryLevels %4 %181 +%184 = OpULessThan %150 %5 %183 +OpSelectionMerge %185 None +OpBranchConditional %184 %186 %185 +%186 = OpLabel +%187 = OpImageQuerySizeLod %26 %181 %5 +%188 = OpULessThan %157 %77 %187 +%189 = OpAll %150 %188 +OpBranchConditional %189 %190 %185 +%190 = OpLabel +%191 = OpImageFetch %25 %181 %77 Lod %5 +OpBranch %185 +%185 = OpLabel +%192 = OpPhi %25 %182 %170 %182 %186 %191 %190 +%193 = OpFAdd %25 %179 %192 +OpStore %54 %193 +%194 = OpLoad %4 %48 +%196 = OpAccessChain %195 %33 %66 +%197 = OpLoad %13 %196 +%199 = OpImageQuerySizeLod %198 %197 %66 +%200 = OpCompositeExtract %4 %199 2 +%201 = OpIAdd %4 %194 %200 +OpStore %48 %201 +%202 = OpLoad %4 %48 +%203 = OpAccessChain %195 %33 %71 +%204 = OpLoad %13 %203 +%205 = OpImageQuerySizeLod %198 %204 %66 +%206 = OpCompositeExtract %4 %205 2 +%207 = OpIAdd %4 %202 %206 OpStore %48 %207 %208 = OpLoad %4 %48 -%209 = OpAccessChain %198 %35 %72 -%210 = OpLoad %15 %209 -%211 = OpImageQuerySamples %4 %210 -%212 = OpIAdd %4 %208 %211 -OpStore %48 %212 -%213 = OpLoad %25 %54 -%214 = OpAccessChain %79 %31 %66 -%215 = OpLoad %10 %214 -%216 = OpAccessChain %97 %41 %66 -%217 = OpLoad %21 %216 -%218 = OpSampledImage %100 %215 %217 -%219 = OpImageSampleImplicitLod %25 %218 %76 -%220 = OpFAdd %25 %213 %219 -OpStore %54 %220 -%221 = OpLoad %25 %54 -%222 = OpAccessChain %79 %31 %71 -%223 = OpLoad %10 %222 -%224 = OpAccessChain %97 %41 %71 -%225 = OpLoad %21 %224 -%226 = OpSampledImage %100 %223 %225 -%227 = OpImageSampleImplicitLod %25 %226 %76 -%228 = OpFAdd %25 %221 %227 -OpStore %54 %228 -%229 = OpLoad %25 %54 -%230 = OpAccessChain %79 %31 %72 -%231 = OpLoad %10 %230 -%232 = OpAccessChain %97 %41 %72 -%233 = OpLoad %21 %232 -%234 = OpSampledImage %100 %231 %233 -%235 = OpImageSampleImplicitLod %25 %234 %76 -%236 = OpFAdd %25 %229 %235 -OpStore %54 %236 -%237 = OpLoad %25 %54 -%238 = OpAccessChain %79 %31 %66 -%239 = OpLoad %10 %238 -%240 = OpAccessChain %97 %41 %66 -%241 = OpLoad %21 %240 -%242 = OpSampledImage %100 %239 %241 -%243 = OpImageSampleImplicitLod %25 %242 %76 Bias %6 -%244 = OpFAdd %25 %237 %243 -OpStore %54 %244 +%209 = OpAccessChain %195 %33 %72 +%210 = OpLoad %13 %209 +%211 = OpImageQuerySizeLod %198 %210 %66 +%212 = OpCompositeExtract %4 %211 2 +%213 = OpIAdd %4 %208 %212 +OpStore %48 %213 +%214 = OpLoad %4 %48 +%215 = OpAccessChain %79 %31 %66 +%216 = OpLoad %10 %215 +%217 = OpImageQueryLevels %4 %216 +%218 = OpIAdd %4 %214 %217 +OpStore %48 %218 +%219 = OpLoad %4 %48 +%220 = OpAccessChain %79 %31 %71 +%221 = OpLoad %10 %220 +%222 = OpImageQueryLevels %4 %221 +%223 = OpIAdd %4 %219 %222 +OpStore %48 %223 +%224 = OpLoad %4 %48 +%225 = OpAccessChain %79 %31 %72 +%226 = OpLoad %10 %225 +%227 = OpImageQueryLevels %4 %226 +%228 = OpIAdd %4 %224 %227 +OpStore %48 %228 +%229 = OpLoad %4 %48 +%231 = OpAccessChain %230 %35 %66 +%232 = OpLoad %15 %231 +%233 = OpImageQuerySamples %4 %232 +%234 = OpIAdd %4 %229 %233 +OpStore %48 %234 +%235 = OpLoad %4 %48 +%236 = OpAccessChain %230 %35 %71 +%237 = OpLoad %15 %236 +%238 = OpImageQuerySamples %4 %237 +%239 = OpIAdd %4 %235 %238 +OpStore %48 %239 +%240 = OpLoad %4 %48 +%241 = OpAccessChain %230 %35 %72 +%242 = OpLoad %15 %241 +%243 = OpImageQuerySamples %4 %242 +%244 = OpIAdd %4 %240 %243 +OpStore %48 %244 %245 = OpLoad %25 %54 -%246 = OpAccessChain %79 %31 %71 +%246 = OpAccessChain %79 %31 %66 %247 = OpLoad %10 %246 -%248 = OpAccessChain %97 %41 %71 +%248 = OpAccessChain %97 %41 %66 %249 = OpLoad %21 %248 %250 = OpSampledImage %100 %247 %249 -%251 = OpImageSampleImplicitLod %25 %250 %76 Bias %6 +%251 = OpImageSampleImplicitLod %25 %250 %76 %252 = OpFAdd %25 %245 %251 OpStore %54 %252 %253 = OpLoad %25 %54 -%254 = OpAccessChain %79 %31 %72 +%254 = OpAccessChain %79 %31 %71 %255 = OpLoad %10 %254 -%256 = OpAccessChain %97 %41 %72 +%256 = OpAccessChain %97 %41 %71 %257 = OpLoad %21 %256 %258 = OpSampledImage %100 %255 %257 -%259 = OpImageSampleImplicitLod %25 %258 %76 Bias %6 +%259 = OpImageSampleImplicitLod %25 %258 %76 %260 = OpFAdd %25 %253 %259 OpStore %54 %260 -%261 = OpLoad %7 %52 -%262 = OpAccessChain %121 %37 %66 -%263 = OpLoad %17 %262 -%264 = OpAccessChain %124 %43 %66 +%261 = OpLoad %25 %54 +%262 = OpAccessChain %79 %31 %72 +%263 = OpLoad %10 %262 +%264 = OpAccessChain %97 %41 %72 %265 = OpLoad %21 %264 -%266 = OpSampledImage %127 %263 %265 -%267 = OpImageSampleDrefImplicitLod %7 %266 %76 %6 -%268 = OpFAdd %7 %261 %267 -OpStore %52 %268 -%269 = OpLoad %7 %52 -%270 = OpAccessChain %121 %37 %71 -%271 = OpLoad %17 %270 -%272 = OpAccessChain %124 %43 %71 +%266 = OpSampledImage %100 %263 %265 +%267 = OpImageSampleImplicitLod %25 %266 %76 +%268 = OpFAdd %25 %261 %267 +OpStore %54 %268 +%269 = OpLoad %25 %54 +%270 = OpAccessChain %79 %31 %66 +%271 = OpLoad %10 %270 +%272 = OpAccessChain %97 %41 %66 %273 = OpLoad %21 %272 -%274 = OpSampledImage %127 %271 %273 -%275 = OpImageSampleDrefImplicitLod %7 %274 %76 %6 -%276 = OpFAdd %7 %269 %275 -OpStore %52 %276 -%277 = OpLoad %7 %52 -%278 = OpAccessChain %121 %37 %72 -%279 = OpLoad %17 %278 -%280 = OpAccessChain %124 %43 %72 +%274 = OpSampledImage %100 %271 %273 +%275 = OpImageSampleImplicitLod %25 %274 %76 Bias %6 +%276 = OpFAdd %25 %269 %275 +OpStore %54 %276 +%277 = OpLoad %25 %54 +%278 = OpAccessChain %79 %31 %71 +%279 = OpLoad %10 %278 +%280 = OpAccessChain %97 %41 %71 %281 = OpLoad %21 %280 -%282 = OpSampledImage %127 %279 %281 -%283 = OpImageSampleDrefImplicitLod %7 %282 %76 %6 -%284 = OpFAdd %7 %277 %283 -OpStore %52 %284 -%285 = OpLoad %7 %52 -%286 = OpAccessChain %121 %37 %66 -%287 = OpLoad %17 %286 -%288 = OpAccessChain %124 %43 %66 +%282 = OpSampledImage %100 %279 %281 +%283 = OpImageSampleImplicitLod %25 %282 %76 Bias %6 +%284 = OpFAdd %25 %277 %283 +OpStore %54 %284 +%285 = OpLoad %25 %54 +%286 = OpAccessChain %79 %31 %72 +%287 = OpLoad %10 %286 +%288 = OpAccessChain %97 %41 %72 %289 = OpLoad %21 %288 -%290 = OpSampledImage %127 %287 %289 -%291 = OpImageSampleDrefExplicitLod %7 %290 %76 %6 Lod %6 -%292 = OpFAdd %7 %285 %291 -OpStore %52 %292 +%290 = OpSampledImage %100 %287 %289 +%291 = OpImageSampleImplicitLod %25 %290 %76 Bias %6 +%292 = OpFAdd %25 %285 %291 +OpStore %54 %292 %293 = OpLoad %7 %52 -%294 = OpAccessChain %121 %37 %71 +%294 = OpAccessChain %121 %37 %66 %295 = OpLoad %17 %294 -%296 = OpAccessChain %124 %43 %71 +%296 = OpAccessChain %124 %43 %66 %297 = OpLoad %21 %296 %298 = OpSampledImage %127 %295 %297 -%299 = OpImageSampleDrefExplicitLod %7 %298 %76 %6 Lod %6 +%299 = OpImageSampleDrefImplicitLod %7 %298 %76 %6 %300 = OpFAdd %7 %293 %299 OpStore %52 %300 %301 = OpLoad %7 %52 -%302 = OpAccessChain %121 %37 %72 +%302 = OpAccessChain %121 %37 %71 %303 = OpLoad %17 %302 -%304 = OpAccessChain %124 %43 %72 +%304 = OpAccessChain %124 %43 %71 %305 = OpLoad %21 %304 %306 = OpSampledImage %127 %303 %305 -%307 = OpImageSampleDrefExplicitLod %7 %306 %76 %6 Lod %6 +%307 = OpImageSampleDrefImplicitLod %7 %306 %76 %6 %308 = OpFAdd %7 %301 %307 OpStore %52 %308 -%309 = OpLoad %25 %54 -%310 = OpAccessChain %79 %31 %66 -%311 = OpLoad %10 %310 -%312 = OpAccessChain %97 %41 %66 +%309 = OpLoad %7 %52 +%310 = OpAccessChain %121 %37 %72 +%311 = OpLoad %17 %310 +%312 = OpAccessChain %124 %43 %72 %313 = OpLoad %21 %312 -%314 = OpSampledImage %100 %311 %313 -%315 = OpImageSampleExplicitLod %25 %314 %76 Grad %76 %76 -%316 = OpFAdd %25 %309 %315 -OpStore %54 %316 -%317 = OpLoad %25 %54 -%318 = OpAccessChain %79 %31 %71 -%319 = OpLoad %10 %318 -%320 = OpAccessChain %97 %41 %71 +%314 = OpSampledImage %127 %311 %313 +%315 = OpImageSampleDrefImplicitLod %7 %314 %76 %6 +%316 = OpFAdd %7 %309 %315 +OpStore %52 %316 +%317 = OpLoad %7 %52 +%318 = OpAccessChain %121 %37 %66 +%319 = OpLoad %17 %318 +%320 = OpAccessChain %124 %43 %66 %321 = OpLoad %21 %320 -%322 = OpSampledImage %100 %319 %321 -%323 = OpImageSampleExplicitLod %25 %322 %76 Grad %76 %76 -%324 = OpFAdd %25 %317 %323 -OpStore %54 %324 -%325 = OpLoad %25 %54 -%326 = OpAccessChain %79 %31 %72 -%327 = OpLoad %10 %326 -%328 = OpAccessChain %97 %41 %72 +%322 = OpSampledImage %127 %319 %321 +%323 = OpImageSampleDrefExplicitLod %7 %322 %76 %6 Lod %6 +%324 = OpFAdd %7 %317 %323 +OpStore %52 %324 +%325 = OpLoad %7 %52 +%326 = OpAccessChain %121 %37 %71 +%327 = OpLoad %17 %326 +%328 = OpAccessChain %124 %43 %71 %329 = OpLoad %21 %328 -%330 = OpSampledImage %100 %327 %329 -%331 = OpImageSampleExplicitLod %25 %330 %76 Grad %76 %76 -%332 = OpFAdd %25 %325 %331 -OpStore %54 %332 -%333 = OpLoad %25 %54 -%334 = OpAccessChain %79 %31 %66 -%335 = OpLoad %10 %334 -%336 = OpAccessChain %97 %41 %66 +%330 = OpSampledImage %127 %327 %329 +%331 = OpImageSampleDrefExplicitLod %7 %330 %76 %6 Lod %6 +%332 = OpFAdd %7 %325 %331 +OpStore %52 %332 +%333 = OpLoad %7 %52 +%334 = OpAccessChain %121 %37 %72 +%335 = OpLoad %17 %334 +%336 = OpAccessChain %124 %43 %72 %337 = OpLoad %21 %336 -%338 = OpSampledImage %100 %335 %337 -%339 = OpImageSampleExplicitLod %25 %338 %76 Lod %6 -%340 = OpFAdd %25 %333 %339 -OpStore %54 %340 +%338 = OpSampledImage %127 %335 %337 +%339 = OpImageSampleDrefExplicitLod %7 %338 %76 %6 Lod %6 +%340 = OpFAdd %7 %333 %339 +OpStore %52 %340 %341 = OpLoad %25 %54 -%342 = OpAccessChain %79 %31 %71 +%342 = OpAccessChain %79 %31 %66 %343 = OpLoad %10 %342 -%344 = OpAccessChain %97 %41 %71 +%344 = OpAccessChain %97 %41 %66 %345 = OpLoad %21 %344 %346 = OpSampledImage %100 %343 %345 -%347 = OpImageSampleExplicitLod %25 %346 %76 Lod %6 +%347 = OpImageSampleExplicitLod %25 %346 %76 Grad %76 %76 %348 = OpFAdd %25 %341 %347 OpStore %54 %348 %349 = OpLoad %25 %54 -%350 = OpAccessChain %79 %31 %72 +%350 = OpAccessChain %79 %31 %71 %351 = OpLoad %10 %350 -%352 = OpAccessChain %97 %41 %72 +%352 = OpAccessChain %97 %41 %71 %353 = OpLoad %21 %352 %354 = OpSampledImage %100 %351 %353 -%355 = OpImageSampleExplicitLod %25 %354 %76 Lod %6 +%355 = OpImageSampleExplicitLod %25 %354 %76 Grad %76 %76 %356 = OpFAdd %25 %349 %355 OpStore %54 %356 -%358 = OpAccessChain %357 %39 %66 -%359 = OpLoad %19 %358 -%360 = OpLoad %25 %54 -OpImageWrite %359 %77 %360 -%361 = OpAccessChain %357 %39 %71 -%362 = OpLoad %19 %361 -%363 = OpLoad %25 %54 -OpImageWrite %362 %77 %363 -%364 = OpAccessChain %357 %39 %72 -%365 = OpLoad %19 %364 -%366 = OpLoad %25 %54 -OpImageWrite %365 %77 %366 -%367 = OpLoad %26 %50 -%368 = OpLoad %4 %48 -%369 = OpCompositeConstruct %26 %368 %368 -%370 = OpIAdd %26 %367 %369 -%371 = OpConvertSToF %75 %370 -%372 = OpLoad %25 %54 -%373 = OpCompositeExtract %7 %371 0 -%374 = OpCompositeExtract %7 %371 1 -%375 = OpCompositeExtract %7 %371 0 -%376 = OpCompositeExtract %7 %371 1 -%377 = OpCompositeConstruct %25 %373 %374 %375 %376 -%378 = OpFAdd %25 %372 %377 -%379 = OpLoad %7 %52 -%380 = OpCompositeConstruct %25 %379 %379 %379 %379 -%381 = OpFAdd %25 %378 %380 -OpStore %61 %381 +%357 = OpLoad %25 %54 +%358 = OpAccessChain %79 %31 %72 +%359 = OpLoad %10 %358 +%360 = OpAccessChain %97 %41 %72 +%361 = OpLoad %21 %360 +%362 = OpSampledImage %100 %359 %361 +%363 = OpImageSampleExplicitLod %25 %362 %76 Grad %76 %76 +%364 = OpFAdd %25 %357 %363 +OpStore %54 %364 +%365 = OpLoad %25 %54 +%366 = OpAccessChain %79 %31 %66 +%367 = OpLoad %10 %366 +%368 = OpAccessChain %97 %41 %66 +%369 = OpLoad %21 %368 +%370 = OpSampledImage %100 %367 %369 +%371 = OpImageSampleExplicitLod %25 %370 %76 Lod %6 +%372 = OpFAdd %25 %365 %371 +OpStore %54 %372 +%373 = OpLoad %25 %54 +%374 = OpAccessChain %79 %31 %71 +%375 = OpLoad %10 %374 +%376 = OpAccessChain %97 %41 %71 +%377 = OpLoad %21 %376 +%378 = OpSampledImage %100 %375 %377 +%379 = OpImageSampleExplicitLod %25 %378 %76 Lod %6 +%380 = OpFAdd %25 %373 %379 +OpStore %54 %380 +%381 = OpLoad %25 %54 +%382 = OpAccessChain %79 %31 %72 +%383 = OpLoad %10 %382 +%384 = OpAccessChain %97 %41 %72 +%385 = OpLoad %21 %384 +%386 = OpSampledImage %100 %383 %385 +%387 = OpImageSampleExplicitLod %25 %386 %76 Lod %6 +%388 = OpFAdd %25 %381 %387 +OpStore %54 %388 +%390 = OpAccessChain %389 %39 %66 +%391 = OpLoad %19 %390 +%392 = OpLoad %25 %54 +%393 = OpImageQuerySize %26 %391 +%394 = OpULessThan %157 %77 %393 +%395 = OpAll %150 %394 +OpSelectionMerge %396 None +OpBranchConditional %395 %397 %396 +%397 = OpLabel +OpImageWrite %391 %77 %392 +OpBranch %396 +%396 = OpLabel +%398 = OpAccessChain %389 %39 %71 +%399 = OpLoad %19 %398 +%400 = OpLoad %25 %54 +%401 = OpImageQuerySize %26 %399 +%402 = OpULessThan %157 %77 %401 +%403 = OpAll %150 %402 +OpSelectionMerge %404 None +OpBranchConditional %403 %405 %404 +%405 = OpLabel +OpImageWrite %399 %77 %400 +OpBranch %404 +%404 = OpLabel +%406 = OpAccessChain %389 %39 %72 +%407 = OpLoad %19 %406 +%408 = OpLoad %25 %54 +%409 = OpImageQuerySize %26 %407 +%410 = OpULessThan %157 %77 %409 +%411 = OpAll %150 %410 +OpSelectionMerge %412 None +OpBranchConditional %411 %413 %412 +%413 = OpLabel +OpImageWrite %407 %77 %408 +OpBranch %412 +%412 = OpLabel +%414 = OpLoad %26 %50 +%415 = OpLoad %4 %48 +%416 = OpCompositeConstruct %26 %415 %415 +%417 = OpIAdd %26 %414 %416 +%418 = OpConvertSToF %75 %417 +%419 = OpLoad %25 %54 +%420 = OpCompositeExtract %7 %418 0 +%421 = OpCompositeExtract %7 %418 1 +%422 = OpCompositeExtract %7 %418 0 +%423 = OpCompositeExtract %7 %418 1 +%424 = OpCompositeConstruct %25 %420 %421 %422 %423 +%425 = OpFAdd %25 %419 %424 +%426 = OpLoad %7 %52 +%427 = OpCompositeConstruct %25 %426 %426 %426 %426 +%428 = OpFAdd %25 %425 %427 +OpStore %61 %428 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 727149d98..f6a3749c3 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -252,8 +252,8 @@ fn write_output_msl( let mut options = options.clone(); options.bounds_check_policies = bounds_check_policies; - let (string, tr_info) = - msl::write_string(module, info, &options, pipeline_options).expect("Metal write failed"); + let (string, tr_info) = msl::write_string(module, info, &options, pipeline_options) + .unwrap_or_else(|err| panic!("Metal write failed: {}", err)); for (ep, result) in module.entry_points.iter().zip(tr_info.entry_point_names) { if let Err(error) = result { From 9b7fe8803db1c8bb21ee47bd6691f0cd72ef28cc Mon Sep 17 00:00:00 2001 From: Noel Tautges Date: Mon, 25 Apr 2022 23:31:10 -0500 Subject: [PATCH 1705/2212] Clarify accepted types for `Expression::AccessIndex` (#1862) * Clarify accepted types for `AccessIndex` and remove `Constant` fragment * Remove spaces Will I ever learn to run `cargo fmt` before pushing? The answer is probably yes, after this repeated embarrassment --- src/lib.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index fa632b29b..e4d1dca7e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1108,14 +1108,15 @@ pub enum Expression { base: Handle, index: Handle, }, - /// Array access with a known index. + /// Access the same types as [`Access`], plus [`Struct`] with a known index. + /// + /// [`Access`]: Expression::Access + /// [`Struct`]: TypeInner::Struct AccessIndex { base: Handle, index: u32, }, /// Constant value. - /// - /// Every `Constant` expression Constant(Handle), /// Splat scalar into a vector. Splat { From 01212b24b982eb3e93f4dc09dc6576034f7b2765 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 23 Apr 2022 07:20:58 -0700 Subject: [PATCH 1706/2212] Document `TypeInner::BindingArray`. --- src/lib.rs | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index e4d1dca7e..80e7e6f78 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -698,7 +698,48 @@ pub enum TypeInner { }, /// Can be used to sample values from images. Sampler { comparison: bool }, - /// Array of bindings + + /// Array of bindings. + /// + /// A `BindingArray` represents an array where each element draws its value + /// from a separate bound resource. The array's element type `base` may be + /// [`Image`], [`Sampler`], or any type that would be permitted for a global + /// in the [`Uniform`] or [`Storage`] address spaces. Only global variables + /// may be binding arrays; on the host side, their values are provided by + /// [`TextureViewArray`], [`SamplerArray`], or [`BufferArray`] + /// bindings. + /// + /// Since each element comes from a distinct resource, a binding array of + /// images could have images of varying sizes (but not varying dimensions; + /// they must all have the same `Image` type). Or, a binding array of + /// buffers could have elements that are dynamically sized arrays, each with + /// a different length. + /// + /// Binding arrays are not [`DATA`]. This means that all binding array + /// globals must be placed in the [`Handle`] address space. Referring to + /// such a global produces a `BindingArray` value directly; there are never + /// pointers to binding arrays. The only operation permitted on + /// `BindingArray` values is indexing, which yields the element by value, + /// not a pointer to the element. (This means that buffer array contents + /// cannot be stored to; [naga#1864] covers lifting this restriction.) + /// + /// Unlike textures and samplers, binding arrays are not [`ARGUMENT`], so + /// they cannot be passed as arguments to functions. + /// + /// Naga's WGSL front end supports binding arrays with the type syntax + /// `binding_array`. + /// + /// [`Image`]: TypeInner::Image + /// [`Sampler`]: TypeInner::Sampler + /// [`Uniform`]: AddressSpace::Uniform + /// [`Storage`]: AddressSpace::Storage + /// [`TextureViewArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.TextureViewArray + /// [`SamplerArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.SamplerArray + /// [`BufferArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.BufferArray + /// [`DATA`]: crate::valid::TypeFlags::DATA + /// [`Handle`]: AddressSpace::Handle + /// [`ARGUMENT`]: crate::valid::TypeFlags::ARGUMENT + /// [naga#1864]: https://github.com/gfx-rs/naga/issues/1864 BindingArray { base: Handle, size: ArraySize }, } From 062b66ca3157456647d3468d1468039e30aaf421 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 26 Apr 2022 18:40:37 +0200 Subject: [PATCH 1707/2212] implement phony assignment --- src/front/wgsl/lexer.rs | 3 + src/front/wgsl/mod.rs | 21 + tests/in/access.wgsl | 16 +- tests/in/globals.wgsl | 12 +- tests/in/operators.wgsl | 308 ++++---- tests/out/glsl/access.foo_vert.Vertex.glsl | 60 +- tests/out/glsl/operators.main.Compute.glsl | 295 ++++--- tests/out/hlsl/access.hlsl | 60 +- tests/out/hlsl/operators.hlsl | 298 ++++---- tests/out/msl/access.msl | 80 +- tests/out/msl/operators.msl | 295 ++++--- tests/out/spv/access.spvasm | 453 ++++++----- tests/out/spv/operators.spvasm | 849 ++++++++++----------- tests/out/wgsl/access.wgsl | 60 +- tests/out/wgsl/operators.wgsl | 295 ++++--- tests/wgsl-errors.rs | 32 +- 16 files changed, 1502 insertions(+), 1635 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 91986d552..212e41f2b 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -544,6 +544,9 @@ impl<'a> Lexer<'a> { pub(super) fn next_ident_with_span(&mut self) -> Result<(&'a str, Span), Error<'a>> { match self.next() { + (Token::Word(word), span) if word == "_" => { + Err(Error::InvalidIdentifierUnderscore(span)) + } (Token::Word(word), span) if word.starts_with("__") => { Err(Error::ReservedIdentifierPrefix(span)) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 610c8c5f8..5e5502f4b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -147,6 +147,7 @@ pub enum Error<'a> { InvalidForInitializer(Span), InvalidGatherComponent(Span, i32), InvalidConstructorComponentType(Span, i32), + InvalidIdentifierUnderscore(Span), ReservedIdentifierPrefix(Span), UnknownAddressSpace(Span), UnknownAttribute(Span), @@ -362,6 +363,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "invalid component type".into())], notes: vec![], }, + Error::InvalidIdentifierUnderscore(ref bad_span) => ParseError { + message: "Identifier can't be '_'".to_string(), + labels: vec![(bad_span.clone(), "invalid identifier".into())], + notes: vec!["Use phony assignment instead ('_ =' notice the absence of 'let' or 'var')".to_string()], + }, Error::ReservedIdentifierPrefix(ref bad_span) => ParseError { message: format!("Identifier starts with a reserved prefix: '{}'", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "invalid identifier".into())], @@ -3489,6 +3495,21 @@ impl Parser { (Token::Word(word), _) => { let mut emitter = super::Emitter::default(); let statement = match word { + "_" => { + let _ = lexer.next(); + emitter.start(context.expressions); + lexer.expect(Token::Operation('='))?; + let expr_id = self.parse_general_expression( + lexer, + context.as_expression(block, &mut emitter), + )?; + lexer.expect(Token::Separator(';'))?; + block.extend(emitter.finish(context.expressions)); + // TODO: the situation here could be improved but + // for now this is necessary to get the expressions emitted + context.named_expressions.insert(expr_id, "_".to_string()); + None + } "let" => { let _ = lexer.next(); emitter.start(context.expressions); diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 4ad05f201..c80d0349d 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -28,13 +28,13 @@ fn test_matrix_within_struct_accesses() { idx--; // loads - var _ = baz.m; - var _ = baz.m[0]; - var _ = baz.m[idx]; - var _ = baz.m[0][1]; - var _ = baz.m[0][idx]; - var _ = baz.m[idx][1]; - var _ = baz.m[idx][idx]; + _ = baz.m; + _ = baz.m[0]; + _ = baz.m[idx]; + _ = baz.m[0][1]; + _ = baz.m[0][idx]; + _ = baz.m[idx][1]; + _ = baz.m[idx][idx]; var t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); @@ -83,7 +83,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { c[vi + 1u] = 42; let value = c[vi]; - var _ = test_arr_as_arg(array, 5>()); + _ = test_arr_as_arg(array, 5>()); return vec4(_matrix * vec4(vec4(value)), 2.0); } diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 6e571e271..89ab106f9 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -39,17 +39,17 @@ fn test_msl_packed_vec3() { let data = alignment; // loads - let _ = data.v3; - let _ = data.v3.zx; + _ = data.v3; + _ = data.v3.zx; test_msl_packed_vec3_as_arg(data.v3); // matrix vector multiplication - let _ = data.v3 * mat3x3(); - let _ = mat3x3() * data.v3; + _ = data.v3 * mat3x3(); + _ = mat3x3() * data.v3; // scalar vector multiplication - let _ = data.v3 * 2.0; - let _ = 2.0 * data.v3; + _ = data.v3 * 2.0; + _ = 2.0 * data.v3; } @compute @workgroup_size(1) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index f62329499..cfc589659 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -54,211 +54,211 @@ fn constructors() -> f32 { ); // zero value constructors - var _ = bool(); - var _ = i32(); - var _ = u32(); - var _ = f32(); - var _ = vec2(); - var _ = mat2x2(); - var _ = array(); - var _ = Foo(); + _ = bool(); + _ = i32(); + _ = u32(); + _ = f32(); + _ = vec2(); + _ = mat2x2(); + _ = array(); + _ = Foo(); // constructors that infer their type from their parameters - var _ = vec2(0u); - var _ = mat2x2(vec2(0.), vec2(0.)); - var _ = array(0, 1, 2, 3); + _ = vec2(0u); + _ = mat2x2(vec2(0.), vec2(0.)); + _ = array(0, 1, 2, 3); return foo.a.x; } fn logical() { // unary - let _ = !true; - let _ = !vec2(true); + _ = !true; + _ = !vec2(true); // binary - let _ = true || false; - let _ = true && false; - let _ = true | false; - let _ = vec3(true) | vec3(false); - let _ = true & false; - let _ = vec4(true) & vec4(false); + _ = true || false; + _ = true && false; + _ = true | false; + _ = vec3(true) | vec3(false); + _ = true & false; + _ = vec4(true) & vec4(false); } fn arithmetic() { // unary // TODO: uncomment when we get the changes from https://github.com/gfx-rs/rspirv/pull/231 - // let _ = -1; - let _ = -1.0; - let _ = -vec2(1); - let _ = -vec2(1.0); + // _ = -1; + _ = -1.0; + _ = -vec2(1); + _ = -vec2(1.0); // binary // Addition - let _ = 2 + 1; - let _ = 2u + 1u; - let _ = 2.0 + 1.0; - let _ = vec2(2) + vec2(1); - let _ = vec3(2u) + vec3(1u); - let _ = vec4(2.0) + vec4(1.0); + _ = 2 + 1; + _ = 2u + 1u; + _ = 2.0 + 1.0; + _ = vec2(2) + vec2(1); + _ = vec3(2u) + vec3(1u); + _ = vec4(2.0) + vec4(1.0); // Subtraction - let _ = 2 - 1; - let _ = 2u - 1u; - let _ = 2.0 - 1.0; - let _ = vec2(2) - vec2(1); - let _ = vec3(2u) - vec3(1u); - let _ = vec4(2.0) - vec4(1.0); + _ = 2 - 1; + _ = 2u - 1u; + _ = 2.0 - 1.0; + _ = vec2(2) - vec2(1); + _ = vec3(2u) - vec3(1u); + _ = vec4(2.0) - vec4(1.0); // Multiplication - let _ = 2 * 1; - let _ = 2u * 1u; - let _ = 2.0 * 1.0; - let _ = vec2(2) * vec2(1); - let _ = vec3(2u) * vec3(1u); - let _ = vec4(2.0) * vec4(1.0); + _ = 2 * 1; + _ = 2u * 1u; + _ = 2.0 * 1.0; + _ = vec2(2) * vec2(1); + _ = vec3(2u) * vec3(1u); + _ = vec4(2.0) * vec4(1.0); // Division - let _ = 2 / 1; - let _ = 2u / 1u; - let _ = 2.0 / 1.0; - let _ = vec2(2) / vec2(1); - let _ = vec3(2u) / vec3(1u); - let _ = vec4(2.0) / vec4(1.0); + _ = 2 / 1; + _ = 2u / 1u; + _ = 2.0 / 1.0; + _ = vec2(2) / vec2(1); + _ = vec3(2u) / vec3(1u); + _ = vec4(2.0) / vec4(1.0); // Remainder - let _ = 2 % 1; - let _ = 2u % 1u; - let _ = 2.0 % 1.0; - let _ = vec2(2) % vec2(1); - let _ = vec3(2u) % vec3(1u); - let _ = vec4(2.0) % vec4(1.0); + _ = 2 % 1; + _ = 2u % 1u; + _ = 2.0 % 1.0; + _ = vec2(2) % vec2(1); + _ = vec3(2u) % vec3(1u); + _ = vec4(2.0) % vec4(1.0); // Binary arithmetic expressions with mixed scalar and vector operands - let _ = vec2(2) + 1; - let _ = 2 + vec2(1); - let _ = vec2(2u) + 1u; - let _ = 2u + vec2(1u); - let _ = vec2(2.0) + 1.0; - let _ = 2.0 + vec2(1.0); + _ = vec2(2) + 1; + _ = 2 + vec2(1); + _ = vec2(2u) + 1u; + _ = 2u + vec2(1u); + _ = vec2(2.0) + 1.0; + _ = 2.0 + vec2(1.0); - let _ = vec2(2) - 1; - let _ = 2 - vec2(1); - let _ = vec2(2u) - 1u; - let _ = 2u - vec2(1u); - let _ = vec2(2.0) - 1.0; - let _ = 2.0 - vec2(1.0); + _ = vec2(2) - 1; + _ = 2 - vec2(1); + _ = vec2(2u) - 1u; + _ = 2u - vec2(1u); + _ = vec2(2.0) - 1.0; + _ = 2.0 - vec2(1.0); - let _ = vec2(2) * 1; - let _ = 2 * vec2(1); - let _ = vec2(2u) * 1u; - let _ = 2u * vec2(1u); - let _ = vec2(2.0) * 1.0; - let _ = 2.0 * vec2(1.0); + _ = vec2(2) * 1; + _ = 2 * vec2(1); + _ = vec2(2u) * 1u; + _ = 2u * vec2(1u); + _ = vec2(2.0) * 1.0; + _ = 2.0 * vec2(1.0); - let _ = vec2(2) / 1; - let _ = 2 / vec2(1); - let _ = vec2(2u) / 1u; - let _ = 2u / vec2(1u); - let _ = vec2(2.0) / 1.0; - let _ = 2.0 / vec2(1.0); + _ = vec2(2) / 1; + _ = 2 / vec2(1); + _ = vec2(2u) / 1u; + _ = 2u / vec2(1u); + _ = vec2(2.0) / 1.0; + _ = 2.0 / vec2(1.0); - let _ = vec2(2) % 1; - let _ = 2 % vec2(1); - let _ = vec2(2u) % 1u; - let _ = 2u % vec2(1u); - let _ = vec2(2.0) % 1.0; - let _ = 2.0 % vec2(1.0); + _ = vec2(2) % 1; + _ = 2 % vec2(1); + _ = vec2(2u) % 1u; + _ = 2u % vec2(1u); + _ = vec2(2.0) % 1.0; + _ = 2.0 % vec2(1.0); // Matrix arithmetic - let _ = mat3x3() + mat3x3(); - let _ = mat3x3() - mat3x3(); + _ = mat3x3() + mat3x3(); + _ = mat3x3() - mat3x3(); - let _ = mat3x3() * 1.0; - let _ = 2.0 * mat3x3(); + _ = mat3x3() * 1.0; + _ = 2.0 * mat3x3(); - let _ = mat4x3() * vec4(1.0); - let _ = vec3(2.0) * mat4x3(); + _ = mat4x3() * vec4(1.0); + _ = vec3(2.0) * mat4x3(); - let _ = mat4x3() * mat3x4(); + _ = mat4x3() * mat3x4(); } fn bit() { // unary - let _ = ~1; - let _ = ~1u; - let _ = ~vec2(1); - let _ = ~vec3(1u); + _ = ~1; + _ = ~1u; + _ = ~vec2(1); + _ = ~vec3(1u); // binary - let _ = 2 | 1; - let _ = 2u | 1u; - let _ = vec2(2) | vec2(1); - let _ = vec3(2u) | vec3(1u); + _ = 2 | 1; + _ = 2u | 1u; + _ = vec2(2) | vec2(1); + _ = vec3(2u) | vec3(1u); - let _ = 2 & 1; - let _ = 2u & 1u; - let _ = vec2(2) & vec2(1); - let _ = vec3(2u) & vec3(1u); + _ = 2 & 1; + _ = 2u & 1u; + _ = vec2(2) & vec2(1); + _ = vec3(2u) & vec3(1u); - let _ = 2 ^ 1; - let _ = 2u ^ 1u; - let _ = vec2(2) ^ vec2(1); - let _ = vec3(2u) ^ vec3(1u); + _ = 2 ^ 1; + _ = 2u ^ 1u; + _ = vec2(2) ^ vec2(1); + _ = vec3(2u) ^ vec3(1u); - let _ = 2 << 1u; - let _ = 2u << 1u; - let _ = vec2(2) << vec2(1u); - let _ = vec3(2u) << vec3(1u); + _ = 2 << 1u; + _ = 2u << 1u; + _ = vec2(2) << vec2(1u); + _ = vec3(2u) << vec3(1u); - let _ = 2 >> 1u; - let _ = 2u >> 1u; - let _ = vec2(2) >> vec2(1u); - let _ = vec3(2u) >> vec3(1u); + _ = 2 >> 1u; + _ = 2u >> 1u; + _ = vec2(2) >> vec2(1u); + _ = vec3(2u) >> vec3(1u); } fn comparison() { - let _ = 2 == 1; - let _ = 2u == 1u; - let _ = 2.0 == 1.0; - let _ = vec2(2) == vec2(1); - let _ = vec3(2u) == vec3(1u); - let _ = vec4(2.0) == vec4(1.0); + _ = 2 == 1; + _ = 2u == 1u; + _ = 2.0 == 1.0; + _ = vec2(2) == vec2(1); + _ = vec3(2u) == vec3(1u); + _ = vec4(2.0) == vec4(1.0); - let _ = 2 != 1; - let _ = 2u != 1u; - let _ = 2.0 != 1.0; - let _ = vec2(2) != vec2(1); - let _ = vec3(2u) != vec3(1u); - let _ = vec4(2.0) != vec4(1.0); + _ = 2 != 1; + _ = 2u != 1u; + _ = 2.0 != 1.0; + _ = vec2(2) != vec2(1); + _ = vec3(2u) != vec3(1u); + _ = vec4(2.0) != vec4(1.0); - let _ = 2 < 1; - let _ = 2u < 1u; - let _ = 2.0 < 1.0; - let _ = vec2(2) < vec2(1); - let _ = vec3(2u) < vec3(1u); - let _ = vec4(2.0) < vec4(1.0); + _ = 2 < 1; + _ = 2u < 1u; + _ = 2.0 < 1.0; + _ = vec2(2) < vec2(1); + _ = vec3(2u) < vec3(1u); + _ = vec4(2.0) < vec4(1.0); - let _ = 2 <= 1; - let _ = 2u <= 1u; - let _ = 2.0 <= 1.0; - let _ = vec2(2) <= vec2(1); - let _ = vec3(2u) <= vec3(1u); - let _ = vec4(2.0) <= vec4(1.0); + _ = 2 <= 1; + _ = 2u <= 1u; + _ = 2.0 <= 1.0; + _ = vec2(2) <= vec2(1); + _ = vec3(2u) <= vec3(1u); + _ = vec4(2.0) <= vec4(1.0); - let _ = 2 > 1; - let _ = 2u > 1u; - let _ = 2.0 > 1.0; - let _ = vec2(2) > vec2(1); - let _ = vec3(2u) > vec3(1u); - let _ = vec4(2.0) > vec4(1.0); + _ = 2 > 1; + _ = 2u > 1u; + _ = 2.0 > 1.0; + _ = vec2(2) > vec2(1); + _ = vec3(2u) > vec3(1u); + _ = vec4(2.0) > vec4(1.0); - let _ = 2 >= 1; - let _ = 2u >= 1u; - let _ = 2.0 >= 1.0; - let _ = vec2(2) >= vec2(1); - let _ = vec3(2u) >= vec3(1u); - let _ = vec4(2.0) >= vec4(1.0); + _ = 2 >= 1; + _ = 2u >= 1u; + _ = 2.0 >= 1.0; + _ = vec2(2) >= vec2(1); + _ = vec3(2u) >= vec3(1u); + _ = vec4(2.0) >= vec4(1.0); } fn assignment() { @@ -281,10 +281,10 @@ fn assignment() { @compute @workgroup_size(1) fn main() { - let _ = builtins(); - let _ = splat(); - let _ = bool_cast(v_f32_one.xyz); - let _ = constructors(); + _ = builtins(); + _ = splat(); + _ = bool_cast(v_f32_one.xyz); + _ = constructors(); logical(); arithmetic(); diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index 267dc2cea..b5b4804d7 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -22,50 +22,36 @@ uniform Baz_block_1Vertex { Baz _group_0_binding_1_vs; }; void test_matrix_within_struct_accesses() { int idx = 9; - mat3x2 unnamed_1 = mat3x2(0.0); - vec2 unnamed_2 = vec2(0.0); - vec2 unnamed_3 = vec2(0.0); - float unnamed_4 = 0.0; - float unnamed_5 = 0.0; - float unnamed_6 = 0.0; - float unnamed_7 = 0.0; Baz t = Baz(mat3x2(0.0)); int _e4 = idx; idx = (_e4 - 1); - mat3x2 _e8 = _group_0_binding_1_vs.m; - unnamed_1 = _e8; - vec2 _e13 = _group_0_binding_1_vs.m[0]; - unnamed_2 = _e13; - int _e16 = idx; - vec2 _e18 = _group_0_binding_1_vs.m[_e16]; - unnamed_3 = _e18; - float _e25 = _group_0_binding_1_vs.m[0][1]; - unnamed_4 = _e25; + mat3x2 unnamed = _group_0_binding_1_vs.m; + vec2 unnamed_1 = _group_0_binding_1_vs.m[0]; + int _e14 = idx; + vec2 unnamed_2 = _group_0_binding_1_vs.m[_e14]; + float unnamed_3 = _group_0_binding_1_vs.m[0][1]; + int _e26 = idx; + float unnamed_4 = _group_0_binding_1_vs.m[0][_e26]; int _e30 = idx; - float _e32 = _group_0_binding_1_vs.m[0][_e30]; - unnamed_5 = _e32; - int _e35 = idx; - float _e39 = _group_0_binding_1_vs.m[_e35][1]; - unnamed_6 = _e39; - int _e42 = idx; - int _e44 = idx; - float _e46 = _group_0_binding_1_vs.m[_e42][_e44]; - unnamed_7 = _e46; + float unnamed_5 = _group_0_binding_1_vs.m[_e30][1]; + int _e36 = idx; + int _e38 = idx; + float unnamed_6 = _group_0_binding_1_vs.m[_e36][_e38]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - int _e57 = idx; - idx = (_e57 + 1); + int _e50 = idx; + idx = (_e50 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - int _e74 = idx; - t.m[_e74] = vec2(90.0); + int _e67 = idx; + t.m[_e67] = vec2(90.0); t.m[0][1] = 10.0; - int _e87 = idx; - t.m[0][_e87] = 20.0; - int _e91 = idx; - t.m[_e91][1] = 30.0; - int _e97 = idx; - int _e99 = idx; - t.m[_e97][_e99] = 40.0; + int _e80 = idx; + t.m[0][_e80] = 20.0; + int _e84 = idx; + t.m[_e84][1] = 30.0; + int _e90 = idx; + int _e92 = idx; + t.m[_e90][_e92] = 40.0; return; } @@ -82,7 +68,6 @@ void main() { uint vi = uint(gl_VertexID); float foo = 0.0; int c[5] = int[5](0, 0, 0, 0, 0); - float unnamed = 0.0; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); @@ -95,7 +80,6 @@ void main() { c[(vi + 1u)] = 42; int value = c[vi]; float _e42 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); - unnamed = _e42; gl_Position = vec4((_matrix * vec4(ivec4(value))), 2.0); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index bf7a7d847..a27e97939 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -35,174 +35,163 @@ vec3 bool_cast(vec3 x) { float constructors() { Foo foo = Foo(vec4(0.0), 0); - bool unnamed = false; - int unnamed_1 = 0; - uint unnamed_2 = 0u; - float unnamed_3 = 0.0; - uvec2 unnamed_4 = uvec2(0u, 0u); - mat2x2 unnamed_5 = mat2x2(vec2(0.0, 0.0), vec2(0.0, 0.0)); - Foo unnamed_6[3] = Foo[3](Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0)); - Foo unnamed_7 = Foo(vec4(0.0, 0.0, 0.0, 0.0), 0); - uvec2 unnamed_8 = uvec2(0u); - mat2x2 unnamed_9 = mat2x2(0.0); - int unnamed_10[4] = int[4](0, 0, 0, 0); foo = Foo(vec4(1.0), 1); mat2x2 mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); mat4x4 mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - unnamed_8 = uvec2(0u); - unnamed_9 = mat2x2(vec2(0.0), vec2(0.0)); - unnamed_10 = int[4](0, 1, 2, 3); - float _e70 = foo.a.x; - return _e70; + uvec2 unnamed = uvec2(0u); + mat2x2 unnamed_1 = mat2x2(vec2(0.0), vec2(0.0)); + int unnamed_2[4] = int[4](0, 1, 2, 3); + float _e59 = foo.a.x; + return _e59; } void logical() { - bool unnamed_11 = (!true); - bvec2 unnamed_12 = not(bvec2(true)); - bool unnamed_13 = (true || false); - bool unnamed_14 = (true && false); - bool unnamed_15 = (true || false); - bvec3 unnamed_16 = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); - bool unnamed_17 = (true && false); - bvec4 unnamed_18 = bvec4(bvec4(true).x && bvec4(false).x, bvec4(true).y && bvec4(false).y, bvec4(true).z && bvec4(false).z, bvec4(true).w && bvec4(false).w); + bool unnamed_3 = (!true); + bvec2 unnamed_4 = not(bvec2(true)); + bool unnamed_5 = (true || false); + bool unnamed_6 = (true && false); + bool unnamed_7 = (true || false); + bvec3 unnamed_8 = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); + bool unnamed_9 = (true && false); + bvec4 unnamed_10 = bvec4(bvec4(true).x && bvec4(false).x, bvec4(true).y && bvec4(false).y, bvec4(true).z && bvec4(false).z, bvec4(true).w && bvec4(false).w); } void arithmetic() { - ivec2 unnamed_19 = (-ivec2(1)); - vec2 unnamed_20 = (-vec2(1.0)); - int unnamed_21 = (2 + 1); - uint unnamed_22 = (2u + 1u); - float unnamed_23 = (2.0 + 1.0); - ivec2 unnamed_24 = (ivec2(2) + ivec2(1)); - uvec3 unnamed_25 = (uvec3(2u) + uvec3(1u)); - vec4 unnamed_26 = (vec4(2.0) + vec4(1.0)); - int unnamed_27 = (2 - 1); - uint unnamed_28 = (2u - 1u); - float unnamed_29 = (2.0 - 1.0); - ivec2 unnamed_30 = (ivec2(2) - ivec2(1)); - uvec3 unnamed_31 = (uvec3(2u) - uvec3(1u)); - vec4 unnamed_32 = (vec4(2.0) - vec4(1.0)); - int unnamed_33 = (2 * 1); - uint unnamed_34 = (2u * 1u); - float unnamed_35 = (2.0 * 1.0); - ivec2 unnamed_36 = (ivec2(2) * ivec2(1)); - uvec3 unnamed_37 = (uvec3(2u) * uvec3(1u)); - vec4 unnamed_38 = (vec4(2.0) * vec4(1.0)); - int unnamed_39 = (2 / 1); - uint unnamed_40 = (2u / 1u); - float unnamed_41 = (2.0 / 1.0); - ivec2 unnamed_42 = (ivec2(2) / ivec2(1)); - uvec3 unnamed_43 = (uvec3(2u) / uvec3(1u)); - vec4 unnamed_44 = (vec4(2.0) / vec4(1.0)); - int unnamed_45 = (2 % 1); - uint unnamed_46 = (2u % 1u); - float unnamed_47 = (2.0 - 1.0 * trunc(2.0 / 1.0)); - ivec2 unnamed_48 = (ivec2(2) % ivec2(1)); - uvec3 unnamed_49 = (uvec3(2u) % uvec3(1u)); - vec4 unnamed_50 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); - ivec2 unnamed_51 = (ivec2(2) + ivec2(1)); - ivec2 unnamed_52 = (ivec2(2) + ivec2(1)); - uvec2 unnamed_53 = (uvec2(2u) + uvec2(1u)); - uvec2 unnamed_54 = (uvec2(2u) + uvec2(1u)); - vec2 unnamed_55 = (vec2(2.0) + vec2(1.0)); - vec2 unnamed_56 = (vec2(2.0) + vec2(1.0)); - ivec2 unnamed_57 = (ivec2(2) - ivec2(1)); - ivec2 unnamed_58 = (ivec2(2) - ivec2(1)); - uvec2 unnamed_59 = (uvec2(2u) - uvec2(1u)); - uvec2 unnamed_60 = (uvec2(2u) - uvec2(1u)); - vec2 unnamed_61 = (vec2(2.0) - vec2(1.0)); - vec2 unnamed_62 = (vec2(2.0) - vec2(1.0)); - ivec2 unnamed_63 = (ivec2(2) * 1); - ivec2 unnamed_64 = (2 * ivec2(1)); - uvec2 unnamed_65 = (uvec2(2u) * 1u); - uvec2 unnamed_66 = (2u * uvec2(1u)); - vec2 unnamed_67 = (vec2(2.0) * 1.0); - vec2 unnamed_68 = (2.0 * vec2(1.0)); - ivec2 unnamed_69 = (ivec2(2) / ivec2(1)); - ivec2 unnamed_70 = (ivec2(2) / ivec2(1)); - uvec2 unnamed_71 = (uvec2(2u) / uvec2(1u)); - uvec2 unnamed_72 = (uvec2(2u) / uvec2(1u)); - vec2 unnamed_73 = (vec2(2.0) / vec2(1.0)); - vec2 unnamed_74 = (vec2(2.0) / vec2(1.0)); - ivec2 unnamed_75 = (ivec2(2) % ivec2(1)); - ivec2 unnamed_76 = (ivec2(2) % ivec2(1)); - uvec2 unnamed_77 = (uvec2(2u) % uvec2(1u)); - uvec2 unnamed_78 = (uvec2(2u) % uvec2(1u)); - vec2 unnamed_79 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); - vec2 unnamed_80 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); - mat3x3 unnamed_81 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_82 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_83 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - mat3x3 unnamed_84 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - vec3 unnamed_85 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - vec4 unnamed_86 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_87 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + ivec2 unnamed_11 = (-ivec2(1)); + vec2 unnamed_12 = (-vec2(1.0)); + int unnamed_13 = (2 + 1); + uint unnamed_14 = (2u + 1u); + float unnamed_15 = (2.0 + 1.0); + ivec2 unnamed_16 = (ivec2(2) + ivec2(1)); + uvec3 unnamed_17 = (uvec3(2u) + uvec3(1u)); + vec4 unnamed_18 = (vec4(2.0) + vec4(1.0)); + int unnamed_19 = (2 - 1); + uint unnamed_20 = (2u - 1u); + float unnamed_21 = (2.0 - 1.0); + ivec2 unnamed_22 = (ivec2(2) - ivec2(1)); + uvec3 unnamed_23 = (uvec3(2u) - uvec3(1u)); + vec4 unnamed_24 = (vec4(2.0) - vec4(1.0)); + int unnamed_25 = (2 * 1); + uint unnamed_26 = (2u * 1u); + float unnamed_27 = (2.0 * 1.0); + ivec2 unnamed_28 = (ivec2(2) * ivec2(1)); + uvec3 unnamed_29 = (uvec3(2u) * uvec3(1u)); + vec4 unnamed_30 = (vec4(2.0) * vec4(1.0)); + int unnamed_31 = (2 / 1); + uint unnamed_32 = (2u / 1u); + float unnamed_33 = (2.0 / 1.0); + ivec2 unnamed_34 = (ivec2(2) / ivec2(1)); + uvec3 unnamed_35 = (uvec3(2u) / uvec3(1u)); + vec4 unnamed_36 = (vec4(2.0) / vec4(1.0)); + int unnamed_37 = (2 % 1); + uint unnamed_38 = (2u % 1u); + float unnamed_39 = (2.0 - 1.0 * trunc(2.0 / 1.0)); + ivec2 unnamed_40 = (ivec2(2) % ivec2(1)); + uvec3 unnamed_41 = (uvec3(2u) % uvec3(1u)); + vec4 unnamed_42 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); + ivec2 unnamed_43 = (ivec2(2) + ivec2(1)); + ivec2 unnamed_44 = (ivec2(2) + ivec2(1)); + uvec2 unnamed_45 = (uvec2(2u) + uvec2(1u)); + uvec2 unnamed_46 = (uvec2(2u) + uvec2(1u)); + vec2 unnamed_47 = (vec2(2.0) + vec2(1.0)); + vec2 unnamed_48 = (vec2(2.0) + vec2(1.0)); + ivec2 unnamed_49 = (ivec2(2) - ivec2(1)); + ivec2 unnamed_50 = (ivec2(2) - ivec2(1)); + uvec2 unnamed_51 = (uvec2(2u) - uvec2(1u)); + uvec2 unnamed_52 = (uvec2(2u) - uvec2(1u)); + vec2 unnamed_53 = (vec2(2.0) - vec2(1.0)); + vec2 unnamed_54 = (vec2(2.0) - vec2(1.0)); + ivec2 unnamed_55 = (ivec2(2) * 1); + ivec2 unnamed_56 = (2 * ivec2(1)); + uvec2 unnamed_57 = (uvec2(2u) * 1u); + uvec2 unnamed_58 = (2u * uvec2(1u)); + vec2 unnamed_59 = (vec2(2.0) * 1.0); + vec2 unnamed_60 = (2.0 * vec2(1.0)); + ivec2 unnamed_61 = (ivec2(2) / ivec2(1)); + ivec2 unnamed_62 = (ivec2(2) / ivec2(1)); + uvec2 unnamed_63 = (uvec2(2u) / uvec2(1u)); + uvec2 unnamed_64 = (uvec2(2u) / uvec2(1u)); + vec2 unnamed_65 = (vec2(2.0) / vec2(1.0)); + vec2 unnamed_66 = (vec2(2.0) / vec2(1.0)); + ivec2 unnamed_67 = (ivec2(2) % ivec2(1)); + ivec2 unnamed_68 = (ivec2(2) % ivec2(1)); + uvec2 unnamed_69 = (uvec2(2u) % uvec2(1u)); + uvec2 unnamed_70 = (uvec2(2u) % uvec2(1u)); + vec2 unnamed_71 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + vec2 unnamed_72 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + mat3x3 unnamed_73 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_74 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_75 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + mat3x3 unnamed_76 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + vec3 unnamed_77 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + vec4 unnamed_78 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_79 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } void bit() { - int unnamed_88 = (~1); - uint unnamed_89 = (~1u); - ivec2 unnamed_90 = (~ivec2(1)); - uvec3 unnamed_91 = (~uvec3(1u)); - int unnamed_92 = (2 | 1); - uint unnamed_93 = (2u | 1u); - ivec2 unnamed_94 = (ivec2(2) | ivec2(1)); - uvec3 unnamed_95 = (uvec3(2u) | uvec3(1u)); - int unnamed_96 = (2 & 1); - uint unnamed_97 = (2u & 1u); - ivec2 unnamed_98 = (ivec2(2) & ivec2(1)); - uvec3 unnamed_99 = (uvec3(2u) & uvec3(1u)); - int unnamed_100 = (2 ^ 1); - uint unnamed_101 = (2u ^ 1u); - ivec2 unnamed_102 = (ivec2(2) ^ ivec2(1)); - uvec3 unnamed_103 = (uvec3(2u) ^ uvec3(1u)); - int unnamed_104 = (2 << 1u); - uint unnamed_105 = (2u << 1u); - ivec2 unnamed_106 = (ivec2(2) << uvec2(1u)); - uvec3 unnamed_107 = (uvec3(2u) << uvec3(1u)); - int unnamed_108 = (2 >> 1u); - uint unnamed_109 = (2u >> 1u); - ivec2 unnamed_110 = (ivec2(2) >> uvec2(1u)); - uvec3 unnamed_111 = (uvec3(2u) >> uvec3(1u)); + int unnamed_80 = (~1); + uint unnamed_81 = (~1u); + ivec2 unnamed_82 = (~ivec2(1)); + uvec3 unnamed_83 = (~uvec3(1u)); + int unnamed_84 = (2 | 1); + uint unnamed_85 = (2u | 1u); + ivec2 unnamed_86 = (ivec2(2) | ivec2(1)); + uvec3 unnamed_87 = (uvec3(2u) | uvec3(1u)); + int unnamed_88 = (2 & 1); + uint unnamed_89 = (2u & 1u); + ivec2 unnamed_90 = (ivec2(2) & ivec2(1)); + uvec3 unnamed_91 = (uvec3(2u) & uvec3(1u)); + int unnamed_92 = (2 ^ 1); + uint unnamed_93 = (2u ^ 1u); + ivec2 unnamed_94 = (ivec2(2) ^ ivec2(1)); + uvec3 unnamed_95 = (uvec3(2u) ^ uvec3(1u)); + int unnamed_96 = (2 << 1u); + uint unnamed_97 = (2u << 1u); + ivec2 unnamed_98 = (ivec2(2) << uvec2(1u)); + uvec3 unnamed_99 = (uvec3(2u) << uvec3(1u)); + int unnamed_100 = (2 >> 1u); + uint unnamed_101 = (2u >> 1u); + ivec2 unnamed_102 = (ivec2(2) >> uvec2(1u)); + uvec3 unnamed_103 = (uvec3(2u) >> uvec3(1u)); } void comparison() { - bool unnamed_112 = (2 == 1); - bool unnamed_113 = (2u == 1u); - bool unnamed_114 = (2.0 == 1.0); - bvec2 unnamed_115 = equal(ivec2(2), ivec2(1)); - bvec3 unnamed_116 = equal(uvec3(2u), uvec3(1u)); - bvec4 unnamed_117 = equal(vec4(2.0), vec4(1.0)); - bool unnamed_118 = (2 != 1); - bool unnamed_119 = (2u != 1u); - bool unnamed_120 = (2.0 != 1.0); - bvec2 unnamed_121 = notEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_122 = notEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_123 = notEqual(vec4(2.0), vec4(1.0)); - bool unnamed_124 = (2 < 1); - bool unnamed_125 = (2u < 1u); - bool unnamed_126 = (2.0 < 1.0); - bvec2 unnamed_127 = lessThan(ivec2(2), ivec2(1)); - bvec3 unnamed_128 = lessThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_129 = lessThan(vec4(2.0), vec4(1.0)); - bool unnamed_130 = (2 <= 1); - bool unnamed_131 = (2u <= 1u); - bool unnamed_132 = (2.0 <= 1.0); - bvec2 unnamed_133 = lessThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_134 = lessThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_135 = lessThanEqual(vec4(2.0), vec4(1.0)); - bool unnamed_136 = (2 > 1); - bool unnamed_137 = (2u > 1u); - bool unnamed_138 = (2.0 > 1.0); - bvec2 unnamed_139 = greaterThan(ivec2(2), ivec2(1)); - bvec3 unnamed_140 = greaterThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_141 = greaterThan(vec4(2.0), vec4(1.0)); - bool unnamed_142 = (2 >= 1); - bool unnamed_143 = (2u >= 1u); - bool unnamed_144 = (2.0 >= 1.0); - bvec2 unnamed_145 = greaterThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_146 = greaterThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_147 = greaterThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_104 = (2 == 1); + bool unnamed_105 = (2u == 1u); + bool unnamed_106 = (2.0 == 1.0); + bvec2 unnamed_107 = equal(ivec2(2), ivec2(1)); + bvec3 unnamed_108 = equal(uvec3(2u), uvec3(1u)); + bvec4 unnamed_109 = equal(vec4(2.0), vec4(1.0)); + bool unnamed_110 = (2 != 1); + bool unnamed_111 = (2u != 1u); + bool unnamed_112 = (2.0 != 1.0); + bvec2 unnamed_113 = notEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_114 = notEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_115 = notEqual(vec4(2.0), vec4(1.0)); + bool unnamed_116 = (2 < 1); + bool unnamed_117 = (2u < 1u); + bool unnamed_118 = (2.0 < 1.0); + bvec2 unnamed_119 = lessThan(ivec2(2), ivec2(1)); + bvec3 unnamed_120 = lessThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_121 = lessThan(vec4(2.0), vec4(1.0)); + bool unnamed_122 = (2 <= 1); + bool unnamed_123 = (2u <= 1u); + bool unnamed_124 = (2.0 <= 1.0); + bvec2 unnamed_125 = lessThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_126 = lessThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_127 = lessThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_128 = (2 > 1); + bool unnamed_129 = (2u > 1u); + bool unnamed_130 = (2.0 > 1.0); + bvec2 unnamed_131 = greaterThan(ivec2(2), ivec2(1)); + bvec3 unnamed_132 = greaterThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_133 = greaterThan(vec4(2.0), vec4(1.0)); + bool unnamed_134 = (2 >= 1); + bool unnamed_135 = (2u >= 1u); + bool unnamed_136 = (2.0 >= 1.0); + bvec2 unnamed_137 = greaterThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_138 = greaterThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_139 = greaterThanEqual(vec4(2.0), vec4(1.0)); } void assignment() { diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index b94bc16bc..3403cb39e 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -58,51 +58,37 @@ Baz ConstructBaz(float3x2 arg0) { void test_matrix_within_struct_accesses() { int idx = 9; - float3x2 unnamed_1 = (float3x2)0; - float2 unnamed_2 = (float2)0; - float2 unnamed_3 = (float2)0; - float unnamed_4 = (float)0; - float unnamed_5 = (float)0; - float unnamed_6 = (float)0; - float unnamed_7 = (float)0; Baz t = (Baz)0; int _expr4 = idx; idx = (_expr4 - 1); - float3x2 _expr8 = GetMatmOnBaz(baz); - unnamed_1 = _expr8; - float2 _expr13 = GetMatmOnBaz(baz)[0]; - unnamed_2 = _expr13; - int _expr16 = idx; - float2 _expr18 = GetMatmOnBaz(baz)[_expr16]; - unnamed_3 = _expr18; - float _expr25 = GetMatmOnBaz(baz)[0][1]; - unnamed_4 = _expr25; + float3x2 unnamed = GetMatmOnBaz(baz); + float2 unnamed_1 = GetMatmOnBaz(baz)[0]; + int _expr14 = idx; + float2 unnamed_2 = GetMatmOnBaz(baz)[_expr14]; + float unnamed_3 = GetMatmOnBaz(baz)[0][1]; + int _expr26 = idx; + float unnamed_4 = GetMatmOnBaz(baz)[0][_expr26]; int _expr30 = idx; - float _expr32 = GetMatmOnBaz(baz)[0][_expr30]; - unnamed_5 = _expr32; - int _expr35 = idx; - float _expr39 = GetMatmOnBaz(baz)[_expr35][1]; - unnamed_6 = _expr39; - int _expr42 = idx; - int _expr44 = idx; - float _expr46 = GetMatmOnBaz(baz)[_expr42][_expr44]; - unnamed_7 = _expr46; + float unnamed_5 = GetMatmOnBaz(baz)[_expr30][1]; + int _expr36 = idx; + int _expr38 = idx; + float unnamed_6 = GetMatmOnBaz(baz)[_expr36][_expr38]; t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); - int _expr57 = idx; - idx = (_expr57 + 1); + int _expr50 = idx; + idx = (_expr50 + 1); SetMatmOnBaz(t, float3x2((6.0).xx, (5.0).xx, (4.0).xx)); t.m_0 = (9.0).xx; - int _expr74 = idx; - SetMatVecmOnBaz(t, (90.0).xx, _expr74); + int _expr67 = idx; + SetMatVecmOnBaz(t, (90.0).xx, _expr67); t.m_0[1] = 10.0; - int _expr87 = idx; - t.m_0[_expr87] = 20.0; - int _expr91 = idx; - SetMatScalarmOnBaz(t, 30.0, _expr91, 1); - int _expr97 = idx; - int _expr99 = idx; - SetMatScalarmOnBaz(t, 40.0, _expr97, _expr99); + int _expr80 = idx; + t.m_0[_expr80] = 20.0; + int _expr84 = idx; + SetMatScalarmOnBaz(t, 30.0, _expr84, 1); + int _expr90 = idx; + int _expr92 = idx; + SetMatScalarmOnBaz(t, 40.0, _expr90, _expr92); return; } @@ -133,7 +119,6 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position { float foo = 0.0; int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; - float unnamed = (float)0; float baz_1 = foo; foo = 1.0; @@ -150,7 +135,6 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position c[(vi + 1u)] = 42; int value = c[vi]; const float _e42 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); - unnamed = _e42; return float4(mul(float4((value).xxxx), _matrix), 2.0); } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index b23d47799..020a28ca4 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -57,182 +57,168 @@ int Constructarray4_int_(int arg0, int arg1, int arg2, int arg3)[4] { float constructors() { Foo foo = (Foo)0; - bool unnamed = false; - int unnamed_1 = 0; - uint unnamed_2 = 0u; - float unnamed_3 = 0.0; - uint2 unnamed_4 = uint2(0u, 0u); - float2x2 unnamed_5 = float2x2(float2(0.0, 0.0), float2(0.0, 0.0)); - Foo unnamed_6[3] = Constructarray3_Foo_(ConstructFoo(float4(0.0, 0.0, 0.0, 0.0), 0), ConstructFoo(float4(0.0, 0.0, 0.0, 0.0), 0), ConstructFoo(float4(0.0, 0.0, 0.0, 0.0), 0)); - Foo unnamed_7 = ConstructFoo(float4(0.0, 0.0, 0.0, 0.0), 0); - uint2 unnamed_8 = (uint2)0; - float2x2 unnamed_9 = (float2x2)0; - int unnamed_10[4] = {(int)0,(int)0,(int)0,(int)0}; foo = ConstructFoo((1.0).xxxx, 1); float2x2 mat2comp = float2x2(float2(1.0, 0.0), float2(0.0, 1.0)); float4x4 mat4comp = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); - unnamed_8 = (0u).xx; - unnamed_9 = float2x2((0.0).xx, (0.0).xx); - { - int _result[4]=Constructarray4_int_(0, 1, 2, 3); - for(int _i=0; _i<4; ++_i) unnamed_10[_i] = _result[_i]; - } - float _expr70 = foo.a.x; - return _expr70; + uint2 unnamed = (0u).xx; + float2x2 unnamed_1 = float2x2((0.0).xx, (0.0).xx); + int unnamed_2[4] = Constructarray4_int_(0, 1, 2, 3); + float _expr59 = foo.a.x; + return _expr59; } void logical() { - bool unnamed_11 = !true; - bool2 unnamed_12 = !(true).xx; - bool unnamed_13 = (true || false); - bool unnamed_14 = (true && false); - bool unnamed_15 = (true | false); - bool3 unnamed_16 = ((true).xxx | (false).xxx); - bool unnamed_17 = (true & false); - bool4 unnamed_18 = ((true).xxxx & (false).xxxx); + bool unnamed_3 = !true; + bool2 unnamed_4 = !(true).xx; + bool unnamed_5 = (true || false); + bool unnamed_6 = (true && false); + bool unnamed_7 = (true | false); + bool3 unnamed_8 = ((true).xxx | (false).xxx); + bool unnamed_9 = (true & false); + bool4 unnamed_10 = ((true).xxxx & (false).xxxx); } void arithmetic() { - int2 unnamed_19 = -(1).xx; - float2 unnamed_20 = -(1.0).xx; - int unnamed_21 = (2 + 1); - uint unnamed_22 = (2u + 1u); - float unnamed_23 = (2.0 + 1.0); - int2 unnamed_24 = ((2).xx + (1).xx); - uint3 unnamed_25 = ((2u).xxx + (1u).xxx); - float4 unnamed_26 = ((2.0).xxxx + (1.0).xxxx); - int unnamed_27 = (2 - 1); - uint unnamed_28 = (2u - 1u); - float unnamed_29 = (2.0 - 1.0); - int2 unnamed_30 = ((2).xx - (1).xx); - uint3 unnamed_31 = ((2u).xxx - (1u).xxx); - float4 unnamed_32 = ((2.0).xxxx - (1.0).xxxx); - int unnamed_33 = (2 * 1); - uint unnamed_34 = (2u * 1u); - float unnamed_35 = (2.0 * 1.0); - int2 unnamed_36 = ((2).xx * (1).xx); - uint3 unnamed_37 = ((2u).xxx * (1u).xxx); - float4 unnamed_38 = ((2.0).xxxx * (1.0).xxxx); - int unnamed_39 = (2 / 1); - uint unnamed_40 = (2u / 1u); - float unnamed_41 = (2.0 / 1.0); - int2 unnamed_42 = ((2).xx / (1).xx); - uint3 unnamed_43 = ((2u).xxx / (1u).xxx); - float4 unnamed_44 = ((2.0).xxxx / (1.0).xxxx); - int unnamed_45 = (2 % 1); - uint unnamed_46 = (2u % 1u); - float unnamed_47 = (2.0 % 1.0); - int2 unnamed_48 = ((2).xx % (1).xx); - uint3 unnamed_49 = ((2u).xxx % (1u).xxx); - float4 unnamed_50 = ((2.0).xxxx % (1.0).xxxx); - int2 unnamed_51 = ((2).xx + (1).xx); - int2 unnamed_52 = ((2).xx + (1).xx); - uint2 unnamed_53 = ((2u).xx + (1u).xx); - uint2 unnamed_54 = ((2u).xx + (1u).xx); - float2 unnamed_55 = ((2.0).xx + (1.0).xx); - float2 unnamed_56 = ((2.0).xx + (1.0).xx); - int2 unnamed_57 = ((2).xx - (1).xx); - int2 unnamed_58 = ((2).xx - (1).xx); - uint2 unnamed_59 = ((2u).xx - (1u).xx); - uint2 unnamed_60 = ((2u).xx - (1u).xx); - float2 unnamed_61 = ((2.0).xx - (1.0).xx); - float2 unnamed_62 = ((2.0).xx - (1.0).xx); - int2 unnamed_63 = ((2).xx * 1); - int2 unnamed_64 = (2 * (1).xx); - uint2 unnamed_65 = ((2u).xx * 1u); - uint2 unnamed_66 = (2u * (1u).xx); - float2 unnamed_67 = ((2.0).xx * 1.0); - float2 unnamed_68 = (2.0 * (1.0).xx); - int2 unnamed_69 = ((2).xx / (1).xx); - int2 unnamed_70 = ((2).xx / (1).xx); - uint2 unnamed_71 = ((2u).xx / (1u).xx); - uint2 unnamed_72 = ((2u).xx / (1u).xx); - float2 unnamed_73 = ((2.0).xx / (1.0).xx); - float2 unnamed_74 = ((2.0).xx / (1.0).xx); - int2 unnamed_75 = ((2).xx % (1).xx); - int2 unnamed_76 = ((2).xx % (1).xx); - uint2 unnamed_77 = ((2u).xx % (1u).xx); - uint2 unnamed_78 = ((2u).xx % (1u).xx); - float2 unnamed_79 = ((2.0).xx % (1.0).xx); - float2 unnamed_80 = ((2.0).xx % (1.0).xx); - float3x3 unnamed_81 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_82 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_83 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_84 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); - float3 unnamed_85 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float4 unnamed_86 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); - float3x3 unnamed_87 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + int2 unnamed_11 = -(1).xx; + float2 unnamed_12 = -(1.0).xx; + int unnamed_13 = (2 + 1); + uint unnamed_14 = (2u + 1u); + float unnamed_15 = (2.0 + 1.0); + int2 unnamed_16 = ((2).xx + (1).xx); + uint3 unnamed_17 = ((2u).xxx + (1u).xxx); + float4 unnamed_18 = ((2.0).xxxx + (1.0).xxxx); + int unnamed_19 = (2 - 1); + uint unnamed_20 = (2u - 1u); + float unnamed_21 = (2.0 - 1.0); + int2 unnamed_22 = ((2).xx - (1).xx); + uint3 unnamed_23 = ((2u).xxx - (1u).xxx); + float4 unnamed_24 = ((2.0).xxxx - (1.0).xxxx); + int unnamed_25 = (2 * 1); + uint unnamed_26 = (2u * 1u); + float unnamed_27 = (2.0 * 1.0); + int2 unnamed_28 = ((2).xx * (1).xx); + uint3 unnamed_29 = ((2u).xxx * (1u).xxx); + float4 unnamed_30 = ((2.0).xxxx * (1.0).xxxx); + int unnamed_31 = (2 / 1); + uint unnamed_32 = (2u / 1u); + float unnamed_33 = (2.0 / 1.0); + int2 unnamed_34 = ((2).xx / (1).xx); + uint3 unnamed_35 = ((2u).xxx / (1u).xxx); + float4 unnamed_36 = ((2.0).xxxx / (1.0).xxxx); + int unnamed_37 = (2 % 1); + uint unnamed_38 = (2u % 1u); + float unnamed_39 = (2.0 % 1.0); + int2 unnamed_40 = ((2).xx % (1).xx); + uint3 unnamed_41 = ((2u).xxx % (1u).xxx); + float4 unnamed_42 = ((2.0).xxxx % (1.0).xxxx); + int2 unnamed_43 = ((2).xx + (1).xx); + int2 unnamed_44 = ((2).xx + (1).xx); + uint2 unnamed_45 = ((2u).xx + (1u).xx); + uint2 unnamed_46 = ((2u).xx + (1u).xx); + float2 unnamed_47 = ((2.0).xx + (1.0).xx); + float2 unnamed_48 = ((2.0).xx + (1.0).xx); + int2 unnamed_49 = ((2).xx - (1).xx); + int2 unnamed_50 = ((2).xx - (1).xx); + uint2 unnamed_51 = ((2u).xx - (1u).xx); + uint2 unnamed_52 = ((2u).xx - (1u).xx); + float2 unnamed_53 = ((2.0).xx - (1.0).xx); + float2 unnamed_54 = ((2.0).xx - (1.0).xx); + int2 unnamed_55 = ((2).xx * 1); + int2 unnamed_56 = (2 * (1).xx); + uint2 unnamed_57 = ((2u).xx * 1u); + uint2 unnamed_58 = (2u * (1u).xx); + float2 unnamed_59 = ((2.0).xx * 1.0); + float2 unnamed_60 = (2.0 * (1.0).xx); + int2 unnamed_61 = ((2).xx / (1).xx); + int2 unnamed_62 = ((2).xx / (1).xx); + uint2 unnamed_63 = ((2u).xx / (1u).xx); + uint2 unnamed_64 = ((2u).xx / (1u).xx); + float2 unnamed_65 = ((2.0).xx / (1.0).xx); + float2 unnamed_66 = ((2.0).xx / (1.0).xx); + int2 unnamed_67 = ((2).xx % (1).xx); + int2 unnamed_68 = ((2).xx % (1).xx); + uint2 unnamed_69 = ((2u).xx % (1u).xx); + uint2 unnamed_70 = ((2u).xx % (1u).xx); + float2 unnamed_71 = ((2.0).xx % (1.0).xx); + float2 unnamed_72 = ((2.0).xx % (1.0).xx); + float3x3 unnamed_73 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_74 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_75 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_76 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); + float3 unnamed_77 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float4 unnamed_78 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); + float3x3 unnamed_79 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); } void bit() { - int unnamed_88 = ~1; - uint unnamed_89 = ~1u; - int2 unnamed_90 = ~(1).xx; - uint3 unnamed_91 = ~(1u).xxx; - int unnamed_92 = (2 | 1); - uint unnamed_93 = (2u | 1u); - int2 unnamed_94 = ((2).xx | (1).xx); - uint3 unnamed_95 = ((2u).xxx | (1u).xxx); - int unnamed_96 = (2 & 1); - uint unnamed_97 = (2u & 1u); - int2 unnamed_98 = ((2).xx & (1).xx); - uint3 unnamed_99 = ((2u).xxx & (1u).xxx); - int unnamed_100 = (2 ^ 1); - uint unnamed_101 = (2u ^ 1u); - int2 unnamed_102 = ((2).xx ^ (1).xx); - uint3 unnamed_103 = ((2u).xxx ^ (1u).xxx); - int unnamed_104 = (2 << 1u); - uint unnamed_105 = (2u << 1u); - int2 unnamed_106 = ((2).xx << (1u).xx); - uint3 unnamed_107 = ((2u).xxx << (1u).xxx); - int unnamed_108 = (2 >> 1u); - uint unnamed_109 = (2u >> 1u); - int2 unnamed_110 = ((2).xx >> (1u).xx); - uint3 unnamed_111 = ((2u).xxx >> (1u).xxx); + int unnamed_80 = ~1; + uint unnamed_81 = ~1u; + int2 unnamed_82 = ~(1).xx; + uint3 unnamed_83 = ~(1u).xxx; + int unnamed_84 = (2 | 1); + uint unnamed_85 = (2u | 1u); + int2 unnamed_86 = ((2).xx | (1).xx); + uint3 unnamed_87 = ((2u).xxx | (1u).xxx); + int unnamed_88 = (2 & 1); + uint unnamed_89 = (2u & 1u); + int2 unnamed_90 = ((2).xx & (1).xx); + uint3 unnamed_91 = ((2u).xxx & (1u).xxx); + int unnamed_92 = (2 ^ 1); + uint unnamed_93 = (2u ^ 1u); + int2 unnamed_94 = ((2).xx ^ (1).xx); + uint3 unnamed_95 = ((2u).xxx ^ (1u).xxx); + int unnamed_96 = (2 << 1u); + uint unnamed_97 = (2u << 1u); + int2 unnamed_98 = ((2).xx << (1u).xx); + uint3 unnamed_99 = ((2u).xxx << (1u).xxx); + int unnamed_100 = (2 >> 1u); + uint unnamed_101 = (2u >> 1u); + int2 unnamed_102 = ((2).xx >> (1u).xx); + uint3 unnamed_103 = ((2u).xxx >> (1u).xxx); } void comparison() { - bool unnamed_112 = (2 == 1); - bool unnamed_113 = (2u == 1u); - bool unnamed_114 = (2.0 == 1.0); - bool2 unnamed_115 = ((2).xx == (1).xx); - bool3 unnamed_116 = ((2u).xxx == (1u).xxx); - bool4 unnamed_117 = ((2.0).xxxx == (1.0).xxxx); - bool unnamed_118 = (2 != 1); - bool unnamed_119 = (2u != 1u); - bool unnamed_120 = (2.0 != 1.0); - bool2 unnamed_121 = ((2).xx != (1).xx); - bool3 unnamed_122 = ((2u).xxx != (1u).xxx); - bool4 unnamed_123 = ((2.0).xxxx != (1.0).xxxx); - bool unnamed_124 = (2 < 1); - bool unnamed_125 = (2u < 1u); - bool unnamed_126 = (2.0 < 1.0); - bool2 unnamed_127 = ((2).xx < (1).xx); - bool3 unnamed_128 = ((2u).xxx < (1u).xxx); - bool4 unnamed_129 = ((2.0).xxxx < (1.0).xxxx); - bool unnamed_130 = (2 <= 1); - bool unnamed_131 = (2u <= 1u); - bool unnamed_132 = (2.0 <= 1.0); - bool2 unnamed_133 = ((2).xx <= (1).xx); - bool3 unnamed_134 = ((2u).xxx <= (1u).xxx); - bool4 unnamed_135 = ((2.0).xxxx <= (1.0).xxxx); - bool unnamed_136 = (2 > 1); - bool unnamed_137 = (2u > 1u); - bool unnamed_138 = (2.0 > 1.0); - bool2 unnamed_139 = ((2).xx > (1).xx); - bool3 unnamed_140 = ((2u).xxx > (1u).xxx); - bool4 unnamed_141 = ((2.0).xxxx > (1.0).xxxx); - bool unnamed_142 = (2 >= 1); - bool unnamed_143 = (2u >= 1u); - bool unnamed_144 = (2.0 >= 1.0); - bool2 unnamed_145 = ((2).xx >= (1).xx); - bool3 unnamed_146 = ((2u).xxx >= (1u).xxx); - bool4 unnamed_147 = ((2.0).xxxx >= (1.0).xxxx); + bool unnamed_104 = (2 == 1); + bool unnamed_105 = (2u == 1u); + bool unnamed_106 = (2.0 == 1.0); + bool2 unnamed_107 = ((2).xx == (1).xx); + bool3 unnamed_108 = ((2u).xxx == (1u).xxx); + bool4 unnamed_109 = ((2.0).xxxx == (1.0).xxxx); + bool unnamed_110 = (2 != 1); + bool unnamed_111 = (2u != 1u); + bool unnamed_112 = (2.0 != 1.0); + bool2 unnamed_113 = ((2).xx != (1).xx); + bool3 unnamed_114 = ((2u).xxx != (1u).xxx); + bool4 unnamed_115 = ((2.0).xxxx != (1.0).xxxx); + bool unnamed_116 = (2 < 1); + bool unnamed_117 = (2u < 1u); + bool unnamed_118 = (2.0 < 1.0); + bool2 unnamed_119 = ((2).xx < (1).xx); + bool3 unnamed_120 = ((2u).xxx < (1u).xxx); + bool4 unnamed_121 = ((2.0).xxxx < (1.0).xxxx); + bool unnamed_122 = (2 <= 1); + bool unnamed_123 = (2u <= 1u); + bool unnamed_124 = (2.0 <= 1.0); + bool2 unnamed_125 = ((2).xx <= (1).xx); + bool3 unnamed_126 = ((2u).xxx <= (1u).xxx); + bool4 unnamed_127 = ((2.0).xxxx <= (1.0).xxxx); + bool unnamed_128 = (2 > 1); + bool unnamed_129 = (2u > 1u); + bool unnamed_130 = (2.0 > 1.0); + bool2 unnamed_131 = ((2).xx > (1).xx); + bool3 unnamed_132 = ((2u).xxx > (1u).xxx); + bool4 unnamed_133 = ((2.0).xxxx > (1.0).xxxx); + bool unnamed_134 = (2 >= 1); + bool unnamed_135 = (2u >= 1u); + bool unnamed_136 = (2.0 >= 1.0); + bool2 unnamed_137 = ((2).xx >= (1).xx); + bool3 unnamed_138 = ((2u).xxx >= (1u).xxx); + bool4 unnamed_139 = ((2.0).xxxx >= (1.0).xxxx); } void assignment() diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 8ba6750c7..5bcdd7d49 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -29,66 +29,52 @@ struct Bar { struct Baz { metal::float3x2 m; }; -struct type_12 { +struct type_11 { float inner[10]; }; -struct type_13 { - type_12 inner[5]; +struct type_12 { + type_11 inner[5]; }; -struct type_17 { +struct type_16 { int inner[5]; }; -constant type_12 const_type_12_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; -constant type_13 const_type_13_ = {const_type_12_, const_type_12_, const_type_12_, const_type_12_, const_type_12_}; +constant type_11 const_type_11_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; +constant type_12 const_type_12_ = {const_type_11_, const_type_11_, const_type_11_, const_type_11_, const_type_11_}; void test_matrix_within_struct_accesses( constant Baz& baz ) { int idx = 9; - metal::float3x2 unnamed_1; - metal::float2 unnamed_2; - metal::float2 unnamed_3; - float unnamed_4; - float unnamed_5; - float unnamed_6; - float unnamed_7; Baz t; int _e4 = idx; idx = _e4 - 1; - metal::float3x2 _e8 = baz.m; - unnamed_1 = _e8; - metal::float2 _e13 = baz.m[0]; - unnamed_2 = _e13; - int _e16 = idx; - metal::float2 _e18 = baz.m[_e16]; - unnamed_3 = _e18; - float _e25 = baz.m[0].y; - unnamed_4 = _e25; + metal::float3x2 unnamed = baz.m; + metal::float2 unnamed_1 = baz.m[0]; + int _e14 = idx; + metal::float2 unnamed_2 = baz.m[_e14]; + float unnamed_3 = baz.m[0].y; + int _e26 = idx; + float unnamed_4 = baz.m[0][_e26]; int _e30 = idx; - float _e32 = baz.m[0][_e30]; - unnamed_5 = _e32; - int _e35 = idx; - float _e39 = baz.m[_e35].y; - unnamed_6 = _e39; - int _e42 = idx; - int _e44 = idx; - float _e46 = baz.m[_e42][_e44]; - unnamed_7 = _e46; + float unnamed_5 = baz.m[_e30].y; + int _e36 = idx; + int _e38 = idx; + float unnamed_6 = baz.m[_e36][_e38]; t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; - int _e57 = idx; - idx = _e57 + 1; + int _e50 = idx; + idx = _e50 + 1; t.m = metal::float3x2(metal::float2(6.0), metal::float2(5.0), metal::float2(4.0)); t.m[0] = metal::float2(9.0); - int _e74 = idx; - t.m[_e74] = metal::float2(90.0); + int _e67 = idx; + t.m[_e67] = metal::float2(90.0); t.m[0].y = 10.0; - int _e87 = idx; - t.m[0][_e87] = 20.0; - int _e91 = idx; - t.m[_e91].y = 30.0; - int _e97 = idx; - int _e99 = idx; - t.m[_e97][_e99] = 40.0; + int _e80 = idx; + t.m[0][_e80] = 20.0; + int _e84 = idx; + t.m[_e84].y = 30.0; + int _e90 = idx; + int _e92 = idx; + t.m[_e90][_e92] = 40.0; return; } @@ -100,7 +86,7 @@ float read_from_private( } float test_arr_as_arg( - type_13 a + type_12 a ) { return a.inner[4].inner[9]; } @@ -117,8 +103,7 @@ vertex foo_vertOutput foo_vert( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo = 0.0; - type_17 c; - float unnamed; + type_16 c; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); @@ -127,11 +112,10 @@ vertex foo_vertOutput foo_vert( float b = bar._matrix[3].x; int a_1 = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; float _e28 = read_from_private(foo); - for(int _i=0; _i<5; ++_i) c.inner[_i] = type_17 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; + for(int _i=0; _i<5; ++_i) c.inner[_i] = type_16 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; - float _e42 = test_arr_as_arg(const_type_13_); - unnamed = _e42; + float _e42 = test_arr_as_arg(const_type_12_); return foo_vertOutput { metal::float4(_matrix * static_cast(metal::int4(value)), 2.0) }; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 02a9fd6f7..d47f543be 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -59,178 +59,167 @@ metal::float3 bool_cast( float constructors( ) { Foo foo; - bool unnamed = false; - int unnamed_1 = 0; - uint unnamed_2 = 0u; - float unnamed_3 = 0.0; - metal::uint2 unnamed_4 = const_type_11_; - metal::float2x2 unnamed_5 = const_type_7_; - type_12 unnamed_6 = const_type_12_; - Foo unnamed_7 = const_Foo; - metal::uint2 unnamed_8; - metal::float2x2 unnamed_9; - type_13 unnamed_10; foo = Foo {metal::float4(1.0), 1}; metal::float2x2 mat2comp = metal::float2x2(metal::float2(1.0, 0.0), metal::float2(0.0, 1.0)); metal::float4x4 mat4comp = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); - unnamed_8 = metal::uint2(0u); - unnamed_9 = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); - for(int _i=0; _i<4; ++_i) unnamed_10.inner[_i] = type_13 {0, 1, 2, 3}.inner[_i]; - float _e70 = foo.a.x; - return _e70; + metal::uint2 unnamed = metal::uint2(0u); + metal::float2x2 unnamed_1 = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); + type_13 unnamed_2 = type_13 {0, 1, 2, 3}; + float _e59 = foo.a.x; + return _e59; } void logical( ) { - bool unnamed_11 = !true; - metal::bool2 unnamed_12 = !metal::bool2(true); - bool unnamed_13 = true || false; - bool unnamed_14 = true && false; - bool unnamed_15 = true | false; - metal::bool3 unnamed_16 = metal::bool3(true) | metal::bool3(false); - bool unnamed_17 = true & false; - metal::bool4 unnamed_18 = metal::bool4(true) & metal::bool4(false); + bool unnamed_3 = !true; + metal::bool2 unnamed_4 = !metal::bool2(true); + bool unnamed_5 = true || false; + bool unnamed_6 = true && false; + bool unnamed_7 = true | false; + metal::bool3 unnamed_8 = metal::bool3(true) | metal::bool3(false); + bool unnamed_9 = true & false; + metal::bool4 unnamed_10 = metal::bool4(true) & metal::bool4(false); } void arithmetic( ) { - metal::int2 unnamed_19 = -metal::int2(1); - metal::float2 unnamed_20 = -metal::float2(1.0); - int unnamed_21 = 2 + 1; - uint unnamed_22 = 2u + 1u; - float unnamed_23 = 2.0 + 1.0; - metal::int2 unnamed_24 = metal::int2(2) + metal::int2(1); - metal::uint3 unnamed_25 = metal::uint3(2u) + metal::uint3(1u); - metal::float4 unnamed_26 = metal::float4(2.0) + metal::float4(1.0); - int unnamed_27 = 2 - 1; - uint unnamed_28 = 2u - 1u; - float unnamed_29 = 2.0 - 1.0; - metal::int2 unnamed_30 = metal::int2(2) - metal::int2(1); - metal::uint3 unnamed_31 = metal::uint3(2u) - metal::uint3(1u); - metal::float4 unnamed_32 = metal::float4(2.0) - metal::float4(1.0); - int unnamed_33 = 2 * 1; - uint unnamed_34 = 2u * 1u; - float unnamed_35 = 2.0 * 1.0; - metal::int2 unnamed_36 = metal::int2(2) * metal::int2(1); - metal::uint3 unnamed_37 = metal::uint3(2u) * metal::uint3(1u); - metal::float4 unnamed_38 = metal::float4(2.0) * metal::float4(1.0); - int unnamed_39 = 2 / 1; - uint unnamed_40 = 2u / 1u; - float unnamed_41 = 2.0 / 1.0; - metal::int2 unnamed_42 = metal::int2(2) / metal::int2(1); - metal::uint3 unnamed_43 = metal::uint3(2u) / metal::uint3(1u); - metal::float4 unnamed_44 = metal::float4(2.0) / metal::float4(1.0); - int unnamed_45 = 2 % 1; - uint unnamed_46 = 2u % 1u; - float unnamed_47 = metal::fmod(2.0, 1.0); - metal::int2 unnamed_48 = metal::int2(2) % metal::int2(1); - metal::uint3 unnamed_49 = metal::uint3(2u) % metal::uint3(1u); - metal::float4 unnamed_50 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); - metal::int2 unnamed_51 = metal::int2(2) + metal::int2(1); - metal::int2 unnamed_52 = metal::int2(2) + metal::int2(1); - metal::uint2 unnamed_53 = metal::uint2(2u) + metal::uint2(1u); - metal::uint2 unnamed_54 = metal::uint2(2u) + metal::uint2(1u); - metal::float2 unnamed_55 = metal::float2(2.0) + metal::float2(1.0); - metal::float2 unnamed_56 = metal::float2(2.0) + metal::float2(1.0); - metal::int2 unnamed_57 = metal::int2(2) - metal::int2(1); - metal::int2 unnamed_58 = metal::int2(2) - metal::int2(1); - metal::uint2 unnamed_59 = metal::uint2(2u) - metal::uint2(1u); - metal::uint2 unnamed_60 = metal::uint2(2u) - metal::uint2(1u); - metal::float2 unnamed_61 = metal::float2(2.0) - metal::float2(1.0); - metal::float2 unnamed_62 = metal::float2(2.0) - metal::float2(1.0); - metal::int2 unnamed_63 = metal::int2(2) * 1; - metal::int2 unnamed_64 = 2 * metal::int2(1); - metal::uint2 unnamed_65 = metal::uint2(2u) * 1u; - metal::uint2 unnamed_66 = 2u * metal::uint2(1u); - metal::float2 unnamed_67 = metal::float2(2.0) * 1.0; - metal::float2 unnamed_68 = 2.0 * metal::float2(1.0); - metal::int2 unnamed_69 = metal::int2(2) / metal::int2(1); - metal::int2 unnamed_70 = metal::int2(2) / metal::int2(1); - metal::uint2 unnamed_71 = metal::uint2(2u) / metal::uint2(1u); - metal::uint2 unnamed_72 = metal::uint2(2u) / metal::uint2(1u); - metal::float2 unnamed_73 = metal::float2(2.0) / metal::float2(1.0); - metal::float2 unnamed_74 = metal::float2(2.0) / metal::float2(1.0); - metal::int2 unnamed_75 = metal::int2(2) % metal::int2(1); - metal::int2 unnamed_76 = metal::int2(2) % metal::int2(1); - metal::uint2 unnamed_77 = metal::uint2(2u) % metal::uint2(1u); - metal::uint2 unnamed_78 = metal::uint2(2u) % metal::uint2(1u); - metal::float2 unnamed_79 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float2 unnamed_80 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float3x3 unnamed_81 = const_type_14_ + const_type_14_; - metal::float3x3 unnamed_82 = const_type_14_ - const_type_14_; - metal::float3x3 unnamed_83 = const_type_14_ * 1.0; - metal::float3x3 unnamed_84 = 2.0 * const_type_14_; - metal::float3 unnamed_85 = const_type_15_ * metal::float4(1.0); - metal::float4 unnamed_86 = metal::float3(2.0) * const_type_15_; - metal::float3x3 unnamed_87 = const_type_15_ * const_type_16_; + metal::int2 unnamed_11 = -metal::int2(1); + metal::float2 unnamed_12 = -metal::float2(1.0); + int unnamed_13 = 2 + 1; + uint unnamed_14 = 2u + 1u; + float unnamed_15 = 2.0 + 1.0; + metal::int2 unnamed_16 = metal::int2(2) + metal::int2(1); + metal::uint3 unnamed_17 = metal::uint3(2u) + metal::uint3(1u); + metal::float4 unnamed_18 = metal::float4(2.0) + metal::float4(1.0); + int unnamed_19 = 2 - 1; + uint unnamed_20 = 2u - 1u; + float unnamed_21 = 2.0 - 1.0; + metal::int2 unnamed_22 = metal::int2(2) - metal::int2(1); + metal::uint3 unnamed_23 = metal::uint3(2u) - metal::uint3(1u); + metal::float4 unnamed_24 = metal::float4(2.0) - metal::float4(1.0); + int unnamed_25 = 2 * 1; + uint unnamed_26 = 2u * 1u; + float unnamed_27 = 2.0 * 1.0; + metal::int2 unnamed_28 = metal::int2(2) * metal::int2(1); + metal::uint3 unnamed_29 = metal::uint3(2u) * metal::uint3(1u); + metal::float4 unnamed_30 = metal::float4(2.0) * metal::float4(1.0); + int unnamed_31 = 2 / 1; + uint unnamed_32 = 2u / 1u; + float unnamed_33 = 2.0 / 1.0; + metal::int2 unnamed_34 = metal::int2(2) / metal::int2(1); + metal::uint3 unnamed_35 = metal::uint3(2u) / metal::uint3(1u); + metal::float4 unnamed_36 = metal::float4(2.0) / metal::float4(1.0); + int unnamed_37 = 2 % 1; + uint unnamed_38 = 2u % 1u; + float unnamed_39 = metal::fmod(2.0, 1.0); + metal::int2 unnamed_40 = metal::int2(2) % metal::int2(1); + metal::uint3 unnamed_41 = metal::uint3(2u) % metal::uint3(1u); + metal::float4 unnamed_42 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); + metal::int2 unnamed_43 = metal::int2(2) + metal::int2(1); + metal::int2 unnamed_44 = metal::int2(2) + metal::int2(1); + metal::uint2 unnamed_45 = metal::uint2(2u) + metal::uint2(1u); + metal::uint2 unnamed_46 = metal::uint2(2u) + metal::uint2(1u); + metal::float2 unnamed_47 = metal::float2(2.0) + metal::float2(1.0); + metal::float2 unnamed_48 = metal::float2(2.0) + metal::float2(1.0); + metal::int2 unnamed_49 = metal::int2(2) - metal::int2(1); + metal::int2 unnamed_50 = metal::int2(2) - metal::int2(1); + metal::uint2 unnamed_51 = metal::uint2(2u) - metal::uint2(1u); + metal::uint2 unnamed_52 = metal::uint2(2u) - metal::uint2(1u); + metal::float2 unnamed_53 = metal::float2(2.0) - metal::float2(1.0); + metal::float2 unnamed_54 = metal::float2(2.0) - metal::float2(1.0); + metal::int2 unnamed_55 = metal::int2(2) * 1; + metal::int2 unnamed_56 = 2 * metal::int2(1); + metal::uint2 unnamed_57 = metal::uint2(2u) * 1u; + metal::uint2 unnamed_58 = 2u * metal::uint2(1u); + metal::float2 unnamed_59 = metal::float2(2.0) * 1.0; + metal::float2 unnamed_60 = 2.0 * metal::float2(1.0); + metal::int2 unnamed_61 = metal::int2(2) / metal::int2(1); + metal::int2 unnamed_62 = metal::int2(2) / metal::int2(1); + metal::uint2 unnamed_63 = metal::uint2(2u) / metal::uint2(1u); + metal::uint2 unnamed_64 = metal::uint2(2u) / metal::uint2(1u); + metal::float2 unnamed_65 = metal::float2(2.0) / metal::float2(1.0); + metal::float2 unnamed_66 = metal::float2(2.0) / metal::float2(1.0); + metal::int2 unnamed_67 = metal::int2(2) % metal::int2(1); + metal::int2 unnamed_68 = metal::int2(2) % metal::int2(1); + metal::uint2 unnamed_69 = metal::uint2(2u) % metal::uint2(1u); + metal::uint2 unnamed_70 = metal::uint2(2u) % metal::uint2(1u); + metal::float2 unnamed_71 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + metal::float2 unnamed_72 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + metal::float3x3 unnamed_73 = const_type_14_ + const_type_14_; + metal::float3x3 unnamed_74 = const_type_14_ - const_type_14_; + metal::float3x3 unnamed_75 = const_type_14_ * 1.0; + metal::float3x3 unnamed_76 = 2.0 * const_type_14_; + metal::float3 unnamed_77 = const_type_15_ * metal::float4(1.0); + metal::float4 unnamed_78 = metal::float3(2.0) * const_type_15_; + metal::float3x3 unnamed_79 = const_type_15_ * const_type_16_; } void bit( ) { - int unnamed_88 = ~1; - uint unnamed_89 = ~1u; - metal::int2 unnamed_90 = ~metal::int2(1); - metal::uint3 unnamed_91 = ~metal::uint3(1u); - int unnamed_92 = 2 | 1; - uint unnamed_93 = 2u | 1u; - metal::int2 unnamed_94 = metal::int2(2) | metal::int2(1); - metal::uint3 unnamed_95 = metal::uint3(2u) | metal::uint3(1u); - int unnamed_96 = 2 & 1; - uint unnamed_97 = 2u & 1u; - metal::int2 unnamed_98 = metal::int2(2) & metal::int2(1); - metal::uint3 unnamed_99 = metal::uint3(2u) & metal::uint3(1u); - int unnamed_100 = 2 ^ 1; - uint unnamed_101 = 2u ^ 1u; - metal::int2 unnamed_102 = metal::int2(2) ^ metal::int2(1); - metal::uint3 unnamed_103 = metal::uint3(2u) ^ metal::uint3(1u); - int unnamed_104 = 2 << 1u; - uint unnamed_105 = 2u << 1u; - metal::int2 unnamed_106 = metal::int2(2) << metal::uint2(1u); - metal::uint3 unnamed_107 = metal::uint3(2u) << metal::uint3(1u); - int unnamed_108 = 2 >> 1u; - uint unnamed_109 = 2u >> 1u; - metal::int2 unnamed_110 = metal::int2(2) >> metal::uint2(1u); - metal::uint3 unnamed_111 = metal::uint3(2u) >> metal::uint3(1u); + int unnamed_80 = ~1; + uint unnamed_81 = ~1u; + metal::int2 unnamed_82 = ~metal::int2(1); + metal::uint3 unnamed_83 = ~metal::uint3(1u); + int unnamed_84 = 2 | 1; + uint unnamed_85 = 2u | 1u; + metal::int2 unnamed_86 = metal::int2(2) | metal::int2(1); + metal::uint3 unnamed_87 = metal::uint3(2u) | metal::uint3(1u); + int unnamed_88 = 2 & 1; + uint unnamed_89 = 2u & 1u; + metal::int2 unnamed_90 = metal::int2(2) & metal::int2(1); + metal::uint3 unnamed_91 = metal::uint3(2u) & metal::uint3(1u); + int unnamed_92 = 2 ^ 1; + uint unnamed_93 = 2u ^ 1u; + metal::int2 unnamed_94 = metal::int2(2) ^ metal::int2(1); + metal::uint3 unnamed_95 = metal::uint3(2u) ^ metal::uint3(1u); + int unnamed_96 = 2 << 1u; + uint unnamed_97 = 2u << 1u; + metal::int2 unnamed_98 = metal::int2(2) << metal::uint2(1u); + metal::uint3 unnamed_99 = metal::uint3(2u) << metal::uint3(1u); + int unnamed_100 = 2 >> 1u; + uint unnamed_101 = 2u >> 1u; + metal::int2 unnamed_102 = metal::int2(2) >> metal::uint2(1u); + metal::uint3 unnamed_103 = metal::uint3(2u) >> metal::uint3(1u); } void comparison( ) { - bool unnamed_112 = 2 == 1; - bool unnamed_113 = 2u == 1u; - bool unnamed_114 = 2.0 == 1.0; - metal::bool2 unnamed_115 = metal::int2(2) == metal::int2(1); - metal::bool3 unnamed_116 = metal::uint3(2u) == metal::uint3(1u); - metal::bool4 unnamed_117 = metal::float4(2.0) == metal::float4(1.0); - bool unnamed_118 = 2 != 1; - bool unnamed_119 = 2u != 1u; - bool unnamed_120 = 2.0 != 1.0; - metal::bool2 unnamed_121 = metal::int2(2) != metal::int2(1); - metal::bool3 unnamed_122 = metal::uint3(2u) != metal::uint3(1u); - metal::bool4 unnamed_123 = metal::float4(2.0) != metal::float4(1.0); - bool unnamed_124 = 2 < 1; - bool unnamed_125 = 2u < 1u; - bool unnamed_126 = 2.0 < 1.0; - metal::bool2 unnamed_127 = metal::int2(2) < metal::int2(1); - metal::bool3 unnamed_128 = metal::uint3(2u) < metal::uint3(1u); - metal::bool4 unnamed_129 = metal::float4(2.0) < metal::float4(1.0); - bool unnamed_130 = 2 <= 1; - bool unnamed_131 = 2u <= 1u; - bool unnamed_132 = 2.0 <= 1.0; - metal::bool2 unnamed_133 = metal::int2(2) <= metal::int2(1); - metal::bool3 unnamed_134 = metal::uint3(2u) <= metal::uint3(1u); - metal::bool4 unnamed_135 = metal::float4(2.0) <= metal::float4(1.0); - bool unnamed_136 = 2 > 1; - bool unnamed_137 = 2u > 1u; - bool unnamed_138 = 2.0 > 1.0; - metal::bool2 unnamed_139 = metal::int2(2) > metal::int2(1); - metal::bool3 unnamed_140 = metal::uint3(2u) > metal::uint3(1u); - metal::bool4 unnamed_141 = metal::float4(2.0) > metal::float4(1.0); - bool unnamed_142 = 2 >= 1; - bool unnamed_143 = 2u >= 1u; - bool unnamed_144 = 2.0 >= 1.0; - metal::bool2 unnamed_145 = metal::int2(2) >= metal::int2(1); - metal::bool3 unnamed_146 = metal::uint3(2u) >= metal::uint3(1u); - metal::bool4 unnamed_147 = metal::float4(2.0) >= metal::float4(1.0); + bool unnamed_104 = 2 == 1; + bool unnamed_105 = 2u == 1u; + bool unnamed_106 = 2.0 == 1.0; + metal::bool2 unnamed_107 = metal::int2(2) == metal::int2(1); + metal::bool3 unnamed_108 = metal::uint3(2u) == metal::uint3(1u); + metal::bool4 unnamed_109 = metal::float4(2.0) == metal::float4(1.0); + bool unnamed_110 = 2 != 1; + bool unnamed_111 = 2u != 1u; + bool unnamed_112 = 2.0 != 1.0; + metal::bool2 unnamed_113 = metal::int2(2) != metal::int2(1); + metal::bool3 unnamed_114 = metal::uint3(2u) != metal::uint3(1u); + metal::bool4 unnamed_115 = metal::float4(2.0) != metal::float4(1.0); + bool unnamed_116 = 2 < 1; + bool unnamed_117 = 2u < 1u; + bool unnamed_118 = 2.0 < 1.0; + metal::bool2 unnamed_119 = metal::int2(2) < metal::int2(1); + metal::bool3 unnamed_120 = metal::uint3(2u) < metal::uint3(1u); + metal::bool4 unnamed_121 = metal::float4(2.0) < metal::float4(1.0); + bool unnamed_122 = 2 <= 1; + bool unnamed_123 = 2u <= 1u; + bool unnamed_124 = 2.0 <= 1.0; + metal::bool2 unnamed_125 = metal::int2(2) <= metal::int2(1); + metal::bool3 unnamed_126 = metal::uint3(2u) <= metal::uint3(1u); + metal::bool4 unnamed_127 = metal::float4(2.0) <= metal::float4(1.0); + bool unnamed_128 = 2 > 1; + bool unnamed_129 = 2u > 1u; + bool unnamed_130 = 2.0 > 1.0; + metal::bool2 unnamed_131 = metal::int2(2) > metal::int2(1); + metal::bool3 unnamed_132 = metal::uint3(2u) > metal::uint3(1u); + metal::bool4 unnamed_133 = metal::float4(2.0) > metal::float4(1.0); + bool unnamed_134 = 2 >= 1; + bool unnamed_135 = 2u >= 1u; + bool unnamed_136 = 2.0 >= 1.0; + metal::bool2 unnamed_137 = metal::int2(2) >= metal::int2(1); + metal::bool3 unnamed_138 = metal::uint3(2u) >= metal::uint3(1u); + metal::bool4 unnamed_139 = metal::float4(2.0) >= metal::float4(1.0); } void assignment( diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index a50474190..fa5c64395 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 227 +; Bound: 218 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %150 "foo_vert" %145 %148 -OpEntryPoint Fragment %187 "foo_frag" %186 -OpEntryPoint GLCompute %204 "atomics" -OpExecutionMode %187 OriginUpperLeft -OpExecutionMode %204 LocalSize 1 1 1 +OpEntryPoint Vertex %141 "foo_vert" %136 %139 +OpEntryPoint Fragment %178 "foo_frag" %177 +OpEntryPoint GLCompute %195 "atomics" +OpExecutionMode %178 OriginUpperLeft +OpExecutionMode %195 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %32 0 "value" OpName %32 "AlignedWrapper" @@ -25,27 +25,19 @@ OpName %43 "Baz" OpName %52 "bar" OpName %54 "baz" OpName %57 "idx" -OpName %59 "_" -OpName %61 "_" -OpName %63 "_" -OpName %64 "_" -OpName %65 "_" -OpName %66 "_" -OpName %67 "_" -OpName %68 "t" -OpName %71 "test_matrix_within_struct_accesses" -OpName %128 "foo" -OpName %129 "read_from_private" -OpName %134 "a" -OpName %135 "test_arr_as_arg" -OpName %140 "foo" -OpName %141 "c" -OpName %143 "_" -OpName %145 "vi" -OpName %150 "foo_vert" -OpName %187 "foo_frag" -OpName %202 "tmp" -OpName %204 "atomics" +OpName %59 "t" +OpName %62 "test_matrix_within_struct_accesses" +OpName %120 "foo" +OpName %121 "read_from_private" +OpName %126 "a" +OpName %127 "test_arr_as_arg" +OpName %132 "foo" +OpName %133 "c" +OpName %136 "vi" +OpName %141 "foo_vert" +OpName %178 "foo_frag" +OpName %193 "tmp" +OpName %195 "atomics" OpMemberDecorate %32 0 Offset 0 OpDecorate %37 ArrayStride 16 OpDecorate %39 ArrayStride 8 @@ -72,9 +64,9 @@ OpDecorate %54 DescriptorSet 0 OpDecorate %54 Binding 1 OpDecorate %55 Block OpMemberDecorate %55 0 Offset 0 -OpDecorate %145 BuiltIn VertexIndex -OpDecorate %148 BuiltIn Position -OpDecorate %186 Location 0 +OpDecorate %136 BuiltIn VertexIndex +OpDecorate %139 BuiltIn Position +OpDecorate %177 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -131,226 +123,209 @@ OpDecorate %186 Location 0 %56 = OpTypePointer Uniform %55 %54 = OpVariable %56 Uniform %58 = OpTypePointer Function %4 -%60 = OpTypePointer Function %42 -%62 = OpTypePointer Function %36 -%69 = OpTypePointer Function %43 -%72 = OpTypeFunction %2 -%73 = OpTypePointer Uniform %43 -%78 = OpTypePointer Uniform %42 -%81 = OpTypePointer Uniform %36 -%87 = OpTypePointer Uniform %9 -%112 = OpTypePointer Function %36 -%118 = OpTypePointer Function %9 -%130 = OpTypeFunction %9 %44 -%136 = OpTypeFunction %9 %46 -%142 = OpTypePointer Function %49 -%146 = OpTypePointer Input %26 -%145 = OpVariable %146 Input -%149 = OpTypePointer Output %47 -%148 = OpVariable %149 Output -%155 = OpTypePointer StorageBuffer %33 -%158 = OpTypePointer StorageBuffer %39 -%161 = OpTypePointer StorageBuffer %34 -%162 = OpTypePointer StorageBuffer %9 -%165 = OpTypePointer StorageBuffer %40 -%168 = OpTypePointer StorageBuffer %32 -%169 = OpConstant %26 4 -%180 = OpTypeVector %4 4 -%186 = OpVariable %149 Output -%206 = OpTypePointer StorageBuffer %4 -%209 = OpConstant %26 64 -%71 = OpFunction %2 None %72 -%70 = OpLabel -%66 = OpVariable %44 Function -%63 = OpVariable %62 Function +%60 = OpTypePointer Function %43 +%63 = OpTypeFunction %2 +%64 = OpTypePointer Uniform %43 +%69 = OpTypePointer Uniform %42 +%72 = OpTypePointer Uniform %36 +%78 = OpTypePointer Uniform %9 +%98 = OpTypePointer Function %42 +%104 = OpTypePointer Function %36 +%110 = OpTypePointer Function %9 +%122 = OpTypeFunction %9 %44 +%128 = OpTypeFunction %9 %46 +%134 = OpTypePointer Function %49 +%137 = OpTypePointer Input %26 +%136 = OpVariable %137 Input +%140 = OpTypePointer Output %47 +%139 = OpVariable %140 Output +%146 = OpTypePointer StorageBuffer %33 +%149 = OpTypePointer StorageBuffer %39 +%152 = OpTypePointer StorageBuffer %34 +%153 = OpTypePointer StorageBuffer %9 +%156 = OpTypePointer StorageBuffer %40 +%159 = OpTypePointer StorageBuffer %32 +%160 = OpConstant %26 4 +%171 = OpTypeVector %4 4 +%177 = OpVariable %140 Output +%197 = OpTypePointer StorageBuffer %4 +%200 = OpConstant %26 64 +%62 = OpFunction %2 None %63 +%61 = OpLabel %57 = OpVariable %58 Function %5 -%67 = OpVariable %44 Function -%64 = OpVariable %44 Function %59 = OpVariable %60 Function -%68 = OpVariable %69 Function -%65 = OpVariable %44 Function -%61 = OpVariable %62 Function -%74 = OpAccessChain %73 %54 %31 -OpBranch %75 -%75 = OpLabel -%76 = OpLoad %4 %57 -%77 = OpISub %4 %76 %6 -OpStore %57 %77 -%79 = OpAccessChain %78 %74 %31 -%80 = OpLoad %42 %79 -OpStore %59 %80 -%82 = OpAccessChain %81 %74 %31 %31 -%83 = OpLoad %36 %82 -OpStore %61 %83 +%65 = OpAccessChain %64 %54 %31 +OpBranch %66 +%66 = OpLabel +%67 = OpLoad %4 %57 +%68 = OpISub %4 %67 %6 +OpStore %57 %68 +%70 = OpAccessChain %69 %65 %31 +%71 = OpLoad %42 %70 +%73 = OpAccessChain %72 %65 %31 %31 +%74 = OpLoad %36 %73 +%75 = OpLoad %4 %57 +%76 = OpAccessChain %72 %65 %31 %75 +%77 = OpLoad %36 %76 +%79 = OpAccessChain %78 %65 %31 %31 %29 +%80 = OpLoad %9 %79 +%81 = OpLoad %4 %57 +%82 = OpAccessChain %78 %65 %31 %31 %81 +%83 = OpLoad %9 %82 %84 = OpLoad %4 %57 -%85 = OpAccessChain %81 %74 %31 %84 -%86 = OpLoad %36 %85 -OpStore %63 %86 -%88 = OpAccessChain %87 %74 %31 %31 %29 -%89 = OpLoad %9 %88 -OpStore %64 %89 -%90 = OpLoad %4 %57 -%91 = OpAccessChain %87 %74 %31 %31 %90 -%92 = OpLoad %9 %91 -OpStore %65 %92 -%93 = OpLoad %4 %57 -%94 = OpAccessChain %87 %74 %31 %93 %29 -%95 = OpLoad %9 %94 -OpStore %66 %95 +%85 = OpAccessChain %78 %65 %31 %84 %29 +%86 = OpLoad %9 %85 +%87 = OpLoad %4 %57 +%88 = OpLoad %4 %57 +%89 = OpAccessChain %78 %65 %31 %87 %88 +%90 = OpLoad %9 %89 +%91 = OpCompositeConstruct %36 %8 %8 +%92 = OpCompositeConstruct %36 %10 %10 +%93 = OpCompositeConstruct %36 %11 %11 +%94 = OpCompositeConstruct %42 %91 %92 %93 +%95 = OpCompositeConstruct %43 %94 +OpStore %59 %95 %96 = OpLoad %4 %57 -%97 = OpLoad %4 %57 -%98 = OpAccessChain %87 %74 %31 %96 %97 -%99 = OpLoad %9 %98 -OpStore %67 %99 -%100 = OpCompositeConstruct %36 %8 %8 -%101 = OpCompositeConstruct %36 %10 %10 -%102 = OpCompositeConstruct %36 %11 %11 -%103 = OpCompositeConstruct %42 %100 %101 %102 -%104 = OpCompositeConstruct %43 %103 -OpStore %68 %104 -%105 = OpLoad %4 %57 -%106 = OpIAdd %4 %105 %6 -OpStore %57 %106 -%107 = OpCompositeConstruct %36 %12 %12 -%108 = OpCompositeConstruct %36 %13 %13 -%109 = OpCompositeConstruct %36 %14 %14 -%110 = OpCompositeConstruct %42 %107 %108 %109 -%111 = OpAccessChain %60 %68 %31 -OpStore %111 %110 -%113 = OpCompositeConstruct %36 %15 %15 -%114 = OpAccessChain %112 %68 %31 %31 -OpStore %114 %113 -%115 = OpLoad %4 %57 -%116 = OpCompositeConstruct %36 %16 %16 -%117 = OpAccessChain %112 %68 %31 %115 -OpStore %117 %116 -%119 = OpAccessChain %118 %68 %31 %31 %29 -OpStore %119 %17 -%120 = OpLoad %4 %57 -%121 = OpAccessChain %118 %68 %31 %31 %120 -OpStore %121 %18 -%122 = OpLoad %4 %57 -%123 = OpAccessChain %118 %68 %31 %122 %29 -OpStore %123 %19 -%124 = OpLoad %4 %57 -%125 = OpLoad %4 %57 -%126 = OpAccessChain %118 %68 %31 %124 %125 -OpStore %126 %20 +%97 = OpIAdd %4 %96 %6 +OpStore %57 %97 +%99 = OpCompositeConstruct %36 %12 %12 +%100 = OpCompositeConstruct %36 %13 %13 +%101 = OpCompositeConstruct %36 %14 %14 +%102 = OpCompositeConstruct %42 %99 %100 %101 +%103 = OpAccessChain %98 %59 %31 +OpStore %103 %102 +%105 = OpCompositeConstruct %36 %15 %15 +%106 = OpAccessChain %104 %59 %31 %31 +OpStore %106 %105 +%107 = OpLoad %4 %57 +%108 = OpCompositeConstruct %36 %16 %16 +%109 = OpAccessChain %104 %59 %31 %107 +OpStore %109 %108 +%111 = OpAccessChain %110 %59 %31 %31 %29 +OpStore %111 %17 +%112 = OpLoad %4 %57 +%113 = OpAccessChain %110 %59 %31 %31 %112 +OpStore %113 %18 +%114 = OpLoad %4 %57 +%115 = OpAccessChain %110 %59 %31 %114 %29 +OpStore %115 %19 +%116 = OpLoad %4 %57 +%117 = OpLoad %4 %57 +%118 = OpAccessChain %110 %59 %31 %116 %117 +OpStore %118 %20 OpReturn OpFunctionEnd -%129 = OpFunction %9 None %130 -%128 = OpFunctionParameter %44 -%127 = OpLabel -OpBranch %131 -%131 = OpLabel -%132 = OpLoad %9 %128 -OpReturnValue %132 +%121 = OpFunction %9 None %122 +%120 = OpFunctionParameter %44 +%119 = OpLabel +OpBranch %123 +%123 = OpLabel +%124 = OpLoad %9 %120 +OpReturnValue %124 OpFunctionEnd -%135 = OpFunction %9 None %136 -%134 = OpFunctionParameter %46 -%133 = OpLabel -OpBranch %137 -%137 = OpLabel -%138 = OpCompositeExtract %45 %134 4 -%139 = OpCompositeExtract %9 %138 9 -OpReturnValue %139 +%127 = OpFunction %9 None %128 +%126 = OpFunctionParameter %46 +%125 = OpLabel +OpBranch %129 +%129 = OpLabel +%130 = OpCompositeExtract %45 %126 4 +%131 = OpCompositeExtract %9 %130 9 +OpReturnValue %131 OpFunctionEnd -%150 = OpFunction %2 None %72 -%144 = OpLabel -%140 = OpVariable %44 Function %24 -%141 = OpVariable %142 Function -%143 = OpVariable %44 Function -%147 = OpLoad %26 %145 -%151 = OpAccessChain %73 %54 %31 -OpBranch %152 -%152 = OpLabel -%153 = OpLoad %9 %140 -OpStore %140 %8 -%154 = OpFunctionCall %2 %71 -%156 = OpAccessChain %155 %52 %31 -%157 = OpLoad %33 %156 -%159 = OpAccessChain %158 %52 %25 -%160 = OpLoad %39 %159 -%163 = OpAccessChain %162 %52 %31 %25 %31 -%164 = OpLoad %9 %163 -%166 = OpArrayLength %26 %52 4 -%167 = OpISub %26 %166 %27 -%170 = OpAccessChain %48 %52 %169 %167 %31 -%171 = OpLoad %4 %170 -%172 = OpFunctionCall %9 %129 %140 -%173 = OpConvertFToS %4 %164 -%174 = OpCompositeConstruct %49 %171 %173 %28 %23 %22 -OpStore %141 %174 -%175 = OpIAdd %26 %147 %29 -%176 = OpAccessChain %58 %141 %175 -OpStore %176 %30 -%177 = OpAccessChain %58 %141 %147 -%178 = OpLoad %4 %177 -%179 = OpFunctionCall %9 %135 %51 -OpStore %143 %179 -%181 = OpCompositeConstruct %180 %178 %178 %178 %178 -%182 = OpConvertSToF %47 %181 -%183 = OpMatrixTimesVector %34 %157 %182 -%184 = OpCompositeConstruct %47 %183 %10 -OpStore %148 %184 +%141 = OpFunction %2 None %63 +%135 = OpLabel +%132 = OpVariable %44 Function %24 +%133 = OpVariable %134 Function +%138 = OpLoad %26 %136 +%142 = OpAccessChain %64 %54 %31 +OpBranch %143 +%143 = OpLabel +%144 = OpLoad %9 %132 +OpStore %132 %8 +%145 = OpFunctionCall %2 %62 +%147 = OpAccessChain %146 %52 %31 +%148 = OpLoad %33 %147 +%150 = OpAccessChain %149 %52 %25 +%151 = OpLoad %39 %150 +%154 = OpAccessChain %153 %52 %31 %25 %31 +%155 = OpLoad %9 %154 +%157 = OpArrayLength %26 %52 4 +%158 = OpISub %26 %157 %27 +%161 = OpAccessChain %48 %52 %160 %158 %31 +%162 = OpLoad %4 %161 +%163 = OpFunctionCall %9 %121 %132 +%164 = OpConvertFToS %4 %155 +%165 = OpCompositeConstruct %49 %162 %164 %28 %23 %22 +OpStore %133 %165 +%166 = OpIAdd %26 %138 %29 +%167 = OpAccessChain %58 %133 %166 +OpStore %167 %30 +%168 = OpAccessChain %58 %133 %138 +%169 = OpLoad %4 %168 +%170 = OpFunctionCall %9 %127 %51 +%172 = OpCompositeConstruct %171 %169 %169 %169 %169 +%173 = OpConvertSToF %47 %172 +%174 = OpMatrixTimesVector %34 %148 %173 +%175 = OpCompositeConstruct %47 %174 %10 +OpStore %139 %175 OpReturn OpFunctionEnd -%187 = OpFunction %2 None %72 -%185 = OpLabel -OpBranch %188 -%188 = OpLabel -%189 = OpAccessChain %162 %52 %31 %29 %27 -OpStore %189 %8 -%190 = OpCompositeConstruct %34 %24 %24 %24 -%191 = OpCompositeConstruct %34 %8 %8 %8 -%192 = OpCompositeConstruct %34 %10 %10 %10 -%193 = OpCompositeConstruct %34 %11 %11 %11 -%194 = OpCompositeConstruct %33 %190 %191 %192 %193 -%195 = OpAccessChain %155 %52 %31 -OpStore %195 %194 -%196 = OpCompositeConstruct %38 %31 %31 -%197 = OpCompositeConstruct %38 %29 %29 -%198 = OpCompositeConstruct %39 %196 %197 -%199 = OpAccessChain %158 %52 %25 -OpStore %199 %198 -%200 = OpAccessChain %48 %52 %169 %29 %31 -OpStore %200 %6 -%201 = OpCompositeConstruct %47 %24 %24 %24 %24 -OpStore %186 %201 +%178 = OpFunction %2 None %63 +%176 = OpLabel +OpBranch %179 +%179 = OpLabel +%180 = OpAccessChain %153 %52 %31 %29 %27 +OpStore %180 %8 +%181 = OpCompositeConstruct %34 %24 %24 %24 +%182 = OpCompositeConstruct %34 %8 %8 %8 +%183 = OpCompositeConstruct %34 %10 %10 %10 +%184 = OpCompositeConstruct %34 %11 %11 %11 +%185 = OpCompositeConstruct %33 %181 %182 %183 %184 +%186 = OpAccessChain %146 %52 %31 +OpStore %186 %185 +%187 = OpCompositeConstruct %38 %31 %31 +%188 = OpCompositeConstruct %38 %29 %29 +%189 = OpCompositeConstruct %39 %187 %188 +%190 = OpAccessChain %149 %52 %25 +OpStore %190 %189 +%191 = OpAccessChain %48 %52 %160 %29 %31 +OpStore %191 %6 +%192 = OpCompositeConstruct %47 %24 %24 %24 %24 +OpStore %177 %192 OpReturn OpFunctionEnd -%204 = OpFunction %2 None %72 -%203 = OpLabel -%202 = OpVariable %58 Function -OpBranch %205 -%205 = OpLabel -%207 = OpAccessChain %206 %52 %27 -%208 = OpAtomicLoad %4 %207 %6 %209 -%211 = OpAccessChain %206 %52 %27 -%210 = OpAtomicIAdd %4 %211 %6 %209 %22 -OpStore %202 %210 -%213 = OpAccessChain %206 %52 %27 -%212 = OpAtomicISub %4 %213 %6 %209 %22 -OpStore %202 %212 -%215 = OpAccessChain %206 %52 %27 -%214 = OpAtomicAnd %4 %215 %6 %209 %22 -OpStore %202 %214 -%217 = OpAccessChain %206 %52 %27 -%216 = OpAtomicOr %4 %217 %6 %209 %22 -OpStore %202 %216 -%219 = OpAccessChain %206 %52 %27 -%218 = OpAtomicXor %4 %219 %6 %209 %22 -OpStore %202 %218 -%221 = OpAccessChain %206 %52 %27 -%220 = OpAtomicSMin %4 %221 %6 %209 %22 -OpStore %202 %220 -%223 = OpAccessChain %206 %52 %27 -%222 = OpAtomicSMax %4 %223 %6 %209 %22 -OpStore %202 %222 -%225 = OpAccessChain %206 %52 %27 -%224 = OpAtomicExchange %4 %225 %6 %209 %22 -OpStore %202 %224 -%226 = OpAccessChain %206 %52 %27 -OpAtomicStore %226 %6 %209 %208 +%195 = OpFunction %2 None %63 +%194 = OpLabel +%193 = OpVariable %58 Function +OpBranch %196 +%196 = OpLabel +%198 = OpAccessChain %197 %52 %27 +%199 = OpAtomicLoad %4 %198 %6 %200 +%202 = OpAccessChain %197 %52 %27 +%201 = OpAtomicIAdd %4 %202 %6 %200 %22 +OpStore %193 %201 +%204 = OpAccessChain %197 %52 %27 +%203 = OpAtomicISub %4 %204 %6 %200 %22 +OpStore %193 %203 +%206 = OpAccessChain %197 %52 %27 +%205 = OpAtomicAnd %4 %206 %6 %200 %22 +OpStore %193 %205 +%208 = OpAccessChain %197 %52 %27 +%207 = OpAtomicOr %4 %208 %6 %200 %22 +OpStore %193 %207 +%210 = OpAccessChain %197 %52 %27 +%209 = OpAtomicXor %4 %210 %6 %200 %22 +OpStore %193 %209 +%212 = OpAccessChain %197 %52 %27 +%211 = OpAtomicSMin %4 %212 %6 %200 %22 +OpStore %193 %211 +%214 = OpAccessChain %197 %52 %27 +%213 = OpAtomicSMax %4 %214 %6 %200 %22 +OpStore %193 %213 +%216 = OpAccessChain %197 %52 %27 +%215 = OpAtomicExchange %4 %216 %6 %200 %22 +OpStore %193 %215 +%217 = OpAccessChain %197 %52 %27 +OpAtomicStore %217 %6 %200 %199 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 8801c2f24..8de46ea3d 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 519 +; Bound: 501 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %507 "main" -OpExecutionMode %507 LocalSize 1 1 1 +OpEntryPoint GLCompute %489 "main" +OpExecutionMode %489 LocalSize 1 1 1 OpMemberDecorate %30 0 Offset 0 OpMemberDecorate %30 1 Offset 16 OpDecorate %35 ArrayStride 32 @@ -67,21 +67,14 @@ OpDecorate %36 ArrayStride 4 %98 = OpTypeFunction %29 %29 %100 = OpTypeVector %10 3 %107 = OpTypePointer Function %30 -%109 = OpTypePointer Function %10 -%111 = OpTypePointer Function %8 -%113 = OpTypePointer Function %20 -%115 = OpTypePointer Function %4 -%117 = OpTypePointer Function %34 -%119 = OpTypePointer Function %32 -%121 = OpTypePointer Function %35 -%126 = OpTypePointer Function %36 -%129 = OpTypeFunction %4 -%146 = OpTypePointer Function %26 -%147 = OpTypePointer Function %4 -%152 = OpTypeFunction %2 -%155 = OpTypeVector %10 2 -%171 = OpTypeVector %8 2 -%182 = OpTypeVector %20 3 +%110 = OpTypeFunction %4 +%127 = OpTypePointer Function %26 +%128 = OpTypePointer Function %4 +%133 = OpTypeFunction %2 +%136 = OpTypeVector %10 2 +%152 = OpTypeVector %8 2 +%163 = OpTypeVector %20 3 +%458 = OpTypePointer Function %8 %55 = OpFunction %26 None %56 %54 = OpLabel OpBranch %57 @@ -140,437 +133,423 @@ OpBranch %99 %105 = OpSelect %29 %102 %104 %103 OpReturnValue %105 OpFunctionEnd -%128 = OpFunction %4 None %129 -%127 = OpLabel -%123 = OpVariable %117 Function -%118 = OpVariable %119 Function %46 -%112 = OpVariable %113 Function %19 +%109 = OpFunction %4 None %110 +%108 = OpLabel %106 = OpVariable %107 Function -%124 = OpVariable %119 Function -%120 = OpVariable %121 Function %49 -%114 = OpVariable %115 Function %5 -%108 = OpVariable %109 Function %12 -%125 = OpVariable %126 Function -%122 = OpVariable %107 Function %48 -%116 = OpVariable %117 Function %44 -%110 = OpVariable %111 Function %11 -OpBranch %130 -%130 = OpLabel -%131 = OpCompositeConstruct %26 %3 %3 %3 %3 -%132 = OpCompositeConstruct %30 %131 %7 -OpStore %106 %132 -%133 = OpCompositeConstruct %31 %3 %5 -%134 = OpCompositeConstruct %31 %5 %3 -%135 = OpCompositeConstruct %32 %133 %134 -%136 = OpCompositeConstruct %26 %3 %5 %5 %5 -%137 = OpCompositeConstruct %26 %5 %3 %5 %5 -%138 = OpCompositeConstruct %26 %5 %5 %3 %5 -%139 = OpCompositeConstruct %26 %5 %5 %5 %3 -%140 = OpCompositeConstruct %33 %136 %137 %138 %139 -%141 = OpCompositeConstruct %34 %19 %19 -OpStore %123 %141 -%142 = OpCompositeConstruct %31 %5 %5 -%143 = OpCompositeConstruct %31 %5 %5 -%144 = OpCompositeConstruct %32 %142 %143 -OpStore %124 %144 -%145 = OpCompositeConstruct %36 %11 %7 %18 %21 -OpStore %125 %145 -%148 = OpAccessChain %147 %106 %19 %19 -%149 = OpLoad %4 %148 -OpReturnValue %149 +OpBranch %111 +%111 = OpLabel +%112 = OpCompositeConstruct %26 %3 %3 %3 %3 +%113 = OpCompositeConstruct %30 %112 %7 +OpStore %106 %113 +%114 = OpCompositeConstruct %31 %3 %5 +%115 = OpCompositeConstruct %31 %5 %3 +%116 = OpCompositeConstruct %32 %114 %115 +%117 = OpCompositeConstruct %26 %3 %5 %5 %5 +%118 = OpCompositeConstruct %26 %5 %3 %5 %5 +%119 = OpCompositeConstruct %26 %5 %5 %3 %5 +%120 = OpCompositeConstruct %26 %5 %5 %5 %3 +%121 = OpCompositeConstruct %33 %117 %118 %119 %120 +%122 = OpCompositeConstruct %34 %19 %19 +%123 = OpCompositeConstruct %31 %5 %5 +%124 = OpCompositeConstruct %31 %5 %5 +%125 = OpCompositeConstruct %32 %123 %124 +%126 = OpCompositeConstruct %36 %11 %7 %18 %21 +%129 = OpAccessChain %128 %106 %19 %19 +%130 = OpLoad %4 %129 +OpReturnValue %130 OpFunctionEnd -%151 = OpFunction %2 None %152 -%150 = OpLabel -OpBranch %153 -%153 = OpLabel -%154 = OpLogicalNot %10 %9 -%156 = OpCompositeConstruct %155 %9 %9 -%157 = OpLogicalNot %155 %156 -%158 = OpLogicalOr %10 %9 %12 -%159 = OpLogicalAnd %10 %9 %12 -%160 = OpLogicalOr %10 %9 %12 -%161 = OpCompositeConstruct %100 %9 %9 %9 -%162 = OpCompositeConstruct %100 %12 %12 %12 -%163 = OpLogicalOr %100 %161 %162 -%164 = OpLogicalAnd %10 %9 %12 -%165 = OpCompositeConstruct %28 %9 %9 %9 %9 -%166 = OpCompositeConstruct %28 %12 %12 %12 %12 -%167 = OpLogicalAnd %28 %165 %166 +%132 = OpFunction %2 None %133 +%131 = OpLabel +OpBranch %134 +%134 = OpLabel +%135 = OpLogicalNot %10 %9 +%137 = OpCompositeConstruct %136 %9 %9 +%138 = OpLogicalNot %136 %137 +%139 = OpLogicalOr %10 %9 %12 +%140 = OpLogicalAnd %10 %9 %12 +%141 = OpLogicalOr %10 %9 %12 +%142 = OpCompositeConstruct %100 %9 %9 %9 +%143 = OpCompositeConstruct %100 %12 %12 %12 +%144 = OpLogicalOr %100 %142 %143 +%145 = OpLogicalAnd %10 %9 %12 +%146 = OpCompositeConstruct %28 %9 %9 %9 %9 +%147 = OpCompositeConstruct %28 %12 %12 %12 %12 +%148 = OpLogicalAnd %28 %146 %147 OpReturn OpFunctionEnd -%169 = OpFunction %2 None %152 -%168 = OpLabel -OpBranch %170 -%170 = OpLabel -%172 = OpCompositeConstruct %171 %7 %7 -%173 = OpSNegate %171 %172 -%174 = OpCompositeConstruct %31 %3 %3 -%175 = OpFNegate %31 %174 -%176 = OpIAdd %8 %18 %7 -%177 = OpIAdd %20 %24 %25 -%178 = OpFAdd %4 %14 %3 -%179 = OpCompositeConstruct %171 %18 %18 -%180 = OpCompositeConstruct %171 %7 %7 -%181 = OpIAdd %171 %179 %180 -%183 = OpCompositeConstruct %182 %24 %24 %24 -%184 = OpCompositeConstruct %182 %25 %25 %25 -%185 = OpIAdd %182 %183 %184 -%186 = OpCompositeConstruct %26 %14 %14 %14 %14 -%187 = OpCompositeConstruct %26 %3 %3 %3 %3 -%188 = OpFAdd %26 %186 %187 -%189 = OpISub %8 %18 %7 -%190 = OpISub %20 %24 %25 -%191 = OpFSub %4 %14 %3 -%192 = OpCompositeConstruct %171 %18 %18 -%193 = OpCompositeConstruct %171 %7 %7 -%194 = OpISub %171 %192 %193 -%195 = OpCompositeConstruct %182 %24 %24 %24 -%196 = OpCompositeConstruct %182 %25 %25 %25 -%197 = OpISub %182 %195 %196 -%198 = OpCompositeConstruct %26 %14 %14 %14 %14 -%199 = OpCompositeConstruct %26 %3 %3 %3 %3 -%200 = OpFSub %26 %198 %199 -%201 = OpIMul %8 %18 %7 -%202 = OpIMul %20 %24 %25 -%203 = OpFMul %4 %14 %3 -%204 = OpCompositeConstruct %171 %18 %18 -%205 = OpCompositeConstruct %171 %7 %7 -%206 = OpIMul %171 %204 %205 -%207 = OpCompositeConstruct %182 %24 %24 %24 -%208 = OpCompositeConstruct %182 %25 %25 %25 -%209 = OpIMul %182 %207 %208 -%210 = OpCompositeConstruct %26 %14 %14 %14 %14 -%211 = OpCompositeConstruct %26 %3 %3 %3 %3 -%212 = OpFMul %26 %210 %211 -%213 = OpSDiv %8 %18 %7 -%214 = OpUDiv %20 %24 %25 -%215 = OpFDiv %4 %14 %3 -%216 = OpCompositeConstruct %171 %18 %18 -%217 = OpCompositeConstruct %171 %7 %7 -%218 = OpSDiv %171 %216 %217 -%219 = OpCompositeConstruct %182 %24 %24 %24 -%220 = OpCompositeConstruct %182 %25 %25 %25 -%221 = OpUDiv %182 %219 %220 -%222 = OpCompositeConstruct %26 %14 %14 %14 %14 -%223 = OpCompositeConstruct %26 %3 %3 %3 %3 -%224 = OpFDiv %26 %222 %223 -%225 = OpSMod %8 %18 %7 -%226 = OpUMod %20 %24 %25 -%227 = OpFRem %4 %14 %3 -%228 = OpCompositeConstruct %171 %18 %18 -%229 = OpCompositeConstruct %171 %7 %7 -%230 = OpSMod %171 %228 %229 -%231 = OpCompositeConstruct %182 %24 %24 %24 -%232 = OpCompositeConstruct %182 %25 %25 %25 -%233 = OpUMod %182 %231 %232 -%234 = OpCompositeConstruct %26 %14 %14 %14 %14 -%235 = OpCompositeConstruct %26 %3 %3 %3 %3 -%236 = OpFRem %26 %234 %235 -%237 = OpCompositeConstruct %171 %18 %18 -%238 = OpCompositeConstruct %171 %7 %7 -%239 = OpIAdd %171 %237 %238 -%240 = OpCompositeConstruct %171 %7 %7 -%241 = OpCompositeConstruct %171 %18 %18 -%242 = OpIAdd %171 %241 %240 -%243 = OpCompositeConstruct %34 %24 %24 -%244 = OpCompositeConstruct %34 %25 %25 -%245 = OpIAdd %34 %243 %244 -%246 = OpCompositeConstruct %34 %25 %25 -%247 = OpCompositeConstruct %34 %24 %24 -%248 = OpIAdd %34 %247 %246 -%249 = OpCompositeConstruct %31 %14 %14 -%250 = OpCompositeConstruct %31 %3 %3 -%251 = OpFAdd %31 %249 %250 -%252 = OpCompositeConstruct %31 %3 %3 -%253 = OpCompositeConstruct %31 %14 %14 -%254 = OpFAdd %31 %253 %252 -%255 = OpCompositeConstruct %171 %18 %18 -%256 = OpCompositeConstruct %171 %7 %7 -%257 = OpISub %171 %255 %256 -%258 = OpCompositeConstruct %171 %7 %7 -%259 = OpCompositeConstruct %171 %18 %18 -%260 = OpISub %171 %259 %258 -%261 = OpCompositeConstruct %34 %24 %24 +%150 = OpFunction %2 None %133 +%149 = OpLabel +OpBranch %151 +%151 = OpLabel +%153 = OpCompositeConstruct %152 %7 %7 +%154 = OpSNegate %152 %153 +%155 = OpCompositeConstruct %31 %3 %3 +%156 = OpFNegate %31 %155 +%157 = OpIAdd %8 %18 %7 +%158 = OpIAdd %20 %24 %25 +%159 = OpFAdd %4 %14 %3 +%160 = OpCompositeConstruct %152 %18 %18 +%161 = OpCompositeConstruct %152 %7 %7 +%162 = OpIAdd %152 %160 %161 +%164 = OpCompositeConstruct %163 %24 %24 %24 +%165 = OpCompositeConstruct %163 %25 %25 %25 +%166 = OpIAdd %163 %164 %165 +%167 = OpCompositeConstruct %26 %14 %14 %14 %14 +%168 = OpCompositeConstruct %26 %3 %3 %3 %3 +%169 = OpFAdd %26 %167 %168 +%170 = OpISub %8 %18 %7 +%171 = OpISub %20 %24 %25 +%172 = OpFSub %4 %14 %3 +%173 = OpCompositeConstruct %152 %18 %18 +%174 = OpCompositeConstruct %152 %7 %7 +%175 = OpISub %152 %173 %174 +%176 = OpCompositeConstruct %163 %24 %24 %24 +%177 = OpCompositeConstruct %163 %25 %25 %25 +%178 = OpISub %163 %176 %177 +%179 = OpCompositeConstruct %26 %14 %14 %14 %14 +%180 = OpCompositeConstruct %26 %3 %3 %3 %3 +%181 = OpFSub %26 %179 %180 +%182 = OpIMul %8 %18 %7 +%183 = OpIMul %20 %24 %25 +%184 = OpFMul %4 %14 %3 +%185 = OpCompositeConstruct %152 %18 %18 +%186 = OpCompositeConstruct %152 %7 %7 +%187 = OpIMul %152 %185 %186 +%188 = OpCompositeConstruct %163 %24 %24 %24 +%189 = OpCompositeConstruct %163 %25 %25 %25 +%190 = OpIMul %163 %188 %189 +%191 = OpCompositeConstruct %26 %14 %14 %14 %14 +%192 = OpCompositeConstruct %26 %3 %3 %3 %3 +%193 = OpFMul %26 %191 %192 +%194 = OpSDiv %8 %18 %7 +%195 = OpUDiv %20 %24 %25 +%196 = OpFDiv %4 %14 %3 +%197 = OpCompositeConstruct %152 %18 %18 +%198 = OpCompositeConstruct %152 %7 %7 +%199 = OpSDiv %152 %197 %198 +%200 = OpCompositeConstruct %163 %24 %24 %24 +%201 = OpCompositeConstruct %163 %25 %25 %25 +%202 = OpUDiv %163 %200 %201 +%203 = OpCompositeConstruct %26 %14 %14 %14 %14 +%204 = OpCompositeConstruct %26 %3 %3 %3 %3 +%205 = OpFDiv %26 %203 %204 +%206 = OpSMod %8 %18 %7 +%207 = OpUMod %20 %24 %25 +%208 = OpFRem %4 %14 %3 +%209 = OpCompositeConstruct %152 %18 %18 +%210 = OpCompositeConstruct %152 %7 %7 +%211 = OpSMod %152 %209 %210 +%212 = OpCompositeConstruct %163 %24 %24 %24 +%213 = OpCompositeConstruct %163 %25 %25 %25 +%214 = OpUMod %163 %212 %213 +%215 = OpCompositeConstruct %26 %14 %14 %14 %14 +%216 = OpCompositeConstruct %26 %3 %3 %3 %3 +%217 = OpFRem %26 %215 %216 +%218 = OpCompositeConstruct %152 %18 %18 +%219 = OpCompositeConstruct %152 %7 %7 +%220 = OpIAdd %152 %218 %219 +%221 = OpCompositeConstruct %152 %7 %7 +%222 = OpCompositeConstruct %152 %18 %18 +%223 = OpIAdd %152 %222 %221 +%224 = OpCompositeConstruct %34 %24 %24 +%225 = OpCompositeConstruct %34 %25 %25 +%226 = OpIAdd %34 %224 %225 +%227 = OpCompositeConstruct %34 %25 %25 +%228 = OpCompositeConstruct %34 %24 %24 +%229 = OpIAdd %34 %228 %227 +%230 = OpCompositeConstruct %31 %14 %14 +%231 = OpCompositeConstruct %31 %3 %3 +%232 = OpFAdd %31 %230 %231 +%233 = OpCompositeConstruct %31 %3 %3 +%234 = OpCompositeConstruct %31 %14 %14 +%235 = OpFAdd %31 %234 %233 +%236 = OpCompositeConstruct %152 %18 %18 +%237 = OpCompositeConstruct %152 %7 %7 +%238 = OpISub %152 %236 %237 +%239 = OpCompositeConstruct %152 %7 %7 +%240 = OpCompositeConstruct %152 %18 %18 +%241 = OpISub %152 %240 %239 +%242 = OpCompositeConstruct %34 %24 %24 +%243 = OpCompositeConstruct %34 %25 %25 +%244 = OpISub %34 %242 %243 +%245 = OpCompositeConstruct %34 %25 %25 +%246 = OpCompositeConstruct %34 %24 %24 +%247 = OpISub %34 %246 %245 +%248 = OpCompositeConstruct %31 %14 %14 +%249 = OpCompositeConstruct %31 %3 %3 +%250 = OpFSub %31 %248 %249 +%251 = OpCompositeConstruct %31 %3 %3 +%252 = OpCompositeConstruct %31 %14 %14 +%253 = OpFSub %31 %252 %251 +%254 = OpCompositeConstruct %152 %18 %18 +%256 = OpCompositeConstruct %152 %7 %7 +%255 = OpIMul %152 %254 %256 +%257 = OpCompositeConstruct %152 %7 %7 +%259 = OpCompositeConstruct %152 %18 %18 +%258 = OpIMul %152 %257 %259 +%260 = OpCompositeConstruct %34 %24 %24 %262 = OpCompositeConstruct %34 %25 %25 -%263 = OpISub %34 %261 %262 -%264 = OpCompositeConstruct %34 %25 %25 +%261 = OpIMul %34 %260 %262 +%263 = OpCompositeConstruct %34 %25 %25 %265 = OpCompositeConstruct %34 %24 %24 -%266 = OpISub %34 %265 %264 -%267 = OpCompositeConstruct %31 %14 %14 +%264 = OpIMul %34 %263 %265 +%266 = OpCompositeConstruct %31 %14 %14 +%267 = OpVectorTimesScalar %31 %266 %3 %268 = OpCompositeConstruct %31 %3 %3 -%269 = OpFSub %31 %267 %268 -%270 = OpCompositeConstruct %31 %3 %3 -%271 = OpCompositeConstruct %31 %14 %14 -%272 = OpFSub %31 %271 %270 -%273 = OpCompositeConstruct %171 %18 %18 -%275 = OpCompositeConstruct %171 %7 %7 -%274 = OpIMul %171 %273 %275 -%276 = OpCompositeConstruct %171 %7 %7 -%278 = OpCompositeConstruct %171 %18 %18 -%277 = OpIMul %171 %276 %278 -%279 = OpCompositeConstruct %34 %24 %24 -%281 = OpCompositeConstruct %34 %25 %25 -%280 = OpIMul %34 %279 %281 -%282 = OpCompositeConstruct %34 %25 %25 -%284 = OpCompositeConstruct %34 %24 %24 -%283 = OpIMul %34 %282 %284 -%285 = OpCompositeConstruct %31 %14 %14 -%286 = OpVectorTimesScalar %31 %285 %3 -%287 = OpCompositeConstruct %31 %3 %3 -%288 = OpVectorTimesScalar %31 %287 %14 -%289 = OpCompositeConstruct %171 %18 %18 -%290 = OpCompositeConstruct %171 %7 %7 -%291 = OpSDiv %171 %289 %290 -%292 = OpCompositeConstruct %171 %7 %7 -%293 = OpCompositeConstruct %171 %18 %18 -%294 = OpSDiv %171 %293 %292 -%295 = OpCompositeConstruct %34 %24 %24 -%296 = OpCompositeConstruct %34 %25 %25 -%297 = OpUDiv %34 %295 %296 -%298 = OpCompositeConstruct %34 %25 %25 -%299 = OpCompositeConstruct %34 %24 %24 -%300 = OpUDiv %34 %299 %298 -%301 = OpCompositeConstruct %31 %14 %14 -%302 = OpCompositeConstruct %31 %3 %3 -%303 = OpFDiv %31 %301 %302 -%304 = OpCompositeConstruct %31 %3 %3 -%305 = OpCompositeConstruct %31 %14 %14 -%306 = OpFDiv %31 %305 %304 -%307 = OpCompositeConstruct %171 %18 %18 -%308 = OpCompositeConstruct %171 %7 %7 -%309 = OpSMod %171 %307 %308 -%310 = OpCompositeConstruct %171 %7 %7 -%311 = OpCompositeConstruct %171 %18 %18 -%312 = OpSMod %171 %311 %310 -%313 = OpCompositeConstruct %34 %24 %24 -%314 = OpCompositeConstruct %34 %25 %25 -%315 = OpUMod %34 %313 %314 -%316 = OpCompositeConstruct %34 %25 %25 -%317 = OpCompositeConstruct %34 %24 %24 -%318 = OpUMod %34 %317 %316 -%319 = OpCompositeConstruct %31 %14 %14 -%320 = OpCompositeConstruct %31 %3 %3 -%321 = OpFRem %31 %319 %320 -%322 = OpCompositeConstruct %31 %3 %3 -%323 = OpCompositeConstruct %31 %14 %14 -%324 = OpFRem %31 %323 %322 -%326 = OpCompositeExtract %29 %51 0 -%327 = OpCompositeExtract %29 %51 0 -%328 = OpFAdd %29 %326 %327 -%329 = OpCompositeExtract %29 %51 1 -%330 = OpCompositeExtract %29 %51 1 -%331 = OpFAdd %29 %329 %330 -%332 = OpCompositeExtract %29 %51 2 -%333 = OpCompositeExtract %29 %51 2 -%334 = OpFAdd %29 %332 %333 -%325 = OpCompositeConstruct %37 %328 %331 %334 -%336 = OpCompositeExtract %29 %51 0 -%337 = OpCompositeExtract %29 %51 0 -%338 = OpFSub %29 %336 %337 -%339 = OpCompositeExtract %29 %51 1 -%340 = OpCompositeExtract %29 %51 1 -%341 = OpFSub %29 %339 %340 -%342 = OpCompositeExtract %29 %51 2 -%343 = OpCompositeExtract %29 %51 2 -%344 = OpFSub %29 %342 %343 -%335 = OpCompositeConstruct %37 %338 %341 %344 -%345 = OpMatrixTimesScalar %37 %51 %3 -%346 = OpMatrixTimesScalar %37 %51 %14 -%347 = OpCompositeConstruct %26 %3 %3 %3 %3 -%348 = OpMatrixTimesVector %29 %52 %347 -%349 = OpCompositeConstruct %29 %14 %14 %14 -%350 = OpVectorTimesMatrix %26 %349 %52 -%351 = OpMatrixTimesMatrix %37 %52 %53 +%269 = OpVectorTimesScalar %31 %268 %14 +%270 = OpCompositeConstruct %152 %18 %18 +%271 = OpCompositeConstruct %152 %7 %7 +%272 = OpSDiv %152 %270 %271 +%273 = OpCompositeConstruct %152 %7 %7 +%274 = OpCompositeConstruct %152 %18 %18 +%275 = OpSDiv %152 %274 %273 +%276 = OpCompositeConstruct %34 %24 %24 +%277 = OpCompositeConstruct %34 %25 %25 +%278 = OpUDiv %34 %276 %277 +%279 = OpCompositeConstruct %34 %25 %25 +%280 = OpCompositeConstruct %34 %24 %24 +%281 = OpUDiv %34 %280 %279 +%282 = OpCompositeConstruct %31 %14 %14 +%283 = OpCompositeConstruct %31 %3 %3 +%284 = OpFDiv %31 %282 %283 +%285 = OpCompositeConstruct %31 %3 %3 +%286 = OpCompositeConstruct %31 %14 %14 +%287 = OpFDiv %31 %286 %285 +%288 = OpCompositeConstruct %152 %18 %18 +%289 = OpCompositeConstruct %152 %7 %7 +%290 = OpSMod %152 %288 %289 +%291 = OpCompositeConstruct %152 %7 %7 +%292 = OpCompositeConstruct %152 %18 %18 +%293 = OpSMod %152 %292 %291 +%294 = OpCompositeConstruct %34 %24 %24 +%295 = OpCompositeConstruct %34 %25 %25 +%296 = OpUMod %34 %294 %295 +%297 = OpCompositeConstruct %34 %25 %25 +%298 = OpCompositeConstruct %34 %24 %24 +%299 = OpUMod %34 %298 %297 +%300 = OpCompositeConstruct %31 %14 %14 +%301 = OpCompositeConstruct %31 %3 %3 +%302 = OpFRem %31 %300 %301 +%303 = OpCompositeConstruct %31 %3 %3 +%304 = OpCompositeConstruct %31 %14 %14 +%305 = OpFRem %31 %304 %303 +%307 = OpCompositeExtract %29 %51 0 +%308 = OpCompositeExtract %29 %51 0 +%309 = OpFAdd %29 %307 %308 +%310 = OpCompositeExtract %29 %51 1 +%311 = OpCompositeExtract %29 %51 1 +%312 = OpFAdd %29 %310 %311 +%313 = OpCompositeExtract %29 %51 2 +%314 = OpCompositeExtract %29 %51 2 +%315 = OpFAdd %29 %313 %314 +%306 = OpCompositeConstruct %37 %309 %312 %315 +%317 = OpCompositeExtract %29 %51 0 +%318 = OpCompositeExtract %29 %51 0 +%319 = OpFSub %29 %317 %318 +%320 = OpCompositeExtract %29 %51 1 +%321 = OpCompositeExtract %29 %51 1 +%322 = OpFSub %29 %320 %321 +%323 = OpCompositeExtract %29 %51 2 +%324 = OpCompositeExtract %29 %51 2 +%325 = OpFSub %29 %323 %324 +%316 = OpCompositeConstruct %37 %319 %322 %325 +%326 = OpMatrixTimesScalar %37 %51 %3 +%327 = OpMatrixTimesScalar %37 %51 %14 +%328 = OpCompositeConstruct %26 %3 %3 %3 %3 +%329 = OpMatrixTimesVector %29 %52 %328 +%330 = OpCompositeConstruct %29 %14 %14 %14 +%331 = OpVectorTimesMatrix %26 %330 %52 +%332 = OpMatrixTimesMatrix %37 %52 %53 OpReturn OpFunctionEnd -%353 = OpFunction %2 None %152 -%352 = OpLabel -OpBranch %354 -%354 = OpLabel -%355 = OpNot %8 %7 -%356 = OpNot %20 %25 -%357 = OpCompositeConstruct %171 %7 %7 -%358 = OpNot %171 %357 -%359 = OpCompositeConstruct %182 %25 %25 %25 -%360 = OpNot %182 %359 -%361 = OpBitwiseOr %8 %18 %7 -%362 = OpBitwiseOr %20 %24 %25 -%363 = OpCompositeConstruct %171 %18 %18 -%364 = OpCompositeConstruct %171 %7 %7 -%365 = OpBitwiseOr %171 %363 %364 -%366 = OpCompositeConstruct %182 %24 %24 %24 -%367 = OpCompositeConstruct %182 %25 %25 %25 -%368 = OpBitwiseOr %182 %366 %367 -%369 = OpBitwiseAnd %8 %18 %7 -%370 = OpBitwiseAnd %20 %24 %25 -%371 = OpCompositeConstruct %171 %18 %18 -%372 = OpCompositeConstruct %171 %7 %7 -%373 = OpBitwiseAnd %171 %371 %372 -%374 = OpCompositeConstruct %182 %24 %24 %24 -%375 = OpCompositeConstruct %182 %25 %25 %25 -%376 = OpBitwiseAnd %182 %374 %375 -%377 = OpBitwiseXor %8 %18 %7 -%378 = OpBitwiseXor %20 %24 %25 -%379 = OpCompositeConstruct %171 %18 %18 -%380 = OpCompositeConstruct %171 %7 %7 -%381 = OpBitwiseXor %171 %379 %380 -%382 = OpCompositeConstruct %182 %24 %24 %24 -%383 = OpCompositeConstruct %182 %25 %25 %25 -%384 = OpBitwiseXor %182 %382 %383 -%385 = OpShiftLeftLogical %8 %18 %25 -%386 = OpShiftLeftLogical %20 %24 %25 -%387 = OpCompositeConstruct %171 %18 %18 -%388 = OpCompositeConstruct %34 %25 %25 -%389 = OpShiftLeftLogical %171 %387 %388 -%390 = OpCompositeConstruct %182 %24 %24 %24 -%391 = OpCompositeConstruct %182 %25 %25 %25 -%392 = OpShiftLeftLogical %182 %390 %391 -%393 = OpShiftRightArithmetic %8 %18 %25 -%394 = OpShiftRightLogical %20 %24 %25 -%395 = OpCompositeConstruct %171 %18 %18 -%396 = OpCompositeConstruct %34 %25 %25 -%397 = OpShiftRightArithmetic %171 %395 %396 -%398 = OpCompositeConstruct %182 %24 %24 %24 -%399 = OpCompositeConstruct %182 %25 %25 %25 -%400 = OpShiftRightLogical %182 %398 %399 +%334 = OpFunction %2 None %133 +%333 = OpLabel +OpBranch %335 +%335 = OpLabel +%336 = OpNot %8 %7 +%337 = OpNot %20 %25 +%338 = OpCompositeConstruct %152 %7 %7 +%339 = OpNot %152 %338 +%340 = OpCompositeConstruct %163 %25 %25 %25 +%341 = OpNot %163 %340 +%342 = OpBitwiseOr %8 %18 %7 +%343 = OpBitwiseOr %20 %24 %25 +%344 = OpCompositeConstruct %152 %18 %18 +%345 = OpCompositeConstruct %152 %7 %7 +%346 = OpBitwiseOr %152 %344 %345 +%347 = OpCompositeConstruct %163 %24 %24 %24 +%348 = OpCompositeConstruct %163 %25 %25 %25 +%349 = OpBitwiseOr %163 %347 %348 +%350 = OpBitwiseAnd %8 %18 %7 +%351 = OpBitwiseAnd %20 %24 %25 +%352 = OpCompositeConstruct %152 %18 %18 +%353 = OpCompositeConstruct %152 %7 %7 +%354 = OpBitwiseAnd %152 %352 %353 +%355 = OpCompositeConstruct %163 %24 %24 %24 +%356 = OpCompositeConstruct %163 %25 %25 %25 +%357 = OpBitwiseAnd %163 %355 %356 +%358 = OpBitwiseXor %8 %18 %7 +%359 = OpBitwiseXor %20 %24 %25 +%360 = OpCompositeConstruct %152 %18 %18 +%361 = OpCompositeConstruct %152 %7 %7 +%362 = OpBitwiseXor %152 %360 %361 +%363 = OpCompositeConstruct %163 %24 %24 %24 +%364 = OpCompositeConstruct %163 %25 %25 %25 +%365 = OpBitwiseXor %163 %363 %364 +%366 = OpShiftLeftLogical %8 %18 %25 +%367 = OpShiftLeftLogical %20 %24 %25 +%368 = OpCompositeConstruct %152 %18 %18 +%369 = OpCompositeConstruct %34 %25 %25 +%370 = OpShiftLeftLogical %152 %368 %369 +%371 = OpCompositeConstruct %163 %24 %24 %24 +%372 = OpCompositeConstruct %163 %25 %25 %25 +%373 = OpShiftLeftLogical %163 %371 %372 +%374 = OpShiftRightArithmetic %8 %18 %25 +%375 = OpShiftRightLogical %20 %24 %25 +%376 = OpCompositeConstruct %152 %18 %18 +%377 = OpCompositeConstruct %34 %25 %25 +%378 = OpShiftRightArithmetic %152 %376 %377 +%379 = OpCompositeConstruct %163 %24 %24 %24 +%380 = OpCompositeConstruct %163 %25 %25 %25 +%381 = OpShiftRightLogical %163 %379 %380 OpReturn OpFunctionEnd -%402 = OpFunction %2 None %152 -%401 = OpLabel -OpBranch %403 -%403 = OpLabel -%404 = OpIEqual %10 %18 %7 -%405 = OpIEqual %10 %24 %25 -%406 = OpFOrdEqual %10 %14 %3 -%407 = OpCompositeConstruct %171 %18 %18 -%408 = OpCompositeConstruct %171 %7 %7 -%409 = OpIEqual %155 %407 %408 -%410 = OpCompositeConstruct %182 %24 %24 %24 -%411 = OpCompositeConstruct %182 %25 %25 %25 -%412 = OpIEqual %100 %410 %411 -%413 = OpCompositeConstruct %26 %14 %14 %14 %14 -%414 = OpCompositeConstruct %26 %3 %3 %3 %3 -%415 = OpFOrdEqual %28 %413 %414 -%416 = OpINotEqual %10 %18 %7 -%417 = OpINotEqual %10 %24 %25 -%418 = OpFOrdNotEqual %10 %14 %3 -%419 = OpCompositeConstruct %171 %18 %18 -%420 = OpCompositeConstruct %171 %7 %7 -%421 = OpINotEqual %155 %419 %420 -%422 = OpCompositeConstruct %182 %24 %24 %24 -%423 = OpCompositeConstruct %182 %25 %25 %25 -%424 = OpINotEqual %100 %422 %423 -%425 = OpCompositeConstruct %26 %14 %14 %14 %14 -%426 = OpCompositeConstruct %26 %3 %3 %3 %3 -%427 = OpFOrdNotEqual %28 %425 %426 -%428 = OpSLessThan %10 %18 %7 -%429 = OpULessThan %10 %24 %25 -%430 = OpFOrdLessThan %10 %14 %3 -%431 = OpCompositeConstruct %171 %18 %18 -%432 = OpCompositeConstruct %171 %7 %7 -%433 = OpSLessThan %155 %431 %432 -%434 = OpCompositeConstruct %182 %24 %24 %24 -%435 = OpCompositeConstruct %182 %25 %25 %25 -%436 = OpULessThan %100 %434 %435 -%437 = OpCompositeConstruct %26 %14 %14 %14 %14 -%438 = OpCompositeConstruct %26 %3 %3 %3 %3 -%439 = OpFOrdLessThan %28 %437 %438 -%440 = OpSLessThanEqual %10 %18 %7 -%441 = OpULessThanEqual %10 %24 %25 -%442 = OpFOrdLessThanEqual %10 %14 %3 -%443 = OpCompositeConstruct %171 %18 %18 -%444 = OpCompositeConstruct %171 %7 %7 -%445 = OpSLessThanEqual %155 %443 %444 -%446 = OpCompositeConstruct %182 %24 %24 %24 -%447 = OpCompositeConstruct %182 %25 %25 %25 -%448 = OpULessThanEqual %100 %446 %447 -%449 = OpCompositeConstruct %26 %14 %14 %14 %14 -%450 = OpCompositeConstruct %26 %3 %3 %3 %3 -%451 = OpFOrdLessThanEqual %28 %449 %450 -%452 = OpSGreaterThan %10 %18 %7 -%453 = OpUGreaterThan %10 %24 %25 -%454 = OpFOrdGreaterThan %10 %14 %3 -%455 = OpCompositeConstruct %171 %18 %18 -%456 = OpCompositeConstruct %171 %7 %7 -%457 = OpSGreaterThan %155 %455 %456 -%458 = OpCompositeConstruct %182 %24 %24 %24 -%459 = OpCompositeConstruct %182 %25 %25 %25 -%460 = OpUGreaterThan %100 %458 %459 -%461 = OpCompositeConstruct %26 %14 %14 %14 %14 -%462 = OpCompositeConstruct %26 %3 %3 %3 %3 -%463 = OpFOrdGreaterThan %28 %461 %462 -%464 = OpSGreaterThanEqual %10 %18 %7 -%465 = OpUGreaterThanEqual %10 %24 %25 -%466 = OpFOrdGreaterThanEqual %10 %14 %3 -%467 = OpCompositeConstruct %171 %18 %18 -%468 = OpCompositeConstruct %171 %7 %7 -%469 = OpSGreaterThanEqual %155 %467 %468 -%470 = OpCompositeConstruct %182 %24 %24 %24 -%471 = OpCompositeConstruct %182 %25 %25 %25 -%472 = OpUGreaterThanEqual %100 %470 %471 -%473 = OpCompositeConstruct %26 %14 %14 %14 %14 -%474 = OpCompositeConstruct %26 %3 %3 %3 %3 -%475 = OpFOrdGreaterThanEqual %28 %473 %474 +%383 = OpFunction %2 None %133 +%382 = OpLabel +OpBranch %384 +%384 = OpLabel +%385 = OpIEqual %10 %18 %7 +%386 = OpIEqual %10 %24 %25 +%387 = OpFOrdEqual %10 %14 %3 +%388 = OpCompositeConstruct %152 %18 %18 +%389 = OpCompositeConstruct %152 %7 %7 +%390 = OpIEqual %136 %388 %389 +%391 = OpCompositeConstruct %163 %24 %24 %24 +%392 = OpCompositeConstruct %163 %25 %25 %25 +%393 = OpIEqual %100 %391 %392 +%394 = OpCompositeConstruct %26 %14 %14 %14 %14 +%395 = OpCompositeConstruct %26 %3 %3 %3 %3 +%396 = OpFOrdEqual %28 %394 %395 +%397 = OpINotEqual %10 %18 %7 +%398 = OpINotEqual %10 %24 %25 +%399 = OpFOrdNotEqual %10 %14 %3 +%400 = OpCompositeConstruct %152 %18 %18 +%401 = OpCompositeConstruct %152 %7 %7 +%402 = OpINotEqual %136 %400 %401 +%403 = OpCompositeConstruct %163 %24 %24 %24 +%404 = OpCompositeConstruct %163 %25 %25 %25 +%405 = OpINotEqual %100 %403 %404 +%406 = OpCompositeConstruct %26 %14 %14 %14 %14 +%407 = OpCompositeConstruct %26 %3 %3 %3 %3 +%408 = OpFOrdNotEqual %28 %406 %407 +%409 = OpSLessThan %10 %18 %7 +%410 = OpULessThan %10 %24 %25 +%411 = OpFOrdLessThan %10 %14 %3 +%412 = OpCompositeConstruct %152 %18 %18 +%413 = OpCompositeConstruct %152 %7 %7 +%414 = OpSLessThan %136 %412 %413 +%415 = OpCompositeConstruct %163 %24 %24 %24 +%416 = OpCompositeConstruct %163 %25 %25 %25 +%417 = OpULessThan %100 %415 %416 +%418 = OpCompositeConstruct %26 %14 %14 %14 %14 +%419 = OpCompositeConstruct %26 %3 %3 %3 %3 +%420 = OpFOrdLessThan %28 %418 %419 +%421 = OpSLessThanEqual %10 %18 %7 +%422 = OpULessThanEqual %10 %24 %25 +%423 = OpFOrdLessThanEqual %10 %14 %3 +%424 = OpCompositeConstruct %152 %18 %18 +%425 = OpCompositeConstruct %152 %7 %7 +%426 = OpSLessThanEqual %136 %424 %425 +%427 = OpCompositeConstruct %163 %24 %24 %24 +%428 = OpCompositeConstruct %163 %25 %25 %25 +%429 = OpULessThanEqual %100 %427 %428 +%430 = OpCompositeConstruct %26 %14 %14 %14 %14 +%431 = OpCompositeConstruct %26 %3 %3 %3 %3 +%432 = OpFOrdLessThanEqual %28 %430 %431 +%433 = OpSGreaterThan %10 %18 %7 +%434 = OpUGreaterThan %10 %24 %25 +%435 = OpFOrdGreaterThan %10 %14 %3 +%436 = OpCompositeConstruct %152 %18 %18 +%437 = OpCompositeConstruct %152 %7 %7 +%438 = OpSGreaterThan %136 %436 %437 +%439 = OpCompositeConstruct %163 %24 %24 %24 +%440 = OpCompositeConstruct %163 %25 %25 %25 +%441 = OpUGreaterThan %100 %439 %440 +%442 = OpCompositeConstruct %26 %14 %14 %14 %14 +%443 = OpCompositeConstruct %26 %3 %3 %3 %3 +%444 = OpFOrdGreaterThan %28 %442 %443 +%445 = OpSGreaterThanEqual %10 %18 %7 +%446 = OpUGreaterThanEqual %10 %24 %25 +%447 = OpFOrdGreaterThanEqual %10 %14 %3 +%448 = OpCompositeConstruct %152 %18 %18 +%449 = OpCompositeConstruct %152 %7 %7 +%450 = OpSGreaterThanEqual %136 %448 %449 +%451 = OpCompositeConstruct %163 %24 %24 %24 +%452 = OpCompositeConstruct %163 %25 %25 %25 +%453 = OpUGreaterThanEqual %100 %451 %452 +%454 = OpCompositeConstruct %26 %14 %14 %14 %14 +%455 = OpCompositeConstruct %26 %3 %3 %3 %3 +%456 = OpFOrdGreaterThanEqual %28 %454 %455 OpReturn OpFunctionEnd -%478 = OpFunction %2 None %152 -%477 = OpLabel -%476 = OpVariable %111 Function %7 -OpBranch %479 -%479 = OpLabel -%480 = OpLoad %8 %476 -%481 = OpIAdd %8 %480 %7 -OpStore %476 %481 -%482 = OpLoad %8 %476 -%483 = OpISub %8 %482 %7 -OpStore %476 %483 -%484 = OpLoad %8 %476 -%485 = OpLoad %8 %476 -%486 = OpIMul %8 %484 %485 -OpStore %476 %486 -%487 = OpLoad %8 %476 -%488 = OpLoad %8 %476 -%489 = OpSDiv %8 %487 %488 -OpStore %476 %489 -%490 = OpLoad %8 %476 -%491 = OpSMod %8 %490 %7 -OpStore %476 %491 -%492 = OpLoad %8 %476 -%493 = OpBitwiseAnd %8 %492 %11 -OpStore %476 %493 -%494 = OpLoad %8 %476 -%495 = OpBitwiseOr %8 %494 %11 -OpStore %476 %495 -%496 = OpLoad %8 %476 -%497 = OpBitwiseXor %8 %496 %11 -OpStore %476 %497 -%498 = OpLoad %8 %476 -%499 = OpShiftLeftLogical %8 %498 %24 -OpStore %476 %499 -%500 = OpLoad %8 %476 -%501 = OpShiftRightArithmetic %8 %500 %25 -OpStore %476 %501 -%502 = OpLoad %8 %476 -%503 = OpIAdd %8 %502 %7 -OpStore %476 %503 -%504 = OpLoad %8 %476 -%505 = OpISub %8 %504 %7 -OpStore %476 %505 +%460 = OpFunction %2 None %133 +%459 = OpLabel +%457 = OpVariable %458 Function %7 +OpBranch %461 +%461 = OpLabel +%462 = OpLoad %8 %457 +%463 = OpIAdd %8 %462 %7 +OpStore %457 %463 +%464 = OpLoad %8 %457 +%465 = OpISub %8 %464 %7 +OpStore %457 %465 +%466 = OpLoad %8 %457 +%467 = OpLoad %8 %457 +%468 = OpIMul %8 %466 %467 +OpStore %457 %468 +%469 = OpLoad %8 %457 +%470 = OpLoad %8 %457 +%471 = OpSDiv %8 %469 %470 +OpStore %457 %471 +%472 = OpLoad %8 %457 +%473 = OpSMod %8 %472 %7 +OpStore %457 %473 +%474 = OpLoad %8 %457 +%475 = OpBitwiseAnd %8 %474 %11 +OpStore %457 %475 +%476 = OpLoad %8 %457 +%477 = OpBitwiseOr %8 %476 %11 +OpStore %457 %477 +%478 = OpLoad %8 %457 +%479 = OpBitwiseXor %8 %478 %11 +OpStore %457 %479 +%480 = OpLoad %8 %457 +%481 = OpShiftLeftLogical %8 %480 %24 +OpStore %457 %481 +%482 = OpLoad %8 %457 +%483 = OpShiftRightArithmetic %8 %482 %25 +OpStore %457 %483 +%484 = OpLoad %8 %457 +%485 = OpIAdd %8 %484 %7 +OpStore %457 %485 +%486 = OpLoad %8 %457 +%487 = OpISub %8 %486 %7 +OpStore %457 %487 OpReturn OpFunctionEnd -%507 = OpFunction %2 None %152 -%506 = OpLabel -OpBranch %508 -%508 = OpLabel -%509 = OpFunctionCall %26 %55 -%510 = OpFunctionCall %26 %80 -%511 = OpVectorShuffle %29 %40 %40 0 1 2 -%512 = OpFunctionCall %29 %97 %511 -%513 = OpFunctionCall %4 %128 -%514 = OpFunctionCall %2 %151 -%515 = OpFunctionCall %2 %169 -%516 = OpFunctionCall %2 %353 -%517 = OpFunctionCall %2 %402 -%518 = OpFunctionCall %2 %478 +%489 = OpFunction %2 None %133 +%488 = OpLabel +OpBranch %490 +%490 = OpLabel +%491 = OpFunctionCall %26 %55 +%492 = OpFunctionCall %26 %80 +%493 = OpVectorShuffle %29 %40 %40 0 1 2 +%494 = OpFunctionCall %29 %97 %493 +%495 = OpFunctionCall %4 %109 +%496 = OpFunctionCall %2 %132 +%497 = OpFunctionCall %2 %150 +%498 = OpFunctionCall %2 %334 +%499 = OpFunctionCall %2 %383 +%500 = OpFunctionCall %2 %460 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 0fd4b7fd3..98d53fb9b 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -21,51 +21,37 @@ var baz: Baz; fn test_matrix_within_struct_accesses() { var idx: i32 = 9; - var unnamed_1: mat3x2; - var unnamed_2: vec2; - var unnamed_3: vec2; - var unnamed_4: f32; - var unnamed_5: f32; - var unnamed_6: f32; - var unnamed_7: f32; var t: Baz; let _e4 = idx; idx = (_e4 - 1); - let _e8 = baz.m; - unnamed_1 = _e8; - let _e13 = baz.m[0]; - unnamed_2 = _e13; - let _e16 = idx; - let _e18 = baz.m[_e16]; - unnamed_3 = _e18; - let _e25 = baz.m[0][1]; - unnamed_4 = _e25; + let unnamed = baz.m; + let unnamed_1 = baz.m[0]; + let _e14 = idx; + let unnamed_2 = baz.m[_e14]; + let unnamed_3 = baz.m[0][1]; + let _e26 = idx; + let unnamed_4 = baz.m[0][_e26]; let _e30 = idx; - let _e32 = baz.m[0][_e30]; - unnamed_5 = _e32; - let _e35 = idx; - let _e39 = baz.m[_e35][1]; - unnamed_6 = _e39; - let _e42 = idx; - let _e44 = idx; - let _e46 = baz.m[_e42][_e44]; - unnamed_7 = _e46; + let unnamed_5 = baz.m[_e30][1]; + let _e36 = idx; + let _e38 = idx; + let unnamed_6 = baz.m[_e36][_e38]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - let _e57 = idx; - idx = (_e57 + 1); + let _e50 = idx; + idx = (_e50 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - let _e74 = idx; - t.m[_e74] = vec2(90.0); + let _e67 = idx; + t.m[_e67] = vec2(90.0); t.m[0][1] = 10.0; - let _e87 = idx; - t.m[0][_e87] = 20.0; - let _e91 = idx; - t.m[_e91][1] = 30.0; - let _e97 = idx; - let _e99 = idx; - t.m[_e97][_e99] = 40.0; + let _e80 = idx; + t.m[0][_e80] = 20.0; + let _e84 = idx; + t.m[_e84][1] = 30.0; + let _e90 = idx; + let _e92 = idx; + t.m[_e90][_e92] = 40.0; return; } @@ -82,7 +68,6 @@ fn test_arr_as_arg(a: array,5>) -> f32 { fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32 = 0.0; var c: array; - var unnamed: f32; let baz_1 = foo; foo = 1.0; @@ -97,7 +82,6 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { c[(vi + 1u)] = 42; let value = c[vi]; let _e42 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); - unnamed = _e42; return vec4((_matrix * vec4(vec4(value))), 2.0); } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 19660d36d..f9144dd77 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -32,175 +32,164 @@ fn bool_cast(x: vec3) -> vec3 { fn constructors() -> f32 { var foo: Foo; - var unnamed: bool = false; - var unnamed_1: i32 = 0; - var unnamed_2: u32 = 0u; - var unnamed_3: f32 = 0.0; - var unnamed_4: vec2 = vec2(0u, 0u); - var unnamed_5: mat2x2 = mat2x2(vec2(0.0, 0.0), vec2(0.0, 0.0)); - var unnamed_6: array = array(Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0)); - var unnamed_7: Foo = Foo(vec4(0.0, 0.0, 0.0, 0.0), 0); - var unnamed_8: vec2; - var unnamed_9: mat2x2; - var unnamed_10: array; foo = Foo(vec4(1.0), 1); let mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); let mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - unnamed_8 = vec2(0u); - unnamed_9 = mat2x2(vec2(0.0), vec2(0.0)); - unnamed_10 = array(0, 1, 2, 3); - let _e70 = foo.a.x; - return _e70; + let unnamed = vec2(0u); + let unnamed_1 = mat2x2(vec2(0.0), vec2(0.0)); + let unnamed_2 = array(0, 1, 2, 3); + let _e59 = foo.a.x; + return _e59; } fn logical() { - let unnamed_11 = !(true); - let unnamed_12 = !(vec2(true)); - let unnamed_13 = (true || false); - let unnamed_14 = (true && false); - let unnamed_15 = (true | false); - let unnamed_16 = (vec3(true) | vec3(false)); - let unnamed_17 = (true & false); - let unnamed_18 = (vec4(true) & vec4(false)); + let unnamed_3 = !(true); + let unnamed_4 = !(vec2(true)); + let unnamed_5 = (true || false); + let unnamed_6 = (true && false); + let unnamed_7 = (true | false); + let unnamed_8 = (vec3(true) | vec3(false)); + let unnamed_9 = (true & false); + let unnamed_10 = (vec4(true) & vec4(false)); } fn arithmetic() { - let unnamed_19 = -(vec2(1)); - let unnamed_20 = -(vec2(1.0)); - let unnamed_21 = (2 + 1); - let unnamed_22 = (2u + 1u); - let unnamed_23 = (2.0 + 1.0); - let unnamed_24 = (vec2(2) + vec2(1)); - let unnamed_25 = (vec3(2u) + vec3(1u)); - let unnamed_26 = (vec4(2.0) + vec4(1.0)); - let unnamed_27 = (2 - 1); - let unnamed_28 = (2u - 1u); - let unnamed_29 = (2.0 - 1.0); - let unnamed_30 = (vec2(2) - vec2(1)); - let unnamed_31 = (vec3(2u) - vec3(1u)); - let unnamed_32 = (vec4(2.0) - vec4(1.0)); - let unnamed_33 = (2 * 1); - let unnamed_34 = (2u * 1u); - let unnamed_35 = (2.0 * 1.0); - let unnamed_36 = (vec2(2) * vec2(1)); - let unnamed_37 = (vec3(2u) * vec3(1u)); - let unnamed_38 = (vec4(2.0) * vec4(1.0)); - let unnamed_39 = (2 / 1); - let unnamed_40 = (2u / 1u); - let unnamed_41 = (2.0 / 1.0); - let unnamed_42 = (vec2(2) / vec2(1)); - let unnamed_43 = (vec3(2u) / vec3(1u)); - let unnamed_44 = (vec4(2.0) / vec4(1.0)); - let unnamed_45 = (2 % 1); - let unnamed_46 = (2u % 1u); - let unnamed_47 = (2.0 % 1.0); - let unnamed_48 = (vec2(2) % vec2(1)); - let unnamed_49 = (vec3(2u) % vec3(1u)); - let unnamed_50 = (vec4(2.0) % vec4(1.0)); - let unnamed_51 = (vec2(2) + vec2(1)); - let unnamed_52 = (vec2(2) + vec2(1)); - let unnamed_53 = (vec2(2u) + vec2(1u)); - let unnamed_54 = (vec2(2u) + vec2(1u)); - let unnamed_55 = (vec2(2.0) + vec2(1.0)); - let unnamed_56 = (vec2(2.0) + vec2(1.0)); - let unnamed_57 = (vec2(2) - vec2(1)); - let unnamed_58 = (vec2(2) - vec2(1)); - let unnamed_59 = (vec2(2u) - vec2(1u)); - let unnamed_60 = (vec2(2u) - vec2(1u)); - let unnamed_61 = (vec2(2.0) - vec2(1.0)); - let unnamed_62 = (vec2(2.0) - vec2(1.0)); - let unnamed_63 = (vec2(2) * 1); - let unnamed_64 = (2 * vec2(1)); - let unnamed_65 = (vec2(2u) * 1u); - let unnamed_66 = (2u * vec2(1u)); - let unnamed_67 = (vec2(2.0) * 1.0); - let unnamed_68 = (2.0 * vec2(1.0)); - let unnamed_69 = (vec2(2) / vec2(1)); - let unnamed_70 = (vec2(2) / vec2(1)); - let unnamed_71 = (vec2(2u) / vec2(1u)); - let unnamed_72 = (vec2(2u) / vec2(1u)); - let unnamed_73 = (vec2(2.0) / vec2(1.0)); - let unnamed_74 = (vec2(2.0) / vec2(1.0)); - let unnamed_75 = (vec2(2) % vec2(1)); - let unnamed_76 = (vec2(2) % vec2(1)); - let unnamed_77 = (vec2(2u) % vec2(1u)); - let unnamed_78 = (vec2(2u) % vec2(1u)); - let unnamed_79 = (vec2(2.0) % vec2(1.0)); - let unnamed_80 = (vec2(2.0) % vec2(1.0)); - let unnamed_81 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_82 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_83 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - let unnamed_84 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_85 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - let unnamed_86 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_87 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + let unnamed_11 = -(vec2(1)); + let unnamed_12 = -(vec2(1.0)); + let unnamed_13 = (2 + 1); + let unnamed_14 = (2u + 1u); + let unnamed_15 = (2.0 + 1.0); + let unnamed_16 = (vec2(2) + vec2(1)); + let unnamed_17 = (vec3(2u) + vec3(1u)); + let unnamed_18 = (vec4(2.0) + vec4(1.0)); + let unnamed_19 = (2 - 1); + let unnamed_20 = (2u - 1u); + let unnamed_21 = (2.0 - 1.0); + let unnamed_22 = (vec2(2) - vec2(1)); + let unnamed_23 = (vec3(2u) - vec3(1u)); + let unnamed_24 = (vec4(2.0) - vec4(1.0)); + let unnamed_25 = (2 * 1); + let unnamed_26 = (2u * 1u); + let unnamed_27 = (2.0 * 1.0); + let unnamed_28 = (vec2(2) * vec2(1)); + let unnamed_29 = (vec3(2u) * vec3(1u)); + let unnamed_30 = (vec4(2.0) * vec4(1.0)); + let unnamed_31 = (2 / 1); + let unnamed_32 = (2u / 1u); + let unnamed_33 = (2.0 / 1.0); + let unnamed_34 = (vec2(2) / vec2(1)); + let unnamed_35 = (vec3(2u) / vec3(1u)); + let unnamed_36 = (vec4(2.0) / vec4(1.0)); + let unnamed_37 = (2 % 1); + let unnamed_38 = (2u % 1u); + let unnamed_39 = (2.0 % 1.0); + let unnamed_40 = (vec2(2) % vec2(1)); + let unnamed_41 = (vec3(2u) % vec3(1u)); + let unnamed_42 = (vec4(2.0) % vec4(1.0)); + let unnamed_43 = (vec2(2) + vec2(1)); + let unnamed_44 = (vec2(2) + vec2(1)); + let unnamed_45 = (vec2(2u) + vec2(1u)); + let unnamed_46 = (vec2(2u) + vec2(1u)); + let unnamed_47 = (vec2(2.0) + vec2(1.0)); + let unnamed_48 = (vec2(2.0) + vec2(1.0)); + let unnamed_49 = (vec2(2) - vec2(1)); + let unnamed_50 = (vec2(2) - vec2(1)); + let unnamed_51 = (vec2(2u) - vec2(1u)); + let unnamed_52 = (vec2(2u) - vec2(1u)); + let unnamed_53 = (vec2(2.0) - vec2(1.0)); + let unnamed_54 = (vec2(2.0) - vec2(1.0)); + let unnamed_55 = (vec2(2) * 1); + let unnamed_56 = (2 * vec2(1)); + let unnamed_57 = (vec2(2u) * 1u); + let unnamed_58 = (2u * vec2(1u)); + let unnamed_59 = (vec2(2.0) * 1.0); + let unnamed_60 = (2.0 * vec2(1.0)); + let unnamed_61 = (vec2(2) / vec2(1)); + let unnamed_62 = (vec2(2) / vec2(1)); + let unnamed_63 = (vec2(2u) / vec2(1u)); + let unnamed_64 = (vec2(2u) / vec2(1u)); + let unnamed_65 = (vec2(2.0) / vec2(1.0)); + let unnamed_66 = (vec2(2.0) / vec2(1.0)); + let unnamed_67 = (vec2(2) % vec2(1)); + let unnamed_68 = (vec2(2) % vec2(1)); + let unnamed_69 = (vec2(2u) % vec2(1u)); + let unnamed_70 = (vec2(2u) % vec2(1u)); + let unnamed_71 = (vec2(2.0) % vec2(1.0)); + let unnamed_72 = (vec2(2.0) % vec2(1.0)); + let unnamed_73 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_74 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_75 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + let unnamed_76 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_77 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + let unnamed_78 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let unnamed_79 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } fn bit() { - let unnamed_88 = ~(1); - let unnamed_89 = ~(1u); - let unnamed_90 = !(vec2(1)); - let unnamed_91 = !(vec3(1u)); - let unnamed_92 = (2 | 1); - let unnamed_93 = (2u | 1u); - let unnamed_94 = (vec2(2) | vec2(1)); - let unnamed_95 = (vec3(2u) | vec3(1u)); - let unnamed_96 = (2 & 1); - let unnamed_97 = (2u & 1u); - let unnamed_98 = (vec2(2) & vec2(1)); - let unnamed_99 = (vec3(2u) & vec3(1u)); - let unnamed_100 = (2 ^ 1); - let unnamed_101 = (2u ^ 1u); - let unnamed_102 = (vec2(2) ^ vec2(1)); - let unnamed_103 = (vec3(2u) ^ vec3(1u)); - let unnamed_104 = (2 << 1u); - let unnamed_105 = (2u << 1u); - let unnamed_106 = (vec2(2) << vec2(1u)); - let unnamed_107 = (vec3(2u) << vec3(1u)); - let unnamed_108 = (2 >> 1u); - let unnamed_109 = (2u >> 1u); - let unnamed_110 = (vec2(2) >> vec2(1u)); - let unnamed_111 = (vec3(2u) >> vec3(1u)); + let unnamed_80 = ~(1); + let unnamed_81 = ~(1u); + let unnamed_82 = !(vec2(1)); + let unnamed_83 = !(vec3(1u)); + let unnamed_84 = (2 | 1); + let unnamed_85 = (2u | 1u); + let unnamed_86 = (vec2(2) | vec2(1)); + let unnamed_87 = (vec3(2u) | vec3(1u)); + let unnamed_88 = (2 & 1); + let unnamed_89 = (2u & 1u); + let unnamed_90 = (vec2(2) & vec2(1)); + let unnamed_91 = (vec3(2u) & vec3(1u)); + let unnamed_92 = (2 ^ 1); + let unnamed_93 = (2u ^ 1u); + let unnamed_94 = (vec2(2) ^ vec2(1)); + let unnamed_95 = (vec3(2u) ^ vec3(1u)); + let unnamed_96 = (2 << 1u); + let unnamed_97 = (2u << 1u); + let unnamed_98 = (vec2(2) << vec2(1u)); + let unnamed_99 = (vec3(2u) << vec3(1u)); + let unnamed_100 = (2 >> 1u); + let unnamed_101 = (2u >> 1u); + let unnamed_102 = (vec2(2) >> vec2(1u)); + let unnamed_103 = (vec3(2u) >> vec3(1u)); } fn comparison() { - let unnamed_112 = (2 == 1); - let unnamed_113 = (2u == 1u); - let unnamed_114 = (2.0 == 1.0); - let unnamed_115 = (vec2(2) == vec2(1)); - let unnamed_116 = (vec3(2u) == vec3(1u)); - let unnamed_117 = (vec4(2.0) == vec4(1.0)); - let unnamed_118 = (2 != 1); - let unnamed_119 = (2u != 1u); - let unnamed_120 = (2.0 != 1.0); - let unnamed_121 = (vec2(2) != vec2(1)); - let unnamed_122 = (vec3(2u) != vec3(1u)); - let unnamed_123 = (vec4(2.0) != vec4(1.0)); - let unnamed_124 = (2 < 1); - let unnamed_125 = (2u < 1u); - let unnamed_126 = (2.0 < 1.0); - let unnamed_127 = (vec2(2) < vec2(1)); - let unnamed_128 = (vec3(2u) < vec3(1u)); - let unnamed_129 = (vec4(2.0) < vec4(1.0)); - let unnamed_130 = (2 <= 1); - let unnamed_131 = (2u <= 1u); - let unnamed_132 = (2.0 <= 1.0); - let unnamed_133 = (vec2(2) <= vec2(1)); - let unnamed_134 = (vec3(2u) <= vec3(1u)); - let unnamed_135 = (vec4(2.0) <= vec4(1.0)); - let unnamed_136 = (2 > 1); - let unnamed_137 = (2u > 1u); - let unnamed_138 = (2.0 > 1.0); - let unnamed_139 = (vec2(2) > vec2(1)); - let unnamed_140 = (vec3(2u) > vec3(1u)); - let unnamed_141 = (vec4(2.0) > vec4(1.0)); - let unnamed_142 = (2 >= 1); - let unnamed_143 = (2u >= 1u); - let unnamed_144 = (2.0 >= 1.0); - let unnamed_145 = (vec2(2) >= vec2(1)); - let unnamed_146 = (vec3(2u) >= vec3(1u)); - let unnamed_147 = (vec4(2.0) >= vec4(1.0)); + let unnamed_104 = (2 == 1); + let unnamed_105 = (2u == 1u); + let unnamed_106 = (2.0 == 1.0); + let unnamed_107 = (vec2(2) == vec2(1)); + let unnamed_108 = (vec3(2u) == vec3(1u)); + let unnamed_109 = (vec4(2.0) == vec4(1.0)); + let unnamed_110 = (2 != 1); + let unnamed_111 = (2u != 1u); + let unnamed_112 = (2.0 != 1.0); + let unnamed_113 = (vec2(2) != vec2(1)); + let unnamed_114 = (vec3(2u) != vec3(1u)); + let unnamed_115 = (vec4(2.0) != vec4(1.0)); + let unnamed_116 = (2 < 1); + let unnamed_117 = (2u < 1u); + let unnamed_118 = (2.0 < 1.0); + let unnamed_119 = (vec2(2) < vec2(1)); + let unnamed_120 = (vec3(2u) < vec3(1u)); + let unnamed_121 = (vec4(2.0) < vec4(1.0)); + let unnamed_122 = (2 <= 1); + let unnamed_123 = (2u <= 1u); + let unnamed_124 = (2.0 <= 1.0); + let unnamed_125 = (vec2(2) <= vec2(1)); + let unnamed_126 = (vec3(2u) <= vec3(1u)); + let unnamed_127 = (vec4(2.0) <= vec4(1.0)); + let unnamed_128 = (2 > 1); + let unnamed_129 = (2u > 1u); + let unnamed_130 = (2.0 > 1.0); + let unnamed_131 = (vec2(2) > vec2(1)); + let unnamed_132 = (vec3(2u) > vec3(1u)); + let unnamed_133 = (vec4(2.0) > vec4(1.0)); + let unnamed_134 = (2 >= 1); + let unnamed_135 = (2u >= 1u); + let unnamed_136 = (2.0 >= 1.0); + let unnamed_137 = (vec2(2) >= vec2(1)); + let unnamed_138 = (vec3(2u) >= vec3(1u)); + let unnamed_139 = (vec4(2.0) >= vec4(1.0)); } fn assignment() { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index caf855e1b..e5823c250 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -171,14 +171,14 @@ fn type_not_constructible() { check( r#" fn x() { - var _ = atomic(0); + _ = atomic(0); } "#, r#"error: type `atomic` is not constructible - ┌─ wgsl:3:25 + ┌─ wgsl:3:21 │ -3 │ var _ = atomic(0); - │ ^^^^^^ type is not constructible +3 │ _ = atomic(0); + │ ^^^^^^ type is not constructible "#, ); @@ -189,14 +189,14 @@ fn type_not_inferrable() { check( r#" fn x() { - var _ = vec2(); + _ = vec2(); } "#, r#"error: type can't be inferred - ┌─ wgsl:3:25 + ┌─ wgsl:3:21 │ -3 │ var _ = vec2(); - │ ^^^^ type can't be inferred +3 │ _ = vec2(); + │ ^^^^ type can't be inferred "#, ); @@ -207,14 +207,14 @@ fn unexpected_constructor_parameters() { check( r#" fn x() { - var _ = i32(0, 1); + _ = i32(0, 1); } "#, r#"error: unexpected components - ┌─ wgsl:3:31 + ┌─ wgsl:3:27 │ -3 │ var _ = i32(0, 1); - │ ^^ unexpected components +3 │ _ = i32(0, 1); + │ ^^ unexpected components "#, ); @@ -225,14 +225,14 @@ fn constructor_parameter_type_mismatch() { check( r#" fn x() { - var _ = mat2x2(array(0, 1), vec2(2, 3)); + _ = mat2x2(array(0, 1), vec2(2, 3)); } "#, r#"error: invalid type for constructor component at index [0] - ┌─ wgsl:3:37 + ┌─ wgsl:3:33 │ -3 │ var _ = mat2x2(array(0, 1), vec2(2, 3)); - │ ^^^^^^^^^^^ invalid component type +3 │ _ = mat2x2(array(0, 1), vec2(2, 3)); + │ ^^^^^^^^^^^ invalid component type "#, ); From f2e7818e7159916445514b485156ddf84f9244a5 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 27 Apr 2022 07:25:53 +0200 Subject: [PATCH 1708/2212] [wgsl-in] implement firstTrailingBit/firstLeadingBit u32 overloads (#1865) * [wgsl-in] implement firstTrailingBit/firstLeadingBit u32 overloads * fix MSL type issue reverts https://github.com/gfx-rs/naga/pull/1473/commits/b9162e443dd58cf95c2d7930e9c42b0e0e00ede7 --- src/back/glsl/mod.rs | 30 ++++++++++++++++- src/back/msl/writer.rs | 31 +++--------------- src/front/glsl/builtins.rs | 40 +++++++++++++++++++++++ src/proc/typifier.rs | 10 +++--- tests/in/bits.wgsl | 4 +-- tests/out/glsl/bits.main.Compute.glsl | 4 +-- tests/out/msl/bits.msl | 8 ++--- tests/out/spv/bits.spvasm | 8 ++--- tests/out/wgsl/bits.wgsl | 4 +-- tests/out/wgsl/bits_glsl-frag.wgsl | 46 +++++++++++++-------------- 10 files changed, 115 insertions(+), 70 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 699348f05..7ede19e4a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2806,6 +2806,30 @@ impl<'a, W: Write> Writer<'a, W> { let extract_bits = fun == Mf::ExtractBits; let insert_bits = fun == Mf::InsertBits; + // we might need to cast to unsigned integers since + // GLSL's findLSB / findMSB always return signed integers + let need_extra_paren = { + (fun == Mf::FindLsb || fun == Mf::FindMsb) + && match *ctx.info[arg].ty.inner_with(&self.module.types) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } => { + write!(self.out, "uint(")?; + true + } + crate::TypeInner::Vector { + kind: crate::ScalarKind::Uint, + size, + .. + } => { + write!(self.out, "uvec{}(", size as u8)?; + true + } + _ => false, + } + }; + write!(self.out, "{}(", fun_name)?; self.write_expr(arg, ctx)?; if let Some(arg) = arg1 { @@ -2838,7 +2862,11 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(arg, ctx)?; } } - write!(self.out, ")")? + write!(self.out, ")")?; + + if need_extra_paren { + write!(self.out, ")")? + } } // `As` is always a call. // If `convert` is true the function name is the type diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 836985846..1e36b5a9b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1591,21 +1591,6 @@ impl Writer { crate::TypeInner::Scalar { .. } => true, _ => false, }; - let argument_size_suffix = match *context.resolve_type(arg) { - crate::TypeInner::Vector { - size: crate::VectorSize::Bi, - .. - } => "2", - crate::TypeInner::Vector { - size: crate::VectorSize::Tri, - .. - } => "3", - crate::TypeInner::Vector { - size: crate::VectorSize::Quad, - .. - } => "4", - _ => "", - }; let fun_name = match fun { // comparison @@ -1705,21 +1690,13 @@ impl Writer { self.put_expression(arg1.unwrap(), context, false)?; write!(self.out, ")")?; } else if fun == Mf::FindLsb { - write!( - self.out, - "(((1 + int{}({}::ctz(", - argument_size_suffix, NAMESPACE - )?; + write!(self.out, "((({}::ctz(", NAMESPACE)?; self.put_expression(arg, context, true)?; - write!(self.out, "))) % 33) - 1)")?; + write!(self.out, ") + 1) % 33) - 1)")?; } else if fun == Mf::FindMsb { - write!( - self.out, - "(((1 + int{}({}::clz(", - argument_size_suffix, NAMESPACE - )?; + write!(self.out, "((({}::clz(", NAMESPACE)?; self.put_expression(arg, context, true)?; - write!(self.out, "))) % 33) - 1)")?; + write!(self.out, ") + 1) % 33) - 1)")? } else if fun == Mf::Unpack2x16float { write!(self.out, "float2(as_type(")?; self.put_expression(arg, context, false)?; diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 6e6148138..5bee3948f 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -727,6 +727,17 @@ fn inject_standard_builtins( _ => {} } + // we need to cast the return type of findLsb / findMsb + let mc = if kind == Sk::Uint { + match mc { + MacroCall::MathFunction(MathFunction::FindLsb) => MacroCall::FindLsbUint, + MacroCall::MathFunction(MathFunction::FindMsb) => MacroCall::FindMsbUint, + mc => mc, + } + } else { + mc + }; + declaration.overloads.push(module.add_builtin(args, mc)) } } @@ -1580,6 +1591,8 @@ pub enum MacroCall { }, ImageStore, MathFunction(MathFunction), + FindLsbUint, + FindMsbUint, BitfieldExtract, BitfieldInsert, Relational(RelationalFunction), @@ -1848,6 +1861,33 @@ impl MacroCall { Span::default(), body, ), + mc @ (MacroCall::FindLsbUint | MacroCall::FindMsbUint) => { + let fun = match mc { + MacroCall::FindLsbUint => MathFunction::FindLsb, + MacroCall::FindMsbUint => MathFunction::FindMsb, + _ => unreachable!(), + }; + let res = ctx.add_expression( + Expression::Math { + fun, + arg: args[0], + arg1: None, + arg2: None, + arg3: None, + }, + Span::default(), + body, + ); + ctx.add_expression( + Expression::As { + expr: res, + kind: Sk::Sint, + convert: Some(4), + }, + Span::default(), + body, + ) + } MacroCall::BitfieldInsert => { let conv_arg_2 = ctx.add_expression( Expression::As { diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 9f3f2a494..2d48d2ae4 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -821,13 +821,13 @@ impl<'a> ResolveContext<'a> { Mf::CountOneBits | Mf::ReverseBits | Mf::ExtractBits | - Mf::InsertBits => res_arg.clone(), + Mf::InsertBits | Mf::FindLsb | Mf::FindMsb => match *res_arg.inner_with(types) { - Ti::Scalar { kind: _, width } => - TypeResolution::Value(Ti::Scalar { kind: crate::ScalarKind::Sint, width }), - Ti::Vector { size, kind: _, width } => - TypeResolution::Value(Ti::Vector { size, kind: crate::ScalarKind::Sint, width }), + Ti::Scalar { kind: kind @ (crate::ScalarKind::Sint | crate::ScalarKind::Uint), width } => + TypeResolution::Value(Ti::Scalar { kind, width }), + Ti::Vector { size, kind: kind @ (crate::ScalarKind::Sint | crate::ScalarKind::Uint), width } => + TypeResolution::Value(Ti::Vector { size, kind, width }), ref other => return Err(ResolveError::IncompatibleOperands( format!("{:?}({:?})", fun, other) )), diff --git a/tests/in/bits.wgsl b/tests/in/bits.wgsl index 24101d993..1c78dae20 100644 --- a/tests/in/bits.wgsl +++ b/tests/in/bits.wgsl @@ -37,7 +37,7 @@ fn main() { u3 = extractBits(u3, 5u, 10u); u4 = extractBits(u4, 5u, 10u); i = firstTrailingBit(i); - i2 = firstTrailingBit(u2); + u2 = firstTrailingBit(u2); i3 = firstLeadingBit(i3); - i = firstLeadingBit(u); + u = firstLeadingBit(u); } diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl index 9cb276a9c..3166d0136 100644 --- a/tests/out/glsl/bits.main.Compute.glsl +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -88,11 +88,11 @@ void main() { int _e120 = i; i = findLSB(_e120); uvec2 _e122 = u2_; - i2_ = findLSB(_e122); + u2_ = uvec2(findLSB(_e122)); ivec3 _e124 = i3_; i3_ = findMSB(_e124); uint _e126 = u; - i = findMSB(_e126); + u = uint(findMSB(_e126)); return; } diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index cc3a5660a..88503320b 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -86,12 +86,12 @@ kernel void main_( metal::uint4 _e116 = u4_; u4_ = metal::extract_bits(_e116, 5u, 10u); int _e120 = i; - i = (((1 + int(metal::ctz(_e120))) % 33) - 1); + i = (((metal::ctz(_e120) + 1) % 33) - 1); metal::uint2 _e122 = u2_; - i2_ = (((1 + int2(metal::ctz(_e122))) % 33) - 1); + u2_ = (((metal::ctz(_e122) + 1) % 33) - 1); metal::int3 _e124 = i3_; - i3_ = (((1 + int3(metal::clz(_e124))) % 33) - 1); + i3_ = (((metal::clz(_e124) + 1) % 33) - 1); uint _e126 = u; - i = (((1 + int(metal::clz(_e126))) % 33) - 1); + u = (((metal::clz(_e126) + 1) % 33) - 1); return; } diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm index b224d04ab..6d224eee2 100644 --- a/tests/out/spv/bits.spvasm +++ b/tests/out/spv/bits.spvasm @@ -155,13 +155,13 @@ OpStore %33 %110 %112 = OpExtInst %4 %1 FindILsb %111 OpStore %19 %112 %113 = OpLoad %14 %29 -%114 = OpExtInst %11 %1 FindILsb %113 -OpStore %21 %114 +%114 = OpExtInst %14 %1 FindILsb %113 +OpStore %29 %114 %115 = OpLoad %12 %23 %116 = OpExtInst %12 %1 FindSMsb %115 OpStore %23 %116 %117 = OpLoad %6 %27 -%118 = OpExtInst %4 %1 FindUMsb %117 -OpStore %19 %118 +%118 = OpExtInst %6 %1 FindUMsb %117 +OpStore %27 %118 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index a7c3b01e4..2bdaf6e9f 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -82,10 +82,10 @@ fn main() { let _e120 = i; i = firstTrailingBit(_e120); let _e122 = u2_; - i2_ = firstTrailingBit(_e122); + u2_ = firstTrailingBit(_e122); let _e124 = i3_; i3_ = firstLeadingBit(_e124); let _e126 = u; - i = firstLeadingBit(_e126); + u = firstLeadingBit(_e126); return; } diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 977e1ba5b..012f51f46 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -79,29 +79,29 @@ fn main_1() { let _e232 = i4_; i4_ = firstTrailingBit(_e232); let _e235 = u; - i = firstTrailingBit(_e235); - let _e238 = u2_; - i2_ = firstTrailingBit(_e238); - let _e241 = u3_; - i3_ = firstTrailingBit(_e241); - let _e244 = u4_; - i4_ = firstTrailingBit(_e244); - let _e247 = i; - i = firstLeadingBit(_e247); - let _e250 = i2_; - i2_ = firstLeadingBit(_e250); - let _e253 = i3_; - i3_ = firstLeadingBit(_e253); - let _e256 = i4_; - i4_ = firstLeadingBit(_e256); - let _e259 = u; - i = firstLeadingBit(_e259); - let _e262 = u2_; - i2_ = firstLeadingBit(_e262); - let _e265 = u3_; - i3_ = firstLeadingBit(_e265); - let _e268 = u4_; - i4_ = firstLeadingBit(_e268); + i = i32(firstTrailingBit(_e235)); + let _e239 = u2_; + i2_ = vec2(firstTrailingBit(_e239)); + let _e243 = u3_; + i3_ = vec3(firstTrailingBit(_e243)); + let _e247 = u4_; + i4_ = vec4(firstTrailingBit(_e247)); + let _e251 = i; + i = firstLeadingBit(_e251); + let _e254 = i2_; + i2_ = firstLeadingBit(_e254); + let _e257 = i3_; + i3_ = firstLeadingBit(_e257); + let _e260 = i4_; + i4_ = firstLeadingBit(_e260); + let _e263 = u; + i = i32(firstLeadingBit(_e263)); + let _e267 = u2_; + i2_ = vec2(firstLeadingBit(_e267)); + let _e271 = u3_; + i3_ = vec3(firstLeadingBit(_e271)); + let _e275 = u4_; + i4_ = vec4(firstLeadingBit(_e275)); return; } From f76af4e53aaf354bfcf7d1b63b3416b9980a2534 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Fri, 29 Apr 2022 20:48:27 +0300 Subject: [PATCH 1709/2212] [wgsl] Remove buffer, texture, in, out, input, output from reserved keywords --- src/keywords/wgsl.rs | 6 ----- tests/in/extra.wgsl | 8 +++--- tests/in/interface.wgsl | 8 +++--- tests/in/interpolate.wgsl | 20 +++++++------- tests/in/push-constants.wgsl | 4 +-- tests/in/shadow.wgsl | 26 +++++++++---------- tests/in/skybox.wgsl | 4 +-- .../glsl/interpolate.vert_main.Vertex.glsl | 20 +++++++------- .../glsl/push-constants.main.Fragment.glsl | 4 +-- tests/out/glsl/shadow.fs_main.Fragment.glsl | 8 +++--- ...adow.fs_main_without_storage.Fragment.glsl | 8 +++--- tests/out/glsl/shadow.vs_main.Vertex.glsl | 10 +++---- tests/out/glsl/skybox.fs_main.Fragment.glsl | 4 +-- tests/out/hlsl/interface.hlsl | 8 +++--- tests/out/hlsl/interpolate.hlsl | 20 +++++++------- tests/out/hlsl/shadow.hlsl | 26 +++++++++---------- tests/out/hlsl/skybox.hlsl | 4 +-- tests/out/msl/extra.msl | 8 +++--- tests/out/msl/interface.msl | 8 +++--- tests/out/msl/interpolate.msl | 20 +++++++------- tests/out/msl/shadow.msl | 26 +++++++++---------- tests/out/msl/skybox.msl | 4 +-- tests/out/spv/interpolate.spvasm | 2 +- tests/out/spv/shadow.spvasm | 2 +- tests/out/wgsl/extra.wgsl | 8 +++--- tests/out/wgsl/interface.wgsl | 8 +++--- tests/out/wgsl/interpolate.wgsl | 20 +++++++------- tests/out/wgsl/shadow.wgsl | 26 +++++++++---------- tests/out/wgsl/skybox.wgsl | 4 +-- 29 files changed, 159 insertions(+), 165 deletions(-) diff --git a/src/keywords/wgsl.rs b/src/keywords/wgsl.rs index 36a8a55a1..0f6336255 100644 --- a/src/keywords/wgsl.rs +++ b/src/keywords/wgsl.rs @@ -134,7 +134,6 @@ pub const RESERVED: &[&str] = &[ "await", "become", "bf16", - "buffer", "cast", "catch", "cbuffer", @@ -217,10 +216,8 @@ pub const RESERVED: &[&str] = &[ "impl", "implements", "import", - "in", "inline", "inout", - "input", "instanceof", "interface", "invariant", @@ -276,8 +273,6 @@ pub const RESERVED: &[&str] = &[ "nullptr", "of", "operator", - "out", - "output", "package", "packoffset", "partition", @@ -348,7 +343,6 @@ pub const RESERVED: &[&str] = &[ "technique10", "technique11", "template", - "texture", "texture1D", "texture1DArray", "texture2D", diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl index 5ce69c14f..ef68f4aa8 100644 --- a/tests/in/extra.wgsl +++ b/tests/in/extra.wgsl @@ -10,10 +10,10 @@ struct FragmentIn { } @fragment -fn main(_in: FragmentIn) -> @location(0) vec4 { - if _in.primitive_index == pc.index { - return _in.color; +fn main(in: FragmentIn) -> @location(0) vec4 { + if in.primitive_index == pc.index { + return in.color; } else { - return vec4(vec3(1.0) - _in.color.rgb, _in.color.a); + return vec4(vec3(1.0) - in.color.rgb, in.color.a); } } diff --git a/tests/in/interface.wgsl b/tests/in/interface.wgsl index e4316a244..0f64f9564 100644 --- a/tests/in/interface.wgsl +++ b/tests/in/interface.wgsl @@ -23,17 +23,17 @@ struct FragmentOutput { @fragment fn fragment( - _in: VertexOutput, + in: VertexOutput, @builtin(front_facing) front_facing: bool, @builtin(sample_index) sample_index: u32, @builtin(sample_mask) sample_mask: u32, ) -> FragmentOutput { let mask = sample_mask & (1u << sample_index); let color = select(0.0, 1.0, front_facing); - return FragmentOutput(_in._varying, mask, color); + return FragmentOutput(in._varying, mask, color); } -var _output: array; +var output: array; @compute @workgroup_size(1) fn compute( @@ -43,7 +43,7 @@ fn compute( @builtin(workgroup_id) wg_id: vec3, @builtin(num_workgroups) num_wgs: vec3, ) { - _output[0] = global_id.x + local_id.x + local_index + wg_id.x + num_wgs.x; + output[0] = global_id.x + local_id.x + local_index + wg_id.x + num_wgs.x; } struct Input1 { diff --git a/tests/in/interpolate.wgsl b/tests/in/interpolate.wgsl index 6b8837903..2f6967b3e 100644 --- a/tests/in/interpolate.wgsl +++ b/tests/in/interpolate.wgsl @@ -13,18 +13,18 @@ struct FragmentInput { @vertex fn vert_main() -> FragmentInput { - var _out: FragmentInput; + var out: FragmentInput; - _out.position = vec4(2.0, 4.0, 5.0, 6.0); - _out._flat = 8u; - _out._linear = 27.0; - _out.linear_centroid = vec2(64.0, 125.0); - _out.linear_sample = vec3(216.0, 343.0, 512.0); - _out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); - _out.perspective_centroid = 2197.0; - _out.perspective_sample = 2744.0; + out.position = vec4(2.0, 4.0, 5.0, 6.0); + out._flat = 8u; + out._linear = 27.0; + out.linear_centroid = vec2(64.0, 125.0); + out.linear_sample = vec3(216.0, 343.0, 512.0); + out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + out.perspective_centroid = 2197.0; + out.perspective_sample = 2744.0; - return _out; + return out; } @fragment diff --git a/tests/in/push-constants.wgsl b/tests/in/push-constants.wgsl index 44152e561..cc8c4ab02 100644 --- a/tests/in/push-constants.wgsl +++ b/tests/in/push-constants.wgsl @@ -8,6 +8,6 @@ struct FragmentIn { } @fragment -fn main(_in: FragmentIn) -> @location(0) vec4 { - return _in.color * pc.multiplier; +fn main(in: FragmentIn) -> @location(0) vec4 { + return in.color * pc.multiplier; } diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 61c63d0dc..575018863 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -36,11 +36,11 @@ fn vs_main( ) -> VertexOutput { let w = u_entity.world; let world_pos = u_entity.world * vec4(position); - var _out: VertexOutput; - _out.world_normal = mat3x3(w.x.xyz, w.y.xyz, w.z.xyz) * vec3(normal.xyz); - _out.world_position = world_pos; - _out.proj_position = u_globals.view_proj * world_pos; - return _out; + var out: VertexOutput; + out.world_normal = mat3x3(w.x.xyz, w.y.xyz, w.z.xyz) * vec3(normal.xyz); + out.world_position = world_pos; + out.proj_position = u_globals.view_proj * world_pos; + return out; } // fragment shader @@ -81,16 +81,16 @@ let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); let c_max_lights: u32 = 10u; @fragment -fn fs_main(_in: VertexOutput) -> @location(0) vec4 { - let normal = normalize(_in.world_normal); +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + let normal = normalize(in.world_normal); // accumulate color var color: vec3 = c_ambient; for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i++) { let light = s_lights[i]; // project into the light space - let shadow = fetch_shadow(i, light.proj * _in.world_position); + let shadow = fetch_shadow(i, light.proj * in.world_position); // compute Lambertian diffuse term - let light_dir = normalize(light.pos.xyz - _in.world_position.xyz); + let light_dir = normalize(light.pos.xyz - in.world_position.xyz); let diffuse = max(0.0, dot(normal, light_dir)); // add light contribution color += shadow * diffuse * light.color.xyz; @@ -101,15 +101,15 @@ fn fs_main(_in: VertexOutput) -> @location(0) vec4 { // The fragment entrypoint used when storage buffers are not available for the lights @fragment -fn fs_main_without_storage(_in: VertexOutput) -> @location(0) vec4 { - let normal = normalize(_in.world_normal); +fn fs_main_without_storage(in: VertexOutput) -> @location(0) vec4 { + let normal = normalize(in.world_normal); var color: vec3 = c_ambient; for(var i = 0u; i < min(u_globals.num_lights.x, c_max_lights); i++) { // This line is the only difference from the entrypoint above. It uses the lights // uniform instead of the lights storage buffer let light = u_lights[i]; - let shadow = fetch_shadow(i, light.proj * _in.world_position); - let light_dir = normalize(light.pos.xyz - _in.world_position.xyz); + let shadow = fetch_shadow(i, light.proj * in.world_position); + let light_dir = normalize(light.pos.xyz - in.world_position.xyz); let diffuse = max(0.0, dot(normal, light_dir)); color += shadow * diffuse * light.color.xyz; } diff --git a/tests/in/skybox.wgsl b/tests/in/skybox.wgsl index 5d36951c6..f4cc37a44 100644 --- a/tests/in/skybox.wgsl +++ b/tests/in/skybox.wgsl @@ -33,6 +33,6 @@ var r_texture: texture_cube; var r_sampler: sampler; @fragment -fn fs_main(_in: VertexOutput) -> @location(0) vec4 { - return textureSample(r_texture, r_sampler, _in.uv); +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + return textureSample(r_texture, r_sampler, in.uv); } diff --git a/tests/out/glsl/interpolate.vert_main.Vertex.glsl b/tests/out/glsl/interpolate.vert_main.Vertex.glsl index 5155e7852..f423a3dc1 100644 --- a/tests/out/glsl/interpolate.vert_main.Vertex.glsl +++ b/tests/out/glsl/interpolate.vert_main.Vertex.glsl @@ -18,16 +18,16 @@ smooth centroid out float _vs2fs_location5; smooth sample out float _vs2fs_location6; void main() { - FragmentInput _out = FragmentInput(vec4(0.0), 0u, 0.0, vec2(0.0), vec3(0.0), vec4(0.0), 0.0, 0.0); - _out.position = vec4(2.0, 4.0, 5.0, 6.0); - _out._flat = 8u; - _out._linear = 27.0; - _out.linear_centroid = vec2(64.0, 125.0); - _out.linear_sample = vec3(216.0, 343.0, 512.0); - _out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); - _out.perspective_centroid = 2197.0; - _out.perspective_sample = 2744.0; - FragmentInput _e30 = _out; + FragmentInput out_ = FragmentInput(vec4(0.0), 0u, 0.0, vec2(0.0), vec3(0.0), vec4(0.0), 0.0, 0.0); + out_.position = vec4(2.0, 4.0, 5.0, 6.0); + out_._flat = 8u; + out_._linear = 27.0; + out_.linear_centroid = vec2(64.0, 125.0); + out_.linear_sample = vec3(216.0, 343.0, 512.0); + out_.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + out_.perspective_centroid = 2197.0; + out_.perspective_sample = 2744.0; + FragmentInput _e30 = out_; gl_Position = _e30.position; _vs2fs_location0 = _e30._flat; _vs2fs_location1 = _e30._linear; diff --git a/tests/out/glsl/push-constants.main.Fragment.glsl b/tests/out/glsl/push-constants.main.Fragment.glsl index d092ee05f..fa1be9f61 100644 --- a/tests/out/glsl/push-constants.main.Fragment.glsl +++ b/tests/out/glsl/push-constants.main.Fragment.glsl @@ -15,9 +15,9 @@ layout(location = 0) smooth in vec4 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { - FragmentIn _in = FragmentIn(_vs2fs_location0); + FragmentIn in_ = FragmentIn(_vs2fs_location0); float _e4 = pc.multiplier; - _fs2p_location0 = (_in.color * _e4); + _fs2p_location0 = (in_.color * _e4); return; } diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index fca6f9faa..fef409f10 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -45,10 +45,10 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } void main() { - VertexOutput _in = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); + VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); vec3 color = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i = 0u; - vec3 normal_1 = normalize(_in.world_normal); + vec3 normal_1 = normalize(in_.world_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -65,8 +65,8 @@ void main() { uint _e23 = i; Light light = _group_0_binding_1_fs[_e23]; uint _e26 = i; - float _e30 = fetch_shadow(_e26, (light.proj * _in.world_position)); - vec3 light_dir = normalize((light.pos.xyz - _in.world_position.xyz)); + float _e30 = fetch_shadow(_e26, (light.proj * in_.world_position)); + vec3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); float diffuse = max(0.0, dot(normal_1, light_dir)); vec3 _e40 = color; color = (_e40 + ((_e30 * diffuse) * light.color.xyz)); diff --git a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl index 4fc36ae9e..43f02cae1 100644 --- a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl @@ -45,10 +45,10 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { } void main() { - VertexOutput _in_1 = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); + VertexOutput in_1 = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); vec3 color_1 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i_1 = 0u; - vec3 normal_1 = normalize(_in_1.world_normal); + vec3 normal_1 = normalize(in_1.world_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -65,8 +65,8 @@ void main() { uint _e23 = i_1; Light light = _group_0_binding_1_fs[_e23]; uint _e26 = i_1; - float _e30 = fetch_shadow(_e26, (light.proj * _in_1.world_position)); - vec3 light_dir = normalize((light.pos.xyz - _in_1.world_position.xyz)); + float _e30 = fetch_shadow(_e26, (light.proj * in_1.world_position)); + vec3 light_dir = normalize((light.pos.xyz - in_1.world_position.xyz)); float diffuse = max(0.0, dot(normal_1, light_dir)); vec3 _e40 = color_1; color_1 = (_e40 + ((_e30 * diffuse) * light.color.xyz)); diff --git a/tests/out/glsl/shadow.vs_main.Vertex.glsl b/tests/out/glsl/shadow.vs_main.Vertex.glsl index 8c2aff6a3..dce8b2f7d 100644 --- a/tests/out/glsl/shadow.vs_main.Vertex.glsl +++ b/tests/out/glsl/shadow.vs_main.Vertex.glsl @@ -33,15 +33,15 @@ layout(location = 1) smooth out vec4 _vs2fs_location1; void main() { ivec4 position = _p2vs_location0; ivec4 normal = _p2vs_location1; - VertexOutput _out = VertexOutput(vec4(0.0), vec3(0.0), vec4(0.0)); + VertexOutput out_ = VertexOutput(vec4(0.0), vec3(0.0), vec4(0.0)); mat4x4 w = _group_1_binding_0_vs.world; mat4x4 _e7 = _group_1_binding_0_vs.world; vec4 world_pos = (_e7 * vec4(position)); - _out.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); - _out.world_position = world_pos; + out_.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); + out_.world_position = world_pos; mat4x4 _e25 = _group_0_binding_0_vs.view_proj; - _out.proj_position = (_e25 * world_pos); - VertexOutput _e27 = _out; + out_.proj_position = (_e25 * world_pos); + VertexOutput _e27 = out_; gl_Position = _e27.proj_position; _vs2fs_location0 = _e27.world_normal; _vs2fs_location1 = _e27.world_position; diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index 77d686530..2b151db2a 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -17,8 +17,8 @@ layout(location = 0) smooth in vec3 _vs2fs_location0; layout(location = 0) out vec4 _fs2p_location0; void main() { - VertexOutput _in = VertexOutput(gl_FragCoord, _vs2fs_location0); - vec4 _e5 = texture(_group_0_binding_1_fs, vec3(_in.uv)); + VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0); + vec4 _e5 = texture(_group_0_binding_1_fs, vec3(in_.uv)); _fs2p_location0 = _e5; return; } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 7cf1c67cb..341b515ec 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -24,7 +24,7 @@ struct Input2_ { uint index : SV_InstanceID; }; -groupshared uint _output[1]; +groupshared uint output[1]; struct VertexOutput_vertex { float _varying : LOC1; @@ -64,20 +64,20 @@ FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) { FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) { - VertexOutput _in = { fragmentinput_fragment.position_1, fragmentinput_fragment._varying_1 }; + VertexOutput in_ = { fragmentinput_fragment.position_1, fragmentinput_fragment._varying_1 }; bool front_facing = fragmentinput_fragment.front_facing_1; uint sample_index = fragmentinput_fragment.sample_index_1; uint sample_mask = fragmentinput_fragment.sample_mask_1; uint mask = (sample_mask & (1u << sample_index)); float color_1 = (front_facing ? 1.0 : 0.0); - const FragmentOutput fragmentoutput = ConstructFragmentOutput(_in._varying, mask, color_1); + const FragmentOutput fragmentoutput = ConstructFragmentOutput(in_._varying, mask, color_1); return fragmentoutput; } [numthreads(1, 1, 1)] void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThreadID, uint local_index : SV_GroupIndex, uint3 wg_id : SV_GroupID, uint3 num_wgs : SV_GroupID) { - _output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x); + output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x); return; } diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index 44d63239f..a9bd0c346 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -34,17 +34,17 @@ struct FragmentInput_frag_main { VertexOutput_vert_main vert_main() { - FragmentInput _out = (FragmentInput)0; + FragmentInput out_ = (FragmentInput)0; - _out.position = float4(2.0, 4.0, 5.0, 6.0); - _out._flat = 8u; - _out._linear = 27.0; - _out.linear_centroid = float2(64.0, 125.0); - _out.linear_sample = float3(216.0, 343.0, 512.0); - _out.perspective = float4(729.0, 1000.0, 1331.0, 1728.0); - _out.perspective_centroid = 2197.0; - _out.perspective_sample = 2744.0; - FragmentInput _expr30 = _out; + out_.position = float4(2.0, 4.0, 5.0, 6.0); + out_._flat = 8u; + out_._linear = 27.0; + out_.linear_centroid = float2(64.0, 125.0); + out_.linear_sample = float3(216.0, 343.0, 512.0); + out_.perspective = float4(729.0, 1000.0, 1331.0, 1728.0); + out_.perspective_centroid = 2197.0; + out_.perspective_sample = 2744.0; + FragmentInput _expr30 = out_; const FragmentInput fragmentinput = _expr30; const VertexOutput_vert_main fragmentinput_1 = { fragmentinput._flat, fragmentinput._linear, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position }; return fragmentinput_1; diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 4635f9f28..b66713092 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -62,16 +62,16 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords) VertexOutput_vs_main vs_main(int4 position : LOC0, int4 normal : LOC1) { - VertexOutput _out = (VertexOutput)0; + VertexOutput out_ = (VertexOutput)0; float4x4 w = u_entity.world; float4x4 _expr7 = u_entity.world; float4 world_pos = mul(float4(position), _expr7); - _out.world_normal = mul(float3(normal.xyz), float3x3(w[0].xyz, w[1].xyz, w[2].xyz)); - _out.world_position = world_pos; + out_.world_normal = mul(float3(normal.xyz), float3x3(w[0].xyz, w[1].xyz, w[2].xyz)); + out_.world_position = world_pos; float4x4 _expr25 = u_globals.view_proj; - _out.proj_position = mul(world_pos, _expr25); - VertexOutput _expr27 = _out; + out_.proj_position = mul(world_pos, _expr25); + VertexOutput _expr27 = out_; const VertexOutput vertexoutput = _expr27; const VertexOutput_vs_main vertexoutput_1 = { vertexoutput.world_normal, vertexoutput.world_position, vertexoutput.proj_position }; return vertexoutput_1; @@ -79,11 +79,11 @@ VertexOutput_vs_main vs_main(int4 position : LOC0, int4 normal : LOC1) float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { - VertexOutput _in = { fragmentinput_fs_main.proj_position_1, fragmentinput_fs_main.world_normal_1, fragmentinput_fs_main.world_position_1 }; + VertexOutput in_ = { fragmentinput_fs_main.proj_position_1, fragmentinput_fs_main.world_normal_1, fragmentinput_fs_main.world_position_1 }; float3 color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i = 0u; - float3 normal_1 = normalize(_in.world_normal); + float3 normal_1 = normalize(in_.world_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -100,8 +100,8 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 uint _expr23 = i; Light light = {float4x4(asfloat(s_lights.Load4(_expr23*96+0+0)), asfloat(s_lights.Load4(_expr23*96+0+16)), asfloat(s_lights.Load4(_expr23*96+0+32)), asfloat(s_lights.Load4(_expr23*96+0+48))), asfloat(s_lights.Load4(_expr23*96+64)), asfloat(s_lights.Load4(_expr23*96+80))}; uint _expr26 = i; - const float _e30 = fetch_shadow(_expr26, mul(_in.world_position, light.proj)); - float3 light_dir = normalize((light.pos.xyz - _in.world_position.xyz)); + const float _e30 = fetch_shadow(_expr26, mul(in_.world_position, light.proj)); + float3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); float diffuse = max(0.0, dot(normal_1, light_dir)); float3 _expr40 = color; color = (_expr40 + ((_e30 * diffuse) * light.color.xyz)); @@ -113,11 +113,11 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 float4 fs_main_without_storage(FragmentInput_fs_main_without_storage fragmentinput_fs_main_without_storage) : SV_Target0 { - VertexOutput _in_1 = { fragmentinput_fs_main_without_storage.proj_position_2, fragmentinput_fs_main_without_storage.world_normal_2, fragmentinput_fs_main_without_storage.world_position_2 }; + VertexOutput in_1 = { fragmentinput_fs_main_without_storage.proj_position_2, fragmentinput_fs_main_without_storage.world_normal_2, fragmentinput_fs_main_without_storage.world_position_2 }; float3 color_1 = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); uint i_1 = 0u; - float3 normal_2 = normalize(_in_1.world_normal); + float3 normal_2 = normalize(in_1.world_normal); bool loop_init_1 = true; while(true) { if (!loop_init_1) { @@ -134,8 +134,8 @@ float4 fs_main_without_storage(FragmentInput_fs_main_without_storage fragmentinp uint _expr23 = i_1; Light light_1 = u_lights[_expr23]; uint _expr26 = i_1; - const float _e30 = fetch_shadow(_expr26, mul(_in_1.world_position, light_1.proj)); - float3 light_dir_1 = normalize((light_1.pos.xyz - _in_1.world_position.xyz)); + const float _e30 = fetch_shadow(_expr26, mul(in_1.world_position, light_1.proj)); + float3 light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); float diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); float3 _expr40 = color_1; color_1 = (_expr40 + ((_e30 * diffuse_1) * light_1.color.xyz)); diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 6e119903d..3664c497c 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -59,7 +59,7 @@ VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { - VertexOutput _in = { fragmentinput_fs_main.position_1, fragmentinput_fs_main.uv_1 }; - float4 _expr5 = r_texture.Sample(r_sampler, _in.uv); + VertexOutput in_ = { fragmentinput_fs_main.position_1, fragmentinput_fs_main.uv_1 }; + float4 _expr5 = r_texture.Sample(r_sampler, in_.uv); return _expr5; } diff --git a/tests/out/msl/extra.msl b/tests/out/msl/extra.msl index 683b074f2..8288dfad9 100644 --- a/tests/out/msl/extra.msl +++ b/tests/out/msl/extra.msl @@ -25,11 +25,11 @@ fragment main_Output main_( , uint primitive_index [[primitive_id]] , constant PushConstants& pc [[buffer(1)]] ) { - const FragmentIn _in = { varyings.color, primitive_index }; + const FragmentIn in = { varyings.color, primitive_index }; uint _e4 = pc.index; - if (_in.primitive_index == _e4) { - return main_Output { _in.color }; + if (in.primitive_index == _e4) { + return main_Output { in.color }; } else { - return main_Output { metal::float4(metal::float3(1.0) - _in.color.xyz, _in.color.w) }; + return main_Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) }; } } diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 7cb6a401f..9b8013531 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -58,10 +58,10 @@ fragment fragment_Output fragment_( , uint sample_index [[sample_id]] , uint sample_mask [[sample_mask]] ) { - const VertexOutput _in = { position, varyings_1._varying }; + const VertexOutput in = { position, varyings_1._varying }; uint mask = sample_mask & (1u << sample_index); float color_1 = front_facing ? 1.0 : 0.0; - const auto _tmp = FragmentOutput {_in._varying, mask, color_1}; + const auto _tmp = FragmentOutput {in._varying, mask, color_1}; return fragment_Output { _tmp.depth, _tmp.sample_mask, _tmp.color }; } @@ -74,9 +74,9 @@ kernel void compute_( , uint local_index [[thread_index_in_threadgroup]] , metal::uint3 wg_id [[threadgroup_position_in_grid]] , metal::uint3 num_wgs [[threadgroups_per_grid]] -, threadgroup type_4& _output +, threadgroup type_4& output ) { - _output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x; + output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x; return; } diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl index cefc07ab9..4dd84c623 100644 --- a/tests/out/msl/interpolate.msl +++ b/tests/out/msl/interpolate.msl @@ -27,16 +27,16 @@ struct vert_mainOutput { }; vertex vert_mainOutput vert_main( ) { - FragmentInput _out; - _out.position = metal::float4(2.0, 4.0, 5.0, 6.0); - _out._flat = 8u; - _out._linear = 27.0; - _out.linear_centroid = metal::float2(64.0, 125.0); - _out.linear_sample = metal::float3(216.0, 343.0, 512.0); - _out.perspective = metal::float4(729.0, 1000.0, 1331.0, 1728.0); - _out.perspective_centroid = 2197.0; - _out.perspective_sample = 2744.0; - FragmentInput _e30 = _out; + FragmentInput out; + out.position = metal::float4(2.0, 4.0, 5.0, 6.0); + out._flat = 8u; + out._linear = 27.0; + out.linear_centroid = metal::float2(64.0, 125.0); + out.linear_sample = metal::float3(216.0, 343.0, 512.0); + out.perspective = metal::float4(729.0, 1000.0, 1331.0, 1728.0); + out.perspective_centroid = 2197.0; + out.perspective_sample = 2744.0; + FragmentInput _e30 = out; const auto _tmp = _e30; return vert_mainOutput { _tmp.position, _tmp._flat, _tmp._linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample }; } diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index ba723742a..5286b0bd0 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -65,15 +65,15 @@ vertex vs_mainOutput vs_main( ) { const auto position = varyings.position; const auto normal = varyings.normal; - VertexOutput _out; + VertexOutput out; metal::float4x4 w = u_entity.world; metal::float4x4 _e7 = u_entity.world; metal::float4 world_pos = _e7 * static_cast(position); - _out.world_normal = metal::float3x3(w[0].xyz, w[1].xyz, w[2].xyz) * static_cast(normal.xyz); - _out.world_position = world_pos; + out.world_normal = metal::float3x3(w[0].xyz, w[1].xyz, w[2].xyz) * static_cast(normal.xyz); + out.world_position = world_pos; metal::float4x4 _e25 = u_globals.view_proj; - _out.proj_position = _e25 * world_pos; - VertexOutput _e27 = _out; + out.proj_position = _e25 * world_pos; + VertexOutput _e27 = out; const auto _tmp = _e27; return vs_mainOutput { _tmp.proj_position, _tmp.world_normal, _tmp.world_position }; } @@ -96,10 +96,10 @@ fragment fs_mainOutput fs_main( , metal::sampler sampler_shadow [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - const VertexOutput _in = { proj_position, varyings_1.world_normal, varyings_1.world_position }; + const VertexOutput in = { proj_position, varyings_1.world_normal, varyings_1.world_position }; metal::float3 color = c_ambient; uint i = 0u; - metal::float3 normal_1 = metal::normalize(_in.world_normal); + metal::float3 normal_1 = metal::normalize(in.world_normal); bool loop_init = true; while(true) { if (!loop_init) { @@ -116,8 +116,8 @@ fragment fs_mainOutput fs_main( uint _e23 = i; Light light = s_lights[_e23]; uint _e26 = i; - float _e30 = fetch_shadow(_e26, light.proj * _in.world_position, t_shadow, sampler_shadow); - metal::float3 light_dir = metal::normalize(light.pos.xyz - _in.world_position.xyz); + float _e30 = fetch_shadow(_e26, light.proj * in.world_position, t_shadow, sampler_shadow); + metal::float3 light_dir = metal::normalize(light.pos.xyz - in.world_position.xyz); float diffuse = metal::max(0.0, metal::dot(normal_1, light_dir)); metal::float3 _e40 = color; color = _e40 + ((_e30 * diffuse) * light.color.xyz); @@ -144,10 +144,10 @@ fragment fs_main_without_storageOutput fs_main_without_storage( , metal::depth2d_array t_shadow [[user(fake0)]] , metal::sampler sampler_shadow [[user(fake0)]] ) { - const VertexOutput _in_1 = { proj_position_1, varyings_2.world_normal, varyings_2.world_position }; + const VertexOutput in_1 = { proj_position_1, varyings_2.world_normal, varyings_2.world_position }; metal::float3 color_1 = c_ambient; uint i_1 = 0u; - metal::float3 normal_2 = metal::normalize(_in_1.world_normal); + metal::float3 normal_2 = metal::normalize(in_1.world_normal); bool loop_init_1 = true; while(true) { if (!loop_init_1) { @@ -164,8 +164,8 @@ fragment fs_main_without_storageOutput fs_main_without_storage( uint _e23 = i_1; Light light_1 = u_lights.inner[_e23]; uint _e26 = i_1; - float _e30 = fetch_shadow(_e26, light_1.proj * _in_1.world_position, t_shadow, sampler_shadow); - metal::float3 light_dir_1 = metal::normalize(light_1.pos.xyz - _in_1.world_position.xyz); + float _e30 = fetch_shadow(_e26, light_1.proj * in_1.world_position, t_shadow, sampler_shadow); + metal::float3 light_dir_1 = metal::normalize(light_1.pos.xyz - in_1.world_position.xyz); float diffuse_1 = metal::max(0.0, metal::dot(normal_2, light_dir_1)); metal::float3 _e40 = color_1; color_1 = _e40 + ((_e30 * diffuse_1) * light_1.color.xyz); diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index f6b8c006f..bf8725043 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -60,7 +60,7 @@ fragment fs_mainOutput fs_main( metal::min_filter::linear, metal::coord::normalized ); - const VertexOutput _in = { position, varyings_1.uv }; - metal::float4 _e5 = r_texture.sample(r_sampler, _in.uv); + const VertexOutput in = { position, varyings_1.uv }; + metal::float4 _e5 = r_texture.sample(r_sampler, in.uv); return fs_mainOutput { _e5 }; } diff --git a/tests/out/spv/interpolate.spvasm b/tests/out/spv/interpolate.spvasm index 7c48cb646..da47ff164 100644 --- a/tests/out/spv/interpolate.spvasm +++ b/tests/out/spv/interpolate.spvasm @@ -19,7 +19,7 @@ OpMemberName %25 5 "perspective" OpMemberName %25 6 "perspective_centroid" OpMemberName %25 7 "perspective_sample" OpName %25 "FragmentInput" -OpName %26 "_out" +OpName %26 "out" OpName %29 "position" OpName %31 "_flat" OpName %33 "_linear" diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index 9e42405fb..aeb85c96b 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -37,7 +37,7 @@ OpName %45 "sampler_shadow" OpName %48 "light_id" OpName %49 "homogeneous_coords" OpName %50 "fetch_shadow" -OpName %80 "_out" +OpName %80 "out" OpName %83 "position" OpName %86 "normal" OpName %88 "proj_position" diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index a4542763b..34a2e176c 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -11,11 +11,11 @@ struct FragmentIn { var pc: PushConstants; @fragment -fn main(_in: FragmentIn) -> @location(0) vec4 { +fn main(in: FragmentIn) -> @location(0) vec4 { let _e4 = pc.index; - if (_in.primitive_index == _e4) { - return _in.color; + if (in.primitive_index == _e4) { + return in.color; } else { - return vec4((vec3(1.0) - _in.color.xyz), _in.color.w); + return vec4((vec3(1.0) - in.color.xyz), in.color.w); } } diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index eda7d72de..a17865c5a 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -17,7 +17,7 @@ struct Input2_ { @builtin(instance_index) index: u32, } -var _output: array; +var output: array; @vertex fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) instance_index: u32, @location(10) color: u32) -> VertexOutput { @@ -26,15 +26,15 @@ fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) ins } @fragment -fn fragment(_in: VertexOutput, @builtin(front_facing) front_facing: bool, @builtin(sample_index) sample_index: u32, @builtin(sample_mask) sample_mask: u32) -> FragmentOutput { +fn fragment(in: VertexOutput, @builtin(front_facing) front_facing: bool, @builtin(sample_index) sample_index: u32, @builtin(sample_mask) sample_mask: u32) -> FragmentOutput { let mask: u32 = (sample_mask & (1u << sample_index)); let color_1: f32 = select(0.0, 1.0, front_facing); - return FragmentOutput(_in._varying, mask, color_1); + return FragmentOutput(in._varying, mask, color_1); } @compute @workgroup_size(1, 1, 1) fn compute(@builtin(global_invocation_id) global_id: vec3, @builtin(local_invocation_id) local_id: vec3, @builtin(local_invocation_index) local_index: u32, @builtin(workgroup_id) wg_id: vec3, @builtin(num_workgroups) num_wgs: vec3) { - _output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x); + output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x); return; } diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index dbccb1ac8..d566aae80 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -11,17 +11,17 @@ struct FragmentInput { @vertex fn vert_main() -> FragmentInput { - var _out: FragmentInput; + var out: FragmentInput; - _out.position = vec4(2.0, 4.0, 5.0, 6.0); - _out._flat = 8u; - _out._linear = 27.0; - _out.linear_centroid = vec2(64.0, 125.0); - _out.linear_sample = vec3(216.0, 343.0, 512.0); - _out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); - _out.perspective_centroid = 2197.0; - _out.perspective_sample = 2744.0; - let _e30 = _out; + out.position = vec4(2.0, 4.0, 5.0, 6.0); + out._flat = 8u; + out._linear = 27.0; + out.linear_centroid = vec2(64.0, 125.0); + out.linear_sample = vec3(216.0, 343.0, 512.0); + out.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0); + out.perspective_centroid = 2197.0; + out.perspective_sample = 2744.0; + let _e30 = out; return _e30; } diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 653264454..8bb6b5813 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -49,25 +49,25 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { @vertex fn vs_main(@location(0) position: vec4, @location(1) normal: vec4) -> VertexOutput { - var _out: VertexOutput; + var out: VertexOutput; let w = u_entity.world; let _e7 = u_entity.world; let world_pos = (_e7 * vec4(position)); - _out.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); - _out.world_position = world_pos; + out.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); + out.world_position = world_pos; let _e25 = u_globals.view_proj; - _out.proj_position = (_e25 * world_pos); - let _e27 = _out; + out.proj_position = (_e25 * world_pos); + let _e27 = out; return _e27; } @fragment -fn fs_main(_in: VertexOutput) -> @location(0) vec4 { +fn fs_main(in: VertexOutput) -> @location(0) vec4 { var color: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i: u32 = 0u; - let normal_1 = normalize(_in.world_normal); + let normal_1 = normalize(in.world_normal); loop { let _e14 = i; let _e17 = u_globals.num_lights.x; @@ -78,8 +78,8 @@ fn fs_main(_in: VertexOutput) -> @location(0) vec4 { let _e23 = i; let light = s_lights[_e23]; let _e26 = i; - let _e30 = fetch_shadow(_e26, (light.proj * _in.world_position)); - let light_dir = normalize((light.pos.xyz - _in.world_position.xyz)); + let _e30 = fetch_shadow(_e26, (light.proj * in.world_position)); + let light_dir = normalize((light.pos.xyz - in.world_position.xyz)); let diffuse = max(0.0, dot(normal_1, light_dir)); let _e40 = color; color = (_e40 + ((_e30 * diffuse) * light.color.xyz)); @@ -94,11 +94,11 @@ fn fs_main(_in: VertexOutput) -> @location(0) vec4 { } @fragment -fn fs_main_without_storage(_in_1: VertexOutput) -> @location(0) vec4 { +fn fs_main_without_storage(in_1: VertexOutput) -> @location(0) vec4 { var color_1: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); var i_1: u32 = 0u; - let normal_2 = normalize(_in_1.world_normal); + let normal_2 = normalize(in_1.world_normal); loop { let _e14 = i_1; let _e17 = u_globals.num_lights.x; @@ -109,8 +109,8 @@ fn fs_main_without_storage(_in_1: VertexOutput) -> @location(0) vec4 { let _e23 = i_1; let light_1 = u_lights[_e23]; let _e26 = i_1; - let _e30 = fetch_shadow(_e26, (light_1.proj * _in_1.world_position)); - let light_dir_1 = normalize((light_1.pos.xyz - _in_1.world_position.xyz)); + let _e30 = fetch_shadow(_e26, (light_1.proj * in_1.world_position)); + let light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); let diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); let _e40 = color_1; color_1 = (_e40 + ((_e30 * diffuse_1) * light_1.color.xyz)); diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index f759f48de..c9be90196 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -35,7 +35,7 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput { } @fragment -fn fs_main(_in: VertexOutput) -> @location(0) vec4 { - let _e5 = textureSample(r_texture, r_sampler, _in.uv); +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + let _e5 = textureSample(r_texture, r_sampler, in.uv); return _e5; } From a06b604b80aacbebea20e67210eb9438f4601f6c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 29 Apr 2022 14:35:48 -0700 Subject: [PATCH 1710/2212] Rename type flags to better align with the current WGSL spec. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TypeFlags::INTERFACE -> TypeFlags::IO_SHARED (WGSL §4.4.4's "IO-shareable types") TypeFLags::HOST_SHARED -> TypeFlags::HOST_SHAREABLE (WGSL §4.4.5's "Host-shareable types") --- src/valid/interface.rs | 12 +++++++++--- src/valid/type.rs | 36 +++++++++++++++++++----------------- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 50c2fe1e9..1cab7e6af 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -364,7 +364,7 @@ impl super::Validator { )); } } - (TypeFlags::DATA | TypeFlags::HOST_SHARED, true) + (TypeFlags::DATA | TypeFlags::HOST_SHAREABLE, true) } crate::AddressSpace::Uniform => { if let Err((ty_handle, disalignment)) = type_info.uniform_layout { @@ -377,7 +377,10 @@ impl super::Validator { } } ( - TypeFlags::DATA | TypeFlags::COPY | TypeFlags::SIZED | TypeFlags::HOST_SHARED, + TypeFlags::DATA + | TypeFlags::COPY + | TypeFlags::SIZED + | TypeFlags::HOST_SHAREABLE, true, ) } @@ -402,7 +405,10 @@ impl super::Validator { )); } ( - TypeFlags::DATA | TypeFlags::COPY | TypeFlags::HOST_SHARED | TypeFlags::SIZED, + TypeFlags::DATA + | TypeFlags::COPY + | TypeFlags::HOST_SHAREABLE + | TypeFlags::SIZED, false, ) } diff --git a/src/valid/type.rs b/src/valid/type.rs index 7c80adf76..201dc1d50 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -40,14 +40,15 @@ bitflags::bitflags! { /// The data can be copied around. const COPY = 0x4; - /// Can be be used for interfacing between pipeline stages. + /// Can be be used for user-defined IO between pipeline stages. /// - /// This includes non-bool scalars and vectors, matrices, and structs - /// and arrays containing only interface types. - const INTERFACE = 0x8; + /// This covers anything that can be in [`Location`] binding: + /// non-bool scalars and vectors, matrices, and structs and + /// arrays containing only interface types. + const IO_SHAREABLE = 0x8; /// Can be used for host-shareable structures. - const HOST_SHARED = 0x10; + const HOST_SHAREABLE = 0x10; /// This type can be passed as a function argument. const ARGUMENT = 0x40; @@ -214,8 +215,8 @@ impl super::Validator { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY - | TypeFlags::INTERFACE - | TypeFlags::HOST_SHARED + | TypeFlags::IO_SHAREABLE + | TypeFlags::HOST_SHAREABLE | TypeFlags::ARGUMENT, width as u32, ) @@ -229,8 +230,8 @@ impl super::Validator { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY - | TypeFlags::INTERFACE - | TypeFlags::HOST_SHARED + | TypeFlags::IO_SHAREABLE + | TypeFlags::HOST_SHAREABLE | TypeFlags::ARGUMENT, count * (width as u32), ) @@ -248,8 +249,8 @@ impl super::Validator { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY - | TypeFlags::INTERFACE - | TypeFlags::HOST_SHARED + | TypeFlags::IO_SHAREABLE + | TypeFlags::HOST_SHAREABLE | TypeFlags::ARGUMENT, count * (width as u32), ) @@ -263,7 +264,7 @@ impl super::Validator { return Err(TypeError::InvalidAtomicWidth(kind, width)); } TypeInfo::new( - TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED, + TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHAREABLE, width as u32, ) } @@ -445,7 +446,8 @@ impl super::Validator { } }; - let base_mask = TypeFlags::COPY | TypeFlags::HOST_SHARED | TypeFlags::INTERFACE; + let base_mask = + TypeFlags::COPY | TypeFlags::HOST_SHAREABLE | TypeFlags::IO_SHAREABLE; TypeInfo { flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag, uniform_layout, @@ -461,8 +463,8 @@ impl super::Validator { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY - | TypeFlags::HOST_SHARED - | TypeFlags::INTERFACE + | TypeFlags::HOST_SHAREABLE + | TypeFlags::IO_SHAREABLE | TypeFlags::ARGUMENT, 1, ); @@ -480,7 +482,7 @@ impl super::Validator { if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); } - if !base_info.flags.contains(TypeFlags::HOST_SHARED) { + if !base_info.flags.contains(TypeFlags::HOST_SHAREABLE) { if ti.uniform_layout.is_ok() { ti.uniform_layout = Err((member.ty, Disalignment::NonHostShareable)); } @@ -495,7 +497,7 @@ impl super::Validator { // to not bother with offsets/alignments if they are never // used for host sharing. if member.offset == 0 { - ti.flags.set(TypeFlags::HOST_SHARED, false); + ti.flags.set(TypeFlags::HOST_SHAREABLE, false); } else { return Err(TypeError::MemberOverlap { index: i as u32, From 5f4a070504a4bda45f26d0aad69b9e610c67ff5a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 29 Apr 2022 20:57:11 -0700 Subject: [PATCH 1711/2212] Simplify type handling in VaryingContext. When `VaryingContext::validate` discovers that it needs to examine each member of a struct, pass the type as an argument to `validate` and `validate_impl`, rather than mutating `self.ty` on each iteration of the loop. This matches the way we're handling the binding, and avoids stashing per-iteration state in a surprising place. This should have no effect on execution. --- src/valid/interface.rs | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 1cab7e6af..79393f58f 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -98,7 +98,6 @@ fn storage_usage(access: crate::StorageAccess) -> GlobalUse { } struct VaryingContext<'a> { - ty: Handle, stage: crate::ShaderStage, output: bool, types: &'a UniqueArena, @@ -108,12 +107,16 @@ struct VaryingContext<'a> { } impl VaryingContext<'_> { - fn validate_impl(&mut self, binding: &crate::Binding) -> Result<(), VaryingError> { + fn validate_impl( + &mut self, + ty: Handle, + binding: &crate::Binding, + ) -> Result<(), VaryingError> { use crate::{ BuiltIn as Bi, ScalarKind as Sk, ShaderStage as St, TypeInner as Ti, VectorSize as Vs, }; - let ty_inner = &self.types[self.ty].inner; + let ty_inner = &self.types[ty].inner; match *binding { crate::Binding::BuiltIn(built_in) => { // Ignore the `invariant` field for the sake of duplicate checks, @@ -294,7 +297,7 @@ impl VaryingContext<'_> { return Err(VaryingError::InvalidInterpolation); } } - None => return Err(VaryingError::InvalidType(self.ty)), + None => return Err(VaryingError::InvalidType(ty)), } } } @@ -302,19 +305,22 @@ impl VaryingContext<'_> { Ok(()) } - fn validate(&mut self, binding: Option<&crate::Binding>) -> Result<(), WithSpan> { - let span_context = self.types.get_span_context(self.ty); + fn validate( + &mut self, + ty: Handle, + binding: Option<&crate::Binding>, + ) -> Result<(), WithSpan> { + let span_context = self.types.get_span_context(ty); match binding { Some(binding) => self - .validate_impl(binding) + .validate_impl(ty, binding) .map_err(|e| e.with_span_context(span_context)), None => { - match self.types[self.ty].inner { + match self.types[ty].inner { //TODO: check the member types crate::TypeInner::Struct { ref members, .. } => { for (index, member) in members.iter().enumerate() { - self.ty = member.ty; - let span_context = self.types.get_span_context(self.ty); + let span_context = self.types.get_span_context(ty); match member.binding { None => { return Err(VaryingError::MemberMissingBinding(index as u32) @@ -322,7 +328,7 @@ impl VaryingContext<'_> { } // TODO: shouldn't this be validate? Some(ref binding) => self - .validate_impl(binding) + .validate_impl(member.ty, binding) .map_err(|e| e.with_span_context(span_context))?, } } @@ -476,7 +482,6 @@ impl super::Validator { // TODO: add span info to function arguments for (index, fa) in ep.function.arguments.iter().enumerate() { let mut ctx = VaryingContext { - ty: fa.ty, stage: ep.stage, output: false, types: &module.types, @@ -484,7 +489,7 @@ impl super::Validator { built_ins: &mut argument_built_ins, capabilities: self.capabilities, }; - ctx.validate(fa.binding.as_ref()) + ctx.validate(fa.ty, fa.binding.as_ref()) .map_err_inner(|e| EntryPointError::Argument(index as u32, e).with_span())?; } @@ -492,7 +497,6 @@ impl super::Validator { if let Some(ref fr) = ep.function.result { let mut result_built_ins = crate::FastHashSet::default(); let mut ctx = VaryingContext { - ty: fr.ty, stage: ep.stage, output: true, types: &module.types, @@ -500,7 +504,7 @@ impl super::Validator { built_ins: &mut result_built_ins, capabilities: self.capabilities, }; - ctx.validate(fr.binding.as_ref()) + ctx.validate(fr.ty, fr.binding.as_ref()) .map_err_inner(|e| EntryPointError::Result(e).with_span())?; } From e8723219b71aa7daf84422083d603165961770e4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 29 Apr 2022 21:29:29 -0700 Subject: [PATCH 1712/2212] Validate `ValuePointer` exactly like a `Pointer` to a `Scalar`. A `ValuePointer` type should always be handled exactly like the equivalent `Pointer` to `Scalar` type. To this end: - Adjust the handling of `TypeFlags::ARGUMENT`. - Neither `Pointer` nor `ValuePointer` types are ever `DATA`. --- src/valid/type.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/valid/type.rs b/src/valid/type.rs index 201dc1d50..9d77342a6 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -323,12 +323,28 @@ impl super::Validator { size: _, kind, width, - space: _, + space, } => { + // ValuePointer should be treated the same way as the equivalent + // Pointer / Scalar / Vector combination, so each step in those + // variants' match arms should have a counterpart here. + // + // However, some cases are trivial: All our implicit base types + // are DATA and SIZED, so we can never return + // `InvalidPointerBase` or `InvalidPointerToUnsized`. if !self.check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } - TypeInfo::new(TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY, 0) + + use crate::AddressSpace as As; + let argument_flag = match space { + As::Function | As::Private | As::WorkGroup => TypeFlags::ARGUMENT, + As::Uniform | As::Storage { .. } | As::Handle | As::PushConstant => { + TypeFlags::empty() + } + }; + + TypeInfo::new(argument_flag | TypeFlags::SIZED | TypeFlags::COPY, 0) } Ti::Array { base, size, stride } => { if base >= handle { From 7b8d257043b9db9af6118cff4782526e848d4e73 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 29 Apr 2022 21:00:15 -0700 Subject: [PATCH 1713/2212] Correct error message for `Handle` index overflow. This function is used from both `Arena` and `UniqueArena`. When its code moved from `Arena` to `Handle`, the error message was adapted incorrectly. --- src/arena.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/arena.rs b/src/arena.rs index 77f425d1f..c7611ebf9 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -101,7 +101,7 @@ impl Handle { let handle_index = u32::try_from(index + 1) .ok() .and_then(Index::new) - .expect("Failed to insert into UniqueArena. Handle overflows"); + .expect("Failed to insert into arena. Handle overflows"); Handle::new(handle_index) } From a99fc27dc1ae1b03dcd33502a8740e8928b2a25d Mon Sep 17 00:00:00 2001 From: Noel Tautges Date: Sat, 30 Apr 2022 00:43:16 -0500 Subject: [PATCH 1714/2212] Change `!0` to `::MAX` or `-1`, depending on signedness --- cli/src/main.rs | 2 +- src/arena.rs | 2 +- src/back/mod.rs | 2 +- src/back/msl/writer.rs | 4 ++-- src/front/spv/mod.rs | 2 +- src/front/spv/null.rs | 2 +- src/valid/expression.rs | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 30732764d..2e4b1b3c3 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -340,7 +340,7 @@ fn run() -> Result<(), Box> { println!("Validation successful"); return Ok(()); } else { - std::process::exit(!0); + std::process::exit(-1); } } diff --git a/src/arena.rs b/src/arena.rs index c7611ebf9..1f970524e 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -77,7 +77,7 @@ impl hash::Hash for Handle { impl Handle { #[cfg(test)] pub const DUMMY: Self = Handle { - index: unsafe { NonZeroU32::new_unchecked(!0) }, + index: unsafe { NonZeroU32::new_unchecked(u32::MAX) }, marker: PhantomData, }; diff --git a/src/back/mod.rs b/src/back/mod.rs index daec79a8c..16b503cfb 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -131,7 +131,7 @@ impl crate::Expression { const fn bake_ref_count(&self) -> usize { match *self { // accesses are never cached, only loads are - crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => !0, + crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => usize::MAX, // sampling may use the control flow, and image ops look better by themselves crate::Expression::ImageSample { .. } | crate::Expression::ImageLoad { .. } => 1, // derivatives use the control flow diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 1e36b5a9b..3448d0c00 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3878,7 +3878,7 @@ fn test_stack_size() { { // check expression stack - let mut addresses = !0usize..0usize; + let mut addresses = usize::MAX..0usize; for pointer in writer.put_expression_stack_pointers { addresses.start = addresses.start.min(pointer as usize); addresses.end = addresses.end.max(pointer as usize); @@ -3893,7 +3893,7 @@ fn test_stack_size() { { // check block stack - let mut addresses = !0usize..0usize; + let mut addresses = usize::MAX..0usize; for pointer in writer.put_block_stack_pointers { addresses.start = addresses.start.min(pointer as usize); addresses.end = addresses.end.max(pointer as usize); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 141970e6f..5dc8b82e5 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2453,7 +2453,7 @@ impl> Parser { let mut max_component = 0; for _ in 5..inst.wc as usize { let mut index = self.next()?; - if index == !0 { + if index == u32::MAX { // treat Undefined as X index = 0; } diff --git a/src/front/spv/null.rs b/src/front/spv/null.rs index ca62b8454..85350c563 100644 --- a/src/front/spv/null.rs +++ b/src/front/spv/null.rs @@ -158,7 +158,7 @@ pub fn generate_default_built_in( width: 4, }, Some(crate::BuiltIn::SampleMask) => crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(!0), + value: crate::ScalarValue::Uint(u64::MAX), width: 4, }, //Note: `crate::BuiltIn::ClipDistance` is intentionally left for the default path diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 9d6b85271..f433b456b 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -241,7 +241,7 @@ impl super::Validator { size: crate::ArraySize::Constant(handle), .. } => module.constants[handle].to_array_length().unwrap(), - Ti::Array { .. } | Ti::BindingArray { .. } => !0, // can't statically know, but need run-time checks + Ti::Array { .. } | Ti::BindingArray { .. } => u32::MAX, // can't statically know, but need run-time checks Ti::Pointer { base, .. } if top_level => { resolve_index_limit(module, top, &module.types[base].inner, false)? } From 115a8109814667d5adeedf55e8192fcaafbb691e Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 30 Apr 2022 12:09:35 -0700 Subject: [PATCH 1715/2212] [glsl-in] Use `std::mem::take` as appropriate. (#1878) --- src/front/glsl/mod.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 2d9645ab6..f28ff7b6e 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -190,7 +190,7 @@ impl Parser { self.layouter.clear(); // This is necessary because if the last parsing errored out, the module - // wouldn't have been swapped + // wouldn't have been taken self.module = Module::default(); } @@ -213,13 +213,9 @@ impl Parser { } if self.errors.is_empty() { - let mut module = Module::default(); - std::mem::swap(&mut self.module, &mut module); - Ok(module) + Ok(std::mem::take(&mut self.module)) } else { - let mut errors = Vec::new(); - std::mem::swap(&mut self.errors, &mut errors); - Err(errors) + Err(std::mem::take(&mut self.errors)) } } From fae939f537933a1fcc5e9789e18121afc1cb1708 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 30 Apr 2022 16:22:10 -0700 Subject: [PATCH 1716/2212] [glsl-in] Simplify control flow in search for `main`. --- src/front/glsl/parser.rs | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 92b812569..ff253ffc0 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -38,7 +38,7 @@ impl<'source> ParsingContext<'source> { /// Helper method for backtracking from a consumed token /// /// This method should always be used instead of assigning to `backtracked_token` since - /// it validates that backtracking hasn't ocurred more than one time in a row + /// it validates that backtracking hasn't occurred more than one time in a row /// /// # Panics /// - If the parser already backtracked without bumping in between @@ -172,25 +172,23 @@ impl<'source> ParsingContext<'source> { self.parse_external_declaration(parser, &mut ctx, &mut body)?; } - match parser.lookup_function.get("main").and_then(|declaration| { - declaration - .overloads - .iter() - .find_map(|decl| match decl.kind { - FunctionKind::Call(handle) if decl.defined && decl.parameters.is_empty() => { - Some(handle) + // Add an `EntryPoint` to `parser.module` for `main`, if a + // suitable overload exists. Error out if we can't find one. + if let Some(declaration) = parser.lookup_function.get("main") { + for decl in declaration.overloads.iter() { + if let FunctionKind::Call(handle) = decl.kind { + if decl.defined && decl.parameters.is_empty() { + parser.add_entry_point(handle, body, ctx.expressions); + return Ok(()); } - _ => None, - }) - }) { - Some(handle) => parser.add_entry_point(handle, body, ctx.expressions), - None => parser.errors.push(Error { - kind: ErrorKind::SemanticError("Missing entry point".into()), - meta: Span::default(), - }), + } + } } - Ok(()) + Err(Error { + kind: ErrorKind::SemanticError("Missing entry point".into()), + meta: Span::default(), + }) } fn parse_uint_constant(&mut self, parser: &mut Parser) -> Result<(u32, Span)> { From 0d3b9bfe45397a0531c041602a0e15280a9090ae Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sun, 1 May 2022 11:03:50 +0200 Subject: [PATCH 1717/2212] update readme --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 939eb91e1..fe02caf34 100644 --- a/README.md +++ b/README.md @@ -7,12 +7,10 @@ ![MSRV](https://img.shields.io/badge/rustc-1.56+-blue.svg) [![codecov.io](https://codecov.io/gh/gfx-rs/naga/branch/master/graph/badge.svg?token=9VOKYO8BM2)](https://codecov.io/gh/gfx-rs/naga) -The shader translation library for the needs of [wgpu](https://github.com/gfx-rs/wgpu) and [gfx-rs](https://github.com/gfx-rs/gfx) projects. +The shader translation library for the needs of [wgpu](https://github.com/gfx-rs/wgpu). ## Supported end-points -Everything is still work-in-progress, but some end-points are usable: - Front-end | Status | Feature | Notes | --------------- | ------------------ | ------- | ----- | SPIR-V (binary) | :white_check_mark: | spv-in | | From 2571039af0607770948b6bf569a724fd985abef2 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 30 Apr 2022 21:55:25 -0700 Subject: [PATCH 1718/2212] Factor out code for deciding which pointers can be arguments. --- src/valid/type.rs | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/valid/type.rs b/src/valid/type.rs index 9d77342a6..988a8fe5b 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -156,6 +156,22 @@ fn check_member_layout( }; } +/// Determine whether a pointer in `space` can be passed as an argument. +/// +/// If a pointer in `space` is permitted to be passed as an argument to a +/// user-defined function, return `TypeFlags::ARGUMENT`. Otherwise, return +/// `TypeFlags::empty()`. +/// +/// Pointers passed as arguments to user-defined functions must be in the +/// `Function`, `Private`, or `Workgroup` storage space. +const fn ptr_space_argument_flag(space: crate::AddressSpace) -> TypeFlags { + use crate::AddressSpace as As; + match space { + As::Function | As::Private | As::WorkGroup => TypeFlags::ARGUMENT, + As::Uniform | As::Storage { .. } | As::Handle | As::PushConstant => TypeFlags::empty(), + } +} + #[derive(Clone, Debug)] pub(super) struct TypeInfo { pub flags: TypeFlags, @@ -300,20 +316,11 @@ impl super::Validator { } } - // Pointers passed as arguments to user-defined functions must - // be in the `Function`, `Private`, or `Workgroup` storage - // space. We only mark pointers in those spaces as `ARGUMENT`. - // // `Validator::validate_function` actually checks the storage // space of pointer arguments explicitly before checking the // `ARGUMENT` flag, to give better error messages. But it seems // best to set `ARGUMENT` accurately anyway. - let argument_flag = match space { - As::Function | As::Private | As::WorkGroup => TypeFlags::ARGUMENT, - As::Uniform | As::Storage { .. } | As::Handle | As::PushConstant => { - TypeFlags::empty() - } - }; + let argument_flag = ptr_space_argument_flag(space); // Pointers cannot be stored in variables, structure members, or // array elements, so we do not mark them as `DATA`. @@ -336,14 +343,14 @@ impl super::Validator { return Err(TypeError::InvalidWidth(kind, width)); } - use crate::AddressSpace as As; - let argument_flag = match space { - As::Function | As::Private | As::WorkGroup => TypeFlags::ARGUMENT, - As::Uniform | As::Storage { .. } | As::Handle | As::PushConstant => { - TypeFlags::empty() - } - }; + // `Validator::validate_function` actually checks the storage + // space of pointer arguments explicitly before checking the + // `ARGUMENT` flag, to give better error messages. But it seems + // best to set `ARGUMENT` accurately anyway. + let argument_flag = ptr_space_argument_flag(space); + // Pointers cannot be stored in variables, structure members, or + // array elements, so we do not mark them as `DATA`. TypeInfo::new(argument_flag | TypeFlags::SIZED | TypeFlags::COPY, 0) } Ti::Array { base, size, stride } => { From 1c02de537b3b47ea5c4729723a6ffc7e582099ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 30 Apr 2022 14:32:42 +0100 Subject: [PATCH 1719/2212] glsl-in: Fix the ternary to behave as an if The GLSL specification defines that only one of the branches should be evaluated making the ternary operator syntatic sugar for an `if`. --- src/front/glsl/ast.rs | 8 + src/front/glsl/context.rs | 127 ++++++++++-- src/front/glsl/types.rs | 54 +++++ tests/in/glsl/expressions.frag | 7 + tests/out/wgsl/bevy-pbr-frag.wgsl | 291 ++++++++++++++------------- tests/out/wgsl/expressions-frag.wgsl | 61 +++++- 6 files changed, 397 insertions(+), 151 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index dc47647dc..bf381b42f 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -133,9 +133,17 @@ pub enum HirExprKind { }, Variable(VariableReference), Call(FunctionCall), + /// Represents the ternary operator in glsl (`:?`) Conditional { + /// The expression that will decide which branch to take, must evaluate to a boolean condition: Handle, + /// The expression that will be evaluated if [`condition`][condition] returns `true` + /// + /// [condition]: Self::Conditional::condition accept: Handle, + /// The expression that will be evaluated if [`condition`][condition] returns `false` + /// + /// [condition]: Self::Conditional::condition reject: Handle, }, Assign { diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index c0b4bd95f..9fe1adb15 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -1069,35 +1069,138 @@ impl Context { )?; return Ok((maybe_expr, meta)); } + // `HirExprKind::Conditional` represents the ternary operator in glsl (`:?`) + // + // The ternary operator is defined to only evaluate one of the two possible + // expressions which means that it's behavior is that of an `if` statement, + // and it's merely syntatic sugar for it. HirExprKind::Conditional { condition, accept, reject, } if ExprPos::Lhs != pos => { + // Lower the condition first to the current bodyy let condition = self .lower_expect_inner(stmt, parser, condition, ExprPos::Rhs, body)? .0; + + // Emit all expressions since we will be adding statements to + // other bodies next + self.emit_flush(body); + self.emit_start(); + + // Create the bodies for the two cases + let mut accept_body = Block::new(); + let mut reject_body = Block::new(); + + // Lower the `true` branch let (mut accept, accept_meta) = - self.lower_expect_inner(stmt, parser, accept, pos, body)?; + self.lower_expect_inner(stmt, parser, accept, pos, &mut accept_body)?; + + // Flush the body of the `true` branch, to start emitting on the + // `false` branch + self.emit_flush(&mut accept_body); + self.emit_start(); + + // Lower the `false` branch let (mut reject, reject_meta) = - self.lower_expect_inner(stmt, parser, reject, pos, body)?; + self.lower_expect_inner(stmt, parser, reject, pos, &mut reject_body)?; - self.binary_implicit_conversion( - parser, - &mut accept, + // Flush the body of the `false` branch + self.emit_flush(&mut reject_body); + self.emit_start(); + + // We need to do some custom implicit conversions since the two target expressions + // are in different bodies + if let ( + Some((accept_power, accept_width, accept_kind)), + Some((reject_power, reject_width, reject_kind)), + ) = ( + // Get the components of both branches and calculate the type power + self.expr_scalar_components(parser, accept, accept_meta)? + .and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), + self.expr_scalar_components(parser, reject, reject_meta)? + .and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), + ) { + match accept_power.cmp(&reject_power) { + std::cmp::Ordering::Less => { + self.conversion(&mut accept, accept_meta, reject_kind, reject_width)?; + // The expression belongs to the `true` branch so we need to flush to + // the respective body + self.emit_flush(&mut accept_body); + } + // Technically there's nothing to flush but we need to add some + // expressions that must not be emitted so instead of flushing, + // starting and flushing again, just make sure everything is + // flushed. + std::cmp::Ordering::Equal => self.emit_flush(body), + std::cmp::Ordering::Greater => { + self.conversion(&mut reject, reject_meta, accept_kind, accept_width)?; + // The expression belongs to the `false` branch so we need to flush to + // the respective body + self.emit_flush(&mut reject_body); + } + } + } + + // We need to get the type of the resulting expression to create the local, + // this must be done after implicit conversions to ensure both branches have + // the same type. + let ty = parser.resolve_type_handle(self, accept, accept_meta)?; + + // Add the local that will hold the result of our conditional + let local = self.locals.append( + LocalVariable { + name: None, + ty, + init: None, + }, + Span::default(), + ); + + // Note: `Expression::LocalVariable` must not be emited so it's important + // that at this point the emitter is flushed but not started. + let local_expr = self + .expressions + .append(Expression::LocalVariable(local), meta); + + // Add to each body the store to the result variable + accept_body.push( + Statement::Store { + pointer: local_expr, + value: accept, + }, accept_meta, - &mut reject, + ); + reject_body.push( + Statement::Store { + pointer: local_expr, + value: reject, + }, reject_meta, - )?; + ); - self.add_expression( - Expression::Select { + // Finally add the `If` to the main body with the `condition` we lowered + // earlier and the branches we prepared. + body.push( + Statement::If { condition, - accept, - reject, + accept: accept_body, + reject: reject_body, + }, + meta, + ); + + // Restart the emitter + self.emit_start(); + + // Note: `Expression::Load` must be emited before it's used so make + // sure the emitter is active here. + self.expressions.append( + Expression::Load { + pointer: local_expr, }, meta, - body, ) } HirExprKind::Assign { tgt, value } if ExprPos::Lhs != pos => { diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 6a197cceb..90ba99dff 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -225,6 +225,18 @@ pub const fn type_power(kind: ScalarKind, width: Bytes) -> Option { } impl Parser { + /// Resolves the types of the expressions until `handle` (inclusive) + /// + /// This needs to be done before the [`typifier`][typifier] can be queried for + /// the types of the expressions in the range between the last grow and `handle`. + /// + /// # Note + /// + /// The `resolve_type*` methods (like [`resolve_type`][Self::resolve_type]) automatically + /// grow the [`typifier`][typifier] so calling this method is not necessary when using + /// them. + /// + /// [typifier]: Context::typifier pub(crate) fn typifier_grow( &self, ctx: &mut Context, @@ -248,6 +260,12 @@ impl Parser { }) } + /// Gets the type for the result of the `handle` expression + /// + /// Automatically grows the [`typifier`][typifier] to `handle` so calling + /// [`typifier_grow`][Self::typifier_grow] is not necessary + /// + /// [typifier]: Context::typifier pub(crate) fn resolve_type<'b>( &'b self, ctx: &'b mut Context, @@ -258,6 +276,42 @@ impl Parser { Ok(ctx.typifier.get(handle, &self.module.types)) } + /// Gets the type handle for the result of the `handle` expression + /// + /// Automatically grows the [`typifier`][typifier] to `handle` so calling + /// [`typifier_grow`][Self::typifier_grow] is not necessary + /// + /// # Note + /// + /// Consider using [`resolve_type`][Self::resolve_type] whenever possible + /// since it doesn't require adding each type to the [`types`][types] arena + /// and it doesn't need to mutably borrow the [`Parser`][Self] + /// + /// [typifier]: Context::typifier + /// [types]: crate::Module::types + pub(crate) fn resolve_type_handle( + &mut self, + ctx: &mut Context, + handle: Handle, + meta: Span, + ) -> Result> { + self.typifier_grow(ctx, handle, meta)?; + let resolution = &ctx.typifier[handle]; + Ok(match *resolution { + // If the resolution is already a handle return early + crate::proc::TypeResolution::Handle(handle) => handle, + // If it's a value we need to clone it + crate::proc::TypeResolution::Value(_) => match resolution.clone() { + // This is unreachable + crate::proc::TypeResolution::Handle(handle) => handle, + // Add the value to the type arena and return the handle + crate::proc::TypeResolution::Value(inner) => { + self.module.types.insert(Type { name: None, inner }, meta) + } + }, + }) + } + /// Invalidates the cached type resolution for `handle` forcing a recomputation pub(crate) fn invalidate_expression<'b>( &'b self, diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 777b0b973..252a8a1e1 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -121,6 +121,13 @@ void testNonImplicitCastVectorCast() { float global; void privatePointer(inout float a) {} +void ternary(bool a) { + uint b = a ? 0 : 1u; + uint c = a ? 0u : 1; + + uint nested = a ? (a ? (a ? 0u : 1) : 1u) : 1; +} + out vec4 o_color; void main() { privatePointer(global); diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index b1000381d..725952dde 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -698,6 +698,9 @@ fn main_1() { var N_2: vec3; var T: vec3; var B: vec3; + var local: vec3; + var local_1: vec3; + var local_2: vec3; var TBN: mat3x3; var occlusion: f32; var emissive: vec4; @@ -740,158 +743,176 @@ fn main_1() { let _e80 = v_WorldTangent_1; B = (cross(_e77, _e78) * _e80.w); let _e85 = gl_FrontFacing; - let _e86 = N_2; - let _e87 = N_2; - N_2 = select(-(_e87), _e86, _e85); - let _e90 = gl_FrontFacing; - let _e91 = T; - let _e92 = T; - T = select(-(_e92), _e91, _e90); - let _e95 = gl_FrontFacing; - let _e96 = B; - let _e97 = B; - B = select(-(_e97), _e96, _e95); - let _e100 = T; - let _e101 = B; - let _e102 = N_2; - TBN = mat3x3(vec3(_e100.x, _e100.y, _e100.z), vec3(_e101.x, _e101.y, _e101.z), vec3(_e102.x, _e102.y, _e102.z)); - let _e117 = TBN; - let _e119 = v_Uv_1; - let _e120 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e119); - let _e128 = v_Uv_1; - let _e129 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e128); - N_2 = (_e117 * normalize(((_e129.xyz * 2.0) - vec3(1.0)))); - let _e139 = v_Uv_1; - let _e140 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e139); - occlusion = _e140.x; - let _e143 = global_7.emissive; - emissive = _e143; - let _e145 = emissive; - let _e147 = emissive; - let _e150 = v_Uv_1; - let _e151 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e150); - let _e153 = (_e147.xyz * _e151.xyz); - emissive.x = _e153.x; - emissive.y = _e153.y; - emissive.z = _e153.z; - let _e160 = global_1.CameraPos; - let _e162 = v_WorldPosition_1; - let _e165 = global_1.CameraPos; - let _e167 = v_WorldPosition_1; - V_3 = normalize((_e165.xyz - _e167.xyz)); - let _e174 = N_2; - let _e175 = V_3; - let _e180 = N_2; - let _e181 = V_3; - NdotV_4 = max(dot(_e180, _e181), 0.0010000000474974513); - let _e187 = global_6.reflectance; - let _e189 = global_6.reflectance; - let _e192 = metallic; - let _e196 = output_color; - let _e198 = metallic; - F0_4 = (vec3((((0.1599999964237213 * _e187) * _e189) * (1.0 - _e192))) + (_e196.xyz * vec3(_e198))); - let _e203 = output_color; - let _e206 = metallic; - diffuseColor_4 = (_e203.xyz * vec3((1.0 - _e206))); - let _e211 = V_3; + if _e85 { + let _e86 = N_2; + local = _e86; + } else { + let _e87 = N_2; + local = -(_e87); + } + let _e90 = local; + N_2 = _e90; + let _e91 = gl_FrontFacing; + if _e91 { + let _e92 = T; + local_1 = _e92; + } else { + let _e93 = T; + local_1 = -(_e93); + } + let _e96 = local_1; + T = _e96; + let _e97 = gl_FrontFacing; + if _e97 { + let _e98 = B; + local_2 = _e98; + } else { + let _e99 = B; + local_2 = -(_e99); + } + let _e102 = local_2; + B = _e102; + let _e103 = T; + let _e104 = B; + let _e105 = N_2; + TBN = mat3x3(vec3(_e103.x, _e103.y, _e103.z), vec3(_e104.x, _e104.y, _e104.z), vec3(_e105.x, _e105.y, _e105.z)); + let _e120 = TBN; + let _e122 = v_Uv_1; + let _e123 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e122); + let _e131 = v_Uv_1; + let _e132 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e131); + N_2 = (_e120 * normalize(((_e132.xyz * 2.0) - vec3(1.0)))); + let _e142 = v_Uv_1; + let _e143 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e142); + occlusion = _e143.x; + let _e146 = global_7.emissive; + emissive = _e146; + let _e148 = emissive; + let _e150 = emissive; + let _e153 = v_Uv_1; + let _e154 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e153); + let _e156 = (_e150.xyz * _e154.xyz); + emissive.x = _e156.x; + emissive.y = _e156.y; + emissive.z = _e156.z; + let _e163 = global_1.CameraPos; + let _e165 = v_WorldPosition_1; + let _e168 = global_1.CameraPos; + let _e170 = v_WorldPosition_1; + V_3 = normalize((_e168.xyz - _e170.xyz)); + let _e177 = N_2; + let _e178 = V_3; + let _e183 = N_2; + let _e184 = V_3; + NdotV_4 = max(dot(_e183, _e184), 0.0010000000474974513); + let _e190 = global_6.reflectance; + let _e192 = global_6.reflectance; + let _e195 = metallic; + let _e199 = output_color; + let _e201 = metallic; + F0_4 = (vec3((((0.1599999964237213 * _e190) * _e192) * (1.0 - _e195))) + (_e199.xyz * vec3(_e201))); + let _e206 = output_color; + let _e209 = metallic; + diffuseColor_4 = (_e206.xyz * vec3((1.0 - _e209))); let _e214 = V_3; - let _e216 = N_2; - R_4 = reflect(-(_e214), _e216); + let _e217 = V_3; + let _e219 = N_2; + R_4 = reflect(-(_e217), _e219); loop { - let _e224 = i; - let _e225 = global_2.NumLights; - let _e229 = i; - if !(((_e224 < i32(_e225.x)) && (_e229 < 10))) { + let _e227 = i; + let _e228 = global_2.NumLights; + let _e232 = i; + if !(((_e227 < i32(_e228.x)) && (_e232 < 10))) { break; } { - let _e236 = light_accum; - let _e237 = i; - let _e247 = i; - let _e249 = global_2.PointLights[_e247]; - let _e250 = roughness_12; - let _e251 = NdotV_4; - let _e252 = N_2; - let _e253 = V_3; - let _e254 = R_4; - let _e255 = F0_4; - let _e256 = diffuseColor_4; - let _e257 = point_light(_e249, _e250, _e251, _e252, _e253, _e254, _e255, _e256); - light_accum = (_e236 + _e257); + let _e239 = light_accum; + let _e240 = i; + let _e250 = i; + let _e252 = global_2.PointLights[_e250]; + let _e253 = roughness_12; + let _e254 = NdotV_4; + let _e255 = N_2; + let _e256 = V_3; + let _e257 = R_4; + let _e258 = F0_4; + let _e259 = diffuseColor_4; + let _e260 = point_light(_e252, _e253, _e254, _e255, _e256, _e257, _e258, _e259); + light_accum = (_e239 + _e260); } continuing { - let _e233 = i; - i = (_e233 + 1); + let _e236 = i; + i = (_e236 + 1); } } loop { - let _e261 = i_1; - let _e262 = global_2.NumLights; - let _e266 = i_1; - if !(((_e261 < i32(_e262.y)) && (_e266 < 1))) { + let _e264 = i_1; + let _e265 = global_2.NumLights; + let _e269 = i_1; + if !(((_e264 < i32(_e265.y)) && (_e269 < 1))) { break; } { - let _e273 = light_accum; - let _e274 = i_1; - let _e284 = i_1; - let _e286 = global_2.DirectionalLights[_e284]; - let _e287 = roughness_12; - let _e288 = NdotV_4; - let _e289 = N_2; - let _e290 = V_3; - let _e291 = R_4; - let _e292 = F0_4; - let _e293 = diffuseColor_4; - let _e294 = dir_light(_e286, _e287, _e288, _e289, _e290, _e291, _e292, _e293); - light_accum = (_e273 + _e294); + let _e276 = light_accum; + let _e277 = i_1; + let _e287 = i_1; + let _e289 = global_2.DirectionalLights[_e287]; + let _e290 = roughness_12; + let _e291 = NdotV_4; + let _e292 = N_2; + let _e293 = V_3; + let _e294 = R_4; + let _e295 = F0_4; + let _e296 = diffuseColor_4; + let _e297 = dir_light(_e289, _e290, _e291, _e292, _e293, _e294, _e295, _e296); + light_accum = (_e276 + _e297); } continuing { - let _e270 = i_1; - i_1 = (_e270 + 1); + let _e273 = i_1; + i_1 = (_e273 + 1); } } - let _e299 = diffuseColor_4; - let _e301 = NdotV_4; - let _e302 = EnvBRDFApprox(_e299, 1.0, _e301); - diffuse_ambient = _e302; - let _e307 = F0_4; - let _e308 = perceptual_roughness_2; - let _e309 = NdotV_4; - let _e310 = EnvBRDFApprox(_e307, _e308, _e309); - specular_ambient = _e310; - let _e312 = output_color; - let _e314 = light_accum; - output_color.x = _e314.x; - output_color.y = _e314.y; - output_color.z = _e314.z; - let _e321 = output_color; - let _e323 = output_color; - let _e325 = diffuse_ambient; - let _e326 = specular_ambient; - let _e328 = global_2.AmbientColor; - let _e331 = occlusion; - let _e333 = (_e323.xyz + (((_e325 + _e326) * _e328.xyz) * _e331)); - output_color.x = _e333.x; - output_color.y = _e333.y; - output_color.z = _e333.z; - let _e340 = output_color; - let _e342 = output_color; - let _e344 = emissive; - let _e346 = output_color; - let _e349 = (_e342.xyz + (_e344.xyz * _e346.w)); - output_color.x = _e349.x; - output_color.y = _e349.y; - output_color.z = _e349.z; - let _e356 = output_color; - let _e358 = output_color; - let _e360 = output_color; - let _e362 = reinhard_luminance(_e360.xyz); - output_color.x = _e362.x; - output_color.y = _e362.y; - output_color.z = _e362.z; - let _e369 = output_color; - o_Target = _e369; + let _e302 = diffuseColor_4; + let _e304 = NdotV_4; + let _e305 = EnvBRDFApprox(_e302, 1.0, _e304); + diffuse_ambient = _e305; + let _e310 = F0_4; + let _e311 = perceptual_roughness_2; + let _e312 = NdotV_4; + let _e313 = EnvBRDFApprox(_e310, _e311, _e312); + specular_ambient = _e313; + let _e315 = output_color; + let _e317 = light_accum; + output_color.x = _e317.x; + output_color.y = _e317.y; + output_color.z = _e317.z; + let _e324 = output_color; + let _e326 = output_color; + let _e328 = diffuse_ambient; + let _e329 = specular_ambient; + let _e331 = global_2.AmbientColor; + let _e334 = occlusion; + let _e336 = (_e326.xyz + (((_e328 + _e329) * _e331.xyz) * _e334)); + output_color.x = _e336.x; + output_color.y = _e336.y; + output_color.z = _e336.z; + let _e343 = output_color; + let _e345 = output_color; + let _e347 = emissive; + let _e349 = output_color; + let _e352 = (_e345.xyz + (_e347.xyz * _e349.w)); + output_color.x = _e352.x; + output_color.y = _e352.y; + output_color.z = _e352.z; + let _e359 = output_color; + let _e361 = output_color; + let _e363 = output_color; + let _e365 = reinhard_luminance(_e363.xyz); + output_color.x = _e365.x; + output_color.y = _e365.y; + output_color.z = _e365.z; + let _e372 = output_color; + o_Target = _e372; return; } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index a4153c01e..fc2181af3 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -299,13 +299,66 @@ fn privatePointer(a_19: ptr) { return; } +fn ternary(a_20: bool) { + var a_21: bool; + var local: u32; + var b_17: u32; + var local_1: u32; + var c_1: u32; + var local_2: u32; + var local_3: u32; + var local_4: u32; + var nested: u32; + + a_21 = a_20; + let _e3 = a_21; + if _e3 { + local = u32(0); + } else { + local = 1u; + } + let _e8 = local; + b_17 = _e8; + let _e10 = a_21; + if _e10 { + local_1 = 0u; + } else { + local_1 = u32(1); + } + let _e15 = local_1; + c_1 = _e15; + let _e17 = a_21; + if _e17 { + let _e18 = a_21; + if _e18 { + let _e19 = a_21; + if _e19 { + local_2 = 0u; + } else { + local_2 = u32(1); + } + let _e24 = local_2; + local_3 = _e24; + } else { + local_3 = 1u; + } + let _e27 = local_3; + local_4 = _e27; + } else { + local_4 = u32(1); + } + let _e31 = local_4; + nested = _e31; + return; +} + fn main_1() { - var local: f32; + var local_5: f32; let _e3 = global; - local = _e3; - privatePointer((&local)); - let _e5 = local; + local_5 = _e3; + privatePointer((&local_5)); + let _e5 = local_5; global = _e5; let _e6 = o_color; let _e9 = vec4(1.0); From 6a62d009ea2b0d215f2fdb209f8bc132c0589a7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 30 Apr 2022 14:50:11 +0100 Subject: [PATCH 1720/2212] glsl-in: Improve the context emitter interface Adds a new method `emit_restart` to perform the common operation of flushing the `emitter` to the body and starting it again. Adds documentation to all context emitter related methods --- src/front/glsl/builtins.rs | 6 ++-- src/front/glsl/context.rs | 53 ++++++++++++++++++++---------- src/front/glsl/functions.rs | 5 ++- src/front/glsl/parser.rs | 9 +++-- src/front/glsl/parser/functions.rs | 21 ++++-------- 5 files changed, 53 insertions(+), 41 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 5bee3948f..56cd71e9f 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1837,7 +1837,7 @@ impl MacroCall { MacroCall::ImageStore => { let comps = parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; - ctx.emit_flush(body); + ctx.emit_restart(body); body.push( crate::Statement::ImageStore { image: args[0], @@ -1847,7 +1847,6 @@ impl MacroCall { }, meta, ); - ctx.emit_start(); return Ok(None); } MacroCall::MathFunction(fun) => ctx.add_expression( @@ -2038,8 +2037,7 @@ impl MacroCall { body, ), MacroCall::Barrier => { - ctx.emit_flush(body); - ctx.emit_start(); + ctx.emit_restart(body); body.push(crate::Statement::Barrier(crate::Barrier::all()), meta); return Ok(None); } diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 9fe1adb15..c52130d46 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -101,7 +101,7 @@ impl Context { }: GlobalLookup, body: &mut Block, ) { - self.emit_flush(body); + self.emit_end(body); let (expr, load, constant) = match kind { GlobalLookupKind::Variable(v) => { let span = parser.module.global_variables.get_span(v); @@ -170,14 +170,37 @@ impl Context { self.lookup_global_var_exps.insert(name.into(), var); } + /// Starts the expression emitter + /// + /// # Panics + /// + /// - If called twice in a row without calling [`emit_end`][Self::emit_end]. + #[inline] pub fn emit_start(&mut self) { self.emitter.start(&self.expressions) } - pub fn emit_flush(&mut self, body: &mut Block) { + /// Emits all the expressions captured by the emitter to the passed `body` + /// + /// # Panics + /// + /// - If called before calling [`emit_start`][Self::emit_start]. + /// - If called twice in a row without calling [`emit_start`][Self::emit_start]. + pub fn emit_end(&mut self, body: &mut Block) { body.extend(self.emitter.finish(&self.expressions)) } + /// Emits all the expressions captured by the emitter to the passed `body` + /// and starts the emitter again + /// + /// # Panics + /// + /// - If called before calling [`emit_start`][Self::emit_start]. + pub fn emit_restart(&mut self, body: &mut Block) { + self.emit_end(body); + self.emit_start() + } + pub fn add_expression( &mut self, expr: Expression, @@ -186,7 +209,7 @@ impl Context { ) -> Handle { let needs_pre_emit = expr.needs_pre_emit(); if needs_pre_emit { - self.emit_flush(body); + self.emit_end(body); } let handle = self.expressions.append(expr, meta); if needs_pre_emit { @@ -292,8 +315,7 @@ impl Context { ); let local_expr = self.add_expression(Expression::LocalVariable(handle), meta, body); - self.emit_flush(body); - self.emit_start(); + self.emit_restart(body); body.push( Statement::Store { @@ -462,8 +484,7 @@ impl Context { body, ); - self.emit_flush(body); - self.emit_start(); + self.emit_restart(body); body.push( Statement::Store { @@ -474,8 +495,7 @@ impl Context { ); } } else { - self.emit_flush(body); - self.emit_start(); + self.emit_restart(body); body.push(Statement::Store { pointer, value }, meta); } @@ -1086,8 +1106,7 @@ impl Context { // Emit all expressions since we will be adding statements to // other bodies next - self.emit_flush(body); - self.emit_start(); + self.emit_restart(body); // Create the bodies for the two cases let mut accept_body = Block::new(); @@ -1099,16 +1118,14 @@ impl Context { // Flush the body of the `true` branch, to start emitting on the // `false` branch - self.emit_flush(&mut accept_body); - self.emit_start(); + self.emit_restart(&mut accept_body); // Lower the `false` branch let (mut reject, reject_meta) = self.lower_expect_inner(stmt, parser, reject, pos, &mut reject_body)?; // Flush the body of the `false` branch - self.emit_flush(&mut reject_body); - self.emit_start(); + self.emit_restart(&mut reject_body); // We need to do some custom implicit conversions since the two target expressions // are in different bodies @@ -1127,18 +1144,18 @@ impl Context { self.conversion(&mut accept, accept_meta, reject_kind, reject_width)?; // The expression belongs to the `true` branch so we need to flush to // the respective body - self.emit_flush(&mut accept_body); + self.emit_end(&mut accept_body); } // Technically there's nothing to flush but we need to add some // expressions that must not be emitted so instead of flushing, // starting and flushing again, just make sure everything is // flushed. - std::cmp::Ordering::Equal => self.emit_flush(body), + std::cmp::Ordering::Equal => self.emit_end(body), std::cmp::Ordering::Greater => { self.conversion(&mut reject, reject_meta, accept_kind, accept_width)?; // The expression belongs to the `false` branch so we need to flush to // the respective body - self.emit_flush(&mut reject_body); + self.emit_end(&mut reject_body); } } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index a9e8fd417..325f4d8ab 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -972,7 +972,7 @@ impl Parser { match kind { FunctionKind::Call(function) => { - ctx.emit_flush(body); + ctx.emit_end(body); let result = if !is_void { Some(ctx.add_expression(Expression::CallResult(function), meta, body)) @@ -995,8 +995,7 @@ impl Parser { for (original, pointer) in proxy_writes { let value = ctx.add_expression(Expression::Load { pointer }, meta, body); - ctx.emit_flush(body); - ctx.emit_start(); + ctx.emit_restart(body); body.push( Statement::Store { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index ff253ffc0..649677c41 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -436,8 +436,13 @@ impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { } } + /// Emits all the expressions captured by the emitter and starts the emitter again + /// + /// Alias to [`emit_restart`][emit_restart] with the declaration body + /// + /// [emit_restart]: Context::emit_restart + #[inline] fn flush_expressions(&mut self) { - self.ctx.emit_flush(self.body); - self.ctx.emit_start() + self.ctx.emit_restart(self.body); } } diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index ce6f56d8e..8a9487917 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -103,8 +103,7 @@ impl<'source> ParsingContext<'source> { } }; - ctx.emit_flush(body); - ctx.emit_start(); + ctx.emit_restart(body); body.push(Statement::Return { value }, meta); terminator.get_or_insert(body.len()); @@ -132,8 +131,7 @@ impl<'source> ParsingContext<'source> { }; self.expect(parser, TokenValue::RightParen)?; - ctx.emit_flush(body); - ctx.emit_start(); + ctx.emit_restart(body); let mut accept = Block::new(); if let Some(more_meta) = @@ -176,8 +174,7 @@ impl<'source> ParsingContext<'source> { self.expect(parser, TokenValue::RightParen)?; - ctx.emit_flush(body); - ctx.emit_start(); + ctx.emit_restart(body); let mut cases = Vec::new(); @@ -301,8 +298,7 @@ impl<'source> ParsingContext<'source> { &mut loop_body, ); - ctx.emit_flush(&mut loop_body); - ctx.emit_start(); + ctx.emit_restart(&mut loop_body); loop_body.push( Statement::If { @@ -359,8 +355,7 @@ impl<'source> ParsingContext<'source> { &mut loop_body, ); - ctx.emit_flush(&mut loop_body); - ctx.emit_start(); + ctx.emit_restart(&mut loop_body); loop_body.push( Statement::If { @@ -427,8 +422,7 @@ impl<'source> ParsingContext<'source> { let pointer = parser.add_local_var(ctx, &mut block, decl)?; - ctx.emit_flush(&mut block); - ctx.emit_start(); + ctx.emit_restart(&mut block); block.push(Statement::Store { pointer, value }, meta); @@ -448,8 +442,7 @@ impl<'source> ParsingContext<'source> { &mut block, ); - ctx.emit_flush(&mut block); - ctx.emit_start(); + ctx.emit_restart(&mut block); block.push( Statement::If { From 883a88580f95161184e754af9b32d171670a6e87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 1 May 2022 17:39:43 +0100 Subject: [PATCH 1721/2212] glsl-in: Apply comments --- src/front/glsl/ast.rs | 8 ++-- src/front/glsl/context.rs | 30 ++++++++++--- src/front/glsl/parser.rs | 4 +- src/front/glsl/types.rs | 64 +++++++++++++++------------- tests/in/glsl/expressions.frag | 2 +- tests/out/wgsl/expressions-frag.wgsl | 8 ++-- 6 files changed, 68 insertions(+), 48 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index bf381b42f..148049a68 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -137,13 +137,13 @@ pub enum HirExprKind { Conditional { /// The expression that will decide which branch to take, must evaluate to a boolean condition: Handle, - /// The expression that will be evaluated if [`condition`][condition] returns `true` + /// The expression that will be evaluated if [`condition`] returns `true` /// - /// [condition]: Self::Conditional::condition + /// [`condition`]: Self::Conditional::condition accept: Handle, - /// The expression that will be evaluated if [`condition`][condition] returns `false` + /// The expression that will be evaluated if [`condition`] returns `false` /// - /// [condition]: Self::Conditional::condition + /// [`condition`]: Self::Conditional::condition reject: Handle, }, Assign { diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index c52130d46..fe20df410 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -184,8 +184,10 @@ impl Context { /// /// # Panics /// - /// - If called before calling [`emit_start`][Self::emit_start]. - /// - If called twice in a row without calling [`emit_start`][Self::emit_start]. + /// - If called before calling [`emit_start`]. + /// - If called twice in a row without calling [`emit_start`]. + /// + /// [`emit_start`]: Self::emit_start pub fn emit_end(&mut self, body: &mut Block) { body.extend(self.emitter.finish(&self.expressions)) } @@ -1099,6 +1101,20 @@ impl Context { accept, reject, } if ExprPos::Lhs != pos => { + // Given an expression `a ? b : c`, we need to produce a Naga + // statement roughly like: + // + // var temp; + // if a { + // temp = convert(b); + // } else { + // temp = convert(c); + // } + // + // where `convert` stands for type conversions to bring `b` and `c` to + // the same type, and then use `temp` to represent the value of the whole + // conditional expression in subsequent code. + // Lower the condition first to the current bodyy let condition = self .lower_expect_inner(stmt, parser, condition, ExprPos::Rhs, body)? @@ -1146,10 +1162,10 @@ impl Context { // the respective body self.emit_end(&mut accept_body); } - // Technically there's nothing to flush but we need to add some - // expressions that must not be emitted so instead of flushing, - // starting and flushing again, just make sure everything is - // flushed. + // Technically there's nothing to flush but later we will need to + // add some expressions that must not be emitted so instead + // of flushing, starting and flushing again, just make sure + // everything is flushed. std::cmp::Ordering::Equal => self.emit_end(body), std::cmp::Ordering::Greater => { self.conversion(&mut reject, reject_meta, accept_kind, accept_width)?; @@ -1172,7 +1188,7 @@ impl Context { ty, init: None, }, - Span::default(), + meta, ); // Note: `Expression::LocalVariable` must not be emited so it's important diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 649677c41..2705fd904 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -438,9 +438,9 @@ impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { /// Emits all the expressions captured by the emitter and starts the emitter again /// - /// Alias to [`emit_restart`][emit_restart] with the declaration body + /// Alias to [`emit_restart`] with the declaration body /// - /// [emit_restart]: Context::emit_restart + /// [`emit_restart`]: Context::emit_restart #[inline] fn flush_expressions(&mut self) { self.ctx.emit_restart(self.body); diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 90ba99dff..05c415eba 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -225,22 +225,23 @@ pub const fn type_power(kind: ScalarKind, width: Bytes) -> Option { } impl Parser { - /// Resolves the types of the expressions until `handle` (inclusive) + /// Resolves the types of the expressions until `expr` (inclusive) /// - /// This needs to be done before the [`typifier`][typifier] can be queried for - /// the types of the expressions in the range between the last grow and `handle`. + /// This needs to be done before the [`typifier`] can be queried for + /// the types of the expressions in the range between the last grow and `expr`. /// /// # Note /// - /// The `resolve_type*` methods (like [`resolve_type`][Self::resolve_type]) automatically - /// grow the [`typifier`][typifier] so calling this method is not necessary when using + /// The `resolve_type*` methods (like [`resolve_type`]) automatically + /// grow the [`typifier`] so calling this method is not necessary when using /// them. /// - /// [typifier]: Context::typifier + /// [`typifier`]: Context::typifier + /// [`resolve_type`]: Self::resolve_type pub(crate) fn typifier_grow( &self, ctx: &mut Context, - handle: Handle, + expr: Handle, meta: Span, ) -> Result<()> { let resolve_ctx = ResolveContext { @@ -253,57 +254,60 @@ impl Parser { }; ctx.typifier - .grow(handle, &ctx.expressions, &resolve_ctx) + .grow(expr, &ctx.expressions, &resolve_ctx) .map_err(|error| Error { kind: ErrorKind::SemanticError(format!("Can't resolve type: {:?}", error).into()), meta, }) } - /// Gets the type for the result of the `handle` expression + /// Gets the type for the result of the `expr` expression /// - /// Automatically grows the [`typifier`][typifier] to `handle` so calling - /// [`typifier_grow`][Self::typifier_grow] is not necessary + /// Automatically grows the [`typifier`] to `expr` so calling + /// [`typifier_grow`] is not necessary /// - /// [typifier]: Context::typifier + /// [`typifier`]: Context::typifier + /// [`typifier_grow`]: Self::typifier_grow pub(crate) fn resolve_type<'b>( &'b self, ctx: &'b mut Context, - handle: Handle, + expr: Handle, meta: Span, ) -> Result<&'b TypeInner> { - self.typifier_grow(ctx, handle, meta)?; - Ok(ctx.typifier.get(handle, &self.module.types)) + self.typifier_grow(ctx, expr, meta)?; + Ok(ctx.typifier.get(expr, &self.module.types)) } - /// Gets the type handle for the result of the `handle` expression + /// Gets the type handle for the result of the `expr` expression /// - /// Automatically grows the [`typifier`][typifier] to `handle` so calling - /// [`typifier_grow`][Self::typifier_grow] is not necessary + /// Automatically grows the [`typifier`] to `expr` so calling + /// [`typifier_grow`] is not necessary /// /// # Note /// - /// Consider using [`resolve_type`][Self::resolve_type] whenever possible - /// since it doesn't require adding each type to the [`types`][types] arena + /// Consider using [`resolve_type`] whenever possible + /// since it doesn't require adding each type to the [`types`] arena /// and it doesn't need to mutably borrow the [`Parser`][Self] /// - /// [typifier]: Context::typifier - /// [types]: crate::Module::types + /// [`types`]: crate::Module::types + /// [`typifier`]: Context::typifier + /// [`typifier_grow`]: Self::typifier_grow + /// [`resolve_type`]: Self::resolve_type pub(crate) fn resolve_type_handle( &mut self, ctx: &mut Context, - handle: Handle, + expr: Handle, meta: Span, ) -> Result> { - self.typifier_grow(ctx, handle, meta)?; - let resolution = &ctx.typifier[handle]; + self.typifier_grow(ctx, expr, meta)?; + let resolution = &ctx.typifier[expr]; Ok(match *resolution { // If the resolution is already a handle return early - crate::proc::TypeResolution::Handle(handle) => handle, + crate::proc::TypeResolution::Handle(ty) => ty, // If it's a value we need to clone it crate::proc::TypeResolution::Value(_) => match resolution.clone() { // This is unreachable - crate::proc::TypeResolution::Handle(handle) => handle, + crate::proc::TypeResolution::Handle(ty) => ty, // Add the value to the type arena and return the handle crate::proc::TypeResolution::Value(inner) => { self.module.types.insert(Type { name: None, inner }, meta) @@ -312,11 +316,11 @@ impl Parser { }) } - /// Invalidates the cached type resolution for `handle` forcing a recomputation + /// Invalidates the cached type resolution for `expr` forcing a recomputation pub(crate) fn invalidate_expression<'b>( &'b self, ctx: &'b mut Context, - handle: Handle, + expr: Handle, meta: Span, ) -> Result<()> { let resolve_ctx = ResolveContext { @@ -329,7 +333,7 @@ impl Parser { }; ctx.typifier - .invalidate(handle, &ctx.expressions, &resolve_ctx) + .invalidate(expr, &ctx.expressions, &resolve_ctx) .map_err(|error| Error { kind: ErrorKind::SemanticError(format!("Can't resolve type: {:?}", error).into()), meta, diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 252a8a1e1..8dd07c652 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -125,7 +125,7 @@ void ternary(bool a) { uint b = a ? 0 : 1u; uint c = a ? 0u : 1; - uint nested = a ? (a ? (a ? 0u : 1) : 1u) : 1; + uint nested = a ? (a ? (a ? 2u : 3) : 4u) : 5; } out vec4 o_color; diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index fc2181af3..984e28cad 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -333,19 +333,19 @@ fn ternary(a_20: bool) { if _e18 { let _e19 = a_21; if _e19 { - local_2 = 0u; + local_2 = 2u; } else { - local_2 = u32(1); + local_2 = u32(3); } let _e24 = local_2; local_3 = _e24; } else { - local_3 = 1u; + local_3 = 4u; } let _e27 = local_3; local_4 = _e27; } else { - local_4 = u32(1); + local_4 = u32(5); } let _e31 = local_4; nested = _e31; From a8e1e11437d10228df3597db50e25a57ea5466e2 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 29 Apr 2022 13:18:13 -0700 Subject: [PATCH 1722/2212] Rename `check_validation_error` macro to `check_validation`. The macro can check for both success and failure, so the new name is more accurate, and shorter. --- tests/wgsl-errors.rs | 58 ++++++++++++++++++++++---------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index e5823c250..3b2f3aa30 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -810,18 +810,18 @@ fn module_scope_identifier_redefinition() { ); } -macro_rules! check_validation_error { +macro_rules! check_validation { // We want to support an optional guard expression after the pattern, so // that we can check values we can't match against, like strings. // Unfortunately, we can't simply include `$( if $guard:expr )?` in the // pattern, because Rust treats `?` as a repetition operator, and its count // (0 or 1) will not necessarily match `$source`. ( $( $source:literal ),* : $pattern:pat ) => { - check_validation_error!( @full $( $source ),* : $pattern if true ; ""); + check_validation!( @full $( $source ),* : $pattern if true ; ""); }; ( $( $source:literal ),* : $pattern:pat if $guard:expr ) => { - check_validation_error!( @full $( $source ),* : $pattern if $guard ; stringify!( $guard ) ); + check_validation!( @full $( $source ),* : $pattern if $guard ; stringify!( $guard ) ); }; ( @full $( $source:literal ),* : $pattern:pat if $guard:expr ; $guard_string:expr ) => { @@ -864,7 +864,7 @@ fn validation_error(source: &str) -> Result, 4>;", "type Bad = array;", "type Bad = array, 4>;": @@ -874,7 +874,7 @@ fn invalid_arrays() { }) } - check_validation_error! { + check_validation! { "type Bad = array;", r#" let length: f32 = 2.718; @@ -886,7 +886,7 @@ fn invalid_arrays() { }) } - check_validation_error! { + check_validation! { "type Bad = array;", "type Bad = array;": Err(naga::valid::ValidationError::Type { @@ -898,7 +898,7 @@ fn invalid_arrays() { #[test] fn invalid_structs() { - check_validation_error! { + check_validation! { "struct Bad { data: sampler }", "struct Bad { data: texture_2d }": Err(naga::valid::ValidationError::Type { @@ -907,7 +907,7 @@ fn invalid_structs() { }) } - check_validation_error! { + check_validation! { "struct Bad { data: array, other: f32, }": Err(naga::valid::ValidationError::Type { error: naga::valid::TypeError::InvalidDynamicArray(_, _), @@ -915,7 +915,7 @@ fn invalid_structs() { }) } - check_validation_error! { + check_validation! { "struct Empty {}": Err(naga::valid::ValidationError::Type { error: naga::valid::TypeError::EmptyStruct, @@ -926,7 +926,7 @@ fn invalid_structs() { #[test] fn invalid_functions() { - check_validation_error! { + check_validation! { "fn unacceptable_unsized(arg: array) { }", " struct Unsized { data: array } @@ -944,7 +944,7 @@ fn invalid_functions() { } // Pointer's address space cannot hold unsized data. - check_validation_error! { + check_validation! { "fn unacceptable_unsized(arg: ptr>) { }", " struct Unsized { data: array } @@ -960,7 +960,7 @@ fn invalid_functions() { } // Pointers of these storage classes cannot be passed as arguments. - check_validation_error! { + check_validation! { "fn unacceptable_ptr_space(arg: ptr>) { }": Err(naga::valid::ValidationError::Function { name: function_name, @@ -974,7 +974,7 @@ fn invalid_functions() { if function_name == "unacceptable_ptr_space" && argument_name == "arg" } - check_validation_error! { + check_validation! { "fn unacceptable_ptr_space(arg: ptr) { }": Err(naga::valid::ValidationError::Function { name: function_name, @@ -991,7 +991,7 @@ fn invalid_functions() { #[test] fn pointer_type_equivalence() { - check_validation_error! { + check_validation! { r#" fn f(pv: ptr>, pf: ptr) { } @@ -1009,7 +1009,7 @@ fn pointer_type_equivalence() { #[test] fn missing_bindings() { - check_validation_error! { + check_validation! { " @vertex fn vertex(_input: vec4) -> @location(0) vec4 { @@ -1026,7 +1026,7 @@ fn missing_bindings() { }) } - check_validation_error! { + check_validation! { " @vertex fn vertex(@location(0) _input: vec4, more_input: f32) -> @location(0) vec4 { @@ -1043,7 +1043,7 @@ fn missing_bindings() { }) } - check_validation_error! { + check_validation! { " @vertex fn vertex(@location(0) _input: vec4) -> vec4 { @@ -1059,7 +1059,7 @@ fn missing_bindings() { }) } - check_validation_error! { + check_validation! { " struct VertexIn { @location(0) pos: vec4, @@ -1084,7 +1084,7 @@ fn missing_bindings() { #[test] fn invalid_access() { - check_validation_error! { + check_validation! { " fn array_by_value(a: array, i: i32) -> i32 { return a[i]; @@ -1104,7 +1104,7 @@ fn invalid_access() { }) } - check_validation_error! { + check_validation! { r#" fn main() -> f32 { let a = array(0., 1., 2.); @@ -1123,7 +1123,7 @@ fn invalid_access() { #[test] fn valid_access() { - check_validation_error! { + check_validation! { " fn vector_by_value(v: vec4, i: i32) -> i32 { return v[i]; @@ -1150,7 +1150,7 @@ fn valid_access() { #[test] fn invalid_local_vars() { - check_validation_error! { + check_validation! { " struct Unsized { data: array } fn local_ptr_dynamic_array(okay: ptr) { @@ -1171,7 +1171,7 @@ fn invalid_local_vars() { #[test] fn dead_code() { - check_validation_error! { + check_validation! { " fn dead_code_after_if(condition: bool) -> i32 { if (condition) { @@ -1184,7 +1184,7 @@ fn dead_code() { ": Ok(_) } - check_validation_error! { + check_validation! { " fn dead_code_after_block() -> i32 { { @@ -1205,7 +1205,7 @@ fn invalid_runtime_sized_arrays() { // You can't have structs whose last member is an unsized struct. An unsized // array may only appear as the last member of a struct used directly as a // variable's store type. - check_validation_error! { + check_validation! { " struct Unsized { arr: array @@ -1233,7 +1233,7 @@ fn invalid_runtime_sized_arrays() { #[test] fn select() { - check_validation_error! { + check_validation! { " fn select_pointers(which: bool) -> i32 { var x: i32 = 1; @@ -1275,7 +1275,7 @@ fn select() { #[test] fn last_case_falltrough() { - check_validation_error! { + check_validation! { " fn test_falltrough() { switch(0) { @@ -1297,7 +1297,7 @@ fn last_case_falltrough() { #[test] fn missing_default_case() { - check_validation_error! { + check_validation! { " fn test_missing_default_case() { switch(0) { @@ -1318,7 +1318,7 @@ fn missing_default_case() { fn wrong_access_mode() { // The assignments to `global.i` should be forbidden, because they are in // variables whose access mode is `read`, not `read_write`. - check_validation_error! { + check_validation! { " struct Globals { i: i32 From dec07027eebf22e954c9252a6f73622170e228b3 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 29 Apr 2022 15:30:46 -0700 Subject: [PATCH 1723/2212] Split out `check_one_validation` macro from `check_validation`. The new `check_one_validation` macro permits the source code to be a computed expression, not just a string literal. This also cleans up some of the handling of the optional guard expression. --- tests/wgsl-errors.rs | 57 +++++++++++++++++++++++++------------------- 1 file changed, 33 insertions(+), 24 deletions(-) diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 3b2f3aa30..6f0754864 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -810,6 +810,33 @@ fn module_scope_identifier_redefinition() { ); } +/// Check the result of validating a WGSL program against a pattern. +/// +/// Unless you are generating code programmatically, the +/// `check_validation_error` macro will probably be more convenient to +/// use. +macro_rules! check_one_validation { + ( $source:expr, $pattern:pat $( if $guard:expr )? ) => { + let source = $source; + let error = validation_error($source); + if ! matches!(&error, $pattern $( if $guard )? ) { + eprintln!("validation error does not match pattern:\n\ + source code: {}\n\ + \n\ + actual result:\n\ + {:#?}\n\ + \n\ + expected match for pattern:\n\ + {}", + &source, + error, + stringify!($pattern)); + $( eprintln!("if {}", stringify!($guard)); )? + panic!("validation error does not match pattern"); + } + } +} + macro_rules! check_validation { // We want to support an optional guard expression after the pattern, so // that we can check values we can't match against, like strings. @@ -817,33 +844,15 @@ macro_rules! check_validation { // pattern, because Rust treats `?` as a repetition operator, and its count // (0 or 1) will not necessarily match `$source`. ( $( $source:literal ),* : $pattern:pat ) => { - check_validation!( @full $( $source ),* : $pattern if true ; ""); - }; - - ( $( $source:literal ),* : $pattern:pat if $guard:expr ) => { - check_validation!( @full $( $source ),* : $pattern if $guard ; stringify!( $guard ) ); - }; - - ( @full $( $source:literal ),* : $pattern:pat if $guard:expr ; $guard_string:expr ) => { $( - let error = validation_error($source); - if ! matches!(&error, $pattern if $guard) { - eprintln!("validation error does not match pattern:\n\ - source code: {}\n\ - \n\ - actual result:\n\ - {:#?}\n\ - \n\ - expected match for pattern:\n\ - {}{}", - stringify!($source), - error, - stringify!($pattern), - $guard_string); - panic!("validation error does not match pattern"); - } + check_one_validation!($source, $pattern); )* }; + ( $( $source:literal ),* : $pattern:pat if $guard:expr ) => { + $( + check_one_validation!($source, $pattern if $guard); + )* + } } fn validation_error(source: &str) -> Result { From 57e1793143e9ed7937be90f4ef0ea58c7303d61f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 29 Apr 2022 22:02:45 -0700 Subject: [PATCH 1724/2212] Properly check that user-defined IO uses IO-shareable types. Only numeric scalars and vectors, and structs whose members are such values, are permitted as the types of user-defined IO. --- src/proc/mod.rs | 9 ++++ src/valid/interface.rs | 12 +++++ src/valid/type.rs | 23 +++++---- tests/wgsl-errors.rs | 106 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 142 insertions(+), 8 deletions(-) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index ebda58d1e..a4a63abbd 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -67,6 +67,15 @@ impl super::ScalarValue { } } +impl super::ScalarKind { + pub const fn is_numeric(self) -> bool { + match self { + crate::ScalarKind::Sint | crate::ScalarKind::Uint | crate::ScalarKind::Float => true, + crate::ScalarKind::Bool => false, + } + } +} + pub const POINTER_SPAN: u32 = 4; impl super::TypeInner { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 79393f58f..91c121dce 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -39,6 +39,8 @@ pub enum GlobalVariableError { pub enum VaryingError { #[error("The type {0:?} does not match the varying")] InvalidType(Handle), + #[error("The type {0:?} cannot be used for user-defined entry point inputs or outputs")] + NotIOShareableType(Handle), #[error("Interpolation is not valid")] InvalidInterpolation, #[error("Interpolation must be specified on vertex shader outputs and fragment shader inputs")] @@ -101,6 +103,7 @@ struct VaryingContext<'a> { stage: crate::ShaderStage, output: bool, types: &'a UniqueArena, + type_info: &'a Vec, location_mask: &'a mut BitSet, built_ins: &'a mut crate::FastHashSet, capabilities: Capabilities, @@ -270,6 +273,13 @@ impl VaryingContext<'_> { interpolation, sampling, } => { + // Only IO-shareable types may be stored in locations. + if !self.type_info[ty.index()] + .flags + .contains(super::TypeFlags::IO_SHAREABLE) + { + return Err(VaryingError::NotIOShareableType(ty)); + } if !self.location_mask.insert(location as usize) { return Err(VaryingError::BindingCollision { location }); } @@ -485,6 +495,7 @@ impl super::Validator { stage: ep.stage, output: false, types: &module.types, + type_info: &self.types, location_mask: &mut self.location_mask, built_ins: &mut argument_built_ins, capabilities: self.capabilities, @@ -500,6 +511,7 @@ impl super::Validator { stage: ep.stage, output: true, types: &module.types, + type_info: &self.types, location_mask: &mut self.location_mask, built_ins: &mut result_built_ins, capabilities: self.capabilities, diff --git a/src/valid/type.rs b/src/valid/type.rs index 988a8fe5b..71af43e99 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -227,13 +227,17 @@ impl super::Validator { if !self.check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } + let shareable = if kind.is_numeric() { + TypeFlags::IO_SHAREABLE | TypeFlags::HOST_SHAREABLE + } else { + TypeFlags::empty() + }; TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY - | TypeFlags::IO_SHAREABLE - | TypeFlags::HOST_SHAREABLE - | TypeFlags::ARGUMENT, + | TypeFlags::ARGUMENT + | shareable, width as u32, ) } @@ -241,14 +245,19 @@ impl super::Validator { if !self.check_width(kind, width) { return Err(TypeError::InvalidWidth(kind, width)); } + let shareable = if kind.is_numeric() { + TypeFlags::IO_SHAREABLE | TypeFlags::HOST_SHAREABLE + } else { + TypeFlags::empty() + }; let count = if size >= crate::VectorSize::Tri { 4 } else { 2 }; TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY - | TypeFlags::IO_SHAREABLE | TypeFlags::HOST_SHAREABLE - | TypeFlags::ARGUMENT, + | TypeFlags::ARGUMENT + | shareable, count * (width as u32), ) } @@ -265,7 +274,6 @@ impl super::Validator { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY - | TypeFlags::IO_SHAREABLE | TypeFlags::HOST_SHAREABLE | TypeFlags::ARGUMENT, count * (width as u32), @@ -469,8 +477,7 @@ impl super::Validator { } }; - let base_mask = - TypeFlags::COPY | TypeFlags::HOST_SHAREABLE | TypeFlags::IO_SHAREABLE; + let base_mask = TypeFlags::COPY | TypeFlags::HOST_SHAREABLE; TypeInfo { flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag, uniform_layout, diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 6f0754864..bd733d946 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1362,3 +1362,109 @@ fn wrong_access_mode() { if name == "store" } } + +#[test] +fn io_shareable_types() { + for numeric in "i32 u32 f32".split_whitespace() { + let types = format!( + "{} vec2<{}> vec3<{}> vec4<{}>", + numeric, numeric, numeric, numeric + ); + for ty in types.split_whitespace() { + check_one_validation! { + &format!("@vertex + fn f(@location(0) arg: {}) -> @builtin(position) vec4 + {{ return vec4(0.0); }}", + ty), + Ok(_module) + } + } + } + + for ty in "bool + vec2 vec3 vec4 + array + mat2x2 + ptr" + .split_whitespace() + { + check_one_validation! { + &format!("@vertex + fn f(@location(0) arg: {}) -> @builtin(position) vec4 + {{ return vec4(0.0); }}", + ty), + Err( + naga::valid::ValidationError::EntryPoint { + stage: naga::ShaderStage::Vertex, + name, + error: naga::valid::EntryPointError::Argument( + 0, + naga::valid::VaryingError::NotIOShareableType( + _, + ), + ), + }, + ) + if name == "f" + } + } +} + +#[test] +fn host_shareable_types() { + // Host-shareable, constructible types. + let types = "i32 u32 f32 + vec2 vec3 vec4 + mat4x4 + array,4> + AStruct"; + for ty in types.split_whitespace() { + check_one_validation! { + &format!("struct AStruct {{ member: array, 8> }}; + @group(0) @binding(0) var ubuf: {}; + @group(0) @binding(1) var sbuf: {};", + ty, ty), + Ok(_module) + } + } + + // Host-shareable but not constructible types. + let types = "atomic atomic + array,4> + array + AStruct"; + for ty in types.split_whitespace() { + check_one_validation! { + &format!("struct AStruct {{ member: array, 8> }}; + @group(0) @binding(1) var sbuf: {};", + ty), + Ok(_module) + } + } + + // Types that are neither host-shareable nor constructible. + for ty in "bool ptr".split_whitespace() { + check_one_validation! { + &format!("@group(0) @binding(0) var sbuf: {};", ty), + Err( + naga::valid::ValidationError::GlobalVariable { + name, + handle: _, + error: naga::valid::GlobalVariableError::MissingTypeFlags { .. }, + }, + ) + if name == "sbuf" + } + + check_one_validation! { + &format!("@group(0) @binding(0) var ubuf: {};", ty), + Err(naga::valid::ValidationError::GlobalVariable { + name, + handle: _, + error: naga::valid::GlobalVariableError::MissingTypeFlags { .. }, + }, + ) + if name == "ubuf" + } + } +} From 9c8a51830c0348fabb3cda990e2449eea8f9de60 Mon Sep 17 00:00:00 2001 From: Mehmet Oguz Derin Date: Mon, 2 May 2022 16:28:56 +0300 Subject: [PATCH 1725/2212] Use Unicode 14 for WGSL The unicode-xid crate just had a release with Unicode 14 data, which the WGSL spec requires. --- Cargo.toml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 76e30f9cc..1476eb9cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,10 +61,7 @@ serde = { version = "1.0.103", features = ["derive"], optional = true } petgraph = { version ="0.6", optional = true } pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } -# update unicode-xid to the next version since it has been updated to unicode v14 -# (but has no release that includes it yet) -# https://github.com/unicode-rs/unicode-xid/pull/27 -unicode-xid = { version = "0.2.2", optional = true } +unicode-xid = { version = "0.2.3", optional = true } [dev-dependencies] bincode = "1" From 1869c6831e5582e3ee56f724a9ec6b040ba044ce Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 3 May 2022 19:37:24 +0200 Subject: [PATCH 1726/2212] [hlsl-out] zero init struct constructor --- src/back/hlsl/help.rs | 4 ++-- tests/out/hlsl/access.hlsl | 2 +- tests/out/hlsl/interface.hlsl | 4 ++-- tests/out/hlsl/operators.hlsl | 2 +- tests/out/hlsl/quad-vert.hlsl | 4 ++-- tests/out/hlsl/quad.hlsl | 2 +- tests/out/hlsl/skybox.hlsl | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 7612457b1..627524885 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -427,8 +427,8 @@ impl<'a, W: Write> super::Writer<'a, W> { let struct_name = &self.names[&NameKey::Type(constructor.ty)]; writeln!( self.out, - "{}{} {};", - INDENT, struct_name, RETURN_VARIABLE_NAME + "{}{} {} = ({})0;", + INDENT, struct_name, RETURN_VARIABLE_NAME, struct_name )?; for (i, member) in members.iter().enumerate() { let field_name = &self.names[&NameKey::StructMember(constructor.ty, i as u32)]; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 3403cb39e..89dd2ea61 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -48,7 +48,7 @@ void SetMatScalarmOnBaz(Baz obj, float scalar, uint mat_idx, uint vec_idx) { } Baz ConstructBaz(float3x2 arg0) { - Baz ret; + Baz ret = (Baz)0; ret.m_0 = arg0[0]; ret.m_1 = arg0[1]; ret.m_2 = arg0[2]; diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 341b515ec..c88d1ee77 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -40,7 +40,7 @@ struct FragmentInput_fragment { }; VertexOutput ConstructVertexOutput(float4 arg0, float arg1) { - VertexOutput ret; + VertexOutput ret = (VertexOutput)0; ret.position = arg0; ret._varying = arg1; return ret; @@ -55,7 +55,7 @@ VertexOutput_vertex vertex(uint vertex_index : SV_VertexID, uint instance_index } FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) { - FragmentOutput ret; + FragmentOutput ret = (FragmentOutput)0; ret.depth = arg0; ret.sample_mask = arg1; ret.color = arg2; diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 020a28ca4..6eb3994ac 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -12,7 +12,7 @@ struct Foo { }; Foo ConstructFoo(float4 arg0, int arg1) { - Foo ret; + Foo ret = (Foo)0; ret.a = arg0; ret.b = arg1; return ret; diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 9f5e08200..890356040 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -17,7 +17,7 @@ float Constructarray1_float_(float arg0)[1] { } gl_PerVertex Constructgl_PerVertex(float4 arg0, float arg1, float arg2[1], float arg3[1]) { - gl_PerVertex ret; + gl_PerVertex ret = (gl_PerVertex)0; ret.gl_Position = arg0; ret.gl_PointSize = arg1; ret.gl_ClipDistance = arg2; @@ -45,7 +45,7 @@ void main_1() } type_9 Constructtype_9(float2 arg0, float4 arg1) { - type_9 ret; + type_9 ret = (type_9)0; ret.member = arg0; ret.gl_Position = arg1; return ret; diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index d4f7ed54b..9a987af1c 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -18,7 +18,7 @@ struct FragmentInput_frag_main { }; VertexOutput ConstructVertexOutput(float2 arg0, float4 arg1) { - VertexOutput ret; + VertexOutput ret = (VertexOutput)0; ret.uv = arg0; ret.position = arg1; return ret; diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 3664c497c..7d5714a22 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -30,7 +30,7 @@ struct FragmentInput_fs_main { }; VertexOutput ConstructVertexOutput(float4 arg0, float3 arg1) { - VertexOutput ret; + VertexOutput ret = (VertexOutput)0; ret.position = arg0; ret.uv = arg1; return ret; From cf32c2b7f38c985e1c770eeff05a91e0cd15ee04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 2 May 2022 18:20:30 +0100 Subject: [PATCH 1727/2212] glsl-out: Fix feature search in expressions It was also searching in all entry points instead of only in the current one. All samples queries need the ARB_shader_texture_image_samples extension so we need to check if any samples queries are made and if so request the extension. --- src/back/glsl/features.rs | 55 +++++++++++++++++++++++++-------------- src/back/glsl/mod.rs | 1 - 2 files changed, 35 insertions(+), 21 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 61f019682..d3f117045 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -36,6 +36,8 @@ bitflags::bitflags! { const MULTI_VIEW = 1 << 17; /// Fused multiply-add. const FMA = 1 << 18; + /// Texture samples query + const TEXTURE_SAMPLES = 1 << 19; } } @@ -101,7 +103,10 @@ impl FeaturesManager { check_feature!(SAMPLE_VARIABLES, 400, 300); check_feature!(DYNAMIC_ARRAY_SIZE, 430, 310); check_feature!(MULTI_VIEW, 140, 310); - check_feature!(FMA, 400, 310); + // Only available on glsl core, this means that opengl es can't query the number + // of samples in a image and neither do bound checks on the sample argument + // of texelFecth + check_feature!(TEXTURE_SAMPLES, 150); // Return an error if there are missing features if missing.is_empty() { @@ -205,11 +210,19 @@ impl FeaturesManager { writeln!(out, "#extension GL_EXT_multiview : require")?; } - if self.0.contains(Features::FMA) && version.is_es() { + if self.0.contains(Features::FMA) && version >= Version::Embedded(310) { // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_gpu_shader5.txt writeln!(out, "#extension GL_EXT_gpu_shader5 : require")?; } + if self.0.contains(Features::TEXTURE_SAMPLES) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_texture_image_samples.txt + writeln!( + out, + "#extension GL_ARB_shader_texture_image_samples : require" + )?; + } + Ok(()) } } @@ -363,24 +376,26 @@ impl<'a, W> Writer<'a, W> { } } - if self.options.version.supports_fma_function() { - let has_fma = self - .module - .functions - .iter() - .flat_map(|(_, f)| f.expressions.iter()) - .chain( - self.module - .entry_points - .iter() - .flat_map(|e| e.function.expressions.iter()), - ) - .any(|(_, e)| match *e { - Expression::Math { fun, .. } if fun == MathFunction::Fma => true, - _ => false, - }); - if has_fma { - self.features.request(Features::FMA); + // Loop trough all expressions in both functions and entry points + // to check for needed features + for (_, expr) in self + .module + .functions + .iter() + .flat_map(|(_, f)| f.expressions.iter()) + .chain(self.entry_point.function.expressions.iter()) + { + match *expr { + // Check for fused multiply add use + Expression::Math { fun, .. } if fun == MathFunction::Fma => { + self.features.request(Features::FMA) + } + // Check for samples query + Expression::ImageQuery { + query: crate::ImageQuery::NumSamples, + .. + } => self.features.request(Features::TEXTURE_SAMPLES), + _ => {} } } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 7ede19e4a..c645ccf9a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2433,7 +2433,6 @@ impl<'a, W: Write> Writer<'a, W> { } } crate::ImageQuery::NumSamples => { - // assumes ARB_shader_texture_image_samples let fun_name = match class { ImageClass::Sampled { .. } | ImageClass::Depth { .. } => { "textureSamples" From 934fa1691976466cf05a4e14b70bca8bd601bdda Mon Sep 17 00:00:00 2001 From: Hasan Ali Date: Mon, 9 May 2022 22:24:28 +0100 Subject: [PATCH 1728/2212] Implement reverseBits and countOneBits for SPIR-V (#1897) * Implement reverseBits and countOneBits for spir-v * Update tests * Fix type error for glsl countOneBits implementation --- src/back/glsl/mod.rs | 2 +- src/back/spv/block.rs | 16 ++++++--- tests/in/bits.wgsl | 16 +++++++++ tests/out/glsl/bits.main.Compute.glsl | 32 +++++++++++++++++ tests/out/msl/bits.msl | 32 +++++++++++++++++ tests/out/spv/bits.spvasm | 50 ++++++++++++++++++++++++++- tests/out/wgsl/bits.wgsl | 32 +++++++++++++++++ 7 files changed, 174 insertions(+), 6 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c645ccf9a..de0d83feb 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2808,7 +2808,7 @@ impl<'a, W: Write> Writer<'a, W> { // we might need to cast to unsigned integers since // GLSL's findLSB / findMSB always return signed integers let need_extra_paren = { - (fun == Mf::FindLsb || fun == Mf::FindMsb) + (fun == Mf::FindLsb || fun == Mf::FindMsb || fun == Mf::CountOneBits) && match *ctx.info[arg].ty.inner_with(&self.module.types) { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 1bce7d271..c4280a740 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -798,10 +798,18 @@ impl<'w> BlockContext<'w> { arg0_id, )), Mf::Determinant => MathOp::Ext(spirv::GLOp::Determinant), - Mf::ReverseBits | Mf::CountOneBits => { - log::error!("unimplemented math function {:?}", fun); - return Err(Error::FeatureNotImplemented("math function")); - } + Mf::ReverseBits => MathOp::Custom(Instruction::unary( + spirv::Op::BitReverse, + result_type_id, + id, + arg0_id, + )), + Mf::CountOneBits => MathOp::Custom(Instruction::unary( + spirv::Op::BitCount, + result_type_id, + id, + arg0_id, + )), Mf::ExtractBits => { let op = match arg_scalar_kind { Some(crate::ScalarKind::Uint) => spirv::Op::BitFieldUExtract, diff --git a/tests/in/bits.wgsl b/tests/in/bits.wgsl index 1c78dae20..1e05d81f6 100644 --- a/tests/in/bits.wgsl +++ b/tests/in/bits.wgsl @@ -40,4 +40,20 @@ fn main() { u2 = firstTrailingBit(u2); i3 = firstLeadingBit(i3); u = firstLeadingBit(u); + i = countOneBits(i); + i2 = countOneBits(i2); + i3 = countOneBits(i3); + i4 = countOneBits(i4); + u = countOneBits(u); + u2 = countOneBits(u2); + u3 = countOneBits(u3); + u4 = countOneBits(u4); + i = reverseBits(i); + i2 = reverseBits(i2); + i3 = reverseBits(i3); + i4 = reverseBits(i4); + u = reverseBits(u); + u2 = reverseBits(u2); + u3 = reverseBits(u3); + u4 = reverseBits(u4); } diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl index 3166d0136..0cdc8906a 100644 --- a/tests/out/glsl/bits.main.Compute.glsl +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -93,6 +93,38 @@ void main() { i3_ = findMSB(_e124); uint _e126 = u; u = uint(findMSB(_e126)); + int _e128 = i; + i = bitCount(_e128); + ivec2 _e130 = i2_; + i2_ = bitCount(_e130); + ivec3 _e132 = i3_; + i3_ = bitCount(_e132); + ivec4 _e134 = i4_; + i4_ = bitCount(_e134); + uint _e136 = u; + u = uint(bitCount(_e136)); + uvec2 _e138 = u2_; + u2_ = uvec2(bitCount(_e138)); + uvec3 _e140 = u3_; + u3_ = uvec3(bitCount(_e140)); + uvec4 _e142 = u4_; + u4_ = uvec4(bitCount(_e142)); + int _e144 = i; + i = bitfieldReverse(_e144); + ivec2 _e146 = i2_; + i2_ = bitfieldReverse(_e146); + ivec3 _e148 = i3_; + i3_ = bitfieldReverse(_e148); + ivec4 _e150 = i4_; + i4_ = bitfieldReverse(_e150); + uint _e152 = u; + u = bitfieldReverse(_e152); + uvec2 _e154 = u2_; + u2_ = bitfieldReverse(_e154); + uvec3 _e156 = u3_; + u3_ = bitfieldReverse(_e156); + uvec4 _e158 = u4_; + u4_ = bitfieldReverse(_e158); return; } diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index 88503320b..aa35b8c17 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -93,5 +93,37 @@ kernel void main_( i3_ = (((metal::clz(_e124) + 1) % 33) - 1); uint _e126 = u; u = (((metal::clz(_e126) + 1) % 33) - 1); + int _e128 = i; + i = metal::popcount(_e128); + metal::int2 _e130 = i2_; + i2_ = metal::popcount(_e130); + metal::int3 _e132 = i3_; + i3_ = metal::popcount(_e132); + metal::int4 _e134 = i4_; + i4_ = metal::popcount(_e134); + uint _e136 = u; + u = metal::popcount(_e136); + metal::uint2 _e138 = u2_; + u2_ = metal::popcount(_e138); + metal::uint3 _e140 = u3_; + u3_ = metal::popcount(_e140); + metal::uint4 _e142 = u4_; + u4_ = metal::popcount(_e142); + int _e144 = i; + i = metal::reverse_bits(_e144); + metal::int2 _e146 = i2_; + i2_ = metal::reverse_bits(_e146); + metal::int3 _e148 = i3_; + i3_ = metal::reverse_bits(_e148); + metal::int4 _e150 = i4_; + i4_ = metal::reverse_bits(_e150); + uint _e152 = u; + u = metal::reverse_bits(_e152); + metal::uint2 _e154 = u2_; + u2_ = metal::reverse_bits(_e154); + metal::uint3 _e156 = u3_; + u3_ = metal::reverse_bits(_e156); + metal::uint4 _e158 = u4_; + u4_ = metal::reverse_bits(_e158); return; } diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm index 6d224eee2..ddd71d0b7 100644 --- a/tests/out/spv/bits.spvasm +++ b/tests/out/spv/bits.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 119 +; Bound: 151 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -163,5 +163,53 @@ OpStore %23 %116 %117 = OpLoad %6 %27 %118 = OpExtInst %6 %1 FindUMsb %117 OpStore %27 %118 +%119 = OpLoad %4 %19 +%120 = OpBitCount %4 %119 +OpStore %19 %120 +%121 = OpLoad %11 %21 +%122 = OpBitCount %11 %121 +OpStore %21 %122 +%123 = OpLoad %12 %23 +%124 = OpBitCount %12 %123 +OpStore %23 %124 +%125 = OpLoad %13 %25 +%126 = OpBitCount %13 %125 +OpStore %25 %126 +%127 = OpLoad %6 %27 +%128 = OpBitCount %6 %127 +OpStore %27 %128 +%129 = OpLoad %14 %29 +%130 = OpBitCount %14 %129 +OpStore %29 %130 +%131 = OpLoad %15 %31 +%132 = OpBitCount %15 %131 +OpStore %31 %132 +%133 = OpLoad %16 %33 +%134 = OpBitCount %16 %133 +OpStore %33 %134 +%135 = OpLoad %4 %19 +%136 = OpBitReverse %4 %135 +OpStore %19 %136 +%137 = OpLoad %11 %21 +%138 = OpBitReverse %11 %137 +OpStore %21 %138 +%139 = OpLoad %12 %23 +%140 = OpBitReverse %12 %139 +OpStore %23 %140 +%141 = OpLoad %13 %25 +%142 = OpBitReverse %13 %141 +OpStore %25 %142 +%143 = OpLoad %6 %27 +%144 = OpBitReverse %6 %143 +OpStore %27 %144 +%145 = OpLoad %14 %29 +%146 = OpBitReverse %14 %145 +OpStore %29 %146 +%147 = OpLoad %15 %31 +%148 = OpBitReverse %15 %147 +OpStore %31 %148 +%149 = OpLoad %16 %33 +%150 = OpBitReverse %16 %149 +OpStore %33 %150 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index 2bdaf6e9f..ccaebff41 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -87,5 +87,37 @@ fn main() { i3_ = firstLeadingBit(_e124); let _e126 = u; u = firstLeadingBit(_e126); + let _e128 = i; + i = countOneBits(_e128); + let _e130 = i2_; + i2_ = countOneBits(_e130); + let _e132 = i3_; + i3_ = countOneBits(_e132); + let _e134 = i4_; + i4_ = countOneBits(_e134); + let _e136 = u; + u = countOneBits(_e136); + let _e138 = u2_; + u2_ = countOneBits(_e138); + let _e140 = u3_; + u3_ = countOneBits(_e140); + let _e142 = u4_; + u4_ = countOneBits(_e142); + let _e144 = i; + i = reverseBits(_e144); + let _e146 = i2_; + i2_ = reverseBits(_e146); + let _e148 = i3_; + i3_ = reverseBits(_e148); + let _e150 = i4_; + i4_ = reverseBits(_e150); + let _e152 = u; + u = reverseBits(_e152); + let _e154 = u2_; + u2_ = reverseBits(_e154); + let _e156 = u3_; + u3_ = reverseBits(_e156); + let _e158 = u4_; + u4_ = reverseBits(_e158); return; } From f1d72f84338ec1f036cbaa692fa2dae3c94d95d3 Mon Sep 17 00:00:00 2001 From: Hiroaki Yutani Date: Tue, 3 May 2022 12:45:25 +0900 Subject: [PATCH 1729/2212] Show naga-cli instead of cargo run on README --- README.md | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index fe02caf34..8421326d7 100644 --- a/README.md +++ b/README.md @@ -33,12 +33,25 @@ DOT (GraphViz) | :ok: | dot-out | Not a shading language | ## Conversion tool -Naga includes a default binary target, which allows to test the conversion of different code paths. +Naga can be used as a CLI, which allows to test the conversion of different code paths. + +First, install `naga-cli` from crates.io or directly from GitHub. + ```bash -cargo run my_shader.wgsl # validate only -cargo run my_shader.spv my_shader.txt # dump the IR module into a file -cargo run my_shader.spv my_shader.metal --flow-dir flow-dir # convert the SPV to Metal, also dump the SPIR-V flow graph to `flow-dir` -cargo run my_shader.wgsl my_shader.vert --profile es310 # convert the WGSL to GLSL vertex stage under ES 3.20 profile +# release version +cargo install naga-cli + +# development version +cargo install naga-cli --git https://github.com/gfx-rs/naga.git +``` + +Then, you can run `naga` command. + +```bash +naga my_shader.wgsl # validate only +naga my_shader.spv my_shader.txt # dump the IR module into a file +naga my_shader.spv my_shader.metal --flow-dir flow-dir # convert the SPV to Metal, also dump the SPIR-V flow graph to `flow-dir` +naga my_shader.wgsl my_shader.vert --profile es310 # convert the WGSL to GLSL vertex stage under ES 3.20 profile ``` ## Development workflow From af6e2fc7ab3296b71f9472d8fe85ab91a3e72abe Mon Sep 17 00:00:00 2001 From: Hiroaki Yutani Date: Wed, 4 May 2022 11:11:07 +0900 Subject: [PATCH 1730/2212] Describe the usage of `cargo run` --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 8421326d7..fbaa063d7 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,12 @@ naga my_shader.spv my_shader.metal --flow-dir flow-dir # convert the SPV to Meta naga my_shader.wgsl my_shader.vert --profile es310 # convert the WGSL to GLSL vertex stage under ES 3.20 profile ``` +As naga includes a default binary target, you can also use `cargo run` without installation. This is useful when you develop naga itself, or investigate the behavior of naga at a specific commit (e.g. [wgpu](https://github.com/gfx-rs/wgpu) might pin a different version of naga than the `HEAD` of this repository). + +```bash +cargo run my_shader.wgsl +``` + ## Development workflow The main instrument aiding the development is the good old `cargo test --all-features --workspace`, From e312a7adeb5b53b3f9e56c666ea195b1c630a161 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 10 May 2022 05:40:42 +0200 Subject: [PATCH 1731/2212] [hlsl-out] use wrapped constructors when loading from storage address space (#1893) --- src/back/hlsl/help.rs | 42 +++++++++++++++++++++++++++++++++++++ src/back/hlsl/storage.rs | 8 +++++-- tests/out/hlsl/globals.hlsl | 9 +++++++- tests/out/hlsl/shadow.hlsl | 10 ++++++++- 4 files changed, 65 insertions(+), 4 deletions(-) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 627524885..e79b5aceb 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -880,6 +880,48 @@ impl<'a, W: Write> super::Writer<'a, W> { self.wrapped.image_queries.insert(wiq); } } + // Write `WrappedConstructor` for structs that are loaded from `AddressSpace::Storage` + // since they will later be used by the fn `write_storage_load` + crate::Expression::Load { pointer } => { + let pointer_space = func_ctx.info[pointer] + .ty + .inner_with(&module.types) + .pointer_space(); + + if let Some(crate::AddressSpace::Storage { .. }) = pointer_space { + if let Some(ty) = func_ctx.info[handle].ty.handle() { + write_wrapped_constructor(self, ty, module, func_ctx)?; + } + } + + fn write_wrapped_constructor( + writer: &mut super::Writer<'_, W>, + ty: Handle, + module: &crate::Module, + func_ctx: &FunctionCtx, + ) -> BackendResult { + match module.types[ty].inner { + crate::TypeInner::Struct { ref members, .. } => { + for member in members { + write_wrapped_constructor(writer, member.ty, module, func_ctx)?; + } + + let constructor = WrappedConstructor { ty }; + if !writer.wrapped.constructors.contains(&constructor) { + writer + .write_wrapped_constructor_function(module, constructor)?; + writer.wrapped.constructors.insert(constructor); + } + } + crate::TypeInner::Array { base, .. } => { + write_wrapped_constructor(writer, base, module, func_ctx)?; + } + _ => {} + }; + + Ok(()) + } + } crate::Expression::Compose { ty, components: _ } => { let constructor = match module.types[ty].inner { crate::TypeInner::Struct { .. } | crate::TypeInner::Array { .. } => { diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index cea989dee..658090256 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -156,12 +156,16 @@ impl super::Writer<'_, W> { write!(self.out, "}}")?; } crate::TypeInner::Struct { ref members, .. } => { - write!(self.out, "{{")?; + let constructor = super::help::WrappedConstructor { + ty: result_ty.handle().unwrap(), + }; + self.write_wrapped_constructor_function_name(module, constructor)?; + write!(self.out, "(")?; let iter = members .iter() .map(|m| (TypeResolution::Handle(m.ty), m.offset)); self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; - write!(self.out, "}}")?; + write!(self.out, ")")?; } _ => unreachable!(), } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 7b12afdf5..2274aa428 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -18,6 +18,13 @@ void test_msl_packed_vec3_as_arg(float3 arg) return; } +Foo ConstructFoo(float3 arg0, float arg1) { + Foo ret = (Foo)0; + ret.v3_ = arg0; + ret.v1_ = arg1; + return ret; +} + void test_msl_packed_vec3_() { int idx = 1; @@ -27,7 +34,7 @@ void test_msl_packed_vec3_() alignment.Store(0+0, asuint(2.0)); int _expr21 = idx; alignment.Store(_expr21*4+0, asuint(3.0)); - Foo data = {asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))}; + Foo data = ConstructFoo(asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))); float3 unnamed = data.v3_; float2 unnamed_1 = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index b66713092..fe757eaa9 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -77,6 +77,14 @@ VertexOutput_vs_main vs_main(int4 position : LOC0, int4 normal : LOC1) return vertexoutput_1; } +Light ConstructLight(float4x4 arg0, float4 arg1, float4 arg2) { + Light ret = (Light)0; + ret.proj = arg0; + ret.pos = arg1; + ret.color = arg2; + return ret; +} + float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { VertexOutput in_ = { fragmentinput_fs_main.proj_position_1, fragmentinput_fs_main.world_normal_1, fragmentinput_fs_main.world_position_1 }; @@ -98,7 +106,7 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 break; } uint _expr23 = i; - Light light = {float4x4(asfloat(s_lights.Load4(_expr23*96+0+0)), asfloat(s_lights.Load4(_expr23*96+0+16)), asfloat(s_lights.Load4(_expr23*96+0+32)), asfloat(s_lights.Load4(_expr23*96+0+48))), asfloat(s_lights.Load4(_expr23*96+64)), asfloat(s_lights.Load4(_expr23*96+80))}; + Light light = ConstructLight(float4x4(asfloat(s_lights.Load4(_expr23*96+0+0)), asfloat(s_lights.Load4(_expr23*96+0+16)), asfloat(s_lights.Load4(_expr23*96+0+32)), asfloat(s_lights.Load4(_expr23*96+0+48))), asfloat(s_lights.Load4(_expr23*96+64)), asfloat(s_lights.Load4(_expr23*96+80))); uint _expr26 = i; const float _e30 = fetch_shadow(_expr26, mul(in_.world_position, light.proj)); float3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); From c584331f3931a529f83082c927c993dddb2da4a8 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 27 Apr 2022 15:16:50 +0200 Subject: [PATCH 1732/2212] [hlsl-out] use fmod instead of % --- src/back/hlsl/writer.rs | 18 ++++++++++++++++++ tests/out/hlsl/operators.hlsl | 8 ++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 97a141e42..3701d0002 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1795,6 +1795,24 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, left, func_ctx)?; write!(self.out, ")")?; } + // While HLSL supports float operands with the % operator it is only + // defined in cases where both sides are either positive or negative. + Expression::Binary { + op: crate::BinaryOperator::Modulo, + left, + right, + } if func_ctx.info[left] + .ty + .inner_with(&module.types) + .scalar_kind() + == Some(crate::ScalarKind::Float) => + { + write!(self.out, "fmod(")?; + self.write_expr(module, left, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, right, func_ctx)?; + write!(self.out, ")")?; + } Expression::Binary { op, left, right } => { write!(self.out, "(")?; self.write_expr(module, left, func_ctx)?; diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 6eb3994ac..e6356d201 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -110,10 +110,10 @@ void arithmetic() float4 unnamed_36 = ((2.0).xxxx / (1.0).xxxx); int unnamed_37 = (2 % 1); uint unnamed_38 = (2u % 1u); - float unnamed_39 = (2.0 % 1.0); + float unnamed_39 = fmod(2.0, 1.0); int2 unnamed_40 = ((2).xx % (1).xx); uint3 unnamed_41 = ((2u).xxx % (1u).xxx); - float4 unnamed_42 = ((2.0).xxxx % (1.0).xxxx); + float4 unnamed_42 = fmod((2.0).xxxx, (1.0).xxxx); int2 unnamed_43 = ((2).xx + (1).xx); int2 unnamed_44 = ((2).xx + (1).xx); uint2 unnamed_45 = ((2u).xx + (1u).xx); @@ -142,8 +142,8 @@ void arithmetic() int2 unnamed_68 = ((2).xx % (1).xx); uint2 unnamed_69 = ((2u).xx % (1u).xx); uint2 unnamed_70 = ((2u).xx % (1u).xx); - float2 unnamed_71 = ((2.0).xx % (1.0).xx); - float2 unnamed_72 = ((2.0).xx % (1.0).xx); + float2 unnamed_71 = fmod((2.0).xx, (1.0).xx); + float2 unnamed_72 = fmod((2.0).xx, (1.0).xx); float3x3 unnamed_73 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); float3x3 unnamed_74 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); float3x3 unnamed_75 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); From c03d840755144feb0d931707dfffb0fd81d49aee Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 27 Apr 2022 15:55:09 +0200 Subject: [PATCH 1733/2212] [glsl-in] translate mod fn correctly --- src/front/glsl/builtins.rs | 35 ++++++++++++- src/front/glsl/constants.rs | 2 +- tests/out/wgsl/246-collatz-comp.wgsl | 20 ++++---- tests/out/wgsl/math-functions-vert.wgsl | 68 ++++++++++++------------- 4 files changed, 79 insertions(+), 46 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 56cd71e9f..287f66d6f 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1969,14 +1969,45 @@ impl MacroCall { MacroCall::Mod(size) => { ctx.implicit_splat(parser, &mut args[1], meta, size)?; - ctx.add_expression( + // x - y * floor(x / y) + + let div = ctx.add_expression( Expression::Binary { - op: BinaryOperator::Modulo, + op: BinaryOperator::Divide, left: args[0], right: args[1], }, Span::default(), body, + ); + let floor = ctx.add_expression( + Expression::Math { + fun: MathFunction::Floor, + arg: div, + arg1: None, + arg2: None, + arg3: None, + }, + Span::default(), + body, + ); + let mult = ctx.add_expression( + Expression::Binary { + op: BinaryOperator::Multiply, + left: floor, + right: args[1], + }, + Span::default(), + body, + ); + ctx.add_expression( + Expression::Binary { + op: BinaryOperator::Subtract, + left: args[0], + right: mult, + }, + Span::default(), + body, ) } MacroCall::Splatted(fun, size, i) => { diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 3e4bc8b5b..03620ce51 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -506,7 +506,7 @@ impl<'a> ConstantSolver<'a> { BinaryOperator::Subtract => a - b, BinaryOperator::Multiply => a * b, BinaryOperator::Divide => a / b, - BinaryOperator::Modulo => a % b, + BinaryOperator::Modulo => a - b * (a / b).floor(), _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), }) } diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index d54814615..1092f9388 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -18,23 +18,25 @@ fn collatz_iterations(n: u32) -> u32 { } { let _e14 = n_1; - if ((f32(_e14) % f32(2)) == f32(0)) { + let _e15 = f32(_e14); + let _e17 = f32(2); + if ((_e15 - (floor((_e15 / _e17)) * _e17)) == f32(0)) { { - let _e22 = n_1; - n_1 = (_e22 / u32(2)); + let _e25 = n_1; + n_1 = (_e25 / u32(2)); } } else { { - let _e27 = n_1; - n_1 = ((u32(3) * _e27) + u32(1)); + let _e30 = n_1; + n_1 = ((u32(3) * _e30) + u32(1)); } } - let _e33 = i; - i = (_e33 + 1u); + let _e36 = i; + i = (_e36 + 1u); } } - let _e36 = i; - return _e36; + let _e39 = i; + return _e39; } fn main_1() { diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 610adb40a..3fa89d6bc 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -116,41 +116,41 @@ fn main_1() { let _e160 = b; let _e162 = a; let _e164 = b; - modOut = (_e162.x % _e164.x); - let _e170 = a; - let _e171 = b; - powOut = pow(_e170, _e171); - let _e176 = a; - let _e177 = b; - dotOut = dot(_e176, _e177); - let _e182 = a; - let _e183 = b; - maxOut = max(_e182, _e183); - let _e188 = a; - let _e189 = b; - minOut = min(_e188, _e189); - let _e194 = a; - let _e195 = b; - reflectOut = reflect(_e194, _e195); - let _e198 = a; - let _e200 = b; - let _e202 = a; - let _e204 = b; - crossOut = cross(_e202.xyz, _e204.xyz); - let _e210 = a; - let _e211 = b; - outerProductOut = outerProduct(_e210, _e211); - let _e216 = a; - let _e217 = b; - distanceOut = distance(_e216, _e217); - let _e222 = a; - let _e223 = b; - stepOut = step(_e222, _e223); - let _e227 = a; - rad = radians(_e227); + modOut = (_e162.x - (floor((_e162.x / _e164.x)) * _e164.x)); + let _e173 = a; + let _e174 = b; + powOut = pow(_e173, _e174); + let _e179 = a; + let _e180 = b; + dotOut = dot(_e179, _e180); + let _e185 = a; + let _e186 = b; + maxOut = max(_e185, _e186); + let _e191 = a; + let _e192 = b; + minOut = min(_e191, _e192); + let _e197 = a; + let _e198 = b; + reflectOut = reflect(_e197, _e198); + let _e201 = a; + let _e203 = b; + let _e205 = a; + let _e207 = b; + crossOut = cross(_e205.xyz, _e207.xyz); + let _e213 = a; + let _e214 = b; + outerProductOut = outerProduct(_e213, _e214); + let _e219 = a; + let _e220 = b; + distanceOut = distance(_e219, _e220); + let _e225 = a; + let _e226 = b; + stepOut = step(_e225, _e226); let _e230 = a; - let _e232 = a; - deg = degrees(_e232.x); + rad = radians(_e230); + let _e233 = a; + let _e235 = a; + deg = degrees(_e235.x); return; } From 0d4098d6349ac849877aa09254d1f300f15430bf Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 27 Apr 2022 15:59:53 +0200 Subject: [PATCH 1734/2212] [spv-in] translate OpFMod correctly --- src/front/spv/convert.rs | 3 +- src/front/spv/mod.rs | 75 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index b555833ed..365f55d51 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -12,8 +12,7 @@ pub(super) const fn map_binary_operator(word: spirv::Op) -> Result Ok(BinaryOperator::Subtract), Op::IMul | Op::FMul => Ok(BinaryOperator::Multiply), Op::UDiv | Op::SDiv | Op::FDiv => Ok(BinaryOperator::Divide), - Op::UMod | Op::SMod | Op::FMod => Ok(BinaryOperator::Modulo), - Op::SRem => Ok(BinaryOperator::Modulo), + Op::UMod | Op::SMod | Op::SRem => Ok(BinaryOperator::Modulo), // Relational and Logical Instructions Op::IEqual | Op::FOrdEqual | Op::FUnordEqual | Op::LogicalEqual => { Ok(BinaryOperator::Equal) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 5dc8b82e5..342d3a8e3 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2009,10 +2009,83 @@ impl> Parser { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Divide, BINARY)?; } - Op::UMod | Op::FMod | Op::FRem => { + Op::UMod | Op::FRem => { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Modulo, BINARY)?; } + Op::FMod => { + inst.expect(5)?; + + let start = self.data_offset; + let span = self.span_from_with_op(start); + + let result_type_id = self.next()?; + let result_id = self.next()?; + let p1_id = self.next()?; + let p2_id = self.next()?; + + let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let left = self.get_expr_handle( + p1_id, + p1_lexp, + ctx, + &mut emitter, + &mut block, + body_idx, + ); + let p2_lexp = self.lookup_expression.lookup(p2_id)?; + let right = self.get_expr_handle( + p2_id, + p2_lexp, + ctx, + &mut emitter, + &mut block, + body_idx, + ); + + let div = ctx.expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left, + right, + }, + span, + ); + let floor = ctx.expressions.append( + crate::Expression::Math { + fun: crate::MathFunction::Floor, + arg: div, + arg1: None, + arg2: None, + arg3: None, + }, + span, + ); + let mult = ctx.expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Multiply, + left: floor, + right, + }, + span, + ); + let sub = ctx.expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Subtract, + left, + right: mult, + }, + span, + ); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: sub, + type_id: result_type_id, + block_id, + }, + ); + } Op::VectorTimesScalar | Op::VectorTimesMatrix | Op::MatrixTimesScalar From 7109cffb20a83eee499a0899a739d4186952a0ec Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 28 Apr 2022 17:21:05 +0200 Subject: [PATCH 1735/2212] [spv-out] use SRem instead of SMod --- src/back/spv/block.rs | 2 +- tests/out/spv/image.spvasm | 4 ++-- tests/out/spv/operators.spvasm | 12 ++++++------ 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index c4280a740..d492ddf53 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -529,7 +529,7 @@ impl<'w> BlockContext<'w> { _ => unimplemented!(), }, crate::BinaryOperator::Modulo => match left_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Sint) => spirv::Op::SMod, + Some(crate::ScalarKind::Sint) => spirv::Op::SRem, Some(crate::ScalarKind::Uint) => spirv::Op::UMod, Some(crate::ScalarKind::Float) => spirv::Op::FRem, _ => unimplemented!(), diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 89192b737..7ad2b3560 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -213,7 +213,7 @@ OpBranch %84 %88 = OpBitcast %21 %87 %89 = OpIMul %21 %85 %88 %90 = OpCompositeConstruct %21 %3 %5 -%91 = OpSMod %21 %89 %90 +%91 = OpSRem %21 %89 %90 %92 = OpCompositeExtract %13 %75 2 %93 = OpBitcast %4 %92 %95 = OpImageFetch %94 %78 %91 Lod %93 @@ -254,7 +254,7 @@ OpBranch %125 %128 = OpBitcast %21 %127 %129 = OpIMul %21 %126 %128 %130 = OpCompositeConstruct %21 %3 %5 -%131 = OpSMod %21 %129 %130 +%131 = OpSRem %21 %129 %130 %132 = OpCompositeExtract %13 %120 2 %133 = OpBitcast %4 %132 %134 = OpImageFetch %29 %122 %131 Sample %133 diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 8de46ea3d..52063e0fd 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -115,7 +115,7 @@ OpBranch %81 %88 = OpFDiv %31 %86 %87 %89 = OpCompositeConstruct %27 %17 %17 %17 %17 %90 = OpCompositeConstruct %27 %18 %18 %18 %18 -%91 = OpSMod %27 %89 %90 +%91 = OpSRem %27 %89 %90 %92 = OpVectorShuffle %26 %88 %88 0 1 0 1 %93 = OpConvertSToF %26 %91 %94 = OpFAdd %26 %92 %93 @@ -233,12 +233,12 @@ OpBranch %151 %203 = OpCompositeConstruct %26 %14 %14 %14 %14 %204 = OpCompositeConstruct %26 %3 %3 %3 %3 %205 = OpFDiv %26 %203 %204 -%206 = OpSMod %8 %18 %7 +%206 = OpSRem %8 %18 %7 %207 = OpUMod %20 %24 %25 %208 = OpFRem %4 %14 %3 %209 = OpCompositeConstruct %152 %18 %18 %210 = OpCompositeConstruct %152 %7 %7 -%211 = OpSMod %152 %209 %210 +%211 = OpSRem %152 %209 %210 %212 = OpCompositeConstruct %163 %24 %24 %24 %213 = OpCompositeConstruct %163 %25 %25 %25 %214 = OpUMod %163 %212 %213 @@ -317,10 +317,10 @@ OpBranch %151 %287 = OpFDiv %31 %286 %285 %288 = OpCompositeConstruct %152 %18 %18 %289 = OpCompositeConstruct %152 %7 %7 -%290 = OpSMod %152 %288 %289 +%290 = OpSRem %152 %288 %289 %291 = OpCompositeConstruct %152 %7 %7 %292 = OpCompositeConstruct %152 %18 %18 -%293 = OpSMod %152 %292 %291 +%293 = OpSRem %152 %292 %291 %294 = OpCompositeConstruct %34 %24 %24 %295 = OpCompositeConstruct %34 %25 %25 %296 = OpUMod %34 %294 %295 @@ -512,7 +512,7 @@ OpStore %457 %468 %471 = OpSDiv %8 %469 %470 OpStore %457 %471 %472 = OpLoad %8 %457 -%473 = OpSMod %8 %472 %7 +%473 = OpSRem %8 %472 %7 OpStore %457 %473 %474 = OpLoad %8 %457 %475 = OpBitwiseAnd %8 %474 %11 From ecd6d4e4aacb8355cad5f7f3ab50864672aa8d67 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 28 Apr 2022 19:50:08 +0200 Subject: [PATCH 1736/2212] [spv-in] translate OpSMod correctly --- src/front/spv/convert.rs | 2 +- src/front/spv/mod.rs | 106 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 106 insertions(+), 2 deletions(-) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 365f55d51..128f7ceae 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -12,7 +12,7 @@ pub(super) const fn map_binary_operator(word: spirv::Op) -> Result Ok(BinaryOperator::Subtract), Op::IMul | Op::FMul => Ok(BinaryOperator::Multiply), Op::UDiv | Op::SDiv | Op::FDiv => Ok(BinaryOperator::Divide), - Op::UMod | Op::SMod | Op::SRem => Ok(BinaryOperator::Modulo), + Op::SRem => Ok(BinaryOperator::Modulo), // Relational and Logical Instructions Op::IEqual | Op::FOrdEqual | Op::FUnordEqual | Op::LogicalEqual => { Ok(BinaryOperator::Equal) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 342d3a8e3..cf4f50d1d 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1966,7 +1966,6 @@ impl> Parser { | Op::BitwiseXor | Op::BitwiseAnd | Op::SDiv - | Op::SMod | Op::SRem => { inst.expect(5)?; let operator = map_binary_operator(inst.op)?; @@ -2013,9 +2012,114 @@ impl> Parser { inst.expect(5)?; parse_expr_op!(crate::BinaryOperator::Modulo, BINARY)?; } + Op::SMod => { + inst.expect(5)?; + + // x - y * int(floor(float(x) / float(y))) + + let start = self.data_offset; + let result_type_id = self.next()?; + let result_id = self.next()?; + let p1_id = self.next()?; + let p2_id = self.next()?; + let span = self.span_from_with_op(start); + + let p1_lexp = self.lookup_expression.lookup(p1_id)?; + let left = self.get_expr_handle( + p1_id, + p1_lexp, + ctx, + &mut emitter, + &mut block, + body_idx, + ); + let p2_lexp = self.lookup_expression.lookup(p2_id)?; + let right = self.get_expr_handle( + p2_id, + p2_lexp, + ctx, + &mut emitter, + &mut block, + body_idx, + ); + + let left_cast = ctx.expressions.append( + crate::Expression::As { + expr: left, + kind: crate::ScalarKind::Float, + convert: None, + }, + span, + ); + let right_cast = ctx.expressions.append( + crate::Expression::As { + expr: right, + kind: crate::ScalarKind::Float, + convert: None, + }, + span, + ); + let div = ctx.expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Divide, + left: left_cast, + right: right_cast, + }, + span, + ); + let floor = ctx.expressions.append( + crate::Expression::Math { + fun: crate::MathFunction::Floor, + arg: div, + arg1: None, + arg2: None, + arg3: None, + }, + span, + ); + let result_ty = self.lookup_type.lookup(result_type_id)?; + let kind = ctx.type_arena[result_ty.handle] + .inner + .scalar_kind() + .unwrap(); + let cast = ctx.expressions.append( + crate::Expression::As { + expr: floor, + kind, + convert: None, + }, + span, + ); + let mult = ctx.expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Multiply, + left: cast, + right, + }, + span, + ); + let sub = ctx.expressions.append( + crate::Expression::Binary { + op: crate::BinaryOperator::Subtract, + left, + right: mult, + }, + span, + ); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: sub, + type_id: result_type_id, + block_id, + }, + ); + } Op::FMod => { inst.expect(5)?; + // x - y * floor(x / y) + let start = self.data_offset; let span = self.span_from_with_op(start); From 66337af310ca55be296910ba84970775e5c7aba8 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 28 Apr 2022 20:00:21 +0200 Subject: [PATCH 1737/2212] add TODOs for handling undefined behavior --- src/back/glsl/mod.rs | 12 ++++++++++++ src/back/hlsl/writer.rs | 14 ++++++++++++++ src/back/msl/writer.rs | 14 ++++++++++++++ src/back/spv/block.rs | 7 +++++++ 4 files changed, 47 insertions(+) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index de0d83feb..19302f790 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2580,6 +2580,18 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")?; } + // TODO: handle undefined behavior of BinaryOperator::Modulo + // + // sint: + // if right == 0 return 0 + // if left == min(type_of(left)) && right == -1 return 0 + // if sign(left) == -1 || sign(right) == -1 return result as defined by WGSL + // + // uint: + // if right == 0 return 0 + // + // float: + // if right == 0 return ? see https://github.com/gpuweb/gpuweb/issues/2798 BinaryOperation::Modulo => { write!(self.out, "(")?; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 3701d0002..2c1837761 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1795,6 +1795,20 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, left, func_ctx)?; write!(self.out, ")")?; } + + // TODO: handle undefined behavior of BinaryOperator::Modulo + // + // sint: + // if right == 0 return 0 + // if left == min(type_of(left)) && right == -1 return 0 + // if sign(left) != sign(right) return result as defined by WGSL + // + // uint: + // if right == 0 return 0 + // + // float: + // if right == 0 return ? see https://github.com/gpuweb/gpuweb/issues/2798 + // While HLSL supports float operands with the % operator it is only // defined in cases where both sides are either positive or negative. Expression::Binary { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 3448d0c00..2dd256afb 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1482,6 +1482,20 @@ impl Writer { .resolve_type(left) .scalar_kind() .ok_or(Error::UnsupportedBinaryOp(op))?; + + // TODO: handle undefined behavior of BinaryOperator::Modulo + // + // sint: + // if right == 0 return 0 + // if left == min(type_of(left)) && right == -1 return 0 + // if sign(left) == -1 || sign(right) == -1 return result as defined by WGSL + // + // uint: + // if right == 0 return 0 + // + // float: + // if right == 0 return ? see https://github.com/gpuweb/gpuweb/issues/2798 + if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float { write!(self.out, "{}::fmod(", NAMESPACE)?; self.put_expression(left, context, true)?; diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index d492ddf53..d302811db 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -529,8 +529,15 @@ impl<'w> BlockContext<'w> { _ => unimplemented!(), }, crate::BinaryOperator::Modulo => match left_ty_inner.scalar_kind() { + // TODO: handle undefined behavior + // if right == 0 return 0 + // if left == min(type_of(left)) && right == -1 return 0 Some(crate::ScalarKind::Sint) => spirv::Op::SRem, + // TODO: handle undefined behavior + // if right == 0 return 0 Some(crate::ScalarKind::Uint) => spirv::Op::UMod, + // TODO: handle undefined behavior + // if right == 0 return ? see https://github.com/gpuweb/gpuweb/issues/2798 Some(crate::ScalarKind::Float) => spirv::Op::FRem, _ => unimplemented!(), }, From ceb92921c2b7f4d216131fcf10efd4592443a612 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 28 Apr 2022 17:01:14 +0200 Subject: [PATCH 1738/2212] remove named expression entry for phony assignment --- src/back/glsl/mod.rs | 2 + src/back/hlsl/writer.rs | 2 + src/back/msl/writer.rs | 2 + src/back/wgsl/writer.rs | 5 + src/front/wgsl/mod.rs | 5 +- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 2 + tests/out/wgsl/210-bevy-shader-vert.wgsl | 1 + tests/out/wgsl/246-collatz-comp.wgsl | 4 + tests/out/wgsl/277-casting-vert.wgsl | 1 + tests/out/wgsl/280-matrix-cast-vert.wgsl | 1 + .../wgsl/800-out-of-bounds-panic-vert.wgsl | 2 + .../wgsl/900-implicit-conversions-vert.wgsl | 1 + tests/out/wgsl/901-lhs-field-select-vert.wgsl | 1 + tests/out/wgsl/access.wgsl | 14 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 406 ++++++++++++++++++ tests/out/wgsl/bevy-pbr-vert.wgsl | 1 + tests/out/wgsl/bits_glsl-frag.wgsl | 67 +++ tests/out/wgsl/bool-select-frag.wgsl | 5 + tests/out/wgsl/buffer-frag.wgsl | 5 + tests/out/wgsl/clamp-splat-vert.wgsl | 1 + tests/out/wgsl/constant-array-size-vert.wgsl | 1 + tests/out/wgsl/declarations-vert.wgsl | 10 + tests/out/wgsl/expressions-frag.wgsl | 6 + tests/out/wgsl/fma-frag.wgsl | 1 + .../out/wgsl/global-constant-array-vert.wgsl | 1 + tests/out/wgsl/globals.wgsl | 12 +- tests/out/wgsl/images-frag.wgsl | 18 + tests/out/wgsl/long-form-matrix-vert.wgsl | 8 + tests/out/wgsl/math-functions-vert.wgsl | 54 +++ tests/out/wgsl/operators.wgsl | 280 ++++++------ tests/out/wgsl/prepostfix-frag.wgsl | 2 + tests/out/wgsl/samplers-frag.wgsl | 245 +++++++++++ tests/out/wgsl/swizzle_write-frag.wgsl | 5 + 33 files changed, 1014 insertions(+), 157 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 19302f790..cb88562d8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1629,6 +1629,8 @@ impl<'a, W: Write> Writer<'a, W> { Some(self.namer.call(name)) } else if self.need_bake_expressions.contains(&handle) { Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) + } else if info.ref_count == 0 { + Some(self.namer.call("")) } else { None }; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 2c1837761..9a5f2cd61 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1167,6 +1167,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. Some(self.namer.call(name)) + } else if info.ref_count == 0 { + Some(self.namer.call("")) } else { let min_ref_count = func_ctx.expressions[handle].bake_ref_count(); if min_ref_count <= info.ref_count { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 2dd256afb..cae4b6b6b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2436,6 +2436,8 @@ impl Writer { // Don't assume the names in `named_expressions` are unique, // or even valid. Use the `Namer`. Some(self.namer.call(name)) + } else if info.ref_count == 0 { + Some(self.namer.call("")) } else { // If this expression is an index that we're going to first compare // against a limit, and then actually use as an index, then we may diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index f21d82c40..487ea40d8 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -659,6 +659,11 @@ impl Writer { // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. Some(self.namer.call(name)) + } else if info.ref_count == 0 { + write!(self.out, "{}_ = ", level)?; + self.write_expr(module, handle, func_ctx)?; + writeln!(self.out, ";")?; + continue; } else { let expr = &func_ctx.expressions[handle]; let min_ref_count = expr.bake_ref_count(); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 5e5502f4b..87fdccc6d 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3499,15 +3499,12 @@ impl Parser { let _ = lexer.next(); emitter.start(context.expressions); lexer.expect(Token::Operation('='))?; - let expr_id = self.parse_general_expression( + self.parse_general_expression( lexer, context.as_expression(block, &mut emitter), )?; lexer.expect(Token::Separator(';'))?; block.extend(emitter.finish(context.expressions)); - // TODO: the situation here could be improved but - // for now this is necessary to get the expressions emitted - context.named_expressions.insert(expr_id, "_".to_string()); None } "let" => { diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 365fa3470..63e83ddb9 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -47,6 +47,8 @@ fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; + _ = (&global.ViewProj); + _ = (&global_1.Model); main_1(); let _e21 = v_Uv; let _e23 = gl_Position; diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index f7932979b..5447e712c 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -48,6 +48,7 @@ fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; + _ = (&global.ViewProj); main_1(); let _e23 = v_Position; let _e25 = v_Normal; diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 1092f9388..65f47ceb3 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -10,13 +10,16 @@ fn collatz_iterations(n: u32) -> u32 { var n_1: u32; var i: u32 = 0u; + _ = (&global.indices); n_1 = n; + _ = u32(0); loop { let _e7 = n_1; if !((_e7 != u32(1))) { break; } { + _ = n_1; let _e14 = n_1; let _e15 = f32(_e14); let _e17 = f32(2); @@ -46,6 +49,7 @@ fn main_1() { index = _e3.x; let _e6 = index; let _e8 = index; + _ = global.indices[_e8]; let _e11 = index; let _e13 = global.indices[_e11]; let _e14 = collatz_iterations(_e13); diff --git a/tests/out/wgsl/277-casting-vert.wgsl b/tests/out/wgsl/277-casting-vert.wgsl index 3405a8b4c..13c86353b 100644 --- a/tests/out/wgsl/277-casting-vert.wgsl +++ b/tests/out/wgsl/277-casting-vert.wgsl @@ -1,6 +1,7 @@ fn main_1() { var a: f32 = 1.0; + _ = f32(1); } @vertex diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl index b9c5ec5a3..7c34f0756 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl @@ -2,6 +2,7 @@ fn main_1() { var a: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); let _e1 = f32(1); + _ = mat4x4(vec4(_e1, 0.0, 0.0, 0.0), vec4(0.0, _e1, 0.0, 0.0), vec4(0.0, 0.0, _e1, 0.0), vec4(0.0, 0.0, 0.0, _e1)); } @vertex diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index d749d5a1f..fdb5462d4 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -36,6 +36,8 @@ fn main_1() { fn main(@location(0) position: vec2, @location(1) color: vec4) -> VertexOutput { position_1 = position; color_1 = color; + _ = (&global.view_matrix); + _ = (&global_1.world_matrix); main_1(); let _e15 = frag_color; let _e17 = gl_Position; diff --git a/tests/out/wgsl/900-implicit-conversions-vert.wgsl b/tests/out/wgsl/900-implicit-conversions-vert.wgsl index 7e5749c82..a5369f98c 100644 --- a/tests/out/wgsl/900-implicit-conversions-vert.wgsl +++ b/tests/out/wgsl/900-implicit-conversions-vert.wgsl @@ -57,6 +57,7 @@ fn implicit_dims_3(v_6: vec4) { fn main_1() { exact_1(1); implicit(f32(1u)); + _ = vec3(1); implicit_dims_2(vec3(vec3(1))); return; } diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl index ec22e1d57..8f30bc8aa 100644 --- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl +++ b/tests/out/wgsl/901-lhs-field-select-vert.wgsl @@ -1,6 +1,7 @@ fn main_1() { var a: vec4 = vec4(1.0, 1.0, 1.0, 1.0); + _ = vec4(1.0); a.x = 2.0; return; } diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 98d53fb9b..2b88d7aac 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -25,18 +25,18 @@ fn test_matrix_within_struct_accesses() { let _e4 = idx; idx = (_e4 - 1); - let unnamed = baz.m; - let unnamed_1 = baz.m[0]; + _ = baz.m; + _ = baz.m[0]; let _e14 = idx; - let unnamed_2 = baz.m[_e14]; - let unnamed_3 = baz.m[0][1]; + _ = baz.m[_e14]; + _ = baz.m[0][1]; let _e26 = idx; - let unnamed_4 = baz.m[0][_e26]; + _ = baz.m[0][_e26]; let _e30 = idx; - let unnamed_5 = baz.m[_e30][1]; + _ = baz.m[_e30][1]; let _e36 = idx; let _e38 = idx; - let unnamed_6 = baz.m[_e36][_e38]; + _ = baz.m[_e36][_e38]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); let _e50 = idx; idx = (_e50 + 1); diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 725952dde..339012853 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -95,6 +95,17 @@ fn pow5_(x: f32) -> f32 { var x_1: f32; var x2_: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); x_1 = x; let _e42 = x_1; let _e43 = x_1; @@ -112,6 +123,17 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 var smoothFactor: f32; var attenuation: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); distanceSquare_1 = distanceSquare; inverseRangeSquared_1 = inverseRangeSquared; let _e44 = distanceSquare_1; @@ -119,6 +141,7 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 factor = (_e44 * _e45); let _e49 = factor; let _e50 = factor; + _ = (1.0 - (_e49 * _e50)); let _e56 = factor; let _e57 = factor; smoothFactor = clamp((1.0 - (_e56 * _e57)), 0.0, 1.0); @@ -126,6 +149,7 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 let _e65 = smoothFactor; attenuation = (_e64 * _e65); let _e68 = attenuation; + _ = distanceSquare_1; let _e73 = distanceSquare_1; return ((_e68 * 1.0) / max(_e73, 0.0010000000474974513)); } @@ -138,6 +162,17 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { var k: f32; var d: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); roughness_1 = roughness; NoH_1 = NoH; let _e46 = NoH_1; @@ -167,6 +202,17 @@ fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { var lambdaL: f32; var v: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); roughness_3 = roughness_2; NoV_1 = NoV; NoL_1 = NoL; @@ -179,6 +225,7 @@ fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { let _e53 = NoV_1; let _e56 = NoV_1; let _e58 = a2_; + _ = (((_e51 - (_e52 * _e53)) * _e56) + _e58); let _e60 = NoV_1; let _e61 = a2_; let _e62 = NoV_1; @@ -191,6 +238,7 @@ fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { let _e75 = NoL_1; let _e78 = NoL_1; let _e80 = a2_; + _ = (((_e73 - (_e74 * _e75)) * _e78) + _e80); let _e82 = NoL_1; let _e83 = a2_; let _e84 = NoL_1; @@ -208,10 +256,22 @@ fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { var f90_1: f32; var VoH_1: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); f90_1 = f90_; VoH_1 = VoH; let _e45 = f90_1; let _e49 = VoH_1; + _ = (1.0 - _e49); let _e52 = VoH_1; let _e54 = pow5_((1.0 - _e52)); return (f0_ + ((vec3(_e45) - f0_) * _e54)); @@ -222,6 +282,17 @@ fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 { var f90_3: f32; var VoH_3: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); f0_2 = f0_1; f90_3 = f90_2; VoH_3 = VoH_2; @@ -229,6 +300,7 @@ fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 { let _e47 = f90_3; let _e48 = f0_2; let _e51 = VoH_3; + _ = (1.0 - _e51); let _e54 = VoH_3; let _e56 = pow5_((1.0 - _e54)); return (_e46 + ((_e47 - _e48) * _e56)); @@ -239,11 +311,30 @@ fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { var LoH_1: f32; var f90_4: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); f0_4 = f0_3; LoH_1 = LoH; + _ = f0_4; + _ = vec3((50.0 * 0.33000001311302185)); let _e49 = f0_4; + _ = dot(_e49, vec3((50.0 * 0.33000001311302185))); + _ = f0_4; + _ = vec3((50.0 * 0.33000001311302185)); let _e62 = f0_4; f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); + _ = f0_4; + _ = f90_4; + _ = LoH_1; let _e75 = f0_4; let _e76 = f90_4; let _e77 = LoH_1; @@ -263,6 +354,17 @@ fn specular(f0_5: vec3, roughness_4: f32, h_1: vec3, NoV_2: f32, NoL_2 var V: f32; var F: vec3; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); f0_6 = f0_5; roughness_5 = roughness_4; NoV_3 = NoV_2; @@ -270,15 +372,22 @@ fn specular(f0_5: vec3, roughness_4: f32, h_1: vec3, NoV_2: f32, NoL_2 NoH_3 = NoH_2; LoH_3 = LoH_2; specularIntensity_1 = specularIntensity; + _ = roughness_5; + _ = NoH_3; let _e57 = roughness_5; let _e58 = NoH_3; let _e59 = D_GGX(_e57, _e58, h_1); D = _e59; + _ = roughness_5; + _ = NoV_3; + _ = NoL_3; let _e64 = roughness_5; let _e65 = NoV_3; let _e66 = NoL_3; let _e67 = V_SmithGGXCorrelated(_e64, _e65, _e66); V = _e67; + _ = f0_6; + _ = LoH_3; let _e71 = f0_6; let _e72 = LoH_3; let _e73 = fresnel(_e71, _e72); @@ -299,6 +408,17 @@ fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { var lightScatter: f32; var viewScatter: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); roughness_7 = roughness_6; NoV_5 = NoV_4; NoL_5 = NoL_4; @@ -307,10 +427,14 @@ fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { let _e52 = LoH_5; let _e54 = LoH_5; f90_5 = (0.5 + (((2.0 * _e50) * _e52) * _e54)); + _ = f90_5; + _ = NoL_5; let _e62 = f90_5; let _e63 = NoL_5; let _e64 = F_Schlick_1(1.0, _e62, _e63); lightScatter = _e64; + _ = f90_5; + _ = NoV_5; let _e70 = f90_5; let _e71 = NoV_5; let _e72 = F_Schlick_1(1.0, _e70, _e71); @@ -330,20 +454,37 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 var a004_: f32; var AB: vec2; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); f0_8 = f0_7; perceptual_roughness_1 = perceptual_roughness; NoV_7 = NoV_6; + _ = vec4(-(1.0), -(0.027499999850988388), -(0.5720000267028809), 0.02199999988079071); + _ = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -(0.03999999910593033)); let _e62 = perceptual_roughness_1; let _e64 = c0_; let _e66 = c1_; r = ((vec4(_e62) * _e64) + _e66); let _e69 = r; let _e71 = r; + _ = (_e69.x * _e71.x); let _e76 = NoV_7; + _ = (-(9.279999732971191) * _e76); let _e80 = NoV_7; + _ = exp2((-(9.279999732971191) * _e80)); let _e83 = r; let _e85 = r; let _e90 = NoV_7; + _ = (-(9.279999732971191) * _e90); let _e94 = NoV_7; let _e98 = r; let _e101 = r; @@ -361,7 +502,19 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { var perceptualRoughness_1: f32; var clampedPerceptualRoughness: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); perceptualRoughness_1 = perceptualRoughness; + _ = perceptualRoughness_1; let _e45 = perceptualRoughness_1; clampedPerceptualRoughness = clamp(_e45, 0.08900000154972076, 1.0); let _e50 = clampedPerceptualRoughness; @@ -372,6 +525,17 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { fn reinhard(color: vec3) -> vec3 { var color_1: vec3; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); color_1 = color; let _e42 = color_1; let _e45 = color_1; @@ -383,6 +547,17 @@ fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { var max_white_1: f32; var numerator: vec3; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); color_3 = color_2; max_white_1 = max_white; let _e44 = color_3; @@ -398,7 +573,20 @@ fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { fn luminance(v_1: vec3) -> f32 { var v_2: vec3; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); v_2 = v_1; + _ = v_2; + _ = vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023); let _e47 = v_2; return dot(_e47, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); } @@ -408,8 +596,20 @@ fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { var l_out_1: f32; var l_in: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); c_in_1 = c_in; l_out_1 = l_out; + _ = c_in_1; let _e45 = c_in_1; let _e46 = luminance(_e45); l_in = _e46; @@ -424,13 +624,27 @@ fn reinhard_luminance(color_4: vec3) -> vec3 { var l_old: f32; var l_new: f32; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); color_5 = color_4; + _ = color_5; let _e43 = color_5; let _e44 = luminance(_e43); l_old = _e44; let _e46 = l_old; let _e48 = l_old; l_new = (_e46 / (1.0 + _e48)); + _ = color_5; + _ = l_new; let _e54 = color_5; let _e55 = l_new; let _e56 = change_luminance(_e54, _e55); @@ -444,8 +658,20 @@ fn reinhard_extended_luminance(color_6: vec3, max_white_l: f32) -> vec3, max_white_l: f32) -> vec3, V_ var specular_1: vec3; var diffuse: vec3; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); light_1 = light; roughness_9 = roughness_8; NdotV_1 = NdotV; @@ -501,10 +740,14 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ let _e57 = light_1.pos; let _e59 = v_WorldPosition_1; light_to_frag = (_e57.xyz - _e59.xyz); + _ = light_to_frag; + _ = light_to_frag; let _e65 = light_to_frag; let _e66 = light_to_frag; distance_square = dot(_e65, _e66); + _ = distance_square; let _e71 = light_1.lightParams; + _ = _e71.x; let _e73 = distance_square; let _e75 = light_1.lightParams; let _e77 = getDistanceAttenuation(_e73, _e75.x); @@ -513,6 +756,8 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ a_1 = _e79; let _e82 = light_1.lightParams; radius = _e82.y; + _ = light_to_frag; + _ = R_1; let _e87 = light_to_frag; let _e88 = R_1; let _e90 = R_1; @@ -521,18 +766,34 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ let _e95 = light_to_frag; let _e96 = centerToRay; let _e97 = radius; + _ = centerToRay; + _ = centerToRay; let _e100 = centerToRay; let _e101 = centerToRay; + _ = dot(_e100, _e101); + _ = centerToRay; + _ = centerToRay; let _e105 = centerToRay; let _e106 = centerToRay; + _ = (_e97 * inverseSqrt(dot(_e105, _e106))); let _e112 = radius; + _ = centerToRay; + _ = centerToRay; let _e115 = centerToRay; let _e116 = centerToRay; + _ = dot(_e115, _e116); + _ = centerToRay; + _ = centerToRay; let _e120 = centerToRay; let _e121 = centerToRay; closestPoint = (_e95 + (_e96 * clamp((_e112 * inverseSqrt(dot(_e120, _e121))), 0.0, 1.0))); + _ = closestPoint; + _ = closestPoint; let _e133 = closestPoint; let _e134 = closestPoint; + _ = dot(_e133, _e134); + _ = closestPoint; + _ = closestPoint; let _e138 = closestPoint; let _e139 = closestPoint; LspecLengthInverse = inverseSqrt(dot(_e138, _e139)); @@ -540,6 +801,7 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ let _e144 = a_1; let _e145 = radius; let _e148 = LspecLengthInverse; + _ = (_e144 + ((_e145 * 0.5) * _e148)); let _e153 = a_1; let _e154 = radius; let _e157 = LspecLengthInverse; @@ -552,24 +814,48 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ L = (_e169 * _e170); let _e173 = L; let _e174 = V_2; + _ = (_e173 + _e174); let _e176 = L; let _e177 = V_2; H = normalize((_e176 + _e177)); + _ = N_1; + _ = L; let _e183 = N_1; let _e184 = L; + _ = dot(_e183, _e184); + _ = N_1; + _ = L; let _e190 = N_1; let _e191 = L; NoL_6 = clamp(dot(_e190, _e191), 0.0, 1.0); + _ = N_1; + _ = H; let _e199 = N_1; let _e200 = H; + _ = dot(_e199, _e200); + _ = N_1; + _ = H; let _e206 = N_1; let _e207 = H; NoH_4 = clamp(dot(_e206, _e207), 0.0, 1.0); + _ = L; + _ = H; let _e215 = L; let _e216 = H; + _ = dot(_e215, _e216); + _ = L; + _ = H; let _e222 = L; let _e223 = H; LoH_6 = clamp(dot(_e222, _e223), 0.0, 1.0); + _ = F0_1; + _ = roughness_9; + _ = H; + _ = NdotV_1; + _ = NoL_6; + _ = NoH_4; + _ = LoH_6; + _ = specularIntensity_2; let _e237 = F0_1; let _e238 = roughness_9; let _e239 = H; @@ -580,29 +866,50 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ let _e244 = specularIntensity_2; let _e245 = specular(_e237, _e238, _e239, _e240, _e241, _e242, _e243, _e244); specular_1 = _e245; + _ = light_to_frag; let _e248 = light_to_frag; L = normalize(_e248); let _e250 = L; let _e251 = V_2; + _ = (_e250 + _e251); let _e253 = L; let _e254 = V_2; H = normalize((_e253 + _e254)); + _ = N_1; + _ = L; let _e259 = N_1; let _e260 = L; + _ = dot(_e259, _e260); + _ = N_1; + _ = L; let _e266 = N_1; let _e267 = L; NoL_6 = clamp(dot(_e266, _e267), 0.0, 1.0); + _ = N_1; + _ = H; let _e274 = N_1; let _e275 = H; + _ = dot(_e274, _e275); + _ = N_1; + _ = H; let _e281 = N_1; let _e282 = H; NoH_4 = clamp(dot(_e281, _e282), 0.0, 1.0); + _ = L; + _ = H; let _e289 = L; let _e290 = H; + _ = dot(_e289, _e290); + _ = L; + _ = H; let _e296 = L; let _e297 = H; LoH_6 = clamp(dot(_e296, _e297), 0.0, 1.0); let _e302 = diffuseColor_1; + _ = roughness_9; + _ = NdotV_1; + _ = NoL_6; + _ = LoH_6; let _e307 = roughness_9; let _e308 = NdotV_1; let _e309 = NoL_6; @@ -635,6 +942,17 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: var specularIntensity_3: f32 = 1.0; var specular_2: vec3; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); light_3 = light_2; roughness_11 = roughness_10; NdotV_3 = NdotV_2; @@ -647,31 +965,59 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: incident_light = _e57.xyz; let _e60 = incident_light; let _e61 = view_1; + _ = (_e60 + _e61); let _e63 = incident_light; let _e64 = view_1; half_vector = normalize((_e63 + _e64)); + _ = normal_1; + _ = incident_light; let _e70 = normal_1; let _e71 = incident_light; + _ = dot(_e70, _e71); + _ = normal_1; + _ = incident_light; let _e77 = normal_1; let _e78 = incident_light; NoL_7 = clamp(dot(_e77, _e78), 0.0, 1.0); + _ = normal_1; + _ = half_vector; let _e86 = normal_1; let _e87 = half_vector; + _ = dot(_e86, _e87); + _ = normal_1; + _ = half_vector; let _e93 = normal_1; let _e94 = half_vector; NoH_5 = clamp(dot(_e93, _e94), 0.0, 1.0); + _ = incident_light; + _ = half_vector; let _e102 = incident_light; let _e103 = half_vector; + _ = dot(_e102, _e103); + _ = incident_light; + _ = half_vector; let _e109 = incident_light; let _e110 = half_vector; LoH_7 = clamp(dot(_e109, _e110), 0.0, 1.0); let _e116 = diffuseColor_3; + _ = roughness_11; + _ = NdotV_3; + _ = NoL_7; + _ = LoH_7; let _e121 = roughness_11; let _e122 = NdotV_3; let _e123 = NoL_7; let _e124 = LoH_7; let _e125 = Fd_Burley(_e121, _e122, _e123, _e124); diffuse_1 = (_e116 * _e125); + _ = F0_3; + _ = roughness_11; + _ = half_vector; + _ = NdotV_3; + _ = NoL_7; + _ = NoH_5; + _ = LoH_7; + _ = specularIntensity_3; let _e138 = F0_3; let _e139 = roughness_11; let _e140 = half_vector; @@ -715,12 +1061,15 @@ fn main_1() { var diffuse_ambient: vec3; var specular_ambient: vec3; + _ = (&global.ViewProj); let _e40 = global_3.base_color; output_color = _e40; let _e42 = output_color; + _ = v_Uv_1; let _e44 = v_Uv_1; let _e45 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e44); output_color = (_e42 * _e45); + _ = v_Uv_1; let _e48 = v_Uv_1; let _e49 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e48); metallic_roughness = _e49; @@ -730,14 +1079,19 @@ fn main_1() { let _e56 = global_4.perceptual_roughness; let _e57 = metallic_roughness; perceptual_roughness_2 = (_e56 * _e57.y); + _ = perceptual_roughness_2; let _e62 = perceptual_roughness_2; let _e63 = perceptualRoughnessToRoughness(_e62); roughness_12 = _e63; + _ = v_WorldNormal_1; let _e66 = v_WorldNormal_1; N_2 = normalize(_e66); let _e69 = v_WorldTangent_1; + _ = _e69.xyz; let _e71 = v_WorldTangent_1; T = normalize(_e71.xyz); + _ = N_2; + _ = T; let _e77 = N_2; let _e78 = T; let _e80 = v_WorldTangent_1; @@ -777,18 +1131,24 @@ fn main_1() { let _e105 = N_2; TBN = mat3x3(vec3(_e103.x, _e103.y, _e103.z), vec3(_e104.x, _e104.y, _e104.z), vec3(_e105.x, _e105.y, _e105.z)); let _e120 = TBN; + _ = v_Uv_1; let _e122 = v_Uv_1; let _e123 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e122); + _ = ((_e123.xyz * 2.0) - vec3(1.0)); + _ = v_Uv_1; let _e131 = v_Uv_1; let _e132 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e131); N_2 = (_e120 * normalize(((_e132.xyz * 2.0) - vec3(1.0)))); + _ = v_Uv_1; let _e142 = v_Uv_1; let _e143 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e142); occlusion = _e143.x; let _e146 = global_7.emissive; emissive = _e146; let _e148 = emissive; + _ = _e148.xyz; let _e150 = emissive; + _ = v_Uv_1; let _e153 = v_Uv_1; let _e154 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e153); let _e156 = (_e150.xyz * _e154.xyz); @@ -797,11 +1157,17 @@ fn main_1() { emissive.z = _e156.z; let _e163 = global_1.CameraPos; let _e165 = v_WorldPosition_1; + _ = (_e163.xyz - _e165.xyz); let _e168 = global_1.CameraPos; let _e170 = v_WorldPosition_1; V_3 = normalize((_e168.xyz - _e170.xyz)); + _ = N_2; + _ = V_3; let _e177 = N_2; let _e178 = V_3; + _ = dot(_e177, _e178); + _ = N_2; + _ = V_3; let _e183 = N_2; let _e184 = V_3; NdotV_4 = max(dot(_e183, _e184), 0.0010000000474974513); @@ -815,9 +1181,12 @@ fn main_1() { let _e209 = metallic; diffuseColor_4 = (_e206.xyz * vec3((1.0 - _e209))); let _e214 = V_3; + _ = -(_e214); + _ = N_2; let _e217 = V_3; let _e219 = N_2; R_4 = reflect(-(_e217), _e219); + _ = vec3(0.0); loop { let _e227 = i; let _e228 = global_2.NumLights; @@ -828,6 +1197,14 @@ fn main_1() { { let _e239 = light_accum; let _e240 = i; + _ = global_2.PointLights[_e240]; + _ = roughness_12; + _ = NdotV_4; + _ = N_2; + _ = V_3; + _ = R_4; + _ = F0_4; + _ = diffuseColor_4; let _e250 = i; let _e252 = global_2.PointLights[_e250]; let _e253 = roughness_12; @@ -855,6 +1232,14 @@ fn main_1() { { let _e276 = light_accum; let _e277 = i_1; + _ = global_2.DirectionalLights[_e277]; + _ = roughness_12; + _ = NdotV_4; + _ = N_2; + _ = V_3; + _ = R_4; + _ = F0_4; + _ = diffuseColor_4; let _e287 = i_1; let _e289 = global_2.DirectionalLights[_e287]; let _e290 = roughness_12; @@ -872,21 +1257,28 @@ fn main_1() { i_1 = (_e273 + 1); } } + _ = diffuseColor_4; + _ = NdotV_4; let _e302 = diffuseColor_4; let _e304 = NdotV_4; let _e305 = EnvBRDFApprox(_e302, 1.0, _e304); diffuse_ambient = _e305; + _ = F0_4; + _ = perceptual_roughness_2; + _ = NdotV_4; let _e310 = F0_4; let _e311 = perceptual_roughness_2; let _e312 = NdotV_4; let _e313 = EnvBRDFApprox(_e310, _e311, _e312); specular_ambient = _e313; let _e315 = output_color; + _ = _e315.xyz; let _e317 = light_accum; output_color.x = _e317.x; output_color.y = _e317.y; output_color.z = _e317.z; let _e324 = output_color; + _ = _e324.xyz; let _e326 = output_color; let _e328 = diffuse_ambient; let _e329 = specular_ambient; @@ -897,6 +1289,7 @@ fn main_1() { output_color.y = _e336.y; output_color.z = _e336.z; let _e343 = output_color; + _ = _e343.xyz; let _e345 = output_color; let _e347 = emissive; let _e349 = output_color; @@ -905,7 +1298,9 @@ fn main_1() { output_color.y = _e352.y; output_color.z = _e352.z; let _e359 = output_color; + _ = _e359.xyz; let _e361 = output_color; + _ = _e361.xyz; let _e363 = output_color; let _e365 = reinhard_luminance(_e363.xyz); output_color.x = _e365.x; @@ -923,6 +1318,17 @@ fn main(@location(0) v_WorldPosition: vec3, @location(1) v_WorldNormal: vec v_Uv_1 = v_Uv; v_WorldTangent_1 = v_WorldTangent; gl_FrontFacing = param; + _ = (&global.ViewProj); + _ = (&global_1.CameraPos); + _ = (&global_2.AmbientColor); + _ = (&global_2.NumLights); + _ = (&global_2.PointLights); + _ = (&global_2.DirectionalLights); + _ = (&global_3.base_color); + _ = (&global_4.perceptual_roughness); + _ = (&global_5.metallic); + _ = (&global_6.reflectance); + _ = (&global_7.emissive); main_1(); let _e72 = o_Target; return FragmentOutput(_e72); diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index ac13dcdfd..dd4c17496 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -58,6 +58,7 @@ fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; Vertex_Tangent_1 = Vertex_Tangent; + _ = (&global.ViewProj); main_1(); let _e29 = v_WorldPosition; let _e31 = v_WorldNormal; diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 012f51f46..8e1fb15f4 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -10,96 +10,163 @@ fn main_1() { var f2_: vec2 = vec2(0.0, 0.0); var f4_: vec4 = vec4(0.0, 0.0, 0.0, 0.0); + _ = vec2(0); + _ = vec3(0); + _ = vec4(0); + _ = u32(0); + _ = vec2(u32(0)); + _ = vec3(u32(0)); + _ = vec4(u32(0)); + _ = vec2(0.0); + _ = vec4(0.0); + _ = f4_; let _e33 = f4_; u = pack4x8snorm(_e33); + _ = f4_; let _e36 = f4_; u = pack4x8unorm(_e36); + _ = f2_; let _e39 = f2_; u = pack2x16unorm(_e39); + _ = f2_; let _e42 = f2_; u = pack2x16snorm(_e42); + _ = f2_; let _e45 = f2_; u = pack2x16float(_e45); + _ = u; let _e48 = u; f4_ = unpack4x8snorm(_e48); + _ = u; let _e51 = u; f4_ = unpack4x8unorm(_e51); + _ = u; let _e54 = u; f2_ = unpack2x16snorm(_e54); + _ = u; let _e57 = u; f2_ = unpack2x16unorm(_e57); + _ = u; let _e60 = u; f2_ = unpack2x16float(_e60); + _ = i; + _ = i; let _e66 = i; let _e67 = i; + _ = u32(10); i = insertBits(_e66, _e67, u32(5), u32(10)); + _ = i2_; + _ = i2_; let _e77 = i2_; let _e78 = i2_; + _ = u32(10); i2_ = insertBits(_e77, _e78, u32(5), u32(10)); + _ = i3_; + _ = i3_; let _e88 = i3_; let _e89 = i3_; + _ = u32(10); i3_ = insertBits(_e88, _e89, u32(5), u32(10)); + _ = i4_; + _ = i4_; let _e99 = i4_; let _e100 = i4_; + _ = u32(10); i4_ = insertBits(_e99, _e100, u32(5), u32(10)); + _ = u; + _ = u; let _e110 = u; let _e111 = u; + _ = u32(10); u = insertBits(_e110, _e111, u32(5), u32(10)); + _ = u2_; + _ = u2_; let _e121 = u2_; let _e122 = u2_; + _ = u32(10); u2_ = insertBits(_e121, _e122, u32(5), u32(10)); + _ = u3_; + _ = u3_; let _e132 = u3_; let _e133 = u3_; + _ = u32(10); u3_ = insertBits(_e132, _e133, u32(5), u32(10)); + _ = u4_; + _ = u4_; let _e143 = u4_; let _e144 = u4_; + _ = u32(10); u4_ = insertBits(_e143, _e144, u32(5), u32(10)); + _ = i; let _e153 = i; i = extractBits(_e153, u32(5), u32(10)); + _ = i2_; let _e162 = i2_; i2_ = extractBits(_e162, u32(5), u32(10)); + _ = i3_; let _e171 = i3_; i3_ = extractBits(_e171, u32(5), u32(10)); + _ = i4_; let _e180 = i4_; i4_ = extractBits(_e180, u32(5), u32(10)); + _ = u; let _e189 = u; u = extractBits(_e189, u32(5), u32(10)); + _ = u2_; let _e198 = u2_; u2_ = extractBits(_e198, u32(5), u32(10)); + _ = u3_; let _e207 = u3_; u3_ = extractBits(_e207, u32(5), u32(10)); + _ = u4_; let _e216 = u4_; u4_ = extractBits(_e216, u32(5), u32(10)); + _ = i; let _e223 = i; i = firstTrailingBit(_e223); + _ = i2_; let _e226 = i2_; i2_ = firstTrailingBit(_e226); + _ = i3_; let _e229 = i3_; i3_ = firstTrailingBit(_e229); + _ = i4_; let _e232 = i4_; i4_ = firstTrailingBit(_e232); + _ = u; let _e235 = u; i = i32(firstTrailingBit(_e235)); + _ = u2_; let _e239 = u2_; i2_ = vec2(firstTrailingBit(_e239)); + _ = u3_; let _e243 = u3_; i3_ = vec3(firstTrailingBit(_e243)); + _ = u4_; let _e247 = u4_; i4_ = vec4(firstTrailingBit(_e247)); + _ = i; let _e251 = i; i = firstLeadingBit(_e251); + _ = i2_; let _e254 = i2_; i2_ = firstLeadingBit(_e254); + _ = i3_; let _e257 = i3_; i3_ = firstLeadingBit(_e257); + _ = i4_; let _e260 = i4_; i4_ = firstLeadingBit(_e260); + _ = u; let _e263 = u; i = i32(firstLeadingBit(_e263)); + _ = u2_; let _e267 = u2_; i2_ = vec2(firstLeadingBit(_e267)); + _ = u3_; let _e271 = u3_; i3_ = vec3(firstLeadingBit(_e271)); + _ = u4_; let _e275 = u4_; i4_ = vec4(firstLeadingBit(_e275)); return; diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index 4f0e218ee..c34fc979d 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -21,6 +21,8 @@ fn TevPerCompGT_1(a_2: vec3, b_2: vec3) -> vec3 { a_3 = a_2; b_3 = b_2; + _ = a_3; + _ = b_3; let _e7 = a_3; let _e8 = b_3; return select(vec3(0.0), vec3(1.0), (_e7 > _e8)); @@ -28,6 +30,9 @@ fn TevPerCompGT_1(a_2: vec3, b_2: vec3) -> vec3 { fn main_1() { let _e1 = o_color; + _ = _e1.xyz; + _ = vec3(3.0); + _ = vec3(5.0); let _e11 = TevPerCompGT_1(vec3(3.0), vec3(5.0)); o_color.x = _e11.x; o_color.y = _e11.y; diff --git a/tests/out/wgsl/buffer-frag.wgsl b/tests/out/wgsl/buffer-frag.wgsl index 4f561b427..3408a69d9 100644 --- a/tests/out/wgsl/buffer-frag.wgsl +++ b/tests/out/wgsl/buffer-frag.wgsl @@ -21,6 +21,9 @@ fn main_1() { var a: u32; var b: u32; + _ = (&testBuffer.data); + _ = (&testBufferWriteOnly.data); + _ = (&testBufferReadOnly.data); let _e12 = testBuffer.data[0]; a = _e12; testBuffer.data[1] = u32(2); @@ -32,6 +35,8 @@ fn main_1() { @fragment fn main() { + _ = (&testBuffer.data); + _ = (&testBufferWriteOnly.data); main_1(); return; } diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index deeea02ef..777b562b3 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -6,6 +6,7 @@ var a_pos_1: vec2; var gl_Position: vec4; fn main_1() { + _ = a_pos_1; let _e5 = a_pos_1; let _e10 = clamp(_e5, vec2(0.0), vec2(1.0)); gl_Position = vec4(_e10.x, _e10.y, 0.0, 1.0); diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 16acd616e..ba193b7c5 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -9,6 +9,7 @@ fn function_() -> vec4 { var sum: vec4 = vec4(0.0, 0.0, 0.0, 0.0); var i: i32 = 0; + _ = vec4(f32(0)); loop { let _e9 = i; if !((_e9 < 42)) { diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index 555407e46..f0ab4c0fa 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -34,6 +34,12 @@ fn main_1() { var a_1: f32; var b: f32; + _ = (&vert.position); + _ = (&vert.a); + _ = (&frag.position); + _ = (&frag.a); + _ = array,2u>(vec3(-(1.0), 1.0, 0.0), vec3(-(1.0), -(1.0), 0.0)); + _ = TestStruct(f32(1), f32(2)); let _e35 = in_array_2[1]; from_input_array = _e35; let _e41 = array_2d[0][0]; @@ -50,6 +56,10 @@ fn main(@location(0) position: vec2, @location(1) a: vec2, @location(2 vert.a = a; in_array_2[0] = in_array; in_array_2[1] = in_array_1; + _ = (&vert.position); + _ = (&vert.a); + _ = (&frag.position); + _ = (&frag.a); main_1(); let _e30 = frag.position; let _e32 = frag.a; diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 984e28cad..b4364e597 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -270,16 +270,19 @@ fn testUnaryOpMat(a_16: mat3x3) { fn testStructConstructor() { var tree: BST = BST(1); + _ = BST(1); } fn testNonScalarToScalarConstructor() { var f: f32 = 1.0; + _ = f32(mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0))[0].x); } fn testArrayConstructor() { var tree_1: array = array(0.0); + _ = array(0.0); } fn testFreestandingConstructor() { @@ -290,6 +293,7 @@ fn testNonImplicitCastVectorCast() { var a_18: u32 = 1u; var b_16: vec4; + _ = u32(1); let _e3 = a_18; b_16 = vec4(i32(_e3)); return; @@ -355,12 +359,14 @@ fn ternary(a_20: bool) { fn main_1() { var local_5: f32; + _ = global; let _e3 = global; local_5 = _e3; privatePointer((&local_5)); let _e5 = local_5; global = _e5; let _e6 = o_color; + _ = _e6.xyzw; let _e9 = vec4(1.0); o_color.x = _e9.x; o_color.y = _e9.y; diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 2361221f1..cf4c6ff76 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -33,6 +33,7 @@ fn Fma(d: ptr, m: Mat4x3_, s: f32) { fn main_1() { let _e1 = o_color; + _ = _e1.xyzw; let _e4 = vec4(1.0); o_color.x = _e4.x; o_color.y = _e4.y; diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index 6ef3214e7..a74aa3f2c 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -8,6 +8,7 @@ fn main_1() { @vertex fn main() { + _ = array(1.0, 2.0); main_1(); return; } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 42f39a097..77435cabc 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -31,13 +31,13 @@ fn test_msl_packed_vec3_() { let _e21 = idx; alignment.v3_[_e21] = 3.0; let data = alignment; - let unnamed = data.v3_; - let unnamed_1 = data.v3_.zx; + _ = data.v3_; + _ = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); - let unnamed_2 = (data.v3_ * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_3 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * data.v3_); - let unnamed_4 = (data.v3_ * 2.0); - let unnamed_5 = (2.0 * data.v3_); + _ = (data.v3_ * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + _ = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * data.v3_); + _ = (data.v3_ * 2.0); + _ = (2.0 * data.v3_); } @compute @workgroup_size(1, 1, 1) diff --git a/tests/out/wgsl/images-frag.wgsl b/tests/out/wgsl/images-frag.wgsl index 7be742365..6b0345923 100644 --- a/tests/out/wgsl/images-frag.wgsl +++ b/tests/out/wgsl/images-frag.wgsl @@ -23,8 +23,11 @@ fn testImg1D(coord: i32) { coord_1 = coord; let _e10 = textureDimensions(img1D); size = _e10; + _ = coord_1; + _ = vec4(f32(2)); let _e16 = coord_1; textureStore(img1D, _e16, vec4(f32(2))); + _ = coord_1; let _e21 = coord_1; let _e22 = textureLoad(img1D, _e21); c = _e22; @@ -40,9 +43,12 @@ fn testImg1DArray(coord_2: vec2) { let _e10 = textureDimensions(img1DArray); let _e11 = textureNumLayers(img1DArray); size_1 = vec2(vec2(_e10, _e11)); + _ = coord_3; let _e16 = coord_3; let _e19 = textureLoad(img1DArray, _e16.x, _e16.y); c_1 = _e19; + _ = coord_3; + _ = vec4(f32(2)); let _e25 = coord_3; textureStore(img1DArray, _e25.x, _e25.y, vec4(f32(2))); return; @@ -56,9 +62,12 @@ fn testImg2D(coord_4: vec2) { coord_5 = coord_4; let _e10 = textureDimensions(img2D); size_2 = vec2(_e10); + _ = coord_5; let _e14 = coord_5; let _e15 = textureLoad(img2D, _e14); c_2 = _e15; + _ = coord_5; + _ = vec4(f32(2)); let _e21 = coord_5; textureStore(img2D, _e21, vec4(f32(2))); return; @@ -73,9 +82,12 @@ fn testImg2DArray(coord_6: vec3) { let _e10 = textureDimensions(img2DArray); let _e13 = textureNumLayers(img2DArray); size_3 = vec3(vec3(_e10.x, _e10.y, _e13)); + _ = coord_7; let _e18 = coord_7; let _e21 = textureLoad(img2DArray, _e18.xy, _e18.z); c_3 = _e21; + _ = coord_7; + _ = vec4(f32(2)); let _e27 = coord_7; textureStore(img2DArray, _e27.xy, _e27.z, vec4(f32(2))); return; @@ -89,9 +101,12 @@ fn testImg3D(coord_8: vec3) { coord_9 = coord_8; let _e10 = textureDimensions(img3D); size_4 = vec3(_e10); + _ = coord_9; let _e14 = coord_9; let _e15 = textureLoad(img3D, _e14); c_4 = _e15; + _ = coord_9; + _ = vec4(f32(2)); let _e21 = coord_9; textureStore(img3D, _e21, vec4(f32(2))); return; @@ -105,6 +120,7 @@ fn testImgReadOnly(coord_10: vec2) { coord_11 = coord_10; let _e10 = textureDimensions(img2D); size_5 = vec2(_e10); + _ = coord_11; let _e14 = coord_11; let _e15 = textureLoad(imgReadOnly, _e14); c_5 = _e15; @@ -118,6 +134,8 @@ fn testImgWriteOnly(coord_12: vec2) { coord_13 = coord_12; let _e10 = textureDimensions(img2D); size_6 = vec2(_e10); + _ = coord_13; + _ = vec4(f32(2)); let _e17 = coord_13; textureStore(imgWriteOnly, _e17, vec4(f32(2))); return; diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index aaf6cb0eb..8ce67c709 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -9,20 +9,28 @@ fn main_1() { var e: mat4x4 = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); let _e1 = f32(1); + _ = mat2x2(vec2(_e1, 0.0), vec2(0.0, _e1)); let _e9 = vec2(f32(1)); let _e12 = vec2(f32(2)); + _ = mat2x2(vec2(_e9.x, _e9.y), vec2(_e12.x, _e12.y)); let _e26 = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); + _ = mat2x4(vec4(_e26[0].x, _e26[0].y, _e26[0].z, 0.0), vec4(_e26[1].x, _e26[1].y, _e26[1].z, 0.0)); + _ = mat2x2(vec2(f32(1), f32(2)), vec2(f32(3), f32(4))); let _e58 = vec2(f32(2), f32(3)); + _ = mat2x2(vec2(f32(1), _e58.x), vec2(_e58.y, f32(4))); let _e73 = vec3(f32(1)); let _e76 = vec3(f32(1)); + _ = mat3x3(vec3(f32(1), f32(2), f32(3)), vec3(_e73.x, _e73.y, _e73.z), vec3(_e76.x, _e76.y, _e76.z)); let _e93 = vec2(f32(2)); let _e97 = vec3(f32(1)); let _e100 = vec3(f32(1)); + _ = mat3x3(vec3(_e93.x, _e93.y, f32(1)), vec3(_e97.x, _e97.y, _e97.z), vec3(_e100.x, _e100.y, _e100.z)); let _e117 = vec2(f32(2)); let _e120 = vec4(f32(1)); let _e123 = vec2(f32(2)); let _e126 = vec4(f32(1)); let _e129 = vec4(f32(1)); + _ = mat4x4(vec4(_e117.x, _e117.y, _e120.x, _e120.y), vec4(_e120.z, _e120.w, _e123.x, _e123.y), vec4(_e126.x, _e126.y, _e126.z, _e126.w), vec4(_e129.x, _e129.y, _e129.z, _e129.w)); } @vertex diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 3fa89d6bc..6fb6f6bd7 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -45,110 +45,164 @@ fn main_1() { var rad: vec4; var deg: f32; + _ = vec4(1.0); + _ = vec4(2.0); let _e6 = a; let _e7 = b; let _e8 = a; let _e9 = b; m = mat4x4(vec4(_e6.x, _e6.y, _e6.z, _e6.w), vec4(_e7.x, _e7.y, _e7.z, _e7.w), vec4(_e8.x, _e8.y, _e8.z, _e8.w), vec4(_e9.x, _e9.y, _e9.z, _e9.w)); + _ = a; let _e35 = a; ceilOut = ceil(_e35); + _ = a; let _e39 = a; roundOut = round(_e39); + _ = a; let _e43 = a; floorOut = floor(_e43); + _ = a; let _e47 = a; fractOut = fract(_e47); + _ = a; let _e51 = a; truncOut = trunc(_e51); + _ = a; let _e55 = a; sinOut = sin(_e55); + _ = a; let _e59 = a; absOut = abs(_e59); + _ = a; let _e63 = a; sqrtOut = sqrt(_e63); + _ = a; let _e67 = a; inversesqrtOut = inverseSqrt(_e67); + _ = a; let _e71 = a; expOut = exp(_e71); + _ = a; let _e75 = a; exp2Out = exp2(_e75); + _ = a; let _e79 = a; signOut = sign(_e79); + _ = m; let _e83 = m; transposeOut = transpose(_e83); + _ = a; let _e87 = a; normalizeOut = normalize(_e87); + _ = a; let _e91 = a; sinhOut = sinh(_e91); + _ = a; let _e95 = a; cosOut = cos(_e95); + _ = a; let _e99 = a; coshOut = cosh(_e99); + _ = a; let _e103 = a; tanOut = tan(_e103); + _ = a; let _e107 = a; tanhOut = tanh(_e107); + _ = a; let _e111 = a; acosOut = acos(_e111); + _ = a; let _e115 = a; asinOut = asin(_e115); + _ = a; let _e119 = a; logOut = log(_e119); + _ = a; let _e123 = a; log2Out = log2(_e123); + _ = a; let _e127 = a; lengthOut = length(_e127); + _ = m; let _e131 = m; determinantOut = determinant(_e131); + _ = i; let _e135 = i; bitCountOut = countOneBits(_e135); + _ = i; let _e139 = i; bitfieldReverseOut = reverseBits(_e139); let _e142 = a; + _ = _e142.x; let _e144 = a; atanOut = atan(_e144.x); let _e148 = a; + _ = _e148.x; let _e150 = a; + _ = _e150.y; let _e152 = a; let _e154 = a; atan2Out = atan2(_e152.x, _e154.y); let _e158 = a; + _ = _e158.x; let _e160 = b; + _ = _e160.x; let _e162 = a; let _e164 = b; modOut = (_e162.x - (floor((_e162.x / _e164.x)) * _e164.x)); + _ = a; + _ = b; let _e173 = a; let _e174 = b; powOut = pow(_e173, _e174); + _ = a; + _ = b; let _e179 = a; let _e180 = b; dotOut = dot(_e179, _e180); + _ = a; + _ = b; let _e185 = a; let _e186 = b; maxOut = max(_e185, _e186); + _ = a; + _ = b; let _e191 = a; let _e192 = b; minOut = min(_e191, _e192); + _ = a; + _ = b; let _e197 = a; let _e198 = b; reflectOut = reflect(_e197, _e198); let _e201 = a; + _ = _e201.xyz; let _e203 = b; + _ = _e203.xyz; let _e205 = a; let _e207 = b; crossOut = cross(_e205.xyz, _e207.xyz); + _ = a; + _ = b; let _e213 = a; let _e214 = b; outerProductOut = outerProduct(_e213, _e214); + _ = a; + _ = b; let _e219 = a; let _e220 = b; distanceOut = distance(_e219, _e220); + _ = a; + _ = b; let _e225 = a; let _e226 = b; stepOut = step(_e225, _e226); + _ = a; let _e230 = a; rad = radians(_e230); let _e233 = a; + _ = _e233.x; let _e235 = a; deg = degrees(_e235.x); return; diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index f9144dd77..952ab6068 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -36,160 +36,160 @@ fn constructors() -> f32 { foo = Foo(vec4(1.0), 1); let mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); let mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let unnamed = vec2(0u); - let unnamed_1 = mat2x2(vec2(0.0), vec2(0.0)); - let unnamed_2 = array(0, 1, 2, 3); + _ = vec2(0u); + _ = mat2x2(vec2(0.0), vec2(0.0)); + _ = array(0, 1, 2, 3); let _e59 = foo.a.x; return _e59; } fn logical() { - let unnamed_3 = !(true); - let unnamed_4 = !(vec2(true)); - let unnamed_5 = (true || false); - let unnamed_6 = (true && false); - let unnamed_7 = (true | false); - let unnamed_8 = (vec3(true) | vec3(false)); - let unnamed_9 = (true & false); - let unnamed_10 = (vec4(true) & vec4(false)); + _ = !(true); + _ = !(vec2(true)); + _ = (true || false); + _ = (true && false); + _ = (true | false); + _ = (vec3(true) | vec3(false)); + _ = (true & false); + _ = (vec4(true) & vec4(false)); } fn arithmetic() { - let unnamed_11 = -(vec2(1)); - let unnamed_12 = -(vec2(1.0)); - let unnamed_13 = (2 + 1); - let unnamed_14 = (2u + 1u); - let unnamed_15 = (2.0 + 1.0); - let unnamed_16 = (vec2(2) + vec2(1)); - let unnamed_17 = (vec3(2u) + vec3(1u)); - let unnamed_18 = (vec4(2.0) + vec4(1.0)); - let unnamed_19 = (2 - 1); - let unnamed_20 = (2u - 1u); - let unnamed_21 = (2.0 - 1.0); - let unnamed_22 = (vec2(2) - vec2(1)); - let unnamed_23 = (vec3(2u) - vec3(1u)); - let unnamed_24 = (vec4(2.0) - vec4(1.0)); - let unnamed_25 = (2 * 1); - let unnamed_26 = (2u * 1u); - let unnamed_27 = (2.0 * 1.0); - let unnamed_28 = (vec2(2) * vec2(1)); - let unnamed_29 = (vec3(2u) * vec3(1u)); - let unnamed_30 = (vec4(2.0) * vec4(1.0)); - let unnamed_31 = (2 / 1); - let unnamed_32 = (2u / 1u); - let unnamed_33 = (2.0 / 1.0); - let unnamed_34 = (vec2(2) / vec2(1)); - let unnamed_35 = (vec3(2u) / vec3(1u)); - let unnamed_36 = (vec4(2.0) / vec4(1.0)); - let unnamed_37 = (2 % 1); - let unnamed_38 = (2u % 1u); - let unnamed_39 = (2.0 % 1.0); - let unnamed_40 = (vec2(2) % vec2(1)); - let unnamed_41 = (vec3(2u) % vec3(1u)); - let unnamed_42 = (vec4(2.0) % vec4(1.0)); - let unnamed_43 = (vec2(2) + vec2(1)); - let unnamed_44 = (vec2(2) + vec2(1)); - let unnamed_45 = (vec2(2u) + vec2(1u)); - let unnamed_46 = (vec2(2u) + vec2(1u)); - let unnamed_47 = (vec2(2.0) + vec2(1.0)); - let unnamed_48 = (vec2(2.0) + vec2(1.0)); - let unnamed_49 = (vec2(2) - vec2(1)); - let unnamed_50 = (vec2(2) - vec2(1)); - let unnamed_51 = (vec2(2u) - vec2(1u)); - let unnamed_52 = (vec2(2u) - vec2(1u)); - let unnamed_53 = (vec2(2.0) - vec2(1.0)); - let unnamed_54 = (vec2(2.0) - vec2(1.0)); - let unnamed_55 = (vec2(2) * 1); - let unnamed_56 = (2 * vec2(1)); - let unnamed_57 = (vec2(2u) * 1u); - let unnamed_58 = (2u * vec2(1u)); - let unnamed_59 = (vec2(2.0) * 1.0); - let unnamed_60 = (2.0 * vec2(1.0)); - let unnamed_61 = (vec2(2) / vec2(1)); - let unnamed_62 = (vec2(2) / vec2(1)); - let unnamed_63 = (vec2(2u) / vec2(1u)); - let unnamed_64 = (vec2(2u) / vec2(1u)); - let unnamed_65 = (vec2(2.0) / vec2(1.0)); - let unnamed_66 = (vec2(2.0) / vec2(1.0)); - let unnamed_67 = (vec2(2) % vec2(1)); - let unnamed_68 = (vec2(2) % vec2(1)); - let unnamed_69 = (vec2(2u) % vec2(1u)); - let unnamed_70 = (vec2(2u) % vec2(1u)); - let unnamed_71 = (vec2(2.0) % vec2(1.0)); - let unnamed_72 = (vec2(2.0) % vec2(1.0)); - let unnamed_73 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_74 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_75 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - let unnamed_76 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_77 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - let unnamed_78 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let unnamed_79 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + _ = -(vec2(1)); + _ = -(vec2(1.0)); + _ = (2 + 1); + _ = (2u + 1u); + _ = (2.0 + 1.0); + _ = (vec2(2) + vec2(1)); + _ = (vec3(2u) + vec3(1u)); + _ = (vec4(2.0) + vec4(1.0)); + _ = (2 - 1); + _ = (2u - 1u); + _ = (2.0 - 1.0); + _ = (vec2(2) - vec2(1)); + _ = (vec3(2u) - vec3(1u)); + _ = (vec4(2.0) - vec4(1.0)); + _ = (2 * 1); + _ = (2u * 1u); + _ = (2.0 * 1.0); + _ = (vec2(2) * vec2(1)); + _ = (vec3(2u) * vec3(1u)); + _ = (vec4(2.0) * vec4(1.0)); + _ = (2 / 1); + _ = (2u / 1u); + _ = (2.0 / 1.0); + _ = (vec2(2) / vec2(1)); + _ = (vec3(2u) / vec3(1u)); + _ = (vec4(2.0) / vec4(1.0)); + _ = (2 % 1); + _ = (2u % 1u); + _ = (2.0 % 1.0); + _ = (vec2(2) % vec2(1)); + _ = (vec3(2u) % vec3(1u)); + _ = (vec4(2.0) % vec4(1.0)); + _ = (vec2(2) + vec2(1)); + _ = (vec2(2) + vec2(1)); + _ = (vec2(2u) + vec2(1u)); + _ = (vec2(2u) + vec2(1u)); + _ = (vec2(2.0) + vec2(1.0)); + _ = (vec2(2.0) + vec2(1.0)); + _ = (vec2(2) - vec2(1)); + _ = (vec2(2) - vec2(1)); + _ = (vec2(2u) - vec2(1u)); + _ = (vec2(2u) - vec2(1u)); + _ = (vec2(2.0) - vec2(1.0)); + _ = (vec2(2.0) - vec2(1.0)); + _ = (vec2(2) * 1); + _ = (2 * vec2(1)); + _ = (vec2(2u) * 1u); + _ = (2u * vec2(1u)); + _ = (vec2(2.0) * 1.0); + _ = (2.0 * vec2(1.0)); + _ = (vec2(2) / vec2(1)); + _ = (vec2(2) / vec2(1)); + _ = (vec2(2u) / vec2(1u)); + _ = (vec2(2u) / vec2(1u)); + _ = (vec2(2.0) / vec2(1.0)); + _ = (vec2(2.0) / vec2(1.0)); + _ = (vec2(2) % vec2(1)); + _ = (vec2(2) % vec2(1)); + _ = (vec2(2u) % vec2(1u)); + _ = (vec2(2u) % vec2(1u)); + _ = (vec2(2.0) % vec2(1.0)); + _ = (vec2(2.0) % vec2(1.0)); + _ = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + _ = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + _ = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + _ = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + _ = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + _ = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + _ = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } fn bit() { - let unnamed_80 = ~(1); - let unnamed_81 = ~(1u); - let unnamed_82 = !(vec2(1)); - let unnamed_83 = !(vec3(1u)); - let unnamed_84 = (2 | 1); - let unnamed_85 = (2u | 1u); - let unnamed_86 = (vec2(2) | vec2(1)); - let unnamed_87 = (vec3(2u) | vec3(1u)); - let unnamed_88 = (2 & 1); - let unnamed_89 = (2u & 1u); - let unnamed_90 = (vec2(2) & vec2(1)); - let unnamed_91 = (vec3(2u) & vec3(1u)); - let unnamed_92 = (2 ^ 1); - let unnamed_93 = (2u ^ 1u); - let unnamed_94 = (vec2(2) ^ vec2(1)); - let unnamed_95 = (vec3(2u) ^ vec3(1u)); - let unnamed_96 = (2 << 1u); - let unnamed_97 = (2u << 1u); - let unnamed_98 = (vec2(2) << vec2(1u)); - let unnamed_99 = (vec3(2u) << vec3(1u)); - let unnamed_100 = (2 >> 1u); - let unnamed_101 = (2u >> 1u); - let unnamed_102 = (vec2(2) >> vec2(1u)); - let unnamed_103 = (vec3(2u) >> vec3(1u)); + _ = ~(1); + _ = ~(1u); + _ = !(vec2(1)); + _ = !(vec3(1u)); + _ = (2 | 1); + _ = (2u | 1u); + _ = (vec2(2) | vec2(1)); + _ = (vec3(2u) | vec3(1u)); + _ = (2 & 1); + _ = (2u & 1u); + _ = (vec2(2) & vec2(1)); + _ = (vec3(2u) & vec3(1u)); + _ = (2 ^ 1); + _ = (2u ^ 1u); + _ = (vec2(2) ^ vec2(1)); + _ = (vec3(2u) ^ vec3(1u)); + _ = (2 << 1u); + _ = (2u << 1u); + _ = (vec2(2) << vec2(1u)); + _ = (vec3(2u) << vec3(1u)); + _ = (2 >> 1u); + _ = (2u >> 1u); + _ = (vec2(2) >> vec2(1u)); + _ = (vec3(2u) >> vec3(1u)); } fn comparison() { - let unnamed_104 = (2 == 1); - let unnamed_105 = (2u == 1u); - let unnamed_106 = (2.0 == 1.0); - let unnamed_107 = (vec2(2) == vec2(1)); - let unnamed_108 = (vec3(2u) == vec3(1u)); - let unnamed_109 = (vec4(2.0) == vec4(1.0)); - let unnamed_110 = (2 != 1); - let unnamed_111 = (2u != 1u); - let unnamed_112 = (2.0 != 1.0); - let unnamed_113 = (vec2(2) != vec2(1)); - let unnamed_114 = (vec3(2u) != vec3(1u)); - let unnamed_115 = (vec4(2.0) != vec4(1.0)); - let unnamed_116 = (2 < 1); - let unnamed_117 = (2u < 1u); - let unnamed_118 = (2.0 < 1.0); - let unnamed_119 = (vec2(2) < vec2(1)); - let unnamed_120 = (vec3(2u) < vec3(1u)); - let unnamed_121 = (vec4(2.0) < vec4(1.0)); - let unnamed_122 = (2 <= 1); - let unnamed_123 = (2u <= 1u); - let unnamed_124 = (2.0 <= 1.0); - let unnamed_125 = (vec2(2) <= vec2(1)); - let unnamed_126 = (vec3(2u) <= vec3(1u)); - let unnamed_127 = (vec4(2.0) <= vec4(1.0)); - let unnamed_128 = (2 > 1); - let unnamed_129 = (2u > 1u); - let unnamed_130 = (2.0 > 1.0); - let unnamed_131 = (vec2(2) > vec2(1)); - let unnamed_132 = (vec3(2u) > vec3(1u)); - let unnamed_133 = (vec4(2.0) > vec4(1.0)); - let unnamed_134 = (2 >= 1); - let unnamed_135 = (2u >= 1u); - let unnamed_136 = (2.0 >= 1.0); - let unnamed_137 = (vec2(2) >= vec2(1)); - let unnamed_138 = (vec3(2u) >= vec3(1u)); - let unnamed_139 = (vec4(2.0) >= vec4(1.0)); + _ = (2 == 1); + _ = (2u == 1u); + _ = (2.0 == 1.0); + _ = (vec2(2) == vec2(1)); + _ = (vec3(2u) == vec3(1u)); + _ = (vec4(2.0) == vec4(1.0)); + _ = (2 != 1); + _ = (2u != 1u); + _ = (2.0 != 1.0); + _ = (vec2(2) != vec2(1)); + _ = (vec3(2u) != vec3(1u)); + _ = (vec4(2.0) != vec4(1.0)); + _ = (2 < 1); + _ = (2u < 1u); + _ = (2.0 < 1.0); + _ = (vec2(2) < vec2(1)); + _ = (vec3(2u) < vec3(1u)); + _ = (vec4(2.0) < vec4(1.0)); + _ = (2 <= 1); + _ = (2u <= 1u); + _ = (2.0 <= 1.0); + _ = (vec2(2) <= vec2(1)); + _ = (vec3(2u) <= vec3(1u)); + _ = (vec4(2.0) <= vec4(1.0)); + _ = (2 > 1); + _ = (2u > 1u); + _ = (2.0 > 1.0); + _ = (vec2(2) > vec2(1)); + _ = (vec3(2u) > vec3(1u)); + _ = (vec4(2.0) > vec4(1.0)); + _ = (2 >= 1); + _ = (2u >= 1u); + _ = (2.0 >= 1.0); + _ = (vec2(2) >= vec2(1)); + _ = (vec3(2u) >= vec3(1u)); + _ = (vec4(2.0) >= vec4(1.0)); } fn assignment() { diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index 549ac805e..f020792af 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -13,6 +13,7 @@ fn main_1() { let _e8 = (_e6 - 1); scalar = _e8; scalar_target = _e8; + _ = vec2(u32(1)); let _e14 = vec_; vec_ = (_e14 - vec2(1u)); vec_target = _e14; @@ -21,6 +22,7 @@ fn main_1() { vec_ = _e21; vec_target = _e21; let _e24 = f32(1); + _ = mat4x3(vec3(_e24, 0.0, 0.0), vec3(0.0, _e24, 0.0), vec3(0.0, 0.0, _e24), vec3(0.0, 0.0, 0.0)); let _e32 = mat_; let _e34 = vec3(1.0); mat_ = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 3ab0bc0c0..2961a9dbd 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -39,115 +39,141 @@ fn testTex1D(coord: f32) { coord_1 = coord; let _e20 = textureDimensions(tex1D, 0); size1D = _e20; + _ = coord_1; let _e24 = coord_1; let _e25 = textureSample(tex1D, samp, _e24); c = _e25; + _ = coord_1; let _e28 = coord_1; let _e30 = textureSampleBias(tex1D, samp, _e28, 2.0); c = _e30; + _ = coord_1; let _e34 = coord_1; let _e37 = textureSampleGrad(tex1D, samp, _e34, 4.0, 4.0); c = _e37; + _ = coord_1; let _e42 = coord_1; let _e46 = textureSampleGrad(tex1D, samp, _e42, 4.0, 4.0, 5); c = _e46; + _ = coord_1; let _e49 = coord_1; let _e51 = textureSampleLevel(tex1D, samp, _e49, 3.0); c = _e51; + _ = coord_1; let _e55 = coord_1; let _e58 = textureSampleLevel(tex1D, samp, _e55, 3.0, 5); c = _e58; + _ = coord_1; let _e61 = coord_1; let _e63 = textureSample(tex1D, samp, _e61, 5); c = _e63; + _ = coord_1; let _e67 = coord_1; let _e70 = textureSampleBias(tex1D, samp, _e67, 2.0, 5); c = _e70; let _e71 = coord_1; + _ = vec2(_e71, 6.0); let _e74 = coord_1; let _e76 = vec2(_e74, 6.0); let _e80 = textureSample(tex1D, samp, (_e76.x / _e76.y)); c = _e80; let _e81 = coord_1; + _ = vec4(_e81, 0.0, 0.0, 6.0); let _e86 = coord_1; let _e90 = vec4(_e86, 0.0, 0.0, 6.0); let _e96 = textureSample(tex1D, samp, (_e90.xyz / vec3(_e90.w)).x); c = _e96; let _e97 = coord_1; + _ = vec2(_e97, 6.0); let _e101 = coord_1; let _e103 = vec2(_e101, 6.0); let _e108 = textureSampleBias(tex1D, samp, (_e103.x / _e103.y), 2.0); c = _e108; let _e109 = coord_1; + _ = vec4(_e109, 0.0, 0.0, 6.0); let _e115 = coord_1; let _e119 = vec4(_e115, 0.0, 0.0, 6.0); let _e126 = textureSampleBias(tex1D, samp, (_e119.xyz / vec3(_e119.w)).x, 2.0); c = _e126; let _e127 = coord_1; + _ = vec2(_e127, 6.0); let _e132 = coord_1; let _e134 = vec2(_e132, 6.0); let _e140 = textureSampleGrad(tex1D, samp, (_e134.x / _e134.y), 4.0, 4.0); c = _e140; let _e141 = coord_1; + _ = vec4(_e141, 0.0, 0.0, 6.0); let _e148 = coord_1; let _e152 = vec4(_e148, 0.0, 0.0, 6.0); let _e160 = textureSampleGrad(tex1D, samp, (_e152.xyz / vec3(_e152.w)).x, 4.0, 4.0); c = _e160; let _e161 = coord_1; + _ = vec2(_e161, 6.0); let _e167 = coord_1; let _e169 = vec2(_e167, 6.0); let _e176 = textureSampleGrad(tex1D, samp, (_e169.x / _e169.y), 4.0, 4.0, 5); c = _e176; let _e177 = coord_1; + _ = vec4(_e177, 0.0, 0.0, 6.0); let _e185 = coord_1; let _e189 = vec4(_e185, 0.0, 0.0, 6.0); let _e198 = textureSampleGrad(tex1D, samp, (_e189.xyz / vec3(_e189.w)).x, 4.0, 4.0, 5); c = _e198; let _e199 = coord_1; + _ = vec2(_e199, 6.0); let _e203 = coord_1; let _e205 = vec2(_e203, 6.0); let _e210 = textureSampleLevel(tex1D, samp, (_e205.x / _e205.y), 3.0); c = _e210; let _e211 = coord_1; + _ = vec4(_e211, 0.0, 0.0, 6.0); let _e217 = coord_1; let _e221 = vec4(_e217, 0.0, 0.0, 6.0); let _e228 = textureSampleLevel(tex1D, samp, (_e221.xyz / vec3(_e221.w)).x, 3.0); c = _e228; let _e229 = coord_1; + _ = vec2(_e229, 6.0); let _e234 = coord_1; let _e236 = vec2(_e234, 6.0); let _e242 = textureSampleLevel(tex1D, samp, (_e236.x / _e236.y), 3.0, 5); c = _e242; let _e243 = coord_1; + _ = vec4(_e243, 0.0, 0.0, 6.0); let _e250 = coord_1; let _e254 = vec4(_e250, 0.0, 0.0, 6.0); let _e262 = textureSampleLevel(tex1D, samp, (_e254.xyz / vec3(_e254.w)).x, 3.0, 5); c = _e262; let _e263 = coord_1; + _ = vec2(_e263, 6.0); let _e267 = coord_1; let _e269 = vec2(_e267, 6.0); let _e274 = textureSample(tex1D, samp, (_e269.x / _e269.y), 5); c = _e274; let _e275 = coord_1; + _ = vec4(_e275, 0.0, 0.0, 6.0); let _e281 = coord_1; let _e285 = vec4(_e281, 0.0, 0.0, 6.0); let _e292 = textureSample(tex1D, samp, (_e285.xyz / vec3(_e285.w)).x, 5); c = _e292; let _e293 = coord_1; + _ = vec2(_e293, 6.0); let _e298 = coord_1; let _e300 = vec2(_e298, 6.0); let _e306 = textureSampleBias(tex1D, samp, (_e300.x / _e300.y), 2.0, 5); c = _e306; let _e307 = coord_1; + _ = vec4(_e307, 0.0, 0.0, 6.0); let _e314 = coord_1; let _e318 = vec4(_e314, 0.0, 0.0, 6.0); let _e326 = textureSampleBias(tex1D, samp, (_e318.xyz / vec3(_e318.w)).x, 2.0, 5); c = _e326; let _e327 = coord_1; + _ = i32(_e327); let _e330 = coord_1; let _e333 = textureLoad(tex1D, i32(_e330), 3); c = _e333; let _e334 = coord_1; + _ = i32(_e334); let _e338 = coord_1; let _e342 = textureLoad(tex1D, i32(_e338), 3); c = _e342; @@ -163,36 +189,46 @@ fn testTex1DArray(coord_2: vec2) { let _e20 = textureDimensions(tex1DArray, 0); let _e21 = textureNumLayers(tex1DArray); size1DArray = vec2(_e20, _e21); + _ = coord_3; let _e26 = coord_3; let _e30 = textureSample(tex1DArray, samp, _e26.x, i32(_e26.y)); c_1 = _e30; + _ = coord_3; let _e33 = coord_3; let _e38 = textureSampleBias(tex1DArray, samp, _e33.x, i32(_e33.y), 2.0); c_1 = _e38; + _ = coord_3; let _e42 = coord_3; let _e48 = textureSampleGrad(tex1DArray, samp, _e42.x, i32(_e42.y), 4.0, 4.0); c_1 = _e48; + _ = coord_3; let _e53 = coord_3; let _e60 = textureSampleGrad(tex1DArray, samp, _e53.x, i32(_e53.y), 4.0, 4.0, 5); c_1 = _e60; + _ = coord_3; let _e63 = coord_3; let _e68 = textureSampleLevel(tex1DArray, samp, _e63.x, i32(_e63.y), 3.0); c_1 = _e68; + _ = coord_3; let _e72 = coord_3; let _e78 = textureSampleLevel(tex1DArray, samp, _e72.x, i32(_e72.y), 3.0, 5); c_1 = _e78; + _ = coord_3; let _e81 = coord_3; let _e86 = textureSample(tex1DArray, samp, _e81.x, i32(_e81.y), 5); c_1 = _e86; + _ = coord_3; let _e90 = coord_3; let _e96 = textureSampleBias(tex1DArray, samp, _e90.x, i32(_e90.y), 2.0, 5); c_1 = _e96; let _e97 = coord_3; + _ = vec2(_e97); let _e100 = coord_3; let _e101 = vec2(_e100); let _e105 = textureLoad(tex1DArray, _e101.x, _e101.y, 3); c_1 = _e105; let _e106 = coord_3; + _ = vec2(_e106); let _e110 = coord_3; let _e111 = vec2(_e110); let _e116 = textureLoad(tex1DArray, _e111.x, _e111.y, 3); @@ -208,116 +244,180 @@ fn testTex2D(coord_4: vec2) { coord_5 = coord_4; let _e20 = textureDimensions(tex2D, 0); size2D = _e20; + _ = coord_5; let _e24 = coord_5; let _e25 = textureSample(tex2D, samp, _e24); c_2 = _e25; + _ = coord_5; let _e28 = coord_5; let _e30 = textureSampleBias(tex2D, samp, _e28, 2.0); c_2 = _e30; + _ = coord_5; + _ = vec2(4.0); + _ = vec2(4.0); let _e36 = coord_5; let _e41 = textureSampleGrad(tex2D, samp, _e36, vec2(4.0), vec2(4.0)); c_2 = _e41; + _ = coord_5; + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e49 = coord_5; + _ = vec2(5); let _e56 = textureSampleGrad(tex2D, samp, _e49, vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e56; + _ = coord_5; let _e59 = coord_5; let _e61 = textureSampleLevel(tex2D, samp, _e59, 3.0); c_2 = _e61; + _ = coord_5; + _ = vec2(5); let _e66 = coord_5; + _ = vec2(5); let _e70 = textureSampleLevel(tex2D, samp, _e66, 3.0, vec2(5, 5)); c_2 = _e70; + _ = coord_5; + _ = vec2(5); let _e74 = coord_5; + _ = vec2(5); let _e77 = textureSample(tex2D, samp, _e74, vec2(5, 5)); c_2 = _e77; + _ = coord_5; + _ = vec2(5); let _e82 = coord_5; + _ = vec2(5); let _e86 = textureSampleBias(tex2D, samp, _e82, 2.0, vec2(5, 5)); c_2 = _e86; let _e87 = coord_5; + _ = vec3(_e87.x, _e87.y, 6.0); let _e92 = coord_5; let _e96 = vec3(_e92.x, _e92.y, 6.0); let _e101 = textureSample(tex2D, samp, (_e96.xy / vec2(_e96.z))); c_2 = _e101; let _e102 = coord_5; + _ = vec4(_e102.x, _e102.y, 0.0, 6.0); let _e108 = coord_5; let _e113 = vec4(_e108.x, _e108.y, 0.0, 6.0); let _e119 = textureSample(tex2D, samp, (_e113.xyz / vec3(_e113.w)).xy); c_2 = _e119; let _e120 = coord_5; + _ = vec3(_e120.x, _e120.y, 6.0); let _e126 = coord_5; let _e130 = vec3(_e126.x, _e126.y, 6.0); let _e136 = textureSampleBias(tex2D, samp, (_e130.xy / vec2(_e130.z)), 2.0); c_2 = _e136; let _e137 = coord_5; + _ = vec4(_e137.x, _e137.y, 0.0, 6.0); let _e144 = coord_5; let _e149 = vec4(_e144.x, _e144.y, 0.0, 6.0); let _e156 = textureSampleBias(tex2D, samp, (_e149.xyz / vec3(_e149.w)).xy, 2.0); c_2 = _e156; let _e157 = coord_5; + _ = vec3(_e157.x, _e157.y, 6.0); + _ = vec2(4.0); + _ = vec2(4.0); let _e166 = coord_5; let _e170 = vec3(_e166.x, _e166.y, 6.0); let _e179 = textureSampleGrad(tex2D, samp, (_e170.xy / vec2(_e170.z)), vec2(4.0), vec2(4.0)); c_2 = _e179; let _e180 = coord_5; + _ = vec4(_e180.x, _e180.y, 0.0, 6.0); + _ = vec2(4.0); + _ = vec2(4.0); let _e190 = coord_5; let _e195 = vec4(_e190.x, _e190.y, 0.0, 6.0); let _e205 = textureSampleGrad(tex2D, samp, (_e195.xyz / vec3(_e195.w)).xy, vec2(4.0), vec2(4.0)); c_2 = _e205; let _e206 = coord_5; + _ = vec3(_e206.x, _e206.y, 6.0); + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e217 = coord_5; let _e221 = vec3(_e217.x, _e217.y, 6.0); + _ = vec2(5); let _e232 = textureSampleGrad(tex2D, samp, (_e221.xy / vec2(_e221.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e232; let _e233 = coord_5; + _ = vec4(_e233.x, _e233.y, 0.0, 6.0); + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e245 = coord_5; let _e250 = vec4(_e245.x, _e245.y, 0.0, 6.0); + _ = vec2(5); let _e262 = textureSampleGrad(tex2D, samp, (_e250.xyz / vec3(_e250.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e262; let _e263 = coord_5; + _ = vec3(_e263.x, _e263.y, 6.0); let _e269 = coord_5; let _e273 = vec3(_e269.x, _e269.y, 6.0); let _e279 = textureSampleLevel(tex2D, samp, (_e273.xy / vec2(_e273.z)), 3.0); c_2 = _e279; let _e280 = coord_5; + _ = vec4(_e280.x, _e280.y, 0.0, 6.0); let _e287 = coord_5; let _e292 = vec4(_e287.x, _e287.y, 0.0, 6.0); let _e299 = textureSampleLevel(tex2D, samp, (_e292.xyz / vec3(_e292.w)).xy, 3.0); c_2 = _e299; let _e300 = coord_5; + _ = vec3(_e300.x, _e300.y, 6.0); + _ = vec2(5); let _e308 = coord_5; let _e312 = vec3(_e308.x, _e308.y, 6.0); + _ = vec2(5); let _e320 = textureSampleLevel(tex2D, samp, (_e312.xy / vec2(_e312.z)), 3.0, vec2(5, 5)); c_2 = _e320; let _e321 = coord_5; + _ = vec4(_e321.x, _e321.y, 0.0, 6.0); + _ = vec2(5); let _e330 = coord_5; let _e335 = vec4(_e330.x, _e330.y, 0.0, 6.0); + _ = vec2(5); let _e344 = textureSampleLevel(tex2D, samp, (_e335.xyz / vec3(_e335.w)).xy, 3.0, vec2(5, 5)); c_2 = _e344; let _e345 = coord_5; + _ = vec3(_e345.x, _e345.y, 6.0); + _ = vec2(5); let _e352 = coord_5; let _e356 = vec3(_e352.x, _e352.y, 6.0); + _ = vec2(5); let _e363 = textureSample(tex2D, samp, (_e356.xy / vec2(_e356.z)), vec2(5, 5)); c_2 = _e363; let _e364 = coord_5; + _ = vec4(_e364.x, _e364.y, 0.0, 6.0); + _ = vec2(5); let _e372 = coord_5; let _e377 = vec4(_e372.x, _e372.y, 0.0, 6.0); + _ = vec2(5); let _e385 = textureSample(tex2D, samp, (_e377.xyz / vec3(_e377.w)).xy, vec2(5, 5)); c_2 = _e385; let _e386 = coord_5; + _ = vec3(_e386.x, _e386.y, 6.0); + _ = vec2(5); let _e394 = coord_5; let _e398 = vec3(_e394.x, _e394.y, 6.0); + _ = vec2(5); let _e406 = textureSampleBias(tex2D, samp, (_e398.xy / vec2(_e398.z)), 2.0, vec2(5, 5)); c_2 = _e406; let _e407 = coord_5; + _ = vec4(_e407.x, _e407.y, 0.0, 6.0); + _ = vec2(5); let _e416 = coord_5; let _e421 = vec4(_e416.x, _e416.y, 0.0, 6.0); + _ = vec2(5); let _e430 = textureSampleBias(tex2D, samp, (_e421.xyz / vec3(_e421.w)).xy, 2.0, vec2(5, 5)); c_2 = _e430; let _e431 = coord_5; + _ = vec2(_e431); let _e434 = coord_5; let _e437 = textureLoad(tex2D, vec2(_e434), 3); c_2 = _e437; let _e438 = coord_5; + _ = vec2(_e438); + _ = vec2(5); let _e443 = coord_5; + _ = vec2(5); let _e448 = textureLoad(tex2D, vec2(_e443), 3); c_2 = _e448; return; @@ -332,68 +432,108 @@ fn testTex2DShadow(coord_6: vec2) { let _e20 = textureDimensions(tex2DShadow, 0); size2DShadow = _e20; let _e23 = coord_7; + _ = vec3(_e23.x, _e23.y, 1.0); let _e28 = coord_7; let _e32 = vec3(_e28.x, _e28.y, 1.0); let _e35 = textureSampleCompare(tex2DShadow, sampShadow, _e32.xy, _e32.z); d = _e35; let _e36 = coord_7; + _ = vec3(_e36.x, _e36.y, 1.0); + _ = vec2(4.0); + _ = vec2(4.0); let _e45 = coord_7; let _e49 = vec3(_e45.x, _e45.y, 1.0); + _ = vec2(4.0); + _ = vec2(4.0); let _e56 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e49.xy, _e49.z); d = _e56; let _e57 = coord_7; + _ = vec3(_e57.x, _e57.y, 1.0); + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e68 = coord_7; let _e72 = vec3(_e68.x, _e68.y, 1.0); + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e81 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e72.xy, _e72.z, vec2(5, 5)); d = _e81; let _e82 = coord_7; + _ = vec3(_e82.x, _e82.y, 1.0); let _e88 = coord_7; let _e92 = vec3(_e88.x, _e88.y, 1.0); let _e96 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e92.xy, _e92.z); d = _e96; let _e97 = coord_7; + _ = vec3(_e97.x, _e97.y, 1.0); + _ = vec2(5); let _e105 = coord_7; let _e109 = vec3(_e105.x, _e105.y, 1.0); + _ = vec2(5); let _e115 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e109.xy, _e109.z, vec2(5, 5)); d = _e115; let _e116 = coord_7; + _ = vec3(_e116.x, _e116.y, 1.0); + _ = vec2(5); let _e123 = coord_7; let _e127 = vec3(_e123.x, _e123.y, 1.0); + _ = vec2(5); let _e132 = textureSampleCompare(tex2DShadow, sampShadow, _e127.xy, _e127.z, vec2(5, 5)); d = _e132; let _e133 = coord_7; + _ = vec4(_e133.x, _e133.y, 1.0, 6.0); let _e139 = coord_7; let _e144 = vec4(_e139.x, _e139.y, 1.0, 6.0); let _e148 = (_e144.xyz / vec3(_e144.w)); let _e151 = textureSampleCompare(tex2DShadow, sampShadow, _e148.xy, _e148.z); d = _e151; let _e152 = coord_7; + _ = vec4(_e152.x, _e152.y, 1.0, 6.0); + _ = vec2(4.0); + _ = vec2(4.0); let _e162 = coord_7; let _e167 = vec4(_e162.x, _e162.y, 1.0, 6.0); + _ = vec2(4.0); + _ = vec2(4.0); let _e175 = (_e167.xyz / vec3(_e167.w)); let _e178 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e175.xy, _e175.z); d = _e178; let _e179 = coord_7; + _ = vec4(_e179.x, _e179.y, 1.0, 6.0); + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e191 = coord_7; let _e196 = vec4(_e191.x, _e191.y, 1.0, 6.0); + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e206 = (_e196.xyz / vec3(_e196.w)); let _e209 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e206.xy, _e206.z, vec2(5, 5)); d = _e209; let _e210 = coord_7; + _ = vec4(_e210.x, _e210.y, 1.0, 6.0); let _e217 = coord_7; let _e222 = vec4(_e217.x, _e217.y, 1.0, 6.0); let _e227 = (_e222.xyz / vec3(_e222.w)); let _e230 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e227.xy, _e227.z); d = _e230; let _e231 = coord_7; + _ = vec4(_e231.x, _e231.y, 1.0, 6.0); + _ = vec2(5); let _e240 = coord_7; let _e245 = vec4(_e240.x, _e240.y, 1.0, 6.0); + _ = vec2(5); let _e252 = (_e245.xyz / vec3(_e245.w)); let _e255 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e252.xy, _e252.z, vec2(5, 5)); d = _e255; let _e256 = coord_7; + _ = vec4(_e256.x, _e256.y, 1.0, 6.0); + _ = vec2(5); let _e264 = coord_7; let _e269 = vec4(_e264.x, _e264.y, 1.0, 6.0); + _ = vec2(5); let _e275 = (_e269.xyz / vec3(_e269.w)); let _e278 = textureSampleCompare(tex2DShadow, sampShadow, _e275.xy, _e275.z, vec2(5, 5)); d = _e278; @@ -409,38 +549,62 @@ fn testTex2DArray(coord_8: vec3) { let _e20 = textureDimensions(tex2DArray, 0); let _e23 = textureNumLayers(tex2DArray); size2DArray = vec3(_e20.x, _e20.y, _e23); + _ = coord_9; let _e28 = coord_9; let _e32 = textureSample(tex2DArray, samp, _e28.xy, i32(_e28.z)); c_3 = _e32; + _ = coord_9; let _e35 = coord_9; let _e40 = textureSampleBias(tex2DArray, samp, _e35.xy, i32(_e35.z), 2.0); c_3 = _e40; + _ = coord_9; + _ = vec2(4.0); + _ = vec2(4.0); let _e46 = coord_9; let _e54 = textureSampleGrad(tex2DArray, samp, _e46.xy, i32(_e46.z), vec2(4.0), vec2(4.0)); c_3 = _e54; + _ = coord_9; + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e62 = coord_9; + _ = vec2(5); let _e72 = textureSampleGrad(tex2DArray, samp, _e62.xy, i32(_e62.z), vec2(4.0), vec2(4.0), vec2(5, 5)); c_3 = _e72; + _ = coord_9; let _e75 = coord_9; let _e80 = textureSampleLevel(tex2DArray, samp, _e75.xy, i32(_e75.z), 3.0); c_3 = _e80; + _ = coord_9; + _ = vec2(5); let _e85 = coord_9; + _ = vec2(5); let _e92 = textureSampleLevel(tex2DArray, samp, _e85.xy, i32(_e85.z), 3.0, vec2(5, 5)); c_3 = _e92; + _ = coord_9; + _ = vec2(5); let _e96 = coord_9; + _ = vec2(5); let _e102 = textureSample(tex2DArray, samp, _e96.xy, i32(_e96.z), vec2(5, 5)); c_3 = _e102; + _ = coord_9; + _ = vec2(5); let _e107 = coord_9; + _ = vec2(5); let _e114 = textureSampleBias(tex2DArray, samp, _e107.xy, i32(_e107.z), 2.0, vec2(5, 5)); c_3 = _e114; let _e115 = coord_9; + _ = vec3(_e115); let _e118 = coord_9; let _e119 = vec3(_e118); let _e123 = textureLoad(tex2DArray, _e119.xy, _e119.z, 3); c_3 = _e123; let _e124 = coord_9; + _ = vec3(_e124); + _ = vec2(5); let _e129 = coord_9; let _e130 = vec3(_e129); + _ = vec2(5); let _e136 = textureLoad(tex2DArray, _e130.xy, _e130.z, 3); c_3 = _e136; return; @@ -456,23 +620,39 @@ fn testTex2DArrayShadow(coord_10: vec3) { let _e23 = textureNumLayers(tex2DArrayShadow); size2DArrayShadow = vec3(_e20.x, _e20.y, _e23); let _e27 = coord_11; + _ = vec4(_e27.x, _e27.y, _e27.z, 1.0); let _e33 = coord_11; let _e38 = vec4(_e33.x, _e33.y, _e33.z, 1.0); let _e43 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e38.xy, i32(_e38.z), _e38.w); d_1 = _e43; let _e44 = coord_11; + _ = vec4(_e44.x, _e44.y, _e44.z, 1.0); + _ = vec2(4.0); + _ = vec2(4.0); let _e54 = coord_11; let _e59 = vec4(_e54.x, _e54.y, _e54.z, 1.0); + _ = vec2(4.0); + _ = vec2(4.0); let _e68 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e59.xy, i32(_e59.z), _e59.w); d_1 = _e68; let _e69 = coord_11; + _ = vec4(_e69.x, _e69.y, _e69.z, 1.0); + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e81 = coord_11; let _e86 = vec4(_e81.x, _e81.y, _e81.z, 1.0); + _ = vec2(4.0); + _ = vec2(4.0); + _ = vec2(5); let _e97 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e86.xy, i32(_e86.z), _e86.w, vec2(5, 5)); d_1 = _e97; let _e98 = coord_11; + _ = vec4(_e98.x, _e98.y, _e98.z, 1.0); + _ = vec2(5); let _e106 = coord_11; let _e111 = vec4(_e106.x, _e106.y, _e106.z, 1.0); + _ = vec2(5); let _e118 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e111.xy, i32(_e111.z), _e111.w, vec2(5, 5)); d_1 = _e118; return; @@ -486,15 +666,21 @@ fn testTexCube(coord_12: vec3) { coord_13 = coord_12; let _e20 = textureDimensions(texCube, 0); sizeCube = _e20; + _ = coord_13; let _e24 = coord_13; let _e25 = textureSample(texCube, samp, _e24); c_4 = _e25; + _ = coord_13; let _e28 = coord_13; let _e30 = textureSampleBias(texCube, samp, _e28, 2.0); c_4 = _e30; + _ = coord_13; + _ = vec3(4.0); + _ = vec3(4.0); let _e36 = coord_13; let _e41 = textureSampleGrad(texCube, samp, _e36, vec3(4.0), vec3(4.0)); c_4 = _e41; + _ = coord_13; let _e44 = coord_13; let _e46 = textureSampleLevel(texCube, samp, _e44, 3.0); c_4 = _e46; @@ -510,13 +696,19 @@ fn testTexCubeShadow(coord_14: vec3) { let _e20 = textureDimensions(texCubeShadow, 0); sizeCubeShadow = _e20; let _e23 = coord_15; + _ = vec4(_e23.x, _e23.y, _e23.z, 1.0); let _e29 = coord_15; let _e34 = vec4(_e29.x, _e29.y, _e29.z, 1.0); let _e37 = textureSampleCompare(texCubeShadow, sampShadow, _e34.xyz, _e34.w); d_2 = _e37; let _e38 = coord_15; + _ = vec4(_e38.x, _e38.y, _e38.z, 1.0); + _ = vec3(4.0); + _ = vec3(4.0); let _e48 = coord_15; let _e53 = vec4(_e48.x, _e48.y, _e48.z, 1.0); + _ = vec3(4.0); + _ = vec3(4.0); let _e60 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e53.xyz, _e53.w); d_2 = _e60; return; @@ -531,15 +723,21 @@ fn testTexCubeArray(coord_16: vec4) { let _e20 = textureDimensions(texCubeArray, 0); let _e23 = textureNumLayers(texCubeArray); sizeCubeArray = vec3(_e20.x, _e20.y, _e23); + _ = coord_17; let _e28 = coord_17; let _e32 = textureSample(texCubeArray, samp, _e28.xyz, i32(_e28.w)); c_5 = _e32; + _ = coord_17; let _e35 = coord_17; let _e40 = textureSampleBias(texCubeArray, samp, _e35.xyz, i32(_e35.w), 2.0); c_5 = _e40; + _ = coord_17; + _ = vec3(4.0); + _ = vec3(4.0); let _e46 = coord_17; let _e54 = textureSampleGrad(texCubeArray, samp, _e46.xyz, i32(_e46.w), vec3(4.0), vec3(4.0)); c_5 = _e54; + _ = coord_17; let _e57 = coord_17; let _e62 = textureSampleLevel(texCubeArray, samp, _e57.xyz, i32(_e57.w), 3.0); c_5 = _e62; @@ -555,6 +753,7 @@ fn testTexCubeArrayShadow(coord_18: vec4) { let _e20 = textureDimensions(texCubeArrayShadow, 0); let _e23 = textureNumLayers(texCubeArrayShadow); sizeCubeArrayShadow = vec3(_e20.x, _e20.y, _e23); + _ = coord_19; let _e29 = coord_19; let _e34 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e29.xyz, i32(_e29.w), 1.0); d_3 = _e34; @@ -569,76 +768,120 @@ fn testTex3D(coord_20: vec3) { coord_21 = coord_20; let _e20 = textureDimensions(tex3D, 0); size3D = _e20; + _ = coord_21; let _e24 = coord_21; let _e25 = textureSample(tex3D, samp, _e24); c_6 = _e25; + _ = coord_21; let _e28 = coord_21; let _e30 = textureSampleBias(tex3D, samp, _e28, 2.0); c_6 = _e30; let _e31 = coord_21; + _ = vec4(_e31.x, _e31.y, _e31.z, 6.0); let _e37 = coord_21; let _e42 = vec4(_e37.x, _e37.y, _e37.z, 6.0); let _e47 = textureSample(tex3D, samp, (_e42.xyz / vec3(_e42.w))); c_6 = _e47; let _e48 = coord_21; + _ = vec4(_e48.x, _e48.y, _e48.z, 6.0); let _e55 = coord_21; let _e60 = vec4(_e55.x, _e55.y, _e55.z, 6.0); let _e66 = textureSampleBias(tex3D, samp, (_e60.xyz / vec3(_e60.w)), 2.0); c_6 = _e66; let _e67 = coord_21; + _ = vec4(_e67.x, _e67.y, _e67.z, 6.0); + _ = vec3(5); let _e75 = coord_21; let _e80 = vec4(_e75.x, _e75.y, _e75.z, 6.0); + _ = vec3(5); let _e87 = textureSample(tex3D, samp, (_e80.xyz / vec3(_e80.w)), vec3(5, 5, 5)); c_6 = _e87; let _e88 = coord_21; + _ = vec4(_e88.x, _e88.y, _e88.z, 6.0); + _ = vec3(5); let _e97 = coord_21; let _e102 = vec4(_e97.x, _e97.y, _e97.z, 6.0); + _ = vec3(5); let _e110 = textureSampleBias(tex3D, samp, (_e102.xyz / vec3(_e102.w)), 2.0, vec3(5, 5, 5)); c_6 = _e110; let _e111 = coord_21; + _ = vec4(_e111.x, _e111.y, _e111.z, 6.0); let _e118 = coord_21; let _e123 = vec4(_e118.x, _e118.y, _e118.z, 6.0); let _e129 = textureSampleLevel(tex3D, samp, (_e123.xyz / vec3(_e123.w)), 3.0); c_6 = _e129; let _e130 = coord_21; + _ = vec4(_e130.x, _e130.y, _e130.z, 6.0); + _ = vec3(5); let _e139 = coord_21; let _e144 = vec4(_e139.x, _e139.y, _e139.z, 6.0); + _ = vec3(5); let _e152 = textureSampleLevel(tex3D, samp, (_e144.xyz / vec3(_e144.w)), 3.0, vec3(5, 5, 5)); c_6 = _e152; let _e153 = coord_21; + _ = vec4(_e153.x, _e153.y, _e153.z, 6.0); + _ = vec3(4.0); + _ = vec3(4.0); let _e163 = coord_21; let _e168 = vec4(_e163.x, _e163.y, _e163.z, 6.0); let _e177 = textureSampleGrad(tex3D, samp, (_e168.xyz / vec3(_e168.w)), vec3(4.0), vec3(4.0)); c_6 = _e177; let _e178 = coord_21; + _ = vec4(_e178.x, _e178.y, _e178.z, 6.0); + _ = vec3(4.0); + _ = vec3(4.0); + _ = vec3(5); let _e190 = coord_21; let _e195 = vec4(_e190.x, _e190.y, _e190.z, 6.0); + _ = vec3(5); let _e206 = textureSampleGrad(tex3D, samp, (_e195.xyz / vec3(_e195.w)), vec3(4.0), vec3(4.0), vec3(5, 5, 5)); c_6 = _e206; + _ = coord_21; + _ = vec3(4.0); + _ = vec3(4.0); let _e212 = coord_21; let _e217 = textureSampleGrad(tex3D, samp, _e212, vec3(4.0), vec3(4.0)); c_6 = _e217; + _ = coord_21; + _ = vec3(4.0); + _ = vec3(4.0); + _ = vec3(5); let _e225 = coord_21; + _ = vec3(5); let _e232 = textureSampleGrad(tex3D, samp, _e225, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); c_6 = _e232; + _ = coord_21; let _e235 = coord_21; let _e237 = textureSampleLevel(tex3D, samp, _e235, 3.0); c_6 = _e237; + _ = coord_21; + _ = vec3(5); let _e242 = coord_21; + _ = vec3(5); let _e246 = textureSampleLevel(tex3D, samp, _e242, 3.0, vec3(5, 5, 5)); c_6 = _e246; + _ = coord_21; + _ = vec3(5); let _e250 = coord_21; + _ = vec3(5); let _e253 = textureSample(tex3D, samp, _e250, vec3(5, 5, 5)); c_6 = _e253; + _ = coord_21; + _ = vec3(5); let _e258 = coord_21; + _ = vec3(5); let _e262 = textureSampleBias(tex3D, samp, _e258, 2.0, vec3(5, 5, 5)); c_6 = _e262; let _e263 = coord_21; + _ = vec3(_e263); let _e266 = coord_21; let _e269 = textureLoad(tex3D, vec3(_e266), 3); c_6 = _e269; let _e270 = coord_21; + _ = vec3(_e270); + _ = vec3(5); let _e275 = coord_21; + _ = vec3(5); let _e280 = textureLoad(tex3D, vec3(_e275), 3); c_6 = _e280; return; @@ -653,6 +896,7 @@ fn testTex2DMS(coord_22: vec2) { let _e18 = textureDimensions(tex2DMS); size2DMS = _e18; let _e21 = coord_23; + _ = vec2(_e21); let _e24 = coord_23; let _e27 = textureLoad(tex2DMS, vec2(_e24), 3); c_7 = _e27; @@ -669,6 +913,7 @@ fn testTex2DMSArray(coord_24: vec3) { let _e21 = textureNumLayers(tex2DMSArray); size2DMSArray = vec3(_e18.x, _e18.y, _e21); let _e25 = coord_25; + _ = vec3(_e25); let _e28 = coord_25; let _e29 = vec3(_e28); let _e33 = textureLoad(tex2DMSArray, _e29.xy, _e29.z, 3); diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index 1a57a2e3a..a6d7da9e9 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -6,11 +6,15 @@ fn main_1() { var x: vec3 = vec3(2.0, 2.0, 2.0); var local: vec2; + _ = vec3(2.0); let _e3 = x; + _ = _e3.zxy; + _ = _e3.zx; let _e8 = vec2(3.0, 4.0); x.z = _e8.x; x.x = _e8.y; let _e13 = x; + _ = _e13.xy; let _e15 = x; let _e18 = (_e15.xy * 5.0); x.x = _e18.x; @@ -20,6 +24,7 @@ fn main_1() { x.z = _e27.x; x.y = _e27.y; let _e32 = x; + _ = _e32.xz; let _e34 = x; local = _e34.xz; foo((&local)); From 239bbbbed44a5c9e74399af1ae6d38b54766f28d Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 29 Apr 2022 21:26:43 +0200 Subject: [PATCH 1739/2212] [spv-out] zero init variables in function and private address spaces --- src/back/spv/writer.rs | 12 +- tests/out/spv/access.spvasm | 429 ++++++------- tests/out/spv/binding-arrays.spvasm | 932 ++++++++++++++-------------- tests/out/spv/bits.spvasm | 378 +++++------ tests/out/spv/boids.spvasm | 511 +++++++-------- tests/out/spv/collatz.spvasm | 139 +++-- tests/out/spv/control-flow.spvasm | 109 ++-- tests/out/spv/interpolate.spvasm | 313 +++++----- tests/out/spv/operators.spvasm | 821 ++++++++++++------------ tests/out/spv/pointers.spvasm | 85 +-- tests/out/spv/policy-mix.spvasm | 158 ++--- tests/out/spv/shadow.spvasm | 491 +++++++-------- tests/out/spv/skybox.spvasm | 172 ++--- 13 files changed, 2295 insertions(+), 2255 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a629d5beb..f4d9e0e60 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -309,7 +309,10 @@ impl Writer { pointer_type_id, id, spirv::StorageClass::Function, - init_word, + init_word.or_else(|| { + let type_id = self.get_type_id(LookupType::Handle(variable.ty)); + Some(self.write_constant_null(type_id)) + }), ); function .variables @@ -1325,6 +1328,13 @@ impl Writer { } }; + let init_word = match global_variable.space { + crate::AddressSpace::Private => { + init_word.or_else(|| Some(self.write_constant_null(inner_type_id))) + } + _ => init_word, + }; + Instruction::variable(pointer_type_id, id, class, init_word) .to_words(&mut self.logical_layout.declarations); Ok(id) diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index fa5c64395..68f296d42 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 218 +; Bound: 221 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %141 "foo_vert" %136 %139 -OpEntryPoint Fragment %178 "foo_frag" %177 -OpEntryPoint GLCompute %195 "atomics" -OpExecutionMode %178 OriginUpperLeft -OpExecutionMode %195 LocalSize 1 1 1 +OpEntryPoint Vertex %143 "foo_vert" %138 %141 +OpEntryPoint Fragment %180 "foo_frag" %179 +OpEntryPoint GLCompute %198 "atomics" +OpExecutionMode %180 OriginUpperLeft +OpExecutionMode %198 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %32 0 "value" OpName %32 "AlignedWrapper" @@ -26,18 +26,18 @@ OpName %52 "bar" OpName %54 "baz" OpName %57 "idx" OpName %59 "t" -OpName %62 "test_matrix_within_struct_accesses" -OpName %120 "foo" -OpName %121 "read_from_private" -OpName %126 "a" -OpName %127 "test_arr_as_arg" -OpName %132 "foo" -OpName %133 "c" -OpName %136 "vi" -OpName %141 "foo_vert" -OpName %178 "foo_frag" -OpName %193 "tmp" -OpName %195 "atomics" +OpName %63 "test_matrix_within_struct_accesses" +OpName %121 "foo" +OpName %122 "read_from_private" +OpName %127 "a" +OpName %128 "test_arr_as_arg" +OpName %133 "foo" +OpName %134 "c" +OpName %138 "vi" +OpName %143 "foo_vert" +OpName %180 "foo_frag" +OpName %195 "tmp" +OpName %198 "atomics" OpMemberDecorate %32 0 Offset 0 OpDecorate %37 ArrayStride 16 OpDecorate %39 ArrayStride 8 @@ -64,9 +64,9 @@ OpDecorate %54 DescriptorSet 0 OpDecorate %54 Binding 1 OpDecorate %55 Block OpMemberDecorate %55 0 Offset 0 -OpDecorate %136 BuiltIn VertexIndex -OpDecorate %139 BuiltIn Position -OpDecorate %177 Location 0 +OpDecorate %138 BuiltIn VertexIndex +OpDecorate %141 BuiltIn Position +OpDecorate %179 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -124,208 +124,211 @@ OpDecorate %177 Location 0 %54 = OpVariable %56 Uniform %58 = OpTypePointer Function %4 %60 = OpTypePointer Function %43 -%63 = OpTypeFunction %2 -%64 = OpTypePointer Uniform %43 -%69 = OpTypePointer Uniform %42 -%72 = OpTypePointer Uniform %36 -%78 = OpTypePointer Uniform %9 -%98 = OpTypePointer Function %42 -%104 = OpTypePointer Function %36 -%110 = OpTypePointer Function %9 -%122 = OpTypeFunction %9 %44 -%128 = OpTypeFunction %9 %46 -%134 = OpTypePointer Function %49 -%137 = OpTypePointer Input %26 -%136 = OpVariable %137 Input -%140 = OpTypePointer Output %47 -%139 = OpVariable %140 Output -%146 = OpTypePointer StorageBuffer %33 -%149 = OpTypePointer StorageBuffer %39 -%152 = OpTypePointer StorageBuffer %34 -%153 = OpTypePointer StorageBuffer %9 -%156 = OpTypePointer StorageBuffer %40 -%159 = OpTypePointer StorageBuffer %32 -%160 = OpConstant %26 4 -%171 = OpTypeVector %4 4 -%177 = OpVariable %140 Output -%197 = OpTypePointer StorageBuffer %4 -%200 = OpConstant %26 64 -%62 = OpFunction %2 None %63 -%61 = OpLabel +%61 = OpConstantNull %43 +%64 = OpTypeFunction %2 +%65 = OpTypePointer Uniform %43 +%70 = OpTypePointer Uniform %42 +%73 = OpTypePointer Uniform %36 +%79 = OpTypePointer Uniform %9 +%99 = OpTypePointer Function %42 +%105 = OpTypePointer Function %36 +%111 = OpTypePointer Function %9 +%123 = OpTypeFunction %9 %44 +%129 = OpTypeFunction %9 %46 +%135 = OpTypePointer Function %49 +%136 = OpConstantNull %49 +%139 = OpTypePointer Input %26 +%138 = OpVariable %139 Input +%142 = OpTypePointer Output %47 +%141 = OpVariable %142 Output +%148 = OpTypePointer StorageBuffer %33 +%151 = OpTypePointer StorageBuffer %39 +%154 = OpTypePointer StorageBuffer %34 +%155 = OpTypePointer StorageBuffer %9 +%158 = OpTypePointer StorageBuffer %40 +%161 = OpTypePointer StorageBuffer %32 +%162 = OpConstant %26 4 +%173 = OpTypeVector %4 4 +%179 = OpVariable %142 Output +%196 = OpConstantNull %4 +%200 = OpTypePointer StorageBuffer %4 +%203 = OpConstant %26 64 +%63 = OpFunction %2 None %64 +%62 = OpLabel %57 = OpVariable %58 Function %5 -%59 = OpVariable %60 Function -%65 = OpAccessChain %64 %54 %31 -OpBranch %66 -%66 = OpLabel -%67 = OpLoad %4 %57 -%68 = OpISub %4 %67 %6 -OpStore %57 %68 -%70 = OpAccessChain %69 %65 %31 -%71 = OpLoad %42 %70 -%73 = OpAccessChain %72 %65 %31 %31 -%74 = OpLoad %36 %73 -%75 = OpLoad %4 %57 -%76 = OpAccessChain %72 %65 %31 %75 -%77 = OpLoad %36 %76 -%79 = OpAccessChain %78 %65 %31 %31 %29 -%80 = OpLoad %9 %79 -%81 = OpLoad %4 %57 -%82 = OpAccessChain %78 %65 %31 %31 %81 -%83 = OpLoad %9 %82 -%84 = OpLoad %4 %57 -%85 = OpAccessChain %78 %65 %31 %84 %29 -%86 = OpLoad %9 %85 -%87 = OpLoad %4 %57 +%59 = OpVariable %60 Function %61 +%66 = OpAccessChain %65 %54 %31 +OpBranch %67 +%67 = OpLabel +%68 = OpLoad %4 %57 +%69 = OpISub %4 %68 %6 +OpStore %57 %69 +%71 = OpAccessChain %70 %66 %31 +%72 = OpLoad %42 %71 +%74 = OpAccessChain %73 %66 %31 %31 +%75 = OpLoad %36 %74 +%76 = OpLoad %4 %57 +%77 = OpAccessChain %73 %66 %31 %76 +%78 = OpLoad %36 %77 +%80 = OpAccessChain %79 %66 %31 %31 %29 +%81 = OpLoad %9 %80 +%82 = OpLoad %4 %57 +%83 = OpAccessChain %79 %66 %31 %31 %82 +%84 = OpLoad %9 %83 +%85 = OpLoad %4 %57 +%86 = OpAccessChain %79 %66 %31 %85 %29 +%87 = OpLoad %9 %86 %88 = OpLoad %4 %57 -%89 = OpAccessChain %78 %65 %31 %87 %88 -%90 = OpLoad %9 %89 -%91 = OpCompositeConstruct %36 %8 %8 -%92 = OpCompositeConstruct %36 %10 %10 -%93 = OpCompositeConstruct %36 %11 %11 -%94 = OpCompositeConstruct %42 %91 %92 %93 -%95 = OpCompositeConstruct %43 %94 -OpStore %59 %95 -%96 = OpLoad %4 %57 -%97 = OpIAdd %4 %96 %6 -OpStore %57 %97 -%99 = OpCompositeConstruct %36 %12 %12 -%100 = OpCompositeConstruct %36 %13 %13 -%101 = OpCompositeConstruct %36 %14 %14 -%102 = OpCompositeConstruct %42 %99 %100 %101 -%103 = OpAccessChain %98 %59 %31 -OpStore %103 %102 -%105 = OpCompositeConstruct %36 %15 %15 -%106 = OpAccessChain %104 %59 %31 %31 -OpStore %106 %105 -%107 = OpLoad %4 %57 -%108 = OpCompositeConstruct %36 %16 %16 -%109 = OpAccessChain %104 %59 %31 %107 -OpStore %109 %108 -%111 = OpAccessChain %110 %59 %31 %31 %29 -OpStore %111 %17 -%112 = OpLoad %4 %57 -%113 = OpAccessChain %110 %59 %31 %31 %112 -OpStore %113 %18 -%114 = OpLoad %4 %57 -%115 = OpAccessChain %110 %59 %31 %114 %29 -OpStore %115 %19 -%116 = OpLoad %4 %57 +%89 = OpLoad %4 %57 +%90 = OpAccessChain %79 %66 %31 %88 %89 +%91 = OpLoad %9 %90 +%92 = OpCompositeConstruct %36 %8 %8 +%93 = OpCompositeConstruct %36 %10 %10 +%94 = OpCompositeConstruct %36 %11 %11 +%95 = OpCompositeConstruct %42 %92 %93 %94 +%96 = OpCompositeConstruct %43 %95 +OpStore %59 %96 +%97 = OpLoad %4 %57 +%98 = OpIAdd %4 %97 %6 +OpStore %57 %98 +%100 = OpCompositeConstruct %36 %12 %12 +%101 = OpCompositeConstruct %36 %13 %13 +%102 = OpCompositeConstruct %36 %14 %14 +%103 = OpCompositeConstruct %42 %100 %101 %102 +%104 = OpAccessChain %99 %59 %31 +OpStore %104 %103 +%106 = OpCompositeConstruct %36 %15 %15 +%107 = OpAccessChain %105 %59 %31 %31 +OpStore %107 %106 +%108 = OpLoad %4 %57 +%109 = OpCompositeConstruct %36 %16 %16 +%110 = OpAccessChain %105 %59 %31 %108 +OpStore %110 %109 +%112 = OpAccessChain %111 %59 %31 %31 %29 +OpStore %112 %17 +%113 = OpLoad %4 %57 +%114 = OpAccessChain %111 %59 %31 %31 %113 +OpStore %114 %18 +%115 = OpLoad %4 %57 +%116 = OpAccessChain %111 %59 %31 %115 %29 +OpStore %116 %19 %117 = OpLoad %4 %57 -%118 = OpAccessChain %110 %59 %31 %116 %117 -OpStore %118 %20 +%118 = OpLoad %4 %57 +%119 = OpAccessChain %111 %59 %31 %117 %118 +OpStore %119 %20 OpReturn OpFunctionEnd -%121 = OpFunction %9 None %122 -%120 = OpFunctionParameter %44 -%119 = OpLabel -OpBranch %123 -%123 = OpLabel -%124 = OpLoad %9 %120 -OpReturnValue %124 +%122 = OpFunction %9 None %123 +%121 = OpFunctionParameter %44 +%120 = OpLabel +OpBranch %124 +%124 = OpLabel +%125 = OpLoad %9 %121 +OpReturnValue %125 OpFunctionEnd -%127 = OpFunction %9 None %128 -%126 = OpFunctionParameter %46 -%125 = OpLabel -OpBranch %129 -%129 = OpLabel -%130 = OpCompositeExtract %45 %126 4 -%131 = OpCompositeExtract %9 %130 9 -OpReturnValue %131 +%128 = OpFunction %9 None %129 +%127 = OpFunctionParameter %46 +%126 = OpLabel +OpBranch %130 +%130 = OpLabel +%131 = OpCompositeExtract %45 %127 4 +%132 = OpCompositeExtract %9 %131 9 +OpReturnValue %132 OpFunctionEnd -%141 = OpFunction %2 None %63 -%135 = OpLabel -%132 = OpVariable %44 Function %24 -%133 = OpVariable %134 Function -%138 = OpLoad %26 %136 -%142 = OpAccessChain %64 %54 %31 -OpBranch %143 -%143 = OpLabel -%144 = OpLoad %9 %132 -OpStore %132 %8 -%145 = OpFunctionCall %2 %62 -%147 = OpAccessChain %146 %52 %31 -%148 = OpLoad %33 %147 -%150 = OpAccessChain %149 %52 %25 -%151 = OpLoad %39 %150 -%154 = OpAccessChain %153 %52 %31 %25 %31 -%155 = OpLoad %9 %154 -%157 = OpArrayLength %26 %52 4 -%158 = OpISub %26 %157 %27 -%161 = OpAccessChain %48 %52 %160 %158 %31 -%162 = OpLoad %4 %161 -%163 = OpFunctionCall %9 %121 %132 -%164 = OpConvertFToS %4 %155 -%165 = OpCompositeConstruct %49 %162 %164 %28 %23 %22 -OpStore %133 %165 -%166 = OpIAdd %26 %138 %29 -%167 = OpAccessChain %58 %133 %166 -OpStore %167 %30 -%168 = OpAccessChain %58 %133 %138 -%169 = OpLoad %4 %168 -%170 = OpFunctionCall %9 %127 %51 -%172 = OpCompositeConstruct %171 %169 %169 %169 %169 -%173 = OpConvertSToF %47 %172 -%174 = OpMatrixTimesVector %34 %148 %173 -%175 = OpCompositeConstruct %47 %174 %10 -OpStore %139 %175 +%143 = OpFunction %2 None %64 +%137 = OpLabel +%133 = OpVariable %44 Function %24 +%134 = OpVariable %135 Function %136 +%140 = OpLoad %26 %138 +%144 = OpAccessChain %65 %54 %31 +OpBranch %145 +%145 = OpLabel +%146 = OpLoad %9 %133 +OpStore %133 %8 +%147 = OpFunctionCall %2 %63 +%149 = OpAccessChain %148 %52 %31 +%150 = OpLoad %33 %149 +%152 = OpAccessChain %151 %52 %25 +%153 = OpLoad %39 %152 +%156 = OpAccessChain %155 %52 %31 %25 %31 +%157 = OpLoad %9 %156 +%159 = OpArrayLength %26 %52 4 +%160 = OpISub %26 %159 %27 +%163 = OpAccessChain %48 %52 %162 %160 %31 +%164 = OpLoad %4 %163 +%165 = OpFunctionCall %9 %122 %133 +%166 = OpConvertFToS %4 %157 +%167 = OpCompositeConstruct %49 %164 %166 %28 %23 %22 +OpStore %134 %167 +%168 = OpIAdd %26 %140 %29 +%169 = OpAccessChain %58 %134 %168 +OpStore %169 %30 +%170 = OpAccessChain %58 %134 %140 +%171 = OpLoad %4 %170 +%172 = OpFunctionCall %9 %128 %51 +%174 = OpCompositeConstruct %173 %171 %171 %171 %171 +%175 = OpConvertSToF %47 %174 +%176 = OpMatrixTimesVector %34 %150 %175 +%177 = OpCompositeConstruct %47 %176 %10 +OpStore %141 %177 OpReturn OpFunctionEnd -%178 = OpFunction %2 None %63 -%176 = OpLabel -OpBranch %179 -%179 = OpLabel -%180 = OpAccessChain %153 %52 %31 %29 %27 -OpStore %180 %8 -%181 = OpCompositeConstruct %34 %24 %24 %24 -%182 = OpCompositeConstruct %34 %8 %8 %8 -%183 = OpCompositeConstruct %34 %10 %10 %10 -%184 = OpCompositeConstruct %34 %11 %11 %11 -%185 = OpCompositeConstruct %33 %181 %182 %183 %184 -%186 = OpAccessChain %146 %52 %31 -OpStore %186 %185 -%187 = OpCompositeConstruct %38 %31 %31 -%188 = OpCompositeConstruct %38 %29 %29 -%189 = OpCompositeConstruct %39 %187 %188 -%190 = OpAccessChain %149 %52 %25 -OpStore %190 %189 -%191 = OpAccessChain %48 %52 %160 %29 %31 -OpStore %191 %6 -%192 = OpCompositeConstruct %47 %24 %24 %24 %24 -OpStore %177 %192 +%180 = OpFunction %2 None %64 +%178 = OpLabel +OpBranch %181 +%181 = OpLabel +%182 = OpAccessChain %155 %52 %31 %29 %27 +OpStore %182 %8 +%183 = OpCompositeConstruct %34 %24 %24 %24 +%184 = OpCompositeConstruct %34 %8 %8 %8 +%185 = OpCompositeConstruct %34 %10 %10 %10 +%186 = OpCompositeConstruct %34 %11 %11 %11 +%187 = OpCompositeConstruct %33 %183 %184 %185 %186 +%188 = OpAccessChain %148 %52 %31 +OpStore %188 %187 +%189 = OpCompositeConstruct %38 %31 %31 +%190 = OpCompositeConstruct %38 %29 %29 +%191 = OpCompositeConstruct %39 %189 %190 +%192 = OpAccessChain %151 %52 %25 +OpStore %192 %191 +%193 = OpAccessChain %48 %52 %162 %29 %31 +OpStore %193 %6 +%194 = OpCompositeConstruct %47 %24 %24 %24 %24 +OpStore %179 %194 OpReturn OpFunctionEnd -%195 = OpFunction %2 None %63 -%194 = OpLabel -%193 = OpVariable %58 Function -OpBranch %196 -%196 = OpLabel -%198 = OpAccessChain %197 %52 %27 -%199 = OpAtomicLoad %4 %198 %6 %200 -%202 = OpAccessChain %197 %52 %27 -%201 = OpAtomicIAdd %4 %202 %6 %200 %22 -OpStore %193 %201 -%204 = OpAccessChain %197 %52 %27 -%203 = OpAtomicISub %4 %204 %6 %200 %22 -OpStore %193 %203 -%206 = OpAccessChain %197 %52 %27 -%205 = OpAtomicAnd %4 %206 %6 %200 %22 -OpStore %193 %205 -%208 = OpAccessChain %197 %52 %27 -%207 = OpAtomicOr %4 %208 %6 %200 %22 -OpStore %193 %207 -%210 = OpAccessChain %197 %52 %27 -%209 = OpAtomicXor %4 %210 %6 %200 %22 -OpStore %193 %209 -%212 = OpAccessChain %197 %52 %27 -%211 = OpAtomicSMin %4 %212 %6 %200 %22 -OpStore %193 %211 -%214 = OpAccessChain %197 %52 %27 -%213 = OpAtomicSMax %4 %214 %6 %200 %22 -OpStore %193 %213 -%216 = OpAccessChain %197 %52 %27 -%215 = OpAtomicExchange %4 %216 %6 %200 %22 -OpStore %193 %215 -%217 = OpAccessChain %197 %52 %27 -OpAtomicStore %217 %6 %200 %199 +%198 = OpFunction %2 None %64 +%197 = OpLabel +%195 = OpVariable %58 Function %196 +OpBranch %199 +%199 = OpLabel +%201 = OpAccessChain %200 %52 %27 +%202 = OpAtomicLoad %4 %201 %6 %203 +%205 = OpAccessChain %200 %52 %27 +%204 = OpAtomicIAdd %4 %205 %6 %203 %22 +OpStore %195 %204 +%207 = OpAccessChain %200 %52 %27 +%206 = OpAtomicISub %4 %207 %6 %203 %22 +OpStore %195 %206 +%209 = OpAccessChain %200 %52 %27 +%208 = OpAtomicAnd %4 %209 %6 %203 %22 +OpStore %195 %208 +%211 = OpAccessChain %200 %52 %27 +%210 = OpAtomicOr %4 %211 %6 %203 %22 +OpStore %195 %210 +%213 = OpAccessChain %200 %52 %27 +%212 = OpAtomicXor %4 %213 %6 %203 %22 +OpStore %195 %212 +%215 = OpAccessChain %200 %52 %27 +%214 = OpAtomicSMin %4 %215 %6 %203 %22 +OpStore %195 %214 +%217 = OpAccessChain %200 %52 %27 +%216 = OpAtomicSMax %4 %217 %6 %203 %22 +OpStore %195 %216 +%219 = OpAccessChain %200 %52 %27 +%218 = OpAtomicExchange %4 %219 %6 %203 %22 +OpStore %195 %218 +%220 = OpAccessChain %200 %52 %27 +OpAtomicStore %220 %6 %203 %202 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index f68a755cc..a420eba46 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -1,15 +1,15 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 429 +; Bound: 431 OpCapability Shader OpCapability ImageQuery OpCapability ShaderNonUniform OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %63 "main" %58 %61 -OpExecutionMode %63 OriginUpperLeft +OpEntryPoint Fragment %65 "main" %60 %63 +OpExecutionMode %65 OriginUpperLeft OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %24 0 Offset 0 OpDecorate %27 DescriptorSet 0 @@ -32,31 +32,31 @@ OpDecorate %45 DescriptorSet 0 OpDecorate %45 Binding 8 OpDecorate %46 Block OpMemberDecorate %46 0 Offset 0 -OpDecorate %58 Location 0 -OpDecorate %58 Flat -OpDecorate %61 Location 0 -OpDecorate %91 NonUniform -OpDecorate %114 NonUniform +OpDecorate %60 Location 0 +OpDecorate %60 Flat +OpDecorate %63 Location 0 +OpDecorate %93 NonUniform OpDecorate %116 NonUniform -OpDecorate %141 NonUniform +OpDecorate %118 NonUniform OpDecorate %143 NonUniform -OpDecorate %181 NonUniform -OpDecorate %210 NonUniform -OpDecorate %226 NonUniform -OpDecorate %242 NonUniform -OpDecorate %263 NonUniform +OpDecorate %145 NonUniform +OpDecorate %183 NonUniform +OpDecorate %212 NonUniform +OpDecorate %228 NonUniform +OpDecorate %244 NonUniform OpDecorate %265 NonUniform -OpDecorate %287 NonUniform +OpDecorate %267 NonUniform OpDecorate %289 NonUniform -OpDecorate %311 NonUniform +OpDecorate %291 NonUniform OpDecorate %313 NonUniform -OpDecorate %335 NonUniform +OpDecorate %315 NonUniform OpDecorate %337 NonUniform -OpDecorate %359 NonUniform +OpDecorate %339 NonUniform OpDecorate %361 NonUniform -OpDecorate %383 NonUniform +OpDecorate %363 NonUniform OpDecorate %385 NonUniform -OpDecorate %407 NonUniform +OpDecorate %387 NonUniform +OpDecorate %409 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 5 @@ -105,451 +105,453 @@ OpDecorate %407 NonUniform %45 = OpVariable %47 Uniform %49 = OpTypePointer Function %4 %51 = OpTypePointer Function %26 -%53 = OpTypePointer Function %7 -%55 = OpTypePointer Function %25 -%59 = OpTypePointer Input %8 -%58 = OpVariable %59 Input -%62 = OpTypePointer Output %25 -%61 = OpVariable %62 Output -%64 = OpTypeFunction %2 -%65 = OpTypePointer Uniform %9 -%66 = OpConstant %8 0 -%69 = OpTypePointer Uniform %8 -%75 = OpTypeVector %7 2 -%79 = OpTypePointer UniformConstant %10 -%97 = OpTypePointer UniformConstant %21 -%100 = OpTypeSampledImage %10 -%121 = OpTypePointer UniformConstant %17 -%124 = OpTypePointer UniformConstant %21 -%127 = OpTypeSampledImage %17 -%150 = OpTypeBool -%151 = OpConstantNull %25 -%157 = OpTypeVector %150 2 -%167 = OpConstantNull %25 -%182 = OpConstantNull %25 -%195 = OpTypePointer UniformConstant %13 -%198 = OpTypeVector %4 3 -%230 = OpTypePointer UniformConstant %15 -%389 = OpTypePointer UniformConstant %19 -%63 = OpFunction %2 None %64 -%56 = OpLabel -%50 = OpVariable %51 Function -%54 = OpVariable %55 Function +%52 = OpConstantNull %26 +%54 = OpTypePointer Function %7 +%56 = OpTypePointer Function %25 +%57 = OpConstantNull %25 +%61 = OpTypePointer Input %8 +%60 = OpVariable %61 Input +%64 = OpTypePointer Output %25 +%63 = OpVariable %64 Output +%66 = OpTypeFunction %2 +%67 = OpTypePointer Uniform %9 +%68 = OpConstant %8 0 +%71 = OpTypePointer Uniform %8 +%77 = OpTypeVector %7 2 +%81 = OpTypePointer UniformConstant %10 +%99 = OpTypePointer UniformConstant %21 +%102 = OpTypeSampledImage %10 +%123 = OpTypePointer UniformConstant %17 +%126 = OpTypePointer UniformConstant %21 +%129 = OpTypeSampledImage %17 +%152 = OpTypeBool +%153 = OpConstantNull %25 +%159 = OpTypeVector %152 2 +%169 = OpConstantNull %25 +%184 = OpConstantNull %25 +%197 = OpTypePointer UniformConstant %13 +%200 = OpTypeVector %4 3 +%232 = OpTypePointer UniformConstant %15 +%391 = OpTypePointer UniformConstant %19 +%65 = OpFunction %2 None %66 +%58 = OpLabel +%50 = OpVariable %51 Function %52 +%55 = OpVariable %56 Function %57 %48 = OpVariable %49 Function %5 -%52 = OpVariable %53 Function %6 -%60 = OpLoad %8 %58 -%57 = OpCompositeConstruct %24 %60 -%67 = OpAccessChain %65 %45 %66 -OpBranch %68 -%68 = OpLabel -%70 = OpAccessChain %69 %67 %66 -%71 = OpLoad %8 %70 -%72 = OpCompositeExtract %8 %57 0 -%73 = OpCompositeConstruct %26 %5 %5 -OpStore %50 %73 -%74 = OpCompositeConstruct %25 %6 %6 %6 %6 -OpStore %54 %74 -%76 = OpCompositeConstruct %75 %6 %6 -%77 = OpCompositeConstruct %26 %5 %5 -%78 = OpLoad %26 %50 -%80 = OpAccessChain %79 %27 %66 -%81 = OpLoad %10 %80 -%82 = OpImageQuerySizeLod %26 %81 %66 -%83 = OpIAdd %26 %78 %82 -OpStore %50 %83 -%84 = OpLoad %26 %50 -%85 = OpAccessChain %79 %27 %71 -%86 = OpLoad %10 %85 -%87 = OpImageQuerySizeLod %26 %86 %66 -%88 = OpIAdd %26 %84 %87 -OpStore %50 %88 -%89 = OpLoad %26 %50 -%90 = OpAccessChain %79 %27 %72 -%91 = OpLoad %10 %90 -%92 = OpImageQuerySizeLod %26 %91 %66 -%93 = OpIAdd %26 %89 %92 -OpStore %50 %93 -%94 = OpLoad %25 %54 -%95 = OpAccessChain %79 %31 %66 -%96 = OpLoad %10 %95 -%98 = OpAccessChain %97 %41 %66 -%99 = OpLoad %21 %98 -%101 = OpSampledImage %100 %96 %99 -%102 = OpImageGather %25 %101 %76 %66 -%103 = OpFAdd %25 %94 %102 -OpStore %54 %103 -%104 = OpLoad %25 %54 -%105 = OpAccessChain %79 %31 %71 -%106 = OpLoad %10 %105 -%107 = OpAccessChain %97 %41 %71 -%108 = OpLoad %21 %107 -%109 = OpSampledImage %100 %106 %108 -%110 = OpImageGather %25 %109 %76 %66 -%111 = OpFAdd %25 %104 %110 -OpStore %54 %111 -%112 = OpLoad %25 %54 -%113 = OpAccessChain %79 %31 %72 -%114 = OpLoad %10 %113 -%115 = OpAccessChain %97 %41 %72 -%116 = OpLoad %21 %115 -%117 = OpSampledImage %100 %114 %116 -%118 = OpImageGather %25 %117 %76 %66 -%119 = OpFAdd %25 %112 %118 -OpStore %54 %119 -%120 = OpLoad %25 %54 -%122 = OpAccessChain %121 %37 %66 -%123 = OpLoad %17 %122 -%125 = OpAccessChain %124 %43 %66 -%126 = OpLoad %21 %125 -%128 = OpSampledImage %127 %123 %126 -%129 = OpImageDrefGather %25 %128 %76 %6 -%130 = OpFAdd %25 %120 %129 -OpStore %54 %130 -%131 = OpLoad %25 %54 -%132 = OpAccessChain %121 %37 %71 -%133 = OpLoad %17 %132 -%134 = OpAccessChain %124 %43 %71 -%135 = OpLoad %21 %134 -%136 = OpSampledImage %127 %133 %135 -%137 = OpImageDrefGather %25 %136 %76 %6 -%138 = OpFAdd %25 %131 %137 -OpStore %54 %138 -%139 = OpLoad %25 %54 -%140 = OpAccessChain %121 %37 %72 -%141 = OpLoad %17 %140 -%142 = OpAccessChain %124 %43 %72 -%143 = OpLoad %21 %142 -%144 = OpSampledImage %127 %141 %143 -%145 = OpImageDrefGather %25 %144 %76 %6 -%146 = OpFAdd %25 %139 %145 -OpStore %54 %146 -%147 = OpLoad %25 %54 -%148 = OpAccessChain %79 %27 %66 -%149 = OpLoad %10 %148 -%152 = OpImageQueryLevels %4 %149 -%153 = OpULessThan %150 %5 %152 -OpSelectionMerge %154 None -OpBranchConditional %153 %155 %154 -%155 = OpLabel -%156 = OpImageQuerySizeLod %26 %149 %5 -%158 = OpULessThan %157 %77 %156 -%159 = OpAll %150 %158 -OpBranchConditional %159 %160 %154 -%160 = OpLabel -%161 = OpImageFetch %25 %149 %77 Lod %5 -OpBranch %154 -%154 = OpLabel -%162 = OpPhi %25 %151 %68 %151 %155 %161 %160 -%163 = OpFAdd %25 %147 %162 -OpStore %54 %163 -%164 = OpLoad %25 %54 -%165 = OpAccessChain %79 %27 %71 -%166 = OpLoad %10 %165 -%168 = OpImageQueryLevels %4 %166 -%169 = OpULessThan %150 %5 %168 -OpSelectionMerge %170 None -OpBranchConditional %169 %171 %170 -%171 = OpLabel -%172 = OpImageQuerySizeLod %26 %166 %5 -%173 = OpULessThan %157 %77 %172 -%174 = OpAll %150 %173 -OpBranchConditional %174 %175 %170 -%175 = OpLabel -%176 = OpImageFetch %25 %166 %77 Lod %5 -OpBranch %170 -%170 = OpLabel -%177 = OpPhi %25 %167 %154 %167 %171 %176 %175 -%178 = OpFAdd %25 %164 %177 -OpStore %54 %178 -%179 = OpLoad %25 %54 -%180 = OpAccessChain %79 %27 %72 -%181 = OpLoad %10 %180 -%183 = OpImageQueryLevels %4 %181 -%184 = OpULessThan %150 %5 %183 -OpSelectionMerge %185 None -OpBranchConditional %184 %186 %185 -%186 = OpLabel -%187 = OpImageQuerySizeLod %26 %181 %5 -%188 = OpULessThan %157 %77 %187 -%189 = OpAll %150 %188 -OpBranchConditional %189 %190 %185 -%190 = OpLabel -%191 = OpImageFetch %25 %181 %77 Lod %5 -OpBranch %185 -%185 = OpLabel -%192 = OpPhi %25 %182 %170 %182 %186 %191 %190 -%193 = OpFAdd %25 %179 %192 -OpStore %54 %193 -%194 = OpLoad %4 %48 -%196 = OpAccessChain %195 %33 %66 -%197 = OpLoad %13 %196 -%199 = OpImageQuerySizeLod %198 %197 %66 -%200 = OpCompositeExtract %4 %199 2 -%201 = OpIAdd %4 %194 %200 -OpStore %48 %201 -%202 = OpLoad %4 %48 -%203 = OpAccessChain %195 %33 %71 -%204 = OpLoad %13 %203 -%205 = OpImageQuerySizeLod %198 %204 %66 -%206 = OpCompositeExtract %4 %205 2 -%207 = OpIAdd %4 %202 %206 -OpStore %48 %207 -%208 = OpLoad %4 %48 -%209 = OpAccessChain %195 %33 %72 -%210 = OpLoad %13 %209 -%211 = OpImageQuerySizeLod %198 %210 %66 -%212 = OpCompositeExtract %4 %211 2 -%213 = OpIAdd %4 %208 %212 -OpStore %48 %213 -%214 = OpLoad %4 %48 -%215 = OpAccessChain %79 %31 %66 -%216 = OpLoad %10 %215 -%217 = OpImageQueryLevels %4 %216 -%218 = OpIAdd %4 %214 %217 -OpStore %48 %218 -%219 = OpLoad %4 %48 -%220 = OpAccessChain %79 %31 %71 -%221 = OpLoad %10 %220 -%222 = OpImageQueryLevels %4 %221 -%223 = OpIAdd %4 %219 %222 -OpStore %48 %223 -%224 = OpLoad %4 %48 -%225 = OpAccessChain %79 %31 %72 -%226 = OpLoad %10 %225 -%227 = OpImageQueryLevels %4 %226 -%228 = OpIAdd %4 %224 %227 -OpStore %48 %228 -%229 = OpLoad %4 %48 -%231 = OpAccessChain %230 %35 %66 -%232 = OpLoad %15 %231 -%233 = OpImageQuerySamples %4 %232 -%234 = OpIAdd %4 %229 %233 -OpStore %48 %234 -%235 = OpLoad %4 %48 -%236 = OpAccessChain %230 %35 %71 -%237 = OpLoad %15 %236 -%238 = OpImageQuerySamples %4 %237 -%239 = OpIAdd %4 %235 %238 -OpStore %48 %239 -%240 = OpLoad %4 %48 -%241 = OpAccessChain %230 %35 %72 -%242 = OpLoad %15 %241 -%243 = OpImageQuerySamples %4 %242 -%244 = OpIAdd %4 %240 %243 -OpStore %48 %244 -%245 = OpLoad %25 %54 -%246 = OpAccessChain %79 %31 %66 -%247 = OpLoad %10 %246 -%248 = OpAccessChain %97 %41 %66 -%249 = OpLoad %21 %248 -%250 = OpSampledImage %100 %247 %249 -%251 = OpImageSampleImplicitLod %25 %250 %76 -%252 = OpFAdd %25 %245 %251 -OpStore %54 %252 -%253 = OpLoad %25 %54 -%254 = OpAccessChain %79 %31 %71 -%255 = OpLoad %10 %254 -%256 = OpAccessChain %97 %41 %71 -%257 = OpLoad %21 %256 -%258 = OpSampledImage %100 %255 %257 -%259 = OpImageSampleImplicitLod %25 %258 %76 -%260 = OpFAdd %25 %253 %259 -OpStore %54 %260 -%261 = OpLoad %25 %54 -%262 = OpAccessChain %79 %31 %72 -%263 = OpLoad %10 %262 -%264 = OpAccessChain %97 %41 %72 -%265 = OpLoad %21 %264 -%266 = OpSampledImage %100 %263 %265 -%267 = OpImageSampleImplicitLod %25 %266 %76 -%268 = OpFAdd %25 %261 %267 -OpStore %54 %268 -%269 = OpLoad %25 %54 -%270 = OpAccessChain %79 %31 %66 -%271 = OpLoad %10 %270 -%272 = OpAccessChain %97 %41 %66 -%273 = OpLoad %21 %272 -%274 = OpSampledImage %100 %271 %273 -%275 = OpImageSampleImplicitLod %25 %274 %76 Bias %6 -%276 = OpFAdd %25 %269 %275 -OpStore %54 %276 -%277 = OpLoad %25 %54 -%278 = OpAccessChain %79 %31 %71 -%279 = OpLoad %10 %278 -%280 = OpAccessChain %97 %41 %71 -%281 = OpLoad %21 %280 -%282 = OpSampledImage %100 %279 %281 -%283 = OpImageSampleImplicitLod %25 %282 %76 Bias %6 -%284 = OpFAdd %25 %277 %283 -OpStore %54 %284 -%285 = OpLoad %25 %54 -%286 = OpAccessChain %79 %31 %72 -%287 = OpLoad %10 %286 -%288 = OpAccessChain %97 %41 %72 -%289 = OpLoad %21 %288 -%290 = OpSampledImage %100 %287 %289 -%291 = OpImageSampleImplicitLod %25 %290 %76 Bias %6 -%292 = OpFAdd %25 %285 %291 -OpStore %54 %292 -%293 = OpLoad %7 %52 -%294 = OpAccessChain %121 %37 %66 -%295 = OpLoad %17 %294 -%296 = OpAccessChain %124 %43 %66 -%297 = OpLoad %21 %296 -%298 = OpSampledImage %127 %295 %297 -%299 = OpImageSampleDrefImplicitLod %7 %298 %76 %6 -%300 = OpFAdd %7 %293 %299 -OpStore %52 %300 -%301 = OpLoad %7 %52 -%302 = OpAccessChain %121 %37 %71 -%303 = OpLoad %17 %302 -%304 = OpAccessChain %124 %43 %71 -%305 = OpLoad %21 %304 -%306 = OpSampledImage %127 %303 %305 -%307 = OpImageSampleDrefImplicitLod %7 %306 %76 %6 -%308 = OpFAdd %7 %301 %307 -OpStore %52 %308 -%309 = OpLoad %7 %52 -%310 = OpAccessChain %121 %37 %72 -%311 = OpLoad %17 %310 -%312 = OpAccessChain %124 %43 %72 -%313 = OpLoad %21 %312 -%314 = OpSampledImage %127 %311 %313 -%315 = OpImageSampleDrefImplicitLod %7 %314 %76 %6 -%316 = OpFAdd %7 %309 %315 -OpStore %52 %316 -%317 = OpLoad %7 %52 -%318 = OpAccessChain %121 %37 %66 -%319 = OpLoad %17 %318 -%320 = OpAccessChain %124 %43 %66 -%321 = OpLoad %21 %320 -%322 = OpSampledImage %127 %319 %321 -%323 = OpImageSampleDrefExplicitLod %7 %322 %76 %6 Lod %6 -%324 = OpFAdd %7 %317 %323 -OpStore %52 %324 -%325 = OpLoad %7 %52 -%326 = OpAccessChain %121 %37 %71 -%327 = OpLoad %17 %326 -%328 = OpAccessChain %124 %43 %71 -%329 = OpLoad %21 %328 -%330 = OpSampledImage %127 %327 %329 -%331 = OpImageSampleDrefExplicitLod %7 %330 %76 %6 Lod %6 -%332 = OpFAdd %7 %325 %331 -OpStore %52 %332 -%333 = OpLoad %7 %52 -%334 = OpAccessChain %121 %37 %72 -%335 = OpLoad %17 %334 -%336 = OpAccessChain %124 %43 %72 -%337 = OpLoad %21 %336 -%338 = OpSampledImage %127 %335 %337 -%339 = OpImageSampleDrefExplicitLod %7 %338 %76 %6 Lod %6 -%340 = OpFAdd %7 %333 %339 -OpStore %52 %340 -%341 = OpLoad %25 %54 -%342 = OpAccessChain %79 %31 %66 -%343 = OpLoad %10 %342 -%344 = OpAccessChain %97 %41 %66 -%345 = OpLoad %21 %344 -%346 = OpSampledImage %100 %343 %345 -%347 = OpImageSampleExplicitLod %25 %346 %76 Grad %76 %76 -%348 = OpFAdd %25 %341 %347 -OpStore %54 %348 -%349 = OpLoad %25 %54 -%350 = OpAccessChain %79 %31 %71 -%351 = OpLoad %10 %350 -%352 = OpAccessChain %97 %41 %71 -%353 = OpLoad %21 %352 -%354 = OpSampledImage %100 %351 %353 -%355 = OpImageSampleExplicitLod %25 %354 %76 Grad %76 %76 -%356 = OpFAdd %25 %349 %355 -OpStore %54 %356 -%357 = OpLoad %25 %54 -%358 = OpAccessChain %79 %31 %72 -%359 = OpLoad %10 %358 -%360 = OpAccessChain %97 %41 %72 -%361 = OpLoad %21 %360 -%362 = OpSampledImage %100 %359 %361 -%363 = OpImageSampleExplicitLod %25 %362 %76 Grad %76 %76 -%364 = OpFAdd %25 %357 %363 -OpStore %54 %364 -%365 = OpLoad %25 %54 -%366 = OpAccessChain %79 %31 %66 -%367 = OpLoad %10 %366 -%368 = OpAccessChain %97 %41 %66 -%369 = OpLoad %21 %368 -%370 = OpSampledImage %100 %367 %369 -%371 = OpImageSampleExplicitLod %25 %370 %76 Lod %6 -%372 = OpFAdd %25 %365 %371 -OpStore %54 %372 -%373 = OpLoad %25 %54 -%374 = OpAccessChain %79 %31 %71 -%375 = OpLoad %10 %374 -%376 = OpAccessChain %97 %41 %71 -%377 = OpLoad %21 %376 -%378 = OpSampledImage %100 %375 %377 -%379 = OpImageSampleExplicitLod %25 %378 %76 Lod %6 -%380 = OpFAdd %25 %373 %379 -OpStore %54 %380 -%381 = OpLoad %25 %54 -%382 = OpAccessChain %79 %31 %72 -%383 = OpLoad %10 %382 -%384 = OpAccessChain %97 %41 %72 -%385 = OpLoad %21 %384 -%386 = OpSampledImage %100 %383 %385 -%387 = OpImageSampleExplicitLod %25 %386 %76 Lod %6 -%388 = OpFAdd %25 %381 %387 -OpStore %54 %388 -%390 = OpAccessChain %389 %39 %66 -%391 = OpLoad %19 %390 -%392 = OpLoad %25 %54 -%393 = OpImageQuerySize %26 %391 -%394 = OpULessThan %157 %77 %393 -%395 = OpAll %150 %394 -OpSelectionMerge %396 None -OpBranchConditional %395 %397 %396 -%397 = OpLabel -OpImageWrite %391 %77 %392 -OpBranch %396 -%396 = OpLabel -%398 = OpAccessChain %389 %39 %71 -%399 = OpLoad %19 %398 -%400 = OpLoad %25 %54 -%401 = OpImageQuerySize %26 %399 -%402 = OpULessThan %157 %77 %401 -%403 = OpAll %150 %402 -OpSelectionMerge %404 None -OpBranchConditional %403 %405 %404 -%405 = OpLabel -OpImageWrite %399 %77 %400 -OpBranch %404 -%404 = OpLabel -%406 = OpAccessChain %389 %39 %72 -%407 = OpLoad %19 %406 -%408 = OpLoad %25 %54 -%409 = OpImageQuerySize %26 %407 -%410 = OpULessThan %157 %77 %409 -%411 = OpAll %150 %410 -OpSelectionMerge %412 None -OpBranchConditional %411 %413 %412 -%413 = OpLabel -OpImageWrite %407 %77 %408 -OpBranch %412 -%412 = OpLabel -%414 = OpLoad %26 %50 -%415 = OpLoad %4 %48 -%416 = OpCompositeConstruct %26 %415 %415 -%417 = OpIAdd %26 %414 %416 -%418 = OpConvertSToF %75 %417 -%419 = OpLoad %25 %54 -%420 = OpCompositeExtract %7 %418 0 -%421 = OpCompositeExtract %7 %418 1 -%422 = OpCompositeExtract %7 %418 0 -%423 = OpCompositeExtract %7 %418 1 -%424 = OpCompositeConstruct %25 %420 %421 %422 %423 -%425 = OpFAdd %25 %419 %424 -%426 = OpLoad %7 %52 -%427 = OpCompositeConstruct %25 %426 %426 %426 %426 -%428 = OpFAdd %25 %425 %427 -OpStore %61 %428 +%53 = OpVariable %54 Function %6 +%62 = OpLoad %8 %60 +%59 = OpCompositeConstruct %24 %62 +%69 = OpAccessChain %67 %45 %68 +OpBranch %70 +%70 = OpLabel +%72 = OpAccessChain %71 %69 %68 +%73 = OpLoad %8 %72 +%74 = OpCompositeExtract %8 %59 0 +%75 = OpCompositeConstruct %26 %5 %5 +OpStore %50 %75 +%76 = OpCompositeConstruct %25 %6 %6 %6 %6 +OpStore %55 %76 +%78 = OpCompositeConstruct %77 %6 %6 +%79 = OpCompositeConstruct %26 %5 %5 +%80 = OpLoad %26 %50 +%82 = OpAccessChain %81 %27 %68 +%83 = OpLoad %10 %82 +%84 = OpImageQuerySizeLod %26 %83 %68 +%85 = OpIAdd %26 %80 %84 +OpStore %50 %85 +%86 = OpLoad %26 %50 +%87 = OpAccessChain %81 %27 %73 +%88 = OpLoad %10 %87 +%89 = OpImageQuerySizeLod %26 %88 %68 +%90 = OpIAdd %26 %86 %89 +OpStore %50 %90 +%91 = OpLoad %26 %50 +%92 = OpAccessChain %81 %27 %74 +%93 = OpLoad %10 %92 +%94 = OpImageQuerySizeLod %26 %93 %68 +%95 = OpIAdd %26 %91 %94 +OpStore %50 %95 +%96 = OpLoad %25 %55 +%97 = OpAccessChain %81 %31 %68 +%98 = OpLoad %10 %97 +%100 = OpAccessChain %99 %41 %68 +%101 = OpLoad %21 %100 +%103 = OpSampledImage %102 %98 %101 +%104 = OpImageGather %25 %103 %78 %68 +%105 = OpFAdd %25 %96 %104 +OpStore %55 %105 +%106 = OpLoad %25 %55 +%107 = OpAccessChain %81 %31 %73 +%108 = OpLoad %10 %107 +%109 = OpAccessChain %99 %41 %73 +%110 = OpLoad %21 %109 +%111 = OpSampledImage %102 %108 %110 +%112 = OpImageGather %25 %111 %78 %68 +%113 = OpFAdd %25 %106 %112 +OpStore %55 %113 +%114 = OpLoad %25 %55 +%115 = OpAccessChain %81 %31 %74 +%116 = OpLoad %10 %115 +%117 = OpAccessChain %99 %41 %74 +%118 = OpLoad %21 %117 +%119 = OpSampledImage %102 %116 %118 +%120 = OpImageGather %25 %119 %78 %68 +%121 = OpFAdd %25 %114 %120 +OpStore %55 %121 +%122 = OpLoad %25 %55 +%124 = OpAccessChain %123 %37 %68 +%125 = OpLoad %17 %124 +%127 = OpAccessChain %126 %43 %68 +%128 = OpLoad %21 %127 +%130 = OpSampledImage %129 %125 %128 +%131 = OpImageDrefGather %25 %130 %78 %6 +%132 = OpFAdd %25 %122 %131 +OpStore %55 %132 +%133 = OpLoad %25 %55 +%134 = OpAccessChain %123 %37 %73 +%135 = OpLoad %17 %134 +%136 = OpAccessChain %126 %43 %73 +%137 = OpLoad %21 %136 +%138 = OpSampledImage %129 %135 %137 +%139 = OpImageDrefGather %25 %138 %78 %6 +%140 = OpFAdd %25 %133 %139 +OpStore %55 %140 +%141 = OpLoad %25 %55 +%142 = OpAccessChain %123 %37 %74 +%143 = OpLoad %17 %142 +%144 = OpAccessChain %126 %43 %74 +%145 = OpLoad %21 %144 +%146 = OpSampledImage %129 %143 %145 +%147 = OpImageDrefGather %25 %146 %78 %6 +%148 = OpFAdd %25 %141 %147 +OpStore %55 %148 +%149 = OpLoad %25 %55 +%150 = OpAccessChain %81 %27 %68 +%151 = OpLoad %10 %150 +%154 = OpImageQueryLevels %4 %151 +%155 = OpULessThan %152 %5 %154 +OpSelectionMerge %156 None +OpBranchConditional %155 %157 %156 +%157 = OpLabel +%158 = OpImageQuerySizeLod %26 %151 %5 +%160 = OpULessThan %159 %79 %158 +%161 = OpAll %152 %160 +OpBranchConditional %161 %162 %156 +%162 = OpLabel +%163 = OpImageFetch %25 %151 %79 Lod %5 +OpBranch %156 +%156 = OpLabel +%164 = OpPhi %25 %153 %70 %153 %157 %163 %162 +%165 = OpFAdd %25 %149 %164 +OpStore %55 %165 +%166 = OpLoad %25 %55 +%167 = OpAccessChain %81 %27 %73 +%168 = OpLoad %10 %167 +%170 = OpImageQueryLevels %4 %168 +%171 = OpULessThan %152 %5 %170 +OpSelectionMerge %172 None +OpBranchConditional %171 %173 %172 +%173 = OpLabel +%174 = OpImageQuerySizeLod %26 %168 %5 +%175 = OpULessThan %159 %79 %174 +%176 = OpAll %152 %175 +OpBranchConditional %176 %177 %172 +%177 = OpLabel +%178 = OpImageFetch %25 %168 %79 Lod %5 +OpBranch %172 +%172 = OpLabel +%179 = OpPhi %25 %169 %156 %169 %173 %178 %177 +%180 = OpFAdd %25 %166 %179 +OpStore %55 %180 +%181 = OpLoad %25 %55 +%182 = OpAccessChain %81 %27 %74 +%183 = OpLoad %10 %182 +%185 = OpImageQueryLevels %4 %183 +%186 = OpULessThan %152 %5 %185 +OpSelectionMerge %187 None +OpBranchConditional %186 %188 %187 +%188 = OpLabel +%189 = OpImageQuerySizeLod %26 %183 %5 +%190 = OpULessThan %159 %79 %189 +%191 = OpAll %152 %190 +OpBranchConditional %191 %192 %187 +%192 = OpLabel +%193 = OpImageFetch %25 %183 %79 Lod %5 +OpBranch %187 +%187 = OpLabel +%194 = OpPhi %25 %184 %172 %184 %188 %193 %192 +%195 = OpFAdd %25 %181 %194 +OpStore %55 %195 +%196 = OpLoad %4 %48 +%198 = OpAccessChain %197 %33 %68 +%199 = OpLoad %13 %198 +%201 = OpImageQuerySizeLod %200 %199 %68 +%202 = OpCompositeExtract %4 %201 2 +%203 = OpIAdd %4 %196 %202 +OpStore %48 %203 +%204 = OpLoad %4 %48 +%205 = OpAccessChain %197 %33 %73 +%206 = OpLoad %13 %205 +%207 = OpImageQuerySizeLod %200 %206 %68 +%208 = OpCompositeExtract %4 %207 2 +%209 = OpIAdd %4 %204 %208 +OpStore %48 %209 +%210 = OpLoad %4 %48 +%211 = OpAccessChain %197 %33 %74 +%212 = OpLoad %13 %211 +%213 = OpImageQuerySizeLod %200 %212 %68 +%214 = OpCompositeExtract %4 %213 2 +%215 = OpIAdd %4 %210 %214 +OpStore %48 %215 +%216 = OpLoad %4 %48 +%217 = OpAccessChain %81 %31 %68 +%218 = OpLoad %10 %217 +%219 = OpImageQueryLevels %4 %218 +%220 = OpIAdd %4 %216 %219 +OpStore %48 %220 +%221 = OpLoad %4 %48 +%222 = OpAccessChain %81 %31 %73 +%223 = OpLoad %10 %222 +%224 = OpImageQueryLevels %4 %223 +%225 = OpIAdd %4 %221 %224 +OpStore %48 %225 +%226 = OpLoad %4 %48 +%227 = OpAccessChain %81 %31 %74 +%228 = OpLoad %10 %227 +%229 = OpImageQueryLevels %4 %228 +%230 = OpIAdd %4 %226 %229 +OpStore %48 %230 +%231 = OpLoad %4 %48 +%233 = OpAccessChain %232 %35 %68 +%234 = OpLoad %15 %233 +%235 = OpImageQuerySamples %4 %234 +%236 = OpIAdd %4 %231 %235 +OpStore %48 %236 +%237 = OpLoad %4 %48 +%238 = OpAccessChain %232 %35 %73 +%239 = OpLoad %15 %238 +%240 = OpImageQuerySamples %4 %239 +%241 = OpIAdd %4 %237 %240 +OpStore %48 %241 +%242 = OpLoad %4 %48 +%243 = OpAccessChain %232 %35 %74 +%244 = OpLoad %15 %243 +%245 = OpImageQuerySamples %4 %244 +%246 = OpIAdd %4 %242 %245 +OpStore %48 %246 +%247 = OpLoad %25 %55 +%248 = OpAccessChain %81 %31 %68 +%249 = OpLoad %10 %248 +%250 = OpAccessChain %99 %41 %68 +%251 = OpLoad %21 %250 +%252 = OpSampledImage %102 %249 %251 +%253 = OpImageSampleImplicitLod %25 %252 %78 +%254 = OpFAdd %25 %247 %253 +OpStore %55 %254 +%255 = OpLoad %25 %55 +%256 = OpAccessChain %81 %31 %73 +%257 = OpLoad %10 %256 +%258 = OpAccessChain %99 %41 %73 +%259 = OpLoad %21 %258 +%260 = OpSampledImage %102 %257 %259 +%261 = OpImageSampleImplicitLod %25 %260 %78 +%262 = OpFAdd %25 %255 %261 +OpStore %55 %262 +%263 = OpLoad %25 %55 +%264 = OpAccessChain %81 %31 %74 +%265 = OpLoad %10 %264 +%266 = OpAccessChain %99 %41 %74 +%267 = OpLoad %21 %266 +%268 = OpSampledImage %102 %265 %267 +%269 = OpImageSampleImplicitLod %25 %268 %78 +%270 = OpFAdd %25 %263 %269 +OpStore %55 %270 +%271 = OpLoad %25 %55 +%272 = OpAccessChain %81 %31 %68 +%273 = OpLoad %10 %272 +%274 = OpAccessChain %99 %41 %68 +%275 = OpLoad %21 %274 +%276 = OpSampledImage %102 %273 %275 +%277 = OpImageSampleImplicitLod %25 %276 %78 Bias %6 +%278 = OpFAdd %25 %271 %277 +OpStore %55 %278 +%279 = OpLoad %25 %55 +%280 = OpAccessChain %81 %31 %73 +%281 = OpLoad %10 %280 +%282 = OpAccessChain %99 %41 %73 +%283 = OpLoad %21 %282 +%284 = OpSampledImage %102 %281 %283 +%285 = OpImageSampleImplicitLod %25 %284 %78 Bias %6 +%286 = OpFAdd %25 %279 %285 +OpStore %55 %286 +%287 = OpLoad %25 %55 +%288 = OpAccessChain %81 %31 %74 +%289 = OpLoad %10 %288 +%290 = OpAccessChain %99 %41 %74 +%291 = OpLoad %21 %290 +%292 = OpSampledImage %102 %289 %291 +%293 = OpImageSampleImplicitLod %25 %292 %78 Bias %6 +%294 = OpFAdd %25 %287 %293 +OpStore %55 %294 +%295 = OpLoad %7 %53 +%296 = OpAccessChain %123 %37 %68 +%297 = OpLoad %17 %296 +%298 = OpAccessChain %126 %43 %68 +%299 = OpLoad %21 %298 +%300 = OpSampledImage %129 %297 %299 +%301 = OpImageSampleDrefImplicitLod %7 %300 %78 %6 +%302 = OpFAdd %7 %295 %301 +OpStore %53 %302 +%303 = OpLoad %7 %53 +%304 = OpAccessChain %123 %37 %73 +%305 = OpLoad %17 %304 +%306 = OpAccessChain %126 %43 %73 +%307 = OpLoad %21 %306 +%308 = OpSampledImage %129 %305 %307 +%309 = OpImageSampleDrefImplicitLod %7 %308 %78 %6 +%310 = OpFAdd %7 %303 %309 +OpStore %53 %310 +%311 = OpLoad %7 %53 +%312 = OpAccessChain %123 %37 %74 +%313 = OpLoad %17 %312 +%314 = OpAccessChain %126 %43 %74 +%315 = OpLoad %21 %314 +%316 = OpSampledImage %129 %313 %315 +%317 = OpImageSampleDrefImplicitLod %7 %316 %78 %6 +%318 = OpFAdd %7 %311 %317 +OpStore %53 %318 +%319 = OpLoad %7 %53 +%320 = OpAccessChain %123 %37 %68 +%321 = OpLoad %17 %320 +%322 = OpAccessChain %126 %43 %68 +%323 = OpLoad %21 %322 +%324 = OpSampledImage %129 %321 %323 +%325 = OpImageSampleDrefExplicitLod %7 %324 %78 %6 Lod %6 +%326 = OpFAdd %7 %319 %325 +OpStore %53 %326 +%327 = OpLoad %7 %53 +%328 = OpAccessChain %123 %37 %73 +%329 = OpLoad %17 %328 +%330 = OpAccessChain %126 %43 %73 +%331 = OpLoad %21 %330 +%332 = OpSampledImage %129 %329 %331 +%333 = OpImageSampleDrefExplicitLod %7 %332 %78 %6 Lod %6 +%334 = OpFAdd %7 %327 %333 +OpStore %53 %334 +%335 = OpLoad %7 %53 +%336 = OpAccessChain %123 %37 %74 +%337 = OpLoad %17 %336 +%338 = OpAccessChain %126 %43 %74 +%339 = OpLoad %21 %338 +%340 = OpSampledImage %129 %337 %339 +%341 = OpImageSampleDrefExplicitLod %7 %340 %78 %6 Lod %6 +%342 = OpFAdd %7 %335 %341 +OpStore %53 %342 +%343 = OpLoad %25 %55 +%344 = OpAccessChain %81 %31 %68 +%345 = OpLoad %10 %344 +%346 = OpAccessChain %99 %41 %68 +%347 = OpLoad %21 %346 +%348 = OpSampledImage %102 %345 %347 +%349 = OpImageSampleExplicitLod %25 %348 %78 Grad %78 %78 +%350 = OpFAdd %25 %343 %349 +OpStore %55 %350 +%351 = OpLoad %25 %55 +%352 = OpAccessChain %81 %31 %73 +%353 = OpLoad %10 %352 +%354 = OpAccessChain %99 %41 %73 +%355 = OpLoad %21 %354 +%356 = OpSampledImage %102 %353 %355 +%357 = OpImageSampleExplicitLod %25 %356 %78 Grad %78 %78 +%358 = OpFAdd %25 %351 %357 +OpStore %55 %358 +%359 = OpLoad %25 %55 +%360 = OpAccessChain %81 %31 %74 +%361 = OpLoad %10 %360 +%362 = OpAccessChain %99 %41 %74 +%363 = OpLoad %21 %362 +%364 = OpSampledImage %102 %361 %363 +%365 = OpImageSampleExplicitLod %25 %364 %78 Grad %78 %78 +%366 = OpFAdd %25 %359 %365 +OpStore %55 %366 +%367 = OpLoad %25 %55 +%368 = OpAccessChain %81 %31 %68 +%369 = OpLoad %10 %368 +%370 = OpAccessChain %99 %41 %68 +%371 = OpLoad %21 %370 +%372 = OpSampledImage %102 %369 %371 +%373 = OpImageSampleExplicitLod %25 %372 %78 Lod %6 +%374 = OpFAdd %25 %367 %373 +OpStore %55 %374 +%375 = OpLoad %25 %55 +%376 = OpAccessChain %81 %31 %73 +%377 = OpLoad %10 %376 +%378 = OpAccessChain %99 %41 %73 +%379 = OpLoad %21 %378 +%380 = OpSampledImage %102 %377 %379 +%381 = OpImageSampleExplicitLod %25 %380 %78 Lod %6 +%382 = OpFAdd %25 %375 %381 +OpStore %55 %382 +%383 = OpLoad %25 %55 +%384 = OpAccessChain %81 %31 %74 +%385 = OpLoad %10 %384 +%386 = OpAccessChain %99 %41 %74 +%387 = OpLoad %21 %386 +%388 = OpSampledImage %102 %385 %387 +%389 = OpImageSampleExplicitLod %25 %388 %78 Lod %6 +%390 = OpFAdd %25 %383 %389 +OpStore %55 %390 +%392 = OpAccessChain %391 %39 %68 +%393 = OpLoad %19 %392 +%394 = OpLoad %25 %55 +%395 = OpImageQuerySize %26 %393 +%396 = OpULessThan %159 %79 %395 +%397 = OpAll %152 %396 +OpSelectionMerge %398 None +OpBranchConditional %397 %399 %398 +%399 = OpLabel +OpImageWrite %393 %79 %394 +OpBranch %398 +%398 = OpLabel +%400 = OpAccessChain %391 %39 %73 +%401 = OpLoad %19 %400 +%402 = OpLoad %25 %55 +%403 = OpImageQuerySize %26 %401 +%404 = OpULessThan %159 %79 %403 +%405 = OpAll %152 %404 +OpSelectionMerge %406 None +OpBranchConditional %405 %407 %406 +%407 = OpLabel +OpImageWrite %401 %79 %402 +OpBranch %406 +%406 = OpLabel +%408 = OpAccessChain %391 %39 %74 +%409 = OpLoad %19 %408 +%410 = OpLoad %25 %55 +%411 = OpImageQuerySize %26 %409 +%412 = OpULessThan %159 %79 %411 +%413 = OpAll %152 %412 +OpSelectionMerge %414 None +OpBranchConditional %413 %415 %414 +%415 = OpLabel +OpImageWrite %409 %79 %410 +OpBranch %414 +%414 = OpLabel +%416 = OpLoad %26 %50 +%417 = OpLoad %4 %48 +%418 = OpCompositeConstruct %26 %417 %417 +%419 = OpIAdd %26 %416 %418 +%420 = OpConvertSToF %77 %419 +%421 = OpLoad %25 %55 +%422 = OpCompositeExtract %7 %420 0 +%423 = OpCompositeExtract %7 %420 1 +%424 = OpCompositeExtract %7 %420 0 +%425 = OpCompositeExtract %7 %420 1 +%426 = OpCompositeConstruct %25 %422 %423 %424 %425 +%427 = OpFAdd %25 %421 %426 +%428 = OpLoad %7 %53 +%429 = OpCompositeConstruct %25 %428 %428 %428 %428 +%430 = OpFAdd %25 %427 %429 +OpStore %63 %430 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm index ddd71d0b7..c705d8276 100644 --- a/tests/out/spv/bits.spvasm +++ b/tests/out/spv/bits.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 151 +; Bound: 159 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %40 "main" -OpExecutionMode %40 LocalSize 1 1 1 +OpEntryPoint GLCompute %48 "main" +OpExecutionMode %48 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 0 @@ -26,190 +26,198 @@ OpExecutionMode %40 LocalSize 1 1 1 %18 = OpTypeVector %8 4 %20 = OpTypePointer Function %4 %22 = OpTypePointer Function %11 -%24 = OpTypePointer Function %12 -%26 = OpTypePointer Function %13 -%28 = OpTypePointer Function %6 -%30 = OpTypePointer Function %14 -%32 = OpTypePointer Function %15 -%34 = OpTypePointer Function %16 -%36 = OpTypePointer Function %17 -%38 = OpTypePointer Function %18 -%41 = OpTypeFunction %2 -%40 = OpFunction %2 None %41 -%39 = OpLabel -%37 = OpVariable %38 Function -%31 = OpVariable %32 Function -%25 = OpVariable %26 Function +%23 = OpConstantNull %11 +%25 = OpTypePointer Function %12 +%26 = OpConstantNull %12 +%28 = OpTypePointer Function %13 +%29 = OpConstantNull %13 +%31 = OpTypePointer Function %6 +%33 = OpTypePointer Function %14 +%34 = OpConstantNull %14 +%36 = OpTypePointer Function %15 +%37 = OpConstantNull %15 +%39 = OpTypePointer Function %16 +%40 = OpConstantNull %16 +%42 = OpTypePointer Function %17 +%43 = OpConstantNull %17 +%45 = OpTypePointer Function %18 +%46 = OpConstantNull %18 +%49 = OpTypeFunction %2 +%48 = OpFunction %2 None %49 +%47 = OpLabel +%44 = OpVariable %45 Function %46 +%35 = OpVariable %36 Function %37 +%27 = OpVariable %28 Function %29 %19 = OpVariable %20 Function %3 -%33 = OpVariable %34 Function -%27 = OpVariable %28 Function %5 -%21 = OpVariable %22 Function -%35 = OpVariable %36 Function -%29 = OpVariable %30 Function -%23 = OpVariable %24 Function -OpBranch %42 -%42 = OpLabel -%43 = OpCompositeConstruct %11 %3 %3 -OpStore %21 %43 -%44 = OpCompositeConstruct %12 %3 %3 %3 -OpStore %23 %44 -%45 = OpCompositeConstruct %13 %3 %3 %3 %3 -OpStore %25 %45 -%46 = OpCompositeConstruct %14 %5 %5 -OpStore %29 %46 -%47 = OpCompositeConstruct %15 %5 %5 %5 -OpStore %31 %47 -%48 = OpCompositeConstruct %16 %5 %5 %5 %5 -OpStore %33 %48 -%49 = OpCompositeConstruct %17 %7 %7 -OpStore %35 %49 -%50 = OpCompositeConstruct %18 %7 %7 %7 %7 -OpStore %37 %50 -%51 = OpLoad %18 %37 -%52 = OpExtInst %6 %1 PackSnorm4x8 %51 -OpStore %27 %52 -%53 = OpLoad %18 %37 -%54 = OpExtInst %6 %1 PackUnorm4x8 %53 -OpStore %27 %54 -%55 = OpLoad %17 %35 -%56 = OpExtInst %6 %1 PackSnorm2x16 %55 -OpStore %27 %56 -%57 = OpLoad %17 %35 -%58 = OpExtInst %6 %1 PackUnorm2x16 %57 -OpStore %27 %58 -%59 = OpLoad %17 %35 -%60 = OpExtInst %6 %1 PackHalf2x16 %59 -OpStore %27 %60 -%61 = OpLoad %6 %27 -%62 = OpExtInst %18 %1 UnpackSnorm4x8 %61 -OpStore %37 %62 -%63 = OpLoad %6 %27 -%64 = OpExtInst %18 %1 UnpackUnorm4x8 %63 -OpStore %37 %64 -%65 = OpLoad %6 %27 -%66 = OpExtInst %17 %1 UnpackSnorm2x16 %65 -OpStore %35 %66 -%67 = OpLoad %6 %27 -%68 = OpExtInst %17 %1 UnpackUnorm2x16 %67 -OpStore %35 %68 -%69 = OpLoad %6 %27 -%70 = OpExtInst %17 %1 UnpackHalf2x16 %69 -OpStore %35 %70 -%71 = OpLoad %4 %19 -%72 = OpLoad %4 %19 -%73 = OpBitFieldInsert %4 %71 %72 %9 %10 -OpStore %19 %73 -%74 = OpLoad %11 %21 -%75 = OpLoad %11 %21 -%76 = OpBitFieldInsert %11 %74 %75 %9 %10 -OpStore %21 %76 -%77 = OpLoad %12 %23 -%78 = OpLoad %12 %23 -%79 = OpBitFieldInsert %12 %77 %78 %9 %10 -OpStore %23 %79 -%80 = OpLoad %13 %25 -%81 = OpLoad %13 %25 -%82 = OpBitFieldInsert %13 %80 %81 %9 %10 -OpStore %25 %82 -%83 = OpLoad %6 %27 -%84 = OpLoad %6 %27 -%85 = OpBitFieldInsert %6 %83 %84 %9 %10 -OpStore %27 %85 -%86 = OpLoad %14 %29 -%87 = OpLoad %14 %29 -%88 = OpBitFieldInsert %14 %86 %87 %9 %10 -OpStore %29 %88 -%89 = OpLoad %15 %31 -%90 = OpLoad %15 %31 -%91 = OpBitFieldInsert %15 %89 %90 %9 %10 -OpStore %31 %91 -%92 = OpLoad %16 %33 -%93 = OpLoad %16 %33 -%94 = OpBitFieldInsert %16 %92 %93 %9 %10 -OpStore %33 %94 -%95 = OpLoad %4 %19 -%96 = OpBitFieldSExtract %4 %95 %9 %10 -OpStore %19 %96 -%97 = OpLoad %11 %21 -%98 = OpBitFieldSExtract %11 %97 %9 %10 -OpStore %21 %98 -%99 = OpLoad %12 %23 -%100 = OpBitFieldSExtract %12 %99 %9 %10 -OpStore %23 %100 -%101 = OpLoad %13 %25 -%102 = OpBitFieldSExtract %13 %101 %9 %10 -OpStore %25 %102 -%103 = OpLoad %6 %27 -%104 = OpBitFieldUExtract %6 %103 %9 %10 -OpStore %27 %104 -%105 = OpLoad %14 %29 -%106 = OpBitFieldUExtract %14 %105 %9 %10 -OpStore %29 %106 -%107 = OpLoad %15 %31 -%108 = OpBitFieldUExtract %15 %107 %9 %10 -OpStore %31 %108 -%109 = OpLoad %16 %33 -%110 = OpBitFieldUExtract %16 %109 %9 %10 -OpStore %33 %110 -%111 = OpLoad %4 %19 -%112 = OpExtInst %4 %1 FindILsb %111 -OpStore %19 %112 -%113 = OpLoad %14 %29 -%114 = OpExtInst %14 %1 FindILsb %113 -OpStore %29 %114 -%115 = OpLoad %12 %23 -%116 = OpExtInst %12 %1 FindSMsb %115 -OpStore %23 %116 -%117 = OpLoad %6 %27 -%118 = OpExtInst %6 %1 FindUMsb %117 -OpStore %27 %118 +%38 = OpVariable %39 Function %40 +%30 = OpVariable %31 Function %5 +%21 = OpVariable %22 Function %23 +%41 = OpVariable %42 Function %43 +%32 = OpVariable %33 Function %34 +%24 = OpVariable %25 Function %26 +OpBranch %50 +%50 = OpLabel +%51 = OpCompositeConstruct %11 %3 %3 +OpStore %21 %51 +%52 = OpCompositeConstruct %12 %3 %3 %3 +OpStore %24 %52 +%53 = OpCompositeConstruct %13 %3 %3 %3 %3 +OpStore %27 %53 +%54 = OpCompositeConstruct %14 %5 %5 +OpStore %32 %54 +%55 = OpCompositeConstruct %15 %5 %5 %5 +OpStore %35 %55 +%56 = OpCompositeConstruct %16 %5 %5 %5 %5 +OpStore %38 %56 +%57 = OpCompositeConstruct %17 %7 %7 +OpStore %41 %57 +%58 = OpCompositeConstruct %18 %7 %7 %7 %7 +OpStore %44 %58 +%59 = OpLoad %18 %44 +%60 = OpExtInst %6 %1 PackSnorm4x8 %59 +OpStore %30 %60 +%61 = OpLoad %18 %44 +%62 = OpExtInst %6 %1 PackUnorm4x8 %61 +OpStore %30 %62 +%63 = OpLoad %17 %41 +%64 = OpExtInst %6 %1 PackSnorm2x16 %63 +OpStore %30 %64 +%65 = OpLoad %17 %41 +%66 = OpExtInst %6 %1 PackUnorm2x16 %65 +OpStore %30 %66 +%67 = OpLoad %17 %41 +%68 = OpExtInst %6 %1 PackHalf2x16 %67 +OpStore %30 %68 +%69 = OpLoad %6 %30 +%70 = OpExtInst %18 %1 UnpackSnorm4x8 %69 +OpStore %44 %70 +%71 = OpLoad %6 %30 +%72 = OpExtInst %18 %1 UnpackUnorm4x8 %71 +OpStore %44 %72 +%73 = OpLoad %6 %30 +%74 = OpExtInst %17 %1 UnpackSnorm2x16 %73 +OpStore %41 %74 +%75 = OpLoad %6 %30 +%76 = OpExtInst %17 %1 UnpackUnorm2x16 %75 +OpStore %41 %76 +%77 = OpLoad %6 %30 +%78 = OpExtInst %17 %1 UnpackHalf2x16 %77 +OpStore %41 %78 +%79 = OpLoad %4 %19 +%80 = OpLoad %4 %19 +%81 = OpBitFieldInsert %4 %79 %80 %9 %10 +OpStore %19 %81 +%82 = OpLoad %11 %21 +%83 = OpLoad %11 %21 +%84 = OpBitFieldInsert %11 %82 %83 %9 %10 +OpStore %21 %84 +%85 = OpLoad %12 %24 +%86 = OpLoad %12 %24 +%87 = OpBitFieldInsert %12 %85 %86 %9 %10 +OpStore %24 %87 +%88 = OpLoad %13 %27 +%89 = OpLoad %13 %27 +%90 = OpBitFieldInsert %13 %88 %89 %9 %10 +OpStore %27 %90 +%91 = OpLoad %6 %30 +%92 = OpLoad %6 %30 +%93 = OpBitFieldInsert %6 %91 %92 %9 %10 +OpStore %30 %93 +%94 = OpLoad %14 %32 +%95 = OpLoad %14 %32 +%96 = OpBitFieldInsert %14 %94 %95 %9 %10 +OpStore %32 %96 +%97 = OpLoad %15 %35 +%98 = OpLoad %15 %35 +%99 = OpBitFieldInsert %15 %97 %98 %9 %10 +OpStore %35 %99 +%100 = OpLoad %16 %38 +%101 = OpLoad %16 %38 +%102 = OpBitFieldInsert %16 %100 %101 %9 %10 +OpStore %38 %102 +%103 = OpLoad %4 %19 +%104 = OpBitFieldSExtract %4 %103 %9 %10 +OpStore %19 %104 +%105 = OpLoad %11 %21 +%106 = OpBitFieldSExtract %11 %105 %9 %10 +OpStore %21 %106 +%107 = OpLoad %12 %24 +%108 = OpBitFieldSExtract %12 %107 %9 %10 +OpStore %24 %108 +%109 = OpLoad %13 %27 +%110 = OpBitFieldSExtract %13 %109 %9 %10 +OpStore %27 %110 +%111 = OpLoad %6 %30 +%112 = OpBitFieldUExtract %6 %111 %9 %10 +OpStore %30 %112 +%113 = OpLoad %14 %32 +%114 = OpBitFieldUExtract %14 %113 %9 %10 +OpStore %32 %114 +%115 = OpLoad %15 %35 +%116 = OpBitFieldUExtract %15 %115 %9 %10 +OpStore %35 %116 +%117 = OpLoad %16 %38 +%118 = OpBitFieldUExtract %16 %117 %9 %10 +OpStore %38 %118 %119 = OpLoad %4 %19 -%120 = OpBitCount %4 %119 +%120 = OpExtInst %4 %1 FindILsb %119 OpStore %19 %120 -%121 = OpLoad %11 %21 -%122 = OpBitCount %11 %121 -OpStore %21 %122 -%123 = OpLoad %12 %23 -%124 = OpBitCount %12 %123 -OpStore %23 %124 -%125 = OpLoad %13 %25 -%126 = OpBitCount %13 %125 -OpStore %25 %126 -%127 = OpLoad %6 %27 -%128 = OpBitCount %6 %127 -OpStore %27 %128 -%129 = OpLoad %14 %29 -%130 = OpBitCount %14 %129 -OpStore %29 %130 -%131 = OpLoad %15 %31 -%132 = OpBitCount %15 %131 -OpStore %31 %132 -%133 = OpLoad %16 %33 -%134 = OpBitCount %16 %133 -OpStore %33 %134 -%135 = OpLoad %4 %19 -%136 = OpBitReverse %4 %135 -OpStore %19 %136 -%137 = OpLoad %11 %21 -%138 = OpBitReverse %11 %137 -OpStore %21 %138 -%139 = OpLoad %12 %23 -%140 = OpBitReverse %12 %139 -OpStore %23 %140 -%141 = OpLoad %13 %25 -%142 = OpBitReverse %13 %141 -OpStore %25 %142 -%143 = OpLoad %6 %27 -%144 = OpBitReverse %6 %143 -OpStore %27 %144 -%145 = OpLoad %14 %29 -%146 = OpBitReverse %14 %145 -OpStore %29 %146 -%147 = OpLoad %15 %31 -%148 = OpBitReverse %15 %147 -OpStore %31 %148 -%149 = OpLoad %16 %33 -%150 = OpBitReverse %16 %149 -OpStore %33 %150 +%121 = OpLoad %14 %32 +%122 = OpExtInst %14 %1 FindILsb %121 +OpStore %32 %122 +%123 = OpLoad %12 %24 +%124 = OpExtInst %12 %1 FindSMsb %123 +OpStore %24 %124 +%125 = OpLoad %6 %30 +%126 = OpExtInst %6 %1 FindUMsb %125 +OpStore %30 %126 +%127 = OpLoad %4 %19 +%128 = OpBitCount %4 %127 +OpStore %19 %128 +%129 = OpLoad %11 %21 +%130 = OpBitCount %11 %129 +OpStore %21 %130 +%131 = OpLoad %12 %24 +%132 = OpBitCount %12 %131 +OpStore %24 %132 +%133 = OpLoad %13 %27 +%134 = OpBitCount %13 %133 +OpStore %27 %134 +%135 = OpLoad %6 %30 +%136 = OpBitCount %6 %135 +OpStore %30 %136 +%137 = OpLoad %14 %32 +%138 = OpBitCount %14 %137 +OpStore %32 %138 +%139 = OpLoad %15 %35 +%140 = OpBitCount %15 %139 +OpStore %35 %140 +%141 = OpLoad %16 %38 +%142 = OpBitCount %16 %141 +OpStore %38 %142 +%143 = OpLoad %4 %19 +%144 = OpBitReverse %4 %143 +OpStore %19 %144 +%145 = OpLoad %11 %21 +%146 = OpBitReverse %11 %145 +OpStore %21 %146 +%147 = OpLoad %12 %24 +%148 = OpBitReverse %12 %147 +OpStore %24 %148 +%149 = OpLoad %13 %27 +%150 = OpBitReverse %13 %149 +OpStore %27 %150 +%151 = OpLoad %6 %30 +%152 = OpBitReverse %6 %151 +OpStore %30 %152 +%153 = OpLoad %14 %32 +%154 = OpBitReverse %14 %153 +OpStore %32 %154 +%155 = OpLoad %15 %35 +%156 = OpBitReverse %15 %155 +OpStore %35 %156 +%157 = OpLoad %16 %38 +%158 = OpBitReverse %16 %157 +OpStore %38 %158 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index c8f589488..887cdb6ad 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 206 +; Bound: 213 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %44 "main" %41 -OpExecutionMode %44 LocalSize 64 1 1 +OpEntryPoint GLCompute %51 "main" %48 +OpExecutionMode %51 LocalSize 64 1 1 OpSource GLSL 450 OpName %3 "NUM_PARTICLES" OpMemberName %16 0 "pos" @@ -27,17 +27,17 @@ OpName %21 "params" OpName %24 "particlesSrc" OpName %26 "particlesDst" OpName %27 "vPos" -OpName %29 "vVel" -OpName %30 "cMass" -OpName %31 "cVel" -OpName %32 "colVel" -OpName %33 "cMassCount" -OpName %35 "cVelCount" -OpName %36 "pos" -OpName %37 "vel" -OpName %38 "i" -OpName %41 "global_invocation_id" -OpName %44 "main" +OpName %30 "vVel" +OpName %32 "cMass" +OpName %34 "cVel" +OpName %36 "colVel" +OpName %38 "cMassCount" +OpName %40 "cVelCount" +OpName %41 "pos" +OpName %43 "vel" +OpName %45 "i" +OpName %48 "global_invocation_id" +OpName %51 "main" OpMemberDecorate %16 0 Offset 0 OpMemberDecorate %16 1 Offset 8 OpMemberDecorate %17 0 Offset 0 @@ -60,7 +60,7 @@ OpDecorate %19 Block OpDecorate %26 DescriptorSet 0 OpDecorate %26 Binding 2 OpDecorate %19 Block -OpDecorate %41 BuiltIn GlobalInvocationId +OpDecorate %48 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 1500 @@ -87,249 +87,256 @@ OpDecorate %41 BuiltIn GlobalInvocationId %24 = OpVariable %25 StorageBuffer %26 = OpVariable %25 StorageBuffer %28 = OpTypePointer Function %15 -%34 = OpTypePointer Function %8 -%39 = OpTypePointer Function %4 -%42 = OpTypePointer Input %20 -%41 = OpVariable %42 Input -%45 = OpTypeFunction %2 -%46 = OpTypePointer Uniform %17 -%50 = OpTypeBool -%54 = OpTypePointer StorageBuffer %18 -%55 = OpTypePointer StorageBuffer %16 -%56 = OpTypePointer StorageBuffer %15 -%85 = OpTypePointer Uniform %6 -%99 = OpConstant %4 2 -%113 = OpConstant %4 3 -%148 = OpConstant %4 4 -%154 = OpConstant %4 5 -%160 = OpConstant %4 6 -%177 = OpTypePointer Function %6 -%44 = OpFunction %2 None %45 -%40 = OpLabel -%38 = OpVariable %39 Function %9 -%35 = OpVariable %34 Function %7 -%31 = OpVariable %28 Function -%27 = OpVariable %28 Function -%36 = OpVariable %28 Function -%32 = OpVariable %28 Function -%29 = OpVariable %28 Function -%37 = OpVariable %28 Function -%33 = OpVariable %34 Function %7 -%30 = OpVariable %28 Function -%43 = OpLoad %20 %41 -%47 = OpAccessChain %46 %21 %9 -OpBranch %48 -%48 = OpLabel -%49 = OpCompositeExtract %4 %43 0 -%51 = OpUGreaterThanEqual %50 %49 %3 -OpSelectionMerge %52 None -OpBranchConditional %51 %53 %52 -%53 = OpLabel +%29 = OpConstantNull %15 +%31 = OpConstantNull %15 +%33 = OpConstantNull %15 +%35 = OpConstantNull %15 +%37 = OpConstantNull %15 +%39 = OpTypePointer Function %8 +%42 = OpConstantNull %15 +%44 = OpConstantNull %15 +%46 = OpTypePointer Function %4 +%49 = OpTypePointer Input %20 +%48 = OpVariable %49 Input +%52 = OpTypeFunction %2 +%53 = OpTypePointer Uniform %17 +%57 = OpTypeBool +%61 = OpTypePointer StorageBuffer %18 +%62 = OpTypePointer StorageBuffer %16 +%63 = OpTypePointer StorageBuffer %15 +%92 = OpTypePointer Uniform %6 +%106 = OpConstant %4 2 +%120 = OpConstant %4 3 +%155 = OpConstant %4 4 +%161 = OpConstant %4 5 +%167 = OpConstant %4 6 +%184 = OpTypePointer Function %6 +%51 = OpFunction %2 None %52 +%47 = OpLabel +%45 = OpVariable %46 Function %9 +%40 = OpVariable %39 Function %7 +%34 = OpVariable %28 Function %35 +%27 = OpVariable %28 Function %29 +%41 = OpVariable %28 Function %42 +%36 = OpVariable %28 Function %37 +%30 = OpVariable %28 Function %31 +%43 = OpVariable %28 Function %44 +%38 = OpVariable %39 Function %7 +%32 = OpVariable %28 Function %33 +%50 = OpLoad %20 %48 +%54 = OpAccessChain %53 %21 %9 +OpBranch %55 +%55 = OpLabel +%56 = OpCompositeExtract %4 %50 0 +%58 = OpUGreaterThanEqual %57 %56 %3 +OpSelectionMerge %59 None +OpBranchConditional %58 %60 %59 +%60 = OpLabel OpReturn -%52 = OpLabel -%57 = OpAccessChain %56 %24 %9 %49 %9 -%58 = OpLoad %15 %57 -OpStore %27 %58 -%59 = OpAccessChain %56 %24 %9 %49 %11 -%60 = OpLoad %15 %59 -OpStore %29 %60 -%61 = OpCompositeConstruct %15 %5 %5 -OpStore %30 %61 -%62 = OpCompositeConstruct %15 %5 %5 -OpStore %31 %62 -%63 = OpCompositeConstruct %15 %5 %5 -OpStore %32 %63 -OpBranch %64 -%64 = OpLabel -OpLoopMerge %65 %67 None -OpBranch %66 -%66 = OpLabel -%68 = OpLoad %4 %38 -%69 = OpUGreaterThanEqual %50 %68 %3 -OpSelectionMerge %70 None -OpBranchConditional %69 %71 %70 +%59 = OpLabel +%64 = OpAccessChain %63 %24 %9 %56 %9 +%65 = OpLoad %15 %64 +OpStore %27 %65 +%66 = OpAccessChain %63 %24 %9 %56 %11 +%67 = OpLoad %15 %66 +OpStore %30 %67 +%68 = OpCompositeConstruct %15 %5 %5 +OpStore %32 %68 +%69 = OpCompositeConstruct %15 %5 %5 +OpStore %34 %69 +%70 = OpCompositeConstruct %15 %5 %5 +OpStore %36 %70 +OpBranch %71 %71 = OpLabel -OpBranch %65 -%70 = OpLabel -%72 = OpLoad %4 %38 -%73 = OpIEqual %50 %72 %49 -OpSelectionMerge %74 None -OpBranchConditional %73 %75 %74 -%75 = OpLabel -OpBranch %67 +OpLoopMerge %72 %74 None +OpBranch %73 +%73 = OpLabel +%75 = OpLoad %4 %45 +%76 = OpUGreaterThanEqual %57 %75 %3 +OpSelectionMerge %77 None +OpBranchConditional %76 %78 %77 +%78 = OpLabel +OpBranch %72 +%77 = OpLabel +%79 = OpLoad %4 %45 +%80 = OpIEqual %57 %79 %56 +OpSelectionMerge %81 None +OpBranchConditional %80 %82 %81 +%82 = OpLabel +OpBranch %74 +%81 = OpLabel +%83 = OpLoad %4 %45 +%84 = OpAccessChain %63 %24 %9 %83 %9 +%85 = OpLoad %15 %84 +OpStore %41 %85 +%86 = OpLoad %4 %45 +%87 = OpAccessChain %63 %24 %9 %86 %11 +%88 = OpLoad %15 %87 +OpStore %43 %88 +%89 = OpLoad %15 %41 +%90 = OpLoad %15 %27 +%91 = OpExtInst %6 %1 Distance %89 %90 +%93 = OpAccessChain %92 %54 %11 +%94 = OpLoad %6 %93 +%95 = OpFOrdLessThan %57 %91 %94 +OpSelectionMerge %96 None +OpBranchConditional %95 %97 %96 +%97 = OpLabel +%98 = OpLoad %15 %32 +%99 = OpLoad %15 %41 +%100 = OpFAdd %15 %98 %99 +OpStore %32 %100 +%101 = OpLoad %8 %38 +%102 = OpIAdd %8 %101 %10 +OpStore %38 %102 +OpBranch %96 +%96 = OpLabel +%103 = OpLoad %15 %41 +%104 = OpLoad %15 %27 +%105 = OpExtInst %6 %1 Distance %103 %104 +%107 = OpAccessChain %92 %54 %106 +%108 = OpLoad %6 %107 +%109 = OpFOrdLessThan %57 %105 %108 +OpSelectionMerge %110 None +OpBranchConditional %109 %111 %110 +%111 = OpLabel +%112 = OpLoad %15 %36 +%113 = OpLoad %15 %41 +%114 = OpLoad %15 %27 +%115 = OpFSub %15 %113 %114 +%116 = OpFSub %15 %112 %115 +OpStore %36 %116 +OpBranch %110 +%110 = OpLabel +%117 = OpLoad %15 %41 +%118 = OpLoad %15 %27 +%119 = OpExtInst %6 %1 Distance %117 %118 +%121 = OpAccessChain %92 %54 %120 +%122 = OpLoad %6 %121 +%123 = OpFOrdLessThan %57 %119 %122 +OpSelectionMerge %124 None +OpBranchConditional %123 %125 %124 +%125 = OpLabel +%126 = OpLoad %15 %34 +%127 = OpLoad %15 %43 +%128 = OpFAdd %15 %126 %127 +OpStore %34 %128 +%129 = OpLoad %8 %40 +%130 = OpIAdd %8 %129 %10 +OpStore %40 %130 +OpBranch %124 +%124 = OpLabel +OpBranch %74 %74 = OpLabel -%76 = OpLoad %4 %38 -%77 = OpAccessChain %56 %24 %9 %76 %9 -%78 = OpLoad %15 %77 -OpStore %36 %78 -%79 = OpLoad %4 %38 -%80 = OpAccessChain %56 %24 %9 %79 %11 -%81 = OpLoad %15 %80 -OpStore %37 %81 -%82 = OpLoad %15 %36 -%83 = OpLoad %15 %27 -%84 = OpExtInst %6 %1 Distance %82 %83 -%86 = OpAccessChain %85 %47 %11 -%87 = OpLoad %6 %86 -%88 = OpFOrdLessThan %50 %84 %87 -OpSelectionMerge %89 None -OpBranchConditional %88 %90 %89 -%90 = OpLabel -%91 = OpLoad %15 %30 -%92 = OpLoad %15 %36 -%93 = OpFAdd %15 %91 %92 -OpStore %30 %93 -%94 = OpLoad %8 %33 -%95 = OpIAdd %8 %94 %10 -OpStore %33 %95 -OpBranch %89 -%89 = OpLabel -%96 = OpLoad %15 %36 -%97 = OpLoad %15 %27 -%98 = OpExtInst %6 %1 Distance %96 %97 -%100 = OpAccessChain %85 %47 %99 -%101 = OpLoad %6 %100 -%102 = OpFOrdLessThan %50 %98 %101 -OpSelectionMerge %103 None -OpBranchConditional %102 %104 %103 -%104 = OpLabel -%105 = OpLoad %15 %32 -%106 = OpLoad %15 %36 -%107 = OpLoad %15 %27 -%108 = OpFSub %15 %106 %107 -%109 = OpFSub %15 %105 %108 -OpStore %32 %109 -OpBranch %103 -%103 = OpLabel -%110 = OpLoad %15 %36 -%111 = OpLoad %15 %27 -%112 = OpExtInst %6 %1 Distance %110 %111 -%114 = OpAccessChain %85 %47 %113 -%115 = OpLoad %6 %114 -%116 = OpFOrdLessThan %50 %112 %115 -OpSelectionMerge %117 None -OpBranchConditional %116 %118 %117 -%118 = OpLabel -%119 = OpLoad %15 %31 -%120 = OpLoad %15 %37 -%121 = OpFAdd %15 %119 %120 -OpStore %31 %121 -%122 = OpLoad %8 %35 -%123 = OpIAdd %8 %122 %10 -OpStore %35 %123 -OpBranch %117 -%117 = OpLabel -OpBranch %67 -%67 = OpLabel -%124 = OpLoad %4 %38 -%125 = OpIAdd %4 %124 %11 -OpStore %38 %125 -OpBranch %64 -%65 = OpLabel -%126 = OpLoad %8 %33 -%127 = OpSGreaterThan %50 %126 %7 -OpSelectionMerge %128 None -OpBranchConditional %127 %129 %128 -%129 = OpLabel -%130 = OpLoad %15 %30 -%131 = OpLoad %8 %33 -%132 = OpConvertSToF %6 %131 -%133 = OpCompositeConstruct %15 %132 %132 -%134 = OpFDiv %15 %130 %133 -%135 = OpLoad %15 %27 -%136 = OpFSub %15 %134 %135 -OpStore %30 %136 -OpBranch %128 -%128 = OpLabel -%137 = OpLoad %8 %35 -%138 = OpSGreaterThan %50 %137 %7 -OpSelectionMerge %139 None -OpBranchConditional %138 %140 %139 -%140 = OpLabel -%141 = OpLoad %15 %31 -%142 = OpLoad %8 %35 -%143 = OpConvertSToF %6 %142 -%144 = OpCompositeConstruct %15 %143 %143 -%145 = OpFDiv %15 %141 %144 -OpStore %31 %145 -OpBranch %139 -%139 = OpLabel -%146 = OpLoad %15 %29 -%147 = OpLoad %15 %30 -%149 = OpAccessChain %85 %47 %148 -%150 = OpLoad %6 %149 -%151 = OpVectorTimesScalar %15 %147 %150 -%152 = OpFAdd %15 %146 %151 -%153 = OpLoad %15 %32 -%155 = OpAccessChain %85 %47 %154 -%156 = OpLoad %6 %155 -%157 = OpVectorTimesScalar %15 %153 %156 -%158 = OpFAdd %15 %152 %157 -%159 = OpLoad %15 %31 -%161 = OpAccessChain %85 %47 %160 -%162 = OpLoad %6 %161 -%163 = OpVectorTimesScalar %15 %159 %162 -%164 = OpFAdd %15 %158 %163 -OpStore %29 %164 -%165 = OpLoad %15 %29 -%166 = OpExtInst %15 %1 Normalize %165 -%167 = OpLoad %15 %29 -%168 = OpExtInst %6 %1 Length %167 -%169 = OpExtInst %6 %1 FClamp %168 %5 %12 +%131 = OpLoad %4 %45 +%132 = OpIAdd %4 %131 %11 +OpStore %45 %132 +OpBranch %71 +%72 = OpLabel +%133 = OpLoad %8 %38 +%134 = OpSGreaterThan %57 %133 %7 +OpSelectionMerge %135 None +OpBranchConditional %134 %136 %135 +%136 = OpLabel +%137 = OpLoad %15 %32 +%138 = OpLoad %8 %38 +%139 = OpConvertSToF %6 %138 +%140 = OpCompositeConstruct %15 %139 %139 +%141 = OpFDiv %15 %137 %140 +%142 = OpLoad %15 %27 +%143 = OpFSub %15 %141 %142 +OpStore %32 %143 +OpBranch %135 +%135 = OpLabel +%144 = OpLoad %8 %40 +%145 = OpSGreaterThan %57 %144 %7 +OpSelectionMerge %146 None +OpBranchConditional %145 %147 %146 +%147 = OpLabel +%148 = OpLoad %15 %34 +%149 = OpLoad %8 %40 +%150 = OpConvertSToF %6 %149 +%151 = OpCompositeConstruct %15 %150 %150 +%152 = OpFDiv %15 %148 %151 +OpStore %34 %152 +OpBranch %146 +%146 = OpLabel +%153 = OpLoad %15 %30 +%154 = OpLoad %15 %32 +%156 = OpAccessChain %92 %54 %155 +%157 = OpLoad %6 %156 +%158 = OpVectorTimesScalar %15 %154 %157 +%159 = OpFAdd %15 %153 %158 +%160 = OpLoad %15 %36 +%162 = OpAccessChain %92 %54 %161 +%163 = OpLoad %6 %162 +%164 = OpVectorTimesScalar %15 %160 %163 +%165 = OpFAdd %15 %159 %164 +%166 = OpLoad %15 %34 +%168 = OpAccessChain %92 %54 %167 +%169 = OpLoad %6 %168 %170 = OpVectorTimesScalar %15 %166 %169 -OpStore %29 %170 -%171 = OpLoad %15 %27 -%172 = OpLoad %15 %29 -%173 = OpAccessChain %85 %47 %9 -%174 = OpLoad %6 %173 -%175 = OpVectorTimesScalar %15 %172 %174 -%176 = OpFAdd %15 %171 %175 -OpStore %27 %176 -%178 = OpAccessChain %177 %27 %9 -%179 = OpLoad %6 %178 -%180 = OpFOrdLessThan %50 %179 %13 -OpSelectionMerge %181 None -OpBranchConditional %180 %182 %181 -%182 = OpLabel -%183 = OpAccessChain %177 %27 %9 -OpStore %183 %14 -OpBranch %181 -%181 = OpLabel -%184 = OpAccessChain %177 %27 %9 -%185 = OpLoad %6 %184 -%186 = OpFOrdGreaterThan %50 %185 %14 -OpSelectionMerge %187 None -OpBranchConditional %186 %188 %187 +%171 = OpFAdd %15 %165 %170 +OpStore %30 %171 +%172 = OpLoad %15 %30 +%173 = OpExtInst %15 %1 Normalize %172 +%174 = OpLoad %15 %30 +%175 = OpExtInst %6 %1 Length %174 +%176 = OpExtInst %6 %1 FClamp %175 %5 %12 +%177 = OpVectorTimesScalar %15 %173 %176 +OpStore %30 %177 +%178 = OpLoad %15 %27 +%179 = OpLoad %15 %30 +%180 = OpAccessChain %92 %54 %9 +%181 = OpLoad %6 %180 +%182 = OpVectorTimesScalar %15 %179 %181 +%183 = OpFAdd %15 %178 %182 +OpStore %27 %183 +%185 = OpAccessChain %184 %27 %9 +%186 = OpLoad %6 %185 +%187 = OpFOrdLessThan %57 %186 %13 +OpSelectionMerge %188 None +OpBranchConditional %187 %189 %188 +%189 = OpLabel +%190 = OpAccessChain %184 %27 %9 +OpStore %190 %14 +OpBranch %188 %188 = OpLabel -%189 = OpAccessChain %177 %27 %9 -OpStore %189 %13 -OpBranch %187 -%187 = OpLabel -%190 = OpAccessChain %177 %27 %11 -%191 = OpLoad %6 %190 -%192 = OpFOrdLessThan %50 %191 %13 -OpSelectionMerge %193 None -OpBranchConditional %192 %194 %193 +%191 = OpAccessChain %184 %27 %9 +%192 = OpLoad %6 %191 +%193 = OpFOrdGreaterThan %57 %192 %14 +OpSelectionMerge %194 None +OpBranchConditional %193 %195 %194 +%195 = OpLabel +%196 = OpAccessChain %184 %27 %9 +OpStore %196 %13 +OpBranch %194 %194 = OpLabel -%195 = OpAccessChain %177 %27 %11 -OpStore %195 %14 -OpBranch %193 -%193 = OpLabel -%196 = OpAccessChain %177 %27 %11 -%197 = OpLoad %6 %196 -%198 = OpFOrdGreaterThan %50 %197 %14 -OpSelectionMerge %199 None -OpBranchConditional %198 %200 %199 +%197 = OpAccessChain %184 %27 %11 +%198 = OpLoad %6 %197 +%199 = OpFOrdLessThan %57 %198 %13 +OpSelectionMerge %200 None +OpBranchConditional %199 %201 %200 +%201 = OpLabel +%202 = OpAccessChain %184 %27 %11 +OpStore %202 %14 +OpBranch %200 %200 = OpLabel -%201 = OpAccessChain %177 %27 %11 -OpStore %201 %13 -OpBranch %199 -%199 = OpLabel -%202 = OpLoad %15 %27 -%203 = OpAccessChain %56 %26 %9 %49 %9 -OpStore %203 %202 -%204 = OpLoad %15 %29 -%205 = OpAccessChain %56 %26 %9 %49 %11 -OpStore %205 %204 +%203 = OpAccessChain %184 %27 %11 +%204 = OpLoad %6 %203 +%205 = OpFOrdGreaterThan %57 %204 %14 +OpSelectionMerge %206 None +OpBranchConditional %205 %207 %206 +%207 = OpLabel +%208 = OpAccessChain %184 %27 %11 +OpStore %208 %13 +OpBranch %206 +%206 = OpLabel +%209 = OpLoad %15 %27 +%210 = OpAccessChain %63 %26 %9 %56 %9 +OpStore %210 %209 +%211 = OpLoad %15 %30 +%212 = OpAccessChain %63 %26 %9 %56 %11 +OpStore %212 %211 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index 2980ef830..6e6483da1 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -1,29 +1,29 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 59 +; Bound: 60 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %48 "main" %45 -OpExecutionMode %48 LocalSize 1 1 1 +OpEntryPoint GLCompute %49 "main" %46 +OpExecutionMode %49 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %9 0 "data" OpName %9 "PrimeIndices" OpName %11 "v_indices" OpName %13 "n" -OpName %15 "i" -OpName %17 "n_base" -OpName %18 "collatz_iterations" -OpName %45 "global_id" -OpName %48 "main" +OpName %16 "i" +OpName %18 "n_base" +OpName %19 "collatz_iterations" +OpName %46 "global_id" +OpName %49 "main" OpDecorate %8 ArrayStride 4 OpMemberDecorate %9 0 Offset 0 OpDecorate %11 DescriptorSet 0 OpDecorate %11 Binding 0 OpDecorate %9 Block -OpDecorate %45 BuiltIn GlobalInvocationId +OpDecorate %46 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -36,71 +36,72 @@ OpDecorate %45 BuiltIn GlobalInvocationId %12 = OpTypePointer StorageBuffer %9 %11 = OpVariable %12 StorageBuffer %14 = OpTypePointer Function %4 -%19 = OpTypeFunction %4 %4 -%26 = OpTypeBool -%46 = OpTypePointer Input %10 -%45 = OpVariable %46 Input -%49 = OpTypeFunction %2 -%51 = OpTypePointer StorageBuffer %8 -%53 = OpTypePointer StorageBuffer %4 -%18 = OpFunction %4 None %19 -%17 = OpFunctionParameter %4 -%16 = OpLabel -%13 = OpVariable %14 Function -%15 = OpVariable %14 Function %3 -OpBranch %20 -%20 = OpLabel -OpStore %13 %17 +%15 = OpConstantNull %4 +%20 = OpTypeFunction %4 %4 +%27 = OpTypeBool +%47 = OpTypePointer Input %10 +%46 = OpVariable %47 Input +%50 = OpTypeFunction %2 +%52 = OpTypePointer StorageBuffer %8 +%54 = OpTypePointer StorageBuffer %4 +%19 = OpFunction %4 None %20 +%18 = OpFunctionParameter %4 +%17 = OpLabel +%13 = OpVariable %14 Function %15 +%16 = OpVariable %14 Function %3 OpBranch %21 %21 = OpLabel -OpLoopMerge %22 %24 None -OpBranch %23 -%23 = OpLabel -%25 = OpLoad %4 %13 -%27 = OpUGreaterThan %26 %25 %5 -OpSelectionMerge %28 None -OpBranchConditional %27 %28 %29 -%29 = OpLabel +OpStore %13 %18 OpBranch %22 -%28 = OpLabel -%30 = OpLoad %4 %13 -%31 = OpUMod %4 %30 %6 -%32 = OpIEqual %26 %31 %3 -OpSelectionMerge %33 None -OpBranchConditional %32 %34 %35 -%34 = OpLabel -%36 = OpLoad %4 %13 -%37 = OpUDiv %4 %36 %6 -OpStore %13 %37 -OpBranch %33 -%35 = OpLabel -%38 = OpLoad %4 %13 -%39 = OpIMul %4 %7 %38 -%40 = OpIAdd %4 %39 %5 -OpStore %13 %40 -OpBranch %33 -%33 = OpLabel -%41 = OpLoad %4 %15 -%42 = OpIAdd %4 %41 %5 -OpStore %15 %42 +%22 = OpLabel +OpLoopMerge %23 %25 None OpBranch %24 %24 = OpLabel -OpBranch %21 -%22 = OpLabel -%43 = OpLoad %4 %15 -OpReturnValue %43 +%26 = OpLoad %4 %13 +%28 = OpUGreaterThan %27 %26 %5 +OpSelectionMerge %29 None +OpBranchConditional %28 %29 %30 +%30 = OpLabel +OpBranch %23 +%29 = OpLabel +%31 = OpLoad %4 %13 +%32 = OpUMod %4 %31 %6 +%33 = OpIEqual %27 %32 %3 +OpSelectionMerge %34 None +OpBranchConditional %33 %35 %36 +%35 = OpLabel +%37 = OpLoad %4 %13 +%38 = OpUDiv %4 %37 %6 +OpStore %13 %38 +OpBranch %34 +%36 = OpLabel +%39 = OpLoad %4 %13 +%40 = OpIMul %4 %7 %39 +%41 = OpIAdd %4 %40 %5 +OpStore %13 %41 +OpBranch %34 +%34 = OpLabel +%42 = OpLoad %4 %16 +%43 = OpIAdd %4 %42 %5 +OpStore %16 %43 +OpBranch %25 +%25 = OpLabel +OpBranch %22 +%23 = OpLabel +%44 = OpLoad %4 %16 +OpReturnValue %44 OpFunctionEnd -%48 = OpFunction %2 None %49 -%44 = OpLabel -%47 = OpLoad %10 %45 -OpBranch %50 -%50 = OpLabel -%52 = OpCompositeExtract %4 %47 0 -%54 = OpCompositeExtract %4 %47 0 -%55 = OpAccessChain %53 %11 %3 %54 -%56 = OpLoad %4 %55 -%57 = OpFunctionCall %4 %18 %56 -%58 = OpAccessChain %53 %11 %3 %52 -OpStore %58 %57 +%49 = OpFunction %2 None %50 +%45 = OpLabel +%48 = OpLoad %10 %46 +OpBranch %51 +%51 = OpLabel +%53 = OpCompositeExtract %4 %48 0 +%55 = OpCompositeExtract %4 %48 0 +%56 = OpAccessChain %54 %11 %3 %55 +%57 = OpLoad %4 %56 +%58 = OpFunctionCall %4 %19 %57 +%59 = OpAccessChain %54 %11 %3 %53 +OpStore %59 %58 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index 1a34638d8..93da80103 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 67 +; Bound: 68 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %42 "main" %39 -OpExecutionMode %42 LocalSize 1 1 1 -OpDecorate %39 BuiltIn GlobalInvocationId +OpEntryPoint GLCompute %43 "main" %40 +OpExecutionMode %43 LocalSize 1 1 1 +OpDecorate %40 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 @@ -20,12 +20,13 @@ OpDecorate %39 BuiltIn GlobalInvocationId %14 = OpTypeFunction %2 %4 %20 = OpTypeFunction %2 %37 = OpTypePointer Function %4 -%40 = OpTypePointer Input %10 -%39 = OpVariable %40 Input -%44 = OpConstant %9 2 -%45 = OpConstant %9 1 -%46 = OpConstant %9 72 -%47 = OpConstant %9 264 +%38 = OpConstantNull %4 +%41 = OpTypePointer Input %10 +%40 = OpVariable %41 Input +%45 = OpConstant %9 2 +%46 = OpConstant %9 1 +%47 = OpConstant %9 72 +%48 = OpConstant %9 264 %13 = OpFunction %2 None %14 %12 = OpFunctionParameter %4 %11 = OpLabel @@ -74,62 +75,62 @@ OpBranch %29 %30 = OpLabel OpReturn OpFunctionEnd -%42 = OpFunction %2 None %20 -%38 = OpLabel -%36 = OpVariable %37 Function -%41 = OpLoad %10 %39 -OpBranch %43 -%43 = OpLabel -OpControlBarrier %44 %45 %46 -OpControlBarrier %44 %44 %47 -OpSelectionMerge %48 None -OpSwitch %3 %49 +%43 = OpFunction %2 None %20 +%39 = OpLabel +%36 = OpVariable %37 Function %38 +%42 = OpLoad %10 %40 +OpBranch %44 +%44 = OpLabel +OpControlBarrier %45 %46 %47 +OpControlBarrier %45 %45 %48 +OpSelectionMerge %49 None +OpSwitch %3 %50 +%50 = OpLabel +OpStore %36 %3 +OpBranch %49 %49 = OpLabel -OpStore %36 %3 -OpBranch %48 -%48 = OpLabel -%50 = OpLoad %4 %36 -OpSelectionMerge %51 None -OpSwitch %50 %52 1 %53 2 %54 3 %55 4 %56 -%53 = OpLabel -OpStore %36 %5 -OpBranch %51 +%51 = OpLoad %4 %36 +OpSelectionMerge %52 None +OpSwitch %51 %53 1 %54 2 %55 3 %56 4 %57 %54 = OpLabel -OpStore %36 %3 -OpBranch %51 +OpStore %36 %5 +OpBranch %52 %55 = OpLabel -OpStore %36 %6 -OpBranch %56 +OpStore %36 %3 +OpBranch %52 %56 = OpLabel -OpBranch %51 -%52 = OpLabel -OpStore %36 %7 -OpBranch %51 -%51 = OpLabel -OpSelectionMerge %57 None -OpSwitch %8 %58 0 %59 -%59 = OpLabel -OpBranch %57 -%58 = OpLabel +OpStore %36 %6 OpBranch %57 %57 = OpLabel -%60 = OpLoad %4 %36 -OpSelectionMerge %61 None -OpSwitch %60 %62 1 %63 2 %64 3 %65 4 %66 -%63 = OpLabel -OpStore %36 %5 -OpBranch %61 +OpBranch %52 +%53 = OpLabel +OpStore %36 %7 +OpBranch %52 +%52 = OpLabel +OpSelectionMerge %58 None +OpSwitch %8 %59 0 %60 +%60 = OpLabel +OpBranch %58 +%59 = OpLabel +OpBranch %58 +%58 = OpLabel +%61 = OpLoad %4 %36 +OpSelectionMerge %62 None +OpSwitch %61 %63 1 %64 2 %65 3 %66 4 %67 %64 = OpLabel +OpStore %36 %5 +OpBranch %62 +%65 = OpLabel OpStore %36 %3 OpReturn -%65 = OpLabel -OpStore %36 %6 -OpBranch %66 %66 = OpLabel +OpStore %36 %6 +OpBranch %67 +%67 = OpLabel OpReturn -%62 = OpLabel +%63 = OpLabel OpStore %36 %7 OpReturn -%61 = OpLabel +%62 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interpolate.spvasm b/tests/out/spv/interpolate.spvasm index da47ff164..a6fae2b2d 100644 --- a/tests/out/spv/interpolate.spvasm +++ b/tests/out/spv/interpolate.spvasm @@ -1,14 +1,14 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 110 +; Bound: 111 OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %45 "vert_main" %29 %31 %33 %35 %37 %39 %40 %41 %42 -OpEntryPoint Fragment %108 "frag_main" %87 %90 %93 %96 %99 %102 %104 %106 -OpExecutionMode %108 OriginUpperLeft +OpEntryPoint Vertex %46 "vert_main" %30 %32 %34 %36 %38 %40 %41 %42 %43 +OpEntryPoint Fragment %109 "frag_main" %88 %91 %94 %97 %100 %103 %105 %107 +OpExecutionMode %109 OriginUpperLeft OpSource GLSL 450 OpMemberName %25 0 "position" OpMemberName %25 1 "_flat" @@ -20,24 +20,24 @@ OpMemberName %25 6 "perspective_centroid" OpMemberName %25 7 "perspective_sample" OpName %25 "FragmentInput" OpName %26 "out" -OpName %29 "position" -OpName %31 "_flat" -OpName %33 "_linear" -OpName %35 "linear_centroid" -OpName %37 "linear_sample" -OpName %39 "perspective" -OpName %40 "perspective_centroid" -OpName %41 "perspective_sample" -OpName %45 "vert_main" -OpName %87 "position" -OpName %90 "_flat" -OpName %93 "_linear" -OpName %96 "linear_centroid" -OpName %99 "linear_sample" -OpName %102 "perspective" -OpName %104 "perspective_centroid" -OpName %106 "perspective_sample" -OpName %108 "frag_main" +OpName %30 "position" +OpName %32 "_flat" +OpName %34 "_linear" +OpName %36 "linear_centroid" +OpName %38 "linear_sample" +OpName %40 "perspective" +OpName %41 "perspective_centroid" +OpName %42 "perspective_sample" +OpName %46 "vert_main" +OpName %88 "position" +OpName %91 "_flat" +OpName %94 "_linear" +OpName %97 "linear_centroid" +OpName %100 "linear_sample" +OpName %103 "perspective" +OpName %105 "perspective_centroid" +OpName %107 "perspective_sample" +OpName %109 "frag_main" OpMemberDecorate %25 0 Offset 0 OpMemberDecorate %25 1 Offset 16 OpMemberDecorate %25 2 Offset 20 @@ -46,39 +46,39 @@ OpMemberDecorate %25 4 Offset 32 OpMemberDecorate %25 5 Offset 48 OpMemberDecorate %25 6 Offset 64 OpMemberDecorate %25 7 Offset 68 -OpDecorate %29 BuiltIn Position -OpDecorate %31 Location 0 -OpDecorate %31 Flat -OpDecorate %33 Location 1 -OpDecorate %33 NoPerspective -OpDecorate %35 Location 2 -OpDecorate %35 NoPerspective -OpDecorate %35 Centroid -OpDecorate %37 Location 3 -OpDecorate %37 NoPerspective -OpDecorate %37 Sample -OpDecorate %39 Location 4 -OpDecorate %40 Location 5 -OpDecorate %40 Centroid -OpDecorate %41 Location 6 -OpDecorate %41 Sample -OpDecorate %42 BuiltIn PointSize -OpDecorate %87 BuiltIn FragCoord -OpDecorate %90 Location 0 -OpDecorate %90 Flat -OpDecorate %93 Location 1 -OpDecorate %93 NoPerspective -OpDecorate %96 Location 2 -OpDecorate %96 NoPerspective -OpDecorate %96 Centroid -OpDecorate %99 Location 3 -OpDecorate %99 NoPerspective -OpDecorate %99 Sample -OpDecorate %102 Location 4 -OpDecorate %104 Location 5 -OpDecorate %104 Centroid -OpDecorate %106 Location 6 -OpDecorate %106 Sample +OpDecorate %30 BuiltIn Position +OpDecorate %32 Location 0 +OpDecorate %32 Flat +OpDecorate %34 Location 1 +OpDecorate %34 NoPerspective +OpDecorate %36 Location 2 +OpDecorate %36 NoPerspective +OpDecorate %36 Centroid +OpDecorate %38 Location 3 +OpDecorate %38 NoPerspective +OpDecorate %38 Sample +OpDecorate %40 Location 4 +OpDecorate %41 Location 5 +OpDecorate %41 Centroid +OpDecorate %42 Location 6 +OpDecorate %42 Sample +OpDecorate %43 BuiltIn PointSize +OpDecorate %88 BuiltIn FragCoord +OpDecorate %91 Location 0 +OpDecorate %91 Flat +OpDecorate %94 Location 1 +OpDecorate %94 NoPerspective +OpDecorate %97 Location 2 +OpDecorate %97 NoPerspective +OpDecorate %97 Centroid +OpDecorate %100 Location 3 +OpDecorate %100 NoPerspective +OpDecorate %100 Sample +OpDecorate %103 Location 4 +OpDecorate %105 Location 5 +OpDecorate %105 Centroid +OpDecorate %107 Location 6 +OpDecorate %107 Sample %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 2.0 @@ -104,110 +104,111 @@ OpDecorate %106 Sample %24 = OpTypeVector %4 3 %25 = OpTypeStruct %22 %9 %4 %23 %24 %22 %4 %4 %27 = OpTypePointer Function %25 -%30 = OpTypePointer Output %22 -%29 = OpVariable %30 Output -%32 = OpTypePointer Output %9 -%31 = OpVariable %32 Output -%34 = OpTypePointer Output %4 -%33 = OpVariable %34 Output -%36 = OpTypePointer Output %23 -%35 = OpVariable %36 Output -%38 = OpTypePointer Output %24 -%37 = OpVariable %38 Output -%39 = OpVariable %30 Output -%40 = OpVariable %34 Output -%41 = OpVariable %34 Output -%43 = OpTypePointer Output %4 -%42 = OpVariable %43 Output -%44 = OpConstant %4 1.0 -%46 = OpTypeFunction %2 -%48 = OpTypePointer Function %22 -%50 = OpConstant %9 0 -%52 = OpTypePointer Function %9 -%53 = OpConstant %9 1 -%55 = OpTypePointer Function %4 -%56 = OpConstant %9 2 -%58 = OpTypePointer Function %23 -%60 = OpConstant %9 3 -%62 = OpTypePointer Function %24 -%64 = OpConstant %9 4 -%67 = OpConstant %9 5 -%69 = OpConstant %9 6 -%71 = OpConstant %9 7 -%88 = OpTypePointer Input %22 -%87 = OpVariable %88 Input -%91 = OpTypePointer Input %9 -%90 = OpVariable %91 Input -%94 = OpTypePointer Input %4 -%93 = OpVariable %94 Input -%97 = OpTypePointer Input %23 -%96 = OpVariable %97 Input -%100 = OpTypePointer Input %24 -%99 = OpVariable %100 Input -%102 = OpVariable %88 Input -%104 = OpVariable %94 Input -%106 = OpVariable %94 Input -%45 = OpFunction %2 None %46 -%28 = OpLabel -%26 = OpVariable %27 Function -OpStore %42 %44 -OpBranch %47 -%47 = OpLabel -%49 = OpCompositeConstruct %22 %3 %5 %6 %7 -%51 = OpAccessChain %48 %26 %50 -OpStore %51 %49 -%54 = OpAccessChain %52 %26 %53 -OpStore %54 %8 -%57 = OpAccessChain %55 %26 %56 -OpStore %57 %10 -%59 = OpCompositeConstruct %23 %11 %12 -%61 = OpAccessChain %58 %26 %60 -OpStore %61 %59 -%63 = OpCompositeConstruct %24 %13 %14 %15 -%65 = OpAccessChain %62 %26 %64 -OpStore %65 %63 -%66 = OpCompositeConstruct %22 %16 %17 %18 %19 -%68 = OpAccessChain %48 %26 %67 -OpStore %68 %66 -%70 = OpAccessChain %55 %26 %69 -OpStore %70 %20 -%72 = OpAccessChain %55 %26 %71 -OpStore %72 %21 -%73 = OpLoad %25 %26 -%74 = OpCompositeExtract %22 %73 0 -OpStore %29 %74 -%75 = OpAccessChain %43 %29 %53 -%76 = OpLoad %4 %75 -%77 = OpFNegate %4 %76 -OpStore %75 %77 -%78 = OpCompositeExtract %9 %73 1 -OpStore %31 %78 -%79 = OpCompositeExtract %4 %73 2 -OpStore %33 %79 -%80 = OpCompositeExtract %23 %73 3 -OpStore %35 %80 -%81 = OpCompositeExtract %24 %73 4 -OpStore %37 %81 -%82 = OpCompositeExtract %22 %73 5 -OpStore %39 %82 -%83 = OpCompositeExtract %4 %73 6 +%28 = OpConstantNull %25 +%31 = OpTypePointer Output %22 +%30 = OpVariable %31 Output +%33 = OpTypePointer Output %9 +%32 = OpVariable %33 Output +%35 = OpTypePointer Output %4 +%34 = OpVariable %35 Output +%37 = OpTypePointer Output %23 +%36 = OpVariable %37 Output +%39 = OpTypePointer Output %24 +%38 = OpVariable %39 Output +%40 = OpVariable %31 Output +%41 = OpVariable %35 Output +%42 = OpVariable %35 Output +%44 = OpTypePointer Output %4 +%43 = OpVariable %44 Output +%45 = OpConstant %4 1.0 +%47 = OpTypeFunction %2 +%49 = OpTypePointer Function %22 +%51 = OpConstant %9 0 +%53 = OpTypePointer Function %9 +%54 = OpConstant %9 1 +%56 = OpTypePointer Function %4 +%57 = OpConstant %9 2 +%59 = OpTypePointer Function %23 +%61 = OpConstant %9 3 +%63 = OpTypePointer Function %24 +%65 = OpConstant %9 4 +%68 = OpConstant %9 5 +%70 = OpConstant %9 6 +%72 = OpConstant %9 7 +%89 = OpTypePointer Input %22 +%88 = OpVariable %89 Input +%92 = OpTypePointer Input %9 +%91 = OpVariable %92 Input +%95 = OpTypePointer Input %4 +%94 = OpVariable %95 Input +%98 = OpTypePointer Input %23 +%97 = OpVariable %98 Input +%101 = OpTypePointer Input %24 +%100 = OpVariable %101 Input +%103 = OpVariable %89 Input +%105 = OpVariable %95 Input +%107 = OpVariable %95 Input +%46 = OpFunction %2 None %47 +%29 = OpLabel +%26 = OpVariable %27 Function %28 +OpStore %43 %45 +OpBranch %48 +%48 = OpLabel +%50 = OpCompositeConstruct %22 %3 %5 %6 %7 +%52 = OpAccessChain %49 %26 %51 +OpStore %52 %50 +%55 = OpAccessChain %53 %26 %54 +OpStore %55 %8 +%58 = OpAccessChain %56 %26 %57 +OpStore %58 %10 +%60 = OpCompositeConstruct %23 %11 %12 +%62 = OpAccessChain %59 %26 %61 +OpStore %62 %60 +%64 = OpCompositeConstruct %24 %13 %14 %15 +%66 = OpAccessChain %63 %26 %65 +OpStore %66 %64 +%67 = OpCompositeConstruct %22 %16 %17 %18 %19 +%69 = OpAccessChain %49 %26 %68 +OpStore %69 %67 +%71 = OpAccessChain %56 %26 %70 +OpStore %71 %20 +%73 = OpAccessChain %56 %26 %72 +OpStore %73 %21 +%74 = OpLoad %25 %26 +%75 = OpCompositeExtract %22 %74 0 +OpStore %30 %75 +%76 = OpAccessChain %44 %30 %54 +%77 = OpLoad %4 %76 +%78 = OpFNegate %4 %77 +OpStore %76 %78 +%79 = OpCompositeExtract %9 %74 1 +OpStore %32 %79 +%80 = OpCompositeExtract %4 %74 2 +OpStore %34 %80 +%81 = OpCompositeExtract %23 %74 3 +OpStore %36 %81 +%82 = OpCompositeExtract %24 %74 4 +OpStore %38 %82 +%83 = OpCompositeExtract %22 %74 5 OpStore %40 %83 -%84 = OpCompositeExtract %4 %73 7 +%84 = OpCompositeExtract %4 %74 6 OpStore %41 %84 +%85 = OpCompositeExtract %4 %74 7 +OpStore %42 %85 OpReturn OpFunctionEnd -%108 = OpFunction %2 None %46 -%85 = OpLabel -%89 = OpLoad %22 %87 -%92 = OpLoad %9 %90 -%95 = OpLoad %4 %93 -%98 = OpLoad %23 %96 -%101 = OpLoad %24 %99 -%103 = OpLoad %22 %102 -%105 = OpLoad %4 %104 -%107 = OpLoad %4 %106 -%86 = OpCompositeConstruct %25 %89 %92 %95 %98 %101 %103 %105 %107 -OpBranch %109 -%109 = OpLabel +%109 = OpFunction %2 None %47 +%86 = OpLabel +%90 = OpLoad %22 %88 +%93 = OpLoad %9 %91 +%96 = OpLoad %4 %94 +%99 = OpLoad %23 %97 +%102 = OpLoad %24 %100 +%104 = OpLoad %22 %103 +%106 = OpLoad %4 %105 +%108 = OpLoad %4 %107 +%87 = OpCompositeConstruct %25 %90 %93 %96 %99 %102 %104 %106 %108 +OpBranch %110 +%110 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 52063e0fd..850295757 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 501 +; Bound: 502 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %489 "main" -OpExecutionMode %489 LocalSize 1 1 1 +OpEntryPoint GLCompute %490 "main" +OpExecutionMode %490 LocalSize 1 1 1 OpMemberDecorate %30 0 Offset 0 OpMemberDecorate %30 1 Offset 16 OpDecorate %35 ArrayStride 32 @@ -67,14 +67,15 @@ OpDecorate %36 ArrayStride 4 %98 = OpTypeFunction %29 %29 %100 = OpTypeVector %10 3 %107 = OpTypePointer Function %30 -%110 = OpTypeFunction %4 -%127 = OpTypePointer Function %26 -%128 = OpTypePointer Function %4 -%133 = OpTypeFunction %2 -%136 = OpTypeVector %10 2 -%152 = OpTypeVector %8 2 -%163 = OpTypeVector %20 3 -%458 = OpTypePointer Function %8 +%108 = OpConstantNull %30 +%111 = OpTypeFunction %4 +%128 = OpTypePointer Function %26 +%129 = OpTypePointer Function %4 +%134 = OpTypeFunction %2 +%137 = OpTypeVector %10 2 +%153 = OpTypeVector %8 2 +%164 = OpTypeVector %20 3 +%459 = OpTypePointer Function %8 %55 = OpFunction %26 None %56 %54 = OpLabel OpBranch %57 @@ -133,423 +134,423 @@ OpBranch %99 %105 = OpSelect %29 %102 %104 %103 OpReturnValue %105 OpFunctionEnd -%109 = OpFunction %4 None %110 -%108 = OpLabel -%106 = OpVariable %107 Function -OpBranch %111 -%111 = OpLabel -%112 = OpCompositeConstruct %26 %3 %3 %3 %3 -%113 = OpCompositeConstruct %30 %112 %7 -OpStore %106 %113 -%114 = OpCompositeConstruct %31 %3 %5 -%115 = OpCompositeConstruct %31 %5 %3 -%116 = OpCompositeConstruct %32 %114 %115 -%117 = OpCompositeConstruct %26 %3 %5 %5 %5 -%118 = OpCompositeConstruct %26 %5 %3 %5 %5 -%119 = OpCompositeConstruct %26 %5 %5 %3 %5 -%120 = OpCompositeConstruct %26 %5 %5 %5 %3 -%121 = OpCompositeConstruct %33 %117 %118 %119 %120 -%122 = OpCompositeConstruct %34 %19 %19 -%123 = OpCompositeConstruct %31 %5 %5 +%110 = OpFunction %4 None %111 +%109 = OpLabel +%106 = OpVariable %107 Function %108 +OpBranch %112 +%112 = OpLabel +%113 = OpCompositeConstruct %26 %3 %3 %3 %3 +%114 = OpCompositeConstruct %30 %113 %7 +OpStore %106 %114 +%115 = OpCompositeConstruct %31 %3 %5 +%116 = OpCompositeConstruct %31 %5 %3 +%117 = OpCompositeConstruct %32 %115 %116 +%118 = OpCompositeConstruct %26 %3 %5 %5 %5 +%119 = OpCompositeConstruct %26 %5 %3 %5 %5 +%120 = OpCompositeConstruct %26 %5 %5 %3 %5 +%121 = OpCompositeConstruct %26 %5 %5 %5 %3 +%122 = OpCompositeConstruct %33 %118 %119 %120 %121 +%123 = OpCompositeConstruct %34 %19 %19 %124 = OpCompositeConstruct %31 %5 %5 -%125 = OpCompositeConstruct %32 %123 %124 -%126 = OpCompositeConstruct %36 %11 %7 %18 %21 -%129 = OpAccessChain %128 %106 %19 %19 -%130 = OpLoad %4 %129 -OpReturnValue %130 +%125 = OpCompositeConstruct %31 %5 %5 +%126 = OpCompositeConstruct %32 %124 %125 +%127 = OpCompositeConstruct %36 %11 %7 %18 %21 +%130 = OpAccessChain %129 %106 %19 %19 +%131 = OpLoad %4 %130 +OpReturnValue %131 OpFunctionEnd -%132 = OpFunction %2 None %133 -%131 = OpLabel -OpBranch %134 -%134 = OpLabel -%135 = OpLogicalNot %10 %9 -%137 = OpCompositeConstruct %136 %9 %9 -%138 = OpLogicalNot %136 %137 -%139 = OpLogicalOr %10 %9 %12 -%140 = OpLogicalAnd %10 %9 %12 -%141 = OpLogicalOr %10 %9 %12 -%142 = OpCompositeConstruct %100 %9 %9 %9 -%143 = OpCompositeConstruct %100 %12 %12 %12 -%144 = OpLogicalOr %100 %142 %143 -%145 = OpLogicalAnd %10 %9 %12 -%146 = OpCompositeConstruct %28 %9 %9 %9 %9 -%147 = OpCompositeConstruct %28 %12 %12 %12 %12 -%148 = OpLogicalAnd %28 %146 %147 +%133 = OpFunction %2 None %134 +%132 = OpLabel +OpBranch %135 +%135 = OpLabel +%136 = OpLogicalNot %10 %9 +%138 = OpCompositeConstruct %137 %9 %9 +%139 = OpLogicalNot %137 %138 +%140 = OpLogicalOr %10 %9 %12 +%141 = OpLogicalAnd %10 %9 %12 +%142 = OpLogicalOr %10 %9 %12 +%143 = OpCompositeConstruct %100 %9 %9 %9 +%144 = OpCompositeConstruct %100 %12 %12 %12 +%145 = OpLogicalOr %100 %143 %144 +%146 = OpLogicalAnd %10 %9 %12 +%147 = OpCompositeConstruct %28 %9 %9 %9 %9 +%148 = OpCompositeConstruct %28 %12 %12 %12 %12 +%149 = OpLogicalAnd %28 %147 %148 OpReturn OpFunctionEnd -%150 = OpFunction %2 None %133 -%149 = OpLabel -OpBranch %151 -%151 = OpLabel -%153 = OpCompositeConstruct %152 %7 %7 -%154 = OpSNegate %152 %153 -%155 = OpCompositeConstruct %31 %3 %3 -%156 = OpFNegate %31 %155 -%157 = OpIAdd %8 %18 %7 -%158 = OpIAdd %20 %24 %25 -%159 = OpFAdd %4 %14 %3 -%160 = OpCompositeConstruct %152 %18 %18 -%161 = OpCompositeConstruct %152 %7 %7 -%162 = OpIAdd %152 %160 %161 -%164 = OpCompositeConstruct %163 %24 %24 %24 -%165 = OpCompositeConstruct %163 %25 %25 %25 -%166 = OpIAdd %163 %164 %165 -%167 = OpCompositeConstruct %26 %14 %14 %14 %14 -%168 = OpCompositeConstruct %26 %3 %3 %3 %3 -%169 = OpFAdd %26 %167 %168 -%170 = OpISub %8 %18 %7 -%171 = OpISub %20 %24 %25 -%172 = OpFSub %4 %14 %3 -%173 = OpCompositeConstruct %152 %18 %18 -%174 = OpCompositeConstruct %152 %7 %7 -%175 = OpISub %152 %173 %174 -%176 = OpCompositeConstruct %163 %24 %24 %24 -%177 = OpCompositeConstruct %163 %25 %25 %25 -%178 = OpISub %163 %176 %177 -%179 = OpCompositeConstruct %26 %14 %14 %14 %14 -%180 = OpCompositeConstruct %26 %3 %3 %3 %3 -%181 = OpFSub %26 %179 %180 -%182 = OpIMul %8 %18 %7 -%183 = OpIMul %20 %24 %25 -%184 = OpFMul %4 %14 %3 -%185 = OpCompositeConstruct %152 %18 %18 -%186 = OpCompositeConstruct %152 %7 %7 -%187 = OpIMul %152 %185 %186 -%188 = OpCompositeConstruct %163 %24 %24 %24 -%189 = OpCompositeConstruct %163 %25 %25 %25 -%190 = OpIMul %163 %188 %189 -%191 = OpCompositeConstruct %26 %14 %14 %14 %14 -%192 = OpCompositeConstruct %26 %3 %3 %3 %3 -%193 = OpFMul %26 %191 %192 -%194 = OpSDiv %8 %18 %7 -%195 = OpUDiv %20 %24 %25 -%196 = OpFDiv %4 %14 %3 -%197 = OpCompositeConstruct %152 %18 %18 -%198 = OpCompositeConstruct %152 %7 %7 -%199 = OpSDiv %152 %197 %198 -%200 = OpCompositeConstruct %163 %24 %24 %24 -%201 = OpCompositeConstruct %163 %25 %25 %25 -%202 = OpUDiv %163 %200 %201 -%203 = OpCompositeConstruct %26 %14 %14 %14 %14 -%204 = OpCompositeConstruct %26 %3 %3 %3 %3 -%205 = OpFDiv %26 %203 %204 -%206 = OpSRem %8 %18 %7 -%207 = OpUMod %20 %24 %25 -%208 = OpFRem %4 %14 %3 -%209 = OpCompositeConstruct %152 %18 %18 -%210 = OpCompositeConstruct %152 %7 %7 -%211 = OpSRem %152 %209 %210 -%212 = OpCompositeConstruct %163 %24 %24 %24 -%213 = OpCompositeConstruct %163 %25 %25 %25 -%214 = OpUMod %163 %212 %213 -%215 = OpCompositeConstruct %26 %14 %14 %14 %14 -%216 = OpCompositeConstruct %26 %3 %3 %3 %3 -%217 = OpFRem %26 %215 %216 -%218 = OpCompositeConstruct %152 %18 %18 -%219 = OpCompositeConstruct %152 %7 %7 -%220 = OpIAdd %152 %218 %219 -%221 = OpCompositeConstruct %152 %7 %7 -%222 = OpCompositeConstruct %152 %18 %18 -%223 = OpIAdd %152 %222 %221 -%224 = OpCompositeConstruct %34 %24 %24 -%225 = OpCompositeConstruct %34 %25 %25 -%226 = OpIAdd %34 %224 %225 -%227 = OpCompositeConstruct %34 %25 %25 -%228 = OpCompositeConstruct %34 %24 %24 -%229 = OpIAdd %34 %228 %227 -%230 = OpCompositeConstruct %31 %14 %14 -%231 = OpCompositeConstruct %31 %3 %3 -%232 = OpFAdd %31 %230 %231 -%233 = OpCompositeConstruct %31 %3 %3 -%234 = OpCompositeConstruct %31 %14 %14 -%235 = OpFAdd %31 %234 %233 -%236 = OpCompositeConstruct %152 %18 %18 -%237 = OpCompositeConstruct %152 %7 %7 -%238 = OpISub %152 %236 %237 -%239 = OpCompositeConstruct %152 %7 %7 -%240 = OpCompositeConstruct %152 %18 %18 -%241 = OpISub %152 %240 %239 -%242 = OpCompositeConstruct %34 %24 %24 -%243 = OpCompositeConstruct %34 %25 %25 -%244 = OpISub %34 %242 %243 -%245 = OpCompositeConstruct %34 %25 %25 -%246 = OpCompositeConstruct %34 %24 %24 -%247 = OpISub %34 %246 %245 -%248 = OpCompositeConstruct %31 %14 %14 -%249 = OpCompositeConstruct %31 %3 %3 -%250 = OpFSub %31 %248 %249 -%251 = OpCompositeConstruct %31 %3 %3 -%252 = OpCompositeConstruct %31 %14 %14 -%253 = OpFSub %31 %252 %251 -%254 = OpCompositeConstruct %152 %18 %18 -%256 = OpCompositeConstruct %152 %7 %7 -%255 = OpIMul %152 %254 %256 -%257 = OpCompositeConstruct %152 %7 %7 -%259 = OpCompositeConstruct %152 %18 %18 -%258 = OpIMul %152 %257 %259 -%260 = OpCompositeConstruct %34 %24 %24 -%262 = OpCompositeConstruct %34 %25 %25 -%261 = OpIMul %34 %260 %262 +%151 = OpFunction %2 None %134 +%150 = OpLabel +OpBranch %152 +%152 = OpLabel +%154 = OpCompositeConstruct %153 %7 %7 +%155 = OpSNegate %153 %154 +%156 = OpCompositeConstruct %31 %3 %3 +%157 = OpFNegate %31 %156 +%158 = OpIAdd %8 %18 %7 +%159 = OpIAdd %20 %24 %25 +%160 = OpFAdd %4 %14 %3 +%161 = OpCompositeConstruct %153 %18 %18 +%162 = OpCompositeConstruct %153 %7 %7 +%163 = OpIAdd %153 %161 %162 +%165 = OpCompositeConstruct %164 %24 %24 %24 +%166 = OpCompositeConstruct %164 %25 %25 %25 +%167 = OpIAdd %164 %165 %166 +%168 = OpCompositeConstruct %26 %14 %14 %14 %14 +%169 = OpCompositeConstruct %26 %3 %3 %3 %3 +%170 = OpFAdd %26 %168 %169 +%171 = OpISub %8 %18 %7 +%172 = OpISub %20 %24 %25 +%173 = OpFSub %4 %14 %3 +%174 = OpCompositeConstruct %153 %18 %18 +%175 = OpCompositeConstruct %153 %7 %7 +%176 = OpISub %153 %174 %175 +%177 = OpCompositeConstruct %164 %24 %24 %24 +%178 = OpCompositeConstruct %164 %25 %25 %25 +%179 = OpISub %164 %177 %178 +%180 = OpCompositeConstruct %26 %14 %14 %14 %14 +%181 = OpCompositeConstruct %26 %3 %3 %3 %3 +%182 = OpFSub %26 %180 %181 +%183 = OpIMul %8 %18 %7 +%184 = OpIMul %20 %24 %25 +%185 = OpFMul %4 %14 %3 +%186 = OpCompositeConstruct %153 %18 %18 +%187 = OpCompositeConstruct %153 %7 %7 +%188 = OpIMul %153 %186 %187 +%189 = OpCompositeConstruct %164 %24 %24 %24 +%190 = OpCompositeConstruct %164 %25 %25 %25 +%191 = OpIMul %164 %189 %190 +%192 = OpCompositeConstruct %26 %14 %14 %14 %14 +%193 = OpCompositeConstruct %26 %3 %3 %3 %3 +%194 = OpFMul %26 %192 %193 +%195 = OpSDiv %8 %18 %7 +%196 = OpUDiv %20 %24 %25 +%197 = OpFDiv %4 %14 %3 +%198 = OpCompositeConstruct %153 %18 %18 +%199 = OpCompositeConstruct %153 %7 %7 +%200 = OpSDiv %153 %198 %199 +%201 = OpCompositeConstruct %164 %24 %24 %24 +%202 = OpCompositeConstruct %164 %25 %25 %25 +%203 = OpUDiv %164 %201 %202 +%204 = OpCompositeConstruct %26 %14 %14 %14 %14 +%205 = OpCompositeConstruct %26 %3 %3 %3 %3 +%206 = OpFDiv %26 %204 %205 +%207 = OpSRem %8 %18 %7 +%208 = OpUMod %20 %24 %25 +%209 = OpFRem %4 %14 %3 +%210 = OpCompositeConstruct %153 %18 %18 +%211 = OpCompositeConstruct %153 %7 %7 +%212 = OpSRem %153 %210 %211 +%213 = OpCompositeConstruct %164 %24 %24 %24 +%214 = OpCompositeConstruct %164 %25 %25 %25 +%215 = OpUMod %164 %213 %214 +%216 = OpCompositeConstruct %26 %14 %14 %14 %14 +%217 = OpCompositeConstruct %26 %3 %3 %3 %3 +%218 = OpFRem %26 %216 %217 +%219 = OpCompositeConstruct %153 %18 %18 +%220 = OpCompositeConstruct %153 %7 %7 +%221 = OpIAdd %153 %219 %220 +%222 = OpCompositeConstruct %153 %7 %7 +%223 = OpCompositeConstruct %153 %18 %18 +%224 = OpIAdd %153 %223 %222 +%225 = OpCompositeConstruct %34 %24 %24 +%226 = OpCompositeConstruct %34 %25 %25 +%227 = OpIAdd %34 %225 %226 +%228 = OpCompositeConstruct %34 %25 %25 +%229 = OpCompositeConstruct %34 %24 %24 +%230 = OpIAdd %34 %229 %228 +%231 = OpCompositeConstruct %31 %14 %14 +%232 = OpCompositeConstruct %31 %3 %3 +%233 = OpFAdd %31 %231 %232 +%234 = OpCompositeConstruct %31 %3 %3 +%235 = OpCompositeConstruct %31 %14 %14 +%236 = OpFAdd %31 %235 %234 +%237 = OpCompositeConstruct %153 %18 %18 +%238 = OpCompositeConstruct %153 %7 %7 +%239 = OpISub %153 %237 %238 +%240 = OpCompositeConstruct %153 %7 %7 +%241 = OpCompositeConstruct %153 %18 %18 +%242 = OpISub %153 %241 %240 +%243 = OpCompositeConstruct %34 %24 %24 +%244 = OpCompositeConstruct %34 %25 %25 +%245 = OpISub %34 %243 %244 +%246 = OpCompositeConstruct %34 %25 %25 +%247 = OpCompositeConstruct %34 %24 %24 +%248 = OpISub %34 %247 %246 +%249 = OpCompositeConstruct %31 %14 %14 +%250 = OpCompositeConstruct %31 %3 %3 +%251 = OpFSub %31 %249 %250 +%252 = OpCompositeConstruct %31 %3 %3 +%253 = OpCompositeConstruct %31 %14 %14 +%254 = OpFSub %31 %253 %252 +%255 = OpCompositeConstruct %153 %18 %18 +%257 = OpCompositeConstruct %153 %7 %7 +%256 = OpIMul %153 %255 %257 +%258 = OpCompositeConstruct %153 %7 %7 +%260 = OpCompositeConstruct %153 %18 %18 +%259 = OpIMul %153 %258 %260 +%261 = OpCompositeConstruct %34 %24 %24 %263 = OpCompositeConstruct %34 %25 %25 -%265 = OpCompositeConstruct %34 %24 %24 -%264 = OpIMul %34 %263 %265 -%266 = OpCompositeConstruct %31 %14 %14 -%267 = OpVectorTimesScalar %31 %266 %3 -%268 = OpCompositeConstruct %31 %3 %3 -%269 = OpVectorTimesScalar %31 %268 %14 -%270 = OpCompositeConstruct %152 %18 %18 -%271 = OpCompositeConstruct %152 %7 %7 -%272 = OpSDiv %152 %270 %271 -%273 = OpCompositeConstruct %152 %7 %7 -%274 = OpCompositeConstruct %152 %18 %18 -%275 = OpSDiv %152 %274 %273 -%276 = OpCompositeConstruct %34 %24 %24 -%277 = OpCompositeConstruct %34 %25 %25 -%278 = OpUDiv %34 %276 %277 -%279 = OpCompositeConstruct %34 %25 %25 -%280 = OpCompositeConstruct %34 %24 %24 -%281 = OpUDiv %34 %280 %279 -%282 = OpCompositeConstruct %31 %14 %14 -%283 = OpCompositeConstruct %31 %3 %3 -%284 = OpFDiv %31 %282 %283 -%285 = OpCompositeConstruct %31 %3 %3 -%286 = OpCompositeConstruct %31 %14 %14 -%287 = OpFDiv %31 %286 %285 -%288 = OpCompositeConstruct %152 %18 %18 -%289 = OpCompositeConstruct %152 %7 %7 -%290 = OpSRem %152 %288 %289 -%291 = OpCompositeConstruct %152 %7 %7 -%292 = OpCompositeConstruct %152 %18 %18 -%293 = OpSRem %152 %292 %291 -%294 = OpCompositeConstruct %34 %24 %24 -%295 = OpCompositeConstruct %34 %25 %25 -%296 = OpUMod %34 %294 %295 -%297 = OpCompositeConstruct %34 %25 %25 -%298 = OpCompositeConstruct %34 %24 %24 -%299 = OpUMod %34 %298 %297 -%300 = OpCompositeConstruct %31 %14 %14 -%301 = OpCompositeConstruct %31 %3 %3 -%302 = OpFRem %31 %300 %301 -%303 = OpCompositeConstruct %31 %3 %3 -%304 = OpCompositeConstruct %31 %14 %14 -%305 = OpFRem %31 %304 %303 -%307 = OpCompositeExtract %29 %51 0 +%262 = OpIMul %34 %261 %263 +%264 = OpCompositeConstruct %34 %25 %25 +%266 = OpCompositeConstruct %34 %24 %24 +%265 = OpIMul %34 %264 %266 +%267 = OpCompositeConstruct %31 %14 %14 +%268 = OpVectorTimesScalar %31 %267 %3 +%269 = OpCompositeConstruct %31 %3 %3 +%270 = OpVectorTimesScalar %31 %269 %14 +%271 = OpCompositeConstruct %153 %18 %18 +%272 = OpCompositeConstruct %153 %7 %7 +%273 = OpSDiv %153 %271 %272 +%274 = OpCompositeConstruct %153 %7 %7 +%275 = OpCompositeConstruct %153 %18 %18 +%276 = OpSDiv %153 %275 %274 +%277 = OpCompositeConstruct %34 %24 %24 +%278 = OpCompositeConstruct %34 %25 %25 +%279 = OpUDiv %34 %277 %278 +%280 = OpCompositeConstruct %34 %25 %25 +%281 = OpCompositeConstruct %34 %24 %24 +%282 = OpUDiv %34 %281 %280 +%283 = OpCompositeConstruct %31 %14 %14 +%284 = OpCompositeConstruct %31 %3 %3 +%285 = OpFDiv %31 %283 %284 +%286 = OpCompositeConstruct %31 %3 %3 +%287 = OpCompositeConstruct %31 %14 %14 +%288 = OpFDiv %31 %287 %286 +%289 = OpCompositeConstruct %153 %18 %18 +%290 = OpCompositeConstruct %153 %7 %7 +%291 = OpSRem %153 %289 %290 +%292 = OpCompositeConstruct %153 %7 %7 +%293 = OpCompositeConstruct %153 %18 %18 +%294 = OpSRem %153 %293 %292 +%295 = OpCompositeConstruct %34 %24 %24 +%296 = OpCompositeConstruct %34 %25 %25 +%297 = OpUMod %34 %295 %296 +%298 = OpCompositeConstruct %34 %25 %25 +%299 = OpCompositeConstruct %34 %24 %24 +%300 = OpUMod %34 %299 %298 +%301 = OpCompositeConstruct %31 %14 %14 +%302 = OpCompositeConstruct %31 %3 %3 +%303 = OpFRem %31 %301 %302 +%304 = OpCompositeConstruct %31 %3 %3 +%305 = OpCompositeConstruct %31 %14 %14 +%306 = OpFRem %31 %305 %304 %308 = OpCompositeExtract %29 %51 0 -%309 = OpFAdd %29 %307 %308 -%310 = OpCompositeExtract %29 %51 1 +%309 = OpCompositeExtract %29 %51 0 +%310 = OpFAdd %29 %308 %309 %311 = OpCompositeExtract %29 %51 1 -%312 = OpFAdd %29 %310 %311 -%313 = OpCompositeExtract %29 %51 2 +%312 = OpCompositeExtract %29 %51 1 +%313 = OpFAdd %29 %311 %312 %314 = OpCompositeExtract %29 %51 2 -%315 = OpFAdd %29 %313 %314 -%306 = OpCompositeConstruct %37 %309 %312 %315 -%317 = OpCompositeExtract %29 %51 0 +%315 = OpCompositeExtract %29 %51 2 +%316 = OpFAdd %29 %314 %315 +%307 = OpCompositeConstruct %37 %310 %313 %316 %318 = OpCompositeExtract %29 %51 0 -%319 = OpFSub %29 %317 %318 -%320 = OpCompositeExtract %29 %51 1 +%319 = OpCompositeExtract %29 %51 0 +%320 = OpFSub %29 %318 %319 %321 = OpCompositeExtract %29 %51 1 -%322 = OpFSub %29 %320 %321 -%323 = OpCompositeExtract %29 %51 2 +%322 = OpCompositeExtract %29 %51 1 +%323 = OpFSub %29 %321 %322 %324 = OpCompositeExtract %29 %51 2 -%325 = OpFSub %29 %323 %324 -%316 = OpCompositeConstruct %37 %319 %322 %325 -%326 = OpMatrixTimesScalar %37 %51 %3 -%327 = OpMatrixTimesScalar %37 %51 %14 -%328 = OpCompositeConstruct %26 %3 %3 %3 %3 -%329 = OpMatrixTimesVector %29 %52 %328 -%330 = OpCompositeConstruct %29 %14 %14 %14 -%331 = OpVectorTimesMatrix %26 %330 %52 -%332 = OpMatrixTimesMatrix %37 %52 %53 +%325 = OpCompositeExtract %29 %51 2 +%326 = OpFSub %29 %324 %325 +%317 = OpCompositeConstruct %37 %320 %323 %326 +%327 = OpMatrixTimesScalar %37 %51 %3 +%328 = OpMatrixTimesScalar %37 %51 %14 +%329 = OpCompositeConstruct %26 %3 %3 %3 %3 +%330 = OpMatrixTimesVector %29 %52 %329 +%331 = OpCompositeConstruct %29 %14 %14 %14 +%332 = OpVectorTimesMatrix %26 %331 %52 +%333 = OpMatrixTimesMatrix %37 %52 %53 OpReturn OpFunctionEnd -%334 = OpFunction %2 None %133 -%333 = OpLabel -OpBranch %335 -%335 = OpLabel -%336 = OpNot %8 %7 -%337 = OpNot %20 %25 -%338 = OpCompositeConstruct %152 %7 %7 -%339 = OpNot %152 %338 -%340 = OpCompositeConstruct %163 %25 %25 %25 -%341 = OpNot %163 %340 -%342 = OpBitwiseOr %8 %18 %7 -%343 = OpBitwiseOr %20 %24 %25 -%344 = OpCompositeConstruct %152 %18 %18 -%345 = OpCompositeConstruct %152 %7 %7 -%346 = OpBitwiseOr %152 %344 %345 -%347 = OpCompositeConstruct %163 %24 %24 %24 -%348 = OpCompositeConstruct %163 %25 %25 %25 -%349 = OpBitwiseOr %163 %347 %348 -%350 = OpBitwiseAnd %8 %18 %7 -%351 = OpBitwiseAnd %20 %24 %25 -%352 = OpCompositeConstruct %152 %18 %18 -%353 = OpCompositeConstruct %152 %7 %7 -%354 = OpBitwiseAnd %152 %352 %353 -%355 = OpCompositeConstruct %163 %24 %24 %24 -%356 = OpCompositeConstruct %163 %25 %25 %25 -%357 = OpBitwiseAnd %163 %355 %356 -%358 = OpBitwiseXor %8 %18 %7 -%359 = OpBitwiseXor %20 %24 %25 -%360 = OpCompositeConstruct %152 %18 %18 -%361 = OpCompositeConstruct %152 %7 %7 -%362 = OpBitwiseXor %152 %360 %361 -%363 = OpCompositeConstruct %163 %24 %24 %24 -%364 = OpCompositeConstruct %163 %25 %25 %25 -%365 = OpBitwiseXor %163 %363 %364 -%366 = OpShiftLeftLogical %8 %18 %25 -%367 = OpShiftLeftLogical %20 %24 %25 -%368 = OpCompositeConstruct %152 %18 %18 -%369 = OpCompositeConstruct %34 %25 %25 -%370 = OpShiftLeftLogical %152 %368 %369 -%371 = OpCompositeConstruct %163 %24 %24 %24 -%372 = OpCompositeConstruct %163 %25 %25 %25 -%373 = OpShiftLeftLogical %163 %371 %372 -%374 = OpShiftRightArithmetic %8 %18 %25 -%375 = OpShiftRightLogical %20 %24 %25 -%376 = OpCompositeConstruct %152 %18 %18 -%377 = OpCompositeConstruct %34 %25 %25 -%378 = OpShiftRightArithmetic %152 %376 %377 -%379 = OpCompositeConstruct %163 %24 %24 %24 -%380 = OpCompositeConstruct %163 %25 %25 %25 -%381 = OpShiftRightLogical %163 %379 %380 +%335 = OpFunction %2 None %134 +%334 = OpLabel +OpBranch %336 +%336 = OpLabel +%337 = OpNot %8 %7 +%338 = OpNot %20 %25 +%339 = OpCompositeConstruct %153 %7 %7 +%340 = OpNot %153 %339 +%341 = OpCompositeConstruct %164 %25 %25 %25 +%342 = OpNot %164 %341 +%343 = OpBitwiseOr %8 %18 %7 +%344 = OpBitwiseOr %20 %24 %25 +%345 = OpCompositeConstruct %153 %18 %18 +%346 = OpCompositeConstruct %153 %7 %7 +%347 = OpBitwiseOr %153 %345 %346 +%348 = OpCompositeConstruct %164 %24 %24 %24 +%349 = OpCompositeConstruct %164 %25 %25 %25 +%350 = OpBitwiseOr %164 %348 %349 +%351 = OpBitwiseAnd %8 %18 %7 +%352 = OpBitwiseAnd %20 %24 %25 +%353 = OpCompositeConstruct %153 %18 %18 +%354 = OpCompositeConstruct %153 %7 %7 +%355 = OpBitwiseAnd %153 %353 %354 +%356 = OpCompositeConstruct %164 %24 %24 %24 +%357 = OpCompositeConstruct %164 %25 %25 %25 +%358 = OpBitwiseAnd %164 %356 %357 +%359 = OpBitwiseXor %8 %18 %7 +%360 = OpBitwiseXor %20 %24 %25 +%361 = OpCompositeConstruct %153 %18 %18 +%362 = OpCompositeConstruct %153 %7 %7 +%363 = OpBitwiseXor %153 %361 %362 +%364 = OpCompositeConstruct %164 %24 %24 %24 +%365 = OpCompositeConstruct %164 %25 %25 %25 +%366 = OpBitwiseXor %164 %364 %365 +%367 = OpShiftLeftLogical %8 %18 %25 +%368 = OpShiftLeftLogical %20 %24 %25 +%369 = OpCompositeConstruct %153 %18 %18 +%370 = OpCompositeConstruct %34 %25 %25 +%371 = OpShiftLeftLogical %153 %369 %370 +%372 = OpCompositeConstruct %164 %24 %24 %24 +%373 = OpCompositeConstruct %164 %25 %25 %25 +%374 = OpShiftLeftLogical %164 %372 %373 +%375 = OpShiftRightArithmetic %8 %18 %25 +%376 = OpShiftRightLogical %20 %24 %25 +%377 = OpCompositeConstruct %153 %18 %18 +%378 = OpCompositeConstruct %34 %25 %25 +%379 = OpShiftRightArithmetic %153 %377 %378 +%380 = OpCompositeConstruct %164 %24 %24 %24 +%381 = OpCompositeConstruct %164 %25 %25 %25 +%382 = OpShiftRightLogical %164 %380 %381 OpReturn OpFunctionEnd -%383 = OpFunction %2 None %133 -%382 = OpLabel -OpBranch %384 -%384 = OpLabel -%385 = OpIEqual %10 %18 %7 -%386 = OpIEqual %10 %24 %25 -%387 = OpFOrdEqual %10 %14 %3 -%388 = OpCompositeConstruct %152 %18 %18 -%389 = OpCompositeConstruct %152 %7 %7 -%390 = OpIEqual %136 %388 %389 -%391 = OpCompositeConstruct %163 %24 %24 %24 -%392 = OpCompositeConstruct %163 %25 %25 %25 -%393 = OpIEqual %100 %391 %392 -%394 = OpCompositeConstruct %26 %14 %14 %14 %14 -%395 = OpCompositeConstruct %26 %3 %3 %3 %3 -%396 = OpFOrdEqual %28 %394 %395 -%397 = OpINotEqual %10 %18 %7 -%398 = OpINotEqual %10 %24 %25 -%399 = OpFOrdNotEqual %10 %14 %3 -%400 = OpCompositeConstruct %152 %18 %18 -%401 = OpCompositeConstruct %152 %7 %7 -%402 = OpINotEqual %136 %400 %401 -%403 = OpCompositeConstruct %163 %24 %24 %24 -%404 = OpCompositeConstruct %163 %25 %25 %25 -%405 = OpINotEqual %100 %403 %404 -%406 = OpCompositeConstruct %26 %14 %14 %14 %14 -%407 = OpCompositeConstruct %26 %3 %3 %3 %3 -%408 = OpFOrdNotEqual %28 %406 %407 -%409 = OpSLessThan %10 %18 %7 -%410 = OpULessThan %10 %24 %25 -%411 = OpFOrdLessThan %10 %14 %3 -%412 = OpCompositeConstruct %152 %18 %18 -%413 = OpCompositeConstruct %152 %7 %7 -%414 = OpSLessThan %136 %412 %413 -%415 = OpCompositeConstruct %163 %24 %24 %24 -%416 = OpCompositeConstruct %163 %25 %25 %25 -%417 = OpULessThan %100 %415 %416 -%418 = OpCompositeConstruct %26 %14 %14 %14 %14 -%419 = OpCompositeConstruct %26 %3 %3 %3 %3 -%420 = OpFOrdLessThan %28 %418 %419 -%421 = OpSLessThanEqual %10 %18 %7 -%422 = OpULessThanEqual %10 %24 %25 -%423 = OpFOrdLessThanEqual %10 %14 %3 -%424 = OpCompositeConstruct %152 %18 %18 -%425 = OpCompositeConstruct %152 %7 %7 -%426 = OpSLessThanEqual %136 %424 %425 -%427 = OpCompositeConstruct %163 %24 %24 %24 -%428 = OpCompositeConstruct %163 %25 %25 %25 -%429 = OpULessThanEqual %100 %427 %428 -%430 = OpCompositeConstruct %26 %14 %14 %14 %14 -%431 = OpCompositeConstruct %26 %3 %3 %3 %3 -%432 = OpFOrdLessThanEqual %28 %430 %431 -%433 = OpSGreaterThan %10 %18 %7 -%434 = OpUGreaterThan %10 %24 %25 -%435 = OpFOrdGreaterThan %10 %14 %3 -%436 = OpCompositeConstruct %152 %18 %18 -%437 = OpCompositeConstruct %152 %7 %7 -%438 = OpSGreaterThan %136 %436 %437 -%439 = OpCompositeConstruct %163 %24 %24 %24 -%440 = OpCompositeConstruct %163 %25 %25 %25 -%441 = OpUGreaterThan %100 %439 %440 -%442 = OpCompositeConstruct %26 %14 %14 %14 %14 -%443 = OpCompositeConstruct %26 %3 %3 %3 %3 -%444 = OpFOrdGreaterThan %28 %442 %443 -%445 = OpSGreaterThanEqual %10 %18 %7 -%446 = OpUGreaterThanEqual %10 %24 %25 -%447 = OpFOrdGreaterThanEqual %10 %14 %3 -%448 = OpCompositeConstruct %152 %18 %18 -%449 = OpCompositeConstruct %152 %7 %7 -%450 = OpSGreaterThanEqual %136 %448 %449 -%451 = OpCompositeConstruct %163 %24 %24 %24 -%452 = OpCompositeConstruct %163 %25 %25 %25 -%453 = OpUGreaterThanEqual %100 %451 %452 -%454 = OpCompositeConstruct %26 %14 %14 %14 %14 -%455 = OpCompositeConstruct %26 %3 %3 %3 %3 -%456 = OpFOrdGreaterThanEqual %28 %454 %455 +%384 = OpFunction %2 None %134 +%383 = OpLabel +OpBranch %385 +%385 = OpLabel +%386 = OpIEqual %10 %18 %7 +%387 = OpIEqual %10 %24 %25 +%388 = OpFOrdEqual %10 %14 %3 +%389 = OpCompositeConstruct %153 %18 %18 +%390 = OpCompositeConstruct %153 %7 %7 +%391 = OpIEqual %137 %389 %390 +%392 = OpCompositeConstruct %164 %24 %24 %24 +%393 = OpCompositeConstruct %164 %25 %25 %25 +%394 = OpIEqual %100 %392 %393 +%395 = OpCompositeConstruct %26 %14 %14 %14 %14 +%396 = OpCompositeConstruct %26 %3 %3 %3 %3 +%397 = OpFOrdEqual %28 %395 %396 +%398 = OpINotEqual %10 %18 %7 +%399 = OpINotEqual %10 %24 %25 +%400 = OpFOrdNotEqual %10 %14 %3 +%401 = OpCompositeConstruct %153 %18 %18 +%402 = OpCompositeConstruct %153 %7 %7 +%403 = OpINotEqual %137 %401 %402 +%404 = OpCompositeConstruct %164 %24 %24 %24 +%405 = OpCompositeConstruct %164 %25 %25 %25 +%406 = OpINotEqual %100 %404 %405 +%407 = OpCompositeConstruct %26 %14 %14 %14 %14 +%408 = OpCompositeConstruct %26 %3 %3 %3 %3 +%409 = OpFOrdNotEqual %28 %407 %408 +%410 = OpSLessThan %10 %18 %7 +%411 = OpULessThan %10 %24 %25 +%412 = OpFOrdLessThan %10 %14 %3 +%413 = OpCompositeConstruct %153 %18 %18 +%414 = OpCompositeConstruct %153 %7 %7 +%415 = OpSLessThan %137 %413 %414 +%416 = OpCompositeConstruct %164 %24 %24 %24 +%417 = OpCompositeConstruct %164 %25 %25 %25 +%418 = OpULessThan %100 %416 %417 +%419 = OpCompositeConstruct %26 %14 %14 %14 %14 +%420 = OpCompositeConstruct %26 %3 %3 %3 %3 +%421 = OpFOrdLessThan %28 %419 %420 +%422 = OpSLessThanEqual %10 %18 %7 +%423 = OpULessThanEqual %10 %24 %25 +%424 = OpFOrdLessThanEqual %10 %14 %3 +%425 = OpCompositeConstruct %153 %18 %18 +%426 = OpCompositeConstruct %153 %7 %7 +%427 = OpSLessThanEqual %137 %425 %426 +%428 = OpCompositeConstruct %164 %24 %24 %24 +%429 = OpCompositeConstruct %164 %25 %25 %25 +%430 = OpULessThanEqual %100 %428 %429 +%431 = OpCompositeConstruct %26 %14 %14 %14 %14 +%432 = OpCompositeConstruct %26 %3 %3 %3 %3 +%433 = OpFOrdLessThanEqual %28 %431 %432 +%434 = OpSGreaterThan %10 %18 %7 +%435 = OpUGreaterThan %10 %24 %25 +%436 = OpFOrdGreaterThan %10 %14 %3 +%437 = OpCompositeConstruct %153 %18 %18 +%438 = OpCompositeConstruct %153 %7 %7 +%439 = OpSGreaterThan %137 %437 %438 +%440 = OpCompositeConstruct %164 %24 %24 %24 +%441 = OpCompositeConstruct %164 %25 %25 %25 +%442 = OpUGreaterThan %100 %440 %441 +%443 = OpCompositeConstruct %26 %14 %14 %14 %14 +%444 = OpCompositeConstruct %26 %3 %3 %3 %3 +%445 = OpFOrdGreaterThan %28 %443 %444 +%446 = OpSGreaterThanEqual %10 %18 %7 +%447 = OpUGreaterThanEqual %10 %24 %25 +%448 = OpFOrdGreaterThanEqual %10 %14 %3 +%449 = OpCompositeConstruct %153 %18 %18 +%450 = OpCompositeConstruct %153 %7 %7 +%451 = OpSGreaterThanEqual %137 %449 %450 +%452 = OpCompositeConstruct %164 %24 %24 %24 +%453 = OpCompositeConstruct %164 %25 %25 %25 +%454 = OpUGreaterThanEqual %100 %452 %453 +%455 = OpCompositeConstruct %26 %14 %14 %14 %14 +%456 = OpCompositeConstruct %26 %3 %3 %3 %3 +%457 = OpFOrdGreaterThanEqual %28 %455 %456 OpReturn OpFunctionEnd -%460 = OpFunction %2 None %133 -%459 = OpLabel -%457 = OpVariable %458 Function %7 -OpBranch %461 -%461 = OpLabel -%462 = OpLoad %8 %457 -%463 = OpIAdd %8 %462 %7 -OpStore %457 %463 -%464 = OpLoad %8 %457 -%465 = OpISub %8 %464 %7 -OpStore %457 %465 -%466 = OpLoad %8 %457 -%467 = OpLoad %8 %457 -%468 = OpIMul %8 %466 %467 -OpStore %457 %468 -%469 = OpLoad %8 %457 -%470 = OpLoad %8 %457 -%471 = OpSDiv %8 %469 %470 -OpStore %457 %471 -%472 = OpLoad %8 %457 -%473 = OpSRem %8 %472 %7 -OpStore %457 %473 -%474 = OpLoad %8 %457 -%475 = OpBitwiseAnd %8 %474 %11 -OpStore %457 %475 -%476 = OpLoad %8 %457 -%477 = OpBitwiseOr %8 %476 %11 -OpStore %457 %477 -%478 = OpLoad %8 %457 -%479 = OpBitwiseXor %8 %478 %11 -OpStore %457 %479 -%480 = OpLoad %8 %457 -%481 = OpShiftLeftLogical %8 %480 %24 -OpStore %457 %481 -%482 = OpLoad %8 %457 -%483 = OpShiftRightArithmetic %8 %482 %25 -OpStore %457 %483 -%484 = OpLoad %8 %457 -%485 = OpIAdd %8 %484 %7 -OpStore %457 %485 -%486 = OpLoad %8 %457 -%487 = OpISub %8 %486 %7 -OpStore %457 %487 +%461 = OpFunction %2 None %134 +%460 = OpLabel +%458 = OpVariable %459 Function %7 +OpBranch %462 +%462 = OpLabel +%463 = OpLoad %8 %458 +%464 = OpIAdd %8 %463 %7 +OpStore %458 %464 +%465 = OpLoad %8 %458 +%466 = OpISub %8 %465 %7 +OpStore %458 %466 +%467 = OpLoad %8 %458 +%468 = OpLoad %8 %458 +%469 = OpIMul %8 %467 %468 +OpStore %458 %469 +%470 = OpLoad %8 %458 +%471 = OpLoad %8 %458 +%472 = OpSDiv %8 %470 %471 +OpStore %458 %472 +%473 = OpLoad %8 %458 +%474 = OpSRem %8 %473 %7 +OpStore %458 %474 +%475 = OpLoad %8 %458 +%476 = OpBitwiseAnd %8 %475 %11 +OpStore %458 %476 +%477 = OpLoad %8 %458 +%478 = OpBitwiseOr %8 %477 %11 +OpStore %458 %478 +%479 = OpLoad %8 %458 +%480 = OpBitwiseXor %8 %479 %11 +OpStore %458 %480 +%481 = OpLoad %8 %458 +%482 = OpShiftLeftLogical %8 %481 %24 +OpStore %458 %482 +%483 = OpLoad %8 %458 +%484 = OpShiftRightArithmetic %8 %483 %25 +OpStore %458 %484 +%485 = OpLoad %8 %458 +%486 = OpIAdd %8 %485 %7 +OpStore %458 %486 +%487 = OpLoad %8 %458 +%488 = OpISub %8 %487 %7 +OpStore %458 %488 OpReturn OpFunctionEnd -%489 = OpFunction %2 None %133 -%488 = OpLabel -OpBranch %490 -%490 = OpLabel -%491 = OpFunctionCall %26 %55 -%492 = OpFunctionCall %26 %80 -%493 = OpVectorShuffle %29 %40 %40 0 1 2 -%494 = OpFunctionCall %29 %97 %493 -%495 = OpFunctionCall %4 %109 -%496 = OpFunctionCall %2 %132 -%497 = OpFunctionCall %2 %150 -%498 = OpFunctionCall %2 %334 -%499 = OpFunctionCall %2 %383 -%500 = OpFunctionCall %2 %460 +%490 = OpFunction %2 None %134 +%489 = OpLabel +OpBranch %491 +%491 = OpLabel +%492 = OpFunctionCall %26 %55 +%493 = OpFunctionCall %26 %80 +%494 = OpVectorShuffle %29 %40 %40 0 1 2 +%495 = OpFunctionCall %29 %97 %494 +%496 = OpFunctionCall %4 %110 +%497 = OpFunctionCall %2 %133 +%498 = OpFunctionCall %2 %151 +%499 = OpFunctionCall %2 %335 +%500 = OpFunctionCall %2 %384 +%501 = OpFunctionCall %2 %461 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index 968720f9d..81a17b558 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 41 +; Bound: 42 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -12,13 +12,13 @@ OpMemberName %8 0 "arr" OpName %8 "DynamicArray" OpName %11 "dynamic_array" OpName %12 "v" -OpName %15 "f" -OpName %22 "i" -OpName %23 "v" -OpName %24 "index_unsized" -OpName %33 "i" -OpName %34 "v" -OpName %35 "index_dynamic_array" +OpName %16 "f" +OpName %23 "i" +OpName %24 "v" +OpName %25 "index_unsized" +OpName %34 "i" +OpName %35 "v" +OpName %36 "index_dynamic_array" OpDecorate %7 ArrayStride 4 OpMemberDecorate %8 0 Offset 0 OpDecorate %11 DescriptorSet 0 @@ -35,43 +35,44 @@ OpDecorate %8 Block %10 = OpTypePointer StorageBuffer %7 %11 = OpVariable %9 StorageBuffer %13 = OpTypePointer Function %5 -%16 = OpTypeFunction %2 -%18 = OpTypePointer Function %4 -%19 = OpConstant %6 0 -%25 = OpTypeFunction %2 %4 %6 -%27 = OpTypePointer StorageBuffer %6 -%15 = OpFunction %2 None %16 -%14 = OpLabel -%12 = OpVariable %13 Function -OpBranch %17 -%17 = OpLabel -%20 = OpAccessChain %18 %12 %19 -OpStore %20 %3 +%14 = OpConstantNull %5 +%17 = OpTypeFunction %2 +%19 = OpTypePointer Function %4 +%20 = OpConstant %6 0 +%26 = OpTypeFunction %2 %4 %6 +%28 = OpTypePointer StorageBuffer %6 +%16 = OpFunction %2 None %17 +%15 = OpLabel +%12 = OpVariable %13 Function %14 +OpBranch %18 +%18 = OpLabel +%21 = OpAccessChain %19 %12 %20 +OpStore %21 %3 OpReturn OpFunctionEnd -%24 = OpFunction %2 None %25 -%22 = OpFunctionParameter %4 -%23 = OpFunctionParameter %6 -%21 = OpLabel -OpBranch %26 -%26 = OpLabel -%28 = OpAccessChain %27 %11 %19 %22 -%29 = OpLoad %6 %28 -%30 = OpIAdd %6 %29 %23 -%31 = OpAccessChain %27 %11 %19 %22 -OpStore %31 %30 +%25 = OpFunction %2 None %26 +%23 = OpFunctionParameter %4 +%24 = OpFunctionParameter %6 +%22 = OpLabel +OpBranch %27 +%27 = OpLabel +%29 = OpAccessChain %28 %11 %20 %23 +%30 = OpLoad %6 %29 +%31 = OpIAdd %6 %30 %24 +%32 = OpAccessChain %28 %11 %20 %23 +OpStore %32 %31 OpReturn OpFunctionEnd -%35 = OpFunction %2 None %25 -%33 = OpFunctionParameter %4 -%34 = OpFunctionParameter %6 -%32 = OpLabel -OpBranch %36 -%36 = OpLabel -%37 = OpAccessChain %27 %11 %19 %33 -%38 = OpLoad %6 %37 -%39 = OpIAdd %6 %38 %34 -%40 = OpAccessChain %27 %11 %19 %33 -OpStore %40 %39 +%36 = OpFunction %2 None %26 +%34 = OpFunctionParameter %4 +%35 = OpFunctionParameter %6 +%33 = OpLabel +OpBranch %37 +%37 = OpLabel +%38 = OpAccessChain %28 %11 %20 %34 +%39 = OpLoad %6 %38 +%40 = OpIAdd %6 %39 %35 +%41 = OpAccessChain %28 %11 %20 %34 +OpStore %41 %40 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index 685acfeaa..c082d3d46 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 99 +; Bound: 101 OpCapability Shader OpCapability ImageQuery OpCapability Linkage @@ -18,11 +18,11 @@ OpName %26 "in_uniform" OpName %29 "image_2d_array" OpName %31 "in_workgroup" OpName %33 "in_private" -OpName %35 "in_function" -OpName %38 "c" -OpName %39 "i" -OpName %40 "l" -OpName %41 "mock_function" +OpName %36 "in_function" +OpName %40 "c" +OpName %41 "i" +OpName %42 "l" +OpName %43 "mock_function" OpDecorate %14 ArrayStride 16 OpMemberDecorate %15 0 Offset 0 OpDecorate %16 ArrayStride 16 @@ -73,76 +73,78 @@ OpDecorate %29 Binding 2 %32 = OpTypePointer Workgroup %19 %31 = OpVariable %32 Workgroup %34 = OpTypePointer Private %20 -%33 = OpVariable %34 Private -%36 = OpTypePointer Function %22 -%42 = OpTypeFunction %13 %21 %4 %4 -%43 = OpTypePointer StorageBuffer %15 -%45 = OpTypeInt 32 0 -%44 = OpConstant %45 0 -%47 = OpTypePointer Uniform %17 -%54 = OpTypePointer StorageBuffer %14 -%55 = OpTypePointer StorageBuffer %13 -%58 = OpTypePointer Uniform %16 -%59 = OpTypePointer Uniform %13 -%63 = OpTypeVector %4 3 -%65 = OpTypeBool -%66 = OpConstantNull %13 -%72 = OpTypeVector %65 3 -%79 = OpTypePointer Workgroup %10 -%80 = OpConstant %45 29 -%86 = OpTypePointer Private %10 -%87 = OpConstant %45 39 -%93 = OpTypePointer Function %13 -%94 = OpConstant %45 1 -%41 = OpFunction %13 None %42 -%38 = OpFunctionParameter %21 -%39 = OpFunctionParameter %4 -%40 = OpFunctionParameter %4 -%37 = OpLabel -%35 = OpVariable %36 Function -%46 = OpAccessChain %43 %23 %44 -%48 = OpAccessChain %47 %26 %44 -%49 = OpLoad %18 %29 -OpBranch %50 -%50 = OpLabel -%51 = OpCompositeConstruct %13 %9 %11 %11 %12 -%52 = OpCompositeConstruct %13 %11 %9 %11 %12 -%53 = OpCompositeConstruct %22 %51 %52 -OpStore %35 %53 -%56 = OpAccessChain %55 %46 %44 %39 -%57 = OpLoad %13 %56 -%60 = OpAccessChain %59 %48 %44 %39 -%61 = OpLoad %13 %60 -%62 = OpFAdd %13 %57 %61 -%64 = OpCompositeConstruct %63 %38 %39 -%67 = OpImageQueryLevels %4 %49 -%68 = OpULessThan %65 %40 %67 -OpSelectionMerge %69 None -OpBranchConditional %68 %70 %69 -%70 = OpLabel -%71 = OpImageQuerySizeLod %63 %49 %40 -%73 = OpULessThan %72 %64 %71 -%74 = OpAll %65 %73 -OpBranchConditional %74 %75 %69 -%75 = OpLabel -%76 = OpImageFetch %13 %49 %64 Lod %40 -OpBranch %69 -%69 = OpLabel -%77 = OpPhi %13 %66 %50 %66 %70 %76 %75 -%78 = OpFAdd %13 %62 %77 -%81 = OpExtInst %45 %1 UMin %39 %80 -%82 = OpAccessChain %79 %31 %81 -%83 = OpLoad %10 %82 -%84 = OpCompositeConstruct %13 %83 %83 %83 %83 -%85 = OpFAdd %13 %78 %84 -%88 = OpExtInst %45 %1 UMin %39 %87 -%89 = OpAccessChain %86 %33 %88 -%90 = OpLoad %10 %89 -%91 = OpCompositeConstruct %13 %90 %90 %90 %90 -%92 = OpFAdd %13 %85 %91 -%95 = OpExtInst %45 %1 UMin %39 %94 -%96 = OpAccessChain %93 %35 %95 -%97 = OpLoad %13 %96 -%98 = OpFAdd %13 %92 %97 -OpReturnValue %98 +%35 = OpConstantNull %20 +%33 = OpVariable %34 Private %35 +%37 = OpTypePointer Function %22 +%38 = OpConstantNull %22 +%44 = OpTypeFunction %13 %21 %4 %4 +%45 = OpTypePointer StorageBuffer %15 +%47 = OpTypeInt 32 0 +%46 = OpConstant %47 0 +%49 = OpTypePointer Uniform %17 +%56 = OpTypePointer StorageBuffer %14 +%57 = OpTypePointer StorageBuffer %13 +%60 = OpTypePointer Uniform %16 +%61 = OpTypePointer Uniform %13 +%65 = OpTypeVector %4 3 +%67 = OpTypeBool +%68 = OpConstantNull %13 +%74 = OpTypeVector %67 3 +%81 = OpTypePointer Workgroup %10 +%82 = OpConstant %47 29 +%88 = OpTypePointer Private %10 +%89 = OpConstant %47 39 +%95 = OpTypePointer Function %13 +%96 = OpConstant %47 1 +%43 = OpFunction %13 None %44 +%40 = OpFunctionParameter %21 +%41 = OpFunctionParameter %4 +%42 = OpFunctionParameter %4 +%39 = OpLabel +%36 = OpVariable %37 Function %38 +%48 = OpAccessChain %45 %23 %46 +%50 = OpAccessChain %49 %26 %46 +%51 = OpLoad %18 %29 +OpBranch %52 +%52 = OpLabel +%53 = OpCompositeConstruct %13 %9 %11 %11 %12 +%54 = OpCompositeConstruct %13 %11 %9 %11 %12 +%55 = OpCompositeConstruct %22 %53 %54 +OpStore %36 %55 +%58 = OpAccessChain %57 %48 %46 %41 +%59 = OpLoad %13 %58 +%62 = OpAccessChain %61 %50 %46 %41 +%63 = OpLoad %13 %62 +%64 = OpFAdd %13 %59 %63 +%66 = OpCompositeConstruct %65 %40 %41 +%69 = OpImageQueryLevels %4 %51 +%70 = OpULessThan %67 %42 %69 +OpSelectionMerge %71 None +OpBranchConditional %70 %72 %71 +%72 = OpLabel +%73 = OpImageQuerySizeLod %65 %51 %42 +%75 = OpULessThan %74 %66 %73 +%76 = OpAll %67 %75 +OpBranchConditional %76 %77 %71 +%77 = OpLabel +%78 = OpImageFetch %13 %51 %66 Lod %42 +OpBranch %71 +%71 = OpLabel +%79 = OpPhi %13 %68 %52 %68 %72 %78 %77 +%80 = OpFAdd %13 %64 %79 +%83 = OpExtInst %47 %1 UMin %41 %82 +%84 = OpAccessChain %81 %31 %83 +%85 = OpLoad %10 %84 +%86 = OpCompositeConstruct %13 %85 %85 %85 %85 +%87 = OpFAdd %13 %80 %86 +%90 = OpExtInst %47 %1 UMin %41 %89 +%91 = OpAccessChain %88 %33 %90 +%92 = OpLoad %10 %91 +%93 = OpCompositeConstruct %13 %92 %92 %92 %92 +%94 = OpFAdd %13 %87 %93 +%97 = OpExtInst %47 %1 UMin %41 %96 +%98 = OpAccessChain %95 %36 %97 +%99 = OpLoad %13 %98 +%100 = OpFAdd %13 %94 %99 +OpReturnValue %100 OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index aeb85c96b..30829d28a 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 261 +; Bound: 262 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %93 "vs_main" %83 %86 %88 %90 %92 -OpEntryPoint Fragment %147 "fs_main" %138 %141 %144 %146 -OpEntryPoint Fragment %211 "fs_main_without_storage" %204 %206 %208 %210 -OpExecutionMode %147 OriginUpperLeft -OpExecutionMode %211 OriginUpperLeft +OpEntryPoint Vertex %94 "vs_main" %84 %87 %89 %91 %93 +OpEntryPoint Fragment %148 "fs_main" %139 %142 %145 %147 +OpEntryPoint Fragment %212 "fs_main_without_storage" %205 %207 %209 %211 +OpExecutionMode %148 OriginUpperLeft +OpExecutionMode %212 OriginUpperLeft OpSource GLSL 450 OpName %11 "c_max_lights" OpMemberName %18 0 "view_proj" @@ -38,24 +38,24 @@ OpName %48 "light_id" OpName %49 "homogeneous_coords" OpName %50 "fetch_shadow" OpName %80 "out" -OpName %83 "position" -OpName %86 "normal" -OpName %88 "proj_position" -OpName %90 "world_normal" -OpName %92 "world_position" -OpName %93 "vs_main" -OpName %133 "color" -OpName %134 "i" -OpName %138 "proj_position" -OpName %141 "world_normal" -OpName %144 "world_position" -OpName %147 "fs_main" -OpName %200 "color" -OpName %201 "i" -OpName %204 "proj_position" -OpName %206 "world_normal" -OpName %208 "world_position" -OpName %211 "fs_main_without_storage" +OpName %84 "position" +OpName %87 "normal" +OpName %89 "proj_position" +OpName %91 "world_normal" +OpName %93 "world_position" +OpName %94 "vs_main" +OpName %134 "color" +OpName %135 "i" +OpName %139 "proj_position" +OpName %142 "world_normal" +OpName %145 "world_position" +OpName %148 "fs_main" +OpName %201 "color" +OpName %202 "i" +OpName %205 "proj_position" +OpName %207 "world_normal" +OpName %209 "world_position" +OpName %212 "fs_main_without_storage" OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %18 0 ColMajor OpMemberDecorate %18 0 MatrixStride 16 @@ -95,21 +95,21 @@ OpDecorate %43 DescriptorSet 0 OpDecorate %43 Binding 2 OpDecorate %45 DescriptorSet 0 OpDecorate %45 Binding 3 -OpDecorate %83 Location 0 -OpDecorate %83 Flat -OpDecorate %86 Location 1 -OpDecorate %86 Flat -OpDecorate %88 BuiltIn Position -OpDecorate %90 Location 0 -OpDecorate %92 Location 1 -OpDecorate %138 BuiltIn FragCoord -OpDecorate %141 Location 0 -OpDecorate %144 Location 1 -OpDecorate %146 Location 0 -OpDecorate %204 BuiltIn FragCoord -OpDecorate %206 Location 0 -OpDecorate %208 Location 1 -OpDecorate %210 Location 0 +OpDecorate %84 Location 0 +OpDecorate %84 Flat +OpDecorate %87 Location 1 +OpDecorate %87 Flat +OpDecorate %89 BuiltIn Position +OpDecorate %91 Location 0 +OpDecorate %93 Location 1 +OpDecorate %139 BuiltIn FragCoord +OpDecorate %142 Location 0 +OpDecorate %145 Location 1 +OpDecorate %147 Location 0 +OpDecorate %205 BuiltIn FragCoord +OpDecorate %207 Location 0 +OpDecorate %209 Location 1 +OpDecorate %211 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -163,37 +163,38 @@ OpDecorate %210 Location 0 %60 = OpTypeBool %75 = OpTypeSampledImage %27 %81 = OpTypePointer Function %21 -%84 = OpTypePointer Input %22 -%83 = OpVariable %84 Input -%86 = OpVariable %84 Input -%89 = OpTypePointer Output %16 -%88 = OpVariable %89 Output -%91 = OpTypePointer Output %20 -%90 = OpVariable %91 Output -%92 = OpVariable %89 Output -%94 = OpTypeFunction %2 -%98 = OpTypePointer Uniform %15 -%105 = OpTypePointer Function %20 -%113 = OpTypeVector %4 3 -%118 = OpTypePointer Function %16 -%119 = OpConstant %12 2 -%127 = OpTypePointer Output %6 -%135 = OpTypePointer Function %12 -%139 = OpTypePointer Input %16 -%138 = OpVariable %139 Input -%142 = OpTypePointer Input %20 -%141 = OpVariable %142 Input -%144 = OpVariable %139 Input -%146 = OpVariable %89 Output -%161 = OpTypePointer Uniform %17 -%162 = OpTypePointer Uniform %12 -%170 = OpTypePointer StorageBuffer %24 -%196 = OpTypePointer Uniform %16 -%204 = OpVariable %139 Input -%206 = OpVariable %142 Input -%208 = OpVariable %139 Input -%210 = OpVariable %89 Output -%232 = OpTypePointer Uniform %24 +%82 = OpConstantNull %21 +%85 = OpTypePointer Input %22 +%84 = OpVariable %85 Input +%87 = OpVariable %85 Input +%90 = OpTypePointer Output %16 +%89 = OpVariable %90 Output +%92 = OpTypePointer Output %20 +%91 = OpVariable %92 Output +%93 = OpVariable %90 Output +%95 = OpTypeFunction %2 +%99 = OpTypePointer Uniform %15 +%106 = OpTypePointer Function %20 +%114 = OpTypeVector %4 3 +%119 = OpTypePointer Function %16 +%120 = OpConstant %12 2 +%128 = OpTypePointer Output %6 +%136 = OpTypePointer Function %12 +%140 = OpTypePointer Input %16 +%139 = OpVariable %140 Input +%143 = OpTypePointer Input %20 +%142 = OpVariable %143 Input +%145 = OpVariable %140 Input +%147 = OpVariable %90 Output +%162 = OpTypePointer Uniform %17 +%163 = OpTypePointer Uniform %12 +%171 = OpTypePointer StorageBuffer %24 +%197 = OpTypePointer Uniform %16 +%205 = OpVariable %140 Input +%207 = OpVariable %143 Input +%209 = OpVariable %140 Input +%211 = OpVariable %90 Output +%233 = OpTypePointer Uniform %24 %50 = OpFunction %6 None %51 %48 = OpFunctionParameter %12 %49 = OpFunctionParameter %16 @@ -226,190 +227,190 @@ OpReturnValue %7 %79 = OpImageSampleDrefExplicitLod %6 %78 %77 %74 Lod %5 OpReturnValue %79 OpFunctionEnd -%93 = OpFunction %2 None %94 -%82 = OpLabel -%80 = OpVariable %81 Function -%85 = OpLoad %22 %83 -%87 = OpLoad %22 %86 -%95 = OpAccessChain %55 %31 %13 -%96 = OpAccessChain %54 %34 %13 -OpBranch %97 -%97 = OpLabel -%99 = OpAccessChain %98 %96 %13 -%100 = OpLoad %15 %99 -%101 = OpAccessChain %98 %96 %13 -%102 = OpLoad %15 %101 -%103 = OpConvertSToF %16 %85 -%104 = OpMatrixTimesVector %16 %102 %103 -%106 = OpCompositeExtract %16 %100 0 -%107 = OpVectorShuffle %20 %106 %106 0 1 2 -%108 = OpCompositeExtract %16 %100 1 -%109 = OpVectorShuffle %20 %108 %108 0 1 2 -%110 = OpCompositeExtract %16 %100 2 -%111 = OpVectorShuffle %20 %110 %110 0 1 2 -%112 = OpCompositeConstruct %23 %107 %109 %111 -%114 = OpVectorShuffle %113 %87 %87 0 1 2 -%115 = OpConvertSToF %20 %114 -%116 = OpMatrixTimesVector %20 %112 %115 -%117 = OpAccessChain %105 %80 %14 -OpStore %117 %116 -%120 = OpAccessChain %118 %80 %119 -OpStore %120 %104 -%121 = OpAccessChain %98 %95 %13 -%122 = OpLoad %15 %121 -%123 = OpMatrixTimesVector %16 %122 %104 -%124 = OpAccessChain %118 %80 %13 -OpStore %124 %123 -%125 = OpLoad %21 %80 -%126 = OpCompositeExtract %16 %125 0 -OpStore %88 %126 -%128 = OpAccessChain %127 %88 %14 -%129 = OpLoad %6 %128 -%130 = OpFNegate %6 %129 -OpStore %128 %130 -%131 = OpCompositeExtract %20 %125 1 -OpStore %90 %131 -%132 = OpCompositeExtract %16 %125 2 -OpStore %92 %132 +%94 = OpFunction %2 None %95 +%83 = OpLabel +%80 = OpVariable %81 Function %82 +%86 = OpLoad %22 %84 +%88 = OpLoad %22 %87 +%96 = OpAccessChain %55 %31 %13 +%97 = OpAccessChain %54 %34 %13 +OpBranch %98 +%98 = OpLabel +%100 = OpAccessChain %99 %97 %13 +%101 = OpLoad %15 %100 +%102 = OpAccessChain %99 %97 %13 +%103 = OpLoad %15 %102 +%104 = OpConvertSToF %16 %86 +%105 = OpMatrixTimesVector %16 %103 %104 +%107 = OpCompositeExtract %16 %101 0 +%108 = OpVectorShuffle %20 %107 %107 0 1 2 +%109 = OpCompositeExtract %16 %101 1 +%110 = OpVectorShuffle %20 %109 %109 0 1 2 +%111 = OpCompositeExtract %16 %101 2 +%112 = OpVectorShuffle %20 %111 %111 0 1 2 +%113 = OpCompositeConstruct %23 %108 %110 %112 +%115 = OpVectorShuffle %114 %88 %88 0 1 2 +%116 = OpConvertSToF %20 %115 +%117 = OpMatrixTimesVector %20 %113 %116 +%118 = OpAccessChain %106 %80 %14 +OpStore %118 %117 +%121 = OpAccessChain %119 %80 %120 +OpStore %121 %105 +%122 = OpAccessChain %99 %96 %13 +%123 = OpLoad %15 %122 +%124 = OpMatrixTimesVector %16 %123 %105 +%125 = OpAccessChain %119 %80 %13 +OpStore %125 %124 +%126 = OpLoad %21 %80 +%127 = OpCompositeExtract %16 %126 0 +OpStore %89 %127 +%129 = OpAccessChain %128 %89 %14 +%130 = OpLoad %6 %129 +%131 = OpFNegate %6 %130 +OpStore %129 %131 +%132 = OpCompositeExtract %20 %126 1 +OpStore %91 %132 +%133 = OpCompositeExtract %16 %126 2 +OpStore %93 %133 OpReturn OpFunctionEnd -%147 = OpFunction %2 None %94 -%136 = OpLabel -%133 = OpVariable %105 Function %30 -%134 = OpVariable %135 Function %13 -%140 = OpLoad %16 %138 -%143 = OpLoad %20 %141 -%145 = OpLoad %16 %144 -%137 = OpCompositeConstruct %21 %140 %143 %145 -%148 = OpAccessChain %55 %31 %13 -%149 = OpAccessChain %54 %34 %13 -%150 = OpAccessChain %57 %37 %13 -%151 = OpLoad %27 %43 -%152 = OpLoad %28 %45 -OpBranch %153 -%153 = OpLabel -%154 = OpCompositeExtract %20 %137 1 -%155 = OpExtInst %20 %1 Normalize %154 -OpBranch %156 -%156 = OpLabel -OpLoopMerge %157 %159 None -OpBranch %158 -%158 = OpLabel -%160 = OpLoad %12 %134 -%163 = OpAccessChain %162 %148 %14 %13 -%164 = OpLoad %12 %163 -%165 = OpExtInst %12 %1 UMin %164 %11 -%166 = OpULessThan %60 %160 %165 -OpSelectionMerge %167 None -OpBranchConditional %166 %167 %168 -%168 = OpLabel +%148 = OpFunction %2 None %95 +%137 = OpLabel +%134 = OpVariable %106 Function %30 +%135 = OpVariable %136 Function %13 +%141 = OpLoad %16 %139 +%144 = OpLoad %20 %142 +%146 = OpLoad %16 %145 +%138 = OpCompositeConstruct %21 %141 %144 %146 +%149 = OpAccessChain %55 %31 %13 +%150 = OpAccessChain %54 %34 %13 +%151 = OpAccessChain %57 %37 %13 +%152 = OpLoad %27 %43 +%153 = OpLoad %28 %45 +OpBranch %154 +%154 = OpLabel +%155 = OpCompositeExtract %20 %138 1 +%156 = OpExtInst %20 %1 Normalize %155 OpBranch %157 -%167 = OpLabel -%169 = OpLoad %12 %134 -%171 = OpAccessChain %170 %150 %169 -%172 = OpLoad %24 %171 -%173 = OpLoad %12 %134 -%174 = OpCompositeExtract %15 %172 0 -%175 = OpCompositeExtract %16 %137 2 -%176 = OpMatrixTimesVector %16 %174 %175 -%177 = OpFunctionCall %6 %50 %173 %176 -%178 = OpCompositeExtract %16 %172 1 -%179 = OpVectorShuffle %20 %178 %178 0 1 2 -%180 = OpCompositeExtract %16 %137 2 -%181 = OpVectorShuffle %20 %180 %180 0 1 2 -%182 = OpFSub %20 %179 %181 -%183 = OpExtInst %20 %1 Normalize %182 -%184 = OpDot %6 %155 %183 -%185 = OpExtInst %6 %1 FMax %5 %184 -%186 = OpLoad %20 %133 -%187 = OpFMul %6 %177 %185 -%188 = OpCompositeExtract %16 %172 2 -%189 = OpVectorShuffle %20 %188 %188 0 1 2 -%190 = OpVectorTimesScalar %20 %189 %187 -%191 = OpFAdd %20 %186 %190 -OpStore %133 %191 +%157 = OpLabel +OpLoopMerge %158 %160 None OpBranch %159 %159 = OpLabel -%192 = OpLoad %12 %134 -%193 = OpIAdd %12 %192 %14 -OpStore %134 %193 -OpBranch %156 -%157 = OpLabel -%194 = OpLoad %20 %133 -%195 = OpCompositeConstruct %16 %194 %7 -%197 = OpAccessChain %196 %149 %14 -%198 = OpLoad %16 %197 -%199 = OpFMul %16 %195 %198 -OpStore %146 %199 +%161 = OpLoad %12 %135 +%164 = OpAccessChain %163 %149 %14 %13 +%165 = OpLoad %12 %164 +%166 = OpExtInst %12 %1 UMin %165 %11 +%167 = OpULessThan %60 %161 %166 +OpSelectionMerge %168 None +OpBranchConditional %167 %168 %169 +%169 = OpLabel +OpBranch %158 +%168 = OpLabel +%170 = OpLoad %12 %135 +%172 = OpAccessChain %171 %151 %170 +%173 = OpLoad %24 %172 +%174 = OpLoad %12 %135 +%175 = OpCompositeExtract %15 %173 0 +%176 = OpCompositeExtract %16 %138 2 +%177 = OpMatrixTimesVector %16 %175 %176 +%178 = OpFunctionCall %6 %50 %174 %177 +%179 = OpCompositeExtract %16 %173 1 +%180 = OpVectorShuffle %20 %179 %179 0 1 2 +%181 = OpCompositeExtract %16 %138 2 +%182 = OpVectorShuffle %20 %181 %181 0 1 2 +%183 = OpFSub %20 %180 %182 +%184 = OpExtInst %20 %1 Normalize %183 +%185 = OpDot %6 %156 %184 +%186 = OpExtInst %6 %1 FMax %5 %185 +%187 = OpLoad %20 %134 +%188 = OpFMul %6 %178 %186 +%189 = OpCompositeExtract %16 %173 2 +%190 = OpVectorShuffle %20 %189 %189 0 1 2 +%191 = OpVectorTimesScalar %20 %190 %188 +%192 = OpFAdd %20 %187 %191 +OpStore %134 %192 +OpBranch %160 +%160 = OpLabel +%193 = OpLoad %12 %135 +%194 = OpIAdd %12 %193 %14 +OpStore %135 %194 +OpBranch %157 +%158 = OpLabel +%195 = OpLoad %20 %134 +%196 = OpCompositeConstruct %16 %195 %7 +%198 = OpAccessChain %197 %150 %14 +%199 = OpLoad %16 %198 +%200 = OpFMul %16 %196 %199 +OpStore %147 %200 OpReturn OpFunctionEnd -%211 = OpFunction %2 None %94 -%202 = OpLabel -%200 = OpVariable %105 Function %30 -%201 = OpVariable %135 Function %13 -%205 = OpLoad %16 %204 -%207 = OpLoad %20 %206 -%209 = OpLoad %16 %208 -%203 = OpCompositeConstruct %21 %205 %207 %209 -%212 = OpAccessChain %55 %31 %13 -%213 = OpAccessChain %54 %34 %13 -%214 = OpAccessChain %56 %40 %13 -%215 = OpLoad %27 %43 -%216 = OpLoad %28 %45 -OpBranch %217 -%217 = OpLabel -%218 = OpCompositeExtract %20 %203 1 -%219 = OpExtInst %20 %1 Normalize %218 -OpBranch %220 -%220 = OpLabel -OpLoopMerge %221 %223 None -OpBranch %222 -%222 = OpLabel -%224 = OpLoad %12 %201 -%225 = OpAccessChain %162 %212 %14 %13 -%226 = OpLoad %12 %225 -%227 = OpExtInst %12 %1 UMin %226 %11 -%228 = OpULessThan %60 %224 %227 -OpSelectionMerge %229 None -OpBranchConditional %228 %229 %230 -%230 = OpLabel +%212 = OpFunction %2 None %95 +%203 = OpLabel +%201 = OpVariable %106 Function %30 +%202 = OpVariable %136 Function %13 +%206 = OpLoad %16 %205 +%208 = OpLoad %20 %207 +%210 = OpLoad %16 %209 +%204 = OpCompositeConstruct %21 %206 %208 %210 +%213 = OpAccessChain %55 %31 %13 +%214 = OpAccessChain %54 %34 %13 +%215 = OpAccessChain %56 %40 %13 +%216 = OpLoad %27 %43 +%217 = OpLoad %28 %45 +OpBranch %218 +%218 = OpLabel +%219 = OpCompositeExtract %20 %204 1 +%220 = OpExtInst %20 %1 Normalize %219 OpBranch %221 -%229 = OpLabel -%231 = OpLoad %12 %201 -%233 = OpAccessChain %232 %214 %231 -%234 = OpLoad %24 %233 -%235 = OpLoad %12 %201 -%236 = OpCompositeExtract %15 %234 0 -%237 = OpCompositeExtract %16 %203 2 -%238 = OpMatrixTimesVector %16 %236 %237 -%239 = OpFunctionCall %6 %50 %235 %238 -%240 = OpCompositeExtract %16 %234 1 -%241 = OpVectorShuffle %20 %240 %240 0 1 2 -%242 = OpCompositeExtract %16 %203 2 -%243 = OpVectorShuffle %20 %242 %242 0 1 2 -%244 = OpFSub %20 %241 %243 -%245 = OpExtInst %20 %1 Normalize %244 -%246 = OpDot %6 %219 %245 -%247 = OpExtInst %6 %1 FMax %5 %246 -%248 = OpLoad %20 %200 -%249 = OpFMul %6 %239 %247 -%250 = OpCompositeExtract %16 %234 2 -%251 = OpVectorShuffle %20 %250 %250 0 1 2 -%252 = OpVectorTimesScalar %20 %251 %249 -%253 = OpFAdd %20 %248 %252 -OpStore %200 %253 +%221 = OpLabel +OpLoopMerge %222 %224 None OpBranch %223 %223 = OpLabel -%254 = OpLoad %12 %201 -%255 = OpIAdd %12 %254 %14 -OpStore %201 %255 -OpBranch %220 -%221 = OpLabel -%256 = OpLoad %20 %200 -%257 = OpCompositeConstruct %16 %256 %7 -%258 = OpAccessChain %196 %213 %14 -%259 = OpLoad %16 %258 -%260 = OpFMul %16 %257 %259 -OpStore %210 %260 +%225 = OpLoad %12 %202 +%226 = OpAccessChain %163 %213 %14 %13 +%227 = OpLoad %12 %226 +%228 = OpExtInst %12 %1 UMin %227 %11 +%229 = OpULessThan %60 %225 %228 +OpSelectionMerge %230 None +OpBranchConditional %229 %230 %231 +%231 = OpLabel +OpBranch %222 +%230 = OpLabel +%232 = OpLoad %12 %202 +%234 = OpAccessChain %233 %215 %232 +%235 = OpLoad %24 %234 +%236 = OpLoad %12 %202 +%237 = OpCompositeExtract %15 %235 0 +%238 = OpCompositeExtract %16 %204 2 +%239 = OpMatrixTimesVector %16 %237 %238 +%240 = OpFunctionCall %6 %50 %236 %239 +%241 = OpCompositeExtract %16 %235 1 +%242 = OpVectorShuffle %20 %241 %241 0 1 2 +%243 = OpCompositeExtract %16 %204 2 +%244 = OpVectorShuffle %20 %243 %243 0 1 2 +%245 = OpFSub %20 %242 %244 +%246 = OpExtInst %20 %1 Normalize %245 +%247 = OpDot %6 %220 %246 +%248 = OpExtInst %6 %1 FMax %5 %247 +%249 = OpLoad %20 %201 +%250 = OpFMul %6 %240 %248 +%251 = OpCompositeExtract %16 %235 2 +%252 = OpVectorShuffle %20 %251 %251 0 1 2 +%253 = OpVectorTimesScalar %20 %252 %250 +%254 = OpFAdd %20 %249 %253 +OpStore %201 %254 +OpBranch %224 +%224 = OpLabel +%255 = OpLoad %12 %202 +%256 = OpIAdd %12 %255 %14 +OpStore %202 %256 +OpBranch %221 +%222 = OpLabel +%257 = OpLoad %20 %201 +%258 = OpCompositeConstruct %16 %257 %7 +%259 = OpAccessChain %197 %214 %14 +%260 = OpLoad %16 %259 +%261 = OpFMul %16 %258 %260 +OpStore %211 %261 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/skybox.spvasm b/tests/out/spv/skybox.spvasm index 278ec0bb3..ca51a06dd 100644 --- a/tests/out/spv/skybox.spvasm +++ b/tests/out/spv/skybox.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 96 +; Bound: 98 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %37 "vs_main" %30 %33 %35 -OpEntryPoint Fragment %88 "fs_main" %81 %84 %87 -OpExecutionMode %88 OriginUpperLeft +OpEntryPoint Vertex %39 "vs_main" %32 %35 %37 +OpEntryPoint Fragment %90 "fs_main" %83 %86 %89 +OpExecutionMode %90 OriginUpperLeft OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpMemberDecorate %14 0 Offset 0 @@ -24,12 +24,12 @@ OpDecorate %22 DescriptorSet 0 OpDecorate %22 Binding 1 OpDecorate %24 DescriptorSet 0 OpDecorate %24 Binding 2 -OpDecorate %30 BuiltIn VertexIndex -OpDecorate %33 BuiltIn Position -OpDecorate %35 Location 0 -OpDecorate %81 BuiltIn FragCoord -OpDecorate %84 Location 0 -OpDecorate %87 Location 0 +OpDecorate %32 BuiltIn VertexIndex +OpDecorate %35 BuiltIn Position +OpDecorate %37 Location 0 +OpDecorate %83 BuiltIn FragCoord +OpDecorate %86 Location 0 +OpDecorate %89 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -55,83 +55,85 @@ OpDecorate %87 Location 0 %25 = OpTypePointer UniformConstant %18 %24 = OpVariable %25 UniformConstant %27 = OpTypePointer Function %4 -%31 = OpTypePointer Input %15 -%30 = OpVariable %31 Input -%34 = OpTypePointer Output %10 -%33 = OpVariable %34 Output -%36 = OpTypePointer Output %11 +%28 = OpConstantNull %4 +%30 = OpConstantNull %4 +%33 = OpTypePointer Input %15 +%32 = OpVariable %33 Input +%36 = OpTypePointer Output %10 %35 = OpVariable %36 Output -%38 = OpTypeFunction %2 -%39 = OpTypePointer Uniform %14 -%40 = OpConstant %15 0 -%56 = OpTypePointer Uniform %13 -%57 = OpTypePointer Uniform %10 -%58 = OpConstant %15 1 -%65 = OpConstant %15 2 -%82 = OpTypePointer Input %10 -%81 = OpVariable %82 Input -%85 = OpTypePointer Input %11 -%84 = OpVariable %85 Input -%87 = OpVariable %34 Output -%93 = OpTypeSampledImage %17 -%37 = OpFunction %2 None %38 -%29 = OpLabel -%26 = OpVariable %27 Function -%28 = OpVariable %27 Function -%32 = OpLoad %15 %30 -%41 = OpAccessChain %39 %19 %40 -OpBranch %42 -%42 = OpLabel -%43 = OpBitcast %4 %32 -%44 = OpSDiv %4 %43 %3 -OpStore %26 %44 -%45 = OpBitcast %4 %32 -%46 = OpBitwiseAnd %4 %45 %5 -OpStore %28 %46 -%47 = OpLoad %4 %26 -%48 = OpConvertSToF %7 %47 -%49 = OpFMul %7 %48 %6 -%50 = OpFSub %7 %49 %8 -%51 = OpLoad %4 %28 -%52 = OpConvertSToF %7 %51 -%53 = OpFMul %7 %52 %6 -%54 = OpFSub %7 %53 %8 -%55 = OpCompositeConstruct %10 %50 %54 %9 %8 -%59 = OpAccessChain %57 %41 %58 %40 -%60 = OpLoad %10 %59 -%61 = OpVectorShuffle %11 %60 %60 0 1 2 -%62 = OpAccessChain %57 %41 %58 %58 -%63 = OpLoad %10 %62 -%64 = OpVectorShuffle %11 %63 %63 0 1 2 -%66 = OpAccessChain %57 %41 %58 %65 -%67 = OpLoad %10 %66 -%68 = OpVectorShuffle %11 %67 %67 0 1 2 -%69 = OpCompositeConstruct %16 %61 %64 %68 -%70 = OpTranspose %16 %69 -%71 = OpAccessChain %56 %41 %40 -%72 = OpLoad %13 %71 -%73 = OpMatrixTimesVector %10 %72 %55 -%74 = OpVectorShuffle %11 %73 %73 0 1 2 -%75 = OpMatrixTimesVector %11 %70 %74 -%76 = OpCompositeConstruct %12 %55 %75 -%77 = OpCompositeExtract %10 %76 0 -OpStore %33 %77 -%78 = OpCompositeExtract %11 %76 1 -OpStore %35 %78 +%38 = OpTypePointer Output %11 +%37 = OpVariable %38 Output +%40 = OpTypeFunction %2 +%41 = OpTypePointer Uniform %14 +%42 = OpConstant %15 0 +%58 = OpTypePointer Uniform %13 +%59 = OpTypePointer Uniform %10 +%60 = OpConstant %15 1 +%67 = OpConstant %15 2 +%84 = OpTypePointer Input %10 +%83 = OpVariable %84 Input +%87 = OpTypePointer Input %11 +%86 = OpVariable %87 Input +%89 = OpVariable %36 Output +%95 = OpTypeSampledImage %17 +%39 = OpFunction %2 None %40 +%31 = OpLabel +%26 = OpVariable %27 Function %28 +%29 = OpVariable %27 Function %30 +%34 = OpLoad %15 %32 +%43 = OpAccessChain %41 %19 %42 +OpBranch %44 +%44 = OpLabel +%45 = OpBitcast %4 %34 +%46 = OpSDiv %4 %45 %3 +OpStore %26 %46 +%47 = OpBitcast %4 %34 +%48 = OpBitwiseAnd %4 %47 %5 +OpStore %29 %48 +%49 = OpLoad %4 %26 +%50 = OpConvertSToF %7 %49 +%51 = OpFMul %7 %50 %6 +%52 = OpFSub %7 %51 %8 +%53 = OpLoad %4 %29 +%54 = OpConvertSToF %7 %53 +%55 = OpFMul %7 %54 %6 +%56 = OpFSub %7 %55 %8 +%57 = OpCompositeConstruct %10 %52 %56 %9 %8 +%61 = OpAccessChain %59 %43 %60 %42 +%62 = OpLoad %10 %61 +%63 = OpVectorShuffle %11 %62 %62 0 1 2 +%64 = OpAccessChain %59 %43 %60 %60 +%65 = OpLoad %10 %64 +%66 = OpVectorShuffle %11 %65 %65 0 1 2 +%68 = OpAccessChain %59 %43 %60 %67 +%69 = OpLoad %10 %68 +%70 = OpVectorShuffle %11 %69 %69 0 1 2 +%71 = OpCompositeConstruct %16 %63 %66 %70 +%72 = OpTranspose %16 %71 +%73 = OpAccessChain %58 %43 %42 +%74 = OpLoad %13 %73 +%75 = OpMatrixTimesVector %10 %74 %57 +%76 = OpVectorShuffle %11 %75 %75 0 1 2 +%77 = OpMatrixTimesVector %11 %72 %76 +%78 = OpCompositeConstruct %12 %57 %77 +%79 = OpCompositeExtract %10 %78 0 +OpStore %35 %79 +%80 = OpCompositeExtract %11 %78 1 +OpStore %37 %80 OpReturn OpFunctionEnd -%88 = OpFunction %2 None %38 -%79 = OpLabel -%83 = OpLoad %10 %81 -%86 = OpLoad %11 %84 -%80 = OpCompositeConstruct %12 %83 %86 -%89 = OpLoad %17 %22 -%90 = OpLoad %18 %24 -OpBranch %91 -%91 = OpLabel -%92 = OpCompositeExtract %11 %80 1 -%94 = OpSampledImage %93 %89 %90 -%95 = OpImageSampleImplicitLod %10 %94 %92 -OpStore %87 %95 +%90 = OpFunction %2 None %40 +%81 = OpLabel +%85 = OpLoad %10 %83 +%88 = OpLoad %11 %86 +%82 = OpCompositeConstruct %12 %85 %88 +%91 = OpLoad %17 %22 +%92 = OpLoad %18 %24 +OpBranch %93 +%93 = OpLabel +%94 = OpCompositeExtract %11 %82 1 +%96 = OpSampledImage %95 %91 %92 +%97 = OpImageSampleImplicitLod %10 %96 %94 +OpStore %89 %97 OpReturn OpFunctionEnd \ No newline at end of file From b3d5e6d807560310fa514c0920c91c7f2cac974b Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 29 Apr 2022 21:31:06 +0200 Subject: [PATCH 1740/2212] [msl-out] zero init variables in function address space --- src/back/msl/writer.rs | 46 +++++++++++++++++++------------- tests/out/msl/access.msl | 6 ++--- tests/out/msl/binding-arrays.msl | 4 +-- tests/out/msl/bits.msl | 16 +++++------ tests/out/msl/boids.msl | 14 +++++----- tests/out/msl/collatz.msl | 2 +- tests/out/msl/control-flow.msl | 2 +- tests/out/msl/interpolate.msl | 2 +- tests/out/msl/operators.msl | 2 +- tests/out/msl/policy-mix.msl | 2 +- tests/out/msl/shadow.msl | 2 +- tests/out/msl/skybox.msl | 4 +-- 12 files changed, 56 insertions(+), 46 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index cae4b6b6b..870b9b76f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3269,15 +3269,20 @@ impl Writer { }; let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; write!(self.out, "{}{} {}", back::INDENT, ty_name, local_name)?; - if let Some(value) = local.init { - let coco = ConstantContext { - handle: value, - arena: &module.constants, - names: &self.names, - first_time: false, - }; - write!(self.out, " = {}", coco)?; - } + match local.init { + Some(value) => { + let coco = ConstantContext { + handle: value, + arena: &module.constants, + names: &self.names, + first_time: false, + }; + write!(self.out, " = {}", coco)?; + } + None => { + write!(self.out, " = {{}}")?; + } + }; writeln!(self.out, ";")?; } @@ -3801,15 +3806,20 @@ impl Writer { first_time: false, }; write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; - if let Some(value) = local.init { - let coco = ConstantContext { - handle: value, - arena: &module.constants, - names: &self.names, - first_time: false, - }; - write!(self.out, " = {}", coco)?; - } + match local.init { + Some(value) => { + let coco = ConstantContext { + handle: value, + arena: &module.constants, + names: &self.names, + first_time: false, + }; + write!(self.out, " = {}", coco)?; + } + None => { + write!(self.out, " = {{}}")?; + } + }; writeln!(self.out, ";")?; } diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 5bcdd7d49..7ee2d6c13 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -45,7 +45,7 @@ void test_matrix_within_struct_accesses( constant Baz& baz ) { int idx = 9; - Baz t; + Baz t = {}; int _e4 = idx; idx = _e4 - 1; metal::float3x2 unnamed = baz.m; @@ -103,7 +103,7 @@ vertex foo_vertOutput foo_vert( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo = 0.0; - type_16 c; + type_16 c = {}; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); @@ -139,7 +139,7 @@ kernel void atomics( device Bar& bar [[buffer(0)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - int tmp; + int tmp = {}; int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); int _e7 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e7; diff --git a/tests/out/msl/binding-arrays.msl b/tests/out/msl/binding-arrays.msl index 62e0bb6b1..ba3c3c8b0 100644 --- a/tests/out/msl/binding-arrays.msl +++ b/tests/out/msl/binding-arrays.msl @@ -37,9 +37,9 @@ fragment main_Output main_( ) { const FragmentIn fragment_in = { varyings.index }; int i1_ = 0; - metal::int2 i2_; + metal::int2 i2_ = {}; float v1_ = 0.0; - metal::float4 v4_; + metal::float4 v4_ = {}; uint uniform_index = uni.index; uint non_uniform_index = fragment_in.index; i2_ = metal::int2(0); diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index aa35b8c17..9c9eedaeb 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -8,15 +8,15 @@ using metal::uint; kernel void main_( ) { int i = 0; - metal::int2 i2_; - metal::int3 i3_; - metal::int4 i4_; + metal::int2 i2_ = {}; + metal::int3 i3_ = {}; + metal::int4 i4_ = {}; uint u = 0u; - metal::uint2 u2_; - metal::uint3 u3_; - metal::uint4 u4_; - metal::float2 f2_; - metal::float4 f4_; + metal::uint2 u2_ = {}; + metal::uint3 u3_ = {}; + metal::uint4 u4_ = {}; + metal::float2 f2_ = {}; + metal::float4 f4_ = {}; i2_ = metal::int2(0); i3_ = metal::int3(0); i4_ = metal::int4(0); diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index bcd80ca05..fd46d1f21 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -37,15 +37,15 @@ kernel void main_( , device Particles& particlesDst [[buffer(2)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(3)]] ) { - metal::float2 vPos; - metal::float2 vVel; - metal::float2 cMass; - metal::float2 cVel; - metal::float2 colVel; + metal::float2 vPos = {}; + metal::float2 vVel = {}; + metal::float2 cMass = {}; + metal::float2 cVel = {}; + metal::float2 colVel = {}; int cMassCount = 0; int cVelCount = 0; - metal::float2 pos; - metal::float2 vel; + metal::float2 pos = {}; + metal::float2 vel = {}; uint i = 0u; uint index = global_invocation_id.x; if (index >= NUM_PARTICLES) { diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index e0f8ece62..2189632d0 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -16,7 +16,7 @@ struct PrimeIndices { uint collatz_iterations( uint n_base ) { - uint n; + uint n = {}; uint i = 0u; n = n_base; while(true) { diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index 8fb23b5b7..e35d24d5f 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -49,7 +49,7 @@ struct main_Input { kernel void main_( metal::uint3 global_id [[thread_position_in_grid]] ) { - int pos; + int pos = {}; metal::threadgroup_barrier(metal::mem_flags::mem_device); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); switch(1) { diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl index 4dd84c623..5d8b67111 100644 --- a/tests/out/msl/interpolate.msl +++ b/tests/out/msl/interpolate.msl @@ -27,7 +27,7 @@ struct vert_mainOutput { }; vertex vert_mainOutput vert_main( ) { - FragmentInput out; + FragmentInput out = {}; out.position = metal::float4(2.0, 4.0, 5.0, 6.0); out._flat = 8u; out._linear = 27.0; diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index d47f543be..8cc741a4e 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -58,7 +58,7 @@ metal::float3 bool_cast( float constructors( ) { - Foo foo; + Foo foo = {}; foo = Foo {metal::float4(1.0), 1}; metal::float2x2 mat2comp = metal::float2x2(metal::float2(1.0, 0.0), metal::float2(0.0, 1.0)); metal::float4x4 mat4comp = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index b6b9b942b..430e36610 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -42,7 +42,7 @@ metal::float4 mock_function( threadgroup type_5 const& in_workgroup, thread type_6 const& in_private ) { - type_9 in_function; + type_9 in_function = {}; for(int _i=0; _i<2; ++_i) in_function.inner[_i] = type_9 {metal::float4(0.7070000171661377, 0.0, 0.0, 1.0), metal::float4(0.0, 0.7070000171661377, 0.0, 1.0)}.inner[_i]; metal::float4 _e22 = in_storage.a.inner[i]; metal::float4 _e25 = in_uniform.a.inner[i]; diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 5286b0bd0..651a89841 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -65,7 +65,7 @@ vertex vs_mainOutput vs_main( ) { const auto position = varyings.position; const auto normal = varyings.normal; - VertexOutput out; + VertexOutput out = {}; metal::float4x4 w = u_entity.world; metal::float4x4 _e7 = u_entity.world; metal::float4 world_pos = _e7 * static_cast(position); diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index bf8725043..c25770d4f 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -23,8 +23,8 @@ vertex vs_mainOutput vs_main( uint vertex_index [[vertex_id]] , constant Data& r_data [[buffer(0)]] ) { - int tmp1_; - int tmp2_; + int tmp1_ = {}; + int tmp2_ = {}; tmp1_ = static_cast(vertex_index) / 2; tmp2_ = static_cast(vertex_index) & 1; int _e10 = tmp1_; From 205ea6cc5c437fa42bafb75514387c1dcbf5d585 Mon Sep 17 00:00:00 2001 From: Hasan Ali Date: Tue, 10 May 2022 21:22:20 +0100 Subject: [PATCH 1741/2212] Fix hlsl output for writes to scalar/vector storage buffer --- src/back/hlsl/storage.rs | 3 + tests/in/access.param.ron | 2 + tests/in/access.wgsl | 5 + tests/out/glsl/access.atomics.Compute.glsl | 36 +- tests/out/glsl/access.foo_frag.Fragment.glsl | 7 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 55 ++- tests/out/hlsl/access.hlsl | 87 ++-- tests/out/msl/access.msl | 107 ++-- tests/out/spv/access.spvasm | 495 ++++++++++--------- tests/out/wgsl/access.wgsl | 88 ++-- 10 files changed, 464 insertions(+), 421 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 658090256..637b05d4b 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -44,6 +44,9 @@ impl super::Writer<'_, W> { chain: &[SubAccess], func_ctx: &FunctionCtx, ) -> BackendResult { + if chain.is_empty() { + write!(self.out, "0")?; + } for (i, access) in chain.iter().enumerate() { if i != 0 { write!(self.out, "+")?; diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 57cb7a632..3e79bea26 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -11,12 +11,14 @@ resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: false), (group: 0, binding: 1): (buffer: Some(1), mutable: false), + (group: 0, binding: 2): (buffer: Some(2), mutable: false), }, sizes_buffer: Some(24), ), fs: ( resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: true), + (group: 0, binding: 2): (buffer: Some(2), mutable: true), }, sizes_buffer: Some(24), ), diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index c80d0349d..ee426876d 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -22,6 +22,9 @@ struct Baz { @group(0) @binding(1) var baz: Baz; +@group(0) @binding(2) +var qux: vec2; + fn test_matrix_within_struct_accesses() { var idx = 9; @@ -73,6 +76,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let index = 3u; let b = bar._matrix[index].x; let a = bar.data[arrayLength(&bar.data) - 2u].value; + let c = qux; // test pointer types let data_pointer: ptr = &bar.data[0].value; @@ -95,6 +99,7 @@ fn foo_frag() -> @location(0) vec4 { bar._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); bar.arr = array, 2>(vec2(0u), vec2(1u)); bar.data[1].value = 1; + qux = vec2(); return vec4(0.0); } diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 1a8668a82..2ab1b4fa8 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -21,8 +21,8 @@ layout(std430) buffer Bar_block_0Compute { float read_from_private(inout float foo_1) { - float _e3 = foo_1; - return _e3; + float _e4 = foo_1; + return _e4; } float test_arr_as_arg(float a[5][10]) { @@ -32,22 +32,22 @@ float test_arr_as_arg(float a[5][10]) { void main() { int tmp = 0; int value = _group_0_binding_0_cs.atom; - int _e7 = atomicAdd(_group_0_binding_0_cs.atom, 5); - tmp = _e7; - int _e10 = atomicAdd(_group_0_binding_0_cs.atom, -5); - tmp = _e10; - int _e13 = atomicAnd(_group_0_binding_0_cs.atom, 5); - tmp = _e13; - int _e16 = atomicOr(_group_0_binding_0_cs.atom, 5); - tmp = _e16; - int _e19 = atomicXor(_group_0_binding_0_cs.atom, 5); - tmp = _e19; - int _e22 = atomicMin(_group_0_binding_0_cs.atom, 5); - tmp = _e22; - int _e25 = atomicMax(_group_0_binding_0_cs.atom, 5); - tmp = _e25; - int _e28 = atomicExchange(_group_0_binding_0_cs.atom, 5); - tmp = _e28; + int _e8 = atomicAdd(_group_0_binding_0_cs.atom, 5); + tmp = _e8; + int _e11 = atomicAdd(_group_0_binding_0_cs.atom, -5); + tmp = _e11; + int _e14 = atomicAnd(_group_0_binding_0_cs.atom, 5); + tmp = _e14; + int _e17 = atomicOr(_group_0_binding_0_cs.atom, 5); + tmp = _e17; + int _e20 = atomicXor(_group_0_binding_0_cs.atom, 5); + tmp = _e20; + int _e23 = atomicMin(_group_0_binding_0_cs.atom, 5); + tmp = _e23; + int _e26 = atomicMax(_group_0_binding_0_cs.atom, 5); + tmp = _e26; + int _e29 = atomicExchange(_group_0_binding_0_cs.atom, 5); + tmp = _e29; _group_0_binding_0_cs.atom = value; return; } diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index df6ac6770..fcd3e4300 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -17,11 +17,13 @@ layout(std430) buffer Bar_block_0Fragment { AlignedWrapper data[]; } _group_0_binding_0_fs; +layout(std430) buffer type_9_block_1Fragment { ivec2 _group_0_binding_2_fs; }; + layout(location = 0) out vec4 _fs2p_location0; float read_from_private(inout float foo_1) { - float _e3 = foo_1; - return _e3; + float _e4 = foo_1; + return _e4; } float test_arr_as_arg(float a[5][10]) { @@ -33,6 +35,7 @@ void main() { _group_0_binding_0_fs._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); _group_0_binding_0_fs.arr = uvec2[2](uvec2(0u), uvec2(1u)); _group_0_binding_0_fs.data[1].value = 1; + _group_0_binding_2_fs = ivec2(0, 0); _fs2p_location0 = vec4(0.0); return; } diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index b5b4804d7..5eead818e 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -19,45 +19,47 @@ layout(std430) buffer Bar_block_0Vertex { uniform Baz_block_1Vertex { Baz _group_0_binding_1_vs; }; +layout(std430) buffer type_9_block_2Vertex { ivec2 _group_0_binding_2_vs; }; + void test_matrix_within_struct_accesses() { int idx = 9; Baz t = Baz(mat3x2(0.0)); - int _e4 = idx; - idx = (_e4 - 1); + int _e5 = idx; + idx = (_e5 - 1); mat3x2 unnamed = _group_0_binding_1_vs.m; vec2 unnamed_1 = _group_0_binding_1_vs.m[0]; - int _e14 = idx; - vec2 unnamed_2 = _group_0_binding_1_vs.m[_e14]; + int _e15 = idx; + vec2 unnamed_2 = _group_0_binding_1_vs.m[_e15]; float unnamed_3 = _group_0_binding_1_vs.m[0][1]; - int _e26 = idx; - float unnamed_4 = _group_0_binding_1_vs.m[0][_e26]; - int _e30 = idx; - float unnamed_5 = _group_0_binding_1_vs.m[_e30][1]; - int _e36 = idx; - int _e38 = idx; - float unnamed_6 = _group_0_binding_1_vs.m[_e36][_e38]; + int _e27 = idx; + float unnamed_4 = _group_0_binding_1_vs.m[0][_e27]; + int _e31 = idx; + float unnamed_5 = _group_0_binding_1_vs.m[_e31][1]; + int _e37 = idx; + int _e39 = idx; + float unnamed_6 = _group_0_binding_1_vs.m[_e37][_e39]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - int _e50 = idx; - idx = (_e50 + 1); + int _e51 = idx; + idx = (_e51 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - int _e67 = idx; - t.m[_e67] = vec2(90.0); + int _e68 = idx; + t.m[_e68] = vec2(90.0); t.m[0][1] = 10.0; - int _e80 = idx; - t.m[0][_e80] = 20.0; - int _e84 = idx; - t.m[_e84][1] = 30.0; - int _e90 = idx; - int _e92 = idx; - t.m[_e90][_e92] = 40.0; + int _e81 = idx; + t.m[0][_e81] = 20.0; + int _e85 = idx; + t.m[_e85][1] = 30.0; + int _e91 = idx; + int _e93 = idx; + t.m[_e91][_e93] = 40.0; return; } float read_from_private(inout float foo_1) { - float _e3 = foo_1; - return _e3; + float _e4 = foo_1; + return _e4; } float test_arr_as_arg(float a[5][10]) { @@ -75,11 +77,12 @@ void main() { uvec2 arr[2] = _group_0_binding_0_vs.arr; float b = _group_0_binding_0_vs._matrix[3][0]; int a_1 = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; - float _e28 = read_from_private(foo); + ivec2 c_1 = _group_0_binding_2_vs; + float _e30 = read_from_private(foo); c = int[5](a_1, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; - float _e42 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + float _e44 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); gl_Position = vec4((_matrix * vec4(ivec4(value))), 2.0); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 89dd2ea61..4bb113716 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -20,6 +20,7 @@ float Constructarray5_array10_float__(float arg0[10], float arg1[10], float arg2 RWByteAddressBuffer bar : register(u0); cbuffer baz : register(b1) { Baz baz; } +RWByteAddressBuffer qux : register(u2); float3x2 GetMatmOnBaz(Baz obj) { return float3x2(obj.m_0, obj.m_1, obj.m_2); @@ -60,42 +61,42 @@ void test_matrix_within_struct_accesses() int idx = 9; Baz t = (Baz)0; - int _expr4 = idx; - idx = (_expr4 - 1); + int _expr5 = idx; + idx = (_expr5 - 1); float3x2 unnamed = GetMatmOnBaz(baz); float2 unnamed_1 = GetMatmOnBaz(baz)[0]; - int _expr14 = idx; - float2 unnamed_2 = GetMatmOnBaz(baz)[_expr14]; + int _expr15 = idx; + float2 unnamed_2 = GetMatmOnBaz(baz)[_expr15]; float unnamed_3 = GetMatmOnBaz(baz)[0][1]; - int _expr26 = idx; - float unnamed_4 = GetMatmOnBaz(baz)[0][_expr26]; - int _expr30 = idx; - float unnamed_5 = GetMatmOnBaz(baz)[_expr30][1]; - int _expr36 = idx; - int _expr38 = idx; - float unnamed_6 = GetMatmOnBaz(baz)[_expr36][_expr38]; + int _expr27 = idx; + float unnamed_4 = GetMatmOnBaz(baz)[0][_expr27]; + int _expr31 = idx; + float unnamed_5 = GetMatmOnBaz(baz)[_expr31][1]; + int _expr37 = idx; + int _expr39 = idx; + float unnamed_6 = GetMatmOnBaz(baz)[_expr37][_expr39]; t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); - int _expr50 = idx; - idx = (_expr50 + 1); + int _expr51 = idx; + idx = (_expr51 + 1); SetMatmOnBaz(t, float3x2((6.0).xx, (5.0).xx, (4.0).xx)); t.m_0 = (9.0).xx; - int _expr67 = idx; - SetMatVecmOnBaz(t, (90.0).xx, _expr67); + int _expr68 = idx; + SetMatVecmOnBaz(t, (90.0).xx, _expr68); t.m_0[1] = 10.0; - int _expr80 = idx; - t.m_0[_expr80] = 20.0; - int _expr84 = idx; - SetMatScalarmOnBaz(t, 30.0, _expr84, 1); - int _expr90 = idx; - int _expr92 = idx; - SetMatScalarmOnBaz(t, 40.0, _expr90, _expr92); + int _expr81 = idx; + t.m_0[_expr81] = 20.0; + int _expr85 = idx; + SetMatScalarmOnBaz(t, 30.0, _expr85, 1); + int _expr91 = idx; + int _expr93 = idx; + SetMatScalarmOnBaz(t, 40.0, _expr91, _expr93); return; } float read_from_private(inout float foo_1) { - float _expr3 = foo_1; - return _expr3; + float _expr4 = foo_1; + return _expr4; } float test_arr_as_arg(float a[5][10]) @@ -127,14 +128,15 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); - const float _e28 = read_from_private(foo); + int2 c_1 = asint(qux.Load2(0)); + const float _e30 = read_from_private(foo); { int _result[5]=Constructarray5_int_(a_1, int(b), 3, 4, 5); for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; } c[(vi + 1u)] = 42; int value = c[vi]; - const float _e42 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + const float _e44 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); return float4(mul(float4((value).xxxx), _matrix), 2.0); } @@ -159,6 +161,7 @@ float4 foo_frag() : SV_Target0 bar.Store2(104+8, asuint(_value2[1])); } bar.Store(0+8+120, asuint(1)); + qux.Store2(0, asuint(int2(0, 0))); return (0.0).xxxx; } @@ -168,22 +171,22 @@ void atomics() int tmp = (int)0; int value_1 = asint(bar.Load(96)); - int _e7; bar.InterlockedAdd(96, 5, _e7); - tmp = _e7; - int _e10; bar.InterlockedAdd(96, -5, _e10); - tmp = _e10; - int _e13; bar.InterlockedAnd(96, 5, _e13); - tmp = _e13; - int _e16; bar.InterlockedOr(96, 5, _e16); - tmp = _e16; - int _e19; bar.InterlockedXor(96, 5, _e19); - tmp = _e19; - int _e22; bar.InterlockedMin(96, 5, _e22); - tmp = _e22; - int _e25; bar.InterlockedMax(96, 5, _e25); - tmp = _e25; - int _e28; bar.InterlockedExchange(96, 5, _e28); - tmp = _e28; + int _e8; bar.InterlockedAdd(96, 5, _e8); + tmp = _e8; + int _e11; bar.InterlockedAdd(96, -5, _e11); + tmp = _e11; + int _e14; bar.InterlockedAnd(96, 5, _e14); + tmp = _e14; + int _e17; bar.InterlockedOr(96, 5, _e17); + tmp = _e17; + int _e20; bar.InterlockedXor(96, 5, _e20); + tmp = _e20; + int _e23; bar.InterlockedMin(96, 5, _e23); + tmp = _e23; + int _e26; bar.InterlockedMax(96, 5, _e26); + tmp = _e26; + int _e29; bar.InterlockedExchange(96, 5, _e29); + tmp = _e29; bar.Store(96, asuint(value_1)); return; } diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 7ee2d6c13..f3f11559c 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -29,64 +29,65 @@ struct Bar { struct Baz { metal::float3x2 m; }; -struct type_11 { +struct type_12 { float inner[10]; }; -struct type_12 { - type_11 inner[5]; +struct type_13 { + type_12 inner[5]; }; -struct type_16 { +struct type_17 { int inner[5]; }; -constant type_11 const_type_11_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; -constant type_12 const_type_12_ = {const_type_11_, const_type_11_, const_type_11_, const_type_11_, const_type_11_}; +constant type_12 const_type_12_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; +constant type_13 const_type_13_ = {const_type_12_, const_type_12_, const_type_12_, const_type_12_, const_type_12_}; +constant metal::int2 const_type_9_ = {0, 0}; void test_matrix_within_struct_accesses( constant Baz& baz ) { int idx = 9; Baz t = {}; - int _e4 = idx; - idx = _e4 - 1; + int _e5 = idx; + idx = _e5 - 1; metal::float3x2 unnamed = baz.m; metal::float2 unnamed_1 = baz.m[0]; - int _e14 = idx; - metal::float2 unnamed_2 = baz.m[_e14]; + int _e15 = idx; + metal::float2 unnamed_2 = baz.m[_e15]; float unnamed_3 = baz.m[0].y; - int _e26 = idx; - float unnamed_4 = baz.m[0][_e26]; - int _e30 = idx; - float unnamed_5 = baz.m[_e30].y; - int _e36 = idx; - int _e38 = idx; - float unnamed_6 = baz.m[_e36][_e38]; + int _e27 = idx; + float unnamed_4 = baz.m[0][_e27]; + int _e31 = idx; + float unnamed_5 = baz.m[_e31].y; + int _e37 = idx; + int _e39 = idx; + float unnamed_6 = baz.m[_e37][_e39]; t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; - int _e50 = idx; - idx = _e50 + 1; + int _e51 = idx; + idx = _e51 + 1; t.m = metal::float3x2(metal::float2(6.0), metal::float2(5.0), metal::float2(4.0)); t.m[0] = metal::float2(9.0); - int _e67 = idx; - t.m[_e67] = metal::float2(90.0); + int _e68 = idx; + t.m[_e68] = metal::float2(90.0); t.m[0].y = 10.0; - int _e80 = idx; - t.m[0][_e80] = 20.0; - int _e84 = idx; - t.m[_e84].y = 30.0; - int _e90 = idx; - int _e92 = idx; - t.m[_e90][_e92] = 40.0; + int _e81 = idx; + t.m[0][_e81] = 20.0; + int _e85 = idx; + t.m[_e85].y = 30.0; + int _e91 = idx; + int _e93 = idx; + t.m[_e91][_e93] = 40.0; return; } float read_from_private( thread float& foo_1 ) { - float _e3 = foo_1; - return _e3; + float _e4 = foo_1; + return _e4; } float test_arr_as_arg( - type_12 a + type_13 a ) { return a.inner[4].inner[9]; } @@ -100,10 +101,11 @@ vertex foo_vertOutput foo_vert( uint vi [[vertex_id]] , device Bar const& bar [[buffer(0)]] , constant Baz& baz [[buffer(1)]] +, device metal::int2 const& qux [[buffer(2)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo = 0.0; - type_16 c = {}; + type_17 c = {}; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); @@ -111,11 +113,12 @@ vertex foo_vertOutput foo_vert( type_6 arr = bar.arr; float b = bar._matrix[3].x; int a_1 = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; - float _e28 = read_from_private(foo); - for(int _i=0; _i<5; ++_i) c.inner[_i] = type_16 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; + metal::int2 c_1 = qux; + float _e30 = read_from_private(foo); + for(int _i=0; _i<5; ++_i) c.inner[_i] = type_17 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; - float _e42 = test_arr_as_arg(const_type_12_); + float _e44 = test_arr_as_arg(const_type_13_); return foo_vertOutput { metal::float4(_matrix * static_cast(metal::int4(value)), 2.0) }; } @@ -125,12 +128,14 @@ struct foo_fragOutput { }; fragment foo_fragOutput foo_frag( device Bar& bar [[buffer(0)]] +, device metal::int2& qux [[buffer(2)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { bar._matrix[1].z = 1.0; bar._matrix = metal::float4x3(metal::float3(0.0), metal::float3(1.0), metal::float3(2.0), metal::float3(3.0)); for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_6 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; bar.data[1].value = 1; + qux = const_type_9_; return foo_fragOutput { metal::float4(0.0) }; } @@ -141,22 +146,22 @@ kernel void atomics( ) { int tmp = {}; int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); - int _e7 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e7; - int _e10 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e10; - int _e13 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e13; - int _e16 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e16; - int _e19 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e19; - int _e22 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e22; - int _e25 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e25; - int _e28 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e28; + int _e8 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e8; + int _e11 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e11; + int _e14 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e14; + int _e17 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e17; + int _e20 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e20; + int _e23 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e23; + int _e26 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e26; + int _e29 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e29; metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 68f296d42..21e92ab2b 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 221 +; Bound: 230 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %143 "foo_vert" %138 %141 -OpEntryPoint Fragment %180 "foo_frag" %179 -OpEntryPoint GLCompute %198 "atomics" -OpExecutionMode %180 OriginUpperLeft -OpExecutionMode %198 LocalSize 1 1 1 +OpEntryPoint Vertex %149 "foo_vert" %144 %147 +OpEntryPoint Fragment %188 "foo_frag" %187 +OpEntryPoint GLCompute %207 "atomics" +OpExecutionMode %188 OriginUpperLeft +OpExecutionMode %207 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %32 0 "value" OpName %32 "AlignedWrapper" @@ -22,22 +22,23 @@ OpMemberName %41 4 "data" OpName %41 "Bar" OpMemberName %43 0 "m" OpName %43 "Baz" -OpName %52 "bar" -OpName %54 "baz" -OpName %57 "idx" -OpName %59 "t" -OpName %63 "test_matrix_within_struct_accesses" -OpName %121 "foo" -OpName %122 "read_from_private" -OpName %127 "a" -OpName %128 "test_arr_as_arg" -OpName %133 "foo" -OpName %134 "c" -OpName %138 "vi" -OpName %143 "foo_vert" -OpName %180 "foo_frag" -OpName %195 "tmp" -OpName %198 "atomics" +OpName %54 "bar" +OpName %56 "baz" +OpName %59 "qux" +OpName %62 "idx" +OpName %64 "t" +OpName %68 "test_matrix_within_struct_accesses" +OpName %127 "foo" +OpName %128 "read_from_private" +OpName %133 "a" +OpName %134 "test_arr_as_arg" +OpName %139 "foo" +OpName %140 "c" +OpName %144 "vi" +OpName %149 "foo_vert" +OpName %188 "foo_frag" +OpName %204 "tmp" +OpName %207 "atomics" OpMemberDecorate %32 0 Offset 0 OpDecorate %37 ArrayStride 16 OpDecorate %39 ArrayStride 8 @@ -54,19 +55,23 @@ OpMemberDecorate %41 4 Offset 120 OpMemberDecorate %43 0 Offset 0 OpMemberDecorate %43 0 ColMajor OpMemberDecorate %43 0 MatrixStride 8 -OpDecorate %45 ArrayStride 4 -OpDecorate %46 ArrayStride 40 -OpDecorate %49 ArrayStride 4 -OpDecorate %52 DescriptorSet 0 -OpDecorate %52 Binding 0 -OpDecorate %41 Block +OpDecorate %46 ArrayStride 4 +OpDecorate %47 ArrayStride 40 +OpDecorate %50 ArrayStride 4 OpDecorate %54 DescriptorSet 0 -OpDecorate %54 Binding 1 -OpDecorate %55 Block -OpMemberDecorate %55 0 Offset 0 -OpDecorate %138 BuiltIn VertexIndex -OpDecorate %141 BuiltIn Position -OpDecorate %179 Location 0 +OpDecorate %54 Binding 0 +OpDecorate %41 Block +OpDecorate %56 DescriptorSet 0 +OpDecorate %56 Binding 1 +OpDecorate %57 Block +OpMemberDecorate %57 0 Offset 0 +OpDecorate %59 DescriptorSet 0 +OpDecorate %59 Binding 2 +OpDecorate %60 Block +OpMemberDecorate %60 0 Offset 0 +OpDecorate %144 BuiltIn VertexIndex +OpDecorate %147 BuiltIn Position +OpDecorate %187 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -109,226 +114,236 @@ OpDecorate %179 Location 0 %41 = OpTypeStruct %33 %37 %4 %39 %40 %42 = OpTypeMatrix %36 3 %43 = OpTypeStruct %42 -%44 = OpTypePointer Function %9 -%45 = OpTypeArray %9 %21 -%46 = OpTypeArray %45 %22 -%47 = OpTypeVector %9 4 -%48 = OpTypePointer StorageBuffer %4 -%49 = OpTypeArray %4 %22 -%50 = OpConstantComposite %45 %24 %24 %24 %24 %24 %24 %24 %24 %24 %24 -%51 = OpConstantComposite %46 %50 %50 %50 %50 %50 -%53 = OpTypePointer StorageBuffer %41 -%52 = OpVariable %53 StorageBuffer -%55 = OpTypeStruct %43 -%56 = OpTypePointer Uniform %55 -%54 = OpVariable %56 Uniform -%58 = OpTypePointer Function %4 -%60 = OpTypePointer Function %43 -%61 = OpConstantNull %43 -%64 = OpTypeFunction %2 -%65 = OpTypePointer Uniform %43 -%70 = OpTypePointer Uniform %42 -%73 = OpTypePointer Uniform %36 -%79 = OpTypePointer Uniform %9 -%99 = OpTypePointer Function %42 -%105 = OpTypePointer Function %36 -%111 = OpTypePointer Function %9 -%123 = OpTypeFunction %9 %44 -%129 = OpTypeFunction %9 %46 -%135 = OpTypePointer Function %49 -%136 = OpConstantNull %49 -%139 = OpTypePointer Input %26 -%138 = OpVariable %139 Input -%142 = OpTypePointer Output %47 -%141 = OpVariable %142 Output -%148 = OpTypePointer StorageBuffer %33 -%151 = OpTypePointer StorageBuffer %39 -%154 = OpTypePointer StorageBuffer %34 -%155 = OpTypePointer StorageBuffer %9 -%158 = OpTypePointer StorageBuffer %40 -%161 = OpTypePointer StorageBuffer %32 -%162 = OpConstant %26 4 -%173 = OpTypeVector %4 4 -%179 = OpVariable %142 Output -%196 = OpConstantNull %4 -%200 = OpTypePointer StorageBuffer %4 -%203 = OpConstant %26 64 -%63 = OpFunction %2 None %64 -%62 = OpLabel -%57 = OpVariable %58 Function %5 -%59 = OpVariable %60 Function %61 -%66 = OpAccessChain %65 %54 %31 -OpBranch %67 +%44 = OpTypeVector %4 2 +%45 = OpTypePointer Function %9 +%46 = OpTypeArray %9 %21 +%47 = OpTypeArray %46 %22 +%48 = OpTypeVector %9 4 +%49 = OpTypePointer StorageBuffer %4 +%50 = OpTypeArray %4 %22 +%51 = OpConstantComposite %46 %24 %24 %24 %24 %24 %24 %24 %24 %24 %24 +%52 = OpConstantComposite %47 %51 %51 %51 %51 %51 +%53 = OpConstantComposite %44 %7 %7 +%55 = OpTypePointer StorageBuffer %41 +%54 = OpVariable %55 StorageBuffer +%57 = OpTypeStruct %43 +%58 = OpTypePointer Uniform %57 +%56 = OpVariable %58 Uniform +%60 = OpTypeStruct %44 +%61 = OpTypePointer StorageBuffer %60 +%59 = OpVariable %61 StorageBuffer +%63 = OpTypePointer Function %4 +%65 = OpTypePointer Function %43 +%66 = OpConstantNull %43 +%69 = OpTypeFunction %2 +%70 = OpTypePointer Uniform %43 +%72 = OpTypePointer StorageBuffer %44 +%76 = OpTypePointer Uniform %42 +%79 = OpTypePointer Uniform %36 +%85 = OpTypePointer Uniform %9 +%105 = OpTypePointer Function %42 +%111 = OpTypePointer Function %36 +%117 = OpTypePointer Function %9 +%129 = OpTypeFunction %9 %45 +%135 = OpTypeFunction %9 %47 +%141 = OpTypePointer Function %50 +%142 = OpConstantNull %50 +%145 = OpTypePointer Input %26 +%144 = OpVariable %145 Input +%148 = OpTypePointer Output %48 +%147 = OpVariable %148 Output +%155 = OpTypePointer StorageBuffer %33 +%158 = OpTypePointer StorageBuffer %39 +%161 = OpTypePointer StorageBuffer %34 +%162 = OpTypePointer StorageBuffer %9 +%165 = OpTypePointer StorageBuffer %40 +%168 = OpTypePointer StorageBuffer %32 +%169 = OpConstant %26 4 +%181 = OpTypeVector %4 4 +%187 = OpVariable %148 Output +%205 = OpConstantNull %4 +%209 = OpTypePointer StorageBuffer %4 +%212 = OpConstant %26 64 +%68 = OpFunction %2 None %69 %67 = OpLabel -%68 = OpLoad %4 %57 -%69 = OpISub %4 %68 %6 -OpStore %57 %69 -%71 = OpAccessChain %70 %66 %31 -%72 = OpLoad %42 %71 -%74 = OpAccessChain %73 %66 %31 %31 -%75 = OpLoad %36 %74 -%76 = OpLoad %4 %57 -%77 = OpAccessChain %73 %66 %31 %76 -%78 = OpLoad %36 %77 -%80 = OpAccessChain %79 %66 %31 %31 %29 -%81 = OpLoad %9 %80 -%82 = OpLoad %4 %57 -%83 = OpAccessChain %79 %66 %31 %31 %82 -%84 = OpLoad %9 %83 -%85 = OpLoad %4 %57 -%86 = OpAccessChain %79 %66 %31 %85 %29 +%62 = OpVariable %63 Function %5 +%64 = OpVariable %65 Function %66 +%71 = OpAccessChain %70 %56 %31 +OpBranch %73 +%73 = OpLabel +%74 = OpLoad %4 %62 +%75 = OpISub %4 %74 %6 +OpStore %62 %75 +%77 = OpAccessChain %76 %71 %31 +%78 = OpLoad %42 %77 +%80 = OpAccessChain %79 %71 %31 %31 +%81 = OpLoad %36 %80 +%82 = OpLoad %4 %62 +%83 = OpAccessChain %79 %71 %31 %82 +%84 = OpLoad %36 %83 +%86 = OpAccessChain %85 %71 %31 %31 %29 %87 = OpLoad %9 %86 -%88 = OpLoad %4 %57 -%89 = OpLoad %4 %57 -%90 = OpAccessChain %79 %66 %31 %88 %89 -%91 = OpLoad %9 %90 -%92 = OpCompositeConstruct %36 %8 %8 -%93 = OpCompositeConstruct %36 %10 %10 -%94 = OpCompositeConstruct %36 %11 %11 -%95 = OpCompositeConstruct %42 %92 %93 %94 -%96 = OpCompositeConstruct %43 %95 -OpStore %59 %96 -%97 = OpLoad %4 %57 -%98 = OpIAdd %4 %97 %6 -OpStore %57 %98 -%100 = OpCompositeConstruct %36 %12 %12 -%101 = OpCompositeConstruct %36 %13 %13 -%102 = OpCompositeConstruct %36 %14 %14 -%103 = OpCompositeConstruct %42 %100 %101 %102 -%104 = OpAccessChain %99 %59 %31 -OpStore %104 %103 -%106 = OpCompositeConstruct %36 %15 %15 -%107 = OpAccessChain %105 %59 %31 %31 -OpStore %107 %106 -%108 = OpLoad %4 %57 -%109 = OpCompositeConstruct %36 %16 %16 -%110 = OpAccessChain %105 %59 %31 %108 +%88 = OpLoad %4 %62 +%89 = OpAccessChain %85 %71 %31 %31 %88 +%90 = OpLoad %9 %89 +%91 = OpLoad %4 %62 +%92 = OpAccessChain %85 %71 %31 %91 %29 +%93 = OpLoad %9 %92 +%94 = OpLoad %4 %62 +%95 = OpLoad %4 %62 +%96 = OpAccessChain %85 %71 %31 %94 %95 +%97 = OpLoad %9 %96 +%98 = OpCompositeConstruct %36 %8 %8 +%99 = OpCompositeConstruct %36 %10 %10 +%100 = OpCompositeConstruct %36 %11 %11 +%101 = OpCompositeConstruct %42 %98 %99 %100 +%102 = OpCompositeConstruct %43 %101 +OpStore %64 %102 +%103 = OpLoad %4 %62 +%104 = OpIAdd %4 %103 %6 +OpStore %62 %104 +%106 = OpCompositeConstruct %36 %12 %12 +%107 = OpCompositeConstruct %36 %13 %13 +%108 = OpCompositeConstruct %36 %14 %14 +%109 = OpCompositeConstruct %42 %106 %107 %108 +%110 = OpAccessChain %105 %64 %31 OpStore %110 %109 -%112 = OpAccessChain %111 %59 %31 %31 %29 -OpStore %112 %17 -%113 = OpLoad %4 %57 -%114 = OpAccessChain %111 %59 %31 %31 %113 -OpStore %114 %18 -%115 = OpLoad %4 %57 -%116 = OpAccessChain %111 %59 %31 %115 %29 -OpStore %116 %19 -%117 = OpLoad %4 %57 -%118 = OpLoad %4 %57 -%119 = OpAccessChain %111 %59 %31 %117 %118 -OpStore %119 %20 +%112 = OpCompositeConstruct %36 %15 %15 +%113 = OpAccessChain %111 %64 %31 %31 +OpStore %113 %112 +%114 = OpLoad %4 %62 +%115 = OpCompositeConstruct %36 %16 %16 +%116 = OpAccessChain %111 %64 %31 %114 +OpStore %116 %115 +%118 = OpAccessChain %117 %64 %31 %31 %29 +OpStore %118 %17 +%119 = OpLoad %4 %62 +%120 = OpAccessChain %117 %64 %31 %31 %119 +OpStore %120 %18 +%121 = OpLoad %4 %62 +%122 = OpAccessChain %117 %64 %31 %121 %29 +OpStore %122 %19 +%123 = OpLoad %4 %62 +%124 = OpLoad %4 %62 +%125 = OpAccessChain %117 %64 %31 %123 %124 +OpStore %125 %20 OpReturn OpFunctionEnd -%122 = OpFunction %9 None %123 -%121 = OpFunctionParameter %44 -%120 = OpLabel -OpBranch %124 -%124 = OpLabel -%125 = OpLoad %9 %121 -OpReturnValue %125 -OpFunctionEnd %128 = OpFunction %9 None %129 -%127 = OpFunctionParameter %46 +%127 = OpFunctionParameter %45 %126 = OpLabel OpBranch %130 %130 = OpLabel -%131 = OpCompositeExtract %45 %127 4 -%132 = OpCompositeExtract %9 %131 9 -OpReturnValue %132 +%131 = OpLoad %9 %127 +OpReturnValue %131 OpFunctionEnd -%143 = OpFunction %2 None %64 -%137 = OpLabel -%133 = OpVariable %44 Function %24 -%134 = OpVariable %135 Function %136 -%140 = OpLoad %26 %138 -%144 = OpAccessChain %65 %54 %31 -OpBranch %145 -%145 = OpLabel -%146 = OpLoad %9 %133 -OpStore %133 %8 -%147 = OpFunctionCall %2 %63 -%149 = OpAccessChain %148 %52 %31 -%150 = OpLoad %33 %149 -%152 = OpAccessChain %151 %52 %25 -%153 = OpLoad %39 %152 -%156 = OpAccessChain %155 %52 %31 %25 %31 -%157 = OpLoad %9 %156 -%159 = OpArrayLength %26 %52 4 -%160 = OpISub %26 %159 %27 -%163 = OpAccessChain %48 %52 %162 %160 %31 -%164 = OpLoad %4 %163 -%165 = OpFunctionCall %9 %122 %133 -%166 = OpConvertFToS %4 %157 -%167 = OpCompositeConstruct %49 %164 %166 %28 %23 %22 -OpStore %134 %167 -%168 = OpIAdd %26 %140 %29 -%169 = OpAccessChain %58 %134 %168 -OpStore %169 %30 -%170 = OpAccessChain %58 %134 %140 +%134 = OpFunction %9 None %135 +%133 = OpFunctionParameter %47 +%132 = OpLabel +OpBranch %136 +%136 = OpLabel +%137 = OpCompositeExtract %46 %133 4 +%138 = OpCompositeExtract %9 %137 9 +OpReturnValue %138 +OpFunctionEnd +%149 = OpFunction %2 None %69 +%143 = OpLabel +%139 = OpVariable %45 Function %24 +%140 = OpVariable %141 Function %142 +%146 = OpLoad %26 %144 +%150 = OpAccessChain %70 %56 %31 +%151 = OpAccessChain %72 %59 %31 +OpBranch %152 +%152 = OpLabel +%153 = OpLoad %9 %139 +OpStore %139 %8 +%154 = OpFunctionCall %2 %68 +%156 = OpAccessChain %155 %54 %31 +%157 = OpLoad %33 %156 +%159 = OpAccessChain %158 %54 %25 +%160 = OpLoad %39 %159 +%163 = OpAccessChain %162 %54 %31 %25 %31 +%164 = OpLoad %9 %163 +%166 = OpArrayLength %26 %54 4 +%167 = OpISub %26 %166 %27 +%170 = OpAccessChain %49 %54 %169 %167 %31 %171 = OpLoad %4 %170 -%172 = OpFunctionCall %9 %128 %51 -%174 = OpCompositeConstruct %173 %171 %171 %171 %171 -%175 = OpConvertSToF %47 %174 -%176 = OpMatrixTimesVector %34 %150 %175 -%177 = OpCompositeConstruct %47 %176 %10 -OpStore %141 %177 +%172 = OpLoad %44 %151 +%173 = OpFunctionCall %9 %128 %139 +%174 = OpConvertFToS %4 %164 +%175 = OpCompositeConstruct %50 %171 %174 %28 %23 %22 +OpStore %140 %175 +%176 = OpIAdd %26 %146 %29 +%177 = OpAccessChain %63 %140 %176 +OpStore %177 %30 +%178 = OpAccessChain %63 %140 %146 +%179 = OpLoad %4 %178 +%180 = OpFunctionCall %9 %134 %52 +%182 = OpCompositeConstruct %181 %179 %179 %179 %179 +%183 = OpConvertSToF %48 %182 +%184 = OpMatrixTimesVector %34 %157 %183 +%185 = OpCompositeConstruct %48 %184 %10 +OpStore %147 %185 OpReturn OpFunctionEnd -%180 = OpFunction %2 None %64 -%178 = OpLabel -OpBranch %181 -%181 = OpLabel -%182 = OpAccessChain %155 %52 %31 %29 %27 -OpStore %182 %8 -%183 = OpCompositeConstruct %34 %24 %24 %24 -%184 = OpCompositeConstruct %34 %8 %8 %8 -%185 = OpCompositeConstruct %34 %10 %10 %10 -%186 = OpCompositeConstruct %34 %11 %11 %11 -%187 = OpCompositeConstruct %33 %183 %184 %185 %186 -%188 = OpAccessChain %148 %52 %31 -OpStore %188 %187 -%189 = OpCompositeConstruct %38 %31 %31 -%190 = OpCompositeConstruct %38 %29 %29 -%191 = OpCompositeConstruct %39 %189 %190 -%192 = OpAccessChain %151 %52 %25 -OpStore %192 %191 -%193 = OpAccessChain %48 %52 %162 %29 %31 -OpStore %193 %6 -%194 = OpCompositeConstruct %47 %24 %24 %24 %24 -OpStore %179 %194 +%188 = OpFunction %2 None %69 +%186 = OpLabel +%189 = OpAccessChain %72 %59 %31 +OpBranch %190 +%190 = OpLabel +%191 = OpAccessChain %162 %54 %31 %29 %27 +OpStore %191 %8 +%192 = OpCompositeConstruct %34 %24 %24 %24 +%193 = OpCompositeConstruct %34 %8 %8 %8 +%194 = OpCompositeConstruct %34 %10 %10 %10 +%195 = OpCompositeConstruct %34 %11 %11 %11 +%196 = OpCompositeConstruct %33 %192 %193 %194 %195 +%197 = OpAccessChain %155 %54 %31 +OpStore %197 %196 +%198 = OpCompositeConstruct %38 %31 %31 +%199 = OpCompositeConstruct %38 %29 %29 +%200 = OpCompositeConstruct %39 %198 %199 +%201 = OpAccessChain %158 %54 %25 +OpStore %201 %200 +%202 = OpAccessChain %49 %54 %169 %29 %31 +OpStore %202 %6 +OpStore %189 %53 +%203 = OpCompositeConstruct %48 %24 %24 %24 %24 +OpStore %187 %203 OpReturn OpFunctionEnd -%198 = OpFunction %2 None %64 -%197 = OpLabel -%195 = OpVariable %58 Function %196 -OpBranch %199 -%199 = OpLabel -%201 = OpAccessChain %200 %52 %27 -%202 = OpAtomicLoad %4 %201 %6 %203 -%205 = OpAccessChain %200 %52 %27 -%204 = OpAtomicIAdd %4 %205 %6 %203 %22 -OpStore %195 %204 -%207 = OpAccessChain %200 %52 %27 -%206 = OpAtomicISub %4 %207 %6 %203 %22 -OpStore %195 %206 -%209 = OpAccessChain %200 %52 %27 -%208 = OpAtomicAnd %4 %209 %6 %203 %22 -OpStore %195 %208 -%211 = OpAccessChain %200 %52 %27 -%210 = OpAtomicOr %4 %211 %6 %203 %22 -OpStore %195 %210 -%213 = OpAccessChain %200 %52 %27 -%212 = OpAtomicXor %4 %213 %6 %203 %22 -OpStore %195 %212 -%215 = OpAccessChain %200 %52 %27 -%214 = OpAtomicSMin %4 %215 %6 %203 %22 -OpStore %195 %214 -%217 = OpAccessChain %200 %52 %27 -%216 = OpAtomicSMax %4 %217 %6 %203 %22 -OpStore %195 %216 -%219 = OpAccessChain %200 %52 %27 -%218 = OpAtomicExchange %4 %219 %6 %203 %22 -OpStore %195 %218 -%220 = OpAccessChain %200 %52 %27 -OpAtomicStore %220 %6 %203 %202 +%207 = OpFunction %2 None %69 +%206 = OpLabel +%204 = OpVariable %63 Function %205 +OpBranch %208 +%208 = OpLabel +%210 = OpAccessChain %209 %54 %27 +%211 = OpAtomicLoad %4 %210 %6 %212 +%214 = OpAccessChain %209 %54 %27 +%213 = OpAtomicIAdd %4 %214 %6 %212 %22 +OpStore %204 %213 +%216 = OpAccessChain %209 %54 %27 +%215 = OpAtomicISub %4 %216 %6 %212 %22 +OpStore %204 %215 +%218 = OpAccessChain %209 %54 %27 +%217 = OpAtomicAnd %4 %218 %6 %212 %22 +OpStore %204 %217 +%220 = OpAccessChain %209 %54 %27 +%219 = OpAtomicOr %4 %220 %6 %212 %22 +OpStore %204 %219 +%222 = OpAccessChain %209 %54 %27 +%221 = OpAtomicXor %4 %222 %6 %212 %22 +OpStore %204 %221 +%224 = OpAccessChain %209 %54 %27 +%223 = OpAtomicSMin %4 %224 %6 %212 %22 +OpStore %204 %223 +%226 = OpAccessChain %209 %54 %27 +%225 = OpAtomicSMax %4 %226 %6 %212 %22 +OpStore %204 %225 +%228 = OpAccessChain %209 %54 %27 +%227 = OpAtomicExchange %4 %228 %6 %212 %22 +OpStore %204 %227 +%229 = OpAccessChain %209 %54 %27 +OpAtomicStore %229 %6 %212 %211 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 2b88d7aac..752e3853d 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -18,46 +18,48 @@ struct Baz { var bar: Bar; @group(0) @binding(1) var baz: Baz; +@group(0) @binding(2) +var qux: vec2; fn test_matrix_within_struct_accesses() { var idx: i32 = 9; var t: Baz; - let _e4 = idx; - idx = (_e4 - 1); + let _e5 = idx; + idx = (_e5 - 1); _ = baz.m; _ = baz.m[0]; - let _e14 = idx; - _ = baz.m[_e14]; + let _e15 = idx; + _ = baz.m[_e15]; _ = baz.m[0][1]; - let _e26 = idx; - _ = baz.m[0][_e26]; - let _e30 = idx; - _ = baz.m[_e30][1]; - let _e36 = idx; - let _e38 = idx; - _ = baz.m[_e36][_e38]; + let _e27 = idx; + _ = baz.m[0][_e27]; + let _e31 = idx; + _ = baz.m[_e31][1]; + let _e37 = idx; + let _e39 = idx; + _ = baz.m[_e37][_e39]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - let _e50 = idx; - idx = (_e50 + 1); + let _e51 = idx; + idx = (_e51 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - let _e67 = idx; - t.m[_e67] = vec2(90.0); + let _e68 = idx; + t.m[_e68] = vec2(90.0); t.m[0][1] = 10.0; - let _e80 = idx; - t.m[0][_e80] = 20.0; - let _e84 = idx; - t.m[_e84][1] = 30.0; - let _e90 = idx; - let _e92 = idx; - t.m[_e90][_e92] = 40.0; + let _e81 = idx; + t.m[0][_e81] = 20.0; + let _e85 = idx; + t.m[_e85][1] = 30.0; + let _e91 = idx; + let _e93 = idx; + t.m[_e91][_e93] = 40.0; return; } fn read_from_private(foo_1: ptr) -> f32 { - let _e3 = (*foo_1); - return _e3; + let _e4 = (*foo_1); + return _e4; } fn test_arr_as_arg(a: array,5>) -> f32 { @@ -76,12 +78,13 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let arr = bar.arr; let b = bar._matrix[3][0]; let a_1 = bar.data[(arrayLength((&bar.data)) - 2u)].value; + let c_1 = qux; let data_pointer = (&bar.data[0].value); - let _e28 = read_from_private((&foo)); + let _e30 = read_from_private((&foo)); c = array(a_1, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value = c[vi]; - let _e42 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + let _e44 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); return vec4((_matrix * vec4(vec4(value))), 2.0); } @@ -91,6 +94,7 @@ fn foo_frag() -> @location(0) vec4 { bar._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); bar.data[1].value = 1; + qux = vec2(0, 0); return vec4(0.0); } @@ -99,22 +103,22 @@ fn atomics() { var tmp: i32; let value_1 = atomicLoad((&bar.atom)); - let _e7 = atomicAdd((&bar.atom), 5); - tmp = _e7; - let _e10 = atomicSub((&bar.atom), 5); - tmp = _e10; - let _e13 = atomicAnd((&bar.atom), 5); - tmp = _e13; - let _e16 = atomicOr((&bar.atom), 5); - tmp = _e16; - let _e19 = atomicXor((&bar.atom), 5); - tmp = _e19; - let _e22 = atomicMin((&bar.atom), 5); - tmp = _e22; - let _e25 = atomicMax((&bar.atom), 5); - tmp = _e25; - let _e28 = atomicExchange((&bar.atom), 5); - tmp = _e28; + let _e8 = atomicAdd((&bar.atom), 5); + tmp = _e8; + let _e11 = atomicSub((&bar.atom), 5); + tmp = _e11; + let _e14 = atomicAnd((&bar.atom), 5); + tmp = _e14; + let _e17 = atomicOr((&bar.atom), 5); + tmp = _e17; + let _e20 = atomicXor((&bar.atom), 5); + tmp = _e20; + let _e23 = atomicMin((&bar.atom), 5); + tmp = _e23; + let _e26 = atomicMax((&bar.atom), 5); + tmp = _e26; + let _e29 = atomicExchange((&bar.atom), 5); + tmp = _e29; atomicStore((&bar.atom), value_1); return; } From 8db27c49f861901e7ee66ea41364635bae3f5dd1 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 11 May 2022 14:21:19 +0300 Subject: [PATCH 1742/2212] [wgsl] Reserve binding_array --- src/keywords/wgsl.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/keywords/wgsl.rs b/src/keywords/wgsl.rs index 0f6336255..3231915b5 100644 --- a/src/keywords/wgsl.rs +++ b/src/keywords/wgsl.rs @@ -134,6 +134,7 @@ pub const RESERVED: &[&str] = &[ "await", "become", "bf16", + "binding_array", "cast", "catch", "cbuffer", From fea33c682e7bfff8e82182d81925de1a7fb4440c Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 11 May 2022 21:13:57 +0200 Subject: [PATCH 1743/2212] [wgsl-in] fix incr/decr not matching ValuePointer --- src/front/wgsl/mod.rs | 31 +- tests/in/operators.wgsl | 4 + tests/out/glsl/operators.main.Compute.glsl | 5 + tests/out/hlsl/operators.hlsl | 5 + tests/out/msl/operators.msl | 6 + tests/out/spv/operators.spvasm | 971 +++++++++++---------- tests/out/wgsl/operators.wgsl | 5 + 7 files changed, 534 insertions(+), 493 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 87fdccc6d..04f115fbe 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3353,25 +3353,26 @@ impl Parser { let _ = context.resolve_type(reference.handle)?; let ty = context.typifier.get(reference.handle, context.types); - let constant_inner = match ty.canonical_form(context.types) { - Some(crate::TypeInner::ValuePointer { + let (kind, width) = match *ty { + crate::TypeInner::ValuePointer { size: None, kind, width, - space: _, - }) => crate::ConstantInner::Scalar { - width, - value: match kind { - crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), - crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), - _ => { - return Err(Error::BadIncrDecrReferenceType(lhs_span)); - } - }, + .. + } => (kind, width), + crate::TypeInner::Pointer { base, .. } => match context.types[base].inner { + crate::TypeInner::Scalar { kind, width } => (kind, width), + _ => return Err(Error::BadIncrDecrReferenceType(lhs_span)), + }, + _ => return Err(Error::BadIncrDecrReferenceType(lhs_span)), + }; + let constant_inner = crate::ConstantInner::Scalar { + width, + value: match kind { + crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), + crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), + _ => return Err(Error::BadIncrDecrReferenceType(lhs_span)), }, - _ => { - return Err(Error::BadIncrDecrReferenceType(lhs_span)); - } }; let constant = context.constants.append( crate::Constant { diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index cfc589659..332fb25da 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -277,6 +277,10 @@ fn assignment() { a++; a--; + + var vec0: vec3 = vec3(); + vec0[1]++; + vec0[1]--; } @compute @workgroup_size(1) diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index a27e97939..f6f15fc7b 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -196,6 +196,7 @@ void comparison() { void assignment() { int a = 1; + ivec3 vec0_ = ivec3(0, 0, 0); int _e6 = a; a = (_e6 + 1); int _e9 = a; @@ -222,6 +223,10 @@ void assignment() { a = (_e36 + 1); int _e39 = a; a = (_e39 - 1); + int _e46 = vec0_.y; + vec0_.y = (_e46 + 1); + int _e51 = vec0_.y; + vec0_.y = (_e51 - 1); return; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index e6356d201..9cd73942e 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -224,6 +224,7 @@ void comparison() void assignment() { int a = 1; + int3 vec0_ = int3(0, 0, 0); int _expr6 = a; a = (_expr6 + 1); @@ -251,6 +252,10 @@ void assignment() a = (_expr36 + 1); int _expr39 = a; a = (_expr39 - 1); + int _expr46 = vec0_.y; + vec0_.y = (_expr46 + 1); + int _expr51 = vec0_.y; + vec0_.y = (_expr51 - 1); return; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 8cc741a4e..e9415d12b 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -28,6 +28,7 @@ constant metal::float3 const_type_4_ = {0.0, 0.0, 0.0}; constant metal::float3x3 const_type_14_ = {const_type_4_, const_type_4_, const_type_4_}; constant metal::float4x3 const_type_15_ = {const_type_4_, const_type_4_, const_type_4_, const_type_4_}; constant metal::float3x4 const_type_16_ = {const_type, const_type, const_type}; +constant metal::int3 const_type_17_ = {0, 0, 0}; metal::float4 builtins( ) { @@ -225,6 +226,7 @@ void comparison( void assignment( ) { int a = 1; + metal::int3 vec0_ = const_type_17_; int _e6 = a; a = _e6 + 1; int _e9 = a; @@ -251,6 +253,10 @@ void assignment( a = _e36 + 1; int _e39 = a; a = _e39 - 1; + int _e46 = vec0_.y; + vec0_.y = _e46 + 1; + int _e51 = vec0_.y; + vec0_.y = _e51 - 1; return; } diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 850295757..e805de91c 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 502 +; Bound: 515 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %490 "main" -OpExecutionMode %490 LocalSize 1 1 1 +OpEntryPoint GLCompute %503 "main" +OpExecutionMode %503 LocalSize 1 1 1 OpMemberDecorate %30 0 Offset 0 OpMemberDecorate %30 1 Offset 16 OpDecorate %35 ArrayStride 32 @@ -49,508 +49,523 @@ OpDecorate %36 ArrayStride 4 %37 = OpTypeMatrix %29 3 %38 = OpTypeMatrix %29 4 %39 = OpTypeMatrix %26 3 -%40 = OpConstantComposite %26 %3 %3 %3 %3 -%41 = OpConstantComposite %26 %5 %5 %5 %5 -%42 = OpConstantComposite %26 %6 %6 %6 %6 -%43 = OpConstantComposite %27 %7 %7 %7 %7 -%44 = OpConstantComposite %34 %19 %19 -%45 = OpConstantComposite %31 %5 %5 -%46 = OpConstantComposite %32 %45 %45 -%47 = OpConstantComposite %26 %5 %5 %5 %5 -%48 = OpConstantComposite %30 %47 %11 -%49 = OpConstantComposite %35 %48 %48 %48 -%50 = OpConstantComposite %29 %5 %5 %5 -%51 = OpConstantComposite %37 %50 %50 %50 -%52 = OpConstantComposite %38 %50 %50 %50 %50 -%53 = OpConstantComposite %39 %47 %47 %47 -%56 = OpTypeFunction %26 -%98 = OpTypeFunction %29 %29 -%100 = OpTypeVector %10 3 -%107 = OpTypePointer Function %30 -%108 = OpConstantNull %30 -%111 = OpTypeFunction %4 -%128 = OpTypePointer Function %26 -%129 = OpTypePointer Function %4 -%134 = OpTypeFunction %2 -%137 = OpTypeVector %10 2 -%153 = OpTypeVector %8 2 -%164 = OpTypeVector %20 3 -%459 = OpTypePointer Function %8 -%55 = OpFunction %26 None %56 -%54 = OpLabel -OpBranch %57 -%57 = OpLabel -%58 = OpSelect %8 %9 %7 %11 -%60 = OpCompositeConstruct %28 %9 %9 %9 %9 -%59 = OpSelect %26 %60 %40 %41 -%61 = OpCompositeConstruct %28 %12 %12 %12 %12 -%62 = OpSelect %26 %61 %41 %40 -%63 = OpExtInst %26 %1 FMix %41 %40 %42 -%65 = OpCompositeConstruct %26 %13 %13 %13 %13 -%64 = OpExtInst %26 %1 FMix %41 %40 %65 -%66 = OpCompositeExtract %8 %43 0 -%67 = OpBitcast %4 %66 -%68 = OpBitcast %26 %43 -%69 = OpConvertFToS %27 %41 -%70 = OpCompositeConstruct %27 %58 %58 %58 %58 -%71 = OpIAdd %27 %70 %69 -%72 = OpConvertSToF %26 %71 -%73 = OpFAdd %26 %72 %59 -%74 = OpFAdd %26 %73 %63 -%75 = OpFAdd %26 %74 %64 -%76 = OpCompositeConstruct %26 %67 %67 %67 %67 -%77 = OpFAdd %26 %75 %76 -%78 = OpFAdd %26 %77 %68 -OpReturnValue %78 +%40 = OpTypeVector %8 3 +%41 = OpConstantComposite %26 %3 %3 %3 %3 +%42 = OpConstantComposite %26 %5 %5 %5 %5 +%43 = OpConstantComposite %26 %6 %6 %6 %6 +%44 = OpConstantComposite %27 %7 %7 %7 %7 +%45 = OpConstantComposite %34 %19 %19 +%46 = OpConstantComposite %31 %5 %5 +%47 = OpConstantComposite %32 %46 %46 +%48 = OpConstantComposite %26 %5 %5 %5 %5 +%49 = OpConstantComposite %30 %48 %11 +%50 = OpConstantComposite %35 %49 %49 %49 +%51 = OpConstantComposite %29 %5 %5 %5 +%52 = OpConstantComposite %37 %51 %51 %51 +%53 = OpConstantComposite %38 %51 %51 %51 %51 +%54 = OpConstantComposite %39 %48 %48 %48 +%55 = OpConstantComposite %40 %11 %11 %11 +%58 = OpTypeFunction %26 +%100 = OpTypeFunction %29 %29 +%102 = OpTypeVector %10 3 +%109 = OpTypePointer Function %30 +%110 = OpConstantNull %30 +%113 = OpTypeFunction %4 +%130 = OpTypePointer Function %26 +%131 = OpTypePointer Function %4 +%136 = OpTypeFunction %2 +%139 = OpTypeVector %10 2 +%155 = OpTypeVector %8 2 +%166 = OpTypeVector %20 3 +%461 = OpTypePointer Function %8 +%463 = OpTypePointer Function %40 +%493 = OpTypePointer Function %8 +%57 = OpFunction %26 None %58 +%56 = OpLabel +OpBranch %59 +%59 = OpLabel +%60 = OpSelect %8 %9 %7 %11 +%62 = OpCompositeConstruct %28 %9 %9 %9 %9 +%61 = OpSelect %26 %62 %41 %42 +%63 = OpCompositeConstruct %28 %12 %12 %12 %12 +%64 = OpSelect %26 %63 %42 %41 +%65 = OpExtInst %26 %1 FMix %42 %41 %43 +%67 = OpCompositeConstruct %26 %13 %13 %13 %13 +%66 = OpExtInst %26 %1 FMix %42 %41 %67 +%68 = OpCompositeExtract %8 %44 0 +%69 = OpBitcast %4 %68 +%70 = OpBitcast %26 %44 +%71 = OpConvertFToS %27 %42 +%72 = OpCompositeConstruct %27 %60 %60 %60 %60 +%73 = OpIAdd %27 %72 %71 +%74 = OpConvertSToF %26 %73 +%75 = OpFAdd %26 %74 %61 +%76 = OpFAdd %26 %75 %65 +%77 = OpFAdd %26 %76 %66 +%78 = OpCompositeConstruct %26 %69 %69 %69 %69 +%79 = OpFAdd %26 %77 %78 +%80 = OpFAdd %26 %79 %70 +OpReturnValue %80 OpFunctionEnd -%80 = OpFunction %26 None %56 -%79 = OpLabel -OpBranch %81 +%82 = OpFunction %26 None %58 %81 = OpLabel -%82 = OpCompositeConstruct %31 %14 %14 -%83 = OpCompositeConstruct %31 %3 %3 -%84 = OpFAdd %31 %83 %82 -%85 = OpCompositeConstruct %31 %15 %15 -%86 = OpFSub %31 %84 %85 -%87 = OpCompositeConstruct %31 %16 %16 -%88 = OpFDiv %31 %86 %87 -%89 = OpCompositeConstruct %27 %17 %17 %17 %17 -%90 = OpCompositeConstruct %27 %18 %18 %18 %18 -%91 = OpSRem %27 %89 %90 -%92 = OpVectorShuffle %26 %88 %88 0 1 0 1 -%93 = OpConvertSToF %26 %91 -%94 = OpFAdd %26 %92 %93 -OpReturnValue %94 +OpBranch %83 +%83 = OpLabel +%84 = OpCompositeConstruct %31 %14 %14 +%85 = OpCompositeConstruct %31 %3 %3 +%86 = OpFAdd %31 %85 %84 +%87 = OpCompositeConstruct %31 %15 %15 +%88 = OpFSub %31 %86 %87 +%89 = OpCompositeConstruct %31 %16 %16 +%90 = OpFDiv %31 %88 %89 +%91 = OpCompositeConstruct %27 %17 %17 %17 %17 +%92 = OpCompositeConstruct %27 %18 %18 %18 %18 +%93 = OpSRem %27 %91 %92 +%94 = OpVectorShuffle %26 %90 %90 0 1 0 1 +%95 = OpConvertSToF %26 %93 +%96 = OpFAdd %26 %94 %95 +OpReturnValue %96 OpFunctionEnd -%97 = OpFunction %29 None %98 -%96 = OpFunctionParameter %29 -%95 = OpLabel -OpBranch %99 -%99 = OpLabel -%101 = OpCompositeConstruct %29 %5 %5 %5 -%102 = OpFUnordNotEqual %100 %96 %101 +%99 = OpFunction %29 None %100 +%98 = OpFunctionParameter %29 +%97 = OpLabel +OpBranch %101 +%101 = OpLabel %103 = OpCompositeConstruct %29 %5 %5 %5 -%104 = OpCompositeConstruct %29 %3 %3 %3 -%105 = OpSelect %29 %102 %104 %103 -OpReturnValue %105 +%104 = OpFUnordNotEqual %102 %98 %103 +%105 = OpCompositeConstruct %29 %5 %5 %5 +%106 = OpCompositeConstruct %29 %3 %3 %3 +%107 = OpSelect %29 %104 %106 %105 +OpReturnValue %107 OpFunctionEnd -%110 = OpFunction %4 None %111 -%109 = OpLabel -%106 = OpVariable %107 Function %108 -OpBranch %112 -%112 = OpLabel -%113 = OpCompositeConstruct %26 %3 %3 %3 %3 -%114 = OpCompositeConstruct %30 %113 %7 -OpStore %106 %114 -%115 = OpCompositeConstruct %31 %3 %5 -%116 = OpCompositeConstruct %31 %5 %3 -%117 = OpCompositeConstruct %32 %115 %116 -%118 = OpCompositeConstruct %26 %3 %5 %5 %5 -%119 = OpCompositeConstruct %26 %5 %3 %5 %5 -%120 = OpCompositeConstruct %26 %5 %5 %3 %5 -%121 = OpCompositeConstruct %26 %5 %5 %5 %3 -%122 = OpCompositeConstruct %33 %118 %119 %120 %121 -%123 = OpCompositeConstruct %34 %19 %19 -%124 = OpCompositeConstruct %31 %5 %5 -%125 = OpCompositeConstruct %31 %5 %5 -%126 = OpCompositeConstruct %32 %124 %125 -%127 = OpCompositeConstruct %36 %11 %7 %18 %21 -%130 = OpAccessChain %129 %106 %19 %19 -%131 = OpLoad %4 %130 -OpReturnValue %131 +%112 = OpFunction %4 None %113 +%111 = OpLabel +%108 = OpVariable %109 Function %110 +OpBranch %114 +%114 = OpLabel +%115 = OpCompositeConstruct %26 %3 %3 %3 %3 +%116 = OpCompositeConstruct %30 %115 %7 +OpStore %108 %116 +%117 = OpCompositeConstruct %31 %3 %5 +%118 = OpCompositeConstruct %31 %5 %3 +%119 = OpCompositeConstruct %32 %117 %118 +%120 = OpCompositeConstruct %26 %3 %5 %5 %5 +%121 = OpCompositeConstruct %26 %5 %3 %5 %5 +%122 = OpCompositeConstruct %26 %5 %5 %3 %5 +%123 = OpCompositeConstruct %26 %5 %5 %5 %3 +%124 = OpCompositeConstruct %33 %120 %121 %122 %123 +%125 = OpCompositeConstruct %34 %19 %19 +%126 = OpCompositeConstruct %31 %5 %5 +%127 = OpCompositeConstruct %31 %5 %5 +%128 = OpCompositeConstruct %32 %126 %127 +%129 = OpCompositeConstruct %36 %11 %7 %18 %21 +%132 = OpAccessChain %131 %108 %19 %19 +%133 = OpLoad %4 %132 +OpReturnValue %133 OpFunctionEnd -%133 = OpFunction %2 None %134 -%132 = OpLabel -OpBranch %135 -%135 = OpLabel -%136 = OpLogicalNot %10 %9 -%138 = OpCompositeConstruct %137 %9 %9 -%139 = OpLogicalNot %137 %138 -%140 = OpLogicalOr %10 %9 %12 -%141 = OpLogicalAnd %10 %9 %12 +%135 = OpFunction %2 None %136 +%134 = OpLabel +OpBranch %137 +%137 = OpLabel +%138 = OpLogicalNot %10 %9 +%140 = OpCompositeConstruct %139 %9 %9 +%141 = OpLogicalNot %139 %140 %142 = OpLogicalOr %10 %9 %12 -%143 = OpCompositeConstruct %100 %9 %9 %9 -%144 = OpCompositeConstruct %100 %12 %12 %12 -%145 = OpLogicalOr %100 %143 %144 -%146 = OpLogicalAnd %10 %9 %12 -%147 = OpCompositeConstruct %28 %9 %9 %9 %9 -%148 = OpCompositeConstruct %28 %12 %12 %12 %12 -%149 = OpLogicalAnd %28 %147 %148 +%143 = OpLogicalAnd %10 %9 %12 +%144 = OpLogicalOr %10 %9 %12 +%145 = OpCompositeConstruct %102 %9 %9 %9 +%146 = OpCompositeConstruct %102 %12 %12 %12 +%147 = OpLogicalOr %102 %145 %146 +%148 = OpLogicalAnd %10 %9 %12 +%149 = OpCompositeConstruct %28 %9 %9 %9 %9 +%150 = OpCompositeConstruct %28 %12 %12 %12 %12 +%151 = OpLogicalAnd %28 %149 %150 OpReturn OpFunctionEnd -%151 = OpFunction %2 None %134 -%150 = OpLabel -OpBranch %152 +%153 = OpFunction %2 None %136 %152 = OpLabel -%154 = OpCompositeConstruct %153 %7 %7 -%155 = OpSNegate %153 %154 -%156 = OpCompositeConstruct %31 %3 %3 -%157 = OpFNegate %31 %156 -%158 = OpIAdd %8 %18 %7 -%159 = OpIAdd %20 %24 %25 -%160 = OpFAdd %4 %14 %3 -%161 = OpCompositeConstruct %153 %18 %18 -%162 = OpCompositeConstruct %153 %7 %7 -%163 = OpIAdd %153 %161 %162 -%165 = OpCompositeConstruct %164 %24 %24 %24 -%166 = OpCompositeConstruct %164 %25 %25 %25 -%167 = OpIAdd %164 %165 %166 -%168 = OpCompositeConstruct %26 %14 %14 %14 %14 -%169 = OpCompositeConstruct %26 %3 %3 %3 %3 -%170 = OpFAdd %26 %168 %169 -%171 = OpISub %8 %18 %7 -%172 = OpISub %20 %24 %25 -%173 = OpFSub %4 %14 %3 -%174 = OpCompositeConstruct %153 %18 %18 -%175 = OpCompositeConstruct %153 %7 %7 -%176 = OpISub %153 %174 %175 -%177 = OpCompositeConstruct %164 %24 %24 %24 -%178 = OpCompositeConstruct %164 %25 %25 %25 -%179 = OpISub %164 %177 %178 -%180 = OpCompositeConstruct %26 %14 %14 %14 %14 -%181 = OpCompositeConstruct %26 %3 %3 %3 %3 -%182 = OpFSub %26 %180 %181 -%183 = OpIMul %8 %18 %7 -%184 = OpIMul %20 %24 %25 -%185 = OpFMul %4 %14 %3 -%186 = OpCompositeConstruct %153 %18 %18 -%187 = OpCompositeConstruct %153 %7 %7 -%188 = OpIMul %153 %186 %187 -%189 = OpCompositeConstruct %164 %24 %24 %24 -%190 = OpCompositeConstruct %164 %25 %25 %25 -%191 = OpIMul %164 %189 %190 -%192 = OpCompositeConstruct %26 %14 %14 %14 %14 -%193 = OpCompositeConstruct %26 %3 %3 %3 %3 -%194 = OpFMul %26 %192 %193 -%195 = OpSDiv %8 %18 %7 -%196 = OpUDiv %20 %24 %25 -%197 = OpFDiv %4 %14 %3 -%198 = OpCompositeConstruct %153 %18 %18 -%199 = OpCompositeConstruct %153 %7 %7 -%200 = OpSDiv %153 %198 %199 -%201 = OpCompositeConstruct %164 %24 %24 %24 -%202 = OpCompositeConstruct %164 %25 %25 %25 -%203 = OpUDiv %164 %201 %202 -%204 = OpCompositeConstruct %26 %14 %14 %14 %14 -%205 = OpCompositeConstruct %26 %3 %3 %3 %3 -%206 = OpFDiv %26 %204 %205 -%207 = OpSRem %8 %18 %7 -%208 = OpUMod %20 %24 %25 -%209 = OpFRem %4 %14 %3 -%210 = OpCompositeConstruct %153 %18 %18 -%211 = OpCompositeConstruct %153 %7 %7 -%212 = OpSRem %153 %210 %211 -%213 = OpCompositeConstruct %164 %24 %24 %24 -%214 = OpCompositeConstruct %164 %25 %25 %25 -%215 = OpUMod %164 %213 %214 -%216 = OpCompositeConstruct %26 %14 %14 %14 %14 -%217 = OpCompositeConstruct %26 %3 %3 %3 %3 -%218 = OpFRem %26 %216 %217 -%219 = OpCompositeConstruct %153 %18 %18 -%220 = OpCompositeConstruct %153 %7 %7 -%221 = OpIAdd %153 %219 %220 -%222 = OpCompositeConstruct %153 %7 %7 -%223 = OpCompositeConstruct %153 %18 %18 -%224 = OpIAdd %153 %223 %222 -%225 = OpCompositeConstruct %34 %24 %24 -%226 = OpCompositeConstruct %34 %25 %25 -%227 = OpIAdd %34 %225 %226 +OpBranch %154 +%154 = OpLabel +%156 = OpCompositeConstruct %155 %7 %7 +%157 = OpSNegate %155 %156 +%158 = OpCompositeConstruct %31 %3 %3 +%159 = OpFNegate %31 %158 +%160 = OpIAdd %8 %18 %7 +%161 = OpIAdd %20 %24 %25 +%162 = OpFAdd %4 %14 %3 +%163 = OpCompositeConstruct %155 %18 %18 +%164 = OpCompositeConstruct %155 %7 %7 +%165 = OpIAdd %155 %163 %164 +%167 = OpCompositeConstruct %166 %24 %24 %24 +%168 = OpCompositeConstruct %166 %25 %25 %25 +%169 = OpIAdd %166 %167 %168 +%170 = OpCompositeConstruct %26 %14 %14 %14 %14 +%171 = OpCompositeConstruct %26 %3 %3 %3 %3 +%172 = OpFAdd %26 %170 %171 +%173 = OpISub %8 %18 %7 +%174 = OpISub %20 %24 %25 +%175 = OpFSub %4 %14 %3 +%176 = OpCompositeConstruct %155 %18 %18 +%177 = OpCompositeConstruct %155 %7 %7 +%178 = OpISub %155 %176 %177 +%179 = OpCompositeConstruct %166 %24 %24 %24 +%180 = OpCompositeConstruct %166 %25 %25 %25 +%181 = OpISub %166 %179 %180 +%182 = OpCompositeConstruct %26 %14 %14 %14 %14 +%183 = OpCompositeConstruct %26 %3 %3 %3 %3 +%184 = OpFSub %26 %182 %183 +%185 = OpIMul %8 %18 %7 +%186 = OpIMul %20 %24 %25 +%187 = OpFMul %4 %14 %3 +%188 = OpCompositeConstruct %155 %18 %18 +%189 = OpCompositeConstruct %155 %7 %7 +%190 = OpIMul %155 %188 %189 +%191 = OpCompositeConstruct %166 %24 %24 %24 +%192 = OpCompositeConstruct %166 %25 %25 %25 +%193 = OpIMul %166 %191 %192 +%194 = OpCompositeConstruct %26 %14 %14 %14 %14 +%195 = OpCompositeConstruct %26 %3 %3 %3 %3 +%196 = OpFMul %26 %194 %195 +%197 = OpSDiv %8 %18 %7 +%198 = OpUDiv %20 %24 %25 +%199 = OpFDiv %4 %14 %3 +%200 = OpCompositeConstruct %155 %18 %18 +%201 = OpCompositeConstruct %155 %7 %7 +%202 = OpSDiv %155 %200 %201 +%203 = OpCompositeConstruct %166 %24 %24 %24 +%204 = OpCompositeConstruct %166 %25 %25 %25 +%205 = OpUDiv %166 %203 %204 +%206 = OpCompositeConstruct %26 %14 %14 %14 %14 +%207 = OpCompositeConstruct %26 %3 %3 %3 %3 +%208 = OpFDiv %26 %206 %207 +%209 = OpSRem %8 %18 %7 +%210 = OpUMod %20 %24 %25 +%211 = OpFRem %4 %14 %3 +%212 = OpCompositeConstruct %155 %18 %18 +%213 = OpCompositeConstruct %155 %7 %7 +%214 = OpSRem %155 %212 %213 +%215 = OpCompositeConstruct %166 %24 %24 %24 +%216 = OpCompositeConstruct %166 %25 %25 %25 +%217 = OpUMod %166 %215 %216 +%218 = OpCompositeConstruct %26 %14 %14 %14 %14 +%219 = OpCompositeConstruct %26 %3 %3 %3 %3 +%220 = OpFRem %26 %218 %219 +%221 = OpCompositeConstruct %155 %18 %18 +%222 = OpCompositeConstruct %155 %7 %7 +%223 = OpIAdd %155 %221 %222 +%224 = OpCompositeConstruct %155 %7 %7 +%225 = OpCompositeConstruct %155 %18 %18 +%226 = OpIAdd %155 %225 %224 +%227 = OpCompositeConstruct %34 %24 %24 %228 = OpCompositeConstruct %34 %25 %25 -%229 = OpCompositeConstruct %34 %24 %24 -%230 = OpIAdd %34 %229 %228 -%231 = OpCompositeConstruct %31 %14 %14 -%232 = OpCompositeConstruct %31 %3 %3 -%233 = OpFAdd %31 %231 %232 +%229 = OpIAdd %34 %227 %228 +%230 = OpCompositeConstruct %34 %25 %25 +%231 = OpCompositeConstruct %34 %24 %24 +%232 = OpIAdd %34 %231 %230 +%233 = OpCompositeConstruct %31 %14 %14 %234 = OpCompositeConstruct %31 %3 %3 -%235 = OpCompositeConstruct %31 %14 %14 -%236 = OpFAdd %31 %235 %234 -%237 = OpCompositeConstruct %153 %18 %18 -%238 = OpCompositeConstruct %153 %7 %7 -%239 = OpISub %153 %237 %238 -%240 = OpCompositeConstruct %153 %7 %7 -%241 = OpCompositeConstruct %153 %18 %18 -%242 = OpISub %153 %241 %240 -%243 = OpCompositeConstruct %34 %24 %24 -%244 = OpCompositeConstruct %34 %25 %25 -%245 = OpISub %34 %243 %244 +%235 = OpFAdd %31 %233 %234 +%236 = OpCompositeConstruct %31 %3 %3 +%237 = OpCompositeConstruct %31 %14 %14 +%238 = OpFAdd %31 %237 %236 +%239 = OpCompositeConstruct %155 %18 %18 +%240 = OpCompositeConstruct %155 %7 %7 +%241 = OpISub %155 %239 %240 +%242 = OpCompositeConstruct %155 %7 %7 +%243 = OpCompositeConstruct %155 %18 %18 +%244 = OpISub %155 %243 %242 +%245 = OpCompositeConstruct %34 %24 %24 %246 = OpCompositeConstruct %34 %25 %25 -%247 = OpCompositeConstruct %34 %24 %24 -%248 = OpISub %34 %247 %246 -%249 = OpCompositeConstruct %31 %14 %14 -%250 = OpCompositeConstruct %31 %3 %3 -%251 = OpFSub %31 %249 %250 +%247 = OpISub %34 %245 %246 +%248 = OpCompositeConstruct %34 %25 %25 +%249 = OpCompositeConstruct %34 %24 %24 +%250 = OpISub %34 %249 %248 +%251 = OpCompositeConstruct %31 %14 %14 %252 = OpCompositeConstruct %31 %3 %3 -%253 = OpCompositeConstruct %31 %14 %14 -%254 = OpFSub %31 %253 %252 -%255 = OpCompositeConstruct %153 %18 %18 -%257 = OpCompositeConstruct %153 %7 %7 -%256 = OpIMul %153 %255 %257 -%258 = OpCompositeConstruct %153 %7 %7 -%260 = OpCompositeConstruct %153 %18 %18 -%259 = OpIMul %153 %258 %260 -%261 = OpCompositeConstruct %34 %24 %24 -%263 = OpCompositeConstruct %34 %25 %25 -%262 = OpIMul %34 %261 %263 -%264 = OpCompositeConstruct %34 %25 %25 -%266 = OpCompositeConstruct %34 %24 %24 -%265 = OpIMul %34 %264 %266 -%267 = OpCompositeConstruct %31 %14 %14 -%268 = OpVectorTimesScalar %31 %267 %3 -%269 = OpCompositeConstruct %31 %3 %3 -%270 = OpVectorTimesScalar %31 %269 %14 -%271 = OpCompositeConstruct %153 %18 %18 -%272 = OpCompositeConstruct %153 %7 %7 -%273 = OpSDiv %153 %271 %272 -%274 = OpCompositeConstruct %153 %7 %7 -%275 = OpCompositeConstruct %153 %18 %18 -%276 = OpSDiv %153 %275 %274 -%277 = OpCompositeConstruct %34 %24 %24 -%278 = OpCompositeConstruct %34 %25 %25 -%279 = OpUDiv %34 %277 %278 +%253 = OpFSub %31 %251 %252 +%254 = OpCompositeConstruct %31 %3 %3 +%255 = OpCompositeConstruct %31 %14 %14 +%256 = OpFSub %31 %255 %254 +%257 = OpCompositeConstruct %155 %18 %18 +%259 = OpCompositeConstruct %155 %7 %7 +%258 = OpIMul %155 %257 %259 +%260 = OpCompositeConstruct %155 %7 %7 +%262 = OpCompositeConstruct %155 %18 %18 +%261 = OpIMul %155 %260 %262 +%263 = OpCompositeConstruct %34 %24 %24 +%265 = OpCompositeConstruct %34 %25 %25 +%264 = OpIMul %34 %263 %265 +%266 = OpCompositeConstruct %34 %25 %25 +%268 = OpCompositeConstruct %34 %24 %24 +%267 = OpIMul %34 %266 %268 +%269 = OpCompositeConstruct %31 %14 %14 +%270 = OpVectorTimesScalar %31 %269 %3 +%271 = OpCompositeConstruct %31 %3 %3 +%272 = OpVectorTimesScalar %31 %271 %14 +%273 = OpCompositeConstruct %155 %18 %18 +%274 = OpCompositeConstruct %155 %7 %7 +%275 = OpSDiv %155 %273 %274 +%276 = OpCompositeConstruct %155 %7 %7 +%277 = OpCompositeConstruct %155 %18 %18 +%278 = OpSDiv %155 %277 %276 +%279 = OpCompositeConstruct %34 %24 %24 %280 = OpCompositeConstruct %34 %25 %25 -%281 = OpCompositeConstruct %34 %24 %24 -%282 = OpUDiv %34 %281 %280 -%283 = OpCompositeConstruct %31 %14 %14 -%284 = OpCompositeConstruct %31 %3 %3 -%285 = OpFDiv %31 %283 %284 +%281 = OpUDiv %34 %279 %280 +%282 = OpCompositeConstruct %34 %25 %25 +%283 = OpCompositeConstruct %34 %24 %24 +%284 = OpUDiv %34 %283 %282 +%285 = OpCompositeConstruct %31 %14 %14 %286 = OpCompositeConstruct %31 %3 %3 -%287 = OpCompositeConstruct %31 %14 %14 -%288 = OpFDiv %31 %287 %286 -%289 = OpCompositeConstruct %153 %18 %18 -%290 = OpCompositeConstruct %153 %7 %7 -%291 = OpSRem %153 %289 %290 -%292 = OpCompositeConstruct %153 %7 %7 -%293 = OpCompositeConstruct %153 %18 %18 -%294 = OpSRem %153 %293 %292 -%295 = OpCompositeConstruct %34 %24 %24 -%296 = OpCompositeConstruct %34 %25 %25 -%297 = OpUMod %34 %295 %296 +%287 = OpFDiv %31 %285 %286 +%288 = OpCompositeConstruct %31 %3 %3 +%289 = OpCompositeConstruct %31 %14 %14 +%290 = OpFDiv %31 %289 %288 +%291 = OpCompositeConstruct %155 %18 %18 +%292 = OpCompositeConstruct %155 %7 %7 +%293 = OpSRem %155 %291 %292 +%294 = OpCompositeConstruct %155 %7 %7 +%295 = OpCompositeConstruct %155 %18 %18 +%296 = OpSRem %155 %295 %294 +%297 = OpCompositeConstruct %34 %24 %24 %298 = OpCompositeConstruct %34 %25 %25 -%299 = OpCompositeConstruct %34 %24 %24 -%300 = OpUMod %34 %299 %298 -%301 = OpCompositeConstruct %31 %14 %14 -%302 = OpCompositeConstruct %31 %3 %3 -%303 = OpFRem %31 %301 %302 +%299 = OpUMod %34 %297 %298 +%300 = OpCompositeConstruct %34 %25 %25 +%301 = OpCompositeConstruct %34 %24 %24 +%302 = OpUMod %34 %301 %300 +%303 = OpCompositeConstruct %31 %14 %14 %304 = OpCompositeConstruct %31 %3 %3 -%305 = OpCompositeConstruct %31 %14 %14 -%306 = OpFRem %31 %305 %304 -%308 = OpCompositeExtract %29 %51 0 -%309 = OpCompositeExtract %29 %51 0 -%310 = OpFAdd %29 %308 %309 -%311 = OpCompositeExtract %29 %51 1 -%312 = OpCompositeExtract %29 %51 1 -%313 = OpFAdd %29 %311 %312 -%314 = OpCompositeExtract %29 %51 2 -%315 = OpCompositeExtract %29 %51 2 -%316 = OpFAdd %29 %314 %315 -%307 = OpCompositeConstruct %37 %310 %313 %316 -%318 = OpCompositeExtract %29 %51 0 -%319 = OpCompositeExtract %29 %51 0 -%320 = OpFSub %29 %318 %319 -%321 = OpCompositeExtract %29 %51 1 -%322 = OpCompositeExtract %29 %51 1 -%323 = OpFSub %29 %321 %322 -%324 = OpCompositeExtract %29 %51 2 -%325 = OpCompositeExtract %29 %51 2 -%326 = OpFSub %29 %324 %325 -%317 = OpCompositeConstruct %37 %320 %323 %326 -%327 = OpMatrixTimesScalar %37 %51 %3 -%328 = OpMatrixTimesScalar %37 %51 %14 -%329 = OpCompositeConstruct %26 %3 %3 %3 %3 -%330 = OpMatrixTimesVector %29 %52 %329 -%331 = OpCompositeConstruct %29 %14 %14 %14 -%332 = OpVectorTimesMatrix %26 %331 %52 -%333 = OpMatrixTimesMatrix %37 %52 %53 +%305 = OpFRem %31 %303 %304 +%306 = OpCompositeConstruct %31 %3 %3 +%307 = OpCompositeConstruct %31 %14 %14 +%308 = OpFRem %31 %307 %306 +%310 = OpCompositeExtract %29 %52 0 +%311 = OpCompositeExtract %29 %52 0 +%312 = OpFAdd %29 %310 %311 +%313 = OpCompositeExtract %29 %52 1 +%314 = OpCompositeExtract %29 %52 1 +%315 = OpFAdd %29 %313 %314 +%316 = OpCompositeExtract %29 %52 2 +%317 = OpCompositeExtract %29 %52 2 +%318 = OpFAdd %29 %316 %317 +%309 = OpCompositeConstruct %37 %312 %315 %318 +%320 = OpCompositeExtract %29 %52 0 +%321 = OpCompositeExtract %29 %52 0 +%322 = OpFSub %29 %320 %321 +%323 = OpCompositeExtract %29 %52 1 +%324 = OpCompositeExtract %29 %52 1 +%325 = OpFSub %29 %323 %324 +%326 = OpCompositeExtract %29 %52 2 +%327 = OpCompositeExtract %29 %52 2 +%328 = OpFSub %29 %326 %327 +%319 = OpCompositeConstruct %37 %322 %325 %328 +%329 = OpMatrixTimesScalar %37 %52 %3 +%330 = OpMatrixTimesScalar %37 %52 %14 +%331 = OpCompositeConstruct %26 %3 %3 %3 %3 +%332 = OpMatrixTimesVector %29 %53 %331 +%333 = OpCompositeConstruct %29 %14 %14 %14 +%334 = OpVectorTimesMatrix %26 %333 %53 +%335 = OpMatrixTimesMatrix %37 %53 %54 OpReturn OpFunctionEnd -%335 = OpFunction %2 None %134 -%334 = OpLabel -OpBranch %336 +%337 = OpFunction %2 None %136 %336 = OpLabel -%337 = OpNot %8 %7 -%338 = OpNot %20 %25 -%339 = OpCompositeConstruct %153 %7 %7 -%340 = OpNot %153 %339 -%341 = OpCompositeConstruct %164 %25 %25 %25 -%342 = OpNot %164 %341 -%343 = OpBitwiseOr %8 %18 %7 -%344 = OpBitwiseOr %20 %24 %25 -%345 = OpCompositeConstruct %153 %18 %18 -%346 = OpCompositeConstruct %153 %7 %7 -%347 = OpBitwiseOr %153 %345 %346 -%348 = OpCompositeConstruct %164 %24 %24 %24 -%349 = OpCompositeConstruct %164 %25 %25 %25 -%350 = OpBitwiseOr %164 %348 %349 -%351 = OpBitwiseAnd %8 %18 %7 -%352 = OpBitwiseAnd %20 %24 %25 -%353 = OpCompositeConstruct %153 %18 %18 -%354 = OpCompositeConstruct %153 %7 %7 -%355 = OpBitwiseAnd %153 %353 %354 -%356 = OpCompositeConstruct %164 %24 %24 %24 -%357 = OpCompositeConstruct %164 %25 %25 %25 -%358 = OpBitwiseAnd %164 %356 %357 -%359 = OpBitwiseXor %8 %18 %7 -%360 = OpBitwiseXor %20 %24 %25 -%361 = OpCompositeConstruct %153 %18 %18 -%362 = OpCompositeConstruct %153 %7 %7 -%363 = OpBitwiseXor %153 %361 %362 -%364 = OpCompositeConstruct %164 %24 %24 %24 -%365 = OpCompositeConstruct %164 %25 %25 %25 -%366 = OpBitwiseXor %164 %364 %365 -%367 = OpShiftLeftLogical %8 %18 %25 -%368 = OpShiftLeftLogical %20 %24 %25 -%369 = OpCompositeConstruct %153 %18 %18 -%370 = OpCompositeConstruct %34 %25 %25 -%371 = OpShiftLeftLogical %153 %369 %370 -%372 = OpCompositeConstruct %164 %24 %24 %24 -%373 = OpCompositeConstruct %164 %25 %25 %25 -%374 = OpShiftLeftLogical %164 %372 %373 -%375 = OpShiftRightArithmetic %8 %18 %25 -%376 = OpShiftRightLogical %20 %24 %25 -%377 = OpCompositeConstruct %153 %18 %18 -%378 = OpCompositeConstruct %34 %25 %25 -%379 = OpShiftRightArithmetic %153 %377 %378 -%380 = OpCompositeConstruct %164 %24 %24 %24 -%381 = OpCompositeConstruct %164 %25 %25 %25 -%382 = OpShiftRightLogical %164 %380 %381 +OpBranch %338 +%338 = OpLabel +%339 = OpNot %8 %7 +%340 = OpNot %20 %25 +%341 = OpCompositeConstruct %155 %7 %7 +%342 = OpNot %155 %341 +%343 = OpCompositeConstruct %166 %25 %25 %25 +%344 = OpNot %166 %343 +%345 = OpBitwiseOr %8 %18 %7 +%346 = OpBitwiseOr %20 %24 %25 +%347 = OpCompositeConstruct %155 %18 %18 +%348 = OpCompositeConstruct %155 %7 %7 +%349 = OpBitwiseOr %155 %347 %348 +%350 = OpCompositeConstruct %166 %24 %24 %24 +%351 = OpCompositeConstruct %166 %25 %25 %25 +%352 = OpBitwiseOr %166 %350 %351 +%353 = OpBitwiseAnd %8 %18 %7 +%354 = OpBitwiseAnd %20 %24 %25 +%355 = OpCompositeConstruct %155 %18 %18 +%356 = OpCompositeConstruct %155 %7 %7 +%357 = OpBitwiseAnd %155 %355 %356 +%358 = OpCompositeConstruct %166 %24 %24 %24 +%359 = OpCompositeConstruct %166 %25 %25 %25 +%360 = OpBitwiseAnd %166 %358 %359 +%361 = OpBitwiseXor %8 %18 %7 +%362 = OpBitwiseXor %20 %24 %25 +%363 = OpCompositeConstruct %155 %18 %18 +%364 = OpCompositeConstruct %155 %7 %7 +%365 = OpBitwiseXor %155 %363 %364 +%366 = OpCompositeConstruct %166 %24 %24 %24 +%367 = OpCompositeConstruct %166 %25 %25 %25 +%368 = OpBitwiseXor %166 %366 %367 +%369 = OpShiftLeftLogical %8 %18 %25 +%370 = OpShiftLeftLogical %20 %24 %25 +%371 = OpCompositeConstruct %155 %18 %18 +%372 = OpCompositeConstruct %34 %25 %25 +%373 = OpShiftLeftLogical %155 %371 %372 +%374 = OpCompositeConstruct %166 %24 %24 %24 +%375 = OpCompositeConstruct %166 %25 %25 %25 +%376 = OpShiftLeftLogical %166 %374 %375 +%377 = OpShiftRightArithmetic %8 %18 %25 +%378 = OpShiftRightLogical %20 %24 %25 +%379 = OpCompositeConstruct %155 %18 %18 +%380 = OpCompositeConstruct %34 %25 %25 +%381 = OpShiftRightArithmetic %155 %379 %380 +%382 = OpCompositeConstruct %166 %24 %24 %24 +%383 = OpCompositeConstruct %166 %25 %25 %25 +%384 = OpShiftRightLogical %166 %382 %383 OpReturn OpFunctionEnd -%384 = OpFunction %2 None %134 -%383 = OpLabel -OpBranch %385 +%386 = OpFunction %2 None %136 %385 = OpLabel -%386 = OpIEqual %10 %18 %7 -%387 = OpIEqual %10 %24 %25 -%388 = OpFOrdEqual %10 %14 %3 -%389 = OpCompositeConstruct %153 %18 %18 -%390 = OpCompositeConstruct %153 %7 %7 -%391 = OpIEqual %137 %389 %390 -%392 = OpCompositeConstruct %164 %24 %24 %24 -%393 = OpCompositeConstruct %164 %25 %25 %25 -%394 = OpIEqual %100 %392 %393 -%395 = OpCompositeConstruct %26 %14 %14 %14 %14 -%396 = OpCompositeConstruct %26 %3 %3 %3 %3 -%397 = OpFOrdEqual %28 %395 %396 -%398 = OpINotEqual %10 %18 %7 -%399 = OpINotEqual %10 %24 %25 -%400 = OpFOrdNotEqual %10 %14 %3 -%401 = OpCompositeConstruct %153 %18 %18 -%402 = OpCompositeConstruct %153 %7 %7 -%403 = OpINotEqual %137 %401 %402 -%404 = OpCompositeConstruct %164 %24 %24 %24 -%405 = OpCompositeConstruct %164 %25 %25 %25 -%406 = OpINotEqual %100 %404 %405 -%407 = OpCompositeConstruct %26 %14 %14 %14 %14 -%408 = OpCompositeConstruct %26 %3 %3 %3 %3 -%409 = OpFOrdNotEqual %28 %407 %408 -%410 = OpSLessThan %10 %18 %7 -%411 = OpULessThan %10 %24 %25 -%412 = OpFOrdLessThan %10 %14 %3 -%413 = OpCompositeConstruct %153 %18 %18 -%414 = OpCompositeConstruct %153 %7 %7 -%415 = OpSLessThan %137 %413 %414 -%416 = OpCompositeConstruct %164 %24 %24 %24 -%417 = OpCompositeConstruct %164 %25 %25 %25 -%418 = OpULessThan %100 %416 %417 -%419 = OpCompositeConstruct %26 %14 %14 %14 %14 -%420 = OpCompositeConstruct %26 %3 %3 %3 %3 -%421 = OpFOrdLessThan %28 %419 %420 -%422 = OpSLessThanEqual %10 %18 %7 -%423 = OpULessThanEqual %10 %24 %25 -%424 = OpFOrdLessThanEqual %10 %14 %3 -%425 = OpCompositeConstruct %153 %18 %18 -%426 = OpCompositeConstruct %153 %7 %7 -%427 = OpSLessThanEqual %137 %425 %426 -%428 = OpCompositeConstruct %164 %24 %24 %24 -%429 = OpCompositeConstruct %164 %25 %25 %25 -%430 = OpULessThanEqual %100 %428 %429 -%431 = OpCompositeConstruct %26 %14 %14 %14 %14 -%432 = OpCompositeConstruct %26 %3 %3 %3 %3 -%433 = OpFOrdLessThanEqual %28 %431 %432 -%434 = OpSGreaterThan %10 %18 %7 -%435 = OpUGreaterThan %10 %24 %25 -%436 = OpFOrdGreaterThan %10 %14 %3 -%437 = OpCompositeConstruct %153 %18 %18 -%438 = OpCompositeConstruct %153 %7 %7 -%439 = OpSGreaterThan %137 %437 %438 -%440 = OpCompositeConstruct %164 %24 %24 %24 -%441 = OpCompositeConstruct %164 %25 %25 %25 -%442 = OpUGreaterThan %100 %440 %441 -%443 = OpCompositeConstruct %26 %14 %14 %14 %14 -%444 = OpCompositeConstruct %26 %3 %3 %3 %3 -%445 = OpFOrdGreaterThan %28 %443 %444 -%446 = OpSGreaterThanEqual %10 %18 %7 -%447 = OpUGreaterThanEqual %10 %24 %25 -%448 = OpFOrdGreaterThanEqual %10 %14 %3 -%449 = OpCompositeConstruct %153 %18 %18 -%450 = OpCompositeConstruct %153 %7 %7 -%451 = OpSGreaterThanEqual %137 %449 %450 -%452 = OpCompositeConstruct %164 %24 %24 %24 -%453 = OpCompositeConstruct %164 %25 %25 %25 -%454 = OpUGreaterThanEqual %100 %452 %453 -%455 = OpCompositeConstruct %26 %14 %14 %14 %14 -%456 = OpCompositeConstruct %26 %3 %3 %3 %3 -%457 = OpFOrdGreaterThanEqual %28 %455 %456 +OpBranch %387 +%387 = OpLabel +%388 = OpIEqual %10 %18 %7 +%389 = OpIEqual %10 %24 %25 +%390 = OpFOrdEqual %10 %14 %3 +%391 = OpCompositeConstruct %155 %18 %18 +%392 = OpCompositeConstruct %155 %7 %7 +%393 = OpIEqual %139 %391 %392 +%394 = OpCompositeConstruct %166 %24 %24 %24 +%395 = OpCompositeConstruct %166 %25 %25 %25 +%396 = OpIEqual %102 %394 %395 +%397 = OpCompositeConstruct %26 %14 %14 %14 %14 +%398 = OpCompositeConstruct %26 %3 %3 %3 %3 +%399 = OpFOrdEqual %28 %397 %398 +%400 = OpINotEqual %10 %18 %7 +%401 = OpINotEqual %10 %24 %25 +%402 = OpFOrdNotEqual %10 %14 %3 +%403 = OpCompositeConstruct %155 %18 %18 +%404 = OpCompositeConstruct %155 %7 %7 +%405 = OpINotEqual %139 %403 %404 +%406 = OpCompositeConstruct %166 %24 %24 %24 +%407 = OpCompositeConstruct %166 %25 %25 %25 +%408 = OpINotEqual %102 %406 %407 +%409 = OpCompositeConstruct %26 %14 %14 %14 %14 +%410 = OpCompositeConstruct %26 %3 %3 %3 %3 +%411 = OpFOrdNotEqual %28 %409 %410 +%412 = OpSLessThan %10 %18 %7 +%413 = OpULessThan %10 %24 %25 +%414 = OpFOrdLessThan %10 %14 %3 +%415 = OpCompositeConstruct %155 %18 %18 +%416 = OpCompositeConstruct %155 %7 %7 +%417 = OpSLessThan %139 %415 %416 +%418 = OpCompositeConstruct %166 %24 %24 %24 +%419 = OpCompositeConstruct %166 %25 %25 %25 +%420 = OpULessThan %102 %418 %419 +%421 = OpCompositeConstruct %26 %14 %14 %14 %14 +%422 = OpCompositeConstruct %26 %3 %3 %3 %3 +%423 = OpFOrdLessThan %28 %421 %422 +%424 = OpSLessThanEqual %10 %18 %7 +%425 = OpULessThanEqual %10 %24 %25 +%426 = OpFOrdLessThanEqual %10 %14 %3 +%427 = OpCompositeConstruct %155 %18 %18 +%428 = OpCompositeConstruct %155 %7 %7 +%429 = OpSLessThanEqual %139 %427 %428 +%430 = OpCompositeConstruct %166 %24 %24 %24 +%431 = OpCompositeConstruct %166 %25 %25 %25 +%432 = OpULessThanEqual %102 %430 %431 +%433 = OpCompositeConstruct %26 %14 %14 %14 %14 +%434 = OpCompositeConstruct %26 %3 %3 %3 %3 +%435 = OpFOrdLessThanEqual %28 %433 %434 +%436 = OpSGreaterThan %10 %18 %7 +%437 = OpUGreaterThan %10 %24 %25 +%438 = OpFOrdGreaterThan %10 %14 %3 +%439 = OpCompositeConstruct %155 %18 %18 +%440 = OpCompositeConstruct %155 %7 %7 +%441 = OpSGreaterThan %139 %439 %440 +%442 = OpCompositeConstruct %166 %24 %24 %24 +%443 = OpCompositeConstruct %166 %25 %25 %25 +%444 = OpUGreaterThan %102 %442 %443 +%445 = OpCompositeConstruct %26 %14 %14 %14 %14 +%446 = OpCompositeConstruct %26 %3 %3 %3 %3 +%447 = OpFOrdGreaterThan %28 %445 %446 +%448 = OpSGreaterThanEqual %10 %18 %7 +%449 = OpUGreaterThanEqual %10 %24 %25 +%450 = OpFOrdGreaterThanEqual %10 %14 %3 +%451 = OpCompositeConstruct %155 %18 %18 +%452 = OpCompositeConstruct %155 %7 %7 +%453 = OpSGreaterThanEqual %139 %451 %452 +%454 = OpCompositeConstruct %166 %24 %24 %24 +%455 = OpCompositeConstruct %166 %25 %25 %25 +%456 = OpUGreaterThanEqual %102 %454 %455 +%457 = OpCompositeConstruct %26 %14 %14 %14 %14 +%458 = OpCompositeConstruct %26 %3 %3 %3 %3 +%459 = OpFOrdGreaterThanEqual %28 %457 %458 OpReturn OpFunctionEnd -%461 = OpFunction %2 None %134 -%460 = OpLabel -%458 = OpVariable %459 Function %7 -OpBranch %462 -%462 = OpLabel -%463 = OpLoad %8 %458 -%464 = OpIAdd %8 %463 %7 -OpStore %458 %464 -%465 = OpLoad %8 %458 -%466 = OpISub %8 %465 %7 -OpStore %458 %466 -%467 = OpLoad %8 %458 -%468 = OpLoad %8 %458 -%469 = OpIMul %8 %467 %468 -OpStore %458 %469 -%470 = OpLoad %8 %458 -%471 = OpLoad %8 %458 -%472 = OpSDiv %8 %470 %471 -OpStore %458 %472 -%473 = OpLoad %8 %458 -%474 = OpSRem %8 %473 %7 -OpStore %458 %474 -%475 = OpLoad %8 %458 -%476 = OpBitwiseAnd %8 %475 %11 -OpStore %458 %476 -%477 = OpLoad %8 %458 -%478 = OpBitwiseOr %8 %477 %11 -OpStore %458 %478 -%479 = OpLoad %8 %458 -%480 = OpBitwiseXor %8 %479 %11 -OpStore %458 %480 -%481 = OpLoad %8 %458 -%482 = OpShiftLeftLogical %8 %481 %24 -OpStore %458 %482 -%483 = OpLoad %8 %458 -%484 = OpShiftRightArithmetic %8 %483 %25 -OpStore %458 %484 -%485 = OpLoad %8 %458 -%486 = OpIAdd %8 %485 %7 -OpStore %458 %486 -%487 = OpLoad %8 %458 -%488 = OpISub %8 %487 %7 -OpStore %458 %488 +%465 = OpFunction %2 None %136 +%464 = OpLabel +%460 = OpVariable %461 Function %7 +%462 = OpVariable %463 Function %55 +OpBranch %466 +%466 = OpLabel +%467 = OpLoad %8 %460 +%468 = OpIAdd %8 %467 %7 +OpStore %460 %468 +%469 = OpLoad %8 %460 +%470 = OpISub %8 %469 %7 +OpStore %460 %470 +%471 = OpLoad %8 %460 +%472 = OpLoad %8 %460 +%473 = OpIMul %8 %471 %472 +OpStore %460 %473 +%474 = OpLoad %8 %460 +%475 = OpLoad %8 %460 +%476 = OpSDiv %8 %474 %475 +OpStore %460 %476 +%477 = OpLoad %8 %460 +%478 = OpSRem %8 %477 %7 +OpStore %460 %478 +%479 = OpLoad %8 %460 +%480 = OpBitwiseAnd %8 %479 %11 +OpStore %460 %480 +%481 = OpLoad %8 %460 +%482 = OpBitwiseOr %8 %481 %11 +OpStore %460 %482 +%483 = OpLoad %8 %460 +%484 = OpBitwiseXor %8 %483 %11 +OpStore %460 %484 +%485 = OpLoad %8 %460 +%486 = OpShiftLeftLogical %8 %485 %24 +OpStore %460 %486 +%487 = OpLoad %8 %460 +%488 = OpShiftRightArithmetic %8 %487 %25 +OpStore %460 %488 +%489 = OpLoad %8 %460 +%490 = OpIAdd %8 %489 %7 +OpStore %460 %490 +%491 = OpLoad %8 %460 +%492 = OpISub %8 %491 %7 +OpStore %460 %492 +%494 = OpAccessChain %493 %462 %25 +%495 = OpLoad %8 %494 +%496 = OpIAdd %8 %495 %7 +%497 = OpAccessChain %493 %462 %25 +OpStore %497 %496 +%498 = OpAccessChain %493 %462 %25 +%499 = OpLoad %8 %498 +%500 = OpISub %8 %499 %7 +%501 = OpAccessChain %493 %462 %25 +OpStore %501 %500 OpReturn OpFunctionEnd -%490 = OpFunction %2 None %134 -%489 = OpLabel -OpBranch %491 -%491 = OpLabel -%492 = OpFunctionCall %26 %55 -%493 = OpFunctionCall %26 %80 -%494 = OpVectorShuffle %29 %40 %40 0 1 2 -%495 = OpFunctionCall %29 %97 %494 -%496 = OpFunctionCall %4 %110 -%497 = OpFunctionCall %2 %133 -%498 = OpFunctionCall %2 %151 -%499 = OpFunctionCall %2 %335 -%500 = OpFunctionCall %2 %384 -%501 = OpFunctionCall %2 %461 +%503 = OpFunction %2 None %136 +%502 = OpLabel +OpBranch %504 +%504 = OpLabel +%505 = OpFunctionCall %26 %57 +%506 = OpFunctionCall %26 %82 +%507 = OpVectorShuffle %29 %41 %41 0 1 2 +%508 = OpFunctionCall %29 %99 %507 +%509 = OpFunctionCall %4 %112 +%510 = OpFunctionCall %2 %135 +%511 = OpFunctionCall %2 %153 +%512 = OpFunctionCall %2 %337 +%513 = OpFunctionCall %2 %386 +%514 = OpFunctionCall %2 %465 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 952ab6068..ec6a73654 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -194,6 +194,7 @@ fn comparison() { fn assignment() { var a: i32 = 1; + var vec0_: vec3 = vec3(0, 0, 0); let _e6 = a; a = (_e6 + 1); @@ -221,6 +222,10 @@ fn assignment() { a = (_e36 + 1); let _e39 = a; a = (_e39 - 1); + let _e46 = vec0_.y; + vec0_.y = (_e46 + 1); + let _e51 = vec0_.y; + vec0_.y = (_e51 - 1); return; } From b688584d87fd76e7388b06421c358a5e984b350d Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 10 May 2022 17:56:05 +0200 Subject: [PATCH 1744/2212] [msl-out] fix pointers to private or workgroup address spaces possibly being read only --- src/back/msl/writer.rs | 4 +- tests/in/access.wgsl | 11 + .../access.assign_through_ptr.Compute.glsl | 35 + tests/out/glsl/access.atomics.Compute.glsl | 5 + tests/out/glsl/access.foo_frag.Fragment.glsl | 5 + tests/out/glsl/access.foo_vert.Vertex.glsl | 5 + tests/out/hlsl/access.hlsl | 14 + tests/out/hlsl/access.hlsl.config | 2 +- tests/out/msl/access.msl | 15 + tests/out/msl/policy-mix.msl | 4 +- tests/out/msl/quad-vert.msl | 4 +- tests/out/spv/access.spvasm | 613 +++++++++--------- tests/out/wgsl/access.wgsl | 12 + 13 files changed, 429 insertions(+), 300 deletions(-) create mode 100644 tests/out/glsl/access.assign_through_ptr.Compute.glsl diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 870b9b76f..56e2e4f25 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -462,7 +462,9 @@ impl crate::AddressSpace { // rely on the actual use of a global by functions. This means we // may end up with "const" even if the binding is read-write, // and that should be OK. - Self::Storage { .. } | Self::Private | Self::WorkGroup => true, + Self::Storage { .. } => true, + // These should always be read-write. + Self::Private | Self::WorkGroup => false, // These translate to `constant` address space, no need for qualifiers. Self::Uniform | Self::PushConstant => false, // Not applicable. diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index ee426876d..3b859db42 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -120,3 +120,14 @@ fn atomics() { // tmp = atomicCompareExchangeWeak(&bar.atom, 5, 5); atomicStore(&bar.atom, value); } + +var val: u32; + +fn assign_through_ptr_fn(p: ptr) { + *p = 42u; +} + +@compute @workgroup_size(1) +fn assign_through_ptr() { + assign_through_ptr_fn(&val); +} diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/tests/out/glsl/access.assign_through_ptr.Compute.glsl new file mode 100644 index 000000000..f90e0f015 --- /dev/null +++ b/tests/out/glsl/access.assign_through_ptr.Compute.glsl @@ -0,0 +1,35 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +struct AlignedWrapper { + int value; +}; +struct Baz { + mat3x2 m; +}; +shared uint val; + + +float read_from_private(inout float foo_1) { + float _e4 = foo_1; + return _e4; +} + +float test_arr_as_arg(float a[5][10]) { + return a[4][9]; +} + +void assign_through_ptr_fn(inout uint p) { + p = 42u; + return; +} + +void main() { + assign_through_ptr_fn(val); + return; +} + diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 2ab1b4fa8..8485b1628 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -29,6 +29,11 @@ float test_arr_as_arg(float a[5][10]) { return a[4][9]; } +void assign_through_ptr_fn(inout uint p) { + p = 42u; + return; +} + void main() { int tmp = 0; int value = _group_0_binding_0_cs.atom; diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index fcd3e4300..189702c5d 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -30,6 +30,11 @@ float test_arr_as_arg(float a[5][10]) { return a[4][9]; } +void assign_through_ptr_fn(inout uint p) { + p = 42u; + return; +} + void main() { _group_0_binding_0_fs._matrix[1][2] = 1.0; _group_0_binding_0_fs._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index 5eead818e..b53af9437 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -66,6 +66,11 @@ float test_arr_as_arg(float a[5][10]) { return a[4][9]; } +void assign_through_ptr_fn(inout uint p) { + p = 42u; + return; +} + void main() { uint vi = uint(gl_VertexID); float foo = 0.0; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 4bb113716..3b76080d4 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -21,6 +21,7 @@ float Constructarray5_array10_float__(float arg0[10], float arg1[10], float arg2 RWByteAddressBuffer bar : register(u0); cbuffer baz : register(b1) { Baz baz; } RWByteAddressBuffer qux : register(u2); +groupshared uint val; float3x2 GetMatmOnBaz(Baz obj) { return float3x2(obj.m_0, obj.m_1, obj.m_2); @@ -104,6 +105,12 @@ float test_arr_as_arg(float a[5][10]) return a[4][9]; } +void assign_through_ptr_fn(inout uint p) +{ + p = 42u; + return; +} + uint NagaBufferLengthRW(RWByteAddressBuffer buffer) { uint ret; @@ -190,3 +197,10 @@ void atomics() bar.Store(96, asuint(value_1)); return; } + +[numthreads(1, 1, 1)] +void assign_through_ptr() +{ + assign_through_ptr_fn(val); + return; +} diff --git a/tests/out/hlsl/access.hlsl.config b/tests/out/hlsl/access.hlsl.config index f6a8845ad..b68dda72d 100644 --- a/tests/out/hlsl/access.hlsl.config +++ b/tests/out/hlsl/access.hlsl.config @@ -1,3 +1,3 @@ vertex=(foo_vert:vs_5_1 ) fragment=(foo_frag:ps_5_1 ) -compute=(atomics:cs_5_1 ) +compute=(atomics:cs_5_1 assign_through_ptr:cs_5_1 ) diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index f3f11559c..c90483cd5 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -92,6 +92,13 @@ float test_arr_as_arg( return a.inner[4].inner[9]; } +void assign_through_ptr_fn( + threadgroup uint& p +) { + p = 42u; + return; +} + struct foo_vertInput { }; struct foo_vertOutput { @@ -165,3 +172,11 @@ kernel void atomics( metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed); return; } + + +kernel void assign_through_ptr( + threadgroup uint& val +) { + assign_through_ptr_fn(val); + return; +} diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index 430e36610..dd780641f 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -39,8 +39,8 @@ metal::float4 mock_function( device InStorage const& in_storage, constant InUniform& in_uniform, metal::texture2d_array image_2d_array, - threadgroup type_5 const& in_workgroup, - thread type_6 const& in_private + threadgroup type_5& in_workgroup, + thread type_6& in_private ) { type_9 in_function = {}; for(int _i=0; _i<2; ++_i) in_function.inner[_i] = type_9 {metal::float4(0.7070000171661377, 0.0, 0.0, 1.0), metal::float4(0.0, 0.7070000171661377, 0.0, 1.0)}.inner[_i]; diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index ade1791db..918396a08 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -23,9 +23,9 @@ constant gl_PerVertex const_gl_PerVertex = {const_type_3_, 1.0, const_type_5_, c void main_1( thread metal::float2& v_uv, - thread metal::float2 const& a_uv_1, + thread metal::float2& a_uv_1, thread gl_PerVertex& perVertexStruct, - thread metal::float2 const& a_pos_1 + thread metal::float2& a_pos_1 ) { metal::float2 _e12 = a_uv_1; v_uv = _e12; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 21e92ab2b..d42e6a443 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,77 +1,83 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 230 +; Bound: 242 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %149 "foo_vert" %144 %147 -OpEntryPoint Fragment %188 "foo_frag" %187 -OpEntryPoint GLCompute %207 "atomics" -OpExecutionMode %188 OriginUpperLeft -OpExecutionMode %207 LocalSize 1 1 1 +OpEntryPoint Vertex %157 "foo_vert" %152 %155 +OpEntryPoint Fragment %196 "foo_frag" %195 +OpEntryPoint GLCompute %215 "atomics" +OpEntryPoint GLCompute %239 "assign_through_ptr" +OpExecutionMode %196 OriginUpperLeft +OpExecutionMode %215 LocalSize 1 1 1 +OpExecutionMode %239 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %32 0 "value" -OpName %32 "AlignedWrapper" -OpMemberName %41 0 "_matrix" -OpMemberName %41 1 "matrix_array" -OpMemberName %41 2 "atom" -OpMemberName %41 3 "arr" -OpMemberName %41 4 "data" -OpName %41 "Bar" -OpMemberName %43 0 "m" -OpName %43 "Baz" -OpName %54 "bar" -OpName %56 "baz" -OpName %59 "qux" -OpName %62 "idx" -OpName %64 "t" -OpName %68 "test_matrix_within_struct_accesses" -OpName %127 "foo" -OpName %128 "read_from_private" -OpName %133 "a" -OpName %134 "test_arr_as_arg" -OpName %139 "foo" -OpName %140 "c" -OpName %144 "vi" -OpName %149 "foo_vert" -OpName %188 "foo_frag" -OpName %204 "tmp" -OpName %207 "atomics" -OpMemberDecorate %32 0 Offset 0 -OpDecorate %37 ArrayStride 16 -OpDecorate %39 ArrayStride 8 +OpMemberName %33 0 "value" +OpName %33 "AlignedWrapper" +OpMemberName %42 0 "_matrix" +OpMemberName %42 1 "matrix_array" +OpMemberName %42 2 "atom" +OpMemberName %42 3 "arr" +OpMemberName %42 4 "data" +OpName %42 "Bar" +OpMemberName %44 0 "m" +OpName %44 "Baz" +OpName %56 "bar" +OpName %58 "baz" +OpName %61 "qux" +OpName %64 "val" +OpName %65 "idx" +OpName %67 "t" +OpName %71 "test_matrix_within_struct_accesses" +OpName %130 "foo" +OpName %131 "read_from_private" +OpName %136 "a" +OpName %137 "test_arr_as_arg" +OpName %143 "p" +OpName %144 "assign_through_ptr_fn" +OpName %147 "foo" +OpName %148 "c" +OpName %152 "vi" +OpName %157 "foo_vert" +OpName %196 "foo_frag" +OpName %212 "tmp" +OpName %215 "atomics" +OpName %239 "assign_through_ptr" +OpMemberDecorate %33 0 Offset 0 +OpDecorate %38 ArrayStride 16 OpDecorate %40 ArrayStride 8 -OpMemberDecorate %41 0 Offset 0 -OpMemberDecorate %41 0 ColMajor -OpMemberDecorate %41 0 MatrixStride 16 -OpMemberDecorate %41 1 Offset 64 -OpMemberDecorate %41 1 ColMajor -OpMemberDecorate %41 1 MatrixStride 8 -OpMemberDecorate %41 2 Offset 96 -OpMemberDecorate %41 3 Offset 104 -OpMemberDecorate %41 4 Offset 120 -OpMemberDecorate %43 0 Offset 0 -OpMemberDecorate %43 0 ColMajor -OpMemberDecorate %43 0 MatrixStride 8 -OpDecorate %46 ArrayStride 4 -OpDecorate %47 ArrayStride 40 -OpDecorate %50 ArrayStride 4 -OpDecorate %54 DescriptorSet 0 -OpDecorate %54 Binding 0 -OpDecorate %41 Block +OpDecorate %41 ArrayStride 8 +OpMemberDecorate %42 0 Offset 0 +OpMemberDecorate %42 0 ColMajor +OpMemberDecorate %42 0 MatrixStride 16 +OpMemberDecorate %42 1 Offset 64 +OpMemberDecorate %42 1 ColMajor +OpMemberDecorate %42 1 MatrixStride 8 +OpMemberDecorate %42 2 Offset 96 +OpMemberDecorate %42 3 Offset 104 +OpMemberDecorate %42 4 Offset 120 +OpMemberDecorate %44 0 Offset 0 +OpMemberDecorate %44 0 ColMajor +OpMemberDecorate %44 0 MatrixStride 8 +OpDecorate %47 ArrayStride 4 +OpDecorate %48 ArrayStride 40 +OpDecorate %51 ArrayStride 4 OpDecorate %56 DescriptorSet 0 -OpDecorate %56 Binding 1 -OpDecorate %57 Block -OpMemberDecorate %57 0 Offset 0 -OpDecorate %59 DescriptorSet 0 -OpDecorate %59 Binding 2 -OpDecorate %60 Block -OpMemberDecorate %60 0 Offset 0 -OpDecorate %144 BuiltIn VertexIndex -OpDecorate %147 BuiltIn Position -OpDecorate %187 Location 0 +OpDecorate %56 Binding 0 +OpDecorate %42 Block +OpDecorate %58 DescriptorSet 0 +OpDecorate %58 Binding 1 +OpDecorate %59 Block +OpMemberDecorate %59 0 Offset 0 +OpDecorate %61 DescriptorSet 0 +OpDecorate %61 Binding 2 +OpDecorate %62 Block +OpMemberDecorate %62 0 Offset 0 +OpDecorate %152 BuiltIn VertexIndex +OpDecorate %155 BuiltIn Position +OpDecorate %195 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -102,248 +108,267 @@ OpDecorate %187 Location 0 %29 = OpConstant %26 1 %30 = OpConstant %4 42 %31 = OpConstant %26 0 -%32 = OpTypeStruct %4 -%34 = OpTypeVector %9 3 -%33 = OpTypeMatrix %34 4 -%36 = OpTypeVector %9 2 -%35 = OpTypeMatrix %36 2 -%37 = OpTypeArray %35 %3 -%38 = OpTypeVector %26 2 -%39 = OpTypeArray %38 %3 -%40 = OpTypeRuntimeArray %32 -%41 = OpTypeStruct %33 %37 %4 %39 %40 -%42 = OpTypeMatrix %36 3 -%43 = OpTypeStruct %42 -%44 = OpTypeVector %4 2 -%45 = OpTypePointer Function %9 -%46 = OpTypeArray %9 %21 -%47 = OpTypeArray %46 %22 -%48 = OpTypeVector %9 4 -%49 = OpTypePointer StorageBuffer %4 -%50 = OpTypeArray %4 %22 -%51 = OpConstantComposite %46 %24 %24 %24 %24 %24 %24 %24 %24 %24 %24 -%52 = OpConstantComposite %47 %51 %51 %51 %51 %51 -%53 = OpConstantComposite %44 %7 %7 -%55 = OpTypePointer StorageBuffer %41 -%54 = OpVariable %55 StorageBuffer -%57 = OpTypeStruct %43 -%58 = OpTypePointer Uniform %57 -%56 = OpVariable %58 Uniform -%60 = OpTypeStruct %44 -%61 = OpTypePointer StorageBuffer %60 -%59 = OpVariable %61 StorageBuffer -%63 = OpTypePointer Function %4 -%65 = OpTypePointer Function %43 -%66 = OpConstantNull %43 -%69 = OpTypeFunction %2 -%70 = OpTypePointer Uniform %43 -%72 = OpTypePointer StorageBuffer %44 -%76 = OpTypePointer Uniform %42 -%79 = OpTypePointer Uniform %36 -%85 = OpTypePointer Uniform %9 -%105 = OpTypePointer Function %42 -%111 = OpTypePointer Function %36 -%117 = OpTypePointer Function %9 -%129 = OpTypeFunction %9 %45 -%135 = OpTypeFunction %9 %47 -%141 = OpTypePointer Function %50 -%142 = OpConstantNull %50 -%145 = OpTypePointer Input %26 -%144 = OpVariable %145 Input -%148 = OpTypePointer Output %48 -%147 = OpVariable %148 Output -%155 = OpTypePointer StorageBuffer %33 -%158 = OpTypePointer StorageBuffer %39 -%161 = OpTypePointer StorageBuffer %34 -%162 = OpTypePointer StorageBuffer %9 -%165 = OpTypePointer StorageBuffer %40 -%168 = OpTypePointer StorageBuffer %32 -%169 = OpConstant %26 4 -%181 = OpTypeVector %4 4 -%187 = OpVariable %148 Output -%205 = OpConstantNull %4 -%209 = OpTypePointer StorageBuffer %4 -%212 = OpConstant %26 64 -%68 = OpFunction %2 None %69 -%67 = OpLabel -%62 = OpVariable %63 Function %5 -%64 = OpVariable %65 Function %66 -%71 = OpAccessChain %70 %56 %31 -OpBranch %73 -%73 = OpLabel -%74 = OpLoad %4 %62 -%75 = OpISub %4 %74 %6 -OpStore %62 %75 -%77 = OpAccessChain %76 %71 %31 -%78 = OpLoad %42 %77 -%80 = OpAccessChain %79 %71 %31 %31 -%81 = OpLoad %36 %80 -%82 = OpLoad %4 %62 -%83 = OpAccessChain %79 %71 %31 %82 -%84 = OpLoad %36 %83 -%86 = OpAccessChain %85 %71 %31 %31 %29 -%87 = OpLoad %9 %86 -%88 = OpLoad %4 %62 -%89 = OpAccessChain %85 %71 %31 %31 %88 +%32 = OpConstant %26 42 +%33 = OpTypeStruct %4 +%35 = OpTypeVector %9 3 +%34 = OpTypeMatrix %35 4 +%37 = OpTypeVector %9 2 +%36 = OpTypeMatrix %37 2 +%38 = OpTypeArray %36 %3 +%39 = OpTypeVector %26 2 +%40 = OpTypeArray %39 %3 +%41 = OpTypeRuntimeArray %33 +%42 = OpTypeStruct %34 %38 %4 %40 %41 +%43 = OpTypeMatrix %37 3 +%44 = OpTypeStruct %43 +%45 = OpTypeVector %4 2 +%46 = OpTypePointer Function %9 +%47 = OpTypeArray %9 %21 +%48 = OpTypeArray %47 %22 +%49 = OpTypeVector %9 4 +%50 = OpTypePointer StorageBuffer %4 +%51 = OpTypeArray %4 %22 +%52 = OpTypePointer Workgroup %26 +%53 = OpConstantComposite %47 %24 %24 %24 %24 %24 %24 %24 %24 %24 %24 +%54 = OpConstantComposite %48 %53 %53 %53 %53 %53 +%55 = OpConstantComposite %45 %7 %7 +%57 = OpTypePointer StorageBuffer %42 +%56 = OpVariable %57 StorageBuffer +%59 = OpTypeStruct %44 +%60 = OpTypePointer Uniform %59 +%58 = OpVariable %60 Uniform +%62 = OpTypeStruct %45 +%63 = OpTypePointer StorageBuffer %62 +%61 = OpVariable %63 StorageBuffer +%64 = OpVariable %52 Workgroup +%66 = OpTypePointer Function %4 +%68 = OpTypePointer Function %44 +%69 = OpConstantNull %44 +%72 = OpTypeFunction %2 +%73 = OpTypePointer Uniform %44 +%75 = OpTypePointer StorageBuffer %45 +%79 = OpTypePointer Uniform %43 +%82 = OpTypePointer Uniform %37 +%88 = OpTypePointer Uniform %9 +%108 = OpTypePointer Function %43 +%114 = OpTypePointer Function %37 +%120 = OpTypePointer Function %9 +%132 = OpTypeFunction %9 %46 +%138 = OpTypeFunction %9 %48 +%145 = OpTypeFunction %2 %52 +%149 = OpTypePointer Function %51 +%150 = OpConstantNull %51 +%153 = OpTypePointer Input %26 +%152 = OpVariable %153 Input +%156 = OpTypePointer Output %49 +%155 = OpVariable %156 Output +%163 = OpTypePointer StorageBuffer %34 +%166 = OpTypePointer StorageBuffer %40 +%169 = OpTypePointer StorageBuffer %35 +%170 = OpTypePointer StorageBuffer %9 +%173 = OpTypePointer StorageBuffer %41 +%176 = OpTypePointer StorageBuffer %33 +%177 = OpConstant %26 4 +%189 = OpTypeVector %4 4 +%195 = OpVariable %156 Output +%213 = OpConstantNull %4 +%217 = OpTypePointer StorageBuffer %4 +%220 = OpConstant %26 64 +%71 = OpFunction %2 None %72 +%70 = OpLabel +%65 = OpVariable %66 Function %5 +%67 = OpVariable %68 Function %69 +%74 = OpAccessChain %73 %58 %31 +OpBranch %76 +%76 = OpLabel +%77 = OpLoad %4 %65 +%78 = OpISub %4 %77 %6 +OpStore %65 %78 +%80 = OpAccessChain %79 %74 %31 +%81 = OpLoad %43 %80 +%83 = OpAccessChain %82 %74 %31 %31 +%84 = OpLoad %37 %83 +%85 = OpLoad %4 %65 +%86 = OpAccessChain %82 %74 %31 %85 +%87 = OpLoad %37 %86 +%89 = OpAccessChain %88 %74 %31 %31 %29 %90 = OpLoad %9 %89 -%91 = OpLoad %4 %62 -%92 = OpAccessChain %85 %71 %31 %91 %29 +%91 = OpLoad %4 %65 +%92 = OpAccessChain %88 %74 %31 %31 %91 %93 = OpLoad %9 %92 -%94 = OpLoad %4 %62 -%95 = OpLoad %4 %62 -%96 = OpAccessChain %85 %71 %31 %94 %95 -%97 = OpLoad %9 %96 -%98 = OpCompositeConstruct %36 %8 %8 -%99 = OpCompositeConstruct %36 %10 %10 -%100 = OpCompositeConstruct %36 %11 %11 -%101 = OpCompositeConstruct %42 %98 %99 %100 -%102 = OpCompositeConstruct %43 %101 -OpStore %64 %102 -%103 = OpLoad %4 %62 -%104 = OpIAdd %4 %103 %6 -OpStore %62 %104 -%106 = OpCompositeConstruct %36 %12 %12 -%107 = OpCompositeConstruct %36 %13 %13 -%108 = OpCompositeConstruct %36 %14 %14 -%109 = OpCompositeConstruct %42 %106 %107 %108 -%110 = OpAccessChain %105 %64 %31 -OpStore %110 %109 -%112 = OpCompositeConstruct %36 %15 %15 -%113 = OpAccessChain %111 %64 %31 %31 +%94 = OpLoad %4 %65 +%95 = OpAccessChain %88 %74 %31 %94 %29 +%96 = OpLoad %9 %95 +%97 = OpLoad %4 %65 +%98 = OpLoad %4 %65 +%99 = OpAccessChain %88 %74 %31 %97 %98 +%100 = OpLoad %9 %99 +%101 = OpCompositeConstruct %37 %8 %8 +%102 = OpCompositeConstruct %37 %10 %10 +%103 = OpCompositeConstruct %37 %11 %11 +%104 = OpCompositeConstruct %43 %101 %102 %103 +%105 = OpCompositeConstruct %44 %104 +OpStore %67 %105 +%106 = OpLoad %4 %65 +%107 = OpIAdd %4 %106 %6 +OpStore %65 %107 +%109 = OpCompositeConstruct %37 %12 %12 +%110 = OpCompositeConstruct %37 %13 %13 +%111 = OpCompositeConstruct %37 %14 %14 +%112 = OpCompositeConstruct %43 %109 %110 %111 +%113 = OpAccessChain %108 %67 %31 OpStore %113 %112 -%114 = OpLoad %4 %62 -%115 = OpCompositeConstruct %36 %16 %16 -%116 = OpAccessChain %111 %64 %31 %114 +%115 = OpCompositeConstruct %37 %15 %15 +%116 = OpAccessChain %114 %67 %31 %31 OpStore %116 %115 -%118 = OpAccessChain %117 %64 %31 %31 %29 -OpStore %118 %17 -%119 = OpLoad %4 %62 -%120 = OpAccessChain %117 %64 %31 %31 %119 -OpStore %120 %18 -%121 = OpLoad %4 %62 -%122 = OpAccessChain %117 %64 %31 %121 %29 -OpStore %122 %19 -%123 = OpLoad %4 %62 -%124 = OpLoad %4 %62 -%125 = OpAccessChain %117 %64 %31 %123 %124 -OpStore %125 %20 +%117 = OpLoad %4 %65 +%118 = OpCompositeConstruct %37 %16 %16 +%119 = OpAccessChain %114 %67 %31 %117 +OpStore %119 %118 +%121 = OpAccessChain %120 %67 %31 %31 %29 +OpStore %121 %17 +%122 = OpLoad %4 %65 +%123 = OpAccessChain %120 %67 %31 %31 %122 +OpStore %123 %18 +%124 = OpLoad %4 %65 +%125 = OpAccessChain %120 %67 %31 %124 %29 +OpStore %125 %19 +%126 = OpLoad %4 %65 +%127 = OpLoad %4 %65 +%128 = OpAccessChain %120 %67 %31 %126 %127 +OpStore %128 %20 OpReturn OpFunctionEnd -%128 = OpFunction %9 None %129 -%127 = OpFunctionParameter %45 -%126 = OpLabel -OpBranch %130 -%130 = OpLabel -%131 = OpLoad %9 %127 -OpReturnValue %131 +%131 = OpFunction %9 None %132 +%130 = OpFunctionParameter %46 +%129 = OpLabel +OpBranch %133 +%133 = OpLabel +%134 = OpLoad %9 %130 +OpReturnValue %134 OpFunctionEnd -%134 = OpFunction %9 None %135 -%133 = OpFunctionParameter %47 -%132 = OpLabel -OpBranch %136 -%136 = OpLabel -%137 = OpCompositeExtract %46 %133 4 -%138 = OpCompositeExtract %9 %137 9 -OpReturnValue %138 +%137 = OpFunction %9 None %138 +%136 = OpFunctionParameter %48 +%135 = OpLabel +OpBranch %139 +%139 = OpLabel +%140 = OpCompositeExtract %47 %136 4 +%141 = OpCompositeExtract %9 %140 9 +OpReturnValue %141 OpFunctionEnd -%149 = OpFunction %2 None %69 -%143 = OpLabel -%139 = OpVariable %45 Function %24 -%140 = OpVariable %141 Function %142 -%146 = OpLoad %26 %144 -%150 = OpAccessChain %70 %56 %31 -%151 = OpAccessChain %72 %59 %31 -OpBranch %152 -%152 = OpLabel -%153 = OpLoad %9 %139 -OpStore %139 %8 -%154 = OpFunctionCall %2 %68 -%156 = OpAccessChain %155 %54 %31 -%157 = OpLoad %33 %156 -%159 = OpAccessChain %158 %54 %25 -%160 = OpLoad %39 %159 -%163 = OpAccessChain %162 %54 %31 %25 %31 -%164 = OpLoad %9 %163 -%166 = OpArrayLength %26 %54 4 -%167 = OpISub %26 %166 %27 -%170 = OpAccessChain %49 %54 %169 %167 %31 -%171 = OpLoad %4 %170 -%172 = OpLoad %44 %151 -%173 = OpFunctionCall %9 %128 %139 -%174 = OpConvertFToS %4 %164 -%175 = OpCompositeConstruct %50 %171 %174 %28 %23 %22 -OpStore %140 %175 -%176 = OpIAdd %26 %146 %29 -%177 = OpAccessChain %63 %140 %176 -OpStore %177 %30 -%178 = OpAccessChain %63 %140 %146 +%144 = OpFunction %2 None %145 +%143 = OpFunctionParameter %52 +%142 = OpLabel +OpBranch %146 +%146 = OpLabel +OpStore %143 %32 +OpReturn +OpFunctionEnd +%157 = OpFunction %2 None %72 +%151 = OpLabel +%147 = OpVariable %46 Function %24 +%148 = OpVariable %149 Function %150 +%154 = OpLoad %26 %152 +%158 = OpAccessChain %73 %58 %31 +%159 = OpAccessChain %75 %61 %31 +OpBranch %160 +%160 = OpLabel +%161 = OpLoad %9 %147 +OpStore %147 %8 +%162 = OpFunctionCall %2 %71 +%164 = OpAccessChain %163 %56 %31 +%165 = OpLoad %34 %164 +%167 = OpAccessChain %166 %56 %25 +%168 = OpLoad %40 %167 +%171 = OpAccessChain %170 %56 %31 %25 %31 +%172 = OpLoad %9 %171 +%174 = OpArrayLength %26 %56 4 +%175 = OpISub %26 %174 %27 +%178 = OpAccessChain %50 %56 %177 %175 %31 %179 = OpLoad %4 %178 -%180 = OpFunctionCall %9 %134 %52 -%182 = OpCompositeConstruct %181 %179 %179 %179 %179 -%183 = OpConvertSToF %48 %182 -%184 = OpMatrixTimesVector %34 %157 %183 -%185 = OpCompositeConstruct %48 %184 %10 -OpStore %147 %185 +%180 = OpLoad %45 %159 +%181 = OpFunctionCall %9 %131 %147 +%182 = OpConvertFToS %4 %172 +%183 = OpCompositeConstruct %51 %179 %182 %28 %23 %22 +OpStore %148 %183 +%184 = OpIAdd %26 %154 %29 +%185 = OpAccessChain %66 %148 %184 +OpStore %185 %30 +%186 = OpAccessChain %66 %148 %154 +%187 = OpLoad %4 %186 +%188 = OpFunctionCall %9 %137 %54 +%190 = OpCompositeConstruct %189 %187 %187 %187 %187 +%191 = OpConvertSToF %49 %190 +%192 = OpMatrixTimesVector %35 %165 %191 +%193 = OpCompositeConstruct %49 %192 %10 +OpStore %155 %193 OpReturn OpFunctionEnd -%188 = OpFunction %2 None %69 -%186 = OpLabel -%189 = OpAccessChain %72 %59 %31 -OpBranch %190 -%190 = OpLabel -%191 = OpAccessChain %162 %54 %31 %29 %27 -OpStore %191 %8 -%192 = OpCompositeConstruct %34 %24 %24 %24 -%193 = OpCompositeConstruct %34 %8 %8 %8 -%194 = OpCompositeConstruct %34 %10 %10 %10 -%195 = OpCompositeConstruct %34 %11 %11 %11 -%196 = OpCompositeConstruct %33 %192 %193 %194 %195 -%197 = OpAccessChain %155 %54 %31 -OpStore %197 %196 -%198 = OpCompositeConstruct %38 %31 %31 -%199 = OpCompositeConstruct %38 %29 %29 -%200 = OpCompositeConstruct %39 %198 %199 -%201 = OpAccessChain %158 %54 %25 -OpStore %201 %200 -%202 = OpAccessChain %49 %54 %169 %29 %31 -OpStore %202 %6 -OpStore %189 %53 -%203 = OpCompositeConstruct %48 %24 %24 %24 %24 -OpStore %187 %203 +%196 = OpFunction %2 None %72 +%194 = OpLabel +%197 = OpAccessChain %75 %61 %31 +OpBranch %198 +%198 = OpLabel +%199 = OpAccessChain %170 %56 %31 %29 %27 +OpStore %199 %8 +%200 = OpCompositeConstruct %35 %24 %24 %24 +%201 = OpCompositeConstruct %35 %8 %8 %8 +%202 = OpCompositeConstruct %35 %10 %10 %10 +%203 = OpCompositeConstruct %35 %11 %11 %11 +%204 = OpCompositeConstruct %34 %200 %201 %202 %203 +%205 = OpAccessChain %163 %56 %31 +OpStore %205 %204 +%206 = OpCompositeConstruct %39 %31 %31 +%207 = OpCompositeConstruct %39 %29 %29 +%208 = OpCompositeConstruct %40 %206 %207 +%209 = OpAccessChain %166 %56 %25 +OpStore %209 %208 +%210 = OpAccessChain %50 %56 %177 %29 %31 +OpStore %210 %6 +OpStore %197 %55 +%211 = OpCompositeConstruct %49 %24 %24 %24 %24 +OpStore %195 %211 OpReturn OpFunctionEnd -%207 = OpFunction %2 None %69 -%206 = OpLabel -%204 = OpVariable %63 Function %205 -OpBranch %208 -%208 = OpLabel -%210 = OpAccessChain %209 %54 %27 -%211 = OpAtomicLoad %4 %210 %6 %212 -%214 = OpAccessChain %209 %54 %27 -%213 = OpAtomicIAdd %4 %214 %6 %212 %22 -OpStore %204 %213 -%216 = OpAccessChain %209 %54 %27 -%215 = OpAtomicISub %4 %216 %6 %212 %22 -OpStore %204 %215 -%218 = OpAccessChain %209 %54 %27 -%217 = OpAtomicAnd %4 %218 %6 %212 %22 -OpStore %204 %217 -%220 = OpAccessChain %209 %54 %27 -%219 = OpAtomicOr %4 %220 %6 %212 %22 -OpStore %204 %219 -%222 = OpAccessChain %209 %54 %27 -%221 = OpAtomicXor %4 %222 %6 %212 %22 -OpStore %204 %221 -%224 = OpAccessChain %209 %54 %27 -%223 = OpAtomicSMin %4 %224 %6 %212 %22 -OpStore %204 %223 -%226 = OpAccessChain %209 %54 %27 -%225 = OpAtomicSMax %4 %226 %6 %212 %22 -OpStore %204 %225 -%228 = OpAccessChain %209 %54 %27 -%227 = OpAtomicExchange %4 %228 %6 %212 %22 -OpStore %204 %227 -%229 = OpAccessChain %209 %54 %27 -OpAtomicStore %229 %6 %212 %211 +%215 = OpFunction %2 None %72 +%214 = OpLabel +%212 = OpVariable %66 Function %213 +OpBranch %216 +%216 = OpLabel +%218 = OpAccessChain %217 %56 %27 +%219 = OpAtomicLoad %4 %218 %6 %220 +%222 = OpAccessChain %217 %56 %27 +%221 = OpAtomicIAdd %4 %222 %6 %220 %22 +OpStore %212 %221 +%224 = OpAccessChain %217 %56 %27 +%223 = OpAtomicISub %4 %224 %6 %220 %22 +OpStore %212 %223 +%226 = OpAccessChain %217 %56 %27 +%225 = OpAtomicAnd %4 %226 %6 %220 %22 +OpStore %212 %225 +%228 = OpAccessChain %217 %56 %27 +%227 = OpAtomicOr %4 %228 %6 %220 %22 +OpStore %212 %227 +%230 = OpAccessChain %217 %56 %27 +%229 = OpAtomicXor %4 %230 %6 %220 %22 +OpStore %212 %229 +%232 = OpAccessChain %217 %56 %27 +%231 = OpAtomicSMin %4 %232 %6 %220 %22 +OpStore %212 %231 +%234 = OpAccessChain %217 %56 %27 +%233 = OpAtomicSMax %4 %234 %6 %220 %22 +OpStore %212 %233 +%236 = OpAccessChain %217 %56 %27 +%235 = OpAtomicExchange %4 %236 %6 %220 %22 +OpStore %212 %235 +%237 = OpAccessChain %217 %56 %27 +OpAtomicStore %237 %6 %220 %219 +OpReturn +OpFunctionEnd +%239 = OpFunction %2 None %72 +%238 = OpLabel +OpBranch %240 +%240 = OpLabel +%241 = OpFunctionCall %2 %144 %64 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 752e3853d..315ade51a 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -20,6 +20,7 @@ var bar: Bar; var baz: Baz; @group(0) @binding(2) var qux: vec2; +var val: u32; fn test_matrix_within_struct_accesses() { var idx: i32 = 9; @@ -66,6 +67,11 @@ fn test_arr_as_arg(a: array,5>) -> f32 { return a[4][9]; } +fn assign_through_ptr_fn(p: ptr) { + (*p) = 42u; + return; +} + @vertex fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32 = 0.0; @@ -122,3 +128,9 @@ fn atomics() { atomicStore((&bar.atom), value_1); return; } + +@compute @workgroup_size(1, 1, 1) +fn assign_through_ptr() { + assign_through_ptr_fn((&val)); + return; +} From 95d5d165fbae8adb4fd5e5d37e51e7d0ab104137 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Thu, 12 May 2022 09:10:17 -0400 Subject: [PATCH 1745/2212] [valid] Fix bitflag assignments (#1915) --- src/valid/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 77b92152b..29ef658db 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -93,7 +93,7 @@ bitflags::bitflags! { /// Support for non-uniform indexing of uniform buffers and storage texture arrays. const UNIFORM_BUFFER_AND_STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING = 0x10; /// Support for non-uniform indexing of samplers. - const SAMPLER_NON_UNIFORM_INDEXING = 0x11; + const SAMPLER_NON_UNIFORM_INDEXING = 0x20; } } From afb6504b8b5e6b697f3d6c3d580a8c67a870bb43 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 12 May 2022 15:14:46 +0200 Subject: [PATCH 1746/2212] add support for identity matrix constructor --- src/back/glsl/mod.rs | 5 + src/back/hlsl/writer.rs | 31 +- src/back/msl/writer.rs | 4 + src/back/spv/block.rs | 1 + src/proc/typifier.rs | 9 + tests/in/operators.wgsl | 8 + tests/out/glsl/operators.main.Compute.glsl | 284 +++--- tests/out/hlsl/operators.hlsl | 284 +++--- tests/out/msl/operators.msl | 295 +++--- tests/out/spv/operators.spvasm | 1020 ++++++++++---------- tests/out/wgsl/operators.wgsl | 10 +- 11 files changed, 1016 insertions(+), 935 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index cb88562d8..5b7700ba9 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2895,6 +2895,11 @@ impl<'a, W: Write> Writer<'a, W> { // this is similar to `write_type`, but with the target kind let scalar = glsl_scalar(target_kind, width)?; match *inner { + TypeInner::Matrix { columns, rows, .. } => write!( + self.out, + "{}mat{}x{}", + scalar.prefix, columns as u8, rows as u8 + )?, TypeInner::Vector { size, .. } => { write!(self.out, "{}vec{}", scalar.prefix, size as u8)? } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 9a5f2cd61..9a7e84b44 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2141,9 +2141,32 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { convert, } => { let inner = func_ctx.info[expr].ty.inner_with(&module.types); - let (size_str, src_width) = match *inner { - TypeInner::Vector { size, width, .. } => (back::vector_size_str(size), width), - TypeInner::Scalar { width, .. } => ("", width), + let get_width = |src_width| kind.to_hlsl_str(convert.unwrap_or(src_width)); + match *inner { + TypeInner::Vector { size, width, .. } => { + write!( + self.out, + "{}{}(", + get_width(width)?, + back::vector_size_str(size) + )?; + } + TypeInner::Scalar { width, .. } => { + write!(self.out, "{}(", get_width(width)?,)?; + } + TypeInner::Matrix { + columns, + rows, + width, + } => { + write!( + self.out, + "{}{}x{}(", + get_width(width)?, + back::vector_size_str(columns), + back::vector_size_str(rows) + )?; + } _ => { return Err(Error::Unimplemented(format!( "write_expr expression::as {:?}", @@ -2151,8 +2174,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ))); } }; - let kind_str = kind.to_hlsl_str(convert.unwrap_or(src_width))?; - write!(self.out, "{}{}(", kind_str, size_str,)?; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")?; } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 56e2e4f25..07f83c86e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1745,6 +1745,7 @@ impl Writer { let (src_kind, src_width) = match *context.resolve_type(expr) { crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Vector { kind, width, .. } => (kind, width), + crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), _ => return Err(Error::Validation), }; let is_bool_cast = @@ -1759,6 +1760,9 @@ impl Writer { }; write!(self.out, "{}<", op)?; match *context.resolve_type(expr) { + crate::TypeInner::Matrix { columns, rows, .. } => { + put_numeric_type(&mut self.out, kind, &[rows, columns])? + } crate::TypeInner::Vector { size, .. } => { put_numeric_type(&mut self.out, kind, &[size])? } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index d302811db..4e4149b06 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -942,6 +942,7 @@ impl<'w> BlockContext<'w> { match *self.fun_info[expr].ty.inner_with(&self.ir_module.types) { crate::TypeInner::Scalar { kind, width } => (kind, None, width), crate::TypeInner::Vector { kind, width, size } => (kind, Some(size), width), + crate::TypeInner::Matrix { width, .. } => (kind, None, width), ref other => { log::error!("As source {:?}", other); return Err(Error::Validation("Unexpected Expression::As source")); diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 2d48d2ae4..a5304b738 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -864,6 +864,15 @@ impl<'a> ResolveContext<'a> { size, width: convert.unwrap_or(width), }), + Ti::Matrix { + columns, + rows, + width, + } => TypeResolution::Value(Ti::Matrix { + columns, + rows, + width: convert.unwrap_or(width), + }), ref other => { return Err(ResolveError::IncompatibleOperands(format!( "{:?} as {:?}", diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 332fb25da..385b424a9 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -68,6 +68,14 @@ fn constructors() -> f32 { _ = mat2x2(vec2(0.), vec2(0.)); _ = array(0, 1, 2, 3); + // identity constructors + _ = bool(bool()); + _ = i32(i32()); + _ = u32(u32()); + _ = f32(f32()); + _ = vec2(vec2()); + _ = mat2x3(mat2x3()); + return foo.a.x; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index f6f15fc7b..85f9e16c8 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -41,157 +41,163 @@ float constructors() { uvec2 unnamed = uvec2(0u); mat2x2 unnamed_1 = mat2x2(vec2(0.0), vec2(0.0)); int unnamed_2[4] = int[4](0, 1, 2, 3); - float _e59 = foo.a.x; - return _e59; + bool unnamed_3 = bool(false); + int unnamed_4 = int(0); + uint unnamed_5 = uint(0u); + float unnamed_6 = float(0.0); + uvec2 unnamed_7 = uvec2(uvec2(0u, 0u)); + mat2x3 unnamed_8 = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + float _e71 = foo.a.x; + return _e71; } void logical() { - bool unnamed_3 = (!true); - bvec2 unnamed_4 = not(bvec2(true)); - bool unnamed_5 = (true || false); - bool unnamed_6 = (true && false); - bool unnamed_7 = (true || false); - bvec3 unnamed_8 = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); - bool unnamed_9 = (true && false); - bvec4 unnamed_10 = bvec4(bvec4(true).x && bvec4(false).x, bvec4(true).y && bvec4(false).y, bvec4(true).z && bvec4(false).z, bvec4(true).w && bvec4(false).w); + bool unnamed_9 = (!true); + bvec2 unnamed_10 = not(bvec2(true)); + bool unnamed_11 = (true || false); + bool unnamed_12 = (true && false); + bool unnamed_13 = (true || false); + bvec3 unnamed_14 = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); + bool unnamed_15 = (true && false); + bvec4 unnamed_16 = bvec4(bvec4(true).x && bvec4(false).x, bvec4(true).y && bvec4(false).y, bvec4(true).z && bvec4(false).z, bvec4(true).w && bvec4(false).w); } void arithmetic() { - ivec2 unnamed_11 = (-ivec2(1)); - vec2 unnamed_12 = (-vec2(1.0)); - int unnamed_13 = (2 + 1); - uint unnamed_14 = (2u + 1u); - float unnamed_15 = (2.0 + 1.0); - ivec2 unnamed_16 = (ivec2(2) + ivec2(1)); - uvec3 unnamed_17 = (uvec3(2u) + uvec3(1u)); - vec4 unnamed_18 = (vec4(2.0) + vec4(1.0)); - int unnamed_19 = (2 - 1); - uint unnamed_20 = (2u - 1u); - float unnamed_21 = (2.0 - 1.0); - ivec2 unnamed_22 = (ivec2(2) - ivec2(1)); - uvec3 unnamed_23 = (uvec3(2u) - uvec3(1u)); - vec4 unnamed_24 = (vec4(2.0) - vec4(1.0)); - int unnamed_25 = (2 * 1); - uint unnamed_26 = (2u * 1u); - float unnamed_27 = (2.0 * 1.0); - ivec2 unnamed_28 = (ivec2(2) * ivec2(1)); - uvec3 unnamed_29 = (uvec3(2u) * uvec3(1u)); - vec4 unnamed_30 = (vec4(2.0) * vec4(1.0)); - int unnamed_31 = (2 / 1); - uint unnamed_32 = (2u / 1u); - float unnamed_33 = (2.0 / 1.0); - ivec2 unnamed_34 = (ivec2(2) / ivec2(1)); - uvec3 unnamed_35 = (uvec3(2u) / uvec3(1u)); - vec4 unnamed_36 = (vec4(2.0) / vec4(1.0)); - int unnamed_37 = (2 % 1); - uint unnamed_38 = (2u % 1u); - float unnamed_39 = (2.0 - 1.0 * trunc(2.0 / 1.0)); - ivec2 unnamed_40 = (ivec2(2) % ivec2(1)); - uvec3 unnamed_41 = (uvec3(2u) % uvec3(1u)); - vec4 unnamed_42 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); - ivec2 unnamed_43 = (ivec2(2) + ivec2(1)); - ivec2 unnamed_44 = (ivec2(2) + ivec2(1)); - uvec2 unnamed_45 = (uvec2(2u) + uvec2(1u)); - uvec2 unnamed_46 = (uvec2(2u) + uvec2(1u)); - vec2 unnamed_47 = (vec2(2.0) + vec2(1.0)); - vec2 unnamed_48 = (vec2(2.0) + vec2(1.0)); - ivec2 unnamed_49 = (ivec2(2) - ivec2(1)); - ivec2 unnamed_50 = (ivec2(2) - ivec2(1)); - uvec2 unnamed_51 = (uvec2(2u) - uvec2(1u)); - uvec2 unnamed_52 = (uvec2(2u) - uvec2(1u)); - vec2 unnamed_53 = (vec2(2.0) - vec2(1.0)); - vec2 unnamed_54 = (vec2(2.0) - vec2(1.0)); - ivec2 unnamed_55 = (ivec2(2) * 1); - ivec2 unnamed_56 = (2 * ivec2(1)); - uvec2 unnamed_57 = (uvec2(2u) * 1u); - uvec2 unnamed_58 = (2u * uvec2(1u)); - vec2 unnamed_59 = (vec2(2.0) * 1.0); - vec2 unnamed_60 = (2.0 * vec2(1.0)); - ivec2 unnamed_61 = (ivec2(2) / ivec2(1)); - ivec2 unnamed_62 = (ivec2(2) / ivec2(1)); - uvec2 unnamed_63 = (uvec2(2u) / uvec2(1u)); - uvec2 unnamed_64 = (uvec2(2u) / uvec2(1u)); - vec2 unnamed_65 = (vec2(2.0) / vec2(1.0)); - vec2 unnamed_66 = (vec2(2.0) / vec2(1.0)); - ivec2 unnamed_67 = (ivec2(2) % ivec2(1)); - ivec2 unnamed_68 = (ivec2(2) % ivec2(1)); - uvec2 unnamed_69 = (uvec2(2u) % uvec2(1u)); - uvec2 unnamed_70 = (uvec2(2u) % uvec2(1u)); - vec2 unnamed_71 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); - vec2 unnamed_72 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); - mat3x3 unnamed_73 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_74 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_75 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - mat3x3 unnamed_76 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - vec3 unnamed_77 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - vec4 unnamed_78 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_79 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + ivec2 unnamed_17 = (-ivec2(1)); + vec2 unnamed_18 = (-vec2(1.0)); + int unnamed_19 = (2 + 1); + uint unnamed_20 = (2u + 1u); + float unnamed_21 = (2.0 + 1.0); + ivec2 unnamed_22 = (ivec2(2) + ivec2(1)); + uvec3 unnamed_23 = (uvec3(2u) + uvec3(1u)); + vec4 unnamed_24 = (vec4(2.0) + vec4(1.0)); + int unnamed_25 = (2 - 1); + uint unnamed_26 = (2u - 1u); + float unnamed_27 = (2.0 - 1.0); + ivec2 unnamed_28 = (ivec2(2) - ivec2(1)); + uvec3 unnamed_29 = (uvec3(2u) - uvec3(1u)); + vec4 unnamed_30 = (vec4(2.0) - vec4(1.0)); + int unnamed_31 = (2 * 1); + uint unnamed_32 = (2u * 1u); + float unnamed_33 = (2.0 * 1.0); + ivec2 unnamed_34 = (ivec2(2) * ivec2(1)); + uvec3 unnamed_35 = (uvec3(2u) * uvec3(1u)); + vec4 unnamed_36 = (vec4(2.0) * vec4(1.0)); + int unnamed_37 = (2 / 1); + uint unnamed_38 = (2u / 1u); + float unnamed_39 = (2.0 / 1.0); + ivec2 unnamed_40 = (ivec2(2) / ivec2(1)); + uvec3 unnamed_41 = (uvec3(2u) / uvec3(1u)); + vec4 unnamed_42 = (vec4(2.0) / vec4(1.0)); + int unnamed_43 = (2 % 1); + uint unnamed_44 = (2u % 1u); + float unnamed_45 = (2.0 - 1.0 * trunc(2.0 / 1.0)); + ivec2 unnamed_46 = (ivec2(2) % ivec2(1)); + uvec3 unnamed_47 = (uvec3(2u) % uvec3(1u)); + vec4 unnamed_48 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); + ivec2 unnamed_49 = (ivec2(2) + ivec2(1)); + ivec2 unnamed_50 = (ivec2(2) + ivec2(1)); + uvec2 unnamed_51 = (uvec2(2u) + uvec2(1u)); + uvec2 unnamed_52 = (uvec2(2u) + uvec2(1u)); + vec2 unnamed_53 = (vec2(2.0) + vec2(1.0)); + vec2 unnamed_54 = (vec2(2.0) + vec2(1.0)); + ivec2 unnamed_55 = (ivec2(2) - ivec2(1)); + ivec2 unnamed_56 = (ivec2(2) - ivec2(1)); + uvec2 unnamed_57 = (uvec2(2u) - uvec2(1u)); + uvec2 unnamed_58 = (uvec2(2u) - uvec2(1u)); + vec2 unnamed_59 = (vec2(2.0) - vec2(1.0)); + vec2 unnamed_60 = (vec2(2.0) - vec2(1.0)); + ivec2 unnamed_61 = (ivec2(2) * 1); + ivec2 unnamed_62 = (2 * ivec2(1)); + uvec2 unnamed_63 = (uvec2(2u) * 1u); + uvec2 unnamed_64 = (2u * uvec2(1u)); + vec2 unnamed_65 = (vec2(2.0) * 1.0); + vec2 unnamed_66 = (2.0 * vec2(1.0)); + ivec2 unnamed_67 = (ivec2(2) / ivec2(1)); + ivec2 unnamed_68 = (ivec2(2) / ivec2(1)); + uvec2 unnamed_69 = (uvec2(2u) / uvec2(1u)); + uvec2 unnamed_70 = (uvec2(2u) / uvec2(1u)); + vec2 unnamed_71 = (vec2(2.0) / vec2(1.0)); + vec2 unnamed_72 = (vec2(2.0) / vec2(1.0)); + ivec2 unnamed_73 = (ivec2(2) % ivec2(1)); + ivec2 unnamed_74 = (ivec2(2) % ivec2(1)); + uvec2 unnamed_75 = (uvec2(2u) % uvec2(1u)); + uvec2 unnamed_76 = (uvec2(2u) % uvec2(1u)); + vec2 unnamed_77 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + vec2 unnamed_78 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + mat3x3 unnamed_79 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_80 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_81 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + mat3x3 unnamed_82 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + vec3 unnamed_83 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + vec4 unnamed_84 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_85 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } void bit() { - int unnamed_80 = (~1); - uint unnamed_81 = (~1u); - ivec2 unnamed_82 = (~ivec2(1)); - uvec3 unnamed_83 = (~uvec3(1u)); - int unnamed_84 = (2 | 1); - uint unnamed_85 = (2u | 1u); - ivec2 unnamed_86 = (ivec2(2) | ivec2(1)); - uvec3 unnamed_87 = (uvec3(2u) | uvec3(1u)); - int unnamed_88 = (2 & 1); - uint unnamed_89 = (2u & 1u); - ivec2 unnamed_90 = (ivec2(2) & ivec2(1)); - uvec3 unnamed_91 = (uvec3(2u) & uvec3(1u)); - int unnamed_92 = (2 ^ 1); - uint unnamed_93 = (2u ^ 1u); - ivec2 unnamed_94 = (ivec2(2) ^ ivec2(1)); - uvec3 unnamed_95 = (uvec3(2u) ^ uvec3(1u)); - int unnamed_96 = (2 << 1u); - uint unnamed_97 = (2u << 1u); - ivec2 unnamed_98 = (ivec2(2) << uvec2(1u)); - uvec3 unnamed_99 = (uvec3(2u) << uvec3(1u)); - int unnamed_100 = (2 >> 1u); - uint unnamed_101 = (2u >> 1u); - ivec2 unnamed_102 = (ivec2(2) >> uvec2(1u)); - uvec3 unnamed_103 = (uvec3(2u) >> uvec3(1u)); + int unnamed_86 = (~1); + uint unnamed_87 = (~1u); + ivec2 unnamed_88 = (~ivec2(1)); + uvec3 unnamed_89 = (~uvec3(1u)); + int unnamed_90 = (2 | 1); + uint unnamed_91 = (2u | 1u); + ivec2 unnamed_92 = (ivec2(2) | ivec2(1)); + uvec3 unnamed_93 = (uvec3(2u) | uvec3(1u)); + int unnamed_94 = (2 & 1); + uint unnamed_95 = (2u & 1u); + ivec2 unnamed_96 = (ivec2(2) & ivec2(1)); + uvec3 unnamed_97 = (uvec3(2u) & uvec3(1u)); + int unnamed_98 = (2 ^ 1); + uint unnamed_99 = (2u ^ 1u); + ivec2 unnamed_100 = (ivec2(2) ^ ivec2(1)); + uvec3 unnamed_101 = (uvec3(2u) ^ uvec3(1u)); + int unnamed_102 = (2 << 1u); + uint unnamed_103 = (2u << 1u); + ivec2 unnamed_104 = (ivec2(2) << uvec2(1u)); + uvec3 unnamed_105 = (uvec3(2u) << uvec3(1u)); + int unnamed_106 = (2 >> 1u); + uint unnamed_107 = (2u >> 1u); + ivec2 unnamed_108 = (ivec2(2) >> uvec2(1u)); + uvec3 unnamed_109 = (uvec3(2u) >> uvec3(1u)); } void comparison() { - bool unnamed_104 = (2 == 1); - bool unnamed_105 = (2u == 1u); - bool unnamed_106 = (2.0 == 1.0); - bvec2 unnamed_107 = equal(ivec2(2), ivec2(1)); - bvec3 unnamed_108 = equal(uvec3(2u), uvec3(1u)); - bvec4 unnamed_109 = equal(vec4(2.0), vec4(1.0)); - bool unnamed_110 = (2 != 1); - bool unnamed_111 = (2u != 1u); - bool unnamed_112 = (2.0 != 1.0); - bvec2 unnamed_113 = notEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_114 = notEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_115 = notEqual(vec4(2.0), vec4(1.0)); - bool unnamed_116 = (2 < 1); - bool unnamed_117 = (2u < 1u); - bool unnamed_118 = (2.0 < 1.0); - bvec2 unnamed_119 = lessThan(ivec2(2), ivec2(1)); - bvec3 unnamed_120 = lessThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_121 = lessThan(vec4(2.0), vec4(1.0)); - bool unnamed_122 = (2 <= 1); - bool unnamed_123 = (2u <= 1u); - bool unnamed_124 = (2.0 <= 1.0); - bvec2 unnamed_125 = lessThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_126 = lessThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_127 = lessThanEqual(vec4(2.0), vec4(1.0)); - bool unnamed_128 = (2 > 1); - bool unnamed_129 = (2u > 1u); - bool unnamed_130 = (2.0 > 1.0); - bvec2 unnamed_131 = greaterThan(ivec2(2), ivec2(1)); - bvec3 unnamed_132 = greaterThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_133 = greaterThan(vec4(2.0), vec4(1.0)); - bool unnamed_134 = (2 >= 1); - bool unnamed_135 = (2u >= 1u); - bool unnamed_136 = (2.0 >= 1.0); - bvec2 unnamed_137 = greaterThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_138 = greaterThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_139 = greaterThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_110 = (2 == 1); + bool unnamed_111 = (2u == 1u); + bool unnamed_112 = (2.0 == 1.0); + bvec2 unnamed_113 = equal(ivec2(2), ivec2(1)); + bvec3 unnamed_114 = equal(uvec3(2u), uvec3(1u)); + bvec4 unnamed_115 = equal(vec4(2.0), vec4(1.0)); + bool unnamed_116 = (2 != 1); + bool unnamed_117 = (2u != 1u); + bool unnamed_118 = (2.0 != 1.0); + bvec2 unnamed_119 = notEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_120 = notEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_121 = notEqual(vec4(2.0), vec4(1.0)); + bool unnamed_122 = (2 < 1); + bool unnamed_123 = (2u < 1u); + bool unnamed_124 = (2.0 < 1.0); + bvec2 unnamed_125 = lessThan(ivec2(2), ivec2(1)); + bvec3 unnamed_126 = lessThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_127 = lessThan(vec4(2.0), vec4(1.0)); + bool unnamed_128 = (2 <= 1); + bool unnamed_129 = (2u <= 1u); + bool unnamed_130 = (2.0 <= 1.0); + bvec2 unnamed_131 = lessThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_132 = lessThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_133 = lessThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_134 = (2 > 1); + bool unnamed_135 = (2u > 1u); + bool unnamed_136 = (2.0 > 1.0); + bvec2 unnamed_137 = greaterThan(ivec2(2), ivec2(1)); + bvec3 unnamed_138 = greaterThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_139 = greaterThan(vec4(2.0), vec4(1.0)); + bool unnamed_140 = (2 >= 1); + bool unnamed_141 = (2u >= 1u); + bool unnamed_142 = (2.0 >= 1.0); + bvec2 unnamed_143 = greaterThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_144 = greaterThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_145 = greaterThanEqual(vec4(2.0), vec4(1.0)); } void assignment() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 9cd73942e..672dcc303 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -64,161 +64,167 @@ float constructors() uint2 unnamed = (0u).xx; float2x2 unnamed_1 = float2x2((0.0).xx, (0.0).xx); int unnamed_2[4] = Constructarray4_int_(0, 1, 2, 3); - float _expr59 = foo.a.x; - return _expr59; + bool unnamed_3 = bool(false); + int unnamed_4 = int(0); + uint unnamed_5 = uint(0u); + float unnamed_6 = float(0.0); + uint2 unnamed_7 = uint2(uint2(0u, 0u)); + float2x3 unnamed_8 = float2x3(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float _expr71 = foo.a.x; + return _expr71; } void logical() { - bool unnamed_3 = !true; - bool2 unnamed_4 = !(true).xx; - bool unnamed_5 = (true || false); - bool unnamed_6 = (true && false); - bool unnamed_7 = (true | false); - bool3 unnamed_8 = ((true).xxx | (false).xxx); - bool unnamed_9 = (true & false); - bool4 unnamed_10 = ((true).xxxx & (false).xxxx); + bool unnamed_9 = !true; + bool2 unnamed_10 = !(true).xx; + bool unnamed_11 = (true || false); + bool unnamed_12 = (true && false); + bool unnamed_13 = (true | false); + bool3 unnamed_14 = ((true).xxx | (false).xxx); + bool unnamed_15 = (true & false); + bool4 unnamed_16 = ((true).xxxx & (false).xxxx); } void arithmetic() { - int2 unnamed_11 = -(1).xx; - float2 unnamed_12 = -(1.0).xx; - int unnamed_13 = (2 + 1); - uint unnamed_14 = (2u + 1u); - float unnamed_15 = (2.0 + 1.0); - int2 unnamed_16 = ((2).xx + (1).xx); - uint3 unnamed_17 = ((2u).xxx + (1u).xxx); - float4 unnamed_18 = ((2.0).xxxx + (1.0).xxxx); - int unnamed_19 = (2 - 1); - uint unnamed_20 = (2u - 1u); - float unnamed_21 = (2.0 - 1.0); - int2 unnamed_22 = ((2).xx - (1).xx); - uint3 unnamed_23 = ((2u).xxx - (1u).xxx); - float4 unnamed_24 = ((2.0).xxxx - (1.0).xxxx); - int unnamed_25 = (2 * 1); - uint unnamed_26 = (2u * 1u); - float unnamed_27 = (2.0 * 1.0); - int2 unnamed_28 = ((2).xx * (1).xx); - uint3 unnamed_29 = ((2u).xxx * (1u).xxx); - float4 unnamed_30 = ((2.0).xxxx * (1.0).xxxx); - int unnamed_31 = (2 / 1); - uint unnamed_32 = (2u / 1u); - float unnamed_33 = (2.0 / 1.0); - int2 unnamed_34 = ((2).xx / (1).xx); - uint3 unnamed_35 = ((2u).xxx / (1u).xxx); - float4 unnamed_36 = ((2.0).xxxx / (1.0).xxxx); - int unnamed_37 = (2 % 1); - uint unnamed_38 = (2u % 1u); - float unnamed_39 = fmod(2.0, 1.0); - int2 unnamed_40 = ((2).xx % (1).xx); - uint3 unnamed_41 = ((2u).xxx % (1u).xxx); - float4 unnamed_42 = fmod((2.0).xxxx, (1.0).xxxx); - int2 unnamed_43 = ((2).xx + (1).xx); - int2 unnamed_44 = ((2).xx + (1).xx); - uint2 unnamed_45 = ((2u).xx + (1u).xx); - uint2 unnamed_46 = ((2u).xx + (1u).xx); - float2 unnamed_47 = ((2.0).xx + (1.0).xx); - float2 unnamed_48 = ((2.0).xx + (1.0).xx); - int2 unnamed_49 = ((2).xx - (1).xx); - int2 unnamed_50 = ((2).xx - (1).xx); - uint2 unnamed_51 = ((2u).xx - (1u).xx); - uint2 unnamed_52 = ((2u).xx - (1u).xx); - float2 unnamed_53 = ((2.0).xx - (1.0).xx); - float2 unnamed_54 = ((2.0).xx - (1.0).xx); - int2 unnamed_55 = ((2).xx * 1); - int2 unnamed_56 = (2 * (1).xx); - uint2 unnamed_57 = ((2u).xx * 1u); - uint2 unnamed_58 = (2u * (1u).xx); - float2 unnamed_59 = ((2.0).xx * 1.0); - float2 unnamed_60 = (2.0 * (1.0).xx); - int2 unnamed_61 = ((2).xx / (1).xx); - int2 unnamed_62 = ((2).xx / (1).xx); - uint2 unnamed_63 = ((2u).xx / (1u).xx); - uint2 unnamed_64 = ((2u).xx / (1u).xx); - float2 unnamed_65 = ((2.0).xx / (1.0).xx); - float2 unnamed_66 = ((2.0).xx / (1.0).xx); - int2 unnamed_67 = ((2).xx % (1).xx); - int2 unnamed_68 = ((2).xx % (1).xx); - uint2 unnamed_69 = ((2u).xx % (1u).xx); - uint2 unnamed_70 = ((2u).xx % (1u).xx); - float2 unnamed_71 = fmod((2.0).xx, (1.0).xx); - float2 unnamed_72 = fmod((2.0).xx, (1.0).xx); - float3x3 unnamed_73 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_74 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_75 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_76 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); - float3 unnamed_77 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float4 unnamed_78 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); - float3x3 unnamed_79 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + int2 unnamed_17 = -(1).xx; + float2 unnamed_18 = -(1.0).xx; + int unnamed_19 = (2 + 1); + uint unnamed_20 = (2u + 1u); + float unnamed_21 = (2.0 + 1.0); + int2 unnamed_22 = ((2).xx + (1).xx); + uint3 unnamed_23 = ((2u).xxx + (1u).xxx); + float4 unnamed_24 = ((2.0).xxxx + (1.0).xxxx); + int unnamed_25 = (2 - 1); + uint unnamed_26 = (2u - 1u); + float unnamed_27 = (2.0 - 1.0); + int2 unnamed_28 = ((2).xx - (1).xx); + uint3 unnamed_29 = ((2u).xxx - (1u).xxx); + float4 unnamed_30 = ((2.0).xxxx - (1.0).xxxx); + int unnamed_31 = (2 * 1); + uint unnamed_32 = (2u * 1u); + float unnamed_33 = (2.0 * 1.0); + int2 unnamed_34 = ((2).xx * (1).xx); + uint3 unnamed_35 = ((2u).xxx * (1u).xxx); + float4 unnamed_36 = ((2.0).xxxx * (1.0).xxxx); + int unnamed_37 = (2 / 1); + uint unnamed_38 = (2u / 1u); + float unnamed_39 = (2.0 / 1.0); + int2 unnamed_40 = ((2).xx / (1).xx); + uint3 unnamed_41 = ((2u).xxx / (1u).xxx); + float4 unnamed_42 = ((2.0).xxxx / (1.0).xxxx); + int unnamed_43 = (2 % 1); + uint unnamed_44 = (2u % 1u); + float unnamed_45 = fmod(2.0, 1.0); + int2 unnamed_46 = ((2).xx % (1).xx); + uint3 unnamed_47 = ((2u).xxx % (1u).xxx); + float4 unnamed_48 = fmod((2.0).xxxx, (1.0).xxxx); + int2 unnamed_49 = ((2).xx + (1).xx); + int2 unnamed_50 = ((2).xx + (1).xx); + uint2 unnamed_51 = ((2u).xx + (1u).xx); + uint2 unnamed_52 = ((2u).xx + (1u).xx); + float2 unnamed_53 = ((2.0).xx + (1.0).xx); + float2 unnamed_54 = ((2.0).xx + (1.0).xx); + int2 unnamed_55 = ((2).xx - (1).xx); + int2 unnamed_56 = ((2).xx - (1).xx); + uint2 unnamed_57 = ((2u).xx - (1u).xx); + uint2 unnamed_58 = ((2u).xx - (1u).xx); + float2 unnamed_59 = ((2.0).xx - (1.0).xx); + float2 unnamed_60 = ((2.0).xx - (1.0).xx); + int2 unnamed_61 = ((2).xx * 1); + int2 unnamed_62 = (2 * (1).xx); + uint2 unnamed_63 = ((2u).xx * 1u); + uint2 unnamed_64 = (2u * (1u).xx); + float2 unnamed_65 = ((2.0).xx * 1.0); + float2 unnamed_66 = (2.0 * (1.0).xx); + int2 unnamed_67 = ((2).xx / (1).xx); + int2 unnamed_68 = ((2).xx / (1).xx); + uint2 unnamed_69 = ((2u).xx / (1u).xx); + uint2 unnamed_70 = ((2u).xx / (1u).xx); + float2 unnamed_71 = ((2.0).xx / (1.0).xx); + float2 unnamed_72 = ((2.0).xx / (1.0).xx); + int2 unnamed_73 = ((2).xx % (1).xx); + int2 unnamed_74 = ((2).xx % (1).xx); + uint2 unnamed_75 = ((2u).xx % (1u).xx); + uint2 unnamed_76 = ((2u).xx % (1u).xx); + float2 unnamed_77 = fmod((2.0).xx, (1.0).xx); + float2 unnamed_78 = fmod((2.0).xx, (1.0).xx); + float3x3 unnamed_79 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_80 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_81 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_82 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); + float3 unnamed_83 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float4 unnamed_84 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); + float3x3 unnamed_85 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); } void bit() { - int unnamed_80 = ~1; - uint unnamed_81 = ~1u; - int2 unnamed_82 = ~(1).xx; - uint3 unnamed_83 = ~(1u).xxx; - int unnamed_84 = (2 | 1); - uint unnamed_85 = (2u | 1u); - int2 unnamed_86 = ((2).xx | (1).xx); - uint3 unnamed_87 = ((2u).xxx | (1u).xxx); - int unnamed_88 = (2 & 1); - uint unnamed_89 = (2u & 1u); - int2 unnamed_90 = ((2).xx & (1).xx); - uint3 unnamed_91 = ((2u).xxx & (1u).xxx); - int unnamed_92 = (2 ^ 1); - uint unnamed_93 = (2u ^ 1u); - int2 unnamed_94 = ((2).xx ^ (1).xx); - uint3 unnamed_95 = ((2u).xxx ^ (1u).xxx); - int unnamed_96 = (2 << 1u); - uint unnamed_97 = (2u << 1u); - int2 unnamed_98 = ((2).xx << (1u).xx); - uint3 unnamed_99 = ((2u).xxx << (1u).xxx); - int unnamed_100 = (2 >> 1u); - uint unnamed_101 = (2u >> 1u); - int2 unnamed_102 = ((2).xx >> (1u).xx); - uint3 unnamed_103 = ((2u).xxx >> (1u).xxx); + int unnamed_86 = ~1; + uint unnamed_87 = ~1u; + int2 unnamed_88 = ~(1).xx; + uint3 unnamed_89 = ~(1u).xxx; + int unnamed_90 = (2 | 1); + uint unnamed_91 = (2u | 1u); + int2 unnamed_92 = ((2).xx | (1).xx); + uint3 unnamed_93 = ((2u).xxx | (1u).xxx); + int unnamed_94 = (2 & 1); + uint unnamed_95 = (2u & 1u); + int2 unnamed_96 = ((2).xx & (1).xx); + uint3 unnamed_97 = ((2u).xxx & (1u).xxx); + int unnamed_98 = (2 ^ 1); + uint unnamed_99 = (2u ^ 1u); + int2 unnamed_100 = ((2).xx ^ (1).xx); + uint3 unnamed_101 = ((2u).xxx ^ (1u).xxx); + int unnamed_102 = (2 << 1u); + uint unnamed_103 = (2u << 1u); + int2 unnamed_104 = ((2).xx << (1u).xx); + uint3 unnamed_105 = ((2u).xxx << (1u).xxx); + int unnamed_106 = (2 >> 1u); + uint unnamed_107 = (2u >> 1u); + int2 unnamed_108 = ((2).xx >> (1u).xx); + uint3 unnamed_109 = ((2u).xxx >> (1u).xxx); } void comparison() { - bool unnamed_104 = (2 == 1); - bool unnamed_105 = (2u == 1u); - bool unnamed_106 = (2.0 == 1.0); - bool2 unnamed_107 = ((2).xx == (1).xx); - bool3 unnamed_108 = ((2u).xxx == (1u).xxx); - bool4 unnamed_109 = ((2.0).xxxx == (1.0).xxxx); - bool unnamed_110 = (2 != 1); - bool unnamed_111 = (2u != 1u); - bool unnamed_112 = (2.0 != 1.0); - bool2 unnamed_113 = ((2).xx != (1).xx); - bool3 unnamed_114 = ((2u).xxx != (1u).xxx); - bool4 unnamed_115 = ((2.0).xxxx != (1.0).xxxx); - bool unnamed_116 = (2 < 1); - bool unnamed_117 = (2u < 1u); - bool unnamed_118 = (2.0 < 1.0); - bool2 unnamed_119 = ((2).xx < (1).xx); - bool3 unnamed_120 = ((2u).xxx < (1u).xxx); - bool4 unnamed_121 = ((2.0).xxxx < (1.0).xxxx); - bool unnamed_122 = (2 <= 1); - bool unnamed_123 = (2u <= 1u); - bool unnamed_124 = (2.0 <= 1.0); - bool2 unnamed_125 = ((2).xx <= (1).xx); - bool3 unnamed_126 = ((2u).xxx <= (1u).xxx); - bool4 unnamed_127 = ((2.0).xxxx <= (1.0).xxxx); - bool unnamed_128 = (2 > 1); - bool unnamed_129 = (2u > 1u); - bool unnamed_130 = (2.0 > 1.0); - bool2 unnamed_131 = ((2).xx > (1).xx); - bool3 unnamed_132 = ((2u).xxx > (1u).xxx); - bool4 unnamed_133 = ((2.0).xxxx > (1.0).xxxx); - bool unnamed_134 = (2 >= 1); - bool unnamed_135 = (2u >= 1u); - bool unnamed_136 = (2.0 >= 1.0); - bool2 unnamed_137 = ((2).xx >= (1).xx); - bool3 unnamed_138 = ((2u).xxx >= (1u).xxx); - bool4 unnamed_139 = ((2.0).xxxx >= (1.0).xxxx); + bool unnamed_110 = (2 == 1); + bool unnamed_111 = (2u == 1u); + bool unnamed_112 = (2.0 == 1.0); + bool2 unnamed_113 = ((2).xx == (1).xx); + bool3 unnamed_114 = ((2u).xxx == (1u).xxx); + bool4 unnamed_115 = ((2.0).xxxx == (1.0).xxxx); + bool unnamed_116 = (2 != 1); + bool unnamed_117 = (2u != 1u); + bool unnamed_118 = (2.0 != 1.0); + bool2 unnamed_119 = ((2).xx != (1).xx); + bool3 unnamed_120 = ((2u).xxx != (1u).xxx); + bool4 unnamed_121 = ((2.0).xxxx != (1.0).xxxx); + bool unnamed_122 = (2 < 1); + bool unnamed_123 = (2u < 1u); + bool unnamed_124 = (2.0 < 1.0); + bool2 unnamed_125 = ((2).xx < (1).xx); + bool3 unnamed_126 = ((2u).xxx < (1u).xxx); + bool4 unnamed_127 = ((2.0).xxxx < (1.0).xxxx); + bool unnamed_128 = (2 <= 1); + bool unnamed_129 = (2u <= 1u); + bool unnamed_130 = (2.0 <= 1.0); + bool2 unnamed_131 = ((2).xx <= (1).xx); + bool3 unnamed_132 = ((2u).xxx <= (1u).xxx); + bool4 unnamed_133 = ((2.0).xxxx <= (1.0).xxxx); + bool unnamed_134 = (2 > 1); + bool unnamed_135 = (2u > 1u); + bool unnamed_136 = (2.0 > 1.0); + bool2 unnamed_137 = ((2).xx > (1).xx); + bool3 unnamed_138 = ((2u).xxx > (1u).xxx); + bool4 unnamed_139 = ((2.0).xxxx > (1.0).xxxx); + bool unnamed_140 = (2 >= 1); + bool unnamed_141 = (2u >= 1u); + bool unnamed_142 = (2.0 >= 1.0); + bool2 unnamed_143 = ((2).xx >= (1).xx); + bool3 unnamed_144 = ((2u).xxx >= (1u).xxx); + bool4 unnamed_145 = ((2.0).xxxx >= (1.0).xxxx); } void assignment() diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index e9415d12b..03b176113 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -25,10 +25,11 @@ constant metal::float4 const_type = {0.0, 0.0, 0.0, 0.0}; constant Foo const_Foo = {const_type, 0}; constant type_12 const_type_12_ = {const_Foo, const_Foo, const_Foo}; constant metal::float3 const_type_4_ = {0.0, 0.0, 0.0}; -constant metal::float3x3 const_type_14_ = {const_type_4_, const_type_4_, const_type_4_}; -constant metal::float4x3 const_type_15_ = {const_type_4_, const_type_4_, const_type_4_, const_type_4_}; -constant metal::float3x4 const_type_16_ = {const_type, const_type, const_type}; -constant metal::int3 const_type_17_ = {0, 0, 0}; +constant metal::float2x3 const_type_14_ = {const_type_4_, const_type_4_}; +constant metal::float3x3 const_type_15_ = {const_type_4_, const_type_4_, const_type_4_}; +constant metal::float4x3 const_type_16_ = {const_type_4_, const_type_4_, const_type_4_, const_type_4_}; +constant metal::float3x4 const_type_17_ = {const_type, const_type, const_type}; +constant metal::int3 const_type_18_ = {0, 0, 0}; metal::float4 builtins( ) { @@ -66,167 +67,173 @@ float constructors( metal::uint2 unnamed = metal::uint2(0u); metal::float2x2 unnamed_1 = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); type_13 unnamed_2 = type_13 {0, 1, 2, 3}; - float _e59 = foo.a.x; - return _e59; + bool unnamed_3 = static_cast(false); + int unnamed_4 = static_cast(0); + uint unnamed_5 = static_cast(0u); + float unnamed_6 = static_cast(0.0); + metal::uint2 unnamed_7 = static_cast(const_type_11_); + metal::float2x3 unnamed_8 = static_cast(const_type_14_); + float _e71 = foo.a.x; + return _e71; } void logical( ) { - bool unnamed_3 = !true; - metal::bool2 unnamed_4 = !metal::bool2(true); - bool unnamed_5 = true || false; - bool unnamed_6 = true && false; - bool unnamed_7 = true | false; - metal::bool3 unnamed_8 = metal::bool3(true) | metal::bool3(false); - bool unnamed_9 = true & false; - metal::bool4 unnamed_10 = metal::bool4(true) & metal::bool4(false); + bool unnamed_9 = !true; + metal::bool2 unnamed_10 = !metal::bool2(true); + bool unnamed_11 = true || false; + bool unnamed_12 = true && false; + bool unnamed_13 = true | false; + metal::bool3 unnamed_14 = metal::bool3(true) | metal::bool3(false); + bool unnamed_15 = true & false; + metal::bool4 unnamed_16 = metal::bool4(true) & metal::bool4(false); } void arithmetic( ) { - metal::int2 unnamed_11 = -metal::int2(1); - metal::float2 unnamed_12 = -metal::float2(1.0); - int unnamed_13 = 2 + 1; - uint unnamed_14 = 2u + 1u; - float unnamed_15 = 2.0 + 1.0; - metal::int2 unnamed_16 = metal::int2(2) + metal::int2(1); - metal::uint3 unnamed_17 = metal::uint3(2u) + metal::uint3(1u); - metal::float4 unnamed_18 = metal::float4(2.0) + metal::float4(1.0); - int unnamed_19 = 2 - 1; - uint unnamed_20 = 2u - 1u; - float unnamed_21 = 2.0 - 1.0; - metal::int2 unnamed_22 = metal::int2(2) - metal::int2(1); - metal::uint3 unnamed_23 = metal::uint3(2u) - metal::uint3(1u); - metal::float4 unnamed_24 = metal::float4(2.0) - metal::float4(1.0); - int unnamed_25 = 2 * 1; - uint unnamed_26 = 2u * 1u; - float unnamed_27 = 2.0 * 1.0; - metal::int2 unnamed_28 = metal::int2(2) * metal::int2(1); - metal::uint3 unnamed_29 = metal::uint3(2u) * metal::uint3(1u); - metal::float4 unnamed_30 = metal::float4(2.0) * metal::float4(1.0); - int unnamed_31 = 2 / 1; - uint unnamed_32 = 2u / 1u; - float unnamed_33 = 2.0 / 1.0; - metal::int2 unnamed_34 = metal::int2(2) / metal::int2(1); - metal::uint3 unnamed_35 = metal::uint3(2u) / metal::uint3(1u); - metal::float4 unnamed_36 = metal::float4(2.0) / metal::float4(1.0); - int unnamed_37 = 2 % 1; - uint unnamed_38 = 2u % 1u; - float unnamed_39 = metal::fmod(2.0, 1.0); - metal::int2 unnamed_40 = metal::int2(2) % metal::int2(1); - metal::uint3 unnamed_41 = metal::uint3(2u) % metal::uint3(1u); - metal::float4 unnamed_42 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); - metal::int2 unnamed_43 = metal::int2(2) + metal::int2(1); - metal::int2 unnamed_44 = metal::int2(2) + metal::int2(1); - metal::uint2 unnamed_45 = metal::uint2(2u) + metal::uint2(1u); - metal::uint2 unnamed_46 = metal::uint2(2u) + metal::uint2(1u); - metal::float2 unnamed_47 = metal::float2(2.0) + metal::float2(1.0); - metal::float2 unnamed_48 = metal::float2(2.0) + metal::float2(1.0); - metal::int2 unnamed_49 = metal::int2(2) - metal::int2(1); - metal::int2 unnamed_50 = metal::int2(2) - metal::int2(1); - metal::uint2 unnamed_51 = metal::uint2(2u) - metal::uint2(1u); - metal::uint2 unnamed_52 = metal::uint2(2u) - metal::uint2(1u); - metal::float2 unnamed_53 = metal::float2(2.0) - metal::float2(1.0); - metal::float2 unnamed_54 = metal::float2(2.0) - metal::float2(1.0); - metal::int2 unnamed_55 = metal::int2(2) * 1; - metal::int2 unnamed_56 = 2 * metal::int2(1); - metal::uint2 unnamed_57 = metal::uint2(2u) * 1u; - metal::uint2 unnamed_58 = 2u * metal::uint2(1u); - metal::float2 unnamed_59 = metal::float2(2.0) * 1.0; - metal::float2 unnamed_60 = 2.0 * metal::float2(1.0); - metal::int2 unnamed_61 = metal::int2(2) / metal::int2(1); - metal::int2 unnamed_62 = metal::int2(2) / metal::int2(1); - metal::uint2 unnamed_63 = metal::uint2(2u) / metal::uint2(1u); - metal::uint2 unnamed_64 = metal::uint2(2u) / metal::uint2(1u); - metal::float2 unnamed_65 = metal::float2(2.0) / metal::float2(1.0); - metal::float2 unnamed_66 = metal::float2(2.0) / metal::float2(1.0); - metal::int2 unnamed_67 = metal::int2(2) % metal::int2(1); - metal::int2 unnamed_68 = metal::int2(2) % metal::int2(1); - metal::uint2 unnamed_69 = metal::uint2(2u) % metal::uint2(1u); - metal::uint2 unnamed_70 = metal::uint2(2u) % metal::uint2(1u); - metal::float2 unnamed_71 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float2 unnamed_72 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float3x3 unnamed_73 = const_type_14_ + const_type_14_; - metal::float3x3 unnamed_74 = const_type_14_ - const_type_14_; - metal::float3x3 unnamed_75 = const_type_14_ * 1.0; - metal::float3x3 unnamed_76 = 2.0 * const_type_14_; - metal::float3 unnamed_77 = const_type_15_ * metal::float4(1.0); - metal::float4 unnamed_78 = metal::float3(2.0) * const_type_15_; - metal::float3x3 unnamed_79 = const_type_15_ * const_type_16_; + metal::int2 unnamed_17 = -metal::int2(1); + metal::float2 unnamed_18 = -metal::float2(1.0); + int unnamed_19 = 2 + 1; + uint unnamed_20 = 2u + 1u; + float unnamed_21 = 2.0 + 1.0; + metal::int2 unnamed_22 = metal::int2(2) + metal::int2(1); + metal::uint3 unnamed_23 = metal::uint3(2u) + metal::uint3(1u); + metal::float4 unnamed_24 = metal::float4(2.0) + metal::float4(1.0); + int unnamed_25 = 2 - 1; + uint unnamed_26 = 2u - 1u; + float unnamed_27 = 2.0 - 1.0; + metal::int2 unnamed_28 = metal::int2(2) - metal::int2(1); + metal::uint3 unnamed_29 = metal::uint3(2u) - metal::uint3(1u); + metal::float4 unnamed_30 = metal::float4(2.0) - metal::float4(1.0); + int unnamed_31 = 2 * 1; + uint unnamed_32 = 2u * 1u; + float unnamed_33 = 2.0 * 1.0; + metal::int2 unnamed_34 = metal::int2(2) * metal::int2(1); + metal::uint3 unnamed_35 = metal::uint3(2u) * metal::uint3(1u); + metal::float4 unnamed_36 = metal::float4(2.0) * metal::float4(1.0); + int unnamed_37 = 2 / 1; + uint unnamed_38 = 2u / 1u; + float unnamed_39 = 2.0 / 1.0; + metal::int2 unnamed_40 = metal::int2(2) / metal::int2(1); + metal::uint3 unnamed_41 = metal::uint3(2u) / metal::uint3(1u); + metal::float4 unnamed_42 = metal::float4(2.0) / metal::float4(1.0); + int unnamed_43 = 2 % 1; + uint unnamed_44 = 2u % 1u; + float unnamed_45 = metal::fmod(2.0, 1.0); + metal::int2 unnamed_46 = metal::int2(2) % metal::int2(1); + metal::uint3 unnamed_47 = metal::uint3(2u) % metal::uint3(1u); + metal::float4 unnamed_48 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); + metal::int2 unnamed_49 = metal::int2(2) + metal::int2(1); + metal::int2 unnamed_50 = metal::int2(2) + metal::int2(1); + metal::uint2 unnamed_51 = metal::uint2(2u) + metal::uint2(1u); + metal::uint2 unnamed_52 = metal::uint2(2u) + metal::uint2(1u); + metal::float2 unnamed_53 = metal::float2(2.0) + metal::float2(1.0); + metal::float2 unnamed_54 = metal::float2(2.0) + metal::float2(1.0); + metal::int2 unnamed_55 = metal::int2(2) - metal::int2(1); + metal::int2 unnamed_56 = metal::int2(2) - metal::int2(1); + metal::uint2 unnamed_57 = metal::uint2(2u) - metal::uint2(1u); + metal::uint2 unnamed_58 = metal::uint2(2u) - metal::uint2(1u); + metal::float2 unnamed_59 = metal::float2(2.0) - metal::float2(1.0); + metal::float2 unnamed_60 = metal::float2(2.0) - metal::float2(1.0); + metal::int2 unnamed_61 = metal::int2(2) * 1; + metal::int2 unnamed_62 = 2 * metal::int2(1); + metal::uint2 unnamed_63 = metal::uint2(2u) * 1u; + metal::uint2 unnamed_64 = 2u * metal::uint2(1u); + metal::float2 unnamed_65 = metal::float2(2.0) * 1.0; + metal::float2 unnamed_66 = 2.0 * metal::float2(1.0); + metal::int2 unnamed_67 = metal::int2(2) / metal::int2(1); + metal::int2 unnamed_68 = metal::int2(2) / metal::int2(1); + metal::uint2 unnamed_69 = metal::uint2(2u) / metal::uint2(1u); + metal::uint2 unnamed_70 = metal::uint2(2u) / metal::uint2(1u); + metal::float2 unnamed_71 = metal::float2(2.0) / metal::float2(1.0); + metal::float2 unnamed_72 = metal::float2(2.0) / metal::float2(1.0); + metal::int2 unnamed_73 = metal::int2(2) % metal::int2(1); + metal::int2 unnamed_74 = metal::int2(2) % metal::int2(1); + metal::uint2 unnamed_75 = metal::uint2(2u) % metal::uint2(1u); + metal::uint2 unnamed_76 = metal::uint2(2u) % metal::uint2(1u); + metal::float2 unnamed_77 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + metal::float2 unnamed_78 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + metal::float3x3 unnamed_79 = const_type_15_ + const_type_15_; + metal::float3x3 unnamed_80 = const_type_15_ - const_type_15_; + metal::float3x3 unnamed_81 = const_type_15_ * 1.0; + metal::float3x3 unnamed_82 = 2.0 * const_type_15_; + metal::float3 unnamed_83 = const_type_16_ * metal::float4(1.0); + metal::float4 unnamed_84 = metal::float3(2.0) * const_type_16_; + metal::float3x3 unnamed_85 = const_type_16_ * const_type_17_; } void bit( ) { - int unnamed_80 = ~1; - uint unnamed_81 = ~1u; - metal::int2 unnamed_82 = ~metal::int2(1); - metal::uint3 unnamed_83 = ~metal::uint3(1u); - int unnamed_84 = 2 | 1; - uint unnamed_85 = 2u | 1u; - metal::int2 unnamed_86 = metal::int2(2) | metal::int2(1); - metal::uint3 unnamed_87 = metal::uint3(2u) | metal::uint3(1u); - int unnamed_88 = 2 & 1; - uint unnamed_89 = 2u & 1u; - metal::int2 unnamed_90 = metal::int2(2) & metal::int2(1); - metal::uint3 unnamed_91 = metal::uint3(2u) & metal::uint3(1u); - int unnamed_92 = 2 ^ 1; - uint unnamed_93 = 2u ^ 1u; - metal::int2 unnamed_94 = metal::int2(2) ^ metal::int2(1); - metal::uint3 unnamed_95 = metal::uint3(2u) ^ metal::uint3(1u); - int unnamed_96 = 2 << 1u; - uint unnamed_97 = 2u << 1u; - metal::int2 unnamed_98 = metal::int2(2) << metal::uint2(1u); - metal::uint3 unnamed_99 = metal::uint3(2u) << metal::uint3(1u); - int unnamed_100 = 2 >> 1u; - uint unnamed_101 = 2u >> 1u; - metal::int2 unnamed_102 = metal::int2(2) >> metal::uint2(1u); - metal::uint3 unnamed_103 = metal::uint3(2u) >> metal::uint3(1u); + int unnamed_86 = ~1; + uint unnamed_87 = ~1u; + metal::int2 unnamed_88 = ~metal::int2(1); + metal::uint3 unnamed_89 = ~metal::uint3(1u); + int unnamed_90 = 2 | 1; + uint unnamed_91 = 2u | 1u; + metal::int2 unnamed_92 = metal::int2(2) | metal::int2(1); + metal::uint3 unnamed_93 = metal::uint3(2u) | metal::uint3(1u); + int unnamed_94 = 2 & 1; + uint unnamed_95 = 2u & 1u; + metal::int2 unnamed_96 = metal::int2(2) & metal::int2(1); + metal::uint3 unnamed_97 = metal::uint3(2u) & metal::uint3(1u); + int unnamed_98 = 2 ^ 1; + uint unnamed_99 = 2u ^ 1u; + metal::int2 unnamed_100 = metal::int2(2) ^ metal::int2(1); + metal::uint3 unnamed_101 = metal::uint3(2u) ^ metal::uint3(1u); + int unnamed_102 = 2 << 1u; + uint unnamed_103 = 2u << 1u; + metal::int2 unnamed_104 = metal::int2(2) << metal::uint2(1u); + metal::uint3 unnamed_105 = metal::uint3(2u) << metal::uint3(1u); + int unnamed_106 = 2 >> 1u; + uint unnamed_107 = 2u >> 1u; + metal::int2 unnamed_108 = metal::int2(2) >> metal::uint2(1u); + metal::uint3 unnamed_109 = metal::uint3(2u) >> metal::uint3(1u); } void comparison( ) { - bool unnamed_104 = 2 == 1; - bool unnamed_105 = 2u == 1u; - bool unnamed_106 = 2.0 == 1.0; - metal::bool2 unnamed_107 = metal::int2(2) == metal::int2(1); - metal::bool3 unnamed_108 = metal::uint3(2u) == metal::uint3(1u); - metal::bool4 unnamed_109 = metal::float4(2.0) == metal::float4(1.0); - bool unnamed_110 = 2 != 1; - bool unnamed_111 = 2u != 1u; - bool unnamed_112 = 2.0 != 1.0; - metal::bool2 unnamed_113 = metal::int2(2) != metal::int2(1); - metal::bool3 unnamed_114 = metal::uint3(2u) != metal::uint3(1u); - metal::bool4 unnamed_115 = metal::float4(2.0) != metal::float4(1.0); - bool unnamed_116 = 2 < 1; - bool unnamed_117 = 2u < 1u; - bool unnamed_118 = 2.0 < 1.0; - metal::bool2 unnamed_119 = metal::int2(2) < metal::int2(1); - metal::bool3 unnamed_120 = metal::uint3(2u) < metal::uint3(1u); - metal::bool4 unnamed_121 = metal::float4(2.0) < metal::float4(1.0); - bool unnamed_122 = 2 <= 1; - bool unnamed_123 = 2u <= 1u; - bool unnamed_124 = 2.0 <= 1.0; - metal::bool2 unnamed_125 = metal::int2(2) <= metal::int2(1); - metal::bool3 unnamed_126 = metal::uint3(2u) <= metal::uint3(1u); - metal::bool4 unnamed_127 = metal::float4(2.0) <= metal::float4(1.0); - bool unnamed_128 = 2 > 1; - bool unnamed_129 = 2u > 1u; - bool unnamed_130 = 2.0 > 1.0; - metal::bool2 unnamed_131 = metal::int2(2) > metal::int2(1); - metal::bool3 unnamed_132 = metal::uint3(2u) > metal::uint3(1u); - metal::bool4 unnamed_133 = metal::float4(2.0) > metal::float4(1.0); - bool unnamed_134 = 2 >= 1; - bool unnamed_135 = 2u >= 1u; - bool unnamed_136 = 2.0 >= 1.0; - metal::bool2 unnamed_137 = metal::int2(2) >= metal::int2(1); - metal::bool3 unnamed_138 = metal::uint3(2u) >= metal::uint3(1u); - metal::bool4 unnamed_139 = metal::float4(2.0) >= metal::float4(1.0); + bool unnamed_110 = 2 == 1; + bool unnamed_111 = 2u == 1u; + bool unnamed_112 = 2.0 == 1.0; + metal::bool2 unnamed_113 = metal::int2(2) == metal::int2(1); + metal::bool3 unnamed_114 = metal::uint3(2u) == metal::uint3(1u); + metal::bool4 unnamed_115 = metal::float4(2.0) == metal::float4(1.0); + bool unnamed_116 = 2 != 1; + bool unnamed_117 = 2u != 1u; + bool unnamed_118 = 2.0 != 1.0; + metal::bool2 unnamed_119 = metal::int2(2) != metal::int2(1); + metal::bool3 unnamed_120 = metal::uint3(2u) != metal::uint3(1u); + metal::bool4 unnamed_121 = metal::float4(2.0) != metal::float4(1.0); + bool unnamed_122 = 2 < 1; + bool unnamed_123 = 2u < 1u; + bool unnamed_124 = 2.0 < 1.0; + metal::bool2 unnamed_125 = metal::int2(2) < metal::int2(1); + metal::bool3 unnamed_126 = metal::uint3(2u) < metal::uint3(1u); + metal::bool4 unnamed_127 = metal::float4(2.0) < metal::float4(1.0); + bool unnamed_128 = 2 <= 1; + bool unnamed_129 = 2u <= 1u; + bool unnamed_130 = 2.0 <= 1.0; + metal::bool2 unnamed_131 = metal::int2(2) <= metal::int2(1); + metal::bool3 unnamed_132 = metal::uint3(2u) <= metal::uint3(1u); + metal::bool4 unnamed_133 = metal::float4(2.0) <= metal::float4(1.0); + bool unnamed_134 = 2 > 1; + bool unnamed_135 = 2u > 1u; + bool unnamed_136 = 2.0 > 1.0; + metal::bool2 unnamed_137 = metal::int2(2) > metal::int2(1); + metal::bool3 unnamed_138 = metal::uint3(2u) > metal::uint3(1u); + metal::bool4 unnamed_139 = metal::float4(2.0) > metal::float4(1.0); + bool unnamed_140 = 2 >= 1; + bool unnamed_141 = 2u >= 1u; + bool unnamed_142 = 2.0 >= 1.0; + metal::bool2 unnamed_143 = metal::int2(2) >= metal::int2(1); + metal::bool3 unnamed_144 = metal::uint3(2u) >= metal::uint3(1u); + metal::bool4 unnamed_145 = metal::float4(2.0) >= metal::float4(1.0); } void assignment( ) { int a = 1; - metal::int3 vec0_ = const_type_17_; + metal::int3 vec0_ = const_type_18_; int _e6 = a; a = _e6 + 1; int _e9 = a; diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index e805de91c..c39fcfb63 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 515 +; Bound: 523 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %503 "main" -OpExecutionMode %503 LocalSize 1 1 1 +OpEntryPoint GLCompute %511 "main" +OpExecutionMode %511 LocalSize 1 1 1 OpMemberDecorate %30 0 Offset 0 OpMemberDecorate %30 1 Offset 16 OpDecorate %35 ArrayStride 32 @@ -46,526 +46,534 @@ OpDecorate %36 ArrayStride 4 %34 = OpTypeVector %20 2 %35 = OpTypeArray %30 %21 %36 = OpTypeArray %8 %22 -%37 = OpTypeMatrix %29 3 -%38 = OpTypeMatrix %29 4 -%39 = OpTypeMatrix %26 3 -%40 = OpTypeVector %8 3 -%41 = OpConstantComposite %26 %3 %3 %3 %3 -%42 = OpConstantComposite %26 %5 %5 %5 %5 -%43 = OpConstantComposite %26 %6 %6 %6 %6 -%44 = OpConstantComposite %27 %7 %7 %7 %7 -%45 = OpConstantComposite %34 %19 %19 -%46 = OpConstantComposite %31 %5 %5 -%47 = OpConstantComposite %32 %46 %46 -%48 = OpConstantComposite %26 %5 %5 %5 %5 -%49 = OpConstantComposite %30 %48 %11 -%50 = OpConstantComposite %35 %49 %49 %49 -%51 = OpConstantComposite %29 %5 %5 %5 -%52 = OpConstantComposite %37 %51 %51 %51 -%53 = OpConstantComposite %38 %51 %51 %51 %51 -%54 = OpConstantComposite %39 %48 %48 %48 -%55 = OpConstantComposite %40 %11 %11 %11 -%58 = OpTypeFunction %26 -%100 = OpTypeFunction %29 %29 -%102 = OpTypeVector %10 3 -%109 = OpTypePointer Function %30 -%110 = OpConstantNull %30 -%113 = OpTypeFunction %4 -%130 = OpTypePointer Function %26 -%131 = OpTypePointer Function %4 -%136 = OpTypeFunction %2 -%139 = OpTypeVector %10 2 -%155 = OpTypeVector %8 2 -%166 = OpTypeVector %20 3 -%461 = OpTypePointer Function %8 -%463 = OpTypePointer Function %40 -%493 = OpTypePointer Function %8 -%57 = OpFunction %26 None %58 -%56 = OpLabel -OpBranch %59 -%59 = OpLabel -%60 = OpSelect %8 %9 %7 %11 -%62 = OpCompositeConstruct %28 %9 %9 %9 %9 -%61 = OpSelect %26 %62 %41 %42 -%63 = OpCompositeConstruct %28 %12 %12 %12 %12 -%64 = OpSelect %26 %63 %42 %41 -%65 = OpExtInst %26 %1 FMix %42 %41 %43 -%67 = OpCompositeConstruct %26 %13 %13 %13 %13 -%66 = OpExtInst %26 %1 FMix %42 %41 %67 -%68 = OpCompositeExtract %8 %44 0 -%69 = OpBitcast %4 %68 -%70 = OpBitcast %26 %44 -%71 = OpConvertFToS %27 %42 -%72 = OpCompositeConstruct %27 %60 %60 %60 %60 -%73 = OpIAdd %27 %72 %71 -%74 = OpConvertSToF %26 %73 -%75 = OpFAdd %26 %74 %61 -%76 = OpFAdd %26 %75 %65 -%77 = OpFAdd %26 %76 %66 -%78 = OpCompositeConstruct %26 %69 %69 %69 %69 -%79 = OpFAdd %26 %77 %78 -%80 = OpFAdd %26 %79 %70 -OpReturnValue %80 +%37 = OpTypeMatrix %29 2 +%38 = OpTypeMatrix %29 3 +%39 = OpTypeMatrix %29 4 +%40 = OpTypeMatrix %26 3 +%41 = OpTypeVector %8 3 +%42 = OpConstantComposite %26 %3 %3 %3 %3 +%43 = OpConstantComposite %26 %5 %5 %5 %5 +%44 = OpConstantComposite %26 %6 %6 %6 %6 +%45 = OpConstantComposite %27 %7 %7 %7 %7 +%46 = OpConstantComposite %34 %19 %19 +%47 = OpConstantComposite %31 %5 %5 +%48 = OpConstantComposite %32 %47 %47 +%49 = OpConstantComposite %26 %5 %5 %5 %5 +%50 = OpConstantComposite %30 %49 %11 +%51 = OpConstantComposite %35 %50 %50 %50 +%52 = OpConstantComposite %29 %5 %5 %5 +%53 = OpConstantComposite %37 %52 %52 +%54 = OpConstantComposite %38 %52 %52 %52 +%55 = OpConstantComposite %39 %52 %52 %52 %52 +%56 = OpConstantComposite %40 %49 %49 %49 +%57 = OpConstantComposite %41 %11 %11 %11 +%60 = OpTypeFunction %26 +%102 = OpTypeFunction %29 %29 +%104 = OpTypeVector %10 3 +%111 = OpTypePointer Function %30 +%112 = OpConstantNull %30 +%115 = OpTypeFunction %4 +%138 = OpTypePointer Function %26 +%139 = OpTypePointer Function %4 +%144 = OpTypeFunction %2 +%147 = OpTypeVector %10 2 +%163 = OpTypeVector %8 2 +%174 = OpTypeVector %20 3 +%469 = OpTypePointer Function %8 +%471 = OpTypePointer Function %41 +%501 = OpTypePointer Function %8 +%59 = OpFunction %26 None %60 +%58 = OpLabel +OpBranch %61 +%61 = OpLabel +%62 = OpSelect %8 %9 %7 %11 +%64 = OpCompositeConstruct %28 %9 %9 %9 %9 +%63 = OpSelect %26 %64 %42 %43 +%65 = OpCompositeConstruct %28 %12 %12 %12 %12 +%66 = OpSelect %26 %65 %43 %42 +%67 = OpExtInst %26 %1 FMix %43 %42 %44 +%69 = OpCompositeConstruct %26 %13 %13 %13 %13 +%68 = OpExtInst %26 %1 FMix %43 %42 %69 +%70 = OpCompositeExtract %8 %45 0 +%71 = OpBitcast %4 %70 +%72 = OpBitcast %26 %45 +%73 = OpConvertFToS %27 %43 +%74 = OpCompositeConstruct %27 %62 %62 %62 %62 +%75 = OpIAdd %27 %74 %73 +%76 = OpConvertSToF %26 %75 +%77 = OpFAdd %26 %76 %63 +%78 = OpFAdd %26 %77 %67 +%79 = OpFAdd %26 %78 %68 +%80 = OpCompositeConstruct %26 %71 %71 %71 %71 +%81 = OpFAdd %26 %79 %80 +%82 = OpFAdd %26 %81 %72 +OpReturnValue %82 OpFunctionEnd -%82 = OpFunction %26 None %58 -%81 = OpLabel -OpBranch %83 +%84 = OpFunction %26 None %60 %83 = OpLabel -%84 = OpCompositeConstruct %31 %14 %14 -%85 = OpCompositeConstruct %31 %3 %3 -%86 = OpFAdd %31 %85 %84 -%87 = OpCompositeConstruct %31 %15 %15 -%88 = OpFSub %31 %86 %87 -%89 = OpCompositeConstruct %31 %16 %16 -%90 = OpFDiv %31 %88 %89 -%91 = OpCompositeConstruct %27 %17 %17 %17 %17 -%92 = OpCompositeConstruct %27 %18 %18 %18 %18 -%93 = OpSRem %27 %91 %92 -%94 = OpVectorShuffle %26 %90 %90 0 1 0 1 -%95 = OpConvertSToF %26 %93 -%96 = OpFAdd %26 %94 %95 -OpReturnValue %96 +OpBranch %85 +%85 = OpLabel +%86 = OpCompositeConstruct %31 %14 %14 +%87 = OpCompositeConstruct %31 %3 %3 +%88 = OpFAdd %31 %87 %86 +%89 = OpCompositeConstruct %31 %15 %15 +%90 = OpFSub %31 %88 %89 +%91 = OpCompositeConstruct %31 %16 %16 +%92 = OpFDiv %31 %90 %91 +%93 = OpCompositeConstruct %27 %17 %17 %17 %17 +%94 = OpCompositeConstruct %27 %18 %18 %18 %18 +%95 = OpSRem %27 %93 %94 +%96 = OpVectorShuffle %26 %92 %92 0 1 0 1 +%97 = OpConvertSToF %26 %95 +%98 = OpFAdd %26 %96 %97 +OpReturnValue %98 OpFunctionEnd -%99 = OpFunction %29 None %100 -%98 = OpFunctionParameter %29 -%97 = OpLabel -OpBranch %101 -%101 = OpLabel -%103 = OpCompositeConstruct %29 %5 %5 %5 -%104 = OpFUnordNotEqual %102 %98 %103 +%101 = OpFunction %29 None %102 +%100 = OpFunctionParameter %29 +%99 = OpLabel +OpBranch %103 +%103 = OpLabel %105 = OpCompositeConstruct %29 %5 %5 %5 -%106 = OpCompositeConstruct %29 %3 %3 %3 -%107 = OpSelect %29 %104 %106 %105 -OpReturnValue %107 +%106 = OpFUnordNotEqual %104 %100 %105 +%107 = OpCompositeConstruct %29 %5 %5 %5 +%108 = OpCompositeConstruct %29 %3 %3 %3 +%109 = OpSelect %29 %106 %108 %107 +OpReturnValue %109 OpFunctionEnd -%112 = OpFunction %4 None %113 -%111 = OpLabel -%108 = OpVariable %109 Function %110 -OpBranch %114 -%114 = OpLabel -%115 = OpCompositeConstruct %26 %3 %3 %3 %3 -%116 = OpCompositeConstruct %30 %115 %7 -OpStore %108 %116 -%117 = OpCompositeConstruct %31 %3 %5 -%118 = OpCompositeConstruct %31 %5 %3 -%119 = OpCompositeConstruct %32 %117 %118 -%120 = OpCompositeConstruct %26 %3 %5 %5 %5 -%121 = OpCompositeConstruct %26 %5 %3 %5 %5 -%122 = OpCompositeConstruct %26 %5 %5 %3 %5 -%123 = OpCompositeConstruct %26 %5 %5 %5 %3 -%124 = OpCompositeConstruct %33 %120 %121 %122 %123 -%125 = OpCompositeConstruct %34 %19 %19 -%126 = OpCompositeConstruct %31 %5 %5 -%127 = OpCompositeConstruct %31 %5 %5 -%128 = OpCompositeConstruct %32 %126 %127 -%129 = OpCompositeConstruct %36 %11 %7 %18 %21 -%132 = OpAccessChain %131 %108 %19 %19 -%133 = OpLoad %4 %132 -OpReturnValue %133 +%114 = OpFunction %4 None %115 +%113 = OpLabel +%110 = OpVariable %111 Function %112 +OpBranch %116 +%116 = OpLabel +%117 = OpCompositeConstruct %26 %3 %3 %3 %3 +%118 = OpCompositeConstruct %30 %117 %7 +OpStore %110 %118 +%119 = OpCompositeConstruct %31 %3 %5 +%120 = OpCompositeConstruct %31 %5 %3 +%121 = OpCompositeConstruct %32 %119 %120 +%122 = OpCompositeConstruct %26 %3 %5 %5 %5 +%123 = OpCompositeConstruct %26 %5 %3 %5 %5 +%124 = OpCompositeConstruct %26 %5 %5 %3 %5 +%125 = OpCompositeConstruct %26 %5 %5 %5 %3 +%126 = OpCompositeConstruct %33 %122 %123 %124 %125 +%127 = OpCompositeConstruct %34 %19 %19 +%128 = OpCompositeConstruct %31 %5 %5 +%129 = OpCompositeConstruct %31 %5 %5 +%130 = OpCompositeConstruct %32 %128 %129 +%131 = OpCompositeConstruct %36 %11 %7 %18 %21 +%132 = OpBitcast %10 %12 +%133 = OpBitcast %8 %11 +%134 = OpBitcast %20 %19 +%135 = OpBitcast %4 %5 +%136 = OpBitcast %34 %46 +%137 = OpBitcast %37 %53 +%140 = OpAccessChain %139 %110 %19 %19 +%141 = OpLoad %4 %140 +OpReturnValue %141 OpFunctionEnd -%135 = OpFunction %2 None %136 -%134 = OpLabel -OpBranch %137 -%137 = OpLabel -%138 = OpLogicalNot %10 %9 -%140 = OpCompositeConstruct %139 %9 %9 -%141 = OpLogicalNot %139 %140 -%142 = OpLogicalOr %10 %9 %12 -%143 = OpLogicalAnd %10 %9 %12 -%144 = OpLogicalOr %10 %9 %12 -%145 = OpCompositeConstruct %102 %9 %9 %9 -%146 = OpCompositeConstruct %102 %12 %12 %12 -%147 = OpLogicalOr %102 %145 %146 -%148 = OpLogicalAnd %10 %9 %12 -%149 = OpCompositeConstruct %28 %9 %9 %9 %9 -%150 = OpCompositeConstruct %28 %12 %12 %12 %12 -%151 = OpLogicalAnd %28 %149 %150 +%143 = OpFunction %2 None %144 +%142 = OpLabel +OpBranch %145 +%145 = OpLabel +%146 = OpLogicalNot %10 %9 +%148 = OpCompositeConstruct %147 %9 %9 +%149 = OpLogicalNot %147 %148 +%150 = OpLogicalOr %10 %9 %12 +%151 = OpLogicalAnd %10 %9 %12 +%152 = OpLogicalOr %10 %9 %12 +%153 = OpCompositeConstruct %104 %9 %9 %9 +%154 = OpCompositeConstruct %104 %12 %12 %12 +%155 = OpLogicalOr %104 %153 %154 +%156 = OpLogicalAnd %10 %9 %12 +%157 = OpCompositeConstruct %28 %9 %9 %9 %9 +%158 = OpCompositeConstruct %28 %12 %12 %12 %12 +%159 = OpLogicalAnd %28 %157 %158 OpReturn OpFunctionEnd -%153 = OpFunction %2 None %136 -%152 = OpLabel -OpBranch %154 -%154 = OpLabel -%156 = OpCompositeConstruct %155 %7 %7 -%157 = OpSNegate %155 %156 -%158 = OpCompositeConstruct %31 %3 %3 -%159 = OpFNegate %31 %158 -%160 = OpIAdd %8 %18 %7 -%161 = OpIAdd %20 %24 %25 -%162 = OpFAdd %4 %14 %3 -%163 = OpCompositeConstruct %155 %18 %18 -%164 = OpCompositeConstruct %155 %7 %7 -%165 = OpIAdd %155 %163 %164 -%167 = OpCompositeConstruct %166 %24 %24 %24 -%168 = OpCompositeConstruct %166 %25 %25 %25 -%169 = OpIAdd %166 %167 %168 -%170 = OpCompositeConstruct %26 %14 %14 %14 %14 -%171 = OpCompositeConstruct %26 %3 %3 %3 %3 -%172 = OpFAdd %26 %170 %171 -%173 = OpISub %8 %18 %7 -%174 = OpISub %20 %24 %25 -%175 = OpFSub %4 %14 %3 -%176 = OpCompositeConstruct %155 %18 %18 -%177 = OpCompositeConstruct %155 %7 %7 -%178 = OpISub %155 %176 %177 -%179 = OpCompositeConstruct %166 %24 %24 %24 -%180 = OpCompositeConstruct %166 %25 %25 %25 -%181 = OpISub %166 %179 %180 -%182 = OpCompositeConstruct %26 %14 %14 %14 %14 -%183 = OpCompositeConstruct %26 %3 %3 %3 %3 -%184 = OpFSub %26 %182 %183 -%185 = OpIMul %8 %18 %7 -%186 = OpIMul %20 %24 %25 -%187 = OpFMul %4 %14 %3 -%188 = OpCompositeConstruct %155 %18 %18 -%189 = OpCompositeConstruct %155 %7 %7 -%190 = OpIMul %155 %188 %189 -%191 = OpCompositeConstruct %166 %24 %24 %24 -%192 = OpCompositeConstruct %166 %25 %25 %25 -%193 = OpIMul %166 %191 %192 -%194 = OpCompositeConstruct %26 %14 %14 %14 %14 -%195 = OpCompositeConstruct %26 %3 %3 %3 %3 -%196 = OpFMul %26 %194 %195 -%197 = OpSDiv %8 %18 %7 -%198 = OpUDiv %20 %24 %25 -%199 = OpFDiv %4 %14 %3 -%200 = OpCompositeConstruct %155 %18 %18 -%201 = OpCompositeConstruct %155 %7 %7 -%202 = OpSDiv %155 %200 %201 -%203 = OpCompositeConstruct %166 %24 %24 %24 -%204 = OpCompositeConstruct %166 %25 %25 %25 -%205 = OpUDiv %166 %203 %204 -%206 = OpCompositeConstruct %26 %14 %14 %14 %14 -%207 = OpCompositeConstruct %26 %3 %3 %3 %3 -%208 = OpFDiv %26 %206 %207 -%209 = OpSRem %8 %18 %7 -%210 = OpUMod %20 %24 %25 -%211 = OpFRem %4 %14 %3 -%212 = OpCompositeConstruct %155 %18 %18 -%213 = OpCompositeConstruct %155 %7 %7 -%214 = OpSRem %155 %212 %213 -%215 = OpCompositeConstruct %166 %24 %24 %24 -%216 = OpCompositeConstruct %166 %25 %25 %25 -%217 = OpUMod %166 %215 %216 -%218 = OpCompositeConstruct %26 %14 %14 %14 %14 -%219 = OpCompositeConstruct %26 %3 %3 %3 %3 -%220 = OpFRem %26 %218 %219 -%221 = OpCompositeConstruct %155 %18 %18 -%222 = OpCompositeConstruct %155 %7 %7 -%223 = OpIAdd %155 %221 %222 -%224 = OpCompositeConstruct %155 %7 %7 -%225 = OpCompositeConstruct %155 %18 %18 -%226 = OpIAdd %155 %225 %224 -%227 = OpCompositeConstruct %34 %24 %24 -%228 = OpCompositeConstruct %34 %25 %25 -%229 = OpIAdd %34 %227 %228 -%230 = OpCompositeConstruct %34 %25 %25 -%231 = OpCompositeConstruct %34 %24 %24 -%232 = OpIAdd %34 %231 %230 -%233 = OpCompositeConstruct %31 %14 %14 -%234 = OpCompositeConstruct %31 %3 %3 -%235 = OpFAdd %31 %233 %234 -%236 = OpCompositeConstruct %31 %3 %3 -%237 = OpCompositeConstruct %31 %14 %14 -%238 = OpFAdd %31 %237 %236 -%239 = OpCompositeConstruct %155 %18 %18 -%240 = OpCompositeConstruct %155 %7 %7 -%241 = OpISub %155 %239 %240 -%242 = OpCompositeConstruct %155 %7 %7 -%243 = OpCompositeConstruct %155 %18 %18 -%244 = OpISub %155 %243 %242 -%245 = OpCompositeConstruct %34 %24 %24 -%246 = OpCompositeConstruct %34 %25 %25 -%247 = OpISub %34 %245 %246 -%248 = OpCompositeConstruct %34 %25 %25 -%249 = OpCompositeConstruct %34 %24 %24 -%250 = OpISub %34 %249 %248 -%251 = OpCompositeConstruct %31 %14 %14 -%252 = OpCompositeConstruct %31 %3 %3 -%253 = OpFSub %31 %251 %252 -%254 = OpCompositeConstruct %31 %3 %3 -%255 = OpCompositeConstruct %31 %14 %14 -%256 = OpFSub %31 %255 %254 -%257 = OpCompositeConstruct %155 %18 %18 -%259 = OpCompositeConstruct %155 %7 %7 -%258 = OpIMul %155 %257 %259 -%260 = OpCompositeConstruct %155 %7 %7 -%262 = OpCompositeConstruct %155 %18 %18 -%261 = OpIMul %155 %260 %262 -%263 = OpCompositeConstruct %34 %24 %24 -%265 = OpCompositeConstruct %34 %25 %25 -%264 = OpIMul %34 %263 %265 -%266 = OpCompositeConstruct %34 %25 %25 -%268 = OpCompositeConstruct %34 %24 %24 -%267 = OpIMul %34 %266 %268 -%269 = OpCompositeConstruct %31 %14 %14 -%270 = OpVectorTimesScalar %31 %269 %3 -%271 = OpCompositeConstruct %31 %3 %3 -%272 = OpVectorTimesScalar %31 %271 %14 -%273 = OpCompositeConstruct %155 %18 %18 -%274 = OpCompositeConstruct %155 %7 %7 -%275 = OpSDiv %155 %273 %274 -%276 = OpCompositeConstruct %155 %7 %7 -%277 = OpCompositeConstruct %155 %18 %18 -%278 = OpSDiv %155 %277 %276 -%279 = OpCompositeConstruct %34 %24 %24 -%280 = OpCompositeConstruct %34 %25 %25 -%281 = OpUDiv %34 %279 %280 -%282 = OpCompositeConstruct %34 %25 %25 -%283 = OpCompositeConstruct %34 %24 %24 -%284 = OpUDiv %34 %283 %282 -%285 = OpCompositeConstruct %31 %14 %14 -%286 = OpCompositeConstruct %31 %3 %3 -%287 = OpFDiv %31 %285 %286 -%288 = OpCompositeConstruct %31 %3 %3 -%289 = OpCompositeConstruct %31 %14 %14 -%290 = OpFDiv %31 %289 %288 -%291 = OpCompositeConstruct %155 %18 %18 -%292 = OpCompositeConstruct %155 %7 %7 -%293 = OpSRem %155 %291 %292 -%294 = OpCompositeConstruct %155 %7 %7 -%295 = OpCompositeConstruct %155 %18 %18 -%296 = OpSRem %155 %295 %294 -%297 = OpCompositeConstruct %34 %24 %24 -%298 = OpCompositeConstruct %34 %25 %25 -%299 = OpUMod %34 %297 %298 -%300 = OpCompositeConstruct %34 %25 %25 -%301 = OpCompositeConstruct %34 %24 %24 -%302 = OpUMod %34 %301 %300 -%303 = OpCompositeConstruct %31 %14 %14 -%304 = OpCompositeConstruct %31 %3 %3 -%305 = OpFRem %31 %303 %304 -%306 = OpCompositeConstruct %31 %3 %3 -%307 = OpCompositeConstruct %31 %14 %14 -%308 = OpFRem %31 %307 %306 -%310 = OpCompositeExtract %29 %52 0 -%311 = OpCompositeExtract %29 %52 0 -%312 = OpFAdd %29 %310 %311 -%313 = OpCompositeExtract %29 %52 1 -%314 = OpCompositeExtract %29 %52 1 -%315 = OpFAdd %29 %313 %314 -%316 = OpCompositeExtract %29 %52 2 -%317 = OpCompositeExtract %29 %52 2 -%318 = OpFAdd %29 %316 %317 -%309 = OpCompositeConstruct %37 %312 %315 %318 -%320 = OpCompositeExtract %29 %52 0 -%321 = OpCompositeExtract %29 %52 0 -%322 = OpFSub %29 %320 %321 -%323 = OpCompositeExtract %29 %52 1 -%324 = OpCompositeExtract %29 %52 1 -%325 = OpFSub %29 %323 %324 -%326 = OpCompositeExtract %29 %52 2 -%327 = OpCompositeExtract %29 %52 2 -%328 = OpFSub %29 %326 %327 -%319 = OpCompositeConstruct %37 %322 %325 %328 -%329 = OpMatrixTimesScalar %37 %52 %3 -%330 = OpMatrixTimesScalar %37 %52 %14 -%331 = OpCompositeConstruct %26 %3 %3 %3 %3 -%332 = OpMatrixTimesVector %29 %53 %331 -%333 = OpCompositeConstruct %29 %14 %14 %14 -%334 = OpVectorTimesMatrix %26 %333 %53 -%335 = OpMatrixTimesMatrix %37 %53 %54 +%161 = OpFunction %2 None %144 +%160 = OpLabel +OpBranch %162 +%162 = OpLabel +%164 = OpCompositeConstruct %163 %7 %7 +%165 = OpSNegate %163 %164 +%166 = OpCompositeConstruct %31 %3 %3 +%167 = OpFNegate %31 %166 +%168 = OpIAdd %8 %18 %7 +%169 = OpIAdd %20 %24 %25 +%170 = OpFAdd %4 %14 %3 +%171 = OpCompositeConstruct %163 %18 %18 +%172 = OpCompositeConstruct %163 %7 %7 +%173 = OpIAdd %163 %171 %172 +%175 = OpCompositeConstruct %174 %24 %24 %24 +%176 = OpCompositeConstruct %174 %25 %25 %25 +%177 = OpIAdd %174 %175 %176 +%178 = OpCompositeConstruct %26 %14 %14 %14 %14 +%179 = OpCompositeConstruct %26 %3 %3 %3 %3 +%180 = OpFAdd %26 %178 %179 +%181 = OpISub %8 %18 %7 +%182 = OpISub %20 %24 %25 +%183 = OpFSub %4 %14 %3 +%184 = OpCompositeConstruct %163 %18 %18 +%185 = OpCompositeConstruct %163 %7 %7 +%186 = OpISub %163 %184 %185 +%187 = OpCompositeConstruct %174 %24 %24 %24 +%188 = OpCompositeConstruct %174 %25 %25 %25 +%189 = OpISub %174 %187 %188 +%190 = OpCompositeConstruct %26 %14 %14 %14 %14 +%191 = OpCompositeConstruct %26 %3 %3 %3 %3 +%192 = OpFSub %26 %190 %191 +%193 = OpIMul %8 %18 %7 +%194 = OpIMul %20 %24 %25 +%195 = OpFMul %4 %14 %3 +%196 = OpCompositeConstruct %163 %18 %18 +%197 = OpCompositeConstruct %163 %7 %7 +%198 = OpIMul %163 %196 %197 +%199 = OpCompositeConstruct %174 %24 %24 %24 +%200 = OpCompositeConstruct %174 %25 %25 %25 +%201 = OpIMul %174 %199 %200 +%202 = OpCompositeConstruct %26 %14 %14 %14 %14 +%203 = OpCompositeConstruct %26 %3 %3 %3 %3 +%204 = OpFMul %26 %202 %203 +%205 = OpSDiv %8 %18 %7 +%206 = OpUDiv %20 %24 %25 +%207 = OpFDiv %4 %14 %3 +%208 = OpCompositeConstruct %163 %18 %18 +%209 = OpCompositeConstruct %163 %7 %7 +%210 = OpSDiv %163 %208 %209 +%211 = OpCompositeConstruct %174 %24 %24 %24 +%212 = OpCompositeConstruct %174 %25 %25 %25 +%213 = OpUDiv %174 %211 %212 +%214 = OpCompositeConstruct %26 %14 %14 %14 %14 +%215 = OpCompositeConstruct %26 %3 %3 %3 %3 +%216 = OpFDiv %26 %214 %215 +%217 = OpSRem %8 %18 %7 +%218 = OpUMod %20 %24 %25 +%219 = OpFRem %4 %14 %3 +%220 = OpCompositeConstruct %163 %18 %18 +%221 = OpCompositeConstruct %163 %7 %7 +%222 = OpSRem %163 %220 %221 +%223 = OpCompositeConstruct %174 %24 %24 %24 +%224 = OpCompositeConstruct %174 %25 %25 %25 +%225 = OpUMod %174 %223 %224 +%226 = OpCompositeConstruct %26 %14 %14 %14 %14 +%227 = OpCompositeConstruct %26 %3 %3 %3 %3 +%228 = OpFRem %26 %226 %227 +%229 = OpCompositeConstruct %163 %18 %18 +%230 = OpCompositeConstruct %163 %7 %7 +%231 = OpIAdd %163 %229 %230 +%232 = OpCompositeConstruct %163 %7 %7 +%233 = OpCompositeConstruct %163 %18 %18 +%234 = OpIAdd %163 %233 %232 +%235 = OpCompositeConstruct %34 %24 %24 +%236 = OpCompositeConstruct %34 %25 %25 +%237 = OpIAdd %34 %235 %236 +%238 = OpCompositeConstruct %34 %25 %25 +%239 = OpCompositeConstruct %34 %24 %24 +%240 = OpIAdd %34 %239 %238 +%241 = OpCompositeConstruct %31 %14 %14 +%242 = OpCompositeConstruct %31 %3 %3 +%243 = OpFAdd %31 %241 %242 +%244 = OpCompositeConstruct %31 %3 %3 +%245 = OpCompositeConstruct %31 %14 %14 +%246 = OpFAdd %31 %245 %244 +%247 = OpCompositeConstruct %163 %18 %18 +%248 = OpCompositeConstruct %163 %7 %7 +%249 = OpISub %163 %247 %248 +%250 = OpCompositeConstruct %163 %7 %7 +%251 = OpCompositeConstruct %163 %18 %18 +%252 = OpISub %163 %251 %250 +%253 = OpCompositeConstruct %34 %24 %24 +%254 = OpCompositeConstruct %34 %25 %25 +%255 = OpISub %34 %253 %254 +%256 = OpCompositeConstruct %34 %25 %25 +%257 = OpCompositeConstruct %34 %24 %24 +%258 = OpISub %34 %257 %256 +%259 = OpCompositeConstruct %31 %14 %14 +%260 = OpCompositeConstruct %31 %3 %3 +%261 = OpFSub %31 %259 %260 +%262 = OpCompositeConstruct %31 %3 %3 +%263 = OpCompositeConstruct %31 %14 %14 +%264 = OpFSub %31 %263 %262 +%265 = OpCompositeConstruct %163 %18 %18 +%267 = OpCompositeConstruct %163 %7 %7 +%266 = OpIMul %163 %265 %267 +%268 = OpCompositeConstruct %163 %7 %7 +%270 = OpCompositeConstruct %163 %18 %18 +%269 = OpIMul %163 %268 %270 +%271 = OpCompositeConstruct %34 %24 %24 +%273 = OpCompositeConstruct %34 %25 %25 +%272 = OpIMul %34 %271 %273 +%274 = OpCompositeConstruct %34 %25 %25 +%276 = OpCompositeConstruct %34 %24 %24 +%275 = OpIMul %34 %274 %276 +%277 = OpCompositeConstruct %31 %14 %14 +%278 = OpVectorTimesScalar %31 %277 %3 +%279 = OpCompositeConstruct %31 %3 %3 +%280 = OpVectorTimesScalar %31 %279 %14 +%281 = OpCompositeConstruct %163 %18 %18 +%282 = OpCompositeConstruct %163 %7 %7 +%283 = OpSDiv %163 %281 %282 +%284 = OpCompositeConstruct %163 %7 %7 +%285 = OpCompositeConstruct %163 %18 %18 +%286 = OpSDiv %163 %285 %284 +%287 = OpCompositeConstruct %34 %24 %24 +%288 = OpCompositeConstruct %34 %25 %25 +%289 = OpUDiv %34 %287 %288 +%290 = OpCompositeConstruct %34 %25 %25 +%291 = OpCompositeConstruct %34 %24 %24 +%292 = OpUDiv %34 %291 %290 +%293 = OpCompositeConstruct %31 %14 %14 +%294 = OpCompositeConstruct %31 %3 %3 +%295 = OpFDiv %31 %293 %294 +%296 = OpCompositeConstruct %31 %3 %3 +%297 = OpCompositeConstruct %31 %14 %14 +%298 = OpFDiv %31 %297 %296 +%299 = OpCompositeConstruct %163 %18 %18 +%300 = OpCompositeConstruct %163 %7 %7 +%301 = OpSRem %163 %299 %300 +%302 = OpCompositeConstruct %163 %7 %7 +%303 = OpCompositeConstruct %163 %18 %18 +%304 = OpSRem %163 %303 %302 +%305 = OpCompositeConstruct %34 %24 %24 +%306 = OpCompositeConstruct %34 %25 %25 +%307 = OpUMod %34 %305 %306 +%308 = OpCompositeConstruct %34 %25 %25 +%309 = OpCompositeConstruct %34 %24 %24 +%310 = OpUMod %34 %309 %308 +%311 = OpCompositeConstruct %31 %14 %14 +%312 = OpCompositeConstruct %31 %3 %3 +%313 = OpFRem %31 %311 %312 +%314 = OpCompositeConstruct %31 %3 %3 +%315 = OpCompositeConstruct %31 %14 %14 +%316 = OpFRem %31 %315 %314 +%318 = OpCompositeExtract %29 %54 0 +%319 = OpCompositeExtract %29 %54 0 +%320 = OpFAdd %29 %318 %319 +%321 = OpCompositeExtract %29 %54 1 +%322 = OpCompositeExtract %29 %54 1 +%323 = OpFAdd %29 %321 %322 +%324 = OpCompositeExtract %29 %54 2 +%325 = OpCompositeExtract %29 %54 2 +%326 = OpFAdd %29 %324 %325 +%317 = OpCompositeConstruct %38 %320 %323 %326 +%328 = OpCompositeExtract %29 %54 0 +%329 = OpCompositeExtract %29 %54 0 +%330 = OpFSub %29 %328 %329 +%331 = OpCompositeExtract %29 %54 1 +%332 = OpCompositeExtract %29 %54 1 +%333 = OpFSub %29 %331 %332 +%334 = OpCompositeExtract %29 %54 2 +%335 = OpCompositeExtract %29 %54 2 +%336 = OpFSub %29 %334 %335 +%327 = OpCompositeConstruct %38 %330 %333 %336 +%337 = OpMatrixTimesScalar %38 %54 %3 +%338 = OpMatrixTimesScalar %38 %54 %14 +%339 = OpCompositeConstruct %26 %3 %3 %3 %3 +%340 = OpMatrixTimesVector %29 %55 %339 +%341 = OpCompositeConstruct %29 %14 %14 %14 +%342 = OpVectorTimesMatrix %26 %341 %55 +%343 = OpMatrixTimesMatrix %38 %55 %56 OpReturn OpFunctionEnd -%337 = OpFunction %2 None %136 -%336 = OpLabel -OpBranch %338 -%338 = OpLabel -%339 = OpNot %8 %7 -%340 = OpNot %20 %25 -%341 = OpCompositeConstruct %155 %7 %7 -%342 = OpNot %155 %341 -%343 = OpCompositeConstruct %166 %25 %25 %25 -%344 = OpNot %166 %343 -%345 = OpBitwiseOr %8 %18 %7 -%346 = OpBitwiseOr %20 %24 %25 -%347 = OpCompositeConstruct %155 %18 %18 -%348 = OpCompositeConstruct %155 %7 %7 -%349 = OpBitwiseOr %155 %347 %348 -%350 = OpCompositeConstruct %166 %24 %24 %24 -%351 = OpCompositeConstruct %166 %25 %25 %25 -%352 = OpBitwiseOr %166 %350 %351 -%353 = OpBitwiseAnd %8 %18 %7 -%354 = OpBitwiseAnd %20 %24 %25 -%355 = OpCompositeConstruct %155 %18 %18 -%356 = OpCompositeConstruct %155 %7 %7 -%357 = OpBitwiseAnd %155 %355 %356 -%358 = OpCompositeConstruct %166 %24 %24 %24 -%359 = OpCompositeConstruct %166 %25 %25 %25 -%360 = OpBitwiseAnd %166 %358 %359 -%361 = OpBitwiseXor %8 %18 %7 -%362 = OpBitwiseXor %20 %24 %25 -%363 = OpCompositeConstruct %155 %18 %18 -%364 = OpCompositeConstruct %155 %7 %7 -%365 = OpBitwiseXor %155 %363 %364 -%366 = OpCompositeConstruct %166 %24 %24 %24 -%367 = OpCompositeConstruct %166 %25 %25 %25 -%368 = OpBitwiseXor %166 %366 %367 -%369 = OpShiftLeftLogical %8 %18 %25 -%370 = OpShiftLeftLogical %20 %24 %25 -%371 = OpCompositeConstruct %155 %18 %18 -%372 = OpCompositeConstruct %34 %25 %25 -%373 = OpShiftLeftLogical %155 %371 %372 -%374 = OpCompositeConstruct %166 %24 %24 %24 -%375 = OpCompositeConstruct %166 %25 %25 %25 -%376 = OpShiftLeftLogical %166 %374 %375 -%377 = OpShiftRightArithmetic %8 %18 %25 -%378 = OpShiftRightLogical %20 %24 %25 -%379 = OpCompositeConstruct %155 %18 %18 +%345 = OpFunction %2 None %144 +%344 = OpLabel +OpBranch %346 +%346 = OpLabel +%347 = OpNot %8 %7 +%348 = OpNot %20 %25 +%349 = OpCompositeConstruct %163 %7 %7 +%350 = OpNot %163 %349 +%351 = OpCompositeConstruct %174 %25 %25 %25 +%352 = OpNot %174 %351 +%353 = OpBitwiseOr %8 %18 %7 +%354 = OpBitwiseOr %20 %24 %25 +%355 = OpCompositeConstruct %163 %18 %18 +%356 = OpCompositeConstruct %163 %7 %7 +%357 = OpBitwiseOr %163 %355 %356 +%358 = OpCompositeConstruct %174 %24 %24 %24 +%359 = OpCompositeConstruct %174 %25 %25 %25 +%360 = OpBitwiseOr %174 %358 %359 +%361 = OpBitwiseAnd %8 %18 %7 +%362 = OpBitwiseAnd %20 %24 %25 +%363 = OpCompositeConstruct %163 %18 %18 +%364 = OpCompositeConstruct %163 %7 %7 +%365 = OpBitwiseAnd %163 %363 %364 +%366 = OpCompositeConstruct %174 %24 %24 %24 +%367 = OpCompositeConstruct %174 %25 %25 %25 +%368 = OpBitwiseAnd %174 %366 %367 +%369 = OpBitwiseXor %8 %18 %7 +%370 = OpBitwiseXor %20 %24 %25 +%371 = OpCompositeConstruct %163 %18 %18 +%372 = OpCompositeConstruct %163 %7 %7 +%373 = OpBitwiseXor %163 %371 %372 +%374 = OpCompositeConstruct %174 %24 %24 %24 +%375 = OpCompositeConstruct %174 %25 %25 %25 +%376 = OpBitwiseXor %174 %374 %375 +%377 = OpShiftLeftLogical %8 %18 %25 +%378 = OpShiftLeftLogical %20 %24 %25 +%379 = OpCompositeConstruct %163 %18 %18 %380 = OpCompositeConstruct %34 %25 %25 -%381 = OpShiftRightArithmetic %155 %379 %380 -%382 = OpCompositeConstruct %166 %24 %24 %24 -%383 = OpCompositeConstruct %166 %25 %25 %25 -%384 = OpShiftRightLogical %166 %382 %383 +%381 = OpShiftLeftLogical %163 %379 %380 +%382 = OpCompositeConstruct %174 %24 %24 %24 +%383 = OpCompositeConstruct %174 %25 %25 %25 +%384 = OpShiftLeftLogical %174 %382 %383 +%385 = OpShiftRightArithmetic %8 %18 %25 +%386 = OpShiftRightLogical %20 %24 %25 +%387 = OpCompositeConstruct %163 %18 %18 +%388 = OpCompositeConstruct %34 %25 %25 +%389 = OpShiftRightArithmetic %163 %387 %388 +%390 = OpCompositeConstruct %174 %24 %24 %24 +%391 = OpCompositeConstruct %174 %25 %25 %25 +%392 = OpShiftRightLogical %174 %390 %391 OpReturn OpFunctionEnd -%386 = OpFunction %2 None %136 -%385 = OpLabel -OpBranch %387 -%387 = OpLabel -%388 = OpIEqual %10 %18 %7 -%389 = OpIEqual %10 %24 %25 -%390 = OpFOrdEqual %10 %14 %3 -%391 = OpCompositeConstruct %155 %18 %18 -%392 = OpCompositeConstruct %155 %7 %7 -%393 = OpIEqual %139 %391 %392 -%394 = OpCompositeConstruct %166 %24 %24 %24 -%395 = OpCompositeConstruct %166 %25 %25 %25 -%396 = OpIEqual %102 %394 %395 -%397 = OpCompositeConstruct %26 %14 %14 %14 %14 -%398 = OpCompositeConstruct %26 %3 %3 %3 %3 -%399 = OpFOrdEqual %28 %397 %398 -%400 = OpINotEqual %10 %18 %7 -%401 = OpINotEqual %10 %24 %25 -%402 = OpFOrdNotEqual %10 %14 %3 -%403 = OpCompositeConstruct %155 %18 %18 -%404 = OpCompositeConstruct %155 %7 %7 -%405 = OpINotEqual %139 %403 %404 -%406 = OpCompositeConstruct %166 %24 %24 %24 -%407 = OpCompositeConstruct %166 %25 %25 %25 -%408 = OpINotEqual %102 %406 %407 -%409 = OpCompositeConstruct %26 %14 %14 %14 %14 -%410 = OpCompositeConstruct %26 %3 %3 %3 %3 -%411 = OpFOrdNotEqual %28 %409 %410 -%412 = OpSLessThan %10 %18 %7 -%413 = OpULessThan %10 %24 %25 -%414 = OpFOrdLessThan %10 %14 %3 -%415 = OpCompositeConstruct %155 %18 %18 -%416 = OpCompositeConstruct %155 %7 %7 -%417 = OpSLessThan %139 %415 %416 -%418 = OpCompositeConstruct %166 %24 %24 %24 -%419 = OpCompositeConstruct %166 %25 %25 %25 -%420 = OpULessThan %102 %418 %419 -%421 = OpCompositeConstruct %26 %14 %14 %14 %14 -%422 = OpCompositeConstruct %26 %3 %3 %3 %3 -%423 = OpFOrdLessThan %28 %421 %422 -%424 = OpSLessThanEqual %10 %18 %7 -%425 = OpULessThanEqual %10 %24 %25 -%426 = OpFOrdLessThanEqual %10 %14 %3 -%427 = OpCompositeConstruct %155 %18 %18 -%428 = OpCompositeConstruct %155 %7 %7 -%429 = OpSLessThanEqual %139 %427 %428 -%430 = OpCompositeConstruct %166 %24 %24 %24 -%431 = OpCompositeConstruct %166 %25 %25 %25 -%432 = OpULessThanEqual %102 %430 %431 -%433 = OpCompositeConstruct %26 %14 %14 %14 %14 -%434 = OpCompositeConstruct %26 %3 %3 %3 %3 -%435 = OpFOrdLessThanEqual %28 %433 %434 -%436 = OpSGreaterThan %10 %18 %7 -%437 = OpUGreaterThan %10 %24 %25 -%438 = OpFOrdGreaterThan %10 %14 %3 -%439 = OpCompositeConstruct %155 %18 %18 -%440 = OpCompositeConstruct %155 %7 %7 -%441 = OpSGreaterThan %139 %439 %440 -%442 = OpCompositeConstruct %166 %24 %24 %24 -%443 = OpCompositeConstruct %166 %25 %25 %25 -%444 = OpUGreaterThan %102 %442 %443 -%445 = OpCompositeConstruct %26 %14 %14 %14 %14 -%446 = OpCompositeConstruct %26 %3 %3 %3 %3 -%447 = OpFOrdGreaterThan %28 %445 %446 -%448 = OpSGreaterThanEqual %10 %18 %7 -%449 = OpUGreaterThanEqual %10 %24 %25 -%450 = OpFOrdGreaterThanEqual %10 %14 %3 -%451 = OpCompositeConstruct %155 %18 %18 -%452 = OpCompositeConstruct %155 %7 %7 -%453 = OpSGreaterThanEqual %139 %451 %452 -%454 = OpCompositeConstruct %166 %24 %24 %24 -%455 = OpCompositeConstruct %166 %25 %25 %25 -%456 = OpUGreaterThanEqual %102 %454 %455 -%457 = OpCompositeConstruct %26 %14 %14 %14 %14 -%458 = OpCompositeConstruct %26 %3 %3 %3 %3 -%459 = OpFOrdGreaterThanEqual %28 %457 %458 +%394 = OpFunction %2 None %144 +%393 = OpLabel +OpBranch %395 +%395 = OpLabel +%396 = OpIEqual %10 %18 %7 +%397 = OpIEqual %10 %24 %25 +%398 = OpFOrdEqual %10 %14 %3 +%399 = OpCompositeConstruct %163 %18 %18 +%400 = OpCompositeConstruct %163 %7 %7 +%401 = OpIEqual %147 %399 %400 +%402 = OpCompositeConstruct %174 %24 %24 %24 +%403 = OpCompositeConstruct %174 %25 %25 %25 +%404 = OpIEqual %104 %402 %403 +%405 = OpCompositeConstruct %26 %14 %14 %14 %14 +%406 = OpCompositeConstruct %26 %3 %3 %3 %3 +%407 = OpFOrdEqual %28 %405 %406 +%408 = OpINotEqual %10 %18 %7 +%409 = OpINotEqual %10 %24 %25 +%410 = OpFOrdNotEqual %10 %14 %3 +%411 = OpCompositeConstruct %163 %18 %18 +%412 = OpCompositeConstruct %163 %7 %7 +%413 = OpINotEqual %147 %411 %412 +%414 = OpCompositeConstruct %174 %24 %24 %24 +%415 = OpCompositeConstruct %174 %25 %25 %25 +%416 = OpINotEqual %104 %414 %415 +%417 = OpCompositeConstruct %26 %14 %14 %14 %14 +%418 = OpCompositeConstruct %26 %3 %3 %3 %3 +%419 = OpFOrdNotEqual %28 %417 %418 +%420 = OpSLessThan %10 %18 %7 +%421 = OpULessThan %10 %24 %25 +%422 = OpFOrdLessThan %10 %14 %3 +%423 = OpCompositeConstruct %163 %18 %18 +%424 = OpCompositeConstruct %163 %7 %7 +%425 = OpSLessThan %147 %423 %424 +%426 = OpCompositeConstruct %174 %24 %24 %24 +%427 = OpCompositeConstruct %174 %25 %25 %25 +%428 = OpULessThan %104 %426 %427 +%429 = OpCompositeConstruct %26 %14 %14 %14 %14 +%430 = OpCompositeConstruct %26 %3 %3 %3 %3 +%431 = OpFOrdLessThan %28 %429 %430 +%432 = OpSLessThanEqual %10 %18 %7 +%433 = OpULessThanEqual %10 %24 %25 +%434 = OpFOrdLessThanEqual %10 %14 %3 +%435 = OpCompositeConstruct %163 %18 %18 +%436 = OpCompositeConstruct %163 %7 %7 +%437 = OpSLessThanEqual %147 %435 %436 +%438 = OpCompositeConstruct %174 %24 %24 %24 +%439 = OpCompositeConstruct %174 %25 %25 %25 +%440 = OpULessThanEqual %104 %438 %439 +%441 = OpCompositeConstruct %26 %14 %14 %14 %14 +%442 = OpCompositeConstruct %26 %3 %3 %3 %3 +%443 = OpFOrdLessThanEqual %28 %441 %442 +%444 = OpSGreaterThan %10 %18 %7 +%445 = OpUGreaterThan %10 %24 %25 +%446 = OpFOrdGreaterThan %10 %14 %3 +%447 = OpCompositeConstruct %163 %18 %18 +%448 = OpCompositeConstruct %163 %7 %7 +%449 = OpSGreaterThan %147 %447 %448 +%450 = OpCompositeConstruct %174 %24 %24 %24 +%451 = OpCompositeConstruct %174 %25 %25 %25 +%452 = OpUGreaterThan %104 %450 %451 +%453 = OpCompositeConstruct %26 %14 %14 %14 %14 +%454 = OpCompositeConstruct %26 %3 %3 %3 %3 +%455 = OpFOrdGreaterThan %28 %453 %454 +%456 = OpSGreaterThanEqual %10 %18 %7 +%457 = OpUGreaterThanEqual %10 %24 %25 +%458 = OpFOrdGreaterThanEqual %10 %14 %3 +%459 = OpCompositeConstruct %163 %18 %18 +%460 = OpCompositeConstruct %163 %7 %7 +%461 = OpSGreaterThanEqual %147 %459 %460 +%462 = OpCompositeConstruct %174 %24 %24 %24 +%463 = OpCompositeConstruct %174 %25 %25 %25 +%464 = OpUGreaterThanEqual %104 %462 %463 +%465 = OpCompositeConstruct %26 %14 %14 %14 %14 +%466 = OpCompositeConstruct %26 %3 %3 %3 %3 +%467 = OpFOrdGreaterThanEqual %28 %465 %466 OpReturn OpFunctionEnd -%465 = OpFunction %2 None %136 -%464 = OpLabel -%460 = OpVariable %461 Function %7 -%462 = OpVariable %463 Function %55 -OpBranch %466 -%466 = OpLabel -%467 = OpLoad %8 %460 -%468 = OpIAdd %8 %467 %7 -OpStore %460 %468 -%469 = OpLoad %8 %460 -%470 = OpISub %8 %469 %7 -OpStore %460 %470 -%471 = OpLoad %8 %460 -%472 = OpLoad %8 %460 -%473 = OpIMul %8 %471 %472 -OpStore %460 %473 -%474 = OpLoad %8 %460 -%475 = OpLoad %8 %460 -%476 = OpSDiv %8 %474 %475 -OpStore %460 %476 -%477 = OpLoad %8 %460 -%478 = OpSRem %8 %477 %7 -OpStore %460 %478 -%479 = OpLoad %8 %460 -%480 = OpBitwiseAnd %8 %479 %11 -OpStore %460 %480 -%481 = OpLoad %8 %460 -%482 = OpBitwiseOr %8 %481 %11 -OpStore %460 %482 -%483 = OpLoad %8 %460 -%484 = OpBitwiseXor %8 %483 %11 -OpStore %460 %484 -%485 = OpLoad %8 %460 -%486 = OpShiftLeftLogical %8 %485 %24 -OpStore %460 %486 -%487 = OpLoad %8 %460 -%488 = OpShiftRightArithmetic %8 %487 %25 -OpStore %460 %488 -%489 = OpLoad %8 %460 -%490 = OpIAdd %8 %489 %7 -OpStore %460 %490 -%491 = OpLoad %8 %460 -%492 = OpISub %8 %491 %7 -OpStore %460 %492 -%494 = OpAccessChain %493 %462 %25 -%495 = OpLoad %8 %494 -%496 = OpIAdd %8 %495 %7 -%497 = OpAccessChain %493 %462 %25 -OpStore %497 %496 -%498 = OpAccessChain %493 %462 %25 -%499 = OpLoad %8 %498 +%473 = OpFunction %2 None %144 +%472 = OpLabel +%468 = OpVariable %469 Function %7 +%470 = OpVariable %471 Function %57 +OpBranch %474 +%474 = OpLabel +%475 = OpLoad %8 %468 +%476 = OpIAdd %8 %475 %7 +OpStore %468 %476 +%477 = OpLoad %8 %468 +%478 = OpISub %8 %477 %7 +OpStore %468 %478 +%479 = OpLoad %8 %468 +%480 = OpLoad %8 %468 +%481 = OpIMul %8 %479 %480 +OpStore %468 %481 +%482 = OpLoad %8 %468 +%483 = OpLoad %8 %468 +%484 = OpSDiv %8 %482 %483 +OpStore %468 %484 +%485 = OpLoad %8 %468 +%486 = OpSRem %8 %485 %7 +OpStore %468 %486 +%487 = OpLoad %8 %468 +%488 = OpBitwiseAnd %8 %487 %11 +OpStore %468 %488 +%489 = OpLoad %8 %468 +%490 = OpBitwiseOr %8 %489 %11 +OpStore %468 %490 +%491 = OpLoad %8 %468 +%492 = OpBitwiseXor %8 %491 %11 +OpStore %468 %492 +%493 = OpLoad %8 %468 +%494 = OpShiftLeftLogical %8 %493 %24 +OpStore %468 %494 +%495 = OpLoad %8 %468 +%496 = OpShiftRightArithmetic %8 %495 %25 +OpStore %468 %496 +%497 = OpLoad %8 %468 +%498 = OpIAdd %8 %497 %7 +OpStore %468 %498 +%499 = OpLoad %8 %468 %500 = OpISub %8 %499 %7 -%501 = OpAccessChain %493 %462 %25 -OpStore %501 %500 +OpStore %468 %500 +%502 = OpAccessChain %501 %470 %25 +%503 = OpLoad %8 %502 +%504 = OpIAdd %8 %503 %7 +%505 = OpAccessChain %501 %470 %25 +OpStore %505 %504 +%506 = OpAccessChain %501 %470 %25 +%507 = OpLoad %8 %506 +%508 = OpISub %8 %507 %7 +%509 = OpAccessChain %501 %470 %25 +OpStore %509 %508 OpReturn OpFunctionEnd -%503 = OpFunction %2 None %136 -%502 = OpLabel -OpBranch %504 -%504 = OpLabel -%505 = OpFunctionCall %26 %57 -%506 = OpFunctionCall %26 %82 -%507 = OpVectorShuffle %29 %41 %41 0 1 2 -%508 = OpFunctionCall %29 %99 %507 -%509 = OpFunctionCall %4 %112 -%510 = OpFunctionCall %2 %135 -%511 = OpFunctionCall %2 %153 -%512 = OpFunctionCall %2 %337 -%513 = OpFunctionCall %2 %386 -%514 = OpFunctionCall %2 %465 +%511 = OpFunction %2 None %144 +%510 = OpLabel +OpBranch %512 +%512 = OpLabel +%513 = OpFunctionCall %26 %59 +%514 = OpFunctionCall %26 %84 +%515 = OpVectorShuffle %29 %42 %42 0 1 2 +%516 = OpFunctionCall %29 %101 %515 +%517 = OpFunctionCall %4 %114 +%518 = OpFunctionCall %2 %143 +%519 = OpFunctionCall %2 %161 +%520 = OpFunctionCall %2 %345 +%521 = OpFunctionCall %2 %394 +%522 = OpFunctionCall %2 %473 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index ec6a73654..172a39109 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -39,8 +39,14 @@ fn constructors() -> f32 { _ = vec2(0u); _ = mat2x2(vec2(0.0), vec2(0.0)); _ = array(0, 1, 2, 3); - let _e59 = foo.a.x; - return _e59; + _ = bool(false); + _ = i32(0); + _ = u32(0u); + _ = f32(0.0); + _ = vec2(vec2(0u, 0u)); + _ = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let _e71 = foo.a.x; + return _e71; } fn logical() { From b7ff50619c952647d9204a5b8ac54b9a9b7dd1ab Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 12 May 2022 16:03:45 +0200 Subject: [PATCH 1747/2212] [spv-out] use OpCopyObject for bool - bool conversion due to OpBitcast not being feasible for booleans --- src/back/spv/block.rs | 3 ++- tests/out/spv/operators.spvasm | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 4e4149b06..c19dbdb6b 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -956,7 +956,8 @@ impl<'w> BlockContext<'w> { } let cast = match (src_kind, kind, convert) { - (_, _, None) | (Sk::Bool, Sk::Bool, Some(_)) => Cast::Unary(spirv::Op::Bitcast), + (Sk::Bool, Sk::Bool, _) => Cast::Unary(spirv::Op::CopyObject), + (_, _, None) => Cast::Unary(spirv::Op::Bitcast), // casting to a bool - generate `OpXxxNotEqual` (_, Sk::Bool, Some(_)) => { let (op, value) = match src_kind { diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index c39fcfb63..36cc238ef 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -161,7 +161,7 @@ OpStore %110 %118 %129 = OpCompositeConstruct %31 %5 %5 %130 = OpCompositeConstruct %32 %128 %129 %131 = OpCompositeConstruct %36 %11 %7 %18 %21 -%132 = OpBitcast %10 %12 +%132 = OpCopyObject %10 %12 %133 = OpBitcast %8 %11 %134 = OpBitcast %20 %19 %135 = OpBitcast %4 %5 From f48174a0b46a8bd30310d4c9b39ef71639db00c3 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 12 May 2022 16:16:06 +0200 Subject: [PATCH 1748/2212] [spv-out] use OpCopyObject for matrix identity casts --- src/back/spv/block.rs | 203 +++++++++++++++++---------------- tests/out/spv/operators.spvasm | 2 +- 2 files changed, 108 insertions(+), 97 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index c19dbdb6b..413f4df5d 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -938,11 +938,13 @@ impl<'w> BlockContext<'w> { use crate::ScalarKind as Sk; let expr_id = self.cached[expr]; - let (src_kind, src_size, src_width) = + let (src_kind, src_size, src_width, is_matrix) = match *self.fun_info[expr].ty.inner_with(&self.ir_module.types) { - crate::TypeInner::Scalar { kind, width } => (kind, None, width), - crate::TypeInner::Vector { kind, width, size } => (kind, Some(size), width), - crate::TypeInner::Matrix { width, .. } => (kind, None, width), + crate::TypeInner::Scalar { kind, width } => (kind, None, width, false), + crate::TypeInner::Vector { kind, width, size } => { + (kind, Some(size), width, false) + } + crate::TypeInner::Matrix { width, .. } => (kind, None, width, true), ref other => { log::error!("As source {:?}", other); return Err(Error::Validation("Unexpected Expression::As source")); @@ -955,103 +957,112 @@ impl<'w> BlockContext<'w> { Ternary(spirv::Op, Word, Word), } - let cast = match (src_kind, kind, convert) { - (Sk::Bool, Sk::Bool, _) => Cast::Unary(spirv::Op::CopyObject), - (_, _, None) => Cast::Unary(spirv::Op::Bitcast), - // casting to a bool - generate `OpXxxNotEqual` - (_, Sk::Bool, Some(_)) => { - let (op, value) = match src_kind { - Sk::Sint => (spirv::Op::INotEqual, crate::ScalarValue::Sint(0)), - Sk::Uint => (spirv::Op::INotEqual, crate::ScalarValue::Uint(0)), - Sk::Float => { - (spirv::Op::FUnordNotEqual, crate::ScalarValue::Float(0.0)) - } - Sk::Bool => unreachable!(), - }; - let zero_scalar_id = self.writer.get_constant_scalar(value, src_width); - let zero_id = match src_size { - Some(size) => { - let vector_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(size), - kind: src_kind, - width: src_width, - pointer_space: None, - })); - let components = [zero_scalar_id; 4]; + let cast = if is_matrix { + // we only support identity casts for matrices + Cast::Unary(spirv::Op::CopyObject) + } else { + match (src_kind, kind, convert) { + (Sk::Bool, Sk::Bool, _) => Cast::Unary(spirv::Op::CopyObject), + (_, _, None) => Cast::Unary(spirv::Op::Bitcast), + // casting to a bool - generate `OpXxxNotEqual` + (_, Sk::Bool, Some(_)) => { + let (op, value) = match src_kind { + Sk::Sint => (spirv::Op::INotEqual, crate::ScalarValue::Sint(0)), + Sk::Uint => (spirv::Op::INotEqual, crate::ScalarValue::Uint(0)), + Sk::Float => { + (spirv::Op::FUnordNotEqual, crate::ScalarValue::Float(0.0)) + } + Sk::Bool => unreachable!(), + }; + let zero_scalar_id = self.writer.get_constant_scalar(value, src_width); + let zero_id = match src_size { + Some(size) => { + let vector_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind: src_kind, + width: src_width, + pointer_space: None, + })); + let components = [zero_scalar_id; 4]; - let zero_id = self.gen_id(); - block.body.push(Instruction::composite_construct( - vector_type_id, - zero_id, - &components[..size as usize], - )); - zero_id - } - None => zero_scalar_id, - }; + let zero_id = self.gen_id(); + block.body.push(Instruction::composite_construct( + vector_type_id, + zero_id, + &components[..size as usize], + )); + zero_id + } + None => zero_scalar_id, + }; - Cast::Binary(op, zero_id) - } - // casting from a bool - generate `OpSelect` - (Sk::Bool, _, Some(dst_width)) => { - let (val0, val1) = match kind { - Sk::Sint => (crate::ScalarValue::Sint(0), crate::ScalarValue::Sint(1)), - Sk::Uint => (crate::ScalarValue::Uint(0), crate::ScalarValue::Uint(1)), - Sk::Float => ( - crate::ScalarValue::Float(0.0), - crate::ScalarValue::Float(1.0), - ), - Sk::Bool => unreachable!(), - }; - let scalar0_id = self.writer.get_constant_scalar(val0, dst_width); - let scalar1_id = self.writer.get_constant_scalar(val1, dst_width); - let (accept_id, reject_id) = match src_size { - Some(size) => { - let vector_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(size), - kind, - width: dst_width, - pointer_space: None, - })); - let components0 = [scalar0_id; 4]; - let components1 = [scalar1_id; 4]; + Cast::Binary(op, zero_id) + } + // casting from a bool - generate `OpSelect` + (Sk::Bool, _, Some(dst_width)) => { + let (val0, val1) = match kind { + Sk::Sint => { + (crate::ScalarValue::Sint(0), crate::ScalarValue::Sint(1)) + } + Sk::Uint => { + (crate::ScalarValue::Uint(0), crate::ScalarValue::Uint(1)) + } + Sk::Float => ( + crate::ScalarValue::Float(0.0), + crate::ScalarValue::Float(1.0), + ), + Sk::Bool => unreachable!(), + }; + let scalar0_id = self.writer.get_constant_scalar(val0, dst_width); + let scalar1_id = self.writer.get_constant_scalar(val1, dst_width); + let (accept_id, reject_id) = match src_size { + Some(size) => { + let vector_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind, + width: dst_width, + pointer_space: None, + })); + let components0 = [scalar0_id; 4]; + let components1 = [scalar1_id; 4]; - let vec0_id = self.gen_id(); - block.body.push(Instruction::composite_construct( - vector_type_id, - vec0_id, - &components0[..size as usize], - )); - let vec1_id = self.gen_id(); - block.body.push(Instruction::composite_construct( - vector_type_id, - vec1_id, - &components1[..size as usize], - )); - (vec1_id, vec0_id) - } - None => (scalar1_id, scalar0_id), - }; + let vec0_id = self.gen_id(); + block.body.push(Instruction::composite_construct( + vector_type_id, + vec0_id, + &components0[..size as usize], + )); + let vec1_id = self.gen_id(); + block.body.push(Instruction::composite_construct( + vector_type_id, + vec1_id, + &components1[..size as usize], + )); + (vec1_id, vec0_id) + } + None => (scalar1_id, scalar0_id), + }; - Cast::Ternary(spirv::Op::Select, accept_id, reject_id) + Cast::Ternary(spirv::Op::Select, accept_id, reject_id) + } + (Sk::Float, Sk::Uint, Some(_)) => Cast::Unary(spirv::Op::ConvertFToU), + (Sk::Float, Sk::Sint, Some(_)) => Cast::Unary(spirv::Op::ConvertFToS), + (Sk::Float, Sk::Float, Some(dst_width)) if src_width != dst_width => { + Cast::Unary(spirv::Op::FConvert) + } + (Sk::Sint, Sk::Float, Some(_)) => Cast::Unary(spirv::Op::ConvertSToF), + (Sk::Sint, Sk::Sint, Some(dst_width)) if src_width != dst_width => { + Cast::Unary(spirv::Op::SConvert) + } + (Sk::Uint, Sk::Float, Some(_)) => Cast::Unary(spirv::Op::ConvertUToF), + (Sk::Uint, Sk::Uint, Some(dst_width)) if src_width != dst_width => { + Cast::Unary(spirv::Op::UConvert) + } + // We assume it's either an identity cast, or int-uint. + _ => Cast::Unary(spirv::Op::Bitcast), } - (Sk::Float, Sk::Uint, Some(_)) => Cast::Unary(spirv::Op::ConvertFToU), - (Sk::Float, Sk::Sint, Some(_)) => Cast::Unary(spirv::Op::ConvertFToS), - (Sk::Float, Sk::Float, Some(dst_width)) if src_width != dst_width => { - Cast::Unary(spirv::Op::FConvert) - } - (Sk::Sint, Sk::Float, Some(_)) => Cast::Unary(spirv::Op::ConvertSToF), - (Sk::Sint, Sk::Sint, Some(dst_width)) if src_width != dst_width => { - Cast::Unary(spirv::Op::SConvert) - } - (Sk::Uint, Sk::Float, Some(_)) => Cast::Unary(spirv::Op::ConvertUToF), - (Sk::Uint, Sk::Uint, Some(dst_width)) if src_width != dst_width => { - Cast::Unary(spirv::Op::UConvert) - } - // We assume it's either an identity cast, or int-uint. - _ => Cast::Unary(spirv::Op::Bitcast), }; let id = self.gen_id(); diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 36cc238ef..657ad2e33 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -166,7 +166,7 @@ OpStore %110 %118 %134 = OpBitcast %20 %19 %135 = OpBitcast %4 %5 %136 = OpBitcast %34 %46 -%137 = OpBitcast %37 %53 +%137 = OpCopyObject %37 %53 %140 = OpAccessChain %139 %110 %19 %19 %141 = OpLoad %4 %140 OpReturnValue %141 From 6dae3ac7e000810a082cbf6b44745235f5832278 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 12 May 2022 16:18:37 +0200 Subject: [PATCH 1749/2212] [wgsl-in] support partial vector & matrix identity constructors --- src/front/wgsl/construction.rs | 41 ++ tests/in/operators.wgsl | 2 + tests/out/glsl/operators.main.Compute.glsl | 278 ++++---- tests/out/hlsl/operators.hlsl | 280 ++++---- tests/out/msl/operators.msl | 280 ++++---- tests/out/spv/operators.spvasm | 792 +++++++++++---------- tests/out/wgsl/operators.wgsl | 6 +- 7 files changed, 866 insertions(+), 813 deletions(-) diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/construction.rs index 281116d3f..f675b12e1 100644 --- a/src/front/wgsl/construction.rs +++ b/src/front/wgsl/construction.rs @@ -363,6 +363,25 @@ pub(super) fn parse_construction<'a>( convert: Some(dst_width), }, + // Vector conversion (vector -> vector) - partial + ( + Components::One { + component, + ty: + &TypeInner::Vector { + size: src_size, + kind: src_kind, + .. + }, + .. + }, + ConstructorType::PartialVector { size: dst_size }, + ) if dst_size == src_size => Expression::As { + expr: component, + kind: src_kind, + convert: None, + }, + // Matrix conversion (matrix -> matrix) ( Components::One { @@ -386,6 +405,28 @@ pub(super) fn parse_construction<'a>( convert: Some(dst_width), }, + // Matrix conversion (matrix -> matrix) - partial + ( + Components::One { + component, + ty: + &TypeInner::Matrix { + columns: src_columns, + rows: src_rows, + .. + }, + .. + }, + ConstructorType::PartialMatrix { + columns: dst_columns, + rows: dst_rows, + }, + ) if dst_columns == src_columns && dst_rows == src_rows => Expression::As { + expr: component, + kind: ScalarKind::Float, + convert: None, + }, + // Vector constructor (splat) - infer type ( Components::One { diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 385b424a9..6cee25f2c 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -75,6 +75,8 @@ fn constructors() -> f32 { _ = f32(f32()); _ = vec2(vec2()); _ = mat2x3(mat2x3()); + _ = vec2(vec2()); + _ = mat2x3(mat2x3()); return foo.a.x; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 85f9e16c8..ab232d553 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -47,157 +47,159 @@ float constructors() { float unnamed_6 = float(0.0); uvec2 unnamed_7 = uvec2(uvec2(0u, 0u)); mat2x3 unnamed_8 = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - float _e71 = foo.a.x; - return _e71; + uvec2 unnamed_9 = uvec2(0u, 0u); + mat2x3 unnamed_10 = mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); + float _e75 = foo.a.x; + return _e75; } void logical() { - bool unnamed_9 = (!true); - bvec2 unnamed_10 = not(bvec2(true)); - bool unnamed_11 = (true || false); - bool unnamed_12 = (true && false); + bool unnamed_11 = (!true); + bvec2 unnamed_12 = not(bvec2(true)); bool unnamed_13 = (true || false); - bvec3 unnamed_14 = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); - bool unnamed_15 = (true && false); - bvec4 unnamed_16 = bvec4(bvec4(true).x && bvec4(false).x, bvec4(true).y && bvec4(false).y, bvec4(true).z && bvec4(false).z, bvec4(true).w && bvec4(false).w); + bool unnamed_14 = (true && false); + bool unnamed_15 = (true || false); + bvec3 unnamed_16 = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); + bool unnamed_17 = (true && false); + bvec4 unnamed_18 = bvec4(bvec4(true).x && bvec4(false).x, bvec4(true).y && bvec4(false).y, bvec4(true).z && bvec4(false).z, bvec4(true).w && bvec4(false).w); } void arithmetic() { - ivec2 unnamed_17 = (-ivec2(1)); - vec2 unnamed_18 = (-vec2(1.0)); - int unnamed_19 = (2 + 1); - uint unnamed_20 = (2u + 1u); - float unnamed_21 = (2.0 + 1.0); - ivec2 unnamed_22 = (ivec2(2) + ivec2(1)); - uvec3 unnamed_23 = (uvec3(2u) + uvec3(1u)); - vec4 unnamed_24 = (vec4(2.0) + vec4(1.0)); - int unnamed_25 = (2 - 1); - uint unnamed_26 = (2u - 1u); - float unnamed_27 = (2.0 - 1.0); - ivec2 unnamed_28 = (ivec2(2) - ivec2(1)); - uvec3 unnamed_29 = (uvec3(2u) - uvec3(1u)); - vec4 unnamed_30 = (vec4(2.0) - vec4(1.0)); - int unnamed_31 = (2 * 1); - uint unnamed_32 = (2u * 1u); - float unnamed_33 = (2.0 * 1.0); - ivec2 unnamed_34 = (ivec2(2) * ivec2(1)); - uvec3 unnamed_35 = (uvec3(2u) * uvec3(1u)); - vec4 unnamed_36 = (vec4(2.0) * vec4(1.0)); - int unnamed_37 = (2 / 1); - uint unnamed_38 = (2u / 1u); - float unnamed_39 = (2.0 / 1.0); - ivec2 unnamed_40 = (ivec2(2) / ivec2(1)); - uvec3 unnamed_41 = (uvec3(2u) / uvec3(1u)); - vec4 unnamed_42 = (vec4(2.0) / vec4(1.0)); - int unnamed_43 = (2 % 1); - uint unnamed_44 = (2u % 1u); - float unnamed_45 = (2.0 - 1.0 * trunc(2.0 / 1.0)); - ivec2 unnamed_46 = (ivec2(2) % ivec2(1)); - uvec3 unnamed_47 = (uvec3(2u) % uvec3(1u)); - vec4 unnamed_48 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); - ivec2 unnamed_49 = (ivec2(2) + ivec2(1)); - ivec2 unnamed_50 = (ivec2(2) + ivec2(1)); - uvec2 unnamed_51 = (uvec2(2u) + uvec2(1u)); - uvec2 unnamed_52 = (uvec2(2u) + uvec2(1u)); - vec2 unnamed_53 = (vec2(2.0) + vec2(1.0)); - vec2 unnamed_54 = (vec2(2.0) + vec2(1.0)); - ivec2 unnamed_55 = (ivec2(2) - ivec2(1)); - ivec2 unnamed_56 = (ivec2(2) - ivec2(1)); - uvec2 unnamed_57 = (uvec2(2u) - uvec2(1u)); - uvec2 unnamed_58 = (uvec2(2u) - uvec2(1u)); - vec2 unnamed_59 = (vec2(2.0) - vec2(1.0)); - vec2 unnamed_60 = (vec2(2.0) - vec2(1.0)); - ivec2 unnamed_61 = (ivec2(2) * 1); - ivec2 unnamed_62 = (2 * ivec2(1)); - uvec2 unnamed_63 = (uvec2(2u) * 1u); - uvec2 unnamed_64 = (2u * uvec2(1u)); - vec2 unnamed_65 = (vec2(2.0) * 1.0); - vec2 unnamed_66 = (2.0 * vec2(1.0)); - ivec2 unnamed_67 = (ivec2(2) / ivec2(1)); - ivec2 unnamed_68 = (ivec2(2) / ivec2(1)); - uvec2 unnamed_69 = (uvec2(2u) / uvec2(1u)); - uvec2 unnamed_70 = (uvec2(2u) / uvec2(1u)); - vec2 unnamed_71 = (vec2(2.0) / vec2(1.0)); - vec2 unnamed_72 = (vec2(2.0) / vec2(1.0)); - ivec2 unnamed_73 = (ivec2(2) % ivec2(1)); - ivec2 unnamed_74 = (ivec2(2) % ivec2(1)); - uvec2 unnamed_75 = (uvec2(2u) % uvec2(1u)); - uvec2 unnamed_76 = (uvec2(2u) % uvec2(1u)); - vec2 unnamed_77 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); - vec2 unnamed_78 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); - mat3x3 unnamed_79 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_80 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_81 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - mat3x3 unnamed_82 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - vec3 unnamed_83 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - vec4 unnamed_84 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_85 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + ivec2 unnamed_19 = (-ivec2(1)); + vec2 unnamed_20 = (-vec2(1.0)); + int unnamed_21 = (2 + 1); + uint unnamed_22 = (2u + 1u); + float unnamed_23 = (2.0 + 1.0); + ivec2 unnamed_24 = (ivec2(2) + ivec2(1)); + uvec3 unnamed_25 = (uvec3(2u) + uvec3(1u)); + vec4 unnamed_26 = (vec4(2.0) + vec4(1.0)); + int unnamed_27 = (2 - 1); + uint unnamed_28 = (2u - 1u); + float unnamed_29 = (2.0 - 1.0); + ivec2 unnamed_30 = (ivec2(2) - ivec2(1)); + uvec3 unnamed_31 = (uvec3(2u) - uvec3(1u)); + vec4 unnamed_32 = (vec4(2.0) - vec4(1.0)); + int unnamed_33 = (2 * 1); + uint unnamed_34 = (2u * 1u); + float unnamed_35 = (2.0 * 1.0); + ivec2 unnamed_36 = (ivec2(2) * ivec2(1)); + uvec3 unnamed_37 = (uvec3(2u) * uvec3(1u)); + vec4 unnamed_38 = (vec4(2.0) * vec4(1.0)); + int unnamed_39 = (2 / 1); + uint unnamed_40 = (2u / 1u); + float unnamed_41 = (2.0 / 1.0); + ivec2 unnamed_42 = (ivec2(2) / ivec2(1)); + uvec3 unnamed_43 = (uvec3(2u) / uvec3(1u)); + vec4 unnamed_44 = (vec4(2.0) / vec4(1.0)); + int unnamed_45 = (2 % 1); + uint unnamed_46 = (2u % 1u); + float unnamed_47 = (2.0 - 1.0 * trunc(2.0 / 1.0)); + ivec2 unnamed_48 = (ivec2(2) % ivec2(1)); + uvec3 unnamed_49 = (uvec3(2u) % uvec3(1u)); + vec4 unnamed_50 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); + ivec2 unnamed_51 = (ivec2(2) + ivec2(1)); + ivec2 unnamed_52 = (ivec2(2) + ivec2(1)); + uvec2 unnamed_53 = (uvec2(2u) + uvec2(1u)); + uvec2 unnamed_54 = (uvec2(2u) + uvec2(1u)); + vec2 unnamed_55 = (vec2(2.0) + vec2(1.0)); + vec2 unnamed_56 = (vec2(2.0) + vec2(1.0)); + ivec2 unnamed_57 = (ivec2(2) - ivec2(1)); + ivec2 unnamed_58 = (ivec2(2) - ivec2(1)); + uvec2 unnamed_59 = (uvec2(2u) - uvec2(1u)); + uvec2 unnamed_60 = (uvec2(2u) - uvec2(1u)); + vec2 unnamed_61 = (vec2(2.0) - vec2(1.0)); + vec2 unnamed_62 = (vec2(2.0) - vec2(1.0)); + ivec2 unnamed_63 = (ivec2(2) * 1); + ivec2 unnamed_64 = (2 * ivec2(1)); + uvec2 unnamed_65 = (uvec2(2u) * 1u); + uvec2 unnamed_66 = (2u * uvec2(1u)); + vec2 unnamed_67 = (vec2(2.0) * 1.0); + vec2 unnamed_68 = (2.0 * vec2(1.0)); + ivec2 unnamed_69 = (ivec2(2) / ivec2(1)); + ivec2 unnamed_70 = (ivec2(2) / ivec2(1)); + uvec2 unnamed_71 = (uvec2(2u) / uvec2(1u)); + uvec2 unnamed_72 = (uvec2(2u) / uvec2(1u)); + vec2 unnamed_73 = (vec2(2.0) / vec2(1.0)); + vec2 unnamed_74 = (vec2(2.0) / vec2(1.0)); + ivec2 unnamed_75 = (ivec2(2) % ivec2(1)); + ivec2 unnamed_76 = (ivec2(2) % ivec2(1)); + uvec2 unnamed_77 = (uvec2(2u) % uvec2(1u)); + uvec2 unnamed_78 = (uvec2(2u) % uvec2(1u)); + vec2 unnamed_79 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + vec2 unnamed_80 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + mat3x3 unnamed_81 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_82 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_83 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); + mat3x3 unnamed_84 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + vec3 unnamed_85 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); + vec4 unnamed_86 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + mat3x3 unnamed_87 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); } void bit() { - int unnamed_86 = (~1); - uint unnamed_87 = (~1u); - ivec2 unnamed_88 = (~ivec2(1)); - uvec3 unnamed_89 = (~uvec3(1u)); - int unnamed_90 = (2 | 1); - uint unnamed_91 = (2u | 1u); - ivec2 unnamed_92 = (ivec2(2) | ivec2(1)); - uvec3 unnamed_93 = (uvec3(2u) | uvec3(1u)); - int unnamed_94 = (2 & 1); - uint unnamed_95 = (2u & 1u); - ivec2 unnamed_96 = (ivec2(2) & ivec2(1)); - uvec3 unnamed_97 = (uvec3(2u) & uvec3(1u)); - int unnamed_98 = (2 ^ 1); - uint unnamed_99 = (2u ^ 1u); - ivec2 unnamed_100 = (ivec2(2) ^ ivec2(1)); - uvec3 unnamed_101 = (uvec3(2u) ^ uvec3(1u)); - int unnamed_102 = (2 << 1u); - uint unnamed_103 = (2u << 1u); - ivec2 unnamed_104 = (ivec2(2) << uvec2(1u)); - uvec3 unnamed_105 = (uvec3(2u) << uvec3(1u)); - int unnamed_106 = (2 >> 1u); - uint unnamed_107 = (2u >> 1u); - ivec2 unnamed_108 = (ivec2(2) >> uvec2(1u)); - uvec3 unnamed_109 = (uvec3(2u) >> uvec3(1u)); + int unnamed_88 = (~1); + uint unnamed_89 = (~1u); + ivec2 unnamed_90 = (~ivec2(1)); + uvec3 unnamed_91 = (~uvec3(1u)); + int unnamed_92 = (2 | 1); + uint unnamed_93 = (2u | 1u); + ivec2 unnamed_94 = (ivec2(2) | ivec2(1)); + uvec3 unnamed_95 = (uvec3(2u) | uvec3(1u)); + int unnamed_96 = (2 & 1); + uint unnamed_97 = (2u & 1u); + ivec2 unnamed_98 = (ivec2(2) & ivec2(1)); + uvec3 unnamed_99 = (uvec3(2u) & uvec3(1u)); + int unnamed_100 = (2 ^ 1); + uint unnamed_101 = (2u ^ 1u); + ivec2 unnamed_102 = (ivec2(2) ^ ivec2(1)); + uvec3 unnamed_103 = (uvec3(2u) ^ uvec3(1u)); + int unnamed_104 = (2 << 1u); + uint unnamed_105 = (2u << 1u); + ivec2 unnamed_106 = (ivec2(2) << uvec2(1u)); + uvec3 unnamed_107 = (uvec3(2u) << uvec3(1u)); + int unnamed_108 = (2 >> 1u); + uint unnamed_109 = (2u >> 1u); + ivec2 unnamed_110 = (ivec2(2) >> uvec2(1u)); + uvec3 unnamed_111 = (uvec3(2u) >> uvec3(1u)); } void comparison() { - bool unnamed_110 = (2 == 1); - bool unnamed_111 = (2u == 1u); - bool unnamed_112 = (2.0 == 1.0); - bvec2 unnamed_113 = equal(ivec2(2), ivec2(1)); - bvec3 unnamed_114 = equal(uvec3(2u), uvec3(1u)); - bvec4 unnamed_115 = equal(vec4(2.0), vec4(1.0)); - bool unnamed_116 = (2 != 1); - bool unnamed_117 = (2u != 1u); - bool unnamed_118 = (2.0 != 1.0); - bvec2 unnamed_119 = notEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_120 = notEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_121 = notEqual(vec4(2.0), vec4(1.0)); - bool unnamed_122 = (2 < 1); - bool unnamed_123 = (2u < 1u); - bool unnamed_124 = (2.0 < 1.0); - bvec2 unnamed_125 = lessThan(ivec2(2), ivec2(1)); - bvec3 unnamed_126 = lessThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_127 = lessThan(vec4(2.0), vec4(1.0)); - bool unnamed_128 = (2 <= 1); - bool unnamed_129 = (2u <= 1u); - bool unnamed_130 = (2.0 <= 1.0); - bvec2 unnamed_131 = lessThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_132 = lessThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_133 = lessThanEqual(vec4(2.0), vec4(1.0)); - bool unnamed_134 = (2 > 1); - bool unnamed_135 = (2u > 1u); - bool unnamed_136 = (2.0 > 1.0); - bvec2 unnamed_137 = greaterThan(ivec2(2), ivec2(1)); - bvec3 unnamed_138 = greaterThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_139 = greaterThan(vec4(2.0), vec4(1.0)); - bool unnamed_140 = (2 >= 1); - bool unnamed_141 = (2u >= 1u); - bool unnamed_142 = (2.0 >= 1.0); - bvec2 unnamed_143 = greaterThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_144 = greaterThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_145 = greaterThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_112 = (2 == 1); + bool unnamed_113 = (2u == 1u); + bool unnamed_114 = (2.0 == 1.0); + bvec2 unnamed_115 = equal(ivec2(2), ivec2(1)); + bvec3 unnamed_116 = equal(uvec3(2u), uvec3(1u)); + bvec4 unnamed_117 = equal(vec4(2.0), vec4(1.0)); + bool unnamed_118 = (2 != 1); + bool unnamed_119 = (2u != 1u); + bool unnamed_120 = (2.0 != 1.0); + bvec2 unnamed_121 = notEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_122 = notEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_123 = notEqual(vec4(2.0), vec4(1.0)); + bool unnamed_124 = (2 < 1); + bool unnamed_125 = (2u < 1u); + bool unnamed_126 = (2.0 < 1.0); + bvec2 unnamed_127 = lessThan(ivec2(2), ivec2(1)); + bvec3 unnamed_128 = lessThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_129 = lessThan(vec4(2.0), vec4(1.0)); + bool unnamed_130 = (2 <= 1); + bool unnamed_131 = (2u <= 1u); + bool unnamed_132 = (2.0 <= 1.0); + bvec2 unnamed_133 = lessThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_134 = lessThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_135 = lessThanEqual(vec4(2.0), vec4(1.0)); + bool unnamed_136 = (2 > 1); + bool unnamed_137 = (2u > 1u); + bool unnamed_138 = (2.0 > 1.0); + bvec2 unnamed_139 = greaterThan(ivec2(2), ivec2(1)); + bvec3 unnamed_140 = greaterThan(uvec3(2u), uvec3(1u)); + bvec4 unnamed_141 = greaterThan(vec4(2.0), vec4(1.0)); + bool unnamed_142 = (2 >= 1); + bool unnamed_143 = (2u >= 1u); + bool unnamed_144 = (2.0 >= 1.0); + bvec2 unnamed_145 = greaterThanEqual(ivec2(2), ivec2(1)); + bvec3 unnamed_146 = greaterThanEqual(uvec3(2u), uvec3(1u)); + bvec4 unnamed_147 = greaterThanEqual(vec4(2.0), vec4(1.0)); } void assignment() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 672dcc303..e1e0335f8 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -70,161 +70,163 @@ float constructors() float unnamed_6 = float(0.0); uint2 unnamed_7 = uint2(uint2(0u, 0u)); float2x3 unnamed_8 = float2x3(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float _expr71 = foo.a.x; - return _expr71; + uint2 unnamed_9 = uint2(uint2(0u, 0u)); + float2x3 unnamed_10 = float2x3(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float _expr75 = foo.a.x; + return _expr75; } void logical() { - bool unnamed_9 = !true; - bool2 unnamed_10 = !(true).xx; - bool unnamed_11 = (true || false); - bool unnamed_12 = (true && false); - bool unnamed_13 = (true | false); - bool3 unnamed_14 = ((true).xxx | (false).xxx); - bool unnamed_15 = (true & false); - bool4 unnamed_16 = ((true).xxxx & (false).xxxx); + bool unnamed_11 = !true; + bool2 unnamed_12 = !(true).xx; + bool unnamed_13 = (true || false); + bool unnamed_14 = (true && false); + bool unnamed_15 = (true | false); + bool3 unnamed_16 = ((true).xxx | (false).xxx); + bool unnamed_17 = (true & false); + bool4 unnamed_18 = ((true).xxxx & (false).xxxx); } void arithmetic() { - int2 unnamed_17 = -(1).xx; - float2 unnamed_18 = -(1.0).xx; - int unnamed_19 = (2 + 1); - uint unnamed_20 = (2u + 1u); - float unnamed_21 = (2.0 + 1.0); - int2 unnamed_22 = ((2).xx + (1).xx); - uint3 unnamed_23 = ((2u).xxx + (1u).xxx); - float4 unnamed_24 = ((2.0).xxxx + (1.0).xxxx); - int unnamed_25 = (2 - 1); - uint unnamed_26 = (2u - 1u); - float unnamed_27 = (2.0 - 1.0); - int2 unnamed_28 = ((2).xx - (1).xx); - uint3 unnamed_29 = ((2u).xxx - (1u).xxx); - float4 unnamed_30 = ((2.0).xxxx - (1.0).xxxx); - int unnamed_31 = (2 * 1); - uint unnamed_32 = (2u * 1u); - float unnamed_33 = (2.0 * 1.0); - int2 unnamed_34 = ((2).xx * (1).xx); - uint3 unnamed_35 = ((2u).xxx * (1u).xxx); - float4 unnamed_36 = ((2.0).xxxx * (1.0).xxxx); - int unnamed_37 = (2 / 1); - uint unnamed_38 = (2u / 1u); - float unnamed_39 = (2.0 / 1.0); - int2 unnamed_40 = ((2).xx / (1).xx); - uint3 unnamed_41 = ((2u).xxx / (1u).xxx); - float4 unnamed_42 = ((2.0).xxxx / (1.0).xxxx); - int unnamed_43 = (2 % 1); - uint unnamed_44 = (2u % 1u); - float unnamed_45 = fmod(2.0, 1.0); - int2 unnamed_46 = ((2).xx % (1).xx); - uint3 unnamed_47 = ((2u).xxx % (1u).xxx); - float4 unnamed_48 = fmod((2.0).xxxx, (1.0).xxxx); - int2 unnamed_49 = ((2).xx + (1).xx); - int2 unnamed_50 = ((2).xx + (1).xx); - uint2 unnamed_51 = ((2u).xx + (1u).xx); - uint2 unnamed_52 = ((2u).xx + (1u).xx); - float2 unnamed_53 = ((2.0).xx + (1.0).xx); - float2 unnamed_54 = ((2.0).xx + (1.0).xx); - int2 unnamed_55 = ((2).xx - (1).xx); - int2 unnamed_56 = ((2).xx - (1).xx); - uint2 unnamed_57 = ((2u).xx - (1u).xx); - uint2 unnamed_58 = ((2u).xx - (1u).xx); - float2 unnamed_59 = ((2.0).xx - (1.0).xx); - float2 unnamed_60 = ((2.0).xx - (1.0).xx); - int2 unnamed_61 = ((2).xx * 1); - int2 unnamed_62 = (2 * (1).xx); - uint2 unnamed_63 = ((2u).xx * 1u); - uint2 unnamed_64 = (2u * (1u).xx); - float2 unnamed_65 = ((2.0).xx * 1.0); - float2 unnamed_66 = (2.0 * (1.0).xx); - int2 unnamed_67 = ((2).xx / (1).xx); - int2 unnamed_68 = ((2).xx / (1).xx); - uint2 unnamed_69 = ((2u).xx / (1u).xx); - uint2 unnamed_70 = ((2u).xx / (1u).xx); - float2 unnamed_71 = ((2.0).xx / (1.0).xx); - float2 unnamed_72 = ((2.0).xx / (1.0).xx); - int2 unnamed_73 = ((2).xx % (1).xx); - int2 unnamed_74 = ((2).xx % (1).xx); - uint2 unnamed_75 = ((2u).xx % (1u).xx); - uint2 unnamed_76 = ((2u).xx % (1u).xx); - float2 unnamed_77 = fmod((2.0).xx, (1.0).xx); - float2 unnamed_78 = fmod((2.0).xx, (1.0).xx); - float3x3 unnamed_79 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_80 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_81 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_82 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); - float3 unnamed_83 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float4 unnamed_84 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); - float3x3 unnamed_85 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + int2 unnamed_19 = -(1).xx; + float2 unnamed_20 = -(1.0).xx; + int unnamed_21 = (2 + 1); + uint unnamed_22 = (2u + 1u); + float unnamed_23 = (2.0 + 1.0); + int2 unnamed_24 = ((2).xx + (1).xx); + uint3 unnamed_25 = ((2u).xxx + (1u).xxx); + float4 unnamed_26 = ((2.0).xxxx + (1.0).xxxx); + int unnamed_27 = (2 - 1); + uint unnamed_28 = (2u - 1u); + float unnamed_29 = (2.0 - 1.0); + int2 unnamed_30 = ((2).xx - (1).xx); + uint3 unnamed_31 = ((2u).xxx - (1u).xxx); + float4 unnamed_32 = ((2.0).xxxx - (1.0).xxxx); + int unnamed_33 = (2 * 1); + uint unnamed_34 = (2u * 1u); + float unnamed_35 = (2.0 * 1.0); + int2 unnamed_36 = ((2).xx * (1).xx); + uint3 unnamed_37 = ((2u).xxx * (1u).xxx); + float4 unnamed_38 = ((2.0).xxxx * (1.0).xxxx); + int unnamed_39 = (2 / 1); + uint unnamed_40 = (2u / 1u); + float unnamed_41 = (2.0 / 1.0); + int2 unnamed_42 = ((2).xx / (1).xx); + uint3 unnamed_43 = ((2u).xxx / (1u).xxx); + float4 unnamed_44 = ((2.0).xxxx / (1.0).xxxx); + int unnamed_45 = (2 % 1); + uint unnamed_46 = (2u % 1u); + float unnamed_47 = fmod(2.0, 1.0); + int2 unnamed_48 = ((2).xx % (1).xx); + uint3 unnamed_49 = ((2u).xxx % (1u).xxx); + float4 unnamed_50 = fmod((2.0).xxxx, (1.0).xxxx); + int2 unnamed_51 = ((2).xx + (1).xx); + int2 unnamed_52 = ((2).xx + (1).xx); + uint2 unnamed_53 = ((2u).xx + (1u).xx); + uint2 unnamed_54 = ((2u).xx + (1u).xx); + float2 unnamed_55 = ((2.0).xx + (1.0).xx); + float2 unnamed_56 = ((2.0).xx + (1.0).xx); + int2 unnamed_57 = ((2).xx - (1).xx); + int2 unnamed_58 = ((2).xx - (1).xx); + uint2 unnamed_59 = ((2u).xx - (1u).xx); + uint2 unnamed_60 = ((2u).xx - (1u).xx); + float2 unnamed_61 = ((2.0).xx - (1.0).xx); + float2 unnamed_62 = ((2.0).xx - (1.0).xx); + int2 unnamed_63 = ((2).xx * 1); + int2 unnamed_64 = (2 * (1).xx); + uint2 unnamed_65 = ((2u).xx * 1u); + uint2 unnamed_66 = (2u * (1u).xx); + float2 unnamed_67 = ((2.0).xx * 1.0); + float2 unnamed_68 = (2.0 * (1.0).xx); + int2 unnamed_69 = ((2).xx / (1).xx); + int2 unnamed_70 = ((2).xx / (1).xx); + uint2 unnamed_71 = ((2u).xx / (1u).xx); + uint2 unnamed_72 = ((2u).xx / (1u).xx); + float2 unnamed_73 = ((2.0).xx / (1.0).xx); + float2 unnamed_74 = ((2.0).xx / (1.0).xx); + int2 unnamed_75 = ((2).xx % (1).xx); + int2 unnamed_76 = ((2).xx % (1).xx); + uint2 unnamed_77 = ((2u).xx % (1u).xx); + uint2 unnamed_78 = ((2u).xx % (1u).xx); + float2 unnamed_79 = fmod((2.0).xx, (1.0).xx); + float2 unnamed_80 = fmod((2.0).xx, (1.0).xx); + float3x3 unnamed_81 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_82 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_83 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_84 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); + float3 unnamed_85 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float4 unnamed_86 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); + float3x3 unnamed_87 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); } void bit() { - int unnamed_86 = ~1; - uint unnamed_87 = ~1u; - int2 unnamed_88 = ~(1).xx; - uint3 unnamed_89 = ~(1u).xxx; - int unnamed_90 = (2 | 1); - uint unnamed_91 = (2u | 1u); - int2 unnamed_92 = ((2).xx | (1).xx); - uint3 unnamed_93 = ((2u).xxx | (1u).xxx); - int unnamed_94 = (2 & 1); - uint unnamed_95 = (2u & 1u); - int2 unnamed_96 = ((2).xx & (1).xx); - uint3 unnamed_97 = ((2u).xxx & (1u).xxx); - int unnamed_98 = (2 ^ 1); - uint unnamed_99 = (2u ^ 1u); - int2 unnamed_100 = ((2).xx ^ (1).xx); - uint3 unnamed_101 = ((2u).xxx ^ (1u).xxx); - int unnamed_102 = (2 << 1u); - uint unnamed_103 = (2u << 1u); - int2 unnamed_104 = ((2).xx << (1u).xx); - uint3 unnamed_105 = ((2u).xxx << (1u).xxx); - int unnamed_106 = (2 >> 1u); - uint unnamed_107 = (2u >> 1u); - int2 unnamed_108 = ((2).xx >> (1u).xx); - uint3 unnamed_109 = ((2u).xxx >> (1u).xxx); + int unnamed_88 = ~1; + uint unnamed_89 = ~1u; + int2 unnamed_90 = ~(1).xx; + uint3 unnamed_91 = ~(1u).xxx; + int unnamed_92 = (2 | 1); + uint unnamed_93 = (2u | 1u); + int2 unnamed_94 = ((2).xx | (1).xx); + uint3 unnamed_95 = ((2u).xxx | (1u).xxx); + int unnamed_96 = (2 & 1); + uint unnamed_97 = (2u & 1u); + int2 unnamed_98 = ((2).xx & (1).xx); + uint3 unnamed_99 = ((2u).xxx & (1u).xxx); + int unnamed_100 = (2 ^ 1); + uint unnamed_101 = (2u ^ 1u); + int2 unnamed_102 = ((2).xx ^ (1).xx); + uint3 unnamed_103 = ((2u).xxx ^ (1u).xxx); + int unnamed_104 = (2 << 1u); + uint unnamed_105 = (2u << 1u); + int2 unnamed_106 = ((2).xx << (1u).xx); + uint3 unnamed_107 = ((2u).xxx << (1u).xxx); + int unnamed_108 = (2 >> 1u); + uint unnamed_109 = (2u >> 1u); + int2 unnamed_110 = ((2).xx >> (1u).xx); + uint3 unnamed_111 = ((2u).xxx >> (1u).xxx); } void comparison() { - bool unnamed_110 = (2 == 1); - bool unnamed_111 = (2u == 1u); - bool unnamed_112 = (2.0 == 1.0); - bool2 unnamed_113 = ((2).xx == (1).xx); - bool3 unnamed_114 = ((2u).xxx == (1u).xxx); - bool4 unnamed_115 = ((2.0).xxxx == (1.0).xxxx); - bool unnamed_116 = (2 != 1); - bool unnamed_117 = (2u != 1u); - bool unnamed_118 = (2.0 != 1.0); - bool2 unnamed_119 = ((2).xx != (1).xx); - bool3 unnamed_120 = ((2u).xxx != (1u).xxx); - bool4 unnamed_121 = ((2.0).xxxx != (1.0).xxxx); - bool unnamed_122 = (2 < 1); - bool unnamed_123 = (2u < 1u); - bool unnamed_124 = (2.0 < 1.0); - bool2 unnamed_125 = ((2).xx < (1).xx); - bool3 unnamed_126 = ((2u).xxx < (1u).xxx); - bool4 unnamed_127 = ((2.0).xxxx < (1.0).xxxx); - bool unnamed_128 = (2 <= 1); - bool unnamed_129 = (2u <= 1u); - bool unnamed_130 = (2.0 <= 1.0); - bool2 unnamed_131 = ((2).xx <= (1).xx); - bool3 unnamed_132 = ((2u).xxx <= (1u).xxx); - bool4 unnamed_133 = ((2.0).xxxx <= (1.0).xxxx); - bool unnamed_134 = (2 > 1); - bool unnamed_135 = (2u > 1u); - bool unnamed_136 = (2.0 > 1.0); - bool2 unnamed_137 = ((2).xx > (1).xx); - bool3 unnamed_138 = ((2u).xxx > (1u).xxx); - bool4 unnamed_139 = ((2.0).xxxx > (1.0).xxxx); - bool unnamed_140 = (2 >= 1); - bool unnamed_141 = (2u >= 1u); - bool unnamed_142 = (2.0 >= 1.0); - bool2 unnamed_143 = ((2).xx >= (1).xx); - bool3 unnamed_144 = ((2u).xxx >= (1u).xxx); - bool4 unnamed_145 = ((2.0).xxxx >= (1.0).xxxx); + bool unnamed_112 = (2 == 1); + bool unnamed_113 = (2u == 1u); + bool unnamed_114 = (2.0 == 1.0); + bool2 unnamed_115 = ((2).xx == (1).xx); + bool3 unnamed_116 = ((2u).xxx == (1u).xxx); + bool4 unnamed_117 = ((2.0).xxxx == (1.0).xxxx); + bool unnamed_118 = (2 != 1); + bool unnamed_119 = (2u != 1u); + bool unnamed_120 = (2.0 != 1.0); + bool2 unnamed_121 = ((2).xx != (1).xx); + bool3 unnamed_122 = ((2u).xxx != (1u).xxx); + bool4 unnamed_123 = ((2.0).xxxx != (1.0).xxxx); + bool unnamed_124 = (2 < 1); + bool unnamed_125 = (2u < 1u); + bool unnamed_126 = (2.0 < 1.0); + bool2 unnamed_127 = ((2).xx < (1).xx); + bool3 unnamed_128 = ((2u).xxx < (1u).xxx); + bool4 unnamed_129 = ((2.0).xxxx < (1.0).xxxx); + bool unnamed_130 = (2 <= 1); + bool unnamed_131 = (2u <= 1u); + bool unnamed_132 = (2.0 <= 1.0); + bool2 unnamed_133 = ((2).xx <= (1).xx); + bool3 unnamed_134 = ((2u).xxx <= (1u).xxx); + bool4 unnamed_135 = ((2.0).xxxx <= (1.0).xxxx); + bool unnamed_136 = (2 > 1); + bool unnamed_137 = (2u > 1u); + bool unnamed_138 = (2.0 > 1.0); + bool2 unnamed_139 = ((2).xx > (1).xx); + bool3 unnamed_140 = ((2u).xxx > (1u).xxx); + bool4 unnamed_141 = ((2.0).xxxx > (1.0).xxxx); + bool unnamed_142 = (2 >= 1); + bool unnamed_143 = (2u >= 1u); + bool unnamed_144 = (2.0 >= 1.0); + bool2 unnamed_145 = ((2).xx >= (1).xx); + bool3 unnamed_146 = ((2u).xxx >= (1u).xxx); + bool4 unnamed_147 = ((2.0).xxxx >= (1.0).xxxx); } void assignment() diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 03b176113..d3665d35a 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -73,161 +73,163 @@ float constructors( float unnamed_6 = static_cast(0.0); metal::uint2 unnamed_7 = static_cast(const_type_11_); metal::float2x3 unnamed_8 = static_cast(const_type_14_); - float _e71 = foo.a.x; - return _e71; + metal::uint2 unnamed_9 = as_type(const_type_11_); + metal::float2x3 unnamed_10 = as_type(const_type_14_); + float _e75 = foo.a.x; + return _e75; } void logical( ) { - bool unnamed_9 = !true; - metal::bool2 unnamed_10 = !metal::bool2(true); - bool unnamed_11 = true || false; - bool unnamed_12 = true && false; - bool unnamed_13 = true | false; - metal::bool3 unnamed_14 = metal::bool3(true) | metal::bool3(false); - bool unnamed_15 = true & false; - metal::bool4 unnamed_16 = metal::bool4(true) & metal::bool4(false); + bool unnamed_11 = !true; + metal::bool2 unnamed_12 = !metal::bool2(true); + bool unnamed_13 = true || false; + bool unnamed_14 = true && false; + bool unnamed_15 = true | false; + metal::bool3 unnamed_16 = metal::bool3(true) | metal::bool3(false); + bool unnamed_17 = true & false; + metal::bool4 unnamed_18 = metal::bool4(true) & metal::bool4(false); } void arithmetic( ) { - metal::int2 unnamed_17 = -metal::int2(1); - metal::float2 unnamed_18 = -metal::float2(1.0); - int unnamed_19 = 2 + 1; - uint unnamed_20 = 2u + 1u; - float unnamed_21 = 2.0 + 1.0; - metal::int2 unnamed_22 = metal::int2(2) + metal::int2(1); - metal::uint3 unnamed_23 = metal::uint3(2u) + metal::uint3(1u); - metal::float4 unnamed_24 = metal::float4(2.0) + metal::float4(1.0); - int unnamed_25 = 2 - 1; - uint unnamed_26 = 2u - 1u; - float unnamed_27 = 2.0 - 1.0; - metal::int2 unnamed_28 = metal::int2(2) - metal::int2(1); - metal::uint3 unnamed_29 = metal::uint3(2u) - metal::uint3(1u); - metal::float4 unnamed_30 = metal::float4(2.0) - metal::float4(1.0); - int unnamed_31 = 2 * 1; - uint unnamed_32 = 2u * 1u; - float unnamed_33 = 2.0 * 1.0; - metal::int2 unnamed_34 = metal::int2(2) * metal::int2(1); - metal::uint3 unnamed_35 = metal::uint3(2u) * metal::uint3(1u); - metal::float4 unnamed_36 = metal::float4(2.0) * metal::float4(1.0); - int unnamed_37 = 2 / 1; - uint unnamed_38 = 2u / 1u; - float unnamed_39 = 2.0 / 1.0; - metal::int2 unnamed_40 = metal::int2(2) / metal::int2(1); - metal::uint3 unnamed_41 = metal::uint3(2u) / metal::uint3(1u); - metal::float4 unnamed_42 = metal::float4(2.0) / metal::float4(1.0); - int unnamed_43 = 2 % 1; - uint unnamed_44 = 2u % 1u; - float unnamed_45 = metal::fmod(2.0, 1.0); - metal::int2 unnamed_46 = metal::int2(2) % metal::int2(1); - metal::uint3 unnamed_47 = metal::uint3(2u) % metal::uint3(1u); - metal::float4 unnamed_48 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); - metal::int2 unnamed_49 = metal::int2(2) + metal::int2(1); - metal::int2 unnamed_50 = metal::int2(2) + metal::int2(1); - metal::uint2 unnamed_51 = metal::uint2(2u) + metal::uint2(1u); - metal::uint2 unnamed_52 = metal::uint2(2u) + metal::uint2(1u); - metal::float2 unnamed_53 = metal::float2(2.0) + metal::float2(1.0); - metal::float2 unnamed_54 = metal::float2(2.0) + metal::float2(1.0); - metal::int2 unnamed_55 = metal::int2(2) - metal::int2(1); - metal::int2 unnamed_56 = metal::int2(2) - metal::int2(1); - metal::uint2 unnamed_57 = metal::uint2(2u) - metal::uint2(1u); - metal::uint2 unnamed_58 = metal::uint2(2u) - metal::uint2(1u); - metal::float2 unnamed_59 = metal::float2(2.0) - metal::float2(1.0); - metal::float2 unnamed_60 = metal::float2(2.0) - metal::float2(1.0); - metal::int2 unnamed_61 = metal::int2(2) * 1; - metal::int2 unnamed_62 = 2 * metal::int2(1); - metal::uint2 unnamed_63 = metal::uint2(2u) * 1u; - metal::uint2 unnamed_64 = 2u * metal::uint2(1u); - metal::float2 unnamed_65 = metal::float2(2.0) * 1.0; - metal::float2 unnamed_66 = 2.0 * metal::float2(1.0); - metal::int2 unnamed_67 = metal::int2(2) / metal::int2(1); - metal::int2 unnamed_68 = metal::int2(2) / metal::int2(1); - metal::uint2 unnamed_69 = metal::uint2(2u) / metal::uint2(1u); - metal::uint2 unnamed_70 = metal::uint2(2u) / metal::uint2(1u); - metal::float2 unnamed_71 = metal::float2(2.0) / metal::float2(1.0); - metal::float2 unnamed_72 = metal::float2(2.0) / metal::float2(1.0); - metal::int2 unnamed_73 = metal::int2(2) % metal::int2(1); - metal::int2 unnamed_74 = metal::int2(2) % metal::int2(1); - metal::uint2 unnamed_75 = metal::uint2(2u) % metal::uint2(1u); - metal::uint2 unnamed_76 = metal::uint2(2u) % metal::uint2(1u); - metal::float2 unnamed_77 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float2 unnamed_78 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float3x3 unnamed_79 = const_type_15_ + const_type_15_; - metal::float3x3 unnamed_80 = const_type_15_ - const_type_15_; - metal::float3x3 unnamed_81 = const_type_15_ * 1.0; - metal::float3x3 unnamed_82 = 2.0 * const_type_15_; - metal::float3 unnamed_83 = const_type_16_ * metal::float4(1.0); - metal::float4 unnamed_84 = metal::float3(2.0) * const_type_16_; - metal::float3x3 unnamed_85 = const_type_16_ * const_type_17_; + metal::int2 unnamed_19 = -metal::int2(1); + metal::float2 unnamed_20 = -metal::float2(1.0); + int unnamed_21 = 2 + 1; + uint unnamed_22 = 2u + 1u; + float unnamed_23 = 2.0 + 1.0; + metal::int2 unnamed_24 = metal::int2(2) + metal::int2(1); + metal::uint3 unnamed_25 = metal::uint3(2u) + metal::uint3(1u); + metal::float4 unnamed_26 = metal::float4(2.0) + metal::float4(1.0); + int unnamed_27 = 2 - 1; + uint unnamed_28 = 2u - 1u; + float unnamed_29 = 2.0 - 1.0; + metal::int2 unnamed_30 = metal::int2(2) - metal::int2(1); + metal::uint3 unnamed_31 = metal::uint3(2u) - metal::uint3(1u); + metal::float4 unnamed_32 = metal::float4(2.0) - metal::float4(1.0); + int unnamed_33 = 2 * 1; + uint unnamed_34 = 2u * 1u; + float unnamed_35 = 2.0 * 1.0; + metal::int2 unnamed_36 = metal::int2(2) * metal::int2(1); + metal::uint3 unnamed_37 = metal::uint3(2u) * metal::uint3(1u); + metal::float4 unnamed_38 = metal::float4(2.0) * metal::float4(1.0); + int unnamed_39 = 2 / 1; + uint unnamed_40 = 2u / 1u; + float unnamed_41 = 2.0 / 1.0; + metal::int2 unnamed_42 = metal::int2(2) / metal::int2(1); + metal::uint3 unnamed_43 = metal::uint3(2u) / metal::uint3(1u); + metal::float4 unnamed_44 = metal::float4(2.0) / metal::float4(1.0); + int unnamed_45 = 2 % 1; + uint unnamed_46 = 2u % 1u; + float unnamed_47 = metal::fmod(2.0, 1.0); + metal::int2 unnamed_48 = metal::int2(2) % metal::int2(1); + metal::uint3 unnamed_49 = metal::uint3(2u) % metal::uint3(1u); + metal::float4 unnamed_50 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); + metal::int2 unnamed_51 = metal::int2(2) + metal::int2(1); + metal::int2 unnamed_52 = metal::int2(2) + metal::int2(1); + metal::uint2 unnamed_53 = metal::uint2(2u) + metal::uint2(1u); + metal::uint2 unnamed_54 = metal::uint2(2u) + metal::uint2(1u); + metal::float2 unnamed_55 = metal::float2(2.0) + metal::float2(1.0); + metal::float2 unnamed_56 = metal::float2(2.0) + metal::float2(1.0); + metal::int2 unnamed_57 = metal::int2(2) - metal::int2(1); + metal::int2 unnamed_58 = metal::int2(2) - metal::int2(1); + metal::uint2 unnamed_59 = metal::uint2(2u) - metal::uint2(1u); + metal::uint2 unnamed_60 = metal::uint2(2u) - metal::uint2(1u); + metal::float2 unnamed_61 = metal::float2(2.0) - metal::float2(1.0); + metal::float2 unnamed_62 = metal::float2(2.0) - metal::float2(1.0); + metal::int2 unnamed_63 = metal::int2(2) * 1; + metal::int2 unnamed_64 = 2 * metal::int2(1); + metal::uint2 unnamed_65 = metal::uint2(2u) * 1u; + metal::uint2 unnamed_66 = 2u * metal::uint2(1u); + metal::float2 unnamed_67 = metal::float2(2.0) * 1.0; + metal::float2 unnamed_68 = 2.0 * metal::float2(1.0); + metal::int2 unnamed_69 = metal::int2(2) / metal::int2(1); + metal::int2 unnamed_70 = metal::int2(2) / metal::int2(1); + metal::uint2 unnamed_71 = metal::uint2(2u) / metal::uint2(1u); + metal::uint2 unnamed_72 = metal::uint2(2u) / metal::uint2(1u); + metal::float2 unnamed_73 = metal::float2(2.0) / metal::float2(1.0); + metal::float2 unnamed_74 = metal::float2(2.0) / metal::float2(1.0); + metal::int2 unnamed_75 = metal::int2(2) % metal::int2(1); + metal::int2 unnamed_76 = metal::int2(2) % metal::int2(1); + metal::uint2 unnamed_77 = metal::uint2(2u) % metal::uint2(1u); + metal::uint2 unnamed_78 = metal::uint2(2u) % metal::uint2(1u); + metal::float2 unnamed_79 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + metal::float2 unnamed_80 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + metal::float3x3 unnamed_81 = const_type_15_ + const_type_15_; + metal::float3x3 unnamed_82 = const_type_15_ - const_type_15_; + metal::float3x3 unnamed_83 = const_type_15_ * 1.0; + metal::float3x3 unnamed_84 = 2.0 * const_type_15_; + metal::float3 unnamed_85 = const_type_16_ * metal::float4(1.0); + metal::float4 unnamed_86 = metal::float3(2.0) * const_type_16_; + metal::float3x3 unnamed_87 = const_type_16_ * const_type_17_; } void bit( ) { - int unnamed_86 = ~1; - uint unnamed_87 = ~1u; - metal::int2 unnamed_88 = ~metal::int2(1); - metal::uint3 unnamed_89 = ~metal::uint3(1u); - int unnamed_90 = 2 | 1; - uint unnamed_91 = 2u | 1u; - metal::int2 unnamed_92 = metal::int2(2) | metal::int2(1); - metal::uint3 unnamed_93 = metal::uint3(2u) | metal::uint3(1u); - int unnamed_94 = 2 & 1; - uint unnamed_95 = 2u & 1u; - metal::int2 unnamed_96 = metal::int2(2) & metal::int2(1); - metal::uint3 unnamed_97 = metal::uint3(2u) & metal::uint3(1u); - int unnamed_98 = 2 ^ 1; - uint unnamed_99 = 2u ^ 1u; - metal::int2 unnamed_100 = metal::int2(2) ^ metal::int2(1); - metal::uint3 unnamed_101 = metal::uint3(2u) ^ metal::uint3(1u); - int unnamed_102 = 2 << 1u; - uint unnamed_103 = 2u << 1u; - metal::int2 unnamed_104 = metal::int2(2) << metal::uint2(1u); - metal::uint3 unnamed_105 = metal::uint3(2u) << metal::uint3(1u); - int unnamed_106 = 2 >> 1u; - uint unnamed_107 = 2u >> 1u; - metal::int2 unnamed_108 = metal::int2(2) >> metal::uint2(1u); - metal::uint3 unnamed_109 = metal::uint3(2u) >> metal::uint3(1u); + int unnamed_88 = ~1; + uint unnamed_89 = ~1u; + metal::int2 unnamed_90 = ~metal::int2(1); + metal::uint3 unnamed_91 = ~metal::uint3(1u); + int unnamed_92 = 2 | 1; + uint unnamed_93 = 2u | 1u; + metal::int2 unnamed_94 = metal::int2(2) | metal::int2(1); + metal::uint3 unnamed_95 = metal::uint3(2u) | metal::uint3(1u); + int unnamed_96 = 2 & 1; + uint unnamed_97 = 2u & 1u; + metal::int2 unnamed_98 = metal::int2(2) & metal::int2(1); + metal::uint3 unnamed_99 = metal::uint3(2u) & metal::uint3(1u); + int unnamed_100 = 2 ^ 1; + uint unnamed_101 = 2u ^ 1u; + metal::int2 unnamed_102 = metal::int2(2) ^ metal::int2(1); + metal::uint3 unnamed_103 = metal::uint3(2u) ^ metal::uint3(1u); + int unnamed_104 = 2 << 1u; + uint unnamed_105 = 2u << 1u; + metal::int2 unnamed_106 = metal::int2(2) << metal::uint2(1u); + metal::uint3 unnamed_107 = metal::uint3(2u) << metal::uint3(1u); + int unnamed_108 = 2 >> 1u; + uint unnamed_109 = 2u >> 1u; + metal::int2 unnamed_110 = metal::int2(2) >> metal::uint2(1u); + metal::uint3 unnamed_111 = metal::uint3(2u) >> metal::uint3(1u); } void comparison( ) { - bool unnamed_110 = 2 == 1; - bool unnamed_111 = 2u == 1u; - bool unnamed_112 = 2.0 == 1.0; - metal::bool2 unnamed_113 = metal::int2(2) == metal::int2(1); - metal::bool3 unnamed_114 = metal::uint3(2u) == metal::uint3(1u); - metal::bool4 unnamed_115 = metal::float4(2.0) == metal::float4(1.0); - bool unnamed_116 = 2 != 1; - bool unnamed_117 = 2u != 1u; - bool unnamed_118 = 2.0 != 1.0; - metal::bool2 unnamed_119 = metal::int2(2) != metal::int2(1); - metal::bool3 unnamed_120 = metal::uint3(2u) != metal::uint3(1u); - metal::bool4 unnamed_121 = metal::float4(2.0) != metal::float4(1.0); - bool unnamed_122 = 2 < 1; - bool unnamed_123 = 2u < 1u; - bool unnamed_124 = 2.0 < 1.0; - metal::bool2 unnamed_125 = metal::int2(2) < metal::int2(1); - metal::bool3 unnamed_126 = metal::uint3(2u) < metal::uint3(1u); - metal::bool4 unnamed_127 = metal::float4(2.0) < metal::float4(1.0); - bool unnamed_128 = 2 <= 1; - bool unnamed_129 = 2u <= 1u; - bool unnamed_130 = 2.0 <= 1.0; - metal::bool2 unnamed_131 = metal::int2(2) <= metal::int2(1); - metal::bool3 unnamed_132 = metal::uint3(2u) <= metal::uint3(1u); - metal::bool4 unnamed_133 = metal::float4(2.0) <= metal::float4(1.0); - bool unnamed_134 = 2 > 1; - bool unnamed_135 = 2u > 1u; - bool unnamed_136 = 2.0 > 1.0; - metal::bool2 unnamed_137 = metal::int2(2) > metal::int2(1); - metal::bool3 unnamed_138 = metal::uint3(2u) > metal::uint3(1u); - metal::bool4 unnamed_139 = metal::float4(2.0) > metal::float4(1.0); - bool unnamed_140 = 2 >= 1; - bool unnamed_141 = 2u >= 1u; - bool unnamed_142 = 2.0 >= 1.0; - metal::bool2 unnamed_143 = metal::int2(2) >= metal::int2(1); - metal::bool3 unnamed_144 = metal::uint3(2u) >= metal::uint3(1u); - metal::bool4 unnamed_145 = metal::float4(2.0) >= metal::float4(1.0); + bool unnamed_112 = 2 == 1; + bool unnamed_113 = 2u == 1u; + bool unnamed_114 = 2.0 == 1.0; + metal::bool2 unnamed_115 = metal::int2(2) == metal::int2(1); + metal::bool3 unnamed_116 = metal::uint3(2u) == metal::uint3(1u); + metal::bool4 unnamed_117 = metal::float4(2.0) == metal::float4(1.0); + bool unnamed_118 = 2 != 1; + bool unnamed_119 = 2u != 1u; + bool unnamed_120 = 2.0 != 1.0; + metal::bool2 unnamed_121 = metal::int2(2) != metal::int2(1); + metal::bool3 unnamed_122 = metal::uint3(2u) != metal::uint3(1u); + metal::bool4 unnamed_123 = metal::float4(2.0) != metal::float4(1.0); + bool unnamed_124 = 2 < 1; + bool unnamed_125 = 2u < 1u; + bool unnamed_126 = 2.0 < 1.0; + metal::bool2 unnamed_127 = metal::int2(2) < metal::int2(1); + metal::bool3 unnamed_128 = metal::uint3(2u) < metal::uint3(1u); + metal::bool4 unnamed_129 = metal::float4(2.0) < metal::float4(1.0); + bool unnamed_130 = 2 <= 1; + bool unnamed_131 = 2u <= 1u; + bool unnamed_132 = 2.0 <= 1.0; + metal::bool2 unnamed_133 = metal::int2(2) <= metal::int2(1); + metal::bool3 unnamed_134 = metal::uint3(2u) <= metal::uint3(1u); + metal::bool4 unnamed_135 = metal::float4(2.0) <= metal::float4(1.0); + bool unnamed_136 = 2 > 1; + bool unnamed_137 = 2u > 1u; + bool unnamed_138 = 2.0 > 1.0; + metal::bool2 unnamed_139 = metal::int2(2) > metal::int2(1); + metal::bool3 unnamed_140 = metal::uint3(2u) > metal::uint3(1u); + metal::bool4 unnamed_141 = metal::float4(2.0) > metal::float4(1.0); + bool unnamed_142 = 2 >= 1; + bool unnamed_143 = 2u >= 1u; + bool unnamed_144 = 2.0 >= 1.0; + metal::bool2 unnamed_145 = metal::int2(2) >= metal::int2(1); + metal::bool3 unnamed_146 = metal::uint3(2u) >= metal::uint3(1u); + metal::bool4 unnamed_147 = metal::float4(2.0) >= metal::float4(1.0); } void assignment( diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 657ad2e33..2e7cc3139 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 523 +; Bound: 525 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %511 "main" -OpExecutionMode %511 LocalSize 1 1 1 +OpEntryPoint GLCompute %513 "main" +OpExecutionMode %513 LocalSize 1 1 1 OpMemberDecorate %30 0 Offset 0 OpMemberDecorate %30 1 Offset 16 OpDecorate %35 ArrayStride 32 @@ -73,15 +73,15 @@ OpDecorate %36 ArrayStride 4 %111 = OpTypePointer Function %30 %112 = OpConstantNull %30 %115 = OpTypeFunction %4 -%138 = OpTypePointer Function %26 -%139 = OpTypePointer Function %4 -%144 = OpTypeFunction %2 -%147 = OpTypeVector %10 2 -%163 = OpTypeVector %8 2 -%174 = OpTypeVector %20 3 -%469 = OpTypePointer Function %8 -%471 = OpTypePointer Function %41 -%501 = OpTypePointer Function %8 +%140 = OpTypePointer Function %26 +%141 = OpTypePointer Function %4 +%146 = OpTypeFunction %2 +%149 = OpTypeVector %10 2 +%165 = OpTypeVector %8 2 +%176 = OpTypeVector %20 3 +%471 = OpTypePointer Function %8 +%473 = OpTypePointer Function %41 +%503 = OpTypePointer Function %8 %59 = OpFunction %26 None %60 %58 = OpLabel OpBranch %61 @@ -167,413 +167,415 @@ OpStore %110 %118 %135 = OpBitcast %4 %5 %136 = OpBitcast %34 %46 %137 = OpCopyObject %37 %53 -%140 = OpAccessChain %139 %110 %19 %19 -%141 = OpLoad %4 %140 -OpReturnValue %141 +%138 = OpBitcast %34 %46 +%139 = OpCopyObject %37 %53 +%142 = OpAccessChain %141 %110 %19 %19 +%143 = OpLoad %4 %142 +OpReturnValue %143 OpFunctionEnd -%143 = OpFunction %2 None %144 -%142 = OpLabel -OpBranch %145 -%145 = OpLabel -%146 = OpLogicalNot %10 %9 -%148 = OpCompositeConstruct %147 %9 %9 -%149 = OpLogicalNot %147 %148 -%150 = OpLogicalOr %10 %9 %12 -%151 = OpLogicalAnd %10 %9 %12 +%145 = OpFunction %2 None %146 +%144 = OpLabel +OpBranch %147 +%147 = OpLabel +%148 = OpLogicalNot %10 %9 +%150 = OpCompositeConstruct %149 %9 %9 +%151 = OpLogicalNot %149 %150 %152 = OpLogicalOr %10 %9 %12 -%153 = OpCompositeConstruct %104 %9 %9 %9 -%154 = OpCompositeConstruct %104 %12 %12 %12 -%155 = OpLogicalOr %104 %153 %154 -%156 = OpLogicalAnd %10 %9 %12 -%157 = OpCompositeConstruct %28 %9 %9 %9 %9 -%158 = OpCompositeConstruct %28 %12 %12 %12 %12 -%159 = OpLogicalAnd %28 %157 %158 +%153 = OpLogicalAnd %10 %9 %12 +%154 = OpLogicalOr %10 %9 %12 +%155 = OpCompositeConstruct %104 %9 %9 %9 +%156 = OpCompositeConstruct %104 %12 %12 %12 +%157 = OpLogicalOr %104 %155 %156 +%158 = OpLogicalAnd %10 %9 %12 +%159 = OpCompositeConstruct %28 %9 %9 %9 %9 +%160 = OpCompositeConstruct %28 %12 %12 %12 %12 +%161 = OpLogicalAnd %28 %159 %160 OpReturn OpFunctionEnd -%161 = OpFunction %2 None %144 -%160 = OpLabel -OpBranch %162 +%163 = OpFunction %2 None %146 %162 = OpLabel -%164 = OpCompositeConstruct %163 %7 %7 -%165 = OpSNegate %163 %164 -%166 = OpCompositeConstruct %31 %3 %3 -%167 = OpFNegate %31 %166 -%168 = OpIAdd %8 %18 %7 -%169 = OpIAdd %20 %24 %25 -%170 = OpFAdd %4 %14 %3 -%171 = OpCompositeConstruct %163 %18 %18 -%172 = OpCompositeConstruct %163 %7 %7 -%173 = OpIAdd %163 %171 %172 -%175 = OpCompositeConstruct %174 %24 %24 %24 -%176 = OpCompositeConstruct %174 %25 %25 %25 -%177 = OpIAdd %174 %175 %176 -%178 = OpCompositeConstruct %26 %14 %14 %14 %14 -%179 = OpCompositeConstruct %26 %3 %3 %3 %3 -%180 = OpFAdd %26 %178 %179 -%181 = OpISub %8 %18 %7 -%182 = OpISub %20 %24 %25 -%183 = OpFSub %4 %14 %3 -%184 = OpCompositeConstruct %163 %18 %18 -%185 = OpCompositeConstruct %163 %7 %7 -%186 = OpISub %163 %184 %185 -%187 = OpCompositeConstruct %174 %24 %24 %24 -%188 = OpCompositeConstruct %174 %25 %25 %25 -%189 = OpISub %174 %187 %188 -%190 = OpCompositeConstruct %26 %14 %14 %14 %14 -%191 = OpCompositeConstruct %26 %3 %3 %3 %3 -%192 = OpFSub %26 %190 %191 -%193 = OpIMul %8 %18 %7 -%194 = OpIMul %20 %24 %25 -%195 = OpFMul %4 %14 %3 -%196 = OpCompositeConstruct %163 %18 %18 -%197 = OpCompositeConstruct %163 %7 %7 -%198 = OpIMul %163 %196 %197 -%199 = OpCompositeConstruct %174 %24 %24 %24 -%200 = OpCompositeConstruct %174 %25 %25 %25 -%201 = OpIMul %174 %199 %200 -%202 = OpCompositeConstruct %26 %14 %14 %14 %14 -%203 = OpCompositeConstruct %26 %3 %3 %3 %3 -%204 = OpFMul %26 %202 %203 -%205 = OpSDiv %8 %18 %7 -%206 = OpUDiv %20 %24 %25 -%207 = OpFDiv %4 %14 %3 -%208 = OpCompositeConstruct %163 %18 %18 -%209 = OpCompositeConstruct %163 %7 %7 -%210 = OpSDiv %163 %208 %209 -%211 = OpCompositeConstruct %174 %24 %24 %24 -%212 = OpCompositeConstruct %174 %25 %25 %25 -%213 = OpUDiv %174 %211 %212 -%214 = OpCompositeConstruct %26 %14 %14 %14 %14 -%215 = OpCompositeConstruct %26 %3 %3 %3 %3 -%216 = OpFDiv %26 %214 %215 -%217 = OpSRem %8 %18 %7 -%218 = OpUMod %20 %24 %25 -%219 = OpFRem %4 %14 %3 -%220 = OpCompositeConstruct %163 %18 %18 -%221 = OpCompositeConstruct %163 %7 %7 -%222 = OpSRem %163 %220 %221 -%223 = OpCompositeConstruct %174 %24 %24 %24 -%224 = OpCompositeConstruct %174 %25 %25 %25 -%225 = OpUMod %174 %223 %224 -%226 = OpCompositeConstruct %26 %14 %14 %14 %14 -%227 = OpCompositeConstruct %26 %3 %3 %3 %3 -%228 = OpFRem %26 %226 %227 -%229 = OpCompositeConstruct %163 %18 %18 -%230 = OpCompositeConstruct %163 %7 %7 -%231 = OpIAdd %163 %229 %230 -%232 = OpCompositeConstruct %163 %7 %7 -%233 = OpCompositeConstruct %163 %18 %18 -%234 = OpIAdd %163 %233 %232 -%235 = OpCompositeConstruct %34 %24 %24 -%236 = OpCompositeConstruct %34 %25 %25 -%237 = OpIAdd %34 %235 %236 +OpBranch %164 +%164 = OpLabel +%166 = OpCompositeConstruct %165 %7 %7 +%167 = OpSNegate %165 %166 +%168 = OpCompositeConstruct %31 %3 %3 +%169 = OpFNegate %31 %168 +%170 = OpIAdd %8 %18 %7 +%171 = OpIAdd %20 %24 %25 +%172 = OpFAdd %4 %14 %3 +%173 = OpCompositeConstruct %165 %18 %18 +%174 = OpCompositeConstruct %165 %7 %7 +%175 = OpIAdd %165 %173 %174 +%177 = OpCompositeConstruct %176 %24 %24 %24 +%178 = OpCompositeConstruct %176 %25 %25 %25 +%179 = OpIAdd %176 %177 %178 +%180 = OpCompositeConstruct %26 %14 %14 %14 %14 +%181 = OpCompositeConstruct %26 %3 %3 %3 %3 +%182 = OpFAdd %26 %180 %181 +%183 = OpISub %8 %18 %7 +%184 = OpISub %20 %24 %25 +%185 = OpFSub %4 %14 %3 +%186 = OpCompositeConstruct %165 %18 %18 +%187 = OpCompositeConstruct %165 %7 %7 +%188 = OpISub %165 %186 %187 +%189 = OpCompositeConstruct %176 %24 %24 %24 +%190 = OpCompositeConstruct %176 %25 %25 %25 +%191 = OpISub %176 %189 %190 +%192 = OpCompositeConstruct %26 %14 %14 %14 %14 +%193 = OpCompositeConstruct %26 %3 %3 %3 %3 +%194 = OpFSub %26 %192 %193 +%195 = OpIMul %8 %18 %7 +%196 = OpIMul %20 %24 %25 +%197 = OpFMul %4 %14 %3 +%198 = OpCompositeConstruct %165 %18 %18 +%199 = OpCompositeConstruct %165 %7 %7 +%200 = OpIMul %165 %198 %199 +%201 = OpCompositeConstruct %176 %24 %24 %24 +%202 = OpCompositeConstruct %176 %25 %25 %25 +%203 = OpIMul %176 %201 %202 +%204 = OpCompositeConstruct %26 %14 %14 %14 %14 +%205 = OpCompositeConstruct %26 %3 %3 %3 %3 +%206 = OpFMul %26 %204 %205 +%207 = OpSDiv %8 %18 %7 +%208 = OpUDiv %20 %24 %25 +%209 = OpFDiv %4 %14 %3 +%210 = OpCompositeConstruct %165 %18 %18 +%211 = OpCompositeConstruct %165 %7 %7 +%212 = OpSDiv %165 %210 %211 +%213 = OpCompositeConstruct %176 %24 %24 %24 +%214 = OpCompositeConstruct %176 %25 %25 %25 +%215 = OpUDiv %176 %213 %214 +%216 = OpCompositeConstruct %26 %14 %14 %14 %14 +%217 = OpCompositeConstruct %26 %3 %3 %3 %3 +%218 = OpFDiv %26 %216 %217 +%219 = OpSRem %8 %18 %7 +%220 = OpUMod %20 %24 %25 +%221 = OpFRem %4 %14 %3 +%222 = OpCompositeConstruct %165 %18 %18 +%223 = OpCompositeConstruct %165 %7 %7 +%224 = OpSRem %165 %222 %223 +%225 = OpCompositeConstruct %176 %24 %24 %24 +%226 = OpCompositeConstruct %176 %25 %25 %25 +%227 = OpUMod %176 %225 %226 +%228 = OpCompositeConstruct %26 %14 %14 %14 %14 +%229 = OpCompositeConstruct %26 %3 %3 %3 %3 +%230 = OpFRem %26 %228 %229 +%231 = OpCompositeConstruct %165 %18 %18 +%232 = OpCompositeConstruct %165 %7 %7 +%233 = OpIAdd %165 %231 %232 +%234 = OpCompositeConstruct %165 %7 %7 +%235 = OpCompositeConstruct %165 %18 %18 +%236 = OpIAdd %165 %235 %234 +%237 = OpCompositeConstruct %34 %24 %24 %238 = OpCompositeConstruct %34 %25 %25 -%239 = OpCompositeConstruct %34 %24 %24 -%240 = OpIAdd %34 %239 %238 -%241 = OpCompositeConstruct %31 %14 %14 -%242 = OpCompositeConstruct %31 %3 %3 -%243 = OpFAdd %31 %241 %242 +%239 = OpIAdd %34 %237 %238 +%240 = OpCompositeConstruct %34 %25 %25 +%241 = OpCompositeConstruct %34 %24 %24 +%242 = OpIAdd %34 %241 %240 +%243 = OpCompositeConstruct %31 %14 %14 %244 = OpCompositeConstruct %31 %3 %3 -%245 = OpCompositeConstruct %31 %14 %14 -%246 = OpFAdd %31 %245 %244 -%247 = OpCompositeConstruct %163 %18 %18 -%248 = OpCompositeConstruct %163 %7 %7 -%249 = OpISub %163 %247 %248 -%250 = OpCompositeConstruct %163 %7 %7 -%251 = OpCompositeConstruct %163 %18 %18 -%252 = OpISub %163 %251 %250 -%253 = OpCompositeConstruct %34 %24 %24 -%254 = OpCompositeConstruct %34 %25 %25 -%255 = OpISub %34 %253 %254 +%245 = OpFAdd %31 %243 %244 +%246 = OpCompositeConstruct %31 %3 %3 +%247 = OpCompositeConstruct %31 %14 %14 +%248 = OpFAdd %31 %247 %246 +%249 = OpCompositeConstruct %165 %18 %18 +%250 = OpCompositeConstruct %165 %7 %7 +%251 = OpISub %165 %249 %250 +%252 = OpCompositeConstruct %165 %7 %7 +%253 = OpCompositeConstruct %165 %18 %18 +%254 = OpISub %165 %253 %252 +%255 = OpCompositeConstruct %34 %24 %24 %256 = OpCompositeConstruct %34 %25 %25 -%257 = OpCompositeConstruct %34 %24 %24 -%258 = OpISub %34 %257 %256 -%259 = OpCompositeConstruct %31 %14 %14 -%260 = OpCompositeConstruct %31 %3 %3 -%261 = OpFSub %31 %259 %260 +%257 = OpISub %34 %255 %256 +%258 = OpCompositeConstruct %34 %25 %25 +%259 = OpCompositeConstruct %34 %24 %24 +%260 = OpISub %34 %259 %258 +%261 = OpCompositeConstruct %31 %14 %14 %262 = OpCompositeConstruct %31 %3 %3 -%263 = OpCompositeConstruct %31 %14 %14 -%264 = OpFSub %31 %263 %262 -%265 = OpCompositeConstruct %163 %18 %18 -%267 = OpCompositeConstruct %163 %7 %7 -%266 = OpIMul %163 %265 %267 -%268 = OpCompositeConstruct %163 %7 %7 -%270 = OpCompositeConstruct %163 %18 %18 -%269 = OpIMul %163 %268 %270 -%271 = OpCompositeConstruct %34 %24 %24 -%273 = OpCompositeConstruct %34 %25 %25 -%272 = OpIMul %34 %271 %273 -%274 = OpCompositeConstruct %34 %25 %25 -%276 = OpCompositeConstruct %34 %24 %24 -%275 = OpIMul %34 %274 %276 -%277 = OpCompositeConstruct %31 %14 %14 -%278 = OpVectorTimesScalar %31 %277 %3 -%279 = OpCompositeConstruct %31 %3 %3 -%280 = OpVectorTimesScalar %31 %279 %14 -%281 = OpCompositeConstruct %163 %18 %18 -%282 = OpCompositeConstruct %163 %7 %7 -%283 = OpSDiv %163 %281 %282 -%284 = OpCompositeConstruct %163 %7 %7 -%285 = OpCompositeConstruct %163 %18 %18 -%286 = OpSDiv %163 %285 %284 -%287 = OpCompositeConstruct %34 %24 %24 -%288 = OpCompositeConstruct %34 %25 %25 -%289 = OpUDiv %34 %287 %288 +%263 = OpFSub %31 %261 %262 +%264 = OpCompositeConstruct %31 %3 %3 +%265 = OpCompositeConstruct %31 %14 %14 +%266 = OpFSub %31 %265 %264 +%267 = OpCompositeConstruct %165 %18 %18 +%269 = OpCompositeConstruct %165 %7 %7 +%268 = OpIMul %165 %267 %269 +%270 = OpCompositeConstruct %165 %7 %7 +%272 = OpCompositeConstruct %165 %18 %18 +%271 = OpIMul %165 %270 %272 +%273 = OpCompositeConstruct %34 %24 %24 +%275 = OpCompositeConstruct %34 %25 %25 +%274 = OpIMul %34 %273 %275 +%276 = OpCompositeConstruct %34 %25 %25 +%278 = OpCompositeConstruct %34 %24 %24 +%277 = OpIMul %34 %276 %278 +%279 = OpCompositeConstruct %31 %14 %14 +%280 = OpVectorTimesScalar %31 %279 %3 +%281 = OpCompositeConstruct %31 %3 %3 +%282 = OpVectorTimesScalar %31 %281 %14 +%283 = OpCompositeConstruct %165 %18 %18 +%284 = OpCompositeConstruct %165 %7 %7 +%285 = OpSDiv %165 %283 %284 +%286 = OpCompositeConstruct %165 %7 %7 +%287 = OpCompositeConstruct %165 %18 %18 +%288 = OpSDiv %165 %287 %286 +%289 = OpCompositeConstruct %34 %24 %24 %290 = OpCompositeConstruct %34 %25 %25 -%291 = OpCompositeConstruct %34 %24 %24 -%292 = OpUDiv %34 %291 %290 -%293 = OpCompositeConstruct %31 %14 %14 -%294 = OpCompositeConstruct %31 %3 %3 -%295 = OpFDiv %31 %293 %294 +%291 = OpUDiv %34 %289 %290 +%292 = OpCompositeConstruct %34 %25 %25 +%293 = OpCompositeConstruct %34 %24 %24 +%294 = OpUDiv %34 %293 %292 +%295 = OpCompositeConstruct %31 %14 %14 %296 = OpCompositeConstruct %31 %3 %3 -%297 = OpCompositeConstruct %31 %14 %14 -%298 = OpFDiv %31 %297 %296 -%299 = OpCompositeConstruct %163 %18 %18 -%300 = OpCompositeConstruct %163 %7 %7 -%301 = OpSRem %163 %299 %300 -%302 = OpCompositeConstruct %163 %7 %7 -%303 = OpCompositeConstruct %163 %18 %18 -%304 = OpSRem %163 %303 %302 -%305 = OpCompositeConstruct %34 %24 %24 -%306 = OpCompositeConstruct %34 %25 %25 -%307 = OpUMod %34 %305 %306 +%297 = OpFDiv %31 %295 %296 +%298 = OpCompositeConstruct %31 %3 %3 +%299 = OpCompositeConstruct %31 %14 %14 +%300 = OpFDiv %31 %299 %298 +%301 = OpCompositeConstruct %165 %18 %18 +%302 = OpCompositeConstruct %165 %7 %7 +%303 = OpSRem %165 %301 %302 +%304 = OpCompositeConstruct %165 %7 %7 +%305 = OpCompositeConstruct %165 %18 %18 +%306 = OpSRem %165 %305 %304 +%307 = OpCompositeConstruct %34 %24 %24 %308 = OpCompositeConstruct %34 %25 %25 -%309 = OpCompositeConstruct %34 %24 %24 -%310 = OpUMod %34 %309 %308 -%311 = OpCompositeConstruct %31 %14 %14 -%312 = OpCompositeConstruct %31 %3 %3 -%313 = OpFRem %31 %311 %312 +%309 = OpUMod %34 %307 %308 +%310 = OpCompositeConstruct %34 %25 %25 +%311 = OpCompositeConstruct %34 %24 %24 +%312 = OpUMod %34 %311 %310 +%313 = OpCompositeConstruct %31 %14 %14 %314 = OpCompositeConstruct %31 %3 %3 -%315 = OpCompositeConstruct %31 %14 %14 -%316 = OpFRem %31 %315 %314 -%318 = OpCompositeExtract %29 %54 0 -%319 = OpCompositeExtract %29 %54 0 -%320 = OpFAdd %29 %318 %319 -%321 = OpCompositeExtract %29 %54 1 -%322 = OpCompositeExtract %29 %54 1 -%323 = OpFAdd %29 %321 %322 -%324 = OpCompositeExtract %29 %54 2 -%325 = OpCompositeExtract %29 %54 2 -%326 = OpFAdd %29 %324 %325 -%317 = OpCompositeConstruct %38 %320 %323 %326 -%328 = OpCompositeExtract %29 %54 0 -%329 = OpCompositeExtract %29 %54 0 -%330 = OpFSub %29 %328 %329 -%331 = OpCompositeExtract %29 %54 1 -%332 = OpCompositeExtract %29 %54 1 -%333 = OpFSub %29 %331 %332 -%334 = OpCompositeExtract %29 %54 2 -%335 = OpCompositeExtract %29 %54 2 -%336 = OpFSub %29 %334 %335 -%327 = OpCompositeConstruct %38 %330 %333 %336 -%337 = OpMatrixTimesScalar %38 %54 %3 -%338 = OpMatrixTimesScalar %38 %54 %14 -%339 = OpCompositeConstruct %26 %3 %3 %3 %3 -%340 = OpMatrixTimesVector %29 %55 %339 -%341 = OpCompositeConstruct %29 %14 %14 %14 -%342 = OpVectorTimesMatrix %26 %341 %55 -%343 = OpMatrixTimesMatrix %38 %55 %56 +%315 = OpFRem %31 %313 %314 +%316 = OpCompositeConstruct %31 %3 %3 +%317 = OpCompositeConstruct %31 %14 %14 +%318 = OpFRem %31 %317 %316 +%320 = OpCompositeExtract %29 %54 0 +%321 = OpCompositeExtract %29 %54 0 +%322 = OpFAdd %29 %320 %321 +%323 = OpCompositeExtract %29 %54 1 +%324 = OpCompositeExtract %29 %54 1 +%325 = OpFAdd %29 %323 %324 +%326 = OpCompositeExtract %29 %54 2 +%327 = OpCompositeExtract %29 %54 2 +%328 = OpFAdd %29 %326 %327 +%319 = OpCompositeConstruct %38 %322 %325 %328 +%330 = OpCompositeExtract %29 %54 0 +%331 = OpCompositeExtract %29 %54 0 +%332 = OpFSub %29 %330 %331 +%333 = OpCompositeExtract %29 %54 1 +%334 = OpCompositeExtract %29 %54 1 +%335 = OpFSub %29 %333 %334 +%336 = OpCompositeExtract %29 %54 2 +%337 = OpCompositeExtract %29 %54 2 +%338 = OpFSub %29 %336 %337 +%329 = OpCompositeConstruct %38 %332 %335 %338 +%339 = OpMatrixTimesScalar %38 %54 %3 +%340 = OpMatrixTimesScalar %38 %54 %14 +%341 = OpCompositeConstruct %26 %3 %3 %3 %3 +%342 = OpMatrixTimesVector %29 %55 %341 +%343 = OpCompositeConstruct %29 %14 %14 %14 +%344 = OpVectorTimesMatrix %26 %343 %55 +%345 = OpMatrixTimesMatrix %38 %55 %56 OpReturn OpFunctionEnd -%345 = OpFunction %2 None %144 -%344 = OpLabel -OpBranch %346 +%347 = OpFunction %2 None %146 %346 = OpLabel -%347 = OpNot %8 %7 -%348 = OpNot %20 %25 -%349 = OpCompositeConstruct %163 %7 %7 -%350 = OpNot %163 %349 -%351 = OpCompositeConstruct %174 %25 %25 %25 -%352 = OpNot %174 %351 -%353 = OpBitwiseOr %8 %18 %7 -%354 = OpBitwiseOr %20 %24 %25 -%355 = OpCompositeConstruct %163 %18 %18 -%356 = OpCompositeConstruct %163 %7 %7 -%357 = OpBitwiseOr %163 %355 %356 -%358 = OpCompositeConstruct %174 %24 %24 %24 -%359 = OpCompositeConstruct %174 %25 %25 %25 -%360 = OpBitwiseOr %174 %358 %359 -%361 = OpBitwiseAnd %8 %18 %7 -%362 = OpBitwiseAnd %20 %24 %25 -%363 = OpCompositeConstruct %163 %18 %18 -%364 = OpCompositeConstruct %163 %7 %7 -%365 = OpBitwiseAnd %163 %363 %364 -%366 = OpCompositeConstruct %174 %24 %24 %24 -%367 = OpCompositeConstruct %174 %25 %25 %25 -%368 = OpBitwiseAnd %174 %366 %367 -%369 = OpBitwiseXor %8 %18 %7 -%370 = OpBitwiseXor %20 %24 %25 -%371 = OpCompositeConstruct %163 %18 %18 -%372 = OpCompositeConstruct %163 %7 %7 -%373 = OpBitwiseXor %163 %371 %372 -%374 = OpCompositeConstruct %174 %24 %24 %24 -%375 = OpCompositeConstruct %174 %25 %25 %25 -%376 = OpBitwiseXor %174 %374 %375 -%377 = OpShiftLeftLogical %8 %18 %25 -%378 = OpShiftLeftLogical %20 %24 %25 -%379 = OpCompositeConstruct %163 %18 %18 -%380 = OpCompositeConstruct %34 %25 %25 -%381 = OpShiftLeftLogical %163 %379 %380 -%382 = OpCompositeConstruct %174 %24 %24 %24 -%383 = OpCompositeConstruct %174 %25 %25 %25 -%384 = OpShiftLeftLogical %174 %382 %383 -%385 = OpShiftRightArithmetic %8 %18 %25 -%386 = OpShiftRightLogical %20 %24 %25 -%387 = OpCompositeConstruct %163 %18 %18 -%388 = OpCompositeConstruct %34 %25 %25 -%389 = OpShiftRightArithmetic %163 %387 %388 -%390 = OpCompositeConstruct %174 %24 %24 %24 -%391 = OpCompositeConstruct %174 %25 %25 %25 -%392 = OpShiftRightLogical %174 %390 %391 +OpBranch %348 +%348 = OpLabel +%349 = OpNot %8 %7 +%350 = OpNot %20 %25 +%351 = OpCompositeConstruct %165 %7 %7 +%352 = OpNot %165 %351 +%353 = OpCompositeConstruct %176 %25 %25 %25 +%354 = OpNot %176 %353 +%355 = OpBitwiseOr %8 %18 %7 +%356 = OpBitwiseOr %20 %24 %25 +%357 = OpCompositeConstruct %165 %18 %18 +%358 = OpCompositeConstruct %165 %7 %7 +%359 = OpBitwiseOr %165 %357 %358 +%360 = OpCompositeConstruct %176 %24 %24 %24 +%361 = OpCompositeConstruct %176 %25 %25 %25 +%362 = OpBitwiseOr %176 %360 %361 +%363 = OpBitwiseAnd %8 %18 %7 +%364 = OpBitwiseAnd %20 %24 %25 +%365 = OpCompositeConstruct %165 %18 %18 +%366 = OpCompositeConstruct %165 %7 %7 +%367 = OpBitwiseAnd %165 %365 %366 +%368 = OpCompositeConstruct %176 %24 %24 %24 +%369 = OpCompositeConstruct %176 %25 %25 %25 +%370 = OpBitwiseAnd %176 %368 %369 +%371 = OpBitwiseXor %8 %18 %7 +%372 = OpBitwiseXor %20 %24 %25 +%373 = OpCompositeConstruct %165 %18 %18 +%374 = OpCompositeConstruct %165 %7 %7 +%375 = OpBitwiseXor %165 %373 %374 +%376 = OpCompositeConstruct %176 %24 %24 %24 +%377 = OpCompositeConstruct %176 %25 %25 %25 +%378 = OpBitwiseXor %176 %376 %377 +%379 = OpShiftLeftLogical %8 %18 %25 +%380 = OpShiftLeftLogical %20 %24 %25 +%381 = OpCompositeConstruct %165 %18 %18 +%382 = OpCompositeConstruct %34 %25 %25 +%383 = OpShiftLeftLogical %165 %381 %382 +%384 = OpCompositeConstruct %176 %24 %24 %24 +%385 = OpCompositeConstruct %176 %25 %25 %25 +%386 = OpShiftLeftLogical %176 %384 %385 +%387 = OpShiftRightArithmetic %8 %18 %25 +%388 = OpShiftRightLogical %20 %24 %25 +%389 = OpCompositeConstruct %165 %18 %18 +%390 = OpCompositeConstruct %34 %25 %25 +%391 = OpShiftRightArithmetic %165 %389 %390 +%392 = OpCompositeConstruct %176 %24 %24 %24 +%393 = OpCompositeConstruct %176 %25 %25 %25 +%394 = OpShiftRightLogical %176 %392 %393 OpReturn OpFunctionEnd -%394 = OpFunction %2 None %144 -%393 = OpLabel -OpBranch %395 +%396 = OpFunction %2 None %146 %395 = OpLabel -%396 = OpIEqual %10 %18 %7 -%397 = OpIEqual %10 %24 %25 -%398 = OpFOrdEqual %10 %14 %3 -%399 = OpCompositeConstruct %163 %18 %18 -%400 = OpCompositeConstruct %163 %7 %7 -%401 = OpIEqual %147 %399 %400 -%402 = OpCompositeConstruct %174 %24 %24 %24 -%403 = OpCompositeConstruct %174 %25 %25 %25 -%404 = OpIEqual %104 %402 %403 -%405 = OpCompositeConstruct %26 %14 %14 %14 %14 -%406 = OpCompositeConstruct %26 %3 %3 %3 %3 -%407 = OpFOrdEqual %28 %405 %406 -%408 = OpINotEqual %10 %18 %7 -%409 = OpINotEqual %10 %24 %25 -%410 = OpFOrdNotEqual %10 %14 %3 -%411 = OpCompositeConstruct %163 %18 %18 -%412 = OpCompositeConstruct %163 %7 %7 -%413 = OpINotEqual %147 %411 %412 -%414 = OpCompositeConstruct %174 %24 %24 %24 -%415 = OpCompositeConstruct %174 %25 %25 %25 -%416 = OpINotEqual %104 %414 %415 -%417 = OpCompositeConstruct %26 %14 %14 %14 %14 -%418 = OpCompositeConstruct %26 %3 %3 %3 %3 -%419 = OpFOrdNotEqual %28 %417 %418 -%420 = OpSLessThan %10 %18 %7 -%421 = OpULessThan %10 %24 %25 -%422 = OpFOrdLessThan %10 %14 %3 -%423 = OpCompositeConstruct %163 %18 %18 -%424 = OpCompositeConstruct %163 %7 %7 -%425 = OpSLessThan %147 %423 %424 -%426 = OpCompositeConstruct %174 %24 %24 %24 -%427 = OpCompositeConstruct %174 %25 %25 %25 -%428 = OpULessThan %104 %426 %427 -%429 = OpCompositeConstruct %26 %14 %14 %14 %14 -%430 = OpCompositeConstruct %26 %3 %3 %3 %3 -%431 = OpFOrdLessThan %28 %429 %430 -%432 = OpSLessThanEqual %10 %18 %7 -%433 = OpULessThanEqual %10 %24 %25 -%434 = OpFOrdLessThanEqual %10 %14 %3 -%435 = OpCompositeConstruct %163 %18 %18 -%436 = OpCompositeConstruct %163 %7 %7 -%437 = OpSLessThanEqual %147 %435 %436 -%438 = OpCompositeConstruct %174 %24 %24 %24 -%439 = OpCompositeConstruct %174 %25 %25 %25 -%440 = OpULessThanEqual %104 %438 %439 -%441 = OpCompositeConstruct %26 %14 %14 %14 %14 -%442 = OpCompositeConstruct %26 %3 %3 %3 %3 -%443 = OpFOrdLessThanEqual %28 %441 %442 -%444 = OpSGreaterThan %10 %18 %7 -%445 = OpUGreaterThan %10 %24 %25 -%446 = OpFOrdGreaterThan %10 %14 %3 -%447 = OpCompositeConstruct %163 %18 %18 -%448 = OpCompositeConstruct %163 %7 %7 -%449 = OpSGreaterThan %147 %447 %448 -%450 = OpCompositeConstruct %174 %24 %24 %24 -%451 = OpCompositeConstruct %174 %25 %25 %25 -%452 = OpUGreaterThan %104 %450 %451 -%453 = OpCompositeConstruct %26 %14 %14 %14 %14 -%454 = OpCompositeConstruct %26 %3 %3 %3 %3 -%455 = OpFOrdGreaterThan %28 %453 %454 -%456 = OpSGreaterThanEqual %10 %18 %7 -%457 = OpUGreaterThanEqual %10 %24 %25 -%458 = OpFOrdGreaterThanEqual %10 %14 %3 -%459 = OpCompositeConstruct %163 %18 %18 -%460 = OpCompositeConstruct %163 %7 %7 -%461 = OpSGreaterThanEqual %147 %459 %460 -%462 = OpCompositeConstruct %174 %24 %24 %24 -%463 = OpCompositeConstruct %174 %25 %25 %25 -%464 = OpUGreaterThanEqual %104 %462 %463 -%465 = OpCompositeConstruct %26 %14 %14 %14 %14 -%466 = OpCompositeConstruct %26 %3 %3 %3 %3 -%467 = OpFOrdGreaterThanEqual %28 %465 %466 +OpBranch %397 +%397 = OpLabel +%398 = OpIEqual %10 %18 %7 +%399 = OpIEqual %10 %24 %25 +%400 = OpFOrdEqual %10 %14 %3 +%401 = OpCompositeConstruct %165 %18 %18 +%402 = OpCompositeConstruct %165 %7 %7 +%403 = OpIEqual %149 %401 %402 +%404 = OpCompositeConstruct %176 %24 %24 %24 +%405 = OpCompositeConstruct %176 %25 %25 %25 +%406 = OpIEqual %104 %404 %405 +%407 = OpCompositeConstruct %26 %14 %14 %14 %14 +%408 = OpCompositeConstruct %26 %3 %3 %3 %3 +%409 = OpFOrdEqual %28 %407 %408 +%410 = OpINotEqual %10 %18 %7 +%411 = OpINotEqual %10 %24 %25 +%412 = OpFOrdNotEqual %10 %14 %3 +%413 = OpCompositeConstruct %165 %18 %18 +%414 = OpCompositeConstruct %165 %7 %7 +%415 = OpINotEqual %149 %413 %414 +%416 = OpCompositeConstruct %176 %24 %24 %24 +%417 = OpCompositeConstruct %176 %25 %25 %25 +%418 = OpINotEqual %104 %416 %417 +%419 = OpCompositeConstruct %26 %14 %14 %14 %14 +%420 = OpCompositeConstruct %26 %3 %3 %3 %3 +%421 = OpFOrdNotEqual %28 %419 %420 +%422 = OpSLessThan %10 %18 %7 +%423 = OpULessThan %10 %24 %25 +%424 = OpFOrdLessThan %10 %14 %3 +%425 = OpCompositeConstruct %165 %18 %18 +%426 = OpCompositeConstruct %165 %7 %7 +%427 = OpSLessThan %149 %425 %426 +%428 = OpCompositeConstruct %176 %24 %24 %24 +%429 = OpCompositeConstruct %176 %25 %25 %25 +%430 = OpULessThan %104 %428 %429 +%431 = OpCompositeConstruct %26 %14 %14 %14 %14 +%432 = OpCompositeConstruct %26 %3 %3 %3 %3 +%433 = OpFOrdLessThan %28 %431 %432 +%434 = OpSLessThanEqual %10 %18 %7 +%435 = OpULessThanEqual %10 %24 %25 +%436 = OpFOrdLessThanEqual %10 %14 %3 +%437 = OpCompositeConstruct %165 %18 %18 +%438 = OpCompositeConstruct %165 %7 %7 +%439 = OpSLessThanEqual %149 %437 %438 +%440 = OpCompositeConstruct %176 %24 %24 %24 +%441 = OpCompositeConstruct %176 %25 %25 %25 +%442 = OpULessThanEqual %104 %440 %441 +%443 = OpCompositeConstruct %26 %14 %14 %14 %14 +%444 = OpCompositeConstruct %26 %3 %3 %3 %3 +%445 = OpFOrdLessThanEqual %28 %443 %444 +%446 = OpSGreaterThan %10 %18 %7 +%447 = OpUGreaterThan %10 %24 %25 +%448 = OpFOrdGreaterThan %10 %14 %3 +%449 = OpCompositeConstruct %165 %18 %18 +%450 = OpCompositeConstruct %165 %7 %7 +%451 = OpSGreaterThan %149 %449 %450 +%452 = OpCompositeConstruct %176 %24 %24 %24 +%453 = OpCompositeConstruct %176 %25 %25 %25 +%454 = OpUGreaterThan %104 %452 %453 +%455 = OpCompositeConstruct %26 %14 %14 %14 %14 +%456 = OpCompositeConstruct %26 %3 %3 %3 %3 +%457 = OpFOrdGreaterThan %28 %455 %456 +%458 = OpSGreaterThanEqual %10 %18 %7 +%459 = OpUGreaterThanEqual %10 %24 %25 +%460 = OpFOrdGreaterThanEqual %10 %14 %3 +%461 = OpCompositeConstruct %165 %18 %18 +%462 = OpCompositeConstruct %165 %7 %7 +%463 = OpSGreaterThanEqual %149 %461 %462 +%464 = OpCompositeConstruct %176 %24 %24 %24 +%465 = OpCompositeConstruct %176 %25 %25 %25 +%466 = OpUGreaterThanEqual %104 %464 %465 +%467 = OpCompositeConstruct %26 %14 %14 %14 %14 +%468 = OpCompositeConstruct %26 %3 %3 %3 %3 +%469 = OpFOrdGreaterThanEqual %28 %467 %468 OpReturn OpFunctionEnd -%473 = OpFunction %2 None %144 -%472 = OpLabel -%468 = OpVariable %469 Function %7 -%470 = OpVariable %471 Function %57 -OpBranch %474 +%475 = OpFunction %2 None %146 %474 = OpLabel -%475 = OpLoad %8 %468 -%476 = OpIAdd %8 %475 %7 -OpStore %468 %476 -%477 = OpLoad %8 %468 -%478 = OpISub %8 %477 %7 -OpStore %468 %478 -%479 = OpLoad %8 %468 -%480 = OpLoad %8 %468 -%481 = OpIMul %8 %479 %480 -OpStore %468 %481 -%482 = OpLoad %8 %468 -%483 = OpLoad %8 %468 -%484 = OpSDiv %8 %482 %483 -OpStore %468 %484 -%485 = OpLoad %8 %468 -%486 = OpSRem %8 %485 %7 -OpStore %468 %486 -%487 = OpLoad %8 %468 -%488 = OpBitwiseAnd %8 %487 %11 -OpStore %468 %488 -%489 = OpLoad %8 %468 -%490 = OpBitwiseOr %8 %489 %11 -OpStore %468 %490 -%491 = OpLoad %8 %468 -%492 = OpBitwiseXor %8 %491 %11 -OpStore %468 %492 -%493 = OpLoad %8 %468 -%494 = OpShiftLeftLogical %8 %493 %24 -OpStore %468 %494 -%495 = OpLoad %8 %468 -%496 = OpShiftRightArithmetic %8 %495 %25 -OpStore %468 %496 -%497 = OpLoad %8 %468 -%498 = OpIAdd %8 %497 %7 -OpStore %468 %498 -%499 = OpLoad %8 %468 -%500 = OpISub %8 %499 %7 -OpStore %468 %500 -%502 = OpAccessChain %501 %470 %25 -%503 = OpLoad %8 %502 -%504 = OpIAdd %8 %503 %7 -%505 = OpAccessChain %501 %470 %25 -OpStore %505 %504 -%506 = OpAccessChain %501 %470 %25 -%507 = OpLoad %8 %506 -%508 = OpISub %8 %507 %7 -%509 = OpAccessChain %501 %470 %25 -OpStore %509 %508 +%470 = OpVariable %471 Function %7 +%472 = OpVariable %473 Function %57 +OpBranch %476 +%476 = OpLabel +%477 = OpLoad %8 %470 +%478 = OpIAdd %8 %477 %7 +OpStore %470 %478 +%479 = OpLoad %8 %470 +%480 = OpISub %8 %479 %7 +OpStore %470 %480 +%481 = OpLoad %8 %470 +%482 = OpLoad %8 %470 +%483 = OpIMul %8 %481 %482 +OpStore %470 %483 +%484 = OpLoad %8 %470 +%485 = OpLoad %8 %470 +%486 = OpSDiv %8 %484 %485 +OpStore %470 %486 +%487 = OpLoad %8 %470 +%488 = OpSRem %8 %487 %7 +OpStore %470 %488 +%489 = OpLoad %8 %470 +%490 = OpBitwiseAnd %8 %489 %11 +OpStore %470 %490 +%491 = OpLoad %8 %470 +%492 = OpBitwiseOr %8 %491 %11 +OpStore %470 %492 +%493 = OpLoad %8 %470 +%494 = OpBitwiseXor %8 %493 %11 +OpStore %470 %494 +%495 = OpLoad %8 %470 +%496 = OpShiftLeftLogical %8 %495 %24 +OpStore %470 %496 +%497 = OpLoad %8 %470 +%498 = OpShiftRightArithmetic %8 %497 %25 +OpStore %470 %498 +%499 = OpLoad %8 %470 +%500 = OpIAdd %8 %499 %7 +OpStore %470 %500 +%501 = OpLoad %8 %470 +%502 = OpISub %8 %501 %7 +OpStore %470 %502 +%504 = OpAccessChain %503 %472 %25 +%505 = OpLoad %8 %504 +%506 = OpIAdd %8 %505 %7 +%507 = OpAccessChain %503 %472 %25 +OpStore %507 %506 +%508 = OpAccessChain %503 %472 %25 +%509 = OpLoad %8 %508 +%510 = OpISub %8 %509 %7 +%511 = OpAccessChain %503 %472 %25 +OpStore %511 %510 OpReturn OpFunctionEnd -%511 = OpFunction %2 None %144 -%510 = OpLabel -OpBranch %512 +%513 = OpFunction %2 None %146 %512 = OpLabel -%513 = OpFunctionCall %26 %59 -%514 = OpFunctionCall %26 %84 -%515 = OpVectorShuffle %29 %42 %42 0 1 2 -%516 = OpFunctionCall %29 %101 %515 -%517 = OpFunctionCall %4 %114 -%518 = OpFunctionCall %2 %143 -%519 = OpFunctionCall %2 %161 -%520 = OpFunctionCall %2 %345 -%521 = OpFunctionCall %2 %394 -%522 = OpFunctionCall %2 %473 +OpBranch %514 +%514 = OpLabel +%515 = OpFunctionCall %26 %59 +%516 = OpFunctionCall %26 %84 +%517 = OpVectorShuffle %29 %42 %42 0 1 2 +%518 = OpFunctionCall %29 %101 %517 +%519 = OpFunctionCall %4 %114 +%520 = OpFunctionCall %2 %145 +%521 = OpFunctionCall %2 %163 +%522 = OpFunctionCall %2 %347 +%523 = OpFunctionCall %2 %396 +%524 = OpFunctionCall %2 %475 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 172a39109..2aa21785e 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -45,8 +45,10 @@ fn constructors() -> f32 { _ = f32(0.0); _ = vec2(vec2(0u, 0u)); _ = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let _e71 = foo.a.x; - return _e71; + _ = bitcast>(vec2(0u, 0u)); + _ = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + let _e75 = foo.a.x; + return _e75; } fn logical() { From 5f47d6d31f64a16c76b16dad8fb4b72e5ce8815a Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 12 May 2022 16:39:12 +0200 Subject: [PATCH 1750/2212] [msl-out] use matrix identity constructor --- src/back/msl/writer.rs | 70 +++++++++++++++++++++---------------- tests/out/msl/operators.msl | 4 +-- 2 files changed, 41 insertions(+), 33 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 07f83c86e..8294626a8 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1741,37 +1741,45 @@ impl Writer { expr, kind, convert, - } => { - let (src_kind, src_width) = match *context.resolve_type(expr) { - crate::TypeInner::Scalar { kind, width } - | crate::TypeInner::Vector { kind, width, .. } => (kind, width), - crate::TypeInner::Matrix { width, .. } => (crate::ScalarKind::Float, width), - _ => return Err(Error::Validation), - }; - let is_bool_cast = - kind == crate::ScalarKind::Bool || src_kind == crate::ScalarKind::Bool; - let op = match convert { - Some(w) if w == src_width || is_bool_cast => "static_cast", - Some(8) if kind == crate::ScalarKind::Float => { - return Err(Error::CapabilityNotSupported(valid::Capabilities::FLOAT64)) - } - Some(_) => return Err(Error::Validation), - None => "as_type", - }; - write!(self.out, "{}<", op)?; - match *context.resolve_type(expr) { - crate::TypeInner::Matrix { columns, rows, .. } => { - put_numeric_type(&mut self.out, kind, &[rows, columns])? - } - crate::TypeInner::Vector { size, .. } => { - put_numeric_type(&mut self.out, kind, &[size])? - } - _ => put_numeric_type(&mut self.out, kind, &[])?, - }; - write!(self.out, ">(")?; - self.put_expression(expr, context, true)?; - write!(self.out, ")")?; - } + } => match *context.resolve_type(expr) { + crate::TypeInner::Scalar { + kind: src_kind, + width: src_width, + } + | crate::TypeInner::Vector { + kind: src_kind, + width: src_width, + .. + } => { + let is_bool_cast = + kind == crate::ScalarKind::Bool || src_kind == crate::ScalarKind::Bool; + let op = match convert { + Some(w) if w == src_width || is_bool_cast => "static_cast", + Some(8) if kind == crate::ScalarKind::Float => { + return Err(Error::CapabilityNotSupported(valid::Capabilities::FLOAT64)) + } + Some(_) => return Err(Error::Validation), + None => "as_type", + }; + write!(self.out, "{}<", op)?; + match *context.resolve_type(expr) { + crate::TypeInner::Vector { size, .. } => { + put_numeric_type(&mut self.out, kind, &[size])? + } + _ => put_numeric_type(&mut self.out, kind, &[])?, + }; + write!(self.out, ">(")?; + self.put_expression(expr, context, true)?; + write!(self.out, ")")?; + } + crate::TypeInner::Matrix { columns, rows, .. } => { + put_numeric_type(&mut self.out, kind, &[rows, columns])?; + write!(self.out, "(")?; + self.put_expression(expr, context, true)?; + write!(self.out, ")")?; + } + _ => return Err(Error::Validation), + }, // has to be a named expression crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } => { unreachable!() diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index d3665d35a..294fa5812 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -72,9 +72,9 @@ float constructors( uint unnamed_5 = static_cast(0u); float unnamed_6 = static_cast(0.0); metal::uint2 unnamed_7 = static_cast(const_type_11_); - metal::float2x3 unnamed_8 = static_cast(const_type_14_); + metal::float2x3 unnamed_8 = metal::float2x3(const_type_14_); metal::uint2 unnamed_9 = as_type(const_type_11_); - metal::float2x3 unnamed_10 = as_type(const_type_14_); + metal::float2x3 unnamed_10 = metal::float2x3(const_type_14_); float _e75 = foo.a.x; return _e75; } From ab2806e05fbd69a502b4b25a85f99ae4d3e82278 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 12 May 2022 12:07:39 +0200 Subject: [PATCH 1751/2212] [hlsl-out] fix array constructor return type (for FXC) --- src/back/hlsl/help.rs | 18 +++++++++++++----- tests/out/hlsl/access.hlsl | 12 ++++++++---- tests/out/hlsl/operators.hlsl | 6 ++++-- tests/out/hlsl/quad-vert.hlsl | 3 ++- 4 files changed, 27 insertions(+), 12 deletions(-) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index e79b5aceb..d71675f6a 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -375,7 +375,19 @@ impl<'a, W: Write> super::Writer<'a, W> { const RETURN_VARIABLE_NAME: &str = "ret"; // Write function return type and name - self.write_type(module, constructor.ty)?; + if let crate::TypeInner::Array { base, size, .. } = module.types[constructor.ty].inner { + write!(self.out, "typedef ")?; + self.write_type(module, constructor.ty)?; + write!(self.out, " ret_")?; + self.write_wrapped_constructor_function_name(module, constructor)?; + self.write_array_size(module, base, size)?; + writeln!(self.out, ";")?; + + write!(self.out, "ret_")?; + self.write_wrapped_constructor_function_name(module, constructor)?; + } else { + self.write_type(module, constructor.ty)?; + } write!(self.out, " ")?; self.write_wrapped_constructor_function_name(module, constructor)?; @@ -415,10 +427,6 @@ impl<'a, W: Write> super::Writer<'a, W> { write!(self.out, ")")?; - if let crate::TypeInner::Array { base, size, .. } = module.types[constructor.ty].inner { - self.write_array_size(module, base, size)?; - } - // Write function body writeln!(self.out, " {{")?; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 3b76080d4..d6a9736a8 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -8,12 +8,14 @@ struct Baz { float2 m_0; float2 m_1; float2 m_2; }; -float Constructarray10_float_(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5, float arg6, float arg7, float arg8, float arg9)[10] { +typedef float ret_Constructarray10_float_[10]; +ret_Constructarray10_float_ Constructarray10_float_(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5, float arg6, float arg7, float arg8, float arg9) { float ret[10] = { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 }; return ret; } -float Constructarray5_array10_float__(float arg0[10], float arg1[10], float arg2[10], float arg3[10], float arg4[10])[5][10] { +typedef float ret_Constructarray5_array10_float__[5][10]; +ret_Constructarray5_array10_float__ Constructarray5_array10_float__(float arg0[10], float arg1[10], float arg2[10], float arg3[10], float arg4[10]) { float ret[5][10] = { arg0, arg1, arg2, arg3, arg4 }; return ret; } @@ -118,7 +120,8 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer) return ret; } -int Constructarray5_int_(int arg0, int arg1, int arg2, int arg3, int arg4)[5] { +typedef int ret_Constructarray5_int_[5]; +ret_Constructarray5_int_ Constructarray5_int_(int arg0, int arg1, int arg2, int arg3, int arg4) { int ret[5] = { arg0, arg1, arg2, arg3, arg4 }; return ret; } @@ -147,7 +150,8 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position return float4(mul(float4((value).xxxx), _matrix), 2.0); } -uint2 Constructarray2_uint2_(uint2 arg0, uint2 arg1)[2] { +typedef uint2 ret_Constructarray2_uint2_[2]; +ret_Constructarray2_uint2_ Constructarray2_uint2_(uint2 arg0, uint2 arg1) { uint2 ret[2] = { arg0, arg1 }; return ret; } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index e1e0335f8..01ffb9036 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -18,7 +18,8 @@ Foo ConstructFoo(float4 arg0, int arg1) { return ret; } -Foo Constructarray3_Foo_(Foo arg0, Foo arg1, Foo arg2)[3] { +typedef Foo ret_Constructarray3_Foo_[3]; +ret_Constructarray3_Foo_ Constructarray3_Foo_(Foo arg0, Foo arg1, Foo arg2) { Foo ret[3] = { arg0, arg1, arg2 }; return ret; } @@ -49,7 +50,8 @@ float3 bool_cast(float3 x) return float3(y); } -int Constructarray4_int_(int arg0, int arg1, int arg2, int arg3)[4] { +typedef int ret_Constructarray4_int_[4]; +ret_Constructarray4_int_ Constructarray4_int_(int arg0, int arg1, int arg2, int arg3) { int ret[4] = { arg0, arg1, arg2, arg3 }; return ret; } diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 890356040..a6c7a23b8 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -11,7 +11,8 @@ struct type_9 { float4 gl_Position : SV_Position; }; -float Constructarray1_float_(float arg0)[1] { +typedef float ret_Constructarray1_float_[1]; +ret_Constructarray1_float_ Constructarray1_float_(float arg0) { float ret[1] = { arg0 }; return ret; } From 60ae549fe1bec8df40518a6164d723d41a2b76b5 Mon Sep 17 00:00:00 2001 From: grovesNL Date: Sat, 14 May 2022 00:19:23 -0230 Subject: [PATCH 1752/2212] Add error for non-floating-point matrix --- src/front/wgsl/construction.rs | 15 ++-- src/front/wgsl/mod.rs | 128 ++++++++++++++++----------------- tests/wgsl-errors.rs | 33 +++++++++ 3 files changed, 103 insertions(+), 73 deletions(-) diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/construction.rs index f675b12e1..ca43894e2 100644 --- a/src/front/wgsl/construction.rs +++ b/src/front/wgsl/construction.rs @@ -184,12 +184,15 @@ fn parse_constructor_type<'a>( Ok(Some(ConstructorType::Vector { size, kind, width })) } (Token::Paren('<'), ConstructorType::PartialMatrix { columns, rows }) => { - let (_, width) = lexer.next_scalar_generic()?; - Ok(Some(ConstructorType::Matrix { - columns, - rows, - width, - })) + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + match kind { + ScalarKind::Float => Ok(Some(ConstructorType::Matrix { + columns, + rows, + width, + })), + _ => Err(Error::BadMatrixScalarKind(span, kind, width)), + } } (Token::Paren('<'), ConstructorType::PartialArray) => { lexer.expect_generic_paren('<')?; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 04f115fbe..7379b51fd 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -130,6 +130,7 @@ pub enum Error<'a> { BadFloat(Span, BadFloatError), BadU32Constant(Span), BadScalarWidth(Span, Bytes), + BadMatrixScalarKind(Span, crate::ScalarKind, u8), BadAccessor(Span), BadTexture(Span), BadTypeCast { @@ -296,12 +297,20 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "expected unsigned integer".into())], notes: vec![], }, - Error::BadScalarWidth(ref bad_span, width) => ParseError { message: format!("invalid width of `{}` bits for literal", width as u32 * 8,), labels: vec![(bad_span.clone(), "invalid width".into())], notes: vec!["the only valid width is 32 for now".to_string()], }, + Error::BadMatrixScalarKind( + ref span, + kind, + width, + ) => ParseError { + message: format!("matrix scalar type must be floating-point, but found `{}`", kind.to_wgsl(width)), + labels: vec![(span.clone(), "must be floating-point (e.g. `f32`)".into())], + notes: vec![], + }, Error::BadAccessor(ref accessor_span) => ParseError { message: format!( "invalid field accessor `{}`", @@ -2901,6 +2910,23 @@ impl Parser { Ok((members, span)) } + fn parse_matrix_scalar_type<'a>( + &mut self, + lexer: &mut Lexer<'a>, + columns: crate::VectorSize, + rows: crate::VectorSize, + ) -> Result> { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + match kind { + crate::ScalarKind::Float => Ok(crate::TypeInner::Matrix { + columns, + rows, + width, + }), + _ => Err(Error::BadMatrixScalarKind(span, kind, width)), + } + } + fn parse_type_decl_impl<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -2912,6 +2938,7 @@ impl Parser { if let Some((kind, width)) = conv::get_scalar_type(word) { return Ok(Some(crate::TypeInner::Scalar { kind, width })); } + Ok(Some(match word { "vec2" => { let (kind, width) = lexer.next_scalar_generic()?; @@ -2938,77 +2965,44 @@ impl Parser { } } "mat2x2" => { - let (_, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Matrix { - columns: crate::VectorSize::Bi, - rows: crate::VectorSize::Bi, - width, - } + self.parse_matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Bi)? } "mat2x3" => { - let (_, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Matrix { - columns: crate::VectorSize::Bi, - rows: crate::VectorSize::Tri, - width, - } - } - "mat2x4" => { - let (_, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Matrix { - columns: crate::VectorSize::Bi, - rows: crate::VectorSize::Quad, - width, - } + self.parse_matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Tri)? } + "mat2x4" => self.parse_matrix_scalar_type( + lexer, + crate::VectorSize::Bi, + crate::VectorSize::Quad, + )?, "mat3x2" => { - let (_, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Matrix { - columns: crate::VectorSize::Tri, - rows: crate::VectorSize::Bi, - width, - } - } - "mat3x3" => { - let (_, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Matrix { - columns: crate::VectorSize::Tri, - rows: crate::VectorSize::Tri, - width, - } - } - "mat3x4" => { - let (_, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Matrix { - columns: crate::VectorSize::Tri, - rows: crate::VectorSize::Quad, - width, - } - } - "mat4x2" => { - let (_, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Matrix { - columns: crate::VectorSize::Quad, - rows: crate::VectorSize::Bi, - width, - } - } - "mat4x3" => { - let (_, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Matrix { - columns: crate::VectorSize::Quad, - rows: crate::VectorSize::Tri, - width, - } - } - "mat4x4" => { - let (_, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Matrix { - columns: crate::VectorSize::Quad, - rows: crate::VectorSize::Quad, - width, - } + self.parse_matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Bi)? } + "mat3x3" => self.parse_matrix_scalar_type( + lexer, + crate::VectorSize::Tri, + crate::VectorSize::Tri, + )?, + "mat3x4" => self.parse_matrix_scalar_type( + lexer, + crate::VectorSize::Tri, + crate::VectorSize::Quad, + )?, + "mat4x2" => self.parse_matrix_scalar_type( + lexer, + crate::VectorSize::Quad, + crate::VectorSize::Bi, + )?, + "mat4x3" => self.parse_matrix_scalar_type( + lexer, + crate::VectorSize::Quad, + crate::VectorSize::Tri, + )?, + "mat4x4" => self.parse_matrix_scalar_type( + lexer, + crate::VectorSize::Quad, + crate::VectorSize::Quad, + )?, "atomic" => { let (kind, width) = lexer.next_scalar_generic()?; crate::TypeInner::Atomic { kind, width } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index bd733d946..db7da613c 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -810,6 +810,39 @@ fn module_scope_identifier_redefinition() { ); } +#[test] +fn matrix_with_bad_type() { + check( + r#" + fn main() { + let m = mat2x2(); + } + "#, + r#"error: matrix scalar type must be floating-point, but found `i32` + ┌─ wgsl:3:32 + │ +3 │ let m = mat2x2(); + │ ^^^ must be floating-point (e.g. `f32`) + +"#, + ); + + check( + r#" + fn main() { + let m: mat3x3; + } + "#, + r#"error: matrix scalar type must be floating-point, but found `i32` + ┌─ wgsl:3:31 + │ +3 │ let m: mat3x3; + │ ^^^ must be floating-point (e.g. `f32`) + +"#, + ); +} + /// Check the result of validating a WGSL program against a pattern. /// /// Unless you are generating code programmatically, the From 571302e3ff09cb856f63a3683da308159872b7cc Mon Sep 17 00:00:00 2001 From: Hasan Ali Date: Mon, 16 May 2022 19:57:21 +0100 Subject: [PATCH 1753/2212] [hlsl-out] Fix countOneBits and reverseBits for signed integers --- src/back/hlsl/writer.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 9a7e84b44..e713c2f5d 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -6,7 +6,7 @@ use super::{ use crate::{ back, proc::{self, NameKey}, - valid, Handle, Module, ShaderStage, TypeInner, + valid, Handle, Module, ScalarKind, ShaderStage, TypeInner, }; use std::{fmt, mem}; @@ -2190,6 +2190,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Asincosh { is_sin: bool }, Atanh, Regular(&'static str), + MissingIntOverload(&'static str), } let fun = match fun { @@ -2251,8 +2252,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::Transpose => Function::Regular("transpose"), Mf::Determinant => Function::Regular("determinant"), // bits - Mf::CountOneBits => Function::Regular("countbits"), - Mf::ReverseBits => Function::Regular("reversebits"), + Mf::CountOneBits => Function::MissingIntOverload("countbits"), + Mf::ReverseBits => Function::MissingIntOverload("reversebits"), Mf::FindLsb => Function::Regular("firstbitlow"), Mf::FindMsb => Function::Regular("firstbithigh"), _ => return Err(Error::Unimplemented(format!("write_expr_math {:?}", fun))), @@ -2295,6 +2296,21 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } write!(self.out, ")")? } + Function::MissingIntOverload(fun_name) => { + let scalar_kind = &func_ctx.info[arg] + .ty + .inner_with(&module.types) + .scalar_kind(); + if let Some(ScalarKind::Sint) = *scalar_kind { + write!(self.out, "asint({}(asuint(", fun_name)?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ")))")?; + } else { + write!(self.out, "{}(", fun_name)?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ")")?; + } + } } } Expression::Swizzle { From fea733f58e5360e6ab5d124e504137261a87a51e Mon Sep 17 00:00:00 2001 From: Ashley Ruglys Date: Fri, 20 May 2022 21:07:30 +0200 Subject: [PATCH 1754/2212] Add MultiView to SUPPORTED_CAPABILITIES --- src/front/spv/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index cf4f50d1d..7e560cfc4 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -71,6 +71,7 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Float16, spirv::Capability::Float64, spirv::Capability::Geometry, + spirv::Capability::MultiView, // tricky ones spirv::Capability::UniformBufferArrayDynamicIndexing, spirv::Capability::StorageBufferArrayDynamicIndexing, From 196c9981bc41320d3169bcf6e3200cbbf6bc0e10 Mon Sep 17 00:00:00 2001 From: Ashley Ruglys Date: Fri, 20 May 2022 21:11:39 +0200 Subject: [PATCH 1755/2212] Run cargo fmt --- src/front/wgsl/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7379b51fd..94c3510d7 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1193,8 +1193,8 @@ impl Composition { #[derive(Default)] struct TypeAttributes { // Although WGSL nas no type attributes at the moment, it had them in the past -// (`[[stride]]`) and may as well acquire some again in the future. -// Therefore, we are leaving the plumbing in for now. + // (`[[stride]]`) and may as well acquire some again in the future. + // Therefore, we are leaving the plumbing in for now. } #[derive(Clone, Debug, PartialEq)] From 104f4dc7ecae8e1f44811a5fca7bcf9413efdb11 Mon Sep 17 00:00:00 2001 From: Ashley Ruglys Date: Fri, 20 May 2022 21:26:34 +0200 Subject: [PATCH 1756/2212] Fix a broken clippy lint --- src/back/msl/writer.rs | 2 ++ src/back/wgsl/writer.rs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 8294626a8..1d63a0753 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -647,6 +647,8 @@ impl Writer { } /// Finishes writing and returns the output. + // See https://github.com/rust-lang/rust-clippy/issues/4979. + #[allow(clippy::missing_const_for_fn)] pub fn finish(self) -> W { self.out } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 487ea40d8..77ab496cb 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1859,6 +1859,8 @@ impl Writer { Ok(()) } + // See https://github.com/rust-lang/rust-clippy/issues/4979. + #[allow(clippy::missing_const_for_fn)] pub fn finish(self) -> W { self.out } From 62da3bf348463a6f1de5f3419fe949075afc9c77 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sat, 14 May 2022 16:23:10 +0200 Subject: [PATCH 1757/2212] add HLSL validation via FXC to CI --- .github/workflows/validation-windows.yml | 22 +++++++++++-- Makefile | 42 +++++++++++++++++++++--- README.md | 4 ++- 3 files changed, 60 insertions(+), 8 deletions(-) diff --git a/.github/workflows/validation-windows.yml b/.github/workflows/validation-windows.yml index c9bd5ae1f..31f7ee368 100644 --- a/.github/workflows/validation-windows.yml +++ b/.github/workflows/validation-windows.yml @@ -5,12 +5,28 @@ on: - 'tests/out/hlsl/*.hlsl' jobs: - validate-windows: - name: HLSL + validate-windows-dxc: + name: HLSL via DXC runs-on: windows-latest steps: - uses: actions/checkout@v2 - name: Add DirectXShaderCompiler uses: napokue/setup-dxc@v1.0.0 - - run: make validate-hlsl + - run: make validate-hlsl-dxc shell: sh + + validate-windows-fxc: + name: HLSL via FXC + runs-on: windows-latest + steps: + - uses: actions/checkout@v2 + - name: Add fxc bin to PATH + run: | + Get-Childitem -Path "C:\Program Files (x86)\Windows Kits\10\bin\**\x64\fxc.exe" ` + | Sort-Object -Property LastWriteTime -Descending ` + | Select-Object -First 1 ` + | Split-Path -Parent ` + | Out-File -FilePath $Env:GITHUB_PATH -Encoding utf8 -Append + shell: powershell + - run: make validate-hlsl-fxc + shell: sh \ No newline at end of file diff --git a/Makefile b/Makefile index 4622fdbb5..a491722af 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all clean validate-spv validate-msl validate-glsl validate-dot validate-wgsl validate-hlsl +.PHONY: all clean validate-spv validate-msl validate-glsl validate-dot validate-wgsl validate-hlsl-dxc validate-hlsl-fxc .SECONDARY: boids.metal quad.metal SNAPSHOTS_BASE_IN=tests/in SNAPSHOTS_BASE_OUT=tests/out @@ -69,10 +69,10 @@ validate-wgsl: $(SNAPSHOTS_BASE_OUT)/wgsl/*.wgsl cargo run $${file}; \ done -validate-hlsl: SHELL:=/bin/bash # required because config files uses arrays -validate-hlsl: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl +validate-hlsl-dxc: SHELL:=/bin/bash # required because config files uses arrays +validate-hlsl-dxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl @set -e && for file in $^ ; do \ - DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug"; \ + DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug -Od"; \ echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ config="$$(dirname $${file})/$$(basename $${file}).config"; \ . $${config}; \ @@ -93,3 +93,37 @@ validate-hlsl: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl done; \ echo "======================"; \ done + +validate-hlsl-fxc: SHELL:=/bin/bash # required because config files uses arrays +validate-hlsl-fxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl + @set -e && for file in $^ ; do \ + FXC_PARAMS="-Zi -Od"; \ + echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ + config="$$(dirname $${file})/$$(basename $${file}).config"; \ + . $${config}; \ + for (( i=0; i<$${#vertex[@]}; i++ )); do \ + name=`echo $${vertex[i]} | cut -d \: -f 1`; \ + profile=`echo $${vertex[i]} | cut -d \: -f 2`; \ + sm=`echo $${profile} | cut -d \_ -f 2`; \ + if (( sm < 6 )); then \ + (set -x; fxc $${file} -T $${profile} -E $${name} $${FXC_PARAMS} > /dev/null); \ + fi \ + done; \ + for (( i=0; i<$${#fragment[@]}; i++ )); do \ + name=`echo $${fragment[i]} | cut -d \: -f 1`; \ + profile=`echo $${fragment[i]} | cut -d \: -f 2`; \ + sm=`echo $${profile} | cut -d \_ -f 2`; \ + if (( sm < 6 )); then \ + (set -x; fxc $${file} -T $${profile} -E $${name} $${FXC_PARAMS} > /dev/null); \ + fi \ + done; \ + for (( i=0; i<$${#compute[@]}; i++ )); do \ + name=`echo $${compute[i]} | cut -d \: -f 1`; \ + profile=`echo $${compute[i]} | cut -d \: -f 2`; \ + sm=`echo $${profile} | cut -d \_ -f 2`; \ + if (( sm < 6 )); then \ + (set -x; fxc $${file} -T $${profile} -E $${name} $${FXC_PARAMS} > /dev/null); \ + fi \ + done; \ + echo "======================"; \ + done diff --git a/README.md b/README.md index fbaa063d7..762822a11 100644 --- a/README.md +++ b/README.md @@ -81,5 +81,7 @@ make validate-msl # for Metal shaders, requires XCode command-line tools install make validate-glsl # for OpenGL shaders, requires GLSLang installed make validate-dot # for dot files, requires GraphViz installed make validate-wgsl # for WGSL shaders -make validate-hlsl # for HLSL shaders. Note: this Make target makes use of the "sh" shell. This is not the default shell in Windows. +make validate-hlsl-dxc # for HLSL shaders via DXC +make validate-hlsl-fxc # for HLSL shaders via FXC +# Note: HLSL Make targets make use of the "sh" shell. This is not the default shell in Windows. ``` From f9dfc38c405be4b97bb2647a7a407c2171c9ba12 Mon Sep 17 00:00:00 2001 From: Nicolas Silva Date: Fri, 20 May 2022 19:01:16 +0200 Subject: [PATCH 1758/2212] Add a helper for getting the location of a span in some textual source. --- src/front/wgsl/mod.rs | 18 ++--- src/lib.rs | 2 +- src/span.rs | 150 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 157 insertions(+), 13 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 94c3510d7..76a61e98e 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -16,6 +16,7 @@ use crate::{ proc::{ ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution, }, + span::SourceLocation, span::Span as NagaSpan, Bytes, ConstantInner, FastHashMap, ScalarValue, }; @@ -29,7 +30,7 @@ use self::{ }; use codespan_reporting::{ diagnostic::{Diagnostic, Label}, - files::{Files, SimpleFile}, + files::SimpleFile, term::{ self, termcolor::{ColorChoice, ColorSpec, StandardStream, WriteColor}, @@ -1367,17 +1368,10 @@ impl ParseError { /// Returns the 1-based line number and column of the first label in the /// error message. - pub fn location(&self, source: &str) -> (usize, usize) { - let files = SimpleFile::new("wgsl", source); - match self.labels.get(0) { - Some(label) => { - let location = files - .location((), label.0.start) - .expect("invalid span location"); - (location.line_number, location.column_number) - } - None => (1, 1), - } + pub fn location(&self, source: &str) -> Option { + self.labels + .get(0) + .map(|label| NagaSpan::new(label.0.start as u32, label.0.end as u32).location(source)) } } diff --git a/src/lib.rs b/src/lib.rs index 80e7e6f78..60bbe0e28 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -211,7 +211,7 @@ pub mod valid; pub use crate::arena::{Arena, Handle, Range, UniqueArena}; -pub use crate::span::{Span, SpanContext, WithSpan}; +pub use crate::span::{SourceLocation, Span, SpanContext, WithSpan}; #[cfg(feature = "arbitrary")] use arbitrary::Arbitrary; #[cfg(feature = "deserialize")] diff --git a/src/span.rs b/src/span.rs index 0c60ee005..1c2249c4a 100644 --- a/src/span.rs +++ b/src/span.rs @@ -59,6 +59,22 @@ impl Span { pub fn is_defined(&self) -> bool { *self != Self::default() } + + /// Returns the 1-based line number and column of the this span in + /// the provided source. + pub fn location(&self, source: &str) -> SourceLocation { + let prefix = &source[..self.start as usize]; + let line_number = prefix.matches('\n').count() as u32 + 1; + let line_start = prefix.rfind('\n').map(|pos| pos + 1).unwrap_or(0); + let line_position = source[line_start..self.start as usize].chars().count() as u32 + 1; + + SourceLocation { + line_number, + line_position, + offset: self.start, + length: self.end - self.start, + } + } } impl From> for Span { @@ -70,6 +86,22 @@ impl From> for Span { } } +/// A human-readable representation for span, tailored for text source. +/// +/// Corresponds to the positional members of `GPUCompilationMessage` from the WebGPU specification, +/// using utf8 instead of utf16 as reference encoding. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct SourceLocation { + /// 1-based line number. + pub line_number: u32, + /// 1-based column of the start of this span + pub line_position: u32, + /// 0-based Offset in code units (in bytes) of the start of the span. + pub offset: u32, + /// Length in code units (in bytes) of the span. + pub length: u32, +} + /// A source code span together with "context", a user-readable description of what part of the error it refers to. pub type SpanContext = (Span, String); @@ -186,6 +218,20 @@ impl WithSpan { res.spans.extend(self.spans); res } + + #[cfg(feature = "span")] + pub fn location(&self, source: &str) -> Option { + if self.spans.is_empty() { + return None; + } + + Some(self.spans[0].0.location(source)) + } + + #[cfg(not(feature = "span"))] + pub fn location(&self, _source: &str) -> Option { + None + } } /// Convenience trait for [`Error`] to be able to apply spans to anything. @@ -273,3 +319,107 @@ impl MapErrWithSpan for Result> { self.map_err(|e| e.and_then(func).into_other::()) } } + +#[test] +fn span_location() { + let source = "12\n45\n\n89\n"; + assert_eq!( + Span { start: 0, end: 1 }.location(source), + SourceLocation { + line_number: 1, + line_position: 1, + offset: 0, + length: 1 + } + ); + assert_eq!( + Span { start: 1, end: 2 }.location(source), + SourceLocation { + line_number: 1, + line_position: 2, + offset: 1, + length: 1 + } + ); + assert_eq!( + Span { start: 2, end: 3 }.location(source), + SourceLocation { + line_number: 1, + line_position: 3, + offset: 2, + length: 1 + } + ); + assert_eq!( + Span { start: 3, end: 5 }.location(source), + SourceLocation { + line_number: 2, + line_position: 1, + offset: 3, + length: 2 + } + ); + assert_eq!( + Span { start: 4, end: 6 }.location(source), + SourceLocation { + line_number: 2, + line_position: 2, + offset: 4, + length: 2 + } + ); + assert_eq!( + Span { start: 5, end: 6 }.location(source), + SourceLocation { + line_number: 2, + line_position: 3, + offset: 5, + length: 1 + } + ); + assert_eq!( + Span { start: 6, end: 7 }.location(source), + SourceLocation { + line_number: 3, + line_position: 1, + offset: 6, + length: 1 + } + ); + assert_eq!( + Span { start: 7, end: 8 }.location(source), + SourceLocation { + line_number: 4, + line_position: 1, + offset: 7, + length: 1 + } + ); + assert_eq!( + Span { start: 8, end: 9 }.location(source), + SourceLocation { + line_number: 4, + line_position: 2, + offset: 8, + length: 1 + } + ); + assert_eq!( + Span { start: 9, end: 10 }.location(source), + SourceLocation { + line_number: 4, + line_position: 3, + offset: 9, + length: 1 + } + ); + assert_eq!( + Span { start: 10, end: 11 }.location(source), + SourceLocation { + line_number: 5, + line_position: 1, + offset: 10, + length: 1 + } + ); +} From f035854dac7faad6660719f4d6f6a9f3bf468ea3 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 25 May 2022 17:10:20 -0700 Subject: [PATCH 1759/2212] Doc tweaks. --- src/front/wgsl/mod.rs | 3 +-- src/span.rs | 14 +++++++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 76a61e98e..a7c1fdced 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1366,8 +1366,7 @@ impl ParseError { writer.into_string() } - /// Returns the 1-based line number and column of the first label in the - /// error message. + /// Returns a [`SourceLocation`] for the first label in the error message. pub fn location(&self, source: &str) -> Option { self.labels .get(0) diff --git a/src/span.rs b/src/span.rs index 1c2249c4a..6f2583a5e 100644 --- a/src/span.rs +++ b/src/span.rs @@ -60,8 +60,7 @@ impl Span { *self != Self::default() } - /// Returns the 1-based line number and column of the this span in - /// the provided source. + /// Return a [`SourceLocation`] for this span in the provided source. pub fn location(&self, source: &str) -> SourceLocation { let prefix = &source[..self.start as usize]; let line_number = prefix.matches('\n').count() as u32 + 1; @@ -86,10 +85,13 @@ impl From> for Span { } } -/// A human-readable representation for span, tailored for text source. +/// A human-readable representation for a span, tailored for text source. /// -/// Corresponds to the positional members of `GPUCompilationMessage` from the WebGPU specification, -/// using utf8 instead of utf16 as reference encoding. +/// Corresponds to the positional members of [`GPUCompilationMessage`][gcm] from +/// the WebGPU specification, except that `offset` and `length` are in bytes +/// (UTF-8 code units), instead of UTF-16 code units. +/// +/// [gcm]: https://www.w3.org/TR/webgpu/#gpucompilationmessage #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct SourceLocation { /// 1-based line number. @@ -220,6 +222,7 @@ impl WithSpan { } #[cfg(feature = "span")] + /// Return a [`SourceLocation`] for our first span, if we have one. pub fn location(&self, source: &str) -> Option { if self.spans.is_empty() { return None; @@ -229,6 +232,7 @@ impl WithSpan { } #[cfg(not(feature = "span"))] + /// Return a [`SourceLocation`] for our first span, if we have one. pub fn location(&self, _source: &str) -> Option { None } From 4cd997a3eb29a33eb4a318e0b1f16acc1b9924e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 28 May 2022 22:22:45 +0100 Subject: [PATCH 1760/2212] glsl-out: Fix storage format for Rgba8Unorm --- src/back/glsl/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5b7700ba9..abce4d4ab 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -3347,7 +3347,7 @@ const fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { Sf::Rg16Uint => "rg16ui", Sf::Rg16Sint => "rg16i", Sf::Rg16Float => "rg16f", - Sf::Rgba8Unorm => "rgba8ui", + Sf::Rgba8Unorm => "rgba8", Sf::Rgba8Snorm => "rgba8_snorm", Sf::Rgba8Uint => "rgba8ui", Sf::Rgba8Sint => "rgba8i", From c7e245c0833e76843dbf269f8217ced6b09906bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 30 May 2022 00:50:30 +0100 Subject: [PATCH 1761/2212] Update README for glsl-in (#1951) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 762822a11..1e407a959 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Front-end | Status | Feature | Notes | --------------- | ------------------ | ------- | ----- | SPIR-V (binary) | :white_check_mark: | spv-in | | WGSL | :white_check_mark: | wgsl-in | Fully validated | -GLSL | :ok: | glsl-in | GLSL 440+ | +GLSL | :ok: | glsl-in | GLSL 440+ and Vulkan semantics only | Back-end | Status | Feature | Notes | --------------- | ------------------ | -------- | ----- | From 0aa7681165f9ae74f2ddd109f4bdfa73a4e094cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 30 May 2022 20:13:58 +0100 Subject: [PATCH 1762/2212] glsl-out: Implement bounds checks for `ImageLoad` (#1889) * glsl-out: Implement bounds checks for `ImageLoad` * Enable image bounds check snapshot tests for GLSL. In addition to the snapshot.rs changes, this entails adding an entry point function to `bounds-check-image-restrict.wgsl` and `bounds-check-image-rzsw.wgsl`, including appropriate data in the param.ron files. * Apply comments Snapshot test changes: Co-authored-by: Jim Blandy --- cli/src/main.rs | 1 + src/back/glsl/features.rs | 83 +- src/back/glsl/mod.rs | 469 +++++++++-- .../in/bounds-check-image-restrict.param.ron | 5 + tests/in/bounds-check-image-restrict.wgsl | 43 +- tests/in/bounds-check-image-rzsw.param.ron | 5 + tests/in/bounds-check-image-rzsw.wgsl | 43 +- ...age-restrict.fragment_shader.Fragment.glsl | 86 ++ ...k-image-rzsw.fragment_shader.Fragment.glsl | 81 ++ tests/out/glsl/image.main.Compute.glsl | 4 +- tests/out/msl/bounds-check-image-restrict.msl | 29 + tests/out/msl/bounds-check-image-rzsw.msl | 29 + .../spv/bounds-check-image-restrict.spvasm | 667 ++++++++------- tests/out/spv/bounds-check-image-rzsw.spvasm | 777 +++++++++--------- tests/snapshots.rs | 30 +- 15 files changed, 1559 insertions(+), 793 deletions(-) create mode 100644 tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl create mode 100644 tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl diff --git a/cli/src/main.rs b/cli/src/main.rs index 2e4b1b3c3..707f95f06 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -455,6 +455,7 @@ fn run() -> Result<(), Box> { ))?, ¶ms.glsl, &pipeline_options, + params.bounds_check_policies, ) .unwrap_pretty(); writer.write()?; diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index d3f117045..82718b040 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -38,6 +38,10 @@ bitflags::bitflags! { const FMA = 1 << 18; /// Texture samples query const TEXTURE_SAMPLES = 1 << 19; + /// Texture levels query + const TEXTURE_LEVELS = 1 << 20; + /// Image size query + const IMAGE_SIZE = 1 << 21; } } @@ -104,9 +108,11 @@ impl FeaturesManager { check_feature!(DYNAMIC_ARRAY_SIZE, 430, 310); check_feature!(MULTI_VIEW, 140, 310); // Only available on glsl core, this means that opengl es can't query the number - // of samples in a image and neither do bound checks on the sample argument - // of texelFecth + // of samples nor levels in a image and neither do bound checks on the sample nor + // the level argument of texelFecth check_feature!(TEXTURE_SAMPLES, 150); + check_feature!(TEXTURE_LEVELS, 130); + check_feature!(IMAGE_SIZE, 430, 310); // Return an error if there are missing features if missing.is_empty() { @@ -223,6 +229,11 @@ impl FeaturesManager { )?; } + if self.0.contains(Features::TEXTURE_LEVELS) && version < Version::Desktop(430) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_query_levels.txt + writeln!(out, "#extension GL_ARB_texture_query_levels : require")?; + } + Ok(()) } } @@ -376,27 +387,75 @@ impl<'a, W> Writer<'a, W> { } } - // Loop trough all expressions in both functions and entry points + // We will need to pass some of the members to a closure, so we need + // to separate them otherwise the borrow checker will complain, this + // shouldn't be needed in rust 2021 + let &mut Self { + module, + info, + ref mut features, + entry_point, + entry_point_idx, + ref policies, + .. + } = self; + + // Loop trough all expressions in both functions and the entry point // to check for needed features - for (_, expr) in self - .module + for (expressions, info) in module .functions .iter() - .flat_map(|(_, f)| f.expressions.iter()) - .chain(self.entry_point.function.expressions.iter()) + .map(|(h, f)| (&f.expressions, &info[h])) + .chain(std::iter::once(( + &entry_point.function.expressions, + info.get_entry_point(entry_point_idx as usize), + ))) { - match *expr { + for (_, expr) in expressions.iter() { + match *expr { // Check for fused multiply add use Expression::Math { fun, .. } if fun == MathFunction::Fma => { - self.features.request(Features::FMA) + features.request(Features::FMA) } - // Check for samples query + // Check for queries that neeed aditonal features Expression::ImageQuery { - query: crate::ImageQuery::NumSamples, + image, + query, .. - } => self.features.request(Features::TEXTURE_SAMPLES), + } => match query { + // Storage images use `imageSize` which is only available + // in glsl > 420 + // + // layers queries are also implemented as size queries + crate::ImageQuery::Size { .. } | crate::ImageQuery::NumLayers => { + if let TypeInner::Image { + class: crate::ImageClass::Storage { .. }, .. + } = *info[image].ty.inner_with(&module.types) { + features.request(Features::IMAGE_SIZE) + } + }, + crate::ImageQuery::NumLevels => features.request(Features::TEXTURE_LEVELS), + crate::ImageQuery::NumSamples => features.request(Features::TEXTURE_SAMPLES), + } + , + // Check for image loads that needs bound checking on the sample + // or level argument since this requires a feature + Expression::ImageLoad { + sample, level, .. + } => { + if policies.image != crate::proc::BoundsCheckPolicy::Unchecked { + if sample.is_some() { + features.request(Features::TEXTURE_SAMPLES) + } + + if level.is_some() { + features.request(Features::TEXTURE_LEVELS) + } + } + } _ => {} } + } } self.features.check_availability(self.options.version) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index abce4d4ab..9e534df53 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -12,7 +12,6 @@ to output a [`Module`](crate::Module) into glsl - 420 - 430 - 450 -- 460 ### ES - 300 @@ -69,6 +68,10 @@ pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450] /// List of supported `es` GLSL versions. pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; +/// The suffix of the variable that will hold the calculated clamped level +/// of detail for bounds checking in `ImageLoad` +const CLAMPED_LOD_SUFFIX: &str = "_clamped_lod"; + /// Mapping between resources and bindings. pub type BindingMap = std::collections::BTreeMap; @@ -375,6 +378,8 @@ pub struct Writer<'a, W> { out: W, /// User defined configuration to be used. options: &'a Options, + /// The bound checking policies to be used + policies: proc::BoundsCheckPolicies, // Internal State /// Features manager used to store all the needed features and write them. @@ -410,6 +415,7 @@ impl<'a, W: Write> Writer<'a, W> { info: &'a valid::ModuleInfo, options: &'a Options, pipeline_options: &'a PipelineOptions, + policies: proc::BoundsCheckPolicies, ) -> Result { // Check if the requested version is supported if !options.version.is_supported() { @@ -437,6 +443,8 @@ impl<'a, W: Write> Writer<'a, W> { info, out, options, + policies, + namer, features: FeaturesManager::new(), names, @@ -1635,6 +1643,27 @@ impl<'a, W: Write> Writer<'a, W> { None }; + // If we are going to write an `ImageLoad` next and the target image + // is sampled and we are using the `Restrict` policy for bounds + // checking images we need to write a local holding the clamped lod. + if let crate::Expression::ImageLoad { + image, + level: Some(level_expr), + .. + } = ctx.expressions[handle] + { + if let TypeInner::Image { + class: crate::ImageClass::Sampled { .. }, + .. + } = *ctx.info[image].ty.inner_with(&self.module.types) + { + if let proc::BoundsCheckPolicy::Restrict = self.policies.image { + write!(self.out, "{}", level)?; + self.write_clamped_lod(ctx, handle, image, level_expr)? + } + } + } + if let Some(name) = expr_name { write!(self.out, "{}", level)?; self.write_named_expr(handle, name, ctx)?; @@ -1933,19 +1962,7 @@ impl<'a, W: Write> Writer<'a, W> { value, } => { write!(self.out, "{}", level)?; - // This will only panic if the module is invalid - let dim = match *ctx.info[image].ty.inner_with(&self.module.types) { - TypeInner::Image { dim, .. } => dim, - _ => unreachable!(), - }; - - write!(self.out, "imageStore(")?; - self.write_expr(image, ctx)?; - write!(self.out, ", ")?; - self.write_texture_coordinates(coordinate, array_index, dim, ctx)?; - write!(self.out, ", ")?; - self.write_expr(value, ctx)?; - writeln!(self.out, ");")?; + self.write_image_store(ctx, image, coordinate, array_index, value)? } // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list Statement::Call { @@ -2320,51 +2337,13 @@ impl<'a, W: Write> Writer<'a, W> { // End the function write!(self.out, ")")? } - // `ImageLoad` is also a bit complicated. - // There are two functions one for sampled - // images another for storage images, the former uses `texelFetch` and the latter uses - // `imageLoad`. - // Furthermore we have `index` which is always `Some` for sampled images - // and `None` for storage images, so we end up with two functions: - // `texelFetch(image, coordinate, index)` - for sampled images - // `imageLoad(image, coordinate)` - for storage images Expression::ImageLoad { image, coordinate, array_index, sample, level, - } => { - // This will only panic if the module is invalid - let (dim, class) = match *ctx.info[image].ty.inner_with(&self.module.types) { - TypeInner::Image { - dim, - arrayed: _, - class, - } => (dim, class), - _ => unreachable!(), - }; - - let fun_name = match class { - crate::ImageClass::Sampled { .. } => "texelFetch", - crate::ImageClass::Storage { .. } => "imageLoad", - // TODO: Is there even a function for this? - crate::ImageClass::Depth { multi: _ } => { - return Err(Error::Custom("TODO: depth sample loads".to_string())) - } - }; - - write!(self.out, "{}(", fun_name)?; - self.write_expr(image, ctx)?; - write!(self.out, ", ")?; - self.write_texture_coordinates(coordinate, array_index, dim, ctx)?; - - if let Some(sample_or_level) = sample.or(level) { - write!(self.out, ", ")?; - self.write_expr(sample_or_level, ctx)?; - } - write!(self.out, ")")?; - } + } => self.write_image_load(expr, ctx, image, coordinate, array_index, sample, level)?, // Query translates into one of the: // - textureSize/imageSize // - textureQueryLevels @@ -2961,25 +2940,71 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } - fn write_texture_coordinates( + /// Helper function to write the local holding the clamped lod + fn write_clamped_lod( &mut self, + ctx: &back::FunctionCtx, + expr: Handle, + image: Handle, + level_expr: Handle, + ) -> Result<(), Error> { + // Define our local and start a call to `clamp` + write!( + self.out, + "int {}{}{} = clamp(", + back::BAKE_PREFIX, + expr.index(), + CLAMPED_LOD_SUFFIX + )?; + // Write the lod that will be clamped + self.write_expr(level_expr, ctx)?; + // Set the min value to 0 and start a call to `textureQueryLevels` to get + // the maximum value + write!(self.out, ", 0, textureQueryLevels(")?; + // Write the target image as an argument to `textureQueryLevels` + self.write_expr(image, ctx)?; + // Close the call to `textureQueryLevels` subtract 1 from it since + // the lod argument is 0 based, close the `clamp` call and end the + // local declaration statement. + writeln!(self.out, ") - 1);")?; + + Ok(()) + } + + // Helper method used to retrieve how many elements a coordinate vector + // for the images operations need. + fn get_coordinate_vector_size(&self, dim: crate::ImageDimension, arrayed: bool) -> u8 { + // openGL es doesn't have 1D images so we need workaround it + let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es(); + // Get how many components the coordinate vector needs for the dimensions only + let tex_coord_size = match dim { + crate::ImageDimension::D1 => 1, + crate::ImageDimension::D2 => 2, + crate::ImageDimension::D3 => 3, + crate::ImageDimension::Cube => 2, + }; + // Calculate the true size of the coordinate vector by adding 1 for arrayed images + // and another 1 if we need to workaround 1D images by making them 2D + tex_coord_size + tex_1d_hack as u8 + arrayed as u8 + } + + /// Helper method to write the coordinate vector for image operations + fn write_texture_coord( + &mut self, + ctx: &back::FunctionCtx, + vector_size: u8, coordinate: Handle, array_index: Option>, - dim: crate::ImageDimension, - ctx: &back::FunctionCtx, + // Emulate 1D images as 2D for profiles that don't support it (glsl es) + tex_1d_hack: bool, ) -> Result<(), Error> { - use crate::ImageDimension as IDim; - - let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es(); match array_index { + // If the image needs an array indice we need to add it to the end of our + // coordinate vector, to do so we will use the `ivec(ivec, scalar)` + // constructor notation (NOTE: the inner `ivec` can also be a scalar, this + // is important for 1D arrayed images). Some(layer_expr) => { - let tex_coord_size = match dim { - IDim::D1 => 2, - IDim::D2 => 3, - IDim::D3 => 4, - IDim::Cube => 4, - }; - write!(self.out, "ivec{}(", tex_coord_size + tex_1d_hack as u8)?; + write!(self.out, "ivec{}(", vector_size)?; self.write_expr(coordinate, ctx)?; write!(self.out, ", ")?; // If we are replacing sampler1D with sampler2D we also need @@ -2990,16 +3015,326 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(layer_expr, ctx)?; write!(self.out, ")")?; } + // Otherwise write just the expression (and the 1D hack if needed) None => { if tex_1d_hack { write!(self.out, "ivec2(")?; } self.write_expr(coordinate, ctx)?; if tex_1d_hack { - write!(self.out, ", 0.0)")?; + write!(self.out, ", 0)")?; } } } + + Ok(()) + } + + /// Helper method to write the `ImageStore` statement + fn write_image_store( + &mut self, + ctx: &back::FunctionCtx, + image: Handle, + coordinate: Handle, + array_index: Option>, + value: Handle, + ) -> Result<(), Error> { + use crate::ImageDimension as IDim; + + // NOTE: openGL requires that `imageStore`s have no effets when the texel is invalid + // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20) + + // This will only panic if the module is invalid + let dim = match *ctx.info[image].ty.inner_with(&self.module.types) { + TypeInner::Image { dim, .. } => dim, + _ => unreachable!(), + }; + + // Begin our call to `imageStore` + write!(self.out, "imageStore(")?; + self.write_expr(image, ctx)?; + // Separate the image argument from the coordinates + write!(self.out, ", ")?; + + // openGL es doesn't have 1D images so we need workaround it + let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es(); + // Write the coordinate vector + self.write_texture_coord( + ctx, + // Get the size of the coordinate vector + self.get_coordinate_vector_size(dim, array_index.is_some()), + coordinate, + array_index, + tex_1d_hack, + )?; + + // Separate the coordinate from the value to write and write the expression + // of the value to write. + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + // End the call to `imageStore` and the statement. + writeln!(self.out, ");")?; + + Ok(()) + } + + /// Helper method for writing an `ImageLoad` expression. + #[allow(clippy::too_many_arguments)] + fn write_image_load( + &mut self, + handle: Handle, + ctx: &back::FunctionCtx, + image: Handle, + coordinate: Handle, + array_index: Option>, + sample: Option>, + level: Option>, + ) -> Result<(), Error> { + use crate::ImageDimension as IDim; + + // `ImageLoad` is a bit complicated. + // There are two functions one for sampled + // images another for storage images, the former uses `texelFetch` and the + // latter uses `imageLoad`. + // + // Furthermore we have `level` which is always `Some` for sampled images + // and `None` for storage images, so we end up with two functions: + // - `texelFetch(image, coordinate, level)` for sampled images + // - `imageLoad(image, coordinate)` for storage images + // + // Finally we also have to consider bounds checking, for storage images + // this is easy since openGL requires that invalid texels always return + // 0, for sampled images we need to either verify that all arguments are + // in bounds (`ReadZeroSkipWrite`) or make them a valid texel (`Restrict`). + + // This will only panic if the module is invalid + let (dim, class) = match *ctx.info[image].ty.inner_with(&self.module.types) { + TypeInner::Image { + dim, + arrayed: _, + class, + } => (dim, class), + _ => unreachable!(), + }; + + // Get the name of the function to be used for the load operation + // and the policy to be used with it. + let (fun_name, policy) = match class { + // Sampled images inherit the policy from the user passed policies + crate::ImageClass::Sampled { .. } => ("texelFetch", self.policies.image), + crate::ImageClass::Storage { .. } => { + // OpenGL 4.2 Core §3.9.20 defines that out of bounds texels in `imageLoad`s + // always return zero values so we don't need to generate bounds checks + ("imageLoad", proc::BoundsCheckPolicy::Unchecked) + } + // TODO: Is there even a function for this? + crate::ImageClass::Depth { multi: _ } => { + return Err(Error::Custom( + "WGSL `textureLoad` from depth textures is not supported in GLSL".to_string(), + )) + } + }; + + // openGL es doesn't have 1D images so we need workaround it + let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es(); + // Get the size of the coordinate vector + let vector_size = self.get_coordinate_vector_size(dim, array_index.is_some()); + + if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy { + // To write the bounds checks for `ReadZeroSkipWrite` we will use a + // ternary operator since we are in the middle of an expression and + // need to return a value. + // + // NOTE: glsl does short circuit when evaluating logical + // expressions so we can be sure that after we test a + // condition it will be true for the next ones + + // Write parantheses around the ternary operator to prevent problems with + // expressions emitted before or after it having more precedence + write!(self.out, "(",)?; + + // The lod check needs to precede the size check since we need + // to use the lod to get the size of the image at that level. + if let Some(level_expr) = level { + self.write_expr(level_expr, ctx)?; + write!(self.out, " < textureQueryLevels(",)?; + self.write_expr(image, ctx)?; + // Chain the next check + write!(self.out, ") && ")?; + } + + // Check that the sample arguments doesn't exceed the number of samples + if let Some(sample_expr) = sample { + self.write_expr(sample_expr, ctx)?; + write!(self.out, " < textureSamples(",)?; + self.write_expr(image, ctx)?; + // Chain the next check + write!(self.out, ") && ")?; + } + + // We now need to write the size checks for the coordinates and array index + // first we write the comparation function in case the image is 1D non arrayed + // (and no 1D to 2D hack was needed) we are comparing scalars so the less than + // operator will suffice, but otherwise we'll be comparing two vectors so we'll + // need to use the `lessThan` function but it returns a vector of booleans (one + // for each comparison) so we need to fold it all in one scalar boolean, since + // we want all comparisons to pass we use the `all` function which will only + // return `true` if all the elements of the boolean vector are also `true`. + // + // So we'll end with one of the following forms + // - `coord < textureSize(image, lod)` for 1D images + // - `all(lessThan(coord, textureSize(image, lod)))` for normal images + // - `all(lessThan(ivec(coord, array_index), textureSize(image, lod)))` + // for arrayed images + // - `all(lessThan(coord, textureSize(image)))` for multi sampled images + + if vector_size != 1 { + write!(self.out, "all(lessThan(")?; + } + + // Write the coordinate vector + self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?; + + if vector_size != 1 { + // If we used the `lessThan` function we need to separate the + // coordinates from the image size. + write!(self.out, ", ")?; + } else { + // If we didn't use it (ie. 1D images) we perform the comparsion + // using the less than operator. + write!(self.out, " < ")?; + } + + // Call `textureSize` to get our image size + write!(self.out, "textureSize(")?; + self.write_expr(image, ctx)?; + // `textureSize` uses the lod as a second argument for mipmapped images + if let Some(level_expr) = level { + // Separate the image from the lod + write!(self.out, ", ")?; + self.write_expr(level_expr, ctx)?; + } + // Close the `textureSize` call + write!(self.out, ")")?; + + if vector_size != 1 { + // Close the `all` and `lessThan` calls + write!(self.out, "))")?; + } + + // Finally end the condition part of the ternary operator + write!(self.out, " ? ")?; + } + + // Begin the call to the function used to load the texel + write!(self.out, "{}(", fun_name)?; + self.write_expr(image, ctx)?; + write!(self.out, ", ")?; + + // If we are using `Restrict` bounds checking we need to pass valid texel + // coordinates, to do so we use the `clamp` function to get a value between + // 0 and the image size - 1 (indexing begins at 0) + if let proc::BoundsCheckPolicy::Restrict = policy { + write!(self.out, "clamp(")?; + } + + // Write the coordinate vector + self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?; + + // If we are using `Restrict` bounds checking we need to write the rest of the + // clamp we initiated before writing the coordinates. + if let proc::BoundsCheckPolicy::Restrict = policy { + // Write the min value 0 + if vector_size == 1 { + write!(self.out, ", 0")?; + } else { + write!(self.out, ", ivec{}(0)", vector_size)?; + } + // Start the `textureSize` call to use as the max value. + write!(self.out, ", textureSize(")?; + self.write_expr(image, ctx)?; + // If the image is mipmapped we need to add the lod argument to the + // `textureSize` call, but this needs to be the clamped lod, this should + // have been generated earlier and put in a local. + if class.is_mipmapped() { + write!( + self.out, + ", {}{}{}", + back::BAKE_PREFIX, + handle.index(), + CLAMPED_LOD_SUFFIX + )?; + } + // Close the `textureSize` call + write!(self.out, ")")?; + + // Subtract 1 from the `textureSize` call since the coordinates are zero based. + if vector_size == 1 { + write!(self.out, " - 1")?; + } else { + write!(self.out, " - ivec{}(1)", vector_size)?; + } + + // Close the `clamp` call + write!(self.out, ")")?; + + // Add the clamped lod (if present) as the second argument to the + // image load function. + if level.is_some() { + write!( + self.out, + ", {}{}{}", + back::BAKE_PREFIX, + handle.index(), + CLAMPED_LOD_SUFFIX + )?; + } + + // If a sample argument is needed we need to clamp it between 0 and + // the number of samples the image has. + if let Some(sample_expr) = sample { + write!(self.out, ", clamp(")?; + self.write_expr(sample_expr, ctx)?; + // Set the min value to 0 and start the call to `textureSamples` + write!(self.out, ", 0, textureSamples(")?; + self.write_expr(image, ctx)?; + // Close the `textureSamples` call, subtract 1 from it since the sample + // argument is zero based, and close the `clamp` call + writeln!(self.out, ") - 1)")?; + } + } else if let Some(sample_or_level) = sample.or(level) { + // If no bounds checking is need just add the sample or level argument + // after the coordinates + write!(self.out, ", ")?; + self.write_expr(sample_or_level, ctx)?; + } + + // Close the image load function. + write!(self.out, ")")?; + + // If we were using the `ReadZeroSkipWrite` policy we need to end the first branch + // (which is taken if the condition is `true`) with a colon (`:`) and write the + // second branch which is just a 0 value. + if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy { + // Get the kind of the output value. + let kind = match class { + // Only sampled images can reach here since storage images + // don't need bounds checks and depth images aren't implmented + crate::ImageClass::Sampled { kind, .. } => kind, + _ => unreachable!(), + }; + + // End the first branch + write!(self.out, " : ")?; + // Write the 0 value + write!(self.out, "{}vec4(", glsl_scalar(kind, 4)?.prefix,)?; + self.write_zero_init_scalar(kind)?; + // Close the zero value constructor + write!(self.out, ")")?; + // Close the parantheses surrounding our ternary + write!(self.out, ")")?; + } + Ok(()) } diff --git a/tests/in/bounds-check-image-restrict.param.ron b/tests/in/bounds-check-image-restrict.param.ron index d6af131df..e91f7fc24 100644 --- a/tests/in/bounds-check-image-restrict.param.ron +++ b/tests/in/bounds-check-image-restrict.param.ron @@ -6,4 +6,9 @@ version: (1, 1), debug: true, ), + glsl: ( + version: Desktop(430), + writer_flags: (bits: 0), + binding_map: { }, + ), ) diff --git a/tests/in/bounds-check-image-restrict.wgsl b/tests/in/bounds-check-image-restrict.wgsl index 3be562ff2..0cce20eaf 100644 --- a/tests/in/bounds-check-image-restrict.wgsl +++ b/tests/in/bounds-check-image-restrict.wgsl @@ -5,79 +5,100 @@ fn test_textureLoad_1d(coords: i32, level: i32) -> vec4 { return textureLoad(image_1d, coords, level); } -@group(0) @binding(0) +@group(0) @binding(1) var image_2d: texture_2d; fn test_textureLoad_2d(coords: vec2, level: i32) -> vec4 { return textureLoad(image_2d, coords, level); } -@group(0) @binding(0) +@group(0) @binding(2) var image_2d_array: texture_2d_array; fn test_textureLoad_2d_array(coords: vec2, index: i32, level: i32) -> vec4 { return textureLoad(image_2d_array, coords, index, level); } -@group(0) @binding(0) +@group(0) @binding(3) var image_3d: texture_3d; fn test_textureLoad_3d(coords: vec3, level: i32) -> vec4 { return textureLoad(image_3d, coords, level); } -@group(0) @binding(0) +@group(0) @binding(4) var image_multisampled_2d: texture_multisampled_2d; fn test_textureLoad_multisampled_2d(coords: vec2, _sample: i32) -> vec4 { return textureLoad(image_multisampled_2d, coords, _sample); } -@group(0) @binding(0) +@group(0) @binding(5) var image_depth_2d: texture_depth_2d; fn test_textureLoad_depth_2d(coords: vec2, level: i32) -> f32 { return textureLoad(image_depth_2d, coords, level); } -@group(0) @binding(0) +@group(0) @binding(6) var image_depth_2d_array: texture_depth_2d_array; fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> f32 { return textureLoad(image_depth_2d_array, coords, index, level); } -@group(0) @binding(0) +@group(0) @binding(7) var image_depth_multisampled_2d: texture_depth_multisampled_2d; fn test_textureLoad_depth_multisampled_2d(coords: vec2, _sample: i32) -> f32 { return textureLoad(image_depth_multisampled_2d, coords, _sample); } -@group(0) @binding(0) +@group(0) @binding(8) var image_storage_1d: texture_storage_1d; fn test_textureStore_1d(coords: i32, value: vec4) { textureStore(image_storage_1d, coords, value); } -@group(0) @binding(0) +@group(0) @binding(9) var image_storage_2d: texture_storage_2d; fn test_textureStore_2d(coords: vec2, value: vec4) { textureStore(image_storage_2d, coords, value); } -@group(0) @binding(0) +@group(0) @binding(10) var image_storage_2d_array: texture_storage_2d_array; fn test_textureStore_2d_array(coords: vec2, array_index: i32, value: vec4) { textureStore(image_storage_2d_array, coords, array_index, value); } -@group(0) @binding(0) +@group(0) @binding(11) var image_storage_3d: texture_storage_3d; fn test_textureStore_3d(coords: vec3, value: vec4) { textureStore(image_storage_3d, coords, value); } + +// GLSL output requires that we identify an entry point, so +// that it can tell what "in" and "out" globals to write. +@fragment +fn fragment_shader() -> @location(0) vec4 { + test_textureLoad_1d(0, 0); + test_textureLoad_2d(vec2(), 0); + test_textureLoad_2d_array(vec2(), 0, 0); + test_textureLoad_3d(vec3(), 0); + test_textureLoad_multisampled_2d(vec2(), 0); + // Not yet implemented for GLSL: + // test_textureLoad_depth_2d(vec2(), 0); + // test_textureLoad_depth_2d_array(vec2(), 0, 0); + // test_textureLoad_depth_multisampled_2d(vec2(), 0); + test_textureStore_1d(0, vec4()); + test_textureStore_2d(vec2(), vec4()); + test_textureStore_2d_array(vec2(), 0, vec4()); + test_textureStore_3d(vec3(), vec4()); + + return vec4(0.,0.,0.,0.); +} diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/tests/in/bounds-check-image-rzsw.param.ron index 2d00b645c..72ccb27e9 100644 --- a/tests/in/bounds-check-image-rzsw.param.ron +++ b/tests/in/bounds-check-image-rzsw.param.ron @@ -6,4 +6,9 @@ version: (1, 1), debug: true, ), + glsl: ( + version: Desktop(430), + writer_flags: (bits: 0), + binding_map: { }, + ), ) diff --git a/tests/in/bounds-check-image-rzsw.wgsl b/tests/in/bounds-check-image-rzsw.wgsl index 3be562ff2..0cce20eaf 100644 --- a/tests/in/bounds-check-image-rzsw.wgsl +++ b/tests/in/bounds-check-image-rzsw.wgsl @@ -5,79 +5,100 @@ fn test_textureLoad_1d(coords: i32, level: i32) -> vec4 { return textureLoad(image_1d, coords, level); } -@group(0) @binding(0) +@group(0) @binding(1) var image_2d: texture_2d; fn test_textureLoad_2d(coords: vec2, level: i32) -> vec4 { return textureLoad(image_2d, coords, level); } -@group(0) @binding(0) +@group(0) @binding(2) var image_2d_array: texture_2d_array; fn test_textureLoad_2d_array(coords: vec2, index: i32, level: i32) -> vec4 { return textureLoad(image_2d_array, coords, index, level); } -@group(0) @binding(0) +@group(0) @binding(3) var image_3d: texture_3d; fn test_textureLoad_3d(coords: vec3, level: i32) -> vec4 { return textureLoad(image_3d, coords, level); } -@group(0) @binding(0) +@group(0) @binding(4) var image_multisampled_2d: texture_multisampled_2d; fn test_textureLoad_multisampled_2d(coords: vec2, _sample: i32) -> vec4 { return textureLoad(image_multisampled_2d, coords, _sample); } -@group(0) @binding(0) +@group(0) @binding(5) var image_depth_2d: texture_depth_2d; fn test_textureLoad_depth_2d(coords: vec2, level: i32) -> f32 { return textureLoad(image_depth_2d, coords, level); } -@group(0) @binding(0) +@group(0) @binding(6) var image_depth_2d_array: texture_depth_2d_array; fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> f32 { return textureLoad(image_depth_2d_array, coords, index, level); } -@group(0) @binding(0) +@group(0) @binding(7) var image_depth_multisampled_2d: texture_depth_multisampled_2d; fn test_textureLoad_depth_multisampled_2d(coords: vec2, _sample: i32) -> f32 { return textureLoad(image_depth_multisampled_2d, coords, _sample); } -@group(0) @binding(0) +@group(0) @binding(8) var image_storage_1d: texture_storage_1d; fn test_textureStore_1d(coords: i32, value: vec4) { textureStore(image_storage_1d, coords, value); } -@group(0) @binding(0) +@group(0) @binding(9) var image_storage_2d: texture_storage_2d; fn test_textureStore_2d(coords: vec2, value: vec4) { textureStore(image_storage_2d, coords, value); } -@group(0) @binding(0) +@group(0) @binding(10) var image_storage_2d_array: texture_storage_2d_array; fn test_textureStore_2d_array(coords: vec2, array_index: i32, value: vec4) { textureStore(image_storage_2d_array, coords, array_index, value); } -@group(0) @binding(0) +@group(0) @binding(11) var image_storage_3d: texture_storage_3d; fn test_textureStore_3d(coords: vec3, value: vec4) { textureStore(image_storage_3d, coords, value); } + +// GLSL output requires that we identify an entry point, so +// that it can tell what "in" and "out" globals to write. +@fragment +fn fragment_shader() -> @location(0) vec4 { + test_textureLoad_1d(0, 0); + test_textureLoad_2d(vec2(), 0); + test_textureLoad_2d_array(vec2(), 0, 0); + test_textureLoad_3d(vec3(), 0); + test_textureLoad_multisampled_2d(vec2(), 0); + // Not yet implemented for GLSL: + // test_textureLoad_depth_2d(vec2(), 0); + // test_textureLoad_depth_2d_array(vec2(), 0, 0); + // test_textureLoad_depth_multisampled_2d(vec2(), 0); + test_textureStore_1d(0, vec4()); + test_textureStore_2d(vec2(), vec4()); + test_textureStore_2d_array(vec2(), 0, vec4()); + test_textureStore_3d(vec3(), vec4()); + + return vec4(0.,0.,0.,0.); +} diff --git a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl new file mode 100644 index 000000000..a1d8b5b05 --- /dev/null +++ b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl @@ -0,0 +1,86 @@ +#version 430 core +#extension GL_ARB_shader_texture_image_samples : require +uniform highp sampler1D _group_0_binding_0_fs; + +uniform highp sampler2D _group_0_binding_1_fs; + +uniform highp sampler2DArray _group_0_binding_2_fs; + +uniform highp sampler3D _group_0_binding_3_fs; + +uniform highp sampler2DMS _group_0_binding_4_fs; + +layout(rgba8) writeonly uniform highp image1D _group_0_binding_8_fs; + +layout(rgba8) writeonly uniform highp image2D _group_0_binding_9_fs; + +layout(rgba8) writeonly uniform highp image2DArray _group_0_binding_10_fs; + +layout(rgba8) writeonly uniform highp image3D _group_0_binding_11_fs; + +layout(location = 0) out vec4 _fs2p_location0; + +vec4 test_textureLoad_1d(int coords, int level) { + int _e3_clamped_lod = clamp(level, 0, textureQueryLevels(_group_0_binding_0_fs) - 1); + vec4 _e3 = texelFetch(_group_0_binding_0_fs, clamp(coords, 0, textureSize(_group_0_binding_0_fs, _e3_clamped_lod) - 1), _e3_clamped_lod); + return _e3; +} + +vec4 test_textureLoad_2d(ivec2 coords_1, int level_1) { + int _e4_clamped_lod = clamp(level_1, 0, textureQueryLevels(_group_0_binding_1_fs) - 1); + vec4 _e4 = texelFetch(_group_0_binding_1_fs, clamp(coords_1, ivec2(0), textureSize(_group_0_binding_1_fs, _e4_clamped_lod) - ivec2(1)), _e4_clamped_lod); + return _e4; +} + +vec4 test_textureLoad_2d_array(ivec2 coords_2, int index, int level_2) { + int _e6_clamped_lod = clamp(level_2, 0, textureQueryLevels(_group_0_binding_2_fs) - 1); + vec4 _e6 = texelFetch(_group_0_binding_2_fs, clamp(ivec3(coords_2, index), ivec3(0), textureSize(_group_0_binding_2_fs, _e6_clamped_lod) - ivec3(1)), _e6_clamped_lod); + return _e6; +} + +vec4 test_textureLoad_3d(ivec3 coords_3, int level_3) { + int _e6_clamped_lod = clamp(level_3, 0, textureQueryLevels(_group_0_binding_3_fs) - 1); + vec4 _e6 = texelFetch(_group_0_binding_3_fs, clamp(coords_3, ivec3(0), textureSize(_group_0_binding_3_fs, _e6_clamped_lod) - ivec3(1)), _e6_clamped_lod); + return _e6; +} + +vec4 test_textureLoad_multisampled_2d(ivec2 coords_4, int _sample) { + vec4 _e7 = texelFetch(_group_0_binding_4_fs, clamp(coords_4, ivec2(0), textureSize(_group_0_binding_4_fs) - ivec2(1)), clamp(_sample, 0, textureSamples(_group_0_binding_4_fs) - 1) +); + return _e7; +} + +void test_textureStore_1d(int coords_8, vec4 value) { + imageStore(_group_0_binding_8_fs, coords_8, value); + return; +} + +void test_textureStore_2d(ivec2 coords_9, vec4 value_1) { + imageStore(_group_0_binding_9_fs, coords_9, value_1); + return; +} + +void test_textureStore_2d_array(ivec2 coords_10, int array_index, vec4 value_2) { + imageStore(_group_0_binding_10_fs, ivec3(coords_10, array_index), value_2); + return; +} + +void test_textureStore_3d(ivec3 coords_11, vec4 value_3) { + imageStore(_group_0_binding_11_fs, coords_11, value_3); + return; +} + +void main() { + vec4 _e14 = test_textureLoad_1d(0, 0); + vec4 _e17 = test_textureLoad_2d(ivec2(0, 0), 0); + vec4 _e21 = test_textureLoad_2d_array(ivec2(0, 0), 0, 0); + vec4 _e24 = test_textureLoad_3d(ivec3(0, 0, 0), 0); + vec4 _e27 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); + test_textureStore_1d(0, vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_2d(ivec2(0, 0), vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_2d_array(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_3d(ivec3(0, 0, 0), vec4(0.0, 0.0, 0.0, 0.0)); + _fs2p_location0 = vec4(0.0, 0.0, 0.0, 0.0); + return; +} + diff --git a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl new file mode 100644 index 000000000..9c2bef19a --- /dev/null +++ b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl @@ -0,0 +1,81 @@ +#version 430 core +#extension GL_ARB_shader_texture_image_samples : require +uniform highp sampler1D _group_0_binding_0_fs; + +uniform highp sampler2D _group_0_binding_1_fs; + +uniform highp sampler2DArray _group_0_binding_2_fs; + +uniform highp sampler3D _group_0_binding_3_fs; + +uniform highp sampler2DMS _group_0_binding_4_fs; + +layout(rgba8) writeonly uniform highp image1D _group_0_binding_8_fs; + +layout(rgba8) writeonly uniform highp image2D _group_0_binding_9_fs; + +layout(rgba8) writeonly uniform highp image2DArray _group_0_binding_10_fs; + +layout(rgba8) writeonly uniform highp image3D _group_0_binding_11_fs; + +layout(location = 0) out vec4 _fs2p_location0; + +vec4 test_textureLoad_1d(int coords, int level) { + vec4 _e3 = (level < textureQueryLevels(_group_0_binding_0_fs) && coords < textureSize(_group_0_binding_0_fs, level) ? texelFetch(_group_0_binding_0_fs, coords, level) : vec4(0.0)); + return _e3; +} + +vec4 test_textureLoad_2d(ivec2 coords_1, int level_1) { + vec4 _e4 = (level_1 < textureQueryLevels(_group_0_binding_1_fs) && all(lessThan(coords_1, textureSize(_group_0_binding_1_fs, level_1))) ? texelFetch(_group_0_binding_1_fs, coords_1, level_1) : vec4(0.0)); + return _e4; +} + +vec4 test_textureLoad_2d_array(ivec2 coords_2, int index, int level_2) { + vec4 _e6 = (level_2 < textureQueryLevels(_group_0_binding_2_fs) && all(lessThan(ivec3(coords_2, index), textureSize(_group_0_binding_2_fs, level_2))) ? texelFetch(_group_0_binding_2_fs, ivec3(coords_2, index), level_2) : vec4(0.0)); + return _e6; +} + +vec4 test_textureLoad_3d(ivec3 coords_3, int level_3) { + vec4 _e6 = (level_3 < textureQueryLevels(_group_0_binding_3_fs) && all(lessThan(coords_3, textureSize(_group_0_binding_3_fs, level_3))) ? texelFetch(_group_0_binding_3_fs, coords_3, level_3) : vec4(0.0)); + return _e6; +} + +vec4 test_textureLoad_multisampled_2d(ivec2 coords_4, int _sample) { + vec4 _e7 = (_sample < textureSamples(_group_0_binding_4_fs) && all(lessThan(coords_4, textureSize(_group_0_binding_4_fs))) ? texelFetch(_group_0_binding_4_fs, coords_4, _sample) : vec4(0.0)); + return _e7; +} + +void test_textureStore_1d(int coords_8, vec4 value) { + imageStore(_group_0_binding_8_fs, coords_8, value); + return; +} + +void test_textureStore_2d(ivec2 coords_9, vec4 value_1) { + imageStore(_group_0_binding_9_fs, coords_9, value_1); + return; +} + +void test_textureStore_2d_array(ivec2 coords_10, int array_index, vec4 value_2) { + imageStore(_group_0_binding_10_fs, ivec3(coords_10, array_index), value_2); + return; +} + +void test_textureStore_3d(ivec3 coords_11, vec4 value_3) { + imageStore(_group_0_binding_11_fs, coords_11, value_3); + return; +} + +void main() { + vec4 _e14 = test_textureLoad_1d(0, 0); + vec4 _e17 = test_textureLoad_2d(ivec2(0, 0), 0); + vec4 _e21 = test_textureLoad_2d_array(ivec2(0, 0), 0, 0); + vec4 _e24 = test_textureLoad_3d(ivec3(0, 0, 0), 0); + vec4 _e27 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); + test_textureStore_1d(0, vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_2d(ivec2(0, 0), vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_2d_array(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_3d(ivec3(0, 0, 0), vec4(0.0, 0.0, 0.0, 0.0)); + _fs2p_location0 = vec4(0.0, 0.0, 0.0, 0.0); + return; +} + diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl index 08c6a32e9..96d4bb775 100644 --- a/tests/out/glsl/image.main.Compute.glsl +++ b/tests/out/glsl/image.main.Compute.glsl @@ -27,8 +27,8 @@ void main() { uvec4 value2_ = texelFetch(_group_0_binding_3_cs, itc, int(local_id.z)); uvec4 value4_ = imageLoad(_group_0_binding_1_cs, itc); uvec4 value5_ = texelFetch(_group_0_binding_5_cs, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); - uvec4 value6_ = texelFetch(_group_0_binding_7_cs, ivec2(int(local_id.x), 0.0), int(local_id.z)); - imageStore(_group_0_binding_2_cs, ivec2(itc.x, 0.0), ((((value1_ + value2_) + value4_) + value5_) + value6_)); + uvec4 value6_ = texelFetch(_group_0_binding_7_cs, ivec2(int(local_id.x), 0), int(local_id.z)); + imageStore(_group_0_binding_2_cs, ivec2(itc.x, 0), ((((value1_ + value2_) + value4_) + value5_) + value6_)); return; } diff --git a/tests/out/msl/bounds-check-image-restrict.msl b/tests/out/msl/bounds-check-image-restrict.msl index 6a4548475..b2f6eca4d 100644 --- a/tests/out/msl/bounds-check-image-restrict.msl +++ b/tests/out/msl/bounds-check-image-restrict.msl @@ -4,6 +4,9 @@ using metal::uint; +constant metal::int2 const_type_4_ = {0, 0}; +constant metal::int3 const_type_7_ = {0, 0, 0}; +constant metal::float4 const_type_2_ = {0.0, 0.0, 0.0, 0.0}; metal::float4 test_textureLoad_1d( int coords, @@ -120,3 +123,29 @@ void test_textureStore_3d( image_storage_3d.write(value_3, metal::min(metal::uint3(coords_11), metal::uint3(image_storage_3d.get_width(), image_storage_3d.get_height(), image_storage_3d.get_depth()) - 1)); return; } + +struct fragment_shaderOutput { + metal::float4 member [[color(0)]]; +}; +fragment fragment_shaderOutput fragment_shader( + metal::texture1d image_1d [[user(fake0)]] +, metal::texture2d image_2d [[user(fake0)]] +, metal::texture2d_array image_2d_array [[user(fake0)]] +, metal::texture3d image_3d [[user(fake0)]] +, metal::texture2d_ms image_multisampled_2d [[user(fake0)]] +, metal::texture1d image_storage_1d [[user(fake0)]] +, metal::texture2d image_storage_2d [[user(fake0)]] +, metal::texture2d_array image_storage_2d_array [[user(fake0)]] +, metal::texture3d image_storage_3d [[user(fake0)]] +) { + metal::float4 _e14 = test_textureLoad_1d(0, 0, image_1d); + metal::float4 _e17 = test_textureLoad_2d(const_type_4_, 0, image_2d); + metal::float4 _e21 = test_textureLoad_2d_array(const_type_4_, 0, 0, image_2d_array); + metal::float4 _e24 = test_textureLoad_3d(const_type_7_, 0, image_3d); + metal::float4 _e27 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); + test_textureStore_1d(0, const_type_2_, image_storage_1d); + test_textureStore_2d(const_type_4_, const_type_2_, image_storage_2d); + test_textureStore_2d_array(const_type_4_, 0, const_type_2_, image_storage_2d_array); + test_textureStore_3d(const_type_7_, const_type_2_, image_storage_3d); + return fragment_shaderOutput { metal::float4(0.0, 0.0, 0.0, 0.0) }; +} diff --git a/tests/out/msl/bounds-check-image-rzsw.msl b/tests/out/msl/bounds-check-image-rzsw.msl index 78bef45ee..16cbf5c0a 100644 --- a/tests/out/msl/bounds-check-image-rzsw.msl +++ b/tests/out/msl/bounds-check-image-rzsw.msl @@ -10,6 +10,9 @@ struct DefaultConstructible { return T {}; } }; +constant metal::int2 const_type_4_ = {0, 0}; +constant metal::int3 const_type_7_ = {0, 0, 0}; +constant metal::float4 const_type_2_ = {0.0, 0.0, 0.0, 0.0}; metal::float4 test_textureLoad_1d( int coords, @@ -129,3 +132,29 @@ void test_textureStore_3d( } return; } + +struct fragment_shaderOutput { + metal::float4 member [[color(0)]]; +}; +fragment fragment_shaderOutput fragment_shader( + metal::texture1d image_1d [[user(fake0)]] +, metal::texture2d image_2d [[user(fake0)]] +, metal::texture2d_array image_2d_array [[user(fake0)]] +, metal::texture3d image_3d [[user(fake0)]] +, metal::texture2d_ms image_multisampled_2d [[user(fake0)]] +, metal::texture1d image_storage_1d [[user(fake0)]] +, metal::texture2d image_storage_2d [[user(fake0)]] +, metal::texture2d_array image_storage_2d_array [[user(fake0)]] +, metal::texture3d image_storage_3d [[user(fake0)]] +) { + metal::float4 _e14 = test_textureLoad_1d(0, 0, image_1d); + metal::float4 _e17 = test_textureLoad_2d(const_type_4_, 0, image_2d); + metal::float4 _e21 = test_textureLoad_2d_array(const_type_4_, 0, 0, image_2d_array); + metal::float4 _e24 = test_textureLoad_3d(const_type_7_, 0, image_3d); + metal::float4 _e27 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); + test_textureStore_1d(0, const_type_2_, image_storage_1d); + test_textureStore_2d(const_type_4_, const_type_2_, image_storage_2d); + test_textureStore_2d_array(const_type_4_, 0, const_type_2_, image_storage_2d_array); + test_textureStore_3d(const_type_7_, const_type_2_, image_storage_3d); + return fragment_shaderOutput { metal::float4(0.0, 0.0, 0.0, 0.0) }; +} diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index fe3bf1759..51d53f3d0 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -1,343 +1,380 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 214 +; Bound: 244 OpCapability ImageQuery OpCapability Image1D OpCapability Shader OpCapability Sampled1D -OpCapability Linkage %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %222 "fragment_shader" %220 +OpExecutionMode %222 OriginUpperLeft OpSource GLSL 450 -OpName %20 "image_1d" -OpName %22 "image_2d" -OpName %24 "image_2d_array" -OpName %26 "image_3d" -OpName %28 "image_multisampled_2d" -OpName %30 "image_depth_2d" -OpName %32 "image_depth_2d_array" -OpName %34 "image_depth_multisampled_2d" -OpName %36 "image_storage_1d" -OpName %38 "image_storage_2d" -OpName %40 "image_storage_2d_array" -OpName %42 "image_storage_3d" -OpName %45 "coords" -OpName %46 "level" -OpName %47 "test_textureLoad_1d" -OpName %60 "coords" -OpName %61 "level" -OpName %62 "test_textureLoad_2d" -OpName %75 "coords" -OpName %76 "index" -OpName %77 "level" -OpName %78 "test_textureLoad_2d_array" -OpName %92 "coords" -OpName %93 "level" -OpName %94 "test_textureLoad_3d" -OpName %107 "coords" -OpName %108 "_sample" -OpName %109 "test_textureLoad_multisampled_2d" -OpName %121 "coords" -OpName %122 "level" -OpName %123 "test_textureLoad_depth_2d" -OpName %137 "coords" -OpName %138 "index" -OpName %139 "level" -OpName %140 "test_textureLoad_depth_2d_array" -OpName %155 "coords" -OpName %156 "_sample" -OpName %157 "test_textureLoad_depth_multisampled_2d" -OpName %170 "coords" -OpName %171 "value" -OpName %172 "test_textureStore_1d" -OpName %180 "coords" -OpName %181 "value" -OpName %182 "test_textureStore_2d" -OpName %191 "coords" -OpName %192 "array_index" -OpName %193 "value" -OpName %194 "test_textureStore_2d_array" -OpName %204 "coords" -OpName %205 "value" -OpName %206 "test_textureStore_3d" -OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 0 -OpDecorate %22 DescriptorSet 0 -OpDecorate %22 Binding 0 -OpDecorate %24 DescriptorSet 0 -OpDecorate %24 Binding 0 -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 0 -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 0 -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 0 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 0 -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 0 -OpDecorate %36 NonReadable -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 0 -OpDecorate %38 NonReadable -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 0 -OpDecorate %40 NonReadable -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 0 -OpDecorate %42 NonReadable -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 0 +OpName %25 "image_1d" +OpName %27 "image_2d" +OpName %29 "image_2d_array" +OpName %31 "image_3d" +OpName %33 "image_multisampled_2d" +OpName %35 "image_depth_2d" +OpName %37 "image_depth_2d_array" +OpName %39 "image_depth_multisampled_2d" +OpName %41 "image_storage_1d" +OpName %43 "image_storage_2d" +OpName %45 "image_storage_2d_array" +OpName %47 "image_storage_3d" +OpName %50 "coords" +OpName %51 "level" +OpName %52 "test_textureLoad_1d" +OpName %65 "coords" +OpName %66 "level" +OpName %67 "test_textureLoad_2d" +OpName %80 "coords" +OpName %81 "index" +OpName %82 "level" +OpName %83 "test_textureLoad_2d_array" +OpName %97 "coords" +OpName %98 "level" +OpName %99 "test_textureLoad_3d" +OpName %112 "coords" +OpName %113 "_sample" +OpName %114 "test_textureLoad_multisampled_2d" +OpName %126 "coords" +OpName %127 "level" +OpName %128 "test_textureLoad_depth_2d" +OpName %142 "coords" +OpName %143 "index" +OpName %144 "level" +OpName %145 "test_textureLoad_depth_2d_array" +OpName %160 "coords" +OpName %161 "_sample" +OpName %162 "test_textureLoad_depth_multisampled_2d" +OpName %175 "coords" +OpName %176 "value" +OpName %177 "test_textureStore_1d" +OpName %185 "coords" +OpName %186 "value" +OpName %187 "test_textureStore_2d" +OpName %196 "coords" +OpName %197 "array_index" +OpName %198 "value" +OpName %199 "test_textureStore_2d_array" +OpName %209 "coords" +OpName %210 "value" +OpName %211 "test_textureStore_3d" +OpName %222 "fragment_shader" +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 0 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 1 +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 2 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 3 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 4 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 5 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 6 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 7 +OpDecorate %41 NonReadable +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 8 +OpDecorate %43 NonReadable +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 9 +OpDecorate %45 NonReadable +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 10 +OpDecorate %47 NonReadable +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 11 +OpDecorate %220 Location 0 %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpTypeImage %4 1D 0 0 0 1 Unknown -%5 = OpTypeInt 32 1 -%6 = OpTypeVector %4 4 -%7 = OpTypeImage %4 2D 0 0 0 1 Unknown -%8 = OpTypeVector %5 2 -%9 = OpTypeImage %4 2D 0 1 0 1 Unknown -%10 = OpTypeImage %4 3D 0 0 0 1 Unknown -%11 = OpTypeVector %5 3 -%12 = OpTypeImage %4 2D 0 0 1 1 Unknown -%13 = OpTypeImage %4 2D 1 0 0 1 Unknown -%14 = OpTypeImage %4 2D 1 1 0 1 Unknown -%15 = OpTypeImage %4 2D 1 0 1 1 Unknown -%16 = OpTypeImage %4 1D 0 0 0 2 Rgba8 -%17 = OpTypeImage %4 2D 0 0 0 2 Rgba8 -%18 = OpTypeImage %4 2D 0 1 0 2 Rgba8 -%19 = OpTypeImage %4 3D 0 0 0 2 Rgba8 -%21 = OpTypePointer UniformConstant %3 -%20 = OpVariable %21 UniformConstant -%23 = OpTypePointer UniformConstant %7 -%22 = OpVariable %23 UniformConstant -%25 = OpTypePointer UniformConstant %9 -%24 = OpVariable %25 UniformConstant -%27 = OpTypePointer UniformConstant %10 -%26 = OpVariable %27 UniformConstant -%29 = OpTypePointer UniformConstant %12 -%28 = OpVariable %29 UniformConstant -%31 = OpTypePointer UniformConstant %13 -%30 = OpVariable %31 UniformConstant -%33 = OpTypePointer UniformConstant %14 -%32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %15 -%34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %16 -%36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %17 -%38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %18 -%40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %19 -%42 = OpVariable %43 UniformConstant -%48 = OpTypeFunction %6 %5 %5 -%52 = OpConstant %5 1 -%63 = OpTypeFunction %6 %8 %5 -%70 = OpConstantComposite %8 %52 %52 -%79 = OpTypeFunction %6 %8 %5 %5 -%87 = OpConstantComposite %11 %52 %52 %52 -%95 = OpTypeFunction %6 %11 %5 -%102 = OpConstantComposite %11 %52 %52 %52 -%116 = OpConstantComposite %8 %52 %52 -%124 = OpTypeFunction %4 %8 %5 -%131 = OpConstantComposite %8 %52 %52 -%141 = OpTypeFunction %4 %8 %5 %5 -%149 = OpConstantComposite %11 %52 %52 %52 -%164 = OpConstantComposite %8 %52 %52 -%173 = OpTypeFunction %2 %5 %6 -%183 = OpTypeFunction %2 %8 %6 -%187 = OpConstantComposite %8 %52 %52 -%195 = OpTypeFunction %2 %8 %5 %6 -%200 = OpConstantComposite %11 %52 %52 %52 -%207 = OpTypeFunction %2 %11 %6 -%211 = OpConstantComposite %11 %52 %52 %52 -%47 = OpFunction %6 None %48 -%45 = OpFunctionParameter %5 -%46 = OpFunctionParameter %5 -%44 = OpLabel -%49 = OpLoad %3 %20 -OpBranch %50 -%50 = OpLabel -%51 = OpImageQueryLevels %5 %49 -%53 = OpISub %5 %51 %52 -%54 = OpExtInst %5 %1 UMin %46 %53 -%55 = OpImageQuerySizeLod %5 %49 %54 -%56 = OpISub %5 %55 %52 -%57 = OpExtInst %5 %1 UMin %45 %56 -%58 = OpImageFetch %6 %49 %57 Lod %54 -OpReturnValue %58 +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 0 +%6 = OpTypeFloat 32 +%5 = OpConstant %6 0.0 +%7 = OpTypeImage %6 1D 0 0 0 1 Unknown +%8 = OpTypeVector %6 4 +%9 = OpTypeImage %6 2D 0 0 0 1 Unknown +%10 = OpTypeVector %4 2 +%11 = OpTypeImage %6 2D 0 1 0 1 Unknown +%12 = OpTypeImage %6 3D 0 0 0 1 Unknown +%13 = OpTypeVector %4 3 +%14 = OpTypeImage %6 2D 0 0 1 1 Unknown +%15 = OpTypeImage %6 2D 1 0 0 1 Unknown +%16 = OpTypeImage %6 2D 1 1 0 1 Unknown +%17 = OpTypeImage %6 2D 1 0 1 1 Unknown +%18 = OpTypeImage %6 1D 0 0 0 2 Rgba8 +%19 = OpTypeImage %6 2D 0 0 0 2 Rgba8 +%20 = OpTypeImage %6 2D 0 1 0 2 Rgba8 +%21 = OpTypeImage %6 3D 0 0 0 2 Rgba8 +%22 = OpConstantComposite %10 %3 %3 +%23 = OpConstantComposite %13 %3 %3 %3 +%24 = OpConstantComposite %8 %5 %5 %5 %5 +%26 = OpTypePointer UniformConstant %7 +%25 = OpVariable %26 UniformConstant +%28 = OpTypePointer UniformConstant %9 +%27 = OpVariable %28 UniformConstant +%30 = OpTypePointer UniformConstant %11 +%29 = OpVariable %30 UniformConstant +%32 = OpTypePointer UniformConstant %12 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %14 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %15 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %16 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %17 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %18 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %19 +%43 = OpVariable %44 UniformConstant +%46 = OpTypePointer UniformConstant %20 +%45 = OpVariable %46 UniformConstant +%48 = OpTypePointer UniformConstant %21 +%47 = OpVariable %48 UniformConstant +%53 = OpTypeFunction %8 %4 %4 +%57 = OpConstant %4 1 +%68 = OpTypeFunction %8 %10 %4 +%75 = OpConstantComposite %10 %57 %57 +%84 = OpTypeFunction %8 %10 %4 %4 +%92 = OpConstantComposite %13 %57 %57 %57 +%100 = OpTypeFunction %8 %13 %4 +%107 = OpConstantComposite %13 %57 %57 %57 +%121 = OpConstantComposite %10 %57 %57 +%129 = OpTypeFunction %6 %10 %4 +%136 = OpConstantComposite %10 %57 %57 +%146 = OpTypeFunction %6 %10 %4 %4 +%154 = OpConstantComposite %13 %57 %57 %57 +%169 = OpConstantComposite %10 %57 %57 +%178 = OpTypeFunction %2 %4 %8 +%188 = OpTypeFunction %2 %10 %8 +%192 = OpConstantComposite %10 %57 %57 +%200 = OpTypeFunction %2 %10 %4 %8 +%205 = OpConstantComposite %13 %57 %57 %57 +%212 = OpTypeFunction %2 %13 %8 +%216 = OpConstantComposite %13 %57 %57 %57 +%221 = OpTypePointer Output %8 +%220 = OpVariable %221 Output +%223 = OpTypeFunction %2 +%52 = OpFunction %8 None %53 +%50 = OpFunctionParameter %4 +%51 = OpFunctionParameter %4 +%49 = OpLabel +%54 = OpLoad %7 %25 +OpBranch %55 +%55 = OpLabel +%56 = OpImageQueryLevels %4 %54 +%58 = OpISub %4 %56 %57 +%59 = OpExtInst %4 %1 UMin %51 %58 +%60 = OpImageQuerySizeLod %4 %54 %59 +%61 = OpISub %4 %60 %57 +%62 = OpExtInst %4 %1 UMin %50 %61 +%63 = OpImageFetch %8 %54 %62 Lod %59 +OpReturnValue %63 OpFunctionEnd -%62 = OpFunction %6 None %63 -%60 = OpFunctionParameter %8 -%61 = OpFunctionParameter %5 -%59 = OpLabel -%64 = OpLoad %7 %22 -OpBranch %65 -%65 = OpLabel -%66 = OpImageQueryLevels %5 %64 -%67 = OpISub %5 %66 %52 -%68 = OpExtInst %5 %1 UMin %61 %67 -%69 = OpImageQuerySizeLod %8 %64 %68 -%71 = OpISub %8 %69 %70 -%72 = OpExtInst %8 %1 UMin %60 %71 -%73 = OpImageFetch %6 %64 %72 Lod %68 -OpReturnValue %73 +%67 = OpFunction %8 None %68 +%65 = OpFunctionParameter %10 +%66 = OpFunctionParameter %4 +%64 = OpLabel +%69 = OpLoad %9 %27 +OpBranch %70 +%70 = OpLabel +%71 = OpImageQueryLevels %4 %69 +%72 = OpISub %4 %71 %57 +%73 = OpExtInst %4 %1 UMin %66 %72 +%74 = OpImageQuerySizeLod %10 %69 %73 +%76 = OpISub %10 %74 %75 +%77 = OpExtInst %10 %1 UMin %65 %76 +%78 = OpImageFetch %8 %69 %77 Lod %73 +OpReturnValue %78 OpFunctionEnd -%78 = OpFunction %6 None %79 -%75 = OpFunctionParameter %8 -%76 = OpFunctionParameter %5 -%77 = OpFunctionParameter %5 -%74 = OpLabel -%80 = OpLoad %9 %24 -OpBranch %81 -%81 = OpLabel -%82 = OpCompositeConstruct %11 %75 %76 -%83 = OpImageQueryLevels %5 %80 -%84 = OpISub %5 %83 %52 -%85 = OpExtInst %5 %1 UMin %77 %84 -%86 = OpImageQuerySizeLod %11 %80 %85 -%88 = OpISub %11 %86 %87 -%89 = OpExtInst %11 %1 UMin %82 %88 -%90 = OpImageFetch %6 %80 %89 Lod %85 -OpReturnValue %90 +%83 = OpFunction %8 None %84 +%80 = OpFunctionParameter %10 +%81 = OpFunctionParameter %4 +%82 = OpFunctionParameter %4 +%79 = OpLabel +%85 = OpLoad %11 %29 +OpBranch %86 +%86 = OpLabel +%87 = OpCompositeConstruct %13 %80 %81 +%88 = OpImageQueryLevels %4 %85 +%89 = OpISub %4 %88 %57 +%90 = OpExtInst %4 %1 UMin %82 %89 +%91 = OpImageQuerySizeLod %13 %85 %90 +%93 = OpISub %13 %91 %92 +%94 = OpExtInst %13 %1 UMin %87 %93 +%95 = OpImageFetch %8 %85 %94 Lod %90 +OpReturnValue %95 OpFunctionEnd -%94 = OpFunction %6 None %95 -%92 = OpFunctionParameter %11 -%93 = OpFunctionParameter %5 -%91 = OpLabel -%96 = OpLoad %10 %26 -OpBranch %97 -%97 = OpLabel -%98 = OpImageQueryLevels %5 %96 -%99 = OpISub %5 %98 %52 -%100 = OpExtInst %5 %1 UMin %93 %99 -%101 = OpImageQuerySizeLod %11 %96 %100 -%103 = OpISub %11 %101 %102 -%104 = OpExtInst %11 %1 UMin %92 %103 -%105 = OpImageFetch %6 %96 %104 Lod %100 -OpReturnValue %105 +%99 = OpFunction %8 None %100 +%97 = OpFunctionParameter %13 +%98 = OpFunctionParameter %4 +%96 = OpLabel +%101 = OpLoad %12 %31 +OpBranch %102 +%102 = OpLabel +%103 = OpImageQueryLevels %4 %101 +%104 = OpISub %4 %103 %57 +%105 = OpExtInst %4 %1 UMin %98 %104 +%106 = OpImageQuerySizeLod %13 %101 %105 +%108 = OpISub %13 %106 %107 +%109 = OpExtInst %13 %1 UMin %97 %108 +%110 = OpImageFetch %8 %101 %109 Lod %105 +OpReturnValue %110 OpFunctionEnd -%109 = OpFunction %6 None %63 -%107 = OpFunctionParameter %8 -%108 = OpFunctionParameter %5 -%106 = OpLabel -%110 = OpLoad %12 %28 -OpBranch %111 +%114 = OpFunction %8 None %68 +%112 = OpFunctionParameter %10 +%113 = OpFunctionParameter %4 %111 = OpLabel -%112 = OpImageQuerySamples %5 %110 -%113 = OpISub %5 %112 %52 -%114 = OpExtInst %5 %1 UMin %108 %113 -%115 = OpImageQuerySize %8 %110 -%117 = OpISub %8 %115 %116 -%118 = OpExtInst %8 %1 UMin %107 %117 -%119 = OpImageFetch %6 %110 %118 Sample %114 -OpReturnValue %119 +%115 = OpLoad %14 %33 +OpBranch %116 +%116 = OpLabel +%117 = OpImageQuerySamples %4 %115 +%118 = OpISub %4 %117 %57 +%119 = OpExtInst %4 %1 UMin %113 %118 +%120 = OpImageQuerySize %10 %115 +%122 = OpISub %10 %120 %121 +%123 = OpExtInst %10 %1 UMin %112 %122 +%124 = OpImageFetch %8 %115 %123 Sample %119 +OpReturnValue %124 OpFunctionEnd -%123 = OpFunction %4 None %124 -%121 = OpFunctionParameter %8 -%122 = OpFunctionParameter %5 -%120 = OpLabel -%125 = OpLoad %13 %30 -OpBranch %126 -%126 = OpLabel -%127 = OpImageQueryLevels %5 %125 -%128 = OpISub %5 %127 %52 -%129 = OpExtInst %5 %1 UMin %122 %128 -%130 = OpImageQuerySizeLod %8 %125 %129 -%132 = OpISub %8 %130 %131 -%133 = OpExtInst %8 %1 UMin %121 %132 -%134 = OpImageFetch %6 %125 %133 Lod %129 -%135 = OpCompositeExtract %4 %134 0 -OpReturnValue %135 +%128 = OpFunction %6 None %129 +%126 = OpFunctionParameter %10 +%127 = OpFunctionParameter %4 +%125 = OpLabel +%130 = OpLoad %15 %35 +OpBranch %131 +%131 = OpLabel +%132 = OpImageQueryLevels %4 %130 +%133 = OpISub %4 %132 %57 +%134 = OpExtInst %4 %1 UMin %127 %133 +%135 = OpImageQuerySizeLod %10 %130 %134 +%137 = OpISub %10 %135 %136 +%138 = OpExtInst %10 %1 UMin %126 %137 +%139 = OpImageFetch %8 %130 %138 Lod %134 +%140 = OpCompositeExtract %6 %139 0 +OpReturnValue %140 OpFunctionEnd -%140 = OpFunction %4 None %141 -%137 = OpFunctionParameter %8 -%138 = OpFunctionParameter %5 -%139 = OpFunctionParameter %5 -%136 = OpLabel -%142 = OpLoad %14 %32 -OpBranch %143 -%143 = OpLabel -%144 = OpCompositeConstruct %11 %137 %138 -%145 = OpImageQueryLevels %5 %142 -%146 = OpISub %5 %145 %52 -%147 = OpExtInst %5 %1 UMin %139 %146 -%148 = OpImageQuerySizeLod %11 %142 %147 -%150 = OpISub %11 %148 %149 -%151 = OpExtInst %11 %1 UMin %144 %150 -%152 = OpImageFetch %6 %142 %151 Lod %147 -%153 = OpCompositeExtract %4 %152 0 -OpReturnValue %153 +%145 = OpFunction %6 None %146 +%142 = OpFunctionParameter %10 +%143 = OpFunctionParameter %4 +%144 = OpFunctionParameter %4 +%141 = OpLabel +%147 = OpLoad %16 %37 +OpBranch %148 +%148 = OpLabel +%149 = OpCompositeConstruct %13 %142 %143 +%150 = OpImageQueryLevels %4 %147 +%151 = OpISub %4 %150 %57 +%152 = OpExtInst %4 %1 UMin %144 %151 +%153 = OpImageQuerySizeLod %13 %147 %152 +%155 = OpISub %13 %153 %154 +%156 = OpExtInst %13 %1 UMin %149 %155 +%157 = OpImageFetch %8 %147 %156 Lod %152 +%158 = OpCompositeExtract %6 %157 0 +OpReturnValue %158 OpFunctionEnd -%157 = OpFunction %4 None %124 -%155 = OpFunctionParameter %8 -%156 = OpFunctionParameter %5 -%154 = OpLabel -%158 = OpLoad %15 %34 -OpBranch %159 +%162 = OpFunction %6 None %129 +%160 = OpFunctionParameter %10 +%161 = OpFunctionParameter %4 %159 = OpLabel -%160 = OpImageQuerySamples %5 %158 -%161 = OpISub %5 %160 %52 -%162 = OpExtInst %5 %1 UMin %156 %161 -%163 = OpImageQuerySize %8 %158 -%165 = OpISub %8 %163 %164 -%166 = OpExtInst %8 %1 UMin %155 %165 -%167 = OpImageFetch %6 %158 %166 Sample %162 -%168 = OpCompositeExtract %4 %167 0 -OpReturnValue %168 +%163 = OpLoad %17 %39 +OpBranch %164 +%164 = OpLabel +%165 = OpImageQuerySamples %4 %163 +%166 = OpISub %4 %165 %57 +%167 = OpExtInst %4 %1 UMin %161 %166 +%168 = OpImageQuerySize %10 %163 +%170 = OpISub %10 %168 %169 +%171 = OpExtInst %10 %1 UMin %160 %170 +%172 = OpImageFetch %8 %163 %171 Sample %167 +%173 = OpCompositeExtract %6 %172 0 +OpReturnValue %173 OpFunctionEnd -%172 = OpFunction %2 None %173 -%170 = OpFunctionParameter %5 -%171 = OpFunctionParameter %6 -%169 = OpLabel -%174 = OpLoad %16 %36 -OpBranch %175 -%175 = OpLabel -%176 = OpImageQuerySize %5 %174 -%177 = OpISub %5 %176 %52 -%178 = OpExtInst %5 %1 UMin %170 %177 -OpImageWrite %174 %178 %171 +%177 = OpFunction %2 None %178 +%175 = OpFunctionParameter %4 +%176 = OpFunctionParameter %8 +%174 = OpLabel +%179 = OpLoad %18 %41 +OpBranch %180 +%180 = OpLabel +%181 = OpImageQuerySize %4 %179 +%182 = OpISub %4 %181 %57 +%183 = OpExtInst %4 %1 UMin %175 %182 +OpImageWrite %179 %183 %176 OpReturn OpFunctionEnd -%182 = OpFunction %2 None %183 -%180 = OpFunctionParameter %8 -%181 = OpFunctionParameter %6 -%179 = OpLabel -%184 = OpLoad %17 %38 -OpBranch %185 -%185 = OpLabel -%186 = OpImageQuerySize %8 %184 -%188 = OpISub %8 %186 %187 -%189 = OpExtInst %8 %1 UMin %180 %188 -OpImageWrite %184 %189 %181 -OpReturn -OpFunctionEnd -%194 = OpFunction %2 None %195 -%191 = OpFunctionParameter %8 -%192 = OpFunctionParameter %5 -%193 = OpFunctionParameter %6 +%187 = OpFunction %2 None %188 +%185 = OpFunctionParameter %10 +%186 = OpFunctionParameter %8 +%184 = OpLabel +%189 = OpLoad %19 %43 +OpBranch %190 %190 = OpLabel -%196 = OpLoad %18 %40 -OpBranch %197 -%197 = OpLabel -%198 = OpCompositeConstruct %11 %191 %192 -%199 = OpImageQuerySize %11 %196 -%201 = OpISub %11 %199 %200 -%202 = OpExtInst %11 %1 UMin %198 %201 -OpImageWrite %196 %202 %193 +%191 = OpImageQuerySize %10 %189 +%193 = OpISub %10 %191 %192 +%194 = OpExtInst %10 %1 UMin %185 %193 +OpImageWrite %189 %194 %186 OpReturn OpFunctionEnd -%206 = OpFunction %2 None %207 -%204 = OpFunctionParameter %11 -%205 = OpFunctionParameter %6 -%203 = OpLabel -%208 = OpLoad %19 %42 -OpBranch %209 -%209 = OpLabel -%210 = OpImageQuerySize %11 %208 -%212 = OpISub %11 %210 %211 -%213 = OpExtInst %11 %1 UMin %204 %212 -OpImageWrite %208 %213 %205 +%199 = OpFunction %2 None %200 +%196 = OpFunctionParameter %10 +%197 = OpFunctionParameter %4 +%198 = OpFunctionParameter %8 +%195 = OpLabel +%201 = OpLoad %20 %45 +OpBranch %202 +%202 = OpLabel +%203 = OpCompositeConstruct %13 %196 %197 +%204 = OpImageQuerySize %13 %201 +%206 = OpISub %13 %204 %205 +%207 = OpExtInst %13 %1 UMin %203 %206 +OpImageWrite %201 %207 %198 +OpReturn +OpFunctionEnd +%211 = OpFunction %2 None %212 +%209 = OpFunctionParameter %13 +%210 = OpFunctionParameter %8 +%208 = OpLabel +%213 = OpLoad %21 %47 +OpBranch %214 +%214 = OpLabel +%215 = OpImageQuerySize %13 %213 +%217 = OpISub %13 %215 %216 +%218 = OpExtInst %13 %1 UMin %209 %217 +OpImageWrite %213 %218 %210 +OpReturn +OpFunctionEnd +%222 = OpFunction %2 None %223 +%219 = OpLabel +%224 = OpLoad %7 %25 +%225 = OpLoad %9 %27 +%226 = OpLoad %11 %29 +%227 = OpLoad %12 %31 +%228 = OpLoad %14 %33 +%229 = OpLoad %18 %41 +%230 = OpLoad %19 %43 +%231 = OpLoad %20 %45 +%232 = OpLoad %21 %47 +OpBranch %233 +%233 = OpLabel +%234 = OpFunctionCall %8 %52 %3 %3 +%235 = OpFunctionCall %8 %67 %22 %3 +%236 = OpFunctionCall %8 %83 %22 %3 %3 +%237 = OpFunctionCall %8 %99 %23 %3 +%238 = OpFunctionCall %8 %114 %22 %3 +%239 = OpFunctionCall %2 %177 %3 %24 +%240 = OpFunctionCall %2 %187 %22 %24 +%241 = OpFunctionCall %2 %199 %22 %3 %24 +%242 = OpFunctionCall %2 %211 %23 %24 +%243 = OpCompositeConstruct %8 %5 %5 %5 %5 +OpStore %220 %243 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index 981355a41..3c8e79009 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -1,417 +1,454 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 244 +; Bound: 274 OpCapability ImageQuery OpCapability Image1D OpCapability Shader OpCapability Sampled1D -OpCapability Linkage %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %252 "fragment_shader" %250 +OpExecutionMode %252 OriginUpperLeft OpSource GLSL 450 -OpName %20 "image_1d" -OpName %22 "image_2d" -OpName %24 "image_2d_array" -OpName %26 "image_3d" -OpName %28 "image_multisampled_2d" -OpName %30 "image_depth_2d" -OpName %32 "image_depth_2d_array" -OpName %34 "image_depth_multisampled_2d" -OpName %36 "image_storage_1d" -OpName %38 "image_storage_2d" -OpName %40 "image_storage_2d_array" -OpName %42 "image_storage_3d" -OpName %45 "coords" -OpName %46 "level" -OpName %47 "test_textureLoad_1d" -OpName %63 "coords" -OpName %64 "level" -OpName %65 "test_textureLoad_2d" -OpName %82 "coords" -OpName %83 "index" -OpName %84 "level" -OpName %85 "test_textureLoad_2d_array" -OpName %103 "coords" -OpName %104 "level" -OpName %105 "test_textureLoad_3d" -OpName %121 "coords" -OpName %122 "_sample" -OpName %123 "test_textureLoad_multisampled_2d" -OpName %138 "coords" -OpName %139 "level" -OpName %140 "test_textureLoad_depth_2d" -OpName %157 "coords" -OpName %158 "index" -OpName %159 "level" -OpName %160 "test_textureLoad_depth_2d_array" -OpName %178 "coords" -OpName %179 "_sample" -OpName %180 "test_textureLoad_depth_multisampled_2d" -OpName %196 "coords" -OpName %197 "value" -OpName %198 "test_textureStore_1d" -OpName %207 "coords" -OpName %208 "value" -OpName %209 "test_textureStore_2d" -OpName %219 "coords" -OpName %220 "array_index" -OpName %221 "value" -OpName %222 "test_textureStore_2d_array" -OpName %233 "coords" -OpName %234 "value" -OpName %235 "test_textureStore_3d" -OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 0 -OpDecorate %22 DescriptorSet 0 -OpDecorate %22 Binding 0 -OpDecorate %24 DescriptorSet 0 -OpDecorate %24 Binding 0 -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 0 -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 0 -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 0 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 0 -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 0 -OpDecorate %36 NonReadable -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 0 -OpDecorate %38 NonReadable -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 0 -OpDecorate %40 NonReadable -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 0 -OpDecorate %42 NonReadable -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 0 +OpName %25 "image_1d" +OpName %27 "image_2d" +OpName %29 "image_2d_array" +OpName %31 "image_3d" +OpName %33 "image_multisampled_2d" +OpName %35 "image_depth_2d" +OpName %37 "image_depth_2d_array" +OpName %39 "image_depth_multisampled_2d" +OpName %41 "image_storage_1d" +OpName %43 "image_storage_2d" +OpName %45 "image_storage_2d_array" +OpName %47 "image_storage_3d" +OpName %50 "coords" +OpName %51 "level" +OpName %52 "test_textureLoad_1d" +OpName %68 "coords" +OpName %69 "level" +OpName %70 "test_textureLoad_2d" +OpName %87 "coords" +OpName %88 "index" +OpName %89 "level" +OpName %90 "test_textureLoad_2d_array" +OpName %108 "coords" +OpName %109 "level" +OpName %110 "test_textureLoad_3d" +OpName %126 "coords" +OpName %127 "_sample" +OpName %128 "test_textureLoad_multisampled_2d" +OpName %143 "coords" +OpName %144 "level" +OpName %145 "test_textureLoad_depth_2d" +OpName %162 "coords" +OpName %163 "index" +OpName %164 "level" +OpName %165 "test_textureLoad_depth_2d_array" +OpName %183 "coords" +OpName %184 "_sample" +OpName %185 "test_textureLoad_depth_multisampled_2d" +OpName %201 "coords" +OpName %202 "value" +OpName %203 "test_textureStore_1d" +OpName %212 "coords" +OpName %213 "value" +OpName %214 "test_textureStore_2d" +OpName %224 "coords" +OpName %225 "array_index" +OpName %226 "value" +OpName %227 "test_textureStore_2d_array" +OpName %238 "coords" +OpName %239 "value" +OpName %240 "test_textureStore_3d" +OpName %252 "fragment_shader" +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 0 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 1 +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 2 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 3 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 4 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 5 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 6 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 7 +OpDecorate %41 NonReadable +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 8 +OpDecorate %43 NonReadable +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 9 +OpDecorate %45 NonReadable +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 10 +OpDecorate %47 NonReadable +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 11 +OpDecorate %250 Location 0 %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpTypeImage %4 1D 0 0 0 1 Unknown -%5 = OpTypeInt 32 1 -%6 = OpTypeVector %4 4 -%7 = OpTypeImage %4 2D 0 0 0 1 Unknown -%8 = OpTypeVector %5 2 -%9 = OpTypeImage %4 2D 0 1 0 1 Unknown -%10 = OpTypeImage %4 3D 0 0 0 1 Unknown -%11 = OpTypeVector %5 3 -%12 = OpTypeImage %4 2D 0 0 1 1 Unknown -%13 = OpTypeImage %4 2D 1 0 0 1 Unknown -%14 = OpTypeImage %4 2D 1 1 0 1 Unknown -%15 = OpTypeImage %4 2D 1 0 1 1 Unknown -%16 = OpTypeImage %4 1D 0 0 0 2 Rgba8 -%17 = OpTypeImage %4 2D 0 0 0 2 Rgba8 -%18 = OpTypeImage %4 2D 0 1 0 2 Rgba8 -%19 = OpTypeImage %4 3D 0 0 0 2 Rgba8 -%21 = OpTypePointer UniformConstant %3 -%20 = OpVariable %21 UniformConstant -%23 = OpTypePointer UniformConstant %7 -%22 = OpVariable %23 UniformConstant -%25 = OpTypePointer UniformConstant %9 -%24 = OpVariable %25 UniformConstant -%27 = OpTypePointer UniformConstant %10 -%26 = OpVariable %27 UniformConstant -%29 = OpTypePointer UniformConstant %12 -%28 = OpVariable %29 UniformConstant -%31 = OpTypePointer UniformConstant %13 -%30 = OpVariable %31 UniformConstant -%33 = OpTypePointer UniformConstant %14 -%32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %15 -%34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %16 -%36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %17 -%38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %18 -%40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %19 -%42 = OpVariable %43 UniformConstant -%48 = OpTypeFunction %6 %5 %5 -%51 = OpTypeBool -%52 = OpConstantNull %6 -%66 = OpTypeFunction %6 %8 %5 -%69 = OpConstantNull %6 -%75 = OpTypeVector %51 2 -%86 = OpTypeFunction %6 %8 %5 %5 -%90 = OpConstantNull %6 -%96 = OpTypeVector %51 3 -%106 = OpTypeFunction %6 %11 %5 -%109 = OpConstantNull %6 -%126 = OpConstantNull %6 -%141 = OpTypeFunction %4 %8 %5 -%144 = OpConstantNull %6 -%161 = OpTypeFunction %4 %8 %5 %5 -%165 = OpConstantNull %6 -%183 = OpConstantNull %6 -%199 = OpTypeFunction %2 %5 %6 -%210 = OpTypeFunction %2 %8 %6 -%223 = OpTypeFunction %2 %8 %5 %6 -%236 = OpTypeFunction %2 %11 %6 -%47 = OpFunction %6 None %48 -%45 = OpFunctionParameter %5 -%46 = OpFunctionParameter %5 -%44 = OpLabel -%49 = OpLoad %3 %20 -OpBranch %50 -%50 = OpLabel -%53 = OpImageQueryLevels %5 %49 -%54 = OpULessThan %51 %46 %53 -OpSelectionMerge %55 None -OpBranchConditional %54 %56 %55 -%56 = OpLabel -%57 = OpImageQuerySizeLod %5 %49 %46 -%58 = OpULessThan %51 %45 %57 -OpBranchConditional %58 %59 %55 -%59 = OpLabel -%60 = OpImageFetch %6 %49 %45 Lod %46 +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 0 +%6 = OpTypeFloat 32 +%5 = OpConstant %6 0.0 +%7 = OpTypeImage %6 1D 0 0 0 1 Unknown +%8 = OpTypeVector %6 4 +%9 = OpTypeImage %6 2D 0 0 0 1 Unknown +%10 = OpTypeVector %4 2 +%11 = OpTypeImage %6 2D 0 1 0 1 Unknown +%12 = OpTypeImage %6 3D 0 0 0 1 Unknown +%13 = OpTypeVector %4 3 +%14 = OpTypeImage %6 2D 0 0 1 1 Unknown +%15 = OpTypeImage %6 2D 1 0 0 1 Unknown +%16 = OpTypeImage %6 2D 1 1 0 1 Unknown +%17 = OpTypeImage %6 2D 1 0 1 1 Unknown +%18 = OpTypeImage %6 1D 0 0 0 2 Rgba8 +%19 = OpTypeImage %6 2D 0 0 0 2 Rgba8 +%20 = OpTypeImage %6 2D 0 1 0 2 Rgba8 +%21 = OpTypeImage %6 3D 0 0 0 2 Rgba8 +%22 = OpConstantComposite %10 %3 %3 +%23 = OpConstantComposite %13 %3 %3 %3 +%24 = OpConstantComposite %8 %5 %5 %5 %5 +%26 = OpTypePointer UniformConstant %7 +%25 = OpVariable %26 UniformConstant +%28 = OpTypePointer UniformConstant %9 +%27 = OpVariable %28 UniformConstant +%30 = OpTypePointer UniformConstant %11 +%29 = OpVariable %30 UniformConstant +%32 = OpTypePointer UniformConstant %12 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %14 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %15 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %16 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %17 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %18 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %19 +%43 = OpVariable %44 UniformConstant +%46 = OpTypePointer UniformConstant %20 +%45 = OpVariable %46 UniformConstant +%48 = OpTypePointer UniformConstant %21 +%47 = OpVariable %48 UniformConstant +%53 = OpTypeFunction %8 %4 %4 +%56 = OpTypeBool +%57 = OpConstantNull %8 +%71 = OpTypeFunction %8 %10 %4 +%74 = OpConstantNull %8 +%80 = OpTypeVector %56 2 +%91 = OpTypeFunction %8 %10 %4 %4 +%95 = OpConstantNull %8 +%101 = OpTypeVector %56 3 +%111 = OpTypeFunction %8 %13 %4 +%114 = OpConstantNull %8 +%131 = OpConstantNull %8 +%146 = OpTypeFunction %6 %10 %4 +%149 = OpConstantNull %8 +%166 = OpTypeFunction %6 %10 %4 %4 +%170 = OpConstantNull %8 +%188 = OpConstantNull %8 +%204 = OpTypeFunction %2 %4 %8 +%215 = OpTypeFunction %2 %10 %8 +%228 = OpTypeFunction %2 %10 %4 %8 +%241 = OpTypeFunction %2 %13 %8 +%251 = OpTypePointer Output %8 +%250 = OpVariable %251 Output +%253 = OpTypeFunction %2 +%52 = OpFunction %8 None %53 +%50 = OpFunctionParameter %4 +%51 = OpFunctionParameter %4 +%49 = OpLabel +%54 = OpLoad %7 %25 OpBranch %55 %55 = OpLabel -%61 = OpPhi %6 %52 %50 %52 %56 %60 %59 -OpReturnValue %61 +%58 = OpImageQueryLevels %4 %54 +%59 = OpULessThan %56 %51 %58 +OpSelectionMerge %60 None +OpBranchConditional %59 %61 %60 +%61 = OpLabel +%62 = OpImageQuerySizeLod %4 %54 %51 +%63 = OpULessThan %56 %50 %62 +OpBranchConditional %63 %64 %60 +%64 = OpLabel +%65 = OpImageFetch %8 %54 %50 Lod %51 +OpBranch %60 +%60 = OpLabel +%66 = OpPhi %8 %57 %55 %57 %61 %65 %64 +OpReturnValue %66 OpFunctionEnd -%65 = OpFunction %6 None %66 -%63 = OpFunctionParameter %8 -%64 = OpFunctionParameter %5 -%62 = OpLabel -%67 = OpLoad %7 %22 -OpBranch %68 -%68 = OpLabel -%70 = OpImageQueryLevels %5 %67 -%71 = OpULessThan %51 %64 %70 -OpSelectionMerge %72 None -OpBranchConditional %71 %73 %72 +%70 = OpFunction %8 None %71 +%68 = OpFunctionParameter %10 +%69 = OpFunctionParameter %4 +%67 = OpLabel +%72 = OpLoad %9 %27 +OpBranch %73 %73 = OpLabel -%74 = OpImageQuerySizeLod %8 %67 %64 -%76 = OpULessThan %75 %63 %74 -%77 = OpAll %51 %76 -OpBranchConditional %77 %78 %72 +%75 = OpImageQueryLevels %4 %72 +%76 = OpULessThan %56 %69 %75 +OpSelectionMerge %77 None +OpBranchConditional %76 %78 %77 %78 = OpLabel -%79 = OpImageFetch %6 %67 %63 Lod %64 -OpBranch %72 -%72 = OpLabel -%80 = OpPhi %6 %69 %68 %69 %73 %79 %78 -OpReturnValue %80 +%79 = OpImageQuerySizeLod %10 %72 %69 +%81 = OpULessThan %80 %68 %79 +%82 = OpAll %56 %81 +OpBranchConditional %82 %83 %77 +%83 = OpLabel +%84 = OpImageFetch %8 %72 %68 Lod %69 +OpBranch %77 +%77 = OpLabel +%85 = OpPhi %8 %74 %73 %74 %78 %84 %83 +OpReturnValue %85 OpFunctionEnd -%85 = OpFunction %6 None %86 -%82 = OpFunctionParameter %8 -%83 = OpFunctionParameter %5 -%84 = OpFunctionParameter %5 -%81 = OpLabel -%87 = OpLoad %9 %24 -OpBranch %88 -%88 = OpLabel -%89 = OpCompositeConstruct %11 %82 %83 -%91 = OpImageQueryLevels %5 %87 -%92 = OpULessThan %51 %84 %91 -OpSelectionMerge %93 None -OpBranchConditional %92 %94 %93 -%94 = OpLabel -%95 = OpImageQuerySizeLod %11 %87 %84 -%97 = OpULessThan %96 %89 %95 -%98 = OpAll %51 %97 -OpBranchConditional %98 %99 %93 -%99 = OpLabel -%100 = OpImageFetch %6 %87 %89 Lod %84 +%90 = OpFunction %8 None %91 +%87 = OpFunctionParameter %10 +%88 = OpFunctionParameter %4 +%89 = OpFunctionParameter %4 +%86 = OpLabel +%92 = OpLoad %11 %29 OpBranch %93 %93 = OpLabel -%101 = OpPhi %6 %90 %88 %90 %94 %100 %99 -OpReturnValue %101 +%94 = OpCompositeConstruct %13 %87 %88 +%96 = OpImageQueryLevels %4 %92 +%97 = OpULessThan %56 %89 %96 +OpSelectionMerge %98 None +OpBranchConditional %97 %99 %98 +%99 = OpLabel +%100 = OpImageQuerySizeLod %13 %92 %89 +%102 = OpULessThan %101 %94 %100 +%103 = OpAll %56 %102 +OpBranchConditional %103 %104 %98 +%104 = OpLabel +%105 = OpImageFetch %8 %92 %94 Lod %89 +OpBranch %98 +%98 = OpLabel +%106 = OpPhi %8 %95 %93 %95 %99 %105 %104 +OpReturnValue %106 OpFunctionEnd -%105 = OpFunction %6 None %106 -%103 = OpFunctionParameter %11 -%104 = OpFunctionParameter %5 -%102 = OpLabel -%107 = OpLoad %10 %26 -OpBranch %108 -%108 = OpLabel -%110 = OpImageQueryLevels %5 %107 -%111 = OpULessThan %51 %104 %110 -OpSelectionMerge %112 None -OpBranchConditional %111 %113 %112 +%110 = OpFunction %8 None %111 +%108 = OpFunctionParameter %13 +%109 = OpFunctionParameter %4 +%107 = OpLabel +%112 = OpLoad %12 %31 +OpBranch %113 %113 = OpLabel -%114 = OpImageQuerySizeLod %11 %107 %104 -%115 = OpULessThan %96 %103 %114 -%116 = OpAll %51 %115 -OpBranchConditional %116 %117 %112 +%115 = OpImageQueryLevels %4 %112 +%116 = OpULessThan %56 %109 %115 +OpSelectionMerge %117 None +OpBranchConditional %116 %118 %117 +%118 = OpLabel +%119 = OpImageQuerySizeLod %13 %112 %109 +%120 = OpULessThan %101 %108 %119 +%121 = OpAll %56 %120 +OpBranchConditional %121 %122 %117 +%122 = OpLabel +%123 = OpImageFetch %8 %112 %108 Lod %109 +OpBranch %117 %117 = OpLabel -%118 = OpImageFetch %6 %107 %103 Lod %104 -OpBranch %112 -%112 = OpLabel -%119 = OpPhi %6 %109 %108 %109 %113 %118 %117 -OpReturnValue %119 +%124 = OpPhi %8 %114 %113 %114 %118 %123 %122 +OpReturnValue %124 OpFunctionEnd -%123 = OpFunction %6 None %66 -%121 = OpFunctionParameter %8 -%122 = OpFunctionParameter %5 -%120 = OpLabel -%124 = OpLoad %12 %28 -OpBranch %125 +%128 = OpFunction %8 None %71 +%126 = OpFunctionParameter %10 +%127 = OpFunctionParameter %4 %125 = OpLabel -%127 = OpImageQuerySamples %5 %124 -%128 = OpULessThan %51 %122 %127 -OpSelectionMerge %129 None -OpBranchConditional %128 %130 %129 +%129 = OpLoad %14 %33 +OpBranch %130 %130 = OpLabel -%131 = OpImageQuerySize %8 %124 -%132 = OpULessThan %75 %121 %131 -%133 = OpAll %51 %132 -OpBranchConditional %133 %134 %129 +%132 = OpImageQuerySamples %4 %129 +%133 = OpULessThan %56 %127 %132 +OpSelectionMerge %134 None +OpBranchConditional %133 %135 %134 +%135 = OpLabel +%136 = OpImageQuerySize %10 %129 +%137 = OpULessThan %80 %126 %136 +%138 = OpAll %56 %137 +OpBranchConditional %138 %139 %134 +%139 = OpLabel +%140 = OpImageFetch %8 %129 %126 Sample %127 +OpBranch %134 %134 = OpLabel -%135 = OpImageFetch %6 %124 %121 Sample %122 -OpBranch %129 -%129 = OpLabel -%136 = OpPhi %6 %126 %125 %126 %130 %135 %134 -OpReturnValue %136 +%141 = OpPhi %8 %131 %130 %131 %135 %140 %139 +OpReturnValue %141 OpFunctionEnd -%140 = OpFunction %4 None %141 -%138 = OpFunctionParameter %8 -%139 = OpFunctionParameter %5 -%137 = OpLabel -%142 = OpLoad %13 %30 -OpBranch %143 -%143 = OpLabel -%145 = OpImageQueryLevels %5 %142 -%146 = OpULessThan %51 %139 %145 -OpSelectionMerge %147 None -OpBranchConditional %146 %148 %147 +%145 = OpFunction %6 None %146 +%143 = OpFunctionParameter %10 +%144 = OpFunctionParameter %4 +%142 = OpLabel +%147 = OpLoad %15 %35 +OpBranch %148 %148 = OpLabel -%149 = OpImageQuerySizeLod %8 %142 %139 -%150 = OpULessThan %75 %138 %149 -%151 = OpAll %51 %150 -OpBranchConditional %151 %152 %147 +%150 = OpImageQueryLevels %4 %147 +%151 = OpULessThan %56 %144 %150 +OpSelectionMerge %152 None +OpBranchConditional %151 %153 %152 +%153 = OpLabel +%154 = OpImageQuerySizeLod %10 %147 %144 +%155 = OpULessThan %80 %143 %154 +%156 = OpAll %56 %155 +OpBranchConditional %156 %157 %152 +%157 = OpLabel +%158 = OpImageFetch %8 %147 %143 Lod %144 +OpBranch %152 %152 = OpLabel -%153 = OpImageFetch %6 %142 %138 Lod %139 -OpBranch %147 -%147 = OpLabel -%154 = OpPhi %6 %144 %143 %144 %148 %153 %152 -%155 = OpCompositeExtract %4 %154 0 -OpReturnValue %155 +%159 = OpPhi %8 %149 %148 %149 %153 %158 %157 +%160 = OpCompositeExtract %6 %159 0 +OpReturnValue %160 OpFunctionEnd -%160 = OpFunction %4 None %161 -%157 = OpFunctionParameter %8 -%158 = OpFunctionParameter %5 -%159 = OpFunctionParameter %5 -%156 = OpLabel -%162 = OpLoad %14 %32 -OpBranch %163 -%163 = OpLabel -%164 = OpCompositeConstruct %11 %157 %158 -%166 = OpImageQueryLevels %5 %162 -%167 = OpULessThan %51 %159 %166 -OpSelectionMerge %168 None -OpBranchConditional %167 %169 %168 -%169 = OpLabel -%170 = OpImageQuerySizeLod %11 %162 %159 -%171 = OpULessThan %96 %164 %170 -%172 = OpAll %51 %171 -OpBranchConditional %172 %173 %168 -%173 = OpLabel -%174 = OpImageFetch %6 %162 %164 Lod %159 +%165 = OpFunction %6 None %166 +%162 = OpFunctionParameter %10 +%163 = OpFunctionParameter %4 +%164 = OpFunctionParameter %4 +%161 = OpLabel +%167 = OpLoad %16 %37 OpBranch %168 %168 = OpLabel -%175 = OpPhi %6 %165 %163 %165 %169 %174 %173 -%176 = OpCompositeExtract %4 %175 0 -OpReturnValue %176 +%169 = OpCompositeConstruct %13 %162 %163 +%171 = OpImageQueryLevels %4 %167 +%172 = OpULessThan %56 %164 %171 +OpSelectionMerge %173 None +OpBranchConditional %172 %174 %173 +%174 = OpLabel +%175 = OpImageQuerySizeLod %13 %167 %164 +%176 = OpULessThan %101 %169 %175 +%177 = OpAll %56 %176 +OpBranchConditional %177 %178 %173 +%178 = OpLabel +%179 = OpImageFetch %8 %167 %169 Lod %164 +OpBranch %173 +%173 = OpLabel +%180 = OpPhi %8 %170 %168 %170 %174 %179 %178 +%181 = OpCompositeExtract %6 %180 0 +OpReturnValue %181 OpFunctionEnd -%180 = OpFunction %4 None %141 -%178 = OpFunctionParameter %8 -%179 = OpFunctionParameter %5 -%177 = OpLabel -%181 = OpLoad %15 %34 -OpBranch %182 +%185 = OpFunction %6 None %146 +%183 = OpFunctionParameter %10 +%184 = OpFunctionParameter %4 %182 = OpLabel -%184 = OpImageQuerySamples %5 %181 -%185 = OpULessThan %51 %179 %184 -OpSelectionMerge %186 None -OpBranchConditional %185 %187 %186 +%186 = OpLoad %17 %39 +OpBranch %187 %187 = OpLabel -%188 = OpImageQuerySize %8 %181 -%189 = OpULessThan %75 %178 %188 -%190 = OpAll %51 %189 -OpBranchConditional %190 %191 %186 +%189 = OpImageQuerySamples %4 %186 +%190 = OpULessThan %56 %184 %189 +OpSelectionMerge %191 None +OpBranchConditional %190 %192 %191 +%192 = OpLabel +%193 = OpImageQuerySize %10 %186 +%194 = OpULessThan %80 %183 %193 +%195 = OpAll %56 %194 +OpBranchConditional %195 %196 %191 +%196 = OpLabel +%197 = OpImageFetch %8 %186 %183 Sample %184 +OpBranch %191 %191 = OpLabel -%192 = OpImageFetch %6 %181 %178 Sample %179 -OpBranch %186 -%186 = OpLabel -%193 = OpPhi %6 %183 %182 %183 %187 %192 %191 -%194 = OpCompositeExtract %4 %193 0 -OpReturnValue %194 +%198 = OpPhi %8 %188 %187 %188 %192 %197 %196 +%199 = OpCompositeExtract %6 %198 0 +OpReturnValue %199 OpFunctionEnd -%198 = OpFunction %2 None %199 -%196 = OpFunctionParameter %5 -%197 = OpFunctionParameter %6 -%195 = OpLabel -%200 = OpLoad %16 %36 -OpBranch %201 -%201 = OpLabel -%202 = OpImageQuerySize %5 %200 -%203 = OpULessThan %51 %196 %202 -OpSelectionMerge %204 None -OpBranchConditional %203 %205 %204 -%205 = OpLabel -OpImageWrite %200 %196 %197 -OpBranch %204 -%204 = OpLabel -OpReturn -OpFunctionEnd -%209 = OpFunction %2 None %210 -%207 = OpFunctionParameter %8 -%208 = OpFunctionParameter %6 +%203 = OpFunction %2 None %204 +%201 = OpFunctionParameter %4 +%202 = OpFunctionParameter %8 +%200 = OpLabel +%205 = OpLoad %18 %41 +OpBranch %206 %206 = OpLabel -%211 = OpLoad %17 %38 -OpBranch %212 -%212 = OpLabel -%213 = OpImageQuerySize %8 %211 -%214 = OpULessThan %75 %207 %213 -%215 = OpAll %51 %214 -OpSelectionMerge %216 None -OpBranchConditional %215 %217 %216 -%217 = OpLabel -OpImageWrite %211 %207 %208 -OpBranch %216 -%216 = OpLabel +%207 = OpImageQuerySize %4 %205 +%208 = OpULessThan %56 %201 %207 +OpSelectionMerge %209 None +OpBranchConditional %208 %210 %209 +%210 = OpLabel +OpImageWrite %205 %201 %202 +OpBranch %209 +%209 = OpLabel OpReturn OpFunctionEnd -%222 = OpFunction %2 None %223 -%219 = OpFunctionParameter %8 -%220 = OpFunctionParameter %5 -%221 = OpFunctionParameter %6 -%218 = OpLabel -%224 = OpLoad %18 %40 -OpBranch %225 -%225 = OpLabel -%226 = OpCompositeConstruct %11 %219 %220 -%227 = OpImageQuerySize %11 %224 -%228 = OpULessThan %96 %226 %227 -%229 = OpAll %51 %228 -OpSelectionMerge %230 None -OpBranchConditional %229 %231 %230 -%231 = OpLabel -OpImageWrite %224 %226 %221 +%214 = OpFunction %2 None %215 +%212 = OpFunctionParameter %10 +%213 = OpFunctionParameter %8 +%211 = OpLabel +%216 = OpLoad %19 %43 +OpBranch %217 +%217 = OpLabel +%218 = OpImageQuerySize %10 %216 +%219 = OpULessThan %80 %212 %218 +%220 = OpAll %56 %219 +OpSelectionMerge %221 None +OpBranchConditional %220 %222 %221 +%222 = OpLabel +OpImageWrite %216 %212 %213 +OpBranch %221 +%221 = OpLabel +OpReturn +OpFunctionEnd +%227 = OpFunction %2 None %228 +%224 = OpFunctionParameter %10 +%225 = OpFunctionParameter %4 +%226 = OpFunctionParameter %8 +%223 = OpLabel +%229 = OpLoad %20 %45 OpBranch %230 %230 = OpLabel +%231 = OpCompositeConstruct %13 %224 %225 +%232 = OpImageQuerySize %13 %229 +%233 = OpULessThan %101 %231 %232 +%234 = OpAll %56 %233 +OpSelectionMerge %235 None +OpBranchConditional %234 %236 %235 +%236 = OpLabel +OpImageWrite %229 %231 %226 +OpBranch %235 +%235 = OpLabel OpReturn OpFunctionEnd -%235 = OpFunction %2 None %236 -%233 = OpFunctionParameter %11 -%234 = OpFunctionParameter %6 -%232 = OpLabel -%237 = OpLoad %19 %42 -OpBranch %238 -%238 = OpLabel -%239 = OpImageQuerySize %11 %237 -%240 = OpULessThan %96 %233 %239 -%241 = OpAll %51 %240 -OpSelectionMerge %242 None -OpBranchConditional %241 %243 %242 +%240 = OpFunction %2 None %241 +%238 = OpFunctionParameter %13 +%239 = OpFunctionParameter %8 +%237 = OpLabel +%242 = OpLoad %21 %47 +OpBranch %243 %243 = OpLabel -OpImageWrite %237 %233 %234 -OpBranch %242 -%242 = OpLabel +%244 = OpImageQuerySize %13 %242 +%245 = OpULessThan %101 %238 %244 +%246 = OpAll %56 %245 +OpSelectionMerge %247 None +OpBranchConditional %246 %248 %247 +%248 = OpLabel +OpImageWrite %242 %238 %239 +OpBranch %247 +%247 = OpLabel +OpReturn +OpFunctionEnd +%252 = OpFunction %2 None %253 +%249 = OpLabel +%254 = OpLoad %7 %25 +%255 = OpLoad %9 %27 +%256 = OpLoad %11 %29 +%257 = OpLoad %12 %31 +%258 = OpLoad %14 %33 +%259 = OpLoad %18 %41 +%260 = OpLoad %19 %43 +%261 = OpLoad %20 %45 +%262 = OpLoad %21 %47 +OpBranch %263 +%263 = OpLabel +%264 = OpFunctionCall %8 %52 %3 %3 +%265 = OpFunctionCall %8 %70 %22 %3 +%266 = OpFunctionCall %8 %90 %22 %3 %3 +%267 = OpFunctionCall %8 %110 %23 %3 +%268 = OpFunctionCall %8 %128 %22 %3 +%269 = OpFunctionCall %2 %203 %3 %24 +%270 = OpFunctionCall %2 %214 %22 %24 +%271 = OpFunctionCall %2 %227 %22 %3 %24 +%272 = OpFunctionCall %2 %240 %23 %24 +%273 = OpCompositeConstruct %8 %5 %5 %5 %5 +OpStore %250 %273 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index f6a3749c3..459cdf222 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -153,7 +153,16 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { if params.glsl_exclude_list.contains(&ep.name) { continue; } - write_output_glsl(module, &info, &dest, name, ep.stage, &ep.name, ¶ms.glsl); + write_output_glsl( + module, + &info, + &dest, + name, + ep.stage, + &ep.name, + ¶ms.glsl, + params.bounds_check_policies, + ); } } } @@ -273,6 +282,7 @@ fn write_output_glsl( stage: naga::ShaderStage, ep_name: &str, options: &naga::back::glsl::Options, + bounds_check_policies: naga::proc::BoundsCheckPolicies, ) { use naga::back::glsl; @@ -284,8 +294,15 @@ fn write_output_glsl( }; let mut buffer = String::new(); - let mut writer = glsl::Writer::new(&mut buffer, module, info, options, &pipeline_options) - .expect("GLSL init failed"); + let mut writer = glsl::Writer::new( + &mut buffer, + module, + info, + options, + &pipeline_options, + bounds_check_policies, + ) + .expect("GLSL init failed"); writer.write().expect("GLSL write failed"); fs::write( @@ -489,9 +506,12 @@ fn convert_wgsl() { ("bounds-check-restrict", Targets::SPIRV | Targets::METAL), ( "bounds-check-image-restrict", - Targets::SPIRV | Targets::METAL, + Targets::SPIRV | Targets::METAL | Targets::GLSL, + ), + ( + "bounds-check-image-rzsw", + Targets::SPIRV | Targets::METAL | Targets::GLSL, ), - ("bounds-check-image-rzsw", Targets::SPIRV | Targets::METAL), ("policy-mix", Targets::SPIRV | Targets::METAL), ( "texture-arg", From 7c7e96276ad86d4538c571c3e93ea59f15cdf1e7 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sat, 14 May 2022 16:36:04 +0200 Subject: [PATCH 1763/2212] [hlsl-out] fix missing break statements (for FXC) --- src/back/hlsl/help.rs | 4 ++-- tests/out/hlsl/access.hlsl | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index d71675f6a..5f81c296d 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -715,7 +715,7 @@ impl<'a, W: Write> super::Writer<'a, W> { for i in 0..columns as u8 { writeln!( self.out, - "{}case {}: {}.{}_{} = {};", + "{}case {}: {{ {}.{}_{} = {}; break; }}", INDENT, i, STRUCT_ARGUMENT_VARIABLE_NAME, @@ -809,7 +809,7 @@ impl<'a, W: Write> super::Writer<'a, W> { for i in 0..columns as u8 { writeln!( self.out, - "{}case {}: {}.{}_{}[{}] = {};", + "{}case {}: {{ {}.{}_{}[{}] = {}; break; }}", INDENT, i, STRUCT_ARGUMENT_VARIABLE_NAME, diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index d6a9736a8..29815f096 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -37,17 +37,17 @@ void SetMatmOnBaz(Baz obj, float3x2 mat) { void SetMatVecmOnBaz(Baz obj, float2 vec, uint mat_idx) { switch(mat_idx) { - case 0: obj.m_0 = vec; - case 1: obj.m_1 = vec; - case 2: obj.m_2 = vec; + case 0: { obj.m_0 = vec; break; } + case 1: { obj.m_1 = vec; break; } + case 2: { obj.m_2 = vec; break; } } } void SetMatScalarmOnBaz(Baz obj, float scalar, uint mat_idx, uint vec_idx) { switch(mat_idx) { - case 0: obj.m_0[vec_idx] = scalar; - case 1: obj.m_1[vec_idx] = scalar; - case 2: obj.m_2[vec_idx] = scalar; + case 0: { obj.m_0[vec_idx] = scalar; break; } + case 1: { obj.m_1[vec_idx] = scalar; break; } + case 2: { obj.m_2[vec_idx] = scalar; break; } } } From 91ee407c87638ed81844ac2f71e5cd0cbf3dbb61 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sat, 14 May 2022 16:46:08 +0200 Subject: [PATCH 1764/2212] [hlsl-out] fix fallthrough in switch statements --- src/back/hlsl/writer.rs | 46 +++-- tests/in/control-flow.wgsl | 7 +- tests/out/glsl/control-flow.main.Compute.glsl | 9 +- tests/out/hlsl/control-flow.hlsl | 24 ++- tests/out/msl/control-flow.msl | 8 +- tests/out/spv/control-flow.spvasm | 192 +++++++++--------- tests/out/wgsl/control-flow.wgsl | 8 +- 7 files changed, 163 insertions(+), 131 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index e713c2f5d..16d21e079 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1651,7 +1651,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let indent_level_1 = level.next(); let indent_level_2 = indent_level_1.next(); - for case in cases { + for (i, case) in cases.iter().enumerate() { match case.value { crate::SwitchValue::Integer(value) => writeln!( self.out, @@ -1663,25 +1663,35 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } + // FXC doesn't support fallthrough so we duplicate the body of the following case blocks if case.fall_through { - // Generate each fallthrough case statement in a new block. This is done to - // prevent symbol collision of variables declared in these cases statements. - writeln!(self.out, "{}/* fallthrough */", indent_level_2)?; - writeln!(self.out, "{}{{", indent_level_2)?; - } - for sta in case.body.iter() { - self.write_stmt( - module, - sta, - func_ctx, - back::Level(indent_level_2.0 + usize::from(case.fall_through)), - )?; - } + let curr_len = i + 1; + let end_case_idx = curr_len + + cases + .iter() + .skip(curr_len) + .position(|case| !case.fall_through) + .unwrap(); + let indent_level_3 = indent_level_2.next(); + for case in &cases[i..=end_case_idx] { + writeln!(self.out, "{}{{", indent_level_2)?; + for sta in case.body.iter() { + self.write_stmt(module, sta, func_ctx, indent_level_3)?; + } + writeln!(self.out, "{}}}", indent_level_2)?; + } - if case.fall_through { - writeln!(self.out, "{}}}", indent_level_2)?; - } else if case.body.last().map_or(true, |s| !s.is_terminator()) { - writeln!(self.out, "{}break;", indent_level_2)?; + let last_case = &cases[end_case_idx]; + if last_case.body.last().map_or(true, |s| !s.is_terminator()) { + writeln!(self.out, "{}break;", indent_level_2)?; + } + } else { + for sta in case.body.iter() { + self.write_stmt(module, sta, func_ctx, indent_level_2)?; + } + if case.body.last().map_or(true, |s| !s.is_terminator()) { + writeln!(self.out, "{}break;", indent_level_2)?; + } } writeln!(self.out, "{}}}", indent_level_1)?; diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index f059eeeb8..787742d71 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -26,9 +26,12 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { pos = 2; fallthrough; } - case 4: {} - default: { + case 4: { pos = 3; + fallthrough; + } + default: { + pos = 4; } } diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index a5e103413..5446e3609 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -59,9 +59,10 @@ void main() { pos = 2; /* fallthrough */ case 4: - break; - default: pos = 3; + /* fallthrough */ + default: + pos = 4; break; } switch(0u) { @@ -70,8 +71,8 @@ void main() { default: break; } - int _e10 = pos; - switch(_e10) { + int _e11 = pos; + switch(_e11) { case 1: pos = 0; break; diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index e65dbc75f..4b879ef20 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -60,16 +60,28 @@ void main(uint3 global_id : SV_DispatchThreadID) break; } case 3: { - /* fallthrough */ { pos = 2; } + { + pos = 3; + } + { + pos = 4; + } + break; } case 4: { + { + pos = 3; + } + { + pos = 4; + } break; } default: { - pos = 3; + pos = 4; break; } } @@ -81,8 +93,8 @@ void main(uint3 global_id : SV_DispatchThreadID) break; } } - int _expr10 = pos; - switch(_expr10) { + int _expr11 = pos; + switch(_expr11) { case 1: { pos = 0; break; @@ -92,10 +104,12 @@ void main(uint3 global_id : SV_DispatchThreadID) return; } case 3: { - /* fallthrough */ { pos = 2; } + { + return; + } } case 4: { return; diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index e35d24d5f..4a0b80566 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -72,10 +72,10 @@ kernel void main_( pos = 2; } case 4: { - break; + pos = 3; } default: { - pos = 3; + pos = 4; break; } } @@ -87,8 +87,8 @@ kernel void main_( break; } } - int _e10 = pos; - switch(_e10) { + int _e11 = pos; + switch(_e11) { case 1: { pos = 0; break; diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index 93da80103..dfd1b145a 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -1,136 +1,138 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 68 +; Bound: 69 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %43 "main" %40 -OpExecutionMode %43 LocalSize 1 1 1 -OpDecorate %40 BuiltIn GlobalInvocationId +OpEntryPoint GLCompute %44 "main" %41 +OpExecutionMode %44 LocalSize 1 1 1 +OpDecorate %41 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 %5 = OpConstant %4 0 %6 = OpConstant %4 2 %7 = OpConstant %4 3 -%9 = OpTypeInt 32 0 -%8 = OpConstant %9 0 -%10 = OpTypeVector %9 3 -%14 = OpTypeFunction %2 %4 -%20 = OpTypeFunction %2 -%37 = OpTypePointer Function %4 -%38 = OpConstantNull %4 -%41 = OpTypePointer Input %10 -%40 = OpVariable %41 Input -%45 = OpConstant %9 2 -%46 = OpConstant %9 1 -%47 = OpConstant %9 72 -%48 = OpConstant %9 264 -%13 = OpFunction %2 None %14 -%12 = OpFunctionParameter %4 -%11 = OpLabel -OpBranch %15 -%15 = OpLabel -OpSelectionMerge %16 None -OpSwitch %12 %17 -%17 = OpLabel +%8 = OpConstant %4 4 +%10 = OpTypeInt 32 0 +%9 = OpConstant %10 0 +%11 = OpTypeVector %10 3 +%15 = OpTypeFunction %2 %4 +%21 = OpTypeFunction %2 +%38 = OpTypePointer Function %4 +%39 = OpConstantNull %4 +%42 = OpTypePointer Input %11 +%41 = OpVariable %42 Input +%46 = OpConstant %10 2 +%47 = OpConstant %10 1 +%48 = OpConstant %10 72 +%49 = OpConstant %10 264 +%14 = OpFunction %2 None %15 +%13 = OpFunctionParameter %4 +%12 = OpLabel OpBranch %16 %16 = OpLabel +OpSelectionMerge %17 None +OpSwitch %13 %18 +%18 = OpLabel +OpBranch %17 +%17 = OpLabel OpReturn OpFunctionEnd -%19 = OpFunction %2 None %20 -%18 = OpLabel -OpBranch %21 -%21 = OpLabel -OpSelectionMerge %22 None -OpSwitch %5 %23 0 %24 -%24 = OpLabel -OpBranch %22 -%23 = OpLabel +%20 = OpFunction %2 None %21 +%19 = OpLabel OpBranch %22 %22 = OpLabel +OpSelectionMerge %23 None +OpSwitch %5 %24 0 %25 +%25 = OpLabel +OpBranch %23 +%24 = OpLabel +OpBranch %23 +%23 = OpLabel OpReturn OpFunctionEnd -%27 = OpFunction %2 None %14 -%26 = OpFunctionParameter %4 -%25 = OpLabel -OpBranch %28 -%28 = OpLabel +%28 = OpFunction %2 None %15 +%27 = OpFunctionParameter %4 +%26 = OpLabel OpBranch %29 %29 = OpLabel -OpLoopMerge %30 %32 None -OpBranch %31 -%31 = OpLabel -OpSelectionMerge %33 None -OpSwitch %26 %34 1 %35 -%35 = OpLabel +OpBranch %30 +%30 = OpLabel +OpLoopMerge %31 %33 None OpBranch %32 +%32 = OpLabel +OpSelectionMerge %34 None +OpSwitch %27 %35 1 %36 +%36 = OpLabel +OpBranch %33 +%35 = OpLabel +OpBranch %34 %34 = OpLabel OpBranch %33 %33 = OpLabel -OpBranch %32 -%32 = OpLabel -OpBranch %29 -%30 = OpLabel +OpBranch %30 +%31 = OpLabel OpReturn OpFunctionEnd -%43 = OpFunction %2 None %20 -%39 = OpLabel -%36 = OpVariable %37 Function %38 -%42 = OpLoad %10 %40 -OpBranch %44 -%44 = OpLabel -OpControlBarrier %45 %46 %47 -OpControlBarrier %45 %45 %48 -OpSelectionMerge %49 None -OpSwitch %3 %50 +%44 = OpFunction %2 None %21 +%40 = OpLabel +%37 = OpVariable %38 Function %39 +%43 = OpLoad %11 %41 +OpBranch %45 +%45 = OpLabel +OpControlBarrier %46 %47 %48 +OpControlBarrier %46 %46 %49 +OpSelectionMerge %50 None +OpSwitch %3 %51 +%51 = OpLabel +OpStore %37 %3 +OpBranch %50 %50 = OpLabel -OpStore %36 %3 -OpBranch %49 -%49 = OpLabel -%51 = OpLoad %4 %36 -OpSelectionMerge %52 None -OpSwitch %51 %53 1 %54 2 %55 3 %56 4 %57 -%54 = OpLabel -OpStore %36 %5 -OpBranch %52 +%52 = OpLoad %4 %37 +OpSelectionMerge %53 None +OpSwitch %52 %54 1 %55 2 %56 3 %57 4 %58 %55 = OpLabel -OpStore %36 %3 -OpBranch %52 +OpStore %37 %5 +OpBranch %53 %56 = OpLabel -OpStore %36 %6 -OpBranch %57 +OpStore %37 %3 +OpBranch %53 %57 = OpLabel -OpBranch %52 -%53 = OpLabel -OpStore %36 %7 -OpBranch %52 -%52 = OpLabel -OpSelectionMerge %58 None -OpSwitch %8 %59 0 %60 -%60 = OpLabel -OpBranch %58 -%59 = OpLabel +OpStore %37 %6 OpBranch %58 %58 = OpLabel -%61 = OpLoad %4 %36 -OpSelectionMerge %62 None -OpSwitch %61 %63 1 %64 2 %65 3 %66 4 %67 -%64 = OpLabel -OpStore %36 %5 -OpBranch %62 +OpStore %37 %7 +OpBranch %54 +%54 = OpLabel +OpStore %37 %8 +OpBranch %53 +%53 = OpLabel +OpSelectionMerge %59 None +OpSwitch %9 %60 0 %61 +%61 = OpLabel +OpBranch %59 +%60 = OpLabel +OpBranch %59 +%59 = OpLabel +%62 = OpLoad %4 %37 +OpSelectionMerge %63 None +OpSwitch %62 %64 1 %65 2 %66 3 %67 4 %68 %65 = OpLabel -OpStore %36 %3 -OpReturn +OpStore %37 %5 +OpBranch %63 %66 = OpLabel -OpStore %36 %6 -OpBranch %67 +OpStore %37 %3 +OpReturn %67 = OpLabel +OpStore %37 %6 +OpBranch %68 +%68 = OpLabel +OpReturn +%64 = OpLabel +OpStore %37 %7 OpReturn %63 = OpLabel -OpStore %36 %7 -OpReturn -%62 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index 55ad20ce2..ce3911f2b 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -55,9 +55,11 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { fallthrough; } case 4: { + pos = 3; + fallthrough; } default: { - pos = 3; + pos = 4; } } switch 0u { @@ -66,8 +68,8 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { default: { } } - let _e10 = pos; - switch _e10 { + let _e11 = pos; + switch _e11 { case 1: { pos = 0; break; From a8256e94c24e46a3cf298439e631ee29de3ec0de Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Sat, 14 May 2022 17:04:39 +0200 Subject: [PATCH 1765/2212] [hlsl-out] avoid error X3694: race condition writing to shared resource detected --- tests/in/spv/empty-global-name.spv | Bin 408 -> 408 bytes tests/in/spv/empty-global-name.spvasm | 2 +- tests/out/hlsl/empty-global-name.hlsl | 2 +- tests/out/wgsl/empty-global-name.wgsl | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/in/spv/empty-global-name.spv b/tests/in/spv/empty-global-name.spv index 02089e13d029b00c8454d00f35e74984d90716f0..ebbd7a1aab9dcaf5baff6f8cedb08fa332d1eb43 100644 GIT binary patch delta 12 TcmbQiJcD_H4 Date: Sat, 14 May 2022 17:10:59 +0200 Subject: [PATCH 1766/2212] [hlsl-out] avoid error X3504: array index out of bounds --- tests/in/access.wgsl | 2 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 2 +- tests/out/hlsl/access.hlsl | 2 +- tests/out/msl/access.msl | 2 +- tests/out/spv/access.spvasm | 154 ++++++++++----------- tests/out/wgsl/access.wgsl | 2 +- 6 files changed, 82 insertions(+), 82 deletions(-) diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 3b859db42..a9034df91 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -26,7 +26,7 @@ var baz: Baz; var qux: vec2; fn test_matrix_within_struct_accesses() { - var idx = 9; + var idx = 1; idx--; diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index b53af9437..5f6c0f10b 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -23,7 +23,7 @@ layout(std430) buffer type_9_block_2Vertex { ivec2 _group_0_binding_2_vs; }; void test_matrix_within_struct_accesses() { - int idx = 9; + int idx = 1; Baz t = Baz(mat3x2(0.0)); int _e5 = idx; idx = (_e5 - 1); diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 29815f096..1427bb20a 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -61,7 +61,7 @@ Baz ConstructBaz(float3x2 arg0) { void test_matrix_within_struct_accesses() { - int idx = 9; + int idx = 1; Baz t = (Baz)0; int _expr5 = idx; diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index c90483cd5..0db07ad57 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -45,7 +45,7 @@ constant metal::int2 const_type_9_ = {0, 0}; void test_matrix_within_struct_accesses( constant Baz& baz ) { - int idx = 9; + int idx = 1; Baz t = {}; int _e5 = idx; idx = _e5 - 1; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index d42e6a443..b1e059bb7 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -81,26 +81,26 @@ OpDecorate %195 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 -%5 = OpConstant %4 9 -%6 = OpConstant %4 1 -%7 = OpConstant %4 0 -%9 = OpTypeFloat 32 -%8 = OpConstant %9 1.0 -%10 = OpConstant %9 2.0 -%11 = OpConstant %9 3.0 -%12 = OpConstant %9 6.0 -%13 = OpConstant %9 5.0 -%14 = OpConstant %9 4.0 -%15 = OpConstant %9 9.0 -%16 = OpConstant %9 90.0 -%17 = OpConstant %9 10.0 -%18 = OpConstant %9 20.0 -%19 = OpConstant %9 30.0 -%20 = OpConstant %9 40.0 -%21 = OpConstant %4 10 -%22 = OpConstant %4 5 -%23 = OpConstant %4 4 -%24 = OpConstant %9 0.0 +%5 = OpConstant %4 1 +%6 = OpConstant %4 0 +%8 = OpTypeFloat 32 +%7 = OpConstant %8 1.0 +%9 = OpConstant %8 2.0 +%10 = OpConstant %8 3.0 +%11 = OpConstant %8 6.0 +%12 = OpConstant %8 5.0 +%13 = OpConstant %8 4.0 +%14 = OpConstant %8 9.0 +%15 = OpConstant %8 90.0 +%16 = OpConstant %8 10.0 +%17 = OpConstant %8 20.0 +%18 = OpConstant %8 30.0 +%19 = OpConstant %8 40.0 +%20 = OpConstant %4 10 +%21 = OpConstant %4 5 +%22 = OpConstant %4 4 +%23 = OpConstant %4 9 +%24 = OpConstant %8 0.0 %26 = OpTypeInt 32 0 %25 = OpConstant %26 3 %27 = OpConstant %26 2 @@ -110,9 +110,9 @@ OpDecorate %195 Location 0 %31 = OpConstant %26 0 %32 = OpConstant %26 42 %33 = OpTypeStruct %4 -%35 = OpTypeVector %9 3 +%35 = OpTypeVector %8 3 %34 = OpTypeMatrix %35 4 -%37 = OpTypeVector %9 2 +%37 = OpTypeVector %8 2 %36 = OpTypeMatrix %37 2 %38 = OpTypeArray %36 %3 %39 = OpTypeVector %26 2 @@ -122,16 +122,16 @@ OpDecorate %195 Location 0 %43 = OpTypeMatrix %37 3 %44 = OpTypeStruct %43 %45 = OpTypeVector %4 2 -%46 = OpTypePointer Function %9 -%47 = OpTypeArray %9 %21 -%48 = OpTypeArray %47 %22 -%49 = OpTypeVector %9 4 +%46 = OpTypePointer Function %8 +%47 = OpTypeArray %8 %20 +%48 = OpTypeArray %47 %21 +%49 = OpTypeVector %8 4 %50 = OpTypePointer StorageBuffer %4 -%51 = OpTypeArray %4 %22 +%51 = OpTypeArray %4 %21 %52 = OpTypePointer Workgroup %26 %53 = OpConstantComposite %47 %24 %24 %24 %24 %24 %24 %24 %24 %24 %24 %54 = OpConstantComposite %48 %53 %53 %53 %53 %53 -%55 = OpConstantComposite %45 %7 %7 +%55 = OpConstantComposite %45 %6 %6 %57 = OpTypePointer StorageBuffer %42 %56 = OpVariable %57 StorageBuffer %59 = OpTypeStruct %44 @@ -149,12 +149,12 @@ OpDecorate %195 Location 0 %75 = OpTypePointer StorageBuffer %45 %79 = OpTypePointer Uniform %43 %82 = OpTypePointer Uniform %37 -%88 = OpTypePointer Uniform %9 +%88 = OpTypePointer Uniform %8 %108 = OpTypePointer Function %43 %114 = OpTypePointer Function %37 -%120 = OpTypePointer Function %9 -%132 = OpTypeFunction %9 %46 -%138 = OpTypeFunction %9 %48 +%120 = OpTypePointer Function %8 +%132 = OpTypeFunction %8 %46 +%138 = OpTypeFunction %8 %48 %145 = OpTypeFunction %2 %52 %149 = OpTypePointer Function %51 %150 = OpConstantNull %51 @@ -165,7 +165,7 @@ OpDecorate %195 Location 0 %163 = OpTypePointer StorageBuffer %34 %166 = OpTypePointer StorageBuffer %40 %169 = OpTypePointer StorageBuffer %35 -%170 = OpTypePointer StorageBuffer %9 +%170 = OpTypePointer StorageBuffer %8 %173 = OpTypePointer StorageBuffer %41 %176 = OpTypePointer StorageBuffer %33 %177 = OpConstant %26 4 @@ -182,7 +182,7 @@ OpDecorate %195 Location 0 OpBranch %76 %76 = OpLabel %77 = OpLoad %4 %65 -%78 = OpISub %4 %77 %6 +%78 = OpISub %4 %77 %5 OpStore %65 %78 %80 = OpAccessChain %79 %74 %31 %81 = OpLoad %43 %80 @@ -192,68 +192,68 @@ OpStore %65 %78 %86 = OpAccessChain %82 %74 %31 %85 %87 = OpLoad %37 %86 %89 = OpAccessChain %88 %74 %31 %31 %29 -%90 = OpLoad %9 %89 +%90 = OpLoad %8 %89 %91 = OpLoad %4 %65 %92 = OpAccessChain %88 %74 %31 %31 %91 -%93 = OpLoad %9 %92 +%93 = OpLoad %8 %92 %94 = OpLoad %4 %65 %95 = OpAccessChain %88 %74 %31 %94 %29 -%96 = OpLoad %9 %95 +%96 = OpLoad %8 %95 %97 = OpLoad %4 %65 %98 = OpLoad %4 %65 %99 = OpAccessChain %88 %74 %31 %97 %98 -%100 = OpLoad %9 %99 -%101 = OpCompositeConstruct %37 %8 %8 -%102 = OpCompositeConstruct %37 %10 %10 -%103 = OpCompositeConstruct %37 %11 %11 +%100 = OpLoad %8 %99 +%101 = OpCompositeConstruct %37 %7 %7 +%102 = OpCompositeConstruct %37 %9 %9 +%103 = OpCompositeConstruct %37 %10 %10 %104 = OpCompositeConstruct %43 %101 %102 %103 %105 = OpCompositeConstruct %44 %104 OpStore %67 %105 %106 = OpLoad %4 %65 -%107 = OpIAdd %4 %106 %6 +%107 = OpIAdd %4 %106 %5 OpStore %65 %107 -%109 = OpCompositeConstruct %37 %12 %12 -%110 = OpCompositeConstruct %37 %13 %13 -%111 = OpCompositeConstruct %37 %14 %14 +%109 = OpCompositeConstruct %37 %11 %11 +%110 = OpCompositeConstruct %37 %12 %12 +%111 = OpCompositeConstruct %37 %13 %13 %112 = OpCompositeConstruct %43 %109 %110 %111 %113 = OpAccessChain %108 %67 %31 OpStore %113 %112 -%115 = OpCompositeConstruct %37 %15 %15 +%115 = OpCompositeConstruct %37 %14 %14 %116 = OpAccessChain %114 %67 %31 %31 OpStore %116 %115 %117 = OpLoad %4 %65 -%118 = OpCompositeConstruct %37 %16 %16 +%118 = OpCompositeConstruct %37 %15 %15 %119 = OpAccessChain %114 %67 %31 %117 OpStore %119 %118 %121 = OpAccessChain %120 %67 %31 %31 %29 -OpStore %121 %17 +OpStore %121 %16 %122 = OpLoad %4 %65 %123 = OpAccessChain %120 %67 %31 %31 %122 -OpStore %123 %18 +OpStore %123 %17 %124 = OpLoad %4 %65 %125 = OpAccessChain %120 %67 %31 %124 %29 -OpStore %125 %19 +OpStore %125 %18 %126 = OpLoad %4 %65 %127 = OpLoad %4 %65 %128 = OpAccessChain %120 %67 %31 %126 %127 -OpStore %128 %20 +OpStore %128 %19 OpReturn OpFunctionEnd -%131 = OpFunction %9 None %132 +%131 = OpFunction %8 None %132 %130 = OpFunctionParameter %46 %129 = OpLabel OpBranch %133 %133 = OpLabel -%134 = OpLoad %9 %130 +%134 = OpLoad %8 %130 OpReturnValue %134 OpFunctionEnd -%137 = OpFunction %9 None %138 +%137 = OpFunction %8 None %138 %136 = OpFunctionParameter %48 %135 = OpLabel OpBranch %139 %139 = OpLabel %140 = OpCompositeExtract %47 %136 4 -%141 = OpCompositeExtract %9 %140 9 +%141 = OpCompositeExtract %8 %140 9 OpReturnValue %141 OpFunctionEnd %144 = OpFunction %2 None %145 @@ -273,34 +273,34 @@ OpFunctionEnd %159 = OpAccessChain %75 %61 %31 OpBranch %160 %160 = OpLabel -%161 = OpLoad %9 %147 -OpStore %147 %8 +%161 = OpLoad %8 %147 +OpStore %147 %7 %162 = OpFunctionCall %2 %71 %164 = OpAccessChain %163 %56 %31 %165 = OpLoad %34 %164 %167 = OpAccessChain %166 %56 %25 %168 = OpLoad %40 %167 %171 = OpAccessChain %170 %56 %31 %25 %31 -%172 = OpLoad %9 %171 +%172 = OpLoad %8 %171 %174 = OpArrayLength %26 %56 4 %175 = OpISub %26 %174 %27 %178 = OpAccessChain %50 %56 %177 %175 %31 %179 = OpLoad %4 %178 %180 = OpLoad %45 %159 -%181 = OpFunctionCall %9 %131 %147 +%181 = OpFunctionCall %8 %131 %147 %182 = OpConvertFToS %4 %172 -%183 = OpCompositeConstruct %51 %179 %182 %28 %23 %22 +%183 = OpCompositeConstruct %51 %179 %182 %28 %22 %21 OpStore %148 %183 %184 = OpIAdd %26 %154 %29 %185 = OpAccessChain %66 %148 %184 OpStore %185 %30 %186 = OpAccessChain %66 %148 %154 %187 = OpLoad %4 %186 -%188 = OpFunctionCall %9 %137 %54 +%188 = OpFunctionCall %8 %137 %54 %190 = OpCompositeConstruct %189 %187 %187 %187 %187 %191 = OpConvertSToF %49 %190 %192 = OpMatrixTimesVector %35 %165 %191 -%193 = OpCompositeConstruct %49 %192 %10 +%193 = OpCompositeConstruct %49 %192 %9 OpStore %155 %193 OpReturn OpFunctionEnd @@ -310,11 +310,11 @@ OpFunctionEnd OpBranch %198 %198 = OpLabel %199 = OpAccessChain %170 %56 %31 %29 %27 -OpStore %199 %8 +OpStore %199 %7 %200 = OpCompositeConstruct %35 %24 %24 %24 -%201 = OpCompositeConstruct %35 %8 %8 %8 -%202 = OpCompositeConstruct %35 %10 %10 %10 -%203 = OpCompositeConstruct %35 %11 %11 %11 +%201 = OpCompositeConstruct %35 %7 %7 %7 +%202 = OpCompositeConstruct %35 %9 %9 %9 +%203 = OpCompositeConstruct %35 %10 %10 %10 %204 = OpCompositeConstruct %34 %200 %201 %202 %203 %205 = OpAccessChain %163 %56 %31 OpStore %205 %204 @@ -324,7 +324,7 @@ OpStore %205 %204 %209 = OpAccessChain %166 %56 %25 OpStore %209 %208 %210 = OpAccessChain %50 %56 %177 %29 %31 -OpStore %210 %6 +OpStore %210 %5 OpStore %197 %55 %211 = OpCompositeConstruct %49 %24 %24 %24 %24 OpStore %195 %211 @@ -336,33 +336,33 @@ OpFunctionEnd OpBranch %216 %216 = OpLabel %218 = OpAccessChain %217 %56 %27 -%219 = OpAtomicLoad %4 %218 %6 %220 +%219 = OpAtomicLoad %4 %218 %5 %220 %222 = OpAccessChain %217 %56 %27 -%221 = OpAtomicIAdd %4 %222 %6 %220 %22 +%221 = OpAtomicIAdd %4 %222 %5 %220 %21 OpStore %212 %221 %224 = OpAccessChain %217 %56 %27 -%223 = OpAtomicISub %4 %224 %6 %220 %22 +%223 = OpAtomicISub %4 %224 %5 %220 %21 OpStore %212 %223 %226 = OpAccessChain %217 %56 %27 -%225 = OpAtomicAnd %4 %226 %6 %220 %22 +%225 = OpAtomicAnd %4 %226 %5 %220 %21 OpStore %212 %225 %228 = OpAccessChain %217 %56 %27 -%227 = OpAtomicOr %4 %228 %6 %220 %22 +%227 = OpAtomicOr %4 %228 %5 %220 %21 OpStore %212 %227 %230 = OpAccessChain %217 %56 %27 -%229 = OpAtomicXor %4 %230 %6 %220 %22 +%229 = OpAtomicXor %4 %230 %5 %220 %21 OpStore %212 %229 %232 = OpAccessChain %217 %56 %27 -%231 = OpAtomicSMin %4 %232 %6 %220 %22 +%231 = OpAtomicSMin %4 %232 %5 %220 %21 OpStore %212 %231 %234 = OpAccessChain %217 %56 %27 -%233 = OpAtomicSMax %4 %234 %6 %220 %22 +%233 = OpAtomicSMax %4 %234 %5 %220 %21 OpStore %212 %233 %236 = OpAccessChain %217 %56 %27 -%235 = OpAtomicExchange %4 %236 %6 %220 %22 +%235 = OpAtomicExchange %4 %236 %5 %220 %21 OpStore %212 %235 %237 = OpAccessChain %217 %56 %27 -OpAtomicStore %237 %6 %220 %219 +OpAtomicStore %237 %5 %220 %219 OpReturn OpFunctionEnd %239 = OpFunction %2 None %72 diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 315ade51a..ec5f8eee5 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -23,7 +23,7 @@ var qux: vec2; var val: u32; fn test_matrix_within_struct_accesses() { - var idx: i32 = 9; + var idx: i32 = 1; var t: Baz; let _e5 = idx; From 9e75332283243223e611607025d44fca0f0407d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 27 May 2022 23:49:15 +0100 Subject: [PATCH 1767/2212] glsl-in: Stop emitter in conditional This wasn't being done when there were no implicit conversions, causing the emitter to panic. --- src/front/glsl/context.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index fe20df410..ed6075908 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -1174,6 +1174,10 @@ impl Context { self.emit_end(&mut reject_body); } } + } else { + // Technically there's nothing to flush but later we will need to + // add some expressions that must not be emitted. + self.emit_end(body) } // We need to get the type of the resulting expression to create the local, From 6a3f526c1224dc74d97514707536354bd5fe8d86 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 30 May 2022 14:26:18 -0700 Subject: [PATCH 1768/2212] [spv-in] Finish truncated comment. --- src/front/spv/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 7e560cfc4..8d14b3816 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -306,7 +306,8 @@ struct LookupExpression { /// /// Note that, while a SPIR-V result id can be used in any block dominated /// by its definition, a Naga `Expression` is only in scope for the rest of - /// its subtree. `Parser::get_expr_handle` takes care of + /// its subtree. `Parser::get_expr_handle` takes care of spilling the result + /// to a `LocalVariable` which can then be used anywhere. handle: Handle, /// The SPIR-V type of this result. From cff744dc8947fbddfcce1e48aba68b51ee41fc5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 28 May 2022 15:14:10 +0100 Subject: [PATCH 1769/2212] spv-in: Implement OpBitReverse and OpBitCount --- src/front/spv/mod.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 8d14b3816..d78a128be 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2393,6 +2393,34 @@ impl> Parser { }, ); } + Op::BitReverse | Op::BitCount => { + inst.expect(4)?; + + let result_type_id = self.next()?; + let result_id = self.next()?; + let base_id = self.next()?; + let base_lexp = self.lookup_expression.lookup(base_id)?; + let base_handle = get_expr_handle!(base_id, base_lexp); + let expr = crate::Expression::Math { + fun: match inst.op { + Op::BitReverse => crate::MathFunction::ReverseBits, + Op::BitCount => crate::MathFunction::CountOneBits, + _ => unreachable!(), + }, + arg: base_handle, + arg1: None, + arg2: None, + arg3: None, + }; + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: ctx.expressions.append(expr, span), + type_id: result_type_id, + block_id, + }, + ); + } Op::OuterProduct => { inst.expect(5)?; From e461d30865150a338c41aa8b57b4b859db5ca7da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 28 May 2022 00:08:02 +0100 Subject: [PATCH 1770/2212] glsl-in: Fix matrix multiplication check The previous check compared rows to rows and columns to columns but multiplication of matrices only needs the columns of the left matrix to be equal to the rows of the right matrix. --- src/front/glsl/context.rs | 11 +++++++---- tests/in/glsl/expressions.frag | 4 ++++ tests/out/wgsl/expressions-frag.wgsl | 13 +++++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index ed6075908..13eb5d180 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -617,11 +617,14 @@ impl Context { width: right_width, }, ) => { + let dimensions_ok = if op == BinaryOperator::Multiply { + left_columns == right_rows + } else { + left_columns == right_columns && left_rows == right_rows + }; + // Check that the two arguments have the same dimensions - if left_columns != right_columns - || left_rows != right_rows - || left_width != right_width - { + if !dimensions_ok || left_width != right_width { parser.errors.push(Error { kind: ErrorKind::SemanticError( format!( diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 8dd07c652..acf0ea921 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -128,6 +128,10 @@ void ternary(bool a) { uint nested = a ? (a ? (a ? 2u : 3) : 4u) : 5; } +void testMatrixMultiplication(mat4x3 a, mat4x4 b) { + mat4x3 c = a * b; +} + out vec4 o_color; void main() { privatePointer(global); diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index b4364e597..7cf1eace0 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -356,6 +356,19 @@ fn ternary(a_20: bool) { return; } +fn testMatrixMultiplication(a_22: mat4x3, b_18: mat4x4) { + var a_23: mat4x3; + var b_19: mat4x4; + var c_2: mat4x3; + + a_23 = a_22; + b_19 = b_18; + let _e5 = a_23; + let _e6 = b_19; + c_2 = (_e5 * _e6); + return; +} + fn main_1() { var local_5: f32; From 231341f056d2fd7ec49ae18c612495895a297e1c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 31 May 2022 17:52:07 -0700 Subject: [PATCH 1771/2212] Fix Criterion benchmark build. As of #1889, the GLSL back end takes an additional argument specifying the bounds checks policies to use. --- benches/criterion.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/benches/criterion.rs b/benches/criterion.rs index f239948e8..117552845 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -255,6 +255,7 @@ fn backends(c: &mut Criterion) { info, &options, &pipeline_options, + naga::proc::BoundsCheckPolicies::default(), ) { Ok(mut writer) => { let _ = writer.write(); // can error if unsupported From 7f5ec31825be688729450c01d112e876c164760f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 31 May 2022 17:41:21 -0700 Subject: [PATCH 1772/2212] Verify in CI that benchmarks build. Also, the documentation job probably doesn't need Clippy. --- .github/workflows/pipeline.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index a4b4bc186..46c427ee0 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -48,6 +48,11 @@ jobs: args: --all-features --workspace - name: Check snapshots run: git diff --exit-code -- tests/out + - uses: actions-rs/cargo@v1 + name: Check benchmarks + with: + command: check + args: --benches clippy: name: Clippy runs-on: ubuntu-latest @@ -75,7 +80,6 @@ jobs: profile: minimal toolchain: stable override: true - - run: rustup component add clippy - uses: actions-rs/cargo@v1 with: command: doc From 1c21fc02fec00f62f2df429abca0647db6583982 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 31 May 2022 17:29:40 -0700 Subject: [PATCH 1773/2212] Let validation check for more unsupported builtins. Add `valid::Capabilities` flags for the `ClipDistance` and `CullDistance` builtins, which are not supported by all back ends. Have the CLI perform valation with only those capabilities that the requested back ends support. Fixes #1961. --- cli/src/main.rs | 21 ++++++++++++++++----- src/valid/interface.rs | 33 ++++++++++++++++++--------------- src/valid/mod.rs | 8 ++++++-- 3 files changed, 40 insertions(+), 22 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 707f95f06..efaf5959b 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -317,12 +317,23 @@ fn run() -> Result<(), Box> { _ => return Err(CliError("Unknown input file extension").into()), }; + // Decide which capabilities our output formats can support. + let validation_caps = + output_paths + .iter() + .fold(naga::valid::Capabilities::all(), |caps, path| { + use naga::valid::Capabilities as C; + let missing = match Path::new(path).extension().and_then(|ex| ex.to_str()) { + Some("wgsl") => C::CLIP_DISTANCE | C::CULL_DISTANCE, + Some("metal") => C::CULL_DISTANCE, + _ => C::empty(), + }; + caps & !missing + }); + // validate the IR - let info = match naga::valid::Validator::new( - params.validation_flags, - naga::valid::Capabilities::all(), - ) - .validate(&module) + let info = match naga::valid::Validator::new(params.validation_flags, validation_caps) + .validate(&module) { Ok(info) => Some(info), Err(error) => { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 91c121dce..bee57e877 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -135,6 +135,16 @@ impl VaryingContext<'_> { } self.built_ins.insert(canonical); + let required = match built_in { + Bi::ClipDistance => Capabilities::CLIP_DISTANCE, + Bi::CullDistance => Capabilities::CULL_DISTANCE, + Bi::PrimitiveIndex => Capabilities::PRIMITIVE_INDEX, + _ => Capabilities::empty(), + }; + if !self.capabilities.contains(required) { + return Err(VaryingError::UnsupportedCapability(required)); + } + let width = 4; let (visible, type_good) = match built_in { Bi::BaseInstance | Bi::BaseVertex | Bi::InstanceIndex | Bi::VertexIndex => ( @@ -206,21 +216,14 @@ impl VaryingContext<'_> { width: crate::BOOL_WIDTH, }, ), - Bi::PrimitiveIndex => { - if !self.capabilities.contains(Capabilities::PRIMITIVE_INDEX) { - return Err(VaryingError::UnsupportedCapability( - Capabilities::PRIMITIVE_INDEX, - )); - } - ( - self.stage == St::Fragment && !self.output, - *ty_inner - == Ti::Scalar { - kind: Sk::Uint, - width, - }, - ) - } + Bi::PrimitiveIndex => ( + self.stage == St::Fragment && !self.output, + *ty_inner + == Ti::Scalar { + kind: Sk::Uint, + width, + }, + ), Bi::SampleIndex => ( self.stage == St::Fragment && !self.output, *ty_inner diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 29ef658db..60178bb47 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -82,11 +82,11 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Capabilities: u8 { - /// Support for `AddressSpace:PushConstant`. + /// Support for [`AddressSpace:PushConstant`]. const PUSH_CONSTANT = 0x1; /// Float values with width = 8. const FLOAT64 = 0x2; - /// Support for `Builtin:PrimitiveIndex`. + /// Support for [`Builtin:PrimitiveIndex`]. const PRIMITIVE_INDEX = 0x4; /// Support for non-uniform indexing of sampled textures and storage buffer arrays. const SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING = 0x8; @@ -94,6 +94,10 @@ bitflags::bitflags! { const UNIFORM_BUFFER_AND_STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING = 0x10; /// Support for non-uniform indexing of samplers. const SAMPLER_NON_UNIFORM_INDEXING = 0x20; + /// Support for [`Builtin::ClipDistance`]. + const CLIP_DISTANCE = 0x40; + /// Support for [`Builtin::CullDistance`]. + const CULL_DISTANCE = 0x80; } } From 89bed99bcc995bc5068c9c112fd9b7d7896bb148 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 30 Apr 2022 22:22:19 -0700 Subject: [PATCH 1774/2212] Forbid returning pointers and atomics from functions. Introduce a new `TypeFlags::CONSTRUCTIBLE` flag, corresponding to WGSL's "constructible types". Set this on the appropriate types. Check for this flag on function return types. --- src/valid/function.rs | 13 +++++++++++++ src/valid/type.rs | 19 ++++++++++++++++--- tests/wgsl-errors.rs | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 3 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 151952750..b928ff517 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -86,6 +86,8 @@ pub enum FunctionError { }, #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")] InvalidArgumentType { index: usize, name: String }, + #[error("The function's given return type cannot be returned from functions")] + NonConstructibleReturnType, #[error("Argument '{name}' at index {index} is a pointer of space {space:?}, which can't be passed into functions.")] InvalidArgumentPointerSpace { index: usize, @@ -894,6 +896,17 @@ impl super::Validator { } } + #[cfg(feature = "validate")] + if let Some(ref result) = fun.result { + if !self.types[result.ty.index()] + .flags + .contains(super::TypeFlags::CONSTRUCTIBLE) + { + return Err(FunctionError::NonConstructibleReturnType + .with_span_handle(result.ty, &module.types)); + } + } + self.valid_expression_set.clear(); self.valid_expression_list.clear(); for (handle, expr) in fun.expressions.iter() { diff --git a/src/valid/type.rs b/src/valid/type.rs index 71af43e99..0312c2143 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -52,6 +52,15 @@ bitflags::bitflags! { /// This type can be passed as a function argument. const ARGUMENT = 0x40; + + /// A WGSL [constructible] type. + /// + /// The constructible types are scalars, vectors, matrices, fixed-size + /// arrays of constructible types, and structs whose members are all + /// constructible. + /// + /// [constructible]: https://gpuweb.github.io/gpuweb/wgsl/#constructible + const CONSTRUCTIBLE = 0x80; } } @@ -237,6 +246,7 @@ impl super::Validator { | TypeFlags::SIZED | TypeFlags::COPY | TypeFlags::ARGUMENT + | TypeFlags::CONSTRUCTIBLE | shareable, width as u32, ) @@ -257,6 +267,7 @@ impl super::Validator { | TypeFlags::COPY | TypeFlags::HOST_SHAREABLE | TypeFlags::ARGUMENT + | TypeFlags::CONSTRUCTIBLE | shareable, count * (width as u32), ) @@ -275,7 +286,8 @@ impl super::Validator { | TypeFlags::SIZED | TypeFlags::COPY | TypeFlags::HOST_SHAREABLE - | TypeFlags::ARGUMENT, + | TypeFlags::ARGUMENT + | TypeFlags::CONSTRUCTIBLE, count * (width as u32), ) } @@ -467,7 +479,7 @@ impl super::Validator { return Err(TypeError::NonPositiveArrayLength(const_handle)); } - TypeFlags::SIZED | TypeFlags::ARGUMENT + TypeFlags::SIZED | TypeFlags::ARGUMENT | TypeFlags::CONSTRUCTIBLE } crate::ArraySize::Dynamic => { // Non-SIZED types may only appear as the last element of a structure. @@ -495,7 +507,8 @@ impl super::Validator { | TypeFlags::COPY | TypeFlags::HOST_SHAREABLE | TypeFlags::IO_SHAREABLE - | TypeFlags::ARGUMENT, + | TypeFlags::ARGUMENT + | TypeFlags::CONSTRUCTIBLE, 1, ); ti.uniform_layout = Ok(Some(UNIFORM_MIN_ALIGNMENT)); diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index db7da613c..74f9b621f 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1029,6 +1029,43 @@ fn invalid_functions() { }) if function_name == "unacceptable_ptr_space" && argument_name == "arg" } + + check_validation! { + " + struct AFloat { + said_float: f32 + }; + @group(0) @binding(0) + var float: AFloat; + + fn return_pointer() -> ptr { + return &float.said_float; + } + ": + Err(naga::valid::ValidationError::Function { + name: function_name, + error: naga::valid::FunctionError::NonConstructibleReturnType, + .. + }) + if function_name == "return_pointer" + } + + check_validation! { + " + @group(0) @binding(0) + var atom: atomic; + + fn return_atomic() -> atomic { + return atom; + } + ": + Err(naga::valid::ValidationError::Function { + name: function_name, + error: naga::valid::FunctionError::NonConstructibleReturnType, + .. + }) + if function_name == "return_atomic" + } } #[test] From 53aa3e2df525dd772e6e9508e8e4a9758e9f5f98 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 2 May 2022 17:02:35 +0200 Subject: [PATCH 1775/2212] [wgsl-in] overhaul number lexing / parsing Bring the lexer's parsing of numeric literals in line with the WGSL specification as of 86a23b83 (2022-05-10). --- src/front/wgsl/lexer.rs | 463 ++++++++++++------------------ src/front/wgsl/mod.rs | 251 +++++++--------- src/front/wgsl/number.rs | 445 ++++++++++++++++++++++++++++ src/front/wgsl/number_literals.rs | 204 ------------- src/front/wgsl/tests.rs | 70 ----- 5 files changed, 724 insertions(+), 709 deletions(-) create mode 100644 src/front/wgsl/number.rs delete mode 100644 src/front/wgsl/number_literals.rs diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 212e41f2b..1d019e94f 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -1,269 +1,10 @@ -use super::{conv, Error, ExpectedToken, NumberType, Span, Token, TokenSpan}; +use super::{conv, number::consume_number, Error, ExpectedToken, Span, Token, TokenSpan}; fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { let pos = input.find(|c| !what(c)).unwrap_or(input.len()); input.split_at(pos) } -/// Tries to skip a given prefix in the input string. -/// Returns whether the prefix was present and could therefore be skipped, -/// the remaining str and the number of *bytes* skipped. -pub fn try_skip_prefix<'a, 'b>(input: &'a str, prefix: &'b str) -> (bool, &'a str, usize) { - if let Some(rem) = input.strip_prefix(prefix) { - (true, rem, prefix.len()) - } else { - (false, input, 0) - } -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum NLDigitState { - Nothing, - LeadingZero, - DigitBeforeDot, - OnlyDot, - DigitsThenDot, - DigitAfterDot, - Exponent, - SignAfterExponent, - DigitAfterExponent, -} - -struct NumberLexerState { - _minus: bool, - hex: bool, - leading_zeros: usize, - digit_state: NLDigitState, - uint_suffix: bool, -} - -impl NumberLexerState { - // TODO: add proper error reporting, possibly through try_into_token function returning Result - - pub fn _is_valid_number(&self) -> bool { - match *self { - Self { - _minus: false, // No negative zero for integers. - hex, - leading_zeros, - digit_state: NLDigitState::LeadingZero, - .. - } => hex || leading_zeros == 1, // No leading zeros allowed in non-hex integers, "0" is always allowed. - Self { - _minus: minus, - hex, - leading_zeros, - digit_state: NLDigitState::DigitBeforeDot, - uint_suffix, - } => { - (hex || leading_zeros == 0) // No leading zeros allowed in non-hex integers. - // In this state the number has non-zero digits, - // i.e. it is not just "0". - && (minus ^ uint_suffix) // Either a negative number, or and unsigned integer, not both. - } - _ => self.is_float(), - } - } - - pub fn is_float(&self) -> bool { - !self.uint_suffix - && (self.digit_state == NLDigitState::DigitsThenDot - || self.digit_state == NLDigitState::DigitAfterDot - || self.digit_state == NLDigitState::DigitAfterExponent) - } -} - -fn consume_number(input: &str) -> (Token, &str) { - let (minus, working_substr, minus_offset) = try_skip_prefix(input, "-"); - - let (hex, working_substr, hex_offset) = try_skip_prefix(working_substr, "0x"); - - let mut state = NumberLexerState { - _minus: minus, - hex, - leading_zeros: 0, - digit_state: NLDigitState::Nothing, - uint_suffix: false, - }; - - let mut what = |c| { - match state { - NumberLexerState { - uint_suffix: true, .. - } => return false, // Scanning is done once we've reached a type suffix. - NumberLexerState { - hex, - digit_state: NLDigitState::Nothing, - .. - } => match c { - '0' => { - state.digit_state = NLDigitState::LeadingZero; - state.leading_zeros += 1; - } - '1'..='9' => { - state.digit_state = NLDigitState::DigitBeforeDot; - } - 'a'..='f' | 'A'..='F' if hex => { - state.digit_state = NLDigitState::DigitBeforeDot; - } - '.' => { - state.digit_state = NLDigitState::OnlyDot; - } - _ => return false, - }, - - NumberLexerState { - hex, - digit_state: NLDigitState::LeadingZero, - .. - } => match c { - '0' => { - // We stay in NLDigitState::LeadingZero. - state.leading_zeros += 1; - } - '1'..='9' => { - state.digit_state = NLDigitState::DigitBeforeDot; - } - 'a'..='f' | 'A'..='F' if hex => { - state.digit_state = NLDigitState::DigitBeforeDot; - } - '.' => { - state.digit_state = NLDigitState::DigitsThenDot; - } - 'e' | 'E' if !hex => { - state.digit_state = NLDigitState::Exponent; - } - 'p' | 'P' if hex => { - state.digit_state = NLDigitState::Exponent; - } - 'u' => { - // We stay in NLDigitState::LeadingZero. - state.uint_suffix = true; - } - _ => return false, - }, - - NumberLexerState { - hex, - digit_state: NLDigitState::DigitBeforeDot, - .. - } => match c { - '0'..='9' => { - // We stay in NLDigitState::DigitBeforeDot. - } - 'a'..='f' | 'A'..='F' if hex => { - // We stay in NLDigitState::DigitBeforeDot. - } - '.' => { - state.digit_state = NLDigitState::DigitsThenDot; - } - 'e' | 'E' if !hex => { - state.digit_state = NLDigitState::Exponent; - } - 'p' | 'P' if hex => { - state.digit_state = NLDigitState::Exponent; - } - 'u' => { - // We stay in NLDigitState::DigitBeforeDot. - state.uint_suffix = true; - } - _ => return false, - }, - - NumberLexerState { - hex, - digit_state: NLDigitState::OnlyDot, - .. - } => match c { - '0'..='9' => { - state.digit_state = NLDigitState::DigitAfterDot; - } - 'a'..='f' | 'A'..='F' if hex => { - state.digit_state = NLDigitState::DigitAfterDot; - } - _ => return false, - }, - - NumberLexerState { - hex, - digit_state: NLDigitState::DigitsThenDot | NLDigitState::DigitAfterDot, - .. - } => match c { - '0'..='9' => { - state.digit_state = NLDigitState::DigitAfterDot; - } - 'a'..='f' | 'A'..='F' if hex => { - state.digit_state = NLDigitState::DigitAfterDot; - } - 'e' | 'E' if !hex => { - state.digit_state = NLDigitState::Exponent; - } - 'p' | 'P' if hex => { - state.digit_state = NLDigitState::Exponent; - } - _ => return false, - }, - - NumberLexerState { - digit_state: NLDigitState::Exponent, - .. - } => match c { - '0'..='9' => { - state.digit_state = NLDigitState::DigitAfterExponent; - } - '-' | '+' => { - state.digit_state = NLDigitState::SignAfterExponent; - } - _ => return false, - }, - - NumberLexerState { - digit_state: NLDigitState::SignAfterExponent | NLDigitState::DigitAfterExponent, - .. - } => match c { - '0'..='9' => { - state.digit_state = NLDigitState::DigitAfterExponent; - } - _ => return false, - }, - } - - // No match branch has rejected this yet, so we are still in a number literal - true - }; - - let pos = working_substr - .find(|c| !what(c)) - .unwrap_or(working_substr.len()); - let (value, rest) = input.split_at(pos + minus_offset + hex_offset); - - // NOTE: This code can use string slicing, - // because number literals are exclusively ASCII. - // This means all relevant characters fit into one byte - // and using string slicing (which slices UTF-8 bytes) works for us. - - // TODO: A syntax error can already be recognized here, possibly report it at this stage. - - // Return possibly knowably incorrect (given !state.is_valid_number()) token for now. - ( - Token::Number { - value: if state.uint_suffix { - &value[..value.len() - 1] - } else { - value - }, - ty: if state.uint_suffix { - NumberType::Uint - } else if state.is_float() { - NumberType::Float - } else { - NumberType::Sint - }, - }, - rest, - ) -} - fn consume_token(input: &str, generic: bool) -> (Token<'_>, &str) { let mut chars = input.chars(); let cur = match chars.next() { @@ -632,6 +373,9 @@ impl<'a> Lexer<'a> { } } +#[cfg(test)] +use super::{number::Number, NumberError}; + #[cfg(test)] fn sub_test(source: &str, expected_tokens: &[Token]) { let mut lex = Lexer::new(source); @@ -641,41 +385,195 @@ fn sub_test(source: &str, expected_tokens: &[Token]) { assert_eq!(lex.next().0, Token::End); } +#[test] +fn test_numbers() { + // WGSL spec examples // + + // decimal integer + sub_test( + "0x123 0X123u 1u 123 0 0i 0x3f", + &[ + Token::Number(Ok(Number::I32(291))), + Token::Number(Ok(Number::U32(291))), + Token::Number(Ok(Number::U32(1))), + Token::Number(Ok(Number::I32(123))), + Token::Number(Ok(Number::I32(0))), + Token::Number(Ok(Number::I32(0))), + Token::Number(Ok(Number::I32(63))), + ], + ); + // decimal floating point + sub_test( + "0.e+4f 01. .01 12.34 .0f 0h 1e-3 0xa.fp+2 0x1P+4f 0X.3 0x3p+2h 0X1.fp-4 0x3.2p+2h", + &[ + Token::Number(Ok(Number::F32(0.))), + Token::Number(Ok(Number::F32(1.))), + Token::Number(Ok(Number::F32(0.01))), + Token::Number(Ok(Number::F32(12.34))), + Token::Number(Ok(Number::F32(0.))), + Token::Number(Err(NumberError::UnimplementedF16)), + Token::Number(Ok(Number::F32(0.001))), + Token::Number(Ok(Number::F32(43.75))), + Token::Number(Ok(Number::F32(16.))), + Token::Number(Ok(Number::F32(0.1875))), + Token::Number(Err(NumberError::UnimplementedF16)), + Token::Number(Ok(Number::F32(0.12109375))), + Token::Number(Err(NumberError::UnimplementedF16)), + ], + ); + + // MIN / MAX // + + // min / max decimal signed integer + sub_test( + "-2147483648i 2147483647i -2147483649i 2147483648i", + &[ + Token::Number(Ok(Number::I32(i32::MIN))), + Token::Number(Ok(Number::I32(i32::MAX))), + Token::Number(Err(NumberError::NotRepresentable)), + Token::Number(Err(NumberError::NotRepresentable)), + ], + ); + // min / max decimal unsigned integer + sub_test( + "0u 4294967295u -1u 4294967296u", + &[ + Token::Number(Ok(Number::U32(u32::MIN))), + Token::Number(Ok(Number::U32(u32::MAX))), + Token::Number(Err(NumberError::NotRepresentable)), + Token::Number(Err(NumberError::NotRepresentable)), + ], + ); + + // min / max hexadecimal signed integer + sub_test( + "-0x80000000i 0x7FFFFFFFi -0x80000001i 0x80000000i", + &[ + Token::Number(Ok(Number::I32(i32::MIN))), + Token::Number(Ok(Number::I32(i32::MAX))), + Token::Number(Err(NumberError::NotRepresentable)), + Token::Number(Err(NumberError::NotRepresentable)), + ], + ); + // min / max hexadecimal unsigned integer + sub_test( + "0x0u 0xFFFFFFFFu -0x1u 0x100000000u", + &[ + Token::Number(Ok(Number::U32(u32::MIN))), + Token::Number(Ok(Number::U32(u32::MAX))), + Token::Number(Err(NumberError::NotRepresentable)), + Token::Number(Err(NumberError::NotRepresentable)), + ], + ); + + /// ≈ 2^-126 * 2^−23 (= 2^−149) + const SMALLEST_POSITIVE_SUBNORMAL_F32: f32 = 1e-45; + /// ≈ 2^-126 * (1 − 2^−23) + const LARGEST_SUBNORMAL_F32: f32 = 1.1754942e-38; + /// ≈ 2^-126 + const SMALLEST_POSITIVE_NORMAL_F32: f32 = f32::MIN_POSITIVE; + /// ≈ 1 − 2^−24 + const LARGEST_F32_LESS_THAN_ONE: f32 = 0.99999994; + /// ≈ 1 + 2^−23 + const SMALLEST_F32_LARGER_THAN_ONE: f32 = 1.0000001; + /// ≈ -(2^127 * (2 − 2^−23)) + const SMALLEST_NORMAL_F32: f32 = f32::MIN; + /// ≈ 2^127 * (2 − 2^−23) + const LARGEST_NORMAL_F32: f32 = f32::MAX; + + // decimal floating point + sub_test( + "1e-45f 1.1754942e-38f 1.17549435e-38f 0.99999994f 1.0000001f -3.40282347e+38f 3.40282347e+38f", + &[ + Token::Number(Ok(Number::F32( + SMALLEST_POSITIVE_SUBNORMAL_F32, + ))), + Token::Number(Ok(Number::F32( + LARGEST_SUBNORMAL_F32, + ))), + Token::Number(Ok(Number::F32( + SMALLEST_POSITIVE_NORMAL_F32, + ))), + Token::Number(Ok(Number::F32( + LARGEST_F32_LESS_THAN_ONE, + ))), + Token::Number(Ok(Number::F32( + SMALLEST_F32_LARGER_THAN_ONE, + ))), + Token::Number(Ok(Number::F32( + SMALLEST_NORMAL_F32, + ))), + Token::Number(Ok(Number::F32( + LARGEST_NORMAL_F32, + ))), + ], + ); + sub_test( + "-3.40282367e+38f 3.40282367e+38f", + &[ + Token::Number(Err(NumberError::NotRepresentable)), // ≈ -2^128 + Token::Number(Err(NumberError::NotRepresentable)), // ≈ 2^128 + ], + ); + + // hexadecimal floating point + sub_test( + "0x1p-149f 0x7FFFFFp-149f 0x1p-126f 0xFFFFFFp-24f 0x800001p-23f -0xFFFFFFp+104f 0xFFFFFFp+104f", + &[ + Token::Number(Ok(Number::F32( + SMALLEST_POSITIVE_SUBNORMAL_F32, + ))), + Token::Number(Ok(Number::F32( + LARGEST_SUBNORMAL_F32, + ))), + Token::Number(Ok(Number::F32( + SMALLEST_POSITIVE_NORMAL_F32, + ))), + Token::Number(Ok(Number::F32( + LARGEST_F32_LESS_THAN_ONE, + ))), + Token::Number(Ok(Number::F32( + SMALLEST_F32_LARGER_THAN_ONE, + ))), + Token::Number(Ok(Number::F32( + SMALLEST_NORMAL_F32, + ))), + Token::Number(Ok(Number::F32( + LARGEST_NORMAL_F32, + ))), + ], + ); + sub_test( + "-0x1p128f 0x1p128f 0x1.000001p0f", + &[ + Token::Number(Err(NumberError::NotRepresentable)), // = -2^128 + Token::Number(Err(NumberError::NotRepresentable)), // = 2^128 + Token::Number(Err(NumberError::NotRepresentable)), + ], + ); +} + #[test] fn test_tokens() { sub_test("id123_OK", &[Token::Word("id123_OK")]); sub_test( "92No", - &[ - Token::Number { - value: "92", - ty: NumberType::Sint, - }, - Token::Word("No"), - ], + &[Token::Number(Ok(Number::I32(92))), Token::Word("No")], ); sub_test( "2u3o", &[ - Token::Number { - value: "2", - ty: NumberType::Uint, - }, - Token::Number { - value: "3", - ty: NumberType::Sint, - }, + Token::Number(Ok(Number::U32(2))), + Token::Number(Ok(Number::I32(3))), Token::Word("o"), ], ); sub_test( "2.4f44po", &[ - Token::Number { - value: "2.4", - ty: NumberType::Float, - }, - Token::Word("f44po"), + Token::Number(Ok(Number::F32(2.4))), + Token::Number(Ok(Number::I32(44))), + Token::Word("po"), ], ); sub_test( @@ -715,10 +613,7 @@ fn test_variable_decl() { Token::Attribute, Token::Word("group"), Token::Paren('('), - Token::Number { - value: "0", - ty: NumberType::Sint, - }, + Token::Number(Ok(Number::I32(0))), Token::Paren(')'), Token::Word("var"), Token::Paren('<'), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index a7c1fdced..0e32f54ff 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -7,7 +7,7 @@ Frontend for [WGSL][wgsl] (WebGPU Shading Language). mod construction; mod conv; mod lexer; -mod number_literals; +mod number; #[cfg(test)] mod tests; @@ -18,16 +18,10 @@ use crate::{ }, span::SourceLocation, span::Span as NagaSpan, - Bytes, ConstantInner, FastHashMap, ScalarValue, + ConstantInner, FastHashMap, ScalarValue, }; -use self::{ - lexer::Lexer, - number_literals::{ - get_f32_literal, get_i32_literal, get_u32_literal, parse_generic_non_negative_int_literal, - parse_non_negative_sint_literal, - }, -}; +use self::{lexer::Lexer, number::Number}; use codespan_reporting::{ diagnostic::{Diagnostic, Label}, files::SimpleFile, @@ -36,12 +30,11 @@ use codespan_reporting::{ termcolor::{ColorChoice, ColorSpec, StandardStream, WriteColor}, }, }; -use hexf_parse::ParseHexfError; use std::{ borrow::Cow, convert::TryFrom, io::{self, Write}, - num::{NonZeroU32, ParseFloatError, ParseIntError}, + num::NonZeroU32, ops, }; use thiserror::Error; @@ -49,19 +42,12 @@ use thiserror::Error; type Span = ops::Range; type TokenSpan<'a> = (Token<'a>, Span); -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum NumberType { - Sint, - Uint, - Float, -} - #[derive(Copy, Clone, Debug, PartialEq)] pub enum Token<'a> { Separator(char), Paren(char), Attribute, - Number { value: &'a str, ty: NumberType }, + Number(Result), Word(&'a str), Operation(char), LogicalOperation(char), @@ -75,14 +61,18 @@ pub enum Token<'a> { End, } +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum NumberType { + I32, + U32, + F32, +} + #[derive(Copy, Clone, Debug, PartialEq)] pub enum ExpectedToken<'a> { Token(Token<'a>), Identifier, - Number { - ty: Option, - width: Option, - }, + Number(NumberType), Integer, Constant, /// Expected: constant, parenthesized expression, identifier @@ -101,36 +91,25 @@ pub enum ExpectedToken<'a> { GlobalItem, } -#[derive(Clone, Debug, Error)] -pub enum BadIntError { - #[error(transparent)] - ParseIntError(#[from] ParseIntError), - #[error("non-hex negative zero integer literals are not allowed")] - NegativeZero, - #[error("leading zeros for non-hex integer literals are not allowed")] - LeadingZeros, -} - -#[derive(Clone, Debug, Error)] -pub enum BadFloatError { - #[error(transparent)] - ParseFloatError(#[from] ParseFloatError), - #[error(transparent)] - ParseHexfError(#[from] ParseHexfError), +#[derive(Clone, Copy, Debug, Error, PartialEq)] +pub enum NumberError { + #[error("invalid numeric literal format")] + Invalid, + #[error("numeric literal not representable by target type")] + NotRepresentable, + #[error("unimplemented f16 type")] + UnimplementedF16, } #[derive(Clone, Debug)] pub enum Error<'a> { Unexpected(TokenSpan<'a>, ExpectedToken<'a>), UnexpectedComponents(Span), - BadU32(Span, BadIntError), - BadI32(Span, BadIntError), + BadNumber(Span, NumberError), /// A negative signed integer literal where both signed and unsigned, /// but only non-negative literals are allowed. NegativeInt(Span), - BadFloat(Span, BadFloatError), BadU32Constant(Span), - BadScalarWidth(Span, Bytes), BadMatrixScalarKind(Span, crate::ScalarKind, u8), BadAccessor(Span), BadTexture(Span), @@ -147,7 +126,7 @@ pub enum Error<'a> { BadIncrDecrReferenceType(Span), InvalidResolve(ResolveError), InvalidForInitializer(Span), - InvalidGatherComponent(Span, i32), + InvalidGatherComponent(Span, u32), InvalidConstructorComponentType(Span, i32), InvalidIdentifierUnderscore(Span), ReservedIdentifierPrefix(Span), @@ -192,9 +171,7 @@ impl<'a> Error<'a> { Token::Separator(c) => format!("'{}'", c), Token::Paren(c) => format!("'{}'", c), Token::Attribute => "@".to_string(), - Token::Number { value, .. } => { - format!("number ({})", value) - } + Token::Number(_) => "number".to_string(), Token::Word(s) => s.to_string(), Token::Operation(c) => format!("operation ('{}')", c), Token::LogicalOperation(c) => format!("logical operation ('{}')", c), @@ -210,25 +187,12 @@ impl<'a> Error<'a> { } } ExpectedToken::Identifier => "identifier".to_string(), - ExpectedToken::Number { ty, width } => { - let literal_ty_str = match ty { - Some(NumberType::Float) => "floating-point", - Some(NumberType::Uint) => "unsigned integer", - Some(NumberType::Sint) => "signed integer", - None => "arbitrary number", - }; - if let Some(width) = width { - format!( - "{} literal of {}-bit width", - literal_ty_str, - width as u32 * 8, - ) - } else { - format!( - "{} literal of arbitrary width", - literal_ty_str, - ) - } + ExpectedToken::Number(ty) => { + match ty { + NumberType::I32 => "32-bit signed integer literal", + NumberType::U32 => "32-bit unsigned integer literal", + NumberType::F32 => "32-bit floating-point literal", + }.to_string() }, ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), ExpectedToken::Constant => "constant".to_string(), @@ -258,21 +222,13 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "unexpected components".into())], notes: vec![], }, - Error::BadU32(ref bad_span, ref err) => ParseError { + Error::BadNumber(ref bad_span, ref err) => ParseError { message: format!( - "expected unsigned integer literal, found `{}`", - &source[bad_span.clone()], + "{}: `{}`", + err,&source[bad_span.clone()], ), - labels: vec![(bad_span.clone(), "expected unsigned integer".into())], - notes: vec![err.to_string()], - }, - Error::BadI32(ref bad_span, ref err) => ParseError { - message: format!( - "expected integer literal, found `{}`", - &source[bad_span.clone()], - ), - labels: vec![(bad_span.clone(), "expected signed integer".into())], - notes: vec![err.to_string()], + labels: vec![(bad_span.clone(), err.to_string().into())], + notes: vec![], }, Error::NegativeInt(ref bad_span) => ParseError { message: format!( @@ -282,14 +238,6 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "expected non-negative integer".into())], notes: vec![], }, - Error::BadFloat(ref bad_span, ref err) => ParseError { - message: format!( - "expected floating-point literal, found `{}`", - &source[bad_span.clone()], - ), - labels: vec![(bad_span.clone(), "expected floating-point literal".into())], - notes: vec![err.to_string()], - }, Error::BadU32Constant(ref bad_span) => ParseError { message: format!( "expected unsigned integer constant expression, found `{}`", @@ -298,11 +246,6 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "expected unsigned integer".into())], notes: vec![], }, - Error::BadScalarWidth(ref bad_span, width) => ParseError { - message: format!("invalid width of `{}` bits for literal", width as u32 * 8,), - labels: vec![(bad_span.clone(), "invalid width".into())], - notes: vec!["the only valid width is 32 for now".to_string()], - }, Error::BadMatrixScalarKind( ref span, kind, @@ -1235,7 +1178,7 @@ impl BindingParser { match name { "location" => { lexer.expect(Token::Paren('('))?; - self.location = Some(parse_non_negative_sint_literal(lexer, 4)?); + self.location = Some(Parser::parse_non_negative_i32_literal(lexer)?); lexer.expect(Token::Paren(')'))?; } "builtin" => { @@ -1424,38 +1367,45 @@ impl Parser { lexer.span_from(initial) } - fn get_constant_inner<'a>( - word: &'a str, - ty: NumberType, - token_span: TokenSpan<'a>, - ) -> Result> { - let span = token_span.1; - - let value = match ty { - NumberType::Sint => { - get_i32_literal(word, span).map(|val| crate::ScalarValue::Sint(val as i64))? - } - NumberType::Uint => { - get_u32_literal(word, span).map(|val| crate::ScalarValue::Uint(val as u64))? - } - NumberType::Float => { - get_f32_literal(word, span).map(|val| crate::ScalarValue::Float(val as f64))? - } - }; - - Ok(crate::ConstantInner::Scalar { value, width: 4 }) - } - fn parse_switch_value<'a>(lexer: &mut Lexer<'a>, uint: bool) -> Result> { let token_span = lexer.next(); - let word = match token_span.0 { - Token::Number { value, .. } => value, - _ => return Err(Error::Unexpected(token_span, ExpectedToken::Integer)), - }; + match token_span.0 { + Token::Number(Ok(Number::U32(num))) if uint => Ok(num as i32), + Token::Number(Ok(Number::I32(num))) if !uint => Ok(num), + Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)), + _ => Err(Error::Unexpected(token_span, ExpectedToken::Integer)), + } + } - match uint { - true => get_u32_literal(word, token_span.1).map(|v| v as i32), - false => get_i32_literal(word, token_span.1), + /// Parse a non-negative signed integer literal. + /// This is for attributes like `size`, `location` and others. + fn parse_non_negative_i32_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + match lexer.next() { + (Token::Number(Ok(Number::I32(num))), span) => { + u32::try_from(num).map_err(|_| Error::NegativeInt(span)) + } + (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), + other => Err(Error::Unexpected( + other, + ExpectedToken::Number(NumberType::I32), + )), + } + } + + /// Parse a non-negative integer literal that may be either signed or unsigned. + /// This is for the `workgroup_size` attribute and array lengths. + /// Note: these values should be no larger than [`i32::MAX`], but this is not checked here. + fn parse_generic_non_negative_int_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + match lexer.next() { + (Token::Number(Ok(Number::I32(num))), span) => { + u32::try_from(num).map_err(|_| Error::NegativeInt(span)) + } + (Token::Number(Ok(Number::U32(num))), _) => Ok(num), + (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), + other => Err(Error::Unexpected( + other, + ExpectedToken::Number(NumberType::I32), + )), } } @@ -1999,17 +1949,9 @@ impl Parser { "textureGather" => { let _ = lexer.next(); lexer.open_arguments()?; - let component = if let ( - Token::Number { - value, - ty: NumberType::Sint, - }, - span, - ) = lexer.peek() - { - let _ = lexer.next(); + let component = if let (Token::Number(..), span) = lexer.peek() { + let index = Self::parse_non_negative_i32_literal(lexer)?; lexer.expect(Token::Separator(','))?; - let index = get_i32_literal(value, span.clone())?; *crate::SwizzleComponent::XYZW .get(index as usize) .ok_or(Error::InvalidGatherComponent(span, index))? @@ -2212,9 +2154,22 @@ impl Parser { let inner = match first_token_span { (Token::Word("true"), _) => crate::ConstantInner::boolean(true), (Token::Word("false"), _) => crate::ConstantInner::boolean(false), - (Token::Number { value, ty }, _) => { - Self::get_constant_inner(value, ty, first_token_span)? - } + (Token::Number(num), _) => match num { + Ok(Number::I32(num)) => crate::ConstantInner::Scalar { + value: crate::ScalarValue::Sint(num as i64), + width: 4, + }, + Ok(Number::U32(num)) => crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(num as u64), + width: 4, + }, + Ok(Number::F32(num)) => crate::ConstantInner::Scalar { + value: crate::ScalarValue::Float(num as f64), + width: 4, + }, + Ok(Number::AbstractInt(_) | Number::AbstractFloat(_)) => unreachable!(), + Err(e) => return Err(Error::BadNumber(first_token_span.1, e)), + }, (Token::Word(name), name_span) => { // look for an existing constant first for (handle, var) in const_arena.iter() { @@ -2305,10 +2260,8 @@ impl Parser { self.pop_scope(lexer); expr } - token @ (Token::Word("true" | "false") | Token::Number { .. }, _) => { - let _ = lexer.next(); - let const_handle = - self.parse_const_expression_impl(token, lexer, None, ctx.types, ctx.constants)?; + (Token::Word("true" | "false") | Token::Number(..), _) => { + let const_handle = self.parse_const_expression(lexer, ctx.types, ctx.constants)?; let span = NagaSpan::from(self.pop_scope(lexer)); TypedExpression::non_reference( ctx.interrupt_emitter(crate::Expression::Constant(const_handle), span), @@ -2853,15 +2806,15 @@ impl Parser { match lexer.next_ident_with_span()? { ("size", _) => { lexer.expect(Token::Paren('('))?; - let (value, span) = lexer - .capture_span(|lexer| parse_non_negative_sint_literal(lexer, 4))?; + let (value, span) = + lexer.capture_span(Self::parse_non_negative_i32_literal)?; lexer.expect(Token::Paren(')'))?; size = Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign(span))?); } ("align", _) => { lexer.expect(Token::Paren('('))?; - let (value, span) = lexer - .capture_span(|lexer| parse_non_negative_sint_literal(lexer, 4))?; + let (value, span) = + lexer.capture_span(Self::parse_non_negative_i32_literal)?; lexer.expect(Token::Paren(')'))?; align = Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign(span))?); } @@ -4237,12 +4190,12 @@ impl Parser { match lexer.next_ident_with_span()? { ("binding", _) => { lexer.expect(Token::Paren('('))?; - bind_index = Some(parse_non_negative_sint_literal(lexer, 4)?); + bind_index = Some(Self::parse_non_negative_i32_literal(lexer)?); lexer.expect(Token::Paren(')'))?; } ("group", _) => { lexer.expect(Token::Paren('('))?; - bind_group = Some(parse_non_negative_sint_literal(lexer, 4)?); + bind_group = Some(Self::parse_non_negative_i32_literal(lexer)?); lexer.expect(Token::Paren(')'))?; } ("vertex", _) => { @@ -4256,8 +4209,9 @@ impl Parser { } ("workgroup_size", _) => { lexer.expect(Token::Paren('('))?; + workgroup_size = [1u32; 3]; for (i, size) in workgroup_size.iter_mut().enumerate() { - *size = parse_generic_non_negative_int_literal(lexer, 4)?; + *size = Self::parse_generic_non_negative_int_literal(lexer)?; match lexer.next() { (Token::Paren(')'), _) => break, (Token::Separator(','), _) if i != 2 => (), @@ -4269,11 +4223,6 @@ impl Parser { } } } - for size in workgroup_size.iter_mut() { - if *size == 0 { - *size = 1; - } - } } ("early_depth_test", _) => { let conservative = if lexer.skip(Token::Paren('(')) { diff --git a/src/front/wgsl/number.rs b/src/front/wgsl/number.rs new file mode 100644 index 000000000..d7e8801b0 --- /dev/null +++ b/src/front/wgsl/number.rs @@ -0,0 +1,445 @@ +use std::borrow::Cow; + +use super::{NumberError, Token}; + +/// When using this type assume no Abstract Int/Float for now +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum Number { + /// Abstract Int (-2^63 ≤ i < 2^63) + AbstractInt(i64), + /// Abstract Float (IEEE-754 binary64) + AbstractFloat(f64), + /// Concrete i32 + I32(i32), + /// Concrete u32 + U32(u32), + /// Concrete f32 + F32(f32), +} + +impl Number { + /// Convert abstract numbers to a plausible concrete counterpart. + /// + /// Return concrete numbers unchanged. If the conversion would be + /// lossy, return an error. + fn abstract_to_concrete(self) -> Result { + match self { + Number::AbstractInt(num) => { + use std::convert::TryFrom; + i32::try_from(num) + .map(Number::I32) + .map_err(|_| NumberError::NotRepresentable) + } + Number::AbstractFloat(num) => { + let num = num as f32; + if num.is_finite() { + Ok(Number::F32(num)) + } else { + Err(NumberError::NotRepresentable) + } + } + num => Ok(num), + } + } +} + +// TODO: when implementing Creation-Time Expressions, remove the ability to match the minus sign + +pub(super) fn consume_number(input: &str) -> (Token<'_>, &str) { + let (result, rest) = parse(input); + ( + Token::Number(result.and_then(Number::abstract_to_concrete)), + rest, + ) +} + +enum Kind { + Int(IntKind), + Float(FloatKind), +} + +enum IntKind { + I32, + U32, +} + +enum FloatKind { + F32, + F16, +} + +// The following regexes (from the WGSL spec) will be matched: + +// int_literal: +// | / 0 [iu]? / +// | / [1-9][0-9]* [iu]? / +// | / 0[xX][0-9a-fA-F]+ [iu]? / + +// decimal_float_literal: +// | / 0 [fh] / +// | / [1-9][0-9]* [fh] / +// | / [0-9]* \.[0-9]+ ([eE][+-]?[0-9]+)? [fh]? / +// | / [0-9]+ \.[0-9]* ([eE][+-]?[0-9]+)? [fh]? / +// | / [0-9]+ [eE][+-]?[0-9]+ [fh]? / + +// hex_float_literal: +// | / 0[xX][0-9a-fA-F]* \.[0-9a-fA-F]+ ([pP][+-]?[0-9]+ [fh]?)? / +// | / 0[xX][0-9a-fA-F]+ \.[0-9a-fA-F]* ([pP][+-]?[0-9]+ [fh]?)? / +// | / 0[xX][0-9a-fA-F]+ [pP][+-]?[0-9]+ [fh]? / + +// You could visualize the regex below via https://debuggex.com to get a rough idea what `parse` is doing +// -?(?:0[xX](?:([0-9a-fA-F]+\.[0-9a-fA-F]*|[0-9a-fA-F]*\.[0-9a-fA-F]+)(?:([pP][+-]?[0-9]+)([fh]?))?|([0-9a-fA-F]+)([pP][+-]?[0-9]+)([fh]?)|([0-9a-fA-F]+)([iu]?))|((?:[0-9]+[eE][+-]?[0-9]+|(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?))([fh]?)|((?:[0-9]|[1-9][0-9]+))([iufh]?)) + +fn parse(input: &str) -> (Result, &str) { + /// returns `true` and consumes `X` bytes from the given byte buffer + /// if the given `X` nr of patterns are found at the start of the buffer + macro_rules! consume { + ($bytes:ident, $($($pattern:pat)|*),*) => { + match $bytes { + &[$($($pattern)|*),*, ref rest @ ..] => { $bytes = rest; true }, + _ => false, + } + }; + } + + /// consumes one byte from the given byte buffer + /// if one of the given patterns are found at the start of the buffer + /// returning the corresponding expr for the matched pattern + macro_rules! consume_map { + ($bytes:ident, [$($($pattern:pat)|* => $to:expr),*]) => { + match $bytes { + $( &[$($pattern)|*, ref rest @ ..] => { $bytes = rest; Some($to) }, )* + _ => None, + } + }; + } + + /// consumes all consecutive bytes matched by the `0-9` pattern from the given byte buffer + /// returning the number of consumed bytes + macro_rules! consume_dec_digits { + ($bytes:ident) => {{ + let start_len = $bytes.len(); + while let &[b'0'..=b'9', ref rest @ ..] = $bytes { + $bytes = rest; + } + start_len - $bytes.len() + }}; + } + + /// consumes all consecutive bytes matched by the `0-9 | a-f | A-F` pattern from the given byte buffer + /// returning the number of consumed bytes + macro_rules! consume_hex_digits { + ($bytes:ident) => {{ + let start_len = $bytes.len(); + while let &[b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F', ref rest @ ..] = $bytes { + $bytes = rest; + } + start_len - $bytes.len() + }}; + } + + /// maps the given `&[u8]` (tail of the initial `input: &str`) to a `&str` + macro_rules! rest_to_str { + ($bytes:ident) => { + &input[input.len() - $bytes.len()..] + }; + } + + struct ExtractSubStr<'a>(&'a str); + + impl<'a> ExtractSubStr<'a> { + /// given an `input` and a `start` (tail of the `input`) + /// creates a new [ExtractSubStr] + fn start(input: &'a str, start: &'a [u8]) -> Self { + let start = input.len() - start.len(); + Self(&input[start..]) + } + /// given an `end` (tail of the initial `input`) + /// returns a substring of `input` + fn end(&self, end: &'a [u8]) -> &'a str { + let end = self.0.len() - end.len(); + &self.0[..end] + } + } + + let mut bytes = input.as_bytes(); + + let general_extract = ExtractSubStr::start(input, bytes); + + let is_negative = consume!(bytes, b'-'); + + if consume!(bytes, b'0', b'x' | b'X') { + let digits_extract = ExtractSubStr::start(input, bytes); + + let consumed = consume_hex_digits!(bytes); + + if consume!(bytes, b'.') { + let consumed_after_period = consume_hex_digits!(bytes); + + if consumed + consumed_after_period == 0 { + return (Err(NumberError::Invalid), rest_to_str!(bytes)); + } + + let significand = general_extract.end(bytes); + + if consume!(bytes, b'p' | b'P') { + consume!(bytes, b'+' | b'-'); + let consumed = consume_dec_digits!(bytes); + + if consumed == 0 { + return (Err(NumberError::Invalid), rest_to_str!(bytes)); + } + + let number = general_extract.end(bytes); + + let kind = consume_map!(bytes, [b'f' => FloatKind::F32, b'h' => FloatKind::F16]); + + (parse_hex_float(number, kind), rest_to_str!(bytes)) + } else { + ( + parse_hex_float_missing_exponent(significand, None), + rest_to_str!(bytes), + ) + } + } else { + if consumed == 0 { + return (Err(NumberError::Invalid), rest_to_str!(bytes)); + } + + let significand = general_extract.end(bytes); + let digits = digits_extract.end(bytes); + + let exp_extract = ExtractSubStr::start(input, bytes); + + if consume!(bytes, b'p' | b'P') { + consume!(bytes, b'+' | b'-'); + let consumed = consume_dec_digits!(bytes); + + if consumed == 0 { + return (Err(NumberError::Invalid), rest_to_str!(bytes)); + } + + let exponent = exp_extract.end(bytes); + + let kind = consume_map!(bytes, [b'f' => FloatKind::F32, b'h' => FloatKind::F16]); + + ( + parse_hex_float_missing_period(significand, exponent, kind), + rest_to_str!(bytes), + ) + } else { + let kind = consume_map!(bytes, [b'i' => IntKind::I32, b'u' => IntKind::U32]); + + ( + parse_hex_int(is_negative, digits, kind), + rest_to_str!(bytes), + ) + } + } + } else { + let is_first_zero = bytes.first() == Some(&b'0'); + + let consumed = consume_dec_digits!(bytes); + + if consume!(bytes, b'.') { + let consumed_after_period = consume_dec_digits!(bytes); + + if consumed + consumed_after_period == 0 { + return (Err(NumberError::Invalid), rest_to_str!(bytes)); + } + + if consume!(bytes, b'e' | b'E') { + consume!(bytes, b'+' | b'-'); + let consumed = consume_dec_digits!(bytes); + + if consumed == 0 { + return (Err(NumberError::Invalid), rest_to_str!(bytes)); + } + } + + let number = general_extract.end(bytes); + + let kind = consume_map!(bytes, [b'f' => FloatKind::F32, b'h' => FloatKind::F16]); + + (parse_dec_float(number, kind), rest_to_str!(bytes)) + } else { + if consumed == 0 { + return (Err(NumberError::Invalid), rest_to_str!(bytes)); + } + + if consume!(bytes, b'e' | b'E') { + consume!(bytes, b'+' | b'-'); + let consumed = consume_dec_digits!(bytes); + + if consumed == 0 { + return (Err(NumberError::Invalid), rest_to_str!(bytes)); + } + + let number = general_extract.end(bytes); + + let kind = consume_map!(bytes, [b'f' => FloatKind::F32, b'h' => FloatKind::F16]); + + (parse_dec_float(number, kind), rest_to_str!(bytes)) + } else { + // make sure the multi-digit numbers don't start with zero + if consumed > 1 && is_first_zero { + return (Err(NumberError::Invalid), rest_to_str!(bytes)); + } + + let digits_with_sign = general_extract.end(bytes); + + let kind = consume_map!(bytes, [ + b'i' => Kind::Int(IntKind::I32), + b'u' => Kind::Int(IntKind::U32), + b'f' => Kind::Float(FloatKind::F32), + b'h' => Kind::Float(FloatKind::F16) + ]); + + ( + parse_dec(is_negative, digits_with_sign, kind), + rest_to_str!(bytes), + ) + } + } + } +} + +fn parse_hex_float_missing_exponent( + // format: -?0[xX] ( [0-9a-fA-F]+\.[0-9a-fA-F]* | [0-9a-fA-F]*\.[0-9a-fA-F]+ ) + significand: &str, + kind: Option, +) -> Result { + let hexf_input = format!("{}{}", significand, "p0"); + parse_hex_float(&hexf_input, kind) +} + +fn parse_hex_float_missing_period( + // format: -?0[xX] [0-9a-fA-F]+ + significand: &str, + // format: [pP][+-]?[0-9]+ + exponent: &str, + kind: Option, +) -> Result { + let hexf_input = format!("{}.{}", significand, exponent); + parse_hex_float(&hexf_input, kind) +} + +fn parse_hex_int( + is_negative: bool, + // format: [0-9a-fA-F]+ + digits: &str, + kind: Option, +) -> Result { + let digits_with_sign = if is_negative { + Cow::Owned(format!("-{}", digits)) + } else { + Cow::Borrowed(digits) + }; + parse_int(&digits_with_sign, kind, 16, is_negative) +} + +fn parse_dec( + is_negative: bool, + // format: -? ( [0-9] | [1-9][0-9]+ ) + digits_with_sign: &str, + kind: Option, +) -> Result { + match kind { + None => parse_int(digits_with_sign, None, 10, is_negative), + Some(Kind::Int(kind)) => parse_int(digits_with_sign, Some(kind), 10, is_negative), + Some(Kind::Float(kind)) => parse_dec_float(digits_with_sign, Some(kind)), + } +} + +// Float parsing notes + +// The following chapters of IEEE 754-2019 are relevant: +// +// 7.4 Overflow (largest finite number is exceeded by what would have been +// the rounded floating-point result were the exponent range unbounded) +// +// 7.5 Underflow (tiny non-zero result is detected; +// for decimal formats tininess is detected before rounding when a non-zero result +// computed as though both the exponent range and the precision were unbounded +// would lie strictly between 2^−126) +// +// 7.6 Inexact (rounded result differs from what would have been computed +// were both exponent range and precision unbounded) + +// The WGSL spec requires us to error: +// on overflow for decimal floating point literals +// on overflow and inexact for hexadecimal floating point literals +// (underflow is not mentioned) + +// hexf_parse errors on overflow, underflow, inexact +// rust std lib float from str handles overflow, underflow, inexact transparently (rounds and will not error) + +// Therefore we only check for overflow manually for decimal floating point literals + +// input format: -?0[xX] ( [0-9a-fA-F]+\.[0-9a-fA-F]* | [0-9a-fA-F]*\.[0-9a-fA-F]+ ) [pP][+-]?[0-9]+ +fn parse_hex_float(input: &str, kind: Option) -> Result { + match kind { + None => match hexf_parse::parse_hexf64(input, false) { + Ok(num) => Ok(Number::AbstractFloat(num)), + // can only be ParseHexfErrorKind::Inexact but we can't check since it's private + _ => Err(NumberError::NotRepresentable), + }, + Some(FloatKind::F32) => match hexf_parse::parse_hexf32(input, false) { + Ok(num) => Ok(Number::F32(num)), + // can only be ParseHexfErrorKind::Inexact but we can't check since it's private + _ => Err(NumberError::NotRepresentable), + }, + Some(FloatKind::F16) => Err(NumberError::UnimplementedF16), + } +} + +// input format: -? ( [0-9]+\.[0-9]* | [0-9]*\.[0-9]+ ) ([eE][+-]?[0-9]+)? +// | -? [0-9]+ [eE][+-]?[0-9]+ +fn parse_dec_float(input: &str, kind: Option) -> Result { + match kind { + None => { + let num = input.parse::().unwrap(); // will never fail + num.is_finite() + .then(|| Number::AbstractFloat(num)) + .ok_or(NumberError::NotRepresentable) + } + Some(FloatKind::F32) => { + let num = input.parse::().unwrap(); // will never fail + num.is_finite() + .then(|| Number::F32(num)) + .ok_or(NumberError::NotRepresentable) + } + Some(FloatKind::F16) => Err(NumberError::UnimplementedF16), + } +} + +fn parse_int( + input: &str, + kind: Option, + radix: u32, + is_negative: bool, +) -> Result { + fn map_err(e: core::num::ParseIntError) -> NumberError { + match *e.kind() { + core::num::IntErrorKind::PosOverflow | core::num::IntErrorKind::NegOverflow => { + NumberError::NotRepresentable + } + _ => unreachable!(), + } + } + match kind { + None => match i64::from_str_radix(input, radix) { + Ok(num) => Ok(Number::AbstractInt(num)), + Err(e) => Err(map_err(e)), + }, + Some(IntKind::I32) => match i32::from_str_radix(input, radix) { + Ok(num) => Ok(Number::I32(num)), + Err(e) => Err(map_err(e)), + }, + Some(IntKind::U32) if is_negative => Err(NumberError::NotRepresentable), + Some(IntKind::U32) => match u32::from_str_radix(input, radix) { + Ok(num) => Ok(Number::U32(num)), + Err(e) => Err(map_err(e)), + }, + } +} diff --git a/src/front/wgsl/number_literals.rs b/src/front/wgsl/number_literals.rs deleted file mode 100644 index 6691ab2d0..000000000 --- a/src/front/wgsl/number_literals.rs +++ /dev/null @@ -1,204 +0,0 @@ -use std::convert::TryFrom; - -use hexf_parse::parse_hexf32; - -use crate::Bytes; - -use super::{ - lexer::{try_skip_prefix, Lexer}, - BadFloatError, BadIntError, Error, ExpectedToken, NumberType, Span, Token, -}; - -fn check_int_literal(word_without_minus: &str, minus: bool, hex: bool) -> Result<(), BadIntError> { - let leading_zeros = word_without_minus - .bytes() - .take_while(|&b| b == b'0') - .count(); - - if word_without_minus == "0" && minus { - Err(BadIntError::NegativeZero) - } else if word_without_minus != "0" && !hex && leading_zeros != 0 { - Err(BadIntError::LeadingZeros) - } else { - Ok(()) - } -} - -pub fn get_i32_literal(word: &str, span: Span) -> Result> { - let (minus, word_without_minus, _) = try_skip_prefix(word, "-"); - let (hex, word_without_minus_and_0x, _) = try_skip_prefix(word_without_minus, "0x"); - - check_int_literal(word_without_minus, minus, hex) - .map_err(|e| Error::BadI32(span.clone(), e))?; - - let parsed_val = match (hex, minus) { - (true, true) => i32::from_str_radix(&format!("-{}", word_without_minus_and_0x), 16), - (true, false) => i32::from_str_radix(word_without_minus_and_0x, 16), - (false, _) => word.parse(), - }; - - parsed_val.map_err(|e| Error::BadI32(span, e.into())) -} - -pub fn get_u32_literal(word: &str, span: Span) -> Result> { - let (minus, word_without_minus, _) = try_skip_prefix(word, "-"); - let (hex, word_without_minus_and_0x, _) = try_skip_prefix(word_without_minus, "0x"); - - check_int_literal(word_without_minus, minus, hex) - .map_err(|e| Error::BadU32(span.clone(), e))?; - - // We need to add a minus here as well, since the lexer also accepts syntactically incorrect negative uints - let parsed_val = match (hex, minus) { - (true, true) => u32::from_str_radix(&format!("-{}", word_without_minus_and_0x), 16), - (true, false) => u32::from_str_radix(word_without_minus_and_0x, 16), - (false, _) => word.parse(), - }; - - parsed_val.map_err(|e| Error::BadU32(span, e.into())) -} - -pub fn get_f32_literal(word: &str, span: Span) -> Result> { - let hex = word.starts_with("0x") || word.starts_with("-0x"); - - let parsed_val = if hex { - parse_hexf32(word, false).map_err(BadFloatError::ParseHexfError) - } else { - word.parse::().map_err(BadFloatError::ParseFloatError) - }; - - parsed_val.map_err(|e| Error::BadFloat(span, e)) -} - -pub(super) fn _parse_uint_literal<'a>( - lexer: &mut Lexer<'a>, - width: Bytes, -) -> Result> { - let token_span = lexer.next(); - - if width != 4 { - // Only 32-bit literals supported by the spec and naga for now! - return Err(Error::BadScalarWidth(token_span.1, width)); - } - - match token_span { - ( - Token::Number { - value, - ty: NumberType::Uint, - }, - span, - ) => get_u32_literal(value, span), - other => Err(Error::Unexpected( - other, - ExpectedToken::Number { - ty: Some(NumberType::Uint), - width: Some(width), - }, - )), - } -} - -/// Parse a non-negative signed integer literal. -/// This is for attributes like `size`, `location` and others. -pub(super) fn parse_non_negative_sint_literal<'a>( - lexer: &mut Lexer<'a>, - width: Bytes, -) -> Result> { - let token_span = lexer.next(); - - if width != 4 { - // Only 32-bit literals supported by the spec and naga for now! - return Err(Error::BadScalarWidth(token_span.1, width)); - } - - match token_span { - ( - Token::Number { - value, - ty: NumberType::Sint, - }, - span, - ) => { - let i32_val = get_i32_literal(value, span.clone())?; - u32::try_from(i32_val).map_err(|_| Error::NegativeInt(span)) - } - other => Err(Error::Unexpected( - other, - ExpectedToken::Number { - ty: Some(NumberType::Sint), - width: Some(width), - }, - )), - } -} - -/// Parse a non-negative integer literal that may be either signed or unsigned. -/// This is for the `workgroup_size` attribute and array lengths. -/// Note: these values should be no larger than [`i32::MAX`], but this is not checked here. -pub(super) fn parse_generic_non_negative_int_literal<'a>( - lexer: &mut Lexer<'a>, - width: Bytes, -) -> Result> { - let token_span = lexer.next(); - - if width != 4 { - // Only 32-bit literals supported by the spec and naga for now! - return Err(Error::BadScalarWidth(token_span.1, width)); - } - - match token_span { - ( - Token::Number { - value, - ty: NumberType::Sint, - }, - span, - ) => { - let i32_val = get_i32_literal(value, span.clone())?; - u32::try_from(i32_val).map_err(|_| Error::NegativeInt(span)) - } - ( - Token::Number { - value, - ty: NumberType::Uint, - }, - span, - ) => get_u32_literal(value, span), - other => Err(Error::Unexpected( - other, - ExpectedToken::Number { - ty: Some(NumberType::Sint), - width: Some(width), - }, - )), - } -} - -pub(super) fn _parse_float_literal<'a>( - lexer: &mut Lexer<'a>, - width: Bytes, -) -> Result> { - let token_span = lexer.next(); - - if width != 4 { - // Only 32-bit literals supported by the spec and naga for now! - return Err(Error::BadScalarWidth(token_span.1, width)); - } - - match token_span { - ( - Token::Number { - value, - ty: NumberType::Float, - }, - span, - ) => get_f32_literal(value, span), - other => Err(Error::Unexpected( - other, - ExpectedToken::Number { - ty: Some(NumberType::Float), - width: Some(width), - }, - )), - } -} diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 1f7e451f9..8c5604ecc 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -14,76 +14,6 @@ fn parse_comment() { .unwrap(); } -// Regexes for the literals are taken from the working draft at -// https://www.w3.org/TR/2021/WD-WGSL-20210806/#literals - -#[test] -fn parse_decimal_floats() { - // /^(-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?$/ - parse_str("let a : f32 = -1.;").unwrap(); - parse_str("let a : f32 = -.1;").unwrap(); - parse_str("let a : f32 = 42.1234;").unwrap(); - parse_str("let a : f32 = -1.E3;").unwrap(); - parse_str("let a : f32 = -.1e-5;").unwrap(); - parse_str("let a : f32 = 2.3e+55;").unwrap(); - - assert!(parse_str("let a : f32 = 42.1234f;").is_err()); - assert!(parse_str("let a : f32 = 42.1234f32;").is_err()); -} - -#[test] -fn parse_hex_floats() { - // /^-?0x([0-9a-fA-F]*\.?[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)(p|P)(\+|-)?[0-9]+$/ - parse_str("let a : f32 = -0xa.p1;").unwrap(); - parse_str("let a : f32 = -0x.fp9;").unwrap(); - parse_str("let a : f32 = 0x2a.4D2P4;").unwrap(); - parse_str("let a : f32 = -0x.1p-5;").unwrap(); - parse_str("let a : f32 = 0xC.8p+55;").unwrap(); - parse_str("let a : f32 = 0x1p1;").unwrap(); - - assert!(parse_str("let a : f32 = 0x1p1f;").is_err()); - assert!(parse_str("let a : f32 = 0x1p1f32;").is_err()); -} - -#[test] -fn parse_decimal_ints() { - // i32 /^-?0x[0-9a-fA-F]+|0|-?[1-9][0-9]*$/ - parse_str("let a : i32 = 0;").unwrap(); - parse_str("let a : i32 = 1092;").unwrap(); - parse_str("let a : i32 = -9923;").unwrap(); - - assert!(parse_str("let a : i32 = -0;").is_err()); - assert!(parse_str("let a : i32 = 01;").is_err()); - assert!(parse_str("let a : i32 = 1.0;").is_err()); - assert!(parse_str("let a : i32 = 1i;").is_err()); - assert!(parse_str("let a : i32 = 1i32;").is_err()); - - // u32 /^0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u$/ - parse_str("let a : u32 = 0u;").unwrap(); - parse_str("let a : u32 = 1092u;").unwrap(); - - assert!(parse_str("let a : u32 = -0u;").is_err()); - assert!(parse_str("let a : u32 = 01u;").is_err()); - assert!(parse_str("let a : u32 = 1.0u;").is_err()); - assert!(parse_str("let a : u32 = 1u32;").is_err()); -} - -#[test] -fn parse_hex_ints() { - // i32 /^-?0x[0-9a-fA-F]+|0|-?[1-9][0-9]*$/ - parse_str("let a : i32 = -0x0;").unwrap(); - parse_str("let a : i32 = 0x2a4D2;").unwrap(); - - assert!(parse_str("let a : i32 = 0x2a4D2i;").is_err()); - assert!(parse_str("let a : i32 = 0x2a4D2i32;").is_err()); - - // u32 /^0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u$/ - parse_str("let a : u32 = 0x0u;").unwrap(); - parse_str("let a : u32 = 0x2a4D2u;").unwrap(); - - assert!(parse_str("let a : u32 = 0x2a4D2u32;").is_err()); -} - #[test] fn parse_types() { parse_str("let a : i32 = 2;").unwrap(); From 0a6b0e5b7100a26bd467607359b32c9d3ad3df46 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 13 Jun 2022 15:47:32 +0200 Subject: [PATCH 1776/2212] update changelog for v0.9 --- CHANGELOG.md | 312 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 292 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aef49154e..d1959c357 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,16 +1,288 @@ # Change Log ## v0.9 (TBD) - - WGSL: - - semicolon after struct declaration are now optional - - commas are used to separate struct members instead of semicolons - - attributes are declared with `@attrib` instead of `[[attrib]]` - - `stride` attribute is removed - - block comments are supported - - renames: - - `findLsb` -> `firstTrailingBit` - - `findMsb` -> `firstLeadingBit` - - `smoothStep` -> `smoothstep` + +- Fix minimal-versions of dependencies ([#1840](https://github.com/gfx-rs/naga/pull/1840)) **@teoxoy** +- Update MSRV to 1.56 ([#1838](https://github.com/gfx-rs/naga/pull/1838)) **@teoxoy** + +API + +- Rename `TypeFlags` `INTERFACE`/`HOST_SHARED` to `IO_SHARED`/`HOST_SHAREABLE` ([#1872](https://github.com/gfx-rs/naga/pull/1872)) **@jimblandy** +- Expose more error information ([#1827](https://github.com/gfx-rs/naga/pull/1827), [#1937](https://github.com/gfx-rs/naga/pull/1937)) **@jakobhellermann** **@nical** **@jimblandy** +- Do not unconditionally make error output colorful ([#1707](https://github.com/gfx-rs/naga/pull/1707)) **@rhysd** +- Rename `StorageClass` to `AddressSpace` ([#1699](https://github.com/gfx-rs/naga/pull/1699)) **@kvark** +- Add a way to emit errors to a path ([#1640](https://github.com/gfx-rs/naga/pull/1640)) **@laptou** + +CLI + +- Add `bincode` representation ([#1729](https://github.com/gfx-rs/naga/pull/1729)) **@kvark** +- Include file path in WGSL parse error ([#1708](https://github.com/gfx-rs/naga/pull/1708)) **@rhysd** +- Add `--version` flag ([#1706](https://github.com/gfx-rs/naga/pull/1706)) **@rhysd** +- Support reading input from stdin via `--stdin-file-path` ([#1701](https://github.com/gfx-rs/naga/pull/1701)) **@rhysd** +- Use `panic = "abort"` ([#1597](https://github.com/gfx-rs/naga/pull/1597)) **@jrmuizel** + +DOCS + +- Standardize some docs ([#1660](https://github.com/gfx-rs/naga/pull/1660)) **@NoelTautges** +- Document `TypeInner::BindingArray` ([#1859](https://github.com/gfx-rs/naga/pull/1859)) **@jimblandy** +- Clarify accepted types for `Expression::AccessIndex` ([#1862](https://github.com/gfx-rs/naga/pull/1862)) **@NoelTautges** +- Document `proc::layouter` ([#1693](https://github.com/gfx-rs/naga/pull/1693)) **@jimblandy** +- Document Naga's promises around validation and panics ([#1828](https://github.com/gfx-rs/naga/pull/1828)) **@jimblandy** +- `FunctionInfo` doc fixes ([#1726](https://github.com/gfx-rs/naga/pull/1726)) **@jimblandy** + +VALIDATOR + +- Forbid returning pointers and atomics from functions ([#911](https://github.com/gfx-rs/naga/pull/911)) **@jimblandy** +- Let validation check for more unsupported builtins ([#1962](https://github.com/gfx-rs/naga/pull/1962)) **@jimblandy** +- Fix `Capabilities::SAMPLER_NON_UNIFORM_INDEXING` bitflag ([#1915](https://github.com/gfx-rs/naga/pull/1915)) **@cwfitzgerald** +- Properly check that user-defined IO uses IO-shareable types ([#912](https://github.com/gfx-rs/naga/pull/912)) **@jimblandy** +- Validate `ValuePointer` exactly like a `Pointer` to a `Scalar` ([#1875](https://github.com/gfx-rs/naga/pull/1875)) **@jimblandy** +- Reject empty structs ([#1826](https://github.com/gfx-rs/naga/pull/1826)) **@jimblandy** +- Validate uniform address space layout constraints ([#1812](https://github.com/gfx-rs/naga/pull/1812)) **@teoxoy** +- Improve `AddressSpace` related error messages ([#1710](https://github.com/gfx-rs/naga/pull/1710)) **@kvark** + +WGSL-IN + +Main breaking changes + +- Commas to separate struct members (comma after last member is optional) + - `struct S { a: f32; b: i32; }` -> `struct S { a: f32, b: i32 }` +- Attribute syntax + - `[[binding(0), group(0)]]` -> `@binding(0) @group(0)` +- Entry point stage attributes + - `@stage(vertex)` -> `@vertex` + - `@stage(fragment)` -> `@fragment` + - `@stage(compute)` -> `@compute` +- Function renames + - `smoothStep` -> `smoothstep` + - `findLsb` -> `firstTrailingBit` + - `findMsb` -> `firstLeadingBit` + +Specification Changes (relavant changes have also been applied to the WGSL backend) + +- Update number literal format ([#1863](https://github.com/gfx-rs/naga/pull/1863)) **@teoxoy** +- Allow non-ascii characters in identifiers ([#1849](https://github.com/gfx-rs/naga/pull/1849)) **@teoxoy** +- Update reserved keywords ([#1847](https://github.com/gfx-rs/naga/pull/1847), [#1870](https://github.com/gfx-rs/naga/pull/1870), [#1905](https://github.com/gfx-rs/naga/pull/1905)) **@teoxoy** **@Gordon-F** +- Update entry point stage attributes ([#1833](https://github.com/gfx-rs/naga/pull/1833)) **@Gordon-F** +- Make colon in case optional ([#1801](https://github.com/gfx-rs/naga/pull/1801)) **@Gordon-F** +- Rename `smoothStep` to `smoothstep` ([#1800](https://github.com/gfx-rs/naga/pull/1800)) **@Gordon-F** +- Make semicolon after struct declaration optional ([#1791](https://github.com/gfx-rs/naga/pull/1791)) **@stshine** +- Use commas to separate struct members instead of semicolons ([#1773](https://github.com/gfx-rs/naga/pull/1773)) **@Gordon-F** +- Rename `findLsb`/`findMsb` to `firstTrailingBit`/`firstLeadingBit` ([#1735](https://github.com/gfx-rs/naga/pull/1735)) **@kvark** +- Make parenthesis optional for `if` and `switch` statements ([#1725](https://github.com/gfx-rs/naga/pull/1725)) **@Gordon-F** +- Declare attribtues with `@attrib` instead of `[[attrib]]` ([#1676](https://github.com/gfx-rs/naga/pull/1676)) **@kvark** +- Allow non-structure buffer types ([#1682](https://github.com/gfx-rs/naga/pull/1682)) **@kvark** +- Remove `stride` attribute ([#1681](https://github.com/gfx-rs/naga/pull/1681)) **@kvark** + +Improvements + +- Implement `firstTrailingBit`/`firstLeadingBit` u32 overloads ([#1865](https://github.com/gfx-rs/naga/pull/1865)) **@teoxoy** +- Add error for non-floating-point matrix ([#1917](https://github.com/gfx-rs/naga/pull/1917)) **@grovesNL** +- Implement partial vector & matrix identity constructors ([#1916](https://github.com/gfx-rs/naga/pull/1916)) **@teoxoy** +- Implement phony assignment ([#1866](https://github.com/gfx-rs/naga/pull/1866), [#1869](https://github.com/gfx-rs/naga/pull/1869)) **@teoxoy** +- Fix being able to match `~=` as LogicalOperation ([#1849](https://github.com/gfx-rs/naga/pull/1849)) **@teoxoy** +- Implement Binding Arrays ([#1845](https://github.com/gfx-rs/naga/pull/1845)) **@cwfitzgerald** +- Implement unary vector operators ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy** +- Implement zero value constructors and constructors that infer their type from their parameters ([#1790](https://github.com/gfx-rs/naga/pull/1790)) **@teoxoy** +- Implement invariant attribute ([#1789](https://github.com/gfx-rs/naga/pull/1789), [#1822](https://github.com/gfx-rs/naga/pull/1822)) **@teoxoy** **@jimblandy** +- Implement increment and decrement statements ([#1788](https://github.com/gfx-rs/naga/pull/1788), [#1912](https://github.com/gfx-rs/naga/pull/1912)) **@teoxoy** +- Implement `while` loop ([#1787](https://github.com/gfx-rs/naga/pull/1787)) **@teoxoy** +- Fix array size on globals ([#1717](https://github.com/gfx-rs/naga/pull/1717)) **@jimblandy** +- Implement integer vector overloads for `dot` function ([#1689](https://github.com/gfx-rs/naga/pull/1689)) **@francesco-cattoglio** +- Implement block comments ([#1675](https://github.com/gfx-rs/naga/pull/1675)) **@kocsis1david** +- Implement assignment binary operators ([#1662](https://github.com/gfx-rs/naga/pull/1662)) **@kvark** +- Implement `radians`/`degrees` builtin functions ([#1627](https://github.com/gfx-rs/naga/pull/1627)) **@encounter** +- Implement `findLsb`/`findMsb` builtin functions ([#1473](https://github.com/gfx-rs/naga/pull/1473)) **@fintelia** +- Implement `textureGather`/`textureGatherCompare` builtin functions ([#1596](https://github.com/gfx-rs/naga/pull/1596)) **@kvark** + +SPV-IN + +- Implement `OpBitReverse` and `OpBitCount` ([#1954](https://github.com/gfx-rs/naga/pull/1954)) **@JCapucho** +- Add `MultiView` to `SUPPORTED_CAPABILITIES` ([#1934](https://github.com/gfx-rs/naga/pull/1934)) **@expenses** +- Translate `OpSMod` and `OpFMod` correctly ([#1867](https://github.com/gfx-rs/naga/pull/1867)) **@teoxoy** +- Error on unsupported `MatrixStride` ([#1805](https://github.com/gfx-rs/naga/pull/1805)) **@teoxoy** +- Align array stride for undecorated arrays ([#1724](https://github.com/gfx-rs/naga/pull/1724)) **@JCapucho** + +GLSL-IN + +- Fix matrix multiplication check ([#1953](https://github.com/gfx-rs/naga/pull/1953)) **@JCapucho** +- Fix panic (stop emitter in conditional) ([#1952](https://github.com/gfx-rs/naga/pull/1952)) **@JCapucho** +- Translate `mod` fn correctly ([#1867](https://github.com/gfx-rs/naga/pull/1867)) **@teoxoy** +- Make the ternary operator behave as an if ([#1877](https://github.com/gfx-rs/naga/pull/1877)) **@JCapucho** +- Add support for `clamp` function ([#1502](https://github.com/gfx-rs/naga/pull/1502)) **@sjinno** +- Better errors for bad constant expression ([#1501](https://github.com/gfx-rs/naga/pull/1501)) **@sjinno** +- Error on a `matCx2` used with the `std140` layout ([#1806](https://github.com/gfx-rs/naga/pull/1806)) **@teoxoy** +- Allow nested accesses in lhs positions ([#1794](https://github.com/gfx-rs/naga/pull/1794)) **@JCapucho** +- Use forced conversions for vector/matrix constructors ([#1796](https://github.com/gfx-rs/naga/pull/1796)) **@JCapucho** +- Add support for `barrier` function ([#1793](https://github.com/gfx-rs/naga/pull/1793)) **@fintelia** +- Fix panic (resume expression emit after `imageStore`) ([#1795](https://github.com/gfx-rs/naga/pull/1795)) **@JCapucho** +- Allow multiple array specifiers ([#1780](https://github.com/gfx-rs/naga/pull/1780)) **@JCapucho** +- Fix memory qualifiers being inverted ([#1779](https://github.com/gfx-rs/naga/pull/1779)) **@JCapucho** +- Support arrays as input/output types ([#1759](https://github.com/gfx-rs/naga/pull/1759)) **@JCapucho** +- Fix freestanding constructor parsing ([#1758](https://github.com/gfx-rs/naga/pull/1758)) **@JCapucho** +- Fix matrix - scalar operations ([#1757](https://github.com/gfx-rs/naga/pull/1757)) **@JCapucho** +- Fix matrix - matrix division ([#1757](https://github.com/gfx-rs/naga/pull/1757)) **@JCapucho** +- Fix matrix comparisons ([#1757](https://github.com/gfx-rs/naga/pull/1757)) **@JCapucho** +- Add support for `texelFetchOffset` ([#1746](https://github.com/gfx-rs/naga/pull/1746)) **@JCapucho** +- Inject `sampler2DMSArray` builtins on use ([#1737](https://github.com/gfx-rs/naga/pull/1737)) **@JCapucho** +- Inject `samplerCubeArray` builtins on use ([#1736](https://github.com/gfx-rs/naga/pull/1736)) **@JCapucho** +- Add support for image builtin functions ([#1723](https://github.com/gfx-rs/naga/pull/1723)) **@JCapucho** +- Add support for image declarations ([#1723](https://github.com/gfx-rs/naga/pull/1723)) **@JCapucho** +- Texture builtins fixes ([#1719](https://github.com/gfx-rs/naga/pull/1719)) **@JCapucho** +- Type qualifiers rework ([#1713](https://github.com/gfx-rs/naga/pull/1713)) **@JCapucho** +- `texelFetch` accept multisampled textures ([#1715](https://github.com/gfx-rs/naga/pull/1715)) **@JCapucho** +- Fix panic when culling nested block ([#1714](https://github.com/gfx-rs/naga/pull/1714)) **@JCapucho** +- Fix composite constructors ([#1631](https://github.com/gfx-rs/naga/pull/1631)) **@JCapucho** +- Fix using swizzle as out arguments ([#1632](https://github.com/gfx-rs/naga/pull/1632)) **@JCapucho** + +SPV-OUT + +- Implement `reverseBits` and `countOneBits` ([#1897](https://github.com/gfx-rs/naga/pull/1897)) **@hasali19** +- Use `OpCopyObject` for matrix identity casts ([#1916](https://github.com/gfx-rs/naga/pull/1916)) **@teoxoy** +- Use `OpCopyObject` for bool - bool conversion due to `OpBitcast` not being feasible for booleans ([#1916](https://github.com/gfx-rs/naga/pull/1916)) **@teoxoy** +- Zero init variables in function and private address spaces ([#1871](https://github.com/gfx-rs/naga/pull/1871)) **@teoxoy** +- Use `SRem` instead of `SMod` ([#1867](https://github.com/gfx-rs/naga/pull/1867)) **@teoxoy** +- Add support for integer vector - scalar multiplication ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy** +- Add support for matrix addition and subtraction ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy** +- Emit required decorations on wrapper struct types ([#1815](https://github.com/gfx-rs/naga/pull/1815)) **@jimblandy** +- Decorate array and struct type layouts unconditionally ([#1815](https://github.com/gfx-rs/naga/pull/1815)) **@jimblandy** +- Fix wrong `MatrixStride` for `matCx2` and `mat2xR` ([#1781](https://github.com/gfx-rs/naga/pull/1781)) **@teoxoy** +- Use `OpImageQuerySize` for MS images ([#1742](https://github.com/gfx-rs/naga/pull/1742)) **@JCapucho** + +MSL-OUT + +- Fix pointers to private or workgroup address spaces possibly being read only ([#1901](https://github.com/gfx-rs/naga/pull/1901)) **@teoxoy** +- Zero init variables in function address space ([#1871](https://github.com/gfx-rs/naga/pull/1871)) **@teoxoy** +- Make binding arrays play nice with bounds checks ([#1855](https://github.com/gfx-rs/naga/pull/1855)) **@cwfitzgerald** +- Permit `invariant` qualifier on vertex shader outputs ([#1821](https://github.com/gfx-rs/naga/pull/1821)) **@jimblandy** +- Fix packed `vec3` stores ([#1816](https://github.com/gfx-rs/naga/pull/1816)) **@teoxoy** +- Actually test push constants to be used ([#1767](https://github.com/gfx-rs/naga/pull/1767)) **@kvark** +- Properly rename entry point arguments for struct members ([#1766](https://github.com/gfx-rs/naga/pull/1766)) **@jimblandy** +- Qualify read-only storage with const ([#1763](https://github.com/gfx-rs/naga/pull/1763)) **@kvark** +- Fix not unary operator for integer scalars ([#1760](https://github.com/gfx-rs/naga/pull/1760)) **@vincentisambart** +- Add bounds checks for `ImageLoad` and `ImageStore` ([#1730](https://github.com/gfx-rs/naga/pull/1730)) **@jimblandy** +- Fix resource bindings for non-structures ([#1718](https://github.com/gfx-rs/naga/pull/1718)) **@kvark** +- Always check whether _buffer_sizes arg is needed ([#1717](https://github.com/gfx-rs/naga/pull/1717)) **@jimblandy** +- WGSL storage address space should always correspond to MSL device address space ([#1711](https://github.com/gfx-rs/naga/pull/1711)) **@wtholliday** +- Mitigation for MSL atomic bounds check ([#1703](https://github.com/gfx-rs/naga/pull/1703)) **@glalonde** + +HLSL-OUT + +- Fix fallthrough in switch statements ([#1920](https://github.com/gfx-rs/naga/pull/1920)) **@teoxoy** +- Fix missing break statements ([#1919](https://github.com/gfx-rs/naga/pull/1919)) **@teoxoy** +- Fix `countOneBits` and `reverseBits` for signed integers ([#1928](https://github.com/gfx-rs/naga/pull/1928)) **@hasali19** +- Fix array constructor return type ([#1914](https://github.com/gfx-rs/naga/pull/1914)) **@teoxoy** +- Fix hlsl output for writes to scalar/vector storage buffer ([#1903](https://github.com/gfx-rs/naga/pull/1903)) **@hasali19** +- Use `fmod` instead of `%` ([#1867](https://github.com/gfx-rs/naga/pull/1867)) **@teoxoy** +- Use wrapped constructors when loading from storage address space ([#1893](https://github.com/gfx-rs/naga/pull/1893)) **@teoxoy** +- Zero init struct constructor ([#1890](https://github.com/gfx-rs/naga/pull/1890)) **@teoxoy** +- Flesh out matrix handling documentation ([#1850](https://github.com/gfx-rs/naga/pull/1850)) **@jimblandy** +- Emit `row_major` qualifier on matrix uniform globals ([#1846](https://github.com/gfx-rs/naga/pull/1846)) **@jimblandy** +- Fix bool splat ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy** +- Add more padding when necessary ([#1814](https://github.com/gfx-rs/naga/pull/1814)) **@teoxoy** +- Support multidimensional arrays ([#1814](https://github.com/gfx-rs/naga/pull/1814)) **@teoxoy** +- Don't output interpolation modifier if it's the default ([#1809](https://github.com/gfx-rs/naga/pull/1809)) **@NoelTautges** +- Fix `matCx2` translation for uniform buffers ([#1802](https://github.com/gfx-rs/naga/pull/1802)) **@teoxoy** +- Fix modifiers not being written in the vertex output and fragment input structs ([#1789](https://github.com/gfx-rs/naga/pull/1789)) **@teoxoy** +- Fix matrix not being declared as transposed ([#1784](https://github.com/gfx-rs/naga/pull/1784)) **@teoxoy** +- Insert padding between struct members ([#1786](https://github.com/gfx-rs/naga/pull/1786)) **@teoxoy** +- Fix not unary operator for integer scalars ([#1760](https://github.com/gfx-rs/naga/pull/1760)) **@vincentisambart** + +GLSL-OUT + +- Fix type error for `countOneBits` implementation ([#1897](https://github.com/gfx-rs/naga/pull/1897)) **@hasali19** +- Fix storage format for `Rgba8Unorm` ([#1955](https://github.com/gfx-rs/naga/pull/1955)) **@JCapucho** +- Implement bounds checks for `ImageLoad` ([#1889](https://github.com/gfx-rs/naga/pull/1889)) **@JCapucho** +- Fix feature search in expressions ([#1887](https://github.com/gfx-rs/naga/pull/1887)) **@JCapucho** +- Emit globals of any type ([#1823](https://github.com/gfx-rs/naga/pull/1823)) **@jimblandy** +- Add support for boolean vector `~`, `|` and `&` ops ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy** +- Fix array function arguments ([#1814](https://github.com/gfx-rs/naga/pull/1814)) **@teoxoy** +- Write constant sized array type for uniform ([#1768](https://github.com/gfx-rs/naga/pull/1768)) **@hatoo** +- Texture function fixes ([#1742](https://github.com/gfx-rs/naga/pull/1742)) **@JCapucho** +- Push constants use anonymous uniforms ([#1683](https://github.com/gfx-rs/naga/pull/1683)) **@JCapucho** +- Add support for push constant emulation ([#1672](https://github.com/gfx-rs/naga/pull/1672)) **@JCapucho** +- Skip unsized types if unused ([#1649](https://github.com/gfx-rs/naga/pull/1649)) **@kvark** +- Write struct and array initializers ([#1644](https://github.com/gfx-rs/naga/pull/1644)) **@JCapucho** + + +## v0.8.5 (2022-01-25) + +MSL-OUT + +- Make VS-output positions invariant on even more systems ([#1697](https://github.com/gfx-rs/naga/pull/1697)) **@cwfitzgerald** +- Improve support for point primitives ([#1696](https://github.com/gfx-rs/naga/pull/1696)) **@kvark** + + +## v0.8.4 (2022-01-24) + +MSL-OUT + +- Make VS-output positions invariant if possible ([#1687](https://github.com/gfx-rs/naga/pull/1687)) **@kvark** + +GLSL-OUT + +- Fix `floatBitsToUint` spelling ([#1688](https://github.com/gfx-rs/naga/pull/1688)) **@cwfitzgerald** +- Call proper memory barrier functions ([#1680](https://github.com/gfx-rs/naga/pull/1680)) **@francesco-cattoglio** + + +## v0.8.3 (2022-01-20) + +- Don't pin `indexmap` version ([#1666](https://github.com/gfx-rs/naga/pull/1666)) **@a1phyr** + +MSL-OUT + +- Fix support for point primitives ([#1674](https://github.com/gfx-rs/naga/pull/1674)) **@kvark** + +GLSL-OUT + +- Fix sampler association ([#1671](https://github.com/gfx-rs/naga/pull/1671)) **@JCapucho** + + +## v0.8.2 (2022-01-11) + +VALIDATOR + +- Check structure resource types ([#1639](https://github.com/gfx-rs/naga/pull/1639)) **@kvark** + +WGSL-IN + +- Improve type mismatch errors ([#1658](https://github.com/gfx-rs/naga/pull/1658)) **@Gordon-F** + +SPV-IN + +- Implement more sign agnostic operations ([#1651](https://github.com/gfx-rs/naga/pull/1651), [#1650](https://github.com/gfx-rs/naga/pull/1650)) **@JCapucho** + +SPV-OUT + +- Fix modulo operator (use `OpFRem` instead of `OpFMod`) ([#1653](https://github.com/gfx-rs/naga/pull/1653)) **@JCapucho** + +MSL-OUT + +- Fix `texture1d` accesses ([#1647](https://github.com/gfx-rs/naga/pull/1647)) **@jimblandy** +- Fix data packing functions ([#1637](https://github.com/gfx-rs/naga/pull/1637)) **@phoekz** + + +## v0.8.1 (2021-12-29) + +API + +- Make `WithSpan` clonable ([#1620](https://github.com/gfx-rs/naga/pull/1620)) **@jakobhellermann** + +MSL-OUT + +- Fix packed vec access ([#1634](https://github.com/gfx-rs/naga/pull/1634)) **@kvark** +- Fix packed float support ([#1630](https://github.com/gfx-rs/naga/pull/1630)) **@kvark** + +HLSL-OUT + +- Support arrays of matrices ([#1629](https://github.com/gfx-rs/naga/pull/1629)) **@kvark** +- Use `mad` instead of `fma` function ([#1580](https://github.com/gfx-rs/naga/pull/1580)) **@parasyte** + +GLSL-OUT + +- Fix conflicting names for globals ([#1616](https://github.com/gfx-rs/naga/pull/1616)) **@Gordon-F** +- Fix `fma` function ([#1580](https://github.com/gfx-rs/naga/pull/1580)) **@parasyte** + ## v0.8 (2021-12-18) - development release for wgpu-0.12 @@ -26,7 +298,7 @@ - MSL-out: - full out-of-bounds checking -### v0.7.3 (2021-12-14) +## v0.7.3 (2021-12-14) - API: - `view_index` builtin - GLSL-out: @@ -34,7 +306,7 @@ - SPV-out: - fix incorrect pack/unpack -### v0.7.2 (2021-12-01) +## v0.7.2 (2021-12-01) - validator: - check stores for proper pointer class - HLSL-out: @@ -50,7 +322,7 @@ - GLSL-in: - don't panic on invalid integer operations -### v0.7.1 (2021-10-12) +## v0.7.1 (2021-10-12) - implement casts from and to booleans in the backends ## v0.7 (2021-10-07) @@ -83,7 +355,7 @@ - option to emit point size - option to clamp output depth -### v0.6.3 (2021-09-08) +## v0.6.3 (2021-09-08) - Reduced heap allocations when generating WGSL, HLSL, and GLSL - WGSL-in: - support module-scope `let` type inference @@ -96,7 +368,7 @@ - SPV-out: - allow working around Adreno issue with `OpName` -### v0.6.2 (2021-09-01) +## v0.6.2 (2021-09-01) - SPV-out fixes: - requested capabilities for 1D and cube images, storage formats - handling `break` and `continue` in a `switch` statement @@ -110,7 +382,7 @@ - GLSL-in fixes: - avoid infinite loop on invalid statements -### v0.6.1 (2021-08-24) +## v0.6.1 (2021-08-24) - HLSL-out fixes: - array arguments - pointers to array arguments @@ -165,7 +437,7 @@ - multisampling on GLES - WGSL is vastly improved and now usable -### v0.4.2 (2021-05-28) +## v0.4.2 (2021-05-28) - SPIR-V frontend: - fix image stores - fix matrix stride check @@ -175,7 +447,7 @@ - support sample interpolation - write out swizzled vector accesses -### v0.4.1 (2021-05-14) +## v0.4.1 (2021-05-14) - numerous additions and improvements to SPIR-V frontend: - int8, in16, int64 - null constant initializers for structs and matrices @@ -218,7 +490,7 @@ - `convert` example is transformed into the default binary target named `naga` - lots of frontend and backend fixes -### v0.3.2 (2021-02-15) +## v0.3.2 (2021-02-15) - fix logical expression types - fix _FragDepth_ semantics - spv-in: @@ -227,7 +499,7 @@ - add lots of missing math functions - implement discard -### v0.3.1 (2021-01-31) +## v0.3.1 (2021-01-31) - wgsl: - support constant array sizes - spv-out: From 3d3e5ae00de40de941aa8a9f801228532cf4ae91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 2 Jun 2022 18:02:18 +0100 Subject: [PATCH 1777/2212] glsl-in: Fix parameter not changing to depth The conversion from sampled images to depth changed the `argument` type but didn't change the `parameter` type (`argument` without pointer indirection) causing 2+ deep propagation of depth images with function arguments to fail. --- src/front/glsl/builtins.rs | 18 +++++++++++++++++- src/front/glsl/functions.rs | 7 +++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 287f66d6f..2744fb79a 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -2237,20 +2237,26 @@ pub fn sampled_to_depth( meta: Span, errors: &mut Vec, ) { + // Get the a mutable type handle of the underlying image storage let ty = match ctx[image] { Expression::GlobalVariable(handle) => &mut module.global_variables.get_mut(handle).ty, Expression::FunctionArgument(i) => { + // Mark the function argument as carrying a depth texture ctx.parameters_info[i as usize].depth = true; + // NOTE: We need to later also change the parameter type &mut ctx.arguments[i as usize].ty } _ => { + // Only globals and function arguments are allowed to carry an image return errors.push(Error { kind: ErrorKind::SemanticError("Not a valid texture expression".into()), meta, - }) + }); } }; + match module.types[*ty].inner { + // Update the image class to depth in case it already isn't TypeInner::Image { class, dim, @@ -2270,6 +2276,7 @@ pub fn sampled_to_depth( ) } ImageClass::Depth { .. } => {} + // Other image classes aren't allowed to be transformed to depth _ => errors.push(Error { kind: ErrorKind::SemanticError("Not a texture".into()), meta, @@ -2280,6 +2287,15 @@ pub fn sampled_to_depth( meta, }), }; + + // Copy the handle to allow borrowing the `ctx` again + let ty = *ty; + + // If the image was passed trough a function argument we also need to change + // the corresponding parameter + if let Expression::FunctionArgument(i) = ctx[image] { + ctx.parameters[i as usize] = ty; + } } bitflags::bitflags! { diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 325f4d8ab..2c0445bdf 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -671,6 +671,13 @@ impl Parser { let overload_param_ty = &self.module.types[*overload_parameter].inner; let call_arg_ty = self.resolve_type(ctx, call_argument.0, call_argument.1)?; + log::trace!( + "Testing parameter {}\n\tOverload = {:?}\n\tCall = {:?}", + i, + overload_param_ty, + call_arg_ty + ); + // Storage images cannot be directly compared since while the access is part of the // type in naga's IR, in glsl they are a qualifier and don't enter in the match as // long as the access needed is satisfied. From 81e2b006e1e968029cb85de5a1fc127f16625a4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 7 Jun 2022 15:31:18 +0100 Subject: [PATCH 1778/2212] glsl-in: Add test for nested depth texture calls Co-authored-by: Jasper St. Pierre --- tests/in/glsl/sampler-functions.frag | 16 +++++++++ tests/out/wgsl/sampler-functions-frag.wgsl | 41 ++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 tests/in/glsl/sampler-functions.frag create mode 100644 tests/out/wgsl/sampler-functions-frag.wgsl diff --git a/tests/in/glsl/sampler-functions.frag b/tests/in/glsl/sampler-functions.frag new file mode 100644 index 000000000..0d868780b --- /dev/null +++ b/tests/in/glsl/sampler-functions.frag @@ -0,0 +1,16 @@ +#version 440 +precision mediump float; + +float CalcShadowPCF1(texture2D T_P_t_TextureDepth, samplerShadow S_P_t_TextureDepth, in vec3 t_ProjCoord) { + float t_Res = 0.0f; + t_Res += texture(sampler2DShadow(T_P_t_TextureDepth, S_P_t_TextureDepth), t_ProjCoord.xyz) * (1.0 / 5.0); + return t_Res; +} + +float CalcShadowPCF(texture2D T_P_t_TextureDepth, samplerShadow S_P_t_TextureDepth, in vec3 t_ProjCoord, in float t_Bias) { + t_ProjCoord.z += t_Bias; + return CalcShadowPCF1(T_P_t_TextureDepth, S_P_t_TextureDepth, t_ProjCoord.xyz); +} + +void main() { +} diff --git a/tests/out/wgsl/sampler-functions-frag.wgsl b/tests/out/wgsl/sampler-functions-frag.wgsl new file mode 100644 index 000000000..e9e4830ee --- /dev/null +++ b/tests/out/wgsl/sampler-functions-frag.wgsl @@ -0,0 +1,41 @@ +fn CalcShadowPCF1_(T_P_t_TextureDepth: texture_depth_2d, S_P_t_TextureDepth: sampler_comparison, t_ProjCoord: vec3) -> f32 { + var t_ProjCoord_1: vec3; + var t_Res: f32 = 0.0; + + t_ProjCoord_1 = t_ProjCoord; + let _e6 = t_Res; + let _e7 = t_ProjCoord_1; + _ = _e7.xyz; + let _e9 = t_ProjCoord_1; + let _e10 = _e9.xyz; + let _e13 = textureSampleCompare(T_P_t_TextureDepth, S_P_t_TextureDepth, _e10.xy, _e10.z); + t_Res = (_e6 + (_e13 * (1.0 / 5.0))); + let _e19 = t_Res; + return _e19; +} + +fn CalcShadowPCF(T_P_t_TextureDepth_1: texture_depth_2d, S_P_t_TextureDepth_1: sampler_comparison, t_ProjCoord_2: vec3, t_Bias: f32) -> f32 { + var t_ProjCoord_3: vec3; + var t_Bias_1: f32; + + t_ProjCoord_3 = t_ProjCoord_2; + t_Bias_1 = t_Bias; + let _e7 = t_ProjCoord_3; + let _e9 = t_Bias_1; + t_ProjCoord_3.z = (_e7.z + _e9); + let _e11 = t_ProjCoord_3; + _ = _e11.xyz; + let _e13 = t_ProjCoord_3; + let _e15 = CalcShadowPCF1_(T_P_t_TextureDepth_1, S_P_t_TextureDepth_1, _e13.xyz); + return _e15; +} + +fn main_1() { + return; +} + +@fragment +fn main() { + main_1(); + return; +} From b5a046982f97e27a93885dfcfa624c29fbcaf3dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 7 Jun 2022 15:58:37 +0100 Subject: [PATCH 1779/2212] glsl-out: don't rely on cached expressions Expressions marked for caching might not be cached, this can happen for example when these expressions are pre emitted (for example Contants). --- src/back/glsl/mod.rs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9e534df53..cba3b3ca0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1526,20 +1526,30 @@ impl<'a, W: Write> Writer<'a, W> { arg: Handle, arg1: Handle, size: usize, + ctx: &back::FunctionCtx<'_>, ) -> BackendResult { + // Write parantheses around the dot product expression to prevent operators + // with different precedences from applying earlier. write!(self.out, "(")?; - let arg0_name = &self.named_expressions[&arg]; - let arg1_name = &self.named_expressions[&arg1]; - - // This will print an extra '+' at the beginning but that is fine in glsl + // Cycle trough all the components of the vector for index in 0..size { let component = back::COMPONENTS[index]; - write!( - self.out, - " + {}.{} * {}.{}", - arg0_name, component, arg1_name, component - )?; + // Write the addition to the previous product + // This will print an extra '+' at the beginning but that is fine in glsl + write!(self.out, " + ")?; + // Write the first vector expression, this expression is marked to be + // cached so unless it can't be cached (for example, it's a Constant) + // it shouldn't produce large expressions. + self.write_expr(arg, ctx)?; + // Access the current component on the first vector + write!(self.out, ".{} * ", component)?; + // Write the second vector expression, this expression is marked to be + // cached so unless it can't be cached (for example, it's a Constant) + // it shouldn't produce large expressions. + self.write_expr(arg1, ctx)?; + // Access the current component on the second vector + write!(self.out, ".{}", component)?; } write!(self.out, ")")?; @@ -2726,7 +2736,7 @@ impl<'a, W: Write> Writer<'a, W> { .. } => "dot", crate::TypeInner::Vector { size, .. } => { - return self.write_dot_product(arg, arg1.unwrap(), size as usize) + return self.write_dot_product(arg, arg1.unwrap(), size as usize, ctx) } _ => unreachable!( "Correct TypeInner for dot product should be already validated" From 46bc882d19f012c6a3491f647fee5b886079e48c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 12 Jun 2022 16:29:11 +0100 Subject: [PATCH 1780/2212] msl: don't rely on cached expressions Expressions marked for caching might not be cached, this can happen for example when these expressions are pre emitted (for example Contants). --- src/back/msl/writer.rs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 1d63a0753..1f85c4d0a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1223,20 +1223,30 @@ impl Writer { arg: Handle, arg1: Handle, size: usize, + context: &ExpressionContext, ) -> BackendResult { + // Write parantheses around the dot product expression to prevent operators + // with different precedences from applying earlier. write!(self.out, "(")?; - let arg0_name = &self.named_expressions[&arg]; - let arg1_name = &self.named_expressions[&arg1]; - - // This will print an extra '+' at the beginning but that is fine in msl + // Cycle trough all the components of the vector for index in 0..size { let component = back::COMPONENTS[index]; - write!( - self.out, - " + {}.{} * {}.{}", - arg0_name, component, arg1_name, component - )?; + // Write the addition to the previous product + // This will print an extra '+' at the beginning but that is fine in msl + write!(self.out, " + ")?; + // Write the first vector expression, this expression is marked to be + // cached so unless it can't be cached (for example, it's a Constant) + // it shouldn't produce large expressions. + self.put_expression(arg, context, true)?; + // Access the current component on the first vector + write!(self.out, ".{} * ", component)?; + // Write the second vector expression, this expression is marked to be + // cached so unless it can't be cached (for example, it's a Constant) + // it shouldn't produce large expressions. + self.put_expression(arg1, context, true)?; + // Access the current component on the second vector + write!(self.out, ".{}", component)?; } write!(self.out, ")")?; @@ -1654,7 +1664,7 @@ impl Writer { .. } => "dot", crate::TypeInner::Vector { size, .. } => { - return self.put_dot_product(arg, arg1.unwrap(), size as usize) + return self.put_dot_product(arg, arg1.unwrap(), size as usize, context) } _ => unreachable!( "Correct TypeInner for dot product should be already validated" From c7e67690013ce08132f5e8203379c72534b84f39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 12 Jun 2022 16:29:22 +0100 Subject: [PATCH 1781/2212] Add tests --- tests/in/math-functions.wgsl | 1 + .../out/glsl/math-functions.main.Vertex.glsl | 1 + tests/out/hlsl/math-functions.hlsl | 1 + tests/out/msl/math-functions.msl | 2 + tests/out/spv/math-functions.spvasm | 39 ++++++++++++------- tests/out/wgsl/math-functions.wgsl | 1 + 6 files changed, 32 insertions(+), 13 deletions(-) diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index a298a5e2b..38e9acee9 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -6,4 +6,5 @@ fn main() { let b = radians(f); let c = degrees(v); let d = radians(v); + let const_dot = dot(vec2(), vec2()); } diff --git a/tests/out/glsl/math-functions.main.Vertex.glsl b/tests/out/glsl/math-functions.main.Vertex.glsl index b69069b38..02a94ea69 100644 --- a/tests/out/glsl/math-functions.main.Vertex.glsl +++ b/tests/out/glsl/math-functions.main.Vertex.glsl @@ -10,5 +10,6 @@ void main() { float b = radians(1.0); vec4 c = degrees(v); vec4 d = radians(v); + int const_dot = ( + ivec2(0, 0).x * ivec2(0, 0).x + ivec2(0, 0).y * ivec2(0, 0).y); } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index 584c4c4ff..b17a32cf4 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -6,4 +6,5 @@ void main() float b = radians(1.0); float4 c = degrees(v); float4 d = radians(v); + int const_dot = dot(int2(0, 0), int2(0, 0)); } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index fe1fd5573..e08894037 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -4,6 +4,7 @@ using metal::uint; +constant metal::int2 const_type = {0, 0}; vertex void main_( ) { @@ -12,4 +13,5 @@ vertex void main_( float b = ((1.0) * 0.017453292519943295474); metal::float4 c = ((v) * 57.295779513082322865); metal::float4 d = ((v) * 0.017453292519943295474); + int const_dot = ( + const_type.x * const_type.x + const_type.y * const_type.y); } diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 738ac6a72..03b4a0423 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,25 +1,38 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 16 +; Bound: 29 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %7 "main" +OpEntryPoint Vertex %11 "main" %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 %5 = OpConstant %4 0.0 -%8 = OpTypeFunction %2 -%10 = OpTypeVector %4 4 -%7 = OpFunction %2 None %8 -%6 = OpLabel -OpBranch %9 -%9 = OpLabel -%11 = OpCompositeConstruct %10 %5 %5 %5 %5 -%12 = OpExtInst %4 %1 Degrees %3 -%13 = OpExtInst %4 %1 Radians %3 -%14 = OpExtInst %10 %1 Degrees %11 -%15 = OpExtInst %10 %1 Radians %11 +%7 = OpTypeInt 32 1 +%6 = OpConstant %7 0 +%8 = OpTypeVector %7 2 +%9 = OpConstantComposite %8 %6 %6 +%12 = OpTypeFunction %2 +%14 = OpTypeVector %4 4 +%21 = OpConstantNull %7 +%11 = OpFunction %2 None %12 +%10 = OpLabel +OpBranch %13 +%13 = OpLabel +%15 = OpCompositeConstruct %14 %5 %5 %5 %5 +%16 = OpExtInst %4 %1 Degrees %3 +%17 = OpExtInst %4 %1 Radians %3 +%18 = OpExtInst %14 %1 Degrees %15 +%19 = OpExtInst %14 %1 Radians %15 +%22 = OpCompositeExtract %7 %9 0 +%23 = OpCompositeExtract %7 %9 0 +%24 = OpIMul %7 %22 %23 +%25 = OpIAdd %7 %21 %24 +%26 = OpCompositeExtract %7 %9 1 +%27 = OpCompositeExtract %7 %9 1 +%28 = OpIMul %7 %26 %27 +%20 = OpIAdd %7 %25 %28 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index c87270742..2be33d564 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -5,4 +5,5 @@ fn main() { let b = radians(1.0); let c = degrees(v); let d = radians(v); + let const_dot = dot(vec2(0, 0), vec2(0, 0)); } From 52bb25179bcd48097f4371a487955cf34d26bd26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 7 Jun 2022 16:17:29 +0100 Subject: [PATCH 1782/2212] glsl-in: Splat inputs for smoothstep if needed Glsl defines two overloads for smoothstep that accept `min` and `max` as scalars and the value as a vector, naga's IR is stricter and only allows operators with the same dimensions, so this inputs must be splatted. --- src/front/glsl/builtins.rs | 24 +++++++++++++++++++++++- tests/in/glsl/math-functions.vert | 3 +++ tests/out/wgsl/math-functions-vert.wgsl | 10 ++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 2744fb79a..ea75ba2a2 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1556,7 +1556,7 @@ fn inject_common_builtin( }; declaration.overloads.push(module.add_builtin( vec![ty(), ty(), base_ty()], - MacroCall::MathFunction(MathFunction::SmoothStep), + MacroCall::SmoothStep { splatted: size }, )) } } @@ -1604,6 +1604,12 @@ pub enum MacroCall { BitCast(Sk), Derivate(DerivativeAxis), Barrier, + /// SmoothStep needs a separate variant because it might need it's inputs + /// to be splatted depending on the overload + SmoothStep { + /// The size of the splat operation if some + splatted: Option, + }, } impl MacroCall { @@ -2072,6 +2078,22 @@ impl MacroCall { body.push(crate::Statement::Barrier(crate::Barrier::all()), meta); return Ok(None); } + MacroCall::SmoothStep { splatted } => { + ctx.implicit_splat(parser, &mut args[0], meta, splatted)?; + ctx.implicit_splat(parser, &mut args[1], meta, splatted)?; + + ctx.add_expression( + Expression::Math { + fun: MathFunction::SmoothStep, + arg: args[0], + arg1: args.get(1).copied(), + arg2: args.get(2).copied(), + arg3: None, + }, + Span::default(), + body, + ) + } })) } } diff --git a/tests/in/glsl/math-functions.vert b/tests/in/glsl/math-functions.vert index dd8ab7cda..104ca0eea 100644 --- a/tests/in/glsl/math-functions.vert +++ b/tests/in/glsl/math-functions.vert @@ -53,4 +53,7 @@ void main() { // float ldexpOut = ldexp(a.x, i); vec4 rad = radians(a); float deg = degrees(a.x); + float smoothStepScalar = smoothstep(0.0, 1.0, 0.5); + vec4 smoothStepVector = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); + vec4 smoothStepMixed = smoothstep(0.0, 1.0, vec4(0.5)); } diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 6fb6f6bd7..58e95f673 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -44,6 +44,9 @@ fn main_1() { var stepOut: vec4; var rad: vec4; var deg: f32; + var smoothStepScalar: f32; + var smoothStepVector: vec4; + var smoothStepMixed: vec4; _ = vec4(1.0); _ = vec4(2.0); @@ -205,6 +208,13 @@ fn main_1() { _ = _e233.x; let _e235 = a; deg = degrees(_e235.x); + smoothStepScalar = smoothstep(0.0, 1.0, 0.5); + _ = vec4(0.0); + _ = vec4(1.0); + _ = vec4(0.5); + smoothStepVector = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); + _ = vec4(0.5); + smoothStepMixed = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); return; } From dab932e8ce46eed20989baa2d52f206f97eaf17c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 12 Jun 2022 17:33:43 +0100 Subject: [PATCH 1783/2212] glsl-in: Fix last case falltrough and empty switch GLSL allows the last case of a switch statement to not have a `break` statement causing it to be marked as fall-trough, naga's IR on the other hand doesn't allow the last case to be fall-trough, this is fixed by force marking it in the glsl frontend as not fall-trough. GLSL also allows empty switch statements and without default cases, naga's IR requires there be a default case, this is fixed by adding an empty default case in the glsl frontend if no default case was present in the switch statement. --- src/front/glsl/parser/functions.rs | 25 +++++++++++++++ tests/in/glsl/statements.frag | 27 ++++++++++++++++ tests/out/wgsl/statements-frag.wgsl | 50 +++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+) create mode 100644 tests/in/glsl/statements.frag create mode 100644 tests/out/wgsl/statements-frag.wgsl diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 8a9487917..549b73045 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -177,6 +177,8 @@ impl<'source> ParsingContext<'source> { ctx.emit_restart(body); let mut cases = Vec::new(); + // Track if any default case is present in the switch statement. + let mut default_present = false; self.expect(parser, TokenValue::LeftBrace)?; loop { @@ -215,6 +217,7 @@ impl<'source> ParsingContext<'source> { } TokenValue::Default => { self.bump(parser)?; + default_present = true; crate::SwitchValue::Default } TokenValue::RightBrace => { @@ -273,6 +276,28 @@ impl<'source> ParsingContext<'source> { meta.subsume(end_meta); + // GLSL allows the last case to not have any `break` statement, + // this would mark it as fall trough but naga's IR requires that + // the last case must not be fall trough, so we mark need to mark + // the last case as not fall trough always. + // + // NOTE: do not unwrap here since a switch statement isn't required + // to have any cases. + if let Some(case) = cases.last_mut() { + case.fall_through = false; + } + + // Add an empty default case in case non was present, this is needed because + // naga's IR requires that all switch statements must have a default case but + // GLSL doesn't require that, so we might need to add an empty default case. + if !default_present { + cases.push(SwitchCase { + value: crate::SwitchValue::Default, + body: Block::new(), + fall_through: false, + }) + } + body.push(Statement::Switch { selector, cases }, meta); meta diff --git a/tests/in/glsl/statements.frag b/tests/in/glsl/statements.frag new file mode 100644 index 000000000..c9e276c87 --- /dev/null +++ b/tests/in/glsl/statements.frag @@ -0,0 +1,27 @@ +#version 460 core + +void switchEmpty(int a) { + switch (a) {} + + return; +} + +void switchNoDefault(int a) { + switch (a) { + case 0: + break; + } + + return; +} + +void switchNoLastBreak(int a) { + switch (a) { + default: + int b = a; + } + + return; +} + +void main() {} diff --git a/tests/out/wgsl/statements-frag.wgsl b/tests/out/wgsl/statements-frag.wgsl new file mode 100644 index 000000000..b79995932 --- /dev/null +++ b/tests/out/wgsl/statements-frag.wgsl @@ -0,0 +1,50 @@ +fn switchEmpty(a: i32) { + var a_1: i32; + + a_1 = a; + let _e2 = a_1; + switch _e2 { + default: { + } + } + return; +} + +fn switchNoDefault(a_2: i32) { + var a_3: i32; + + a_3 = a_2; + let _e2 = a_3; + switch _e2 { + case 0: { + } + default: { + } + } + return; +} + +fn switchNoLastBreak(a_4: i32) { + var a_5: i32; + var b: i32; + + a_5 = a_4; + let _e2 = a_5; + switch _e2 { + default: { + let _e3 = a_5; + b = _e3; + } + } + return; +} + +fn main_1() { + return; +} + +@fragment +fn main() { + main_1(); + return; +} From ae50f31d4f0ae954da1816a5d841201fcab15dc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 12 Jun 2022 18:32:02 +0100 Subject: [PATCH 1784/2212] glsl-in: Don't allow empty last case in switch The GLSL spec forbids switch statements with an empty last case, so we check that now and throw an error if necessary --- src/front/glsl/parser/functions.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 549b73045..2f271b816 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -276,14 +276,26 @@ impl<'source> ParsingContext<'source> { meta.subsume(end_meta); - // GLSL allows the last case to not have any `break` statement, - // this would mark it as fall trough but naga's IR requires that - // the last case must not be fall trough, so we mark need to mark - // the last case as not fall trough always. - // // NOTE: do not unwrap here since a switch statement isn't required // to have any cases. if let Some(case) = cases.last_mut() { + // GLSL requires that the last case not be empty, so we check + // that here and produce an error otherwise (fall_trough must + // also be checked because `break`s count as statements but + // they aren't added to the body) + if case.body.is_empty() && case.fall_through { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + "last case/default label must be followed by statements".into(), + ), + meta, + }) + } + + // GLSL allows the last case to not have any `break` statement, + // this would mark it as fall trough but naga's IR requires that + // the last case must not be fall trough, so we mark need to mark + // the last case as not fall trough always. case.fall_through = false; } From 70743ee7dc379f6c22fd25da8bd581a03f73f1d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 7 Jun 2022 21:22:34 +0100 Subject: [PATCH 1785/2212] glsl-in: Perform casts in int only math functions Some functions like abs only accept signed integers while naga's IR accepts both signed and unsigned integers, this wasn't accounted for in the glsl backend causing it to produce code that wouldn't type check. This commit addresses it by performing casts from uint to int of the function argument and then back from int to uint for the function return. --- src/back/glsl/mod.rs | 74 ++++++++++++++++++++++++++++++-------------- 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index cba3b3ca0..134b4e241 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2808,32 +2808,59 @@ impl<'a, W: Write> Writer<'a, W> { let extract_bits = fun == Mf::ExtractBits; let insert_bits = fun == Mf::InsertBits; - // we might need to cast to unsigned integers since - // GLSL's findLSB / findMSB always return signed integers - let need_extra_paren = { - (fun == Mf::FindLsb || fun == Mf::FindMsb || fun == Mf::CountOneBits) - && match *ctx.info[arg].ty.inner_with(&self.module.types) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - .. - } => { - write!(self.out, "uint(")?; - true - } - crate::TypeInner::Vector { - kind: crate::ScalarKind::Uint, - size, - .. - } => { - write!(self.out, "uvec{}(", size as u8)?; - true - } - _ => false, - } + // Some GLSL functions always return signed integers (like findMSB), + // so they need to be cast to uint if the argument is also an uint. + let needs_int_to_uint = + matches!(fun, Mf::FindLsb | Mf::FindMsb | Mf::CountOneBits | Mf::Abs); + + // Some GLSL functions only accept signed integers (like abs), + // so they need their argument cast from uint to int. + let needs_uint_to_int = matches!(fun, Mf::Abs); + + // Check if the argument is an unsigned integer and return the vector size + // in case it's a vector + let maybe_uint_size = match *ctx.info[arg].ty.inner_with(&self.module.types) { + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } => Some(None), + crate::TypeInner::Vector { + kind: crate::ScalarKind::Uint, + size, + .. + } => Some(Some(size)), + _ => None, }; + if let Some(maybe_size) = maybe_uint_size { + // Cast to uint if the function needs it + if needs_int_to_uint { + match maybe_size { + Some(size) => write!(self.out, "uvec{}(", size as u8)?, + None => write!(self.out, "uint(")?, + } + } + } + write!(self.out, "{}(", fun_name)?; + + if let Some(maybe_size) = maybe_uint_size { + // Cast to int if the function needs it + if needs_uint_to_int { + match maybe_size { + Some(size) => write!(self.out, "ivec{}(", size as u8)?, + None => write!(self.out, "int(")?, + } + } + } + self.write_expr(arg, ctx)?; + + // Close the cast from uint to int + if needs_uint_to_int && maybe_uint_size.is_some() { + write!(self.out, ")")? + } + if let Some(arg) = arg1 { write!(self.out, ", ")?; if extract_bits { @@ -2866,7 +2893,8 @@ impl<'a, W: Write> Writer<'a, W> { } write!(self.out, ")")?; - if need_extra_paren { + // Close the cast from int to uint + if needs_int_to_uint && maybe_uint_size.is_some() { write!(self.out, ")")? } } From ae58fbf4d04d7fb4d8d2340f06a11b869eecb290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 12 Jun 2022 16:17:33 +0100 Subject: [PATCH 1786/2212] Add tests --- tests/in/math-functions.wgsl | 1 + .../out/glsl/math-functions.main.Vertex.glsl | 1 + tests/out/hlsl/math-functions.hlsl | 1 + tests/out/msl/math-functions.msl | 1 + tests/out/spv/math-functions.spvasm | 52 ++++++++++--------- tests/out/wgsl/math-functions.wgsl | 1 + 6 files changed, 33 insertions(+), 24 deletions(-) diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index 38e9acee9..a2e097a04 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -7,4 +7,5 @@ fn main() { let c = degrees(v); let d = radians(v); let const_dot = dot(vec2(), vec2()); + let first_leading_bit_abs = firstLeadingBit(abs(0u)); } diff --git a/tests/out/glsl/math-functions.main.Vertex.glsl b/tests/out/glsl/math-functions.main.Vertex.glsl index 02a94ea69..8d7286829 100644 --- a/tests/out/glsl/math-functions.main.Vertex.glsl +++ b/tests/out/glsl/math-functions.main.Vertex.glsl @@ -11,5 +11,6 @@ void main() { vec4 c = degrees(v); vec4 d = radians(v); int const_dot = ( + ivec2(0, 0).x * ivec2(0, 0).x + ivec2(0, 0).y * ivec2(0, 0).y); + uint first_leading_bit_abs = uint(findMSB(uint(abs(int(0u))))); } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index b17a32cf4..179cfee66 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -7,4 +7,5 @@ void main() float4 c = degrees(v); float4 d = radians(v); int const_dot = dot(int2(0, 0), int2(0, 0)); + uint first_leading_bit_abs = firstbithigh(abs(0u)); } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index e08894037..87de8418c 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -14,4 +14,5 @@ vertex void main_( metal::float4 c = ((v) * 57.295779513082322865); metal::float4 d = ((v) * 0.017453292519943295474); int const_dot = ( + const_type.x * const_type.x + const_type.y * const_type.y); + uint first_leading_bit_abs = (((metal::clz(metal::abs(0u)) + 1) % 33) - 1); } diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 03b4a0423..07a16f754 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,38 +1,42 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 29 +; Bound: 33 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %11 "main" +OpEntryPoint Vertex %13 "main" %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 %5 = OpConstant %4 0.0 %7 = OpTypeInt 32 1 %6 = OpConstant %7 0 -%8 = OpTypeVector %7 2 -%9 = OpConstantComposite %8 %6 %6 -%12 = OpTypeFunction %2 -%14 = OpTypeVector %4 4 -%21 = OpConstantNull %7 -%11 = OpFunction %2 None %12 -%10 = OpLabel -OpBranch %13 -%13 = OpLabel -%15 = OpCompositeConstruct %14 %5 %5 %5 %5 -%16 = OpExtInst %4 %1 Degrees %3 -%17 = OpExtInst %4 %1 Radians %3 -%18 = OpExtInst %14 %1 Degrees %15 -%19 = OpExtInst %14 %1 Radians %15 -%22 = OpCompositeExtract %7 %9 0 -%23 = OpCompositeExtract %7 %9 0 -%24 = OpIMul %7 %22 %23 -%25 = OpIAdd %7 %21 %24 -%26 = OpCompositeExtract %7 %9 1 -%27 = OpCompositeExtract %7 %9 1 -%28 = OpIMul %7 %26 %27 -%20 = OpIAdd %7 %25 %28 +%9 = OpTypeInt 32 0 +%8 = OpConstant %9 0 +%10 = OpTypeVector %7 2 +%11 = OpConstantComposite %10 %6 %6 +%14 = OpTypeFunction %2 +%16 = OpTypeVector %4 4 +%23 = OpConstantNull %7 +%13 = OpFunction %2 None %14 +%12 = OpLabel +OpBranch %15 +%15 = OpLabel +%17 = OpCompositeConstruct %16 %5 %5 %5 %5 +%18 = OpExtInst %4 %1 Degrees %3 +%19 = OpExtInst %4 %1 Radians %3 +%20 = OpExtInst %16 %1 Degrees %17 +%21 = OpExtInst %16 %1 Radians %17 +%24 = OpCompositeExtract %7 %11 0 +%25 = OpCompositeExtract %7 %11 0 +%26 = OpIMul %7 %24 %25 +%27 = OpIAdd %7 %23 %26 +%28 = OpCompositeExtract %7 %11 1 +%29 = OpCompositeExtract %7 %11 1 +%30 = OpIMul %7 %28 %29 +%22 = OpIAdd %7 %27 %30 +%31 = OpCopyObject %9 %8 +%32 = OpExtInst %9 %1 FindUMsb %31 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 2be33d564..954316879 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -6,4 +6,5 @@ fn main() { let c = degrees(v); let d = radians(v); let const_dot = dot(vec2(0, 0), vec2(0, 0)); + let first_leading_bit_abs = firstLeadingBit(abs(0u)); } From 98bc8fedf9b88ecbdc1bbe653f4a4f92a915d9ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 14 Jun 2022 22:27:47 +0100 Subject: [PATCH 1787/2212] Apply comments --- src/back/glsl/mod.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 134b4e241..18ba9f29b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2810,12 +2810,12 @@ impl<'a, W: Write> Writer<'a, W> { // Some GLSL functions always return signed integers (like findMSB), // so they need to be cast to uint if the argument is also an uint. - let needs_int_to_uint = + let ret_might_need_int_to_uint = matches!(fun, Mf::FindLsb | Mf::FindMsb | Mf::CountOneBits | Mf::Abs); // Some GLSL functions only accept signed integers (like abs), // so they need their argument cast from uint to int. - let needs_uint_to_int = matches!(fun, Mf::Abs); + let arg_might_need_uint_to_int = matches!(fun, Mf::Abs); // Check if the argument is an unsigned integer and return the vector size // in case it's a vector @@ -2832,9 +2832,9 @@ impl<'a, W: Write> Writer<'a, W> { _ => None, }; - if let Some(maybe_size) = maybe_uint_size { - // Cast to uint if the function needs it - if needs_int_to_uint { + // Cast to uint if the function needs it + if ret_might_need_int_to_uint { + if let Some(maybe_size) = maybe_uint_size { match maybe_size { Some(size) => write!(self.out, "uvec{}(", size as u8)?, None => write!(self.out, "uint(")?, @@ -2844,9 +2844,9 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}(", fun_name)?; - if let Some(maybe_size) = maybe_uint_size { - // Cast to int if the function needs it - if needs_uint_to_int { + // Cast to int if the function needs it + if arg_might_need_uint_to_int { + if let Some(maybe_size) = maybe_uint_size { match maybe_size { Some(size) => write!(self.out, "ivec{}(", size as u8)?, None => write!(self.out, "int(")?, @@ -2857,7 +2857,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(arg, ctx)?; // Close the cast from uint to int - if needs_uint_to_int && maybe_uint_size.is_some() { + if arg_might_need_uint_to_int && maybe_uint_size.is_some() { write!(self.out, ")")? } @@ -2894,7 +2894,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")?; // Close the cast from int to uint - if needs_int_to_uint && maybe_uint_size.is_some() { + if ret_might_need_int_to_uint && maybe_uint_size.is_some() { write!(self.out, ")")? } } From 357da630765d58b5998a80c3d1457ae93a97cbe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 15 Jun 2022 20:17:59 +0100 Subject: [PATCH 1788/2212] Patch ron version (#1986) Require at least version 0.7.1 of ron, this version changed how floating points are serialized by forcing them to always have the decimal part, this makes it backwards incompatible with our tests because we do a syntatic diff and not a semantic one. --- Cargo.toml | 5 ++++- tests/out/ir/shadow.ron | 6 +++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1476eb9cf..1b2fb838b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,7 +67,10 @@ unicode-xid = { version = "0.2.3", optional = true } bincode = "1" criterion = { version = "0.3", features = [] } diff = "0.1" -ron = "0.7" +# Require at least version 0.7.1 of ron, this version changed how floating points are +# serialized by forcing them to always have the decimal part, this makes it backwards +# incompatible with our tests because we do a syntatic diff and not a semantic one. +ron = "~0.7.1" serde = { version = "1.0", features = ["derive"] } spirv = { version = "0.2", features = ["deserialize"] } rspirv = "0.11" diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 128a4032e..d9a07a96a 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -324,7 +324,7 @@ specialization: None, inner: Scalar( width: 4, - value: Float(0), + value: Float(0.0), ), ), ( @@ -332,7 +332,7 @@ specialization: None, inner: Scalar( width: 4, - value: Float(1), + value: Float(1.0), ), ), ( @@ -400,7 +400,7 @@ specialization: None, inner: Scalar( width: 4, - value: Float(0), + value: Float(0.0), ), ), ( From 46387e90ceaf121974c505f29aeb80e9e4226a73 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 9 Jun 2022 16:25:06 +0200 Subject: [PATCH 1789/2212] unify alignment related functionality --- src/back/hlsl/conv.rs | 5 +- src/back/hlsl/storage.rs | 21 +---- src/back/spv/writer.rs | 9 +- src/front/glsl/offset.rs | 44 +++++----- src/front/glsl/parser/declarations.rs | 10 ++- src/front/mod.rs | 17 ---- src/front/spv/mod.rs | 14 +-- src/front/wgsl/mod.rs | 4 +- src/proc/layouter.rs | 122 +++++++++++++++++++------- src/proc/mod.rs | 5 +- src/valid/type.rs | 105 ++++++++++------------ 11 files changed, 181 insertions(+), 175 deletions(-) diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index b63d63577..039bfcce3 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -1,5 +1,7 @@ use std::borrow::Cow; +use crate::proc::Alignment; + use super::Error; impl crate::ScalarKind { @@ -49,8 +51,7 @@ impl crate::TypeInner { rows, width, } => { - let aligned_rows = if rows > crate::VectorSize::Bi { 4 } else { 2 }; - let stride = aligned_rows * width as u32; + let stride = Alignment::from(rows) * width as u32; let last_row_size = rows as u32 * width as u32; ((columns as u32 - 1) * stride) + last_row_size } diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 637b05d4b..65edc9202 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -6,7 +6,7 @@ HLSL backend uses byte address buffers for all storage buffers in IR. use super::{super::FunctionCtx, BackendResult, Error}; use crate::{ - proc::{NameKey, TypeResolution}, + proc::{Alignment, NameKey, TypeResolution}, Handle, }; @@ -130,11 +130,7 @@ impl super::Writer<'_, W> { )?; // Note: Matrices containing vec3s, due to padding, act like they contain vec4s. - let padded_rows = match rows { - crate::VectorSize::Tri => 4, - rows => rows as u32, - }; - let row_stride = width as u32 * padded_rows; + let row_stride = Alignment::from(rows) * width as u32; let iter = (0..columns as u32).map(|i| { let ty_inner = crate::TypeInner::Vector { size: rows, @@ -277,11 +273,7 @@ impl super::Writer<'_, W> { writeln!(self.out, ";")?; // Note: Matrices containing vec3s, due to padding, act like they contain vec4s. - let padded_rows = match rows { - crate::VectorSize::Tri => 4, - rows => rows as u32, - }; - let row_stride = width as u32 * padded_rows; + let row_stride = Alignment::from(rows) * width as u32; // then iterate the stores for i in 0..columns as u32 { @@ -409,12 +401,7 @@ impl super::Writer<'_, W> { stride: width as u32, }, crate::TypeInner::Matrix { columns, width, .. } => Parent::Array { - stride: width as u32 - * if columns > crate::VectorSize::Bi { - 4 - } else { - 2 - }, + stride: Alignment::from(columns) * width as u32, }, _ => unreachable!(), }, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f4d9e0e60..e9dae65f9 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -8,7 +8,7 @@ use super::{ use crate::{ arena::{Handle, UniqueArena}, back::spv::BindingInfo, - proc::TypeResolution, + proc::{Alignment, TypeResolution}, valid::{FunctionInfo, ModuleInfo}, }; use spirv::Word; @@ -1379,10 +1379,7 @@ impl Writer { width, } = *member_array_subty_inner { - let byte_stride = match rows { - crate::VectorSize::Bi => 2 * width, - crate::VectorSize::Tri | crate::VectorSize::Quad => 4 * width, - }; + let byte_stride = Alignment::from(rows) * width as u32; self.annotations.push(Instruction::member_decorate( struct_id, index as u32, @@ -1393,7 +1390,7 @@ impl Writer { struct_id, index as u32, Decoration::MatrixStride, - &[byte_stride as u32], + &[byte_stride], )); } diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 9c89b5d2c..d7950489c 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -16,7 +16,7 @@ use super::{ error::{Error, ErrorKind}, Span, }; -use crate::{front::align_up, Arena, Constant, Handle, Type, TypeInner, UniqueArena}; +use crate::{proc::Alignment, Arena, Constant, Handle, Type, TypeInner, UniqueArena}; /// Struct with information needed for defining a struct member. /// @@ -28,7 +28,7 @@ pub struct TypeAlignSpan { /// with a different stride set. pub ty: Handle, /// The alignment required by the type. - pub align: u32, + pub align: Alignment, /// The size of the type. pub span: u32, } @@ -54,15 +54,15 @@ pub fn calculate_offset( let (align, span) = match types[ty].inner { // 1. If the member is a scalar consuming N basic machine units, // the base alignment is N. - TypeInner::Scalar { width, .. } => (width as u32, width as u32), + TypeInner::Scalar { width, .. } => (Alignment::from_width(width), width as u32), // 2. If the member is a two- or four-component vector with components // consuming N basic machine units, the base alignment is 2N or 4N, respectively. // 3. If the member is a three-component vector with components consuming N // basic machine units, the base alignment is 4N. - TypeInner::Vector { size, width, .. } => match size { - crate::VectorSize::Tri => (4 * width as u32, 3 * width as u32), - _ => (size as u32 * width as u32, size as u32 * width as u32), - }, + TypeInner::Vector { size, width, .. } => ( + Alignment::from(size) * Alignment::from_width(width), + size as u32 * width as u32, + ), // 4. If the member is an array of scalars or vectors, the base alignment and array // stride are set to match the base alignment of a single array element, according // to rules (1), (2), and (3), and rounded up to the base alignment of a vec4. @@ -71,14 +71,14 @@ pub fn calculate_offset( let info = calculate_offset(base, meta, layout, types, constants, errors); let name = types[ty].name.clone(); - let mut align = info.align; - let mut stride = (align).max(info.span); // See comment at the beginning of the function - if StructLayout::Std430 != layout { - stride = align_up(stride, 16); - align = align_up(align, 16); - } + let (align, stride) = if StructLayout::Std430 == layout { + (info.align, info.align.round_up(info.span)) + } else { + let align = info.align.max(Alignment::MIN_UNIFORM); + (align, align.round_up(info.span)) + }; let span = match size { crate::ArraySize::Constant(s) => { @@ -111,14 +111,11 @@ pub fn calculate_offset( rows, width, } => { - let mut align = match rows { - crate::VectorSize::Tri => (4 * width as u32), - _ => (rows as u32 * width as u32), - }; + let mut align = Alignment::from(rows) * Alignment::from_width(width); // See comment at the beginning of the function if StructLayout::Std430 != layout { - align = align_up(align, 16); + align = align.max(Alignment::MIN_UNIFORM); } // See comment on the error kind @@ -133,15 +130,16 @@ pub fn calculate_offset( } TypeInner::Struct { ref members, .. } => { let mut span = 0; - let mut align = 0; + let mut align = Alignment::ONE; let mut members = members.clone(); let name = types[ty].name.clone(); for member in members.iter_mut() { let info = calculate_offset(member.ty, meta, layout, types, constants, errors); - span = align_up(span, info.align); - align = align.max(info.align); + let member_alignment = info.align; + span = member_alignment.round_up(span); + align = member_alignment.max(align); member.ty = info.ty; member.offset = span; @@ -149,7 +147,7 @@ pub fn calculate_offset( span += info.span; } - span = align_up(span, align); + span = align.round_up(span); let ty_span = types.get_span(ty); ty = types.insert( @@ -167,7 +165,7 @@ pub fn calculate_offset( kind: ErrorKind::SemanticError("Invalid struct member type".into()), meta, }); - (1, 0) + (Alignment::ONE, 0) } }; diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 18a6ceb2e..a43f2fe77 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -12,6 +12,7 @@ use crate::{ variables::{GlobalOrConstant, VarDeclaration}, Error, ErrorKind, Parser, Span, }, + proc::Alignment, AddressSpace, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StructMember, Type, TypeInner, }; @@ -570,7 +571,7 @@ impl<'source> ParsingContext<'source> { layout: StructLayout, ) -> Result { let mut span = 0; - let mut align = 0; + let mut align = Alignment::ONE; loop { // TODO: type_qualifier @@ -593,8 +594,9 @@ impl<'source> ParsingContext<'source> { &mut parser.errors, ); - span = crate::front::align_up(span, info.align); - align = align.max(info.align); + let member_alignment = info.align; + span = member_alignment.round_up(span); + align = member_alignment.max(align); members.push(StructMember { name: Some(name), @@ -610,7 +612,7 @@ impl<'source> ParsingContext<'source> { } } - span = crate::front::align_up(span, align); + span = align.round_up(span); Ok(span) } diff --git a/src/front/mod.rs b/src/front/mod.rs index fb6bef75e..bfc99f1f9 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -133,20 +133,3 @@ impl ops::Index> for Typifier { &self.resolutions[handle.index()] } } - -/// Helper function used for aligning `value` to the next multiple of `align` -/// -/// # Notes: -/// - `align` must be a power of two. -/// - The returned value will be greater or equal to `value`. -/// # Examples: -/// ```ignore -/// assert_eq!(0, align_up(0, 16)); -/// assert_eq!(16, align_up(1, 16)); -/// assert_eq!(16, align_up(16, 16)); -/// assert_eq!(334, align_up(333, 2)); -/// assert_eq!(384, align_up(257, 128)); -/// ``` -pub const fn align_up(value: u32, align: u32) -> u32 { - ((value.wrapping_sub(1)) & !(align - 1)).wrapping_add(align) -} diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d78a128be..234efd016 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -39,7 +39,7 @@ use function::*; use crate::{ arena::{Arena, Handle, UniqueArena}, - proc::Layouter, + proc::{Alignment, Layouter}, FastHashMap, FastHashSet, }; @@ -4377,7 +4377,7 @@ impl> Parser { let mut member_lookups = Vec::with_capacity(members.capacity()); let mut storage_access = crate::StorageAccess::empty(); let mut span = 0; - let mut alignment = 1; + let mut alignment = Alignment::ONE; for i in 0..u32::from(inst.wc) - 2 { let type_id = self.next()?; let ty = self.lookup_type.lookup(type_id)?.handle; @@ -4393,8 +4393,9 @@ impl> Parser { row_major: decor.matrix_major == Some(Majority::Row), }); - span = crate::front::align_up(span, self.layouter[ty].alignment.get()); - alignment = self.layouter[ty].alignment.get().max(alignment); + let member_alignment = self.layouter[ty].alignment; + span = member_alignment.round_up(span); + alignment = member_alignment.max(alignment); let mut binding = decor.io_binding().ok(); if let Some(offset) = decor.offset { @@ -4412,8 +4413,7 @@ impl> Parser { } = *inner { if let Some(stride) = decor.matrix_stride { - let aligned_rows = if rows > crate::VectorSize::Bi { 4 } else { 2 }; - let expected_stride = aligned_rows * width as u32; + let expected_stride = Alignment::from(rows) * width as u32; if stride.get() != expected_stride { return Err(Error::UnsupportedMatrixStride { stride: stride.get(), @@ -4436,7 +4436,7 @@ impl> Parser { }); } - span = crate::front::align_up(span, alignment); + span = alignment.round_up(span); let inner = crate::TypeInner::Struct { span, members }; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 0e32f54ff..8dd28e047 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -2816,7 +2816,7 @@ impl Parser { let (value, span) = lexer.capture_span(Self::parse_non_negative_i32_literal)?; lexer.expect(Token::Paren(')'))?; - align = Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign(span))?); + align = Some(Alignment::new(value).ok_or(Error::ZeroSizeOrAlign(span))?); } (word, word_span) => bind_parser.parse(lexer, word, word_span)?, } @@ -2852,7 +2852,7 @@ impl Parser { }); } - let span = Layouter::round_up(alignment, offset); + let span = alignment.round_up(offset); Ok((members, span)) } diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 598afba92..4bfb7ec05 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -1,7 +1,86 @@ use crate::arena::{Arena, BadHandle, Handle, UniqueArena}; -use std::{num::NonZeroU32, ops}; +use std::{fmt::Display, num::NonZeroU32, ops}; -pub type Alignment = NonZeroU32; +/// A newtype struct where its only valid values are powers of 2 +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct Alignment(NonZeroU32); + +impl Alignment { + pub const ONE: Self = Self(unsafe { NonZeroU32::new_unchecked(1) }); + pub const TWO: Self = Self(unsafe { NonZeroU32::new_unchecked(2) }); + pub const FOUR: Self = Self(unsafe { NonZeroU32::new_unchecked(4) }); + pub const EIGHT: Self = Self(unsafe { NonZeroU32::new_unchecked(8) }); + pub const SIXTEEN: Self = Self(unsafe { NonZeroU32::new_unchecked(16) }); + + pub const MIN_UNIFORM: Self = Self::SIXTEEN; + + pub const fn new(n: u32) -> Option { + if n.is_power_of_two() { + // SAFETY: value can't be 0 since we just checked if it's a power of 2 + Some(Self(unsafe { NonZeroU32::new_unchecked(n) })) + } else { + None + } + } + + /// # Panics + /// If `width` is not a power of 2 + pub fn from_width(width: u8) -> Self { + Self::new(width as u32).unwrap() + } + + /// Returns whether or not `n` is a multiple of this alignment. + pub const fn is_aligned(&self, n: u32) -> bool { + // equivalent to: `n % self.0.get() == 0` but much faster + n & (self.0.get() - 1) == 0 + } + + /// Round `n` up to the nearest alignment boundary. + pub const fn round_up(&self, n: u32) -> u32 { + // equivalent to: + // match n % self.0.get() { + // 0 => n, + // rem => n + (self.0.get() - rem), + // } + let mask = self.0.get() - 1; + (n + mask) & !mask + } +} + +impl Display for Alignment { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.get().fmt(f) + } +} + +impl ops::Mul for Alignment { + type Output = u32; + + fn mul(self, rhs: u32) -> Self::Output { + self.0.get() * rhs + } +} + +impl ops::Mul for Alignment { + type Output = Alignment; + + fn mul(self, rhs: Alignment) -> Self::Output { + // SAFETY: both lhs and rhs are powers of 2, the result will be a power of 2 + Self(unsafe { NonZeroU32::new_unchecked(self.0.get() * rhs.0.get()) }) + } +} + +impl From for Alignment { + fn from(size: crate::VectorSize) -> Self { + match size { + crate::VectorSize::Bi => Alignment::TWO, + crate::VectorSize::Tri => Alignment::FOUR, + crate::VectorSize::Quad => Alignment::FOUR, + } + } +} /// Size and alignment information for a type. #[derive(Clone, Copy, Debug, Hash, PartialEq)] @@ -15,7 +94,7 @@ pub struct TypeLayout { impl TypeLayout { /// Produce the stride as if this type is a base of an array. pub const fn to_stride(&self) -> u32 { - Layouter::round_up(self.alignment, self.size) + self.alignment.round_up(self.size) } } @@ -49,8 +128,6 @@ pub enum LayoutErrorInner { InvalidArrayElementType(Handle), #[error("Struct member[{0}] type {1:?} doesn't exist")] InvalidStructMemberType(u32, Handle), - #[error("Zero width is not supported")] - ZeroWidth, #[error("Array size is a bad handle")] BadHandle(#[from] BadHandle), } @@ -74,14 +151,6 @@ impl Layouter { self.layouts.clear(); } - /// Round `offset` up to the nearest `alignment` boundary. - pub const fn round_up(alignment: Alignment, offset: u32) -> u32 { - match offset & (alignment.get() - 1) { - 0 => offset, - other => offset + alignment.get() - other, - } - } - /// Return the offset and span of a struct member. /// /// The member must fall at or after `offset`. The member's alignment and @@ -100,7 +169,7 @@ impl Layouter { ) -> (ops::Range, Alignment) { let layout = self.layouts[ty.index()]; let alignment = align.unwrap_or(layout.alignment); - let start = Self::round_up(alignment, offset); + let start = alignment.round_up(offset); let span = match size { Some(size) => size.get(), None => layout.size, @@ -137,8 +206,7 @@ impl Layouter { let layout = match ty.inner { Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => TypeLayout { size, - alignment: Alignment::new(width as u32) - .ok_or(LayoutErrorInner::ZeroWidth.with(ty_handle))?, + alignment: Alignment::from_width(width), }, Ti::Vector { size: vec_size, @@ -146,15 +214,7 @@ impl Layouter { .. } => TypeLayout { size, - alignment: { - let count = if vec_size >= crate::VectorSize::Tri { - 4 - } else { - 2 - }; - Alignment::new(count * width as u32) - .ok_or(LayoutErrorInner::ZeroWidth.with(ty_handle))? - }, + alignment: { Alignment::from(vec_size) * Alignment::from_width(width) }, }, Ti::Matrix { columns: _, @@ -162,15 +222,11 @@ impl Layouter { width, } => TypeLayout { size, - alignment: { - let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; - Alignment::new(count * width as u32) - .ok_or(LayoutErrorInner::ZeroWidth.with(ty_handle))? - }, + alignment: { Alignment::from(rows) * Alignment::from_width(width) }, }, Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { size, - alignment: Alignment::new(1).unwrap(), + alignment: Alignment::ONE, }, Ti::Array { base, @@ -185,7 +241,7 @@ impl Layouter { }, }, Ti::Struct { span, ref members } => { - let mut alignment = Alignment::new(1).unwrap(); + let mut alignment = Alignment::ONE; for (index, member) in members.iter().enumerate() { alignment = if member.ty < ty_handle { alignment.max(self[member.ty].alignment) @@ -204,7 +260,7 @@ impl Layouter { } Ti::Image { .. } | Ti::Sampler { .. } | Ti::BindingArray { .. } => TypeLayout { size, - alignment: Alignment::new(1).unwrap(), + alignment: Alignment::ONE, }, }; debug_assert!(size <= layout.size); diff --git a/src/proc/mod.rs b/src/proc/mod.rs index a4a63abbd..823a190de 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -113,10 +113,7 @@ impl super::TypeInner { columns, rows, width, - } => { - let aligned_rows = if rows > crate::VectorSize::Bi { 4 } else { 2 }; - columns as u32 * aligned_rows * width as u32 - } + } => Alignment::from(rows) * width as u32 * columns as u32, Self::Pointer { .. } | Self::ValuePointer { .. } => POINTER_SPAN, Self::Array { base: _, diff --git a/src/valid/type.rs b/src/valid/type.rs index 0312c2143..f103017dd 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -4,8 +4,6 @@ use crate::{ proc::Alignment, }; -const UNIFORM_MIN_ALIGNMENT: Alignment = unsafe { Alignment::new_unchecked(16) }; - bitflags::bitflags! { /// Flags associated with [`Type`]s by [`Validator`]. /// @@ -67,14 +65,14 @@ bitflags::bitflags! { #[derive(Clone, Copy, Debug, thiserror::Error)] pub enum Disalignment { #[error("The array stride {stride} is not a multiple of the required alignment {alignment}")] - ArrayStride { stride: u32, alignment: u32 }, + ArrayStride { stride: u32, alignment: Alignment }, #[error("The struct span {span}, is not a multiple of the required alignment {alignment}")] - StructSpan { span: u32, alignment: u32 }, + StructSpan { span: u32, alignment: Alignment }, #[error("The struct member[{index}] offset {offset} is not a multiple of the required alignment {alignment}")] MemberOffset { index: u32, offset: u32, - alignment: u32, + alignment: Alignment, }, #[error("The struct member[{index}] offset {offset} must be at least {expected}")] MemberOffsetAfterStruct { @@ -134,8 +132,8 @@ pub enum TypeError { EmptyStruct, } -// Only makes sense if `flags.contains(HOST_SHARED)` -type LayoutCompatibility = Result, (Handle, Disalignment)>; +// Only makes sense if `flags.contains(HOST_SHAREABLE)` +type LayoutCompatibility = Result, Disalignment)>; fn check_member_layout( accum: &mut LayoutCompatibility, @@ -145,20 +143,18 @@ fn check_member_layout( parent_handle: Handle, ) { *accum = match (*accum, member_layout) { - (Ok(cur_alignment), Ok(align)) => { - let align = align.unwrap().get(); - if member.offset % align != 0 { + (Ok(cur_alignment), Ok(alignment)) => { + if alignment.is_aligned(member.offset) { + Ok(cur_alignment.max(alignment)) + } else { Err(( parent_handle, Disalignment::MemberOffset { index: member_index, offset: member.offset, - alignment: align, + alignment, }, )) - } else { - let combined_alignment = ((cur_alignment.unwrap().get() - 1) | (align - 1)) + 1; - Ok(Alignment::new(combined_alignment)) } } (Err(e), _) | (_, Err(e)) => Err(e), @@ -192,13 +188,12 @@ impl TypeInfo { const fn dummy() -> Self { TypeInfo { flags: TypeFlags::empty(), - uniform_layout: Ok(None), - storage_layout: Ok(None), + uniform_layout: Ok(Alignment::ONE), + storage_layout: Ok(Alignment::ONE), } } - const fn new(flags: TypeFlags, align: u32) -> Self { - let alignment = Alignment::new(align); + const fn new(flags: TypeFlags, alignment: Alignment) -> Self { TypeInfo { flags, uniform_layout: Ok(alignment), @@ -248,7 +243,7 @@ impl super::Validator { | TypeFlags::ARGUMENT | TypeFlags::CONSTRUCTIBLE | shareable, - width as u32, + Alignment::from_width(width), ) } Ti::Vector { size, kind, width } => { @@ -260,7 +255,6 @@ impl super::Validator { } else { TypeFlags::empty() }; - let count = if size >= crate::VectorSize::Tri { 4 } else { 2 }; TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED @@ -269,7 +263,7 @@ impl super::Validator { | TypeFlags::ARGUMENT | TypeFlags::CONSTRUCTIBLE | shareable, - count * (width as u32), + Alignment::from(size) * Alignment::from_width(width), ) } Ti::Matrix { @@ -280,7 +274,6 @@ impl super::Validator { if !self.check_width(crate::ScalarKind::Float, width) { return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); } - let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 }; TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED @@ -288,7 +281,7 @@ impl super::Validator { | TypeFlags::HOST_SHAREABLE | TypeFlags::ARGUMENT | TypeFlags::CONSTRUCTIBLE, - count * (width as u32), + Alignment::from(rows) * Alignment::from_width(width), ) } Ti::Atomic { kind, width } => { @@ -301,7 +294,7 @@ impl super::Validator { } TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHAREABLE, - width as u32, + Alignment::from_width(width), ) } Ti::Pointer { base, space } => { @@ -344,7 +337,10 @@ impl super::Validator { // Pointers cannot be stored in variables, structure members, or // array elements, so we do not mark them as `DATA`. - TypeInfo::new(argument_flag | TypeFlags::SIZED | TypeFlags::COPY, 0) + TypeInfo::new( + argument_flag | TypeFlags::SIZED | TypeFlags::COPY, + Alignment::ONE, + ) } Ti::ValuePointer { size: _, @@ -371,7 +367,10 @@ impl super::Validator { // Pointers cannot be stored in variables, structure members, or // array elements, so we do not mark them as `DATA`. - TypeInfo::new(argument_flag | TypeFlags::SIZED | TypeFlags::COPY, 0) + TypeInfo::new( + argument_flag | TypeFlags::SIZED | TypeFlags::COPY, + Alignment::ONE, + ) } Ti::Array { base, size, stride } => { if base >= handle { @@ -391,42 +390,27 @@ impl super::Validator { }); } - let general_alignment = base_layout.alignment.get(); + let general_alignment = base_layout.alignment; let uniform_layout = match base_info.uniform_layout { Ok(base_alignment) => { - // combine the alignment requirements - let align = base_alignment - .unwrap() - .get() + let alignment = base_alignment .max(general_alignment) - .max(UNIFORM_MIN_ALIGNMENT.get()); - if stride % align != 0 { - Err(( - handle, - Disalignment::ArrayStride { - stride, - alignment: align, - }, - )) + .max(Alignment::MIN_UNIFORM); + if alignment.is_aligned(stride) { + Ok(alignment) } else { - Ok(Alignment::new(align)) + Err((handle, Disalignment::ArrayStride { stride, alignment })) } } Err(e) => Err(e), }; let storage_layout = match base_info.storage_layout { Ok(base_alignment) => { - let align = base_alignment.unwrap().get().max(general_alignment); - if stride % align != 0 { - Err(( - handle, - Disalignment::ArrayStride { - stride, - alignment: align, - }, - )) + let alignment = base_alignment.max(general_alignment); + if alignment.is_aligned(stride) { + Ok(alignment) } else { - Ok(Alignment::new(align)) + Err((handle, Disalignment::ArrayStride { stride, alignment })) } } Err(e) => Err(e), @@ -509,9 +493,9 @@ impl super::Validator { | TypeFlags::IO_SHAREABLE | TypeFlags::ARGUMENT | TypeFlags::CONSTRUCTIBLE, - 1, + Alignment::ONE, ); - ti.uniform_layout = Ok(Some(UNIFORM_MIN_ALIGNMENT)); + ti.uniform_layout = Ok(Alignment::MIN_UNIFORM); let mut min_offset = 0; @@ -536,7 +520,7 @@ impl super::Validator { ti.flags &= base_info.flags; if member.offset < min_offset { - //HACK: this could be nicer. We want to allow some structures + // HACK: this could be nicer. We want to allow some structures // to not bother with offsets/alignments if they are never // used for host sharing. if member.offset == 0 { @@ -549,7 +533,6 @@ impl super::Validator { } } - //Note: `unwrap()` is fine because `Layouter` goes first and checks this let base_size = types[member.ty].inner.size(constants); min_offset = member.offset + base_size; if min_offset > span { @@ -581,7 +564,7 @@ impl super::Validator { // the start of any following member must be at least roundUp(16, SizeOf(S)). if let Some((span, offset)) = prev_struct_data { let diff = member.offset - offset; - let min = crate::valid::Layouter::round_up(UNIFORM_MIN_ALIGNMENT, span); + let min = Alignment::MIN_UNIFORM.round_up(span); if diff < min { ti.uniform_layout = Err(( handle, @@ -616,16 +599,18 @@ impl super::Validator { } } - let alignment = self.layouter[handle].alignment.get(); - if span % alignment != 0 { + let alignment = self.layouter[handle].alignment; + if !alignment.is_aligned(span) { ti.uniform_layout = Err((handle, Disalignment::StructSpan { span, alignment })); ti.storage_layout = Err((handle, Disalignment::StructSpan { span, alignment })); } ti } - Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::new(TypeFlags::ARGUMENT, 0), - Ti::BindingArray { .. } => TypeInfo::new(TypeFlags::empty(), 0), + Ti::Image { .. } | Ti::Sampler { .. } => { + TypeInfo::new(TypeFlags::ARGUMENT, Alignment::ONE) + } + Ti::BindingArray { .. } => TypeInfo::new(TypeFlags::empty(), Alignment::ONE), }) } } From 531d563f0eb18f647f066f700f28775722b76ff0 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 9 Jun 2022 16:27:51 +0200 Subject: [PATCH 1790/2212] [wgsl-in] implement complete validation for size and align attributes --- src/front/wgsl/mod.rs | 75 +++++++++++++++++++++++++++++++---------- src/front/wgsl/tests.rs | 2 +- src/proc/layouter.rs | 26 -------------- tests/wgsl-errors.rs | 34 ++++++++++++++----- 4 files changed, 85 insertions(+), 52 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 8dd28e047..8c4f24578 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -34,7 +34,6 @@ use std::{ borrow::Cow, convert::TryFrom, io::{self, Write}, - num::NonZeroU32, ops, }; use thiserror::Error; @@ -140,7 +139,9 @@ pub enum Error<'a> { UnknownType(Span), UnknownStorageFormat(Span), UnknownConservativeDepth(Span), - ZeroSizeOrAlign(Span), + SizeAttributeTooLow(Span, u32), + AlignAttributeTooLow(Span, Alignment), + NonPowerOfTwoAlignAttribute(Span), InconsistentBinding(Span), UnknownLocalFunction(Span), TypeNotConstructible(Span), @@ -366,9 +367,19 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "unknown type".into())], notes: vec![], }, - Error::ZeroSizeOrAlign(ref bad_span) => ParseError { - message: "struct member size or alignment must not be 0".to_string(), - labels: vec![(bad_span.clone(), "struct member size or alignment must not be 0".into())], + Error::SizeAttributeTooLow(ref bad_span, min_size) => ParseError { + message: format!("struct member size must be at least {}", min_size), + labels: vec![(bad_span.clone(), format!("must be at least {}", min_size).into())], + notes: vec![], + }, + Error::AlignAttributeTooLow(ref bad_span, min_align) => ParseError { + message: format!("struct member alignment must be at least {}", min_align), + labels: vec![(bad_span.clone(), format!("must be at least {}", min_align).into())], + notes: vec![], + }, + Error::NonPowerOfTwoAlignAttribute(ref bad_span) => ParseError { + message: "struct member alignment must be a power of 2".to_string(), + labels: vec![(bad_span.clone(), "must be a power of 2".into())], notes: vec![], }, Error::InconsistentBinding(ref span) => ParseError { @@ -2787,7 +2798,7 @@ impl Parser { const_arena: &mut Arena, ) -> Result<(Vec, u32), Error<'a>> { let mut offset = 0; - let mut alignment = Alignment::new(1).unwrap(); + let mut struct_alignment = Alignment::ONE; let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; @@ -2799,7 +2810,7 @@ impl Parser { ExpectedToken::Token(Token::Separator(',')), )); } - let (mut size, mut align) = (None, None); + let (mut size_attr, mut align_attr) = (None, None); self.push_scope(Scope::Attribute, lexer); let mut bind_parser = BindingParser::default(); while lexer.skip(Token::Attribute) { @@ -2809,20 +2820,22 @@ impl Parser { let (value, span) = lexer.capture_span(Self::parse_non_negative_i32_literal)?; lexer.expect(Token::Paren(')'))?; - size = Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign(span))?); + size_attr = Some((value, span)); } ("align", _) => { lexer.expect(Token::Paren('('))?; let (value, span) = lexer.capture_span(Self::parse_non_negative_i32_literal)?; lexer.expect(Token::Paren(')'))?; - align = Some(Alignment::new(value).ok_or(Error::ZeroSizeOrAlign(span))?); + align_attr = Some((value, span)); } (word, word_span) => bind_parser.parse(lexer, word, word_span)?, } } let bind_span = self.pop_scope(lexer); + let mut binding = bind_parser.finish(bind_span)?; + let (name, span) = match lexer.next() { (Token::Word(word), span) => (word, span), other => return Err(Error::Unexpected(other, ExpectedToken::FieldName)), @@ -2831,29 +2844,57 @@ impl Parser { return Err(Error::ReservedKeyword(span)); } lexer.expect(Token::Separator(':'))?; - let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let (ty, _) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; ready = lexer.skip(Token::Separator(',')); self.layouter.update(type_arena, const_arena).unwrap(); - let (range, align) = self.layouter.member_placement(offset, ty, align, size); - alignment = alignment.max(align); - offset = range.end; + let member_min_size = self.layouter[ty].size; + let member_min_alignment = self.layouter[ty].alignment; + + let member_size = if let Some((size, span)) = size_attr { + if size < member_min_size { + return Err(Error::SizeAttributeTooLow(span, member_min_size)); + } else { + size + } + } else { + member_min_size + }; + + let member_alignment = if let Some((align, span)) = align_attr { + if let Some(alignment) = Alignment::new(align) { + if alignment < member_min_alignment { + return Err(Error::AlignAttributeTooLow(span, member_min_alignment)); + } else { + alignment + } + } else { + return Err(Error::NonPowerOfTwoAlignAttribute(span)); + } + } else { + member_min_alignment + }; + + offset = member_alignment.round_up(offset); + struct_alignment = struct_alignment.max(member_alignment); - let mut binding = bind_parser.finish(bind_span)?; if let Some(ref mut binding) = binding { binding.apply_default_interpolation(&type_arena[ty].inner); } + members.push(crate::StructMember { name: Some(name.to_owned()), ty, binding, - offset: range.start, + offset, }); + + offset += member_size; } - let span = alignment.round_up(offset); - Ok((members, span)) + let struct_size = struct_alignment.round_up(offset); + Ok((members, struct_size)) } fn parse_matrix_scalar_type<'a>( diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 8c5604ecc..33fc541ac 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -91,7 +91,7 @@ fn parse_struct() { struct Bar { @size(16) x: vec2, @align(16) y: f32, - @size(32) @align(8) z: vec3, + @size(32) @align(128) z: vec3, }; struct Empty {} var s: Foo; diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 4bfb7ec05..562c681f5 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -151,32 +151,6 @@ impl Layouter { self.layouts.clear(); } - /// Return the offset and span of a struct member. - /// - /// The member must fall at or after `offset`. The member's alignment and - /// size are `align` and `size` if given, defaulting to the values this - /// `Layouter` has previously determined for `ty`. - /// - /// The return value is the range of offsets within the containing struct to - /// reserve for this member, along with the alignment used. The containing - /// struct must have sufficient space and alignment to accommodate these. - pub fn member_placement( - &self, - offset: u32, - ty: Handle, - align: Option, - size: Option, - ) -> (ops::Range, Alignment) { - let layout = self.layouts[ty.index()]; - let alignment = align.unwrap_or(layout.alignment); - let start = alignment.round_up(offset); - let span = match size { - Some(size) => size.get(), - None => layout.size, - }; - (start..start + span, alignment) - } - /// Extend this `Layouter` with layouts for any new entries in `types`. /// /// Ensure that every type in `types` has a corresponding [TypeLayout] in diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 74f9b621f..564958f81 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -428,36 +428,54 @@ fn unknown_conservative_depth() { } #[test] -fn struct_member_zero_size() { +fn struct_member_size_too_low() { check( r#" struct Bar { @size(0) data: array } "#, - r#"error: struct member size or alignment must not be 0 + r#"error: struct member size must be at least 4 ┌─ wgsl:3:23 │ 3 │ @size(0) data: array - │ ^ struct member size or alignment must not be 0 + │ ^ must be at least 4 "#, ); } #[test] -fn struct_member_zero_align() { +fn struct_member_align_too_low() { check( r#" struct Bar { - @align(0) data: array + @align(8) data: vec3 } "#, - r#"error: struct member size or alignment must not be 0 + r#"error: struct member alignment must be at least 16 ┌─ wgsl:3:24 │ -3 │ @align(0) data: array - │ ^ struct member size or alignment must not be 0 +3 │ @align(8) data: vec3 + │ ^ must be at least 16 + +"#, + ); +} + +#[test] +fn struct_member_non_po2_align() { + check( + r#" + struct Bar { + @align(7) data: array + } + "#, + r#"error: struct member alignment must be a power of 2 + ┌─ wgsl:3:24 + │ +3 │ @align(7) data: array + │ ^ must be a power of 2 "#, ); From ad536ce0dfd5c9cc92ebf623ce44432cd9e68c0e Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 9 Jun 2022 16:31:12 +0200 Subject: [PATCH 1791/2212] [wgsl-in] remove unused code --- src/front/wgsl/construction.rs | 4 +--- src/front/wgsl/mod.rs | 36 ++++++++++++++++------------------ 2 files changed, 18 insertions(+), 22 deletions(-) diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/construction.rs index ca43894e2..7039bb5dd 100644 --- a/src/front/wgsl/construction.rs +++ b/src/front/wgsl/construction.rs @@ -196,9 +196,7 @@ fn parse_constructor_type<'a>( } (Token::Paren('<'), ConstructorType::PartialArray) => { lexer.expect_generic_paren('<')?; - let base = parser - .parse_type_decl(lexer, None, type_arena, const_arena)? - .0; + let base = parser.parse_type_decl(lexer, None, type_arena, const_arena)?; let size = if lexer.skip(Token::Separator(',')) { let const_handle = parser.parse_const_expression(lexer, type_arena, const_arena)?; ArraySize::Constant(const_handle) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 8c4f24578..f0e6ac51c 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1569,7 +1569,7 @@ impl Parser { "bitcast" => { let _ = lexer.next(); lexer.expect_generic_paren('<')?; - let ((ty, _access), type_span) = lexer.capture_span(|lexer| { + let (ty, type_span) = lexer.capture_span(|lexer| { self.parse_type_decl(lexer, None, ctx.types, ctx.constants) })?; lexer.expect_generic_paren('>')?; @@ -2738,11 +2738,11 @@ impl Parser { lexer: &mut Lexer<'a>, type_arena: &mut UniqueArena, const_arena: &mut Arena, - ) -> Result<(&'a str, Span, Handle, crate::StorageAccess), Error<'a>> { + ) -> Result<(&'a str, Span, Handle), Error<'a>> { let (name, name_span) = lexer.next_ident_with_span()?; lexer.expect(Token::Separator(':'))?; - let (ty, access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; - Ok((name, name_span, ty, access)) + let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + Ok((name, name_span, ty)) } fn parse_variable_decl<'a>( @@ -2772,7 +2772,7 @@ impl Parser { } let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let init = if lexer.skip(Token::Operation('=')) { let handle = self.parse_const_expression(lexer, type_arena, const_arena)?; @@ -2844,7 +2844,7 @@ impl Parser { return Err(Error::ReservedKeyword(span)); } lexer.expect(Token::Separator(':'))?; - let (ty, _) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; ready = lexer.skip(Token::Separator(',')); self.layouter.update(type_arena, const_arena).unwrap(); @@ -2999,7 +2999,7 @@ impl Parser { let (ident, span) = lexer.next_ident_with_span()?; let mut space = conv::map_address_space(ident, span)?; lexer.expect(Token::Separator(','))?; - let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; if let crate::AddressSpace::Storage { ref mut access } = space { *access = if lexer.skip(Token::Separator(',')) { lexer.next_storage_access()? @@ -3012,7 +3012,7 @@ impl Parser { } "array" => { lexer.expect_generic_paren('<')?; - let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let size = if lexer.skip(Token::Separator(',')) { let const_handle = self.parse_const_expression(lexer, type_arena, const_arena)?; @@ -3030,7 +3030,7 @@ impl Parser { } "binding_array" => { lexer.expect_generic_paren('<')?; - let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; let size = if lexer.skip(Token::Separator(',')) { let const_handle = self.parse_const_expression(lexer, type_arena, const_arena)?; @@ -3245,7 +3245,7 @@ impl Parser { debug_name: Option<&'a str>, type_arena: &mut UniqueArena, const_arena: &mut Arena, - ) -> Result<(Handle, crate::StorageAccess), Error<'a>> { + ) -> Result, Error<'a>> { self.push_scope(Scope::TypeDecl, lexer); let attribute = TypeAttributes::default(); @@ -3254,7 +3254,6 @@ impl Parser { return Err(Error::Unexpected(other, ExpectedToken::TypeAttribute)); } - let storage_access = crate::StorageAccess::default(); let (name, name_span) = lexer.next_ident_with_span()?; let handle = self.parse_type_decl_name( lexer, @@ -3269,7 +3268,7 @@ impl Parser { // Only set span if it's the first occurrence of the type. // Type spans therefore should only be used for errors in type declarations; // use variable spans/expression spans/etc. otherwise - Ok((handle, storage_access)) + Ok(handle) } /// Parse an assignment statement (will also parse increment and decrement statements) @@ -3497,7 +3496,7 @@ impl Parser { return Err(Error::ReservedKeyword(name_span)); } let given_ty = if lexer.skip(Token::Separator(':')) { - let (ty, _access) = self.parse_type_decl( + let ty = self.parse_type_decl( lexer, None, context.types, @@ -3558,7 +3557,7 @@ impl Parser { return Err(Error::ReservedKeyword(name_span)); } let given_ty = if lexer.skip(Token::Separator(':')) { - let (ty, _access) = self.parse_type_decl( + let ty = self.parse_type_decl( lexer, None, context.types, @@ -4133,7 +4132,7 @@ impl Parser { )); } let mut binding = self.parse_varying_binding(lexer)?; - let (param_name, param_name_span, param_type, _access) = + let (param_name, param_name_span, param_type) = self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; if crate::keywords::wgsl::RESERVED.contains(¶m_name) { return Err(Error::ReservedKeyword(param_name_span)); @@ -4163,8 +4162,7 @@ impl Parser { // read return type let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { let mut binding = self.parse_varying_binding(lexer)?; - let (ty, _access) = - self.parse_type_decl(lexer, None, &mut module.types, &mut module.constants)?; + let ty = self.parse_type_decl(lexer, None, &mut module.types, &mut module.constants)?; if let Some(ref mut binding) = binding { binding.apply_default_interpolation(&module.types[ty].inner); } @@ -4317,7 +4315,7 @@ impl Parser { (Token::Word("type"), _) => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; - let (ty, _access) = self.parse_type_decl( + let ty = self.parse_type_decl( lexer, Some(name), &mut module.types, @@ -4341,7 +4339,7 @@ impl Parser { }); } let given_ty = if lexer.skip(Token::Separator(':')) { - let (ty, _access) = self.parse_type_decl( + let ty = self.parse_type_decl( lexer, None, &mut module.types, From 0b60f410ab7bd0ca0d67d024c8b5da84b55fbf18 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 16 Jun 2022 16:09:17 -0700 Subject: [PATCH 1792/2212] [wgsl-in] Restore error in the case of bad scalar widths. --- src/proc/layouter.rs | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 562c681f5..0c3a00db1 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -128,6 +128,8 @@ pub enum LayoutErrorInner { InvalidArrayElementType(Handle), #[error("Struct member[{0}] type {1:?} doesn't exist")] InvalidStructMemberType(u32, Handle), + #[error("Type width must be a power of two")] + NonPowerOfTwoWidth, #[error("Array size is a bad handle")] BadHandle(#[from] BadHandle), } @@ -178,26 +180,35 @@ impl Layouter { .try_size(constants) .map_err(|error| LayoutErrorInner::BadHandle(error).with(ty_handle))?; let layout = match ty.inner { - Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => TypeLayout { - size, - alignment: Alignment::from_width(width), - }, + Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => { + let alignment = Alignment::new(width as u32) + .ok_or(LayoutErrorInner::NonPowerOfTwoWidth.with(ty_handle))?; + TypeLayout { size, alignment } + } Ti::Vector { size: vec_size, width, .. - } => TypeLayout { - size, - alignment: { Alignment::from(vec_size) * Alignment::from_width(width) }, - }, + } => { + let alignment = Alignment::new(width as u32) + .ok_or(LayoutErrorInner::NonPowerOfTwoWidth.with(ty_handle))?; + TypeLayout { + size, + alignment: Alignment::from(vec_size) * alignment, + } + } Ti::Matrix { columns: _, rows, width, - } => TypeLayout { - size, - alignment: { Alignment::from(rows) * Alignment::from_width(width) }, - }, + } => { + let alignment = Alignment::new(width as u32) + .ok_or(LayoutErrorInner::NonPowerOfTwoWidth.with(ty_handle))?; + TypeLayout { + size, + alignment: Alignment::from(rows) * alignment, + } + } Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout { size, alignment: Alignment::ONE, From 89f24b6cfe4f7c25c4c5890a5e15e5e479094189 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 17 Jun 2022 10:50:09 +0200 Subject: [PATCH 1793/2212] [msl-out] insert padding initialization for global constants --- src/back/msl/writer.rs | 6 + tests/in/access.wgsl | 8 + .../access.assign_through_ptr.Compute.glsl | 9 +- tests/out/glsl/access.atomics.Compute.glsl | 41 +- tests/out/glsl/access.foo_frag.Fragment.glsl | 11 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 59 +- tests/out/hlsl/access.hlsl | 102 +-- tests/out/msl/access.msl | 134 ++-- tests/out/spv/access.spvasm | 702 +++++++++--------- tests/out/wgsl/access.wgsl | 91 +-- 10 files changed, 622 insertions(+), 541 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 1f85c4d0a..3992b6374 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -364,6 +364,8 @@ pub struct Writer { put_expression_stack_pointers: FastHashSet<*const ()>, #[cfg(test)] put_block_stack_pointers: FastHashSet<*const ()>, + /// Set of (struct type, struct field index) denoting which fields require + /// padding inserted **before** them (i.e. between fields at index - 1 and index) struct_member_pads: FastHashSet<(Handle, u32)>, } @@ -3092,6 +3094,10 @@ impl Writer { }; write!(self.out, "constant {} {} = {{", ty_name, name,)?; for (i, &sub_handle) in components.iter().enumerate() { + // insert padding initialization, if needed + if self.struct_member_pads.contains(&(ty, i as u32)) { + write!(self.out, ", {{}}")?; + } let separator = if i != 0 { ", " } else { "" }; let coco = ConstantContext { handle: sub_handle, diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index a9034df91..456aee4b3 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -1,5 +1,13 @@ // This snapshot tests accessing various containers, dereferencing pointers. +struct GlobalConst { + a: u32, + b: vec3, + c: i32, +} +// tests msl padding insertion for global constants +var global_const: GlobalConst = GlobalConst(0u, vec3(0u, 0u, 0u), 0); + struct AlignedWrapper { @align(8) value: i32 } diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/tests/out/glsl/access.assign_through_ptr.Compute.glsl index f90e0f015..34b989a0f 100644 --- a/tests/out/glsl/access.assign_through_ptr.Compute.glsl +++ b/tests/out/glsl/access.assign_through_ptr.Compute.glsl @@ -5,6 +5,11 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +struct GlobalConst { + uint a; + uvec3 b; + int c; +}; struct AlignedWrapper { int value; }; @@ -15,8 +20,8 @@ shared uint val; float read_from_private(inout float foo_1) { - float _e4 = foo_1; - return _e4; + float _e5 = foo_1; + return _e5; } float test_arr_as_arg(float a[5][10]) { diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 8485b1628..83e7e1e78 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -5,6 +5,11 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +struct GlobalConst { + uint a; + uvec3 b; + int c; +}; struct AlignedWrapper { int value; }; @@ -21,8 +26,8 @@ layout(std430) buffer Bar_block_0Compute { float read_from_private(inout float foo_1) { - float _e4 = foo_1; - return _e4; + float _e5 = foo_1; + return _e5; } float test_arr_as_arg(float a[5][10]) { @@ -37,22 +42,22 @@ void assign_through_ptr_fn(inout uint p) { void main() { int tmp = 0; int value = _group_0_binding_0_cs.atom; - int _e8 = atomicAdd(_group_0_binding_0_cs.atom, 5); - tmp = _e8; - int _e11 = atomicAdd(_group_0_binding_0_cs.atom, -5); - tmp = _e11; - int _e14 = atomicAnd(_group_0_binding_0_cs.atom, 5); - tmp = _e14; - int _e17 = atomicOr(_group_0_binding_0_cs.atom, 5); - tmp = _e17; - int _e20 = atomicXor(_group_0_binding_0_cs.atom, 5); - tmp = _e20; - int _e23 = atomicMin(_group_0_binding_0_cs.atom, 5); - tmp = _e23; - int _e26 = atomicMax(_group_0_binding_0_cs.atom, 5); - tmp = _e26; - int _e29 = atomicExchange(_group_0_binding_0_cs.atom, 5); - tmp = _e29; + int _e9 = atomicAdd(_group_0_binding_0_cs.atom, 5); + tmp = _e9; + int _e12 = atomicAdd(_group_0_binding_0_cs.atom, -5); + tmp = _e12; + int _e15 = atomicAnd(_group_0_binding_0_cs.atom, 5); + tmp = _e15; + int _e18 = atomicOr(_group_0_binding_0_cs.atom, 5); + tmp = _e18; + int _e21 = atomicXor(_group_0_binding_0_cs.atom, 5); + tmp = _e21; + int _e24 = atomicMin(_group_0_binding_0_cs.atom, 5); + tmp = _e24; + int _e27 = atomicMax(_group_0_binding_0_cs.atom, 5); + tmp = _e27; + int _e30 = atomicExchange(_group_0_binding_0_cs.atom, 5); + tmp = _e30; _group_0_binding_0_cs.atom = value; return; } diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index 189702c5d..36c8fb2a4 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -3,6 +3,11 @@ precision highp float; precision highp int; +struct GlobalConst { + uint a; + uvec3 b; + int c; +}; struct AlignedWrapper { int value; }; @@ -17,13 +22,13 @@ layout(std430) buffer Bar_block_0Fragment { AlignedWrapper data[]; } _group_0_binding_0_fs; -layout(std430) buffer type_9_block_1Fragment { ivec2 _group_0_binding_2_fs; }; +layout(std430) buffer type_11_block_1Fragment { ivec2 _group_0_binding_2_fs; }; layout(location = 0) out vec4 _fs2p_location0; float read_from_private(inout float foo_1) { - float _e4 = foo_1; - return _e4; + float _e5 = foo_1; + return _e5; } float test_arr_as_arg(float a[5][10]) { diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index 5f6c0f10b..cd3a65ac0 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -3,6 +3,11 @@ precision highp float; precision highp int; +struct GlobalConst { + uint a; + uvec3 b; + int c; +}; struct AlignedWrapper { int value; }; @@ -19,47 +24,47 @@ layout(std430) buffer Bar_block_0Vertex { uniform Baz_block_1Vertex { Baz _group_0_binding_1_vs; }; -layout(std430) buffer type_9_block_2Vertex { ivec2 _group_0_binding_2_vs; }; +layout(std430) buffer type_11_block_2Vertex { ivec2 _group_0_binding_2_vs; }; void test_matrix_within_struct_accesses() { int idx = 1; Baz t = Baz(mat3x2(0.0)); - int _e5 = idx; - idx = (_e5 - 1); + int _e6 = idx; + idx = (_e6 - 1); mat3x2 unnamed = _group_0_binding_1_vs.m; vec2 unnamed_1 = _group_0_binding_1_vs.m[0]; - int _e15 = idx; - vec2 unnamed_2 = _group_0_binding_1_vs.m[_e15]; + int _e16 = idx; + vec2 unnamed_2 = _group_0_binding_1_vs.m[_e16]; float unnamed_3 = _group_0_binding_1_vs.m[0][1]; - int _e27 = idx; - float unnamed_4 = _group_0_binding_1_vs.m[0][_e27]; - int _e31 = idx; - float unnamed_5 = _group_0_binding_1_vs.m[_e31][1]; - int _e37 = idx; - int _e39 = idx; - float unnamed_6 = _group_0_binding_1_vs.m[_e37][_e39]; + int _e28 = idx; + float unnamed_4 = _group_0_binding_1_vs.m[0][_e28]; + int _e32 = idx; + float unnamed_5 = _group_0_binding_1_vs.m[_e32][1]; + int _e38 = idx; + int _e40 = idx; + float unnamed_6 = _group_0_binding_1_vs.m[_e38][_e40]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - int _e51 = idx; - idx = (_e51 + 1); + int _e52 = idx; + idx = (_e52 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - int _e68 = idx; - t.m[_e68] = vec2(90.0); + int _e69 = idx; + t.m[_e69] = vec2(90.0); t.m[0][1] = 10.0; - int _e81 = idx; - t.m[0][_e81] = 20.0; - int _e85 = idx; - t.m[_e85][1] = 30.0; - int _e91 = idx; - int _e93 = idx; - t.m[_e91][_e93] = 40.0; + int _e82 = idx; + t.m[0][_e82] = 20.0; + int _e86 = idx; + t.m[_e86][1] = 30.0; + int _e92 = idx; + int _e94 = idx; + t.m[_e92][_e94] = 40.0; return; } float read_from_private(inout float foo_1) { - float _e4 = foo_1; - return _e4; + float _e5 = foo_1; + return _e5; } float test_arr_as_arg(float a[5][10]) { @@ -83,11 +88,11 @@ void main() { float b = _group_0_binding_0_vs._matrix[3][0]; int a_1 = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; ivec2 c_1 = _group_0_binding_2_vs; - float _e30 = read_from_private(foo); + float _e31 = read_from_private(foo); c = int[5](a_1, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; - float _e44 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + float _e45 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); gl_Position = vec4((_matrix * vec4(ivec4(value))), 2.0); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 1427bb20a..5f264572d 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -1,4 +1,13 @@ +struct GlobalConst { + uint a; + int _pad1_0; + int _pad1_1; + int _pad1_2; + uint3 b; + int c; +}; + struct AlignedWrapper { int value; int _end_pad_0; @@ -8,6 +17,14 @@ struct Baz { float2 m_0; float2 m_1; float2 m_2; }; +GlobalConst ConstructGlobalConst(uint arg0, uint3 arg1, int arg2) { + GlobalConst ret = (GlobalConst)0; + ret.a = arg0; + ret.b = arg1; + ret.c = arg2; + return ret; +} + typedef float ret_Constructarray10_float_[10]; ret_Constructarray10_float_ Constructarray10_float_(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5, float arg6, float arg7, float arg8, float arg9) { float ret[10] = { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 }; @@ -20,6 +37,7 @@ ret_Constructarray5_array10_float__ Constructarray5_array10_float__(float arg0[1 return ret; } +static GlobalConst global_const = ConstructGlobalConst(0u, uint3(0u, 0u, 0u), 0); RWByteAddressBuffer bar : register(u0); cbuffer baz : register(b1) { Baz baz; } RWByteAddressBuffer qux : register(u2); @@ -64,42 +82,42 @@ void test_matrix_within_struct_accesses() int idx = 1; Baz t = (Baz)0; - int _expr5 = idx; - idx = (_expr5 - 1); + int _expr6 = idx; + idx = (_expr6 - 1); float3x2 unnamed = GetMatmOnBaz(baz); float2 unnamed_1 = GetMatmOnBaz(baz)[0]; - int _expr15 = idx; - float2 unnamed_2 = GetMatmOnBaz(baz)[_expr15]; + int _expr16 = idx; + float2 unnamed_2 = GetMatmOnBaz(baz)[_expr16]; float unnamed_3 = GetMatmOnBaz(baz)[0][1]; - int _expr27 = idx; - float unnamed_4 = GetMatmOnBaz(baz)[0][_expr27]; - int _expr31 = idx; - float unnamed_5 = GetMatmOnBaz(baz)[_expr31][1]; - int _expr37 = idx; - int _expr39 = idx; - float unnamed_6 = GetMatmOnBaz(baz)[_expr37][_expr39]; + int _expr28 = idx; + float unnamed_4 = GetMatmOnBaz(baz)[0][_expr28]; + int _expr32 = idx; + float unnamed_5 = GetMatmOnBaz(baz)[_expr32][1]; + int _expr38 = idx; + int _expr40 = idx; + float unnamed_6 = GetMatmOnBaz(baz)[_expr38][_expr40]; t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); - int _expr51 = idx; - idx = (_expr51 + 1); + int _expr52 = idx; + idx = (_expr52 + 1); SetMatmOnBaz(t, float3x2((6.0).xx, (5.0).xx, (4.0).xx)); t.m_0 = (9.0).xx; - int _expr68 = idx; - SetMatVecmOnBaz(t, (90.0).xx, _expr68); + int _expr69 = idx; + SetMatVecmOnBaz(t, (90.0).xx, _expr69); t.m_0[1] = 10.0; - int _expr81 = idx; - t.m_0[_expr81] = 20.0; - int _expr85 = idx; - SetMatScalarmOnBaz(t, 30.0, _expr85, 1); - int _expr91 = idx; - int _expr93 = idx; - SetMatScalarmOnBaz(t, 40.0, _expr91, _expr93); + int _expr82 = idx; + t.m_0[_expr82] = 20.0; + int _expr86 = idx; + SetMatScalarmOnBaz(t, 30.0, _expr86, 1); + int _expr92 = idx; + int _expr94 = idx; + SetMatScalarmOnBaz(t, 40.0, _expr92, _expr94); return; } float read_from_private(inout float foo_1) { - float _expr4 = foo_1; - return _expr4; + float _expr5 = foo_1; + return _expr5; } float test_arr_as_arg(float a[5][10]) @@ -139,14 +157,14 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position float b = asfloat(bar.Load(0+48+0)); int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); int2 c_1 = asint(qux.Load2(0)); - const float _e30 = read_from_private(foo); + const float _e31 = read_from_private(foo); { int _result[5]=Constructarray5_int_(a_1, int(b), 3, 4, 5); for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; } c[(vi + 1u)] = 42; int value = c[vi]; - const float _e44 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + const float _e45 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); return float4(mul(float4((value).xxxx), _matrix), 2.0); } @@ -182,22 +200,22 @@ void atomics() int tmp = (int)0; int value_1 = asint(bar.Load(96)); - int _e8; bar.InterlockedAdd(96, 5, _e8); - tmp = _e8; - int _e11; bar.InterlockedAdd(96, -5, _e11); - tmp = _e11; - int _e14; bar.InterlockedAnd(96, 5, _e14); - tmp = _e14; - int _e17; bar.InterlockedOr(96, 5, _e17); - tmp = _e17; - int _e20; bar.InterlockedXor(96, 5, _e20); - tmp = _e20; - int _e23; bar.InterlockedMin(96, 5, _e23); - tmp = _e23; - int _e26; bar.InterlockedMax(96, 5, _e26); - tmp = _e26; - int _e29; bar.InterlockedExchange(96, 5, _e29); - tmp = _e29; + int _e9; bar.InterlockedAdd(96, 5, _e9); + tmp = _e9; + int _e12; bar.InterlockedAdd(96, -5, _e12); + tmp = _e12; + int _e15; bar.InterlockedAnd(96, 5, _e15); + tmp = _e15; + int _e18; bar.InterlockedOr(96, 5, _e18); + tmp = _e18; + int _e21; bar.InterlockedXor(96, 5, _e21); + tmp = _e21; + int _e24; bar.InterlockedMin(96, 5, _e24); + tmp = _e24; + int _e27; bar.InterlockedMax(96, 5, _e27); + tmp = _e27; + int _e30; bar.InterlockedExchange(96, 5, _e30); + tmp = _e30; bar.Store(96, asuint(value_1)); return; } diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 0db07ad57..ef4bf86a6 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -5,89 +5,97 @@ using metal::uint; struct _mslBufferSizes { - uint size0; + uint size1; }; +struct GlobalConst { + uint a; + char _pad1[12]; + metal::packed_uint3 b; + int c; +}; struct AlignedWrapper { int value; }; -struct type_3 { +struct type_5 { metal::float2x2 inner[2]; }; -struct type_6 { +struct type_8 { metal::uint2 inner[2]; }; -typedef AlignedWrapper type_7[1]; +typedef AlignedWrapper type_9[1]; struct Bar { metal::float4x3 _matrix; - type_3 matrix_array; + type_5 matrix_array; metal::atomic_int atom; char _pad3[4]; - type_6 arr; - type_7 data; + type_8 arr; + type_9 data; }; struct Baz { metal::float3x2 m; }; -struct type_12 { +struct type_14 { float inner[10]; }; -struct type_13 { - type_12 inner[5]; +struct type_15 { + type_14 inner[5]; }; -struct type_17 { +struct type_18 { int inner[5]; }; -constant type_12 const_type_12_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; -constant type_13 const_type_13_ = {const_type_12_, const_type_12_, const_type_12_, const_type_12_, const_type_12_}; -constant metal::int2 const_type_9_ = {0, 0}; +constant metal::uint3 const_type_1_ = {0u, 0u, 0u}; +constant GlobalConst const_GlobalConst = {0u, {}, const_type_1_, 0}; +constant type_14 const_type_14_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; +constant type_15 const_type_15_ = {const_type_14_, const_type_14_, const_type_14_, const_type_14_, const_type_14_}; +constant metal::int2 const_type_11_ = {0, 0}; void test_matrix_within_struct_accesses( constant Baz& baz ) { int idx = 1; Baz t = {}; - int _e5 = idx; - idx = _e5 - 1; + int _e6 = idx; + idx = _e6 - 1; metal::float3x2 unnamed = baz.m; metal::float2 unnamed_1 = baz.m[0]; - int _e15 = idx; - metal::float2 unnamed_2 = baz.m[_e15]; + int _e16 = idx; + metal::float2 unnamed_2 = baz.m[_e16]; float unnamed_3 = baz.m[0].y; - int _e27 = idx; - float unnamed_4 = baz.m[0][_e27]; - int _e31 = idx; - float unnamed_5 = baz.m[_e31].y; - int _e37 = idx; - int _e39 = idx; - float unnamed_6 = baz.m[_e37][_e39]; + int _e28 = idx; + float unnamed_4 = baz.m[0][_e28]; + int _e32 = idx; + float unnamed_5 = baz.m[_e32].y; + int _e38 = idx; + int _e40 = idx; + float unnamed_6 = baz.m[_e38][_e40]; t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; - int _e51 = idx; - idx = _e51 + 1; + int _e52 = idx; + idx = _e52 + 1; t.m = metal::float3x2(metal::float2(6.0), metal::float2(5.0), metal::float2(4.0)); t.m[0] = metal::float2(9.0); - int _e68 = idx; - t.m[_e68] = metal::float2(90.0); + int _e69 = idx; + t.m[_e69] = metal::float2(90.0); t.m[0].y = 10.0; - int _e81 = idx; - t.m[0][_e81] = 20.0; - int _e85 = idx; - t.m[_e85].y = 30.0; - int _e91 = idx; - int _e93 = idx; - t.m[_e91][_e93] = 40.0; + int _e82 = idx; + t.m[0][_e82] = 20.0; + int _e86 = idx; + t.m[_e86].y = 30.0; + int _e92 = idx; + int _e94 = idx; + t.m[_e92][_e94] = 40.0; return; } float read_from_private( thread float& foo_1 ) { - float _e4 = foo_1; - return _e4; + float _e5 = foo_1; + return _e5; } float test_arr_as_arg( - type_13 a + type_15 a ) { return a.inner[4].inner[9]; } @@ -112,20 +120,20 @@ vertex foo_vertOutput foo_vert( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo = 0.0; - type_17 c = {}; + type_18 c = {}; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); metal::float4x3 _matrix = bar._matrix; - type_6 arr = bar.arr; + type_8 arr = bar.arr; float b = bar._matrix[3].x; - int a_1 = bar.data[(1 + (_buffer_sizes.size0 - 120 - 8) / 8) - 2u].value; + int a_1 = bar.data[(1 + (_buffer_sizes.size1 - 120 - 8) / 8) - 2u].value; metal::int2 c_1 = qux; - float _e30 = read_from_private(foo); - for(int _i=0; _i<5; ++_i) c.inner[_i] = type_17 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; + float _e31 = read_from_private(foo); + for(int _i=0; _i<5; ++_i) c.inner[_i] = type_18 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; - float _e44 = test_arr_as_arg(const_type_13_); + float _e45 = test_arr_as_arg(const_type_15_); return foo_vertOutput { metal::float4(_matrix * static_cast(metal::int4(value)), 2.0) }; } @@ -140,9 +148,9 @@ fragment foo_fragOutput foo_frag( ) { bar._matrix[1].z = 1.0; bar._matrix = metal::float4x3(metal::float3(0.0), metal::float3(1.0), metal::float3(2.0), metal::float3(3.0)); - for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_6 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; + for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_8 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; bar.data[1].value = 1; - qux = const_type_9_; + qux = const_type_11_; return foo_fragOutput { metal::float4(0.0) }; } @@ -153,22 +161,22 @@ kernel void atomics( ) { int tmp = {}; int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); - int _e8 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e8; - int _e11 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e11; - int _e14 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e14; - int _e17 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e17; - int _e20 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e20; - int _e23 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e23; - int _e26 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e26; - int _e29 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e29; + int _e9 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e9; + int _e12 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e12; + int _e15 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e15; + int _e18 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e18; + int _e21 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e21; + int _e24 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e24; + int _e27 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e27; + int _e30 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e30; metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed); return; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index b1e059bb7..218b08a74 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,374 +1,388 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 242 +; Bound: 248 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %157 "foo_vert" %152 %155 -OpEntryPoint Fragment %196 "foo_frag" %195 -OpEntryPoint GLCompute %215 "atomics" -OpEntryPoint GLCompute %239 "assign_through_ptr" -OpExecutionMode %196 OriginUpperLeft -OpExecutionMode %215 LocalSize 1 1 1 -OpExecutionMode %239 LocalSize 1 1 1 +OpEntryPoint Vertex %163 "foo_vert" %158 %161 +OpEntryPoint Fragment %202 "foo_frag" %201 +OpEntryPoint GLCompute %221 "atomics" +OpEntryPoint GLCompute %245 "assign_through_ptr" +OpExecutionMode %202 OriginUpperLeft +OpExecutionMode %221 LocalSize 1 1 1 +OpExecutionMode %245 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %33 0 "value" -OpName %33 "AlignedWrapper" -OpMemberName %42 0 "_matrix" -OpMemberName %42 1 "matrix_array" -OpMemberName %42 2 "atom" -OpMemberName %42 3 "arr" -OpMemberName %42 4 "data" -OpName %42 "Bar" -OpMemberName %44 0 "m" -OpName %44 "Baz" -OpName %56 "bar" -OpName %58 "baz" -OpName %61 "qux" -OpName %64 "val" -OpName %65 "idx" -OpName %67 "t" -OpName %71 "test_matrix_within_struct_accesses" -OpName %130 "foo" -OpName %131 "read_from_private" -OpName %136 "a" -OpName %137 "test_arr_as_arg" -OpName %143 "p" -OpName %144 "assign_through_ptr_fn" -OpName %147 "foo" -OpName %148 "c" -OpName %152 "vi" -OpName %157 "foo_vert" -OpName %196 "foo_frag" -OpName %212 "tmp" -OpName %215 "atomics" -OpName %239 "assign_through_ptr" -OpMemberDecorate %33 0 Offset 0 -OpDecorate %38 ArrayStride 16 -OpDecorate %40 ArrayStride 8 -OpDecorate %41 ArrayStride 8 -OpMemberDecorate %42 0 Offset 0 -OpMemberDecorate %42 0 ColMajor -OpMemberDecorate %42 0 MatrixStride 16 -OpMemberDecorate %42 1 Offset 64 -OpMemberDecorate %42 1 ColMajor -OpMemberDecorate %42 1 MatrixStride 8 -OpMemberDecorate %42 2 Offset 96 -OpMemberDecorate %42 3 Offset 104 -OpMemberDecorate %42 4 Offset 120 +OpMemberName %34 0 "a" +OpMemberName %34 1 "b" +OpMemberName %34 2 "c" +OpName %34 "GlobalConst" +OpMemberName %35 0 "value" +OpName %35 "AlignedWrapper" +OpMemberName %44 0 "_matrix" +OpMemberName %44 1 "matrix_array" +OpMemberName %44 2 "atom" +OpMemberName %44 3 "arr" +OpMemberName %44 4 "data" +OpName %44 "Bar" +OpMemberName %46 0 "m" +OpName %46 "Baz" +OpName %60 "global_const" +OpName %62 "bar" +OpName %64 "baz" +OpName %67 "qux" +OpName %70 "val" +OpName %71 "idx" +OpName %73 "t" +OpName %77 "test_matrix_within_struct_accesses" +OpName %136 "foo" +OpName %137 "read_from_private" +OpName %142 "a" +OpName %143 "test_arr_as_arg" +OpName %149 "p" +OpName %150 "assign_through_ptr_fn" +OpName %153 "foo" +OpName %154 "c" +OpName %158 "vi" +OpName %163 "foo_vert" +OpName %202 "foo_frag" +OpName %218 "tmp" +OpName %221 "atomics" +OpName %245 "assign_through_ptr" +OpMemberDecorate %34 0 Offset 0 +OpMemberDecorate %34 1 Offset 16 +OpMemberDecorate %34 2 Offset 28 +OpMemberDecorate %35 0 Offset 0 +OpDecorate %40 ArrayStride 16 +OpDecorate %42 ArrayStride 8 +OpDecorate %43 ArrayStride 8 OpMemberDecorate %44 0 Offset 0 OpMemberDecorate %44 0 ColMajor -OpMemberDecorate %44 0 MatrixStride 8 -OpDecorate %47 ArrayStride 4 -OpDecorate %48 ArrayStride 40 -OpDecorate %51 ArrayStride 4 -OpDecorate %56 DescriptorSet 0 -OpDecorate %56 Binding 0 -OpDecorate %42 Block -OpDecorate %58 DescriptorSet 0 -OpDecorate %58 Binding 1 -OpDecorate %59 Block -OpMemberDecorate %59 0 Offset 0 -OpDecorate %61 DescriptorSet 0 -OpDecorate %61 Binding 2 -OpDecorate %62 Block -OpMemberDecorate %62 0 Offset 0 -OpDecorate %152 BuiltIn VertexIndex -OpDecorate %155 BuiltIn Position -OpDecorate %195 Location 0 +OpMemberDecorate %44 0 MatrixStride 16 +OpMemberDecorate %44 1 Offset 64 +OpMemberDecorate %44 1 ColMajor +OpMemberDecorate %44 1 MatrixStride 8 +OpMemberDecorate %44 2 Offset 96 +OpMemberDecorate %44 3 Offset 104 +OpMemberDecorate %44 4 Offset 120 +OpMemberDecorate %46 0 Offset 0 +OpMemberDecorate %46 0 ColMajor +OpMemberDecorate %46 0 MatrixStride 8 +OpDecorate %49 ArrayStride 4 +OpDecorate %50 ArrayStride 40 +OpDecorate %53 ArrayStride 4 +OpDecorate %62 DescriptorSet 0 +OpDecorate %62 Binding 0 +OpDecorate %44 Block +OpDecorate %64 DescriptorSet 0 +OpDecorate %64 Binding 1 +OpDecorate %65 Block +OpMemberDecorate %65 0 Offset 0 +OpDecorate %67 DescriptorSet 0 +OpDecorate %67 Binding 2 +OpDecorate %68 Block +OpMemberDecorate %68 0 Offset 0 +OpDecorate %158 BuiltIn VertexIndex +OpDecorate %161 BuiltIn Position +OpDecorate %201 Location 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 2 -%5 = OpConstant %4 1 -%6 = OpConstant %4 0 -%8 = OpTypeFloat 32 -%7 = OpConstant %8 1.0 -%9 = OpConstant %8 2.0 -%10 = OpConstant %8 3.0 -%11 = OpConstant %8 6.0 -%12 = OpConstant %8 5.0 -%13 = OpConstant %8 4.0 -%14 = OpConstant %8 9.0 -%15 = OpConstant %8 90.0 -%16 = OpConstant %8 10.0 -%17 = OpConstant %8 20.0 -%18 = OpConstant %8 30.0 -%19 = OpConstant %8 40.0 -%20 = OpConstant %4 10 -%21 = OpConstant %4 5 -%22 = OpConstant %4 4 -%23 = OpConstant %4 9 -%24 = OpConstant %8 0.0 -%26 = OpTypeInt 32 0 -%25 = OpConstant %26 3 -%27 = OpConstant %26 2 -%28 = OpConstant %4 3 -%29 = OpConstant %26 1 -%30 = OpConstant %4 42 -%31 = OpConstant %26 0 -%32 = OpConstant %26 42 -%33 = OpTypeStruct %4 -%35 = OpTypeVector %8 3 -%34 = OpTypeMatrix %35 4 -%37 = OpTypeVector %8 2 -%36 = OpTypeMatrix %37 2 -%38 = OpTypeArray %36 %3 -%39 = OpTypeVector %26 2 -%40 = OpTypeArray %39 %3 -%41 = OpTypeRuntimeArray %33 -%42 = OpTypeStruct %34 %38 %4 %40 %41 -%43 = OpTypeMatrix %37 3 -%44 = OpTypeStruct %43 -%45 = OpTypeVector %4 2 -%46 = OpTypePointer Function %8 -%47 = OpTypeArray %8 %20 -%48 = OpTypeArray %47 %21 -%49 = OpTypeVector %8 4 -%50 = OpTypePointer StorageBuffer %4 -%51 = OpTypeArray %4 %21 -%52 = OpTypePointer Workgroup %26 -%53 = OpConstantComposite %47 %24 %24 %24 %24 %24 %24 %24 %24 %24 %24 -%54 = OpConstantComposite %48 %53 %53 %53 %53 %53 -%55 = OpConstantComposite %45 %6 %6 -%57 = OpTypePointer StorageBuffer %42 -%56 = OpVariable %57 StorageBuffer -%59 = OpTypeStruct %44 -%60 = OpTypePointer Uniform %59 -%58 = OpVariable %60 Uniform -%62 = OpTypeStruct %45 -%63 = OpTypePointer StorageBuffer %62 -%61 = OpVariable %63 StorageBuffer -%64 = OpVariable %52 Workgroup -%66 = OpTypePointer Function %4 -%68 = OpTypePointer Function %44 -%69 = OpConstantNull %44 -%72 = OpTypeFunction %2 -%73 = OpTypePointer Uniform %44 -%75 = OpTypePointer StorageBuffer %45 -%79 = OpTypePointer Uniform %43 -%82 = OpTypePointer Uniform %37 -%88 = OpTypePointer Uniform %8 -%108 = OpTypePointer Function %43 -%114 = OpTypePointer Function %37 -%120 = OpTypePointer Function %8 -%132 = OpTypeFunction %8 %46 -%138 = OpTypeFunction %8 %48 -%145 = OpTypeFunction %2 %52 -%149 = OpTypePointer Function %51 -%150 = OpConstantNull %51 -%153 = OpTypePointer Input %26 -%152 = OpVariable %153 Input -%156 = OpTypePointer Output %49 -%155 = OpVariable %156 Output -%163 = OpTypePointer StorageBuffer %34 -%166 = OpTypePointer StorageBuffer %40 -%169 = OpTypePointer StorageBuffer %35 -%170 = OpTypePointer StorageBuffer %8 -%173 = OpTypePointer StorageBuffer %41 -%176 = OpTypePointer StorageBuffer %33 -%177 = OpConstant %26 4 -%189 = OpTypeVector %4 4 -%195 = OpVariable %156 Output -%213 = OpConstantNull %4 -%217 = OpTypePointer StorageBuffer %4 -%220 = OpConstant %26 64 -%71 = OpFunction %2 None %72 -%70 = OpLabel -%65 = OpVariable %66 Function %5 -%67 = OpVariable %68 Function %69 -%74 = OpAccessChain %73 %58 %31 -OpBranch %76 +%4 = OpTypeInt 32 0 +%3 = OpConstant %4 0 +%6 = OpTypeInt 32 1 +%5 = OpConstant %6 0 +%7 = OpConstant %6 2 +%8 = OpConstant %6 1 +%10 = OpTypeFloat 32 +%9 = OpConstant %10 1.0 +%11 = OpConstant %10 2.0 +%12 = OpConstant %10 3.0 +%13 = OpConstant %10 6.0 +%14 = OpConstant %10 5.0 +%15 = OpConstant %10 4.0 +%16 = OpConstant %10 9.0 +%17 = OpConstant %10 90.0 +%18 = OpConstant %10 10.0 +%19 = OpConstant %10 20.0 +%20 = OpConstant %10 30.0 +%21 = OpConstant %10 40.0 +%22 = OpConstant %6 10 +%23 = OpConstant %6 5 +%24 = OpConstant %6 4 +%25 = OpConstant %6 9 +%26 = OpConstant %10 0.0 +%27 = OpConstant %4 3 +%28 = OpConstant %4 2 +%29 = OpConstant %6 3 +%30 = OpConstant %4 1 +%31 = OpConstant %6 42 +%32 = OpConstant %4 42 +%33 = OpTypeVector %4 3 +%34 = OpTypeStruct %4 %33 %6 +%35 = OpTypeStruct %6 +%37 = OpTypeVector %10 3 +%36 = OpTypeMatrix %37 4 +%39 = OpTypeVector %10 2 +%38 = OpTypeMatrix %39 2 +%40 = OpTypeArray %38 %7 +%41 = OpTypeVector %4 2 +%42 = OpTypeArray %41 %7 +%43 = OpTypeRuntimeArray %35 +%44 = OpTypeStruct %36 %40 %6 %42 %43 +%45 = OpTypeMatrix %39 3 +%46 = OpTypeStruct %45 +%47 = OpTypeVector %6 2 +%48 = OpTypePointer Function %10 +%49 = OpTypeArray %10 %22 +%50 = OpTypeArray %49 %23 +%51 = OpTypeVector %10 4 +%52 = OpTypePointer StorageBuffer %6 +%53 = OpTypeArray %6 %23 +%54 = OpTypePointer Workgroup %4 +%55 = OpConstantComposite %33 %3 %3 %3 +%56 = OpConstantComposite %34 %3 %55 %5 +%57 = OpConstantComposite %49 %26 %26 %26 %26 %26 %26 %26 %26 %26 %26 +%58 = OpConstantComposite %50 %57 %57 %57 %57 %57 +%59 = OpConstantComposite %47 %5 %5 +%61 = OpTypePointer Private %34 +%60 = OpVariable %61 Private %56 +%63 = OpTypePointer StorageBuffer %44 +%62 = OpVariable %63 StorageBuffer +%65 = OpTypeStruct %46 +%66 = OpTypePointer Uniform %65 +%64 = OpVariable %66 Uniform +%68 = OpTypeStruct %47 +%69 = OpTypePointer StorageBuffer %68 +%67 = OpVariable %69 StorageBuffer +%70 = OpVariable %54 Workgroup +%72 = OpTypePointer Function %6 +%74 = OpTypePointer Function %46 +%75 = OpConstantNull %46 +%78 = OpTypeFunction %2 +%79 = OpTypePointer Uniform %46 +%81 = OpTypePointer StorageBuffer %47 +%85 = OpTypePointer Uniform %45 +%88 = OpTypePointer Uniform %39 +%94 = OpTypePointer Uniform %10 +%114 = OpTypePointer Function %45 +%120 = OpTypePointer Function %39 +%126 = OpTypePointer Function %10 +%138 = OpTypeFunction %10 %48 +%144 = OpTypeFunction %10 %50 +%151 = OpTypeFunction %2 %54 +%155 = OpTypePointer Function %53 +%156 = OpConstantNull %53 +%159 = OpTypePointer Input %4 +%158 = OpVariable %159 Input +%162 = OpTypePointer Output %51 +%161 = OpVariable %162 Output +%169 = OpTypePointer StorageBuffer %36 +%172 = OpTypePointer StorageBuffer %42 +%175 = OpTypePointer StorageBuffer %37 +%176 = OpTypePointer StorageBuffer %10 +%179 = OpTypePointer StorageBuffer %43 +%182 = OpTypePointer StorageBuffer %35 +%183 = OpConstant %4 4 +%195 = OpTypeVector %6 4 +%201 = OpVariable %162 Output +%219 = OpConstantNull %6 +%223 = OpTypePointer StorageBuffer %6 +%226 = OpConstant %4 64 +%77 = OpFunction %2 None %78 %76 = OpLabel -%77 = OpLoad %4 %65 -%78 = OpISub %4 %77 %5 -OpStore %65 %78 -%80 = OpAccessChain %79 %74 %31 -%81 = OpLoad %43 %80 -%83 = OpAccessChain %82 %74 %31 %31 -%84 = OpLoad %37 %83 -%85 = OpLoad %4 %65 -%86 = OpAccessChain %82 %74 %31 %85 -%87 = OpLoad %37 %86 -%89 = OpAccessChain %88 %74 %31 %31 %29 -%90 = OpLoad %8 %89 -%91 = OpLoad %4 %65 -%92 = OpAccessChain %88 %74 %31 %31 %91 -%93 = OpLoad %8 %92 -%94 = OpLoad %4 %65 -%95 = OpAccessChain %88 %74 %31 %94 %29 -%96 = OpLoad %8 %95 -%97 = OpLoad %4 %65 -%98 = OpLoad %4 %65 -%99 = OpAccessChain %88 %74 %31 %97 %98 -%100 = OpLoad %8 %99 -%101 = OpCompositeConstruct %37 %7 %7 -%102 = OpCompositeConstruct %37 %9 %9 -%103 = OpCompositeConstruct %37 %10 %10 -%104 = OpCompositeConstruct %43 %101 %102 %103 -%105 = OpCompositeConstruct %44 %104 -OpStore %67 %105 -%106 = OpLoad %4 %65 -%107 = OpIAdd %4 %106 %5 -OpStore %65 %107 -%109 = OpCompositeConstruct %37 %11 %11 -%110 = OpCompositeConstruct %37 %12 %12 -%111 = OpCompositeConstruct %37 %13 %13 -%112 = OpCompositeConstruct %43 %109 %110 %111 -%113 = OpAccessChain %108 %67 %31 -OpStore %113 %112 -%115 = OpCompositeConstruct %37 %14 %14 -%116 = OpAccessChain %114 %67 %31 %31 -OpStore %116 %115 -%117 = OpLoad %4 %65 -%118 = OpCompositeConstruct %37 %15 %15 -%119 = OpAccessChain %114 %67 %31 %117 +%71 = OpVariable %72 Function %8 +%73 = OpVariable %74 Function %75 +%80 = OpAccessChain %79 %64 %3 +OpBranch %82 +%82 = OpLabel +%83 = OpLoad %6 %71 +%84 = OpISub %6 %83 %8 +OpStore %71 %84 +%86 = OpAccessChain %85 %80 %3 +%87 = OpLoad %45 %86 +%89 = OpAccessChain %88 %80 %3 %3 +%90 = OpLoad %39 %89 +%91 = OpLoad %6 %71 +%92 = OpAccessChain %88 %80 %3 %91 +%93 = OpLoad %39 %92 +%95 = OpAccessChain %94 %80 %3 %3 %30 +%96 = OpLoad %10 %95 +%97 = OpLoad %6 %71 +%98 = OpAccessChain %94 %80 %3 %3 %97 +%99 = OpLoad %10 %98 +%100 = OpLoad %6 %71 +%101 = OpAccessChain %94 %80 %3 %100 %30 +%102 = OpLoad %10 %101 +%103 = OpLoad %6 %71 +%104 = OpLoad %6 %71 +%105 = OpAccessChain %94 %80 %3 %103 %104 +%106 = OpLoad %10 %105 +%107 = OpCompositeConstruct %39 %9 %9 +%108 = OpCompositeConstruct %39 %11 %11 +%109 = OpCompositeConstruct %39 %12 %12 +%110 = OpCompositeConstruct %45 %107 %108 %109 +%111 = OpCompositeConstruct %46 %110 +OpStore %73 %111 +%112 = OpLoad %6 %71 +%113 = OpIAdd %6 %112 %8 +OpStore %71 %113 +%115 = OpCompositeConstruct %39 %13 %13 +%116 = OpCompositeConstruct %39 %14 %14 +%117 = OpCompositeConstruct %39 %15 %15 +%118 = OpCompositeConstruct %45 %115 %116 %117 +%119 = OpAccessChain %114 %73 %3 OpStore %119 %118 -%121 = OpAccessChain %120 %67 %31 %31 %29 -OpStore %121 %16 -%122 = OpLoad %4 %65 -%123 = OpAccessChain %120 %67 %31 %31 %122 -OpStore %123 %17 -%124 = OpLoad %4 %65 -%125 = OpAccessChain %120 %67 %31 %124 %29 -OpStore %125 %18 -%126 = OpLoad %4 %65 -%127 = OpLoad %4 %65 -%128 = OpAccessChain %120 %67 %31 %126 %127 -OpStore %128 %19 +%121 = OpCompositeConstruct %39 %16 %16 +%122 = OpAccessChain %120 %73 %3 %3 +OpStore %122 %121 +%123 = OpLoad %6 %71 +%124 = OpCompositeConstruct %39 %17 %17 +%125 = OpAccessChain %120 %73 %3 %123 +OpStore %125 %124 +%127 = OpAccessChain %126 %73 %3 %3 %30 +OpStore %127 %18 +%128 = OpLoad %6 %71 +%129 = OpAccessChain %126 %73 %3 %3 %128 +OpStore %129 %19 +%130 = OpLoad %6 %71 +%131 = OpAccessChain %126 %73 %3 %130 %30 +OpStore %131 %20 +%132 = OpLoad %6 %71 +%133 = OpLoad %6 %71 +%134 = OpAccessChain %126 %73 %3 %132 %133 +OpStore %134 %21 OpReturn OpFunctionEnd -%131 = OpFunction %8 None %132 -%130 = OpFunctionParameter %46 -%129 = OpLabel -OpBranch %133 -%133 = OpLabel -%134 = OpLoad %8 %130 -OpReturnValue %134 -OpFunctionEnd -%137 = OpFunction %8 None %138 +%137 = OpFunction %10 None %138 %136 = OpFunctionParameter %48 %135 = OpLabel OpBranch %139 %139 = OpLabel -%140 = OpCompositeExtract %47 %136 4 -%141 = OpCompositeExtract %8 %140 9 -OpReturnValue %141 +%140 = OpLoad %10 %136 +OpReturnValue %140 OpFunctionEnd -%144 = OpFunction %2 None %145 -%143 = OpFunctionParameter %52 -%142 = OpLabel -OpBranch %146 -%146 = OpLabel -OpStore %143 %32 +%143 = OpFunction %10 None %144 +%142 = OpFunctionParameter %50 +%141 = OpLabel +OpBranch %145 +%145 = OpLabel +%146 = OpCompositeExtract %49 %142 4 +%147 = OpCompositeExtract %10 %146 9 +OpReturnValue %147 +OpFunctionEnd +%150 = OpFunction %2 None %151 +%149 = OpFunctionParameter %54 +%148 = OpLabel +OpBranch %152 +%152 = OpLabel +OpStore %149 %32 OpReturn OpFunctionEnd -%157 = OpFunction %2 None %72 -%151 = OpLabel -%147 = OpVariable %46 Function %24 -%148 = OpVariable %149 Function %150 -%154 = OpLoad %26 %152 -%158 = OpAccessChain %73 %58 %31 -%159 = OpAccessChain %75 %61 %31 -OpBranch %160 -%160 = OpLabel -%161 = OpLoad %8 %147 -OpStore %147 %7 -%162 = OpFunctionCall %2 %71 -%164 = OpAccessChain %163 %56 %31 -%165 = OpLoad %34 %164 -%167 = OpAccessChain %166 %56 %25 -%168 = OpLoad %40 %167 -%171 = OpAccessChain %170 %56 %31 %25 %31 -%172 = OpLoad %8 %171 -%174 = OpArrayLength %26 %56 4 -%175 = OpISub %26 %174 %27 -%178 = OpAccessChain %50 %56 %177 %175 %31 -%179 = OpLoad %4 %178 -%180 = OpLoad %45 %159 -%181 = OpFunctionCall %8 %131 %147 -%182 = OpConvertFToS %4 %172 -%183 = OpCompositeConstruct %51 %179 %182 %28 %22 %21 -OpStore %148 %183 -%184 = OpIAdd %26 %154 %29 -%185 = OpAccessChain %66 %148 %184 -OpStore %185 %30 -%186 = OpAccessChain %66 %148 %154 -%187 = OpLoad %4 %186 -%188 = OpFunctionCall %8 %137 %54 -%190 = OpCompositeConstruct %189 %187 %187 %187 %187 -%191 = OpConvertSToF %49 %190 -%192 = OpMatrixTimesVector %35 %165 %191 -%193 = OpCompositeConstruct %49 %192 %9 -OpStore %155 %193 +%163 = OpFunction %2 None %78 +%157 = OpLabel +%153 = OpVariable %48 Function %26 +%154 = OpVariable %155 Function %156 +%160 = OpLoad %4 %158 +%164 = OpAccessChain %79 %64 %3 +%165 = OpAccessChain %81 %67 %3 +OpBranch %166 +%166 = OpLabel +%167 = OpLoad %10 %153 +OpStore %153 %9 +%168 = OpFunctionCall %2 %77 +%170 = OpAccessChain %169 %62 %3 +%171 = OpLoad %36 %170 +%173 = OpAccessChain %172 %62 %27 +%174 = OpLoad %42 %173 +%177 = OpAccessChain %176 %62 %3 %27 %3 +%178 = OpLoad %10 %177 +%180 = OpArrayLength %4 %62 4 +%181 = OpISub %4 %180 %28 +%184 = OpAccessChain %52 %62 %183 %181 %3 +%185 = OpLoad %6 %184 +%186 = OpLoad %47 %165 +%187 = OpFunctionCall %10 %137 %153 +%188 = OpConvertFToS %6 %178 +%189 = OpCompositeConstruct %53 %185 %188 %29 %24 %23 +OpStore %154 %189 +%190 = OpIAdd %4 %160 %30 +%191 = OpAccessChain %72 %154 %190 +OpStore %191 %31 +%192 = OpAccessChain %72 %154 %160 +%193 = OpLoad %6 %192 +%194 = OpFunctionCall %10 %143 %58 +%196 = OpCompositeConstruct %195 %193 %193 %193 %193 +%197 = OpConvertSToF %51 %196 +%198 = OpMatrixTimesVector %37 %171 %197 +%199 = OpCompositeConstruct %51 %198 %11 +OpStore %161 %199 OpReturn OpFunctionEnd -%196 = OpFunction %2 None %72 -%194 = OpLabel -%197 = OpAccessChain %75 %61 %31 -OpBranch %198 -%198 = OpLabel -%199 = OpAccessChain %170 %56 %31 %29 %27 -OpStore %199 %7 -%200 = OpCompositeConstruct %35 %24 %24 %24 -%201 = OpCompositeConstruct %35 %7 %7 %7 -%202 = OpCompositeConstruct %35 %9 %9 %9 -%203 = OpCompositeConstruct %35 %10 %10 %10 -%204 = OpCompositeConstruct %34 %200 %201 %202 %203 -%205 = OpAccessChain %163 %56 %31 -OpStore %205 %204 -%206 = OpCompositeConstruct %39 %31 %31 -%207 = OpCompositeConstruct %39 %29 %29 -%208 = OpCompositeConstruct %40 %206 %207 -%209 = OpAccessChain %166 %56 %25 -OpStore %209 %208 -%210 = OpAccessChain %50 %56 %177 %29 %31 -OpStore %210 %5 -OpStore %197 %55 -%211 = OpCompositeConstruct %49 %24 %24 %24 %24 -OpStore %195 %211 +%202 = OpFunction %2 None %78 +%200 = OpLabel +%203 = OpAccessChain %81 %67 %3 +OpBranch %204 +%204 = OpLabel +%205 = OpAccessChain %176 %62 %3 %30 %28 +OpStore %205 %9 +%206 = OpCompositeConstruct %37 %26 %26 %26 +%207 = OpCompositeConstruct %37 %9 %9 %9 +%208 = OpCompositeConstruct %37 %11 %11 %11 +%209 = OpCompositeConstruct %37 %12 %12 %12 +%210 = OpCompositeConstruct %36 %206 %207 %208 %209 +%211 = OpAccessChain %169 %62 %3 +OpStore %211 %210 +%212 = OpCompositeConstruct %41 %3 %3 +%213 = OpCompositeConstruct %41 %30 %30 +%214 = OpCompositeConstruct %42 %212 %213 +%215 = OpAccessChain %172 %62 %27 +OpStore %215 %214 +%216 = OpAccessChain %52 %62 %183 %30 %3 +OpStore %216 %8 +OpStore %203 %59 +%217 = OpCompositeConstruct %51 %26 %26 %26 %26 +OpStore %201 %217 OpReturn OpFunctionEnd -%215 = OpFunction %2 None %72 -%214 = OpLabel -%212 = OpVariable %66 Function %213 -OpBranch %216 -%216 = OpLabel -%218 = OpAccessChain %217 %56 %27 -%219 = OpAtomicLoad %4 %218 %5 %220 -%222 = OpAccessChain %217 %56 %27 -%221 = OpAtomicIAdd %4 %222 %5 %220 %21 -OpStore %212 %221 -%224 = OpAccessChain %217 %56 %27 -%223 = OpAtomicISub %4 %224 %5 %220 %21 -OpStore %212 %223 -%226 = OpAccessChain %217 %56 %27 -%225 = OpAtomicAnd %4 %226 %5 %220 %21 -OpStore %212 %225 -%228 = OpAccessChain %217 %56 %27 -%227 = OpAtomicOr %4 %228 %5 %220 %21 -OpStore %212 %227 -%230 = OpAccessChain %217 %56 %27 -%229 = OpAtomicXor %4 %230 %5 %220 %21 -OpStore %212 %229 -%232 = OpAccessChain %217 %56 %27 -%231 = OpAtomicSMin %4 %232 %5 %220 %21 -OpStore %212 %231 -%234 = OpAccessChain %217 %56 %27 -%233 = OpAtomicSMax %4 %234 %5 %220 %21 -OpStore %212 %233 -%236 = OpAccessChain %217 %56 %27 -%235 = OpAtomicExchange %4 %236 %5 %220 %21 -OpStore %212 %235 -%237 = OpAccessChain %217 %56 %27 -OpAtomicStore %237 %5 %220 %219 +%221 = OpFunction %2 None %78 +%220 = OpLabel +%218 = OpVariable %72 Function %219 +OpBranch %222 +%222 = OpLabel +%224 = OpAccessChain %223 %62 %28 +%225 = OpAtomicLoad %6 %224 %8 %226 +%228 = OpAccessChain %223 %62 %28 +%227 = OpAtomicIAdd %6 %228 %8 %226 %23 +OpStore %218 %227 +%230 = OpAccessChain %223 %62 %28 +%229 = OpAtomicISub %6 %230 %8 %226 %23 +OpStore %218 %229 +%232 = OpAccessChain %223 %62 %28 +%231 = OpAtomicAnd %6 %232 %8 %226 %23 +OpStore %218 %231 +%234 = OpAccessChain %223 %62 %28 +%233 = OpAtomicOr %6 %234 %8 %226 %23 +OpStore %218 %233 +%236 = OpAccessChain %223 %62 %28 +%235 = OpAtomicXor %6 %236 %8 %226 %23 +OpStore %218 %235 +%238 = OpAccessChain %223 %62 %28 +%237 = OpAtomicSMin %6 %238 %8 %226 %23 +OpStore %218 %237 +%240 = OpAccessChain %223 %62 %28 +%239 = OpAtomicSMax %6 %240 %8 %226 %23 +OpStore %218 %239 +%242 = OpAccessChain %223 %62 %28 +%241 = OpAtomicExchange %6 %242 %8 %226 %23 +OpStore %218 %241 +%243 = OpAccessChain %223 %62 %28 +OpAtomicStore %243 %8 %226 %225 OpReturn OpFunctionEnd -%239 = OpFunction %2 None %72 -%238 = OpLabel -OpBranch %240 -%240 = OpLabel -%241 = OpFunctionCall %2 %144 %64 +%245 = OpFunction %2 None %78 +%244 = OpLabel +OpBranch %246 +%246 = OpLabel +%247 = OpFunctionCall %2 %150 %70 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index ec5f8eee5..74caf8cd8 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -1,3 +1,9 @@ +struct GlobalConst { + a: u32, + b: vec3, + c: i32, +} + struct AlignedWrapper { value: i32, } @@ -14,6 +20,7 @@ struct Baz { m: mat3x2, } +var global_const: GlobalConst = GlobalConst(0u, vec3(0u, 0u, 0u), 0); @group(0) @binding(0) var bar: Bar; @group(0) @binding(1) @@ -26,41 +33,41 @@ fn test_matrix_within_struct_accesses() { var idx: i32 = 1; var t: Baz; - let _e5 = idx; - idx = (_e5 - 1); + let _e6 = idx; + idx = (_e6 - 1); _ = baz.m; _ = baz.m[0]; - let _e15 = idx; - _ = baz.m[_e15]; + let _e16 = idx; + _ = baz.m[_e16]; _ = baz.m[0][1]; - let _e27 = idx; - _ = baz.m[0][_e27]; - let _e31 = idx; - _ = baz.m[_e31][1]; - let _e37 = idx; - let _e39 = idx; - _ = baz.m[_e37][_e39]; + let _e28 = idx; + _ = baz.m[0][_e28]; + let _e32 = idx; + _ = baz.m[_e32][1]; + let _e38 = idx; + let _e40 = idx; + _ = baz.m[_e38][_e40]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - let _e51 = idx; - idx = (_e51 + 1); + let _e52 = idx; + idx = (_e52 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - let _e68 = idx; - t.m[_e68] = vec2(90.0); + let _e69 = idx; + t.m[_e69] = vec2(90.0); t.m[0][1] = 10.0; - let _e81 = idx; - t.m[0][_e81] = 20.0; - let _e85 = idx; - t.m[_e85][1] = 30.0; - let _e91 = idx; - let _e93 = idx; - t.m[_e91][_e93] = 40.0; + let _e82 = idx; + t.m[0][_e82] = 20.0; + let _e86 = idx; + t.m[_e86][1] = 30.0; + let _e92 = idx; + let _e94 = idx; + t.m[_e92][_e94] = 40.0; return; } fn read_from_private(foo_1: ptr) -> f32 { - let _e4 = (*foo_1); - return _e4; + let _e5 = (*foo_1); + return _e5; } fn test_arr_as_arg(a: array,5>) -> f32 { @@ -86,11 +93,11 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let a_1 = bar.data[(arrayLength((&bar.data)) - 2u)].value; let c_1 = qux; let data_pointer = (&bar.data[0].value); - let _e30 = read_from_private((&foo)); + let _e31 = read_from_private((&foo)); c = array(a_1, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value = c[vi]; - let _e44 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + let _e45 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); return vec4((_matrix * vec4(vec4(value))), 2.0); } @@ -109,22 +116,22 @@ fn atomics() { var tmp: i32; let value_1 = atomicLoad((&bar.atom)); - let _e8 = atomicAdd((&bar.atom), 5); - tmp = _e8; - let _e11 = atomicSub((&bar.atom), 5); - tmp = _e11; - let _e14 = atomicAnd((&bar.atom), 5); - tmp = _e14; - let _e17 = atomicOr((&bar.atom), 5); - tmp = _e17; - let _e20 = atomicXor((&bar.atom), 5); - tmp = _e20; - let _e23 = atomicMin((&bar.atom), 5); - tmp = _e23; - let _e26 = atomicMax((&bar.atom), 5); - tmp = _e26; - let _e29 = atomicExchange((&bar.atom), 5); - tmp = _e29; + let _e9 = atomicAdd((&bar.atom), 5); + tmp = _e9; + let _e12 = atomicSub((&bar.atom), 5); + tmp = _e12; + let _e15 = atomicAnd((&bar.atom), 5); + tmp = _e15; + let _e18 = atomicOr((&bar.atom), 5); + tmp = _e18; + let _e21 = atomicXor((&bar.atom), 5); + tmp = _e21; + let _e24 = atomicMin((&bar.atom), 5); + tmp = _e24; + let _e27 = atomicMax((&bar.atom), 5); + tmp = _e27; + let _e30 = atomicExchange((&bar.atom), 5); + tmp = _e30; atomicStore((&bar.atom), value_1); return; } From cafdb160ae554a847a35af19d3f6969db4574908 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 17 Jun 2022 14:33:59 +0100 Subject: [PATCH 1794/2212] glsl-out: Fix indentation for continuing block --- src/back/glsl/mod.rs | 7 ++++--- tests/out/glsl/boids.main.Compute.glsl | 4 ++-- tests/out/glsl/shadow.fs_main.Fragment.glsl | 4 ++-- .../out/glsl/shadow.fs_main_without_storage.Fragment.glsl | 4 ++-- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 18ba9f29b..b8ec31c71 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1805,11 +1805,12 @@ impl<'a, W: Write> Writer<'a, W> { let gate_name = self.namer.call("loop_init"); writeln!(self.out, "{}bool {} = true;", level, gate_name)?; writeln!(self.out, "{}while(true) {{", level)?; - writeln!(self.out, "{}if (!{}) {{", level.next(), gate_name)?; + let l2 = level.next(); + writeln!(self.out, "{}if (!{}) {{", l2, gate_name)?; for sta in continuing { - self.write_stmt(sta, ctx, level.next())?; + self.write_stmt(sta, ctx, l2.next())?; } - writeln!(self.out, "{}}}", level.next())?; + writeln!(self.out, "{}}}", l2)?; writeln!(self.out, "{}{} = false;", level.next(), gate_name)?; } else { writeln!(self.out, "{}while(true) {{", level)?; diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index e438ded42..8253d50d9 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -55,8 +55,8 @@ void main() { bool loop_init = true; while(true) { if (!loop_init) { - uint _e86 = i; - i = (_e86 + 1u); + uint _e86 = i; + i = (_e86 + 1u); } loop_init = false; uint _e37 = i; diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index fef409f10..6c0fed433 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -52,8 +52,8 @@ void main() { bool loop_init = true; while(true) { if (!loop_init) { - uint _e20 = i; - i = (_e20 + 1u); + uint _e20 = i; + i = (_e20 + 1u); } loop_init = false; uint _e14 = i; diff --git a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl index 43f02cae1..7cd75cff9 100644 --- a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl @@ -52,8 +52,8 @@ void main() { bool loop_init = true; while(true) { if (!loop_init) { - uint _e20 = i_1; - i_1 = (_e20 + 1u); + uint _e20 = i_1; + i_1 = (_e20 + 1u); } loop_init = false; uint _e14 = i_1; From 6d78f1c06dd5327da015f06bc6145c0b68c15b2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 17 Jun 2022 15:27:04 +0100 Subject: [PATCH 1795/2212] hlsl-out: Fix indentation for continuing block The continuing block in hlsl was being generated with the same indentation as the loop body --- src/back/hlsl/writer.rs | 2 +- tests/out/hlsl/boids.hlsl | 4 ++-- tests/out/hlsl/shadow.hlsl | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 16d21e079..de8b02936 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1505,7 +1505,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, "{}while(true) {{", level)?; writeln!(self.out, "{}if (!{}) {{", l2, gate_name)?; for sta in continuing.iter() { - self.write_stmt(module, sta, func_ctx, l2)?; + self.write_stmt(module, sta, func_ctx, l2.next())?; } writeln!(self.out, "{}}}", level.next())?; writeln!(self.out, "{}{} = false;", level.next(), gate_name)?; diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index 5fea9fc17..fb4640a76 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -47,8 +47,8 @@ void main(uint3 global_invocation_id : SV_DispatchThreadID) bool loop_init = true; while(true) { if (!loop_init) { - uint _expr86 = i; - i = (_expr86 + 1u); + uint _expr86 = i; + i = (_expr86 + 1u); } loop_init = false; uint _expr37 = i; diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index fe757eaa9..a3942386b 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -95,8 +95,8 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 bool loop_init = true; while(true) { if (!loop_init) { - uint _expr20 = i; - i = (_expr20 + 1u); + uint _expr20 = i; + i = (_expr20 + 1u); } loop_init = false; uint _expr14 = i; @@ -129,8 +129,8 @@ float4 fs_main_without_storage(FragmentInput_fs_main_without_storage fragmentinp bool loop_init_1 = true; while(true) { if (!loop_init_1) { - uint _expr20 = i_1; - i_1 = (_expr20 + 1u); + uint _expr20 = i_1; + i_1 = (_expr20 + 1u); } loop_init_1 = false; uint _expr14 = i_1; From ea832a9eec13560560c017072d4318d5d942e5e5 Mon Sep 17 00:00:00 2001 From: Ashley Date: Tue, 21 Jun 2022 07:25:13 +0200 Subject: [PATCH 1796/2212] [glsl-out] Handle vector bitcasts (#1966) * [spv-in] Fix bitcasts on non-scalars * Fix ::As handling in glsl * Cargo fmt * Make cargo clippy happy * Add snapshot tests * Use write_type_value * target_vector_kind -> target_vector_type --- src/back/glsl/mod.rs | 72 +++++++++------- tests/in/bitcast.params.ron | 15 ++++ tests/in/bitcast.wgsl | 26 ++++++ tests/out/glsl/bitcast.main.Compute.glsl | 48 +++++++++++ tests/out/msl/bitcast.msl | 47 ++++++++++ tests/out/spv/bitcast.spvasm | 104 +++++++++++++++++++++++ tests/out/wgsl/bitcast.wgsl | 41 +++++++++ tests/snapshots.rs | 4 + 8 files changed, 327 insertions(+), 30 deletions(-) create mode 100644 tests/in/bitcast.params.ron create mode 100644 tests/in/bitcast.wgsl create mode 100644 tests/out/glsl/bitcast.main.Compute.glsl create mode 100644 tests/out/msl/bitcast.msl create mode 100644 tests/out/spv/bitcast.spvasm create mode 100644 tests/out/wgsl/bitcast.wgsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b8ec31c71..a9d7efc8d 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2931,38 +2931,50 @@ impl<'a, W: Write> Writer<'a, W> { None => { use crate::ScalarKind as Sk; - let source_kind = inner.scalar_kind().unwrap(); - let conv_op = match (source_kind, target_kind) { - (Sk::Float, Sk::Sint) => "floatBitsToInt", - (Sk::Float, Sk::Uint) => "floatBitsToUint", - (Sk::Sint, Sk::Float) => "intBitsToFloat", - (Sk::Uint, Sk::Float) => "uintBitsToFloat", - // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion - (Sk::Uint, Sk::Sint) => "int", - (Sk::Sint, Sk::Uint) => "uint", - - (Sk::Bool, Sk::Sint) => "int", - (Sk::Bool, Sk::Uint) => "uint", - (Sk::Bool, Sk::Float) => "float", - - (Sk::Sint, Sk::Bool) => "bool", - (Sk::Uint, Sk::Bool) => "bool", - (Sk::Float, Sk::Bool) => "bool", - - // No conversion needed - (Sk::Sint, Sk::Sint) => "", - (Sk::Uint, Sk::Uint) => "", - (Sk::Float, Sk::Float) => "", - (Sk::Bool, Sk::Bool) => "", + let target_vector_type = match *inner { + TypeInner::Vector { size, width, .. } => Some(TypeInner::Vector { + size, + width, + kind: target_kind, + }), + _ => None, }; - write!(self.out, "{}", conv_op)?; - if !conv_op.is_empty() { - write!(self.out, "(")?; - } + + let source_kind = inner.scalar_kind().unwrap(); + + match (source_kind, target_kind, target_vector_type) { + // No conversion needed + (Sk::Sint, Sk::Sint, _) + | (Sk::Uint, Sk::Uint, _) + | (Sk::Float, Sk::Float, _) + | (Sk::Bool, Sk::Bool, _) => { + self.write_expr(expr, ctx)?; + return Ok(()); + } + + // Cast to/from floats + (Sk::Float, Sk::Sint, _) => write!(self.out, "floatBitsToInt")?, + (Sk::Float, Sk::Uint, _) => write!(self.out, "floatBitsToUint")?, + (Sk::Sint, Sk::Float, _) => write!(self.out, "intBitsToFloat")?, + (Sk::Uint, Sk::Float, _) => write!(self.out, "uintBitsToFloat")?, + + // Cast between vector types + (_, _, Some(vector)) => { + self.write_value_type(&vector)?; + } + + // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion + (Sk::Uint | Sk::Bool, Sk::Sint, None) => write!(self.out, "int")?, + (Sk::Sint | Sk::Bool, Sk::Uint, None) => write!(self.out, "uint")?, + (Sk::Bool, Sk::Float, None) => write!(self.out, "float")?, + (Sk::Sint | Sk::Uint | Sk::Float, Sk::Bool, None) => { + write!(self.out, "bool")? + } + }; + + write!(self.out, "(")?; self.write_expr(expr, ctx)?; - if !conv_op.is_empty() { - write!(self.out, ")")? - } + write!(self.out, ")")?; } } } diff --git a/tests/in/bitcast.params.ron b/tests/in/bitcast.params.ron new file mode 100644 index 000000000..fb45784e5 --- /dev/null +++ b/tests/in/bitcast.params.ron @@ -0,0 +1,15 @@ +( + msl: ( + lang_version: (1, 2), + per_stage_map: ( + cs: ( + resources: { + }, + sizes_buffer: Some(0), + ) + ), + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + ), +) diff --git a/tests/in/bitcast.wgsl b/tests/in/bitcast.wgsl new file mode 100644 index 000000000..11613f9b4 --- /dev/null +++ b/tests/in/bitcast.wgsl @@ -0,0 +1,26 @@ +@compute @workgroup_size(1) +fn main() { + var i2 = vec2(0); + var i3 = vec3(0); + var i4 = vec4(0); + + var u2 = vec2(0u); + var u3 = vec3(0u); + var u4 = vec4(0u); + + var f2 = vec2(0.0); + var f3 = vec3(0.0); + var f4 = vec4(0.0); + + u2 = bitcast>(i2); + u3 = bitcast>(i3); + u4 = bitcast>(i4); + + i2 = bitcast>(u2); + i3 = bitcast>(u3); + i4 = bitcast>(u4); + + f2 = bitcast>(i2); + f3 = bitcast>(i3); + f4 = bitcast>(i4); +} diff --git a/tests/out/glsl/bitcast.main.Compute.glsl b/tests/out/glsl/bitcast.main.Compute.glsl new file mode 100644 index 000000000..215aef8a5 --- /dev/null +++ b/tests/out/glsl/bitcast.main.Compute.glsl @@ -0,0 +1,48 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + + +void main() { + ivec2 i2_ = ivec2(0); + ivec3 i3_ = ivec3(0); + ivec4 i4_ = ivec4(0); + uvec2 u2_ = uvec2(0u); + uvec3 u3_ = uvec3(0u); + uvec4 u4_ = uvec4(0u); + vec2 f2_ = vec2(0.0); + vec3 f3_ = vec3(0.0); + vec4 f4_ = vec4(0.0); + i2_ = ivec2(0); + i3_ = ivec3(0); + i4_ = ivec4(0); + u2_ = uvec2(0u); + u3_ = uvec3(0u); + u4_ = uvec4(0u); + f2_ = vec2(0.0); + f3_ = vec3(0.0); + f4_ = vec4(0.0); + ivec2 _e27 = i2_; + u2_ = uvec2(_e27); + ivec3 _e29 = i3_; + u3_ = uvec3(_e29); + ivec4 _e31 = i4_; + u4_ = uvec4(_e31); + uvec2 _e33 = u2_; + i2_ = ivec2(_e33); + uvec3 _e35 = u3_; + i3_ = ivec3(_e35); + uvec4 _e37 = u4_; + i4_ = ivec4(_e37); + ivec2 _e39 = i2_; + f2_ = intBitsToFloat(_e39); + ivec3 _e41 = i3_; + f3_ = intBitsToFloat(_e41); + ivec4 _e43 = i4_; + f4_ = intBitsToFloat(_e43); + return; +} + diff --git a/tests/out/msl/bitcast.msl b/tests/out/msl/bitcast.msl new file mode 100644 index 000000000..a0cf093b7 --- /dev/null +++ b/tests/out/msl/bitcast.msl @@ -0,0 +1,47 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + + +kernel void main_( +) { + metal::int2 i2_ = {}; + metal::int3 i3_ = {}; + metal::int4 i4_ = {}; + metal::uint2 u2_ = {}; + metal::uint3 u3_ = {}; + metal::uint4 u4_ = {}; + metal::float2 f2_ = {}; + metal::float3 f3_ = {}; + metal::float4 f4_ = {}; + i2_ = metal::int2(0); + i3_ = metal::int3(0); + i4_ = metal::int4(0); + u2_ = metal::uint2(0u); + u3_ = metal::uint3(0u); + u4_ = metal::uint4(0u); + f2_ = metal::float2(0.0); + f3_ = metal::float3(0.0); + f4_ = metal::float4(0.0); + metal::int2 _e27 = i2_; + u2_ = as_type(_e27); + metal::int3 _e29 = i3_; + u3_ = as_type(_e29); + metal::int4 _e31 = i4_; + u4_ = as_type(_e31); + metal::uint2 _e33 = u2_; + i2_ = as_type(_e33); + metal::uint3 _e35 = u3_; + i3_ = as_type(_e35); + metal::uint4 _e37 = u4_; + i4_ = as_type(_e37); + metal::int2 _e39 = i2_; + f2_ = as_type(_e39); + metal::int3 _e41 = i3_; + f3_ = as_type(_e41); + metal::int4 _e43 = i4_; + f4_ = as_type(_e43); + return; +} diff --git a/tests/out/spv/bitcast.spvasm b/tests/out/spv/bitcast.spvasm new file mode 100644 index 000000000..6fffef8dc --- /dev/null +++ b/tests/out/spv/bitcast.spvasm @@ -0,0 +1,104 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 76 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %46 "main" +OpExecutionMode %46 LocalSize 1 1 1 +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 0 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 0 +%8 = OpTypeFloat 32 +%7 = OpConstant %8 0.0 +%9 = OpTypeVector %4 2 +%10 = OpTypeVector %4 3 +%11 = OpTypeVector %4 4 +%12 = OpTypeVector %6 2 +%13 = OpTypeVector %6 3 +%14 = OpTypeVector %6 4 +%15 = OpTypeVector %8 2 +%16 = OpTypeVector %8 3 +%17 = OpTypeVector %8 4 +%19 = OpTypePointer Function %9 +%20 = OpConstantNull %9 +%22 = OpTypePointer Function %10 +%23 = OpConstantNull %10 +%25 = OpTypePointer Function %11 +%26 = OpConstantNull %11 +%28 = OpTypePointer Function %12 +%29 = OpConstantNull %12 +%31 = OpTypePointer Function %13 +%32 = OpConstantNull %13 +%34 = OpTypePointer Function %14 +%35 = OpConstantNull %14 +%37 = OpTypePointer Function %15 +%38 = OpConstantNull %15 +%40 = OpTypePointer Function %16 +%41 = OpConstantNull %16 +%43 = OpTypePointer Function %17 +%44 = OpConstantNull %17 +%47 = OpTypeFunction %2 +%46 = OpFunction %2 None %47 +%45 = OpLabel +%36 = OpVariable %37 Function %38 +%27 = OpVariable %28 Function %29 +%18 = OpVariable %19 Function %20 +%39 = OpVariable %40 Function %41 +%30 = OpVariable %31 Function %32 +%21 = OpVariable %22 Function %23 +%42 = OpVariable %43 Function %44 +%33 = OpVariable %34 Function %35 +%24 = OpVariable %25 Function %26 +OpBranch %48 +%48 = OpLabel +%49 = OpCompositeConstruct %9 %3 %3 +OpStore %18 %49 +%50 = OpCompositeConstruct %10 %3 %3 %3 +OpStore %21 %50 +%51 = OpCompositeConstruct %11 %3 %3 %3 %3 +OpStore %24 %51 +%52 = OpCompositeConstruct %12 %5 %5 +OpStore %27 %52 +%53 = OpCompositeConstruct %13 %5 %5 %5 +OpStore %30 %53 +%54 = OpCompositeConstruct %14 %5 %5 %5 %5 +OpStore %33 %54 +%55 = OpCompositeConstruct %15 %7 %7 +OpStore %36 %55 +%56 = OpCompositeConstruct %16 %7 %7 %7 +OpStore %39 %56 +%57 = OpCompositeConstruct %17 %7 %7 %7 %7 +OpStore %42 %57 +%58 = OpLoad %9 %18 +%59 = OpBitcast %12 %58 +OpStore %27 %59 +%60 = OpLoad %10 %21 +%61 = OpBitcast %13 %60 +OpStore %30 %61 +%62 = OpLoad %11 %24 +%63 = OpBitcast %14 %62 +OpStore %33 %63 +%64 = OpLoad %12 %27 +%65 = OpBitcast %9 %64 +OpStore %18 %65 +%66 = OpLoad %13 %30 +%67 = OpBitcast %10 %66 +OpStore %21 %67 +%68 = OpLoad %14 %33 +%69 = OpBitcast %11 %68 +OpStore %24 %69 +%70 = OpLoad %9 %18 +%71 = OpBitcast %15 %70 +OpStore %36 %71 +%72 = OpLoad %10 %21 +%73 = OpBitcast %16 %72 +OpStore %39 %73 +%74 = OpLoad %11 %24 +%75 = OpBitcast %17 %74 +OpStore %42 %75 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/bitcast.wgsl b/tests/out/wgsl/bitcast.wgsl new file mode 100644 index 000000000..298c5fc21 --- /dev/null +++ b/tests/out/wgsl/bitcast.wgsl @@ -0,0 +1,41 @@ +@compute @workgroup_size(1, 1, 1) +fn main() { + var i2_: vec2; + var i3_: vec3; + var i4_: vec4; + var u2_: vec2; + var u3_: vec3; + var u4_: vec4; + var f2_: vec2; + var f3_: vec3; + var f4_: vec4; + + i2_ = vec2(0); + i3_ = vec3(0); + i4_ = vec4(0); + u2_ = vec2(0u); + u3_ = vec3(0u); + u4_ = vec4(0u); + f2_ = vec2(0.0); + f3_ = vec3(0.0); + f4_ = vec4(0.0); + let _e27 = i2_; + u2_ = bitcast>(_e27); + let _e29 = i3_; + u3_ = bitcast>(_e29); + let _e31 = i4_; + u4_ = bitcast>(_e31); + let _e33 = u2_; + i2_ = bitcast>(_e33); + let _e35 = u3_; + i3_ = bitcast>(_e35); + let _e37 = u4_; + i4_ = bitcast>(_e37); + let _e39 = i2_; + f2_ = bitcast>(_e39); + let _e41 = i3_; + f3_ = bitcast>(_e41); + let _e43 = i4_; + f4_ = bitcast>(_e43); + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 459cdf222..e36378556 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -435,6 +435,10 @@ fn convert_wgsl() { "bits", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, ), + ( + "bitcast", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + ), ( "boids", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From 67ef37ae991f72f06a58774c3866d716d1c9a9c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 16 Jun 2022 22:45:21 +0100 Subject: [PATCH 1797/2212] Add support for 'break if' to IR, wgsl-in, and all backends. --- src/back/dot/mod.rs | 4 + src/back/glsl/mod.rs | 13 ++- src/back/hlsl/writer.rs | 17 ++- src/back/msl/writer.rs | 13 ++- src/back/spv/block.rs | 96 ++++++++++++++--- src/back/spv/writer.rs | 7 +- src/back/wgsl/writer.rs | 18 +++- src/front/glsl/parser/functions.rs | 3 + src/front/spv/function.rs | 6 +- src/front/spv/mod.rs | 1 + src/front/wgsl/mod.rs | 123 ++++++++++++++++++---- src/lib.rs | 14 ++- src/valid/analyzer.rs | 1 + src/valid/function.rs | 15 +++ tests/in/break-if.wgsl | 32 ++++++ tests/out/glsl/break-if.main.Compute.glsl | 65 ++++++++++++ tests/out/hlsl/break-if.hlsl | 64 +++++++++++ tests/out/hlsl/break-if.hlsl.config | 3 + tests/out/ir/collatz.ron | 1 + tests/out/ir/shadow.ron | 1 + tests/out/msl/break-if.msl | 69 ++++++++++++ tests/out/spv/break-if.spvasm | 88 ++++++++++++++++ tests/out/wgsl/break-if.wgsl | 47 +++++++++ tests/snapshots.rs | 4 + tests/wgsl-errors.rs | 41 ++++++++ 25 files changed, 698 insertions(+), 48 deletions(-) create mode 100644 tests/in/break-if.wgsl create mode 100644 tests/out/glsl/break-if.main.Compute.glsl create mode 100644 tests/out/hlsl/break-if.hlsl create mode 100644 tests/out/hlsl/break-if.hlsl.config create mode 100644 tests/out/msl/break-if.msl create mode 100644 tests/out/spv/break-if.spvasm create mode 100644 tests/out/wgsl/break-if.wgsl diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 523e48ce5..265e40075 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -81,11 +81,15 @@ impl StatementGraph { S::Loop { ref body, ref continuing, + break_if, } => { let body_id = self.add(body); self.flow.push((id, body_id, "body")); let continuing_id = self.add(continuing); self.flow.push((body_id, continuing_id, "continuing")); + if let Some(expr) = break_if { + self.dependencies.push((id, expr, "break if")); + } "Loop" } S::Return { value } => { diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a9d7efc8d..a59a0b9d7 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1800,15 +1800,24 @@ impl<'a, W: Write> Writer<'a, W> { Statement::Loop { ref body, ref continuing, + break_if, } => { - if !continuing.is_empty() { + if !continuing.is_empty() || break_if.is_some() { let gate_name = self.namer.call("loop_init"); writeln!(self.out, "{}bool {} = true;", level, gate_name)?; writeln!(self.out, "{}while(true) {{", level)?; let l2 = level.next(); + let l3 = l2.next(); writeln!(self.out, "{}if (!{}) {{", l2, gate_name)?; for sta in continuing { - self.write_stmt(sta, ctx, l2.next())?; + self.write_stmt(sta, ctx, l3)?; + } + if let Some(condition) = break_if { + write!(self.out, "{}if (", l3)?; + self.write_expr(condition, ctx)?; + writeln!(self.out, ") {{")?; + writeln!(self.out, "{}break;", l3.next())?; + writeln!(self.out, "{}}}", l3)?; } writeln!(self.out, "{}}}", l2)?; writeln!(self.out, "{}{} = false;", level.next(), gate_name)?; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index de8b02936..4a14cc6ba 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1497,18 +1497,27 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Statement::Loop { ref body, ref continuing, + break_if, } => { let l2 = level.next(); - if !continuing.is_empty() { + if !continuing.is_empty() || break_if.is_some() { let gate_name = self.namer.call("loop_init"); writeln!(self.out, "{}bool {} = true;", level, gate_name)?; writeln!(self.out, "{}while(true) {{", level)?; writeln!(self.out, "{}if (!{}) {{", l2, gate_name)?; + let l3 = l2.next(); for sta in continuing.iter() { - self.write_stmt(module, sta, func_ctx, l2.next())?; + self.write_stmt(module, sta, func_ctx, l3)?; } - writeln!(self.out, "{}}}", level.next())?; - writeln!(self.out, "{}{} = false;", level.next(), gate_name)?; + if let Some(condition) = break_if { + write!(self.out, "{}if (", l3)?; + self.write_expr(module, condition, func_ctx)?; + writeln!(self.out, ") {{")?; + writeln!(self.out, "{}break;", l3.next())?; + writeln!(self.out, "{}}}", l3)?; + } + writeln!(self.out, "{}}}", l2)?; + writeln!(self.out, "{}{} = false;", l2, gate_name)?; } else { writeln!(self.out, "{}while(true) {{", level)?; } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 3992b6374..c35786f7a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2552,14 +2552,23 @@ impl Writer { crate::Statement::Loop { ref body, ref continuing, + break_if, } => { - if !continuing.is_empty() { + if !continuing.is_empty() || break_if.is_some() { let gate_name = self.namer.call("loop_init"); writeln!(self.out, "{}bool {} = true;", level, gate_name)?; writeln!(self.out, "{}while(true) {{", level)?; let lif = level.next(); + let lcontinuing = lif.next(); writeln!(self.out, "{}if (!{}) {{", lif, gate_name)?; - self.put_block(lif.next(), continuing, context)?; + self.put_block(lcontinuing, continuing, context)?; + if let Some(condition) = break_if { + write!(self.out, "{}if (", lcontinuing)?; + self.put_expression(condition, &context.expression, true)?; + writeln!(self.out, ") {{")?; + writeln!(self.out, "{}break;", lcontinuing.next())?; + writeln!(self.out, "{}}}", lcontinuing)?; + } writeln!(self.out, "{}}}", lif)?; writeln!(self.out, "{}{} = false;", lif, gate_name)?; } else { diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 413f4df5d..1c475e49b 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -37,6 +37,28 @@ enum ExpressionPointer { }, } +/// The termination statement to be added to the end of the block +pub enum BlockExit { + /// Generates an OpReturn (void return) + Return, + /// Generates an OpBranch to the specified block + Branch { + /// The branch target block + target: Word, + }, + /// Translates a loop `break if` into an `OpBranchConditional` to the + /// merge block if true (the merge block is passed through [`LoopContext::break_id`] + /// or else to the loop header (passed through [`preamble_id`]) + /// + /// [`preamble_id`]: Self::BreakIf::preamble_id + BreakIf { + /// The condition of the `break if` + condition: Handle, + /// The loop header block id + preamble_id: Word, + }, +} + impl Writer { // Flip Y coordinate to adjust for coordinate space difference // between SPIR-V and our IR. @@ -1491,7 +1513,7 @@ impl<'w> BlockContext<'w> { &mut self, label_id: Word, statements: &[crate::Statement], - exit_id: Option, + exit: BlockExit, loop_context: LoopContext, ) -> Result<(), Error> { let mut block = Block::new(label_id); @@ -1508,7 +1530,12 @@ impl<'w> BlockContext<'w> { self.function.consume(block, Instruction::branch(scope_id)); let merge_id = self.gen_id(); - self.write_block(scope_id, block_statements, Some(merge_id), loop_context)?; + self.write_block( + scope_id, + block_statements, + BlockExit::Branch { target: merge_id }, + loop_context, + )?; block = Block::new(merge_id); } @@ -1546,10 +1573,20 @@ impl<'w> BlockContext<'w> { ); if let Some(block_id) = accept_id { - self.write_block(block_id, accept, Some(merge_id), loop_context)?; + self.write_block( + block_id, + accept, + BlockExit::Branch { target: merge_id }, + loop_context, + )?; } if let Some(block_id) = reject_id { - self.write_block(block_id, reject, Some(merge_id), loop_context)?; + self.write_block( + block_id, + reject, + BlockExit::Branch { target: merge_id }, + loop_context, + )?; } block = Block::new(merge_id); @@ -1611,7 +1648,9 @@ impl<'w> BlockContext<'w> { self.write_block( *label_id, &case.body, - Some(case_finish_id), + BlockExit::Branch { + target: case_finish_id, + }, inner_context, )?; } @@ -1619,7 +1658,12 @@ impl<'w> BlockContext<'w> { // If no default was encountered write a empty block to satisfy the presence of // a block the default label if !reached_default { - self.write_block(default_id, &[], Some(merge_id), inner_context)?; + self.write_block( + default_id, + &[], + BlockExit::Branch { target: merge_id }, + inner_context, + )?; } block = Block::new(merge_id); @@ -1627,6 +1671,7 @@ impl<'w> BlockContext<'w> { crate::Statement::Loop { ref body, ref continuing, + break_if, } => { let preamble_id = self.gen_id(); self.function @@ -1649,17 +1694,29 @@ impl<'w> BlockContext<'w> { self.write_block( body_id, body, - Some(continuing_id), + BlockExit::Branch { + target: continuing_id, + }, LoopContext { continuing_id: Some(continuing_id), break_id: Some(merge_id), }, )?; + let exit = match break_if { + Some(condition) => BlockExit::BreakIf { + condition, + preamble_id, + }, + None => BlockExit::Branch { + target: preamble_id, + }, + }; + self.write_block( continuing_id, continuing, - Some(preamble_id), + exit, LoopContext { continuing_id: None, break_id: Some(merge_id), @@ -1955,12 +2012,10 @@ impl<'w> BlockContext<'w> { } } - let termination = match exit_id { - Some(id) => Instruction::branch(id), - // This can happen if the last branch had all the paths - // leading out of the graph (i.e. returning). - // Or it may be the end of the self.function. - None => match self.ir_function.result { + let termination = match exit { + // We're generating code for the top-level Block of the function, so we + // need to end it with some kind of return instruction. + BlockExit::Return => match self.ir_function.result { Some(ref result) if self.function.entry_point_context.is_none() => { let type_id = self.get_type_id(LookupType::Handle(result.ty)); let null_id = self.writer.write_constant_null(type_id); @@ -1968,6 +2023,19 @@ impl<'w> BlockContext<'w> { } _ => Instruction::return_void(), }, + BlockExit::Branch { target } => Instruction::branch(target), + BlockExit::BreakIf { + condition, + preamble_id, + } => { + let condition_id = self.cached[condition]; + + Instruction::branch_conditional( + condition_id, + loop_context.break_id.unwrap(), + preamble_id, + ) + } }; self.function.consume(block, termination); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e9dae65f9..6e8758f0c 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -574,7 +574,12 @@ impl Writer { context .function .consume(prelude, Instruction::branch(main_id)); - context.write_block(main_id, &ir_function.body, None, LoopContext::default())?; + context.write_block( + main_id, + &ir_function.body, + super::block::BlockExit::Return, + LoopContext::default(), + )?; // Consume the `BlockContext`, ending its borrows and letting the // `Writer` steal back its cached expression table and temp_list. diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 77ab496cb..8a7a71cdc 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -908,6 +908,7 @@ impl Writer { Statement::Loop { ref body, ref continuing, + break_if, } => { write!(self.out, "{}", level)?; writeln!(self.out, "loop {{")?; @@ -917,11 +918,26 @@ impl Writer { self.write_stmt(module, sta, func_ctx, l2)?; } - if !continuing.is_empty() { + // The continuing is optional so we don't need to write it if + // it is empty, but the `break if` counts as a continuing statement + // so even if `continuing` is empty we must generate it if a + // `break if` exists + if !continuing.is_empty() || break_if.is_some() { writeln!(self.out, "{}continuing {{", l2)?; for sta in continuing.iter() { self.write_stmt(module, sta, func_ctx, l2.next())?; } + + // The `break if` is always the last + // statement of the `continuing` block + if let Some(condition) = break_if { + // The trailing space is important + write!(self.out, "{}break if ", l2.next())?; + self.write_expr(module, condition, func_ctx)?; + // Close the `break if` statement + writeln!(self.out, ";")?; + } + writeln!(self.out, "{}}}", l2)?; } diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 2f271b816..6cb9bf017 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -358,6 +358,7 @@ impl<'source> ParsingContext<'source> { Statement::Loop { body: loop_body, continuing: Block::new(), + break_if: None, }, meta, ); @@ -411,6 +412,7 @@ impl<'source> ParsingContext<'source> { Statement::Loop { body: loop_body, continuing: Block::new(), + break_if: None, }, meta, ); @@ -513,6 +515,7 @@ impl<'source> ParsingContext<'source> { Statement::Loop { body: block, continuing, + break_if: None, }, meta, ); diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index c57695601..956f93cf9 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -556,7 +556,11 @@ impl<'function> BlockContext<'function> { let continuing = lower_impl(blocks, bodies, continuing); block.push( - crate::Statement::Loop { body, continuing }, + crate::Statement::Loop { + body, + continuing, + break_if: None, + }, crate::Span::default(), ) } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 234efd016..9f5d710e1 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3565,6 +3565,7 @@ impl> Parser { S::Loop { ref mut body, ref mut continuing, + break_if: _, } => { self.patch_statements(body, expressions, fun_parameter_sampling)?; self.patch_statements(continuing, expressions, fun_parameter_sampling)?; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f0e6ac51c..2f68534cf 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -125,6 +125,8 @@ pub enum Error<'a> { BadIncrDecrReferenceType(Span), InvalidResolve(ResolveError), InvalidForInitializer(Span), + /// A break if appeared outside of a continuing block + InvalidBreakIf(Span), InvalidGatherComponent(Span, u32), InvalidConstructorComponentType(Span, i32), InvalidIdentifierUnderscore(Span), @@ -307,6 +309,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "not an assignment or function call".into())], notes: vec![], }, + Error::InvalidBreakIf(ref bad_span) => ParseError { + message: "A break if is only allowed in a continuing block".to_string(), + labels: vec![(bad_span.clone(), "not in a continuing block".into())], + notes: vec![], + }, Error::InvalidGatherComponent(ref bad_span, component) => ParseError { message: format!("textureGather component {} doesn't exist, must be 0, 1, 2, or 3", component), labels: vec![(bad_span.clone(), "invalid component".into())], @@ -3811,26 +3818,7 @@ impl Parser { Some(crate::Statement::Switch { selector, cases }) } - "loop" => { - let _ = lexer.next(); - let mut body = crate::Block::new(); - let mut continuing = crate::Block::new(); - lexer.expect(Token::Paren('{'))?; - - loop { - if lexer.skip(Token::Word("continuing")) { - continuing = self.parse_block(lexer, context.reborrow(), false)?; - lexer.expect(Token::Paren('}'))?; - break; - } - if lexer.skip(Token::Paren('}')) { - break; - } - self.parse_statement(lexer, context.reborrow(), &mut body, false)?; - } - - Some(crate::Statement::Loop { body, continuing }) - } + "loop" => Some(self.parse_loop(lexer, context.reborrow(), &mut emitter)?), "while" => { let _ = lexer.next(); let mut body = crate::Block::new(); @@ -3863,6 +3851,7 @@ impl Parser { Some(crate::Statement::Loop { body, continuing: crate::Block::new(), + break_if: None, }) } "for" => { @@ -3935,10 +3924,22 @@ impl Parser { self.parse_statement(lexer, context.reborrow(), &mut body, false)?; } - Some(crate::Statement::Loop { body, continuing }) + Some(crate::Statement::Loop { + body, + continuing, + break_if: None, + }) } "break" => { - let _ = lexer.next(); + let (_, mut span) = lexer.next(); + // Check if the next token is an `if`, this indicates + // that the user tried to type out a `break if` which + // is illegal in this position. + let (peeked_token, peeked_span) = lexer.peek(); + if let Token::Word("if") = peeked_token { + span.end = peeked_span.end; + return Err(Error::InvalidBreakIf(span)); + } Some(crate::Statement::Break) } "continue" => { @@ -4041,6 +4042,84 @@ impl Parser { Ok(()) } + fn parse_loop<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: StatementContext<'a, '_, '_>, + emitter: &mut super::Emitter, + ) -> Result> { + let _ = lexer.next(); + let mut body = crate::Block::new(); + let mut continuing = crate::Block::new(); + let mut break_if = None; + lexer.expect(Token::Paren('{'))?; + + loop { + if lexer.skip(Token::Word("continuing")) { + // Branch for the `continuing` block, this must be + // the last thing in the loop body + + // Expect a opening brace to start the continuing block + lexer.expect(Token::Paren('{'))?; + loop { + if lexer.skip(Token::Word("break")) { + // Branch for the `break if` statement, this statement + // has the form `break if ;` and must be the last + // statement in a continuing block + + // The break must be followed by an `if` to form + // the break if + lexer.expect(Token::Word("if"))?; + + // Start the emitter to begin parsing an expression + emitter.start(context.expressions); + let condition = self.parse_general_expression( + lexer, + context.as_expression(&mut body, emitter), + )?; + // Add all emits to the continuing body + continuing.extend(emitter.finish(context.expressions)); + // Set the condition of the break if to the newly parsed + // expression + break_if = Some(condition); + + // Expext a semicolon to close the statement + lexer.expect(Token::Separator(';'))?; + // Expect a closing brace to close the continuing block, + // since the break if must be the last statement + lexer.expect(Token::Paren('}'))?; + // Stop parsing the continuing block + break; + } else if lexer.skip(Token::Paren('}')) { + // If we encounter a closing brace it means we have reached + // the end of the continuing block and should stop processing + break; + } else { + // Otherwise try to parse a statement + self.parse_statement(lexer, context.reborrow(), &mut continuing, false)?; + } + } + // Since the continuing block must be the last part of the loop body, + // we expect to see a closing brace to end the loop body + lexer.expect(Token::Paren('}'))?; + break; + } + if lexer.skip(Token::Paren('}')) { + // If we encounter a closing brace it means we have reached + // the end of the loop body and should stop processing + break; + } + // Otherwise try to parse a statement + self.parse_statement(lexer, context.reborrow(), &mut body, false)?; + } + + Ok(crate::Statement::Loop { + body, + continuing, + break_if, + }) + } + fn parse_block<'a>( &mut self, lexer: &mut Lexer<'a>, diff --git a/src/lib.rs b/src/lib.rs index 60bbe0e28..29bcbeaf4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1439,11 +1439,23 @@ pub enum Statement { /// this loop. (It may have `Break` and `Continue` statements targeting /// loops or switches nested within the `continuing` block.) /// + /// If present, `break_if` is an expression which is evaluated after the + /// continuing block. If its value is true, control continues after the + /// `Loop` statement, rather than branching back to the top of body as + /// usual. The `break_if` expression corresponds to a "break if" statement + /// in WGSL, or a loop whose back edge is an `OpBranchConditional` + /// instruction in SPIR-V. + /// /// [`Break`]: Statement::Break /// [`Continue`]: Statement::Continue /// [`Kill`]: Statement::Kill /// [`Return`]: Statement::Return - Loop { body: Block, continuing: Block }, + /// [`break if`]: Self::Loop::break_if + Loop { + body: Block, + continuing: Block, + break_if: Option>, + }, /// Exits the innermost enclosing [`Loop`] or [`Switch`]. /// diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 932e8b0f8..9a7130ff9 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -841,6 +841,7 @@ impl FunctionInfo { S::Loop { ref body, ref continuing, + break_if: _, } => { let body_uniformity = self.process_block(body, other_functions, disruptor, expression_arena)?; diff --git a/src/valid/function.rs b/src/valid/function.rs index b928ff517..67903601c 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -499,6 +499,7 @@ impl super::Validator { S::Loop { ref body, ref continuing, + break_if, } => { // special handling for block scoping is needed here, // because the continuing{} block inherits the scope @@ -520,6 +521,20 @@ impl super::Validator { &context.with_abilities(ControlFlowAbility::empty()), )? .stages; + + if let Some(condition) = break_if { + match *context.resolve_type(condition, &self.valid_expression_set)? { + Ti::Scalar { + kind: crate::ScalarKind::Bool, + width: _, + } => {} + _ => { + return Err(FunctionError::InvalidIfType(condition) + .with_span_handle(condition, context.expressions)) + } + } + } + for handle in self.valid_expression_list.drain(base_expression_count..) { self.valid_expression_set.remove(handle.index()); } diff --git a/tests/in/break-if.wgsl b/tests/in/break-if.wgsl new file mode 100644 index 000000000..a948edf14 --- /dev/null +++ b/tests/in/break-if.wgsl @@ -0,0 +1,32 @@ +@compute @workgroup_size(1) +fn main() {} + +fn breakIfEmpty() { + loop { + continuing { + break if true; + } + } +} + +fn breakIfEmptyBody(a: bool) { + loop { + continuing { + var b = a; + var c = a != b; + + break if a == c; + } + } +} + +fn breakIf(a: bool) { + loop { + var d = a; + var e = a != d; + + continuing { + break if a == e; + } + } +} diff --git a/tests/out/glsl/break-if.main.Compute.glsl b/tests/out/glsl/break-if.main.Compute.glsl new file mode 100644 index 000000000..025156af7 --- /dev/null +++ b/tests/out/glsl/break-if.main.Compute.glsl @@ -0,0 +1,65 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + + +void breakIfEmpty() { + bool loop_init = true; + while(true) { + if (!loop_init) { + if (true) { + break; + } + } + loop_init = false; + } + return; +} + +void breakIfEmptyBody(bool a) { + bool b = false; + bool c = false; + bool loop_init_1 = true; + while(true) { + if (!loop_init_1) { + b = a; + bool _e2 = b; + c = (a != _e2); + bool _e5 = c; + bool unnamed = (a == _e5); + if (unnamed) { + break; + } + } + loop_init_1 = false; + } + return; +} + +void breakIf(bool a_1) { + bool d = false; + bool e = false; + bool loop_init_2 = true; + while(true) { + if (!loop_init_2) { + bool _e5 = e; + bool unnamed_1 = (a_1 == _e5); + if (unnamed_1) { + break; + } + } + loop_init_2 = false; + d = a_1; + bool _e2 = d; + e = (a_1 != _e2); + } + return; +} + +void main() { + return; +} + diff --git a/tests/out/hlsl/break-if.hlsl b/tests/out/hlsl/break-if.hlsl new file mode 100644 index 000000000..fc91096a9 --- /dev/null +++ b/tests/out/hlsl/break-if.hlsl @@ -0,0 +1,64 @@ + +void breakIfEmpty() +{ + bool loop_init = true; + while(true) { + if (!loop_init) { + if (true) { + break; + } + } + loop_init = false; + } + return; +} + +void breakIfEmptyBody(bool a) +{ + bool b = (bool)0; + bool c = (bool)0; + + bool loop_init_1 = true; + while(true) { + if (!loop_init_1) { + b = a; + bool _expr2 = b; + c = (a != _expr2); + bool _expr5 = c; + bool unnamed = (a == _expr5); + if (unnamed) { + break; + } + } + loop_init_1 = false; + } + return; +} + +void breakIf(bool a_1) +{ + bool d = (bool)0; + bool e = (bool)0; + + bool loop_init_2 = true; + while(true) { + if (!loop_init_2) { + bool _expr5 = e; + bool unnamed_1 = (a_1 == _expr5); + if (unnamed_1) { + break; + } + } + loop_init_2 = false; + d = a_1; + bool _expr2 = d; + e = (a_1 != _expr2); + } + return; +} + +[numthreads(1, 1, 1)] +void main() +{ + return; +} diff --git a/tests/out/hlsl/break-if.hlsl.config b/tests/out/hlsl/break-if.hlsl.config new file mode 100644 index 000000000..246c485cf --- /dev/null +++ b/tests/out/hlsl/break-if.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(main:cs_5_1 ) diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 50860b2cb..2f3d06d13 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -261,6 +261,7 @@ ), ], continuing: [], + break_if: None, ), Emit(( start: 24, diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index d9a07a96a..11411c89e 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -1320,6 +1320,7 @@ value: 120, ), ], + break_if: None, ), Emit(( start: 120, diff --git a/tests/out/msl/break-if.msl b/tests/out/msl/break-if.msl new file mode 100644 index 000000000..600cca60d --- /dev/null +++ b/tests/out/msl/break-if.msl @@ -0,0 +1,69 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + + +void breakIfEmpty( +) { + bool loop_init = true; + while(true) { + if (!loop_init) { + if (true) { + break; + } + } + loop_init = false; + } + return; +} + +void breakIfEmptyBody( + bool a +) { + bool b = {}; + bool c = {}; + bool loop_init_1 = true; + while(true) { + if (!loop_init_1) { + b = a; + bool _e2 = b; + c = a != _e2; + bool _e5 = c; + bool unnamed = a == _e5; + if (a == c) { + break; + } + } + loop_init_1 = false; + } + return; +} + +void breakIf( + bool a_1 +) { + bool d = {}; + bool e = {}; + bool loop_init_2 = true; + while(true) { + if (!loop_init_2) { + bool _e5 = e; + bool unnamed_1 = a_1 == _e5; + if (a_1 == e) { + break; + } + } + loop_init_2 = false; + d = a_1; + bool _e2 = d; + e = a_1 != _e2; + } + return; +} + +kernel void main_( +) { + return; +} diff --git a/tests/out/spv/break-if.spvasm b/tests/out/spv/break-if.spvasm new file mode 100644 index 000000000..138fb0b61 --- /dev/null +++ b/tests/out/spv/break-if.spvasm @@ -0,0 +1,88 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 50 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %48 "main" +OpExecutionMode %48 LocalSize 1 1 1 +%2 = OpTypeVoid +%4 = OpTypeBool +%3 = OpConstantTrue %4 +%7 = OpTypeFunction %2 +%14 = OpTypePointer Function %4 +%15 = OpConstantNull %4 +%17 = OpConstantNull %4 +%21 = OpTypeFunction %2 %4 +%32 = OpConstantNull %4 +%34 = OpConstantNull %4 +%6 = OpFunction %2 None %7 +%5 = OpLabel +OpBranch %8 +%8 = OpLabel +OpBranch %9 +%9 = OpLabel +OpLoopMerge %10 %12 None +OpBranch %11 +%11 = OpLabel +OpBranch %12 +%12 = OpLabel +OpBranchConditional %3 %10 %9 +%10 = OpLabel +OpReturn +OpFunctionEnd +%20 = OpFunction %2 None %21 +%19 = OpFunctionParameter %4 +%18 = OpLabel +%13 = OpVariable %14 Function %15 +%16 = OpVariable %14 Function %17 +OpBranch %22 +%22 = OpLabel +OpBranch %23 +%23 = OpLabel +OpLoopMerge %24 %26 None +OpBranch %25 +%25 = OpLabel +OpBranch %26 +%26 = OpLabel +OpStore %13 %19 +%27 = OpLoad %4 %13 +%28 = OpLogicalNotEqual %4 %19 %27 +OpStore %16 %28 +%29 = OpLoad %4 %16 +%30 = OpLogicalEqual %4 %19 %29 +OpBranchConditional %30 %24 %23 +%24 = OpLabel +OpReturn +OpFunctionEnd +%37 = OpFunction %2 None %21 +%36 = OpFunctionParameter %4 +%35 = OpLabel +%31 = OpVariable %14 Function %32 +%33 = OpVariable %14 Function %34 +OpBranch %38 +%38 = OpLabel +OpBranch %39 +%39 = OpLabel +OpLoopMerge %40 %42 None +OpBranch %41 +%41 = OpLabel +OpStore %31 %36 +%43 = OpLoad %4 %31 +%44 = OpLogicalNotEqual %4 %36 %43 +OpStore %33 %44 +OpBranch %42 +%42 = OpLabel +%45 = OpLoad %4 %33 +%46 = OpLogicalEqual %4 %36 %45 +OpBranchConditional %46 %40 %39 +%40 = OpLabel +OpReturn +OpFunctionEnd +%48 = OpFunction %2 None %7 +%47 = OpLabel +OpBranch %49 +%49 = OpLabel +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/break-if.wgsl b/tests/out/wgsl/break-if.wgsl new file mode 100644 index 000000000..04b232905 --- /dev/null +++ b/tests/out/wgsl/break-if.wgsl @@ -0,0 +1,47 @@ +fn breakIfEmpty() { + loop { + continuing { + break if true; + } + } + return; +} + +fn breakIfEmptyBody(a: bool) { + var b: bool; + var c: bool; + + loop { + continuing { + b = a; + let _e2 = b; + c = (a != _e2); + let _e5 = c; + _ = (a == _e5); + break if (a == _e5); + } + } + return; +} + +fn breakIf(a_1: bool) { + var d: bool; + var e: bool; + + loop { + d = a_1; + let _e2 = d; + e = (a_1 != _e2); + continuing { + let _e5 = e; + _ = (a_1 == _e5); + break if (a_1 == _e5); + } + } + return; +} + +@compute @workgroup_size(1, 1, 1) +fn main() { + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e36378556..a7f773490 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -531,6 +531,10 @@ fn convert_wgsl() { "binding-arrays", Targets::WGSL | Targets::HLSL | Targets::METAL | Targets::SPIRV, ), + ( + "break-if", + Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, + ), ]; for &(name, targets) in inputs.iter() { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 564958f81..8ccaf1597 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1556,3 +1556,44 @@ fn host_shareable_types() { } } } + +#[test] +fn misplaced_break_if() { + check( + " + fn test_misplaced_break_if() { + loop { + break if true; + } + } + ", + r###"error: A break if is only allowed in a continuing block + ┌─ wgsl:4:17 + │ +4 │ break if true; + │ ^^^^^^^^ not in a continuing block + +"###, + ); +} + +#[test] +fn break_if_bad_condition() { + check_validation! { + " + fn test_break_if_bad_condition() { + loop { + continuing { + break if 1; + } + } + } + ": + Err( + naga::valid::ValidationError::Function { + error: naga::valid::FunctionError::InvalidIfType(_), + .. + }, + ) + } +} From 27d38aae33fdbfa72197847038cb470720594cb1 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 28 Jun 2022 00:56:10 +0200 Subject: [PATCH 1798/2212] [hlsl-out] More `matCx2` fixes (#1989) * [hlsl-out] fix matCx2 as global uniform * [hlsl-out] update comments * [hlsl-out] fix `row_major` not being written on global arrays of matrices and also write it on nested arrays of matrices * [hlsl-out] fix matCx2's nested inside global arrays * [hlsl-out] fix struct members of type array * [hlsl-out] test mat2x4 to make sure our matCx2 code behaves properly --- src/back/hlsl/help.rs | 154 +++- src/back/hlsl/mod.rs | 10 +- src/back/hlsl/writer.rs | 511 +++++++++-- tests/in/access.param.ron | 1 + tests/in/access.wgsl | 38 + tests/in/globals.wgsl | 11 +- .../access.assign_through_ptr.Compute.glsl | 7 +- tests/out/glsl/access.atomics.Compute.glsl | 39 +- tests/out/glsl/access.foo_frag.Fragment.glsl | 7 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 51 +- tests/out/glsl/globals.main.Compute.glsl | 37 +- tests/out/hlsl/access.hlsl | 150 +++- tests/out/hlsl/globals.hlsl | 86 +- tests/out/msl/access.msl | 108 ++- tests/out/msl/globals.msl | 53 +- tests/out/spv/access.spvasm | 792 ++++++++++-------- tests/out/spv/globals.spvasm | 394 +++++---- tests/out/wgsl/access.wgsl | 85 +- tests/out/wgsl/globals.wgsl | 37 +- 19 files changed, 1793 insertions(+), 778 deletions(-) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 5f81c296d..ec913ba66 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -54,6 +54,11 @@ pub(super) struct WrappedStructMatrixAccess { pub(super) index: u32, } +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) struct WrappedMatCx2 { + pub(super) columns: crate::VectorSize, +} + /// HLSL backend requires its own `ImageQuery` enum. /// /// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function. @@ -461,12 +466,36 @@ impl<'a, W: Write> super::Writer<'a, W> { )?; } } - _ => { - writeln!( - self.out, - "{}{}.{} = {}{};", - INDENT, RETURN_VARIABLE_NAME, field_name, ARGUMENT_VARIABLE_NAME, i, - )?; + ref other => { + // We cast arrays of native HLSL `floatCx2`s to arrays of `matCx2`s + // (where the inner matrix is represented by a struct with C `float2` members). + // See the module-level block comment in mod.rs for details. + if let Some(super::writer::MatrixType { + columns, + rows: crate::VectorSize::Bi, + width: 4, + }) = super::writer::get_inner_matrix_data(module, member.ty) + { + write!( + self.out, + "{}{}.{} = (__mat{}x2", + INDENT, RETURN_VARIABLE_NAME, field_name, columns as u8 + )?; + if let crate::TypeInner::Array { base, size, .. } = *other { + self.write_array_size(module, base, size)?; + } + writeln!(self.out, "){}{};", ARGUMENT_VARIABLE_NAME, i,)?; + } else { + writeln!( + self.out, + "{}{}.{} = {}{};", + INDENT, + RETURN_VARIABLE_NAME, + field_name, + ARGUMENT_VARIABLE_NAME, + i, + )?; + } } } } @@ -1050,4 +1079,117 @@ impl<'a, W: Write> super::Writer<'a, W> { } Ok(()) } + + pub(super) fn write_mat_cx2_typedef_and_functions( + &mut self, + WrappedMatCx2 { columns }: WrappedMatCx2, + ) -> BackendResult { + use crate::back::INDENT; + + // typedef + write!(self.out, "typedef struct {{ ")?; + for i in 0..columns as u8 { + write!(self.out, "float2 _{}; ", i)?; + } + writeln!(self.out, "}} __mat{}x2;", columns as u8)?; + + // __get_col_of_mat + writeln!( + self.out, + "float2 __get_col_of_mat{}x2(__mat{}x2 mat, uint idx) {{", + columns as u8, columns as u8 + )?; + writeln!(self.out, "{}switch(idx) {{", INDENT)?; + for i in 0..columns as u8 { + writeln!(self.out, "{}case {}: {{ return mat._{}; }}", INDENT, i, i)?; + } + writeln!(self.out, "{}default: {{ return (float2)0; }}", INDENT)?; + writeln!(self.out, "{}}}", INDENT)?; + writeln!(self.out, "}}")?; + + // __set_col_of_mat + writeln!( + self.out, + "void __set_col_of_mat{}x2(__mat{}x2 mat, uint idx, float2 value) {{", + columns as u8, columns as u8 + )?; + writeln!(self.out, "{}switch(idx) {{", INDENT)?; + for i in 0..columns as u8 { + writeln!( + self.out, + "{}case {}: {{ mat._{} = value; break; }}", + INDENT, i, i + )?; + } + writeln!(self.out, "{}}}", INDENT)?; + writeln!(self.out, "}}")?; + + // __set_el_of_mat + writeln!( + self.out, + "void __set_el_of_mat{}x2(__mat{}x2 mat, uint idx, uint vec_idx, float value) {{", + columns as u8, columns as u8 + )?; + writeln!(self.out, "{}switch(idx) {{", INDENT)?; + for i in 0..columns as u8 { + writeln!( + self.out, + "{}case {}: {{ mat._{}[vec_idx] = value; break; }}", + INDENT, i, i + )?; + } + writeln!(self.out, "{}}}", INDENT)?; + writeln!(self.out, "}}")?; + + writeln!(self.out)?; + + Ok(()) + } + + pub(super) fn write_all_mat_cx2_typedefs_and_functions( + &mut self, + module: &crate::Module, + ) -> BackendResult { + for (handle, _) in module.global_variables.iter() { + let global = &module.global_variables[handle]; + + if global.space == crate::AddressSpace::Uniform { + if let Some(super::writer::MatrixType { + columns, + rows: crate::VectorSize::Bi, + width: 4, + }) = super::writer::get_inner_matrix_data(module, global.ty) + { + let entry = WrappedMatCx2 { columns }; + if !self.wrapped.mat_cx2s.contains(&entry) { + self.write_mat_cx2_typedef_and_functions(entry)?; + self.wrapped.mat_cx2s.insert(entry); + } + } + } + } + + for (_, ty) in module.types.iter() { + if let crate::TypeInner::Struct { ref members, .. } = ty.inner { + for member in members.iter() { + if let crate::TypeInner::Array { .. } = module.types[member.ty].inner { + if let Some(super::writer::MatrixType { + columns, + rows: crate::VectorSize::Bi, + width: 4, + }) = super::writer::get_inner_matrix_data(module, member.ty) + { + let entry = WrappedMatCx2 { columns }; + if !self.wrapped.mat_cx2s.contains(&entry) { + self.write_mat_cx2_typedef_and_functions(entry)?; + self.wrapped.mat_cx2s.insert(entry); + } + } + } + } + } + } + + Ok(()) + } } diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index db027f776..76abb2978 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -57,8 +57,8 @@ that the columns of a `matKx2` need only be [aligned as required for `vec2`][ilov], which is [eight-byte alignment][8bb]. To compensate for this, any time a `matKx2` appears in a WGSL -`uniform` variable, whether directly as the variable's type or as a -struct member, we actually emit `K` separate `float2` members, and +`uniform` variable, whether directly as the variable's type or as part +of a struct/array, we actually emit `K` separate `float2` members, and assemble/disassemble the matrix from its columns (in WGSL; rows in HLSL) upon load and store. @@ -92,14 +92,10 @@ float3x2 GetMatmOnBaz(Baz obj) { We also emit an analogous `Set` function, as well as functions for accessing individual columns by dynamic index. -At present, we do not generate correct HLSL when `matCx2` us used -directly as the type of a WGSL `uniform` global ([#1837]). - [hlsl]: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl [ilov]: https://gpuweb.github.io/gpuweb/wgsl/#internal-value-layout [16bb]: https://github.com/microsoft/DirectXShaderCompiler/wiki/Buffer-Packing#constant-buffer-packing [8bb]: https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size -[#1837]: https://github.com/gfx-rs/naga/issues/1837 */ mod conv; @@ -253,6 +249,7 @@ struct Wrapped { image_queries: crate::FastHashSet, constructors: crate::FastHashSet, struct_matrix_access: crate::FastHashSet, + mat_cx2s: crate::FastHashSet, } impl Wrapped { @@ -261,6 +258,7 @@ impl Wrapped { self.image_queries.clear(); self.constructors.clear(); self.struct_matrix_access.clear(); + self.mat_cx2s.clear(); } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 4a14cc6ba..b582cfa4f 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -150,6 +150,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { .map(|ep| (ep.stage, ep.function.result.clone())) .collect::)>>(); + self.write_all_mat_cx2_typedefs_and_functions(module)?; + // Write all structs for (handle, ty) in module.types.iter() { if let TypeInner::Struct { ref members, span } = ty.inner { @@ -661,19 +663,41 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if global.space == crate::AddressSpace::Uniform { write!(self.out, " {{ ")?; - // Even though Naga IR matrices are column-major, we must describe - // matrices passed from the CPU as being in row-major order. See - // the module-level comments for details. - if let TypeInner::Matrix { .. } = module.types[global.ty].inner { - write!(self.out, "row_major ")?; + + let matrix_data = get_inner_matrix_data(module, global.ty); + + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s. + // See the module-level block comment in mod.rs for details. + if let Some(MatrixType { + columns, + rows: crate::VectorSize::Bi, + width: 4, + }) = matrix_data + { + write!( + self.out, + "__mat{}x2 {}", + columns as u8, + &self.names[&NameKey::GlobalVariable(handle)] + )?; + } else { + // Even though Naga IR matrices are column-major, we must describe + // matrices passed from the CPU as being in row-major order. + // See the module-level block comment in mod.rs for details. + if matrix_data.is_some() { + write!(self.out, "row_major ")?; + } + + self.write_type(module, global.ty)?; + let sub_name = &self.names[&NameKey::GlobalVariable(handle)]; + write!(self.out, " {}", sub_name)?; } - self.write_type(module, global.ty)?; - let sub_name = &self.names[&NameKey::GlobalVariable(handle)]; - write!(self.out, " {}", sub_name)?; + // need to write the array size if the type was emitted with `write_type` if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner { self.write_array_size(module, base, size)?; } + writeln!(self.out, "; }}")?; } else { writeln!(self.out, ";")?; @@ -801,16 +825,31 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "{}", back::INDENT)?; match module.types[member.ty].inner { - TypeInner::Array { - base, - size, - stride: _, - } => { + TypeInner::Array { base, size, .. } => { // HLSL arrays are written as `type name[size]` - if let TypeInner::Matrix { .. } = module.types[base].inner { - write!(self.out, "row_major ")?; + + let matrix_data = get_inner_matrix_data(module, member.ty); + + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s. + // See the module-level block comment in mod.rs for details. + if let Some(MatrixType { + columns, + rows: crate::VectorSize::Bi, + width: 4, + }) = matrix_data + { + write!(self.out, "__mat{}x2", columns as u8)?; + } else { + // Even though Naga IR matrices are column-major, we must describe + // matrices passed from the CPU as being in row-major order. + // See the module-level block comment in mod.rs for details. + if matrix_data.is_some() { + write!(self.out, "row_major ")?; + } + + self.write_type(module, base)?; } - self.write_type(module, base)?; + // Write `name` write!( self.out, @@ -820,8 +859,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write [size] self.write_array_size(module, base, size)?; } - // We treat matrices of the form `matCx2` as a sequence of C `vec2`s - // (see top level module docs for details). + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s. + // See the module-level block comment in mod.rs for details. TypeInner::Matrix { rows, columns, @@ -848,6 +887,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_modifier(binding)?; } + // Even though Naga IR matrices are column-major, we must describe + // matrices passed from the CPU as being in row-major order. + // See the module-level block comment in mod.rs for details. if let TypeInner::Matrix { .. } = module.types[member.ty].inner { write!(self.out, "row_major ")?; } @@ -1285,17 +1327,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } Statement::Store { pointer, value } => { let ty_inner = func_ctx.info[pointer].ty.inner_with(&module.types); - let array_info = match *ty_inner { - TypeInner::Pointer { base, .. } => match module.types[base].inner { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(ch), - .. - } => Some((ch, base)), - _ => None, - }, - _ => None, - }; - if let Some(crate::AddressSpace::Storage { .. }) = ty_inner.pointer_space() { let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; self.write_storage_store( @@ -1305,26 +1336,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { func_ctx, level, )?; - } else if let Some((const_handle, base_ty)) = array_info { - let size = module.constants[const_handle].to_array_length().unwrap(); - writeln!(self.out, "{}{{", level)?; - write!(self.out, "{}", level.next())?; - self.write_type(module, base_ty)?; - write!(self.out, " _result[{}]=", size)?; - self.write_expr(module, value, func_ctx)?; - writeln!(self.out, ";")?; - write!( - self.out, - "{}for(int _i=0; _i<{}; ++_i) ", - level.next(), - size - )?; - self.write_expr(module, pointer, func_ctx)?; - writeln!(self.out, "[_i] = _result[_i];")?; - writeln!(self.out, "{}}}", level)?; } else { - // We treat matrices of the form `matCx2` as a sequence of C `vec2`s - // (see top level module docs for details). + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s. + // See the module-level block comment in mod.rs for details. // // We handle matrix Stores here directly (including sub accesses for Vectors and Scalars). // Loads are handled by `Expression::AccessIndex` (since sub accesses work fine for Loads). @@ -1487,10 +1501,132 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, ");")?; } } else { - self.write_expr(module, pointer, func_ctx)?; - write!(self.out, " = ")?; - self.write_expr(module, value, func_ctx)?; - writeln!(self.out, ";")? + // We handle `Store`s to __matCx2 column vectors and scalar elements via + // the previously injected functions __set_col_of_matCx2 / __set_el_of_matCx2. + struct MatrixData { + columns: crate::VectorSize, + base: Handle, + } + + enum Index { + Expression(Handle), + Static(u32), + } + + let mut matrix = None; + let mut vector = None; + let mut scalar = None; + + let mut current_expr = pointer; + for _ in 0..3 { + let resolved = func_ctx.info[current_expr].ty.inner_with(&module.types); + match (resolved, &func_ctx.expressions[current_expr]) { + ( + &TypeInner::ValuePointer { + size: Some(crate::VectorSize::Bi), + .. + }, + &crate::Expression::Access { base, index }, + ) => { + vector = Some(index); + current_expr = base; + } + ( + &TypeInner::ValuePointer { size: None, .. }, + &crate::Expression::Access { base, index }, + ) => { + scalar = Some(Index::Expression(index)); + current_expr = base; + } + ( + &TypeInner::ValuePointer { size: None, .. }, + &crate::Expression::AccessIndex { base, index }, + ) => { + scalar = Some(Index::Static(index)); + current_expr = base; + } + _ => { + if let Some(MatrixType { + columns, + rows: crate::VectorSize::Bi, + width: 4, + }) = get_inner_matrix_of_struct_array_member( + module, + current_expr, + func_ctx, + true, + ) { + matrix = Some(MatrixData { + columns, + base: current_expr, + }); + } + + break; + } + } + } + + if let (Some(MatrixData { columns, base }), Some(vec_index)) = + (matrix, vector) + { + if scalar.is_some() { + write!(self.out, "__set_el_of_mat{}x2", columns as u8)?; + } else { + write!(self.out, "__set_col_of_mat{}x2", columns as u8)?; + } + write!(self.out, "(")?; + self.write_expr(module, base, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, vec_index, func_ctx)?; + + if let Some(scalar_index) = scalar { + write!(self.out, ", ")?; + match scalar_index { + Index::Static(index) => { + write!(self.out, "{}", index)?; + } + Index::Expression(index) => { + self.write_expr(module, index, func_ctx)?; + } + } + } + + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + + writeln!(self.out, ");")?; + } else { + self.write_expr(module, pointer, func_ctx)?; + write!(self.out, " = ")?; + + // We cast the RHS of this store in cases where the LHS + // is a struct member with type: + // - matCx2 or + // - a (possibly nested) array of matCx2's + if let Some(MatrixType { + columns, + rows: crate::VectorSize::Bi, + width: 4, + }) = get_inner_matrix_of_struct_array_member( + module, pointer, func_ctx, false, + ) { + let mut resolved = + func_ctx.info[pointer].ty.inner_with(&module.types); + if let TypeInner::Pointer { base, .. } = *resolved { + resolved = &module.types[base].inner; + } + + write!(self.out, "(__mat{}x2", columns as u8)?; + if let TypeInner::Array { base, size, .. } = *resolved { + self.write_array_size(module, base, size)?; + } + write!(self.out, ")")?; + } + + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ";")? + } } } } @@ -1863,6 +1999,26 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { { // do nothing, the chain is written on `Load`/`Store` } else { + // We use the function __get_col_of_matCx2 here in cases + // where `base`s type resolves to a matCx2 and is part of a + // struct member with type of (possibly nested) array of matCx2's. + // + // Note that this only works for `Load`s and we handle + // `Store`s differently in `Statement::Store`. + if let Some(MatrixType { + columns, + rows: crate::VectorSize::Bi, + width: 4, + }) = get_inner_matrix_of_struct_array_member(module, base, func_ctx, true) + { + write!(self.out, "__get_col_of_mat{}x2(", columns as u8)?; + self.write_expr(module, base, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, index, func_ctx)?; + write!(self.out, ")")?; + return Ok(()); + } + let base_ty_res = &func_ctx.info[base].ty; let resolved = base_ty_res.inner_with(&module.types); @@ -1895,18 +2051,64 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { { // do nothing, the chain is written on `Load`/`Store` } else { + fn write_access( + writer: &mut super::Writer<'_, W>, + resolved: &TypeInner, + base_ty_handle: Option>, + index: u32, + ) -> BackendResult { + match *resolved { + TypeInner::Vector { .. } => { + // Write vector access as a swizzle + write!(writer.out, ".{}", back::COMPONENTS[index as usize])? + } + TypeInner::Matrix { .. } + | TypeInner::Array { .. } + | TypeInner::BindingArray { .. } + | TypeInner::ValuePointer { .. } => write!(writer.out, "[{}]", index)?, + TypeInner::Struct { .. } => { + // This will never panic in case the type is a `Struct`, this is not true + // for other types so we can only check while inside this match arm + let ty = base_ty_handle.unwrap(); + + write!( + writer.out, + ".{}", + &writer.names[&NameKey::StructMember(ty, index)] + )? + } + ref other => { + return Err(Error::Custom(format!("Cannot index {:?}", other))) + } + } + Ok(()) + } + + // We write the matrix column access in a special way since + // the type of `base` is our special __matCx2 struct. + if let Some(MatrixType { + rows: crate::VectorSize::Bi, + width: 4, + .. + }) = get_inner_matrix_of_struct_array_member(module, base, func_ctx, true) + { + self.write_expr(module, base, func_ctx)?; + write!(self.out, "._{}", index)?; + return Ok(()); + } + let base_ty_res = &func_ctx.info[base].ty; let mut resolved = base_ty_res.inner_with(&module.types); let base_ty_handle = match *resolved { - TypeInner::Pointer { base, space: _ } => { + TypeInner::Pointer { base, .. } => { resolved = &module.types[base].inner; Some(base) } _ => base_ty_res.handle(), }; - // We treat matrices of the form `matCx2` as a sequence of C `vec2`s - // (see top level module docs for details). + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s. + // See the module-level block comment in mod.rs for details. // // We handle matrix reconstruction here for Loads. // Stores are handled directly by `Statement::Store`. @@ -1929,34 +2131,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } _ => {} } - }; + } self.write_expr(module, base, func_ctx)?; - - match *resolved { - TypeInner::Vector { .. } => { - // Write vector access as a swizzle - write!(self.out, ".{}", back::COMPONENTS[index as usize])? - } - TypeInner::Matrix { .. } - | TypeInner::Array { .. } - | TypeInner::BindingArray { .. } - | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, - TypeInner::Struct { .. } => { - // This will never panic in case the type is a `Struct`, this is not true - // for other types so we can only check while inside this match arm - let ty = base_ty_handle.unwrap(); - - write!( - self.out, - ".{}", - &self.names[&NameKey::StructMember(ty, index)] - )? - } - ref other => { - return Err(Error::Custom(format!("Cannot index {:?}", other))) - } - } + write_access(self, resolved, base_ty_handle, index)?; } } Expression::FunctionArgument(pos) => { @@ -2127,7 +2305,42 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_storage_load(module, var_handle, result_ty, func_ctx)?; } _ => { + let mut close_paren = false; + + // We cast the value loaded to a native HLSL floatCx2 + // in cases where it is of type: + // - __matCx2 or + // - a (possibly nested) array of __matCx2's + if let Some(MatrixType { + rows: crate::VectorSize::Bi, + width: 4, + .. + }) = get_inner_matrix_of_struct_array_member( + module, pointer, func_ctx, false, + ) + .or_else(|| get_inner_matrix_of_global_uniform(module, pointer, func_ctx)) + { + let mut resolved = func_ctx.info[pointer].ty.inner_with(&module.types); + if let TypeInner::Pointer { base, .. } = *resolved { + resolved = &module.types[base].inner; + } + + write!(self.out, "((")?; + if let TypeInner::Array { base, size, .. } = *resolved { + self.write_type(module, base)?; + self.write_array_size(module, base, size)?; + } else { + self.write_value_type(module, resolved)?; + } + write!(self.out, ")")?; + close_paren = true; + } + self.write_expr(module, pointer, func_ctx)?; + + if close_paren { + write!(self.out, ")")?; + } } } } @@ -2586,3 +2799,139 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } } + +pub(super) struct MatrixType { + pub(super) columns: crate::VectorSize, + pub(super) rows: crate::VectorSize, + pub(super) width: crate::Bytes, +} + +pub(super) fn get_inner_matrix_data( + module: &Module, + handle: Handle, +) -> Option { + match module.types[handle].inner { + TypeInner::Matrix { + columns, + rows, + width, + } => Some(MatrixType { + columns, + rows, + width, + }), + TypeInner::Array { base, .. } => get_inner_matrix_data(module, base), + _ => None, + } +} + +/// Returns the matrix data if the access chain starting at `base`: +/// - starts with an expression with resolved type of [`TypeInner::Matrix`] if `direct = true` +/// - contains one or more expressions with resolved type of [`TypeInner::Array`] of [`TypeInner::Matrix`] +/// - ends at an expression with resolved type of [`TypeInner::Struct`] +pub(super) fn get_inner_matrix_of_struct_array_member( + module: &Module, + base: Handle, + func_ctx: &back::FunctionCtx<'_>, + direct: bool, +) -> Option { + let mut mat_data = None; + let mut array_base = None; + + let mut current_base = base; + loop { + let mut resolved = func_ctx.info[current_base].ty.inner_with(&module.types); + if let TypeInner::Pointer { base, .. } = *resolved { + resolved = &module.types[base].inner; + }; + + match *resolved { + TypeInner::Matrix { + columns, + rows, + width, + } => { + mat_data = Some(MatrixType { + columns, + rows, + width, + }) + } + TypeInner::Array { base, .. } => { + array_base = Some(base); + } + TypeInner::Struct { .. } => { + if let Some(array_base) = array_base { + if direct { + return mat_data; + } else { + return get_inner_matrix_data(module, array_base); + } + } + + break; + } + _ => break, + } + + current_base = match func_ctx.expressions[current_base] { + crate::Expression::Access { base, .. } => base, + crate::Expression::AccessIndex { base, .. } => base, + _ => break, + }; + } + None +} + +/// Returns the matrix data if the access chain starting at `base`: +/// - starts with an expression with resolved type of [`TypeInner::Matrix`] +/// - contains zero or more expressions with resolved type of [`TypeInner::Array`] of [`TypeInner::Matrix`] +/// - ends with an [`Expression::GlobalVariable`](crate::Expression::GlobalVariable) in [`AddressSpace::Uniform`](crate::AddressSpace::Uniform) +fn get_inner_matrix_of_global_uniform( + module: &Module, + base: Handle, + func_ctx: &back::FunctionCtx<'_>, +) -> Option { + let mut mat_data = None; + let mut array_base = None; + + let mut current_base = base; + loop { + let mut resolved = func_ctx.info[current_base].ty.inner_with(&module.types); + if let TypeInner::Pointer { base, .. } = *resolved { + resolved = &module.types[base].inner; + }; + + match *resolved { + TypeInner::Matrix { + columns, + rows, + width, + } => { + mat_data = Some(MatrixType { + columns, + rows, + width, + }) + } + TypeInner::Array { base, .. } => { + array_base = Some(base); + } + _ => break, + } + + current_base = match func_ctx.expressions[current_base] { + crate::Expression::Access { base, .. } => base, + crate::Expression::AccessIndex { base, .. } => base, + crate::Expression::GlobalVariable(handle) + if module.global_variables[handle].space == crate::AddressSpace::Uniform => + { + return mat_data.or_else(|| { + array_base.and_then(|array_base| get_inner_matrix_data(module, array_base)) + }) + } + _ => break, + }; + } + None +} diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 3e79bea26..8408e4cb6 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -12,6 +12,7 @@ (group: 0, binding: 0): (buffer: Some(0), mutable: false), (group: 0, binding: 1): (buffer: Some(1), mutable: false), (group: 0, binding: 2): (buffer: Some(2), mutable: false), + (group: 0, binding: 3): (buffer: Some(3), mutable: false), }, sizes_buffer: Some(24), ), diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 456aee4b3..c2e4d25b6 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -61,6 +61,43 @@ fn test_matrix_within_struct_accesses() { t.m[idx][idx] = 40.0; } +struct MatCx2InArray { + am: array, 2>, +} + +@group(0) @binding(3) +var nested_mat_cx2: MatCx2InArray; + +fn test_matrix_within_array_within_struct_accesses() { + var idx = 1; + + idx--; + + // loads + _ = nested_mat_cx2.am; + _ = nested_mat_cx2.am[0]; + _ = nested_mat_cx2.am[0][0]; + _ = nested_mat_cx2.am[0][idx]; + _ = nested_mat_cx2.am[0][0][1]; + _ = nested_mat_cx2.am[0][0][idx]; + _ = nested_mat_cx2.am[0][idx][1]; + _ = nested_mat_cx2.am[0][idx][idx]; + + var t = MatCx2InArray(array, 2>()); + + idx++; + + // stores + t.am = array, 2>(); + t.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); + t.am[0][0] = vec2(9.0); + t.am[0][idx] = vec2(90.0); + t.am[0][0][1] = 10.0; + t.am[0][0][idx] = 20.0; + t.am[0][idx][1] = 30.0; + t.am[0][idx][idx] = 40.0; +} + fn read_from_private(foo: ptr) -> f32 { return *foo; } @@ -77,6 +114,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { foo = 1.0; test_matrix_within_struct_accesses(); + test_matrix_within_array_within_struct_accesses(); // test storage loads let _matrix = bar._matrix; diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 89ab106f9..59820ab36 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -20,10 +20,16 @@ var dummy: array>; var float_vecs: array, 20>; @group(0) @binding(4) -var global_vec: vec4; +var global_vec: vec3; @group(0) @binding(5) -var global_mat: mat4x4; +var global_mat: mat3x2; + +@group(0) @binding(6) +var global_nested_arrays_of_matrices_2x4: array, 2>, 2>; + +@group(0) @binding(7) +var global_nested_arrays_of_matrices_4x2: array, 2>, 2>; fn test_msl_packed_vec3_as_arg(arg: vec3) {} @@ -56,6 +62,7 @@ fn test_msl_packed_vec3() { fn main() { test_msl_packed_vec3(); + wg[7] = (global_nested_arrays_of_matrices_4x2[0][0] * global_nested_arrays_of_matrices_2x4[0][0][0]).x; wg[6] = (global_mat * global_vec).x; wg[5] = dummy[1].y; wg[4] = float_vecs[0].w; diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/tests/out/glsl/access.assign_through_ptr.Compute.glsl index 34b989a0f..c7ee8362c 100644 --- a/tests/out/glsl/access.assign_through_ptr.Compute.glsl +++ b/tests/out/glsl/access.assign_through_ptr.Compute.glsl @@ -16,12 +16,15 @@ struct AlignedWrapper { struct Baz { mat3x2 m; }; +struct MatCx2InArray { + mat4x2 am[2]; +}; shared uint val; float read_from_private(inout float foo_1) { - float _e5 = foo_1; - return _e5; + float _e6 = foo_1; + return _e6; } float test_arr_as_arg(float a[5][10]) { diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 83e7e1e78..56c844f6a 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -16,6 +16,9 @@ struct AlignedWrapper { struct Baz { mat3x2 m; }; +struct MatCx2InArray { + mat4x2 am[2]; +}; layout(std430) buffer Bar_block_0Compute { mat4x3 _matrix; mat2x2 matrix_array[2]; @@ -26,8 +29,8 @@ layout(std430) buffer Bar_block_0Compute { float read_from_private(inout float foo_1) { - float _e5 = foo_1; - return _e5; + float _e6 = foo_1; + return _e6; } float test_arr_as_arg(float a[5][10]) { @@ -42,22 +45,22 @@ void assign_through_ptr_fn(inout uint p) { void main() { int tmp = 0; int value = _group_0_binding_0_cs.atom; - int _e9 = atomicAdd(_group_0_binding_0_cs.atom, 5); - tmp = _e9; - int _e12 = atomicAdd(_group_0_binding_0_cs.atom, -5); - tmp = _e12; - int _e15 = atomicAnd(_group_0_binding_0_cs.atom, 5); - tmp = _e15; - int _e18 = atomicOr(_group_0_binding_0_cs.atom, 5); - tmp = _e18; - int _e21 = atomicXor(_group_0_binding_0_cs.atom, 5); - tmp = _e21; - int _e24 = atomicMin(_group_0_binding_0_cs.atom, 5); - tmp = _e24; - int _e27 = atomicMax(_group_0_binding_0_cs.atom, 5); - tmp = _e27; - int _e30 = atomicExchange(_group_0_binding_0_cs.atom, 5); - tmp = _e30; + int _e10 = atomicAdd(_group_0_binding_0_cs.atom, 5); + tmp = _e10; + int _e13 = atomicAdd(_group_0_binding_0_cs.atom, -5); + tmp = _e13; + int _e16 = atomicAnd(_group_0_binding_0_cs.atom, 5); + tmp = _e16; + int _e19 = atomicOr(_group_0_binding_0_cs.atom, 5); + tmp = _e19; + int _e22 = atomicXor(_group_0_binding_0_cs.atom, 5); + tmp = _e22; + int _e25 = atomicMin(_group_0_binding_0_cs.atom, 5); + tmp = _e25; + int _e28 = atomicMax(_group_0_binding_0_cs.atom, 5); + tmp = _e28; + int _e31 = atomicExchange(_group_0_binding_0_cs.atom, 5); + tmp = _e31; _group_0_binding_0_cs.atom = value; return; } diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index 36c8fb2a4..a3d6d21dd 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -14,6 +14,9 @@ struct AlignedWrapper { struct Baz { mat3x2 m; }; +struct MatCx2InArray { + mat4x2 am[2]; +}; layout(std430) buffer Bar_block_0Fragment { mat4x3 _matrix; mat2x2 matrix_array[2]; @@ -27,8 +30,8 @@ layout(std430) buffer type_11_block_1Fragment { ivec2 _group_0_binding_2_fs; }; layout(location = 0) out vec4 _fs2p_location0; float read_from_private(inout float foo_1) { - float _e5 = foo_1; - return _e5; + float _e6 = foo_1; + return _e6; } float test_arr_as_arg(float a[5][10]) { diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index cd3a65ac0..9fbfc272f 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -14,6 +14,9 @@ struct AlignedWrapper { struct Baz { mat3x2 m; }; +struct MatCx2InArray { + mat4x2 am[2]; +}; layout(std430) buffer Bar_block_0Vertex { mat4x3 _matrix; mat2x2 matrix_array[2]; @@ -26,6 +29,8 @@ uniform Baz_block_1Vertex { Baz _group_0_binding_1_vs; }; layout(std430) buffer type_11_block_2Vertex { ivec2 _group_0_binding_2_vs; }; +uniform MatCx2InArray_block_3Vertex { MatCx2InArray _group_0_binding_3_vs; }; + void test_matrix_within_struct_accesses() { int idx = 1; @@ -62,9 +67,46 @@ void test_matrix_within_struct_accesses() { return; } +void test_matrix_within_array_within_struct_accesses() { + int idx_1 = 1; + MatCx2InArray t_1 = MatCx2InArray(mat4x2[2](mat4x2(0.0), mat4x2(0.0))); + int _e7 = idx_1; + idx_1 = (_e7 - 1); + mat4x2 unnamed_7[2] = _group_0_binding_3_vs.am; + mat4x2 unnamed_8 = _group_0_binding_3_vs.am[0]; + vec2 unnamed_9 = _group_0_binding_3_vs.am[0][0]; + int _e25 = idx_1; + vec2 unnamed_10 = _group_0_binding_3_vs.am[0][_e25]; + float unnamed_11 = _group_0_binding_3_vs.am[0][0][1]; + int _e41 = idx_1; + float unnamed_12 = _group_0_binding_3_vs.am[0][0][_e41]; + int _e47 = idx_1; + float unnamed_13 = _group_0_binding_3_vs.am[0][_e47][1]; + int _e55 = idx_1; + int _e57 = idx_1; + float unnamed_14 = _group_0_binding_3_vs.am[0][_e55][_e57]; + t_1 = MatCx2InArray(mat4x2[2](mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)))); + int _e63 = idx_1; + idx_1 = (_e63 + 1); + t_1.am = mat4x2[2](mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0))); + t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); + t_1.am[0][0] = vec2(9.0); + int _e90 = idx_1; + t_1.am[0][_e90] = vec2(90.0); + t_1.am[0][0][1] = 10.0; + int _e107 = idx_1; + t_1.am[0][0][_e107] = 20.0; + int _e113 = idx_1; + t_1.am[0][_e113][1] = 30.0; + int _e121 = idx_1; + int _e123 = idx_1; + t_1.am[0][_e121][_e123] = 40.0; + return; +} + float read_from_private(inout float foo_1) { - float _e5 = foo_1; - return _e5; + float _e6 = foo_1; + return _e6; } float test_arr_as_arg(float a[5][10]) { @@ -83,16 +125,17 @@ void main() { float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); + test_matrix_within_array_within_struct_accesses(); mat4x3 _matrix = _group_0_binding_0_vs._matrix; uvec2 arr[2] = _group_0_binding_0_vs.arr; float b = _group_0_binding_0_vs._matrix[3][0]; int a_1 = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; ivec2 c_1 = _group_0_binding_2_vs; - float _e31 = read_from_private(foo); + float _e32 = read_from_private(foo); c = int[5](a_1, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; - float _e45 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + float _e46 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); gl_Position = vec4((_matrix * vec4(ivec4(value))), 2.0); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index 40066567f..0d5cb797b 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -19,9 +19,13 @@ layout(std430) readonly buffer type_6_block_1Compute { vec2 _group_0_binding_2_c uniform type_8_block_2Compute { vec4 _group_0_binding_3_cs[20]; }; -uniform type_7_block_3Compute { vec4 _group_0_binding_4_cs; }; +uniform type_4_block_3Compute { vec3 _group_0_binding_4_cs; }; -uniform type_9_block_4Compute { mat4x4 _group_0_binding_5_cs; }; +uniform type_9_block_4Compute { mat3x2 _group_0_binding_5_cs; }; + +uniform type_12_block_5Compute { mat2x4 _group_0_binding_6_cs[2][2]; }; + +uniform type_15_block_6Compute { mat4x2 _group_0_binding_7_cs[2][2]; }; void test_msl_packed_vec3_as_arg(vec3 arg) { @@ -33,8 +37,8 @@ void test_msl_packed_vec3_() { _group_0_binding_1_cs.v3_ = vec3(1.0); _group_0_binding_1_cs.v3_.x = 1.0; _group_0_binding_1_cs.v3_.x = 2.0; - int _e21 = idx; - _group_0_binding_1_cs.v3_[_e21] = 3.0; + int _e23 = idx; + _group_0_binding_1_cs.v3_[_e23] = 3.0; Foo data = _group_0_binding_1_cs; vec3 unnamed = data.v3_; vec2 unnamed_1 = data.v3_.zx; @@ -49,17 +53,20 @@ void main() { float Foo_1 = 1.0; bool at = true; test_msl_packed_vec3_(); - mat4x4 _e10 = _group_0_binding_5_cs; - vec4 _e11 = _group_0_binding_4_cs; - wg[6] = (_e10 * _e11).x; - float _e19 = _group_0_binding_2_cs[1].y; - wg[5] = _e19; - float _e25 = _group_0_binding_3_cs[0].w; - wg[4] = _e25; - float _e29 = _group_0_binding_1_cs.v1_; - wg[3] = _e29; - float _e34 = _group_0_binding_1_cs.v3_.x; - wg[2] = _e34; + mat4x2 _e16 = _group_0_binding_7_cs[0][0]; + vec4 _e23 = _group_0_binding_6_cs[0][0][0]; + wg[7] = (_e16 * _e23).x; + mat3x2 _e28 = _group_0_binding_5_cs; + vec3 _e29 = _group_0_binding_4_cs; + wg[6] = (_e28 * _e29).x; + float _e37 = _group_0_binding_2_cs[1].y; + wg[5] = _e37; + float _e43 = _group_0_binding_3_cs[0].w; + wg[4] = _e43; + float _e47 = _group_0_binding_1_cs.v1_; + wg[3] = _e47; + float _e52 = _group_0_binding_1_cs.v3_.x; + wg[2] = _e52; _group_0_binding_1_cs.v1_ = 4.0; wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 5f264572d..5510ec05b 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -1,4 +1,52 @@ +typedef struct { float2 _0; float2 _1; } __mat2x2; +float2 __get_col_of_mat2x2(__mat2x2 mat, uint idx) { + switch(idx) { + case 0: { return mat._0; } + case 1: { return mat._1; } + default: { return (float2)0; } + } +} +void __set_col_of_mat2x2(__mat2x2 mat, uint idx, float2 value) { + switch(idx) { + case 0: { mat._0 = value; break; } + case 1: { mat._1 = value; break; } + } +} +void __set_el_of_mat2x2(__mat2x2 mat, uint idx, uint vec_idx, float value) { + switch(idx) { + case 0: { mat._0[vec_idx] = value; break; } + case 1: { mat._1[vec_idx] = value; break; } + } +} + +typedef struct { float2 _0; float2 _1; float2 _2; float2 _3; } __mat4x2; +float2 __get_col_of_mat4x2(__mat4x2 mat, uint idx) { + switch(idx) { + case 0: { return mat._0; } + case 1: { return mat._1; } + case 2: { return mat._2; } + case 3: { return mat._3; } + default: { return (float2)0; } + } +} +void __set_col_of_mat4x2(__mat4x2 mat, uint idx, float2 value) { + switch(idx) { + case 0: { mat._0 = value; break; } + case 1: { mat._1 = value; break; } + case 2: { mat._2 = value; break; } + case 3: { mat._3 = value; break; } + } +} +void __set_el_of_mat4x2(__mat4x2 mat, uint idx, uint vec_idx, float value) { + switch(idx) { + case 0: { mat._0[vec_idx] = value; break; } + case 1: { mat._1[vec_idx] = value; break; } + case 2: { mat._2[vec_idx] = value; break; } + case 3: { mat._3[vec_idx] = value; break; } + } +} + struct GlobalConst { uint a; int _pad1_0; @@ -17,6 +65,10 @@ struct Baz { float2 m_0; float2 m_1; float2 m_2; }; +struct MatCx2InArray { + __mat4x2 am[2]; +}; + GlobalConst ConstructGlobalConst(uint arg0, uint3 arg1, int arg2) { GlobalConst ret = (GlobalConst)0; ret.a = arg0; @@ -25,6 +77,12 @@ GlobalConst ConstructGlobalConst(uint arg0, uint3 arg1, int arg2) { return ret; } +typedef float4x2 ret_Constructarray2_float4x2_[2]; +ret_Constructarray2_float4x2_ Constructarray2_float4x2_(float4x2 arg0, float4x2 arg1) { + float4x2 ret[2] = { arg0, arg1 }; + return ret; +} + typedef float ret_Constructarray10_float_[10]; ret_Constructarray10_float_ Constructarray10_float_(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5, float arg6, float arg7, float arg8, float arg9) { float ret[10] = { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 }; @@ -41,6 +99,7 @@ static GlobalConst global_const = ConstructGlobalConst(0u, uint3(0u, 0u, 0u), 0) RWByteAddressBuffer bar : register(u0); cbuffer baz : register(b1) { Baz baz; } RWByteAddressBuffer qux : register(u2); +cbuffer nested_mat_cx2_ : register(b3) { MatCx2InArray nested_mat_cx2_; } groupshared uint val; float3x2 GetMatmOnBaz(Baz obj) { @@ -114,10 +173,55 @@ void test_matrix_within_struct_accesses() return; } +MatCx2InArray ConstructMatCx2InArray(float4x2 arg0[2]) { + MatCx2InArray ret = (MatCx2InArray)0; + ret.am = (__mat4x2[2])arg0; + return ret; +} + +void test_matrix_within_array_within_struct_accesses() +{ + int idx_1 = 1; + MatCx2InArray t_1 = (MatCx2InArray)0; + + int _expr7 = idx_1; + idx_1 = (_expr7 - 1); + float4x2 unnamed_7[2] = ((float4x2[2])nested_mat_cx2_.am); + float4x2 unnamed_8 = ((float4x2)nested_mat_cx2_.am[0]); + float2 unnamed_9 = nested_mat_cx2_.am[0]._0; + int _expr25 = idx_1; + float2 unnamed_10 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr25); + float unnamed_11 = nested_mat_cx2_.am[0]._0[1]; + int _expr41 = idx_1; + float unnamed_12 = nested_mat_cx2_.am[0]._0[_expr41]; + int _expr47 = idx_1; + float unnamed_13 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr47)[1]; + int _expr55 = idx_1; + int _expr57 = idx_1; + float unnamed_14 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr55)[_expr57]; + t_1 = ConstructMatCx2InArray(Constructarray2_float4x2_(float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0)), float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0)))); + int _expr63 = idx_1; + idx_1 = (_expr63 + 1); + t_1.am = (__mat4x2[2])Constructarray2_float4x2_(float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0)), float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0))); + t_1.am[0] = (__mat4x2)float4x2((8.0).xx, (7.0).xx, (6.0).xx, (5.0).xx); + t_1.am[0]._0 = (9.0).xx; + int _expr90 = idx_1; + __set_col_of_mat4x2(t_1.am[0], _expr90, (90.0).xx); + t_1.am[0]._0[1] = 10.0; + int _expr107 = idx_1; + t_1.am[0]._0[_expr107] = 20.0; + int _expr113 = idx_1; + __set_el_of_mat4x2(t_1.am[0], _expr113, 1, 30.0); + int _expr121 = idx_1; + int _expr123 = idx_1; + __set_el_of_mat4x2(t_1.am[0], _expr121, _expr123, 40.0); + return; +} + float read_from_private(inout float foo_1) { - float _expr5 = foo_1; - return _expr5; + float _expr6 = foo_1; + return _expr6; } float test_arr_as_arg(float a[5][10]) @@ -152,19 +256,17 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); + test_matrix_within_array_within_struct_accesses(); float4x3 _matrix = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); int2 c_1 = asint(qux.Load2(0)); - const float _e31 = read_from_private(foo); - { - int _result[5]=Constructarray5_int_(a_1, int(b), 3, 4, 5); - for(int _i=0; _i<5; ++_i) c[_i] = _result[_i]; - } + const float _e32 = read_from_private(foo); + c = Constructarray5_int_(a_1, int(b), 3, 4, 5); c[(vi + 1u)] = 42; int value = c[vi]; - const float _e45 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + const float _e46 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); return float4(mul(float4((value).xxxx), _matrix), 2.0); } @@ -200,22 +302,22 @@ void atomics() int tmp = (int)0; int value_1 = asint(bar.Load(96)); - int _e9; bar.InterlockedAdd(96, 5, _e9); - tmp = _e9; - int _e12; bar.InterlockedAdd(96, -5, _e12); - tmp = _e12; - int _e15; bar.InterlockedAnd(96, 5, _e15); - tmp = _e15; - int _e18; bar.InterlockedOr(96, 5, _e18); - tmp = _e18; - int _e21; bar.InterlockedXor(96, 5, _e21); - tmp = _e21; - int _e24; bar.InterlockedMin(96, 5, _e24); - tmp = _e24; - int _e27; bar.InterlockedMax(96, 5, _e27); - tmp = _e27; - int _e30; bar.InterlockedExchange(96, 5, _e30); - tmp = _e30; + int _e10; bar.InterlockedAdd(96, 5, _e10); + tmp = _e10; + int _e13; bar.InterlockedAdd(96, -5, _e13); + tmp = _e13; + int _e16; bar.InterlockedAnd(96, 5, _e16); + tmp = _e16; + int _e19; bar.InterlockedOr(96, 5, _e19); + tmp = _e19; + int _e22; bar.InterlockedXor(96, 5, _e22); + tmp = _e22; + int _e25; bar.InterlockedMin(96, 5, _e25); + tmp = _e25; + int _e28; bar.InterlockedMax(96, 5, _e28); + tmp = _e28; + int _e31; bar.InterlockedExchange(96, 5, _e31); + tmp = _e31; bar.Store(96, asuint(value_1)); return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 2274aa428..def5c8dbb 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -1,5 +1,56 @@ static const bool Foo_2 = true; +typedef struct { float2 _0; float2 _1; float2 _2; } __mat3x2; +float2 __get_col_of_mat3x2(__mat3x2 mat, uint idx) { + switch(idx) { + case 0: { return mat._0; } + case 1: { return mat._1; } + case 2: { return mat._2; } + default: { return (float2)0; } + } +} +void __set_col_of_mat3x2(__mat3x2 mat, uint idx, float2 value) { + switch(idx) { + case 0: { mat._0 = value; break; } + case 1: { mat._1 = value; break; } + case 2: { mat._2 = value; break; } + } +} +void __set_el_of_mat3x2(__mat3x2 mat, uint idx, uint vec_idx, float value) { + switch(idx) { + case 0: { mat._0[vec_idx] = value; break; } + case 1: { mat._1[vec_idx] = value; break; } + case 2: { mat._2[vec_idx] = value; break; } + } +} + +typedef struct { float2 _0; float2 _1; float2 _2; float2 _3; } __mat4x2; +float2 __get_col_of_mat4x2(__mat4x2 mat, uint idx) { + switch(idx) { + case 0: { return mat._0; } + case 1: { return mat._1; } + case 2: { return mat._2; } + case 3: { return mat._3; } + default: { return (float2)0; } + } +} +void __set_col_of_mat4x2(__mat4x2 mat, uint idx, float2 value) { + switch(idx) { + case 0: { mat._0 = value; break; } + case 1: { mat._1 = value; break; } + case 2: { mat._2 = value; break; } + case 3: { mat._3 = value; break; } + } +} +void __set_el_of_mat4x2(__mat4x2 mat, uint idx, uint vec_idx, float value) { + switch(idx) { + case 0: { mat._0[vec_idx] = value; break; } + case 1: { mat._1[vec_idx] = value; break; } + case 2: { mat._2[vec_idx] = value; break; } + case 3: { mat._3[vec_idx] = value; break; } + } +} + struct Foo { float3 v3_; float v1_; @@ -10,8 +61,10 @@ groupshared uint at_1; RWByteAddressBuffer alignment : register(u1); ByteAddressBuffer dummy : register(t2); cbuffer float_vecs : register(b3) { float4 float_vecs[20]; } -cbuffer global_vec : register(b4) { float4 global_vec; } -cbuffer global_mat : register(b5) { row_major float4x4 global_mat; } +cbuffer global_vec : register(b4) { float3 global_vec; } +cbuffer global_mat : register(b5) { __mat3x2 global_mat; } +cbuffer global_nested_arrays_of_matrices_2x4_ : register(b6) { row_major float2x4 global_nested_arrays_of_matrices_2x4_[2][2]; } +cbuffer global_nested_arrays_of_matrices_4x2_ : register(b7) { __mat4x2 global_nested_arrays_of_matrices_4x2_[2][2]; } void test_msl_packed_vec3_as_arg(float3 arg) { @@ -32,8 +85,8 @@ void test_msl_packed_vec3_() alignment.Store3(0, asuint((1.0).xxx)); alignment.Store(0+0, asuint(1.0)); alignment.Store(0+0, asuint(2.0)); - int _expr21 = idx; - alignment.Store(_expr21*4+0, asuint(3.0)); + int _expr23 = idx; + alignment.Store(_expr23*4+0, asuint(3.0)); Foo data = ConstructFoo(asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))); float3 unnamed = data.v3_; float2 unnamed_1 = data.v3_.zx; @@ -58,17 +111,20 @@ void main() bool at = true; test_msl_packed_vec3_(); - float4x4 _expr10 = global_mat; - float4 _expr11 = global_vec; - wg[6] = mul(_expr11, _expr10).x; - float _expr19 = asfloat(dummy.Load(4+8)); - wg[5] = _expr19; - float _expr25 = float_vecs[0].w; - wg[4] = _expr25; - float _expr29 = asfloat(alignment.Load(12)); - wg[3] = _expr29; - float _expr34 = asfloat(alignment.Load(0+0)); - wg[2] = _expr34; + float4x2 _expr16 = ((float4x2)global_nested_arrays_of_matrices_4x2_[0][0]); + float4 _expr23 = global_nested_arrays_of_matrices_2x4_[0][0][0]; + wg[7] = mul(_expr23, _expr16).x; + float3x2 _expr28 = ((float3x2)global_mat); + float3 _expr29 = global_vec; + wg[6] = mul(_expr29, _expr28).x; + float _expr37 = asfloat(dummy.Load(4+8)); + wg[5] = _expr37; + float _expr43 = float_vecs[0].w; + wg[4] = _expr43; + float _expr47 = asfloat(alignment.Load(12)); + wg[3] = _expr47; + float _expr52 = asfloat(alignment.Load(0+0)); + wg[2] = _expr52; alignment.Store(12, asuint(4.0)); wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index ef4bf86a6..19e4ab21d 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -35,19 +35,28 @@ struct Bar { struct Baz { metal::float3x2 m; }; -struct type_14 { +struct type_13 { + metal::float4x2 inner[2]; +}; +struct MatCx2InArray { + type_13 am; +}; +struct type_17 { float inner[10]; }; -struct type_15 { - type_14 inner[5]; -}; struct type_18 { + type_17 inner[5]; +}; +struct type_21 { int inner[5]; }; constant metal::uint3 const_type_1_ = {0u, 0u, 0u}; constant GlobalConst const_GlobalConst = {0u, {}, const_type_1_, 0}; -constant type_14 const_type_14_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; -constant type_15 const_type_15_ = {const_type_14_, const_type_14_, const_type_14_, const_type_14_, const_type_14_}; +constant metal::float2 const_type_14_ = {0.0, 0.0}; +constant metal::float4x2 const_type_12_ = {const_type_14_, const_type_14_, const_type_14_, const_type_14_}; +constant type_13 const_type_13_ = {const_type_12_, const_type_12_}; +constant type_17 const_type_17_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; +constant type_18 const_type_18_ = {const_type_17_, const_type_17_, const_type_17_, const_type_17_, const_type_17_}; constant metal::int2 const_type_11_ = {0, 0}; void test_matrix_within_struct_accesses( @@ -87,15 +96,54 @@ void test_matrix_within_struct_accesses( return; } +void test_matrix_within_array_within_struct_accesses( + constant MatCx2InArray& nested_mat_cx2_ +) { + int idx_1 = 1; + MatCx2InArray t_1 = {}; + int _e7 = idx_1; + idx_1 = _e7 - 1; + type_13 unnamed_7 = nested_mat_cx2_.am; + metal::float4x2 unnamed_8 = nested_mat_cx2_.am.inner[0]; + metal::float2 unnamed_9 = nested_mat_cx2_.am.inner[0][0]; + int _e25 = idx_1; + metal::float2 unnamed_10 = nested_mat_cx2_.am.inner[0][_e25]; + float unnamed_11 = nested_mat_cx2_.am.inner[0][0].y; + int _e41 = idx_1; + float unnamed_12 = nested_mat_cx2_.am.inner[0][0][_e41]; + int _e47 = idx_1; + float unnamed_13 = nested_mat_cx2_.am.inner[0][_e47].y; + int _e55 = idx_1; + int _e57 = idx_1; + float unnamed_14 = nested_mat_cx2_.am.inner[0][_e55][_e57]; + t_1 = MatCx2InArray {const_type_13_}; + int _e63 = idx_1; + idx_1 = _e63 + 1; + for(int _i=0; _i<2; ++_i) t_1.am.inner[_i] = const_type_13_.inner[_i]; + t_1.am.inner[0] = metal::float4x2(metal::float2(8.0), metal::float2(7.0), metal::float2(6.0), metal::float2(5.0)); + t_1.am.inner[0][0] = metal::float2(9.0); + int _e90 = idx_1; + t_1.am.inner[0][_e90] = metal::float2(90.0); + t_1.am.inner[0][0].y = 10.0; + int _e107 = idx_1; + t_1.am.inner[0][0][_e107] = 20.0; + int _e113 = idx_1; + t_1.am.inner[0][_e113].y = 30.0; + int _e121 = idx_1; + int _e123 = idx_1; + t_1.am.inner[0][_e121][_e123] = 40.0; + return; +} + float read_from_private( thread float& foo_1 ) { - float _e5 = foo_1; - return _e5; + float _e6 = foo_1; + return _e6; } float test_arr_as_arg( - type_15 a + type_18 a ) { return a.inner[4].inner[9]; } @@ -117,23 +165,25 @@ vertex foo_vertOutput foo_vert( , device Bar const& bar [[buffer(0)]] , constant Baz& baz [[buffer(1)]] , device metal::int2 const& qux [[buffer(2)]] +, constant MatCx2InArray& nested_mat_cx2_ [[buffer(3)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo = 0.0; - type_18 c = {}; + type_21 c = {}; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); + test_matrix_within_array_within_struct_accesses(nested_mat_cx2_); metal::float4x3 _matrix = bar._matrix; type_8 arr = bar.arr; float b = bar._matrix[3].x; int a_1 = bar.data[(1 + (_buffer_sizes.size1 - 120 - 8) / 8) - 2u].value; metal::int2 c_1 = qux; - float _e31 = read_from_private(foo); - for(int _i=0; _i<5; ++_i) c.inner[_i] = type_18 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; + float _e32 = read_from_private(foo); + for(int _i=0; _i<5; ++_i) c.inner[_i] = type_21 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; c.inner[vi + 1u] = 42; int value = c.inner[vi]; - float _e45 = test_arr_as_arg(const_type_15_); + float _e46 = test_arr_as_arg(const_type_18_); return foo_vertOutput { metal::float4(_matrix * static_cast(metal::int4(value)), 2.0) }; } @@ -161,22 +211,22 @@ kernel void atomics( ) { int tmp = {}; int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); - int _e9 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e9; - int _e12 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e12; - int _e15 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e15; - int _e18 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e18; - int _e21 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e21; - int _e24 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e24; - int _e27 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e27; - int _e30 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e30; + int _e10 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e10; + int _e13 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e13; + int _e16 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e16; + int _e19 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e19; + int _e22 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e22; + int _e25 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e25; + int _e28 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e28; + int _e31 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e31; metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed); return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index b02d6056d..b461cce3f 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -20,8 +20,20 @@ typedef metal::float2 type_6[1]; struct type_8 { metal::float4 inner[20]; }; +struct type_11 { + metal::float2x4 inner[2]; +}; +struct type_12 { + type_11 inner[2]; +}; +struct type_14 { + metal::float4x2 inner[2]; +}; +struct type_15 { + type_14 inner[2]; +}; constant metal::float3 const_type_4_ = {0.0, 0.0, 0.0}; -constant metal::float3x3 const_type_11_ = {const_type_4_, const_type_4_, const_type_4_}; +constant metal::float3x3 const_type_17_ = {const_type_4_, const_type_4_, const_type_4_}; void test_msl_packed_vec3_as_arg( metal::float3 arg @@ -36,14 +48,14 @@ void test_msl_packed_vec3_( alignment.v3_ = metal::float3(1.0); alignment.v3_[0] = 1.0; alignment.v3_[0] = 2.0; - int _e21 = idx; - alignment.v3_[_e21] = 3.0; + int _e23 = idx; + alignment.v3_[_e23] = 3.0; Foo data = alignment; metal::float3 unnamed = data.v3_; metal::float2 unnamed_1 = metal::float3(data.v3_).zx; test_msl_packed_vec3_as_arg(data.v3_); - metal::float3 unnamed_2 = metal::float3(data.v3_) * const_type_11_; - metal::float3 unnamed_3 = const_type_11_ * metal::float3(data.v3_); + metal::float3 unnamed_2 = metal::float3(data.v3_) * const_type_17_; + metal::float3 unnamed_3 = const_type_17_ * metal::float3(data.v3_); metal::float3 unnamed_4 = data.v3_ * 2.0; metal::float3 unnamed_5 = 2.0 * data.v3_; } @@ -54,24 +66,29 @@ kernel void main_( , device Foo& alignment [[user(fake0)]] , device type_6 const& dummy [[user(fake0)]] , constant type_8& float_vecs [[user(fake0)]] -, constant metal::float4& global_vec [[user(fake0)]] -, constant metal::float4x4& global_mat [[user(fake0)]] +, constant metal::float3& global_vec [[user(fake0)]] +, constant metal::float3x2& global_mat [[user(fake0)]] +, constant type_12& global_nested_arrays_of_matrices_2x4_ [[user(fake0)]] +, constant type_15& global_nested_arrays_of_matrices_4x2_ [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { float Foo_1 = 1.0; bool at = true; test_msl_packed_vec3_(alignment); - metal::float4x4 _e10 = global_mat; - metal::float4 _e11 = global_vec; - wg.inner[6] = (_e10 * _e11).x; - float _e19 = dummy[1].y; - wg.inner[5] = _e19; - float _e25 = float_vecs.inner[0].w; - wg.inner[4] = _e25; - float _e29 = alignment.v1_; - wg.inner[3] = _e29; - float _e34 = alignment.v3_[0]; - wg.inner[2] = _e34; + metal::float4x2 _e16 = global_nested_arrays_of_matrices_4x2_.inner[0].inner[0]; + metal::float4 _e23 = global_nested_arrays_of_matrices_2x4_.inner[0].inner[0][0]; + wg.inner[7] = (_e16 * _e23).x; + metal::float3x2 _e28 = global_mat; + metal::float3 _e29 = global_vec; + wg.inner[6] = (_e28 * _e29).x; + float _e37 = dummy[1].y; + wg.inner[5] = _e37; + float _e43 = float_vecs.inner[0].w; + wg.inner[4] = _e43; + float _e47 = alignment.v1_; + wg.inner[3] = _e47; + float _e52 = alignment.v3_[0]; + wg.inner[2] = _e52; alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 218b08a74..fe7e75d4a 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,91 +1,105 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 248 +; Bound: 320 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %163 "foo_vert" %158 %161 -OpEntryPoint Fragment %202 "foo_frag" %201 -OpEntryPoint GLCompute %221 "atomics" -OpEntryPoint GLCompute %245 "assign_through_ptr" -OpExecutionMode %202 OriginUpperLeft -OpExecutionMode %221 LocalSize 1 1 1 -OpExecutionMode %245 LocalSize 1 1 1 +OpEntryPoint Vertex %233 "foo_vert" %228 %231 +OpEntryPoint Fragment %274 "foo_frag" %273 +OpEntryPoint GLCompute %293 "atomics" +OpEntryPoint GLCompute %317 "assign_through_ptr" +OpExecutionMode %274 OriginUpperLeft +OpExecutionMode %293 LocalSize 1 1 1 +OpExecutionMode %317 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %34 0 "a" -OpMemberName %34 1 "b" -OpMemberName %34 2 "c" -OpName %34 "GlobalConst" -OpMemberName %35 0 "value" -OpName %35 "AlignedWrapper" -OpMemberName %44 0 "_matrix" -OpMemberName %44 1 "matrix_array" -OpMemberName %44 2 "atom" -OpMemberName %44 3 "arr" -OpMemberName %44 4 "data" -OpName %44 "Bar" -OpMemberName %46 0 "m" -OpName %46 "Baz" -OpName %60 "global_const" -OpName %62 "bar" -OpName %64 "baz" -OpName %67 "qux" -OpName %70 "val" -OpName %71 "idx" -OpName %73 "t" -OpName %77 "test_matrix_within_struct_accesses" -OpName %136 "foo" -OpName %137 "read_from_private" -OpName %142 "a" -OpName %143 "test_arr_as_arg" -OpName %149 "p" -OpName %150 "assign_through_ptr_fn" -OpName %153 "foo" -OpName %154 "c" -OpName %158 "vi" -OpName %163 "foo_vert" -OpName %202 "foo_frag" -OpName %218 "tmp" -OpName %221 "atomics" -OpName %245 "assign_through_ptr" -OpMemberDecorate %34 0 Offset 0 -OpMemberDecorate %34 1 Offset 16 -OpMemberDecorate %34 2 Offset 28 -OpMemberDecorate %35 0 Offset 0 -OpDecorate %40 ArrayStride 16 -OpDecorate %42 ArrayStride 8 -OpDecorate %43 ArrayStride 8 -OpMemberDecorate %44 0 Offset 0 -OpMemberDecorate %44 0 ColMajor -OpMemberDecorate %44 0 MatrixStride 16 -OpMemberDecorate %44 1 Offset 64 -OpMemberDecorate %44 1 ColMajor -OpMemberDecorate %44 1 MatrixStride 8 -OpMemberDecorate %44 2 Offset 96 -OpMemberDecorate %44 3 Offset 104 -OpMemberDecorate %44 4 Offset 120 +OpMemberName %36 0 "a" +OpMemberName %36 1 "b" +OpMemberName %36 2 "c" +OpName %36 "GlobalConst" +OpMemberName %37 0 "value" +OpName %37 "AlignedWrapper" +OpMemberName %46 0 "_matrix" +OpMemberName %46 1 "matrix_array" +OpMemberName %46 2 "atom" +OpMemberName %46 3 "arr" +OpMemberName %46 4 "data" +OpName %46 "Bar" +OpMemberName %48 0 "m" +OpName %48 "Baz" +OpMemberName %52 0 "am" +OpName %52 "MatCx2InArray" +OpName %68 "global_const" +OpName %70 "bar" +OpName %72 "baz" +OpName %75 "qux" +OpName %78 "nested_mat_cx2" +OpName %81 "val" +OpName %82 "idx" +OpName %84 "t" +OpName %88 "test_matrix_within_struct_accesses" +OpName %146 "idx" +OpName %147 "t" +OpName %151 "test_matrix_within_array_within_struct_accesses" +OpName %206 "foo" +OpName %207 "read_from_private" +OpName %212 "a" +OpName %213 "test_arr_as_arg" +OpName %219 "p" +OpName %220 "assign_through_ptr_fn" +OpName %223 "foo" +OpName %224 "c" +OpName %228 "vi" +OpName %233 "foo_vert" +OpName %274 "foo_frag" +OpName %290 "tmp" +OpName %293 "atomics" +OpName %317 "assign_through_ptr" +OpMemberDecorate %36 0 Offset 0 +OpMemberDecorate %36 1 Offset 16 +OpMemberDecorate %36 2 Offset 28 +OpMemberDecorate %37 0 Offset 0 +OpDecorate %42 ArrayStride 16 +OpDecorate %44 ArrayStride 8 +OpDecorate %45 ArrayStride 8 OpMemberDecorate %46 0 Offset 0 OpMemberDecorate %46 0 ColMajor -OpMemberDecorate %46 0 MatrixStride 8 -OpDecorate %49 ArrayStride 4 -OpDecorate %50 ArrayStride 40 -OpDecorate %53 ArrayStride 4 -OpDecorate %62 DescriptorSet 0 -OpDecorate %62 Binding 0 -OpDecorate %44 Block -OpDecorate %64 DescriptorSet 0 -OpDecorate %64 Binding 1 -OpDecorate %65 Block -OpMemberDecorate %65 0 Offset 0 -OpDecorate %67 DescriptorSet 0 -OpDecorate %67 Binding 2 -OpDecorate %68 Block -OpMemberDecorate %68 0 Offset 0 -OpDecorate %158 BuiltIn VertexIndex -OpDecorate %161 BuiltIn Position -OpDecorate %201 Location 0 +OpMemberDecorate %46 0 MatrixStride 16 +OpMemberDecorate %46 1 Offset 64 +OpMemberDecorate %46 1 ColMajor +OpMemberDecorate %46 1 MatrixStride 8 +OpMemberDecorate %46 2 Offset 96 +OpMemberDecorate %46 3 Offset 104 +OpMemberDecorate %46 4 Offset 120 +OpMemberDecorate %48 0 Offset 0 +OpMemberDecorate %48 0 ColMajor +OpMemberDecorate %48 0 MatrixStride 8 +OpDecorate %51 ArrayStride 32 +OpMemberDecorate %52 0 Offset 0 +OpMemberDecorate %52 0 ColMajor +OpMemberDecorate %52 0 MatrixStride 8 +OpDecorate %54 ArrayStride 4 +OpDecorate %55 ArrayStride 40 +OpDecorate %58 ArrayStride 4 +OpDecorate %70 DescriptorSet 0 +OpDecorate %70 Binding 0 +OpDecorate %46 Block +OpDecorate %72 DescriptorSet 0 +OpDecorate %72 Binding 1 +OpDecorate %73 Block +OpMemberDecorate %73 0 Offset 0 +OpDecorate %75 DescriptorSet 0 +OpDecorate %75 Binding 2 +OpDecorate %76 Block +OpMemberDecorate %76 0 Offset 0 +OpDecorate %78 DescriptorSet 0 +OpDecorate %78 Binding 3 +OpDecorate %79 Block +OpMemberDecorate %79 0 Offset 0 +OpDecorate %228 BuiltIn VertexIndex +OpDecorate %231 BuiltIn Position +OpDecorate %273 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -106,283 +120,369 @@ OpDecorate %201 Location 0 %19 = OpConstant %10 20.0 %20 = OpConstant %10 30.0 %21 = OpConstant %10 40.0 -%22 = OpConstant %6 10 -%23 = OpConstant %6 5 -%24 = OpConstant %6 4 -%25 = OpConstant %6 9 -%26 = OpConstant %10 0.0 -%27 = OpConstant %4 3 -%28 = OpConstant %4 2 -%29 = OpConstant %6 3 -%30 = OpConstant %4 1 -%31 = OpConstant %6 42 -%32 = OpConstant %4 42 -%33 = OpTypeVector %4 3 -%34 = OpTypeStruct %4 %33 %6 -%35 = OpTypeStruct %6 -%37 = OpTypeVector %10 3 -%36 = OpTypeMatrix %37 4 -%39 = OpTypeVector %10 2 -%38 = OpTypeMatrix %39 2 -%40 = OpTypeArray %38 %7 -%41 = OpTypeVector %4 2 -%42 = OpTypeArray %41 %7 -%43 = OpTypeRuntimeArray %35 -%44 = OpTypeStruct %36 %40 %6 %42 %43 -%45 = OpTypeMatrix %39 3 -%46 = OpTypeStruct %45 -%47 = OpTypeVector %6 2 -%48 = OpTypePointer Function %10 -%49 = OpTypeArray %10 %22 -%50 = OpTypeArray %49 %23 -%51 = OpTypeVector %10 4 -%52 = OpTypePointer StorageBuffer %6 -%53 = OpTypeArray %6 %23 -%54 = OpTypePointer Workgroup %4 -%55 = OpConstantComposite %33 %3 %3 %3 -%56 = OpConstantComposite %34 %3 %55 %5 -%57 = OpConstantComposite %49 %26 %26 %26 %26 %26 %26 %26 %26 %26 %26 -%58 = OpConstantComposite %50 %57 %57 %57 %57 %57 -%59 = OpConstantComposite %47 %5 %5 -%61 = OpTypePointer Private %34 -%60 = OpVariable %61 Private %56 -%63 = OpTypePointer StorageBuffer %44 -%62 = OpVariable %63 StorageBuffer -%65 = OpTypeStruct %46 -%66 = OpTypePointer Uniform %65 -%64 = OpVariable %66 Uniform -%68 = OpTypeStruct %47 -%69 = OpTypePointer StorageBuffer %68 -%67 = OpVariable %69 StorageBuffer -%70 = OpVariable %54 Workgroup -%72 = OpTypePointer Function %6 -%74 = OpTypePointer Function %46 -%75 = OpConstantNull %46 -%78 = OpTypeFunction %2 -%79 = OpTypePointer Uniform %46 -%81 = OpTypePointer StorageBuffer %47 -%85 = OpTypePointer Uniform %45 -%88 = OpTypePointer Uniform %39 -%94 = OpTypePointer Uniform %10 -%114 = OpTypePointer Function %45 -%120 = OpTypePointer Function %39 -%126 = OpTypePointer Function %10 -%138 = OpTypeFunction %10 %48 -%144 = OpTypeFunction %10 %50 -%151 = OpTypeFunction %2 %54 -%155 = OpTypePointer Function %53 -%156 = OpConstantNull %53 -%159 = OpTypePointer Input %4 -%158 = OpVariable %159 Input -%162 = OpTypePointer Output %51 -%161 = OpVariable %162 Output -%169 = OpTypePointer StorageBuffer %36 -%172 = OpTypePointer StorageBuffer %42 -%175 = OpTypePointer StorageBuffer %37 -%176 = OpTypePointer StorageBuffer %10 -%179 = OpTypePointer StorageBuffer %43 -%182 = OpTypePointer StorageBuffer %35 -%183 = OpConstant %4 4 -%195 = OpTypeVector %6 4 -%201 = OpVariable %162 Output -%219 = OpConstantNull %6 -%223 = OpTypePointer StorageBuffer %6 -%226 = OpConstant %4 64 -%77 = OpFunction %2 None %78 -%76 = OpLabel -%71 = OpVariable %72 Function %8 -%73 = OpVariable %74 Function %75 -%80 = OpAccessChain %79 %64 %3 -OpBranch %82 -%82 = OpLabel -%83 = OpLoad %6 %71 -%84 = OpISub %6 %83 %8 -OpStore %71 %84 -%86 = OpAccessChain %85 %80 %3 -%87 = OpLoad %45 %86 -%89 = OpAccessChain %88 %80 %3 %3 -%90 = OpLoad %39 %89 -%91 = OpLoad %6 %71 -%92 = OpAccessChain %88 %80 %3 %91 -%93 = OpLoad %39 %92 -%95 = OpAccessChain %94 %80 %3 %3 %30 -%96 = OpLoad %10 %95 -%97 = OpLoad %6 %71 -%98 = OpAccessChain %94 %80 %3 %3 %97 -%99 = OpLoad %10 %98 -%100 = OpLoad %6 %71 -%101 = OpAccessChain %94 %80 %3 %100 %30 -%102 = OpLoad %10 %101 -%103 = OpLoad %6 %71 -%104 = OpLoad %6 %71 -%105 = OpAccessChain %94 %80 %3 %103 %104 -%106 = OpLoad %10 %105 -%107 = OpCompositeConstruct %39 %9 %9 -%108 = OpCompositeConstruct %39 %11 %11 -%109 = OpCompositeConstruct %39 %12 %12 -%110 = OpCompositeConstruct %45 %107 %108 %109 -%111 = OpCompositeConstruct %46 %110 -OpStore %73 %111 -%112 = OpLoad %6 %71 -%113 = OpIAdd %6 %112 %8 -OpStore %71 %113 -%115 = OpCompositeConstruct %39 %13 %13 -%116 = OpCompositeConstruct %39 %14 %14 -%117 = OpCompositeConstruct %39 %15 %15 -%118 = OpCompositeConstruct %45 %115 %116 %117 -%119 = OpAccessChain %114 %73 %3 -OpStore %119 %118 -%121 = OpCompositeConstruct %39 %16 %16 -%122 = OpAccessChain %120 %73 %3 %3 -OpStore %122 %121 -%123 = OpLoad %6 %71 -%124 = OpCompositeConstruct %39 %17 %17 -%125 = OpAccessChain %120 %73 %3 %123 -OpStore %125 %124 -%127 = OpAccessChain %126 %73 %3 %3 %30 -OpStore %127 %18 -%128 = OpLoad %6 %71 -%129 = OpAccessChain %126 %73 %3 %3 %128 -OpStore %129 %19 -%130 = OpLoad %6 %71 -%131 = OpAccessChain %126 %73 %3 %130 %30 -OpStore %131 %20 -%132 = OpLoad %6 %71 -%133 = OpLoad %6 %71 -%134 = OpAccessChain %126 %73 %3 %132 %133 -OpStore %134 %21 +%22 = OpConstant %10 0.0 +%23 = OpConstant %10 8.0 +%24 = OpConstant %10 7.0 +%25 = OpConstant %6 10 +%26 = OpConstant %6 5 +%27 = OpConstant %6 4 +%28 = OpConstant %6 9 +%29 = OpConstant %4 3 +%30 = OpConstant %4 2 +%31 = OpConstant %6 3 +%32 = OpConstant %4 1 +%33 = OpConstant %6 42 +%34 = OpConstant %4 42 +%35 = OpTypeVector %4 3 +%36 = OpTypeStruct %4 %35 %6 +%37 = OpTypeStruct %6 +%39 = OpTypeVector %10 3 +%38 = OpTypeMatrix %39 4 +%41 = OpTypeVector %10 2 +%40 = OpTypeMatrix %41 2 +%42 = OpTypeArray %40 %7 +%43 = OpTypeVector %4 2 +%44 = OpTypeArray %43 %7 +%45 = OpTypeRuntimeArray %37 +%46 = OpTypeStruct %38 %42 %6 %44 %45 +%47 = OpTypeMatrix %41 3 +%48 = OpTypeStruct %47 +%49 = OpTypeVector %6 2 +%50 = OpTypeMatrix %41 4 +%51 = OpTypeArray %50 %7 +%52 = OpTypeStruct %51 +%53 = OpTypePointer Function %10 +%54 = OpTypeArray %10 %25 +%55 = OpTypeArray %54 %26 +%56 = OpTypeVector %10 4 +%57 = OpTypePointer StorageBuffer %6 +%58 = OpTypeArray %6 %26 +%59 = OpTypePointer Workgroup %4 +%60 = OpConstantComposite %35 %3 %3 %3 +%61 = OpConstantComposite %36 %3 %60 %5 +%62 = OpConstantComposite %41 %22 %22 +%63 = OpConstantComposite %50 %62 %62 %62 %62 +%64 = OpConstantComposite %51 %63 %63 +%65 = OpConstantComposite %54 %22 %22 %22 %22 %22 %22 %22 %22 %22 %22 +%66 = OpConstantComposite %55 %65 %65 %65 %65 %65 +%67 = OpConstantComposite %49 %5 %5 +%69 = OpTypePointer Private %36 +%68 = OpVariable %69 Private %61 +%71 = OpTypePointer StorageBuffer %46 +%70 = OpVariable %71 StorageBuffer +%73 = OpTypeStruct %48 +%74 = OpTypePointer Uniform %73 +%72 = OpVariable %74 Uniform +%76 = OpTypeStruct %49 +%77 = OpTypePointer StorageBuffer %76 +%75 = OpVariable %77 StorageBuffer +%79 = OpTypeStruct %52 +%80 = OpTypePointer Uniform %79 +%78 = OpVariable %80 Uniform +%81 = OpVariable %59 Workgroup +%83 = OpTypePointer Function %6 +%85 = OpTypePointer Function %48 +%86 = OpConstantNull %48 +%89 = OpTypeFunction %2 +%90 = OpTypePointer Uniform %48 +%92 = OpTypePointer StorageBuffer %49 +%96 = OpTypePointer Uniform %47 +%99 = OpTypePointer Uniform %41 +%105 = OpTypePointer Uniform %10 +%125 = OpTypePointer Function %47 +%131 = OpTypePointer Function %41 +%137 = OpTypePointer Function %10 +%148 = OpTypePointer Function %52 +%149 = OpConstantNull %52 +%152 = OpTypePointer Uniform %52 +%157 = OpTypePointer Uniform %51 +%160 = OpTypePointer Uniform %50 +%183 = OpTypePointer Function %51 +%185 = OpTypePointer Function %50 +%208 = OpTypeFunction %10 %53 +%214 = OpTypeFunction %10 %55 +%221 = OpTypeFunction %2 %59 +%225 = OpTypePointer Function %58 +%226 = OpConstantNull %58 +%229 = OpTypePointer Input %4 +%228 = OpVariable %229 Input +%232 = OpTypePointer Output %56 +%231 = OpVariable %232 Output +%241 = OpTypePointer StorageBuffer %38 +%244 = OpTypePointer StorageBuffer %44 +%247 = OpTypePointer StorageBuffer %39 +%248 = OpTypePointer StorageBuffer %10 +%251 = OpTypePointer StorageBuffer %45 +%254 = OpTypePointer StorageBuffer %37 +%255 = OpConstant %4 4 +%267 = OpTypeVector %6 4 +%273 = OpVariable %232 Output +%291 = OpConstantNull %6 +%295 = OpTypePointer StorageBuffer %6 +%298 = OpConstant %4 64 +%88 = OpFunction %2 None %89 +%87 = OpLabel +%82 = OpVariable %83 Function %8 +%84 = OpVariable %85 Function %86 +%91 = OpAccessChain %90 %72 %3 +OpBranch %93 +%93 = OpLabel +%94 = OpLoad %6 %82 +%95 = OpISub %6 %94 %8 +OpStore %82 %95 +%97 = OpAccessChain %96 %91 %3 +%98 = OpLoad %47 %97 +%100 = OpAccessChain %99 %91 %3 %3 +%101 = OpLoad %41 %100 +%102 = OpLoad %6 %82 +%103 = OpAccessChain %99 %91 %3 %102 +%104 = OpLoad %41 %103 +%106 = OpAccessChain %105 %91 %3 %3 %32 +%107 = OpLoad %10 %106 +%108 = OpLoad %6 %82 +%109 = OpAccessChain %105 %91 %3 %3 %108 +%110 = OpLoad %10 %109 +%111 = OpLoad %6 %82 +%112 = OpAccessChain %105 %91 %3 %111 %32 +%113 = OpLoad %10 %112 +%114 = OpLoad %6 %82 +%115 = OpLoad %6 %82 +%116 = OpAccessChain %105 %91 %3 %114 %115 +%117 = OpLoad %10 %116 +%118 = OpCompositeConstruct %41 %9 %9 +%119 = OpCompositeConstruct %41 %11 %11 +%120 = OpCompositeConstruct %41 %12 %12 +%121 = OpCompositeConstruct %47 %118 %119 %120 +%122 = OpCompositeConstruct %48 %121 +OpStore %84 %122 +%123 = OpLoad %6 %82 +%124 = OpIAdd %6 %123 %8 +OpStore %82 %124 +%126 = OpCompositeConstruct %41 %13 %13 +%127 = OpCompositeConstruct %41 %14 %14 +%128 = OpCompositeConstruct %41 %15 %15 +%129 = OpCompositeConstruct %47 %126 %127 %128 +%130 = OpAccessChain %125 %84 %3 +OpStore %130 %129 +%132 = OpCompositeConstruct %41 %16 %16 +%133 = OpAccessChain %131 %84 %3 %3 +OpStore %133 %132 +%134 = OpLoad %6 %82 +%135 = OpCompositeConstruct %41 %17 %17 +%136 = OpAccessChain %131 %84 %3 %134 +OpStore %136 %135 +%138 = OpAccessChain %137 %84 %3 %3 %32 +OpStore %138 %18 +%139 = OpLoad %6 %82 +%140 = OpAccessChain %137 %84 %3 %3 %139 +OpStore %140 %19 +%141 = OpLoad %6 %82 +%142 = OpAccessChain %137 %84 %3 %141 %32 +OpStore %142 %20 +%143 = OpLoad %6 %82 +%144 = OpLoad %6 %82 +%145 = OpAccessChain %137 %84 %3 %143 %144 +OpStore %145 %21 OpReturn OpFunctionEnd -%137 = OpFunction %10 None %138 -%136 = OpFunctionParameter %48 -%135 = OpLabel -OpBranch %139 -%139 = OpLabel -%140 = OpLoad %10 %136 -OpReturnValue %140 -OpFunctionEnd -%143 = OpFunction %10 None %144 -%142 = OpFunctionParameter %50 -%141 = OpLabel -OpBranch %145 -%145 = OpLabel -%146 = OpCompositeExtract %49 %142 4 -%147 = OpCompositeExtract %10 %146 9 -OpReturnValue %147 -OpFunctionEnd -%150 = OpFunction %2 None %151 -%149 = OpFunctionParameter %54 -%148 = OpLabel -OpBranch %152 -%152 = OpLabel -OpStore %149 %32 +%151 = OpFunction %2 None %89 +%150 = OpLabel +%146 = OpVariable %83 Function %8 +%147 = OpVariable %148 Function %149 +%153 = OpAccessChain %152 %78 %3 +OpBranch %154 +%154 = OpLabel +%155 = OpLoad %6 %146 +%156 = OpISub %6 %155 %8 +OpStore %146 %156 +%158 = OpAccessChain %157 %153 %3 +%159 = OpLoad %51 %158 +%161 = OpAccessChain %160 %153 %3 %3 +%162 = OpLoad %50 %161 +%163 = OpAccessChain %99 %153 %3 %3 %3 +%164 = OpLoad %41 %163 +%165 = OpLoad %6 %146 +%166 = OpAccessChain %99 %153 %3 %3 %165 +%167 = OpLoad %41 %166 +%168 = OpAccessChain %105 %153 %3 %3 %3 %32 +%169 = OpLoad %10 %168 +%170 = OpLoad %6 %146 +%171 = OpAccessChain %105 %153 %3 %3 %3 %170 +%172 = OpLoad %10 %171 +%173 = OpLoad %6 %146 +%174 = OpAccessChain %105 %153 %3 %3 %173 %32 +%175 = OpLoad %10 %174 +%176 = OpLoad %6 %146 +%177 = OpLoad %6 %146 +%178 = OpAccessChain %105 %153 %3 %3 %176 %177 +%179 = OpLoad %10 %178 +%180 = OpCompositeConstruct %52 %64 +OpStore %147 %180 +%181 = OpLoad %6 %146 +%182 = OpIAdd %6 %181 %8 +OpStore %146 %182 +%184 = OpAccessChain %183 %147 %3 +OpStore %184 %64 +%186 = OpCompositeConstruct %41 %23 %23 +%187 = OpCompositeConstruct %41 %24 %24 +%188 = OpCompositeConstruct %41 %13 %13 +%189 = OpCompositeConstruct %41 %14 %14 +%190 = OpCompositeConstruct %50 %186 %187 %188 %189 +%191 = OpAccessChain %185 %147 %3 %3 +OpStore %191 %190 +%192 = OpCompositeConstruct %41 %16 %16 +%193 = OpAccessChain %131 %147 %3 %3 %3 +OpStore %193 %192 +%194 = OpLoad %6 %146 +%195 = OpCompositeConstruct %41 %17 %17 +%196 = OpAccessChain %131 %147 %3 %3 %194 +OpStore %196 %195 +%197 = OpAccessChain %137 %147 %3 %3 %3 %32 +OpStore %197 %18 +%198 = OpLoad %6 %146 +%199 = OpAccessChain %137 %147 %3 %3 %3 %198 +OpStore %199 %19 +%200 = OpLoad %6 %146 +%201 = OpAccessChain %137 %147 %3 %3 %200 %32 +OpStore %201 %20 +%202 = OpLoad %6 %146 +%203 = OpLoad %6 %146 +%204 = OpAccessChain %137 %147 %3 %3 %202 %203 +OpStore %204 %21 OpReturn OpFunctionEnd -%163 = OpFunction %2 None %78 -%157 = OpLabel -%153 = OpVariable %48 Function %26 -%154 = OpVariable %155 Function %156 -%160 = OpLoad %4 %158 -%164 = OpAccessChain %79 %64 %3 -%165 = OpAccessChain %81 %67 %3 -OpBranch %166 -%166 = OpLabel -%167 = OpLoad %10 %153 -OpStore %153 %9 -%168 = OpFunctionCall %2 %77 -%170 = OpAccessChain %169 %62 %3 -%171 = OpLoad %36 %170 -%173 = OpAccessChain %172 %62 %27 -%174 = OpLoad %42 %173 -%177 = OpAccessChain %176 %62 %3 %27 %3 -%178 = OpLoad %10 %177 -%180 = OpArrayLength %4 %62 4 -%181 = OpISub %4 %180 %28 -%184 = OpAccessChain %52 %62 %183 %181 %3 -%185 = OpLoad %6 %184 -%186 = OpLoad %47 %165 -%187 = OpFunctionCall %10 %137 %153 -%188 = OpConvertFToS %6 %178 -%189 = OpCompositeConstruct %53 %185 %188 %29 %24 %23 -OpStore %154 %189 -%190 = OpIAdd %4 %160 %30 -%191 = OpAccessChain %72 %154 %190 -OpStore %191 %31 -%192 = OpAccessChain %72 %154 %160 -%193 = OpLoad %6 %192 -%194 = OpFunctionCall %10 %143 %58 -%196 = OpCompositeConstruct %195 %193 %193 %193 %193 -%197 = OpConvertSToF %51 %196 -%198 = OpMatrixTimesVector %37 %171 %197 -%199 = OpCompositeConstruct %51 %198 %11 -OpStore %161 %199 -OpReturn +%207 = OpFunction %10 None %208 +%206 = OpFunctionParameter %53 +%205 = OpLabel +OpBranch %209 +%209 = OpLabel +%210 = OpLoad %10 %206 +OpReturnValue %210 OpFunctionEnd -%202 = OpFunction %2 None %78 -%200 = OpLabel -%203 = OpAccessChain %81 %67 %3 -OpBranch %204 -%204 = OpLabel -%205 = OpAccessChain %176 %62 %3 %30 %28 -OpStore %205 %9 -%206 = OpCompositeConstruct %37 %26 %26 %26 -%207 = OpCompositeConstruct %37 %9 %9 %9 -%208 = OpCompositeConstruct %37 %11 %11 %11 -%209 = OpCompositeConstruct %37 %12 %12 %12 -%210 = OpCompositeConstruct %36 %206 %207 %208 %209 -%211 = OpAccessChain %169 %62 %3 -OpStore %211 %210 -%212 = OpCompositeConstruct %41 %3 %3 -%213 = OpCompositeConstruct %41 %30 %30 -%214 = OpCompositeConstruct %42 %212 %213 -%215 = OpAccessChain %172 %62 %27 -OpStore %215 %214 -%216 = OpAccessChain %52 %62 %183 %30 %3 -OpStore %216 %8 -OpStore %203 %59 -%217 = OpCompositeConstruct %51 %26 %26 %26 %26 -OpStore %201 %217 -OpReturn +%213 = OpFunction %10 None %214 +%212 = OpFunctionParameter %55 +%211 = OpLabel +OpBranch %215 +%215 = OpLabel +%216 = OpCompositeExtract %54 %212 4 +%217 = OpCompositeExtract %10 %216 9 +OpReturnValue %217 OpFunctionEnd -%221 = OpFunction %2 None %78 -%220 = OpLabel -%218 = OpVariable %72 Function %219 +%220 = OpFunction %2 None %221 +%219 = OpFunctionParameter %59 +%218 = OpLabel OpBranch %222 %222 = OpLabel -%224 = OpAccessChain %223 %62 %28 -%225 = OpAtomicLoad %6 %224 %8 %226 -%228 = OpAccessChain %223 %62 %28 -%227 = OpAtomicIAdd %6 %228 %8 %226 %23 -OpStore %218 %227 -%230 = OpAccessChain %223 %62 %28 -%229 = OpAtomicISub %6 %230 %8 %226 %23 -OpStore %218 %229 -%232 = OpAccessChain %223 %62 %28 -%231 = OpAtomicAnd %6 %232 %8 %226 %23 -OpStore %218 %231 -%234 = OpAccessChain %223 %62 %28 -%233 = OpAtomicOr %6 %234 %8 %226 %23 -OpStore %218 %233 -%236 = OpAccessChain %223 %62 %28 -%235 = OpAtomicXor %6 %236 %8 %226 %23 -OpStore %218 %235 -%238 = OpAccessChain %223 %62 %28 -%237 = OpAtomicSMin %6 %238 %8 %226 %23 -OpStore %218 %237 -%240 = OpAccessChain %223 %62 %28 -%239 = OpAtomicSMax %6 %240 %8 %226 %23 -OpStore %218 %239 -%242 = OpAccessChain %223 %62 %28 -%241 = OpAtomicExchange %6 %242 %8 %226 %23 -OpStore %218 %241 -%243 = OpAccessChain %223 %62 %28 -OpAtomicStore %243 %8 %226 %225 +OpStore %219 %34 OpReturn OpFunctionEnd -%245 = OpFunction %2 None %78 -%244 = OpLabel -OpBranch %246 -%246 = OpLabel -%247 = OpFunctionCall %2 %150 %70 +%233 = OpFunction %2 None %89 +%227 = OpLabel +%223 = OpVariable %53 Function %22 +%224 = OpVariable %225 Function %226 +%230 = OpLoad %4 %228 +%234 = OpAccessChain %90 %72 %3 +%235 = OpAccessChain %92 %75 %3 +%236 = OpAccessChain %152 %78 %3 +OpBranch %237 +%237 = OpLabel +%238 = OpLoad %10 %223 +OpStore %223 %9 +%239 = OpFunctionCall %2 %88 +%240 = OpFunctionCall %2 %151 +%242 = OpAccessChain %241 %70 %3 +%243 = OpLoad %38 %242 +%245 = OpAccessChain %244 %70 %29 +%246 = OpLoad %44 %245 +%249 = OpAccessChain %248 %70 %3 %29 %3 +%250 = OpLoad %10 %249 +%252 = OpArrayLength %4 %70 4 +%253 = OpISub %4 %252 %30 +%256 = OpAccessChain %57 %70 %255 %253 %3 +%257 = OpLoad %6 %256 +%258 = OpLoad %49 %235 +%259 = OpFunctionCall %10 %207 %223 +%260 = OpConvertFToS %6 %250 +%261 = OpCompositeConstruct %58 %257 %260 %31 %27 %26 +OpStore %224 %261 +%262 = OpIAdd %4 %230 %32 +%263 = OpAccessChain %83 %224 %262 +OpStore %263 %33 +%264 = OpAccessChain %83 %224 %230 +%265 = OpLoad %6 %264 +%266 = OpFunctionCall %10 %213 %66 +%268 = OpCompositeConstruct %267 %265 %265 %265 %265 +%269 = OpConvertSToF %56 %268 +%270 = OpMatrixTimesVector %39 %243 %269 +%271 = OpCompositeConstruct %56 %270 %11 +OpStore %231 %271 +OpReturn +OpFunctionEnd +%274 = OpFunction %2 None %89 +%272 = OpLabel +%275 = OpAccessChain %92 %75 %3 +OpBranch %276 +%276 = OpLabel +%277 = OpAccessChain %248 %70 %3 %32 %30 +OpStore %277 %9 +%278 = OpCompositeConstruct %39 %22 %22 %22 +%279 = OpCompositeConstruct %39 %9 %9 %9 +%280 = OpCompositeConstruct %39 %11 %11 %11 +%281 = OpCompositeConstruct %39 %12 %12 %12 +%282 = OpCompositeConstruct %38 %278 %279 %280 %281 +%283 = OpAccessChain %241 %70 %3 +OpStore %283 %282 +%284 = OpCompositeConstruct %43 %3 %3 +%285 = OpCompositeConstruct %43 %32 %32 +%286 = OpCompositeConstruct %44 %284 %285 +%287 = OpAccessChain %244 %70 %29 +OpStore %287 %286 +%288 = OpAccessChain %57 %70 %255 %32 %3 +OpStore %288 %8 +OpStore %275 %67 +%289 = OpCompositeConstruct %56 %22 %22 %22 %22 +OpStore %273 %289 +OpReturn +OpFunctionEnd +%293 = OpFunction %2 None %89 +%292 = OpLabel +%290 = OpVariable %83 Function %291 +OpBranch %294 +%294 = OpLabel +%296 = OpAccessChain %295 %70 %30 +%297 = OpAtomicLoad %6 %296 %8 %298 +%300 = OpAccessChain %295 %70 %30 +%299 = OpAtomicIAdd %6 %300 %8 %298 %26 +OpStore %290 %299 +%302 = OpAccessChain %295 %70 %30 +%301 = OpAtomicISub %6 %302 %8 %298 %26 +OpStore %290 %301 +%304 = OpAccessChain %295 %70 %30 +%303 = OpAtomicAnd %6 %304 %8 %298 %26 +OpStore %290 %303 +%306 = OpAccessChain %295 %70 %30 +%305 = OpAtomicOr %6 %306 %8 %298 %26 +OpStore %290 %305 +%308 = OpAccessChain %295 %70 %30 +%307 = OpAtomicXor %6 %308 %8 %298 %26 +OpStore %290 %307 +%310 = OpAccessChain %295 %70 %30 +%309 = OpAtomicSMin %6 %310 %8 %298 %26 +OpStore %290 %309 +%312 = OpAccessChain %295 %70 %30 +%311 = OpAtomicSMax %6 %312 %8 %298 %26 +OpStore %290 %311 +%314 = OpAccessChain %295 %70 %30 +%313 = OpAtomicExchange %6 %314 %8 %298 %26 +OpStore %290 %313 +%315 = OpAccessChain %295 %70 %30 +OpAtomicStore %315 %8 %298 %297 +OpReturn +OpFunctionEnd +%317 = OpFunction %2 None %89 +%316 = OpLabel +OpBranch %318 +%318 = OpLabel +%319 = OpFunctionCall %2 %220 %81 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 8109c3ebf..2c1691c0c 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,41 +1,53 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 138 +; Bound: 169 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %99 "main" -OpExecutionMode %99 LocalSize 1 1 1 -OpDecorate %24 ArrayStride 4 -OpMemberDecorate %26 0 Offset 0 -OpMemberDecorate %26 1 Offset 12 -OpDecorate %28 ArrayStride 8 -OpDecorate %30 ArrayStride 16 -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 1 -OpDecorate %40 Block -OpMemberDecorate %40 0 Offset 0 -OpDecorate %42 NonWritable -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 2 -OpDecorate %43 Block -OpMemberDecorate %43 0 Offset 0 -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 3 -OpDecorate %46 Block -OpMemberDecorate %46 0 Offset 0 -OpDecorate %48 DescriptorSet 0 -OpDecorate %48 Binding 4 -OpDecorate %49 Block -OpMemberDecorate %49 0 Offset 0 -OpDecorate %51 DescriptorSet 0 -OpDecorate %51 Binding 5 -OpDecorate %52 Block -OpMemberDecorate %52 0 Offset 0 -OpMemberDecorate %52 0 ColMajor -OpMemberDecorate %52 0 MatrixStride 16 +OpEntryPoint GLCompute %114 "main" +OpExecutionMode %114 LocalSize 1 1 1 +OpDecorate %25 ArrayStride 4 +OpMemberDecorate %27 0 Offset 0 +OpMemberDecorate %27 1 Offset 12 +OpDecorate %29 ArrayStride 8 +OpDecorate %31 ArrayStride 16 +OpDecorate %34 ArrayStride 32 +OpDecorate %35 ArrayStride 64 +OpDecorate %37 ArrayStride 32 +OpDecorate %38 ArrayStride 64 +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 1 +OpDecorate %47 Block +OpMemberDecorate %47 0 Offset 0 +OpDecorate %49 NonWritable +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 2 +OpDecorate %50 Block +OpMemberDecorate %50 0 Offset 0 +OpDecorate %52 DescriptorSet 0 +OpDecorate %52 Binding 3 +OpDecorate %53 Block +OpMemberDecorate %53 0 Offset 0 +OpDecorate %55 DescriptorSet 0 +OpDecorate %55 Binding 4 +OpDecorate %56 Block +OpMemberDecorate %56 0 Offset 0 +OpDecorate %58 DescriptorSet 0 +OpDecorate %58 Binding 5 +OpDecorate %59 Block +OpMemberDecorate %59 0 Offset 0 +OpMemberDecorate %59 0 ColMajor +OpMemberDecorate %59 0 MatrixStride 8 +OpDecorate %61 DescriptorSet 0 +OpDecorate %61 Binding 6 +OpDecorate %62 Block +OpMemberDecorate %62 0 Offset 0 +OpDecorate %64 DescriptorSet 0 +OpDecorate %64 Binding 7 +OpDecorate %65 Block +OpMemberDecorate %65 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -43,153 +55,185 @@ OpMemberDecorate %52 0 MatrixStride 16 %5 = OpConstant %6 10 %8 = OpTypeInt 32 1 %7 = OpConstant %8 20 -%10 = OpTypeFloat 32 -%9 = OpConstant %10 1.0 -%11 = OpConstant %8 1 -%12 = OpConstant %8 0 -%13 = OpConstant %10 2.0 -%14 = OpConstant %10 3.0 -%15 = OpConstant %10 0.0 -%16 = OpConstant %8 6 -%17 = OpConstant %8 5 -%18 = OpConstant %8 4 -%19 = OpConstant %8 3 -%20 = OpConstant %8 2 -%21 = OpConstant %10 4.0 -%22 = OpConstant %6 2 -%23 = OpConstantTrue %4 -%24 = OpTypeArray %10 %5 -%25 = OpTypeVector %10 3 -%26 = OpTypeStruct %25 %10 -%27 = OpTypeVector %10 2 -%28 = OpTypeRuntimeArray %27 -%29 = OpTypeVector %10 4 -%30 = OpTypeArray %29 %7 -%31 = OpTypeMatrix %29 4 -%32 = OpTypeMatrix %25 3 -%33 = OpConstantComposite %25 %15 %15 %15 -%34 = OpConstantComposite %32 %33 %33 %33 -%36 = OpTypePointer Workgroup %24 -%35 = OpVariable %36 Workgroup -%38 = OpTypePointer Workgroup %6 -%37 = OpVariable %38 Workgroup -%40 = OpTypeStruct %26 -%41 = OpTypePointer StorageBuffer %40 -%39 = OpVariable %41 StorageBuffer -%43 = OpTypeStruct %28 -%44 = OpTypePointer StorageBuffer %43 -%42 = OpVariable %44 StorageBuffer -%46 = OpTypeStruct %30 -%47 = OpTypePointer Uniform %46 -%45 = OpVariable %47 Uniform -%49 = OpTypeStruct %29 -%50 = OpTypePointer Uniform %49 -%48 = OpVariable %50 Uniform -%52 = OpTypeStruct %31 -%53 = OpTypePointer Uniform %52 -%51 = OpVariable %53 Uniform -%57 = OpTypeFunction %2 %25 -%58 = OpTypePointer StorageBuffer %28 -%59 = OpTypePointer Uniform %29 -%60 = OpTypePointer StorageBuffer %26 -%61 = OpTypePointer Uniform %30 -%62 = OpTypePointer Uniform %31 -%65 = OpTypePointer Function %8 -%68 = OpTypeFunction %2 -%69 = OpConstant %6 0 -%72 = OpTypePointer StorageBuffer %25 -%75 = OpTypePointer StorageBuffer %10 -%95 = OpTypePointer Function %10 -%97 = OpTypePointer Function %4 -%107 = OpTypePointer Workgroup %10 -%112 = OpConstant %6 6 -%114 = OpTypePointer StorageBuffer %27 -%115 = OpConstant %6 1 -%118 = OpConstant %6 5 -%120 = OpTypePointer Uniform %10 -%121 = OpConstant %6 3 -%124 = OpConstant %6 4 -%126 = OpTypePointer StorageBuffer %10 -%137 = OpConstant %6 256 -%56 = OpFunction %2 None %57 -%55 = OpFunctionParameter %25 -%54 = OpLabel -OpBranch %63 -%63 = OpLabel +%9 = OpConstant %8 2 +%11 = OpTypeFloat 32 +%10 = OpConstant %11 1.0 +%12 = OpConstant %8 1 +%13 = OpConstant %8 0 +%14 = OpConstant %11 2.0 +%15 = OpConstant %11 3.0 +%16 = OpConstant %11 0.0 +%17 = OpConstant %8 7 +%18 = OpConstant %8 6 +%19 = OpConstant %8 5 +%20 = OpConstant %8 4 +%21 = OpConstant %8 3 +%22 = OpConstant %11 4.0 +%23 = OpConstant %6 2 +%24 = OpConstantTrue %4 +%25 = OpTypeArray %11 %5 +%26 = OpTypeVector %11 3 +%27 = OpTypeStruct %26 %11 +%28 = OpTypeVector %11 2 +%29 = OpTypeRuntimeArray %28 +%30 = OpTypeVector %11 4 +%31 = OpTypeArray %30 %7 +%32 = OpTypeMatrix %28 3 +%33 = OpTypeMatrix %30 2 +%34 = OpTypeArray %33 %9 +%35 = OpTypeArray %34 %9 +%36 = OpTypeMatrix %28 4 +%37 = OpTypeArray %36 %9 +%38 = OpTypeArray %37 %9 +%39 = OpTypeMatrix %26 3 +%40 = OpConstantComposite %26 %16 %16 %16 +%41 = OpConstantComposite %39 %40 %40 %40 +%43 = OpTypePointer Workgroup %25 +%42 = OpVariable %43 Workgroup +%45 = OpTypePointer Workgroup %6 +%44 = OpVariable %45 Workgroup +%47 = OpTypeStruct %27 +%48 = OpTypePointer StorageBuffer %47 +%46 = OpVariable %48 StorageBuffer +%50 = OpTypeStruct %29 +%51 = OpTypePointer StorageBuffer %50 +%49 = OpVariable %51 StorageBuffer +%53 = OpTypeStruct %31 +%54 = OpTypePointer Uniform %53 +%52 = OpVariable %54 Uniform +%56 = OpTypeStruct %26 +%57 = OpTypePointer Uniform %56 +%55 = OpVariable %57 Uniform +%59 = OpTypeStruct %32 +%60 = OpTypePointer Uniform %59 +%58 = OpVariable %60 Uniform +%62 = OpTypeStruct %35 +%63 = OpTypePointer Uniform %62 +%61 = OpVariable %63 Uniform +%65 = OpTypeStruct %38 +%66 = OpTypePointer Uniform %65 +%64 = OpVariable %66 Uniform +%70 = OpTypeFunction %2 %26 +%71 = OpTypePointer StorageBuffer %29 +%72 = OpTypePointer Uniform %26 +%73 = OpTypePointer StorageBuffer %27 +%74 = OpTypePointer Uniform %35 +%75 = OpTypePointer Uniform %31 +%76 = OpTypePointer Uniform %38 +%77 = OpTypePointer Uniform %32 +%80 = OpTypePointer Function %8 +%83 = OpTypeFunction %2 +%84 = OpConstant %6 0 +%87 = OpTypePointer StorageBuffer %26 +%90 = OpTypePointer StorageBuffer %11 +%110 = OpTypePointer Function %11 +%112 = OpTypePointer Function %4 +%124 = OpTypePointer Workgroup %11 +%125 = OpTypePointer Uniform %37 +%126 = OpTypePointer Uniform %36 +%129 = OpTypePointer Uniform %34 +%130 = OpTypePointer Uniform %33 +%131 = OpTypePointer Uniform %30 +%136 = OpConstant %6 7 +%142 = OpConstant %6 6 +%144 = OpTypePointer StorageBuffer %28 +%145 = OpConstant %6 1 +%148 = OpConstant %6 5 +%150 = OpTypePointer Uniform %30 +%151 = OpTypePointer Uniform %11 +%152 = OpConstant %6 3 +%155 = OpConstant %6 4 +%157 = OpTypePointer StorageBuffer %11 +%168 = OpConstant %6 256 +%69 = OpFunction %2 None %70 +%68 = OpFunctionParameter %26 +%67 = OpLabel +OpBranch %78 +%78 = OpLabel OpReturn OpFunctionEnd -%67 = OpFunction %2 None %68 -%66 = OpLabel -%64 = OpVariable %65 Function %11 -%70 = OpAccessChain %60 %39 %69 -OpBranch %71 -%71 = OpLabel -%73 = OpCompositeConstruct %25 %9 %9 %9 -%74 = OpAccessChain %72 %70 %69 -OpStore %74 %73 -%76 = OpAccessChain %75 %70 %69 %69 -OpStore %76 %9 -%77 = OpAccessChain %75 %70 %69 %69 -OpStore %77 %13 -%78 = OpLoad %8 %64 -%79 = OpAccessChain %75 %70 %69 %78 -OpStore %79 %14 -%80 = OpLoad %26 %70 -%81 = OpCompositeExtract %25 %80 0 -%82 = OpCompositeExtract %25 %80 0 -%83 = OpVectorShuffle %27 %82 %82 2 0 -%84 = OpCompositeExtract %25 %80 0 -%85 = OpFunctionCall %2 %56 %84 -%86 = OpCompositeExtract %25 %80 0 -%87 = OpVectorTimesMatrix %25 %86 %34 -%88 = OpCompositeExtract %25 %80 0 -%89 = OpMatrixTimesVector %25 %34 %88 -%90 = OpCompositeExtract %25 %80 0 -%91 = OpVectorTimesScalar %25 %90 %13 -%92 = OpCompositeExtract %25 %80 0 -%93 = OpVectorTimesScalar %25 %92 %13 +%82 = OpFunction %2 None %83 +%81 = OpLabel +%79 = OpVariable %80 Function %12 +%85 = OpAccessChain %73 %46 %84 +OpBranch %86 +%86 = OpLabel +%88 = OpCompositeConstruct %26 %10 %10 %10 +%89 = OpAccessChain %87 %85 %84 +OpStore %89 %88 +%91 = OpAccessChain %90 %85 %84 %84 +OpStore %91 %10 +%92 = OpAccessChain %90 %85 %84 %84 +OpStore %92 %14 +%93 = OpLoad %8 %79 +%94 = OpAccessChain %90 %85 %84 %93 +OpStore %94 %15 +%95 = OpLoad %27 %85 +%96 = OpCompositeExtract %26 %95 0 +%97 = OpCompositeExtract %26 %95 0 +%98 = OpVectorShuffle %28 %97 %97 2 0 +%99 = OpCompositeExtract %26 %95 0 +%100 = OpFunctionCall %2 %69 %99 +%101 = OpCompositeExtract %26 %95 0 +%102 = OpVectorTimesMatrix %26 %101 %41 +%103 = OpCompositeExtract %26 %95 0 +%104 = OpMatrixTimesVector %26 %41 %103 +%105 = OpCompositeExtract %26 %95 0 +%106 = OpVectorTimesScalar %26 %105 %14 +%107 = OpCompositeExtract %26 %95 0 +%108 = OpVectorTimesScalar %26 %107 %14 OpReturn OpFunctionEnd -%99 = OpFunction %2 None %68 -%98 = OpLabel -%94 = OpVariable %95 Function %9 -%96 = OpVariable %97 Function %23 -%100 = OpAccessChain %60 %39 %69 -%101 = OpAccessChain %58 %42 %69 -%102 = OpAccessChain %61 %45 %69 -%103 = OpAccessChain %59 %48 %69 -%104 = OpAccessChain %62 %51 %69 -OpBranch %105 -%105 = OpLabel -%106 = OpFunctionCall %2 %67 -%108 = OpLoad %31 %104 -%109 = OpLoad %29 %103 -%110 = OpMatrixTimesVector %29 %108 %109 -%111 = OpCompositeExtract %10 %110 0 -%113 = OpAccessChain %107 %35 %112 -OpStore %113 %111 -%116 = OpAccessChain %75 %101 %115 %115 -%117 = OpLoad %10 %116 -%119 = OpAccessChain %107 %35 %118 -OpStore %119 %117 -%122 = OpAccessChain %120 %102 %69 %121 -%123 = OpLoad %10 %122 -%125 = OpAccessChain %107 %35 %124 -OpStore %125 %123 -%127 = OpAccessChain %126 %100 %115 -%128 = OpLoad %10 %127 -%129 = OpAccessChain %107 %35 %121 -OpStore %129 %128 -%130 = OpAccessChain %75 %100 %69 %69 -%131 = OpLoad %10 %130 -%132 = OpAccessChain %107 %35 %22 -OpStore %132 %131 -%133 = OpAccessChain %126 %100 %115 -OpStore %133 %21 -%134 = OpArrayLength %6 %42 0 -%135 = OpConvertUToF %10 %134 -%136 = OpAccessChain %107 %35 %115 -OpStore %136 %135 -OpAtomicStore %37 %20 %137 %22 +%114 = OpFunction %2 None %83 +%113 = OpLabel +%109 = OpVariable %110 Function %10 +%111 = OpVariable %112 Function %24 +%115 = OpAccessChain %73 %46 %84 +%116 = OpAccessChain %71 %49 %84 +%117 = OpAccessChain %75 %52 %84 +%118 = OpAccessChain %72 %55 %84 +%119 = OpAccessChain %77 %58 %84 +%120 = OpAccessChain %74 %61 %84 +%121 = OpAccessChain %76 %64 %84 +OpBranch %122 +%122 = OpLabel +%123 = OpFunctionCall %2 %82 +%127 = OpAccessChain %126 %121 %84 %84 +%128 = OpLoad %36 %127 +%132 = OpAccessChain %131 %120 %84 %84 %84 +%133 = OpLoad %30 %132 +%134 = OpMatrixTimesVector %28 %128 %133 +%135 = OpCompositeExtract %11 %134 0 +%137 = OpAccessChain %124 %42 %136 +OpStore %137 %135 +%138 = OpLoad %32 %119 +%139 = OpLoad %26 %118 +%140 = OpMatrixTimesVector %28 %138 %139 +%141 = OpCompositeExtract %11 %140 0 +%143 = OpAccessChain %124 %42 %142 +OpStore %143 %141 +%146 = OpAccessChain %90 %116 %145 %145 +%147 = OpLoad %11 %146 +%149 = OpAccessChain %124 %42 %148 +OpStore %149 %147 +%153 = OpAccessChain %151 %117 %84 %152 +%154 = OpLoad %11 %153 +%156 = OpAccessChain %124 %42 %155 +OpStore %156 %154 +%158 = OpAccessChain %157 %115 %145 +%159 = OpLoad %11 %158 +%160 = OpAccessChain %124 %42 %152 +OpStore %160 %159 +%161 = OpAccessChain %90 %115 %84 %84 +%162 = OpLoad %11 %161 +%163 = OpAccessChain %124 %42 %23 +OpStore %163 %162 +%164 = OpAccessChain %157 %115 %145 +OpStore %164 %22 +%165 = OpArrayLength %6 %49 0 +%166 = OpConvertUToF %11 %165 +%167 = OpAccessChain %124 %42 %145 +OpStore %167 %166 +OpAtomicStore %44 %9 %168 %23 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 74caf8cd8..2a2570454 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -20,6 +20,10 @@ struct Baz { m: mat3x2, } +struct MatCx2InArray { + am: array,2>, +} + var global_const: GlobalConst = GlobalConst(0u, vec3(0u, 0u, 0u), 0); @group(0) @binding(0) var bar: Bar; @@ -27,6 +31,8 @@ var bar: Bar; var baz: Baz; @group(0) @binding(2) var qux: vec2; +@group(0) @binding(3) +var nested_mat_cx2_: MatCx2InArray; var val: u32; fn test_matrix_within_struct_accesses() { @@ -65,9 +71,47 @@ fn test_matrix_within_struct_accesses() { return; } +fn test_matrix_within_array_within_struct_accesses() { + var idx_1: i32 = 1; + var t_1: MatCx2InArray; + + let _e7 = idx_1; + idx_1 = (_e7 - 1); + _ = nested_mat_cx2_.am; + _ = nested_mat_cx2_.am[0]; + _ = nested_mat_cx2_.am[0][0]; + let _e25 = idx_1; + _ = nested_mat_cx2_.am[0][_e25]; + _ = nested_mat_cx2_.am[0][0][1]; + let _e41 = idx_1; + _ = nested_mat_cx2_.am[0][0][_e41]; + let _e47 = idx_1; + _ = nested_mat_cx2_.am[0][_e47][1]; + let _e55 = idx_1; + let _e57 = idx_1; + _ = nested_mat_cx2_.am[0][_e55][_e57]; + t_1 = MatCx2InArray(array,2>(mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)))); + let _e63 = idx_1; + idx_1 = (_e63 + 1); + t_1.am = array,2>(mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0))); + t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); + t_1.am[0][0] = vec2(9.0); + let _e90 = idx_1; + t_1.am[0][_e90] = vec2(90.0); + t_1.am[0][0][1] = 10.0; + let _e107 = idx_1; + t_1.am[0][0][_e107] = 20.0; + let _e113 = idx_1; + t_1.am[0][_e113][1] = 30.0; + let _e121 = idx_1; + let _e123 = idx_1; + t_1.am[0][_e121][_e123] = 40.0; + return; +} + fn read_from_private(foo_1: ptr) -> f32 { - let _e5 = (*foo_1); - return _e5; + let _e6 = (*foo_1); + return _e6; } fn test_arr_as_arg(a: array,5>) -> f32 { @@ -87,17 +131,18 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); + test_matrix_within_array_within_struct_accesses(); let _matrix = bar._matrix; let arr = bar.arr; let b = bar._matrix[3][0]; let a_1 = bar.data[(arrayLength((&bar.data)) - 2u)].value; let c_1 = qux; let data_pointer = (&bar.data[0].value); - let _e31 = read_from_private((&foo)); + let _e32 = read_from_private((&foo)); c = array(a_1, i32(b), 3, 4, 5); c[(vi + 1u)] = 42; let value = c[vi]; - let _e45 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + let _e46 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); return vec4((_matrix * vec4(vec4(value))), 2.0); } @@ -116,22 +161,22 @@ fn atomics() { var tmp: i32; let value_1 = atomicLoad((&bar.atom)); - let _e9 = atomicAdd((&bar.atom), 5); - tmp = _e9; - let _e12 = atomicSub((&bar.atom), 5); - tmp = _e12; - let _e15 = atomicAnd((&bar.atom), 5); - tmp = _e15; - let _e18 = atomicOr((&bar.atom), 5); - tmp = _e18; - let _e21 = atomicXor((&bar.atom), 5); - tmp = _e21; - let _e24 = atomicMin((&bar.atom), 5); - tmp = _e24; - let _e27 = atomicMax((&bar.atom), 5); - tmp = _e27; - let _e30 = atomicExchange((&bar.atom), 5); - tmp = _e30; + let _e10 = atomicAdd((&bar.atom), 5); + tmp = _e10; + let _e13 = atomicSub((&bar.atom), 5); + tmp = _e13; + let _e16 = atomicAnd((&bar.atom), 5); + tmp = _e16; + let _e19 = atomicOr((&bar.atom), 5); + tmp = _e19; + let _e22 = atomicXor((&bar.atom), 5); + tmp = _e22; + let _e25 = atomicMin((&bar.atom), 5); + tmp = _e25; + let _e28 = atomicMax((&bar.atom), 5); + tmp = _e28; + let _e31 = atomicExchange((&bar.atom), 5); + tmp = _e31; atomicStore((&bar.atom), value_1); return; } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 77435cabc..147f6ec32 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -14,9 +14,13 @@ var dummy: array>; @group(0) @binding(3) var float_vecs: array,20>; @group(0) @binding(4) -var global_vec: vec4; +var global_vec: vec3; @group(0) @binding(5) -var global_mat: mat4x4; +var global_mat: mat3x2; +@group(0) @binding(6) +var global_nested_arrays_of_matrices_2x4_: array,2>,2>; +@group(0) @binding(7) +var global_nested_arrays_of_matrices_4x2_: array,2>,2>; fn test_msl_packed_vec3_as_arg(arg: vec3) { return; @@ -28,8 +32,8 @@ fn test_msl_packed_vec3_() { alignment.v3_ = vec3(1.0); alignment.v3_.x = 1.0; alignment.v3_.x = 2.0; - let _e21 = idx; - alignment.v3_[_e21] = 3.0; + let _e23 = idx; + alignment.v3_[_e23] = 3.0; let data = alignment; _ = data.v3_; _ = data.v3_.zx; @@ -46,17 +50,20 @@ fn main() { var at: bool = true; test_msl_packed_vec3_(); - let _e10 = global_mat; - let _e11 = global_vec; - wg[6] = (_e10 * _e11).x; - let _e19 = dummy[1].y; - wg[5] = _e19; - let _e25 = float_vecs[0].w; - wg[4] = _e25; - let _e29 = alignment.v1_; - wg[3] = _e29; - let _e34 = alignment.v3_.x; - wg[2] = _e34; + let _e16 = global_nested_arrays_of_matrices_4x2_[0][0]; + let _e23 = global_nested_arrays_of_matrices_2x4_[0][0][0]; + wg[7] = (_e16 * _e23).x; + let _e28 = global_mat; + let _e29 = global_vec; + wg[6] = (_e28 * _e29).x; + let _e37 = dummy[1].y; + wg[5] = _e37; + let _e43 = float_vecs[0].w; + wg[4] = _e43; + let _e47 = alignment.v1_; + wg[3] = _e47; + let _e52 = alignment.v3_.x; + wg[2] = _e52; alignment.v1_ = 4.0; wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); From b746e0a4209133c0654d0c8959db97b45cf9358a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Thu, 30 Jun 2022 16:34:42 +0100 Subject: [PATCH 1799/2212] spv-in: Fix incorrect translation of SMod (#1995) Since spirv's SMod doesn't map to naga's IR modulo operator the instruction is mapped into it's direct formula, this formula requires some casts from int to float and back. These casts were present but their `convert` field was left to `None` which implied that they were bitcasts, causing some wildly incorrect results. This commit fixes it by setting the `convert` field to the same size as the result type. --- src/front/spv/mod.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 9f5d710e1..944d68593 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2045,11 +2045,16 @@ impl> Parser { body_idx, ); + let result_ty = self.lookup_type.lookup(result_type_id)?; + let inner = &ctx.type_arena[result_ty.handle].inner; + let kind = inner.scalar_kind().unwrap(); + let size = inner.size(ctx.const_arena) as u8; + let left_cast = ctx.expressions.append( crate::Expression::As { expr: left, kind: crate::ScalarKind::Float, - convert: None, + convert: Some(size), }, span, ); @@ -2057,7 +2062,7 @@ impl> Parser { crate::Expression::As { expr: right, kind: crate::ScalarKind::Float, - convert: None, + convert: Some(size), }, span, ); @@ -2079,16 +2084,11 @@ impl> Parser { }, span, ); - let result_ty = self.lookup_type.lookup(result_type_id)?; - let kind = ctx.type_arena[result_ty.handle] - .inner - .scalar_kind() - .unwrap(); let cast = ctx.expressions.append( crate::Expression::As { expr: floor, kind, - convert: None, + convert: Some(size), }, span, ); From e2d688088a8e900e22da348cdc7ba0655394b498 Mon Sep 17 00:00:00 2001 From: Ashley Date: Thu, 30 Jun 2022 18:58:47 +0200 Subject: [PATCH 1800/2212] Support for the `OVR_multiview2` WebGL extension (#1933) * Make some (currently hacky) changes to enable multiview in webgl * Fix ViewIndex built in for this extension * Run cargo fmt, fix tests * Allow specifying if we're targetting webgl in the glsl version * Document multiview2 extension * fn embedded -> const fn embedded * Fix tests * Fix benches * Add snapshot tests * Revamp so that the glsl options have some multiview options. Also add tests * Make clippy happier * Go back to having is_webgl be part of Version * Use wgsl as input for tests * Rename Version::new_embedded to Version::new_gles, fix glsl validation * Run cargo fmt * Fix brand new clippy warnings --- benches/criterion.rs | 3 +- cli/src/main.rs | 3 +- src/back/glsl/features.rs | 22 ++++-- src/back/glsl/mod.rs | 76 +++++++++++++++---- src/back/mod.rs | 2 +- src/valid/analyzer.rs | 1 - tests/in/functions-webgl.param.ron | 5 +- tests/in/multiview.param.ron | 3 + tests/in/multiview.wgsl | 2 + tests/in/multiview_webgl.param.ron | 11 +++ tests/in/multiview_webgl.wgsl | 2 + tests/in/push-constants.param.ron | 5 +- tests/in/quad.param.ron | 5 +- tests/in/skybox.param.ron | 5 +- tests/out/glsl/multiview.main.Vertex.glsl | 13 ++++ .../out/glsl/multiview_webgl.main.Vertex.glsl | 14 ++++ tests/out/spv/multiview.spvasm | 23 ++++++ tests/out/wgsl/multiview.wgsl | 4 + tests/snapshots.rs | 8 ++ 19 files changed, 180 insertions(+), 27 deletions(-) create mode 100644 tests/in/multiview.param.ron create mode 100644 tests/in/multiview.wgsl create mode 100644 tests/in/multiview_webgl.param.ron create mode 100644 tests/in/multiview_webgl.wgsl create mode 100644 tests/out/glsl/multiview.main.Vertex.glsl create mode 100644 tests/out/glsl/multiview_webgl.main.Vertex.glsl create mode 100644 tests/out/spv/multiview.spvasm create mode 100644 tests/out/wgsl/multiview.wgsl diff --git a/benches/criterion.rs b/benches/criterion.rs index 117552845..ee8765b92 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -239,7 +239,7 @@ fn backends(c: &mut Criterion) { b.iter(|| { let mut string = String::new(); let options = naga::back::glsl::Options { - version: naga::back::glsl::Version::Embedded(320), + version: naga::back::glsl::Version::new_gles(320), writer_flags: naga::back::glsl::WriterFlags::empty(), binding_map: Default::default(), }; @@ -248,6 +248,7 @@ fn backends(c: &mut Criterion) { let pipeline_options = naga::back::glsl::PipelineOptions { shader_stage: ep.stage, entry_point: ep.name.clone(), + multiview: None, }; match naga::back::glsl::Writer::new( &mut string, diff --git a/cli/src/main.rs b/cli/src/main.rs index efaf5959b..6b924e995 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -133,7 +133,7 @@ impl FromStr for GlslProfileArg { Ok(Self(if s.starts_with("core") { Version::Desktop(s[4..].parse().unwrap_or(330)) } else if s.starts_with("es") { - Version::Embedded(s[2..].parse().unwrap_or(310)) + Version::new_gles(s[2..].parse().unwrap_or(310)) } else { return Err(format!("Unknown profile: {}", s)); })) @@ -454,6 +454,7 @@ fn run() -> Result<(), Box> { "comp" => naga::ShaderStage::Compute, _ => unreachable!(), }, + multiview: None, }; let mut buffer = String::new(); diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 82718b040..b898b1d2b 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -82,7 +82,7 @@ impl FeaturesManager { // Used when both core and es support the feature ($feature:ident, $core:literal, $es:literal) => { if self.0.contains(Features::$feature) - && (version < Version::Desktop($core) || version < Version::Embedded($es)) + && (version < Version::Desktop($core) || version < Version::new_gles($es)) { missing |= Features::$feature; } @@ -106,7 +106,10 @@ impl FeaturesManager { check_feature!(CULL_DISTANCE, 450, 300); check_feature!(SAMPLE_VARIABLES, 400, 300); check_feature!(DYNAMIC_ARRAY_SIZE, 430, 310); - check_feature!(MULTI_VIEW, 140, 310); + match version { + Version::Embedded { is_webgl: true, .. } => check_feature!(MULTI_VIEW, 140, 300), + _ => check_feature!(MULTI_VIEW, 140, 310), + }; // Only available on glsl core, this means that opengl es can't query the number // of samples nor levels in a image and neither do bound checks on the sample nor // the level argument of texelFecth @@ -212,11 +215,16 @@ impl FeaturesManager { } if self.0.contains(Features::MULTI_VIEW) { - // https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GL_EXT_multiview.txt - writeln!(out, "#extension GL_EXT_multiview : require")?; + if let Version::Embedded { is_webgl: true, .. } = version { + // https://www.khronos.org/registry/OpenGL/extensions/OVR/OVR_multiview2.txt + writeln!(out, "#extension GL_OVR_multiview2 : require")?; + } else { + // https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GL_EXT_multiview.txt + writeln!(out, "#extension GL_EXT_multiview : require")?; + } } - if self.0.contains(Features::FMA) && version >= Version::Embedded(310) { + if self.0.contains(Features::FMA) && version >= Version::new_gles(310) { // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_gpu_shader5.txt writeln!(out, "#extension GL_EXT_gpu_shader5 : require")?; } @@ -269,6 +277,10 @@ impl<'a, W> Writer<'a, W> { self.features.request(Features::COMPUTE_SHADER) } + if self.multiview.is_some() { + self.features.request(Features::MULTI_VIEW); + } + for (ty_handle, ty) in self.module.types.iter() { match ty.inner { TypeInner::Scalar { kind, width } => self.scalar_required_features(kind, width), diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a59a0b9d7..e714b6447 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -119,15 +119,31 @@ pub enum Version { /// `core` GLSL. Desktop(u16), /// `es` GLSL. - Embedded(u16), + Embedded { version: u16, is_webgl: bool }, } impl Version { + /// Create a new gles version + pub const fn new_gles(version: u16) -> Self { + Self::Embedded { + version, + is_webgl: false, + } + } + /// Returns true if self is `Version::Embedded` (i.e. is a es version) const fn is_es(&self) -> bool { match *self { Version::Desktop(_) => false, - Version::Embedded(_) => true, + Version::Embedded { .. } => true, + } + } + + /// Returns true if targetting WebGL + const fn is_webgl(&self) -> bool { + match *self { + Version::Desktop(_) => false, + Version::Embedded { is_webgl, .. } => is_webgl, } } @@ -140,7 +156,7 @@ impl Version { fn is_supported(&self) -> bool { match *self { Version::Desktop(v) => SUPPORTED_CORE_VERSIONS.contains(&v), - Version::Embedded(v) => SUPPORTED_ES_VERSIONS.contains(&v), + Version::Embedded { version: v, .. } => SUPPORTED_ES_VERSIONS.contains(&v), } } @@ -151,19 +167,19 @@ impl Version { /// Note: `location=` for vertex inputs and fragment outputs is supported /// unconditionally for GLES 300. fn supports_explicit_locations(&self) -> bool { - *self >= Version::Embedded(310) || *self >= Version::Desktop(410) + *self >= Version::Desktop(410) || *self >= Version::new_gles(310) } fn supports_early_depth_test(&self) -> bool { - *self >= Version::Desktop(130) || *self >= Version::Embedded(310) + *self >= Version::Desktop(130) || *self >= Version::new_gles(310) } fn supports_std430_layout(&self) -> bool { - *self >= Version::Desktop(430) || *self >= Version::Embedded(310) + *self >= Version::Desktop(430) || *self >= Version::new_gles(310) } fn supports_fma_function(&self) -> bool { - *self >= Version::Desktop(400) || *self >= Version::Embedded(310) + *self >= Version::Desktop(400) || *self >= Version::new_gles(310) } } @@ -171,7 +187,9 @@ impl PartialOrd for Version { fn partial_cmp(&self, other: &Self) -> Option { match (*self, *other) { (Version::Desktop(x), Version::Desktop(y)) => Some(x.cmp(&y)), - (Version::Embedded(x), Version::Embedded(y)) => Some(x.cmp(&y)), + (Version::Embedded { version: x, .. }, Version::Embedded { version: y, .. }) => { + Some(x.cmp(&y)) + } _ => None, } } @@ -181,7 +199,7 @@ impl fmt::Display for Version { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Version::Desktop(v) => write!(f, "{} core", v), - Version::Embedded(v) => write!(f, "{} es", v), + Version::Embedded { version: v, .. } => write!(f, "{} es", v), } } } @@ -215,7 +233,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { Options { - version: Version::Embedded(310), + version: Version::new_gles(310), writer_flags: WriterFlags::ADJUST_COORDINATE_SPACE, binding_map: BindingMap::default(), } @@ -233,6 +251,8 @@ pub struct PipelineOptions { /// /// If no entry point that matches is found while creating a [`Writer`], a error will be thrown. pub entry_point: String, + /// How many views to render to, if doing multiview rendering. + pub multiview: Option, } /// Reflection info for texture mappings and uniforms. @@ -285,6 +305,7 @@ struct VaryingName<'a> { binding: &'a crate::Binding, stage: ShaderStage, output: bool, + targetting_webgl: bool, } impl fmt::Display for VaryingName<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -302,7 +323,11 @@ impl fmt::Display for VaryingName<'_> { write!(f, "_{}_location{}", prefix, location,) } crate::Binding::BuiltIn(built_in) => { - write!(f, "{}", glsl_built_in(built_in, self.output)) + write!( + f, + "{}", + glsl_built_in(built_in, self.output, self.targetting_webgl) + ) } } } @@ -400,6 +425,8 @@ pub struct Writer<'a, W> { named_expressions: crate::NamedExpressions, /// Set of expressions that need to be baked to avoid unnecessary repetition in output need_bake_expressions: back::NeedBakeExpressions, + /// How many views to render to, if doing multiview rendering. + multiview: Option, } impl<'a, W: Write> Writer<'a, W> { @@ -451,7 +478,7 @@ impl<'a, W: Write> Writer<'a, W> { reflection_names_globals: crate::FastHashMap::default(), entry_point: &module.entry_points[ep_idx], entry_point_idx: ep_idx as u16, - + multiview: pipeline_options.multiview, block_id: IdGenerator::default(), named_expressions: Default::default(), need_bake_expressions: Default::default(), @@ -540,6 +567,13 @@ impl<'a, W: Write> Writer<'a, W> { } } + if self.entry_point.stage == ShaderStage::Vertex && self.options.version.is_webgl() { + if let Some(multiview) = self.multiview.as_ref() { + writeln!(self.out, "layout(num_views = {}) in;", multiview)?; + writeln!(self.out)?; + } + } + let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); // Write struct types. @@ -1180,7 +1214,11 @@ impl<'a, W: Write> Writer<'a, W> { } => (location, interpolation, sampling), crate::Binding::BuiltIn(built_in) => { if let crate::BuiltIn::Position { invariant: true } = built_in { - writeln!(self.out, "invariant {};", glsl_built_in(built_in, output))?; + writeln!( + self.out, + "invariant {};", + glsl_built_in(built_in, output, self.options.version.is_webgl()) + )?; } return Ok(()); } @@ -1238,6 +1276,7 @@ impl<'a, W: Write> Writer<'a, W> { }, stage: self.entry_point.stage, output, + targetting_webgl: self.options.version.is_webgl(), }; writeln!(self.out, " {};", vname)?; @@ -1378,6 +1417,7 @@ impl<'a, W: Write> Writer<'a, W> { binding: member.binding.as_ref().unwrap(), stage, output: false, + targetting_webgl: self.options.version.is_webgl(), }; if index != 0 { write!(self.out, ", ")?; @@ -1391,6 +1431,7 @@ impl<'a, W: Write> Writer<'a, W> { binding: arg.binding.as_ref().unwrap(), stage, output: false, + targetting_webgl: self.options.version.is_webgl(), }; writeln!(self.out, "{};", varying_name)?; } @@ -1897,6 +1938,7 @@ impl<'a, W: Write> Writer<'a, W> { binding: member.binding.as_ref().unwrap(), stage: ep.stage, output: true, + targetting_webgl: self.options.version.is_webgl(), }; write!(self.out, "{} = ", varying_name)?; @@ -1921,6 +1963,7 @@ impl<'a, W: Write> Writer<'a, W> { binding: result.binding.as_ref().unwrap(), stage: ep.stage, output: true, + targetting_webgl: self.options.version.is_webgl(), }; write!(self.out, "{} = ", name)?; self.write_expr(value, ctx)?; @@ -3629,7 +3672,11 @@ const fn glsl_scalar( } /// Helper function that returns the glsl variable name for a builtin -const fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { +const fn glsl_built_in( + built_in: crate::BuiltIn, + output: bool, + targetting_webgl: bool, +) -> &'static str { use crate::BuiltIn as Bi; match built_in { @@ -3640,6 +3687,7 @@ const fn glsl_built_in(built_in: crate::BuiltIn, output: bool) -> &'static str { "gl_FragCoord" } } + Bi::ViewIndex if targetting_webgl => "int(gl_ViewID_OVR)", Bi::ViewIndex => "gl_ViewIndex", // vertex Bi::BaseInstance => "uint(gl_BaseInstance)", diff --git a/src/back/mod.rs b/src/back/mod.rs index 16b503cfb..d8e016c00 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -59,7 +59,7 @@ struct FunctionCtx<'a> { named_expressions: &'a crate::NamedExpressions, } -impl<'a> FunctionCtx<'_> { +impl FunctionCtx<'_> { /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function const fn name_key(&self, local: crate::Handle) -> crate::proc::NameKey { match self.ty { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 9a7130ff9..3f13aba32 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -484,7 +484,6 @@ impl FunctionInfo { return Err(ExpressionError::MissingCapabilities(needed_caps)); } - let _ = (); Uniformity { non_uniform_result: self .add_assignable_ref(base, &mut assignable_global) diff --git a/tests/in/functions-webgl.param.ron b/tests/in/functions-webgl.param.ron index bc3dd4a8d..923da0729 100644 --- a/tests/in/functions-webgl.param.ron +++ b/tests/in/functions-webgl.param.ron @@ -1,6 +1,9 @@ ( glsl: ( - version: Embedded(300), + version: Embedded( + version: 300, + is_webgl: false + ), writer_flags: (bits: 0), binding_map: {}, ), diff --git a/tests/in/multiview.param.ron b/tests/in/multiview.param.ron new file mode 100644 index 000000000..35dd990fd --- /dev/null +++ b/tests/in/multiview.param.ron @@ -0,0 +1,3 @@ +( + glsl_multiview: Some(2), +) diff --git a/tests/in/multiview.wgsl b/tests/in/multiview.wgsl new file mode 100644 index 000000000..b4531c8a7 --- /dev/null +++ b/tests/in/multiview.wgsl @@ -0,0 +1,2 @@ +@vertex +fn main(@builtin(view_index) view_index: i32) {} diff --git a/tests/in/multiview_webgl.param.ron b/tests/in/multiview_webgl.param.ron new file mode 100644 index 000000000..720b51fbb --- /dev/null +++ b/tests/in/multiview_webgl.param.ron @@ -0,0 +1,11 @@ +( + glsl: ( + version: Embedded ( + version: 300, + is_webgl: true + ), + writer_flags: (bits: 0), + binding_map: {}, + ), + glsl_multiview: Some(2), +) diff --git a/tests/in/multiview_webgl.wgsl b/tests/in/multiview_webgl.wgsl new file mode 100644 index 000000000..b4531c8a7 --- /dev/null +++ b/tests/in/multiview_webgl.wgsl @@ -0,0 +1,2 @@ +@vertex +fn main(@builtin(view_index) view_index: i32) {} diff --git a/tests/in/push-constants.param.ron b/tests/in/push-constants.param.ron index 0a35edeab..3972328c9 100644 --- a/tests/in/push-constants.param.ron +++ b/tests/in/push-constants.param.ron @@ -1,7 +1,10 @@ ( god_mode: true, glsl: ( - version: Embedded(320), + version: Embedded( + version: 320, + is_webgl: false + ), writer_flags: (bits: 0), binding_map: {}, ), diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index acde3aed4..568b96189 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -5,7 +5,10 @@ adjust_coordinate_space: true, ), glsl: ( - version: Embedded(300), + version: Embedded( + version: 300, + is_webgl: false + ), writer_flags: (bits: 0), binding_map: {}, ), diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 9c9bd1f30..b90f2e5a2 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -37,7 +37,10 @@ fake_missing_bindings: false, ), glsl: ( - version: Embedded(320), + version: Embedded( + version: 320, + is_webgl: false + ), writer_flags: (bits: 0), binding_map: { (group: 0, binding: 0): 0, diff --git a/tests/out/glsl/multiview.main.Vertex.glsl b/tests/out/glsl/multiview.main.Vertex.glsl new file mode 100644 index 000000000..a466f7df9 --- /dev/null +++ b/tests/out/glsl/multiview.main.Vertex.glsl @@ -0,0 +1,13 @@ +#version 310 es +#extension GL_EXT_multiview : require + +precision highp float; +precision highp int; + + +void main() { + int view_index = gl_ViewIndex; + gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); + return; +} + diff --git a/tests/out/glsl/multiview_webgl.main.Vertex.glsl b/tests/out/glsl/multiview_webgl.main.Vertex.glsl new file mode 100644 index 000000000..bb8b6e687 --- /dev/null +++ b/tests/out/glsl/multiview_webgl.main.Vertex.glsl @@ -0,0 +1,14 @@ +#version 300 es +#extension GL_OVR_multiview2 : require + +precision highp float; +precision highp int; + +layout(num_views = 2) in; + + +void main() { + int view_index = int(gl_ViewID_OVR); + return; +} + diff --git a/tests/out/spv/multiview.spvasm b/tests/out/spv/multiview.spvasm new file mode 100644 index 000000000..bb67d7eba --- /dev/null +++ b/tests/out/spv/multiview.spvasm @@ -0,0 +1,23 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 11 +OpCapability Shader +OpCapability MultiView +OpExtension "SPV_KHR_multiview" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %8 "main" %5 +OpDecorate %5 BuiltIn ViewIndex +%2 = OpTypeVoid +%3 = OpTypeInt 32 1 +%6 = OpTypePointer Input %3 +%5 = OpVariable %6 Input +%9 = OpTypeFunction %2 +%8 = OpFunction %2 None %9 +%4 = OpLabel +%7 = OpLoad %3 %5 +OpBranch %10 +%10 = OpLabel +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/multiview.wgsl b/tests/out/wgsl/multiview.wgsl new file mode 100644 index 000000000..3ea9676b8 --- /dev/null +++ b/tests/out/wgsl/multiview.wgsl @@ -0,0 +1,4 @@ +@vertex +fn main(@builtin(view_index) view_index: i32) { + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index a7f773490..5859e2b1c 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -79,6 +79,9 @@ struct Parameters { hlsl: naga::back::hlsl::Options, #[serde(default)] wgsl: WgslOutParameters, + #[cfg(all(feature = "deserialize", feature = "glsl-out"))] + #[serde(default)] + glsl_multiview: Option, } #[allow(unused_variables)] @@ -162,6 +165,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { &ep.name, ¶ms.glsl, params.bounds_check_policies, + params.glsl_multiview, ); } } @@ -283,6 +287,7 @@ fn write_output_glsl( ep_name: &str, options: &naga::back::glsl::Options, bounds_check_policies: naga::proc::BoundsCheckPolicies, + multiview: Option, ) { use naga::back::glsl; @@ -291,6 +296,7 @@ fn write_output_glsl( let pipeline_options = glsl::PipelineOptions { shader_stage: stage, entry_point: ep_name.to_string(), + multiview, }; let mut buffer = String::new(); @@ -531,6 +537,8 @@ fn convert_wgsl() { "binding-arrays", Targets::WGSL | Targets::HLSL | Targets::METAL | Targets::SPIRV, ), + ("multiview", Targets::SPIRV | Targets::GLSL | Targets::WGSL), + ("multiview_webgl", Targets::GLSL), ( "break-if", Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, From 06ae90527dcede1a98d6f15fa7c440f0eab5d0ba Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Thu, 30 Jun 2022 15:51:46 -0400 Subject: [PATCH 1801/2212] Release 0.9 (#1998) * Release 0.9 * Further update changelog * Apply suggestions from code review Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> --- CHANGELOG.md | 16 ++++++++++++++-- Cargo.toml | 4 ++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1959c357..5bd561cef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Change Log -## v0.9 (TBD) +## v0.9 (2022-06-30) - Fix minimal-versions of dependencies ([#1840](https://github.com/gfx-rs/naga/pull/1840)) **@teoxoy** - Update MSRV to 1.56 ([#1838](https://github.com/gfx-rs/naga/pull/1838)) **@teoxoy** @@ -60,6 +60,7 @@ Main breaking changes Specification Changes (relavant changes have also been applied to the WGSL backend) +- Add support for `break if` ([#1993](https://github.com/gfx-rs/naga/pull/1993)) **@JCapucho** - Update number literal format ([#1863](https://github.com/gfx-rs/naga/pull/1863)) **@teoxoy** - Allow non-ascii characters in identifiers ([#1849](https://github.com/gfx-rs/naga/pull/1849)) **@teoxoy** - Update reserved keywords ([#1847](https://github.com/gfx-rs/naga/pull/1847), [#1870](https://github.com/gfx-rs/naga/pull/1870), [#1905](https://github.com/gfx-rs/naga/pull/1905)) **@teoxoy** **@Gordon-F** @@ -76,6 +77,7 @@ Specification Changes (relavant changes have also been applied to the WGSL backe Improvements +- Implement complete validation for size and align attributes ([#1979](https://github.com/gfx-rs/naga/pull/1979)) **@teoxoy** - Implement `firstTrailingBit`/`firstLeadingBit` u32 overloads ([#1865](https://github.com/gfx-rs/naga/pull/1865)) **@teoxoy** - Add error for non-floating-point matrix ([#1917](https://github.com/gfx-rs/naga/pull/1917)) **@grovesNL** - Implement partial vector & matrix identity constructors ([#1916](https://github.com/gfx-rs/naga/pull/1916)) **@teoxoy** @@ -99,12 +101,16 @@ SPV-IN - Implement `OpBitReverse` and `OpBitCount` ([#1954](https://github.com/gfx-rs/naga/pull/1954)) **@JCapucho** - Add `MultiView` to `SUPPORTED_CAPABILITIES` ([#1934](https://github.com/gfx-rs/naga/pull/1934)) **@expenses** -- Translate `OpSMod` and `OpFMod` correctly ([#1867](https://github.com/gfx-rs/naga/pull/1867)) **@teoxoy** +- Translate `OpSMod` and `OpFMod` correctly ([#1867](https://github.com/gfx-rs/naga/pull/1867), [#1995](https://github.com/gfx-rs/naga/pull/1995)) **@teoxoy** **@JCapucho** - Error on unsupported `MatrixStride` ([#1805](https://github.com/gfx-rs/naga/pull/1805)) **@teoxoy** - Align array stride for undecorated arrays ([#1724](https://github.com/gfx-rs/naga/pull/1724)) **@JCapucho** GLSL-IN +- Don't allow empty last case in switch ([#1981](https://github.com/gfx-rs/naga/pull/1981)) **@JCapucho** +- Fix last case falltrough and empty switch ([#1981](https://github.com/gfx-rs/naga/pull/1981)) **@JCapucho** +- Splat inputs for smoothstep if needed ([#1976](https://github.com/gfx-rs/naga/pull/1976)) **@JCapucho** +- Fix parameter not changing to depth ([#1967](https://github.com/gfx-rs/naga/pull/1967)) **@JCapucho** - Fix matrix multiplication check ([#1953](https://github.com/gfx-rs/naga/pull/1953)) **@JCapucho** - Fix panic (stop emitter in conditional) ([#1952](https://github.com/gfx-rs/naga/pull/1952)) **@JCapucho** - Translate `mod` fn correctly ([#1867](https://github.com/gfx-rs/naga/pull/1867)) **@teoxoy** @@ -151,6 +157,8 @@ SPV-OUT MSL-OUT +- Insert padding initialization for global constants ([#1988](https://github.com/gfx-rs/naga/pull/1988)) **@teoxoy** +- Don't rely on cached expressions ([#1975](https://github.com/gfx-rs/naga/pull/1975)) **@JCapucho** - Fix pointers to private or workgroup address spaces possibly being read only ([#1901](https://github.com/gfx-rs/naga/pull/1901)) **@teoxoy** - Zero init variables in function address space ([#1871](https://github.com/gfx-rs/naga/pull/1871)) **@teoxoy** - Make binding arrays play nice with bounds checks ([#1855](https://github.com/gfx-rs/naga/pull/1855)) **@cwfitzgerald** @@ -168,6 +176,7 @@ MSL-OUT HLSL-OUT +- More `matCx2` fixes (#1989) ([#1989](https://github.com/gfx-rs/naga/pull/1989)) **@teoxoy** - Fix fallthrough in switch statements ([#1920](https://github.com/gfx-rs/naga/pull/1920)) **@teoxoy** - Fix missing break statements ([#1919](https://github.com/gfx-rs/naga/pull/1919)) **@teoxoy** - Fix `countOneBits` and `reverseBits` for signed integers ([#1928](https://github.com/gfx-rs/naga/pull/1928)) **@hasali19** @@ -190,6 +199,9 @@ HLSL-OUT GLSL-OUT +- Fix vector bitcasts (#1966) ([#1966](https://github.com/gfx-rs/naga/pull/1966)) **@expenses** +- Perform casts in int only math functions ([#1978](https://github.com/gfx-rs/naga/pull/1978)) **@JCapucho** +- Don't rely on cached expressions ([#1975](https://github.com/gfx-rs/naga/pull/1975)) **@JCapucho** - Fix type error for `countOneBits` implementation ([#1897](https://github.com/gfx-rs/naga/pull/1897)) **@hasali19** - Fix storage format for `Rgba8Unorm` ([#1955](https://github.com/gfx-rs/naga/pull/1955)) **@JCapucho** - Implement bounds checks for `ImageLoad` ([#1889](https://github.com/gfx-rs/naga/pull/1889)) **@JCapucho** diff --git a/Cargo.toml b/Cargo.toml index 1b2fb838b..ed3ae954c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,11 +1,11 @@ [package] name = "naga" -version = "0.8.0" +version = "0.9.0" authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" homepage = "https://github.com/gfx-rs/naga" -repository = "https://github.com/gfx-rs/naga/tree/v0.8" +repository = "https://github.com/gfx-rs/naga/tree/v0.9" keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] From 350171ed2f45612386cc91a0ee9ff79d918939a9 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Sat, 2 Jul 2022 00:00:51 -0400 Subject: [PATCH 1802/2212] Prepare naga-cli 0.9 for release (#1999) --- cli/Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cli/Cargo.toml b/cli/Cargo.toml index ce12d0c06..ac5238bd5 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga-cli" -version = "0.4.0" +version = "0.9.0" authors = ["Naga Developers"] edition = "2018" description = "Shader translation command line tool" @@ -14,7 +14,7 @@ name = "naga" path = "src/main.rs" [dependencies] -naga = { path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate", "serialize", "deserialize"] } +naga = { version = "0.9", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate", "serialize", "deserialize"] } bincode = "1" log = "0.4" codespan-reporting = "0.11" From 17dcf39a1b2e4282943580302f510955704650f5 Mon Sep 17 00:00:00 2001 From: Ashley Date: Wed, 6 Jul 2022 20:27:54 +0200 Subject: [PATCH 1803/2212] Rename hlsl input/output structs (#2001) --- src/back/hlsl/writer.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index b582cfa4f..39c9cdab7 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -199,8 +199,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } // Write all entry points wrapped structs - for ep in module.entry_points.iter() { - let ep_io = self.write_ep_interface(module, &ep.function, ep.stage, &ep.name)?; + for (index, ep) in module.entry_points.iter().enumerate() { + let ep_name = self.names[&NameKey::EntryPoint(index as u16)].clone(); + let ep_io = self.write_ep_interface(module, &ep.function, ep.stage, &ep_name)?; self.entry_point_io.push(ep_io); } From 8f302a89ef350c462c3c0c69f7084a5cf11d196d Mon Sep 17 00:00:00 2001 From: ani <97794085+norepimorphism@users.noreply.github.com> Date: Sun, 17 Jul 2022 04:40:05 +0000 Subject: [PATCH 1804/2212] Update reserved WGSL keywords (#2009) --- src/keywords/wgsl.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/keywords/wgsl.rs b/src/keywords/wgsl.rs index 3231915b5..b5cc6ea9f 100644 --- a/src/keywords/wgsl.rs +++ b/src/keywords/wgsl.rs @@ -138,7 +138,6 @@ pub const RESERVED: &[&str] = &[ "cast", "catch", "cbuffer", - "centroid", "char", "class", "co_await", @@ -174,7 +173,6 @@ pub const RESERVED: &[&str] = &[ "final", "finally", "fixed", - "flat", "friend", "from", "fvec2", @@ -249,7 +247,6 @@ pub const RESERVED: &[&str] = &[ "layout", "line", "lineadj", - "linear", "lowp", "macro", "macro_rules", @@ -298,7 +295,6 @@ pub const RESERVED: &[&str] = &[ "restrict", "row_major", "samper", - "sample", "sampler1D", "sampler1DArray", "sampler1DArrayShadow", From cc985396dadc95039a0f3d5cfc818a6b4d5eba6b Mon Sep 17 00:00:00 2001 From: Ashley Date: Sun, 17 Jul 2022 09:18:48 +0200 Subject: [PATCH 1805/2212] Handle Unpack2x16float in hlsl (#2002) --- src/back/hlsl/writer.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 39c9cdab7..a37a89444 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2422,6 +2422,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { enum Function { Asincosh { is_sin: bool }, Atanh, + Unpack2x16float, Regular(&'static str), MissingIntOverload(&'static str), } @@ -2489,6 +2490,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::ReverseBits => Function::MissingIntOverload("reversebits"), Mf::FindLsb => Function::Regular("firstbitlow"), Mf::FindMsb => Function::Regular("firstbithigh"), + Mf::Unpack2x16float => Function::Unpack2x16float, _ => return Err(Error::Unimplemented(format!("write_expr_math {:?}", fun))), }; @@ -2512,6 +2514,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, arg, func_ctx)?; write!(self.out, "))")?; } + Function::Unpack2x16float => { + write!(self.out, "float2(f16tof32(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "), f16tof32((")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ") >> 16))")?; + } Function::Regular(fun_name) => { write!(self.out, "{}(", fun_name)?; self.write_expr(module, arg, func_ctx)?; From a0058217d63672e49c7b8e26e497c1afe176d736 Mon Sep 17 00:00:00 2001 From: Jeron Aldaron Lau Date: Fri, 22 Jul 2022 23:46:28 -0500 Subject: [PATCH 1806/2212] Make termcolor dependency optional (#2014) --- Cargo.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ed3ae954c..c38ff67ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,10 +32,10 @@ serialize = ["serde", "indexmap/serde-1"] deserialize = ["serde", "indexmap/serde-1"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] -wgsl-in = ["codespan-reporting", "hexf-parse", "unicode-xid"] +wgsl-in = ["codespan-reporting", "hexf-parse", "termcolor", "unicode-xid"] wgsl-out = [] hlsl-out = [] -span = ["codespan-reporting"] +span = ["codespan-reporting", "termcolor"] validate = [] [[bench]] @@ -46,7 +46,7 @@ harness = false arbitrary = { version = "1.0.2", features = ["derive"], optional = true } bitflags = "1.0.5" bit-set = "0.5" -termcolor = "1.0.4" +termcolor = { version = "1.0.4", optional = true } # remove termcolor dep when updating to the next version of codespan-reporting # termcolor minimum version was wrong and was fixed in # https://github.com/brendanzab/codespan/commit/e99c867339a877731437e7ee6a903a3d03b5439e From c6f34fa4d896cad5b194e3290b87b76489bfbe74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 15 Jun 2022 21:02:07 +0100 Subject: [PATCH 1807/2212] dot-out: Improvements Improves the dot backend output by: - Linking new nodes to the end of other blocks, instead of the beginning - Generating merge nodes for conditional statements - Generating connections from break/continue nodes to their target - Introducing a "cfg only" mode that only generates statements --- cli/src/main.rs | 12 +- src/back/dot/mod.rs | 326 +++++++++++++++++++++++++++++------------ tests/out/dot/quad.dot | 13 +- tests/snapshots.rs | 2 +- 4 files changed, 253 insertions(+), 100 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 6b924e995..f7a3f8312 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -60,6 +60,10 @@ struct Args { #[argh(switch)] keep_coordinate_space: bool, + /// in dot output, include only the control flow graph + #[argh(switch)] + dot_cfg_only: bool, + /// specify file path to process STDIN as #[argh(option)] stdin_file_path: Option, @@ -476,7 +480,13 @@ fn run() -> Result<(), Box> { "dot" => { use naga::back::dot; - let output = dot::write(&module, info.as_ref())?; + let output = dot::write( + &module, + info.as_ref(), + naga::back::dot::Options { + cfg_only: args.dot_cfg_only, + }, + )?; fs::write(output_path, output)?; } "hlsl" => { diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 265e40075..ce88f02e8 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -17,24 +17,70 @@ use std::{ fmt::{Error as FmtError, Write as _}, }; +/// Configuration options for the dot backend +#[derive(Default)] +pub struct Options { + /// Only emit function bodies + pub cfg_only: bool, +} + +/// Identifier used to address a graph node +type NodeId = usize; + +/// Stores the target nodes for control flow statements +#[derive(Default, Clone, Copy)] +struct Targets { + /// The node, if some, where continue operations will land + continue_target: Option, + /// The node, if some, where break operations will land + break_target: Option, +} + +/// Stores information about the graph of statements #[derive(Default)] struct StatementGraph { + /// List of node names nodes: Vec<&'static str>, - flow: Vec<(usize, usize, &'static str)>, - dependencies: Vec<(usize, Handle, &'static str)>, - emits: Vec<(usize, Handle)>, - calls: Vec<(usize, Handle)>, + /// List of edges of the control flow, the items are defined as + /// (from, to, label) + flow: Vec<(NodeId, NodeId, &'static str)>, + /// List of implicit edges of the control flow, used for jump + /// operations such as continue or break, the items are defined as + /// (from, to, label, color_id) + jumps: Vec<(NodeId, NodeId, &'static str, usize)>, + /// List of dependency relationships between a statement node and + /// expressions + dependencies: Vec<(NodeId, Handle, &'static str)>, + /// List of expression emitted by statement node + emits: Vec<(NodeId, Handle)>, + /// List of function call by statement node + calls: Vec<(NodeId, Handle)>, } impl StatementGraph { - fn add(&mut self, block: &[crate::Statement]) -> usize { + /// Adds a new block to the statement graph, returning the first and last node, respectively + fn add(&mut self, block: &[crate::Statement], targets: Targets) -> (NodeId, NodeId) { use crate::Statement as S; + + // The first node of the block isn't a statement but a virtual node let root = self.nodes.len(); self.nodes.push(if root == 0 { "Root" } else { "Node" }); + // Track the last placed node, this will be returned to the caller and + // will also be used to generate the control flow edges + let mut last_node = root; for statement in block { + // Reserve a new node for the current statement and link it to the + // node of the previous statement let id = self.nodes.len(); - self.flow.push((id - 1, id, "")); + self.flow.push((last_node, id, "")); self.nodes.push(""); // reserve space + + // Track the node identifier for the merge node, the merge node is + // the last node of a statement, normally this is the node itself, + // but for control flow statements such as `if`s and `switch`s this + // is a virtual node where all branches merge back. + let mut merge_id = id; + self.nodes[id] = match *statement { S::Emit(ref range) => { for handle in range.clone() { @@ -42,13 +88,34 @@ impl StatementGraph { } "Emit" } - S::Break => "Break", //TODO: loop context - S::Continue => "Continue", //TODO: loop context - S::Kill => "Kill", //TODO: link to the beginning + S::Kill => "Kill", //TODO: link to the beginning + S::Break => { + // Try to link to the break target, otherwise produce + // a broken connection + if let Some(target) = targets.break_target { + self.jumps.push((id, target, "Break", 5)) + } else { + self.jumps.push((id, root, "Broken", 7)) + } + "Break" + } + S::Continue => { + // Try to link to the continue target, otherwise produce + // a broken connection + if let Some(target) = targets.continue_target { + self.jumps.push((id, target, "Continue", 5)) + } else { + self.jumps.push((id, root, "Broken", 7)) + } + "Continue" + } S::Barrier(_flags) => "Barrier", S::Block(ref b) => { - let other = self.add(b); + let (other, last) = self.add(b, targets); self.flow.push((id, other, "")); + // All following nodes should connect to the end of the block + // statement so change the merge id to it. + merge_id = last; "Block" } S::If { @@ -57,10 +124,18 @@ impl StatementGraph { ref reject, } => { self.dependencies.push((id, condition, "condition")); - let accept_id = self.add(accept); + let (accept_id, accept_last) = self.add(accept, targets); self.flow.push((id, accept_id, "accept")); - let reject_id = self.add(reject); + let (reject_id, reject_last) = self.add(reject, targets); self.flow.push((id, reject_id, "reject")); + + // Create a merge node, link the branches to it and set it + // as the merge node to make the next statement node link to it + merge_id = self.nodes.len(); + self.nodes.push("Merge"); + self.flow.push((accept_last, merge_id, "")); + self.flow.push((reject_last, merge_id, "")); + "If" } S::Switch { @@ -68,13 +143,26 @@ impl StatementGraph { ref cases, } => { self.dependencies.push((id, selector, "selector")); + + // Create a merge node and set it as the merge node to make + // the next statement node link to it + merge_id = self.nodes.len(); + self.nodes.push("Merge"); + + // Create a new targets structure and set the break target + // to the merge node + let mut targets = targets; + targets.break_target = Some(merge_id); + for case in cases { - let case_id = self.add(&case.body); + let (case_id, case_last) = self.add(&case.body, targets); let label = match case.value { crate::SwitchValue::Integer(_) => "case", crate::SwitchValue::Default => "default", }; self.flow.push((id, case_id, label)); + // Link the last node of the branch to the merge node + self.flow.push((case_last, merge_id, "")); } "Switch" } @@ -83,13 +171,32 @@ impl StatementGraph { ref continuing, break_if, } => { - let body_id = self.add(body); + // Create a new targets structure and set the break target + // to the merge node, this must happen before generating the + // continuing block since it can break. + let mut targets = targets; + targets.break_target = Some(id); + + let (continuing_id, continuing_last) = self.add(continuing, targets); + + // Set the the continue target to the beginning + // of the newly generated continuing block + targets.continue_target = Some(continuing_id); + + let (body_id, body_last) = self.add(body, targets); + self.flow.push((id, body_id, "body")); - let continuing_id = self.add(continuing); - self.flow.push((body_id, continuing_id, "continuing")); + + // Link the last node of the body to the continuing block + self.flow.push((body_last, continuing_id, "continuing")); + // Link the last node of the continuing block back to the + // beginning of the loop body + self.flow.push((continuing_last, body_id, "continuing")); + if let Some(expr) = break_if { - self.dependencies.push((id, expr, "break if")); + self.dependencies.push((continuing_id, expr, "break if")); } + "Loop" } S::Return { value } => { @@ -146,8 +253,10 @@ impl StatementGraph { "Atomic" } }; + // Set the last node to the merge node + last_node = merge_id; } - root + (root, last_node) } } @@ -171,6 +280,91 @@ fn write_fun( prefix: String, fun: &crate::Function, info: Option<&FunctionInfo>, + options: &Options, +) -> Result<(), FmtError> { + writeln!(output, "\t\tnode [ style=filled ]")?; + + if !options.cfg_only { + for (handle, var) in fun.local_variables.iter() { + writeln!( + output, + "\t\t{}_l{} [ shape=hexagon label=\"{:?} '{}'\" ]", + prefix, + handle.index(), + handle, + name(&var.name), + )?; + } + + write_function_expressions(output, &prefix, fun, info)?; + } + + let mut sg = StatementGraph::default(); + sg.add(&fun.body, Targets::default()); + for (index, label) in sg.nodes.into_iter().enumerate() { + writeln!( + output, + "\t\t{}_s{} [ shape=square label=\"{}\" ]", + prefix, index, label, + )?; + } + for (from, to, label) in sg.flow { + writeln!( + output, + "\t\t{}_s{} -> {}_s{} [ arrowhead=tee label=\"{}\" ]", + prefix, from, prefix, to, label, + )?; + } + for (from, to, label, color_id) in sg.jumps { + writeln!( + output, + "\t\t{}_s{} -> {}_s{} [ arrowhead=tee style=dashed color=\"{}\" label=\"{}\" ]", + prefix, from, prefix, to, COLORS[color_id], label, + )?; + } + + if !options.cfg_only { + for (to, expr, label) in sg.dependencies { + writeln!( + output, + "\t\t{}_e{} -> {}_s{} [ label=\"{}\" ]", + prefix, + expr.index(), + prefix, + to, + label, + )?; + } + for (from, to) in sg.emits { + writeln!( + output, + "\t\t{}_s{} -> {}_e{} [ style=dotted ]", + prefix, + from, + prefix, + to.index(), + )?; + } + } + + for (from, function) in sg.calls { + writeln!( + output, + "\t\t{}_s{} -> f{}_s0", + prefix, + from, + function.index(), + )?; + } + + Ok(()) +} + +fn write_function_expressions( + output: &mut String, + prefix: &str, + fun: &crate::Function, + info: Option<&FunctionInfo>, ) -> Result<(), FmtError> { enum Payload<'a> { Arguments(&'a [Handle]), @@ -178,19 +372,6 @@ fn write_fun( Global(Handle), } - writeln!(output, "\t\tnode [ style=filled ]")?; - - for (handle, var) in fun.local_variables.iter() { - writeln!( - output, - "\t\t{}_l{} [ shape=hexagon label=\"{:?} '{}'\" ]", - prefix, - handle.index(), - handle, - name(&var.name), - )?; - } - let mut edges = crate::FastHashMap::<&str, _>::default(); let mut payload = None; for (handle, expression) in fun.expressions.iter() { @@ -431,76 +612,35 @@ fn write_fun( } } - let mut sg = StatementGraph::default(); - sg.add(&fun.body); - for (index, label) in sg.nodes.into_iter().enumerate() { - writeln!( - output, - "\t\t{}_s{} [ shape=square label=\"{}\" ]", - prefix, index, label, - )?; - } - for (from, to, label) in sg.flow { - writeln!( - output, - "\t\t{}_s{} -> {}_s{} [ arrowhead=tee label=\"{}\" ]", - prefix, from, prefix, to, label, - )?; - } - for (to, expr, label) in sg.dependencies { - writeln!( - output, - "\t\t{}_e{} -> {}_s{} [ label=\"{}\" ]", - prefix, - expr.index(), - prefix, - to, - label, - )?; - } - for (from, to) in sg.emits { - writeln!( - output, - "\t\t{}_s{} -> {}_e{} [ style=dotted ]", - prefix, - from, - prefix, - to.index(), - )?; - } - for (from, function) in sg.calls { - writeln!( - output, - "\t\t{}_s{} -> f{}_s0", - prefix, - from, - function.index(), - )?; - } - Ok(()) } /// Write shader module to a [`String`]. -pub fn write(module: &crate::Module, mod_info: Option<&ModuleInfo>) -> Result { +pub fn write( + module: &crate::Module, + mod_info: Option<&ModuleInfo>, + options: Options, +) -> Result { use std::fmt::Write as _; let mut output = String::new(); output += "digraph Module {\n"; - writeln!(output, "\tsubgraph cluster_globals {{")?; - writeln!(output, "\t\tlabel=\"Globals\"")?; - for (handle, var) in module.global_variables.iter() { - writeln!( - output, - "\t\tg{} [ shape=hexagon label=\"{:?} {:?}/'{}'\" ]", - handle.index(), - handle, - var.space, - name(&var.name), - )?; + if !options.cfg_only { + writeln!(output, "\tsubgraph cluster_globals {{")?; + writeln!(output, "\t\tlabel=\"Globals\"")?; + for (handle, var) in module.global_variables.iter() { + writeln!( + output, + "\t\tg{} [ shape=hexagon label=\"{:?} {:?}/'{}'\" ]", + handle.index(), + handle, + var.space, + name(&var.name), + )?; + } + writeln!(output, "\t}}")?; } - writeln!(output, "\t}}")?; for (handle, fun) in module.functions.iter() { let prefix = format!("f{}", handle.index()); @@ -512,7 +652,7 @@ pub fn write(module: &crate::Module, mod_info: Option<&ModuleInfo>) -> Result) -> Result ep1_s1 [ arrowhead=tee label="" ] ep1_s1 -> ep1_s2 [ arrowhead=tee label="" ] ep1_s2 -> ep1_s3 [ arrowhead=tee label="" ] @@ -72,15 +73,17 @@ digraph Module { ep1_s5 -> ep1_s6 [ arrowhead=tee label="" ] ep1_s4 -> ep1_s5 [ arrowhead=tee label="accept" ] ep1_s4 -> ep1_s7 [ arrowhead=tee label="reject" ] + ep1_s6 -> ep1_s8 [ arrowhead=tee label="" ] ep1_s7 -> ep1_s8 [ arrowhead=tee label="" ] ep1_s8 -> ep1_s9 [ arrowhead=tee label="" ] + ep1_s9 -> ep1_s10 [ arrowhead=tee label="" ] ep1_e7 -> ep1_s4 [ label="condition" ] - ep1_e9 -> ep1_s9 [ label="value" ] + ep1_e9 -> ep1_s10 [ label="value" ] ep1_s1 -> ep1_e4 [ style=dotted ] ep1_s2 -> ep1_e5 [ style=dotted ] ep1_s3 -> ep1_e7 [ style=dotted ] - ep1_s8 -> ep1_e8 [ style=dotted ] - ep1_s8 -> ep1_e9 [ style=dotted ] + ep1_s9 -> ep1_e8 [ style=dotted ] + ep1_s9 -> ep1_e9 [ style=dotted ] } subgraph cluster_ep2 { label="Fragment/'fs_extra'" diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 5859e2b1c..d7837e34f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -173,7 +173,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(feature = "dot-out")] { if targets.contains(Targets::DOT) { - let string = naga::back::dot::write(module, Some(&info)).unwrap(); + let string = naga::back::dot::write(module, Some(&info), Default::default()).unwrap(); fs::write(dest.join(format!("dot/{}.dot", name)), string).unwrap(); } } From cfbc91d6cf34983d25418a201f00d015dc23e6fc Mon Sep 17 00:00:00 2001 From: Christofer Nolander Date: Sat, 6 Aug 2022 23:48:07 +0200 Subject: [PATCH 1808/2212] add `emit_to_{stderr,string}` helpers for validation errors (#2012) Mirrors those already found for parse errors. Also removes the `StringErrorBuffer` writer in favor of the existing `NoColor` writer (from `codespan`) and added the emit_to_string_with_path method to complete the set. --- src/front/wgsl/mod.rs | 59 ++++++--------------------------- src/span.rs | 77 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 49 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2f68534cf..2732c5b57 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -27,15 +27,10 @@ use codespan_reporting::{ files::SimpleFile, term::{ self, - termcolor::{ColorChoice, ColorSpec, StandardStream, WriteColor}, + termcolor::{ColorChoice, NoColor, StandardStream}, }, }; -use std::{ - borrow::Cow, - convert::TryFrom, - io::{self, Write}, - ops, -}; +use std::{borrow::Cow, convert::TryFrom, ops}; use thiserror::Error; type Span = ops::Range; @@ -1320,11 +1315,16 @@ impl ParseError { /// Emits a summary of the error to a string. pub fn emit_to_string(&self, source: &str) -> String { - let files = SimpleFile::new("wgsl", source); + self.emit_to_string_with_path(source, "wgsl") + } + + /// Emits a summary of the error to a string. + pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String { + let files = SimpleFile::new(path, source); let config = codespan_reporting::term::Config::default(); - let mut writer = StringErrorBuffer::new(); + let mut writer = NoColor::new(Vec::new()); term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); - writer.into_string() + String::from_utf8(writer.into_inner()).unwrap() } /// Returns a [`SourceLocation`] for the first label in the error message. @@ -4556,42 +4556,3 @@ impl Parser { pub fn parse_str(source: &str) -> Result { Parser::new().parse(source) } - -pub struct StringErrorBuffer { - buf: Vec, -} - -impl StringErrorBuffer { - pub const fn new() -> Self { - Self { buf: Vec::new() } - } - - pub fn into_string(self) -> String { - String::from_utf8(self.buf).unwrap() - } -} - -impl Write for StringErrorBuffer { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.buf.extend(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -impl WriteColor for StringErrorBuffer { - fn supports_color(&self) -> bool { - false - } - - fn set_color(&mut self, _spec: &ColorSpec) -> io::Result<()> { - Ok(()) - } - - fn reset(&mut self) -> io::Result<()> { - Ok(()) - } -} diff --git a/src/span.rs b/src/span.rs index 6f2583a5e..a4670e2da 100644 --- a/src/span.rs +++ b/src/span.rs @@ -236,6 +236,83 @@ impl WithSpan { pub fn location(&self, _source: &str) -> Option { None } + + #[cfg(feature = "span")] + fn diagnostic(&self) -> codespan_reporting::diagnostic::Diagnostic<()> + where + E: Error, + { + use codespan_reporting::diagnostic::{Diagnostic, Label}; + let diagnostic = Diagnostic::error() + .with_message(self.inner.to_string()) + .with_labels( + self.spans() + .map(|&(span, ref desc)| { + Label::primary((), span.to_range().unwrap()).with_message(desc.to_owned()) + }) + .collect(), + ) + .with_notes({ + let mut notes = Vec::new(); + let mut source: &dyn Error = &self.inner; + while let Some(next) = Error::source(source) { + notes.push(next.to_string()); + source = next; + } + notes + }); + diagnostic + } + + /// Emits a summary of the error to standard error stream. + #[cfg(feature = "span")] + pub fn emit_to_stderr(&self, source: &str) + where + E: Error, + { + self.emit_to_stderr_with_path(source, "wgsl") + } + + /// Emits a summary of the error to standard error stream. + #[cfg(feature = "span")] + pub fn emit_to_stderr_with_path(&self, source: &str, path: &str) + where + E: Error, + { + use codespan_reporting::{files, term}; + use term::termcolor::{ColorChoice, StandardStream}; + + let files = files::SimpleFile::new(path, source); + let config = term::Config::default(); + let writer = StandardStream::stderr(ColorChoice::Auto); + term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) + .expect("cannot write error"); + } + + /// Emits a summary of the error to a string. + #[cfg(feature = "span")] + pub fn emit_to_string(&self, source: &str) -> String + where + E: Error, + { + self.emit_to_string_with_path(source, "wgsl") + } + + /// Emits a summary of the error to a string. + #[cfg(feature = "span")] + pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String + where + E: Error, + { + use codespan_reporting::{files, term}; + use term::termcolor::NoColor; + + let files = files::SimpleFile::new(path, source); + let config = codespan_reporting::term::Config::default(); + let mut writer = NoColor::new(Vec::new()); + term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); + String::from_utf8(writer.into_inner()).unwrap() + } } /// Convenience trait for [`Error`] to be able to apply spans to anything. From f2624ea378e5248244e5486e18934e77051f88a7 Mon Sep 17 00:00:00 2001 From: SpaceCat~Chan <49094338+SpaceCat-Chan@users.noreply.github.com> Date: Mon, 8 Aug 2022 19:09:22 +0200 Subject: [PATCH 1809/2212] [glsl-in] add support for .length() (#2017) Adds parsing support for methods on the glsl frontend, while `.length` is the only method in the base extensions, there might be more in extensions. Adds support for the `.length` method and tests for it. --- src/front/glsl/ast.rs | 9 ++++ src/front/glsl/context.rs | 61 ++++++++++++++++++++++++++++ src/front/glsl/parser/expressions.rs | 18 ++++++++ tests/in/glsl/expressions.frag | 12 ++++++ tests/out/wgsl/expressions-frag.wgsl | 51 +++++++++++++++++------ 5 files changed, 138 insertions(+), 13 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 148049a68..cbb21f6de 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -159,6 +159,15 @@ pub enum HirExprKind { /// The target expression expr: Handle, }, + /// A method call like `what.something(a, b, c)` + Method { + /// expression the method call applies to (`what` in the example) + expr: Handle, + /// the method name (`something` in the example) + name: String, + /// the arguments to the method (`a`, `b`, and `c` in the example) + args: Vec>, + }, } #[derive(Debug, Hash, PartialEq, Eq)] diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 13eb5d180..c269e5fd1 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -1366,6 +1366,67 @@ impl Context { value } } + HirExprKind::Method { + expr: object, + ref name, + ref args, + } if ExprPos::Lhs != pos => { + let args = args + .iter() + .map(|e| self.lower_expect_inner(stmt, parser, *e, ExprPos::Rhs, body)) + .collect::>>()?; + match name.as_ref() { + "length" => { + if !args.is_empty() { + parser.errors.push(Error { + kind: ErrorKind::SemanticError( + ".length() doesn't take any arguments".into(), + ), + meta, + }); + } + let lowered_array = + self.lower_expect_inner(stmt, parser, object, pos, body)?.0; + let array_type = parser.resolve_type(self, lowered_array, meta)?; + + match *array_type { + TypeInner::Array { + size: crate::ArraySize::Constant(size), + .. + } => { + let mut array_length = + self.add_expression(Expression::Constant(size), meta, body); + self.forced_conversion( + parser, + &mut array_length, + meta, + ScalarKind::Sint, + 4, + )?; + array_length + } + // let the error be handled in type checking if it's not a dynamic array + _ => { + let mut array_length = self.add_expression( + Expression::ArrayLength(lowered_array), + meta, + body, + ); + self.conversion(&mut array_length, meta, ScalarKind::Sint, 4)?; + array_length + } + } + } + _ => { + return Err(Error { + kind: ErrorKind::SemanticError( + format!("unknown method '{}'", name).into(), + ), + meta, + }); + } + } + } _ => { return Err(Error { kind: ErrorKind::SemanticError( diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 44f9ea9d0..ad9cf80a0 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -231,6 +231,24 @@ impl<'source> ParsingContext<'source> { TokenValue::Dot => { let (field, end_meta) = self.expect_ident(parser)?; + if self.bump_if(parser, TokenValue::LeftParen).is_some() { + let args = + self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; + + base = stmt.hir_exprs.append( + HirExpr { + kind: HirExprKind::Method { + expr: base, + name: field, + args, + }, + meta, + }, + Default::default(), + ); + continue; + } + meta.subsume(end_meta); base = stmt.hir_exprs.append( HirExpr { diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index acf0ea921..2e386057b 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -132,6 +132,18 @@ void testMatrixMultiplication(mat4x3 a, mat4x4 b) { mat4x3 c = a * b; } +layout(std430, binding = 0) buffer a_buf { + float a[]; +}; + +void testLength() { + int len = a.length(); +} + +void testConstantLength(float a[4u]) { + int len = a.length(); +} + out vec4 o_color; void main() { privatePointer(global); diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 7cf1eace0..5c8a3de5f 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -2,11 +2,17 @@ struct BST { data: i32, } +struct a_buf { + a: array, +} + struct FragmentOutput { @location(0) o_color: vec4, } var global: f32; +@group(0) @binding(0) +var global_1: a_buf; var o_color: vec4; fn testBinOpVecFloat(a: vec4, b: f32) { @@ -369,28 +375,47 @@ fn testMatrixMultiplication(a_22: mat4x3, b_18: mat4x4) { return; } +fn testLength() { + var len: i32; + + len = i32(arrayLength((&global_1.a))); + return; +} + +fn testConstantLength(a_24: array) { + var a_25: array; + var len_1: i32 = 4; + + _ = (&global_1.a); + a_25 = a_24; + _ = a_25; + _ = i32(4u); +} + fn main_1() { var local_5: f32; + _ = (&global_1.a); _ = global; - let _e3 = global; - local_5 = _e3; + let _e5 = global; + local_5 = _e5; privatePointer((&local_5)); - let _e5 = local_5; - global = _e5; - let _e6 = o_color; - _ = _e6.xyzw; - let _e9 = vec4(1.0); - o_color.x = _e9.x; - o_color.y = _e9.y; - o_color.z = _e9.z; - o_color.w = _e9.w; + let _e7 = local_5; + global = _e7; + let _e8 = o_color; + _ = _e8.xyzw; + let _e11 = vec4(1.0); + o_color.x = _e11.x; + o_color.y = _e11.y; + o_color.z = _e11.z; + o_color.w = _e11.w; return; } @fragment fn main() -> FragmentOutput { + _ = (&global_1.a); main_1(); - let _e5 = o_color; - return FragmentOutput(_e5); + let _e7 = o_color; + return FragmentOutput(_e7); } From 6f4003ca9b2582b438de7414f530d9662dcd30ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 16 Aug 2022 02:53:14 +0100 Subject: [PATCH 1810/2212] Fix clippy lints for 1.63 (#2026) --- src/front/glsl/builtins.rs | 50 +++++++++++++++++++------------------- src/lib.rs | 3 ++- 2 files changed, 27 insertions(+), 26 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index ea75ba2a2..7501809c3 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -537,7 +537,7 @@ fn inject_standard_builtins( | "dFdyFine" | "dFdyCoarse" | "fwidth" | "fwidthFine" | "fwidthCoarse" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b100) { + for bits in 0..0b100 { let size = match bits { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -588,7 +588,7 @@ fn inject_standard_builtins( "intBitsToFloat" | "uintBitsToFloat" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b100) { + for bits in 0..0b100 { let size = match bits { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -612,7 +612,7 @@ fn inject_standard_builtins( "pow" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b100) { + for bits in 0..0b100 { let size = match bits { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -635,7 +635,7 @@ fn inject_standard_builtins( // bits layout // bit 0 trough 1 - dims // bit 2 - float/sint - for bits in 0..(0b1000) { + for bits in 0..0b1000 { let size = match bits & 0b11 { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -683,7 +683,7 @@ fn inject_standard_builtins( // bits layout // bit 0 - int/uint // bit 1 trough 2 - dims - for bits in 0..(0b1000) { + for bits in 0..0b1000 { let kind = match bits & 0b1 { 0b0 => Sk::Sint, _ => Sk::Uint, @@ -797,7 +797,7 @@ fn inject_standard_builtins( // bits layout // bit 0 - atan/atan2 // bit 1 trough 2 - dims - for bits in 0..(0b1000) { + for bits in 0..0b1000 { let fun = match bits & 0b1 { 0b0 => MathFunction::Atan, _ => MathFunction::Atan2, @@ -828,7 +828,7 @@ fn inject_standard_builtins( "all" | "any" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b11) { + for bits in 0..0b11 { let size = match bits { 0b00 => VectorSize::Bi, 0b01 => VectorSize::Tri, @@ -852,7 +852,7 @@ fn inject_standard_builtins( } "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" | "notEqual" => { - for bits in 0..(0b1001) { + for bits in 0..0b1001 { let (size, kind) = match bits { 0b0000 => (VectorSize::Bi, Sk::Float), 0b0001 => (VectorSize::Tri, Sk::Float), @@ -885,7 +885,7 @@ fn inject_standard_builtins( // bits layout // bit 0 trough 1 - scalar kind // bit 2 trough 4 - dims - for bits in 0..(0b11100) { + for bits in 0..0b11100 { let kind = match bits & 0b11 { 0b00 => Sk::Float, 0b01 => Sk::Sint, @@ -929,7 +929,7 @@ fn inject_standard_builtins( // // 0b10011 is the last element since splatted single elements // were already added - for bits in 0..(0b10011) { + for bits in 0..0b10011 { let size = match bits & 0b11 { 0b00 => Some(VectorSize::Bi), 0b01 => Some(VectorSize::Tri), @@ -975,7 +975,7 @@ fn inject_standard_builtins( // // 0b11010 is the last element since splatted single elements // were already added - for bits in 0..(0b11011) { + for bits in 0..0b11011 { let kind = match bits & 0b11 { 0b00 => Sk::Float, 0b01 => Sk::Sint, @@ -1021,7 +1021,7 @@ fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Mod "abs" | "sign" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b100) { + for bits in 0..0b100 { let size = match bits { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -1048,7 +1048,7 @@ fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Mod "min" | "max" => { // bits layout // bit 0 trough 2 - dims - for bits in 0..(0b111) { + for bits in 0..0b111 { let (size, second_size) = match bits { 0b000 => (None, None), 0b001 => (Some(VectorSize::Bi), None), @@ -1087,7 +1087,7 @@ fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Mod // // 0b1010 is the last element since splatted with single elements // is equal to normal single elements - for bits in 0..(0b1011) { + for bits in 0..0b1011 { let size = match bits & 0b11 { 0b00 => Some(VectorSize::Quad), 0b01 => Some(VectorSize::Bi), @@ -1131,7 +1131,7 @@ fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Mod // // 0b110 is the last element since splatted with single elements // is equal to normal single elements - for bits in 0..(0b111) { + for bits in 0..0b111 { let kind = Sk::Float; let size = match bits & 0b11 { 0b00 => Some(VectorSize::Bi), @@ -1174,7 +1174,7 @@ fn inject_common_builtin( | "normalize" | "length" | "isinf" | "isnan" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b100) { + for bits in 0..0b100 { let size = match bits { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -1215,7 +1215,7 @@ fn inject_common_builtin( "dot" | "reflect" | "distance" | "ldexp" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b100) { + for bits in 0..0b100 { let size = match bits { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -1250,7 +1250,7 @@ fn inject_common_builtin( "transpose" => { // bits layout // bit 0 trough 3 - dims - for bits in 0..(0b1001) { + for bits in 0..0b1001 { let (rows, columns) = match bits { 0b0000 => (VectorSize::Bi, VectorSize::Bi), 0b0001 => (VectorSize::Bi, VectorSize::Tri), @@ -1276,7 +1276,7 @@ fn inject_common_builtin( "inverse" | "determinant" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b11) { + for bits in 0..0b11 { let (rows, columns) = match bits { 0b00 => (VectorSize::Bi, VectorSize::Bi), 0b01 => (VectorSize::Tri, VectorSize::Tri), @@ -1302,7 +1302,7 @@ fn inject_common_builtin( "mod" | "step" => { // bits layout // bit 0 trough 2 - dims - for bits in 0..(0b111) { + for bits in 0..0b111 { let (size, second_size) = match bits { 0b000 => (None, None), 0b001 => (Some(VectorSize::Bi), None), @@ -1347,7 +1347,7 @@ fn inject_common_builtin( "modf" | "frexp" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b100) { + for bits in 0..0b100 { let size = match bits { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -1421,7 +1421,7 @@ fn inject_common_builtin( "outerProduct" => { // bits layout // bit 0 trough 3 - dims - for bits in 0..(0b1001) { + for bits in 0..0b1001 { let (size1, size2) = match bits { 0b0000 => (VectorSize::Bi, VectorSize::Bi), 0b0001 => (VectorSize::Bi, VectorSize::Tri), @@ -1455,7 +1455,7 @@ fn inject_common_builtin( "faceforward" | "fma" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b100) { + for bits in 0..0b100 { let size = match bits { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -1488,7 +1488,7 @@ fn inject_common_builtin( "refract" => { // bits layout // bit 0 trough 1 - dims - for bits in 0..(0b100) { + for bits in 0..0b100 { let size = match bits { 0b00 => None, 0b01 => Some(VectorSize::Bi), @@ -1523,7 +1523,7 @@ fn inject_common_builtin( "smoothstep" => { // bit 0 - splatted // bit 1 trough 2 - dims - for bits in 0..(0b1000) { + for bits in 0..0b1000 { let splatted = bits & 0b1 == 0b1; let size = match bits >> 1 { 0b00 => None, diff --git a/src/lib.rs b/src/lib.rs index 29bcbeaf4..9f45c082a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -188,7 +188,8 @@ tree. clippy::new_without_default, clippy::unneeded_field_pattern, clippy::match_like_matches_macro, - clippy::if_same_then_else + clippy::if_same_then_else, + clippy::derive_partial_eq_without_eq )] #![warn( trivial_casts, From a80967f860f26c318715cf0c59c6fbdafa0b4f13 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Tue, 16 Aug 2022 03:43:41 -0700 Subject: [PATCH 1811/2212] Add support for the saturate function (#2025) uses clamp in place of saturate in spv and glsl --- src/back/glsl/mod.rs | 18 ++++++ src/back/hlsl/writer.rs | 1 + src/back/msl/writer.rs | 1 + src/back/spv/block.rs | 55 +++++++++++++++++++ src/back/wgsl/writer.rs | 1 + src/front/wgsl/conv.rs | 1 + src/lib.rs | 1 + src/proc/mod.rs | 1 + src/proc/typifier.rs | 1 + src/valid/expression.rs | 3 +- tests/in/math-functions.wgsl | 1 + .../out/glsl/math-functions.main.Vertex.glsl | 1 + tests/out/hlsl/math-functions.hlsl | 1 + tests/out/msl/math-functions.msl | 1 + tests/out/spv/math-functions.spvasm | 27 +++++---- tests/out/wgsl/math-functions.wgsl | 1 + 16 files changed, 102 insertions(+), 13 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index e714b6447..a3f2a5383 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2749,6 +2749,24 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Min => "min", Mf::Max => "max", Mf::Clamp => "clamp", + Mf::Saturate => { + write!(self.out, "clamp(")?; + + self.write_expr(arg, ctx)?; + + match *ctx.info[arg].ty.inner_with(&self.module.types) { + crate::TypeInner::Vector { size, .. } => write!( + self.out, + ", vec{}(0.0), vec{0}(1.0)", + back::vector_size_str(size) + )?, + _ => write!(self.out, ", 0.0, 1.0")?, + } + + write!(self.out, ")")?; + + return Ok(()); + } // trigonometry Mf::Cos => "cos", Mf::Cosh => "cosh", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index a37a89444..ae761ead4 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2433,6 +2433,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::Min => Function::Regular("min"), Mf::Max => Function::Regular("max"), Mf::Clamp => Function::Regular("clamp"), + Mf::Saturate => Function::Regular("saturate"), // trigonometry Mf::Cos => Function::Regular("cos"), Mf::Cosh => Function::Regular("cosh"), diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c35786f7a..9a59289be 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1628,6 +1628,7 @@ impl Writer { Mf::Min => "min", Mf::Max => "max", Mf::Clamp => "clamp", + Mf::Saturate => "saturate", // trigonometry Mf::Cos => "cos", Mf::Cosh => "cosh", diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 1c475e49b..8a388be22 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -696,6 +696,61 @@ impl<'w> BlockContext<'w> { Some(crate::ScalarKind::Uint) => spirv::GLOp::UClamp, other => unimplemented!("Unexpected max({:?})", other), }), + Mf::Saturate => { + let (maybe_size, width) = match *arg_ty { + crate::TypeInner::Vector { size, width, .. } => (Some(size), width), + crate::TypeInner::Scalar { width, .. } => (None, width), + ref other => unimplemented!("Unexpected saturate({:?})", other), + }; + + let mut arg1_id = self + .writer + .get_constant_scalar(crate::ScalarValue::Float(0.0), width); + let mut arg2_id = self + .writer + .get_constant_scalar(crate::ScalarValue::Float(1.0), width); + + if let Some(size) = maybe_size { + let value = LocalType::Value { + vector_size: Some(size), + kind: crate::ScalarKind::Float, + width, + pointer_space: None, + }; + + let result_type_id = self.get_type_id(LookupType::Local(value)); + + self.temp_list.clear(); + self.temp_list.resize(size as _, arg1_id); + + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + result_type_id, + id, + &self.temp_list, + )); + arg1_id = id; + + self.temp_list.clear(); + self.temp_list.resize(size as _, arg2_id); + + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + result_type_id, + id, + &self.temp_list, + )); + arg2_id = id; + } + + MathOp::Custom(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + spirv::GLOp::FClamp, + result_type_id, + id, + &[arg0_id, arg1_id, arg2_id], + )) + } // trigonometry Mf::Sin => MathOp::Ext(spirv::GLOp::Sin), Mf::Sinh => MathOp::Ext(spirv::GLOp::Sinh), diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 8a7a71cdc..0be7ef072 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1511,6 +1511,7 @@ impl Writer { Mf::Min => Function::Regular("min"), Mf::Max => Function::Regular("max"), Mf::Clamp => Function::Regular("clamp"), + Mf::Saturate => Function::Regular("saturate"), // trigonometry Mf::Cos => Function::Regular("cos"), Mf::Cosh => Function::Regular("cosh"), diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index c1bbb8971..ba4164875 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -140,6 +140,7 @@ pub fn map_standard_fun(word: &str) -> Option { "min" => Mf::Min, "max" => Mf::Max, "clamp" => Mf::Clamp, + "saturate" => Mf::Saturate, // trigonometry "cos" => Mf::Cos, "cosh" => Mf::Cosh, diff --git a/src/lib.rs b/src/lib.rs index 9f45c082a..107534c8b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -952,6 +952,7 @@ pub enum MathFunction { Min, Max, Clamp, + Saturate, // trigonometry Cos, Cosh, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 823a190de..0b9f406af 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -228,6 +228,7 @@ impl super::MathFunction { Self::Min => 2, Self::Max => 2, Self::Clamp => 3, + Self::Saturate => 1, // trigonometry Self::Cos => 1, Self::Cosh => 1, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index a5304b738..9a5922ea7 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -704,6 +704,7 @@ impl<'a> ResolveContext<'a> { Mf::Min | Mf::Max | Mf::Clamp | + Mf::Saturate | // trigonometry Mf::Cos | Mf::Cosh | diff --git a/src/valid/expression.rs b/src/valid/expression.rs index f433b456b..6279ed362 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1040,7 +1040,8 @@ impl super::Validator { )); } } - Mf::Cos + Mf::Saturate + | Mf::Cos | Mf::Cosh | Mf::Sin | Mf::Sinh diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index a2e097a04..9ecac8049 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -6,6 +6,7 @@ fn main() { let b = radians(f); let c = degrees(v); let d = radians(v); + let e = saturate(v); let const_dot = dot(vec2(), vec2()); let first_leading_bit_abs = firstLeadingBit(abs(0u)); } diff --git a/tests/out/glsl/math-functions.main.Vertex.glsl b/tests/out/glsl/math-functions.main.Vertex.glsl index 8d7286829..f0954772e 100644 --- a/tests/out/glsl/math-functions.main.Vertex.glsl +++ b/tests/out/glsl/math-functions.main.Vertex.glsl @@ -10,6 +10,7 @@ void main() { float b = radians(1.0); vec4 c = degrees(v); vec4 d = radians(v); + vec4 e = clamp(v, vec4(0.0), vec4(1.0)); int const_dot = ( + ivec2(0, 0).x * ivec2(0, 0).x + ivec2(0, 0).y * ivec2(0, 0).y); uint first_leading_bit_abs = uint(findMSB(uint(abs(int(0u))))); } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index 179cfee66..827da71b4 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -6,6 +6,7 @@ void main() float b = radians(1.0); float4 c = degrees(v); float4 d = radians(v); + float4 e = saturate(v); int const_dot = dot(int2(0, 0), int2(0, 0)); uint first_leading_bit_abs = firstbithigh(abs(0u)); } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 87de8418c..6ee0093d0 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -13,6 +13,7 @@ vertex void main_( float b = ((1.0) * 0.017453292519943295474); metal::float4 c = ((v) * 57.295779513082322865); metal::float4 d = ((v) * 0.017453292519943295474); + metal::float4 e = metal::saturate(v); int const_dot = ( + const_type.x * const_type.x + const_type.y * const_type.y); uint first_leading_bit_abs = (((metal::clz(metal::abs(0u)) + 1) % 33) - 1); } diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 07a16f754..fc970f863 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 33 +; Bound: 36 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -18,7 +18,7 @@ OpEntryPoint Vertex %13 "main" %11 = OpConstantComposite %10 %6 %6 %14 = OpTypeFunction %2 %16 = OpTypeVector %4 4 -%23 = OpConstantNull %7 +%26 = OpConstantNull %7 %13 = OpFunction %2 None %14 %12 = OpLabel OpBranch %15 @@ -28,15 +28,18 @@ OpBranch %15 %19 = OpExtInst %4 %1 Radians %3 %20 = OpExtInst %16 %1 Degrees %17 %21 = OpExtInst %16 %1 Radians %17 -%24 = OpCompositeExtract %7 %11 0 -%25 = OpCompositeExtract %7 %11 0 -%26 = OpIMul %7 %24 %25 -%27 = OpIAdd %7 %23 %26 -%28 = OpCompositeExtract %7 %11 1 -%29 = OpCompositeExtract %7 %11 1 -%30 = OpIMul %7 %28 %29 -%22 = OpIAdd %7 %27 %30 -%31 = OpCopyObject %9 %8 -%32 = OpExtInst %9 %1 FindUMsb %31 +%23 = OpCompositeConstruct %16 %5 %5 %5 %5 +%24 = OpCompositeConstruct %16 %3 %3 %3 %3 +%22 = OpExtInst %16 %1 FClamp %17 %23 %24 +%27 = OpCompositeExtract %7 %11 0 +%28 = OpCompositeExtract %7 %11 0 +%29 = OpIMul %7 %27 %28 +%30 = OpIAdd %7 %26 %29 +%31 = OpCompositeExtract %7 %11 1 +%32 = OpCompositeExtract %7 %11 1 +%33 = OpIMul %7 %31 %32 +%25 = OpIAdd %7 %30 %33 +%34 = OpCopyObject %9 %8 +%35 = OpExtInst %9 %1 FindUMsb %34 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 954316879..2643879ee 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -5,6 +5,7 @@ fn main() { let b = radians(1.0); let c = degrees(v); let d = radians(v); + let e = saturate(v); let const_dot = dot(vec2(0, 0), vec2(0, 0)); let first_leading_bit_abs = firstLeadingBit(abs(0u)); } From 48e79388b506535d668df4f6c7be4e681812ab81 Mon Sep 17 00:00:00 2001 From: daxpedda Date: Tue, 16 Aug 2022 12:45:19 +0200 Subject: [PATCH 1812/2212] Implement `Clone` for `Module` (#2013) This is hidden behind the `clone` feature flag --- Cargo.toml | 1 + src/arena.rs | 2 ++ src/lib.rs | 9 +++++++++ 3 files changed, 12 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index c38ff67ad..5a6d62805 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ panic = "abort" [features] default = [] +clone = [] dot-out = [] glsl-in = ["pp-rs"] glsl-validate = [] diff --git a/src/arena.rs b/src/arena.rs index 1f970524e..d21a786cb 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -161,6 +161,7 @@ impl Iterator for Range { /// Adding new items to the arena produces a strongly-typed [`Handle`]. /// The arena can be indexed using the given handle to obtain /// a reference to the stored item. +#[cfg_attr(feature = "clone", derive(Clone))] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "serialize", serde(transparent))] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] @@ -412,6 +413,7 @@ mod tests { /// /// `UniqueArena` is similar to [`Arena`]: If `Arena` is vector-like, /// `UniqueArena` is `HashSet`-like. +#[cfg_attr(feature = "clone", derive(Clone))] pub struct UniqueArena { set: IndexSet, diff --git a/src/lib.rs b/src/lib.rs index 107534c8b..5db2a397d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -34,6 +34,9 @@ with optional span info, representing a series of statements executed in order. `EntryPoint`s or `Function` is a `Block`, and `Statement` has a [`Block`][Statement::Block] variant. +If the `clone` feature is enabled, [`Arena`], [`UniqueArena`], [`Type`], [`TypeInner`], +[`Constant`], [`Function`], [`EntryPoint`] and [`Module`] can be cloned. + ## Arenas To improve translator performance and reduce memory usage, most structures are @@ -558,6 +561,7 @@ pub enum ImageClass { /// A data type declared in the module. #[derive(Debug, Eq, Hash, PartialEq)] +#[cfg_attr(feature = "clone", derive(Clone))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] @@ -570,6 +574,7 @@ pub struct Type { /// Enum with additional information, depending on the kind of type. #[derive(Debug, Eq, Hash, PartialEq)] +#[cfg_attr(feature = "clone", derive(Clone))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] @@ -746,6 +751,7 @@ pub enum TypeInner { /// Constant value. #[derive(Debug, PartialEq)] +#[cfg_attr(feature = "clone", derive(Clone))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] @@ -1585,6 +1591,7 @@ pub struct FunctionResult { /// A function defined in the module. #[derive(Debug, Default)] +#[cfg_attr(feature = "clone", derive(Clone))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] @@ -1649,6 +1656,7 @@ pub struct Function { /// [`function`]: EntryPoint::function /// [`stage`]: EntryPoint::stage #[derive(Debug)] +#[cfg_attr(feature = "clone", derive(Clone))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] @@ -1679,6 +1687,7 @@ pub struct EntryPoint { /// /// When finished, you can export modules using one of the [available backends][back]. #[derive(Debug, Default)] +#[cfg_attr(feature = "clone", derive(Clone))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] From e7ddd3564c214d8acf554a03915d9bb179e0b772 Mon Sep 17 00:00:00 2001 From: Adeline <82405965+adeline-sparks@users.noreply.github.com> Date: Wed, 24 Aug 2022 17:05:11 -0400 Subject: [PATCH 1813/2212] glsl-in: Fix missing stores for local declarations (#2029) Previously, if a local variable was declared with a constant value, we would elide the store and instead give the variable an initial value (as if it was a global variable). This caused variables to not be re-initialized each time through a loop. --- src/front/glsl/parser/declarations.rs | 25 ++++++------ src/front/glsl/variables.rs | 2 +- tests/out/wgsl/246-collatz-comp.wgsl | 4 +- tests/out/wgsl/277-casting-vert.wgsl | 5 ++- tests/out/wgsl/280-matrix-cast-vert.wgsl | 5 ++- tests/out/wgsl/901-lhs-field-select-vert.wgsl | 4 +- tests/out/wgsl/932-for-loop-if-vert.wgsl | 3 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 21 +++++----- tests/out/wgsl/bits_glsl-frag.wgsl | 39 ++++++++++--------- tests/out/wgsl/constant-array-size-vert.wgsl | 7 ++-- tests/out/wgsl/declarations-vert.wgsl | 8 ++-- tests/out/wgsl/expressions-frag.wgsl | 24 +++++++----- tests/out/wgsl/long-form-matrix-vert.wgsl | 33 ++++++++-------- tests/out/wgsl/math-functions-vert.wgsl | 11 +++--- tests/out/wgsl/prepostfix-frag.wgsl | 11 +++--- tests/out/wgsl/sampler-functions-frag.wgsl | 3 +- tests/out/wgsl/swizzle_write-frag.wgsl | 4 +- 17 files changed, 112 insertions(+), 97 deletions(-) diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index a43f2fe77..346d20b19 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -190,19 +190,18 @@ impl<'source> ParsingContext<'source> { }) .transpose()?; - // If the declaration has an initializer try to make a constant out of it, - // this is only strictly needed for global constant declarations (and if the - // initializer can't be made a constant it should throw an error) but we also - // try to do it for all other types of declarations. - let maybe_constant = if let Some((root, meta)) = init { - let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; - - match parser.solve_constant(ctx.ctx, root, meta) { - Ok(res) => Some(res), - // If the declaration is external (global scope) and is constant qualified - // then the initializer must be a constant expression - Err(err) if ctx.external && is_const => return Err(err), - _ => None, + let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; + let maybe_constant = if ctx.external { + if let Some((root, meta)) = init { + match parser.solve_constant(ctx.ctx, root, meta) { + Ok(res) => Some(res), + // If the declaration is external (global scope) and is constant qualified + // then the initializer must be a constant expression + Err(err) if is_const => return Err(err), + _ => None, + } + } else { + None } } else { None diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 8375e1674..6aa20ce28 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -643,7 +643,7 @@ impl Parser { LocalVariable { name: decl.name.clone(), ty: decl.ty, - init: decl.init, + init: None, }, decl.meta, ); diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index 65f47ceb3..ffd05885e 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -8,11 +8,11 @@ var gl_GlobalInvocationID: vec3; fn collatz_iterations(n: u32) -> u32 { var n_1: u32; - var i: u32 = 0u; + var i: u32; _ = (&global.indices); n_1 = n; - _ = u32(0); + i = u32(0); loop { let _e7 = n_1; if !((_e7 != u32(1))) { diff --git a/tests/out/wgsl/277-casting-vert.wgsl b/tests/out/wgsl/277-casting-vert.wgsl index 13c86353b..045edd83f 100644 --- a/tests/out/wgsl/277-casting-vert.wgsl +++ b/tests/out/wgsl/277-casting-vert.wgsl @@ -1,7 +1,8 @@ fn main_1() { - var a: f32 = 1.0; + var a: f32; - _ = f32(1); + a = f32(1); + return; } @vertex diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl index 7c34f0756..86df4628e 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl @@ -1,8 +1,9 @@ fn main_1() { - var a: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + var a: mat4x4; let _e1 = f32(1); - _ = mat4x4(vec4(_e1, 0.0, 0.0, 0.0), vec4(0.0, _e1, 0.0, 0.0), vec4(0.0, 0.0, _e1, 0.0), vec4(0.0, 0.0, 0.0, _e1)); + a = mat4x4(vec4(_e1, 0.0, 0.0, 0.0), vec4(0.0, _e1, 0.0, 0.0), vec4(0.0, 0.0, _e1, 0.0), vec4(0.0, 0.0, 0.0, _e1)); + return; } @vertex diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl index 8f30bc8aa..1b4175809 100644 --- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl +++ b/tests/out/wgsl/901-lhs-field-select-vert.wgsl @@ -1,7 +1,7 @@ fn main_1() { - var a: vec4 = vec4(1.0, 1.0, 1.0, 1.0); + var a: vec4; - _ = vec4(1.0); + a = vec4(1.0); a.x = 2.0; return; } diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl index 2d599cca8..7fdd3c613 100644 --- a/tests/out/wgsl/932-for-loop-if-vert.wgsl +++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl @@ -1,6 +1,7 @@ fn main_1() { - var i: i32 = 0; + var i: i32; + i = 0; loop { let _e2 = i; if !((_e2 < 1)) { diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 339012853..8c48bd9ae 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -448,8 +448,8 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 var f0_8: vec3; var perceptual_roughness_1: f32; var NoV_7: f32; - var c0_: vec4 = vec4(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071); - var c1_: vec4 = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033); + var c0_: vec4; + var c1_: vec4; var r: vec4; var a004_: f32; var AB: vec2; @@ -468,8 +468,8 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 f0_8 = f0_7; perceptual_roughness_1 = perceptual_roughness; NoV_7 = NoV_6; - _ = vec4(-(1.0), -(0.027499999850988388), -(0.5720000267028809), 0.02199999988079071); - _ = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -(0.03999999910593033)); + c0_ = vec4(-(1.0), -(0.027499999850988388), -(0.5720000267028809), 0.02199999988079071); + c1_ = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -(0.03999999910593033)); let _e62 = perceptual_roughness_1; let _e64 = c0_; let _e66 = c1_; @@ -939,7 +939,7 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: var NoH_5: f32; var LoH_7: f32; var diffuse_1: vec3; - var specularIntensity_3: f32 = 1.0; + var specularIntensity_3: f32; var specular_2: vec3; _ = (&global.ViewProj); @@ -1010,6 +1010,7 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: let _e124 = LoH_7; let _e125 = Fd_Burley(_e121, _e122, _e123, _e124); diffuse_1 = (_e116 * _e125); + specularIntensity_3 = 1.0; _ = F0_3; _ = roughness_11; _ = half_vector; @@ -1055,9 +1056,9 @@ fn main_1() { var F0_4: vec3; var diffuseColor_4: vec3; var R_4: vec3; - var light_accum: vec3 = vec3(0.0, 0.0, 0.0); - var i: i32 = 0; - var i_1: i32 = 0; + var light_accum: vec3; + var i: i32; + var i_1: i32; var diffuse_ambient: vec3; var specular_ambient: vec3; @@ -1186,7 +1187,8 @@ fn main_1() { let _e217 = V_3; let _e219 = N_2; R_4 = reflect(-(_e217), _e219); - _ = vec3(0.0); + light_accum = vec3(0.0); + i = 0; loop { let _e227 = i; let _e228 = global_2.NumLights; @@ -1222,6 +1224,7 @@ fn main_1() { i = (_e236 + 1); } } + i_1 = 0; loop { let _e264 = i_1; let _e265 = global_2.NumLights; diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 8e1fb15f4..b68253a27 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -1,24 +1,25 @@ fn main_1() { - var i: i32 = 0; - var i2_: vec2 = vec2(0, 0); - var i3_: vec3 = vec3(0, 0, 0); - var i4_: vec4 = vec4(0, 0, 0, 0); - var u: u32 = 0u; - var u2_: vec2 = vec2(0u, 0u); - var u3_: vec3 = vec3(0u, 0u, 0u); - var u4_: vec4 = vec4(0u, 0u, 0u, 0u); - var f2_: vec2 = vec2(0.0, 0.0); - var f4_: vec4 = vec4(0.0, 0.0, 0.0, 0.0); + var i: i32; + var i2_: vec2; + var i3_: vec3; + var i4_: vec4; + var u: u32; + var u2_: vec2; + var u3_: vec3; + var u4_: vec4; + var f2_: vec2; + var f4_: vec4; - _ = vec2(0); - _ = vec3(0); - _ = vec4(0); - _ = u32(0); - _ = vec2(u32(0)); - _ = vec3(u32(0)); - _ = vec4(u32(0)); - _ = vec2(0.0); - _ = vec4(0.0); + i = 0; + i2_ = vec2(0); + i3_ = vec3(0); + i4_ = vec4(0); + u = u32(0); + u2_ = vec2(u32(0)); + u3_ = vec3(u32(0)); + u4_ = vec4(u32(0)); + f2_ = vec2(0.0); + f4_ = vec4(0.0); _ = f4_; let _e33 = f4_; u = pack4x8snorm(_e33); diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index ba193b7c5..f2f7f9d24 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -6,10 +6,11 @@ struct Data { var global: Data; fn function_() -> vec4 { - var sum: vec4 = vec4(0.0, 0.0, 0.0, 0.0); - var i: i32 = 0; + var sum: vec4; + var i: i32; - _ = vec4(f32(0)); + sum = vec4(f32(0)); + i = 0; loop { let _e9 = i; if !((_e9 < 42)) { diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-vert.wgsl index f0ab4c0fa..4b61704b9 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-vert.wgsl @@ -28,8 +28,8 @@ var array_2d: array,2u>; var array_toomanyd: array,2u>,2u>,2u>,2u>,2u>,2u>; fn main_1() { - var positions: array,2u> = array,2u>(vec3(-1.0, 1.0, 0.0), vec3(-1.0, -1.0, 0.0)); - var strct: TestStruct = TestStruct(1.0, 2.0); + var positions: array,2u>; + var strct: TestStruct; var from_input_array: vec4; var a_1: f32; var b: f32; @@ -38,8 +38,8 @@ fn main_1() { _ = (&vert.a); _ = (&frag.position); _ = (&frag.a); - _ = array,2u>(vec3(-(1.0), 1.0, 0.0), vec3(-(1.0), -(1.0), 0.0)); - _ = TestStruct(f32(1), f32(2)); + positions = array,2u>(vec3(-(1.0), 1.0, 0.0), vec3(-(1.0), -(1.0), 0.0)); + strct = TestStruct(f32(1), f32(2)); let _e35 = in_array_2[1]; from_input_array = _e35; let _e41 = array_2d[0][0]; diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 5c8a3de5f..f92bb53a5 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -274,21 +274,24 @@ fn testUnaryOpMat(a_16: mat3x3) { } fn testStructConstructor() { - var tree: BST = BST(1); + var tree: BST; - _ = BST(1); + tree = BST(1); + return; } fn testNonScalarToScalarConstructor() { - var f: f32 = 1.0; + var f: f32; - _ = f32(mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0))[0].x); + f = f32(mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0))[0].x); + return; } fn testArrayConstructor() { - var tree_1: array = array(0.0); + var tree_1: array; - _ = array(0.0); + tree_1 = array(0.0); + return; } fn testFreestandingConstructor() { @@ -296,10 +299,10 @@ fn testFreestandingConstructor() { } fn testNonImplicitCastVectorCast() { - var a_18: u32 = 1u; + var a_18: u32; var b_16: vec4; - _ = u32(1); + a_18 = u32(1); let _e3 = a_18; b_16 = vec4(i32(_e3)); return; @@ -384,12 +387,13 @@ fn testLength() { fn testConstantLength(a_24: array) { var a_25: array; - var len_1: i32 = 4; + var len_1: i32; _ = (&global_1.a); a_25 = a_24; _ = a_25; - _ = i32(4u); + len_1 = i32(4u); + return; } fn main_1() { diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl index 8ce67c709..5048a419a 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-vert.wgsl @@ -1,36 +1,37 @@ fn main_1() { - var splat: mat2x2 = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); - var normal: mat2x2 = mat2x2(vec2(1.0, 1.0), vec2(2.0, 2.0)); - var from_matrix: mat2x4 = mat2x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0)); - var a: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); - var b: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); - var c: mat3x3 = mat3x3(vec3(1.0, 2.0, 3.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); - var d: mat3x3 = mat3x3(vec3(2.0, 2.0, 1.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); - var e: mat4x4 = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); + var splat: mat2x2; + var normal: mat2x2; + var from_matrix: mat2x4; + var a: mat2x2; + var b: mat2x2; + var c: mat3x3; + var d: mat3x3; + var e: mat4x4; let _e1 = f32(1); - _ = mat2x2(vec2(_e1, 0.0), vec2(0.0, _e1)); + splat = mat2x2(vec2(_e1, 0.0), vec2(0.0, _e1)); let _e9 = vec2(f32(1)); let _e12 = vec2(f32(2)); - _ = mat2x2(vec2(_e9.x, _e9.y), vec2(_e12.x, _e12.y)); + normal = mat2x2(vec2(_e9.x, _e9.y), vec2(_e12.x, _e12.y)); let _e26 = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); - _ = mat2x4(vec4(_e26[0].x, _e26[0].y, _e26[0].z, 0.0), vec4(_e26[1].x, _e26[1].y, _e26[1].z, 0.0)); - _ = mat2x2(vec2(f32(1), f32(2)), vec2(f32(3), f32(4))); + from_matrix = mat2x4(vec4(_e26[0].x, _e26[0].y, _e26[0].z, 0.0), vec4(_e26[1].x, _e26[1].y, _e26[1].z, 0.0)); + a = mat2x2(vec2(f32(1), f32(2)), vec2(f32(3), f32(4))); let _e58 = vec2(f32(2), f32(3)); - _ = mat2x2(vec2(f32(1), _e58.x), vec2(_e58.y, f32(4))); + b = mat2x2(vec2(f32(1), _e58.x), vec2(_e58.y, f32(4))); let _e73 = vec3(f32(1)); let _e76 = vec3(f32(1)); - _ = mat3x3(vec3(f32(1), f32(2), f32(3)), vec3(_e73.x, _e73.y, _e73.z), vec3(_e76.x, _e76.y, _e76.z)); + c = mat3x3(vec3(f32(1), f32(2), f32(3)), vec3(_e73.x, _e73.y, _e73.z), vec3(_e76.x, _e76.y, _e76.z)); let _e93 = vec2(f32(2)); let _e97 = vec3(f32(1)); let _e100 = vec3(f32(1)); - _ = mat3x3(vec3(_e93.x, _e93.y, f32(1)), vec3(_e97.x, _e97.y, _e97.z), vec3(_e100.x, _e100.y, _e100.z)); + d = mat3x3(vec3(_e93.x, _e93.y, f32(1)), vec3(_e97.x, _e97.y, _e97.z), vec3(_e100.x, _e100.y, _e100.z)); let _e117 = vec2(f32(2)); let _e120 = vec4(f32(1)); let _e123 = vec2(f32(2)); let _e126 = vec4(f32(1)); let _e129 = vec4(f32(1)); - _ = mat4x4(vec4(_e117.x, _e117.y, _e120.x, _e120.y), vec4(_e120.z, _e120.w, _e123.x, _e123.y), vec4(_e126.x, _e126.y, _e126.z, _e126.w), vec4(_e129.x, _e129.y, _e129.z, _e129.w)); + e = mat4x4(vec4(_e117.x, _e117.y, _e120.x, _e120.y), vec4(_e120.z, _e120.w, _e123.x, _e123.y), vec4(_e126.x, _e126.y, _e126.z, _e126.w), vec4(_e129.x, _e129.y, _e129.z, _e129.w)); + return; } @vertex diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl index 58e95f673..0d499fc58 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-vert.wgsl @@ -1,8 +1,8 @@ fn main_1() { - var a: vec4 = vec4(1.0, 1.0, 1.0, 1.0); - var b: vec4 = vec4(2.0, 2.0, 2.0, 2.0); + var a: vec4; + var b: vec4; var m: mat4x4; - var i: i32 = 5; + var i: i32; var ceilOut: vec4; var roundOut: vec4; var floorOut: vec4; @@ -48,13 +48,14 @@ fn main_1() { var smoothStepVector: vec4; var smoothStepMixed: vec4; - _ = vec4(1.0); - _ = vec4(2.0); + a = vec4(1.0); + b = vec4(2.0); let _e6 = a; let _e7 = b; let _e8 = a; let _e9 = b; m = mat4x4(vec4(_e6.x, _e6.y, _e6.z, _e6.w), vec4(_e7.x, _e7.y, _e7.z, _e7.w), vec4(_e8.x, _e8.y, _e8.z, _e8.w), vec4(_e9.x, _e9.y, _e9.z, _e9.w)); + i = 5; _ = a; let _e35 = a; ceilOut = ceil(_e35); diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index f020792af..72347bfd6 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -1,11 +1,12 @@ fn main_1() { var scalar_target: i32; - var scalar: i32 = 1; + var scalar: i32; var vec_target: vec2; - var vec_: vec2 = vec2(1u, 1u); + var vec_: vec2; var mat_target: mat4x3; - var mat_: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); + var mat_: mat4x3; + scalar = 1; let _e3 = scalar; scalar = (_e3 + 1); scalar_target = _e3; @@ -13,7 +14,7 @@ fn main_1() { let _e8 = (_e6 - 1); scalar = _e8; scalar_target = _e8; - _ = vec2(u32(1)); + vec_ = vec2(u32(1)); let _e14 = vec_; vec_ = (_e14 - vec2(1u)); vec_target = _e14; @@ -22,7 +23,7 @@ fn main_1() { vec_ = _e21; vec_target = _e21; let _e24 = f32(1); - _ = mat4x3(vec3(_e24, 0.0, 0.0), vec3(0.0, _e24, 0.0), vec3(0.0, 0.0, _e24), vec3(0.0, 0.0, 0.0)); + mat_ = mat4x3(vec3(_e24, 0.0, 0.0), vec3(0.0, _e24, 0.0), vec3(0.0, 0.0, _e24), vec3(0.0, 0.0, 0.0)); let _e32 = mat_; let _e34 = vec3(1.0); mat_ = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); diff --git a/tests/out/wgsl/sampler-functions-frag.wgsl b/tests/out/wgsl/sampler-functions-frag.wgsl index e9e4830ee..805dc8f7f 100644 --- a/tests/out/wgsl/sampler-functions-frag.wgsl +++ b/tests/out/wgsl/sampler-functions-frag.wgsl @@ -1,8 +1,9 @@ fn CalcShadowPCF1_(T_P_t_TextureDepth: texture_depth_2d, S_P_t_TextureDepth: sampler_comparison, t_ProjCoord: vec3) -> f32 { var t_ProjCoord_1: vec3; - var t_Res: f32 = 0.0; + var t_Res: f32; t_ProjCoord_1 = t_ProjCoord; + t_Res = 0.0; let _e6 = t_Res; let _e7 = t_ProjCoord_1; _ = _e7.xyz; diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl index a6d7da9e9..e6b29a58e 100644 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ b/tests/out/wgsl/swizzle_write-frag.wgsl @@ -3,10 +3,10 @@ fn foo(p: ptr>) { } fn main_1() { - var x: vec3 = vec3(2.0, 2.0, 2.0); + var x: vec3; var local: vec2; - _ = vec3(2.0); + x = vec3(2.0); let _e3 = x; _ = _e3.zxy; _ = _e3.zx; From 9df243c42c8042a8db558741030d67bba5a05003 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 29 Aug 2022 11:58:02 +0100 Subject: [PATCH 1814/2212] hlsl-out: Add support for push constants (#2005) Push constants need to be configured by the consumer which must pass the bind target of the constant buffer used for the push constants. --- Makefile | 4 +- src/back/hlsl/mod.rs | 3 + src/back/hlsl/writer.rs | 124 +++++++++++------- tests/in/push-constants.param.ron | 7 + tests/in/push-constants.wgsl | 8 ++ .../glsl/push-constants.vert_main.Vertex.glsl | 23 ++++ tests/out/hlsl/push-constants.hlsl | 33 +++++ tests/out/hlsl/push-constants.hlsl.config | 3 + tests/snapshots.rs | 2 +- 9 files changed, 155 insertions(+), 52 deletions(-) create mode 100644 tests/out/glsl/push-constants.vert_main.Vertex.glsl create mode 100644 tests/out/hlsl/push-constants.hlsl create mode 100644 tests/out/hlsl/push-constants.hlsl.config diff --git a/Makefile b/Makefile index a491722af..de27e3049 100644 --- a/Makefile +++ b/Makefile @@ -69,7 +69,7 @@ validate-wgsl: $(SNAPSHOTS_BASE_OUT)/wgsl/*.wgsl cargo run $${file}; \ done -validate-hlsl-dxc: SHELL:=/bin/bash # required because config files uses arrays +validate-hlsl-dxc: SHELL:=/usr/bin/env bash # required because config files uses arrays validate-hlsl-dxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl @set -e && for file in $^ ; do \ DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug -Od"; \ @@ -94,7 +94,7 @@ validate-hlsl-dxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl echo "======================"; \ done -validate-hlsl-fxc: SHELL:=/bin/bash # required because config files uses arrays +validate-hlsl-fxc: SHELL:=/usr/bin/env bash # required because config files uses arrays validate-hlsl-fxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl @set -e && for file in $^ ; do \ FXC_PARAMS="-Zi -Od"; \ diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 76abb2978..333ea2cf1 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -189,6 +189,8 @@ pub struct Options { /// Add special constants to `SV_VertexIndex` and `SV_InstanceIndex`, /// to make them work like in Vulkan/Metal, with help of the host. pub special_constants_binding: Option, + /// Bind target of the push constant buffer + pub push_constants_target: Option, } impl Default for Options { @@ -198,6 +200,7 @@ impl Default for Options { binding_map: BindingMap::default(), fake_missing_bindings: true, special_constants_binding: None, + push_constants_target: None, } } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index ae761ead4..42e306079 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -623,12 +623,45 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_type(module, global.ty)?; register } - crate::AddressSpace::PushConstant => unimplemented!("Push constants"), + crate::AddressSpace::PushConstant => { + // The type of the push constants will be wrapped in `ConstantBuffer` + write!(self.out, "ConstantBuffer<")?; + "b" + } }; + // If the global is a push constant write the type now because it will be a + // generic argument to `ConstantBuffer` + if global.space == crate::AddressSpace::PushConstant { + self.write_global_type(module, global.ty)?; + + // need to write the array size if the type was emitted with `write_type` + if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner { + self.write_array_size(module, base, size)?; + } + + // Close the angled brackets for the generic argument + write!(self.out, ">")?; + } + let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, " {}", name)?; + // Push constants need to be assigned a binding explicitly by the consumer + // since naga has no way to know the binding from the shader alone + if global.space == crate::AddressSpace::PushConstant { + let target = self + .options + .push_constants_target + .as_ref() + .expect("No bind target was defined for the push constants block"); + write!(self.out, ": register(b{}", target.register)?; + if target.space != 0 { + write!(self.out, ", space{}", target.space)?; + } + write!(self.out, ")")?; + } + if let Some(ref binding) = global.binding { // this was already resolved earlier when we started evaluating an entry point. let bt = self.options.resolve_resource_binding(binding).unwrap(); @@ -665,34 +698,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if global.space == crate::AddressSpace::Uniform { write!(self.out, " {{ ")?; - let matrix_data = get_inner_matrix_data(module, global.ty); + self.write_global_type(module, global.ty)?; - // We treat matrices of the form `matCx2` as a sequence of C `vec2`s. - // See the module-level block comment in mod.rs for details. - if let Some(MatrixType { - columns, - rows: crate::VectorSize::Bi, - width: 4, - }) = matrix_data - { - write!( - self.out, - "__mat{}x2 {}", - columns as u8, - &self.names[&NameKey::GlobalVariable(handle)] - )?; - } else { - // Even though Naga IR matrices are column-major, we must describe - // matrices passed from the CPU as being in row-major order. - // See the module-level block comment in mod.rs for details. - if matrix_data.is_some() { - write!(self.out, "row_major ")?; - } - - self.write_type(module, global.ty)?; - let sub_name = &self.names[&NameKey::GlobalVariable(handle)]; - write!(self.out, " {}", sub_name)?; - } + write!( + self.out, + " {}", + &self.names[&NameKey::GlobalVariable(handle)] + )?; // need to write the array size if the type was emitted with `write_type` if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner { @@ -829,27 +841,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { TypeInner::Array { base, size, .. } => { // HLSL arrays are written as `type name[size]` - let matrix_data = get_inner_matrix_data(module, member.ty); - - // We treat matrices of the form `matCx2` as a sequence of C `vec2`s. - // See the module-level block comment in mod.rs for details. - if let Some(MatrixType { - columns, - rows: crate::VectorSize::Bi, - width: 4, - }) = matrix_data - { - write!(self.out, "__mat{}x2", columns as u8)?; - } else { - // Even though Naga IR matrices are column-major, we must describe - // matrices passed from the CPU as being in row-major order. - // See the module-level block comment in mod.rs for details. - if matrix_data.is_some() { - write!(self.out, "row_major ")?; - } - - self.write_type(module, base)?; - } + self.write_global_type(module, member.ty)?; // Write `name` write!( @@ -923,6 +915,40 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } + /// Helper method used to write global/structs non image/sampler types + /// + /// # Notes + /// Adds no trailing or leading whitespace + pub(super) fn write_global_type( + &mut self, + module: &Module, + ty: Handle, + ) -> BackendResult { + let matrix_data = get_inner_matrix_data(module, ty); + + // We treat matrices of the form `matCx2` as a sequence of C `vec2`s. + // See the module-level block comment in mod.rs for details. + if let Some(MatrixType { + columns, + rows: crate::VectorSize::Bi, + width: 4, + }) = matrix_data + { + write!(self.out, "__mat{}x2", columns as u8)?; + } else { + // Even though Naga IR matrices are column-major, we must describe + // matrices passed from the CPU as being in row-major order. + // See the module-level block comment in mod.rs for details. + if matrix_data.is_some() { + write!(self.out, "row_major ")?; + } + + self.write_type(module, ty)?; + } + + Ok(()) + } + /// Helper method used to write non image/sampler types /// /// # Notes diff --git a/tests/in/push-constants.param.ron b/tests/in/push-constants.param.ron index 3972328c9..a5cfe142c 100644 --- a/tests/in/push-constants.param.ron +++ b/tests/in/push-constants.param.ron @@ -8,4 +8,11 @@ writer_flags: (bits: 0), binding_map: {}, ), + hlsl: ( + shader_model: V5_1, + binding_map: {}, + fake_missing_bindings: true, + special_constants_binding: Some((space: 1, register: 0)), + push_constants_target: Some((space: 0, register: 0)), + ), ) diff --git a/tests/in/push-constants.wgsl b/tests/in/push-constants.wgsl index cc8c4ab02..b3dc51523 100644 --- a/tests/in/push-constants.wgsl +++ b/tests/in/push-constants.wgsl @@ -7,6 +7,14 @@ struct FragmentIn { @location(0) color: vec4 } +@vertex +fn vert_main( + @location(0) pos : vec2, + @builtin(vertex_index) vi: u32, +) -> @builtin(position) vec4 { + return vec4(f32(vi) * pc.multiplier * pos, 0.0, 1.0); +} + @fragment fn main(in: FragmentIn) -> @location(0) vec4 { return in.color * pc.multiplier; diff --git a/tests/out/glsl/push-constants.vert_main.Vertex.glsl b/tests/out/glsl/push-constants.vert_main.Vertex.glsl new file mode 100644 index 000000000..27cd7037a --- /dev/null +++ b/tests/out/glsl/push-constants.vert_main.Vertex.glsl @@ -0,0 +1,23 @@ +#version 320 es + +precision highp float; +precision highp int; + +struct PushConstants { + float multiplier; +}; +struct FragmentIn { + vec4 color; +}; +uniform PushConstants pc; + +layout(location = 0) in vec2 _p2vs_location0; + +void main() { + vec2 pos = _p2vs_location0; + uint vi = uint(gl_VertexID); + float _e5 = pc.multiplier; + gl_Position = vec4(((float(vi) * _e5) * pos), 0.0, 1.0); + return; +} + diff --git a/tests/out/hlsl/push-constants.hlsl b/tests/out/hlsl/push-constants.hlsl new file mode 100644 index 000000000..22b4b6acd --- /dev/null +++ b/tests/out/hlsl/push-constants.hlsl @@ -0,0 +1,33 @@ +struct NagaConstants { + int base_vertex; + int base_instance; + uint other; +}; +ConstantBuffer _NagaConstants: register(b0, space1); + +struct PushConstants { + float multiplier; +}; + +struct FragmentIn { + float4 color : LOC0; +}; + +ConstantBuffer pc: register(b0); + +struct FragmentInput_main { + float4 color : LOC0; +}; + +float4 vert_main(float2 pos : LOC0, uint vi : SV_VertexID) : SV_Position +{ + float _expr5 = pc.multiplier; + return float4(((float((_NagaConstants.base_vertex + vi)) * _expr5) * pos), 0.0, 1.0); +} + +float4 main(FragmentInput_main fragmentinput_main) : SV_Target0 +{ + FragmentIn in_ = { fragmentinput_main.color }; + float _expr4 = pc.multiplier; + return (in_.color * _expr4); +} diff --git a/tests/out/hlsl/push-constants.hlsl.config b/tests/out/hlsl/push-constants.hlsl.config new file mode 100644 index 000000000..f214655f7 --- /dev/null +++ b/tests/out/hlsl/push-constants.hlsl.config @@ -0,0 +1,3 @@ +vertex=(vert_main:vs_5_1 ) +fragment=(main:ps_5_1 ) +compute=() diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d7837e34f..fa32580e3 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -471,7 +471,7 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::HLSL | Targets::WGSL | Targets::GLSL, ), ("extra", Targets::SPIRV | Targets::METAL | Targets::WGSL), - ("push-constants", Targets::GLSL), + ("push-constants", Targets::GLSL | Targets::HLSL), ( "operators", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From 6b3c111f3fd4005ed06f3bb52eabe961f0d869de Mon Sep 17 00:00:00 2001 From: Nicolas Silva Date: Thu, 1 Sep 2022 15:42:14 +0200 Subject: [PATCH 1815/2212] Don't decorate varyings with interpolation modes at the beginning and end of the pipeline. Fixes #2036. --- src/back/spv/writer.rs | 70 +++++++++++++++++++++------ tests/out/spv/interface.vertex.spvasm | 1 - tests/out/spv/shadow.spvasm | 2 - 3 files changed, 54 insertions(+), 19 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 6e8758f0c..2506b9ba9 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -340,10 +340,22 @@ impl Writer { }; if let Some(ref mut iface) = interface { + use crate::ShaderStage; + let interpolation_decoration = match iface.stage { + ShaderStage::Vertex | ShaderStage::Compute => false, + ShaderStage::Fragment => true, + }; let id = if let Some(ref binding) = argument.binding { let name = argument.name.as_ref().map(AsRef::as_ref); - let varying_id = - self.write_varying(ir_module, class, name, argument.ty, binding)?; + + let varying_id = self.write_varying( + ir_module, + class, + name, + argument.ty, + binding, + interpolation_decoration, + )?; iface.varying_ids.push(varying_id); let id = self.id_gen.next(); prelude @@ -359,8 +371,14 @@ impl Writer { let type_id = self.get_type_id(LookupType::Handle(member.ty)); let name = member.name.as_ref().map(AsRef::as_ref); let binding = member.binding.as_ref().unwrap(); - let varying_id = - self.write_varying(ir_module, class, name, member.ty, binding)?; + let varying_id = self.write_varying( + ir_module, + class, + name, + member.ty, + binding, + interpolation_decoration, + )?; iface.varying_ids.push(varying_id); let id = self.id_gen.next(); prelude @@ -408,14 +426,25 @@ impl Writer { let return_type_id = match ir_function.result { Some(ref result) => { if let Some(ref mut iface) = interface { + use crate::ShaderStage; + let interpolation_decoration = match iface.stage { + ShaderStage::Fragment | ShaderStage::Compute => false, + ShaderStage::Vertex => true, + }; let mut has_point_size = false; let class = spirv::StorageClass::Output; if let Some(ref binding) = result.binding { has_point_size |= *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); let type_id = self.get_type_id(LookupType::Handle(result.ty)); - let varying_id = - self.write_varying(ir_module, class, None, result.ty, binding)?; + let varying_id = self.write_varying( + ir_module, + class, + None, + result.ty, + binding, + interpolation_decoration, + )?; iface.varying_ids.push(varying_id); ep_context.results.push(ResultMember { id: varying_id, @@ -431,8 +460,14 @@ impl Writer { let binding = member.binding.as_ref().unwrap(); has_point_size |= *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); - let varying_id = - self.write_varying(ir_module, class, name, member.ty, binding)?; + let varying_id = self.write_varying( + ir_module, + class, + name, + member.ty, + binding, + interpolation_decoration, + )?; iface.varying_ids.push(varying_id); ep_context.results.push(ResultMember { id: varying_id, @@ -1119,6 +1154,7 @@ impl Writer { debug_name: Option<&str>, ty: Handle, binding: &crate::Binding, + interpolation_decoration: bool, ) -> Result { let id = self.id_gen.next(); let pointer_type_id = self.get_pointer_id(&ir_module.types, ty, class)?; @@ -1144,14 +1180,16 @@ impl Writer { } => { self.decorate(id, Decoration::Location, &[location]); - match interpolation { - // Perspective-correct interpolation is the default in SPIR-V. - None | Some(crate::Interpolation::Perspective) => (), - Some(crate::Interpolation::Flat) => { - self.decorate(id, Decoration::Flat, &[]); - } - Some(crate::Interpolation::Linear) => { - self.decorate(id, Decoration::NoPerspective, &[]); + if interpolation_decoration { + match interpolation { + // Perspective-correct interpolation is the default in SPIR-V. + None | Some(crate::Interpolation::Perspective) => (), + Some(crate::Interpolation::Flat) => { + self.decorate(id, Decoration::Flat, &[]); + } + Some(crate::Interpolation::Linear) => { + self.decorate(id, Decoration::NoPerspective, &[]); + } } } diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index 645077ca2..62e4acb1b 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -17,7 +17,6 @@ OpMemberDecorate %19 0 Offset 0 OpDecorate %21 BuiltIn VertexIndex OpDecorate %24 BuiltIn InstanceIndex OpDecorate %26 Location 10 -OpDecorate %26 Flat OpDecorate %28 Invariant OpDecorate %28 BuiltIn Position OpDecorate %30 Location 1 diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index 30829d28a..e20fcebc5 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -96,9 +96,7 @@ OpDecorate %43 Binding 2 OpDecorate %45 DescriptorSet 0 OpDecorate %45 Binding 3 OpDecorate %84 Location 0 -OpDecorate %84 Flat OpDecorate %87 Location 1 -OpDecorate %87 Flat OpDecorate %89 BuiltIn Position OpDecorate %91 Location 0 OpDecorate %93 Location 1 From b63436af36f23e9d36d0762df19072682b23ebc8 Mon Sep 17 00:00:00 2001 From: Nicolas Silva Date: Wed, 31 Aug 2022 11:17:05 +0200 Subject: [PATCH 1816/2212] Decorate most builtins as Flat in the spirv writer. Fixes #2032 --- src/back/spv/writer.rs | 20 +++++++++++++++++++ tests/out/spv/access.spvasm | 1 + tests/out/spv/boids.spvasm | 1 + tests/out/spv/collatz.spvasm | 1 + tests/out/spv/control-flow.spvasm | 1 + tests/out/spv/extra.spvasm | 1 + tests/out/spv/image.spvasm | 2 ++ tests/out/spv/interface.compute.spvasm | 5 +++++ tests/out/spv/interface.fragment.spvasm | 4 ++++ tests/out/spv/interface.vertex.spvasm | 2 ++ .../spv/interface.vertex_two_structs.spvasm | 2 ++ tests/out/spv/multiview.spvasm | 1 + tests/out/spv/skybox.spvasm | 1 + 13 files changed, 42 insertions(+) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 2506b9ba9..2b4a72303 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1263,6 +1263,26 @@ impl Writer { }; self.decorate(id, Decoration::BuiltIn, &[built_in as u32]); + + use crate::ScalarKind as Sk; + + // Per the Vulkan spec, `VUID-StandaloneSpirv-Flat-04744`: + // + // > Any variable with integer or double-precision floating- + // > point type and with Input storage class in a fragment + // > shader, must be decorated Flat + let is_flat = match ir_module.types[ty].inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } => match kind { + Sk::Uint | Sk::Sint | Sk::Bool => true, + Sk::Float => false, + }, + _ => false, + }; + + if is_flat { + self.decorate(id, Decoration::Flat, &[]); + } } } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index fe7e75d4a..a710a39b9 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -98,6 +98,7 @@ OpDecorate %78 Binding 3 OpDecorate %79 Block OpMemberDecorate %79 0 Offset 0 OpDecorate %228 BuiltIn VertexIndex +OpDecorate %228 Flat OpDecorate %231 BuiltIn Position OpDecorate %273 Location 0 %2 = OpTypeVoid diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 887cdb6ad..69a7433b3 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -61,6 +61,7 @@ OpDecorate %26 DescriptorSet 0 OpDecorate %26 Binding 2 OpDecorate %19 Block OpDecorate %48 BuiltIn GlobalInvocationId +OpDecorate %48 Flat %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 1500 diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index 6e6483da1..c3630f916 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -24,6 +24,7 @@ OpDecorate %11 DescriptorSet 0 OpDecorate %11 Binding 0 OpDecorate %9 Block OpDecorate %46 BuiltIn GlobalInvocationId +OpDecorate %46 Flat %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index dfd1b145a..467393b01 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -8,6 +8,7 @@ OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %44 "main" %41 OpExecutionMode %44 LocalSize 1 1 1 OpDecorate %41 BuiltIn GlobalInvocationId +OpDecorate %41 Flat %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index bf0f92e7b..99a367c64 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -17,6 +17,7 @@ OpDecorate %12 Block OpMemberDecorate %12 0 Offset 0 OpDecorate %16 Location 0 OpDecorate %19 BuiltIn PrimitiveId +OpDecorate %19 Flat OpDecorate %22 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 7ad2b3560..35f973442 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -95,7 +95,9 @@ OpDecorate %68 Binding 2 OpDecorate %70 DescriptorSet 1 OpDecorate %70 Binding 3 OpDecorate %73 BuiltIn LocalInvocationId +OpDecorate %73 Flat OpDecorate %119 BuiltIn LocalInvocationId +OpDecorate %119 Flat OpDecorate %140 BuiltIn Position OpDecorate %193 BuiltIn Position OpDecorate %222 Location 0 diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index 6c1dac372..748b445b6 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -16,10 +16,15 @@ OpDecorate %16 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 OpDecorate %23 BuiltIn GlobalInvocationId +OpDecorate %23 Flat OpDecorate %26 BuiltIn LocalInvocationId +OpDecorate %26 Flat OpDecorate %28 BuiltIn LocalInvocationIndex +OpDecorate %28 Flat OpDecorate %31 BuiltIn WorkgroupId +OpDecorate %31 Flat OpDecorate %33 BuiltIn NumWorkgroups +OpDecorate %33 Flat %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 154747e5f..503345825 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -21,10 +21,14 @@ OpDecorate %22 Invariant OpDecorate %22 BuiltIn FragCoord OpDecorate %25 Location 1 OpDecorate %28 BuiltIn FrontFacing +OpDecorate %28 Flat OpDecorate %31 BuiltIn SampleId +OpDecorate %31 Flat OpDecorate %34 BuiltIn SampleMask +OpDecorate %34 Flat OpDecorate %36 BuiltIn FragDepth OpDecorate %38 BuiltIn SampleMask +OpDecorate %38 Flat OpDecorate %40 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index 62e4acb1b..83a6aae82 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -15,7 +15,9 @@ OpDecorate %16 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 OpDecorate %21 BuiltIn VertexIndex +OpDecorate %21 Flat OpDecorate %24 BuiltIn InstanceIndex +OpDecorate %24 Flat OpDecorate %26 Location 10 OpDecorate %28 Invariant OpDecorate %28 BuiltIn Position diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index 190f391c3..dc681b5b4 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -15,7 +15,9 @@ OpDecorate %16 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 OpDecorate %24 BuiltIn VertexIndex +OpDecorate %24 Flat OpDecorate %28 BuiltIn InstanceIndex +OpDecorate %28 Flat OpDecorate %30 Invariant OpDecorate %30 BuiltIn Position OpDecorate %32 BuiltIn PointSize diff --git a/tests/out/spv/multiview.spvasm b/tests/out/spv/multiview.spvasm index bb67d7eba..343396ea0 100644 --- a/tests/out/spv/multiview.spvasm +++ b/tests/out/spv/multiview.spvasm @@ -9,6 +9,7 @@ OpExtension "SPV_KHR_multiview" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %8 "main" %5 OpDecorate %5 BuiltIn ViewIndex +OpDecorate %5 Flat %2 = OpTypeVoid %3 = OpTypeInt 32 1 %6 = OpTypePointer Input %3 diff --git a/tests/out/spv/skybox.spvasm b/tests/out/spv/skybox.spvasm index ca51a06dd..227c7786e 100644 --- a/tests/out/spv/skybox.spvasm +++ b/tests/out/spv/skybox.spvasm @@ -25,6 +25,7 @@ OpDecorate %22 Binding 1 OpDecorate %24 DescriptorSet 0 OpDecorate %24 Binding 2 OpDecorate %32 BuiltIn VertexIndex +OpDecorate %32 Flat OpDecorate %35 BuiltIn Position OpDecorate %37 Location 0 OpDecorate %83 BuiltIn FragCoord From 5be898e7e76e2410485fab1e5b3de6bc39452571 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 1 Sep 2022 09:34:44 -0700 Subject: [PATCH 1817/2212] Use `Option::as_deref` as appropriate. --- src/back/spv/writer.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 2b4a72303..0bb937c2e 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -346,7 +346,7 @@ impl Writer { ShaderStage::Fragment => true, }; let id = if let Some(ref binding) = argument.binding { - let name = argument.name.as_ref().map(AsRef::as_ref); + let name = argument.name.as_deref(); let varying_id = self.write_varying( ir_module, @@ -369,7 +369,7 @@ impl Writer { let mut constituent_ids = Vec::with_capacity(members.len()); for member in members { let type_id = self.get_type_id(LookupType::Handle(member.ty)); - let name = member.name.as_ref().map(AsRef::as_ref); + let name = member.name.as_deref(); let binding = member.binding.as_ref().unwrap(); let varying_id = self.write_varying( ir_module, @@ -456,7 +456,7 @@ impl Writer { { for member in members { let type_id = self.get_type_id(LookupType::Handle(member.ty)); - let name = member.name.as_ref().map(AsRef::as_ref); + let name = member.name.as_deref(); let binding = member.binding.as_ref().unwrap(); has_point_size |= *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); From b209d911681c4ef563f7d9048623667743e6248f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 1 Sep 2022 13:44:36 -0700 Subject: [PATCH 1818/2212] [spv-out] Properly combine the fixes for #2035 and #2038. The Vulkan decoration rules require us to distinguish vertex shader inputs, fragment shader inputs, and everything else, so just pass the stage to `Writer::write_varying`. Together with the SPIRV storage class, this is sufficient to distinguish all the cases in a way that closely follows the spec language. --- src/back/spv/writer.rs | 49 +++++++++---------- tests/out/spv/access.spvasm | 1 - tests/out/spv/boids.spvasm | 1 - tests/out/spv/collatz.spvasm | 1 - tests/out/spv/control-flow.spvasm | 1 - tests/out/spv/image.spvasm | 2 - tests/out/spv/interface.compute.spvasm | 5 -- tests/out/spv/interface.fragment.spvasm | 1 - tests/out/spv/interface.vertex.spvasm | 2 - .../spv/interface.vertex_two_structs.spvasm | 2 - tests/out/spv/multiview.spvasm | 1 - tests/out/spv/skybox.spvasm | 1 - 12 files changed, 23 insertions(+), 44 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 0bb937c2e..59fe739f2 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -340,21 +340,16 @@ impl Writer { }; if let Some(ref mut iface) = interface { - use crate::ShaderStage; - let interpolation_decoration = match iface.stage { - ShaderStage::Vertex | ShaderStage::Compute => false, - ShaderStage::Fragment => true, - }; let id = if let Some(ref binding) = argument.binding { let name = argument.name.as_deref(); let varying_id = self.write_varying( ir_module, + iface.stage, class, name, argument.ty, binding, - interpolation_decoration, )?; iface.varying_ids.push(varying_id); let id = self.id_gen.next(); @@ -373,11 +368,11 @@ impl Writer { let binding = member.binding.as_ref().unwrap(); let varying_id = self.write_varying( ir_module, + iface.stage, class, name, member.ty, binding, - interpolation_decoration, )?; iface.varying_ids.push(varying_id); let id = self.id_gen.next(); @@ -426,11 +421,6 @@ impl Writer { let return_type_id = match ir_function.result { Some(ref result) => { if let Some(ref mut iface) = interface { - use crate::ShaderStage; - let interpolation_decoration = match iface.stage { - ShaderStage::Fragment | ShaderStage::Compute => false, - ShaderStage::Vertex => true, - }; let mut has_point_size = false; let class = spirv::StorageClass::Output; if let Some(ref binding) = result.binding { @@ -439,11 +429,11 @@ impl Writer { let type_id = self.get_type_id(LookupType::Handle(result.ty)); let varying_id = self.write_varying( ir_module, + iface.stage, class, None, result.ty, binding, - interpolation_decoration, )?; iface.varying_ids.push(varying_id); ep_context.results.push(ResultMember { @@ -462,11 +452,11 @@ impl Writer { *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize); let varying_id = self.write_varying( ir_module, + iface.stage, class, name, member.ty, binding, - interpolation_decoration, )?; iface.varying_ids.push(varying_id); ep_context.results.push(ResultMember { @@ -1150,11 +1140,11 @@ impl Writer { fn write_varying( &mut self, ir_module: &crate::Module, + stage: crate::ShaderStage, class: spirv::StorageClass, debug_name: Option<&str>, ty: Handle, binding: &crate::Binding, - interpolation_decoration: bool, ) -> Result { let id = self.id_gen.next(); let pointer_type_id = self.get_pointer_id(&ir_module.types, ty, class)?; @@ -1180,7 +1170,12 @@ impl Writer { } => { self.decorate(id, Decoration::Location, &[location]); - if interpolation_decoration { + // The Vulkan spec says: VUID-StandaloneSpirv-Flat-06202 + // + // > The Flat, NoPerspective, Sample, and Centroid decorations + // > must not be used on variables with the Input storage class in + // > a vertex shader + if class != spirv::StorageClass::Input || stage != crate::ShaderStage::Vertex { match interpolation { // Perspective-correct interpolation is the default in SPIR-V. None | Some(crate::Interpolation::Perspective) => (), @@ -1271,17 +1266,19 @@ impl Writer { // > Any variable with integer or double-precision floating- // > point type and with Input storage class in a fragment // > shader, must be decorated Flat - let is_flat = match ir_module.types[ty].inner { - crate::TypeInner::Scalar { kind, .. } - | crate::TypeInner::Vector { kind, .. } => match kind { - Sk::Uint | Sk::Sint | Sk::Bool => true, - Sk::Float => false, - }, - _ => false, - }; + if class == spirv::StorageClass::Input && stage == crate::ShaderStage::Fragment { + let is_flat = match ir_module.types[ty].inner { + crate::TypeInner::Scalar { kind, .. } + | crate::TypeInner::Vector { kind, .. } => match kind { + Sk::Uint | Sk::Sint | Sk::Bool => true, + Sk::Float => false, + }, + _ => false, + }; - if is_flat { - self.decorate(id, Decoration::Flat, &[]); + if is_flat { + self.decorate(id, Decoration::Flat, &[]); + } } } } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index a710a39b9..fe7e75d4a 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -98,7 +98,6 @@ OpDecorate %78 Binding 3 OpDecorate %79 Block OpMemberDecorate %79 0 Offset 0 OpDecorate %228 BuiltIn VertexIndex -OpDecorate %228 Flat OpDecorate %231 BuiltIn Position OpDecorate %273 Location 0 %2 = OpTypeVoid diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 69a7433b3..887cdb6ad 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -61,7 +61,6 @@ OpDecorate %26 DescriptorSet 0 OpDecorate %26 Binding 2 OpDecorate %19 Block OpDecorate %48 BuiltIn GlobalInvocationId -OpDecorate %48 Flat %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 1500 diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index c3630f916..6e6483da1 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -24,7 +24,6 @@ OpDecorate %11 DescriptorSet 0 OpDecorate %11 Binding 0 OpDecorate %9 Block OpDecorate %46 BuiltIn GlobalInvocationId -OpDecorate %46 Flat %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index 467393b01..dfd1b145a 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -8,7 +8,6 @@ OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %44 "main" %41 OpExecutionMode %44 LocalSize 1 1 1 OpDecorate %41 BuiltIn GlobalInvocationId -OpDecorate %41 Flat %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 35f973442..7ad2b3560 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -95,9 +95,7 @@ OpDecorate %68 Binding 2 OpDecorate %70 DescriptorSet 1 OpDecorate %70 Binding 3 OpDecorate %73 BuiltIn LocalInvocationId -OpDecorate %73 Flat OpDecorate %119 BuiltIn LocalInvocationId -OpDecorate %119 Flat OpDecorate %140 BuiltIn Position OpDecorate %193 BuiltIn Position OpDecorate %222 Location 0 diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index 748b445b6..6c1dac372 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -16,15 +16,10 @@ OpDecorate %16 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 OpDecorate %23 BuiltIn GlobalInvocationId -OpDecorate %23 Flat OpDecorate %26 BuiltIn LocalInvocationId -OpDecorate %26 Flat OpDecorate %28 BuiltIn LocalInvocationIndex -OpDecorate %28 Flat OpDecorate %31 BuiltIn WorkgroupId -OpDecorate %31 Flat OpDecorate %33 BuiltIn NumWorkgroups -OpDecorate %33 Flat %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 503345825..424208def 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -28,7 +28,6 @@ OpDecorate %34 BuiltIn SampleMask OpDecorate %34 Flat OpDecorate %36 BuiltIn FragDepth OpDecorate %38 BuiltIn SampleMask -OpDecorate %38 Flat OpDecorate %40 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index 83a6aae82..62e4acb1b 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -15,9 +15,7 @@ OpDecorate %16 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 OpDecorate %21 BuiltIn VertexIndex -OpDecorate %21 Flat OpDecorate %24 BuiltIn InstanceIndex -OpDecorate %24 Flat OpDecorate %26 Location 10 OpDecorate %28 Invariant OpDecorate %28 BuiltIn Position diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index dc681b5b4..190f391c3 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -15,9 +15,7 @@ OpDecorate %16 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 OpDecorate %24 BuiltIn VertexIndex -OpDecorate %24 Flat OpDecorate %28 BuiltIn InstanceIndex -OpDecorate %28 Flat OpDecorate %30 Invariant OpDecorate %30 BuiltIn Position OpDecorate %32 BuiltIn PointSize diff --git a/tests/out/spv/multiview.spvasm b/tests/out/spv/multiview.spvasm index 343396ea0..bb67d7eba 100644 --- a/tests/out/spv/multiview.spvasm +++ b/tests/out/spv/multiview.spvasm @@ -9,7 +9,6 @@ OpExtension "SPV_KHR_multiview" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %8 "main" %5 OpDecorate %5 BuiltIn ViewIndex -OpDecorate %5 Flat %2 = OpTypeVoid %3 = OpTypeInt 32 1 %6 = OpTypePointer Input %3 diff --git a/tests/out/spv/skybox.spvasm b/tests/out/spv/skybox.spvasm index 227c7786e..ca51a06dd 100644 --- a/tests/out/spv/skybox.spvasm +++ b/tests/out/spv/skybox.spvasm @@ -25,7 +25,6 @@ OpDecorate %22 Binding 1 OpDecorate %24 DescriptorSet 0 OpDecorate %24 Binding 2 OpDecorate %32 BuiltIn VertexIndex -OpDecorate %32 Flat OpDecorate %35 BuiltIn Position OpDecorate %37 Location 0 OpDecorate %83 BuiltIn FragCoord From 66f5506e109f5cb8b41bcd40eea25b60bb06dcab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 6 Aug 2022 20:08:45 +0100 Subject: [PATCH 1819/2212] Add a frontend agnostic symbol table Adds a new type `SymbolTable` to allow sharing code between the frontends related to variable name lookup and lexical scope management, this way improvements in variable lookup can be shared among all frontends. --- src/front/mod.rs | 155 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) diff --git a/src/front/mod.rs b/src/front/mod.rs index bfc99f1f9..837916da0 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -14,6 +14,7 @@ pub mod wgsl; use crate::{ arena::{Arena, Handle, UniqueArena}, proc::{ResolveContext, ResolveError, TypeResolution}, + FastHashMap, }; use std::ops; @@ -133,3 +134,157 @@ impl ops::Index> for Typifier { &self.resolutions[handle.index()] } } + +/// Type representing a lexical scope, associating a name to a single variable +/// +/// The scope is generic over the variable representation and name representaion +/// in order to allow larger flexibility on the frontends on how they might +/// represent them. +type Scope = FastHashMap; + +/// Structure responsible for managing variable lookups and keeping track of +/// lexical scopes +/// +/// The symbol table is generic over the variable representation and it's name +/// to allow larger flexibility on the frontends on how they might represent them. +/// +/// ``` +/// use naga::front::SymbolTable; +/// +/// // Create a new symbol table with `u32`s representing the variable +/// let mut symbol_table: SymbolTable<&str, u32> = SymbolTable::default(); +/// +/// // Add two variables named `var1` and `var2` with 0 and 2 respectively +/// symbol_table.add("var1", 0); +/// symbol_table.add("var2", 2); +/// +/// // Check that `var1` exists and is `0` +/// assert_eq!(symbol_table.lookup("var1"), Some(&0)); +/// +/// // Push a new scope and add a variable to it with name `var1` shadowing the +/// // variable of our previous scope +/// symbol_table.push_scope(); +/// symbol_table.add("var1", 1); +/// +/// // Check that `var1` now points to the new value of `1` and `var2` still +/// // exists with it's value of `2` +/// assert_eq!(symbol_table.lookup("var1"), Some(&1)); +/// assert_eq!(symbol_table.lookup("var2"), Some(&2)); +/// +/// // Pop the scope +/// symbol_table.pop_scope(); +/// +/// // Check that `var1` now refers to our initial variable with value `0` +/// assert_eq!(symbol_table.lookup("var1"), Some(&0)); +/// ``` +/// +/// Scopes are ordered as LIFO stack so a variable defined in a later scope +/// with the same name as another variable defined in a earlier scope will take +/// precedence in the lookup. Scopes can be added with [`push_scope`] and +/// removed with [`pop_scope`]. +/// +/// A root scope is added when the symbol table is created and must always be +/// present, trying to pop it will result in a panic. +/// +/// Variables can be added with [`add`] and looked up with [`lookup`], adding a +/// variable will do so in the currently active scope and as mentioned +/// previously a lookup will search from the current scope to the root scope. +/// +/// [`push_scope`]: Self::push_scope +/// [`pop_scope`]: Self::push_scope +/// [`add`]: Self::add +/// [`lookup`]: Self::lookup +pub struct SymbolTable { + /// Stack of lexical scopes, not all scopes are active see [`cursor`] + /// + /// [`cursor`]: Self::cursor + scopes: Vec>, + /// Limit of the [`scopes`] stack (exclusive), by using a separate value for + /// the stack length instead of `Vec`'s own internal length the scopes can + /// be reused to cache memory allocations + /// + /// [`scopes`]: Self::scopes + cursor: usize, +} + +impl SymbolTable { + /// Adds a new lexical scope + /// + /// All variables declared after this points will be added to this scope + /// until another scope is pushed or [`pop_scope`] is called causing this + /// scope to be removed along with all variables added to it. + /// + /// [`pop_scope`]: Self::pop_scope + pub fn push_scope(&mut self) { + // If the cursor is equal to the scopes stack length then we need to + // push another empty scope, otherwise we can reuse the already existing + // scope. + if self.scopes.len() == self.cursor { + self.scopes.push(FastHashMap::default()) + } else { + self.scopes[self.cursor].clear(); + } + + self.cursor += 1; + } + + /// Removes the current lexical scope and all it's variables + /// + /// # PANICS + /// - If the current lexical scope is the root scope + pub fn pop_scope(&mut self) { + // Despite the method title, the variables are only deleted when the + // scope is reused, this is because while a clear is inevitable if the + // scope needs to be reused, there are cases where the scope might be + // popped and not reused, i.e. if another scope with the same nesting + // level is never pushed again. + assert!(self.cursor != 1, "Tried to pop the root scope"); + + self.cursor -= 1; + } +} + +impl SymbolTable +where + Name: std::hash::Hash + Eq, +{ + /// Perform a lookup for a variable named `name` + /// + /// As stated in the struct level documentation the lookup will proceed from + /// the current scope to the root scope, returning `Some` when a variable is + /// found or `None` if there doesn't exist a variable with `name` in any + /// scope. + pub fn lookup(&mut self, name: &Q) -> Option<&Var> + where + Name: std::borrow::Borrow, + Q: std::hash::Hash + Eq, + { + // Iterate backwards trough the scopes and try to find the variable + for scope in self.scopes[..self.cursor].iter().rev() { + if let Some(var) = scope.get(name) { + return Some(var); + } + } + + None + } + + /// Adds a new variable to the current scope + /// + /// Returns the previous variable with the same name in this scope if it + /// exists so that the frontend might handle it in case variable shadowing + /// is disallowed + pub fn add(&mut self, name: Name, var: Var) -> Option { + self.scopes[self.cursor - 1].insert(name, var) + } +} + +impl Default for SymbolTable { + /// Constructs a new symbol table with a root scope + fn default() -> Self { + Self { + scopes: vec![FastHashMap::default()], + cursor: 1, + } + } +} From d64d78ff0b7b76aea8594c9c16d06cb0184df327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 6 Aug 2022 20:53:04 +0100 Subject: [PATCH 1820/2212] wgsl-in: Implement lexical scopes Previously the wgsl frontend wasn't aware of lexical scopes causing all variables and named expressions to share a single function scope, this meant that if a variable was defined in a block with the same name as a variable in the function body, the variable in the function body would be lost and exiting the block all references to the variable in the function body would be replaced with the variable of the block. This commit fixes that by using the previously introduced `SymbolTable` to track the lexical and perform the variable lookups, scopes are pushed and popped as defined in the wgsl specification. --- src/front/mod.rs | 42 ++++++++++---------- src/front/wgsl/mod.rs | 63 +++++++++++++++++++++++------- tests/in/lexical-scopes.wgsl | 58 +++++++++++++++++++++++++++ tests/out/wgsl/lexical-scopes.wgsl | 60 ++++++++++++++++++++++++++++ tests/snapshots.rs | 1 + 5 files changed, 189 insertions(+), 35 deletions(-) create mode 100644 tests/in/lexical-scopes.wgsl create mode 100644 tests/out/wgsl/lexical-scopes.wgsl diff --git a/src/front/mod.rs b/src/front/mod.rs index 837916da0..245839d3e 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -145,7 +145,7 @@ type Scope = FastHashMap; /// Structure responsible for managing variable lookups and keeping track of /// lexical scopes /// -/// The symbol table is generic over the variable representation and it's name +/// The symbol table is generic over the variable representation and its name /// to allow larger flexibility on the frontends on how they might represent them. /// /// ``` @@ -161,13 +161,13 @@ type Scope = FastHashMap; /// // Check that `var1` exists and is `0` /// assert_eq!(symbol_table.lookup("var1"), Some(&0)); /// -/// // Push a new scope and add a variable to it with name `var1` shadowing the +/// // Push a new scope and add a variable to it named `var1` shadowing the /// // variable of our previous scope /// symbol_table.push_scope(); /// symbol_table.add("var1", 1); /// /// // Check that `var1` now points to the new value of `1` and `var2` still -/// // exists with it's value of `2` +/// // exists with its value of `2` /// assert_eq!(symbol_table.lookup("var1"), Some(&1)); /// assert_eq!(symbol_table.lookup("var2"), Some(&2)); /// @@ -178,15 +178,15 @@ type Scope = FastHashMap; /// assert_eq!(symbol_table.lookup("var1"), Some(&0)); /// ``` /// -/// Scopes are ordered as LIFO stack so a variable defined in a later scope +/// Scopes are ordered as a LIFO stack so a variable defined in a later scope /// with the same name as another variable defined in a earlier scope will take /// precedence in the lookup. Scopes can be added with [`push_scope`] and /// removed with [`pop_scope`]. /// /// A root scope is added when the symbol table is created and must always be -/// present, trying to pop it will result in a panic. +/// present. Trying to pop it will result in a panic. /// -/// Variables can be added with [`add`] and looked up with [`lookup`], adding a +/// Variables can be added with [`add`] and looked up with [`lookup`]. Adding a /// variable will do so in the currently active scope and as mentioned /// previously a lookup will search from the current scope to the root scope. /// @@ -195,29 +195,29 @@ type Scope = FastHashMap; /// [`add`]: Self::add /// [`lookup`]: Self::lookup pub struct SymbolTable { - /// Stack of lexical scopes, not all scopes are active see [`cursor`] + /// Stack of lexical scopes. Not all scopes are active; see [`cursor`]. /// /// [`cursor`]: Self::cursor scopes: Vec>, - /// Limit of the [`scopes`] stack (exclusive), by using a separate value for - /// the stack length instead of `Vec`'s own internal length the scopes can - /// be reused to cache memory allocations + /// Limit of the [`scopes`] stack (exclusive). By using a separate value for + /// the stack length instead of `Vec`'s own internal length, the scopes can + /// be reused to cache memory allocations. /// /// [`scopes`]: Self::scopes cursor: usize, } impl SymbolTable { - /// Adds a new lexical scope + /// Adds a new lexical scope. /// - /// All variables declared after this points will be added to this scope - /// until another scope is pushed or [`pop_scope`] is called causing this + /// All variables declared after this point will be added to this scope + /// until another scope is pushed or [`pop_scope`] is called, causing this /// scope to be removed along with all variables added to it. /// /// [`pop_scope`]: Self::pop_scope pub fn push_scope(&mut self) { - // If the cursor is equal to the scopes stack length then we need to - // push another empty scope, otherwise we can reuse the already existing + // If the cursor is equal to the scope's stack length then we need to + // push another empty scope. Otherwise we can reuse the already existing // scope. if self.scopes.len() == self.cursor { self.scopes.push(FastHashMap::default()) @@ -228,13 +228,13 @@ impl SymbolTable { self.cursor += 1; } - /// Removes the current lexical scope and all it's variables + /// Removes the current lexical scope and all its variables /// /// # PANICS /// - If the current lexical scope is the root scope pub fn pop_scope(&mut self) { // Despite the method title, the variables are only deleted when the - // scope is reused, this is because while a clear is inevitable if the + // scope is reused. This is because while a clear is inevitable if the // scope needs to be reused, there are cases where the scope might be // popped and not reused, i.e. if another scope with the same nesting // level is never pushed again. @@ -248,7 +248,7 @@ impl SymbolTable where Name: std::hash::Hash + Eq, { - /// Perform a lookup for a variable named `name` + /// Perform a lookup for a variable named `name`. /// /// As stated in the struct level documentation the lookup will proceed from /// the current scope to the root scope, returning `Some` when a variable is @@ -269,11 +269,11 @@ where None } - /// Adds a new variable to the current scope + /// Adds a new variable to the current scope. /// /// Returns the previous variable with the same name in this scope if it - /// exists so that the frontend might handle it in case variable shadowing - /// is disallowed + /// exists, so that the frontend might handle it in case variable shadowing + /// is disallowed. pub fn add(&mut self, name: Name, var: Var) -> Option { self.scopes[self.cursor - 1].insert(name, var) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2732c5b57..489c16f33 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -749,7 +749,7 @@ impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, TypedExpression> { } struct StatementContext<'input, 'temp, 'out> { - lookup_ident: &'temp mut FastHashMap<&'input str, TypedExpression>, + symbol_table: &'temp mut super::SymbolTable<&'input str, TypedExpression>, typifier: &'temp mut super::Typifier, variables: &'out mut Arena, expressions: &'out mut Arena, @@ -764,7 +764,7 @@ struct StatementContext<'input, 'temp, 'out> { impl<'a, 'temp> StatementContext<'a, 'temp, '_> { fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { StatementContext { - lookup_ident: self.lookup_ident, + symbol_table: self.symbol_table, typifier: self.typifier, variables: self.variables, expressions: self.expressions, @@ -786,7 +786,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { 'temp: 't, { ExpressionContext { - lookup_ident: self.lookup_ident, + symbol_table: self.symbol_table, typifier: self.typifier, expressions: self.expressions, types: self.types, @@ -807,7 +807,7 @@ struct SamplingContext { } struct ExpressionContext<'input, 'temp, 'out> { - lookup_ident: &'temp FastHashMap<&'input str, TypedExpression>, + symbol_table: &'temp mut super::SymbolTable<&'input str, TypedExpression>, typifier: &'temp mut super::Typifier, expressions: &'out mut Arena, types: &'out mut UniqueArena, @@ -823,7 +823,7 @@ struct ExpressionContext<'input, 'temp, 'out> { impl<'a> ExpressionContext<'a, '_, '_> { fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { ExpressionContext { - lookup_ident: self.lookup_ident, + symbol_table: self.symbol_table, typifier: self.typifier, expressions: self.expressions, types: self.types, @@ -2286,7 +2286,7 @@ impl Parser { ) } (Token::Word(word), span) => { - if let Some(definition) = ctx.lookup_ident.get(word) { + if let Some(definition) = ctx.symbol_table.lookup(word) { let _ = lexer.next(); self.pop_scope(lexer); @@ -3432,6 +3432,9 @@ impl Parser { mut context: StatementContext<'a, '_, 'out>, ) -> Result<(bool, crate::Block), Error<'a>> { let mut body = crate::Block::new(); + // Push a new lexical scope for the switch case body + context.symbol_table.push_scope(); + lexer.expect(Token::Paren('{'))?; let fall_through = loop { // default statements @@ -3445,6 +3448,8 @@ impl Parser { } self.parse_statement(lexer, context.reborrow(), &mut body, false)?; }; + // Pop the switch case body lexical scope + context.symbol_table.pop_scope(); Ok((fall_through, body)) } @@ -3465,6 +3470,9 @@ impl Parser { } (Token::Paren('{'), _) => { self.push_scope(Scope::Block, lexer); + // Push a new lexical scope for the block statement + context.symbol_table.push_scope(); + let _ = lexer.next(); let mut statements = crate::Block::new(); while !lexer.skip(Token::Paren('}')) { @@ -3475,6 +3483,9 @@ impl Parser { is_uniform_control_flow, )?; } + // Pop the block statement lexical scope + context.symbol_table.pop_scope(); + self.pop_scope(lexer); let span = NagaSpan::from(self.pop_scope(lexer)); block.push(crate::Statement::Block(statements), span); @@ -3539,7 +3550,7 @@ impl Parser { } } block.extend(emitter.finish(context.expressions)); - context.lookup_ident.insert( + context.symbol_table.add( name, TypedExpression { handle: expr_id, @@ -3655,7 +3666,7 @@ impl Parser { let expr_id = context .expressions .append(crate::Expression::LocalVariable(var_id), Default::default()); - context.lookup_ident.insert( + context.symbol_table.add( name, TypedExpression { handle: expr_id, @@ -3843,10 +3854,14 @@ impl Parser { }, NagaSpan::from(span), ); + // Push a lexical scope for the while loop body + context.symbol_table.push_scope(); while !lexer.skip(Token::Paren('}')) { self.parse_statement(lexer, context.reborrow(), &mut body, false)?; } + // Pop the while loop body lexical scope + context.symbol_table.pop_scope(); Some(crate::Statement::Loop { body, @@ -3857,6 +3872,9 @@ impl Parser { "for" => { let _ = lexer.next(); lexer.expect(Token::Paren('('))?; + // Push a lexical scope for the for loop + context.symbol_table.push_scope(); + if !lexer.skip(Token::Separator(';')) { let num_statements = block.len(); let (_, span) = lexer.capture_span(|lexer| { @@ -3904,7 +3922,9 @@ impl Parser { let mut continuing = crate::Block::new(); if !lexer.skip(Token::Paren(')')) { match lexer.peek().0 { - Token::Word(ident) if context.lookup_ident.get(ident).is_none() => { + Token::Word(ident) + if context.symbol_table.lookup(ident).is_none() => + { self.parse_function_statement( lexer, ident, @@ -3923,6 +3943,8 @@ impl Parser { while !lexer.skip(Token::Paren('}')) { self.parse_statement(lexer, context.reborrow(), &mut body, false)?; } + // Pop the for loop lexical scope + context.symbol_table.pop_scope(); Some(crate::Statement::Loop { body, @@ -4013,7 +4035,7 @@ impl Parser { } // assignment or a function call ident => { - match context.lookup_ident.get(ident) { + match context.symbol_table.lookup(ident) { Some(_) => self.parse_assignment_statement( lexer, context.as_expression(block, &mut emitter), @@ -4052,6 +4074,10 @@ impl Parser { let mut body = crate::Block::new(); let mut continuing = crate::Block::new(); let mut break_if = None; + + // Push a lexical scope for the loop body + context.symbol_table.push_scope(); + lexer.expect(Token::Paren('{'))?; loop { @@ -4113,6 +4139,9 @@ impl Parser { self.parse_statement(lexer, context.reborrow(), &mut body, false)?; } + // Pop the loop body lexical scope + context.symbol_table.pop_scope(); + Ok(crate::Statement::Loop { body, continuing, @@ -4127,6 +4156,9 @@ impl Parser { is_uniform_control_flow: bool, ) -> Result> { self.push_scope(Scope::Block, lexer); + // Push a lexical scope for the block + context.symbol_table.push_scope(); + lexer.expect(Token::Paren('{'))?; let mut block = crate::Block::new(); while !lexer.skip(Token::Paren('}')) { @@ -4137,6 +4169,9 @@ impl Parser { is_uniform_control_flow, )?; } + //Pop the block lexical scope + context.symbol_table.pop_scope(); + self.pop_scope(lexer); Ok(block) } @@ -4165,7 +4200,7 @@ impl Parser { ) -> Result<(crate::Function, &'a str), Error<'a>> { self.push_scope(Scope::FunctionDecl, lexer); // read function name - let mut lookup_ident = FastHashMap::default(); + let mut symbol_table = super::SymbolTable::default(); let (fun_name, span) = lexer.next_ident_with_span()?; if crate::keywords::wgsl::RESERVED.contains(&fun_name) { return Err(Error::ReservedKeyword(span)); @@ -4191,7 +4226,7 @@ impl Parser { _ => unreachable!(), }; let expression = expressions.append(expression.clone(), span); - lookup_ident.insert( + symbol_table.add( name, TypedExpression { handle: expression, @@ -4221,7 +4256,7 @@ impl Parser { crate::Expression::FunctionArgument(param_index), NagaSpan::from(param_name_span), ); - lookup_ident.insert( + symbol_table.add( param_name, TypedExpression { handle: expression, @@ -4266,7 +4301,7 @@ impl Parser { fun.body = self.parse_block( lexer, StatementContext { - lookup_ident: &mut lookup_ident, + symbol_table: &mut symbol_table, typifier: &mut typifier, variables: &mut fun.local_variables, expressions: &mut fun.expressions, diff --git a/tests/in/lexical-scopes.wgsl b/tests/in/lexical-scopes.wgsl new file mode 100644 index 000000000..70a18a488 --- /dev/null +++ b/tests/in/lexical-scopes.wgsl @@ -0,0 +1,58 @@ +fn blockLexicalScope(a: bool) { + let a = 1.0; + { + let a = 2; + { + let a = true; + } + let test = a == 3; + } + let test = a == 2.0; +} + +fn ifLexicalScope(a: bool) { + let a = 1.0; + if (a == 1.0) { + let a = true; + } + let test = a == 2.0; +} + + +fn loopLexicalScope(a: bool) { + let a = 1.0; + loop { + let a = true; + } + let test = a == 2.0; +} + +fn forLexicalScope(a: f32) { + let a = false; + for (var a = 0; a < 1; a++) { + let a = 3.0; + } + let test = a == true; +} + +fn whileLexicalScope(a: i32) { + while (a > 2) { + let a = false; + } + let test = a == 1; +} + +fn switchLexicalScope(a: i32) { + switch (a) { + case 0 { + let a = false; + } + case 1 { + let a = 2.0; + } + default { + let a = true; + } + } + let test = a == 2; +} diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/tests/out/wgsl/lexical-scopes.wgsl new file mode 100644 index 000000000..39f033cb1 --- /dev/null +++ b/tests/out/wgsl/lexical-scopes.wgsl @@ -0,0 +1,60 @@ +fn blockLexicalScope(a: bool) { + { + { + } + let test = (2 == 3); + } + let test_1 = (1.0 == 2.0); +} + +fn ifLexicalScope(a_1: bool) { + if (1.0 == 1.0) { + } + let test_2 = (1.0 == 2.0); +} + +fn loopLexicalScope(a_2: bool) { + loop { + } + let test_3 = (1.0 == 2.0); +} + +fn forLexicalScope(a_3: f32) { + var a_4: i32 = 0; + + loop { + let _e4 = a_4; + if (_e4 < 1) { + } else { + break; + } + continuing { + let _e7 = a_4; + a_4 = (_e7 + 1); + } + } + let test_4 = (false == true); +} + +fn whileLexicalScope(a_5: i32) { + loop { + if (a_5 > 2) { + } else { + break; + } + } + let test_5 = (a_5 == 1); +} + +fn switchLexicalScope(a_6: i32) { + switch a_6 { + case 0: { + } + case 1: { + } + default: { + } + } + let test_6 = (a_6 == 2); +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index fa32580e3..59a3e314b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -543,6 +543,7 @@ fn convert_wgsl() { "break-if", Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, ), + ("lexical-scopes", Targets::WGSL), ]; for &(name, targets) in inputs.iter() { From 7505187476cc1c01dd8e6b2ad2f45cec1dff5382 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 2 Sep 2022 11:29:25 -0700 Subject: [PATCH 1821/2212] [spv-out] Don't emit no-op `OpBitCast` instructions. As reported in #2015, some drivers trip over these. --- src/back/spv/block.rs | 40 ++++++++++++++++++++++++++-------- tests/out/spv/image.spvasm | 3 +-- tests/out/spv/operators.spvasm | 6 ----- 3 files changed, 32 insertions(+), 17 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 8a388be22..10fd5d72a 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1029,6 +1029,7 @@ impl<'w> BlockContext<'w> { }; enum Cast { + Identity, Unary(spirv::Op), Binary(spirv::Op, Word), Ternary(spirv::Op, Word, Word), @@ -1039,6 +1040,13 @@ impl<'w> BlockContext<'w> { Cast::Unary(spirv::Op::CopyObject) } else { match (src_kind, kind, convert) { + // Filter out identity casts. Some Adreno drivers are + // confused by no-op OpBitCast instructions. + (src_kind, kind, convert) + if src_kind == kind && convert.unwrap_or(src_width) == src_width => + { + Cast::Identity + } (Sk::Bool, Sk::Bool, _) => Cast::Unary(spirv::Op::CopyObject), (_, _, None) => Cast::Unary(spirv::Op::Bitcast), // casting to a bool - generate `OpXxxNotEqual` @@ -1144,16 +1152,30 @@ impl<'w> BlockContext<'w> { let id = self.gen_id(); let instruction = match cast { - Cast::Unary(op) => Instruction::unary(op, result_type_id, id, expr_id), - Cast::Binary(op, operand) => { - Instruction::binary(op, result_type_id, id, expr_id, operand) - } - Cast::Ternary(op, op1, op2) => { - Instruction::ternary(op, result_type_id, id, expr_id, op1, op2) - } + Cast::Identity => None, + Cast::Unary(op) => Some(Instruction::unary(op, result_type_id, id, expr_id)), + Cast::Binary(op, operand) => Some(Instruction::binary( + op, + result_type_id, + id, + expr_id, + operand, + )), + Cast::Ternary(op, op1, op2) => Some(Instruction::ternary( + op, + result_type_id, + id, + expr_id, + op1, + op2, + )), }; - block.body.push(instruction); - id + if let Some(instruction) = instruction { + block.body.push(instruction); + id + } else { + expr_id + } } crate::Expression::ImageLoad { image, diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 7ad2b3560..f0556d35d 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -277,8 +277,7 @@ OpFunctionEnd OpBranch %150 %150 = OpLabel %152 = OpImageQuerySizeLod %4 %143 %151 -%153 = OpBitcast %4 %152 -%154 = OpImageQuerySizeLod %4 %143 %153 +%154 = OpImageQuerySizeLod %4 %143 %152 %155 = OpImageQuerySizeLod %21 %144 %151 %156 = OpImageQuerySizeLod %21 %144 %6 %157 = OpImageQuerySizeLod %105 %145 %151 diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 2e7cc3139..bdd355110 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -161,13 +161,7 @@ OpStore %110 %118 %129 = OpCompositeConstruct %31 %5 %5 %130 = OpCompositeConstruct %32 %128 %129 %131 = OpCompositeConstruct %36 %11 %7 %18 %21 -%132 = OpCopyObject %10 %12 -%133 = OpBitcast %8 %11 -%134 = OpBitcast %20 %19 -%135 = OpBitcast %4 %5 -%136 = OpBitcast %34 %46 %137 = OpCopyObject %37 %53 -%138 = OpBitcast %34 %46 %139 = OpCopyObject %37 %53 %142 = OpAccessChain %141 %110 %19 %19 %143 = OpLoad %4 %142 From 13a0d28ddc138609b1ed686aaa69d922f87adfed Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 1 Sep 2022 17:37:44 -0700 Subject: [PATCH 1822/2212] wgsl-in: Rename `Scope` to `Rule`, since we now have lexical scope. Rename related functions and variables appropriately. Also, make `Rule` private to the WGSL front end, and remove the unused `ImportDecl` variant. --- src/front/wgsl/construction.rs | 12 ++-- src/front/wgsl/mod.rs | 126 +++++++++++++++++---------------- 2 files changed, 71 insertions(+), 67 deletions(-) diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/construction.rs index 7039bb5dd..43e719d0f 100644 --- a/src/front/wgsl/construction.rs +++ b/src/front/wgsl/construction.rs @@ -3,7 +3,7 @@ use crate::{ ScalarKind, ScalarValue, Span as NagaSpan, Type, TypeInner, UniqueArena, VectorSize, }; -use super::{Error, ExpressionContext, Lexer, Parser, Scope, Span, Token}; +use super::{Error, ExpressionContext, Lexer, Parser, Rule, Span, Token}; /// Represents the type of the constructor /// @@ -216,7 +216,7 @@ fn parse_constructor_type<'a>( } } -/// Expects [`Scope::PrimaryExpr`] scope on top; if returning Some(_), pops it. +/// Expects [`Rule::PrimaryExpr`] on top of rule stack; if returning Some(_), pops it. pub(super) fn parse_construction<'a>( parser: &mut Parser, lexer: &mut Lexer<'a>, @@ -225,8 +225,8 @@ pub(super) fn parse_construction<'a>( mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { assert_eq!( - parser.scopes.last().map(|&(ref scope, _)| scope.clone()), - Some(Scope::PrimaryExpr) + parser.rules.last().map(|&(ref rule, _)| rule.clone()), + Some(Rule::PrimaryExpr) ); let dst_ty = match parser.lookup_type.get(type_name) { Some(&handle) => ConstructorType::Struct(handle), @@ -322,7 +322,7 @@ pub(super) fn parse_construction<'a>( return match ctx.create_zero_value_constant(ty) { Some(constant) => { - let span = parser.pop_scope(lexer); + let span = parser.pop_rule_span(lexer); Ok(Some(ctx.interrupt_emitter( Expression::Constant(constant), span.into(), @@ -674,6 +674,6 @@ pub(super) fn parse_construction<'a>( } }; - let span = NagaSpan::from(parser.pop_scope(lexer)); + let span = NagaSpan::from(parser.pop_rule_span(lexer)); Ok(Some(ctx.expressions.append(expr, span))) } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 489c16f33..657de486f 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1154,10 +1154,14 @@ struct TypeAttributes { // Therefore, we are leaving the plumbing in for now. } +/// Which grammar rule we are in the midst of parsing. +/// +/// This is used for error checking. `Parser` maintains a stack of +/// these and (occasionally) checks that it is being pushed and popped +/// as expected. #[derive(Clone, Debug, PartialEq)] -pub enum Scope { +enum Rule { Attribute, - ImportDecl, VariableDecl, TypeDecl, FunctionDecl, @@ -1348,7 +1352,7 @@ impl std::error::Error for ParseError { } pub struct Parser { - scopes: Vec<(Scope, usize)>, + rules: Vec<(Rule, usize)>, module_scope_identifiers: FastHashMap, lookup_type: FastHashMap>, layouter: Layouter, @@ -1357,7 +1361,7 @@ pub struct Parser { impl Parser { pub fn new() -> Self { Parser { - scopes: Vec::new(), + rules: Vec::new(), module_scope_identifiers: FastHashMap::default(), lookup_type: FastHashMap::default(), layouter: Default::default(), @@ -1365,23 +1369,23 @@ impl Parser { } fn reset(&mut self) { - self.scopes.clear(); + self.rules.clear(); self.module_scope_identifiers.clear(); self.lookup_type.clear(); self.layouter.clear(); } - fn push_scope(&mut self, scope: Scope, lexer: &Lexer<'_>) { - self.scopes.push((scope, lexer.current_byte_offset())); + fn push_rule_span(&mut self, rule: Rule, lexer: &Lexer<'_>) { + self.rules.push((rule, lexer.current_byte_offset())); } - fn pop_scope(&mut self, lexer: &Lexer<'_>) -> Span { - let (_, initial) = self.scopes.pop().unwrap(); + fn pop_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { + let (_, initial) = self.rules.pop().unwrap(); lexer.span_from(initial) } - fn peek_scope(&mut self, lexer: &Lexer<'_>) -> Span { - let &(_, initial) = self.scopes.last().unwrap(); + fn peek_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { + let &(_, initial) = self.rules.last().unwrap(); lexer.span_from(initial) } @@ -1519,7 +1523,7 @@ impl Parser { Ok(result) } - /// Expects [`Scope::PrimaryExpr`] or [`Scope::SingularExpr`] on top; does not pop it. + /// Expects [`Rule::PrimaryExpr`] or [`Rule::SingularExpr`] on top; does not pop it. /// Expects `word` to be peeked (still in lexer), doesn't consume if returning None. fn parse_function_call_inner<'a>( &mut self, @@ -1527,7 +1531,7 @@ impl Parser { name: &'a str, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { - assert!(self.scopes.last().is_some()); + assert!(self.rules.last().is_some()); let expr = if let Some(fun) = conv::map_relational_fun(name) { let _ = lexer.next(); lexer.open_arguments()?; @@ -1738,7 +1742,7 @@ impl Parser { _ => return Err(Error::InvalidAtomicOperandType(value_span)), }; - let span = NagaSpan::from(self.peek_scope(lexer)); + let span = NagaSpan::from(self.peek_rule_span(lexer)); let result = ctx.interrupt_emitter(expression, span); ctx.block.push( crate::Statement::Atomic { @@ -2130,7 +2134,7 @@ impl Parser { let result = match self.parse_local_function_call(lexer, name, ctx.reborrow())? { Some((function, arguments)) => { - let span = NagaSpan::from(self.peek_scope(lexer)); + let span = NagaSpan::from(self.peek_rule_span(lexer)); ctx.block.extend(ctx.emitter.finish(ctx.expressions)); let result = ctx.functions[function].result.as_ref().map(|_| { ctx.expressions @@ -2153,7 +2157,7 @@ impl Parser { } } }; - let span = NagaSpan::from(self.peek_scope(lexer)); + let span = NagaSpan::from(self.peek_rule_span(lexer)); let handle = ctx.expressions.append(expr, span); Ok(Some(CalledFunction { result: Some(handle), @@ -2168,7 +2172,7 @@ impl Parser { type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result, Error<'a>> { - self.push_scope(Scope::ConstantExpr, lexer); + self.push_rule_span(Rule::ConstantExpr, lexer); let inner = match first_token_span { (Token::Word("true"), _) => crate::ConstantInner::boolean(true), (Token::Word("false"), _) => crate::ConstantInner::boolean(false), @@ -2193,7 +2197,7 @@ impl Parser { for (handle, var) in const_arena.iter() { match var.name { Some(ref string) if string == name => { - self.pop_scope(lexer); + self.pop_rule_span(lexer); return Ok(handle); } _ => {} @@ -2226,7 +2230,7 @@ impl Parser { // Only set span if it's a named constant. Otherwise, the enclosing Expression should have // the span. - let span = self.pop_scope(lexer); + let span = self.pop_rule_span(lexer); let handle = if let Some(name) = register_name { if crate::keywords::wgsl::RESERVED.contains(&name) { return Err(Error::ReservedKeyword(span)); @@ -2268,19 +2272,19 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result> { // Will be popped inside match, possibly inside parse_function_call_inner or parse_construction - self.push_scope(Scope::PrimaryExpr, lexer); + self.push_rule_span(Rule::PrimaryExpr, lexer); let expr = match lexer.peek() { (Token::Paren('('), _) => { let _ = lexer.next(); let (expr, _span) = self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; - self.pop_scope(lexer); + self.pop_rule_span(lexer); expr } (Token::Word("true" | "false") | Token::Number(..), _) => { let const_handle = self.parse_const_expression(lexer, ctx.types, ctx.constants)?; - let span = NagaSpan::from(self.pop_scope(lexer)); + let span = NagaSpan::from(self.pop_rule_span(lexer)); TypedExpression::non_reference( ctx.interrupt_emitter(crate::Expression::Constant(const_handle), span), ) @@ -2288,14 +2292,14 @@ impl Parser { (Token::Word(word), span) => { if let Some(definition) = ctx.symbol_table.lookup(word) { let _ = lexer.next(); - self.pop_scope(lexer); + self.pop_rule_span(lexer); *definition } else if let Some(CalledFunction { result: Some(expr) }) = self.parse_function_call_inner(lexer, word, ctx.reborrow())? { //TODO: resolve the duplicate call in `parse_singular_expression` - self.pop_scope(lexer); + self.pop_rule_span(lexer); TypedExpression::non_reference(expr) } else { let _ = lexer.next(); @@ -2487,7 +2491,7 @@ impl Parser { lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result> { - self.push_scope(Scope::UnaryExpr, lexer); + self.push_rule_span(Rule::UnaryExpr, lexer); //TODO: refactor this to avoid backing up let expr = match lexer.peek().0 { Token::Operation('-') => { @@ -2498,7 +2502,7 @@ impl Parser { op: crate::UnaryOperator::Negate, expr, }; - let span = NagaSpan::from(self.peek_scope(lexer)); + let span = NagaSpan::from(self.peek_rule_span(lexer)); TypedExpression::non_reference(ctx.expressions.append(expr, span)) } Token::Operation('!' | '~') => { @@ -2509,7 +2513,7 @@ impl Parser { op: crate::UnaryOperator::Not, expr, }; - let span = NagaSpan::from(self.peek_scope(lexer)); + let span = NagaSpan::from(self.peek_rule_span(lexer)); TypedExpression::non_reference(ctx.expressions.append(expr, span)) } Token::Operation('*') => { @@ -2529,7 +2533,7 @@ impl Parser { .expressions .get_span(pointer) .to_range() - .unwrap_or_else(|| self.peek_scope(lexer)); + .unwrap_or_else(|| self.peek_rule_span(lexer)); return Err(Error::NotPointer(span)); } @@ -2548,7 +2552,7 @@ impl Parser { .expressions .get_span(operand.handle) .to_range() - .unwrap_or_else(|| self.peek_scope(lexer)); + .unwrap_or_else(|| self.peek_rule_span(lexer)); return Err(Error::NotReference("the operand of the `&` operator", span)); } @@ -2561,7 +2565,7 @@ impl Parser { _ => self.parse_singular_expression(lexer, ctx.reborrow())?, }; - self.pop_scope(lexer); + self.pop_rule_span(lexer); Ok(expr) } @@ -2572,10 +2576,10 @@ impl Parser { mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result> { let start = lexer.current_byte_offset(); - self.push_scope(Scope::SingularExpr, lexer); + self.push_rule_span(Rule::SingularExpr, lexer); let primary_expr = self.parse_primary_expression(lexer, ctx.reborrow())?; let singular_expr = self.parse_postfix(start, lexer, ctx.reborrow(), primary_expr)?; - self.pop_scope(lexer); + self.pop_rule_span(lexer); Ok(singular_expr) } @@ -2681,7 +2685,7 @@ impl Parser { lexer: &mut Lexer<'a>, mut context: ExpressionContext<'a, '_, '_>, ) -> Result<(TypedExpression, Span), Error<'a>> { - self.push_scope(Scope::GeneralExpr, lexer); + self.push_rule_span(Rule::GeneralExpr, lexer); // logical_or_expression let handle = context.parse_binary_op( lexer, @@ -2737,7 +2741,7 @@ impl Parser { ) }, )?; - Ok((handle, self.pop_scope(lexer))) + Ok((handle, self.pop_rule_span(lexer))) } fn parse_variable_ident_decl<'a>( @@ -2758,7 +2762,7 @@ impl Parser { type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result, Error<'a>> { - self.push_scope(Scope::VariableDecl, lexer); + self.push_rule_span(Rule::VariableDecl, lexer); let mut space = None; if lexer.skip(Token::Paren('<')) { @@ -2788,7 +2792,7 @@ impl Parser { None }; lexer.expect(Token::Separator(';'))?; - let name_span = self.pop_scope(lexer); + let name_span = self.pop_rule_span(lexer); Ok(ParsedVariable { name, name_span, @@ -2818,7 +2822,7 @@ impl Parser { )); } let (mut size_attr, mut align_attr) = (None, None); - self.push_scope(Scope::Attribute, lexer); + self.push_rule_span(Rule::Attribute, lexer); let mut bind_parser = BindingParser::default(); while lexer.skip(Token::Attribute) { match lexer.next_ident_with_span()? { @@ -2840,7 +2844,7 @@ impl Parser { } } - let bind_span = self.pop_scope(lexer); + let bind_span = self.pop_rule_span(lexer); let mut binding = bind_parser.finish(bind_span)?; let (name, span) = match lexer.next() { @@ -3253,7 +3257,7 @@ impl Parser { type_arena: &mut UniqueArena, const_arena: &mut Arena, ) -> Result, Error<'a>> { - self.push_scope(Scope::TypeDecl, lexer); + self.push_rule_span(Rule::TypeDecl, lexer); let attribute = TypeAttributes::default(); if lexer.skip(Token::Attribute) { @@ -3271,7 +3275,7 @@ impl Parser { type_arena, const_arena, )?; - self.pop_scope(lexer); + self.pop_rule_span(lexer); // Only set span if it's the first occurrence of the type. // Type spans therefore should only be used for errors in type declarations; // use variable spans/expression spans/etc. otherwise @@ -3409,7 +3413,7 @@ impl Parser { ident: &'a str, mut context: ExpressionContext<'a, '_, 'out>, ) -> Result<(), Error<'a>> { - self.push_scope(Scope::SingularExpr, lexer); + self.push_rule_span(Rule::SingularExpr, lexer); context.emitter.start(context.expressions); if self .parse_function_call_inner(lexer, ident, context.reborrow())? @@ -3421,7 +3425,7 @@ impl Parser { context .block .extend(context.emitter.finish(context.expressions)); - self.pop_scope(lexer); + self.pop_rule_span(lexer); Ok(()) } @@ -3461,15 +3465,15 @@ impl Parser { block: &'out mut crate::Block, is_uniform_control_flow: bool, ) -> Result<(), Error<'a>> { - self.push_scope(Scope::Statement, lexer); + self.push_rule_span(Rule::Statement, lexer); match lexer.peek() { (Token::Separator(';'), _) => { let _ = lexer.next(); - self.pop_scope(lexer); + self.pop_rule_span(lexer); return Ok(()); } (Token::Paren('{'), _) => { - self.push_scope(Scope::Block, lexer); + self.push_rule_span(Rule::Block, lexer); // Push a new lexical scope for the block statement context.symbol_table.push_scope(); @@ -3486,8 +3490,8 @@ impl Parser { // Pop the block statement lexical scope context.symbol_table.pop_scope(); - self.pop_scope(lexer); - let span = NagaSpan::from(self.pop_scope(lexer)); + self.pop_rule_span(lexer); + let span = NagaSpan::from(self.pop_rule_span(lexer)); block.push(crate::Statement::Block(statements), span); return Ok(()); } @@ -4050,7 +4054,7 @@ impl Parser { None } }; - let span = NagaSpan::from(self.pop_scope(lexer)); + let span = NagaSpan::from(self.pop_rule_span(lexer)); if let Some(statement) = statement { block.push(statement, span); } @@ -4058,7 +4062,7 @@ impl Parser { _ => { let mut emitter = super::Emitter::default(); self.parse_assignment_statement(lexer, context.as_expression(block, &mut emitter))?; - self.pop_scope(lexer); + self.pop_rule_span(lexer); } } Ok(()) @@ -4155,7 +4159,7 @@ impl Parser { mut context: StatementContext<'a, '_, '_>, is_uniform_control_flow: bool, ) -> Result> { - self.push_scope(Scope::Block, lexer); + self.push_rule_span(Rule::Block, lexer); // Push a lexical scope for the block context.symbol_table.push_scope(); @@ -4172,7 +4176,7 @@ impl Parser { //Pop the block lexical scope context.symbol_table.pop_scope(); - self.pop_scope(lexer); + self.pop_rule_span(lexer); Ok(block) } @@ -4181,14 +4185,14 @@ impl Parser { lexer: &mut Lexer<'a>, ) -> Result, Error<'a>> { let mut bind_parser = BindingParser::default(); - self.push_scope(Scope::Attribute, lexer); + self.push_rule_span(Rule::Attribute, lexer); while lexer.skip(Token::Attribute) { let (word, span) = lexer.next_ident_with_span()?; bind_parser.parse(lexer, word, span)?; } - let span = self.pop_scope(lexer); + let span = self.pop_rule_span(lexer); bind_parser.finish(span) } @@ -4198,7 +4202,7 @@ impl Parser { module: &mut crate::Module, lookup_global_expression: &FastHashMap<&'a str, crate::Expression>, ) -> Result<(crate::Function, &'a str), Error<'a>> { - self.push_scope(Scope::FunctionDecl, lexer); + self.push_rule_span(Rule::FunctionDecl, lexer); // read function name let mut symbol_table = super::SymbolTable::default(); let (fun_name, span) = lexer.next_ident_with_span()?; @@ -4317,7 +4321,7 @@ impl Parser { // fixup the IR ensure_block_returns(&mut fun.body); // done - self.pop_scope(lexer); + self.pop_rule_span(lexer); // Set named expressions after block parsing ends fun.named_expressions = named_expressions; @@ -4338,7 +4342,7 @@ impl Parser { let mut early_depth_test = None; let (mut bind_index, mut bind_group) = (None, None); - self.push_scope(Scope::Attribute, lexer); + self.push_rule_span(Rule::Attribute, lexer); while lexer.skip(Token::Attribute) { match lexer.next_ident_with_span()? { ("binding", _) => { @@ -4392,7 +4396,7 @@ impl Parser { } } - let attrib_scope = self.pop_scope(lexer); + let attrib_span = self.pop_rule_span(lexer); match (bind_group, bind_index) { (Some(group), Some(index)) => { binding = Some(crate::ResourceBinding { @@ -4400,8 +4404,8 @@ impl Parser { binding: index, }); } - (Some(_), None) => return Err(Error::MissingAttribute("binding", attrib_scope)), - (None, Some(_)) => return Err(Error::MissingAttribute("group", attrib_scope)), + (Some(_), None) => return Err(Error::MissingAttribute("binding", attrib_span)), + (None, Some(_)) => return Err(Error::MissingAttribute("group", attrib_span)), (None, None) => {} } @@ -4577,8 +4581,8 @@ impl Parser { Err(error) => return Err(error.as_parse_error(lexer.source)), Ok(true) => {} Ok(false) => { - if !self.scopes.is_empty() { - log::error!("Reached the end of file, but scopes are not closed"); + if !self.rules.is_empty() { + log::error!("Reached the end of file, but rule stack is not empty"); return Err(Error::Other.as_parse_error(lexer.source)); }; return Ok(module); From 544f14ad2f7ac63875053a33ccd1ef60bf3293c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 3 Sep 2022 18:23:44 +0100 Subject: [PATCH 1823/2212] Add some methods to SymbolTable and implement Debug --- src/front/mod.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/front/mod.rs b/src/front/mod.rs index 245839d3e..09836c676 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -254,7 +254,7 @@ where /// the current scope to the root scope, returning `Some` when a variable is /// found or `None` if there doesn't exist a variable with `name` in any /// scope. - pub fn lookup(&mut self, name: &Q) -> Option<&Var> + pub fn lookup(&self, name: &Q) -> Option<&Var> where Name: std::borrow::Borrow, Q: std::hash::Hash + Eq, @@ -277,6 +277,19 @@ where pub fn add(&mut self, name: Name, var: Var) -> Option { self.scopes[self.cursor - 1].insert(name, var) } + + /// Adds a new variable to the root scope. + /// + /// This is used in GLSL for builtins which aren't known in advance and only + /// when used for the first time, so there must be a way to add those + /// declarations to the root unconditionally from the current scope. + /// + /// Returns the previous variable with the same name in the root scope if it + /// exists, so that the frontend might handle it in case variable shadowing + /// is disallowed. + pub fn add_root(&mut self, name: Name, var: Var) -> Option { + self.scopes[0].insert(name, var) + } } impl Default for SymbolTable { @@ -288,3 +301,14 @@ impl Default for SymbolTable { } } } + +use std::fmt; + +impl fmt::Debug for SymbolTable { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SymbolTable ")?; + f.debug_list() + .entries(self.scopes[..self.cursor].iter()) + .finish() + } +} From d9c9fe6218553edcbba7b1c69b05000aca159387 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 3 Sep 2022 18:25:33 +0100 Subject: [PATCH 1824/2212] glsl-in: Migrate to SymbolTable --- src/front/glsl/context.rs | 116 ++++++++++------------------- src/front/glsl/parser/functions.rs | 11 +-- src/front/glsl/variables.rs | 50 ++++++------- 3 files changed, 68 insertions(+), 109 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index c269e5fd1..48574fc5b 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -49,9 +49,7 @@ pub struct Context { pub parameters: Vec>, pub parameters_info: Vec, - //TODO: Find less allocation heavy representation - pub scopes: Vec>, - pub lookup_global_var_exps: FastHashMap, + pub symbol_table: crate::front::SymbolTable, pub samplers: FastHashMap, Handle>, pub typifier: Typifier, @@ -69,11 +67,7 @@ impl Context { parameters: Vec::new(), parameters_info: Vec::new(), - scopes: vec![FastHashMap::default()], - lookup_global_var_exps: FastHashMap::with_capacity_and_hasher( - parser.global_variables.len(), - Default::default(), - ), + symbol_table: crate::front::SymbolTable::default(), samplers: FastHashMap::default(), typifier: Typifier::new(), @@ -167,7 +161,7 @@ impl Context { entry_arg, }; - self.lookup_global_var_exps.insert(name.into(), var); + self.symbol_table.add(name.into(), var); } /// Starts the expression emitter @@ -220,42 +214,25 @@ impl Context { handle } - pub fn lookup_local_var(&self, name: &str) -> Option { - for scope in self.scopes.iter().rev() { - if let Some(var) = scope.get(name) { - return Some(var.clone()); - } - } - None - } - - pub fn lookup_global_var(&mut self, name: &str) -> Option { - self.lookup_global_var_exps.get(name).cloned() - } - - #[cfg(feature = "glsl-validate")] - pub fn lookup_local_var_current_scope(&self, name: &str) -> Option { - if let Some(current) = self.scopes.last() { - current.get(name).cloned() - } else { - None - } - } - /// Add variable to current scope - pub fn add_local_var(&mut self, name: String, expr: Handle, mutable: bool) { - if let Some(current) = self.scopes.last_mut() { - (*current).insert( - name, - VariableReference { - expr, - load: true, - mutable, - constant: None, - entry_arg: None, - }, - ); - } + /// + /// Returns a variable if a variable with the same name was already defined, + /// otherwise returns `None` + pub fn add_local_var( + &mut self, + name: String, + expr: Handle, + mutable: bool, + ) -> Option { + let var = VariableReference { + expr, + load: true, + mutable, + constant: None, + entry_arg: None, + }; + + self.symbol_table.add(name, var) } /// Add function argument to current scope @@ -306,7 +283,7 @@ impl Context { let mutable = qualifier != ParameterQualifier::Const && !opaque; let load = qualifier.is_lhs(); - if mutable && !load { + let var = if mutable && !load { let handle = self.locals.append( LocalVariable { name: Some(name.clone()), @@ -327,42 +304,27 @@ impl Context { meta, ); - if let Some(current) = self.scopes.last_mut() { - (*current).insert( - name, - VariableReference { - expr: local_expr, - load: true, - mutable, - constant: None, - entry_arg: None, - }, - ); + VariableReference { + expr: local_expr, + load: true, + mutable, + constant: None, + entry_arg: None, } - } else if let Some(current) = self.scopes.last_mut() { - (*current).insert( - name, - VariableReference { - expr, - load, - mutable, - constant: None, - entry_arg: None, - }, - ); - } + } else { + VariableReference { + expr, + load, + mutable, + constant: None, + entry_arg: None, + } + }; + + self.symbol_table.add(name, var); } } - /// Add new empty scope - pub fn push_scope(&mut self) { - self.scopes.push(FastHashMap::default()); - } - - pub fn remove_current_scope(&mut self) { - self.scopes.pop(); - } - /// Returns a [`StmtContext`](StmtContext) to be used in parsing and lowering /// /// # Panics diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 6cb9bf017..9ab3400eb 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -422,7 +422,7 @@ impl<'source> ParsingContext<'source> { TokenValue::For => { let mut meta = self.bump(parser)?.meta; - ctx.push_scope(); + ctx.symbol_table.push_scope(); self.expect(parser, TokenValue::LeftParen)?; if self.bump_if(parser, TokenValue::Semicolon).is_none() { @@ -520,7 +520,7 @@ impl<'source> ParsingContext<'source> { meta, ); - ctx.remove_current_scope(); + ctx.symbol_table.pop_scope(); meta } @@ -528,7 +528,6 @@ impl<'source> ParsingContext<'source> { let meta = self.bump(parser)?.meta; let mut block = Block::new(); - ctx.push_scope(); let mut block_terminator = None; let meta = self.parse_compound_statement( @@ -539,8 +538,6 @@ impl<'source> ParsingContext<'source> { &mut block_terminator, )?; - ctx.remove_current_scope(); - body.push(Statement::Block(block), meta); if block_terminator.is_some() { terminator.get_or_insert(body.len()); @@ -572,6 +569,8 @@ impl<'source> ParsingContext<'source> { body: &mut Block, terminator: &mut Option, ) -> Result { + ctx.symbol_table.push_scope(); + loop { if let Some(Token { meta: brace_meta, .. @@ -592,6 +591,8 @@ impl<'source> ParsingContext<'source> { body.cull(idx..) } + ctx.symbol_table.pop_scope(); + Ok(meta) } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 6aa20ce28..d6f9d7e0f 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -82,18 +82,18 @@ impl Parser { )); let expr = ctx.add_expression(Expression::GlobalVariable(handle), meta, body); - ctx.lookup_global_var_exps.insert( - name.into(), - VariableReference { - expr, - load: true, - mutable: data.mutable, - constant: None, - entry_arg: Some(idx), - }, - ); - ctx.lookup_global_var(name) + let var = VariableReference { + expr, + load: true, + mutable: data.mutable, + constant: None, + entry_arg: Some(idx), + }; + + ctx.symbol_table.add_root(name.into(), var.clone()); + + Some(var) } pub(crate) fn lookup_variable( @@ -103,11 +103,8 @@ impl Parser { name: &str, meta: Span, ) -> Option { - if let Some(local_var) = ctx.lookup_local_var(name) { - return Some(local_var); - } - if let Some(global_var) = ctx.lookup_global_var(name) { - return Some(global_var); + if let Some(var) = ctx.symbol_table.lookup(name).cloned() { + return Some(var); } let data = match name { @@ -616,16 +613,6 @@ impl Parser { body: &mut Block, decl: VarDeclaration, ) -> Result> { - #[cfg(feature = "glsl-validate")] - if let Some(ref name) = decl.name { - if ctx.lookup_local_var_current_scope(name).is_some() { - self.errors.push(Error { - kind: ErrorKind::VariableAlreadyDeclared(name.clone()), - meta: decl.meta, - }) - } - } - let storage = decl.qualifiers.storage; let mutable = match storage.0 { StorageQualifier::AddressSpace(AddressSpace::Function) => true, @@ -650,7 +637,16 @@ impl Parser { let expr = ctx.add_expression(Expression::LocalVariable(handle), decl.meta, body); if let Some(name) = decl.name { - ctx.add_local_var(name, expr, mutable); + #[allow(unused_variables)] + let maybe_var = ctx.add_local_var(name.clone(), expr, mutable); + + #[cfg(feature = "glsl-validate")] + if maybe_var.is_some() { + self.errors.push(Error { + kind: ErrorKind::VariableAlreadyDeclared(name), + meta: decl.meta, + }) + } } decl.qualifiers.unused_errors(&mut self.errors); From 7d0e9847b00a3b02df4413713eb048faa420a1d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Mon, 5 Sep 2022 23:45:55 +0100 Subject: [PATCH 1825/2212] Remove the glsl-validate feature When it was introduced it was supposed to allow for fast compiles by skipping glsl specific validation, but as it turns the subset of glsl that's compilable code is already pretty close to the subset of valid glsl code. So the current code gated behind glsl-validate amounts to a single branch that isn't even performance sensitive, and most of the validation is not specific to glsl and is made by naga's validator which can be turned off, so the original goal of fast compile times by disabling validation can still be accomplished. --- Cargo.toml | 1 - cli/Cargo.toml | 2 +- src/front/glsl/error.rs | 1 - src/front/glsl/variables.rs | 2 -- 4 files changed, 1 insertion(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5a6d62805..cbad28e8e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,6 @@ default = [] clone = [] dot-out = [] glsl-in = ["pp-rs"] -glsl-validate = [] glsl-out = [] msl-out = [] serialize = ["serde", "indexmap/serde-1"] diff --git a/cli/Cargo.toml b/cli/Cargo.toml index ac5238bd5..daf169f42 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -14,7 +14,7 @@ name = "naga" path = "src/main.rs" [dependencies] -naga = { version = "0.9", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate", "serialize", "deserialize"] } +naga = { version = "0.9", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } bincode = "1" log = "0.4" codespan-reporting = "0.11" diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index c9ea102fa..299bf57aa 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -101,7 +101,6 @@ pub enum ErrorKind { #[error("unsupported matrix of the form matCx2 in std140 block layout")] UnsupportedMatrixTypeInStd140, /// A variable with the same name already exists in the current scope. - #[cfg(feature = "glsl-validate")] #[error("Variable already declared: {0}")] VariableAlreadyDeclared(String), /// A semantic error was detected in the shader. diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index d6f9d7e0f..1634fb40c 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -637,10 +637,8 @@ impl Parser { let expr = ctx.add_expression(Expression::LocalVariable(handle), decl.meta, body); if let Some(name) = decl.name { - #[allow(unused_variables)] let maybe_var = ctx.add_local_var(name.clone(), expr, mutable); - #[cfg(feature = "glsl-validate")] if maybe_var.is_some() { self.errors.push(Error { kind: ErrorKind::VariableAlreadyDeclared(name), From eb6124ec94ac6eed83b5acc4272bd9016c2e61dc Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 9 Sep 2022 16:24:13 -0700 Subject: [PATCH 1826/2212] Document arithmetic binary operation type rules. --- src/lib.rs | 39 +++++++++++++++++++++++++++++++++++++++ src/valid/expression.rs | 9 +++++++-- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5db2a397d..c4893b73a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -876,6 +876,45 @@ pub enum UnaryOperator { } /// Operation that can be applied on two values. +/// +/// ## Arithmetic type rules +/// +/// The arithmetic operations `Add`, `Subtract`, `Multiply`, `Divide`, and +/// `Modulo` can all be applied to [`Scalar`] types other than [`Bool`], or +/// [`Vector`]s thereof. Both operands must have the same type. +/// +/// `Add` and `Subtract` can also be applied to [`Matrix`] values. Both operands +/// must have the same type. +/// +/// `Multiply` supports additional cases: +/// +/// - A [`Matrix`] or [`Vector`] can be multiplied by a scalar [`Float`], +/// either on the left or the right. +/// +/// - A [`Matrix`] on the left can be multiplied by a [`Vector`] on the right +/// if the matrix has as many columns as the vector has components (`matCxR +/// * VecC`). +/// +/// - A [`Vector`] on the left can be multiplied by a [`Matrix`] on the right +/// if the matrix has as many rows as the vector has components (`VecR * +/// matCxR`). +/// +/// - Two matrices can be multiplied if the left operand has as many columns +/// as the right operand has rows (`matNxR * matCxN`). +/// +/// In all the above `Multiply` cases, the byte widths of the underlying scalar +/// types of both operands must be the same. +/// +/// Note that `Multiply` supports mixed vector and scalar operations directly, +/// whereas the other arithmetic operations require an explicit [`Splat`] for +/// mixed-type use. +/// +/// [`Scalar`]: TypeInner::Scalar +/// [`Vector`]: TypeInner::Vector +/// [`Matrix`]: TypeInner::Matrix +/// [`Float`]: ScalarKind::Float +/// [`Bool`]: ScalarKind::Bool +/// [`Splat`]: Expression::Splat #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 6279ed362..0f173707f 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -740,16 +740,18 @@ impl super::Validator { _ => false, }, Bo::Multiply => { - let kind_match = match left_inner.scalar_kind() { + let kind_allowed = match left_inner.scalar_kind() { Some(Sk::Uint | Sk::Sint | Sk::Float) => true, Some(Sk::Bool) | None => false, }; let types_match = match (left_inner, right_inner) { + // Straight scalar and mixed scalar/vector. (&Ti::Scalar { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) | (&Ti::Vector { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. }) | (&Ti::Scalar { kind: kind1, .. }, &Ti::Vector { kind: kind2, .. }) => { kind1 == kind2 } + // Scalar/matrix. ( &Ti::Scalar { kind: Sk::Float, .. @@ -762,6 +764,7 @@ impl super::Validator { kind: Sk::Float, .. }, ) => true, + // Vector/vector. ( &Ti::Vector { kind: kind1, @@ -774,6 +777,7 @@ impl super::Validator { .. }, ) => kind1 == kind2 && size1 == size2, + // Matrix * vector. ( &Ti::Matrix { columns, .. }, &Ti::Vector { @@ -782,6 +786,7 @@ impl super::Validator { .. }, ) => columns == size, + // Vector * matrix. ( &Ti::Vector { kind: Sk::Float, @@ -807,7 +812,7 @@ impl super::Validator { | Ti::Matrix { width, .. } => width, _ => 0, }; - kind_match && types_match && left_width == right_width + kind_allowed && types_match && left_width == right_width } Bo::Equal | Bo::NotEqual => left_inner.is_sized() && left_inner == right_inner, Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual => { From db1321cfb6b40855ce6580f4fa9c225fe7b0d3d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 7 Sep 2022 22:58:40 +0100 Subject: [PATCH 1827/2212] wgsl-in: Splat on compound assignments Compound assignments on wgsl follow the same semantics as their underlying operation, this includes the splatting behavior when mixing scalar and vector operands, which was done for binary operations but not for compound assignments. --- src/front/wgsl/mod.rs | 67 +- tests/in/operators.wgsl | 8 + tests/out/glsl/operators.main.Compute.glsl | 71 +- tests/out/hlsl/operators.hlsl | 73 +- tests/out/msl/operators.msl | 84 +- tests/out/spv/operators.spvasm | 941 +++++++++++---------- tests/out/wgsl/operators.wgsl | 72 +- 7 files changed, 711 insertions(+), 605 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 657de486f..6e600ba59 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -916,29 +916,8 @@ impl<'a> ExpressionContext<'a, '_, '_> { let mut right = self.apply_load_rule(unloaded_right); let end = lexer.current_byte_offset() as u32; - // Insert splats, if needed by the non-'*' operations. - // (`BinaryOperator::Multiply` handles splats itself.) - if op != crate::BinaryOperator::Multiply { - let left_size = match *self.resolve_type(left)? { - crate::TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - match (left_size, self.resolve_type(right)?) { - (Some(size), &crate::TypeInner::Scalar { .. }) => { - right = self.expressions.append( - crate::Expression::Splat { size, value: right }, - self.expressions.get_span(right), - ); - } - (None, &crate::TypeInner::Vector { size, .. }) => { - left = self.expressions.append( - crate::Expression::Splat { size, value: left }, - self.expressions.get_span(left), - ); - } - _ => {} - } - } + self.binary_op_splat(op, &mut left, &mut right)?; + accumulator = TypedExpression::non_reference(self.expressions.append( crate::Expression::Binary { op, left, right }, NagaSpan::new(start, end), @@ -947,6 +926,41 @@ impl<'a> ExpressionContext<'a, '_, '_> { Ok(accumulator) } + /// Insert splats, if needed by the non-'*' operations. + fn binary_op_splat( + &mut self, + op: crate::BinaryOperator, + left: &mut Handle, + right: &mut Handle, + ) -> Result<(), Error<'a>> { + if op != crate::BinaryOperator::Multiply { + let left_size = match *self.resolve_type(*left)? { + crate::TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + match (left_size, self.resolve_type(*right)?) { + (Some(size), &crate::TypeInner::Scalar { .. }) => { + *right = self.expressions.append( + crate::Expression::Splat { + size, + value: *right, + }, + self.expressions.get_span(*right), + ); + } + (None, &crate::TypeInner::Vector { size, .. }) => { + *left = self.expressions.append( + crate::Expression::Splat { size, value: *left }, + self.expressions.get_span(*left), + ); + } + _ => {} + } + } + + Ok(()) + } + /// Add a single expression to the expression table that is not covered by `self.emitter`. /// /// This is useful for `CallResult` and `AtomicResult` expressions, which should not be covered by @@ -3321,13 +3335,16 @@ impl Parser { //Note: `consume_token` shouldn't produce any other assignment ops _ => unreachable!(), }; - let left = context.expressions.append( + let mut left = context.expressions.append( crate::Expression::Load { pointer: reference.handle, }, lhs_span.into(), ); - let right = self.parse_general_expression(lexer, context.reborrow())?; + let mut right = self.parse_general_expression(lexer, context.reborrow())?; + + context.binary_op_splat(op, &mut left, &mut right)?; + context .expressions .append(crate::Expression::Binary { op, left, right }, span.into()) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 6cee25f2c..1f6155397 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -28,6 +28,14 @@ fn splat() -> vec4 { return a.xyxy + vec4(b); } +fn splat_assignment() -> vec2 { + var a = vec2(2.0); + a += 1.0; + a -= 3.0; + a /= 4.0; + return a; +} + fn bool_cast(x: vec3) -> vec3 { let y = vec3(x); return vec3(y); diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index ab232d553..32716658f 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -23,9 +23,22 @@ vec4 builtins() { } vec4 splat() { - vec2 a_1 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + vec2 a_2 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); ivec4 b = (ivec4(5) % ivec4(2)); - return (a_1.xyxy + vec4(b)); + return (a_2.xyxy + vec4(b)); +} + +vec2 splat_assignment() { + vec2 a = vec2(0.0); + a = vec2(2.0); + vec2 _e7 = a; + a = (_e7 + vec2(1.0)); + vec2 _e11 = a; + a = (_e11 - vec2(3.0)); + vec2 _e15 = a; + a = (_e15 / vec2(4.0)); + vec2 _e19 = a; + return _e19; } vec3 bool_cast(vec3 x) { @@ -203,34 +216,34 @@ void comparison() { } void assignment() { - int a = 1; + int a_1 = 1; ivec3 vec0_ = ivec3(0, 0, 0); - int _e6 = a; - a = (_e6 + 1); - int _e9 = a; - a = (_e9 - 1); - int _e12 = a; - int _e13 = a; - a = (_e12 * _e13); - int _e15 = a; - int _e16 = a; - a = (_e15 / _e16); - int _e18 = a; - a = (_e18 % 1); - int _e21 = a; - a = (_e21 & 0); - int _e24 = a; - a = (_e24 | 0); - int _e27 = a; - a = (_e27 ^ 0); - int _e30 = a; - a = (_e30 << 2u); - int _e33 = a; - a = (_e33 >> 1u); - int _e36 = a; - a = (_e36 + 1); - int _e39 = a; - a = (_e39 - 1); + int _e6 = a_1; + a_1 = (_e6 + 1); + int _e9 = a_1; + a_1 = (_e9 - 1); + int _e12 = a_1; + int _e13 = a_1; + a_1 = (_e12 * _e13); + int _e15 = a_1; + int _e16 = a_1; + a_1 = (_e15 / _e16); + int _e18 = a_1; + a_1 = (_e18 % 1); + int _e21 = a_1; + a_1 = (_e21 & 0); + int _e24 = a_1; + a_1 = (_e24 | 0); + int _e27 = a_1; + a_1 = (_e27 ^ 0); + int _e30 = a_1; + a_1 = (_e30 << 2u); + int _e33 = a_1; + a_1 = (_e33 >> 1u); + int _e36 = a_1; + a_1 = (_e36 + 1); + int _e39 = a_1; + a_1 = (_e39 - 1); int _e46 = vec0_.y; vec0_.y = (_e46 + 1); int _e51 = vec0_.y; diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 01ffb9036..48e8fee09 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -39,9 +39,24 @@ float4 builtins() float4 splat() { - float2 a_1 = ((((1.0).xx + (2.0).xx) - (3.0).xx) / (4.0).xx); + float2 a_2 = ((((1.0).xx + (2.0).xx) - (3.0).xx) / (4.0).xx); int4 b = ((5).xxxx % (2).xxxx); - return (a_1.xyxy + float4(b)); + return (a_2.xyxy + float4(b)); +} + +float2 splat_assignment() +{ + float2 a = (float2)0; + + a = (2.0).xx; + float2 _expr7 = a; + a = (_expr7 + (1.0).xx); + float2 _expr11 = a; + a = (_expr11 - (3.0).xx); + float2 _expr15 = a; + a = (_expr15 / (4.0).xx); + float2 _expr19 = a; + return _expr19; } float3 bool_cast(float3 x) @@ -233,35 +248,35 @@ void comparison() void assignment() { - int a = 1; + int a_1 = 1; int3 vec0_ = int3(0, 0, 0); - int _expr6 = a; - a = (_expr6 + 1); - int _expr9 = a; - a = (_expr9 - 1); - int _expr12 = a; - int _expr13 = a; - a = (_expr12 * _expr13); - int _expr15 = a; - int _expr16 = a; - a = (_expr15 / _expr16); - int _expr18 = a; - a = (_expr18 % 1); - int _expr21 = a; - a = (_expr21 & 0); - int _expr24 = a; - a = (_expr24 | 0); - int _expr27 = a; - a = (_expr27 ^ 0); - int _expr30 = a; - a = (_expr30 << 2u); - int _expr33 = a; - a = (_expr33 >> 1u); - int _expr36 = a; - a = (_expr36 + 1); - int _expr39 = a; - a = (_expr39 - 1); + int _expr6 = a_1; + a_1 = (_expr6 + 1); + int _expr9 = a_1; + a_1 = (_expr9 - 1); + int _expr12 = a_1; + int _expr13 = a_1; + a_1 = (_expr12 * _expr13); + int _expr15 = a_1; + int _expr16 = a_1; + a_1 = (_expr15 / _expr16); + int _expr18 = a_1; + a_1 = (_expr18 % 1); + int _expr21 = a_1; + a_1 = (_expr21 & 0); + int _expr24 = a_1; + a_1 = (_expr24 | 0); + int _expr27 = a_1; + a_1 = (_expr27 ^ 0); + int _expr30 = a_1; + a_1 = (_expr30 << 2u); + int _expr33 = a_1; + a_1 = (_expr33 >> 1u); + int _expr36 = a_1; + a_1 = (_expr36 + 1); + int _expr39 = a_1; + a_1 = (_expr39 - 1); int _expr46 = vec0_.y; vec0_.y = (_expr46 + 1); int _expr51 = vec0_.y; diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 294fa5812..0c3872000 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -19,15 +19,15 @@ constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0}; constant metal::float4 v_f32_half = {0.5, 0.5, 0.5, 0.5}; constant metal::int4 v_i32_one = {1, 1, 1, 1}; constant metal::uint2 const_type_11_ = {0u, 0u}; -constant metal::float2 const_type_6_ = {0.0, 0.0}; -constant metal::float2x2 const_type_7_ = {const_type_6_, const_type_6_}; +constant metal::float2 const_type_4_ = {0.0, 0.0}; +constant metal::float2x2 const_type_7_ = {const_type_4_, const_type_4_}; constant metal::float4 const_type = {0.0, 0.0, 0.0, 0.0}; constant Foo const_Foo = {const_type, 0}; constant type_12 const_type_12_ = {const_Foo, const_Foo, const_Foo}; -constant metal::float3 const_type_4_ = {0.0, 0.0, 0.0}; -constant metal::float2x3 const_type_14_ = {const_type_4_, const_type_4_}; -constant metal::float3x3 const_type_15_ = {const_type_4_, const_type_4_, const_type_4_}; -constant metal::float4x3 const_type_16_ = {const_type_4_, const_type_4_, const_type_4_, const_type_4_}; +constant metal::float3 const_type_5_ = {0.0, 0.0, 0.0}; +constant metal::float2x3 const_type_14_ = {const_type_5_, const_type_5_}; +constant metal::float3x3 const_type_15_ = {const_type_5_, const_type_5_, const_type_5_}; +constant metal::float4x3 const_type_16_ = {const_type_5_, const_type_5_, const_type_5_, const_type_5_}; constant metal::float3x4 const_type_17_ = {const_type, const_type, const_type}; constant metal::int3 const_type_18_ = {0, 0, 0}; @@ -46,9 +46,23 @@ metal::float4 builtins( metal::float4 splat( ) { - metal::float2 a_1 = ((metal::float2(1.0) + metal::float2(2.0)) - metal::float2(3.0)) / metal::float2(4.0); + metal::float2 a_2 = ((metal::float2(1.0) + metal::float2(2.0)) - metal::float2(3.0)) / metal::float2(4.0); metal::int4 b = metal::int4(5) % metal::int4(2); - return a_1.xyxy + static_cast(b); + return a_2.xyxy + static_cast(b); +} + +metal::float2 splat_assignment( +) { + metal::float2 a = {}; + a = metal::float2(2.0); + metal::float2 _e7 = a; + a = _e7 + metal::float2(1.0); + metal::float2 _e11 = a; + a = _e11 - metal::float2(3.0); + metal::float2 _e15 = a; + a = _e15 / metal::float2(4.0); + metal::float2 _e19 = a; + return _e19; } metal::float3 bool_cast( @@ -234,34 +248,34 @@ void comparison( void assignment( ) { - int a = 1; + int a_1 = 1; metal::int3 vec0_ = const_type_18_; - int _e6 = a; - a = _e6 + 1; - int _e9 = a; - a = _e9 - 1; - int _e12 = a; - int _e13 = a; - a = _e12 * _e13; - int _e15 = a; - int _e16 = a; - a = _e15 / _e16; - int _e18 = a; - a = _e18 % 1; - int _e21 = a; - a = _e21 & 0; - int _e24 = a; - a = _e24 | 0; - int _e27 = a; - a = _e27 ^ 0; - int _e30 = a; - a = _e30 << 2u; - int _e33 = a; - a = _e33 >> 1u; - int _e36 = a; - a = _e36 + 1; - int _e39 = a; - a = _e39 - 1; + int _e6 = a_1; + a_1 = _e6 + 1; + int _e9 = a_1; + a_1 = _e9 - 1; + int _e12 = a_1; + int _e13 = a_1; + a_1 = _e12 * _e13; + int _e15 = a_1; + int _e16 = a_1; + a_1 = _e15 / _e16; + int _e18 = a_1; + a_1 = _e18 % 1; + int _e21 = a_1; + a_1 = _e21 & 0; + int _e24 = a_1; + a_1 = _e24 | 0; + int _e27 = a_1; + a_1 = _e27 ^ 0; + int _e30 = a_1; + a_1 = _e30 << 2u; + int _e33 = a_1; + a_1 = _e33 >> 1u; + int _e36 = a_1; + a_1 = _e36 + 1; + int _e39 = a_1; + a_1 = _e39 - 1; int _e46 = vec0_.y; vec0_.y = _e46 + 1; int _e51 = vec0_.y; diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index bdd355110..0fde0a707 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,14 +1,14 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 525 +; Bound: 543 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %513 "main" -OpExecutionMode %513 LocalSize 1 1 1 -OpMemberDecorate %30 0 Offset 0 -OpMemberDecorate %30 1 Offset 16 +OpEntryPoint GLCompute %531 "main" +OpExecutionMode %531 LocalSize 1 1 1 +OpMemberDecorate %31 0 Offset 0 +OpMemberDecorate %31 1 Offset 16 OpDecorate %35 ArrayStride 32 OpDecorate %36 ArrayStride 4 %2 = OpTypeVoid @@ -38,17 +38,17 @@ OpDecorate %36 ArrayStride 4 %26 = OpTypeVector %4 4 %27 = OpTypeVector %8 4 %28 = OpTypeVector %10 4 -%29 = OpTypeVector %4 3 -%30 = OpTypeStruct %26 %8 -%31 = OpTypeVector %4 2 -%32 = OpTypeMatrix %31 2 +%29 = OpTypeVector %4 2 +%30 = OpTypeVector %4 3 +%31 = OpTypeStruct %26 %8 +%32 = OpTypeMatrix %29 2 %33 = OpTypeMatrix %26 4 %34 = OpTypeVector %20 2 -%35 = OpTypeArray %30 %21 +%35 = OpTypeArray %31 %21 %36 = OpTypeArray %8 %22 -%37 = OpTypeMatrix %29 2 -%38 = OpTypeMatrix %29 3 -%39 = OpTypeMatrix %29 4 +%37 = OpTypeMatrix %30 2 +%38 = OpTypeMatrix %30 3 +%39 = OpTypeMatrix %30 4 %40 = OpTypeMatrix %26 3 %41 = OpTypeVector %8 3 %42 = OpConstantComposite %26 %3 %3 %3 %3 @@ -56,32 +56,35 @@ OpDecorate %36 ArrayStride 4 %44 = OpConstantComposite %26 %6 %6 %6 %6 %45 = OpConstantComposite %27 %7 %7 %7 %7 %46 = OpConstantComposite %34 %19 %19 -%47 = OpConstantComposite %31 %5 %5 +%47 = OpConstantComposite %29 %5 %5 %48 = OpConstantComposite %32 %47 %47 %49 = OpConstantComposite %26 %5 %5 %5 %5 -%50 = OpConstantComposite %30 %49 %11 +%50 = OpConstantComposite %31 %49 %11 %51 = OpConstantComposite %35 %50 %50 %50 -%52 = OpConstantComposite %29 %5 %5 %5 +%52 = OpConstantComposite %30 %5 %5 %5 %53 = OpConstantComposite %37 %52 %52 %54 = OpConstantComposite %38 %52 %52 %52 %55 = OpConstantComposite %39 %52 %52 %52 %52 %56 = OpConstantComposite %40 %49 %49 %49 %57 = OpConstantComposite %41 %11 %11 %11 %60 = OpTypeFunction %26 -%102 = OpTypeFunction %29 %29 -%104 = OpTypeVector %10 3 -%111 = OpTypePointer Function %30 -%112 = OpConstantNull %30 -%115 = OpTypeFunction %4 -%140 = OpTypePointer Function %26 -%141 = OpTypePointer Function %4 -%146 = OpTypeFunction %2 -%149 = OpTypeVector %10 2 -%165 = OpTypeVector %8 2 -%176 = OpTypeVector %20 3 -%471 = OpTypePointer Function %8 -%473 = OpTypePointer Function %41 -%503 = OpTypePointer Function %8 +%100 = OpTypePointer Function %29 +%101 = OpConstantNull %29 +%104 = OpTypeFunction %29 +%120 = OpTypeFunction %30 %30 +%122 = OpTypeVector %10 3 +%129 = OpTypePointer Function %31 +%130 = OpConstantNull %31 +%133 = OpTypeFunction %4 +%158 = OpTypePointer Function %26 +%159 = OpTypePointer Function %4 +%164 = OpTypeFunction %2 +%167 = OpTypeVector %10 2 +%183 = OpTypeVector %8 2 +%194 = OpTypeVector %20 3 +%489 = OpTypePointer Function %8 +%491 = OpTypePointer Function %41 +%521 = OpTypePointer Function %8 %59 = OpFunction %26 None %60 %58 = OpLabel OpBranch %61 @@ -113,13 +116,13 @@ OpFunctionEnd %83 = OpLabel OpBranch %85 %85 = OpLabel -%86 = OpCompositeConstruct %31 %14 %14 -%87 = OpCompositeConstruct %31 %3 %3 -%88 = OpFAdd %31 %87 %86 -%89 = OpCompositeConstruct %31 %15 %15 -%90 = OpFSub %31 %88 %89 -%91 = OpCompositeConstruct %31 %16 %16 -%92 = OpFDiv %31 %90 %91 +%86 = OpCompositeConstruct %29 %14 %14 +%87 = OpCompositeConstruct %29 %3 %3 +%88 = OpFAdd %29 %87 %86 +%89 = OpCompositeConstruct %29 %15 %15 +%90 = OpFSub %29 %88 %89 +%91 = OpCompositeConstruct %29 %16 %16 +%92 = OpFDiv %29 %90 %91 %93 = OpCompositeConstruct %27 %17 %17 %17 %17 %94 = OpCompositeConstruct %27 %18 %18 %18 %18 %95 = OpSRem %27 %93 %94 @@ -128,448 +131,470 @@ OpBranch %85 %98 = OpFAdd %26 %96 %97 OpReturnValue %98 OpFunctionEnd -%101 = OpFunction %29 None %102 -%100 = OpFunctionParameter %29 -%99 = OpLabel -OpBranch %103 -%103 = OpLabel -%105 = OpCompositeConstruct %29 %5 %5 %5 -%106 = OpFUnordNotEqual %104 %100 %105 -%107 = OpCompositeConstruct %29 %5 %5 %5 -%108 = OpCompositeConstruct %29 %3 %3 %3 -%109 = OpSelect %29 %106 %108 %107 -OpReturnValue %109 +%103 = OpFunction %29 None %104 +%102 = OpLabel +%99 = OpVariable %100 Function %101 +OpBranch %105 +%105 = OpLabel +%106 = OpCompositeConstruct %29 %14 %14 +OpStore %99 %106 +%107 = OpLoad %29 %99 +%108 = OpCompositeConstruct %29 %3 %3 +%109 = OpFAdd %29 %107 %108 +OpStore %99 %109 +%110 = OpLoad %29 %99 +%111 = OpCompositeConstruct %29 %15 %15 +%112 = OpFSub %29 %110 %111 +OpStore %99 %112 +%113 = OpLoad %29 %99 +%114 = OpCompositeConstruct %29 %16 %16 +%115 = OpFDiv %29 %113 %114 +OpStore %99 %115 +%116 = OpLoad %29 %99 +OpReturnValue %116 OpFunctionEnd -%114 = OpFunction %4 None %115 -%113 = OpLabel -%110 = OpVariable %111 Function %112 -OpBranch %116 -%116 = OpLabel -%117 = OpCompositeConstruct %26 %3 %3 %3 %3 -%118 = OpCompositeConstruct %30 %117 %7 -OpStore %110 %118 -%119 = OpCompositeConstruct %31 %3 %5 -%120 = OpCompositeConstruct %31 %5 %3 -%121 = OpCompositeConstruct %32 %119 %120 -%122 = OpCompositeConstruct %26 %3 %5 %5 %5 -%123 = OpCompositeConstruct %26 %5 %3 %5 %5 -%124 = OpCompositeConstruct %26 %5 %5 %3 %5 -%125 = OpCompositeConstruct %26 %5 %5 %5 %3 -%126 = OpCompositeConstruct %33 %122 %123 %124 %125 -%127 = OpCompositeConstruct %34 %19 %19 -%128 = OpCompositeConstruct %31 %5 %5 -%129 = OpCompositeConstruct %31 %5 %5 -%130 = OpCompositeConstruct %32 %128 %129 -%131 = OpCompositeConstruct %36 %11 %7 %18 %21 -%137 = OpCopyObject %37 %53 -%139 = OpCopyObject %37 %53 -%142 = OpAccessChain %141 %110 %19 %19 -%143 = OpLoad %4 %142 -OpReturnValue %143 +%119 = OpFunction %30 None %120 +%118 = OpFunctionParameter %30 +%117 = OpLabel +OpBranch %121 +%121 = OpLabel +%123 = OpCompositeConstruct %30 %5 %5 %5 +%124 = OpFUnordNotEqual %122 %118 %123 +%125 = OpCompositeConstruct %30 %5 %5 %5 +%126 = OpCompositeConstruct %30 %3 %3 %3 +%127 = OpSelect %30 %124 %126 %125 +OpReturnValue %127 OpFunctionEnd -%145 = OpFunction %2 None %146 -%144 = OpLabel -OpBranch %147 -%147 = OpLabel -%148 = OpLogicalNot %10 %9 -%150 = OpCompositeConstruct %149 %9 %9 -%151 = OpLogicalNot %149 %150 -%152 = OpLogicalOr %10 %9 %12 -%153 = OpLogicalAnd %10 %9 %12 -%154 = OpLogicalOr %10 %9 %12 -%155 = OpCompositeConstruct %104 %9 %9 %9 -%156 = OpCompositeConstruct %104 %12 %12 %12 -%157 = OpLogicalOr %104 %155 %156 -%158 = OpLogicalAnd %10 %9 %12 -%159 = OpCompositeConstruct %28 %9 %9 %9 %9 -%160 = OpCompositeConstruct %28 %12 %12 %12 %12 -%161 = OpLogicalAnd %28 %159 %160 +%132 = OpFunction %4 None %133 +%131 = OpLabel +%128 = OpVariable %129 Function %130 +OpBranch %134 +%134 = OpLabel +%135 = OpCompositeConstruct %26 %3 %3 %3 %3 +%136 = OpCompositeConstruct %31 %135 %7 +OpStore %128 %136 +%137 = OpCompositeConstruct %29 %3 %5 +%138 = OpCompositeConstruct %29 %5 %3 +%139 = OpCompositeConstruct %32 %137 %138 +%140 = OpCompositeConstruct %26 %3 %5 %5 %5 +%141 = OpCompositeConstruct %26 %5 %3 %5 %5 +%142 = OpCompositeConstruct %26 %5 %5 %3 %5 +%143 = OpCompositeConstruct %26 %5 %5 %5 %3 +%144 = OpCompositeConstruct %33 %140 %141 %142 %143 +%145 = OpCompositeConstruct %34 %19 %19 +%146 = OpCompositeConstruct %29 %5 %5 +%147 = OpCompositeConstruct %29 %5 %5 +%148 = OpCompositeConstruct %32 %146 %147 +%149 = OpCompositeConstruct %36 %11 %7 %18 %21 +%155 = OpCopyObject %37 %53 +%157 = OpCopyObject %37 %53 +%160 = OpAccessChain %159 %128 %19 %19 +%161 = OpLoad %4 %160 +OpReturnValue %161 +OpFunctionEnd +%163 = OpFunction %2 None %164 +%162 = OpLabel +OpBranch %165 +%165 = OpLabel +%166 = OpLogicalNot %10 %9 +%168 = OpCompositeConstruct %167 %9 %9 +%169 = OpLogicalNot %167 %168 +%170 = OpLogicalOr %10 %9 %12 +%171 = OpLogicalAnd %10 %9 %12 +%172 = OpLogicalOr %10 %9 %12 +%173 = OpCompositeConstruct %122 %9 %9 %9 +%174 = OpCompositeConstruct %122 %12 %12 %12 +%175 = OpLogicalOr %122 %173 %174 +%176 = OpLogicalAnd %10 %9 %12 +%177 = OpCompositeConstruct %28 %9 %9 %9 %9 +%178 = OpCompositeConstruct %28 %12 %12 %12 %12 +%179 = OpLogicalAnd %28 %177 %178 OpReturn OpFunctionEnd -%163 = OpFunction %2 None %146 -%162 = OpLabel -OpBranch %164 -%164 = OpLabel -%166 = OpCompositeConstruct %165 %7 %7 -%167 = OpSNegate %165 %166 -%168 = OpCompositeConstruct %31 %3 %3 -%169 = OpFNegate %31 %168 -%170 = OpIAdd %8 %18 %7 -%171 = OpIAdd %20 %24 %25 -%172 = OpFAdd %4 %14 %3 -%173 = OpCompositeConstruct %165 %18 %18 -%174 = OpCompositeConstruct %165 %7 %7 -%175 = OpIAdd %165 %173 %174 -%177 = OpCompositeConstruct %176 %24 %24 %24 -%178 = OpCompositeConstruct %176 %25 %25 %25 -%179 = OpIAdd %176 %177 %178 -%180 = OpCompositeConstruct %26 %14 %14 %14 %14 -%181 = OpCompositeConstruct %26 %3 %3 %3 %3 -%182 = OpFAdd %26 %180 %181 -%183 = OpISub %8 %18 %7 -%184 = OpISub %20 %24 %25 -%185 = OpFSub %4 %14 %3 -%186 = OpCompositeConstruct %165 %18 %18 -%187 = OpCompositeConstruct %165 %7 %7 -%188 = OpISub %165 %186 %187 -%189 = OpCompositeConstruct %176 %24 %24 %24 -%190 = OpCompositeConstruct %176 %25 %25 %25 -%191 = OpISub %176 %189 %190 -%192 = OpCompositeConstruct %26 %14 %14 %14 %14 -%193 = OpCompositeConstruct %26 %3 %3 %3 %3 -%194 = OpFSub %26 %192 %193 -%195 = OpIMul %8 %18 %7 -%196 = OpIMul %20 %24 %25 -%197 = OpFMul %4 %14 %3 -%198 = OpCompositeConstruct %165 %18 %18 -%199 = OpCompositeConstruct %165 %7 %7 -%200 = OpIMul %165 %198 %199 -%201 = OpCompositeConstruct %176 %24 %24 %24 -%202 = OpCompositeConstruct %176 %25 %25 %25 -%203 = OpIMul %176 %201 %202 -%204 = OpCompositeConstruct %26 %14 %14 %14 %14 -%205 = OpCompositeConstruct %26 %3 %3 %3 %3 -%206 = OpFMul %26 %204 %205 -%207 = OpSDiv %8 %18 %7 -%208 = OpUDiv %20 %24 %25 -%209 = OpFDiv %4 %14 %3 -%210 = OpCompositeConstruct %165 %18 %18 -%211 = OpCompositeConstruct %165 %7 %7 -%212 = OpSDiv %165 %210 %211 -%213 = OpCompositeConstruct %176 %24 %24 %24 -%214 = OpCompositeConstruct %176 %25 %25 %25 -%215 = OpUDiv %176 %213 %214 -%216 = OpCompositeConstruct %26 %14 %14 %14 %14 -%217 = OpCompositeConstruct %26 %3 %3 %3 %3 -%218 = OpFDiv %26 %216 %217 -%219 = OpSRem %8 %18 %7 -%220 = OpUMod %20 %24 %25 -%221 = OpFRem %4 %14 %3 -%222 = OpCompositeConstruct %165 %18 %18 -%223 = OpCompositeConstruct %165 %7 %7 -%224 = OpSRem %165 %222 %223 -%225 = OpCompositeConstruct %176 %24 %24 %24 -%226 = OpCompositeConstruct %176 %25 %25 %25 -%227 = OpUMod %176 %225 %226 -%228 = OpCompositeConstruct %26 %14 %14 %14 %14 -%229 = OpCompositeConstruct %26 %3 %3 %3 %3 -%230 = OpFRem %26 %228 %229 -%231 = OpCompositeConstruct %165 %18 %18 -%232 = OpCompositeConstruct %165 %7 %7 -%233 = OpIAdd %165 %231 %232 -%234 = OpCompositeConstruct %165 %7 %7 -%235 = OpCompositeConstruct %165 %18 %18 -%236 = OpIAdd %165 %235 %234 -%237 = OpCompositeConstruct %34 %24 %24 -%238 = OpCompositeConstruct %34 %25 %25 -%239 = OpIAdd %34 %237 %238 -%240 = OpCompositeConstruct %34 %25 %25 -%241 = OpCompositeConstruct %34 %24 %24 -%242 = OpIAdd %34 %241 %240 -%243 = OpCompositeConstruct %31 %14 %14 -%244 = OpCompositeConstruct %31 %3 %3 -%245 = OpFAdd %31 %243 %244 -%246 = OpCompositeConstruct %31 %3 %3 -%247 = OpCompositeConstruct %31 %14 %14 -%248 = OpFAdd %31 %247 %246 -%249 = OpCompositeConstruct %165 %18 %18 -%250 = OpCompositeConstruct %165 %7 %7 -%251 = OpISub %165 %249 %250 -%252 = OpCompositeConstruct %165 %7 %7 -%253 = OpCompositeConstruct %165 %18 %18 -%254 = OpISub %165 %253 %252 +%181 = OpFunction %2 None %164 +%180 = OpLabel +OpBranch %182 +%182 = OpLabel +%184 = OpCompositeConstruct %183 %7 %7 +%185 = OpSNegate %183 %184 +%186 = OpCompositeConstruct %29 %3 %3 +%187 = OpFNegate %29 %186 +%188 = OpIAdd %8 %18 %7 +%189 = OpIAdd %20 %24 %25 +%190 = OpFAdd %4 %14 %3 +%191 = OpCompositeConstruct %183 %18 %18 +%192 = OpCompositeConstruct %183 %7 %7 +%193 = OpIAdd %183 %191 %192 +%195 = OpCompositeConstruct %194 %24 %24 %24 +%196 = OpCompositeConstruct %194 %25 %25 %25 +%197 = OpIAdd %194 %195 %196 +%198 = OpCompositeConstruct %26 %14 %14 %14 %14 +%199 = OpCompositeConstruct %26 %3 %3 %3 %3 +%200 = OpFAdd %26 %198 %199 +%201 = OpISub %8 %18 %7 +%202 = OpISub %20 %24 %25 +%203 = OpFSub %4 %14 %3 +%204 = OpCompositeConstruct %183 %18 %18 +%205 = OpCompositeConstruct %183 %7 %7 +%206 = OpISub %183 %204 %205 +%207 = OpCompositeConstruct %194 %24 %24 %24 +%208 = OpCompositeConstruct %194 %25 %25 %25 +%209 = OpISub %194 %207 %208 +%210 = OpCompositeConstruct %26 %14 %14 %14 %14 +%211 = OpCompositeConstruct %26 %3 %3 %3 %3 +%212 = OpFSub %26 %210 %211 +%213 = OpIMul %8 %18 %7 +%214 = OpIMul %20 %24 %25 +%215 = OpFMul %4 %14 %3 +%216 = OpCompositeConstruct %183 %18 %18 +%217 = OpCompositeConstruct %183 %7 %7 +%218 = OpIMul %183 %216 %217 +%219 = OpCompositeConstruct %194 %24 %24 %24 +%220 = OpCompositeConstruct %194 %25 %25 %25 +%221 = OpIMul %194 %219 %220 +%222 = OpCompositeConstruct %26 %14 %14 %14 %14 +%223 = OpCompositeConstruct %26 %3 %3 %3 %3 +%224 = OpFMul %26 %222 %223 +%225 = OpSDiv %8 %18 %7 +%226 = OpUDiv %20 %24 %25 +%227 = OpFDiv %4 %14 %3 +%228 = OpCompositeConstruct %183 %18 %18 +%229 = OpCompositeConstruct %183 %7 %7 +%230 = OpSDiv %183 %228 %229 +%231 = OpCompositeConstruct %194 %24 %24 %24 +%232 = OpCompositeConstruct %194 %25 %25 %25 +%233 = OpUDiv %194 %231 %232 +%234 = OpCompositeConstruct %26 %14 %14 %14 %14 +%235 = OpCompositeConstruct %26 %3 %3 %3 %3 +%236 = OpFDiv %26 %234 %235 +%237 = OpSRem %8 %18 %7 +%238 = OpUMod %20 %24 %25 +%239 = OpFRem %4 %14 %3 +%240 = OpCompositeConstruct %183 %18 %18 +%241 = OpCompositeConstruct %183 %7 %7 +%242 = OpSRem %183 %240 %241 +%243 = OpCompositeConstruct %194 %24 %24 %24 +%244 = OpCompositeConstruct %194 %25 %25 %25 +%245 = OpUMod %194 %243 %244 +%246 = OpCompositeConstruct %26 %14 %14 %14 %14 +%247 = OpCompositeConstruct %26 %3 %3 %3 %3 +%248 = OpFRem %26 %246 %247 +%249 = OpCompositeConstruct %183 %18 %18 +%250 = OpCompositeConstruct %183 %7 %7 +%251 = OpIAdd %183 %249 %250 +%252 = OpCompositeConstruct %183 %7 %7 +%253 = OpCompositeConstruct %183 %18 %18 +%254 = OpIAdd %183 %253 %252 %255 = OpCompositeConstruct %34 %24 %24 %256 = OpCompositeConstruct %34 %25 %25 -%257 = OpISub %34 %255 %256 +%257 = OpIAdd %34 %255 %256 %258 = OpCompositeConstruct %34 %25 %25 %259 = OpCompositeConstruct %34 %24 %24 -%260 = OpISub %34 %259 %258 -%261 = OpCompositeConstruct %31 %14 %14 -%262 = OpCompositeConstruct %31 %3 %3 -%263 = OpFSub %31 %261 %262 -%264 = OpCompositeConstruct %31 %3 %3 -%265 = OpCompositeConstruct %31 %14 %14 -%266 = OpFSub %31 %265 %264 -%267 = OpCompositeConstruct %165 %18 %18 -%269 = OpCompositeConstruct %165 %7 %7 -%268 = OpIMul %165 %267 %269 -%270 = OpCompositeConstruct %165 %7 %7 -%272 = OpCompositeConstruct %165 %18 %18 -%271 = OpIMul %165 %270 %272 +%260 = OpIAdd %34 %259 %258 +%261 = OpCompositeConstruct %29 %14 %14 +%262 = OpCompositeConstruct %29 %3 %3 +%263 = OpFAdd %29 %261 %262 +%264 = OpCompositeConstruct %29 %3 %3 +%265 = OpCompositeConstruct %29 %14 %14 +%266 = OpFAdd %29 %265 %264 +%267 = OpCompositeConstruct %183 %18 %18 +%268 = OpCompositeConstruct %183 %7 %7 +%269 = OpISub %183 %267 %268 +%270 = OpCompositeConstruct %183 %7 %7 +%271 = OpCompositeConstruct %183 %18 %18 +%272 = OpISub %183 %271 %270 %273 = OpCompositeConstruct %34 %24 %24 -%275 = OpCompositeConstruct %34 %25 %25 -%274 = OpIMul %34 %273 %275 +%274 = OpCompositeConstruct %34 %25 %25 +%275 = OpISub %34 %273 %274 %276 = OpCompositeConstruct %34 %25 %25 -%278 = OpCompositeConstruct %34 %24 %24 -%277 = OpIMul %34 %276 %278 -%279 = OpCompositeConstruct %31 %14 %14 -%280 = OpVectorTimesScalar %31 %279 %3 -%281 = OpCompositeConstruct %31 %3 %3 -%282 = OpVectorTimesScalar %31 %281 %14 -%283 = OpCompositeConstruct %165 %18 %18 -%284 = OpCompositeConstruct %165 %7 %7 -%285 = OpSDiv %165 %283 %284 -%286 = OpCompositeConstruct %165 %7 %7 -%287 = OpCompositeConstruct %165 %18 %18 -%288 = OpSDiv %165 %287 %286 -%289 = OpCompositeConstruct %34 %24 %24 -%290 = OpCompositeConstruct %34 %25 %25 -%291 = OpUDiv %34 %289 %290 -%292 = OpCompositeConstruct %34 %25 %25 -%293 = OpCompositeConstruct %34 %24 %24 -%294 = OpUDiv %34 %293 %292 -%295 = OpCompositeConstruct %31 %14 %14 -%296 = OpCompositeConstruct %31 %3 %3 -%297 = OpFDiv %31 %295 %296 -%298 = OpCompositeConstruct %31 %3 %3 -%299 = OpCompositeConstruct %31 %14 %14 -%300 = OpFDiv %31 %299 %298 -%301 = OpCompositeConstruct %165 %18 %18 -%302 = OpCompositeConstruct %165 %7 %7 -%303 = OpSRem %165 %301 %302 -%304 = OpCompositeConstruct %165 %7 %7 -%305 = OpCompositeConstruct %165 %18 %18 -%306 = OpSRem %165 %305 %304 +%277 = OpCompositeConstruct %34 %24 %24 +%278 = OpISub %34 %277 %276 +%279 = OpCompositeConstruct %29 %14 %14 +%280 = OpCompositeConstruct %29 %3 %3 +%281 = OpFSub %29 %279 %280 +%282 = OpCompositeConstruct %29 %3 %3 +%283 = OpCompositeConstruct %29 %14 %14 +%284 = OpFSub %29 %283 %282 +%285 = OpCompositeConstruct %183 %18 %18 +%287 = OpCompositeConstruct %183 %7 %7 +%286 = OpIMul %183 %285 %287 +%288 = OpCompositeConstruct %183 %7 %7 +%290 = OpCompositeConstruct %183 %18 %18 +%289 = OpIMul %183 %288 %290 +%291 = OpCompositeConstruct %34 %24 %24 +%293 = OpCompositeConstruct %34 %25 %25 +%292 = OpIMul %34 %291 %293 +%294 = OpCompositeConstruct %34 %25 %25 +%296 = OpCompositeConstruct %34 %24 %24 +%295 = OpIMul %34 %294 %296 +%297 = OpCompositeConstruct %29 %14 %14 +%298 = OpVectorTimesScalar %29 %297 %3 +%299 = OpCompositeConstruct %29 %3 %3 +%300 = OpVectorTimesScalar %29 %299 %14 +%301 = OpCompositeConstruct %183 %18 %18 +%302 = OpCompositeConstruct %183 %7 %7 +%303 = OpSDiv %183 %301 %302 +%304 = OpCompositeConstruct %183 %7 %7 +%305 = OpCompositeConstruct %183 %18 %18 +%306 = OpSDiv %183 %305 %304 %307 = OpCompositeConstruct %34 %24 %24 %308 = OpCompositeConstruct %34 %25 %25 -%309 = OpUMod %34 %307 %308 +%309 = OpUDiv %34 %307 %308 %310 = OpCompositeConstruct %34 %25 %25 %311 = OpCompositeConstruct %34 %24 %24 -%312 = OpUMod %34 %311 %310 -%313 = OpCompositeConstruct %31 %14 %14 -%314 = OpCompositeConstruct %31 %3 %3 -%315 = OpFRem %31 %313 %314 -%316 = OpCompositeConstruct %31 %3 %3 -%317 = OpCompositeConstruct %31 %14 %14 -%318 = OpFRem %31 %317 %316 -%320 = OpCompositeExtract %29 %54 0 -%321 = OpCompositeExtract %29 %54 0 -%322 = OpFAdd %29 %320 %321 -%323 = OpCompositeExtract %29 %54 1 -%324 = OpCompositeExtract %29 %54 1 -%325 = OpFAdd %29 %323 %324 -%326 = OpCompositeExtract %29 %54 2 -%327 = OpCompositeExtract %29 %54 2 -%328 = OpFAdd %29 %326 %327 -%319 = OpCompositeConstruct %38 %322 %325 %328 -%330 = OpCompositeExtract %29 %54 0 -%331 = OpCompositeExtract %29 %54 0 -%332 = OpFSub %29 %330 %331 -%333 = OpCompositeExtract %29 %54 1 -%334 = OpCompositeExtract %29 %54 1 -%335 = OpFSub %29 %333 %334 -%336 = OpCompositeExtract %29 %54 2 -%337 = OpCompositeExtract %29 %54 2 -%338 = OpFSub %29 %336 %337 -%329 = OpCompositeConstruct %38 %332 %335 %338 -%339 = OpMatrixTimesScalar %38 %54 %3 -%340 = OpMatrixTimesScalar %38 %54 %14 -%341 = OpCompositeConstruct %26 %3 %3 %3 %3 -%342 = OpMatrixTimesVector %29 %55 %341 -%343 = OpCompositeConstruct %29 %14 %14 %14 -%344 = OpVectorTimesMatrix %26 %343 %55 -%345 = OpMatrixTimesMatrix %38 %55 %56 +%312 = OpUDiv %34 %311 %310 +%313 = OpCompositeConstruct %29 %14 %14 +%314 = OpCompositeConstruct %29 %3 %3 +%315 = OpFDiv %29 %313 %314 +%316 = OpCompositeConstruct %29 %3 %3 +%317 = OpCompositeConstruct %29 %14 %14 +%318 = OpFDiv %29 %317 %316 +%319 = OpCompositeConstruct %183 %18 %18 +%320 = OpCompositeConstruct %183 %7 %7 +%321 = OpSRem %183 %319 %320 +%322 = OpCompositeConstruct %183 %7 %7 +%323 = OpCompositeConstruct %183 %18 %18 +%324 = OpSRem %183 %323 %322 +%325 = OpCompositeConstruct %34 %24 %24 +%326 = OpCompositeConstruct %34 %25 %25 +%327 = OpUMod %34 %325 %326 +%328 = OpCompositeConstruct %34 %25 %25 +%329 = OpCompositeConstruct %34 %24 %24 +%330 = OpUMod %34 %329 %328 +%331 = OpCompositeConstruct %29 %14 %14 +%332 = OpCompositeConstruct %29 %3 %3 +%333 = OpFRem %29 %331 %332 +%334 = OpCompositeConstruct %29 %3 %3 +%335 = OpCompositeConstruct %29 %14 %14 +%336 = OpFRem %29 %335 %334 +%338 = OpCompositeExtract %30 %54 0 +%339 = OpCompositeExtract %30 %54 0 +%340 = OpFAdd %30 %338 %339 +%341 = OpCompositeExtract %30 %54 1 +%342 = OpCompositeExtract %30 %54 1 +%343 = OpFAdd %30 %341 %342 +%344 = OpCompositeExtract %30 %54 2 +%345 = OpCompositeExtract %30 %54 2 +%346 = OpFAdd %30 %344 %345 +%337 = OpCompositeConstruct %38 %340 %343 %346 +%348 = OpCompositeExtract %30 %54 0 +%349 = OpCompositeExtract %30 %54 0 +%350 = OpFSub %30 %348 %349 +%351 = OpCompositeExtract %30 %54 1 +%352 = OpCompositeExtract %30 %54 1 +%353 = OpFSub %30 %351 %352 +%354 = OpCompositeExtract %30 %54 2 +%355 = OpCompositeExtract %30 %54 2 +%356 = OpFSub %30 %354 %355 +%347 = OpCompositeConstruct %38 %350 %353 %356 +%357 = OpMatrixTimesScalar %38 %54 %3 +%358 = OpMatrixTimesScalar %38 %54 %14 +%359 = OpCompositeConstruct %26 %3 %3 %3 %3 +%360 = OpMatrixTimesVector %30 %55 %359 +%361 = OpCompositeConstruct %30 %14 %14 %14 +%362 = OpVectorTimesMatrix %26 %361 %55 +%363 = OpMatrixTimesMatrix %38 %55 %56 OpReturn OpFunctionEnd -%347 = OpFunction %2 None %146 -%346 = OpLabel -OpBranch %348 -%348 = OpLabel -%349 = OpNot %8 %7 -%350 = OpNot %20 %25 -%351 = OpCompositeConstruct %165 %7 %7 -%352 = OpNot %165 %351 -%353 = OpCompositeConstruct %176 %25 %25 %25 -%354 = OpNot %176 %353 -%355 = OpBitwiseOr %8 %18 %7 -%356 = OpBitwiseOr %20 %24 %25 -%357 = OpCompositeConstruct %165 %18 %18 -%358 = OpCompositeConstruct %165 %7 %7 -%359 = OpBitwiseOr %165 %357 %358 -%360 = OpCompositeConstruct %176 %24 %24 %24 -%361 = OpCompositeConstruct %176 %25 %25 %25 -%362 = OpBitwiseOr %176 %360 %361 -%363 = OpBitwiseAnd %8 %18 %7 -%364 = OpBitwiseAnd %20 %24 %25 -%365 = OpCompositeConstruct %165 %18 %18 -%366 = OpCompositeConstruct %165 %7 %7 -%367 = OpBitwiseAnd %165 %365 %366 -%368 = OpCompositeConstruct %176 %24 %24 %24 -%369 = OpCompositeConstruct %176 %25 %25 %25 -%370 = OpBitwiseAnd %176 %368 %369 -%371 = OpBitwiseXor %8 %18 %7 -%372 = OpBitwiseXor %20 %24 %25 -%373 = OpCompositeConstruct %165 %18 %18 -%374 = OpCompositeConstruct %165 %7 %7 -%375 = OpBitwiseXor %165 %373 %374 -%376 = OpCompositeConstruct %176 %24 %24 %24 -%377 = OpCompositeConstruct %176 %25 %25 %25 -%378 = OpBitwiseXor %176 %376 %377 -%379 = OpShiftLeftLogical %8 %18 %25 -%380 = OpShiftLeftLogical %20 %24 %25 -%381 = OpCompositeConstruct %165 %18 %18 -%382 = OpCompositeConstruct %34 %25 %25 -%383 = OpShiftLeftLogical %165 %381 %382 -%384 = OpCompositeConstruct %176 %24 %24 %24 -%385 = OpCompositeConstruct %176 %25 %25 %25 -%386 = OpShiftLeftLogical %176 %384 %385 -%387 = OpShiftRightArithmetic %8 %18 %25 -%388 = OpShiftRightLogical %20 %24 %25 -%389 = OpCompositeConstruct %165 %18 %18 -%390 = OpCompositeConstruct %34 %25 %25 -%391 = OpShiftRightArithmetic %165 %389 %390 -%392 = OpCompositeConstruct %176 %24 %24 %24 -%393 = OpCompositeConstruct %176 %25 %25 %25 -%394 = OpShiftRightLogical %176 %392 %393 +%365 = OpFunction %2 None %164 +%364 = OpLabel +OpBranch %366 +%366 = OpLabel +%367 = OpNot %8 %7 +%368 = OpNot %20 %25 +%369 = OpCompositeConstruct %183 %7 %7 +%370 = OpNot %183 %369 +%371 = OpCompositeConstruct %194 %25 %25 %25 +%372 = OpNot %194 %371 +%373 = OpBitwiseOr %8 %18 %7 +%374 = OpBitwiseOr %20 %24 %25 +%375 = OpCompositeConstruct %183 %18 %18 +%376 = OpCompositeConstruct %183 %7 %7 +%377 = OpBitwiseOr %183 %375 %376 +%378 = OpCompositeConstruct %194 %24 %24 %24 +%379 = OpCompositeConstruct %194 %25 %25 %25 +%380 = OpBitwiseOr %194 %378 %379 +%381 = OpBitwiseAnd %8 %18 %7 +%382 = OpBitwiseAnd %20 %24 %25 +%383 = OpCompositeConstruct %183 %18 %18 +%384 = OpCompositeConstruct %183 %7 %7 +%385 = OpBitwiseAnd %183 %383 %384 +%386 = OpCompositeConstruct %194 %24 %24 %24 +%387 = OpCompositeConstruct %194 %25 %25 %25 +%388 = OpBitwiseAnd %194 %386 %387 +%389 = OpBitwiseXor %8 %18 %7 +%390 = OpBitwiseXor %20 %24 %25 +%391 = OpCompositeConstruct %183 %18 %18 +%392 = OpCompositeConstruct %183 %7 %7 +%393 = OpBitwiseXor %183 %391 %392 +%394 = OpCompositeConstruct %194 %24 %24 %24 +%395 = OpCompositeConstruct %194 %25 %25 %25 +%396 = OpBitwiseXor %194 %394 %395 +%397 = OpShiftLeftLogical %8 %18 %25 +%398 = OpShiftLeftLogical %20 %24 %25 +%399 = OpCompositeConstruct %183 %18 %18 +%400 = OpCompositeConstruct %34 %25 %25 +%401 = OpShiftLeftLogical %183 %399 %400 +%402 = OpCompositeConstruct %194 %24 %24 %24 +%403 = OpCompositeConstruct %194 %25 %25 %25 +%404 = OpShiftLeftLogical %194 %402 %403 +%405 = OpShiftRightArithmetic %8 %18 %25 +%406 = OpShiftRightLogical %20 %24 %25 +%407 = OpCompositeConstruct %183 %18 %18 +%408 = OpCompositeConstruct %34 %25 %25 +%409 = OpShiftRightArithmetic %183 %407 %408 +%410 = OpCompositeConstruct %194 %24 %24 %24 +%411 = OpCompositeConstruct %194 %25 %25 %25 +%412 = OpShiftRightLogical %194 %410 %411 OpReturn OpFunctionEnd -%396 = OpFunction %2 None %146 -%395 = OpLabel -OpBranch %397 -%397 = OpLabel -%398 = OpIEqual %10 %18 %7 -%399 = OpIEqual %10 %24 %25 -%400 = OpFOrdEqual %10 %14 %3 -%401 = OpCompositeConstruct %165 %18 %18 -%402 = OpCompositeConstruct %165 %7 %7 -%403 = OpIEqual %149 %401 %402 -%404 = OpCompositeConstruct %176 %24 %24 %24 -%405 = OpCompositeConstruct %176 %25 %25 %25 -%406 = OpIEqual %104 %404 %405 -%407 = OpCompositeConstruct %26 %14 %14 %14 %14 -%408 = OpCompositeConstruct %26 %3 %3 %3 %3 -%409 = OpFOrdEqual %28 %407 %408 -%410 = OpINotEqual %10 %18 %7 -%411 = OpINotEqual %10 %24 %25 -%412 = OpFOrdNotEqual %10 %14 %3 -%413 = OpCompositeConstruct %165 %18 %18 -%414 = OpCompositeConstruct %165 %7 %7 -%415 = OpINotEqual %149 %413 %414 -%416 = OpCompositeConstruct %176 %24 %24 %24 -%417 = OpCompositeConstruct %176 %25 %25 %25 -%418 = OpINotEqual %104 %416 %417 -%419 = OpCompositeConstruct %26 %14 %14 %14 %14 -%420 = OpCompositeConstruct %26 %3 %3 %3 %3 -%421 = OpFOrdNotEqual %28 %419 %420 -%422 = OpSLessThan %10 %18 %7 -%423 = OpULessThan %10 %24 %25 -%424 = OpFOrdLessThan %10 %14 %3 -%425 = OpCompositeConstruct %165 %18 %18 -%426 = OpCompositeConstruct %165 %7 %7 -%427 = OpSLessThan %149 %425 %426 -%428 = OpCompositeConstruct %176 %24 %24 %24 -%429 = OpCompositeConstruct %176 %25 %25 %25 -%430 = OpULessThan %104 %428 %429 -%431 = OpCompositeConstruct %26 %14 %14 %14 %14 -%432 = OpCompositeConstruct %26 %3 %3 %3 %3 -%433 = OpFOrdLessThan %28 %431 %432 -%434 = OpSLessThanEqual %10 %18 %7 -%435 = OpULessThanEqual %10 %24 %25 -%436 = OpFOrdLessThanEqual %10 %14 %3 -%437 = OpCompositeConstruct %165 %18 %18 -%438 = OpCompositeConstruct %165 %7 %7 -%439 = OpSLessThanEqual %149 %437 %438 -%440 = OpCompositeConstruct %176 %24 %24 %24 -%441 = OpCompositeConstruct %176 %25 %25 %25 -%442 = OpULessThanEqual %104 %440 %441 -%443 = OpCompositeConstruct %26 %14 %14 %14 %14 -%444 = OpCompositeConstruct %26 %3 %3 %3 %3 -%445 = OpFOrdLessThanEqual %28 %443 %444 -%446 = OpSGreaterThan %10 %18 %7 -%447 = OpUGreaterThan %10 %24 %25 -%448 = OpFOrdGreaterThan %10 %14 %3 -%449 = OpCompositeConstruct %165 %18 %18 -%450 = OpCompositeConstruct %165 %7 %7 -%451 = OpSGreaterThan %149 %449 %450 -%452 = OpCompositeConstruct %176 %24 %24 %24 -%453 = OpCompositeConstruct %176 %25 %25 %25 -%454 = OpUGreaterThan %104 %452 %453 -%455 = OpCompositeConstruct %26 %14 %14 %14 %14 -%456 = OpCompositeConstruct %26 %3 %3 %3 %3 -%457 = OpFOrdGreaterThan %28 %455 %456 -%458 = OpSGreaterThanEqual %10 %18 %7 -%459 = OpUGreaterThanEqual %10 %24 %25 -%460 = OpFOrdGreaterThanEqual %10 %14 %3 -%461 = OpCompositeConstruct %165 %18 %18 -%462 = OpCompositeConstruct %165 %7 %7 -%463 = OpSGreaterThanEqual %149 %461 %462 -%464 = OpCompositeConstruct %176 %24 %24 %24 -%465 = OpCompositeConstruct %176 %25 %25 %25 -%466 = OpUGreaterThanEqual %104 %464 %465 -%467 = OpCompositeConstruct %26 %14 %14 %14 %14 -%468 = OpCompositeConstruct %26 %3 %3 %3 %3 -%469 = OpFOrdGreaterThanEqual %28 %467 %468 +%414 = OpFunction %2 None %164 +%413 = OpLabel +OpBranch %415 +%415 = OpLabel +%416 = OpIEqual %10 %18 %7 +%417 = OpIEqual %10 %24 %25 +%418 = OpFOrdEqual %10 %14 %3 +%419 = OpCompositeConstruct %183 %18 %18 +%420 = OpCompositeConstruct %183 %7 %7 +%421 = OpIEqual %167 %419 %420 +%422 = OpCompositeConstruct %194 %24 %24 %24 +%423 = OpCompositeConstruct %194 %25 %25 %25 +%424 = OpIEqual %122 %422 %423 +%425 = OpCompositeConstruct %26 %14 %14 %14 %14 +%426 = OpCompositeConstruct %26 %3 %3 %3 %3 +%427 = OpFOrdEqual %28 %425 %426 +%428 = OpINotEqual %10 %18 %7 +%429 = OpINotEqual %10 %24 %25 +%430 = OpFOrdNotEqual %10 %14 %3 +%431 = OpCompositeConstruct %183 %18 %18 +%432 = OpCompositeConstruct %183 %7 %7 +%433 = OpINotEqual %167 %431 %432 +%434 = OpCompositeConstruct %194 %24 %24 %24 +%435 = OpCompositeConstruct %194 %25 %25 %25 +%436 = OpINotEqual %122 %434 %435 +%437 = OpCompositeConstruct %26 %14 %14 %14 %14 +%438 = OpCompositeConstruct %26 %3 %3 %3 %3 +%439 = OpFOrdNotEqual %28 %437 %438 +%440 = OpSLessThan %10 %18 %7 +%441 = OpULessThan %10 %24 %25 +%442 = OpFOrdLessThan %10 %14 %3 +%443 = OpCompositeConstruct %183 %18 %18 +%444 = OpCompositeConstruct %183 %7 %7 +%445 = OpSLessThan %167 %443 %444 +%446 = OpCompositeConstruct %194 %24 %24 %24 +%447 = OpCompositeConstruct %194 %25 %25 %25 +%448 = OpULessThan %122 %446 %447 +%449 = OpCompositeConstruct %26 %14 %14 %14 %14 +%450 = OpCompositeConstruct %26 %3 %3 %3 %3 +%451 = OpFOrdLessThan %28 %449 %450 +%452 = OpSLessThanEqual %10 %18 %7 +%453 = OpULessThanEqual %10 %24 %25 +%454 = OpFOrdLessThanEqual %10 %14 %3 +%455 = OpCompositeConstruct %183 %18 %18 +%456 = OpCompositeConstruct %183 %7 %7 +%457 = OpSLessThanEqual %167 %455 %456 +%458 = OpCompositeConstruct %194 %24 %24 %24 +%459 = OpCompositeConstruct %194 %25 %25 %25 +%460 = OpULessThanEqual %122 %458 %459 +%461 = OpCompositeConstruct %26 %14 %14 %14 %14 +%462 = OpCompositeConstruct %26 %3 %3 %3 %3 +%463 = OpFOrdLessThanEqual %28 %461 %462 +%464 = OpSGreaterThan %10 %18 %7 +%465 = OpUGreaterThan %10 %24 %25 +%466 = OpFOrdGreaterThan %10 %14 %3 +%467 = OpCompositeConstruct %183 %18 %18 +%468 = OpCompositeConstruct %183 %7 %7 +%469 = OpSGreaterThan %167 %467 %468 +%470 = OpCompositeConstruct %194 %24 %24 %24 +%471 = OpCompositeConstruct %194 %25 %25 %25 +%472 = OpUGreaterThan %122 %470 %471 +%473 = OpCompositeConstruct %26 %14 %14 %14 %14 +%474 = OpCompositeConstruct %26 %3 %3 %3 %3 +%475 = OpFOrdGreaterThan %28 %473 %474 +%476 = OpSGreaterThanEqual %10 %18 %7 +%477 = OpUGreaterThanEqual %10 %24 %25 +%478 = OpFOrdGreaterThanEqual %10 %14 %3 +%479 = OpCompositeConstruct %183 %18 %18 +%480 = OpCompositeConstruct %183 %7 %7 +%481 = OpSGreaterThanEqual %167 %479 %480 +%482 = OpCompositeConstruct %194 %24 %24 %24 +%483 = OpCompositeConstruct %194 %25 %25 %25 +%484 = OpUGreaterThanEqual %122 %482 %483 +%485 = OpCompositeConstruct %26 %14 %14 %14 %14 +%486 = OpCompositeConstruct %26 %3 %3 %3 %3 +%487 = OpFOrdGreaterThanEqual %28 %485 %486 OpReturn OpFunctionEnd -%475 = OpFunction %2 None %146 -%474 = OpLabel -%470 = OpVariable %471 Function %7 -%472 = OpVariable %473 Function %57 -OpBranch %476 -%476 = OpLabel -%477 = OpLoad %8 %470 -%478 = OpIAdd %8 %477 %7 -OpStore %470 %478 -%479 = OpLoad %8 %470 -%480 = OpISub %8 %479 %7 -OpStore %470 %480 -%481 = OpLoad %8 %470 -%482 = OpLoad %8 %470 -%483 = OpIMul %8 %481 %482 -OpStore %470 %483 -%484 = OpLoad %8 %470 -%485 = OpLoad %8 %470 -%486 = OpSDiv %8 %484 %485 -OpStore %470 %486 -%487 = OpLoad %8 %470 -%488 = OpSRem %8 %487 %7 -OpStore %470 %488 -%489 = OpLoad %8 %470 -%490 = OpBitwiseAnd %8 %489 %11 -OpStore %470 %490 -%491 = OpLoad %8 %470 -%492 = OpBitwiseOr %8 %491 %11 -OpStore %470 %492 -%493 = OpLoad %8 %470 -%494 = OpBitwiseXor %8 %493 %11 -OpStore %470 %494 -%495 = OpLoad %8 %470 -%496 = OpShiftLeftLogical %8 %495 %24 -OpStore %470 %496 -%497 = OpLoad %8 %470 -%498 = OpShiftRightArithmetic %8 %497 %25 -OpStore %470 %498 -%499 = OpLoad %8 %470 -%500 = OpIAdd %8 %499 %7 -OpStore %470 %500 -%501 = OpLoad %8 %470 -%502 = OpISub %8 %501 %7 -OpStore %470 %502 -%504 = OpAccessChain %503 %472 %25 -%505 = OpLoad %8 %504 -%506 = OpIAdd %8 %505 %7 -%507 = OpAccessChain %503 %472 %25 -OpStore %507 %506 -%508 = OpAccessChain %503 %472 %25 -%509 = OpLoad %8 %508 -%510 = OpISub %8 %509 %7 -%511 = OpAccessChain %503 %472 %25 -OpStore %511 %510 +%493 = OpFunction %2 None %164 +%492 = OpLabel +%488 = OpVariable %489 Function %7 +%490 = OpVariable %491 Function %57 +OpBranch %494 +%494 = OpLabel +%495 = OpLoad %8 %488 +%496 = OpIAdd %8 %495 %7 +OpStore %488 %496 +%497 = OpLoad %8 %488 +%498 = OpISub %8 %497 %7 +OpStore %488 %498 +%499 = OpLoad %8 %488 +%500 = OpLoad %8 %488 +%501 = OpIMul %8 %499 %500 +OpStore %488 %501 +%502 = OpLoad %8 %488 +%503 = OpLoad %8 %488 +%504 = OpSDiv %8 %502 %503 +OpStore %488 %504 +%505 = OpLoad %8 %488 +%506 = OpSRem %8 %505 %7 +OpStore %488 %506 +%507 = OpLoad %8 %488 +%508 = OpBitwiseAnd %8 %507 %11 +OpStore %488 %508 +%509 = OpLoad %8 %488 +%510 = OpBitwiseOr %8 %509 %11 +OpStore %488 %510 +%511 = OpLoad %8 %488 +%512 = OpBitwiseXor %8 %511 %11 +OpStore %488 %512 +%513 = OpLoad %8 %488 +%514 = OpShiftLeftLogical %8 %513 %24 +OpStore %488 %514 +%515 = OpLoad %8 %488 +%516 = OpShiftRightArithmetic %8 %515 %25 +OpStore %488 %516 +%517 = OpLoad %8 %488 +%518 = OpIAdd %8 %517 %7 +OpStore %488 %518 +%519 = OpLoad %8 %488 +%520 = OpISub %8 %519 %7 +OpStore %488 %520 +%522 = OpAccessChain %521 %490 %25 +%523 = OpLoad %8 %522 +%524 = OpIAdd %8 %523 %7 +%525 = OpAccessChain %521 %490 %25 +OpStore %525 %524 +%526 = OpAccessChain %521 %490 %25 +%527 = OpLoad %8 %526 +%528 = OpISub %8 %527 %7 +%529 = OpAccessChain %521 %490 %25 +OpStore %529 %528 OpReturn OpFunctionEnd -%513 = OpFunction %2 None %146 -%512 = OpLabel -OpBranch %514 -%514 = OpLabel -%515 = OpFunctionCall %26 %59 -%516 = OpFunctionCall %26 %84 -%517 = OpVectorShuffle %29 %42 %42 0 1 2 -%518 = OpFunctionCall %29 %101 %517 -%519 = OpFunctionCall %4 %114 -%520 = OpFunctionCall %2 %145 -%521 = OpFunctionCall %2 %163 -%522 = OpFunctionCall %2 %347 -%523 = OpFunctionCall %2 %396 -%524 = OpFunctionCall %2 %475 +%531 = OpFunction %2 None %164 +%530 = OpLabel +OpBranch %532 +%532 = OpLabel +%533 = OpFunctionCall %26 %59 +%534 = OpFunctionCall %26 %84 +%535 = OpVectorShuffle %30 %42 %42 0 1 2 +%536 = OpFunctionCall %30 %119 %535 +%537 = OpFunctionCall %4 %132 +%538 = OpFunctionCall %2 %163 +%539 = OpFunctionCall %2 %181 +%540 = OpFunctionCall %2 %365 +%541 = OpFunctionCall %2 %414 +%542 = OpFunctionCall %2 %493 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 2aa21785e..a8a488dff 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -20,9 +20,23 @@ fn builtins() -> vec4 { } fn splat() -> vec4 { - let a_1 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + let a_2 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); let b = (vec4(5) % vec4(2)); - return (a_1.xyxy + vec4(b)); + return (a_2.xyxy + vec4(b)); +} + +fn splat_assignment() -> vec2 { + var a: vec2; + + a = vec2(2.0); + let _e7 = a; + a = (_e7 + vec2(1.0)); + let _e11 = a; + a = (_e11 - vec2(3.0)); + let _e15 = a; + a = (_e15 / vec2(4.0)); + let _e19 = a; + return _e19; } fn bool_cast(x: vec3) -> vec3 { @@ -201,35 +215,35 @@ fn comparison() { } fn assignment() { - var a: i32 = 1; + var a_1: i32 = 1; var vec0_: vec3 = vec3(0, 0, 0); - let _e6 = a; - a = (_e6 + 1); - let _e9 = a; - a = (_e9 - 1); - let _e12 = a; - let _e13 = a; - a = (_e12 * _e13); - let _e15 = a; - let _e16 = a; - a = (_e15 / _e16); - let _e18 = a; - a = (_e18 % 1); - let _e21 = a; - a = (_e21 & 0); - let _e24 = a; - a = (_e24 | 0); - let _e27 = a; - a = (_e27 ^ 0); - let _e30 = a; - a = (_e30 << 2u); - let _e33 = a; - a = (_e33 >> 1u); - let _e36 = a; - a = (_e36 + 1); - let _e39 = a; - a = (_e39 - 1); + let _e6 = a_1; + a_1 = (_e6 + 1); + let _e9 = a_1; + a_1 = (_e9 - 1); + let _e12 = a_1; + let _e13 = a_1; + a_1 = (_e12 * _e13); + let _e15 = a_1; + let _e16 = a_1; + a_1 = (_e15 / _e16); + let _e18 = a_1; + a_1 = (_e18 % 1); + let _e21 = a_1; + a_1 = (_e21 & 0); + let _e24 = a_1; + a_1 = (_e24 | 0); + let _e27 = a_1; + a_1 = (_e27 ^ 0); + let _e30 = a_1; + a_1 = (_e30 << 2u); + let _e33 = a_1; + a_1 = (_e33 >> 1u); + let _e36 = a_1; + a_1 = (_e36 + 1); + let _e39 = a_1; + a_1 = (_e39 - 1); let _e46 = vec0_.y; vec0_.y = (_e46 + 1); let _e51 = vec0_.y; From ff69053bf28857c6f00aedbe044ce144f96c7c1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 7 Sep 2022 23:34:39 +0100 Subject: [PATCH 1828/2212] valid: Check regular functions don't have bindings Checks that all arguments and return types have no bindings in regular functions. --- src/valid/function.rs | 17 +++++++++++++++++ src/valid/interface.rs | 2 +- src/valid/mod.rs | 2 +- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 67903601c..db66a0f6c 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -143,6 +143,10 @@ pub enum FunctionError { Handle, UniformityDisruptor, ), + #[error("Functions that are not entry points cannot have `@location` or `@builtin` attributes on their arguments: \"{name}\" has attributes")] + PipelineInputRegularFunction { name: String }, + #[error("Functions that are not entry points cannot have `@location` or `@builtin` attributes on their return value types")] + PipelineOutputRegularFunction, } bitflags::bitflags! { @@ -859,6 +863,7 @@ impl super::Validator { fun: &crate::Function, module: &crate::Module, mod_info: &ModuleInfo, + entry_point: bool, ) -> Result> { #[cfg_attr(not(feature = "validate"), allow(unused_mut))] let mut info = mod_info.process_function(fun, module, self.flags, self.capabilities)?; @@ -909,6 +914,13 @@ impl super::Validator { } .with_span_handle(argument.ty, &module.types)); } + + if !entry_point && argument.binding.is_some() { + return Err(FunctionError::PipelineInputRegularFunction { + name: argument.name.clone().unwrap_or_default(), + } + .with_span_handle(argument.ty, &module.types)); + } } #[cfg(feature = "validate")] @@ -920,6 +932,11 @@ impl super::Validator { return Err(FunctionError::NonConstructibleReturnType .with_span_handle(result.ty, &module.types)); } + + if !entry_point && result.binding.is_some() { + return Err(FunctionError::PipelineOutputRegularFunction + .with_span_handle(result.ty, &module.types)); + } } self.valid_expression_set.clear(); diff --git a/src/valid/interface.rs b/src/valid/interface.rs index bee57e877..072550e9b 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -472,7 +472,7 @@ impl super::Validator { } let info = self - .validate_function(&ep.function, module, mod_info) + .validate_function(&ep.function, module, mod_info, true) .map_err(WithSpan::into_other)?; #[cfg(feature = "validate")] diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 60178bb47..b746f6abd 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -373,7 +373,7 @@ impl Validator { }; for (handle, fun) in module.functions.iter() { - match self.validate_function(fun, module, &mod_info) { + match self.validate_function(fun, module, &mod_info, false) { Ok(info) => mod_info.functions.push(info), Err(error) => { return Err(error.and_then(|error| { From 1a99c1cf066de8d660904f1fb681f5647bc45205 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sat, 10 Sep 2022 22:05:24 +0100 Subject: [PATCH 1829/2212] wgsl-in: Fix bad span in assignment lhs error The wgsl frontend was emiting errors for lhs expressions on assignments that weren't references using a span that didn't skip blankspaces causing the span to look weird (like starting at the end of the previous line) This is fixed by consuming the blankspace before constructing the span --- src/front/wgsl/lexer.rs | 16 ++++++++++++++++ src/front/wgsl/mod.rs | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 1d019e94f..ed5bb6998 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -237,6 +237,22 @@ impl<'a> Lexer<'a> { } } + /// Consumes [`Trivia`] tokens until another token is encountered, returns + /// the byte offset after consuming the tokens. + /// + /// [`Trivia`]: Token::Trivia + #[must_use] + pub(super) fn consume_blankspace(&mut self) -> usize { + loop { + let (token, rest) = consume_token(self.input, false); + if let Token::Trivia = token { + self.input = rest; + } else { + return self.current_byte_offset(); + } + } + } + #[must_use] pub(super) fn peek(&mut self) -> TokenSpan<'a> { let (token, _) = self.peek_token_and_rest(); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6e600ba59..9f5cfe5da 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3304,7 +3304,7 @@ impl Parser { ) -> Result<(), Error<'a>> { use crate::BinaryOperator as Bo; - let span_start = lexer.current_byte_offset(); + let span_start = lexer.consume_blankspace(); context.emitter.start(context.expressions); let reference = self.parse_unary_expression(lexer, context.reborrow())?; // The left hand side of an assignment must be a reference. From 5d9cdd361f06c5d080815720c26314f3fa0b4f9b Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Tue, 13 Sep 2022 23:23:14 +0530 Subject: [PATCH 1830/2212] fix inclusion of trivia in spans --- src/front/wgsl/lexer.rs | 34 +++++++++++++++++----------------- src/front/wgsl/mod.rs | 32 ++++++++++++++++---------------- tests/wgsl-errors.rs | 18 +++++++++--------- 3 files changed, 42 insertions(+), 42 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index ed5bb6998..df726e417 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -196,6 +196,22 @@ impl<'a> Lexer<'a> { Ok((res, start..end)) } + pub(super) fn start_byte_offset(&mut self) -> usize { + loop { + // Eat all trivia becuase `next` doesn't eat trailing trivia. + let (token, rest) = consume_token(self.input, false); + if let Token::Trivia = token { + self.input = rest; + } else { + return self.current_byte_offset(); + } + } + } + + pub(super) const fn end_byte_offset(&self) -> usize { + self.current_byte_offset() + } + fn peek_token_and_rest(&mut self) -> (TokenSpan<'a>, &'a str) { let mut cloned = self.clone(); let token = cloned.next(); @@ -203,7 +219,7 @@ impl<'a> Lexer<'a> { (token, rest) } - pub(super) const fn current_byte_offset(&self) -> usize { + const fn current_byte_offset(&self) -> usize { self.source.len() - self.input.len() } @@ -237,22 +253,6 @@ impl<'a> Lexer<'a> { } } - /// Consumes [`Trivia`] tokens until another token is encountered, returns - /// the byte offset after consuming the tokens. - /// - /// [`Trivia`]: Token::Trivia - #[must_use] - pub(super) fn consume_blankspace(&mut self) -> usize { - loop { - let (token, rest) = consume_token(self.input, false); - if let Token::Trivia = token { - self.input = rest; - } else { - return self.current_byte_offset(); - } - } - } - #[must_use] pub(super) fn peek(&mut self) -> TokenSpan<'a> { let (token, _) = self.peek_token_and_rest(); diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 9f5cfe5da..f39f88fd2 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -223,7 +223,7 @@ impl<'a> Error<'a> { Error::BadNumber(ref bad_span, ref err) => ParseError { message: format!( "{}: `{}`", - err,&source[bad_span.clone()], + err, &source[bad_span.clone()], ), labels: vec![(bad_span.clone(), err.to_string().into())], notes: vec![], @@ -878,7 +878,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { ExpressionContext<'a, '_, '_>, ) -> Result>, ) -> Result> { - let start = lexer.current_byte_offset() as u32; + let start = lexer.start_byte_offset() as u32; let mut accumulator = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); @@ -886,7 +886,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { let mut left = self.apply_load_rule(accumulator); let unloaded_right = parser(lexer, self.reborrow())?; let right = self.apply_load_rule(unloaded_right); - let end = lexer.current_byte_offset() as u32; + let end = lexer.end_byte_offset() as u32; left = self.expressions.append( crate::Expression::Binary { op, left, right }, NagaSpan::new(start, end), @@ -906,7 +906,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { ExpressionContext<'a, '_, '_>, ) -> Result>, ) -> Result> { - let start = lexer.current_byte_offset() as u32; + let start = lexer.start_byte_offset() as u32; let mut accumulator = parser(lexer, self.reborrow())?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); @@ -914,7 +914,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { let mut left = self.apply_load_rule(accumulator); let unloaded_right = parser(lexer, self.reborrow())?; let mut right = self.apply_load_rule(unloaded_right); - let end = lexer.current_byte_offset() as u32; + let end = lexer.end_byte_offset() as u32; self.binary_op_splat(op, &mut left, &mut right)?; @@ -1389,8 +1389,8 @@ impl Parser { self.layouter.clear(); } - fn push_rule_span(&mut self, rule: Rule, lexer: &Lexer<'_>) { - self.rules.push((rule, lexer.current_byte_offset())); + fn push_rule_span(&mut self, rule: Rule, lexer: &mut Lexer<'_>) { + self.rules.push((rule, lexer.start_byte_offset())); } fn pop_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { @@ -2589,7 +2589,7 @@ impl Parser { lexer: &mut Lexer<'a>, mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result> { - let start = lexer.current_byte_offset(); + let start = lexer.start_byte_offset(); self.push_rule_span(Rule::SingularExpr, lexer); let primary_expr = self.parse_primary_expression(lexer, ctx.reborrow())?; let singular_expr = self.parse_postfix(start, lexer, ctx.reborrow(), primary_expr)?; @@ -3249,7 +3249,7 @@ impl Parser { None => { match self.parse_type_decl_impl(lexer, attribute, name, type_arena, const_arena)? { Some(inner) => { - let span = name_span.start..lexer.current_byte_offset(); + let span = name_span.start..lexer.end_byte_offset(); type_arena.insert( crate::Type { name: debug_name.map(|s| s.to_string()), @@ -3304,11 +3304,11 @@ impl Parser { ) -> Result<(), Error<'a>> { use crate::BinaryOperator as Bo; - let span_start = lexer.consume_blankspace(); + let span_start = lexer.start_byte_offset(); context.emitter.start(context.expressions); let reference = self.parse_unary_expression(lexer, context.reborrow())?; // The left hand side of an assignment must be a reference. - let lhs_span = span_start..lexer.current_byte_offset(); + let lhs_span = span_start..lexer.end_byte_offset(); if !reference.is_reference { return Err(Error::NotReference( "the left-hand side of an assignment", @@ -3409,7 +3409,7 @@ impl Parser { other => return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)), }; - let span_end = lexer.current_byte_offset(); + let span_end = lexer.end_byte_offset(); context .block .extend(context.emitter.finish(context.expressions)); @@ -3732,7 +3732,7 @@ impl Parser { let accept = self.parse_block(lexer, context.reborrow(), false)?; let mut elsif_stack = Vec::new(); - let mut elseif_span_start = lexer.current_byte_offset(); + let mut elseif_span_start = lexer.start_byte_offset(); let mut reject = loop { if !lexer.skip(Token::Word("else")) { break crate::Block::new(); @@ -3759,10 +3759,10 @@ impl Parser { other_emit, other_block, )); - elseif_span_start = lexer.current_byte_offset(); + elseif_span_start = lexer.start_byte_offset(); }; - let span_end = lexer.current_byte_offset(); + let span_end = lexer.end_byte_offset(); // reverse-fold the else-if blocks //Note: we may consider uplifting this to the IR for (other_span_start, other_cond, other_emit, other_block) in @@ -4427,7 +4427,7 @@ impl Parser { } // read items - let start = lexer.current_byte_offset(); + let start = lexer.start_byte_offset(); match lexer.next() { (Token::Separator(';'), _) => {} (Token::Word("struct"), _) => { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 8ccaf1597..13b020ee4 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -640,11 +640,11 @@ fn reserved_keyword() { r#" var bool: bool = true; "#, - r###"error: name ` bool: bool = true;` is a reserved keyword - ┌─ wgsl:2:16 + r###"error: name `bool: bool = true;` is a reserved keyword + ┌─ wgsl:2:17 │ 2 │ var bool: bool = true; - │ ^^^^^^^^^^^^^^^^^^^ definition of ` bool: bool = true;` + │ ^^^^^^^^^^^^^^^^^^ definition of `bool: bool = true;` "###, ); @@ -765,13 +765,13 @@ fn module_scope_identifier_redefinition() { var foo: bool = true; var foo: bool = true; "#, - r###"error: redefinition of ` foo: bool = true;` - ┌─ wgsl:2:16 + r###"error: redefinition of `foo: bool = true;` + ┌─ wgsl:2:17 │ 2 │ var foo: bool = true; - │ ^^^^^^^^^^^^^^^^^^ previous definition of ` foo: bool = true;` + │ ^^^^^^^^^^^^^^^^^ previous definition of `foo: bool = true;` 3 │ var foo: bool = true; - │ ^^^^^^^^^^^^^^^^^^ redefinition of ` foo: bool = true;` + │ ^^^^^^^^^^^^^^^^^ redefinition of `foo: bool = true;` "###, ); @@ -783,10 +783,10 @@ fn module_scope_identifier_redefinition() { let foo: bool = true; "#, r###"error: redefinition of `foo` - ┌─ wgsl:2:16 + ┌─ wgsl:2:17 │ 2 │ var foo: bool = true; - │ ^^^^^^^^^^^^^^^^^^ previous definition of ` foo: bool = true;` + │ ^^^^^^^^^^^^^^^^^ previous definition of `foo: bool = true;` 3 │ let foo: bool = true; │ ^^^ redefinition of `foo` From 4f8db997b0b1e73fc1e2cac070485333a5b61925 Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Wed, 14 Sep 2022 11:52:26 +0530 Subject: [PATCH 1831/2212] remove trailing trivia --- src/front/wgsl/lexer.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index df726e417..6255d36f2 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -163,6 +163,8 @@ fn is_word_part(c: char) -> bool { pub(super) struct Lexer<'a> { input: &'a str, pub(super) source: &'a str, + // The byte offset of the end of the last non-trivia token. + last_end_offset: usize, } impl<'a> Lexer<'a> { @@ -170,6 +172,7 @@ impl<'a> Lexer<'a> { Lexer { input, source: input, + last_end_offset: 0, } } @@ -198,7 +201,7 @@ impl<'a> Lexer<'a> { pub(super) fn start_byte_offset(&mut self) -> usize { loop { - // Eat all trivia becuase `next` doesn't eat trailing trivia. + // Eat all trivia because `next` doesn't eat trailing trivia. let (token, rest) = consume_token(self.input, false); if let Token::Trivia = token { self.input = rest; @@ -209,7 +212,7 @@ impl<'a> Lexer<'a> { } pub(super) const fn end_byte_offset(&self) -> usize { - self.current_byte_offset() + self.last_end_offset } fn peek_token_and_rest(&mut self) -> (TokenSpan<'a>, &'a str) { @@ -224,7 +227,7 @@ impl<'a> Lexer<'a> { } pub(super) const fn span_from(&self, offset: usize) -> Span { - offset..self.current_byte_offset() + offset..self.end_byte_offset() } #[must_use] @@ -235,7 +238,10 @@ impl<'a> Lexer<'a> { self.input = rest; match token { Token::Trivia => start_byte_offset = self.current_byte_offset(), - _ => return (token, start_byte_offset..self.current_byte_offset()), + _ => { + self.last_end_offset = self.current_byte_offset(); + return (token, start_byte_offset..self.last_end_offset); + } } } } From 5166c2a1d84c3c96ff1ed2b827c313640d1e3fb9 Mon Sep 17 00:00:00 2001 From: Shaye Garg <64652557+SparkyPotato@users.noreply.github.com> Date: Thu, 15 Sep 2022 21:47:00 +0530 Subject: [PATCH 1832/2212] wgsl-in: Improve assignment diagnostics (#2056) Fixes #2052. * improved assignment statement errors * hint immutable binding * fix clippy * add diagnostic tests * cleanup formatting --- src/front/wgsl/lexer.rs | 6 +-- src/front/wgsl/mod.rs | 110 ++++++++++++++++++++++++++++++---------- tests/wgsl-errors.rs | 80 +++++++++++++++++++++++++++++ 3 files changed, 165 insertions(+), 31 deletions(-) diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 6255d36f2..35fe45089 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -273,7 +273,7 @@ impl<'a> Lexer<'a> { if next.0 == expected { Ok(next.1) } else { - Err(Error::Unexpected(next, ExpectedToken::Token(expected))) + Err(Error::Unexpected(next.1, ExpectedToken::Token(expected))) } } @@ -288,7 +288,7 @@ impl<'a> Lexer<'a> { Ok(()) } else { Err(Error::Unexpected( - next, + next.1, ExpectedToken::Token(Token::Paren(expected)), )) } @@ -314,7 +314,7 @@ impl<'a> Lexer<'a> { Err(Error::ReservedIdentifierPrefix(span)) } (Token::Word(word), span) => Ok((word, span)), - other => Err(Error::Unexpected(other, ExpectedToken::Identifier)), + other => Err(Error::Unexpected(other.1, ExpectedToken::Identifier)), } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f39f88fd2..df71cfc98 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -71,6 +71,8 @@ pub enum ExpectedToken<'a> { Constant, /// Expected: constant, parenthesized expression, identifier PrimaryExpression, + /// Expected: assignment, increment/decrement expression + Assignment, /// Expected: '}', identifier FieldName, /// Expected: attribute for a type @@ -95,9 +97,16 @@ pub enum NumberError { UnimplementedF16, } +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum InvalidAssignmentType { + Other, + Swizzle, + ImmutableBinding, +} + #[derive(Clone, Debug)] pub enum Error<'a> { - Unexpected(TokenSpan<'a>, ExpectedToken<'a>), + Unexpected(Span, ExpectedToken<'a>), UnexpectedComponents(Span), BadNumber(Span, NumberError), /// A negative signed integer literal where both signed and unsigned, @@ -151,6 +160,10 @@ pub enum Error<'a> { Pointer(&'static str, Span), NotPointer(Span), NotReference(&'static str, Span), + InvalidAssignment { + span: Span, + ty: InvalidAssignmentType, + }, ReservedKeyword(Span), Redefinition { previous: Span, @@ -162,7 +175,7 @@ pub enum Error<'a> { impl<'a> Error<'a> { fn as_parse_error(&self, source: &'a str) -> ParseError { match *self { - Error::Unexpected((_, ref unexpected_span), expected) => { + Error::Unexpected(ref unexpected_span, expected) => { let expected_str = match expected { ExpectedToken::Token(token) => { match token { @@ -195,6 +208,7 @@ impl<'a> Error<'a> { ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), ExpectedToken::Constant => "constant".to_string(), ExpectedToken::PrimaryExpression => "expression".to_string(), + ExpectedToken::Assignment => "assignment or increment/decrement".to_string(), ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(), ExpectedToken::TypeAttribute => "type attribute".to_string(), ExpectedToken::Statement => "statement".to_string(), @@ -439,6 +453,20 @@ impl<'a> Error<'a> { labels: vec![(span.clone(), "expression is not a reference".into())], notes: vec![], }, + Error::InvalidAssignment{ ref span, ty} => ParseError { + message: "invalid left-hand side of assignment".into(), + labels: vec![(span.clone(), "cannot assign to this expression".into())], + notes: match ty { + InvalidAssignmentType::Swizzle => vec![ + "WGSL does not support assignments to swizzles".into(), + "consider assigning each component individually".into() + ], + InvalidAssignmentType::ImmutableBinding => vec![ + format!("'{}' is an immutable binding", &source[span.clone()]), "consider declaring it with `var` instead of `let`".into() + ], + InvalidAssignmentType::Other => vec![], + }, + }, Error::Pointer(what, ref span) => ParseError { message: format!("{} must not be a pointer", what), labels: vec![(span.clone(), "expression is a pointer".into())], @@ -1409,7 +1437,7 @@ impl Parser { Token::Number(Ok(Number::U32(num))) if uint => Ok(num as i32), Token::Number(Ok(Number::I32(num))) if !uint => Ok(num), Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)), - _ => Err(Error::Unexpected(token_span, ExpectedToken::Integer)), + _ => Err(Error::Unexpected(token_span.1, ExpectedToken::Integer)), } } @@ -1422,7 +1450,7 @@ impl Parser { } (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), other => Err(Error::Unexpected( - other, + other.1, ExpectedToken::Number(NumberType::I32), )), } @@ -1439,7 +1467,7 @@ impl Parser { (Token::Number(Ok(Number::U32(num))), _) => Ok(num), (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), other => Err(Error::Unexpected( - other, + other.1, ExpectedToken::Number(NumberType::I32), )), } @@ -2239,7 +2267,7 @@ impl Parser { components, } } - other => return Err(Error::Unexpected(other, ExpectedToken::Constant)), + other => return Err(Error::Unexpected(other.1, ExpectedToken::Constant)), }; // Only set span if it's a named constant. Otherwise, the enclosing Expression should have @@ -2330,7 +2358,7 @@ impl Parser { } } } - other => return Err(Error::Unexpected(other, ExpectedToken::PrimaryExpression)), + other => return Err(Error::Unexpected(other.1, ExpectedToken::PrimaryExpression)), }; Ok(expr) } @@ -2831,7 +2859,7 @@ impl Parser { while !lexer.skip(Token::Paren('}')) { if !ready { return Err(Error::Unexpected( - lexer.next(), + lexer.next().1, ExpectedToken::Token(Token::Separator(',')), )); } @@ -2863,7 +2891,7 @@ impl Parser { let (name, span) = match lexer.next() { (Token::Word(word), span) => (word, span), - other => return Err(Error::Unexpected(other, ExpectedToken::FieldName)), + other => return Err(Error::Unexpected(other.1, ExpectedToken::FieldName)), }; if crate::keywords::wgsl::RESERVED.contains(&name) { return Err(Error::ReservedKeyword(span)); @@ -3276,7 +3304,7 @@ impl Parser { if lexer.skip(Token::Attribute) { let other = lexer.next(); - return Err(Error::Unexpected(other, ExpectedToken::TypeAttribute)); + return Err(Error::Unexpected(other.1, ExpectedToken::TypeAttribute)); } let (name, name_span) = lexer.next_ident_with_span()?; @@ -3300,23 +3328,42 @@ impl Parser { fn parse_assignment_statement<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, - mut context: ExpressionContext<'a, '_, 'out>, + mut context: StatementContext<'a, '_, 'out>, + block: &mut crate::Block, + emitter: &mut super::Emitter, ) -> Result<(), Error<'a>> { use crate::BinaryOperator as Bo; let span_start = lexer.start_byte_offset(); - context.emitter.start(context.expressions); - let reference = self.parse_unary_expression(lexer, context.reborrow())?; + emitter.start(context.expressions); + let (reference, lhs_span) = self + .parse_general_expression_for_reference(lexer, context.as_expression(block, emitter))?; + let op = lexer.next(); // The left hand side of an assignment must be a reference. - let lhs_span = span_start..lexer.end_byte_offset(); - if !reference.is_reference { - return Err(Error::NotReference( - "the left-hand side of an assignment", - lhs_span, - )); + if !matches!( + op.0, + Token::Operation('=') + | Token::AssignmentOperation(_) + | Token::IncrementOperation + | Token::DecrementOperation + ) { + return Err(Error::Unexpected(lhs_span, ExpectedToken::Assignment)); + } else if !reference.is_reference { + let ty = if context.named_expressions.contains_key(&reference.handle) { + InvalidAssignmentType::ImmutableBinding + } else { + match *context.expressions.get_mut(reference.handle) { + crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, + _ => InvalidAssignmentType::Other, + } + }; + + return Err(Error::InvalidAssignment { span: lhs_span, ty }); } - let value = match lexer.next() { + let mut context = context.as_expression(block, emitter); + + let value = match op { (Token::Operation('='), _) => { self.parse_general_expression(lexer, context.reborrow())? } @@ -3406,7 +3453,7 @@ impl Parser { op_span.into(), ) } - other => return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)), + other => return Err(Error::Unexpected(other.1, ExpectedToken::SwitchItem)), }; let span_end = lexer.end_byte_offset(); @@ -3843,7 +3890,10 @@ impl Parser { } (Token::Paren('}'), _) => break, other => { - return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)) + return Err(Error::Unexpected( + other.1, + ExpectedToken::SwitchItem, + )) } } } @@ -3954,7 +4004,9 @@ impl Parser { } _ => self.parse_assignment_statement( lexer, - context.as_expression(&mut continuing, &mut emitter), + context.reborrow(), + &mut continuing, + &mut emitter, )?, } lexer.expect(Token::Paren(')'))?; @@ -4059,7 +4111,9 @@ impl Parser { match context.symbol_table.lookup(ident) { Some(_) => self.parse_assignment_statement( lexer, - context.as_expression(block, &mut emitter), + context, + block, + &mut emitter, )?, None => self.parse_function_statement( lexer, @@ -4078,7 +4132,7 @@ impl Parser { } _ => { let mut emitter = super::Emitter::default(); - self.parse_assignment_statement(lexer, context.as_expression(block, &mut emitter))?; + self.parse_assignment_statement(lexer, context, block, &mut emitter)?; self.pop_rule_span(lexer); } } @@ -4262,7 +4316,7 @@ impl Parser { while !lexer.skip(Token::Paren(')')) { if !ready { return Err(Error::Unexpected( - lexer.next(), + lexer.next().1, ExpectedToken::Token(Token::Separator(',')), )); } @@ -4391,7 +4445,7 @@ impl Parser { (Token::Separator(','), _) if i != 2 => (), other => { return Err(Error::Unexpected( - other, + other.1, ExpectedToken::WorkgroupSizeSeparator, )) } @@ -4577,7 +4631,7 @@ impl Parser { } } (Token::End, _) => return Ok(false), - other => return Err(Error::Unexpected(other, ExpectedToken::GlobalItem)), + other => return Err(Error::Unexpected(other.1, ExpectedToken::GlobalItem)), } match binding { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 13b020ee4..445459f3b 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1597,3 +1597,83 @@ fn break_if_bad_condition() { ) } } + +#[test] +fn swizzle_assignment() { + check( + " + fn f() { + var v = vec2(0); + v.xy = vec2(1); + } + ", + r###"error: invalid left-hand side of assignment + ┌─ wgsl:4:13 + │ +4 │ v.xy = vec2(1); + │ ^^^^ cannot assign to this expression + │ + = note: WGSL does not support assignments to swizzles + = note: consider assigning each component individually + +"###, + ); +} + +#[test] +fn binary_statement() { + check( + " + fn f() { + 3 + 5; + } + ", + r###"error: expected assignment or increment/decrement, found '3 + 5' + ┌─ wgsl:3:13 + │ +3 │ 3 + 5; + │ ^^^^^ expected assignment or increment/decrement + +"###, + ); +} + +#[test] +fn assign_to_expr() { + check( + " + fn f() { + 3 + 5 = 10; + } + ", + r###"error: invalid left-hand side of assignment + ┌─ wgsl:3:13 + │ +3 │ 3 + 5 = 10; + │ ^^^^^ cannot assign to this expression + +"###, + ); +} + +#[test] +fn assign_to_let() { + check( + " + fn f() { + let a = 10; + a = 20; + } + ", + r###"error: invalid left-hand side of assignment + ┌─ wgsl:4:10 + │ +4 │ a = 20; + │ ^ cannot assign to this expression + │ + = note: 'a' is an immutable binding + = note: consider declaring it with `var` instead of `let` + +"###, + ); +} From 33392382ee59b23ab749c7a35d8bf25173dc48b4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 15 Sep 2022 12:06:11 -0700 Subject: [PATCH 1833/2212] [wgsl-in] Break up long string, reformat rest of file. (#2057) Whitespace and formatting changes only. It turns out that if `cargo fmt` comes across a single line it can't make fit within the margins, then it sort of gives up on the surrounding construct. So breaking up the error message for `Error::UnknownScalarType` in `Error::as_parse_error` and then re-running `cargo fmt` cleans up lots of other stuff in the file. cargo fmt issue: https://github.com/rust-lang/rustfmt/issues/3863 --- src/front/wgsl/mod.rs | 168 +++++++++++++++++++++++++++++++----------- 1 file changed, 125 insertions(+), 43 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index df71cfc98..2873e6c73 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -216,7 +216,7 @@ impl<'a> Error<'a> { ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), ExpectedToken::GlobalItem => "global item ('struct', 'let', 'var', 'type', ';', 'fn') or the end of the file".to_string(), }; - ParseError { + ParseError { message: format!( "expected {}, found '{}'", expected_str, @@ -228,17 +228,14 @@ impl<'a> Error<'a> { )], notes: vec![], } - }, + } Error::UnexpectedComponents(ref bad_span) => ParseError { message: "unexpected components".to_string(), labels: vec![(bad_span.clone(), "unexpected components".into())], notes: vec![], }, Error::BadNumber(ref bad_span, ref err) => ParseError { - message: format!( - "{}: `{}`", - err, &source[bad_span.clone()], - ), + message: format!("{}: `{}`", err, &source[bad_span.clone()],), labels: vec![(bad_span.clone(), err.to_string().into())], notes: vec![], }, @@ -258,12 +255,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span.clone(), "expected unsigned integer".into())], notes: vec![], }, - Error::BadMatrixScalarKind( - ref span, - kind, - width, - ) => ParseError { - message: format!("matrix scalar type must be floating-point, but found `{}`", kind.to_wgsl(width)), + Error::BadMatrixScalarKind(ref span, kind, width) => ParseError { + message: format!( + "matrix scalar type must be floating-point, but found `{}`", + kind.to_wgsl(width) + ), labels: vec![(span.clone(), "must be floating-point (e.g. `f32`)".into())], notes: vec![], }, @@ -283,39 +279,67 @@ impl<'a> Error<'a> { Error::UnknownScalarType(ref bad_span) => ParseError { message: format!("unknown scalar type: '{}'", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "unknown scalar type".into())], - notes: vec!["Valid scalar types are f16, f32, f64, i8, i16, i32, i64, u8, u16, u32, u64, bool".into()], + notes: vec!["Valid scalar types are f16, f32, f64, \ + i8, i16, i32, i64, \ + u8, u16, u32, u64, bool" + .into()], }, - Error::BadTextureSampleType { ref span, kind, width } => ParseError { - message: format!("texture sample type must be one of f32, i32 or u32, but found {}", kind.to_wgsl(width)), + Error::BadTextureSampleType { + ref span, + kind, + width, + } => ParseError { + message: format!( + "texture sample type must be one of f32, i32 or u32, but found {}", + kind.to_wgsl(width) + ), labels: vec![(span.clone(), "must be one of f32, i32 or u32".into())], notes: vec![], }, Error::BadIncrDecrReferenceType(ref span) => ParseError { - message: "increment/decrement operation requires reference type to be one of i32 or u32".to_string(), - labels: vec![(span.clone(), "must be a reference type of i32 or u32".into())], + message: + "increment/decrement operation requires reference type to be one of i32 or u32" + .to_string(), + labels: vec![( + span.clone(), + "must be a reference type of i32 or u32".into(), + )], notes: vec![], }, Error::BadTexture(ref bad_span) => ParseError { - message: format!("expected an image, but found '{}' which is not an image", &source[bad_span.clone()]), + message: format!( + "expected an image, but found '{}' which is not an image", + &source[bad_span.clone()] + ), labels: vec![(bad_span.clone(), "not an image".into())], notes: vec![], }, - Error::BadTypeCast { ref span, ref from_type, ref to_type } => { + Error::BadTypeCast { + ref span, + ref from_type, + ref to_type, + } => { let msg = format!("cannot cast a {} to a {}", from_type, to_type); ParseError { message: msg.clone(), labels: vec![(span.clone(), msg.into())], notes: vec![], } - }, + } Error::InvalidResolve(ref resolve_error) => ParseError { message: resolve_error.to_string(), labels: vec![], notes: vec![], }, Error::InvalidForInitializer(ref bad_span) => ParseError { - message: format!("for(;;) initializer is not an assignment or a function call: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "not an assignment or function call".into())], + message: format!( + "for(;;) initializer is not an assignment or a function call: '{}'", + &source[bad_span.clone()] + ), + labels: vec![( + bad_span.clone(), + "not an assignment or function call".into(), + )], notes: vec![], }, Error::InvalidBreakIf(ref bad_span) => ParseError { @@ -324,22 +348,34 @@ impl<'a> Error<'a> { notes: vec![], }, Error::InvalidGatherComponent(ref bad_span, component) => ParseError { - message: format!("textureGather component {} doesn't exist, must be 0, 1, 2, or 3", component), + message: format!( + "textureGather component {} doesn't exist, must be 0, 1, 2, or 3", + component + ), labels: vec![(bad_span.clone(), "invalid component".into())], notes: vec![], }, Error::InvalidConstructorComponentType(ref bad_span, component) => ParseError { - message: format!("invalid type for constructor component at index [{}]", component), + message: format!( + "invalid type for constructor component at index [{}]", + component + ), labels: vec![(bad_span.clone(), "invalid component type".into())], notes: vec![], }, Error::InvalidIdentifierUnderscore(ref bad_span) => ParseError { message: "Identifier can't be '_'".to_string(), labels: vec![(bad_span.clone(), "invalid identifier".into())], - notes: vec!["Use phony assignment instead ('_ =' notice the absence of 'let' or 'var')".to_string()], + notes: vec![ + "Use phony assignment instead ('_ =' notice the absence of 'let' or 'var')" + .to_string(), + ], }, Error::ReservedIdentifierPrefix(ref bad_span) => ParseError { - message: format!("Identifier starts with a reserved prefix: '{}'", &source[bad_span.clone()]), + message: format!( + "Identifier starts with a reserved prefix: '{}'", + &source[bad_span.clone()] + ), labels: vec![(bad_span.clone(), "invalid identifier".into())], notes: vec![], }, @@ -374,7 +410,10 @@ impl<'a> Error<'a> { notes: vec![], }, Error::UnknownConservativeDepth(ref bad_span) => ParseError { - message: format!("unknown conservative depth: '{}'", &source[bad_span.clone()]), + message: format!( + "unknown conservative depth: '{}'", + &source[bad_span.clone()] + ), labels: vec![(bad_span.clone(), "unknown conservative depth".into())], notes: vec![], }, @@ -385,12 +424,18 @@ impl<'a> Error<'a> { }, Error::SizeAttributeTooLow(ref bad_span, min_size) => ParseError { message: format!("struct member size must be at least {}", min_size), - labels: vec![(bad_span.clone(), format!("must be at least {}", min_size).into())], + labels: vec![( + bad_span.clone(), + format!("must be at least {}", min_size).into(), + )], notes: vec![], }, Error::AlignAttributeTooLow(ref bad_span, min_align) => ParseError { message: format!("struct member alignment must be at least {}", min_align), - labels: vec![(bad_span.clone(), format!("must be at least {}", min_align).into())], + labels: vec![( + bad_span.clone(), + format!("must be at least {}", min_align).into(), + )], notes: vec![], }, Error::NonPowerOfTwoAlignAttribute(ref bad_span) => ParseError { @@ -400,7 +445,10 @@ impl<'a> Error<'a> { }, Error::InconsistentBinding(ref span) => ParseError { message: "input/output binding is not consistent".to_string(), - labels: vec![(span.clone(), "input/output binding is not consistent".into())], + labels: vec![( + span.clone(), + "input/output binding is not consistent".into(), + )], notes: vec![], }, Error::UnknownLocalFunction(ref span) => ParseError { @@ -419,18 +467,35 @@ impl<'a> Error<'a> { notes: vec![], }, Error::InitializationTypeMismatch(ref name_span, ref expected_ty) => ParseError { - message: format!("the type of `{}` is expected to be `{}`", &source[name_span.clone()], expected_ty), - labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], + message: format!( + "the type of `{}` is expected to be `{}`", + &source[name_span.clone()], + expected_ty + ), + labels: vec![( + name_span.clone(), + format!("definition of `{}`", &source[name_span.clone()]).into(), + )], notes: vec![], }, Error::MissingType(ref name_span) => ParseError { message: format!("variable `{}` needs a type", &source[name_span.clone()]), - labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], + labels: vec![( + name_span.clone(), + format!("definition of `{}`", &source[name_span.clone()]).into(), + )], notes: vec![], }, Error::MissingAttribute(name, ref name_span) => ParseError { - message: format!("variable `{}` needs a '{}' attribute", &source[name_span.clone()], name), - labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], + message: format!( + "variable `{}` needs a '{}' attribute", + &source[name_span.clone()], + name + ), + labels: vec![( + name_span.clone(), + format!("definition of `{}`", &source[name_span.clone()]).into(), + )], notes: vec![], }, Error::InvalidAtomicPointer(ref span) => ParseError { @@ -453,16 +518,17 @@ impl<'a> Error<'a> { labels: vec![(span.clone(), "expression is not a reference".into())], notes: vec![], }, - Error::InvalidAssignment{ ref span, ty} => ParseError { + Error::InvalidAssignment { ref span, ty } => ParseError { message: "invalid left-hand side of assignment".into(), labels: vec![(span.clone(), "cannot assign to this expression".into())], notes: match ty { InvalidAssignmentType::Swizzle => vec![ "WGSL does not support assignments to swizzles".into(), - "consider assigning each component individually".into() + "consider assigning each component individually".into(), ], InvalidAssignmentType::ImmutableBinding => vec![ - format!("'{}' is an immutable binding", &source[span.clone()]), "consider declaring it with `var` instead of `let`".into() + format!("'{}' is an immutable binding", &source[span.clone()]), + "consider declaring it with `var` instead of `let`".into(), ], InvalidAssignmentType::Other => vec![], }, @@ -473,14 +539,30 @@ impl<'a> Error<'a> { notes: vec![], }, Error::ReservedKeyword(ref name_span) => ParseError { - message: format!("name `{}` is a reserved keyword", &source[name_span.clone()]), - labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())], + message: format!( + "name `{}` is a reserved keyword", + &source[name_span.clone()] + ), + labels: vec![( + name_span.clone(), + format!("definition of `{}`", &source[name_span.clone()]).into(), + )], notes: vec![], }, - Error::Redefinition { ref previous, ref current } => ParseError { + Error::Redefinition { + ref previous, + ref current, + } => ParseError { message: format!("redefinition of `{}`", &source[current.clone()]), - labels: vec![(current.clone(), format!("redefinition of `{}`", &source[current.clone()]).into()), - (previous.clone(), format!("previous definition of `{}`", &source[previous.clone()]).into()) + labels: vec![ + ( + current.clone(), + format!("redefinition of `{}`", &source[current.clone()]).into(), + ), + ( + previous.clone(), + format!("previous definition of `{}`", &source[previous.clone()]).into(), + ), ], notes: vec![], }, From 7e3750a7f2eca0ab357dfa72d90bdc60b77c3202 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 16 Sep 2022 17:52:00 -0700 Subject: [PATCH 1834/2212] [wgsl] Fix line endings on wgsl reserved words list. (#2059) --- src/keywords/wgsl.rs | 848 +++++++++++++++++++++---------------------- 1 file changed, 424 insertions(+), 424 deletions(-) diff --git a/src/keywords/wgsl.rs b/src/keywords/wgsl.rs index b5cc6ea9f..8d077c099 100644 --- a/src/keywords/wgsl.rs +++ b/src/keywords/wgsl.rs @@ -1,424 +1,424 @@ -/*! -Keywords for [WGSL][wgsl] (WebGPU Shading Language). - -[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html -*/ - -// https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary -pub const RESERVED: &[&str] = &[ - // type-defining - "array", - "atomic", - "bool", - "f32", - "f16", - "i32", - "mat2x2", - "mat2x3", - "mat2x4", - "mat3x2", - "mat3x3", - "mat3x4", - "mat4x2", - "mat4x3", - "mat4x4", - "override", - "ptr", - "sampler", - "sampler_comparison", - "struct", - "texture_1d", - "texture_2d", - "texture_2d_array", - "texture_3d", - "texture_cube", - "texture_cube_array", - "texture_multisampled_2d", - "texture_storage_1d", - "texture_storage_2d", - "texture_storage_2d_array", - "texture_storage_3d", - "texture_depth_2d", - "texture_depth_2d_array", - "texture_depth_cube", - "texture_depth_cube_array", - "texture_depth_multisampled_2d", - "u32", - "vec2", - "vec3", - "vec4", - // other - "bitcast", - "break", - "case", - "const", - "continue", - "continuing", - "default", - "discard", - "else", - "enable", - "fallthrough", - "false", - "fn", - "for", - "function", - "if", - "let", - "loop", - "private", - "return", - "storage", - "switch", - "true", - "type", - "uniform", - "var", - "while", - "workgroup", - // reserved - "AppendStructuredBuffer", - "BlendState", - "Buffer", - "ByteAddressBuffer", - "CompileShader", - "ComputeShader", - "ConsumeStructuredBuffer", - "DepthStencilState", - "DepthStencilView", - "DomainShader", - "GeometryShader", - "Hullshader", - "InputPatch", - "LineStream", - "NULL", - "OutputPatch", - "PixelShader", - "PointStream", - "RWBuffer", - "RWByteAddressBuffer", - "RWStructuredBuffer", - "RWTexture1D", - "RWTexture1DArray", - "RWTexture2D", - "RWTexture2DArray", - "RWTexture3D", - "RasterizerState", - "RenderTargetView", - "SamplerComparisonState", - "SamplerState", - "Self", - "StructuredBuffer", - "Texture1D", - "Texture1DArray", - "Texture2D", - "Texture2DArray", - "Texture2DMS", - "Texture2DMSArray", - "Texture3D", - "TextureCube", - "TextureCubeArray", - "TriangleStream", - "VertexShader", - "abstract", - "active", - "alignas", - "alignof", - "as", - "asm", - "asm_fragment", - "async", - "atomic_uint", - "attribute", - "auto", - "await", - "become", - "bf16", - "binding_array", - "cast", - "catch", - "cbuffer", - "char", - "class", - "co_await", - "co_return", - "co_yield", - "coherent", - "column_major", - "common", - "compile", - "compile_fragment", - "concept", - "const_cast", - "consteval", - "constexpr", - "constinit", - "crate", - "debugger", - "decltype", - "delete", - "demote", - "demote_to_helper", - "do", - "dword", - "dynamic_cast", - "enum", - "explicit", - "export", - "extends", - "extern", - "external", - "f64", - "filter", - "final", - "finally", - "fixed", - "friend", - "from", - "fvec2", - "fvec3", - "fvec4", - "fxgroup", - "get", - "goto", - "groupshared", - "handle", - "highp", - "hvec2", - "hvec3", - "hvec4", - "i16", - "i64", - "i8", - "iimage1D", - "iimage1DArray", - "iimage2D", - "iimage2DArray", - "iimage2DMS", - "iimage2DMSArray", - "iimage2DRect", - "iimage3D", - "iimageBuffer", - "iimageCube", - "iimageCubeArray", - "image1D", - "image1DArray", - "image2D", - "image2DArray", - "image2DMS", - "image2DMSArray", - "image2DRect", - "image3D", - "imageBuffer", - "imageCube", - "imageCubeArray", - "impl", - "implements", - "import", - "inline", - "inout", - "instanceof", - "interface", - "invariant", - "isampler1D", - "isampler1DArray", - "isampler2D", - "isampler2DArray", - "isampler2DMS", - "isampler2DMSArray", - "isampler2DRect", - "isampler3D", - "isamplerBuffer", - "isamplerCube", - "isamplerCubeArray", - "isubpassInput", - "isubpassInputMS", - "itexture1D", - "itexture1DArray", - "itexture2D", - "itexture2DArray", - "itexture2DMS", - "itexture2DMSArray", - "itexture2DRect", - "itexture3D", - "itextureBuffer", - "itextureCube", - "itextureCubeArray", - "layout", - "line", - "lineadj", - "lowp", - "macro", - "macro_rules", - "mat", - "match", - "matrix", - "mediump", - "meta", - "mod", - "module", - "move", - "mut", - "mutable", - "namespace", - "new", - "nil", - "noexcept", - "noinline", - "nointerpolation", - "noperspective", - "null", - "nullptr", - "of", - "operator", - "package", - "packoffset", - "partition", - "pass", - "patch", - "pixelfragment", - "point", - "precise", - "precision", - "premerge", - "priv", - "protected", - "pub", - "public", - "readonly", - "ref", - "regardless", - "register", - "reinterpret_cast", - "requires", - "resource", - "restrict", - "row_major", - "samper", - "sampler1D", - "sampler1DArray", - "sampler1DArrayShadow", - "sampler1DShadow", - "sampler2D", - "sampler2DArray", - "sampler2DArrayShadow", - "sampler2DMS", - "sampler2DMSArray", - "sampler2DRect", - "sampler2DRectShadow", - "sampler2DShadow", - "sampler3D", - "sampler3DRect", - "samplerBuffer", - "samplerCube", - "samplerCubeArray", - "samplerCubeArrayShadow", - "samplerCubeShadow", - "samplerShadow", - "self", - "set", - "shared", - "signed", - "sizeof", - "smooth", - "snorm", - "stateblock", - "stateblock_state", - "static", - "static_assert", - "static_cast", - "std", - "string", - "subpassInput", - "subpassInputMS", - "subroutine", - "super", - "superp", - "target", - "tbuffer", - "technique", - "technique10", - "technique11", - "template", - "texture1D", - "texture1DArray", - "texture2D", - "texture2DArray", - "texture2DMS", - "texture2DMSArray", - "texture2DRect", - "texture3D", - "textureBuffer", - "textureCube", - "textureCubeArray", - "this", - "thread_local", - "throw", - "trait", - "triangle", - "triangleadj", - "try", - "typedef", - "typeid", - "typename", - "typeof", - "u16", - "u64", - "u8", - "uimage1D", - "uimage1DArray", - "uimage2D", - "uimage2DArray", - "uimage2DMS", - "uimage2DMSArray", - "uimage2DRect", - "uimage3D", - "uimageBuffer", - "uimageCube", - "uimageCubeArray", - "union", - "unless", - "unorm", - "unsafe", - "unsigned", - "unsized", - "usampler1D", - "usampler1DArray", - "usampler2D", - "usampler2DArray", - "usampler2DMS", - "usampler2DMSArray", - "usampler2DRect", - "usampler3D", - "usamplerBuffer", - "usamplerCube", - "usamplerCubeArray", - "use", - "using", - "usubpassInput", - "usubpassInputMS", - "utexture1D", - "utexture1DArray", - "utexture2D", - "utexture2DArray", - "utexture2DMS", - "utexture2DMSArray", - "utexture2DRect", - "utexture3D", - "utextureBuffer", - "utextureCube", - "utextureCubeArray", - "varying", - "vec", - "vector", - "vertexfragment", - "virtual", - "void", - "volatile", - "wchar_t", - "wgsl", - "where", - "with", - "writeonly", - "yield", -]; +/*! +Keywords for [WGSL][wgsl] (WebGPU Shading Language). + +[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html +*/ + +// https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary +pub const RESERVED: &[&str] = &[ + // type-defining + "array", + "atomic", + "bool", + "f32", + "f16", + "i32", + "mat2x2", + "mat2x3", + "mat2x4", + "mat3x2", + "mat3x3", + "mat3x4", + "mat4x2", + "mat4x3", + "mat4x4", + "override", + "ptr", + "sampler", + "sampler_comparison", + "struct", + "texture_1d", + "texture_2d", + "texture_2d_array", + "texture_3d", + "texture_cube", + "texture_cube_array", + "texture_multisampled_2d", + "texture_storage_1d", + "texture_storage_2d", + "texture_storage_2d_array", + "texture_storage_3d", + "texture_depth_2d", + "texture_depth_2d_array", + "texture_depth_cube", + "texture_depth_cube_array", + "texture_depth_multisampled_2d", + "u32", + "vec2", + "vec3", + "vec4", + // other + "bitcast", + "break", + "case", + "const", + "continue", + "continuing", + "default", + "discard", + "else", + "enable", + "fallthrough", + "false", + "fn", + "for", + "function", + "if", + "let", + "loop", + "private", + "return", + "storage", + "switch", + "true", + "type", + "uniform", + "var", + "while", + "workgroup", + // reserved + "AppendStructuredBuffer", + "BlendState", + "Buffer", + "ByteAddressBuffer", + "CompileShader", + "ComputeShader", + "ConsumeStructuredBuffer", + "DepthStencilState", + "DepthStencilView", + "DomainShader", + "GeometryShader", + "Hullshader", + "InputPatch", + "LineStream", + "NULL", + "OutputPatch", + "PixelShader", + "PointStream", + "RWBuffer", + "RWByteAddressBuffer", + "RWStructuredBuffer", + "RWTexture1D", + "RWTexture1DArray", + "RWTexture2D", + "RWTexture2DArray", + "RWTexture3D", + "RasterizerState", + "RenderTargetView", + "SamplerComparisonState", + "SamplerState", + "Self", + "StructuredBuffer", + "Texture1D", + "Texture1DArray", + "Texture2D", + "Texture2DArray", + "Texture2DMS", + "Texture2DMSArray", + "Texture3D", + "TextureCube", + "TextureCubeArray", + "TriangleStream", + "VertexShader", + "abstract", + "active", + "alignas", + "alignof", + "as", + "asm", + "asm_fragment", + "async", + "atomic_uint", + "attribute", + "auto", + "await", + "become", + "bf16", + "binding_array", + "cast", + "catch", + "cbuffer", + "char", + "class", + "co_await", + "co_return", + "co_yield", + "coherent", + "column_major", + "common", + "compile", + "compile_fragment", + "concept", + "const_cast", + "consteval", + "constexpr", + "constinit", + "crate", + "debugger", + "decltype", + "delete", + "demote", + "demote_to_helper", + "do", + "dword", + "dynamic_cast", + "enum", + "explicit", + "export", + "extends", + "extern", + "external", + "f64", + "filter", + "final", + "finally", + "fixed", + "friend", + "from", + "fvec2", + "fvec3", + "fvec4", + "fxgroup", + "get", + "goto", + "groupshared", + "handle", + "highp", + "hvec2", + "hvec3", + "hvec4", + "i16", + "i64", + "i8", + "iimage1D", + "iimage1DArray", + "iimage2D", + "iimage2DArray", + "iimage2DMS", + "iimage2DMSArray", + "iimage2DRect", + "iimage3D", + "iimageBuffer", + "iimageCube", + "iimageCubeArray", + "image1D", + "image1DArray", + "image2D", + "image2DArray", + "image2DMS", + "image2DMSArray", + "image2DRect", + "image3D", + "imageBuffer", + "imageCube", + "imageCubeArray", + "impl", + "implements", + "import", + "inline", + "inout", + "instanceof", + "interface", + "invariant", + "isampler1D", + "isampler1DArray", + "isampler2D", + "isampler2DArray", + "isampler2DMS", + "isampler2DMSArray", + "isampler2DRect", + "isampler3D", + "isamplerBuffer", + "isamplerCube", + "isamplerCubeArray", + "isubpassInput", + "isubpassInputMS", + "itexture1D", + "itexture1DArray", + "itexture2D", + "itexture2DArray", + "itexture2DMS", + "itexture2DMSArray", + "itexture2DRect", + "itexture3D", + "itextureBuffer", + "itextureCube", + "itextureCubeArray", + "layout", + "line", + "lineadj", + "lowp", + "macro", + "macro_rules", + "mat", + "match", + "matrix", + "mediump", + "meta", + "mod", + "module", + "move", + "mut", + "mutable", + "namespace", + "new", + "nil", + "noexcept", + "noinline", + "nointerpolation", + "noperspective", + "null", + "nullptr", + "of", + "operator", + "package", + "packoffset", + "partition", + "pass", + "patch", + "pixelfragment", + "point", + "precise", + "precision", + "premerge", + "priv", + "protected", + "pub", + "public", + "readonly", + "ref", + "regardless", + "register", + "reinterpret_cast", + "requires", + "resource", + "restrict", + "row_major", + "samper", + "sampler1D", + "sampler1DArray", + "sampler1DArrayShadow", + "sampler1DShadow", + "sampler2D", + "sampler2DArray", + "sampler2DArrayShadow", + "sampler2DMS", + "sampler2DMSArray", + "sampler2DRect", + "sampler2DRectShadow", + "sampler2DShadow", + "sampler3D", + "sampler3DRect", + "samplerBuffer", + "samplerCube", + "samplerCubeArray", + "samplerCubeArrayShadow", + "samplerCubeShadow", + "samplerShadow", + "self", + "set", + "shared", + "signed", + "sizeof", + "smooth", + "snorm", + "stateblock", + "stateblock_state", + "static", + "static_assert", + "static_cast", + "std", + "string", + "subpassInput", + "subpassInputMS", + "subroutine", + "super", + "superp", + "target", + "tbuffer", + "technique", + "technique10", + "technique11", + "template", + "texture1D", + "texture1DArray", + "texture2D", + "texture2DArray", + "texture2DMS", + "texture2DMSArray", + "texture2DRect", + "texture3D", + "textureBuffer", + "textureCube", + "textureCubeArray", + "this", + "thread_local", + "throw", + "trait", + "triangle", + "triangleadj", + "try", + "typedef", + "typeid", + "typename", + "typeof", + "u16", + "u64", + "u8", + "uimage1D", + "uimage1DArray", + "uimage2D", + "uimage2DArray", + "uimage2DMS", + "uimage2DMSArray", + "uimage2DRect", + "uimage3D", + "uimageBuffer", + "uimageCube", + "uimageCubeArray", + "union", + "unless", + "unorm", + "unsafe", + "unsigned", + "unsized", + "usampler1D", + "usampler1DArray", + "usampler2D", + "usampler2DArray", + "usampler2DMS", + "usampler2DMSArray", + "usampler2DRect", + "usampler3D", + "usamplerBuffer", + "usamplerCube", + "usamplerCubeArray", + "use", + "using", + "usubpassInput", + "usubpassInputMS", + "utexture1D", + "utexture1DArray", + "utexture2D", + "utexture2DArray", + "utexture2DMS", + "utexture2DMSArray", + "utexture2DRect", + "utexture3D", + "utextureBuffer", + "utextureCube", + "utextureCubeArray", + "varying", + "vec", + "vector", + "vertexfragment", + "virtual", + "void", + "volatile", + "wchar_t", + "wgsl", + "where", + "with", + "writeonly", + "yield", +]; From abc4e1572affc9f0e12fa446c5f7f9a78652c1a9 Mon Sep 17 00:00:00 2001 From: Max Ammann Date: Sat, 17 Sep 2022 21:39:34 +0200 Subject: [PATCH 1835/2212] Explicitely enable std, and don't rely on environment (#2062) --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index cbad28e8e..b74e8ad52 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,7 @@ termcolor = { version = "1.0.4", optional = true } # https://github.com/brendanzab/codespan/commit/e99c867339a877731437e7ee6a903a3d03b5439e codespan-reporting = { version = "0.11.0", optional = true } rustc-hash = "1.1.0" -indexmap = "1.6" +indexmap = { version = "1.6", features = ["std"] } log = "0.4" num-traits = "0.2" spirv = { version = "0.2", optional = true } From 0f26e5c808631d3d647a71f985274755d01edb6d Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 4 Oct 2022 14:19:41 +0300 Subject: [PATCH 1836/2212] [validate] Fix compiler warning --- src/valid/function.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index db66a0f6c..2107e71e0 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -863,7 +863,7 @@ impl super::Validator { fun: &crate::Function, module: &crate::Module, mod_info: &ModuleInfo, - entry_point: bool, + #[cfg_attr(not(feature = "validate"), allow(unused))] entry_point: bool, ) -> Result> { #[cfg_attr(not(feature = "validate"), allow(unused_mut))] let mut info = mod_info.process_function(fun, module, self.flags, self.capabilities)?; From e07fd981c208767fc00c78a6da162026b47835ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Wed, 5 Oct 2022 19:17:25 +0100 Subject: [PATCH 1837/2212] glsl-in: Update initializer list type when parsing (#2066) Previously when parsing an initializer list, the type passed to `parse_initializer` was not updated to reflect the child type, this caused implicit conversions to not work and nested initializer lists to not be allowed. --- src/front/glsl/parser/declarations.rs | 55 ++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 346d20b19..fe1c66e8f 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -19,6 +19,55 @@ use crate::{ use super::{DeclarationContext, ParsingContext, Result}; +/// Helper method used to retrieve the child type of `ty` at +/// index `i`. +/// +/// # Note +/// +/// Does not check if the index is valid and returns the same type +/// when indexing out-of-bounds a struct or indexing a non indexable +/// type. +fn element_or_member_type( + ty: Handle, + i: usize, + types: &mut crate::UniqueArena, +) -> Handle { + match types[ty].inner { + // The child type of a vector is a scalar of the same kind and width + TypeInner::Vector { kind, width, .. } => types.insert( + Type { + name: None, + inner: TypeInner::Scalar { kind, width }, + }, + Default::default(), + ), + // The child type of a matrix is a vector of floats with the same + // width and the size of the matrix rows. + TypeInner::Matrix { rows, width, .. } => types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, + }, + }, + Default::default(), + ), + // The child type of an array is the base type of the array + TypeInner::Array { base, .. } => base, + // The child type of a struct at index `i` is the type of it's + // member at that same index. + // + // In case the index is out of bounds the same type is returned + TypeInner::Struct { ref members, .. } => { + members.get(i).map(|member| member.ty).unwrap_or(ty) + } + // The type isn't indexable, the same type is returned + _ => ty, + } +} + impl<'source> ParsingContext<'source> { pub fn parse_external_declaration( &mut self, @@ -68,8 +117,10 @@ impl<'source> ParsingContext<'source> { // initializer_list let mut components = Vec::new(); loop { - // TODO: Change type - components.push(self.parse_initializer(parser, ty, ctx, body)?.0); + // The type expected to be parsed inside the initializer list + let new_ty = element_or_member_type(ty, components.len(), &mut parser.module.types); + + components.push(self.parse_initializer(parser, new_ty, ctx, body)?.0); let token = self.bump(parser)?; match token.value { From c52d91023d43092323615fcc746162e478033f26 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Wed, 5 Oct 2022 17:04:49 -0400 Subject: [PATCH 1838/2212] Add changelog and bump version to 0.10 (#2077) --- CHANGELOG.md | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 2 +- cli/Cargo.toml | 4 ++-- 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bd561cef..edf7b878a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,56 @@ # Change Log +## v0.10 (2022-10-05) + +- Make termcolor dependency optional by @AldaronLau in https://github.com/gfx-rs/naga/pull/2014 +- Fix clippy lints for 1.63 by @JCapucho in https://github.com/gfx-rs/naga/pull/2026 +- Saturate by @evahop in https://github.com/gfx-rs/naga/pull/2025 +- Use `Option::as_deref` as appropriate. by @jimblandy in https://github.com/gfx-rs/naga/pull/2040 +- Explicitely enable std for indexmap by @maxammann in https://github.com/gfx-rs/naga/pull/2062 +- Fix compiler warning by @Gordon-F in https://github.com/gfx-rs/naga/pull/2074 + +API +- Implement `Clone` for `Module` by @daxpedda in https://github.com/gfx-rs/naga/pull/2013 +- Remove the glsl-validate feature by @JCapucho in https://github.com/gfx-rs/naga/pull/2045 + +DOCS +- Document arithmetic binary operation type rules. by @jimblandy in https://github.com/gfx-rs/naga/pull/2051 + +VALIDATOR +- Add `emit_to_{stderr,string}` helpers to validation error by @nolanderc in https://github.com/gfx-rs/naga/pull/2012 +- Check regular functions don't have bindings by @JCapucho in https://github.com/gfx-rs/naga/pull/2050 + +WGSL-IN +- Update reserved WGSL keywords by @norepimorphism in https://github.com/gfx-rs/naga/pull/2009 +- Implement lexical scopes by @JCapucho in https://github.com/gfx-rs/naga/pull/2024 +- Rename `Scope` to `Rule`, since we now have lexical scope. by @jimblandy in https://github.com/gfx-rs/naga/pull/2042 +- Splat on compound assignments by @JCapucho in https://github.com/gfx-rs/naga/pull/2049 +- Fix bad span in assignment lhs error by @JCapucho in https://github.com/gfx-rs/naga/pull/2054 +- Fix inclusion of trivia in spans by @SparkyPotato in https://github.com/gfx-rs/naga/pull/2055 +- Improve assignment diagnostics by @SparkyPotato in https://github.com/gfx-rs/naga/pull/2056 +- Break up long string, reformat rest of file. by @jimblandy in https://github.com/gfx-rs/naga/pull/2057 +- Fix line endings on wgsl reserved words list. by @jimblandy in https://github.com/gfx-rs/naga/pull/2059 + +GLSL-IN +- Add support for .length() by @SpaceCat-Chan in https://github.com/gfx-rs/naga/pull/2017 +- Fix missing stores for local declarations by @adeline-sparks in https://github.com/gfx-rs/naga/pull/2029 +- Migrate to `SymbolTable` by @JCapucho in https://github.com/gfx-rs/naga/pull/2044 +- Update initializer list type when parsing by @JCapucho in https://github.com/gfx-rs/naga/pull/2066 + +SPV-OUT +- Don't decorate varyings with interpolation modes at pipeline start/end by @nical in https://github.com/gfx-rs/naga/pull/2038 +- Decorate integer builtins as Flat in the spirv writer by @nical in https://github.com/gfx-rs/naga/pull/2035 +- Properly combine the fixes for #2035 and #2038. by @jimblandy in https://github.com/gfx-rs/naga/pull/2041 +- Don't emit no-op `OpBitCast` instructions. by @jimblandy in https://github.com/gfx-rs/naga/pull/2043 + +HLSL-OUT +- Use the namer to sanitise entrypoint input/output struct names by @expenses in https://github.com/gfx-rs/naga/pull/2001 +- Handle Unpack2x16float in hlsl by @expenses in https://github.com/gfx-rs/naga/pull/2002 +- Add support for push constants by @JCapucho in https://github.com/gfx-rs/naga/pull/2005 + +DOT-OUT +- Improvements by @JCapucho in https://github.com/gfx-rs/naga/pull/1987 + ## v0.9 (2022-06-30) - Fix minimal-versions of dependencies ([#1840](https://github.com/gfx-rs/naga/pull/1840)) **@teoxoy** diff --git a/Cargo.toml b/Cargo.toml index b74e8ad52..c441b6e62 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.9.0" +version = "0.10.0" authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" diff --git a/cli/Cargo.toml b/cli/Cargo.toml index daf169f42..02e563772 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga-cli" -version = "0.9.0" +version = "0.10.0" authors = ["Naga Developers"] edition = "2018" description = "Shader translation command line tool" @@ -14,7 +14,7 @@ name = "naga" path = "src/main.rs" [dependencies] -naga = { version = "0.9", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } +naga = { version = "0.10", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } bincode = "1" log = "0.4" codespan-reporting = "0.11" From a7193d652e49180661a6ca047889e0685667acdb Mon Sep 17 00:00:00 2001 From: Sludge <96552222+SludgePhD@users.noreply.github.com> Date: Fri, 7 Oct 2022 01:39:41 +0200 Subject: [PATCH 1839/2212] Fix repository link pointing to the 0.9 branch (#2078) --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index c441b6e62..c951456a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Naga Developers"] edition = "2018" description = "Shader translation infrastructure" homepage = "https://github.com/gfx-rs/naga" -repository = "https://github.com/gfx-rs/naga/tree/v0.9" +repository = "https://github.com/gfx-rs/naga" keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] From 20d5445cb7f0cd9fa614c926173d57d420afccc2 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Thu, 20 Oct 2022 01:37:35 -0400 Subject: [PATCH 1840/2212] Workaround FXC Bug in Matrix Indexing (#2096) --- src/back/hlsl/writer.rs | 10 +++++++--- tests/out/hlsl/access.hlsl | 10 +++++----- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 42e306079..09cdeed48 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2085,14 +2085,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { index: u32, ) -> BackendResult { match *resolved { - TypeInner::Vector { .. } => { + // We specifcally lift the ValuePointer to this case. While `[0]` is valid + // HLSL for any vector behind a value pointer, FXC completely miscompiles + // it and generates completely nonsensical DXBC. + // + // See https://github.com/gfx-rs/naga/issues/2095 for more details. + TypeInner::Vector { .. } | TypeInner::ValuePointer { .. } => { // Write vector access as a swizzle write!(writer.out, ".{}", back::COMPONENTS[index as usize])? } TypeInner::Matrix { .. } | TypeInner::Array { .. } - | TypeInner::BindingArray { .. } - | TypeInner::ValuePointer { .. } => write!(writer.out, "[{}]", index)?, + | TypeInner::BindingArray { .. } => write!(writer.out, "[{}]", index)?, TypeInner::Struct { .. } => { // This will never panic in case the type is a `Struct`, this is not true // for other types so we can only check while inside this match arm diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 5510ec05b..4402cfdf8 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -147,11 +147,11 @@ void test_matrix_within_struct_accesses() float2 unnamed_1 = GetMatmOnBaz(baz)[0]; int _expr16 = idx; float2 unnamed_2 = GetMatmOnBaz(baz)[_expr16]; - float unnamed_3 = GetMatmOnBaz(baz)[0][1]; + float unnamed_3 = GetMatmOnBaz(baz)[0].y; int _expr28 = idx; float unnamed_4 = GetMatmOnBaz(baz)[0][_expr28]; int _expr32 = idx; - float unnamed_5 = GetMatmOnBaz(baz)[_expr32][1]; + float unnamed_5 = GetMatmOnBaz(baz)[_expr32].y; int _expr38 = idx; int _expr40 = idx; float unnamed_6 = GetMatmOnBaz(baz)[_expr38][_expr40]; @@ -191,11 +191,11 @@ void test_matrix_within_array_within_struct_accesses() float2 unnamed_9 = nested_mat_cx2_.am[0]._0; int _expr25 = idx_1; float2 unnamed_10 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr25); - float unnamed_11 = nested_mat_cx2_.am[0]._0[1]; + float unnamed_11 = nested_mat_cx2_.am[0]._0.y; int _expr41 = idx_1; float unnamed_12 = nested_mat_cx2_.am[0]._0[_expr41]; int _expr47 = idx_1; - float unnamed_13 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr47)[1]; + float unnamed_13 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr47).y; int _expr55 = idx_1; int _expr57 = idx_1; float unnamed_14 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr55)[_expr57]; @@ -207,7 +207,7 @@ void test_matrix_within_array_within_struct_accesses() t_1.am[0]._0 = (9.0).xx; int _expr90 = idx_1; __set_col_of_mat4x2(t_1.am[0], _expr90, (90.0).xx); - t_1.am[0]._0[1] = 10.0; + t_1.am[0]._0.y = 10.0; int _expr107 = idx_1; t_1.am[0]._0[_expr107] = 20.0; int _expr113 = idx_1; From 2754a0136ecd4d371af5a85fc715c9f8f4c64fc1 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Thu, 20 Oct 2022 02:13:05 -0400 Subject: [PATCH 1841/2212] [hlsl-out] Fix storage access chain through a matrix --- src/back/hlsl/storage.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 65edc9202..439715045 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -400,8 +400,10 @@ impl super::Writer<'_, W> { crate::TypeInner::Vector { width, .. } => Parent::Array { stride: width as u32, }, - crate::TypeInner::Matrix { columns, width, .. } => Parent::Array { - stride: Alignment::from(columns) * width as u32, + crate::TypeInner::Matrix { rows, width, .. } => Parent::Array { + // The stride between matrices is the count of rows as this is how + // long each column is. + stride: Alignment::from(rows) * width as u32, }, _ => unreachable!(), }, From d974f2f832681366e9e6d99c4c3b0096b37efcdd Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Thu, 20 Oct 2022 02:27:30 -0400 Subject: [PATCH 1842/2212] [hlsl-out] Properly implement bitcast --- src/back/hlsl/writer.rs | 64 +++++++++++++++--------------- tests/out/hlsl/bitcast.hlsl | 43 ++++++++++++++++++++ tests/out/hlsl/bitcast.hlsl.config | 3 ++ tests/out/hlsl/operators.hlsl | 8 ++-- tests/snapshots.rs | 2 +- 5 files changed, 84 insertions(+), 36 deletions(-) create mode 100644 tests/out/hlsl/bitcast.hlsl create mode 100644 tests/out/hlsl/bitcast.hlsl.config diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 09cdeed48..e29d2c41d 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2404,39 +2404,41 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { convert, } => { let inner = func_ctx.info[expr].ty.inner_with(&module.types); - let get_width = |src_width| kind.to_hlsl_str(convert.unwrap_or(src_width)); - match *inner { - TypeInner::Vector { size, width, .. } => { - write!( - self.out, - "{}{}(", - get_width(width)?, - back::vector_size_str(size) - )?; + match convert { + Some(dst_width) => { + match *inner { + TypeInner::Vector { size, .. } => { + write!( + self.out, + "{}{}(", + kind.to_hlsl_str(dst_width)?, + back::vector_size_str(size) + )?; + } + TypeInner::Scalar { .. } => { + write!(self.out, "{}(", kind.to_hlsl_str(dst_width)?,)?; + } + TypeInner::Matrix { columns, rows, .. } => { + write!( + self.out, + "{}{}x{}(", + kind.to_hlsl_str(dst_width)?, + back::vector_size_str(columns), + back::vector_size_str(rows) + )?; + } + _ => { + return Err(Error::Unimplemented(format!( + "write_expr expression::as {:?}", + inner + ))); + } + }; } - TypeInner::Scalar { width, .. } => { - write!(self.out, "{}(", get_width(width)?,)?; + None => { + write!(self.out, "{}(", kind.to_hlsl_cast(),)?; } - TypeInner::Matrix { - columns, - rows, - width, - } => { - write!( - self.out, - "{}{}x{}(", - get_width(width)?, - back::vector_size_str(columns), - back::vector_size_str(rows) - )?; - } - _ => { - return Err(Error::Unimplemented(format!( - "write_expr expression::as {:?}", - inner - ))); - } - }; + } self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")?; } diff --git a/tests/out/hlsl/bitcast.hlsl b/tests/out/hlsl/bitcast.hlsl new file mode 100644 index 000000000..eda86b0ab --- /dev/null +++ b/tests/out/hlsl/bitcast.hlsl @@ -0,0 +1,43 @@ + +[numthreads(1, 1, 1)] +void main() +{ + int2 i2_ = (int2)0; + int3 i3_ = (int3)0; + int4 i4_ = (int4)0; + uint2 u2_ = (uint2)0; + uint3 u3_ = (uint3)0; + uint4 u4_ = (uint4)0; + float2 f2_ = (float2)0; + float3 f3_ = (float3)0; + float4 f4_ = (float4)0; + + i2_ = (0).xx; + i3_ = (0).xxx; + i4_ = (0).xxxx; + u2_ = (0u).xx; + u3_ = (0u).xxx; + u4_ = (0u).xxxx; + f2_ = (0.0).xx; + f3_ = (0.0).xxx; + f4_ = (0.0).xxxx; + int2 _expr27 = i2_; + u2_ = asuint(_expr27); + int3 _expr29 = i3_; + u3_ = asuint(_expr29); + int4 _expr31 = i4_; + u4_ = asuint(_expr31); + uint2 _expr33 = u2_; + i2_ = asint(_expr33); + uint3 _expr35 = u3_; + i3_ = asint(_expr35); + uint4 _expr37 = u4_; + i4_ = asint(_expr37); + int2 _expr39 = i2_; + f2_ = asfloat(_expr39); + int3 _expr41 = i3_; + f3_ = asfloat(_expr41); + int4 _expr43 = i4_; + f4_ = asfloat(_expr43); + return; +} diff --git a/tests/out/hlsl/bitcast.hlsl.config b/tests/out/hlsl/bitcast.hlsl.config new file mode 100644 index 000000000..246c485cf --- /dev/null +++ b/tests/out/hlsl/bitcast.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 48e8fee09..62e028f80 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -31,8 +31,8 @@ float4 builtins() float4 s3_ = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); - float b1_ = float(int4(1, 1, 1, 1).x); - float4 b2_ = float4(int4(1, 1, 1, 1)); + float b1_ = asfloat(int4(1, 1, 1, 1).x); + float4 b2_ = asfloat(int4(1, 1, 1, 1)); int4 v_i32_zero = int4(float4(0.0, 0.0, 0.0, 0.0)); return (((((float4(((s1_).xxxx + v_i32_zero)) + s2_) + m1_) + m2_) + (b1_).xxxx) + b2_); } @@ -87,8 +87,8 @@ float constructors() float unnamed_6 = float(0.0); uint2 unnamed_7 = uint2(uint2(0u, 0u)); float2x3 unnamed_8 = float2x3(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - uint2 unnamed_9 = uint2(uint2(0u, 0u)); - float2x3 unnamed_10 = float2x3(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + uint2 unnamed_9 = asuint(uint2(0u, 0u)); + float2x3 unnamed_10 = asfloat(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); float _expr75 = foo.a.x; return _expr75; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 59a3e314b..cebeade8f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -443,7 +443,7 @@ fn convert_wgsl() { ), ( "bitcast", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "boids", From ddcd5d3121150b2b1beee6e54e9125ff31aaa9a2 Mon Sep 17 00:00:00 2001 From: Raph Levien Date: Mon, 24 Oct 2022 09:20:57 -0700 Subject: [PATCH 1843/2212] Fix incorrect atomic bounds check on metal back-end (#2099) * Fix incorrect atomic bounds check on metal back-end Generalize put_atomic_fetch to handle `exchange` as well, rather than special-cased code which didn't do the bounds check (the check handling as fixed in #1703 but only for the fetch cases, exchange was skipped). Fixes #1848 * Add tests for atomic exchange --- src/back/msl/writer.rs | 29 ++++++++++++++-------- tests/in/bounds-check-zero-atomic.wgsl | 13 ++++++++++ tests/out/msl/bounds-check-zero-atomic.msl | 26 +++++++++++++++++++ 3 files changed, 58 insertions(+), 10 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 9a59289be..a832c348a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1187,6 +1187,17 @@ impl Writer { key: &str, value: Handle, context: &ExpressionContext, + ) -> BackendResult { + self.put_atomic_operation(pointer, "fetch_", key, value, context) + } + + fn put_atomic_operation( + &mut self, + pointer: Handle, + key1: &str, + key2: &str, + value: Handle, + context: &ExpressionContext, ) -> BackendResult { // If the pointer we're passing to the atomic operation needs to be conditional // for `ReadZeroSkipWrite`, the condition needs to *surround* the atomic op, and @@ -1202,8 +1213,8 @@ impl Writer { write!( self.out, - "{}::atomic_fetch_{}_explicit({}", - NAMESPACE, key, ATOMIC_REFERENCE + "{}::atomic_{}{}_explicit({}", + NAMESPACE, key1, key2, ATOMIC_REFERENCE )?; self.put_access_chain(pointer, policy, context)?; write!(self.out, ", ")?; @@ -2725,15 +2736,13 @@ impl Writer { self.put_atomic_fetch(pointer, "max", value, &context.expression)?; } crate::AtomicFunction::Exchange { compare: None } => { - write!( - self.out, - "{}::atomic_exchange_explicit({}", - NAMESPACE, ATOMIC_REFERENCE, + self.put_atomic_operation( + pointer, + "exchange", + "", + value, + &context.expression, )?; - self.put_expression(pointer, &context.expression, true)?; - write!(self.out, ", ")?; - self.put_expression(value, &context.expression, true)?; - write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; } crate::AtomicFunction::Exchange { .. } => { return Err(Error::FeatureNotImplemented( diff --git a/tests/in/bounds-check-zero-atomic.wgsl b/tests/in/bounds-check-zero-atomic.wgsl index 3cdbea14a..004f08a0a 100644 --- a/tests/in/bounds-check-zero-atomic.wgsl +++ b/tests/in/bounds-check-zero-atomic.wgsl @@ -23,3 +23,16 @@ fn fetch_add_atomic_static_sized_array(i: i32) -> u32 { fn fetch_add_atomic_dynamic_sized_array(i: i32) -> u32 { return atomicAdd(&globals.c[i], 1u); } + +fn exchange_atomic() -> u32 { + return atomicExchange(&globals.a, 1u); +} + +fn exchange_atomic_static_sized_array(i: i32) -> u32 { + return atomicExchange(&globals.b[i], 1u); +} + +fn exchange_atomic_dynamic_sized_array(i: i32) -> u32 { + return atomicExchange(&globals.c[i], 1u); +} + diff --git a/tests/out/msl/bounds-check-zero-atomic.msl b/tests/out/msl/bounds-check-zero-atomic.msl index c76ba1b54..95028ee79 100644 --- a/tests/out/msl/bounds-check-zero-atomic.msl +++ b/tests/out/msl/bounds-check-zero-atomic.msl @@ -49,3 +49,29 @@ uint fetch_add_atomic_dynamic_sized_array( uint _e5 = uint(i_1) < 1 + (_buffer_sizes.size0 - 44 - 4) / 4 ? metal::atomic_fetch_add_explicit(&globals.c[i_1], 1u, metal::memory_order_relaxed) : DefaultConstructible(); return _e5; } + +uint exchange_atomic( + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + uint _e3 = metal::atomic_exchange_explicit(&globals.a, 1u, metal::memory_order_relaxed); + return _e3; +} + +uint exchange_atomic_static_sized_array( + int i_2, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + uint _e5 = uint(i_2) < 10 ? metal::atomic_exchange_explicit(&globals.b.inner[i_2], 1u, metal::memory_order_relaxed) : DefaultConstructible(); + return _e5; +} + +uint exchange_atomic_dynamic_sized_array( + int i_3, + device Globals& globals, + constant _mslBufferSizes& _buffer_sizes +) { + uint _e5 = uint(i_3) < 1 + (_buffer_sizes.size0 - 44 - 4) / 4 ? metal::atomic_exchange_explicit(&globals.c[i_3], 1u, metal::memory_order_relaxed) : DefaultConstructible(); + return _e5; +} From 2a11d830bb8a4965758cab787196322de4f24e19 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Tue, 25 Oct 2022 05:38:44 -1000 Subject: [PATCH 1844/2212] refactor: factor out new `Validator::global_var_ty` for expr. validation (#2086) --- src/valid/expression.rs | 131 ++++++++++------------------------------ 1 file changed, 31 insertions(+), 100 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 0f173707f..eb95c0e09 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -346,57 +346,9 @@ impl super::Validator { depth_ref, } => { // check the validity of expressions - let image_ty = match function.expressions[image] { - crate::Expression::GlobalVariable(var_handle) => { - module.global_variables[var_handle].ty - } - crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, - crate::Expression::Access { base, .. } - | crate::Expression::AccessIndex { base, .. } => { - match function.expressions[base] { - crate::Expression::GlobalVariable(var_handle) => { - let array_ty = module.global_variables[var_handle].ty; + let image_ty = Self::global_var_ty(module, function, image)?; + let sampler_ty = Self::global_var_ty(module, function, sampler)?; - match module.types[array_ty].inner { - Ti::BindingArray { base, .. } => base, - _ => { - return Err(ExpressionError::ExpectedBindingArrayType( - array_ty, - )) - } - } - } - _ => return Err(ExpressionError::ExpectedGlobalVariable), - } - } - _ => return Err(ExpressionError::ExpectedGlobalVariable), - }; - - let sampler_ty = match function.expressions[sampler] { - crate::Expression::GlobalVariable(var_handle) => { - module.global_variables[var_handle].ty - } - crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, - crate::Expression::Access { base, .. } - | crate::Expression::AccessIndex { base, .. } => { - match function.expressions[base] { - crate::Expression::GlobalVariable(var_handle) => { - let array_ty = module.global_variables[var_handle].ty; - - match module.types[array_ty].inner { - Ti::BindingArray { base, .. } => base, - _ => { - return Err(ExpressionError::ExpectedBindingArrayType( - array_ty, - )) - } - } - } - _ => return Err(ExpressionError::ExpectedGlobalVariable), - } - } - _ => return Err(ExpressionError::ExpectedGlobalVariable), - }; let comparison = match module.types[sampler_ty].inner { Ti::Sampler { comparison } => comparison, _ => return Err(ExpressionError::ExpectedSamplerType(sampler_ty)), @@ -579,31 +531,7 @@ impl super::Validator { sample, level, } => { - let ty = match function.expressions[image] { - crate::Expression::GlobalVariable(var_handle) => { - module.global_variables[var_handle].ty - } - crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, - crate::Expression::Access { base, .. } - | crate::Expression::AccessIndex { base, .. } => { - match function.expressions[base] { - crate::Expression::GlobalVariable(var_handle) => { - let array_ty = module.global_variables[var_handle].ty; - - match module.types[array_ty].inner { - Ti::BindingArray { base, .. } => base, - _ => { - return Err(ExpressionError::ExpectedBindingArrayType( - array_ty, - )) - } - } - } - _ => return Err(ExpressionError::ExpectedGlobalVariable), - } - } - _ => return Err(ExpressionError::ExpectedGlobalVariable), - }; + let ty = Self::global_var_ty(module, function, image)?; match module.types[ty].inner { Ti::Image { class, @@ -662,31 +590,7 @@ impl super::Validator { ShaderStages::all() } E::ImageQuery { image, query } => { - let ty = match function.expressions[image] { - crate::Expression::GlobalVariable(var_handle) => { - module.global_variables[var_handle].ty - } - crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty, - crate::Expression::Access { base, .. } - | crate::Expression::AccessIndex { base, .. } => { - match function.expressions[base] { - crate::Expression::GlobalVariable(var_handle) => { - let array_ty = module.global_variables[var_handle].ty; - - match module.types[array_ty].inner { - Ti::BindingArray { base, .. } => base, - _ => { - return Err(ExpressionError::ExpectedBindingArrayType( - array_ty, - )) - } - } - } - _ => return Err(ExpressionError::ExpectedGlobalVariable), - } - } - _ => return Err(ExpressionError::ExpectedGlobalVariable), - }; + let ty = Self::global_var_ty(module, function, image)?; match module.types[ty].inner { Ti::Image { class, arrayed, .. } => { let good = match query { @@ -1518,4 +1422,31 @@ impl super::Validator { }; Ok(stages) } + + fn global_var_ty( + module: &crate::Module, + function: &crate::Function, + expr: Handle, + ) -> Result, ExpressionError> { + use crate::Expression as Ex; + + match function.expressions[expr] { + Ex::GlobalVariable(var_handle) => Ok(module.global_variables[var_handle].ty), + Ex::FunctionArgument(i) => Ok(function.arguments[i as usize].ty), + Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => { + match function.expressions[base] { + Ex::GlobalVariable(var_handle) => { + let array_ty = module.global_variables[var_handle].ty; + + match module.types[array_ty].inner { + crate::TypeInner::BindingArray { base, .. } => Ok(base), + _ => Err(ExpressionError::ExpectedBindingArrayType(array_ty)), + } + } + _ => Err(ExpressionError::ExpectedGlobalVariable), + } + } + _ => Err(ExpressionError::ExpectedGlobalVariable), + } + } } From b37dda8854d63b9a9869624cfb6db31d504a04ff Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Tue, 25 Oct 2022 05:44:17 -1000 Subject: [PATCH 1845/2212] build: move to the Rust 2021 edition (#2085) * build: move to the Rust 2021 edition Since the MSRV of `naga` [is currently 1.56][msrv], I don't think there's a strong reason to stay with the 2018 edition, and there _are_ a [few good reasons][edition-guide] to move to the 2021 edition. I did this migration mostly automatically, per [official Rust guidelines]: ```sh $ cargo fix --edition --all-targets $ sed -i Cargo.toml 's/2018/2021' $ cargo fix --edition-idioms --allow-dirty # doesn't change anything ``` The only manual edit needed to stymie a new warning introduced was the removal of the `TryFrom` import in several modules, since it's now in the 2021 prelude. [msrv]: https://github.com/gfx-rs/naga/blob/a7193d652e49180661a6ca047889e0685667acdb/.github/workflows/pipeline.yml#L14 [edition-guide]: https://doc.rust-lang.org/edition-guide/rust-2021/index.html [official Rust guidelines]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html#edition-migration * refactor(wgsl-in): use `pat` instead of `pat_param` again How we were using `pat` in the Rust 2018 edition is actually the use case that Rust 2021's `pat` fragment specifier is intended to satisfy. So, let's just use that! --- Cargo.toml | 2 +- cli/Cargo.toml | 2 +- src/arena.rs | 2 -- src/front/wgsl/number.rs | 17 +++++++---------- src/proc/mod.rs | 1 - 5 files changed, 9 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c951456a3..80a4915b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "naga" version = "0.10.0" authors = ["Naga Developers"] -edition = "2018" +edition = "2021" description = "Shader translation infrastructure" homepage = "https://github.com/gfx-rs/naga" repository = "https://github.com/gfx-rs/naga" diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 02e563772..6cc017e35 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -2,7 +2,7 @@ name = "naga-cli" version = "0.10.0" authors = ["Naga Developers"] -edition = "2018" +edition = "2021" description = "Shader translation command line tool" homepage = "https://github.com/gfx-rs/naga" repository = "https://github.com/gfx-rs/naga" diff --git a/src/arena.rs b/src/arena.rs index d21a786cb..5d5cf3793 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -96,8 +96,6 @@ impl Handle { /// Convert a `usize` index into a `Handle`. fn from_usize(index: usize) -> Self { - use std::convert::TryFrom; - let handle_index = u32::try_from(index + 1) .ok() .and_then(Index::new) diff --git a/src/front/wgsl/number.rs b/src/front/wgsl/number.rs index d7e8801b0..fafe1d227 100644 --- a/src/front/wgsl/number.rs +++ b/src/front/wgsl/number.rs @@ -24,12 +24,9 @@ impl Number { /// lossy, return an error. fn abstract_to_concrete(self) -> Result { match self { - Number::AbstractInt(num) => { - use std::convert::TryFrom; - i32::try_from(num) - .map(Number::I32) - .map_err(|_| NumberError::NotRepresentable) - } + Number::AbstractInt(num) => i32::try_from(num) + .map(Number::I32) + .map_err(|_| NumberError::NotRepresentable), Number::AbstractFloat(num) => { let num = num as f32; if num.is_finite() { @@ -94,9 +91,9 @@ fn parse(input: &str) -> (Result, &str) { /// returns `true` and consumes `X` bytes from the given byte buffer /// if the given `X` nr of patterns are found at the start of the buffer macro_rules! consume { - ($bytes:ident, $($($pattern:pat)|*),*) => { + ($bytes:ident, $($pattern:pat),*) => { match $bytes { - &[$($($pattern)|*),*, ref rest @ ..] => { $bytes = rest; true }, + &[$($pattern),*, ref rest @ ..] => { $bytes = rest; true }, _ => false, } }; @@ -106,9 +103,9 @@ fn parse(input: &str) -> (Result, &str) { /// if one of the given patterns are found at the start of the buffer /// returning the corresponding expr for the matched pattern macro_rules! consume_map { - ($bytes:ident, [$($($pattern:pat)|* => $to:expr),*]) => { + ($bytes:ident, [$($pattern:pat_param => $to:expr),*]) => { match $bytes { - $( &[$($pattern)|*, ref rest @ ..] => { $bytes = rest; Some($to) }, )* + $( &[$pattern, ref rest @ ..] => { $bytes = rest; Some($to) }, )* _ => None, } }; diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 0b9f406af..a5731de89 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -389,7 +389,6 @@ impl crate::Constant { /// `OpArrayType` referring to an inappropriate `OpConstant`). So we return /// `Option` and let the caller sort things out. pub(crate) fn to_array_length(&self) -> Option { - use std::convert::TryInto; match self.inner { crate::ConstantInner::Scalar { value, width: _ } => match value { crate::ScalarValue::Uint(value) => value.try_into().ok(), From 469272c6130a5c88bc2231c8b7ec2641e0449d1e Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Tue, 25 Oct 2022 17:06:59 -0600 Subject: [PATCH 1846/2212] refactor(valid): s/error/source member name for `ValidationError` --- src/valid/analyzer.rs | 12 ++++---- src/valid/function.rs | 26 ++++++++--------- src/valid/mod.rs | 39 +++++++++++-------------- tests/wgsl-errors.rs | 66 +++++++++++++++++++++---------------------- 4 files changed, 68 insertions(+), 75 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 3f13aba32..ec8e9d96e 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -365,8 +365,8 @@ impl FunctionInfo { GlobalOrArgument::Argument(i) => { let handle = arguments[i as usize]; GlobalOrArgument::from_expression(expression_arena, handle).map_err( - |error| { - FunctionError::Expression { handle, error } + |source| { + FunctionError::Expression { handle, source } .with_span_handle(handle, expression_arena) }, )? @@ -378,8 +378,8 @@ impl FunctionInfo { GlobalOrArgument::Argument(i) => { let handle = arguments[i as usize]; GlobalOrArgument::from_expression(expression_arena, handle).map_err( - |error| { - FunctionError::Expression { handle, error } + |source| { + FunctionError::Expression { handle, source } .with_span_handle(handle, expression_arena) }, )? @@ -956,7 +956,7 @@ impl ModuleInfo { }; for (handle, expr) in fun.expressions.iter() { - if let Err(error) = info.process_expression( + if let Err(source) = info.process_expression( handle, expr, &fun.expressions, @@ -964,7 +964,7 @@ impl ModuleInfo { &resolve_context, capabilities, ) { - return Err(FunctionError::Expression { handle, error } + return Err(FunctionError::Expression { handle, source } .with_span_handle(handle, &fun.expressions)); } } diff --git a/src/valid/function.rs b/src/valid/function.rs index 2107e71e0..5684f670f 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -23,8 +23,7 @@ pub enum CallError { #[error("Argument {index} expression is invalid")] Argument { index: usize, - #[source] - error: ExpressionError, + source: ExpressionError, }, #[error("Result expression {0:?} has already been introduced earlier")] ResultAlreadyInScope(Handle), @@ -72,8 +71,7 @@ pub enum FunctionError { #[error("Expression {handle:?} is invalid")] Expression { handle: Handle, - #[source] - error: ExpressionError, + source: ExpressionError, }, #[error("Expression {0:?} can't be introduced - it's already in scope")] ExpressionAlreadyInScope(Handle), @@ -81,8 +79,7 @@ pub enum FunctionError { LocalVariable { handle: Handle, name: String, - #[source] - error: LocalVariableError, + source: LocalVariableError, }, #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")] InvalidArgumentType { index: usize, name: String }, @@ -230,7 +227,7 @@ impl<'a> BlockContext<'a> { valid_expressions: &BitSet, ) -> Result<&crate::TypeInner, WithSpan> { self.resolve_type_impl(handle, valid_expressions) - .map_err_inner(|error| FunctionError::Expression { handle, error }.with_span()) + .map_err_inner(|source| FunctionError::Expression { handle, source }.with_span()) } fn resolve_pointer_type( @@ -240,7 +237,7 @@ impl<'a> BlockContext<'a> { if handle.index() >= self.expressions.len() { Err(FunctionError::Expression { handle, - error: ExpressionError::DoesntExist, + source: ExpressionError::DoesntExist, }) } else { Ok(self.info[handle].ty.inner_with(self.types)) @@ -272,8 +269,9 @@ impl super::Validator { for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() { let ty = context .resolve_type_impl(expr, &self.valid_expression_set) - .map_err_inner(|error| { - CallError::Argument { index, error }.with_span_handle(expr, context.expressions) + .map_err_inner(|source| { + CallError::Argument { index, source } + .with_span_handle(expr, context.expressions) })?; let arg_inner = &context.types[arg.ty].inner; if !ty.equivalent(arg_inner, context.types) { @@ -871,11 +869,11 @@ impl super::Validator { #[cfg(feature = "validate")] for (var_handle, var) in fun.local_variables.iter() { self.validate_local_var(var, &module.types, &module.constants) - .map_err(|error| { + .map_err(|source| { FunctionError::LocalVariable { handle: var_handle, name: var.name.clone().unwrap_or_default(), - error, + source, } .with_span_handle(var.ty, &module.types) .with_handle(var_handle, &fun.local_variables) @@ -956,8 +954,8 @@ impl super::Validator { &mod_info.functions, ) { Ok(stages) => info.available_stages &= stages, - Err(error) => { - return Err(FunctionError::Expression { handle, error } + Err(source) => { + return Err(FunctionError::Expression { handle, source } .with_span_handle(handle, &fun.expressions)) } } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index b746f6abd..be2731629 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -163,36 +163,31 @@ pub enum ValidationError { Type { handle: Handle, name: String, - #[source] - error: TypeError, + source: TypeError, }, #[error("Constant {handle:?} '{name}' is invalid")] Constant { handle: Handle, name: String, - #[source] - error: ConstantError, + source: ConstantError, }, #[error("Global variable {handle:?} '{name}' is invalid")] GlobalVariable { handle: Handle, name: String, - #[source] - error: GlobalVariableError, + source: GlobalVariableError, }, #[error("Function {handle:?} '{name}' is invalid")] Function { handle: Handle, name: String, - #[source] - error: FunctionError, + source: FunctionError, }, #[error("Entry point {name} at {stage:?} is invalid")] EntryPoint { stage: crate::ShaderStage, name: String, - #[source] - error: EntryPointError, + source: EntryPointError, }, #[error("Module is corrupted")] Corrupted, @@ -329,11 +324,11 @@ impl Validator { if self.flags.contains(ValidationFlags::CONSTANTS) { for (handle, constant) in module.constants.iter() { self.validate_constant(handle, &module.constants, &module.types) - .map_err(|error| { + .map_err(|source| { ValidationError::Constant { handle, name: constant.name.clone().unwrap_or_default(), - error, + source, } .with_span_handle(handle, &module.constants) })? @@ -343,11 +338,11 @@ impl Validator { for (handle, ty) in module.types.iter() { let ty_info = self .validate_type(handle, &module.types, &module.constants) - .map_err(|error| { + .map_err(|source| { ValidationError::Type { handle, name: ty.name.clone().unwrap_or_default(), - error, + source, } .with_span_handle(handle, &module.types) })?; @@ -357,11 +352,11 @@ impl Validator { #[cfg(feature = "validate")] for (var_handle, var) in module.global_variables.iter() { self.validate_global_var(var, &module.types) - .map_err(|error| { + .map_err(|source| { ValidationError::GlobalVariable { handle: var_handle, name: var.name.clone().unwrap_or_default(), - error, + source, } .with_span_handle(var_handle, &module.global_variables) })?; @@ -376,11 +371,11 @@ impl Validator { match self.validate_function(fun, module, &mod_info, false) { Ok(info) => mod_info.functions.push(info), Err(error) => { - return Err(error.and_then(|error| { + return Err(error.and_then(|source| { ValidationError::Function { handle, name: fun.name.clone().unwrap_or_default(), - error, + source, } .with_span_handle(handle, &module.functions) })) @@ -394,7 +389,7 @@ impl Validator { return Err(ValidationError::EntryPoint { stage: ep.stage, name: ep.name.clone(), - error: EntryPointError::Conflict, + source: EntryPointError::Conflict, } .with_span()); // TODO: keep some EP span information? } @@ -402,14 +397,14 @@ impl Validator { match self.validate_entry_point(ep, module, &mod_info) { Ok(info) => mod_info.entry_points.push(info), Err(error) => { - return Err(error.and_then(|inner| { + return Err(error.and_then(|source| { ValidationError::EntryPoint { stage: ep.stage, name: ep.name.clone(), - error: inner, + source, } .with_span() - })) + })); } } } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 445459f3b..dd3e3dda6 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -929,7 +929,7 @@ fn invalid_arrays() { "type Bad = array;", "type Bad = array, 4>;": Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::InvalidArrayBaseType(_), + source: naga::valid::TypeError::InvalidArrayBaseType(_), .. }) } @@ -941,7 +941,7 @@ fn invalid_arrays() { type Bad = array; "#: Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::InvalidArraySizeConstant(_), + source: naga::valid::TypeError::InvalidArraySizeConstant(_), .. }) } @@ -950,7 +950,7 @@ fn invalid_arrays() { "type Bad = array;", "type Bad = array;": Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::NonPositiveArrayLength(_), + source: naga::valid::TypeError::NonPositiveArrayLength(_), .. }) } @@ -962,7 +962,7 @@ fn invalid_structs() { "struct Bad { data: sampler }", "struct Bad { data: texture_2d }": Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::InvalidData(_), + source: naga::valid::TypeError::InvalidData(_), .. }) } @@ -970,7 +970,7 @@ fn invalid_structs() { check_validation! { "struct Bad { data: array, other: f32, }": Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::InvalidDynamicArray(_, _), + source: naga::valid::TypeError::InvalidDynamicArray(_, _), .. }) } @@ -978,7 +978,7 @@ fn invalid_structs() { check_validation! { "struct Empty {}": Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::EmptyStruct, + source: naga::valid::TypeError::EmptyStruct, .. }) } @@ -994,7 +994,7 @@ fn invalid_functions() { ": Err(naga::valid::ValidationError::Function { name: function_name, - error: naga::valid::FunctionError::InvalidArgumentType { + source: naga::valid::FunctionError::InvalidArgumentType { index: 0, name: argument_name, }, @@ -1011,7 +1011,7 @@ fn invalid_functions() { fn unacceptable_unsized(arg: ptr) { } ": Err(naga::valid::ValidationError::Type { - error: naga::valid::TypeError::InvalidPointerToUnsized { + source: naga::valid::TypeError::InvalidPointerToUnsized { base: _, space: naga::AddressSpace::WorkGroup { .. }, }, @@ -1024,7 +1024,7 @@ fn invalid_functions() { "fn unacceptable_ptr_space(arg: ptr>) { }": Err(naga::valid::ValidationError::Function { name: function_name, - error: naga::valid::FunctionError::InvalidArgumentPointerSpace { + source: naga::valid::FunctionError::InvalidArgumentPointerSpace { index: 0, name: argument_name, space: naga::AddressSpace::Storage { .. }, @@ -1038,7 +1038,7 @@ fn invalid_functions() { "fn unacceptable_ptr_space(arg: ptr) { }": Err(naga::valid::ValidationError::Function { name: function_name, - error: naga::valid::FunctionError::InvalidArgumentPointerSpace { + source: naga::valid::FunctionError::InvalidArgumentPointerSpace { index: 0, name: argument_name, space: naga::AddressSpace::Uniform, @@ -1062,7 +1062,7 @@ fn invalid_functions() { ": Err(naga::valid::ValidationError::Function { name: function_name, - error: naga::valid::FunctionError::NonConstructibleReturnType, + source: naga::valid::FunctionError::NonConstructibleReturnType, .. }) if function_name == "return_pointer" @@ -1079,7 +1079,7 @@ fn invalid_functions() { ": Err(naga::valid::ValidationError::Function { name: function_name, - error: naga::valid::FunctionError::NonConstructibleReturnType, + source: naga::valid::FunctionError::NonConstructibleReturnType, .. }) if function_name == "return_atomic" @@ -1115,7 +1115,7 @@ fn missing_bindings() { ": Err(naga::valid::ValidationError::EntryPoint { stage: naga::ShaderStage::Vertex, - error: naga::valid::EntryPointError::Argument( + source: naga::valid::EntryPointError::Argument( 0, naga::valid::VaryingError::MissingBinding, ), @@ -1132,7 +1132,7 @@ fn missing_bindings() { ": Err(naga::valid::ValidationError::EntryPoint { stage: naga::ShaderStage::Vertex, - error: naga::valid::EntryPointError::Argument( + source: naga::valid::EntryPointError::Argument( 1, naga::valid::VaryingError::MissingBinding, ), @@ -1149,7 +1149,7 @@ fn missing_bindings() { ": Err(naga::valid::ValidationError::EntryPoint { stage: naga::ShaderStage::Vertex, - error: naga::valid::EntryPointError::Result( + source: naga::valid::EntryPointError::Result( naga::valid::VaryingError::MissingBinding, ), .. @@ -1170,7 +1170,7 @@ fn missing_bindings() { ": Err(naga::valid::ValidationError::EntryPoint { stage: naga::ShaderStage::Vertex, - error: naga::valid::EntryPointError::Argument( + source: naga::valid::EntryPointError::Argument( 0, naga::valid::VaryingError::MemberMissingBinding(1), ), @@ -1193,8 +1193,8 @@ fn invalid_access() { } ": Err(naga::valid::ValidationError::Function { - error: naga::valid::FunctionError::Expression { - error: naga::valid::ExpressionError::IndexMustBeConstant(_), + source: naga::valid::FunctionError::Expression { + source: naga::valid::ExpressionError::IndexMustBeConstant(_), .. }, .. @@ -1209,8 +1209,8 @@ fn invalid_access() { } "#: Err(naga::valid::ValidationError::Function { - error: naga::valid::FunctionError::Expression { - error: naga::valid::ExpressionError::IndexOutOfBounds(_, _), + source: naga::valid::FunctionError::Expression { + source: naga::valid::ExpressionError::IndexOutOfBounds(_, _), .. }, .. @@ -1255,9 +1255,9 @@ fn invalid_local_vars() { } ": Err(naga::valid::ValidationError::Function { - error: naga::valid::FunctionError::LocalVariable { + source: naga::valid::FunctionError::LocalVariable { name: local_var_name, - error: naga::valid::LocalVariableError::InvalidType(_), + source: naga::valid::LocalVariableError::InvalidType(_), .. }, .. @@ -1291,7 +1291,7 @@ fn dead_code() { } ": Err(naga::valid::ValidationError::Function { - error: naga::valid::FunctionError::InstructionsAfterReturn, + source: naga::valid::FunctionError::InstructionsAfterReturn, .. }) } @@ -1321,7 +1321,7 @@ fn invalid_runtime_sized_arrays() { ": Err(naga::valid::ValidationError::Type { name: struct_name, - error: naga::valid::TypeError::InvalidDynamicArray(member_name, _), + source: naga::valid::TypeError::InvalidDynamicArray(member_name, _), .. }) if struct_name == "Outer" && member_name == "_unsized" @@ -1359,8 +1359,8 @@ fn select() { Err( naga::valid::ValidationError::Function { name, - error: naga::valid::FunctionError::Expression { - error: naga::valid::ExpressionError::InvalidSelectTypes, + source: naga::valid::FunctionError::Expression { + source: naga::valid::ExpressionError::InvalidSelectTypes, .. }, .. @@ -1385,7 +1385,7 @@ fn last_case_falltrough() { ": Err( naga::valid::ValidationError::Function { - error: naga::valid::FunctionError::LastCaseFallTrough, + source: naga::valid::FunctionError::LastCaseFallTrough, .. }, ) @@ -1404,7 +1404,7 @@ fn missing_default_case() { ": Err( naga::valid::ValidationError::Function { - error: naga::valid::FunctionError::MissingDefaultCase, + source: naga::valid::FunctionError::MissingDefaultCase, .. }, ) @@ -1443,7 +1443,7 @@ fn wrong_access_mode() { Err( naga::valid::ValidationError::Function { name, - error: naga::valid::FunctionError::InvalidStorePointer(_), + source: naga::valid::FunctionError::InvalidStorePointer(_), .. }, ) @@ -1485,7 +1485,7 @@ fn io_shareable_types() { naga::valid::ValidationError::EntryPoint { stage: naga::ShaderStage::Vertex, name, - error: naga::valid::EntryPointError::Argument( + source: naga::valid::EntryPointError::Argument( 0, naga::valid::VaryingError::NotIOShareableType( _, @@ -1538,7 +1538,7 @@ fn host_shareable_types() { naga::valid::ValidationError::GlobalVariable { name, handle: _, - error: naga::valid::GlobalVariableError::MissingTypeFlags { .. }, + source: naga::valid::GlobalVariableError::MissingTypeFlags { .. }, }, ) if name == "sbuf" @@ -1549,7 +1549,7 @@ fn host_shareable_types() { Err(naga::valid::ValidationError::GlobalVariable { name, handle: _, - error: naga::valid::GlobalVariableError::MissingTypeFlags { .. }, + source: naga::valid::GlobalVariableError::MissingTypeFlags { .. }, }, ) if name == "ubuf" @@ -1591,7 +1591,7 @@ fn break_if_bad_condition() { ": Err( naga::valid::ValidationError::Function { - error: naga::valid::FunctionError::InvalidIfType(_), + source: naga::valid::FunctionError::InvalidIfType(_), .. }, ) From df4e40327c280a038365fb3d4ec839353f06eed3 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Tue, 18 Oct 2022 21:50:57 -0400 Subject: [PATCH 1847/2212] refactor(wgsl-out): use `for` loop for function arg. writing --- src/back/wgsl/writer.rs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 0be7ef072..817fa78b0 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1609,15 +1609,7 @@ impl Writer { Function::Regular(fun_name) => { write!(self.out, "{}(", fun_name)?; self.write_expr(module, arg, func_ctx)?; - if let Some(arg) = arg1 { - write!(self.out, ", ")?; - self.write_expr(module, arg, func_ctx)?; - } - if let Some(arg) = arg2 { - write!(self.out, ", ")?; - self.write_expr(module, arg, func_ctx)?; - } - if let Some(arg) = arg3 { + for arg in IntoIterator::into_iter([arg1, arg2, arg3]).flatten() { write!(self.out, ", ")?; self.write_expr(module, arg, func_ctx)?; } From e7fc8e64f2f23397b149217ecce6e123c5aa5092 Mon Sep 17 00:00:00 2001 From: Xiaopeng Li Date: Thu, 27 Oct 2022 15:28:46 +0800 Subject: [PATCH 1848/2212] Fix textureGather compatibility on macOS 10.13 (#2104) * Fix textureGather compatibility on macOS 10.13 * Fix tests * Update src/back/msl/writer.rs Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Co-authored-by: Jet Spark Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> --- src/back/msl/writer.rs | 2 +- tests/out/msl/image.msl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a832c348a..9147fbe39 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1440,7 +1440,7 @@ impl Writer { // Offset always comes before the gather, except // in cube maps where it's not applicable if offset.is_none() && !is_cube_map { - write!(self.out, ", int2(0)")?; + write!(self.out, ", {}::int2(0)", NAMESPACE)?; } let letter = ['x', 'y', 'z', 'w'][component as usize]; write!(self.out, ", {}::component::{}", NAMESPACE, letter)?; diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 16839dfbe..df247be4f 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -144,7 +144,7 @@ fragment gatherOutput gather( , metal::depth2d image_2d_depth [[user(fake0)]] ) { metal::float2 tc_2 = metal::float2(0.5); - metal::float4 s2d_1 = image_2d.gather(sampler_reg, tc_2, int2(0), metal::component::y); + metal::float4 s2d_1 = image_2d.gather(sampler_reg, tc_2, metal::int2(0), metal::component::y); metal::float4 s2d_offset_1 = image_2d.gather(sampler_reg, tc_2, const_type_9_, metal::component::w); metal::float4 s2d_depth_1 = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5); metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, const_type_9_); From 21c709276229d051a74a76eb493f29c1e2cf2d07 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Thu, 3 Nov 2022 12:32:15 -0400 Subject: [PATCH 1849/2212] Satisfy latest `clippy` lints (up to Rust 1.64) (#2081) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: satisfy `clippy::borrow_deref_ref` * chore: satisfy `clippy::ptr_arg` * refactor: satisfy `clippy::needless_update` * chore: `allow(clippy::too_many_arguments)` on `write_output_glsl` test Since this is test code, I don't think there's a strong impetus to refactor types to consolidate or otherwise alter arguments here. Let's just `allow` this. * refactor: satisfy `clippy::single_match` I think it's sixes whether to keep this code as-is or to `allow(...)` as-is. 🤷🏻‍♂️ * refactor: satisfy `clippy::single_char_pattern` * refactor: satisfy `clippy::reversed_empty_ranges` The lint fires because it generally doesn't make sense to use a `Range` built this way; [upstream `Range` docs]) states: > It is empty if `start >= end`. `clippy` wants to help us from naively iterating over a `Range` like this! Thanks, `clippy`! However, we're not actually using the offending `addresses` variables for iteration. We're using them as a flat data structure with fields that happen to conceptually match. We can, therefore, sidestep this lint by "just" inlining into separate variables for start and end instead. [upstream `Range` docs]: https://doc.rust-lang.org/stable/std/ops/struct.Range.html * refactor: satisfy `clippy::pattern_type_mismatch` * chore: `allow(clippy::panic)` for `test` We definitely should let `panic!(...)` calls exist in `cfg(test)`! It's a very standard way to fail `#[test]` functions. It seems that previous test authors agree! 😅 * fixup! refactor: satisfy `clippy::pattern_type_mismatch` * fixup! refactor: satisfy `clippy::single_match` --- benches/criterion.rs | 16 +++++++--------- src/back/msl/writer.rs | 18 ++++++++++-------- src/front/glsl/constants.rs | 14 ++++++++++---- src/lib.rs | 2 +- tests/snapshots.rs | 19 +++++++++++-------- 5 files changed, 39 insertions(+), 30 deletions(-) diff --git a/benches/criterion.rs b/benches/criterion.rs index ee8765b92..81c55c70c 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -10,7 +10,7 @@ fn gather_inputs(folder: &str, extension: &str) -> Vec> { for file_entry in read_dir { match file_entry { Ok(entry) => match entry.path().extension() { - Some(ostr) if &*ostr == extension => { + Some(ostr) if ostr == extension => { let input = fs::read(entry.path()).unwrap_or_default(); list.push(input.into_boxed_slice()); } @@ -250,7 +250,9 @@ fn backends(c: &mut Criterion) { entry_point: ep.name.clone(), multiview: None, }; - match naga::back::glsl::Writer::new( + + // might be `Err` if missing features + if let Ok(mut writer) = naga::back::glsl::Writer::new( &mut string, module, info, @@ -258,13 +260,9 @@ fn backends(c: &mut Criterion) { &pipeline_options, naga::proc::BoundsCheckPolicies::default(), ) { - Ok(mut writer) => { - let _ = writer.write(); // can error if unsupported - } - Err(_) => { - // missing features - } - }; + let _ = writer.write(); // might be `Err` if unsupported + } + string.clear(); } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 9147fbe39..144ce0b40 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3955,12 +3955,13 @@ fn test_stack_size() { { // check expression stack - let mut addresses = usize::MAX..0usize; + let mut addresses_start = usize::MAX; + let mut addresses_end = 0usize; for pointer in writer.put_expression_stack_pointers { - addresses.start = addresses.start.min(pointer as usize); - addresses.end = addresses.end.max(pointer as usize); + addresses_start = addresses_start.min(pointer as usize); + addresses_end = addresses_end.max(pointer as usize); } - let stack_size = addresses.end - addresses.start; + let stack_size = addresses_end - addresses_start; // check the size (in debug only) // last observed macOS value: 20528 (CI) if !(11000..=25000).contains(&stack_size) { @@ -3970,12 +3971,13 @@ fn test_stack_size() { { // check block stack - let mut addresses = usize::MAX..0usize; + let mut addresses_start = usize::MAX; + let mut addresses_end = 0usize; for pointer in writer.put_block_stack_pointers { - addresses.start = addresses.start.min(pointer as usize); - addresses.end = addresses.end.max(pointer as usize); + addresses_start = addresses_start.min(pointer as usize); + addresses_end = addresses_end.max(pointer as usize); } - let stack_size = addresses.end - addresses.start; + let stack_size = addresses_end - addresses_start; // check the size (in debug only) // last observed macOS value: 19152 (CI) if !(9500..=20000).contains(&stack_size) { diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 03620ce51..9b30b9c37 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -739,8 +739,11 @@ mod tests { let res3_inner = &constants[res3].inner; - match res3_inner { - ConstantInner::Composite { ty, components } => { + match *res3_inner { + ConstantInner::Composite { + ref ty, + ref components, + } => { assert_eq!(*ty, vec_ty); let mut components_iter = components.iter().copied(); assert_eq!( @@ -933,8 +936,11 @@ mod tests { let res1_inner = &constants[res1].inner; - match res1_inner { - ConstantInner::Composite { ty, components } => { + match *res1_inner { + ConstantInner::Composite { + ref ty, + ref components, + } => { assert_eq!(*ty, vec_ty); let mut components_iter = components.iter().copied(); assert_eq!( diff --git a/src/lib.rs b/src/lib.rs index c4893b73a..c0f102670 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -202,7 +202,7 @@ tree. clippy::pattern_type_mismatch, clippy::missing_const_for_fn )] -#![deny(clippy::panic)] +#![cfg_attr(not(test), deny(clippy::panic))] mod arena; pub mod back; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index cebeade8f..197a29692 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -2,7 +2,10 @@ // the corresponding warnings aren't helpful. #![allow(dead_code)] -use std::{fs, path::PathBuf}; +use std::{ + fs, + path::{Path, PathBuf}, +}; const BASE_DIR_IN: &str = "tests/in"; const BASE_DIR_OUT: &str = "tests/out"; @@ -195,7 +198,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { fn write_output_spv( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, params: &SpirvOutParameters, bounds_check_policies: naga::proc::BoundsCheckPolicies, @@ -224,7 +227,6 @@ fn write_output_spv( }, bounds_check_policies, binding_map: params.binding_map.clone(), - ..spv::Options::default() }; if params.separate_entry_points { @@ -253,7 +255,7 @@ fn write_output_spv( fn write_output_msl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, options: &naga::back::msl::Options, pipeline_options: &naga::back::msl::PipelineOptions, @@ -278,10 +280,11 @@ fn write_output_msl( } #[cfg(feature = "glsl-out")] +#[allow(clippy::too_many_arguments)] fn write_output_glsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, stage: naga::ShaderStage, ep_name: &str, @@ -322,7 +325,7 @@ fn write_output_glsl( fn write_output_hlsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, options: &naga::back::hlsl::Options, ) { @@ -401,7 +404,7 @@ fn write_output_hlsl( fn write_output_wgsl( module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &PathBuf, + destination: &Path, file_name: &str, params: &WgslOutParameters, ) { @@ -676,7 +679,7 @@ fn convert_glsl_folder() { &module, &info, &dest, - &file_name.replace(".", "-"), + &file_name.replace('.', "-"), &WgslOutParameters::default(), ); } From 01fbdea21f6537c0db95e2a2a284e61598574f2c Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Thu, 3 Nov 2022 18:32:20 +0100 Subject: [PATCH 1850/2212] fix 1.65 clippy lints (#2112) --- src/back/hlsl/conv.rs | 3 +-- src/back/hlsl/help.rs | 11 +++++------ src/back/spv/image.rs | 2 +- src/front/glsl/mod.rs | 2 +- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 039bfcce3..3feb80bb6 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -73,7 +73,6 @@ impl crate::TypeInner { /// Used to generate the name of the wrapped type constructor pub(super) fn hlsl_type_id<'a>( - &self, base: crate::Handle, types: &crate::UniqueArena, constants: &crate::Arena, @@ -103,7 +102,7 @@ impl crate::TypeInner { } => Cow::Owned(format!( "array{}_{}_", constants[size].to_array_length().unwrap(), - self.hlsl_type_id(base, types, constants, names)? + Self::hlsl_type_id(base, types, constants, names)? )), crate::TypeInner::Struct { .. } => { Cow::Borrowed(&names[&crate::proc::NameKey::Type(base)]) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index ec913ba66..bea6220e7 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -274,7 +274,7 @@ impl<'a, W: Write> super::Writer<'a, W> { // Write function body writeln!(self.out, "{{")?; - let array_coords = if wiq.arrayed { 1 } else { 0 }; + let array_coords = usize::from(wiq.arrayed); // extra parameter is the mip level count or the sample count let extra_coords = match wiq.class { crate::ImageClass::Storage { .. } => 0, @@ -358,7 +358,7 @@ impl<'a, W: Write> super::Writer<'a, W> { module: &crate::Module, constructor: WrappedConstructor, ) -> BackendResult { - let name = module.types[constructor.ty].inner.hlsl_type_id( + let name = crate::TypeInner::hlsl_type_id( constructor.ty, &module.types, &module.constants, @@ -927,7 +927,7 @@ impl<'a, W: Write> super::Writer<'a, W> { if let Some(crate::AddressSpace::Storage { .. }) = pointer_space { if let Some(ty) = func_ctx.info[handle].ty.handle() { - write_wrapped_constructor(self, ty, module, func_ctx)?; + write_wrapped_constructor(self, ty, module)?; } } @@ -935,12 +935,11 @@ impl<'a, W: Write> super::Writer<'a, W> { writer: &mut super::Writer<'_, W>, ty: Handle, module: &crate::Module, - func_ctx: &FunctionCtx, ) -> BackendResult { match module.types[ty].inner { crate::TypeInner::Struct { ref members, .. } => { for member in members { - write_wrapped_constructor(writer, member.ty, module, func_ctx)?; + write_wrapped_constructor(writer, member.ty, module)?; } let constructor = WrappedConstructor { ty }; @@ -951,7 +950,7 @@ impl<'a, W: Write> super::Writer<'a, W> { } } crate::TypeInner::Array { base, .. } => { - write_wrapped_constructor(writer, base, module, func_ctx)?; + write_wrapped_constructor(writer, base, module)?; } _ => {} }; diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index e070cd617..e19da1485 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -1017,7 +1017,7 @@ impl<'w> BlockContext<'w> { Id::D3 => 3, }; let extended_size_type_id = { - let array_coords = if arrayed { 1 } else { 0 }; + let array_coords = usize::from(arrayed); let vector_size = match dim_coords + array_coords { 2 => Some(crate::VectorSize::Bi), 3 => Some(crate::VectorSize::Tri), diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index f28ff7b6e..0e0b503d3 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -105,7 +105,7 @@ impl ShaderMetadata { self.version = 0; self.profile = Profile::Core; self.stage = stage; - self.workgroup_size = [if stage == ShaderStage::Compute { 1 } else { 0 }; 3]; + self.workgroup_size = [u32::from(stage == ShaderStage::Compute); 3]; self.early_fragment_tests = false; self.extensions.clear(); } From 1650581fe7a94ed40067313f3cd205414dd4febf Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Fri, 4 Nov 2022 11:20:47 -0400 Subject: [PATCH 1851/2212] refactor(cli): simplify `output_paths` w/ `<&[T]>::get` and `Option::unwrap` (#2114) --- cli/src/main.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index f7a3f8312..b983473a1 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -231,11 +231,7 @@ fn run() -> Result<(), Box> { } else { return Err(CliError("Input file path is not specified").into()); }; - let output_paths = if !args.files.is_empty() { - &args.files[1..] - } else { - &[] - }; + let output_paths = args.files.get(1..).unwrap_or(&[]); // Update parameters from commandline arguments if let Some(bits) = args.validate { From e0568057840d38debc889d86f826b1ac67dd004d Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 16 Nov 2022 20:12:45 +0100 Subject: [PATCH 1852/2212] [msl-out] use back::COMPONENTS (#2124) --- src/back/msl/writer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 144ce0b40..bee66fc68 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1442,7 +1442,7 @@ impl Writer { if offset.is_none() && !is_cube_map { write!(self.out, ", {}::int2(0)", NAMESPACE)?; } - let letter = ['x', 'y', 'z', 'w'][component as usize]; + let letter = back::COMPONENTS[component as usize]; write!(self.out, ", {}::component::{}", NAMESPACE, letter)?; } } From aa22301b4b2fa22ae2c7521a38d16eb3533f3803 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Thu, 17 Nov 2022 05:43:56 -0500 Subject: [PATCH 1853/2212] Parenthesize unary negations to avoid `--` (#2087) * fix(glsl-out,hlsl-out,msl-out): parenthesize unary negations a la `wgsl` everywhere Unify parenthesization of unary negations across all backends with what the `wgsl` backend does, which is `()`. This avoids ambiguity with output languages for which `--` is a different operation; in this case, we've been accidentally emitting prefix decrements. * build: update `rspirv` 0.11 -> 0.12 (FIXME: use upstream release) * test: add `operators::negation_avoids_prefix_decrement` test Co-authored-by: Dzmitry Malyshau --- Cargo.toml | 2 +- src/back/glsl/mod.rs | 2 +- src/back/hlsl/writer.rs | 3 +- src/back/msl/writer.rs | 3 +- tests/in/operators.wgsl | 13 +- tests/out/glsl/operators.main.Compute.glsl | 24 +- tests/out/hlsl/operators.hlsl | 27 +- tests/out/msl/operators.msl | 27 +- tests/out/spv/operators.spvasm | 1136 ++++++++++---------- tests/out/wgsl/operators.wgsl | 10 + 10 files changed, 666 insertions(+), 581 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 80a4915b5..c9f589421 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,7 +73,7 @@ diff = "0.1" ron = "~0.7.1" serde = { version = "1.0", features = ["derive"] } spirv = { version = "0.2", features = ["deserialize"] } -rspirv = "0.11" +rspirv = { version = "0.11", git = "https://github.com/gfx-rs/rspirv", rev = "b969f175d5663258b4891e44b76c1544da9661ab" } env_logger = "0.9" [workspace] diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a3f2a5383..3698b7978 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2519,7 +2519,7 @@ impl<'a, W: Write> Writer<'a, W> { }, }; - write!(self.out, "({}", operator)?; + write!(self.out, "{}(", operator)?; } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index e29d2c41d..c0f244230 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2395,8 +2395,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } }, }; - write!(self.out, "{}", op_str)?; + write!(self.out, "{}(", op_str)?; self.write_expr(module, expr, func_ctx)?; + write!(self.out, ")")?; } Expression::As { expr, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index bee66fc68..7617ca9a6 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1500,8 +1500,9 @@ impl Writer { _ => return Err(Error::Validation), }, }; - write!(self.out, "{}", op_str)?; + write!(self.out, "{}(", op_str)?; self.put_expression(expr, context, false)?; + write!(self.out, ")")?; } crate::Expression::Binary { op, left, right } => { let op_str = crate::back::binary_operation_str(op); diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 1f6155397..be185399e 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -105,8 +105,6 @@ fn logical() { fn arithmetic() { // unary - // TODO: uncomment when we get the changes from https://github.com/gfx-rs/rspirv/pull/231 - // _ = -1; _ = -1.0; _ = -vec2(1); _ = -vec2(1.0); @@ -314,3 +312,14 @@ fn main() { comparison(); assignment(); } + +fn negation_avoids_prefix_decrement() { + _ = -1; + _ = - -2; + _ = -(-3); + _ = -(- 4); + _ = - - -5; + _ = - - - - 6; + _ = - - -(- -7); + _ = (- - - - -8); +} diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 32716658f..30d7c53a3 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -67,7 +67,7 @@ float constructors() { } void logical() { - bool unnamed_11 = (!true); + bool unnamed_11 = !(true); bvec2 unnamed_12 = not(bvec2(true)); bool unnamed_13 = (true || false); bool unnamed_14 = (true && false); @@ -78,8 +78,8 @@ void logical() { } void arithmetic() { - ivec2 unnamed_19 = (-ivec2(1)); - vec2 unnamed_20 = (-vec2(1.0)); + ivec2 unnamed_19 = -(ivec2(1)); + vec2 unnamed_20 = -(vec2(1.0)); int unnamed_21 = (2 + 1); uint unnamed_22 = (2u + 1u); float unnamed_23 = (2.0 + 1.0); @@ -150,10 +150,10 @@ void arithmetic() { } void bit() { - int unnamed_88 = (~1); - uint unnamed_89 = (~1u); - ivec2 unnamed_90 = (~ivec2(1)); - uvec3 unnamed_91 = (~uvec3(1u)); + int unnamed_88 = ~(1); + uint unnamed_89 = ~(1u); + ivec2 unnamed_90 = ~(ivec2(1)); + uvec3 unnamed_91 = ~(uvec3(1u)); int unnamed_92 = (2 | 1); uint unnamed_93 = (2u | 1u); ivec2 unnamed_94 = (ivec2(2) | ivec2(1)); @@ -251,6 +251,16 @@ void assignment() { return; } +void negation_avoids_prefix_decrement() { + int unnamed_148 = -(-2); + int unnamed_149 = -(-3); + int unnamed_150 = -(-(4)); + int unnamed_151 = -(-(-5)); + int unnamed_152 = -(-(-(-(6)))); + int unnamed_153 = -(-(-(-(-7)))); + int unnamed_154 = -(-(-(-(-8)))); +} + void main() { vec4 _e4 = builtins(); vec4 _e5 = splat(); diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 62e028f80..743ca2813 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -95,8 +95,8 @@ float constructors() void logical() { - bool unnamed_11 = !true; - bool2 unnamed_12 = !(true).xx; + bool unnamed_11 = !(true); + bool2 unnamed_12 = !((true).xx); bool unnamed_13 = (true || false); bool unnamed_14 = (true && false); bool unnamed_15 = (true | false); @@ -107,8 +107,8 @@ void logical() void arithmetic() { - int2 unnamed_19 = -(1).xx; - float2 unnamed_20 = -(1.0).xx; + int2 unnamed_19 = -((1).xx); + float2 unnamed_20 = -((1.0).xx); int unnamed_21 = (2 + 1); uint unnamed_22 = (2u + 1u); float unnamed_23 = (2.0 + 1.0); @@ -180,10 +180,10 @@ void arithmetic() void bit() { - int unnamed_88 = ~1; - uint unnamed_89 = ~1u; - int2 unnamed_90 = ~(1).xx; - uint3 unnamed_91 = ~(1u).xxx; + int unnamed_88 = ~(1); + uint unnamed_89 = ~(1u); + int2 unnamed_90 = ~((1).xx); + uint3 unnamed_91 = ~((1u).xxx); int unnamed_92 = (2 | 1); uint unnamed_93 = (2u | 1u); int2 unnamed_94 = ((2).xx | (1).xx); @@ -284,6 +284,17 @@ void assignment() return; } +void negation_avoids_prefix_decrement() +{ + int unnamed_148 = -(-2); + int unnamed_149 = -(-3); + int unnamed_150 = -(-(4)); + int unnamed_151 = -(-(-5)); + int unnamed_152 = -(-(-(-(6)))); + int unnamed_153 = -(-(-(-(-7)))); + int unnamed_154 = -(-(-(-(-8)))); +} + [numthreads(1, 1, 1)] void main() { diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 0c3872000..72a0c3025 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -95,8 +95,8 @@ float constructors( void logical( ) { - bool unnamed_11 = !true; - metal::bool2 unnamed_12 = !metal::bool2(true); + bool unnamed_11 = !(true); + metal::bool2 unnamed_12 = !(metal::bool2(true)); bool unnamed_13 = true || false; bool unnamed_14 = true && false; bool unnamed_15 = true | false; @@ -107,8 +107,8 @@ void logical( void arithmetic( ) { - metal::int2 unnamed_19 = -metal::int2(1); - metal::float2 unnamed_20 = -metal::float2(1.0); + metal::int2 unnamed_19 = -(metal::int2(1)); + metal::float2 unnamed_20 = -(metal::float2(1.0)); int unnamed_21 = 2 + 1; uint unnamed_22 = 2u + 1u; float unnamed_23 = 2.0 + 1.0; @@ -180,10 +180,10 @@ void arithmetic( void bit( ) { - int unnamed_88 = ~1; - uint unnamed_89 = ~1u; - metal::int2 unnamed_90 = ~metal::int2(1); - metal::uint3 unnamed_91 = ~metal::uint3(1u); + int unnamed_88 = ~(1); + uint unnamed_89 = ~(1u); + metal::int2 unnamed_90 = ~(metal::int2(1)); + metal::uint3 unnamed_91 = ~(metal::uint3(1u)); int unnamed_92 = 2 | 1; uint unnamed_93 = 2u | 1u; metal::int2 unnamed_94 = metal::int2(2) | metal::int2(1); @@ -283,6 +283,17 @@ void assignment( return; } +void negation_avoids_prefix_decrement( +) { + int unnamed_148 = -(-2); + int unnamed_149 = -(-3); + int unnamed_150 = -(-(4)); + int unnamed_151 = -(-(-5)); + int unnamed_152 = -(-(-(-(6)))); + int unnamed_153 = -(-(-(-(-7)))); + int unnamed_154 = -(-(-(-(-8)))); +} + kernel void main_( ) { metal::float4 _e4 = builtins(); diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 0fde0a707..87f6ce309 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 543 +; Bound: 572 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %531 "main" -OpExecutionMode %531 LocalSize 1 1 1 -OpMemberDecorate %31 0 Offset 0 -OpMemberDecorate %31 1 Offset 16 -OpDecorate %35 ArrayStride 32 -OpDecorate %36 ArrayStride 4 +OpEntryPoint GLCompute %560 "main" +OpExecutionMode %560 LocalSize 1 1 1 +OpMemberDecorate %39 0 Offset 0 +OpMemberDecorate %39 1 Offset 16 +OpDecorate %43 ArrayStride 32 +OpDecorate %44 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -35,566 +35,598 @@ OpDecorate %36 ArrayStride 4 %23 = OpConstant %4 -1.0 %24 = OpConstant %20 2 %25 = OpConstant %20 1 -%26 = OpTypeVector %4 4 -%27 = OpTypeVector %8 4 -%28 = OpTypeVector %10 4 -%29 = OpTypeVector %4 2 -%30 = OpTypeVector %4 3 -%31 = OpTypeStruct %26 %8 -%32 = OpTypeMatrix %29 2 -%33 = OpTypeMatrix %26 4 -%34 = OpTypeVector %20 2 -%35 = OpTypeArray %31 %21 -%36 = OpTypeArray %8 %22 -%37 = OpTypeMatrix %30 2 -%38 = OpTypeMatrix %30 3 -%39 = OpTypeMatrix %30 4 -%40 = OpTypeMatrix %26 3 -%41 = OpTypeVector %8 3 -%42 = OpConstantComposite %26 %3 %3 %3 %3 -%43 = OpConstantComposite %26 %5 %5 %5 %5 -%44 = OpConstantComposite %26 %6 %6 %6 %6 -%45 = OpConstantComposite %27 %7 %7 %7 %7 -%46 = OpConstantComposite %34 %19 %19 -%47 = OpConstantComposite %29 %5 %5 -%48 = OpConstantComposite %32 %47 %47 -%49 = OpConstantComposite %26 %5 %5 %5 %5 -%50 = OpConstantComposite %31 %49 %11 -%51 = OpConstantComposite %35 %50 %50 %50 -%52 = OpConstantComposite %30 %5 %5 %5 -%53 = OpConstantComposite %37 %52 %52 -%54 = OpConstantComposite %38 %52 %52 %52 -%55 = OpConstantComposite %39 %52 %52 %52 %52 -%56 = OpConstantComposite %40 %49 %49 %49 -%57 = OpConstantComposite %41 %11 %11 %11 -%60 = OpTypeFunction %26 -%100 = OpTypePointer Function %29 -%101 = OpConstantNull %29 -%104 = OpTypeFunction %29 -%120 = OpTypeFunction %30 %30 -%122 = OpTypeVector %10 3 -%129 = OpTypePointer Function %31 -%130 = OpConstantNull %31 -%133 = OpTypeFunction %4 -%158 = OpTypePointer Function %26 -%159 = OpTypePointer Function %4 -%164 = OpTypeFunction %2 -%167 = OpTypeVector %10 2 -%183 = OpTypeVector %8 2 -%194 = OpTypeVector %20 3 -%489 = OpTypePointer Function %8 -%491 = OpTypePointer Function %41 -%521 = OpTypePointer Function %8 -%59 = OpFunction %26 None %60 -%58 = OpLabel -OpBranch %61 -%61 = OpLabel -%62 = OpSelect %8 %9 %7 %11 -%64 = OpCompositeConstruct %28 %9 %9 %9 %9 -%63 = OpSelect %26 %64 %42 %43 -%65 = OpCompositeConstruct %28 %12 %12 %12 %12 -%66 = OpSelect %26 %65 %43 %42 -%67 = OpExtInst %26 %1 FMix %43 %42 %44 -%69 = OpCompositeConstruct %26 %13 %13 %13 %13 -%68 = OpExtInst %26 %1 FMix %43 %42 %69 -%70 = OpCompositeExtract %8 %45 0 -%71 = OpBitcast %4 %70 -%72 = OpBitcast %26 %45 -%73 = OpConvertFToS %27 %43 -%74 = OpCompositeConstruct %27 %62 %62 %62 %62 -%75 = OpIAdd %27 %74 %73 -%76 = OpConvertSToF %26 %75 -%77 = OpFAdd %26 %76 %63 -%78 = OpFAdd %26 %77 %67 -%79 = OpFAdd %26 %78 %68 -%80 = OpCompositeConstruct %26 %71 %71 %71 %71 -%81 = OpFAdd %26 %79 %80 -%82 = OpFAdd %26 %81 %72 -OpReturnValue %82 +%26 = OpConstant %8 -1 +%27 = OpConstant %8 -2 +%28 = OpConstant %8 -3 +%29 = OpConstant %8 4 +%30 = OpConstant %8 -5 +%31 = OpConstant %8 6 +%32 = OpConstant %8 -7 +%33 = OpConstant %8 -8 +%34 = OpTypeVector %4 4 +%35 = OpTypeVector %8 4 +%36 = OpTypeVector %10 4 +%37 = OpTypeVector %4 2 +%38 = OpTypeVector %4 3 +%39 = OpTypeStruct %34 %8 +%40 = OpTypeMatrix %37 2 +%41 = OpTypeMatrix %34 4 +%42 = OpTypeVector %20 2 +%43 = OpTypeArray %39 %21 +%44 = OpTypeArray %8 %22 +%45 = OpTypeMatrix %38 2 +%46 = OpTypeMatrix %38 3 +%47 = OpTypeMatrix %38 4 +%48 = OpTypeMatrix %34 3 +%49 = OpTypeVector %8 3 +%50 = OpConstantComposite %34 %3 %3 %3 %3 +%51 = OpConstantComposite %34 %5 %5 %5 %5 +%52 = OpConstantComposite %34 %6 %6 %6 %6 +%53 = OpConstantComposite %35 %7 %7 %7 %7 +%54 = OpConstantComposite %42 %19 %19 +%55 = OpConstantComposite %37 %5 %5 +%56 = OpConstantComposite %40 %55 %55 +%57 = OpConstantComposite %34 %5 %5 %5 %5 +%58 = OpConstantComposite %39 %57 %11 +%59 = OpConstantComposite %43 %58 %58 %58 +%60 = OpConstantComposite %38 %5 %5 %5 +%61 = OpConstantComposite %45 %60 %60 +%62 = OpConstantComposite %46 %60 %60 %60 +%63 = OpConstantComposite %47 %60 %60 %60 %60 +%64 = OpConstantComposite %48 %57 %57 %57 +%65 = OpConstantComposite %49 %11 %11 %11 +%68 = OpTypeFunction %34 +%108 = OpTypePointer Function %37 +%109 = OpConstantNull %37 +%112 = OpTypeFunction %37 +%128 = OpTypeFunction %38 %38 +%130 = OpTypeVector %10 3 +%137 = OpTypePointer Function %39 +%138 = OpConstantNull %39 +%141 = OpTypeFunction %4 +%166 = OpTypePointer Function %34 +%167 = OpTypePointer Function %4 +%172 = OpTypeFunction %2 +%175 = OpTypeVector %10 2 +%191 = OpTypeVector %8 2 +%202 = OpTypeVector %20 3 +%497 = OpTypePointer Function %8 +%499 = OpTypePointer Function %49 +%529 = OpTypePointer Function %8 +%67 = OpFunction %34 None %68 +%66 = OpLabel +OpBranch %69 +%69 = OpLabel +%70 = OpSelect %8 %9 %7 %11 +%72 = OpCompositeConstruct %36 %9 %9 %9 %9 +%71 = OpSelect %34 %72 %50 %51 +%73 = OpCompositeConstruct %36 %12 %12 %12 %12 +%74 = OpSelect %34 %73 %51 %50 +%75 = OpExtInst %34 %1 FMix %51 %50 %52 +%77 = OpCompositeConstruct %34 %13 %13 %13 %13 +%76 = OpExtInst %34 %1 FMix %51 %50 %77 +%78 = OpCompositeExtract %8 %53 0 +%79 = OpBitcast %4 %78 +%80 = OpBitcast %34 %53 +%81 = OpConvertFToS %35 %51 +%82 = OpCompositeConstruct %35 %70 %70 %70 %70 +%83 = OpIAdd %35 %82 %81 +%84 = OpConvertSToF %34 %83 +%85 = OpFAdd %34 %84 %71 +%86 = OpFAdd %34 %85 %75 +%87 = OpFAdd %34 %86 %76 +%88 = OpCompositeConstruct %34 %79 %79 %79 %79 +%89 = OpFAdd %34 %87 %88 +%90 = OpFAdd %34 %89 %80 +OpReturnValue %90 OpFunctionEnd -%84 = OpFunction %26 None %60 -%83 = OpLabel -OpBranch %85 -%85 = OpLabel -%86 = OpCompositeConstruct %29 %14 %14 -%87 = OpCompositeConstruct %29 %3 %3 -%88 = OpFAdd %29 %87 %86 -%89 = OpCompositeConstruct %29 %15 %15 -%90 = OpFSub %29 %88 %89 -%91 = OpCompositeConstruct %29 %16 %16 -%92 = OpFDiv %29 %90 %91 -%93 = OpCompositeConstruct %27 %17 %17 %17 %17 -%94 = OpCompositeConstruct %27 %18 %18 %18 %18 -%95 = OpSRem %27 %93 %94 -%96 = OpVectorShuffle %26 %92 %92 0 1 0 1 -%97 = OpConvertSToF %26 %95 -%98 = OpFAdd %26 %96 %97 -OpReturnValue %98 +%92 = OpFunction %34 None %68 +%91 = OpLabel +OpBranch %93 +%93 = OpLabel +%94 = OpCompositeConstruct %37 %14 %14 +%95 = OpCompositeConstruct %37 %3 %3 +%96 = OpFAdd %37 %95 %94 +%97 = OpCompositeConstruct %37 %15 %15 +%98 = OpFSub %37 %96 %97 +%99 = OpCompositeConstruct %37 %16 %16 +%100 = OpFDiv %37 %98 %99 +%101 = OpCompositeConstruct %35 %17 %17 %17 %17 +%102 = OpCompositeConstruct %35 %18 %18 %18 %18 +%103 = OpSRem %35 %101 %102 +%104 = OpVectorShuffle %34 %100 %100 0 1 0 1 +%105 = OpConvertSToF %34 %103 +%106 = OpFAdd %34 %104 %105 +OpReturnValue %106 OpFunctionEnd -%103 = OpFunction %29 None %104 -%102 = OpLabel -%99 = OpVariable %100 Function %101 -OpBranch %105 -%105 = OpLabel -%106 = OpCompositeConstruct %29 %14 %14 -OpStore %99 %106 -%107 = OpLoad %29 %99 -%108 = OpCompositeConstruct %29 %3 %3 -%109 = OpFAdd %29 %107 %108 -OpStore %99 %109 -%110 = OpLoad %29 %99 -%111 = OpCompositeConstruct %29 %15 %15 -%112 = OpFSub %29 %110 %111 -OpStore %99 %112 -%113 = OpLoad %29 %99 -%114 = OpCompositeConstruct %29 %16 %16 -%115 = OpFDiv %29 %113 %114 -OpStore %99 %115 -%116 = OpLoad %29 %99 -OpReturnValue %116 +%111 = OpFunction %37 None %112 +%110 = OpLabel +%107 = OpVariable %108 Function %109 +OpBranch %113 +%113 = OpLabel +%114 = OpCompositeConstruct %37 %14 %14 +OpStore %107 %114 +%115 = OpLoad %37 %107 +%116 = OpCompositeConstruct %37 %3 %3 +%117 = OpFAdd %37 %115 %116 +OpStore %107 %117 +%118 = OpLoad %37 %107 +%119 = OpCompositeConstruct %37 %15 %15 +%120 = OpFSub %37 %118 %119 +OpStore %107 %120 +%121 = OpLoad %37 %107 +%122 = OpCompositeConstruct %37 %16 %16 +%123 = OpFDiv %37 %121 %122 +OpStore %107 %123 +%124 = OpLoad %37 %107 +OpReturnValue %124 OpFunctionEnd -%119 = OpFunction %30 None %120 -%118 = OpFunctionParameter %30 -%117 = OpLabel -OpBranch %121 -%121 = OpLabel -%123 = OpCompositeConstruct %30 %5 %5 %5 -%124 = OpFUnordNotEqual %122 %118 %123 -%125 = OpCompositeConstruct %30 %5 %5 %5 -%126 = OpCompositeConstruct %30 %3 %3 %3 -%127 = OpSelect %30 %124 %126 %125 -OpReturnValue %127 +%127 = OpFunction %38 None %128 +%126 = OpFunctionParameter %38 +%125 = OpLabel +OpBranch %129 +%129 = OpLabel +%131 = OpCompositeConstruct %38 %5 %5 %5 +%132 = OpFUnordNotEqual %130 %126 %131 +%133 = OpCompositeConstruct %38 %5 %5 %5 +%134 = OpCompositeConstruct %38 %3 %3 %3 +%135 = OpSelect %38 %132 %134 %133 +OpReturnValue %135 OpFunctionEnd -%132 = OpFunction %4 None %133 -%131 = OpLabel -%128 = OpVariable %129 Function %130 -OpBranch %134 -%134 = OpLabel -%135 = OpCompositeConstruct %26 %3 %3 %3 %3 -%136 = OpCompositeConstruct %31 %135 %7 -OpStore %128 %136 -%137 = OpCompositeConstruct %29 %3 %5 -%138 = OpCompositeConstruct %29 %5 %3 -%139 = OpCompositeConstruct %32 %137 %138 -%140 = OpCompositeConstruct %26 %3 %5 %5 %5 -%141 = OpCompositeConstruct %26 %5 %3 %5 %5 -%142 = OpCompositeConstruct %26 %5 %5 %3 %5 -%143 = OpCompositeConstruct %26 %5 %5 %5 %3 -%144 = OpCompositeConstruct %33 %140 %141 %142 %143 -%145 = OpCompositeConstruct %34 %19 %19 -%146 = OpCompositeConstruct %29 %5 %5 -%147 = OpCompositeConstruct %29 %5 %5 -%148 = OpCompositeConstruct %32 %146 %147 -%149 = OpCompositeConstruct %36 %11 %7 %18 %21 -%155 = OpCopyObject %37 %53 -%157 = OpCopyObject %37 %53 -%160 = OpAccessChain %159 %128 %19 %19 -%161 = OpLoad %4 %160 -OpReturnValue %161 +%140 = OpFunction %4 None %141 +%139 = OpLabel +%136 = OpVariable %137 Function %138 +OpBranch %142 +%142 = OpLabel +%143 = OpCompositeConstruct %34 %3 %3 %3 %3 +%144 = OpCompositeConstruct %39 %143 %7 +OpStore %136 %144 +%145 = OpCompositeConstruct %37 %3 %5 +%146 = OpCompositeConstruct %37 %5 %3 +%147 = OpCompositeConstruct %40 %145 %146 +%148 = OpCompositeConstruct %34 %3 %5 %5 %5 +%149 = OpCompositeConstruct %34 %5 %3 %5 %5 +%150 = OpCompositeConstruct %34 %5 %5 %3 %5 +%151 = OpCompositeConstruct %34 %5 %5 %5 %3 +%152 = OpCompositeConstruct %41 %148 %149 %150 %151 +%153 = OpCompositeConstruct %42 %19 %19 +%154 = OpCompositeConstruct %37 %5 %5 +%155 = OpCompositeConstruct %37 %5 %5 +%156 = OpCompositeConstruct %40 %154 %155 +%157 = OpCompositeConstruct %44 %11 %7 %18 %21 +%163 = OpCopyObject %45 %61 +%165 = OpCopyObject %45 %61 +%168 = OpAccessChain %167 %136 %19 %19 +%169 = OpLoad %4 %168 +OpReturnValue %169 OpFunctionEnd -%163 = OpFunction %2 None %164 -%162 = OpLabel -OpBranch %165 -%165 = OpLabel -%166 = OpLogicalNot %10 %9 -%168 = OpCompositeConstruct %167 %9 %9 -%169 = OpLogicalNot %167 %168 -%170 = OpLogicalOr %10 %9 %12 -%171 = OpLogicalAnd %10 %9 %12 -%172 = OpLogicalOr %10 %9 %12 -%173 = OpCompositeConstruct %122 %9 %9 %9 -%174 = OpCompositeConstruct %122 %12 %12 %12 -%175 = OpLogicalOr %122 %173 %174 -%176 = OpLogicalAnd %10 %9 %12 -%177 = OpCompositeConstruct %28 %9 %9 %9 %9 -%178 = OpCompositeConstruct %28 %12 %12 %12 %12 -%179 = OpLogicalAnd %28 %177 %178 +%171 = OpFunction %2 None %172 +%170 = OpLabel +OpBranch %173 +%173 = OpLabel +%174 = OpLogicalNot %10 %9 +%176 = OpCompositeConstruct %175 %9 %9 +%177 = OpLogicalNot %175 %176 +%178 = OpLogicalOr %10 %9 %12 +%179 = OpLogicalAnd %10 %9 %12 +%180 = OpLogicalOr %10 %9 %12 +%181 = OpCompositeConstruct %130 %9 %9 %9 +%182 = OpCompositeConstruct %130 %12 %12 %12 +%183 = OpLogicalOr %130 %181 %182 +%184 = OpLogicalAnd %10 %9 %12 +%185 = OpCompositeConstruct %36 %9 %9 %9 %9 +%186 = OpCompositeConstruct %36 %12 %12 %12 %12 +%187 = OpLogicalAnd %36 %185 %186 OpReturn OpFunctionEnd -%181 = OpFunction %2 None %164 -%180 = OpLabel -OpBranch %182 -%182 = OpLabel -%184 = OpCompositeConstruct %183 %7 %7 -%185 = OpSNegate %183 %184 -%186 = OpCompositeConstruct %29 %3 %3 -%187 = OpFNegate %29 %186 -%188 = OpIAdd %8 %18 %7 -%189 = OpIAdd %20 %24 %25 -%190 = OpFAdd %4 %14 %3 -%191 = OpCompositeConstruct %183 %18 %18 -%192 = OpCompositeConstruct %183 %7 %7 -%193 = OpIAdd %183 %191 %192 -%195 = OpCompositeConstruct %194 %24 %24 %24 -%196 = OpCompositeConstruct %194 %25 %25 %25 -%197 = OpIAdd %194 %195 %196 -%198 = OpCompositeConstruct %26 %14 %14 %14 %14 -%199 = OpCompositeConstruct %26 %3 %3 %3 %3 -%200 = OpFAdd %26 %198 %199 -%201 = OpISub %8 %18 %7 -%202 = OpISub %20 %24 %25 -%203 = OpFSub %4 %14 %3 -%204 = OpCompositeConstruct %183 %18 %18 -%205 = OpCompositeConstruct %183 %7 %7 -%206 = OpISub %183 %204 %205 -%207 = OpCompositeConstruct %194 %24 %24 %24 -%208 = OpCompositeConstruct %194 %25 %25 %25 -%209 = OpISub %194 %207 %208 -%210 = OpCompositeConstruct %26 %14 %14 %14 %14 -%211 = OpCompositeConstruct %26 %3 %3 %3 %3 -%212 = OpFSub %26 %210 %211 -%213 = OpIMul %8 %18 %7 -%214 = OpIMul %20 %24 %25 -%215 = OpFMul %4 %14 %3 -%216 = OpCompositeConstruct %183 %18 %18 -%217 = OpCompositeConstruct %183 %7 %7 -%218 = OpIMul %183 %216 %217 -%219 = OpCompositeConstruct %194 %24 %24 %24 -%220 = OpCompositeConstruct %194 %25 %25 %25 -%221 = OpIMul %194 %219 %220 -%222 = OpCompositeConstruct %26 %14 %14 %14 %14 -%223 = OpCompositeConstruct %26 %3 %3 %3 %3 -%224 = OpFMul %26 %222 %223 -%225 = OpSDiv %8 %18 %7 -%226 = OpUDiv %20 %24 %25 -%227 = OpFDiv %4 %14 %3 -%228 = OpCompositeConstruct %183 %18 %18 -%229 = OpCompositeConstruct %183 %7 %7 -%230 = OpSDiv %183 %228 %229 -%231 = OpCompositeConstruct %194 %24 %24 %24 -%232 = OpCompositeConstruct %194 %25 %25 %25 -%233 = OpUDiv %194 %231 %232 -%234 = OpCompositeConstruct %26 %14 %14 %14 %14 -%235 = OpCompositeConstruct %26 %3 %3 %3 %3 -%236 = OpFDiv %26 %234 %235 -%237 = OpSRem %8 %18 %7 -%238 = OpUMod %20 %24 %25 -%239 = OpFRem %4 %14 %3 -%240 = OpCompositeConstruct %183 %18 %18 -%241 = OpCompositeConstruct %183 %7 %7 -%242 = OpSRem %183 %240 %241 -%243 = OpCompositeConstruct %194 %24 %24 %24 -%244 = OpCompositeConstruct %194 %25 %25 %25 -%245 = OpUMod %194 %243 %244 -%246 = OpCompositeConstruct %26 %14 %14 %14 %14 -%247 = OpCompositeConstruct %26 %3 %3 %3 %3 -%248 = OpFRem %26 %246 %247 -%249 = OpCompositeConstruct %183 %18 %18 -%250 = OpCompositeConstruct %183 %7 %7 -%251 = OpIAdd %183 %249 %250 -%252 = OpCompositeConstruct %183 %7 %7 -%253 = OpCompositeConstruct %183 %18 %18 -%254 = OpIAdd %183 %253 %252 -%255 = OpCompositeConstruct %34 %24 %24 -%256 = OpCompositeConstruct %34 %25 %25 -%257 = OpIAdd %34 %255 %256 -%258 = OpCompositeConstruct %34 %25 %25 -%259 = OpCompositeConstruct %34 %24 %24 -%260 = OpIAdd %34 %259 %258 -%261 = OpCompositeConstruct %29 %14 %14 -%262 = OpCompositeConstruct %29 %3 %3 -%263 = OpFAdd %29 %261 %262 -%264 = OpCompositeConstruct %29 %3 %3 -%265 = OpCompositeConstruct %29 %14 %14 -%266 = OpFAdd %29 %265 %264 -%267 = OpCompositeConstruct %183 %18 %18 -%268 = OpCompositeConstruct %183 %7 %7 -%269 = OpISub %183 %267 %268 -%270 = OpCompositeConstruct %183 %7 %7 -%271 = OpCompositeConstruct %183 %18 %18 -%272 = OpISub %183 %271 %270 -%273 = OpCompositeConstruct %34 %24 %24 -%274 = OpCompositeConstruct %34 %25 %25 -%275 = OpISub %34 %273 %274 -%276 = OpCompositeConstruct %34 %25 %25 -%277 = OpCompositeConstruct %34 %24 %24 -%278 = OpISub %34 %277 %276 -%279 = OpCompositeConstruct %29 %14 %14 -%280 = OpCompositeConstruct %29 %3 %3 -%281 = OpFSub %29 %279 %280 -%282 = OpCompositeConstruct %29 %3 %3 -%283 = OpCompositeConstruct %29 %14 %14 -%284 = OpFSub %29 %283 %282 -%285 = OpCompositeConstruct %183 %18 %18 -%287 = OpCompositeConstruct %183 %7 %7 -%286 = OpIMul %183 %285 %287 -%288 = OpCompositeConstruct %183 %7 %7 -%290 = OpCompositeConstruct %183 %18 %18 -%289 = OpIMul %183 %288 %290 -%291 = OpCompositeConstruct %34 %24 %24 -%293 = OpCompositeConstruct %34 %25 %25 -%292 = OpIMul %34 %291 %293 -%294 = OpCompositeConstruct %34 %25 %25 -%296 = OpCompositeConstruct %34 %24 %24 -%295 = OpIMul %34 %294 %296 -%297 = OpCompositeConstruct %29 %14 %14 -%298 = OpVectorTimesScalar %29 %297 %3 -%299 = OpCompositeConstruct %29 %3 %3 -%300 = OpVectorTimesScalar %29 %299 %14 -%301 = OpCompositeConstruct %183 %18 %18 -%302 = OpCompositeConstruct %183 %7 %7 -%303 = OpSDiv %183 %301 %302 -%304 = OpCompositeConstruct %183 %7 %7 -%305 = OpCompositeConstruct %183 %18 %18 -%306 = OpSDiv %183 %305 %304 -%307 = OpCompositeConstruct %34 %24 %24 -%308 = OpCompositeConstruct %34 %25 %25 -%309 = OpUDiv %34 %307 %308 -%310 = OpCompositeConstruct %34 %25 %25 -%311 = OpCompositeConstruct %34 %24 %24 -%312 = OpUDiv %34 %311 %310 -%313 = OpCompositeConstruct %29 %14 %14 -%314 = OpCompositeConstruct %29 %3 %3 -%315 = OpFDiv %29 %313 %314 -%316 = OpCompositeConstruct %29 %3 %3 -%317 = OpCompositeConstruct %29 %14 %14 -%318 = OpFDiv %29 %317 %316 -%319 = OpCompositeConstruct %183 %18 %18 -%320 = OpCompositeConstruct %183 %7 %7 -%321 = OpSRem %183 %319 %320 -%322 = OpCompositeConstruct %183 %7 %7 -%323 = OpCompositeConstruct %183 %18 %18 -%324 = OpSRem %183 %323 %322 -%325 = OpCompositeConstruct %34 %24 %24 -%326 = OpCompositeConstruct %34 %25 %25 -%327 = OpUMod %34 %325 %326 -%328 = OpCompositeConstruct %34 %25 %25 -%329 = OpCompositeConstruct %34 %24 %24 -%330 = OpUMod %34 %329 %328 -%331 = OpCompositeConstruct %29 %14 %14 -%332 = OpCompositeConstruct %29 %3 %3 -%333 = OpFRem %29 %331 %332 -%334 = OpCompositeConstruct %29 %3 %3 -%335 = OpCompositeConstruct %29 %14 %14 -%336 = OpFRem %29 %335 %334 -%338 = OpCompositeExtract %30 %54 0 -%339 = OpCompositeExtract %30 %54 0 -%340 = OpFAdd %30 %338 %339 -%341 = OpCompositeExtract %30 %54 1 -%342 = OpCompositeExtract %30 %54 1 -%343 = OpFAdd %30 %341 %342 -%344 = OpCompositeExtract %30 %54 2 -%345 = OpCompositeExtract %30 %54 2 -%346 = OpFAdd %30 %344 %345 -%337 = OpCompositeConstruct %38 %340 %343 %346 -%348 = OpCompositeExtract %30 %54 0 -%349 = OpCompositeExtract %30 %54 0 -%350 = OpFSub %30 %348 %349 -%351 = OpCompositeExtract %30 %54 1 -%352 = OpCompositeExtract %30 %54 1 -%353 = OpFSub %30 %351 %352 -%354 = OpCompositeExtract %30 %54 2 -%355 = OpCompositeExtract %30 %54 2 -%356 = OpFSub %30 %354 %355 -%347 = OpCompositeConstruct %38 %350 %353 %356 -%357 = OpMatrixTimesScalar %38 %54 %3 -%358 = OpMatrixTimesScalar %38 %54 %14 -%359 = OpCompositeConstruct %26 %3 %3 %3 %3 -%360 = OpMatrixTimesVector %30 %55 %359 -%361 = OpCompositeConstruct %30 %14 %14 %14 -%362 = OpVectorTimesMatrix %26 %361 %55 -%363 = OpMatrixTimesMatrix %38 %55 %56 +%189 = OpFunction %2 None %172 +%188 = OpLabel +OpBranch %190 +%190 = OpLabel +%192 = OpCompositeConstruct %191 %7 %7 +%193 = OpSNegate %191 %192 +%194 = OpCompositeConstruct %37 %3 %3 +%195 = OpFNegate %37 %194 +%196 = OpIAdd %8 %18 %7 +%197 = OpIAdd %20 %24 %25 +%198 = OpFAdd %4 %14 %3 +%199 = OpCompositeConstruct %191 %18 %18 +%200 = OpCompositeConstruct %191 %7 %7 +%201 = OpIAdd %191 %199 %200 +%203 = OpCompositeConstruct %202 %24 %24 %24 +%204 = OpCompositeConstruct %202 %25 %25 %25 +%205 = OpIAdd %202 %203 %204 +%206 = OpCompositeConstruct %34 %14 %14 %14 %14 +%207 = OpCompositeConstruct %34 %3 %3 %3 %3 +%208 = OpFAdd %34 %206 %207 +%209 = OpISub %8 %18 %7 +%210 = OpISub %20 %24 %25 +%211 = OpFSub %4 %14 %3 +%212 = OpCompositeConstruct %191 %18 %18 +%213 = OpCompositeConstruct %191 %7 %7 +%214 = OpISub %191 %212 %213 +%215 = OpCompositeConstruct %202 %24 %24 %24 +%216 = OpCompositeConstruct %202 %25 %25 %25 +%217 = OpISub %202 %215 %216 +%218 = OpCompositeConstruct %34 %14 %14 %14 %14 +%219 = OpCompositeConstruct %34 %3 %3 %3 %3 +%220 = OpFSub %34 %218 %219 +%221 = OpIMul %8 %18 %7 +%222 = OpIMul %20 %24 %25 +%223 = OpFMul %4 %14 %3 +%224 = OpCompositeConstruct %191 %18 %18 +%225 = OpCompositeConstruct %191 %7 %7 +%226 = OpIMul %191 %224 %225 +%227 = OpCompositeConstruct %202 %24 %24 %24 +%228 = OpCompositeConstruct %202 %25 %25 %25 +%229 = OpIMul %202 %227 %228 +%230 = OpCompositeConstruct %34 %14 %14 %14 %14 +%231 = OpCompositeConstruct %34 %3 %3 %3 %3 +%232 = OpFMul %34 %230 %231 +%233 = OpSDiv %8 %18 %7 +%234 = OpUDiv %20 %24 %25 +%235 = OpFDiv %4 %14 %3 +%236 = OpCompositeConstruct %191 %18 %18 +%237 = OpCompositeConstruct %191 %7 %7 +%238 = OpSDiv %191 %236 %237 +%239 = OpCompositeConstruct %202 %24 %24 %24 +%240 = OpCompositeConstruct %202 %25 %25 %25 +%241 = OpUDiv %202 %239 %240 +%242 = OpCompositeConstruct %34 %14 %14 %14 %14 +%243 = OpCompositeConstruct %34 %3 %3 %3 %3 +%244 = OpFDiv %34 %242 %243 +%245 = OpSRem %8 %18 %7 +%246 = OpUMod %20 %24 %25 +%247 = OpFRem %4 %14 %3 +%248 = OpCompositeConstruct %191 %18 %18 +%249 = OpCompositeConstruct %191 %7 %7 +%250 = OpSRem %191 %248 %249 +%251 = OpCompositeConstruct %202 %24 %24 %24 +%252 = OpCompositeConstruct %202 %25 %25 %25 +%253 = OpUMod %202 %251 %252 +%254 = OpCompositeConstruct %34 %14 %14 %14 %14 +%255 = OpCompositeConstruct %34 %3 %3 %3 %3 +%256 = OpFRem %34 %254 %255 +%257 = OpCompositeConstruct %191 %18 %18 +%258 = OpCompositeConstruct %191 %7 %7 +%259 = OpIAdd %191 %257 %258 +%260 = OpCompositeConstruct %191 %7 %7 +%261 = OpCompositeConstruct %191 %18 %18 +%262 = OpIAdd %191 %261 %260 +%263 = OpCompositeConstruct %42 %24 %24 +%264 = OpCompositeConstruct %42 %25 %25 +%265 = OpIAdd %42 %263 %264 +%266 = OpCompositeConstruct %42 %25 %25 +%267 = OpCompositeConstruct %42 %24 %24 +%268 = OpIAdd %42 %267 %266 +%269 = OpCompositeConstruct %37 %14 %14 +%270 = OpCompositeConstruct %37 %3 %3 +%271 = OpFAdd %37 %269 %270 +%272 = OpCompositeConstruct %37 %3 %3 +%273 = OpCompositeConstruct %37 %14 %14 +%274 = OpFAdd %37 %273 %272 +%275 = OpCompositeConstruct %191 %18 %18 +%276 = OpCompositeConstruct %191 %7 %7 +%277 = OpISub %191 %275 %276 +%278 = OpCompositeConstruct %191 %7 %7 +%279 = OpCompositeConstruct %191 %18 %18 +%280 = OpISub %191 %279 %278 +%281 = OpCompositeConstruct %42 %24 %24 +%282 = OpCompositeConstruct %42 %25 %25 +%283 = OpISub %42 %281 %282 +%284 = OpCompositeConstruct %42 %25 %25 +%285 = OpCompositeConstruct %42 %24 %24 +%286 = OpISub %42 %285 %284 +%287 = OpCompositeConstruct %37 %14 %14 +%288 = OpCompositeConstruct %37 %3 %3 +%289 = OpFSub %37 %287 %288 +%290 = OpCompositeConstruct %37 %3 %3 +%291 = OpCompositeConstruct %37 %14 %14 +%292 = OpFSub %37 %291 %290 +%293 = OpCompositeConstruct %191 %18 %18 +%295 = OpCompositeConstruct %191 %7 %7 +%294 = OpIMul %191 %293 %295 +%296 = OpCompositeConstruct %191 %7 %7 +%298 = OpCompositeConstruct %191 %18 %18 +%297 = OpIMul %191 %296 %298 +%299 = OpCompositeConstruct %42 %24 %24 +%301 = OpCompositeConstruct %42 %25 %25 +%300 = OpIMul %42 %299 %301 +%302 = OpCompositeConstruct %42 %25 %25 +%304 = OpCompositeConstruct %42 %24 %24 +%303 = OpIMul %42 %302 %304 +%305 = OpCompositeConstruct %37 %14 %14 +%306 = OpVectorTimesScalar %37 %305 %3 +%307 = OpCompositeConstruct %37 %3 %3 +%308 = OpVectorTimesScalar %37 %307 %14 +%309 = OpCompositeConstruct %191 %18 %18 +%310 = OpCompositeConstruct %191 %7 %7 +%311 = OpSDiv %191 %309 %310 +%312 = OpCompositeConstruct %191 %7 %7 +%313 = OpCompositeConstruct %191 %18 %18 +%314 = OpSDiv %191 %313 %312 +%315 = OpCompositeConstruct %42 %24 %24 +%316 = OpCompositeConstruct %42 %25 %25 +%317 = OpUDiv %42 %315 %316 +%318 = OpCompositeConstruct %42 %25 %25 +%319 = OpCompositeConstruct %42 %24 %24 +%320 = OpUDiv %42 %319 %318 +%321 = OpCompositeConstruct %37 %14 %14 +%322 = OpCompositeConstruct %37 %3 %3 +%323 = OpFDiv %37 %321 %322 +%324 = OpCompositeConstruct %37 %3 %3 +%325 = OpCompositeConstruct %37 %14 %14 +%326 = OpFDiv %37 %325 %324 +%327 = OpCompositeConstruct %191 %18 %18 +%328 = OpCompositeConstruct %191 %7 %7 +%329 = OpSRem %191 %327 %328 +%330 = OpCompositeConstruct %191 %7 %7 +%331 = OpCompositeConstruct %191 %18 %18 +%332 = OpSRem %191 %331 %330 +%333 = OpCompositeConstruct %42 %24 %24 +%334 = OpCompositeConstruct %42 %25 %25 +%335 = OpUMod %42 %333 %334 +%336 = OpCompositeConstruct %42 %25 %25 +%337 = OpCompositeConstruct %42 %24 %24 +%338 = OpUMod %42 %337 %336 +%339 = OpCompositeConstruct %37 %14 %14 +%340 = OpCompositeConstruct %37 %3 %3 +%341 = OpFRem %37 %339 %340 +%342 = OpCompositeConstruct %37 %3 %3 +%343 = OpCompositeConstruct %37 %14 %14 +%344 = OpFRem %37 %343 %342 +%346 = OpCompositeExtract %38 %62 0 +%347 = OpCompositeExtract %38 %62 0 +%348 = OpFAdd %38 %346 %347 +%349 = OpCompositeExtract %38 %62 1 +%350 = OpCompositeExtract %38 %62 1 +%351 = OpFAdd %38 %349 %350 +%352 = OpCompositeExtract %38 %62 2 +%353 = OpCompositeExtract %38 %62 2 +%354 = OpFAdd %38 %352 %353 +%345 = OpCompositeConstruct %46 %348 %351 %354 +%356 = OpCompositeExtract %38 %62 0 +%357 = OpCompositeExtract %38 %62 0 +%358 = OpFSub %38 %356 %357 +%359 = OpCompositeExtract %38 %62 1 +%360 = OpCompositeExtract %38 %62 1 +%361 = OpFSub %38 %359 %360 +%362 = OpCompositeExtract %38 %62 2 +%363 = OpCompositeExtract %38 %62 2 +%364 = OpFSub %38 %362 %363 +%355 = OpCompositeConstruct %46 %358 %361 %364 +%365 = OpMatrixTimesScalar %46 %62 %3 +%366 = OpMatrixTimesScalar %46 %62 %14 +%367 = OpCompositeConstruct %34 %3 %3 %3 %3 +%368 = OpMatrixTimesVector %38 %63 %367 +%369 = OpCompositeConstruct %38 %14 %14 %14 +%370 = OpVectorTimesMatrix %34 %369 %63 +%371 = OpMatrixTimesMatrix %46 %63 %64 OpReturn OpFunctionEnd -%365 = OpFunction %2 None %164 -%364 = OpLabel -OpBranch %366 -%366 = OpLabel -%367 = OpNot %8 %7 -%368 = OpNot %20 %25 -%369 = OpCompositeConstruct %183 %7 %7 -%370 = OpNot %183 %369 -%371 = OpCompositeConstruct %194 %25 %25 %25 -%372 = OpNot %194 %371 -%373 = OpBitwiseOr %8 %18 %7 -%374 = OpBitwiseOr %20 %24 %25 -%375 = OpCompositeConstruct %183 %18 %18 -%376 = OpCompositeConstruct %183 %7 %7 -%377 = OpBitwiseOr %183 %375 %376 -%378 = OpCompositeConstruct %194 %24 %24 %24 -%379 = OpCompositeConstruct %194 %25 %25 %25 -%380 = OpBitwiseOr %194 %378 %379 -%381 = OpBitwiseAnd %8 %18 %7 -%382 = OpBitwiseAnd %20 %24 %25 -%383 = OpCompositeConstruct %183 %18 %18 -%384 = OpCompositeConstruct %183 %7 %7 -%385 = OpBitwiseAnd %183 %383 %384 -%386 = OpCompositeConstruct %194 %24 %24 %24 -%387 = OpCompositeConstruct %194 %25 %25 %25 -%388 = OpBitwiseAnd %194 %386 %387 -%389 = OpBitwiseXor %8 %18 %7 -%390 = OpBitwiseXor %20 %24 %25 -%391 = OpCompositeConstruct %183 %18 %18 -%392 = OpCompositeConstruct %183 %7 %7 -%393 = OpBitwiseXor %183 %391 %392 -%394 = OpCompositeConstruct %194 %24 %24 %24 -%395 = OpCompositeConstruct %194 %25 %25 %25 -%396 = OpBitwiseXor %194 %394 %395 -%397 = OpShiftLeftLogical %8 %18 %25 -%398 = OpShiftLeftLogical %20 %24 %25 -%399 = OpCompositeConstruct %183 %18 %18 -%400 = OpCompositeConstruct %34 %25 %25 -%401 = OpShiftLeftLogical %183 %399 %400 -%402 = OpCompositeConstruct %194 %24 %24 %24 -%403 = OpCompositeConstruct %194 %25 %25 %25 -%404 = OpShiftLeftLogical %194 %402 %403 -%405 = OpShiftRightArithmetic %8 %18 %25 -%406 = OpShiftRightLogical %20 %24 %25 -%407 = OpCompositeConstruct %183 %18 %18 -%408 = OpCompositeConstruct %34 %25 %25 -%409 = OpShiftRightArithmetic %183 %407 %408 -%410 = OpCompositeConstruct %194 %24 %24 %24 -%411 = OpCompositeConstruct %194 %25 %25 %25 -%412 = OpShiftRightLogical %194 %410 %411 +%373 = OpFunction %2 None %172 +%372 = OpLabel +OpBranch %374 +%374 = OpLabel +%375 = OpNot %8 %7 +%376 = OpNot %20 %25 +%377 = OpCompositeConstruct %191 %7 %7 +%378 = OpNot %191 %377 +%379 = OpCompositeConstruct %202 %25 %25 %25 +%380 = OpNot %202 %379 +%381 = OpBitwiseOr %8 %18 %7 +%382 = OpBitwiseOr %20 %24 %25 +%383 = OpCompositeConstruct %191 %18 %18 +%384 = OpCompositeConstruct %191 %7 %7 +%385 = OpBitwiseOr %191 %383 %384 +%386 = OpCompositeConstruct %202 %24 %24 %24 +%387 = OpCompositeConstruct %202 %25 %25 %25 +%388 = OpBitwiseOr %202 %386 %387 +%389 = OpBitwiseAnd %8 %18 %7 +%390 = OpBitwiseAnd %20 %24 %25 +%391 = OpCompositeConstruct %191 %18 %18 +%392 = OpCompositeConstruct %191 %7 %7 +%393 = OpBitwiseAnd %191 %391 %392 +%394 = OpCompositeConstruct %202 %24 %24 %24 +%395 = OpCompositeConstruct %202 %25 %25 %25 +%396 = OpBitwiseAnd %202 %394 %395 +%397 = OpBitwiseXor %8 %18 %7 +%398 = OpBitwiseXor %20 %24 %25 +%399 = OpCompositeConstruct %191 %18 %18 +%400 = OpCompositeConstruct %191 %7 %7 +%401 = OpBitwiseXor %191 %399 %400 +%402 = OpCompositeConstruct %202 %24 %24 %24 +%403 = OpCompositeConstruct %202 %25 %25 %25 +%404 = OpBitwiseXor %202 %402 %403 +%405 = OpShiftLeftLogical %8 %18 %25 +%406 = OpShiftLeftLogical %20 %24 %25 +%407 = OpCompositeConstruct %191 %18 %18 +%408 = OpCompositeConstruct %42 %25 %25 +%409 = OpShiftLeftLogical %191 %407 %408 +%410 = OpCompositeConstruct %202 %24 %24 %24 +%411 = OpCompositeConstruct %202 %25 %25 %25 +%412 = OpShiftLeftLogical %202 %410 %411 +%413 = OpShiftRightArithmetic %8 %18 %25 +%414 = OpShiftRightLogical %20 %24 %25 +%415 = OpCompositeConstruct %191 %18 %18 +%416 = OpCompositeConstruct %42 %25 %25 +%417 = OpShiftRightArithmetic %191 %415 %416 +%418 = OpCompositeConstruct %202 %24 %24 %24 +%419 = OpCompositeConstruct %202 %25 %25 %25 +%420 = OpShiftRightLogical %202 %418 %419 OpReturn OpFunctionEnd -%414 = OpFunction %2 None %164 -%413 = OpLabel -OpBranch %415 -%415 = OpLabel -%416 = OpIEqual %10 %18 %7 -%417 = OpIEqual %10 %24 %25 -%418 = OpFOrdEqual %10 %14 %3 -%419 = OpCompositeConstruct %183 %18 %18 -%420 = OpCompositeConstruct %183 %7 %7 -%421 = OpIEqual %167 %419 %420 -%422 = OpCompositeConstruct %194 %24 %24 %24 -%423 = OpCompositeConstruct %194 %25 %25 %25 -%424 = OpIEqual %122 %422 %423 -%425 = OpCompositeConstruct %26 %14 %14 %14 %14 -%426 = OpCompositeConstruct %26 %3 %3 %3 %3 -%427 = OpFOrdEqual %28 %425 %426 -%428 = OpINotEqual %10 %18 %7 -%429 = OpINotEqual %10 %24 %25 -%430 = OpFOrdNotEqual %10 %14 %3 -%431 = OpCompositeConstruct %183 %18 %18 -%432 = OpCompositeConstruct %183 %7 %7 -%433 = OpINotEqual %167 %431 %432 -%434 = OpCompositeConstruct %194 %24 %24 %24 -%435 = OpCompositeConstruct %194 %25 %25 %25 -%436 = OpINotEqual %122 %434 %435 -%437 = OpCompositeConstruct %26 %14 %14 %14 %14 -%438 = OpCompositeConstruct %26 %3 %3 %3 %3 -%439 = OpFOrdNotEqual %28 %437 %438 -%440 = OpSLessThan %10 %18 %7 -%441 = OpULessThan %10 %24 %25 -%442 = OpFOrdLessThan %10 %14 %3 -%443 = OpCompositeConstruct %183 %18 %18 -%444 = OpCompositeConstruct %183 %7 %7 -%445 = OpSLessThan %167 %443 %444 -%446 = OpCompositeConstruct %194 %24 %24 %24 -%447 = OpCompositeConstruct %194 %25 %25 %25 -%448 = OpULessThan %122 %446 %447 -%449 = OpCompositeConstruct %26 %14 %14 %14 %14 -%450 = OpCompositeConstruct %26 %3 %3 %3 %3 -%451 = OpFOrdLessThan %28 %449 %450 -%452 = OpSLessThanEqual %10 %18 %7 -%453 = OpULessThanEqual %10 %24 %25 -%454 = OpFOrdLessThanEqual %10 %14 %3 -%455 = OpCompositeConstruct %183 %18 %18 -%456 = OpCompositeConstruct %183 %7 %7 -%457 = OpSLessThanEqual %167 %455 %456 -%458 = OpCompositeConstruct %194 %24 %24 %24 -%459 = OpCompositeConstruct %194 %25 %25 %25 -%460 = OpULessThanEqual %122 %458 %459 -%461 = OpCompositeConstruct %26 %14 %14 %14 %14 -%462 = OpCompositeConstruct %26 %3 %3 %3 %3 -%463 = OpFOrdLessThanEqual %28 %461 %462 -%464 = OpSGreaterThan %10 %18 %7 -%465 = OpUGreaterThan %10 %24 %25 -%466 = OpFOrdGreaterThan %10 %14 %3 -%467 = OpCompositeConstruct %183 %18 %18 -%468 = OpCompositeConstruct %183 %7 %7 -%469 = OpSGreaterThan %167 %467 %468 -%470 = OpCompositeConstruct %194 %24 %24 %24 -%471 = OpCompositeConstruct %194 %25 %25 %25 -%472 = OpUGreaterThan %122 %470 %471 -%473 = OpCompositeConstruct %26 %14 %14 %14 %14 -%474 = OpCompositeConstruct %26 %3 %3 %3 %3 -%475 = OpFOrdGreaterThan %28 %473 %474 -%476 = OpSGreaterThanEqual %10 %18 %7 -%477 = OpUGreaterThanEqual %10 %24 %25 -%478 = OpFOrdGreaterThanEqual %10 %14 %3 -%479 = OpCompositeConstruct %183 %18 %18 -%480 = OpCompositeConstruct %183 %7 %7 -%481 = OpSGreaterThanEqual %167 %479 %480 -%482 = OpCompositeConstruct %194 %24 %24 %24 -%483 = OpCompositeConstruct %194 %25 %25 %25 -%484 = OpUGreaterThanEqual %122 %482 %483 -%485 = OpCompositeConstruct %26 %14 %14 %14 %14 -%486 = OpCompositeConstruct %26 %3 %3 %3 %3 -%487 = OpFOrdGreaterThanEqual %28 %485 %486 +%422 = OpFunction %2 None %172 +%421 = OpLabel +OpBranch %423 +%423 = OpLabel +%424 = OpIEqual %10 %18 %7 +%425 = OpIEqual %10 %24 %25 +%426 = OpFOrdEqual %10 %14 %3 +%427 = OpCompositeConstruct %191 %18 %18 +%428 = OpCompositeConstruct %191 %7 %7 +%429 = OpIEqual %175 %427 %428 +%430 = OpCompositeConstruct %202 %24 %24 %24 +%431 = OpCompositeConstruct %202 %25 %25 %25 +%432 = OpIEqual %130 %430 %431 +%433 = OpCompositeConstruct %34 %14 %14 %14 %14 +%434 = OpCompositeConstruct %34 %3 %3 %3 %3 +%435 = OpFOrdEqual %36 %433 %434 +%436 = OpINotEqual %10 %18 %7 +%437 = OpINotEqual %10 %24 %25 +%438 = OpFOrdNotEqual %10 %14 %3 +%439 = OpCompositeConstruct %191 %18 %18 +%440 = OpCompositeConstruct %191 %7 %7 +%441 = OpINotEqual %175 %439 %440 +%442 = OpCompositeConstruct %202 %24 %24 %24 +%443 = OpCompositeConstruct %202 %25 %25 %25 +%444 = OpINotEqual %130 %442 %443 +%445 = OpCompositeConstruct %34 %14 %14 %14 %14 +%446 = OpCompositeConstruct %34 %3 %3 %3 %3 +%447 = OpFOrdNotEqual %36 %445 %446 +%448 = OpSLessThan %10 %18 %7 +%449 = OpULessThan %10 %24 %25 +%450 = OpFOrdLessThan %10 %14 %3 +%451 = OpCompositeConstruct %191 %18 %18 +%452 = OpCompositeConstruct %191 %7 %7 +%453 = OpSLessThan %175 %451 %452 +%454 = OpCompositeConstruct %202 %24 %24 %24 +%455 = OpCompositeConstruct %202 %25 %25 %25 +%456 = OpULessThan %130 %454 %455 +%457 = OpCompositeConstruct %34 %14 %14 %14 %14 +%458 = OpCompositeConstruct %34 %3 %3 %3 %3 +%459 = OpFOrdLessThan %36 %457 %458 +%460 = OpSLessThanEqual %10 %18 %7 +%461 = OpULessThanEqual %10 %24 %25 +%462 = OpFOrdLessThanEqual %10 %14 %3 +%463 = OpCompositeConstruct %191 %18 %18 +%464 = OpCompositeConstruct %191 %7 %7 +%465 = OpSLessThanEqual %175 %463 %464 +%466 = OpCompositeConstruct %202 %24 %24 %24 +%467 = OpCompositeConstruct %202 %25 %25 %25 +%468 = OpULessThanEqual %130 %466 %467 +%469 = OpCompositeConstruct %34 %14 %14 %14 %14 +%470 = OpCompositeConstruct %34 %3 %3 %3 %3 +%471 = OpFOrdLessThanEqual %36 %469 %470 +%472 = OpSGreaterThan %10 %18 %7 +%473 = OpUGreaterThan %10 %24 %25 +%474 = OpFOrdGreaterThan %10 %14 %3 +%475 = OpCompositeConstruct %191 %18 %18 +%476 = OpCompositeConstruct %191 %7 %7 +%477 = OpSGreaterThan %175 %475 %476 +%478 = OpCompositeConstruct %202 %24 %24 %24 +%479 = OpCompositeConstruct %202 %25 %25 %25 +%480 = OpUGreaterThan %130 %478 %479 +%481 = OpCompositeConstruct %34 %14 %14 %14 %14 +%482 = OpCompositeConstruct %34 %3 %3 %3 %3 +%483 = OpFOrdGreaterThan %36 %481 %482 +%484 = OpSGreaterThanEqual %10 %18 %7 +%485 = OpUGreaterThanEqual %10 %24 %25 +%486 = OpFOrdGreaterThanEqual %10 %14 %3 +%487 = OpCompositeConstruct %191 %18 %18 +%488 = OpCompositeConstruct %191 %7 %7 +%489 = OpSGreaterThanEqual %175 %487 %488 +%490 = OpCompositeConstruct %202 %24 %24 %24 +%491 = OpCompositeConstruct %202 %25 %25 %25 +%492 = OpUGreaterThanEqual %130 %490 %491 +%493 = OpCompositeConstruct %34 %14 %14 %14 %14 +%494 = OpCompositeConstruct %34 %3 %3 %3 %3 +%495 = OpFOrdGreaterThanEqual %36 %493 %494 OpReturn OpFunctionEnd -%493 = OpFunction %2 None %164 -%492 = OpLabel -%488 = OpVariable %489 Function %7 -%490 = OpVariable %491 Function %57 -OpBranch %494 -%494 = OpLabel -%495 = OpLoad %8 %488 -%496 = OpIAdd %8 %495 %7 -OpStore %488 %496 -%497 = OpLoad %8 %488 -%498 = OpISub %8 %497 %7 -OpStore %488 %498 -%499 = OpLoad %8 %488 -%500 = OpLoad %8 %488 -%501 = OpIMul %8 %499 %500 -OpStore %488 %501 -%502 = OpLoad %8 %488 -%503 = OpLoad %8 %488 -%504 = OpSDiv %8 %502 %503 -OpStore %488 %504 -%505 = OpLoad %8 %488 -%506 = OpSRem %8 %505 %7 -OpStore %488 %506 -%507 = OpLoad %8 %488 -%508 = OpBitwiseAnd %8 %507 %11 -OpStore %488 %508 -%509 = OpLoad %8 %488 -%510 = OpBitwiseOr %8 %509 %11 -OpStore %488 %510 -%511 = OpLoad %8 %488 -%512 = OpBitwiseXor %8 %511 %11 -OpStore %488 %512 -%513 = OpLoad %8 %488 -%514 = OpShiftLeftLogical %8 %513 %24 -OpStore %488 %514 -%515 = OpLoad %8 %488 -%516 = OpShiftRightArithmetic %8 %515 %25 -OpStore %488 %516 -%517 = OpLoad %8 %488 -%518 = OpIAdd %8 %517 %7 -OpStore %488 %518 -%519 = OpLoad %8 %488 -%520 = OpISub %8 %519 %7 -OpStore %488 %520 -%522 = OpAccessChain %521 %490 %25 -%523 = OpLoad %8 %522 -%524 = OpIAdd %8 %523 %7 -%525 = OpAccessChain %521 %490 %25 -OpStore %525 %524 -%526 = OpAccessChain %521 %490 %25 -%527 = OpLoad %8 %526 +%501 = OpFunction %2 None %172 +%500 = OpLabel +%496 = OpVariable %497 Function %7 +%498 = OpVariable %499 Function %65 +OpBranch %502 +%502 = OpLabel +%503 = OpLoad %8 %496 +%504 = OpIAdd %8 %503 %7 +OpStore %496 %504 +%505 = OpLoad %8 %496 +%506 = OpISub %8 %505 %7 +OpStore %496 %506 +%507 = OpLoad %8 %496 +%508 = OpLoad %8 %496 +%509 = OpIMul %8 %507 %508 +OpStore %496 %509 +%510 = OpLoad %8 %496 +%511 = OpLoad %8 %496 +%512 = OpSDiv %8 %510 %511 +OpStore %496 %512 +%513 = OpLoad %8 %496 +%514 = OpSRem %8 %513 %7 +OpStore %496 %514 +%515 = OpLoad %8 %496 +%516 = OpBitwiseAnd %8 %515 %11 +OpStore %496 %516 +%517 = OpLoad %8 %496 +%518 = OpBitwiseOr %8 %517 %11 +OpStore %496 %518 +%519 = OpLoad %8 %496 +%520 = OpBitwiseXor %8 %519 %11 +OpStore %496 %520 +%521 = OpLoad %8 %496 +%522 = OpShiftLeftLogical %8 %521 %24 +OpStore %496 %522 +%523 = OpLoad %8 %496 +%524 = OpShiftRightArithmetic %8 %523 %25 +OpStore %496 %524 +%525 = OpLoad %8 %496 +%526 = OpIAdd %8 %525 %7 +OpStore %496 %526 +%527 = OpLoad %8 %496 %528 = OpISub %8 %527 %7 -%529 = OpAccessChain %521 %490 %25 -OpStore %529 %528 +OpStore %496 %528 +%530 = OpAccessChain %529 %498 %25 +%531 = OpLoad %8 %530 +%532 = OpIAdd %8 %531 %7 +%533 = OpAccessChain %529 %498 %25 +OpStore %533 %532 +%534 = OpAccessChain %529 %498 %25 +%535 = OpLoad %8 %534 +%536 = OpISub %8 %535 %7 +%537 = OpAccessChain %529 %498 %25 +OpStore %537 %536 OpReturn OpFunctionEnd -%531 = OpFunction %2 None %164 -%530 = OpLabel -OpBranch %532 -%532 = OpLabel -%533 = OpFunctionCall %26 %59 -%534 = OpFunctionCall %26 %84 -%535 = OpVectorShuffle %30 %42 %42 0 1 2 -%536 = OpFunctionCall %30 %119 %535 -%537 = OpFunctionCall %4 %132 -%538 = OpFunctionCall %2 %163 -%539 = OpFunctionCall %2 %181 -%540 = OpFunctionCall %2 %365 -%541 = OpFunctionCall %2 %414 -%542 = OpFunctionCall %2 %493 +%539 = OpFunction %2 None %172 +%538 = OpLabel +OpBranch %540 +%540 = OpLabel +%541 = OpSNegate %8 %27 +%542 = OpSNegate %8 %28 +%543 = OpSNegate %8 %29 +%544 = OpSNegate %8 %543 +%545 = OpSNegate %8 %30 +%546 = OpSNegate %8 %545 +%547 = OpSNegate %8 %31 +%548 = OpSNegate %8 %547 +%549 = OpSNegate %8 %548 +%550 = OpSNegate %8 %549 +%551 = OpSNegate %8 %32 +%552 = OpSNegate %8 %551 +%553 = OpSNegate %8 %552 +%554 = OpSNegate %8 %553 +%555 = OpSNegate %8 %33 +%556 = OpSNegate %8 %555 +%557 = OpSNegate %8 %556 +%558 = OpSNegate %8 %557 +OpReturn +OpFunctionEnd +%560 = OpFunction %2 None %172 +%559 = OpLabel +OpBranch %561 +%561 = OpLabel +%562 = OpFunctionCall %34 %67 +%563 = OpFunctionCall %34 %92 +%564 = OpVectorShuffle %38 %50 %50 0 1 2 +%565 = OpFunctionCall %38 %127 %564 +%566 = OpFunctionCall %4 %140 +%567 = OpFunctionCall %2 %171 +%568 = OpFunctionCall %2 %189 +%569 = OpFunctionCall %2 %373 +%570 = OpFunctionCall %2 %422 +%571 = OpFunctionCall %2 %501 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index a8a488dff..9b7d647e3 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -251,6 +251,16 @@ fn assignment() { return; } +fn negation_avoids_prefix_decrement() { + _ = -(-2); + _ = -(-3); + _ = -(-(4)); + _ = -(-(-5)); + _ = -(-(-(-(6)))); + _ = -(-(-(-(-7)))); + _ = -(-(-(-(-8)))); +} + @compute @workgroup_size(1, 1, 1) fn main() { let _e4 = builtins(); From 5b79cca384ad9834f56bd7ecf164210deded054b Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Fri, 18 Nov 2022 17:29:49 +0100 Subject: [PATCH 1854/2212] bump MSRV to 1.63 (#2129) --- .github/workflows/pipeline.yml | 2 +- Cargo.toml | 2 +- README.md | 2 +- src/front/wgsl/number.rs | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 46c427ee0..512571327 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -11,7 +11,7 @@ jobs: - uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: "1.56.0" + toolchain: "1.63.0" override: true - uses: taiki-e/install-action@cargo-hack - uses: taiki-e/install-action@cargo-minimal-versions diff --git a/Cargo.toml b/Cargo.toml index c9f589421..40e8106d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] resolver = "2" -rust-version = "1.56" +rust-version = "1.63" [package.metadata.docs.rs] all-features = true diff --git a/README.md b/README.md index 1e407a959..0de0cd61b 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Crates.io](https://img.shields.io/crates/v/naga.svg?label=naga)](https://crates.io/crates/naga) [![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga) [![Build Status](https://github.com/gfx-rs/naga/workflows/pipeline/badge.svg)](https://github.com/gfx-rs/naga/actions) -![MSRV](https://img.shields.io/badge/rustc-1.56+-blue.svg) +![MSRV](https://img.shields.io/badge/rustc-1.63+-blue.svg) [![codecov.io](https://codecov.io/gh/gfx-rs/naga/branch/master/graph/badge.svg?token=9VOKYO8BM2)](https://codecov.io/gh/gfx-rs/naga) The shader translation library for the needs of [wgpu](https://github.com/gfx-rs/wgpu). diff --git a/src/front/wgsl/number.rs b/src/front/wgsl/number.rs index fafe1d227..6c3d93c39 100644 --- a/src/front/wgsl/number.rs +++ b/src/front/wgsl/number.rs @@ -397,13 +397,13 @@ fn parse_dec_float(input: &str, kind: Option) -> Result { let num = input.parse::().unwrap(); // will never fail num.is_finite() - .then(|| Number::AbstractFloat(num)) + .then_some(Number::AbstractFloat(num)) .ok_or(NumberError::NotRepresentable) } Some(FloatKind::F32) => { let num = input.parse::().unwrap(); // will never fail num.is_finite() - .then(|| Number::F32(num)) + .then_some(Number::F32(num)) .ok_or(NumberError::NotRepresentable) } Some(FloatKind::F16) => Err(NumberError::UnimplementedF16), From 49764947096fd400543599e920681252ba731fde Mon Sep 17 00:00:00 2001 From: Marco Buono Date: Sun, 20 Nov 2022 06:45:45 -0300 Subject: [PATCH 1855/2212] Document `EarlyDepthTest` and `ConservativeDepth` syntax in WGSL (#2132) --- src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index c0f102670..e122d1224 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -246,6 +246,7 @@ pub(crate) type NamedExpressions = FastHashMap, String>; /// - GLSL: `layout(early_fragment_tests) in;` /// - HLSL: `Attribute earlydepthstencil` /// - SPIR-V: `ExecutionMode EarlyFragmentTests` +/// - WGSL: `@early_depth_test` /// /// For more, see: /// - @@ -265,6 +266,7 @@ pub struct EarlyDepthTest { /// - `depth_any` option behaves as if the layout qualifier was not present. /// - HLSL: `SV_DepthGreaterEqual`/`SV_DepthLessEqual`/`SV_Depth` /// - SPIR-V: `ExecutionMode Depth` +/// - WGSL: `@early_depth_test(greater_equal/less_equal/unchanged)` /// /// For more, see: /// - From d1c29534c8614e39f469ab5a555d1ebd5ad0ce9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 2 Dec 2022 09:48:20 +0000 Subject: [PATCH 1856/2212] glsl-in: Fix position propagation in lowering (#2079) When lowering `Select` expressions the position could be wrongfully updated from `AccessBase { constant_index: false }` to `AccessBase { constant_index: true }` this caused dynamic indexing in an array behind a structure to fail if it was stored in a constant. Furthermore the position could also be updated from `Rhs` to `AccessBase`, this could cause issues because `AccessBase` doesn't load variables (which `Rhs` does), so accessing a member from a structure behind a pointer would return the wrong result. --- src/front/glsl/context.rs | 11 ++++--- tests/in/glsl/expressions.frag | 7 ++++ tests/out/wgsl/bevy-pbr-frag.wgsl | 28 ++++++++-------- tests/out/wgsl/expressions-frag.wgsl | 48 +++++++++++++++++++--------- tests/out/wgsl/fma-frag.wgsl | 18 +++++------ 5 files changed, 69 insertions(+), 43 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 48574fc5b..44aea8a30 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -34,7 +34,10 @@ impl ExprPos { /// Returns an lhs position if the current position is lhs otherwise AccessBase const fn maybe_access_base(&self, constant_index: bool) -> Self { match *self { - ExprPos::Lhs => *self, + ExprPos::Lhs + | ExprPos::AccessBase { + constant_index: false, + } => *self, _ => ExprPos::AccessBase { constant_index }, } } @@ -476,7 +479,7 @@ impl Context { ) -> Result<(Option>, Span)> { let HirExpr { ref kind, meta } = stmt.hir_exprs[expr]; - log::debug!("Lowering {:?}", expr); + log::debug!("Lowering {:?} (kind {:?}, pos {:?})", expr, kind, pos); let handle = match *kind { HirExprKind::Access { base, index } => { @@ -537,9 +540,7 @@ impl Context { pointer } HirExprKind::Select { base, ref field } => { - let base = self - .lower_expect_inner(stmt, parser, base, pos.maybe_access_base(true), body)? - .0; + let base = self.lower_expect_inner(stmt, parser, base, pos, body)?.0; parser.field_selection(self, pos, body, base, field, meta)? } diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index 2e386057b..e9f3c59f8 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -144,6 +144,13 @@ void testConstantLength(float a[4u]) { int len = a.length(); } +struct TestStruct { uvec4 array[2]; }; +const TestStruct strct = { { uvec4(0), uvec4(1) } }; + +void indexConstantNonConstantIndex(int i) { + const uvec4 a = strct.array[i]; +} + out vec4 o_color; void main() { privatePointer(global); diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 8c48bd9ae..cdfafde02 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -737,25 +737,25 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ R_1 = R; F0_1 = F0_; diffuseColor_1 = diffuseColor; - let _e57 = light_1.pos; + let _e56 = light_1; let _e59 = v_WorldPosition_1; - light_to_frag = (_e57.xyz - _e59.xyz); + light_to_frag = (_e56.pos.xyz - _e59.xyz); _ = light_to_frag; _ = light_to_frag; let _e65 = light_to_frag; let _e66 = light_to_frag; distance_square = dot(_e65, _e66); _ = distance_square; - let _e71 = light_1.lightParams; - _ = _e71.x; + let _e70 = light_1; + _ = _e70.lightParams.x; let _e73 = distance_square; - let _e75 = light_1.lightParams; - let _e77 = getDistanceAttenuation(_e73, _e75.x); + let _e74 = light_1; + let _e77 = getDistanceAttenuation(_e73, _e74.lightParams.x); rangeAttenuation = _e77; let _e79 = roughness_9; a_1 = _e79; - let _e82 = light_1.lightParams; - radius = _e82.y; + let _e81 = light_1; + radius = _e81.lightParams.y; _ = light_to_frag; _ = R_1; let _e87 = light_to_frag; @@ -918,10 +918,10 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ diffuse = (_e302 * _e311); let _e314 = diffuse; let _e315 = specular_1; - let _e318 = light_1.color; + let _e317 = light_1; let _e321 = rangeAttenuation; let _e322 = NoL_6; - return (((_e314 + _e315) * _e318.xyz) * (_e321 * _e322)); + return (((_e314 + _e315) * _e317.color.xyz) * (_e321 * _e322)); } fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: vec3, view: vec3, R_2: vec3, F0_2: vec3, diffuseColor_2: vec3) -> vec3 { @@ -961,8 +961,8 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: R_3 = R_2; F0_3 = F0_2; diffuseColor_3 = diffuseColor_2; - let _e57 = light_3.direction; - incident_light = _e57.xyz; + let _e56 = light_3; + incident_light = _e56.direction.xyz; let _e60 = incident_light; let _e61 = view_1; _ = (_e60 + _e61); @@ -1031,9 +1031,9 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: specular_2 = _e146; let _e148 = specular_2; let _e149 = diffuse_1; - let _e152 = light_3.color; + let _e151 = light_3; let _e155 = NoL_7; - return (((_e148 + _e149) * _e152.xyz) * _e155); + return (((_e148 + _e149) * _e151.color.xyz) * _e155); } fn main_1() { diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index f92bb53a5..8e4f46ec4 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -6,6 +6,10 @@ struct a_buf { a: array, } +struct TestStruct { + array_: array,2u>, +} + struct FragmentOutput { @location(0) o_color: vec4, } @@ -396,30 +400,44 @@ fn testConstantLength(a_24: array) { return; } +fn indexConstantNonConstantIndex(i: i32) { + var i_1: i32; + var local_5: TestStruct = TestStruct(array,2u>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); + var a_26: vec4; + + _ = (&global_1.a); + i_1 = i; + let _e6 = i_1; + let _e10 = local_5.array_[_e6]; + a_26 = _e10; + return; +} + fn main_1() { - var local_5: f32; + var local_6: f32; _ = (&global_1.a); _ = global; - let _e5 = global; - local_5 = _e5; - privatePointer((&local_5)); - let _e7 = local_5; - global = _e7; - let _e8 = o_color; - _ = _e8.xyzw; - let _e11 = vec4(1.0); - o_color.x = _e11.x; - o_color.y = _e11.y; - o_color.z = _e11.z; - o_color.w = _e11.w; + let _e6 = global; + local_6 = _e6; + privatePointer((&local_6)); + let _e8 = local_6; + global = _e8; + let _e9 = o_color; + _ = _e9.xyzw; + let _e12 = vec4(1.0); + o_color.x = _e12.x; + o_color.y = _e12.y; + o_color.z = _e12.z; + o_color.w = _e12.w; return; } @fragment fn main() -> FragmentOutput { _ = (&global_1.a); + _ = TestStruct(array,2u>(vec4(u32(0)), vec4(u32(1)))); main_1(); - let _e7 = o_color; - return FragmentOutput(_e7); + let _e17 = o_color; + return FragmentOutput(_e17); } diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index cf4c6ff76..08ec9ddd8 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -16,18 +16,18 @@ fn Fma(d: ptr, m: Mat4x3_, s: f32) { m_1 = m; s_1 = s; - let _e7 = (*d).mx; - let _e9 = m_1.mx; + let _e6 = (*d); + let _e8 = m_1; let _e10 = s_1; - (*d).mx = (_e7 + (_e9 * _e10)); - let _e15 = (*d).my; - let _e17 = m_1.my; + (*d).mx = (_e6.mx + (_e8.mx * _e10)); + let _e14 = (*d); + let _e16 = m_1; let _e18 = s_1; - (*d).my = (_e15 + (_e17 * _e18)); - let _e23 = (*d).mz; - let _e25 = m_1.mz; + (*d).my = (_e14.my + (_e16.my * _e18)); + let _e22 = (*d); + let _e24 = m_1; let _e26 = s_1; - (*d).mz = (_e23 + (_e25 * _e26)); + (*d).mz = (_e22.mz + (_e24.mz * _e26)); return; } From bf4e62b1ac78759705f544f71bf0b43b654a163c Mon Sep 17 00:00:00 2001 From: JMS55 <47158642+JMS55@users.noreply.github.com> Date: Mon, 5 Dec 2022 05:03:11 -0500 Subject: [PATCH 1857/2212] Fix textureGather on texture_2d (#2138) * Fix textureGather on texture_2d * Add textureGather u32/i32 tests * Update src/valid/expression.rs Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> * Fix formatting * undo analyzer change Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> --- src/valid/expression.rs | 4 + tests/in/image.wgsl | 21 +- tests/out/glsl/image.gather.Fragment.glsl | 9 +- tests/out/glsl/image.queries.Vertex.glsl | 28 +- tests/out/hlsl/image.hlsl | 17 +- tests/out/msl/image.msl | 7 +- tests/out/spv/image.spvasm | 741 +++++++++++----------- tests/out/wgsl/image.wgsl | 17 +- 8 files changed, 452 insertions(+), 392 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index eb95c0e09..20a6237d9 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -384,6 +384,10 @@ impl super::Validator { kind: crate::ScalarKind::Float, multi: false, } => false, + crate::ImageClass::Sampled { + kind: crate::ScalarKind::Uint | crate::ScalarKind::Sint, + multi: false, + } if gather.is_some() => false, crate::ImageClass::Depth { multi: false } => true, _ => return Err(ExpressionError::InvalidImageClass(class)), }; diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index e1fb11a40..8ece6d7a0 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -45,14 +45,18 @@ var image_1d: texture_1d; @group(0) @binding(1) var image_2d: texture_2d; @group(0) @binding(2) -var image_2d_array: texture_2d_array; +var image_2d_u32: texture_2d; @group(0) @binding(3) -var image_cube: texture_cube; +var image_2d_i32: texture_2d; @group(0) @binding(4) -var image_cube_array: texture_cube_array; +var image_2d_array: texture_2d_array; @group(0) @binding(5) -var image_3d: texture_3d; +var image_cube: texture_cube; @group(0) @binding(6) +var image_cube_array: texture_cube_array; +@group(0) @binding(7) +var image_3d: texture_3d; +@group(0) @binding(8) var image_aa: texture_multisampled_2d; @vertex @@ -71,7 +75,7 @@ fn queries() -> @builtin(position) vec4 { let dim_3d_lod = textureDimensions(image_3d, 1); let dim_2s_ms = textureDimensions(image_aa); - let sum = dim_1d + dim_2d.y + dim_2d_lod.y + dim_2d_array.y + dim_2d_array_lod.y + + let sum = dim_1d + dim_2d.y + dim_2d_lod.y + dim_2d_array.y + dim_2d_array_lod.y + dim_cube.y + dim_cube_lod.y + dim_cube_array.y + dim_cube_array_lod.y + dim_3d.z + dim_3d_lod.z; return vec4(f32(sum)); @@ -134,7 +138,12 @@ fn gather() -> @location(0) vec4 { let s2d_offset = textureGather(3, image_2d, sampler_reg, tc, vec2(3, 1)); let s2d_depth = textureGatherCompare(image_2d_depth, sampler_cmp, tc, dref); let s2d_depth_offset = textureGatherCompare(image_2d_depth, sampler_cmp, tc, dref, vec2(3, 1)); - return s2d + s2d_offset + s2d_depth + s2d_depth_offset; + + let u = textureGather(0, image_2d_u32, sampler_reg, tc); + let i = textureGather(0, image_2d_i32, sampler_reg, tc); + let f = vec4(u) + vec4(i); + + return s2d + s2d_offset + s2d_depth + s2d_depth_offset + f; } @fragment diff --git a/tests/out/glsl/image.gather.Fragment.glsl b/tests/out/glsl/image.gather.Fragment.glsl index 5a44544a2..c7c2fc534 100644 --- a/tests/out/glsl/image.gather.Fragment.glsl +++ b/tests/out/glsl/image.gather.Fragment.glsl @@ -6,6 +6,10 @@ precision highp int; uniform highp sampler2D _group_0_binding_1_fs; +uniform highp usampler2D _group_0_binding_2_fs; + +uniform highp isampler2D _group_0_binding_3_fs; + uniform highp sampler2DShadow _group_1_binding_2_fs; layout(location = 0) out vec4 _fs2p_location0; @@ -16,7 +20,10 @@ void main() { vec4 s2d_offset = textureGatherOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 3); vec4 s2d_depth = textureGather(_group_1_binding_2_fs, vec2(tc), 0.5); vec4 s2d_depth_offset = textureGatherOffset(_group_1_binding_2_fs, vec2(tc), 0.5, ivec2(3, 1)); - _fs2p_location0 = (((s2d + s2d_offset) + s2d_depth) + s2d_depth_offset); + uvec4 u = textureGather(_group_0_binding_2_fs, vec2(tc), 0); + ivec4 i = textureGather(_group_0_binding_3_fs, vec2(tc), 0); + vec4 f = (vec4(u) + vec4(i)); + _fs2p_location0 = ((((s2d + s2d_offset) + s2d_depth) + s2d_depth_offset) + f); return; } diff --git a/tests/out/glsl/image.queries.Vertex.glsl b/tests/out/glsl/image.queries.Vertex.glsl index dfafa041b..d416c73cf 100644 --- a/tests/out/glsl/image.queries.Vertex.glsl +++ b/tests/out/glsl/image.queries.Vertex.glsl @@ -8,15 +8,15 @@ uniform highp sampler2D _group_0_binding_0_vs; uniform highp sampler2D _group_0_binding_1_vs; -uniform highp sampler2DArray _group_0_binding_2_vs; +uniform highp sampler2DArray _group_0_binding_4_vs; -uniform highp samplerCube _group_0_binding_3_vs; +uniform highp samplerCube _group_0_binding_5_vs; -uniform highp samplerCubeArray _group_0_binding_4_vs; +uniform highp samplerCubeArray _group_0_binding_6_vs; -uniform highp sampler3D _group_0_binding_5_vs; +uniform highp sampler3D _group_0_binding_7_vs; -uniform highp sampler2DMS _group_0_binding_6_vs; +uniform highp sampler2DMS _group_0_binding_8_vs; void main() { @@ -24,15 +24,15 @@ void main() { int dim_1d_lod = textureSize(_group_0_binding_0_vs, int(dim_1d)).x; ivec2 dim_2d = textureSize(_group_0_binding_1_vs, 0).xy; ivec2 dim_2d_lod = textureSize(_group_0_binding_1_vs, 1).xy; - ivec2 dim_2d_array = textureSize(_group_0_binding_2_vs, 0).xy; - ivec2 dim_2d_array_lod = textureSize(_group_0_binding_2_vs, 1).xy; - ivec2 dim_cube = textureSize(_group_0_binding_3_vs, 0).xy; - ivec2 dim_cube_lod = textureSize(_group_0_binding_3_vs, 1).xy; - ivec2 dim_cube_array = textureSize(_group_0_binding_4_vs, 0).xy; - ivec2 dim_cube_array_lod = textureSize(_group_0_binding_4_vs, 1).xy; - ivec3 dim_3d = textureSize(_group_0_binding_5_vs, 0).xyz; - ivec3 dim_3d_lod = textureSize(_group_0_binding_5_vs, 1).xyz; - ivec2 dim_2s_ms = textureSize(_group_0_binding_6_vs).xy; + ivec2 dim_2d_array = textureSize(_group_0_binding_4_vs, 0).xy; + ivec2 dim_2d_array_lod = textureSize(_group_0_binding_4_vs, 1).xy; + ivec2 dim_cube = textureSize(_group_0_binding_5_vs, 0).xy; + ivec2 dim_cube_lod = textureSize(_group_0_binding_5_vs, 1).xy; + ivec2 dim_cube_array = textureSize(_group_0_binding_6_vs, 0).xy; + ivec2 dim_cube_array_lod = textureSize(_group_0_binding_6_vs, 1).xy; + ivec3 dim_3d = textureSize(_group_0_binding_7_vs, 0).xyz; + ivec3 dim_3d_lod = textureSize(_group_0_binding_7_vs, 1).xyz; + ivec2 dim_2s_ms = textureSize(_group_0_binding_8_vs).xy; int sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); gl_Position = vec4(float(sum)); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index a21e308da..10a3c38c0 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -9,11 +9,13 @@ Texture1D image_1d_src : register(t7); RWTexture1D image_dst : register(u2); Texture1D image_1d : register(t0); Texture2D image_2d : register(t1); -Texture2DArray image_2d_array : register(t2); -TextureCube image_cube : register(t3); -TextureCubeArray image_cube_array : register(t4); -Texture3D image_3d : register(t5); -Texture2DMS image_aa : register(t6); +Texture2D image_2d_u32_ : register(t2); +Texture2D image_2d_i32_ : register(t3); +Texture2DArray image_2d_array : register(t4); +TextureCube image_cube : register(t5); +TextureCubeArray image_cube_array : register(t6); +Texture3D image_3d : register(t7); +Texture2DMS image_aa : register(t8); SamplerState sampler_reg : register(s0, space1); SamplerComparisonState sampler_cmp : register(s1, space1); Texture2D image_2d_depth : register(t2, space1); @@ -258,7 +260,10 @@ float4 gather() : SV_Target0 float4 s2d_offset_1 = image_2d.GatherAlpha(sampler_reg, tc_2, int2(3, 1)); float4 s2d_depth_1 = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5); float4 s2d_depth_offset = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5, int2(3, 1)); - return (((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset); + uint4 u = image_2d_u32_.Gather(sampler_reg, tc_2); + int4 i = image_2d_i32_.Gather(sampler_reg, tc_2); + float4 f = (float4(u) + float4(i)); + return ((((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset) + f); } float4 depth_no_comparison() : SV_Target0 diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index df247be4f..958e147a3 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -139,6 +139,8 @@ struct gatherOutput { }; fragment gatherOutput gather( metal::texture2d image_2d [[user(fake0)]] +, metal::texture2d image_2d_u32_ [[user(fake0)]] +, metal::texture2d image_2d_i32_ [[user(fake0)]] , metal::sampler sampler_reg [[user(fake0)]] , metal::sampler sampler_cmp [[user(fake0)]] , metal::depth2d image_2d_depth [[user(fake0)]] @@ -148,7 +150,10 @@ fragment gatherOutput gather( metal::float4 s2d_offset_1 = image_2d.gather(sampler_reg, tc_2, const_type_9_, metal::component::w); metal::float4 s2d_depth_1 = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5); metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, const_type_9_); - return gatherOutput { ((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset }; + metal::uint4 u = image_2d_u32_.gather(sampler_reg, tc_2); + metal::int4 i = image_2d_i32_.gather(sampler_reg, tc_2); + metal::float4 f = static_cast(u) + static_cast(i); + return gatherOutput { (((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset) + f }; } diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index f0556d35d..23afaea87 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 306 +; Bound: 323 OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D @@ -9,75 +9,77 @@ OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %76 "main" %73 -OpEntryPoint GLCompute %121 "depth_load" %119 -OpEntryPoint Vertex %142 "queries" %140 -OpEntryPoint Vertex %194 "levels_queries" %193 -OpEntryPoint Fragment %223 "texture_sample" %222 -OpEntryPoint Fragment %252 "texture_sample_comparison" %250 -OpEntryPoint Fragment %272 "gather" %271 -OpEntryPoint Fragment %294 "depth_no_comparison" %293 -OpExecutionMode %76 LocalSize 16 1 1 -OpExecutionMode %121 LocalSize 16 1 1 -OpExecutionMode %223 OriginUpperLeft -OpExecutionMode %252 OriginUpperLeft -OpExecutionMode %272 OriginUpperLeft -OpExecutionMode %294 OriginUpperLeft +OpEntryPoint GLCompute %80 "main" %77 +OpEntryPoint GLCompute %125 "depth_load" %123 +OpEntryPoint Vertex %146 "queries" %144 +OpEntryPoint Vertex %198 "levels_queries" %197 +OpEntryPoint Fragment %227 "texture_sample" %226 +OpEntryPoint Fragment %256 "texture_sample_comparison" %254 +OpEntryPoint Fragment %276 "gather" %275 +OpEntryPoint Fragment %311 "depth_no_comparison" %310 +OpExecutionMode %80 LocalSize 16 1 1 +OpExecutionMode %125 LocalSize 16 1 1 +OpExecutionMode %227 OriginUpperLeft +OpExecutionMode %256 OriginUpperLeft +OpExecutionMode %276 OriginUpperLeft +OpExecutionMode %311 OriginUpperLeft OpSource GLSL 450 -OpName %34 "image_mipmapped_src" -OpName %36 "image_multisampled_src" -OpName %38 "image_depth_multisampled_src" -OpName %40 "image_storage_src" -OpName %42 "image_array_src" -OpName %44 "image_dup_src" -OpName %46 "image_1d_src" -OpName %48 "image_dst" -OpName %50 "image_1d" -OpName %52 "image_2d" -OpName %54 "image_2d_array" -OpName %56 "image_cube" -OpName %58 "image_cube_array" -OpName %60 "image_3d" -OpName %62 "image_aa" -OpName %64 "sampler_reg" -OpName %66 "sampler_cmp" -OpName %68 "image_2d_depth" -OpName %70 "image_cube_depth" -OpName %73 "local_id" -OpName %76 "main" -OpName %119 "local_id" -OpName %121 "depth_load" -OpName %142 "queries" -OpName %194 "levels_queries" -OpName %223 "texture_sample" -OpName %252 "texture_sample_comparison" -OpName %272 "gather" -OpName %294 "depth_no_comparison" -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 0 -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 3 -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 4 -OpDecorate %40 NonWritable -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 1 -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 5 -OpDecorate %44 NonWritable -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 6 -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 7 -OpDecorate %48 NonReadable -OpDecorate %48 DescriptorSet 0 -OpDecorate %48 Binding 2 -OpDecorate %50 DescriptorSet 0 -OpDecorate %50 Binding 0 -OpDecorate %52 DescriptorSet 0 -OpDecorate %52 Binding 1 -OpDecorate %54 DescriptorSet 0 -OpDecorate %54 Binding 2 +OpName %35 "image_mipmapped_src" +OpName %37 "image_multisampled_src" +OpName %39 "image_depth_multisampled_src" +OpName %41 "image_storage_src" +OpName %43 "image_array_src" +OpName %45 "image_dup_src" +OpName %47 "image_1d_src" +OpName %49 "image_dst" +OpName %51 "image_1d" +OpName %53 "image_2d" +OpName %55 "image_2d_u32" +OpName %56 "image_2d_i32" +OpName %58 "image_2d_array" +OpName %60 "image_cube" +OpName %62 "image_cube_array" +OpName %64 "image_3d" +OpName %66 "image_aa" +OpName %68 "sampler_reg" +OpName %70 "sampler_cmp" +OpName %72 "image_2d_depth" +OpName %74 "image_cube_depth" +OpName %77 "local_id" +OpName %80 "main" +OpName %123 "local_id" +OpName %125 "depth_load" +OpName %146 "queries" +OpName %198 "levels_queries" +OpName %227 "texture_sample" +OpName %256 "texture_sample_comparison" +OpName %276 "gather" +OpName %311 "depth_no_comparison" +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 0 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 3 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 4 +OpDecorate %41 NonWritable +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 1 +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 5 +OpDecorate %45 NonWritable +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 6 +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 7 +OpDecorate %49 NonReadable +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 2 +OpDecorate %51 DescriptorSet 0 +OpDecorate %51 Binding 0 +OpDecorate %53 DescriptorSet 0 +OpDecorate %53 Binding 1 +OpDecorate %55 DescriptorSet 0 +OpDecorate %55 Binding 2 OpDecorate %56 DescriptorSet 0 OpDecorate %56 Binding 3 OpDecorate %58 DescriptorSet 0 @@ -86,22 +88,26 @@ OpDecorate %60 DescriptorSet 0 OpDecorate %60 Binding 5 OpDecorate %62 DescriptorSet 0 OpDecorate %62 Binding 6 -OpDecorate %64 DescriptorSet 1 -OpDecorate %64 Binding 0 -OpDecorate %66 DescriptorSet 1 -OpDecorate %66 Binding 1 +OpDecorate %64 DescriptorSet 0 +OpDecorate %64 Binding 7 +OpDecorate %66 DescriptorSet 0 +OpDecorate %66 Binding 8 OpDecorate %68 DescriptorSet 1 -OpDecorate %68 Binding 2 +OpDecorate %68 Binding 0 OpDecorate %70 DescriptorSet 1 -OpDecorate %70 Binding 3 -OpDecorate %73 BuiltIn LocalInvocationId -OpDecorate %119 BuiltIn LocalInvocationId -OpDecorate %140 BuiltIn Position -OpDecorate %193 BuiltIn Position -OpDecorate %222 Location 0 -OpDecorate %250 Location 0 -OpDecorate %271 Location 0 -OpDecorate %293 Location 0 +OpDecorate %70 Binding 1 +OpDecorate %72 DescriptorSet 1 +OpDecorate %72 Binding 2 +OpDecorate %74 DescriptorSet 1 +OpDecorate %74 Binding 3 +OpDecorate %77 BuiltIn LocalInvocationId +OpDecorate %123 BuiltIn LocalInvocationId +OpDecorate %144 BuiltIn Position +OpDecorate %197 BuiltIn Position +OpDecorate %226 Location 0 +OpDecorate %254 Location 0 +OpDecorate %275 Location 0 +OpDecorate %310 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -124,316 +130,333 @@ OpDecorate %293 Location 0 %21 = OpTypeVector %4 2 %22 = OpTypeImage %8 1D 0 0 0 1 Unknown %23 = OpTypeImage %8 2D 0 0 0 1 Unknown -%24 = OpTypeImage %8 2D 0 1 0 1 Unknown -%25 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%26 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%27 = OpTypeImage %8 3D 0 0 0 1 Unknown -%28 = OpTypeImage %8 2D 0 0 1 1 Unknown -%29 = OpTypeVector %8 4 -%30 = OpTypeSampler -%31 = OpTypeImage %8 2D 1 0 0 1 Unknown -%32 = OpTypeImage %8 Cube 1 0 0 1 Unknown -%33 = OpConstantComposite %21 %10 %6 -%35 = OpTypePointer UniformConstant %12 -%34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %14 -%36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %15 -%38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %16 -%40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %17 -%42 = OpVariable %43 UniformConstant -%45 = OpTypePointer UniformConstant %18 -%44 = OpVariable %45 UniformConstant -%47 = OpTypePointer UniformConstant %19 -%46 = OpVariable %47 UniformConstant -%49 = OpTypePointer UniformConstant %18 -%48 = OpVariable %49 UniformConstant -%51 = OpTypePointer UniformConstant %22 -%50 = OpVariable %51 UniformConstant -%53 = OpTypePointer UniformConstant %23 -%52 = OpVariable %53 UniformConstant -%55 = OpTypePointer UniformConstant %24 -%54 = OpVariable %55 UniformConstant -%57 = OpTypePointer UniformConstant %25 +%24 = OpTypeImage %4 2D 0 0 0 1 Unknown +%25 = OpTypeImage %8 2D 0 1 0 1 Unknown +%26 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%27 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%28 = OpTypeImage %8 3D 0 0 0 1 Unknown +%29 = OpTypeImage %8 2D 0 0 1 1 Unknown +%30 = OpTypeVector %8 4 +%31 = OpTypeSampler +%32 = OpTypeImage %8 2D 1 0 0 1 Unknown +%33 = OpTypeImage %8 Cube 1 0 0 1 Unknown +%34 = OpConstantComposite %21 %10 %6 +%36 = OpTypePointer UniformConstant %12 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %14 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %15 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %16 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %17 +%43 = OpVariable %44 UniformConstant +%46 = OpTypePointer UniformConstant %18 +%45 = OpVariable %46 UniformConstant +%48 = OpTypePointer UniformConstant %19 +%47 = OpVariable %48 UniformConstant +%50 = OpTypePointer UniformConstant %18 +%49 = OpVariable %50 UniformConstant +%52 = OpTypePointer UniformConstant %22 +%51 = OpVariable %52 UniformConstant +%54 = OpTypePointer UniformConstant %23 +%53 = OpVariable %54 UniformConstant +%55 = OpVariable %36 UniformConstant +%57 = OpTypePointer UniformConstant %24 %56 = OpVariable %57 UniformConstant -%59 = OpTypePointer UniformConstant %26 +%59 = OpTypePointer UniformConstant %25 %58 = OpVariable %59 UniformConstant -%61 = OpTypePointer UniformConstant %27 +%61 = OpTypePointer UniformConstant %26 %60 = OpVariable %61 UniformConstant -%63 = OpTypePointer UniformConstant %28 +%63 = OpTypePointer UniformConstant %27 %62 = OpVariable %63 UniformConstant -%65 = OpTypePointer UniformConstant %30 +%65 = OpTypePointer UniformConstant %28 %64 = OpVariable %65 UniformConstant -%67 = OpTypePointer UniformConstant %30 +%67 = OpTypePointer UniformConstant %29 %66 = OpVariable %67 UniformConstant %69 = OpTypePointer UniformConstant %31 %68 = OpVariable %69 UniformConstant -%71 = OpTypePointer UniformConstant %32 +%71 = OpTypePointer UniformConstant %31 %70 = OpVariable %71 UniformConstant -%74 = OpTypePointer Input %20 -%73 = OpVariable %74 Input -%77 = OpTypeFunction %2 -%86 = OpTypeVector %13 2 -%94 = OpTypeVector %13 4 -%105 = OpTypeVector %4 3 -%119 = OpVariable %74 Input -%141 = OpTypePointer Output %29 -%140 = OpVariable %141 Output -%151 = OpConstant %13 0 -%193 = OpVariable %141 Output -%222 = OpVariable %141 Output -%228 = OpTypeVector %8 2 -%231 = OpTypeSampledImage %22 -%234 = OpTypeSampledImage %23 -%251 = OpTypePointer Output %8 -%250 = OpVariable %251 Output -%258 = OpTypeSampledImage %31 -%263 = OpConstant %8 0.0 -%264 = OpTypeVector %8 3 -%266 = OpTypeSampledImage %32 -%271 = OpVariable %141 Output -%281 = OpConstant %13 1 -%284 = OpConstant %13 3 -%293 = OpVariable %141 Output -%76 = OpFunction %2 None %77 -%72 = OpLabel -%75 = OpLoad %20 %73 -%78 = OpLoad %12 %34 -%79 = OpLoad %14 %36 -%80 = OpLoad %16 %40 -%81 = OpLoad %17 %42 -%82 = OpLoad %19 %46 -%83 = OpLoad %18 %48 -OpBranch %84 -%84 = OpLabel -%85 = OpImageQuerySize %21 %80 -%87 = OpVectorShuffle %86 %75 %75 0 1 -%88 = OpBitcast %21 %87 -%89 = OpIMul %21 %85 %88 -%90 = OpCompositeConstruct %21 %3 %5 -%91 = OpSRem %21 %89 %90 -%92 = OpCompositeExtract %13 %75 2 -%93 = OpBitcast %4 %92 -%95 = OpImageFetch %94 %78 %91 Lod %93 -%96 = OpCompositeExtract %13 %75 2 +%73 = OpTypePointer UniformConstant %32 +%72 = OpVariable %73 UniformConstant +%75 = OpTypePointer UniformConstant %33 +%74 = OpVariable %75 UniformConstant +%78 = OpTypePointer Input %20 +%77 = OpVariable %78 Input +%81 = OpTypeFunction %2 +%90 = OpTypeVector %13 2 +%98 = OpTypeVector %13 4 +%109 = OpTypeVector %4 3 +%123 = OpVariable %78 Input +%145 = OpTypePointer Output %30 +%144 = OpVariable %145 Output +%155 = OpConstant %13 0 +%197 = OpVariable %145 Output +%226 = OpVariable %145 Output +%232 = OpTypeVector %8 2 +%235 = OpTypeSampledImage %22 +%238 = OpTypeSampledImage %23 +%255 = OpTypePointer Output %8 +%254 = OpVariable %255 Output +%262 = OpTypeSampledImage %32 +%267 = OpConstant %8 0.0 +%268 = OpTypeVector %8 3 +%270 = OpTypeSampledImage %33 +%275 = OpVariable %145 Output +%287 = OpConstant %13 1 +%290 = OpConstant %13 3 +%295 = OpTypeSampledImage %12 +%298 = OpTypeVector %4 4 +%299 = OpTypeSampledImage %24 +%310 = OpVariable %145 Output +%80 = OpFunction %2 None %81 +%76 = OpLabel +%79 = OpLoad %20 %77 +%82 = OpLoad %12 %35 +%83 = OpLoad %14 %37 +%84 = OpLoad %16 %41 +%85 = OpLoad %17 %43 +%86 = OpLoad %19 %47 +%87 = OpLoad %18 %49 +OpBranch %88 +%88 = OpLabel +%89 = OpImageQuerySize %21 %84 +%91 = OpVectorShuffle %90 %79 %79 0 1 +%92 = OpBitcast %21 %91 +%93 = OpIMul %21 %89 %92 +%94 = OpCompositeConstruct %21 %3 %5 +%95 = OpSRem %21 %93 %94 +%96 = OpCompositeExtract %13 %79 2 %97 = OpBitcast %4 %96 -%98 = OpImageFetch %94 %79 %91 Sample %97 -%99 = OpImageRead %94 %80 %91 -%100 = OpCompositeExtract %13 %75 2 +%99 = OpImageFetch %98 %82 %95 Lod %97 +%100 = OpCompositeExtract %13 %79 2 %101 = OpBitcast %4 %100 -%102 = OpCompositeExtract %13 %75 2 -%103 = OpBitcast %4 %102 -%104 = OpIAdd %4 %103 %6 -%106 = OpCompositeConstruct %105 %91 %101 -%107 = OpImageFetch %94 %81 %106 Lod %104 -%108 = OpCompositeExtract %13 %75 0 -%109 = OpBitcast %4 %108 -%110 = OpCompositeExtract %13 %75 2 -%111 = OpBitcast %4 %110 -%112 = OpImageFetch %94 %82 %109 Lod %111 -%113 = OpCompositeExtract %4 %91 0 -%114 = OpIAdd %94 %95 %98 -%115 = OpIAdd %94 %114 %99 -%116 = OpIAdd %94 %115 %107 -%117 = OpIAdd %94 %116 %112 -OpImageWrite %83 %113 %117 +%102 = OpImageFetch %98 %83 %95 Sample %101 +%103 = OpImageRead %98 %84 %95 +%104 = OpCompositeExtract %13 %79 2 +%105 = OpBitcast %4 %104 +%106 = OpCompositeExtract %13 %79 2 +%107 = OpBitcast %4 %106 +%108 = OpIAdd %4 %107 %6 +%110 = OpCompositeConstruct %109 %95 %105 +%111 = OpImageFetch %98 %85 %110 Lod %108 +%112 = OpCompositeExtract %13 %79 0 +%113 = OpBitcast %4 %112 +%114 = OpCompositeExtract %13 %79 2 +%115 = OpBitcast %4 %114 +%116 = OpImageFetch %98 %86 %113 Lod %115 +%117 = OpCompositeExtract %4 %95 0 +%118 = OpIAdd %98 %99 %102 +%119 = OpIAdd %98 %118 %103 +%120 = OpIAdd %98 %119 %111 +%121 = OpIAdd %98 %120 %116 +OpImageWrite %87 %117 %121 OpReturn OpFunctionEnd -%121 = OpFunction %2 None %77 -%118 = OpLabel -%120 = OpLoad %20 %119 -%122 = OpLoad %15 %38 -%123 = OpLoad %16 %40 -%124 = OpLoad %18 %48 -OpBranch %125 -%125 = OpLabel -%126 = OpImageQuerySize %21 %123 -%127 = OpVectorShuffle %86 %120 %120 0 1 -%128 = OpBitcast %21 %127 -%129 = OpIMul %21 %126 %128 -%130 = OpCompositeConstruct %21 %3 %5 -%131 = OpSRem %21 %129 %130 -%132 = OpCompositeExtract %13 %120 2 -%133 = OpBitcast %4 %132 -%134 = OpImageFetch %29 %122 %131 Sample %133 -%135 = OpCompositeExtract %8 %134 0 -%136 = OpCompositeExtract %4 %131 0 -%137 = OpConvertFToU %13 %135 -%138 = OpCompositeConstruct %94 %137 %137 %137 %137 -OpImageWrite %124 %136 %138 +%125 = OpFunction %2 None %81 +%122 = OpLabel +%124 = OpLoad %20 %123 +%126 = OpLoad %15 %39 +%127 = OpLoad %16 %41 +%128 = OpLoad %18 %49 +OpBranch %129 +%129 = OpLabel +%130 = OpImageQuerySize %21 %127 +%131 = OpVectorShuffle %90 %124 %124 0 1 +%132 = OpBitcast %21 %131 +%133 = OpIMul %21 %130 %132 +%134 = OpCompositeConstruct %21 %3 %5 +%135 = OpSRem %21 %133 %134 +%136 = OpCompositeExtract %13 %124 2 +%137 = OpBitcast %4 %136 +%138 = OpImageFetch %30 %126 %135 Sample %137 +%139 = OpCompositeExtract %8 %138 0 +%140 = OpCompositeExtract %4 %135 0 +%141 = OpConvertFToU %13 %139 +%142 = OpCompositeConstruct %98 %141 %141 %141 %141 +OpImageWrite %128 %140 %142 OpReturn OpFunctionEnd -%142 = OpFunction %2 None %77 -%139 = OpLabel -%143 = OpLoad %22 %50 -%144 = OpLoad %23 %52 -%145 = OpLoad %24 %54 -%146 = OpLoad %25 %56 -%147 = OpLoad %26 %58 -%148 = OpLoad %27 %60 -%149 = OpLoad %28 %62 -OpBranch %150 -%150 = OpLabel -%152 = OpImageQuerySizeLod %4 %143 %151 -%154 = OpImageQuerySizeLod %4 %143 %152 -%155 = OpImageQuerySizeLod %21 %144 %151 -%156 = OpImageQuerySizeLod %21 %144 %6 -%157 = OpImageQuerySizeLod %105 %145 %151 -%158 = OpVectorShuffle %21 %157 %157 0 1 -%159 = OpImageQuerySizeLod %105 %145 %6 -%160 = OpVectorShuffle %21 %159 %159 0 1 -%161 = OpImageQuerySizeLod %21 %146 %151 -%162 = OpImageQuerySizeLod %21 %146 %6 -%163 = OpImageQuerySizeLod %105 %147 %151 -%164 = OpVectorShuffle %21 %163 %163 0 0 -%165 = OpImageQuerySizeLod %105 %147 %6 -%166 = OpVectorShuffle %21 %165 %165 0 0 -%167 = OpImageQuerySizeLod %105 %148 %151 -%168 = OpImageQuerySizeLod %105 %148 %6 -%169 = OpImageQuerySize %21 %149 -%170 = OpCompositeExtract %4 %155 1 -%171 = OpIAdd %4 %152 %170 -%172 = OpCompositeExtract %4 %156 1 -%173 = OpIAdd %4 %171 %172 -%174 = OpCompositeExtract %4 %158 1 -%175 = OpIAdd %4 %173 %174 +%146 = OpFunction %2 None %81 +%143 = OpLabel +%147 = OpLoad %22 %51 +%148 = OpLoad %23 %53 +%149 = OpLoad %25 %58 +%150 = OpLoad %26 %60 +%151 = OpLoad %27 %62 +%152 = OpLoad %28 %64 +%153 = OpLoad %29 %66 +OpBranch %154 +%154 = OpLabel +%156 = OpImageQuerySizeLod %4 %147 %155 +%158 = OpImageQuerySizeLod %4 %147 %156 +%159 = OpImageQuerySizeLod %21 %148 %155 +%160 = OpImageQuerySizeLod %21 %148 %6 +%161 = OpImageQuerySizeLod %109 %149 %155 +%162 = OpVectorShuffle %21 %161 %161 0 1 +%163 = OpImageQuerySizeLod %109 %149 %6 +%164 = OpVectorShuffle %21 %163 %163 0 1 +%165 = OpImageQuerySizeLod %21 %150 %155 +%166 = OpImageQuerySizeLod %21 %150 %6 +%167 = OpImageQuerySizeLod %109 %151 %155 +%168 = OpVectorShuffle %21 %167 %167 0 0 +%169 = OpImageQuerySizeLod %109 %151 %6 +%170 = OpVectorShuffle %21 %169 %169 0 0 +%171 = OpImageQuerySizeLod %109 %152 %155 +%172 = OpImageQuerySizeLod %109 %152 %6 +%173 = OpImageQuerySize %21 %153 +%174 = OpCompositeExtract %4 %159 1 +%175 = OpIAdd %4 %156 %174 %176 = OpCompositeExtract %4 %160 1 %177 = OpIAdd %4 %175 %176 -%178 = OpCompositeExtract %4 %161 1 +%178 = OpCompositeExtract %4 %162 1 %179 = OpIAdd %4 %177 %178 -%180 = OpCompositeExtract %4 %162 1 +%180 = OpCompositeExtract %4 %164 1 %181 = OpIAdd %4 %179 %180 -%182 = OpCompositeExtract %4 %164 1 +%182 = OpCompositeExtract %4 %165 1 %183 = OpIAdd %4 %181 %182 %184 = OpCompositeExtract %4 %166 1 %185 = OpIAdd %4 %183 %184 -%186 = OpCompositeExtract %4 %167 2 +%186 = OpCompositeExtract %4 %168 1 %187 = OpIAdd %4 %185 %186 -%188 = OpCompositeExtract %4 %168 2 +%188 = OpCompositeExtract %4 %170 1 %189 = OpIAdd %4 %187 %188 -%190 = OpConvertSToF %8 %189 -%191 = OpCompositeConstruct %29 %190 %190 %190 %190 -OpStore %140 %191 +%190 = OpCompositeExtract %4 %171 2 +%191 = OpIAdd %4 %189 %190 +%192 = OpCompositeExtract %4 %172 2 +%193 = OpIAdd %4 %191 %192 +%194 = OpConvertSToF %8 %193 +%195 = OpCompositeConstruct %30 %194 %194 %194 %194 +OpStore %144 %195 OpReturn OpFunctionEnd -%194 = OpFunction %2 None %77 -%192 = OpLabel -%195 = OpLoad %23 %52 -%196 = OpLoad %24 %54 -%197 = OpLoad %25 %56 -%198 = OpLoad %26 %58 -%199 = OpLoad %27 %60 -%200 = OpLoad %28 %62 -OpBranch %201 -%201 = OpLabel -%202 = OpImageQueryLevels %4 %195 -%203 = OpImageQueryLevels %4 %196 -%204 = OpImageQuerySizeLod %105 %196 %151 -%205 = OpCompositeExtract %4 %204 2 -%206 = OpImageQueryLevels %4 %197 -%207 = OpImageQueryLevels %4 %198 -%208 = OpImageQuerySizeLod %105 %198 %151 +%198 = OpFunction %2 None %81 +%196 = OpLabel +%199 = OpLoad %23 %53 +%200 = OpLoad %25 %58 +%201 = OpLoad %26 %60 +%202 = OpLoad %27 %62 +%203 = OpLoad %28 %64 +%204 = OpLoad %29 %66 +OpBranch %205 +%205 = OpLabel +%206 = OpImageQueryLevels %4 %199 +%207 = OpImageQueryLevels %4 %200 +%208 = OpImageQuerySizeLod %109 %200 %155 %209 = OpCompositeExtract %4 %208 2 -%210 = OpImageQueryLevels %4 %199 -%211 = OpImageQuerySamples %4 %200 -%212 = OpIAdd %4 %205 %209 -%213 = OpIAdd %4 %212 %211 -%214 = OpIAdd %4 %213 %202 -%215 = OpIAdd %4 %214 %203 -%216 = OpIAdd %4 %215 %210 -%217 = OpIAdd %4 %216 %206 -%218 = OpIAdd %4 %217 %207 -%219 = OpConvertSToF %8 %218 -%220 = OpCompositeConstruct %29 %219 %219 %219 %219 -OpStore %193 %220 +%210 = OpImageQueryLevels %4 %201 +%211 = OpImageQueryLevels %4 %202 +%212 = OpImageQuerySizeLod %109 %202 %155 +%213 = OpCompositeExtract %4 %212 2 +%214 = OpImageQueryLevels %4 %203 +%215 = OpImageQuerySamples %4 %204 +%216 = OpIAdd %4 %209 %213 +%217 = OpIAdd %4 %216 %215 +%218 = OpIAdd %4 %217 %206 +%219 = OpIAdd %4 %218 %207 +%220 = OpIAdd %4 %219 %214 +%221 = OpIAdd %4 %220 %210 +%222 = OpIAdd %4 %221 %211 +%223 = OpConvertSToF %8 %222 +%224 = OpCompositeConstruct %30 %223 %223 %223 %223 +OpStore %197 %224 OpReturn OpFunctionEnd -%223 = OpFunction %2 None %77 -%221 = OpLabel -%224 = OpLoad %22 %50 -%225 = OpLoad %23 %52 -%226 = OpLoad %30 %64 -OpBranch %227 -%227 = OpLabel -%229 = OpCompositeConstruct %228 %7 %7 -%230 = OpCompositeExtract %8 %229 0 -%232 = OpSampledImage %231 %224 %226 -%233 = OpImageSampleImplicitLod %29 %232 %230 -%235 = OpSampledImage %234 %225 %226 -%236 = OpImageSampleImplicitLod %29 %235 %229 -%237 = OpSampledImage %234 %225 %226 -%238 = OpImageSampleImplicitLod %29 %237 %229 ConstOffset %33 -%239 = OpSampledImage %234 %225 %226 -%240 = OpImageSampleExplicitLod %29 %239 %229 Lod %9 -%241 = OpSampledImage %234 %225 %226 -%242 = OpImageSampleExplicitLod %29 %241 %229 Lod|ConstOffset %9 %33 -%243 = OpSampledImage %234 %225 %226 -%244 = OpImageSampleImplicitLod %29 %243 %229 Bias|ConstOffset %11 %33 -%245 = OpFAdd %29 %233 %236 -%246 = OpFAdd %29 %245 %238 -%247 = OpFAdd %29 %246 %240 -%248 = OpFAdd %29 %247 %242 -OpStore %222 %248 +%227 = OpFunction %2 None %81 +%225 = OpLabel +%228 = OpLoad %22 %51 +%229 = OpLoad %23 %53 +%230 = OpLoad %31 %68 +OpBranch %231 +%231 = OpLabel +%233 = OpCompositeConstruct %232 %7 %7 +%234 = OpCompositeExtract %8 %233 0 +%236 = OpSampledImage %235 %228 %230 +%237 = OpImageSampleImplicitLod %30 %236 %234 +%239 = OpSampledImage %238 %229 %230 +%240 = OpImageSampleImplicitLod %30 %239 %233 +%241 = OpSampledImage %238 %229 %230 +%242 = OpImageSampleImplicitLod %30 %241 %233 ConstOffset %34 +%243 = OpSampledImage %238 %229 %230 +%244 = OpImageSampleExplicitLod %30 %243 %233 Lod %9 +%245 = OpSampledImage %238 %229 %230 +%246 = OpImageSampleExplicitLod %30 %245 %233 Lod|ConstOffset %9 %34 +%247 = OpSampledImage %238 %229 %230 +%248 = OpImageSampleImplicitLod %30 %247 %233 Bias|ConstOffset %11 %34 +%249 = OpFAdd %30 %237 %240 +%250 = OpFAdd %30 %249 %242 +%251 = OpFAdd %30 %250 %244 +%252 = OpFAdd %30 %251 %246 +OpStore %226 %252 OpReturn OpFunctionEnd -%252 = OpFunction %2 None %77 -%249 = OpLabel -%253 = OpLoad %30 %66 -%254 = OpLoad %31 %68 -%255 = OpLoad %32 %70 -OpBranch %256 -%256 = OpLabel -%257 = OpCompositeConstruct %228 %7 %7 -%259 = OpSampledImage %258 %254 %253 -%260 = OpImageSampleDrefImplicitLod %8 %259 %257 %7 -%261 = OpSampledImage %258 %254 %253 -%262 = OpImageSampleDrefExplicitLod %8 %261 %257 %7 Lod %263 -%265 = OpCompositeConstruct %264 %7 %7 %7 -%267 = OpSampledImage %266 %255 %253 -%268 = OpImageSampleDrefExplicitLod %8 %267 %265 %7 Lod %263 -%269 = OpFAdd %8 %260 %262 -OpStore %250 %269 +%256 = OpFunction %2 None %81 +%253 = OpLabel +%257 = OpLoad %31 %70 +%258 = OpLoad %32 %72 +%259 = OpLoad %33 %74 +OpBranch %260 +%260 = OpLabel +%261 = OpCompositeConstruct %232 %7 %7 +%263 = OpSampledImage %262 %258 %257 +%264 = OpImageSampleDrefImplicitLod %8 %263 %261 %7 +%265 = OpSampledImage %262 %258 %257 +%266 = OpImageSampleDrefExplicitLod %8 %265 %261 %7 Lod %267 +%269 = OpCompositeConstruct %268 %7 %7 %7 +%271 = OpSampledImage %270 %259 %257 +%272 = OpImageSampleDrefExplicitLod %8 %271 %269 %7 Lod %267 +%273 = OpFAdd %8 %264 %266 +OpStore %254 %273 OpReturn OpFunctionEnd -%272 = OpFunction %2 None %77 -%270 = OpLabel -%273 = OpLoad %23 %52 -%274 = OpLoad %30 %64 -%275 = OpLoad %30 %66 -%276 = OpLoad %31 %68 -OpBranch %277 -%277 = OpLabel -%278 = OpCompositeConstruct %228 %7 %7 -%279 = OpSampledImage %234 %273 %274 -%280 = OpImageGather %29 %279 %278 %281 -%282 = OpSampledImage %234 %273 %274 -%283 = OpImageGather %29 %282 %278 %284 ConstOffset %33 -%285 = OpSampledImage %258 %276 %275 -%286 = OpImageDrefGather %29 %285 %278 %7 -%287 = OpSampledImage %258 %276 %275 -%288 = OpImageDrefGather %29 %287 %278 %7 ConstOffset %33 -%289 = OpFAdd %29 %280 %283 -%290 = OpFAdd %29 %289 %286 -%291 = OpFAdd %29 %290 %288 -OpStore %271 %291 +%276 = OpFunction %2 None %81 +%274 = OpLabel +%277 = OpLoad %23 %53 +%278 = OpLoad %12 %55 +%279 = OpLoad %24 %56 +%280 = OpLoad %31 %68 +%281 = OpLoad %31 %70 +%282 = OpLoad %32 %72 +OpBranch %283 +%283 = OpLabel +%284 = OpCompositeConstruct %232 %7 %7 +%285 = OpSampledImage %238 %277 %280 +%286 = OpImageGather %30 %285 %284 %287 +%288 = OpSampledImage %238 %277 %280 +%289 = OpImageGather %30 %288 %284 %290 ConstOffset %34 +%291 = OpSampledImage %262 %282 %281 +%292 = OpImageDrefGather %30 %291 %284 %7 +%293 = OpSampledImage %262 %282 %281 +%294 = OpImageDrefGather %30 %293 %284 %7 ConstOffset %34 +%296 = OpSampledImage %295 %278 %280 +%297 = OpImageGather %98 %296 %284 %155 +%300 = OpSampledImage %299 %279 %280 +%301 = OpImageGather %298 %300 %284 %155 +%302 = OpConvertUToF %30 %297 +%303 = OpConvertSToF %30 %301 +%304 = OpFAdd %30 %302 %303 +%305 = OpFAdd %30 %286 %289 +%306 = OpFAdd %30 %305 %292 +%307 = OpFAdd %30 %306 %294 +%308 = OpFAdd %30 %307 %304 +OpStore %275 %308 OpReturn OpFunctionEnd -%294 = OpFunction %2 None %77 -%292 = OpLabel -%295 = OpLoad %30 %64 -%296 = OpLoad %31 %68 -OpBranch %297 -%297 = OpLabel -%298 = OpCompositeConstruct %228 %7 %7 -%299 = OpSampledImage %258 %296 %295 -%300 = OpImageSampleImplicitLod %29 %299 %298 -%301 = OpCompositeExtract %8 %300 0 -%302 = OpSampledImage %258 %296 %295 -%303 = OpImageGather %29 %302 %298 %151 -%304 = OpCompositeConstruct %29 %301 %301 %301 %301 -%305 = OpFAdd %29 %304 %303 -OpStore %293 %305 +%311 = OpFunction %2 None %81 +%309 = OpLabel +%312 = OpLoad %31 %68 +%313 = OpLoad %32 %72 +OpBranch %314 +%314 = OpLabel +%315 = OpCompositeConstruct %232 %7 %7 +%316 = OpSampledImage %262 %313 %312 +%317 = OpImageSampleImplicitLod %30 %316 %315 +%318 = OpCompositeExtract %8 %317 0 +%319 = OpSampledImage %262 %313 %312 +%320 = OpImageGather %30 %319 %315 %155 +%321 = OpCompositeConstruct %30 %318 %318 %318 %318 +%322 = OpFAdd %30 %321 %320 +OpStore %310 %322 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 062876f22..0c1dc48f8 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -19,14 +19,18 @@ var image_1d: texture_1d; @group(0) @binding(1) var image_2d: texture_2d; @group(0) @binding(2) -var image_2d_array: texture_2d_array; +var image_2d_u32_: texture_2d; @group(0) @binding(3) -var image_cube: texture_cube; +var image_2d_i32_: texture_2d; @group(0) @binding(4) -var image_cube_array: texture_cube_array; +var image_2d_array: texture_2d_array; @group(0) @binding(5) -var image_3d: texture_3d; +var image_cube: texture_cube; @group(0) @binding(6) +var image_cube_array: texture_cube_array; +@group(0) @binding(7) +var image_3d: texture_3d; +@group(0) @binding(8) var image_aa: texture_multisampled_2d; @group(1) @binding(0) var sampler_reg: sampler; @@ -120,7 +124,10 @@ fn gather() -> @location(0) vec4 { let s2d_offset_1 = textureGather(3, image_2d, sampler_reg, tc_2, vec2(3, 1)); let s2d_depth_1 = textureGatherCompare(image_2d_depth, sampler_cmp, tc_2, 0.5); let s2d_depth_offset = textureGatherCompare(image_2d_depth, sampler_cmp, tc_2, 0.5, vec2(3, 1)); - return (((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset); + let u = textureGather(0, image_2d_u32_, sampler_reg, tc_2); + let i = textureGather(0, image_2d_i32_, sampler_reg, tc_2); + let f = (vec4(u) + vec4(i)); + return ((((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset) + f); } @fragment From 8405e387d813201809e78fa174fee23b0914d662 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 15 Nov 2022 14:21:45 +0100 Subject: [PATCH 1858/2212] [wgsl-in] use parse_block in more places --- src/front/wgsl/mod.rs | 41 ++++++++--------------------------------- 1 file changed, 8 insertions(+), 33 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2873e6c73..6117d0066 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -3619,26 +3619,9 @@ impl Parser { return Ok(()); } (Token::Paren('{'), _) => { - self.push_rule_span(Rule::Block, lexer); - // Push a new lexical scope for the block statement - context.symbol_table.push_scope(); - - let _ = lexer.next(); - let mut statements = crate::Block::new(); - while !lexer.skip(Token::Paren('}')) { - self.parse_statement( - lexer, - context.reborrow(), - &mut statements, - is_uniform_control_flow, - )?; - } - // Pop the block statement lexical scope - context.symbol_table.pop_scope(); - - self.pop_rule_span(lexer); - let span = NagaSpan::from(self.pop_rule_span(lexer)); - block.push(crate::Statement::Block(statements), span); + let body = self.parse_block(lexer, context, is_uniform_control_flow)?; + let span = self.pop_rule_span(lexer); + block.push(crate::Statement::Block(body), NagaSpan::from(span)); return Ok(()); } (Token::Word(word), _) => { @@ -3993,7 +3976,6 @@ impl Parser { lexer, context.as_expression(&mut body, &mut emitter), )?; - lexer.expect(Token::Paren('{'))?; body.extend(emitter.finish(context.expressions)); Ok(condition) })?; @@ -4007,14 +3989,8 @@ impl Parser { }, NagaSpan::from(span), ); - // Push a lexical scope for the while loop body - context.symbol_table.push_scope(); - while !lexer.skip(Token::Paren('}')) { - self.parse_statement(lexer, context.reborrow(), &mut body, false)?; - } - // Pop the while loop body lexical scope - context.symbol_table.pop_scope(); + body.extend_block(self.parse_block(lexer, context.reborrow(), false)?); Some(crate::Statement::Loop { body, @@ -4093,11 +4069,9 @@ impl Parser { } lexer.expect(Token::Paren(')'))?; } - lexer.expect(Token::Paren('{'))?; - while !lexer.skip(Token::Paren('}')) { - self.parse_statement(lexer, context.reborrow(), &mut body, false)?; - } + body.extend_block(self.parse_block(lexer, context.reborrow(), false)?); + // Pop the for loop lexical scope context.symbol_table.pop_scope(); @@ -4306,6 +4280,7 @@ impl Parser { }) } + /// compound_statement fn parse_block<'a>( &mut self, lexer: &mut Lexer<'a>, @@ -4326,7 +4301,7 @@ impl Parser { is_uniform_control_flow, )?; } - //Pop the block lexical scope + // Pop the block lexical scope context.symbol_table.pop_scope(); self.pop_rule_span(lexer); From e05706bc48606991aa67d1580faf7e262a0bb8df Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 15 Nov 2022 14:29:11 +0100 Subject: [PATCH 1859/2212] [wgsl] remove fallthrough statement also add support for default to be used with other case selectors --- src/back/wgsl/writer.rs | 48 ++++++++---- src/front/wgsl/mod.rs | 74 +++++++------------ src/front/wgsl/tests.rs | 23 +++++- tests/in/control-flow.wgsl | 9 +-- tests/out/glsl/control-flow.main.Compute.glsl | 10 ++- tests/out/hlsl/control-flow.hlsl | 27 ++++--- tests/out/msl/control-flow.msl | 9 ++- tests/out/spv/control-flow.spvasm | 46 ++++++------ tests/out/wgsl/control-flow.wgsl | 10 +-- tests/wgsl-errors.rs | 22 ------ 10 files changed, 139 insertions(+), 139 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 817fa78b0..34dfba76a 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -880,25 +880,47 @@ impl Writer { }; let l2 = level.next(); - if !cases.is_empty() { - for case in cases { - match case.value { - crate::SwitchValue::Integer(value) => { - writeln!(self.out, "{}case {}{}: {{", l2, value, type_postfix)?; + let mut new_case = true; + for case in cases { + if case.fall_through && !case.body.is_empty() { + // TODO: we could do the same workaround as we did for the HLSL backend + return Err(Error::Unimplemented( + "fall-through switch case block".into(), + )); + } + + match case.value { + crate::SwitchValue::Integer(value) => { + if new_case { + write!(self.out, "{}case ", l2)?; } - crate::SwitchValue::Default => { - writeln!(self.out, "{}default: {{", l2)?; + write!(self.out, "{}{}", value, type_postfix)?; + } + crate::SwitchValue::Default => { + if new_case { + if case.fall_through { + write!(self.out, "{}case ", l2)?; + } else { + write!(self.out, "{}", l2)?; + } } + write!(self.out, "default")?; } + } - for sta in case.body.iter() { - self.write_stmt(module, sta, func_ctx, l2.next())?; - } + new_case = !case.fall_through; - if case.fall_through { - writeln!(self.out, "{}fallthrough;", l2.next())?; - } + if case.fall_through { + write!(self.out, ", ")?; + } else { + writeln!(self.out, ": {{")?; + } + for sta in case.body.iter() { + self.write_stmt(module, sta, func_ctx, l2.next())?; + } + + if !case.fall_through { writeln!(self.out, "{}}}", l2)?; } } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6117d0066..4e2733f69 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1513,13 +1513,20 @@ impl Parser { lexer.span_from(initial) } - fn parse_switch_value<'a>(lexer: &mut Lexer<'a>, uint: bool) -> Result> { - let token_span = lexer.next(); - match token_span.0 { - Token::Number(Ok(Number::U32(num))) if uint => Ok(num as i32), - Token::Number(Ok(Number::I32(num))) if !uint => Ok(num), - Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)), - _ => Err(Error::Unexpected(token_span.1, ExpectedToken::Integer)), + fn parse_switch_value<'a>( + lexer: &mut Lexer<'a>, + uint: bool, + ) -> Result> { + match lexer.next() { + (Token::Word("default"), _) => Ok(crate::SwitchValue::Default), + (Token::Number(Ok(Number::U32(num))), _) if uint => { + Ok(crate::SwitchValue::Integer(num as i32)) + } + (Token::Number(Ok(Number::I32(num))), _) if !uint => { + Ok(crate::SwitchValue::Integer(num)) + } + (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), + (_, span) => Err(Error::Unexpected(span, ExpectedToken::Integer)), } } @@ -3576,34 +3583,6 @@ impl Parser { Ok(()) } - fn parse_switch_case_body<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - mut context: StatementContext<'a, '_, 'out>, - ) -> Result<(bool, crate::Block), Error<'a>> { - let mut body = crate::Block::new(); - // Push a new lexical scope for the switch case body - context.symbol_table.push_scope(); - - lexer.expect(Token::Paren('{'))?; - let fall_through = loop { - // default statements - if lexer.skip(Token::Word("fallthrough")) { - lexer.expect(Token::Separator(';'))?; - lexer.expect(Token::Paren('}'))?; - break true; - } - if lexer.skip(Token::Paren('}')) { - break false; - } - self.parse_statement(lexer, context.reborrow(), &mut body, false)?; - }; - // Pop the switch case body lexical scope - context.symbol_table.pop_scope(); - - Ok((fall_through, body)) - } - fn parse_statement<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, @@ -3928,37 +3907,34 @@ impl Parser { break value; } cases.push(crate::SwitchCase { - value: crate::SwitchValue::Integer(value), + value, body: crate::Block::new(), fall_through: true, }); }; - let (fall_through, body) = - self.parse_switch_case_body(lexer, context.reborrow())?; - + let body = + self.parse_block(lexer, context.reborrow(), false)?; cases.push(crate::SwitchCase { - value: crate::SwitchValue::Integer(value), + value, body, - fall_through, + fall_through: false, }); } (Token::Word("default"), _) => { lexer.skip(Token::Separator(':')); - let (fall_through, body) = - self.parse_switch_case_body(lexer, context.reborrow())?; + + let body = + self.parse_block(lexer, context.reborrow(), false)?; cases.push(crate::SwitchCase { value: crate::SwitchValue::Default, body, - fall_through, + fall_through: false, }); } (Token::Paren('}'), _) => break, - other => { - return Err(Error::Unexpected( - other.1, - ExpectedToken::SwitchItem, - )) + (_, span) => { + return Err(Error::Unexpected(span, ExpectedToken::SwitchItem)) } } } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 33fc541ac..6aaa505d4 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -249,8 +249,7 @@ fn parse_switch() { var pos: f32; switch (3) { case 0, 1: { pos = 0.0; } - case 2: { pos = 1.0; fallthrough; } - case 3: {} + case 2: { pos = 1.0; } default: { pos = 3.0; } } } @@ -267,8 +266,7 @@ fn parse_switch_optional_colon_in_case() { var pos: f32; switch (3) { case 0, 1 { pos = 0.0; } - case 2 { pos = 1.0; fallthrough; } - case 3 {} + case 2 { pos = 1.0; } default { pos = 3.0; } } } @@ -277,6 +275,23 @@ fn parse_switch_optional_colon_in_case() { .unwrap(); } +#[test] +fn parse_switch_default_in_case() { + parse_str( + " + fn main() { + var pos: f32; + switch (3) { + case 0, 1: { pos = 0.0; } + case 2: {} + case default, 3: { pos = 3.0; } + } + } + ", + ) + .unwrap(); +} + #[test] fn parse_parentheses_switch() { parse_str( diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl index 787742d71..5a0ef1cbb 100644 --- a/tests/in/control-flow.wgsl +++ b/tests/in/control-flow.wgsl @@ -22,15 +22,13 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { case 2: { pos = 1; } - case 3: { + case 3, 4: { pos = 2; - fallthrough; } - case 4: { + case 5: { pos = 3; - fallthrough; } - default: { + case default, 6: { pos = 4; } } @@ -54,7 +52,6 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { } case 3: { pos = 2; - fallthrough; } case 4: {} default: { diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index 5446e3609..a66c83a30 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -56,12 +56,16 @@ void main() { pos = 1; break; case 3: - pos = 2; /* fallthrough */ case 4: + pos = 2; + break; + case 5: pos = 3; - /* fallthrough */ + break; default: + /* fallthrough */ + case 6: pos = 4; break; } @@ -81,7 +85,7 @@ void main() { return; case 3: pos = 2; - /* fallthrough */ + return; case 4: return; default: diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index 4b879ef20..354c552a1 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -60,27 +60,30 @@ void main(uint3 global_id : SV_DispatchThreadID) break; } case 3: { + { + } { pos = 2; } - { - pos = 3; - } - { - pos = 4; - } break; } case 4: { + pos = 2; + break; + } + case 5: { + pos = 3; + break; + } + default: { { - pos = 3; } { pos = 4; } break; } - default: { + case 6: { pos = 4; break; } @@ -104,12 +107,8 @@ void main(uint3 global_id : SV_DispatchThreadID) return; } case 3: { - { - pos = 2; - } - { - return; - } + pos = 2; + return; } case 4: { return; diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index 4a0b80566..d00b7ec18 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -69,12 +69,18 @@ kernel void main_( break; } case 3: { - pos = 2; } case 4: { + pos = 2; + break; + } + case 5: { pos = 3; + break; } default: { + } + case 6: { pos = 4; break; } @@ -99,6 +105,7 @@ kernel void main_( } case 3: { pos = 2; + return; } case 4: { return; diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index dfd1b145a..fa00d2dba 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 69 +; Bound: 71 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -92,7 +92,7 @@ OpBranch %50 %50 = OpLabel %52 = OpLoad %4 %37 OpSelectionMerge %53 None -OpSwitch %52 %54 1 %55 2 %56 3 %57 4 %58 +OpSwitch %52 %54 1 %55 2 %56 3 %57 4 %58 5 %59 %55 = OpLabel OpStore %37 %5 OpBranch %53 @@ -100,39 +100,43 @@ OpBranch %53 OpStore %37 %3 OpBranch %53 %57 = OpLabel -OpStore %37 %6 OpBranch %58 %58 = OpLabel +OpStore %37 %6 +OpBranch %53 +%59 = OpLabel OpStore %37 %7 -OpBranch %54 +OpBranch %53 %54 = OpLabel +OpBranch %60 +%60 = OpLabel OpStore %37 %8 OpBranch %53 %53 = OpLabel -OpSelectionMerge %59 None -OpSwitch %9 %60 0 %61 +OpSelectionMerge %61 None +OpSwitch %9 %62 0 %63 +%63 = OpLabel +OpBranch %61 +%62 = OpLabel +OpBranch %61 %61 = OpLabel -OpBranch %59 -%60 = OpLabel -OpBranch %59 -%59 = OpLabel -%62 = OpLoad %4 %37 -OpSelectionMerge %63 None -OpSwitch %62 %64 1 %65 2 %66 3 %67 4 %68 -%65 = OpLabel +%64 = OpLoad %4 %37 +OpSelectionMerge %65 None +OpSwitch %64 %66 1 %67 2 %68 3 %69 4 %70 +%67 = OpLabel OpStore %37 %5 -OpBranch %63 -%66 = OpLabel +OpBranch %65 +%68 = OpLabel OpStore %37 %3 OpReturn -%67 = OpLabel +%69 = OpLabel OpStore %37 %6 -OpBranch %68 -%68 = OpLabel OpReturn -%64 = OpLabel +%70 = OpLabel +OpReturn +%66 = OpLabel OpStore %37 %7 OpReturn -%63 = OpLabel +%65 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl index ce3911f2b..2872406d7 100644 --- a/tests/out/wgsl/control-flow.wgsl +++ b/tests/out/wgsl/control-flow.wgsl @@ -50,15 +50,13 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { case 2: { pos = 1; } - case 3: { + case 3, 4: { pos = 2; - fallthrough; } - case 4: { + case 5: { pos = 3; - fallthrough; } - default: { + case default, 6: { pos = 4; } } @@ -80,7 +78,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { } case 3: { pos = 2; - fallthrough; + return; } case 4: { return; diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index dd3e3dda6..594d92354 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1370,28 +1370,6 @@ fn select() { } } -#[test] -fn last_case_falltrough() { - check_validation! { - " - fn test_falltrough() { - switch(0) { - default: {} - case 0: { - fallthrough; - } - } - } - ": - Err( - naga::valid::ValidationError::Function { - source: naga::valid::FunctionError::LastCaseFallTrough, - .. - }, - ) - } -} - #[test] fn missing_default_case() { check_validation! { From db63877c8c82626682785c4e04a359d4bcba411f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 15 Nov 2022 14:31:21 +0100 Subject: [PATCH 1860/2212] [msl-out] omit extra switch case blocks where possible --- src/back/msl/writer.rs | 17 ++++++++++++++--- tests/out/msl/control-flow.msl | 6 ++---- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7617ca9a6..7cf6ebed6 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2546,19 +2546,30 @@ impl Writer { for case in cases.iter() { match case.value { crate::SwitchValue::Integer(value) => { - writeln!(self.out, "{}case {}{}: {{", lcase, value, type_postfix)?; + write!(self.out, "{}case {}{}:", lcase, value, type_postfix)?; } crate::SwitchValue::Default => { - writeln!(self.out, "{}default: {{", lcase)?; + write!(self.out, "{}default:", lcase)?; } } + + let write_block_braces = !(case.fall_through && case.body.is_empty()); + if write_block_braces { + writeln!(self.out, " {{")?; + } else { + writeln!(self.out)?; + } + self.put_block(lcase.next(), &case.body, context)?; if !case.fall_through && case.body.last().map_or(true, |s| !s.is_terminator()) { writeln!(self.out, "{}break;", lcase.next())?; } - writeln!(self.out, "{}}}", lcase)?; + + if write_block_braces { + writeln!(self.out, "{}}}", lcase)?; + } } writeln!(self.out, "{}}}", level)?; } diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index d00b7ec18..be396e23a 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -68,8 +68,7 @@ kernel void main_( pos = 1; break; } - case 3: { - } + case 3: case 4: { pos = 2; break; @@ -78,8 +77,7 @@ kernel void main_( pos = 3; break; } - default: { - } + default: case 6: { pos = 4; break; From 34551474968f2627da2263d0ab9a6941c57911ef Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 15 Nov 2022 14:32:00 +0100 Subject: [PATCH 1861/2212] [hlsl-out] omit extra switch case blocks where possible --- src/back/hlsl/writer.rs | 23 +++++++++++++++++------ tests/out/hlsl/control-flow.hlsl | 18 ++---------------- 2 files changed, 19 insertions(+), 22 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index c0f244230..0c6ce9bb6 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1825,18 +1825,25 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { for (i, case) in cases.iter().enumerate() { match case.value { - crate::SwitchValue::Integer(value) => writeln!( + crate::SwitchValue::Integer(value) => write!( self.out, - "{}case {}{}: {{", + "{}case {}{}:", indent_level_1, value, type_postfix )?, crate::SwitchValue::Default => { - writeln!(self.out, "{}default: {{", indent_level_1)? + write!(self.out, "{}default:", indent_level_1)? } } + let write_block_braces = !(case.fall_through && case.body.is_empty()); + if write_block_braces { + writeln!(self.out, " {{")?; + } else { + writeln!(self.out)?; + } + // FXC doesn't support fallthrough so we duplicate the body of the following case blocks - if case.fall_through { + if case.fall_through && !case.body.is_empty() { let curr_len = i + 1; let end_case_idx = curr_len + cases @@ -1861,12 +1868,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { for sta in case.body.iter() { self.write_stmt(module, sta, func_ctx, indent_level_2)?; } - if case.body.last().map_or(true, |s| !s.is_terminator()) { + if !case.fall_through + && case.body.last().map_or(true, |s| !s.is_terminator()) + { writeln!(self.out, "{}break;", indent_level_2)?; } } - writeln!(self.out, "{}}}", indent_level_1)?; + if write_block_braces { + writeln!(self.out, "{}}}", indent_level_1)?; + } } writeln!(self.out, "{}}}", level)? diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index 354c552a1..7f7a4b6e5 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -59,14 +59,7 @@ void main(uint3 global_id : SV_DispatchThreadID) pos = 1; break; } - case 3: { - { - } - { - pos = 2; - } - break; - } + case 3: case 4: { pos = 2; break; @@ -75,14 +68,7 @@ void main(uint3 global_id : SV_DispatchThreadID) pos = 3; break; } - default: { - { - } - { - pos = 4; - } - break; - } + default: case 6: { pos = 4; break; From be70a2ec03cd02db0c03cbfb95f49f3b568aa2be Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 15 Nov 2022 14:36:52 +0100 Subject: [PATCH 1862/2212] [spv-out] fix switch cases after default not being output --- src/back/spv/block.rs | 25 ++++--------------------- tests/out/spv/control-flow.spvasm | 2 +- 2 files changed, 5 insertions(+), 22 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 10fd5d72a..3c32ca85c 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1682,26 +1682,20 @@ impl<'w> BlockContext<'w> { let default_id = self.gen_id(); - let mut reached_default = false; let mut raw_cases = Vec::with_capacity(cases.len()); let mut case_ids = Vec::with_capacity(cases.len()); for case in cases.iter() { match case.value { crate::SwitchValue::Integer(value) => { let label_id = self.gen_id(); - // No cases should be added after the default case is encountered - // since the default case catches all - if !reached_default { - raw_cases.push(super::instructions::Case { - value: value as Word, - label_id, - }); - } + raw_cases.push(super::instructions::Case { + value: value as Word, + label_id, + }); case_ids.push(label_id); } crate::SwitchValue::Default => { case_ids.push(default_id); - reached_default = true; } } } @@ -1732,17 +1726,6 @@ impl<'w> BlockContext<'w> { )?; } - // If no default was encountered write a empty block to satisfy the presence of - // a block the default label - if !reached_default { - self.write_block( - default_id, - &[], - BlockExit::Branch { target: merge_id }, - inner_context, - )?; - } - block = Block::new(merge_id); } crate::Statement::Loop { diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index fa00d2dba..cc986fe77 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -92,7 +92,7 @@ OpBranch %50 %50 = OpLabel %52 = OpLoad %4 %37 OpSelectionMerge %53 None -OpSwitch %52 %54 1 %55 2 %56 3 %57 4 %58 5 %59 +OpSwitch %52 %54 1 %55 2 %56 3 %57 4 %58 5 %59 6 %60 %55 = OpLabel OpStore %37 %5 OpBranch %53 From eccdc0aeb1921fc49296e769c45a4f921df6f7fd Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 15 Nov 2022 14:39:39 +0100 Subject: [PATCH 1863/2212] [spv-out] omit extra switch case blocks where possible --- src/back/spv/block.rs | 25 ++++++++++--- tests/out/spv/control-flow.spvasm | 62 +++++++++++++++---------------- 2 files changed, 49 insertions(+), 38 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 3c32ca85c..728af63c2 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1680,26 +1680,36 @@ impl<'w> BlockContext<'w> { spirv::SelectionControl::NONE, )); - let default_id = self.gen_id(); + let mut default_id = None; + // id of previous empty fall-through case + let mut last_id = None; let mut raw_cases = Vec::with_capacity(cases.len()); let mut case_ids = Vec::with_capacity(cases.len()); for case in cases.iter() { + let label_id = last_id.take().unwrap_or_else(|| self.gen_id()); + + if case.fall_through && case.body.is_empty() { + last_id = Some(label_id); + } + + case_ids.push(label_id); + match case.value { crate::SwitchValue::Integer(value) => { - let label_id = self.gen_id(); raw_cases.push(super::instructions::Case { value: value as Word, label_id, }); - case_ids.push(label_id); } crate::SwitchValue::Default => { - case_ids.push(default_id); + default_id = Some(label_id); } } } + let default_id = default_id.unwrap(); + self.function.consume( block, Instruction::switch(selector_id, default_id, &raw_cases), @@ -1710,7 +1720,12 @@ impl<'w> BlockContext<'w> { ..loop_context }; - for (i, (case, label_id)) in cases.iter().zip(case_ids.iter()).enumerate() { + for (i, (case, label_id)) in cases + .iter() + .zip(case_ids.iter()) + .filter(|&(case, _)| !(case.fall_through && case.body.is_empty())) + .enumerate() + { let case_finish_id = if case.fall_through { case_ids[i + 1] } else { diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index cc986fe77..e1885e715 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 71 +; Bound: 69 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -45,11 +45,11 @@ OpFunctionEnd OpBranch %22 %22 = OpLabel OpSelectionMerge %23 None -OpSwitch %5 %24 0 %25 -%25 = OpLabel -OpBranch %23 +OpSwitch %5 %25 0 %24 %24 = OpLabel OpBranch %23 +%25 = OpLabel +OpBranch %23 %23 = OpLabel OpReturn OpFunctionEnd @@ -64,10 +64,10 @@ OpLoopMerge %31 %33 None OpBranch %32 %32 = OpLabel OpSelectionMerge %34 None -OpSwitch %27 %35 1 %36 -%36 = OpLabel -OpBranch %33 +OpSwitch %27 %36 1 %35 %35 = OpLabel +OpBranch %33 +%36 = OpLabel OpBranch %34 %34 = OpLabel OpBranch %33 @@ -92,51 +92,47 @@ OpBranch %50 %50 = OpLabel %52 = OpLoad %4 %37 OpSelectionMerge %53 None -OpSwitch %52 %54 1 %55 2 %56 3 %57 4 %58 5 %59 6 %60 -%55 = OpLabel +OpSwitch %52 %58 1 %54 2 %55 3 %56 4 %56 5 %57 6 %58 +%54 = OpLabel OpStore %37 %5 OpBranch %53 -%56 = OpLabel +%55 = OpLabel OpStore %37 %3 OpBranch %53 -%57 = OpLabel -OpBranch %58 -%58 = OpLabel +%56 = OpLabel OpStore %37 %6 OpBranch %53 -%59 = OpLabel +%57 = OpLabel OpStore %37 %7 OpBranch %53 -%54 = OpLabel -OpBranch %60 -%60 = OpLabel +%58 = OpLabel OpStore %37 %8 OpBranch %53 %53 = OpLabel -OpSelectionMerge %61 None -OpSwitch %9 %62 0 %63 -%63 = OpLabel -OpBranch %61 -%62 = OpLabel -OpBranch %61 +OpSelectionMerge %59 None +OpSwitch %9 %61 0 %60 +%60 = OpLabel +OpBranch %59 %61 = OpLabel -%64 = OpLoad %4 %37 -OpSelectionMerge %65 None -OpSwitch %64 %66 1 %67 2 %68 3 %69 4 %70 -%67 = OpLabel +OpBranch %59 +%59 = OpLabel +%62 = OpLoad %4 %37 +OpSelectionMerge %63 None +OpSwitch %62 %68 1 %64 2 %65 3 %66 4 %67 +%64 = OpLabel OpStore %37 %5 -OpBranch %65 -%68 = OpLabel +OpBranch %63 +%65 = OpLabel OpStore %37 %3 OpReturn -%69 = OpLabel +%66 = OpLabel OpStore %37 %6 OpReturn -%70 = OpLabel +%67 = OpLabel OpReturn -%66 = OpLabel +%68 = OpLabel OpStore %37 %7 OpReturn -%65 = OpLabel +%63 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file From f36adeefaa88fba13cfaa0c79bd6b85a1313b4ce Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 17 Nov 2022 18:10:19 +0100 Subject: [PATCH 1864/2212] [glsl-out] introduce a new block for switch cases --- src/back/glsl/mod.rs | 22 +++++--- tests/out/glsl/control-flow.main.Compute.glsl | 56 ++++++++++++------- 2 files changed, 50 insertions(+), 28 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 3698b7978..72a5d46f7 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1807,23 +1807,29 @@ impl<'a, W: Write> Writer<'a, W> { for case in cases { match case.value { crate::SwitchValue::Integer(value) => { - writeln!(self.out, "{}case {}{}:", l2, value, type_postfix)? + write!(self.out, "{}case {}{}:", l2, value, type_postfix)? } - crate::SwitchValue::Default => writeln!(self.out, "{}default:", l2)?, + crate::SwitchValue::Default => write!(self.out, "{}default:", l2)?, + } + + let write_block_braces = !(case.fall_through && case.body.is_empty()); + if write_block_braces { + writeln!(self.out, " {{")?; + } else { + writeln!(self.out)?; } for sta in case.body.iter() { self.write_stmt(sta, ctx, l2.next())?; } - // Write fallthrough comment if the case is fallthrough, - // otherwise write a break, if the case is not already - // broken out of at the end of its body. - if case.fall_through { - writeln!(self.out, "{}/* fallthrough */", l2.next())?; - } else if case.body.last().map_or(true, |s| !s.is_terminator()) { + if !case.fall_through && case.body.last().map_or(true, |s| !s.is_terminator()) { writeln!(self.out, "{}break;", l2.next())?; } + + if write_block_braces { + writeln!(self.out, "{}}}", l2)?; + } } writeln!(self.out, "{}}}", level)? diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl index a66c83a30..b877f9cb6 100644 --- a/tests/out/glsl/control-flow.main.Compute.glsl +++ b/tests/out/glsl/control-flow.main.Compute.glsl @@ -8,17 +8,20 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; void switch_default_break(int i) { switch(i) { - default: + default: { break; + } } } void switch_case_break() { switch(0) { - case 0: + case 0: { break; - default: + } + default: { break; + } } return; } @@ -26,10 +29,12 @@ void switch_case_break() { void loop_switch_continue(int x) { while(true) { switch(x) { - case 1: + case 1: { continue; - default: + } + default: { break; + } } } return; @@ -43,54 +48,65 @@ void main() { memoryBarrierShared(); barrier(); switch(1) { - default: + default: { pos = 1; break; + } } int _e4 = pos; switch(_e4) { - case 1: + case 1: { pos = 0; break; - case 2: + } + case 2: { pos = 1; break; + } case 3: - /* fallthrough */ - case 4: + case 4: { pos = 2; break; - case 5: + } + case 5: { pos = 3; break; + } default: - /* fallthrough */ - case 6: + case 6: { pos = 4; break; + } } switch(0u) { - case 0u: + case 0u: { break; - default: + } + default: { break; + } } int _e11 = pos; switch(_e11) { - case 1: + case 1: { pos = 0; break; - case 2: + } + case 2: { pos = 1; return; - case 3: + } + case 3: { pos = 2; return; - case 4: + } + case 4: { return; - default: + } + default: { pos = 3; return; + } } } From 63e85b4b159c44b74c357894f2db3910b68bf43f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 17 Nov 2022 18:34:54 +0100 Subject: [PATCH 1865/2212] [doc] explain how case clauses with multiple selectors are supported --- src/lib.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index e122d1224..abd6cb858 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1466,6 +1466,22 @@ pub enum Statement { reject: Block, }, /// Conditionally executes one of multiple blocks, based on the value of the selector. + /// + /// Each case must have a distinct [`value`], exactly one of which must be + /// [`Default`]. The `Default` may appear at any position, and covers all + /// values not explicitly appearing in other cases. A `Default` appearing in + /// the midst of the list of cases does not shadow the cases that follow. + /// + /// Some backend languages don't support fallthrough (HLSL due to FXC, + /// WGSL), and may translate fallthrough cases in the IR by duplicating + /// code. However, all backend languages do support cases selected by + /// multiple values, like `case 1: case 2: case 3: { ... }`. This is + /// represented in the IR as a series of fallthrough cases with empty + /// bodies, except for the last. + /// + /// [`value`]: SwitchCase::value + /// [`body`]: SwitchCase::body + /// [`Default`]: SwitchValue::Default Switch { selector: Handle, //int cases: Vec, From 5a1f43d12d4ab32333ec5bb1b42dfcaa9ae34c4f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 9 Dec 2022 12:37:27 +0100 Subject: [PATCH 1866/2212] [doc] add more switch docs --- src/back/hlsl/writer.rs | 24 +++++++++++++++++++++++- src/back/spv/block.rs | 1 + 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 0c6ce9bb6..e1325e5ab 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1835,6 +1835,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } + // The new block is not only stylistic, it plays a role here: + // We might end up having to write the same case body + // multiple times due to FXC not supporting fallthrough. + // Therefore, some `Expression`s written by `Statement::Emit` + // will end up having the same name (`_expr`). + // So we need to put each case in its own scope. let write_block_braces = !(case.fall_through && case.body.is_empty()); if write_block_braces { writeln!(self.out, " {{")?; @@ -1842,7 +1848,23 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out)?; } - // FXC doesn't support fallthrough so we duplicate the body of the following case blocks + // Although FXC does support a series of case clauses before + // a block[^yes], it does not support fallthrough from a + // non-empty case block to the next[^no]. If this case has a + // non-empty body with a fallthrough, emulate that by + // duplicating the bodies of all the cases it would fall + // into as extensions of this case's own body. This makes + // the HLSL output potentially quadratic in the size of the + // Naga IR. + // + // [^yes]: ```hlsl + // case 1: + // case 2: do_stuff() + // ``` + // [^no]: ```hlsl + // case 1: do_this(); + // case 2: do_that(); + // ``` if case.fall_through && !case.body.is_empty() { let curr_len = i + 1; let end_case_idx = curr_len diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 728af63c2..9bf0b8c89 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1687,6 +1687,7 @@ impl<'w> BlockContext<'w> { let mut raw_cases = Vec::with_capacity(cases.len()); let mut case_ids = Vec::with_capacity(cases.len()); for case in cases.iter() { + // take id of previous empty fall-through case or generate a new one let label_id = last_id.take().unwrap_or_else(|| self.gen_id()); if case.fall_through && case.body.is_empty() { From 4f77cbafb73ae2dac1b0bc2338620b916a0b11a1 Mon Sep 17 00:00:00 2001 From: Jonathan Behrens Date: Mon, 12 Dec 2022 04:56:28 -0500 Subject: [PATCH 1867/2212] [wgsl-out] Write correct scalar kind when width != 4 (#1514) * [wgsl-out] Write correct scalar kind when width != 4 * slight refactoring * Also handle matrix scalar widths * Fix formatting --- src/back/wgsl/writer.rs | 66 ++++++++++++++++++++++----------------- tests/out/wgsl/extra.wgsl | 2 +- 2 files changed, 39 insertions(+), 29 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 34dfba76a..cbdbe1c8a 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -452,11 +452,11 @@ impl Writer { /// Adds no trailing or leading whitespace fn write_value_type(&mut self, module: &Module, inner: &TypeInner) -> BackendResult { match *inner { - TypeInner::Vector { size, kind, .. } => write!( + TypeInner::Vector { size, kind, width } => write!( self.out, "vec{}<{}>", back::vector_size_str(size), - scalar_kind_str(kind), + scalar_kind_str(kind, width), )?, TypeInner::Sampler { comparison: false } => { write!(self.out, "sampler")?; @@ -478,7 +478,7 @@ impl Writer { Ic::Sampled { kind, multi } => ( "", if multi { "multisampled_" } else { "" }, - scalar_kind_str(kind), + scalar_kind_str(kind, 4), "", ), Ic::Depth { multi } => { @@ -508,11 +508,11 @@ impl Writer { write!(self.out, "<{}{}>", format_str, storage_str)?; } } - TypeInner::Scalar { kind, .. } => { - write!(self.out, "{}", scalar_kind_str(kind))?; + TypeInner::Scalar { kind, width } => { + write!(self.out, "{}", scalar_kind_str(kind, width))?; } - TypeInner::Atomic { kind, .. } => { - write!(self.out, "atomic<{}>", scalar_kind_str(kind))?; + TypeInner::Atomic { kind, width } => { + write!(self.out, "atomic<{}>", scalar_kind_str(kind, width))?; } TypeInner::Array { base, @@ -582,12 +582,12 @@ impl Writer { TypeInner::ValuePointer { size: None, kind, - width: _, + width, space, } => { let (address, maybe_access) = address_space_str(space); if let Some(space) = address { - write!(self.out, "ptr<{}, {}", space, scalar_kind_str(kind))?; + write!(self.out, "ptr<{}, {}", space, scalar_kind_str(kind, width))?; if let Some(access) = maybe_access { write!(self.out, ", {}", access)?; } @@ -602,7 +602,7 @@ impl Writer { TypeInner::ValuePointer { size: Some(size), kind, - width: _, + width, space, } => { let (address, maybe_access) = address_space_str(space); @@ -612,7 +612,7 @@ impl Writer { "ptr<{}, vec{}<{}>", space, back::vector_size_str(size), - scalar_kind_str(kind) + scalar_kind_str(kind, width) )?; if let Some(access) = maybe_access { write!(self.out, ", {}", access)?; @@ -1424,17 +1424,24 @@ impl Writer { } => { let inner = func_ctx.info[expr].ty.inner_with(&module.types); match *inner { - TypeInner::Matrix { columns, rows, .. } => { + TypeInner::Matrix { + columns, + rows, + width, + .. + } => { + let scalar_kind_str = scalar_kind_str(kind, convert.unwrap_or(width)); write!( self.out, - "mat{}x{}", + "mat{}x{}<{}>", back::vector_size_str(columns), - back::vector_size_str(rows) + back::vector_size_str(rows), + scalar_kind_str )?; } - TypeInner::Vector { size, .. } => { + TypeInner::Vector { size, width, .. } => { let vector_size_str = back::vector_size_str(size); - let scalar_kind_str = scalar_kind_str(kind); + let scalar_kind_str = scalar_kind_str(kind, convert.unwrap_or(width)); if convert.is_some() { write!(self.out, "vec{}<{}>", vector_size_str, scalar_kind_str)?; } else { @@ -1445,11 +1452,12 @@ impl Writer { )?; } } - TypeInner::Scalar { .. } => { + TypeInner::Scalar { width, .. } => { + let scalar_kind_str = scalar_kind_str(kind, convert.unwrap_or(width)); if convert.is_some() { - write!(self.out, "{}", scalar_kind_str(kind))? + write!(self.out, "{}", scalar_kind_str)? } else { - write!(self.out, "bitcast<{}>", scalar_kind_str(kind))? + write!(self.out, "bitcast<{}>", scalar_kind_str)? } } _ => { @@ -1465,8 +1473,8 @@ impl Writer { } Expression::Splat { size, value } => { let inner = func_ctx.info[value].ty.inner_with(&module.types); - let scalar_kind = match *inner { - crate::TypeInner::Scalar { kind, .. } => kind, + let (scalar_kind, scalar_width) = match *inner { + crate::TypeInner::Scalar { kind, width } => (kind, width), _ => { return Err(Error::Unimplemented(format!( "write_expr expression::splat {:?}", @@ -1474,7 +1482,7 @@ impl Writer { ))); } }; - let scalar = scalar_kind_str(scalar_kind); + let scalar = scalar_kind_str(scalar_kind, scalar_width); let size = back::vector_size_str(size); write!(self.out, "vec{}<{}>(", size, scalar)?; @@ -1931,14 +1939,16 @@ const fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { } } -const fn scalar_kind_str(kind: crate::ScalarKind) -> &'static str { +const fn scalar_kind_str(kind: crate::ScalarKind, width: u8) -> &'static str { use crate::ScalarKind as Sk; - match kind { - Sk::Float => "f32", - Sk::Sint => "i32", - Sk::Uint => "u32", - Sk::Bool => "bool", + match (kind, width) { + (Sk::Float, 8) => "f64", + (Sk::Float, 4) => "f32", + (Sk::Sint, 4) => "i32", + (Sk::Uint, 4) => "u32", + (Sk::Bool, 1) => "bool", + _ => unreachable!(), } } diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index 34a2e176c..8fc91fa2d 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -1,6 +1,6 @@ struct PushConstants { index: u32, - double: vec2, + double: vec2, } struct FragmentIn { From 0197246365ae1e2e3f4b7a65481b3e0b8079f9d4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 9 Dec 2022 14:57:07 -0800 Subject: [PATCH 1868/2212] Ignore `unused_imports` in tests/snapshots.rs. This is for the same reason that we ignore `dead_code`: // A lot of the code can be unused based on configuration flags, // the corresponding warnings aren't helpful. --- tests/snapshots.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 197a29692..9336b60c5 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -1,6 +1,6 @@ // A lot of the code can be unused based on configuration flags, // the corresponding warnings aren't helpful. -#![allow(dead_code)] +#![allow(dead_code, unused_imports)] use std::{ fs, From 2dcb6963fadf6ad000418f54eeffc431b5167e00 Mon Sep 17 00:00:00 2001 From: robtfm <50659922+robtfm@users.noreply.github.com> Date: Mon, 5 Dec 2022 15:59:07 +0000 Subject: [PATCH 1869/2212] add Range::new_from_bounds --- src/arena.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/arena.rs b/src/arena.rs index 5d5cf3793..99d977b2f 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -153,6 +153,15 @@ impl Iterator for Range { } } +impl Range { + pub fn new_from_bounds(first: Handle, last: Handle) -> Self { + Self { + inner: (first.index() as u32)..(last.index() as u32 + 1), + marker: Default::default(), + } + } +} + /// An arena holding some kind of component (e.g., type, constant, /// instruction, etc.) that can be referenced. /// From e671d6b49cc373340fd67b3c5058cd25523f16dd Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 5 Dec 2022 11:53:45 +0100 Subject: [PATCH 1870/2212] [wgsl-in] remove `workgroup_size` builtin --- src/front/wgsl/conv.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index ba4164875..6da7ee4ce 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -32,7 +32,6 @@ pub fn map_built_in(word: &str, span: Span) -> Result> "local_invocation_id" => crate::BuiltIn::LocalInvocationId, "local_invocation_index" => crate::BuiltIn::LocalInvocationIndex, "workgroup_id" => crate::BuiltIn::WorkGroupId, - "workgroup_size" => crate::BuiltIn::WorkGroupSize, "num_workgroups" => crate::BuiltIn::NumWorkGroups, _ => return Err(Error::UnknownBuiltin(span)), }) From bf71b015a1ef596a0b497a5a27a399a5e5cbc178 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 5 Dec 2022 11:56:52 +0100 Subject: [PATCH 1871/2212] [wgsl-out] remove `workgroup_size` builtin --- src/back/wgsl/writer.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index cbdbe1c8a..f9e98e8cd 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1918,7 +1918,6 @@ const fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { Bi::LocalInvocationIndex => Some("local_invocation_index"), Bi::GlobalInvocationId => Some("global_invocation_id"), Bi::WorkGroupId => Some("workgroup_id"), - Bi::WorkGroupSize => Some("workgroup_size"), Bi::NumWorkGroups => Some("num_workgroups"), Bi::SampleIndex => Some("sample_index"), Bi::SampleMask => Some("sample_mask"), From 4748721857297e53b9a77593ec3992d85b22b0dd Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 5 Dec 2022 11:58:52 +0100 Subject: [PATCH 1872/2212] remove comment --- tests/in/image.wgsl | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 8ece6d7a0..47549283b 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -16,11 +16,7 @@ var image_1d_src: texture_1d; var image_dst: texture_storage_1d; @compute @workgroup_size(16) -fn main( - @builtin(local_invocation_id) local_id: vec3, - //TODO: https://github.com/gpuweb/gpuweb/issues/1590 - //@builtin(workgroup_size) wg_size: vec3 -) { +fn main(@builtin(local_invocation_id) local_id: vec3) { let dim = textureDimensions(image_storage_src); let itc = dim * vec2(local_id.xy) % vec2(10, 20); let value1 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); From 36bae0760de2757c67bc4e6f0cdbae27e2f0a638 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 5 Dec 2022 11:29:35 +0100 Subject: [PATCH 1873/2212] remove non-32bit integers --- src/front/wgsl/conv.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 6da7ee4ce..be3c2933f 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -96,17 +96,11 @@ pub fn map_storage_format(word: &str, span: Span) -> Result Option<(crate::ScalarKind, crate::Bytes)> { match word { - "f16" => Some((crate::ScalarKind::Float, 2)), + // "f16" => Some((crate::ScalarKind::Float, 2)), "f32" => Some((crate::ScalarKind::Float, 4)), "f64" => Some((crate::ScalarKind::Float, 8)), - "i8" => Some((crate::ScalarKind::Sint, 1)), - "i16" => Some((crate::ScalarKind::Sint, 2)), "i32" => Some((crate::ScalarKind::Sint, 4)), - "i64" => Some((crate::ScalarKind::Sint, 8)), - "u8" => Some((crate::ScalarKind::Uint, 1)), - "u16" => Some((crate::ScalarKind::Uint, 2)), "u32" => Some((crate::ScalarKind::Uint, 4)), - "u64" => Some((crate::ScalarKind::Uint, 8)), "bool" => Some((crate::ScalarKind::Bool, crate::BOOL_WIDTH)), _ => None, } From ee5c343038b4a8582394ef7a87d997cb3e722743 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 5 Dec 2022 11:39:15 +0100 Subject: [PATCH 1874/2212] fix tests --- tests/wgsl-errors.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 594d92354..7085ac156 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -78,12 +78,12 @@ fn invalid_float() { #[test] fn invalid_texture_sample_type() { check( - "let x: texture_2d;", - r###"error: texture sample type must be one of f32, i32 or u32, but found f16 + "let x: texture_2d;", + r###"error: texture sample type must be one of f32, i32 or u32, but found bool ┌─ wgsl:1:19 │ -1 │ let x: texture_2d; - │ ^^^ must be one of f32, i32 or u32 +1 │ let x: texture_2d; + │ ^^^^ must be one of f32, i32 or u32 "###, ); @@ -373,7 +373,7 @@ fn unknown_scalar_type() { 2 │ let a: vec2; │ ^^^^^^^^^ unknown scalar type │ - = note: Valid scalar types are f16, f32, f64, i8, i16, i32, i64, u8, u16, u32, u64, bool + = note: Valid scalar types are f32, f64, i32, u32, bool "#, ); From 300ffcafbf21b1c5ff8d8c984f5400bf84a50c32 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 5 Dec 2022 11:41:24 +0100 Subject: [PATCH 1875/2212] update error note --- src/front/wgsl/mod.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 4e2733f69..a313752cf 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -279,9 +279,7 @@ impl<'a> Error<'a> { Error::UnknownScalarType(ref bad_span) => ParseError { message: format!("unknown scalar type: '{}'", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "unknown scalar type".into())], - notes: vec!["Valid scalar types are f16, f32, f64, \ - i8, i16, i32, i64, \ - u8, u16, u32, u64, bool" + notes: vec!["Valid scalar types are f32, f64, i32, u32, bool" .into()], }, Error::BadTextureSampleType { From 9a00937b500d98d08824aced17f332aa48517d72 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 5 Dec 2022 11:43:33 +0100 Subject: [PATCH 1876/2212] fix-fmt --- src/front/wgsl/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index a313752cf..80701ce7b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -279,8 +279,7 @@ impl<'a> Error<'a> { Error::UnknownScalarType(ref bad_span) => ParseError { message: format!("unknown scalar type: '{}'", &source[bad_span.clone()]), labels: vec![(bad_span.clone(), "unknown scalar type".into())], - notes: vec!["Valid scalar types are f32, f64, i32, u32, bool" - .into()], + notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()], }, Error::BadTextureSampleType { ref span, From 8f1d82f0d2a10052e43935336b5a325ddaa40f9d Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 18 Nov 2022 20:13:14 +0100 Subject: [PATCH 1877/2212] [wgsl] update reserved keywords --- src/keywords/wgsl.rs | 212 +----------------- .../out/wgsl/931-constant-emitting-vert.wgsl | 2 +- tests/out/wgsl/constant-array-size-vert.wgsl | 2 +- tests/out/wgsl/empty-global-name.wgsl | 4 +- tests/out/wgsl/prepostfix-frag.wgsl | 24 +- 5 files changed, 24 insertions(+), 220 deletions(-) diff --git a/src/keywords/wgsl.rs b/src/keywords/wgsl.rs index 8d077c099..0a2abbfd2 100644 --- a/src/keywords/wgsl.rs +++ b/src/keywords/wgsl.rs @@ -5,8 +5,9 @@ Keywords for [WGSL][wgsl] (WebGPU Shading Language). */ // https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary +// last sync: https://github.com/gpuweb/gpuweb/blob/39f2321f547c8f0b7f473cf1d47fba30b1691303/wgsl/index.bs pub const RESERVED: &[&str] = &[ - // type-defining + // Type-defining Keywords "array", "atomic", "bool", @@ -22,11 +23,9 @@ pub const RESERVED: &[&str] = &[ "mat4x2", "mat4x3", "mat4x4", - "override", "ptr", "sampler", "sampler_comparison", - "struct", "texture_1d", "texture_2d", "texture_2d_array", @@ -47,7 +46,7 @@ pub const RESERVED: &[&str] = &[ "vec2", "vec3", "vec4", - // other + // Other Keywords "bitcast", "break", "case", @@ -58,68 +57,29 @@ pub const RESERVED: &[&str] = &[ "discard", "else", "enable", - "fallthrough", "false", "fn", "for", - "function", "if", "let", "loop", - "private", + "override", "return", - "storage", + "static_assert", + "struct", "switch", "true", "type", - "uniform", "var", "while", - "workgroup", - // reserved - "AppendStructuredBuffer", - "BlendState", - "Buffer", - "ByteAddressBuffer", + // Reserved Words "CompileShader", "ComputeShader", - "ConsumeStructuredBuffer", - "DepthStencilState", - "DepthStencilView", "DomainShader", "GeometryShader", "Hullshader", - "InputPatch", - "LineStream", "NULL", - "OutputPatch", - "PixelShader", - "PointStream", - "RWBuffer", - "RWByteAddressBuffer", - "RWStructuredBuffer", - "RWTexture1D", - "RWTexture1DArray", - "RWTexture2D", - "RWTexture2DArray", - "RWTexture3D", - "RasterizerState", - "RenderTargetView", - "SamplerComparisonState", - "SamplerState", "Self", - "StructuredBuffer", - "Texture1D", - "Texture1DArray", - "Texture2D", - "Texture2DArray", - "Texture2DMS", - "Texture2DMSArray", - "Texture3D", - "TextureCube", - "TextureCubeArray", - "TriangleStream", - "VertexShader", "abstract", "active", "alignas", @@ -128,17 +88,13 @@ pub const RESERVED: &[&str] = &[ "asm", "asm_fragment", "async", - "atomic_uint", "attribute", "auto", "await", "become", - "bf16", "binding_array", "cast", "catch", - "cbuffer", - "char", "class", "co_await", "co_return", @@ -160,7 +116,6 @@ pub const RESERVED: &[&str] = &[ "demote", "demote_to_helper", "do", - "dword", "dynamic_cast", "enum", "explicit", @@ -168,50 +123,18 @@ pub const RESERVED: &[&str] = &[ "extends", "extern", "external", - "f64", + "fallthrough", "filter", "final", "finally", - "fixed", "friend", "from", - "fvec2", - "fvec3", - "fvec4", "fxgroup", "get", "goto", "groupshared", "handle", "highp", - "hvec2", - "hvec3", - "hvec4", - "i16", - "i64", - "i8", - "iimage1D", - "iimage1DArray", - "iimage2D", - "iimage2DArray", - "iimage2DMS", - "iimage2DMSArray", - "iimage2DRect", - "iimage3D", - "iimageBuffer", - "iimageCube", - "iimageCubeArray", - "image1D", - "image1DArray", - "image2D", - "image2DArray", - "image2DMS", - "image2DMSArray", - "image2DRect", - "image3D", - "imageBuffer", - "imageCube", - "imageCubeArray", "impl", "implements", "import", @@ -219,40 +142,11 @@ pub const RESERVED: &[&str] = &[ "inout", "instanceof", "interface", - "invariant", - "isampler1D", - "isampler1DArray", - "isampler2D", - "isampler2DArray", - "isampler2DMS", - "isampler2DMSArray", - "isampler2DRect", - "isampler3D", - "isamplerBuffer", - "isamplerCube", - "isamplerCubeArray", - "isubpassInput", - "isubpassInputMS", - "itexture1D", - "itexture1DArray", - "itexture2D", - "itexture2DArray", - "itexture2DMS", - "itexture2DMSArray", - "itexture2DRect", - "itexture3D", - "itextureBuffer", - "itextureCube", - "itextureCubeArray", "layout", - "line", - "lineadj", "lowp", "macro", "macro_rules", - "mat", "match", - "matrix", "mediump", "meta", "mod", @@ -277,7 +171,6 @@ pub const RESERVED: &[&str] = &[ "pass", "patch", "pixelfragment", - "point", "precise", "precision", "premerge", @@ -293,28 +186,6 @@ pub const RESERVED: &[&str] = &[ "requires", "resource", "restrict", - "row_major", - "samper", - "sampler1D", - "sampler1DArray", - "sampler1DArrayShadow", - "sampler1DShadow", - "sampler2D", - "sampler2DArray", - "sampler2DArrayShadow", - "sampler2DMS", - "sampler2DMSArray", - "sampler2DRect", - "sampler2DRectShadow", - "sampler2DShadow", - "sampler3D", - "sampler3DRect", - "samplerBuffer", - "samplerCube", - "samplerCubeArray", - "samplerCubeArrayShadow", - "samplerCubeShadow", - "samplerShadow", "self", "set", "shared", @@ -322,100 +193,33 @@ pub const RESERVED: &[&str] = &[ "sizeof", "smooth", "snorm", - "stateblock", - "stateblock_state", "static", "static_assert", "static_cast", "std", - "string", - "subpassInput", - "subpassInputMS", "subroutine", "super", - "superp", "target", - "tbuffer", - "technique", - "technique10", - "technique11", "template", - "texture1D", - "texture1DArray", - "texture2D", - "texture2DArray", - "texture2DMS", - "texture2DMSArray", - "texture2DRect", - "texture3D", - "textureBuffer", - "textureCube", - "textureCubeArray", "this", "thread_local", "throw", "trait", - "triangle", - "triangleadj", "try", "typedef", "typeid", "typename", "typeof", - "u16", - "u64", - "u8", - "uimage1D", - "uimage1DArray", - "uimage2D", - "uimage2DArray", - "uimage2DMS", - "uimage2DMSArray", - "uimage2DRect", - "uimage3D", - "uimageBuffer", - "uimageCube", - "uimageCubeArray", "union", "unless", "unorm", "unsafe", - "unsigned", "unsized", - "usampler1D", - "usampler1DArray", - "usampler2D", - "usampler2DArray", - "usampler2DMS", - "usampler2DMSArray", - "usampler2DRect", - "usampler3D", - "usamplerBuffer", - "usamplerCube", - "usamplerCubeArray", "use", "using", - "usubpassInput", - "usubpassInputMS", - "utexture1D", - "utexture1DArray", - "utexture2D", - "utexture2DArray", - "utexture2DMS", - "utexture2DMSArray", - "utexture2DRect", - "utexture3D", - "utextureBuffer", - "utextureCube", - "utextureCubeArray", "varying", - "vec", - "vector", - "vertexfragment", "virtual", - "void", "volatile", - "wchar_t", "wgsl", "where", "with", diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl index 8634d13d6..dfb5a38a0 100644 --- a/tests/out/wgsl/931-constant-emitting-vert.wgsl +++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl @@ -1,4 +1,4 @@ -fn function_() -> f32 { +fn function() -> f32 { return 0.0; } diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index f2f7f9d24..15018270f 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -5,7 +5,7 @@ struct Data { @group(1) @binding(0) var global: Data; -fn function_() -> vec4 { +fn function() -> vec4 { var sum: vec4; var i: i32; diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index 7229ea2f4..c84e56ad8 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -5,7 +5,7 @@ struct type_1 { @group(0) @binding(0) var unnamed: type_1; -fn function_() { +fn function() { let _e8 = unnamed.member; unnamed.member = (_e8 + 1); return; @@ -13,5 +13,5 @@ fn function_() { @compute @workgroup_size(1, 1, 1) fn main() { - function_(); + function(); } diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index 72347bfd6..5515f9827 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -2,9 +2,9 @@ fn main_1() { var scalar_target: i32; var scalar: i32; var vec_target: vec2; - var vec_: vec2; + var vec: vec2; var mat_target: mat4x3; - var mat_: mat4x3; + var mat: mat4x3; scalar = 1; let _e3 = scalar; @@ -14,24 +14,24 @@ fn main_1() { let _e8 = (_e6 - 1); scalar = _e8; scalar_target = _e8; - vec_ = vec2(u32(1)); - let _e14 = vec_; - vec_ = (_e14 - vec2(1u)); + vec = vec2(u32(1)); + let _e14 = vec; + vec = (_e14 - vec2(1u)); vec_target = _e14; - let _e18 = vec_; + let _e18 = vec; let _e21 = (_e18 + vec2(1u)); - vec_ = _e21; + vec = _e21; vec_target = _e21; let _e24 = f32(1); - mat_ = mat4x3(vec3(_e24, 0.0, 0.0), vec3(0.0, _e24, 0.0), vec3(0.0, 0.0, _e24), vec3(0.0, 0.0, 0.0)); - let _e32 = mat_; + mat = mat4x3(vec3(_e24, 0.0, 0.0), vec3(0.0, _e24, 0.0), vec3(0.0, 0.0, _e24), vec3(0.0, 0.0, 0.0)); + let _e32 = mat; let _e34 = vec3(1.0); - mat_ = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); + mat = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); mat_target = _e32; - let _e37 = mat_; + let _e37 = mat; let _e39 = vec3(1.0); let _e41 = (_e37 - mat4x3(_e39, _e39, _e39, _e39)); - mat_ = _e41; + mat = _e41; mat_target = _e41; return; } From 5d8fc3fdcf676c2bf67e20d5475e1169da9ac3d5 Mon Sep 17 00:00:00 2001 From: Avi Weinstock Date: Tue, 13 Dec 2022 04:47:28 -0500 Subject: [PATCH 1878/2212] [wgsl-in/spv-out] Add support for WGSL's `atomicCompareExchangeWeak` (#2165) * Add support for WGSL's `atomicCompareExchangeWeak` with the `__atomic_compare_exchange_result` struct, and add SPIR-V codegen for it. Partially addresses https://github.com/gpuweb/gpuweb/pull/2113, #1755. * Add tests for `atomicCompareExchangeWeak`, and support both u32 and i32 atomics with it. * More thorough typechecking of the struct returned by `atomicCompareExchangeWeak`. --- src/back/spv/block.rs | 46 ++++- src/front/wgsl/mod.rs | 52 +++++- src/lib.rs | 6 +- src/proc/typifier.rs | 16 +- src/valid/expression.rs | 35 ++-- src/valid/function.rs | 29 +++- src/valid/mod.rs | 17 ++ tests/in/atomicCompareExchange.wgsl | 34 ++++ tests/out/spv/atomicCompareExchange.spvasm | 188 +++++++++++++++++++++ tests/out/wgsl/atomicCompareExchange.wgsl | 92 ++++++++++ tests/snapshots.rs | 1 + 11 files changed, 472 insertions(+), 44 deletions(-) create mode 100644 tests/in/atomicCompareExchange.wgsl create mode 100644 tests/out/spv/atomicCompareExchange.spvasm create mode 100644 tests/out/wgsl/atomicCompareExchange.wgsl diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 9bf0b8c89..23d23eec3 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -2078,8 +2078,50 @@ impl<'w> BlockContext<'w> { value_id, ) } - crate::AtomicFunction::Exchange { compare: Some(_) } => { - return Err(Error::FeatureNotImplemented("atomic CompareExchange")); + crate::AtomicFunction::Exchange { compare: Some(cmp) } => { + let scalar_type_id = match *value_inner { + crate::TypeInner::Scalar { kind, width } => { + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind, + width, + pointer_space: None, + })) + } + _ => unimplemented!(), + }; + let bool_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + pointer_space: None, + })); + + let cas_result_id = self.gen_id(); + let equality_result_id = self.gen_id(); + let mut cas_instr = Instruction::new(spirv::Op::AtomicCompareExchange); + cas_instr.set_type(scalar_type_id); + cas_instr.set_result(cas_result_id); + cas_instr.add_operand(pointer_id); + cas_instr.add_operand(scope_constant_id); + cas_instr.add_operand(semantics_id); // semantics if equal + cas_instr.add_operand(semantics_id); // semantics if not equal + cas_instr.add_operand(value_id); + cas_instr.add_operand(self.cached[cmp]); + block.body.push(cas_instr); + block.body.push(Instruction::binary( + spirv::Op::IEqual, + bool_type_id, + equality_result_id, + cas_result_id, + self.cached[cmp], + )); + Instruction::composite_construct( + result_type_id, + id, + &[cas_result_id, equality_result_id], + ) } }; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 80701ce7b..bc68d3e73 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -1630,8 +1630,13 @@ impl Parser { let expression = match *ctx.resolve_type(value)? { crate::TypeInner::Scalar { kind, width } => crate::Expression::AtomicResult { - kind, - width, + ty: ctx.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind, width }, + }, + NagaSpan::UNDEFINED, + ), comparison: false, }, _ => return Err(Error::InvalidAtomicOperandType(value_span)), @@ -1861,9 +1866,48 @@ impl Parser { let expression = match *ctx.resolve_type(value)? { crate::TypeInner::Scalar { kind, width } => { + let bool_ty = ctx.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }, + }, + NagaSpan::UNDEFINED, + ); + let scalar_ty = ctx.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind, width }, + }, + NagaSpan::UNDEFINED, + ); + let struct_ty = ctx.types.insert( + crate::Type { + name: Some("__atomic_compare_exchange_result".to_string()), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("old_value".to_string()), + ty: scalar_ty, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("exchanged".to_string()), + ty: bool_ty, + binding: None, + offset: 4, + }, + ], + span: 8, + }, + }, + NagaSpan::UNDEFINED, + ); crate::Expression::AtomicResult { - kind, - width, + ty: struct_ty, comparison: true, } } diff --git a/src/lib.rs b/src/lib.rs index abd6cb858..9aa8a704b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1401,11 +1401,7 @@ pub enum Expression { /// Result of calling another function. CallResult(Handle), /// Result of an atomic operation. - AtomicResult { - kind: ScalarKind, - width: Bytes, - comparison: bool, - }, + AtomicResult { ty: Handle, comparison: bool }, /// Get the length of an array. /// The expression must resolve to a pointer to an array with a dynamic size. /// diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 9a5922ea7..9df538cc2 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -644,21 +644,7 @@ impl<'a> ResolveContext<'a> { | crate::BinaryOperator::ShiftLeft | crate::BinaryOperator::ShiftRight => past(left)?.clone(), }, - crate::Expression::AtomicResult { - kind, - width, - comparison, - } => { - if comparison { - TypeResolution::Value(Ti::Vector { - size: crate::VectorSize::Bi, - kind, - width, - }) - } else { - TypeResolution::Value(Ti::Scalar { kind, width }) - } - } + crate::Expression::AtomicResult { ty, .. } => TypeResolution::Handle(ty), crate::Expression::Select { accept, .. } => past(accept)?.clone(), crate::Expression::Derivative { axis: _, expr } => past(expr)?.clone(), crate::Expression::Relational { fun, argument } => match fun { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 20a6237d9..a3afc0535 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,5 +1,8 @@ #[cfg(feature = "validate")] -use super::{compose::validate_compose, FunctionInfo, ShaderStages, TypeFlags}; +use super::{ + compose::validate_compose, validate_atomic_compare_exchange_struct, FunctionInfo, ShaderStages, + TypeFlags, +}; #[cfg(feature = "validate")] use crate::arena::UniqueArena; @@ -115,8 +118,8 @@ pub enum ExpressionError { WrongArgumentCount(crate::MathFunction), #[error("Argument [{1}] to {0:?} as expression {2:?} has an invalid type.")] InvalidArgumentType(crate::MathFunction, u32, Handle), - #[error("Atomic result type can't be {0:?} of {1} bytes")] - InvalidAtomicResultType(crate::ScalarKind, crate::Bytes), + #[error("Atomic result type can't be {0:?}")] + InvalidAtomicResultType(Handle), #[error("Shader requires capability {0:?}")] MissingCapabilities(super::Capabilities), } @@ -1389,19 +1392,27 @@ impl super::Validator { ShaderStages::all() } E::CallResult(function) => other_infos[function.index()].available_stages, - E::AtomicResult { - kind, - width, - comparison: _, - } => { - let good = match kind { - crate::ScalarKind::Uint | crate::ScalarKind::Sint => { - self.check_width(kind, width) + E::AtomicResult { ty, comparison } => { + let scalar_predicate = |ty: &crate::TypeInner| match ty { + &crate::TypeInner::Scalar { + kind: kind @ (crate::ScalarKind::Uint | crate::ScalarKind::Sint), + width, + } => self.check_width(kind, width), + _ => false, + }; + let good = match &module.types[ty].inner { + ty if !comparison => scalar_predicate(ty), + &crate::TypeInner::Struct { ref members, .. } if comparison => { + validate_atomic_compare_exchange_struct( + &module.types, + members, + scalar_predicate, + ) } _ => false, }; if !good { - return Err(ExpressionError::InvalidAtomicResultType(kind, width)); + return Err(ExpressionError::InvalidAtomicResultType(ty)); } ShaderStages::all() } diff --git a/src/valid/function.rs b/src/valid/function.rs index 5684f670f..0f0a7b89f 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -2,6 +2,9 @@ use crate::arena::{Arena, UniqueArena}; use crate::arena::{BadHandle, Handle}; +#[cfg(feature = "validate")] +use super::validate_atomic_compare_exchange_struct; + use super::{ analyzer::{UniformityDisruptor, UniformityRequirements}, ExpressionError, FunctionInfo, ModuleInfo, @@ -363,12 +366,26 @@ impl super::Validator { .into_other()); } match context.expressions[result] { - //TODO: support atomic result with comparison - crate::Expression::AtomicResult { - kind, - width, - comparison: false, - } if kind == ptr_kind && width == ptr_width => {} + crate::Expression::AtomicResult { ty, comparison } + if { + let scalar_predicate = |ty: &crate::TypeInner| { + *ty == crate::TypeInner::Scalar { + kind: ptr_kind, + width: ptr_width, + } + }; + match &context.types[ty].inner { + ty if !comparison => scalar_predicate(ty), + &crate::TypeInner::Struct { ref members, .. } if comparison => { + validate_atomic_compare_exchange_struct( + context.types, + members, + scalar_predicate, + ) + } + _ => false, + } + } => {} _ => { return Err(AtomicError::ResultTypeMismatch(result) .with_span_handle(result, context.expressions) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index be2731629..17f3d8da0 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -412,3 +412,20 @@ impl Validator { Ok(mod_info) } } + +#[cfg(feature = "validate")] +fn validate_atomic_compare_exchange_struct( + types: &UniqueArena, + members: &[crate::StructMember], + scalar_predicate: impl FnOnce(&crate::TypeInner) -> bool, +) -> bool { + members.len() == 2 + && members[0].name.as_deref() == Some("old_value") + && scalar_predicate(&types[members[0].ty].inner) + && members[1].name.as_deref() == Some("exchanged") + && types[members[1].ty].inner + == crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + } +} diff --git a/tests/in/atomicCompareExchange.wgsl b/tests/in/atomicCompareExchange.wgsl new file mode 100644 index 000000000..35b91aaf7 --- /dev/null +++ b/tests/in/atomicCompareExchange.wgsl @@ -0,0 +1,34 @@ +let SIZE: u32 = 128u; + +@group(0) @binding(0) +var arr_i32: array, SIZE>; +@group(0) @binding(1) +var arr_u32: array, SIZE>; + +@compute @workgroup_size(1) +fn test_atomic_compare_exchange_i32() { + for(var i = 0u; i < SIZE; i++) { + var old = atomicLoad(&arr_i32[i]); + var exchanged = false; + while(!exchanged) { + let new_ = bitcast(bitcast(old) + 1.0); + let result = atomicCompareExchangeWeak(&arr_i32[i], old, new_); + old = result.old_value; + exchanged = result.exchanged; + } + } +} + +@compute @workgroup_size(1) +fn test_atomic_compare_exchange_u32() { + for(var i = 0u; i < SIZE; i++) { + var old = atomicLoad(&arr_u32[i]); + var exchanged = false; + while(!exchanged) { + let new_ = bitcast(bitcast(old) + 1.0); + let result = atomicCompareExchangeWeak(&arr_u32[i], old, new_); + old = result.old_value; + exchanged = result.exchanged; + } + } +} diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/tests/out/spv/atomicCompareExchange.spvasm new file mode 100644 index 000000000..9587f9aaa --- /dev/null +++ b/tests/out/spv/atomicCompareExchange.spvasm @@ -0,0 +1,188 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 116 +OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %31 "test_atomic_compare_exchange_i32" +OpEntryPoint GLCompute %79 "test_atomic_compare_exchange_u32" +OpExecutionMode %31 LocalSize 1 1 1 +OpExecutionMode %79 LocalSize 1 1 1 +OpDecorate %12 ArrayStride 4 +OpDecorate %13 ArrayStride 4 +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 1 Offset 4 +OpMemberDecorate %15 0 Offset 0 +OpMemberDecorate %15 1 Offset 4 +OpDecorate %16 DescriptorSet 0 +OpDecorate %16 Binding 0 +OpDecorate %17 Block +OpMemberDecorate %17 0 Offset 0 +OpDecorate %19 DescriptorSet 0 +OpDecorate %19 Binding 1 +OpDecorate %20 Block +OpMemberDecorate %20 0 Offset 0 +%2 = OpTypeVoid +%4 = OpTypeInt 32 0 +%3 = OpConstant %4 128 +%5 = OpConstant %4 0 +%6 = OpConstant %4 1 +%8 = OpTypeBool +%7 = OpConstantFalse %8 +%10 = OpTypeFloat 32 +%9 = OpConstant %10 1.0 +%11 = OpTypeInt 32 1 +%12 = OpTypeArray %11 %3 +%13 = OpTypeArray %4 %3 +%14 = OpTypeStruct %11 %8 +%15 = OpTypeStruct %4 %8 +%17 = OpTypeStruct %12 +%18 = OpTypePointer StorageBuffer %17 +%16 = OpVariable %18 StorageBuffer +%20 = OpTypeStruct %13 +%21 = OpTypePointer StorageBuffer %20 +%19 = OpVariable %21 StorageBuffer +%23 = OpTypePointer Function %4 +%25 = OpTypePointer Function %11 +%26 = OpConstantNull %11 +%28 = OpTypePointer Function %8 +%29 = OpConstantNull %8 +%32 = OpTypeFunction %2 +%33 = OpTypePointer StorageBuffer %12 +%35 = OpTypePointer StorageBuffer %13 +%46 = OpTypePointer StorageBuffer %11 +%49 = OpConstant %11 1 +%50 = OpConstant %4 64 +%75 = OpConstantNull %4 +%77 = OpConstantNull %8 +%91 = OpTypePointer StorageBuffer %4 +%31 = OpFunction %2 None %32 +%30 = OpLabel +%22 = OpVariable %23 Function %5 +%24 = OpVariable %25 Function %26 +%27 = OpVariable %28 Function %29 +%34 = OpAccessChain %33 %16 %5 +OpBranch %36 +%36 = OpLabel +OpBranch %37 +%37 = OpLabel +OpLoopMerge %38 %40 None +OpBranch %39 +%39 = OpLabel +%41 = OpLoad %4 %22 +%42 = OpULessThan %8 %41 %3 +OpSelectionMerge %43 None +OpBranchConditional %42 %43 %44 +%44 = OpLabel +OpBranch %38 +%43 = OpLabel +%45 = OpLoad %4 %22 +%47 = OpAccessChain %46 %34 %45 +%48 = OpAtomicLoad %11 %47 %49 %50 +OpStore %24 %48 +OpStore %27 %7 +OpBranch %51 +%51 = OpLabel +OpLoopMerge %52 %54 None +OpBranch %53 +%53 = OpLabel +%55 = OpLoad %8 %27 +%56 = OpLogicalNot %8 %55 +OpSelectionMerge %57 None +OpBranchConditional %56 %57 %58 +%58 = OpLabel +OpBranch %52 +%57 = OpLabel +%59 = OpLoad %11 %24 +%60 = OpBitcast %10 %59 +%61 = OpFAdd %10 %60 %9 +%62 = OpBitcast %11 %61 +%63 = OpLoad %4 %22 +%64 = OpLoad %11 %24 +%66 = OpAccessChain %46 %34 %63 +%67 = OpAtomicCompareExchange %11 %66 %49 %50 %50 %62 %64 +%68 = OpIEqual %8 %67 %64 +%65 = OpCompositeConstruct %14 %67 %68 +%69 = OpCompositeExtract %11 %65 0 +OpStore %24 %69 +%70 = OpCompositeExtract %8 %65 1 +OpStore %27 %70 +OpBranch %54 +%54 = OpLabel +OpBranch %51 +%52 = OpLabel +OpBranch %40 +%40 = OpLabel +%71 = OpLoad %4 %22 +%72 = OpIAdd %4 %71 %6 +OpStore %22 %72 +OpBranch %37 +%38 = OpLabel +OpReturn +OpFunctionEnd +%79 = OpFunction %2 None %32 +%78 = OpLabel +%73 = OpVariable %23 Function %5 +%74 = OpVariable %23 Function %75 +%76 = OpVariable %28 Function %77 +%80 = OpAccessChain %35 %19 %5 +OpBranch %81 +%81 = OpLabel +OpBranch %82 +%82 = OpLabel +OpLoopMerge %83 %85 None +OpBranch %84 +%84 = OpLabel +%86 = OpLoad %4 %73 +%87 = OpULessThan %8 %86 %3 +OpSelectionMerge %88 None +OpBranchConditional %87 %88 %89 +%89 = OpLabel +OpBranch %83 +%88 = OpLabel +%90 = OpLoad %4 %73 +%92 = OpAccessChain %91 %80 %90 +%93 = OpAtomicLoad %4 %92 %49 %50 +OpStore %74 %93 +OpStore %76 %7 +OpBranch %94 +%94 = OpLabel +OpLoopMerge %95 %97 None +OpBranch %96 +%96 = OpLabel +%98 = OpLoad %8 %76 +%99 = OpLogicalNot %8 %98 +OpSelectionMerge %100 None +OpBranchConditional %99 %100 %101 +%101 = OpLabel +OpBranch %95 +%100 = OpLabel +%102 = OpLoad %4 %74 +%103 = OpBitcast %10 %102 +%104 = OpFAdd %10 %103 %9 +%105 = OpBitcast %4 %104 +%106 = OpLoad %4 %73 +%107 = OpLoad %4 %74 +%109 = OpAccessChain %91 %80 %106 +%110 = OpAtomicCompareExchange %4 %109 %49 %50 %50 %105 %107 +%111 = OpIEqual %8 %110 %107 +%108 = OpCompositeConstruct %15 %110 %111 +%112 = OpCompositeExtract %4 %108 0 +OpStore %74 %112 +%113 = OpCompositeExtract %8 %108 1 +OpStore %76 %113 +OpBranch %97 +%97 = OpLabel +OpBranch %94 +%95 = OpLabel +OpBranch %85 +%85 = OpLabel +%114 = OpLoad %4 %73 +%115 = OpIAdd %4 %114 %6 +OpStore %73 %115 +OpBranch %82 +%83 = OpLabel +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/tests/out/wgsl/atomicCompareExchange.wgsl new file mode 100644 index 000000000..b1e2d06a4 --- /dev/null +++ b/tests/out/wgsl/atomicCompareExchange.wgsl @@ -0,0 +1,92 @@ +struct gen___atomic_compare_exchange_result { + old_value: i32, + exchanged: bool, +} + +struct gen___atomic_compare_exchange_result_1 { + old_value: u32, + exchanged: bool, +} + +let SIZE: u32 = 128u; + +@group(0) @binding(0) +var arr_i32_: array,SIZE>; +@group(0) @binding(1) +var arr_u32_: array,SIZE>; + +@compute @workgroup_size(1, 1, 1) +fn test_atomic_compare_exchange_i32_() { + var i: u32 = 0u; + var old: i32; + var exchanged: bool; + + loop { + let _e5 = i; + if (_e5 < SIZE) { + } else { + break; + } + let _e10 = i; + let _e12 = atomicLoad((&arr_i32_[_e10])); + old = _e12; + exchanged = false; + loop { + let _e16 = exchanged; + if !(_e16) { + } else { + break; + } + let _e18 = old; + let new_ = bitcast((bitcast(_e18) + 1.0)); + let _e23 = i; + let _e25 = old; + let _e26 = atomicCompareExchangeWeak((&arr_i32_[_e23]), _e25, new_); + old = _e26.old_value; + exchanged = _e26.exchanged; + } + continuing { + let _e7 = i; + i = (_e7 + 1u); + } + } + return; +} + +@compute @workgroup_size(1, 1, 1) +fn test_atomic_compare_exchange_u32_() { + var i_1: u32 = 0u; + var old_1: u32; + var exchanged_1: bool; + + loop { + let _e5 = i_1; + if (_e5 < SIZE) { + } else { + break; + } + let _e10 = i_1; + let _e12 = atomicLoad((&arr_u32_[_e10])); + old_1 = _e12; + exchanged_1 = false; + loop { + let _e16 = exchanged_1; + if !(_e16) { + } else { + break; + } + let _e18 = old_1; + let new_1 = bitcast((bitcast(_e18) + 1.0)); + let _e23 = i_1; + let _e25 = old_1; + let _e26 = atomicCompareExchangeWeak((&arr_u32_[_e23]), _e25, new_1); + old_1 = _e26.old_value; + exchanged_1 = _e26.exchanged; + } + continuing { + let _e7 = i_1; + i_1 = (_e7 + 1u); + } + } + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 9336b60c5..c38c23f8b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -492,6 +492,7 @@ fn convert_wgsl() { "access", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ("atomicCompareExchange", Targets::SPIRV | Targets::WGSL), ( "padding", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From 76d30e5055f1c3ecd58c1e0d87df4431cc15d065 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 6 Dec 2022 22:15:57 -0800 Subject: [PATCH 1879/2212] Add ValidationFlags::BINDINGS --- src/lib.rs | 1 + src/valid/interface.rs | 38 +++++++++++++++++++++++------ src/valid/mod.rs | 3 +++ tests/out/analysis/collatz.info.ron | 4 +-- tests/out/analysis/shadow.info.ron | 6 ++--- 5 files changed, 39 insertions(+), 13 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9aa8a704b..314cbc516 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -192,6 +192,7 @@ tree. clippy::unneeded_field_pattern, clippy::match_like_matches_macro, clippy::if_same_then_else, + clippy::collapsible_if, clippy::derive_partial_eq_without_eq )] #![warn( diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 072550e9b..85610b068 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -102,6 +102,7 @@ fn storage_usage(access: crate::StorageAccess) -> GlobalUse { struct VaryingContext<'a> { stage: crate::ShaderStage, output: bool, + flags: super::ValidationFlags, types: &'a UniqueArena, type_info: &'a Vec, location_mask: &'a mut BitSet, @@ -284,7 +285,10 @@ impl VaryingContext<'_> { return Err(VaryingError::NotIOShareableType(ty)); } if !self.location_mask.insert(location as usize) { - return Err(VaryingError::BindingCollision { location }); + #[cfg(feature = "validate")] + if self.flags.contains(super::ValidationFlags::BINDINGS) { + return Err(VaryingError::BindingCollision { location }); + } } let needs_interpolation = match self.stage { @@ -335,9 +339,15 @@ impl VaryingContext<'_> { for (index, member) in members.iter().enumerate() { let span_context = self.types.get_span_context(ty); match member.binding { - None => { - return Err(VaryingError::MemberMissingBinding(index as u32) - .with_span_context(span_context)) + None => + { + #[cfg(feature = "validate")] + if self.flags.contains(super::ValidationFlags::BINDINGS) { + return Err(VaryingError::MemberMissingBinding( + index as u32, + ) + .with_span_context(span_context)); + } } // TODO: shouldn't this be validate? Some(ref binding) => self @@ -346,7 +356,13 @@ impl VaryingContext<'_> { } } } - _ => return Err(VaryingError::MissingBinding.with_span()), + _ => + { + #[cfg(feature = "validate")] + if self.flags.contains(super::ValidationFlags::BINDINGS) { + return Err(VaryingError::MissingBinding.with_span()); + } + } } Ok(()) } @@ -441,7 +457,9 @@ impl super::Validator { } if is_resource != var.binding.is_some() { - return Err(GlobalVariableError::InvalidBinding); + if self.flags.contains(super::ValidationFlags::BINDINGS) { + return Err(GlobalVariableError::InvalidBinding); + } } Ok(()) @@ -497,6 +515,7 @@ impl super::Validator { let mut ctx = VaryingContext { stage: ep.stage, output: false, + flags: self.flags, types: &module.types, type_info: &self.types, location_mask: &mut self.location_mask, @@ -513,6 +532,7 @@ impl super::Validator { let mut ctx = VaryingContext { stage: ep.stage, output: true, + flags: self.flags, types: &module.types, type_info: &self.types, location_mask: &mut self.location_mask, @@ -571,8 +591,10 @@ impl super::Validator { self.bind_group_masks.push(BitSet::new()); } if !self.bind_group_masks[bind.group as usize].insert(bind.binding as usize) { - return Err(EntryPointError::BindingCollision(var_handle) - .with_span_handle(var_handle, &module.global_variables)); + if self.flags.contains(super::ValidationFlags::BINDINGS) { + return Err(EntryPointError::BindingCollision(var_handle) + .with_span_handle(var_handle, &module.global_variables)); + } } } } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 17f3d8da0..255d6f428 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -66,6 +66,9 @@ bitflags::bitflags! { /// Constants. #[cfg(feature = "validate")] const CONSTANTS = 0x10; + /// Group, binding, and location attributes. + #[cfg(feature = "validate")] + const BINDINGS = 0x20; } } diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index cba89d576..3e1805c6f 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -2,7 +2,7 @@ functions: [ ( flags: ( - bits: 31, + bits: 63, ), available_stages: ( bits: 7, @@ -346,7 +346,7 @@ entry_points: [ ( flags: ( - bits: 31, + bits: 63, ), available_stages: ( bits: 7, diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 9f721bce9..01a3c9655 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -2,7 +2,7 @@ functions: [ ( flags: ( - bits: 31, + bits: 63, ), available_stages: ( bits: 7, @@ -1068,7 +1068,7 @@ ), ( flags: ( - bits: 31, + bits: 63, ), available_stages: ( bits: 7, @@ -2871,7 +2871,7 @@ entry_points: [ ( flags: ( - bits: 31, + bits: 63, ), available_stages: ( bits: 7, From 3c26ffb07a9708634d5b874f6564384ef1f06d25 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Thu, 15 Dec 2022 14:12:24 -0500 Subject: [PATCH 1880/2212] fix(docs): fix invalid `<...>` URLs with code spans --- src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 314cbc516..4b1e7e576 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1262,7 +1262,7 @@ pub enum Expression { /// Load a value indirectly. /// /// For [`TypeInner::Atomic`] the result is a corresponding scalar. - /// For other types behind the pointer, the result is T. + /// For other types behind the `pointer`, the result is `T`. Load { pointer: Handle }, /// Sample a point from a sampled or a depth image. ImageSample { @@ -1562,7 +1562,7 @@ pub enum Statement { /// /// For [`TypeInner::Atomic`] type behind the pointer, the value /// has to be a corresponding scalar. - /// For other types behind the pointer, the value is T. + /// For other types behind the `pointer`, the value is `T`. /// /// This statement is a barrier for any operations on the /// `Expression::LocalVariable` or `Expression::GlobalVariable` From 420c9845f8f9f9a2103e3e3b798fe15da5e111b2 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Thu, 15 Dec 2022 14:13:46 -0500 Subject: [PATCH 1881/2212] refactor: resolve `clippy::manual_clamp` --- src/front/glsl/constants.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 9b30b9c37..53b3b77a3 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -224,12 +224,12 @@ impl<'a> ConstantSolver<'a> { ScalarValue::Sint(a), ScalarValue::Sint(b), ScalarValue::Sint(c), - ) => ScalarValue::Sint(a.max(b).min(c)), + ) => ScalarValue::Sint(a.clamp(b, c)), ( ScalarValue::Uint(a), ScalarValue::Uint(b), ScalarValue::Uint(c), - ) => ScalarValue::Uint(a.max(b).min(c)), + ) => ScalarValue::Uint(a.clamp(b, c)), ( ScalarValue::Float(a), ScalarValue::Float(b), From 461fdda4250cdf9aa49de960afd0fa5042a51bc9 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Fri, 16 Dec 2022 17:26:43 -0700 Subject: [PATCH 1882/2212] Add handle validation pass to `Validator` (#2090) Before proceeding with any other validation, check that all Handles are valid for their arenas, and refer only to older handles than themselves. This allows subsequent stages to simply use indexing without panics, assuming validation has passed. --- src/arena.rs | 86 +++++- src/back/hlsl/conv.rs | 15 +- src/back/hlsl/writer.rs | 5 +- src/proc/layouter.rs | 9 +- src/proc/mod.rs | 19 +- src/proc/typifier.rs | 31 +- src/valid/analyzer.rs | 9 +- src/valid/compose.rs | 7 +- src/valid/expression.rs | 112 ++++---- src/valid/function.rs | 28 +- src/valid/handles.rs | 616 ++++++++++++++++++++++++++++++++++++++++ src/valid/interface.rs | 9 +- src/valid/mod.rs | 14 +- src/valid/type.rs | 6 +- 14 files changed, 796 insertions(+), 170 deletions(-) create mode 100644 src/valid/handles.rs diff --git a/src/arena.rs b/src/arena.rs index 99d977b2f..1e7b65937 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -15,6 +15,15 @@ pub struct BadHandle { pub index: usize, } +impl BadHandle { + fn new(handle: Handle) -> Self { + Self { + kind: std::any::type_name::(), + index: handle.index(), + } + } +} + /// A strongly typed reference to an arena item. /// /// A `Handle` value can be used as an index into an [`Arena`] or [`UniqueArena`]. @@ -123,6 +132,35 @@ pub struct Range { marker: PhantomData, } +impl Range { + pub(crate) const fn erase_type(self) -> Range<()> { + let Self { inner, marker: _ } = self; + Range { + inner, + marker: PhantomData, + } + } +} + +// NOTE: Keep this diagnostic in sync with that of [`BadHandle`]. +#[derive(Clone, Debug, thiserror::Error)] +#[error("Handle range {range:?} of {kind} is either not present, or inaccessible yet")] +pub struct BadRangeError { + // This error is used for many `Handle` types, but there's no point in making this generic, so + // we just flatten them all to `Handle<()>` here. + kind: &'static str, + range: Range<()>, +} + +impl BadRangeError { + pub fn new(range: Range) -> Self { + Self { + kind: std::any::type_name::(), + range: range.erase_type(), + } + } +} + impl Clone for Range { fn clone(&self) -> Self { Range { @@ -282,10 +320,9 @@ impl Arena { } pub fn try_get(&self, handle: Handle) -> Result<&T, BadHandle> { - self.data.get(handle.index()).ok_or_else(|| BadHandle { - kind: std::any::type_name::(), - index: handle.index(), - }) + self.data + .get(handle.index()) + .ok_or_else(|| BadHandle::new(handle)) } /// Get a mutable reference to an element in the arena. @@ -320,6 +357,31 @@ impl Arena { Span::default() } } + + /// Assert that `handle` is valid for this arena. + pub fn check_contains_handle(&self, handle: Handle) -> Result<(), BadHandle> { + if handle.index() < self.data.len() { + Ok(()) + } else { + Err(BadHandle::new(handle)) + } + } + + /// Assert that `range` is valid for this arena. + pub fn check_contains_range(&self, range: &Range) -> Result<(), BadRangeError> { + // Since `range.inner` is a `Range`, we only need to + // check that the start precedes the end, and that the end is + // in range. + if range.inner.start > range.inner.end + || self + .check_contains_handle(Handle::new(range.inner.end.try_into().unwrap())) + .is_err() + { + Err(BadRangeError::new(range.clone())) + } else { + Ok(()) + } + } } #[cfg(feature = "deserialize")] @@ -540,10 +602,18 @@ impl UniqueArena { /// Return this arena's value at `handle`, if that is a valid handle. pub fn get_handle(&self, handle: Handle) -> Result<&T, BadHandle> { - self.set.get_index(handle.index()).ok_or_else(|| BadHandle { - kind: std::any::type_name::(), - index: handle.index(), - }) + self.set + .get_index(handle.index()) + .ok_or_else(|| BadHandle::new(handle)) + } + + /// Assert that `handle` is valid for this arena. + pub fn check_contains_handle(&self, handle: Handle) -> Result<(), BadHandle> { + if handle.index() < self.set.len() { + Ok(()) + } else { + Err(BadHandle::new(handle)) + } } } diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 3feb80bb6..525930e1c 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -40,12 +40,12 @@ impl crate::TypeInner { } } - pub(super) fn try_size_hlsl( + pub(super) fn size_hlsl( &self, types: &crate::UniqueArena, constants: &crate::Arena, - ) -> Result { - Ok(match *self { + ) -> u32 { + match *self { Self::Matrix { columns, rows, @@ -58,17 +58,16 @@ impl crate::TypeInner { Self::Array { base, size, stride } => { let count = match size { crate::ArraySize::Constant(handle) => { - let constant = constants.try_get(handle)?; - constant.to_array_length().unwrap_or(1) + constants[handle].to_array_length().unwrap_or(1) } // A dynamically-sized array has to have at least one element crate::ArraySize::Dynamic => 1, }; - let last_el_size = types[base].inner.try_size_hlsl(types, constants)?; + let last_el_size = types[base].inner.size_hlsl(types, constants); ((count - 1) * stride) + last_el_size } - _ => self.try_size(constants)?, - }) + _ => self.size(constants), + } } /// Used to generate the name of the wrapped type constructor diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index e1325e5ab..bf841a121 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -829,10 +829,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } let ty_inner = &module.types[member.ty].inner; - last_offset = member.offset - + ty_inner - .try_size_hlsl(&module.types, &module.constants) - .unwrap(); + last_offset = member.offset + ty_inner.size_hlsl(&module.types, &module.constants); // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 0c3a00db1..db07f261a 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -1,4 +1,4 @@ -use crate::arena::{Arena, BadHandle, Handle, UniqueArena}; +use crate::arena::{Arena, Handle, UniqueArena}; use std::{fmt::Display, num::NonZeroU32, ops}; /// A newtype struct where its only valid values are powers of 2 @@ -130,8 +130,6 @@ pub enum LayoutErrorInner { InvalidStructMemberType(u32, Handle), #[error("Type width must be a power of two")] NonPowerOfTwoWidth, - #[error("Array size is a bad handle")] - BadHandle(#[from] BadHandle), } #[derive(Clone, Copy, Debug, PartialEq, thiserror::Error)] @@ -175,10 +173,7 @@ impl Layouter { use crate::TypeInner as Ti; for (ty_handle, ty) in types.iter().skip(self.layouts.len()) { - let size = ty - .inner - .try_size(constants) - .map_err(|error| LayoutErrorInner::BadHandle(error).with(ty_handle))?; + let size = ty.inner.size(constants); let layout = match ty.inner { Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => { let alignment = Alignment::new(width as u32) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index a5731de89..c718c33b2 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -97,11 +97,9 @@ impl super::TypeInner { } } - pub fn try_size( - &self, - constants: &super::Arena, - ) -> Result { - Ok(match *self { + /// Get the size of this type. + pub fn size(&self, constants: &super::Arena) -> u32 { + match *self { Self::Scalar { kind: _, width } | Self::Atomic { kind: _, width } => width as u32, Self::Vector { size, @@ -122,8 +120,7 @@ impl super::TypeInner { } => { let count = match size { super::ArraySize::Constant(handle) => { - let constant = constants.try_get(handle)?; - constant.to_array_length().unwrap_or(1) + constants[handle].to_array_length().unwrap_or(1) } // A dynamically-sized array has to have at least one element super::ArraySize::Dynamic => 1, @@ -132,13 +129,7 @@ impl super::TypeInner { } Self::Struct { span, .. } => span, Self::Image { .. } | Self::Sampler { .. } | Self::BindingArray { .. } => 0, - }) - } - - /// Get the size of this type. Panics if the `constants` doesn't contain - /// a referenced handle. This may not happen in a properly validated IR module. - pub fn size(&self, constants: &super::Arena) -> u32 { - self.try_size(constants).unwrap() + } } /// Return the canonical form of `self`, or `None` if it's already in diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 9df538cc2..47ad05e06 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -1,4 +1,4 @@ -use crate::arena::{Arena, BadHandle, Handle, UniqueArena}; +use crate::arena::{Arena, Handle, UniqueArena}; use thiserror::Error; @@ -162,8 +162,6 @@ impl crate::ConstantInner { #[derive(Clone, Debug, Error, PartialEq)] pub enum ResolveError { - #[error(transparent)] - BadHandle(#[from] BadHandle), #[error("Index {index} is out of bounds for expression {expr:?}")] OutOfBoundsIndex { expr: Handle, @@ -195,8 +193,6 @@ pub enum ResolveError { IncompatibleOperands(String), #[error("Function argument {0} doesn't exist")] FunctionArgumentNotFound(u32), - #[error("Expression {0:?} depends on expressions that follow")] - ExpressionForwardDependency(Handle), } pub struct ResolveContext<'a> { @@ -403,20 +399,15 @@ impl<'a> ResolveContext<'a> { } } } - crate::Expression::Constant(h) => { - let constant = self.constants.try_get(h)?; - match constant.inner { - crate::ConstantInner::Scalar { width, ref value } => { - TypeResolution::Value(Ti::Scalar { - kind: value.scalar_kind(), - width, - }) - } - crate::ConstantInner::Composite { ty, components: _ } => { - TypeResolution::Handle(ty) - } + crate::Expression::Constant(h) => match self.constants[h].inner { + crate::ConstantInner::Scalar { width, ref value } => { + TypeResolution::Value(Ti::Scalar { + kind: value.scalar_kind(), + width, + }) } - } + crate::ConstantInner::Composite { ty, components: _ } => TypeResolution::Handle(ty), + }, crate::Expression::Splat { size, value } => match *past(value)?.inner_with(types) { Ti::Scalar { kind, width } => { TypeResolution::Value(Ti::Vector { size, kind, width }) @@ -450,7 +441,7 @@ impl<'a> ResolveContext<'a> { TypeResolution::Handle(arg.ty) } crate::Expression::GlobalVariable(h) => { - let var = self.global_vars.try_get(h)?; + let var = &self.global_vars[h]; if var.space == crate::AddressSpace::Handle { TypeResolution::Handle(var.ty) } else { @@ -461,7 +452,7 @@ impl<'a> ResolveContext<'a> { } } crate::Expression::LocalVariable(h) => { - let var = self.local_vars.try_get(h)?; + let var = &self.local_vars[h]; TypeResolution::Value(Ti::Pointer { base: var.ty, space: crate::AddressSpace::Function, diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index ec8e9d96e..eb6c1fc4a 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -10,7 +10,7 @@ use super::{CallError, ExpressionError, FunctionError, ModuleInfo, ShaderStages, use crate::span::{AddSpan as _, WithSpan}; use crate::{ arena::{Arena, Handle}, - proc::{ResolveContext, ResolveError, TypeResolution}, + proc::{ResolveContext, TypeResolution}, }; use std::ops; @@ -706,12 +706,7 @@ impl FunctionInfo { }, }; - let ty = resolve_context.resolve(expression, |h| { - self.expressions - .get(h.index()) - .map(|ei| &ei.ty) - .ok_or(ResolveError::ExpressionForwardDependency(h)) - })?; + let ty = resolve_context.resolve(expression, |h| Ok(&self[h].ty))?; self.expressions[handle.index()] = ExpressionInfo { uniformity, ref_count: 0, diff --git a/src/valid/compose.rs b/src/valid/compose.rs index 6e5c49922..e77d53825 100644 --- a/src/valid/compose.rs +++ b/src/valid/compose.rs @@ -4,13 +4,11 @@ use crate::{ proc::TypeResolution, }; -use crate::arena::{BadHandle, Handle}; +use crate::arena::Handle; #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum ComposeError { - #[error(transparent)] - BadHandle(#[from] BadHandle), #[error("Composing of type {0:?} can't be done")] Type(Handle), #[error("Composing expects {expected} components but {given} were given")] @@ -28,8 +26,7 @@ pub fn validate_compose( ) -> Result<(), ComposeError> { use crate::TypeInner as Ti; - let self_ty = type_arena.get_handle(self_ty_handle)?; - match self_ty.inner { + match type_arena[self_ty_handle].inner { // vectors are composed from scalars or other vectors Ti::Vector { size, kind, width } => { let mut total = 0; diff --git a/src/valid/expression.rs b/src/valid/expression.rs index a3afc0535..14f52fb93 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,3 +1,6 @@ +#[cfg(feature = "validate")] +use std::ops::Index; + #[cfg(feature = "validate")] use super::{ compose::validate_compose, validate_atomic_compare_exchange_struct, FunctionInfo, ShaderStages, @@ -7,7 +10,7 @@ use super::{ use crate::arena::UniqueArena; use crate::{ - arena::{BadHandle, Handle}, + arena::Handle, proc::{IndexableLengthError, ResolveError}, }; @@ -18,10 +21,6 @@ pub enum ExpressionError { DoesntExist, #[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")] NotInScope, - #[error("Depends on {0:?}, which has not been processed yet")] - ForwardDependency(Handle), - #[error(transparent)] - BadDependency(#[from] BadHandle), #[error("Base type {0:?} is not compatible with this expression")] InvalidBaseType(Handle), #[error("Accessing with index {0:?} can't be done")] @@ -132,15 +131,19 @@ struct ExpressionTypeResolver<'a> { } #[cfg(feature = "validate")] -impl<'a> ExpressionTypeResolver<'a> { - fn resolve( - &self, - handle: Handle, - ) -> Result<&'a crate::TypeInner, ExpressionError> { +impl<'a> Index> for ExpressionTypeResolver<'a> { + type Output = crate::TypeInner; + + #[allow(clippy::panic)] + fn index(&self, handle: Handle) -> &Self::Output { if handle < self.root { - Ok(self.info[handle].ty.inner_with(self.types)) + self.info[handle].ty.inner_with(self.types) } else { - Err(ExpressionError::ForwardDependency(handle)) + // `Validator::validate_module_handles` should have caught this. + panic!( + "Depends on {:?}, which has not been processed yet", + self.root + ) } } } @@ -166,7 +169,7 @@ impl super::Validator { let stages = match *expression { E::Access { base, index } => { - let base_type = resolver.resolve(base)?; + let base_type = &resolver[base]; // See the documentation for `Expression::Access`. let dynamic_indexing_restricted = match *base_type { Ti::Vector { .. } => false, @@ -179,7 +182,7 @@ impl super::Validator { return Err(ExpressionError::InvalidBaseType(base)); } }; - match *resolver.resolve(index)? { + match resolver[index] { //TODO: only allow one of these Ti::Scalar { kind: Sk::Sint | Sk::Uint, @@ -257,7 +260,7 @@ impl super::Validator { Ok(limit) } - let limit = resolve_index_limit(module, base, resolver.resolve(base)?, true)?; + let limit = resolve_index_limit(module, base, &resolver[base], true)?; if index >= limit { return Err(ExpressionError::IndexOutOfBounds( base, @@ -266,11 +269,8 @@ impl super::Validator { } ShaderStages::all() } - E::Constant(handle) => { - let _ = module.constants.try_get(handle)?; - ShaderStages::all() - } - E::Splat { size: _, value } => match *resolver.resolve(value)? { + E::Constant(_handle) => ShaderStages::all(), + E::Splat { size: _, value } => match resolver[value] { Ti::Scalar { .. } => ShaderStages::all(), ref other => { log::error!("Splat scalar type {:?}", other); @@ -282,7 +282,7 @@ impl super::Validator { vector, pattern, } => { - let vec_size = match *resolver.resolve(vector)? { + let vec_size = match resolver[vector] { Ti::Vector { size: vec_size, .. } => vec_size, ref other => { log::error!("Swizzle vector type {:?}", other); @@ -297,11 +297,6 @@ impl super::Validator { ShaderStages::all() } E::Compose { ref components, ty } => { - for &handle in components { - if handle >= root { - return Err(ExpressionError::ForwardDependency(handle)); - } - } validate_compose( ty, &module.constants, @@ -316,16 +311,10 @@ impl super::Validator { } ShaderStages::all() } - E::GlobalVariable(handle) => { - let _ = module.global_variables.try_get(handle)?; - ShaderStages::all() - } - E::LocalVariable(handle) => { - let _ = function.local_variables.try_get(handle)?; - ShaderStages::all() - } + E::GlobalVariable(_handle) => ShaderStages::all(), + E::LocalVariable(_handle) => ShaderStages::all(), E::Load { pointer } => { - match *resolver.resolve(pointer)? { + match resolver[pointer] { Ti::Pointer { base, .. } if self.types[base.index()] .flags @@ -368,7 +357,7 @@ impl super::Validator { return Err(ExpressionError::InvalidImageArrayIndex); } if let Some(expr) = array_index { - match *resolver.resolve(expr)? { + match resolver[expr] { Ti::Scalar { kind: Sk::Sint, width: _, @@ -408,7 +397,7 @@ impl super::Validator { crate::ImageDimension::D2 => 2, crate::ImageDimension::D3 | crate::ImageDimension::Cube => 3, }; - match *resolver.resolve(coordinate)? { + match resolver[coordinate] { Ti::Scalar { kind: Sk::Float, .. } if num_components == 1 => {} @@ -446,7 +435,7 @@ impl super::Validator { // check depth reference type if let Some(expr) = depth_ref { - match *resolver.resolve(expr)? { + match resolver[expr] { Ti::Scalar { kind: Sk::Float, .. } => {} @@ -483,7 +472,7 @@ impl super::Validator { crate::SampleLevel::Auto => ShaderStages::FRAGMENT, crate::SampleLevel::Zero => ShaderStages::all(), crate::SampleLevel::Exact(expr) => { - match *resolver.resolve(expr)? { + match resolver[expr] { Ti::Scalar { kind: Sk::Float, .. } => {} @@ -492,7 +481,7 @@ impl super::Validator { ShaderStages::all() } crate::SampleLevel::Bias(expr) => { - match *resolver.resolve(expr)? { + match resolver[expr] { Ti::Scalar { kind: Sk::Float, .. } => {} @@ -501,7 +490,7 @@ impl super::Validator { ShaderStages::all() } crate::SampleLevel::Gradient { x, y } => { - match *resolver.resolve(x)? { + match resolver[x] { Ti::Scalar { kind: Sk::Float, .. } if num_components == 1 => {} @@ -514,7 +503,7 @@ impl super::Validator { return Err(ExpressionError::InvalidSampleLevelGradientType(dim, x)) } } - match *resolver.resolve(y)? { + match resolver[y] { Ti::Scalar { kind: Sk::Float, .. } if num_components == 1 => {} @@ -545,7 +534,7 @@ impl super::Validator { arrayed, dim, } => { - match resolver.resolve(coordinate)?.image_storage_coordinates() { + match resolver[coordinate].image_storage_coordinates() { Some(coord_dim) if coord_dim == dim => {} _ => { return Err(ExpressionError::InvalidImageCoordinateType( @@ -557,7 +546,7 @@ impl super::Validator { return Err(ExpressionError::InvalidImageArrayIndex); } if let Some(expr) = array_index { - match *resolver.resolve(expr)? { + match resolver[expr] { Ti::Scalar { kind: Sk::Sint, width: _, @@ -569,7 +558,7 @@ impl super::Validator { match (sample, class.is_multisampled()) { (None, false) => {} (Some(sample), true) => { - if resolver.resolve(sample)?.scalar_kind() != Some(Sk::Sint) { + if resolver[sample].scalar_kind() != Some(Sk::Sint) { return Err(ExpressionError::InvalidImageOtherIndexType( sample, )); @@ -583,7 +572,7 @@ impl super::Validator { match (level, class.is_mipmapped()) { (None, false) => {} (Some(level), true) => { - if resolver.resolve(level)?.scalar_kind() != Some(Sk::Sint) { + if resolver[level].scalar_kind() != Some(Sk::Sint) { return Err(ExpressionError::InvalidImageOtherIndexType(level)); } } @@ -617,7 +606,7 @@ impl super::Validator { } E::Unary { op, expr } => { use crate::UnaryOperator as Uo; - let inner = resolver.resolve(expr)?; + let inner = &resolver[expr]; match (op, inner.scalar_kind()) { (_, Some(Sk::Sint | Sk::Bool)) //TODO: restrict Negate for bools? @@ -632,8 +621,8 @@ impl super::Validator { } E::Binary { op, left, right } => { use crate::BinaryOperator as Bo; - let left_inner = resolver.resolve(left)?; - let right_inner = resolver.resolve(right)?; + let left_inner = &resolver[left]; + let right_inner = &resolver[right]; let good = match op { Bo::Add | Bo::Subtract => match *left_inner { Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind { @@ -814,9 +803,9 @@ impl super::Validator { accept, reject, } => { - let accept_inner = resolver.resolve(accept)?; - let reject_inner = resolver.resolve(reject)?; - let condition_good = match *resolver.resolve(condition)? { + let accept_inner = &resolver[accept]; + let reject_inner = &resolver[reject]; + let condition_good = match resolver[condition] { Ti::Scalar { kind: Sk::Bool, width: _, @@ -846,7 +835,7 @@ impl super::Validator { ShaderStages::all() } E::Derivative { axis: _, expr } => { - match *resolver.resolve(expr)? { + match resolver[expr] { Ti::Scalar { kind: Sk::Float, .. } @@ -859,7 +848,7 @@ impl super::Validator { } E::Relational { fun, argument } => { use crate::RelationalFunction as Rf; - let argument_inner = resolver.resolve(argument)?; + let argument_inner = &resolver[argument]; match fun { Rf::All | Rf::Any => match *argument_inner { Ti::Vector { kind: Sk::Bool, .. } => {} @@ -892,10 +881,11 @@ impl super::Validator { } => { use crate::MathFunction as Mf; - let arg_ty = resolver.resolve(arg)?; - let arg1_ty = arg1.map(|expr| resolver.resolve(expr)).transpose()?; - let arg2_ty = arg2.map(|expr| resolver.resolve(expr)).transpose()?; - let arg3_ty = arg3.map(|expr| resolver.resolve(expr)).transpose()?; + let resolve = |arg| &resolver[arg]; + let arg_ty = resolve(arg); + let arg1_ty = arg1.map(resolve); + let arg2_ty = arg2.map(resolve); + let arg3_ty = arg3.map(resolve); match fun { Mf::Abs => { if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { @@ -1379,7 +1369,7 @@ impl super::Validator { kind, convert, } => { - let base_width = match *resolver.resolve(expr)? { + let base_width = match resolver[expr] { crate::TypeInner::Scalar { width, .. } | crate::TypeInner::Vector { width, .. } | crate::TypeInner::Matrix { width, .. } => width, @@ -1416,9 +1406,9 @@ impl super::Validator { } ShaderStages::all() } - E::ArrayLength(expr) => match *resolver.resolve(expr)? { + E::ArrayLength(expr) => match resolver[expr] { Ti::Pointer { base, .. } => { - let base_ty = resolver.types.get_handle(base)?; + let base_ty = &resolver.types[base]; if let Ti::Array { size: crate::ArraySize::Dynamic, .. diff --git a/src/valid/function.rs b/src/valid/function.rs index 0f0a7b89f..3c555491c 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -1,6 +1,6 @@ +use crate::arena::Handle; #[cfg(feature = "validate")] use crate::arena::{Arena, UniqueArena}; -use crate::arena::{BadHandle, Handle}; #[cfg(feature = "validate")] use super::validate_atomic_compare_exchange_struct; @@ -19,8 +19,6 @@ use bit_set::BitSet; #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum CallError { - #[error(transparent)] - BadHandle(#[from] BadHandle), #[error("The callee is declared after the caller")] ForwardDeclaredFunction, #[error("Argument {index} expression is invalid")] @@ -69,8 +67,6 @@ pub enum LocalVariableError { #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum FunctionError { - #[error(transparent)] - BadHandle(#[from] BadHandle), #[error("Expression {handle:?} is invalid")] Expression { handle: Handle, @@ -203,11 +199,8 @@ impl<'a> BlockContext<'a> { BlockContext { abilities, ..*self } } - fn get_expression( - &self, - handle: Handle, - ) -> Result<&'a crate::Expression, FunctionError> { - Ok(self.expressions.try_get(handle)?) + fn get_expression(&self, handle: Handle) -> &'a crate::Expression { + &self.expressions[handle] } fn resolve_type_impl( @@ -257,11 +250,7 @@ impl super::Validator { result: Option>, context: &BlockContext, ) -> Result> { - let fun = context - .functions - .try_get(function) - .map_err(CallError::BadHandle) - .map_err(WithSpan::new)?; + let fun = &context.functions[function]; if fun.arguments.len() != arguments.len() { return Err(CallError::ArgumentCount { required: fun.arguments.len(), @@ -689,14 +678,14 @@ impl super::Validator { } => { //Note: this code uses a lot of `FunctionError::InvalidImageStore`, // and could probably be refactored. - let var = match *context.get_expression(image).map_err(|e| e.with_span())? { + let var = match *context.get_expression(image) { crate::Expression::GlobalVariable(var_handle) => { &context.global_vars[var_handle] } // We're looking at a binding index situation, so punch through the index and look at the global behind it. crate::Expression::Access { base, .. } | crate::Expression::AccessIndex { base, .. } => { - match *context.get_expression(base).map_err(|e| e.with_span())? { + match *context.get_expression(base) { crate::Expression::GlobalVariable(var_handle) => { &context.global_vars[var_handle] } @@ -899,10 +888,7 @@ impl super::Validator { #[cfg(feature = "validate")] for (index, argument) in fun.arguments.iter().enumerate() { - let ty = module.types.get_handle(argument.ty).map_err(|err| { - FunctionError::from(err).with_span_handle(argument.ty, &module.types) - })?; - match ty.inner.pointer_space() { + match module.types[argument.ty].inner.pointer_space() { Some( crate::AddressSpace::Private | crate::AddressSpace::Function diff --git a/src/valid/handles.rs b/src/valid/handles.rs new file mode 100644 index 000000000..5b3375a87 --- /dev/null +++ b/src/valid/handles.rs @@ -0,0 +1,616 @@ +//! Implementation of [`super::Validator::validate_module_handles`]. + +use crate::{ + arena::{BadHandle, BadRangeError}, + Handle, +}; + +#[cfg(feature = "validate")] +use crate::{Arena, UniqueArena}; + +#[cfg(feature = "validate")] +use super::{TypeError, ValidationError}; + +#[cfg(feature = "validate")] +use std::{convert::TryInto, hash::Hash, num::NonZeroU32}; + +#[cfg(feature = "validate")] +impl super::Validator { + /// Validates that all handles within `module` are: + /// + /// * Valid, in the sense that they contain indices within each arena structure inside the + /// [`crate::Module`] type. + /// * No arena contents contain any items that have forward dependencies; that is, the value + /// associated with a handle only may contain references to handles in the same arena that + /// were constructed before it. + /// + /// By validating the above conditions, we free up subsequent logic to assume that handle + /// accesses are infallible. + /// + /// # Errors + /// + /// Errors returned by this method are intentionally sparse, for simplicity of implementation. + /// It is expected that only buggy frontends or fuzzers should ever emit IR that fails this + /// validation pass. + pub(super) fn validate_module_handles(module: &crate::Module) -> Result<(), ValidationError> { + let &crate::Module { + ref constants, + ref entry_points, + ref functions, + ref global_variables, + ref types, + } = module; + + // NOTE: Types being first is important. All other forms of validation depend on this. + for (this_handle, ty) in types.iter() { + let &crate::Type { + ref name, + ref inner, + } = ty; + + let validate_array_size = |size| { + match size { + crate::ArraySize::Constant(constant) => { + let &crate::Constant { + name: _, + specialization: _, + ref inner, + } = constants.try_get(constant)?; + if !matches!(inner, &crate::ConstantInner::Scalar { .. }) { + return Err(ValidationError::Type { + handle: this_handle, + name: name.clone().unwrap_or_default(), + source: TypeError::InvalidArraySizeConstant(constant), + }); + } + } + crate::ArraySize::Dynamic => (), + }; + Ok(this_handle) + }; + + match *inner { + crate::TypeInner::Scalar { .. } + | crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } + | crate::TypeInner::ValuePointer { .. } + | crate::TypeInner::Atomic { .. } + | crate::TypeInner::Image { .. } + | crate::TypeInner::Sampler { .. } => (), + crate::TypeInner::Pointer { base, space: _ } => { + this_handle.check_dep(base)?; + } + crate::TypeInner::Array { + base, + size, + stride: _, + } + | crate::TypeInner::BindingArray { base, size } => { + this_handle.check_dep(base)?; + validate_array_size(size)?; + } + crate::TypeInner::Struct { + ref members, + span: _, + } => { + this_handle.check_dep_iter(members.iter().map(|m| m.ty))?; + } + } + } + + let validate_type = |handle| Self::validate_type_handle(handle, types); + + for (this_handle, constant) in constants.iter() { + let &crate::Constant { + name: _, + specialization: _, + ref inner, + } = constant; + match *inner { + crate::ConstantInner::Scalar { .. } => (), + crate::ConstantInner::Composite { ty, ref components } => { + validate_type(ty)?; + this_handle.check_dep_iter(components.iter().copied())?; + } + } + } + + let validate_constant = |handle| Self::validate_constant_handle(handle, constants); + + for (_handle, global_variable) in global_variables.iter() { + let &crate::GlobalVariable { + name: _, + space: _, + binding: _, + ty, + init, + } = global_variable; + validate_type(ty)?; + if let Some(init_expr) = init { + validate_constant(init_expr)?; + } + } + + let validate_function = |function: &_| -> Result<_, InvalidHandleError> { + let &crate::Function { + name: _, + ref arguments, + ref result, + ref local_variables, + ref expressions, + ref named_expressions, + ref body, + } = function; + + for arg in arguments.iter() { + let &crate::FunctionArgument { + name: _, + ty, + binding: _, + } = arg; + validate_type(ty)?; + } + + if let &Some(crate::FunctionResult { ty, binding: _ }) = result { + validate_type(ty)?; + } + + for (_handle, local_variable) in local_variables.iter() { + let &crate::LocalVariable { name: _, ty, init } = local_variable; + validate_type(ty)?; + if let Some(init_constant) = init { + validate_constant(init_constant)?; + } + } + + for handle in named_expressions.keys().copied() { + Self::validate_expression_handle(handle, expressions)?; + } + + for handle_and_expr in expressions.iter() { + Self::validate_expression_handles( + handle_and_expr, + constants, + types, + local_variables, + global_variables, + functions, + )?; + } + + Self::validate_block_handles(body, expressions, functions)?; + + Ok(()) + }; + + for entry_point in entry_points.iter() { + validate_function(&entry_point.function)?; + } + + for (_function_handle, function) in functions.iter() { + validate_function(function)?; + } + + Ok(()) + } + + fn validate_type_handle( + handle: Handle, + types: &UniqueArena, + ) -> Result<(), InvalidHandleError> { + handle.check_valid_for_uniq(types).map(|_| ()) + } + + fn validate_constant_handle( + handle: Handle, + constants: &Arena, + ) -> Result<(), InvalidHandleError> { + handle.check_valid_for(constants).map(|_| ()) + } + + fn validate_expression_handle( + handle: Handle, + expressions: &Arena, + ) -> Result<(), InvalidHandleError> { + handle.check_valid_for(expressions).map(|_| ()) + } + + fn validate_function_handle( + handle: Handle, + functions: &Arena, + ) -> Result<(), InvalidHandleError> { + handle.check_valid_for(functions).map(|_| ()) + } + + fn validate_expression_handles( + (handle, expression): (Handle, &crate::Expression), + constants: &Arena, + types: &UniqueArena, + local_variables: &Arena, + global_variables: &Arena, + functions: &Arena, + ) -> Result<(), InvalidHandleError> { + let validate_constant = |handle| Self::validate_constant_handle(handle, constants); + let validate_type = |handle| Self::validate_type_handle(handle, types); + + match *expression { + crate::Expression::Access { base, index } => { + handle.check_dep(base)?.check_dep(index)?; + } + crate::Expression::AccessIndex { base, .. } => { + handle.check_dep(base)?; + } + crate::Expression::Constant(constant) => { + validate_constant(constant)?; + } + crate::Expression::Splat { value, .. } => { + handle.check_dep(value)?; + } + crate::Expression::Swizzle { vector, .. } => { + handle.check_dep(vector)?; + } + crate::Expression::Compose { ty, ref components } => { + validate_type(ty)?; + handle.check_dep_iter(components.iter().copied())?; + } + crate::Expression::FunctionArgument(_arg_idx) => (), + crate::Expression::GlobalVariable(global_variable) => { + global_variable.check_valid_for(global_variables)?; + } + crate::Expression::LocalVariable(local_variable) => { + local_variable.check_valid_for(local_variables)?; + } + crate::Expression::Load { pointer } => { + handle.check_dep(pointer)?; + } + crate::Expression::ImageSample { + image, + sampler, + gather: _, + coordinate, + array_index, + offset, + level, + depth_ref, + } => { + if let Some(offset) = offset { + validate_constant(offset)?; + } + + handle + .check_dep(image)? + .check_dep(sampler)? + .check_dep(coordinate)? + .check_dep_opt(array_index)?; + + match level { + crate::SampleLevel::Auto | crate::SampleLevel::Zero => (), + crate::SampleLevel::Exact(expr) => { + handle.check_dep(expr)?; + } + crate::SampleLevel::Bias(expr) => { + handle.check_dep(expr)?; + } + crate::SampleLevel::Gradient { x, y } => { + handle.check_dep(x)?.check_dep(y)?; + } + }; + + handle.check_dep_opt(depth_ref)?; + } + crate::Expression::ImageLoad { + image, + coordinate, + array_index, + sample, + level, + } => { + handle + .check_dep(image)? + .check_dep(coordinate)? + .check_dep_opt(array_index)? + .check_dep_opt(sample)? + .check_dep_opt(level)?; + } + crate::Expression::ImageQuery { image, query } => { + handle.check_dep(image)?; + match query { + crate::ImageQuery::Size { level } => { + handle.check_dep_opt(level)?; + } + crate::ImageQuery::NumLevels + | crate::ImageQuery::NumLayers + | crate::ImageQuery::NumSamples => (), + }; + } + crate::Expression::Unary { + op: _, + expr: operand, + } => { + handle.check_dep(operand)?; + } + crate::Expression::Binary { op: _, left, right } => { + handle.check_dep(left)?.check_dep(right)?; + } + crate::Expression::Select { + condition, + accept, + reject, + } => { + handle + .check_dep(condition)? + .check_dep(accept)? + .check_dep(reject)?; + } + crate::Expression::Derivative { + axis: _, + expr: argument, + } => { + handle.check_dep(argument)?; + } + crate::Expression::Relational { fun: _, argument } => { + handle.check_dep(argument)?; + } + crate::Expression::Math { + fun: _, + arg, + arg1, + arg2, + arg3, + } => { + handle + .check_dep(arg)? + .check_dep_opt(arg1)? + .check_dep_opt(arg2)? + .check_dep_opt(arg3)?; + } + crate::Expression::As { + expr: input, + kind: _, + convert: _, + } => { + handle.check_dep(input)?; + } + crate::Expression::CallResult(function) => { + Self::validate_function_handle(function, functions)?; + } + crate::Expression::AtomicResult { .. } => (), + crate::Expression::ArrayLength(array) => { + handle.check_dep(array)?; + } + } + Ok(()) + } + + fn validate_block_handles( + block: &crate::Block, + expressions: &Arena, + functions: &Arena, + ) -> Result<(), InvalidHandleError> { + let validate_block = |block| Self::validate_block_handles(block, expressions, functions); + let validate_expr = |handle| Self::validate_expression_handle(handle, expressions); + let validate_expr_opt = |handle_opt| { + if let Some(handle) = handle_opt { + validate_expr(handle)?; + } + Ok(()) + }; + + block.iter().try_for_each(|stmt| match *stmt { + crate::Statement::Emit(ref expr_range) => { + expr_range.check_valid_for(expressions)?; + Ok(()) + } + crate::Statement::Block(ref block) => { + validate_block(block)?; + Ok(()) + } + crate::Statement::If { + condition, + ref accept, + ref reject, + } => { + validate_expr(condition)?; + validate_block(accept)?; + validate_block(reject)?; + Ok(()) + } + crate::Statement::Switch { + selector, + ref cases, + } => { + validate_expr(selector)?; + for &crate::SwitchCase { + value: _, + ref body, + fall_through: _, + } in cases + { + validate_block(body)?; + } + Ok(()) + } + crate::Statement::Loop { + ref body, + ref continuing, + break_if, + } => { + validate_block(body)?; + validate_block(continuing)?; + validate_expr_opt(break_if)?; + Ok(()) + } + crate::Statement::Return { value } => validate_expr_opt(value), + crate::Statement::Store { pointer, value } => { + validate_expr(pointer)?; + validate_expr(value)?; + Ok(()) + } + crate::Statement::ImageStore { + image, + coordinate, + array_index, + value, + } => { + validate_expr(image)?; + validate_expr(coordinate)?; + validate_expr_opt(array_index)?; + validate_expr(value)?; + Ok(()) + } + crate::Statement::Atomic { + pointer, + fun, + value, + result, + } => { + validate_expr(pointer)?; + match fun { + crate::AtomicFunction::Add + | crate::AtomicFunction::Subtract + | crate::AtomicFunction::And + | crate::AtomicFunction::ExclusiveOr + | crate::AtomicFunction::InclusiveOr + | crate::AtomicFunction::Min + | crate::AtomicFunction::Max => (), + crate::AtomicFunction::Exchange { compare } => validate_expr_opt(compare)?, + }; + validate_expr(value)?; + validate_expr(result)?; + Ok(()) + } + crate::Statement::Call { + function, + ref arguments, + result, + } => { + Self::validate_function_handle(function, functions)?; + for arg in arguments.iter().copied() { + validate_expr(arg)?; + } + validate_expr_opt(result)?; + Ok(()) + } + crate::Statement::Break + | crate::Statement::Continue + | crate::Statement::Kill + | crate::Statement::Barrier(_) => Ok(()), + }) + } +} + +#[cfg(feature = "validate")] +impl From for ValidationError { + fn from(source: BadHandle) -> Self { + Self::InvalidHandle(source.into()) + } +} + +#[cfg(feature = "validate")] +impl From for ValidationError { + fn from(source: FwdDepError) -> Self { + Self::InvalidHandle(source.into()) + } +} + +#[cfg(feature = "validate")] +impl From for ValidationError { + fn from(source: BadRangeError) -> Self { + Self::InvalidHandle(source.into()) + } +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum InvalidHandleError { + #[error(transparent)] + BadHandle(#[from] BadHandle), + #[error(transparent)] + ForwardDependency(#[from] FwdDepError), + #[error(transparent)] + BadRange(#[from] BadRangeError), +} + +#[derive(Clone, Debug, thiserror::Error)] +#[error( + "{subject:?} of kind depends on {depends_on:?} of kind {depends_on_kind}, which has not been \ + processed yet" +)] +pub struct FwdDepError { + // This error is used for many `Handle` types, but there's no point in making this generic, so + // we just flatten them all to `Handle<()>` here. + subject: Handle<()>, + subject_kind: &'static str, + depends_on: Handle<()>, + depends_on_kind: &'static str, +} + +#[cfg(feature = "validate")] +impl Handle { + /// Check that `self` is valid within `arena` using [`Arena::check_contains_handle`]. + pub(self) fn check_valid_for(self, arena: &Arena) -> Result<(), InvalidHandleError> { + arena.check_contains_handle(self)?; + Ok(()) + } + + /// Check that `self` is valid within `arena` using [`UniqueArena::check_contains_handle`]. + pub(self) fn check_valid_for_uniq( + self, + arena: &UniqueArena, + ) -> Result<(), InvalidHandleError> + where + T: Eq + Hash, + { + arena.check_contains_handle(self)?; + Ok(()) + } + + /// Check that `depends_on` was constructed before `self` by comparing handle indices. + /// + /// If `self` is a valid handle (i.e., it has been validated using [`Self::check_valid_for`]) + /// and this function returns [`Ok`], then it may be assumed that `depends_on` is also valid. + /// In [`naga`](crate)'s current arena-based implementation, this is useful for validating + /// recursive definitions of arena-based values in linear time. + /// + /// # Errors + /// + /// If `depends_on`'s handle is from the same [`Arena`] as `self'`s, but not constructed earlier + /// than `self`'s, this function returns an error. + pub(self) fn check_dep(self, depends_on: Self) -> Result { + if depends_on < self { + Ok(self) + } else { + let erase_handle_type = |handle: Handle<_>| { + Handle::new(NonZeroU32::new(handle.index().try_into().unwrap()).unwrap()) + }; + Err(FwdDepError { + subject: erase_handle_type(self), + subject_kind: std::any::type_name::(), + depends_on: erase_handle_type(depends_on), + depends_on_kind: std::any::type_name::(), + }) + } + } + + /// Like [`Self::check_dep`], except for [`Option`]al handle values. + pub(self) fn check_dep_opt(self, depends_on: Option) -> Result { + self.check_dep_iter(depends_on.into_iter()) + } + + /// Like [`Self::check_dep`], except for [`Iterator`]s over handle values. + pub(self) fn check_dep_iter( + self, + depends_on: impl Iterator, + ) -> Result { + for handle in depends_on { + self.check_dep(handle)?; + } + Ok(self) + } +} + +#[cfg(feature = "validate")] +impl crate::arena::Range { + pub(self) fn check_valid_for(&self, arena: &Arena) -> Result<(), BadRangeError> { + arena.check_contains_range(self) + } +} diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 85610b068..289a068f7 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -2,7 +2,7 @@ use super::{ analyzer::{FunctionInfo, GlobalUse}, Capabilities, Disalignment, FunctionError, ModuleInfo, }; -use crate::arena::{BadHandle, Handle, UniqueArena}; +use crate::arena::{Handle, UniqueArena}; use crate::span::{AddSpan as _, MapErrWithSpan as _, SpanProvider as _, WithSpan}; use bit_set::BitSet; @@ -12,8 +12,6 @@ const MAX_WORKGROUP_SIZE: u32 = 0x4000; #[derive(Clone, Debug, thiserror::Error)] pub enum GlobalVariableError { - #[error(transparent)] - BadHandle(#[from] BadHandle), #[error("Usage isn't compatible with address space {0:?}")] InvalidUsage(crate::AddressSpace), #[error("Type isn't compatible with address space {0:?}")] @@ -380,10 +378,7 @@ impl super::Validator { use super::TypeFlags; log::debug!("var {:?}", var); - let type_info = self.types.get(var.ty.index()).ok_or_else(|| BadHandle { - kind: "type", - index: var.ty.index(), - })?; + let type_info = &self.types[var.ty.index()]; let (required_type_flags, is_resource) = match var.space { crate::AddressSpace::Function => { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 255d6f428..4e62a2ca7 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -6,6 +6,7 @@ mod analyzer; mod compose; mod expression; mod function; +mod handles; mod interface; mod r#type; @@ -13,7 +14,7 @@ mod r#type; use crate::arena::{Arena, UniqueArena}; use crate::{ - arena::{BadHandle, Handle}, + arena::Handle, proc::{LayoutError, Layouter}, FastHashSet, }; @@ -31,6 +32,8 @@ pub use function::{CallError, FunctionError, LocalVariableError}; pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; pub use r#type::{Disalignment, TypeError, TypeFlags}; +use self::handles::InvalidHandleError; + bitflags::bitflags! { /// Validation flags. /// @@ -146,8 +149,6 @@ pub struct Validator { #[derive(Clone, Debug, thiserror::Error)] pub enum ConstantError { - #[error(transparent)] - BadHandle(#[from] BadHandle), #[error("The type doesn't match the constant")] InvalidType, #[error("The component handle {0:?} can not be resolved")] @@ -160,6 +161,8 @@ pub enum ConstantError { #[derive(Clone, Debug, thiserror::Error)] pub enum ValidationError { + #[error(transparent)] + InvalidHandle(#[from] InvalidHandleError), #[error(transparent)] Layouter(#[from] LayoutError), #[error("Type {handle:?} '{name}' is invalid")] @@ -283,7 +286,7 @@ impl Validator { } } crate::ConstantInner::Composite { ty, ref components } => { - match types.get_handle(ty)?.inner { + match types[ty].inner { crate::TypeInner::Array { size: crate::ArraySize::Constant(size_handle), .. @@ -316,6 +319,9 @@ impl Validator { self.reset(); self.reset_types(module.types.len()); + #[cfg(feature = "validate")] + Self::validate_module_handles(module).map_err(|e| e.with_span())?; + self.layouter .update(&module.types, &module.constants) .map_err(|e| { diff --git a/src/valid/type.rs b/src/valid/type.rs index f103017dd..172f11072 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -1,6 +1,6 @@ use super::Capabilities; use crate::{ - arena::{Arena, BadHandle, Handle, UniqueArena}, + arena::{Arena, Handle, UniqueArena}, proc::Alignment, }; @@ -88,8 +88,6 @@ pub enum Disalignment { #[derive(Clone, Debug, thiserror::Error)] pub enum TypeError { - #[error(transparent)] - BadHandle(#[from] BadHandle), #[error("The {0:?} scalar width {1} is not supported")] InvalidWidth(crate::ScalarKind, crate::Bytes), #[error("The {0:?} scalar width {1} is not supported for an atomic")] @@ -418,7 +416,7 @@ impl super::Validator { let sized_flag = match size { crate::ArraySize::Constant(const_handle) => { - let constant = constants.try_get(const_handle)?; + let constant = &constants[const_handle]; let length_is_positive = match *constant { crate::Constant { specialization: Some(_), From 37be4df2b8e7c56b0390445f4457955211040433 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 16 Dec 2022 16:16:07 -0800 Subject: [PATCH 1883/2212] Fix warnings when building tests without validation. --- src/valid/interface.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 289a068f7..f15396441 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -100,12 +100,14 @@ fn storage_usage(access: crate::StorageAccess) -> GlobalUse { struct VaryingContext<'a> { stage: crate::ShaderStage, output: bool, - flags: super::ValidationFlags, types: &'a UniqueArena, type_info: &'a Vec, location_mask: &'a mut BitSet, built_ins: &'a mut crate::FastHashSet, capabilities: Capabilities, + + #[cfg(feature = "validate")] + flags: super::ValidationFlags, } impl VaryingContext<'_> { @@ -337,8 +339,7 @@ impl VaryingContext<'_> { for (index, member) in members.iter().enumerate() { let span_context = self.types.get_span_context(ty); match member.binding { - None => - { + None => { #[cfg(feature = "validate")] if self.flags.contains(super::ValidationFlags::BINDINGS) { return Err(VaryingError::MemberMissingBinding( @@ -346,6 +347,8 @@ impl VaryingContext<'_> { ) .with_span_context(span_context)); } + #[cfg(not(feature = "validate"))] + let _ = index; } // TODO: shouldn't this be validate? Some(ref binding) => self @@ -510,12 +513,14 @@ impl super::Validator { let mut ctx = VaryingContext { stage: ep.stage, output: false, - flags: self.flags, types: &module.types, type_info: &self.types, location_mask: &mut self.location_mask, built_ins: &mut argument_built_ins, capabilities: self.capabilities, + + #[cfg(feature = "validate")] + flags: self.flags, }; ctx.validate(fa.ty, fa.binding.as_ref()) .map_err_inner(|e| EntryPointError::Argument(index as u32, e).with_span())?; @@ -527,12 +532,14 @@ impl super::Validator { let mut ctx = VaryingContext { stage: ep.stage, output: true, - flags: self.flags, types: &module.types, type_info: &self.types, location_mask: &mut self.location_mask, built_ins: &mut result_built_ins, capabilities: self.capabilities, + + #[cfg(feature = "validate")] + flags: self.flags, }; ctx.validate(fr.ty, fr.binding.as_ref()) .map_err_inner(|e| EntryPointError::Result(e).with_span())?; From 8e1b0529e62f39f2051ec813f99fd682d1a43b5f Mon Sep 17 00:00:00 2001 From: Zhixing Zhang Date: Wed, 21 Dec 2022 04:05:15 -0800 Subject: [PATCH 1884/2212] Supporting gl_PointCoord (#2180) --- src/back/glsl/mod.rs | 1 + src/back/hlsl/conv.rs | 2 +- src/back/msl/mod.rs | 1 + src/back/spv/writer.rs | 1 + src/front/glsl/variables.rs | 10 ++++++++++ src/front/spv/convert.rs | 1 + src/lib.rs | 1 + src/valid/interface.rs | 9 +++++++++ 8 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 72a5d46f7..ca708ff7a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -3723,6 +3723,7 @@ const fn glsl_built_in( Bi::VertexIndex => "uint(gl_VertexID)", // fragment Bi::FragDepth => "gl_FragDepth", + Bi::PointCoord => "gl_PointCoord", Bi::FrontFacing => "gl_FrontFacing", Bi::PrimitiveIndex => "uint(gl_PrimitiveID)", Bi::SampleIndex => "gl_SampleID", diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 525930e1c..886b250b3 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -177,7 +177,7 @@ impl crate::BuiltIn { Self::BaseInstance | Self::BaseVertex | Self::WorkGroupSize => { return Err(Error::Unimplemented(format!("builtin {:?}", self))) } - Self::ViewIndex => { + Self::ViewIndex | Self::PointCoord => { return Err(Error::Custom(format!("Unsupported builtin {:?}", self))) } }) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index a8ed2dd0d..5b3a50d6e 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -391,6 +391,7 @@ impl ResolvedBinding { Bi::VertexIndex => "vertex_id", // fragment Bi::FragDepth => "depth(any)", + Bi::PointCoord => "point_coord", Bi::FrontFacing => "front_facing", Bi::PrimitiveIndex => "primitive_id", Bi::SampleIndex => "sample_id", diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 59fe739f2..4303006bf 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1231,6 +1231,7 @@ impl Writer { Bi::VertexIndex => BuiltIn::VertexIndex, // fragment Bi::FragDepth => BuiltIn::FragDepth, + Bi::PointCoord => BuiltIn::PointCoord, Bi::FrontFacing => BuiltIn::FrontFacing, Bi::PrimitiveIndex => { self.require_any( diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 1634fb40c..c174c9acf 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -128,6 +128,16 @@ impl Parser { mutable: false, storage: StorageQualifier::Input, }, + "gl_PointCoord" => BuiltInData { + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Float, + width: 4, + }, + builtin: BuiltIn::PointCoord, + mutable: false, + storage: StorageQualifier::Input, + }, "gl_GlobalInvocationID" | "gl_NumWorkGroups" | "gl_WorkGroupSize" diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 128f7ceae..af7d2b083 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -137,6 +137,7 @@ pub(super) fn map_builtin(word: spirv::Word, invariant: bool) -> Result crate::BuiltIn::VertexIndex, // fragment Some(Bi::FragDepth) => crate::BuiltIn::FragDepth, + Some(Bi::PointCoord) => crate::BuiltIn::PointCoord, Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing, Some(Bi::PrimitiveId) => crate::BuiltIn::PrimitiveIndex, Some(Bi::SampleId) => crate::BuiltIn::SampleIndex, diff --git a/src/lib.rs b/src/lib.rs index 4b1e7e576..65f018948 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -340,6 +340,7 @@ pub enum BuiltIn { VertexIndex, // fragment FragDepth, + PointCoord, FrontFacing, PrimitiveIndex, SampleIndex, diff --git a/src/valid/interface.rs b/src/valid/interface.rs index f15396441..fdc1cf43e 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -177,6 +177,15 @@ impl VaryingContext<'_> { width, }, ), + Bi::PointCoord => ( + self.stage == St::Fragment && !self.output, + *ty_inner + == Ti::Vector { + size: Vs::Bi, + kind: Sk::Float, + width, + }, + ), Bi::Position { .. } => ( match self.stage { St::Vertex => self.output, From 02280a73572e5e07b53e6119c39e4ed032868472 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 22 Dec 2022 05:21:21 -0500 Subject: [PATCH 1885/2212] msl: handle the case of missing binding (#2175) --- src/back/msl/mod.rs | 6 ++-- src/back/msl/writer.rs | 65 +++++++++++++++++++++++++++--------------- 2 files changed, 46 insertions(+), 25 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 5b3a50d6e..4c0177173 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -156,8 +156,10 @@ pub enum Error { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub enum EntryPointError { + #[error("global '{0}' doesn't have a binding")] + MissingBinding(String), #[error("mapping of {0:?} is missing")] - MissingBinding(crate::ResourceBinding), + MissingBindTarget(crate::ResourceBinding), #[error("mapping for push constants is missing")] MissingPushConstants, #[error("mapping for sizes buffer is missing")] @@ -303,7 +305,7 @@ impl Options { index: 0, interpolation: None, }), - None => Err(EntryPointError::MissingBinding(res_binding.clone())), + None => Err(EntryPointError::MissingBindTarget(res_binding.clone())), } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7cf6ebed6..4ef17975f 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3399,33 +3399,52 @@ impl Writer { if fun_info[var_handle].is_empty() { continue; } - if let Some(ref br) = var.binding { - let good = match options.per_stage_map[ep.stage].resources.get(br) { - Some(target) => { - let binding_ty = match module.types[var.ty].inner { - crate::TypeInner::BindingArray { base, .. } => { - &module.types[base].inner - } - ref ty => ty, - }; - match *binding_ty { - crate::TypeInner::Image { .. } => target.texture.is_some(), - crate::TypeInner::Sampler { .. } => target.sampler.is_some(), - _ => target.buffer.is_some(), + match var.space { + crate::AddressSpace::Uniform + | crate::AddressSpace::Storage { .. } + | crate::AddressSpace::Handle => { + let br = match var.binding { + Some(ref br) => br, + None => { + let var_name = var.name.clone().unwrap_or_default(); + ep_error = + Some(super::EntryPointError::MissingBinding(var_name)); + break; } + }; + let good = match options.per_stage_map[ep.stage].resources.get(br) { + Some(target) => { + let binding_ty = match module.types[var.ty].inner { + crate::TypeInner::BindingArray { base, .. } => { + &module.types[base].inner + } + ref ty => ty, + }; + match *binding_ty { + crate::TypeInner::Image { .. } => target.texture.is_some(), + crate::TypeInner::Sampler { .. } => { + target.sampler.is_some() + } + _ => target.buffer.is_some(), + } + } + None => false, + }; + if !good { + ep_error = + Some(super::EntryPointError::MissingBindTarget(br.clone())); + break; } - None => false, - }; - if !good { - ep_error = Some(super::EntryPointError::MissingBinding(br.clone())); - break; } - } - if var.space == crate::AddressSpace::PushConstant { - if let Err(e) = options.resolve_push_constants(ep.stage) { - ep_error = Some(e); - break; + crate::AddressSpace::PushConstant => { + if let Err(e) = options.resolve_push_constants(ep.stage) { + ep_error = Some(e); + break; + } } + crate::AddressSpace::Function + | crate::AddressSpace::Private + | crate::AddressSpace::WorkGroup => {} } } if supports_array_length { From 24316fd4bc9fca3b0c9cdd858ea593114c208eba Mon Sep 17 00:00:00 2001 From: PENGUINLIONG Date: Fri, 23 Dec 2022 01:59:22 +0800 Subject: [PATCH 1886/2212] Allow `u32` coordinates for `textureStore`/`textureLoad` (#2172) --- src/back/glsl/mod.rs | 20 + src/back/spv/image.rs | 16 + src/valid/mod.rs | 6 +- tests/in/image.wgsl | 10 + tests/out/glsl/image.main.Compute.glsl | 6 + tests/out/hlsl/image.hlsl | 6 + tests/out/msl/image.msl | 6 + tests/out/spv/image.spvasm | 526 +++++++++++++------------ tests/out/wgsl/image.wgsl | 6 + 9 files changed, 351 insertions(+), 251 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ca708ff7a..9ce80658d 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -3144,12 +3144,32 @@ impl<'a, W: Write> Writer<'a, W> { } // Otherwise write just the expression (and the 1D hack if needed) None => { + let uvec_size = match *ctx.info[coordinate].ty.inner_with(&self.module.types) { + TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } => Some(None), + TypeInner::Vector { + size, + kind: crate::ScalarKind::Uint, + .. + } => Some(Some(size as u32)), + _ => None, + }; if tex_1d_hack { write!(self.out, "ivec2(")?; + } else if uvec_size.is_some() { + match uvec_size { + Some(None) => write!(self.out, "int(")?, + Some(Some(size)) => write!(self.out, "ivec{}(", size)?, + _ => {} + } } self.write_expr(coordinate, ctx)?; if tex_1d_hack { write!(self.out, ", 0)")?; + } else if uvec_size.is_some() { + write!(self.out, ")")?; } } } diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index e19da1485..bf2ce28f1 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -317,6 +317,22 @@ impl<'w> BlockContext<'w> { let array_index_i32_id = self.cached[array_index]; let reconciled_array_index_id = if component_kind == crate::ScalarKind::Sint { array_index_i32_id + } else if component_kind == crate::ScalarKind::Uint { + let u32_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Uint, + width: 4, + pointer_space: None, + })); + + let reconciled_id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + u32_id, + reconciled_id, + array_index_i32_id, + )); + reconciled_id } else { let component_type_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size: None, diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 4e62a2ca7..7679223f0 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -226,17 +226,17 @@ impl crate::TypeInner { const fn image_storage_coordinates(&self) -> Option { match *self { Self::Scalar { - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint, .. } => Some(crate::ImageDimension::D1), Self::Vector { size: crate::VectorSize::Bi, - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint, .. } => Some(crate::ImageDimension::D2), Self::Vector { size: crate::VectorSize::Tri, - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint, .. } => Some(crate::ImageDimension::D3), _ => None, diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index 47549283b..d668851be 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -19,12 +19,22 @@ var image_dst: texture_storage_1d; fn main(@builtin(local_invocation_id) local_id: vec3) { let dim = textureDimensions(image_storage_src); let itc = dim * vec2(local_id.xy) % vec2(10, 20); + // loads with ivec2 coords. let value1 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); let value2 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); let value4 = textureLoad(image_storage_src, itc); let value5 = textureLoad(image_array_src, itc, i32(local_id.z), i32(local_id.z) + 1); let value6 = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z)); + // loads with uvec2 coords. + let value1u = textureLoad(image_mipmapped_src, vec2(itc), i32(local_id.z)); + let value2u = textureLoad(image_multisampled_src, vec2(itc), i32(local_id.z)); + let value4u = textureLoad(image_storage_src, vec2(itc)); + let value5u = textureLoad(image_array_src, vec2(itc), i32(local_id.z), i32(local_id.z) + 1); + let value6u = textureLoad(image_1d_src, u32(local_id.x), i32(local_id.z)); + // store with ivec2 coords. textureStore(image_dst, itc.x, value1 + value2 + value4 + value5 + value6); + // store with uvec2 coords. + textureStore(image_dst, u32(itc.x), value1u + value2u + value4u + value5u + value6u); } @compute @workgroup_size(16, 1, 1) diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl index 96d4bb775..8244b908d 100644 --- a/tests/out/glsl/image.main.Compute.glsl +++ b/tests/out/glsl/image.main.Compute.glsl @@ -28,7 +28,13 @@ void main() { uvec4 value4_ = imageLoad(_group_0_binding_1_cs, itc); uvec4 value5_ = texelFetch(_group_0_binding_5_cs, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); uvec4 value6_ = texelFetch(_group_0_binding_7_cs, ivec2(int(local_id.x), 0), int(local_id.z)); + uvec4 value1u = texelFetch(_group_0_binding_0_cs, ivec2(uvec2(itc)), int(local_id.z)); + uvec4 value2u = texelFetch(_group_0_binding_3_cs, ivec2(uvec2(itc)), int(local_id.z)); + uvec4 value4u = imageLoad(_group_0_binding_1_cs, ivec2(uvec2(itc))); + uvec4 value5u = texelFetch(_group_0_binding_5_cs, ivec3(uvec2(itc), int(local_id.z)), (int(local_id.z) + 1)); + uvec4 value6u = texelFetch(_group_0_binding_7_cs, ivec2(uint(local_id.x), 0), int(local_id.z)); imageStore(_group_0_binding_2_cs, ivec2(itc.x, 0), ((((value1_ + value2_) + value4_) + value5_) + value6_)); + imageStore(_group_0_binding_2_cs, ivec2(uint(itc.x), 0), ((((value1u + value2u) + value4u) + value5u) + value6u)); return; } diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 10a3c38c0..5ccec5b10 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -38,7 +38,13 @@ void main(uint3 local_id : SV_GroupThreadID) uint4 value4_ = image_storage_src.Load(itc); uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); uint4 value6_ = image_1d_src.Load(int2(int(local_id.x), int(local_id.z))); + uint4 value1u = image_mipmapped_src.Load(int3(uint2(itc), int(local_id.z))); + uint4 value2u = image_multisampled_src.Load(uint2(itc), int(local_id.z)); + uint4 value4u = image_storage_src.Load(uint2(itc)); + uint4 value5u = image_array_src.Load(int4(uint2(itc), int(local_id.z), (int(local_id.z) + 1))); + uint4 value6u = image_1d_src.Load(int2(uint(local_id.x), int(local_id.z))); image_dst[itc.x] = ((((value1_ + value2_) + value4_) + value5_) + value6_); + image_dst[uint(itc.x)] = ((((value1u + value2u) + value4u) + value5u) + value6u); return; } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 958e147a3..26675c684 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -24,7 +24,13 @@ kernel void main_( metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); metal::uint4 value6_ = image_1d_src.read(uint(static_cast(local_id.x))); + metal::uint4 value1u = image_mipmapped_src.read(metal::uint2(static_cast(itc)), static_cast(local_id.z)); + metal::uint4 value2u = image_multisampled_src.read(metal::uint2(static_cast(itc)), static_cast(local_id.z)); + metal::uint4 value4u = image_storage_src.read(metal::uint2(static_cast(itc))); + metal::uint4 value5u = image_array_src.read(metal::uint2(static_cast(itc)), static_cast(local_id.z), static_cast(local_id.z) + 1); + metal::uint4 value6u = image_1d_src.read(uint(static_cast(local_id.x))); image_dst.write((((value1_ + value2_) + value4_) + value5_) + value6_, uint(itc.x)); + image_dst.write((((value1u + value2u) + value4u) + value5u) + value6u, uint(static_cast(itc.x))); return; } diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 23afaea87..7a50df4a8 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 323 +; Bound: 353 OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D @@ -10,19 +10,19 @@ OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %80 "main" %77 -OpEntryPoint GLCompute %125 "depth_load" %123 -OpEntryPoint Vertex %146 "queries" %144 -OpEntryPoint Vertex %198 "levels_queries" %197 -OpEntryPoint Fragment %227 "texture_sample" %226 -OpEntryPoint Fragment %256 "texture_sample_comparison" %254 -OpEntryPoint Fragment %276 "gather" %275 -OpEntryPoint Fragment %311 "depth_no_comparison" %310 +OpEntryPoint GLCompute %155 "depth_load" %153 +OpEntryPoint Vertex %176 "queries" %174 +OpEntryPoint Vertex %228 "levels_queries" %227 +OpEntryPoint Fragment %257 "texture_sample" %256 +OpEntryPoint Fragment %286 "texture_sample_comparison" %284 +OpEntryPoint Fragment %306 "gather" %305 +OpEntryPoint Fragment %341 "depth_no_comparison" %340 OpExecutionMode %80 LocalSize 16 1 1 -OpExecutionMode %125 LocalSize 16 1 1 -OpExecutionMode %227 OriginUpperLeft -OpExecutionMode %256 OriginUpperLeft -OpExecutionMode %276 OriginUpperLeft -OpExecutionMode %311 OriginUpperLeft +OpExecutionMode %155 LocalSize 16 1 1 +OpExecutionMode %257 OriginUpperLeft +OpExecutionMode %286 OriginUpperLeft +OpExecutionMode %306 OriginUpperLeft +OpExecutionMode %341 OriginUpperLeft OpSource GLSL 450 OpName %35 "image_mipmapped_src" OpName %37 "image_multisampled_src" @@ -47,14 +47,14 @@ OpName %72 "image_2d_depth" OpName %74 "image_cube_depth" OpName %77 "local_id" OpName %80 "main" -OpName %123 "local_id" -OpName %125 "depth_load" -OpName %146 "queries" -OpName %198 "levels_queries" -OpName %227 "texture_sample" -OpName %256 "texture_sample_comparison" -OpName %276 "gather" -OpName %311 "depth_no_comparison" +OpName %153 "local_id" +OpName %155 "depth_load" +OpName %176 "queries" +OpName %228 "levels_queries" +OpName %257 "texture_sample" +OpName %286 "texture_sample_comparison" +OpName %306 "gather" +OpName %341 "depth_no_comparison" OpDecorate %35 DescriptorSet 0 OpDecorate %35 Binding 0 OpDecorate %37 DescriptorSet 0 @@ -101,13 +101,13 @@ OpDecorate %72 Binding 2 OpDecorate %74 DescriptorSet 1 OpDecorate %74 Binding 3 OpDecorate %77 BuiltIn LocalInvocationId -OpDecorate %123 BuiltIn LocalInvocationId -OpDecorate %144 BuiltIn Position -OpDecorate %197 BuiltIn Position -OpDecorate %226 Location 0 -OpDecorate %254 Location 0 -OpDecorate %275 Location 0 -OpDecorate %310 Location 0 +OpDecorate %153 BuiltIn LocalInvocationId +OpDecorate %174 BuiltIn Position +OpDecorate %227 BuiltIn Position +OpDecorate %256 Location 0 +OpDecorate %284 Location 0 +OpDecorate %305 Location 0 +OpDecorate %340 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -188,28 +188,28 @@ OpDecorate %310 Location 0 %90 = OpTypeVector %13 2 %98 = OpTypeVector %13 4 %109 = OpTypeVector %4 3 -%123 = OpVariable %78 Input -%145 = OpTypePointer Output %30 -%144 = OpVariable %145 Output -%155 = OpConstant %13 0 -%197 = OpVariable %145 Output -%226 = OpVariable %145 Output -%232 = OpTypeVector %8 2 -%235 = OpTypeSampledImage %22 -%238 = OpTypeSampledImage %23 -%255 = OpTypePointer Output %8 -%254 = OpVariable %255 Output -%262 = OpTypeSampledImage %32 -%267 = OpConstant %8 0.0 -%268 = OpTypeVector %8 3 -%270 = OpTypeSampledImage %33 -%275 = OpVariable %145 Output -%287 = OpConstant %13 1 -%290 = OpConstant %13 3 -%295 = OpTypeSampledImage %12 -%298 = OpTypeVector %4 4 -%299 = OpTypeSampledImage %24 -%310 = OpVariable %145 Output +%153 = OpVariable %78 Input +%175 = OpTypePointer Output %30 +%174 = OpVariable %175 Output +%185 = OpConstant %13 0 +%227 = OpVariable %175 Output +%256 = OpVariable %175 Output +%262 = OpTypeVector %8 2 +%265 = OpTypeSampledImage %22 +%268 = OpTypeSampledImage %23 +%285 = OpTypePointer Output %8 +%284 = OpVariable %285 Output +%292 = OpTypeSampledImage %32 +%297 = OpConstant %8 0.0 +%298 = OpTypeVector %8 3 +%300 = OpTypeSampledImage %33 +%305 = OpVariable %175 Output +%317 = OpConstant %13 1 +%320 = OpConstant %13 3 +%325 = OpTypeSampledImage %12 +%328 = OpTypeVector %4 4 +%329 = OpTypeSampledImage %24 +%340 = OpVariable %175 Output %80 = OpFunction %2 None %81 %76 = OpLabel %79 = OpLoad %20 %77 @@ -246,217 +246,247 @@ OpBranch %88 %114 = OpCompositeExtract %13 %79 2 %115 = OpBitcast %4 %114 %116 = OpImageFetch %98 %86 %113 Lod %115 -%117 = OpCompositeExtract %4 %95 0 -%118 = OpIAdd %98 %99 %102 -%119 = OpIAdd %98 %118 %103 -%120 = OpIAdd %98 %119 %111 -%121 = OpIAdd %98 %120 %116 -OpImageWrite %87 %117 %121 +%117 = OpBitcast %90 %95 +%118 = OpCompositeExtract %13 %79 2 +%119 = OpBitcast %4 %118 +%120 = OpImageFetch %98 %82 %117 Lod %119 +%121 = OpBitcast %90 %95 +%122 = OpCompositeExtract %13 %79 2 +%123 = OpBitcast %4 %122 +%124 = OpImageFetch %98 %83 %121 Sample %123 +%125 = OpBitcast %90 %95 +%126 = OpImageRead %98 %84 %125 +%127 = OpBitcast %90 %95 +%128 = OpCompositeExtract %13 %79 2 +%129 = OpBitcast %4 %128 +%130 = OpCompositeExtract %13 %79 2 +%131 = OpBitcast %4 %130 +%132 = OpIAdd %4 %131 %6 +%133 = OpBitcast %13 %129 +%134 = OpCompositeConstruct %20 %127 %133 +%135 = OpImageFetch %98 %85 %134 Lod %132 +%136 = OpCompositeExtract %13 %79 0 +%138 = OpCompositeExtract %13 %79 2 +%139 = OpBitcast %4 %138 +%140 = OpImageFetch %98 %86 %136 Lod %139 +%141 = OpCompositeExtract %4 %95 0 +%142 = OpIAdd %98 %99 %102 +%143 = OpIAdd %98 %142 %103 +%144 = OpIAdd %98 %143 %111 +%145 = OpIAdd %98 %144 %116 +OpImageWrite %87 %141 %145 +%146 = OpCompositeExtract %4 %95 0 +%147 = OpBitcast %13 %146 +%148 = OpIAdd %98 %120 %124 +%149 = OpIAdd %98 %148 %126 +%150 = OpIAdd %98 %149 %135 +%151 = OpIAdd %98 %150 %140 +OpImageWrite %87 %147 %151 OpReturn OpFunctionEnd -%125 = OpFunction %2 None %81 -%122 = OpLabel -%124 = OpLoad %20 %123 -%126 = OpLoad %15 %39 -%127 = OpLoad %16 %41 -%128 = OpLoad %18 %49 -OpBranch %129 -%129 = OpLabel -%130 = OpImageQuerySize %21 %127 -%131 = OpVectorShuffle %90 %124 %124 0 1 -%132 = OpBitcast %21 %131 -%133 = OpIMul %21 %130 %132 -%134 = OpCompositeConstruct %21 %3 %5 -%135 = OpSRem %21 %133 %134 -%136 = OpCompositeExtract %13 %124 2 -%137 = OpBitcast %4 %136 -%138 = OpImageFetch %30 %126 %135 Sample %137 -%139 = OpCompositeExtract %8 %138 0 -%140 = OpCompositeExtract %4 %135 0 -%141 = OpConvertFToU %13 %139 -%142 = OpCompositeConstruct %98 %141 %141 %141 %141 -OpImageWrite %128 %140 %142 +%155 = OpFunction %2 None %81 +%152 = OpLabel +%154 = OpLoad %20 %153 +%156 = OpLoad %15 %39 +%157 = OpLoad %16 %41 +%158 = OpLoad %18 %49 +OpBranch %159 +%159 = OpLabel +%160 = OpImageQuerySize %21 %157 +%161 = OpVectorShuffle %90 %154 %154 0 1 +%162 = OpBitcast %21 %161 +%163 = OpIMul %21 %160 %162 +%164 = OpCompositeConstruct %21 %3 %5 +%165 = OpSRem %21 %163 %164 +%166 = OpCompositeExtract %13 %154 2 +%167 = OpBitcast %4 %166 +%168 = OpImageFetch %30 %156 %165 Sample %167 +%169 = OpCompositeExtract %8 %168 0 +%170 = OpCompositeExtract %4 %165 0 +%171 = OpConvertFToU %13 %169 +%172 = OpCompositeConstruct %98 %171 %171 %171 %171 +OpImageWrite %158 %170 %172 OpReturn OpFunctionEnd -%146 = OpFunction %2 None %81 -%143 = OpLabel -%147 = OpLoad %22 %51 -%148 = OpLoad %23 %53 -%149 = OpLoad %25 %58 -%150 = OpLoad %26 %60 -%151 = OpLoad %27 %62 -%152 = OpLoad %28 %64 -%153 = OpLoad %29 %66 -OpBranch %154 -%154 = OpLabel -%156 = OpImageQuerySizeLod %4 %147 %155 -%158 = OpImageQuerySizeLod %4 %147 %156 -%159 = OpImageQuerySizeLod %21 %148 %155 -%160 = OpImageQuerySizeLod %21 %148 %6 -%161 = OpImageQuerySizeLod %109 %149 %155 -%162 = OpVectorShuffle %21 %161 %161 0 1 -%163 = OpImageQuerySizeLod %109 %149 %6 -%164 = OpVectorShuffle %21 %163 %163 0 1 -%165 = OpImageQuerySizeLod %21 %150 %155 -%166 = OpImageQuerySizeLod %21 %150 %6 -%167 = OpImageQuerySizeLod %109 %151 %155 -%168 = OpVectorShuffle %21 %167 %167 0 0 -%169 = OpImageQuerySizeLod %109 %151 %6 -%170 = OpVectorShuffle %21 %169 %169 0 0 -%171 = OpImageQuerySizeLod %109 %152 %155 -%172 = OpImageQuerySizeLod %109 %152 %6 -%173 = OpImageQuerySize %21 %153 -%174 = OpCompositeExtract %4 %159 1 -%175 = OpIAdd %4 %156 %174 -%176 = OpCompositeExtract %4 %160 1 -%177 = OpIAdd %4 %175 %176 -%178 = OpCompositeExtract %4 %162 1 -%179 = OpIAdd %4 %177 %178 -%180 = OpCompositeExtract %4 %164 1 -%181 = OpIAdd %4 %179 %180 -%182 = OpCompositeExtract %4 %165 1 -%183 = OpIAdd %4 %181 %182 -%184 = OpCompositeExtract %4 %166 1 -%185 = OpIAdd %4 %183 %184 -%186 = OpCompositeExtract %4 %168 1 -%187 = OpIAdd %4 %185 %186 -%188 = OpCompositeExtract %4 %170 1 -%189 = OpIAdd %4 %187 %188 -%190 = OpCompositeExtract %4 %171 2 -%191 = OpIAdd %4 %189 %190 -%192 = OpCompositeExtract %4 %172 2 -%193 = OpIAdd %4 %191 %192 -%194 = OpConvertSToF %8 %193 -%195 = OpCompositeConstruct %30 %194 %194 %194 %194 -OpStore %144 %195 +%176 = OpFunction %2 None %81 +%173 = OpLabel +%177 = OpLoad %22 %51 +%178 = OpLoad %23 %53 +%179 = OpLoad %25 %58 +%180 = OpLoad %26 %60 +%181 = OpLoad %27 %62 +%182 = OpLoad %28 %64 +%183 = OpLoad %29 %66 +OpBranch %184 +%184 = OpLabel +%186 = OpImageQuerySizeLod %4 %177 %185 +%188 = OpImageQuerySizeLod %4 %177 %186 +%189 = OpImageQuerySizeLod %21 %178 %185 +%190 = OpImageQuerySizeLod %21 %178 %6 +%191 = OpImageQuerySizeLod %109 %179 %185 +%192 = OpVectorShuffle %21 %191 %191 0 1 +%193 = OpImageQuerySizeLod %109 %179 %6 +%194 = OpVectorShuffle %21 %193 %193 0 1 +%195 = OpImageQuerySizeLod %21 %180 %185 +%196 = OpImageQuerySizeLod %21 %180 %6 +%197 = OpImageQuerySizeLod %109 %181 %185 +%198 = OpVectorShuffle %21 %197 %197 0 0 +%199 = OpImageQuerySizeLod %109 %181 %6 +%200 = OpVectorShuffle %21 %199 %199 0 0 +%201 = OpImageQuerySizeLod %109 %182 %185 +%202 = OpImageQuerySizeLod %109 %182 %6 +%203 = OpImageQuerySize %21 %183 +%204 = OpCompositeExtract %4 %189 1 +%205 = OpIAdd %4 %186 %204 +%206 = OpCompositeExtract %4 %190 1 +%207 = OpIAdd %4 %205 %206 +%208 = OpCompositeExtract %4 %192 1 +%209 = OpIAdd %4 %207 %208 +%210 = OpCompositeExtract %4 %194 1 +%211 = OpIAdd %4 %209 %210 +%212 = OpCompositeExtract %4 %195 1 +%213 = OpIAdd %4 %211 %212 +%214 = OpCompositeExtract %4 %196 1 +%215 = OpIAdd %4 %213 %214 +%216 = OpCompositeExtract %4 %198 1 +%217 = OpIAdd %4 %215 %216 +%218 = OpCompositeExtract %4 %200 1 +%219 = OpIAdd %4 %217 %218 +%220 = OpCompositeExtract %4 %201 2 +%221 = OpIAdd %4 %219 %220 +%222 = OpCompositeExtract %4 %202 2 +%223 = OpIAdd %4 %221 %222 +%224 = OpConvertSToF %8 %223 +%225 = OpCompositeConstruct %30 %224 %224 %224 %224 +OpStore %174 %225 OpReturn OpFunctionEnd -%198 = OpFunction %2 None %81 -%196 = OpLabel -%199 = OpLoad %23 %53 -%200 = OpLoad %25 %58 -%201 = OpLoad %26 %60 -%202 = OpLoad %27 %62 -%203 = OpLoad %28 %64 -%204 = OpLoad %29 %66 -OpBranch %205 -%205 = OpLabel -%206 = OpImageQueryLevels %4 %199 -%207 = OpImageQueryLevels %4 %200 -%208 = OpImageQuerySizeLod %109 %200 %155 -%209 = OpCompositeExtract %4 %208 2 -%210 = OpImageQueryLevels %4 %201 -%211 = OpImageQueryLevels %4 %202 -%212 = OpImageQuerySizeLod %109 %202 %155 -%213 = OpCompositeExtract %4 %212 2 -%214 = OpImageQueryLevels %4 %203 -%215 = OpImageQuerySamples %4 %204 -%216 = OpIAdd %4 %209 %213 -%217 = OpIAdd %4 %216 %215 -%218 = OpIAdd %4 %217 %206 -%219 = OpIAdd %4 %218 %207 -%220 = OpIAdd %4 %219 %214 -%221 = OpIAdd %4 %220 %210 -%222 = OpIAdd %4 %221 %211 -%223 = OpConvertSToF %8 %222 -%224 = OpCompositeConstruct %30 %223 %223 %223 %223 -OpStore %197 %224 -OpReturn -OpFunctionEnd -%227 = OpFunction %2 None %81 -%225 = OpLabel -%228 = OpLoad %22 %51 +%228 = OpFunction %2 None %81 +%226 = OpLabel %229 = OpLoad %23 %53 -%230 = OpLoad %31 %68 -OpBranch %231 -%231 = OpLabel -%233 = OpCompositeConstruct %232 %7 %7 -%234 = OpCompositeExtract %8 %233 0 -%236 = OpSampledImage %235 %228 %230 -%237 = OpImageSampleImplicitLod %30 %236 %234 -%239 = OpSampledImage %238 %229 %230 -%240 = OpImageSampleImplicitLod %30 %239 %233 -%241 = OpSampledImage %238 %229 %230 -%242 = OpImageSampleImplicitLod %30 %241 %233 ConstOffset %34 -%243 = OpSampledImage %238 %229 %230 -%244 = OpImageSampleExplicitLod %30 %243 %233 Lod %9 -%245 = OpSampledImage %238 %229 %230 -%246 = OpImageSampleExplicitLod %30 %245 %233 Lod|ConstOffset %9 %34 -%247 = OpSampledImage %238 %229 %230 -%248 = OpImageSampleImplicitLod %30 %247 %233 Bias|ConstOffset %11 %34 -%249 = OpFAdd %30 %237 %240 -%250 = OpFAdd %30 %249 %242 -%251 = OpFAdd %30 %250 %244 -%252 = OpFAdd %30 %251 %246 -OpStore %226 %252 +%230 = OpLoad %25 %58 +%231 = OpLoad %26 %60 +%232 = OpLoad %27 %62 +%233 = OpLoad %28 %64 +%234 = OpLoad %29 %66 +OpBranch %235 +%235 = OpLabel +%236 = OpImageQueryLevels %4 %229 +%237 = OpImageQueryLevels %4 %230 +%238 = OpImageQuerySizeLod %109 %230 %185 +%239 = OpCompositeExtract %4 %238 2 +%240 = OpImageQueryLevels %4 %231 +%241 = OpImageQueryLevels %4 %232 +%242 = OpImageQuerySizeLod %109 %232 %185 +%243 = OpCompositeExtract %4 %242 2 +%244 = OpImageQueryLevels %4 %233 +%245 = OpImageQuerySamples %4 %234 +%246 = OpIAdd %4 %239 %243 +%247 = OpIAdd %4 %246 %245 +%248 = OpIAdd %4 %247 %236 +%249 = OpIAdd %4 %248 %237 +%250 = OpIAdd %4 %249 %244 +%251 = OpIAdd %4 %250 %240 +%252 = OpIAdd %4 %251 %241 +%253 = OpConvertSToF %8 %252 +%254 = OpCompositeConstruct %30 %253 %253 %253 %253 +OpStore %227 %254 OpReturn OpFunctionEnd -%256 = OpFunction %2 None %81 -%253 = OpLabel -%257 = OpLoad %31 %70 -%258 = OpLoad %32 %72 -%259 = OpLoad %33 %74 -OpBranch %260 -%260 = OpLabel -%261 = OpCompositeConstruct %232 %7 %7 -%263 = OpSampledImage %262 %258 %257 -%264 = OpImageSampleDrefImplicitLod %8 %263 %261 %7 -%265 = OpSampledImage %262 %258 %257 -%266 = OpImageSampleDrefExplicitLod %8 %265 %261 %7 Lod %267 -%269 = OpCompositeConstruct %268 %7 %7 %7 -%271 = OpSampledImage %270 %259 %257 -%272 = OpImageSampleDrefExplicitLod %8 %271 %269 %7 Lod %267 -%273 = OpFAdd %8 %264 %266 -OpStore %254 %273 +%257 = OpFunction %2 None %81 +%255 = OpLabel +%258 = OpLoad %22 %51 +%259 = OpLoad %23 %53 +%260 = OpLoad %31 %68 +OpBranch %261 +%261 = OpLabel +%263 = OpCompositeConstruct %262 %7 %7 +%264 = OpCompositeExtract %8 %263 0 +%266 = OpSampledImage %265 %258 %260 +%267 = OpImageSampleImplicitLod %30 %266 %264 +%269 = OpSampledImage %268 %259 %260 +%270 = OpImageSampleImplicitLod %30 %269 %263 +%271 = OpSampledImage %268 %259 %260 +%272 = OpImageSampleImplicitLod %30 %271 %263 ConstOffset %34 +%273 = OpSampledImage %268 %259 %260 +%274 = OpImageSampleExplicitLod %30 %273 %263 Lod %9 +%275 = OpSampledImage %268 %259 %260 +%276 = OpImageSampleExplicitLod %30 %275 %263 Lod|ConstOffset %9 %34 +%277 = OpSampledImage %268 %259 %260 +%278 = OpImageSampleImplicitLod %30 %277 %263 Bias|ConstOffset %11 %34 +%279 = OpFAdd %30 %267 %270 +%280 = OpFAdd %30 %279 %272 +%281 = OpFAdd %30 %280 %274 +%282 = OpFAdd %30 %281 %276 +OpStore %256 %282 OpReturn OpFunctionEnd -%276 = OpFunction %2 None %81 -%274 = OpLabel -%277 = OpLoad %23 %53 -%278 = OpLoad %12 %55 -%279 = OpLoad %24 %56 -%280 = OpLoad %31 %68 -%281 = OpLoad %31 %70 -%282 = OpLoad %32 %72 -OpBranch %283 +%286 = OpFunction %2 None %81 %283 = OpLabel -%284 = OpCompositeConstruct %232 %7 %7 -%285 = OpSampledImage %238 %277 %280 -%286 = OpImageGather %30 %285 %284 %287 -%288 = OpSampledImage %238 %277 %280 -%289 = OpImageGather %30 %288 %284 %290 ConstOffset %34 -%291 = OpSampledImage %262 %282 %281 -%292 = OpImageDrefGather %30 %291 %284 %7 -%293 = OpSampledImage %262 %282 %281 -%294 = OpImageDrefGather %30 %293 %284 %7 ConstOffset %34 -%296 = OpSampledImage %295 %278 %280 -%297 = OpImageGather %98 %296 %284 %155 -%300 = OpSampledImage %299 %279 %280 -%301 = OpImageGather %298 %300 %284 %155 -%302 = OpConvertUToF %30 %297 -%303 = OpConvertSToF %30 %301 -%304 = OpFAdd %30 %302 %303 -%305 = OpFAdd %30 %286 %289 -%306 = OpFAdd %30 %305 %292 -%307 = OpFAdd %30 %306 %294 -%308 = OpFAdd %30 %307 %304 -OpStore %275 %308 +%287 = OpLoad %31 %70 +%288 = OpLoad %32 %72 +%289 = OpLoad %33 %74 +OpBranch %290 +%290 = OpLabel +%291 = OpCompositeConstruct %262 %7 %7 +%293 = OpSampledImage %292 %288 %287 +%294 = OpImageSampleDrefImplicitLod %8 %293 %291 %7 +%295 = OpSampledImage %292 %288 %287 +%296 = OpImageSampleDrefExplicitLod %8 %295 %291 %7 Lod %297 +%299 = OpCompositeConstruct %298 %7 %7 %7 +%301 = OpSampledImage %300 %289 %287 +%302 = OpImageSampleDrefExplicitLod %8 %301 %299 %7 Lod %297 +%303 = OpFAdd %8 %294 %296 +OpStore %284 %303 OpReturn OpFunctionEnd -%311 = OpFunction %2 None %81 -%309 = OpLabel -%312 = OpLoad %31 %68 -%313 = OpLoad %32 %72 -OpBranch %314 -%314 = OpLabel -%315 = OpCompositeConstruct %232 %7 %7 -%316 = OpSampledImage %262 %313 %312 -%317 = OpImageSampleImplicitLod %30 %316 %315 -%318 = OpCompositeExtract %8 %317 0 -%319 = OpSampledImage %262 %313 %312 -%320 = OpImageGather %30 %319 %315 %155 -%321 = OpCompositeConstruct %30 %318 %318 %318 %318 -%322 = OpFAdd %30 %321 %320 -OpStore %310 %322 +%306 = OpFunction %2 None %81 +%304 = OpLabel +%307 = OpLoad %23 %53 +%308 = OpLoad %12 %55 +%309 = OpLoad %24 %56 +%310 = OpLoad %31 %68 +%311 = OpLoad %31 %70 +%312 = OpLoad %32 %72 +OpBranch %313 +%313 = OpLabel +%314 = OpCompositeConstruct %262 %7 %7 +%315 = OpSampledImage %268 %307 %310 +%316 = OpImageGather %30 %315 %314 %317 +%318 = OpSampledImage %268 %307 %310 +%319 = OpImageGather %30 %318 %314 %320 ConstOffset %34 +%321 = OpSampledImage %292 %312 %311 +%322 = OpImageDrefGather %30 %321 %314 %7 +%323 = OpSampledImage %292 %312 %311 +%324 = OpImageDrefGather %30 %323 %314 %7 ConstOffset %34 +%326 = OpSampledImage %325 %308 %310 +%327 = OpImageGather %98 %326 %314 %185 +%330 = OpSampledImage %329 %309 %310 +%331 = OpImageGather %328 %330 %314 %185 +%332 = OpConvertUToF %30 %327 +%333 = OpConvertSToF %30 %331 +%334 = OpFAdd %30 %332 %333 +%335 = OpFAdd %30 %316 %319 +%336 = OpFAdd %30 %335 %322 +%337 = OpFAdd %30 %336 %324 +%338 = OpFAdd %30 %337 %334 +OpStore %305 %338 +OpReturn +OpFunctionEnd +%341 = OpFunction %2 None %81 +%339 = OpLabel +%342 = OpLoad %31 %68 +%343 = OpLoad %32 %72 +OpBranch %344 +%344 = OpLabel +%345 = OpCompositeConstruct %262 %7 %7 +%346 = OpSampledImage %292 %343 %342 +%347 = OpImageSampleImplicitLod %30 %346 %345 +%348 = OpCompositeExtract %8 %347 0 +%349 = OpSampledImage %292 %343 %342 +%350 = OpImageGather %30 %349 %345 %185 +%351 = OpCompositeConstruct %30 %348 %348 %348 %348 +%352 = OpFAdd %30 %351 %350 +OpStore %340 %352 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 0c1dc48f8..5af7d073a 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -50,7 +50,13 @@ fn main(@builtin(local_invocation_id) local_id: vec3) { let value4_ = textureLoad(image_storage_src, itc); let value5_ = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); let value6_ = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z)); + let value1u = textureLoad(image_mipmapped_src, vec2(itc), i32(local_id.z)); + let value2u = textureLoad(image_multisampled_src, vec2(itc), i32(local_id.z)); + let value4u = textureLoad(image_storage_src, vec2(itc)); + let value5u = textureLoad(image_array_src, vec2(itc), i32(local_id.z), (i32(local_id.z) + 1)); + let value6u = textureLoad(image_1d_src, u32(local_id.x), i32(local_id.z)); textureStore(image_dst, itc.x, ((((value1_ + value2_) + value4_) + value5_) + value6_)); + textureStore(image_dst, u32(itc.x), ((((value1u + value2u) + value4u) + value5u) + value6u)); return; } From 224ff3897d51aa5bd85d296d0e41171dfa7a5b35 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Tue, 25 Oct 2022 09:44:02 -0600 Subject: [PATCH 1887/2212] build(cli): use conventional `bin` path for `naga-cli` --- cli/Cargo.toml | 4 ---- cli/src/{main.rs => bin/naga.rs} | 0 2 files changed, 4 deletions(-) rename cli/src/{main.rs => bin/naga.rs} (100%) diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 6cc017e35..06df3b681 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -9,10 +9,6 @@ repository = "https://github.com/gfx-rs/naga" keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" -[[bin]] -name = "naga" -path = "src/main.rs" - [dependencies] naga = { version = "0.10", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } bincode = "1" diff --git a/cli/src/main.rs b/cli/src/bin/naga.rs similarity index 100% rename from cli/src/main.rs rename to cli/src/bin/naga.rs From e98bd9264c3a6b04dff15a6b1213c0c80201740a Mon Sep 17 00:00:00 2001 From: "Rainb0w :3" <81040339+Rainb0wCodes@users.noreply.github.com> Date: Wed, 4 Jan 2023 12:26:52 -0700 Subject: [PATCH 1888/2212] [glsl-out] emit reflection info for non-struct uniforms (#2189) --- src/back/glsl/mod.rs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9ce80658d..3c750d8d8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -3634,13 +3634,6 @@ impl<'a, W: Write> Writer<'a, W> { continue; } match self.module.types[var.ty].inner { - crate::TypeInner::Struct { .. } => match var.space { - crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } => { - let name = self.reflection_names_globals[&handle].clone(); - uniforms.insert(handle, name); - } - _ => (), - }, crate::TypeInner::Image { .. } => { let tex_name = self.reflection_names_globals[&handle].clone(); match texture_mapping.entry(tex_name) { @@ -3655,7 +3648,13 @@ impl<'a, W: Write> Writer<'a, W> { } } } - _ => {} + _ => match var.space { + crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } => { + let name = self.reflection_names_globals[&handle].clone(); + uniforms.insert(handle, name); + } + _ => (), + }, } } From 5b4e94630be452cdbb662940c3cf637f9dccfade Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 6 Jan 2023 16:34:23 +0100 Subject: [PATCH 1889/2212] [glsl-out] use `fma` polyfill for versions below gles 320 --- src/back/glsl/features.rs | 19 ++++--------------- src/back/glsl/mod.rs | 2 +- tests/in/functions-webgl.param.ron | 2 +- .../out/glsl/functions-webgl.main.Vertex.glsl | 4 ++-- tests/out/glsl/functions.main.Compute.glsl | 3 +-- 5 files changed, 9 insertions(+), 21 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index b898b1d2b..ca292364f 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -1,7 +1,7 @@ use super::{BackendResult, Error, Version, Writer}; use crate::{ AddressSpace, Binding, Bytes, Expression, Handle, ImageClass, ImageDimension, Interpolation, - MathFunction, Sampling, ScalarKind, ShaderStage, StorageFormat, Type, TypeInner, + Sampling, ScalarKind, ShaderStage, StorageFormat, Type, TypeInner, }; use std::fmt::Write; @@ -34,14 +34,12 @@ bitflags::bitflags! { /// Arrays with a dynamic length. const DYNAMIC_ARRAY_SIZE = 1 << 16; const MULTI_VIEW = 1 << 17; - /// Fused multiply-add. - const FMA = 1 << 18; /// Texture samples query - const TEXTURE_SAMPLES = 1 << 19; + const TEXTURE_SAMPLES = 1 << 18; /// Texture levels query - const TEXTURE_LEVELS = 1 << 20; + const TEXTURE_LEVELS = 1 << 19; /// Image size query - const IMAGE_SIZE = 1 << 21; + const IMAGE_SIZE = 1 << 20; } } @@ -224,11 +222,6 @@ impl FeaturesManager { } } - if self.0.contains(Features::FMA) && version >= Version::new_gles(310) { - // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_gpu_shader5.txt - writeln!(out, "#extension GL_EXT_gpu_shader5 : require")?; - } - if self.0.contains(Features::TEXTURE_SAMPLES) { // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_texture_image_samples.txt writeln!( @@ -425,10 +418,6 @@ impl<'a, W> Writer<'a, W> { { for (_, expr) in expressions.iter() { match *expr { - // Check for fused multiply add use - Expression::Math { fun, .. } if fun == MathFunction::Fma => { - features.request(Features::FMA) - } // Check for queries that neeed aditonal features Expression::ImageQuery { image, diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 3c750d8d8..5a7d4d12a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -179,7 +179,7 @@ impl Version { } fn supports_fma_function(&self) -> bool { - *self >= Version::Desktop(400) || *self >= Version::new_gles(310) + *self >= Version::Desktop(400) || *self >= Version::new_gles(320) } } diff --git a/tests/in/functions-webgl.param.ron b/tests/in/functions-webgl.param.ron index 923da0729..8ac016ad2 100644 --- a/tests/in/functions-webgl.param.ron +++ b/tests/in/functions-webgl.param.ron @@ -1,7 +1,7 @@ ( glsl: ( version: Embedded( - version: 300, + version: 320, is_webgl: false ), writer_flags: (bits: 0), diff --git a/tests/out/glsl/functions-webgl.main.Vertex.glsl b/tests/out/glsl/functions-webgl.main.Vertex.glsl index 3522f1a65..9dd084c32 100644 --- a/tests/out/glsl/functions-webgl.main.Vertex.glsl +++ b/tests/out/glsl/functions-webgl.main.Vertex.glsl @@ -1,4 +1,4 @@ -#version 300 es +#version 320 es precision highp float; precision highp int; @@ -8,7 +8,7 @@ vec2 test_fma() { vec2 a = vec2(2.0, 2.0); vec2 b = vec2(0.5, 0.5); vec2 c = vec2(0.5, 0.5); - return (a * b + c); + return fma(a, b, c); } void main() { diff --git a/tests/out/glsl/functions.main.Compute.glsl b/tests/out/glsl/functions.main.Compute.glsl index 07e4e7cde..b0f23125f 100644 --- a/tests/out/glsl/functions.main.Compute.glsl +++ b/tests/out/glsl/functions.main.Compute.glsl @@ -1,5 +1,4 @@ #version 310 es -#extension GL_EXT_gpu_shader5 : require precision highp float; precision highp int; @@ -11,7 +10,7 @@ vec2 test_fma() { vec2 a = vec2(2.0, 2.0); vec2 b = vec2(0.5, 0.5); vec2 c = vec2(0.5, 0.5); - return fma(a, b, c); + return (a * b + c); } int test_integer_dot_product() { From e6e94d65ab8c1ec6fedf5e492418d9c2217c4bf3 Mon Sep 17 00:00:00 2001 From: Daniel McNab <36049421+DJMcNab@users.noreply.github.com> Date: Fri, 4 Nov 2022 15:41:13 +0000 Subject: [PATCH 1890/2212] Error if the uniformity requirements for a barrier aren't met --- src/valid/analyzer.rs | 49 ++++++++++++++++++++++++++++++++++++------- src/valid/function.rs | 2 ++ 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index eb6c1fc4a..e59c3a242 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -775,13 +775,25 @@ impl FunctionInfo { ExitFlags::empty() }, }, - S::Barrier(_) => FunctionUniformity { - result: Uniformity { - non_uniform_result: None, - requirements: UniformityRequirements::WORK_GROUP_BARRIER, - }, - exit: ExitFlags::empty(), - }, + S::Barrier(_) => { + #[cfg(feature = "validate")] + if self + .flags + .contains(super::ValidationFlags::CONTROL_FLOW_UNIFORMITY) + { + if let Some(cause) = disruptor { + return Err(FunctionError::NonUniformBarrier(cause) + .with_span_static(span, "Barrier creation")); + } + } + FunctionUniformity { + result: Uniformity { + non_uniform_result: None, + requirements: UniformityRequirements::WORK_GROUP_BARRIER, + }, + exit: ExitFlags::empty(), + } + } S::Block(ref b) => { self.process_block(b, other_functions, disruptor, expression_arena)? } @@ -1154,7 +1166,7 @@ fn uniform_control_flow() { assert_eq!(info[derivative_expr].ref_count, 1); assert_eq!(info[non_uniform_global], GlobalUse::READ); - let stmt_emit3 = S::Emit(emit_range_globals); + let stmt_emit3 = S::Emit(emit_range_globals.clone()); let stmt_return_non_uniform = S::Return { value: Some(non_uniform_global_expr), }; @@ -1201,4 +1213,25 @@ fn uniform_control_flow() { }), ); assert_eq!(info[non_uniform_global], GlobalUse::READ | GlobalUse::WRITE); + + let stmt_emit5 = S::Emit(emit_range_globals.clone()); + let stmt_if_non_uniform = S::If { + condition: non_uniform_global_expr, + accept: vec![S::Barrier(crate::Barrier::empty())].into(), + reject: crate::Block::new(), + }; + assert_eq!( + info.process_block( + &vec![stmt_emit5, stmt_if_non_uniform].into(), + &[], + None, + &expressions + ), + Err( + FunctionError::NonUniformBarrier(UniformityDisruptor::Expression( + non_uniform_global_expr + )) + .with_span() + ), + ); } diff --git a/src/valid/function.rs b/src/valid/function.rs index 3c555491c..a7cdc45f2 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -139,6 +139,8 @@ pub enum FunctionError { Handle, UniformityDisruptor, ), + #[error("Required uniformity of barrier is not fulfilled because of {0:?}")] + NonUniformBarrier(UniformityDisruptor), #[error("Functions that are not entry points cannot have `@location` or `@builtin` attributes on their arguments: \"{name}\" has attributes")] PipelineInputRegularFunction { name: String }, #[error("Functions that are not entry points cannot have `@location` or `@builtin` attributes on their return value types")] From 86a88de3968133049c11c9e728ef4aa0c2d3b9f4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 11 Jan 2023 07:35:03 -0800 Subject: [PATCH 1891/2212] Revert "Error if the uniformity requirements for a barrier aren't met" (#2203) This reverts commit e6e94d65ab8c1ec6fedf5e492418d9c2217c4bf3. --- src/valid/analyzer.rs | 49 +++++++------------------------------------ src/valid/function.rs | 2 -- 2 files changed, 8 insertions(+), 43 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index e59c3a242..eb6c1fc4a 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -775,25 +775,13 @@ impl FunctionInfo { ExitFlags::empty() }, }, - S::Barrier(_) => { - #[cfg(feature = "validate")] - if self - .flags - .contains(super::ValidationFlags::CONTROL_FLOW_UNIFORMITY) - { - if let Some(cause) = disruptor { - return Err(FunctionError::NonUniformBarrier(cause) - .with_span_static(span, "Barrier creation")); - } - } - FunctionUniformity { - result: Uniformity { - non_uniform_result: None, - requirements: UniformityRequirements::WORK_GROUP_BARRIER, - }, - exit: ExitFlags::empty(), - } - } + S::Barrier(_) => FunctionUniformity { + result: Uniformity { + non_uniform_result: None, + requirements: UniformityRequirements::WORK_GROUP_BARRIER, + }, + exit: ExitFlags::empty(), + }, S::Block(ref b) => { self.process_block(b, other_functions, disruptor, expression_arena)? } @@ -1166,7 +1154,7 @@ fn uniform_control_flow() { assert_eq!(info[derivative_expr].ref_count, 1); assert_eq!(info[non_uniform_global], GlobalUse::READ); - let stmt_emit3 = S::Emit(emit_range_globals.clone()); + let stmt_emit3 = S::Emit(emit_range_globals); let stmt_return_non_uniform = S::Return { value: Some(non_uniform_global_expr), }; @@ -1213,25 +1201,4 @@ fn uniform_control_flow() { }), ); assert_eq!(info[non_uniform_global], GlobalUse::READ | GlobalUse::WRITE); - - let stmt_emit5 = S::Emit(emit_range_globals.clone()); - let stmt_if_non_uniform = S::If { - condition: non_uniform_global_expr, - accept: vec![S::Barrier(crate::Barrier::empty())].into(), - reject: crate::Block::new(), - }; - assert_eq!( - info.process_block( - &vec![stmt_emit5, stmt_if_non_uniform].into(), - &[], - None, - &expressions - ), - Err( - FunctionError::NonUniformBarrier(UniformityDisruptor::Expression( - non_uniform_global_expr - )) - .with_span() - ), - ); } diff --git a/src/valid/function.rs b/src/valid/function.rs index a7cdc45f2..3c555491c 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -139,8 +139,6 @@ pub enum FunctionError { Handle, UniformityDisruptor, ), - #[error("Required uniformity of barrier is not fulfilled because of {0:?}")] - NonUniformBarrier(UniformityDisruptor), #[error("Functions that are not entry points cannot have `@location` or `@builtin` attributes on their arguments: \"{name}\" has attributes")] PipelineInputRegularFunction { name: String }, #[error("Functions that are not entry points cannot have `@location` or `@builtin` attributes on their return value types")] From 7effd125962ebf91b2a17f0100c6474f61f46e50 Mon Sep 17 00:00:00 2001 From: Timo de Kort Date: Wed, 11 Jan 2023 18:23:42 +0100 Subject: [PATCH 1892/2212] Update setup-dxc to v1.1.0 (#2204) --- .github/workflows/validation-windows.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/validation-windows.yml b/.github/workflows/validation-windows.yml index 31f7ee368..1d1d32401 100644 --- a/.github/workflows/validation-windows.yml +++ b/.github/workflows/validation-windows.yml @@ -11,7 +11,7 @@ jobs: steps: - uses: actions/checkout@v2 - name: Add DirectXShaderCompiler - uses: napokue/setup-dxc@v1.0.0 + uses: napokue/setup-dxc@v1.1.0 - run: make validate-hlsl-dxc shell: sh From 6035b07b786135f65cb4140f99cf67cc0381b4c3 Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Thu, 12 Jan 2023 09:26:28 -0800 Subject: [PATCH 1893/2212] [wgsl-in] Implement module-level scoping. Fixes #1745: Support out-of-order module scope declarations in WGSL Fixes #1044: Forbid local variable shadowing in WGSL Fixes #2076: [wgsl-in] no error for duplicated type definition Fixes #2071: Global item does not support 'const' Fixes #2105: [wgsl-in] Type aliases for a vecN doesn't work when constructing vec from a single argument Fixes #1775: Referencing a function without a return type yields an unknown identifier error. Fixes #2089: Error span reported on the declaration of a variable instead of its use Fixes #1996: [wgsl-in] Confusing error: "expected unsigned/signed integer literal, found '1'" Separate parsing from lowering by generating an AST, which desugars as much as possible down to something like Naga IR. The AST is then used to resolve identifiers while lowering to Naga IR. Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Co-authored-by: Jim Blandy --- src/back/wgsl/writer.rs | 4 +- src/front/glsl/parser_tests.rs | 2 +- src/front/glsl/types.rs | 15 +- src/front/mod.rs | 67 +- src/front/wgsl/ast.rs | 476 ++ src/front/wgsl/construction.rs | 1271 ++-- src/front/wgsl/conv.rs | 3 +- src/front/wgsl/index.rs | 192 + src/front/wgsl/lexer.rs | 88 +- src/front/wgsl/mod.rs | 5787 +++++++++-------- src/front/wgsl/tests.rs | 6 +- src/span.rs | 17 + tests/in/access.wgsl | 6 +- tests/in/atomicCompareExchange.wgsl | 2 +- tests/in/bitcast.wgsl | 8 +- tests/in/boids.wgsl | 2 +- tests/in/globals.wgsl | 6 +- tests/in/module-scope.wgsl | 26 + tests/in/operators.wgsl | 8 +- tests/in/quad.wgsl | 4 +- tests/in/shadow.wgsl | 4 +- tests/in/type-alias.wgsl | 13 + tests/out/analysis/collatz.info.ron | 110 +- tests/out/dot/quad.dot | 78 +- .../access.assign_through_ptr.Compute.glsl | 4 +- tests/out/glsl/access.atomics.Compute.glsl | 30 +- tests/out/glsl/access.foo_frag.Fragment.glsl | 4 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 113 +- tests/out/glsl/bits.main.Compute.glsl | 2 + tests/out/glsl/boids.main.Compute.glsl | 159 +- ...age-restrict.fragment_shader.Fragment.glsl | 32 +- ...k-image-rzsw.fragment_shader.Fragment.glsl | 26 +- tests/out/glsl/globals.main.Compute.glsl | 43 +- tests/out/glsl/operators.main.Compute.glsl | 74 +- tests/out/glsl/padding.vertex.Vertex.glsl | 6 +- tests/out/glsl/shadow.fs_main.Fragment.glsl | 42 +- ...adow.fs_main_without_storage.Fragment.glsl | 42 +- tests/out/glsl/shadow.vs_main.Vertex.glsl | 12 +- tests/out/glsl/skybox.fs_main.Fragment.glsl | 4 +- tests/out/glsl/skybox.vs_main.Vertex.glsl | 16 +- tests/out/glsl/texture-arg.main.Fragment.glsl | 4 +- tests/out/hlsl/access.hlsl | 141 +- tests/out/hlsl/binding-arrays.hlsl | 236 +- tests/out/hlsl/boids.hlsl | 165 +- tests/out/hlsl/collatz.hlsl | 37 +- tests/out/hlsl/globals.hlsl | 47 +- tests/out/hlsl/interface.hlsl | 7 +- tests/out/hlsl/operators.hlsl | 74 +- tests/out/hlsl/padding.hlsl | 6 +- tests/out/hlsl/shadow.hlsl | 92 +- tests/out/hlsl/skybox.hlsl | 20 +- tests/out/hlsl/texture-arg.hlsl | 4 +- tests/out/ir/collatz.ron | 220 +- tests/out/msl/access.msl | 157 +- tests/out/msl/binding-arrays.msl | 236 +- tests/out/msl/bits.msl | 6 +- tests/out/msl/boids.msl | 165 +- tests/out/msl/bounds-check-image-restrict.msl | 48 +- tests/out/msl/bounds-check-image-rzsw.msl | 38 +- tests/out/msl/bounds-check-restrict.msl | 6 +- tests/out/msl/bounds-check-zero.msl | 6 +- tests/out/msl/collatz.msl | 37 +- tests/out/msl/globals.msl | 47 +- tests/out/msl/interface.msl | 7 +- tests/out/msl/math-functions.msl | 4 +- tests/out/msl/operators.msl | 118 +- tests/out/msl/padding.msl | 6 +- tests/out/msl/policy-mix.msl | 10 +- tests/out/msl/shadow.msl | 92 +- tests/out/msl/skybox.msl | 20 +- tests/out/msl/texture-arg.msl | 4 +- tests/out/spv/access.spvasm | 732 +-- tests/out/spv/atomicCompareExchange.spvasm | 264 +- tests/out/spv/binding-arrays.spvasm | 1032 +-- tests/out/spv/bits.spvasm | 398 +- tests/out/spv/boids.spvasm | 498 +- tests/out/spv/collatz.spvasm | 140 +- tests/out/spv/extra.spvasm | 96 +- tests/out/spv/functions.spvasm | 86 +- tests/out/spv/globals.spvasm | 234 +- tests/out/spv/image.spvasm | 718 +- .../spv/interface.vertex_two_structs.spvasm | 53 +- tests/out/spv/math-functions.spvasm | 38 +- tests/out/spv/operators.spvasm | 488 +- tests/out/spv/shadow.spvasm | 524 +- tests/out/wgsl/access.wgsl | 141 +- tests/out/wgsl/atomicCompareExchange.wgsl | 96 +- tests/out/wgsl/binding-arrays.wgsl | 260 +- tests/out/wgsl/bits.wgsl | 6 +- tests/out/wgsl/boids.wgsl | 167 +- tests/out/wgsl/collatz.wgsl | 37 +- tests/out/wgsl/globals.wgsl | 43 +- tests/out/wgsl/interface.wgsl | 7 +- tests/out/wgsl/lexical-scopes.wgsl | 11 +- tests/out/wgsl/module-scope.wgsl | 26 + tests/out/wgsl/operators.wgsl | 82 +- tests/out/wgsl/padding.wgsl | 6 +- tests/out/wgsl/quad.wgsl | 2 +- tests/out/wgsl/shadow.wgsl | 96 +- tests/out/wgsl/skybox.wgsl | 20 +- tests/out/wgsl/texture-arg.wgsl | 4 +- tests/out/wgsl/type-alias.wgsl | 9 + tests/snapshots.rs | 2 + tests/wgsl-errors.rs | 252 +- 104 files changed, 9624 insertions(+), 7808 deletions(-) create mode 100644 src/front/wgsl/ast.rs create mode 100644 src/front/wgsl/index.rs create mode 100644 tests/in/module-scope.wgsl create mode 100644 tests/in/type-alias.wgsl create mode 100644 tests/out/wgsl/module-scope.wgsl create mode 100644 tests/out/wgsl/type-alias.wgsl diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index f9e98e8cd..51091f8be 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1850,7 +1850,7 @@ impl Writer { } => { let name = &self.names[&NameKey::Constant(handle)]; // First write only constant name - write!(self.out, "let {}: ", name)?; + write!(self.out, "const {}: ", name)?; // Next write constant type and value match *value { crate::ScalarValue::Sint(value) => { @@ -1874,7 +1874,7 @@ impl Writer { crate::ConstantInner::Composite { ty, ref components } => { let name = &self.names[&NameKey::Constant(handle)]; // First write only constant name - write!(self.out, "let {}: ", name)?; + write!(self.out, "const {}: ", name)?; // Next write constant type self.write_type(module, ty)?; diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index 5f865e975..d6d831aaf 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -796,7 +796,7 @@ fn expressions() { # version 450 void main() { uint index = 0; - + --index; ++index; } diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 05c415eba..427b0b27b 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -300,20 +300,7 @@ impl Parser { meta: Span, ) -> Result> { self.typifier_grow(ctx, expr, meta)?; - let resolution = &ctx.typifier[expr]; - Ok(match *resolution { - // If the resolution is already a handle return early - crate::proc::TypeResolution::Handle(ty) => ty, - // If it's a value we need to clone it - crate::proc::TypeResolution::Value(_) => match resolution.clone() { - // This is unreachable - crate::proc::TypeResolution::Handle(ty) => ty, - // Add the value to the type arena and return the handle - crate::proc::TypeResolution::Value(inner) => { - self.module.types.insert(Type { name: None, inner }, meta) - } - }, - }) + Ok(ctx.typifier.register_type(expr, &mut self.module.types)) } /// Invalidates the cached type resolution for `expr` forcing a recomputation diff --git a/src/front/mod.rs b/src/front/mod.rs index 09836c676..071e805a6 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -64,7 +64,35 @@ impl super::ConstantInner { } } -/// Helper processor that derives the types of all expressions. +/// A table of types for an `Arena`. +/// +/// A front end can use a `Typifier` to get types for an arena's expressions +/// while it is still contributing expressions to it. At any point, you can call +/// [`typifier.grow(expr, arena, ctx)`], where `expr` is a `Handle` +/// referring to something in `arena`, and the `Typifier` will resolve the types +/// of all the expressions up to and including `expr`. Then you can write +/// `typifier[handle]` to get the type of any handle at or before `expr`. +/// +/// Note that `Typifier` does *not* build an `Arena` as a part of its +/// usual operation. Ideally, a module's type arena should only contain types +/// actually needed by `Handle`s elsewhere in the module — functions, +/// variables, [`Compose`] expressions, other types, and so on — so we don't +/// want every little thing that occurs as the type of some intermediate +/// expression to show up there. +/// +/// Instead, `Typifier` accumulates a [`TypeResolution`] for each expression, +/// which refers to the `Arena` in the [`ResolveContext`] passed to `grow` +/// as needed. [`TypeResolution`] is a lightweight representation for +/// intermediate types like this; see its documentation for details. +/// +/// If you do need to register a `Typifier`'s conclusion in an `Arena` +/// (say, for a [`LocalVariable`] whose type you've inferred), you can use +/// [`register_type`] to do so. +/// +/// [`typifier.grow(expr, arena)`]: Typifier::grow +/// [`register_type`]: Typifier::register_type +/// [`Compose`]: crate::Expression::Compose +/// [`LocalVariable`]: crate::LocalVariable #[derive(Debug, Default)] pub struct Typifier { resolutions: Vec, @@ -89,6 +117,34 @@ impl Typifier { self.resolutions[expr_handle.index()].inner_with(types) } + /// Add an expression's type to an `Arena`. + /// + /// Add the type of `expr_handle` to `types`, and return a `Handle` + /// referring to it. + /// + /// # Note + /// + /// If you just need a [`TypeInner`] for `expr_handle`'s type, consider + /// using `typifier[expression].inner_with(types)` instead. Calling + /// [`TypeResolution::inner_with`] often lets us avoid adding anything to + /// the arena, which can significantly reduce the number of types that end + /// up in the final module. + /// + /// [`TypeInner`]: crate::TypeInner + pub fn register_type( + &self, + expr_handle: Handle, + types: &mut UniqueArena, + ) -> Handle { + match self[expr_handle].clone() { + TypeResolution::Handle(handle) => handle, + TypeResolution::Value(inner) => { + types.insert(crate::Type { name: None, inner }, crate::Span::UNDEFINED) + } + } + } + + /// Grow this typifier until it contains a type for `expr_handle`. pub fn grow( &mut self, expr_handle: Handle, @@ -106,10 +162,13 @@ impl Typifier { Ok(()) } - /// Invalidates the cached type resolution for `expr_handle` forcing a recomputation + /// Recompute the type resolution for `expr_handle`. /// - /// If the type of the expression hasn't yet been calculated a - /// [`grow`](Self::grow) is performed instead + /// If the type of `expr_handle` hasn't yet been calculated, call + /// [`grow`](Self::grow) to ensure it is covered. + /// + /// In either case, when this returns, `self[expr_handle]` should be an + /// updated type resolution for `expr_handle`. pub fn invalidate( &mut self, expr_handle: Handle, diff --git a/src/front/wgsl/ast.rs b/src/front/wgsl/ast.rs new file mode 100644 index 000000000..eff74530f --- /dev/null +++ b/src/front/wgsl/ast.rs @@ -0,0 +1,476 @@ +use super::Number; +use crate::{Arena, FastHashSet, Handle, Span}; +use std::hash::Hash; + +#[derive(Debug, Default)] +pub struct TranslationUnit<'a> { + pub decls: Arena>, + /// The common expressions arena for the entire translation unit. + /// + /// All functions, global initializers, array lengths, etc. store their + /// expressions here. We apportion these out to individual Naga + /// [`Function`]s' expression arenas at lowering time. Keeping them all in a + /// single arena simplifies handling of things like array lengths (which are + /// effectively global and thus don't clearly belong to any function) and + /// initializers (which can appear in both function-local and module-scope + /// contexts). + /// + /// [`Function`]: crate::Function + pub expressions: Arena>, + + /// Non-user-defined types, like `vec4` or `array`. + /// + /// These are referred to by `Handle>` values. + /// User-defined types are referred to by name until lowering. + pub types: Arena>, +} + +#[derive(Debug, Clone, Copy)] +pub struct Ident<'a> { + pub name: &'a str, + pub span: Span, +} + +#[derive(Debug)] +pub enum IdentExpr<'a> { + Unresolved(&'a str), + Local(Handle), +} + +/// A reference to a module-scope definition or predeclared object. +/// +/// Each [`GlobalDecl`] holds a set of these values, to be resolved to +/// specific definitions later. To support de-duplication, `Eq` and +/// `Hash` on a `Dependency` value consider only the name, not the +/// source location at which the reference occurs. +#[derive(Debug)] +pub struct Dependency<'a> { + /// The name referred to. + pub ident: &'a str, + + /// The location at which the reference to that name occurs. + pub usage: Span, +} + +impl Hash for Dependency<'_> { + fn hash(&self, state: &mut H) { + self.ident.hash(state); + } +} + +impl PartialEq for Dependency<'_> { + fn eq(&self, other: &Self) -> bool { + self.ident == other.ident + } +} + +impl Eq for Dependency<'_> {} + +/// A module-scope declaration. +#[derive(Debug)] +pub struct GlobalDecl<'a> { + pub kind: GlobalDeclKind<'a>, + + /// Names of all module-scope or predeclared objects this + /// declaration uses. + pub dependencies: FastHashSet>, +} + +#[derive(Debug)] +pub enum GlobalDeclKind<'a> { + Fn(Function<'a>), + Var(GlobalVariable<'a>), + Const(Const<'a>), + Struct(Struct<'a>), + Type(TypeAlias<'a>), +} + +#[derive(Debug)] +pub struct FunctionArgument<'a> { + pub name: Ident<'a>, + pub ty: Handle>, + pub binding: Option, + pub handle: Handle, +} + +#[derive(Debug)] +pub struct FunctionResult<'a> { + pub ty: Handle>, + pub binding: Option, +} + +#[derive(Debug)] +pub struct EntryPoint { + pub stage: crate::ShaderStage, + pub early_depth_test: Option, + pub workgroup_size: [u32; 3], +} + +#[derive(Debug)] +pub struct Function<'a> { + pub entry_point: Option, + pub name: Ident<'a>, + pub arguments: Vec>, + pub result: Option>, + + /// Local variable and function argument arena. + /// + /// Note that the `Local` here is actually a zero-sized type. The AST keeps + /// all the detailed information about locals - names, types, etc. - in + /// [`LocalDecl`] statements. For arguments, that information is kept in + /// [`arguments`]. This `Arena`'s only role is to assign a unique `Handle` + /// to each of them, and track their definitions' spans for use in + /// diagnostics. + /// + /// In the AST, when an [`Ident`] expression refers to a local variable or + /// argument, its [`IdentExpr`] holds the referent's `Handle` in this + /// arena. + /// + /// During lowering, [`LocalDecl`] statements add entries to a per-function + /// table that maps `Handle` values to their Naga representations, + /// accessed via [`StatementContext::local_table`] and + /// [`ExpressionContext::local_table`]. This table is then consulted when + /// lowering subsequent [`Ident`] expressions. + /// + /// [`LocalDecl`]: StatementKind::LocalDecl + /// [`arguments`]: Function::arguments + /// [`Ident`]: Expression::Ident + /// [`StatementContext::local_table`]: super::StatementContext::local_table + /// [`ExpressionContext::local_table`]: super::ExpressionContext::local_table + pub locals: Arena, + + pub body: Block<'a>, +} + +#[derive(Debug)] +pub struct GlobalVariable<'a> { + pub name: Ident<'a>, + pub space: crate::AddressSpace, + pub binding: Option, + pub ty: Handle>, + pub init: Option>>, +} + +#[derive(Debug)] +pub struct StructMember<'a> { + pub name: Ident<'a>, + pub ty: Handle>, + pub binding: Option, + pub align: Option<(u32, Span)>, + pub size: Option<(u32, Span)>, +} + +#[derive(Debug)] +pub struct Struct<'a> { + pub name: Ident<'a>, + pub members: Vec>, +} + +#[derive(Debug)] +pub struct TypeAlias<'a> { + pub name: Ident<'a>, + pub ty: Handle>, +} + +#[derive(Debug)] +pub struct Const<'a> { + pub name: Ident<'a>, + pub ty: Option>>, + pub init: Handle>, +} + +/// The size of an [`Array`] or [`BindingArray`]. +/// +/// [`Array`]: Type::Array +/// [`BindingArray`]: Type::BindingArray +#[derive(Debug, Copy, Clone)] +pub enum ArraySize<'a> { + /// The length as a constant expression. + Constant(Handle>), + Dynamic, +} + +#[derive(Debug)] +pub enum Type<'a> { + Scalar { + kind: crate::ScalarKind, + width: crate::Bytes, + }, + Vector { + size: crate::VectorSize, + kind: crate::ScalarKind, + width: crate::Bytes, + }, + Matrix { + columns: crate::VectorSize, + rows: crate::VectorSize, + width: crate::Bytes, + }, + Atomic { + kind: crate::ScalarKind, + width: crate::Bytes, + }, + Pointer { + base: Handle>, + space: crate::AddressSpace, + }, + Array { + base: Handle>, + size: ArraySize<'a>, + }, + Image { + dim: crate::ImageDimension, + arrayed: bool, + class: crate::ImageClass, + }, + Sampler { + comparison: bool, + }, + BindingArray { + base: Handle>, + size: ArraySize<'a>, + }, + + /// A user-defined type, like a struct or a type alias. + User(Ident<'a>), +} + +#[derive(Debug, Default)] +pub struct Block<'a> { + pub stmts: Vec>, +} + +#[derive(Debug)] +pub struct Statement<'a> { + pub kind: StatementKind<'a>, + pub span: Span, +} + +#[derive(Debug)] +pub enum StatementKind<'a> { + LocalDecl(LocalDecl<'a>), + Block(Block<'a>), + If { + condition: Handle>, + accept: Block<'a>, + reject: Block<'a>, + }, + Switch { + selector: Handle>, + cases: Vec>, + }, + Loop { + body: Block<'a>, + continuing: Block<'a>, + break_if: Option>>, + }, + Break, + Continue, + Return { + value: Option>>, + }, + Kill, + Call { + function: Ident<'a>, + arguments: Vec>>, + }, + Assign { + target: Handle>, + op: Option, + value: Handle>, + }, + Increment(Handle>), + Decrement(Handle>), + Ignore(Handle>), +} + +#[derive(Debug)] +pub enum SwitchValue { + I32(i32), + U32(u32), + Default, +} + +#[derive(Debug)] +pub struct SwitchCase<'a> { + pub value: SwitchValue, + pub value_span: Span, + pub body: Block<'a>, + pub fall_through: bool, +} + +/// A type at the head of a [`Construct`] expression. +/// +/// WGSL has two types of [`type constructor expressions`]: +/// +/// - Those that fully specify the type being constructed, like +/// `vec3(x,y,z)`, which obviously constructs a `vec3`. +/// +/// - Those that leave the component type of the composite being constructed +/// implicit, to be inferred from the argument types, like `vec3(x,y,z)`, +/// which constructs a `vec3` where `T` is the type of `x`, `y`, and `z`. +/// +/// This enum represents the head type of both cases. The `PartialFoo` variants +/// represent the second case, where the component type is implicit. +/// +/// This does not cover structs or types referred to by type aliases. See the +/// documentation for [`Construct`] and [`Call`] expressions for details. +/// +/// [`Construct`]: Expression::Construct +/// [`type constructor expressions`]: https://gpuweb.github.io/gpuweb/wgsl/#type-constructor-expr +/// [`Call`]: Expression::Call +#[derive(Debug)] +pub enum ConstructorType<'a> { + /// A scalar type or conversion: `f32(1)`. + Scalar { + kind: crate::ScalarKind, + width: crate::Bytes, + }, + + /// A vector construction whose component type is inferred from the + /// argument: `vec3(1.0)`. + PartialVector { size: crate::VectorSize }, + + /// A vector construction whose component type is written out: + /// `vec3(1.0)`. + Vector { + size: crate::VectorSize, + kind: crate::ScalarKind, + width: crate::Bytes, + }, + + /// A matrix construction whose component type is inferred from the + /// argument: `mat2x2(1,2,3,4)`. + PartialMatrix { + columns: crate::VectorSize, + rows: crate::VectorSize, + }, + + /// A matrix construction whose component type is written out: + /// `mat2x2(1,2,3,4)`. + Matrix { + columns: crate::VectorSize, + rows: crate::VectorSize, + width: crate::Bytes, + }, + + /// An array whose component type and size are inferred from the arguments: + /// `array(3,4,5)`. + PartialArray, + + /// An array whose component type and size are written out: + /// `array(3,4,5)`. + Array { + base: Handle>, + size: ArraySize<'a>, + }, + + /// Constructing a value of a known Naga IR type. + /// + /// This variant is produced only during lowering, when we have Naga types + /// available, never during parsing. + Type(Handle), +} + +#[derive(Debug, Copy, Clone)] +pub enum Literal { + Bool(bool), + Number(Number), +} + +#[derive(Debug)] +pub enum Expression<'a> { + Literal(Literal), + Ident(IdentExpr<'a>), + + /// A type constructor expression. + /// + /// This is only used for expressions like `KEYWORD(EXPR...)` and + /// `KEYWORD(EXPR...)`, where `KEYWORD` is a [type-defining keyword] like + /// `vec3`. These keywords cannot be shadowed by user definitions, so we can + /// tell that such an expression is a construction immediately. + /// + /// For ordinary identifiers, we can't tell whether an expression like + /// `IDENTIFIER(EXPR, ...)` is a construction expression or a function call + /// until we know `IDENTIFIER`'s definition, so we represent those as + /// [`Call`] expressions. + /// + /// [type-defining keyword]: https://gpuweb.github.io/gpuweb/wgsl/#type-defining-keywords + /// [`Call`]: Expression::Call + Construct { + ty: ConstructorType<'a>, + ty_span: Span, + components: Vec>>, + }, + Unary { + op: crate::UnaryOperator, + expr: Handle>, + }, + AddrOf(Handle>), + Deref(Handle>), + Binary { + op: crate::BinaryOperator, + left: Handle>, + right: Handle>, + }, + + /// A function call or type constructor expression. + /// + /// We can't tell whether an expression like `IDENTIFIER(EXPR, ...)` is a + /// construction expression or a function call until we know `IDENTIFIER`'s + /// definition, so we represent everything of that form as one of these + /// expressions until lowering. At that point, [`Lowerer::call`] has + /// everything's definition in hand, and can decide whether to emit a Naga + /// [`Constant`], [`As`], [`Splat`], or [`Compose`] expression. + /// + /// [`Lowerer::call`]: super::Lowerer::call + /// [`Constant`]: crate::Expression::Constant + /// [`As`]: crate::Expression::As + /// [`Splat`]: crate::Expression::Splat + /// [`Compose`]: crate::Expression::Compose + Call { + function: Ident<'a>, + arguments: Vec>>, + }, + Index { + base: Handle>, + index: Handle>, + }, + Member { + base: Handle>, + field: Ident<'a>, + }, + Bitcast { + expr: Handle>, + to: Handle>, + ty_span: Span, + }, +} + +#[derive(Debug)] +pub struct LocalVariable<'a> { + pub name: Ident<'a>, + pub ty: Option>>, + pub init: Option>>, + pub handle: Handle, +} + +#[derive(Debug)] +pub struct Let<'a> { + pub name: Ident<'a>, + pub ty: Option>>, + pub init: Handle>, + pub handle: Handle, +} + +#[derive(Debug)] +pub enum LocalDecl<'a> { + Var(LocalVariable<'a>), + Let(Let<'a>), +} + +#[derive(Debug)] +/// A placeholder for a local variable declaration. +/// +/// See [`Function::locals`] for more information. +pub struct Local; diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/construction.rs index 43e719d0f..2fae293c1 100644 --- a/src/front/wgsl/construction.rs +++ b/src/front/wgsl/construction.rs @@ -1,679 +1,666 @@ -use crate::{ - proc::TypeResolution, Arena, ArraySize, Bytes, Constant, ConstantInner, Expression, Handle, - ScalarKind, ScalarValue, Span as NagaSpan, Type, TypeInner, UniqueArena, VectorSize, -}; +use crate::{Handle, Span}; -use super::{Error, ExpressionContext, Lexer, Parser, Rule, Span, Token}; +use super::{ast, Error, ExpressionContext, Lowerer, OutputContext}; +use crate::proc::TypeResolution; -/// Represents the type of the constructor -/// -/// Vectors, Matrices and Arrays can have partial type information -/// which later gets inferred from the constructor parameters -enum ConstructorType { - Scalar { - kind: ScalarKind, - width: Bytes, - }, +enum ConcreteConstructorHandle { PartialVector { - size: VectorSize, - }, - Vector { - size: VectorSize, - kind: ScalarKind, - width: Bytes, + size: crate::VectorSize, }, PartialMatrix { - columns: VectorSize, - rows: VectorSize, - }, - Matrix { - columns: VectorSize, - rows: VectorSize, - width: Bytes, + columns: crate::VectorSize, + rows: crate::VectorSize, }, PartialArray, - Array { - base: Handle, - size: ArraySize, - stride: u32, - }, - Struct(Handle), + Type(Handle), } -impl ConstructorType { - const fn to_type_resolution(&self) -> Option { - Some(match *self { - ConstructorType::Scalar { kind, width } => { - TypeResolution::Value(TypeInner::Scalar { kind, width }) +impl ConcreteConstructorHandle { + fn borrow<'a>(&self, module: &'a crate::Module) -> ConcreteConstructor<'a> { + match *self { + Self::PartialVector { size } => ConcreteConstructor::PartialVector { size }, + Self::PartialMatrix { columns, rows } => { + ConcreteConstructor::PartialMatrix { columns, rows } } - ConstructorType::Vector { size, kind, width } => { - TypeResolution::Value(TypeInner::Vector { size, kind, width }) - } - ConstructorType::Matrix { - columns, - rows, - width, - } => TypeResolution::Value(TypeInner::Matrix { - columns, - rows, - width, - }), - ConstructorType::Array { base, size, stride } => { - TypeResolution::Value(TypeInner::Array { base, size, stride }) - } - ConstructorType::Struct(handle) => TypeResolution::Handle(handle), - _ => return None, - }) + Self::PartialArray => ConcreteConstructor::PartialArray, + Self::Type(handle) => ConcreteConstructor::Type(handle, &module.types[handle].inner), + } } } -impl ConstructorType { - fn to_error_string(&self, types: &UniqueArena, constants: &Arena) -> String { +enum ConcreteConstructor<'a> { + PartialVector { + size: crate::VectorSize, + }, + PartialMatrix { + columns: crate::VectorSize, + rows: crate::VectorSize, + }, + PartialArray, + Type(Handle, &'a crate::TypeInner), +} + +impl ConcreteConstructorHandle { + fn to_error_string(&self, ctx: ExpressionContext) -> String { match *self { - ConstructorType::Scalar { kind, width } => kind.to_wgsl(width), - ConstructorType::PartialVector { size } => { + Self::PartialVector { size } => { format!("vec{}", size as u32,) } - ConstructorType::Vector { size, kind, width } => { - format!("vec{}<{}>", size as u32, kind.to_wgsl(width)) - } - ConstructorType::PartialMatrix { columns, rows } => { + Self::PartialMatrix { columns, rows } => { format!("mat{}x{}", columns as u32, rows as u32,) } - ConstructorType::Matrix { - columns, - rows, - width, - } => { - format!( - "mat{}x{}<{}>", - columns as u32, - rows as u32, - ScalarKind::Float.to_wgsl(width) - ) - } - ConstructorType::PartialArray => "array".to_string(), - ConstructorType::Array { base, size, .. } => { - format!( - "array<{}, {}>", - types[base].name.as_deref().unwrap_or("?"), - match size { - ArraySize::Constant(size) => { - constants[size] - .to_array_length() - .map(|len| len.to_string()) - .unwrap_or_else(|| "?".to_string()) - } - _ => unreachable!(), - } - ) - } - ConstructorType::Struct(handle) => types[handle] - .name - .clone() - .unwrap_or_else(|| "?".to_string()), + Self::PartialArray => "array".to_string(), + Self::Type(ty) => ctx.format_type(ty), } } } -fn parse_constructor_type<'a>( - parser: &mut Parser, - lexer: &mut Lexer<'a>, - word: &'a str, - type_arena: &mut UniqueArena, - const_arena: &mut Arena, -) -> Result, Error<'a>> { - if let Some((kind, width)) = super::conv::get_scalar_type(word) { - return Ok(Some(ConstructorType::Scalar { kind, width })); - } +enum ComponentsHandle<'a> { + None, + One { + component: Handle, + span: Span, + ty: &'a TypeResolution, + }, + Many { + components: Vec>, + spans: Vec, + first_component_ty: &'a TypeResolution, + }, +} - let partial = match word { - "vec2" => ConstructorType::PartialVector { - size: VectorSize::Bi, - }, - "vec3" => ConstructorType::PartialVector { - size: VectorSize::Tri, - }, - "vec4" => ConstructorType::PartialVector { - size: VectorSize::Quad, - }, - "mat2x2" => ConstructorType::PartialMatrix { - columns: VectorSize::Bi, - rows: VectorSize::Bi, - }, - "mat2x3" => ConstructorType::PartialMatrix { - columns: VectorSize::Bi, - rows: VectorSize::Tri, - }, - "mat2x4" => ConstructorType::PartialMatrix { - columns: VectorSize::Bi, - rows: VectorSize::Quad, - }, - "mat3x2" => ConstructorType::PartialMatrix { - columns: VectorSize::Tri, - rows: VectorSize::Bi, - }, - "mat3x3" => ConstructorType::PartialMatrix { - columns: VectorSize::Tri, - rows: VectorSize::Tri, - }, - "mat3x4" => ConstructorType::PartialMatrix { - columns: VectorSize::Tri, - rows: VectorSize::Quad, - }, - "mat4x2" => ConstructorType::PartialMatrix { - columns: VectorSize::Quad, - rows: VectorSize::Bi, - }, - "mat4x3" => ConstructorType::PartialMatrix { - columns: VectorSize::Quad, - rows: VectorSize::Tri, - }, - "mat4x4" => ConstructorType::PartialMatrix { - columns: VectorSize::Quad, - rows: VectorSize::Quad, - }, - "array" => ConstructorType::PartialArray, - _ => return Ok(None), - }; - - // parse component type if present - match (lexer.peek().0, partial) { - (Token::Paren('<'), ConstructorType::PartialVector { size }) => { - let (kind, width) = lexer.next_scalar_generic()?; - Ok(Some(ConstructorType::Vector { size, kind, width })) +impl<'a> ComponentsHandle<'a> { + fn borrow(self, module: &'a crate::Module) -> Components<'a> { + match self { + Self::None => Components::None, + Self::One { + component, + span, + ty, + } => Components::One { + component, + span, + ty_inner: ty.inner_with(&module.types), + }, + Self::Many { + components, + spans, + first_component_ty, + } => Components::Many { + components, + spans, + first_component_ty_inner: first_component_ty.inner_with(&module.types), + }, } - (Token::Paren('<'), ConstructorType::PartialMatrix { columns, rows }) => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - match kind { - ScalarKind::Float => Ok(Some(ConstructorType::Matrix { + } +} + +enum Components<'a> { + None, + One { + component: Handle, + span: Span, + ty_inner: &'a crate::TypeInner, + }, + Many { + components: Vec>, + spans: Vec, + first_component_ty_inner: &'a crate::TypeInner, + }, +} + +impl Components<'_> { + fn into_components_vec(self) -> Vec> { + match self { + Self::None => vec![], + Self::One { component, .. } => vec![component], + Self::Many { components, .. } => components, + } + } +} + +impl<'source, 'temp> Lowerer<'source, 'temp> { + /// Generate Naga IR for a type constructor expression. + /// + /// The `constructor` value represents the head of the constructor + /// expression, which is at least a hint of which type is being built; if + /// it's one of the `Partial` variants, we need to consider the argument + /// types as well. + /// + /// This is used for [`Construct`] expressions, but also for [`Call`] + /// expressions, once we've determined that the "callable" (in WGSL spec + /// terms) is actually a type. + /// + /// [`Construct`]: ast::Expression::Construct + /// [`Call`]: ast::Expression::Call + pub(super) fn construct( + &mut self, + span: Span, + constructor: &ast::ConstructorType<'source>, + ty_span: Span, + components: &[Handle>], + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let constructor_h = self.constructor(constructor, ctx.as_output())?; + + let components_h = match *components { + [] => ComponentsHandle::None, + [component] => { + let span = ctx.ast_expressions.get_span(component); + let component = self.expression(component, ctx.reborrow())?; + ctx.grow_types(component)?; + let ty = &ctx.typifier[component]; + + ComponentsHandle::One { + component, + span, + ty, + } + } + [component, ref rest @ ..] => { + let span = ctx.ast_expressions.get_span(component); + let component = self.expression(component, ctx.reborrow())?; + + let components = std::iter::once(Ok(component)) + .chain( + rest.iter() + .map(|&component| self.expression(component, ctx.reborrow())), + ) + .collect::>()?; + let spans = std::iter::once(span) + .chain( + rest.iter() + .map(|&component| ctx.ast_expressions.get_span(component)), + ) + .collect(); + + ctx.grow_types(component)?; + let ty = &ctx.typifier[component]; + + ComponentsHandle::Many { + components, + spans, + first_component_ty: ty, + } + } + }; + + let (components, constructor) = ( + components_h.borrow(ctx.module), + constructor_h.borrow(ctx.module), + ); + let expr = match (components, constructor) { + // Empty constructor + (Components::None, dst_ty) => { + let ty = match dst_ty { + ConcreteConstructor::Type(ty, _) => ty, + _ => return Err(Error::TypeNotInferrable(ty_span)), + }; + + return match ctx.create_zero_value_constant(ty) { + Some(constant) => { + Ok(ctx.interrupt_emitter(crate::Expression::Constant(constant), span)) + } + None => Err(Error::TypeNotConstructible(ty_span)), + }; + } + + // Scalar constructor & conversion (scalar -> scalar) + ( + Components::One { + component, + ty_inner: &crate::TypeInner::Scalar { .. }, + .. + }, + ConcreteConstructor::Type(_, &crate::TypeInner::Scalar { kind, width }), + ) => crate::Expression::As { + expr: component, + kind, + convert: Some(width), + }, + + // Vector conversion (vector -> vector) + ( + Components::One { + component, + ty_inner: &crate::TypeInner::Vector { size: src_size, .. }, + .. + }, + ConcreteConstructor::Type( + _, + &crate::TypeInner::Vector { + size: dst_size, + kind: dst_kind, + width: dst_width, + }, + ), + ) if dst_size == src_size => crate::Expression::As { + expr: component, + kind: dst_kind, + convert: Some(dst_width), + }, + + // Vector conversion (vector -> vector) - partial + ( + Components::One { + component, + ty_inner: + &crate::TypeInner::Vector { + size: src_size, + kind: src_kind, + .. + }, + .. + }, + ConcreteConstructor::PartialVector { size: dst_size }, + ) if dst_size == src_size => crate::Expression::As { + expr: component, + kind: src_kind, + convert: None, + }, + + // Matrix conversion (matrix -> matrix) + ( + Components::One { + component, + ty_inner: + &crate::TypeInner::Matrix { + columns: src_columns, + rows: src_rows, + .. + }, + .. + }, + ConcreteConstructor::Type( + _, + &crate::TypeInner::Matrix { + columns: dst_columns, + rows: dst_rows, + width: dst_width, + }, + ), + ) if dst_columns == src_columns && dst_rows == src_rows => crate::Expression::As { + expr: component, + kind: crate::ScalarKind::Float, + convert: Some(dst_width), + }, + + // Matrix conversion (matrix -> matrix) - partial + ( + Components::One { + component, + ty_inner: + &crate::TypeInner::Matrix { + columns: src_columns, + rows: src_rows, + .. + }, + .. + }, + ConcreteConstructor::PartialMatrix { + columns: dst_columns, + rows: dst_rows, + }, + ) if dst_columns == src_columns && dst_rows == src_rows => crate::Expression::As { + expr: component, + kind: crate::ScalarKind::Float, + convert: None, + }, + + // Vector constructor (splat) - infer type + ( + Components::One { + component, + ty_inner: &crate::TypeInner::Scalar { .. }, + .. + }, + ConcreteConstructor::PartialVector { size }, + ) => crate::Expression::Splat { + size, + value: component, + }, + + // Vector constructor (splat) + ( + Components::One { + component, + ty_inner: + &crate::TypeInner::Scalar { + kind: src_kind, + width: src_width, + .. + }, + .. + }, + ConcreteConstructor::Type( + _, + &crate::TypeInner::Vector { + size, + kind: dst_kind, + width: dst_width, + }, + ), + ) if dst_kind == src_kind || dst_width == src_width => crate::Expression::Splat { + size, + value: component, + }, + + // Vector constructor (by elements) + ( + Components::Many { + components, + first_component_ty_inner: + &crate::TypeInner::Scalar { kind, width } + | &crate::TypeInner::Vector { kind, width, .. }, + .. + }, + ConcreteConstructor::PartialVector { size }, + ) + | ( + Components::Many { + components, + first_component_ty_inner: + &crate::TypeInner::Scalar { .. } | &crate::TypeInner::Vector { .. }, + .. + }, + ConcreteConstructor::Type(_, &crate::TypeInner::Vector { size, width, kind }), + ) => { + let inner = crate::TypeInner::Vector { size, kind, width }; + let ty = ctx.ensure_type_exists(inner); + crate::Expression::Compose { ty, components } + } + + // Matrix constructor (by elements) + ( + Components::Many { + components, + first_component_ty_inner: &crate::TypeInner::Scalar { width, .. }, + .. + }, + ConcreteConstructor::PartialMatrix { columns, rows }, + ) + | ( + Components::Many { + components, + first_component_ty_inner: &crate::TypeInner::Scalar { .. }, + .. + }, + ConcreteConstructor::Type( + _, + &crate::TypeInner::Matrix { + columns, + rows, + width, + }, + ), + ) => { + let vec_ty = ctx.ensure_type_exists(crate::TypeInner::Vector { + width, + kind: crate::ScalarKind::Float, + size: rows, + }); + + let components = components + .chunks(rows as usize) + .map(|vec_components| { + ctx.naga_expressions.append( + crate::Expression::Compose { + ty: vec_ty, + components: Vec::from(vec_components), + }, + Default::default(), + ) + }) + .collect(); + + let ty = ctx.ensure_type_exists(crate::TypeInner::Matrix { columns, rows, width, - })), - _ => Err(Error::BadMatrixScalarKind(span, kind, width)), + }); + crate::Expression::Compose { ty, components } } - } - (Token::Paren('<'), ConstructorType::PartialArray) => { - lexer.expect_generic_paren('<')?; - let base = parser.parse_type_decl(lexer, None, type_arena, const_arena)?; - let size = if lexer.skip(Token::Separator(',')) { - let const_handle = parser.parse_const_expression(lexer, type_arena, const_arena)?; - ArraySize::Constant(const_handle) - } else { - ArraySize::Dynamic - }; - lexer.expect_generic_paren('>')?; - let stride = { - parser.layouter.update(type_arena, const_arena).unwrap(); - parser.layouter[base].to_stride() - }; + // Matrix constructor (by columns) + ( + Components::Many { + components, + first_component_ty_inner: &crate::TypeInner::Vector { width, .. }, + .. + }, + ConcreteConstructor::PartialMatrix { columns, rows }, + ) + | ( + Components::Many { + components, + first_component_ty_inner: &crate::TypeInner::Vector { .. }, + .. + }, + ConcreteConstructor::Type( + _, + &crate::TypeInner::Matrix { + columns, + rows, + width, + }, + ), + ) => { + let ty = ctx.ensure_type_exists(crate::TypeInner::Matrix { + columns, + rows, + width, + }); + crate::Expression::Compose { ty, components } + } - Ok(Some(ConstructorType::Array { base, size, stride })) - } - (_, partial) => Ok(Some(partial)), + // Array constructor - infer type + (components, ConcreteConstructor::PartialArray) => { + let components = components.into_components_vec(); + + let base = ctx.register_type(components[0])?; + + let size = crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(components.len() as _), + }, + }; + + let inner = crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant( + ctx.module.constants.fetch_or_append(size, Span::UNDEFINED), + ), + stride: { + self.layouter + .update(&ctx.module.types, &ctx.module.constants) + .unwrap(); + self.layouter[base].to_stride() + }, + }; + let ty = ctx.ensure_type_exists(inner); + + crate::Expression::Compose { ty, components } + } + + // Array constructor + (components, ConcreteConstructor::Type(ty, &crate::TypeInner::Array { .. })) => { + let components = components.into_components_vec(); + crate::Expression::Compose { ty, components } + } + + // Struct constructor + (components, ConcreteConstructor::Type(ty, &crate::TypeInner::Struct { .. })) => { + crate::Expression::Compose { + ty, + components: components.into_components_vec(), + } + } + + // ERRORS + + // Bad conversion (type cast) + (Components::One { span, ty_inner, .. }, _) => { + let from_type = ctx.format_typeinner(ty_inner); + return Err(Error::BadTypeCast { + span, + from_type, + to_type: constructor_h.to_error_string(ctx.reborrow()), + }); + } + + // Too many parameters for scalar constructor + ( + Components::Many { spans, .. }, + ConcreteConstructor::Type(_, &crate::TypeInner::Scalar { .. }), + ) => { + let span = spans[1].until(spans.last().unwrap()); + return Err(Error::UnexpectedComponents(span)); + } + + // Parameters are of the wrong type for vector or matrix constructor + ( + Components::Many { spans, .. }, + ConcreteConstructor::Type( + _, + &crate::TypeInner::Vector { .. } | &crate::TypeInner::Matrix { .. }, + ) + | ConcreteConstructor::PartialVector { .. } + | ConcreteConstructor::PartialMatrix { .. }, + ) => { + return Err(Error::InvalidConstructorComponentType(spans[0], 0)); + } + + // Other types can't be constructed + _ => return Err(Error::TypeNotConstructible(ty_span)), + }; + + let expr = ctx.naga_expressions.append(expr, span); + Ok(expr) } -} -/// Expects [`Rule::PrimaryExpr`] on top of rule stack; if returning Some(_), pops it. -pub(super) fn parse_construction<'a>( - parser: &mut Parser, - lexer: &mut Lexer<'a>, - type_name: &'a str, - type_span: Span, - mut ctx: ExpressionContext<'a, '_, '_>, -) -> Result>, Error<'a>> { - assert_eq!( - parser.rules.last().map(|&(ref rule, _)| rule.clone()), - Some(Rule::PrimaryExpr) - ); - let dst_ty = match parser.lookup_type.get(type_name) { - Some(&handle) => ConstructorType::Struct(handle), - None => match parse_constructor_type(parser, lexer, type_name, ctx.types, ctx.constants)? { - Some(inner) => inner, - None => { - match parser.parse_type_decl_impl( - lexer, - super::TypeAttributes::default(), - type_name, - ctx.types, - ctx.constants, - )? { - Some(_) => { - return Err(Error::TypeNotConstructible(type_span)); + /// Build a Naga IR [`ConstantInner`] given a WGSL construction expression. + /// + /// Given `constructor`, representing the head of a WGSL [`type constructor + /// expression`], and a slice of [`ast::Expression`] handles representing + /// the constructor's arguments, build a Naga [`ConstantInner`] value + /// representing the given value. + /// + /// If `constructor` is for a composite type, this may entail adding new + /// [`Type`]s and [`Constant`]s to [`ctx.module`], if it doesn't already + /// have what we need. + /// + /// If the arguments cannot be evaluated at compile time, return an error. + /// + /// [`ConstantInner`]: crate::ConstantInner + /// [`type constructor expression`]: https://gpuweb.github.io/gpuweb/wgsl/#type-constructor-expr + /// [`Function::expressions`]: ast::Function::expressions + /// [`TranslationUnit::global_expressions`]: ast::TranslationUnit::global_expressions + /// [`Type`]: crate::Type + /// [`Constant`]: crate::Constant + /// [`ctx.module`]: OutputContext::module + pub(super) fn const_construct( + &mut self, + span: Span, + constructor: &ast::ConstructorType<'source>, + components: &[Handle>], + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result> { + // TODO: Support zero values, splatting and inference. + + let constructor = self.constructor(constructor, ctx.reborrow())?; + + let c = match constructor { + ConcreteConstructorHandle::Type(ty) => { + let components = components + .iter() + .map(|&expr| self.constant(expr, ctx.reborrow())) + .collect::>()?; + + crate::ConstantInner::Composite { ty, components } + } + _ => return Err(Error::ConstExprUnsupported(span)), + }; + Ok(c) + } + + /// Build a Naga IR [`Type`] for `constructor` if there is enough + /// information to do so. + /// + /// For `Partial` variants of [`ast::ConstructorType`], we don't know the + /// component type, so in that case we return the appropriate `Partial` + /// variant of [`ConcreteConstructorHandle`]. + /// + /// But for the other `ConstructorType` variants, we have everything we need + /// to know to actually produce a Naga IR type. In this case we add to/find + /// in [`ctx.module`] a suitable Naga `Type` and return a + /// [`ConcreteConstructorHandle::Type`] value holding its handle. + /// + /// Note that constructing an [`Array`] type may require inserting + /// [`Constant`]s as well as `Type`s into `ctx.module`, to represent the + /// array's length. + /// + /// [`Type`]: crate::Type + /// [`ctx.module`]: OutputContext::module + /// [`Array`]: crate::TypeInner::Array + /// [`Constant`]: crate::Constant + fn constructor<'out>( + &mut self, + constructor: &ast::ConstructorType<'source>, + mut ctx: OutputContext<'source, '_, 'out>, + ) -> Result> { + let c = match *constructor { + ast::ConstructorType::Scalar { width, kind } => { + let ty = ctx.ensure_type_exists(crate::TypeInner::Scalar { width, kind }); + ConcreteConstructorHandle::Type(ty) + } + ast::ConstructorType::PartialVector { size } => { + ConcreteConstructorHandle::PartialVector { size } + } + ast::ConstructorType::Vector { size, kind, width } => { + let ty = ctx.ensure_type_exists(crate::TypeInner::Vector { size, kind, width }); + ConcreteConstructorHandle::Type(ty) + } + ast::ConstructorType::PartialMatrix { rows, columns } => { + ConcreteConstructorHandle::PartialMatrix { rows, columns } + } + ast::ConstructorType::Matrix { + rows, + columns, + width, + } => { + let ty = ctx.ensure_type_exists(crate::TypeInner::Matrix { + columns, + rows, + width, + }); + ConcreteConstructorHandle::Type(ty) + } + ast::ConstructorType::PartialArray => ConcreteConstructorHandle::PartialArray, + ast::ConstructorType::Array { base, size } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + let size = match size { + ast::ArraySize::Constant(expr) => { + crate::ArraySize::Constant(self.constant(expr, ctx.reborrow())?) } - None => return Ok(None), - } + ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, + }; + + self.layouter + .update(&ctx.module.types, &ctx.module.constants) + .unwrap(); + let ty = ctx.ensure_type_exists(crate::TypeInner::Array { + base, + size, + stride: self.layouter[base].to_stride(), + }); + ConcreteConstructorHandle::Type(ty) } - }, - }; + ast::ConstructorType::Type(ty) => ConcreteConstructorHandle::Type(ty), + }; - lexer.open_arguments()?; - - let mut components = Vec::new(); - let mut spans = Vec::new(); - - if lexer.peek().0 == Token::Paren(')') { - let _ = lexer.next(); - } else { - while components.is_empty() || lexer.next_argument()? { - let (component, span) = lexer - .capture_span(|lexer| parser.parse_general_expression(lexer, ctx.reborrow()))?; - components.push(component); - spans.push(span); - } + Ok(c) } - - enum Components<'a> { - None, - One { - component: Handle, - span: Span, - ty: &'a TypeInner, - }, - Many { - components: Vec>, - spans: Vec, - first_component_ty: &'a TypeInner, - }, - } - - impl<'a> Components<'a> { - fn into_components_vec(self) -> Vec> { - match self { - Components::None => vec![], - Components::One { component, .. } => vec![component], - Components::Many { components, .. } => components, - } - } - } - - let components = match *components.as_slice() { - [] => Components::None, - [component] => { - ctx.resolve_type(component)?; - Components::One { - component, - span: spans[0].clone(), - ty: ctx.typifier.get(component, ctx.types), - } - } - [component, ..] => { - ctx.resolve_type(component)?; - Components::Many { - components, - spans, - first_component_ty: ctx.typifier.get(component, ctx.types), - } - } - }; - - let expr = match (components, dst_ty) { - // Empty constructor - (Components::None, dst_ty) => { - let ty = match dst_ty.to_type_resolution() { - Some(TypeResolution::Handle(handle)) => handle, - Some(TypeResolution::Value(inner)) => ctx - .types - .insert(Type { name: None, inner }, Default::default()), - None => return Err(Error::TypeNotInferrable(type_span)), - }; - - return match ctx.create_zero_value_constant(ty) { - Some(constant) => { - let span = parser.pop_rule_span(lexer); - Ok(Some(ctx.interrupt_emitter( - Expression::Constant(constant), - span.into(), - ))) - } - None => Err(Error::TypeNotConstructible(type_span)), - }; - } - - // Scalar constructor & conversion (scalar -> scalar) - ( - Components::One { - component, - ty: &TypeInner::Scalar { .. }, - .. - }, - ConstructorType::Scalar { kind, width }, - ) => Expression::As { - expr: component, - kind, - convert: Some(width), - }, - - // Vector conversion (vector -> vector) - ( - Components::One { - component, - ty: &TypeInner::Vector { size: src_size, .. }, - .. - }, - ConstructorType::Vector { - size: dst_size, - kind: dst_kind, - width: dst_width, - }, - ) if dst_size == src_size => Expression::As { - expr: component, - kind: dst_kind, - convert: Some(dst_width), - }, - - // Vector conversion (vector -> vector) - partial - ( - Components::One { - component, - ty: - &TypeInner::Vector { - size: src_size, - kind: src_kind, - .. - }, - .. - }, - ConstructorType::PartialVector { size: dst_size }, - ) if dst_size == src_size => Expression::As { - expr: component, - kind: src_kind, - convert: None, - }, - - // Matrix conversion (matrix -> matrix) - ( - Components::One { - component, - ty: - &TypeInner::Matrix { - columns: src_columns, - rows: src_rows, - .. - }, - .. - }, - ConstructorType::Matrix { - columns: dst_columns, - rows: dst_rows, - width: dst_width, - }, - ) if dst_columns == src_columns && dst_rows == src_rows => Expression::As { - expr: component, - kind: ScalarKind::Float, - convert: Some(dst_width), - }, - - // Matrix conversion (matrix -> matrix) - partial - ( - Components::One { - component, - ty: - &TypeInner::Matrix { - columns: src_columns, - rows: src_rows, - .. - }, - .. - }, - ConstructorType::PartialMatrix { - columns: dst_columns, - rows: dst_rows, - }, - ) if dst_columns == src_columns && dst_rows == src_rows => Expression::As { - expr: component, - kind: ScalarKind::Float, - convert: None, - }, - - // Vector constructor (splat) - infer type - ( - Components::One { - component, - ty: &TypeInner::Scalar { .. }, - .. - }, - ConstructorType::PartialVector { size }, - ) => Expression::Splat { - size, - value: component, - }, - - // Vector constructor (splat) - ( - Components::One { - component, - ty: - &TypeInner::Scalar { - kind: src_kind, - width: src_width, - .. - }, - .. - }, - ConstructorType::Vector { - size, - kind: dst_kind, - width: dst_width, - }, - ) if dst_kind == src_kind || dst_width == src_width => Expression::Splat { - size, - value: component, - }, - - // Vector constructor (by elements) - ( - Components::Many { - components, - first_component_ty: - &TypeInner::Scalar { kind, width } | &TypeInner::Vector { kind, width, .. }, - .. - }, - ConstructorType::PartialVector { size }, - ) - | ( - Components::Many { - components, - first_component_ty: &TypeInner::Scalar { .. } | &TypeInner::Vector { .. }, - .. - }, - ConstructorType::Vector { size, width, kind }, - ) => { - let ty = ctx.types.insert( - Type { - name: None, - inner: TypeInner::Vector { size, kind, width }, - }, - Default::default(), - ); - Expression::Compose { ty, components } - } - - // Matrix constructor (by elements) - ( - Components::Many { - components, - first_component_ty: &TypeInner::Scalar { width, .. }, - .. - }, - ConstructorType::PartialMatrix { columns, rows }, - ) - | ( - Components::Many { - components, - first_component_ty: &TypeInner::Scalar { .. }, - .. - }, - ConstructorType::Matrix { - columns, - rows, - width, - }, - ) => { - let vec_ty = ctx.types.insert( - Type { - name: None, - inner: TypeInner::Vector { - width, - kind: ScalarKind::Float, - size: rows, - }, - }, - Default::default(), - ); - - let components = components - .chunks(rows as usize) - .map(|vec_components| { - ctx.expressions.append( - Expression::Compose { - ty: vec_ty, - components: Vec::from(vec_components), - }, - Default::default(), - ) - }) - .collect(); - - let ty = ctx.types.insert( - Type { - name: None, - inner: TypeInner::Matrix { - columns, - rows, - width, - }, - }, - Default::default(), - ); - Expression::Compose { ty, components } - } - - // Matrix constructor (by columns) - ( - Components::Many { - components, - first_component_ty: &TypeInner::Vector { width, .. }, - .. - }, - ConstructorType::PartialMatrix { columns, rows }, - ) - | ( - Components::Many { - components, - first_component_ty: &TypeInner::Vector { .. }, - .. - }, - ConstructorType::Matrix { - columns, - rows, - width, - }, - ) => { - let ty = ctx.types.insert( - Type { - name: None, - inner: TypeInner::Matrix { - columns, - rows, - width, - }, - }, - Default::default(), - ); - Expression::Compose { ty, components } - } - - // Array constructor - infer type - (components, ConstructorType::PartialArray) => { - let components = components.into_components_vec(); - - let base = match ctx.typifier[components[0]].clone() { - TypeResolution::Handle(ty) => ty, - TypeResolution::Value(inner) => ctx - .types - .insert(Type { name: None, inner }, Default::default()), - }; - - let size = Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Uint(components.len() as u64), - }, - }; - - let inner = TypeInner::Array { - base, - size: ArraySize::Constant(ctx.constants.append(size, Default::default())), - stride: { - parser.layouter.update(ctx.types, ctx.constants).unwrap(); - parser.layouter[base].to_stride() - }, - }; - - let ty = ctx - .types - .insert(Type { name: None, inner }, Default::default()); - - Expression::Compose { ty, components } - } - - // Array constructor - (components, ConstructorType::Array { base, size, stride }) => { - let components = components.into_components_vec(); - let inner = TypeInner::Array { base, size, stride }; - let ty = ctx - .types - .insert(Type { name: None, inner }, Default::default()); - Expression::Compose { ty, components } - } - - // Struct constructor - (components, ConstructorType::Struct(ty)) => Expression::Compose { - ty, - components: components.into_components_vec(), - }, - - // ERRORS - - // Bad conversion (type cast) - ( - Components::One { - span, ty: src_ty, .. - }, - dst_ty, - ) => { - return Err(Error::BadTypeCast { - span, - from_type: src_ty.to_wgsl(ctx.types, ctx.constants), - to_type: dst_ty.to_error_string(ctx.types, ctx.constants), - }); - } - - // Too many parameters for scalar constructor - (Components::Many { spans, .. }, ConstructorType::Scalar { .. }) => { - return Err(Error::UnexpectedComponents(Span { - start: spans[1].start, - end: spans.last().unwrap().end, - })); - } - - // Parameters are of the wrong type for vector or matrix constructor - ( - Components::Many { spans, .. }, - ConstructorType::Vector { .. } - | ConstructorType::Matrix { .. } - | ConstructorType::PartialVector { .. } - | ConstructorType::PartialMatrix { .. }, - ) => { - return Err(Error::InvalidConstructorComponentType(spans[0].clone(), 0)); - } - }; - - let span = NagaSpan::from(parser.pop_rule_span(lexer)); - Ok(Some(ctx.expressions.append(expr, span))) } diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index be3c2933f..25acdcb21 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -1,4 +1,5 @@ -use super::{Error, Span}; +use super::Error; +use crate::Span; pub fn map_address_space(word: &str, span: Span) -> Result> { match word { diff --git a/src/front/wgsl/index.rs b/src/front/wgsl/index.rs new file mode 100644 index 000000000..a36273572 --- /dev/null +++ b/src/front/wgsl/index.rs @@ -0,0 +1,192 @@ +use super::{ast, Error}; +use crate::{FastHashMap, Handle, Span}; + +/// A `GlobalDecl` list in which each definition occurs before all its uses. +pub struct Index<'a> { + dependency_order: Vec>>, +} + +impl<'a> Index<'a> { + /// Generate an `Index` for the given translation unit. + /// + /// Perform a topological sort on `tu`'s global declarations, placing + /// referents before the definitions that refer to them. + /// + /// Return an error if the graph of references between declarations contains + /// any cycles. + pub fn generate(tu: &ast::TranslationUnit<'a>) -> Result> { + // Produce a map from global definitions' names to their `Handle`s. + // While doing so, reject conflicting definitions. + let mut globals = FastHashMap::with_capacity_and_hasher(tu.decls.len(), Default::default()); + for (handle, decl) in tu.decls.iter() { + let ident = decl_ident(decl); + let name = ident.name; + if let Some(old) = globals.insert(name, handle) { + return Err(Error::Redefinition { + previous: decl_ident(&tu.decls[old]).span, + current: ident.span, + }); + } + } + + let len = tu.decls.len(); + let solver = DependencySolver { + globals: &globals, + module: tu, + visited: vec![false; len], + temp_visited: vec![false; len], + path: Vec::new(), + out: Vec::with_capacity(len), + }; + let dependency_order = solver.solve()?; + + Ok(Self { dependency_order }) + } + + /// Iterate over `GlobalDecl`s, visiting each definition before all its uses. + /// + /// Produce handles for all of the `GlobalDecl`s of the `TranslationUnit` + /// passed to `Index::generate`, ordered so that a given declaration is + /// produced before any other declaration that uses it. + pub fn visit_ordered(&self) -> impl Iterator>> + '_ { + self.dependency_order.iter().copied() + } +} + +/// An edge from a reference to its referent in the current depth-first +/// traversal. +/// +/// This is like `ast::Dependency`, except that we've determined which +/// `GlobalDecl` it refers to. +struct ResolvedDependency<'a> { + /// The referent of some identifier used in the current declaration. + decl: Handle>, + + /// Where that use occurs within the current declaration. + usage: Span, +} + +/// Local state for ordering a `TranslationUnit`'s module-scope declarations. +/// +/// Values of this type are used temporarily by `Index::generate` +/// to perform a depth-first sort on the declarations. +/// Technically, what we want is a topological sort, but a depth-first sort +/// has one key benefit - it's much more efficient in storing +/// the path of each node for error generation. +struct DependencySolver<'source, 'temp> { + /// A map from module-scope definitions' names to their handles. + globals: &'temp FastHashMap<&'source str, Handle>>, + + /// The translation unit whose declarations we're ordering. + module: &'temp ast::TranslationUnit<'source>, + + /// For each handle, whether we have pushed it onto `out` yet. + visited: Vec, + + /// For each handle, whether it is an predecessor in the current depth-first + /// traversal. This is used to detect cycles in the reference graph. + temp_visited: Vec, + + /// The current path in our depth-first traversal. Used for generating + /// error messages for non-trivial reference cycles. + path: Vec>, + + /// The list of declaration handles, with declarations before uses. + out: Vec>>, +} + +impl<'a> DependencySolver<'a, '_> { + /// Produce the sorted list of declaration handles, and check for cycles. + fn solve(mut self) -> Result>>, Error<'a>> { + for (id, _) in self.module.decls.iter() { + if self.visited[id.index()] { + continue; + } + + self.dfs(id)?; + } + + Ok(self.out) + } + + /// Ensure that all declarations used by `id` have been added to the + /// ordering, and then append `id` itself. + fn dfs(&mut self, id: Handle>) -> Result<(), Error<'a>> { + let decl = &self.module.decls[id]; + let id_usize = id.index(); + + self.temp_visited[id_usize] = true; + for dep in decl.dependencies.iter() { + if let Some(&dep_id) = self.globals.get(dep.ident) { + self.path.push(ResolvedDependency { + decl: dep_id, + usage: dep.usage, + }); + let dep_id_usize = dep_id.index(); + + if self.temp_visited[dep_id_usize] { + // Found a cycle. + return if dep_id == id { + // A declaration refers to itself directly. + Err(Error::RecursiveDeclaration { + ident: decl_ident(decl).span, + usage: dep.usage, + }) + } else { + // A declaration refers to itself indirectly, through + // one or more other definitions. Report the entire path + // of references. + let start_at = self + .path + .iter() + .rev() + .enumerate() + .find_map(|(i, dep)| (dep.decl == dep_id).then_some(i)) + .unwrap_or(0); + + Err(Error::CyclicDeclaration { + ident: decl_ident(&self.module.decls[dep_id]).span, + path: self.path[start_at..] + .iter() + .map(|curr_dep| { + let curr_id = curr_dep.decl; + let curr_decl = &self.module.decls[curr_id]; + + (decl_ident(curr_decl).span, curr_dep.usage) + }) + .collect(), + }) + }; + } else if !self.visited[dep_id_usize] { + self.dfs(dep_id)?; + } + + // Remove this edge from the current path. + self.path.pop(); + } + + // Ignore unresolved identifiers; they may be predeclared objects. + } + + // Remove this node from the current path. + self.temp_visited[id_usize] = false; + + // Now everything this declaration uses has been visited, and is already + // present in `out`. That means we we can append this one to the + // ordering, and mark it as visited. + self.out.push(id); + self.visited[id_usize] = true; + + Ok(()) + } +} + +const fn decl_ident<'a>(decl: &ast::GlobalDecl<'a>) -> ast::Ident<'a> { + match decl.kind { + ast::GlobalDeclKind::Fn(ref f) => f.name, + ast::GlobalDeclKind::Var(ref v) => v.name, + ast::GlobalDeclKind::Const(ref c) => c.name, + ast::GlobalDeclKind::Struct(ref s) => s.name, + ast::GlobalDeclKind::Type(ref t) => t.name, + } +} diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs index 35fe45089..d6975bf98 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/lexer.rs @@ -1,10 +1,26 @@ -use super::{conv, number::consume_number, Error, ExpectedToken, Span, Token, TokenSpan}; +use super::{conv, number::consume_number, Error, ExpectedToken, Token, TokenSpan}; +use crate::Span; fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { let pos = input.find(|c| !what(c)).unwrap_or(input.len()); input.split_at(pos) } +/// Return the token at the start of `input`. +/// +/// If `generic` is `false`, then the bit shift operators `>>` or `<<` +/// are valid lookahead tokens for the current parser state (see [§3.1 +/// Parsing] in the WGSL specification). In other words: +/// +/// - If `generic` is `true`, then we are expecting an angle bracket +/// around a generic type parameter, like the `<` and `>` in +/// `vec3`, so interpret `<` and `>` as `Token::Paren` tokens, +/// even if they're part of `<<` or `>>` sequences. +/// +/// - Otherwise, interpret `<<` and `>>` as shift operators: +/// `Token::LogicalOperation` tokens. +/// +/// [§3.1 Parsing]: https://gpuweb.github.io/gpuweb/wgsl/#parsing fn consume_token(input: &str, generic: bool) -> (Token<'_>, &str) { let mut chars = input.chars(); let cur = match chars.next() { @@ -176,10 +192,6 @@ impl<'a> Lexer<'a> { } } - pub(super) const fn _leftover_span(&self) -> Span { - self.source.len() - self.input.len()..self.source.len() - } - /// Calls the function with a lexer and returns the result of the function as well as the span for everything the function parsed /// /// # Examples @@ -196,7 +208,7 @@ impl<'a> Lexer<'a> { let start = self.current_byte_offset(); let res = inner(self)?; let end = self.current_byte_offset(); - Ok((res, start..end)) + Ok((res, Span::from(start..end))) } pub(super) fn start_byte_offset(&mut self) -> usize { @@ -211,10 +223,6 @@ impl<'a> Lexer<'a> { } } - pub(super) const fn end_byte_offset(&self) -> usize { - self.last_end_offset - } - fn peek_token_and_rest(&mut self) -> (TokenSpan<'a>, &'a str) { let mut cloned = self.clone(); let token = cloned.next(); @@ -226,49 +234,53 @@ impl<'a> Lexer<'a> { self.source.len() - self.input.len() } - pub(super) const fn span_from(&self, offset: usize) -> Span { - offset..self.end_byte_offset() + pub(super) fn span_from(&self, offset: usize) -> Span { + Span::from(offset..self.last_end_offset) } + /// Return the next non-whitespace token from `self`. + /// + /// Assume we are a parse state where bit shift operators may + /// occur, but not angle brackets. #[must_use] pub(super) fn next(&mut self) -> TokenSpan<'a> { + self.next_impl(false) + } + + /// Return the next non-whitespace token from `self`. + /// + /// Assume we are in a parse state where angle brackets may occur, + /// but not bit shift operators. + #[must_use] + pub(super) fn next_generic(&mut self) -> TokenSpan<'a> { + self.next_impl(true) + } + + /// Return the next non-whitespace token from `self`, with a span. + /// + /// See [`consume_token`] for the meaning of `generic`. + fn next_impl(&mut self, generic: bool) -> TokenSpan<'a> { let mut start_byte_offset = self.current_byte_offset(); loop { - let (token, rest) = consume_token(self.input, false); + let (token, rest) = consume_token(self.input, generic); self.input = rest; match token { Token::Trivia => start_byte_offset = self.current_byte_offset(), _ => { self.last_end_offset = self.current_byte_offset(); - return (token, start_byte_offset..self.last_end_offset); + return (token, self.span_from(start_byte_offset)); } } } } - #[must_use] - pub(super) fn next_generic(&mut self) -> TokenSpan<'a> { - let mut start_byte_offset = self.current_byte_offset(); - loop { - let (token, rest) = consume_token(self.input, true); - self.input = rest; - match token { - Token::Trivia => start_byte_offset = self.current_byte_offset(), - _ => return (token, start_byte_offset..self.current_byte_offset()), - } - } - } - #[must_use] pub(super) fn peek(&mut self) -> TokenSpan<'a> { let (token, _) = self.peek_token_and_rest(); token } - pub(super) fn expect_span( - &mut self, - expected: Token<'a>, - ) -> Result, Error<'a>> { + pub(super) fn expect_span(&mut self, expected: Token<'a>) -> Result> { let next = self.next(); if next.0 == expected { Ok(next.1) @@ -318,8 +330,16 @@ impl<'a> Lexer<'a> { } } - pub(super) fn next_ident(&mut self) -> Result<&'a str, Error<'a>> { - self.next_ident_with_span().map(|(word, _)| word) + pub(super) fn next_ident(&mut self) -> Result, Error<'a>> { + let ident = self + .next_ident_with_span() + .map(|(name, span)| super::ast::Ident { name, span })?; + + if crate::keywords::wgsl::RESERVED.contains(&ident.name) { + return Err(Error::ReservedKeyword(ident.span)); + } + + Ok(ident) } /// Parses a generic scalar type, for example ``. @@ -346,7 +366,7 @@ impl<'a> Lexer<'a> { self.expect_generic_paren('<')?; let pair = match self.next() { (Token::Word(word), span) => conv::get_scalar_type(word) - .map(|(a, b)| (a, b, span.clone())) + .map(|(a, b)| (a, b, span)) .ok_or(Error::UnknownScalarType(span)), (_, span) => Err(Error::UnknownScalarType(span)), }?; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index bc68d3e73..80d542952 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -4,8 +4,10 @@ Frontend for [WGSL][wgsl] (WebGPU Shading Language). [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html */ +mod ast; mod construction; mod conv; +mod index; mod lexer; mod number; #[cfg(test)] @@ -17,8 +19,7 @@ use crate::{ ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution, }, span::SourceLocation, - span::Span as NagaSpan, - ConstantInner, FastHashMap, ScalarValue, + FastHashMap, FastHashSet, Span, }; use self::{lexer::Lexer, number::Number}; @@ -30,10 +31,9 @@ use codespan_reporting::{ termcolor::{ColorChoice, NoColor, StandardStream}, }, }; -use std::{borrow::Cow, convert::TryFrom, ops}; +use std::{borrow::Cow, convert::TryFrom, ops::Range}; use thiserror::Error; -type Span = ops::Range; type TokenSpan<'a> = (Token<'a>, Span); #[derive(Copy, Clone, Debug, PartialEq)] @@ -68,6 +68,7 @@ pub enum ExpectedToken<'a> { Identifier, Number(NumberType), Integer, + /// A compile-time constant expression. Constant, /// Expected: constant, parenthesized expression, identifier PrimaryExpression, @@ -75,16 +76,18 @@ pub enum ExpectedToken<'a> { Assignment, /// Expected: '}', identifier FieldName, - /// Expected: attribute for a type - TypeAttribute, - /// Expected: ';', '{', word - Statement, /// Expected: 'case', 'default', '}' SwitchItem, /// Expected: ',', ')' WorkgroupSizeSeparator, /// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof GlobalItem, + /// Expected a type. + Type, + /// Access of `var`, `let`, `const`. + Variable, + /// Access of a function + Function, } #[derive(Clone, Copy, Debug, Error, PartialEq)] @@ -131,7 +134,7 @@ pub enum Error<'a> { InvalidForInitializer(Span), /// A break if appeared outside of a continuing block InvalidBreakIf(Span), - InvalidGatherComponent(Span, u32), + InvalidGatherComponent(Span), InvalidConstructorComponentType(Span, i32), InvalidIdentifierUnderscore(Span), ReservedIdentifierPrefix(Span), @@ -139,7 +142,6 @@ pub enum Error<'a> { UnknownAttribute(Span), UnknownBuiltin(Span), UnknownAccess(Span), - UnknownShaderStage(Span), UnknownIdent(Span, &'a str), UnknownScalarType(Span), UnknownType(Span), @@ -149,10 +151,9 @@ pub enum Error<'a> { AlignAttributeTooLow(Span, Alignment), NonPowerOfTwoAlignAttribute(Span), InconsistentBinding(Span), - UnknownLocalFunction(Span), TypeNotConstructible(Span), TypeNotInferrable(Span), - InitializationTypeMismatch(Span, String), + InitializationTypeMismatch(Span, String, String), MissingType(Span), MissingAttribute(&'static str, Span), InvalidAtomicPointer(Span), @@ -165,17 +166,55 @@ pub enum Error<'a> { ty: InvalidAssignmentType, }, ReservedKeyword(Span), + /// Redefinition of an identifier (used for both module-scope and local redefinitions). Redefinition { + /// Span of the identifier in the previous definition. previous: Span, + + /// Span of the identifier in the new definition. current: Span, }, + /// A declaration refers to itself directly. + RecursiveDeclaration { + /// The location of the name of the declaration. + ident: Span, + + /// The point at which it is used. + usage: Span, + }, + /// A declaration refers to itself indirectly, through one or more other + /// definitions. + CyclicDeclaration { + /// The location of the name of some declaration in the cycle. + ident: Span, + + /// The edges of the cycle of references. + /// + /// Each `(decl, reference)` pair indicates that the declaration whose + /// name is `decl` has an identifier at `reference` whose definition is + /// the next declaration in the cycle. The last pair's `reference` is + /// the same identifier as `ident`, above. + path: Vec<(Span, Span)>, + }, + ConstExprUnsupported(Span), + InvalidSwitchValue { + uint: bool, + span: Span, + }, + CalledEntryPoint(Span), + WrongArgumentCount { + span: Span, + expected: Range, + found: u32, + }, + FunctionReturnsVoid(Span), Other, } impl<'a> Error<'a> { fn as_parse_error(&self, source: &'a str) -> ParseError { match *self { - Error::Unexpected(ref unexpected_span, expected) => { + Error::Unexpected(unexpected_span, expected) => { let expected_str = match expected { ExpectedToken::Token(token) => { match token { @@ -206,120 +245,107 @@ impl<'a> Error<'a> { }.to_string() }, ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), - ExpectedToken::Constant => "constant".to_string(), + ExpectedToken::Constant => "compile-time constant".to_string(), ExpectedToken::PrimaryExpression => "expression".to_string(), ExpectedToken::Assignment => "assignment or increment/decrement".to_string(), ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(), - ExpectedToken::TypeAttribute => "type attribute".to_string(), - ExpectedToken::Statement => "statement".to_string(), ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), - ExpectedToken::GlobalItem => "global item ('struct', 'let', 'var', 'type', ';', 'fn') or the end of the file".to_string(), + ExpectedToken::GlobalItem => "global item ('struct', 'const', 'var', 'type', ';', 'fn') or the end of the file".to_string(), + ExpectedToken::Type => "type".to_string(), + ExpectedToken::Variable => "variable access".to_string(), + ExpectedToken::Function => "function name".to_string(), }; ParseError { message: format!( "expected {}, found '{}'", - expected_str, - &source[unexpected_span.clone()], + expected_str, &source[unexpected_span], ), - labels: vec![( - unexpected_span.clone(), - format!("expected {}", expected_str).into(), - )], + labels: vec![(unexpected_span, format!("expected {}", expected_str).into())], notes: vec![], } } - Error::UnexpectedComponents(ref bad_span) => ParseError { + Error::UnexpectedComponents(bad_span) => ParseError { message: "unexpected components".to_string(), - labels: vec![(bad_span.clone(), "unexpected components".into())], + labels: vec![(bad_span, "unexpected components".into())], notes: vec![], }, - Error::BadNumber(ref bad_span, ref err) => ParseError { - message: format!("{}: `{}`", err, &source[bad_span.clone()],), - labels: vec![(bad_span.clone(), err.to_string().into())], + Error::BadNumber(bad_span, ref err) => ParseError { + message: format!("{}: `{}`", err, &source[bad_span],), + labels: vec![(bad_span, err.to_string().into())], notes: vec![], }, - Error::NegativeInt(ref bad_span) => ParseError { + Error::NegativeInt(bad_span) => ParseError { message: format!( "expected non-negative integer literal, found `{}`", - &source[bad_span.clone()], + &source[bad_span], ), - labels: vec![(bad_span.clone(), "expected non-negative integer".into())], + labels: vec![(bad_span, "expected non-negative integer".into())], notes: vec![], }, - Error::BadU32Constant(ref bad_span) => ParseError { + Error::BadU32Constant(bad_span) => ParseError { message: format!( "expected unsigned integer constant expression, found `{}`", - &source[bad_span.clone()], + &source[bad_span], ), - labels: vec![(bad_span.clone(), "expected unsigned integer".into())], + labels: vec![(bad_span, "expected unsigned integer".into())], notes: vec![], }, - Error::BadMatrixScalarKind(ref span, kind, width) => ParseError { + Error::BadMatrixScalarKind(span, kind, width) => ParseError { message: format!( "matrix scalar type must be floating-point, but found `{}`", kind.to_wgsl(width) ), - labels: vec![(span.clone(), "must be floating-point (e.g. `f32`)".into())], + labels: vec![(span, "must be floating-point (e.g. `f32`)".into())], notes: vec![], }, - Error::BadAccessor(ref accessor_span) => ParseError { - message: format!( - "invalid field accessor `{}`", - &source[accessor_span.clone()], - ), - labels: vec![(accessor_span.clone(), "invalid accessor".into())], + Error::BadAccessor(accessor_span) => ParseError { + message: format!("invalid field accessor `{}`", &source[accessor_span],), + labels: vec![(accessor_span, "invalid accessor".into())], notes: vec![], }, - Error::UnknownIdent(ref ident_span, ident) => ParseError { + Error::UnknownIdent(ident_span, ident) => ParseError { message: format!("no definition in scope for identifier: '{}'", ident), - labels: vec![(ident_span.clone(), "unknown identifier".into())], + labels: vec![(ident_span, "unknown identifier".into())], notes: vec![], }, - Error::UnknownScalarType(ref bad_span) => ParseError { - message: format!("unknown scalar type: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "unknown scalar type".into())], + Error::UnknownScalarType(bad_span) => ParseError { + message: format!("unknown scalar type: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown scalar type".into())], notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()], }, - Error::BadTextureSampleType { - ref span, - kind, - width, - } => ParseError { + Error::BadTextureSampleType { span, kind, width } => ParseError { message: format!( "texture sample type must be one of f32, i32 or u32, but found {}", kind.to_wgsl(width) ), - labels: vec![(span.clone(), "must be one of f32, i32 or u32".into())], + labels: vec![(span, "must be one of f32, i32 or u32".into())], notes: vec![], }, - Error::BadIncrDecrReferenceType(ref span) => ParseError { + Error::BadIncrDecrReferenceType(span) => ParseError { message: "increment/decrement operation requires reference type to be one of i32 or u32" .to_string(), - labels: vec![( - span.clone(), - "must be a reference type of i32 or u32".into(), - )], + labels: vec![(span, "must be a reference type of i32 or u32".into())], notes: vec![], }, - Error::BadTexture(ref bad_span) => ParseError { + Error::BadTexture(bad_span) => ParseError { message: format!( "expected an image, but found '{}' which is not an image", - &source[bad_span.clone()] + &source[bad_span] ), - labels: vec![(bad_span.clone(), "not an image".into())], + labels: vec![(bad_span, "not an image".into())], notes: vec![], }, Error::BadTypeCast { - ref span, + span, ref from_type, ref to_type, } => { let msg = format!("cannot cast a {} to a {}", from_type, to_type); ParseError { message: msg.clone(), - labels: vec![(span.clone(), msg.into())], + labels: vec![(span, msg.into())], notes: vec![], } } @@ -328,241 +354,294 @@ impl<'a> Error<'a> { labels: vec![], notes: vec![], }, - Error::InvalidForInitializer(ref bad_span) => ParseError { + Error::InvalidForInitializer(bad_span) => ParseError { message: format!( "for(;;) initializer is not an assignment or a function call: '{}'", - &source[bad_span.clone()] + &source[bad_span] ), - labels: vec![( - bad_span.clone(), - "not an assignment or function call".into(), - )], + labels: vec![(bad_span, "not an assignment or function call".into())], notes: vec![], }, - Error::InvalidBreakIf(ref bad_span) => ParseError { + Error::InvalidBreakIf(bad_span) => ParseError { message: "A break if is only allowed in a continuing block".to_string(), - labels: vec![(bad_span.clone(), "not in a continuing block".into())], + labels: vec![(bad_span, "not in a continuing block".into())], notes: vec![], }, - Error::InvalidGatherComponent(ref bad_span, component) => ParseError { + Error::InvalidGatherComponent(bad_span) => ParseError { message: format!( - "textureGather component {} doesn't exist, must be 0, 1, 2, or 3", - component + "textureGather component '{}' doesn't exist, must be 0, 1, 2, or 3", + &source[bad_span] ), - labels: vec![(bad_span.clone(), "invalid component".into())], + labels: vec![(bad_span, "invalid component".into())], notes: vec![], }, - Error::InvalidConstructorComponentType(ref bad_span, component) => ParseError { + Error::InvalidConstructorComponentType(bad_span, component) => ParseError { message: format!( "invalid type for constructor component at index [{}]", component ), - labels: vec![(bad_span.clone(), "invalid component type".into())], + labels: vec![(bad_span, "invalid component type".into())], notes: vec![], }, - Error::InvalidIdentifierUnderscore(ref bad_span) => ParseError { + Error::InvalidIdentifierUnderscore(bad_span) => ParseError { message: "Identifier can't be '_'".to_string(), - labels: vec![(bad_span.clone(), "invalid identifier".into())], + labels: vec![(bad_span, "invalid identifier".into())], notes: vec![ "Use phony assignment instead ('_ =' notice the absence of 'let' or 'var')" .to_string(), ], }, - Error::ReservedIdentifierPrefix(ref bad_span) => ParseError { + Error::ReservedIdentifierPrefix(bad_span) => ParseError { message: format!( "Identifier starts with a reserved prefix: '{}'", - &source[bad_span.clone()] + &source[bad_span] ), - labels: vec![(bad_span.clone(), "invalid identifier".into())], + labels: vec![(bad_span, "invalid identifier".into())], notes: vec![], }, - Error::UnknownAddressSpace(ref bad_span) => ParseError { - message: format!("unknown address space: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "unknown address space".into())], + Error::UnknownAddressSpace(bad_span) => ParseError { + message: format!("unknown address space: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown address space".into())], notes: vec![], }, - Error::UnknownAttribute(ref bad_span) => ParseError { - message: format!("unknown attribute: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "unknown attribute".into())], + Error::UnknownAttribute(bad_span) => ParseError { + message: format!("unknown attribute: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown attribute".into())], notes: vec![], }, - Error::UnknownBuiltin(ref bad_span) => ParseError { - message: format!("unknown builtin: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "unknown builtin".into())], + Error::UnknownBuiltin(bad_span) => ParseError { + message: format!("unknown builtin: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown builtin".into())], notes: vec![], }, - Error::UnknownAccess(ref bad_span) => ParseError { - message: format!("unknown access: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "unknown access".into())], + Error::UnknownAccess(bad_span) => ParseError { + message: format!("unknown access: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown access".into())], notes: vec![], }, - Error::UnknownShaderStage(ref bad_span) => ParseError { - message: format!("unknown shader stage: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "unknown shader stage".into())], + Error::UnknownStorageFormat(bad_span) => ParseError { + message: format!("unknown storage format: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown storage format".into())], notes: vec![], }, - Error::UnknownStorageFormat(ref bad_span) => ParseError { - message: format!("unknown storage format: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "unknown storage format".into())], + Error::UnknownConservativeDepth(bad_span) => ParseError { + message: format!("unknown conservative depth: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown conservative depth".into())], notes: vec![], }, - Error::UnknownConservativeDepth(ref bad_span) => ParseError { - message: format!( - "unknown conservative depth: '{}'", - &source[bad_span.clone()] - ), - labels: vec![(bad_span.clone(), "unknown conservative depth".into())], + Error::UnknownType(bad_span) => ParseError { + message: format!("unknown type: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown type".into())], notes: vec![], }, - Error::UnknownType(ref bad_span) => ParseError { - message: format!("unknown type: '{}'", &source[bad_span.clone()]), - labels: vec![(bad_span.clone(), "unknown type".into())], - notes: vec![], - }, - Error::SizeAttributeTooLow(ref bad_span, min_size) => ParseError { + Error::SizeAttributeTooLow(bad_span, min_size) => ParseError { message: format!("struct member size must be at least {}", min_size), - labels: vec![( - bad_span.clone(), - format!("must be at least {}", min_size).into(), - )], + labels: vec![(bad_span, format!("must be at least {}", min_size).into())], notes: vec![], }, - Error::AlignAttributeTooLow(ref bad_span, min_align) => ParseError { + Error::AlignAttributeTooLow(bad_span, min_align) => ParseError { message: format!("struct member alignment must be at least {}", min_align), - labels: vec![( - bad_span.clone(), - format!("must be at least {}", min_align).into(), - )], + labels: vec![(bad_span, format!("must be at least {}", min_align).into())], notes: vec![], }, - Error::NonPowerOfTwoAlignAttribute(ref bad_span) => ParseError { + Error::NonPowerOfTwoAlignAttribute(bad_span) => ParseError { message: "struct member alignment must be a power of 2".to_string(), - labels: vec![(bad_span.clone(), "must be a power of 2".into())], + labels: vec![(bad_span, "must be a power of 2".into())], notes: vec![], }, - Error::InconsistentBinding(ref span) => ParseError { + Error::InconsistentBinding(span) => ParseError { message: "input/output binding is not consistent".to_string(), - labels: vec![( - span.clone(), - "input/output binding is not consistent".into(), - )], + labels: vec![(span, "input/output binding is not consistent".into())], notes: vec![], }, - Error::UnknownLocalFunction(ref span) => ParseError { - message: format!("unknown local function `{}`", &source[span.clone()]), - labels: vec![(span.clone(), "unknown local function".into())], + Error::TypeNotConstructible(span) => ParseError { + message: format!("type `{}` is not constructible", &source[span]), + labels: vec![(span, "type is not constructible".into())], notes: vec![], }, - Error::TypeNotConstructible(ref span) => ParseError { - message: format!("type `{}` is not constructible", &source[span.clone()]), - labels: vec![(span.clone(), "type is not constructible".into())], - notes: vec![], - }, - Error::TypeNotInferrable(ref span) => ParseError { + Error::TypeNotInferrable(span) => ParseError { message: "type can't be inferred".to_string(), - labels: vec![(span.clone(), "type can't be inferred".into())], + labels: vec![(span, "type can't be inferred".into())], notes: vec![], }, - Error::InitializationTypeMismatch(ref name_span, ref expected_ty) => ParseError { - message: format!( - "the type of `{}` is expected to be `{}`", - &source[name_span.clone()], - expected_ty - ), + Error::InitializationTypeMismatch(name_span, ref expected_ty, ref got_ty) => { + ParseError { + message: format!( + "the type of `{}` is expected to be `{}`, but got `{}`", + &source[name_span], expected_ty, got_ty, + ), + labels: vec![( + name_span, + format!("definition of `{}`", &source[name_span]).into(), + )], + notes: vec![], + } + } + Error::MissingType(name_span) => ParseError { + message: format!("variable `{}` needs a type", &source[name_span]), labels: vec![( - name_span.clone(), - format!("definition of `{}`", &source[name_span.clone()]).into(), + name_span, + format!("definition of `{}`", &source[name_span]).into(), )], notes: vec![], }, - Error::MissingType(ref name_span) => ParseError { - message: format!("variable `{}` needs a type", &source[name_span.clone()]), - labels: vec![( - name_span.clone(), - format!("definition of `{}`", &source[name_span.clone()]).into(), - )], - notes: vec![], - }, - Error::MissingAttribute(name, ref name_span) => ParseError { + Error::MissingAttribute(name, name_span) => ParseError { message: format!( "variable `{}` needs a '{}' attribute", - &source[name_span.clone()], - name + &source[name_span], name ), labels: vec![( - name_span.clone(), - format!("definition of `{}`", &source[name_span.clone()]).into(), + name_span, + format!("definition of `{}`", &source[name_span]).into(), )], notes: vec![], }, - Error::InvalidAtomicPointer(ref span) => ParseError { + Error::InvalidAtomicPointer(span) => ParseError { message: "atomic operation is done on a pointer to a non-atomic".to_string(), - labels: vec![(span.clone(), "atomic pointer is invalid".into())], + labels: vec![(span, "atomic pointer is invalid".into())], notes: vec![], }, - Error::InvalidAtomicOperandType(ref span) => ParseError { + Error::InvalidAtomicOperandType(span) => ParseError { message: "atomic operand type is inconsistent with the operation".to_string(), - labels: vec![(span.clone(), "atomic operand type is invalid".into())], + labels: vec![(span, "atomic operand type is invalid".into())], notes: vec![], }, - Error::NotPointer(ref span) => ParseError { + Error::NotPointer(span) => ParseError { message: "the operand of the `*` operator must be a pointer".to_string(), - labels: vec![(span.clone(), "expression is not a pointer".into())], + labels: vec![(span, "expression is not a pointer".into())], notes: vec![], }, - Error::NotReference(what, ref span) => ParseError { + Error::NotReference(what, span) => ParseError { message: format!("{} must be a reference", what), - labels: vec![(span.clone(), "expression is not a reference".into())], + labels: vec![(span, "expression is not a reference".into())], notes: vec![], }, - Error::InvalidAssignment { ref span, ty } => ParseError { + Error::InvalidAssignment { span, ty } => ParseError { message: "invalid left-hand side of assignment".into(), - labels: vec![(span.clone(), "cannot assign to this expression".into())], + labels: vec![(span, "cannot assign to this expression".into())], notes: match ty { InvalidAssignmentType::Swizzle => vec![ "WGSL does not support assignments to swizzles".into(), "consider assigning each component individually".into(), ], InvalidAssignmentType::ImmutableBinding => vec![ - format!("'{}' is an immutable binding", &source[span.clone()]), + format!("'{}' is an immutable binding", &source[span]), "consider declaring it with `var` instead of `let`".into(), ], InvalidAssignmentType::Other => vec![], }, }, - Error::Pointer(what, ref span) => ParseError { + Error::Pointer(what, span) => ParseError { message: format!("{} must not be a pointer", what), - labels: vec![(span.clone(), "expression is a pointer".into())], + labels: vec![(span, "expression is a pointer".into())], notes: vec![], }, - Error::ReservedKeyword(ref name_span) => ParseError { - message: format!( - "name `{}` is a reserved keyword", - &source[name_span.clone()] - ), + Error::ReservedKeyword(name_span) => ParseError { + message: format!("name `{}` is a reserved keyword", &source[name_span]), labels: vec![( - name_span.clone(), - format!("definition of `{}`", &source[name_span.clone()]).into(), + name_span, + format!("definition of `{}`", &source[name_span]).into(), )], notes: vec![], }, - Error::Redefinition { - ref previous, - ref current, - } => ParseError { - message: format!("redefinition of `{}`", &source[current.clone()]), + Error::Redefinition { previous, current } => ParseError { + message: format!("redefinition of `{}`", &source[current]), labels: vec![ ( - current.clone(), - format!("redefinition of `{}`", &source[current.clone()]).into(), + current, + format!("redefinition of `{}`", &source[current]).into(), ), ( - previous.clone(), - format!("previous definition of `{}`", &source[previous.clone()]).into(), + previous, + format!("previous definition of `{}`", &source[previous]).into(), ), ], notes: vec![], }, + Error::RecursiveDeclaration { ident, usage } => ParseError { + message: format!("declaration of `{}` is recursive", &source[ident]), + labels: vec![(ident, "".into()), (usage, "uses itself here".into())], + notes: vec![], + }, + Error::CyclicDeclaration { ident, ref path } => ParseError { + message: format!("declaration of `{}` is cyclic", &source[ident]), + labels: path + .iter() + .enumerate() + .flat_map(|(i, &(ident, usage))| { + [ + (ident, "".into()), + ( + usage, + if i == path.len() - 1 { + "ending the cycle".into() + } else { + format!("uses `{}`", &source[ident]).into() + }, + ), + ] + }) + .collect(), + notes: vec![], + }, + Error::ConstExprUnsupported(span) => ParseError { + message: "this constant expression is not supported".to_string(), + labels: vec![(span, "expression is not supported".into())], + notes: vec![ + "this should be fixed in a future version of Naga".into(), + "https://github.com/gfx-rs/naga/issues/1829".into(), + ], + }, + Error::InvalidSwitchValue { uint, span } => ParseError { + message: "invalid switch value".to_string(), + labels: vec![( + span, + if uint { + "expected unsigned integer" + } else { + "expected signed integer" + } + .into(), + )], + notes: vec![if uint { + format!("suffix the integer with a `u`: '{}u'", &source[span]) + } else { + let span = span.to_range().unwrap(); + format!( + "remove the `u` suffix: '{}'", + &source[span.start..span.end - 1] + ) + }], + }, + Error::CalledEntryPoint(span) => ParseError { + message: "entry point cannot be called".to_string(), + labels: vec![(span, "entry point cannot be called".into())], + notes: vec![], + }, + Error::WrongArgumentCount { + span, + ref expected, + found, + } => ParseError { + message: format!( + "wrong number of arguments: expected {}, found {}", + if expected.len() < 2 { + format!("{}", expected.start) + } else { + format!("{}..{}", expected.start, expected.end) + }, + found + ), + labels: vec![(span, "wrong number of arguments".into())], + notes: vec![], + }, + Error::FunctionReturnsVoid(span) => ParseError { + message: "function does not return any value".to_string(), + labels: vec![(span, "".into())], + notes: vec![ + "perhaps you meant to call the function in a separate statement?".into(), + ], + }, Error::Other => ParseError { message: "other error".to_string(), labels: vec![], @@ -658,7 +737,21 @@ impl crate::TypeInner { let base = member_type.name.as_deref().unwrap_or("unknown"); match size { crate::ArraySize::Constant(size) => { - let size = constants[size].name.as_deref().unwrap_or("unknown"); + let constant = &constants[size]; + let size = constant + .name + .clone() + .unwrap_or_else(|| match constant.inner { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(size), + .. + } => size.to_string(), + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Sint(size), + .. + } => size.to_string(), + _ => "?".to_string(), + }); format!("array<{}, {}>", base, size) } crate::ArraySize::Dynamic => format!("array<{}>", base), @@ -844,43 +937,165 @@ impl crate::ScalarKind { } } -trait StringValueLookup<'a> { - type Value; - fn lookup(&self, key: &'a str, span: Span) -> Result>; +/// State for constructing an AST expression. +struct ParseExpressionContext<'input, 'temp, 'out> { + /// The [`TranslationUnit::expressions`] arena to which we should contribute + /// expressions. + /// + /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions + expressions: &'out mut Arena>, + + /// The [`TranslationUnit::types`] arena to which we should contribute new + /// types. + /// + /// [`TranslationUnit::types`]: ast::TranslationUnit::types + types: &'out mut Arena>, + + /// A map from identifiers in scope to the locals/arguments they represent. + /// + /// The handles refer to the [`Function::locals`] area; see that field's + /// documentation for details. + /// + /// [`Function::locals`]: ast::Function::locals + local_table: &'temp mut super::SymbolTable<&'input str, Handle>, + + /// The [`Function::locals`] arena for the function we're building. + /// + /// [`Function::locals`]: ast::Function::locals + locals: &'out mut Arena, + + /// Identifiers used by the current global declaration that have no local definition. + /// + /// This becomes the [`GlobalDecl`]'s [`dependencies`] set. + /// + /// Note that we don't know at parse time what kind of [`GlobalDecl`] the + /// name refers to. We can't look up names until we've seen the entire + /// translation unit. + /// + /// [`GlobalDecl`]: ast::GlobalDecl + /// [`dependencies`]: ast::GlobalDecl::dependencies + unresolved: &'out mut FastHashSet>, } -impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, TypedExpression> { - type Value = TypedExpression; - fn lookup(&self, key: &'a str, span: Span) -> Result> { - self.get(key).cloned().ok_or(Error::UnknownIdent(span, key)) + +impl<'a> ParseExpressionContext<'a, '_, '_> { + fn reborrow(&mut self) -> ParseExpressionContext<'a, '_, '_> { + ParseExpressionContext { + expressions: self.expressions, + types: self.types, + local_table: self.local_table, + locals: self.locals, + unresolved: self.unresolved, + } + } + + fn parse_binary_op( + &mut self, + lexer: &mut Lexer<'a>, + classifier: impl Fn(Token<'a>) -> Option, + mut parser: impl FnMut( + &mut Lexer<'a>, + ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>>, + ) -> Result>, Error<'a>> { + let start = lexer.start_byte_offset(); + let mut accumulator = parser(lexer, self.reborrow())?; + while let Some(op) = classifier(lexer.peek().0) { + let _ = lexer.next(); + let left = accumulator; + let right = parser(lexer, self.reborrow())?; + accumulator = self.expressions.append( + ast::Expression::Binary { op, left, right }, + lexer.span_from(start), + ); + } + Ok(accumulator) } } -struct StatementContext<'input, 'temp, 'out> { - symbol_table: &'temp mut super::SymbolTable<&'input str, TypedExpression>, +/// State for constructing a `crate::Module`. +struct OutputContext<'source, 'temp, 'out> { + /// The `TranslationUnit`'s expressions arena. + ast_expressions: &'temp Arena>, + + /// The `TranslationUnit`'s types arena. + types: &'temp Arena>, + + // Naga IR values. + /// The map from the names of module-scope declarations to the Naga IR + /// `Handle`s we have built for them, owned by `Lowerer::lower`. + globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, + + /// The module we're constructing. + module: &'out mut crate::Module, +} + +impl<'source> OutputContext<'source, '_, '_> { + fn reborrow(&mut self) -> OutputContext<'source, '_, '_> { + OutputContext { + ast_expressions: self.ast_expressions, + globals: self.globals, + types: self.types, + module: self.module, + } + } + + fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { + self.module + .types + .insert(crate::Type { inner, name: None }, Span::UNDEFINED) + } +} + +/// State for lowering a statement within a function. +struct StatementContext<'source, 'temp, 'out> { + // WGSL AST values. + /// A reference to [`TranslationUnit::expressions`] for the translation unit + /// we're lowering. + /// + /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions + ast_expressions: &'temp Arena>, + + /// A reference to [`TranslationUnit::types`] for the translation unit + /// we're lowering. + /// + /// [`TranslationUnit::types`]: ast::TranslationUnit::types + types: &'temp Arena>, + + // Naga IR values. + /// The map from the names of module-scope declarations to the Naga IR + /// `Handle`s we have built for them, owned by `Lowerer::lower`. + globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, + + /// A map from `ast::Local` handles to the Naga expressions we've built for them. + /// + /// The Naga expressions are either [`LocalVariable`] or + /// [`FunctionArgument`] expressions. + /// + /// [`LocalVariable`]: crate::Expression::LocalVariable + /// [`FunctionArgument`]: crate::Expression::FunctionArgument + local_table: &'temp mut FastHashMap, TypedExpression>, + typifier: &'temp mut super::Typifier, variables: &'out mut Arena, - expressions: &'out mut Arena, + naga_expressions: &'out mut Arena, named_expressions: &'out mut FastHashMap, String>, - types: &'out mut UniqueArena, - constants: &'out mut Arena, - global_vars: &'out Arena, - functions: &'out Arena, arguments: &'out [crate::FunctionArgument], + module: &'out mut crate::Module, } impl<'a, 'temp> StatementContext<'a, 'temp, '_> { fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { StatementContext { - symbol_table: self.symbol_table, + local_table: self.local_table, + globals: self.globals, + types: self.types, + ast_expressions: self.ast_expressions, typifier: self.typifier, variables: self.variables, - expressions: self.expressions, + naga_expressions: self.naga_expressions, named_expressions: self.named_expressions, - types: self.types, - constants: self.constants, - global_vars: self.global_vars, - functions: self.functions, arguments: self.arguments, + module: self.module, } } @@ -893,36 +1108,46 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { 'temp: 't, { ExpressionContext { - symbol_table: self.symbol_table, - typifier: self.typifier, - expressions: self.expressions, + local_table: self.local_table, + globals: self.globals, types: self.types, - constants: self.constants, - global_vars: self.global_vars, + ast_expressions: self.ast_expressions, + typifier: self.typifier, + naga_expressions: self.naga_expressions, + module: self.module, local_vars: self.variables, - functions: self.functions, arguments: self.arguments, block, emitter, } } + + fn as_output(&mut self) -> OutputContext<'a, '_, '_> { + OutputContext { + ast_expressions: self.ast_expressions, + globals: self.globals, + types: self.types, + module: self.module, + } + } } -struct SamplingContext { - image: Handle, - arrayed: bool, -} +struct ExpressionContext<'source, 'temp, 'out> { + // WGSL AST values. + local_table: &'temp mut FastHashMap, TypedExpression>, + ast_expressions: &'temp Arena>, + types: &'temp Arena>, + + // Naga IR values. + /// The map from the names of module-scope declarations to the Naga IR + /// `Handle`s we have built for them, owned by `Lowerer::lower`. + globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, -struct ExpressionContext<'input, 'temp, 'out> { - symbol_table: &'temp mut super::SymbolTable<&'input str, TypedExpression>, typifier: &'temp mut super::Typifier, - expressions: &'out mut Arena, - types: &'out mut UniqueArena, - constants: &'out mut Arena, - global_vars: &'out Arena, + naga_expressions: &'out mut Arena, local_vars: &'out Arena, arguments: &'out [crate::FunctionArgument], - functions: &'out Arena, + module: &'out mut crate::Module, block: &'temp mut crate::Block, emitter: &'temp mut super::Emitter, } @@ -930,107 +1155,113 @@ struct ExpressionContext<'input, 'temp, 'out> { impl<'a> ExpressionContext<'a, '_, '_> { fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { ExpressionContext { - symbol_table: self.symbol_table, - typifier: self.typifier, - expressions: self.expressions, + local_table: self.local_table, + globals: self.globals, types: self.types, - constants: self.constants, - global_vars: self.global_vars, + ast_expressions: self.ast_expressions, + typifier: self.typifier, + naga_expressions: self.naga_expressions, + module: self.module, local_vars: self.local_vars, - functions: self.functions, arguments: self.arguments, block: self.block, emitter: self.emitter, } } - fn resolve_type( - &mut self, - handle: Handle, - ) -> Result<&crate::TypeInner, Error<'a>> { - let resolve_ctx = ResolveContext { - constants: self.constants, + fn as_output(&mut self) -> OutputContext<'a, '_, '_> { + OutputContext { + ast_expressions: self.ast_expressions, + globals: self.globals, types: self.types, - global_vars: self.global_vars, - local_vars: self.local_vars, - functions: self.functions, - arguments: self.arguments, - }; - match self.typifier.grow(handle, self.expressions, &resolve_ctx) { - Err(e) => Err(Error::InvalidResolve(e)), - Ok(()) => Ok(self.typifier.get(handle, self.types)), + module: self.module, } } - fn prepare_sampling( + /// Determine the type of `handle`, and add it to the module's arena. + /// + /// If you just need a `TypeInner` for `handle`'s type, use + /// [`grow_types`] and [`resolved_inner`] instead. This function + /// should only be used when the type of `handle` needs to appear + /// in the module's final `Arena`, for example, if you're + /// creating a [`LocalVariable`] whose type is inferred from its + /// initializer. + /// + /// [`grow_types`]: Self::grow_types + /// [`resolved_inner`]: Self::resolved_inner + /// [`LocalVariable`]: crate::LocalVariable + fn register_type( + &mut self, + handle: Handle, + ) -> Result, Error<'a>> { + self.grow_types(handle)?; + Ok(self.typifier.register_type(handle, &mut self.module.types)) + } + + /// Resolve the types of all expressions up through `handle`. + /// + /// Ensure that [`self.typifier`] has a [`TypeResolution`] for + /// every expression in [`self.naga_expressions`]. + /// + /// This does not add types to any arena. The [`Typifier`] + /// documentation explains the steps we take to avoid filling + /// arenas with intermediate types. + /// + /// This function takes `&mut self`, so it can't conveniently + /// return a shared reference to the resulting `TypeResolution`: + /// the shared reference would extend the mutable borrow, and you + /// wouldn't be able to use `self` for anything else. Instead, you + /// should call `grow_types` to cover the handles you need, and + /// then use `self.typifier[handle]` or + /// [`self.resolved_inner(handle)`] to get at their resolutions. + /// + /// [`self.typifier`]: ExpressionContext::typifier + /// [`self.resolved_inner(handle)`]: ExpressionContext::resolved_inner + /// [`Typifier`]: super::Typifier + fn grow_types(&mut self, handle: Handle) -> Result<&mut Self, Error<'a>> { + let resolve_ctx = ResolveContext { + constants: &self.module.constants, + types: &self.module.types, + global_vars: &self.module.global_variables, + local_vars: self.local_vars, + functions: &self.module.functions, + arguments: self.arguments, + }; + self.typifier + .grow(handle, self.naga_expressions, &resolve_ctx) + .map_err(Error::InvalidResolve)?; + Ok(self) + } + + fn resolved_inner(&self, handle: Handle) -> &crate::TypeInner { + self.typifier[handle].inner_with(&self.module.types) + } + + fn image_data( &mut self, image: Handle, span: Span, - ) -> Result> { - Ok(SamplingContext { - image, - arrayed: match *self.resolve_type(image)? { - crate::TypeInner::Image { arrayed, .. } => arrayed, - _ => return Err(Error::BadTexture(span)), - }, - }) + ) -> Result<(crate::ImageClass, bool), Error<'a>> { + self.grow_types(image)?; + match *self.resolved_inner(image) { + crate::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), + _ => Err(Error::BadTexture(span)), + } } - fn parse_binary_op( + fn prepare_args<'b>( &mut self, - lexer: &mut Lexer<'a>, - classifier: impl Fn(Token<'a>) -> Option, - mut parser: impl FnMut( - &mut Lexer<'a>, - ExpressionContext<'a, '_, '_>, - ) -> Result>, - ) -> Result> { - let start = lexer.start_byte_offset() as u32; - let mut accumulator = parser(lexer, self.reborrow())?; - while let Some(op) = classifier(lexer.peek().0) { - let _ = lexer.next(); - // Binary expressions always apply the load rule to their operands. - let mut left = self.apply_load_rule(accumulator); - let unloaded_right = parser(lexer, self.reborrow())?; - let right = self.apply_load_rule(unloaded_right); - let end = lexer.end_byte_offset() as u32; - left = self.expressions.append( - crate::Expression::Binary { op, left, right }, - NagaSpan::new(start, end), - ); - // Binary expressions never produce references. - accumulator = TypedExpression::non_reference(left); + args: &'b [Handle>], + min_args: u32, + span: Span, + ) -> ArgumentContext<'b, 'a> { + ArgumentContext { + args: args.iter(), + min_args, + args_used: 0, + total_args: args.len() as u32, + span, } - Ok(accumulator) - } - - fn parse_binary_splat_op( - &mut self, - lexer: &mut Lexer<'a>, - classifier: impl Fn(Token<'a>) -> Option, - mut parser: impl FnMut( - &mut Lexer<'a>, - ExpressionContext<'a, '_, '_>, - ) -> Result>, - ) -> Result> { - let start = lexer.start_byte_offset() as u32; - let mut accumulator = parser(lexer, self.reborrow())?; - while let Some(op) = classifier(lexer.peek().0) { - let _ = lexer.next(); - // Binary expressions always apply the load rule to their operands. - let mut left = self.apply_load_rule(accumulator); - let unloaded_right = parser(lexer, self.reborrow())?; - let mut right = self.apply_load_rule(unloaded_right); - let end = lexer.end_byte_offset() as u32; - - self.binary_op_splat(op, &mut left, &mut right)?; - - accumulator = TypedExpression::non_reference(self.expressions.append( - crate::Expression::Binary { op, left, right }, - NagaSpan::new(start, end), - )); - } - Ok(accumulator) } /// Insert splats, if needed by the non-'*' operations. @@ -1041,24 +1272,27 @@ impl<'a> ExpressionContext<'a, '_, '_> { right: &mut Handle, ) -> Result<(), Error<'a>> { if op != crate::BinaryOperator::Multiply { - let left_size = match *self.resolve_type(*left)? { + self.grow_types(*left)?.grow_types(*right)?; + + let left_size = match *self.resolved_inner(*left) { crate::TypeInner::Vector { size, .. } => Some(size), _ => None, }; - match (left_size, self.resolve_type(*right)?) { + + match (left_size, self.resolved_inner(*right)) { (Some(size), &crate::TypeInner::Scalar { .. }) => { - *right = self.expressions.append( + *right = self.naga_expressions.append( crate::Expression::Splat { size, value: *right, }, - self.expressions.get_span(*right), + self.naga_expressions.get_span(*right), ); } (None, &crate::TypeInner::Vector { size, .. }) => { - *left = self.expressions.append( + *left = self.naga_expressions.append( crate::Expression::Splat { size, value: *left }, - self.expressions.get_span(*left), + self.naga_expressions.get_span(*left), ); } _ => {} @@ -1075,11 +1309,12 @@ impl<'a> ExpressionContext<'a, '_, '_> { fn interrupt_emitter( &mut self, expression: crate::Expression, - span: NagaSpan, + span: Span, ) -> Handle { - self.block.extend(self.emitter.finish(self.expressions)); - let result = self.expressions.append(expression, span); - self.emitter.start(self.expressions); + self.block + .extend(self.emitter.finish(self.naga_expressions)); + let result = self.naga_expressions.append(expression, span); + self.emitter.start(self.naga_expressions); result } @@ -1092,8 +1327,8 @@ impl<'a> ExpressionContext<'a, '_, '_> { let load = crate::Expression::Load { pointer: expr.handle, }; - let span = self.expressions.get_span(expr.handle); - self.expressions.append(load, span) + let span = self.naga_expressions.get_span(expr.handle); + self.naga_expressions.append(load, span) } else { expr.handle } @@ -1106,7 +1341,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { &mut self, ty: Handle, ) -> Option> { - let inner = match self.types[ty].inner { + let inner = match self.module.types[ty].inner { crate::TypeInner::Scalar { kind, width } => { let value = match kind { crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), @@ -1117,13 +1352,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { crate::ConstantInner::Scalar { width, value } } crate::TypeInner::Vector { size, kind, width } => { - let scalar_ty = self.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { width, kind }, - }, - Default::default(), - ); + let scalar_ty = self.ensure_type_exists(crate::TypeInner::Scalar { width, kind }); let component = self.create_zero_value_constant(scalar_ty); crate::ConstantInner::Composite { ty, @@ -1135,17 +1364,11 @@ impl<'a> ExpressionContext<'a, '_, '_> { rows, width, } => { - let vec_ty = self.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Vector { - width, - kind: crate::ScalarKind::Float, - size: rows, - }, - }, - Default::default(), - ); + let vec_ty = self.ensure_type_exists(crate::TypeInner::Vector { + width, + kind: crate::ScalarKind::Float, + size: rows, + }); let component = self.create_zero_value_constant(vec_ty); crate::ConstantInner::Composite { ty, @@ -1162,7 +1385,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { let component = self.create_zero_value_constant(base); crate::ConstantInner::Composite { ty, - components: (0..self.constants[size].to_array_length().unwrap()) + components: (0..self.module.constants[size].to_array_length().unwrap()) .map(|_| component) .collect::>()?, } @@ -1180,16 +1403,75 @@ impl<'a> ExpressionContext<'a, '_, '_> { _ => return None, }; - let constant = self.constants.fetch_or_append( + let constant = self.module.constants.fetch_or_append( crate::Constant { name: None, specialization: None, inner, }, - crate::Span::default(), + Span::UNDEFINED, ); Some(constant) } + + fn format_typeinner(&self, inner: &crate::TypeInner) -> String { + inner.to_wgsl(&self.module.types, &self.module.constants) + } + + fn format_type(&self, handle: Handle) -> String { + let ty = &self.module.types[handle]; + match ty.name { + Some(ref name) => name.clone(), + None => self.format_typeinner(&ty.inner), + } + } + + fn format_type_resolution(&self, resolution: &TypeResolution) -> String { + match *resolution { + TypeResolution::Handle(handle) => self.format_type(handle), + TypeResolution::Value(ref inner) => self.format_typeinner(inner), + } + } + + fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { + self.as_output().ensure_type_exists(inner) + } +} + +struct ArgumentContext<'ctx, 'source> { + args: std::slice::Iter<'ctx, Handle>>, + min_args: u32, + args_used: u32, + total_args: u32, + span: Span, +} + +impl<'source> ArgumentContext<'_, 'source> { + pub fn finish(self) -> Result<(), Error<'source>> { + if self.args.len() == 0 { + Ok(()) + } else { + Err(Error::WrongArgumentCount { + found: self.total_args, + expected: self.min_args..self.args_used + 1, + span: self.span, + }) + } + } + + pub fn next(&mut self) -> Result>, Error<'source>> { + match self.args.next().copied() { + Some(arg) => { + self.args_used += 1; + Ok(arg) + } + None => Err(Error::WrongArgumentCount { + found: self.total_args, + expected: self.min_args..self.args_used + 1, + span: self.span, + }), + } + } } /// A Naga [`Expression`] handle, with WGSL type information. @@ -1237,10 +1519,7 @@ impl Composition { } fn extract_impl(name: &str, name_span: Span) -> Result { - let ch = name - .chars() - .next() - .ok_or_else(|| Error::BadAccessor(name_span.clone()))?; + let ch = name.chars().next().ok_or(Error::BadAccessor(name_span))?; match Self::letter_component(ch) { Some(sc) => Ok(sc as u32), None => Err(Error::BadAccessor(name_span)), @@ -1251,8 +1530,7 @@ impl Composition { if name.len() > 1 { let mut components = [crate::SwizzleComponent::X; 4]; for (comp, ch) in components.iter_mut().zip(name.chars()) { - *comp = Self::letter_component(ch) - .ok_or_else(|| Error::BadAccessor(name_span.clone()))?; + *comp = Self::letter_component(ch).ok_or(Error::BadAccessor(name_span))?; } let size = match name.len() { @@ -1268,13 +1546,6 @@ impl Composition { } } -#[derive(Default)] -struct TypeAttributes { - // Although WGSL nas no type attributes at the moment, it had them in the past - // (`[[stride]]`) and may as well acquire some again in the future. - // Therefore, we are leaving the plumbing in for now. -} - /// Which grammar rule we are in the midst of parsing. /// /// This is used for error checking. `Parser` maintains a stack of @@ -1288,15 +1559,12 @@ enum Rule { FunctionDecl, Block, Statement, - ConstantExpr, PrimaryExpr, SingularExpr, UnaryExpr, GeneralExpr, } -type LocalFunctionCall = (Handle, Vec>); - #[derive(Default)] struct BindingParser { location: Option, @@ -1316,7 +1584,7 @@ impl BindingParser { match name { "location" => { lexer.expect(Token::Paren('('))?; - self.location = Some(Parser::parse_non_negative_i32_literal(lexer)?); + self.location = Some(Parser::non_negative_i32_literal(lexer)?); lexer.expect(Token::Paren(')'))?; } "builtin" => { @@ -1374,18 +1642,6 @@ impl BindingParser { } } -struct ParsedVariable<'a> { - name: &'a str, - name_span: Span, - space: Option, - ty: Handle, - init: Option>, -} - -struct CalledFunction { - result: Option>, -} - #[derive(Clone, Debug)] pub struct ParseError { message: String, @@ -1397,7 +1653,7 @@ impl ParseError { pub fn labels(&self) -> impl Iterator + ExactSizeIterator + '_ { self.labels .iter() - .map(|&(ref span, ref msg)| (span.clone(), msg.as_ref())) + .map(|&(span, ref msg)| (span, msg.as_ref())) } pub fn message(&self) -> &str { @@ -1411,7 +1667,8 @@ impl ParseError { self.labels .iter() .map(|label| { - Label::primary((), label.0.clone()).with_message(label.1.to_string()) + Label::primary((), label.0.to_range().unwrap()) + .with_message(label.1.to_string()) }) .collect(), ) @@ -1454,9 +1711,7 @@ impl ParseError { /// Returns a [`SourceLocation`] for the first label in the error message. pub fn location(&self, source: &str) -> Option { - self.labels - .get(0) - .map(|label| NagaSpan::new(label.0.start as u32, label.0.end as u32).location(source)) + self.labels.get(0).map(|label| label.0.location(source)) } } @@ -1474,26 +1729,15 @@ impl std::error::Error for ParseError { pub struct Parser { rules: Vec<(Rule, usize)>, - module_scope_identifiers: FastHashMap, - lookup_type: FastHashMap>, - layouter: Layouter, } impl Parser { - pub fn new() -> Self { - Parser { - rules: Vec::new(), - module_scope_identifiers: FastHashMap::default(), - lookup_type: FastHashMap::default(), - layouter: Default::default(), - } + pub const fn new() -> Self { + Parser { rules: Vec::new() } } fn reset(&mut self) { self.rules.clear(); - self.module_scope_identifiers.clear(); - self.lookup_type.clear(); - self.layouter.clear(); } fn push_rule_span(&mut self, rule: Rule, lexer: &mut Lexer<'_>) { @@ -1510,26 +1754,20 @@ impl Parser { lexer.span_from(initial) } - fn parse_switch_value<'a>( - lexer: &mut Lexer<'a>, - uint: bool, - ) -> Result> { - match lexer.next() { - (Token::Word("default"), _) => Ok(crate::SwitchValue::Default), - (Token::Number(Ok(Number::U32(num))), _) if uint => { - Ok(crate::SwitchValue::Integer(num as i32)) - } - (Token::Number(Ok(Number::I32(num))), _) if !uint => { - Ok(crate::SwitchValue::Integer(num)) - } - (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), - (_, span) => Err(Error::Unexpected(span, ExpectedToken::Integer)), + fn switch_value<'a>(lexer: &mut Lexer<'a>) -> Result<(ast::SwitchValue, Span), Error<'a>> { + let token_span = lexer.next(); + match token_span.0 { + Token::Word("default") => Ok((ast::SwitchValue::Default, token_span.1)), + Token::Number(Ok(Number::U32(num))) => Ok((ast::SwitchValue::U32(num), token_span.1)), + Token::Number(Ok(Number::I32(num))) => Ok((ast::SwitchValue::I32(num), token_span.1)), + Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)), + _ => Err(Error::Unexpected(token_span.1, ExpectedToken::Integer)), } } /// Parse a non-negative signed integer literal. /// This is for attributes like `size`, `location` and others. - fn parse_non_negative_i32_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + fn non_negative_i32_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { match lexer.next() { (Token::Number(Ok(Number::I32(num))), span) => { u32::try_from(num).map_err(|_| Error::NegativeInt(span)) @@ -1545,7 +1783,7 @@ impl Parser { /// Parse a non-negative integer literal that may be either signed or unsigned. /// This is for the `workgroup_size` attribute and array lengths. /// Note: these values should be no larger than [`i32::MAX`], but this is not checked here. - fn parse_generic_non_negative_int_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + fn generic_non_negative_int_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { match lexer.next() { (Token::Number(Ok(Number::I32(num))), span) => { u32::try_from(num).map_err(|_| Error::NegativeInt(span)) @@ -1559,1182 +1797,365 @@ impl Parser { } } - fn parse_atomic_pointer<'a>( + /// Decide if we're looking at a construction expression, and return its + /// type if so. + /// + /// If the identifier `word` is a [type-defining keyword], then return a + /// [`ConstructorType`] value describing the type to build. Return an error + /// if the type is not constructible (like `sampler`). + /// + /// If `word` isn't a type name, then return `None`. + /// + /// [type-defining keyword]: https://gpuweb.github.io/gpuweb/wgsl/#type-defining-keywords + /// [`ConstructorType`]: ast::ConstructorType + fn constructor_type<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - let (pointer, pointer_span) = - lexer.capture_span(|lexer| self.parse_general_expression(lexer, ctx.reborrow()))?; - // Check if the pointer expression is to an atomic. - // The IR uses regular `Expression::Load` and `Statement::Store` for atomic load/stores, - // and it will not catch the use of a non-atomic variable here. - match *ctx.resolve_type(pointer)? { - crate::TypeInner::Pointer { base, .. } => match ctx.types[base].inner { - crate::TypeInner::Atomic { .. } => Ok(pointer), - ref other => { - log::error!("Pointer type to {:?} passed to atomic op", other); - Err(Error::InvalidAtomicPointer(pointer_span)) - } + word: &'a str, + span: Span, + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + if let Some((kind, width)) = conv::get_scalar_type(word) { + return Ok(Some(ast::ConstructorType::Scalar { kind, width })); + } + + let partial = match word { + "vec2" => ast::ConstructorType::PartialVector { + size: crate::VectorSize::Bi, }, - ref other => { - log::error!("Type {:?} passed to atomic op", other); - Err(Error::InvalidAtomicPointer(pointer_span)) + "vec3" => ast::ConstructorType::PartialVector { + size: crate::VectorSize::Tri, + }, + "vec4" => ast::ConstructorType::PartialVector { + size: crate::VectorSize::Quad, + }, + "mat2x2" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Bi, + }, + "mat2x3" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Tri, + }, + "mat2x4" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Quad, + }, + "mat3x2" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Bi, + }, + "mat3x3" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Tri, + }, + "mat3x4" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Quad, + }, + "mat4x2" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Bi, + }, + "mat4x3" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Tri, + }, + "mat4x4" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Quad, + }, + "array" => ast::ConstructorType::PartialArray, + "atomic" + | "binding_array" + | "sampler" + | "sampler_comparison" + | "texture_1d" + | "texture_1d_array" + | "texture_2d" + | "texture_2d_array" + | "texture_3d" + | "texture_cube" + | "texture_cube_array" + | "texture_multisampled_2d" + | "texture_multisampled_2d_array" + | "texture_depth_2d" + | "texture_depth_2d_array" + | "texture_depth_cube" + | "texture_depth_cube_array" + | "texture_depth_multisampled_2d" + | "texture_storage_1d" + | "texture_storage_1d_array" + | "texture_storage_2d" + | "texture_storage_2d_array" + | "texture_storage_3d" => return Err(Error::TypeNotConstructible(span)), + _ => return Ok(None), + }; + + // parse component type if present + match (lexer.peek().0, partial) { + (Token::Paren('<'), ast::ConstructorType::PartialVector { size }) => { + let (kind, width) = lexer.next_scalar_generic()?; + Ok(Some(ast::ConstructorType::Vector { size, kind, width })) } + (Token::Paren('<'), ast::ConstructorType::PartialMatrix { columns, rows }) => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + match kind { + crate::ScalarKind::Float => Ok(Some(ast::ConstructorType::Matrix { + columns, + rows, + width, + })), + _ => Err(Error::BadMatrixScalarKind(span, kind, width)), + } + } + (Token::Paren('<'), ast::ConstructorType::PartialArray) => { + lexer.expect_generic_paren('<')?; + let base = self.type_decl(lexer, ctx.reborrow())?; + let size = if lexer.skip(Token::Separator(',')) { + let expr = self.unary_expression(lexer, ctx.reborrow())?; + ast::ArraySize::Constant(expr) + } else { + ast::ArraySize::Dynamic + }; + lexer.expect_generic_paren('>')?; + + Ok(Some(ast::ConstructorType::Array { base, size })) + } + (_, partial) => Ok(Some(partial)), } } - /// Expects name to be peeked from lexer, does not consume if returns None. - fn parse_local_function_call<'a>( + /// Expects `name` to be consumed (not in lexer). + fn arguments<'a>( &mut self, lexer: &mut Lexer<'a>, - name: &'a str, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - let fun_handle = match ctx.functions.iter().find(|&(_, fun)| match fun.name { - Some(ref string) => string == name, - None => false, - }) { - Some((fun_handle, _)) => fun_handle, - None => return Ok(None), - }; - - let count = ctx.functions[fun_handle].arguments.len(); - let mut arguments = Vec::with_capacity(count); - let _ = lexer.next(); + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>>, Error<'a>> { lexer.open_arguments()?; - while arguments.len() != count { + let mut arguments = Vec::new(); + loop { if !arguments.is_empty() { - lexer.expect(Token::Separator(','))?; + if !lexer.next_argument()? { + break; + } + } else if lexer.skip(Token::Paren(')')) { + break; } - let arg = self.parse_general_expression(lexer, ctx.reborrow())?; + let arg = self.general_expression(lexer, ctx.reborrow())?; arguments.push(arg); } - lexer.close_arguments()?; - Ok(Some((fun_handle, arguments))) - } - fn parse_atomic_helper<'a>( - &mut self, - lexer: &mut Lexer<'a>, - fun: crate::AtomicFunction, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - lexer.open_arguments()?; - let pointer = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let ctx_span = ctx.reborrow(); - let (value, value_span) = - lexer.capture_span(|lexer| self.parse_general_expression(lexer, ctx_span))?; - lexer.close_arguments()?; - - let expression = match *ctx.resolve_type(value)? { - crate::TypeInner::Scalar { kind, width } => crate::Expression::AtomicResult { - ty: ctx.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { kind, width }, - }, - NagaSpan::UNDEFINED, - ), - comparison: false, - }, - _ => return Err(Error::InvalidAtomicOperandType(value_span)), - }; - - let span = NagaSpan::from(value_span); - let result = ctx.interrupt_emitter(expression, span); - ctx.block.push( - crate::Statement::Atomic { - pointer, - fun, - value, - result, - }, - span, - ); - Ok(result) + Ok(arguments) } /// Expects [`Rule::PrimaryExpr`] or [`Rule::SingularExpr`] on top; does not pop it. - /// Expects `word` to be peeked (still in lexer), doesn't consume if returning None. - fn parse_function_call_inner<'a>( + /// Expects `name` to be consumed (not in lexer). + fn function_call<'a>( &mut self, lexer: &mut Lexer<'a>, name: &'a str, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { + name_span: Span, + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { assert!(self.rules.last().is_some()); - let expr = if let Some(fun) = conv::map_relational_fun(name) { - let _ = lexer.next(); - lexer.open_arguments()?; - let argument = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::Relational { fun, argument } - } else if let Some(axis) = conv::map_derivative_axis(name) { - let _ = lexer.next(); - lexer.open_arguments()?; - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::Derivative { axis, expr } - } else if let Some(fun) = conv::map_standard_fun(name) { - let _ = lexer.next(); - lexer.open_arguments()?; - let arg_count = fun.argument_count(); - let arg = self.parse_general_expression(lexer, ctx.reborrow())?; - let arg1 = if arg_count > 1 { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - let arg2 = if arg_count > 2 { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - let arg3 = if arg_count > 3 { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::Math { - fun, - arg, - arg1, - arg2, - arg3, - } - } else { - match name { - "bitcast" => { - let _ = lexer.next(); - lexer.expect_generic_paren('<')?; - let (ty, type_span) = lexer.capture_span(|lexer| { - self.parse_type_decl(lexer, None, ctx.types, ctx.constants) - })?; - lexer.expect_generic_paren('>')?; - lexer.open_arguments()?; - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - - let kind = match ctx.types[ty].inner { - crate::TypeInner::Scalar { kind, .. } => kind, - crate::TypeInner::Vector { kind, .. } => kind, - _ => { - return Err(Error::BadTypeCast { - from_type: format!("{:?}", ctx.resolve_type(expr)?), - span: type_span, - to_type: format!("{:?}", ctx.types[ty].inner), - }) - } - }; - - crate::Expression::As { - expr, - kind, - convert: None, - } - } - "select" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let reject = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let accept = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let condition = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::Select { - condition, - accept, - reject, - } - } - "arrayLength" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let array = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::ArrayLength(array) - } - // atomics - "atomicLoad" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let pointer = self.parse_atomic_pointer(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::Load { pointer } - } - "atomicAdd" => { - let _ = lexer.next(); - let handle = self.parse_atomic_helper( - lexer, - crate::AtomicFunction::Add, - ctx.reborrow(), - )?; - return Ok(Some(CalledFunction { - result: Some(handle), - })); - } - "atomicSub" => { - let _ = lexer.next(); - let handle = self.parse_atomic_helper( - lexer, - crate::AtomicFunction::Subtract, - ctx.reborrow(), - )?; - return Ok(Some(CalledFunction { - result: Some(handle), - })); - } - "atomicAnd" => { - let _ = lexer.next(); - let handle = self.parse_atomic_helper( - lexer, - crate::AtomicFunction::And, - ctx.reborrow(), - )?; - return Ok(Some(CalledFunction { - result: Some(handle), - })); - } - "atomicOr" => { - let _ = lexer.next(); - let handle = self.parse_atomic_helper( - lexer, - crate::AtomicFunction::InclusiveOr, - ctx.reborrow(), - )?; - return Ok(Some(CalledFunction { - result: Some(handle), - })); - } - "atomicXor" => { - let _ = lexer.next(); - let handle = self.parse_atomic_helper( - lexer, - crate::AtomicFunction::ExclusiveOr, - ctx.reborrow(), - )?; - return Ok(Some(CalledFunction { - result: Some(handle), - })); - } - "atomicMin" => { - let _ = lexer.next(); - let handle = - self.parse_atomic_helper(lexer, crate::AtomicFunction::Min, ctx)?; - return Ok(Some(CalledFunction { - result: Some(handle), - })); - } - "atomicMax" => { - let _ = lexer.next(); - let handle = - self.parse_atomic_helper(lexer, crate::AtomicFunction::Max, ctx)?; - return Ok(Some(CalledFunction { - result: Some(handle), - })); - } - "atomicExchange" => { - let _ = lexer.next(); - let handle = self.parse_atomic_helper( - lexer, - crate::AtomicFunction::Exchange { compare: None }, - ctx, - )?; - return Ok(Some(CalledFunction { - result: Some(handle), - })); - } - "atomicCompareExchangeWeak" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let pointer = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let cmp = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let (value, value_span) = lexer.capture_span(|lexer| { - self.parse_general_expression(lexer, ctx.reborrow()) - })?; - lexer.close_arguments()?; - - let expression = match *ctx.resolve_type(value)? { - crate::TypeInner::Scalar { kind, width } => { - let bool_ty = ctx.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: crate::BOOL_WIDTH, - }, - }, - NagaSpan::UNDEFINED, - ); - let scalar_ty = ctx.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { kind, width }, - }, - NagaSpan::UNDEFINED, - ); - let struct_ty = ctx.types.insert( - crate::Type { - name: Some("__atomic_compare_exchange_result".to_string()), - inner: crate::TypeInner::Struct { - members: vec![ - crate::StructMember { - name: Some("old_value".to_string()), - ty: scalar_ty, - binding: None, - offset: 0, - }, - crate::StructMember { - name: Some("exchanged".to_string()), - ty: bool_ty, - binding: None, - offset: 4, - }, - ], - span: 8, - }, - }, - NagaSpan::UNDEFINED, - ); - crate::Expression::AtomicResult { - ty: struct_ty, - comparison: true, - } - } - _ => return Err(Error::InvalidAtomicOperandType(value_span)), - }; - - let span = NagaSpan::from(self.peek_rule_span(lexer)); - let result = ctx.interrupt_emitter(expression, span); - ctx.block.push( - crate::Statement::Atomic { - pointer, - fun: crate::AtomicFunction::Exchange { compare: Some(cmp) }, - value, - result, - }, - span, - ); - return Ok(Some(CalledFunction { - result: Some(result), - })); - } - // texture sampling - "textureSample" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let (image, image_span) = - self.parse_general_expression_with_span(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image, image_span)?; - let array_index = if sc.arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageSample { - image: sc.image, - sampler: sampler_expr, - gather: None, - coordinate, - array_index, - offset, - level: crate::SampleLevel::Auto, - depth_ref: None, - } - } - "textureSampleLevel" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let (image, image_span) = - self.parse_general_expression_with_span(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image, image_span)?; - let array_index = if sc.arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - lexer.expect(Token::Separator(','))?; - let level = self.parse_general_expression(lexer, ctx.reborrow())?; - let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageSample { - image: sc.image, - sampler: sampler_expr, - gather: None, - coordinate, - array_index, - offset, - level: crate::SampleLevel::Exact(level), - depth_ref: None, - } - } - "textureSampleBias" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let (image, image_span) = - self.parse_general_expression_with_span(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image, image_span)?; - let array_index = if sc.arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - lexer.expect(Token::Separator(','))?; - let bias = self.parse_general_expression(lexer, ctx.reborrow())?; - let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageSample { - image: sc.image, - sampler: sampler_expr, - gather: None, - coordinate, - array_index, - offset, - level: crate::SampleLevel::Bias(bias), - depth_ref: None, - } - } - "textureSampleGrad" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let (image, image_span) = - self.parse_general_expression_with_span(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image, image_span)?; - let array_index = if sc.arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - lexer.expect(Token::Separator(','))?; - let x = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let y = self.parse_general_expression(lexer, ctx.reborrow())?; - let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageSample { - image: sc.image, - sampler: sampler_expr, - gather: None, - coordinate, - array_index, - offset, - level: crate::SampleLevel::Gradient { x, y }, - depth_ref: None, - } - } - "textureSampleCompare" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let (image, image_span) = - self.parse_general_expression_with_span(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image, image_span)?; - let array_index = if sc.arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - lexer.expect(Token::Separator(','))?; - let reference = self.parse_general_expression(lexer, ctx.reborrow())?; - let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageSample { - image: sc.image, - sampler: sampler_expr, - gather: None, - coordinate, - array_index, - offset, - level: crate::SampleLevel::Auto, - depth_ref: Some(reference), - } - } - "textureSampleCompareLevel" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let (image, image_span) = - self.parse_general_expression_with_span(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image, image_span)?; - let array_index = if sc.arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - lexer.expect(Token::Separator(','))?; - let reference = self.parse_general_expression(lexer, ctx.reborrow())?; - let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageSample { - image: sc.image, - sampler: sampler_expr, - gather: None, - coordinate, - array_index, - offset, - level: crate::SampleLevel::Zero, - depth_ref: Some(reference), - } - } - "textureGather" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let component = if let (Token::Number(..), span) = lexer.peek() { - let index = Self::parse_non_negative_i32_literal(lexer)?; - lexer.expect(Token::Separator(','))?; - *crate::SwizzleComponent::XYZW - .get(index as usize) - .ok_or(Error::InvalidGatherComponent(span, index))? - } else { - crate::SwizzleComponent::X - }; - let (image, image_span) = - self.parse_general_expression_with_span(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image, image_span)?; - let array_index = if sc.arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageSample { - image: sc.image, - sampler: sampler_expr, - gather: Some(component), - coordinate, - array_index, - offset, - level: crate::SampleLevel::Zero, - depth_ref: None, - } - } - "textureGatherCompare" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let (image, image_span) = - self.parse_general_expression_with_span(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let sampler_expr = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let sc = ctx.prepare_sampling(image, image_span)?; - let array_index = if sc.arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - lexer.expect(Token::Separator(','))?; - let reference = self.parse_general_expression(lexer, ctx.reborrow())?; - let offset = if lexer.skip(Token::Separator(',')) { - Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageSample { - image: sc.image, - sampler: sampler_expr, - gather: Some(crate::SwizzleComponent::X), - coordinate, - array_index, - offset, - level: crate::SampleLevel::Zero, - depth_ref: Some(reference), - } - } - "textureLoad" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let (image, image_span) = - self.parse_general_expression_with_span(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?; - let (class, arrayed) = match *ctx.resolve_type(image)? { - crate::TypeInner::Image { class, arrayed, .. } => (class, arrayed), - _ => return Err(Error::BadTexture(image_span)), - }; - let array_index = if arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - let level = if class.is_mipmapped() { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - let sample = if class.is_multisampled() { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression(lexer, ctx.reborrow())?) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageLoad { - image, - coordinate, - array_index, - sample, - level, - } - } - "textureDimensions" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let image = self.parse_general_expression(lexer, ctx.reborrow())?; - let level = if lexer.skip(Token::Separator(',')) { - let expr = self.parse_general_expression(lexer, ctx.reborrow())?; - Some(expr) - } else { - None - }; - lexer.close_arguments()?; - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::Size { level }, - } - } - "textureNumLevels" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let image = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::NumLevels, - } - } - "textureNumLayers" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let image = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::NumLayers, - } - } - "textureNumSamples" => { - let _ = lexer.next(); - lexer.open_arguments()?; - let image = self.parse_general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::NumSamples, - } - } - // other - _ => { - let result = - match self.parse_local_function_call(lexer, name, ctx.reborrow())? { - Some((function, arguments)) => { - let span = NagaSpan::from(self.peek_rule_span(lexer)); - ctx.block.extend(ctx.emitter.finish(ctx.expressions)); - let result = ctx.functions[function].result.as_ref().map(|_| { - ctx.expressions - .append(crate::Expression::CallResult(function), span) - }); - ctx.emitter.start(ctx.expressions); - ctx.block.push( - crate::Statement::Call { - function, - arguments, - result, - }, - span, - ); - result - } - None => return Ok(None), - }; - return Ok(Some(CalledFunction { result })); - } - } - }; - let span = NagaSpan::from(self.peek_rule_span(lexer)); - let handle = ctx.expressions.append(expr, span); - Ok(Some(CalledFunction { - result: Some(handle), - })) - } - - fn parse_const_expression_impl<'a>( - &mut self, - first_token_span: TokenSpan<'a>, - lexer: &mut Lexer<'a>, - register_name: Option<&'a str>, - type_arena: &mut UniqueArena, - const_arena: &mut Arena, - ) -> Result, Error<'a>> { - self.push_rule_span(Rule::ConstantExpr, lexer); - let inner = match first_token_span { - (Token::Word("true"), _) => crate::ConstantInner::boolean(true), - (Token::Word("false"), _) => crate::ConstantInner::boolean(false), - (Token::Number(num), _) => match num { - Ok(Number::I32(num)) => crate::ConstantInner::Scalar { - value: crate::ScalarValue::Sint(num as i64), - width: 4, - }, - Ok(Number::U32(num)) => crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(num as u64), - width: 4, - }, - Ok(Number::F32(num)) => crate::ConstantInner::Scalar { - value: crate::ScalarValue::Float(num as f64), - width: 4, - }, - Ok(Number::AbstractInt(_) | Number::AbstractFloat(_)) => unreachable!(), - Err(e) => return Err(Error::BadNumber(first_token_span.1, e)), - }, - (Token::Word(name), name_span) => { - // look for an existing constant first - for (handle, var) in const_arena.iter() { - match var.name { - Some(ref string) if string == name => { - self.pop_rule_span(lexer); - return Ok(handle); - } - _ => {} - } - } - let composite_ty = self.parse_type_decl_name( - lexer, - name, - name_span, - None, - TypeAttributes::default(), - type_arena, - const_arena, - )?; + let expr = match name { + // bitcast looks like a function call, but it's an operator and must be handled differently. + "bitcast" => { + lexer.expect_generic_paren('<')?; + let start = lexer.start_byte_offset(); + let to = self.type_decl(lexer, ctx.reborrow())?; + let span = lexer.span_from(start); + lexer.expect_generic_paren('>')?; lexer.open_arguments()?; - //Note: this expects at least one argument - let mut components = Vec::new(); - while components.is_empty() || lexer.next_argument()? { - let component = self.parse_const_expression(lexer, type_arena, const_arena)?; - components.push(component); - } - crate::ConstantInner::Composite { - ty: composite_ty, - components, + let expr = self.general_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + + ast::Expression::Bitcast { + expr, + to, + ty_span: span, } } - other => return Err(Error::Unexpected(other.1, ExpectedToken::Constant)), - }; - - // Only set span if it's a named constant. Otherwise, the enclosing Expression should have - // the span. - let span = self.pop_rule_span(lexer); - let handle = if let Some(name) = register_name { - if crate::keywords::wgsl::RESERVED.contains(&name) { - return Err(Error::ReservedKeyword(span)); + // everything else must be handled later, since they can be hidden by user-defined functions. + _ => { + let arguments = self.arguments(lexer, ctx.reborrow())?; + ctx.unresolved.insert(ast::Dependency { + ident: name, + usage: name_span, + }); + ast::Expression::Call { + function: ast::Ident { + name, + span: name_span, + }, + arguments, + } } - const_arena.append( - crate::Constant { - name: Some(name.to_string()), - specialization: None, - inner, - }, - NagaSpan::from(span), - ) - } else { - const_arena.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Default::default(), - ) }; - Ok(handle) + let span = self.peek_rule_span(lexer); + let expr = ctx.expressions.append(expr, span); + Ok(expr) } - fn parse_const_expression<'a>( + fn ident_expr<'a>( &mut self, - lexer: &mut Lexer<'a>, - type_arena: &mut UniqueArena, - const_arena: &mut Arena, - ) -> Result, Error<'a>> { - self.parse_const_expression_impl(lexer.next(), lexer, None, type_arena, const_arena) + name: &'a str, + name_span: Span, + ctx: ParseExpressionContext<'a, '_, '_>, + ) -> ast::IdentExpr<'a> { + match ctx.local_table.lookup(name) { + Some(&local) => ast::IdentExpr::Local(local), + None => { + ctx.unresolved.insert(ast::Dependency { + ident: name, + usage: name_span, + }); + ast::IdentExpr::Unresolved(name) + } + } } - fn parse_primary_expression<'a>( + fn primary_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result> { - // Will be popped inside match, possibly inside parse_function_call_inner or parse_construction + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { self.push_rule_span(Rule::PrimaryExpr, lexer); + let expr = match lexer.peek() { (Token::Paren('('), _) => { let _ = lexer.next(); - let (expr, _span) = - self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; + let expr = self.general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; self.pop_rule_span(lexer); - expr + return Ok(expr); } - (Token::Word("true" | "false") | Token::Number(..), _) => { - let const_handle = self.parse_const_expression(lexer, ctx.types, ctx.constants)?; - let span = NagaSpan::from(self.pop_rule_span(lexer)); - TypedExpression::non_reference( - ctx.interrupt_emitter(crate::Expression::Constant(const_handle), span), - ) + (Token::Word("true"), _) => { + let _ = lexer.next(); + ast::Expression::Literal(ast::Literal::Bool(true)) + } + (Token::Word("false"), _) => { + let _ = lexer.next(); + ast::Expression::Literal(ast::Literal::Bool(false)) + } + (Token::Number(res), span) => { + let _ = lexer.next(); + let num = res.map_err(|err| Error::BadNumber(span, err))?; + ast::Expression::Literal(ast::Literal::Number(num)) } (Token::Word(word), span) => { - if let Some(definition) = ctx.symbol_table.lookup(word) { - let _ = lexer.next(); - self.pop_rule_span(lexer); + let start = lexer.start_byte_offset(); + let _ = lexer.next(); - *definition - } else if let Some(CalledFunction { result: Some(expr) }) = - self.parse_function_call_inner(lexer, word, ctx.reborrow())? - { - //TODO: resolve the duplicate call in `parse_singular_expression` - self.pop_rule_span(lexer); - TypedExpression::non_reference(expr) - } else { - let _ = lexer.next(); - if let Some(expr) = construction::parse_construction( - self, - lexer, - word, - span.clone(), - ctx.reborrow(), - )? { - TypedExpression::non_reference(expr) - } else { - return Err(Error::UnknownIdent(span, word)); + if let Some(ty) = self.constructor_type(lexer, word, span, ctx.reborrow())? { + let ty_span = lexer.span_from(start); + let components = self.arguments(lexer, ctx.reborrow())?; + ast::Expression::Construct { + ty, + ty_span, + components, } + } else if let Token::Paren('(') = lexer.peek().0 { + self.pop_rule_span(lexer); + return self.function_call(lexer, word, span, ctx); + } else if word == "bitcast" { + self.pop_rule_span(lexer); + return self.function_call(lexer, word, span, ctx); + } else { + let ident = self.ident_expr(word, span, ctx.reborrow()); + ast::Expression::Ident(ident) } } other => return Err(Error::Unexpected(other.1, ExpectedToken::PrimaryExpression)), }; + + let span = self.pop_rule_span(lexer); + let expr = ctx.expressions.append(expr, span); Ok(expr) } - fn parse_postfix<'a>( + fn postfix<'a>( &mut self, span_start: usize, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, - expr: TypedExpression, - ) -> Result> { - // Parse postfix expressions, adjusting `handle` and `is_reference` along the way. - // - // Most postfix expressions don't affect `is_reference`: for example, `s.x` is a - // reference whenever `s` is a reference. But swizzles (WGSL spec: "multiple - // component selection") apply the load rule, converting references to values, so - // those affect `is_reference` as well as `handle`. - let TypedExpression { - mut handle, - mut is_reference, - } = expr; - let mut prefix_span = lexer.span_from(span_start); + mut ctx: ParseExpressionContext<'a, '_, '_>, + expr: Handle>, + ) -> Result>, Error<'a>> { + let mut expr = expr; loop { - // Step lightly around `resolve_type`'s mutable borrow. - ctx.resolve_type(handle)?; - - // Find the type of the composite whose elements, components or members we're - // accessing, skipping through references: except for swizzles, the `Access` - // or `AccessIndex` expressions we'd generate are the same either way. - // - // Pointers, however, are not permitted. For error checks below, note whether - // the base expression is a WGSL pointer. - let temp_inner; - let (composite, wgsl_pointer) = match *ctx.typifier.get(handle, ctx.types) { - crate::TypeInner::Pointer { base, .. } => (&ctx.types[base].inner, !is_reference), - crate::TypeInner::ValuePointer { - size: None, - kind, - width, - .. - } => { - temp_inner = crate::TypeInner::Scalar { kind, width }; - (&temp_inner, !is_reference) - } - crate::TypeInner::ValuePointer { - size: Some(size), - kind, - width, - .. - } => { - temp_inner = crate::TypeInner::Vector { size, kind, width }; - (&temp_inner, !is_reference) - } - ref other => (other, false), - }; - let expression = match lexer.peek().0 { Token::Separator('.') => { let _ = lexer.next(); - let (name, name_span) = lexer.next_ident_with_span()?; + let field = lexer.next_ident()?; - // WGSL doesn't allow accessing members on pointers, or swizzling - // them. But Naga IR doesn't distinguish pointers and references, so - // we must check here. - if wgsl_pointer { - return Err(Error::Pointer( - "the value accessed by a `.member` expression", - prefix_span, - )); - } - - let access = match *composite { - crate::TypeInner::Struct { ref members, .. } => { - let index = members - .iter() - .position(|m| m.name.as_deref() == Some(name)) - .ok_or(Error::BadAccessor(name_span))? - as u32; - crate::Expression::AccessIndex { - base: handle, - index, - } - } - crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { - match Composition::make(name, name_span)? { - Composition::Multi(size, pattern) => { - // Once you apply the load rule, the expression is no - // longer a reference. - let current_expr = TypedExpression { - handle, - is_reference, - }; - let vector = ctx.apply_load_rule(current_expr); - is_reference = false; - - crate::Expression::Swizzle { - size, - vector, - pattern, - } - } - Composition::Single(index) => crate::Expression::AccessIndex { - base: handle, - index, - }, - } - } - _ => return Err(Error::BadAccessor(name_span)), - }; - - access + ast::Expression::Member { base: expr, field } } Token::Paren('[') => { - let (_, open_brace_span) = lexer.next(); - let index = self.parse_general_expression(lexer, ctx.reborrow())?; - let close_brace_span = lexer.expect_span(Token::Paren(']'))?; + let _ = lexer.next(); + let index = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(']'))?; - // WGSL doesn't allow pointers to be subscripted. But Naga IR doesn't - // distinguish pointers and references, so we must check here. - if wgsl_pointer { - return Err(Error::Pointer( - "the value indexed by a `[]` subscripting expression", - prefix_span, - )); - } - - if let crate::Expression::Constant(constant) = ctx.expressions[index] { - let expr_span = open_brace_span.end..close_brace_span.start; - - let index = match ctx.constants[constant].inner { - ConstantInner::Scalar { - value: ScalarValue::Uint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(expr_span)), - ConstantInner::Scalar { - value: ScalarValue::Sint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(expr_span)), - _ => Err(Error::BadU32Constant(expr_span)), - }?; - - crate::Expression::AccessIndex { - base: handle, - index, - } - } else { - crate::Expression::Access { - base: handle, - index, - } - } + ast::Expression::Index { base: expr, index } } _ => break, }; - prefix_span = lexer.span_from(span_start); - handle = ctx - .expressions - .append(expression, NagaSpan::from(prefix_span.clone())); + let span = lexer.span_from(span_start); + expr = ctx.expressions.append(expression, span); } - Ok(TypedExpression { - handle, - is_reference, - }) + Ok(expr) } /// Parse a `unary_expression`. - fn parse_unary_expression<'a>( + fn unary_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result> { + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { self.push_rule_span(Rule::UnaryExpr, lexer); //TODO: refactor this to avoid backing up let expr = match lexer.peek().0 { Token::Operation('-') => { let _ = lexer.next(); - let unloaded_expr = self.parse_unary_expression(lexer, ctx.reborrow())?; - let expr = ctx.apply_load_rule(unloaded_expr); - let expr = crate::Expression::Unary { + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Unary { op: crate::UnaryOperator::Negate, expr, }; - let span = NagaSpan::from(self.peek_rule_span(lexer)); - TypedExpression::non_reference(ctx.expressions.append(expr, span)) + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) } Token::Operation('!' | '~') => { let _ = lexer.next(); - let unloaded_expr = self.parse_unary_expression(lexer, ctx.reborrow())?; - let expr = ctx.apply_load_rule(unloaded_expr); - let expr = crate::Expression::Unary { + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Unary { op: crate::UnaryOperator::Not, expr, }; - let span = NagaSpan::from(self.peek_rule_span(lexer)); - TypedExpression::non_reference(ctx.expressions.append(expr, span)) + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) } Token::Operation('*') => { let _ = lexer.next(); - // The `*` operator does not accept a reference, so we must apply the Load - // Rule here. But the operator itself simply changes the type from - // `ptr` to `ref`, so we generate no code for the - // operator itself. We simply return a `TypedExpression` with - // `is_reference` set to true. - let unloaded_pointer = self.parse_unary_expression(lexer, ctx.reborrow())?; - let pointer = ctx.apply_load_rule(unloaded_pointer); - - // An expression like `&*ptr` may generate no Naga IR at all, but WGSL requires - // an error if `ptr` is not a pointer. So we have to type-check this ourselves. - if ctx.resolve_type(pointer)?.pointer_space().is_none() { - let span = ctx - .expressions - .get_span(pointer) - .to_range() - .unwrap_or_else(|| self.peek_rule_span(lexer)); - return Err(Error::NotPointer(span)); - } - - TypedExpression { - handle: pointer, - is_reference: true, - } + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Deref(expr); + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) } Token::Operation('&') => { let _ = lexer.next(); - // The `&` operator simply converts a reference to a pointer. And since a - // reference is required, the Load Rule is not applied. - let operand = self.parse_unary_expression(lexer, ctx.reborrow())?; - if !operand.is_reference { - let span = ctx - .expressions - .get_span(operand.handle) - .to_range() - .unwrap_or_else(|| self.peek_rule_span(lexer)); - return Err(Error::NotReference("the operand of the `&` operator", span)); - } - - // No code is generated. We just declare the pointer a reference now. - TypedExpression { - is_reference: false, - ..operand - } + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::AddrOf(expr); + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) } - _ => self.parse_singular_expression(lexer, ctx.reborrow())?, + _ => self.singular_expression(lexer, ctx.reborrow())?, }; self.pop_rule_span(lexer); @@ -2742,25 +2163,25 @@ impl Parser { } /// Parse a `singular_expression`. - fn parse_singular_expression<'a>( + fn singular_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result> { + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { let start = lexer.start_byte_offset(); self.push_rule_span(Rule::SingularExpr, lexer); - let primary_expr = self.parse_primary_expression(lexer, ctx.reborrow())?; - let singular_expr = self.parse_postfix(start, lexer, ctx.reborrow(), primary_expr)?; + let primary_expr = self.primary_expression(lexer, ctx.reborrow())?; + let singular_expr = self.postfix(start, lexer, ctx.reborrow(), primary_expr)?; self.pop_rule_span(lexer); Ok(singular_expr) } - fn parse_equality_expression<'a>( + fn equality_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut context: ExpressionContext<'a, '_, '_>, - ) -> Result> { + mut context: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { // equality_expression context.parse_binary_op( lexer, @@ -2795,7 +2216,7 @@ impl Parser { }, // additive_expression |lexer, mut context| { - context.parse_binary_splat_op( + context.parse_binary_op( lexer, |token| match token { Token::Operation('+') => Some(crate::BinaryOperator::Add), @@ -2806,7 +2227,7 @@ impl Parser { }, // multiplicative_expression |lexer, mut context| { - context.parse_binary_splat_op( + context.parse_binary_op( lexer, |token| match token { Token::Operation('*') => { @@ -2820,9 +2241,7 @@ impl Parser { } _ => None, }, - |lexer, context| { - self.parse_unary_expression(lexer, context) - }, + |lexer, context| self.unary_expression(lexer, context), ) }, ) @@ -2834,29 +2253,20 @@ impl Parser { ) } - fn parse_general_expression_with_span<'a>( + fn general_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result<(Handle, Span), Error<'a>> { - let (expr, span) = self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; - Ok((ctx.apply_load_rule(expr), span)) + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + self.general_expression_with_span(lexer, ctx.reborrow()) + .map(|(expr, _)| expr) } - fn parse_general_expression<'a>( + fn general_expression_with_span<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - let (expr, _span) = self.parse_general_expression_for_reference(lexer, ctx.reborrow())?; - Ok(ctx.apply_load_rule(expr)) - } - - fn parse_general_expression_for_reference<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut context: ExpressionContext<'a, '_, '_>, - ) -> Result<(TypedExpression, Span), Error<'a>> { + mut context: ParseExpressionContext<'a, '_, '_>, + ) -> Result<(Handle>, Span), Error<'a>> { self.push_rule_span(Rule::GeneralExpr, lexer); // logical_or_expression let handle = context.parse_binary_op( @@ -2902,7 +2312,7 @@ impl Parser { _ => None, }, |lexer, context| { - self.parse_equality_expression(lexer, context) + self.equality_expression(lexer, context) }, ) }, @@ -2916,30 +2326,17 @@ impl Parser { Ok((handle, self.pop_rule_span(lexer))) } - fn parse_variable_ident_decl<'a>( + fn variable_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - type_arena: &mut UniqueArena, - const_arena: &mut Arena, - ) -> Result<(&'a str, Span, Handle), Error<'a>> { - let (name, name_span) = lexer.next_ident_with_span()?; - lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; - Ok((name, name_span, ty)) - } - - fn parse_variable_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - type_arena: &mut UniqueArena, - const_arena: &mut Arena, - ) -> Result, Error<'a>> { + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { self.push_rule_span(Rule::VariableDecl, lexer); - let mut space = None; + let mut space = crate::AddressSpace::Handle; if lexer.skip(Token::Paren('<')) { let (class_str, span) = lexer.next_ident_with_span()?; - space = Some(match class_str { + space = match class_str { "storage" => { let access = if lexer.skip(Token::Separator(',')) { lexer.next_storage_access()? @@ -2950,38 +2347,36 @@ impl Parser { crate::AddressSpace::Storage { access } } _ => conv::map_address_space(class_str, span)?, - }); + }; lexer.expect(Token::Paren('>'))?; } let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let ty = self.type_decl(lexer, ctx.reborrow())?; let init = if lexer.skip(Token::Operation('=')) { - let handle = self.parse_const_expression(lexer, type_arena, const_arena)?; + let handle = self.general_expression(lexer, ctx.reborrow())?; Some(handle) } else { None }; lexer.expect(Token::Separator(';'))?; - let name_span = self.pop_rule_span(lexer); - Ok(ParsedVariable { + self.pop_rule_span(lexer); + + Ok(ast::GlobalVariable { name, - name_span, space, + binding: None, ty, init, }) } - fn parse_struct_body<'a>( + fn struct_body<'a>( &mut self, lexer: &mut Lexer<'a>, - type_arena: &mut UniqueArena, - const_arena: &mut Arena, - ) -> Result<(Vec, u32), Error<'a>> { - let mut offset = 0; - let mut struct_alignment = Alignment::ONE; + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { let mut members = Vec::new(); lexer.expect(Token::Paren('{'))?; @@ -2993,102 +2388,56 @@ impl Parser { ExpectedToken::Token(Token::Separator(',')), )); } - let (mut size_attr, mut align_attr) = (None, None); + let (mut size, mut align) = (None, None); self.push_rule_span(Rule::Attribute, lexer); let mut bind_parser = BindingParser::default(); while lexer.skip(Token::Attribute) { match lexer.next_ident_with_span()? { ("size", _) => { lexer.expect(Token::Paren('('))?; - let (value, span) = - lexer.capture_span(Self::parse_non_negative_i32_literal)?; + let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; lexer.expect(Token::Paren(')'))?; - size_attr = Some((value, span)); + size = Some((value, span)); } ("align", _) => { lexer.expect(Token::Paren('('))?; - let (value, span) = - lexer.capture_span(Self::parse_non_negative_i32_literal)?; + let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; lexer.expect(Token::Paren(')'))?; - align_attr = Some((value, span)); + align = Some((value, span)); } (word, word_span) => bind_parser.parse(lexer, word, word_span)?, } } let bind_span = self.pop_rule_span(lexer); - let mut binding = bind_parser.finish(bind_span)?; + let binding = bind_parser.finish(bind_span)?; - let (name, span) = match lexer.next() { - (Token::Word(word), span) => (word, span), - other => return Err(Error::Unexpected(other.1, ExpectedToken::FieldName)), - }; - if crate::keywords::wgsl::RESERVED.contains(&name) { - return Err(Error::ReservedKeyword(span)); - } + let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let ty = self.type_decl(lexer, ctx.reborrow())?; ready = lexer.skip(Token::Separator(',')); - self.layouter.update(type_arena, const_arena).unwrap(); - - let member_min_size = self.layouter[ty].size; - let member_min_alignment = self.layouter[ty].alignment; - - let member_size = if let Some((size, span)) = size_attr { - if size < member_min_size { - return Err(Error::SizeAttributeTooLow(span, member_min_size)); - } else { - size - } - } else { - member_min_size - }; - - let member_alignment = if let Some((align, span)) = align_attr { - if let Some(alignment) = Alignment::new(align) { - if alignment < member_min_alignment { - return Err(Error::AlignAttributeTooLow(span, member_min_alignment)); - } else { - alignment - } - } else { - return Err(Error::NonPowerOfTwoAlignAttribute(span)); - } - } else { - member_min_alignment - }; - - offset = member_alignment.round_up(offset); - struct_alignment = struct_alignment.max(member_alignment); - - if let Some(ref mut binding) = binding { - binding.apply_default_interpolation(&type_arena[ty].inner); - } - - members.push(crate::StructMember { - name: Some(name.to_owned()), + members.push(ast::StructMember { + name, ty, binding, - offset, + size, + align, }); - - offset += member_size; } - let struct_size = struct_alignment.round_up(offset); - Ok((members, struct_size)) + Ok(members) } - fn parse_matrix_scalar_type<'a>( + fn matrix_scalar_type<'a>( &mut self, lexer: &mut Lexer<'a>, columns: crate::VectorSize, rows: crate::VectorSize, - ) -> Result> { + ) -> Result, Error<'a>> { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; match kind { - crate::ScalarKind::Float => Ok(crate::TypeInner::Matrix { + crate::ScalarKind::Float => Ok(ast::Type::Matrix { columns, rows, width, @@ -3097,22 +2446,20 @@ impl Parser { } } - fn parse_type_decl_impl<'a>( + fn type_decl_impl<'a>( &mut self, lexer: &mut Lexer<'a>, - _attribute: TypeAttributes, word: &'a str, - type_arena: &mut UniqueArena, - const_arena: &mut Arena, - ) -> Result, Error<'a>> { + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { if let Some((kind, width)) = conv::get_scalar_type(word) { - return Ok(Some(crate::TypeInner::Scalar { kind, width })); + return Ok(Some(ast::Type::Scalar { kind, width })); } Ok(Some(match word { "vec2" => { let (kind, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Vector { + ast::Type::Vector { size: crate::VectorSize::Bi, kind, width, @@ -3120,7 +2467,7 @@ impl Parser { } "vec3" => { let (kind, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Vector { + ast::Type::Vector { size: crate::VectorSize::Tri, kind, width, @@ -3128,61 +2475,49 @@ impl Parser { } "vec4" => { let (kind, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Vector { + ast::Type::Vector { size: crate::VectorSize::Quad, kind, width, } } "mat2x2" => { - self.parse_matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Bi)? + self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Bi)? } "mat2x3" => { - self.parse_matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Tri)? + self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Tri)? + } + "mat2x4" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Quad)? } - "mat2x4" => self.parse_matrix_scalar_type( - lexer, - crate::VectorSize::Bi, - crate::VectorSize::Quad, - )?, "mat3x2" => { - self.parse_matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Bi)? + self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Bi)? + } + "mat3x3" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Tri)? + } + "mat3x4" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Quad)? + } + "mat4x2" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Bi)? + } + "mat4x3" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Tri)? + } + "mat4x4" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Quad)? } - "mat3x3" => self.parse_matrix_scalar_type( - lexer, - crate::VectorSize::Tri, - crate::VectorSize::Tri, - )?, - "mat3x4" => self.parse_matrix_scalar_type( - lexer, - crate::VectorSize::Tri, - crate::VectorSize::Quad, - )?, - "mat4x2" => self.parse_matrix_scalar_type( - lexer, - crate::VectorSize::Quad, - crate::VectorSize::Bi, - )?, - "mat4x3" => self.parse_matrix_scalar_type( - lexer, - crate::VectorSize::Quad, - crate::VectorSize::Tri, - )?, - "mat4x4" => self.parse_matrix_scalar_type( - lexer, - crate::VectorSize::Quad, - crate::VectorSize::Quad, - )?, "atomic" => { let (kind, width) = lexer.next_scalar_generic()?; - crate::TypeInner::Atomic { kind, width } + ast::Type::Atomic { kind, width } } "ptr" => { lexer.expect_generic_paren('<')?; let (ident, span) = lexer.next_ident_with_span()?; let mut space = conv::map_address_space(ident, span)?; lexer.expect(Token::Separator(','))?; - let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let base = self.type_decl(lexer, ctx)?; if let crate::AddressSpace::Storage { ref mut access } = space { *access = if lexer.skip(Token::Separator(',')) { lexer.next_storage_access()? @@ -3191,46 +2526,40 @@ impl Parser { }; } lexer.expect_generic_paren('>')?; - crate::TypeInner::Pointer { base, space } + ast::Type::Pointer { base, space } } "array" => { lexer.expect_generic_paren('<')?; - let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let base = self.type_decl(lexer, ctx.reborrow())?; let size = if lexer.skip(Token::Separator(',')) { - let const_handle = - self.parse_const_expression(lexer, type_arena, const_arena)?; - crate::ArraySize::Constant(const_handle) + let size = self.unary_expression(lexer, ctx.reborrow())?; + ast::ArraySize::Constant(size) } else { - crate::ArraySize::Dynamic + ast::ArraySize::Dynamic }; lexer.expect_generic_paren('>')?; - let stride = { - self.layouter.update(type_arena, const_arena).unwrap(); - self.layouter[base].to_stride() - }; - crate::TypeInner::Array { base, size, stride } + ast::Type::Array { base, size } } "binding_array" => { lexer.expect_generic_paren('<')?; - let base = self.parse_type_decl(lexer, None, type_arena, const_arena)?; + let base = self.type_decl(lexer, ctx.reborrow())?; let size = if lexer.skip(Token::Separator(',')) { - let const_handle = - self.parse_const_expression(lexer, type_arena, const_arena)?; - crate::ArraySize::Constant(const_handle) + let size = self.unary_expression(lexer, ctx.reborrow())?; + ast::ArraySize::Constant(size) } else { - crate::ArraySize::Dynamic + ast::ArraySize::Dynamic }; lexer.expect_generic_paren('>')?; - crate::TypeInner::BindingArray { base, size } + ast::Type::BindingArray { base, size } } - "sampler" => crate::TypeInner::Sampler { comparison: false }, - "sampler_comparison" => crate::TypeInner::Sampler { comparison: true }, + "sampler" => ast::Type::Sampler { comparison: false }, + "sampler_comparison" => ast::Type::Sampler { comparison: true }, "texture_1d" => { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; Self::check_texture_sample_type(kind, width, span)?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D1, arrayed: false, class: crate::ImageClass::Sampled { kind, multi: false }, @@ -3239,7 +2568,7 @@ impl Parser { "texture_1d_array" => { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; Self::check_texture_sample_type(kind, width, span)?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D1, arrayed: true, class: crate::ImageClass::Sampled { kind, multi: false }, @@ -3248,7 +2577,7 @@ impl Parser { "texture_2d" => { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; Self::check_texture_sample_type(kind, width, span)?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Sampled { kind, multi: false }, @@ -3257,7 +2586,7 @@ impl Parser { "texture_2d_array" => { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; Self::check_texture_sample_type(kind, width, span)?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D2, arrayed: true, class: crate::ImageClass::Sampled { kind, multi: false }, @@ -3266,7 +2595,7 @@ impl Parser { "texture_3d" => { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; Self::check_texture_sample_type(kind, width, span)?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D3, arrayed: false, class: crate::ImageClass::Sampled { kind, multi: false }, @@ -3275,7 +2604,7 @@ impl Parser { "texture_cube" => { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; Self::check_texture_sample_type(kind, width, span)?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::Cube, arrayed: false, class: crate::ImageClass::Sampled { kind, multi: false }, @@ -3284,7 +2613,7 @@ impl Parser { "texture_cube_array" => { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; Self::check_texture_sample_type(kind, width, span)?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::Cube, arrayed: true, class: crate::ImageClass::Sampled { kind, multi: false }, @@ -3293,7 +2622,7 @@ impl Parser { "texture_multisampled_2d" => { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; Self::check_texture_sample_type(kind, width, span)?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Sampled { kind, multi: true }, @@ -3302,40 +2631,40 @@ impl Parser { "texture_multisampled_2d_array" => { let (kind, width, span) = lexer.next_scalar_generic_with_span()?; Self::check_texture_sample_type(kind, width, span)?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D2, arrayed: true, class: crate::ImageClass::Sampled { kind, multi: true }, } } - "texture_depth_2d" => crate::TypeInner::Image { + "texture_depth_2d" => ast::Type::Image { dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Depth { multi: false }, }, - "texture_depth_2d_array" => crate::TypeInner::Image { + "texture_depth_2d_array" => ast::Type::Image { dim: crate::ImageDimension::D2, arrayed: true, class: crate::ImageClass::Depth { multi: false }, }, - "texture_depth_cube" => crate::TypeInner::Image { + "texture_depth_cube" => ast::Type::Image { dim: crate::ImageDimension::Cube, arrayed: false, class: crate::ImageClass::Depth { multi: false }, }, - "texture_depth_cube_array" => crate::TypeInner::Image { + "texture_depth_cube_array" => ast::Type::Image { dim: crate::ImageDimension::Cube, arrayed: true, class: crate::ImageClass::Depth { multi: false }, }, - "texture_depth_multisampled_2d" => crate::TypeInner::Image { + "texture_depth_multisampled_2d" => ast::Type::Image { dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Depth { multi: true }, }, "texture_storage_1d" => { let (format, access) = lexer.next_format_generic()?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D1, arrayed: false, class: crate::ImageClass::Storage { format, access }, @@ -3343,7 +2672,7 @@ impl Parser { } "texture_storage_1d_array" => { let (format, access) = lexer.next_format_generic()?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D1, arrayed: true, class: crate::ImageClass::Storage { format, access }, @@ -3351,7 +2680,7 @@ impl Parser { } "texture_storage_2d" => { let (format, access) = lexer.next_format_generic()?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Storage { format, access }, @@ -3359,7 +2688,7 @@ impl Parser { } "texture_storage_2d_array" => { let (format, access) = lexer.next_format_generic()?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D2, arrayed: true, class: crate::ImageClass::Storage { format, access }, @@ -3367,7 +2696,7 @@ impl Parser { } "texture_storage_3d" => { let (format, access) = lexer.next_format_generic()?; - crate::TypeInner::Image { + ast::Type::Image { dim: crate::ImageDimension::D3, arrayed: false, class: crate::ImageClass::Storage { format, access }, @@ -3390,114 +2719,50 @@ impl Parser { } } - /// Parse type declaration of a given name and attribute. - #[allow(clippy::too_many_arguments)] - fn parse_type_decl_name<'a>( + /// Parse type declaration of a given name. + fn type_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - name: &'a str, - name_span: Span, - debug_name: Option<&'a str>, - attribute: TypeAttributes, - type_arena: &mut UniqueArena, - const_arena: &mut Arena, - ) -> Result, Error<'a>> { - Ok(match self.lookup_type.get(name) { - Some(&handle) => handle, - None => { - match self.parse_type_decl_impl(lexer, attribute, name, type_arena, const_arena)? { - Some(inner) => { - let span = name_span.start..lexer.end_byte_offset(); - type_arena.insert( - crate::Type { - name: debug_name.map(|s| s.to_string()), - inner, - }, - NagaSpan::from(span), - ) - } - None => return Err(Error::UnknownType(name_span)), - } - } - }) - } - - fn parse_type_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - debug_name: Option<&'a str>, - type_arena: &mut UniqueArena, - const_arena: &mut Arena, - ) -> Result, Error<'a>> { + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { self.push_rule_span(Rule::TypeDecl, lexer); - let attribute = TypeAttributes::default(); - if lexer.skip(Token::Attribute) { - let other = lexer.next(); - return Err(Error::Unexpected(other.1, ExpectedToken::TypeAttribute)); - } + let (name, span) = lexer.next_ident_with_span()?; + + let ty = match self.type_decl_impl(lexer, name, ctx.reborrow())? { + Some(ty) => ty, + None => { + ctx.unresolved.insert(ast::Dependency { + ident: name, + usage: span, + }); + ast::Type::User(ast::Ident { name, span }) + } + }; - let (name, name_span) = lexer.next_ident_with_span()?; - let handle = self.parse_type_decl_name( - lexer, - name, - name_span, - debug_name, - attribute, - type_arena, - const_arena, - )?; self.pop_rule_span(lexer); - // Only set span if it's the first occurrence of the type. - // Type spans therefore should only be used for errors in type declarations; - // use variable spans/expression spans/etc. otherwise + + let handle = ctx.types.append(ty, Span::UNDEFINED); Ok(handle) } - /// Parse an assignment statement (will also parse increment and decrement statements) - fn parse_assignment_statement<'a, 'out>( + fn assignment_op_and_rhs<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, - mut context: StatementContext<'a, '_, 'out>, - block: &mut crate::Block, - emitter: &mut super::Emitter, + mut ctx: ParseExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + target: Handle>, + span_start: usize, ) -> Result<(), Error<'a>> { use crate::BinaryOperator as Bo; - let span_start = lexer.start_byte_offset(); - emitter.start(context.expressions); - let (reference, lhs_span) = self - .parse_general_expression_for_reference(lexer, context.as_expression(block, emitter))?; let op = lexer.next(); - // The left hand side of an assignment must be a reference. - if !matches!( - op.0, - Token::Operation('=') - | Token::AssignmentOperation(_) - | Token::IncrementOperation - | Token::DecrementOperation - ) { - return Err(Error::Unexpected(lhs_span, ExpectedToken::Assignment)); - } else if !reference.is_reference { - let ty = if context.named_expressions.contains_key(&reference.handle) { - InvalidAssignmentType::ImmutableBinding - } else { - match *context.expressions.get_mut(reference.handle) { - crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, - _ => InvalidAssignmentType::Other, - } - }; - - return Err(Error::InvalidAssignment { span: lhs_span, ty }); - } - - let mut context = context.as_expression(block, emitter); - - let value = match op { + let (op, value) = match op { (Token::Operation('='), _) => { - self.parse_general_expression(lexer, context.reborrow())? + let value = self.general_expression(lexer, ctx.reborrow())?; + (None, value) } - (Token::AssignmentOperation(c), span) => { + (Token::AssignmentOperation(c), _) => { let op = match c { '<' => Bo::ShiftLeft, '>' => Bo::ShiftRight, @@ -3509,127 +2774,122 @@ impl Parser { '&' => Bo::And, '|' => Bo::InclusiveOr, '^' => Bo::ExclusiveOr, - //Note: `consume_token` shouldn't produce any other assignment ops + // Note: `consume_token` shouldn't produce any other assignment ops _ => unreachable!(), }; - let mut left = context.expressions.append( - crate::Expression::Load { - pointer: reference.handle, - }, - lhs_span.into(), - ); - let mut right = self.parse_general_expression(lexer, context.reborrow())?; - context.binary_op_splat(op, &mut left, &mut right)?; - - context - .expressions - .append(crate::Expression::Binary { op, left, right }, span.into()) + let value = self.general_expression(lexer, ctx.reborrow())?; + (Some(op), value) } token @ (Token::IncrementOperation | Token::DecrementOperation, _) => { let op = match token.0 { - Token::IncrementOperation => Bo::Add, - Token::DecrementOperation => Bo::Subtract, + Token::IncrementOperation => ast::StatementKind::Increment, + Token::DecrementOperation => ast::StatementKind::Decrement, _ => unreachable!(), }; - let op_span = token.1; - // prepare the typifier, but work around mutable borrowing... - let _ = context.resolve_type(reference.handle)?; - - let ty = context.typifier.get(reference.handle, context.types); - let (kind, width) = match *ty { - crate::TypeInner::ValuePointer { - size: None, - kind, - width, - .. - } => (kind, width), - crate::TypeInner::Pointer { base, .. } => match context.types[base].inner { - crate::TypeInner::Scalar { kind, width } => (kind, width), - _ => return Err(Error::BadIncrDecrReferenceType(lhs_span)), - }, - _ => return Err(Error::BadIncrDecrReferenceType(lhs_span)), - }; - let constant_inner = crate::ConstantInner::Scalar { - width, - value: match kind { - crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), - crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), - _ => return Err(Error::BadIncrDecrReferenceType(lhs_span)), - }, - }; - let constant = context.constants.append( - crate::Constant { - name: None, - specialization: None, - inner: constant_inner, - }, - crate::Span::default(), - ); - - let left = context.expressions.append( - crate::Expression::Load { - pointer: reference.handle, - }, - lhs_span.into(), - ); - let right = context.interrupt_emitter( - crate::Expression::Constant(constant), - crate::Span::default(), - ); - context.expressions.append( - crate::Expression::Binary { op, left, right }, - op_span.into(), - ) + let span = lexer.span_from(span_start); + block.stmts.push(ast::Statement { + kind: op(target), + span, + }); + return Ok(()); } - other => return Err(Error::Unexpected(other.1, ExpectedToken::SwitchItem)), + _ => return Err(Error::Unexpected(op.1, ExpectedToken::Assignment)), }; - let span_end = lexer.end_byte_offset(); - context - .block - .extend(context.emitter.finish(context.expressions)); - context.block.push( - crate::Statement::Store { - pointer: reference.handle, - value, - }, - NagaSpan::from(span_start..span_end), - ); + let span = lexer.span_from(span_start); + block.stmts.push(ast::Statement { + kind: ast::StatementKind::Assign { target, op, value }, + span, + }); Ok(()) } + /// Parse an assignment statement (will also parse increment and decrement statements) + fn assignment_statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ParseExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + let span_start = lexer.start_byte_offset(); + let target = self.general_expression(lexer, ctx.reborrow())?; + self.assignment_op_and_rhs(lexer, ctx, block, target, span_start) + } + /// Parse a function call statement. - fn parse_function_statement<'a, 'out>( + /// Expects `ident` to be consumed (not in the lexer). + fn function_statement<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, ident: &'a str, - mut context: ExpressionContext<'a, '_, 'out>, + ident_span: Span, + span_start: usize, + mut context: ParseExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, ) -> Result<(), Error<'a>> { self.push_rule_span(Rule::SingularExpr, lexer); - context.emitter.start(context.expressions); - if self - .parse_function_call_inner(lexer, ident, context.reborrow())? - .is_none() - { - let span = lexer.next().1; - return Err(Error::UnknownLocalFunction(span)); - } - context - .block - .extend(context.emitter.finish(context.expressions)); + + context.unresolved.insert(ast::Dependency { + ident, + usage: ident_span, + }); + let arguments = self.arguments(lexer, context.reborrow())?; + let span = lexer.span_from(span_start); + + block.stmts.push(ast::Statement { + kind: ast::StatementKind::Call { + function: ast::Ident { + name: ident, + span: ident_span, + }, + arguments, + }, + span, + }); + self.pop_rule_span(lexer); Ok(()) } - fn parse_statement<'a, 'out>( + fn function_call_or_assignment_statement<'a, 'out>( &mut self, lexer: &mut Lexer<'a>, - mut context: StatementContext<'a, '_, 'out>, - block: &'out mut crate::Block, - is_uniform_control_flow: bool, + mut context: ParseExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + let span_start = lexer.start_byte_offset(); + match lexer.peek() { + (Token::Word(name), span) => { + // A little hack for 2 token lookahead. + let cloned = lexer.clone(); + let _ = lexer.next(); + match lexer.peek() { + (Token::Paren('('), _) => self.function_statement( + lexer, + name, + span, + span_start, + context.reborrow(), + block, + ), + _ => { + *lexer = cloned; + self.assignment_statement(lexer, context.reborrow(), block) + } + } + } + _ => self.assignment_statement(lexer, context.reborrow(), block), + } + } + + fn statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ParseExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, ) -> Result<(), Error<'a>> { self.push_rule_span(Rule::Statement, lexer); match lexer.peek() { @@ -3639,296 +2899,151 @@ impl Parser { return Ok(()); } (Token::Paren('{'), _) => { - let body = self.parse_block(lexer, context, is_uniform_control_flow)?; - let span = self.pop_rule_span(lexer); - block.push(crate::Statement::Block(body), NagaSpan::from(span)); + let (inner, span) = self.block(lexer, ctx.reborrow())?; + block.stmts.push(ast::Statement { + kind: ast::StatementKind::Block(inner), + span, + }); + self.pop_rule_span(lexer); return Ok(()); } (Token::Word(word), _) => { - let mut emitter = super::Emitter::default(); - let statement = match word { + let kind = match word { "_" => { let _ = lexer.next(); - emitter.start(context.expressions); lexer.expect(Token::Operation('='))?; - self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?; + let expr = self.general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(';'))?; - block.extend(emitter.finish(context.expressions)); - None + + ast::StatementKind::Ignore(expr) } "let" => { let _ = lexer.next(); - emitter.start(context.expressions); - let (name, name_span) = lexer.next_ident_with_span()?; - if crate::keywords::wgsl::RESERVED.contains(&name) { - return Err(Error::ReservedKeyword(name_span)); - } + let name = lexer.next_ident()?; + let given_ty = if lexer.skip(Token::Separator(':')) { - let ty = self.parse_type_decl( - lexer, - None, - context.types, - context.constants, - )?; + let ty = self.type_decl(lexer, ctx.reborrow())?; Some(ty) } else { None }; lexer.expect(Token::Operation('='))?; - let expr_id = self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?; + let expr_id = self.general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(';'))?; - if let Some(ty) = given_ty { - // prepare the typifier, but work around mutable borrowing... - let _ = context - .as_expression(block, &mut emitter) - .resolve_type(expr_id)?; - let expr_inner = context.typifier.get(expr_id, context.types); - let given_inner = &context.types[ty].inner; - if !given_inner.equivalent(expr_inner, context.types) { - log::error!( - "Given type {:?} doesn't match expected {:?}", - given_inner, - expr_inner - ); - return Err(Error::InitializationTypeMismatch( - name_span, - expr_inner.to_wgsl(context.types, context.constants), - )); - } + + let handle = ctx.locals.append(ast::Local, name.span); + if let Some(old) = ctx.local_table.add(name.name, handle) { + return Err(Error::Redefinition { + previous: ctx.locals.get_span(old), + current: name.span, + }); } - block.extend(emitter.finish(context.expressions)); - context.symbol_table.add( + + ast::StatementKind::LocalDecl(ast::LocalDecl::Let(ast::Let { name, - TypedExpression { - handle: expr_id, - is_reference: false, - }, - ); - context - .named_expressions - .insert(expr_id, String::from(name)); - None + ty: given_ty, + init: expr_id, + handle, + })) } "var" => { let _ = lexer.next(); - enum Init { - Empty, - Constant(Handle), - Variable(Handle), - } - let (name, name_span) = lexer.next_ident_with_span()?; - if crate::keywords::wgsl::RESERVED.contains(&name) { - return Err(Error::ReservedKeyword(name_span)); - } - let given_ty = if lexer.skip(Token::Separator(':')) { - let ty = self.parse_type_decl( - lexer, - None, - context.types, - context.constants, - )?; + let name = lexer.next_ident()?; + let ty = if lexer.skip(Token::Separator(':')) { + let ty = self.type_decl(lexer, ctx.reborrow())?; Some(ty) } else { None }; - let (init, ty) = if lexer.skip(Token::Operation('=')) { - emitter.start(context.expressions); - let value = self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?; - block.extend(emitter.finish(context.expressions)); - - // prepare the typifier, but work around mutable borrowing... - let _ = context - .as_expression(block, &mut emitter) - .resolve_type(value)?; - - //TODO: share more of this code with `let` arm - let ty = match given_ty { - Some(ty) => { - let expr_inner = context.typifier.get(value, context.types); - let given_inner = &context.types[ty].inner; - if !given_inner.equivalent(expr_inner, context.types) { - log::error!( - "Given type {:?} doesn't match expected {:?}", - given_inner, - expr_inner - ); - return Err(Error::InitializationTypeMismatch( - name_span, - expr_inner.to_wgsl(context.types, context.constants), - )); - } - ty - } - None => { - // register the type, if needed - match context.typifier[value].clone() { - TypeResolution::Handle(ty) => ty, - TypeResolution::Value(inner) => context.types.insert( - crate::Type { name: None, inner }, - Default::default(), - ), - } - } - }; - - let init = match context.expressions[value] { - crate::Expression::Constant(handle) if is_uniform_control_flow => { - Init::Constant(handle) - } - _ => Init::Variable(value), - }; - (init, ty) + let init = if lexer.skip(Token::Operation('=')) { + let init = self.general_expression(lexer, ctx.reborrow())?; + Some(init) } else { - match given_ty { - Some(ty) => (Init::Empty, ty), - None => { - log::error!( - "Variable '{}' without an initializer needs a type", - name - ); - return Err(Error::MissingType(name_span)); - } - } + None }; lexer.expect(Token::Separator(';'))?; - let var_id = context.variables.append( - crate::LocalVariable { - name: Some(name.to_owned()), - ty, - init: match init { - Init::Constant(value) => Some(value), - _ => None, - }, - }, - NagaSpan::from(name_span), - ); - // Doesn't make sense to assign a span to cached lookup - let expr_id = context - .expressions - .append(crate::Expression::LocalVariable(var_id), Default::default()); - context.symbol_table.add( - name, - TypedExpression { - handle: expr_id, - is_reference: true, - }, - ); - - if let Init::Variable(value) = init { - Some(crate::Statement::Store { - pointer: expr_id, - value, - }) - } else { - None + let handle = ctx.locals.append(ast::Local, name.span); + if let Some(old) = ctx.local_table.add(name.name, handle) { + return Err(Error::Redefinition { + previous: ctx.locals.get_span(old), + current: name.span, + }); } + + ast::StatementKind::LocalDecl(ast::LocalDecl::Var(ast::LocalVariable { + name, + ty, + init, + handle, + })) } "return" => { let _ = lexer.next(); let value = if lexer.peek().0 != Token::Separator(';') { - emitter.start(context.expressions); - let handle = self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?; - block.extend(emitter.finish(context.expressions)); + let handle = self.general_expression(lexer, ctx.reborrow())?; Some(handle) } else { None }; lexer.expect(Token::Separator(';'))?; - Some(crate::Statement::Return { value }) + ast::StatementKind::Return { value } } "if" => { let _ = lexer.next(); - emitter.start(context.expressions); - let condition = self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?; - block.extend(emitter.finish(context.expressions)); + let condition = self.general_expression(lexer, ctx.reborrow())?; - let accept = self.parse_block(lexer, context.reborrow(), false)?; + let accept = self.block(lexer, ctx.reborrow())?.0; let mut elsif_stack = Vec::new(); let mut elseif_span_start = lexer.start_byte_offset(); let mut reject = loop { if !lexer.skip(Token::Word("else")) { - break crate::Block::new(); + break ast::Block::default(); } if !lexer.skip(Token::Word("if")) { // ... else { ... } - break self.parse_block(lexer, context.reborrow(), false)?; + break self.block(lexer, ctx.reborrow())?.0; } // ... else if (...) { ... } - let mut sub_emitter = super::Emitter::default(); - - sub_emitter.start(context.expressions); - let other_condition = self.parse_general_expression( - lexer, - context.as_expression(block, &mut sub_emitter), - )?; - let other_emit = sub_emitter.finish(context.expressions); - let other_block = self.parse_block(lexer, context.reborrow(), false)?; - elsif_stack.push(( - elseif_span_start, - other_condition, - other_emit, - other_block, - )); + let other_condition = self.general_expression(lexer, ctx.reborrow())?; + let other_block = self.block(lexer, ctx.reborrow())?; + elsif_stack.push((elseif_span_start, other_condition, other_block)); elseif_span_start = lexer.start_byte_offset(); }; - let span_end = lexer.end_byte_offset(); // reverse-fold the else-if blocks //Note: we may consider uplifting this to the IR - for (other_span_start, other_cond, other_emit, other_block) in + for (other_span_start, other_cond, other_block) in elsif_stack.into_iter().rev() { - let sub_stmt = crate::Statement::If { + let sub_stmt = ast::StatementKind::If { condition: other_cond, - accept: other_block, + accept: other_block.0, reject, }; - reject = crate::Block::new(); - reject.extend(other_emit); - reject.push(sub_stmt, NagaSpan::from(other_span_start..span_end)) + reject = ast::Block::default(); + let span = lexer.span_from(other_span_start); + reject.stmts.push(ast::Statement { + kind: sub_stmt, + span, + }) } - Some(crate::Statement::If { + ast::StatementKind::If { condition, accept, reject, - }) + } } "switch" => { let _ = lexer.next(); - emitter.start(context.expressions); - let selector = self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?; - let uint = Some(crate::ScalarKind::Uint) - == context - .as_expression(block, &mut emitter) - .resolve_type(selector)? - .scalar_kind(); - block.extend(emitter.finish(context.expressions)); + let selector = self.general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren('{'))?; let mut cases = Vec::new(); @@ -3937,38 +3052,39 @@ impl Parser { match lexer.next() { (Token::Word("case"), _) => { // parse a list of values - let value = loop { - let value = Self::parse_switch_value(lexer, uint)?; + let (value, value_span) = loop { + let (value, value_span) = Self::switch_value(lexer)?; if lexer.skip(Token::Separator(',')) { if lexer.skip(Token::Separator(':')) { - break value; + break (value, value_span); } } else { lexer.skip(Token::Separator(':')); - break value; + break (value, value_span); } - cases.push(crate::SwitchCase { + cases.push(ast::SwitchCase { value, - body: crate::Block::new(), + value_span, + body: ast::Block::default(), fall_through: true, }); }; - let body = - self.parse_block(lexer, context.reborrow(), false)?; - cases.push(crate::SwitchCase { + let body = self.block(lexer, ctx.reborrow())?.0; + + cases.push(ast::SwitchCase { value, + value_span, body, fall_through: false, }); } - (Token::Word("default"), _) => { + (Token::Word("default"), value_span) => { lexer.skip(Token::Separator(':')); - - let body = - self.parse_block(lexer, context.reborrow(), false)?; - cases.push(crate::SwitchCase { - value: crate::SwitchValue::Default, + let body = self.block(lexer, ctx.reborrow())?.0; + cases.push(ast::SwitchCase { + value: ast::SwitchValue::Default, + value_span, body, fall_through: false, }); @@ -3980,254 +3096,166 @@ impl Parser { } } - Some(crate::Statement::Switch { selector, cases }) + ast::StatementKind::Switch { selector, cases } } - "loop" => Some(self.parse_loop(lexer, context.reborrow(), &mut emitter)?), + "loop" => self.r#loop(lexer, ctx.reborrow())?, "while" => { let _ = lexer.next(); - let mut body = crate::Block::new(); + let mut body = ast::Block::default(); let (condition, span) = lexer.capture_span(|lexer| { - emitter.start(context.expressions); - let condition = self.parse_general_expression( - lexer, - context.as_expression(&mut body, &mut emitter), - )?; - body.extend(emitter.finish(context.expressions)); + let condition = self.general_expression(lexer, ctx.reborrow())?; Ok(condition) })?; - let mut reject = crate::Block::new(); - reject.push(crate::Statement::Break, NagaSpan::default()); - body.push( - crate::Statement::If { + let mut reject = ast::Block::default(); + reject.stmts.push(ast::Statement { + kind: ast::StatementKind::Break, + span, + }); + + body.stmts.push(ast::Statement { + kind: ast::StatementKind::If { condition, - accept: crate::Block::new(), + accept: ast::Block::default(), reject, }, - NagaSpan::from(span), - ); + span, + }); - body.extend_block(self.parse_block(lexer, context.reborrow(), false)?); + let (block, span) = self.block(lexer, ctx.reborrow())?; + body.stmts.push(ast::Statement { + kind: ast::StatementKind::Block(block), + span, + }); - Some(crate::Statement::Loop { + ast::StatementKind::Loop { body, - continuing: crate::Block::new(), + continuing: ast::Block::default(), break_if: None, - }) + } } "for" => { let _ = lexer.next(); lexer.expect(Token::Paren('('))?; - // Push a lexical scope for the for loop - context.symbol_table.push_scope(); + + ctx.local_table.push_scope(); if !lexer.skip(Token::Separator(';')) { - let num_statements = block.len(); + let num_statements = block.stmts.len(); let (_, span) = lexer.capture_span(|lexer| { - self.parse_statement( - lexer, - context.reborrow(), - block, - is_uniform_control_flow, - ) + self.statement(lexer, ctx.reborrow(), block) })?; - if block.len() != num_statements { - match *block.last().unwrap() { - crate::Statement::Store { .. } - | crate::Statement::Call { .. } => {} + if block.stmts.len() != num_statements { + match block.stmts.last().unwrap().kind { + ast::StatementKind::Call { .. } + | ast::StatementKind::Assign { .. } + | ast::StatementKind::LocalDecl(_) => {} _ => return Err(Error::InvalidForInitializer(span)), } } }; - let mut body = crate::Block::new(); + let mut body = ast::Block::default(); if !lexer.skip(Token::Separator(';')) { let (condition, span) = lexer.capture_span(|lexer| { - emitter.start(context.expressions); - let condition = self.parse_general_expression( - lexer, - context.as_expression(&mut body, &mut emitter), - )?; + let condition = self.general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(';'))?; - body.extend(emitter.finish(context.expressions)); Ok(condition) })?; - let mut reject = crate::Block::new(); - reject.push(crate::Statement::Break, NagaSpan::default()); - body.push( - crate::Statement::If { + let mut reject = ast::Block::default(); + reject.stmts.push(ast::Statement { + kind: ast::StatementKind::Break, + span, + }); + body.stmts.push(ast::Statement { + kind: ast::StatementKind::If { condition, - accept: crate::Block::new(), + accept: ast::Block::default(), reject, }, - NagaSpan::from(span), - ); + span, + }); }; - let mut continuing = crate::Block::new(); + let mut continuing = ast::Block::default(); if !lexer.skip(Token::Paren(')')) { - match lexer.peek().0 { - Token::Word(ident) - if context.symbol_table.lookup(ident).is_none() => - { - self.parse_function_statement( - lexer, - ident, - context.as_expression(&mut continuing, &mut emitter), - )? - } - _ => self.parse_assignment_statement( - lexer, - context.reborrow(), - &mut continuing, - &mut emitter, - )?, - } + self.function_call_or_assignment_statement( + lexer, + ctx.reborrow(), + &mut continuing, + )?; lexer.expect(Token::Paren(')'))?; } - body.extend_block(self.parse_block(lexer, context.reborrow(), false)?); + let (block, span) = self.block(lexer, ctx.reborrow())?; + body.stmts.push(ast::Statement { + kind: ast::StatementKind::Block(block), + span, + }); - // Pop the for loop lexical scope - context.symbol_table.pop_scope(); + ctx.local_table.pop_scope(); - Some(crate::Statement::Loop { + ast::StatementKind::Loop { body, continuing, break_if: None, - }) + } } "break" => { - let (_, mut span) = lexer.next(); + let (_, span) = lexer.next(); // Check if the next token is an `if`, this indicates // that the user tried to type out a `break if` which // is illegal in this position. let (peeked_token, peeked_span) = lexer.peek(); if let Token::Word("if") = peeked_token { - span.end = peeked_span.end; + let span = span.until(&peeked_span); return Err(Error::InvalidBreakIf(span)); } - Some(crate::Statement::Break) + ast::StatementKind::Break } "continue" => { let _ = lexer.next(); - Some(crate::Statement::Continue) + ast::StatementKind::Continue } "discard" => { let _ = lexer.next(); - Some(crate::Statement::Kill) - } - "storageBarrier" => { - let _ = lexer.next(); - lexer.expect(Token::Paren('('))?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Statement::Barrier(crate::Barrier::STORAGE)) - } - "workgroupBarrier" => { - let _ = lexer.next(); - lexer.expect(Token::Paren('('))?; - lexer.expect(Token::Paren(')'))?; - Some(crate::Statement::Barrier(crate::Barrier::WORK_GROUP)) - } - "atomicStore" => { - let _ = lexer.next(); - emitter.start(context.expressions); - lexer.open_arguments()?; - let mut expression_ctx = context.as_expression(block, &mut emitter); - let pointer = - self.parse_atomic_pointer(lexer, expression_ctx.reborrow())?; - lexer.expect(Token::Separator(','))?; - let value = self.parse_general_expression(lexer, expression_ctx)?; - lexer.close_arguments()?; - block.extend(emitter.finish(context.expressions)); - Some(crate::Statement::Store { pointer, value }) - } - "textureStore" => { - let _ = lexer.next(); - emitter.start(context.expressions); - lexer.open_arguments()?; - let mut expr_context = context.as_expression(block, &mut emitter); - let (image, image_span) = self - .parse_general_expression_with_span(lexer, expr_context.reborrow())?; - lexer.expect(Token::Separator(','))?; - let arrayed = match *expr_context.resolve_type(image)? { - crate::TypeInner::Image { arrayed, .. } => arrayed, - _ => return Err(Error::BadTexture(image_span)), - }; - let coordinate = self.parse_general_expression(lexer, expr_context)?; - let array_index = if arrayed { - lexer.expect(Token::Separator(','))?; - Some(self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?) - } else { - None - }; - lexer.expect(Token::Separator(','))?; - let value = self.parse_general_expression( - lexer, - context.as_expression(block, &mut emitter), - )?; - lexer.close_arguments()?; - block.extend(emitter.finish(context.expressions)); - Some(crate::Statement::ImageStore { - image, - coordinate, - array_index, - value, - }) + ast::StatementKind::Kill } // assignment or a function call - ident => { - match context.symbol_table.lookup(ident) { - Some(_) => self.parse_assignment_statement( - lexer, - context, - block, - &mut emitter, - )?, - None => self.parse_function_statement( - lexer, - ident, - context.as_expression(block, &mut emitter), - )?, - } + _ => { + self.function_call_or_assignment_statement(lexer, ctx.reborrow(), block)?; lexer.expect(Token::Separator(';'))?; - None + self.pop_rule_span(lexer); + return Ok(()); } }; - let span = NagaSpan::from(self.pop_rule_span(lexer)); - if let Some(statement) = statement { - block.push(statement, span); - } + + let span = self.pop_rule_span(lexer); + block.stmts.push(ast::Statement { kind, span }); } _ => { - let mut emitter = super::Emitter::default(); - self.parse_assignment_statement(lexer, context, block, &mut emitter)?; + self.assignment_statement(lexer, ctx.reborrow(), block)?; self.pop_rule_span(lexer); } } Ok(()) } - fn parse_loop<'a>( + fn r#loop<'a>( &mut self, lexer: &mut Lexer<'a>, - mut context: StatementContext<'a, '_, '_>, - emitter: &mut super::Emitter, - ) -> Result> { + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { let _ = lexer.next(); - let mut body = crate::Block::new(); - let mut continuing = crate::Block::new(); + let mut body = ast::Block::default(); + let mut continuing = ast::Block::default(); let mut break_if = None; - // Push a lexical scope for the loop body - context.symbol_table.push_scope(); - lexer.expect(Token::Paren('{'))?; + ctx.local_table.push_scope(); + loop { if lexer.skip(Token::Word("continuing")) { // Branch for the `continuing` block, this must be @@ -4245,19 +3273,12 @@ impl Parser { // the break if lexer.expect(Token::Word("if"))?; - // Start the emitter to begin parsing an expression - emitter.start(context.expressions); - let condition = self.parse_general_expression( - lexer, - context.as_expression(&mut body, emitter), - )?; - // Add all emits to the continuing body - continuing.extend(emitter.finish(context.expressions)); + let condition = self.general_expression(lexer, ctx.reborrow())?; // Set the condition of the break if to the newly parsed // expression break_if = Some(condition); - // Expext a semicolon to close the statement + // Expect a semicolon to close the statement lexer.expect(Token::Separator(';'))?; // Expect a closing brace to close the continuing block, // since the break if must be the last statement @@ -4270,7 +3291,7 @@ impl Parser { break; } else { // Otherwise try to parse a statement - self.parse_statement(lexer, context.reborrow(), &mut continuing, false)?; + self.statement(lexer, ctx.reborrow(), &mut continuing)?; } } // Since the continuing block must be the last part of the loop body, @@ -4284,13 +3305,12 @@ impl Parser { break; } // Otherwise try to parse a statement - self.parse_statement(lexer, context.reborrow(), &mut body, false)?; + self.statement(lexer, ctx.reborrow(), &mut body)?; } - // Pop the loop body lexical scope - context.symbol_table.pop_scope(); + ctx.local_table.pop_scope(); - Ok(crate::Statement::Loop { + Ok(ast::StatementKind::Loop { body, continuing, break_if, @@ -4298,34 +3318,28 @@ impl Parser { } /// compound_statement - fn parse_block<'a>( + fn block<'a>( &mut self, lexer: &mut Lexer<'a>, - mut context: StatementContext<'a, '_, '_>, - is_uniform_control_flow: bool, - ) -> Result> { + mut ctx: ParseExpressionContext<'a, '_, '_>, + ) -> Result<(ast::Block<'a>, Span), Error<'a>> { self.push_rule_span(Rule::Block, lexer); - // Push a lexical scope for the block - context.symbol_table.push_scope(); - lexer.expect(Token::Paren('{'))?; - let mut block = crate::Block::new(); + ctx.local_table.push_scope(); + + let _ = lexer.next(); + let mut statements = ast::Block::default(); while !lexer.skip(Token::Paren('}')) { - self.parse_statement( - lexer, - context.reborrow(), - &mut block, - is_uniform_control_flow, - )?; + self.statement(lexer, ctx.reborrow(), &mut statements)?; } - // Pop the block lexical scope - context.symbol_table.pop_scope(); - self.pop_rule_span(lexer); - Ok(block) + ctx.local_table.pop_scope(); + + let span = self.pop_rule_span(lexer); + Ok((statements, span)) } - fn parse_varying_binding<'a>( + fn varying_binding<'a>( &mut self, lexer: &mut Lexer<'a>, ) -> Result, Error<'a>> { @@ -4341,48 +3355,26 @@ impl Parser { bind_parser.finish(span) } - fn parse_function_decl<'a>( + fn function_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - module: &mut crate::Module, - lookup_global_expression: &FastHashMap<&'a str, crate::Expression>, - ) -> Result<(crate::Function, &'a str), Error<'a>> { + out: &mut ast::TranslationUnit<'a>, + dependencies: &mut FastHashSet>, + ) -> Result, Error<'a>> { self.push_rule_span(Rule::FunctionDecl, lexer); // read function name - let mut symbol_table = super::SymbolTable::default(); - let (fun_name, span) = lexer.next_ident_with_span()?; - if crate::keywords::wgsl::RESERVED.contains(&fun_name) { - return Err(Error::ReservedKeyword(span)); - } - if let Some(entry) = self - .module_scope_identifiers - .insert(String::from(fun_name), span.clone()) - { - return Err(Error::Redefinition { - previous: entry, - current: span, - }); - } - // populate initial expressions - let mut expressions = Arena::new(); - for (&name, expression) in lookup_global_expression.iter() { - let (span, is_reference) = match *expression { - crate::Expression::GlobalVariable(handle) => ( - module.global_variables.get_span(handle), - module.global_variables[handle].space != crate::AddressSpace::Handle, - ), - crate::Expression::Constant(handle) => (module.constants.get_span(handle), false), - _ => unreachable!(), - }; - let expression = expressions.append(expression.clone(), span); - symbol_table.add( - name, - TypedExpression { - handle: expression, - is_reference, - }, - ); - } + let fun_name = lexer.next_ident()?; + + let mut locals = Arena::new(); + + let mut ctx = ParseExpressionContext { + expressions: &mut out.expressions, + local_table: &mut super::SymbolTable::default(), + locals: &mut locals, + types: &mut out.types, + unresolved: dependencies, + }; + // read parameter list let mut arguments = Vec::new(); lexer.expect(Token::Paren('('))?; @@ -4394,92 +3386,55 @@ impl Parser { ExpectedToken::Token(Token::Separator(',')), )); } - let mut binding = self.parse_varying_binding(lexer)?; - let (param_name, param_name_span, param_type) = - self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?; - if crate::keywords::wgsl::RESERVED.contains(¶m_name) { - return Err(Error::ReservedKeyword(param_name_span)); - } - let param_index = arguments.len() as u32; - let expression = expressions.append( - crate::Expression::FunctionArgument(param_index), - NagaSpan::from(param_name_span), - ); - symbol_table.add( - param_name, - TypedExpression { - handle: expression, - is_reference: false, - }, - ); - if let Some(ref mut binding) = binding { - binding.apply_default_interpolation(&module.types[param_type].inner); - } - arguments.push(crate::FunctionArgument { - name: Some(param_name.to_string()), + let binding = self.varying_binding(lexer)?; + + let param_name = lexer.next_ident()?; + + lexer.expect(Token::Separator(':'))?; + let param_type = self.type_decl(lexer, ctx.reborrow())?; + + let handle = ctx.locals.append(ast::Local, param_name.span); + ctx.local_table.add(param_name.name, handle); + arguments.push(ast::FunctionArgument { + name: param_name, ty: param_type, binding, + handle, }); ready = lexer.skip(Token::Separator(',')); } // read return type let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { - let mut binding = self.parse_varying_binding(lexer)?; - let ty = self.parse_type_decl(lexer, None, &mut module.types, &mut module.constants)?; - if let Some(ref mut binding) = binding { - binding.apply_default_interpolation(&module.types[ty].inner); - } - Some(crate::FunctionResult { ty, binding }) + let binding = self.varying_binding(lexer)?; + let ty = self.type_decl(lexer, ctx.reborrow())?; + Some(ast::FunctionResult { ty, binding }) } else { None }; - let mut fun = crate::Function { - name: Some(fun_name.to_string()), + // read body + let body = self.block(lexer, ctx)?.0; + + let fun = ast::Function { + entry_point: None, + name: fun_name, arguments, result, - local_variables: Arena::new(), - expressions, - named_expressions: crate::NamedExpressions::default(), - body: crate::Block::new(), + body, + locals, }; - // read body - let mut typifier = super::Typifier::new(); - let mut named_expressions = crate::FastHashMap::default(); - fun.body = self.parse_block( - lexer, - StatementContext { - symbol_table: &mut symbol_table, - typifier: &mut typifier, - variables: &mut fun.local_variables, - expressions: &mut fun.expressions, - named_expressions: &mut named_expressions, - types: &mut module.types, - constants: &mut module.constants, - global_vars: &module.global_variables, - functions: &module.functions, - arguments: &fun.arguments, - }, - true, - )?; - // fixup the IR - ensure_block_returns(&mut fun.body); // done self.pop_rule_span(lexer); - // Set named expressions after block parsing ends - fun.named_expressions = named_expressions; - - Ok((fun, fun_name)) + Ok(fun) } - fn parse_global_decl<'a>( + fn global_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - module: &mut crate::Module, - lookup_global_expression: &mut FastHashMap<&'a str, crate::Expression>, - ) -> Result> { + out: &mut ast::TranslationUnit<'a>, + ) -> Result<(), Error<'a>> { // read attributes let mut binding = None; let mut stage = None; @@ -4492,12 +3447,12 @@ impl Parser { match lexer.next_ident_with_span()? { ("binding", _) => { lexer.expect(Token::Paren('('))?; - bind_index = Some(Self::parse_non_negative_i32_literal(lexer)?); + bind_index = Some(Self::non_negative_i32_literal(lexer)?); lexer.expect(Token::Paren(')'))?; } ("group", _) => { lexer.expect(Token::Paren('('))?; - bind_group = Some(Self::parse_non_negative_i32_literal(lexer)?); + bind_group = Some(Self::non_negative_i32_literal(lexer)?); lexer.expect(Token::Paren(')'))?; } ("vertex", _) => { @@ -4513,7 +3468,7 @@ impl Parser { lexer.expect(Token::Paren('('))?; workgroup_size = [1u32; 3]; for (i, size) in workgroup_size.iter_mut().enumerate() { - *size = Self::parse_generic_non_negative_int_literal(lexer)?; + *size = Self::generic_non_negative_int_literal(lexer)?; match lexer.next() { (Token::Paren(')'), _) => break, (Token::Separator(','), _) if i != 2 => (), @@ -4554,162 +3509,84 @@ impl Parser { (None, None) => {} } - // read items + let mut dependencies = FastHashSet::default(); + let mut ctx = ParseExpressionContext { + expressions: &mut out.expressions, + local_table: &mut super::SymbolTable::default(), + locals: &mut Arena::new(), + types: &mut out.types, + unresolved: &mut dependencies, + }; + + // read item let start = lexer.start_byte_offset(); - match lexer.next() { - (Token::Separator(';'), _) => {} + let kind = match lexer.next() { + (Token::Separator(';'), _) => None, (Token::Word("struct"), _) => { - let (name, span) = lexer.next_ident_with_span()?; - if crate::keywords::wgsl::RESERVED.contains(&name) { - return Err(Error::ReservedKeyword(span)); - } - let (members, span) = - self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?; - let type_span = NagaSpan::from(lexer.span_from(start)); - let ty = module.types.insert( - crate::Type { - name: Some(name.to_string()), - inner: crate::TypeInner::Struct { members, span }, - }, - type_span, - ); - self.lookup_type.insert(name.to_owned(), ty); + let name = lexer.next_ident()?; + + let members = self.struct_body(lexer, ctx)?; + Some(ast::GlobalDeclKind::Struct(ast::Struct { name, members })) } (Token::Word("type"), _) => { let name = lexer.next_ident()?; + lexer.expect(Token::Operation('='))?; - let ty = self.parse_type_decl( - lexer, - Some(name), - &mut module.types, - &mut module.constants, - )?; - self.lookup_type.insert(name.to_owned(), ty); + let ty = self.type_decl(lexer, ctx)?; lexer.expect(Token::Separator(';'))?; + Some(ast::GlobalDeclKind::Type(ast::TypeAlias { name, ty })) } - (Token::Word("let"), _) => { - let (name, name_span) = lexer.next_ident_with_span()?; - if crate::keywords::wgsl::RESERVED.contains(&name) { - return Err(Error::ReservedKeyword(name_span)); - } - if let Some(entry) = self - .module_scope_identifiers - .insert(String::from(name), name_span.clone()) - { - return Err(Error::Redefinition { - previous: entry, - current: name_span, - }); - } - let given_ty = if lexer.skip(Token::Separator(':')) { - let ty = self.parse_type_decl( - lexer, - None, - &mut module.types, - &mut module.constants, - )?; + (Token::Word("const"), _) => { + let name = lexer.next_ident()?; + + let ty = if lexer.skip(Token::Separator(':')) { + let ty = self.type_decl(lexer, ctx.reborrow())?; Some(ty) } else { None }; lexer.expect(Token::Operation('='))?; - let first_token_span = lexer.next(); - let const_handle = self.parse_const_expression_impl( - first_token_span, - lexer, - Some(name), - &mut module.types, - &mut module.constants, - )?; - - if let Some(explicit_ty) = given_ty { - let con = &module.constants[const_handle]; - let type_match = match con.inner { - crate::ConstantInner::Scalar { width, value } => { - module.types[explicit_ty].inner - == crate::TypeInner::Scalar { - kind: value.scalar_kind(), - width, - } - } - crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty, - }; - if !type_match { - let expected_inner_str = match con.inner { - crate::ConstantInner::Scalar { width, value } => { - crate::TypeInner::Scalar { - kind: value.scalar_kind(), - width, - } - .to_wgsl(&module.types, &module.constants) - } - crate::ConstantInner::Composite { .. } => module.types[explicit_ty] - .inner - .to_wgsl(&module.types, &module.constants), - }; - return Err(Error::InitializationTypeMismatch( - name_span, - expected_inner_str, - )); - } - } - + let init = self.general_expression(lexer, ctx)?; lexer.expect(Token::Separator(';'))?; - lookup_global_expression.insert(name, crate::Expression::Constant(const_handle)); + + Some(ast::GlobalDeclKind::Const(ast::Const { name, ty, init })) } (Token::Word("var"), _) => { - let pvar = - self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?; - if crate::keywords::wgsl::RESERVED.contains(&pvar.name) { - return Err(Error::ReservedKeyword(pvar.name_span)); - } - if let Some(entry) = self - .module_scope_identifiers - .insert(String::from(pvar.name), pvar.name_span.clone()) - { - return Err(Error::Redefinition { - previous: entry, - current: pvar.name_span, - }); - } - let var_handle = module.global_variables.append( - crate::GlobalVariable { - name: Some(pvar.name.to_owned()), - space: pvar.space.unwrap_or(crate::AddressSpace::Handle), - binding: binding.take(), - ty: pvar.ty, - init: pvar.init, - }, - NagaSpan::from(pvar.name_span), - ); - lookup_global_expression - .insert(pvar.name, crate::Expression::GlobalVariable(var_handle)); + let mut var = self.variable_decl(lexer, ctx)?; + var.binding = binding.take(); + Some(ast::GlobalDeclKind::Var(var)) } (Token::Word("fn"), _) => { - let (function, name) = - self.parse_function_decl(lexer, module, lookup_global_expression)?; - match stage { - Some(stage) => module.entry_points.push(crate::EntryPoint { - name: name.to_string(), + let function = self.function_decl(lexer, out, &mut dependencies)?; + Some(ast::GlobalDeclKind::Fn(ast::Function { + entry_point: stage.map(|stage| ast::EntryPoint { stage, early_depth_test, workgroup_size, - function, }), - None => { - module - .functions - .append(function, NagaSpan::from(lexer.span_from(start))); - } - } + ..function + })) } - (Token::End, _) => return Ok(false), + (Token::End, _) => return Ok(()), other => return Err(Error::Unexpected(other.1, ExpectedToken::GlobalItem)), + }; + + if let Some(kind) = kind { + out.decls.append( + ast::GlobalDecl { kind, dependencies }, + lexer.span_from(start), + ); } + if !self.rules.is_empty() { + log::error!("Reached the end of global decl, but rule stack is not empty"); + log::error!("Rules: {:?}", self.rules); + return Err(Error::Other); + }; + match binding { - None => Ok(true), + None => Ok(()), // we had the attribute but no var? Some(_) => Err(Error::Other), } @@ -4718,22 +3595,1850 @@ impl Parser { pub fn parse(&mut self, source: &str) -> Result { self.reset(); - let mut module = crate::Module::default(); let mut lexer = Lexer::new(source); - let mut lookup_global_expression = FastHashMap::default(); + let mut tu = ast::TranslationUnit::default(); loop { - match self.parse_global_decl(&mut lexer, &mut module, &mut lookup_global_expression) { + match self.global_decl(&mut lexer, &mut tu) { Err(error) => return Err(error.as_parse_error(lexer.source)), - Ok(true) => {} - Ok(false) => { - if !self.rules.is_empty() { - log::error!("Reached the end of file, but rule stack is not empty"); - return Err(Error::Other.as_parse_error(lexer.source)); - }; - return Ok(module); + Ok(()) => { + if lexer.peek().0 == Token::End { + break; + } } } } + + let index = index::Index::generate(&tu).map_err(|x| x.as_parse_error(source))?; + let module = Lowerer::new(&index) + .lower(&tu) + .map_err(|x| x.as_parse_error(source))?; + + Ok(module) + } +} + +/// An `ast::GlobalDecl` for which we have built the Naga IR equivalent. +enum LoweredGlobalDecl { + Function(Handle), + Var(Handle), + Const(Handle), + Type(Handle), + EntryPoint, +} + +enum ConstantOrInner { + Constant(Handle), + Inner(crate::ConstantInner), +} + +enum Texture { + Gather, + GatherCompare, + + Sample, + SampleBias, + SampleCompare, + SampleCompareLevel, + SampleGrad, + SampleLevel, + // SampleBaseClampToEdge, +} + +impl Texture { + pub fn map(word: &str) -> Option { + Some(match word { + "textureGather" => Self::Gather, + "textureGatherCompare" => Self::GatherCompare, + + "textureSample" => Self::Sample, + "textureSampleBias" => Self::SampleBias, + "textureSampleCompare" => Self::SampleCompare, + "textureSampleCompareLevel" => Self::SampleCompareLevel, + "textureSampleGrad" => Self::SampleGrad, + "textureSampleLevel" => Self::SampleLevel, + // "textureSampleBaseClampToEdge" => Some(Self::SampleBaseClampToEdge), + _ => return None, + }) + } + + pub const fn min_argument_count(&self) -> u32 { + match *self { + Self::Gather => 3, + Self::GatherCompare => 4, + + Self::Sample => 3, + Self::SampleBias => 5, + Self::SampleCompare => 5, + Self::SampleCompareLevel => 5, + Self::SampleGrad => 6, + Self::SampleLevel => 5, + // Self::SampleBaseClampToEdge => 3, + } + } +} + +struct Lowerer<'source, 'temp> { + index: &'temp index::Index<'source>, + layouter: Layouter, +} + +impl<'source, 'temp> Lowerer<'source, 'temp> { + pub fn new(index: &'temp index::Index<'source>) -> Self { + Self { + index, + layouter: Layouter::default(), + } + } + + pub fn lower( + &mut self, + tu: &'temp ast::TranslationUnit<'source>, + ) -> Result> { + let mut module = crate::Module::default(); + + let mut ctx = OutputContext { + ast_expressions: &tu.expressions, + globals: &mut FastHashMap::default(), + types: &tu.types, + module: &mut module, + }; + + for decl in self.index.visit_ordered() { + let span = tu.decls.get_span(decl); + let decl = &tu.decls[decl]; + + match decl.kind { + ast::GlobalDeclKind::Fn(ref f) => { + let decl = self.function(f, span, ctx.reborrow())?; + ctx.globals.insert(f.name.name, decl); + } + ast::GlobalDeclKind::Var(ref v) => { + let ty = self.resolve_ast_type(v.ty, ctx.reborrow())?; + + let init = v + .init + .map(|init| self.constant(init, ctx.reborrow())) + .transpose()?; + + let handle = ctx.module.global_variables.append( + crate::GlobalVariable { + name: Some(v.name.name.to_string()), + space: v.space, + binding: v.binding.clone(), + ty, + init, + }, + span, + ); + + ctx.globals + .insert(v.name.name, LoweredGlobalDecl::Var(handle)); + } + ast::GlobalDeclKind::Const(ref c) => { + let inner = self.constant_inner(c.init, ctx.reborrow())?; + let inner = match inner { + ConstantOrInner::Constant(c) => ctx.module.constants[c].inner.clone(), + ConstantOrInner::Inner(inner) => inner, + }; + + let inferred_type = match inner { + crate::ConstantInner::Scalar { width, value } => { + ctx.ensure_type_exists(crate::TypeInner::Scalar { + width, + kind: value.scalar_kind(), + }) + } + crate::ConstantInner::Composite { ty, .. } => ty, + }; + + let handle = ctx.module.constants.append( + crate::Constant { + name: Some(c.name.name.to_string()), + specialization: None, + inner, + }, + span, + ); + + let explicit_ty = + c.ty.map(|ty| self.resolve_ast_type(ty, ctx.reborrow())) + .transpose()?; + + if let Some(explicit) = explicit_ty { + if explicit != inferred_type { + let ty = &ctx.module.types[explicit]; + let explicit = ty.name.clone().unwrap_or_else(|| { + ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) + }); + + let ty = &ctx.module.types[inferred_type]; + let inferred = ty.name.clone().unwrap_or_else(|| { + ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) + }); + + return Err(Error::InitializationTypeMismatch( + c.name.span, + explicit, + inferred, + )); + } + } + + ctx.globals + .insert(c.name.name, LoweredGlobalDecl::Const(handle)); + } + ast::GlobalDeclKind::Struct(ref s) => { + let handle = self.r#struct(s, span, ctx.reborrow())?; + ctx.globals + .insert(s.name.name, LoweredGlobalDecl::Type(handle)); + } + ast::GlobalDeclKind::Type(ref alias) => { + let ty = self.resolve_ast_type(alias.ty, ctx.reborrow())?; + ctx.globals + .insert(alias.name.name, LoweredGlobalDecl::Type(ty)); + } + } + } + + Ok(module) + } + + fn function( + &mut self, + f: &ast::Function<'source>, + span: Span, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result> { + let mut local_table = FastHashMap::default(); + let mut local_variables = Arena::new(); + let mut expressions = Arena::new(); + let mut named_expressions = crate::NamedExpressions::default(); + + let arguments = f + .arguments + .iter() + .enumerate() + .map(|(i, arg)| { + let ty = self.resolve_ast_type(arg.ty, ctx.reborrow())?; + let expr = expressions + .append(crate::Expression::FunctionArgument(i as u32), arg.name.span); + local_table.insert(arg.handle, TypedExpression::non_reference(expr)); + named_expressions.insert(expr, arg.name.name.to_string()); + + Ok(crate::FunctionArgument { + name: Some(arg.name.name.to_string()), + ty, + binding: self.interpolate_default(&arg.binding, ty, ctx.reborrow()), + }) + }) + .collect::, _>>()?; + + let result = f + .result + .as_ref() + .map(|res| { + self.resolve_ast_type(res.ty, ctx.reborrow()) + .map(|ty| crate::FunctionResult { + ty, + binding: self.interpolate_default(&res.binding, ty, ctx.reborrow()), + }) + }) + .transpose()?; + + let mut typifier = super::Typifier::default(); + let mut body = self.block( + &f.body, + StatementContext { + local_table: &mut local_table, + globals: ctx.globals, + ast_expressions: ctx.ast_expressions, + typifier: &mut typifier, + variables: &mut local_variables, + naga_expressions: &mut expressions, + named_expressions: &mut named_expressions, + types: ctx.types, + module: ctx.module, + arguments: &arguments, + }, + )?; + ensure_block_returns(&mut body); + + let function = crate::Function { + name: Some(f.name.name.to_string()), + arguments, + result, + local_variables, + expressions, + named_expressions, + body, + }; + + if let Some(ref entry) = f.entry_point { + ctx.module.entry_points.push(crate::EntryPoint { + name: f.name.name.to_string(), + stage: entry.stage, + early_depth_test: entry.early_depth_test, + workgroup_size: entry.workgroup_size, + function, + }); + Ok(LoweredGlobalDecl::EntryPoint) + } else { + let handle = ctx.module.functions.append(function, span); + Ok(LoweredGlobalDecl::Function(handle)) + } + } + + fn block( + &mut self, + b: &ast::Block<'source>, + mut ctx: StatementContext<'source, '_, '_>, + ) -> Result> { + let mut block = crate::Block::default(); + + for stmt in b.stmts.iter() { + self.statement(stmt, &mut block, ctx.reborrow())?; + } + + Ok(block) + } + + fn statement( + &mut self, + stmt: &ast::Statement<'source>, + block: &mut crate::Block, + mut ctx: StatementContext<'source, '_, '_>, + ) -> Result<(), Error<'source>> { + let out = match stmt.kind { + ast::StatementKind::Block(ref block) => { + let block = self.block(block, ctx.reborrow())?; + crate::Statement::Block(block) + } + ast::StatementKind::LocalDecl(ref decl) => match *decl { + ast::LocalDecl::Let(ref l) => { + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + + let value = self.expression(l.init, ctx.as_expression(block, &mut emitter))?; + + let explicit_ty = + l.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) + .transpose()?; + + if let Some(ty) = explicit_ty { + let mut ctx = ctx.as_expression(block, &mut emitter); + let init_ty = ctx.register_type(value)?; + if !ctx.module.types[ty] + .inner + .equivalent(&ctx.module.types[init_ty].inner, &ctx.module.types) + { + return Err(Error::InitializationTypeMismatch( + l.name.span, + ctx.format_type(ty), + ctx.format_type(init_ty), + )); + } + } + + block.extend(emitter.finish(ctx.naga_expressions)); + ctx.local_table + .insert(l.handle, TypedExpression::non_reference(value)); + ctx.named_expressions.insert(value, l.name.name.to_string()); + + return Ok(()); + } + ast::LocalDecl::Var(ref v) => { + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + + let initializer = match v.init { + Some(init) => { + let initializer = + self.expression(init, ctx.as_expression(block, &mut emitter))?; + ctx.as_expression(block, &mut emitter) + .grow_types(initializer)?; + Some(initializer) + } + None => None, + }; + + let explicit_ty = + v.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) + .transpose()?; + + let ty = match (explicit_ty, initializer) { + (Some(explicit), Some(initializer)) => { + let ctx = ctx.as_expression(block, &mut emitter); + let initializer_ty = ctx.resolved_inner(initializer); + if !ctx.module.types[explicit] + .inner + .equivalent(initializer_ty, &ctx.module.types) + { + return Err(Error::InitializationTypeMismatch( + v.name.span, + ctx.format_type(explicit), + ctx.format_typeinner(initializer_ty), + )); + } + explicit + } + (Some(explicit), None) => explicit, + (None, Some(initializer)) => ctx + .as_expression(block, &mut emitter) + .register_type(initializer)?, + (None, None) => { + return Err(Error::MissingType(v.name.span)); + } + }; + + let var = ctx.variables.append( + crate::LocalVariable { + name: Some(v.name.name.to_string()), + ty, + init: None, + }, + stmt.span, + ); + + let handle = ctx + .as_expression(block, &mut emitter) + .interrupt_emitter(crate::Expression::LocalVariable(var), Span::UNDEFINED); + block.extend(emitter.finish(ctx.naga_expressions)); + ctx.local_table.insert( + v.handle, + TypedExpression { + handle, + is_reference: true, + }, + ); + + match initializer { + Some(initializer) => crate::Statement::Store { + pointer: handle, + value: initializer, + }, + None => return Ok(()), + } + } + }, + ast::StatementKind::If { + condition, + ref accept, + ref reject, + } => { + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + + let condition = + self.expression(condition, ctx.as_expression(block, &mut emitter))?; + block.extend(emitter.finish(ctx.naga_expressions)); + + let accept = self.block(accept, ctx.reborrow())?; + let reject = self.block(reject, ctx.reborrow())?; + + crate::Statement::If { + condition, + accept, + reject, + } + } + ast::StatementKind::Switch { + selector, + ref cases, + } => { + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + + let mut ectx = ctx.as_expression(block, &mut emitter); + let selector = self.expression(selector, ectx.reborrow())?; + + ectx.grow_types(selector)?; + let uint = + ectx.resolved_inner(selector).scalar_kind() == Some(crate::ScalarKind::Uint); + block.extend(emitter.finish(ctx.naga_expressions)); + + let cases = cases + .iter() + .map(|case| { + Ok(crate::SwitchCase { + value: match case.value { + ast::SwitchValue::I32(num) if !uint => { + crate::SwitchValue::Integer(num) + } + ast::SwitchValue::U32(num) if uint => { + crate::SwitchValue::Integer(num as i32) + } + ast::SwitchValue::Default => crate::SwitchValue::Default, + _ => { + return Err(Error::InvalidSwitchValue { + uint, + span: case.value_span, + }); + } + }, + body: self.block(&case.body, ctx.reborrow())?, + fall_through: case.fall_through, + }) + }) + .collect::>()?; + + crate::Statement::Switch { selector, cases } + } + ast::StatementKind::Loop { + ref body, + ref continuing, + break_if, + } => { + let body = self.block(body, ctx.reborrow())?; + let mut continuing = self.block(continuing, ctx.reborrow())?; + + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + let break_if = break_if + .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) + .transpose()?; + continuing.extend(emitter.finish(ctx.naga_expressions)); + + crate::Statement::Loop { + body, + continuing, + break_if, + } + } + ast::StatementKind::Break => crate::Statement::Break, + ast::StatementKind::Continue => crate::Statement::Continue, + ast::StatementKind::Return { value } => { + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + + let value = value + .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) + .transpose()?; + block.extend(emitter.finish(ctx.naga_expressions)); + + crate::Statement::Return { value } + } + ast::StatementKind::Kill => crate::Statement::Kill, + ast::StatementKind::Call { + ref function, + ref arguments, + } => { + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + + let _ = self.call( + stmt.span, + function, + arguments, + ctx.as_expression(block, &mut emitter), + )?; + block.extend(emitter.finish(ctx.naga_expressions)); + return Ok(()); + } + ast::StatementKind::Assign { target, op, value } => { + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + + let expr = + self.expression_for_reference(target, ctx.as_expression(block, &mut emitter))?; + let mut value = self.expression(value, ctx.as_expression(block, &mut emitter))?; + + if !expr.is_reference { + let ty = if ctx.named_expressions.contains_key(&expr.handle) { + InvalidAssignmentType::ImmutableBinding + } else { + match ctx.naga_expressions[expr.handle] { + crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, + _ => InvalidAssignmentType::Other, + } + }; + + return Err(Error::InvalidAssignment { + span: ctx.ast_expressions.get_span(target), + ty, + }); + } + + let value = match op { + Some(op) => { + let mut ctx = ctx.as_expression(block, &mut emitter); + let mut left = ctx.apply_load_rule(expr); + ctx.binary_op_splat(op, &mut left, &mut value)?; + ctx.naga_expressions.append( + crate::Expression::Binary { + op, + left, + right: value, + }, + stmt.span, + ) + } + None => value, + }; + block.extend(emitter.finish(ctx.naga_expressions)); + + crate::Statement::Store { + pointer: expr.handle, + value, + } + } + ast::StatementKind::Increment(value) | ast::StatementKind::Decrement(value) => { + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + + let op = match stmt.kind { + ast::StatementKind::Increment(_) => crate::BinaryOperator::Add, + ast::StatementKind::Decrement(_) => crate::BinaryOperator::Subtract, + _ => unreachable!(), + }; + + let value_span = ctx.ast_expressions.get_span(value); + let reference = + self.expression_for_reference(value, ctx.as_expression(block, &mut emitter))?; + let mut ectx = ctx.as_expression(block, &mut emitter); + + ectx.grow_types(reference.handle)?; + let (kind, width) = match *ectx.resolved_inner(reference.handle) { + crate::TypeInner::ValuePointer { + size: None, + kind, + width, + .. + } => (kind, width), + crate::TypeInner::Pointer { base, .. } => match ectx.module.types[base].inner { + crate::TypeInner::Scalar { kind, width } => (kind, width), + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), + }, + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), + }; + let constant_inner = crate::ConstantInner::Scalar { + width, + value: match kind { + crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), + crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), + }, + }; + let constant = ectx.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: constant_inner, + }, + Span::UNDEFINED, + ); + + let left = ectx.naga_expressions.append( + crate::Expression::Load { + pointer: reference.handle, + }, + value_span, + ); + let right = + ectx.interrupt_emitter(crate::Expression::Constant(constant), Span::UNDEFINED); + let value = ectx + .naga_expressions + .append(crate::Expression::Binary { op, left, right }, stmt.span); + + block.extend(emitter.finish(ctx.naga_expressions)); + crate::Statement::Store { + pointer: reference.handle, + value, + } + } + ast::StatementKind::Ignore(expr) => { + let mut emitter = super::Emitter::default(); + emitter.start(ctx.naga_expressions); + + let _ = self.expression(expr, ctx.as_expression(block, &mut emitter))?; + block.extend(emitter.finish(ctx.naga_expressions)); + return Ok(()); + } + }; + + block.push(out, stmt.span); + + Ok(()) + } + + fn expression( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let expr = self.expression_for_reference(expr, ctx.reborrow())?; + Ok(ctx.apply_load_rule(expr)) + } + + fn expression_for_reference( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result> { + let span = ctx.ast_expressions.get_span(expr); + let expr = &ctx.ast_expressions[expr]; + + let (expr, is_reference) = match *expr { + ast::Expression::Literal(literal) => { + let inner = match literal { + ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Float(f as _), + }, + ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Sint(i as _), + }, + ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(u as _), + }, + ast::Literal::Number(_) => { + unreachable!("got abstract numeric type when not expected"); + } + ast::Literal::Bool(b) => crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(b), + }, + }; + let handle = ctx.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + Span::UNDEFINED, + ); + let handle = ctx.interrupt_emitter(crate::Expression::Constant(handle), span); + return Ok(TypedExpression::non_reference(handle)); + } + ast::Expression::Ident(ast::IdentExpr::Local(local)) => { + return Ok(ctx.local_table[&local]) + } + ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { + return if let Some(global) = ctx.globals.get(name) { + let (expr, is_reference) = match *global { + LoweredGlobalDecl::Var(handle) => ( + crate::Expression::GlobalVariable(handle), + ctx.module.global_variables[handle].space + != crate::AddressSpace::Handle, + ), + LoweredGlobalDecl::Const(handle) => { + (crate::Expression::Constant(handle), false) + } + _ => { + return Err(Error::Unexpected(span, ExpectedToken::Variable)); + } + }; + + let handle = ctx.interrupt_emitter(expr, span); + Ok(TypedExpression { + handle, + is_reference, + }) + } else { + Err(Error::UnknownIdent(span, name)) + } + } + ast::Expression::Construct { + ref ty, + ty_span, + ref components, + } => { + let handle = self.construct(span, ty, ty_span, components, ctx.reborrow())?; + return Ok(TypedExpression::non_reference(handle)); + } + ast::Expression::Unary { op, expr } => { + let expr = self.expression(expr, ctx.reborrow())?; + (crate::Expression::Unary { op, expr }, false) + } + ast::Expression::AddrOf(expr) => { + // The `&` operator simply converts a reference to a pointer. And since a + // reference is required, the Load Rule is not applied. + let expr = self.expression_for_reference(expr, ctx.reborrow())?; + if !expr.is_reference { + return Err(Error::NotReference("the operand of the `&` operator", span)); + } + + // No code is generated. We just declare the pointer a reference now. + return Ok(TypedExpression { + is_reference: false, + ..expr + }); + } + ast::Expression::Deref(expr) => { + // The pointer we dereference must be loaded. + let pointer = self.expression(expr, ctx.reborrow())?; + + ctx.grow_types(pointer)?; + if ctx.resolved_inner(pointer).pointer_space().is_none() { + return Err(Error::NotPointer(span)); + } + + return Ok(TypedExpression { + handle: pointer, + is_reference: true, + }); + } + ast::Expression::Binary { op, left, right } => { + // Load both operands. + let mut left = self.expression(left, ctx.reborrow())?; + let mut right = self.expression(right, ctx.reborrow())?; + ctx.binary_op_splat(op, &mut left, &mut right)?; + (crate::Expression::Binary { op, left, right }, false) + } + ast::Expression::Call { + ref function, + ref arguments, + } => { + let handle = self + .call(span, function, arguments, ctx.reborrow())? + .ok_or(Error::FunctionReturnsVoid(function.span))?; + return Ok(TypedExpression::non_reference(handle)); + } + ast::Expression::Index { base, index } => { + let expr = self.expression_for_reference(base, ctx.reborrow())?; + let index = self.expression(index, ctx.reborrow())?; + + ctx.grow_types(expr.handle)?; + let wgsl_pointer = + ctx.resolved_inner(expr.handle).pointer_space().is_some() && !expr.is_reference; + + if wgsl_pointer { + return Err(Error::Pointer( + "the value indexed by a `[]` subscripting expression", + ctx.ast_expressions.get_span(base), + )); + } + + if let crate::Expression::Constant(constant) = ctx.naga_expressions[index] { + let span = ctx.naga_expressions.get_span(index); + let index = match ctx.module.constants[constant].inner { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Sint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), + _ => Err(Error::BadU32Constant(span)), + }?; + + ( + crate::Expression::AccessIndex { + base: expr.handle, + index, + }, + expr.is_reference, + ) + } else { + ( + crate::Expression::Access { + base: expr.handle, + index, + }, + expr.is_reference, + ) + } + } + ast::Expression::Member { base, ref field } => { + let TypedExpression { + handle, + is_reference, + } = self.expression_for_reference(base, ctx.reborrow())?; + + ctx.grow_types(handle)?; + let temp_inner; + let (composite, wgsl_pointer) = match *ctx.resolved_inner(handle) { + crate::TypeInner::Pointer { base, .. } => { + (&ctx.module.types[base].inner, !is_reference) + } + crate::TypeInner::ValuePointer { + size: None, + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Scalar { kind, width }; + (&temp_inner, !is_reference) + } + crate::TypeInner::ValuePointer { + size: Some(size), + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Vector { size, kind, width }; + (&temp_inner, !is_reference) + } + ref other => (other, false), + }; + + if wgsl_pointer { + return Err(Error::Pointer( + "the value accessed by a `.member` expression", + ctx.ast_expressions.get_span(base), + )); + } + + let access = match *composite { + crate::TypeInner::Struct { ref members, .. } => { + let index = members + .iter() + .position(|m| m.name.as_deref() == Some(field.name)) + .ok_or(Error::BadAccessor(field.span))? + as u32; + + ( + crate::Expression::AccessIndex { + base: handle, + index, + }, + is_reference, + ) + } + crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { + match Composition::make(field.name, field.span)? { + Composition::Multi(size, pattern) => { + let vector = ctx.apply_load_rule(TypedExpression { + handle, + is_reference, + }); + + ( + crate::Expression::Swizzle { + size, + vector, + pattern, + }, + false, + ) + } + Composition::Single(index) => ( + crate::Expression::AccessIndex { + base: handle, + index, + }, + is_reference, + ), + } + } + _ => return Err(Error::BadAccessor(field.span)), + }; + + access + } + ast::Expression::Bitcast { expr, to, ty_span } => { + let expr = self.expression(expr, ctx.reborrow())?; + let to_resolved = self.resolve_ast_type(to, ctx.as_output())?; + + let kind = match ctx.module.types[to_resolved].inner { + crate::TypeInner::Scalar { kind, .. } => kind, + crate::TypeInner::Vector { kind, .. } => kind, + _ => { + let ty = &ctx.typifier[expr]; + return Err(Error::BadTypeCast { + from_type: ctx.format_type_resolution(ty), + span: ty_span, + to_type: ctx.format_type(to_resolved), + }); + } + }; + + ( + crate::Expression::As { + expr, + kind, + convert: None, + }, + false, + ) + } + }; + + let handle = ctx.naga_expressions.append(expr, span); + Ok(TypedExpression { + handle, + is_reference, + }) + } + + /// Generate Naga IR for call expressions and statements, and type + /// constructor expressions. + /// + /// The "function" being called is simply an `Ident` that we know refers to + /// some module-scope definition. + /// + /// - If it is the name of a type, then the expression is a type constructor + /// expression: either constructing a value from components, a conversion + /// expression, or a zero value expression. + /// + /// - If it is the name of a function, then we're generating a [`Call`] + /// statement. We may be in the midst of generating code for an + /// expression, in which case we must generate an `Emit` statement to + /// force evaluation of the IR expressions we've generated so far, add the + /// `Call` statement to the current block, and then resume generating + /// expressions. + /// + /// [`Call`]: crate::Statement::Call + fn call( + &mut self, + span: Span, + function: &ast::Ident<'source>, + arguments: &[Handle>], + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result>, Error<'source>> { + match ctx.globals.get(function.name) { + Some(&LoweredGlobalDecl::Type(ty)) => { + let handle = self.construct( + span, + &ast::ConstructorType::Type(ty), + function.span, + arguments, + ctx.reborrow(), + )?; + Ok(Some(handle)) + } + Some(&LoweredGlobalDecl::Const(_) | &LoweredGlobalDecl::Var(_)) => { + Err(Error::Unexpected(function.span, ExpectedToken::Function)) + } + Some(&LoweredGlobalDecl::EntryPoint) => Err(Error::CalledEntryPoint(function.span)), + Some(&LoweredGlobalDecl::Function(function)) => { + let arguments = arguments + .iter() + .map(|&arg| self.expression(arg, ctx.reborrow())) + .collect::, _>>()?; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + let result = ctx.module.functions[function].result.is_some().then(|| { + ctx.naga_expressions + .append(crate::Expression::CallResult(function), span) + }); + ctx.emitter.start(ctx.naga_expressions); + ctx.block.push( + crate::Statement::Call { + function, + arguments, + result, + }, + span, + ); + + Ok(result) + } + None => { + let span = function.span; + let expr = if let Some(fun) = conv::map_relational_fun(function.name) { + let mut args = ctx.prepare_args(arguments, 1, span); + let argument = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::Relational { fun, argument } + } else if let Some(axis) = conv::map_derivative_axis(function.name) { + let mut args = ctx.prepare_args(arguments, 1, span); + let expr = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::Derivative { axis, expr } + } else if let Some(fun) = conv::map_standard_fun(function.name) { + let expected = fun.argument_count() as _; + let mut args = ctx.prepare_args(arguments, expected, span); + + let arg = self.expression(args.next()?, ctx.reborrow())?; + let arg1 = args + .next() + .map(|x| self.expression(x, ctx.reborrow())) + .ok() + .transpose()?; + let arg2 = args + .next() + .map(|x| self.expression(x, ctx.reborrow())) + .ok() + .transpose()?; + let arg3 = args + .next() + .map(|x| self.expression(x, ctx.reborrow())) + .ok() + .transpose()?; + + args.finish()?; + + crate::Expression::Math { + fun, + arg, + arg1, + arg2, + arg3, + } + } else if let Some(fun) = Texture::map(function.name) { + self.texture_sample_helper(fun, arguments, span, ctx.reborrow())? + } else { + match function.name { + "select" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let reject = self.expression(args.next()?, ctx.reborrow())?; + let accept = self.expression(args.next()?, ctx.reborrow())?; + let condition = self.expression(args.next()?, ctx.reborrow())?; + + args.finish()?; + + crate::Expression::Select { + reject, + accept, + condition, + } + } + "arrayLength" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let expr = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ArrayLength(expr) + } + "atomicLoad" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::Load { pointer } + } + "atomicStore" => { + let mut args = ctx.prepare_args(arguments, 2, span); + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + let value = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + ctx.emitter.start(ctx.naga_expressions); + ctx.block + .push(crate::Statement::Store { pointer, value }, span); + return Ok(None); + } + "atomicAdd" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Add, + arguments, + ctx.reborrow(), + )?)) + } + "atomicSub" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Subtract, + arguments, + ctx.reborrow(), + )?)) + } + "atomicAnd" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::And, + arguments, + ctx.reborrow(), + )?)) + } + "atomicOr" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::InclusiveOr, + arguments, + ctx.reborrow(), + )?)) + } + "atomicXor" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::ExclusiveOr, + arguments, + ctx.reborrow(), + )?)) + } + "atomicMin" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Min, + arguments, + ctx.reborrow(), + )?)) + } + "atomicMax" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Max, + arguments, + ctx.reborrow(), + )?)) + } + "atomicExchange" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Exchange { compare: None }, + arguments, + ctx.reborrow(), + )?)) + } + "atomicCompareExchangeWeak" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + + let compare = self.expression(args.next()?, ctx.reborrow())?; + + let value = args.next()?; + let value_span = ctx.ast_expressions.get_span(value); + let value = self.expression(value, ctx.reborrow())?; + ctx.grow_types(value)?; + + args.finish()?; + + let expression = match *ctx.resolved_inner(value) { + crate::TypeInner::Scalar { kind, width } => { + let bool_ty = ctx.module.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }, + }, + Span::UNDEFINED, + ); + let scalar_ty = ctx.module.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind, width }, + }, + Span::UNDEFINED, + ); + let struct_ty = ctx.module.types.insert( + crate::Type { + name: Some( + "__atomic_compare_exchange_result".to_string(), + ), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("old_value".to_string()), + ty: scalar_ty, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("exchanged".to_string()), + ty: bool_ty, + binding: None, + offset: 4, + }, + ], + span: 8, + }, + }, + Span::UNDEFINED, + ); + crate::Expression::AtomicResult { + ty: struct_ty, + comparison: true, + } + } + _ => return Err(Error::InvalidAtomicOperandType(value_span)), + }; + + let result = ctx.interrupt_emitter(expression, span); + ctx.block.push( + crate::Statement::Atomic { + pointer, + fun: crate::AtomicFunction::Exchange { + compare: Some(compare), + }, + value, + result, + }, + span, + ); + return Ok(Some(result)); + } + "storageBarrier" => { + ctx.prepare_args(arguments, 0, span).finish()?; + + ctx.block + .push(crate::Statement::Barrier(crate::Barrier::STORAGE), span); + return Ok(None); + } + "workgroupBarrier" => { + ctx.prepare_args(arguments, 0, span).finish()?; + + ctx.block + .push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP), span); + return Ok(None); + } + "textureStore" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let image = args.next()?; + let image_span = ctx.ast_expressions.get_span(image); + let image = self.expression(image, ctx.reborrow())?; + + let coordinate = self.expression(args.next()?, ctx.reborrow())?; + + let (_, arrayed) = ctx.image_data(image, image_span)?; + let array_index = arrayed + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let value = self.expression(args.next()?, ctx.reborrow())?; + + args.finish()?; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + ctx.emitter.start(ctx.naga_expressions); + let stmt = crate::Statement::ImageStore { + image, + coordinate, + array_index, + value, + }; + ctx.block.push(stmt, span); + return Ok(None); + } + "textureLoad" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let image = args.next()?; + let image_span = ctx.ast_expressions.get_span(image); + let image = self.expression(image, ctx.reborrow())?; + + let coordinate = self.expression(args.next()?, ctx.reborrow())?; + + let (class, arrayed) = ctx.image_data(image, image_span)?; + let array_index = arrayed + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let level = class + .is_mipmapped() + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let sample = class + .is_multisampled() + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + args.finish()?; + + crate::Expression::ImageLoad { + image, + coordinate, + array_index, + level, + sample, + } + } + "textureDimensions" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + let level = args + .next() + .map(|arg| self.expression(arg, ctx.reborrow())) + .ok() + .transpose()?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::Size { level }, + } + } + "textureNumLevels" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumLevels, + } + } + "textureNumLayers" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumLayers, + } + } + "textureNumSamples" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumSamples, + } + } + _ => return Err(Error::UnknownIdent(function.span, function.name)), + } + }; + + let expr = ctx.naga_expressions.append(expr, span); + Ok(Some(expr)) + } + } + } + + fn atomic_pointer( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let span = ctx.ast_expressions.get_span(expr); + let pointer = self.expression(expr, ctx.reborrow())?; + + ctx.grow_types(pointer)?; + match *ctx.resolved_inner(pointer) { + crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { + crate::TypeInner::Atomic { .. } => Ok(pointer), + ref other => { + log::error!("Pointer type to {:?} passed to atomic op", other); + Err(Error::InvalidAtomicPointer(span)) + } + }, + ref other => { + log::error!("Type {:?} passed to atomic op", other); + Err(Error::InvalidAtomicPointer(span)) + } + } + } + + fn atomic_helper( + &mut self, + span: Span, + fun: crate::AtomicFunction, + args: &[Handle>], + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let mut args = ctx.prepare_args(args, 2, span); + + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + + let value = args.next()?; + let value = self.expression(value, ctx.reborrow())?; + let ty = ctx.register_type(value)?; + + args.finish()?; + + let result = ctx.interrupt_emitter( + crate::Expression::AtomicResult { + ty, + comparison: false, + }, + span, + ); + ctx.block.push( + crate::Statement::Atomic { + pointer, + fun, + value, + result, + }, + span, + ); + Ok(result) + } + + fn texture_sample_helper( + &mut self, + fun: Texture, + args: &[Handle>], + span: Span, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result> { + let mut args = ctx.prepare_args(args, fun.min_argument_count(), span); + + let (image, gather) = match fun { + Texture::Gather => { + let image_or_component = args.next()?; + match self.gather_component(image_or_component, ctx.reborrow())? { + Some(component) => { + let image = args.next()?; + (image, Some(component)) + } + None => (image_or_component, Some(crate::SwizzleComponent::X)), + } + } + Texture::GatherCompare => { + let image = args.next()?; + (image, Some(crate::SwizzleComponent::X)) + } + + _ => { + let image = args.next()?; + (image, None) + } + }; + + let image_span = ctx.ast_expressions.get_span(image); + let image = self.expression(image, ctx.reborrow())?; + + let sampler = self.expression(args.next()?, ctx.reborrow())?; + + let coordinate = self.expression(args.next()?, ctx.reborrow())?; + + let (_, arrayed) = ctx.image_data(image, image_span)?; + let array_index = arrayed + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let (level, depth_ref) = match fun { + Texture::Gather => (crate::SampleLevel::Zero, None), + Texture::GatherCompare => { + let reference = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Zero, Some(reference)) + } + + Texture::Sample => (crate::SampleLevel::Auto, None), + Texture::SampleBias => { + let bias = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Bias(bias), None) + } + Texture::SampleCompare => { + let reference = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Auto, Some(reference)) + } + Texture::SampleCompareLevel => { + let reference = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Zero, Some(reference)) + } + Texture::SampleGrad => { + let x = self.expression(args.next()?, ctx.reborrow())?; + let y = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Gradient { x, y }, None) + } + Texture::SampleLevel => { + let level = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Exact(level), None) + } + }; + + let offset = args + .next() + .map(|arg| self.constant(arg, ctx.as_output())) + .ok() + .transpose()?; + + args.finish()?; + + Ok(crate::Expression::ImageSample { + image, + sampler, + gather, + coordinate, + array_index, + offset, + level, + depth_ref, + }) + } + + fn gather_component( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let span = ctx.ast_expressions.get_span(expr); + + let constant = match self.constant_inner(expr, ctx.as_output()).ok() { + Some(ConstantOrInner::Constant(c)) => ctx.module.constants[c].inner.clone(), + Some(ConstantOrInner::Inner(inner)) => inner, + None => return Ok(None), + }; + + let int = match constant { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Sint(i), + .. + } if i >= 0 => i as u64, + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(i), + .. + } => i, + _ => { + return Err(Error::InvalidGatherComponent(span)); + } + }; + + crate::SwizzleComponent::XYZW + .get(int as usize) + .copied() + .map(Some) + .ok_or(Error::InvalidGatherComponent(span)) + } + + fn r#struct( + &mut self, + s: &ast::Struct<'source>, + span: Span, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let mut offset = 0; + let mut struct_alignment = Alignment::ONE; + let mut members = Vec::with_capacity(s.members.len()); + + for member in s.members.iter() { + let ty = self.resolve_ast_type(member.ty, ctx.reborrow())?; + + self.layouter + .update(&ctx.module.types, &ctx.module.constants) + .unwrap(); + + let member_min_size = self.layouter[ty].size; + let member_min_alignment = self.layouter[ty].alignment; + + let member_size = if let Some((size, span)) = member.size { + if size < member_min_size { + return Err(Error::SizeAttributeTooLow(span, member_min_size)); + } else { + size + } + } else { + member_min_size + }; + + let member_alignment = if let Some((align, span)) = member.align { + if let Some(alignment) = Alignment::new(align) { + if alignment < member_min_alignment { + return Err(Error::AlignAttributeTooLow(span, member_min_alignment)); + } else { + alignment + } + } else { + return Err(Error::NonPowerOfTwoAlignAttribute(span)); + } + } else { + member_min_alignment + }; + + let binding = self.interpolate_default(&member.binding, ty, ctx.reborrow()); + + offset = member_alignment.round_up(offset); + struct_alignment = struct_alignment.max(member_alignment); + + members.push(crate::StructMember { + name: Some(member.name.name.to_owned()), + ty, + binding, + offset, + }); + + offset += member_size; + } + + let size = struct_alignment.round_up(offset); + let inner = crate::TypeInner::Struct { + members, + span: size, + }; + + let handle = ctx.module.types.insert( + crate::Type { + name: Some(s.name.name.to_string()), + inner, + }, + span, + ); + Ok(handle) + } + + /// Return a Naga `Handle` representing the front-end type `handle`. + fn resolve_ast_type( + &mut self, + handle: Handle>, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let inner = match ctx.types[handle] { + ast::Type::Scalar { kind, width } => crate::TypeInner::Scalar { kind, width }, + ast::Type::Vector { size, kind, width } => { + crate::TypeInner::Vector { size, kind, width } + } + ast::Type::Matrix { + rows, + columns, + width, + } => crate::TypeInner::Matrix { + columns, + rows, + width, + }, + ast::Type::Atomic { kind, width } => crate::TypeInner::Atomic { kind, width }, + ast::Type::Pointer { base, space } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + crate::TypeInner::Pointer { base, space } + } + ast::Type::Array { base, size } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + self.layouter + .update(&ctx.module.types, &ctx.module.constants) + .unwrap(); + + crate::TypeInner::Array { + base, + size: match size { + ast::ArraySize::Constant(constant) => { + let constant = self.constant(constant, ctx.reborrow())?; + crate::ArraySize::Constant(constant) + } + ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, + }, + stride: self.layouter[base].to_stride(), + } + } + ast::Type::Image { + dim, + arrayed, + class, + } => crate::TypeInner::Image { + dim, + arrayed, + class, + }, + ast::Type::Sampler { comparison } => crate::TypeInner::Sampler { comparison }, + ast::Type::BindingArray { base, size } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + + crate::TypeInner::BindingArray { + base, + size: match size { + ast::ArraySize::Constant(constant) => { + let constant = self.constant(constant, ctx.reborrow())?; + crate::ArraySize::Constant(constant) + } + ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, + }, + } + } + ast::Type::User(ref ident) => { + return match ctx.globals.get(ident.name) { + Some(&LoweredGlobalDecl::Type(handle)) => Ok(handle), + Some(_) => Err(Error::Unexpected(ident.span, ExpectedToken::Type)), + None => Err(Error::UnknownType(ident.span)), + } + } + }; + + Ok(ctx.ensure_type_exists(inner)) + } + + /// Find or construct a Naga [`Constant`] whose value is `expr`. + /// + /// The `ctx` indicates the Naga [`Module`] to which we should add + /// new `Constant`s or [`Type`]s as needed. + /// + /// [`Module`]: crate::Module + /// [`Constant`]: crate::Constant + /// [`Type`]: crate::Type + fn constant( + &mut self, + expr: Handle>, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let inner = match self.constant_inner(expr, ctx.reborrow())? { + ConstantOrInner::Constant(c) => return Ok(c), + ConstantOrInner::Inner(inner) => inner, + }; + + let c = ctx.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + Span::UNDEFINED, + ); + Ok(c) + } + + fn constant_inner( + &mut self, + expr: Handle>, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result> { + let span = ctx.ast_expressions.get_span(expr); + let inner = match ctx.ast_expressions[expr] { + ast::Expression::Literal(literal) => match literal { + ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Float(f as _), + }, + ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Sint(i as _), + }, + ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(u as _), + }, + ast::Literal::Number(_) => { + unreachable!("got abstract numeric type when not expected"); + } + ast::Literal::Bool(b) => crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(b), + }, + }, + ast::Expression::Ident(ast::IdentExpr::Local(_)) => { + return Err(Error::Unexpected(span, ExpectedToken::Constant)) + } + ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { + return if let Some(global) = ctx.globals.get(name) { + match *global { + LoweredGlobalDecl::Const(handle) => Ok(ConstantOrInner::Constant(handle)), + _ => Err(Error::Unexpected(span, ExpectedToken::Constant)), + } + } else { + Err(Error::UnknownIdent(span, name)) + } + } + ast::Expression::Construct { + ref ty, + ref components, + .. + } => self.const_construct(span, ty, components, ctx.reborrow())?, + ast::Expression::Call { + ref function, + ref arguments, + } => match ctx.globals.get(function.name) { + Some(&LoweredGlobalDecl::Type(ty)) => self.const_construct( + span, + &ast::ConstructorType::Type(ty), + arguments, + ctx.reborrow(), + )?, + Some(_) => return Err(Error::ConstExprUnsupported(span)), + None => return Err(Error::UnknownIdent(function.span, function.name)), + }, + _ => return Err(Error::ConstExprUnsupported(span)), + }; + + Ok(ConstantOrInner::Inner(inner)) + } + + fn interpolate_default( + &mut self, + binding: &Option, + ty: Handle, + ctx: OutputContext<'source, '_, '_>, + ) -> Option { + let mut binding = binding.clone(); + if let Some(ref mut binding) = binding { + binding.apply_default_interpolation(&ctx.module.types[ty].inner); + } + + binding } } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 6aaa505d4..73e843229 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -16,8 +16,8 @@ fn parse_comment() { #[test] fn parse_types() { - parse_str("let a : i32 = 2;").unwrap(); - assert!(parse_str("let a : x32 = 2;").is_err()); + parse_str("const a : i32 = 2;").unwrap(); + assert!(parse_str("const a : x32 = 2;").is_err()); parse_str("var t: texture_2d;").unwrap(); parse_str("var t: texture_cube_array;").unwrap(); parse_str("var t: texture_multisampled_2d;").unwrap(); @@ -48,7 +48,7 @@ fn parse_type_inference() { fn parse_type_cast() { parse_str( " - let a : i32 = 2; + const a : i32 = 2; fn main() { var x: f32 = f32(a); x = f32(i32(a + 1) / 2); diff --git a/src/span.rs b/src/span.rs index a4670e2da..90bf3d174 100644 --- a/src/span.rs +++ b/src/span.rs @@ -18,6 +18,14 @@ impl Span { Span { start, end } } + /// Returns a new `Span` starting at `self` and ending at `other` + pub const fn until(&self, other: &Self) -> Self { + Span { + start: self.start, + end: other.end, + } + } + /// Modifies `self` to contain the smallest `Span` possible that /// contains both `self` and `other` pub fn subsume(&mut self, other: Self) { @@ -85,6 +93,15 @@ impl From> for Span { } } +impl std::ops::Index for str { + type Output = str; + + #[inline] + fn index(&self, span: Span) -> &str { + &self[span.start as usize..span.end as usize] + } +} + /// A human-readable representation for a span, tailored for text source. /// /// Corresponds to the positional members of [`GPUCompilationMessage`][gcm] from diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index c2e4d25b6..798de528d 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -129,9 +129,9 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let foo_value = read_from_private(&foo); // test array indexing - var c = array(a, i32(b), 3, 4, 5); - c[vi + 1u] = 42; - let value = c[vi]; + var c2 = array(a, i32(b), 3, 4, 5); + c2[vi + 1u] = 42; + let value = c2[vi]; _ = test_arr_as_arg(array, 5>()); diff --git a/tests/in/atomicCompareExchange.wgsl b/tests/in/atomicCompareExchange.wgsl index 35b91aaf7..4b6144b12 100644 --- a/tests/in/atomicCompareExchange.wgsl +++ b/tests/in/atomicCompareExchange.wgsl @@ -1,4 +1,4 @@ -let SIZE: u32 = 128u; +const SIZE: u32 = 128u; @group(0) @binding(0) var arr_i32: array, SIZE>; diff --git a/tests/in/bitcast.wgsl b/tests/in/bitcast.wgsl index 11613f9b4..c698f1bdf 100644 --- a/tests/in/bitcast.wgsl +++ b/tests/in/bitcast.wgsl @@ -3,11 +3,11 @@ fn main() { var i2 = vec2(0); var i3 = vec3(0); var i4 = vec4(0); - + var u2 = vec2(0u); var u3 = vec3(0u); var u4 = vec4(0u); - + var f2 = vec2(0.0); var f3 = vec3(0.0); var f4 = vec4(0.0); @@ -15,11 +15,11 @@ fn main() { u2 = bitcast>(i2); u3 = bitcast>(i3); u4 = bitcast>(i4); - + i2 = bitcast>(u2); i3 = bitcast>(u3); i4 = bitcast>(u4); - + f2 = bitcast>(i2); f3 = bitcast>(i3); f4 = bitcast>(i4); diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl index 31bbc85bb..caa67df77 100644 --- a/tests/in/boids.wgsl +++ b/tests/in/boids.wgsl @@ -1,4 +1,4 @@ -let NUM_PARTICLES: u32 = 1500u; +const NUM_PARTICLES: u32 = 1500u; struct Particle { pos : vec2, diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 59820ab36..8f687fd35 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -1,17 +1,17 @@ // Global variable & constant declarations -let Foo: bool = true; +const Foo: bool = true; var wg : array; var at: atomic; -struct Foo { +struct FooStruct { v3: vec3, // test packed vec3 v1: f32, } @group(0) @binding(1) -var alignment: Foo; +var alignment: FooStruct; @group(0) @binding(2) var dummy: array>; diff --git a/tests/in/module-scope.wgsl b/tests/in/module-scope.wgsl new file mode 100644 index 000000000..54638cb40 --- /dev/null +++ b/tests/in/module-scope.wgsl @@ -0,0 +1,26 @@ +fn call() { + statement(); + let x: S = returns(); + let vf = f32(Value); + let s = textureSample(Texture, Sampler, Vec2(vf)); +} + +fn statement() {} + +fn returns() -> S { + return S(Value); +} + +struct S { + x: i32, +} + +const Value: i32 = 1; + +@group(0) @binding(0) +var Texture: texture_2d; + +@group(0) @binding(1) +var Sampler: sampler; + +type Vec2 = vec2; diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index be185399e..e5b9a15d5 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -1,8 +1,8 @@ //TODO: support splatting constructors for globals? -let v_f32_one = vec4(1.0, 1.0, 1.0, 1.0); -let v_f32_zero = vec4(0.0, 0.0, 0.0, 0.0); -let v_f32_half = vec4(0.5, 0.5, 0.5, 0.5); -let v_i32_one = vec4(1, 1, 1, 1); +const v_f32_one = vec4(1.0, 1.0, 1.0, 1.0); +const v_f32_zero = vec4(0.0, 0.0, 0.0, 0.0); +const v_f32_half = vec4(0.5, 0.5, 0.5, 0.5); +const v_i32_one = vec4(1, 1, 1, 1); fn builtins() -> vec4 { // select() diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl index f2c85f095..b51e1a91d 100644 --- a/tests/in/quad.wgsl +++ b/tests/in/quad.wgsl @@ -1,5 +1,5 @@ // vertex -let c_scale: f32 = 1.2; +const c_scale: f32 = 1.2; struct VertexOutput { @location(0) uv : vec2, @@ -31,7 +31,7 @@ fn frag_main(@location(0) uv : vec2) -> @location(0) vec4 { } -// We need to make sure that backends are successfully handling multiple entry points for the same shader stage. +// We need to make sure that backends are successfully handling multiple entry points for the same shader stage. @fragment fn fs_extra() -> @location(0) vec4 { return vec4(0.0, 0.5, 0.0, 0.5); diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl index 575018863..b02cf6877 100644 --- a/tests/in/shadow.wgsl +++ b/tests/in/shadow.wgsl @@ -77,8 +77,8 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { return textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z * proj_correction); } -let c_ambient: vec3 = vec3(0.05, 0.05, 0.05); -let c_max_lights: u32 = 10u; +const c_ambient: vec3 = vec3(0.05, 0.05, 0.05); +const c_max_lights: u32 = 10u; @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4 { diff --git a/tests/in/type-alias.wgsl b/tests/in/type-alias.wgsl new file mode 100644 index 000000000..429f153b5 --- /dev/null +++ b/tests/in/type-alias.wgsl @@ -0,0 +1,13 @@ +type FVec3 = vec3; +type IVec3 = vec3; +type Mat2 = mat2x2; + +fn main() { + let a = FVec3(0.0, 0.0, 0.0); + let c = FVec3(0.0); + let b = FVec3(vec2(0.0), 0.0); + let d = FVec3(vec2(0.0), 0.0); + let e = IVec3(d); + + let f = Mat2(1.0, 2.0, 3.0, 4.0); +} diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index 3e1805c6f..f33439444 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -8,7 +8,7 @@ bits: 7, ), uniformity: ( - non_uniform_result: Some(5), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -28,31 +28,13 @@ bits: 0, ), ), - ref_count: 0, - assignable_global: Some(1), - ty: Value(Pointer( - base: 3, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), - ), ref_count: 1, assignable_global: None, ty: Handle(1), ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -71,7 +53,7 @@ bits: 0, ), ), - ref_count: 0, + ref_count: 1, assignable_global: None, ty: Value(Scalar( kind: Uint, @@ -80,12 +62,12 @@ ), ( uniformity: ( - non_uniform_result: Some(5), + non_uniform_result: Some(4), requirements: ( bits: 0, ), ), - ref_count: 3, + ref_count: 4, assignable_global: None, ty: Value(Pointer( base: 1, @@ -94,7 +76,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -119,7 +101,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -133,7 +115,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -158,7 +140,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -183,7 +165,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -197,7 +179,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -222,7 +204,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -247,7 +229,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -258,7 +240,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -283,7 +265,7 @@ ), ( uniformity: ( - non_uniform_result: Some(3), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -294,7 +276,7 @@ ), ( uniformity: ( - non_uniform_result: Some(5), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -319,7 +301,7 @@ ), ( uniformity: ( - non_uniform_result: Some(5), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -330,7 +312,7 @@ ), ( uniformity: ( - non_uniform_result: Some(5), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -352,7 +334,7 @@ bits: 7, ), uniformity: ( - non_uniform_result: Some(5), + non_uniform_result: Some(4), requirements: ( bits: 0, ), @@ -373,6 +355,17 @@ ), ), ref_count: 2, + assignable_global: None, + ty: Handle(4), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, assignable_global: Some(1), ty: Value(Pointer( base: 3, @@ -390,17 +383,6 @@ bits: 0, ), ), - ref_count: 2, - assignable_global: None, - ty: Handle(4), - ), - ( - uniformity: ( - non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), - ), ref_count: 1, assignable_global: Some(1), ty: Value(Pointer( @@ -414,7 +396,7 @@ ), ( uniformity: ( - non_uniform_result: Some(2), + non_uniform_result: Some(1), requirements: ( bits: 0, ), @@ -428,7 +410,7 @@ ), ( uniformity: ( - non_uniform_result: Some(1), + non_uniform_result: Some(2), requirements: ( bits: 0, ), @@ -446,7 +428,25 @@ ), ( uniformity: ( - non_uniform_result: Some(1), + non_uniform_result: Some(6), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(1), + ty: Value(Pointer( + base: 3, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -464,7 +464,7 @@ ), ( uniformity: ( - non_uniform_result: Some(2), + non_uniform_result: Some(1), requirements: ( bits: 0, ), @@ -478,7 +478,7 @@ ), ( uniformity: ( - non_uniform_result: Some(1), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -496,7 +496,7 @@ ), ( uniformity: ( - non_uniform_result: Some(1), + non_uniform_result: Some(6), requirements: ( bits: 0, ), @@ -507,7 +507,7 @@ ), ( uniformity: ( - non_uniform_result: Some(5), + non_uniform_result: Some(4), requirements: ( bits: 0, ), diff --git a/tests/out/dot/quad.dot b/tests/out/dot/quad.dot index c4e242b3a..4f2cde18c 100644 --- a/tests/out/dot/quad.dot +++ b/tests/out/dot/quad.dot @@ -7,18 +7,18 @@ digraph Module { subgraph cluster_ep0 { label="Vertex/'vert_main'" node [ style=filled ] - ep0_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] - ep0_e1 [ color="#8dd3c7" label="[2] Argument[0]" ] - ep0_e2 [ color="#8dd3c7" label="[3] Argument[1]" ] + ep0_e0 [ color="#8dd3c7" label="[1] Argument[0]" ] + ep0_e1 [ color="#8dd3c7" label="[2] Argument[1]" ] + ep0_e2 [ fillcolor="#ffffb3" label="[3] Constant" ] ep0_e3 [ color="#fdb462" label="[4] Multiply" ] - ep0_e1 -> ep0_e3 [ label="right" ] - ep0_e0 -> ep0_e3 [ label="left" ] + ep0_e0 -> ep0_e3 [ label="right" ] + ep0_e2 -> ep0_e3 [ label="left" ] ep0_e4 [ fillcolor="#ffffb3" label="[5] Constant" ] ep0_e5 [ fillcolor="#ffffb3" label="[6] Constant" ] ep0_e6 [ color="#bebada" label="[7] Compose" ] { ep0_e3 ep0_e4 ep0_e5 } -> ep0_e6 ep0_e7 [ color="#bebada" label="[8] Compose" ] - { ep0_e2 ep0_e6 } -> ep0_e7 + { ep0_e1 ep0_e6 } -> ep0_e7 ep0_s0 [ shape=square label="Root" ] ep0_s1 [ shape=square label="Emit" ] ep0_s2 [ shape=square label="Emit" ] @@ -34,27 +34,26 @@ digraph Module { subgraph cluster_ep1 { label="Fragment/'frag_main'" node [ style=filled ] - ep1_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] + ep1_e0 [ color="#8dd3c7" label="[1] Argument[0]" ] ep1_e1 [ color="#ffffb3" label="[2] Global" ] - g1 -> ep1_e1 [fillcolor=gray] + g0 -> ep1_e1 [fillcolor=gray] ep1_e2 [ color="#ffffb3" label="[3] Global" ] - g0 -> ep1_e2 [fillcolor=gray] - ep1_e3 [ color="#8dd3c7" label="[4] Argument[0]" ] - ep1_e4 [ color="#80b1d3" label="[5] ImageSample" ] - ep1_e1 -> ep1_e4 [ label="sampler" ] - ep1_e2 -> ep1_e4 [ label="image" ] - ep1_e3 -> ep1_e4 [ label="coordinate" ] - ep1_e5 [ color="#8dd3c7" label="[6] AccessIndex[3]" ] - ep1_e4 -> ep1_e5 [ label="base" ] - ep1_e6 [ fillcolor="#ffffb3" label="[7] Constant" ] - ep1_e7 [ color="#fdb462" label="[8] Equal" ] - ep1_e6 -> ep1_e7 [ label="right" ] - ep1_e5 -> ep1_e7 [ label="left" ] - ep1_e8 [ color="#8dd3c7" label="[9] AccessIndex[3]" ] - ep1_e4 -> ep1_e8 [ label="base" ] - ep1_e9 [ color="#fdb462" label="[10] Multiply" ] - ep1_e4 -> ep1_e9 [ label="right" ] - ep1_e8 -> ep1_e9 [ label="left" ] + g1 -> ep1_e2 [fillcolor=gray] + ep1_e3 [ color="#80b1d3" label="[4] ImageSample" ] + ep1_e2 -> ep1_e3 [ label="sampler" ] + ep1_e1 -> ep1_e3 [ label="image" ] + ep1_e0 -> ep1_e3 [ label="coordinate" ] + ep1_e4 [ color="#8dd3c7" label="[5] AccessIndex[3]" ] + ep1_e3 -> ep1_e4 [ label="base" ] + ep1_e5 [ fillcolor="#ffffb3" label="[6] Constant" ] + ep1_e6 [ color="#fdb462" label="[7] Equal" ] + ep1_e5 -> ep1_e6 [ label="right" ] + ep1_e4 -> ep1_e6 [ label="left" ] + ep1_e7 [ color="#8dd3c7" label="[8] AccessIndex[3]" ] + ep1_e3 -> ep1_e7 [ label="base" ] + ep1_e8 [ color="#fdb462" label="[9] Multiply" ] + ep1_e3 -> ep1_e8 [ label="right" ] + ep1_e7 -> ep1_e8 [ label="left" ] ep1_s0 [ shape=square label="Root" ] ep1_s1 [ shape=square label="Emit" ] ep1_s2 [ shape=square label="Emit" ] @@ -77,34 +76,29 @@ digraph Module { ep1_s7 -> ep1_s8 [ arrowhead=tee label="" ] ep1_s8 -> ep1_s9 [ arrowhead=tee label="" ] ep1_s9 -> ep1_s10 [ arrowhead=tee label="" ] - ep1_e7 -> ep1_s4 [ label="condition" ] - ep1_e9 -> ep1_s10 [ label="value" ] - ep1_s1 -> ep1_e4 [ style=dotted ] - ep1_s2 -> ep1_e5 [ style=dotted ] - ep1_s3 -> ep1_e7 [ style=dotted ] + ep1_e6 -> ep1_s4 [ label="condition" ] + ep1_e8 -> ep1_s10 [ label="value" ] + ep1_s1 -> ep1_e3 [ style=dotted ] + ep1_s2 -> ep1_e4 [ style=dotted ] + ep1_s3 -> ep1_e6 [ style=dotted ] + ep1_s9 -> ep1_e7 [ style=dotted ] ep1_s9 -> ep1_e8 [ style=dotted ] - ep1_s9 -> ep1_e9 [ style=dotted ] } subgraph cluster_ep2 { label="Fragment/'fs_extra'" node [ style=filled ] ep2_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] - ep2_e1 [ color="#ffffb3" label="[2] Global" ] - g1 -> ep2_e1 [fillcolor=gray] - ep2_e2 [ color="#ffffb3" label="[3] Global" ] - g0 -> ep2_e2 [fillcolor=gray] + ep2_e1 [ fillcolor="#ffffb3" label="[2] Constant" ] + ep2_e2 [ fillcolor="#ffffb3" label="[3] Constant" ] ep2_e3 [ fillcolor="#ffffb3" label="[4] Constant" ] - ep2_e4 [ fillcolor="#ffffb3" label="[5] Constant" ] - ep2_e5 [ fillcolor="#ffffb3" label="[6] Constant" ] - ep2_e6 [ fillcolor="#ffffb3" label="[7] Constant" ] - ep2_e7 [ fillcolor="#bebada" label="[8] Compose" ] - { ep2_e3 ep2_e4 ep2_e5 ep2_e6 } -> ep2_e7 + ep2_e4 [ fillcolor="#bebada" label="[5] Compose" ] + { ep2_e0 ep2_e1 ep2_e2 ep2_e3 } -> ep2_e4 ep2_s0 [ shape=square label="Root" ] ep2_s1 [ shape=square label="Emit" ] ep2_s2 [ shape=square label="Return" ] ep2_s0 -> ep2_s1 [ arrowhead=tee label="" ] ep2_s1 -> ep2_s2 [ arrowhead=tee label="" ] - ep2_e7 -> ep2_s2 [ label="value" ] - ep2_s1 -> ep2_e7 [ style=dotted ] + ep2_e4 -> ep2_s2 [ label="value" ] + ep2_s1 -> ep2_e4 [ style=dotted ] } } diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/tests/out/glsl/access.assign_through_ptr.Compute.glsl index c7ee8362c..aafc30b90 100644 --- a/tests/out/glsl/access.assign_through_ptr.Compute.glsl +++ b/tests/out/glsl/access.assign_through_ptr.Compute.glsl @@ -23,8 +23,8 @@ shared uint val; float read_from_private(inout float foo_1) { - float _e6 = foo_1; - return _e6; + float _e1 = foo_1; + return _e1; } float test_arr_as_arg(float a[5][10]) { diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index 56c844f6a..f5448b842 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -29,8 +29,8 @@ layout(std430) buffer Bar_block_0Compute { float read_from_private(inout float foo_1) { - float _e6 = foo_1; - return _e6; + float _e1 = foo_1; + return _e1; } float test_arr_as_arg(float a[5][10]) { @@ -45,22 +45,22 @@ void assign_through_ptr_fn(inout uint p) { void main() { int tmp = 0; int value = _group_0_binding_0_cs.atom; - int _e10 = atomicAdd(_group_0_binding_0_cs.atom, 5); - tmp = _e10; - int _e13 = atomicAdd(_group_0_binding_0_cs.atom, -5); - tmp = _e13; - int _e16 = atomicAnd(_group_0_binding_0_cs.atom, 5); - tmp = _e16; + int _e7 = atomicAdd(_group_0_binding_0_cs.atom, 5); + tmp = _e7; + int _e11 = atomicAdd(_group_0_binding_0_cs.atom, -5); + tmp = _e11; + int _e15 = atomicAnd(_group_0_binding_0_cs.atom, 5); + tmp = _e15; int _e19 = atomicOr(_group_0_binding_0_cs.atom, 5); tmp = _e19; - int _e22 = atomicXor(_group_0_binding_0_cs.atom, 5); - tmp = _e22; - int _e25 = atomicMin(_group_0_binding_0_cs.atom, 5); - tmp = _e25; - int _e28 = atomicMax(_group_0_binding_0_cs.atom, 5); - tmp = _e28; - int _e31 = atomicExchange(_group_0_binding_0_cs.atom, 5); + int _e23 = atomicXor(_group_0_binding_0_cs.atom, 5); + tmp = _e23; + int _e27 = atomicMin(_group_0_binding_0_cs.atom, 5); + tmp = _e27; + int _e31 = atomicMax(_group_0_binding_0_cs.atom, 5); tmp = _e31; + int _e35 = atomicExchange(_group_0_binding_0_cs.atom, 5); + tmp = _e35; _group_0_binding_0_cs.atom = value; return; } diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index a3d6d21dd..2e52a4698 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -30,8 +30,8 @@ layout(std430) buffer type_11_block_1Fragment { ivec2 _group_0_binding_2_fs; }; layout(location = 0) out vec4 _fs2p_location0; float read_from_private(inout float foo_1) { - float _e6 = foo_1; - return _e6; + float _e1 = foo_1; + return _e1; } float test_arr_as_arg(float a[5][10]) { diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index 9fbfc272f..866d6f64b 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -33,80 +33,82 @@ uniform MatCx2InArray_block_3Vertex { MatCx2InArray _group_0_binding_3_vs; }; void test_matrix_within_struct_accesses() { - int idx = 1; + int idx = 0; Baz t = Baz(mat3x2(0.0)); - int _e6 = idx; - idx = (_e6 - 1); + idx = 1; + int _e2 = idx; + idx = (_e2 - 1); mat3x2 unnamed = _group_0_binding_1_vs.m; vec2 unnamed_1 = _group_0_binding_1_vs.m[0]; - int _e16 = idx; - vec2 unnamed_2 = _group_0_binding_1_vs.m[_e16]; + int _e15 = idx; + vec2 unnamed_2 = _group_0_binding_1_vs.m[_e15]; float unnamed_3 = _group_0_binding_1_vs.m[0][1]; - int _e28 = idx; - float unnamed_4 = _group_0_binding_1_vs.m[0][_e28]; - int _e32 = idx; - float unnamed_5 = _group_0_binding_1_vs.m[_e32][1]; - int _e38 = idx; - int _e40 = idx; - float unnamed_6 = _group_0_binding_1_vs.m[_e38][_e40]; + int _e29 = idx; + float unnamed_4 = _group_0_binding_1_vs.m[0][_e29]; + int _e34 = idx; + float unnamed_5 = _group_0_binding_1_vs.m[_e34][1]; + int _e41 = idx; + int _e43 = idx; + float unnamed_6 = _group_0_binding_1_vs.m[_e41][_e43]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - int _e52 = idx; - idx = (_e52 + 1); + int _e55 = idx; + idx = (_e55 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - int _e69 = idx; - t.m[_e69] = vec2(90.0); + int _e72 = idx; + t.m[_e72] = vec2(90.0); t.m[0][1] = 10.0; - int _e82 = idx; - t.m[0][_e82] = 20.0; - int _e86 = idx; - t.m[_e86][1] = 30.0; - int _e92 = idx; - int _e94 = idx; - t.m[_e92][_e94] = 40.0; + int _e85 = idx; + t.m[0][_e85] = 20.0; + int _e89 = idx; + t.m[_e89][1] = 30.0; + int _e95 = idx; + int _e97 = idx; + t.m[_e95][_e97] = 40.0; return; } void test_matrix_within_array_within_struct_accesses() { - int idx_1 = 1; + int idx_1 = 0; MatCx2InArray t_1 = MatCx2InArray(mat4x2[2](mat4x2(0.0), mat4x2(0.0))); - int _e7 = idx_1; - idx_1 = (_e7 - 1); + idx_1 = 1; + int _e2 = idx_1; + idx_1 = (_e2 - 1); mat4x2 unnamed_7[2] = _group_0_binding_3_vs.am; mat4x2 unnamed_8 = _group_0_binding_3_vs.am[0]; vec2 unnamed_9 = _group_0_binding_3_vs.am[0][0]; - int _e25 = idx_1; - vec2 unnamed_10 = _group_0_binding_3_vs.am[0][_e25]; + int _e24 = idx_1; + vec2 unnamed_10 = _group_0_binding_3_vs.am[0][_e24]; float unnamed_11 = _group_0_binding_3_vs.am[0][0][1]; - int _e41 = idx_1; - float unnamed_12 = _group_0_binding_3_vs.am[0][0][_e41]; - int _e47 = idx_1; - float unnamed_13 = _group_0_binding_3_vs.am[0][_e47][1]; - int _e55 = idx_1; - int _e57 = idx_1; - float unnamed_14 = _group_0_binding_3_vs.am[0][_e55][_e57]; + int _e42 = idx_1; + float unnamed_12 = _group_0_binding_3_vs.am[0][0][_e42]; + int _e49 = idx_1; + float unnamed_13 = _group_0_binding_3_vs.am[0][_e49][1]; + int _e58 = idx_1; + int _e60 = idx_1; + float unnamed_14 = _group_0_binding_3_vs.am[0][_e58][_e60]; t_1 = MatCx2InArray(mat4x2[2](mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)))); - int _e63 = idx_1; - idx_1 = (_e63 + 1); + int _e66 = idx_1; + idx_1 = (_e66 + 1); t_1.am = mat4x2[2](mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0))); t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); t_1.am[0][0] = vec2(9.0); - int _e90 = idx_1; - t_1.am[0][_e90] = vec2(90.0); + int _e93 = idx_1; + t_1.am[0][_e93] = vec2(90.0); t_1.am[0][0][1] = 10.0; - int _e107 = idx_1; - t_1.am[0][0][_e107] = 20.0; - int _e113 = idx_1; - t_1.am[0][_e113][1] = 30.0; - int _e121 = idx_1; - int _e123 = idx_1; - t_1.am[0][_e121][_e123] = 40.0; + int _e110 = idx_1; + t_1.am[0][0][_e110] = 20.0; + int _e116 = idx_1; + t_1.am[0][_e116][1] = 30.0; + int _e124 = idx_1; + int _e126 = idx_1; + t_1.am[0][_e124][_e126] = 40.0; return; } float read_from_private(inout float foo_1) { - float _e6 = foo_1; - return _e6; + float _e1 = foo_1; + return _e1; } float test_arr_as_arg(float a[5][10]) { @@ -121,7 +123,8 @@ void assign_through_ptr_fn(inout uint p) { void main() { uint vi = uint(gl_VertexID); float foo = 0.0; - int c[5] = int[5](0, 0, 0, 0, 0); + int c2_[5] = int[5](0, 0, 0, 0, 0); + foo = 0.0; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); @@ -130,12 +133,12 @@ void main() { uvec2 arr[2] = _group_0_binding_0_vs.arr; float b = _group_0_binding_0_vs._matrix[3][0]; int a_1 = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; - ivec2 c_1 = _group_0_binding_2_vs; - float _e32 = read_from_private(foo); - c = int[5](a_1, int(b), 3, 4, 5); - c[(vi + 1u)] = 42; - int value = c[vi]; - float _e46 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + ivec2 c = _group_0_binding_2_vs; + float _e34 = read_from_private(foo); + c2_ = int[5](a_1, int(b), 3, 4, 5); + c2_[(vi + 1u)] = 42; + int value = c2_[vi]; + float _e48 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); gl_Position = vec4((_matrix * vec4(ivec4(value))), 2.0); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl index 0cdc8906a..504fb7c94 100644 --- a/tests/out/glsl/bits.main.Compute.glsl +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -17,9 +17,11 @@ void main() { uvec4 u4_ = uvec4(0u); vec2 f2_ = vec2(0.0); vec4 f4_ = vec4(0.0); + i = 0; i2_ = ivec2(0); i3_ = ivec3(0); i4_ = ivec4(0); + u = 0u; u2_ = uvec2(0u); u3_ = uvec3(0u); u4_ = uvec4(0u); diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 8253d50d9..c8df993f5 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -45,112 +45,115 @@ void main() { if ((index >= 1500u)) { return; } - vec2 _e10 = _group_0_binding_1_cs.particles[index].pos; - vPos = _e10; - vec2 _e15 = _group_0_binding_1_cs.particles[index].vel; - vVel = _e15; + vec2 _e8 = _group_0_binding_1_cs.particles[index].pos; + vPos = _e8; + vec2 _e14 = _group_0_binding_1_cs.particles[index].vel; + vVel = _e14; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); + cMassCount = 0; + cVelCount = 0; + i = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _e86 = i; - i = (_e86 + 1u); + uint _e91 = i; + i = (_e91 + 1u); } loop_init = false; - uint _e37 = i; - if ((_e37 >= 1500u)) { + uint _e36 = i; + if ((_e36 >= 1500u)) { break; } uint _e39 = i; if ((_e39 == index)) { continue; } - uint _e42 = i; - vec2 _e45 = _group_0_binding_1_cs.particles[_e42].pos; - pos = _e45; - uint _e47 = i; - vec2 _e50 = _group_0_binding_1_cs.particles[_e47].vel; - vel = _e50; - vec2 _e51 = pos; - vec2 _e52 = vPos; - float _e55 = _group_0_binding_0_cs.rule1Distance; - if ((distance(_e51, _e52) < _e55)) { - vec2 _e57 = cMass; - vec2 _e58 = pos; - cMass = (_e57 + _e58); - int _e60 = cMassCount; - cMassCount = (_e60 + 1); + uint _e43 = i; + vec2 _e46 = _group_0_binding_1_cs.particles[_e43].pos; + pos = _e46; + uint _e49 = i; + vec2 _e52 = _group_0_binding_1_cs.particles[_e49].vel; + vel = _e52; + vec2 _e53 = pos; + vec2 _e54 = vPos; + float _e58 = _group_0_binding_0_cs.rule1Distance; + if ((distance(_e53, _e54) < _e58)) { + vec2 _e60 = cMass; + vec2 _e61 = pos; + cMass = (_e60 + _e61); + int _e63 = cMassCount; + cMassCount = (_e63 + 1); } - vec2 _e63 = pos; - vec2 _e64 = vPos; - float _e67 = _group_0_binding_0_cs.rule2Distance; - if ((distance(_e63, _e64) < _e67)) { - vec2 _e69 = colVel; - vec2 _e70 = pos; - vec2 _e71 = vPos; - colVel = (_e69 - (_e70 - _e71)); + vec2 _e66 = pos; + vec2 _e67 = vPos; + float _e71 = _group_0_binding_0_cs.rule2Distance; + if ((distance(_e66, _e67) < _e71)) { + vec2 _e73 = colVel; + vec2 _e74 = pos; + vec2 _e75 = vPos; + colVel = (_e73 - (_e74 - _e75)); } - vec2 _e74 = pos; - vec2 _e75 = vPos; - float _e78 = _group_0_binding_0_cs.rule3Distance; - if ((distance(_e74, _e75) < _e78)) { - vec2 _e80 = cVel; - vec2 _e81 = vel; - cVel = (_e80 + _e81); - int _e83 = cVelCount; - cVelCount = (_e83 + 1); + vec2 _e78 = pos; + vec2 _e79 = vPos; + float _e83 = _group_0_binding_0_cs.rule3Distance; + if ((distance(_e78, _e79) < _e83)) { + vec2 _e85 = cVel; + vec2 _e86 = vel; + cVel = (_e85 + _e86); + int _e88 = cVelCount; + cVelCount = (_e88 + 1); } } - int _e89 = cMassCount; - if ((_e89 > 0)) { - vec2 _e92 = cMass; - int _e93 = cMassCount; - vec2 _e97 = vPos; - cMass = ((_e92 / vec2(float(_e93))) - _e97); + int _e94 = cMassCount; + if ((_e94 > 0)) { + vec2 _e97 = cMass; + int _e98 = cMassCount; + vec2 _e102 = vPos; + cMass = ((_e97 / vec2(float(_e98))) - _e102); } - int _e99 = cVelCount; - if ((_e99 > 0)) { - vec2 _e102 = cVel; - int _e103 = cVelCount; - cVel = (_e102 / vec2(float(_e103))); + int _e104 = cVelCount; + if ((_e104 > 0)) { + vec2 _e107 = cVel; + int _e108 = cVelCount; + cVel = (_e107 / vec2(float(_e108))); } - vec2 _e107 = vVel; - vec2 _e108 = cMass; - float _e110 = _group_0_binding_0_cs.rule1Scale; - vec2 _e113 = colVel; - float _e115 = _group_0_binding_0_cs.rule2Scale; - vec2 _e118 = cVel; - float _e120 = _group_0_binding_0_cs.rule3Scale; - vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); - vec2 _e123 = vVel; - vec2 _e125 = vVel; - vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.10000000149011612)); - vec2 _e131 = vPos; - vec2 _e132 = vVel; - float _e134 = _group_0_binding_0_cs.deltaT; - vPos = (_e131 + (_e132 * _e134)); - float _e138 = vPos.x; - if ((_e138 < -1.0)) { + vec2 _e112 = vVel; + vec2 _e113 = cMass; + float _e116 = _group_0_binding_0_cs.rule1Scale; + vec2 _e119 = colVel; + float _e122 = _group_0_binding_0_cs.rule2Scale; + vec2 _e125 = cVel; + float _e128 = _group_0_binding_0_cs.rule3Scale; + vVel = (((_e112 + (_e113 * _e116)) + (_e119 * _e122)) + (_e125 * _e128)); + vec2 _e131 = vVel; + vec2 _e133 = vVel; + vVel = (normalize(_e131) * clamp(length(_e133), 0.0, 0.10000000149011612)); + vec2 _e139 = vPos; + vec2 _e140 = vVel; + float _e143 = _group_0_binding_0_cs.deltaT; + vPos = (_e139 + (_e140 * _e143)); + float _e147 = vPos.x; + if ((_e147 < -1.0)) { vPos.x = 1.0; } - float _e144 = vPos.x; - if ((_e144 > 1.0)) { + float _e153 = vPos.x; + if ((_e153 > 1.0)) { vPos.x = -1.0; } - float _e150 = vPos.y; - if ((_e150 < -1.0)) { + float _e159 = vPos.y; + if ((_e159 < -1.0)) { vPos.y = 1.0; } - float _e156 = vPos.y; - if ((_e156 > 1.0)) { + float _e165 = vPos.y; + if ((_e165 > 1.0)) { vPos.y = -1.0; } - vec2 _e164 = vPos; - _group_0_binding_2_cs.particles[index].pos = _e164; - vec2 _e168 = vVel; - _group_0_binding_2_cs.particles[index].vel = _e168; + vec2 _e174 = vPos; + _group_0_binding_2_cs.particles[index].pos = _e174; + vec2 _e179 = vVel; + _group_0_binding_2_cs.particles[index].vel = _e179; return; } diff --git a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl index a1d8b5b05..8196d197d 100644 --- a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl +++ b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl @@ -27,27 +27,27 @@ vec4 test_textureLoad_1d(int coords, int level) { } vec4 test_textureLoad_2d(ivec2 coords_1, int level_1) { - int _e4_clamped_lod = clamp(level_1, 0, textureQueryLevels(_group_0_binding_1_fs) - 1); - vec4 _e4 = texelFetch(_group_0_binding_1_fs, clamp(coords_1, ivec2(0), textureSize(_group_0_binding_1_fs, _e4_clamped_lod) - ivec2(1)), _e4_clamped_lod); - return _e4; + int _e3_clamped_lod = clamp(level_1, 0, textureQueryLevels(_group_0_binding_1_fs) - 1); + vec4 _e3 = texelFetch(_group_0_binding_1_fs, clamp(coords_1, ivec2(0), textureSize(_group_0_binding_1_fs, _e3_clamped_lod) - ivec2(1)), _e3_clamped_lod); + return _e3; } vec4 test_textureLoad_2d_array(ivec2 coords_2, int index, int level_2) { - int _e6_clamped_lod = clamp(level_2, 0, textureQueryLevels(_group_0_binding_2_fs) - 1); - vec4 _e6 = texelFetch(_group_0_binding_2_fs, clamp(ivec3(coords_2, index), ivec3(0), textureSize(_group_0_binding_2_fs, _e6_clamped_lod) - ivec3(1)), _e6_clamped_lod); - return _e6; + int _e4_clamped_lod = clamp(level_2, 0, textureQueryLevels(_group_0_binding_2_fs) - 1); + vec4 _e4 = texelFetch(_group_0_binding_2_fs, clamp(ivec3(coords_2, index), ivec3(0), textureSize(_group_0_binding_2_fs, _e4_clamped_lod) - ivec3(1)), _e4_clamped_lod); + return _e4; } vec4 test_textureLoad_3d(ivec3 coords_3, int level_3) { - int _e6_clamped_lod = clamp(level_3, 0, textureQueryLevels(_group_0_binding_3_fs) - 1); - vec4 _e6 = texelFetch(_group_0_binding_3_fs, clamp(coords_3, ivec3(0), textureSize(_group_0_binding_3_fs, _e6_clamped_lod) - ivec3(1)), _e6_clamped_lod); - return _e6; + int _e3_clamped_lod = clamp(level_3, 0, textureQueryLevels(_group_0_binding_3_fs) - 1); + vec4 _e3 = texelFetch(_group_0_binding_3_fs, clamp(coords_3, ivec3(0), textureSize(_group_0_binding_3_fs, _e3_clamped_lod) - ivec3(1)), _e3_clamped_lod); + return _e3; } vec4 test_textureLoad_multisampled_2d(ivec2 coords_4, int _sample) { - vec4 _e7 = texelFetch(_group_0_binding_4_fs, clamp(coords_4, ivec2(0), textureSize(_group_0_binding_4_fs) - ivec2(1)), clamp(_sample, 0, textureSamples(_group_0_binding_4_fs) - 1) + vec4 _e3 = texelFetch(_group_0_binding_4_fs, clamp(coords_4, ivec2(0), textureSize(_group_0_binding_4_fs) - ivec2(1)), clamp(_sample, 0, textureSamples(_group_0_binding_4_fs) - 1) ); - return _e7; + return _e3; } void test_textureStore_1d(int coords_8, vec4 value) { @@ -71,11 +71,11 @@ void test_textureStore_3d(ivec3 coords_11, vec4 value_3) { } void main() { - vec4 _e14 = test_textureLoad_1d(0, 0); - vec4 _e17 = test_textureLoad_2d(ivec2(0, 0), 0); - vec4 _e21 = test_textureLoad_2d_array(ivec2(0, 0), 0, 0); - vec4 _e24 = test_textureLoad_3d(ivec3(0, 0, 0), 0); - vec4 _e27 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); + vec4 _e2 = test_textureLoad_1d(0, 0); + vec4 _e5 = test_textureLoad_2d(ivec2(0, 0), 0); + vec4 _e9 = test_textureLoad_2d_array(ivec2(0, 0), 0, 0); + vec4 _e12 = test_textureLoad_3d(ivec3(0, 0, 0), 0); + vec4 _e15 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); test_textureStore_1d(0, vec4(0.0, 0.0, 0.0, 0.0)); test_textureStore_2d(ivec2(0, 0), vec4(0.0, 0.0, 0.0, 0.0)); test_textureStore_2d_array(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); diff --git a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl index 9c2bef19a..50d1590d2 100644 --- a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl +++ b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl @@ -26,23 +26,23 @@ vec4 test_textureLoad_1d(int coords, int level) { } vec4 test_textureLoad_2d(ivec2 coords_1, int level_1) { - vec4 _e4 = (level_1 < textureQueryLevels(_group_0_binding_1_fs) && all(lessThan(coords_1, textureSize(_group_0_binding_1_fs, level_1))) ? texelFetch(_group_0_binding_1_fs, coords_1, level_1) : vec4(0.0)); - return _e4; + vec4 _e3 = (level_1 < textureQueryLevels(_group_0_binding_1_fs) && all(lessThan(coords_1, textureSize(_group_0_binding_1_fs, level_1))) ? texelFetch(_group_0_binding_1_fs, coords_1, level_1) : vec4(0.0)); + return _e3; } vec4 test_textureLoad_2d_array(ivec2 coords_2, int index, int level_2) { - vec4 _e6 = (level_2 < textureQueryLevels(_group_0_binding_2_fs) && all(lessThan(ivec3(coords_2, index), textureSize(_group_0_binding_2_fs, level_2))) ? texelFetch(_group_0_binding_2_fs, ivec3(coords_2, index), level_2) : vec4(0.0)); - return _e6; + vec4 _e4 = (level_2 < textureQueryLevels(_group_0_binding_2_fs) && all(lessThan(ivec3(coords_2, index), textureSize(_group_0_binding_2_fs, level_2))) ? texelFetch(_group_0_binding_2_fs, ivec3(coords_2, index), level_2) : vec4(0.0)); + return _e4; } vec4 test_textureLoad_3d(ivec3 coords_3, int level_3) { - vec4 _e6 = (level_3 < textureQueryLevels(_group_0_binding_3_fs) && all(lessThan(coords_3, textureSize(_group_0_binding_3_fs, level_3))) ? texelFetch(_group_0_binding_3_fs, coords_3, level_3) : vec4(0.0)); - return _e6; + vec4 _e3 = (level_3 < textureQueryLevels(_group_0_binding_3_fs) && all(lessThan(coords_3, textureSize(_group_0_binding_3_fs, level_3))) ? texelFetch(_group_0_binding_3_fs, coords_3, level_3) : vec4(0.0)); + return _e3; } vec4 test_textureLoad_multisampled_2d(ivec2 coords_4, int _sample) { - vec4 _e7 = (_sample < textureSamples(_group_0_binding_4_fs) && all(lessThan(coords_4, textureSize(_group_0_binding_4_fs))) ? texelFetch(_group_0_binding_4_fs, coords_4, _sample) : vec4(0.0)); - return _e7; + vec4 _e3 = (_sample < textureSamples(_group_0_binding_4_fs) && all(lessThan(coords_4, textureSize(_group_0_binding_4_fs))) ? texelFetch(_group_0_binding_4_fs, coords_4, _sample) : vec4(0.0)); + return _e3; } void test_textureStore_1d(int coords_8, vec4 value) { @@ -66,11 +66,11 @@ void test_textureStore_3d(ivec3 coords_11, vec4 value_3) { } void main() { - vec4 _e14 = test_textureLoad_1d(0, 0); - vec4 _e17 = test_textureLoad_2d(ivec2(0, 0), 0); - vec4 _e21 = test_textureLoad_2d_array(ivec2(0, 0), 0, 0); - vec4 _e24 = test_textureLoad_3d(ivec3(0, 0, 0), 0); - vec4 _e27 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); + vec4 _e2 = test_textureLoad_1d(0, 0); + vec4 _e5 = test_textureLoad_2d(ivec2(0, 0), 0); + vec4 _e9 = test_textureLoad_2d_array(ivec2(0, 0), 0, 0); + vec4 _e12 = test_textureLoad_3d(ivec3(0, 0, 0), 0); + vec4 _e15 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); test_textureStore_1d(0, vec4(0.0, 0.0, 0.0, 0.0)); test_textureStore_2d(ivec2(0, 0), vec4(0.0, 0.0, 0.0, 0.0)); test_textureStore_2d_array(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index 0d5cb797b..e77585f0b 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -5,7 +5,7 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; -struct Foo { +struct FooStruct { vec3 v3_; float v1_; }; @@ -13,7 +13,7 @@ shared float wg[10]; shared uint at_1; -layout(std430) buffer Foo_block_0Compute { Foo _group_0_binding_1_cs; }; +layout(std430) buffer FooStruct_block_0Compute { FooStruct _group_0_binding_1_cs; }; layout(std430) readonly buffer type_6_block_1Compute { vec2 _group_0_binding_2_cs[]; }; @@ -33,13 +33,14 @@ void test_msl_packed_vec3_as_arg(vec3 arg) { } void test_msl_packed_vec3_() { - int idx = 1; + int idx = 0; _group_0_binding_1_cs.v3_ = vec3(1.0); + idx = 1; _group_0_binding_1_cs.v3_.x = 1.0; _group_0_binding_1_cs.v3_.x = 2.0; - int _e23 = idx; - _group_0_binding_1_cs.v3_[_e23] = 3.0; - Foo data = _group_0_binding_1_cs; + int _e17 = idx; + _group_0_binding_1_cs.v3_[_e17] = 3.0; + FooStruct data = _group_0_binding_1_cs; vec3 unnamed = data.v3_; vec2 unnamed_1 = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); @@ -50,26 +51,28 @@ void test_msl_packed_vec3_() { } void main() { - float Foo_1 = 1.0; - bool at = true; + float Foo = 0.0; + bool at = false; test_msl_packed_vec3_(); - mat4x2 _e16 = _group_0_binding_7_cs[0][0]; - vec4 _e23 = _group_0_binding_6_cs[0][0][0]; - wg[7] = (_e16 * _e23).x; - mat3x2 _e28 = _group_0_binding_5_cs; - vec3 _e29 = _group_0_binding_4_cs; - wg[6] = (_e28 * _e29).x; - float _e37 = _group_0_binding_2_cs[1].y; - wg[5] = _e37; + mat4x2 _e8 = _group_0_binding_7_cs[0][0]; + vec4 _e16 = _group_0_binding_6_cs[0][0][0]; + wg[7] = (_e8 * _e16).x; + mat3x2 _e23 = _group_0_binding_5_cs; + vec3 _e25 = _group_0_binding_4_cs; + wg[6] = (_e23 * _e25).x; + float _e35 = _group_0_binding_2_cs[1].y; + wg[5] = _e35; float _e43 = _group_0_binding_3_cs[0].w; wg[4] = _e43; - float _e47 = _group_0_binding_1_cs.v1_; - wg[3] = _e47; - float _e52 = _group_0_binding_1_cs.v3_.x; - wg[2] = _e52; + float _e49 = _group_0_binding_1_cs.v1_; + wg[3] = _e49; + float _e56 = _group_0_binding_1_cs.v3_.x; + wg[2] = _e56; _group_0_binding_1_cs.v1_ = 4.0; wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; + Foo = 1.0; + at = true; return; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 30d7c53a3..385792339 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -31,14 +31,14 @@ vec4 splat() { vec2 splat_assignment() { vec2 a = vec2(0.0); a = vec2(2.0); - vec2 _e7 = a; - a = (_e7 + vec2(1.0)); - vec2 _e11 = a; - a = (_e11 - vec2(3.0)); + vec2 _e4 = a; + a = (_e4 + vec2(1.0)); + vec2 _e8 = a; + a = (_e8 - vec2(3.0)); + vec2 _e12 = a; + a = (_e12 / vec2(4.0)); vec2 _e15 = a; - a = (_e15 / vec2(4.0)); - vec2 _e19 = a; - return _e19; + return _e15; } vec3 bool_cast(vec3 x) { @@ -62,8 +62,8 @@ float constructors() { mat2x3 unnamed_8 = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); uvec2 unnamed_9 = uvec2(0u, 0u); mat2x3 unnamed_10 = mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); - float _e75 = foo.a.x; - return _e75; + float _e71 = foo.a.x; + return _e71; } void logical() { @@ -216,38 +216,40 @@ void comparison() { } void assignment() { - int a_1 = 1; - ivec3 vec0_ = ivec3(0, 0, 0); + int a_1 = 0; + ivec3 vec0_ = ivec3(0); + a_1 = 1; + int _e3 = a_1; + a_1 = (_e3 + 1); int _e6 = a_1; - a_1 = (_e6 + 1); + a_1 = (_e6 - 1); + int _e8 = a_1; int _e9 = a_1; - a_1 = (_e9 - 1); + a_1 = (_e9 * _e8); + int _e11 = a_1; int _e12 = a_1; - int _e13 = a_1; - a_1 = (_e12 * _e13); + a_1 = (_e12 / _e11); int _e15 = a_1; - int _e16 = a_1; - a_1 = (_e15 / _e16); + a_1 = (_e15 % 1); int _e18 = a_1; - a_1 = (_e18 % 1); + a_1 = (_e18 & 0); int _e21 = a_1; - a_1 = (_e21 & 0); + a_1 = (_e21 | 0); int _e24 = a_1; - a_1 = (_e24 | 0); + a_1 = (_e24 ^ 0); int _e27 = a_1; - a_1 = (_e27 ^ 0); + a_1 = (_e27 << 2u); int _e30 = a_1; - a_1 = (_e30 << 2u); - int _e33 = a_1; - a_1 = (_e33 >> 1u); - int _e36 = a_1; - a_1 = (_e36 + 1); - int _e39 = a_1; - a_1 = (_e39 - 1); - int _e46 = vec0_.y; - vec0_.y = (_e46 + 1); - int _e51 = vec0_.y; - vec0_.y = (_e51 - 1); + a_1 = (_e30 >> 1u); + int _e32 = a_1; + a_1 = (_e32 + 1); + int _e35 = a_1; + a_1 = (_e35 - 1); + vec0_ = ivec3(0, 0, 0); + int _e42 = vec0_.y; + vec0_.y = (_e42 + 1); + int _e47 = vec0_.y; + vec0_.y = (_e47 - 1); return; } @@ -262,10 +264,10 @@ void negation_avoids_prefix_decrement() { } void main() { - vec4 _e4 = builtins(); - vec4 _e5 = splat(); - vec3 _e7 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); - float _e8 = constructors(); + vec4 _e0 = builtins(); + vec4 _e1 = splat(); + vec3 _e4 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + float _e5 = constructors(); logical(); arithmetic(); bit(); diff --git a/tests/out/glsl/padding.vertex.Vertex.glsl b/tests/out/glsl/padding.vertex.Vertex.glsl index 21a231a37..1810cffc6 100644 --- a/tests/out/glsl/padding.vertex.Vertex.glsl +++ b/tests/out/glsl/padding.vertex.Vertex.glsl @@ -26,10 +26,10 @@ uniform Test3__block_2Vertex { Test3_ _group_0_binding_2_vs; }; void main() { - float _e6 = _group_0_binding_0_vs.b; - float _e9 = _group_0_binding_1_vs.b; + float _e4 = _group_0_binding_0_vs.b; + float _e8 = _group_0_binding_1_vs.b; float _e12 = _group_0_binding_2_vs.b; - gl_Position = (((vec4(1.0) * _e6) * _e9) * _e12); + gl_Position = (((vec4(1.0) * _e4) * _e8) * _e12); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; } diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 6c0fed433..b34e39e5c 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -40,40 +40,44 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { vec2 flip_correction = vec2(0.5, -0.5); float proj_correction = (1.0 / homogeneous_coords.w); vec2 light_local = (((homogeneous_coords.xy * flip_correction) * proj_correction) + vec2(0.5, 0.5)); - float _e28 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z * proj_correction)), vec2(0.0), vec2(0.0)); - return _e28; + float _e24 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z * proj_correction)), vec2(0.0), vec2(0.0)); + return _e24; } void main() { VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); - vec3 color = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + vec3 color = vec3(0.0); uint i = 0u; vec3 normal_1 = normalize(in_.world_normal); + color = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + i = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _e20 = i; - i = (_e20 + 1u); + uint _e39 = i; + i = (_e39 + 1u); } loop_init = false; - uint _e14 = i; - uint _e17 = _group_0_binding_0_fs.num_lights.x; - if ((_e14 < min(_e17, 10u))) { + uint _e7 = i; + uint _e11 = _group_0_binding_0_fs.num_lights.x; + if ((_e7 < min(_e11, 10u))) { } else { break; } - uint _e23 = i; - Light light = _group_0_binding_1_fs[_e23]; - uint _e26 = i; - float _e30 = fetch_shadow(_e26, (light.proj * in_.world_position)); - vec3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); - float diffuse = max(0.0, dot(normal_1, light_dir)); - vec3 _e40 = color; - color = (_e40 + ((_e30 * diffuse) * light.color.xyz)); + { + uint _e16 = i; + Light light = _group_0_binding_1_fs[_e16]; + uint _e19 = i; + float _e23 = fetch_shadow(_e19, (light.proj * in_.world_position)); + vec3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); + float diffuse = max(0.0, dot(normal_1, light_dir)); + vec3 _e37 = color; + color = (_e37 + ((_e23 * diffuse) * light.color.xyz)); + } } - vec3 _e46 = color; - vec4 _e50 = _group_1_binding_0_fs.color; - _fs2p_location0 = (vec4(_e46, 1.0) * _e50); + vec3 _e42 = color; + vec4 _e47 = _group_1_binding_0_fs.color; + _fs2p_location0 = (vec4(_e42, 1.0) * _e47); return; } diff --git a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl index 7cd75cff9..ae3dd1c86 100644 --- a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl @@ -40,40 +40,44 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { vec2 flip_correction = vec2(0.5, -0.5); float proj_correction = (1.0 / homogeneous_coords.w); vec2 light_local = (((homogeneous_coords.xy * flip_correction) * proj_correction) + vec2(0.5, 0.5)); - float _e28 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z * proj_correction)), vec2(0.0), vec2(0.0)); - return _e28; + float _e24 = textureGrad(_group_0_binding_2_fs, vec4(light_local, int(light_id), (homogeneous_coords.z * proj_correction)), vec2(0.0), vec2(0.0)); + return _e24; } void main() { VertexOutput in_1 = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); - vec3 color_1 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + vec3 color_1 = vec3(0.0); uint i_1 = 0u; vec3 normal_1 = normalize(in_1.world_normal); + color_1 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + i_1 = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _e20 = i_1; - i_1 = (_e20 + 1u); + uint _e39 = i_1; + i_1 = (_e39 + 1u); } loop_init = false; - uint _e14 = i_1; - uint _e17 = _group_0_binding_0_fs.num_lights.x; - if ((_e14 < min(_e17, 10u))) { + uint _e7 = i_1; + uint _e11 = _group_0_binding_0_fs.num_lights.x; + if ((_e7 < min(_e11, 10u))) { } else { break; } - uint _e23 = i_1; - Light light = _group_0_binding_1_fs[_e23]; - uint _e26 = i_1; - float _e30 = fetch_shadow(_e26, (light.proj * in_1.world_position)); - vec3 light_dir = normalize((light.pos.xyz - in_1.world_position.xyz)); - float diffuse = max(0.0, dot(normal_1, light_dir)); - vec3 _e40 = color_1; - color_1 = (_e40 + ((_e30 * diffuse) * light.color.xyz)); + { + uint _e16 = i_1; + Light light = _group_0_binding_1_fs[_e16]; + uint _e19 = i_1; + float _e23 = fetch_shadow(_e19, (light.proj * in_1.world_position)); + vec3 light_dir = normalize((light.pos.xyz - in_1.world_position.xyz)); + float diffuse = max(0.0, dot(normal_1, light_dir)); + vec3 _e37 = color_1; + color_1 = (_e37 + ((_e23 * diffuse) * light.color.xyz)); + } } - vec3 _e46 = color_1; - vec4 _e50 = _group_1_binding_0_fs.color; - _fs2p_location0 = (vec4(_e46, 1.0) * _e50); + vec3 _e42 = color_1; + vec4 _e47 = _group_1_binding_0_fs.color; + _fs2p_location0 = (vec4(_e42, 1.0) * _e47); return; } diff --git a/tests/out/glsl/shadow.vs_main.Vertex.glsl b/tests/out/glsl/shadow.vs_main.Vertex.glsl index dce8b2f7d..eced93ae7 100644 --- a/tests/out/glsl/shadow.vs_main.Vertex.glsl +++ b/tests/out/glsl/shadow.vs_main.Vertex.glsl @@ -39,12 +39,12 @@ void main() { vec4 world_pos = (_e7 * vec4(position)); out_.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); out_.world_position = world_pos; - mat4x4 _e25 = _group_0_binding_0_vs.view_proj; - out_.proj_position = (_e25 * world_pos); - VertexOutput _e27 = out_; - gl_Position = _e27.proj_position; - _vs2fs_location0 = _e27.world_normal; - _vs2fs_location1 = _e27.world_position; + mat4x4 _e26 = _group_0_binding_0_vs.view_proj; + out_.proj_position = (_e26 * world_pos); + VertexOutput _e28 = out_; + gl_Position = _e28.proj_position; + _vs2fs_location0 = _e28.world_normal; + _vs2fs_location1 = _e28.world_position; gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; } diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl index 2b151db2a..133461481 100644 --- a/tests/out/glsl/skybox.fs_main.Fragment.glsl +++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl @@ -18,8 +18,8 @@ layout(location = 0) out vec4 _fs2p_location0; void main() { VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0); - vec4 _e5 = texture(_group_0_binding_1_fs, vec3(in_.uv)); - _fs2p_location0 = _e5; + vec4 _e4 = texture(_group_0_binding_1_fs, vec3(in_.uv)); + _fs2p_location0 = _e4; return; } diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl index 115245a71..e40addaa2 100644 --- a/tests/out/glsl/skybox.vs_main.Vertex.glsl +++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl @@ -21,15 +21,15 @@ void main() { int tmp2_ = 0; tmp1_ = (int(vertex_index) / 2); tmp2_ = (int(vertex_index) & 1); - int _e10 = tmp1_; - int _e16 = tmp2_; - vec4 pos = vec4(((float(_e10) * 4.0) - 1.0), ((float(_e16) * 4.0) - 1.0), 0.0, 1.0); + int _e9 = tmp1_; + int _e15 = tmp2_; + vec4 pos = vec4(((float(_e9) * 4.0) - 1.0), ((float(_e15) * 4.0) - 1.0), 0.0, 1.0); vec4 _e27 = _group_0_binding_0_vs.view[0]; - vec4 _e31 = _group_0_binding_0_vs.view[1]; - vec4 _e35 = _group_0_binding_0_vs.view[2]; - mat3x3 inv_model_view = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); - mat4x4 _e40 = _group_0_binding_0_vs.proj_inv; - vec4 unprojected = (_e40 * pos); + vec4 _e32 = _group_0_binding_0_vs.view[1]; + vec4 _e37 = _group_0_binding_0_vs.view[2]; + mat3x3 inv_model_view = transpose(mat3x3(_e27.xyz, _e32.xyz, _e37.xyz)); + mat4x4 _e43 = _group_0_binding_0_vs.proj_inv; + vec4 unprojected = (_e43 * pos); VertexOutput _tmp_return = VertexOutput(pos, (inv_model_view * unprojected.xyz)); gl_Position = _tmp_return.position; _vs2fs_location0 = _tmp_return.uv; diff --git a/tests/out/glsl/texture-arg.main.Fragment.glsl b/tests/out/glsl/texture-arg.main.Fragment.glsl index 1ff2a9022..234043d95 100644 --- a/tests/out/glsl/texture-arg.main.Fragment.glsl +++ b/tests/out/glsl/texture-arg.main.Fragment.glsl @@ -8,8 +8,8 @@ uniform highp sampler2D _group_0_binding_0_fs; layout(location = 0) out vec4 _fs2p_location0; vec4 test(highp sampler2D Passed_Texture) { - vec4 _e7 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); - return _e7; + vec4 _e5 = texture(Passed_Texture, vec2(vec2(0.0, 0.0))); + return _e5; } void main() { diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 4402cfdf8..35a96e118 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -138,38 +138,39 @@ Baz ConstructBaz(float3x2 arg0) { void test_matrix_within_struct_accesses() { - int idx = 1; + int idx = (int)0; Baz t = (Baz)0; - int _expr6 = idx; - idx = (_expr6 - 1); + idx = 1; + int _expr2 = idx; + idx = (_expr2 - 1); float3x2 unnamed = GetMatmOnBaz(baz); float2 unnamed_1 = GetMatmOnBaz(baz)[0]; - int _expr16 = idx; - float2 unnamed_2 = GetMatmOnBaz(baz)[_expr16]; + int _expr15 = idx; + float2 unnamed_2 = GetMatmOnBaz(baz)[_expr15]; float unnamed_3 = GetMatmOnBaz(baz)[0].y; - int _expr28 = idx; - float unnamed_4 = GetMatmOnBaz(baz)[0][_expr28]; - int _expr32 = idx; - float unnamed_5 = GetMatmOnBaz(baz)[_expr32].y; - int _expr38 = idx; - int _expr40 = idx; - float unnamed_6 = GetMatmOnBaz(baz)[_expr38][_expr40]; + int _expr29 = idx; + float unnamed_4 = GetMatmOnBaz(baz)[0][_expr29]; + int _expr34 = idx; + float unnamed_5 = GetMatmOnBaz(baz)[_expr34].y; + int _expr41 = idx; + int _expr43 = idx; + float unnamed_6 = GetMatmOnBaz(baz)[_expr41][_expr43]; t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); - int _expr52 = idx; - idx = (_expr52 + 1); + int _expr55 = idx; + idx = (_expr55 + 1); SetMatmOnBaz(t, float3x2((6.0).xx, (5.0).xx, (4.0).xx)); t.m_0 = (9.0).xx; - int _expr69 = idx; - SetMatVecmOnBaz(t, (90.0).xx, _expr69); + int _expr72 = idx; + SetMatVecmOnBaz(t, (90.0).xx, _expr72); t.m_0[1] = 10.0; - int _expr82 = idx; - t.m_0[_expr82] = 20.0; - int _expr86 = idx; - SetMatScalarmOnBaz(t, 30.0, _expr86, 1); - int _expr92 = idx; - int _expr94 = idx; - SetMatScalarmOnBaz(t, 40.0, _expr92, _expr94); + int _expr85 = idx; + t.m_0[_expr85] = 20.0; + int _expr89 = idx; + SetMatScalarmOnBaz(t, 30.0, _expr89, 1); + int _expr95 = idx; + int _expr97 = idx; + SetMatScalarmOnBaz(t, 40.0, _expr95, _expr97); return; } @@ -181,47 +182,48 @@ MatCx2InArray ConstructMatCx2InArray(float4x2 arg0[2]) { void test_matrix_within_array_within_struct_accesses() { - int idx_1 = 1; + int idx_1 = (int)0; MatCx2InArray t_1 = (MatCx2InArray)0; - int _expr7 = idx_1; - idx_1 = (_expr7 - 1); + idx_1 = 1; + int _expr2 = idx_1; + idx_1 = (_expr2 - 1); float4x2 unnamed_7[2] = ((float4x2[2])nested_mat_cx2_.am); float4x2 unnamed_8 = ((float4x2)nested_mat_cx2_.am[0]); float2 unnamed_9 = nested_mat_cx2_.am[0]._0; - int _expr25 = idx_1; - float2 unnamed_10 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr25); + int _expr24 = idx_1; + float2 unnamed_10 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr24); float unnamed_11 = nested_mat_cx2_.am[0]._0.y; - int _expr41 = idx_1; - float unnamed_12 = nested_mat_cx2_.am[0]._0[_expr41]; - int _expr47 = idx_1; - float unnamed_13 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr47).y; - int _expr55 = idx_1; - int _expr57 = idx_1; - float unnamed_14 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr55)[_expr57]; + int _expr42 = idx_1; + float unnamed_12 = nested_mat_cx2_.am[0]._0[_expr42]; + int _expr49 = idx_1; + float unnamed_13 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr49).y; + int _expr58 = idx_1; + int _expr60 = idx_1; + float unnamed_14 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr58)[_expr60]; t_1 = ConstructMatCx2InArray(Constructarray2_float4x2_(float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0)), float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0)))); - int _expr63 = idx_1; - idx_1 = (_expr63 + 1); + int _expr66 = idx_1; + idx_1 = (_expr66 + 1); t_1.am = (__mat4x2[2])Constructarray2_float4x2_(float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0)), float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0))); t_1.am[0] = (__mat4x2)float4x2((8.0).xx, (7.0).xx, (6.0).xx, (5.0).xx); t_1.am[0]._0 = (9.0).xx; - int _expr90 = idx_1; - __set_col_of_mat4x2(t_1.am[0], _expr90, (90.0).xx); + int _expr93 = idx_1; + __set_col_of_mat4x2(t_1.am[0], _expr93, (90.0).xx); t_1.am[0]._0.y = 10.0; - int _expr107 = idx_1; - t_1.am[0]._0[_expr107] = 20.0; - int _expr113 = idx_1; - __set_el_of_mat4x2(t_1.am[0], _expr113, 1, 30.0); - int _expr121 = idx_1; - int _expr123 = idx_1; - __set_el_of_mat4x2(t_1.am[0], _expr121, _expr123, 40.0); + int _expr110 = idx_1; + t_1.am[0]._0[_expr110] = 20.0; + int _expr116 = idx_1; + __set_el_of_mat4x2(t_1.am[0], _expr116, 1, 30.0); + int _expr124 = idx_1; + int _expr126 = idx_1; + __set_el_of_mat4x2(t_1.am[0], _expr124, _expr126, 40.0); return; } float read_from_private(inout float foo_1) { - float _expr6 = foo_1; - return _expr6; + float _expr1 = foo_1; + return _expr1; } float test_arr_as_arg(float a[5][10]) @@ -250,9 +252,10 @@ ret_Constructarray5_int_ Constructarray5_int_(int arg0, int arg1, int arg2, int float4 foo_vert(uint vi : SV_VertexID) : SV_Position { - float foo = 0.0; - int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; + float foo = (float)0; + int c2_[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; + foo = 0.0; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); @@ -261,12 +264,12 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; float b = asfloat(bar.Load(0+48+0)); int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); - int2 c_1 = asint(qux.Load2(0)); - const float _e32 = read_from_private(foo); - c = Constructarray5_int_(a_1, int(b), 3, 4, 5); - c[(vi + 1u)] = 42; - int value = c[vi]; - const float _e46 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + int2 c = asint(qux.Load2(0)); + const float _e34 = read_from_private(foo); + c2_ = Constructarray5_int_(a_1, int(b), 3, 4, 5); + c2_[(vi + 1u)] = 42; + int value = c2_[vi]; + const float _e48 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); return float4(mul(float4((value).xxxx), _matrix), 2.0); } @@ -302,22 +305,22 @@ void atomics() int tmp = (int)0; int value_1 = asint(bar.Load(96)); - int _e10; bar.InterlockedAdd(96, 5, _e10); - tmp = _e10; - int _e13; bar.InterlockedAdd(96, -5, _e13); - tmp = _e13; - int _e16; bar.InterlockedAnd(96, 5, _e16); - tmp = _e16; + int _e7; bar.InterlockedAdd(96, 5, _e7); + tmp = _e7; + int _e11; bar.InterlockedAdd(96, -5, _e11); + tmp = _e11; + int _e15; bar.InterlockedAnd(96, 5, _e15); + tmp = _e15; int _e19; bar.InterlockedOr(96, 5, _e19); tmp = _e19; - int _e22; bar.InterlockedXor(96, 5, _e22); - tmp = _e22; - int _e25; bar.InterlockedMin(96, 5, _e25); - tmp = _e25; - int _e28; bar.InterlockedMax(96, 5, _e28); - tmp = _e28; - int _e31; bar.InterlockedExchange(96, 5, _e31); + int _e23; bar.InterlockedXor(96, 5, _e23); + tmp = _e23; + int _e27; bar.InterlockedMin(96, 5, _e27); + tmp = _e27; + int _e31; bar.InterlockedMax(96, 5, _e31); tmp = _e31; + int _e35; bar.InterlockedExchange(96, 5, _e35); + tmp = _e35; bar.Store(96, asuint(value_1)); return; } diff --git a/tests/out/hlsl/binding-arrays.hlsl b/tests/out/hlsl/binding-arrays.hlsl index f01d67329..b596ae28f 100644 --- a/tests/out/hlsl/binding-arrays.hlsl +++ b/tests/out/hlsl/binding-arrays.hlsl @@ -52,132 +52,134 @@ int NagaMSNumSamples2D(Texture2DMS tex) float4 main(FragmentInput_main fragmentinput_main) : SV_Target0 { FragmentIn fragment_in = { fragmentinput_main.index }; - int i1_ = 0; + int i1_ = (int)0; int2 i2_ = (int2)0; - float v1_ = 0.0; + float v1_ = (float)0; float4 v4_ = (float4)0; uint uniform_index = uni.index; uint non_uniform_index = fragment_in.index; + i1_ = 0; i2_ = (0).xx; + v1_ = 0.0; v4_ = (0.0).xxxx; float2 uv = (0.0).xx; int2 pix = (0).xx; - int2 _expr27 = i2_; - i2_ = (_expr27 + NagaDimensions2D(texture_array_unbounded[0])); - int2 _expr32 = i2_; - i2_ = (_expr32 + NagaDimensions2D(texture_array_unbounded[uniform_index])); - int2 _expr36 = i2_; - i2_ = (_expr36 + NagaDimensions2D(texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)])); - float4 _expr40 = v4_; - float4 _expr45 = texture_array_bounded[0].Gather(samp[0], uv); - v4_ = (_expr40 + _expr45); - float4 _expr47 = v4_; - float4 _expr50 = texture_array_bounded[uniform_index].Gather(samp[uniform_index], uv); - v4_ = (_expr47 + _expr50); - float4 _expr52 = v4_; + int2 _expr23 = i2_; + i2_ = (_expr23 + NagaDimensions2D(texture_array_unbounded[0])); + int2 _expr28 = i2_; + i2_ = (_expr28 + NagaDimensions2D(texture_array_unbounded[uniform_index])); + int2 _expr33 = i2_; + i2_ = (_expr33 + NagaDimensions2D(texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)])); + float4 _expr41 = texture_array_bounded[0].Gather(samp[0], uv); + float4 _expr42 = v4_; + v4_ = (_expr42 + _expr41); + float4 _expr48 = texture_array_bounded[uniform_index].Gather(samp[uniform_index], uv); + float4 _expr49 = v4_; + v4_ = (_expr49 + _expr48); float4 _expr55 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Gather(samp[NonUniformResourceIndex(non_uniform_index)], uv); - v4_ = (_expr52 + _expr55); - float4 _expr57 = v4_; - float4 _expr63 = texture_array_depth[0].GatherCmp(samp_comp[0], uv, 0.0); - v4_ = (_expr57 + _expr63); - float4 _expr65 = v4_; - float4 _expr69 = texture_array_depth[uniform_index].GatherCmp(samp_comp[uniform_index], uv, 0.0); - v4_ = (_expr65 + _expr69); - float4 _expr71 = v4_; - float4 _expr75 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].GatherCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - v4_ = (_expr71 + _expr75); - float4 _expr77 = v4_; - float4 _expr81 = texture_array_unbounded[0].Load(int3(pix, 0)); - v4_ = (_expr77 + _expr81); - float4 _expr83 = v4_; - float4 _expr86 = texture_array_unbounded[uniform_index].Load(int3(pix, 0)); - v4_ = (_expr83 + _expr86); - float4 _expr88 = v4_; - float4 _expr91 = texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)].Load(int3(pix, 0)); - v4_ = (_expr88 + _expr91); - int _expr93 = i1_; - i1_ = (_expr93 + NagaNumLayers2DArray(texture_array_2darray[0])); - int _expr98 = i1_; - i1_ = (_expr98 + NagaNumLayers2DArray(texture_array_2darray[uniform_index])); - int _expr102 = i1_; - i1_ = (_expr102 + NagaNumLayers2DArray(texture_array_2darray[NonUniformResourceIndex(non_uniform_index)])); - int _expr106 = i1_; - i1_ = (_expr106 + NagaNumLevels2D(texture_array_bounded[0])); - int _expr111 = i1_; - i1_ = (_expr111 + NagaNumLevels2D(texture_array_bounded[uniform_index])); - int _expr115 = i1_; - i1_ = (_expr115 + NagaNumLevels2D(texture_array_bounded[NonUniformResourceIndex(non_uniform_index)])); - int _expr119 = i1_; - i1_ = (_expr119 + NagaMSNumSamples2D(texture_array_multisampled[0])); - int _expr124 = i1_; - i1_ = (_expr124 + NagaMSNumSamples2D(texture_array_multisampled[uniform_index])); + float4 _expr56 = v4_; + v4_ = (_expr56 + _expr55); + float4 _expr65 = texture_array_depth[0].GatherCmp(samp_comp[0], uv, 0.0); + float4 _expr66 = v4_; + v4_ = (_expr66 + _expr65); + float4 _expr73 = texture_array_depth[uniform_index].GatherCmp(samp_comp[uniform_index], uv, 0.0); + float4 _expr74 = v4_; + v4_ = (_expr74 + _expr73); + float4 _expr81 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].GatherCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float4 _expr82 = v4_; + v4_ = (_expr82 + _expr81); + float4 _expr88 = texture_array_unbounded[0].Load(int3(pix, 0)); + float4 _expr89 = v4_; + v4_ = (_expr89 + _expr88); + float4 _expr94 = texture_array_unbounded[uniform_index].Load(int3(pix, 0)); + float4 _expr95 = v4_; + v4_ = (_expr95 + _expr94); + float4 _expr100 = texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)].Load(int3(pix, 0)); + float4 _expr101 = v4_; + v4_ = (_expr101 + _expr100); + int _expr107 = i1_; + i1_ = (_expr107 + NagaNumLayers2DArray(texture_array_2darray[0])); + int _expr112 = i1_; + i1_ = (_expr112 + NagaNumLayers2DArray(texture_array_2darray[uniform_index])); + int _expr117 = i1_; + i1_ = (_expr117 + NagaNumLayers2DArray(texture_array_2darray[NonUniformResourceIndex(non_uniform_index)])); + int _expr123 = i1_; + i1_ = (_expr123 + NagaNumLevels2D(texture_array_bounded[0])); int _expr128 = i1_; - i1_ = (_expr128 + NagaMSNumSamples2D(texture_array_multisampled[NonUniformResourceIndex(non_uniform_index)])); - float4 _expr132 = v4_; - float4 _expr137 = texture_array_bounded[0].Sample(samp[0], uv); - v4_ = (_expr132 + _expr137); - float4 _expr139 = v4_; - float4 _expr142 = texture_array_bounded[uniform_index].Sample(samp[uniform_index], uv); - v4_ = (_expr139 + _expr142); - float4 _expr144 = v4_; - float4 _expr147 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Sample(samp[NonUniformResourceIndex(non_uniform_index)], uv); - v4_ = (_expr144 + _expr147); - float4 _expr149 = v4_; - float4 _expr155 = texture_array_bounded[0].SampleBias(samp[0], uv, 0.0); - v4_ = (_expr149 + _expr155); - float4 _expr157 = v4_; - float4 _expr161 = texture_array_bounded[uniform_index].SampleBias(samp[uniform_index], uv, 0.0); - v4_ = (_expr157 + _expr161); - float4 _expr163 = v4_; - float4 _expr167 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleBias(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - v4_ = (_expr163 + _expr167); - float _expr169 = v1_; - float _expr175 = texture_array_depth[0].SampleCmp(samp_comp[0], uv, 0.0); - v1_ = (_expr169 + _expr175); - float _expr177 = v1_; - float _expr181 = texture_array_depth[uniform_index].SampleCmp(samp_comp[uniform_index], uv, 0.0); - v1_ = (_expr177 + _expr181); - float _expr183 = v1_; - float _expr187 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - v1_ = (_expr183 + _expr187); - float _expr189 = v1_; - float _expr195 = texture_array_depth[0].SampleCmpLevelZero(samp_comp[0], uv, 0.0); - v1_ = (_expr189 + _expr195); - float _expr197 = v1_; - float _expr201 = texture_array_depth[uniform_index].SampleCmpLevelZero(samp_comp[uniform_index], uv, 0.0); - v1_ = (_expr197 + _expr201); - float _expr203 = v1_; - float _expr207 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmpLevelZero(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - v1_ = (_expr203 + _expr207); - float4 _expr209 = v4_; - float4 _expr214 = texture_array_bounded[0].SampleGrad(samp[0], uv, uv, uv); - v4_ = (_expr209 + _expr214); - float4 _expr216 = v4_; - float4 _expr219 = texture_array_bounded[uniform_index].SampleGrad(samp[uniform_index], uv, uv, uv); - v4_ = (_expr216 + _expr219); - float4 _expr221 = v4_; - float4 _expr224 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleGrad(samp[NonUniformResourceIndex(non_uniform_index)], uv, uv, uv); - v4_ = (_expr221 + _expr224); - float4 _expr226 = v4_; - float4 _expr232 = texture_array_bounded[0].SampleLevel(samp[0], uv, 0.0); - v4_ = (_expr226 + _expr232); - float4 _expr234 = v4_; - float4 _expr238 = texture_array_bounded[uniform_index].SampleLevel(samp[uniform_index], uv, 0.0); - v4_ = (_expr234 + _expr238); - float4 _expr240 = v4_; - float4 _expr244 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleLevel(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - v4_ = (_expr240 + _expr244); - float4 _expr248 = v4_; - texture_array_storage[0][pix] = _expr248; - float4 _expr250 = v4_; - texture_array_storage[uniform_index][pix] = _expr250; - float4 _expr252 = v4_; - texture_array_storage[NonUniformResourceIndex(non_uniform_index)][pix] = _expr252; - int2 _expr253 = i2_; - int _expr254 = i1_; - float2 v2_ = float2((_expr253 + (_expr254).xx)); - float4 _expr258 = v4_; - float _expr265 = v1_; - return ((_expr258 + float4(v2_.x, v2_.y, v2_.x, v2_.y)) + (_expr265).xxxx); + i1_ = (_expr128 + NagaNumLevels2D(texture_array_bounded[uniform_index])); + int _expr133 = i1_; + i1_ = (_expr133 + NagaNumLevels2D(texture_array_bounded[NonUniformResourceIndex(non_uniform_index)])); + int _expr139 = i1_; + i1_ = (_expr139 + NagaMSNumSamples2D(texture_array_multisampled[0])); + int _expr144 = i1_; + i1_ = (_expr144 + NagaMSNumSamples2D(texture_array_multisampled[uniform_index])); + int _expr149 = i1_; + i1_ = (_expr149 + NagaMSNumSamples2D(texture_array_multisampled[NonUniformResourceIndex(non_uniform_index)])); + float4 _expr157 = texture_array_bounded[0].Sample(samp[0], uv); + float4 _expr158 = v4_; + v4_ = (_expr158 + _expr157); + float4 _expr164 = texture_array_bounded[uniform_index].Sample(samp[uniform_index], uv); + float4 _expr165 = v4_; + v4_ = (_expr165 + _expr164); + float4 _expr171 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Sample(samp[NonUniformResourceIndex(non_uniform_index)], uv); + float4 _expr172 = v4_; + v4_ = (_expr172 + _expr171); + float4 _expr181 = texture_array_bounded[0].SampleBias(samp[0], uv, 0.0); + float4 _expr182 = v4_; + v4_ = (_expr182 + _expr181); + float4 _expr189 = texture_array_bounded[uniform_index].SampleBias(samp[uniform_index], uv, 0.0); + float4 _expr190 = v4_; + v4_ = (_expr190 + _expr189); + float4 _expr197 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleBias(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float4 _expr198 = v4_; + v4_ = (_expr198 + _expr197); + float _expr207 = texture_array_depth[0].SampleCmp(samp_comp[0], uv, 0.0); + float _expr208 = v1_; + v1_ = (_expr208 + _expr207); + float _expr215 = texture_array_depth[uniform_index].SampleCmp(samp_comp[uniform_index], uv, 0.0); + float _expr216 = v1_; + v1_ = (_expr216 + _expr215); + float _expr223 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float _expr224 = v1_; + v1_ = (_expr224 + _expr223); + float _expr233 = texture_array_depth[0].SampleCmpLevelZero(samp_comp[0], uv, 0.0); + float _expr234 = v1_; + v1_ = (_expr234 + _expr233); + float _expr241 = texture_array_depth[uniform_index].SampleCmpLevelZero(samp_comp[uniform_index], uv, 0.0); + float _expr242 = v1_; + v1_ = (_expr242 + _expr241); + float _expr249 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmpLevelZero(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float _expr250 = v1_; + v1_ = (_expr250 + _expr249); + float4 _expr258 = texture_array_bounded[0].SampleGrad(samp[0], uv, uv, uv); + float4 _expr259 = v4_; + v4_ = (_expr259 + _expr258); + float4 _expr265 = texture_array_bounded[uniform_index].SampleGrad(samp[uniform_index], uv, uv, uv); + float4 _expr266 = v4_; + v4_ = (_expr266 + _expr265); + float4 _expr272 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleGrad(samp[NonUniformResourceIndex(non_uniform_index)], uv, uv, uv); + float4 _expr273 = v4_; + v4_ = (_expr273 + _expr272); + float4 _expr282 = texture_array_bounded[0].SampleLevel(samp[0], uv, 0.0); + float4 _expr283 = v4_; + v4_ = (_expr283 + _expr282); + float4 _expr290 = texture_array_bounded[uniform_index].SampleLevel(samp[uniform_index], uv, 0.0); + float4 _expr291 = v4_; + v4_ = (_expr291 + _expr290); + float4 _expr298 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleLevel(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float4 _expr299 = v4_; + v4_ = (_expr299 + _expr298); + float4 _expr304 = v4_; + texture_array_storage[0][pix] = _expr304; + float4 _expr307 = v4_; + texture_array_storage[uniform_index][pix] = _expr307; + float4 _expr310 = v4_; + texture_array_storage[NonUniformResourceIndex(non_uniform_index)][pix] = _expr310; + int2 _expr311 = i2_; + int _expr312 = i1_; + float2 v2_ = float2((_expr311 + (_expr312).xx)); + float4 _expr316 = v4_; + float _expr323 = v1_; + return ((_expr316 + float4(v2_.x, v2_.y, v2_.x, v2_.y)) + (_expr323).xxxx); } diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index fb4640a76..d9f134048 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -27,121 +27,124 @@ void main(uint3 global_invocation_id : SV_DispatchThreadID) float2 cMass = (float2)0; float2 cVel = (float2)0; float2 colVel = (float2)0; - int cMassCount = 0; - int cVelCount = 0; + int cMassCount = (int)0; + int cVelCount = (int)0; float2 pos = (float2)0; float2 vel = (float2)0; - uint i = 0u; + uint i = (uint)0; uint index = global_invocation_id.x; if ((index >= NUM_PARTICLES)) { return; } - float2 _expr10 = asfloat(particlesSrc.Load2(0+index*16+0)); - vPos = _expr10; - float2 _expr15 = asfloat(particlesSrc.Load2(8+index*16+0)); - vVel = _expr15; + float2 _expr8 = asfloat(particlesSrc.Load2(0+index*16+0)); + vPos = _expr8; + float2 _expr14 = asfloat(particlesSrc.Load2(8+index*16+0)); + vVel = _expr14; cMass = float2(0.0, 0.0); cVel = float2(0.0, 0.0); colVel = float2(0.0, 0.0); + cMassCount = 0; + cVelCount = 0; + i = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _expr86 = i; - i = (_expr86 + 1u); + uint _expr91 = i; + i = (_expr91 + 1u); } loop_init = false; - uint _expr37 = i; - if ((_expr37 >= NUM_PARTICLES)) { + uint _expr36 = i; + if ((_expr36 >= NUM_PARTICLES)) { break; } uint _expr39 = i; if ((_expr39 == index)) { continue; } - uint _expr42 = i; - float2 _expr45 = asfloat(particlesSrc.Load2(0+_expr42*16+0)); - pos = _expr45; - uint _expr47 = i; - float2 _expr50 = asfloat(particlesSrc.Load2(8+_expr47*16+0)); - vel = _expr50; - float2 _expr51 = pos; - float2 _expr52 = vPos; - float _expr55 = params.rule1Distance; - if ((distance(_expr51, _expr52) < _expr55)) { - float2 _expr57 = cMass; - float2 _expr58 = pos; - cMass = (_expr57 + _expr58); - int _expr60 = cMassCount; - cMassCount = (_expr60 + 1); + uint _expr43 = i; + float2 _expr46 = asfloat(particlesSrc.Load2(0+_expr43*16+0)); + pos = _expr46; + uint _expr49 = i; + float2 _expr52 = asfloat(particlesSrc.Load2(8+_expr49*16+0)); + vel = _expr52; + float2 _expr53 = pos; + float2 _expr54 = vPos; + float _expr58 = params.rule1Distance; + if ((distance(_expr53, _expr54) < _expr58)) { + float2 _expr60 = cMass; + float2 _expr61 = pos; + cMass = (_expr60 + _expr61); + int _expr63 = cMassCount; + cMassCount = (_expr63 + 1); } - float2 _expr63 = pos; - float2 _expr64 = vPos; - float _expr67 = params.rule2Distance; - if ((distance(_expr63, _expr64) < _expr67)) { - float2 _expr69 = colVel; - float2 _expr70 = pos; - float2 _expr71 = vPos; - colVel = (_expr69 - (_expr70 - _expr71)); + float2 _expr66 = pos; + float2 _expr67 = vPos; + float _expr71 = params.rule2Distance; + if ((distance(_expr66, _expr67) < _expr71)) { + float2 _expr73 = colVel; + float2 _expr74 = pos; + float2 _expr75 = vPos; + colVel = (_expr73 - (_expr74 - _expr75)); } - float2 _expr74 = pos; - float2 _expr75 = vPos; - float _expr78 = params.rule3Distance; - if ((distance(_expr74, _expr75) < _expr78)) { - float2 _expr80 = cVel; - float2 _expr81 = vel; - cVel = (_expr80 + _expr81); - int _expr83 = cVelCount; - cVelCount = (_expr83 + 1); + float2 _expr78 = pos; + float2 _expr79 = vPos; + float _expr83 = params.rule3Distance; + if ((distance(_expr78, _expr79) < _expr83)) { + float2 _expr85 = cVel; + float2 _expr86 = vel; + cVel = (_expr85 + _expr86); + int _expr88 = cVelCount; + cVelCount = (_expr88 + 1); } } - int _expr89 = cMassCount; - if ((_expr89 > 0)) { - float2 _expr92 = cMass; - int _expr93 = cMassCount; - float2 _expr97 = vPos; - cMass = ((_expr92 / (float(_expr93)).xx) - _expr97); + int _expr94 = cMassCount; + if ((_expr94 > 0)) { + float2 _expr97 = cMass; + int _expr98 = cMassCount; + float2 _expr102 = vPos; + cMass = ((_expr97 / (float(_expr98)).xx) - _expr102); } - int _expr99 = cVelCount; - if ((_expr99 > 0)) { - float2 _expr102 = cVel; - int _expr103 = cVelCount; - cVel = (_expr102 / (float(_expr103)).xx); + int _expr104 = cVelCount; + if ((_expr104 > 0)) { + float2 _expr107 = cVel; + int _expr108 = cVelCount; + cVel = (_expr107 / (float(_expr108)).xx); } - float2 _expr107 = vVel; - float2 _expr108 = cMass; - float _expr110 = params.rule1Scale; - float2 _expr113 = colVel; - float _expr115 = params.rule2Scale; - float2 _expr118 = cVel; - float _expr120 = params.rule3Scale; - vVel = (((_expr107 + (_expr108 * _expr110)) + (_expr113 * _expr115)) + (_expr118 * _expr120)); - float2 _expr123 = vVel; - float2 _expr125 = vVel; - vVel = (normalize(_expr123) * clamp(length(_expr125), 0.0, 0.10000000149011612)); - float2 _expr131 = vPos; - float2 _expr132 = vVel; - float _expr134 = params.deltaT; - vPos = (_expr131 + (_expr132 * _expr134)); - float _expr138 = vPos.x; - if ((_expr138 < -1.0)) { + float2 _expr112 = vVel; + float2 _expr113 = cMass; + float _expr116 = params.rule1Scale; + float2 _expr119 = colVel; + float _expr122 = params.rule2Scale; + float2 _expr125 = cVel; + float _expr128 = params.rule3Scale; + vVel = (((_expr112 + (_expr113 * _expr116)) + (_expr119 * _expr122)) + (_expr125 * _expr128)); + float2 _expr131 = vVel; + float2 _expr133 = vVel; + vVel = (normalize(_expr131) * clamp(length(_expr133), 0.0, 0.10000000149011612)); + float2 _expr139 = vPos; + float2 _expr140 = vVel; + float _expr143 = params.deltaT; + vPos = (_expr139 + (_expr140 * _expr143)); + float _expr147 = vPos.x; + if ((_expr147 < -1.0)) { vPos.x = 1.0; } - float _expr144 = vPos.x; - if ((_expr144 > 1.0)) { + float _expr153 = vPos.x; + if ((_expr153 > 1.0)) { vPos.x = -1.0; } - float _expr150 = vPos.y; - if ((_expr150 < -1.0)) { + float _expr159 = vPos.y; + if ((_expr159 < -1.0)) { vPos.y = 1.0; } - float _expr156 = vPos.y; - if ((_expr156 > 1.0)) { + float _expr165 = vPos.y; + if ((_expr165 > 1.0)) { vPos.y = -1.0; } - float2 _expr164 = vPos; - particlesDst.Store2(0+index*16+0, asuint(_expr164)); - float2 _expr168 = vVel; - particlesDst.Store2(8+index*16+0, asuint(_expr168)); + float2 _expr174 = vPos; + particlesDst.Store2(0+index*16+0, asuint(_expr174)); + float2 _expr179 = vVel; + particlesDst.Store2(8+index*16+0, asuint(_expr179)); return; } diff --git a/tests/out/hlsl/collatz.hlsl b/tests/out/hlsl/collatz.hlsl index d74efad89..aa0412965 100644 --- a/tests/out/hlsl/collatz.hlsl +++ b/tests/out/hlsl/collatz.hlsl @@ -4,35 +4,38 @@ RWByteAddressBuffer v_indices : register(u0); uint collatz_iterations(uint n_base) { uint n = (uint)0; - uint i = 0u; + uint i = (uint)0; n = n_base; + i = 0u; while(true) { - uint _expr5 = n; - if ((_expr5 > 1u)) { + uint _expr4 = n; + if ((_expr4 > 1u)) { } else { break; } - uint _expr8 = n; - if (((_expr8 % 2u) == 0u)) { - uint _expr13 = n; - n = (_expr13 / 2u); - } else { - uint _expr17 = n; - n = ((3u * _expr17) + 1u); + { + uint _expr7 = n; + if (((_expr7 % 2u) == 0u)) { + uint _expr12 = n; + n = (_expr12 / 2u); + } else { + uint _expr16 = n; + n = ((3u * _expr16) + 1u); + } + uint _expr20 = i; + i = (_expr20 + 1u); } - uint _expr21 = i; - i = (_expr21 + 1u); } - uint _expr24 = i; - return _expr24; + uint _expr23 = i; + return _expr23; } [numthreads(1, 1, 1)] void main(uint3 global_id : SV_DispatchThreadID) { - uint _expr8 = asuint(v_indices.Load(global_id.x*4+0)); - const uint _e9 = collatz_iterations(_expr8); - v_indices.Store(global_id.x*4+0, asuint(_e9)); + uint _expr9 = asuint(v_indices.Load(global_id.x*4+0)); + const uint _e10 = collatz_iterations(_expr9); + v_indices.Store(global_id.x*4+0, asuint(_e10)); return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index def5c8dbb..d941f8e09 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -1,4 +1,4 @@ -static const bool Foo_2 = true; +static const bool Foo_1 = true; typedef struct { float2 _0; float2 _1; float2 _2; } __mat3x2; float2 __get_col_of_mat3x2(__mat3x2 mat, uint idx) { @@ -51,7 +51,7 @@ void __set_el_of_mat4x2(__mat4x2 mat, uint idx, uint vec_idx, float value) { } } -struct Foo { +struct FooStruct { float3 v3_; float v1_; }; @@ -71,8 +71,8 @@ void test_msl_packed_vec3_as_arg(float3 arg) return; } -Foo ConstructFoo(float3 arg0, float arg1) { - Foo ret = (Foo)0; +FooStruct ConstructFooStruct(float3 arg0, float arg1) { + FooStruct ret = (FooStruct)0; ret.v3_ = arg0; ret.v1_ = arg1; return ret; @@ -80,14 +80,15 @@ Foo ConstructFoo(float3 arg0, float arg1) { void test_msl_packed_vec3_() { - int idx = 1; + int idx = (int)0; alignment.Store3(0, asuint((1.0).xxx)); + idx = 1; alignment.Store(0+0, asuint(1.0)); alignment.Store(0+0, asuint(2.0)); - int _expr23 = idx; - alignment.Store(_expr23*4+0, asuint(3.0)); - Foo data = ConstructFoo(asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))); + int _expr17 = idx; + alignment.Store(_expr17*4+0, asuint(3.0)); + FooStruct data = ConstructFooStruct(asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))); float3 unnamed = data.v3_; float2 unnamed_1 = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); @@ -107,26 +108,28 @@ uint NagaBufferLength(ByteAddressBuffer buffer) [numthreads(1, 1, 1)] void main() { - float Foo_1 = 1.0; - bool at = true; + float Foo = (float)0; + bool at = (bool)0; test_msl_packed_vec3_(); - float4x2 _expr16 = ((float4x2)global_nested_arrays_of_matrices_4x2_[0][0]); - float4 _expr23 = global_nested_arrays_of_matrices_2x4_[0][0][0]; - wg[7] = mul(_expr23, _expr16).x; - float3x2 _expr28 = ((float3x2)global_mat); - float3 _expr29 = global_vec; - wg[6] = mul(_expr29, _expr28).x; - float _expr37 = asfloat(dummy.Load(4+8)); - wg[5] = _expr37; + float4x2 _expr8 = ((float4x2)global_nested_arrays_of_matrices_4x2_[0][0]); + float4 _expr16 = global_nested_arrays_of_matrices_2x4_[0][0][0]; + wg[7] = mul(_expr16, _expr8).x; + float3x2 _expr23 = ((float3x2)global_mat); + float3 _expr25 = global_vec; + wg[6] = mul(_expr25, _expr23).x; + float _expr35 = asfloat(dummy.Load(4+8)); + wg[5] = _expr35; float _expr43 = float_vecs[0].w; wg[4] = _expr43; - float _expr47 = asfloat(alignment.Load(12)); - wg[3] = _expr47; - float _expr52 = asfloat(alignment.Load(0+0)); - wg[2] = _expr52; + float _expr49 = asfloat(alignment.Load(12)); + wg[3] = _expr49; + float _expr56 = asfloat(alignment.Load(0+0)); + wg[2] = _expr56; alignment.Store(12, asuint(4.0)); wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; + Foo = 1.0; + at = true; return; } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index c88d1ee77..99d5ecccb 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -83,8 +83,9 @@ void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThr precise float4 vertex_two_structs(Input1_ in1_, Input2_ in2_) : SV_Position { - uint index = 2u; + uint index = (uint)0; - uint _expr9 = index; - return float4(float((_NagaConstants.base_vertex + in1_.index)), float((_NagaConstants.base_instance + in2_.index)), float(_expr9), 0.0); + index = 2u; + uint _expr8 = index; + return float4(float((_NagaConstants.base_vertex + in1_.index)), float((_NagaConstants.base_instance + in2_.index)), float(_expr8), 0.0); } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 743ca2813..3136972d4 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -49,14 +49,14 @@ float2 splat_assignment() float2 a = (float2)0; a = (2.0).xx; - float2 _expr7 = a; - a = (_expr7 + (1.0).xx); - float2 _expr11 = a; - a = (_expr11 - (3.0).xx); + float2 _expr4 = a; + a = (_expr4 + (1.0).xx); + float2 _expr8 = a; + a = (_expr8 - (3.0).xx); + float2 _expr12 = a; + a = (_expr12 / (4.0).xx); float2 _expr15 = a; - a = (_expr15 / (4.0).xx); - float2 _expr19 = a; - return _expr19; + return _expr15; } float3 bool_cast(float3 x) @@ -89,8 +89,8 @@ float constructors() float2x3 unnamed_8 = float2x3(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); uint2 unnamed_9 = asuint(uint2(0u, 0u)); float2x3 unnamed_10 = asfloat(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float _expr75 = foo.a.x; - return _expr75; + float _expr71 = foo.a.x; + return _expr71; } void logical() @@ -248,39 +248,41 @@ void comparison() void assignment() { - int a_1 = 1; - int3 vec0_ = int3(0, 0, 0); + int a_1 = (int)0; + int3 vec0_ = (int3)0; + a_1 = 1; + int _expr3 = a_1; + a_1 = (_expr3 + 1); int _expr6 = a_1; - a_1 = (_expr6 + 1); + a_1 = (_expr6 - 1); + int _expr8 = a_1; int _expr9 = a_1; - a_1 = (_expr9 - 1); + a_1 = (_expr9 * _expr8); + int _expr11 = a_1; int _expr12 = a_1; - int _expr13 = a_1; - a_1 = (_expr12 * _expr13); + a_1 = (_expr12 / _expr11); int _expr15 = a_1; - int _expr16 = a_1; - a_1 = (_expr15 / _expr16); + a_1 = (_expr15 % 1); int _expr18 = a_1; - a_1 = (_expr18 % 1); + a_1 = (_expr18 & 0); int _expr21 = a_1; - a_1 = (_expr21 & 0); + a_1 = (_expr21 | 0); int _expr24 = a_1; - a_1 = (_expr24 | 0); + a_1 = (_expr24 ^ 0); int _expr27 = a_1; - a_1 = (_expr27 ^ 0); + a_1 = (_expr27 << 2u); int _expr30 = a_1; - a_1 = (_expr30 << 2u); - int _expr33 = a_1; - a_1 = (_expr33 >> 1u); - int _expr36 = a_1; - a_1 = (_expr36 + 1); - int _expr39 = a_1; - a_1 = (_expr39 - 1); - int _expr46 = vec0_.y; - vec0_.y = (_expr46 + 1); - int _expr51 = vec0_.y; - vec0_.y = (_expr51 - 1); + a_1 = (_expr30 >> 1u); + int _expr32 = a_1; + a_1 = (_expr32 + 1); + int _expr35 = a_1; + a_1 = (_expr35 - 1); + vec0_ = int3(0, 0, 0); + int _expr42 = vec0_.y; + vec0_.y = (_expr42 + 1); + int _expr47 = vec0_.y; + vec0_.y = (_expr47 - 1); return; } @@ -298,10 +300,10 @@ void negation_avoids_prefix_decrement() [numthreads(1, 1, 1)] void main() { - const float4 _e4 = builtins(); - const float4 _e5 = splat(); - const float3 _e7 = bool_cast(float4(1.0, 1.0, 1.0, 1.0).xyz); - const float _e8 = constructors(); + const float4 _e0 = builtins(); + const float4 _e1 = splat(); + const float3 _e4 = bool_cast(float4(1.0, 1.0, 1.0, 1.0).xyz); + const float _e5 = constructors(); logical(); arithmetic(); bit(); diff --git a/tests/out/hlsl/padding.hlsl b/tests/out/hlsl/padding.hlsl index f833b936c..32e762cce 100644 --- a/tests/out/hlsl/padding.hlsl +++ b/tests/out/hlsl/padding.hlsl @@ -36,8 +36,8 @@ cbuffer input3_ : register(b2) { Test3_ input3_; } float4 vertex() : SV_Position { - float _expr6 = input1_.b; - float _expr9 = input2_.b; + float _expr4 = input1_.b; + float _expr8 = input2_.b; float _expr12 = input3_.b; - return ((((1.0).xxxx * _expr6) * _expr9) * _expr12); + return ((((1.0).xxxx * _expr4) * _expr8) * _expr12); } diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index a3942386b..5ea06f90c 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -56,8 +56,8 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords) float2 flip_correction = float2(0.5, -0.5); float proj_correction = (1.0 / homogeneous_coords.w); float2 light_local = (((homogeneous_coords.xy * flip_correction) * proj_correction) + float2(0.5, 0.5)); - float _expr28 = t_shadow.SampleCmpLevelZero(sampler_shadow, float3(light_local, int(light_id)), (homogeneous_coords.z * proj_correction)); - return _expr28; + float _expr24 = t_shadow.SampleCmpLevelZero(sampler_shadow, float3(light_local, int(light_id)), (homogeneous_coords.z * proj_correction)); + return _expr24; } VertexOutput_vs_main vs_main(int4 position : LOC0, int4 normal : LOC1) @@ -69,10 +69,10 @@ VertexOutput_vs_main vs_main(int4 position : LOC0, int4 normal : LOC1) float4 world_pos = mul(float4(position), _expr7); out_.world_normal = mul(float3(normal.xyz), float3x3(w[0].xyz, w[1].xyz, w[2].xyz)); out_.world_position = world_pos; - float4x4 _expr25 = u_globals.view_proj; - out_.proj_position = mul(world_pos, _expr25); - VertexOutput _expr27 = out_; - const VertexOutput vertexoutput = _expr27; + float4x4 _expr26 = u_globals.view_proj; + out_.proj_position = mul(world_pos, _expr26); + VertexOutput _expr28 = out_; + const VertexOutput vertexoutput = _expr28; const VertexOutput_vs_main vertexoutput_1 = { vertexoutput.world_normal, vertexoutput.world_position, vertexoutput.proj_position }; return vertexoutput_1; } @@ -88,67 +88,75 @@ Light ConstructLight(float4x4 arg0, float4 arg1, float4 arg2) { float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { VertexOutput in_ = { fragmentinput_fs_main.proj_position_1, fragmentinput_fs_main.world_normal_1, fragmentinput_fs_main.world_position_1 }; - float3 color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); - uint i = 0u; + float3 color = (float3)0; + uint i = (uint)0; float3 normal_1 = normalize(in_.world_normal); + color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + i = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _expr20 = i; - i = (_expr20 + 1u); + uint _expr39 = i; + i = (_expr39 + 1u); } loop_init = false; - uint _expr14 = i; - uint _expr17 = u_globals.num_lights.x; - if ((_expr14 < min(_expr17, c_max_lights))) { + uint _expr7 = i; + uint _expr11 = u_globals.num_lights.x; + if ((_expr7 < min(_expr11, c_max_lights))) { } else { break; } - uint _expr23 = i; - Light light = ConstructLight(float4x4(asfloat(s_lights.Load4(_expr23*96+0+0)), asfloat(s_lights.Load4(_expr23*96+0+16)), asfloat(s_lights.Load4(_expr23*96+0+32)), asfloat(s_lights.Load4(_expr23*96+0+48))), asfloat(s_lights.Load4(_expr23*96+64)), asfloat(s_lights.Load4(_expr23*96+80))); - uint _expr26 = i; - const float _e30 = fetch_shadow(_expr26, mul(in_.world_position, light.proj)); - float3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); - float diffuse = max(0.0, dot(normal_1, light_dir)); - float3 _expr40 = color; - color = (_expr40 + ((_e30 * diffuse) * light.color.xyz)); + { + uint _expr16 = i; + Light light = ConstructLight(float4x4(asfloat(s_lights.Load4(_expr16*96+0+0)), asfloat(s_lights.Load4(_expr16*96+0+16)), asfloat(s_lights.Load4(_expr16*96+0+32)), asfloat(s_lights.Load4(_expr16*96+0+48))), asfloat(s_lights.Load4(_expr16*96+64)), asfloat(s_lights.Load4(_expr16*96+80))); + uint _expr19 = i; + const float _e23 = fetch_shadow(_expr19, mul(in_.world_position, light.proj)); + float3 light_dir = normalize((light.pos.xyz - in_.world_position.xyz)); + float diffuse = max(0.0, dot(normal_1, light_dir)); + float3 _expr37 = color; + color = (_expr37 + ((_e23 * diffuse) * light.color.xyz)); + } } - float3 _expr46 = color; - float4 _expr50 = u_entity.color; - return (float4(_expr46, 1.0) * _expr50); + float3 _expr42 = color; + float4 _expr47 = u_entity.color; + return (float4(_expr42, 1.0) * _expr47); } float4 fs_main_without_storage(FragmentInput_fs_main_without_storage fragmentinput_fs_main_without_storage) : SV_Target0 { VertexOutput in_1 = { fragmentinput_fs_main_without_storage.proj_position_2, fragmentinput_fs_main_without_storage.world_normal_2, fragmentinput_fs_main_without_storage.world_position_2 }; - float3 color_1 = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); - uint i_1 = 0u; + float3 color_1 = (float3)0; + uint i_1 = (uint)0; float3 normal_2 = normalize(in_1.world_normal); + color_1 = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + i_1 = 0u; bool loop_init_1 = true; while(true) { if (!loop_init_1) { - uint _expr20 = i_1; - i_1 = (_expr20 + 1u); + uint _expr39 = i_1; + i_1 = (_expr39 + 1u); } loop_init_1 = false; - uint _expr14 = i_1; - uint _expr17 = u_globals.num_lights.x; - if ((_expr14 < min(_expr17, c_max_lights))) { + uint _expr7 = i_1; + uint _expr11 = u_globals.num_lights.x; + if ((_expr7 < min(_expr11, c_max_lights))) { } else { break; } - uint _expr23 = i_1; - Light light_1 = u_lights[_expr23]; - uint _expr26 = i_1; - const float _e30 = fetch_shadow(_expr26, mul(in_1.world_position, light_1.proj)); - float3 light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); - float diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); - float3 _expr40 = color_1; - color_1 = (_expr40 + ((_e30 * diffuse_1) * light_1.color.xyz)); + { + uint _expr16 = i_1; + Light light_1 = u_lights[_expr16]; + uint _expr19 = i_1; + const float _e23 = fetch_shadow(_expr19, mul(in_1.world_position, light_1.proj)); + float3 light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); + float diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); + float3 _expr37 = color_1; + color_1 = (_expr37 + ((_e23 * diffuse_1) * light_1.color.xyz)); + } } - float3 _expr46 = color_1; - float4 _expr50 = u_entity.color; - return (float4(_expr46, 1.0) * _expr50); + float3 _expr42 = color_1; + float4 _expr47 = u_entity.color; + return (float4(_expr42, 1.0) * _expr47); } diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl index 7d5714a22..7a6a36b87 100644 --- a/tests/out/hlsl/skybox.hlsl +++ b/tests/out/hlsl/skybox.hlsl @@ -43,15 +43,15 @@ VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) tmp1_ = (int((_NagaConstants.base_vertex + vertex_index)) / 2); tmp2_ = (int((_NagaConstants.base_vertex + vertex_index)) & 1); - int _expr10 = tmp1_; - int _expr16 = tmp2_; - float4 pos = float4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0); + int _expr9 = tmp1_; + int _expr15 = tmp2_; + float4 pos = float4(((float(_expr9) * 4.0) - 1.0), ((float(_expr15) * 4.0) - 1.0), 0.0, 1.0); float4 _expr27 = r_data.view[0]; - float4 _expr31 = r_data.view[1]; - float4 _expr35 = r_data.view[2]; - float3x3 inv_model_view = transpose(float3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz)); - float4x4 _expr40 = r_data.proj_inv; - float4 unprojected = mul(pos, _expr40); + float4 _expr32 = r_data.view[1]; + float4 _expr37 = r_data.view[2]; + float3x3 inv_model_view = transpose(float3x3(_expr27.xyz, _expr32.xyz, _expr37.xyz)); + float4x4 _expr43 = r_data.proj_inv; + float4 unprojected = mul(pos, _expr43); const VertexOutput vertexoutput = ConstructVertexOutput(pos, mul(unprojected.xyz, inv_model_view)); const VertexOutput_vs_main vertexoutput_1 = { vertexoutput.uv, vertexoutput.position }; return vertexoutput_1; @@ -60,6 +60,6 @@ VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID) float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { VertexOutput in_ = { fragmentinput_fs_main.position_1, fragmentinput_fs_main.uv_1 }; - float4 _expr5 = r_texture.Sample(r_sampler, in_.uv); - return _expr5; + float4 _expr4 = r_texture.Sample(r_sampler, in_.uv); + return _expr4; } diff --git a/tests/out/hlsl/texture-arg.hlsl b/tests/out/hlsl/texture-arg.hlsl index 32f950dff..dd0ca1096 100644 --- a/tests/out/hlsl/texture-arg.hlsl +++ b/tests/out/hlsl/texture-arg.hlsl @@ -4,8 +4,8 @@ SamplerState Sampler : register(s1); float4 test(Texture2D Passed_Texture, SamplerState Passed_Sampler) { - float4 _expr7 = Passed_Texture.Sample(Passed_Sampler, float2(0.0, 0.0)); - return _expr7; + float4 _expr5 = Passed_Texture.Sample(Passed_Sampler, float2(0.0, 0.0)); + return _expr5; } float4 main() : SV_Target0 diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 2f3d06d13..00cab8e88 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -111,164 +111,171 @@ ( name: Some("i"), ty: 1, - init: Some(1), + init: None, ), ], expressions: [ - GlobalVariable(1), FunctionArgument(0), LocalVariable(1), Constant(1), LocalVariable(2), Load( - pointer: 3, + pointer: 2, ), Constant(2), Binary( op: Greater, - left: 6, - right: 7, + left: 5, + right: 6, ), Load( - pointer: 3, + pointer: 2, ), Constant(3), Binary( op: Modulo, - left: 9, - right: 10, + left: 8, + right: 9, ), Constant(1), Binary( op: Equal, - left: 11, - right: 12, + left: 10, + right: 11, ), Load( - pointer: 3, + pointer: 2, ), Constant(3), Binary( op: Divide, - left: 14, - right: 15, + left: 13, + right: 14, ), Constant(4), Load( - pointer: 3, + pointer: 2, ), Binary( op: Multiply, - left: 17, - right: 18, + left: 16, + right: 17, ), Constant(2), Binary( op: Add, - left: 19, - right: 20, + left: 18, + right: 19, ), Load( - pointer: 5, + pointer: 4, ), Constant(2), Binary( op: Add, - left: 22, - right: 23, + left: 21, + right: 22, ), Load( - pointer: 5, + pointer: 4, ), ], - named_expressions: {}, + named_expressions: { + 1: "n_base", + }, body: [ Store( - pointer: 3, - value: 2, + pointer: 2, + value: 1, + ), + Store( + pointer: 4, + value: 3, ), Loop( body: [ Emit(( - start: 5, - end: 6, + start: 4, + end: 5, )), Emit(( - start: 7, - end: 8, + start: 6, + end: 7, )), If( - condition: 8, + condition: 7, accept: [], reject: [ Break, ], ), - Emit(( - start: 8, - end: 9, - )), - Emit(( - start: 10, - end: 11, - )), - Emit(( - start: 12, - end: 13, - )), - If( - condition: 13, - accept: [ - Emit(( - start: 13, - end: 14, - )), - Emit(( - start: 15, - end: 16, - )), - Store( - pointer: 3, - value: 16, - ), - ], - reject: [ - Emit(( - start: 17, - end: 19, - )), - Emit(( - start: 20, - end: 21, - )), - Store( - pointer: 3, - value: 21, - ), - ], - ), - Emit(( - start: 21, - end: 22, - )), - Emit(( - start: 23, - end: 24, - )), - Store( - pointer: 5, - value: 24, - ), + Block([ + Emit(( + start: 7, + end: 8, + )), + Emit(( + start: 9, + end: 10, + )), + Emit(( + start: 11, + end: 12, + )), + If( + condition: 12, + accept: [ + Emit(( + start: 12, + end: 13, + )), + Emit(( + start: 14, + end: 15, + )), + Store( + pointer: 2, + value: 15, + ), + ], + reject: [ + Emit(( + start: 16, + end: 18, + )), + Emit(( + start: 19, + end: 20, + )), + Store( + pointer: 2, + value: 20, + ), + ], + ), + Emit(( + start: 20, + end: 21, + )), + Emit(( + start: 22, + end: 23, + )), + Store( + pointer: 4, + value: 23, + ), + ]), ], continuing: [], break_if: None, ), Emit(( - start: 24, - end: 25, + start: 23, + end: 24, )), Return( - value: Some(25), + value: Some(24), ), ], ), @@ -291,53 +298,60 @@ result: None, local_variables: [], expressions: [ - GlobalVariable(1), FunctionArgument(0), + GlobalVariable(1), AccessIndex( - base: 1, + base: 2, index: 0, ), AccessIndex( - base: 2, + base: 1, index: 0, ), Access( base: 3, index: 4, ), + GlobalVariable(1), + AccessIndex( + base: 6, + index: 0, + ), AccessIndex( base: 1, index: 0, ), - AccessIndex( - base: 2, - index: 0, - ), Access( - base: 6, - index: 7, + base: 7, + index: 8, ), Load( - pointer: 8, + pointer: 9, ), CallResult(1), ], - named_expressions: {}, + named_expressions: { + 1: "global_id", + }, body: [ Emit(( start: 2, - end: 9, + end: 5, + )), + Emit(( + start: 6, + end: 10, )), Call( function: 1, arguments: [ - 9, + 10, ], - result: Some(10), + result: Some(11), ), Store( pointer: 5, - value: 10, + value: 11, ), Return( value: None, diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 19e4ab21d..245f8a2be 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -35,11 +35,11 @@ struct Bar { struct Baz { metal::float3x2 m; }; -struct type_13 { +struct type_14 { metal::float4x2 inner[2]; }; struct MatCx2InArray { - type_13 am; + type_14 am; }; struct type_17 { float inner[10]; @@ -52,9 +52,9 @@ struct type_21 { }; constant metal::uint3 const_type_1_ = {0u, 0u, 0u}; constant GlobalConst const_GlobalConst = {0u, {}, const_type_1_, 0}; -constant metal::float2 const_type_14_ = {0.0, 0.0}; -constant metal::float4x2 const_type_12_ = {const_type_14_, const_type_14_, const_type_14_, const_type_14_}; -constant type_13 const_type_13_ = {const_type_12_, const_type_12_}; +constant metal::float2 const_type_12_ = {0.0, 0.0}; +constant metal::float4x2 const_type_13_ = {const_type_12_, const_type_12_, const_type_12_, const_type_12_}; +constant type_14 const_type_14_ = {const_type_13_, const_type_13_}; constant type_17 const_type_17_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; constant type_18 const_type_18_ = {const_type_17_, const_type_17_, const_type_17_, const_type_17_, const_type_17_}; constant metal::int2 const_type_11_ = {0, 0}; @@ -62,84 +62,86 @@ constant metal::int2 const_type_11_ = {0, 0}; void test_matrix_within_struct_accesses( constant Baz& baz ) { - int idx = 1; + int idx = {}; Baz t = {}; - int _e6 = idx; - idx = _e6 - 1; + idx = 1; + int _e2 = idx; + idx = _e2 - 1; metal::float3x2 unnamed = baz.m; metal::float2 unnamed_1 = baz.m[0]; - int _e16 = idx; - metal::float2 unnamed_2 = baz.m[_e16]; + int _e15 = idx; + metal::float2 unnamed_2 = baz.m[_e15]; float unnamed_3 = baz.m[0].y; - int _e28 = idx; - float unnamed_4 = baz.m[0][_e28]; - int _e32 = idx; - float unnamed_5 = baz.m[_e32].y; - int _e38 = idx; - int _e40 = idx; - float unnamed_6 = baz.m[_e38][_e40]; + int _e29 = idx; + float unnamed_4 = baz.m[0][_e29]; + int _e34 = idx; + float unnamed_5 = baz.m[_e34].y; + int _e41 = idx; + int _e43 = idx; + float unnamed_6 = baz.m[_e41][_e43]; t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; - int _e52 = idx; - idx = _e52 + 1; + int _e55 = idx; + idx = _e55 + 1; t.m = metal::float3x2(metal::float2(6.0), metal::float2(5.0), metal::float2(4.0)); t.m[0] = metal::float2(9.0); - int _e69 = idx; - t.m[_e69] = metal::float2(90.0); + int _e72 = idx; + t.m[_e72] = metal::float2(90.0); t.m[0].y = 10.0; - int _e82 = idx; - t.m[0][_e82] = 20.0; - int _e86 = idx; - t.m[_e86].y = 30.0; - int _e92 = idx; - int _e94 = idx; - t.m[_e92][_e94] = 40.0; + int _e85 = idx; + t.m[0][_e85] = 20.0; + int _e89 = idx; + t.m[_e89].y = 30.0; + int _e95 = idx; + int _e97 = idx; + t.m[_e95][_e97] = 40.0; return; } void test_matrix_within_array_within_struct_accesses( constant MatCx2InArray& nested_mat_cx2_ ) { - int idx_1 = 1; + int idx_1 = {}; MatCx2InArray t_1 = {}; - int _e7 = idx_1; - idx_1 = _e7 - 1; - type_13 unnamed_7 = nested_mat_cx2_.am; + idx_1 = 1; + int _e2 = idx_1; + idx_1 = _e2 - 1; + type_14 unnamed_7 = nested_mat_cx2_.am; metal::float4x2 unnamed_8 = nested_mat_cx2_.am.inner[0]; metal::float2 unnamed_9 = nested_mat_cx2_.am.inner[0][0]; - int _e25 = idx_1; - metal::float2 unnamed_10 = nested_mat_cx2_.am.inner[0][_e25]; + int _e24 = idx_1; + metal::float2 unnamed_10 = nested_mat_cx2_.am.inner[0][_e24]; float unnamed_11 = nested_mat_cx2_.am.inner[0][0].y; - int _e41 = idx_1; - float unnamed_12 = nested_mat_cx2_.am.inner[0][0][_e41]; - int _e47 = idx_1; - float unnamed_13 = nested_mat_cx2_.am.inner[0][_e47].y; - int _e55 = idx_1; - int _e57 = idx_1; - float unnamed_14 = nested_mat_cx2_.am.inner[0][_e55][_e57]; - t_1 = MatCx2InArray {const_type_13_}; - int _e63 = idx_1; - idx_1 = _e63 + 1; - for(int _i=0; _i<2; ++_i) t_1.am.inner[_i] = const_type_13_.inner[_i]; + int _e42 = idx_1; + float unnamed_12 = nested_mat_cx2_.am.inner[0][0][_e42]; + int _e49 = idx_1; + float unnamed_13 = nested_mat_cx2_.am.inner[0][_e49].y; + int _e58 = idx_1; + int _e60 = idx_1; + float unnamed_14 = nested_mat_cx2_.am.inner[0][_e58][_e60]; + t_1 = MatCx2InArray {const_type_14_}; + int _e66 = idx_1; + idx_1 = _e66 + 1; + for(int _i=0; _i<2; ++_i) t_1.am.inner[_i] = const_type_14_.inner[_i]; t_1.am.inner[0] = metal::float4x2(metal::float2(8.0), metal::float2(7.0), metal::float2(6.0), metal::float2(5.0)); t_1.am.inner[0][0] = metal::float2(9.0); - int _e90 = idx_1; - t_1.am.inner[0][_e90] = metal::float2(90.0); + int _e93 = idx_1; + t_1.am.inner[0][_e93] = metal::float2(90.0); t_1.am.inner[0][0].y = 10.0; - int _e107 = idx_1; - t_1.am.inner[0][0][_e107] = 20.0; - int _e113 = idx_1; - t_1.am.inner[0][_e113].y = 30.0; - int _e121 = idx_1; - int _e123 = idx_1; - t_1.am.inner[0][_e121][_e123] = 40.0; + int _e110 = idx_1; + t_1.am.inner[0][0][_e110] = 20.0; + int _e116 = idx_1; + t_1.am.inner[0][_e116].y = 30.0; + int _e124 = idx_1; + int _e126 = idx_1; + t_1.am.inner[0][_e124][_e126] = 40.0; return; } float read_from_private( thread float& foo_1 ) { - float _e6 = foo_1; - return _e6; + float _e1 = foo_1; + return _e1; } float test_arr_as_arg( @@ -168,8 +170,9 @@ vertex foo_vertOutput foo_vert( , constant MatCx2InArray& nested_mat_cx2_ [[buffer(3)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - float foo = 0.0; - type_21 c = {}; + float foo = {}; + type_21 c2_ = {}; + foo = 0.0; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); @@ -178,12 +181,12 @@ vertex foo_vertOutput foo_vert( type_8 arr = bar.arr; float b = bar._matrix[3].x; int a_1 = bar.data[(1 + (_buffer_sizes.size1 - 120 - 8) / 8) - 2u].value; - metal::int2 c_1 = qux; - float _e32 = read_from_private(foo); - for(int _i=0; _i<5; ++_i) c.inner[_i] = type_21 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; - c.inner[vi + 1u] = 42; - int value = c.inner[vi]; - float _e46 = test_arr_as_arg(const_type_18_); + metal::int2 c = qux; + float _e34 = read_from_private(foo); + for(int _i=0; _i<5; ++_i) c2_.inner[_i] = type_21 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; + c2_.inner[vi + 1u] = 42; + int value = c2_.inner[vi]; + float _e48 = test_arr_as_arg(const_type_18_); return foo_vertOutput { metal::float4(_matrix * static_cast(metal::int4(value)), 2.0) }; } @@ -211,22 +214,22 @@ kernel void atomics( ) { int tmp = {}; int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); - int _e10 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e10; - int _e13 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e13; - int _e16 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e16; + int _e7 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e7; + int _e11 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e11; + int _e15 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e15; int _e19 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e19; - int _e22 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e22; - int _e25 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e25; - int _e28 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e28; - int _e31 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + int _e23 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e23; + int _e27 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e27; + int _e31 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); tmp = _e31; + int _e35 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); + tmp = _e35; metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed); return; } diff --git a/tests/out/msl/binding-arrays.msl b/tests/out/msl/binding-arrays.msl index ba3c3c8b0..d54fc9982 100644 --- a/tests/out/msl/binding-arrays.msl +++ b/tests/out/msl/binding-arrays.msl @@ -36,137 +36,139 @@ fragment main_Output main_( , constant UniformIndex& uni [[user(fake0)]] ) { const FragmentIn fragment_in = { varyings.index }; - int i1_ = 0; + int i1_ = {}; metal::int2 i2_ = {}; - float v1_ = 0.0; + float v1_ = {}; metal::float4 v4_ = {}; uint uniform_index = uni.index; uint non_uniform_index = fragment_in.index; + i1_ = 0; i2_ = metal::int2(0); + v1_ = 0.0; v4_ = metal::float4(0.0); metal::float2 uv = metal::float2(0.0); metal::int2 pix = metal::int2(0); - metal::int2 _e27 = i2_; - i2_ = _e27 + metal::int2(texture_array_unbounded[0].get_width(), texture_array_unbounded[0].get_height()); - metal::int2 _e32 = i2_; - i2_ = _e32 + metal::int2(texture_array_unbounded[uniform_index].get_width(), texture_array_unbounded[uniform_index].get_height()); - metal::int2 _e36 = i2_; - i2_ = _e36 + metal::int2(texture_array_unbounded[non_uniform_index].get_width(), texture_array_unbounded[non_uniform_index].get_height()); - metal::float4 _e40 = v4_; - metal::float4 _e45 = texture_array_bounded[0].gather(samp[0], uv); - v4_ = _e40 + _e45; - metal::float4 _e47 = v4_; - metal::float4 _e50 = texture_array_bounded[uniform_index].gather(samp[uniform_index], uv); - v4_ = _e47 + _e50; - metal::float4 _e52 = v4_; + metal::int2 _e23 = i2_; + i2_ = _e23 + metal::int2(texture_array_unbounded[0].get_width(), texture_array_unbounded[0].get_height()); + metal::int2 _e28 = i2_; + i2_ = _e28 + metal::int2(texture_array_unbounded[uniform_index].get_width(), texture_array_unbounded[uniform_index].get_height()); + metal::int2 _e33 = i2_; + i2_ = _e33 + metal::int2(texture_array_unbounded[non_uniform_index].get_width(), texture_array_unbounded[non_uniform_index].get_height()); + metal::float4 _e41 = texture_array_bounded[0].gather(samp[0], uv); + metal::float4 _e42 = v4_; + v4_ = _e42 + _e41; + metal::float4 _e48 = texture_array_bounded[uniform_index].gather(samp[uniform_index], uv); + metal::float4 _e49 = v4_; + v4_ = _e49 + _e48; metal::float4 _e55 = texture_array_bounded[non_uniform_index].gather(samp[non_uniform_index], uv); - v4_ = _e52 + _e55; - metal::float4 _e57 = v4_; - metal::float4 _e63 = texture_array_depth[0].gather_compare(samp_comp[0], uv, 0.0); - v4_ = _e57 + _e63; - metal::float4 _e65 = v4_; - metal::float4 _e69 = texture_array_depth[uniform_index].gather_compare(samp_comp[uniform_index], uv, 0.0); - v4_ = _e65 + _e69; - metal::float4 _e71 = v4_; - metal::float4 _e75 = texture_array_depth[non_uniform_index].gather_compare(samp_comp[non_uniform_index], uv, 0.0); - v4_ = _e71 + _e75; - metal::float4 _e77 = v4_; - metal::float4 _e81 = (uint(0) < texture_array_unbounded[0].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[0].get_width(0), texture_array_unbounded[0].get_height(0))) ? texture_array_unbounded[0].read(metal::uint2(pix), 0): DefaultConstructible()); - v4_ = _e77 + _e81; - metal::float4 _e83 = v4_; - metal::float4 _e86 = (uint(0) < texture_array_unbounded[uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[uniform_index].get_width(0), texture_array_unbounded[uniform_index].get_height(0))) ? texture_array_unbounded[uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); - v4_ = _e83 + _e86; - metal::float4 _e88 = v4_; - metal::float4 _e91 = (uint(0) < texture_array_unbounded[non_uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[non_uniform_index].get_width(0), texture_array_unbounded[non_uniform_index].get_height(0))) ? texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); - v4_ = _e88 + _e91; - int _e93 = i1_; - i1_ = _e93 + int(texture_array_2darray[0].get_array_size()); - int _e98 = i1_; - i1_ = _e98 + int(texture_array_2darray[uniform_index].get_array_size()); - int _e102 = i1_; - i1_ = _e102 + int(texture_array_2darray[non_uniform_index].get_array_size()); - int _e106 = i1_; - i1_ = _e106 + int(texture_array_bounded[0].get_num_mip_levels()); - int _e111 = i1_; - i1_ = _e111 + int(texture_array_bounded[uniform_index].get_num_mip_levels()); - int _e115 = i1_; - i1_ = _e115 + int(texture_array_bounded[non_uniform_index].get_num_mip_levels()); - int _e119 = i1_; - i1_ = _e119 + int(texture_array_multisampled[0].get_num_samples()); - int _e124 = i1_; - i1_ = _e124 + int(texture_array_multisampled[uniform_index].get_num_samples()); + metal::float4 _e56 = v4_; + v4_ = _e56 + _e55; + metal::float4 _e65 = texture_array_depth[0].gather_compare(samp_comp[0], uv, 0.0); + metal::float4 _e66 = v4_; + v4_ = _e66 + _e65; + metal::float4 _e73 = texture_array_depth[uniform_index].gather_compare(samp_comp[uniform_index], uv, 0.0); + metal::float4 _e74 = v4_; + v4_ = _e74 + _e73; + metal::float4 _e81 = texture_array_depth[non_uniform_index].gather_compare(samp_comp[non_uniform_index], uv, 0.0); + metal::float4 _e82 = v4_; + v4_ = _e82 + _e81; + metal::float4 _e88 = (uint(0) < texture_array_unbounded[0].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[0].get_width(0), texture_array_unbounded[0].get_height(0))) ? texture_array_unbounded[0].read(metal::uint2(pix), 0): DefaultConstructible()); + metal::float4 _e89 = v4_; + v4_ = _e89 + _e88; + metal::float4 _e94 = (uint(0) < texture_array_unbounded[uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[uniform_index].get_width(0), texture_array_unbounded[uniform_index].get_height(0))) ? texture_array_unbounded[uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); + metal::float4 _e95 = v4_; + v4_ = _e95 + _e94; + metal::float4 _e100 = (uint(0) < texture_array_unbounded[non_uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[non_uniform_index].get_width(0), texture_array_unbounded[non_uniform_index].get_height(0))) ? texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); + metal::float4 _e101 = v4_; + v4_ = _e101 + _e100; + int _e107 = i1_; + i1_ = _e107 + int(texture_array_2darray[0].get_array_size()); + int _e112 = i1_; + i1_ = _e112 + int(texture_array_2darray[uniform_index].get_array_size()); + int _e117 = i1_; + i1_ = _e117 + int(texture_array_2darray[non_uniform_index].get_array_size()); + int _e123 = i1_; + i1_ = _e123 + int(texture_array_bounded[0].get_num_mip_levels()); int _e128 = i1_; - i1_ = _e128 + int(texture_array_multisampled[non_uniform_index].get_num_samples()); - metal::float4 _e132 = v4_; - metal::float4 _e137 = texture_array_bounded[0].sample(samp[0], uv); - v4_ = _e132 + _e137; - metal::float4 _e139 = v4_; - metal::float4 _e142 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv); - v4_ = _e139 + _e142; - metal::float4 _e144 = v4_; - metal::float4 _e147 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv); - v4_ = _e144 + _e147; - metal::float4 _e149 = v4_; - metal::float4 _e155 = texture_array_bounded[0].sample(samp[0], uv, metal::bias(0.0)); - v4_ = _e149 + _e155; - metal::float4 _e157 = v4_; - metal::float4 _e161 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::bias(0.0)); - v4_ = _e157 + _e161; - metal::float4 _e163 = v4_; - metal::float4 _e167 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::bias(0.0)); - v4_ = _e163 + _e167; - float _e169 = v1_; - float _e175 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); - v1_ = _e169 + _e175; - float _e177 = v1_; - float _e181 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); - v1_ = _e177 + _e181; - float _e183 = v1_; - float _e187 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); - v1_ = _e183 + _e187; - float _e189 = v1_; - float _e195 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); - v1_ = _e189 + _e195; - float _e197 = v1_; - float _e201 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); - v1_ = _e197 + _e201; - float _e203 = v1_; - float _e207 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); - v1_ = _e203 + _e207; - metal::float4 _e209 = v4_; - metal::float4 _e214 = texture_array_bounded[0].sample(samp[0], uv, metal::gradient2d(uv, uv)); - v4_ = _e209 + _e214; - metal::float4 _e216 = v4_; - metal::float4 _e219 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::gradient2d(uv, uv)); - v4_ = _e216 + _e219; - metal::float4 _e221 = v4_; - metal::float4 _e224 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::gradient2d(uv, uv)); - v4_ = _e221 + _e224; - metal::float4 _e226 = v4_; - metal::float4 _e232 = texture_array_bounded[0].sample(samp[0], uv, metal::level(0.0)); - v4_ = _e226 + _e232; - metal::float4 _e234 = v4_; - metal::float4 _e238 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::level(0.0)); - v4_ = _e234 + _e238; - metal::float4 _e240 = v4_; - metal::float4 _e244 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::level(0.0)); - v4_ = _e240 + _e244; - metal::float4 _e248 = v4_; + i1_ = _e128 + int(texture_array_bounded[uniform_index].get_num_mip_levels()); + int _e133 = i1_; + i1_ = _e133 + int(texture_array_bounded[non_uniform_index].get_num_mip_levels()); + int _e139 = i1_; + i1_ = _e139 + int(texture_array_multisampled[0].get_num_samples()); + int _e144 = i1_; + i1_ = _e144 + int(texture_array_multisampled[uniform_index].get_num_samples()); + int _e149 = i1_; + i1_ = _e149 + int(texture_array_multisampled[non_uniform_index].get_num_samples()); + metal::float4 _e157 = texture_array_bounded[0].sample(samp[0], uv); + metal::float4 _e158 = v4_; + v4_ = _e158 + _e157; + metal::float4 _e164 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv); + metal::float4 _e165 = v4_; + v4_ = _e165 + _e164; + metal::float4 _e171 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv); + metal::float4 _e172 = v4_; + v4_ = _e172 + _e171; + metal::float4 _e181 = texture_array_bounded[0].sample(samp[0], uv, metal::bias(0.0)); + metal::float4 _e182 = v4_; + v4_ = _e182 + _e181; + metal::float4 _e189 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::bias(0.0)); + metal::float4 _e190 = v4_; + v4_ = _e190 + _e189; + metal::float4 _e197 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::bias(0.0)); + metal::float4 _e198 = v4_; + v4_ = _e198 + _e197; + float _e207 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); + float _e208 = v1_; + v1_ = _e208 + _e207; + float _e215 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); + float _e216 = v1_; + v1_ = _e216 + _e215; + float _e223 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); + float _e224 = v1_; + v1_ = _e224 + _e223; + float _e233 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); + float _e234 = v1_; + v1_ = _e234 + _e233; + float _e241 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); + float _e242 = v1_; + v1_ = _e242 + _e241; + float _e249 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); + float _e250 = v1_; + v1_ = _e250 + _e249; + metal::float4 _e258 = texture_array_bounded[0].sample(samp[0], uv, metal::gradient2d(uv, uv)); + metal::float4 _e259 = v4_; + v4_ = _e259 + _e258; + metal::float4 _e265 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::gradient2d(uv, uv)); + metal::float4 _e266 = v4_; + v4_ = _e266 + _e265; + metal::float4 _e272 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::gradient2d(uv, uv)); + metal::float4 _e273 = v4_; + v4_ = _e273 + _e272; + metal::float4 _e282 = texture_array_bounded[0].sample(samp[0], uv, metal::level(0.0)); + metal::float4 _e283 = v4_; + v4_ = _e283 + _e282; + metal::float4 _e290 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::level(0.0)); + metal::float4 _e291 = v4_; + v4_ = _e291 + _e290; + metal::float4 _e298 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::level(0.0)); + metal::float4 _e299 = v4_; + v4_ = _e299 + _e298; + metal::float4 _e304 = v4_; if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[0].get_width(), texture_array_storage[0].get_height()))) { - texture_array_storage[0].write(_e248, metal::uint2(pix)); + texture_array_storage[0].write(_e304, metal::uint2(pix)); } - metal::float4 _e250 = v4_; + metal::float4 _e307 = v4_; if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[uniform_index].get_width(), texture_array_storage[uniform_index].get_height()))) { - texture_array_storage[uniform_index].write(_e250, metal::uint2(pix)); + texture_array_storage[uniform_index].write(_e307, metal::uint2(pix)); } - metal::float4 _e252 = v4_; + metal::float4 _e310 = v4_; if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[non_uniform_index].get_width(), texture_array_storage[non_uniform_index].get_height()))) { - texture_array_storage[non_uniform_index].write(_e252, metal::uint2(pix)); + texture_array_storage[non_uniform_index].write(_e310, metal::uint2(pix)); } - metal::int2 _e253 = i2_; - int _e254 = i1_; - metal::float2 v2_ = static_cast(_e253 + metal::int2(_e254)); - metal::float4 _e258 = v4_; - float _e265 = v1_; - return main_Output { (_e258 + metal::float4(v2_.x, v2_.y, v2_.x, v2_.y)) + metal::float4(_e265) }; + metal::int2 _e311 = i2_; + int _e312 = i1_; + metal::float2 v2_ = static_cast(_e311 + metal::int2(_e312)); + metal::float4 _e316 = v4_; + float _e323 = v1_; + return main_Output { (_e316 + metal::float4(v2_.x, v2_.y, v2_.x, v2_.y)) + metal::float4(_e323) }; } diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index 9c9eedaeb..2a95996c7 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -7,19 +7,21 @@ using metal::uint; kernel void main_( ) { - int i = 0; + int i = {}; metal::int2 i2_ = {}; metal::int3 i3_ = {}; metal::int4 i4_ = {}; - uint u = 0u; + uint u = {}; metal::uint2 u2_ = {}; metal::uint3 u3_ = {}; metal::uint4 u4_ = {}; metal::float2 f2_ = {}; metal::float4 f4_ = {}; + i = 0; i2_ = metal::int2(0); i3_ = metal::int3(0); i4_ = metal::int4(0); + u = 0u; u2_ = metal::uint2(0u); u3_ = metal::uint3(0u); u4_ = metal::uint4(0u); diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index fd46d1f21..2b832c0f2 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -42,120 +42,123 @@ kernel void main_( metal::float2 cMass = {}; metal::float2 cVel = {}; metal::float2 colVel = {}; - int cMassCount = 0; - int cVelCount = 0; + int cMassCount = {}; + int cVelCount = {}; metal::float2 pos = {}; metal::float2 vel = {}; - uint i = 0u; + uint i = {}; uint index = global_invocation_id.x; if (index >= NUM_PARTICLES) { return; } - metal::float2 _e10 = particlesSrc.particles[index].pos; - vPos = _e10; - metal::float2 _e15 = particlesSrc.particles[index].vel; - vVel = _e15; + metal::float2 _e8 = particlesSrc.particles[index].pos; + vPos = _e8; + metal::float2 _e14 = particlesSrc.particles[index].vel; + vVel = _e14; cMass = metal::float2(0.0, 0.0); cVel = metal::float2(0.0, 0.0); colVel = metal::float2(0.0, 0.0); + cMassCount = 0; + cVelCount = 0; + i = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _e86 = i; - i = _e86 + 1u; + uint _e91 = i; + i = _e91 + 1u; } loop_init = false; - uint _e37 = i; - if (_e37 >= NUM_PARTICLES) { + uint _e36 = i; + if (_e36 >= NUM_PARTICLES) { break; } uint _e39 = i; if (_e39 == index) { continue; } - uint _e42 = i; - metal::float2 _e45 = particlesSrc.particles[_e42].pos; - pos = _e45; - uint _e47 = i; - metal::float2 _e50 = particlesSrc.particles[_e47].vel; - vel = _e50; - metal::float2 _e51 = pos; - metal::float2 _e52 = vPos; - float _e55 = params.rule1Distance; - if (metal::distance(_e51, _e52) < _e55) { - metal::float2 _e57 = cMass; - metal::float2 _e58 = pos; - cMass = _e57 + _e58; - int _e60 = cMassCount; - cMassCount = _e60 + 1; + uint _e43 = i; + metal::float2 _e46 = particlesSrc.particles[_e43].pos; + pos = _e46; + uint _e49 = i; + metal::float2 _e52 = particlesSrc.particles[_e49].vel; + vel = _e52; + metal::float2 _e53 = pos; + metal::float2 _e54 = vPos; + float _e58 = params.rule1Distance; + if (metal::distance(_e53, _e54) < _e58) { + metal::float2 _e60 = cMass; + metal::float2 _e61 = pos; + cMass = _e60 + _e61; + int _e63 = cMassCount; + cMassCount = _e63 + 1; } - metal::float2 _e63 = pos; - metal::float2 _e64 = vPos; - float _e67 = params.rule2Distance; - if (metal::distance(_e63, _e64) < _e67) { - metal::float2 _e69 = colVel; - metal::float2 _e70 = pos; - metal::float2 _e71 = vPos; - colVel = _e69 - (_e70 - _e71); + metal::float2 _e66 = pos; + metal::float2 _e67 = vPos; + float _e71 = params.rule2Distance; + if (metal::distance(_e66, _e67) < _e71) { + metal::float2 _e73 = colVel; + metal::float2 _e74 = pos; + metal::float2 _e75 = vPos; + colVel = _e73 - (_e74 - _e75); } - metal::float2 _e74 = pos; - metal::float2 _e75 = vPos; - float _e78 = params.rule3Distance; - if (metal::distance(_e74, _e75) < _e78) { - metal::float2 _e80 = cVel; - metal::float2 _e81 = vel; - cVel = _e80 + _e81; - int _e83 = cVelCount; - cVelCount = _e83 + 1; + metal::float2 _e78 = pos; + metal::float2 _e79 = vPos; + float _e83 = params.rule3Distance; + if (metal::distance(_e78, _e79) < _e83) { + metal::float2 _e85 = cVel; + metal::float2 _e86 = vel; + cVel = _e85 + _e86; + int _e88 = cVelCount; + cVelCount = _e88 + 1; } } - int _e89 = cMassCount; - if (_e89 > 0) { - metal::float2 _e92 = cMass; - int _e93 = cMassCount; - metal::float2 _e97 = vPos; - cMass = (_e92 / metal::float2(static_cast(_e93))) - _e97; + int _e94 = cMassCount; + if (_e94 > 0) { + metal::float2 _e97 = cMass; + int _e98 = cMassCount; + metal::float2 _e102 = vPos; + cMass = (_e97 / metal::float2(static_cast(_e98))) - _e102; } - int _e99 = cVelCount; - if (_e99 > 0) { - metal::float2 _e102 = cVel; - int _e103 = cVelCount; - cVel = _e102 / metal::float2(static_cast(_e103)); + int _e104 = cVelCount; + if (_e104 > 0) { + metal::float2 _e107 = cVel; + int _e108 = cVelCount; + cVel = _e107 / metal::float2(static_cast(_e108)); } - metal::float2 _e107 = vVel; - metal::float2 _e108 = cMass; - float _e110 = params.rule1Scale; - metal::float2 _e113 = colVel; - float _e115 = params.rule2Scale; - metal::float2 _e118 = cVel; - float _e120 = params.rule3Scale; - vVel = ((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120); - metal::float2 _e123 = vVel; - metal::float2 _e125 = vVel; - vVel = metal::normalize(_e123) * metal::clamp(metal::length(_e125), 0.0, 0.10000000149011612); - metal::float2 _e131 = vPos; - metal::float2 _e132 = vVel; - float _e134 = params.deltaT; - vPos = _e131 + (_e132 * _e134); - float _e138 = vPos.x; - if (_e138 < -1.0) { + metal::float2 _e112 = vVel; + metal::float2 _e113 = cMass; + float _e116 = params.rule1Scale; + metal::float2 _e119 = colVel; + float _e122 = params.rule2Scale; + metal::float2 _e125 = cVel; + float _e128 = params.rule3Scale; + vVel = ((_e112 + (_e113 * _e116)) + (_e119 * _e122)) + (_e125 * _e128); + metal::float2 _e131 = vVel; + metal::float2 _e133 = vVel; + vVel = metal::normalize(_e131) * metal::clamp(metal::length(_e133), 0.0, 0.10000000149011612); + metal::float2 _e139 = vPos; + metal::float2 _e140 = vVel; + float _e143 = params.deltaT; + vPos = _e139 + (_e140 * _e143); + float _e147 = vPos.x; + if (_e147 < -1.0) { vPos.x = 1.0; } - float _e144 = vPos.x; - if (_e144 > 1.0) { + float _e153 = vPos.x; + if (_e153 > 1.0) { vPos.x = -1.0; } - float _e150 = vPos.y; - if (_e150 < -1.0) { + float _e159 = vPos.y; + if (_e159 < -1.0) { vPos.y = 1.0; } - float _e156 = vPos.y; - if (_e156 > 1.0) { + float _e165 = vPos.y; + if (_e165 > 1.0) { vPos.y = -1.0; } - metal::float2 _e164 = vPos; - particlesDst.particles[index].pos = _e164; - metal::float2 _e168 = vVel; - particlesDst.particles[index].vel = _e168; + metal::float2 _e174 = vPos; + particlesDst.particles[index].pos = _e174; + metal::float2 _e179 = vVel; + particlesDst.particles[index].vel = _e179; return; } diff --git a/tests/out/msl/bounds-check-image-restrict.msl b/tests/out/msl/bounds-check-image-restrict.msl index b2f6eca4d..c1e5b99df 100644 --- a/tests/out/msl/bounds-check-image-restrict.msl +++ b/tests/out/msl/bounds-check-image-restrict.msl @@ -22,9 +22,9 @@ metal::float4 test_textureLoad_2d( int level_1, metal::texture2d image_2d ) { - uint clamped_lod_e4 = metal::min(uint(level_1), image_2d.get_num_mip_levels() - 1); - metal::float4 _e4 = image_2d.read(metal::min(metal::uint2(coords_1), metal::uint2(image_2d.get_width(clamped_lod_e4), image_2d.get_height(clamped_lod_e4)) - 1), clamped_lod_e4); - return _e4; + uint clamped_lod_e3 = metal::min(uint(level_1), image_2d.get_num_mip_levels() - 1); + metal::float4 _e3 = image_2d.read(metal::min(metal::uint2(coords_1), metal::uint2(image_2d.get_width(clamped_lod_e3), image_2d.get_height(clamped_lod_e3)) - 1), clamped_lod_e3); + return _e3; } metal::float4 test_textureLoad_2d_array( @@ -33,9 +33,9 @@ metal::float4 test_textureLoad_2d_array( int level_2, metal::texture2d_array image_2d_array ) { - uint clamped_lod_e6 = metal::min(uint(level_2), image_2d_array.get_num_mip_levels() - 1); - metal::float4 _e6 = image_2d_array.read(metal::min(metal::uint2(coords_2), metal::uint2(image_2d_array.get_width(clamped_lod_e6), image_2d_array.get_height(clamped_lod_e6)) - 1), metal::min(uint(index), image_2d_array.get_array_size() - 1), clamped_lod_e6); - return _e6; + uint clamped_lod_e4 = metal::min(uint(level_2), image_2d_array.get_num_mip_levels() - 1); + metal::float4 _e4 = image_2d_array.read(metal::min(metal::uint2(coords_2), metal::uint2(image_2d_array.get_width(clamped_lod_e4), image_2d_array.get_height(clamped_lod_e4)) - 1), metal::min(uint(index), image_2d_array.get_array_size() - 1), clamped_lod_e4); + return _e4; } metal::float4 test_textureLoad_3d( @@ -43,9 +43,9 @@ metal::float4 test_textureLoad_3d( int level_3, metal::texture3d image_3d ) { - uint clamped_lod_e6 = metal::min(uint(level_3), image_3d.get_num_mip_levels() - 1); - metal::float4 _e6 = image_3d.read(metal::min(metal::uint3(coords_3), metal::uint3(image_3d.get_width(clamped_lod_e6), image_3d.get_height(clamped_lod_e6), image_3d.get_depth(clamped_lod_e6)) - 1), clamped_lod_e6); - return _e6; + uint clamped_lod_e3 = metal::min(uint(level_3), image_3d.get_num_mip_levels() - 1); + metal::float4 _e3 = image_3d.read(metal::min(metal::uint3(coords_3), metal::uint3(image_3d.get_width(clamped_lod_e3), image_3d.get_height(clamped_lod_e3), image_3d.get_depth(clamped_lod_e3)) - 1), clamped_lod_e3); + return _e3; } metal::float4 test_textureLoad_multisampled_2d( @@ -53,8 +53,8 @@ metal::float4 test_textureLoad_multisampled_2d( int _sample, metal::texture2d_ms image_multisampled_2d ) { - metal::float4 _e7 = image_multisampled_2d.read(metal::min(metal::uint2(coords_4), metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height()) - 1), metal::min(uint(_sample), image_multisampled_2d.get_num_samples() - 1)); - return _e7; + metal::float4 _e3 = image_multisampled_2d.read(metal::min(metal::uint2(coords_4), metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height()) - 1), metal::min(uint(_sample), image_multisampled_2d.get_num_samples() - 1)); + return _e3; } float test_textureLoad_depth_2d( @@ -62,9 +62,9 @@ float test_textureLoad_depth_2d( int level_4, metal::depth2d image_depth_2d ) { - uint clamped_lod_e8 = metal::min(uint(level_4), image_depth_2d.get_num_mip_levels() - 1); - float _e8 = image_depth_2d.read(metal::min(metal::uint2(coords_5), metal::uint2(image_depth_2d.get_width(clamped_lod_e8), image_depth_2d.get_height(clamped_lod_e8)) - 1), clamped_lod_e8); - return _e8; + uint clamped_lod_e3 = metal::min(uint(level_4), image_depth_2d.get_num_mip_levels() - 1); + float _e3 = image_depth_2d.read(metal::min(metal::uint2(coords_5), metal::uint2(image_depth_2d.get_width(clamped_lod_e3), image_depth_2d.get_height(clamped_lod_e3)) - 1), clamped_lod_e3); + return _e3; } float test_textureLoad_depth_2d_array( @@ -73,9 +73,9 @@ float test_textureLoad_depth_2d_array( int level_5, metal::depth2d_array image_depth_2d_array ) { - uint clamped_lod_e10 = metal::min(uint(level_5), image_depth_2d_array.get_num_mip_levels() - 1); - float _e10 = image_depth_2d_array.read(metal::min(metal::uint2(coords_6), metal::uint2(image_depth_2d_array.get_width(clamped_lod_e10), image_depth_2d_array.get_height(clamped_lod_e10)) - 1), metal::min(uint(index_1), image_depth_2d_array.get_array_size() - 1), clamped_lod_e10); - return _e10; + uint clamped_lod_e4 = metal::min(uint(level_5), image_depth_2d_array.get_num_mip_levels() - 1); + float _e4 = image_depth_2d_array.read(metal::min(metal::uint2(coords_6), metal::uint2(image_depth_2d_array.get_width(clamped_lod_e4), image_depth_2d_array.get_height(clamped_lod_e4)) - 1), metal::min(uint(index_1), image_depth_2d_array.get_array_size() - 1), clamped_lod_e4); + return _e4; } float test_textureLoad_depth_multisampled_2d( @@ -83,8 +83,8 @@ float test_textureLoad_depth_multisampled_2d( int _sample_1, metal::depth2d_ms image_depth_multisampled_2d ) { - float _e10 = image_depth_multisampled_2d.read(metal::min(metal::uint2(coords_7), metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height()) - 1), metal::min(uint(_sample_1), image_depth_multisampled_2d.get_num_samples() - 1)); - return _e10; + float _e3 = image_depth_multisampled_2d.read(metal::min(metal::uint2(coords_7), metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height()) - 1), metal::min(uint(_sample_1), image_depth_multisampled_2d.get_num_samples() - 1)); + return _e3; } void test_textureStore_1d( @@ -138,11 +138,11 @@ fragment fragment_shaderOutput fragment_shader( , metal::texture2d_array image_storage_2d_array [[user(fake0)]] , metal::texture3d image_storage_3d [[user(fake0)]] ) { - metal::float4 _e14 = test_textureLoad_1d(0, 0, image_1d); - metal::float4 _e17 = test_textureLoad_2d(const_type_4_, 0, image_2d); - metal::float4 _e21 = test_textureLoad_2d_array(const_type_4_, 0, 0, image_2d_array); - metal::float4 _e24 = test_textureLoad_3d(const_type_7_, 0, image_3d); - metal::float4 _e27 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); + metal::float4 _e2 = test_textureLoad_1d(0, 0, image_1d); + metal::float4 _e5 = test_textureLoad_2d(const_type_4_, 0, image_2d); + metal::float4 _e9 = test_textureLoad_2d_array(const_type_4_, 0, 0, image_2d_array); + metal::float4 _e12 = test_textureLoad_3d(const_type_7_, 0, image_3d); + metal::float4 _e15 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); test_textureStore_1d(0, const_type_2_, image_storage_1d); test_textureStore_2d(const_type_4_, const_type_2_, image_storage_2d); test_textureStore_2d_array(const_type_4_, 0, const_type_2_, image_storage_2d_array); diff --git a/tests/out/msl/bounds-check-image-rzsw.msl b/tests/out/msl/bounds-check-image-rzsw.msl index 16cbf5c0a..9032af14c 100644 --- a/tests/out/msl/bounds-check-image-rzsw.msl +++ b/tests/out/msl/bounds-check-image-rzsw.msl @@ -28,8 +28,8 @@ metal::float4 test_textureLoad_2d( int level_1, metal::texture2d image_2d ) { - metal::float4 _e4 = (uint(level_1) < image_2d.get_num_mip_levels() && metal::all(metal::uint2(coords_1) < metal::uint2(image_2d.get_width(level_1), image_2d.get_height(level_1))) ? image_2d.read(metal::uint2(coords_1), level_1): DefaultConstructible()); - return _e4; + metal::float4 _e3 = (uint(level_1) < image_2d.get_num_mip_levels() && metal::all(metal::uint2(coords_1) < metal::uint2(image_2d.get_width(level_1), image_2d.get_height(level_1))) ? image_2d.read(metal::uint2(coords_1), level_1): DefaultConstructible()); + return _e3; } metal::float4 test_textureLoad_2d_array( @@ -38,8 +38,8 @@ metal::float4 test_textureLoad_2d_array( int level_2, metal::texture2d_array image_2d_array ) { - metal::float4 _e6 = (uint(level_2) < image_2d_array.get_num_mip_levels() && uint(index) < image_2d_array.get_array_size() && metal::all(metal::uint2(coords_2) < metal::uint2(image_2d_array.get_width(level_2), image_2d_array.get_height(level_2))) ? image_2d_array.read(metal::uint2(coords_2), index, level_2): DefaultConstructible()); - return _e6; + metal::float4 _e4 = (uint(level_2) < image_2d_array.get_num_mip_levels() && uint(index) < image_2d_array.get_array_size() && metal::all(metal::uint2(coords_2) < metal::uint2(image_2d_array.get_width(level_2), image_2d_array.get_height(level_2))) ? image_2d_array.read(metal::uint2(coords_2), index, level_2): DefaultConstructible()); + return _e4; } metal::float4 test_textureLoad_3d( @@ -47,8 +47,8 @@ metal::float4 test_textureLoad_3d( int level_3, metal::texture3d image_3d ) { - metal::float4 _e6 = (uint(level_3) < image_3d.get_num_mip_levels() && metal::all(metal::uint3(coords_3) < metal::uint3(image_3d.get_width(level_3), image_3d.get_height(level_3), image_3d.get_depth(level_3))) ? image_3d.read(metal::uint3(coords_3), level_3): DefaultConstructible()); - return _e6; + metal::float4 _e3 = (uint(level_3) < image_3d.get_num_mip_levels() && metal::all(metal::uint3(coords_3) < metal::uint3(image_3d.get_width(level_3), image_3d.get_height(level_3), image_3d.get_depth(level_3))) ? image_3d.read(metal::uint3(coords_3), level_3): DefaultConstructible()); + return _e3; } metal::float4 test_textureLoad_multisampled_2d( @@ -56,8 +56,8 @@ metal::float4 test_textureLoad_multisampled_2d( int _sample, metal::texture2d_ms image_multisampled_2d ) { - metal::float4 _e7 = (uint(_sample) < image_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_4) < metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height())) ? image_multisampled_2d.read(metal::uint2(coords_4), _sample): DefaultConstructible()); - return _e7; + metal::float4 _e3 = (uint(_sample) < image_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_4) < metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height())) ? image_multisampled_2d.read(metal::uint2(coords_4), _sample): DefaultConstructible()); + return _e3; } float test_textureLoad_depth_2d( @@ -65,8 +65,8 @@ float test_textureLoad_depth_2d( int level_4, metal::depth2d image_depth_2d ) { - float _e8 = (uint(level_4) < image_depth_2d.get_num_mip_levels() && metal::all(metal::uint2(coords_5) < metal::uint2(image_depth_2d.get_width(level_4), image_depth_2d.get_height(level_4))) ? image_depth_2d.read(metal::uint2(coords_5), level_4): DefaultConstructible()); - return _e8; + float _e3 = (uint(level_4) < image_depth_2d.get_num_mip_levels() && metal::all(metal::uint2(coords_5) < metal::uint2(image_depth_2d.get_width(level_4), image_depth_2d.get_height(level_4))) ? image_depth_2d.read(metal::uint2(coords_5), level_4): DefaultConstructible()); + return _e3; } float test_textureLoad_depth_2d_array( @@ -75,8 +75,8 @@ float test_textureLoad_depth_2d_array( int level_5, metal::depth2d_array image_depth_2d_array ) { - float _e10 = (uint(level_5) < image_depth_2d_array.get_num_mip_levels() && uint(index_1) < image_depth_2d_array.get_array_size() && metal::all(metal::uint2(coords_6) < metal::uint2(image_depth_2d_array.get_width(level_5), image_depth_2d_array.get_height(level_5))) ? image_depth_2d_array.read(metal::uint2(coords_6), index_1, level_5): DefaultConstructible()); - return _e10; + float _e4 = (uint(level_5) < image_depth_2d_array.get_num_mip_levels() && uint(index_1) < image_depth_2d_array.get_array_size() && metal::all(metal::uint2(coords_6) < metal::uint2(image_depth_2d_array.get_width(level_5), image_depth_2d_array.get_height(level_5))) ? image_depth_2d_array.read(metal::uint2(coords_6), index_1, level_5): DefaultConstructible()); + return _e4; } float test_textureLoad_depth_multisampled_2d( @@ -84,8 +84,8 @@ float test_textureLoad_depth_multisampled_2d( int _sample_1, metal::depth2d_ms image_depth_multisampled_2d ) { - float _e10 = (uint(_sample_1) < image_depth_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_7) < metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height())) ? image_depth_multisampled_2d.read(metal::uint2(coords_7), _sample_1): DefaultConstructible()); - return _e10; + float _e3 = (uint(_sample_1) < image_depth_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_7) < metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height())) ? image_depth_multisampled_2d.read(metal::uint2(coords_7), _sample_1): DefaultConstructible()); + return _e3; } void test_textureStore_1d( @@ -147,11 +147,11 @@ fragment fragment_shaderOutput fragment_shader( , metal::texture2d_array image_storage_2d_array [[user(fake0)]] , metal::texture3d image_storage_3d [[user(fake0)]] ) { - metal::float4 _e14 = test_textureLoad_1d(0, 0, image_1d); - metal::float4 _e17 = test_textureLoad_2d(const_type_4_, 0, image_2d); - metal::float4 _e21 = test_textureLoad_2d_array(const_type_4_, 0, 0, image_2d_array); - metal::float4 _e24 = test_textureLoad_3d(const_type_7_, 0, image_3d); - metal::float4 _e27 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); + metal::float4 _e2 = test_textureLoad_1d(0, 0, image_1d); + metal::float4 _e5 = test_textureLoad_2d(const_type_4_, 0, image_2d); + metal::float4 _e9 = test_textureLoad_2d_array(const_type_4_, 0, 0, image_2d_array); + metal::float4 _e12 = test_textureLoad_3d(const_type_7_, 0, image_3d); + metal::float4 _e15 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); test_textureStore_1d(0, const_type_2_, image_storage_1d); test_textureStore_2d(const_type_4_, const_type_2_, image_storage_2d); test_textureStore_2d_array(const_type_4_, 0, const_type_2_, image_storage_2d_array); diff --git a/tests/out/msl/bounds-check-restrict.msl b/tests/out/msl/bounds-check-restrict.msl index a614e5924..49a232e70 100644 --- a/tests/out/msl/bounds-check-restrict.msl +++ b/tests/out/msl/bounds-check-restrict.msl @@ -87,9 +87,9 @@ float index_in_bounds( constant _mslBufferSizes& _buffer_sizes ) { float _e4 = globals.a.inner[9]; - float _e8 = globals.v.w; - float _e15 = globals.m[2].w; - return (_e4 + _e8) + _e15; + float _e9 = globals.v.w; + float _e17 = globals.m[2].w; + return (_e4 + _e9) + _e17; } void set_array( diff --git a/tests/out/msl/bounds-check-zero.msl b/tests/out/msl/bounds-check-zero.msl index b45550d5a..fece92de3 100644 --- a/tests/out/msl/bounds-check-zero.msl +++ b/tests/out/msl/bounds-check-zero.msl @@ -94,9 +94,9 @@ float index_in_bounds( constant _mslBufferSizes& _buffer_sizes ) { float _e4 = globals.a.inner[9]; - float _e8 = globals.v.w; - float _e15 = globals.m[2].w; - return (_e4 + _e8) + _e15; + float _e9 = globals.v.w; + float _e17 = globals.m[2].w; + return (_e4 + _e9) + _e17; } void set_array( diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index 2189632d0..88f9521a2 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -17,27 +17,30 @@ uint collatz_iterations( uint n_base ) { uint n = {}; - uint i = 0u; + uint i = {}; n = n_base; + i = 0u; while(true) { - uint _e5 = n; - if (_e5 > 1u) { + uint _e4 = n; + if (_e4 > 1u) { } else { break; } - uint _e8 = n; - if ((_e8 % 2u) == 0u) { - uint _e13 = n; - n = _e13 / 2u; - } else { - uint _e17 = n; - n = (3u * _e17) + 1u; + { + uint _e7 = n; + if ((_e7 % 2u) == 0u) { + uint _e12 = n; + n = _e12 / 2u; + } else { + uint _e16 = n; + n = (3u * _e16) + 1u; + } + uint _e20 = i; + i = _e20 + 1u; } - uint _e21 = i; - i = _e21 + 1u; } - uint _e24 = i; - return _e24; + uint _e23 = i; + return _e23; } struct main_Input { @@ -47,8 +50,8 @@ kernel void main_( , device PrimeIndices& v_indices [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - uint _e8 = v_indices.data[global_id.x]; - uint _e9 = collatz_iterations(_e8); - v_indices.data[global_id.x] = _e9; + uint _e9 = v_indices.data[global_id.x]; + uint _e10 = collatz_iterations(_e9); + v_indices.data[global_id.x] = _e10; return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index b461cce3f..b821cc9d5 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -8,11 +8,11 @@ struct _mslBufferSizes { uint size3; }; -constexpr constant bool Foo_2 = true; +constexpr constant bool Foo_1 = true; struct type_2 { float inner[10u]; }; -struct Foo { +struct FooStruct { metal::packed_float3 v3_; float v1_; }; @@ -42,15 +42,16 @@ void test_msl_packed_vec3_as_arg( } void test_msl_packed_vec3_( - device Foo& alignment + device FooStruct& alignment ) { - int idx = 1; + int idx = {}; alignment.v3_ = metal::float3(1.0); + idx = 1; alignment.v3_[0] = 1.0; alignment.v3_[0] = 2.0; - int _e23 = idx; - alignment.v3_[_e23] = 3.0; - Foo data = alignment; + int _e17 = idx; + alignment.v3_[_e17] = 3.0; + FooStruct data = alignment; metal::float3 unnamed = data.v3_; metal::float2 unnamed_1 = metal::float3(data.v3_).zx; test_msl_packed_vec3_as_arg(data.v3_); @@ -63,7 +64,7 @@ void test_msl_packed_vec3_( kernel void main_( threadgroup type_2& wg , threadgroup metal::atomic_uint& at_1 -, device Foo& alignment [[user(fake0)]] +, device FooStruct& alignment [[user(fake0)]] , device type_6 const& dummy [[user(fake0)]] , constant type_8& float_vecs [[user(fake0)]] , constant metal::float3& global_vec [[user(fake0)]] @@ -72,25 +73,27 @@ kernel void main_( , constant type_15& global_nested_arrays_of_matrices_4x2_ [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - float Foo_1 = 1.0; - bool at = true; + float Foo = {}; + bool at = {}; test_msl_packed_vec3_(alignment); - metal::float4x2 _e16 = global_nested_arrays_of_matrices_4x2_.inner[0].inner[0]; - metal::float4 _e23 = global_nested_arrays_of_matrices_2x4_.inner[0].inner[0][0]; - wg.inner[7] = (_e16 * _e23).x; - metal::float3x2 _e28 = global_mat; - metal::float3 _e29 = global_vec; - wg.inner[6] = (_e28 * _e29).x; - float _e37 = dummy[1].y; - wg.inner[5] = _e37; + metal::float4x2 _e8 = global_nested_arrays_of_matrices_4x2_.inner[0].inner[0]; + metal::float4 _e16 = global_nested_arrays_of_matrices_2x4_.inner[0].inner[0][0]; + wg.inner[7] = (_e8 * _e16).x; + metal::float3x2 _e23 = global_mat; + metal::float3 _e25 = global_vec; + wg.inner[6] = (_e23 * _e25).x; + float _e35 = dummy[1].y; + wg.inner[5] = _e35; float _e43 = float_vecs.inner[0].w; wg.inner[4] = _e43; - float _e47 = alignment.v1_; - wg.inner[3] = _e47; - float _e52 = alignment.v3_[0]; - wg.inner[2] = _e52; + float _e49 = alignment.v1_; + wg.inner[3] = _e49; + float _e56 = alignment.v3_[0]; + wg.inner[2] = _e56; alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); + Foo = 1.0; + at = true; return; } diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 9b8013531..7eea0a4f0 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -93,7 +93,8 @@ vertex vertex_two_structsOutput vertex_two_structs( ) { const Input1_ in1_ = { index_1 }; const Input2_ in2_ = { index_2 }; - uint index = 2u; - uint _e9 = index; - return vertex_two_structsOutput { metal::float4(static_cast(in1_.index), static_cast(in2_.index), static_cast(_e9), 0.0), 1.0 }; + uint index = {}; + index = 2u; + uint _e8 = index; + return vertex_two_structsOutput { metal::float4(static_cast(in1_.index), static_cast(in2_.index), static_cast(_e8), 0.0), 1.0 }; } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 6ee0093d0..559d46468 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -4,7 +4,7 @@ using metal::uint; -constant metal::int2 const_type = {0, 0}; +constant metal::int2 const_type_1_ = {0, 0}; vertex void main_( ) { @@ -14,6 +14,6 @@ vertex void main_( metal::float4 c = ((v) * 57.295779513082322865); metal::float4 d = ((v) * 0.017453292519943295474); metal::float4 e = metal::saturate(v); - int const_dot = ( + const_type.x * const_type.x + const_type.y * const_type.y); + int const_dot = ( + const_type_1_.x * const_type_1_.x + const_type_1_.y * const_type_1_.y); uint first_leading_bit_abs = (((metal::clz(metal::abs(0u)) + 1) % 33) - 1); } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 72a0c3025..549ed49ef 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -8,28 +8,28 @@ struct Foo { metal::float4 a; int b; }; -struct type_12 { +struct type_13 { Foo inner[3]; }; -struct type_13 { +struct type_14 { int inner[4u]; }; constant metal::float4 v_f32_one = {1.0, 1.0, 1.0, 1.0}; constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0}; constant metal::float4 v_f32_half = {0.5, 0.5, 0.5, 0.5}; constant metal::int4 v_i32_one = {1, 1, 1, 1}; -constant metal::uint2 const_type_11_ = {0u, 0u}; +constant metal::uint2 const_type_12_ = {0u, 0u}; constant metal::float2 const_type_4_ = {0.0, 0.0}; -constant metal::float2x2 const_type_7_ = {const_type_4_, const_type_4_}; +constant metal::float2x2 const_type_8_ = {const_type_4_, const_type_4_}; constant metal::float4 const_type = {0.0, 0.0, 0.0, 0.0}; constant Foo const_Foo = {const_type, 0}; -constant type_12 const_type_12_ = {const_Foo, const_Foo, const_Foo}; +constant type_13 const_type_13_ = {const_Foo, const_Foo, const_Foo}; constant metal::float3 const_type_5_ = {0.0, 0.0, 0.0}; -constant metal::float2x3 const_type_14_ = {const_type_5_, const_type_5_}; -constant metal::float3x3 const_type_15_ = {const_type_5_, const_type_5_, const_type_5_}; -constant metal::float4x3 const_type_16_ = {const_type_5_, const_type_5_, const_type_5_, const_type_5_}; -constant metal::float3x4 const_type_17_ = {const_type, const_type, const_type}; -constant metal::int3 const_type_18_ = {0, 0, 0}; +constant metal::float2x3 const_type_15_ = {const_type_5_, const_type_5_}; +constant metal::float3x3 const_type_16_ = {const_type_5_, const_type_5_, const_type_5_}; +constant metal::float4x3 const_type_17_ = {const_type_5_, const_type_5_, const_type_5_, const_type_5_}; +constant metal::float3x4 const_type_18_ = {const_type, const_type, const_type}; +constant metal::int3 const_type_19_ = {0, 0, 0}; metal::float4 builtins( ) { @@ -55,14 +55,14 @@ metal::float2 splat_assignment( ) { metal::float2 a = {}; a = metal::float2(2.0); - metal::float2 _e7 = a; - a = _e7 + metal::float2(1.0); - metal::float2 _e11 = a; - a = _e11 - metal::float2(3.0); + metal::float2 _e4 = a; + a = _e4 + metal::float2(1.0); + metal::float2 _e8 = a; + a = _e8 - metal::float2(3.0); + metal::float2 _e12 = a; + a = _e12 / metal::float2(4.0); metal::float2 _e15 = a; - a = _e15 / metal::float2(4.0); - metal::float2 _e19 = a; - return _e19; + return _e15; } metal::float3 bool_cast( @@ -80,17 +80,17 @@ float constructors( metal::float4x4 mat4comp = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); metal::uint2 unnamed = metal::uint2(0u); metal::float2x2 unnamed_1 = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); - type_13 unnamed_2 = type_13 {0, 1, 2, 3}; + type_14 unnamed_2 = type_14 {0, 1, 2, 3}; bool unnamed_3 = static_cast(false); int unnamed_4 = static_cast(0); uint unnamed_5 = static_cast(0u); float unnamed_6 = static_cast(0.0); - metal::uint2 unnamed_7 = static_cast(const_type_11_); - metal::float2x3 unnamed_8 = metal::float2x3(const_type_14_); - metal::uint2 unnamed_9 = as_type(const_type_11_); - metal::float2x3 unnamed_10 = metal::float2x3(const_type_14_); - float _e75 = foo.a.x; - return _e75; + metal::uint2 unnamed_7 = static_cast(const_type_12_); + metal::float2x3 unnamed_8 = metal::float2x3(const_type_15_); + metal::uint2 unnamed_9 = as_type(const_type_12_); + metal::float2x3 unnamed_10 = metal::float2x3(const_type_15_); + float _e71 = foo.a.x; + return _e71; } void logical( @@ -169,13 +169,13 @@ void arithmetic( metal::uint2 unnamed_78 = metal::uint2(2u) % metal::uint2(1u); metal::float2 unnamed_79 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); metal::float2 unnamed_80 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float3x3 unnamed_81 = const_type_15_ + const_type_15_; - metal::float3x3 unnamed_82 = const_type_15_ - const_type_15_; - metal::float3x3 unnamed_83 = const_type_15_ * 1.0; - metal::float3x3 unnamed_84 = 2.0 * const_type_15_; - metal::float3 unnamed_85 = const_type_16_ * metal::float4(1.0); - metal::float4 unnamed_86 = metal::float3(2.0) * const_type_16_; - metal::float3x3 unnamed_87 = const_type_16_ * const_type_17_; + metal::float3x3 unnamed_81 = const_type_16_ + const_type_16_; + metal::float3x3 unnamed_82 = const_type_16_ - const_type_16_; + metal::float3x3 unnamed_83 = const_type_16_ * 1.0; + metal::float3x3 unnamed_84 = 2.0 * const_type_16_; + metal::float3 unnamed_85 = const_type_17_ * metal::float4(1.0); + metal::float4 unnamed_86 = metal::float3(2.0) * const_type_17_; + metal::float3x3 unnamed_87 = const_type_17_ * const_type_18_; } void bit( @@ -248,38 +248,40 @@ void comparison( void assignment( ) { - int a_1 = 1; - metal::int3 vec0_ = const_type_18_; + int a_1 = {}; + metal::int3 vec0_ = {}; + a_1 = 1; + int _e3 = a_1; + a_1 = _e3 + 1; int _e6 = a_1; - a_1 = _e6 + 1; + a_1 = _e6 - 1; + int _e8 = a_1; int _e9 = a_1; - a_1 = _e9 - 1; + a_1 = _e9 * _e8; + int _e11 = a_1; int _e12 = a_1; - int _e13 = a_1; - a_1 = _e12 * _e13; + a_1 = _e12 / _e11; int _e15 = a_1; - int _e16 = a_1; - a_1 = _e15 / _e16; + a_1 = _e15 % 1; int _e18 = a_1; - a_1 = _e18 % 1; + a_1 = _e18 & 0; int _e21 = a_1; - a_1 = _e21 & 0; + a_1 = _e21 | 0; int _e24 = a_1; - a_1 = _e24 | 0; + a_1 = _e24 ^ 0; int _e27 = a_1; - a_1 = _e27 ^ 0; + a_1 = _e27 << 2u; int _e30 = a_1; - a_1 = _e30 << 2u; - int _e33 = a_1; - a_1 = _e33 >> 1u; - int _e36 = a_1; - a_1 = _e36 + 1; - int _e39 = a_1; - a_1 = _e39 - 1; - int _e46 = vec0_.y; - vec0_.y = _e46 + 1; - int _e51 = vec0_.y; - vec0_.y = _e51 - 1; + a_1 = _e30 >> 1u; + int _e32 = a_1; + a_1 = _e32 + 1; + int _e35 = a_1; + a_1 = _e35 - 1; + vec0_ = const_type_19_; + int _e42 = vec0_.y; + vec0_.y = _e42 + 1; + int _e47 = vec0_.y; + vec0_.y = _e47 - 1; return; } @@ -296,10 +298,10 @@ void negation_avoids_prefix_decrement( kernel void main_( ) { - metal::float4 _e4 = builtins(); - metal::float4 _e5 = splat(); - metal::float3 _e7 = bool_cast(v_f32_one.xyz); - float _e8 = constructors(); + metal::float4 _e0 = builtins(); + metal::float4 _e1 = splat(); + metal::float3 _e4 = bool_cast(v_f32_one.xyz); + float _e5 = constructors(); logical(); arithmetic(); bit(); diff --git a/tests/out/msl/padding.msl b/tests/out/msl/padding.msl index 90b2c2eb1..4d99bb4c4 100644 --- a/tests/out/msl/padding.msl +++ b/tests/out/msl/padding.msl @@ -31,8 +31,8 @@ vertex vertex_Output vertex_( , constant Test2_& input2_ [[buffer(1)]] , constant Test3_& input3_ [[buffer(2)]] ) { - float _e6 = input1_.b; - float _e9 = input2_.b; + float _e4 = input1_.b; + float _e8 = input2_.b; float _e12 = input3_.b; - return vertex_Output { ((metal::float4(1.0) * _e6) * _e9) * _e12 }; + return vertex_Output { ((metal::float4(1.0) * _e4) * _e8) * _e12 }; } diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index dd780641f..842c57e58 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -44,11 +44,11 @@ metal::float4 mock_function( ) { type_9 in_function = {}; for(int _i=0; _i<2; ++_i) in_function.inner[_i] = type_9 {metal::float4(0.7070000171661377, 0.0, 0.0, 1.0), metal::float4(0.0, 0.7070000171661377, 0.0, 1.0)}.inner[_i]; - metal::float4 _e22 = in_storage.a.inner[i]; - metal::float4 _e25 = in_uniform.a.inner[i]; - metal::float4 _e27 = (uint(l) < image_2d_array.get_num_mip_levels() && uint(i) < image_2d_array.get_array_size() && metal::all(metal::uint2(c) < metal::uint2(image_2d_array.get_width(l), image_2d_array.get_height(l))) ? image_2d_array.read(metal::uint2(c), i, l): DefaultConstructible()); - float _e30 = in_workgroup.inner[metal::min(unsigned(i), 29u)]; + metal::float4 _e18 = in_storage.a.inner[i]; + metal::float4 _e22 = in_uniform.a.inner[i]; + metal::float4 _e25 = (uint(l) < image_2d_array.get_num_mip_levels() && uint(i) < image_2d_array.get_array_size() && metal::all(metal::uint2(c) < metal::uint2(image_2d_array.get_width(l), image_2d_array.get_height(l))) ? image_2d_array.read(metal::uint2(c), i, l): DefaultConstructible()); + float _e29 = in_workgroup.inner[metal::min(unsigned(i), 29u)]; float _e34 = in_private.inner[metal::min(unsigned(i), 39u)]; metal::float4 _e38 = in_function.inner[metal::min(unsigned(i), 1u)]; - return ((((_e22 + _e25) + _e27) + metal::float4(_e30)) + metal::float4(_e34)) + _e38; + return ((((_e18 + _e22) + _e25) + metal::float4(_e29)) + metal::float4(_e34)) + _e38; } diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 651a89841..fa1b284c6 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -45,8 +45,8 @@ float fetch_shadow( metal::float2 flip_correction = metal::float2(0.5, -0.5); float proj_correction = 1.0 / homogeneous_coords.w; metal::float2 light_local = ((homogeneous_coords.xy * flip_correction) * proj_correction) + metal::float2(0.5, 0.5); - float _e28 = t_shadow.sample_compare(sampler_shadow, light_local, static_cast(light_id), homogeneous_coords.z * proj_correction); - return _e28; + float _e24 = t_shadow.sample_compare(sampler_shadow, light_local, static_cast(light_id), homogeneous_coords.z * proj_correction); + return _e24; } struct vs_mainInput { @@ -71,10 +71,10 @@ vertex vs_mainOutput vs_main( metal::float4 world_pos = _e7 * static_cast(position); out.world_normal = metal::float3x3(w[0].xyz, w[1].xyz, w[2].xyz) * static_cast(normal.xyz); out.world_position = world_pos; - metal::float4x4 _e25 = u_globals.view_proj; - out.proj_position = _e25 * world_pos; - VertexOutput _e27 = out; - const auto _tmp = _e27; + metal::float4x4 _e26 = u_globals.view_proj; + out.proj_position = _e26 * world_pos; + VertexOutput _e28 = out; + const auto _tmp = _e28; return vs_mainOutput { _tmp.proj_position, _tmp.world_normal, _tmp.world_position }; } @@ -97,34 +97,38 @@ fragment fs_mainOutput fs_main( , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { const VertexOutput in = { proj_position, varyings_1.world_normal, varyings_1.world_position }; - metal::float3 color = c_ambient; - uint i = 0u; + metal::float3 color = {}; + uint i = {}; metal::float3 normal_1 = metal::normalize(in.world_normal); + color = c_ambient; + i = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _e20 = i; - i = _e20 + 1u; + uint _e39 = i; + i = _e39 + 1u; } loop_init = false; - uint _e14 = i; - uint _e17 = u_globals.num_lights.x; - if (_e14 < metal::min(_e17, c_max_lights)) { + uint _e7 = i; + uint _e11 = u_globals.num_lights.x; + if (_e7 < metal::min(_e11, c_max_lights)) { } else { break; } - uint _e23 = i; - Light light = s_lights[_e23]; - uint _e26 = i; - float _e30 = fetch_shadow(_e26, light.proj * in.world_position, t_shadow, sampler_shadow); - metal::float3 light_dir = metal::normalize(light.pos.xyz - in.world_position.xyz); - float diffuse = metal::max(0.0, metal::dot(normal_1, light_dir)); - metal::float3 _e40 = color; - color = _e40 + ((_e30 * diffuse) * light.color.xyz); + { + uint _e16 = i; + Light light = s_lights[_e16]; + uint _e19 = i; + float _e23 = fetch_shadow(_e19, light.proj * in.world_position, t_shadow, sampler_shadow); + metal::float3 light_dir = metal::normalize(light.pos.xyz - in.world_position.xyz); + float diffuse = metal::max(0.0, metal::dot(normal_1, light_dir)); + metal::float3 _e37 = color; + color = _e37 + ((_e23 * diffuse) * light.color.xyz); + } } - metal::float3 _e46 = color; - metal::float4 _e50 = u_entity.color; - return fs_mainOutput { metal::float4(_e46, 1.0) * _e50 }; + metal::float3 _e42 = color; + metal::float4 _e47 = u_entity.color; + return fs_mainOutput { metal::float4(_e42, 1.0) * _e47 }; } @@ -145,32 +149,36 @@ fragment fs_main_without_storageOutput fs_main_without_storage( , metal::sampler sampler_shadow [[user(fake0)]] ) { const VertexOutput in_1 = { proj_position_1, varyings_2.world_normal, varyings_2.world_position }; - metal::float3 color_1 = c_ambient; - uint i_1 = 0u; + metal::float3 color_1 = {}; + uint i_1 = {}; metal::float3 normal_2 = metal::normalize(in_1.world_normal); + color_1 = c_ambient; + i_1 = 0u; bool loop_init_1 = true; while(true) { if (!loop_init_1) { - uint _e20 = i_1; - i_1 = _e20 + 1u; + uint _e39 = i_1; + i_1 = _e39 + 1u; } loop_init_1 = false; - uint _e14 = i_1; - uint _e17 = u_globals.num_lights.x; - if (_e14 < metal::min(_e17, c_max_lights)) { + uint _e7 = i_1; + uint _e11 = u_globals.num_lights.x; + if (_e7 < metal::min(_e11, c_max_lights)) { } else { break; } - uint _e23 = i_1; - Light light_1 = u_lights.inner[_e23]; - uint _e26 = i_1; - float _e30 = fetch_shadow(_e26, light_1.proj * in_1.world_position, t_shadow, sampler_shadow); - metal::float3 light_dir_1 = metal::normalize(light_1.pos.xyz - in_1.world_position.xyz); - float diffuse_1 = metal::max(0.0, metal::dot(normal_2, light_dir_1)); - metal::float3 _e40 = color_1; - color_1 = _e40 + ((_e30 * diffuse_1) * light_1.color.xyz); + { + uint _e16 = i_1; + Light light_1 = u_lights.inner[_e16]; + uint _e19 = i_1; + float _e23 = fetch_shadow(_e19, light_1.proj * in_1.world_position, t_shadow, sampler_shadow); + metal::float3 light_dir_1 = metal::normalize(light_1.pos.xyz - in_1.world_position.xyz); + float diffuse_1 = metal::max(0.0, metal::dot(normal_2, light_dir_1)); + metal::float3 _e37 = color_1; + color_1 = _e37 + ((_e23 * diffuse_1) * light_1.color.xyz); + } } - metal::float3 _e46 = color_1; - metal::float4 _e50 = u_entity.color; - return fs_main_without_storageOutput { metal::float4(_e46, 1.0) * _e50 }; + metal::float3 _e42 = color_1; + metal::float4 _e47 = u_entity.color; + return fs_main_without_storageOutput { metal::float4(_e42, 1.0) * _e47 }; } diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl index c25770d4f..7b10ea23e 100644 --- a/tests/out/msl/skybox.msl +++ b/tests/out/msl/skybox.msl @@ -27,15 +27,15 @@ vertex vs_mainOutput vs_main( int tmp2_ = {}; tmp1_ = static_cast(vertex_index) / 2; tmp2_ = static_cast(vertex_index) & 1; - int _e10 = tmp1_; - int _e16 = tmp2_; - metal::float4 pos = metal::float4((static_cast(_e10) * 4.0) - 1.0, (static_cast(_e16) * 4.0) - 1.0, 0.0, 1.0); + int _e9 = tmp1_; + int _e15 = tmp2_; + metal::float4 pos = metal::float4((static_cast(_e9) * 4.0) - 1.0, (static_cast(_e15) * 4.0) - 1.0, 0.0, 1.0); metal::float4 _e27 = r_data.view[0]; - metal::float4 _e31 = r_data.view[1]; - metal::float4 _e35 = r_data.view[2]; - metal::float3x3 inv_model_view = metal::transpose(metal::float3x3(_e27.xyz, _e31.xyz, _e35.xyz)); - metal::float4x4 _e40 = r_data.proj_inv; - metal::float4 unprojected = _e40 * pos; + metal::float4 _e32 = r_data.view[1]; + metal::float4 _e37 = r_data.view[2]; + metal::float3x3 inv_model_view = metal::transpose(metal::float3x3(_e27.xyz, _e32.xyz, _e37.xyz)); + metal::float4x4 _e43 = r_data.proj_inv; + metal::float4 unprojected = _e43 * pos; const auto _tmp = VertexOutput {pos, inv_model_view * unprojected.xyz}; return vs_mainOutput { _tmp.position, _tmp.uv }; } @@ -61,6 +61,6 @@ fragment fs_mainOutput fs_main( metal::coord::normalized ); const VertexOutput in = { position, varyings_1.uv }; - metal::float4 _e5 = r_texture.sample(r_sampler, in.uv); - return fs_mainOutput { _e5 }; + metal::float4 _e4 = r_texture.sample(r_sampler, in.uv); + return fs_mainOutput { _e4 }; } diff --git a/tests/out/msl/texture-arg.msl b/tests/out/msl/texture-arg.msl index ba0be05e1..5fb9b2564 100644 --- a/tests/out/msl/texture-arg.msl +++ b/tests/out/msl/texture-arg.msl @@ -9,8 +9,8 @@ metal::float4 test( metal::texture2d Passed_Texture, metal::sampler Passed_Sampler ) { - metal::float4 _e7 = Passed_Texture.sample(Passed_Sampler, metal::float2(0.0, 0.0)); - return _e7; + metal::float4 _e5 = Passed_Texture.sample(Passed_Sampler, metal::float2(0.0, 0.0)); + return _e5; } struct main_Output { diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index fe7e75d4a..bc3cb6a50 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,18 +1,18 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 320 +; Bound: 323 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %233 "foo_vert" %228 %231 -OpEntryPoint Fragment %274 "foo_frag" %273 -OpEntryPoint GLCompute %293 "atomics" -OpEntryPoint GLCompute %317 "assign_through_ptr" -OpExecutionMode %274 OriginUpperLeft -OpExecutionMode %293 LocalSize 1 1 1 -OpExecutionMode %317 LocalSize 1 1 1 +OpEntryPoint Vertex %236 "foo_vert" %231 %234 +OpEntryPoint Fragment %277 "foo_frag" %276 +OpEntryPoint GLCompute %296 "atomics" +OpEntryPoint GLCompute %320 "assign_through_ptr" +OpExecutionMode %277 OriginUpperLeft +OpExecutionMode %296 LocalSize 1 1 1 +OpExecutionMode %320 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %36 0 "a" OpMemberName %36 1 "b" @@ -30,32 +30,32 @@ OpMemberName %48 0 "m" OpName %48 "Baz" OpMemberName %52 0 "am" OpName %52 "MatCx2InArray" -OpName %68 "global_const" -OpName %70 "bar" -OpName %72 "baz" -OpName %75 "qux" -OpName %78 "nested_mat_cx2" -OpName %81 "val" -OpName %82 "idx" -OpName %84 "t" -OpName %88 "test_matrix_within_struct_accesses" -OpName %146 "idx" -OpName %147 "t" -OpName %151 "test_matrix_within_array_within_struct_accesses" -OpName %206 "foo" -OpName %207 "read_from_private" -OpName %212 "a" -OpName %213 "test_arr_as_arg" -OpName %219 "p" -OpName %220 "assign_through_ptr_fn" -OpName %223 "foo" -OpName %224 "c" -OpName %228 "vi" -OpName %233 "foo_vert" -OpName %274 "foo_frag" -OpName %290 "tmp" -OpName %293 "atomics" -OpName %317 "assign_through_ptr" +OpName %69 "global_const" +OpName %71 "bar" +OpName %73 "baz" +OpName %76 "qux" +OpName %79 "nested_mat_cx2" +OpName %82 "val" +OpName %83 "idx" +OpName %86 "t" +OpName %90 "test_matrix_within_struct_accesses" +OpName %147 "idx" +OpName %149 "t" +OpName %153 "test_matrix_within_array_within_struct_accesses" +OpName %208 "foo" +OpName %209 "read_from_private" +OpName %214 "a" +OpName %215 "test_arr_as_arg" +OpName %221 "p" +OpName %222 "assign_through_ptr_fn" +OpName %225 "foo" +OpName %227 "c2" +OpName %231 "vi" +OpName %236 "foo_vert" +OpName %277 "foo_frag" +OpName %293 "tmp" +OpName %296 "atomics" +OpName %320 "assign_through_ptr" OpMemberDecorate %36 0 Offset 0 OpMemberDecorate %36 1 Offset 16 OpMemberDecorate %36 2 Offset 28 @@ -82,24 +82,24 @@ OpMemberDecorate %52 0 MatrixStride 8 OpDecorate %54 ArrayStride 4 OpDecorate %55 ArrayStride 40 OpDecorate %58 ArrayStride 4 -OpDecorate %70 DescriptorSet 0 -OpDecorate %70 Binding 0 +OpDecorate %71 DescriptorSet 0 +OpDecorate %71 Binding 0 OpDecorate %46 Block -OpDecorate %72 DescriptorSet 0 -OpDecorate %72 Binding 1 -OpDecorate %73 Block -OpMemberDecorate %73 0 Offset 0 -OpDecorate %75 DescriptorSet 0 -OpDecorate %75 Binding 2 -OpDecorate %76 Block -OpMemberDecorate %76 0 Offset 0 -OpDecorate %78 DescriptorSet 0 -OpDecorate %78 Binding 3 -OpDecorate %79 Block -OpMemberDecorate %79 0 Offset 0 -OpDecorate %228 BuiltIn VertexIndex -OpDecorate %231 BuiltIn Position -OpDecorate %273 Location 0 +OpDecorate %73 DescriptorSet 0 +OpDecorate %73 Binding 1 +OpDecorate %74 Block +OpMemberDecorate %74 0 Offset 0 +OpDecorate %76 DescriptorSet 0 +OpDecorate %76 Binding 2 +OpDecorate %77 Block +OpMemberDecorate %77 0 Offset 0 +OpDecorate %79 DescriptorSet 0 +OpDecorate %79 Binding 3 +OpDecorate %80 Block +OpMemberDecorate %80 0 Offset 0 +OpDecorate %231 BuiltIn VertexIndex +OpDecorate %234 BuiltIn Position +OpDecorate %276 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -157,332 +157,338 @@ OpDecorate %273 Location 0 %56 = OpTypeVector %10 4 %57 = OpTypePointer StorageBuffer %6 %58 = OpTypeArray %6 %26 -%59 = OpTypePointer Workgroup %4 -%60 = OpConstantComposite %35 %3 %3 %3 -%61 = OpConstantComposite %36 %3 %60 %5 -%62 = OpConstantComposite %41 %22 %22 -%63 = OpConstantComposite %50 %62 %62 %62 %62 -%64 = OpConstantComposite %51 %63 %63 -%65 = OpConstantComposite %54 %22 %22 %22 %22 %22 %22 %22 %22 %22 %22 -%66 = OpConstantComposite %55 %65 %65 %65 %65 %65 -%67 = OpConstantComposite %49 %5 %5 -%69 = OpTypePointer Private %36 -%68 = OpVariable %69 Private %61 -%71 = OpTypePointer StorageBuffer %46 -%70 = OpVariable %71 StorageBuffer -%73 = OpTypeStruct %48 -%74 = OpTypePointer Uniform %73 -%72 = OpVariable %74 Uniform -%76 = OpTypeStruct %49 -%77 = OpTypePointer StorageBuffer %76 -%75 = OpVariable %77 StorageBuffer -%79 = OpTypeStruct %52 -%80 = OpTypePointer Uniform %79 -%78 = OpVariable %80 Uniform -%81 = OpVariable %59 Workgroup -%83 = OpTypePointer Function %6 -%85 = OpTypePointer Function %48 -%86 = OpConstantNull %48 -%89 = OpTypeFunction %2 -%90 = OpTypePointer Uniform %48 -%92 = OpTypePointer StorageBuffer %49 -%96 = OpTypePointer Uniform %47 -%99 = OpTypePointer Uniform %41 -%105 = OpTypePointer Uniform %10 -%125 = OpTypePointer Function %47 -%131 = OpTypePointer Function %41 -%137 = OpTypePointer Function %10 -%148 = OpTypePointer Function %52 -%149 = OpConstantNull %52 -%152 = OpTypePointer Uniform %52 -%157 = OpTypePointer Uniform %51 -%160 = OpTypePointer Uniform %50 -%183 = OpTypePointer Function %51 -%185 = OpTypePointer Function %50 -%208 = OpTypeFunction %10 %53 -%214 = OpTypeFunction %10 %55 -%221 = OpTypeFunction %2 %59 -%225 = OpTypePointer Function %58 -%226 = OpConstantNull %58 -%229 = OpTypePointer Input %4 -%228 = OpVariable %229 Input -%232 = OpTypePointer Output %56 -%231 = OpVariable %232 Output -%241 = OpTypePointer StorageBuffer %38 -%244 = OpTypePointer StorageBuffer %44 -%247 = OpTypePointer StorageBuffer %39 -%248 = OpTypePointer StorageBuffer %10 -%251 = OpTypePointer StorageBuffer %45 -%254 = OpTypePointer StorageBuffer %37 -%255 = OpConstant %4 4 -%267 = OpTypeVector %6 4 -%273 = OpVariable %232 Output -%291 = OpConstantNull %6 -%295 = OpTypePointer StorageBuffer %6 -%298 = OpConstant %4 64 -%88 = OpFunction %2 None %89 -%87 = OpLabel -%82 = OpVariable %83 Function %8 -%84 = OpVariable %85 Function %86 -%91 = OpAccessChain %90 %72 %3 -OpBranch %93 -%93 = OpLabel -%94 = OpLoad %6 %82 -%95 = OpISub %6 %94 %8 -OpStore %82 %95 -%97 = OpAccessChain %96 %91 %3 -%98 = OpLoad %47 %97 -%100 = OpAccessChain %99 %91 %3 %3 -%101 = OpLoad %41 %100 -%102 = OpLoad %6 %82 -%103 = OpAccessChain %99 %91 %3 %102 -%104 = OpLoad %41 %103 -%106 = OpAccessChain %105 %91 %3 %3 %32 -%107 = OpLoad %10 %106 -%108 = OpLoad %6 %82 -%109 = OpAccessChain %105 %91 %3 %3 %108 -%110 = OpLoad %10 %109 -%111 = OpLoad %6 %82 -%112 = OpAccessChain %105 %91 %3 %111 %32 -%113 = OpLoad %10 %112 -%114 = OpLoad %6 %82 -%115 = OpLoad %6 %82 -%116 = OpAccessChain %105 %91 %3 %114 %115 -%117 = OpLoad %10 %116 -%118 = OpCompositeConstruct %41 %9 %9 -%119 = OpCompositeConstruct %41 %11 %11 -%120 = OpCompositeConstruct %41 %12 %12 -%121 = OpCompositeConstruct %47 %118 %119 %120 -%122 = OpCompositeConstruct %48 %121 -OpStore %84 %122 -%123 = OpLoad %6 %82 -%124 = OpIAdd %6 %123 %8 -OpStore %82 %124 -%126 = OpCompositeConstruct %41 %13 %13 -%127 = OpCompositeConstruct %41 %14 %14 -%128 = OpCompositeConstruct %41 %15 %15 -%129 = OpCompositeConstruct %47 %126 %127 %128 -%130 = OpAccessChain %125 %84 %3 -OpStore %130 %129 -%132 = OpCompositeConstruct %41 %16 %16 -%133 = OpAccessChain %131 %84 %3 %3 -OpStore %133 %132 -%134 = OpLoad %6 %82 -%135 = OpCompositeConstruct %41 %17 %17 -%136 = OpAccessChain %131 %84 %3 %134 -OpStore %136 %135 -%138 = OpAccessChain %137 %84 %3 %3 %32 -OpStore %138 %18 -%139 = OpLoad %6 %82 -%140 = OpAccessChain %137 %84 %3 %3 %139 -OpStore %140 %19 -%141 = OpLoad %6 %82 -%142 = OpAccessChain %137 %84 %3 %141 %32 -OpStore %142 %20 -%143 = OpLoad %6 %82 -%144 = OpLoad %6 %82 -%145 = OpAccessChain %137 %84 %3 %143 %144 -OpStore %145 %21 +%59 = OpTypeVector %6 4 +%60 = OpTypePointer Workgroup %4 +%61 = OpConstantComposite %35 %3 %3 %3 +%62 = OpConstantComposite %36 %3 %61 %5 +%63 = OpConstantComposite %41 %22 %22 +%64 = OpConstantComposite %50 %63 %63 %63 %63 +%65 = OpConstantComposite %51 %64 %64 +%66 = OpConstantComposite %54 %22 %22 %22 %22 %22 %22 %22 %22 %22 %22 +%67 = OpConstantComposite %55 %66 %66 %66 %66 %66 +%68 = OpConstantComposite %49 %5 %5 +%70 = OpTypePointer Private %36 +%69 = OpVariable %70 Private %62 +%72 = OpTypePointer StorageBuffer %46 +%71 = OpVariable %72 StorageBuffer +%74 = OpTypeStruct %48 +%75 = OpTypePointer Uniform %74 +%73 = OpVariable %75 Uniform +%77 = OpTypeStruct %49 +%78 = OpTypePointer StorageBuffer %77 +%76 = OpVariable %78 StorageBuffer +%80 = OpTypeStruct %52 +%81 = OpTypePointer Uniform %80 +%79 = OpVariable %81 Uniform +%82 = OpVariable %60 Workgroup +%84 = OpTypePointer Function %6 +%85 = OpConstantNull %6 +%87 = OpTypePointer Function %48 +%88 = OpConstantNull %48 +%91 = OpTypeFunction %2 +%92 = OpTypePointer Uniform %48 +%97 = OpTypePointer Uniform %47 +%100 = OpTypePointer Uniform %41 +%106 = OpTypePointer Uniform %10 +%126 = OpTypePointer Function %47 +%132 = OpTypePointer Function %41 +%138 = OpTypePointer Function %10 +%148 = OpConstantNull %6 +%150 = OpTypePointer Function %52 +%151 = OpConstantNull %52 +%154 = OpTypePointer Uniform %52 +%159 = OpTypePointer Uniform %51 +%162 = OpTypePointer Uniform %50 +%185 = OpTypePointer Function %51 +%187 = OpTypePointer Function %50 +%210 = OpTypeFunction %10 %53 +%216 = OpTypeFunction %10 %55 +%223 = OpTypeFunction %2 %60 +%226 = OpConstantNull %10 +%228 = OpTypePointer Function %58 +%229 = OpConstantNull %58 +%232 = OpTypePointer Input %4 +%231 = OpVariable %232 Input +%235 = OpTypePointer Output %56 +%234 = OpVariable %235 Output +%238 = OpTypePointer StorageBuffer %49 +%245 = OpTypePointer StorageBuffer %38 +%248 = OpTypePointer StorageBuffer %44 +%251 = OpTypePointer StorageBuffer %39 +%252 = OpTypePointer StorageBuffer %10 +%255 = OpTypePointer StorageBuffer %45 +%258 = OpTypePointer StorageBuffer %37 +%259 = OpConstant %4 4 +%276 = OpVariable %235 Output +%294 = OpConstantNull %6 +%298 = OpTypePointer StorageBuffer %6 +%301 = OpConstant %4 64 +%90 = OpFunction %2 None %91 +%89 = OpLabel +%83 = OpVariable %84 Function %85 +%86 = OpVariable %87 Function %88 +%93 = OpAccessChain %92 %73 %3 +OpBranch %94 +%94 = OpLabel +OpStore %83 %8 +%95 = OpLoad %6 %83 +%96 = OpISub %6 %95 %8 +OpStore %83 %96 +%98 = OpAccessChain %97 %93 %3 +%99 = OpLoad %47 %98 +%101 = OpAccessChain %100 %93 %3 %3 +%102 = OpLoad %41 %101 +%103 = OpLoad %6 %83 +%104 = OpAccessChain %100 %93 %3 %103 +%105 = OpLoad %41 %104 +%107 = OpAccessChain %106 %93 %3 %3 %32 +%108 = OpLoad %10 %107 +%109 = OpLoad %6 %83 +%110 = OpAccessChain %106 %93 %3 %3 %109 +%111 = OpLoad %10 %110 +%112 = OpLoad %6 %83 +%113 = OpAccessChain %106 %93 %3 %112 %32 +%114 = OpLoad %10 %113 +%115 = OpLoad %6 %83 +%116 = OpLoad %6 %83 +%117 = OpAccessChain %106 %93 %3 %115 %116 +%118 = OpLoad %10 %117 +%119 = OpCompositeConstruct %41 %9 %9 +%120 = OpCompositeConstruct %41 %11 %11 +%121 = OpCompositeConstruct %41 %12 %12 +%122 = OpCompositeConstruct %47 %119 %120 %121 +%123 = OpCompositeConstruct %48 %122 +OpStore %86 %123 +%124 = OpLoad %6 %83 +%125 = OpIAdd %6 %124 %8 +OpStore %83 %125 +%127 = OpCompositeConstruct %41 %13 %13 +%128 = OpCompositeConstruct %41 %14 %14 +%129 = OpCompositeConstruct %41 %15 %15 +%130 = OpCompositeConstruct %47 %127 %128 %129 +%131 = OpAccessChain %126 %86 %3 +OpStore %131 %130 +%133 = OpCompositeConstruct %41 %16 %16 +%134 = OpAccessChain %132 %86 %3 %3 +OpStore %134 %133 +%135 = OpLoad %6 %83 +%136 = OpCompositeConstruct %41 %17 %17 +%137 = OpAccessChain %132 %86 %3 %135 +OpStore %137 %136 +%139 = OpAccessChain %138 %86 %3 %3 %32 +OpStore %139 %18 +%140 = OpLoad %6 %83 +%141 = OpAccessChain %138 %86 %3 %3 %140 +OpStore %141 %19 +%142 = OpLoad %6 %83 +%143 = OpAccessChain %138 %86 %3 %142 %32 +OpStore %143 %20 +%144 = OpLoad %6 %83 +%145 = OpLoad %6 %83 +%146 = OpAccessChain %138 %86 %3 %144 %145 +OpStore %146 %21 OpReturn OpFunctionEnd -%151 = OpFunction %2 None %89 -%150 = OpLabel -%146 = OpVariable %83 Function %8 -%147 = OpVariable %148 Function %149 -%153 = OpAccessChain %152 %78 %3 -OpBranch %154 -%154 = OpLabel -%155 = OpLoad %6 %146 -%156 = OpISub %6 %155 %8 -OpStore %146 %156 -%158 = OpAccessChain %157 %153 %3 -%159 = OpLoad %51 %158 -%161 = OpAccessChain %160 %153 %3 %3 -%162 = OpLoad %50 %161 -%163 = OpAccessChain %99 %153 %3 %3 %3 -%164 = OpLoad %41 %163 -%165 = OpLoad %6 %146 -%166 = OpAccessChain %99 %153 %3 %3 %165 -%167 = OpLoad %41 %166 -%168 = OpAccessChain %105 %153 %3 %3 %3 %32 -%169 = OpLoad %10 %168 -%170 = OpLoad %6 %146 -%171 = OpAccessChain %105 %153 %3 %3 %3 %170 -%172 = OpLoad %10 %171 -%173 = OpLoad %6 %146 -%174 = OpAccessChain %105 %153 %3 %3 %173 %32 -%175 = OpLoad %10 %174 -%176 = OpLoad %6 %146 -%177 = OpLoad %6 %146 -%178 = OpAccessChain %105 %153 %3 %3 %176 %177 -%179 = OpLoad %10 %178 -%180 = OpCompositeConstruct %52 %64 -OpStore %147 %180 -%181 = OpLoad %6 %146 -%182 = OpIAdd %6 %181 %8 -OpStore %146 %182 -%184 = OpAccessChain %183 %147 %3 -OpStore %184 %64 -%186 = OpCompositeConstruct %41 %23 %23 -%187 = OpCompositeConstruct %41 %24 %24 -%188 = OpCompositeConstruct %41 %13 %13 -%189 = OpCompositeConstruct %41 %14 %14 -%190 = OpCompositeConstruct %50 %186 %187 %188 %189 -%191 = OpAccessChain %185 %147 %3 %3 -OpStore %191 %190 -%192 = OpCompositeConstruct %41 %16 %16 -%193 = OpAccessChain %131 %147 %3 %3 %3 +%153 = OpFunction %2 None %91 +%152 = OpLabel +%147 = OpVariable %84 Function %148 +%149 = OpVariable %150 Function %151 +%155 = OpAccessChain %154 %79 %3 +OpBranch %156 +%156 = OpLabel +OpStore %147 %8 +%157 = OpLoad %6 %147 +%158 = OpISub %6 %157 %8 +OpStore %147 %158 +%160 = OpAccessChain %159 %155 %3 +%161 = OpLoad %51 %160 +%163 = OpAccessChain %162 %155 %3 %3 +%164 = OpLoad %50 %163 +%165 = OpAccessChain %100 %155 %3 %3 %3 +%166 = OpLoad %41 %165 +%167 = OpLoad %6 %147 +%168 = OpAccessChain %100 %155 %3 %3 %167 +%169 = OpLoad %41 %168 +%170 = OpAccessChain %106 %155 %3 %3 %3 %32 +%171 = OpLoad %10 %170 +%172 = OpLoad %6 %147 +%173 = OpAccessChain %106 %155 %3 %3 %3 %172 +%174 = OpLoad %10 %173 +%175 = OpLoad %6 %147 +%176 = OpAccessChain %106 %155 %3 %3 %175 %32 +%177 = OpLoad %10 %176 +%178 = OpLoad %6 %147 +%179 = OpLoad %6 %147 +%180 = OpAccessChain %106 %155 %3 %3 %178 %179 +%181 = OpLoad %10 %180 +%182 = OpCompositeConstruct %52 %65 +OpStore %149 %182 +%183 = OpLoad %6 %147 +%184 = OpIAdd %6 %183 %8 +OpStore %147 %184 +%186 = OpAccessChain %185 %149 %3 +OpStore %186 %65 +%188 = OpCompositeConstruct %41 %23 %23 +%189 = OpCompositeConstruct %41 %24 %24 +%190 = OpCompositeConstruct %41 %13 %13 +%191 = OpCompositeConstruct %41 %14 %14 +%192 = OpCompositeConstruct %50 %188 %189 %190 %191 +%193 = OpAccessChain %187 %149 %3 %3 OpStore %193 %192 -%194 = OpLoad %6 %146 -%195 = OpCompositeConstruct %41 %17 %17 -%196 = OpAccessChain %131 %147 %3 %3 %194 -OpStore %196 %195 -%197 = OpAccessChain %137 %147 %3 %3 %3 %32 -OpStore %197 %18 -%198 = OpLoad %6 %146 -%199 = OpAccessChain %137 %147 %3 %3 %3 %198 -OpStore %199 %19 -%200 = OpLoad %6 %146 -%201 = OpAccessChain %137 %147 %3 %3 %200 %32 -OpStore %201 %20 -%202 = OpLoad %6 %146 -%203 = OpLoad %6 %146 -%204 = OpAccessChain %137 %147 %3 %3 %202 %203 -OpStore %204 %21 +%194 = OpCompositeConstruct %41 %16 %16 +%195 = OpAccessChain %132 %149 %3 %3 %3 +OpStore %195 %194 +%196 = OpLoad %6 %147 +%197 = OpCompositeConstruct %41 %17 %17 +%198 = OpAccessChain %132 %149 %3 %3 %196 +OpStore %198 %197 +%199 = OpAccessChain %138 %149 %3 %3 %3 %32 +OpStore %199 %18 +%200 = OpLoad %6 %147 +%201 = OpAccessChain %138 %149 %3 %3 %3 %200 +OpStore %201 %19 +%202 = OpLoad %6 %147 +%203 = OpAccessChain %138 %149 %3 %3 %202 %32 +OpStore %203 %20 +%204 = OpLoad %6 %147 +%205 = OpLoad %6 %147 +%206 = OpAccessChain %138 %149 %3 %3 %204 %205 +OpStore %206 %21 OpReturn OpFunctionEnd -%207 = OpFunction %10 None %208 -%206 = OpFunctionParameter %53 -%205 = OpLabel -OpBranch %209 -%209 = OpLabel -%210 = OpLoad %10 %206 -OpReturnValue %210 -OpFunctionEnd -%213 = OpFunction %10 None %214 -%212 = OpFunctionParameter %55 +%209 = OpFunction %10 None %210 +%208 = OpFunctionParameter %53 +%207 = OpLabel +OpBranch %211 %211 = OpLabel -OpBranch %215 -%215 = OpLabel -%216 = OpCompositeExtract %54 %212 4 -%217 = OpCompositeExtract %10 %216 9 -OpReturnValue %217 +%212 = OpLoad %10 %208 +OpReturnValue %212 OpFunctionEnd -%220 = OpFunction %2 None %221 -%219 = OpFunctionParameter %59 -%218 = OpLabel -OpBranch %222 -%222 = OpLabel -OpStore %219 %34 +%215 = OpFunction %10 None %216 +%214 = OpFunctionParameter %55 +%213 = OpLabel +OpBranch %217 +%217 = OpLabel +%218 = OpCompositeExtract %54 %214 4 +%219 = OpCompositeExtract %10 %218 9 +OpReturnValue %219 +OpFunctionEnd +%222 = OpFunction %2 None %223 +%221 = OpFunctionParameter %60 +%220 = OpLabel +OpBranch %224 +%224 = OpLabel +OpStore %221 %34 OpReturn OpFunctionEnd -%233 = OpFunction %2 None %89 -%227 = OpLabel -%223 = OpVariable %53 Function %22 -%224 = OpVariable %225 Function %226 -%230 = OpLoad %4 %228 -%234 = OpAccessChain %90 %72 %3 -%235 = OpAccessChain %92 %75 %3 -%236 = OpAccessChain %152 %78 %3 -OpBranch %237 -%237 = OpLabel -%238 = OpLoad %10 %223 -OpStore %223 %9 -%239 = OpFunctionCall %2 %88 -%240 = OpFunctionCall %2 %151 -%242 = OpAccessChain %241 %70 %3 -%243 = OpLoad %38 %242 -%245 = OpAccessChain %244 %70 %29 -%246 = OpLoad %44 %245 -%249 = OpAccessChain %248 %70 %3 %29 %3 -%250 = OpLoad %10 %249 -%252 = OpArrayLength %4 %70 4 -%253 = OpISub %4 %252 %30 -%256 = OpAccessChain %57 %70 %255 %253 %3 -%257 = OpLoad %6 %256 -%258 = OpLoad %49 %235 -%259 = OpFunctionCall %10 %207 %223 -%260 = OpConvertFToS %6 %250 -%261 = OpCompositeConstruct %58 %257 %260 %31 %27 %26 -OpStore %224 %261 -%262 = OpIAdd %4 %230 %32 -%263 = OpAccessChain %83 %224 %262 -OpStore %263 %33 -%264 = OpAccessChain %83 %224 %230 -%265 = OpLoad %6 %264 -%266 = OpFunctionCall %10 %213 %66 -%268 = OpCompositeConstruct %267 %265 %265 %265 %265 -%269 = OpConvertSToF %56 %268 -%270 = OpMatrixTimesVector %39 %243 %269 -%271 = OpCompositeConstruct %56 %270 %11 -OpStore %231 %271 +%236 = OpFunction %2 None %91 +%230 = OpLabel +%225 = OpVariable %53 Function %226 +%227 = OpVariable %228 Function %229 +%233 = OpLoad %4 %231 +%237 = OpAccessChain %92 %73 %3 +%239 = OpAccessChain %238 %76 %3 +%240 = OpAccessChain %154 %79 %3 +OpBranch %241 +%241 = OpLabel +OpStore %225 %22 +%242 = OpLoad %10 %225 +OpStore %225 %9 +%243 = OpFunctionCall %2 %90 +%244 = OpFunctionCall %2 %153 +%246 = OpAccessChain %245 %71 %3 +%247 = OpLoad %38 %246 +%249 = OpAccessChain %248 %71 %29 +%250 = OpLoad %44 %249 +%253 = OpAccessChain %252 %71 %3 %29 %3 +%254 = OpLoad %10 %253 +%256 = OpArrayLength %4 %71 4 +%257 = OpISub %4 %256 %30 +%260 = OpAccessChain %57 %71 %259 %257 %3 +%261 = OpLoad %6 %260 +%262 = OpLoad %49 %239 +%263 = OpFunctionCall %10 %209 %225 +%264 = OpConvertFToS %6 %254 +%265 = OpCompositeConstruct %58 %261 %264 %31 %27 %26 +OpStore %227 %265 +%266 = OpIAdd %4 %233 %32 +%267 = OpAccessChain %84 %227 %266 +OpStore %267 %33 +%268 = OpAccessChain %84 %227 %233 +%269 = OpLoad %6 %268 +%270 = OpFunctionCall %10 %215 %67 +%271 = OpCompositeConstruct %59 %269 %269 %269 %269 +%272 = OpConvertSToF %56 %271 +%273 = OpMatrixTimesVector %39 %247 %272 +%274 = OpCompositeConstruct %56 %273 %11 +OpStore %234 %274 OpReturn OpFunctionEnd -%274 = OpFunction %2 None %89 -%272 = OpLabel -%275 = OpAccessChain %92 %75 %3 -OpBranch %276 -%276 = OpLabel -%277 = OpAccessChain %248 %70 %3 %32 %30 -OpStore %277 %9 -%278 = OpCompositeConstruct %39 %22 %22 %22 -%279 = OpCompositeConstruct %39 %9 %9 %9 -%280 = OpCompositeConstruct %39 %11 %11 %11 -%281 = OpCompositeConstruct %39 %12 %12 %12 -%282 = OpCompositeConstruct %38 %278 %279 %280 %281 -%283 = OpAccessChain %241 %70 %3 -OpStore %283 %282 -%284 = OpCompositeConstruct %43 %3 %3 -%285 = OpCompositeConstruct %43 %32 %32 -%286 = OpCompositeConstruct %44 %284 %285 -%287 = OpAccessChain %244 %70 %29 -OpStore %287 %286 -%288 = OpAccessChain %57 %70 %255 %32 %3 -OpStore %288 %8 -OpStore %275 %67 -%289 = OpCompositeConstruct %56 %22 %22 %22 %22 -OpStore %273 %289 +%277 = OpFunction %2 None %91 +%275 = OpLabel +%278 = OpAccessChain %238 %76 %3 +OpBranch %279 +%279 = OpLabel +%280 = OpAccessChain %252 %71 %3 %32 %30 +OpStore %280 %9 +%281 = OpCompositeConstruct %39 %22 %22 %22 +%282 = OpCompositeConstruct %39 %9 %9 %9 +%283 = OpCompositeConstruct %39 %11 %11 %11 +%284 = OpCompositeConstruct %39 %12 %12 %12 +%285 = OpCompositeConstruct %38 %281 %282 %283 %284 +%286 = OpAccessChain %245 %71 %3 +OpStore %286 %285 +%287 = OpCompositeConstruct %43 %3 %3 +%288 = OpCompositeConstruct %43 %32 %32 +%289 = OpCompositeConstruct %44 %287 %288 +%290 = OpAccessChain %248 %71 %29 +OpStore %290 %289 +%291 = OpAccessChain %57 %71 %259 %32 %3 +OpStore %291 %8 +OpStore %278 %68 +%292 = OpCompositeConstruct %56 %22 %22 %22 %22 +OpStore %276 %292 OpReturn OpFunctionEnd -%293 = OpFunction %2 None %89 -%292 = OpLabel -%290 = OpVariable %83 Function %291 -OpBranch %294 -%294 = OpLabel -%296 = OpAccessChain %295 %70 %30 -%297 = OpAtomicLoad %6 %296 %8 %298 -%300 = OpAccessChain %295 %70 %30 -%299 = OpAtomicIAdd %6 %300 %8 %298 %26 -OpStore %290 %299 -%302 = OpAccessChain %295 %70 %30 -%301 = OpAtomicISub %6 %302 %8 %298 %26 -OpStore %290 %301 -%304 = OpAccessChain %295 %70 %30 -%303 = OpAtomicAnd %6 %304 %8 %298 %26 -OpStore %290 %303 -%306 = OpAccessChain %295 %70 %30 -%305 = OpAtomicOr %6 %306 %8 %298 %26 -OpStore %290 %305 -%308 = OpAccessChain %295 %70 %30 -%307 = OpAtomicXor %6 %308 %8 %298 %26 -OpStore %290 %307 -%310 = OpAccessChain %295 %70 %30 -%309 = OpAtomicSMin %6 %310 %8 %298 %26 -OpStore %290 %309 -%312 = OpAccessChain %295 %70 %30 -%311 = OpAtomicSMax %6 %312 %8 %298 %26 -OpStore %290 %311 -%314 = OpAccessChain %295 %70 %30 -%313 = OpAtomicExchange %6 %314 %8 %298 %26 -OpStore %290 %313 -%315 = OpAccessChain %295 %70 %30 -OpAtomicStore %315 %8 %298 %297 +%296 = OpFunction %2 None %91 +%295 = OpLabel +%293 = OpVariable %84 Function %294 +OpBranch %297 +%297 = OpLabel +%299 = OpAccessChain %298 %71 %30 +%300 = OpAtomicLoad %6 %299 %8 %301 +%303 = OpAccessChain %298 %71 %30 +%302 = OpAtomicIAdd %6 %303 %8 %301 %26 +OpStore %293 %302 +%305 = OpAccessChain %298 %71 %30 +%304 = OpAtomicISub %6 %305 %8 %301 %26 +OpStore %293 %304 +%307 = OpAccessChain %298 %71 %30 +%306 = OpAtomicAnd %6 %307 %8 %301 %26 +OpStore %293 %306 +%309 = OpAccessChain %298 %71 %30 +%308 = OpAtomicOr %6 %309 %8 %301 %26 +OpStore %293 %308 +%311 = OpAccessChain %298 %71 %30 +%310 = OpAtomicXor %6 %311 %8 %301 %26 +OpStore %293 %310 +%313 = OpAccessChain %298 %71 %30 +%312 = OpAtomicSMin %6 %313 %8 %301 %26 +OpStore %293 %312 +%315 = OpAccessChain %298 %71 %30 +%314 = OpAtomicSMax %6 %315 %8 %301 %26 +OpStore %293 %314 +%317 = OpAccessChain %298 %71 %30 +%316 = OpAtomicExchange %6 %317 %8 %301 %26 +OpStore %293 %316 +%318 = OpAccessChain %298 %71 %30 +OpAtomicStore %318 %8 %301 %300 OpReturn OpFunctionEnd -%317 = OpFunction %2 None %89 -%316 = OpLabel -OpBranch %318 -%318 = OpLabel -%319 = OpFunctionCall %2 %220 %81 +%320 = OpFunction %2 None %91 +%319 = OpLabel +OpBranch %321 +%321 = OpLabel +%322 = OpFunctionCall %2 %222 %82 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/tests/out/spv/atomicCompareExchange.spvasm index 9587f9aaa..5af859324 100644 --- a/tests/out/spv/atomicCompareExchange.spvasm +++ b/tests/out/spv/atomicCompareExchange.spvasm @@ -1,15 +1,15 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 116 +; Bound: 126 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %31 "test_atomic_compare_exchange_i32" -OpEntryPoint GLCompute %79 "test_atomic_compare_exchange_u32" -OpExecutionMode %31 LocalSize 1 1 1 -OpExecutionMode %79 LocalSize 1 1 1 +OpEntryPoint GLCompute %32 "test_atomic_compare_exchange_i32" +OpEntryPoint GLCompute %84 "test_atomic_compare_exchange_u32" +OpExecutionMode %32 LocalSize 1 1 1 +OpExecutionMode %84 LocalSize 1 1 1 OpDecorate %12 ArrayStride 4 OpDecorate %13 ArrayStride 4 OpMemberDecorate %14 0 Offset 0 @@ -28,16 +28,16 @@ OpMemberDecorate %20 0 Offset 0 %4 = OpTypeInt 32 0 %3 = OpConstant %4 128 %5 = OpConstant %4 0 -%6 = OpConstant %4 1 -%8 = OpTypeBool -%7 = OpConstantFalse %8 -%10 = OpTypeFloat 32 -%9 = OpConstant %10 1.0 +%7 = OpTypeBool +%6 = OpConstantFalse %7 +%9 = OpTypeFloat 32 +%8 = OpConstant %9 1.0 +%10 = OpConstant %4 1 %11 = OpTypeInt 32 1 %12 = OpTypeArray %11 %3 %13 = OpTypeArray %4 %3 -%14 = OpTypeStruct %11 %8 -%15 = OpTypeStruct %4 %8 +%14 = OpTypeStruct %11 %7 +%15 = OpTypeStruct %4 %7 %17 = OpTypeStruct %12 %18 = OpTypePointer StorageBuffer %17 %16 = OpVariable %18 StorageBuffer @@ -45,144 +45,164 @@ OpMemberDecorate %20 0 Offset 0 %21 = OpTypePointer StorageBuffer %20 %19 = OpVariable %21 StorageBuffer %23 = OpTypePointer Function %4 -%25 = OpTypePointer Function %11 -%26 = OpConstantNull %11 -%28 = OpTypePointer Function %8 -%29 = OpConstantNull %8 -%32 = OpTypeFunction %2 -%33 = OpTypePointer StorageBuffer %12 -%35 = OpTypePointer StorageBuffer %13 -%46 = OpTypePointer StorageBuffer %11 -%49 = OpConstant %11 1 -%50 = OpConstant %4 64 -%75 = OpConstantNull %4 -%77 = OpConstantNull %8 -%91 = OpTypePointer StorageBuffer %4 -%31 = OpFunction %2 None %32 -%30 = OpLabel -%22 = OpVariable %23 Function %5 -%24 = OpVariable %25 Function %26 -%27 = OpVariable %28 Function %29 -%34 = OpAccessChain %33 %16 %5 +%24 = OpConstantNull %4 +%26 = OpTypePointer Function %11 +%27 = OpConstantNull %11 +%29 = OpTypePointer Function %7 +%30 = OpConstantNull %7 +%33 = OpTypeFunction %2 +%34 = OpTypePointer StorageBuffer %12 +%48 = OpTypePointer StorageBuffer %11 +%51 = OpConstant %11 1 +%52 = OpConstant %4 64 +%78 = OpConstantNull %4 +%80 = OpConstantNull %4 +%82 = OpConstantNull %7 +%85 = OpTypePointer StorageBuffer %13 +%99 = OpTypePointer StorageBuffer %4 +%32 = OpFunction %2 None %33 +%31 = OpLabel +%22 = OpVariable %23 Function %24 +%25 = OpVariable %26 Function %27 +%28 = OpVariable %29 Function %30 +%35 = OpAccessChain %34 %16 %5 OpBranch %36 %36 = OpLabel +OpStore %22 %5 OpBranch %37 %37 = OpLabel OpLoopMerge %38 %40 None OpBranch %39 %39 = OpLabel %41 = OpLoad %4 %22 -%42 = OpULessThan %8 %41 %3 +%42 = OpULessThan %7 %41 %3 OpSelectionMerge %43 None OpBranchConditional %42 %43 %44 %44 = OpLabel OpBranch %38 %43 = OpLabel -%45 = OpLoad %4 %22 -%47 = OpAccessChain %46 %34 %45 -%48 = OpAtomicLoad %11 %47 %49 %50 -OpStore %24 %48 -OpStore %27 %7 -OpBranch %51 -%51 = OpLabel -OpLoopMerge %52 %54 None +OpBranch %45 +%45 = OpLabel +%47 = OpLoad %4 %22 +%49 = OpAccessChain %48 %35 %47 +%50 = OpAtomicLoad %11 %49 %51 %52 +OpStore %25 %50 +OpStore %28 %6 OpBranch %53 %53 = OpLabel -%55 = OpLoad %8 %27 -%56 = OpLogicalNot %8 %55 -OpSelectionMerge %57 None -OpBranchConditional %56 %57 %58 -%58 = OpLabel -OpBranch %52 -%57 = OpLabel -%59 = OpLoad %11 %24 -%60 = OpBitcast %10 %59 -%61 = OpFAdd %10 %60 %9 -%62 = OpBitcast %11 %61 -%63 = OpLoad %4 %22 -%64 = OpLoad %11 %24 -%66 = OpAccessChain %46 %34 %63 -%67 = OpAtomicCompareExchange %11 %66 %49 %50 %50 %62 %64 -%68 = OpIEqual %8 %67 %64 -%65 = OpCompositeConstruct %14 %67 %68 -%69 = OpCompositeExtract %11 %65 0 -OpStore %24 %69 -%70 = OpCompositeExtract %8 %65 1 -OpStore %27 %70 +OpLoopMerge %54 %56 None +OpBranch %55 +%55 = OpLabel +%57 = OpLoad %7 %28 +%58 = OpLogicalNot %7 %57 +OpSelectionMerge %59 None +OpBranchConditional %58 %59 %60 +%60 = OpLabel OpBranch %54 +%59 = OpLabel +OpBranch %61 +%61 = OpLabel +%63 = OpLoad %11 %25 +%64 = OpBitcast %9 %63 +%65 = OpFAdd %9 %64 %8 +%66 = OpBitcast %11 %65 +%67 = OpLoad %4 %22 +%68 = OpLoad %11 %25 +%70 = OpAccessChain %48 %35 %67 +%71 = OpAtomicCompareExchange %11 %70 %51 %52 %52 %66 %68 +%72 = OpIEqual %7 %71 %68 +%69 = OpCompositeConstruct %14 %71 %72 +%73 = OpCompositeExtract %11 %69 0 +OpStore %25 %73 +%74 = OpCompositeExtract %7 %69 1 +OpStore %28 %74 +OpBranch %62 +%62 = OpLabel +OpBranch %56 +%56 = OpLabel +OpBranch %53 %54 = OpLabel -OpBranch %51 -%52 = OpLabel +OpBranch %46 +%46 = OpLabel OpBranch %40 %40 = OpLabel -%71 = OpLoad %4 %22 -%72 = OpIAdd %4 %71 %6 -OpStore %22 %72 +%75 = OpLoad %4 %22 +%76 = OpIAdd %4 %75 %10 +OpStore %22 %76 OpBranch %37 %38 = OpLabel OpReturn OpFunctionEnd -%79 = OpFunction %2 None %32 -%78 = OpLabel -%73 = OpVariable %23 Function %5 -%74 = OpVariable %23 Function %75 -%76 = OpVariable %28 Function %77 -%80 = OpAccessChain %35 %19 %5 -OpBranch %81 -%81 = OpLabel -OpBranch %82 -%82 = OpLabel -OpLoopMerge %83 %85 None -OpBranch %84 -%84 = OpLabel -%86 = OpLoad %4 %73 -%87 = OpULessThan %8 %86 %3 -OpSelectionMerge %88 None -OpBranchConditional %87 %88 %89 -%89 = OpLabel -OpBranch %83 +%84 = OpFunction %2 None %33 +%83 = OpLabel +%77 = OpVariable %23 Function %78 +%79 = OpVariable %23 Function %80 +%81 = OpVariable %29 Function %82 +%86 = OpAccessChain %85 %19 %5 +OpBranch %87 +%87 = OpLabel +OpStore %77 %5 +OpBranch %88 %88 = OpLabel -%90 = OpLoad %4 %73 -%92 = OpAccessChain %91 %80 %90 -%93 = OpAtomicLoad %4 %92 %49 %50 -OpStore %74 %93 -OpStore %76 %7 -OpBranch %94 +OpLoopMerge %89 %91 None +OpBranch %90 +%90 = OpLabel +%92 = OpLoad %4 %77 +%93 = OpULessThan %7 %92 %3 +OpSelectionMerge %94 None +OpBranchConditional %93 %94 %95 +%95 = OpLabel +OpBranch %89 %94 = OpLabel -OpLoopMerge %95 %97 None OpBranch %96 %96 = OpLabel -%98 = OpLoad %8 %76 -%99 = OpLogicalNot %8 %98 -OpSelectionMerge %100 None -OpBranchConditional %99 %100 %101 -%101 = OpLabel -OpBranch %95 -%100 = OpLabel -%102 = OpLoad %4 %74 -%103 = OpBitcast %10 %102 -%104 = OpFAdd %10 %103 %9 -%105 = OpBitcast %4 %104 -%106 = OpLoad %4 %73 -%107 = OpLoad %4 %74 -%109 = OpAccessChain %91 %80 %106 -%110 = OpAtomicCompareExchange %4 %109 %49 %50 %50 %105 %107 -%111 = OpIEqual %8 %110 %107 -%108 = OpCompositeConstruct %15 %110 %111 -%112 = OpCompositeExtract %4 %108 0 -OpStore %74 %112 -%113 = OpCompositeExtract %8 %108 1 -OpStore %76 %113 +%98 = OpLoad %4 %77 +%100 = OpAccessChain %99 %86 %98 +%101 = OpAtomicLoad %4 %100 %51 %52 +OpStore %79 %101 +OpStore %81 %6 +OpBranch %102 +%102 = OpLabel +OpLoopMerge %103 %105 None +OpBranch %104 +%104 = OpLabel +%106 = OpLoad %7 %81 +%107 = OpLogicalNot %7 %106 +OpSelectionMerge %108 None +OpBranchConditional %107 %108 %109 +%109 = OpLabel +OpBranch %103 +%108 = OpLabel +OpBranch %110 +%110 = OpLabel +%112 = OpLoad %4 %79 +%113 = OpBitcast %9 %112 +%114 = OpFAdd %9 %113 %8 +%115 = OpBitcast %4 %114 +%116 = OpLoad %4 %77 +%117 = OpLoad %4 %79 +%119 = OpAccessChain %99 %86 %116 +%120 = OpAtomicCompareExchange %4 %119 %51 %52 %52 %115 %117 +%121 = OpIEqual %7 %120 %117 +%118 = OpCompositeConstruct %15 %120 %121 +%122 = OpCompositeExtract %4 %118 0 +OpStore %79 %122 +%123 = OpCompositeExtract %7 %118 1 +OpStore %81 %123 +OpBranch %111 +%111 = OpLabel +OpBranch %105 +%105 = OpLabel +OpBranch %102 +%103 = OpLabel OpBranch %97 %97 = OpLabel -OpBranch %94 -%95 = OpLabel -OpBranch %85 -%85 = OpLabel -%114 = OpLoad %4 %73 -%115 = OpIAdd %4 %114 %6 -OpStore %73 %115 -OpBranch %82 -%83 = OpLabel +OpBranch %91 +%91 = OpLabel +%124 = OpLoad %4 %77 +%125 = OpIAdd %4 %124 %10 +OpStore %77 %125 +OpBranch %88 +%89 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index a420eba46..4c7ad3d22 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -1,62 +1,62 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 431 +; Bound: 433 OpCapability Shader OpCapability ImageQuery OpCapability ShaderNonUniform OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %65 "main" %60 %63 -OpExecutionMode %65 OriginUpperLeft +OpEntryPoint Fragment %68 "main" %63 %66 +OpExecutionMode %68 OriginUpperLeft OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %24 0 Offset 0 -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 0 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 1 -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 2 -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 3 -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 4 -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 5 -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 6 -OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 7 -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 8 -OpDecorate %46 Block -OpMemberDecorate %46 0 Offset 0 -OpDecorate %60 Location 0 -OpDecorate %60 Flat +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 0 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 1 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 2 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 3 +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 4 +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 5 +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 6 +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 7 +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 8 +OpDecorate %47 Block +OpMemberDecorate %47 0 Offset 0 OpDecorate %63 Location 0 -OpDecorate %93 NonUniform -OpDecorate %116 NonUniform -OpDecorate %118 NonUniform -OpDecorate %143 NonUniform -OpDecorate %145 NonUniform -OpDecorate %183 NonUniform -OpDecorate %212 NonUniform -OpDecorate %228 NonUniform -OpDecorate %244 NonUniform -OpDecorate %265 NonUniform -OpDecorate %267 NonUniform -OpDecorate %289 NonUniform -OpDecorate %291 NonUniform -OpDecorate %313 NonUniform -OpDecorate %315 NonUniform -OpDecorate %337 NonUniform -OpDecorate %339 NonUniform -OpDecorate %361 NonUniform -OpDecorate %363 NonUniform -OpDecorate %385 NonUniform -OpDecorate %387 NonUniform -OpDecorate %409 NonUniform +OpDecorate %63 Flat +OpDecorate %66 Location 0 +OpDecorate %94 NonUniform +OpDecorate %117 NonUniform +OpDecorate %119 NonUniform +OpDecorate %144 NonUniform +OpDecorate %146 NonUniform +OpDecorate %184 NonUniform +OpDecorate %213 NonUniform +OpDecorate %229 NonUniform +OpDecorate %245 NonUniform +OpDecorate %266 NonUniform +OpDecorate %268 NonUniform +OpDecorate %290 NonUniform +OpDecorate %292 NonUniform +OpDecorate %314 NonUniform +OpDecorate %316 NonUniform +OpDecorate %338 NonUniform +OpDecorate %340 NonUniform +OpDecorate %362 NonUniform +OpDecorate %364 NonUniform +OpDecorate %386 NonUniform +OpDecorate %388 NonUniform +OpDecorate %411 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 5 @@ -82,476 +82,480 @@ OpDecorate %409 NonUniform %24 = OpTypeStruct %8 %25 = OpTypeVector %7 4 %26 = OpTypeVector %4 2 -%30 = OpConstant %8 10 -%29 = OpTypeArray %10 %30 -%28 = OpTypePointer UniformConstant %29 -%27 = OpVariable %28 UniformConstant -%32 = OpTypePointer UniformConstant %12 -%31 = OpVariable %32 UniformConstant -%34 = OpTypePointer UniformConstant %14 -%33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %16 -%35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %18 -%37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %20 -%39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %22 -%41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %23 -%43 = OpVariable %44 UniformConstant -%46 = OpTypeStruct %9 -%47 = OpTypePointer Uniform %46 -%45 = OpVariable %47 Uniform -%49 = OpTypePointer Function %4 -%51 = OpTypePointer Function %26 -%52 = OpConstantNull %26 -%54 = OpTypePointer Function %7 -%56 = OpTypePointer Function %25 -%57 = OpConstantNull %25 -%61 = OpTypePointer Input %8 -%60 = OpVariable %61 Input -%64 = OpTypePointer Output %25 -%63 = OpVariable %64 Output -%66 = OpTypeFunction %2 -%67 = OpTypePointer Uniform %9 -%68 = OpConstant %8 0 -%71 = OpTypePointer Uniform %8 -%77 = OpTypeVector %7 2 -%81 = OpTypePointer UniformConstant %10 -%99 = OpTypePointer UniformConstant %21 -%102 = OpTypeSampledImage %10 -%123 = OpTypePointer UniformConstant %17 -%126 = OpTypePointer UniformConstant %21 -%129 = OpTypeSampledImage %17 -%152 = OpTypeBool -%153 = OpConstantNull %25 -%159 = OpTypeVector %152 2 -%169 = OpConstantNull %25 -%184 = OpConstantNull %25 -%197 = OpTypePointer UniformConstant %13 -%200 = OpTypeVector %4 3 -%232 = OpTypePointer UniformConstant %15 -%391 = OpTypePointer UniformConstant %19 -%65 = OpFunction %2 None %66 -%58 = OpLabel -%50 = OpVariable %51 Function %52 +%27 = OpTypeVector %7 2 +%31 = OpConstant %8 10 +%30 = OpTypeArray %10 %31 +%29 = OpTypePointer UniformConstant %30 +%28 = OpVariable %29 UniformConstant +%33 = OpTypePointer UniformConstant %12 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer UniformConstant %14 +%34 = OpVariable %35 UniformConstant +%37 = OpTypePointer UniformConstant %16 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %18 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %20 +%40 = OpVariable %41 UniformConstant +%43 = OpTypePointer UniformConstant %22 +%42 = OpVariable %43 UniformConstant +%45 = OpTypePointer UniformConstant %23 +%44 = OpVariable %45 UniformConstant +%47 = OpTypeStruct %9 +%48 = OpTypePointer Uniform %47 +%46 = OpVariable %48 Uniform +%50 = OpTypePointer Function %4 +%51 = OpConstantNull %4 +%53 = OpTypePointer Function %26 +%54 = OpConstantNull %26 +%56 = OpTypePointer Function %7 +%57 = OpConstantNull %7 +%59 = OpTypePointer Function %25 +%60 = OpConstantNull %25 +%64 = OpTypePointer Input %8 +%63 = OpVariable %64 Input +%67 = OpTypePointer Output %25 +%66 = OpVariable %67 Output +%69 = OpTypeFunction %2 +%70 = OpTypePointer Uniform %9 +%71 = OpConstant %8 0 +%74 = OpTypePointer Uniform %8 +%82 = OpTypePointer UniformConstant %10 +%100 = OpTypePointer UniformConstant %21 +%103 = OpTypeSampledImage %10 +%124 = OpTypePointer UniformConstant %17 +%127 = OpTypePointer UniformConstant %21 +%130 = OpTypeSampledImage %17 +%153 = OpTypeBool +%154 = OpConstantNull %25 +%160 = OpTypeVector %153 2 +%170 = OpConstantNull %25 +%185 = OpConstantNull %25 +%198 = OpTypePointer UniformConstant %13 +%201 = OpTypeVector %4 3 +%233 = OpTypePointer UniformConstant %15 +%393 = OpTypePointer UniformConstant %19 +%68 = OpFunction %2 None %69 +%61 = OpLabel +%52 = OpVariable %53 Function %54 +%58 = OpVariable %59 Function %60 +%49 = OpVariable %50 Function %51 %55 = OpVariable %56 Function %57 -%48 = OpVariable %49 Function %5 -%53 = OpVariable %54 Function %6 -%62 = OpLoad %8 %60 -%59 = OpCompositeConstruct %24 %62 -%69 = OpAccessChain %67 %45 %68 -OpBranch %70 -%70 = OpLabel -%72 = OpAccessChain %71 %69 %68 -%73 = OpLoad %8 %72 -%74 = OpCompositeExtract %8 %59 0 -%75 = OpCompositeConstruct %26 %5 %5 -OpStore %50 %75 -%76 = OpCompositeConstruct %25 %6 %6 %6 %6 -OpStore %55 %76 -%78 = OpCompositeConstruct %77 %6 %6 -%79 = OpCompositeConstruct %26 %5 %5 -%80 = OpLoad %26 %50 -%82 = OpAccessChain %81 %27 %68 -%83 = OpLoad %10 %82 -%84 = OpImageQuerySizeLod %26 %83 %68 -%85 = OpIAdd %26 %80 %84 -OpStore %50 %85 -%86 = OpLoad %26 %50 -%87 = OpAccessChain %81 %27 %73 -%88 = OpLoad %10 %87 -%89 = OpImageQuerySizeLod %26 %88 %68 -%90 = OpIAdd %26 %86 %89 -OpStore %50 %90 -%91 = OpLoad %26 %50 -%92 = OpAccessChain %81 %27 %74 -%93 = OpLoad %10 %92 -%94 = OpImageQuerySizeLod %26 %93 %68 -%95 = OpIAdd %26 %91 %94 -OpStore %50 %95 -%96 = OpLoad %25 %55 -%97 = OpAccessChain %81 %31 %68 -%98 = OpLoad %10 %97 -%100 = OpAccessChain %99 %41 %68 -%101 = OpLoad %21 %100 -%103 = OpSampledImage %102 %98 %101 -%104 = OpImageGather %25 %103 %78 %68 -%105 = OpFAdd %25 %96 %104 -OpStore %55 %105 -%106 = OpLoad %25 %55 -%107 = OpAccessChain %81 %31 %73 -%108 = OpLoad %10 %107 -%109 = OpAccessChain %99 %41 %73 -%110 = OpLoad %21 %109 -%111 = OpSampledImage %102 %108 %110 -%112 = OpImageGather %25 %111 %78 %68 -%113 = OpFAdd %25 %106 %112 -OpStore %55 %113 -%114 = OpLoad %25 %55 -%115 = OpAccessChain %81 %31 %74 -%116 = OpLoad %10 %115 -%117 = OpAccessChain %99 %41 %74 -%118 = OpLoad %21 %117 -%119 = OpSampledImage %102 %116 %118 -%120 = OpImageGather %25 %119 %78 %68 -%121 = OpFAdd %25 %114 %120 -OpStore %55 %121 -%122 = OpLoad %25 %55 -%124 = OpAccessChain %123 %37 %68 -%125 = OpLoad %17 %124 -%127 = OpAccessChain %126 %43 %68 -%128 = OpLoad %21 %127 -%130 = OpSampledImage %129 %125 %128 -%131 = OpImageDrefGather %25 %130 %78 %6 -%132 = OpFAdd %25 %122 %131 -OpStore %55 %132 -%133 = OpLoad %25 %55 -%134 = OpAccessChain %123 %37 %73 -%135 = OpLoad %17 %134 -%136 = OpAccessChain %126 %43 %73 -%137 = OpLoad %21 %136 -%138 = OpSampledImage %129 %135 %137 -%139 = OpImageDrefGather %25 %138 %78 %6 -%140 = OpFAdd %25 %133 %139 -OpStore %55 %140 -%141 = OpLoad %25 %55 -%142 = OpAccessChain %123 %37 %74 -%143 = OpLoad %17 %142 -%144 = OpAccessChain %126 %43 %74 -%145 = OpLoad %21 %144 -%146 = OpSampledImage %129 %143 %145 -%147 = OpImageDrefGather %25 %146 %78 %6 -%148 = OpFAdd %25 %141 %147 -OpStore %55 %148 -%149 = OpLoad %25 %55 -%150 = OpAccessChain %81 %27 %68 -%151 = OpLoad %10 %150 -%154 = OpImageQueryLevels %4 %151 -%155 = OpULessThan %152 %5 %154 -OpSelectionMerge %156 None -OpBranchConditional %155 %157 %156 +%65 = OpLoad %8 %63 +%62 = OpCompositeConstruct %24 %65 +%72 = OpAccessChain %70 %46 %71 +OpBranch %73 +%73 = OpLabel +%75 = OpAccessChain %74 %72 %71 +%76 = OpLoad %8 %75 +%77 = OpCompositeExtract %8 %62 0 +OpStore %49 %5 +%78 = OpCompositeConstruct %26 %5 %5 +OpStore %52 %78 +OpStore %55 %6 +%79 = OpCompositeConstruct %25 %6 %6 %6 %6 +OpStore %58 %79 +%80 = OpCompositeConstruct %27 %6 %6 +%81 = OpCompositeConstruct %26 %5 %5 +%83 = OpAccessChain %82 %28 %71 +%84 = OpLoad %10 %83 +%85 = OpImageQuerySizeLod %26 %84 %71 +%86 = OpLoad %26 %52 +%87 = OpIAdd %26 %86 %85 +OpStore %52 %87 +%88 = OpAccessChain %82 %28 %76 +%89 = OpLoad %10 %88 +%90 = OpImageQuerySizeLod %26 %89 %71 +%91 = OpLoad %26 %52 +%92 = OpIAdd %26 %91 %90 +OpStore %52 %92 +%93 = OpAccessChain %82 %28 %77 +%94 = OpLoad %10 %93 +%95 = OpImageQuerySizeLod %26 %94 %71 +%96 = OpLoad %26 %52 +%97 = OpIAdd %26 %96 %95 +OpStore %52 %97 +%98 = OpAccessChain %82 %32 %71 +%99 = OpLoad %10 %98 +%101 = OpAccessChain %100 %42 %71 +%102 = OpLoad %21 %101 +%104 = OpSampledImage %103 %99 %102 +%105 = OpImageGather %25 %104 %80 %71 +%106 = OpLoad %25 %58 +%107 = OpFAdd %25 %106 %105 +OpStore %58 %107 +%108 = OpAccessChain %82 %32 %76 +%109 = OpLoad %10 %108 +%110 = OpAccessChain %100 %42 %76 +%111 = OpLoad %21 %110 +%112 = OpSampledImage %103 %109 %111 +%113 = OpImageGather %25 %112 %80 %71 +%114 = OpLoad %25 %58 +%115 = OpFAdd %25 %114 %113 +OpStore %58 %115 +%116 = OpAccessChain %82 %32 %77 +%117 = OpLoad %10 %116 +%118 = OpAccessChain %100 %42 %77 +%119 = OpLoad %21 %118 +%120 = OpSampledImage %103 %117 %119 +%121 = OpImageGather %25 %120 %80 %71 +%122 = OpLoad %25 %58 +%123 = OpFAdd %25 %122 %121 +OpStore %58 %123 +%125 = OpAccessChain %124 %38 %71 +%126 = OpLoad %17 %125 +%128 = OpAccessChain %127 %44 %71 +%129 = OpLoad %21 %128 +%131 = OpSampledImage %130 %126 %129 +%132 = OpImageDrefGather %25 %131 %80 %6 +%133 = OpLoad %25 %58 +%134 = OpFAdd %25 %133 %132 +OpStore %58 %134 +%135 = OpAccessChain %124 %38 %76 +%136 = OpLoad %17 %135 +%137 = OpAccessChain %127 %44 %76 +%138 = OpLoad %21 %137 +%139 = OpSampledImage %130 %136 %138 +%140 = OpImageDrefGather %25 %139 %80 %6 +%141 = OpLoad %25 %58 +%142 = OpFAdd %25 %141 %140 +OpStore %58 %142 +%143 = OpAccessChain %124 %38 %77 +%144 = OpLoad %17 %143 +%145 = OpAccessChain %127 %44 %77 +%146 = OpLoad %21 %145 +%147 = OpSampledImage %130 %144 %146 +%148 = OpImageDrefGather %25 %147 %80 %6 +%149 = OpLoad %25 %58 +%150 = OpFAdd %25 %149 %148 +OpStore %58 %150 +%151 = OpAccessChain %82 %28 %71 +%152 = OpLoad %10 %151 +%155 = OpImageQueryLevels %4 %152 +%156 = OpULessThan %153 %5 %155 +OpSelectionMerge %157 None +OpBranchConditional %156 %158 %157 +%158 = OpLabel +%159 = OpImageQuerySizeLod %26 %152 %5 +%161 = OpULessThan %160 %81 %159 +%162 = OpAll %153 %161 +OpBranchConditional %162 %163 %157 +%163 = OpLabel +%164 = OpImageFetch %25 %152 %81 Lod %5 +OpBranch %157 %157 = OpLabel -%158 = OpImageQuerySizeLod %26 %151 %5 -%160 = OpULessThan %159 %79 %158 -%161 = OpAll %152 %160 -OpBranchConditional %161 %162 %156 -%162 = OpLabel -%163 = OpImageFetch %25 %151 %79 Lod %5 -OpBranch %156 -%156 = OpLabel -%164 = OpPhi %25 %153 %70 %153 %157 %163 %162 -%165 = OpFAdd %25 %149 %164 -OpStore %55 %165 -%166 = OpLoad %25 %55 -%167 = OpAccessChain %81 %27 %73 -%168 = OpLoad %10 %167 -%170 = OpImageQueryLevels %4 %168 -%171 = OpULessThan %152 %5 %170 -OpSelectionMerge %172 None -OpBranchConditional %171 %173 %172 +%165 = OpPhi %25 %154 %73 %154 %158 %164 %163 +%166 = OpLoad %25 %58 +%167 = OpFAdd %25 %166 %165 +OpStore %58 %167 +%168 = OpAccessChain %82 %28 %76 +%169 = OpLoad %10 %168 +%171 = OpImageQueryLevels %4 %169 +%172 = OpULessThan %153 %5 %171 +OpSelectionMerge %173 None +OpBranchConditional %172 %174 %173 +%174 = OpLabel +%175 = OpImageQuerySizeLod %26 %169 %5 +%176 = OpULessThan %160 %81 %175 +%177 = OpAll %153 %176 +OpBranchConditional %177 %178 %173 +%178 = OpLabel +%179 = OpImageFetch %25 %169 %81 Lod %5 +OpBranch %173 %173 = OpLabel -%174 = OpImageQuerySizeLod %26 %168 %5 -%175 = OpULessThan %159 %79 %174 -%176 = OpAll %152 %175 -OpBranchConditional %176 %177 %172 -%177 = OpLabel -%178 = OpImageFetch %25 %168 %79 Lod %5 -OpBranch %172 -%172 = OpLabel -%179 = OpPhi %25 %169 %156 %169 %173 %178 %177 -%180 = OpFAdd %25 %166 %179 -OpStore %55 %180 -%181 = OpLoad %25 %55 -%182 = OpAccessChain %81 %27 %74 -%183 = OpLoad %10 %182 -%185 = OpImageQueryLevels %4 %183 -%186 = OpULessThan %152 %5 %185 -OpSelectionMerge %187 None -OpBranchConditional %186 %188 %187 +%180 = OpPhi %25 %170 %157 %170 %174 %179 %178 +%181 = OpLoad %25 %58 +%182 = OpFAdd %25 %181 %180 +OpStore %58 %182 +%183 = OpAccessChain %82 %28 %77 +%184 = OpLoad %10 %183 +%186 = OpImageQueryLevels %4 %184 +%187 = OpULessThan %153 %5 %186 +OpSelectionMerge %188 None +OpBranchConditional %187 %189 %188 +%189 = OpLabel +%190 = OpImageQuerySizeLod %26 %184 %5 +%191 = OpULessThan %160 %81 %190 +%192 = OpAll %153 %191 +OpBranchConditional %192 %193 %188 +%193 = OpLabel +%194 = OpImageFetch %25 %184 %81 Lod %5 +OpBranch %188 %188 = OpLabel -%189 = OpImageQuerySizeLod %26 %183 %5 -%190 = OpULessThan %159 %79 %189 -%191 = OpAll %152 %190 -OpBranchConditional %191 %192 %187 -%192 = OpLabel -%193 = OpImageFetch %25 %183 %79 Lod %5 -OpBranch %187 -%187 = OpLabel -%194 = OpPhi %25 %184 %172 %184 %188 %193 %192 -%195 = OpFAdd %25 %181 %194 -OpStore %55 %195 -%196 = OpLoad %4 %48 -%198 = OpAccessChain %197 %33 %68 -%199 = OpLoad %13 %198 -%201 = OpImageQuerySizeLod %200 %199 %68 -%202 = OpCompositeExtract %4 %201 2 -%203 = OpIAdd %4 %196 %202 -OpStore %48 %203 -%204 = OpLoad %4 %48 -%205 = OpAccessChain %197 %33 %73 -%206 = OpLoad %13 %205 -%207 = OpImageQuerySizeLod %200 %206 %68 -%208 = OpCompositeExtract %4 %207 2 -%209 = OpIAdd %4 %204 %208 -OpStore %48 %209 -%210 = OpLoad %4 %48 -%211 = OpAccessChain %197 %33 %74 -%212 = OpLoad %13 %211 -%213 = OpImageQuerySizeLod %200 %212 %68 -%214 = OpCompositeExtract %4 %213 2 -%215 = OpIAdd %4 %210 %214 -OpStore %48 %215 -%216 = OpLoad %4 %48 -%217 = OpAccessChain %81 %31 %68 -%218 = OpLoad %10 %217 -%219 = OpImageQueryLevels %4 %218 -%220 = OpIAdd %4 %216 %219 -OpStore %48 %220 -%221 = OpLoad %4 %48 -%222 = OpAccessChain %81 %31 %73 -%223 = OpLoad %10 %222 -%224 = OpImageQueryLevels %4 %223 -%225 = OpIAdd %4 %221 %224 -OpStore %48 %225 -%226 = OpLoad %4 %48 -%227 = OpAccessChain %81 %31 %74 -%228 = OpLoad %10 %227 -%229 = OpImageQueryLevels %4 %228 -%230 = OpIAdd %4 %226 %229 -OpStore %48 %230 -%231 = OpLoad %4 %48 -%233 = OpAccessChain %232 %35 %68 -%234 = OpLoad %15 %233 -%235 = OpImageQuerySamples %4 %234 -%236 = OpIAdd %4 %231 %235 -OpStore %48 %236 -%237 = OpLoad %4 %48 -%238 = OpAccessChain %232 %35 %73 -%239 = OpLoad %15 %238 -%240 = OpImageQuerySamples %4 %239 -%241 = OpIAdd %4 %237 %240 -OpStore %48 %241 -%242 = OpLoad %4 %48 -%243 = OpAccessChain %232 %35 %74 -%244 = OpLoad %15 %243 -%245 = OpImageQuerySamples %4 %244 -%246 = OpIAdd %4 %242 %245 -OpStore %48 %246 -%247 = OpLoad %25 %55 -%248 = OpAccessChain %81 %31 %68 -%249 = OpLoad %10 %248 -%250 = OpAccessChain %99 %41 %68 -%251 = OpLoad %21 %250 -%252 = OpSampledImage %102 %249 %251 -%253 = OpImageSampleImplicitLod %25 %252 %78 -%254 = OpFAdd %25 %247 %253 -OpStore %55 %254 -%255 = OpLoad %25 %55 -%256 = OpAccessChain %81 %31 %73 -%257 = OpLoad %10 %256 -%258 = OpAccessChain %99 %41 %73 -%259 = OpLoad %21 %258 -%260 = OpSampledImage %102 %257 %259 -%261 = OpImageSampleImplicitLod %25 %260 %78 -%262 = OpFAdd %25 %255 %261 -OpStore %55 %262 -%263 = OpLoad %25 %55 -%264 = OpAccessChain %81 %31 %74 -%265 = OpLoad %10 %264 -%266 = OpAccessChain %99 %41 %74 -%267 = OpLoad %21 %266 -%268 = OpSampledImage %102 %265 %267 -%269 = OpImageSampleImplicitLod %25 %268 %78 -%270 = OpFAdd %25 %263 %269 -OpStore %55 %270 -%271 = OpLoad %25 %55 -%272 = OpAccessChain %81 %31 %68 -%273 = OpLoad %10 %272 -%274 = OpAccessChain %99 %41 %68 -%275 = OpLoad %21 %274 -%276 = OpSampledImage %102 %273 %275 -%277 = OpImageSampleImplicitLod %25 %276 %78 Bias %6 -%278 = OpFAdd %25 %271 %277 -OpStore %55 %278 -%279 = OpLoad %25 %55 -%280 = OpAccessChain %81 %31 %73 -%281 = OpLoad %10 %280 -%282 = OpAccessChain %99 %41 %73 -%283 = OpLoad %21 %282 -%284 = OpSampledImage %102 %281 %283 -%285 = OpImageSampleImplicitLod %25 %284 %78 Bias %6 -%286 = OpFAdd %25 %279 %285 -OpStore %55 %286 -%287 = OpLoad %25 %55 -%288 = OpAccessChain %81 %31 %74 -%289 = OpLoad %10 %288 -%290 = OpAccessChain %99 %41 %74 -%291 = OpLoad %21 %290 -%292 = OpSampledImage %102 %289 %291 -%293 = OpImageSampleImplicitLod %25 %292 %78 Bias %6 -%294 = OpFAdd %25 %287 %293 -OpStore %55 %294 -%295 = OpLoad %7 %53 -%296 = OpAccessChain %123 %37 %68 -%297 = OpLoad %17 %296 -%298 = OpAccessChain %126 %43 %68 -%299 = OpLoad %21 %298 -%300 = OpSampledImage %129 %297 %299 -%301 = OpImageSampleDrefImplicitLod %7 %300 %78 %6 -%302 = OpFAdd %7 %295 %301 -OpStore %53 %302 -%303 = OpLoad %7 %53 -%304 = OpAccessChain %123 %37 %73 -%305 = OpLoad %17 %304 -%306 = OpAccessChain %126 %43 %73 -%307 = OpLoad %21 %306 -%308 = OpSampledImage %129 %305 %307 -%309 = OpImageSampleDrefImplicitLod %7 %308 %78 %6 -%310 = OpFAdd %7 %303 %309 -OpStore %53 %310 -%311 = OpLoad %7 %53 -%312 = OpAccessChain %123 %37 %74 -%313 = OpLoad %17 %312 -%314 = OpAccessChain %126 %43 %74 -%315 = OpLoad %21 %314 -%316 = OpSampledImage %129 %313 %315 -%317 = OpImageSampleDrefImplicitLod %7 %316 %78 %6 -%318 = OpFAdd %7 %311 %317 -OpStore %53 %318 -%319 = OpLoad %7 %53 -%320 = OpAccessChain %123 %37 %68 -%321 = OpLoad %17 %320 -%322 = OpAccessChain %126 %43 %68 -%323 = OpLoad %21 %322 -%324 = OpSampledImage %129 %321 %323 -%325 = OpImageSampleDrefExplicitLod %7 %324 %78 %6 Lod %6 -%326 = OpFAdd %7 %319 %325 -OpStore %53 %326 -%327 = OpLoad %7 %53 -%328 = OpAccessChain %123 %37 %73 -%329 = OpLoad %17 %328 -%330 = OpAccessChain %126 %43 %73 -%331 = OpLoad %21 %330 -%332 = OpSampledImage %129 %329 %331 -%333 = OpImageSampleDrefExplicitLod %7 %332 %78 %6 Lod %6 -%334 = OpFAdd %7 %327 %333 -OpStore %53 %334 -%335 = OpLoad %7 %53 -%336 = OpAccessChain %123 %37 %74 -%337 = OpLoad %17 %336 -%338 = OpAccessChain %126 %43 %74 -%339 = OpLoad %21 %338 -%340 = OpSampledImage %129 %337 %339 -%341 = OpImageSampleDrefExplicitLod %7 %340 %78 %6 Lod %6 -%342 = OpFAdd %7 %335 %341 -OpStore %53 %342 -%343 = OpLoad %25 %55 -%344 = OpAccessChain %81 %31 %68 -%345 = OpLoad %10 %344 -%346 = OpAccessChain %99 %41 %68 -%347 = OpLoad %21 %346 -%348 = OpSampledImage %102 %345 %347 -%349 = OpImageSampleExplicitLod %25 %348 %78 Grad %78 %78 -%350 = OpFAdd %25 %343 %349 -OpStore %55 %350 -%351 = OpLoad %25 %55 -%352 = OpAccessChain %81 %31 %73 -%353 = OpLoad %10 %352 -%354 = OpAccessChain %99 %41 %73 -%355 = OpLoad %21 %354 -%356 = OpSampledImage %102 %353 %355 -%357 = OpImageSampleExplicitLod %25 %356 %78 Grad %78 %78 -%358 = OpFAdd %25 %351 %357 -OpStore %55 %358 -%359 = OpLoad %25 %55 -%360 = OpAccessChain %81 %31 %74 -%361 = OpLoad %10 %360 -%362 = OpAccessChain %99 %41 %74 -%363 = OpLoad %21 %362 -%364 = OpSampledImage %102 %361 %363 -%365 = OpImageSampleExplicitLod %25 %364 %78 Grad %78 %78 -%366 = OpFAdd %25 %359 %365 -OpStore %55 %366 -%367 = OpLoad %25 %55 -%368 = OpAccessChain %81 %31 %68 -%369 = OpLoad %10 %368 -%370 = OpAccessChain %99 %41 %68 -%371 = OpLoad %21 %370 -%372 = OpSampledImage %102 %369 %371 -%373 = OpImageSampleExplicitLod %25 %372 %78 Lod %6 -%374 = OpFAdd %25 %367 %373 -OpStore %55 %374 -%375 = OpLoad %25 %55 -%376 = OpAccessChain %81 %31 %73 -%377 = OpLoad %10 %376 -%378 = OpAccessChain %99 %41 %73 -%379 = OpLoad %21 %378 -%380 = OpSampledImage %102 %377 %379 -%381 = OpImageSampleExplicitLod %25 %380 %78 Lod %6 -%382 = OpFAdd %25 %375 %381 -OpStore %55 %382 -%383 = OpLoad %25 %55 -%384 = OpAccessChain %81 %31 %74 -%385 = OpLoad %10 %384 -%386 = OpAccessChain %99 %41 %74 -%387 = OpLoad %21 %386 -%388 = OpSampledImage %102 %385 %387 -%389 = OpImageSampleExplicitLod %25 %388 %78 Lod %6 -%390 = OpFAdd %25 %383 %389 -OpStore %55 %390 -%392 = OpAccessChain %391 %39 %68 -%393 = OpLoad %19 %392 -%394 = OpLoad %25 %55 -%395 = OpImageQuerySize %26 %393 -%396 = OpULessThan %159 %79 %395 -%397 = OpAll %152 %396 -OpSelectionMerge %398 None -OpBranchConditional %397 %399 %398 -%399 = OpLabel -OpImageWrite %393 %79 %394 -OpBranch %398 -%398 = OpLabel -%400 = OpAccessChain %391 %39 %73 -%401 = OpLoad %19 %400 -%402 = OpLoad %25 %55 -%403 = OpImageQuerySize %26 %401 -%404 = OpULessThan %159 %79 %403 -%405 = OpAll %152 %404 -OpSelectionMerge %406 None -OpBranchConditional %405 %407 %406 -%407 = OpLabel -OpImageWrite %401 %79 %402 -OpBranch %406 -%406 = OpLabel -%408 = OpAccessChain %391 %39 %74 -%409 = OpLoad %19 %408 -%410 = OpLoad %25 %55 -%411 = OpImageQuerySize %26 %409 -%412 = OpULessThan %159 %79 %411 -%413 = OpAll %152 %412 -OpSelectionMerge %414 None -OpBranchConditional %413 %415 %414 -%415 = OpLabel -OpImageWrite %409 %79 %410 -OpBranch %414 -%414 = OpLabel -%416 = OpLoad %26 %50 -%417 = OpLoad %4 %48 -%418 = OpCompositeConstruct %26 %417 %417 -%419 = OpIAdd %26 %416 %418 -%420 = OpConvertSToF %77 %419 -%421 = OpLoad %25 %55 -%422 = OpCompositeExtract %7 %420 0 -%423 = OpCompositeExtract %7 %420 1 -%424 = OpCompositeExtract %7 %420 0 -%425 = OpCompositeExtract %7 %420 1 -%426 = OpCompositeConstruct %25 %422 %423 %424 %425 -%427 = OpFAdd %25 %421 %426 -%428 = OpLoad %7 %53 -%429 = OpCompositeConstruct %25 %428 %428 %428 %428 -%430 = OpFAdd %25 %427 %429 -OpStore %63 %430 +%195 = OpPhi %25 %185 %173 %185 %189 %194 %193 +%196 = OpLoad %25 %58 +%197 = OpFAdd %25 %196 %195 +OpStore %58 %197 +%199 = OpAccessChain %198 %34 %71 +%200 = OpLoad %13 %199 +%202 = OpImageQuerySizeLod %201 %200 %71 +%203 = OpCompositeExtract %4 %202 2 +%204 = OpLoad %4 %49 +%205 = OpIAdd %4 %204 %203 +OpStore %49 %205 +%206 = OpAccessChain %198 %34 %76 +%207 = OpLoad %13 %206 +%208 = OpImageQuerySizeLod %201 %207 %71 +%209 = OpCompositeExtract %4 %208 2 +%210 = OpLoad %4 %49 +%211 = OpIAdd %4 %210 %209 +OpStore %49 %211 +%212 = OpAccessChain %198 %34 %77 +%213 = OpLoad %13 %212 +%214 = OpImageQuerySizeLod %201 %213 %71 +%215 = OpCompositeExtract %4 %214 2 +%216 = OpLoad %4 %49 +%217 = OpIAdd %4 %216 %215 +OpStore %49 %217 +%218 = OpAccessChain %82 %32 %71 +%219 = OpLoad %10 %218 +%220 = OpImageQueryLevels %4 %219 +%221 = OpLoad %4 %49 +%222 = OpIAdd %4 %221 %220 +OpStore %49 %222 +%223 = OpAccessChain %82 %32 %76 +%224 = OpLoad %10 %223 +%225 = OpImageQueryLevels %4 %224 +%226 = OpLoad %4 %49 +%227 = OpIAdd %4 %226 %225 +OpStore %49 %227 +%228 = OpAccessChain %82 %32 %77 +%229 = OpLoad %10 %228 +%230 = OpImageQueryLevels %4 %229 +%231 = OpLoad %4 %49 +%232 = OpIAdd %4 %231 %230 +OpStore %49 %232 +%234 = OpAccessChain %233 %36 %71 +%235 = OpLoad %15 %234 +%236 = OpImageQuerySamples %4 %235 +%237 = OpLoad %4 %49 +%238 = OpIAdd %4 %237 %236 +OpStore %49 %238 +%239 = OpAccessChain %233 %36 %76 +%240 = OpLoad %15 %239 +%241 = OpImageQuerySamples %4 %240 +%242 = OpLoad %4 %49 +%243 = OpIAdd %4 %242 %241 +OpStore %49 %243 +%244 = OpAccessChain %233 %36 %77 +%245 = OpLoad %15 %244 +%246 = OpImageQuerySamples %4 %245 +%247 = OpLoad %4 %49 +%248 = OpIAdd %4 %247 %246 +OpStore %49 %248 +%249 = OpAccessChain %82 %32 %71 +%250 = OpLoad %10 %249 +%251 = OpAccessChain %100 %42 %71 +%252 = OpLoad %21 %251 +%253 = OpSampledImage %103 %250 %252 +%254 = OpImageSampleImplicitLod %25 %253 %80 +%255 = OpLoad %25 %58 +%256 = OpFAdd %25 %255 %254 +OpStore %58 %256 +%257 = OpAccessChain %82 %32 %76 +%258 = OpLoad %10 %257 +%259 = OpAccessChain %100 %42 %76 +%260 = OpLoad %21 %259 +%261 = OpSampledImage %103 %258 %260 +%262 = OpImageSampleImplicitLod %25 %261 %80 +%263 = OpLoad %25 %58 +%264 = OpFAdd %25 %263 %262 +OpStore %58 %264 +%265 = OpAccessChain %82 %32 %77 +%266 = OpLoad %10 %265 +%267 = OpAccessChain %100 %42 %77 +%268 = OpLoad %21 %267 +%269 = OpSampledImage %103 %266 %268 +%270 = OpImageSampleImplicitLod %25 %269 %80 +%271 = OpLoad %25 %58 +%272 = OpFAdd %25 %271 %270 +OpStore %58 %272 +%273 = OpAccessChain %82 %32 %71 +%274 = OpLoad %10 %273 +%275 = OpAccessChain %100 %42 %71 +%276 = OpLoad %21 %275 +%277 = OpSampledImage %103 %274 %276 +%278 = OpImageSampleImplicitLod %25 %277 %80 Bias %6 +%279 = OpLoad %25 %58 +%280 = OpFAdd %25 %279 %278 +OpStore %58 %280 +%281 = OpAccessChain %82 %32 %76 +%282 = OpLoad %10 %281 +%283 = OpAccessChain %100 %42 %76 +%284 = OpLoad %21 %283 +%285 = OpSampledImage %103 %282 %284 +%286 = OpImageSampleImplicitLod %25 %285 %80 Bias %6 +%287 = OpLoad %25 %58 +%288 = OpFAdd %25 %287 %286 +OpStore %58 %288 +%289 = OpAccessChain %82 %32 %77 +%290 = OpLoad %10 %289 +%291 = OpAccessChain %100 %42 %77 +%292 = OpLoad %21 %291 +%293 = OpSampledImage %103 %290 %292 +%294 = OpImageSampleImplicitLod %25 %293 %80 Bias %6 +%295 = OpLoad %25 %58 +%296 = OpFAdd %25 %295 %294 +OpStore %58 %296 +%297 = OpAccessChain %124 %38 %71 +%298 = OpLoad %17 %297 +%299 = OpAccessChain %127 %44 %71 +%300 = OpLoad %21 %299 +%301 = OpSampledImage %130 %298 %300 +%302 = OpImageSampleDrefImplicitLod %7 %301 %80 %6 +%303 = OpLoad %7 %55 +%304 = OpFAdd %7 %303 %302 +OpStore %55 %304 +%305 = OpAccessChain %124 %38 %76 +%306 = OpLoad %17 %305 +%307 = OpAccessChain %127 %44 %76 +%308 = OpLoad %21 %307 +%309 = OpSampledImage %130 %306 %308 +%310 = OpImageSampleDrefImplicitLod %7 %309 %80 %6 +%311 = OpLoad %7 %55 +%312 = OpFAdd %7 %311 %310 +OpStore %55 %312 +%313 = OpAccessChain %124 %38 %77 +%314 = OpLoad %17 %313 +%315 = OpAccessChain %127 %44 %77 +%316 = OpLoad %21 %315 +%317 = OpSampledImage %130 %314 %316 +%318 = OpImageSampleDrefImplicitLod %7 %317 %80 %6 +%319 = OpLoad %7 %55 +%320 = OpFAdd %7 %319 %318 +OpStore %55 %320 +%321 = OpAccessChain %124 %38 %71 +%322 = OpLoad %17 %321 +%323 = OpAccessChain %127 %44 %71 +%324 = OpLoad %21 %323 +%325 = OpSampledImage %130 %322 %324 +%326 = OpImageSampleDrefExplicitLod %7 %325 %80 %6 Lod %6 +%327 = OpLoad %7 %55 +%328 = OpFAdd %7 %327 %326 +OpStore %55 %328 +%329 = OpAccessChain %124 %38 %76 +%330 = OpLoad %17 %329 +%331 = OpAccessChain %127 %44 %76 +%332 = OpLoad %21 %331 +%333 = OpSampledImage %130 %330 %332 +%334 = OpImageSampleDrefExplicitLod %7 %333 %80 %6 Lod %6 +%335 = OpLoad %7 %55 +%336 = OpFAdd %7 %335 %334 +OpStore %55 %336 +%337 = OpAccessChain %124 %38 %77 +%338 = OpLoad %17 %337 +%339 = OpAccessChain %127 %44 %77 +%340 = OpLoad %21 %339 +%341 = OpSampledImage %130 %338 %340 +%342 = OpImageSampleDrefExplicitLod %7 %341 %80 %6 Lod %6 +%343 = OpLoad %7 %55 +%344 = OpFAdd %7 %343 %342 +OpStore %55 %344 +%345 = OpAccessChain %82 %32 %71 +%346 = OpLoad %10 %345 +%347 = OpAccessChain %100 %42 %71 +%348 = OpLoad %21 %347 +%349 = OpSampledImage %103 %346 %348 +%350 = OpImageSampleExplicitLod %25 %349 %80 Grad %80 %80 +%351 = OpLoad %25 %58 +%352 = OpFAdd %25 %351 %350 +OpStore %58 %352 +%353 = OpAccessChain %82 %32 %76 +%354 = OpLoad %10 %353 +%355 = OpAccessChain %100 %42 %76 +%356 = OpLoad %21 %355 +%357 = OpSampledImage %103 %354 %356 +%358 = OpImageSampleExplicitLod %25 %357 %80 Grad %80 %80 +%359 = OpLoad %25 %58 +%360 = OpFAdd %25 %359 %358 +OpStore %58 %360 +%361 = OpAccessChain %82 %32 %77 +%362 = OpLoad %10 %361 +%363 = OpAccessChain %100 %42 %77 +%364 = OpLoad %21 %363 +%365 = OpSampledImage %103 %362 %364 +%366 = OpImageSampleExplicitLod %25 %365 %80 Grad %80 %80 +%367 = OpLoad %25 %58 +%368 = OpFAdd %25 %367 %366 +OpStore %58 %368 +%369 = OpAccessChain %82 %32 %71 +%370 = OpLoad %10 %369 +%371 = OpAccessChain %100 %42 %71 +%372 = OpLoad %21 %371 +%373 = OpSampledImage %103 %370 %372 +%374 = OpImageSampleExplicitLod %25 %373 %80 Lod %6 +%375 = OpLoad %25 %58 +%376 = OpFAdd %25 %375 %374 +OpStore %58 %376 +%377 = OpAccessChain %82 %32 %76 +%378 = OpLoad %10 %377 +%379 = OpAccessChain %100 %42 %76 +%380 = OpLoad %21 %379 +%381 = OpSampledImage %103 %378 %380 +%382 = OpImageSampleExplicitLod %25 %381 %80 Lod %6 +%383 = OpLoad %25 %58 +%384 = OpFAdd %25 %383 %382 +OpStore %58 %384 +%385 = OpAccessChain %82 %32 %77 +%386 = OpLoad %10 %385 +%387 = OpAccessChain %100 %42 %77 +%388 = OpLoad %21 %387 +%389 = OpSampledImage %103 %386 %388 +%390 = OpImageSampleExplicitLod %25 %389 %80 Lod %6 +%391 = OpLoad %25 %58 +%392 = OpFAdd %25 %391 %390 +OpStore %58 %392 +%394 = OpAccessChain %393 %40 %71 +%395 = OpLoad %19 %394 +%396 = OpLoad %25 %58 +%397 = OpImageQuerySize %26 %395 +%398 = OpULessThan %160 %81 %397 +%399 = OpAll %153 %398 +OpSelectionMerge %400 None +OpBranchConditional %399 %401 %400 +%401 = OpLabel +OpImageWrite %395 %81 %396 +OpBranch %400 +%400 = OpLabel +%402 = OpAccessChain %393 %40 %76 +%403 = OpLoad %19 %402 +%404 = OpLoad %25 %58 +%405 = OpImageQuerySize %26 %403 +%406 = OpULessThan %160 %81 %405 +%407 = OpAll %153 %406 +OpSelectionMerge %408 None +OpBranchConditional %407 %409 %408 +%409 = OpLabel +OpImageWrite %403 %81 %404 +OpBranch %408 +%408 = OpLabel +%410 = OpAccessChain %393 %40 %77 +%411 = OpLoad %19 %410 +%412 = OpLoad %25 %58 +%413 = OpImageQuerySize %26 %411 +%414 = OpULessThan %160 %81 %413 +%415 = OpAll %153 %414 +OpSelectionMerge %416 None +OpBranchConditional %415 %417 %416 +%417 = OpLabel +OpImageWrite %411 %81 %412 +OpBranch %416 +%416 = OpLabel +%418 = OpLoad %26 %52 +%419 = OpLoad %4 %49 +%420 = OpCompositeConstruct %26 %419 %419 +%421 = OpIAdd %26 %418 %420 +%422 = OpConvertSToF %27 %421 +%423 = OpLoad %25 %58 +%424 = OpCompositeExtract %7 %422 0 +%425 = OpCompositeExtract %7 %422 1 +%426 = OpCompositeExtract %7 %422 0 +%427 = OpCompositeExtract %7 %422 1 +%428 = OpCompositeConstruct %25 %424 %425 %426 %427 +%429 = OpFAdd %25 %423 %428 +%430 = OpLoad %7 %55 +%431 = OpCompositeConstruct %25 %430 %430 %430 %430 +%432 = OpFAdd %25 %429 %431 +OpStore %66 %432 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm index c705d8276..b8c17d870 100644 --- a/tests/out/spv/bits.spvasm +++ b/tests/out/spv/bits.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 159 +; Bound: 161 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %48 "main" -OpExecutionMode %48 LocalSize 1 1 1 +OpEntryPoint GLCompute %50 "main" +OpExecutionMode %50 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 0 @@ -25,199 +25,203 @@ OpExecutionMode %48 LocalSize 1 1 1 %17 = OpTypeVector %8 2 %18 = OpTypeVector %8 4 %20 = OpTypePointer Function %4 -%22 = OpTypePointer Function %11 -%23 = OpConstantNull %11 -%25 = OpTypePointer Function %12 -%26 = OpConstantNull %12 -%28 = OpTypePointer Function %13 -%29 = OpConstantNull %13 -%31 = OpTypePointer Function %6 -%33 = OpTypePointer Function %14 -%34 = OpConstantNull %14 -%36 = OpTypePointer Function %15 -%37 = OpConstantNull %15 -%39 = OpTypePointer Function %16 -%40 = OpConstantNull %16 -%42 = OpTypePointer Function %17 -%43 = OpConstantNull %17 -%45 = OpTypePointer Function %18 -%46 = OpConstantNull %18 -%49 = OpTypeFunction %2 -%48 = OpFunction %2 None %49 -%47 = OpLabel -%44 = OpVariable %45 Function %46 -%35 = OpVariable %36 Function %37 -%27 = OpVariable %28 Function %29 -%19 = OpVariable %20 Function %3 -%38 = OpVariable %39 Function %40 -%30 = OpVariable %31 Function %5 -%21 = OpVariable %22 Function %23 -%41 = OpVariable %42 Function %43 -%32 = OpVariable %33 Function %34 -%24 = OpVariable %25 Function %26 -OpBranch %50 -%50 = OpLabel -%51 = OpCompositeConstruct %11 %3 %3 -OpStore %21 %51 -%52 = OpCompositeConstruct %12 %3 %3 %3 -OpStore %24 %52 -%53 = OpCompositeConstruct %13 %3 %3 %3 %3 -OpStore %27 %53 -%54 = OpCompositeConstruct %14 %5 %5 -OpStore %32 %54 -%55 = OpCompositeConstruct %15 %5 %5 %5 -OpStore %35 %55 -%56 = OpCompositeConstruct %16 %5 %5 %5 %5 -OpStore %38 %56 -%57 = OpCompositeConstruct %17 %7 %7 -OpStore %41 %57 -%58 = OpCompositeConstruct %18 %7 %7 %7 %7 -OpStore %44 %58 -%59 = OpLoad %18 %44 -%60 = OpExtInst %6 %1 PackSnorm4x8 %59 -OpStore %30 %60 -%61 = OpLoad %18 %44 -%62 = OpExtInst %6 %1 PackUnorm4x8 %61 -OpStore %30 %62 -%63 = OpLoad %17 %41 -%64 = OpExtInst %6 %1 PackSnorm2x16 %63 -OpStore %30 %64 -%65 = OpLoad %17 %41 -%66 = OpExtInst %6 %1 PackUnorm2x16 %65 -OpStore %30 %66 -%67 = OpLoad %17 %41 -%68 = OpExtInst %6 %1 PackHalf2x16 %67 -OpStore %30 %68 -%69 = OpLoad %6 %30 -%70 = OpExtInst %18 %1 UnpackSnorm4x8 %69 -OpStore %44 %70 -%71 = OpLoad %6 %30 -%72 = OpExtInst %18 %1 UnpackUnorm4x8 %71 -OpStore %44 %72 -%73 = OpLoad %6 %30 -%74 = OpExtInst %17 %1 UnpackSnorm2x16 %73 -OpStore %41 %74 -%75 = OpLoad %6 %30 -%76 = OpExtInst %17 %1 UnpackUnorm2x16 %75 -OpStore %41 %76 -%77 = OpLoad %6 %30 -%78 = OpExtInst %17 %1 UnpackHalf2x16 %77 -OpStore %41 %78 -%79 = OpLoad %4 %19 -%80 = OpLoad %4 %19 -%81 = OpBitFieldInsert %4 %79 %80 %9 %10 -OpStore %19 %81 -%82 = OpLoad %11 %21 -%83 = OpLoad %11 %21 -%84 = OpBitFieldInsert %11 %82 %83 %9 %10 -OpStore %21 %84 -%85 = OpLoad %12 %24 -%86 = OpLoad %12 %24 -%87 = OpBitFieldInsert %12 %85 %86 %9 %10 -OpStore %24 %87 -%88 = OpLoad %13 %27 -%89 = OpLoad %13 %27 -%90 = OpBitFieldInsert %13 %88 %89 %9 %10 -OpStore %27 %90 -%91 = OpLoad %6 %30 -%92 = OpLoad %6 %30 -%93 = OpBitFieldInsert %6 %91 %92 %9 %10 -OpStore %30 %93 -%94 = OpLoad %14 %32 -%95 = OpLoad %14 %32 -%96 = OpBitFieldInsert %14 %94 %95 %9 %10 -OpStore %32 %96 -%97 = OpLoad %15 %35 -%98 = OpLoad %15 %35 -%99 = OpBitFieldInsert %15 %97 %98 %9 %10 -OpStore %35 %99 -%100 = OpLoad %16 %38 -%101 = OpLoad %16 %38 -%102 = OpBitFieldInsert %16 %100 %101 %9 %10 -OpStore %38 %102 -%103 = OpLoad %4 %19 -%104 = OpBitFieldSExtract %4 %103 %9 %10 -OpStore %19 %104 -%105 = OpLoad %11 %21 -%106 = OpBitFieldSExtract %11 %105 %9 %10 -OpStore %21 %106 -%107 = OpLoad %12 %24 -%108 = OpBitFieldSExtract %12 %107 %9 %10 -OpStore %24 %108 -%109 = OpLoad %13 %27 -%110 = OpBitFieldSExtract %13 %109 %9 %10 -OpStore %27 %110 -%111 = OpLoad %6 %30 -%112 = OpBitFieldUExtract %6 %111 %9 %10 -OpStore %30 %112 -%113 = OpLoad %14 %32 -%114 = OpBitFieldUExtract %14 %113 %9 %10 -OpStore %32 %114 -%115 = OpLoad %15 %35 -%116 = OpBitFieldUExtract %15 %115 %9 %10 -OpStore %35 %116 -%117 = OpLoad %16 %38 -%118 = OpBitFieldUExtract %16 %117 %9 %10 -OpStore %38 %118 -%119 = OpLoad %4 %19 -%120 = OpExtInst %4 %1 FindILsb %119 -OpStore %19 %120 -%121 = OpLoad %14 %32 -%122 = OpExtInst %14 %1 FindILsb %121 -OpStore %32 %122 -%123 = OpLoad %12 %24 -%124 = OpExtInst %12 %1 FindSMsb %123 -OpStore %24 %124 -%125 = OpLoad %6 %30 -%126 = OpExtInst %6 %1 FindUMsb %125 -OpStore %30 %126 -%127 = OpLoad %4 %19 -%128 = OpBitCount %4 %127 -OpStore %19 %128 -%129 = OpLoad %11 %21 -%130 = OpBitCount %11 %129 -OpStore %21 %130 -%131 = OpLoad %12 %24 -%132 = OpBitCount %12 %131 -OpStore %24 %132 -%133 = OpLoad %13 %27 -%134 = OpBitCount %13 %133 -OpStore %27 %134 -%135 = OpLoad %6 %30 -%136 = OpBitCount %6 %135 -OpStore %30 %136 -%137 = OpLoad %14 %32 -%138 = OpBitCount %14 %137 -OpStore %32 %138 -%139 = OpLoad %15 %35 -%140 = OpBitCount %15 %139 -OpStore %35 %140 -%141 = OpLoad %16 %38 -%142 = OpBitCount %16 %141 -OpStore %38 %142 -%143 = OpLoad %4 %19 -%144 = OpBitReverse %4 %143 -OpStore %19 %144 -%145 = OpLoad %11 %21 -%146 = OpBitReverse %11 %145 -OpStore %21 %146 -%147 = OpLoad %12 %24 -%148 = OpBitReverse %12 %147 -OpStore %24 %148 -%149 = OpLoad %13 %27 -%150 = OpBitReverse %13 %149 -OpStore %27 %150 -%151 = OpLoad %6 %30 -%152 = OpBitReverse %6 %151 -OpStore %30 %152 -%153 = OpLoad %14 %32 -%154 = OpBitReverse %14 %153 -OpStore %32 %154 -%155 = OpLoad %15 %35 -%156 = OpBitReverse %15 %155 -OpStore %35 %156 -%157 = OpLoad %16 %38 -%158 = OpBitReverse %16 %157 -OpStore %38 %158 +%21 = OpConstantNull %4 +%23 = OpTypePointer Function %11 +%24 = OpConstantNull %11 +%26 = OpTypePointer Function %12 +%27 = OpConstantNull %12 +%29 = OpTypePointer Function %13 +%30 = OpConstantNull %13 +%32 = OpTypePointer Function %6 +%33 = OpConstantNull %6 +%35 = OpTypePointer Function %14 +%36 = OpConstantNull %14 +%38 = OpTypePointer Function %15 +%39 = OpConstantNull %15 +%41 = OpTypePointer Function %16 +%42 = OpConstantNull %16 +%44 = OpTypePointer Function %17 +%45 = OpConstantNull %17 +%47 = OpTypePointer Function %18 +%48 = OpConstantNull %18 +%51 = OpTypeFunction %2 +%50 = OpFunction %2 None %51 +%49 = OpLabel +%46 = OpVariable %47 Function %48 +%37 = OpVariable %38 Function %39 +%28 = OpVariable %29 Function %30 +%19 = OpVariable %20 Function %21 +%40 = OpVariable %41 Function %42 +%31 = OpVariable %32 Function %33 +%22 = OpVariable %23 Function %24 +%43 = OpVariable %44 Function %45 +%34 = OpVariable %35 Function %36 +%25 = OpVariable %26 Function %27 +OpBranch %52 +%52 = OpLabel +OpStore %19 %3 +%53 = OpCompositeConstruct %11 %3 %3 +OpStore %22 %53 +%54 = OpCompositeConstruct %12 %3 %3 %3 +OpStore %25 %54 +%55 = OpCompositeConstruct %13 %3 %3 %3 %3 +OpStore %28 %55 +OpStore %31 %5 +%56 = OpCompositeConstruct %14 %5 %5 +OpStore %34 %56 +%57 = OpCompositeConstruct %15 %5 %5 %5 +OpStore %37 %57 +%58 = OpCompositeConstruct %16 %5 %5 %5 %5 +OpStore %40 %58 +%59 = OpCompositeConstruct %17 %7 %7 +OpStore %43 %59 +%60 = OpCompositeConstruct %18 %7 %7 %7 %7 +OpStore %46 %60 +%61 = OpLoad %18 %46 +%62 = OpExtInst %6 %1 PackSnorm4x8 %61 +OpStore %31 %62 +%63 = OpLoad %18 %46 +%64 = OpExtInst %6 %1 PackUnorm4x8 %63 +OpStore %31 %64 +%65 = OpLoad %17 %43 +%66 = OpExtInst %6 %1 PackSnorm2x16 %65 +OpStore %31 %66 +%67 = OpLoad %17 %43 +%68 = OpExtInst %6 %1 PackUnorm2x16 %67 +OpStore %31 %68 +%69 = OpLoad %17 %43 +%70 = OpExtInst %6 %1 PackHalf2x16 %69 +OpStore %31 %70 +%71 = OpLoad %6 %31 +%72 = OpExtInst %18 %1 UnpackSnorm4x8 %71 +OpStore %46 %72 +%73 = OpLoad %6 %31 +%74 = OpExtInst %18 %1 UnpackUnorm4x8 %73 +OpStore %46 %74 +%75 = OpLoad %6 %31 +%76 = OpExtInst %17 %1 UnpackSnorm2x16 %75 +OpStore %43 %76 +%77 = OpLoad %6 %31 +%78 = OpExtInst %17 %1 UnpackUnorm2x16 %77 +OpStore %43 %78 +%79 = OpLoad %6 %31 +%80 = OpExtInst %17 %1 UnpackHalf2x16 %79 +OpStore %43 %80 +%81 = OpLoad %4 %19 +%82 = OpLoad %4 %19 +%83 = OpBitFieldInsert %4 %81 %82 %9 %10 +OpStore %19 %83 +%84 = OpLoad %11 %22 +%85 = OpLoad %11 %22 +%86 = OpBitFieldInsert %11 %84 %85 %9 %10 +OpStore %22 %86 +%87 = OpLoad %12 %25 +%88 = OpLoad %12 %25 +%89 = OpBitFieldInsert %12 %87 %88 %9 %10 +OpStore %25 %89 +%90 = OpLoad %13 %28 +%91 = OpLoad %13 %28 +%92 = OpBitFieldInsert %13 %90 %91 %9 %10 +OpStore %28 %92 +%93 = OpLoad %6 %31 +%94 = OpLoad %6 %31 +%95 = OpBitFieldInsert %6 %93 %94 %9 %10 +OpStore %31 %95 +%96 = OpLoad %14 %34 +%97 = OpLoad %14 %34 +%98 = OpBitFieldInsert %14 %96 %97 %9 %10 +OpStore %34 %98 +%99 = OpLoad %15 %37 +%100 = OpLoad %15 %37 +%101 = OpBitFieldInsert %15 %99 %100 %9 %10 +OpStore %37 %101 +%102 = OpLoad %16 %40 +%103 = OpLoad %16 %40 +%104 = OpBitFieldInsert %16 %102 %103 %9 %10 +OpStore %40 %104 +%105 = OpLoad %4 %19 +%106 = OpBitFieldSExtract %4 %105 %9 %10 +OpStore %19 %106 +%107 = OpLoad %11 %22 +%108 = OpBitFieldSExtract %11 %107 %9 %10 +OpStore %22 %108 +%109 = OpLoad %12 %25 +%110 = OpBitFieldSExtract %12 %109 %9 %10 +OpStore %25 %110 +%111 = OpLoad %13 %28 +%112 = OpBitFieldSExtract %13 %111 %9 %10 +OpStore %28 %112 +%113 = OpLoad %6 %31 +%114 = OpBitFieldUExtract %6 %113 %9 %10 +OpStore %31 %114 +%115 = OpLoad %14 %34 +%116 = OpBitFieldUExtract %14 %115 %9 %10 +OpStore %34 %116 +%117 = OpLoad %15 %37 +%118 = OpBitFieldUExtract %15 %117 %9 %10 +OpStore %37 %118 +%119 = OpLoad %16 %40 +%120 = OpBitFieldUExtract %16 %119 %9 %10 +OpStore %40 %120 +%121 = OpLoad %4 %19 +%122 = OpExtInst %4 %1 FindILsb %121 +OpStore %19 %122 +%123 = OpLoad %14 %34 +%124 = OpExtInst %14 %1 FindILsb %123 +OpStore %34 %124 +%125 = OpLoad %12 %25 +%126 = OpExtInst %12 %1 FindSMsb %125 +OpStore %25 %126 +%127 = OpLoad %6 %31 +%128 = OpExtInst %6 %1 FindUMsb %127 +OpStore %31 %128 +%129 = OpLoad %4 %19 +%130 = OpBitCount %4 %129 +OpStore %19 %130 +%131 = OpLoad %11 %22 +%132 = OpBitCount %11 %131 +OpStore %22 %132 +%133 = OpLoad %12 %25 +%134 = OpBitCount %12 %133 +OpStore %25 %134 +%135 = OpLoad %13 %28 +%136 = OpBitCount %13 %135 +OpStore %28 %136 +%137 = OpLoad %6 %31 +%138 = OpBitCount %6 %137 +OpStore %31 %138 +%139 = OpLoad %14 %34 +%140 = OpBitCount %14 %139 +OpStore %34 %140 +%141 = OpLoad %15 %37 +%142 = OpBitCount %15 %141 +OpStore %37 %142 +%143 = OpLoad %16 %40 +%144 = OpBitCount %16 %143 +OpStore %40 %144 +%145 = OpLoad %4 %19 +%146 = OpBitReverse %4 %145 +OpStore %19 %146 +%147 = OpLoad %11 %22 +%148 = OpBitReverse %11 %147 +OpStore %22 %148 +%149 = OpLoad %12 %25 +%150 = OpBitReverse %12 %149 +OpStore %25 %150 +%151 = OpLoad %13 %28 +%152 = OpBitReverse %13 %151 +OpStore %28 %152 +%153 = OpLoad %6 %31 +%154 = OpBitReverse %6 %153 +OpStore %31 %154 +%155 = OpLoad %14 %34 +%156 = OpBitReverse %14 %155 +OpStore %34 %156 +%157 = OpLoad %15 %37 +%158 = OpBitReverse %15 %157 +OpStore %37 %158 +%159 = OpLoad %16 %40 +%160 = OpBitReverse %16 %159 +OpStore %40 %160 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 887cdb6ad..070504436 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 213 +; Bound: 216 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %51 "main" %48 -OpExecutionMode %51 LocalSize 64 1 1 +OpEntryPoint GLCompute %54 "main" %51 +OpExecutionMode %54 LocalSize 64 1 1 OpSource GLSL 450 OpName %3 "NUM_PARTICLES" OpMemberName %16 0 "pos" @@ -32,12 +32,12 @@ OpName %32 "cMass" OpName %34 "cVel" OpName %36 "colVel" OpName %38 "cMassCount" -OpName %40 "cVelCount" -OpName %41 "pos" -OpName %43 "vel" -OpName %45 "i" -OpName %48 "global_invocation_id" -OpName %51 "main" +OpName %41 "cVelCount" +OpName %43 "pos" +OpName %45 "vel" +OpName %47 "i" +OpName %51 "global_invocation_id" +OpName %54 "main" OpMemberDecorate %16 0 Offset 0 OpMemberDecorate %16 1 Offset 8 OpMemberDecorate %17 0 Offset 0 @@ -60,7 +60,7 @@ OpDecorate %19 Block OpDecorate %26 DescriptorSet 0 OpDecorate %26 Binding 2 OpDecorate %19 Block -OpDecorate %48 BuiltIn GlobalInvocationId +OpDecorate %51 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 1500 @@ -93,250 +93,256 @@ OpDecorate %48 BuiltIn GlobalInvocationId %35 = OpConstantNull %15 %37 = OpConstantNull %15 %39 = OpTypePointer Function %8 -%42 = OpConstantNull %15 +%40 = OpConstantNull %8 +%42 = OpConstantNull %8 %44 = OpConstantNull %15 -%46 = OpTypePointer Function %4 -%49 = OpTypePointer Input %20 -%48 = OpVariable %49 Input -%52 = OpTypeFunction %2 -%53 = OpTypePointer Uniform %17 -%57 = OpTypeBool -%61 = OpTypePointer StorageBuffer %18 -%62 = OpTypePointer StorageBuffer %16 -%63 = OpTypePointer StorageBuffer %15 -%92 = OpTypePointer Uniform %6 -%106 = OpConstant %4 2 -%120 = OpConstant %4 3 -%155 = OpConstant %4 4 -%161 = OpConstant %4 5 -%167 = OpConstant %4 6 -%184 = OpTypePointer Function %6 -%51 = OpFunction %2 None %52 -%47 = OpLabel -%45 = OpVariable %46 Function %9 -%40 = OpVariable %39 Function %7 +%46 = OpConstantNull %15 +%48 = OpTypePointer Function %4 +%49 = OpConstantNull %4 +%52 = OpTypePointer Input %20 +%51 = OpVariable %52 Input +%55 = OpTypeFunction %2 +%56 = OpTypePointer Uniform %17 +%60 = OpTypeBool +%64 = OpTypePointer StorageBuffer %18 +%65 = OpTypePointer StorageBuffer %16 +%66 = OpTypePointer StorageBuffer %15 +%95 = OpTypePointer Uniform %6 +%109 = OpConstant %4 2 +%123 = OpConstant %4 3 +%158 = OpConstant %4 4 +%164 = OpConstant %4 5 +%170 = OpConstant %4 6 +%187 = OpTypePointer Function %6 +%54 = OpFunction %2 None %55 +%50 = OpLabel +%47 = OpVariable %48 Function %49 +%41 = OpVariable %39 Function %42 %34 = OpVariable %28 Function %35 %27 = OpVariable %28 Function %29 -%41 = OpVariable %28 Function %42 +%43 = OpVariable %28 Function %44 %36 = OpVariable %28 Function %37 %30 = OpVariable %28 Function %31 -%43 = OpVariable %28 Function %44 -%38 = OpVariable %39 Function %7 +%45 = OpVariable %28 Function %46 +%38 = OpVariable %39 Function %40 %32 = OpVariable %28 Function %33 -%50 = OpLoad %20 %48 -%54 = OpAccessChain %53 %21 %9 -OpBranch %55 -%55 = OpLabel -%56 = OpCompositeExtract %4 %50 0 -%58 = OpUGreaterThanEqual %57 %56 %3 -OpSelectionMerge %59 None -OpBranchConditional %58 %60 %59 -%60 = OpLabel +%53 = OpLoad %20 %51 +%57 = OpAccessChain %56 %21 %9 +OpBranch %58 +%58 = OpLabel +%59 = OpCompositeExtract %4 %53 0 +%61 = OpUGreaterThanEqual %60 %59 %3 +OpSelectionMerge %62 None +OpBranchConditional %61 %63 %62 +%63 = OpLabel OpReturn -%59 = OpLabel -%64 = OpAccessChain %63 %24 %9 %56 %9 -%65 = OpLoad %15 %64 -OpStore %27 %65 -%66 = OpAccessChain %63 %24 %9 %56 %11 -%67 = OpLoad %15 %66 -OpStore %30 %67 -%68 = OpCompositeConstruct %15 %5 %5 -OpStore %32 %68 -%69 = OpCompositeConstruct %15 %5 %5 -OpStore %34 %69 -%70 = OpCompositeConstruct %15 %5 %5 -OpStore %36 %70 -OpBranch %71 -%71 = OpLabel -OpLoopMerge %72 %74 None -OpBranch %73 -%73 = OpLabel -%75 = OpLoad %4 %45 -%76 = OpUGreaterThanEqual %57 %75 %3 -OpSelectionMerge %77 None -OpBranchConditional %76 %78 %77 -%78 = OpLabel -OpBranch %72 -%77 = OpLabel -%79 = OpLoad %4 %45 -%80 = OpIEqual %57 %79 %56 -OpSelectionMerge %81 None -OpBranchConditional %80 %82 %81 -%82 = OpLabel -OpBranch %74 -%81 = OpLabel -%83 = OpLoad %4 %45 -%84 = OpAccessChain %63 %24 %9 %83 %9 -%85 = OpLoad %15 %84 -OpStore %41 %85 -%86 = OpLoad %4 %45 -%87 = OpAccessChain %63 %24 %9 %86 %11 -%88 = OpLoad %15 %87 -OpStore %43 %88 -%89 = OpLoad %15 %41 -%90 = OpLoad %15 %27 -%91 = OpExtInst %6 %1 Distance %89 %90 -%93 = OpAccessChain %92 %54 %11 -%94 = OpLoad %6 %93 -%95 = OpFOrdLessThan %57 %91 %94 -OpSelectionMerge %96 None -OpBranchConditional %95 %97 %96 -%97 = OpLabel -%98 = OpLoad %15 %32 -%99 = OpLoad %15 %41 -%100 = OpFAdd %15 %98 %99 -OpStore %32 %100 -%101 = OpLoad %8 %38 -%102 = OpIAdd %8 %101 %10 -OpStore %38 %102 -OpBranch %96 -%96 = OpLabel -%103 = OpLoad %15 %41 -%104 = OpLoad %15 %27 -%105 = OpExtInst %6 %1 Distance %103 %104 -%107 = OpAccessChain %92 %54 %106 -%108 = OpLoad %6 %107 -%109 = OpFOrdLessThan %57 %105 %108 -OpSelectionMerge %110 None -OpBranchConditional %109 %111 %110 -%111 = OpLabel -%112 = OpLoad %15 %36 -%113 = OpLoad %15 %41 -%114 = OpLoad %15 %27 -%115 = OpFSub %15 %113 %114 -%116 = OpFSub %15 %112 %115 -OpStore %36 %116 -OpBranch %110 -%110 = OpLabel -%117 = OpLoad %15 %41 -%118 = OpLoad %15 %27 -%119 = OpExtInst %6 %1 Distance %117 %118 -%121 = OpAccessChain %92 %54 %120 -%122 = OpLoad %6 %121 -%123 = OpFOrdLessThan %57 %119 %122 -OpSelectionMerge %124 None -OpBranchConditional %123 %125 %124 -%125 = OpLabel -%126 = OpLoad %15 %34 -%127 = OpLoad %15 %43 -%128 = OpFAdd %15 %126 %127 -OpStore %34 %128 -%129 = OpLoad %8 %40 -%130 = OpIAdd %8 %129 %10 -OpStore %40 %130 -OpBranch %124 -%124 = OpLabel +%62 = OpLabel +%67 = OpAccessChain %66 %24 %9 %59 %9 +%68 = OpLoad %15 %67 +OpStore %27 %68 +%69 = OpAccessChain %66 %24 %9 %59 %11 +%70 = OpLoad %15 %69 +OpStore %30 %70 +%71 = OpCompositeConstruct %15 %5 %5 +OpStore %32 %71 +%72 = OpCompositeConstruct %15 %5 %5 +OpStore %34 %72 +%73 = OpCompositeConstruct %15 %5 %5 +OpStore %36 %73 +OpStore %38 %7 +OpStore %41 %7 +OpStore %47 %9 OpBranch %74 %74 = OpLabel -%131 = OpLoad %4 %45 -%132 = OpIAdd %4 %131 %11 -OpStore %45 %132 -OpBranch %71 -%72 = OpLabel -%133 = OpLoad %8 %38 -%134 = OpSGreaterThan %57 %133 %7 -OpSelectionMerge %135 None -OpBranchConditional %134 %136 %135 -%136 = OpLabel -%137 = OpLoad %15 %32 -%138 = OpLoad %8 %38 -%139 = OpConvertSToF %6 %138 -%140 = OpCompositeConstruct %15 %139 %139 -%141 = OpFDiv %15 %137 %140 -%142 = OpLoad %15 %27 -%143 = OpFSub %15 %141 %142 -OpStore %32 %143 -OpBranch %135 -%135 = OpLabel -%144 = OpLoad %8 %40 -%145 = OpSGreaterThan %57 %144 %7 -OpSelectionMerge %146 None -OpBranchConditional %145 %147 %146 -%147 = OpLabel -%148 = OpLoad %15 %34 -%149 = OpLoad %8 %40 -%150 = OpConvertSToF %6 %149 -%151 = OpCompositeConstruct %15 %150 %150 -%152 = OpFDiv %15 %148 %151 -OpStore %34 %152 -OpBranch %146 -%146 = OpLabel -%153 = OpLoad %15 %30 -%154 = OpLoad %15 %32 -%156 = OpAccessChain %92 %54 %155 -%157 = OpLoad %6 %156 -%158 = OpVectorTimesScalar %15 %154 %157 -%159 = OpFAdd %15 %153 %158 -%160 = OpLoad %15 %36 -%162 = OpAccessChain %92 %54 %161 -%163 = OpLoad %6 %162 -%164 = OpVectorTimesScalar %15 %160 %163 -%165 = OpFAdd %15 %159 %164 -%166 = OpLoad %15 %34 -%168 = OpAccessChain %92 %54 %167 -%169 = OpLoad %6 %168 -%170 = OpVectorTimesScalar %15 %166 %169 -%171 = OpFAdd %15 %165 %170 -OpStore %30 %171 -%172 = OpLoad %15 %30 -%173 = OpExtInst %15 %1 Normalize %172 -%174 = OpLoad %15 %30 -%175 = OpExtInst %6 %1 Length %174 -%176 = OpExtInst %6 %1 FClamp %175 %5 %12 -%177 = OpVectorTimesScalar %15 %173 %176 -OpStore %30 %177 -%178 = OpLoad %15 %27 -%179 = OpLoad %15 %30 -%180 = OpAccessChain %92 %54 %9 -%181 = OpLoad %6 %180 -%182 = OpVectorTimesScalar %15 %179 %181 -%183 = OpFAdd %15 %178 %182 -OpStore %27 %183 -%185 = OpAccessChain %184 %27 %9 -%186 = OpLoad %6 %185 -%187 = OpFOrdLessThan %57 %186 %13 -OpSelectionMerge %188 None -OpBranchConditional %187 %189 %188 -%189 = OpLabel -%190 = OpAccessChain %184 %27 %9 -OpStore %190 %14 -OpBranch %188 -%188 = OpLabel -%191 = OpAccessChain %184 %27 %9 -%192 = OpLoad %6 %191 -%193 = OpFOrdGreaterThan %57 %192 %14 -OpSelectionMerge %194 None -OpBranchConditional %193 %195 %194 -%195 = OpLabel -%196 = OpAccessChain %184 %27 %9 -OpStore %196 %13 -OpBranch %194 -%194 = OpLabel -%197 = OpAccessChain %184 %27 %11 -%198 = OpLoad %6 %197 -%199 = OpFOrdLessThan %57 %198 %13 -OpSelectionMerge %200 None -OpBranchConditional %199 %201 %200 -%201 = OpLabel -%202 = OpAccessChain %184 %27 %11 -OpStore %202 %14 -OpBranch %200 -%200 = OpLabel -%203 = OpAccessChain %184 %27 %11 -%204 = OpLoad %6 %203 -%205 = OpFOrdGreaterThan %57 %204 %14 -OpSelectionMerge %206 None -OpBranchConditional %205 %207 %206 -%207 = OpLabel -%208 = OpAccessChain %184 %27 %11 -OpStore %208 %13 -OpBranch %206 -%206 = OpLabel -%209 = OpLoad %15 %27 -%210 = OpAccessChain %63 %26 %9 %56 %9 -OpStore %210 %209 -%211 = OpLoad %15 %30 -%212 = OpAccessChain %63 %26 %9 %56 %11 -OpStore %212 %211 +OpLoopMerge %75 %77 None +OpBranch %76 +%76 = OpLabel +%78 = OpLoad %4 %47 +%79 = OpUGreaterThanEqual %60 %78 %3 +OpSelectionMerge %80 None +OpBranchConditional %79 %81 %80 +%81 = OpLabel +OpBranch %75 +%80 = OpLabel +%82 = OpLoad %4 %47 +%83 = OpIEqual %60 %82 %59 +OpSelectionMerge %84 None +OpBranchConditional %83 %85 %84 +%85 = OpLabel +OpBranch %77 +%84 = OpLabel +%86 = OpLoad %4 %47 +%87 = OpAccessChain %66 %24 %9 %86 %9 +%88 = OpLoad %15 %87 +OpStore %43 %88 +%89 = OpLoad %4 %47 +%90 = OpAccessChain %66 %24 %9 %89 %11 +%91 = OpLoad %15 %90 +OpStore %45 %91 +%92 = OpLoad %15 %43 +%93 = OpLoad %15 %27 +%94 = OpExtInst %6 %1 Distance %92 %93 +%96 = OpAccessChain %95 %57 %11 +%97 = OpLoad %6 %96 +%98 = OpFOrdLessThan %60 %94 %97 +OpSelectionMerge %99 None +OpBranchConditional %98 %100 %99 +%100 = OpLabel +%101 = OpLoad %15 %32 +%102 = OpLoad %15 %43 +%103 = OpFAdd %15 %101 %102 +OpStore %32 %103 +%104 = OpLoad %8 %38 +%105 = OpIAdd %8 %104 %10 +OpStore %38 %105 +OpBranch %99 +%99 = OpLabel +%106 = OpLoad %15 %43 +%107 = OpLoad %15 %27 +%108 = OpExtInst %6 %1 Distance %106 %107 +%110 = OpAccessChain %95 %57 %109 +%111 = OpLoad %6 %110 +%112 = OpFOrdLessThan %60 %108 %111 +OpSelectionMerge %113 None +OpBranchConditional %112 %114 %113 +%114 = OpLabel +%115 = OpLoad %15 %36 +%116 = OpLoad %15 %43 +%117 = OpLoad %15 %27 +%118 = OpFSub %15 %116 %117 +%119 = OpFSub %15 %115 %118 +OpStore %36 %119 +OpBranch %113 +%113 = OpLabel +%120 = OpLoad %15 %43 +%121 = OpLoad %15 %27 +%122 = OpExtInst %6 %1 Distance %120 %121 +%124 = OpAccessChain %95 %57 %123 +%125 = OpLoad %6 %124 +%126 = OpFOrdLessThan %60 %122 %125 +OpSelectionMerge %127 None +OpBranchConditional %126 %128 %127 +%128 = OpLabel +%129 = OpLoad %15 %34 +%130 = OpLoad %15 %45 +%131 = OpFAdd %15 %129 %130 +OpStore %34 %131 +%132 = OpLoad %8 %41 +%133 = OpIAdd %8 %132 %10 +OpStore %41 %133 +OpBranch %127 +%127 = OpLabel +OpBranch %77 +%77 = OpLabel +%134 = OpLoad %4 %47 +%135 = OpIAdd %4 %134 %11 +OpStore %47 %135 +OpBranch %74 +%75 = OpLabel +%136 = OpLoad %8 %38 +%137 = OpSGreaterThan %60 %136 %7 +OpSelectionMerge %138 None +OpBranchConditional %137 %139 %138 +%139 = OpLabel +%140 = OpLoad %15 %32 +%141 = OpLoad %8 %38 +%142 = OpConvertSToF %6 %141 +%143 = OpCompositeConstruct %15 %142 %142 +%144 = OpFDiv %15 %140 %143 +%145 = OpLoad %15 %27 +%146 = OpFSub %15 %144 %145 +OpStore %32 %146 +OpBranch %138 +%138 = OpLabel +%147 = OpLoad %8 %41 +%148 = OpSGreaterThan %60 %147 %7 +OpSelectionMerge %149 None +OpBranchConditional %148 %150 %149 +%150 = OpLabel +%151 = OpLoad %15 %34 +%152 = OpLoad %8 %41 +%153 = OpConvertSToF %6 %152 +%154 = OpCompositeConstruct %15 %153 %153 +%155 = OpFDiv %15 %151 %154 +OpStore %34 %155 +OpBranch %149 +%149 = OpLabel +%156 = OpLoad %15 %30 +%157 = OpLoad %15 %32 +%159 = OpAccessChain %95 %57 %158 +%160 = OpLoad %6 %159 +%161 = OpVectorTimesScalar %15 %157 %160 +%162 = OpFAdd %15 %156 %161 +%163 = OpLoad %15 %36 +%165 = OpAccessChain %95 %57 %164 +%166 = OpLoad %6 %165 +%167 = OpVectorTimesScalar %15 %163 %166 +%168 = OpFAdd %15 %162 %167 +%169 = OpLoad %15 %34 +%171 = OpAccessChain %95 %57 %170 +%172 = OpLoad %6 %171 +%173 = OpVectorTimesScalar %15 %169 %172 +%174 = OpFAdd %15 %168 %173 +OpStore %30 %174 +%175 = OpLoad %15 %30 +%176 = OpExtInst %15 %1 Normalize %175 +%177 = OpLoad %15 %30 +%178 = OpExtInst %6 %1 Length %177 +%179 = OpExtInst %6 %1 FClamp %178 %5 %12 +%180 = OpVectorTimesScalar %15 %176 %179 +OpStore %30 %180 +%181 = OpLoad %15 %27 +%182 = OpLoad %15 %30 +%183 = OpAccessChain %95 %57 %9 +%184 = OpLoad %6 %183 +%185 = OpVectorTimesScalar %15 %182 %184 +%186 = OpFAdd %15 %181 %185 +OpStore %27 %186 +%188 = OpAccessChain %187 %27 %9 +%189 = OpLoad %6 %188 +%190 = OpFOrdLessThan %60 %189 %13 +OpSelectionMerge %191 None +OpBranchConditional %190 %192 %191 +%192 = OpLabel +%193 = OpAccessChain %187 %27 %9 +OpStore %193 %14 +OpBranch %191 +%191 = OpLabel +%194 = OpAccessChain %187 %27 %9 +%195 = OpLoad %6 %194 +%196 = OpFOrdGreaterThan %60 %195 %14 +OpSelectionMerge %197 None +OpBranchConditional %196 %198 %197 +%198 = OpLabel +%199 = OpAccessChain %187 %27 %9 +OpStore %199 %13 +OpBranch %197 +%197 = OpLabel +%200 = OpAccessChain %187 %27 %11 +%201 = OpLoad %6 %200 +%202 = OpFOrdLessThan %60 %201 %13 +OpSelectionMerge %203 None +OpBranchConditional %202 %204 %203 +%204 = OpLabel +%205 = OpAccessChain %187 %27 %11 +OpStore %205 %14 +OpBranch %203 +%203 = OpLabel +%206 = OpAccessChain %187 %27 %11 +%207 = OpLoad %6 %206 +%208 = OpFOrdGreaterThan %60 %207 %14 +OpSelectionMerge %209 None +OpBranchConditional %208 %210 %209 +%210 = OpLabel +%211 = OpAccessChain %187 %27 %11 +OpStore %211 %13 +OpBranch %209 +%209 = OpLabel +%212 = OpLoad %15 %27 +%213 = OpAccessChain %66 %26 %9 %59 %9 +OpStore %213 %212 +%214 = OpLoad %15 %30 +%215 = OpAccessChain %66 %26 %9 %59 %11 +OpStore %215 %214 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index 6e6483da1..7be8c912c 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -1,29 +1,29 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 60 +; Bound: 63 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %49 "main" %46 -OpExecutionMode %49 LocalSize 1 1 1 +OpEntryPoint GLCompute %52 "main" %49 +OpExecutionMode %52 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %9 0 "data" OpName %9 "PrimeIndices" OpName %11 "v_indices" OpName %13 "n" OpName %16 "i" -OpName %18 "n_base" -OpName %19 "collatz_iterations" -OpName %46 "global_id" -OpName %49 "main" +OpName %19 "n_base" +OpName %20 "collatz_iterations" +OpName %49 "global_id" +OpName %52 "main" OpDecorate %8 ArrayStride 4 OpMemberDecorate %9 0 Offset 0 OpDecorate %11 DescriptorSet 0 OpDecorate %11 Binding 0 OpDecorate %9 Block -OpDecorate %46 BuiltIn GlobalInvocationId +OpDecorate %49 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -37,71 +37,77 @@ OpDecorate %46 BuiltIn GlobalInvocationId %11 = OpVariable %12 StorageBuffer %14 = OpTypePointer Function %4 %15 = OpConstantNull %4 -%20 = OpTypeFunction %4 %4 -%27 = OpTypeBool -%47 = OpTypePointer Input %10 -%46 = OpVariable %47 Input -%50 = OpTypeFunction %2 -%52 = OpTypePointer StorageBuffer %8 -%54 = OpTypePointer StorageBuffer %4 -%19 = OpFunction %4 None %20 -%18 = OpFunctionParameter %4 -%17 = OpLabel +%17 = OpConstantNull %4 +%21 = OpTypeFunction %4 %4 +%28 = OpTypeBool +%50 = OpTypePointer Input %10 +%49 = OpVariable %50 Input +%53 = OpTypeFunction %2 +%55 = OpTypePointer StorageBuffer %8 +%57 = OpTypePointer StorageBuffer %4 +%20 = OpFunction %4 None %21 +%19 = OpFunctionParameter %4 +%18 = OpLabel %13 = OpVariable %14 Function %15 -%16 = OpVariable %14 Function %3 -OpBranch %21 -%21 = OpLabel -OpStore %13 %18 +%16 = OpVariable %14 Function %17 OpBranch %22 %22 = OpLabel -OpLoopMerge %23 %25 None -OpBranch %24 -%24 = OpLabel -%26 = OpLoad %4 %13 -%28 = OpUGreaterThan %27 %26 %5 -OpSelectionMerge %29 None -OpBranchConditional %28 %29 %30 -%30 = OpLabel +OpStore %13 %19 +OpStore %16 %3 OpBranch %23 -%29 = OpLabel -%31 = OpLoad %4 %13 -%32 = OpUMod %4 %31 %6 -%33 = OpIEqual %27 %32 %3 -OpSelectionMerge %34 None -OpBranchConditional %33 %35 %36 -%35 = OpLabel -%37 = OpLoad %4 %13 -%38 = OpUDiv %4 %37 %6 -OpStore %13 %38 -OpBranch %34 -%36 = OpLabel -%39 = OpLoad %4 %13 -%40 = OpIMul %4 %7 %39 -%41 = OpIAdd %4 %40 %5 -OpStore %13 %41 -OpBranch %34 -%34 = OpLabel -%42 = OpLoad %4 %16 -%43 = OpIAdd %4 %42 %5 -OpStore %16 %43 +%23 = OpLabel +OpLoopMerge %24 %26 None OpBranch %25 %25 = OpLabel -OpBranch %22 -%23 = OpLabel -%44 = OpLoad %4 %16 -OpReturnValue %44 +%27 = OpLoad %4 %13 +%29 = OpUGreaterThan %28 %27 %5 +OpSelectionMerge %30 None +OpBranchConditional %29 %30 %31 +%31 = OpLabel +OpBranch %24 +%30 = OpLabel +OpBranch %32 +%32 = OpLabel +%34 = OpLoad %4 %13 +%35 = OpUMod %4 %34 %6 +%36 = OpIEqual %28 %35 %3 +OpSelectionMerge %37 None +OpBranchConditional %36 %38 %39 +%38 = OpLabel +%40 = OpLoad %4 %13 +%41 = OpUDiv %4 %40 %6 +OpStore %13 %41 +OpBranch %37 +%39 = OpLabel +%42 = OpLoad %4 %13 +%43 = OpIMul %4 %7 %42 +%44 = OpIAdd %4 %43 %5 +OpStore %13 %44 +OpBranch %37 +%37 = OpLabel +%45 = OpLoad %4 %16 +%46 = OpIAdd %4 %45 %5 +OpStore %16 %46 +OpBranch %33 +%33 = OpLabel +OpBranch %26 +%26 = OpLabel +OpBranch %23 +%24 = OpLabel +%47 = OpLoad %4 %16 +OpReturnValue %47 OpFunctionEnd -%49 = OpFunction %2 None %50 -%45 = OpLabel -%48 = OpLoad %10 %46 -OpBranch %51 -%51 = OpLabel -%53 = OpCompositeExtract %4 %48 0 -%55 = OpCompositeExtract %4 %48 0 -%56 = OpAccessChain %54 %11 %3 %55 -%57 = OpLoad %4 %56 -%58 = OpFunctionCall %4 %19 %57 -%59 = OpAccessChain %54 %11 %3 %53 -OpStore %59 %58 +%52 = OpFunction %2 None %53 +%48 = OpLabel +%51 = OpLoad %10 %49 +OpBranch %54 +%54 = OpLabel +%56 = OpCompositeExtract %4 %51 0 +%58 = OpCompositeExtract %4 %51 0 +%59 = OpAccessChain %57 %11 %3 %58 +%60 = OpLoad %4 %59 +%61 = OpFunctionCall %4 %20 %60 +%62 = OpAccessChain %57 %11 %3 %56 +OpStore %62 %61 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index 99a367c64..0c4f7a1d7 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -7,18 +7,18 @@ OpCapability Float64 OpCapability Geometry %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %24 "main" %16 %19 %22 -OpExecutionMode %24 OriginUpperLeft +OpEntryPoint Fragment %25 "main" %17 %20 %23 +OpExecutionMode %25 OriginUpperLeft OpMemberDecorate %8 0 Offset 0 OpMemberDecorate %8 1 Offset 16 OpMemberDecorate %10 0 Offset 0 OpMemberDecorate %10 1 Offset 16 -OpDecorate %12 Block -OpMemberDecorate %12 0 Offset 0 -OpDecorate %16 Location 0 -OpDecorate %19 BuiltIn PrimitiveId -OpDecorate %19 Flat -OpDecorate %22 Location 0 +OpDecorate %13 Block +OpMemberDecorate %13 0 Offset 0 +OpDecorate %17 Location 0 +OpDecorate %20 BuiltIn PrimitiveId +OpDecorate %20 Flat +OpDecorate %23 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -28,49 +28,49 @@ OpDecorate %22 Location 0 %8 = OpTypeStruct %5 %6 %9 = OpTypeVector %4 4 %10 = OpTypeStruct %9 %5 -%12 = OpTypeStruct %8 -%13 = OpTypePointer PushConstant %12 -%11 = OpVariable %13 PushConstant -%17 = OpTypePointer Input %9 -%16 = OpVariable %17 Input -%20 = OpTypePointer Input %5 -%19 = OpVariable %20 Input -%23 = OpTypePointer Output %9 -%22 = OpVariable %23 Output -%25 = OpTypeFunction %2 -%26 = OpTypePointer PushConstant %8 -%27 = OpConstant %5 0 -%31 = OpTypePointer PushConstant %5 -%34 = OpTypeBool -%40 = OpTypeVector %4 3 -%24 = OpFunction %2 None %25 -%14 = OpLabel -%18 = OpLoad %9 %16 -%21 = OpLoad %5 %19 -%15 = OpCompositeConstruct %10 %18 %21 -%28 = OpAccessChain %26 %11 %27 -OpBranch %29 -%29 = OpLabel -%30 = OpCompositeExtract %5 %15 1 -%32 = OpAccessChain %31 %28 %27 -%33 = OpLoad %5 %32 -%35 = OpIEqual %34 %30 %33 -OpSelectionMerge %36 None -OpBranchConditional %35 %37 %38 -%37 = OpLabel -%39 = OpCompositeExtract %9 %15 0 -OpStore %22 %39 -OpReturn +%11 = OpTypeVector %4 3 +%13 = OpTypeStruct %8 +%14 = OpTypePointer PushConstant %13 +%12 = OpVariable %14 PushConstant +%18 = OpTypePointer Input %9 +%17 = OpVariable %18 Input +%21 = OpTypePointer Input %5 +%20 = OpVariable %21 Input +%24 = OpTypePointer Output %9 +%23 = OpVariable %24 Output +%26 = OpTypeFunction %2 +%27 = OpTypePointer PushConstant %8 +%28 = OpConstant %5 0 +%32 = OpTypePointer PushConstant %5 +%35 = OpTypeBool +%25 = OpFunction %2 None %26 +%15 = OpLabel +%19 = OpLoad %9 %17 +%22 = OpLoad %5 %20 +%16 = OpCompositeConstruct %10 %19 %22 +%29 = OpAccessChain %27 %12 %28 +OpBranch %30 +%30 = OpLabel +%31 = OpCompositeExtract %5 %16 1 +%33 = OpAccessChain %32 %29 %28 +%34 = OpLoad %5 %33 +%36 = OpIEqual %35 %31 %34 +OpSelectionMerge %37 None +OpBranchConditional %36 %38 %39 %38 = OpLabel -%41 = OpCompositeConstruct %40 %3 %3 %3 -%42 = OpCompositeExtract %9 %15 0 -%43 = OpVectorShuffle %40 %42 %42 0 1 2 -%44 = OpFSub %40 %41 %43 -%45 = OpCompositeExtract %9 %15 0 +%40 = OpCompositeExtract %9 %16 0 +OpStore %23 %40 +OpReturn +%39 = OpLabel +%41 = OpCompositeConstruct %11 %3 %3 %3 +%42 = OpCompositeExtract %9 %16 0 +%43 = OpVectorShuffle %11 %42 %42 0 1 2 +%44 = OpFSub %11 %41 %43 +%45 = OpCompositeExtract %9 %16 0 %46 = OpCompositeExtract %4 %45 3 %47 = OpCompositeConstruct %9 %44 %46 -OpStore %22 %47 +OpStore %23 %47 OpReturn -%36 = OpLabel +%37 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/functions.spvasm b/tests/out/spv/functions.spvasm index da2d240aa..bfebd09f8 100644 --- a/tests/out/spv/functions.spvasm +++ b/tests/out/spv/functions.spvasm @@ -18,55 +18,55 @@ OpExecutionMode %74 LocalSize 1 1 1 %10 = OpConstant %7 4 %11 = OpConstant %7 2 %12 = OpTypeVector %4 2 -%15 = OpTypeFunction %12 -%23 = OpTypeFunction %7 -%25 = OpTypeVector %7 2 -%37 = OpTypeVector %9 3 -%53 = OpTypeVector %7 4 +%13 = OpTypeVector %7 2 +%14 = OpTypeVector %9 3 +%15 = OpTypeVector %7 4 +%18 = OpTypeFunction %12 +%26 = OpTypeFunction %7 %75 = OpTypeFunction %2 -%29 = OpConstantNull %7 -%41 = OpConstantNull %9 +%31 = OpConstantNull %7 +%42 = OpConstantNull %9 %57 = OpConstantNull %7 -%14 = OpFunction %12 None %15 -%13 = OpLabel -OpBranch %16 +%17 = OpFunction %12 None %18 %16 = OpLabel -%17 = OpCompositeConstruct %12 %3 %3 -%18 = OpCompositeConstruct %12 %5 %5 -%19 = OpCompositeConstruct %12 %5 %5 -%20 = OpExtInst %12 %1 Fma %17 %18 %19 -OpReturnValue %20 +OpBranch %19 +%19 = OpLabel +%20 = OpCompositeConstruct %12 %3 %3 +%21 = OpCompositeConstruct %12 %5 %5 +%22 = OpCompositeConstruct %12 %5 %5 +%23 = OpExtInst %12 %1 Fma %20 %21 %22 +OpReturnValue %23 OpFunctionEnd -%22 = OpFunction %7 None %23 -%21 = OpLabel -OpBranch %24 +%25 = OpFunction %7 None %26 %24 = OpLabel -%26 = OpCompositeConstruct %25 %6 %6 -%27 = OpCompositeConstruct %25 %6 %6 -%30 = OpCompositeExtract %7 %26 0 -%31 = OpCompositeExtract %7 %27 0 -%32 = OpIMul %7 %30 %31 -%33 = OpIAdd %7 %29 %32 -%34 = OpCompositeExtract %7 %26 1 -%35 = OpCompositeExtract %7 %27 1 -%36 = OpIMul %7 %34 %35 -%28 = OpIAdd %7 %33 %36 -%38 = OpCompositeConstruct %37 %8 %8 %8 -%39 = OpCompositeConstruct %37 %8 %8 %8 -%42 = OpCompositeExtract %9 %38 0 +OpBranch %27 +%27 = OpLabel +%28 = OpCompositeConstruct %13 %6 %6 +%29 = OpCompositeConstruct %13 %6 %6 +%32 = OpCompositeExtract %7 %28 0 +%33 = OpCompositeExtract %7 %29 0 +%34 = OpIMul %7 %32 %33 +%35 = OpIAdd %7 %31 %34 +%36 = OpCompositeExtract %7 %28 1 +%37 = OpCompositeExtract %7 %29 1 +%38 = OpIMul %7 %36 %37 +%30 = OpIAdd %7 %35 %38 +%39 = OpCompositeConstruct %14 %8 %8 %8 +%40 = OpCompositeConstruct %14 %8 %8 %8 %43 = OpCompositeExtract %9 %39 0 -%44 = OpIMul %9 %42 %43 -%45 = OpIAdd %9 %41 %44 -%46 = OpCompositeExtract %9 %38 1 +%44 = OpCompositeExtract %9 %40 0 +%45 = OpIMul %9 %43 %44 +%46 = OpIAdd %9 %42 %45 %47 = OpCompositeExtract %9 %39 1 -%48 = OpIMul %9 %46 %47 -%49 = OpIAdd %9 %45 %48 -%50 = OpCompositeExtract %9 %38 2 +%48 = OpCompositeExtract %9 %40 1 +%49 = OpIMul %9 %47 %48 +%50 = OpIAdd %9 %46 %49 %51 = OpCompositeExtract %9 %39 2 -%52 = OpIMul %9 %50 %51 -%40 = OpIAdd %9 %49 %52 -%54 = OpCompositeConstruct %53 %10 %10 %10 %10 -%55 = OpCompositeConstruct %53 %11 %11 %11 %11 +%52 = OpCompositeExtract %9 %40 2 +%53 = OpIMul %9 %51 %52 +%41 = OpIAdd %9 %50 %53 +%54 = OpCompositeConstruct %15 %10 %10 %10 %10 +%55 = OpCompositeConstruct %15 %11 %11 %11 %11 %58 = OpCompositeExtract %7 %54 0 %59 = OpCompositeExtract %7 %55 0 %60 = OpIMul %7 %58 %59 @@ -89,7 +89,7 @@ OpFunctionEnd %73 = OpLabel OpBranch %76 %76 = OpLabel -%77 = OpFunctionCall %12 %14 -%78 = OpFunctionCall %7 %22 +%77 = OpFunctionCall %12 %17 +%78 = OpFunctionCall %7 %25 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 2c1691c0c..ba39fa05c 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 169 +; Bound: 172 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %114 "main" -OpExecutionMode %114 LocalSize 1 1 1 +OpEntryPoint GLCompute %111 "main" +OpExecutionMode %111 LocalSize 1 1 1 OpDecorate %25 ArrayStride 4 OpMemberDecorate %27 0 Offset 0 OpMemberDecorate %27 1 Offset 12 @@ -114,126 +114,132 @@ OpMemberDecorate %65 0 Offset 0 %66 = OpTypePointer Uniform %65 %64 = OpVariable %66 Uniform %70 = OpTypeFunction %2 %26 -%71 = OpTypePointer StorageBuffer %29 -%72 = OpTypePointer Uniform %26 -%73 = OpTypePointer StorageBuffer %27 -%74 = OpTypePointer Uniform %35 -%75 = OpTypePointer Uniform %31 -%76 = OpTypePointer Uniform %38 -%77 = OpTypePointer Uniform %32 -%80 = OpTypePointer Function %8 -%83 = OpTypeFunction %2 -%84 = OpConstant %6 0 -%87 = OpTypePointer StorageBuffer %26 -%90 = OpTypePointer StorageBuffer %11 -%110 = OpTypePointer Function %11 -%112 = OpTypePointer Function %4 -%124 = OpTypePointer Workgroup %11 -%125 = OpTypePointer Uniform %37 -%126 = OpTypePointer Uniform %36 -%129 = OpTypePointer Uniform %34 -%130 = OpTypePointer Uniform %33 -%131 = OpTypePointer Uniform %30 -%136 = OpConstant %6 7 -%142 = OpConstant %6 6 -%144 = OpTypePointer StorageBuffer %28 -%145 = OpConstant %6 1 -%148 = OpConstant %6 5 -%150 = OpTypePointer Uniform %30 -%151 = OpTypePointer Uniform %11 -%152 = OpConstant %6 3 -%155 = OpConstant %6 4 -%157 = OpTypePointer StorageBuffer %11 -%168 = OpConstant %6 256 +%73 = OpTypePointer Function %8 +%74 = OpConstantNull %8 +%77 = OpTypeFunction %2 +%78 = OpTypePointer StorageBuffer %27 +%79 = OpConstant %6 0 +%82 = OpTypePointer StorageBuffer %26 +%85 = OpTypePointer StorageBuffer %11 +%105 = OpTypePointer Function %11 +%106 = OpConstantNull %11 +%108 = OpTypePointer Function %4 +%109 = OpConstantNull %4 +%113 = OpTypePointer StorageBuffer %29 +%115 = OpTypePointer Uniform %31 +%117 = OpTypePointer Uniform %26 +%119 = OpTypePointer Uniform %32 +%121 = OpTypePointer Uniform %35 +%123 = OpTypePointer Uniform %38 +%127 = OpTypePointer Workgroup %11 +%128 = OpTypePointer Uniform %37 +%129 = OpTypePointer Uniform %36 +%132 = OpTypePointer Uniform %34 +%133 = OpTypePointer Uniform %33 +%134 = OpTypePointer Uniform %30 +%139 = OpConstant %6 7 +%145 = OpConstant %6 6 +%147 = OpTypePointer StorageBuffer %28 +%148 = OpConstant %6 1 +%151 = OpConstant %6 5 +%153 = OpTypePointer Uniform %30 +%154 = OpTypePointer Uniform %11 +%155 = OpConstant %6 3 +%158 = OpConstant %6 4 +%160 = OpTypePointer StorageBuffer %11 +%171 = OpConstant %6 256 %69 = OpFunction %2 None %70 %68 = OpFunctionParameter %26 %67 = OpLabel -OpBranch %78 -%78 = OpLabel +OpBranch %71 +%71 = OpLabel OpReturn OpFunctionEnd -%82 = OpFunction %2 None %83 +%76 = OpFunction %2 None %77 +%75 = OpLabel +%72 = OpVariable %73 Function %74 +%80 = OpAccessChain %78 %46 %79 +OpBranch %81 %81 = OpLabel -%79 = OpVariable %80 Function %12 -%85 = OpAccessChain %73 %46 %84 -OpBranch %86 -%86 = OpLabel -%88 = OpCompositeConstruct %26 %10 %10 %10 -%89 = OpAccessChain %87 %85 %84 -OpStore %89 %88 -%91 = OpAccessChain %90 %85 %84 %84 -OpStore %91 %10 -%92 = OpAccessChain %90 %85 %84 %84 -OpStore %92 %14 -%93 = OpLoad %8 %79 -%94 = OpAccessChain %90 %85 %84 %93 -OpStore %94 %15 -%95 = OpLoad %27 %85 -%96 = OpCompositeExtract %26 %95 0 -%97 = OpCompositeExtract %26 %95 0 -%98 = OpVectorShuffle %28 %97 %97 2 0 -%99 = OpCompositeExtract %26 %95 0 -%100 = OpFunctionCall %2 %69 %99 -%101 = OpCompositeExtract %26 %95 0 -%102 = OpVectorTimesMatrix %26 %101 %41 -%103 = OpCompositeExtract %26 %95 0 -%104 = OpMatrixTimesVector %26 %41 %103 -%105 = OpCompositeExtract %26 %95 0 -%106 = OpVectorTimesScalar %26 %105 %14 -%107 = OpCompositeExtract %26 %95 0 -%108 = OpVectorTimesScalar %26 %107 %14 +%83 = OpCompositeConstruct %26 %10 %10 %10 +%84 = OpAccessChain %82 %80 %79 +OpStore %84 %83 +OpStore %72 %12 +%86 = OpAccessChain %85 %80 %79 %79 +OpStore %86 %10 +%87 = OpAccessChain %85 %80 %79 %79 +OpStore %87 %14 +%88 = OpLoad %8 %72 +%89 = OpAccessChain %85 %80 %79 %88 +OpStore %89 %15 +%90 = OpLoad %27 %80 +%91 = OpCompositeExtract %26 %90 0 +%92 = OpCompositeExtract %26 %90 0 +%93 = OpVectorShuffle %28 %92 %92 2 0 +%94 = OpCompositeExtract %26 %90 0 +%95 = OpFunctionCall %2 %69 %94 +%96 = OpCompositeExtract %26 %90 0 +%97 = OpVectorTimesMatrix %26 %96 %41 +%98 = OpCompositeExtract %26 %90 0 +%99 = OpMatrixTimesVector %26 %41 %98 +%100 = OpCompositeExtract %26 %90 0 +%101 = OpVectorTimesScalar %26 %100 %14 +%102 = OpCompositeExtract %26 %90 0 +%103 = OpVectorTimesScalar %26 %102 %14 OpReturn OpFunctionEnd -%114 = OpFunction %2 None %83 -%113 = OpLabel -%109 = OpVariable %110 Function %10 -%111 = OpVariable %112 Function %24 -%115 = OpAccessChain %73 %46 %84 -%116 = OpAccessChain %71 %49 %84 -%117 = OpAccessChain %75 %52 %84 -%118 = OpAccessChain %72 %55 %84 -%119 = OpAccessChain %77 %58 %84 -%120 = OpAccessChain %74 %61 %84 -%121 = OpAccessChain %76 %64 %84 -OpBranch %122 -%122 = OpLabel -%123 = OpFunctionCall %2 %82 -%127 = OpAccessChain %126 %121 %84 %84 -%128 = OpLoad %36 %127 -%132 = OpAccessChain %131 %120 %84 %84 %84 -%133 = OpLoad %30 %132 -%134 = OpMatrixTimesVector %28 %128 %133 -%135 = OpCompositeExtract %11 %134 0 -%137 = OpAccessChain %124 %42 %136 -OpStore %137 %135 -%138 = OpLoad %32 %119 -%139 = OpLoad %26 %118 -%140 = OpMatrixTimesVector %28 %138 %139 -%141 = OpCompositeExtract %11 %140 0 -%143 = OpAccessChain %124 %42 %142 -OpStore %143 %141 -%146 = OpAccessChain %90 %116 %145 %145 -%147 = OpLoad %11 %146 -%149 = OpAccessChain %124 %42 %148 -OpStore %149 %147 -%153 = OpAccessChain %151 %117 %84 %152 -%154 = OpLoad %11 %153 -%156 = OpAccessChain %124 %42 %155 -OpStore %156 %154 -%158 = OpAccessChain %157 %115 %145 -%159 = OpLoad %11 %158 -%160 = OpAccessChain %124 %42 %152 -OpStore %160 %159 -%161 = OpAccessChain %90 %115 %84 %84 +%111 = OpFunction %2 None %77 +%110 = OpLabel +%104 = OpVariable %105 Function %106 +%107 = OpVariable %108 Function %109 +%112 = OpAccessChain %78 %46 %79 +%114 = OpAccessChain %113 %49 %79 +%116 = OpAccessChain %115 %52 %79 +%118 = OpAccessChain %117 %55 %79 +%120 = OpAccessChain %119 %58 %79 +%122 = OpAccessChain %121 %61 %79 +%124 = OpAccessChain %123 %64 %79 +OpBranch %125 +%125 = OpLabel +%126 = OpFunctionCall %2 %76 +%130 = OpAccessChain %129 %124 %79 %79 +%131 = OpLoad %36 %130 +%135 = OpAccessChain %134 %122 %79 %79 %79 +%136 = OpLoad %30 %135 +%137 = OpMatrixTimesVector %28 %131 %136 +%138 = OpCompositeExtract %11 %137 0 +%140 = OpAccessChain %127 %42 %139 +OpStore %140 %138 +%141 = OpLoad %32 %120 +%142 = OpLoad %26 %118 +%143 = OpMatrixTimesVector %28 %141 %142 +%144 = OpCompositeExtract %11 %143 0 +%146 = OpAccessChain %127 %42 %145 +OpStore %146 %144 +%149 = OpAccessChain %85 %114 %148 %148 +%150 = OpLoad %11 %149 +%152 = OpAccessChain %127 %42 %151 +OpStore %152 %150 +%156 = OpAccessChain %154 %116 %79 %155 +%157 = OpLoad %11 %156 +%159 = OpAccessChain %127 %42 %158 +OpStore %159 %157 +%161 = OpAccessChain %160 %112 %148 %162 = OpLoad %11 %161 -%163 = OpAccessChain %124 %42 %23 +%163 = OpAccessChain %127 %42 %155 OpStore %163 %162 -%164 = OpAccessChain %157 %115 %145 -OpStore %164 %22 -%165 = OpArrayLength %6 %49 0 -%166 = OpConvertUToF %11 %165 -%167 = OpAccessChain %124 %42 %145 -OpStore %167 %166 -OpAtomicStore %44 %9 %168 %23 +%164 = OpAccessChain %85 %112 %79 %79 +%165 = OpLoad %11 %164 +%166 = OpAccessChain %127 %42 %23 +OpStore %166 %165 +%167 = OpAccessChain %160 %112 %148 +OpStore %167 %22 +%168 = OpArrayLength %6 %49 0 +%169 = OpConvertUToF %11 %168 +%170 = OpAccessChain %127 %42 %148 +OpStore %170 %169 +OpAtomicStore %44 %9 %171 %23 +OpStore %104 %10 +OpStore %107 %24 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 7a50df4a8..f6cd159d6 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -9,103 +9,103 @@ OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %80 "main" %77 -OpEntryPoint GLCompute %155 "depth_load" %153 -OpEntryPoint Vertex %176 "queries" %174 -OpEntryPoint Vertex %228 "levels_queries" %227 -OpEntryPoint Fragment %257 "texture_sample" %256 -OpEntryPoint Fragment %286 "texture_sample_comparison" %284 +OpEntryPoint GLCompute %84 "main" %81 +OpEntryPoint GLCompute %157 "depth_load" %155 +OpEntryPoint Vertex %178 "queries" %176 +OpEntryPoint Vertex %230 "levels_queries" %229 +OpEntryPoint Fragment %259 "texture_sample" %258 +OpEntryPoint Fragment %287 "texture_sample_comparison" %285 OpEntryPoint Fragment %306 "gather" %305 OpEntryPoint Fragment %341 "depth_no_comparison" %340 -OpExecutionMode %80 LocalSize 16 1 1 -OpExecutionMode %155 LocalSize 16 1 1 -OpExecutionMode %257 OriginUpperLeft -OpExecutionMode %286 OriginUpperLeft +OpExecutionMode %84 LocalSize 16 1 1 +OpExecutionMode %157 LocalSize 16 1 1 +OpExecutionMode %259 OriginUpperLeft +OpExecutionMode %287 OriginUpperLeft OpExecutionMode %306 OriginUpperLeft OpExecutionMode %341 OriginUpperLeft OpSource GLSL 450 -OpName %35 "image_mipmapped_src" -OpName %37 "image_multisampled_src" -OpName %39 "image_depth_multisampled_src" -OpName %41 "image_storage_src" -OpName %43 "image_array_src" -OpName %45 "image_dup_src" -OpName %47 "image_1d_src" -OpName %49 "image_dst" -OpName %51 "image_1d" -OpName %53 "image_2d" -OpName %55 "image_2d_u32" -OpName %56 "image_2d_i32" -OpName %58 "image_2d_array" -OpName %60 "image_cube" -OpName %62 "image_cube_array" -OpName %64 "image_3d" -OpName %66 "image_aa" -OpName %68 "sampler_reg" -OpName %70 "sampler_cmp" -OpName %72 "image_2d_depth" -OpName %74 "image_cube_depth" -OpName %77 "local_id" -OpName %80 "main" -OpName %153 "local_id" -OpName %155 "depth_load" -OpName %176 "queries" -OpName %228 "levels_queries" -OpName %257 "texture_sample" -OpName %286 "texture_sample_comparison" +OpName %39 "image_mipmapped_src" +OpName %41 "image_multisampled_src" +OpName %43 "image_depth_multisampled_src" +OpName %45 "image_storage_src" +OpName %47 "image_array_src" +OpName %49 "image_dup_src" +OpName %51 "image_1d_src" +OpName %53 "image_dst" +OpName %55 "image_1d" +OpName %57 "image_2d" +OpName %59 "image_2d_u32" +OpName %60 "image_2d_i32" +OpName %62 "image_2d_array" +OpName %64 "image_cube" +OpName %66 "image_cube_array" +OpName %68 "image_3d" +OpName %70 "image_aa" +OpName %72 "sampler_reg" +OpName %74 "sampler_cmp" +OpName %76 "image_2d_depth" +OpName %78 "image_cube_depth" +OpName %81 "local_id" +OpName %84 "main" +OpName %155 "local_id" +OpName %157 "depth_load" +OpName %178 "queries" +OpName %230 "levels_queries" +OpName %259 "texture_sample" +OpName %287 "texture_sample_comparison" OpName %306 "gather" OpName %341 "depth_no_comparison" -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 0 -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 3 OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 4 -OpDecorate %41 NonWritable +OpDecorate %39 Binding 0 OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 1 +OpDecorate %41 Binding 3 OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 5 +OpDecorate %43 Binding 4 OpDecorate %45 NonWritable OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 6 +OpDecorate %45 Binding 1 OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 7 -OpDecorate %49 NonReadable +OpDecorate %47 Binding 5 +OpDecorate %49 NonWritable OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 2 +OpDecorate %49 Binding 6 OpDecorate %51 DescriptorSet 0 -OpDecorate %51 Binding 0 +OpDecorate %51 Binding 7 +OpDecorate %53 NonReadable OpDecorate %53 DescriptorSet 0 -OpDecorate %53 Binding 1 +OpDecorate %53 Binding 2 OpDecorate %55 DescriptorSet 0 -OpDecorate %55 Binding 2 -OpDecorate %56 DescriptorSet 0 -OpDecorate %56 Binding 3 -OpDecorate %58 DescriptorSet 0 -OpDecorate %58 Binding 4 +OpDecorate %55 Binding 0 +OpDecorate %57 DescriptorSet 0 +OpDecorate %57 Binding 1 +OpDecorate %59 DescriptorSet 0 +OpDecorate %59 Binding 2 OpDecorate %60 DescriptorSet 0 -OpDecorate %60 Binding 5 +OpDecorate %60 Binding 3 OpDecorate %62 DescriptorSet 0 -OpDecorate %62 Binding 6 +OpDecorate %62 Binding 4 OpDecorate %64 DescriptorSet 0 -OpDecorate %64 Binding 7 +OpDecorate %64 Binding 5 OpDecorate %66 DescriptorSet 0 -OpDecorate %66 Binding 8 -OpDecorate %68 DescriptorSet 1 -OpDecorate %68 Binding 0 -OpDecorate %70 DescriptorSet 1 -OpDecorate %70 Binding 1 +OpDecorate %66 Binding 6 +OpDecorate %68 DescriptorSet 0 +OpDecorate %68 Binding 7 +OpDecorate %70 DescriptorSet 0 +OpDecorate %70 Binding 8 OpDecorate %72 DescriptorSet 1 -OpDecorate %72 Binding 2 +OpDecorate %72 Binding 0 OpDecorate %74 DescriptorSet 1 -OpDecorate %74 Binding 3 -OpDecorate %77 BuiltIn LocalInvocationId -OpDecorate %153 BuiltIn LocalInvocationId -OpDecorate %174 BuiltIn Position -OpDecorate %227 BuiltIn Position -OpDecorate %256 Location 0 -OpDecorate %284 Location 0 +OpDecorate %74 Binding 1 +OpDecorate %76 DescriptorSet 1 +OpDecorate %76 Binding 2 +OpDecorate %78 DescriptorSet 1 +OpDecorate %78 Binding 3 +OpDecorate %81 BuiltIn LocalInvocationId +OpDecorate %155 BuiltIn LocalInvocationId +OpDecorate %176 BuiltIn Position +OpDecorate %229 BuiltIn Position +OpDecorate %258 Location 0 +OpDecorate %285 Location 0 OpDecorate %305 Location 0 OpDecorate %340 Location 0 %2 = OpTypeVoid @@ -128,44 +128,44 @@ OpDecorate %340 Location 0 %19 = OpTypeImage %13 1D 0 0 0 1 Unknown %20 = OpTypeVector %13 3 %21 = OpTypeVector %4 2 -%22 = OpTypeImage %8 1D 0 0 0 1 Unknown -%23 = OpTypeImage %8 2D 0 0 0 1 Unknown -%24 = OpTypeImage %4 2D 0 0 0 1 Unknown -%25 = OpTypeImage %8 2D 0 1 0 1 Unknown -%26 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%27 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%28 = OpTypeImage %8 3D 0 0 0 1 Unknown -%29 = OpTypeImage %8 2D 0 0 1 1 Unknown -%30 = OpTypeVector %8 4 -%31 = OpTypeSampler -%32 = OpTypeImage %8 2D 1 0 0 1 Unknown -%33 = OpTypeImage %8 Cube 1 0 0 1 Unknown -%34 = OpConstantComposite %21 %10 %6 -%36 = OpTypePointer UniformConstant %12 -%35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %14 -%37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %15 +%22 = OpTypeVector %13 2 +%23 = OpTypeVector %13 4 +%24 = OpTypeImage %8 1D 0 0 0 1 Unknown +%25 = OpTypeImage %8 2D 0 0 0 1 Unknown +%26 = OpTypeImage %4 2D 0 0 0 1 Unknown +%27 = OpTypeImage %8 2D 0 1 0 1 Unknown +%28 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%29 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%30 = OpTypeImage %8 3D 0 0 0 1 Unknown +%31 = OpTypeImage %8 2D 0 0 1 1 Unknown +%32 = OpTypeVector %8 4 +%33 = OpTypeSampler +%34 = OpTypeVector %8 2 +%35 = OpTypeImage %8 2D 1 0 0 1 Unknown +%36 = OpTypeImage %8 Cube 1 0 0 1 Unknown +%37 = OpTypeVector %8 3 +%38 = OpConstantComposite %21 %10 %6 +%40 = OpTypePointer UniformConstant %12 %39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %16 +%42 = OpTypePointer UniformConstant %14 %41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %17 +%44 = OpTypePointer UniformConstant %15 %43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %18 +%46 = OpTypePointer UniformConstant %16 %45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %19 +%48 = OpTypePointer UniformConstant %17 %47 = OpVariable %48 UniformConstant %50 = OpTypePointer UniformConstant %18 %49 = OpVariable %50 UniformConstant -%52 = OpTypePointer UniformConstant %22 +%52 = OpTypePointer UniformConstant %19 %51 = OpVariable %52 UniformConstant -%54 = OpTypePointer UniformConstant %23 +%54 = OpTypePointer UniformConstant %18 %53 = OpVariable %54 UniformConstant -%55 = OpVariable %36 UniformConstant -%57 = OpTypePointer UniformConstant %24 -%56 = OpVariable %57 UniformConstant -%59 = OpTypePointer UniformConstant %25 -%58 = OpVariable %59 UniformConstant +%56 = OpTypePointer UniformConstant %24 +%55 = OpVariable %56 UniformConstant +%58 = OpTypePointer UniformConstant %25 +%57 = OpVariable %58 UniformConstant +%59 = OpVariable %40 UniformConstant %61 = OpTypePointer UniformConstant %26 %60 = OpVariable %61 UniformConstant %63 = OpTypePointer UniformConstant %27 @@ -174,319 +174,319 @@ OpDecorate %340 Location 0 %64 = OpVariable %65 UniformConstant %67 = OpTypePointer UniformConstant %29 %66 = OpVariable %67 UniformConstant -%69 = OpTypePointer UniformConstant %31 +%69 = OpTypePointer UniformConstant %30 %68 = OpVariable %69 UniformConstant %71 = OpTypePointer UniformConstant %31 %70 = OpVariable %71 UniformConstant -%73 = OpTypePointer UniformConstant %32 +%73 = OpTypePointer UniformConstant %33 %72 = OpVariable %73 UniformConstant %75 = OpTypePointer UniformConstant %33 %74 = OpVariable %75 UniformConstant -%78 = OpTypePointer Input %20 -%77 = OpVariable %78 Input -%81 = OpTypeFunction %2 -%90 = OpTypeVector %13 2 -%98 = OpTypeVector %13 4 -%109 = OpTypeVector %4 3 -%153 = OpVariable %78 Input -%175 = OpTypePointer Output %30 -%174 = OpVariable %175 Output -%185 = OpConstant %13 0 -%227 = OpVariable %175 Output -%256 = OpVariable %175 Output -%262 = OpTypeVector %8 2 -%265 = OpTypeSampledImage %22 -%268 = OpTypeSampledImage %23 -%285 = OpTypePointer Output %8 -%284 = OpVariable %285 Output -%292 = OpTypeSampledImage %32 -%297 = OpConstant %8 0.0 -%298 = OpTypeVector %8 3 -%300 = OpTypeSampledImage %33 -%305 = OpVariable %175 Output +%77 = OpTypePointer UniformConstant %35 +%76 = OpVariable %77 UniformConstant +%79 = OpTypePointer UniformConstant %36 +%78 = OpVariable %79 UniformConstant +%82 = OpTypePointer Input %20 +%81 = OpVariable %82 Input +%85 = OpTypeFunction %2 +%111 = OpTypeVector %4 3 +%155 = OpVariable %82 Input +%177 = OpTypePointer Output %32 +%176 = OpVariable %177 Output +%187 = OpConstant %13 0 +%229 = OpVariable %177 Output +%258 = OpVariable %177 Output +%266 = OpTypeSampledImage %24 +%269 = OpTypeSampledImage %25 +%286 = OpTypePointer Output %8 +%285 = OpVariable %286 Output +%293 = OpTypeSampledImage %35 +%298 = OpConstant %8 0.0 +%300 = OpTypeSampledImage %36 +%305 = OpVariable %177 Output %317 = OpConstant %13 1 %320 = OpConstant %13 3 %325 = OpTypeSampledImage %12 %328 = OpTypeVector %4 4 -%329 = OpTypeSampledImage %24 -%340 = OpVariable %175 Output -%80 = OpFunction %2 None %81 -%76 = OpLabel -%79 = OpLoad %20 %77 -%82 = OpLoad %12 %35 -%83 = OpLoad %14 %37 -%84 = OpLoad %16 %41 -%85 = OpLoad %17 %43 -%86 = OpLoad %19 %47 -%87 = OpLoad %18 %49 -OpBranch %88 -%88 = OpLabel -%89 = OpImageQuerySize %21 %84 -%91 = OpVectorShuffle %90 %79 %79 0 1 -%92 = OpBitcast %21 %91 -%93 = OpIMul %21 %89 %92 -%94 = OpCompositeConstruct %21 %3 %5 -%95 = OpSRem %21 %93 %94 -%96 = OpCompositeExtract %13 %79 2 -%97 = OpBitcast %4 %96 -%99 = OpImageFetch %98 %82 %95 Lod %97 -%100 = OpCompositeExtract %13 %79 2 -%101 = OpBitcast %4 %100 -%102 = OpImageFetch %98 %83 %95 Sample %101 -%103 = OpImageRead %98 %84 %95 -%104 = OpCompositeExtract %13 %79 2 -%105 = OpBitcast %4 %104 -%106 = OpCompositeExtract %13 %79 2 +%329 = OpTypeSampledImage %26 +%340 = OpVariable %177 Output +%84 = OpFunction %2 None %85 +%80 = OpLabel +%83 = OpLoad %20 %81 +%86 = OpLoad %12 %39 +%87 = OpLoad %14 %41 +%88 = OpLoad %16 %45 +%89 = OpLoad %17 %47 +%90 = OpLoad %19 %51 +%91 = OpLoad %18 %53 +OpBranch %92 +%92 = OpLabel +%93 = OpImageQuerySize %21 %88 +%94 = OpVectorShuffle %22 %83 %83 0 1 +%95 = OpBitcast %21 %94 +%96 = OpIMul %21 %93 %95 +%97 = OpCompositeConstruct %21 %3 %5 +%98 = OpSRem %21 %96 %97 +%99 = OpCompositeExtract %13 %83 2 +%100 = OpBitcast %4 %99 +%101 = OpImageFetch %23 %86 %98 Lod %100 +%102 = OpCompositeExtract %13 %83 2 +%103 = OpBitcast %4 %102 +%104 = OpImageFetch %23 %87 %98 Sample %103 +%105 = OpImageRead %23 %88 %98 +%106 = OpCompositeExtract %13 %83 2 %107 = OpBitcast %4 %106 -%108 = OpIAdd %4 %107 %6 -%110 = OpCompositeConstruct %109 %95 %105 -%111 = OpImageFetch %98 %85 %110 Lod %108 -%112 = OpCompositeExtract %13 %79 0 -%113 = OpBitcast %4 %112 -%114 = OpCompositeExtract %13 %79 2 +%108 = OpCompositeExtract %13 %83 2 +%109 = OpBitcast %4 %108 +%110 = OpIAdd %4 %109 %6 +%112 = OpCompositeConstruct %111 %98 %107 +%113 = OpImageFetch %23 %89 %112 Lod %110 +%114 = OpCompositeExtract %13 %83 0 %115 = OpBitcast %4 %114 -%116 = OpImageFetch %98 %86 %113 Lod %115 -%117 = OpBitcast %90 %95 -%118 = OpCompositeExtract %13 %79 2 -%119 = OpBitcast %4 %118 -%120 = OpImageFetch %98 %82 %117 Lod %119 -%121 = OpBitcast %90 %95 -%122 = OpCompositeExtract %13 %79 2 -%123 = OpBitcast %4 %122 -%124 = OpImageFetch %98 %83 %121 Sample %123 -%125 = OpBitcast %90 %95 -%126 = OpImageRead %98 %84 %125 -%127 = OpBitcast %90 %95 -%128 = OpCompositeExtract %13 %79 2 -%129 = OpBitcast %4 %128 -%130 = OpCompositeExtract %13 %79 2 +%116 = OpCompositeExtract %13 %83 2 +%117 = OpBitcast %4 %116 +%118 = OpImageFetch %23 %90 %115 Lod %117 +%119 = OpBitcast %22 %98 +%120 = OpCompositeExtract %13 %83 2 +%121 = OpBitcast %4 %120 +%122 = OpImageFetch %23 %86 %119 Lod %121 +%123 = OpBitcast %22 %98 +%124 = OpCompositeExtract %13 %83 2 +%125 = OpBitcast %4 %124 +%126 = OpImageFetch %23 %87 %123 Sample %125 +%127 = OpBitcast %22 %98 +%128 = OpImageRead %23 %88 %127 +%129 = OpBitcast %22 %98 +%130 = OpCompositeExtract %13 %83 2 %131 = OpBitcast %4 %130 -%132 = OpIAdd %4 %131 %6 -%133 = OpBitcast %13 %129 -%134 = OpCompositeConstruct %20 %127 %133 -%135 = OpImageFetch %98 %85 %134 Lod %132 -%136 = OpCompositeExtract %13 %79 0 -%138 = OpCompositeExtract %13 %79 2 -%139 = OpBitcast %4 %138 -%140 = OpImageFetch %98 %86 %136 Lod %139 -%141 = OpCompositeExtract %4 %95 0 -%142 = OpIAdd %98 %99 %102 -%143 = OpIAdd %98 %142 %103 -%144 = OpIAdd %98 %143 %111 -%145 = OpIAdd %98 %144 %116 -OpImageWrite %87 %141 %145 -%146 = OpCompositeExtract %4 %95 0 -%147 = OpBitcast %13 %146 -%148 = OpIAdd %98 %120 %124 -%149 = OpIAdd %98 %148 %126 -%150 = OpIAdd %98 %149 %135 -%151 = OpIAdd %98 %150 %140 -OpImageWrite %87 %147 %151 +%132 = OpCompositeExtract %13 %83 2 +%133 = OpBitcast %4 %132 +%134 = OpIAdd %4 %133 %6 +%135 = OpBitcast %13 %131 +%136 = OpCompositeConstruct %20 %129 %135 +%137 = OpImageFetch %23 %89 %136 Lod %134 +%138 = OpCompositeExtract %13 %83 0 +%140 = OpCompositeExtract %13 %83 2 +%141 = OpBitcast %4 %140 +%142 = OpImageFetch %23 %90 %138 Lod %141 +%143 = OpCompositeExtract %4 %98 0 +%144 = OpIAdd %23 %101 %104 +%145 = OpIAdd %23 %144 %105 +%146 = OpIAdd %23 %145 %113 +%147 = OpIAdd %23 %146 %118 +OpImageWrite %91 %143 %147 +%148 = OpCompositeExtract %4 %98 0 +%149 = OpBitcast %13 %148 +%150 = OpIAdd %23 %122 %126 +%151 = OpIAdd %23 %150 %128 +%152 = OpIAdd %23 %151 %137 +%153 = OpIAdd %23 %152 %142 +OpImageWrite %91 %149 %153 OpReturn OpFunctionEnd -%155 = OpFunction %2 None %81 -%152 = OpLabel -%154 = OpLoad %20 %153 -%156 = OpLoad %15 %39 -%157 = OpLoad %16 %41 -%158 = OpLoad %18 %49 -OpBranch %159 -%159 = OpLabel -%160 = OpImageQuerySize %21 %157 -%161 = OpVectorShuffle %90 %154 %154 0 1 -%162 = OpBitcast %21 %161 -%163 = OpIMul %21 %160 %162 -%164 = OpCompositeConstruct %21 %3 %5 -%165 = OpSRem %21 %163 %164 -%166 = OpCompositeExtract %13 %154 2 -%167 = OpBitcast %4 %166 -%168 = OpImageFetch %30 %156 %165 Sample %167 -%169 = OpCompositeExtract %8 %168 0 -%170 = OpCompositeExtract %4 %165 0 -%171 = OpConvertFToU %13 %169 -%172 = OpCompositeConstruct %98 %171 %171 %171 %171 -OpImageWrite %158 %170 %172 +%157 = OpFunction %2 None %85 +%154 = OpLabel +%156 = OpLoad %20 %155 +%158 = OpLoad %15 %43 +%159 = OpLoad %16 %45 +%160 = OpLoad %18 %53 +OpBranch %161 +%161 = OpLabel +%162 = OpImageQuerySize %21 %159 +%163 = OpVectorShuffle %22 %156 %156 0 1 +%164 = OpBitcast %21 %163 +%165 = OpIMul %21 %162 %164 +%166 = OpCompositeConstruct %21 %3 %5 +%167 = OpSRem %21 %165 %166 +%168 = OpCompositeExtract %13 %156 2 +%169 = OpBitcast %4 %168 +%170 = OpImageFetch %32 %158 %167 Sample %169 +%171 = OpCompositeExtract %8 %170 0 +%172 = OpCompositeExtract %4 %167 0 +%173 = OpConvertFToU %13 %171 +%174 = OpCompositeConstruct %23 %173 %173 %173 %173 +OpImageWrite %160 %172 %174 OpReturn OpFunctionEnd -%176 = OpFunction %2 None %81 -%173 = OpLabel -%177 = OpLoad %22 %51 -%178 = OpLoad %23 %53 -%179 = OpLoad %25 %58 -%180 = OpLoad %26 %60 +%178 = OpFunction %2 None %85 +%175 = OpLabel +%179 = OpLoad %24 %55 +%180 = OpLoad %25 %57 %181 = OpLoad %27 %62 %182 = OpLoad %28 %64 %183 = OpLoad %29 %66 -OpBranch %184 -%184 = OpLabel -%186 = OpImageQuerySizeLod %4 %177 %185 -%188 = OpImageQuerySizeLod %4 %177 %186 -%189 = OpImageQuerySizeLod %21 %178 %185 -%190 = OpImageQuerySizeLod %21 %178 %6 -%191 = OpImageQuerySizeLod %109 %179 %185 -%192 = OpVectorShuffle %21 %191 %191 0 1 -%193 = OpImageQuerySizeLod %109 %179 %6 +%184 = OpLoad %30 %68 +%185 = OpLoad %31 %70 +OpBranch %186 +%186 = OpLabel +%188 = OpImageQuerySizeLod %4 %179 %187 +%190 = OpImageQuerySizeLod %4 %179 %188 +%191 = OpImageQuerySizeLod %21 %180 %187 +%192 = OpImageQuerySizeLod %21 %180 %6 +%193 = OpImageQuerySizeLod %111 %181 %187 %194 = OpVectorShuffle %21 %193 %193 0 1 -%195 = OpImageQuerySizeLod %21 %180 %185 -%196 = OpImageQuerySizeLod %21 %180 %6 -%197 = OpImageQuerySizeLod %109 %181 %185 -%198 = OpVectorShuffle %21 %197 %197 0 0 -%199 = OpImageQuerySizeLod %109 %181 %6 +%195 = OpImageQuerySizeLod %111 %181 %6 +%196 = OpVectorShuffle %21 %195 %195 0 1 +%197 = OpImageQuerySizeLod %21 %182 %187 +%198 = OpImageQuerySizeLod %21 %182 %6 +%199 = OpImageQuerySizeLod %111 %183 %187 %200 = OpVectorShuffle %21 %199 %199 0 0 -%201 = OpImageQuerySizeLod %109 %182 %185 -%202 = OpImageQuerySizeLod %109 %182 %6 -%203 = OpImageQuerySize %21 %183 -%204 = OpCompositeExtract %4 %189 1 -%205 = OpIAdd %4 %186 %204 -%206 = OpCompositeExtract %4 %190 1 -%207 = OpIAdd %4 %205 %206 +%201 = OpImageQuerySizeLod %111 %183 %6 +%202 = OpVectorShuffle %21 %201 %201 0 0 +%203 = OpImageQuerySizeLod %111 %184 %187 +%204 = OpImageQuerySizeLod %111 %184 %6 +%205 = OpImageQuerySize %21 %185 +%206 = OpCompositeExtract %4 %191 1 +%207 = OpIAdd %4 %188 %206 %208 = OpCompositeExtract %4 %192 1 %209 = OpIAdd %4 %207 %208 %210 = OpCompositeExtract %4 %194 1 %211 = OpIAdd %4 %209 %210 -%212 = OpCompositeExtract %4 %195 1 +%212 = OpCompositeExtract %4 %196 1 %213 = OpIAdd %4 %211 %212 -%214 = OpCompositeExtract %4 %196 1 +%214 = OpCompositeExtract %4 %197 1 %215 = OpIAdd %4 %213 %214 %216 = OpCompositeExtract %4 %198 1 %217 = OpIAdd %4 %215 %216 %218 = OpCompositeExtract %4 %200 1 %219 = OpIAdd %4 %217 %218 -%220 = OpCompositeExtract %4 %201 2 +%220 = OpCompositeExtract %4 %202 1 %221 = OpIAdd %4 %219 %220 -%222 = OpCompositeExtract %4 %202 2 +%222 = OpCompositeExtract %4 %203 2 %223 = OpIAdd %4 %221 %222 -%224 = OpConvertSToF %8 %223 -%225 = OpCompositeConstruct %30 %224 %224 %224 %224 -OpStore %174 %225 +%224 = OpCompositeExtract %4 %204 2 +%225 = OpIAdd %4 %223 %224 +%226 = OpConvertSToF %8 %225 +%227 = OpCompositeConstruct %32 %226 %226 %226 %226 +OpStore %176 %227 OpReturn OpFunctionEnd -%228 = OpFunction %2 None %81 -%226 = OpLabel -%229 = OpLoad %23 %53 -%230 = OpLoad %25 %58 -%231 = OpLoad %26 %60 +%230 = OpFunction %2 None %85 +%228 = OpLabel +%231 = OpLoad %25 %57 %232 = OpLoad %27 %62 %233 = OpLoad %28 %64 %234 = OpLoad %29 %66 -OpBranch %235 -%235 = OpLabel -%236 = OpImageQueryLevels %4 %229 -%237 = OpImageQueryLevels %4 %230 -%238 = OpImageQuerySizeLod %109 %230 %185 -%239 = OpCompositeExtract %4 %238 2 -%240 = OpImageQueryLevels %4 %231 -%241 = OpImageQueryLevels %4 %232 -%242 = OpImageQuerySizeLod %109 %232 %185 -%243 = OpCompositeExtract %4 %242 2 -%244 = OpImageQueryLevels %4 %233 -%245 = OpImageQuerySamples %4 %234 -%246 = OpIAdd %4 %239 %243 -%247 = OpIAdd %4 %246 %245 -%248 = OpIAdd %4 %247 %236 -%249 = OpIAdd %4 %248 %237 -%250 = OpIAdd %4 %249 %244 -%251 = OpIAdd %4 %250 %240 -%252 = OpIAdd %4 %251 %241 -%253 = OpConvertSToF %8 %252 -%254 = OpCompositeConstruct %30 %253 %253 %253 %253 -OpStore %227 %254 +%235 = OpLoad %30 %68 +%236 = OpLoad %31 %70 +OpBranch %237 +%237 = OpLabel +%238 = OpImageQueryLevels %4 %231 +%239 = OpImageQueryLevels %4 %232 +%240 = OpImageQuerySizeLod %111 %232 %187 +%241 = OpCompositeExtract %4 %240 2 +%242 = OpImageQueryLevels %4 %233 +%243 = OpImageQueryLevels %4 %234 +%244 = OpImageQuerySizeLod %111 %234 %187 +%245 = OpCompositeExtract %4 %244 2 +%246 = OpImageQueryLevels %4 %235 +%247 = OpImageQuerySamples %4 %236 +%248 = OpIAdd %4 %241 %245 +%249 = OpIAdd %4 %248 %247 +%250 = OpIAdd %4 %249 %238 +%251 = OpIAdd %4 %250 %239 +%252 = OpIAdd %4 %251 %246 +%253 = OpIAdd %4 %252 %242 +%254 = OpIAdd %4 %253 %243 +%255 = OpConvertSToF %8 %254 +%256 = OpCompositeConstruct %32 %255 %255 %255 %255 +OpStore %229 %256 OpReturn OpFunctionEnd -%257 = OpFunction %2 None %81 -%255 = OpLabel -%258 = OpLoad %22 %51 -%259 = OpLoad %23 %53 -%260 = OpLoad %31 %68 -OpBranch %261 -%261 = OpLabel -%263 = OpCompositeConstruct %262 %7 %7 -%264 = OpCompositeExtract %8 %263 0 -%266 = OpSampledImage %265 %258 %260 -%267 = OpImageSampleImplicitLod %30 %266 %264 -%269 = OpSampledImage %268 %259 %260 -%270 = OpImageSampleImplicitLod %30 %269 %263 -%271 = OpSampledImage %268 %259 %260 -%272 = OpImageSampleImplicitLod %30 %271 %263 ConstOffset %34 -%273 = OpSampledImage %268 %259 %260 -%274 = OpImageSampleExplicitLod %30 %273 %263 Lod %9 -%275 = OpSampledImage %268 %259 %260 -%276 = OpImageSampleExplicitLod %30 %275 %263 Lod|ConstOffset %9 %34 -%277 = OpSampledImage %268 %259 %260 -%278 = OpImageSampleImplicitLod %30 %277 %263 Bias|ConstOffset %11 %34 -%279 = OpFAdd %30 %267 %270 -%280 = OpFAdd %30 %279 %272 -%281 = OpFAdd %30 %280 %274 -%282 = OpFAdd %30 %281 %276 -OpStore %256 %282 +%259 = OpFunction %2 None %85 +%257 = OpLabel +%260 = OpLoad %24 %55 +%261 = OpLoad %25 %57 +%262 = OpLoad %33 %72 +OpBranch %263 +%263 = OpLabel +%264 = OpCompositeConstruct %34 %7 %7 +%265 = OpCompositeExtract %8 %264 0 +%267 = OpSampledImage %266 %260 %262 +%268 = OpImageSampleImplicitLod %32 %267 %265 +%270 = OpSampledImage %269 %261 %262 +%271 = OpImageSampleImplicitLod %32 %270 %264 +%272 = OpSampledImage %269 %261 %262 +%273 = OpImageSampleImplicitLod %32 %272 %264 ConstOffset %38 +%274 = OpSampledImage %269 %261 %262 +%275 = OpImageSampleExplicitLod %32 %274 %264 Lod %9 +%276 = OpSampledImage %269 %261 %262 +%277 = OpImageSampleExplicitLod %32 %276 %264 Lod|ConstOffset %9 %38 +%278 = OpSampledImage %269 %261 %262 +%279 = OpImageSampleImplicitLod %32 %278 %264 Bias|ConstOffset %11 %38 +%280 = OpFAdd %32 %268 %271 +%281 = OpFAdd %32 %280 %273 +%282 = OpFAdd %32 %281 %275 +%283 = OpFAdd %32 %282 %277 +OpStore %258 %283 OpReturn OpFunctionEnd -%286 = OpFunction %2 None %81 -%283 = OpLabel -%287 = OpLoad %31 %70 -%288 = OpLoad %32 %72 -%289 = OpLoad %33 %74 -OpBranch %290 -%290 = OpLabel -%291 = OpCompositeConstruct %262 %7 %7 -%293 = OpSampledImage %292 %288 %287 -%294 = OpImageSampleDrefImplicitLod %8 %293 %291 %7 -%295 = OpSampledImage %292 %288 %287 -%296 = OpImageSampleDrefExplicitLod %8 %295 %291 %7 Lod %297 -%299 = OpCompositeConstruct %298 %7 %7 %7 -%301 = OpSampledImage %300 %289 %287 -%302 = OpImageSampleDrefExplicitLod %8 %301 %299 %7 Lod %297 -%303 = OpFAdd %8 %294 %296 -OpStore %284 %303 +%287 = OpFunction %2 None %85 +%284 = OpLabel +%288 = OpLoad %33 %74 +%289 = OpLoad %35 %76 +%290 = OpLoad %36 %78 +OpBranch %291 +%291 = OpLabel +%292 = OpCompositeConstruct %34 %7 %7 +%294 = OpSampledImage %293 %289 %288 +%295 = OpImageSampleDrefImplicitLod %8 %294 %292 %7 +%296 = OpSampledImage %293 %289 %288 +%297 = OpImageSampleDrefExplicitLod %8 %296 %292 %7 Lod %298 +%299 = OpCompositeConstruct %37 %7 %7 %7 +%301 = OpSampledImage %300 %290 %288 +%302 = OpImageSampleDrefExplicitLod %8 %301 %299 %7 Lod %298 +%303 = OpFAdd %8 %295 %297 +OpStore %285 %303 OpReturn OpFunctionEnd -%306 = OpFunction %2 None %81 +%306 = OpFunction %2 None %85 %304 = OpLabel -%307 = OpLoad %23 %53 -%308 = OpLoad %12 %55 -%309 = OpLoad %24 %56 -%310 = OpLoad %31 %68 -%311 = OpLoad %31 %70 -%312 = OpLoad %32 %72 +%307 = OpLoad %25 %57 +%308 = OpLoad %12 %59 +%309 = OpLoad %26 %60 +%310 = OpLoad %33 %72 +%311 = OpLoad %33 %74 +%312 = OpLoad %35 %76 OpBranch %313 %313 = OpLabel -%314 = OpCompositeConstruct %262 %7 %7 -%315 = OpSampledImage %268 %307 %310 -%316 = OpImageGather %30 %315 %314 %317 -%318 = OpSampledImage %268 %307 %310 -%319 = OpImageGather %30 %318 %314 %320 ConstOffset %34 -%321 = OpSampledImage %292 %312 %311 -%322 = OpImageDrefGather %30 %321 %314 %7 -%323 = OpSampledImage %292 %312 %311 -%324 = OpImageDrefGather %30 %323 %314 %7 ConstOffset %34 +%314 = OpCompositeConstruct %34 %7 %7 +%315 = OpSampledImage %269 %307 %310 +%316 = OpImageGather %32 %315 %314 %317 +%318 = OpSampledImage %269 %307 %310 +%319 = OpImageGather %32 %318 %314 %320 ConstOffset %38 +%321 = OpSampledImage %293 %312 %311 +%322 = OpImageDrefGather %32 %321 %314 %7 +%323 = OpSampledImage %293 %312 %311 +%324 = OpImageDrefGather %32 %323 %314 %7 ConstOffset %38 %326 = OpSampledImage %325 %308 %310 -%327 = OpImageGather %98 %326 %314 %185 +%327 = OpImageGather %23 %326 %314 %187 %330 = OpSampledImage %329 %309 %310 -%331 = OpImageGather %328 %330 %314 %185 -%332 = OpConvertUToF %30 %327 -%333 = OpConvertSToF %30 %331 -%334 = OpFAdd %30 %332 %333 -%335 = OpFAdd %30 %316 %319 -%336 = OpFAdd %30 %335 %322 -%337 = OpFAdd %30 %336 %324 -%338 = OpFAdd %30 %337 %334 +%331 = OpImageGather %328 %330 %314 %187 +%332 = OpConvertUToF %32 %327 +%333 = OpConvertSToF %32 %331 +%334 = OpFAdd %32 %332 %333 +%335 = OpFAdd %32 %316 %319 +%336 = OpFAdd %32 %335 %322 +%337 = OpFAdd %32 %336 %324 +%338 = OpFAdd %32 %337 %334 OpStore %305 %338 OpReturn OpFunctionEnd -%341 = OpFunction %2 None %81 +%341 = OpFunction %2 None %85 %339 = OpLabel -%342 = OpLoad %31 %68 -%343 = OpLoad %32 %72 +%342 = OpLoad %33 %72 +%343 = OpLoad %35 %76 OpBranch %344 %344 = OpLabel -%345 = OpCompositeConstruct %262 %7 %7 -%346 = OpSampledImage %292 %343 %342 -%347 = OpImageSampleImplicitLod %30 %346 %345 +%345 = OpCompositeConstruct %34 %7 %7 +%346 = OpSampledImage %293 %343 %342 +%347 = OpImageSampleImplicitLod %32 %346 %345 %348 = OpCompositeExtract %8 %347 0 -%349 = OpSampledImage %292 %343 %342 -%350 = OpImageGather %30 %349 %345 %185 -%351 = OpCompositeConstruct %30 %348 %348 %348 %348 -%352 = OpFAdd %30 %351 %350 +%349 = OpSampledImage %293 %343 %342 +%350 = OpImageGather %32 %349 %345 %187 +%351 = OpCompositeConstruct %32 %348 %348 %348 %348 +%352 = OpFAdd %32 %351 %350 OpStore %340 %352 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index 190f391c3..1455090ab 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -5,7 +5,7 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %34 "vertex_two_structs" %24 %28 %30 %32 +OpEntryPoint Vertex %35 "vertex_two_structs" %25 %29 %31 %33 OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %13 1 Offset 16 OpMemberDecorate %14 0 Offset 0 @@ -14,11 +14,11 @@ OpMemberDecorate %14 2 Offset 8 OpDecorate %16 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %19 0 Offset 0 -OpDecorate %24 BuiltIn VertexIndex -OpDecorate %28 BuiltIn InstanceIndex -OpDecorate %30 Invariant -OpDecorate %30 BuiltIn Position -OpDecorate %32 BuiltIn PointSize +OpDecorate %25 BuiltIn VertexIndex +OpDecorate %29 BuiltIn InstanceIndex +OpDecorate %31 Invariant +OpDecorate %31 BuiltIn Position +OpDecorate %33 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -38,32 +38,33 @@ OpDecorate %32 BuiltIn PointSize %18 = OpTypeStruct %6 %19 = OpTypeStruct %6 %21 = OpTypePointer Function %6 -%25 = OpTypePointer Input %6 -%24 = OpVariable %25 Input -%28 = OpVariable %25 Input -%31 = OpTypePointer Output %12 -%30 = OpVariable %31 Output -%33 = OpTypePointer Output %4 -%32 = OpVariable %33 Output -%35 = OpTypeFunction %2 -%36 = OpTypePointer Workgroup %16 -%34 = OpFunction %2 None %35 -%22 = OpLabel -%20 = OpVariable %21 Function %11 -%26 = OpLoad %6 %24 -%23 = OpCompositeConstruct %18 %26 -%29 = OpLoad %6 %28 -%27 = OpCompositeConstruct %19 %29 -OpStore %32 %3 +%22 = OpConstantNull %6 +%26 = OpTypePointer Input %6 +%25 = OpVariable %26 Input +%29 = OpVariable %26 Input +%32 = OpTypePointer Output %12 +%31 = OpVariable %32 Output +%34 = OpTypePointer Output %4 +%33 = OpVariable %34 Output +%36 = OpTypeFunction %2 +%35 = OpFunction %2 None %36 +%23 = OpLabel +%20 = OpVariable %21 Function %22 +%27 = OpLoad %6 %25 +%24 = OpCompositeConstruct %18 %27 +%30 = OpLoad %6 %29 +%28 = OpCompositeConstruct %19 %30 +OpStore %33 %3 OpBranch %37 %37 = OpLabel -%38 = OpCompositeExtract %6 %23 0 +OpStore %20 %11 +%38 = OpCompositeExtract %6 %24 0 %39 = OpConvertUToF %4 %38 -%40 = OpCompositeExtract %6 %27 0 +%40 = OpCompositeExtract %6 %28 0 %41 = OpConvertUToF %4 %40 %42 = OpLoad %6 %20 %43 = OpConvertUToF %4 %42 %44 = OpCompositeConstruct %12 %39 %41 %43 %7 -OpStore %30 %44 +OpStore %31 %44 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index fc970f863..194024b76 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -5,7 +5,7 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %13 "main" +OpEntryPoint Vertex %14 "main" %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -14,29 +14,29 @@ OpEntryPoint Vertex %13 "main" %6 = OpConstant %7 0 %9 = OpTypeInt 32 0 %8 = OpConstant %9 0 -%10 = OpTypeVector %7 2 -%11 = OpConstantComposite %10 %6 %6 -%14 = OpTypeFunction %2 -%16 = OpTypeVector %4 4 +%10 = OpTypeVector %4 4 +%11 = OpTypeVector %7 2 +%12 = OpConstantComposite %11 %6 %6 +%15 = OpTypeFunction %2 %26 = OpConstantNull %7 -%13 = OpFunction %2 None %14 -%12 = OpLabel -OpBranch %15 -%15 = OpLabel -%17 = OpCompositeConstruct %16 %5 %5 %5 %5 +%14 = OpFunction %2 None %15 +%13 = OpLabel +OpBranch %16 +%16 = OpLabel +%17 = OpCompositeConstruct %10 %5 %5 %5 %5 %18 = OpExtInst %4 %1 Degrees %3 %19 = OpExtInst %4 %1 Radians %3 -%20 = OpExtInst %16 %1 Degrees %17 -%21 = OpExtInst %16 %1 Radians %17 -%23 = OpCompositeConstruct %16 %5 %5 %5 %5 -%24 = OpCompositeConstruct %16 %3 %3 %3 %3 -%22 = OpExtInst %16 %1 FClamp %17 %23 %24 -%27 = OpCompositeExtract %7 %11 0 -%28 = OpCompositeExtract %7 %11 0 +%20 = OpExtInst %10 %1 Degrees %17 +%21 = OpExtInst %10 %1 Radians %17 +%23 = OpCompositeConstruct %10 %5 %5 %5 %5 +%24 = OpCompositeConstruct %10 %3 %3 %3 %3 +%22 = OpExtInst %10 %1 FClamp %17 %23 %24 +%27 = OpCompositeExtract %7 %12 0 +%28 = OpCompositeExtract %7 %12 0 %29 = OpIMul %7 %27 %28 %30 = OpIAdd %7 %26 %29 -%31 = OpCompositeExtract %7 %11 1 -%32 = OpCompositeExtract %7 %11 1 +%31 = OpCompositeExtract %7 %12 1 +%32 = OpCompositeExtract %7 %12 1 %33 = OpIMul %7 %31 %32 %25 = OpIAdd %7 %30 %33 %34 = OpCopyObject %9 %8 diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 87f6ce309..3263e223f 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 572 +; Bound: 574 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %560 "main" -OpExecutionMode %560 LocalSize 1 1 1 -OpMemberDecorate %39 0 Offset 0 -OpMemberDecorate %39 1 Offset 16 -OpDecorate %43 ArrayStride 32 -OpDecorate %44 ArrayStride 4 +OpEntryPoint GLCompute %562 "main" +OpExecutionMode %562 LocalSize 1 1 1 +OpMemberDecorate %40 0 Offset 0 +OpMemberDecorate %40 1 Offset 16 +OpDecorate %44 ArrayStride 32 +OpDecorate %45 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -48,41 +48,41 @@ OpDecorate %44 ArrayStride 4 %36 = OpTypeVector %10 4 %37 = OpTypeVector %4 2 %38 = OpTypeVector %4 3 -%39 = OpTypeStruct %34 %8 -%40 = OpTypeMatrix %37 2 -%41 = OpTypeMatrix %34 4 -%42 = OpTypeVector %20 2 -%43 = OpTypeArray %39 %21 -%44 = OpTypeArray %8 %22 -%45 = OpTypeMatrix %38 2 -%46 = OpTypeMatrix %38 3 -%47 = OpTypeMatrix %38 4 -%48 = OpTypeMatrix %34 3 -%49 = OpTypeVector %8 3 -%50 = OpConstantComposite %34 %3 %3 %3 %3 -%51 = OpConstantComposite %34 %5 %5 %5 %5 -%52 = OpConstantComposite %34 %6 %6 %6 %6 -%53 = OpConstantComposite %35 %7 %7 %7 %7 -%54 = OpConstantComposite %42 %19 %19 -%55 = OpConstantComposite %37 %5 %5 -%56 = OpConstantComposite %40 %55 %55 -%57 = OpConstantComposite %34 %5 %5 %5 %5 -%58 = OpConstantComposite %39 %57 %11 -%59 = OpConstantComposite %43 %58 %58 %58 -%60 = OpConstantComposite %38 %5 %5 %5 -%61 = OpConstantComposite %45 %60 %60 -%62 = OpConstantComposite %46 %60 %60 %60 -%63 = OpConstantComposite %47 %60 %60 %60 %60 -%64 = OpConstantComposite %48 %57 %57 %57 -%65 = OpConstantComposite %49 %11 %11 %11 -%68 = OpTypeFunction %34 -%108 = OpTypePointer Function %37 -%109 = OpConstantNull %37 -%112 = OpTypeFunction %37 -%128 = OpTypeFunction %38 %38 -%130 = OpTypeVector %10 3 -%137 = OpTypePointer Function %39 -%138 = OpConstantNull %39 +%39 = OpTypeVector %10 3 +%40 = OpTypeStruct %34 %8 +%41 = OpTypeMatrix %37 2 +%42 = OpTypeMatrix %34 4 +%43 = OpTypeVector %20 2 +%44 = OpTypeArray %40 %21 +%45 = OpTypeArray %8 %22 +%46 = OpTypeMatrix %38 2 +%47 = OpTypeMatrix %38 3 +%48 = OpTypeMatrix %38 4 +%49 = OpTypeMatrix %34 3 +%50 = OpTypeVector %8 3 +%51 = OpConstantComposite %34 %3 %3 %3 %3 +%52 = OpConstantComposite %34 %5 %5 %5 %5 +%53 = OpConstantComposite %34 %6 %6 %6 %6 +%54 = OpConstantComposite %35 %7 %7 %7 %7 +%55 = OpConstantComposite %43 %19 %19 +%56 = OpConstantComposite %37 %5 %5 +%57 = OpConstantComposite %41 %56 %56 +%58 = OpConstantComposite %34 %5 %5 %5 %5 +%59 = OpConstantComposite %40 %58 %11 +%60 = OpConstantComposite %44 %59 %59 %59 +%61 = OpConstantComposite %38 %5 %5 %5 +%62 = OpConstantComposite %46 %61 %61 +%63 = OpConstantComposite %47 %61 %61 %61 +%64 = OpConstantComposite %48 %61 %61 %61 %61 +%65 = OpConstantComposite %49 %58 %58 %58 +%66 = OpConstantComposite %50 %11 %11 %11 +%69 = OpTypeFunction %34 +%109 = OpTypePointer Function %37 +%110 = OpConstantNull %37 +%113 = OpTypeFunction %37 +%129 = OpTypeFunction %38 %38 +%137 = OpTypePointer Function %40 +%138 = OpConstantNull %40 %141 = OpTypeFunction %4 %166 = OpTypePointer Function %34 %167 = OpTypePointer Function %4 @@ -91,83 +91,85 @@ OpDecorate %44 ArrayStride 4 %191 = OpTypeVector %8 2 %202 = OpTypeVector %20 3 %497 = OpTypePointer Function %8 -%499 = OpTypePointer Function %49 -%529 = OpTypePointer Function %8 -%67 = OpFunction %34 None %68 -%66 = OpLabel -OpBranch %69 -%69 = OpLabel -%70 = OpSelect %8 %9 %7 %11 -%72 = OpCompositeConstruct %36 %9 %9 %9 %9 -%71 = OpSelect %34 %72 %50 %51 -%73 = OpCompositeConstruct %36 %12 %12 %12 %12 -%74 = OpSelect %34 %73 %51 %50 -%75 = OpExtInst %34 %1 FMix %51 %50 %52 -%77 = OpCompositeConstruct %34 %13 %13 %13 %13 -%76 = OpExtInst %34 %1 FMix %51 %50 %77 -%78 = OpCompositeExtract %8 %53 0 -%79 = OpBitcast %4 %78 -%80 = OpBitcast %34 %53 -%81 = OpConvertFToS %35 %51 -%82 = OpCompositeConstruct %35 %70 %70 %70 %70 -%83 = OpIAdd %35 %82 %81 -%84 = OpConvertSToF %34 %83 -%85 = OpFAdd %34 %84 %71 -%86 = OpFAdd %34 %85 %75 +%498 = OpConstantNull %8 +%500 = OpTypePointer Function %50 +%501 = OpConstantNull %50 +%531 = OpTypePointer Function %8 +%68 = OpFunction %34 None %69 +%67 = OpLabel +OpBranch %70 +%70 = OpLabel +%71 = OpSelect %8 %9 %7 %11 +%73 = OpCompositeConstruct %36 %9 %9 %9 %9 +%72 = OpSelect %34 %73 %51 %52 +%74 = OpCompositeConstruct %36 %12 %12 %12 %12 +%75 = OpSelect %34 %74 %52 %51 +%76 = OpExtInst %34 %1 FMix %52 %51 %53 +%78 = OpCompositeConstruct %34 %13 %13 %13 %13 +%77 = OpExtInst %34 %1 FMix %52 %51 %78 +%79 = OpCompositeExtract %8 %54 0 +%80 = OpBitcast %4 %79 +%81 = OpBitcast %34 %54 +%82 = OpConvertFToS %35 %52 +%83 = OpCompositeConstruct %35 %71 %71 %71 %71 +%84 = OpIAdd %35 %83 %82 +%85 = OpConvertSToF %34 %84 +%86 = OpFAdd %34 %85 %72 %87 = OpFAdd %34 %86 %76 -%88 = OpCompositeConstruct %34 %79 %79 %79 %79 -%89 = OpFAdd %34 %87 %88 -%90 = OpFAdd %34 %89 %80 -OpReturnValue %90 +%88 = OpFAdd %34 %87 %77 +%89 = OpCompositeConstruct %34 %80 %80 %80 %80 +%90 = OpFAdd %34 %88 %89 +%91 = OpFAdd %34 %90 %81 +OpReturnValue %91 OpFunctionEnd -%92 = OpFunction %34 None %68 -%91 = OpLabel -OpBranch %93 -%93 = OpLabel -%94 = OpCompositeConstruct %37 %14 %14 -%95 = OpCompositeConstruct %37 %3 %3 -%96 = OpFAdd %37 %95 %94 -%97 = OpCompositeConstruct %37 %15 %15 -%98 = OpFSub %37 %96 %97 -%99 = OpCompositeConstruct %37 %16 %16 -%100 = OpFDiv %37 %98 %99 -%101 = OpCompositeConstruct %35 %17 %17 %17 %17 -%102 = OpCompositeConstruct %35 %18 %18 %18 %18 -%103 = OpSRem %35 %101 %102 -%104 = OpVectorShuffle %34 %100 %100 0 1 0 1 -%105 = OpConvertSToF %34 %103 -%106 = OpFAdd %34 %104 %105 -OpReturnValue %106 +%93 = OpFunction %34 None %69 +%92 = OpLabel +OpBranch %94 +%94 = OpLabel +%95 = OpCompositeConstruct %37 %14 %14 +%96 = OpCompositeConstruct %37 %3 %3 +%97 = OpFAdd %37 %96 %95 +%98 = OpCompositeConstruct %37 %15 %15 +%99 = OpFSub %37 %97 %98 +%100 = OpCompositeConstruct %37 %16 %16 +%101 = OpFDiv %37 %99 %100 +%102 = OpCompositeConstruct %35 %17 %17 %17 %17 +%103 = OpCompositeConstruct %35 %18 %18 %18 %18 +%104 = OpSRem %35 %102 %103 +%105 = OpVectorShuffle %34 %101 %101 0 1 0 1 +%106 = OpConvertSToF %34 %104 +%107 = OpFAdd %34 %105 %106 +OpReturnValue %107 OpFunctionEnd -%111 = OpFunction %37 None %112 -%110 = OpLabel -%107 = OpVariable %108 Function %109 -OpBranch %113 -%113 = OpLabel -%114 = OpCompositeConstruct %37 %14 %14 -OpStore %107 %114 -%115 = OpLoad %37 %107 -%116 = OpCompositeConstruct %37 %3 %3 -%117 = OpFAdd %37 %115 %116 -OpStore %107 %117 -%118 = OpLoad %37 %107 -%119 = OpCompositeConstruct %37 %15 %15 -%120 = OpFSub %37 %118 %119 -OpStore %107 %120 -%121 = OpLoad %37 %107 -%122 = OpCompositeConstruct %37 %16 %16 -%123 = OpFDiv %37 %121 %122 -OpStore %107 %123 -%124 = OpLoad %37 %107 -OpReturnValue %124 +%112 = OpFunction %37 None %113 +%111 = OpLabel +%108 = OpVariable %109 Function %110 +OpBranch %114 +%114 = OpLabel +%115 = OpCompositeConstruct %37 %14 %14 +OpStore %108 %115 +%116 = OpLoad %37 %108 +%117 = OpCompositeConstruct %37 %3 %3 +%118 = OpFAdd %37 %116 %117 +OpStore %108 %118 +%119 = OpLoad %37 %108 +%120 = OpCompositeConstruct %37 %15 %15 +%121 = OpFSub %37 %119 %120 +OpStore %108 %121 +%122 = OpLoad %37 %108 +%123 = OpCompositeConstruct %37 %16 %16 +%124 = OpFDiv %37 %122 %123 +OpStore %108 %124 +%125 = OpLoad %37 %108 +OpReturnValue %125 OpFunctionEnd -%127 = OpFunction %38 None %128 -%126 = OpFunctionParameter %38 -%125 = OpLabel -OpBranch %129 -%129 = OpLabel +%128 = OpFunction %38 None %129 +%127 = OpFunctionParameter %38 +%126 = OpLabel +OpBranch %130 +%130 = OpLabel %131 = OpCompositeConstruct %38 %5 %5 %5 -%132 = OpFUnordNotEqual %130 %126 %131 +%132 = OpFUnordNotEqual %39 %127 %131 %133 = OpCompositeConstruct %38 %5 %5 %5 %134 = OpCompositeConstruct %38 %3 %3 %3 %135 = OpSelect %38 %132 %134 %133 @@ -179,23 +181,23 @@ OpFunctionEnd OpBranch %142 %142 = OpLabel %143 = OpCompositeConstruct %34 %3 %3 %3 %3 -%144 = OpCompositeConstruct %39 %143 %7 +%144 = OpCompositeConstruct %40 %143 %7 OpStore %136 %144 %145 = OpCompositeConstruct %37 %3 %5 %146 = OpCompositeConstruct %37 %5 %3 -%147 = OpCompositeConstruct %40 %145 %146 +%147 = OpCompositeConstruct %41 %145 %146 %148 = OpCompositeConstruct %34 %3 %5 %5 %5 %149 = OpCompositeConstruct %34 %5 %3 %5 %5 %150 = OpCompositeConstruct %34 %5 %5 %3 %5 %151 = OpCompositeConstruct %34 %5 %5 %5 %3 -%152 = OpCompositeConstruct %41 %148 %149 %150 %151 -%153 = OpCompositeConstruct %42 %19 %19 +%152 = OpCompositeConstruct %42 %148 %149 %150 %151 +%153 = OpCompositeConstruct %43 %19 %19 %154 = OpCompositeConstruct %37 %5 %5 %155 = OpCompositeConstruct %37 %5 %5 -%156 = OpCompositeConstruct %40 %154 %155 -%157 = OpCompositeConstruct %44 %11 %7 %18 %21 -%163 = OpCopyObject %45 %61 -%165 = OpCopyObject %45 %61 +%156 = OpCompositeConstruct %41 %154 %155 +%157 = OpCompositeConstruct %45 %11 %7 %18 %21 +%163 = OpCopyObject %46 %62 +%165 = OpCopyObject %46 %62 %168 = OpAccessChain %167 %136 %19 %19 %169 = OpLoad %4 %168 OpReturnValue %169 @@ -210,9 +212,9 @@ OpBranch %173 %178 = OpLogicalOr %10 %9 %12 %179 = OpLogicalAnd %10 %9 %12 %180 = OpLogicalOr %10 %9 %12 -%181 = OpCompositeConstruct %130 %9 %9 %9 -%182 = OpCompositeConstruct %130 %12 %12 %12 -%183 = OpLogicalOr %130 %181 %182 +%181 = OpCompositeConstruct %39 %9 %9 %9 +%182 = OpCompositeConstruct %39 %12 %12 %12 +%183 = OpLogicalOr %39 %181 %182 %184 = OpLogicalAnd %10 %9 %12 %185 = OpCompositeConstruct %36 %9 %9 %9 %9 %186 = OpCompositeConstruct %36 %12 %12 %12 %12 @@ -293,12 +295,12 @@ OpBranch %190 %260 = OpCompositeConstruct %191 %7 %7 %261 = OpCompositeConstruct %191 %18 %18 %262 = OpIAdd %191 %261 %260 -%263 = OpCompositeConstruct %42 %24 %24 -%264 = OpCompositeConstruct %42 %25 %25 -%265 = OpIAdd %42 %263 %264 -%266 = OpCompositeConstruct %42 %25 %25 -%267 = OpCompositeConstruct %42 %24 %24 -%268 = OpIAdd %42 %267 %266 +%263 = OpCompositeConstruct %43 %24 %24 +%264 = OpCompositeConstruct %43 %25 %25 +%265 = OpIAdd %43 %263 %264 +%266 = OpCompositeConstruct %43 %25 %25 +%267 = OpCompositeConstruct %43 %24 %24 +%268 = OpIAdd %43 %267 %266 %269 = OpCompositeConstruct %37 %14 %14 %270 = OpCompositeConstruct %37 %3 %3 %271 = OpFAdd %37 %269 %270 @@ -311,12 +313,12 @@ OpBranch %190 %278 = OpCompositeConstruct %191 %7 %7 %279 = OpCompositeConstruct %191 %18 %18 %280 = OpISub %191 %279 %278 -%281 = OpCompositeConstruct %42 %24 %24 -%282 = OpCompositeConstruct %42 %25 %25 -%283 = OpISub %42 %281 %282 -%284 = OpCompositeConstruct %42 %25 %25 -%285 = OpCompositeConstruct %42 %24 %24 -%286 = OpISub %42 %285 %284 +%281 = OpCompositeConstruct %43 %24 %24 +%282 = OpCompositeConstruct %43 %25 %25 +%283 = OpISub %43 %281 %282 +%284 = OpCompositeConstruct %43 %25 %25 +%285 = OpCompositeConstruct %43 %24 %24 +%286 = OpISub %43 %285 %284 %287 = OpCompositeConstruct %37 %14 %14 %288 = OpCompositeConstruct %37 %3 %3 %289 = OpFSub %37 %287 %288 @@ -329,12 +331,12 @@ OpBranch %190 %296 = OpCompositeConstruct %191 %7 %7 %298 = OpCompositeConstruct %191 %18 %18 %297 = OpIMul %191 %296 %298 -%299 = OpCompositeConstruct %42 %24 %24 -%301 = OpCompositeConstruct %42 %25 %25 -%300 = OpIMul %42 %299 %301 -%302 = OpCompositeConstruct %42 %25 %25 -%304 = OpCompositeConstruct %42 %24 %24 -%303 = OpIMul %42 %302 %304 +%299 = OpCompositeConstruct %43 %24 %24 +%301 = OpCompositeConstruct %43 %25 %25 +%300 = OpIMul %43 %299 %301 +%302 = OpCompositeConstruct %43 %25 %25 +%304 = OpCompositeConstruct %43 %24 %24 +%303 = OpIMul %43 %302 %304 %305 = OpCompositeConstruct %37 %14 %14 %306 = OpVectorTimesScalar %37 %305 %3 %307 = OpCompositeConstruct %37 %3 %3 @@ -345,12 +347,12 @@ OpBranch %190 %312 = OpCompositeConstruct %191 %7 %7 %313 = OpCompositeConstruct %191 %18 %18 %314 = OpSDiv %191 %313 %312 -%315 = OpCompositeConstruct %42 %24 %24 -%316 = OpCompositeConstruct %42 %25 %25 -%317 = OpUDiv %42 %315 %316 -%318 = OpCompositeConstruct %42 %25 %25 -%319 = OpCompositeConstruct %42 %24 %24 -%320 = OpUDiv %42 %319 %318 +%315 = OpCompositeConstruct %43 %24 %24 +%316 = OpCompositeConstruct %43 %25 %25 +%317 = OpUDiv %43 %315 %316 +%318 = OpCompositeConstruct %43 %25 %25 +%319 = OpCompositeConstruct %43 %24 %24 +%320 = OpUDiv %43 %319 %318 %321 = OpCompositeConstruct %37 %14 %14 %322 = OpCompositeConstruct %37 %3 %3 %323 = OpFDiv %37 %321 %322 @@ -363,45 +365,45 @@ OpBranch %190 %330 = OpCompositeConstruct %191 %7 %7 %331 = OpCompositeConstruct %191 %18 %18 %332 = OpSRem %191 %331 %330 -%333 = OpCompositeConstruct %42 %24 %24 -%334 = OpCompositeConstruct %42 %25 %25 -%335 = OpUMod %42 %333 %334 -%336 = OpCompositeConstruct %42 %25 %25 -%337 = OpCompositeConstruct %42 %24 %24 -%338 = OpUMod %42 %337 %336 +%333 = OpCompositeConstruct %43 %24 %24 +%334 = OpCompositeConstruct %43 %25 %25 +%335 = OpUMod %43 %333 %334 +%336 = OpCompositeConstruct %43 %25 %25 +%337 = OpCompositeConstruct %43 %24 %24 +%338 = OpUMod %43 %337 %336 %339 = OpCompositeConstruct %37 %14 %14 %340 = OpCompositeConstruct %37 %3 %3 %341 = OpFRem %37 %339 %340 %342 = OpCompositeConstruct %37 %3 %3 %343 = OpCompositeConstruct %37 %14 %14 %344 = OpFRem %37 %343 %342 -%346 = OpCompositeExtract %38 %62 0 -%347 = OpCompositeExtract %38 %62 0 +%346 = OpCompositeExtract %38 %63 0 +%347 = OpCompositeExtract %38 %63 0 %348 = OpFAdd %38 %346 %347 -%349 = OpCompositeExtract %38 %62 1 -%350 = OpCompositeExtract %38 %62 1 +%349 = OpCompositeExtract %38 %63 1 +%350 = OpCompositeExtract %38 %63 1 %351 = OpFAdd %38 %349 %350 -%352 = OpCompositeExtract %38 %62 2 -%353 = OpCompositeExtract %38 %62 2 +%352 = OpCompositeExtract %38 %63 2 +%353 = OpCompositeExtract %38 %63 2 %354 = OpFAdd %38 %352 %353 -%345 = OpCompositeConstruct %46 %348 %351 %354 -%356 = OpCompositeExtract %38 %62 0 -%357 = OpCompositeExtract %38 %62 0 +%345 = OpCompositeConstruct %47 %348 %351 %354 +%356 = OpCompositeExtract %38 %63 0 +%357 = OpCompositeExtract %38 %63 0 %358 = OpFSub %38 %356 %357 -%359 = OpCompositeExtract %38 %62 1 -%360 = OpCompositeExtract %38 %62 1 +%359 = OpCompositeExtract %38 %63 1 +%360 = OpCompositeExtract %38 %63 1 %361 = OpFSub %38 %359 %360 -%362 = OpCompositeExtract %38 %62 2 -%363 = OpCompositeExtract %38 %62 2 +%362 = OpCompositeExtract %38 %63 2 +%363 = OpCompositeExtract %38 %63 2 %364 = OpFSub %38 %362 %363 -%355 = OpCompositeConstruct %46 %358 %361 %364 -%365 = OpMatrixTimesScalar %46 %62 %3 -%366 = OpMatrixTimesScalar %46 %62 %14 +%355 = OpCompositeConstruct %47 %358 %361 %364 +%365 = OpMatrixTimesScalar %47 %63 %3 +%366 = OpMatrixTimesScalar %47 %63 %14 %367 = OpCompositeConstruct %34 %3 %3 %3 %3 -%368 = OpMatrixTimesVector %38 %63 %367 +%368 = OpMatrixTimesVector %38 %64 %367 %369 = OpCompositeConstruct %38 %14 %14 %14 -%370 = OpVectorTimesMatrix %34 %369 %63 -%371 = OpMatrixTimesMatrix %46 %63 %64 +%370 = OpVectorTimesMatrix %34 %369 %64 +%371 = OpMatrixTimesMatrix %47 %64 %65 OpReturn OpFunctionEnd %373 = OpFunction %2 None %172 @@ -441,7 +443,7 @@ OpBranch %374 %405 = OpShiftLeftLogical %8 %18 %25 %406 = OpShiftLeftLogical %20 %24 %25 %407 = OpCompositeConstruct %191 %18 %18 -%408 = OpCompositeConstruct %42 %25 %25 +%408 = OpCompositeConstruct %43 %25 %25 %409 = OpShiftLeftLogical %191 %407 %408 %410 = OpCompositeConstruct %202 %24 %24 %24 %411 = OpCompositeConstruct %202 %25 %25 %25 @@ -449,7 +451,7 @@ OpBranch %374 %413 = OpShiftRightArithmetic %8 %18 %25 %414 = OpShiftRightLogical %20 %24 %25 %415 = OpCompositeConstruct %191 %18 %18 -%416 = OpCompositeConstruct %42 %25 %25 +%416 = OpCompositeConstruct %43 %25 %25 %417 = OpShiftRightArithmetic %191 %415 %416 %418 = OpCompositeConstruct %202 %24 %24 %24 %419 = OpCompositeConstruct %202 %25 %25 %25 @@ -468,7 +470,7 @@ OpBranch %423 %429 = OpIEqual %175 %427 %428 %430 = OpCompositeConstruct %202 %24 %24 %24 %431 = OpCompositeConstruct %202 %25 %25 %25 -%432 = OpIEqual %130 %430 %431 +%432 = OpIEqual %39 %430 %431 %433 = OpCompositeConstruct %34 %14 %14 %14 %14 %434 = OpCompositeConstruct %34 %3 %3 %3 %3 %435 = OpFOrdEqual %36 %433 %434 @@ -480,7 +482,7 @@ OpBranch %423 %441 = OpINotEqual %175 %439 %440 %442 = OpCompositeConstruct %202 %24 %24 %24 %443 = OpCompositeConstruct %202 %25 %25 %25 -%444 = OpINotEqual %130 %442 %443 +%444 = OpINotEqual %39 %442 %443 %445 = OpCompositeConstruct %34 %14 %14 %14 %14 %446 = OpCompositeConstruct %34 %3 %3 %3 %3 %447 = OpFOrdNotEqual %36 %445 %446 @@ -492,7 +494,7 @@ OpBranch %423 %453 = OpSLessThan %175 %451 %452 %454 = OpCompositeConstruct %202 %24 %24 %24 %455 = OpCompositeConstruct %202 %25 %25 %25 -%456 = OpULessThan %130 %454 %455 +%456 = OpULessThan %39 %454 %455 %457 = OpCompositeConstruct %34 %14 %14 %14 %14 %458 = OpCompositeConstruct %34 %3 %3 %3 %3 %459 = OpFOrdLessThan %36 %457 %458 @@ -504,7 +506,7 @@ OpBranch %423 %465 = OpSLessThanEqual %175 %463 %464 %466 = OpCompositeConstruct %202 %24 %24 %24 %467 = OpCompositeConstruct %202 %25 %25 %25 -%468 = OpULessThanEqual %130 %466 %467 +%468 = OpULessThanEqual %39 %466 %467 %469 = OpCompositeConstruct %34 %14 %14 %14 %14 %470 = OpCompositeConstruct %34 %3 %3 %3 %3 %471 = OpFOrdLessThanEqual %36 %469 %470 @@ -516,7 +518,7 @@ OpBranch %423 %477 = OpSGreaterThan %175 %475 %476 %478 = OpCompositeConstruct %202 %24 %24 %24 %479 = OpCompositeConstruct %202 %25 %25 %25 -%480 = OpUGreaterThan %130 %478 %479 +%480 = OpUGreaterThan %39 %478 %479 %481 = OpCompositeConstruct %34 %14 %14 %14 %14 %482 = OpCompositeConstruct %34 %3 %3 %3 %3 %483 = OpFOrdGreaterThan %36 %481 %482 @@ -528,105 +530,107 @@ OpBranch %423 %489 = OpSGreaterThanEqual %175 %487 %488 %490 = OpCompositeConstruct %202 %24 %24 %24 %491 = OpCompositeConstruct %202 %25 %25 %25 -%492 = OpUGreaterThanEqual %130 %490 %491 +%492 = OpUGreaterThanEqual %39 %490 %491 %493 = OpCompositeConstruct %34 %14 %14 %14 %14 %494 = OpCompositeConstruct %34 %3 %3 %3 %3 %495 = OpFOrdGreaterThanEqual %36 %493 %494 OpReturn OpFunctionEnd -%501 = OpFunction %2 None %172 -%500 = OpLabel -%496 = OpVariable %497 Function %7 -%498 = OpVariable %499 Function %65 -OpBranch %502 +%503 = OpFunction %2 None %172 %502 = OpLabel -%503 = OpLoad %8 %496 -%504 = OpIAdd %8 %503 %7 -OpStore %496 %504 +%496 = OpVariable %497 Function %498 +%499 = OpVariable %500 Function %501 +OpBranch %504 +%504 = OpLabel +OpStore %496 %7 %505 = OpLoad %8 %496 -%506 = OpISub %8 %505 %7 +%506 = OpIAdd %8 %505 %7 OpStore %496 %506 %507 = OpLoad %8 %496 -%508 = OpLoad %8 %496 -%509 = OpIMul %8 %507 %508 -OpStore %496 %509 +%508 = OpISub %8 %507 %7 +OpStore %496 %508 +%509 = OpLoad %8 %496 %510 = OpLoad %8 %496 -%511 = OpLoad %8 %496 -%512 = OpSDiv %8 %510 %511 -OpStore %496 %512 +%511 = OpIMul %8 %510 %509 +OpStore %496 %511 +%512 = OpLoad %8 %496 %513 = OpLoad %8 %496 -%514 = OpSRem %8 %513 %7 +%514 = OpSDiv %8 %513 %512 OpStore %496 %514 %515 = OpLoad %8 %496 -%516 = OpBitwiseAnd %8 %515 %11 +%516 = OpSRem %8 %515 %7 OpStore %496 %516 %517 = OpLoad %8 %496 -%518 = OpBitwiseOr %8 %517 %11 +%518 = OpBitwiseAnd %8 %517 %11 OpStore %496 %518 %519 = OpLoad %8 %496 -%520 = OpBitwiseXor %8 %519 %11 +%520 = OpBitwiseOr %8 %519 %11 OpStore %496 %520 %521 = OpLoad %8 %496 -%522 = OpShiftLeftLogical %8 %521 %24 +%522 = OpBitwiseXor %8 %521 %11 OpStore %496 %522 %523 = OpLoad %8 %496 -%524 = OpShiftRightArithmetic %8 %523 %25 +%524 = OpShiftLeftLogical %8 %523 %24 OpStore %496 %524 %525 = OpLoad %8 %496 -%526 = OpIAdd %8 %525 %7 +%526 = OpShiftRightArithmetic %8 %525 %25 OpStore %496 %526 %527 = OpLoad %8 %496 -%528 = OpISub %8 %527 %7 +%528 = OpIAdd %8 %527 %7 OpStore %496 %528 -%530 = OpAccessChain %529 %498 %25 -%531 = OpLoad %8 %530 -%532 = OpIAdd %8 %531 %7 -%533 = OpAccessChain %529 %498 %25 -OpStore %533 %532 -%534 = OpAccessChain %529 %498 %25 -%535 = OpLoad %8 %534 -%536 = OpISub %8 %535 %7 -%537 = OpAccessChain %529 %498 %25 -OpStore %537 %536 +%529 = OpLoad %8 %496 +%530 = OpISub %8 %529 %7 +OpStore %496 %530 +OpStore %499 %66 +%532 = OpAccessChain %531 %499 %25 +%533 = OpLoad %8 %532 +%534 = OpIAdd %8 %533 %7 +%535 = OpAccessChain %531 %499 %25 +OpStore %535 %534 +%536 = OpAccessChain %531 %499 %25 +%537 = OpLoad %8 %536 +%538 = OpISub %8 %537 %7 +%539 = OpAccessChain %531 %499 %25 +OpStore %539 %538 OpReturn OpFunctionEnd -%539 = OpFunction %2 None %172 -%538 = OpLabel -OpBranch %540 +%541 = OpFunction %2 None %172 %540 = OpLabel -%541 = OpSNegate %8 %27 -%542 = OpSNegate %8 %28 -%543 = OpSNegate %8 %29 -%544 = OpSNegate %8 %543 -%545 = OpSNegate %8 %30 +OpBranch %542 +%542 = OpLabel +%543 = OpSNegate %8 %27 +%544 = OpSNegate %8 %28 +%545 = OpSNegate %8 %29 %546 = OpSNegate %8 %545 -%547 = OpSNegate %8 %31 +%547 = OpSNegate %8 %30 %548 = OpSNegate %8 %547 -%549 = OpSNegate %8 %548 +%549 = OpSNegate %8 %31 %550 = OpSNegate %8 %549 -%551 = OpSNegate %8 %32 +%551 = OpSNegate %8 %550 %552 = OpSNegate %8 %551 -%553 = OpSNegate %8 %552 +%553 = OpSNegate %8 %32 %554 = OpSNegate %8 %553 -%555 = OpSNegate %8 %33 +%555 = OpSNegate %8 %554 %556 = OpSNegate %8 %555 -%557 = OpSNegate %8 %556 +%557 = OpSNegate %8 %33 %558 = OpSNegate %8 %557 +%559 = OpSNegate %8 %558 +%560 = OpSNegate %8 %559 OpReturn OpFunctionEnd -%560 = OpFunction %2 None %172 -%559 = OpLabel -OpBranch %561 +%562 = OpFunction %2 None %172 %561 = OpLabel -%562 = OpFunctionCall %34 %67 -%563 = OpFunctionCall %34 %92 -%564 = OpVectorShuffle %38 %50 %50 0 1 2 -%565 = OpFunctionCall %38 %127 %564 -%566 = OpFunctionCall %4 %140 -%567 = OpFunctionCall %2 %171 -%568 = OpFunctionCall %2 %189 -%569 = OpFunctionCall %2 %373 -%570 = OpFunctionCall %2 %422 -%571 = OpFunctionCall %2 %501 +OpBranch %563 +%563 = OpLabel +%564 = OpFunctionCall %34 %68 +%565 = OpFunctionCall %34 %93 +%566 = OpVectorShuffle %38 %51 %51 0 1 2 +%567 = OpFunctionCall %38 %128 %566 +%568 = OpFunctionCall %4 %140 +%569 = OpFunctionCall %2 %171 +%570 = OpFunctionCall %2 %189 +%571 = OpFunctionCall %2 %373 +%572 = OpFunctionCall %2 %422 +%573 = OpFunctionCall %2 %503 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index e20fcebc5..15f18c4f5 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 262 +; Bound: 270 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %94 "vs_main" %84 %87 %89 %91 %93 +OpEntryPoint Vertex %90 "vs_main" %80 %83 %85 %87 %89 OpEntryPoint Fragment %148 "fs_main" %139 %142 %145 %147 -OpEntryPoint Fragment %212 "fs_main_without_storage" %205 %207 %209 %211 +OpEntryPoint Fragment %217 "fs_main_without_storage" %210 %212 %214 %216 OpExecutionMode %148 OriginUpperLeft -OpExecutionMode %212 OriginUpperLeft +OpExecutionMode %217 OriginUpperLeft OpSource GLSL 450 OpName %11 "c_max_lights" OpMemberName %18 0 "view_proj" @@ -37,25 +37,25 @@ OpName %45 "sampler_shadow" OpName %48 "light_id" OpName %49 "homogeneous_coords" OpName %50 "fetch_shadow" -OpName %80 "out" -OpName %84 "position" -OpName %87 "normal" -OpName %89 "proj_position" -OpName %91 "world_normal" -OpName %93 "world_position" -OpName %94 "vs_main" -OpName %134 "color" -OpName %135 "i" +OpName %76 "out" +OpName %80 "position" +OpName %83 "normal" +OpName %85 "proj_position" +OpName %87 "world_normal" +OpName %89 "world_position" +OpName %90 "vs_main" +OpName %132 "color" +OpName %134 "i" OpName %139 "proj_position" OpName %142 "world_normal" OpName %145 "world_position" OpName %148 "fs_main" -OpName %201 "color" -OpName %202 "i" -OpName %205 "proj_position" -OpName %207 "world_normal" -OpName %209 "world_position" -OpName %212 "fs_main_without_storage" +OpName %204 "color" +OpName %206 "i" +OpName %210 "proj_position" +OpName %212 "world_normal" +OpName %214 "world_position" +OpName %217 "fs_main_without_storage" OpMemberDecorate %18 0 Offset 0 OpMemberDecorate %18 0 ColMajor OpMemberDecorate %18 0 MatrixStride 16 @@ -95,19 +95,19 @@ OpDecorate %43 DescriptorSet 0 OpDecorate %43 Binding 2 OpDecorate %45 DescriptorSet 0 OpDecorate %45 Binding 3 -OpDecorate %84 Location 0 -OpDecorate %87 Location 1 -OpDecorate %89 BuiltIn Position -OpDecorate %91 Location 0 -OpDecorate %93 Location 1 +OpDecorate %80 Location 0 +OpDecorate %83 Location 1 +OpDecorate %85 BuiltIn Position +OpDecorate %87 Location 0 +OpDecorate %89 Location 1 OpDecorate %139 BuiltIn FragCoord OpDecorate %142 Location 0 OpDecorate %145 Location 1 OpDecorate %147 Location 0 -OpDecorate %205 BuiltIn FragCoord -OpDecorate %207 Location 0 -OpDecorate %209 Location 1 -OpDecorate %211 Location 0 +OpDecorate %210 BuiltIn FragCoord +OpDecorate %212 Location 0 +OpDecorate %214 Location 1 +OpDecorate %216 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -154,261 +154,277 @@ OpDecorate %211 Location 0 %46 = OpTypePointer UniformConstant %28 %45 = OpVariable %46 UniformConstant %51 = OpTypeFunction %6 %12 %16 -%54 = OpTypePointer Uniform %19 -%55 = OpTypePointer Uniform %18 -%56 = OpTypePointer Uniform %26 -%57 = OpTypePointer StorageBuffer %25 -%60 = OpTypeBool -%75 = OpTypeSampledImage %27 -%81 = OpTypePointer Function %21 -%82 = OpConstantNull %21 -%85 = OpTypePointer Input %22 -%84 = OpVariable %85 Input -%87 = OpVariable %85 Input -%90 = OpTypePointer Output %16 -%89 = OpVariable %90 Output -%92 = OpTypePointer Output %20 -%91 = OpVariable %92 Output -%93 = OpVariable %90 Output -%95 = OpTypeFunction %2 -%99 = OpTypePointer Uniform %15 -%106 = OpTypePointer Function %20 -%114 = OpTypeVector %4 3 -%119 = OpTypePointer Function %16 -%120 = OpConstant %12 2 -%128 = OpTypePointer Output %6 -%136 = OpTypePointer Function %12 +%56 = OpTypeBool +%71 = OpTypeSampledImage %27 +%77 = OpTypePointer Function %21 +%78 = OpConstantNull %21 +%81 = OpTypePointer Input %22 +%80 = OpVariable %81 Input +%83 = OpVariable %81 Input +%86 = OpTypePointer Output %16 +%85 = OpVariable %86 Output +%88 = OpTypePointer Output %20 +%87 = OpVariable %88 Output +%89 = OpVariable %86 Output +%91 = OpTypeFunction %2 +%92 = OpTypePointer Uniform %18 +%94 = OpTypePointer Uniform %19 +%97 = OpTypePointer Uniform %15 +%104 = OpTypePointer Function %20 +%112 = OpTypeVector %4 3 +%117 = OpTypePointer Function %16 +%118 = OpConstant %12 2 +%126 = OpTypePointer Output %6 +%133 = OpConstantNull %20 +%135 = OpTypePointer Function %12 +%136 = OpConstantNull %12 %140 = OpTypePointer Input %16 %139 = OpVariable %140 Input %143 = OpTypePointer Input %20 %142 = OpVariable %143 Input %145 = OpVariable %140 Input -%147 = OpVariable %90 Output -%162 = OpTypePointer Uniform %17 -%163 = OpTypePointer Uniform %12 -%171 = OpTypePointer StorageBuffer %24 -%197 = OpTypePointer Uniform %16 -%205 = OpVariable %140 Input -%207 = OpVariable %143 Input -%209 = OpVariable %140 Input -%211 = OpVariable %90 Output -%233 = OpTypePointer Uniform %24 +%147 = OpVariable %86 Output +%151 = OpTypePointer StorageBuffer %25 +%163 = OpTypePointer Uniform %17 +%164 = OpTypePointer Uniform %12 +%174 = OpTypePointer StorageBuffer %24 +%200 = OpTypePointer Uniform %16 +%205 = OpConstantNull %20 +%207 = OpConstantNull %12 +%210 = OpVariable %140 Input +%212 = OpVariable %143 Input +%214 = OpVariable %140 Input +%216 = OpVariable %86 Output +%220 = OpTypePointer Uniform %26 +%241 = OpTypePointer Uniform %24 %50 = OpFunction %6 None %51 %48 = OpFunctionParameter %12 %49 = OpFunctionParameter %16 %47 = OpLabel %52 = OpLoad %27 %43 %53 = OpLoad %28 %45 -OpBranch %58 -%58 = OpLabel -%59 = OpCompositeExtract %6 %49 3 -%61 = OpFOrdLessThanEqual %60 %59 %5 -OpSelectionMerge %62 None -OpBranchConditional %61 %63 %62 -%63 = OpLabel +OpBranch %54 +%54 = OpLabel +%55 = OpCompositeExtract %6 %49 3 +%57 = OpFOrdLessThanEqual %56 %55 %5 +OpSelectionMerge %58 None +OpBranchConditional %57 %59 %58 +%59 = OpLabel OpReturnValue %7 -%62 = OpLabel -%64 = OpCompositeConstruct %29 %8 %9 -%65 = OpCompositeExtract %6 %49 3 -%66 = OpFDiv %6 %7 %65 -%67 = OpVectorShuffle %29 %49 %49 0 1 -%68 = OpFMul %29 %67 %64 -%69 = OpVectorTimesScalar %29 %68 %66 -%70 = OpCompositeConstruct %29 %8 %8 -%71 = OpFAdd %29 %69 %70 -%72 = OpBitcast %4 %48 -%73 = OpCompositeExtract %6 %49 2 -%74 = OpFMul %6 %73 %66 -%76 = OpConvertUToF %6 %72 -%77 = OpCompositeConstruct %20 %71 %76 -%78 = OpSampledImage %75 %52 %53 -%79 = OpImageSampleDrefExplicitLod %6 %78 %77 %74 Lod %5 -OpReturnValue %79 +%58 = OpLabel +%60 = OpCompositeConstruct %29 %8 %9 +%61 = OpCompositeExtract %6 %49 3 +%62 = OpFDiv %6 %7 %61 +%63 = OpVectorShuffle %29 %49 %49 0 1 +%64 = OpFMul %29 %63 %60 +%65 = OpVectorTimesScalar %29 %64 %62 +%66 = OpCompositeConstruct %29 %8 %8 +%67 = OpFAdd %29 %65 %66 +%68 = OpBitcast %4 %48 +%69 = OpCompositeExtract %6 %49 2 +%70 = OpFMul %6 %69 %62 +%72 = OpConvertUToF %6 %68 +%73 = OpCompositeConstruct %20 %67 %72 +%74 = OpSampledImage %71 %52 %53 +%75 = OpImageSampleDrefExplicitLod %6 %74 %73 %70 Lod %5 +OpReturnValue %75 OpFunctionEnd -%94 = OpFunction %2 None %95 -%83 = OpLabel -%80 = OpVariable %81 Function %82 -%86 = OpLoad %22 %84 -%88 = OpLoad %22 %87 -%96 = OpAccessChain %55 %31 %13 -%97 = OpAccessChain %54 %34 %13 -OpBranch %98 -%98 = OpLabel -%100 = OpAccessChain %99 %97 %13 +%90 = OpFunction %2 None %91 +%79 = OpLabel +%76 = OpVariable %77 Function %78 +%82 = OpLoad %22 %80 +%84 = OpLoad %22 %83 +%93 = OpAccessChain %92 %31 %13 +%95 = OpAccessChain %94 %34 %13 +OpBranch %96 +%96 = OpLabel +%98 = OpAccessChain %97 %95 %13 +%99 = OpLoad %15 %98 +%100 = OpAccessChain %97 %95 %13 %101 = OpLoad %15 %100 -%102 = OpAccessChain %99 %97 %13 -%103 = OpLoad %15 %102 -%104 = OpConvertSToF %16 %86 -%105 = OpMatrixTimesVector %16 %103 %104 -%107 = OpCompositeExtract %16 %101 0 +%102 = OpConvertSToF %16 %82 +%103 = OpMatrixTimesVector %16 %101 %102 +%105 = OpCompositeExtract %16 %99 0 +%106 = OpVectorShuffle %20 %105 %105 0 1 2 +%107 = OpCompositeExtract %16 %99 1 %108 = OpVectorShuffle %20 %107 %107 0 1 2 -%109 = OpCompositeExtract %16 %101 1 +%109 = OpCompositeExtract %16 %99 2 %110 = OpVectorShuffle %20 %109 %109 0 1 2 -%111 = OpCompositeExtract %16 %101 2 -%112 = OpVectorShuffle %20 %111 %111 0 1 2 -%113 = OpCompositeConstruct %23 %108 %110 %112 -%115 = OpVectorShuffle %114 %88 %88 0 1 2 -%116 = OpConvertSToF %20 %115 -%117 = OpMatrixTimesVector %20 %113 %116 -%118 = OpAccessChain %106 %80 %14 -OpStore %118 %117 -%121 = OpAccessChain %119 %80 %120 -OpStore %121 %105 -%122 = OpAccessChain %99 %96 %13 -%123 = OpLoad %15 %122 -%124 = OpMatrixTimesVector %16 %123 %105 -%125 = OpAccessChain %119 %80 %13 -OpStore %125 %124 -%126 = OpLoad %21 %80 -%127 = OpCompositeExtract %16 %126 0 -OpStore %89 %127 -%129 = OpAccessChain %128 %89 %14 -%130 = OpLoad %6 %129 -%131 = OpFNegate %6 %130 -OpStore %129 %131 -%132 = OpCompositeExtract %20 %126 1 -OpStore %91 %132 -%133 = OpCompositeExtract %16 %126 2 -OpStore %93 %133 +%111 = OpCompositeConstruct %23 %106 %108 %110 +%113 = OpVectorShuffle %112 %84 %84 0 1 2 +%114 = OpConvertSToF %20 %113 +%115 = OpMatrixTimesVector %20 %111 %114 +%116 = OpAccessChain %104 %76 %14 +OpStore %116 %115 +%119 = OpAccessChain %117 %76 %118 +OpStore %119 %103 +%120 = OpAccessChain %97 %93 %13 +%121 = OpLoad %15 %120 +%122 = OpMatrixTimesVector %16 %121 %103 +%123 = OpAccessChain %117 %76 %13 +OpStore %123 %122 +%124 = OpLoad %21 %76 +%125 = OpCompositeExtract %16 %124 0 +OpStore %85 %125 +%127 = OpAccessChain %126 %85 %14 +%128 = OpLoad %6 %127 +%129 = OpFNegate %6 %128 +OpStore %127 %129 +%130 = OpCompositeExtract %20 %124 1 +OpStore %87 %130 +%131 = OpCompositeExtract %16 %124 2 +OpStore %89 %131 OpReturn OpFunctionEnd -%148 = OpFunction %2 None %95 +%148 = OpFunction %2 None %91 %137 = OpLabel -%134 = OpVariable %106 Function %30 -%135 = OpVariable %136 Function %13 +%132 = OpVariable %104 Function %133 +%134 = OpVariable %135 Function %136 %141 = OpLoad %16 %139 %144 = OpLoad %20 %142 %146 = OpLoad %16 %145 %138 = OpCompositeConstruct %21 %141 %144 %146 -%149 = OpAccessChain %55 %31 %13 -%150 = OpAccessChain %54 %34 %13 -%151 = OpAccessChain %57 %37 %13 -%152 = OpLoad %27 %43 -%153 = OpLoad %28 %45 -OpBranch %154 -%154 = OpLabel -%155 = OpCompositeExtract %20 %138 1 -%156 = OpExtInst %20 %1 Normalize %155 -OpBranch %157 -%157 = OpLabel -OpLoopMerge %158 %160 None -OpBranch %159 -%159 = OpLabel -%161 = OpLoad %12 %135 -%164 = OpAccessChain %163 %149 %14 %13 -%165 = OpLoad %12 %164 -%166 = OpExtInst %12 %1 UMin %165 %11 -%167 = OpULessThan %60 %161 %166 -OpSelectionMerge %168 None -OpBranchConditional %167 %168 %169 -%169 = OpLabel +%149 = OpAccessChain %92 %31 %13 +%150 = OpAccessChain %94 %34 %13 +%152 = OpAccessChain %151 %37 %13 +%153 = OpLoad %27 %43 +%154 = OpLoad %28 %45 +OpBranch %155 +%155 = OpLabel +%156 = OpCompositeExtract %20 %138 1 +%157 = OpExtInst %20 %1 Normalize %156 +OpStore %132 %30 +OpStore %134 %13 OpBranch %158 -%168 = OpLabel -%170 = OpLoad %12 %135 -%172 = OpAccessChain %171 %151 %170 -%173 = OpLoad %24 %172 -%174 = OpLoad %12 %135 -%175 = OpCompositeExtract %15 %173 0 -%176 = OpCompositeExtract %16 %138 2 -%177 = OpMatrixTimesVector %16 %175 %176 -%178 = OpFunctionCall %6 %50 %174 %177 -%179 = OpCompositeExtract %16 %173 1 -%180 = OpVectorShuffle %20 %179 %179 0 1 2 -%181 = OpCompositeExtract %16 %138 2 -%182 = OpVectorShuffle %20 %181 %181 0 1 2 -%183 = OpFSub %20 %180 %182 -%184 = OpExtInst %20 %1 Normalize %183 -%185 = OpDot %6 %156 %184 -%186 = OpExtInst %6 %1 FMax %5 %185 -%187 = OpLoad %20 %134 -%188 = OpFMul %6 %178 %186 -%189 = OpCompositeExtract %16 %173 2 -%190 = OpVectorShuffle %20 %189 %189 0 1 2 -%191 = OpVectorTimesScalar %20 %190 %188 -%192 = OpFAdd %20 %187 %191 -OpStore %134 %192 +%158 = OpLabel +OpLoopMerge %159 %161 None OpBranch %160 %160 = OpLabel -%193 = OpLoad %12 %135 -%194 = OpIAdd %12 %193 %14 -OpStore %135 %194 -OpBranch %157 -%158 = OpLabel -%195 = OpLoad %20 %134 -%196 = OpCompositeConstruct %16 %195 %7 -%198 = OpAccessChain %197 %150 %14 -%199 = OpLoad %16 %198 -%200 = OpFMul %16 %196 %199 -OpStore %147 %200 +%162 = OpLoad %12 %134 +%165 = OpAccessChain %164 %149 %14 %13 +%166 = OpLoad %12 %165 +%167 = OpExtInst %12 %1 UMin %166 %11 +%168 = OpULessThan %56 %162 %167 +OpSelectionMerge %169 None +OpBranchConditional %168 %169 %170 +%170 = OpLabel +OpBranch %159 +%169 = OpLabel +OpBranch %171 +%171 = OpLabel +%173 = OpLoad %12 %134 +%175 = OpAccessChain %174 %152 %173 +%176 = OpLoad %24 %175 +%177 = OpLoad %12 %134 +%178 = OpCompositeExtract %15 %176 0 +%179 = OpCompositeExtract %16 %138 2 +%180 = OpMatrixTimesVector %16 %178 %179 +%181 = OpFunctionCall %6 %50 %177 %180 +%182 = OpCompositeExtract %16 %176 1 +%183 = OpVectorShuffle %20 %182 %182 0 1 2 +%184 = OpCompositeExtract %16 %138 2 +%185 = OpVectorShuffle %20 %184 %184 0 1 2 +%186 = OpFSub %20 %183 %185 +%187 = OpExtInst %20 %1 Normalize %186 +%188 = OpDot %6 %157 %187 +%189 = OpExtInst %6 %1 FMax %5 %188 +%190 = OpFMul %6 %181 %189 +%191 = OpCompositeExtract %16 %176 2 +%192 = OpVectorShuffle %20 %191 %191 0 1 2 +%193 = OpVectorTimesScalar %20 %192 %190 +%194 = OpLoad %20 %132 +%195 = OpFAdd %20 %194 %193 +OpStore %132 %195 +OpBranch %172 +%172 = OpLabel +OpBranch %161 +%161 = OpLabel +%196 = OpLoad %12 %134 +%197 = OpIAdd %12 %196 %14 +OpStore %134 %197 +OpBranch %158 +%159 = OpLabel +%198 = OpLoad %20 %132 +%199 = OpCompositeConstruct %16 %198 %7 +%201 = OpAccessChain %200 %150 %14 +%202 = OpLoad %16 %201 +%203 = OpFMul %16 %199 %202 +OpStore %147 %203 OpReturn OpFunctionEnd -%212 = OpFunction %2 None %95 -%203 = OpLabel -%201 = OpVariable %106 Function %30 -%202 = OpVariable %136 Function %13 -%206 = OpLoad %16 %205 -%208 = OpLoad %20 %207 -%210 = OpLoad %16 %209 -%204 = OpCompositeConstruct %21 %206 %208 %210 -%213 = OpAccessChain %55 %31 %13 -%214 = OpAccessChain %54 %34 %13 -%215 = OpAccessChain %56 %40 %13 -%216 = OpLoad %27 %43 -%217 = OpLoad %28 %45 -OpBranch %218 -%218 = OpLabel -%219 = OpCompositeExtract %20 %204 1 -%220 = OpExtInst %20 %1 Normalize %219 -OpBranch %221 -%221 = OpLabel -OpLoopMerge %222 %224 None -OpBranch %223 -%223 = OpLabel -%225 = OpLoad %12 %202 -%226 = OpAccessChain %163 %213 %14 %13 -%227 = OpLoad %12 %226 -%228 = OpExtInst %12 %1 UMin %227 %11 -%229 = OpULessThan %60 %225 %228 -OpSelectionMerge %230 None -OpBranchConditional %229 %230 %231 -%231 = OpLabel -OpBranch %222 -%230 = OpLabel -%232 = OpLoad %12 %202 -%234 = OpAccessChain %233 %215 %232 -%235 = OpLoad %24 %234 -%236 = OpLoad %12 %202 -%237 = OpCompositeExtract %15 %235 0 -%238 = OpCompositeExtract %16 %204 2 -%239 = OpMatrixTimesVector %16 %237 %238 -%240 = OpFunctionCall %6 %50 %236 %239 -%241 = OpCompositeExtract %16 %235 1 -%242 = OpVectorShuffle %20 %241 %241 0 1 2 -%243 = OpCompositeExtract %16 %204 2 -%244 = OpVectorShuffle %20 %243 %243 0 1 2 -%245 = OpFSub %20 %242 %244 -%246 = OpExtInst %20 %1 Normalize %245 -%247 = OpDot %6 %220 %246 -%248 = OpExtInst %6 %1 FMax %5 %247 -%249 = OpLoad %20 %201 -%250 = OpFMul %6 %240 %248 -%251 = OpCompositeExtract %16 %235 2 -%252 = OpVectorShuffle %20 %251 %251 0 1 2 -%253 = OpVectorTimesScalar %20 %252 %250 -%254 = OpFAdd %20 %249 %253 -OpStore %201 %254 +%217 = OpFunction %2 None %91 +%208 = OpLabel +%204 = OpVariable %104 Function %205 +%206 = OpVariable %135 Function %207 +%211 = OpLoad %16 %210 +%213 = OpLoad %20 %212 +%215 = OpLoad %16 %214 +%209 = OpCompositeConstruct %21 %211 %213 %215 +%218 = OpAccessChain %92 %31 %13 +%219 = OpAccessChain %94 %34 %13 +%221 = OpAccessChain %220 %40 %13 +%222 = OpLoad %27 %43 +%223 = OpLoad %28 %45 OpBranch %224 %224 = OpLabel -%255 = OpLoad %12 %202 -%256 = OpIAdd %12 %255 %14 -OpStore %202 %256 -OpBranch %221 -%222 = OpLabel -%257 = OpLoad %20 %201 -%258 = OpCompositeConstruct %16 %257 %7 -%259 = OpAccessChain %197 %214 %14 -%260 = OpLoad %16 %259 -%261 = OpFMul %16 %258 %260 -OpStore %211 %261 +%225 = OpCompositeExtract %20 %209 1 +%226 = OpExtInst %20 %1 Normalize %225 +OpStore %204 %30 +OpStore %206 %13 +OpBranch %227 +%227 = OpLabel +OpLoopMerge %228 %230 None +OpBranch %229 +%229 = OpLabel +%231 = OpLoad %12 %206 +%232 = OpAccessChain %164 %218 %14 %13 +%233 = OpLoad %12 %232 +%234 = OpExtInst %12 %1 UMin %233 %11 +%235 = OpULessThan %56 %231 %234 +OpSelectionMerge %236 None +OpBranchConditional %235 %236 %237 +%237 = OpLabel +OpBranch %228 +%236 = OpLabel +OpBranch %238 +%238 = OpLabel +%240 = OpLoad %12 %206 +%242 = OpAccessChain %241 %221 %240 +%243 = OpLoad %24 %242 +%244 = OpLoad %12 %206 +%245 = OpCompositeExtract %15 %243 0 +%246 = OpCompositeExtract %16 %209 2 +%247 = OpMatrixTimesVector %16 %245 %246 +%248 = OpFunctionCall %6 %50 %244 %247 +%249 = OpCompositeExtract %16 %243 1 +%250 = OpVectorShuffle %20 %249 %249 0 1 2 +%251 = OpCompositeExtract %16 %209 2 +%252 = OpVectorShuffle %20 %251 %251 0 1 2 +%253 = OpFSub %20 %250 %252 +%254 = OpExtInst %20 %1 Normalize %253 +%255 = OpDot %6 %226 %254 +%256 = OpExtInst %6 %1 FMax %5 %255 +%257 = OpFMul %6 %248 %256 +%258 = OpCompositeExtract %16 %243 2 +%259 = OpVectorShuffle %20 %258 %258 0 1 2 +%260 = OpVectorTimesScalar %20 %259 %257 +%261 = OpLoad %20 %204 +%262 = OpFAdd %20 %261 %260 +OpStore %204 %262 +OpBranch %239 +%239 = OpLabel +OpBranch %230 +%230 = OpLabel +%263 = OpLoad %12 %206 +%264 = OpIAdd %12 %263 %14 +OpStore %206 %264 +OpBranch %227 +%228 = OpLabel +%265 = OpLoad %20 %204 +%266 = OpCompositeConstruct %16 %265 %7 +%267 = OpAccessChain %200 %219 %14 +%268 = OpLoad %16 %267 +%269 = OpFMul %16 %266 %268 +OpStore %216 %269 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 2a2570454..31054c870 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -36,82 +36,84 @@ var nested_mat_cx2_: MatCx2InArray; var val: u32; fn test_matrix_within_struct_accesses() { - var idx: i32 = 1; + var idx: i32; var t: Baz; - let _e6 = idx; - idx = (_e6 - 1); + idx = 1; + let _e2 = idx; + idx = (_e2 - 1); _ = baz.m; _ = baz.m[0]; - let _e16 = idx; - _ = baz.m[_e16]; + let _e15 = idx; + _ = baz.m[_e15]; _ = baz.m[0][1]; - let _e28 = idx; - _ = baz.m[0][_e28]; - let _e32 = idx; - _ = baz.m[_e32][1]; - let _e38 = idx; - let _e40 = idx; - _ = baz.m[_e38][_e40]; + let _e29 = idx; + _ = baz.m[0][_e29]; + let _e34 = idx; + _ = baz.m[_e34][1]; + let _e41 = idx; + let _e43 = idx; + _ = baz.m[_e41][_e43]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - let _e52 = idx; - idx = (_e52 + 1); + let _e55 = idx; + idx = (_e55 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - let _e69 = idx; - t.m[_e69] = vec2(90.0); + let _e72 = idx; + t.m[_e72] = vec2(90.0); t.m[0][1] = 10.0; - let _e82 = idx; - t.m[0][_e82] = 20.0; - let _e86 = idx; - t.m[_e86][1] = 30.0; - let _e92 = idx; - let _e94 = idx; - t.m[_e92][_e94] = 40.0; + let _e85 = idx; + t.m[0][_e85] = 20.0; + let _e89 = idx; + t.m[_e89][1] = 30.0; + let _e95 = idx; + let _e97 = idx; + t.m[_e95][_e97] = 40.0; return; } fn test_matrix_within_array_within_struct_accesses() { - var idx_1: i32 = 1; + var idx_1: i32; var t_1: MatCx2InArray; - let _e7 = idx_1; - idx_1 = (_e7 - 1); + idx_1 = 1; + let _e2 = idx_1; + idx_1 = (_e2 - 1); _ = nested_mat_cx2_.am; _ = nested_mat_cx2_.am[0]; _ = nested_mat_cx2_.am[0][0]; - let _e25 = idx_1; - _ = nested_mat_cx2_.am[0][_e25]; + let _e24 = idx_1; + _ = nested_mat_cx2_.am[0][_e24]; _ = nested_mat_cx2_.am[0][0][1]; - let _e41 = idx_1; - _ = nested_mat_cx2_.am[0][0][_e41]; - let _e47 = idx_1; - _ = nested_mat_cx2_.am[0][_e47][1]; - let _e55 = idx_1; - let _e57 = idx_1; - _ = nested_mat_cx2_.am[0][_e55][_e57]; + let _e42 = idx_1; + _ = nested_mat_cx2_.am[0][0][_e42]; + let _e49 = idx_1; + _ = nested_mat_cx2_.am[0][_e49][1]; + let _e58 = idx_1; + let _e60 = idx_1; + _ = nested_mat_cx2_.am[0][_e58][_e60]; t_1 = MatCx2InArray(array,2>(mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)))); - let _e63 = idx_1; - idx_1 = (_e63 + 1); + let _e66 = idx_1; + idx_1 = (_e66 + 1); t_1.am = array,2>(mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0))); t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); t_1.am[0][0] = vec2(9.0); - let _e90 = idx_1; - t_1.am[0][_e90] = vec2(90.0); + let _e93 = idx_1; + t_1.am[0][_e93] = vec2(90.0); t_1.am[0][0][1] = 10.0; - let _e107 = idx_1; - t_1.am[0][0][_e107] = 20.0; - let _e113 = idx_1; - t_1.am[0][_e113][1] = 30.0; - let _e121 = idx_1; - let _e123 = idx_1; - t_1.am[0][_e121][_e123] = 40.0; + let _e110 = idx_1; + t_1.am[0][0][_e110] = 20.0; + let _e116 = idx_1; + t_1.am[0][_e116][1] = 30.0; + let _e124 = idx_1; + let _e126 = idx_1; + t_1.am[0][_e124][_e126] = 40.0; return; } fn read_from_private(foo_1: ptr) -> f32 { - let _e6 = (*foo_1); - return _e6; + let _e1 = (*foo_1); + return _e1; } fn test_arr_as_arg(a: array,5>) -> f32 { @@ -125,9 +127,10 @@ fn assign_through_ptr_fn(p: ptr) { @vertex fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { - var foo: f32 = 0.0; - var c: array; + var foo: f32; + var c2_: array; + foo = 0.0; let baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); @@ -136,13 +139,13 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let arr = bar.arr; let b = bar._matrix[3][0]; let a_1 = bar.data[(arrayLength((&bar.data)) - 2u)].value; - let c_1 = qux; + let c = qux; let data_pointer = (&bar.data[0].value); - let _e32 = read_from_private((&foo)); - c = array(a_1, i32(b), 3, 4, 5); - c[(vi + 1u)] = 42; - let value = c[vi]; - let _e46 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + let _e34 = read_from_private((&foo)); + c2_ = array(a_1, i32(b), 3, 4, 5); + c2_[(vi + 1u)] = 42; + let value = c2_[vi]; + let _e48 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); return vec4((_matrix * vec4(vec4(value))), 2.0); } @@ -161,22 +164,22 @@ fn atomics() { var tmp: i32; let value_1 = atomicLoad((&bar.atom)); - let _e10 = atomicAdd((&bar.atom), 5); - tmp = _e10; - let _e13 = atomicSub((&bar.atom), 5); - tmp = _e13; - let _e16 = atomicAnd((&bar.atom), 5); - tmp = _e16; + let _e7 = atomicAdd((&bar.atom), 5); + tmp = _e7; + let _e11 = atomicSub((&bar.atom), 5); + tmp = _e11; + let _e15 = atomicAnd((&bar.atom), 5); + tmp = _e15; let _e19 = atomicOr((&bar.atom), 5); tmp = _e19; - let _e22 = atomicXor((&bar.atom), 5); - tmp = _e22; - let _e25 = atomicMin((&bar.atom), 5); - tmp = _e25; - let _e28 = atomicMax((&bar.atom), 5); - tmp = _e28; - let _e31 = atomicExchange((&bar.atom), 5); + let _e23 = atomicXor((&bar.atom), 5); + tmp = _e23; + let _e27 = atomicMin((&bar.atom), 5); + tmp = _e27; + let _e31 = atomicMax((&bar.atom), 5); tmp = _e31; + let _e35 = atomicExchange((&bar.atom), 5); + tmp = _e35; atomicStore((&bar.atom), value_1); return; } diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/tests/out/wgsl/atomicCompareExchange.wgsl index b1e2d06a4..2c213c8fe 100644 --- a/tests/out/wgsl/atomicCompareExchange.wgsl +++ b/tests/out/wgsl/atomicCompareExchange.wgsl @@ -8,7 +8,7 @@ struct gen___atomic_compare_exchange_result_1 { exchanged: bool, } -let SIZE: u32 = 128u; +const SIZE: u32 = 128u; @group(0) @binding(0) var arr_i32_: array,SIZE>; @@ -17,37 +17,42 @@ var arr_u32_: array,SIZE>; @compute @workgroup_size(1, 1, 1) fn test_atomic_compare_exchange_i32_() { - var i: u32 = 0u; + var i: u32; var old: i32; var exchanged: bool; + i = 0u; loop { - let _e5 = i; - if (_e5 < SIZE) { + let _e2 = i; + if (_e2 < SIZE) { } else { break; } - let _e10 = i; - let _e12 = atomicLoad((&arr_i32_[_e10])); - old = _e12; - exchanged = false; - loop { - let _e16 = exchanged; - if !(_e16) { - } else { - break; + { + let _e6 = i; + let _e8 = atomicLoad((&arr_i32_[_e6])); + old = _e8; + exchanged = false; + loop { + let _e12 = exchanged; + if !(_e12) { + } else { + break; + } + { + let _e14 = old; + let new_ = bitcast((bitcast(_e14) + 1.0)); + let _e20 = i; + let _e22 = old; + let _e23 = atomicCompareExchangeWeak((&arr_i32_[_e20]), _e22, new_); + old = _e23.old_value; + exchanged = _e23.exchanged; + } } - let _e18 = old; - let new_ = bitcast((bitcast(_e18) + 1.0)); - let _e23 = i; - let _e25 = old; - let _e26 = atomicCompareExchangeWeak((&arr_i32_[_e23]), _e25, new_); - old = _e26.old_value; - exchanged = _e26.exchanged; } continuing { - let _e7 = i; - i = (_e7 + 1u); + let _e26 = i; + i = (_e26 + 1u); } } return; @@ -55,37 +60,42 @@ fn test_atomic_compare_exchange_i32_() { @compute @workgroup_size(1, 1, 1) fn test_atomic_compare_exchange_u32_() { - var i_1: u32 = 0u; + var i_1: u32; var old_1: u32; var exchanged_1: bool; + i_1 = 0u; loop { - let _e5 = i_1; - if (_e5 < SIZE) { + let _e2 = i_1; + if (_e2 < SIZE) { } else { break; } - let _e10 = i_1; - let _e12 = atomicLoad((&arr_u32_[_e10])); - old_1 = _e12; - exchanged_1 = false; - loop { - let _e16 = exchanged_1; - if !(_e16) { - } else { - break; + { + let _e6 = i_1; + let _e8 = atomicLoad((&arr_u32_[_e6])); + old_1 = _e8; + exchanged_1 = false; + loop { + let _e12 = exchanged_1; + if !(_e12) { + } else { + break; + } + { + let _e14 = old_1; + let new_1 = bitcast((bitcast(_e14) + 1.0)); + let _e20 = i_1; + let _e22 = old_1; + let _e23 = atomicCompareExchangeWeak((&arr_u32_[_e20]), _e22, new_1); + old_1 = _e23.old_value; + exchanged_1 = _e23.exchanged; + } } - let _e18 = old_1; - let new_1 = bitcast((bitcast(_e18) + 1.0)); - let _e23 = i_1; - let _e25 = old_1; - let _e26 = atomicCompareExchangeWeak((&arr_u32_[_e23]), _e25, new_1); - old_1 = _e26.old_value; - exchanged_1 = _e26.exchanged; } continuing { - let _e7 = i_1; - i_1 = (_e7 + 1u); + let _e26 = i_1; + i_1 = (_e26 + 1u); } } return; diff --git a/tests/out/wgsl/binding-arrays.wgsl b/tests/out/wgsl/binding-arrays.wgsl index 0760aef72..e3abd5c35 100644 --- a/tests/out/wgsl/binding-arrays.wgsl +++ b/tests/out/wgsl/binding-arrays.wgsl @@ -27,144 +27,146 @@ var uni: UniformIndex; @fragment fn main(fragment_in: FragmentIn) -> @location(0) vec4 { - var i1_: i32 = 0; + var i1_: i32; var i2_: vec2; - var v1_: f32 = 0.0; + var v1_: f32; var v4_: vec4; let uniform_index = uni.index; let non_uniform_index = fragment_in.index; + i1_ = 0; i2_ = vec2(0); + v1_ = 0.0; v4_ = vec4(0.0); let uv = vec2(0.0); let pix = vec2(0); - let _e27 = i2_; - let _e30 = textureDimensions(texture_array_unbounded[0]); - i2_ = (_e27 + _e30); - let _e32 = i2_; - let _e34 = textureDimensions(texture_array_unbounded[uniform_index]); - i2_ = (_e32 + _e34); - let _e36 = i2_; - let _e38 = textureDimensions(texture_array_unbounded[non_uniform_index]); - i2_ = (_e36 + _e38); - let _e40 = v4_; - let _e45 = textureGather(0, texture_array_bounded[0], samp[0], uv); - v4_ = (_e40 + _e45); - let _e47 = v4_; - let _e50 = textureGather(0, texture_array_bounded[uniform_index], samp[uniform_index], uv); - v4_ = (_e47 + _e50); - let _e52 = v4_; + let _e22 = textureDimensions(texture_array_unbounded[0]); + let _e23 = i2_; + i2_ = (_e23 + _e22); + let _e27 = textureDimensions(texture_array_unbounded[uniform_index]); + let _e28 = i2_; + i2_ = (_e28 + _e27); + let _e32 = textureDimensions(texture_array_unbounded[non_uniform_index]); + let _e33 = i2_; + i2_ = (_e33 + _e32); + let _e41 = textureGather(0, texture_array_bounded[0], samp[0], uv); + let _e42 = v4_; + v4_ = (_e42 + _e41); + let _e48 = textureGather(0, texture_array_bounded[uniform_index], samp[uniform_index], uv); + let _e49 = v4_; + v4_ = (_e49 + _e48); let _e55 = textureGather(0, texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); - v4_ = (_e52 + _e55); - let _e57 = v4_; - let _e63 = textureGatherCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); - v4_ = (_e57 + _e63); - let _e65 = v4_; - let _e69 = textureGatherCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); - v4_ = (_e65 + _e69); - let _e71 = v4_; - let _e75 = textureGatherCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); - v4_ = (_e71 + _e75); - let _e77 = v4_; - let _e81 = textureLoad(texture_array_unbounded[0], pix, 0); - v4_ = (_e77 + _e81); - let _e83 = v4_; - let _e86 = textureLoad(texture_array_unbounded[uniform_index], pix, 0); - v4_ = (_e83 + _e86); - let _e88 = v4_; - let _e91 = textureLoad(texture_array_unbounded[non_uniform_index], pix, 0); - v4_ = (_e88 + _e91); - let _e93 = i1_; - let _e96 = textureNumLayers(texture_array_2darray[0]); - i1_ = (_e93 + _e96); - let _e98 = i1_; - let _e100 = textureNumLayers(texture_array_2darray[uniform_index]); - i1_ = (_e98 + _e100); - let _e102 = i1_; - let _e104 = textureNumLayers(texture_array_2darray[non_uniform_index]); - i1_ = (_e102 + _e104); - let _e106 = i1_; - let _e109 = textureNumLevels(texture_array_bounded[0]); - i1_ = (_e106 + _e109); - let _e111 = i1_; - let _e113 = textureNumLevels(texture_array_bounded[uniform_index]); - i1_ = (_e111 + _e113); - let _e115 = i1_; - let _e117 = textureNumLevels(texture_array_bounded[non_uniform_index]); - i1_ = (_e115 + _e117); - let _e119 = i1_; - let _e122 = textureNumSamples(texture_array_multisampled[0]); - i1_ = (_e119 + _e122); - let _e124 = i1_; - let _e126 = textureNumSamples(texture_array_multisampled[uniform_index]); - i1_ = (_e124 + _e126); + let _e56 = v4_; + v4_ = (_e56 + _e55); + let _e65 = textureGatherCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e66 = v4_; + v4_ = (_e66 + _e65); + let _e73 = textureGatherCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + let _e74 = v4_; + v4_ = (_e74 + _e73); + let _e81 = textureGatherCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + let _e82 = v4_; + v4_ = (_e82 + _e81); + let _e88 = textureLoad(texture_array_unbounded[0], pix, 0); + let _e89 = v4_; + v4_ = (_e89 + _e88); + let _e94 = textureLoad(texture_array_unbounded[uniform_index], pix, 0); + let _e95 = v4_; + v4_ = (_e95 + _e94); + let _e100 = textureLoad(texture_array_unbounded[non_uniform_index], pix, 0); + let _e101 = v4_; + v4_ = (_e101 + _e100); + let _e106 = textureNumLayers(texture_array_2darray[0]); + let _e107 = i1_; + i1_ = (_e107 + _e106); + let _e111 = textureNumLayers(texture_array_2darray[uniform_index]); + let _e112 = i1_; + i1_ = (_e112 + _e111); + let _e116 = textureNumLayers(texture_array_2darray[non_uniform_index]); + let _e117 = i1_; + i1_ = (_e117 + _e116); + let _e122 = textureNumLevels(texture_array_bounded[0]); + let _e123 = i1_; + i1_ = (_e123 + _e122); + let _e127 = textureNumLevels(texture_array_bounded[uniform_index]); let _e128 = i1_; - let _e130 = textureNumSamples(texture_array_multisampled[non_uniform_index]); - i1_ = (_e128 + _e130); - let _e132 = v4_; - let _e137 = textureSample(texture_array_bounded[0], samp[0], uv); - v4_ = (_e132 + _e137); - let _e139 = v4_; - let _e142 = textureSample(texture_array_bounded[uniform_index], samp[uniform_index], uv); - v4_ = (_e139 + _e142); - let _e144 = v4_; - let _e147 = textureSample(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); - v4_ = (_e144 + _e147); - let _e149 = v4_; - let _e155 = textureSampleBias(texture_array_bounded[0], samp[0], uv, 0.0); - v4_ = (_e149 + _e155); - let _e157 = v4_; - let _e161 = textureSampleBias(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); - v4_ = (_e157 + _e161); - let _e163 = v4_; - let _e167 = textureSampleBias(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); - v4_ = (_e163 + _e167); - let _e169 = v1_; - let _e175 = textureSampleCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); - v1_ = (_e169 + _e175); - let _e177 = v1_; - let _e181 = textureSampleCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); - v1_ = (_e177 + _e181); - let _e183 = v1_; - let _e187 = textureSampleCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); - v1_ = (_e183 + _e187); - let _e189 = v1_; - let _e195 = textureSampleCompareLevel(texture_array_depth[0], samp_comp[0], uv, 0.0); - v1_ = (_e189 + _e195); - let _e197 = v1_; - let _e201 = textureSampleCompareLevel(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); - v1_ = (_e197 + _e201); - let _e203 = v1_; - let _e207 = textureSampleCompareLevel(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); - v1_ = (_e203 + _e207); - let _e209 = v4_; - let _e214 = textureSampleGrad(texture_array_bounded[0], samp[0], uv, uv, uv); - v4_ = (_e209 + _e214); - let _e216 = v4_; - let _e219 = textureSampleGrad(texture_array_bounded[uniform_index], samp[uniform_index], uv, uv, uv); - v4_ = (_e216 + _e219); - let _e221 = v4_; - let _e224 = textureSampleGrad(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, uv, uv); - v4_ = (_e221 + _e224); - let _e226 = v4_; - let _e232 = textureSampleLevel(texture_array_bounded[0], samp[0], uv, 0.0); - v4_ = (_e226 + _e232); - let _e234 = v4_; - let _e238 = textureSampleLevel(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); - v4_ = (_e234 + _e238); - let _e240 = v4_; - let _e244 = textureSampleLevel(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); - v4_ = (_e240 + _e244); - let _e248 = v4_; - textureStore(texture_array_storage[0], pix, _e248); - let _e250 = v4_; - textureStore(texture_array_storage[uniform_index], pix, _e250); - let _e252 = v4_; - textureStore(texture_array_storage[non_uniform_index], pix, _e252); - let _e253 = i2_; - let _e254 = i1_; - let v2_ = vec2((_e253 + vec2(_e254))); - let _e258 = v4_; - let _e265 = v1_; - return ((_e258 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e265)); + i1_ = (_e128 + _e127); + let _e132 = textureNumLevels(texture_array_bounded[non_uniform_index]); + let _e133 = i1_; + i1_ = (_e133 + _e132); + let _e138 = textureNumSamples(texture_array_multisampled[0]); + let _e139 = i1_; + i1_ = (_e139 + _e138); + let _e143 = textureNumSamples(texture_array_multisampled[uniform_index]); + let _e144 = i1_; + i1_ = (_e144 + _e143); + let _e148 = textureNumSamples(texture_array_multisampled[non_uniform_index]); + let _e149 = i1_; + i1_ = (_e149 + _e148); + let _e157 = textureSample(texture_array_bounded[0], samp[0], uv); + let _e158 = v4_; + v4_ = (_e158 + _e157); + let _e164 = textureSample(texture_array_bounded[uniform_index], samp[uniform_index], uv); + let _e165 = v4_; + v4_ = (_e165 + _e164); + let _e171 = textureSample(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); + let _e172 = v4_; + v4_ = (_e172 + _e171); + let _e181 = textureSampleBias(texture_array_bounded[0], samp[0], uv, 0.0); + let _e182 = v4_; + v4_ = (_e182 + _e181); + let _e189 = textureSampleBias(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + let _e190 = v4_; + v4_ = (_e190 + _e189); + let _e197 = textureSampleBias(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); + let _e198 = v4_; + v4_ = (_e198 + _e197); + let _e207 = textureSampleCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e208 = v1_; + v1_ = (_e208 + _e207); + let _e215 = textureSampleCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + let _e216 = v1_; + v1_ = (_e216 + _e215); + let _e223 = textureSampleCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + let _e224 = v1_; + v1_ = (_e224 + _e223); + let _e233 = textureSampleCompareLevel(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e234 = v1_; + v1_ = (_e234 + _e233); + let _e241 = textureSampleCompareLevel(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + let _e242 = v1_; + v1_ = (_e242 + _e241); + let _e249 = textureSampleCompareLevel(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + let _e250 = v1_; + v1_ = (_e250 + _e249); + let _e258 = textureSampleGrad(texture_array_bounded[0], samp[0], uv, uv, uv); + let _e259 = v4_; + v4_ = (_e259 + _e258); + let _e265 = textureSampleGrad(texture_array_bounded[uniform_index], samp[uniform_index], uv, uv, uv); + let _e266 = v4_; + v4_ = (_e266 + _e265); + let _e272 = textureSampleGrad(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, uv, uv); + let _e273 = v4_; + v4_ = (_e273 + _e272); + let _e282 = textureSampleLevel(texture_array_bounded[0], samp[0], uv, 0.0); + let _e283 = v4_; + v4_ = (_e283 + _e282); + let _e290 = textureSampleLevel(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + let _e291 = v4_; + v4_ = (_e291 + _e290); + let _e298 = textureSampleLevel(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); + let _e299 = v4_; + v4_ = (_e299 + _e298); + let _e304 = v4_; + textureStore(texture_array_storage[0], pix, _e304); + let _e307 = v4_; + textureStore(texture_array_storage[uniform_index], pix, _e307); + let _e310 = v4_; + textureStore(texture_array_storage[non_uniform_index], pix, _e310); + let _e311 = i2_; + let _e312 = i1_; + let v2_ = vec2((_e311 + vec2(_e312))); + let _e316 = v4_; + let _e323 = v1_; + return ((_e316 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e323)); } diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index ccaebff41..88876ec05 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -1,19 +1,21 @@ @compute @workgroup_size(1, 1, 1) fn main() { - var i: i32 = 0; + var i: i32; var i2_: vec2; var i3_: vec3; var i4_: vec4; - var u: u32 = 0u; + var u: u32; var u2_: vec2; var u3_: vec3; var u4_: vec4; var f2_: vec2; var f4_: vec4; + i = 0; i2_ = vec2(0); i3_ = vec3(0); i4_ = vec4(0); + u = 0u; u2_ = vec2(0u); u3_ = vec3(0u); u4_ = vec4(0u); diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index fd143f79f..a3f03dd2d 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -17,7 +17,7 @@ struct Particles { particles: array, } -let NUM_PARTICLES: u32 = 1500u; +const NUM_PARTICLES: u32 = 1500u; @group(0) @binding(0) var params: SimParams; @@ -33,119 +33,122 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { var cMass: vec2; var cVel: vec2; var colVel: vec2; - var cMassCount: i32 = 0; - var cVelCount: i32 = 0; + var cMassCount: i32; + var cVelCount: i32; var pos: vec2; var vel: vec2; - var i: u32 = 0u; + var i: u32; let index = global_invocation_id.x; if (index >= NUM_PARTICLES) { return; } - let _e10 = particlesSrc.particles[index].pos; - vPos = _e10; - let _e15 = particlesSrc.particles[index].vel; - vVel = _e15; + let _e8 = particlesSrc.particles[index].pos; + vPos = _e8; + let _e14 = particlesSrc.particles[index].vel; + vVel = _e14; cMass = vec2(0.0, 0.0); cVel = vec2(0.0, 0.0); colVel = vec2(0.0, 0.0); + cMassCount = 0; + cVelCount = 0; + i = 0u; loop { - let _e37 = i; - if (_e37 >= NUM_PARTICLES) { + let _e36 = i; + if (_e36 >= NUM_PARTICLES) { break; } let _e39 = i; if (_e39 == index) { continue; } - let _e42 = i; - let _e45 = particlesSrc.particles[_e42].pos; - pos = _e45; - let _e47 = i; - let _e50 = particlesSrc.particles[_e47].vel; - vel = _e50; - let _e51 = pos; - let _e52 = vPos; - let _e55 = params.rule1Distance; - if (distance(_e51, _e52) < _e55) { - let _e57 = cMass; - let _e58 = pos; - cMass = (_e57 + _e58); - let _e60 = cMassCount; - cMassCount = (_e60 + 1); + let _e43 = i; + let _e46 = particlesSrc.particles[_e43].pos; + pos = _e46; + let _e49 = i; + let _e52 = particlesSrc.particles[_e49].vel; + vel = _e52; + let _e53 = pos; + let _e54 = vPos; + let _e58 = params.rule1Distance; + if (distance(_e53, _e54) < _e58) { + let _e60 = cMass; + let _e61 = pos; + cMass = (_e60 + _e61); + let _e63 = cMassCount; + cMassCount = (_e63 + 1); } - let _e63 = pos; - let _e64 = vPos; - let _e67 = params.rule2Distance; - if (distance(_e63, _e64) < _e67) { - let _e69 = colVel; - let _e70 = pos; - let _e71 = vPos; - colVel = (_e69 - (_e70 - _e71)); + let _e66 = pos; + let _e67 = vPos; + let _e71 = params.rule2Distance; + if (distance(_e66, _e67) < _e71) { + let _e73 = colVel; + let _e74 = pos; + let _e75 = vPos; + colVel = (_e73 - (_e74 - _e75)); } - let _e74 = pos; - let _e75 = vPos; - let _e78 = params.rule3Distance; - if (distance(_e74, _e75) < _e78) { - let _e80 = cVel; - let _e81 = vel; - cVel = (_e80 + _e81); - let _e83 = cVelCount; - cVelCount = (_e83 + 1); + let _e78 = pos; + let _e79 = vPos; + let _e83 = params.rule3Distance; + if (distance(_e78, _e79) < _e83) { + let _e85 = cVel; + let _e86 = vel; + cVel = (_e85 + _e86); + let _e88 = cVelCount; + cVelCount = (_e88 + 1); } continuing { - let _e86 = i; - i = (_e86 + 1u); + let _e91 = i; + i = (_e91 + 1u); } } - let _e89 = cMassCount; - if (_e89 > 0) { - let _e92 = cMass; - let _e93 = cMassCount; - let _e97 = vPos; - cMass = ((_e92 / vec2(f32(_e93))) - _e97); + let _e94 = cMassCount; + if (_e94 > 0) { + let _e97 = cMass; + let _e98 = cMassCount; + let _e102 = vPos; + cMass = ((_e97 / vec2(f32(_e98))) - _e102); } - let _e99 = cVelCount; - if (_e99 > 0) { - let _e102 = cVel; - let _e103 = cVelCount; - cVel = (_e102 / vec2(f32(_e103))); + let _e104 = cVelCount; + if (_e104 > 0) { + let _e107 = cVel; + let _e108 = cVelCount; + cVel = (_e107 / vec2(f32(_e108))); } - let _e107 = vVel; - let _e108 = cMass; - let _e110 = params.rule1Scale; - let _e113 = colVel; - let _e115 = params.rule2Scale; - let _e118 = cVel; - let _e120 = params.rule3Scale; - vVel = (((_e107 + (_e108 * _e110)) + (_e113 * _e115)) + (_e118 * _e120)); - let _e123 = vVel; - let _e125 = vVel; - vVel = (normalize(_e123) * clamp(length(_e125), 0.0, 0.10000000149011612)); - let _e131 = vPos; - let _e132 = vVel; - let _e134 = params.deltaT; - vPos = (_e131 + (_e132 * _e134)); - let _e138 = vPos.x; - if (_e138 < -1.0) { + let _e112 = vVel; + let _e113 = cMass; + let _e116 = params.rule1Scale; + let _e119 = colVel; + let _e122 = params.rule2Scale; + let _e125 = cVel; + let _e128 = params.rule3Scale; + vVel = (((_e112 + (_e113 * _e116)) + (_e119 * _e122)) + (_e125 * _e128)); + let _e131 = vVel; + let _e133 = vVel; + vVel = (normalize(_e131) * clamp(length(_e133), 0.0, 0.10000000149011612)); + let _e139 = vPos; + let _e140 = vVel; + let _e143 = params.deltaT; + vPos = (_e139 + (_e140 * _e143)); + let _e147 = vPos.x; + if (_e147 < -1.0) { vPos.x = 1.0; } - let _e144 = vPos.x; - if (_e144 > 1.0) { + let _e153 = vPos.x; + if (_e153 > 1.0) { vPos.x = -1.0; } - let _e150 = vPos.y; - if (_e150 < -1.0) { + let _e159 = vPos.y; + if (_e159 < -1.0) { vPos.y = 1.0; } - let _e156 = vPos.y; - if (_e156 > 1.0) { + let _e165 = vPos.y; + if (_e165 > 1.0) { vPos.y = -1.0; } - let _e164 = vPos; - particlesDst.particles[index].pos = _e164; - let _e168 = vVel; - particlesDst.particles[index].vel = _e168; + let _e174 = vPos; + particlesDst.particles[index].pos = _e174; + let _e179 = vVel; + particlesDst.particles[index].vel = _e179; return; } diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index ea16c7961..a25f79536 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -7,34 +7,37 @@ var v_indices: PrimeIndices; fn collatz_iterations(n_base: u32) -> u32 { var n: u32; - var i: u32 = 0u; + var i: u32; n = n_base; + i = 0u; loop { - let _e5 = n; - if (_e5 > 1u) { + let _e4 = n; + if (_e4 > 1u) { } else { break; } - let _e8 = n; - if ((_e8 % 2u) == 0u) { - let _e13 = n; - n = (_e13 / 2u); - } else { - let _e17 = n; - n = ((3u * _e17) + 1u); + { + let _e7 = n; + if ((_e7 % 2u) == 0u) { + let _e12 = n; + n = (_e12 / 2u); + } else { + let _e16 = n; + n = ((3u * _e16) + 1u); + } + let _e20 = i; + i = (_e20 + 1u); } - let _e21 = i; - i = (_e21 + 1u); } - let _e24 = i; - return _e24; + let _e23 = i; + return _e23; } @compute @workgroup_size(1, 1, 1) fn main(@builtin(global_invocation_id) global_id: vec3) { - let _e8 = v_indices.data[global_id.x]; - let _e9 = collatz_iterations(_e8); - v_indices.data[global_id.x] = _e9; + let _e9 = v_indices.data[global_id.x]; + let _e10 = collatz_iterations(_e9); + v_indices.data[global_id.x] = _e10; return; } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 147f6ec32..d961db81b 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -1,14 +1,14 @@ -struct Foo { +struct FooStruct { v3_: vec3, v1_: f32, } -let Foo_2: bool = true; +const Foo_1: bool = true; var wg: array; var at_1: atomic; @group(0) @binding(1) -var alignment: Foo; +var alignment: FooStruct; @group(0) @binding(2) var dummy: array>; @group(0) @binding(3) @@ -27,13 +27,14 @@ fn test_msl_packed_vec3_as_arg(arg: vec3) { } fn test_msl_packed_vec3_() { - var idx: i32 = 1; + var idx: i32; alignment.v3_ = vec3(1.0); + idx = 1; alignment.v3_.x = 1.0; alignment.v3_.x = 2.0; - let _e23 = idx; - alignment.v3_[_e23] = 3.0; + let _e17 = idx; + alignment.v3_[_e17] = 3.0; let data = alignment; _ = data.v3_; _ = data.v3_.zx; @@ -46,26 +47,28 @@ fn test_msl_packed_vec3_() { @compute @workgroup_size(1, 1, 1) fn main() { - var Foo_1: f32 = 1.0; - var at: bool = true; + var Foo: f32; + var at: bool; test_msl_packed_vec3_(); - let _e16 = global_nested_arrays_of_matrices_4x2_[0][0]; - let _e23 = global_nested_arrays_of_matrices_2x4_[0][0][0]; - wg[7] = (_e16 * _e23).x; - let _e28 = global_mat; - let _e29 = global_vec; - wg[6] = (_e28 * _e29).x; - let _e37 = dummy[1].y; - wg[5] = _e37; + let _e8 = global_nested_arrays_of_matrices_4x2_[0][0]; + let _e16 = global_nested_arrays_of_matrices_2x4_[0][0][0]; + wg[7] = (_e8 * _e16).x; + let _e23 = global_mat; + let _e25 = global_vec; + wg[6] = (_e23 * _e25).x; + let _e35 = dummy[1].y; + wg[5] = _e35; let _e43 = float_vecs[0].w; wg[4] = _e43; - let _e47 = alignment.v1_; - wg[3] = _e47; - let _e52 = alignment.v3_.x; - wg[2] = _e52; + let _e49 = alignment.v1_; + wg[3] = _e49; + let _e56 = alignment.v3_.x; + wg[2] = _e56; alignment.v1_ = 4.0; wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); + Foo = 1.0; + at = true; return; } diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index a17865c5a..7c06d1db5 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -40,8 +40,9 @@ fn compute(@builtin(global_invocation_id) global_id: vec3, @builtin(local_i @vertex fn vertex_two_structs(in1_: Input1_, in2_: Input2_) -> @builtin(position) @invariant vec4 { - var index: u32 = 2u; + var index: u32; - let _e9: u32 = index; - return vec4(f32(in1_.index), f32(in2_.index), f32(_e9), 0.0); + index = 2u; + let _e8: u32 = index; + return vec4(f32(in1_.index), f32(in2_.index), f32(_e8), 0.0); } diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/tests/out/wgsl/lexical-scopes.wgsl index 39f033cb1..3d645f5ae 100644 --- a/tests/out/wgsl/lexical-scopes.wgsl +++ b/tests/out/wgsl/lexical-scopes.wgsl @@ -20,17 +20,20 @@ fn loopLexicalScope(a_2: bool) { } fn forLexicalScope(a_3: f32) { - var a_4: i32 = 0; + var a_4: i32; + a_4 = 0; loop { let _e4 = a_4; if (_e4 < 1) { } else { break; } + { + } continuing { - let _e7 = a_4; - a_4 = (_e7 + 1); + let _e8 = a_4; + a_4 = (_e8 + 1); } } let test_4 = (false == true); @@ -42,6 +45,8 @@ fn whileLexicalScope(a_5: i32) { } else { break; } + { + } } let test_5 = (a_5 == 1); } diff --git a/tests/out/wgsl/module-scope.wgsl b/tests/out/wgsl/module-scope.wgsl new file mode 100644 index 000000000..91a13718d --- /dev/null +++ b/tests/out/wgsl/module-scope.wgsl @@ -0,0 +1,26 @@ +struct S { + x: i32, +} + +const Value: i32 = 1; + +@group(0) @binding(0) +var Texture: texture_2d; +@group(0) @binding(1) +var Sampler: sampler; + +fn returns() -> S { + return S(Value); +} + +fn statement() { + return; +} + +fn call() { + statement(); + let _e0 = returns(); + let vf = f32(Value); + let s = textureSample(Texture, Sampler, vec2(vf)); +} + diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 9b7d647e3..487704927 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -3,10 +3,10 @@ struct Foo { b: i32, } -let v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); -let v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); -let v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); -let v_i32_one: vec4 = vec4(1, 1, 1, 1); +const v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); +const v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); +const v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); +const v_i32_one: vec4 = vec4(1, 1, 1, 1); fn builtins() -> vec4 { let s1_ = select(0, 1, true); let s2_ = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); @@ -29,14 +29,14 @@ fn splat_assignment() -> vec2 { var a: vec2; a = vec2(2.0); - let _e7 = a; - a = (_e7 + vec2(1.0)); - let _e11 = a; - a = (_e11 - vec2(3.0)); + let _e4 = a; + a = (_e4 + vec2(1.0)); + let _e8 = a; + a = (_e8 - vec2(3.0)); + let _e12 = a; + a = (_e12 / vec2(4.0)); let _e15 = a; - a = (_e15 / vec2(4.0)); - let _e19 = a; - return _e19; + return _e15; } fn bool_cast(x: vec3) -> vec3 { @@ -61,8 +61,8 @@ fn constructors() -> f32 { _ = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); _ = bitcast>(vec2(0u, 0u)); _ = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - let _e75 = foo.a.x; - return _e75; + let _e71 = foo.a.x; + return _e71; } fn logical() { @@ -215,39 +215,41 @@ fn comparison() { } fn assignment() { - var a_1: i32 = 1; - var vec0_: vec3 = vec3(0, 0, 0); + var a_1: i32; + var vec0_: vec3; + a_1 = 1; + let _e3 = a_1; + a_1 = (_e3 + 1); let _e6 = a_1; - a_1 = (_e6 + 1); + a_1 = (_e6 - 1); + let _e8 = a_1; let _e9 = a_1; - a_1 = (_e9 - 1); + a_1 = (_e9 * _e8); + let _e11 = a_1; let _e12 = a_1; - let _e13 = a_1; - a_1 = (_e12 * _e13); + a_1 = (_e12 / _e11); let _e15 = a_1; - let _e16 = a_1; - a_1 = (_e15 / _e16); + a_1 = (_e15 % 1); let _e18 = a_1; - a_1 = (_e18 % 1); + a_1 = (_e18 & 0); let _e21 = a_1; - a_1 = (_e21 & 0); + a_1 = (_e21 | 0); let _e24 = a_1; - a_1 = (_e24 | 0); + a_1 = (_e24 ^ 0); let _e27 = a_1; - a_1 = (_e27 ^ 0); + a_1 = (_e27 << 2u); let _e30 = a_1; - a_1 = (_e30 << 2u); - let _e33 = a_1; - a_1 = (_e33 >> 1u); - let _e36 = a_1; - a_1 = (_e36 + 1); - let _e39 = a_1; - a_1 = (_e39 - 1); - let _e46 = vec0_.y; - vec0_.y = (_e46 + 1); - let _e51 = vec0_.y; - vec0_.y = (_e51 - 1); + a_1 = (_e30 >> 1u); + let _e32 = a_1; + a_1 = (_e32 + 1); + let _e35 = a_1; + a_1 = (_e35 - 1); + vec0_ = vec3(0, 0, 0); + let _e42 = vec0_.y; + vec0_.y = (_e42 + 1); + let _e47 = vec0_.y; + vec0_.y = (_e47 - 1); return; } @@ -263,10 +265,10 @@ fn negation_avoids_prefix_decrement() { @compute @workgroup_size(1, 1, 1) fn main() { - let _e4 = builtins(); - let _e5 = splat(); - let _e7 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); - let _e8 = constructors(); + let _e0 = builtins(); + let _e1 = splat(); + let _e4 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + let _e5 = constructors(); logical(); arithmetic(); bit(); diff --git a/tests/out/wgsl/padding.wgsl b/tests/out/wgsl/padding.wgsl index 4f2b8d4b7..a4c0a968d 100644 --- a/tests/out/wgsl/padding.wgsl +++ b/tests/out/wgsl/padding.wgsl @@ -26,8 +26,8 @@ var input3_: Test3_; @vertex fn vertex() -> @builtin(position) vec4 { - let _e6 = input1_.b; - let _e9 = input2_.b; + let _e4 = input1_.b; + let _e8 = input2_.b; let _e12 = input3_.b; - return (((vec4(1.0) * _e6) * _e9) * _e12); + return (((vec4(1.0) * _e4) * _e8) * _e12); } diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index 98a4c6106..b4cf4dd28 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -3,7 +3,7 @@ struct VertexOutput { @builtin(position) position: vec4, } -let c_scale: f32 = 1.2000000476837158; +const c_scale: f32 = 1.2000000476837158; @group(0) @binding(0) var u_texture: texture_2d; diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 8bb6b5813..df042d9e1 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -20,8 +20,8 @@ struct Light { color: vec4, } -let c_ambient: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); -let c_max_lights: u32 = 10u; +const c_ambient: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); +const c_max_lights: u32 = 10u; @group(0) @binding(0) var u_globals: Globals; @@ -43,8 +43,8 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { let flip_correction = vec2(0.5, -0.5); let proj_correction = (1.0 / homogeneous_coords.w); let light_local = (((homogeneous_coords.xy * flip_correction) * proj_correction) + vec2(0.5, 0.5)); - let _e28 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z * proj_correction)); - return _e28; + let _e24 = textureSampleCompareLevel(t_shadow, sampler_shadow, light_local, i32(light_id), (homogeneous_coords.z * proj_correction)); + return _e24; } @vertex @@ -56,70 +56,78 @@ fn vs_main(@location(0) position: vec4, @location(1) normal: vec4) -> let world_pos = (_e7 * vec4(position)); out.world_normal = (mat3x3(w[0].xyz, w[1].xyz, w[2].xyz) * vec3(normal.xyz)); out.world_position = world_pos; - let _e25 = u_globals.view_proj; - out.proj_position = (_e25 * world_pos); - let _e27 = out; - return _e27; + let _e26 = u_globals.view_proj; + out.proj_position = (_e26 * world_pos); + let _e28 = out; + return _e28; } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4 { - var color: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); - var i: u32 = 0u; + var color: vec3; + var i: u32; let normal_1 = normalize(in.world_normal); + color = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + i = 0u; loop { - let _e14 = i; - let _e17 = u_globals.num_lights.x; - if (_e14 < min(_e17, c_max_lights)) { + let _e7 = i; + let _e11 = u_globals.num_lights.x; + if (_e7 < min(_e11, c_max_lights)) { } else { break; } - let _e23 = i; - let light = s_lights[_e23]; - let _e26 = i; - let _e30 = fetch_shadow(_e26, (light.proj * in.world_position)); - let light_dir = normalize((light.pos.xyz - in.world_position.xyz)); - let diffuse = max(0.0, dot(normal_1, light_dir)); - let _e40 = color; - color = (_e40 + ((_e30 * diffuse) * light.color.xyz)); + { + let _e16 = i; + let light = s_lights[_e16]; + let _e19 = i; + let _e23 = fetch_shadow(_e19, (light.proj * in.world_position)); + let light_dir = normalize((light.pos.xyz - in.world_position.xyz)); + let diffuse = max(0.0, dot(normal_1, light_dir)); + let _e37 = color; + color = (_e37 + ((_e23 * diffuse) * light.color.xyz)); + } continuing { - let _e20 = i; - i = (_e20 + 1u); + let _e39 = i; + i = (_e39 + 1u); } } - let _e46 = color; - let _e50 = u_entity.color; - return (vec4(_e46, 1.0) * _e50); + let _e42 = color; + let _e47 = u_entity.color; + return (vec4(_e42, 1.0) * _e47); } @fragment fn fs_main_without_storage(in_1: VertexOutput) -> @location(0) vec4 { - var color_1: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); - var i_1: u32 = 0u; + var color_1: vec3; + var i_1: u32; let normal_2 = normalize(in_1.world_normal); + color_1 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + i_1 = 0u; loop { - let _e14 = i_1; - let _e17 = u_globals.num_lights.x; - if (_e14 < min(_e17, c_max_lights)) { + let _e7 = i_1; + let _e11 = u_globals.num_lights.x; + if (_e7 < min(_e11, c_max_lights)) { } else { break; } - let _e23 = i_1; - let light_1 = u_lights[_e23]; - let _e26 = i_1; - let _e30 = fetch_shadow(_e26, (light_1.proj * in_1.world_position)); - let light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); - let diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); - let _e40 = color_1; - color_1 = (_e40 + ((_e30 * diffuse_1) * light_1.color.xyz)); + { + let _e16 = i_1; + let light_1 = u_lights[_e16]; + let _e19 = i_1; + let _e23 = fetch_shadow(_e19, (light_1.proj * in_1.world_position)); + let light_dir_1 = normalize((light_1.pos.xyz - in_1.world_position.xyz)); + let diffuse_1 = max(0.0, dot(normal_2, light_dir_1)); + let _e37 = color_1; + color_1 = (_e37 + ((_e23 * diffuse_1) * light_1.color.xyz)); + } continuing { - let _e20 = i_1; - i_1 = (_e20 + 1u); + let _e39 = i_1; + i_1 = (_e39 + 1u); } } - let _e46 = color_1; - let _e50 = u_entity.color; - return (vec4(_e46, 1.0) * _e50); + let _e42 = color_1; + let _e47 = u_entity.color; + return (vec4(_e42, 1.0) * _e47); } diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl index c9be90196..73d4da78a 100644 --- a/tests/out/wgsl/skybox.wgsl +++ b/tests/out/wgsl/skybox.wgsl @@ -22,20 +22,20 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput { tmp1_ = (i32(vertex_index) / 2); tmp2_ = (i32(vertex_index) & 1); - let _e10 = tmp1_; - let _e16 = tmp2_; - let pos = vec4(((f32(_e10) * 4.0) - 1.0), ((f32(_e16) * 4.0) - 1.0), 0.0, 1.0); + let _e9 = tmp1_; + let _e15 = tmp2_; + let pos = vec4(((f32(_e9) * 4.0) - 1.0), ((f32(_e15) * 4.0) - 1.0), 0.0, 1.0); let _e27 = r_data.view[0]; - let _e31 = r_data.view[1]; - let _e35 = r_data.view[2]; - let inv_model_view = transpose(mat3x3(_e27.xyz, _e31.xyz, _e35.xyz)); - let _e40 = r_data.proj_inv; - let unprojected = (_e40 * pos); + let _e32 = r_data.view[1]; + let _e37 = r_data.view[2]; + let inv_model_view = transpose(mat3x3(_e27.xyz, _e32.xyz, _e37.xyz)); + let _e43 = r_data.proj_inv; + let unprojected = (_e43 * pos); return VertexOutput(pos, (inv_model_view * unprojected.xyz)); } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4 { - let _e5 = textureSample(r_texture, r_sampler, in.uv); - return _e5; + let _e4 = textureSample(r_texture, r_sampler, in.uv); + return _e4; } diff --git a/tests/out/wgsl/texture-arg.wgsl b/tests/out/wgsl/texture-arg.wgsl index 09924d5eb..6edf0250e 100644 --- a/tests/out/wgsl/texture-arg.wgsl +++ b/tests/out/wgsl/texture-arg.wgsl @@ -4,8 +4,8 @@ var Texture: texture_2d; var Sampler: sampler; fn test(Passed_Texture: texture_2d, Passed_Sampler: sampler) -> vec4 { - let _e7 = textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); - return _e7; + let _e5 = textureSample(Passed_Texture, Passed_Sampler, vec2(0.0, 0.0)); + return _e5; } @fragment diff --git a/tests/out/wgsl/type-alias.wgsl b/tests/out/wgsl/type-alias.wgsl new file mode 100644 index 000000000..b9c551cc9 --- /dev/null +++ b/tests/out/wgsl/type-alias.wgsl @@ -0,0 +1,9 @@ +fn main() { + let a = vec3(0.0, 0.0, 0.0); + let c = vec3(0.0); + let b = vec3(vec2(0.0), 0.0); + let d = vec3(vec2(0.0), 0.0); + let e = vec3(d); + let f = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index c38c23f8b..34c881f0b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -548,6 +548,8 @@ fn convert_wgsl() { Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, ), ("lexical-scopes", Targets::WGSL), + ("type-alias", Targets::WGSL), + ("module-scope", Targets::WGSL), ]; for &(name, targets) in inputs.iter() { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 7085ac156..917628b27 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -64,12 +64,12 @@ fn invalid_integer() { #[test] fn invalid_float() { check( - "let scale: f32 = 1.1.;", - r###"error: expected ';', found '.' - ┌─ wgsl:1:21 + "const scale: f32 = 1.1.;", + r###"error: expected identifier, found ';' + ┌─ wgsl:1:24 │ -1 │ let scale: f32 = 1.1.; - │ ^ expected ';' +1 │ const scale: f32 = 1.1.; + │ ^ expected identifier "###, ); @@ -78,12 +78,12 @@ fn invalid_float() { #[test] fn invalid_texture_sample_type() { check( - "let x: texture_2d;", + "const x: texture_2d;", r###"error: texture sample type must be one of f32, i32 or u32, but found bool - ┌─ wgsl:1:19 + ┌─ wgsl:1:21 │ -1 │ let x: texture_2d; - │ ^^^^ must be one of f32, i32 or u32 +1 │ const x: texture_2d; + │ ^^^^ must be one of f32, i32 or u32 "###, ); @@ -211,10 +211,10 @@ fn unexpected_constructor_parameters() { } "#, r#"error: unexpected components - ┌─ wgsl:3:27 + ┌─ wgsl:3:28 │ 3 │ _ = i32(0, 1); - │ ^^ unexpected components + │ ^ unexpected components "#, ); @@ -365,13 +365,13 @@ fn unknown_ident() { fn unknown_scalar_type() { check( r#" - let a: vec2; + const a: vec2; "#, r#"error: unknown scalar type: 'something' - ┌─ wgsl:2:25 + ┌─ wgsl:2:27 │ -2 │ let a: vec2; - │ ^^^^^^^^^ unknown scalar type +2 │ const a: vec2; + │ ^^^^^^^^^ unknown scalar type │ = note: Valid scalar types are f32, f64, i32, u32, bool @@ -383,13 +383,13 @@ fn unknown_scalar_type() { fn unknown_type() { check( r#" - let a: Vec; + const a: Vec = 10; "#, r#"error: unknown type: 'Vec' - ┌─ wgsl:2:20 + ┌─ wgsl:2:22 │ -2 │ let a: Vec; - │ ^^^ unknown type +2 │ const a: Vec = 10; + │ ^^^ unknown type "#, ); @@ -399,13 +399,13 @@ fn unknown_type() { fn unknown_storage_format() { check( r#" - let storage1: texture_storage_1d; + const storage1: texture_storage_1d; "#, r#"error: unknown storage format: 'rgba' - ┌─ wgsl:2:46 + ┌─ wgsl:2:48 │ -2 │ let storage1: texture_storage_1d; - │ ^^^^ unknown storage format +2 │ const storage1: texture_storage_1d; + │ ^^^^ unknown storage format "#, ); @@ -505,11 +505,11 @@ fn unknown_local_function() { for (a();;) {} } "#, - r#"error: unknown local function `a` + r#"error: no definition in scope for identifier: 'a' ┌─ wgsl:3:22 │ 3 │ for (a();;) {} - │ ^ unknown local function + │ ^ unknown identifier "#, ); @@ -519,13 +519,13 @@ fn unknown_local_function() { fn let_type_mismatch() { check( r#" - let x: i32 = 1.0; + const x: i32 = 1.0; "#, - r#"error: the type of `x` is expected to be `f32` - ┌─ wgsl:2:17 + r#"error: the type of `x` is expected to be `i32`, but got `f32` + ┌─ wgsl:2:19 │ -2 │ let x: i32 = 1.0; - │ ^ definition of `x` +2 │ const x: i32 = 1.0; + │ ^ definition of `x` "#, ); @@ -536,7 +536,7 @@ fn let_type_mismatch() { let x: f32 = true; } "#, - r#"error: the type of `x` is expected to be `bool` + r#"error: the type of `x` is expected to be `f32`, but got `bool` ┌─ wgsl:3:21 │ 3 │ let x: f32 = true; @@ -548,29 +548,16 @@ fn let_type_mismatch() { #[test] fn var_type_mismatch() { - check( - r#" - let x: f32 = 1; - "#, - r#"error: the type of `x` is expected to be `i32` - ┌─ wgsl:2:17 - │ -2 │ let x: f32 = 1; - │ ^ definition of `x` - -"#, - ); - check( r#" fn foo() { - var x: f32 = 1u32; + var x: f32 = 1u; } "#, - r#"error: the type of `x` is expected to be `u32` + r#"error: the type of `x` is expected to be `f32`, but got `u32` ┌─ wgsl:3:21 │ -3 │ var x: f32 = 1u32; +3 │ var x: f32 = 1u; │ ^ definition of `x` "#, @@ -640,11 +627,11 @@ fn reserved_keyword() { r#" var bool: bool = true; "#, - r###"error: name `bool: bool = true;` is a reserved keyword + r###"error: name `bool` is a reserved keyword ┌─ wgsl:2:17 │ 2 │ var bool: bool = true; - │ ^^^^^^^^^^^^^^^^^^ definition of `bool: bool = true;` + │ ^^^^ definition of `bool` "###, ); @@ -652,16 +639,16 @@ fn reserved_keyword() { // global constant check( r#" - let break: bool = true; + const break: bool = true; fn foo() { var foo = break; } "#, r###"error: name `break` is a reserved keyword - ┌─ wgsl:2:17 + ┌─ wgsl:2:19 │ -2 │ let break: bool = true; - │ ^^^^^ definition of `break` +2 │ const break: bool = true; + │ ^^^^^ definition of `break` "###, ); @@ -743,19 +730,19 @@ fn reserved_keyword() { #[test] fn module_scope_identifier_redefinition() { - // let + // const check( r#" - let foo: bool = true; - let foo: bool = true; + const foo: bool = true; + const foo: bool = true; "#, r###"error: redefinition of `foo` - ┌─ wgsl:2:17 + ┌─ wgsl:2:19 │ -2 │ let foo: bool = true; - │ ^^^ previous definition of `foo` -3 │ let foo: bool = true; - │ ^^^ redefinition of `foo` +2 │ const foo: bool = true; + │ ^^^ previous definition of `foo` +3 │ const foo: bool = true; + │ ^^^ redefinition of `foo` "###, ); @@ -765,13 +752,13 @@ fn module_scope_identifier_redefinition() { var foo: bool = true; var foo: bool = true; "#, - r###"error: redefinition of `foo: bool = true;` + r###"error: redefinition of `foo` ┌─ wgsl:2:17 │ 2 │ var foo: bool = true; - │ ^^^^^^^^^^^^^^^^^ previous definition of `foo: bool = true;` + │ ^^^ previous definition of `foo` 3 │ var foo: bool = true; - │ ^^^^^^^^^^^^^^^^^ redefinition of `foo: bool = true;` + │ ^^^ redefinition of `foo` "###, ); @@ -780,15 +767,15 @@ fn module_scope_identifier_redefinition() { check( r#" var foo: bool = true; - let foo: bool = true; + const foo: bool = true; "#, r###"error: redefinition of `foo` ┌─ wgsl:2:17 │ 2 │ var foo: bool = true; - │ ^^^^^^^^^^^^^^^^^ previous definition of `foo: bool = true;` -3 │ let foo: bool = true; - │ ^^^ redefinition of `foo` + │ ^^^ previous definition of `foo` +3 │ const foo: bool = true; + │ ^^^ redefinition of `foo` "###, ); @@ -813,14 +800,14 @@ fn module_scope_identifier_redefinition() { // let and function check( r#" - let foo: bool = true; + const foo: bool = true; fn foo() {} "#, r###"error: redefinition of `foo` - ┌─ wgsl:2:17 + ┌─ wgsl:2:19 │ -2 │ let foo: bool = true; - │ ^^^ previous definition of `foo` +2 │ const foo: bool = true; + │ ^^^ previous definition of `foo` 3 │ fn foo() {} │ ^^^ redefinition of `foo` @@ -937,7 +924,7 @@ fn invalid_arrays() { check_validation! { "type Bad = array;", r#" - let length: f32 = 2.718; + const length: f32 = 2.718; type Bad = array; "#: Err(naga::valid::ValidationError::Type { @@ -1606,11 +1593,11 @@ fn binary_statement() { 3 + 5; } ", - r###"error: expected assignment or increment/decrement, found '3 + 5' - ┌─ wgsl:3:13 + r###"error: expected assignment or increment/decrement, found ';' + ┌─ wgsl:3:18 │ 3 │ 3 + 5; - │ ^^^^^ expected assignment or increment/decrement + │ ^ expected assignment or increment/decrement "###, ); @@ -1655,3 +1642,116 @@ fn assign_to_let() { "###, ); } + +#[test] +fn recursive_function() { + check( + " + fn f() { + f(); + } + ", + r###"error: declaration of `f` is recursive + ┌─ wgsl:2:12 + │ +2 │ fn f() { + │ ^ +3 │ f(); + │ ^ uses itself here + +"###, + ); +} + +#[test] +fn cyclic_function() { + check( + " + fn f() { + g(); + } + fn g() { + f(); + } + ", + r###"error: declaration of `f` is cyclic + ┌─ wgsl:2:12 + │ +2 │ fn f() { + │ ^ +3 │ g(); + │ ^ uses `g` +4 │ } +5 │ fn g() { + │ ^ +6 │ f(); + │ ^ ending the cycle + +"###, + ); +} + +#[test] +fn switch_signed_unsigned_mismatch() { + check( + " + fn x(y: u32) { + switch y { + case 1: {} + } + } + ", + r###"error: invalid switch value + ┌─ wgsl:4:16 + │ +4 │ case 1: {} + │ ^ expected unsigned integer + │ + = note: suffix the integer with a `u`: '1u' + +"###, + ); + + check( + " + fn x(y: i32) { + switch y { + case 1u: {} + } + } + ", + r###"error: invalid switch value + ┌─ wgsl:4:16 + │ +4 │ case 1u: {} + │ ^^ expected signed integer + │ + = note: remove the `u` suffix: '1' + +"###, + ); +} + +#[test] +fn function_returns_void() { + check( + " + fn x() { + let a = vec2(1, 2u); + } + + fn b() { + let a = x(); + } + ", + r###"error: function does not return any value + ┌─ wgsl:7:18 + │ +7 │ let a = x(); + │ ^ + │ + = note: perhaps you meant to call the function in a separate statement? + +"###, + ) +} From f0a8ff6b3a316be22e945a60f85c75037c10f94f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 14 Jan 2023 15:00:15 -0800 Subject: [PATCH 1894/2212] Fix docs for `Emit` statements. (#2208) --- src/lib.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 65f018948..4497c14ac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -108,9 +108,7 @@ Naga's rules for when `Expression`s are evaluated are as follows: evaluated when the `Atomic` statement is executed. - All other expressions are evaluated when the (unique) [`Statement::Emit`] - statement that covers them is executed. The [`Expression::needs_pre_emit`] - method returns `true` if the given expression is one of those variants that - does *not* need to be covered by an `Emit` statement. + statement that covers them is executed. Now, strictly speaking, not all `Expression` variants actually care when they're evaluated. For example, you can evaluate a [`BinaryOperator::Add`] expression From cdcfad277a26f29cf5d0dff4ca1655f1b0d7a0cc Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 9 Jan 2023 16:31:01 -0800 Subject: [PATCH 1895/2212] Let the uniformity analysis trust the handle validation pass. Undo some changes from #1668, now that #2090 has been merged. --- src/valid/analyzer.rs | 33 +++++++-------------------------- src/valid/expression.rs | 2 -- src/valid/function.rs | 2 -- 3 files changed, 7 insertions(+), 30 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index eb6c1fc4a..30fb32d07 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -6,7 +6,7 @@ Figures out the following properties: - expression reference counts !*/ -use super::{CallError, ExpressionError, FunctionError, ModuleInfo, ShaderStages, ValidationFlags}; +use super::{ExpressionError, FunctionError, ModuleInfo, ShaderStages, ValidationFlags}; use crate::span::{AddSpan as _, WithSpan}; use crate::{ arena::{Arena, Handle}, @@ -308,10 +308,7 @@ impl FunctionInfo { handle: Handle, global_use: GlobalUse, ) -> NonUniformResult { - //Note: if the expression doesn't exist, this function - // will return `None`, but the later validation of - // expressions should detect this and error properly. - let info = self.expressions.get_mut(handle.index())?; + let info = &mut self.expressions[handle.index()]; info.ref_count += 1; // mark the used global as read if let Some(global) = info.assignable_global { @@ -335,8 +332,7 @@ impl FunctionInfo { handle: Handle, assignable_global: &mut Option>, ) -> NonUniformResult { - //Note: similarly to `add_ref_impl`, this ignores invalid expressions. - let info = self.expressions.get_mut(handle.index())?; + let info = &mut self.expressions[handle.index()]; info.ref_count += 1; // propagate the assignable global up the chain, till it either hits // a value-type expression, or the assignment statement. @@ -689,13 +685,7 @@ impl FunctionInfo { non_uniform_result: self.add_ref(expr), requirements: UniformityRequirements::empty(), }, - E::CallResult(function) => { - let info = other_functions - .get(function.index()) - .ok_or(ExpressionError::CallToUndeclaredFunction(function))?; - - info.uniformity.clone() - } + E::CallResult(function) => other_functions[function.index()].uniformity.clone(), E::AtomicResult { .. } => Uniformity { non_uniform_result: Some(handle), requirements: UniformityRequirements::empty(), @@ -736,15 +726,12 @@ impl FunctionInfo { use crate::Statement as S; let mut combined_uniformity = FunctionUniformity::new(); - for (statement, &span) in statements.span_iter() { + for statement in statements { let uniformity = match *statement { S::Emit(ref range) => { let mut requirements = UniformityRequirements::empty(); for expr in range.clone() { - let req = match self.expressions.get(expr.index()) { - Some(expr) => expr.uniformity.requirements, - None => UniformityRequirements::empty(), - }; + let req = self.expressions[expr.index()].uniformity.requirements; #[cfg(feature = "validate")] if self .flags @@ -889,13 +876,7 @@ impl FunctionInfo { for &argument in arguments { let _ = self.add_ref(argument); } - let info = other_functions.get(function.index()).ok_or( - FunctionError::InvalidCall { - function, - error: CallError::ForwardDeclaredFunction, - } - .with_span_static(span, "forward call"), - )?; + let info = &other_functions[function.index()]; //Note: the result is validated by the Validator, not here self.process_call(info, arguments, expression_arena)? } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 14f52fb93..9853f1d1b 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -65,8 +65,6 @@ pub enum ExpressionError { ExpectedGlobalVariable, #[error("Not a global variable or a function argument")] ExpectedGlobalOrArgument, - #[error("Calling an undeclared function {0:?}")] - CallToUndeclaredFunction(Handle), #[error("Needs to be an binding array instead of {0:?}")] ExpectedBindingArrayType(Handle), #[error("Needs to be an image instead of {0:?}")] diff --git a/src/valid/function.rs b/src/valid/function.rs index 3c555491c..b615895ae 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -19,8 +19,6 @@ use bit_set::BitSet; #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum CallError { - #[error("The callee is declared after the caller")] - ForwardDeclaredFunction, #[error("Argument {index} expression is invalid")] Argument { index: usize, From 1cffd236a7b85d4d6fc95517cbf8c584f5a957ea Mon Sep 17 00:00:00 2001 From: Jonathan Behrens Date: Wed, 18 Jan 2023 07:28:38 -0800 Subject: [PATCH 1896/2212] Remove overly restrictive array stride check (#2215) --- src/valid/type.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/valid/type.rs b/src/valid/type.rs index 172f11072..083501c67 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -380,14 +380,6 @@ impl super::Validator { } let base_layout = self.layouter[base]; - let expected_stride = base_layout.to_stride(); - if stride != expected_stride { - return Err(TypeError::InvalidArrayStride { - stride, - expected: expected_stride, - }); - } - let general_alignment = base_layout.alignment; let uniform_layout = match base_info.uniform_layout { Ok(base_alignment) => { From 1be8024bda3594987b417bead5024b98be9ab521 Mon Sep 17 00:00:00 2001 From: Jonathan Behrens Date: Wed, 18 Jan 2023 10:03:24 -0800 Subject: [PATCH 1897/2212] Support 16-bit unorm/snorm formats (#2210) * Support 16-bit unorm/snorm formats * Add Capabilities::STORAGE_TEXTURE_16BIT_NORM_FORMATS * Add 16-bit normalized formats to spv frontend --- src/back/glsl/mod.rs | 6 ++++++ src/back/hlsl/conv.rs | 12 ++++++------ src/back/spv/instructions.rs | 6 ++++++ src/back/wgsl/writer.rs | 6 ++++++ src/front/glsl/parser/types.rs | 12 ++++++------ src/front/spv/convert.rs | 6 ++++++ src/front/wgsl/conv.rs | 6 ++++++ src/front/wgsl/mod.rs | 6 ++++++ src/lib.rs | 8 ++++++++ src/proc/mod.rs | 6 ++++++ src/valid/interface.rs | 29 +++++++++++++++++++++++++++++ src/valid/mod.rs | 4 +++- 12 files changed, 94 insertions(+), 13 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5a7d4d12a..81df401d0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -3849,6 +3849,12 @@ const fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { Sf::Rgba32Uint => "rgba32ui", Sf::Rgba32Sint => "rgba32i", Sf::Rgba32Float => "rgba32f", + Sf::R16Unorm => "r16", + Sf::R16Snorm => "r16_snorm", + Sf::Rg16Unorm => "rg16", + Sf::Rg16Snorm => "rg16_snorm", + Sf::Rgba16Unorm => "rgba16", + Sf::Rgba16Snorm => "rgba16_snorm", } } diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 886b250b3..819ddb4d4 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -115,14 +115,14 @@ impl crate::StorageFormat { pub(super) const fn to_hlsl_str(self) -> &'static str { match self { Self::R16Float => "float", - Self::R8Unorm => "unorm float", - Self::R8Snorm => "snorm float", + Self::R8Unorm | Self::R16Unorm => "unorm float", + Self::R8Snorm | Self::R16Snorm => "snorm float", Self::R8Uint | Self::R16Uint => "uint", Self::R8Sint | Self::R16Sint => "int", Self::Rg16Float => "float2", - Self::Rg8Unorm => "unorm float2", - Self::Rg8Snorm => "snorm float2", + Self::Rg8Unorm | Self::Rg16Unorm => "unorm float2", + Self::Rg8Snorm | Self::Rg16Snorm => "snorm float2", Self::Rg8Sint | Self::Rg16Sint => "int2", Self::Rg8Uint | Self::Rg16Uint => "uint2", @@ -130,8 +130,8 @@ impl crate::StorageFormat { Self::Rg11b10Float => "float3", Self::Rgba16Float | Self::R32Float | Self::Rg32Float | Self::Rgba32Float => "float4", - Self::Rgba8Unorm | Self::Rgb10a2Unorm => "unorm float4", - Self::Rgba8Snorm => "snorm float4", + Self::Rgba8Unorm | Self::Rgba16Unorm | Self::Rgb10a2Unorm => "unorm float4", + Self::Rgba8Snorm | Self::Rgba16Snorm => "snorm float4", Self::Rgba8Uint | Self::Rgba16Uint diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 9ec1deb0b..c21379018 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -979,6 +979,12 @@ impl From for spirv::ImageFormat { Sf::Rgba32Uint => Self::Rgba32ui, Sf::Rgba32Sint => Self::Rgba32i, Sf::Rgba32Float => Self::Rgba32f, + Sf::R16Unorm => Self::R16, + Sf::R16Snorm => Self::R16Snorm, + Sf::Rg16Unorm => Self::Rg16, + Sf::Rg16Snorm => Self::Rg16Snorm, + Sf::Rgba16Unorm => Self::Rgba16, + Sf::Rgba16Snorm => Self::Rgba16Snorm, } } } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 51091f8be..b2cec92da 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1987,6 +1987,12 @@ const fn storage_format_str(format: crate::StorageFormat) -> &'static str { Sf::Rgba32Uint => "rgba32uint", Sf::Rgba32Sint => "rgba32sint", Sf::Rgba32Float => "rgba32float", + Sf::R16Unorm => "r16unorm", + Sf::R16Snorm => "r16snorm", + Sf::Rg16Unorm => "rg16unorm", + Sf::Rg16Snorm => "rg16snorm", + Sf::Rgba16Unorm => "rgba16unorm", + Sf::Rgba16Snorm => "rgba16snorm", } } diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 7a7757c9c..93396823e 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -385,15 +385,18 @@ fn map_image_format(word: &str) -> Option { "r11f_g11f_b10f" => Sf::Rg11b10Float, "r32f" => Sf::R32Float, "r16f" => Sf::R16Float, - "rgba16" => Sf::Rgba16Float, + "rgba16" => Sf::Rgba16Unorm, "rgb10_a2" => Sf::Rgb10a2Unorm, "rgba8" => Sf::Rgba8Unorm, - "rg16" => Sf::Rg16Float, + "rg16" => Sf::Rg16Unorm, "rg8" => Sf::Rg8Unorm, - "r16" => Sf::R16Float, + "r16" => Sf::R16Unorm, "r8" => Sf::R8Unorm, + "rgba16_snorm" => Sf::Rgba16Snorm, "rgba8_snorm" => Sf::Rgba8Snorm, + "rg16_snorm" => Sf::Rg16Snorm, "rg8_snorm" => Sf::Rg8Snorm, + "r16_snorm" => Sf::R16Snorm, "r8_snorm" => Sf::R8Snorm, // int-image-format-qualifier: "rgba32i" => Sf::Rgba32Sint, @@ -416,9 +419,6 @@ fn map_image_format(word: &str) -> Option { "r16ui" => Sf::R16Uint, "r8ui" => Sf::R8Uint, // TODO: These next ones seem incorrect to me - // "rgba16_snorm" => Sf::Rgba16Float, - // "rg16_snorm" => Sf::Rg16Float, - // "r16_snorm" => Sf::R16Float, // "rgb10_a2ui" => Sf::Rgb10a2Unorm, _ => return None, }; diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index af7d2b083..2967555d2 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -84,6 +84,8 @@ pub(super) fn map_image_format(word: spirv::Word) -> Result Ok(crate::StorageFormat::R8Snorm), Some(spirv::ImageFormat::R8ui) => Ok(crate::StorageFormat::R8Uint), Some(spirv::ImageFormat::R8i) => Ok(crate::StorageFormat::R8Sint), + Some(spirv::ImageFormat::R16) => Ok(crate::StorageFormat::R16Unorm), + Some(spirv::ImageFormat::R16Snorm) => Ok(crate::StorageFormat::R16Snorm), Some(spirv::ImageFormat::R16ui) => Ok(crate::StorageFormat::R16Uint), Some(spirv::ImageFormat::R16i) => Ok(crate::StorageFormat::R16Sint), Some(spirv::ImageFormat::R16f) => Ok(crate::StorageFormat::R16Float), @@ -94,6 +96,8 @@ pub(super) fn map_image_format(word: spirv::Word) -> Result Ok(crate::StorageFormat::R32Uint), Some(spirv::ImageFormat::R32i) => Ok(crate::StorageFormat::R32Sint), Some(spirv::ImageFormat::R32f) => Ok(crate::StorageFormat::R32Float), + Some(spirv::ImageFormat::Rg16) => Ok(crate::StorageFormat::Rg16Unorm), + Some(spirv::ImageFormat::Rg16Snorm) => Ok(crate::StorageFormat::Rg16Snorm), Some(spirv::ImageFormat::Rg16ui) => Ok(crate::StorageFormat::Rg16Uint), Some(spirv::ImageFormat::Rg16i) => Ok(crate::StorageFormat::Rg16Sint), Some(spirv::ImageFormat::Rg16f) => Ok(crate::StorageFormat::Rg16Float), @@ -106,6 +110,8 @@ pub(super) fn map_image_format(word: spirv::Word) -> Result Ok(crate::StorageFormat::Rg32Uint), Some(spirv::ImageFormat::Rg32i) => Ok(crate::StorageFormat::Rg32Sint), Some(spirv::ImageFormat::Rg32f) => Ok(crate::StorageFormat::Rg32Float), + Some(spirv::ImageFormat::Rgba16) => Ok(crate::StorageFormat::Rgba16Unorm), + Some(spirv::ImageFormat::Rgba16Snorm) => Ok(crate::StorageFormat::Rgba16Snorm), Some(spirv::ImageFormat::Rgba16ui) => Ok(crate::StorageFormat::Rgba16Uint), Some(spirv::ImageFormat::Rgba16i) => Ok(crate::StorageFormat::Rgba16Sint), Some(spirv::ImageFormat::Rgba16f) => Ok(crate::StorageFormat::Rgba16Float), diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 25acdcb21..645f90b01 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -63,6 +63,8 @@ pub fn map_storage_format(word: &str, span: Span) -> Result Sf::R8Snorm, "r8uint" => Sf::R8Uint, "r8sint" => Sf::R8Sint, + "r16unorm" => Sf::R16Unorm, + "r16snorm" => Sf::R16Snorm, "r16uint" => Sf::R16Uint, "r16sint" => Sf::R16Sint, "r16float" => Sf::R16Float, @@ -73,6 +75,8 @@ pub fn map_storage_format(word: &str, span: Span) -> Result Sf::R32Uint, "r32sint" => Sf::R32Sint, "r32float" => Sf::R32Float, + "rg16unorm" => Sf::Rg16Unorm, + "rg16snorm" => Sf::Rg16Snorm, "rg16uint" => Sf::Rg16Uint, "rg16sint" => Sf::Rg16Sint, "rg16float" => Sf::Rg16Float, @@ -85,6 +89,8 @@ pub fn map_storage_format(word: &str, span: Span) -> Result Sf::Rg32Uint, "rg32sint" => Sf::Rg32Sint, "rg32float" => Sf::Rg32Float, + "rgba16unorm" => Sf::Rgba16Unorm, + "rgba16snorm" => Sf::Rgba16Snorm, "rgba16uint" => Sf::Rgba16Uint, "rgba16sint" => Sf::Rgba16Sint, "rgba16float" => Sf::Rgba16Float, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 80d542952..c4821ba62 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -687,6 +687,12 @@ impl crate::StorageFormat { Sf::Rgba32Uint => "rgba32uint", Sf::Rgba32Sint => "rgba32sint", Sf::Rgba32Float => "rgba32float", + Sf::R16Unorm => "r16unorm", + Sf::R16Snorm => "r16snorm", + Sf::Rg16Unorm => "rg16unorm", + Sf::Rg16Snorm => "rg16snorm", + Sf::Rgba16Unorm => "rgba16unorm", + Sf::Rgba16Snorm => "rgba16snorm", } } } diff --git a/src/lib.rs b/src/lib.rs index 4497c14ac..705452008 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -531,6 +531,14 @@ pub enum StorageFormat { Rgba32Uint, Rgba32Sint, Rgba32Float, + + // Normalized 16-bit per channel formats + R16Unorm, + R16Snorm, + Rg16Unorm, + Rg16Snorm, + Rgba16Unorm, + Rgba16Snorm, } /// Sub-class of the image type. diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c718c33b2..f30158c11 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -52,6 +52,12 @@ impl From for super::ScalarKind { Sf::Rgba32Uint => Sk::Uint, Sf::Rgba32Sint => Sk::Sint, Sf::Rgba32Float => Sk::Float, + Sf::R16Unorm => Sk::Float, + Sf::R16Snorm => Sk::Float, + Sf::Rg16Unorm => Sk::Float, + Sf::Rg16Snorm => Sk::Float, + Sf::Rgba16Unorm => Sk::Float, + Sf::Rgba16Snorm => Sk::Float, } } } diff --git a/src/valid/interface.rs b/src/valid/interface.rs index fdc1cf43e..67130ddc6 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -435,6 +435,35 @@ impl super::Validator { return Err(GlobalVariableError::InvalidType(var.space)); } }; + let inner_ty = match &types[var.ty].inner { + &crate::TypeInner::BindingArray { base, .. } => &types[base].inner, + ty => ty, + }; + if let crate::TypeInner::Image { + class: + crate::ImageClass::Storage { + format: + crate::StorageFormat::R16Unorm + | crate::StorageFormat::R16Snorm + | crate::StorageFormat::Rg16Unorm + | crate::StorageFormat::Rg16Snorm + | crate::StorageFormat::Rgba16Unorm + | crate::StorageFormat::Rgba16Snorm, + .. + }, + .. + } = *inner_ty + { + if !self + .capabilities + .contains(Capabilities::STORAGE_TEXTURE_16BIT_NORM_FORMATS) + { + return Err(GlobalVariableError::UnsupportedCapability( + Capabilities::STORAGE_TEXTURE_16BIT_NORM_FORMATS, + )); + } + } + (TypeFlags::empty(), true) } crate::AddressSpace::Private | crate::AddressSpace::WorkGroup => { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 7679223f0..25fdf20cc 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -87,7 +87,7 @@ bitflags::bitflags! { #[derive(Default)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] - pub struct Capabilities: u8 { + pub struct Capabilities: u16 { /// Support for [`AddressSpace:PushConstant`]. const PUSH_CONSTANT = 0x1; /// Float values with width = 8. @@ -104,6 +104,8 @@ bitflags::bitflags! { const CLIP_DISTANCE = 0x40; /// Support for [`Builtin::CullDistance`]. const CULL_DISTANCE = 0x80; + /// Support for 16-bit normalized storage texture formats. + const STORAGE_TEXTURE_16BIT_NORM_FORMATS = 0x100; } } From 9f182ade30680d47f300e47d9afa5ce06586eb65 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins Date: Sun, 22 Jan 2023 14:24:47 -0500 Subject: [PATCH 1898/2212] [wgsl] Add refract built-in --- src/back/wgsl/writer.rs | 1 + src/front/wgsl/conv.rs | 1 + tests/in/math-functions.wgsl | 1 + .../out/glsl/math-functions.main.Vertex.glsl | 1 + tests/out/hlsl/math-functions.hlsl | 1 + tests/out/msl/math-functions.msl | 1 + tests/out/spv/math-functions.spvasm | 21 ++++++++++--------- tests/out/wgsl/math-functions.wgsl | 1 + 8 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index b2cec92da..74c0bf3e8 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1582,6 +1582,7 @@ impl Writer { Mf::Normalize => Function::Regular("normalize"), Mf::FaceForward => Function::Regular("faceForward"), Mf::Reflect => Function::Regular("reflect"), + Mf::Refract => Function::Regular("refract"), // computational Mf::Sign => Function::Regular("sign"), Mf::Fma => Function::Regular("fma"), diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 645f90b01..e4c29f793 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -178,6 +178,7 @@ pub fn map_standard_fun(word: &str) -> Option { "normalize" => Mf::Normalize, "faceForward" => Mf::FaceForward, "reflect" => Mf::Reflect, + "refract" => Mf::Refract, // computational "sign" => Mf::Sign, "fma" => Mf::Fma, diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index 9ecac8049..13b080e92 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -7,6 +7,7 @@ fn main() { let c = degrees(v); let d = radians(v); let e = saturate(v); + let g = refract(v, v, f); let const_dot = dot(vec2(), vec2()); let first_leading_bit_abs = firstLeadingBit(abs(0u)); } diff --git a/tests/out/glsl/math-functions.main.Vertex.glsl b/tests/out/glsl/math-functions.main.Vertex.glsl index f0954772e..5efa8f27c 100644 --- a/tests/out/glsl/math-functions.main.Vertex.glsl +++ b/tests/out/glsl/math-functions.main.Vertex.glsl @@ -11,6 +11,7 @@ void main() { vec4 c = degrees(v); vec4 d = radians(v); vec4 e = clamp(v, vec4(0.0), vec4(1.0)); + vec4 g = refract(v, v, 1.0); int const_dot = ( + ivec2(0, 0).x * ivec2(0, 0).x + ivec2(0, 0).y * ivec2(0, 0).y); uint first_leading_bit_abs = uint(findMSB(uint(abs(int(0u))))); } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index 827da71b4..64c2e87ea 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -7,6 +7,7 @@ void main() float4 c = degrees(v); float4 d = radians(v); float4 e = saturate(v); + float4 g = refract(v, v, 1.0); int const_dot = dot(int2(0, 0), int2(0, 0)); uint first_leading_bit_abs = firstbithigh(abs(0u)); } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 559d46468..d097be47a 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -14,6 +14,7 @@ vertex void main_( metal::float4 c = ((v) * 57.295779513082322865); metal::float4 d = ((v) * 0.017453292519943295474); metal::float4 e = metal::saturate(v); + metal::float4 g = metal::refract(v, v, 1.0); int const_dot = ( + const_type_1_.x * const_type_1_.x + const_type_1_.y * const_type_1_.y); uint first_leading_bit_abs = (((metal::clz(metal::abs(0u)) + 1) % 33) - 1); } diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 194024b76..4fada56c7 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 36 +; Bound: 37 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -18,7 +18,7 @@ OpEntryPoint Vertex %14 "main" %11 = OpTypeVector %7 2 %12 = OpConstantComposite %11 %6 %6 %15 = OpTypeFunction %2 -%26 = OpConstantNull %7 +%27 = OpConstantNull %7 %14 = OpFunction %2 None %15 %13 = OpLabel OpBranch %16 @@ -31,15 +31,16 @@ OpBranch %16 %23 = OpCompositeConstruct %10 %5 %5 %5 %5 %24 = OpCompositeConstruct %10 %3 %3 %3 %3 %22 = OpExtInst %10 %1 FClamp %17 %23 %24 -%27 = OpCompositeExtract %7 %12 0 +%25 = OpExtInst %10 %1 Refract %17 %17 %3 %28 = OpCompositeExtract %7 %12 0 -%29 = OpIMul %7 %27 %28 -%30 = OpIAdd %7 %26 %29 -%31 = OpCompositeExtract %7 %12 1 +%29 = OpCompositeExtract %7 %12 0 +%30 = OpIMul %7 %28 %29 +%31 = OpIAdd %7 %27 %30 %32 = OpCompositeExtract %7 %12 1 -%33 = OpIMul %7 %31 %32 -%25 = OpIAdd %7 %30 %33 -%34 = OpCopyObject %9 %8 -%35 = OpExtInst %9 %1 FindUMsb %34 +%33 = OpCompositeExtract %7 %12 1 +%34 = OpIMul %7 %32 %33 +%26 = OpIAdd %7 %31 %34 +%35 = OpCopyObject %9 %8 +%36 = OpExtInst %9 %1 FindUMsb %35 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 2643879ee..004d9cf5b 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -6,6 +6,7 @@ fn main() { let c = degrees(v); let d = radians(v); let e = saturate(v); + let g = refract(v, v, 1.0); let const_dot = dot(vec2(0, 0), vec2(0, 0)); let first_leading_bit_abs = firstLeadingBit(abs(0u)); } From 74e5b4a07e7e260cdce29bb47572066bcf5eb449 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins Date: Sun, 22 Jan 2023 14:29:15 -0500 Subject: [PATCH 1899/2212] [wgsl] Update inverse hyperbolic built-ins --- src/back/wgsl/writer.rs | 29 ++----------------- src/front/wgsl/conv.rs | 3 ++ .../wgsl/inv-hyperbolic-trig-functions.wgsl | 6 ++-- 3 files changed, 9 insertions(+), 29 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 74c0bf3e8..e91024c2e 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1529,13 +1529,9 @@ impl Writer { use crate::MathFunction as Mf; enum Function { - Asincosh { is_sin: bool }, - Atanh, Regular(&'static str), } - // NOTE: If https://github.com/gpuweb/gpuweb/issues/1622 ever is - // accepted, replace this with the builtin functions let function = match fun { Mf::Abs => Function::Regular("abs"), Mf::Min => Function::Regular("min"), @@ -1553,9 +1549,9 @@ impl Writer { Mf::Asin => Function::Regular("asin"), Mf::Atan => Function::Regular("atan"), Mf::Atan2 => Function::Regular("atan2"), - Mf::Asinh => Function::Asincosh { is_sin: true }, - Mf::Acosh => Function::Asincosh { is_sin: false }, - Mf::Atanh => Function::Atanh, + Mf::Asinh => Function::Regular("asinh"), + Mf::Acosh => Function::Regular("acosh"), + Mf::Atanh => Function::Regular("atanh"), Mf::Radians => Function::Regular("radians"), Mf::Degrees => Function::Regular("degrees"), // decomposition @@ -1618,25 +1614,6 @@ impl Writer { }; match function { - Function::Asincosh { is_sin } => { - write!(self.out, "log(")?; - self.write_expr(module, arg, func_ctx)?; - write!(self.out, " + sqrt(")?; - self.write_expr(module, arg, func_ctx)?; - write!(self.out, " * ")?; - self.write_expr(module, arg, func_ctx)?; - match is_sin { - true => write!(self.out, " + 1.0))")?, - false => write!(self.out, " - 1.0))")?, - } - } - Function::Atanh => { - write!(self.out, "0.5 * log((1.0 + ")?; - self.write_expr(module, arg, func_ctx)?; - write!(self.out, ") / (1.0 - ")?; - self.write_expr(module, arg, func_ctx)?; - write!(self.out, "))")?; - } Function::Regular(fun_name) => { write!(self.out, "{}(", fun_name)?; self.write_expr(module, arg, func_ctx)?; diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index e4c29f793..7aa4cbc07 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -149,8 +149,11 @@ pub fn map_standard_fun(word: &str) -> Option { "tan" => Mf::Tan, "tanh" => Mf::Tanh, "acos" => Mf::Acos, + "acosh" => Mf::Acosh, "asin" => Mf::Asin, + "asinh" => Mf::Asinh, "atan" => Mf::Atan, + "atanh" => Mf::Atanh, "atan2" => Mf::Atan2, "radians" => Mf::Radians, "degrees" => Mf::Degrees, diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl index e7bee8d85..2ac357020 100644 --- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -6,11 +6,11 @@ fn main_1() { var d: f32; let _e8 = a; - b = log(_e8 + sqrt(_e8 * _e8 + 1.0)); + b = asinh(_e8); let _e10 = a; - c = log(_e10 + sqrt(_e10 * _e10 - 1.0)); + c = acosh(_e10); let _e12 = a; - d = 0.5 * log((1.0 + _e12) / (1.0 - _e12)); + d = atanh(_e12); return; } From a638da9edb35299ac785fb9cbbac6dda21cae195 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins Date: Sun, 22 Jan 2023 18:43:24 -0500 Subject: [PATCH 1900/2212] [wgsl] Removes isFinite and isNormal --- src/back/wgsl/writer.rs | 2 -- src/front/wgsl/conv.rs | 2 -- 2 files changed, 4 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index e91024c2e..da3f75d7e 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1685,8 +1685,6 @@ impl Writer { use crate::RelationalFunction as Rf; let fun_name = match fun { - Rf::IsFinite => "isFinite", - Rf::IsNormal => "isNormal", Rf::All => "all", Rf::Any => "any", _ => return Err(Error::UnsupportedRelationalFunction(fun)), diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs index 7aa4cbc07..ca4cc5519 100644 --- a/src/front/wgsl/conv.rs +++ b/src/front/wgsl/conv.rs @@ -126,8 +126,6 @@ pub fn map_relational_fun(word: &str) -> Option { match word { "any" => Some(crate::RelationalFunction::Any), "all" => Some(crate::RelationalFunction::All), - "isFinite" => Some(crate::RelationalFunction::IsFinite), - "isNormal" => Some(crate::RelationalFunction::IsNormal), _ => None, } } From 4142971cb1c6b4a9b17282819b968e1909497d1b Mon Sep 17 00:00:00 2001 From: robtfm <50659922+robtfm@users.noreply.github.com> Date: Mon, 23 Jan 2023 10:58:05 +0000 Subject: [PATCH 1901/2212] glsl: include unused items (#2205) * include_unused_items * clippy * tests * rename original const if possible --- src/back/glsl/mod.rs | 49 ++++++++++++++++--- src/front/glsl/parser_tests.rs | 13 ++++- src/front/glsl/variables.rs | 16 ++++++ .../out/wgsl/931-constant-emitting-vert.wgsl | 2 + tests/out/wgsl/bevy-pbr-frag.wgsl | 14 ++++-- tests/out/wgsl/constant-array-size-vert.wgsl | 4 +- tests/out/wgsl/expressions-frag.wgsl | 1 + .../out/wgsl/global-constant-array-vert.wgsl | 1 + tests/out/wgsl/quad_glsl-vert.wgsl | 4 +- 9 files changed, 89 insertions(+), 15 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 81df401d0..d89424128 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -214,6 +214,10 @@ bitflags::bitflags! { /// Supports GL_EXT_texture_shadow_lod on the host, which provides /// additional functions on shadows and arrays of shadows. const TEXTURE_SHADOW_LOD = 0x2; + /// Include unused global variables, constants and functions. By default the output will exclude + /// global variables that are not used in the specified entrypoint (including indirect use), + /// all constant declarations, and functions that use excluded global variables. + const INCLUDE_UNUSED_ITEMS = 0x4; } } @@ -599,11 +603,17 @@ impl<'a, W: Write> Writer<'a, W> { // Write the globals // - // We filter all globals that aren't used by the selected entry point as they might be + // Unless explicitly disabled with WriterFlags::INCLUDE_UNUSED_ITEMS, + // we filter all globals that aren't used by the selected entry point as they might be // interfere with each other (i.e. two globals with the same location but different with // different classes) + let include_unused = self + .options + .writer_flags + .contains(WriterFlags::INCLUDE_UNUSED_ITEMS); for (handle, global) in self.module.global_variables.iter() { - if ep_info[handle].is_empty() { + let is_unused = ep_info[handle].is_empty(); + if !include_unused && is_unused { continue; } @@ -679,11 +689,34 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Sampler { .. } => continue, // All other globals are written by `write_global` _ => { - if !ep_info[handle].is_empty() { - self.write_global(handle, global)?; - // Add a newline (only for readability) - writeln!(self.out)?; - } + self.write_global(handle, global)?; + // Add a newline (only for readability) + writeln!(self.out)?; + } + } + } + + if include_unused { + // write named constants + for (handle, constant) in self.module.constants.iter() { + if let Some(name) = constant.name.as_ref() { + write!(self.out, "const ")?; + match constant.inner { + crate::ConstantInner::Scalar { width, value } => { + // create a TypeInner to write + let inner = TypeInner::Scalar { + width, + kind: value.scalar_kind(), + }; + self.write_value_type(&inner)?; + } + crate::ConstantInner::Composite { ty, .. } => { + self.write_type(ty)?; + } + }; + write!(self.out, " {} = ", name)?; + self.write_constant(handle)?; + writeln!(self.out, ";")?; } } } @@ -700,7 +733,7 @@ impl<'a, W: Write> Writer<'a, W> { for (handle, function) in self.module.functions.iter() { // Check that the function doesn't use globals that aren't supported // by the current entry point - if !ep_info.dominates_global_use(&self.info[handle]) { + if !include_unused && !ep_info.dominates_global_use(&self.info[handle]) { continue; } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index d6d831aaf..df6edd21d 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -531,7 +531,18 @@ fn constants() { assert_eq!( constants.next().unwrap().1, &Constant { - name: None, + name: Some("a".to_owned()), + specialization: None, + inner: ConstantInner::Scalar { + width: 4, + value: ScalarValue::Float(1.0) + } + } + ); + assert_eq!( + constants.next().unwrap().1, + &Constant { + name: Some("b".to_owned()), specialization: None, inner: ConstantInner::Scalar { width: 4, diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index c174c9acf..ea8c9e8b5 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -501,6 +501,22 @@ impl Parser { mutable: false, }; + if let Some(name) = name.as_ref() { + let constant = self.module.constants.get_mut(init); + if constant.name.is_none() { + // set the name of the constant + constant.name = Some(name.clone()) + } else { + // add a copy of the constant with the new name + let new_const = Constant { + name: Some(name.clone()), + specialization: constant.specialization, + inner: constant.inner.clone(), + }; + self.module.constants.fetch_or_append(new_const, meta); + } + } + (GlobalOrConstant::Constant(init), lookup) } StorageQualifier::AddressSpace(mut space) => { diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl index dfb5a38a0..e42eeb054 100644 --- a/tests/out/wgsl/931-constant-emitting-vert.wgsl +++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl @@ -1,3 +1,5 @@ +let constant: i32 = 10; + fn function() -> f32 { return 0.0; } diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index cdfafde02..9bc0449d7 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -48,6 +48,12 @@ struct FragmentOutput { @location(0) o_Target: vec4, } +let MAX_POINT_LIGHTS: i32 = 10; + +let MAX_DIRECTIONAL_LIGHTS: i32 = 1; + +let PI: f32 = 3.1415927410125732; + var v_WorldPosition_1: vec3; var v_WorldNormal_1: vec3; var v_Uv_1: vec2; @@ -188,7 +194,7 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { k = (_e55 / (_e56 + (_e57 * _e58))); let _e63 = k; let _e64 = k; - d = ((_e63 * _e64) * (1.0 / 3.1415927410125732)); + d = ((_e63 * _e64) * (1.0 / PI)); let _e70 = d; return _e70; } @@ -441,7 +447,7 @@ fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { viewScatter = _e72; let _e74 = lightScatter; let _e75 = viewScatter; - return ((_e74 * _e75) * (1.0 / 3.1415927410125732)); + return ((_e74 * _e75) * (1.0 / PI)); } fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 { @@ -1193,7 +1199,7 @@ fn main_1() { let _e227 = i; let _e228 = global_2.NumLights; let _e232 = i; - if !(((_e227 < i32(_e228.x)) && (_e232 < 10))) { + if !(((_e227 < i32(_e228.x)) && (_e232 < MAX_POINT_LIGHTS))) { break; } { @@ -1229,7 +1235,7 @@ fn main_1() { let _e264 = i_1; let _e265 = global_2.NumLights; let _e269 = i_1; - if !(((_e264 < i32(_e265.y)) && (_e269 < 1))) { + if !(((_e264 < i32(_e265.y)) && (_e269 < MAX_DIRECTIONAL_LIGHTS))) { break; } { diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 15018270f..3f26c5b15 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -2,6 +2,8 @@ struct Data { vecs: array,42u>, } +let NUM_VECS: i32 = 42; + @group(1) @binding(0) var global: Data; @@ -13,7 +15,7 @@ fn function() -> vec4 { i = 0; loop { let _e9 = i; - if !((_e9 < 42)) { + if !((_e9 < NUM_VECS)) { break; } { diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 8e4f46ec4..1c8a2aff0 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -14,6 +14,7 @@ struct FragmentOutput { @location(0) o_color: vec4, } +let strct: TestStruct = TestStruct(array,2u>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); var global: f32; @group(0) @binding(0) var global_1: a_buf; diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index a74aa3f2c..e066042e2 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -1,3 +1,4 @@ +let array_: array = array(1.0, 2.0); var i: u32; fn main_1() { diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index ea4d77401..cb6f766d5 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -3,6 +3,8 @@ struct VertexOutput { @builtin(position) member: vec4, } +let c_scale: f32 = 1.2000000476837158; + var a_pos_1: vec2; var a_uv_1: vec2; var v_uv: vec2; @@ -12,7 +14,7 @@ fn main_1() { let _e4 = a_uv_1; v_uv = _e4; let _e6 = a_pos_1; - let _e7 = (1.2000000476837158 * _e6); + let _e7 = (c_scale * _e6); gl_Position = vec4(_e7.x, _e7.y, 0.0, 1.0); return; } From f70d8ec51f6d6e623f7684d579624bfe12d4899a Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 23 Jan 2023 12:09:15 +0100 Subject: [PATCH 1902/2212] update test snapshots (#2219) --- tests/out/wgsl/931-constant-emitting-vert.wgsl | 2 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 6 +++--- tests/out/wgsl/constant-array-size-vert.wgsl | 2 +- tests/out/wgsl/expressions-frag.wgsl | 2 +- tests/out/wgsl/global-constant-array-vert.wgsl | 2 +- tests/out/wgsl/quad_glsl-vert.wgsl | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl index e42eeb054..c6b2687e8 100644 --- a/tests/out/wgsl/931-constant-emitting-vert.wgsl +++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl @@ -1,4 +1,4 @@ -let constant: i32 = 10; +const constant: i32 = 10; fn function() -> f32 { return 0.0; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 9bc0449d7..4b9467e56 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -48,11 +48,11 @@ struct FragmentOutput { @location(0) o_Target: vec4, } -let MAX_POINT_LIGHTS: i32 = 10; +const MAX_POINT_LIGHTS: i32 = 10; -let MAX_DIRECTIONAL_LIGHTS: i32 = 1; +const MAX_DIRECTIONAL_LIGHTS: i32 = 1; -let PI: f32 = 3.1415927410125732; +const PI: f32 = 3.1415927410125732; var v_WorldPosition_1: vec3; var v_WorldNormal_1: vec3; diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl index 3f26c5b15..d9ed86654 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-vert.wgsl @@ -2,7 +2,7 @@ struct Data { vecs: array,42u>, } -let NUM_VECS: i32 = 42; +const NUM_VECS: i32 = 42; @group(1) @binding(0) var global: Data; diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 1c8a2aff0..0cad7bf31 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -14,7 +14,7 @@ struct FragmentOutput { @location(0) o_color: vec4, } -let strct: TestStruct = TestStruct(array,2u>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); +const strct: TestStruct = TestStruct(array,2u>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); var global: f32; @group(0) @binding(0) var global_1: a_buf; diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl index e066042e2..880556812 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-vert.wgsl @@ -1,4 +1,4 @@ -let array_: array = array(1.0, 2.0); +const array_: array = array(1.0, 2.0); var i: u32; fn main_1() { diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index cb6f766d5..68661486c 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -3,7 +3,7 @@ struct VertexOutput { @builtin(position) member: vec4, } -let c_scale: f32 = 1.2000000476837158; +const c_scale: f32 = 1.2000000476837158; var a_pos_1: vec2; var a_uv_1: vec2; From 954cbaaff36503d1336a99991adf37a6c3d53884 Mon Sep 17 00:00:00 2001 From: Patryk Wychowaniec Date: Wed, 25 Jan 2023 17:49:52 +0100 Subject: [PATCH 1903/2212] [spv-in] Support binding arrays (#2199) --- src/front/spv/error.rs | 7 +- src/front/spv/image.rs | 30 +++- src/front/spv/mod.rs | 191 +++++++++++++++------ tests/in/spv/binding-arrays.dynamic.spv | Bin 0 -> 720 bytes tests/in/spv/binding-arrays.dynamic.spvasm | 75 ++++++++ tests/in/spv/binding-arrays.static.spv | Bin 0 -> 760 bytes tests/in/spv/binding-arrays.static.spvasm | 78 +++++++++ tests/out/wgsl/binding-arrays.dynamic.wgsl | 18 ++ tests/out/wgsl/binding-arrays.static.wgsl | 18 ++ tests/snapshots.rs | 7 +- 10 files changed, 366 insertions(+), 58 deletions(-) create mode 100644 tests/in/spv/binding-arrays.dynamic.spv create mode 100644 tests/in/spv/binding-arrays.dynamic.spvasm create mode 100644 tests/in/spv/binding-arrays.static.spv create mode 100644 tests/in/spv/binding-arrays.static.spvasm create mode 100644 tests/out/wgsl/binding-arrays.dynamic.wgsl create mode 100644 tests/out/wgsl/binding-arrays.static.wgsl diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 3877590c4..6c9cf384f 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -118,5 +118,10 @@ pub enum Error { InvalidBarrierScope(spirv::Word), #[error("invalid barrier memory semantics %{0}")] InvalidBarrierMemorySemantics(spirv::Word), - // incomplete implementation errors + #[error( + "arrays of images / samplers are supported only through bindings for \ + now (i.e. you can't create an array of images or samplers that doesn't \ + come from a binding)" + )] + NonBindingArrayOfImageOrSamplers, } diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index c45288ab1..07681917b 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -536,19 +536,47 @@ impl> super::Parser { ctx.global_arena[handle].ty } + crate::Expression::FunctionArgument(i) => { ctx.parameter_sampling[i as usize] |= sampling_bit; ctx.arguments[i as usize].ty } + + crate::Expression::Access { base, .. } => match ctx.expressions[base] { + crate::Expression::GlobalVariable(handle) => { + if let Some(flags) = self.handle_sampling.get_mut(&handle) { + *flags |= sampling_bit; + } + + match ctx.type_arena[ctx.global_arena[handle].ty].inner { + crate::TypeInner::BindingArray { base, .. } => base, + _ => return Err(Error::InvalidGlobalVar(ctx.expressions[base].clone())), + } + } + + ref other => return Err(Error::InvalidGlobalVar(other.clone())), + }, + ref other => return Err(Error::InvalidGlobalVar(other.clone())), }; + match ctx.expressions[si_lexp.sampler] { crate::Expression::GlobalVariable(handle) => { - *self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit + *self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit; } + crate::Expression::FunctionArgument(i) => { ctx.parameter_sampling[i as usize] |= sampling_bit; } + + crate::Expression::Access { base, .. } => match ctx.expressions[base] { + crate::Expression::GlobalVariable(handle) => { + *self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit; + } + + ref other => return Err(Error::InvalidGlobalVar(other.clone())), + }, + ref other => return Err(Error::InvalidGlobalVar(other.clone())), } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 944d68593..b51f10f23 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -106,7 +106,7 @@ impl Instruction { } impl crate::TypeInner { - const fn can_comparison_sample(&self) -> bool { + fn can_comparison_sample(&self, module: &crate::Module) -> bool { match *self { crate::TypeInner::Image { class: @@ -117,6 +117,9 @@ impl crate::TypeInner { .. } => true, crate::TypeInner::Sampler { .. } => true, + crate::TypeInner::BindingArray { base, .. } => { + module.types[base].inner.can_comparison_sample(module) + } _ => false, } } @@ -1428,17 +1431,38 @@ impl> Parser { let result_id = self.next()?; let base_id = self.next()?; log::trace!("\t\t\tlooking up expr {:?}", base_id); + let mut acex = { - // the base type has to be a pointer, - // so we dereference it here for the traversal let lexp = self.lookup_expression.lookup(base_id)?; let lty = self.lookup_type.lookup(lexp.type_id)?; + + // HACK `OpAccessChain` and `OpInBoundsAccessChain` + // require for the result type to be a pointer, but if + // we're given a pointer to an image / sampler, it will + // be *already* dereferenced, since we do that early + // during `parse_type_pointer()`. + // + // This can happen only through `BindingArray`, since + // that's the only case where one can obtain a pointer + // to an image / sampler, and so let's match on that: + let dereference = match ctx.type_arena[lty.handle].inner { + crate::TypeInner::BindingArray { .. } => false, + _ => true, + }; + + let type_id = if dereference { + lty.base_id.ok_or(Error::InvalidAccessType(lexp.type_id))? + } else { + lexp.type_id + }; + AccessExpression { base_handle: get_expr_handle!(base_id, lexp), - type_id: lty.base_id.ok_or(Error::InvalidAccessType(lexp.type_id))?, + type_id, load_override: self.lookup_load_override.get(&base_id).cloned(), } }; + for _ in 4..inst.wc { let access_id = self.next()?; log::trace!("\t\t\tlooking up index expr {:?}", access_id); @@ -4220,6 +4244,7 @@ impl> Parser { let decor = self.future_decor.remove(&id); let base_lookup_ty = self.lookup_type.lookup(type_id)?; let base_inner = &module.types[base_lookup_ty.handle].inner; + let space = if let Some(space) = base_inner.pointer_space() { space } else if self @@ -4289,17 +4314,60 @@ impl> Parser { let decor = self.future_decor.remove(&id).unwrap_or_default(); let base = self.lookup_type.lookup(type_id)?.handle; + self.layouter .update(&module.types, &module.constants) .unwrap(); - let inner = crate::TypeInner::Array { - base, - size: crate::ArraySize::Constant(length_const.handle), - stride: match decor.array_stride { - Some(stride) => stride.get(), - None => self.layouter[base].to_stride(), - }, + + // HACK if the underlying type is an image or a sampler, let's assume + // that we're dealing with a binding-array + // + // Note that it's not a strictly correct assumption, but rather a trade + // off caused by an impedance mismatch between SPIR-V's and Naga's type + // systems - Naga distinguishes between arrays and binding-arrays via + // types (i.e. both kinds of arrays are just different types), while + // SPIR-V distinguishes between them through usage - e.g. given: + // + // ``` + // %image = OpTypeImage %float 2D 2 0 0 2 Rgba16f + // %uint_256 = OpConstant %uint 256 + // %image_array = OpTypeArray %image %uint_256 + // ``` + // + // ``` + // %image = OpTypeImage %float 2D 2 0 0 2 Rgba16f + // %uint_256 = OpConstant %uint 256 + // %image_array = OpTypeArray %image %uint_256 + // %image_array_ptr = OpTypePointer UniformConstant %image_array + // ``` + // + // ... in the first case, `%image_array` should technically correspond + // to `TypeInner::Array`, while in the second case it should say + // `TypeInner::BindingArray` (kinda, depending on whether `%image_array` + // is ever used as a freestanding type or rather always through the + // pointer-indirection). + // + // Anyway, at the moment we don't support other kinds of image / sampler + // arrays than those binding-based, so this assumption is pretty safe + // for now. + let inner = if let crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } = + module.types[base].inner + { + crate::TypeInner::BindingArray { + base, + size: crate::ArraySize::Constant(length_const.handle), + } + } else { + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(length_const.handle), + stride: match decor.array_stride { + Some(stride) => stride.get(), + None => self.layouter[base].to_stride(), + }, + } }; + self.lookup_type.insert( id, LookupType { @@ -4329,17 +4397,30 @@ impl> Parser { let decor = self.future_decor.remove(&id).unwrap_or_default(); let base = self.lookup_type.lookup(type_id)?.handle; + self.layouter .update(&module.types, &module.constants) .unwrap(); - let inner = crate::TypeInner::Array { - base: self.lookup_type.lookup(type_id)?.handle, - size: crate::ArraySize::Dynamic, - stride: match decor.array_stride { - Some(stride) => stride.get(), - None => self.layouter[base].to_stride(), - }, + + // HACK same case as in `parse_type_array()` + let inner = if let crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } = + module.types[base].inner + { + crate::TypeInner::BindingArray { + base: self.lookup_type.lookup(type_id)?.handle, + size: crate::ArraySize::Dynamic, + } + } else { + crate::TypeInner::Array { + base: self.lookup_type.lookup(type_id)?.handle, + size: crate::ArraySize::Dynamic, + stride: match decor.array_stride { + Some(stride) => stride.get(), + None => self.layouter[base].to_stride(), + }, + } }; + self.lookup_type.insert( id, LookupType { @@ -4793,32 +4874,45 @@ impl> Parser { let mut dec = self.future_decor.remove(&id).unwrap_or_default(); let original_ty = self.lookup_type.lookup(type_id)?.handle; - let mut effective_ty = original_ty; + let mut ty = original_ty; + if let crate::TypeInner::Pointer { base, space: _ } = module.types[original_ty].inner { - effective_ty = base; - }; + ty = base; + } + + if let crate::TypeInner::BindingArray { .. } = module.types[original_ty].inner { + // Inside `parse_type_array()` we guess that an array of images or + // samplers must be a binding array, and here we validate that guess + if dec.desc_set.is_none() || dec.desc_index.is_none() { + return Err(Error::NonBindingArrayOfImageOrSamplers); + } + } + if let crate::TypeInner::Image { dim, arrayed, class: crate::ImageClass::Storage { format, access: _ }, - } = module.types[effective_ty].inner + } = module.types[ty].inner { // Storage image types in IR have to contain the access, but not in the SPIR-V. // The same image type in SPIR-V can be used (and has to be used) for multiple images. // So we copy the type out and apply the variable access decorations. let access = dec.flags.to_storage_access(); - let ty = crate::Type { - name: None, - inner: crate::TypeInner::Image { - dim, - arrayed, - class: crate::ImageClass::Storage { format, access }, + + ty = module.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Image { + dim, + arrayed, + class: crate::ImageClass::Storage { format, access }, + }, }, - }; - effective_ty = module.types.insert(ty, Default::default()); + Default::default(), + ); } - let ext_class = match self.lookup_storage_buffer_types.get(&effective_ty) { + let ext_class = match self.lookup_storage_buffer_types.get(&ty) { Some(&access) => ExtendedClass::Global(crate::AddressSpace::Storage { access }), None => map_storage_class(storage_class)?, }; @@ -4843,14 +4937,14 @@ impl> Parser { binding: dec.resource_binding(), name: dec.name, space, - ty: effective_ty, + ty, init, }; (Variable::Global, var) } ExtendedClass::Input => { let mut binding = dec.io_binding()?; - let mut unsigned_ty = effective_ty; + let mut unsigned_ty = ty; if let crate::Binding::BuiltIn(built_in) = binding { let needs_inner_uint = match built_in { crate::BuiltIn::BaseInstance @@ -4873,10 +4967,9 @@ impl> Parser { }), _ => None, }; - if let (Some(inner), Some(crate::ScalarKind::Sint)) = ( - needs_inner_uint, - module.types[effective_ty].inner.scalar_kind(), - ) { + if let (Some(inner), Some(crate::ScalarKind::Sint)) = + (needs_inner_uint, module.types[ty].inner.scalar_kind()) + { unsigned_ty = module .types .insert(crate::Type { name: None, inner }, Default::default()); @@ -4887,7 +4980,7 @@ impl> Parser { name: dec.name.clone(), space: crate::AddressSpace::Private, binding: None, - ty: effective_ty, + ty, init: None, }; @@ -4907,7 +5000,7 @@ impl> Parser { Some(crate::Binding::BuiltIn(built_in)) => { match null::generate_default_built_in( Some(built_in), - effective_ty, + ty, &module.types, &mut module.constants, span, @@ -4920,7 +5013,7 @@ impl> Parser { } } Some(crate::Binding::Location { .. }) => None, - None => match module.types[effective_ty].inner { + None => match module.types[ty].inner { crate::TypeInner::Struct { ref members, .. } => { // A temporary to avoid borrowing `module.types` let pairs = members @@ -4949,10 +5042,7 @@ impl> Parser { crate::Constant { name: None, specialization: None, - inner: crate::ConstantInner::Composite { - ty: effective_ty, - components, - }, + inner: crate::ConstantInner::Composite { ty, components }, }, span, )) @@ -4965,23 +5055,22 @@ impl> Parser { name: dec.name, space: crate::AddressSpace::Private, binding: None, - ty: effective_ty, + ty, init, }; if let Some(ref mut binding) = binding { - binding.apply_default_interpolation(&module.types[effective_ty].inner); + binding.apply_default_interpolation(&module.types[ty].inner); } - let inner = Variable::Output(crate::FunctionResult { - ty: effective_ty, - binding, - }); + let inner = Variable::Output(crate::FunctionResult { ty, binding }); (inner, var) } }; let handle = module.global_variables.append(var, span); - if module.types[effective_ty].inner.can_comparison_sample() { + + if module.types[ty].inner.can_comparison_sample(module) { log::debug!("\t\ttracking {:?} for sampling properties", handle); + self.handle_sampling .insert(handle, image::SamplingFlags::empty()); } diff --git a/tests/in/spv/binding-arrays.dynamic.spv b/tests/in/spv/binding-arrays.dynamic.spv new file mode 100644 index 0000000000000000000000000000000000000000..12bf2e00edf3048a9814efb67dedbf59fbe90ded GIT binary patch literal 720 zcmYk3%T5A85Jk&D8SueF1O!9}S;Cr_7$v~$!vF7*4|n0U@icS0q1s_(6?>O0-7 zVqHf2C?d+J_!`3~LZuh2n)~TTCyvSL-=AMUY6WnI`hZn4CE^X`1g)KFa@U94-g{tJ zm#=EpaOWP@<<>pJ{hoOXj1k=>d4h)yxdKymbjfmO%TE)xw}PLMovXfqyZ0Or`z?Q9 z{{>JJc~6hEF{YuU+@eWypSzN?!1J~-9)xdZCHhiCW(&rH^zwLhFafPY2) B5-I=y literal 0 HcmV?d00001 diff --git a/tests/in/spv/binding-arrays.dynamic.spvasm b/tests/in/spv/binding-arrays.dynamic.spvasm new file mode 100644 index 000000000..d1c38a832 --- /dev/null +++ b/tests/in/spv/binding-arrays.dynamic.spvasm @@ -0,0 +1,75 @@ +;; Make sure that we promote `OpTypeRuntimeArray` of textures and samplers into +;; `TypeInner::BindingArray` and support indexing it through `OpAccessChain` +;; and `OpInBoundsAccessChain`. +;; +;; Code in here corresponds to, more or less: +;; +;; ```rust +;; #[spirv(fragment)] +;; pub fn main( +;; #[spirv(descriptor_set = 0, binding = 0)] +;; images: &RuntimeArray, +;; #[spirv(descriptor_set = 0, binding = 1)] +;; samplers: &RuntimeArray, +;; out: &mut Vec4, +;; ) { +;; let image = images[1]; +;; let sampler = samplers[1]; +;; +;; *out = image.sample_by_lod(sampler, vec2(0.5, 0.5), 0.0); +;; } +;; ``` + + OpCapability Shader + OpMemoryModel Logical Simple + OpEntryPoint Fragment %main "main" %fn_param_images %fn_param_samplers %fn_param_out + OpExecutionMode %main OriginUpperLeft + OpDecorate %images ArrayStride 4 + OpDecorate %samplers ArrayStride 4 + OpDecorate %fn_param_images DescriptorSet 0 + OpDecorate %fn_param_images Binding 0 + OpDecorate %fn_param_samplers DescriptorSet 0 + OpDecorate %fn_param_samplers Binding 1 + OpDecorate %fn_param_out Location 0 + + %void = OpTypeVoid + + %float = OpTypeFloat 32 + %v2float = OpTypeVector %float 2 + %v4float = OpTypeVector %float 4 + %v4float_ptr = OpTypePointer Output %v4float + %float_0_5 = OpConstant %float 0.5 + %float_0_5_0_5 = OpConstantComposite %v2float %float_0_5 %float_0_5 + %float_0 = OpConstant %float 0 + + %int = OpTypeInt 32 1 + %int_1 = OpConstant %int 1 + + %image = OpTypeImage %float 2D 2 0 0 1 Unknown + %image_ptr = OpTypePointer UniformConstant %image + %images = OpTypeRuntimeArray %image + %images_ptr = OpTypePointer UniformConstant %images + + %sampler = OpTypeSampler + %sampler_ptr = OpTypePointer UniformConstant %sampler + %samplers = OpTypeRuntimeArray %sampler + %samplers_ptr = OpTypePointer UniformConstant %samplers + + %sampled_image = OpTypeSampledImage %image + + %fn_void = OpTypeFunction %void +%fn_param_images = OpVariable %images_ptr UniformConstant +%fn_param_samplers = OpVariable %samplers_ptr UniformConstant + %fn_param_out = OpVariable %v4float_ptr Output + + %main = OpFunction %void None %fn_void + %main_prelude = OpLabel + %1 = OpAccessChain %image_ptr %fn_param_images %int_1 + %2 = OpInBoundsAccessChain %sampler_ptr %fn_param_samplers %int_1 + %3 = OpLoad %sampler %2 + %4 = OpLoad %image %1 + %5 = OpSampledImage %sampled_image %4 %3 + %6 = OpImageSampleExplicitLod %v4float %5 %float_0_5_0_5 Lod %float_0 + OpStore %fn_param_out %6 + OpReturn + OpFunctionEnd diff --git a/tests/in/spv/binding-arrays.static.spv b/tests/in/spv/binding-arrays.static.spv new file mode 100644 index 0000000000000000000000000000000000000000..0d3c304af4221791cc5192332be859c6c4c677ab GIT binary patch literal 760 zcmYk3$xZ`73`ETYGGWU?HnIRcaD+2LiV_4D{s3|1$N|2e3li@o-BK*o*i~-3J?>U@ zS4aCGBI>y1s|}(Gm2R}Q+)pn$afny{{`~q;tAHoe`$W4g5pO6*XziSn8}D;#%YEkM z4bbHF-OtO-dxv@Nyaw8k>KZ?xs)J8p%86sV+}`q&%&krEQ@nlE@8O<31K9Hee_;JN zP!r`$mslH9)59m=T;}Ed%*_vo6VS}dFC-MqxM4`>z1BNtF}dcPqg}W?yM()2>+EBG zob&2)x=gY@&AQw=_itS4E^}Ue!6s&S`!>XLygOax{$)0~b?!}*yGM7b_Q-VBmHF-S z%S;RW3pxK~3GC;dUeTQM3RthUrkiv6zUp%4x&hX{Q{$`&sCn*#TYbj{B;dPwhi|o^ Mv-6qzW3ngk58vw(F#rGn literal 0 HcmV?d00001 diff --git a/tests/in/spv/binding-arrays.static.spvasm b/tests/in/spv/binding-arrays.static.spvasm new file mode 100644 index 000000000..d08fe7206 --- /dev/null +++ b/tests/in/spv/binding-arrays.static.spvasm @@ -0,0 +1,78 @@ +;; Make sure that we promote `OpTypeArray` of textures and samplers into +;; `TypeInner::BindingArray` and support indexing it through `OpAccessChain` +;; and `OpInBoundsAccessChain`. +;; +;; Code in here corresponds to, more or less: +;; +;; ```rust +;; #[spirv(fragment)] +;; pub fn main( +;; #[spirv(descriptor_set = 0, binding = 0)] +;; images: &[Image!(2D, type=f32, sampled); 256], +;; #[spirv(descriptor_set = 0, binding = 1)] +;; samplers: &[Sampler; 256], +;; out: &mut Vec4, +;; ) { +;; let image = images[1]; +;; let sampler = samplers[1]; +;; +;; *out = image.sample_by_lod(sampler, vec2(0.5, 0.5), 0.0); +;; } +;; ``` + + OpCapability Shader + OpMemoryModel Logical Simple + OpEntryPoint Fragment %main "main" %fn_param_images %fn_param_samplers %fn_param_out + OpExecutionMode %main OriginUpperLeft + OpDecorate %images ArrayStride 4 + OpDecorate %samplers ArrayStride 4 + OpDecorate %fn_param_images DescriptorSet 0 + OpDecorate %fn_param_images Binding 0 + OpDecorate %fn_param_samplers DescriptorSet 0 + OpDecorate %fn_param_samplers Binding 1 + OpDecorate %fn_param_out Location 0 + + %void = OpTypeVoid + + %float = OpTypeFloat 32 + %v2float = OpTypeVector %float 2 + %v4float = OpTypeVector %float 4 + %v4float_ptr = OpTypePointer Output %v4float + %float_0_5 = OpConstant %float 0.5 + %float_0_5_0_5 = OpConstantComposite %v2float %float_0_5 %float_0_5 + %float_0 = OpConstant %float 0 + + %int = OpTypeInt 32 1 + %int_1 = OpConstant %int 1 + + %uint = OpTypeInt 32 0 + %uint_256 = OpConstant %uint 256 + + %image = OpTypeImage %float 2D 2 0 0 1 Unknown + %image_ptr = OpTypePointer UniformConstant %image + %images = OpTypeArray %image %uint_256 + %images_ptr = OpTypePointer UniformConstant %images + + %sampler = OpTypeSampler + %sampler_ptr = OpTypePointer UniformConstant %sampler + %samplers = OpTypeArray %sampler %uint_256 + %samplers_ptr = OpTypePointer UniformConstant %samplers + + %sampled_image = OpTypeSampledImage %image + + %fn_void = OpTypeFunction %void +%fn_param_images = OpVariable %images_ptr UniformConstant +%fn_param_samplers = OpVariable %samplers_ptr UniformConstant + %fn_param_out = OpVariable %v4float_ptr Output + + %main = OpFunction %void None %fn_void + %main_prelude = OpLabel + %1 = OpAccessChain %image_ptr %fn_param_images %int_1 + %2 = OpInBoundsAccessChain %sampler_ptr %fn_param_samplers %int_1 + %3 = OpLoad %sampler %2 + %4 = OpLoad %image %1 + %5 = OpSampledImage %sampled_image %4 %3 + %6 = OpImageSampleExplicitLod %v4float %5 %float_0_5_0_5 Lod %float_0 + OpStore %fn_param_out %6 + OpReturn + OpFunctionEnd diff --git a/tests/out/wgsl/binding-arrays.dynamic.wgsl b/tests/out/wgsl/binding-arrays.dynamic.wgsl new file mode 100644 index 000000000..523b31127 --- /dev/null +++ b/tests/out/wgsl/binding-arrays.dynamic.wgsl @@ -0,0 +1,18 @@ +@group(0) @binding(0) +var global: binding_array>; +@group(0) @binding(1) +var global_1: binding_array; +var global_2: vec4; + +fn function() { + let _e13 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); + global_2 = _e13; + return; +} + +@fragment +fn main() -> @location(0) vec4 { + function(); + let _e1 = global_2; + return _e1; +} diff --git a/tests/out/wgsl/binding-arrays.static.wgsl b/tests/out/wgsl/binding-arrays.static.wgsl new file mode 100644 index 000000000..c669e9aa6 --- /dev/null +++ b/tests/out/wgsl/binding-arrays.static.wgsl @@ -0,0 +1,18 @@ +@group(0) @binding(0) +var global: binding_array,256u>; +@group(0) @binding(1) +var global_1: binding_array; +var global_2: vec4; + +fn function() { + let _e14 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); + global_2 = _e14; + return; +} + +@fragment +fn main() -> @location(0) vec4 { + function(); + let _e1 = global_2; + return _e1; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 34c881f0b..706e714b0 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -607,12 +607,9 @@ fn convert_spv_all() { true, Targets::HLSL | Targets::WGSL | Targets::METAL, ); - convert_spv( - "empty-global-name", - true, - Targets::HLSL | Targets::WGSL | Targets::METAL, - ); convert_spv("degrees", false, Targets::empty()); + convert_spv("binding-arrays.dynamic", true, Targets::WGSL); + convert_spv("binding-arrays.static", true, Targets::WGSL); } #[cfg(feature = "glsl-in")] From e5121ca01261518146ad9ad6f9d3eeb415414b45 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Jan 2023 12:24:29 +0100 Subject: [PATCH 1904/2212] factor out `write_barrier` functions --- src/back/glsl/mod.rs | 25 +++++++++++--------- src/back/hlsl/writer.rs | 18 +++++++++------ src/back/msl/writer.rs | 51 ++++++++++++++++++++++------------------- src/back/spv/block.rs | 23 +------------------ src/back/spv/writer.rs | 25 ++++++++++++++++++++ 5 files changed, 79 insertions(+), 63 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index d89424128..ede4bf848 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2035,18 +2035,8 @@ impl<'a, W: Write> Writer<'a, W> { // keyword which ceases all further processing in a fragment shader, it's called OpKill // in spir-v that's why it's called `Statement::Kill` Statement::Kill => writeln!(self.out, "{}discard;", level)?, - // Issue a memory barrier. Please note that to ensure visibility, - // OpenGL always requires a call to the `barrier()` function after a `memoryBarrier*()` Statement::Barrier(flags) => { - if flags.contains(crate::Barrier::STORAGE) { - writeln!(self.out, "{}memoryBarrierBuffer();", level)?; - } - - if flags.contains(crate::Barrier::WORK_GROUP) { - writeln!(self.out, "{}memoryBarrierShared();", level)?; - } - - writeln!(self.out, "{}barrier();", level)?; + self.write_barrier(flags, level)?; } // Stores in glsl are just variable assignments written as `pointer = value;` Statement::Store { pointer, value } => { @@ -3621,6 +3611,19 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Issue a memory barrier. Please note that to ensure visibility, + /// OpenGL always requires a call to the `barrier()` function after a `memoryBarrier*()` + fn write_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult { + if flags.contains(crate::Barrier::STORAGE) { + writeln!(self.out, "{}memoryBarrierBuffer();", level)?; + } + if flags.contains(crate::Barrier::WORK_GROUP) { + writeln!(self.out, "{}memoryBarrierShared();", level)?; + } + writeln!(self.out, "{}barrier();", level)?; + Ok(()) + } + /// Helper function that return the glsl storage access string of [`StorageAccess`](crate::StorageAccess) /// /// glsl allows adding both `readonly` and `writeonly` but this means that diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index bf841a121..d119df6f2 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1690,13 +1690,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Statement::Break => writeln!(self.out, "{}break;", level)?, Statement::Continue => writeln!(self.out, "{}continue;", level)?, Statement::Barrier(barrier) => { - if barrier.contains(crate::Barrier::STORAGE) { - writeln!(self.out, "{}DeviceMemoryBarrierWithGroupSync();", level)?; - } - - if barrier.contains(crate::Barrier::WORK_GROUP) { - writeln!(self.out, "{}GroupMemoryBarrierWithGroupSync();", level)?; - } + self.write_barrier(barrier, level)?; } Statement::ImageStore { image, @@ -2872,6 +2866,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } Ok(()) } + + fn write_barrier(&mut self, barrier: crate::Barrier, level: back::Level) -> BackendResult { + if barrier.contains(crate::Barrier::STORAGE) { + writeln!(self.out, "{}DeviceMemoryBarrierWithGroupSync();", level)?; + } + if barrier.contains(crate::Barrier::WORK_GROUP) { + writeln!(self.out, "{}GroupMemoryBarrierWithGroupSync();", level)?; + } + Ok(()) + } } pub(super) struct MatrixType { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 4ef17975f..331f7a2db 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2624,29 +2624,7 @@ impl Writer { writeln!(self.out, "{}{}::discard_fragment();", level, NAMESPACE)?; } crate::Statement::Barrier(flags) => { - //Note: OR-ring bitflags requires `__HAVE_MEMFLAG_OPERATORS__`, - // so we try to avoid it here. - if flags.is_empty() { - writeln!( - self.out, - "{}{}::threadgroup_barrier({}::mem_flags::mem_none);", - level, NAMESPACE, NAMESPACE, - )?; - } - if flags.contains(crate::Barrier::STORAGE) { - writeln!( - self.out, - "{}{}::threadgroup_barrier({}::mem_flags::mem_device);", - level, NAMESPACE, NAMESPACE, - )?; - } - if flags.contains(crate::Barrier::WORK_GROUP) { - writeln!( - self.out, - "{}{}::threadgroup_barrier({}::mem_flags::mem_threadgroup);", - level, NAMESPACE, NAMESPACE, - )?; - } + self.write_barrier(flags, level)?; } crate::Statement::Store { pointer, value } => { self.put_store(pointer, value, level, context)? @@ -3932,6 +3910,33 @@ impl Writer { Ok(info) } + + fn write_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult { + // Note: OR-ring bitflags requires `__HAVE_MEMFLAG_OPERATORS__`, + // so we try to avoid it here. + if flags.is_empty() { + writeln!( + self.out, + "{}{}::threadgroup_barrier({}::mem_flags::mem_none);", + level, NAMESPACE, NAMESPACE, + )?; + } + if flags.contains(crate::Barrier::STORAGE) { + writeln!( + self.out, + "{}{}::threadgroup_barrier({}::mem_flags::mem_device);", + level, NAMESPACE, NAMESPACE, + )?; + } + if flags.contains(crate::Barrier::WORK_GROUP) { + writeln!( + self.out, + "{}{}::threadgroup_barrier({}::mem_flags::mem_threadgroup);", + level, NAMESPACE, NAMESPACE, + )?; + } + Ok(()) + } } #[test] diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 23d23eec3..5ebbf2ea8 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1841,28 +1841,7 @@ impl<'w> BlockContext<'w> { return Ok(()); } crate::Statement::Barrier(flags) => { - let memory_scope = if flags.contains(crate::Barrier::STORAGE) { - spirv::Scope::Device - } else { - spirv::Scope::Workgroup - }; - let mut semantics = spirv::MemorySemantics::ACQUIRE_RELEASE; - semantics.set( - spirv::MemorySemantics::UNIFORM_MEMORY, - flags.contains(crate::Barrier::STORAGE), - ); - semantics.set( - spirv::MemorySemantics::WORKGROUP_MEMORY, - flags.contains(crate::Barrier::WORK_GROUP), - ); - let exec_scope_id = self.get_index_constant(spirv::Scope::Workgroup as u32); - let mem_scope_id = self.get_index_constant(memory_scope as u32); - let semantics_id = self.get_index_constant(semantics.bits()); - block.body.push(Instruction::control_barrier( - exec_scope_id, - mem_scope_id, - semantics_id, - )); + self.writer.write_barrier(flags, &mut block); } crate::Statement::Store { pointer, value } => { let value_id = self.cached[value]; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4303006bf..d61ae08bf 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1118,6 +1118,31 @@ impl Writer { null_id } + pub(super) fn write_barrier(&mut self, flags: crate::Barrier, block: &mut Block) { + let memory_scope = if flags.contains(crate::Barrier::STORAGE) { + spirv::Scope::Device + } else { + spirv::Scope::Workgroup + }; + let mut semantics = spirv::MemorySemantics::ACQUIRE_RELEASE; + semantics.set( + spirv::MemorySemantics::UNIFORM_MEMORY, + flags.contains(crate::Barrier::STORAGE), + ); + semantics.set( + spirv::MemorySemantics::WORKGROUP_MEMORY, + flags.contains(crate::Barrier::WORK_GROUP), + ); + let exec_scope_id = self.get_index_constant(spirv::Scope::Workgroup as u32); + let mem_scope_id = self.get_index_constant(memory_scope as u32); + let semantics_id = self.get_index_constant(semantics.bits()); + block.body.push(Instruction::control_barrier( + exec_scope_id, + mem_scope_id, + semantics_id, + )); + } + /// Generate an `OpVariable` for one value in an [`EntryPoint`]'s IO interface. /// /// The [`Binding`]s of the arguments and result of an [`EntryPoint`]'s From a42857d29160cf087e8de369da02414fad3bc898 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Jan 2023 12:28:57 +0100 Subject: [PATCH 1905/2212] [hlsl-out] simplify `write_default_init` --- src/back/hlsl/writer.rs | 26 +++++--------------------- tests/out/hlsl/access.hlsl | 2 +- 2 files changed, 6 insertions(+), 22 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index d119df6f2..59050455a 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2842,28 +2842,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { /// Helper function that write default zero initialization fn write_default_init(&mut self, module: &Module, ty: Handle) -> BackendResult { - match module.types[ty].inner { - TypeInner::Array { - size: crate::ArraySize::Constant(const_handle), - base, - .. - } => { - write!(self.out, "{{")?; - let count = module.constants[const_handle].to_array_length().unwrap(); - for i in 0..count { - if i != 0 { - write!(self.out, ",")?; - } - self.write_default_init(module, base)?; - } - write!(self.out, "}}")?; - } - _ => { - write!(self.out, "(")?; - self.write_type(module, ty)?; - write!(self.out, ")0")?; - } + write!(self.out, "(")?; + self.write_type(module, ty)?; + if let TypeInner::Array { base, size, .. } = module.types[ty].inner { + self.write_array_size(module, base, size)?; } + write!(self.out, ")0")?; Ok(()) } diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 35a96e118..632692ad9 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -253,7 +253,7 @@ ret_Constructarray5_int_ Constructarray5_int_(int arg0, int arg1, int arg2, int float4 foo_vert(uint vi : SV_VertexID) : SV_Position { float foo = (float)0; - int c2_[5] = {(int)0,(int)0,(int)0,(int)0,(int)0}; + int c2_[5] = (int[5])0; foo = 0.0; float baz_1 = foo; From 85e3b0844f4b422d9029253c1a66877bbcf57dd5 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Jan 2023 13:40:47 +0100 Subject: [PATCH 1906/2212] add `type_flags` to `ModuleInfo` --- src/valid/mod.rs | 20 ++++-- src/valid/type.rs | 2 + tests/out/analysis/collatz.info.ron | 14 +++++ tests/out/analysis/shadow.info.ron | 95 +++++++++++++++++++++++++++++ 4 files changed, 126 insertions(+), 5 deletions(-) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 25fdf20cc..033d96781 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -124,10 +124,18 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct ModuleInfo { + type_flags: Vec, functions: Vec, entry_points: Vec, } +impl ops::Index> for ModuleInfo { + type Output = TypeFlags; + fn index(&self, handle: Handle) -> &Self::Output { + &self.type_flags[handle.index()] + } +} + impl ops::Index> for ModuleInfo { type Output = FunctionInfo; fn index(&self, handle: Handle) -> &Self::Output { @@ -346,6 +354,12 @@ impl Validator { } } + let mut mod_info = ModuleInfo { + type_flags: Vec::with_capacity(module.types.len()), + functions: Vec::with_capacity(module.functions.len()), + entry_points: Vec::with_capacity(module.entry_points.len()), + }; + for (handle, ty) in module.types.iter() { let ty_info = self .validate_type(handle, &module.types, &module.constants) @@ -357,6 +371,7 @@ impl Validator { } .with_span_handle(handle, &module.types) })?; + mod_info.type_flags.push(ty_info.flags); self.types[handle.index()] = ty_info; } @@ -373,11 +388,6 @@ impl Validator { })?; } - let mut mod_info = ModuleInfo { - functions: Vec::with_capacity(module.functions.len()), - entry_points: Vec::with_capacity(module.entry_points.len()), - }; - for (handle, fun) in module.functions.iter() { match self.validate_function(fun, module, &mod_info, false) { Ok(info) => mod_info.functions.push(info), diff --git a/src/valid/type.rs b/src/valid/type.rs index 083501c67..aee6d0f3e 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -9,6 +9,8 @@ bitflags::bitflags! { /// /// [`Type`]: crate::Type /// [`Validator`]: crate::valid::Validator + #[cfg_attr(feature = "serialize", derive(serde::Serialize))] + #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[repr(transparent)] pub struct TypeFlags: u8 { /// Can be used for data variables. diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index f33439444..3896cd943 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -1,4 +1,18 @@ ( + type_flags: [ + ( + bits: 223, + ), + ( + bits: 21, + ), + ( + bits: 21, + ), + ( + bits: 223, + ), + ], functions: [ ( flags: ( diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 01a3c9655..54731d00e 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -1,4 +1,99 @@ ( + type_flags: [ + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 199, + ), + ( + bits: 223, + ), + ( + bits: 64, + ), + ( + bits: 64, + ), + ( + bits: 223, + ), + ( + bits: 70, + ), + ( + bits: 70, + ), + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 6, + ), + ( + bits: 6, + ), + ( + bits: 6, + ), + ( + bits: 215, + ), + ( + bits: 215, + ), + ( + bits: 21, + ), + ( + bits: 21, + ), + ( + bits: 6, + ), + ( + bits: 6, + ), + ( + bits: 6, + ), + ( + bits: 6, + ), + ( + bits: 70, + ), + ( + bits: 70, + ), + ( + bits: 6, + ), + ( + bits: 6, + ), + ( + bits: 70, + ), + ( + bits: 64, + ), + ( + bits: 64, + ), + ], functions: [ ( flags: ( From 3ace8b81cbea6be140a8b113bc9c9579edea2481 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 24 Jan 2023 11:48:10 +0100 Subject: [PATCH 1907/2212] fix array being flagged as constructible when its base isn't --- src/valid/type.rs | 14 +- tests/in/access.wgsl | 1 + tests/out/analysis/access.info.ron | 5682 ++++++++++++++++++ tests/out/glsl/access.atomics.Compute.glsl | 1 + tests/out/glsl/access.foo_frag.Fragment.glsl | 3 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 3 +- tests/out/hlsl/access.hlsl | 10 +- tests/out/ir/access.ron | 2744 +++++++++ tests/out/msl/access.msl | 62 +- tests/out/spv/access.spvasm | 865 +-- tests/out/wgsl/access.wgsl | 1 + tests/snapshots.rs | 8 +- 12 files changed, 8922 insertions(+), 472 deletions(-) create mode 100644 tests/out/analysis/access.info.ron create mode 100644 tests/out/ir/access.ron diff --git a/src/valid/type.rs b/src/valid/type.rs index aee6d0f3e..4fcc1a1c5 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -408,7 +408,7 @@ impl super::Validator { Err(e) => Err(e), }; - let sized_flag = match size { + let type_info_mask = match size { crate::ArraySize::Constant(const_handle) => { let constant = &constants[const_handle]; let length_is_positive = match *constant { @@ -455,19 +455,23 @@ impl super::Validator { return Err(TypeError::NonPositiveArrayLength(const_handle)); } - TypeFlags::SIZED | TypeFlags::ARGUMENT | TypeFlags::CONSTRUCTIBLE + TypeFlags::DATA + | TypeFlags::SIZED + | TypeFlags::COPY + | TypeFlags::HOST_SHAREABLE + | TypeFlags::ARGUMENT + | TypeFlags::CONSTRUCTIBLE } crate::ArraySize::Dynamic => { // Non-SIZED types may only appear as the last element of a structure. // This is enforced by checks for SIZED-ness for all compound types, // and a special case for structs. - TypeFlags::empty() + TypeFlags::DATA | TypeFlags::COPY | TypeFlags::HOST_SHAREABLE } }; - let base_mask = TypeFlags::COPY | TypeFlags::HOST_SHAREABLE; TypeInfo { - flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag, + flags: base_info.flags & type_info_mask, uniform_layout, storage_layout, } diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 798de528d..473f54213 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -16,6 +16,7 @@ struct Bar { _matrix: mat4x3, matrix_array: array, 2>, atom: atomic, + atom_arr: array, 10>, arr: array, 2>, data: array, } diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron new file mode 100644 index 000000000..75f53126b --- /dev/null +++ b/tests/out/analysis/access.info.ron @@ -0,0 +1,5682 @@ +( + type_flags: [ + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 215, + ), + ( + bits: 215, + ), + ( + bits: 215, + ), + ( + bits: 19, + ), + ( + bits: 19, + ), + ( + bits: 223, + ), + ( + bits: 215, + ), + ( + bits: 21, + ), + ( + bits: 17, + ), + ( + bits: 215, + ), + ( + bits: 215, + ), + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 215, + ), + ( + bits: 215, + ), + ( + bits: 215, + ), + ( + bits: 223, + ), + ( + bits: 70, + ), + ( + bits: 215, + ), + ( + bits: 215, + ), + ( + bits: 223, + ), + ( + bits: 6, + ), + ( + bits: 215, + ), + ( + bits: 223, + ), + ( + bits: 223, + ), + ( + bits: 70, + ), + ], + functions: [ + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 1, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 15, + assignable_global: None, + ty: Value(Pointer( + base: 3, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 16, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 15, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Handle(15), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 16, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 15, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 16, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 15, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 16, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 15, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 16, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 15, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 16, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 15, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 16, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(Pointer( + base: 15, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(3), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(15), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(16), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 8, + assignable_global: None, + ty: Value(Pointer( + base: 16, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 15, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(15), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 15, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 15, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 15, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 15, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 15, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 15, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(55), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ], + sampling: [], + ), + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 1, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 15, + assignable_global: None, + ty: Value(Pointer( + base: 3, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 21, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 20, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Handle(20), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 21, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 20, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 19, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Handle(19), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 21, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 20, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 19, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 21, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 20, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 19, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 21, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 20, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 19, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 21, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 20, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 19, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 21, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 20, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 19, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 21, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 20, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 19, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(20), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(21), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 9, + assignable_global: None, + ty: Value(Pointer( + base: 21, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 20, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(20), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 20, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 19, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(19), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 20, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 19, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 20, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 19, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 20, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 19, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 20, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 19, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 20, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 19, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 20, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 19, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: Some(Bi), + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(66), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ], + sampling: [], + ), + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(23), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(22), + ), + ], + sampling: [], + ), + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(25), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(24), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(22), + ), + ], + sampling: [], + ), + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(31), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), + ), + ], + sampling: [], + ), + ], + entry_points: [ + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 5, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 1, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 2, + assignable_global: None, + ty: Handle(1), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(3), + requirements: ( + bits: 0, + ), + ), + ref_count: 4, + assignable_global: None, + ty: Value(Pointer( + base: 22, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(3), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Handle(22), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(6), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(6), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 6, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(6), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(6), + ), + ( + uniformity: ( + non_uniform_result: Some(9), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(9), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 12, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(9), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Handle(12), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(13), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(13), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 6, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(13), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(ValuePointer( + size: Some(Tri), + kind: Float, + width: 4, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(13), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(13), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(18), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(18), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 13, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(20), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(20), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 13, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(20), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(20), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(18), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 5, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(18), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 3, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(18), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(28), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(4), + ty: Value(Pointer( + base: 17, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(28), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Handle(17), + ), + ( + uniformity: ( + non_uniform_result: Some(30), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(30), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 13, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(30), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 5, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(30), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: Some(2), + ty: Value(Pointer( + base: 3, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Handle(22), + ), + ( + uniformity: ( + non_uniform_result: Some(13), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(18), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(28), + ), + ( + uniformity: ( + non_uniform_result: Some(41), + requirements: ( + bits: 0, + ), + ), + ref_count: 3, + assignable_global: None, + ty: Value(Pointer( + base: 28, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(1), + ), + ( + uniformity: ( + non_uniform_result: Some(41), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 3, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(41), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 3, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(41), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(25), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Handle(22), + ), + ( + uniformity: ( + non_uniform_result: Some(41), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Quad, + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(41), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Quad, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(6), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Tri, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(6), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(26), + ), + ], + sampling: [], + ), + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 2, + ), + ( + bits: 0, + ), + ( + bits: 2, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 6, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(ValuePointer( + size: Some(Tri), + kind: Float, + width: 4, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(ValuePointer( + size: None, + kind: Float, + width: 4, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(7), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(7), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 6, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Tri, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Tri, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Tri, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Tri, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(6), + ), + ( + uniformity: ( + non_uniform_result: Some(18), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(18), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 12, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(12), + ), + ( + uniformity: ( + non_uniform_result: Some(25), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(25), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 13, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 0, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(25), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 5, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(25), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 3, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(31), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(4), + ty: Value(Pointer( + base: 17, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(17), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Quad, + kind: Float, + width: 4, + )), + ), + ], + sampling: [], + ), + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 3, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 8, + assignable_global: None, + ty: Value(Pointer( + base: 3, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(5), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(5), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(8), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(9), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(9), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(12), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(13), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(13), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(16), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(17), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(17), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(20), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(21), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(21), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(24), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(25), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(25), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(28), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(29), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(29), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(32), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(33), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(33), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Sint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(36), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(37), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 14, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ( + uniformity: ( + non_uniform_result: Some(37), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(2), + ty: Value(Pointer( + base: 9, + space: Storage( + access: ( + bits: 3, + ), + ), + )), + ), + ], + sampling: [], + ), + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 1, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: Some(6), + ty: Value(Pointer( + base: 1, + space: WorkGroup, + )), + ), + ], + sampling: [], + ), + ], +) \ No newline at end of file diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index f5448b842..ab164cf6f 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -23,6 +23,7 @@ layout(std430) buffer Bar_block_0Compute { mat4x3 _matrix; mat2x2 matrix_array[2]; int atom; + int atom_arr[10]; uvec2 arr[2]; AlignedWrapper data[]; } _group_0_binding_0_cs; diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index 2e52a4698..e7656b8c1 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -21,11 +21,12 @@ layout(std430) buffer Bar_block_0Fragment { mat4x3 _matrix; mat2x2 matrix_array[2]; int atom; + int atom_arr[10]; uvec2 arr[2]; AlignedWrapper data[]; } _group_0_binding_0_fs; -layout(std430) buffer type_11_block_1Fragment { ivec2 _group_0_binding_2_fs; }; +layout(std430) buffer type_12_block_1Fragment { ivec2 _group_0_binding_2_fs; }; layout(location = 0) out vec4 _fs2p_location0; diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index 866d6f64b..331b7cda9 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -21,13 +21,14 @@ layout(std430) buffer Bar_block_0Vertex { mat4x3 _matrix; mat2x2 matrix_array[2]; int atom; + int atom_arr[10]; uvec2 arr[2]; AlignedWrapper data[]; } _group_0_binding_0_vs; uniform Baz_block_1Vertex { Baz _group_0_binding_1_vs; }; -layout(std430) buffer type_11_block_2Vertex { ivec2 _group_0_binding_2_vs; }; +layout(std430) buffer type_12_block_2Vertex { ivec2 _group_0_binding_2_vs; }; uniform MatCx2InArray_block_3Vertex { MatCx2InArray _group_0_binding_3_vs; }; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 632692ad9..68ba8ae28 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -261,9 +261,9 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position test_matrix_within_struct_accesses(); test_matrix_within_array_within_struct_accesses(); float4x3 _matrix = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); - uint2 arr[2] = {asuint(bar.Load2(104+0)), asuint(bar.Load2(104+8))}; + uint2 arr[2] = {asuint(bar.Load2(144+0)), asuint(bar.Load2(144+8))}; float b = asfloat(bar.Load(0+48+0)); - int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 120) / 8) - 2u)*8+120)); + int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 160) / 8) - 2u)*8+160)); int2 c = asint(qux.Load2(0)); const float _e34 = read_from_private(foo); c2_ = Constructarray5_int_(a_1, int(b), 3, 4, 5); @@ -291,10 +291,10 @@ float4 foo_frag() : SV_Target0 } { uint2 _value2[2] = Constructarray2_uint2_((0u).xx, (1u).xx); - bar.Store2(104+0, asuint(_value2[0])); - bar.Store2(104+8, asuint(_value2[1])); + bar.Store2(144+0, asuint(_value2[0])); + bar.Store2(144+8, asuint(_value2[1])); } - bar.Store(0+8+120, asuint(1)); + bar.Store(0+8+160, asuint(1)); qux.Store2(0, asuint(int2(0, 0))); return (0.0).xxxx; } diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron new file mode 100644 index 000000000..d3be85b41 --- /dev/null +++ b/tests/out/ir/access.ron @@ -0,0 +1,2744 @@ +( + types: [ + ( + name: None, + inner: Scalar( + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Tri, + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Scalar( + kind: Sint, + width: 4, + ), + ), + ( + name: Some("GlobalConst"), + inner: Struct( + members: [ + ( + name: Some("a"), + ty: 1, + binding: None, + offset: 0, + ), + ( + name: Some("b"), + ty: 2, + binding: None, + offset: 16, + ), + ( + name: Some("c"), + ty: 3, + binding: None, + offset: 28, + ), + ], + span: 32, + ), + ), + ( + name: Some("AlignedWrapper"), + inner: Struct( + members: [ + ( + name: Some("value"), + ty: 3, + binding: None, + offset: 0, + ), + ], + span: 8, + ), + ), + ( + name: None, + inner: Matrix( + columns: Quad, + rows: Tri, + width: 4, + ), + ), + ( + name: None, + inner: Matrix( + columns: Bi, + rows: Bi, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 7, + size: Constant(5), + stride: 16, + ), + ), + ( + name: None, + inner: Atomic( + kind: Sint, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 9, + size: Constant(6), + stride: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Bi, + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 11, + size: Constant(5), + stride: 8, + ), + ), + ( + name: None, + inner: Array( + base: 5, + size: Dynamic, + stride: 8, + ), + ), + ( + name: Some("Bar"), + inner: Struct( + members: [ + ( + name: Some("_matrix"), + ty: 6, + binding: None, + offset: 0, + ), + ( + name: Some("matrix_array"), + ty: 8, + binding: None, + offset: 64, + ), + ( + name: Some("atom"), + ty: 9, + binding: None, + offset: 96, + ), + ( + name: Some("atom_arr"), + ty: 10, + binding: None, + offset: 100, + ), + ( + name: Some("arr"), + ty: 12, + binding: None, + offset: 144, + ), + ( + name: Some("data"), + ty: 13, + binding: None, + offset: 160, + ), + ], + span: 176, + ), + ), + ( + name: None, + inner: Matrix( + columns: Tri, + rows: Bi, + width: 4, + ), + ), + ( + name: Some("Baz"), + inner: Struct( + members: [ + ( + name: Some("m"), + ty: 15, + binding: None, + offset: 0, + ), + ], + span: 24, + ), + ), + ( + name: None, + inner: Vector( + size: Bi, + kind: Sint, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Bi, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Matrix( + columns: Quad, + rows: Bi, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 19, + size: Constant(5), + stride: 32, + ), + ), + ( + name: Some("MatCx2InArray"), + inner: Struct( + members: [ + ( + name: Some("am"), + ty: 20, + binding: None, + offset: 0, + ), + ], + span: 64, + ), + ), + ( + name: None, + inner: Scalar( + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Pointer( + base: 22, + space: Function, + ), + ), + ( + name: None, + inner: Array( + base: 22, + size: Constant(6), + stride: 4, + ), + ), + ( + name: None, + inner: Array( + base: 24, + size: Constant(26), + stride: 40, + ), + ), + ( + name: None, + inner: Vector( + size: Quad, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Pointer( + base: 3, + space: Storage( + access: ( + bits: 3, + ), + ), + ), + ), + ( + name: None, + inner: Array( + base: 3, + size: Constant(26), + stride: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Quad, + kind: Sint, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Tri, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + space: WorkGroup, + ), + ), + ], + constants: [ + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Composite( + ty: 2, + components: [ + 1, + 1, + 1, + ], + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(0), + ), + ), + ( + name: None, + specialization: None, + inner: Composite( + ty: 4, + components: [ + 1, + 2, + 3, + ], + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(10), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(1.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(2.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(3.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(6.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(5.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(4.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(9.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(90.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(10.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(20.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(30.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(40.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(0.0), + ), + ), + ( + name: None, + specialization: None, + inner: Composite( + ty: 18, + components: [ + 20, + 20, + ], + ), + ), + ( + name: None, + specialization: None, + inner: Composite( + ty: 19, + components: [ + 21, + 21, + 21, + 21, + ], + ), + ), + ( + name: None, + specialization: None, + inner: Composite( + ty: 20, + components: [ + 22, + 22, + ], + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(8.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(7.0), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(5), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(4), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(9), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(3), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(2), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(3), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(1), + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Sint(42), + ), + ), + ( + name: None, + specialization: None, + inner: Composite( + ty: 24, + components: [ + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + ], + ), + ), + ( + name: None, + specialization: None, + inner: Composite( + ty: 25, + components: [ + 34, + 34, + 34, + 34, + 34, + ], + ), + ), + ( + name: None, + specialization: None, + inner: Composite( + ty: 17, + components: [ + 3, + 3, + ], + ), + ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Uint(42), + ), + ), + ], + global_variables: [ + ( + name: Some("global_const"), + space: Private, + binding: None, + ty: 4, + init: Some(4), + ), + ( + name: Some("bar"), + space: Storage( + access: ( + bits: 3, + ), + ), + binding: Some(( + group: 0, + binding: 0, + )), + ty: 14, + init: None, + ), + ( + name: Some("baz"), + space: Uniform, + binding: Some(( + group: 0, + binding: 1, + )), + ty: 16, + init: None, + ), + ( + name: Some("qux"), + space: Storage( + access: ( + bits: 3, + ), + ), + binding: Some(( + group: 0, + binding: 2, + )), + ty: 17, + init: None, + ), + ( + name: Some("nested_mat_cx2"), + space: Uniform, + binding: Some(( + group: 0, + binding: 3, + )), + ty: 21, + init: None, + ), + ( + name: Some("val"), + space: WorkGroup, + binding: None, + ty: 1, + init: None, + ), + ], + functions: [ + ( + name: Some("test_matrix_within_struct_accesses"), + arguments: [], + result: None, + local_variables: [ + ( + name: Some("idx"), + ty: 3, + init: None, + ), + ( + name: Some("t"), + ty: 16, + init: None, + ), + ], + expressions: [ + Constant(7), + LocalVariable(1), + Load( + pointer: 2, + ), + Constant(7), + Binary( + op: Subtract, + left: 3, + right: 4, + ), + GlobalVariable(3), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 7, + ), + GlobalVariable(3), + AccessIndex( + base: 9, + index: 0, + ), + Constant(3), + AccessIndex( + base: 10, + index: 0, + ), + Load( + pointer: 12, + ), + GlobalVariable(3), + AccessIndex( + base: 14, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 15, + index: 16, + ), + Load( + pointer: 17, + ), + GlobalVariable(3), + AccessIndex( + base: 19, + index: 0, + ), + Constant(3), + AccessIndex( + base: 20, + index: 0, + ), + Constant(7), + AccessIndex( + base: 22, + index: 1, + ), + Load( + pointer: 24, + ), + GlobalVariable(3), + AccessIndex( + base: 26, + index: 0, + ), + Constant(3), + AccessIndex( + base: 27, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 29, + index: 30, + ), + Load( + pointer: 31, + ), + GlobalVariable(3), + AccessIndex( + base: 33, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 34, + index: 35, + ), + Constant(7), + AccessIndex( + base: 36, + index: 1, + ), + Load( + pointer: 38, + ), + GlobalVariable(3), + AccessIndex( + base: 40, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 41, + index: 42, + ), + Load( + pointer: 2, + ), + Access( + base: 43, + index: 44, + ), + Load( + pointer: 45, + ), + Constant(8), + Splat( + size: Bi, + value: 47, + ), + Constant(9), + Splat( + size: Bi, + value: 49, + ), + Constant(10), + Splat( + size: Bi, + value: 51, + ), + Compose( + ty: 15, + components: [ + 48, + 50, + 52, + ], + ), + Compose( + ty: 16, + components: [ + 53, + ], + ), + LocalVariable(2), + Load( + pointer: 2, + ), + Constant(7), + Binary( + op: Add, + left: 56, + right: 57, + ), + AccessIndex( + base: 55, + index: 0, + ), + Constant(11), + Splat( + size: Bi, + value: 60, + ), + Constant(12), + Splat( + size: Bi, + value: 62, + ), + Constant(13), + Splat( + size: Bi, + value: 64, + ), + Compose( + ty: 15, + components: [ + 61, + 63, + 65, + ], + ), + AccessIndex( + base: 55, + index: 0, + ), + Constant(3), + AccessIndex( + base: 67, + index: 0, + ), + Constant(14), + Splat( + size: Bi, + value: 70, + ), + AccessIndex( + base: 55, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 72, + index: 73, + ), + Constant(15), + Splat( + size: Bi, + value: 75, + ), + AccessIndex( + base: 55, + index: 0, + ), + Constant(3), + AccessIndex( + base: 77, + index: 0, + ), + Constant(7), + AccessIndex( + base: 79, + index: 1, + ), + Constant(16), + AccessIndex( + base: 55, + index: 0, + ), + Constant(3), + AccessIndex( + base: 83, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 85, + index: 86, + ), + Constant(17), + AccessIndex( + base: 55, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 89, + index: 90, + ), + Constant(7), + AccessIndex( + base: 91, + index: 1, + ), + Constant(18), + AccessIndex( + base: 55, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 95, + index: 96, + ), + Load( + pointer: 2, + ), + Access( + base: 97, + index: 98, + ), + Constant(19), + ], + named_expressions: {}, + body: [ + Store( + pointer: 2, + value: 1, + ), + Emit(( + start: 2, + end: 3, + )), + Emit(( + start: 4, + end: 5, + )), + Store( + pointer: 2, + value: 5, + ), + Emit(( + start: 6, + end: 8, + )), + Emit(( + start: 9, + end: 10, + )), + Emit(( + start: 11, + end: 13, + )), + Emit(( + start: 14, + end: 18, + )), + Emit(( + start: 19, + end: 20, + )), + Emit(( + start: 21, + end: 22, + )), + Emit(( + start: 23, + end: 25, + )), + Emit(( + start: 26, + end: 27, + )), + Emit(( + start: 28, + end: 32, + )), + Emit(( + start: 33, + end: 36, + )), + Emit(( + start: 37, + end: 39, + )), + Emit(( + start: 40, + end: 46, + )), + Emit(( + start: 47, + end: 48, + )), + Emit(( + start: 49, + end: 50, + )), + Emit(( + start: 51, + end: 54, + )), + Store( + pointer: 55, + value: 54, + ), + Emit(( + start: 55, + end: 56, + )), + Emit(( + start: 57, + end: 58, + )), + Store( + pointer: 2, + value: 58, + ), + Emit(( + start: 58, + end: 59, + )), + Emit(( + start: 60, + end: 61, + )), + Emit(( + start: 62, + end: 63, + )), + Emit(( + start: 64, + end: 66, + )), + Store( + pointer: 59, + value: 66, + ), + Emit(( + start: 66, + end: 67, + )), + Emit(( + start: 68, + end: 69, + )), + Emit(( + start: 70, + end: 71, + )), + Store( + pointer: 69, + value: 71, + ), + Emit(( + start: 71, + end: 74, + )), + Emit(( + start: 75, + end: 76, + )), + Store( + pointer: 74, + value: 76, + ), + Emit(( + start: 76, + end: 77, + )), + Emit(( + start: 78, + end: 79, + )), + Emit(( + start: 80, + end: 81, + )), + Store( + pointer: 81, + value: 82, + ), + Emit(( + start: 82, + end: 83, + )), + Emit(( + start: 84, + end: 87, + )), + Store( + pointer: 87, + value: 88, + ), + Emit(( + start: 88, + end: 91, + )), + Emit(( + start: 92, + end: 93, + )), + Store( + pointer: 93, + value: 94, + ), + Emit(( + start: 94, + end: 99, + )), + Store( + pointer: 99, + value: 100, + ), + Return( + value: None, + ), + ], + ), + ( + name: Some("test_matrix_within_array_within_struct_accesses"), + arguments: [], + result: None, + local_variables: [ + ( + name: Some("idx"), + ty: 3, + init: None, + ), + ( + name: Some("t"), + ty: 21, + init: None, + ), + ], + expressions: [ + Constant(7), + LocalVariable(1), + Load( + pointer: 2, + ), + Constant(7), + Binary( + op: Subtract, + left: 3, + right: 4, + ), + GlobalVariable(5), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 7, + ), + GlobalVariable(5), + AccessIndex( + base: 9, + index: 0, + ), + Constant(3), + AccessIndex( + base: 10, + index: 0, + ), + Load( + pointer: 12, + ), + GlobalVariable(5), + AccessIndex( + base: 14, + index: 0, + ), + Constant(3), + AccessIndex( + base: 15, + index: 0, + ), + Constant(3), + AccessIndex( + base: 17, + index: 0, + ), + Load( + pointer: 19, + ), + GlobalVariable(5), + AccessIndex( + base: 21, + index: 0, + ), + Constant(3), + AccessIndex( + base: 22, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 24, + index: 25, + ), + Load( + pointer: 26, + ), + GlobalVariable(5), + AccessIndex( + base: 28, + index: 0, + ), + Constant(3), + AccessIndex( + base: 29, + index: 0, + ), + Constant(3), + AccessIndex( + base: 31, + index: 0, + ), + Constant(7), + AccessIndex( + base: 33, + index: 1, + ), + Load( + pointer: 35, + ), + GlobalVariable(5), + AccessIndex( + base: 37, + index: 0, + ), + Constant(3), + AccessIndex( + base: 38, + index: 0, + ), + Constant(3), + AccessIndex( + base: 40, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 42, + index: 43, + ), + Load( + pointer: 44, + ), + GlobalVariable(5), + AccessIndex( + base: 46, + index: 0, + ), + Constant(3), + AccessIndex( + base: 47, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 49, + index: 50, + ), + Constant(7), + AccessIndex( + base: 51, + index: 1, + ), + Load( + pointer: 53, + ), + GlobalVariable(5), + AccessIndex( + base: 55, + index: 0, + ), + Constant(3), + AccessIndex( + base: 56, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 58, + index: 59, + ), + Load( + pointer: 2, + ), + Access( + base: 60, + index: 61, + ), + Load( + pointer: 62, + ), + Constant(23), + Compose( + ty: 21, + components: [ + 64, + ], + ), + LocalVariable(2), + Load( + pointer: 2, + ), + Constant(7), + Binary( + op: Add, + left: 67, + right: 68, + ), + AccessIndex( + base: 66, + index: 0, + ), + Constant(23), + AccessIndex( + base: 66, + index: 0, + ), + Constant(3), + AccessIndex( + base: 72, + index: 0, + ), + Constant(24), + Splat( + size: Bi, + value: 75, + ), + Constant(25), + Splat( + size: Bi, + value: 77, + ), + Constant(11), + Splat( + size: Bi, + value: 79, + ), + Constant(12), + Splat( + size: Bi, + value: 81, + ), + Compose( + ty: 19, + components: [ + 76, + 78, + 80, + 82, + ], + ), + AccessIndex( + base: 66, + index: 0, + ), + Constant(3), + AccessIndex( + base: 84, + index: 0, + ), + Constant(3), + AccessIndex( + base: 86, + index: 0, + ), + Constant(14), + Splat( + size: Bi, + value: 89, + ), + AccessIndex( + base: 66, + index: 0, + ), + Constant(3), + AccessIndex( + base: 91, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 93, + index: 94, + ), + Constant(15), + Splat( + size: Bi, + value: 96, + ), + AccessIndex( + base: 66, + index: 0, + ), + Constant(3), + AccessIndex( + base: 98, + index: 0, + ), + Constant(3), + AccessIndex( + base: 100, + index: 0, + ), + Constant(7), + AccessIndex( + base: 102, + index: 1, + ), + Constant(16), + AccessIndex( + base: 66, + index: 0, + ), + Constant(3), + AccessIndex( + base: 106, + index: 0, + ), + Constant(3), + AccessIndex( + base: 108, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 110, + index: 111, + ), + Constant(17), + AccessIndex( + base: 66, + index: 0, + ), + Constant(3), + AccessIndex( + base: 114, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 116, + index: 117, + ), + Constant(7), + AccessIndex( + base: 118, + index: 1, + ), + Constant(18), + AccessIndex( + base: 66, + index: 0, + ), + Constant(3), + AccessIndex( + base: 122, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 124, + index: 125, + ), + Load( + pointer: 2, + ), + Access( + base: 126, + index: 127, + ), + Constant(19), + ], + named_expressions: {}, + body: [ + Store( + pointer: 2, + value: 1, + ), + Emit(( + start: 2, + end: 3, + )), + Emit(( + start: 4, + end: 5, + )), + Store( + pointer: 2, + value: 5, + ), + Emit(( + start: 6, + end: 8, + )), + Emit(( + start: 9, + end: 10, + )), + Emit(( + start: 11, + end: 13, + )), + Emit(( + start: 14, + end: 15, + )), + Emit(( + start: 16, + end: 17, + )), + Emit(( + start: 18, + end: 20, + )), + Emit(( + start: 21, + end: 22, + )), + Emit(( + start: 23, + end: 27, + )), + Emit(( + start: 28, + end: 29, + )), + Emit(( + start: 30, + end: 31, + )), + Emit(( + start: 32, + end: 33, + )), + Emit(( + start: 34, + end: 36, + )), + Emit(( + start: 37, + end: 38, + )), + Emit(( + start: 39, + end: 40, + )), + Emit(( + start: 41, + end: 45, + )), + Emit(( + start: 46, + end: 47, + )), + Emit(( + start: 48, + end: 51, + )), + Emit(( + start: 52, + end: 54, + )), + Emit(( + start: 55, + end: 56, + )), + Emit(( + start: 57, + end: 63, + )), + Emit(( + start: 64, + end: 65, + )), + Store( + pointer: 66, + value: 65, + ), + Emit(( + start: 66, + end: 67, + )), + Emit(( + start: 68, + end: 69, + )), + Store( + pointer: 2, + value: 69, + ), + Emit(( + start: 69, + end: 70, + )), + Store( + pointer: 70, + value: 71, + ), + Emit(( + start: 71, + end: 72, + )), + Emit(( + start: 73, + end: 74, + )), + Emit(( + start: 75, + end: 76, + )), + Emit(( + start: 77, + end: 78, + )), + Emit(( + start: 79, + end: 80, + )), + Emit(( + start: 81, + end: 83, + )), + Store( + pointer: 74, + value: 83, + ), + Emit(( + start: 83, + end: 84, + )), + Emit(( + start: 85, + end: 86, + )), + Emit(( + start: 87, + end: 88, + )), + Emit(( + start: 89, + end: 90, + )), + Store( + pointer: 88, + value: 90, + ), + Emit(( + start: 90, + end: 91, + )), + Emit(( + start: 92, + end: 95, + )), + Emit(( + start: 96, + end: 97, + )), + Store( + pointer: 95, + value: 97, + ), + Emit(( + start: 97, + end: 98, + )), + Emit(( + start: 99, + end: 100, + )), + Emit(( + start: 101, + end: 102, + )), + Emit(( + start: 103, + end: 104, + )), + Store( + pointer: 104, + value: 105, + ), + Emit(( + start: 105, + end: 106, + )), + Emit(( + start: 107, + end: 108, + )), + Emit(( + start: 109, + end: 112, + )), + Store( + pointer: 112, + value: 113, + ), + Emit(( + start: 113, + end: 114, + )), + Emit(( + start: 115, + end: 118, + )), + Emit(( + start: 119, + end: 120, + )), + Store( + pointer: 120, + value: 121, + ), + Emit(( + start: 121, + end: 122, + )), + Emit(( + start: 123, + end: 128, + )), + Store( + pointer: 128, + value: 129, + ), + Return( + value: None, + ), + ], + ), + ( + name: Some("read_from_private"), + arguments: [ + ( + name: Some("foo"), + ty: 23, + binding: None, + ), + ], + result: Some(( + ty: 22, + binding: None, + )), + local_variables: [], + expressions: [ + FunctionArgument(0), + Load( + pointer: 1, + ), + ], + named_expressions: { + 1: "foo", + }, + body: [ + Emit(( + start: 1, + end: 2, + )), + Return( + value: Some(2), + ), + ], + ), + ( + name: Some("test_arr_as_arg"), + arguments: [ + ( + name: Some("a"), + ty: 25, + binding: None, + ), + ], + result: Some(( + ty: 22, + binding: None, + )), + local_variables: [], + expressions: [ + FunctionArgument(0), + Constant(27), + AccessIndex( + base: 1, + index: 4, + ), + Constant(28), + AccessIndex( + base: 3, + index: 9, + ), + ], + named_expressions: { + 1: "a", + }, + body: [ + Emit(( + start: 2, + end: 3, + )), + Emit(( + start: 4, + end: 5, + )), + Return( + value: Some(5), + ), + ], + ), + ( + name: Some("assign_through_ptr_fn"), + arguments: [ + ( + name: Some("p"), + ty: 31, + binding: None, + ), + ], + result: None, + local_variables: [], + expressions: [ + FunctionArgument(0), + Constant(37), + ], + named_expressions: { + 1: "p", + }, + body: [ + Store( + pointer: 1, + value: 2, + ), + Return( + value: None, + ), + ], + ), + ], + entry_points: [ + ( + name: "foo_vert", + stage: Vertex, + early_depth_test: None, + workgroup_size: (0, 0, 0), + function: ( + name: Some("foo_vert"), + arguments: [ + ( + name: Some("vi"), + ty: 1, + binding: Some(BuiltIn(VertexIndex)), + ), + ], + result: Some(( + ty: 26, + binding: Some(BuiltIn(Position( + invariant: false, + ))), + )), + local_variables: [ + ( + name: Some("foo"), + ty: 22, + init: None, + ), + ( + name: Some("c2"), + ty: 28, + init: None, + ), + ], + expressions: [ + FunctionArgument(0), + Constant(20), + LocalVariable(1), + Load( + pointer: 3, + ), + Constant(8), + GlobalVariable(2), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 7, + ), + GlobalVariable(2), + AccessIndex( + base: 9, + index: 4, + ), + Load( + pointer: 10, + ), + Constant(29), + GlobalVariable(2), + AccessIndex( + base: 13, + index: 0, + ), + AccessIndex( + base: 14, + index: 3, + ), + AccessIndex( + base: 15, + index: 0, + ), + Load( + pointer: 16, + ), + GlobalVariable(2), + AccessIndex( + base: 18, + index: 5, + ), + GlobalVariable(2), + AccessIndex( + base: 20, + index: 5, + ), + ArrayLength(21), + Constant(30), + Binary( + op: Subtract, + left: 22, + right: 23, + ), + Access( + base: 19, + index: 24, + ), + AccessIndex( + base: 25, + index: 0, + ), + Load( + pointer: 26, + ), + GlobalVariable(4), + Load( + pointer: 28, + ), + GlobalVariable(2), + AccessIndex( + base: 30, + index: 5, + ), + Constant(3), + AccessIndex( + base: 31, + index: 0, + ), + AccessIndex( + base: 33, + index: 0, + ), + CallResult(3), + As( + expr: 17, + kind: Sint, + convert: Some(4), + ), + Constant(31), + Constant(27), + Constant(26), + Compose( + ty: 28, + components: [ + 27, + 36, + 37, + 38, + 39, + ], + ), + LocalVariable(2), + Constant(32), + Binary( + op: Add, + left: 1, + right: 42, + ), + Access( + base: 41, + index: 43, + ), + Constant(33), + Access( + base: 41, + index: 1, + ), + Load( + pointer: 46, + ), + Constant(35), + CallResult(4), + Splat( + size: Quad, + value: 47, + ), + As( + expr: 50, + kind: Float, + convert: Some(4), + ), + Binary( + op: Multiply, + left: 8, + right: 51, + ), + Constant(9), + Compose( + ty: 26, + components: [ + 52, + 53, + ], + ), + ], + named_expressions: { + 29: "c", + 4: "baz", + 17: "b", + 1: "vi", + 27: "a", + 8: "_matrix", + 11: "arr", + 34: "data_pointer", + 47: "value", + 12: "index", + 35: "foo_value", + }, + body: [ + Store( + pointer: 3, + value: 2, + ), + Emit(( + start: 3, + end: 4, + )), + Store( + pointer: 3, + value: 5, + ), + Call( + function: 1, + arguments: [], + result: None, + ), + Call( + function: 2, + arguments: [], + result: None, + ), + Emit(( + start: 6, + end: 8, + )), + Emit(( + start: 9, + end: 11, + )), + Emit(( + start: 13, + end: 17, + )), + Emit(( + start: 18, + end: 19, + )), + Emit(( + start: 20, + end: 22, + )), + Emit(( + start: 23, + end: 27, + )), + Emit(( + start: 28, + end: 29, + )), + Emit(( + start: 30, + end: 31, + )), + Emit(( + start: 32, + end: 34, + )), + Call( + function: 3, + arguments: [ + 3, + ], + result: Some(35), + ), + Emit(( + start: 35, + end: 36, + )), + Emit(( + start: 39, + end: 40, + )), + Store( + pointer: 41, + value: 40, + ), + Emit(( + start: 42, + end: 44, + )), + Store( + pointer: 44, + value: 45, + ), + Emit(( + start: 45, + end: 47, + )), + Call( + function: 4, + arguments: [ + 48, + ], + result: Some(49), + ), + Emit(( + start: 49, + end: 52, + )), + Emit(( + start: 53, + end: 54, + )), + Return( + value: Some(54), + ), + ], + ), + ), + ( + name: "foo_frag", + stage: Fragment, + early_depth_test: None, + workgroup_size: (0, 0, 0), + function: ( + name: Some("foo_frag"), + arguments: [], + result: Some(( + ty: 26, + binding: Some(Location( + location: 0, + interpolation: Some(Perspective), + sampling: Some(Center), + )), + )), + local_variables: [], + expressions: [ + GlobalVariable(2), + AccessIndex( + base: 1, + index: 0, + ), + Constant(7), + AccessIndex( + base: 2, + index: 1, + ), + AccessIndex( + base: 4, + index: 2, + ), + Constant(8), + GlobalVariable(2), + AccessIndex( + base: 7, + index: 0, + ), + Constant(20), + Splat( + size: Tri, + value: 9, + ), + Constant(8), + Splat( + size: Tri, + value: 11, + ), + Constant(9), + Splat( + size: Tri, + value: 13, + ), + Constant(10), + Splat( + size: Tri, + value: 15, + ), + Compose( + ty: 6, + components: [ + 10, + 12, + 14, + 16, + ], + ), + GlobalVariable(2), + AccessIndex( + base: 18, + index: 4, + ), + Constant(1), + Splat( + size: Bi, + value: 20, + ), + Constant(32), + Splat( + size: Bi, + value: 22, + ), + Compose( + ty: 12, + components: [ + 21, + 23, + ], + ), + GlobalVariable(2), + AccessIndex( + base: 25, + index: 5, + ), + Constant(7), + AccessIndex( + base: 26, + index: 1, + ), + AccessIndex( + base: 28, + index: 0, + ), + Constant(7), + GlobalVariable(4), + Constant(36), + Constant(20), + Splat( + size: Quad, + value: 33, + ), + ], + named_expressions: {}, + body: [ + Emit(( + start: 1, + end: 2, + )), + Emit(( + start: 3, + end: 5, + )), + Store( + pointer: 5, + value: 6, + ), + Emit(( + start: 7, + end: 8, + )), + Emit(( + start: 9, + end: 10, + )), + Emit(( + start: 11, + end: 12, + )), + Emit(( + start: 13, + end: 14, + )), + Emit(( + start: 15, + end: 17, + )), + Store( + pointer: 8, + value: 17, + ), + Emit(( + start: 18, + end: 19, + )), + Emit(( + start: 20, + end: 21, + )), + Emit(( + start: 22, + end: 24, + )), + Store( + pointer: 19, + value: 24, + ), + Emit(( + start: 25, + end: 26, + )), + Emit(( + start: 27, + end: 29, + )), + Store( + pointer: 29, + value: 30, + ), + Store( + pointer: 31, + value: 32, + ), + Emit(( + start: 33, + end: 34, + )), + Return( + value: Some(34), + ), + ], + ), + ), + ( + name: "atomics", + stage: Compute, + early_depth_test: None, + workgroup_size: (1, 1, 1), + function: ( + name: Some("atomics"), + arguments: [], + result: None, + local_variables: [ + ( + name: Some("tmp"), + ty: 3, + init: None, + ), + ], + expressions: [ + LocalVariable(1), + GlobalVariable(2), + AccessIndex( + base: 2, + index: 2, + ), + Load( + pointer: 3, + ), + GlobalVariable(2), + AccessIndex( + base: 5, + index: 2, + ), + Constant(26), + AtomicResult( + ty: 3, + comparison: false, + ), + GlobalVariable(2), + AccessIndex( + base: 9, + index: 2, + ), + Constant(26), + AtomicResult( + ty: 3, + comparison: false, + ), + GlobalVariable(2), + AccessIndex( + base: 13, + index: 2, + ), + Constant(26), + AtomicResult( + ty: 3, + comparison: false, + ), + GlobalVariable(2), + AccessIndex( + base: 17, + index: 2, + ), + Constant(26), + AtomicResult( + ty: 3, + comparison: false, + ), + GlobalVariable(2), + AccessIndex( + base: 21, + index: 2, + ), + Constant(26), + AtomicResult( + ty: 3, + comparison: false, + ), + GlobalVariable(2), + AccessIndex( + base: 25, + index: 2, + ), + Constant(26), + AtomicResult( + ty: 3, + comparison: false, + ), + GlobalVariable(2), + AccessIndex( + base: 29, + index: 2, + ), + Constant(26), + AtomicResult( + ty: 3, + comparison: false, + ), + GlobalVariable(2), + AccessIndex( + base: 33, + index: 2, + ), + Constant(26), + AtomicResult( + ty: 3, + comparison: false, + ), + GlobalVariable(2), + AccessIndex( + base: 37, + index: 2, + ), + ], + named_expressions: { + 4: "value", + }, + body: [ + Emit(( + start: 2, + end: 4, + )), + Emit(( + start: 5, + end: 6, + )), + Atomic( + pointer: 6, + fun: Add, + value: 7, + result: 8, + ), + Store( + pointer: 1, + value: 8, + ), + Emit(( + start: 9, + end: 10, + )), + Atomic( + pointer: 10, + fun: Subtract, + value: 11, + result: 12, + ), + Store( + pointer: 1, + value: 12, + ), + Emit(( + start: 13, + end: 14, + )), + Atomic( + pointer: 14, + fun: And, + value: 15, + result: 16, + ), + Store( + pointer: 1, + value: 16, + ), + Emit(( + start: 17, + end: 18, + )), + Atomic( + pointer: 18, + fun: InclusiveOr, + value: 19, + result: 20, + ), + Store( + pointer: 1, + value: 20, + ), + Emit(( + start: 21, + end: 22, + )), + Atomic( + pointer: 22, + fun: ExclusiveOr, + value: 23, + result: 24, + ), + Store( + pointer: 1, + value: 24, + ), + Emit(( + start: 25, + end: 26, + )), + Atomic( + pointer: 26, + fun: Min, + value: 27, + result: 28, + ), + Store( + pointer: 1, + value: 28, + ), + Emit(( + start: 29, + end: 30, + )), + Atomic( + pointer: 30, + fun: Max, + value: 31, + result: 32, + ), + Store( + pointer: 1, + value: 32, + ), + Emit(( + start: 33, + end: 34, + )), + Atomic( + pointer: 34, + fun: Exchange( + compare: None, + ), + value: 35, + result: 36, + ), + Store( + pointer: 1, + value: 36, + ), + Emit(( + start: 37, + end: 38, + )), + Store( + pointer: 38, + value: 4, + ), + Return( + value: None, + ), + ], + ), + ), + ( + name: "assign_through_ptr", + stage: Compute, + early_depth_test: None, + workgroup_size: (1, 1, 1), + function: ( + name: Some("assign_through_ptr"), + arguments: [], + result: None, + local_variables: [], + expressions: [ + GlobalVariable(6), + ], + named_expressions: {}, + body: [ + Call( + function: 5, + arguments: [ + 1, + ], + result: None, + ), + Return( + value: None, + ), + ], + ), + ), + ], +) \ No newline at end of file diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 245f8a2be..02f922fc8 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -20,44 +20,48 @@ struct AlignedWrapper { struct type_5 { metal::float2x2 inner[2]; }; -struct type_8 { +struct type_7 { + metal::atomic_int inner[10]; +}; +struct type_9 { metal::uint2 inner[2]; }; -typedef AlignedWrapper type_9[1]; +typedef AlignedWrapper type_10[1]; struct Bar { metal::float4x3 _matrix; type_5 matrix_array; metal::atomic_int atom; - char _pad3[4]; - type_8 arr; - type_9 data; + type_7 atom_arr; + char _pad4[4]; + type_9 arr; + type_10 data; }; struct Baz { metal::float3x2 m; }; -struct type_14 { +struct type_15 { metal::float4x2 inner[2]; }; struct MatCx2InArray { - type_14 am; -}; -struct type_17 { - float inner[10]; + type_15 am; }; struct type_18 { - type_17 inner[5]; + float inner[10]; }; -struct type_21 { +struct type_19 { + type_18 inner[5]; +}; +struct type_22 { int inner[5]; }; constant metal::uint3 const_type_1_ = {0u, 0u, 0u}; constant GlobalConst const_GlobalConst = {0u, {}, const_type_1_, 0}; -constant metal::float2 const_type_12_ = {0.0, 0.0}; -constant metal::float4x2 const_type_13_ = {const_type_12_, const_type_12_, const_type_12_, const_type_12_}; -constant type_14 const_type_14_ = {const_type_13_, const_type_13_}; -constant type_17 const_type_17_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; -constant type_18 const_type_18_ = {const_type_17_, const_type_17_, const_type_17_, const_type_17_, const_type_17_}; -constant metal::int2 const_type_11_ = {0, 0}; +constant metal::float2 const_type_13_ = {0.0, 0.0}; +constant metal::float4x2 const_type_14_ = {const_type_13_, const_type_13_, const_type_13_, const_type_13_}; +constant type_15 const_type_15_ = {const_type_14_, const_type_14_}; +constant type_18 const_type_18_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; +constant type_19 const_type_19_ = {const_type_18_, const_type_18_, const_type_18_, const_type_18_, const_type_18_}; +constant metal::int2 const_type_12_ = {0, 0}; void test_matrix_within_struct_accesses( constant Baz& baz @@ -105,7 +109,7 @@ void test_matrix_within_array_within_struct_accesses( idx_1 = 1; int _e2 = idx_1; idx_1 = _e2 - 1; - type_14 unnamed_7 = nested_mat_cx2_.am; + type_15 unnamed_7 = nested_mat_cx2_.am; metal::float4x2 unnamed_8 = nested_mat_cx2_.am.inner[0]; metal::float2 unnamed_9 = nested_mat_cx2_.am.inner[0][0]; int _e24 = idx_1; @@ -118,10 +122,10 @@ void test_matrix_within_array_within_struct_accesses( int _e58 = idx_1; int _e60 = idx_1; float unnamed_14 = nested_mat_cx2_.am.inner[0][_e58][_e60]; - t_1 = MatCx2InArray {const_type_14_}; + t_1 = MatCx2InArray {const_type_15_}; int _e66 = idx_1; idx_1 = _e66 + 1; - for(int _i=0; _i<2; ++_i) t_1.am.inner[_i] = const_type_14_.inner[_i]; + for(int _i=0; _i<2; ++_i) t_1.am.inner[_i] = const_type_15_.inner[_i]; t_1.am.inner[0] = metal::float4x2(metal::float2(8.0), metal::float2(7.0), metal::float2(6.0), metal::float2(5.0)); t_1.am.inner[0][0] = metal::float2(9.0); int _e93 = idx_1; @@ -145,7 +149,7 @@ float read_from_private( } float test_arr_as_arg( - type_18 a + type_19 a ) { return a.inner[4].inner[9]; } @@ -171,22 +175,22 @@ vertex foo_vertOutput foo_vert( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo = {}; - type_21 c2_ = {}; + type_22 c2_ = {}; foo = 0.0; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); test_matrix_within_array_within_struct_accesses(nested_mat_cx2_); metal::float4x3 _matrix = bar._matrix; - type_8 arr = bar.arr; + type_9 arr = bar.arr; float b = bar._matrix[3].x; - int a_1 = bar.data[(1 + (_buffer_sizes.size1 - 120 - 8) / 8) - 2u].value; + int a_1 = bar.data[(1 + (_buffer_sizes.size1 - 160 - 8) / 8) - 2u].value; metal::int2 c = qux; float _e34 = read_from_private(foo); - for(int _i=0; _i<5; ++_i) c2_.inner[_i] = type_21 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; + for(int _i=0; _i<5; ++_i) c2_.inner[_i] = type_22 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; c2_.inner[vi + 1u] = 42; int value = c2_.inner[vi]; - float _e48 = test_arr_as_arg(const_type_18_); + float _e48 = test_arr_as_arg(const_type_19_); return foo_vertOutput { metal::float4(_matrix * static_cast(metal::int4(value)), 2.0) }; } @@ -201,9 +205,9 @@ fragment foo_fragOutput foo_frag( ) { bar._matrix[1].z = 1.0; bar._matrix = metal::float4x3(metal::float3(0.0), metal::float3(1.0), metal::float3(2.0), metal::float3(3.0)); - for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_8 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; + for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_9 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; bar.data[1].value = 1; - qux = const_type_11_; + qux = const_type_12_; return foo_fragOutput { metal::float4(0.0) }; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index bc3cb6a50..49d1eb4a6 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,18 +1,18 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 323 +; Bound: 325 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %236 "foo_vert" %231 %234 -OpEntryPoint Fragment %277 "foo_frag" %276 -OpEntryPoint GLCompute %296 "atomics" -OpEntryPoint GLCompute %320 "assign_through_ptr" -OpExecutionMode %277 OriginUpperLeft -OpExecutionMode %296 LocalSize 1 1 1 -OpExecutionMode %320 LocalSize 1 1 1 +OpEntryPoint Vertex %237 "foo_vert" %232 %235 +OpEntryPoint Fragment %279 "foo_frag" %278 +OpEntryPoint GLCompute %298 "atomics" +OpEntryPoint GLCompute %322 "assign_through_ptr" +OpExecutionMode %279 OriginUpperLeft +OpExecutionMode %298 LocalSize 1 1 1 +OpExecutionMode %322 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %36 0 "a" OpMemberName %36 1 "b" @@ -20,110 +20,113 @@ OpMemberName %36 2 "c" OpName %36 "GlobalConst" OpMemberName %37 0 "value" OpName %37 "AlignedWrapper" -OpMemberName %46 0 "_matrix" -OpMemberName %46 1 "matrix_array" -OpMemberName %46 2 "atom" -OpMemberName %46 3 "arr" -OpMemberName %46 4 "data" -OpName %46 "Bar" -OpMemberName %48 0 "m" -OpName %48 "Baz" -OpMemberName %52 0 "am" -OpName %52 "MatCx2InArray" -OpName %69 "global_const" -OpName %71 "bar" -OpName %73 "baz" -OpName %76 "qux" -OpName %79 "nested_mat_cx2" -OpName %82 "val" -OpName %83 "idx" -OpName %86 "t" -OpName %90 "test_matrix_within_struct_accesses" -OpName %147 "idx" -OpName %149 "t" -OpName %153 "test_matrix_within_array_within_struct_accesses" -OpName %208 "foo" -OpName %209 "read_from_private" -OpName %214 "a" -OpName %215 "test_arr_as_arg" -OpName %221 "p" -OpName %222 "assign_through_ptr_fn" -OpName %225 "foo" -OpName %227 "c2" -OpName %231 "vi" -OpName %236 "foo_vert" -OpName %277 "foo_frag" -OpName %293 "tmp" -OpName %296 "atomics" -OpName %320 "assign_through_ptr" +OpMemberName %47 0 "_matrix" +OpMemberName %47 1 "matrix_array" +OpMemberName %47 2 "atom" +OpMemberName %47 3 "atom_arr" +OpMemberName %47 4 "arr" +OpMemberName %47 5 "data" +OpName %47 "Bar" +OpMemberName %49 0 "m" +OpName %49 "Baz" +OpMemberName %53 0 "am" +OpName %53 "MatCx2InArray" +OpName %70 "global_const" +OpName %72 "bar" +OpName %74 "baz" +OpName %77 "qux" +OpName %80 "nested_mat_cx2" +OpName %83 "val" +OpName %84 "idx" +OpName %87 "t" +OpName %91 "test_matrix_within_struct_accesses" +OpName %148 "idx" +OpName %150 "t" +OpName %154 "test_matrix_within_array_within_struct_accesses" +OpName %209 "foo" +OpName %210 "read_from_private" +OpName %215 "a" +OpName %216 "test_arr_as_arg" +OpName %222 "p" +OpName %223 "assign_through_ptr_fn" +OpName %226 "foo" +OpName %228 "c2" +OpName %232 "vi" +OpName %237 "foo_vert" +OpName %279 "foo_frag" +OpName %295 "tmp" +OpName %298 "atomics" +OpName %322 "assign_through_ptr" OpMemberDecorate %36 0 Offset 0 OpMemberDecorate %36 1 Offset 16 OpMemberDecorate %36 2 Offset 28 OpMemberDecorate %37 0 Offset 0 OpDecorate %42 ArrayStride 16 -OpDecorate %44 ArrayStride 8 +OpDecorate %43 ArrayStride 4 OpDecorate %45 ArrayStride 8 -OpMemberDecorate %46 0 Offset 0 -OpMemberDecorate %46 0 ColMajor -OpMemberDecorate %46 0 MatrixStride 16 -OpMemberDecorate %46 1 Offset 64 -OpMemberDecorate %46 1 ColMajor -OpMemberDecorate %46 1 MatrixStride 8 -OpMemberDecorate %46 2 Offset 96 -OpMemberDecorate %46 3 Offset 104 -OpMemberDecorate %46 4 Offset 120 -OpMemberDecorate %48 0 Offset 0 -OpMemberDecorate %48 0 ColMajor -OpMemberDecorate %48 0 MatrixStride 8 -OpDecorate %51 ArrayStride 32 -OpMemberDecorate %52 0 Offset 0 -OpMemberDecorate %52 0 ColMajor -OpMemberDecorate %52 0 MatrixStride 8 -OpDecorate %54 ArrayStride 4 -OpDecorate %55 ArrayStride 40 -OpDecorate %58 ArrayStride 4 -OpDecorate %71 DescriptorSet 0 -OpDecorate %71 Binding 0 -OpDecorate %46 Block -OpDecorate %73 DescriptorSet 0 -OpDecorate %73 Binding 1 -OpDecorate %74 Block -OpMemberDecorate %74 0 Offset 0 -OpDecorate %76 DescriptorSet 0 -OpDecorate %76 Binding 2 -OpDecorate %77 Block -OpMemberDecorate %77 0 Offset 0 -OpDecorate %79 DescriptorSet 0 -OpDecorate %79 Binding 3 -OpDecorate %80 Block -OpMemberDecorate %80 0 Offset 0 -OpDecorate %231 BuiltIn VertexIndex -OpDecorate %234 BuiltIn Position -OpDecorate %276 Location 0 +OpDecorate %46 ArrayStride 8 +OpMemberDecorate %47 0 Offset 0 +OpMemberDecorate %47 0 ColMajor +OpMemberDecorate %47 0 MatrixStride 16 +OpMemberDecorate %47 1 Offset 64 +OpMemberDecorate %47 1 ColMajor +OpMemberDecorate %47 1 MatrixStride 8 +OpMemberDecorate %47 2 Offset 96 +OpMemberDecorate %47 3 Offset 100 +OpMemberDecorate %47 4 Offset 144 +OpMemberDecorate %47 5 Offset 160 +OpMemberDecorate %49 0 Offset 0 +OpMemberDecorate %49 0 ColMajor +OpMemberDecorate %49 0 MatrixStride 8 +OpDecorate %52 ArrayStride 32 +OpMemberDecorate %53 0 Offset 0 +OpMemberDecorate %53 0 ColMajor +OpMemberDecorate %53 0 MatrixStride 8 +OpDecorate %55 ArrayStride 4 +OpDecorate %56 ArrayStride 40 +OpDecorate %59 ArrayStride 4 +OpDecorate %72 DescriptorSet 0 +OpDecorate %72 Binding 0 +OpDecorate %47 Block +OpDecorate %74 DescriptorSet 0 +OpDecorate %74 Binding 1 +OpDecorate %75 Block +OpMemberDecorate %75 0 Offset 0 +OpDecorate %77 DescriptorSet 0 +OpDecorate %77 Binding 2 +OpDecorate %78 Block +OpMemberDecorate %78 0 Offset 0 +OpDecorate %80 DescriptorSet 0 +OpDecorate %80 Binding 3 +OpDecorate %81 Block +OpMemberDecorate %81 0 Offset 0 +OpDecorate %232 BuiltIn VertexIndex +OpDecorate %235 BuiltIn Position +OpDecorate %278 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 %6 = OpTypeInt 32 1 %5 = OpConstant %6 0 %7 = OpConstant %6 2 -%8 = OpConstant %6 1 -%10 = OpTypeFloat 32 -%9 = OpConstant %10 1.0 -%11 = OpConstant %10 2.0 -%12 = OpConstant %10 3.0 -%13 = OpConstant %10 6.0 -%14 = OpConstant %10 5.0 -%15 = OpConstant %10 4.0 -%16 = OpConstant %10 9.0 -%17 = OpConstant %10 90.0 -%18 = OpConstant %10 10.0 -%19 = OpConstant %10 20.0 -%20 = OpConstant %10 30.0 -%21 = OpConstant %10 40.0 -%22 = OpConstant %10 0.0 -%23 = OpConstant %10 8.0 -%24 = OpConstant %10 7.0 -%25 = OpConstant %6 10 +%8 = OpConstant %6 10 +%9 = OpConstant %6 1 +%11 = OpTypeFloat 32 +%10 = OpConstant %11 1.0 +%12 = OpConstant %11 2.0 +%13 = OpConstant %11 3.0 +%14 = OpConstant %11 6.0 +%15 = OpConstant %11 5.0 +%16 = OpConstant %11 4.0 +%17 = OpConstant %11 9.0 +%18 = OpConstant %11 90.0 +%19 = OpConstant %11 10.0 +%20 = OpConstant %11 20.0 +%21 = OpConstant %11 30.0 +%22 = OpConstant %11 40.0 +%23 = OpConstant %11 0.0 +%24 = OpConstant %11 8.0 +%25 = OpConstant %11 7.0 %26 = OpConstant %6 5 %27 = OpConstant %6 4 %28 = OpConstant %6 9 @@ -136,359 +139,361 @@ OpDecorate %276 Location 0 %35 = OpTypeVector %4 3 %36 = OpTypeStruct %4 %35 %6 %37 = OpTypeStruct %6 -%39 = OpTypeVector %10 3 +%39 = OpTypeVector %11 3 %38 = OpTypeMatrix %39 4 -%41 = OpTypeVector %10 2 +%41 = OpTypeVector %11 2 %40 = OpTypeMatrix %41 2 %42 = OpTypeArray %40 %7 -%43 = OpTypeVector %4 2 -%44 = OpTypeArray %43 %7 -%45 = OpTypeRuntimeArray %37 -%46 = OpTypeStruct %38 %42 %6 %44 %45 -%47 = OpTypeMatrix %41 3 -%48 = OpTypeStruct %47 -%49 = OpTypeVector %6 2 -%50 = OpTypeMatrix %41 4 -%51 = OpTypeArray %50 %7 -%52 = OpTypeStruct %51 -%53 = OpTypePointer Function %10 -%54 = OpTypeArray %10 %25 -%55 = OpTypeArray %54 %26 -%56 = OpTypeVector %10 4 -%57 = OpTypePointer StorageBuffer %6 -%58 = OpTypeArray %6 %26 -%59 = OpTypeVector %6 4 -%60 = OpTypePointer Workgroup %4 -%61 = OpConstantComposite %35 %3 %3 %3 -%62 = OpConstantComposite %36 %3 %61 %5 -%63 = OpConstantComposite %41 %22 %22 -%64 = OpConstantComposite %50 %63 %63 %63 %63 -%65 = OpConstantComposite %51 %64 %64 -%66 = OpConstantComposite %54 %22 %22 %22 %22 %22 %22 %22 %22 %22 %22 -%67 = OpConstantComposite %55 %66 %66 %66 %66 %66 -%68 = OpConstantComposite %49 %5 %5 -%70 = OpTypePointer Private %36 -%69 = OpVariable %70 Private %62 -%72 = OpTypePointer StorageBuffer %46 -%71 = OpVariable %72 StorageBuffer -%74 = OpTypeStruct %48 -%75 = OpTypePointer Uniform %74 -%73 = OpVariable %75 Uniform -%77 = OpTypeStruct %49 -%78 = OpTypePointer StorageBuffer %77 -%76 = OpVariable %78 StorageBuffer -%80 = OpTypeStruct %52 -%81 = OpTypePointer Uniform %80 -%79 = OpVariable %81 Uniform -%82 = OpVariable %60 Workgroup -%84 = OpTypePointer Function %6 -%85 = OpConstantNull %6 -%87 = OpTypePointer Function %48 -%88 = OpConstantNull %48 -%91 = OpTypeFunction %2 -%92 = OpTypePointer Uniform %48 -%97 = OpTypePointer Uniform %47 -%100 = OpTypePointer Uniform %41 -%106 = OpTypePointer Uniform %10 -%126 = OpTypePointer Function %47 -%132 = OpTypePointer Function %41 -%138 = OpTypePointer Function %10 -%148 = OpConstantNull %6 -%150 = OpTypePointer Function %52 -%151 = OpConstantNull %52 -%154 = OpTypePointer Uniform %52 -%159 = OpTypePointer Uniform %51 -%162 = OpTypePointer Uniform %50 -%185 = OpTypePointer Function %51 -%187 = OpTypePointer Function %50 -%210 = OpTypeFunction %10 %53 -%216 = OpTypeFunction %10 %55 -%223 = OpTypeFunction %2 %60 -%226 = OpConstantNull %10 -%228 = OpTypePointer Function %58 -%229 = OpConstantNull %58 -%232 = OpTypePointer Input %4 -%231 = OpVariable %232 Input -%235 = OpTypePointer Output %56 -%234 = OpVariable %235 Output -%238 = OpTypePointer StorageBuffer %49 -%245 = OpTypePointer StorageBuffer %38 -%248 = OpTypePointer StorageBuffer %44 -%251 = OpTypePointer StorageBuffer %39 -%252 = OpTypePointer StorageBuffer %10 -%255 = OpTypePointer StorageBuffer %45 -%258 = OpTypePointer StorageBuffer %37 -%259 = OpConstant %4 4 -%276 = OpVariable %235 Output -%294 = OpConstantNull %6 -%298 = OpTypePointer StorageBuffer %6 -%301 = OpConstant %4 64 -%90 = OpFunction %2 None %91 -%89 = OpLabel -%83 = OpVariable %84 Function %85 -%86 = OpVariable %87 Function %88 -%93 = OpAccessChain %92 %73 %3 -OpBranch %94 -%94 = OpLabel -OpStore %83 %8 -%95 = OpLoad %6 %83 -%96 = OpISub %6 %95 %8 -OpStore %83 %96 -%98 = OpAccessChain %97 %93 %3 -%99 = OpLoad %47 %98 -%101 = OpAccessChain %100 %93 %3 %3 -%102 = OpLoad %41 %101 -%103 = OpLoad %6 %83 -%104 = OpAccessChain %100 %93 %3 %103 -%105 = OpLoad %41 %104 -%107 = OpAccessChain %106 %93 %3 %3 %32 -%108 = OpLoad %10 %107 -%109 = OpLoad %6 %83 -%110 = OpAccessChain %106 %93 %3 %3 %109 -%111 = OpLoad %10 %110 -%112 = OpLoad %6 %83 -%113 = OpAccessChain %106 %93 %3 %112 %32 -%114 = OpLoad %10 %113 -%115 = OpLoad %6 %83 -%116 = OpLoad %6 %83 -%117 = OpAccessChain %106 %93 %3 %115 %116 -%118 = OpLoad %10 %117 -%119 = OpCompositeConstruct %41 %9 %9 -%120 = OpCompositeConstruct %41 %11 %11 +%43 = OpTypeArray %6 %8 +%44 = OpTypeVector %4 2 +%45 = OpTypeArray %44 %7 +%46 = OpTypeRuntimeArray %37 +%47 = OpTypeStruct %38 %42 %6 %43 %45 %46 +%48 = OpTypeMatrix %41 3 +%49 = OpTypeStruct %48 +%50 = OpTypeVector %6 2 +%51 = OpTypeMatrix %41 4 +%52 = OpTypeArray %51 %7 +%53 = OpTypeStruct %52 +%54 = OpTypePointer Function %11 +%55 = OpTypeArray %11 %8 +%56 = OpTypeArray %55 %26 +%57 = OpTypeVector %11 4 +%58 = OpTypePointer StorageBuffer %6 +%59 = OpTypeArray %6 %26 +%60 = OpTypeVector %6 4 +%61 = OpTypePointer Workgroup %4 +%62 = OpConstantComposite %35 %3 %3 %3 +%63 = OpConstantComposite %36 %3 %62 %5 +%64 = OpConstantComposite %41 %23 %23 +%65 = OpConstantComposite %51 %64 %64 %64 %64 +%66 = OpConstantComposite %52 %65 %65 +%67 = OpConstantComposite %55 %23 %23 %23 %23 %23 %23 %23 %23 %23 %23 +%68 = OpConstantComposite %56 %67 %67 %67 %67 %67 +%69 = OpConstantComposite %50 %5 %5 +%71 = OpTypePointer Private %36 +%70 = OpVariable %71 Private %63 +%73 = OpTypePointer StorageBuffer %47 +%72 = OpVariable %73 StorageBuffer +%75 = OpTypeStruct %49 +%76 = OpTypePointer Uniform %75 +%74 = OpVariable %76 Uniform +%78 = OpTypeStruct %50 +%79 = OpTypePointer StorageBuffer %78 +%77 = OpVariable %79 StorageBuffer +%81 = OpTypeStruct %53 +%82 = OpTypePointer Uniform %81 +%80 = OpVariable %82 Uniform +%83 = OpVariable %61 Workgroup +%85 = OpTypePointer Function %6 +%86 = OpConstantNull %6 +%88 = OpTypePointer Function %49 +%89 = OpConstantNull %49 +%92 = OpTypeFunction %2 +%93 = OpTypePointer Uniform %49 +%98 = OpTypePointer Uniform %48 +%101 = OpTypePointer Uniform %41 +%107 = OpTypePointer Uniform %11 +%127 = OpTypePointer Function %48 +%133 = OpTypePointer Function %41 +%139 = OpTypePointer Function %11 +%149 = OpConstantNull %6 +%151 = OpTypePointer Function %53 +%152 = OpConstantNull %53 +%155 = OpTypePointer Uniform %53 +%160 = OpTypePointer Uniform %52 +%163 = OpTypePointer Uniform %51 +%186 = OpTypePointer Function %52 +%188 = OpTypePointer Function %51 +%211 = OpTypeFunction %11 %54 +%217 = OpTypeFunction %11 %56 +%224 = OpTypeFunction %2 %61 +%227 = OpConstantNull %11 +%229 = OpTypePointer Function %59 +%230 = OpConstantNull %59 +%233 = OpTypePointer Input %4 +%232 = OpVariable %233 Input +%236 = OpTypePointer Output %57 +%235 = OpVariable %236 Output +%239 = OpTypePointer StorageBuffer %50 +%246 = OpTypePointer StorageBuffer %38 +%249 = OpTypePointer StorageBuffer %45 +%250 = OpConstant %4 4 +%253 = OpTypePointer StorageBuffer %39 +%254 = OpTypePointer StorageBuffer %11 +%257 = OpTypePointer StorageBuffer %46 +%260 = OpTypePointer StorageBuffer %37 +%261 = OpConstant %4 5 +%278 = OpVariable %236 Output +%296 = OpConstantNull %6 +%300 = OpTypePointer StorageBuffer %6 +%303 = OpConstant %4 64 +%91 = OpFunction %2 None %92 +%90 = OpLabel +%84 = OpVariable %85 Function %86 +%87 = OpVariable %88 Function %89 +%94 = OpAccessChain %93 %74 %3 +OpBranch %95 +%95 = OpLabel +OpStore %84 %9 +%96 = OpLoad %6 %84 +%97 = OpISub %6 %96 %9 +OpStore %84 %97 +%99 = OpAccessChain %98 %94 %3 +%100 = OpLoad %48 %99 +%102 = OpAccessChain %101 %94 %3 %3 +%103 = OpLoad %41 %102 +%104 = OpLoad %6 %84 +%105 = OpAccessChain %101 %94 %3 %104 +%106 = OpLoad %41 %105 +%108 = OpAccessChain %107 %94 %3 %3 %32 +%109 = OpLoad %11 %108 +%110 = OpLoad %6 %84 +%111 = OpAccessChain %107 %94 %3 %3 %110 +%112 = OpLoad %11 %111 +%113 = OpLoad %6 %84 +%114 = OpAccessChain %107 %94 %3 %113 %32 +%115 = OpLoad %11 %114 +%116 = OpLoad %6 %84 +%117 = OpLoad %6 %84 +%118 = OpAccessChain %107 %94 %3 %116 %117 +%119 = OpLoad %11 %118 +%120 = OpCompositeConstruct %41 %10 %10 %121 = OpCompositeConstruct %41 %12 %12 -%122 = OpCompositeConstruct %47 %119 %120 %121 -%123 = OpCompositeConstruct %48 %122 -OpStore %86 %123 -%124 = OpLoad %6 %83 -%125 = OpIAdd %6 %124 %8 -OpStore %83 %125 -%127 = OpCompositeConstruct %41 %13 %13 +%122 = OpCompositeConstruct %41 %13 %13 +%123 = OpCompositeConstruct %48 %120 %121 %122 +%124 = OpCompositeConstruct %49 %123 +OpStore %87 %124 +%125 = OpLoad %6 %84 +%126 = OpIAdd %6 %125 %9 +OpStore %84 %126 %128 = OpCompositeConstruct %41 %14 %14 %129 = OpCompositeConstruct %41 %15 %15 -%130 = OpCompositeConstruct %47 %127 %128 %129 -%131 = OpAccessChain %126 %86 %3 -OpStore %131 %130 -%133 = OpCompositeConstruct %41 %16 %16 -%134 = OpAccessChain %132 %86 %3 %3 -OpStore %134 %133 -%135 = OpLoad %6 %83 -%136 = OpCompositeConstruct %41 %17 %17 -%137 = OpAccessChain %132 %86 %3 %135 -OpStore %137 %136 -%139 = OpAccessChain %138 %86 %3 %3 %32 -OpStore %139 %18 -%140 = OpLoad %6 %83 -%141 = OpAccessChain %138 %86 %3 %3 %140 -OpStore %141 %19 -%142 = OpLoad %6 %83 -%143 = OpAccessChain %138 %86 %3 %142 %32 -OpStore %143 %20 -%144 = OpLoad %6 %83 -%145 = OpLoad %6 %83 -%146 = OpAccessChain %138 %86 %3 %144 %145 -OpStore %146 %21 +%130 = OpCompositeConstruct %41 %16 %16 +%131 = OpCompositeConstruct %48 %128 %129 %130 +%132 = OpAccessChain %127 %87 %3 +OpStore %132 %131 +%134 = OpCompositeConstruct %41 %17 %17 +%135 = OpAccessChain %133 %87 %3 %3 +OpStore %135 %134 +%136 = OpLoad %6 %84 +%137 = OpCompositeConstruct %41 %18 %18 +%138 = OpAccessChain %133 %87 %3 %136 +OpStore %138 %137 +%140 = OpAccessChain %139 %87 %3 %3 %32 +OpStore %140 %19 +%141 = OpLoad %6 %84 +%142 = OpAccessChain %139 %87 %3 %3 %141 +OpStore %142 %20 +%143 = OpLoad %6 %84 +%144 = OpAccessChain %139 %87 %3 %143 %32 +OpStore %144 %21 +%145 = OpLoad %6 %84 +%146 = OpLoad %6 %84 +%147 = OpAccessChain %139 %87 %3 %145 %146 +OpStore %147 %22 OpReturn OpFunctionEnd -%153 = OpFunction %2 None %91 -%152 = OpLabel -%147 = OpVariable %84 Function %148 -%149 = OpVariable %150 Function %151 -%155 = OpAccessChain %154 %79 %3 -OpBranch %156 -%156 = OpLabel -OpStore %147 %8 -%157 = OpLoad %6 %147 -%158 = OpISub %6 %157 %8 -OpStore %147 %158 -%160 = OpAccessChain %159 %155 %3 -%161 = OpLoad %51 %160 -%163 = OpAccessChain %162 %155 %3 %3 -%164 = OpLoad %50 %163 -%165 = OpAccessChain %100 %155 %3 %3 %3 -%166 = OpLoad %41 %165 -%167 = OpLoad %6 %147 -%168 = OpAccessChain %100 %155 %3 %3 %167 -%169 = OpLoad %41 %168 -%170 = OpAccessChain %106 %155 %3 %3 %3 %32 -%171 = OpLoad %10 %170 -%172 = OpLoad %6 %147 -%173 = OpAccessChain %106 %155 %3 %3 %3 %172 -%174 = OpLoad %10 %173 -%175 = OpLoad %6 %147 -%176 = OpAccessChain %106 %155 %3 %3 %175 %32 -%177 = OpLoad %10 %176 -%178 = OpLoad %6 %147 -%179 = OpLoad %6 %147 -%180 = OpAccessChain %106 %155 %3 %3 %178 %179 -%181 = OpLoad %10 %180 -%182 = OpCompositeConstruct %52 %65 -OpStore %149 %182 -%183 = OpLoad %6 %147 -%184 = OpIAdd %6 %183 %8 -OpStore %147 %184 -%186 = OpAccessChain %185 %149 %3 -OpStore %186 %65 -%188 = OpCompositeConstruct %41 %23 %23 +%154 = OpFunction %2 None %92 +%153 = OpLabel +%148 = OpVariable %85 Function %149 +%150 = OpVariable %151 Function %152 +%156 = OpAccessChain %155 %80 %3 +OpBranch %157 +%157 = OpLabel +OpStore %148 %9 +%158 = OpLoad %6 %148 +%159 = OpISub %6 %158 %9 +OpStore %148 %159 +%161 = OpAccessChain %160 %156 %3 +%162 = OpLoad %52 %161 +%164 = OpAccessChain %163 %156 %3 %3 +%165 = OpLoad %51 %164 +%166 = OpAccessChain %101 %156 %3 %3 %3 +%167 = OpLoad %41 %166 +%168 = OpLoad %6 %148 +%169 = OpAccessChain %101 %156 %3 %3 %168 +%170 = OpLoad %41 %169 +%171 = OpAccessChain %107 %156 %3 %3 %3 %32 +%172 = OpLoad %11 %171 +%173 = OpLoad %6 %148 +%174 = OpAccessChain %107 %156 %3 %3 %3 %173 +%175 = OpLoad %11 %174 +%176 = OpLoad %6 %148 +%177 = OpAccessChain %107 %156 %3 %3 %176 %32 +%178 = OpLoad %11 %177 +%179 = OpLoad %6 %148 +%180 = OpLoad %6 %148 +%181 = OpAccessChain %107 %156 %3 %3 %179 %180 +%182 = OpLoad %11 %181 +%183 = OpCompositeConstruct %53 %66 +OpStore %150 %183 +%184 = OpLoad %6 %148 +%185 = OpIAdd %6 %184 %9 +OpStore %148 %185 +%187 = OpAccessChain %186 %150 %3 +OpStore %187 %66 %189 = OpCompositeConstruct %41 %24 %24 -%190 = OpCompositeConstruct %41 %13 %13 +%190 = OpCompositeConstruct %41 %25 %25 %191 = OpCompositeConstruct %41 %14 %14 -%192 = OpCompositeConstruct %50 %188 %189 %190 %191 -%193 = OpAccessChain %187 %149 %3 %3 -OpStore %193 %192 -%194 = OpCompositeConstruct %41 %16 %16 -%195 = OpAccessChain %132 %149 %3 %3 %3 -OpStore %195 %194 -%196 = OpLoad %6 %147 -%197 = OpCompositeConstruct %41 %17 %17 -%198 = OpAccessChain %132 %149 %3 %3 %196 -OpStore %198 %197 -%199 = OpAccessChain %138 %149 %3 %3 %3 %32 -OpStore %199 %18 -%200 = OpLoad %6 %147 -%201 = OpAccessChain %138 %149 %3 %3 %3 %200 -OpStore %201 %19 -%202 = OpLoad %6 %147 -%203 = OpAccessChain %138 %149 %3 %3 %202 %32 -OpStore %203 %20 -%204 = OpLoad %6 %147 -%205 = OpLoad %6 %147 -%206 = OpAccessChain %138 %149 %3 %3 %204 %205 -OpStore %206 %21 +%192 = OpCompositeConstruct %41 %15 %15 +%193 = OpCompositeConstruct %51 %189 %190 %191 %192 +%194 = OpAccessChain %188 %150 %3 %3 +OpStore %194 %193 +%195 = OpCompositeConstruct %41 %17 %17 +%196 = OpAccessChain %133 %150 %3 %3 %3 +OpStore %196 %195 +%197 = OpLoad %6 %148 +%198 = OpCompositeConstruct %41 %18 %18 +%199 = OpAccessChain %133 %150 %3 %3 %197 +OpStore %199 %198 +%200 = OpAccessChain %139 %150 %3 %3 %3 %32 +OpStore %200 %19 +%201 = OpLoad %6 %148 +%202 = OpAccessChain %139 %150 %3 %3 %3 %201 +OpStore %202 %20 +%203 = OpLoad %6 %148 +%204 = OpAccessChain %139 %150 %3 %3 %203 %32 +OpStore %204 %21 +%205 = OpLoad %6 %148 +%206 = OpLoad %6 %148 +%207 = OpAccessChain %139 %150 %3 %3 %205 %206 +OpStore %207 %22 OpReturn OpFunctionEnd -%209 = OpFunction %10 None %210 -%208 = OpFunctionParameter %53 -%207 = OpLabel -OpBranch %211 -%211 = OpLabel -%212 = OpLoad %10 %208 -OpReturnValue %212 +%210 = OpFunction %11 None %211 +%209 = OpFunctionParameter %54 +%208 = OpLabel +OpBranch %212 +%212 = OpLabel +%213 = OpLoad %11 %209 +OpReturnValue %213 OpFunctionEnd -%215 = OpFunction %10 None %216 -%214 = OpFunctionParameter %55 -%213 = OpLabel -OpBranch %217 -%217 = OpLabel -%218 = OpCompositeExtract %54 %214 4 -%219 = OpCompositeExtract %10 %218 9 -OpReturnValue %219 +%216 = OpFunction %11 None %217 +%215 = OpFunctionParameter %56 +%214 = OpLabel +OpBranch %218 +%218 = OpLabel +%219 = OpCompositeExtract %55 %215 4 +%220 = OpCompositeExtract %11 %219 9 +OpReturnValue %220 OpFunctionEnd -%222 = OpFunction %2 None %223 -%221 = OpFunctionParameter %60 -%220 = OpLabel -OpBranch %224 -%224 = OpLabel -OpStore %221 %34 +%223 = OpFunction %2 None %224 +%222 = OpFunctionParameter %61 +%221 = OpLabel +OpBranch %225 +%225 = OpLabel +OpStore %222 %34 OpReturn OpFunctionEnd -%236 = OpFunction %2 None %91 -%230 = OpLabel -%225 = OpVariable %53 Function %226 -%227 = OpVariable %228 Function %229 -%233 = OpLoad %4 %231 -%237 = OpAccessChain %92 %73 %3 -%239 = OpAccessChain %238 %76 %3 -%240 = OpAccessChain %154 %79 %3 -OpBranch %241 -%241 = OpLabel -OpStore %225 %22 -%242 = OpLoad %10 %225 -OpStore %225 %9 -%243 = OpFunctionCall %2 %90 -%244 = OpFunctionCall %2 %153 -%246 = OpAccessChain %245 %71 %3 -%247 = OpLoad %38 %246 -%249 = OpAccessChain %248 %71 %29 -%250 = OpLoad %44 %249 -%253 = OpAccessChain %252 %71 %3 %29 %3 -%254 = OpLoad %10 %253 -%256 = OpArrayLength %4 %71 4 -%257 = OpISub %4 %256 %30 -%260 = OpAccessChain %57 %71 %259 %257 %3 -%261 = OpLoad %6 %260 -%262 = OpLoad %49 %239 -%263 = OpFunctionCall %10 %209 %225 -%264 = OpConvertFToS %6 %254 -%265 = OpCompositeConstruct %58 %261 %264 %31 %27 %26 -OpStore %227 %265 -%266 = OpIAdd %4 %233 %32 -%267 = OpAccessChain %84 %227 %266 -OpStore %267 %33 -%268 = OpAccessChain %84 %227 %233 -%269 = OpLoad %6 %268 -%270 = OpFunctionCall %10 %215 %67 -%271 = OpCompositeConstruct %59 %269 %269 %269 %269 -%272 = OpConvertSToF %56 %271 -%273 = OpMatrixTimesVector %39 %247 %272 -%274 = OpCompositeConstruct %56 %273 %11 -OpStore %234 %274 +%237 = OpFunction %2 None %92 +%231 = OpLabel +%226 = OpVariable %54 Function %227 +%228 = OpVariable %229 Function %230 +%234 = OpLoad %4 %232 +%238 = OpAccessChain %93 %74 %3 +%240 = OpAccessChain %239 %77 %3 +%241 = OpAccessChain %155 %80 %3 +OpBranch %242 +%242 = OpLabel +OpStore %226 %23 +%243 = OpLoad %11 %226 +OpStore %226 %10 +%244 = OpFunctionCall %2 %91 +%245 = OpFunctionCall %2 %154 +%247 = OpAccessChain %246 %72 %3 +%248 = OpLoad %38 %247 +%251 = OpAccessChain %249 %72 %250 +%252 = OpLoad %45 %251 +%255 = OpAccessChain %254 %72 %3 %29 %3 +%256 = OpLoad %11 %255 +%258 = OpArrayLength %4 %72 5 +%259 = OpISub %4 %258 %30 +%262 = OpAccessChain %58 %72 %261 %259 %3 +%263 = OpLoad %6 %262 +%264 = OpLoad %50 %240 +%265 = OpFunctionCall %11 %210 %226 +%266 = OpConvertFToS %6 %256 +%267 = OpCompositeConstruct %59 %263 %266 %31 %27 %26 +OpStore %228 %267 +%268 = OpIAdd %4 %234 %32 +%269 = OpAccessChain %85 %228 %268 +OpStore %269 %33 +%270 = OpAccessChain %85 %228 %234 +%271 = OpLoad %6 %270 +%272 = OpFunctionCall %11 %216 %68 +%273 = OpCompositeConstruct %60 %271 %271 %271 %271 +%274 = OpConvertSToF %57 %273 +%275 = OpMatrixTimesVector %39 %248 %274 +%276 = OpCompositeConstruct %57 %275 %12 +OpStore %235 %276 OpReturn OpFunctionEnd -%277 = OpFunction %2 None %91 -%275 = OpLabel -%278 = OpAccessChain %238 %76 %3 -OpBranch %279 -%279 = OpLabel -%280 = OpAccessChain %252 %71 %3 %32 %30 -OpStore %280 %9 -%281 = OpCompositeConstruct %39 %22 %22 %22 -%282 = OpCompositeConstruct %39 %9 %9 %9 -%283 = OpCompositeConstruct %39 %11 %11 %11 -%284 = OpCompositeConstruct %39 %12 %12 %12 -%285 = OpCompositeConstruct %38 %281 %282 %283 %284 -%286 = OpAccessChain %245 %71 %3 -OpStore %286 %285 -%287 = OpCompositeConstruct %43 %3 %3 -%288 = OpCompositeConstruct %43 %32 %32 -%289 = OpCompositeConstruct %44 %287 %288 -%290 = OpAccessChain %248 %71 %29 -OpStore %290 %289 -%291 = OpAccessChain %57 %71 %259 %32 %3 -OpStore %291 %8 -OpStore %278 %68 -%292 = OpCompositeConstruct %56 %22 %22 %22 %22 -OpStore %276 %292 +%279 = OpFunction %2 None %92 +%277 = OpLabel +%280 = OpAccessChain %239 %77 %3 +OpBranch %281 +%281 = OpLabel +%282 = OpAccessChain %254 %72 %3 %32 %30 +OpStore %282 %10 +%283 = OpCompositeConstruct %39 %23 %23 %23 +%284 = OpCompositeConstruct %39 %10 %10 %10 +%285 = OpCompositeConstruct %39 %12 %12 %12 +%286 = OpCompositeConstruct %39 %13 %13 %13 +%287 = OpCompositeConstruct %38 %283 %284 %285 %286 +%288 = OpAccessChain %246 %72 %3 +OpStore %288 %287 +%289 = OpCompositeConstruct %44 %3 %3 +%290 = OpCompositeConstruct %44 %32 %32 +%291 = OpCompositeConstruct %45 %289 %290 +%292 = OpAccessChain %249 %72 %250 +OpStore %292 %291 +%293 = OpAccessChain %58 %72 %261 %32 %3 +OpStore %293 %9 +OpStore %280 %69 +%294 = OpCompositeConstruct %57 %23 %23 %23 %23 +OpStore %278 %294 OpReturn OpFunctionEnd -%296 = OpFunction %2 None %91 -%295 = OpLabel -%293 = OpVariable %84 Function %294 -OpBranch %297 +%298 = OpFunction %2 None %92 %297 = OpLabel -%299 = OpAccessChain %298 %71 %30 -%300 = OpAtomicLoad %6 %299 %8 %301 -%303 = OpAccessChain %298 %71 %30 -%302 = OpAtomicIAdd %6 %303 %8 %301 %26 -OpStore %293 %302 -%305 = OpAccessChain %298 %71 %30 -%304 = OpAtomicISub %6 %305 %8 %301 %26 -OpStore %293 %304 -%307 = OpAccessChain %298 %71 %30 -%306 = OpAtomicAnd %6 %307 %8 %301 %26 -OpStore %293 %306 -%309 = OpAccessChain %298 %71 %30 -%308 = OpAtomicOr %6 %309 %8 %301 %26 -OpStore %293 %308 -%311 = OpAccessChain %298 %71 %30 -%310 = OpAtomicXor %6 %311 %8 %301 %26 -OpStore %293 %310 -%313 = OpAccessChain %298 %71 %30 -%312 = OpAtomicSMin %6 %313 %8 %301 %26 -OpStore %293 %312 -%315 = OpAccessChain %298 %71 %30 -%314 = OpAtomicSMax %6 %315 %8 %301 %26 -OpStore %293 %314 -%317 = OpAccessChain %298 %71 %30 -%316 = OpAtomicExchange %6 %317 %8 %301 %26 -OpStore %293 %316 -%318 = OpAccessChain %298 %71 %30 -OpAtomicStore %318 %8 %301 %300 +%295 = OpVariable %85 Function %296 +OpBranch %299 +%299 = OpLabel +%301 = OpAccessChain %300 %72 %30 +%302 = OpAtomicLoad %6 %301 %9 %303 +%305 = OpAccessChain %300 %72 %30 +%304 = OpAtomicIAdd %6 %305 %9 %303 %26 +OpStore %295 %304 +%307 = OpAccessChain %300 %72 %30 +%306 = OpAtomicISub %6 %307 %9 %303 %26 +OpStore %295 %306 +%309 = OpAccessChain %300 %72 %30 +%308 = OpAtomicAnd %6 %309 %9 %303 %26 +OpStore %295 %308 +%311 = OpAccessChain %300 %72 %30 +%310 = OpAtomicOr %6 %311 %9 %303 %26 +OpStore %295 %310 +%313 = OpAccessChain %300 %72 %30 +%312 = OpAtomicXor %6 %313 %9 %303 %26 +OpStore %295 %312 +%315 = OpAccessChain %300 %72 %30 +%314 = OpAtomicSMin %6 %315 %9 %303 %26 +OpStore %295 %314 +%317 = OpAccessChain %300 %72 %30 +%316 = OpAtomicSMax %6 %317 %9 %303 %26 +OpStore %295 %316 +%319 = OpAccessChain %300 %72 %30 +%318 = OpAtomicExchange %6 %319 %9 %303 %26 +OpStore %295 %318 +%320 = OpAccessChain %300 %72 %30 +OpAtomicStore %320 %9 %303 %302 OpReturn OpFunctionEnd -%320 = OpFunction %2 None %91 -%319 = OpLabel -OpBranch %321 +%322 = OpFunction %2 None %92 %321 = OpLabel -%322 = OpFunctionCall %2 %222 %82 +OpBranch %323 +%323 = OpLabel +%324 = OpFunctionCall %2 %223 %83 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 31054c870..5510a7988 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -12,6 +12,7 @@ struct Bar { _matrix: mat4x3, matrix_array: array,2>, atom: atomic, + atom_arr: array,10>, arr: array,2>, data: array, } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 706e714b0..02e77a6cf 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -490,7 +490,13 @@ fn convert_wgsl() { ), ( "access", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + Targets::SPIRV + | Targets::METAL + | Targets::GLSL + | Targets::HLSL + | Targets::WGSL + | Targets::IR + | Targets::ANALYSIS, ), ("atomicCompareExchange", Targets::SPIRV | Targets::WGSL), ( From c7d02151f08d6285683795289b5725b827d836d1 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 25 Jan 2023 18:00:11 +0100 Subject: [PATCH 1908/2212] add support for zero-initializing workgroup memory --- benches/criterion.rs | 1 + src/back/glsl/mod.rs | 49 +- src/back/hlsl/mod.rs | 3 + src/back/hlsl/writer.rs | 57 ++ src/back/mod.rs | 11 + src/back/msl/mod.rs | 3 + src/back/msl/writer.rs | 237 +++++++- src/back/spv/mod.rs | 14 + src/back/spv/writer.rs | 197 ++++++- tests/in/access.param.ron | 1 + tests/in/binding-arrays.param.ron | 2 + tests/in/bitcast.params.ron | 1 + tests/in/bits.param.ron | 1 + tests/in/boids.param.ron | 1 + .../in/bounds-check-image-restrict.param.ron | 1 + tests/in/bounds-check-image-rzsw.param.ron | 1 + tests/in/extra.param.ron | 1 + tests/in/functions-webgl.param.ron | 1 + tests/in/interface.param.ron | 2 + tests/in/interpolate.param.ron | 1 + tests/in/multiview_webgl.param.ron | 1 + tests/in/padding.param.ron | 1 + tests/in/push-constants.param.ron | 2 + tests/in/quad.param.ron | 1 + tests/in/skybox.param.ron | 3 + tests/in/workgroup-var-init.param.ron | 22 + tests/in/workgroup-var-init.wgsl | 15 + .../access.assign_through_ptr.Compute.glsl | 5 + tests/out/glsl/globals.main.Compute.glsl | 6 + .../glsl/workgroup-var-init.main.Compute.glsl | 28 + tests/out/hlsl/access.hlsl | 6 +- tests/out/hlsl/globals.hlsl | 7 +- tests/out/hlsl/interface.hlsl | 6 +- tests/out/hlsl/workgroup-var-init.hlsl | 535 ++++++++++++++++++ tests/out/hlsl/workgroup-var-init.hlsl.config | 3 + tests/out/msl/access.msl | 7 +- tests/out/msl/globals.msl | 8 +- tests/out/msl/interface.msl | 4 + tests/out/msl/workgroup-var-init.msl | 40 ++ tests/out/spv/access.spvasm | 26 +- tests/out/spv/globals.spvasm | 136 +++-- tests/out/spv/interface.compute.spvasm | 41 +- tests/out/spv/workgroup-var-init.spvasm | 78 +++ tests/out/wgsl/workgroup-var-init.wgsl | 16 + tests/snapshots.rs | 5 + 45 files changed, 1502 insertions(+), 85 deletions(-) create mode 100644 tests/in/workgroup-var-init.param.ron create mode 100644 tests/in/workgroup-var-init.wgsl create mode 100644 tests/out/glsl/workgroup-var-init.main.Compute.glsl create mode 100644 tests/out/hlsl/workgroup-var-init.hlsl create mode 100644 tests/out/hlsl/workgroup-var-init.hlsl.config create mode 100644 tests/out/msl/workgroup-var-init.msl create mode 100644 tests/out/spv/workgroup-var-init.spvasm create mode 100644 tests/out/wgsl/workgroup-var-init.wgsl diff --git a/benches/criterion.rs b/benches/criterion.rs index 81c55c70c..0bf247899 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -242,6 +242,7 @@ fn backends(c: &mut Criterion) { version: naga::back::glsl::Version::new_gles(320), writer_flags: naga::back::glsl::WriterFlags::empty(), binding_map: Default::default(), + zero_initialize_workgroup_memory: true, }; for &(ref module, ref info) in inputs.iter() { for ep in module.entry_points.iter() { diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ede4bf848..9b4bf0cf2 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -232,6 +232,8 @@ pub struct Options { pub writer_flags: WriterFlags, /// Map of resources association to binding locations. pub binding_map: BindingMap, + /// Should workgroup variables be zero initialized (by polyfilling)? + pub zero_initialize_workgroup_memory: bool, } impl Default for Options { @@ -240,6 +242,7 @@ impl Default for Options { version: Version::new_gles(310), writer_flags: WriterFlags::ADJUST_COORDINATE_SPACE, binding_map: BindingMap::default(), + zero_initialize_workgroup_memory: true, } } } @@ -1432,6 +1435,12 @@ impl<'a, W: Write> Writer<'a, W> { // Close the parentheses and open braces to start the function body writeln!(self.out, ") {{")?; + if self.options.zero_initialize_workgroup_memory + && ctx.ty.is_compute_entry_point(self.module) + { + self.write_workgroup_variables_initialization(&ctx)?; + } + // Compose the function arguments from globals, in case of an entry point. if let back::FunctionType::EntryPoint(ep_index) = ctx.ty { let stage = self.module.entry_points[ep_index as usize].stage; @@ -1520,6 +1529,42 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + fn write_workgroup_variables_initialization( + &mut self, + ctx: &back::FunctionCtx, + ) -> BackendResult { + let mut vars = self + .module + .global_variables + .iter() + .filter(|&(handle, var)| { + !ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup + }) + .peekable(); + + if vars.peek().is_some() { + let level = back::Level(1); + + writeln!( + self.out, + "{}if (gl_GlobalInvocationID == uvec3(0u)) {{", + level + )?; + + for (handle, var) in vars { + let name = &self.names[&NameKey::GlobalVariable(handle)]; + write!(self.out, "{}{} = ", level.next(), name)?; + self.write_zero_init_value(var.ty)?; + writeln!(self.out, ";")?; + } + + writeln!(self.out, "{}}}", level)?; + self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + } + + Ok(()) + } + /// Helper method that writes a list of comma separated `T` with a writer function `F` /// /// The writer function `F` receives a mutable reference to `self` that if needed won't cause @@ -3548,7 +3593,7 @@ impl<'a, W: Write> Writer<'a, W> { fn write_zero_init_value(&mut self, ty: Handle) -> BackendResult { let inner = &self.module.types[ty].inner; match *inner { - TypeInner::Scalar { kind, .. } => { + TypeInner::Scalar { kind, .. } | TypeInner::Atomic { kind, .. } => { self.write_zero_init_scalar(kind)?; } TypeInner::Vector { kind, .. } => { @@ -3593,7 +3638,7 @@ impl<'a, W: Write> Writer<'a, W> { } write!(self.out, ")")?; } - _ => {} // TODO: + _ => unreachable!(), } Ok(()) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 333ea2cf1..103127039 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -191,6 +191,8 @@ pub struct Options { pub special_constants_binding: Option, /// Bind target of the push constant buffer pub push_constants_target: Option, + /// Should workgroup variables be zero initialized (by polyfilling)? + pub zero_initialize_workgroup_memory: bool, } impl Default for Options { @@ -201,6 +203,7 @@ impl Default for Options { fake_missing_bindings: true, special_constants_binding: None, push_constants_target: None, + zero_initialize_workgroup_memory: true, } } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 59050455a..664b326a1 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1077,6 +1077,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write function name write!(self.out, " {}(", name)?; + let need_workgroup_variables_initialization = + self.need_workgroup_variables_initialization(func_ctx, module); + // Write function arguments for non entry point functions match func_ctx.ty { back::FunctionType::Function(handle) => { @@ -1129,6 +1132,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_semantic(binding, Some((stage, Io::Input)))?; } } + + if need_workgroup_variables_initialization { + if !func.arguments.is_empty() { + write!(self.out, ", ")?; + } + write!( + self.out, + "uint3 __global_invocation_id : SV_DispatchThreadID" + )?; + } } } } @@ -1151,6 +1164,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out)?; writeln!(self.out, "{{")?; + if need_workgroup_variables_initialization { + self.write_workgroup_variables_initialization(func_ctx, module)?; + } + if let back::FunctionType::EntryPoint(index) = func_ctx.ty { self.write_ep_arguments_initialization(module, func, index)?; } @@ -1204,6 +1221,46 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } + fn need_workgroup_variables_initialization( + &mut self, + func_ctx: &back::FunctionCtx, + module: &Module, + ) -> bool { + self.options.zero_initialize_workgroup_memory + && func_ctx.ty.is_compute_entry_point(module) + && module.global_variables.iter().any(|(handle, var)| { + !func_ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup + }) + } + + fn write_workgroup_variables_initialization( + &mut self, + func_ctx: &back::FunctionCtx, + module: &Module, + ) -> BackendResult { + let level = back::Level(1); + + writeln!( + self.out, + "{}if (all(__global_invocation_id == uint3(0u, 0u, 0u))) {{", + level + )?; + + let vars = module.global_variables.iter().filter(|&(handle, var)| { + !func_ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup + }); + + for (handle, var) in vars { + let name = &self.names[&NameKey::GlobalVariable(handle)]; + write!(self.out, "{}{} = ", level.next(), name)?; + self.write_default_init(module, var.ty)?; + writeln!(self.out, ";")?; + } + + writeln!(self.out, "{}}}", level)?; + self.write_barrier(crate::Barrier::WORK_GROUP, level) + } + /// Helper method used to write statements /// /// # Notes diff --git a/src/back/mod.rs b/src/back/mod.rs index d8e016c00..56223ac2b 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -47,6 +47,17 @@ enum FunctionType { EntryPoint(crate::proc::EntryPointIndex), } +impl FunctionType { + fn is_compute_entry_point(&self, module: &crate::Module) -> bool { + match *self { + FunctionType::EntryPoint(index) => { + module.entry_points[index as usize].stage == crate::ShaderStage::Compute + } + _ => false, + } + } +} + /// Helper structure that stores data needed when writing the function struct FunctionCtx<'a> { /// The current function being written diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 4c0177173..679e5ed29 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -209,6 +209,8 @@ pub struct Options { /// Bounds checking policies. #[cfg_attr(feature = "deserialize", serde(default))] pub bounds_check_policies: index::BoundsCheckPolicies, + /// Should workgroup variables be zero initialized (by polyfilling)? + pub zero_initialize_workgroup_memory: bool, } impl Default for Options { @@ -220,6 +222,7 @@ impl Default for Options { spirv_cross_compatibility: false, fake_missing_bindings: true, bounds_check_policies: index::BoundsCheckPolicies::default(), + zero_initialize_workgroup_memory: true, } } } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 331f7a2db..5b505b358 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3618,6 +3618,8 @@ impl Writer { is_first_argument = false; } + let mut global_invocation_id = None; + // Then pass the remaining arguments not included in the varyings // struct. // @@ -3629,7 +3631,7 @@ impl Writer { let mut flattened_member_names = FastHashMap::default(); for &(ref name_key, ty, binding) in flattened_arguments.iter() { let binding = match binding { - Some(ref binding @ &crate::Binding::BuiltIn { .. }) => binding, + Some(binding @ &crate::Binding::BuiltIn { .. }) => binding, _ => continue, }; let name = if let NameKey::StructMember(ty, index) = *name_key { @@ -3642,6 +3644,11 @@ impl Writer { } else { &self.names[name_key] }; + + if binding == &crate::Binding::BuiltIn(crate::BuiltIn::GlobalInvocationId) { + global_invocation_id = Some(name_key); + } + let ty_name = TypeContext { handle: ty, module, @@ -3662,6 +3669,23 @@ impl Writer { writeln!(self.out)?; } + let need_workgroup_variables_initialization = + self.need_workgroup_variables_initialization(options, ep, module, fun_info); + + if need_workgroup_variables_initialization && global_invocation_id.is_none() { + let separator = if is_first_argument { + is_first_argument = false; + ' ' + } else { + ',' + }; + writeln!( + self.out, + "{} {}::uint3 __global_invocation_id [[thread_position_in_grid]]", + separator, NAMESPACE + )?; + } + // Those global variables used by this entry point and its callees // get passed as arguments. `Private` globals are an exception, they // don't outlive this invocation, so we declare them below as locals @@ -3744,6 +3768,15 @@ impl Writer { // end of the entry point argument list writeln!(self.out, ") {{")?; + if need_workgroup_variables_initialization { + self.write_workgroup_variables_initialization( + module, + mod_info, + fun_info, + global_invocation_id, + )?; + } + // Metal doesn't support private mutable variables outside of functions, // so we put them here, just like the locals. for (handle, var) in module.global_variables.iter() { @@ -3939,6 +3972,208 @@ impl Writer { } } +/// Initializing workgroup variables is more tricky for Metal because we have to deal +/// with atomics at the type-level (which don't have a copy constructor). +mod workgroup_mem_init { + use crate::EntryPoint; + + use super::*; + + enum Access { + GlobalVariable(Handle), + StructMember(Handle, u32), + Array(usize), + } + + impl Access { + fn write( + &self, + writer: &mut W, + names: &FastHashMap, + ) -> Result<(), core::fmt::Error> { + match *self { + Access::GlobalVariable(handle) => { + write!(writer, "{}", &names[&NameKey::GlobalVariable(handle)]) + } + Access::StructMember(handle, index) => { + write!(writer, ".{}", &names[&NameKey::StructMember(handle, index)]) + } + Access::Array(depth) => write!(writer, ".{}[__i{}]", WRAPPED_ARRAY_FIELD, depth), + } + } + } + + struct AccessStack { + stack: Vec, + array_depth: usize, + } + + impl AccessStack { + const fn new() -> Self { + Self { + stack: Vec::new(), + array_depth: 0, + } + } + + fn enter_array(&mut self, cb: impl FnOnce(&mut Self, usize) -> R) -> R { + let array_depth = self.array_depth; + self.stack.push(Access::Array(array_depth)); + self.array_depth += 1; + let res = cb(self, array_depth); + self.stack.pop(); + self.array_depth -= 1; + res + } + + fn enter(&mut self, new: Access, cb: impl FnOnce(&mut Self) -> R) -> R { + self.stack.push(new); + let res = cb(self); + self.stack.pop(); + res + } + + fn write( + &self, + writer: &mut W, + names: &FastHashMap, + ) -> Result<(), core::fmt::Error> { + for next in self.stack.iter() { + next.write(writer, names)?; + } + Ok(()) + } + } + + impl Writer { + pub(super) fn need_workgroup_variables_initialization( + &mut self, + options: &Options, + ep: &EntryPoint, + module: &crate::Module, + fun_info: &valid::FunctionInfo, + ) -> bool { + options.zero_initialize_workgroup_memory + && ep.stage == crate::ShaderStage::Compute + && module.global_variables.iter().any(|(handle, var)| { + !fun_info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup + }) + } + + pub(super) fn write_workgroup_variables_initialization( + &mut self, + module: &crate::Module, + module_info: &valid::ModuleInfo, + fun_info: &valid::FunctionInfo, + global_invocation_id: Option<&NameKey>, + ) -> BackendResult { + let level = back::Level(1); + + writeln!( + self.out, + "{}if ({}::all({} == {}::uint3(0u))) {{", + level, + NAMESPACE, + global_invocation_id + .map(|name_key| self.names[name_key].as_str()) + .unwrap_or("__global_invocation_id"), + NAMESPACE, + )?; + + let mut access_stack = AccessStack::new(); + + let vars = module.global_variables.iter().filter(|&(handle, var)| { + !fun_info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup + }); + + for (handle, var) in vars { + access_stack.enter(Access::GlobalVariable(handle), |access_stack| { + self.write_workgroup_variable_initialization( + module, + module_info, + var.ty, + access_stack, + level.next(), + ) + })?; + } + + writeln!(self.out, "{}}}", level)?; + self.write_barrier(crate::Barrier::WORK_GROUP, level) + } + + fn write_workgroup_variable_initialization( + &mut self, + module: &crate::Module, + module_info: &valid::ModuleInfo, + ty: Handle, + access_stack: &mut AccessStack, + level: back::Level, + ) -> BackendResult { + if module_info[ty].contains(valid::TypeFlags::CONSTRUCTIBLE) { + write!(self.out, "{}", level)?; + access_stack.write(&mut self.out, &self.names)?; + writeln!(self.out, " = {{}};")?; + } else { + match module.types[ty].inner { + crate::TypeInner::Atomic { .. } => { + write!( + self.out, + "{}{}::atomic_store_explicit({}", + level, NAMESPACE, ATOMIC_REFERENCE + )?; + access_stack.write(&mut self.out, &self.names)?; + writeln!(self.out, ", 0, {}::memory_order_relaxed);", NAMESPACE)?; + } + crate::TypeInner::Array { base, size, .. } => { + let count = match size.to_indexable_length(module).expect("Bad array size") + { + proc::IndexableLength::Known(count) => count, + proc::IndexableLength::Dynamic => unreachable!(), + }; + + access_stack.enter_array(|access_stack, array_depth| { + writeln!( + self.out, + "{}for (int __i{} = 0; __i{} < {}; __i{}++) {{", + level, array_depth, array_depth, count, array_depth + )?; + self.write_workgroup_variable_initialization( + module, + module_info, + base, + access_stack, + level.next(), + )?; + writeln!(self.out, "{}}}", level)?; + BackendResult::Ok(()) + })?; + } + crate::TypeInner::Struct { ref members, .. } => { + for (index, member) in members.iter().enumerate() { + access_stack.enter( + Access::StructMember(ty, index as u32), + |access_stack| { + self.write_workgroup_variable_initialization( + module, + module_info, + member.ty, + access_stack, + level, + ) + }, + )?; + } + } + _ => unreachable!(), + } + } + + Ok(()) + } + } +} + #[test] fn test_stack_size() { use crate::valid::{Capabilities, ValidationFlags}; diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 544f5ca4f..e19d825a0 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -582,6 +582,7 @@ pub struct Writer { annotations: Vec, flags: WriterFlags, bounds_check_policies: BoundsCheckPolicies, + zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode, void_type: Word, //TODO: convert most of these into vectors, addressable by handle indices lookup_type: crate::FastHashMap, @@ -630,6 +631,15 @@ pub struct BindingInfo { // Using `BTreeMap` instead of `HashMap` so that we can hash itself. pub type BindingMap = std::collections::BTreeMap; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ZeroInitializeWorkgroupMemoryMode { + /// Via `VK_KHR_zero_initialize_workgroup_memory` or Vulkan 1.3 + Native, + /// Via assignments + barrier + Polyfill, + None, +} + #[derive(Debug, Clone)] pub struct Options { /// (Major, Minor) target version of the SPIR-V. @@ -650,6 +660,9 @@ pub struct Options { /// How should generate code handle array, vector, matrix, or image texel /// indices that are out of range? pub bounds_check_policies: BoundsCheckPolicies, + + /// Dictates the way workgroup variables should be zero initialized + pub zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode, } impl Default for Options { @@ -666,6 +679,7 @@ impl Default for Options { binding_map: BindingMap::default(), capabilities: None, bounds_check_policies: crate::proc::BoundsCheckPolicies::default(), + zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode::Polyfill, } } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index d61ae08bf..f19d83e45 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -65,6 +65,7 @@ impl Writer { annotations: vec![], flags: options.flags, bounds_check_policies: options.bounds_check_policies, + zero_initialize_workgroup_memory: options.zero_initialize_workgroup_memory, void_type, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), @@ -102,6 +103,7 @@ impl Writer { // Copied from the old Writer: flags: self.flags, bounds_check_policies: self.bounds_check_policies, + zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory, capabilities_available: take(&mut self.capabilities_available), binding_map: take(&mut self.binding_map), @@ -248,6 +250,16 @@ impl Writer { self.get_type_id(local_type.into()) } + pub(super) fn get_uint3_type_id(&mut self) -> Word { + let local_type = LocalType::Value { + vector_size: Some(crate::VectorSize::Tri), + kind: crate::ScalarKind::Uint, + width: 4, + pointer_space: None, + }; + self.get_type_id(local_type.into()) + } + pub(super) fn get_float_pointer_type_id(&mut self, class: spirv::StorageClass) -> Word { let lookup_type = LookupType::Local(LocalType::Value { vector_size: None, @@ -267,6 +279,25 @@ impl Writer { } } + pub(super) fn get_uint3_pointer_type_id(&mut self, class: spirv::StorageClass) -> Word { + let lookup_type = LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Tri), + kind: crate::ScalarKind::Uint, + width: 4, + pointer_space: Some(class), + }); + if let Some(&id) = self.lookup_type.get(&lookup_type) { + id + } else { + let id = self.id_gen.next(); + let ty_id = self.get_uint3_type_id(); + let instruction = Instruction::type_pointer(id, class, ty_id); + instruction.to_words(&mut self.logical_layout.declarations); + self.lookup_type.insert(lookup_type, id); + id + } + } + pub(super) fn get_bool_type_id(&mut self) -> Word { let local_type = LocalType::Value { vector_size: None, @@ -277,6 +308,16 @@ impl Writer { self.get_type_id(local_type.into()) } + pub(super) fn get_bool3_type_id(&mut self) -> Word { + let local_type = LocalType::Value { + vector_size: Some(crate::VectorSize::Tri), + kind: crate::ScalarKind::Bool, + width: 1, + pointer_space: None, + }; + self.get_type_id(local_type.into()) + } + pub(super) fn decorate(&mut self, id: Word, decoration: spirv::Decoration, operands: &[Word]) { self.annotations .push(Instruction::decorate(id, decoration, operands)); @@ -326,6 +367,8 @@ impl Writer { results: Vec::new(), }; + let mut global_invocation_id = None; + let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); for argument in ir_function.arguments.iter() { let class = spirv::StorageClass::Input; @@ -356,6 +399,11 @@ impl Writer { prelude .body .push(Instruction::load(argument_type_id, id, varying_id, None)); + + if binding == &crate::Binding::BuiltIn(crate::BuiltIn::GlobalInvocationId) { + global_invocation_id = Some(id); + } + id } else if let crate::TypeInner::Struct { ref members, .. } = ir_module.types[argument.ty].inner @@ -380,6 +428,10 @@ impl Writer { .body .push(Instruction::load(type_id, id, varying_id, None)); constituent_ids.push(id); + + if binding == &crate::Binding::BuiltIn(crate::BuiltIn::GlobalInvocationId) { + global_invocation_id = Some(id); + } } prelude.body.push(Instruction::composite_construct( argument_type_id, @@ -595,10 +647,39 @@ impl Writer { } } - let main_id = context.gen_id(); + let next_id = context.gen_id(); + context .function - .consume(prelude, Instruction::branch(main_id)); + .consume(prelude, Instruction::branch(next_id)); + + let workgroup_vars_init_exit_block_id = + match (context.writer.zero_initialize_workgroup_memory, interface) { + ( + super::ZeroInitializeWorkgroupMemoryMode::Polyfill, + Some( + ref mut interface @ FunctionInterface { + stage: crate::ShaderStage::Compute, + .. + }, + ), + ) => context.writer.generate_workgroup_vars_init_block( + next_id, + ir_module, + info, + global_invocation_id, + interface, + context.function, + ), + _ => None, + }; + + let main_id = if let Some(exit_id) = workgroup_vars_init_exit_block_id { + exit_id + } else { + next_id + }; + context.write_block( main_id, &ir_function.body, @@ -1143,6 +1224,113 @@ impl Writer { )); } + fn generate_workgroup_vars_init_block( + &mut self, + entry_id: Word, + ir_module: &crate::Module, + info: &FunctionInfo, + global_invocation_id: Option, + interface: &mut FunctionInterface, + function: &mut Function, + ) -> Option { + let body = ir_module + .global_variables + .iter() + .filter(|&(handle, var)| { + !info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup + }) + .map(|(handle, var)| { + // It's safe to use `var_id` here, not `access_id`, because only + // variables in the `Uniform` and `StorageBuffer` address spaces + // get wrapped, and we're initializing `WorkGroup` variables. + let var_id = self.global_variables[handle.index()].var_id; + let var_type_id = self.get_type_id(LookupType::Handle(var.ty)); + let init_word = self.write_constant_null(var_type_id); + Instruction::store(var_id, init_word, None) + }) + .collect::>(); + + if body.is_empty() { + return None; + } + + let uint3_type_id = self.get_uint3_type_id(); + + let mut pre_if_block = Block::new(entry_id); + + let global_invocation_id = if let Some(global_invocation_id) = global_invocation_id { + global_invocation_id + } else { + let varying_id = self.id_gen.next(); + let class = spirv::StorageClass::Input; + let pointer_type_id = self.get_uint3_pointer_type_id(class); + + Instruction::variable(pointer_type_id, varying_id, class, None) + .to_words(&mut self.logical_layout.declarations); + + self.decorate( + varying_id, + spirv::Decoration::BuiltIn, + &[spirv::BuiltIn::GlobalInvocationId as u32], + ); + + interface.varying_ids.push(varying_id); + let id = self.id_gen.next(); + pre_if_block + .body + .push(Instruction::load(uint3_type_id, id, varying_id, None)); + + id + }; + + let zero_id = self.write_constant_null(uint3_type_id); + let bool3_type_id = self.get_bool3_type_id(); + + let eq_id = self.id_gen.next(); + pre_if_block.body.push(Instruction::binary( + spirv::Op::IEqual, + bool3_type_id, + eq_id, + global_invocation_id, + zero_id, + )); + + let condition_id = self.id_gen.next(); + let bool_type_id = self.get_bool_type_id(); + pre_if_block.body.push(Instruction::relational( + spirv::Op::All, + bool_type_id, + condition_id, + eq_id, + )); + + let merge_id = self.id_gen.next(); + pre_if_block.body.push(Instruction::selection_merge( + merge_id, + spirv::SelectionControl::NONE, + )); + + let accept_id = self.id_gen.next(); + function.consume( + pre_if_block, + Instruction::branch_conditional(condition_id, accept_id, merge_id), + ); + + let accept_block = Block { + label_id: accept_id, + body, + }; + function.consume(accept_block, Instruction::branch(merge_id)); + + let mut post_if_block = Block::new(merge_id); + + self.write_barrier(crate::Barrier::WORK_GROUP, &mut post_if_block); + + let next_id = self.id_gen.next(); + function.consume(post_if_block, Instruction::branch(next_id)); + Some(next_id) + } + /// Generate an `OpVariable` for one value in an [`EntryPoint`]'s IO interface. /// /// The [`Binding`]s of the arguments and result of an [`EntryPoint`]'s @@ -1414,8 +1602,9 @@ impl Writer { } }; - let init_word = match global_variable.space { - crate::AddressSpace::Private => { + let init_word = match (global_variable.space, self.zero_initialize_workgroup_memory) { + (crate::AddressSpace::Private, _) + | (crate::AddressSpace::WorkGroup, super::ZeroInitializeWorkgroupMemoryMode::Native) => { init_word.or_else(|| Some(self.write_constant_null(inner_type_id))) } _ => init_word, diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 8408e4cb6..af45e4f97 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -33,5 +33,6 @@ inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/binding-arrays.param.ron b/tests/in/binding-arrays.param.ron index 2d3e15263..ad5b0ee31 100644 --- a/tests/in/binding-arrays.param.ron +++ b/tests/in/binding-arrays.param.ron @@ -15,6 +15,7 @@ }, fake_missing_bindings: true, special_constants_binding: None, + zero_initialize_workgroup_memory: true, ), msl: ( lang_version: (2, 0), @@ -29,6 +30,7 @@ inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: true, + zero_initialize_workgroup_memory: true, ), spv: ( version: (1, 1), diff --git a/tests/in/bitcast.params.ron b/tests/in/bitcast.params.ron index fb45784e5..324cd4a51 100644 --- a/tests/in/bitcast.params.ron +++ b/tests/in/bitcast.params.ron @@ -11,5 +11,6 @@ inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/bits.param.ron b/tests/in/bits.param.ron index fb45784e5..324cd4a51 100644 --- a/tests/in/bits.param.ron +++ b/tests/in/bits.param.ron @@ -11,5 +11,6 @@ inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index 91181f7dd..e6d752fca 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -19,5 +19,6 @@ inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/bounds-check-image-restrict.param.ron b/tests/in/bounds-check-image-restrict.param.ron index e91f7fc24..fedcf8407 100644 --- a/tests/in/bounds-check-image-restrict.param.ron +++ b/tests/in/bounds-check-image-restrict.param.ron @@ -10,5 +10,6 @@ version: Desktop(430), writer_flags: (bits: 0), binding_map: { }, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/tests/in/bounds-check-image-rzsw.param.ron index 72ccb27e9..40974004c 100644 --- a/tests/in/bounds-check-image-rzsw.param.ron +++ b/tests/in/bounds-check-image-rzsw.param.ron @@ -10,5 +10,6 @@ version: Desktop(430), writer_flags: (bits: 0), binding_map: { }, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/extra.param.ron b/tests/in/extra.param.ron index ba9e08759..051dee643 100644 --- a/tests/in/extra.param.ron +++ b/tests/in/extra.param.ron @@ -13,5 +13,6 @@ inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/functions-webgl.param.ron b/tests/in/functions-webgl.param.ron index 8ac016ad2..862e6a5d0 100644 --- a/tests/in/functions-webgl.param.ron +++ b/tests/in/functions-webgl.param.ron @@ -6,5 +6,6 @@ ), writer_flags: (bits: 0), binding_map: {}, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index eeb45b0d7..5df3e3b9c 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -12,6 +12,7 @@ binding_map: {}, fake_missing_bindings: false, special_constants_binding: Some((space: 1, register: 0)), + zero_initialize_workgroup_memory: true, ), wgsl: ( explicit_types: true, @@ -22,6 +23,7 @@ inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, ), msl_pipeline: ( allow_point_size: true, diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index cb08368c8..a885c9032 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -10,5 +10,6 @@ version: Desktop(400), writer_flags: (bits: 0), binding_map: {}, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/multiview_webgl.param.ron b/tests/in/multiview_webgl.param.ron index 720b51fbb..a8bc09664 100644 --- a/tests/in/multiview_webgl.param.ron +++ b/tests/in/multiview_webgl.param.ron @@ -6,6 +6,7 @@ ), writer_flags: (bits: 0), binding_map: {}, + zero_initialize_workgroup_memory: true, ), glsl_multiview: Some(2), ) diff --git a/tests/in/padding.param.ron b/tests/in/padding.param.ron index 9e20176ba..41af2916a 100644 --- a/tests/in/padding.param.ron +++ b/tests/in/padding.param.ron @@ -18,5 +18,6 @@ inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/push-constants.param.ron b/tests/in/push-constants.param.ron index a5cfe142c..46874a15a 100644 --- a/tests/in/push-constants.param.ron +++ b/tests/in/push-constants.param.ron @@ -7,6 +7,7 @@ ), writer_flags: (bits: 0), binding_map: {}, + zero_initialize_workgroup_memory: true, ), hlsl: ( shader_model: V5_1, @@ -14,5 +15,6 @@ fake_missing_bindings: true, special_constants_binding: Some((space: 1, register: 0)), push_constants_target: Some((space: 0, register: 0)), + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index 568b96189..db93369f6 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -11,5 +11,6 @@ ), writer_flags: (bits: 0), binding_map: {}, + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index b90f2e5a2..905721c91 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -35,6 +35,7 @@ ], spirv_cross_compatibility: false, fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, ), glsl: ( version: Embedded( @@ -46,6 +47,7 @@ (group: 0, binding: 0): 0, (group: 0, binding: 1): 0, }, + zero_initialize_workgroup_memory: true, ), hlsl: ( shader_model: V5_1, @@ -56,5 +58,6 @@ }, fake_missing_bindings: false, special_constants_binding: Some((space: 0, register: 1)), + zero_initialize_workgroup_memory: true, ), ) diff --git a/tests/in/workgroup-var-init.param.ron b/tests/in/workgroup-var-init.param.ron new file mode 100644 index 000000000..fd10e95d6 --- /dev/null +++ b/tests/in/workgroup-var-init.param.ron @@ -0,0 +1,22 @@ +( + spv: ( + version: (1, 1), + debug: true, + adjust_coordinate_space: false, + ), + msl: ( + lang_version: (2, 0), + per_stage_map: ( + cs: ( + resources: { + (group: 0, binding: 0): (buffer: Some(0), mutable: true), + }, + sizes_buffer: None, + ), + ), + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, + ), +) \ No newline at end of file diff --git a/tests/in/workgroup-var-init.wgsl b/tests/in/workgroup-var-init.wgsl new file mode 100644 index 000000000..8df2bcf4a --- /dev/null +++ b/tests/in/workgroup-var-init.wgsl @@ -0,0 +1,15 @@ +struct WStruct { + arr: array, + atom: atomic, + atom_arr: array, 8>, 8>, +} + +var w_mem: WStruct; + +@group(0) @binding(0) +var output: array; + +@compute @workgroup_size(1) +fn main() { + output = w_mem.arr; +} \ No newline at end of file diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/tests/out/glsl/access.assign_through_ptr.Compute.glsl index aafc30b90..1306fe514 100644 --- a/tests/out/glsl/access.assign_through_ptr.Compute.glsl +++ b/tests/out/glsl/access.assign_through_ptr.Compute.glsl @@ -37,6 +37,11 @@ void assign_through_ptr_fn(inout uint p) { } void main() { + if (gl_GlobalInvocationID == uvec3(0u)) { + val = 0u; + } + memoryBarrierShared(); + barrier(); assign_through_ptr_fn(val); return; } diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index e77585f0b..b5b357105 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -51,6 +51,12 @@ void test_msl_packed_vec3_() { } void main() { + if (gl_GlobalInvocationID == uvec3(0u)) { + wg = float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); + at_1 = 0u; + } + memoryBarrierShared(); + barrier(); float Foo = 0.0; bool at = false; test_msl_packed_vec3_(); diff --git a/tests/out/glsl/workgroup-var-init.main.Compute.glsl b/tests/out/glsl/workgroup-var-init.main.Compute.glsl new file mode 100644 index 000000000..da55fea95 --- /dev/null +++ b/tests/out/glsl/workgroup-var-init.main.Compute.glsl @@ -0,0 +1,28 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +struct WStruct { + uint arr[512]; + int atom; + int atom_arr[8][8]; +}; +shared WStruct w_mem; + +layout(std430) buffer type_1_block_0Compute { uint _group_0_binding_0_cs[512]; }; + + +void main() { + if (gl_GlobalInvocationID == uvec3(0u)) { + w_mem = WStruct(uint[512](0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u), 0, int[8][8](int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0))); + } + memoryBarrierShared(); + barrier(); + uint _e3[512] = w_mem.arr; + _group_0_binding_0_cs = _e3; + return; +} + diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 68ba8ae28..9f898b0e9 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -326,8 +326,12 @@ void atomics() } [numthreads(1, 1, 1)] -void assign_through_ptr() +void assign_through_ptr(uint3 __global_invocation_id : SV_DispatchThreadID) { + if (all(__global_invocation_id == uint3(0u, 0u, 0u))) { + val = (uint)0; + } + GroupMemoryBarrierWithGroupSync(); assign_through_ptr_fn(val); return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index d941f8e09..6047b8dca 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -106,8 +106,13 @@ uint NagaBufferLength(ByteAddressBuffer buffer) } [numthreads(1, 1, 1)] -void main() +void main(uint3 __global_invocation_id : SV_DispatchThreadID) { + if (all(__global_invocation_id == uint3(0u, 0u, 0u))) { + wg = (float[10])0; + at_1 = (uint)0; + } + GroupMemoryBarrierWithGroupSync(); float Foo = (float)0; bool at = (bool)0; diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 99d5ecccb..34ef1ccb4 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -75,8 +75,12 @@ FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) } [numthreads(1, 1, 1)] -void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThreadID, uint local_index : SV_GroupIndex, uint3 wg_id : SV_GroupID, uint3 num_wgs : SV_GroupID) +void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThreadID, uint local_index : SV_GroupIndex, uint3 wg_id : SV_GroupID, uint3 num_wgs : SV_GroupID, uint3 __global_invocation_id : SV_DispatchThreadID) { + if (all(__global_invocation_id == uint3(0u, 0u, 0u))) { + output = (uint[1])0; + } + GroupMemoryBarrierWithGroupSync(); output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x); return; } diff --git a/tests/out/hlsl/workgroup-var-init.hlsl b/tests/out/hlsl/workgroup-var-init.hlsl new file mode 100644 index 000000000..db48d36c0 --- /dev/null +++ b/tests/out/hlsl/workgroup-var-init.hlsl @@ -0,0 +1,535 @@ + +struct WStruct { + uint arr[512]; + int atom; + int atom_arr[8][8]; +}; + +groupshared WStruct w_mem; +RWByteAddressBuffer output : register(u0); + +[numthreads(1, 1, 1)] +void main(uint3 __global_invocation_id : SV_DispatchThreadID) +{ + if (all(__global_invocation_id == uint3(0u, 0u, 0u))) { + w_mem = (WStruct)0; + } + GroupMemoryBarrierWithGroupSync(); + uint _expr3[512] = w_mem.arr; + { + uint _value2[512] = _expr3; + output.Store(0, asuint(_value2[0])); + output.Store(4, asuint(_value2[1])); + output.Store(8, asuint(_value2[2])); + output.Store(12, asuint(_value2[3])); + output.Store(16, asuint(_value2[4])); + output.Store(20, asuint(_value2[5])); + output.Store(24, asuint(_value2[6])); + output.Store(28, asuint(_value2[7])); + output.Store(32, asuint(_value2[8])); + output.Store(36, asuint(_value2[9])); + output.Store(40, asuint(_value2[10])); + output.Store(44, asuint(_value2[11])); + output.Store(48, asuint(_value2[12])); + output.Store(52, asuint(_value2[13])); + output.Store(56, asuint(_value2[14])); + output.Store(60, asuint(_value2[15])); + output.Store(64, asuint(_value2[16])); + output.Store(68, asuint(_value2[17])); + output.Store(72, asuint(_value2[18])); + output.Store(76, asuint(_value2[19])); + output.Store(80, asuint(_value2[20])); + output.Store(84, asuint(_value2[21])); + output.Store(88, asuint(_value2[22])); + output.Store(92, asuint(_value2[23])); + output.Store(96, asuint(_value2[24])); + output.Store(100, asuint(_value2[25])); + output.Store(104, asuint(_value2[26])); + output.Store(108, asuint(_value2[27])); + output.Store(112, asuint(_value2[28])); + output.Store(116, asuint(_value2[29])); + output.Store(120, asuint(_value2[30])); + output.Store(124, asuint(_value2[31])); + output.Store(128, asuint(_value2[32])); + output.Store(132, asuint(_value2[33])); + output.Store(136, asuint(_value2[34])); + output.Store(140, asuint(_value2[35])); + output.Store(144, asuint(_value2[36])); + output.Store(148, asuint(_value2[37])); + output.Store(152, asuint(_value2[38])); + output.Store(156, asuint(_value2[39])); + output.Store(160, asuint(_value2[40])); + output.Store(164, asuint(_value2[41])); + output.Store(168, asuint(_value2[42])); + output.Store(172, asuint(_value2[43])); + output.Store(176, asuint(_value2[44])); + output.Store(180, asuint(_value2[45])); + output.Store(184, asuint(_value2[46])); + output.Store(188, asuint(_value2[47])); + output.Store(192, asuint(_value2[48])); + output.Store(196, asuint(_value2[49])); + output.Store(200, asuint(_value2[50])); + output.Store(204, asuint(_value2[51])); + output.Store(208, asuint(_value2[52])); + output.Store(212, asuint(_value2[53])); + output.Store(216, asuint(_value2[54])); + output.Store(220, asuint(_value2[55])); + output.Store(224, asuint(_value2[56])); + output.Store(228, asuint(_value2[57])); + output.Store(232, asuint(_value2[58])); + output.Store(236, asuint(_value2[59])); + output.Store(240, asuint(_value2[60])); + output.Store(244, asuint(_value2[61])); + output.Store(248, asuint(_value2[62])); + output.Store(252, asuint(_value2[63])); + output.Store(256, asuint(_value2[64])); + output.Store(260, asuint(_value2[65])); + output.Store(264, asuint(_value2[66])); + output.Store(268, asuint(_value2[67])); + output.Store(272, asuint(_value2[68])); + output.Store(276, asuint(_value2[69])); + output.Store(280, asuint(_value2[70])); + output.Store(284, asuint(_value2[71])); + output.Store(288, asuint(_value2[72])); + output.Store(292, asuint(_value2[73])); + output.Store(296, asuint(_value2[74])); + output.Store(300, asuint(_value2[75])); + output.Store(304, asuint(_value2[76])); + output.Store(308, asuint(_value2[77])); + output.Store(312, asuint(_value2[78])); + output.Store(316, asuint(_value2[79])); + output.Store(320, asuint(_value2[80])); + output.Store(324, asuint(_value2[81])); + output.Store(328, asuint(_value2[82])); + output.Store(332, asuint(_value2[83])); + output.Store(336, asuint(_value2[84])); + output.Store(340, asuint(_value2[85])); + output.Store(344, asuint(_value2[86])); + output.Store(348, asuint(_value2[87])); + output.Store(352, asuint(_value2[88])); + output.Store(356, asuint(_value2[89])); + output.Store(360, asuint(_value2[90])); + output.Store(364, asuint(_value2[91])); + output.Store(368, asuint(_value2[92])); + output.Store(372, asuint(_value2[93])); + output.Store(376, asuint(_value2[94])); + output.Store(380, asuint(_value2[95])); + output.Store(384, asuint(_value2[96])); + output.Store(388, asuint(_value2[97])); + output.Store(392, asuint(_value2[98])); + output.Store(396, asuint(_value2[99])); + output.Store(400, asuint(_value2[100])); + output.Store(404, asuint(_value2[101])); + output.Store(408, asuint(_value2[102])); + output.Store(412, asuint(_value2[103])); + output.Store(416, asuint(_value2[104])); + output.Store(420, asuint(_value2[105])); + output.Store(424, asuint(_value2[106])); + output.Store(428, asuint(_value2[107])); + output.Store(432, asuint(_value2[108])); + output.Store(436, asuint(_value2[109])); + output.Store(440, asuint(_value2[110])); + output.Store(444, asuint(_value2[111])); + output.Store(448, asuint(_value2[112])); + output.Store(452, asuint(_value2[113])); + output.Store(456, asuint(_value2[114])); + output.Store(460, asuint(_value2[115])); + output.Store(464, asuint(_value2[116])); + output.Store(468, asuint(_value2[117])); + output.Store(472, asuint(_value2[118])); + output.Store(476, asuint(_value2[119])); + output.Store(480, asuint(_value2[120])); + output.Store(484, asuint(_value2[121])); + output.Store(488, asuint(_value2[122])); + output.Store(492, asuint(_value2[123])); + output.Store(496, asuint(_value2[124])); + output.Store(500, asuint(_value2[125])); + output.Store(504, asuint(_value2[126])); + output.Store(508, asuint(_value2[127])); + output.Store(512, asuint(_value2[128])); + output.Store(516, asuint(_value2[129])); + output.Store(520, asuint(_value2[130])); + output.Store(524, asuint(_value2[131])); + output.Store(528, asuint(_value2[132])); + output.Store(532, asuint(_value2[133])); + output.Store(536, asuint(_value2[134])); + output.Store(540, asuint(_value2[135])); + output.Store(544, asuint(_value2[136])); + output.Store(548, asuint(_value2[137])); + output.Store(552, asuint(_value2[138])); + output.Store(556, asuint(_value2[139])); + output.Store(560, asuint(_value2[140])); + output.Store(564, asuint(_value2[141])); + output.Store(568, asuint(_value2[142])); + output.Store(572, asuint(_value2[143])); + output.Store(576, asuint(_value2[144])); + output.Store(580, asuint(_value2[145])); + output.Store(584, asuint(_value2[146])); + output.Store(588, asuint(_value2[147])); + output.Store(592, asuint(_value2[148])); + output.Store(596, asuint(_value2[149])); + output.Store(600, asuint(_value2[150])); + output.Store(604, asuint(_value2[151])); + output.Store(608, asuint(_value2[152])); + output.Store(612, asuint(_value2[153])); + output.Store(616, asuint(_value2[154])); + output.Store(620, asuint(_value2[155])); + output.Store(624, asuint(_value2[156])); + output.Store(628, asuint(_value2[157])); + output.Store(632, asuint(_value2[158])); + output.Store(636, asuint(_value2[159])); + output.Store(640, asuint(_value2[160])); + output.Store(644, asuint(_value2[161])); + output.Store(648, asuint(_value2[162])); + output.Store(652, asuint(_value2[163])); + output.Store(656, asuint(_value2[164])); + output.Store(660, asuint(_value2[165])); + output.Store(664, asuint(_value2[166])); + output.Store(668, asuint(_value2[167])); + output.Store(672, asuint(_value2[168])); + output.Store(676, asuint(_value2[169])); + output.Store(680, asuint(_value2[170])); + output.Store(684, asuint(_value2[171])); + output.Store(688, asuint(_value2[172])); + output.Store(692, asuint(_value2[173])); + output.Store(696, asuint(_value2[174])); + output.Store(700, asuint(_value2[175])); + output.Store(704, asuint(_value2[176])); + output.Store(708, asuint(_value2[177])); + output.Store(712, asuint(_value2[178])); + output.Store(716, asuint(_value2[179])); + output.Store(720, asuint(_value2[180])); + output.Store(724, asuint(_value2[181])); + output.Store(728, asuint(_value2[182])); + output.Store(732, asuint(_value2[183])); + output.Store(736, asuint(_value2[184])); + output.Store(740, asuint(_value2[185])); + output.Store(744, asuint(_value2[186])); + output.Store(748, asuint(_value2[187])); + output.Store(752, asuint(_value2[188])); + output.Store(756, asuint(_value2[189])); + output.Store(760, asuint(_value2[190])); + output.Store(764, asuint(_value2[191])); + output.Store(768, asuint(_value2[192])); + output.Store(772, asuint(_value2[193])); + output.Store(776, asuint(_value2[194])); + output.Store(780, asuint(_value2[195])); + output.Store(784, asuint(_value2[196])); + output.Store(788, asuint(_value2[197])); + output.Store(792, asuint(_value2[198])); + output.Store(796, asuint(_value2[199])); + output.Store(800, asuint(_value2[200])); + output.Store(804, asuint(_value2[201])); + output.Store(808, asuint(_value2[202])); + output.Store(812, asuint(_value2[203])); + output.Store(816, asuint(_value2[204])); + output.Store(820, asuint(_value2[205])); + output.Store(824, asuint(_value2[206])); + output.Store(828, asuint(_value2[207])); + output.Store(832, asuint(_value2[208])); + output.Store(836, asuint(_value2[209])); + output.Store(840, asuint(_value2[210])); + output.Store(844, asuint(_value2[211])); + output.Store(848, asuint(_value2[212])); + output.Store(852, asuint(_value2[213])); + output.Store(856, asuint(_value2[214])); + output.Store(860, asuint(_value2[215])); + output.Store(864, asuint(_value2[216])); + output.Store(868, asuint(_value2[217])); + output.Store(872, asuint(_value2[218])); + output.Store(876, asuint(_value2[219])); + output.Store(880, asuint(_value2[220])); + output.Store(884, asuint(_value2[221])); + output.Store(888, asuint(_value2[222])); + output.Store(892, asuint(_value2[223])); + output.Store(896, asuint(_value2[224])); + output.Store(900, asuint(_value2[225])); + output.Store(904, asuint(_value2[226])); + output.Store(908, asuint(_value2[227])); + output.Store(912, asuint(_value2[228])); + output.Store(916, asuint(_value2[229])); + output.Store(920, asuint(_value2[230])); + output.Store(924, asuint(_value2[231])); + output.Store(928, asuint(_value2[232])); + output.Store(932, asuint(_value2[233])); + output.Store(936, asuint(_value2[234])); + output.Store(940, asuint(_value2[235])); + output.Store(944, asuint(_value2[236])); + output.Store(948, asuint(_value2[237])); + output.Store(952, asuint(_value2[238])); + output.Store(956, asuint(_value2[239])); + output.Store(960, asuint(_value2[240])); + output.Store(964, asuint(_value2[241])); + output.Store(968, asuint(_value2[242])); + output.Store(972, asuint(_value2[243])); + output.Store(976, asuint(_value2[244])); + output.Store(980, asuint(_value2[245])); + output.Store(984, asuint(_value2[246])); + output.Store(988, asuint(_value2[247])); + output.Store(992, asuint(_value2[248])); + output.Store(996, asuint(_value2[249])); + output.Store(1000, asuint(_value2[250])); + output.Store(1004, asuint(_value2[251])); + output.Store(1008, asuint(_value2[252])); + output.Store(1012, asuint(_value2[253])); + output.Store(1016, asuint(_value2[254])); + output.Store(1020, asuint(_value2[255])); + output.Store(1024, asuint(_value2[256])); + output.Store(1028, asuint(_value2[257])); + output.Store(1032, asuint(_value2[258])); + output.Store(1036, asuint(_value2[259])); + output.Store(1040, asuint(_value2[260])); + output.Store(1044, asuint(_value2[261])); + output.Store(1048, asuint(_value2[262])); + output.Store(1052, asuint(_value2[263])); + output.Store(1056, asuint(_value2[264])); + output.Store(1060, asuint(_value2[265])); + output.Store(1064, asuint(_value2[266])); + output.Store(1068, asuint(_value2[267])); + output.Store(1072, asuint(_value2[268])); + output.Store(1076, asuint(_value2[269])); + output.Store(1080, asuint(_value2[270])); + output.Store(1084, asuint(_value2[271])); + output.Store(1088, asuint(_value2[272])); + output.Store(1092, asuint(_value2[273])); + output.Store(1096, asuint(_value2[274])); + output.Store(1100, asuint(_value2[275])); + output.Store(1104, asuint(_value2[276])); + output.Store(1108, asuint(_value2[277])); + output.Store(1112, asuint(_value2[278])); + output.Store(1116, asuint(_value2[279])); + output.Store(1120, asuint(_value2[280])); + output.Store(1124, asuint(_value2[281])); + output.Store(1128, asuint(_value2[282])); + output.Store(1132, asuint(_value2[283])); + output.Store(1136, asuint(_value2[284])); + output.Store(1140, asuint(_value2[285])); + output.Store(1144, asuint(_value2[286])); + output.Store(1148, asuint(_value2[287])); + output.Store(1152, asuint(_value2[288])); + output.Store(1156, asuint(_value2[289])); + output.Store(1160, asuint(_value2[290])); + output.Store(1164, asuint(_value2[291])); + output.Store(1168, asuint(_value2[292])); + output.Store(1172, asuint(_value2[293])); + output.Store(1176, asuint(_value2[294])); + output.Store(1180, asuint(_value2[295])); + output.Store(1184, asuint(_value2[296])); + output.Store(1188, asuint(_value2[297])); + output.Store(1192, asuint(_value2[298])); + output.Store(1196, asuint(_value2[299])); + output.Store(1200, asuint(_value2[300])); + output.Store(1204, asuint(_value2[301])); + output.Store(1208, asuint(_value2[302])); + output.Store(1212, asuint(_value2[303])); + output.Store(1216, asuint(_value2[304])); + output.Store(1220, asuint(_value2[305])); + output.Store(1224, asuint(_value2[306])); + output.Store(1228, asuint(_value2[307])); + output.Store(1232, asuint(_value2[308])); + output.Store(1236, asuint(_value2[309])); + output.Store(1240, asuint(_value2[310])); + output.Store(1244, asuint(_value2[311])); + output.Store(1248, asuint(_value2[312])); + output.Store(1252, asuint(_value2[313])); + output.Store(1256, asuint(_value2[314])); + output.Store(1260, asuint(_value2[315])); + output.Store(1264, asuint(_value2[316])); + output.Store(1268, asuint(_value2[317])); + output.Store(1272, asuint(_value2[318])); + output.Store(1276, asuint(_value2[319])); + output.Store(1280, asuint(_value2[320])); + output.Store(1284, asuint(_value2[321])); + output.Store(1288, asuint(_value2[322])); + output.Store(1292, asuint(_value2[323])); + output.Store(1296, asuint(_value2[324])); + output.Store(1300, asuint(_value2[325])); + output.Store(1304, asuint(_value2[326])); + output.Store(1308, asuint(_value2[327])); + output.Store(1312, asuint(_value2[328])); + output.Store(1316, asuint(_value2[329])); + output.Store(1320, asuint(_value2[330])); + output.Store(1324, asuint(_value2[331])); + output.Store(1328, asuint(_value2[332])); + output.Store(1332, asuint(_value2[333])); + output.Store(1336, asuint(_value2[334])); + output.Store(1340, asuint(_value2[335])); + output.Store(1344, asuint(_value2[336])); + output.Store(1348, asuint(_value2[337])); + output.Store(1352, asuint(_value2[338])); + output.Store(1356, asuint(_value2[339])); + output.Store(1360, asuint(_value2[340])); + output.Store(1364, asuint(_value2[341])); + output.Store(1368, asuint(_value2[342])); + output.Store(1372, asuint(_value2[343])); + output.Store(1376, asuint(_value2[344])); + output.Store(1380, asuint(_value2[345])); + output.Store(1384, asuint(_value2[346])); + output.Store(1388, asuint(_value2[347])); + output.Store(1392, asuint(_value2[348])); + output.Store(1396, asuint(_value2[349])); + output.Store(1400, asuint(_value2[350])); + output.Store(1404, asuint(_value2[351])); + output.Store(1408, asuint(_value2[352])); + output.Store(1412, asuint(_value2[353])); + output.Store(1416, asuint(_value2[354])); + output.Store(1420, asuint(_value2[355])); + output.Store(1424, asuint(_value2[356])); + output.Store(1428, asuint(_value2[357])); + output.Store(1432, asuint(_value2[358])); + output.Store(1436, asuint(_value2[359])); + output.Store(1440, asuint(_value2[360])); + output.Store(1444, asuint(_value2[361])); + output.Store(1448, asuint(_value2[362])); + output.Store(1452, asuint(_value2[363])); + output.Store(1456, asuint(_value2[364])); + output.Store(1460, asuint(_value2[365])); + output.Store(1464, asuint(_value2[366])); + output.Store(1468, asuint(_value2[367])); + output.Store(1472, asuint(_value2[368])); + output.Store(1476, asuint(_value2[369])); + output.Store(1480, asuint(_value2[370])); + output.Store(1484, asuint(_value2[371])); + output.Store(1488, asuint(_value2[372])); + output.Store(1492, asuint(_value2[373])); + output.Store(1496, asuint(_value2[374])); + output.Store(1500, asuint(_value2[375])); + output.Store(1504, asuint(_value2[376])); + output.Store(1508, asuint(_value2[377])); + output.Store(1512, asuint(_value2[378])); + output.Store(1516, asuint(_value2[379])); + output.Store(1520, asuint(_value2[380])); + output.Store(1524, asuint(_value2[381])); + output.Store(1528, asuint(_value2[382])); + output.Store(1532, asuint(_value2[383])); + output.Store(1536, asuint(_value2[384])); + output.Store(1540, asuint(_value2[385])); + output.Store(1544, asuint(_value2[386])); + output.Store(1548, asuint(_value2[387])); + output.Store(1552, asuint(_value2[388])); + output.Store(1556, asuint(_value2[389])); + output.Store(1560, asuint(_value2[390])); + output.Store(1564, asuint(_value2[391])); + output.Store(1568, asuint(_value2[392])); + output.Store(1572, asuint(_value2[393])); + output.Store(1576, asuint(_value2[394])); + output.Store(1580, asuint(_value2[395])); + output.Store(1584, asuint(_value2[396])); + output.Store(1588, asuint(_value2[397])); + output.Store(1592, asuint(_value2[398])); + output.Store(1596, asuint(_value2[399])); + output.Store(1600, asuint(_value2[400])); + output.Store(1604, asuint(_value2[401])); + output.Store(1608, asuint(_value2[402])); + output.Store(1612, asuint(_value2[403])); + output.Store(1616, asuint(_value2[404])); + output.Store(1620, asuint(_value2[405])); + output.Store(1624, asuint(_value2[406])); + output.Store(1628, asuint(_value2[407])); + output.Store(1632, asuint(_value2[408])); + output.Store(1636, asuint(_value2[409])); + output.Store(1640, asuint(_value2[410])); + output.Store(1644, asuint(_value2[411])); + output.Store(1648, asuint(_value2[412])); + output.Store(1652, asuint(_value2[413])); + output.Store(1656, asuint(_value2[414])); + output.Store(1660, asuint(_value2[415])); + output.Store(1664, asuint(_value2[416])); + output.Store(1668, asuint(_value2[417])); + output.Store(1672, asuint(_value2[418])); + output.Store(1676, asuint(_value2[419])); + output.Store(1680, asuint(_value2[420])); + output.Store(1684, asuint(_value2[421])); + output.Store(1688, asuint(_value2[422])); + output.Store(1692, asuint(_value2[423])); + output.Store(1696, asuint(_value2[424])); + output.Store(1700, asuint(_value2[425])); + output.Store(1704, asuint(_value2[426])); + output.Store(1708, asuint(_value2[427])); + output.Store(1712, asuint(_value2[428])); + output.Store(1716, asuint(_value2[429])); + output.Store(1720, asuint(_value2[430])); + output.Store(1724, asuint(_value2[431])); + output.Store(1728, asuint(_value2[432])); + output.Store(1732, asuint(_value2[433])); + output.Store(1736, asuint(_value2[434])); + output.Store(1740, asuint(_value2[435])); + output.Store(1744, asuint(_value2[436])); + output.Store(1748, asuint(_value2[437])); + output.Store(1752, asuint(_value2[438])); + output.Store(1756, asuint(_value2[439])); + output.Store(1760, asuint(_value2[440])); + output.Store(1764, asuint(_value2[441])); + output.Store(1768, asuint(_value2[442])); + output.Store(1772, asuint(_value2[443])); + output.Store(1776, asuint(_value2[444])); + output.Store(1780, asuint(_value2[445])); + output.Store(1784, asuint(_value2[446])); + output.Store(1788, asuint(_value2[447])); + output.Store(1792, asuint(_value2[448])); + output.Store(1796, asuint(_value2[449])); + output.Store(1800, asuint(_value2[450])); + output.Store(1804, asuint(_value2[451])); + output.Store(1808, asuint(_value2[452])); + output.Store(1812, asuint(_value2[453])); + output.Store(1816, asuint(_value2[454])); + output.Store(1820, asuint(_value2[455])); + output.Store(1824, asuint(_value2[456])); + output.Store(1828, asuint(_value2[457])); + output.Store(1832, asuint(_value2[458])); + output.Store(1836, asuint(_value2[459])); + output.Store(1840, asuint(_value2[460])); + output.Store(1844, asuint(_value2[461])); + output.Store(1848, asuint(_value2[462])); + output.Store(1852, asuint(_value2[463])); + output.Store(1856, asuint(_value2[464])); + output.Store(1860, asuint(_value2[465])); + output.Store(1864, asuint(_value2[466])); + output.Store(1868, asuint(_value2[467])); + output.Store(1872, asuint(_value2[468])); + output.Store(1876, asuint(_value2[469])); + output.Store(1880, asuint(_value2[470])); + output.Store(1884, asuint(_value2[471])); + output.Store(1888, asuint(_value2[472])); + output.Store(1892, asuint(_value2[473])); + output.Store(1896, asuint(_value2[474])); + output.Store(1900, asuint(_value2[475])); + output.Store(1904, asuint(_value2[476])); + output.Store(1908, asuint(_value2[477])); + output.Store(1912, asuint(_value2[478])); + output.Store(1916, asuint(_value2[479])); + output.Store(1920, asuint(_value2[480])); + output.Store(1924, asuint(_value2[481])); + output.Store(1928, asuint(_value2[482])); + output.Store(1932, asuint(_value2[483])); + output.Store(1936, asuint(_value2[484])); + output.Store(1940, asuint(_value2[485])); + output.Store(1944, asuint(_value2[486])); + output.Store(1948, asuint(_value2[487])); + output.Store(1952, asuint(_value2[488])); + output.Store(1956, asuint(_value2[489])); + output.Store(1960, asuint(_value2[490])); + output.Store(1964, asuint(_value2[491])); + output.Store(1968, asuint(_value2[492])); + output.Store(1972, asuint(_value2[493])); + output.Store(1976, asuint(_value2[494])); + output.Store(1980, asuint(_value2[495])); + output.Store(1984, asuint(_value2[496])); + output.Store(1988, asuint(_value2[497])); + output.Store(1992, asuint(_value2[498])); + output.Store(1996, asuint(_value2[499])); + output.Store(2000, asuint(_value2[500])); + output.Store(2004, asuint(_value2[501])); + output.Store(2008, asuint(_value2[502])); + output.Store(2012, asuint(_value2[503])); + output.Store(2016, asuint(_value2[504])); + output.Store(2020, asuint(_value2[505])); + output.Store(2024, asuint(_value2[506])); + output.Store(2028, asuint(_value2[507])); + output.Store(2032, asuint(_value2[508])); + output.Store(2036, asuint(_value2[509])); + output.Store(2040, asuint(_value2[510])); + output.Store(2044, asuint(_value2[511])); + } + return; +} diff --git a/tests/out/hlsl/workgroup-var-init.hlsl.config b/tests/out/hlsl/workgroup-var-init.hlsl.config new file mode 100644 index 000000000..246c485cf --- /dev/null +++ b/tests/out/hlsl/workgroup-var-init.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(main:cs_5_1 ) diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 02f922fc8..30b2bdbc6 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -240,8 +240,13 @@ kernel void atomics( kernel void assign_through_ptr( - threadgroup uint& val + metal::uint3 __global_invocation_id [[thread_position_in_grid]] +, threadgroup uint& val ) { + if (metal::all(__global_invocation_id == metal::uint3(0u))) { + val = {}; + } + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); assign_through_ptr_fn(val); return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index b821cc9d5..62dc1c4ac 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -62,7 +62,8 @@ void test_msl_packed_vec3_( } kernel void main_( - threadgroup type_2& wg + metal::uint3 __global_invocation_id [[thread_position_in_grid]] +, threadgroup type_2& wg , threadgroup metal::atomic_uint& at_1 , device FooStruct& alignment [[user(fake0)]] , device type_6 const& dummy [[user(fake0)]] @@ -73,6 +74,11 @@ kernel void main_( , constant type_15& global_nested_arrays_of_matrices_4x2_ [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { + if (metal::all(__global_invocation_id == metal::uint3(0u))) { + wg = {}; + metal::atomic_store_explicit(&at_1, 0, metal::memory_order_relaxed); + } + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); float Foo = {}; bool at = {}; test_msl_packed_vec3_(alignment); diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 7eea0a4f0..368c8218c 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -76,6 +76,10 @@ kernel void compute_( , metal::uint3 num_wgs [[threadgroups_per_grid]] , threadgroup type_4& output ) { + if (metal::all(global_id == metal::uint3(0u))) { + output = {}; + } + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x; return; } diff --git a/tests/out/msl/workgroup-var-init.msl b/tests/out/msl/workgroup-var-init.msl new file mode 100644 index 000000000..8f8bb14f1 --- /dev/null +++ b/tests/out/msl/workgroup-var-init.msl @@ -0,0 +1,40 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct type_1 { + uint inner[512]; +}; +struct type_3 { + metal::atomic_int inner[8]; +}; +struct type_4 { + type_3 inner[8]; +}; +struct WStruct { + type_1 arr; + metal::atomic_int atom; + type_4 atom_arr; +}; + +kernel void main_( + metal::uint3 __global_invocation_id [[thread_position_in_grid]] +, threadgroup WStruct& w_mem +, device type_1& output [[buffer(0)]] +) { + if (metal::all(__global_invocation_id == metal::uint3(0u))) { + w_mem.arr = {}; + metal::atomic_store_explicit(&w_mem.atom, 0, metal::memory_order_relaxed); + for (int __i0 = 0; __i0 < 8; __i0++) { + for (int __i1 = 0; __i1 < 8; __i1++) { + metal::atomic_store_explicit(&w_mem.atom_arr.inner[__i0].inner[__i1], 0, metal::memory_order_relaxed); + } + } + } + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + type_1 _e3 = w_mem.arr; + for(int _i=0; _i<512; ++_i) output.inner[_i] = _e3.inner[_i]; + return; +} diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 49d1eb4a6..128e0158b 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 325 +; Bound: 338 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" @@ -9,7 +9,7 @@ OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %237 "foo_vert" %232 %235 OpEntryPoint Fragment %279 "foo_frag" %278 OpEntryPoint GLCompute %298 "atomics" -OpEntryPoint GLCompute %322 "assign_through_ptr" +OpEntryPoint GLCompute %322 "assign_through_ptr" %325 OpExecutionMode %279 OriginUpperLeft OpExecutionMode %298 LocalSize 1 1 1 OpExecutionMode %322 LocalSize 1 1 1 @@ -103,6 +103,7 @@ OpMemberDecorate %81 0 Offset 0 OpDecorate %232 BuiltIn VertexIndex OpDecorate %235 BuiltIn Position OpDecorate %278 Location 0 +OpDecorate %325 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -228,6 +229,13 @@ OpDecorate %278 Location 0 %296 = OpConstantNull %6 %300 = OpTypePointer StorageBuffer %6 %303 = OpConstant %4 64 +%324 = OpConstantNull %4 +%326 = OpTypePointer Input %35 +%325 = OpVariable %326 Input +%328 = OpConstantNull %35 +%330 = OpTypeBool +%329 = OpTypeVector %330 3 +%335 = OpConstant %4 264 %91 = OpFunction %2 None %92 %90 = OpLabel %84 = OpVariable %85 Function %86 @@ -494,6 +502,18 @@ OpFunctionEnd %321 = OpLabel OpBranch %323 %323 = OpLabel -%324 = OpFunctionCall %2 %223 %83 +%327 = OpLoad %35 %325 +%331 = OpIEqual %329 %327 %328 +%332 = OpAll %330 %331 +OpSelectionMerge %333 None +OpBranchConditional %332 %334 %333 +%334 = OpLabel +OpStore %83 %324 +OpBranch %333 +%333 = OpLabel +OpControlBarrier %30 %30 %335 +OpBranch %336 +%336 = OpLabel +%337 = OpFunctionCall %2 %223 %83 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index ba39fa05c..0a6cf9d72 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 172 +; Bound: 186 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %111 "main" +OpEntryPoint GLCompute %111 "main" %129 OpExecutionMode %111 LocalSize 1 1 1 OpDecorate %25 ArrayStride 4 OpMemberDecorate %27 0 Offset 0 @@ -48,6 +48,7 @@ OpDecorate %64 DescriptorSet 0 OpDecorate %64 Binding 7 OpDecorate %65 Block OpMemberDecorate %65 0 Offset 0 +OpDecorate %129 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -131,23 +132,31 @@ OpMemberDecorate %65 0 Offset 0 %119 = OpTypePointer Uniform %32 %121 = OpTypePointer Uniform %35 %123 = OpTypePointer Uniform %38 -%127 = OpTypePointer Workgroup %11 -%128 = OpTypePointer Uniform %37 -%129 = OpTypePointer Uniform %36 -%132 = OpTypePointer Uniform %34 -%133 = OpTypePointer Uniform %33 -%134 = OpTypePointer Uniform %30 -%139 = OpConstant %6 7 -%145 = OpConstant %6 6 -%147 = OpTypePointer StorageBuffer %28 -%148 = OpConstant %6 1 -%151 = OpConstant %6 5 -%153 = OpTypePointer Uniform %30 -%154 = OpTypePointer Uniform %11 -%155 = OpConstant %6 3 -%158 = OpConstant %6 4 -%160 = OpTypePointer StorageBuffer %11 -%171 = OpConstant %6 256 +%126 = OpConstantNull %25 +%127 = OpConstantNull %6 +%128 = OpTypeVector %6 3 +%130 = OpTypePointer Input %128 +%129 = OpVariable %130 Input +%132 = OpConstantNull %128 +%133 = OpTypeVector %4 3 +%138 = OpConstant %6 264 +%141 = OpTypePointer Workgroup %11 +%142 = OpTypePointer Uniform %37 +%143 = OpTypePointer Uniform %36 +%146 = OpTypePointer Uniform %34 +%147 = OpTypePointer Uniform %33 +%148 = OpTypePointer Uniform %30 +%153 = OpConstant %6 7 +%159 = OpConstant %6 6 +%161 = OpTypePointer StorageBuffer %28 +%162 = OpConstant %6 1 +%165 = OpConstant %6 5 +%167 = OpTypePointer Uniform %30 +%168 = OpTypePointer Uniform %11 +%169 = OpConstant %6 3 +%172 = OpConstant %6 4 +%174 = OpTypePointer StorageBuffer %11 +%185 = OpConstant %6 256 %69 = OpFunction %2 None %70 %68 = OpFunctionParameter %26 %67 = OpLabel @@ -201,44 +210,57 @@ OpFunctionEnd %124 = OpAccessChain %123 %64 %79 OpBranch %125 %125 = OpLabel -%126 = OpFunctionCall %2 %76 -%130 = OpAccessChain %129 %124 %79 %79 -%131 = OpLoad %36 %130 -%135 = OpAccessChain %134 %122 %79 %79 %79 -%136 = OpLoad %30 %135 -%137 = OpMatrixTimesVector %28 %131 %136 -%138 = OpCompositeExtract %11 %137 0 -%140 = OpAccessChain %127 %42 %139 -OpStore %140 %138 -%141 = OpLoad %32 %120 -%142 = OpLoad %26 %118 -%143 = OpMatrixTimesVector %28 %141 %142 -%144 = OpCompositeExtract %11 %143 0 -%146 = OpAccessChain %127 %42 %145 -OpStore %146 %144 -%149 = OpAccessChain %85 %114 %148 %148 -%150 = OpLoad %11 %149 -%152 = OpAccessChain %127 %42 %151 -OpStore %152 %150 -%156 = OpAccessChain %154 %116 %79 %155 -%157 = OpLoad %11 %156 -%159 = OpAccessChain %127 %42 %158 -OpStore %159 %157 -%161 = OpAccessChain %160 %112 %148 -%162 = OpLoad %11 %161 -%163 = OpAccessChain %127 %42 %155 -OpStore %163 %162 -%164 = OpAccessChain %85 %112 %79 %79 -%165 = OpLoad %11 %164 -%166 = OpAccessChain %127 %42 %23 -OpStore %166 %165 -%167 = OpAccessChain %160 %112 %148 -OpStore %167 %22 -%168 = OpArrayLength %6 %49 0 -%169 = OpConvertUToF %11 %168 -%170 = OpAccessChain %127 %42 %148 -OpStore %170 %169 -OpAtomicStore %44 %9 %171 %23 +%131 = OpLoad %128 %129 +%134 = OpIEqual %133 %131 %132 +%135 = OpAll %4 %134 +OpSelectionMerge %136 None +OpBranchConditional %135 %137 %136 +%137 = OpLabel +OpStore %42 %126 +OpStore %44 %127 +OpBranch %136 +%136 = OpLabel +OpControlBarrier %23 %23 %138 +OpBranch %139 +%139 = OpLabel +%140 = OpFunctionCall %2 %76 +%144 = OpAccessChain %143 %124 %79 %79 +%145 = OpLoad %36 %144 +%149 = OpAccessChain %148 %122 %79 %79 %79 +%150 = OpLoad %30 %149 +%151 = OpMatrixTimesVector %28 %145 %150 +%152 = OpCompositeExtract %11 %151 0 +%154 = OpAccessChain %141 %42 %153 +OpStore %154 %152 +%155 = OpLoad %32 %120 +%156 = OpLoad %26 %118 +%157 = OpMatrixTimesVector %28 %155 %156 +%158 = OpCompositeExtract %11 %157 0 +%160 = OpAccessChain %141 %42 %159 +OpStore %160 %158 +%163 = OpAccessChain %85 %114 %162 %162 +%164 = OpLoad %11 %163 +%166 = OpAccessChain %141 %42 %165 +OpStore %166 %164 +%170 = OpAccessChain %168 %116 %79 %169 +%171 = OpLoad %11 %170 +%173 = OpAccessChain %141 %42 %172 +OpStore %173 %171 +%175 = OpAccessChain %174 %112 %162 +%176 = OpLoad %11 %175 +%177 = OpAccessChain %141 %42 %169 +OpStore %177 %176 +%178 = OpAccessChain %85 %112 %79 %79 +%179 = OpLoad %11 %178 +%180 = OpAccessChain %141 %42 %23 +OpStore %180 %179 +%181 = OpAccessChain %174 %112 %162 +OpStore %181 %22 +%182 = OpArrayLength %6 %49 0 +%183 = OpConvertUToF %11 %182 +%184 = OpAccessChain %141 %42 %162 +OpStore %184 %183 +OpAtomicStore %44 %9 %185 %23 OpStore %104 %10 OpStore %107 %24 OpReturn diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index 6c1dac372..f99174536 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 49 +; Bound: 58 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -48,8 +48,12 @@ OpDecorate %33 BuiltIn NumWorkgroups %31 = OpVariable %24 Input %33 = OpVariable %24 Input %36 = OpTypeFunction %2 -%38 = OpTypePointer Workgroup %6 -%47 = OpConstant %6 0 +%38 = OpConstantNull %16 +%39 = OpConstantNull %17 +%40 = OpTypeVector %15 3 +%45 = OpConstant %6 264 +%47 = OpTypePointer Workgroup %6 +%56 = OpConstant %6 0 %35 = OpFunction %2 None %36 %22 = OpLabel %25 = OpLoad %17 %23 @@ -59,15 +63,26 @@ OpDecorate %33 BuiltIn NumWorkgroups %34 = OpLoad %17 %33 OpBranch %37 %37 = OpLabel -%39 = OpCompositeExtract %6 %25 0 -%40 = OpCompositeExtract %6 %27 0 -%41 = OpIAdd %6 %39 %40 -%42 = OpIAdd %6 %41 %30 -%43 = OpCompositeExtract %6 %32 0 -%44 = OpIAdd %6 %42 %43 -%45 = OpCompositeExtract %6 %34 0 -%46 = OpIAdd %6 %44 %45 -%48 = OpAccessChain %38 %20 %47 -OpStore %48 %46 +%41 = OpIEqual %40 %25 %39 +%42 = OpAll %15 %41 +OpSelectionMerge %43 None +OpBranchConditional %42 %44 %43 +%44 = OpLabel +OpStore %20 %38 +OpBranch %43 +%43 = OpLabel +OpControlBarrier %11 %11 %45 +OpBranch %46 +%46 = OpLabel +%48 = OpCompositeExtract %6 %25 0 +%49 = OpCompositeExtract %6 %27 0 +%50 = OpIAdd %6 %48 %49 +%51 = OpIAdd %6 %50 %30 +%52 = OpCompositeExtract %6 %32 0 +%53 = OpIAdd %6 %51 %52 +%54 = OpCompositeExtract %6 %34 0 +%55 = OpIAdd %6 %53 %54 +%57 = OpAccessChain %47 %20 %56 +OpStore %57 %55 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/workgroup-var-init.spvasm b/tests/out/spv/workgroup-var-init.spvasm new file mode 100644 index 000000000..1cccc889d --- /dev/null +++ b/tests/out/spv/workgroup-var-init.spvasm @@ -0,0 +1,78 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 41 +OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %17 "main" %25 +OpExecutionMode %17 LocalSize 1 1 1 +OpSource GLSL 450 +OpMemberName %10 0 "arr" +OpMemberName %10 1 "atom" +OpMemberName %10 2 "atom_arr" +OpName %10 "WStruct" +OpName %11 "w_mem" +OpName %13 "output" +OpName %17 "main" +OpDecorate %7 ArrayStride 4 +OpDecorate %8 ArrayStride 4 +OpDecorate %9 ArrayStride 32 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 2048 +OpMemberDecorate %10 2 Offset 2052 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 0 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpDecorate %25 BuiltIn GlobalInvocationId +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 512 +%5 = OpConstant %4 8 +%6 = OpTypeInt 32 0 +%7 = OpTypeArray %6 %3 +%8 = OpTypeArray %4 %5 +%9 = OpTypeArray %8 %5 +%10 = OpTypeStruct %7 %4 %9 +%12 = OpTypePointer Workgroup %10 +%11 = OpVariable %12 Workgroup +%14 = OpTypeStruct %7 +%15 = OpTypePointer StorageBuffer %14 +%13 = OpVariable %15 StorageBuffer +%18 = OpTypeFunction %2 +%19 = OpTypePointer StorageBuffer %7 +%20 = OpConstant %6 0 +%23 = OpConstantNull %10 +%24 = OpTypeVector %6 3 +%26 = OpTypePointer Input %24 +%25 = OpVariable %26 Input +%28 = OpConstantNull %24 +%30 = OpTypeBool +%29 = OpTypeVector %30 3 +%35 = OpConstant %6 2 +%36 = OpConstant %6 264 +%38 = OpTypePointer Workgroup %7 +%17 = OpFunction %2 None %18 +%16 = OpLabel +%21 = OpAccessChain %19 %13 %20 +OpBranch %22 +%22 = OpLabel +%27 = OpLoad %24 %25 +%31 = OpIEqual %29 %27 %28 +%32 = OpAll %30 %31 +OpSelectionMerge %33 None +OpBranchConditional %32 %34 %33 +%34 = OpLabel +OpStore %11 %23 +OpBranch %33 +%33 = OpLabel +OpControlBarrier %35 %35 %36 +OpBranch %37 +%37 = OpLabel +%39 = OpAccessChain %38 %11 %20 +%40 = OpLoad %7 %39 +OpStore %21 %40 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/workgroup-var-init.wgsl b/tests/out/wgsl/workgroup-var-init.wgsl new file mode 100644 index 000000000..6197108cb --- /dev/null +++ b/tests/out/wgsl/workgroup-var-init.wgsl @@ -0,0 +1,16 @@ +struct WStruct { + arr: array, + atom: atomic, + atom_arr: array,8>,8>, +} + +var w_mem: WStruct; +@group(0) @binding(0) +var output: array; + +@compute @workgroup_size(1, 1, 1) +fn main() { + let _e3 = w_mem.arr; + output = _e3; + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 02e77a6cf..00c263946 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -227,6 +227,7 @@ fn write_output_spv( }, bounds_check_policies, binding_map: params.binding_map.clone(), + zero_initialize_workgroup_memory: spv::ZeroInitializeWorkgroupMemoryMode::Polyfill, }; if params.separate_entry_points { @@ -556,6 +557,10 @@ fn convert_wgsl() { ("lexical-scopes", Targets::WGSL), ("type-alias", Targets::WGSL), ("module-scope", Targets::WGSL), + ( + "workgroup-var-init", + Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, + ), ]; for &(name, targets) in inputs.iter() { From fe9db5dd8d82c6f8bfc60d1a049a4c28ae6c2485 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 25 Jan 2023 19:21:24 +0100 Subject: [PATCH 1909/2212] install `cargo-tarpaulin` via `cargo-binstall` (#2220) --- .github/workflows/lazy.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index 9423e22cb..faa1bf05b 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -13,10 +13,14 @@ jobs: - uses: actions-rs/toolchain@v1 with: toolchain: stable - - name: Generate report - uses: actions-rs/tarpaulin@v0.1 + - name: Install binstall + uses: taiki-e/install-action@v2 with: - args: '--tests --all-features --workspace' + tool: cargo-binstall + - name: Install cargo-tarpaulin + run: cargo binstall --no-confirm cargo-tarpaulin + - name: Generate report + run: cargo tarpaulin --tests --all-features --workspace --out Xml - name: Upload to codecov.io uses: codecov/codecov-action@v1 with: From 13944c0ae555fd30618a1e9ab1e6e00fa2509e1d Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 25 Jan 2023 21:04:38 +0100 Subject: [PATCH 1910/2212] Update CHANGELOG.md --- CHANGELOG.md | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index edf7b878a..51f0231a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,97 @@ # Change Log +## v0.11 (2023-01-25) + +- Move to the Rust 2021 edition ([#2085](https://github.com/gfx-rs/naga/pull/2085)) **@ErichDonGubler** +- Bump MSRV to 1.63 ([#2129](https://github.com/gfx-rs/naga/pull/2129)) **@teoxoy** + +#### API + +- Add handle validation pass to `Validator` ([#2090](https://github.com/gfx-rs/naga/pull/2090)) **@ErichDonGubler** +- Add `Range::new_from_bounds` ([#2148](https://github.com/gfx-rs/naga/pull/2148)) **@robtfm** + +#### DOCS + +- Fix docs for `Emit` statements ([#2208](https://github.com/gfx-rs/naga/pull/2208)) **@jimblandy** +- Fix invalid `<...>` URLs with code spans ([#2176](https://github.com/gfx-rs/naga/pull/2176)) **@ErichDonGubler** +- Explain how case clauses with multiple selectors are supported ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy** +- Document `EarlyDepthTest` and `ConservativeDepth` syntax ([#2132](https://github.com/gfx-rs/naga/pull/2132)) **@coreh** + +#### VALIDATOR + +- Allow `u32` coordinates for `textureStore`/`textureLoad` ([#2172](https://github.com/gfx-rs/naga/pull/2172)) **@PENGUINLIONG** +- Fix array being flagged as constructible when its base isn't ([#2111](https://github.com/gfx-rs/naga/pull/2111)) **@teoxoy** +- Add `type_flags` to `ModuleInfo` ([#2111](https://github.com/gfx-rs/naga/pull/2111)) **@teoxoy** +- Remove overly restrictive array stride check ([#2215](https://github.com/gfx-rs/naga/pull/2215)) **@fintelia** +- Let the uniformity analysis trust the handle validation pass ([#2200](https://github.com/gfx-rs/naga/pull/2200)) **@jimblandy** +- Fix warnings when building tests without validation ([#2177](https://github.com/gfx-rs/naga/pull/2177)) **@jimblandy** +- Add `ValidationFlags::BINDINGS` ([#2156](https://github.com/gfx-rs/naga/pull/2156)) **@kvark** +- Fix `textureGather` on `texture_2d` ([#2138](https://github.com/gfx-rs/naga/pull/2138)) **@JMS55** + +#### ALL (FRONTENDS/BACKENDS) + +- Support 16-bit unorm/snorm formats ([#2210](https://github.com/gfx-rs/naga/pull/2210)) **@fintelia** +- Support `gl_PointCoord` ([#2180](https://github.com/gfx-rs/naga/pull/2180)) **@Neo-Zhixing** + +#### ALL BACKENDS + +- Add support for zero-initializing workgroup memory ([#2111](https://github.com/gfx-rs/naga/pull/2111)) **@teoxoy** + +#### WGSL-IN + +- Implement module-level scoping ([#2075](https://github.com/gfx-rs/naga/pull/2075)) **@SparkyPotato** +- Remove `isFinite` and `isNormal` ([#2218](https://github.com/gfx-rs/naga/pull/2218)) **@evahop** +- Update inverse hyperbolic built-ins ([#2218](https://github.com/gfx-rs/naga/pull/2218)) **@evahop** +- Add `refract` built-in ([#2218](https://github.com/gfx-rs/naga/pull/2218)) **@evahop** +- Update reserved keywords ([#2130](https://github.com/gfx-rs/naga/pull/2130)) **@teoxoy** +- Remove non-32bit integers ([#2146](https://github.com/gfx-rs/naga/pull/2146)) **@teoxoy** +- Remove `workgroup_size` builtin ([#2147](https://github.com/gfx-rs/naga/pull/2147)) **@teoxoy** +- Remove fallthrough statement ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy** + +#### SPV-IN + +- Support binding arrays ([#2199](https://github.com/gfx-rs/naga/pull/2199)) **@Patryk27** + +#### GLSL-IN + +- Fix position propagation in lowering ([#2079](https://github.com/gfx-rs/naga/pull/2079)) **@JCapucho** +- Update initializer list type when parsing ([#2066](https://github.com/gfx-rs/naga/pull/2066)) **@JCapucho** +- Parenthesize unary negations to avoid `--` ([#2087](https://github.com/gfx-rs/naga/pull/2087)) **@ErichDonGubler** + +#### SPV-OUT + +- Add support for `atomicCompareExchangeWeak` ([#2165](https://github.com/gfx-rs/naga/pull/2165)) **@aweinstock314** +- Omit extra switch case blocks where possible ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy** +- Fix switch cases after default not being output ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy** + +#### MSL-OUT + +- Don't panic on missing bindings ([#2175](https://github.com/gfx-rs/naga/pull/2175)) **@kvark** +- Omit extra switch case blocks where possible ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy** +- Fix `textureGather` compatibility on macOS 10.13 ([#2104](https://github.com/gfx-rs/naga/pull/2104)) **@xiaopengli89** +- Fix incorrect atomic bounds check on metal back-end ([#2099](https://github.com/gfx-rs/naga/pull/2099)) **@raphlinus** +- Parenthesize unary negations to avoid `--` ([#2087](https://github.com/gfx-rs/naga/pull/2087)) **@ErichDonGubler** + +#### HLSL-OUT + +- Simplify `write_default_init` ([#2111](https://github.com/gfx-rs/naga/pull/2111)) **@teoxoy** +- Omit extra switch case blocks where possible ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy** +- Properly implement bitcast ([#2097](https://github.com/gfx-rs/naga/pull/2097)) **@cwfitzgerald** +- Fix storage access chain through a matrix ([#2097](https://github.com/gfx-rs/naga/pull/2097)) **@cwfitzgerald** +- Workaround FXC Bug in Matrix Indexing ([#2096](https://github.com/gfx-rs/naga/pull/2096)) **@cwfitzgerald** +- Parenthesize unary negations to avoid `--` ([#2087](https://github.com/gfx-rs/naga/pull/2087)) **@ErichDonGubler** + +#### GLSL-OUT + +- Introduce a flag to include unused items ([#2205](https://github.com/gfx-rs/naga/pull/2205)) **@robtfm** +- Use `fma` polyfill for versions below gles 320 ([#2197](https://github.com/gfx-rs/naga/pull/2197)) **@teoxoy** +- Emit reflection info for non-struct uniforms ([#2189](https://github.com/gfx-rs/naga/pull/2189)) **@Rainb0wCodes** +- Introduce a new block for switch cases ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy** + +#### WGSL-OUT + +- Write correct scalar kind when `width != 4` ([#1514](https://github.com/gfx-rs/naga/pull/1514)) **@fintelia** + ## v0.10 (2022-10-05) - Make termcolor dependency optional by @AldaronLau in https://github.com/gfx-rs/naga/pull/2014 From f0edae8ce9e55eeef489fc53b10dc95fb79561cc Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Wed, 25 Jan 2023 16:27:09 -0500 Subject: [PATCH 1911/2212] Update to 0.11 (#2222) --- Cargo.toml | 2 +- cli/Cargo.toml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 40e8106d6..a8dc9e0e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.10.0" +version = "0.11.0" authors = ["Naga Developers"] edition = "2021" description = "Shader translation infrastructure" diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 06df3b681..865130516 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga-cli" -version = "0.10.0" +version = "0.11.0" authors = ["Naga Developers"] edition = "2021" description = "Shader translation command line tool" @@ -10,7 +10,7 @@ keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" [dependencies] -naga = { version = "0.10", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } +naga = { version = "0.11", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } bincode = "1" log = "0.4" codespan-reporting = "0.11" From 26dca556a966a7e7eb193cff8f232422e14167f9 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 30 Jan 2023 16:15:53 -0800 Subject: [PATCH 1912/2212] Allow `clippy::needless_borrowed_reference`. In Clippy 1.67, the `needless_borrowed_reference` lint [was enhanced] to look into struct and tuple patterns, so that a line like this: for &(ref module, ref info) in inputs.iter() where `inputs.iter()` is yielding `&(Module, ModuleInfo)` pairs, elicits a warning. Clippy suggests, instead: for (module, info) in inputs.iter() but this is at odds with Naga's preference that `match` patterns should have the same type as the expression being matched, for which we have enabled the `pattern_type_mismatch` lint since 9e5cc4c9 (2021-3-12). [was enhanced]: https://github.com/rust-lang/rust-clippy/pull/9855 --- benches/criterion.rs | 2 ++ src/lib.rs | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/benches/criterion.rs b/benches/criterion.rs index 0bf247899..5093ab045 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -1,3 +1,5 @@ +#![allow(clippy::needless_borrowed_reference)] + use criterion::*; use std::{fs, path::PathBuf, slice}; diff --git a/src/lib.rs b/src/lib.rs index 705452008..077548aa3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -191,7 +191,8 @@ tree. clippy::match_like_matches_macro, clippy::if_same_then_else, clippy::collapsible_if, - clippy::derive_partial_eq_without_eq + clippy::derive_partial_eq_without_eq, + clippy::needless_borrowed_reference )] #![warn( trivial_casts, From ca99d8bcbc0c078636311e85ee41c5d308481f0f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 30 Jan 2023 16:34:04 -0800 Subject: [PATCH 1913/2212] Inline identifiers into format strings. [Since Rust 1.58], Rust format strings have been able to "capture arguments simply by writing {ident} in the string." Clippy 1.67 made the corresponding warning, `uninlined_format_args`, warn-by-default. Inlined arguments seem more readable, so Naga should adopt them. [Since Rust 1.58]: https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1580-2022-01-13 --- cli/src/bin/naga.rs | 17 +- src/back/dot/mod.rs | 36 ++-- src/back/glsl/mod.rs | 188 ++++++++++---------- src/back/hlsl/conv.rs | 4 +- src/back/hlsl/help.rs | 190 +++++++-------------- src/back/hlsl/storage.rs | 31 ++-- src/back/hlsl/writer.rs | 238 +++++++++++--------------- src/back/msl/mod.rs | 14 +- src/back/msl/writer.rs | 331 ++++++++++++++++-------------------- src/back/wgsl/writer.rs | 172 +++++++++---------- src/front/glsl/constants.rs | 5 +- src/front/glsl/context.rs | 11 +- src/front/glsl/error.rs | 2 +- src/front/glsl/functions.rs | 7 +- src/front/glsl/types.rs | 4 +- src/front/glsl/variables.rs | 9 +- src/front/spv/function.rs | 2 +- src/front/spv/mod.rs | 2 +- src/front/wgsl/mod.rs | 58 +++---- src/front/wgsl/number.rs | 4 +- src/proc/namer.rs | 8 +- src/proc/typifier.rs | 28 ++- tests/snapshots.rs | 44 +++-- tests/spirv-capabilities.rs | 10 +- tests/wgsl-errors.rs | 33 ++-- 25 files changed, 628 insertions(+), 820 deletions(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index b983473a1..ddf65f59c 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -99,8 +99,7 @@ impl FromStr for BoundsCheckPolicyArg { "unchecked" => BoundsCheckPolicy::Unchecked, _ => { return Err(format!( - "Invalid value for --index-bounds-check-policy: {}", - s + "Invalid value for --index-bounds-check-policy: {s}" )) } })) @@ -120,7 +119,7 @@ impl FromStr for ShaderModelArg { "50" => ShaderModel::V5_0, "51" => ShaderModel::V5_1, "60" => ShaderModel::V6_0, - _ => return Err(format!("Invalid value for --shader-model: {}", s)), + _ => return Err(format!("Invalid value for --shader-model: {s}")), })) } } @@ -139,7 +138,7 @@ impl FromStr for GlslProfileArg { } else if s.starts_with("es") { Version::new_gles(s[2..].parse().unwrap_or(310)) } else { - return Err(format!("Unknown profile: {}", s)); + return Err(format!("Unknown profile: {s}")); })) } } @@ -163,7 +162,7 @@ trait PrettyResult { } fn print_err(error: &dyn Error) { - eprint!("{}", error); + eprint!("{error}"); let mut e = error.source(); if e.is_some() { @@ -173,7 +172,7 @@ fn print_err(error: &dyn Error) { } while let Some(source) = e { - eprintln!("\t{}", source); + eprintln!("\t{source}"); e = source.source(); } } @@ -366,10 +365,10 @@ fn run() -> Result<(), Box> { use std::io::Write; let mut file = fs::File::create(output_path)?; - writeln!(file, "{:#?}", module)?; + writeln!(file, "{module:#?}")?; if let Some(ref info) = info { writeln!(file)?; - writeln!(file, "{:#?}", info)?; + writeln!(file, "{info:#?}")?; } } "bin" => { @@ -515,7 +514,7 @@ fn run() -> Result<(), Box> { fs::write(output_path, wgsl)?; } other => { - println!("Unknown output extension: {}", other); + println!("Unknown output extension: {other}"); } } } diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index ce88f02e8..5da9029ab 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -304,15 +304,13 @@ fn write_fun( for (index, label) in sg.nodes.into_iter().enumerate() { writeln!( output, - "\t\t{}_s{} [ shape=square label=\"{}\" ]", - prefix, index, label, + "\t\t{prefix}_s{index} [ shape=square label=\"{label}\" ]", )?; } for (from, to, label) in sg.flow { writeln!( output, - "\t\t{}_s{} -> {}_s{} [ arrowhead=tee label=\"{}\" ]", - prefix, from, prefix, to, label, + "\t\t{prefix}_s{from} -> {prefix}_s{to} [ arrowhead=tee label=\"{label}\" ]", )?; } for (from, to, label, color_id) in sg.jumps { @@ -384,12 +382,12 @@ fn write_function_expressions( } E::AccessIndex { base, index } => { edges.insert("base", base); - (format!("AccessIndex[{}]", index).into(), 1) + (format!("AccessIndex[{index}]").into(), 1) } E::Constant(_) => ("Constant".into(), 2), E::Splat { size, value } => { edges.insert("value", value); - (format!("Splat{:?}", size).into(), 3) + (format!("Splat{size:?}").into(), 3) } E::Swizzle { size, @@ -403,7 +401,7 @@ fn write_function_expressions( payload = Some(Payload::Arguments(components)); ("Compose".into(), 3) } - E::FunctionArgument(index) => (format!("Argument[{}]", index).into(), 1), + E::FunctionArgument(index) => (format!("Argument[{index}]").into(), 1), E::GlobalVariable(h) => { payload = Some(Payload::Global(h)); ("Global".into(), 2) @@ -450,7 +448,7 @@ fn write_function_expressions( edges.insert("depth_ref", expr); } let string = match gather { - Some(component) => Cow::Owned(format!("ImageGather{:?}", component)), + Some(component) => Cow::Owned(format!("ImageGather{component:?}")), _ => Cow::Borrowed("ImageSample"), }; (string, 5) @@ -484,18 +482,18 @@ fn write_function_expressions( } Cow::from("ImageSize") } - _ => Cow::Owned(format!("{:?}", query)), + _ => Cow::Owned(format!("{query:?}")), }; (args, 7) } E::Unary { op, expr } => { edges.insert("expr", expr); - (format!("{:?}", op).into(), 6) + (format!("{op:?}").into(), 6) } E::Binary { op, left, right } => { edges.insert("left", left); edges.insert("right", right); - (format!("{:?}", op).into(), 6) + (format!("{op:?}").into(), 6) } E::Select { condition, @@ -509,11 +507,11 @@ fn write_function_expressions( } E::Derivative { axis, expr } => { edges.insert("", expr); - (format!("d{:?}", axis).into(), 8) + (format!("d{axis:?}").into(), 8) } E::Relational { fun, argument } => { edges.insert("arg", argument); - (format!("{:?}", fun).into(), 6) + (format!("{fun:?}").into(), 6) } E::Math { fun, @@ -532,7 +530,7 @@ fn write_function_expressions( if let Some(expr) = arg3 { edges.insert("arg3", expr); } - (format!("{:?}", fun).into(), 7) + (format!("{fun:?}").into(), 7) } E::As { kind, @@ -541,8 +539,8 @@ fn write_function_expressions( } => { edges.insert("", expr); let string = match convert { - Some(width) => format!("Convert<{:?},{}>", kind, width), - None => format!("Bitcast<{:?}>", kind), + Some(width) => format!("Convert<{kind:?},{width}>"), + None => format!("Bitcast<{kind:?}>"), }; (string.into(), 3) } @@ -644,7 +642,7 @@ pub fn write( for (handle, fun) in module.functions.iter() { let prefix = format!("f{}", handle.index()); - writeln!(output, "\tsubgraph cluster_{} {{", prefix)?; + writeln!(output, "\tsubgraph cluster_{prefix} {{")?; writeln!( output, "\t\tlabel=\"Function{:?}/'{}'\"", @@ -656,8 +654,8 @@ pub fn write( writeln!(output, "\t}}")?; } for (ep_index, ep) in module.entry_points.iter().enumerate() { - let prefix = format!("ep{}", ep_index); - writeln!(output, "\tsubgraph cluster_{} {{", prefix)?; + let prefix = format!("ep{ep_index}"); + writeln!(output, "\tsubgraph cluster_{prefix} {{")?; writeln!(output, "\t\tlabel=\"{:?}/'{}'\"", ep.stage, ep.name)?; let info = mod_info.map(|a| a.get_entry_point(ep_index)); write_fun(&mut output, prefix, &ep.function, info, &options)?; diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9b4bf0cf2..420885638 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -198,8 +198,8 @@ impl PartialOrd for Version { impl fmt::Display for Version { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - Version::Desktop(v) => write!(f, "{} core", v), - Version::Embedded { version: v, .. } => write!(f, "{} es", v), + Version::Desktop(v) => write!(f, "{v} core"), + Version::Embedded { version: v, .. } => write!(f, "{v} es"), } } } @@ -327,7 +327,7 @@ impl fmt::Display for VaryingName<'_> { // fragment to pipeline (ShaderStage::Fragment, true) => "fs2p", }; - write!(f, "_{}_location{}", prefix, location,) + write!(f, "_{prefix}_location{location}",) } crate::Binding::BuiltIn(built_in) => { write!( @@ -563,7 +563,7 @@ impl<'a, W: Write> Writer<'a, W> { Cd::LessEqual => "less", Cd::Unchanged => "unchanged", }; - writeln!(self.out, "layout (depth_{}) out float gl_FragDepth;", depth)?; + writeln!(self.out, "layout (depth_{depth}) out float gl_FragDepth;")?; } writeln!(self.out)?; } else { @@ -576,7 +576,7 @@ impl<'a, W: Write> Writer<'a, W> { if self.entry_point.stage == ShaderStage::Vertex && self.options.version.is_webgl() { if let Some(multiview) = self.multiview.as_ref() { - writeln!(self.out, "layout(num_views = {}) in;", multiview)?; + writeln!(self.out, "layout(num_views = {multiview}) in;")?; writeln!(self.out)?; } } @@ -597,7 +597,7 @@ impl<'a, W: Write> Writer<'a, W> { .is_dynamically_sized(&self.module.types) { let name = &self.names[&NameKey::Type(handle)]; - write!(self.out, "struct {} ", name)?; + write!(self.out, "struct {name} ")?; self.write_struct_body(handle, members)?; writeln!(self.out, ";")?; } @@ -653,7 +653,7 @@ impl<'a, W: Write> Writer<'a, W> { if layout_binding.is_some() || storage_format_access.is_some() { write!(self.out, "layout(")?; if let Some(binding) = layout_binding { - write!(self.out, "binding = {}", binding)?; + write!(self.out, "binding = {binding}")?; } if let Some((format, _)) = storage_format_access { let format_str = glsl_storage_format(format); @@ -661,7 +661,7 @@ impl<'a, W: Write> Writer<'a, W> { Some(_) => ",", None => "", }; - write!(self.out, "{}{}", separator, format_str)?; + write!(self.out, "{separator}{format_str}")?; } write!(self.out, ") ")?; } @@ -683,7 +683,7 @@ impl<'a, W: Write> Writer<'a, W> { // Finally write the name and end the global with a `;` // The leading space is important let global_name = self.get_global_name(handle, global); - writeln!(self.out, " {};", global_name)?; + writeln!(self.out, " {global_name};")?; writeln!(self.out)?; self.reflection_names_globals.insert(handle, global_name); @@ -717,7 +717,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_type(ty)?; } }; - write!(self.out, " {} = ", name)?; + write!(self.out, " {name} = ")?; self.write_constant(handle)?; writeln!(self.out, ";")?; } @@ -777,11 +777,11 @@ impl<'a, W: Write> Writer<'a, W> { crate::ConstantInner::Scalar { width: _, value: crate::ScalarValue::Uint(size), - } => write!(self.out, "{}", size)?, + } => write!(self.out, "{size}")?, crate::ConstantInner::Scalar { width: _, value: crate::ScalarValue::Sint(size), - } => write!(self.out, "{}", size)?, + } => write!(self.out, "{size}")?, _ => unreachable!(), } } @@ -865,7 +865,7 @@ impl<'a, W: Write> Writer<'a, W> { | TypeInner::Image { .. } | TypeInner::Sampler { .. } | TypeInner::BindingArray { .. } => { - return Err(Error::Custom(format!("Unable to write type {:?}", inner))) + return Err(Error::Custom(format!("Unable to write type {inner:?}"))) } } @@ -890,7 +890,7 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Struct { .. } => { // Get the struct name let name = &self.names[&NameKey::Type(ty)]; - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; Ok(()) } // glsl array has the size separated from the base type @@ -972,7 +972,7 @@ impl<'a, W: Write> Writer<'a, W> { crate::AddressSpace::Uniform => "std140, ", _ => "", }; - write!(self.out, "layout({}binding = {}) ", layout, binding)? + write!(self.out, "layout({layout}binding = {binding}) ")? } None => { log::debug!("unassigned binding for {:?}", global.name); @@ -991,7 +991,7 @@ impl<'a, W: Write> Writer<'a, W> { } if let Some(storage_qualifier) = glsl_storage_qualifier(global.space) { - write!(self.out, "{} ", storage_qualifier)?; + write!(self.out, "{storage_qualifier} ")?; } match global.space { @@ -1071,7 +1071,7 @@ impl<'a, W: Write> Writer<'a, W> { self.block_id.generate(), self.entry_point.stage, ); - write!(self.out, "{} ", block_name)?; + write!(self.out, "{block_name} ")?; self.reflection_names_globals.insert(handle, block_name); match self.module.types[global.ty].inner { @@ -1272,7 +1272,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the I/O locations, if allowed if self.options.version.supports_explicit_locations() || !emit_interpolation_and_auxiliary { - write!(self.out, "layout(location = {}) ", location)?; + write!(self.out, "layout(location = {location}) ")?; } // Write the interpolation qualifier. @@ -1290,7 +1290,7 @@ impl<'a, W: Write> Writer<'a, W> { if let Some(sampling) = sampling { if emit_interpolation_and_auxiliary { if let Some(qualifier) = glsl_sampling(sampling) { - write!(self.out, "{} ", qualifier)?; + write!(self.out, "{qualifier} ")?; } } } @@ -1314,7 +1314,7 @@ impl<'a, W: Write> Writer<'a, W> { output, targetting_webgl: self.options.version.is_webgl(), }; - writeln!(self.out, " {};", vname)?; + writeln!(self.out, " {vname};")?; Ok(()) } @@ -1366,7 +1366,7 @@ impl<'a, W: Write> Writer<'a, W> { back::FunctionType::Function(handle) => &self.names[&NameKey::Function(handle)], back::FunctionType::EntryPoint(_) => "main", }; - write!(self.out, " {}(", function_name)?; + write!(self.out, " {function_name}(")?; // Write the comma separated argument list // @@ -1448,7 +1448,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "{}", back::INDENT)?; self.write_type(arg.ty)?; let name = &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)]; - write!(self.out, " {}", name)?; + write!(self.out, " {name}")?; write!(self.out, " = ")?; match self.module.types[arg.ty].inner { crate::TypeInner::Struct { ref members, .. } => { @@ -1464,7 +1464,7 @@ impl<'a, W: Write> Writer<'a, W> { if index != 0 { write!(self.out, ", ")?; } - write!(self.out, "{}", varying_name)?; + write!(self.out, "{varying_name}")?; } writeln!(self.out, ");")?; } @@ -1475,7 +1475,7 @@ impl<'a, W: Write> Writer<'a, W> { output: false, targetting_webgl: self.options.version.is_webgl(), }; - writeln!(self.out, "{};", varying_name)?; + writeln!(self.out, "{varying_name};")?; } } } @@ -1547,8 +1547,7 @@ impl<'a, W: Write> Writer<'a, W> { writeln!( self.out, - "{}if (gl_GlobalInvocationID == uvec3(0u)) {{", - level + "{level}if (gl_GlobalInvocationID == uvec3(0u)) {{" )?; for (handle, var) in vars { @@ -1558,7 +1557,7 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ";")?; } - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; self.write_barrier(crate::Barrier::WORK_GROUP, level)?; } @@ -1607,17 +1606,17 @@ impl<'a, W: Write> Writer<'a, W> { ref value, } => match *value { // Signed integers don't need anything special - Sv::Sint(int) => write!(self.out, "{}", int)?, + Sv::Sint(int) => write!(self.out, "{int}")?, // Unsigned integers need a `u` at the end // // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we // always write it as the extra branch wouldn't have any benefit in readability - Sv::Uint(int) => write!(self.out, "{}u", int)?, + Sv::Uint(int) => write!(self.out, "{int}u")?, // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero which is needed for a valid glsl float constant - Sv::Float(float) => write!(self.out, "{:?}", float)?, + Sv::Float(float) => write!(self.out, "{float:?}")?, // Booleans are either `true` or `false` so nothing special needs to be done - Sv::Bool(boolean) => write!(self.out, "{}", boolean)?, + Sv::Bool(boolean) => write!(self.out, "{boolean}")?, }, // Composite constant are created using the same syntax as compose // `type(components)` where `components` is a comma separated list of constants @@ -1662,13 +1661,13 @@ impl<'a, W: Write> Writer<'a, W> { // it shouldn't produce large expressions. self.write_expr(arg, ctx)?; // Access the current component on the first vector - write!(self.out, ".{} * ", component)?; + write!(self.out, ".{component} * ")?; // Write the second vector expression, this expression is marked to be // cached so unless it can't be cached (for example, it's a Constant) // it shouldn't produce large expressions. self.write_expr(arg1, ctx)?; // Access the current component on the second vector - write!(self.out, ".{}", component)?; + write!(self.out, ".{component}")?; } write!(self.out, ")")?; @@ -1787,14 +1786,14 @@ impl<'a, W: Write> Writer<'a, W> { } = *ctx.info[image].ty.inner_with(&self.module.types) { if let proc::BoundsCheckPolicy::Restrict = self.policies.image { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.write_clamped_lod(ctx, handle, image, level_expr)? } } } if let Some(name) = expr_name { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.write_named_expr(handle, name, ctx)?; } } @@ -1803,13 +1802,13 @@ impl<'a, W: Write> Writer<'a, W> { // We could also just print the statements but this is more readable and maps more // closely to the IR Statement::Block(ref block) => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; writeln!(self.out, "{{")?; for sta in block.iter() { // Increase the indentation to help with readability self.write_stmt(sta, ctx, level.next())? } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } // Ifs are written as in C: // ``` @@ -1824,7 +1823,7 @@ impl<'a, W: Write> Writer<'a, W> { ref accept, ref reject, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; write!(self.out, "if (")?; self.write_expr(condition, ctx)?; writeln!(self.out, ") {{")?; @@ -1837,7 +1836,7 @@ impl<'a, W: Write> Writer<'a, W> { // If there are no statements in the reject block we skip writing it // This is only for readability if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", level)?; + writeln!(self.out, "{level}}} else {{")?; for sta in reject { // Increase indentation to help with readability @@ -1845,7 +1844,7 @@ impl<'a, W: Write> Writer<'a, W> { } } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } // Switch are written as in C: // ``` @@ -1868,7 +1867,7 @@ impl<'a, W: Write> Writer<'a, W> { ref cases, } => { // Start the switch - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; write!(self.out, "switch(")?; self.write_expr(selector, ctx)?; writeln!(self.out, ") {{")?; @@ -1885,9 +1884,9 @@ impl<'a, W: Write> Writer<'a, W> { for case in cases { match case.value { crate::SwitchValue::Integer(value) => { - write!(self.out, "{}case {}{}:", l2, value, type_postfix)? + write!(self.out, "{l2}case {value}{type_postfix}:")? } - crate::SwitchValue::Default => write!(self.out, "{}default:", l2)?, + crate::SwitchValue::Default => write!(self.out, "{l2}default:")?, } let write_block_braces = !(case.fall_through && case.body.is_empty()); @@ -1906,11 +1905,11 @@ impl<'a, W: Write> Writer<'a, W> { } if write_block_braces { - writeln!(self.out, "{}}}", l2)?; + writeln!(self.out, "{l2}}}")?; } } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a // while true loop and appending the continuing block to the body resulting on: @@ -1929,45 +1928,45 @@ impl<'a, W: Write> Writer<'a, W> { } => { if !continuing.is_empty() || break_if.is_some() { let gate_name = self.namer.call("loop_init"); - writeln!(self.out, "{}bool {} = true;", level, gate_name)?; - writeln!(self.out, "{}while(true) {{", level)?; + writeln!(self.out, "{level}bool {gate_name} = true;")?; + writeln!(self.out, "{level}while(true) {{")?; let l2 = level.next(); let l3 = l2.next(); - writeln!(self.out, "{}if (!{}) {{", l2, gate_name)?; + writeln!(self.out, "{l2}if (!{gate_name}) {{")?; for sta in continuing { self.write_stmt(sta, ctx, l3)?; } if let Some(condition) = break_if { - write!(self.out, "{}if (", l3)?; + write!(self.out, "{l3}if (")?; self.write_expr(condition, ctx)?; writeln!(self.out, ") {{")?; writeln!(self.out, "{}break;", l3.next())?; - writeln!(self.out, "{}}}", l3)?; + writeln!(self.out, "{l3}}}")?; } - writeln!(self.out, "{}}}", l2)?; + writeln!(self.out, "{l2}}}")?; writeln!(self.out, "{}{} = false;", level.next(), gate_name)?; } else { - writeln!(self.out, "{}while(true) {{", level)?; + writeln!(self.out, "{level}while(true) {{")?; } for sta in body { self.write_stmt(sta, ctx, level.next())?; } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } // Break, continue and return as written as in C // `break;` Statement::Break => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; writeln!(self.out, "break;")? } // `continue;` Statement::Continue => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; writeln!(self.out, "continue;")? } // `return expr;`, `expr` is optional Statement::Return { value } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; match ctx.ty { back::FunctionType::Function(_) => { write!(self.out, "return")?; @@ -1995,7 +1994,7 @@ impl<'a, W: Write> Writer<'a, W> { )?; self.write_expr(value, ctx)?; writeln!(self.out, ";")?; - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; Some(return_struct) } _ => None, @@ -2024,10 +2023,10 @@ impl<'a, W: Write> Writer<'a, W> { output: true, targetting_webgl: self.options.version.is_webgl(), }; - write!(self.out, "{} = ", varying_name)?; + write!(self.out, "{varying_name} = ")?; if let Some(struct_name) = temp_struct_name { - write!(self.out, "{}", struct_name)?; + write!(self.out, "{struct_name}")?; } else { self.write_expr(value, ctx)?; } @@ -2039,7 +2038,7 @@ impl<'a, W: Write> Writer<'a, W> { &self.names [&NameKey::StructMember(result.ty, index as u32)] )?; - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; } } _ => { @@ -2049,10 +2048,10 @@ impl<'a, W: Write> Writer<'a, W> { output: true, targetting_webgl: self.options.version.is_webgl(), }; - write!(self.out, "{} = ", name)?; + write!(self.out, "{name} = ")?; self.write_expr(value, ctx)?; writeln!(self.out, ";")?; - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; } } } @@ -2069,7 +2068,7 @@ impl<'a, W: Write> Writer<'a, W> { self.out, "gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);", )?; - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; } } writeln!(self.out, "return;")?; @@ -2079,13 +2078,13 @@ impl<'a, W: Write> Writer<'a, W> { // This is one of the places were glsl adds to the syntax of C in this case the discard // keyword which ceases all further processing in a fragment shader, it's called OpKill // in spir-v that's why it's called `Statement::Kill` - Statement::Kill => writeln!(self.out, "{}discard;", level)?, + Statement::Kill => writeln!(self.out, "{level}discard;")?, Statement::Barrier(flags) => { self.write_barrier(flags, level)?; } // Stores in glsl are just variable assignments written as `pointer = value;` Statement::Store { pointer, value } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.write_expr(pointer, ctx)?; write!(self.out, " = ")?; self.write_expr(value, ctx)?; @@ -2098,7 +2097,7 @@ impl<'a, W: Write> Writer<'a, W> { array_index, value, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.write_image_store(ctx, image, coordinate, array_index, value)? } // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list @@ -2107,12 +2106,12 @@ impl<'a, W: Write> Writer<'a, W> { ref arguments, result, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; if let Some(expr) = result { let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); let result = self.module.functions[function].result.as_ref().unwrap(); self.write_type(result.ty)?; - write!(self.out, " {} = ", name)?; + write!(self.out, " {name} = ")?; self.named_expressions.insert(expr, name); } write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; @@ -2136,15 +2135,15 @@ impl<'a, W: Write> Writer<'a, W> { value, result, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); let res_ty = ctx.info[result].ty.inner_with(&self.module.types); self.write_value_type(res_ty)?; - write!(self.out, " {} = ", res_name)?; + write!(self.out, " {res_name} = ")?; self.named_expressions.insert(result, res_name); let fun_str = fun.to_glsl(); - write!(self.out, "atomic{}(", fun_str)?; + write!(self.out, "atomic{fun_str}(")?; self.write_expr(pointer, ctx)?; write!(self.out, ", ")?; // handle the special cases @@ -2180,7 +2179,7 @@ impl<'a, W: Write> Writer<'a, W> { use crate::Expression; if let Some(name) = self.named_expressions.get(&expr) { - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; return Ok(()); } @@ -2215,7 +2214,7 @@ impl<'a, W: Write> Writer<'a, W> { } TypeInner::Matrix { .. } | TypeInner::Array { .. } - | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, + | TypeInner::ValuePointer { .. } => write!(self.out, "[{index}]")?, TypeInner::Struct { .. } => { // This will never panic in case the type is a `Struct`, this is not true // for other types so we can only check while inside this match arm @@ -2227,7 +2226,7 @@ impl<'a, W: Write> Writer<'a, W> { &self.names[&NameKey::StructMember(ty, index)] )? } - ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), + ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))), } } // Constants are delegated to `write_constant` @@ -2353,7 +2352,7 @@ impl<'a, W: Write> Writer<'a, W> { None => "", }; - write!(self.out, "{}{}(", fun_name, offset_name)?; + write!(self.out, "{fun_name}{offset_name}(")?; // Write the image that will be used self.write_expr(image, ctx)?; @@ -2413,7 +2412,7 @@ impl<'a, W: Write> Writer<'a, W> { crate::ImageDimension::Cube => 3, _ => 2, }; - write!(self.out, ", vec{}(0.0), vec{}(0.0)", vec_dim, vec_dim)?; + write!(self.out, ", vec{vec_dim}(0.0), vec{vec_dim}(0.0)")?; } else if gather.is_none() { write!(self.out, ", 0.0")?; } @@ -2538,7 +2537,7 @@ impl<'a, W: Write> Writer<'a, W> { ImageClass::Sampled { .. } | ImageClass::Depth { .. } => "textureSize", ImageClass::Storage { .. } => "imageSize", }; - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; self.write_expr(image, ctx)?; // All textureSize calls requires an lod argument // except for multisampled samplers @@ -2557,7 +2556,7 @@ impl<'a, W: Write> Writer<'a, W> { } ImageClass::Storage { .. } => "imageSamples", }; - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; self.write_expr(image, ctx)?; write!(self.out, ")",)?; } @@ -2586,14 +2585,13 @@ impl<'a, W: Write> Writer<'a, W> { Some(Sk::Bool) => "!", ref other => { return Err(Error::Custom(format!( - "Cannot apply not to type {:?}", - other + "Cannot apply not to type {other:?}" ))) } }, }; - write!(self.out, "{}(", operator)?; + write!(self.out, "{operator}(")?; } } @@ -2667,7 +2665,7 @@ impl<'a, W: Write> Writer<'a, W> { Bo::NotEqual => "notEqual(", _ => unreachable!(), }; - write!(self.out, "{}", op_str)?; + write!(self.out, "{op_str}")?; self.write_expr(left, ctx)?; write!(self.out, ", ")?; self.write_expr(right, ctx)?; @@ -2802,7 +2800,7 @@ impl<'a, W: Write> Writer<'a, W> { Rf::All => "all", Rf::Any => "any", }; - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; self.write_expr(argument, ctx)?; @@ -2987,7 +2985,7 @@ impl<'a, W: Write> Writer<'a, W> { } } - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; // Cast to int if the function needs it if arg_might_need_uint_to_int { @@ -3199,7 +3197,7 @@ impl<'a, W: Write> Writer<'a, W> { // constructor notation (NOTE: the inner `ivec` can also be a scalar, this // is important for 1D arrayed images). Some(layer_expr) => { - write!(self.out, "ivec{}(", vector_size)?; + write!(self.out, "ivec{vector_size}(")?; self.write_expr(coordinate, ctx)?; write!(self.out, ", ")?; // If we are replacing sampler1D with sampler2D we also need @@ -3229,7 +3227,7 @@ impl<'a, W: Write> Writer<'a, W> { } else if uvec_size.is_some() { match uvec_size { Some(None) => write!(self.out, "int(")?, - Some(Some(size)) => write!(self.out, "ivec{}(", size)?, + Some(Some(size)) => write!(self.out, "ivec{size}(")?, _ => {} } } @@ -3442,7 +3440,7 @@ impl<'a, W: Write> Writer<'a, W> { } // Begin the call to the function used to load the texel - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; self.write_expr(image, ctx)?; write!(self.out, ", ")?; @@ -3463,7 +3461,7 @@ impl<'a, W: Write> Writer<'a, W> { if vector_size == 1 { write!(self.out, ", 0")?; } else { - write!(self.out, ", ivec{}(0)", vector_size)?; + write!(self.out, ", ivec{vector_size}(0)")?; } // Start the `textureSize` call to use as the max value. write!(self.out, ", textureSize(")?; @@ -3487,7 +3485,7 @@ impl<'a, W: Write> Writer<'a, W> { if vector_size == 1 { write!(self.out, " - 1")?; } else { - write!(self.out, " - ivec{}(1)", vector_size)?; + write!(self.out, " - ivec{vector_size}(1)")?; } // Close the `clamp` call @@ -3563,7 +3561,7 @@ impl<'a, W: Write> Writer<'a, W> { proc::TypeResolution::Handle(ty_handle) => match self.module.types[ty_handle].inner { TypeInner::Struct { .. } => { let ty_name = &self.names[&NameKey::Type(ty_handle)]; - write!(self.out, "{}", ty_name)?; + write!(self.out, "{ty_name}")?; } _ => { self.write_type(ty_handle)?; @@ -3577,7 +3575,7 @@ impl<'a, W: Write> Writer<'a, W> { let base_ty_res = &ctx.info[handle].ty; let resolved = base_ty_res.inner_with(&self.module.types); - write!(self.out, " {}", name)?; + write!(self.out, " {name}")?; if let TypeInner::Array { base, size, .. } = *resolved { self.write_array_size(base, size)?; } @@ -3629,7 +3627,7 @@ impl<'a, W: Write> Writer<'a, W> { } TypeInner::Struct { ref members, .. } => { let name = &self.names[&NameKey::Type(ty)]; - write!(self.out, "{}(", name)?; + write!(self.out, "{name}(")?; for (i, member) in members.iter().enumerate() { self.write_zero_init_value(member.ty)?; if i != members.len().saturating_sub(1) { @@ -3660,12 +3658,12 @@ impl<'a, W: Write> Writer<'a, W> { /// OpenGL always requires a call to the `barrier()` function after a `memoryBarrier*()` fn write_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult { if flags.contains(crate::Barrier::STORAGE) { - writeln!(self.out, "{}memoryBarrierBuffer();", level)?; + writeln!(self.out, "{level}memoryBarrierBuffer();")?; } if flags.contains(crate::Barrier::WORK_GROUP) { - writeln!(self.out, "{}memoryBarrierShared();", level)?; + writeln!(self.out, "{level}memoryBarrierShared();")?; } - writeln!(self.out, "{}barrier();", level)?; + writeln!(self.out, "{level}barrier();")?; Ok(()) } diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 819ddb4d4..1773ed71b 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -175,10 +175,10 @@ impl crate::BuiltIn { // in `Writer::write_expr`. Self::NumWorkGroups => "SV_GroupID", Self::BaseInstance | Self::BaseVertex | Self::WorkGroupSize => { - return Err(Error::Unimplemented(format!("builtin {:?}", self))) + return Err(Error::Unimplemented(format!("builtin {self:?}"))) } Self::ViewIndex | Self::PointCoord => { - return Err(Error::Custom(format!("Unsupported builtin {:?}", self))) + return Err(Error::Custom(format!("Unsupported builtin {self:?}"))) } }) } diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index bea6220e7..bb18bf3ab 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -125,20 +125,20 @@ impl<'a, W: Write> super::Writer<'a, W> { }; let dim_str = dim.to_hlsl_str(); let arrayed_str = if arrayed { "Array" } else { "" }; - write!(self.out, "{}Texture{}{}", access_str, dim_str, arrayed_str)?; + write!(self.out, "{access_str}Texture{dim_str}{arrayed_str}")?; match class { crate::ImageClass::Depth { multi } => { let multi_str = if multi { "MS" } else { "" }; - write!(self.out, "{}", multi_str)? + write!(self.out, "{multi_str}")? } crate::ImageClass::Sampled { kind, multi } => { let multi_str = if multi { "MS" } else { "" }; let scalar_kind_str = kind.to_hlsl_str(4)?; - write!(self.out, "{}<{}4>", multi_str, scalar_kind_str)? + write!(self.out, "{multi_str}<{scalar_kind_str}4>")? } crate::ImageClass::Storage { format, .. } => { let storage_format_str = format.to_hlsl_str(); - write!(self.out, "<{}>", storage_format_str)? + write!(self.out, "<{storage_format_str}>")? } } Ok(()) @@ -149,7 +149,7 @@ impl<'a, W: Write> super::Writer<'a, W> { query: WrappedArrayLength, ) -> BackendResult { let access_str = if query.writable { "RW" } else { "" }; - write!(self.out, "NagaBufferLength{}", access_str,)?; + write!(self.out, "NagaBufferLength{access_str}",)?; Ok(()) } @@ -180,22 +180,20 @@ impl<'a, W: Write> super::Writer<'a, W> { let access_str = if wal.writable { "RW" } else { "" }; writeln!( self.out, - "{}ByteAddressBuffer {})", - access_str, ARGUMENT_VARIABLE_NAME + "{access_str}ByteAddressBuffer {ARGUMENT_VARIABLE_NAME})" )?; // Write function body writeln!(self.out, "{{")?; // Write `GetDimensions` function. - writeln!(self.out, "{}uint {};", INDENT, RETURN_VARIABLE_NAME)?; + writeln!(self.out, "{INDENT}uint {RETURN_VARIABLE_NAME};")?; writeln!( self.out, - "{}{}.GetDimensions({});", - INDENT, ARGUMENT_VARIABLE_NAME, RETURN_VARIABLE_NAME + "{INDENT}{ARGUMENT_VARIABLE_NAME}.GetDimensions({RETURN_VARIABLE_NAME});" )?; // Write return value - writeln!(self.out, "{}return {};", INDENT, RETURN_VARIABLE_NAME)?; + writeln!(self.out, "{INDENT}return {RETURN_VARIABLE_NAME};")?; // End of function body writeln!(self.out, "}}")?; @@ -226,11 +224,7 @@ impl<'a, W: Write> super::Writer<'a, W> { ImageQuery::NumSamples => "NumSamples", }; - write!( - self.out, - "Naga{}{}{}{}", - class_str, query_str, dim_str, arrayed_str - )?; + write!(self.out, "Naga{class_str}{query_str}{dim_str}{arrayed_str}")?; Ok(()) } @@ -264,10 +258,10 @@ impl<'a, W: Write> super::Writer<'a, W> { write!(self.out, "(")?; // Texture always first parameter self.write_image_type(wiq.dim, wiq.arrayed, wiq.class)?; - write!(self.out, " {}", ARGUMENT_VARIABLE_NAME)?; + write!(self.out, " {ARGUMENT_VARIABLE_NAME}")?; // Mipmap is a second parameter if exists if let ImageQuery::SizeLevel = wiq.query { - write!(self.out, ", uint {}", MIP_LEVEL_PARAM)?; + write!(self.out, ", uint {MIP_LEVEL_PARAM}")?; } writeln!(self.out, ")")?; @@ -303,15 +297,11 @@ impl<'a, W: Write> super::Writer<'a, W> { }; // Write `GetDimensions` function. - writeln!(self.out, "{}uint4 {};", INDENT, RETURN_VARIABLE_NAME)?; - write!( - self.out, - "{}{}.GetDimensions(", - INDENT, ARGUMENT_VARIABLE_NAME - )?; + writeln!(self.out, "{INDENT}uint4 {RETURN_VARIABLE_NAME};")?; + write!(self.out, "{INDENT}{ARGUMENT_VARIABLE_NAME}.GetDimensions(")?; match wiq.query { ImageQuery::SizeLevel => { - write!(self.out, "{}, ", MIP_LEVEL_PARAM)?; + write!(self.out, "{MIP_LEVEL_PARAM}, ")?; } _ => match wiq.class { crate::ImageClass::Sampled { multi: true, .. } @@ -325,7 +315,7 @@ impl<'a, W: Write> super::Writer<'a, W> { } for component in COMPONENTS[..number_of_params - 1].iter() { - write!(self.out, "{}.{}, ", RETURN_VARIABLE_NAME, component)?; + write!(self.out, "{RETURN_VARIABLE_NAME}.{component}, ")?; } // write last parameter without comma and space for last parameter @@ -341,8 +331,7 @@ impl<'a, W: Write> super::Writer<'a, W> { // Write return value writeln!( self.out, - "{}return {}.{};", - INDENT, RETURN_VARIABLE_NAME, ret_swizzle + "{INDENT}return {RETURN_VARIABLE_NAME}.{ret_swizzle};" )?; // End of function body @@ -364,7 +353,7 @@ impl<'a, W: Write> super::Writer<'a, W> { &module.constants, &self.names, )?; - write!(self.out, "Construct{}", name)?; + write!(self.out, "Construct{name}")?; Ok(()) } @@ -404,7 +393,7 @@ impl<'a, W: Write> super::Writer<'a, W> { write!(self.out, ", ")?; } self.write_type(module, ty)?; - write!(self.out, " {}{}", ARGUMENT_VARIABLE_NAME, i)?; + write!(self.out, " {ARGUMENT_VARIABLE_NAME}{i}")?; if let crate::TypeInner::Array { base, size, .. } = module.types[ty].inner { self.write_array_size(module, base, size)?; } @@ -440,8 +429,7 @@ impl<'a, W: Write> super::Writer<'a, W> { let struct_name = &self.names[&NameKey::Type(constructor.ty)]; writeln!( self.out, - "{}{} {} = ({})0;", - INDENT, struct_name, RETURN_VARIABLE_NAME, struct_name + "{INDENT}{struct_name} {RETURN_VARIABLE_NAME} = ({struct_name})0;" )?; for (i, member) in members.iter().enumerate() { let field_name = &self.names[&NameKey::StructMember(constructor.ty, i as u32)]; @@ -455,14 +443,7 @@ impl<'a, W: Write> super::Writer<'a, W> { for j in 0..columns as u8 { writeln!( self.out, - "{}{}.{}_{} = {}{}[{}];", - INDENT, - RETURN_VARIABLE_NAME, - field_name, - j, - ARGUMENT_VARIABLE_NAME, - i, - j + "{INDENT}{RETURN_VARIABLE_NAME}.{field_name}_{j} = {ARGUMENT_VARIABLE_NAME}{i}[{j}];" )?; } } @@ -484,16 +465,11 @@ impl<'a, W: Write> super::Writer<'a, W> { if let crate::TypeInner::Array { base, size, .. } = *other { self.write_array_size(module, base, size)?; } - writeln!(self.out, "){}{};", ARGUMENT_VARIABLE_NAME, i,)?; + writeln!(self.out, "){ARGUMENT_VARIABLE_NAME}{i};",)?; } else { writeln!( self.out, - "{}{}.{} = {}{};", - INDENT, - RETURN_VARIABLE_NAME, - field_name, - ARGUMENT_VARIABLE_NAME, - i, + "{INDENT}{RETURN_VARIABLE_NAME}.{field_name} = {ARGUMENT_VARIABLE_NAME}{i};", )?; } } @@ -505,9 +481,9 @@ impl<'a, W: Write> super::Writer<'a, W> { size: crate::ArraySize::Constant(size), .. } => { - write!(self.out, "{}", INDENT)?; + write!(self.out, "{INDENT}")?; self.write_type(module, base)?; - write!(self.out, " {}", RETURN_VARIABLE_NAME)?; + write!(self.out, " {RETURN_VARIABLE_NAME}")?; self.write_array_size(module, base, crate::ArraySize::Constant(size))?; write!(self.out, " = {{ ")?; let count = module.constants[size].to_array_length().unwrap(); @@ -515,7 +491,7 @@ impl<'a, W: Write> super::Writer<'a, W> { if i != 0 { write!(self.out, ", ")?; } - write!(self.out, "{}{}", ARGUMENT_VARIABLE_NAME, i)?; + write!(self.out, "{ARGUMENT_VARIABLE_NAME}{i}")?; } writeln!(self.out, " }};",)?; } @@ -523,7 +499,7 @@ impl<'a, W: Write> super::Writer<'a, W> { } // Write return value - writeln!(self.out, "{}return {};", INDENT, RETURN_VARIABLE_NAME)?; + writeln!(self.out, "{INDENT}return {RETURN_VARIABLE_NAME};")?; // End of function body writeln!(self.out, "}}")?; @@ -539,7 +515,7 @@ impl<'a, W: Write> super::Writer<'a, W> { ) -> BackendResult { let name = &self.names[&NameKey::Type(access.ty)]; let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; - write!(self.out, "GetMat{}On{}", field_name, name)?; + write!(self.out, "GetMat{field_name}On{name}")?; Ok(()) } @@ -566,17 +542,13 @@ impl<'a, W: Write> super::Writer<'a, W> { // Write function parameters write!(self.out, "(")?; let struct_name = &self.names[&NameKey::Type(access.ty)]; - write!( - self.out, - "{} {}", - struct_name, STRUCT_ARGUMENT_VARIABLE_NAME - )?; + write!(self.out, "{struct_name} {STRUCT_ARGUMENT_VARIABLE_NAME}")?; // Write function body writeln!(self.out, ") {{")?; // Write return value - write!(self.out, "{}return ", INDENT)?; + write!(self.out, "{INDENT}return ")?; self.write_value_type(module, ret_ty)?; write!(self.out, "(")?; let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; @@ -586,11 +558,7 @@ impl<'a, W: Write> super::Writer<'a, W> { if i != 0 { write!(self.out, ", ")?; } - write!( - self.out, - "{}.{}_{}", - STRUCT_ARGUMENT_VARIABLE_NAME, field_name, i - )?; + write!(self.out, "{STRUCT_ARGUMENT_VARIABLE_NAME}.{field_name}_{i}")?; } } _ => unreachable!(), @@ -611,7 +579,7 @@ impl<'a, W: Write> super::Writer<'a, W> { ) -> BackendResult { let name = &self.names[&NameKey::Type(access.ty)]; let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; - write!(self.out, "SetMat{}On{}", field_name, name)?; + write!(self.out, "SetMat{field_name}On{name}")?; Ok(()) } @@ -633,17 +601,13 @@ impl<'a, W: Write> super::Writer<'a, W> { // Write function parameters write!(self.out, "(")?; let struct_name = &self.names[&NameKey::Type(access.ty)]; - write!( - self.out, - "{} {}, ", - struct_name, STRUCT_ARGUMENT_VARIABLE_NAME - )?; + write!(self.out, "{struct_name} {STRUCT_ARGUMENT_VARIABLE_NAME}, ")?; let member = match module.types[access.ty].inner { crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], _ => unreachable!(), }; self.write_type(module, member.ty)?; - write!(self.out, " {}", MATRIX_ARGUMENT_VARIABLE_NAME)?; + write!(self.out, " {MATRIX_ARGUMENT_VARIABLE_NAME}")?; // Write function body writeln!(self.out, ") {{")?; @@ -654,13 +618,7 @@ impl<'a, W: Write> super::Writer<'a, W> { for i in 0..columns as u8 { writeln!( self.out, - "{}{}.{}_{} = {}[{}];", - INDENT, - STRUCT_ARGUMENT_VARIABLE_NAME, - field_name, - i, - MATRIX_ARGUMENT_VARIABLE_NAME, - i + "{INDENT}{STRUCT_ARGUMENT_VARIABLE_NAME}.{field_name}_{i} = {MATRIX_ARGUMENT_VARIABLE_NAME}[{i}];" )?; } } @@ -681,7 +639,7 @@ impl<'a, W: Write> super::Writer<'a, W> { ) -> BackendResult { let name = &self.names[&NameKey::Type(access.ty)]; let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; - write!(self.out, "SetMatVec{}On{}", field_name, name)?; + write!(self.out, "SetMatVec{field_name}On{name}")?; Ok(()) } @@ -704,11 +662,7 @@ impl<'a, W: Write> super::Writer<'a, W> { // Write function parameters write!(self.out, "(")?; let struct_name = &self.names[&NameKey::Type(access.ty)]; - write!( - self.out, - "{} {}, ", - struct_name, STRUCT_ARGUMENT_VARIABLE_NAME - )?; + write!(self.out, "{struct_name} {STRUCT_ARGUMENT_VARIABLE_NAME}, ")?; let member = match module.types[access.ty].inner { crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], _ => unreachable!(), @@ -724,8 +678,7 @@ impl<'a, W: Write> super::Writer<'a, W> { self.write_value_type(module, &vec_ty)?; write!( self.out, - " {}, uint {}", - VECTOR_ARGUMENT_VARIABLE_NAME, MATRIX_INDEX_ARGUMENT_VARIABLE_NAME + " {VECTOR_ARGUMENT_VARIABLE_NAME}, uint {MATRIX_INDEX_ARGUMENT_VARIABLE_NAME}" )?; // Write function body @@ -733,8 +686,7 @@ impl<'a, W: Write> super::Writer<'a, W> { writeln!( self.out, - "{}switch({}) {{", - INDENT, MATRIX_INDEX_ARGUMENT_VARIABLE_NAME + "{INDENT}switch({MATRIX_INDEX_ARGUMENT_VARIABLE_NAME}) {{" )?; let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; @@ -744,20 +696,14 @@ impl<'a, W: Write> super::Writer<'a, W> { for i in 0..columns as u8 { writeln!( self.out, - "{}case {}: {{ {}.{}_{} = {}; break; }}", - INDENT, - i, - STRUCT_ARGUMENT_VARIABLE_NAME, - field_name, - i, - VECTOR_ARGUMENT_VARIABLE_NAME + "{INDENT}case {i}: {{ {STRUCT_ARGUMENT_VARIABLE_NAME}.{field_name}_{i} = {VECTOR_ARGUMENT_VARIABLE_NAME}; break; }}" )?; } } _ => unreachable!(), } - writeln!(self.out, "{}}}", INDENT)?; + writeln!(self.out, "{INDENT}}}")?; // End of function body writeln!(self.out, "}}")?; @@ -773,7 +719,7 @@ impl<'a, W: Write> super::Writer<'a, W> { ) -> BackendResult { let name = &self.names[&NameKey::Type(access.ty)]; let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; - write!(self.out, "SetMatScalar{}On{}", field_name, name)?; + write!(self.out, "SetMatScalar{field_name}On{name}")?; Ok(()) } @@ -797,11 +743,7 @@ impl<'a, W: Write> super::Writer<'a, W> { // Write function parameters write!(self.out, "(")?; let struct_name = &self.names[&NameKey::Type(access.ty)]; - write!( - self.out, - "{} {}, ", - struct_name, STRUCT_ARGUMENT_VARIABLE_NAME - )?; + write!(self.out, "{struct_name} {STRUCT_ARGUMENT_VARIABLE_NAME}, ")?; let member = match module.types[access.ty].inner { crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], _ => unreachable!(), @@ -816,10 +758,7 @@ impl<'a, W: Write> super::Writer<'a, W> { self.write_value_type(module, &scalar_ty)?; write!( self.out, - " {}, uint {}, uint {}", - SCALAR_ARGUMENT_VARIABLE_NAME, - MATRIX_INDEX_ARGUMENT_VARIABLE_NAME, - VECTOR_INDEX_ARGUMENT_VARIABLE_NAME + " {SCALAR_ARGUMENT_VARIABLE_NAME}, uint {MATRIX_INDEX_ARGUMENT_VARIABLE_NAME}, uint {VECTOR_INDEX_ARGUMENT_VARIABLE_NAME}" )?; // Write function body @@ -827,8 +766,7 @@ impl<'a, W: Write> super::Writer<'a, W> { writeln!( self.out, - "{}switch({}) {{", - INDENT, MATRIX_INDEX_ARGUMENT_VARIABLE_NAME + "{INDENT}switch({MATRIX_INDEX_ARGUMENT_VARIABLE_NAME}) {{" )?; let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; @@ -838,21 +776,14 @@ impl<'a, W: Write> super::Writer<'a, W> { for i in 0..columns as u8 { writeln!( self.out, - "{}case {}: {{ {}.{}_{}[{}] = {}; break; }}", - INDENT, - i, - STRUCT_ARGUMENT_VARIABLE_NAME, - field_name, - i, - VECTOR_INDEX_ARGUMENT_VARIABLE_NAME, - SCALAR_ARGUMENT_VARIABLE_NAME + "{INDENT}case {i}: {{ {STRUCT_ARGUMENT_VARIABLE_NAME}.{field_name}_{i}[{VECTOR_INDEX_ARGUMENT_VARIABLE_NAME}] = {SCALAR_ARGUMENT_VARIABLE_NAME}; break; }}" )?; } } _ => unreachable!(), } - writeln!(self.out, "{}}}", INDENT)?; + writeln!(self.out, "{INDENT}}}")?; // End of function body writeln!(self.out, "}}")?; @@ -1088,7 +1019,7 @@ impl<'a, W: Write> super::Writer<'a, W> { // typedef write!(self.out, "typedef struct {{ ")?; for i in 0..columns as u8 { - write!(self.out, "float2 _{}; ", i)?; + write!(self.out, "float2 _{i}; ")?; } writeln!(self.out, "}} __mat{}x2;", columns as u8)?; @@ -1098,12 +1029,12 @@ impl<'a, W: Write> super::Writer<'a, W> { "float2 __get_col_of_mat{}x2(__mat{}x2 mat, uint idx) {{", columns as u8, columns as u8 )?; - writeln!(self.out, "{}switch(idx) {{", INDENT)?; + writeln!(self.out, "{INDENT}switch(idx) {{")?; for i in 0..columns as u8 { - writeln!(self.out, "{}case {}: {{ return mat._{}; }}", INDENT, i, i)?; + writeln!(self.out, "{INDENT}case {i}: {{ return mat._{i}; }}")?; } - writeln!(self.out, "{}default: {{ return (float2)0; }}", INDENT)?; - writeln!(self.out, "{}}}", INDENT)?; + writeln!(self.out, "{INDENT}default: {{ return (float2)0; }}")?; + writeln!(self.out, "{INDENT}}}")?; writeln!(self.out, "}}")?; // __set_col_of_mat @@ -1112,15 +1043,11 @@ impl<'a, W: Write> super::Writer<'a, W> { "void __set_col_of_mat{}x2(__mat{}x2 mat, uint idx, float2 value) {{", columns as u8, columns as u8 )?; - writeln!(self.out, "{}switch(idx) {{", INDENT)?; + writeln!(self.out, "{INDENT}switch(idx) {{")?; for i in 0..columns as u8 { - writeln!( - self.out, - "{}case {}: {{ mat._{} = value; break; }}", - INDENT, i, i - )?; + writeln!(self.out, "{INDENT}case {i}: {{ mat._{i} = value; break; }}")?; } - writeln!(self.out, "{}}}", INDENT)?; + writeln!(self.out, "{INDENT}}}")?; writeln!(self.out, "}}")?; // __set_el_of_mat @@ -1129,15 +1056,14 @@ impl<'a, W: Write> super::Writer<'a, W> { "void __set_el_of_mat{}x2(__mat{}x2 mat, uint idx, uint vec_idx, float value) {{", columns as u8, columns as u8 )?; - writeln!(self.out, "{}switch(idx) {{", INDENT)?; + writeln!(self.out, "{INDENT}switch(idx) {{")?; for i in 0..columns as u8 { writeln!( self.out, - "{}case {}: {{ mat._{}[vec_idx] = value; break; }}", - INDENT, i, i + "{INDENT}case {i}: {{ mat._{i}[vec_idx] = value; break; }}" )?; } - writeln!(self.out, "{}}}", INDENT)?; + writeln!(self.out, "{INDENT}}}")?; writeln!(self.out, "}}")?; writeln!(self.out)?; diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 439715045..21396c953 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -53,11 +53,11 @@ impl super::Writer<'_, W> { } match *access { SubAccess::Offset(offset) => { - write!(self.out, "{}", offset)?; + write!(self.out, "{offset}")?; } SubAccess::Index { value, stride } => { self.write_expr(module, value, func_ctx)?; - write!(self.out, "*{}", stride)?; + write!(self.out, "*{stride}")?; } } } @@ -97,7 +97,7 @@ impl super::Writer<'_, W> { let chain = mem::take(&mut self.temp_access_chain); let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; let cast = kind.to_hlsl_cast(); - write!(self.out, "{}({}.Load(", cast, var_name)?; + write!(self.out, "{cast}({var_name}.Load(")?; self.write_storage_address(module, &chain, func_ctx)?; write!(self.out, "))")?; self.temp_access_chain = chain; @@ -183,14 +183,14 @@ impl super::Writer<'_, W> { depth, index, ty: _, - } => write!(self.out, "{}{}[{}]", STORE_TEMP_NAME, depth, index)?, + } => write!(self.out, "{STORE_TEMP_NAME}{depth}[{index}]")?, StoreValue::TempAccess { depth, base, member_index, } => { let name = &self.names[&NameKey::StructMember(base, member_index)]; - write!(self.out, "{}{}.{}", STORE_TEMP_NAME, depth, name)? + write!(self.out, "{STORE_TEMP_NAME}{depth}.{name}")? } } Ok(()) @@ -233,7 +233,7 @@ impl super::Writer<'_, W> { // working around the borrow checker in `self.write_expr` let chain = mem::take(&mut self.temp_access_chain); let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; - write!(self.out, "{}{}.Store(", level, var_name)?; + write!(self.out, "{level}{var_name}.Store(")?; self.write_storage_address(module, &chain, func_ctx)?; write!(self.out, ", asuint(")?; self.write_store_value(module, &value, func_ctx)?; @@ -257,7 +257,7 @@ impl super::Writer<'_, W> { width, } => { // first, assign the value to a temporary - writeln!(self.out, "{}{{", level)?; + writeln!(self.out, "{level}{{")?; let depth = level.0 + 1; write!( self.out, @@ -293,7 +293,7 @@ impl super::Writer<'_, W> { self.temp_access_chain.pop(); } // done - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; } crate::TypeInner::Array { base, @@ -301,11 +301,11 @@ impl super::Writer<'_, W> { .. } => { // first, assign the value to a temporary - writeln!(self.out, "{}{{", level)?; + writeln!(self.out, "{level}{{")?; write!(self.out, "{}", level.next())?; self.write_value_type(module, &module.types[base].inner)?; let depth = level.next().0; - write!(self.out, " {}{}", STORE_TEMP_NAME, depth)?; + write!(self.out, " {STORE_TEMP_NAME}{depth}")?; self.write_array_size(module, base, crate::ArraySize::Constant(const_handle))?; write!(self.out, " = ")?; self.write_store_value(module, &value, func_ctx)?; @@ -324,11 +324,11 @@ impl super::Writer<'_, W> { self.temp_access_chain.pop(); } // done - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; } crate::TypeInner::Struct { ref members, .. } => { // first, assign the value to a temporary - writeln!(self.out, "{}{{", level)?; + writeln!(self.out, "{level}{{")?; let depth = level.next().0; let struct_ty = ty_resolution.handle().unwrap(); let struct_name = &self.names[&NameKey::Type(struct_ty)]; @@ -355,7 +355,7 @@ impl super::Writer<'_, W> { self.temp_access_chain.pop(); } // done - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; } _ => unreachable!(), } @@ -386,10 +386,7 @@ impl super::Writer<'_, W> { (base, AccessIndex::Constant(index)) } ref other => { - return Err(Error::Unimplemented(format!( - "Pointer access of {:?}", - other - ))) + return Err(Error::Unimplemented(format!("Pointer access of {other:?}"))) } }; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 664b326a1..1641c2ee0 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -104,7 +104,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write special constants, if needed if let Some(ref bt) = self.options.special_constants_binding { - writeln!(self.out, "struct {} {{", SPECIAL_CBUF_TYPE)?; + writeln!(self.out, "struct {SPECIAL_CBUF_TYPE} {{")?; writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_BASE_VERTEX)?; writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_BASE_INSTANCE)?; writeln!(self.out, "{}uint {};", back::INDENT, SPECIAL_OTHER)?; @@ -320,13 +320,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } => { if let Some(interpolation) = interpolation { if let Some(string) = interpolation.to_hlsl_str() { - write!(self.out, "{} ", string)? + write!(self.out, "{string} ")? } } if let Some(sampling) = sampling { if let Some(string) = sampling.to_hlsl_str() { - write!(self.out, "{} ", string)? + write!(self.out, "{string} ")? } } } @@ -346,13 +346,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *binding { crate::Binding::BuiltIn(builtin) => { let builtin_str = builtin.to_hlsl_str()?; - write!(self.out, " : {}", builtin_str)?; + write!(self.out, " : {builtin_str}")?; } crate::Binding::Location { location, .. } => { if stage == Some((crate::ShaderStage::Fragment, Io::Output)) { - write!(self.out, " : SV_Target{}", location)?; + write!(self.out, " : SV_Target{location}")?; } else { - write!(self.out, " : {}{}", LOCATION_SEMANTIC, location)?; + write!(self.out, " : {LOCATION_SEMANTIC}{location}")?; } } } @@ -372,7 +372,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // interfaces to match with regards to order. members.sort_by_key(|m| InterfaceKey::new(m.binding.as_ref())); - write!(self.out, "struct {}", struct_name)?; + write!(self.out, "struct {struct_name}")?; writeln!(self.out, " {{")?; for m in members.iter() { write!(self.out, "{}", back::INDENT)?; @@ -416,7 +416,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { stage: ShaderStage, entry_point_name: &str, ) -> Result { - let struct_name = format!("{:?}Input_{}", stage, entry_point_name); + let struct_name = format!("{stage:?}Input_{entry_point_name}"); let mut fake_members = Vec::new(); for arg in func.arguments.iter() { @@ -459,7 +459,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { stage: ShaderStage, entry_point_name: &str, ) -> Result { - let struct_name = format!("{:?}Output_{}", stage, entry_point_name); + let struct_name = format!("{stage:?}Output_{entry_point_name}"); let mut fake_members = Vec::new(); let empty = []; @@ -526,7 +526,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "{}", back::INDENT)?; self.write_type(module, arg.ty)?; let arg_name = &self.names[&NameKey::EntryPointArgument(ep_index, arg_index as u32)]; - write!(self.out, " {}", arg_name)?; + write!(self.out, " {arg_name}")?; match module.types[arg.ty].inner { TypeInner::Array { base, size, .. } => { self.write_array_size(module, base, size)?; @@ -602,7 +602,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } else { ("", "t") }; - write!(self.out, "{}ByteAddressBuffer", prefix)?; + write!(self.out, "{prefix}ByteAddressBuffer")?; register } crate::AddressSpace::Handle => { @@ -645,7 +645,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } let name = &self.names[&NameKey::GlobalVariable(handle)]; - write!(self.out, " {}", name)?; + write!(self.out, " {name}")?; // Push constants need to be assigned a binding explicitly by the consumer // since naga has no way to know the binding from the shader alone @@ -669,7 +669,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // need to write the binding array size if the type was emitted with `write_type` if let TypeInner::BindingArray { base, size, .. } = module.types[global.ty].inner { if let Some(overridden_size) = bt.binding_array_size { - write!(self.out, "[{}]", overridden_size)?; + write!(self.out, "[{overridden_size}]")?; } else { self.write_array_size(module, base, size)?; } @@ -743,24 +743,24 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { crate::ScalarValue::Bool(_) => "bool", }; let name = &self.names[&NameKey::Constant(handle)]; - write!(self.out, "{} {} = ", ty_str, name)?; + write!(self.out, "{ty_str} {name} = ")?; // Second match required to avoid heap allocation by `format!()` match *value { - crate::ScalarValue::Sint(value) => write!(self.out, "{}", value)?, - crate::ScalarValue::Uint(value) => write!(self.out, "{}", value)?, + crate::ScalarValue::Sint(value) => write!(self.out, "{value}")?, + crate::ScalarValue::Uint(value) => write!(self.out, "{value}")?, crate::ScalarValue::Float(value) => { // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero - write!(self.out, "{:?}", value)? + write!(self.out, "{value:?}")? } - crate::ScalarValue::Bool(value) => write!(self.out, "{}", value)?, + crate::ScalarValue::Bool(value) => write!(self.out, "{value}")?, }; } crate::ConstantInner::Composite { ty, ref components } => { self.write_type(module, ty)?; let name = &self.names[&NameKey::Constant(handle)]; - write!(self.out, " {} = ", name)?; + write!(self.out, " {name} = ")?; self.write_composite_constant(module, ty, components)?; } } @@ -782,7 +782,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match size { crate::ArraySize::Constant(const_handle) => { let size = module.constants[const_handle].to_array_length().unwrap(); - write!(self.out, "{}", size)?; + write!(self.out, "{size}")?; } crate::ArraySize::Dynamic => {} } @@ -815,7 +815,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ) -> BackendResult { // Write struct name let struct_name = &self.names[&NameKey::Type(handle)]; - writeln!(self.out, "struct {} {{", struct_name)?; + writeln!(self.out, "struct {struct_name} {{")?; let mut last_offset = 0; for (index, member) in members.iter().enumerate() { @@ -1011,7 +1011,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } else { "SamplerState" }; - write!(self.out, "{}", sampler)?; + write!(self.out, "{sampler}")?; } // HLSL arrays are written as `type name[size]` // Current code is written arrays only as `[size]` @@ -1019,12 +1019,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { TypeInner::Array { base, size, .. } | TypeInner::BindingArray { base, size } => { self.write_array_size(module, base, size)?; } - _ => { - return Err(Error::Unimplemented(format!( - "write_value_type {:?}", - inner - ))) - } + _ => return Err(Error::Unimplemented(format!("write_value_type {inner:?}"))), } Ok(()) @@ -1075,7 +1070,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } // Write function name - write!(self.out, " {}(", name)?; + write!(self.out, " {name}(")?; let need_workgroup_variables_initialization = self.need_workgroup_variables_initialization(func_ctx, module); @@ -1103,7 +1098,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { &self.names[&NameKey::FunctionArgument(handle, index as u32)]; // Write argument name. Space is important. - write!(self.out, " {}", argument_name)?; + write!(self.out, " {argument_name}")?; if let TypeInner::Array { base, size, .. } = module.types[arg.ty].inner { self.write_array_size(module, base, size)?; } @@ -1123,7 +1118,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let argument_name = &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)]; - write!(self.out, " {}", argument_name)?; + write!(self.out, " {argument_name}")?; if let TypeInner::Array { base, size, .. } = module.types[arg.ty].inner { self.write_array_size(module, base, size)?; } @@ -1242,8 +1237,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!( self.out, - "{}if (all(__global_invocation_id == uint3(0u, 0u, 0u))) {{", - level + "{level}if (all(__global_invocation_id == uint3(0u, 0u, 0u))) {{" )?; let vars = module.global_variables.iter().filter(|&(handle, var)| { @@ -1257,7 +1251,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, ";")?; } - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; self.write_barrier(crate::Barrier::WORK_GROUP, level) } @@ -1302,20 +1296,20 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; if let Some(name) = expr_name { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.write_named_expr(module, handle, name, func_ctx)?; } } } // TODO: copy-paste from glsl-out Statement::Block(ref block) => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; writeln!(self.out, "{{")?; for sta in block.iter() { // Increase the indentation to help with readability self.write_stmt(module, sta, func_ctx, level.next())? } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } // TODO: copy-paste from glsl-out Statement::If { @@ -1323,7 +1317,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ref accept, ref reject, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; write!(self.out, "if (")?; self.write_expr(module, condition, func_ctx)?; writeln!(self.out, ") {{")?; @@ -1337,7 +1331,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // If there are no statements in the reject block we skip writing it // This is only for readability if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", level)?; + writeln!(self.out, "{level}}} else {{")?; for sta in reject { // Increase indentation to help with readability @@ -1345,12 +1339,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } // TODO: copy-paste from glsl-out - Statement::Kill => writeln!(self.out, "{}discard;", level)?, + Statement::Kill => writeln!(self.out, "{level}discard;")?, Statement::Return { value: None } => { - writeln!(self.out, "{}return;", level)?; + writeln!(self.out, "{level}return;")?; } Statement::Return { value: Some(expr) } => { let base_ty_res = &func_ctx.info[expr].ty; @@ -1364,11 +1358,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let ty = base_ty_res.handle().unwrap(); let struct_name = &self.names[&NameKey::Type(ty)]; let variable_name = self.namer.call(&struct_name.to_lowercase()); - write!( - self.out, - "{}const {} {} = ", - level, struct_name, variable_name, - )?; + write!(self.out, "{level}const {struct_name} {variable_name} = ",)?; self.write_expr(module, expr, func_ctx)?; writeln!(self.out, ";")?; @@ -1392,16 +1382,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ", ")?; } let member_name = &self.names[&NameKey::StructMember(ty, m.index)]; - write!(self.out, "{}.{}", variable_name, member_name)?; + write!(self.out, "{variable_name}.{member_name}")?; } writeln!(self.out, " }};")?; final_name } None => variable_name, }; - writeln!(self.out, "{}return {};", level, final_name)?; + writeln!(self.out, "{level}return {final_name};")?; } else { - write!(self.out, "{}return ", level)?; + write!(self.out, "{level}return ")?; self.write_expr(module, expr, func_ctx)?; writeln!(self.out, ";")? } @@ -1507,7 +1497,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; if let Some(MatrixAccess { index, base }) = matrix { let base_ty_res = &func_ctx.info[base].ty; @@ -1530,7 +1520,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "[")?; match scalar_index { Index::Static(index) => { - write!(self.out, "{}", index)?; + write!(self.out, "{index}")?; } Index::Expression(index) => { self.write_expr(module, index, func_ctx)?; @@ -1571,7 +1561,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ", ")?; match scalar_index { Index::Static(index) => { - write!(self.out, "{}", index)?; + write!(self.out, "{index}")?; } Index::Expression(index) => { self.write_expr(module, index, func_ctx)?; @@ -1665,7 +1655,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ", ")?; match scalar_index { Index::Static(index) => { - write!(self.out, "{}", index)?; + write!(self.out, "{index}")?; } Index::Expression(index) => { self.write_expr(module, index, func_ctx)?; @@ -1719,33 +1709,33 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let l2 = level.next(); if !continuing.is_empty() || break_if.is_some() { let gate_name = self.namer.call("loop_init"); - writeln!(self.out, "{}bool {} = true;", level, gate_name)?; - writeln!(self.out, "{}while(true) {{", level)?; - writeln!(self.out, "{}if (!{}) {{", l2, gate_name)?; + writeln!(self.out, "{level}bool {gate_name} = true;")?; + writeln!(self.out, "{level}while(true) {{")?; + writeln!(self.out, "{l2}if (!{gate_name}) {{")?; let l3 = l2.next(); for sta in continuing.iter() { self.write_stmt(module, sta, func_ctx, l3)?; } if let Some(condition) = break_if { - write!(self.out, "{}if (", l3)?; + write!(self.out, "{l3}if (")?; self.write_expr(module, condition, func_ctx)?; writeln!(self.out, ") {{")?; writeln!(self.out, "{}break;", l3.next())?; - writeln!(self.out, "{}}}", l3)?; + writeln!(self.out, "{l3}}}")?; } - writeln!(self.out, "{}}}", l2)?; - writeln!(self.out, "{}{} = false;", l2, gate_name)?; + writeln!(self.out, "{l2}}}")?; + writeln!(self.out, "{l2}{gate_name} = false;")?; } else { - writeln!(self.out, "{}while(true) {{", level)?; + writeln!(self.out, "{level}while(true) {{")?; } for sta in body.iter() { self.write_stmt(module, sta, func_ctx, l2)?; } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } - Statement::Break => writeln!(self.out, "{}break;", level)?, - Statement::Continue => writeln!(self.out, "{}continue;", level)?, + Statement::Break => writeln!(self.out, "{level}break;")?, + Statement::Continue => writeln!(self.out, "{level}continue;")?, Statement::Barrier(barrier) => { self.write_barrier(barrier, level)?; } @@ -1755,7 +1745,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { array_index, value, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.write_expr(module, image, func_ctx)?; write!(self.out, "[")?; @@ -1780,7 +1770,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ref arguments, result, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; if let Some(expr) = result { write!(self.out, "const ")?; let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); @@ -1791,11 +1781,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_value_type(module, value)? } }; - write!(self.out, " {} = ", name)?; + write!(self.out, " {name} = ")?; self.named_expressions.insert(expr, name); } let func_name = &self.names[&NameKey::Function(function)]; - write!(self.out, "{}(", func_name)?; + write!(self.out, "{func_name}(")?; for (index, argument) in arguments.iter().enumerate() { self.write_expr(module, *argument, func_ctx)?; // Only write a comma if isn't the last element @@ -1812,7 +1802,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { value, result, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); match func_ctx.info[result].ty { proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?, @@ -1827,11 +1817,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; let fun_str = fun.to_hlsl_suffix(); - write!( - self.out, - " {}; {}.Interlocked{}(", - res_name, var_name, fun_str - )?; + write!(self.out, " {res_name}; {var_name}.Interlocked{fun_str}(")?; self.write_storage_address(module, &chain, func_ctx)?; write!(self.out, ", ")?; // handle the special cases @@ -1846,7 +1832,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { _ => {} } self.write_expr(module, value, func_ctx)?; - writeln!(self.out, ", {});", res_name)?; + writeln!(self.out, ", {res_name});")?; self.temp_access_chain = chain; self.named_expressions.insert(result, res_name); } @@ -1855,7 +1841,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ref cases, } => { // Start the switch - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; write!(self.out, "switch(")?; self.write_expr(module, selector, func_ctx)?; writeln!(self.out, ") {{")?; @@ -1873,13 +1859,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { for (i, case) in cases.iter().enumerate() { match case.value { - crate::SwitchValue::Integer(value) => write!( - self.out, - "{}case {}{}:", - indent_level_1, value, type_postfix - )?, + crate::SwitchValue::Integer(value) => { + write!(self.out, "{indent_level_1}case {value}{type_postfix}:")? + } crate::SwitchValue::Default => { - write!(self.out, "{}default:", indent_level_1)? + write!(self.out, "{indent_level_1}default:")? } } @@ -1923,16 +1907,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { .unwrap(); let indent_level_3 = indent_level_2.next(); for case in &cases[i..=end_case_idx] { - writeln!(self.out, "{}{{", indent_level_2)?; + writeln!(self.out, "{indent_level_2}{{")?; for sta in case.body.iter() { self.write_stmt(module, sta, func_ctx, indent_level_3)?; } - writeln!(self.out, "{}}}", indent_level_2)?; + writeln!(self.out, "{indent_level_2}}}")?; } let last_case = &cases[end_case_idx]; if last_case.body.last().map_or(true, |s| !s.is_terminator()) { - writeln!(self.out, "{}break;", indent_level_2)?; + writeln!(self.out, "{indent_level_2}break;")?; } } else { for sta in case.body.iter() { @@ -1941,16 +1925,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if !case.fall_through && case.body.last().map_or(true, |s| !s.is_terminator()) { - writeln!(self.out, "{}break;", indent_level_2)?; + writeln!(self.out, "{indent_level_2}break;")?; } } if write_block_braces { - writeln!(self.out, "{}}}", indent_level_1)?; + writeln!(self.out, "{indent_level_1}}}")?; } } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } } @@ -1977,15 +1961,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; let closing_bracket = match ff_input { Some(crate::BuiltIn::VertexIndex) => { - write!(self.out, "({}.{} + ", SPECIAL_CBUF_VAR, SPECIAL_BASE_VERTEX)?; + write!(self.out, "({SPECIAL_CBUF_VAR}.{SPECIAL_BASE_VERTEX} + ")?; ")" } Some(crate::BuiltIn::InstanceIndex) => { - write!( - self.out, - "({}.{} + ", - SPECIAL_CBUF_VAR, SPECIAL_BASE_INSTANCE, - )?; + write!(self.out, "({SPECIAL_CBUF_VAR}.{SPECIAL_BASE_INSTANCE} + ",)?; ")" } Some(crate::BuiltIn::NumWorkGroups) => { @@ -1994,13 +1974,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // of workgroups, which we are using here. write!( self.out, - "uint3({}.{}, {}.{}, {}.{})", - SPECIAL_CBUF_VAR, - SPECIAL_BASE_VERTEX, - SPECIAL_CBUF_VAR, - SPECIAL_BASE_INSTANCE, - SPECIAL_CBUF_VAR, - SPECIAL_OTHER, + "uint3({SPECIAL_CBUF_VAR}.{SPECIAL_BASE_VERTEX}, {SPECIAL_CBUF_VAR}.{SPECIAL_BASE_INSTANCE}, {SPECIAL_CBUF_VAR}.{SPECIAL_OTHER})", )?; return Ok(()); } @@ -2008,7 +1982,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; if let Some(name) = self.named_expressions.get(&expr) { - write!(self.out, "{}{}", name, closing_bracket)?; + write!(self.out, "{name}{closing_bracket}")?; return Ok(()); } @@ -2177,7 +2151,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } TypeInner::Matrix { .. } | TypeInner::Array { .. } - | TypeInner::BindingArray { .. } => write!(writer.out, "[{}]", index)?, + | TypeInner::BindingArray { .. } => write!(writer.out, "[{index}]")?, TypeInner::Struct { .. } => { // This will never panic in case the type is a `Struct`, this is not true // for other types so we can only check while inside this match arm @@ -2190,7 +2164,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { )? } ref other => { - return Err(Error::Custom(format!("Cannot index {:?}", other))) + return Err(Error::Custom(format!("Cannot index {other:?}"))) } } Ok(()) @@ -2205,7 +2179,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }) = get_inner_matrix_of_struct_array_member(module, base, func_ctx, true) { self.write_expr(module, base, func_ctx)?; - write!(self.out, "._{}", index)?; + write!(self.out, "._{index}")?; return Ok(()); } @@ -2257,7 +2231,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } }; let name = &self.names[&key]; - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; } Expression::ImageSample { image, @@ -2289,11 +2263,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; self.write_expr(module, image, func_ctx)?; - write!( - self.out, - ".{}{}{}{}(", - base_str, cmp_str, component_str, level_str - )?; + write!(self.out, ".{base_str}{cmp_str}{component_str}{level_str}(")?; self.write_expr(module, sampler, func_ctx)?; write!(self.out, ", ")?; self.write_texture_coordinates( @@ -2399,7 +2369,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { crate::AddressSpace::Storage { .. } => {} _ => { let name = &self.names[&NameKey::GlobalVariable(handle)]; - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; } }, Expression::LocalVariable(handle) => { @@ -2470,13 +2440,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Some(Sk::Bool) => "!", ref other => { return Err(Error::Custom(format!( - "Cannot apply not to type {:?}", - other + "Cannot apply not to type {other:?}" ))) } }, }; - write!(self.out, "{}(", op_str)?; + write!(self.out, "{op_str}(")?; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")?; } @@ -2511,8 +2480,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } _ => { return Err(Error::Unimplemented(format!( - "write_expr expression::as {:?}", - inner + "write_expr expression::as {inner:?}" ))); } }; @@ -2606,7 +2574,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::FindLsb => Function::Regular("firstbitlow"), Mf::FindMsb => Function::Regular("firstbithigh"), Mf::Unpack2x16float => Function::Unpack2x16float, - _ => return Err(Error::Unimplemented(format!("write_expr_math {:?}", fun))), + _ => return Err(Error::Unimplemented(format!("write_expr_math {fun:?}"))), }; match fun { @@ -2637,7 +2605,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ") >> 16))")?; } Function::Regular(fun_name) => { - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; self.write_expr(module, arg, func_ctx)?; if let Some(arg) = arg1 { write!(self.out, ", ")?; @@ -2659,11 +2627,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { .inner_with(&module.types) .scalar_kind(); if let Some(ScalarKind::Sint) = *scalar_kind { - write!(self.out, "asint({}(asuint(", fun_name)?; + write!(self.out, "asint({fun_name}(asuint(")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, ")))")?; } else { - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, ")")?; } @@ -2718,7 +2686,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "((")?; self.write_wrapped_array_length_function_name(wrapped_array_length)?; let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; - write!(self.out, "({}) - {}) / {})", var_name, offset, stride)? + write!(self.out, "({var_name}) - {offset}) / {stride})")? } Expression::Derivative { axis, expr } => { use crate::DerivativeAxis as Da; @@ -2728,7 +2696,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Da::Y => "ddy", Da::Width => "fwidth", }; - write!(self.out, "{}(", fun_str)?; + write!(self.out, "{fun_str}(")?; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")? } @@ -2743,7 +2711,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Rf::IsFinite => "isfinite", Rf::IsNormal => "isnormal", }; - write!(self.out, "{}(", fun_str)?; + write!(self.out, "{fun_str}(")?; self.write_expr(module, argument, func_ctx)?; write!(self.out, ")")? } @@ -2758,7 +2726,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; write!(self.out, "(")?; self.write_expr(module, value, func_ctx)?; - write!(self.out, ").{}", number_of_components)? + write!(self.out, ").{number_of_components}")? } Expression::Select { condition, @@ -2778,7 +2746,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } if !closing_bracket.is_empty() { - write!(self.out, "{}", closing_bracket)?; + write!(self.out, "{closing_bracket}")?; } Ok(()) } @@ -2848,12 +2816,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { use crate::ScalarValue as Sv; match value { - Sv::Sint(value) => write!(self.out, "{}", value)?, - Sv::Uint(value) => write!(self.out, "{}u", value)?, + Sv::Sint(value) => write!(self.out, "{value}")?, + Sv::Uint(value) => write!(self.out, "{value}u")?, // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero - Sv::Float(value) => write!(self.out, "{:?}", value)?, - Sv::Bool(value) => write!(self.out, "{}", value)?, + Sv::Float(value) => write!(self.out, "{value:?}")?, + Sv::Bool(value) => write!(self.out, "{value}")?, } Ok(()) @@ -2870,7 +2838,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { proc::TypeResolution::Handle(ty_handle) => match module.types[ty_handle].inner { TypeInner::Struct { .. } => { let ty_name = &self.names[&NameKey::Type(ty_handle)]; - write!(self.out, "{}", ty_name)?; + write!(self.out, "{ty_name}")?; } _ => { self.write_type(module, ty_handle)?; @@ -2884,7 +2852,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let base_ty_res = &ctx.info[handle].ty; let resolved = base_ty_res.inner_with(&module.types); - write!(self.out, " {}", name)?; + write!(self.out, " {name}")?; // If rhs is a array type, we should write array size if let TypeInner::Array { base, size, .. } = *resolved { self.write_array_size(module, base, size)?; @@ -2910,10 +2878,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { fn write_barrier(&mut self, barrier: crate::Barrier, level: back::Level) -> BackendResult { if barrier.contains(crate::Barrier::STORAGE) { - writeln!(self.out, "{}DeviceMemoryBarrierWithGroupSync();", level)?; + writeln!(self.out, "{level}DeviceMemoryBarrierWithGroupSync();")?; } if barrier.contains(crate::Barrier::WORK_GROUP) { - writeln!(self.out, "{}GroupMemoryBarrierWithGroupSync();", level)?; + writeln!(self.out, "{level}GroupMemoryBarrierWithGroupSync();")?; } Ok(()) } diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 679e5ed29..271557fbf 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -412,16 +412,16 @@ impl ResolvedBinding { return Err(Error::UnsupportedBuiltIn(built_in)) } }; - write!(out, "{}", name)?; + write!(out, "{name}")?; } - Self::Attribute(index) => write!(out, "attribute({})", index)?, - Self::Color(index) => write!(out, "color({})", index)?, + Self::Attribute(index) => write!(out, "attribute({index})")?, + Self::Color(index) => write!(out, "color({index})")?, Self::User { prefix, index, interpolation, } => { - write!(out, "user({}{})", prefix, index)?; + write!(out, "user({prefix}{index})")?; if let Some(interpolation) = interpolation { write!(out, ", ")?; interpolation.try_fmt(out)?; @@ -429,11 +429,11 @@ impl ResolvedBinding { } Self::Resource(ref target) => { if let Some(id) = target.buffer { - write!(out, "buffer({})", id)?; + write!(out, "buffer({id})")?; } else if let Some(id) = target.texture { - write!(out, "texture({})", id)?; + write!(out, "texture({id})")?; } else if let Some(BindSamplerTarget::Resource(id)) = target.sampler { - write!(out, "sampler({})", id)?; + write!(out, "sampler({id})")?; } else { return Err(Error::UnimplementedBindTarget(target.clone())); } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 5b505b358..b72c76783 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -82,7 +82,7 @@ impl<'a> Display for TypeContext<'a> { let ty = &self.module.types[self.handle]; if ty.needs_alias() && !self.first_time { let name = &self.names[&NameKey::Type(self.handle)]; - return write!(out, "{}", name); + return write!(out, "{name}"); } match ty.inner { @@ -104,7 +104,7 @@ impl<'a> Display for TypeContext<'a> { Some(name) => name, None => return Ok(()), }; - write!(out, "{} {}&", space_name, sub) + write!(out, "{space_name} {sub}&") } crate::TypeInner::ValuePointer { size, @@ -113,7 +113,7 @@ impl<'a> Display for TypeContext<'a> { space, } => { match space.to_msl_name() { - Some(name) => write!(out, "{} ", name)?, + Some(name) => write!(out, "{name} ")?, None => return Ok(()), }; match size { @@ -131,7 +131,7 @@ impl<'a> Display for TypeContext<'a> { }; // Array lengths go at the end of the type definition, // so just print the element type here. - write!(out, "{}", sub) + write!(out, "{sub}") } crate::TypeInner::Struct { .. } => unreachable!(), crate::TypeInner::Image { @@ -188,19 +188,11 @@ impl<'a> Display for TypeContext<'a> { let array_str = if arrayed { "_array" } else { "" }; write!( out, - "{}::{}{}{}{}<{}, {}::access::{}>", - NAMESPACE, - texture_str, - dim_str, - msaa_str, - array_str, - base_name, - NAMESPACE, - access, + "{NAMESPACE}::{texture_str}{dim_str}{msaa_str}{array_str}<{base_name}, {NAMESPACE}::access::{access}>", ) } crate::TypeInner::Sampler { comparison: _ } => { - write!(out, "{}::sampler", NAMESPACE) + write!(out, "{NAMESPACE}::sampler") } crate::TypeInner::BindingArray { base, size } => { let base_tyname = Self { @@ -214,11 +206,7 @@ impl<'a> Display for TypeContext<'a> { .. })) = self.binding { - write!( - out, - "{}::array<{}, {}>", - NAMESPACE, base_tyname, override_size - ) + write!(out, "{NAMESPACE}::array<{base_tyname}, {override_size}>") } else if let crate::ArraySize::Constant(size) = size { let constant_ctx = ConstantContext { handle: size, @@ -226,11 +214,7 @@ impl<'a> Display for TypeContext<'a> { names: self.names, first_time: false, }; - write!( - out, - "{}::array<{}, {}>", - NAMESPACE, base_tyname, constant_ctx - ) + write!(out, "{NAMESPACE}::array<{base_tyname}, {constant_ctx}>") } else { unreachable!("metal requires all arrays be constant sized"); } @@ -321,31 +305,31 @@ impl<'a> Display for ConstantContext<'a> { let con = &self.arena[self.handle]; if con.needs_alias() && !self.first_time { let name = &self.names[&NameKey::Constant(self.handle)]; - return write!(out, "{}", name); + return write!(out, "{name}"); } match con.inner { crate::ConstantInner::Scalar { value, width: _ } => match value { crate::ScalarValue::Sint(value) => { - write!(out, "{}", value) + write!(out, "{value}") } crate::ScalarValue::Uint(value) => { - write!(out, "{}u", value) + write!(out, "{value}u") } crate::ScalarValue::Float(value) => { if value.is_infinite() { let sign = if value.is_sign_negative() { "-" } else { "" }; - write!(out, "{}INFINITY", sign) + write!(out, "{sign}INFINITY") } else if value.is_nan() { write!(out, "NAN") } else { let suffix = if value.fract() == 0.0 { ".0" } else { "" }; - write!(out, "{}{}", value, suffix) + write!(out, "{value}{suffix}") } } crate::ScalarValue::Bool(value) => { - write!(out, "{}", value) + write!(out, "{value}") } }, crate::ConstantInner::Composite { .. } => unreachable!("should be aliased"), @@ -693,7 +677,7 @@ impl Writer { context: &ExpressionContext, ) -> BackendResult { self.put_expression(image, context, false)?; - write!(self.out, ".get_{}(", query)?; + write!(self.out, ".get_{query}(")?; if let Some(level) = level { self.put_level_of_detail(level, context)?; } @@ -731,14 +715,14 @@ impl Writer { } } crate::ImageDimension::D2 => { - write!(self.out, "{}::{}2(", NAMESPACE, coordinate_type)?; + write!(self.out, "{NAMESPACE}::{coordinate_type}2(")?; self.put_image_query(image, "width", level, context)?; write!(self.out, ", ")?; self.put_image_query(image, "height", level, context)?; write!(self.out, ")")?; } crate::ImageDimension::D3 => { - write!(self.out, "{}::{}3(", NAMESPACE, coordinate_type)?; + write!(self.out, "{NAMESPACE}::{coordinate_type}3(")?; self.put_image_query(image, "width", level, context)?; write!(self.out, ", ")?; self.put_image_query(image, "height", level, context)?; @@ -747,7 +731,7 @@ impl Writer { write!(self.out, ")")?; } crate::ImageDimension::Cube => { - write!(self.out, "{}::{}2(", NAMESPACE, coordinate_type)?; + write!(self.out, "{NAMESPACE}::{coordinate_type}2(")?; self.put_image_query(image, "width", level, context)?; write!(self.out, ")")?; } @@ -793,17 +777,17 @@ impl Writer { log::warn!("1D image can't be sampled with level {:?}", level); } crate::SampleLevel::Exact(h) => { - write!(self.out, ", {}::level(", NAMESPACE)?; + write!(self.out, ", {NAMESPACE}::level(")?; self.put_expression(h, context, true)?; write!(self.out, ")")?; } crate::SampleLevel::Bias(h) => { - write!(self.out, ", {}::bias(", NAMESPACE)?; + write!(self.out, ", {NAMESPACE}::bias(")?; self.put_expression(h, context, true)?; write!(self.out, ")")?; } crate::SampleLevel::Gradient { x, y } => { - write!(self.out, ", {}::gradient2d(", NAMESPACE)?; + write!(self.out, ", {NAMESPACE}::gradient2d(")?; self.put_expression(x, context, true)?; write!(self.out, ", ")?; self.put_expression(y, context, true)?; @@ -848,11 +832,11 @@ impl Writer { limit_method: &str, context: &ExpressionContext, ) -> BackendResult { - write!(self.out, "{}::min(uint(", NAMESPACE)?; + write!(self.out, "{NAMESPACE}::min(uint(")?; self.put_expression(index, context, true)?; write!(self.out, "), ")?; self.put_expression(image, context, false)?; - write!(self.out, ".{}() - 1)", limit_method)?; + write!(self.out, ".{limit_method}() - 1)")?; Ok(()) } @@ -863,7 +847,7 @@ impl Writer { context: &ExpressionContext, ) -> BackendResult { // Write the coordinate. - write!(self.out, "{}::min(", NAMESPACE)?; + write!(self.out, "{NAMESPACE}::min(")?; self.put_cast_to_uint_scalar_or_vector(address.coordinate, context)?; write!(self.out, ", ")?; self.put_image_coordinate_limits(image, address.level, context)?; @@ -926,7 +910,7 @@ impl Writer { // Check array index, if present. if let Some(array_index) = address.array_index { - write!(self.out, "{}uint(", conjunction)?; + write!(self.out, "{conjunction}uint(")?; self.put_expression(array_index, context, true)?; write!(self.out, ") < ")?; self.put_expression(image, context, true)?; @@ -939,9 +923,9 @@ impl Writer { crate::TypeInner::Vector { .. } => true, _ => false, }; - write!(self.out, "{}", conjunction)?; + write!(self.out, "{conjunction}")?; if coord_is_vector { - write!(self.out, "{}::all(", NAMESPACE)?; + write!(self.out, "{NAMESPACE}::all(")?; } self.put_cast_to_uint_scalar_or_vector(address.coordinate, context)?; write!(self.out, " < ")?; @@ -1035,7 +1019,7 @@ impl Writer { // support writes to mipmapped textures. debug_assert!(address.level.is_none()); - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.put_expression(image, &context.expression, false)?; write!(self.out, ".write(")?; self.put_expression(value, &context.expression, true)?; @@ -1044,11 +1028,11 @@ impl Writer { writeln!(self.out, ");")?; } proc::BoundsCheckPolicy::ReadZeroSkipWrite => { - write!(self.out, "{}if (", level)?; + write!(self.out, "{level}if (")?; self.put_image_access_bounds_check(image, address, &context.expression)?; writeln!(self.out, ") {{")?; self.put_unchecked_image_store(level.next(), image, address, value, context)?; - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; } proc::BoundsCheckPolicy::Unchecked => { self.put_unchecked_image_store(level, image, address, value, context)?; @@ -1066,7 +1050,7 @@ impl Writer { value: Handle, context: &StatementContext, ) -> BackendResult { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.put_expression(image, &context.expression, false)?; write!(self.out, ".write(")?; self.put_expression(value, &context.expression, true)?; @@ -1213,13 +1197,12 @@ impl Writer { write!( self.out, - "{}::atomic_{}{}_explicit({}", - NAMESPACE, key1, key2, ATOMIC_REFERENCE + "{NAMESPACE}::atomic_{key1}{key2}_explicit({ATOMIC_REFERENCE}" )?; self.put_access_chain(pointer, policy, context)?; write!(self.out, ", ")?; self.put_expression(value, context, true)?; - write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; + write!(self.out, ", {NAMESPACE}::memory_order_relaxed)")?; // Finish the ternary expression. if checked { @@ -1253,13 +1236,13 @@ impl Writer { // it shouldn't produce large expressions. self.put_expression(arg, context, true)?; // Access the current component on the first vector - write!(self.out, ".{} * ", component)?; + write!(self.out, ".{component} * ")?; // Write the second vector expression, this expression is marked to be // cached so unless it can't be cached (for example, it's a Constant) // it shouldn't produce large expressions. self.put_expression(arg1, context, true)?; // Access the current component on the second vector - write!(self.out, ".{}", component)?; + write!(self.out, ".{component}")?; } write!(self.out, ")")?; @@ -1290,7 +1273,7 @@ impl Writer { .insert(&expr_handle as *const _ as *const ()); if let Some(name) = self.named_expressions.get(&expr_handle) { - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; return Ok(()); } @@ -1331,7 +1314,7 @@ impl Writer { names: &self.names, first_time: false, }; - write!(self.out, "{}", coco)?; + write!(self.out, "{coco}")?; } crate::Expression::Splat { size, value } => { let scalar_kind = match *context.resolve_type(value) { @@ -1365,11 +1348,11 @@ impl Writer { } }; let name = &self.names[&name_key]; - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; } crate::Expression::GlobalVariable(handle) => { let name = &self.names[&NameKey::GlobalVariable(handle)]; - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; } crate::Expression::LocalVariable(handle) => { let name_key = match context.origin { @@ -1381,7 +1364,7 @@ impl Writer { } }; let name = &self.names[&name_key]; - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; } crate::Expression::Load { pointer } => self.put_load(pointer, context, is_scoped)?, crate::Expression::ImageSample { @@ -1403,7 +1386,7 @@ impl Writer { None => "", }; self.put_expression(image, context, false)?; - write!(self.out, ".{}{}(", main_op, comparison_op)?; + write!(self.out, ".{main_op}{comparison_op}(")?; self.put_expression(sampler, context, true)?; write!(self.out, ", ")?; self.put_expression(coordinate, context, true)?; @@ -1425,7 +1408,7 @@ impl Writer { names: &self.names, first_time: false, }; - write!(self.out, ", {}", coco)?; + write!(self.out, ", {coco}")?; } match gather { None | Some(crate::SwizzleComponent::X) => {} @@ -1440,10 +1423,10 @@ impl Writer { // Offset always comes before the gather, except // in cube maps where it's not applicable if offset.is_none() && !is_cube_map { - write!(self.out, ", {}::int2(0)", NAMESPACE)?; + write!(self.out, ", {NAMESPACE}::int2(0)")?; } let letter = back::COMPONENTS[component as usize]; - write!(self.out, ", {}::component::{}", NAMESPACE, letter)?; + write!(self.out, ", {NAMESPACE}::component::{letter}")?; } } write!(self.out, ")")?; @@ -1500,7 +1483,7 @@ impl Writer { _ => return Err(Error::Validation), }, }; - write!(self.out, "{}(", op_str)?; + write!(self.out, "{op_str}(")?; self.put_expression(expr, context, false)?; write!(self.out, ")")?; } @@ -1525,7 +1508,7 @@ impl Writer { // if right == 0 return ? see https://github.com/gpuweb/gpuweb/issues/2798 if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float { - write!(self.out, "{}::fmod(", NAMESPACE)?; + write!(self.out, "{NAMESPACE}::fmod(")?; self.put_expression(left, context, true)?; write!(self.out, ", ")?; self.put_expression(right, context, true)?; @@ -1548,7 +1531,7 @@ impl Writer { self.put_expression(left, context, false)?; } - write!(self.out, " {} ", op_str)?; + write!(self.out, " {op_str} ")?; // See comment above if op == crate::BinaryOperator::Multiply @@ -1589,7 +1572,7 @@ impl Writer { kind: crate::ScalarKind::Bool, .. } => { - write!(self.out, "{}::select(", NAMESPACE)?; + write!(self.out, "{NAMESPACE}::select(")?; self.put_expression(reject, context, true)?; write!(self.out, ", ")?; self.put_expression(accept, context, true)?; @@ -1605,7 +1588,7 @@ impl Writer { crate::DerivativeAxis::Y => "dfdy", crate::DerivativeAxis::Width => "fwidth", }; - write!(self.out, "{}::{}", NAMESPACE, op)?; + write!(self.out, "{NAMESPACE}::{op}")?; self.put_call_parameters(iter::once(expr), context)?; } crate::Expression::Relational { fun, argument } => { @@ -1617,7 +1600,7 @@ impl Writer { crate::RelationalFunction::IsFinite => "isfinite", crate::RelationalFunction::IsNormal => "isnormal", }; - write!(self.out, "{}::{}", NAMESPACE, op)?; + write!(self.out, "{NAMESPACE}::{op}")?; self.put_call_parameters(iter::once(argument), context)?; } crate::Expression::Math { @@ -1685,7 +1668,7 @@ impl Writer { "Correct TypeInner for dot product should be already validated" ), }, - Mf::Outer => return Err(Error::UnsupportedCall(format!("{:?}", fun))), + Mf::Outer => return Err(Error::UnsupportedCall(format!("{fun:?}"))), Mf::Cross => "cross", Mf::Distance => "distance", Mf::Length if scalar_argument => "abs", @@ -1702,7 +1685,7 @@ impl Writer { Mf::SmoothStep => "smoothstep", Mf::Sqrt => "sqrt", Mf::InverseSqrt => "rsqrt", - Mf::Inverse => return Err(Error::UnsupportedCall(format!("{:?}", fun))), + Mf::Inverse => return Err(Error::UnsupportedCall(format!("{fun:?}"))), Mf::Transpose => "transpose", Mf::Determinant => "determinant", // bits @@ -1727,17 +1710,17 @@ impl Writer { }; if fun == Mf::Distance && scalar_argument { - write!(self.out, "{}::abs(", NAMESPACE)?; + write!(self.out, "{NAMESPACE}::abs(")?; self.put_expression(arg, context, false)?; write!(self.out, " - ")?; self.put_expression(arg1.unwrap(), context, false)?; write!(self.out, ")")?; } else if fun == Mf::FindLsb { - write!(self.out, "((({}::ctz(", NAMESPACE)?; + write!(self.out, "((({NAMESPACE}::ctz(")?; self.put_expression(arg, context, true)?; write!(self.out, ") + 1) % 33) - 1)")?; } else if fun == Mf::FindMsb { - write!(self.out, "((({}::clz(", NAMESPACE)?; + write!(self.out, "((({NAMESPACE}::clz(")?; self.put_expression(arg, context, true)?; write!(self.out, ") + 1) % 33) - 1)")? } else if fun == Mf::Unpack2x16float { @@ -1757,7 +1740,7 @@ impl Writer { self.put_expression(arg, context, false)?; write!(self.out, ") * 57.295779513082322865)")?; } else { - write!(self.out, "{}::{}", NAMESPACE, fun_name)?; + write!(self.out, "{NAMESPACE}::{fun_name}")?; self.put_call_parameters( iter::once(arg).chain(arg1).chain(arg2).chain(arg3), context, @@ -1788,7 +1771,7 @@ impl Writer { Some(_) => return Err(Error::Validation), None => "as_type", }; - write!(self.out, "{}<", op)?; + write!(self.out, "{op}<")?; match *context.resolve_type(expr) { crate::TypeInner::Vector { size, .. } => { put_numeric_type(&mut self.out, kind, &[size])? @@ -1865,7 +1848,7 @@ impl Writer { index::GuardedIndex::Expression(expr) => { self.put_expression(expr, context, is_scoped)? } - index::GuardedIndex::Known(value) => write!(self.out, "{}", value)?, + index::GuardedIndex::Known(value) => write!(self.out, "{value}")?, } Ok(()) } @@ -1937,7 +1920,7 @@ impl Writer { if check_written { write!(self.out, " && ")?; } else { - write!(self.out, "{}{}", level, prefix)?; + write!(self.out, "{level}{prefix}")?; check_written = true; } @@ -1948,7 +1931,7 @@ impl Writer { self.put_index(index, context, true)?; self.out.write_str(") < ")?; match length { - index::IndexableLength::Known(value) => write!(self.out, "{}", value)?, + index::IndexableLength::Known(value) => write!(self.out, "{value}")?, index::IndexableLength::Dynamic => { let global = context .function @@ -2028,14 +2011,14 @@ impl Writer { let base_ty = base_ty_handle.unwrap(); self.put_access_chain(base, policy, context)?; let name = &self.names[&NameKey::StructMember(base_ty, index)]; - write!(self.out, ".{}", name)?; + write!(self.out, ".{name}")?; } crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => { self.put_access_chain(base, policy, context)?; // Prior to Metal v2.1 component access for packed vectors wasn't available // however array indexing is if context.get_packed_vec_kind(base).is_some() { - write!(self.out, "[{}]", index)?; + write!(self.out, "[{index}]")?; } else { write!(self.out, ".{}", back::COMPONENTS[index as usize])?; } @@ -2091,7 +2074,7 @@ impl Writer { self.put_access_chain(base, policy, context)?; if accessing_wrapped_array { - write!(self.out, ".{}", WRAPPED_ARRAY_FIELD)?; + write!(self.out, ".{WRAPPED_ARRAY_FIELD}")?; } write!(self.out, "[")?; @@ -2102,7 +2085,7 @@ impl Writer { None }; if let Some(limit) = restriction_needed { - write!(self.out, "{}::min(unsigned(", NAMESPACE)?; + write!(self.out, "{NAMESPACE}::min(unsigned(")?; self.put_index(index, context, true)?; write!(self.out, "), ")?; match limit { @@ -2175,11 +2158,10 @@ impl Writer { if is_atomic { write!( self.out, - "{}::atomic_load_explicit({}", - NAMESPACE, ATOMIC_REFERENCE + "{NAMESPACE}::atomic_load_explicit({ATOMIC_REFERENCE}" )?; self.put_access_chain(pointer, policy, context)?; - write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?; + write!(self.out, ", {NAMESPACE}::memory_order_relaxed)")?; } else { // We don't do any dereferencing with `*` here as pointer arguments to functions // are done by `&` references and not `*` pointers. These do not need to be @@ -2204,10 +2186,10 @@ impl Writer { match context.module.types[result_ty].inner { crate::TypeInner::Struct { ref members, .. } => { let tmp = "_tmp"; - write!(self.out, "{}const auto {} = ", level, tmp)?; + write!(self.out, "{level}const auto {tmp} = ")?; self.put_expression(expr_handle, context, true)?; writeln!(self.out, ";")?; - write!(self.out, "{}return {} {{", level, struct_name)?; + write!(self.out, "{level}return {struct_name} {{")?; let mut is_first = true; @@ -2240,25 +2222,21 @@ impl Writer { let size = context.module.constants[const_handle] .to_array_length() .unwrap(); - write!(self.out, "{} {{", comma)?; + write!(self.out, "{comma} {{")?; for j in 0..size { if j != 0 { write!(self.out, ",")?; } - write!( - self.out, - "{}.{}.{}[{}]", - tmp, name, WRAPPED_ARRAY_FIELD, j - )?; + write!(self.out, "{tmp}.{name}.{WRAPPED_ARRAY_FIELD}[{j}]")?; } write!(self.out, "}}")?; } else { - write!(self.out, "{} {}.{}", comma, tmp, name)?; + write!(self.out, "{comma} {tmp}.{name}")?; } } } _ => { - write!(self.out, "{}return {} {{ ", level, struct_name)?; + write!(self.out, "{level}return {struct_name} {{ ")?; self.put_expression(expr_handle, context, true)?; } } @@ -2276,7 +2254,7 @@ impl Writer { write!(self.out, " }}")?; } None => { - write!(self.out, "{}return ", level)?; + write!(self.out, "{level}return ")?; self.put_expression(expr_handle, context, true)?; } } @@ -2353,7 +2331,7 @@ impl Writer { binding: None, first_time: false, }; - write!(self.out, "{}", ty_name)?; + write!(self.out, "{ty_name}")?; } TypeResolution::Value(crate::TypeInner::Scalar { kind, .. }) => { put_numeric_type(&mut self.out, kind, &[])?; @@ -2371,7 +2349,7 @@ impl Writer { } //TODO: figure out the naming scheme that wouldn't collide with user names. - write!(self.out, " {} = ", name)?; + write!(self.out, " {name} = ")?; Ok(()) } @@ -2498,7 +2476,7 @@ impl Writer { }; if let Some(name) = expr_name { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.start_baking_expression(handle, &context.expression, &name)?; self.put_expression(handle, &context.expression, true)?; self.named_expressions.insert(handle, name); @@ -2508,9 +2486,9 @@ impl Writer { } crate::Statement::Block(ref block) => { if !block.is_empty() { - writeln!(self.out, "{}{{", level)?; + writeln!(self.out, "{level}{{")?; self.put_block(level.next(), block, context)?; - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; } } crate::Statement::If { @@ -2518,21 +2496,21 @@ impl Writer { ref accept, ref reject, } => { - write!(self.out, "{}if (", level)?; + write!(self.out, "{level}if (")?; self.put_expression(condition, &context.expression, true)?; writeln!(self.out, ") {{")?; self.put_block(level.next(), accept, context)?; if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", level)?; + writeln!(self.out, "{level}}} else {{")?; self.put_block(level.next(), reject, context)?; } - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; } crate::Statement::Switch { selector, ref cases, } => { - write!(self.out, "{}switch(", level)?; + write!(self.out, "{level}switch(")?; self.put_expression(selector, &context.expression, true)?; let type_postfix = match *context.expression.resolve_type(selector) { crate::TypeInner::Scalar { @@ -2546,10 +2524,10 @@ impl Writer { for case in cases.iter() { match case.value { crate::SwitchValue::Integer(value) => { - write!(self.out, "{}case {}{}:", lcase, value, type_postfix)?; + write!(self.out, "{lcase}case {value}{type_postfix}:")?; } crate::SwitchValue::Default => { - write!(self.out, "{}default:", lcase)?; + write!(self.out, "{lcase}default:")?; } } @@ -2568,10 +2546,10 @@ impl Writer { } if write_block_braces { - writeln!(self.out, "{}}}", lcase)?; + writeln!(self.out, "{lcase}}}")?; } } - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; } crate::Statement::Loop { ref body, @@ -2580,32 +2558,32 @@ impl Writer { } => { if !continuing.is_empty() || break_if.is_some() { let gate_name = self.namer.call("loop_init"); - writeln!(self.out, "{}bool {} = true;", level, gate_name)?; - writeln!(self.out, "{}while(true) {{", level)?; + writeln!(self.out, "{level}bool {gate_name} = true;")?; + writeln!(self.out, "{level}while(true) {{")?; let lif = level.next(); let lcontinuing = lif.next(); - writeln!(self.out, "{}if (!{}) {{", lif, gate_name)?; + writeln!(self.out, "{lif}if (!{gate_name}) {{")?; self.put_block(lcontinuing, continuing, context)?; if let Some(condition) = break_if { - write!(self.out, "{}if (", lcontinuing)?; + write!(self.out, "{lcontinuing}if (")?; self.put_expression(condition, &context.expression, true)?; writeln!(self.out, ") {{")?; writeln!(self.out, "{}break;", lcontinuing.next())?; - writeln!(self.out, "{}}}", lcontinuing)?; + writeln!(self.out, "{lcontinuing}}}")?; } - writeln!(self.out, "{}}}", lif)?; - writeln!(self.out, "{}{} = false;", lif, gate_name)?; + writeln!(self.out, "{lif}}}")?; + writeln!(self.out, "{lif}{gate_name} = false;")?; } else { - writeln!(self.out, "{}while(true) {{", level)?; + writeln!(self.out, "{level}while(true) {{")?; } self.put_block(level.next(), body, context)?; - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; } crate::Statement::Break => { - writeln!(self.out, "{}break;", level)?; + writeln!(self.out, "{level}break;")?; } crate::Statement::Continue => { - writeln!(self.out, "{}continue;", level)?; + writeln!(self.out, "{level}continue;")?; } crate::Statement::Return { value: Some(expr_handle), @@ -2618,10 +2596,10 @@ impl Writer { )?; } crate::Statement::Return { value: None } => { - writeln!(self.out, "{}return;", level)?; + writeln!(self.out, "{level}return;")?; } crate::Statement::Kill => { - writeln!(self.out, "{}{}::discard_fragment();", level, NAMESPACE)?; + writeln!(self.out, "{level}{NAMESPACE}::discard_fragment();")?; } crate::Statement::Barrier(flags) => { self.write_barrier(flags, level)?; @@ -2648,14 +2626,14 @@ impl Writer { ref arguments, result, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; if let Some(expr) = result { let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); self.start_baking_expression(expr, &context.expression, &name)?; self.named_expressions.insert(expr, name); } let fun_name = &self.names[&NameKey::Function(function)]; - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; // first, write down the actual arguments for (i, &handle) in arguments.iter().enumerate() { if i != 0 { @@ -2678,7 +2656,7 @@ impl Writer { } else { separate = true; } - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; } supports_array_length |= needs_array_length(var.ty, &context.expression.module.types); @@ -2699,7 +2677,7 @@ impl Writer { value, result, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); self.start_baking_expression(result, &context.expression, &res_name)?; self.named_expressions.insert(result, res_name); @@ -2771,7 +2749,7 @@ impl Writer { { writeln!(self.out, ") {{")?; self.put_unchecked_store(pointer, value, policy, level.next(), context)?; - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; } else { self.put_unchecked_store(pointer, value, policy, level, context)?; } @@ -2807,23 +2785,22 @@ impl Writer { let size = context.expression.module.constants[const_handle] .to_array_length() .unwrap(); - write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?; + write!(self.out, "{level}for(int _i=0; _i<{size}; ++_i) ")?; self.put_access_chain(pointer, policy, &context.expression)?; - write!(self.out, ".{}[_i] = ", WRAPPED_ARRAY_FIELD)?; + write!(self.out, ".{WRAPPED_ARRAY_FIELD}[_i] = ")?; self.put_expression(value, &context.expression, true)?; - writeln!(self.out, ".{}[_i];", WRAPPED_ARRAY_FIELD)?; + writeln!(self.out, ".{WRAPPED_ARRAY_FIELD}[_i];")?; } else if is_atomic { write!( self.out, - "{}{}::atomic_store_explicit({}", - level, NAMESPACE, ATOMIC_REFERENCE + "{level}{NAMESPACE}::atomic_store_explicit({ATOMIC_REFERENCE}" )?; self.put_access_chain(pointer, policy, &context.expression)?; write!(self.out, ", ")?; self.put_expression(value, &context.expression, true)?; - writeln!(self.out, ", {}::memory_order_relaxed);", NAMESPACE)?; + writeln!(self.out, ", {NAMESPACE}::memory_order_relaxed);")?; } else { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.put_access_chain(pointer, policy, &context.expression)?; write!(self.out, " = ")?; self.put_expression(value, &context.expression, true)?; @@ -2854,7 +2831,7 @@ impl Writer { writeln!(self.out, "#include ")?; writeln!(self.out)?; // Work around Metal bug where `uint` is not available by default - writeln!(self.out, "using {}::uint;", NAMESPACE)?; + writeln!(self.out, "using {NAMESPACE}::uint;")?; writeln!(self.out)?; if options @@ -2956,7 +2933,7 @@ impl Writer { first_time: false, }; - writeln!(self.out, "struct {} {{", name)?; + writeln!(self.out, "struct {name} {{")?; writeln!( self.out, "{}{} {}[{}];", @@ -2968,14 +2945,14 @@ impl Writer { writeln!(self.out, "}};")?; } crate::ArraySize::Dynamic => { - writeln!(self.out, "typedef {} {}[1];", base_name, name)?; + writeln!(self.out, "typedef {base_name} {name}[1];")?; } } } crate::TypeInner::Struct { ref members, span, .. } => { - writeln!(self.out, "struct {} {{", name)?; + writeln!(self.out, "struct {name} {{")?; let mut last_offset = 0; for (index, member) in members.iter().enumerate() { // quick and dirty way to figure out if we need this... @@ -3041,7 +3018,7 @@ impl Writer { binding: None, first_time: true, }; - writeln!(self.out, "typedef {} {};", ty_name, name)?; + writeln!(self.out, "typedef {ty_name} {name};")?; } } } @@ -3078,7 +3055,7 @@ impl Writer { names: &self.names, first_time: true, }; - writeln!(self.out, " {} = {};", name, coco)?; + writeln!(self.out, " {name} = {coco};")?; } _ => {} } @@ -3101,7 +3078,7 @@ impl Writer { binding: None, first_time: false, }; - write!(self.out, "constant {} {} = {{", ty_name, name,)?; + write!(self.out, "constant {ty_name} {name} = {{",)?; for (i, &sub_handle) in components.iter().enumerate() { // insert padding initialization, if needed if self.struct_member_pads.contains(&(ty, i as u32)) { @@ -3114,7 +3091,7 @@ impl Writer { names: &self.names, first_time: false, }; - write!(self.out, "{}{}", separator, coco)?; + write!(self.out, "{separator}{coco}")?; } writeln!(self.out, "}};")?; } @@ -3241,13 +3218,13 @@ impl Writer { binding: None, first_time: false, }; - write!(self.out, "{}", ty_name)?; + write!(self.out, "{ty_name}")?; } None => { write!(self.out, "void")?; } } - writeln!(self.out, " {}(", fun_name)?; + writeln!(self.out, " {fun_name}(")?; for (index, arg) in fun.arguments.iter().enumerate() { let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; @@ -3286,7 +3263,7 @@ impl Writer { separate(index + 1 != pass_through_globals.len() || supports_array_length); write!(self.out, "{}", back::INDENT)?; tyvar.try_fmt(&mut self.out)?; - writeln!(self.out, "{}", separator)?; + writeln!(self.out, "{separator}")?; } if supports_array_length { @@ -3318,7 +3295,7 @@ impl Writer { names: &self.names, first_time: false, }; - write!(self.out, " = {}", coco)?; + write!(self.out, " = {coco}")?; } None => { write!(self.out, " = {{}}")?; @@ -3484,11 +3461,11 @@ impl Writer { // Identify the varyings among the argument values, and emit a // struct type named `Input` to hold them. - let stage_in_name = format!("{}Input", fun_name); + let stage_in_name = format!("{fun_name}Input"); let varyings_member_name = self.namer.call("varyings"); let mut has_varyings = false; if !flattened_arguments.is_empty() { - writeln!(self.out, "struct {} {{", stage_in_name)?; + writeln!(self.out, "struct {stage_in_name} {{")?; for &(ref name_key, ty, binding) in flattened_arguments.iter() { let binding = match binding { Some(ref binding @ &crate::Binding::Location { .. }) => binding, @@ -3514,7 +3491,7 @@ impl Writer { // Define a struct type named for the return value, if any, named // `Output`. - let stage_out_name = format!("{}Output", fun_name); + let stage_out_name = format!("{fun_name}Output"); let result_member_name = self.namer.call("member"); let result_type_name = match fun.result { Some(ref result) => { @@ -3537,7 +3514,7 @@ impl Writer { )); } - writeln!(self.out, "struct {} {{", stage_out_name)?; + writeln!(self.out, "struct {stage_out_name} {{")?; let mut has_point_size = false; for (name, ty, binding) in result_members { let ty_name = TypeContext { @@ -3580,7 +3557,7 @@ impl Writer { let resolved = options.resolve_local_binding(binding, out_mode)?; write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; if let Some(array_len) = array_len { - write!(self.out, " [{}]", array_len)?; + write!(self.out, " [{array_len}]")?; } resolved.try_fmt(&mut self.out)?; writeln!(self.out, ";")?; @@ -3604,7 +3581,7 @@ impl Writer { }; // Write the entry point function's name, and begin its argument list. - writeln!(self.out, "{} {} {}(", em_str, result_type_name, fun_name)?; + writeln!(self.out, "{em_str} {result_type_name} {fun_name}(")?; let mut is_first_argument = true; // If we have produced a struct holding the `EntryPoint`'s @@ -3612,8 +3589,7 @@ impl Writer { if has_varyings { writeln!( self.out, - " {} {} [[stage_in]]", - stage_in_name, varyings_member_name + " {stage_in_name} {varyings_member_name} [[stage_in]]" )?; is_first_argument = false; } @@ -3664,7 +3640,7 @@ impl Writer { } else { ',' }; - write!(self.out, "{} {} {}", separator, ty_name, name)?; + write!(self.out, "{separator} {ty_name} {name}")?; resolved.try_fmt(&mut self.out)?; writeln!(self.out)?; } @@ -3681,8 +3657,7 @@ impl Writer { }; writeln!( self.out, - "{} {}::uint3 __global_invocation_id [[thread_position_in_grid]]", - separator, NAMESPACE + "{separator} {NAMESPACE}::uint3 __global_invocation_id [[thread_position_in_grid]]" )?; } @@ -3729,7 +3704,7 @@ impl Writer { } else { ',' }; - write!(self.out, "{} ", separator)?; + write!(self.out, "{separator} ")?; tyvar.try_fmt(&mut self.out)?; if let Some(resolved) = resolved { resolved.try_fmt(&mut self.out)?; @@ -3741,7 +3716,7 @@ impl Writer { names: &self.names, first_time: false, }; - write!(self.out, " = {}", coco)?; + write!(self.out, " = {coco}")?; } writeln!(self.out)?; } @@ -3758,8 +3733,7 @@ impl Writer { }; write!( self.out, - "{} constant _mslBufferSizes& _buffer_sizes", - separator, + "{separator} constant _mslBufferSizes& _buffer_sizes", )?; resolved.try_fmt(&mut self.out)?; writeln!(self.out)?; @@ -3803,7 +3777,7 @@ impl Writer { names: &self.names, first_time: false, }; - writeln!(self.out, " = {};", coco)?; + writeln!(self.out, " = {coco};")?; } None => { writeln!(self.out, " = {{}};")?; @@ -3865,9 +3839,9 @@ impl Writer { write!(self.out, ", ")?; } if let Some(crate::Binding::Location { .. }) = member.binding { - write!(self.out, "{}.", varyings_member_name)?; + write!(self.out, "{varyings_member_name}.")?; } - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; } writeln!(self.out, " }};")?; } @@ -3907,7 +3881,7 @@ impl Writer { names: &self.names, first_time: false, }; - write!(self.out, " = {}", coco)?; + write!(self.out, " = {coco}")?; } None => { write!(self.out, " = {{}}")?; @@ -3950,22 +3924,19 @@ impl Writer { if flags.is_empty() { writeln!( self.out, - "{}{}::threadgroup_barrier({}::mem_flags::mem_none);", - level, NAMESPACE, NAMESPACE, + "{level}{NAMESPACE}::threadgroup_barrier({NAMESPACE}::mem_flags::mem_none);", )?; } if flags.contains(crate::Barrier::STORAGE) { writeln!( self.out, - "{}{}::threadgroup_barrier({}::mem_flags::mem_device);", - level, NAMESPACE, NAMESPACE, + "{level}{NAMESPACE}::threadgroup_barrier({NAMESPACE}::mem_flags::mem_device);", )?; } if flags.contains(crate::Barrier::WORK_GROUP) { writeln!( self.out, - "{}{}::threadgroup_barrier({}::mem_flags::mem_threadgroup);", - level, NAMESPACE, NAMESPACE, + "{level}{NAMESPACE}::threadgroup_barrier({NAMESPACE}::mem_flags::mem_threadgroup);", )?; } Ok(()) @@ -3998,7 +3969,7 @@ mod workgroup_mem_init { Access::StructMember(handle, index) => { write!(writer, ".{}", &names[&NameKey::StructMember(handle, index)]) } - Access::Array(depth) => write!(writer, ".{}[__i{}]", WRAPPED_ARRAY_FIELD, depth), + Access::Array(depth) => write!(writer, ".{WRAPPED_ARRAY_FIELD}[__i{depth}]"), } } } @@ -4098,7 +4069,7 @@ mod workgroup_mem_init { })?; } - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; self.write_barrier(crate::Barrier::WORK_GROUP, level) } @@ -4111,7 +4082,7 @@ mod workgroup_mem_init { level: back::Level, ) -> BackendResult { if module_info[ty].contains(valid::TypeFlags::CONSTRUCTIBLE) { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; access_stack.write(&mut self.out, &self.names)?; writeln!(self.out, " = {{}};")?; } else { @@ -4119,11 +4090,10 @@ mod workgroup_mem_init { crate::TypeInner::Atomic { .. } => { write!( self.out, - "{}{}::atomic_store_explicit({}", - level, NAMESPACE, ATOMIC_REFERENCE + "{level}{NAMESPACE}::atomic_store_explicit({ATOMIC_REFERENCE}" )?; access_stack.write(&mut self.out, &self.names)?; - writeln!(self.out, ", 0, {}::memory_order_relaxed);", NAMESPACE)?; + writeln!(self.out, ", 0, {NAMESPACE}::memory_order_relaxed);")?; } crate::TypeInner::Array { base, size, .. } => { let count = match size.to_indexable_length(module).expect("Bad array size") @@ -4135,8 +4105,7 @@ mod workgroup_mem_init { access_stack.enter_array(|access_stack, array_depth| { writeln!( self.out, - "{}for (int __i{} = 0; __i{} < {}; __i{}++) {{", - level, array_depth, array_depth, count, array_depth + "{level}for (int __i{array_depth} = 0; __i{array_depth} < {count}; __i{array_depth}++) {{" )?; self.write_workgroup_variable_initialization( module, @@ -4145,7 +4114,7 @@ mod workgroup_mem_init { access_stack, level.next(), )?; - writeln!(self.out, "{}}}", level)?; + writeln!(self.out, "{level}}}")?; BackendResult::Ok(()) })?; } @@ -4236,7 +4205,7 @@ fn test_stack_size() { // check the size (in debug only) // last observed macOS value: 20528 (CI) if !(11000..=25000).contains(&stack_size) { - panic!("`put_expression` stack size {} has changed!", stack_size); + panic!("`put_expression` stack size {stack_size} has changed!"); } } @@ -4252,7 +4221,7 @@ fn test_stack_size() { // check the size (in debug only) // last observed macOS value: 19152 (CI) if !(9500..=20000).contains(&stack_size) { - panic!("`put_block` stack size {} has changed!", stack_size); + panic!("`put_block` stack size {stack_size} has changed!"); } } } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index da3f75d7e..5524ca9c2 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -187,12 +187,12 @@ impl Writer { use crate::ScalarValue as Sv; match value { - Sv::Sint(value) => write!(self.out, "{}", value)?, - Sv::Uint(value) => write!(self.out, "{}u", value)?, + Sv::Sint(value) => write!(self.out, "{value}")?, + Sv::Uint(value) => write!(self.out, "{value}u")?, // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero - Sv::Float(value) => write!(self.out, "{:?}", value)?, - Sv::Bool(value) => write!(self.out, "{}", value)?, + Sv::Float(value) => write!(self.out, "{value:?}")?, + Sv::Bool(value) => write!(self.out, "{value}")?, } Ok(()) @@ -211,7 +211,7 @@ impl Writer { ShaderStage::Vertex => "VertexOutput", }; - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; return Ok(()); } } @@ -238,7 +238,7 @@ impl Writer { }; // Write function name - write!(self.out, "fn {}(", func_name)?; + write!(self.out, "fn {func_name}(")?; // Write function arguments for (index, arg) in func.arguments.iter().enumerate() { @@ -259,7 +259,7 @@ impl Writer { } }; - write!(self.out, "{}: ", argument_name)?; + write!(self.out, "{argument_name}: ")?; // Write argument type self.write_type(module, arg.ty)?; if index < func.arguments.len() - 1 { @@ -333,10 +333,10 @@ impl Writer { fn write_attributes(&mut self, attributes: &[Attribute]) -> BackendResult { for attribute in attributes { match *attribute { - Attribute::Location(id) => write!(self.out, "@location({}) ", id)?, + Attribute::Location(id) => write!(self.out, "@location({id}) ")?, Attribute::BuiltIn(builtin_attrib) => { if let Some(builtin) = builtin_str(builtin_attrib) { - write!(self.out, "@builtin({}) ", builtin)?; + write!(self.out, "@builtin({builtin}) ")?; } else { log::warn!("Unsupported builtin attribute: {:?}", builtin_attrib); } @@ -347,7 +347,7 @@ impl Writer { ShaderStage::Fragment => "fragment", ShaderStage::Compute => "compute", }; - write!(self.out, "@{} ", stage_str)?; + write!(self.out, "@{stage_str} ")?; } Attribute::WorkGroupSize(size) => { write!( @@ -356,8 +356,8 @@ impl Writer { size[0], size[1], size[2] )?; } - Attribute::Binding(id) => write!(self.out, "@binding({}) ", id)?, - Attribute::Group(id) => write!(self.out, "@group({}) ", id)?, + Attribute::Binding(id) => write!(self.out, "@binding({id}) ")?, + Attribute::Group(id) => write!(self.out, "@group({id}) ")?, Attribute::Invariant => write!(self.out, "@invariant ")?, Attribute::Interpolate(interpolation, sampling) => { if sampling.is_some() && sampling != Some(crate::Sampling::Center) { @@ -419,7 +419,7 @@ impl Writer { } // Write struct member name and type let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; - write!(self.out, "{}: ", member_name)?; + write!(self.out, "{member_name}: ")?; self.write_type(module, member.ty)?; write!(self.out, ",")?; writeln!(self.out)?; @@ -500,12 +500,11 @@ impl Writer { }; write!( self.out, - "texture_{}{}{}{}", - class_str, multisampled_str, dim_str, arrayed_str + "texture_{class_str}{multisampled_str}{dim_str}{arrayed_str}" )?; if !format_str.is_empty() { - write!(self.out, "<{}{}>", format_str, storage_str)?; + write!(self.out, "<{format_str}{storage_str}>")?; } } TypeInner::Scalar { kind, width } => { @@ -569,12 +568,12 @@ impl Writer { // Naga IR never produces pointers to handles, so it doesn't matter much // how we write such a type. Just write it as the base type alone. if let Some(space) = address { - write!(self.out, "ptr<{}, ", space)?; + write!(self.out, "ptr<{space}, ")?; } self.write_type(module, base)?; if address.is_some() { if let Some(access) = maybe_access { - write!(self.out, ", {}", access)?; + write!(self.out, ", {access}")?; } write!(self.out, ">")?; } @@ -589,13 +588,12 @@ impl Writer { if let Some(space) = address { write!(self.out, "ptr<{}, {}", space, scalar_kind_str(kind, width))?; if let Some(access) = maybe_access { - write!(self.out, ", {}", access)?; + write!(self.out, ", {access}")?; } write!(self.out, ">")?; } else { return Err(Error::Unimplemented(format!( - "ValuePointer to AddressSpace::Handle {:?}", - inner + "ValuePointer to AddressSpace::Handle {inner:?}" ))); } } @@ -615,22 +613,18 @@ impl Writer { scalar_kind_str(kind, width) )?; if let Some(access) = maybe_access { - write!(self.out, ", {}", access)?; + write!(self.out, ", {access}")?; } write!(self.out, ">")?; } else { return Err(Error::Unimplemented(format!( - "ValuePointer to AddressSpace::Handle {:?}", - inner + "ValuePointer to AddressSpace::Handle {inner:?}" ))); } write!(self.out, ">")?; } _ => { - return Err(Error::Unimplemented(format!( - "write_value_type {:?}", - inner - ))); + return Err(Error::Unimplemented(format!("write_value_type {inner:?}"))); } } @@ -660,7 +654,7 @@ impl Writer { // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. Some(self.namer.call(name)) } else if info.ref_count == 0 { - write!(self.out, "{}_ = ", level)?; + write!(self.out, "{level}_ = ")?; self.write_expr(module, handle, func_ctx)?; writeln!(self.out, ";")?; continue; @@ -698,7 +692,7 @@ impl Writer { }; if let Some(name) = expr_name { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; self.start_named_expr(module, handle, func_ctx, &name)?; self.write_expr(module, handle, func_ctx)?; self.named_expressions.insert(handle, name); @@ -712,7 +706,7 @@ impl Writer { ref accept, ref reject, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; write!(self.out, "if ")?; self.write_expr(module, condition, func_ctx)?; writeln!(self.out, " {{")?; @@ -726,7 +720,7 @@ impl Writer { // If there are no statements in the reject block we skip writing it // This is only for readability if !reject.is_empty() { - writeln!(self.out, "{}}} else {{", level)?; + writeln!(self.out, "{level}}} else {{")?; for sta in reject { // Increase indentation to help with readability @@ -734,10 +728,10 @@ impl Writer { } } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } Statement::Return { value } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; write!(self.out, "return")?; if let Some(return_value) = value { // The leading space is important @@ -748,7 +742,7 @@ impl Writer { } // TODO: copy-paste from glsl-out Statement::Kill => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; writeln!(self.out, "discard;")? } Statement::Store { pointer, value } => { @@ -760,7 +754,7 @@ impl Writer { return Ok(()); } } - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { @@ -792,14 +786,14 @@ impl Writer { ref arguments, result, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; if let Some(expr) = result { let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); self.start_named_expr(module, expr, func_ctx, &name)?; self.named_expressions.insert(expr, name); } let func_name = &self.names[&NameKey::Function(function)]; - write!(self.out, "{}(", func_name)?; + write!(self.out, "{func_name}(")?; for (index, &argument) in arguments.iter().enumerate() { self.write_expr(module, argument, func_ctx)?; // Only write a comma if isn't the last element @@ -816,13 +810,13 @@ impl Writer { value, result, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); self.start_named_expr(module, result, func_ctx, &res_name)?; self.named_expressions.insert(result, res_name); let fun_str = fun.to_wgsl(); - write!(self.out, "atomic{}(", fun_str)?; + write!(self.out, "atomic{fun_str}(")?; self.write_expr(module, pointer, func_ctx)?; if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun { write!(self.out, ", ")?; @@ -838,7 +832,7 @@ impl Writer { array_index, value, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; write!(self.out, "textureStore(")?; self.write_expr(module, image, func_ctx)?; write!(self.out, ", ")?; @@ -853,20 +847,20 @@ impl Writer { } // TODO: copy-paste from glsl-out Statement::Block(ref block) => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; writeln!(self.out, "{{")?; for sta in block.iter() { // Increase the indentation to help with readability self.write_stmt(module, sta, func_ctx, level.next())? } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } Statement::Switch { selector, ref cases, } => { // Start the switch - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; write!(self.out, "switch ")?; self.write_expr(module, selector, func_ctx)?; writeln!(self.out, " {{")?; @@ -892,16 +886,16 @@ impl Writer { match case.value { crate::SwitchValue::Integer(value) => { if new_case { - write!(self.out, "{}case ", l2)?; + write!(self.out, "{l2}case ")?; } - write!(self.out, "{}{}", value, type_postfix)?; + write!(self.out, "{value}{type_postfix}")?; } crate::SwitchValue::Default => { if new_case { if case.fall_through { - write!(self.out, "{}case ", l2)?; + write!(self.out, "{l2}case ")?; } else { - write!(self.out, "{}", l2)?; + write!(self.out, "{l2}")?; } } write!(self.out, "default")?; @@ -921,18 +915,18 @@ impl Writer { } if !case.fall_through { - writeln!(self.out, "{}}}", l2)?; + writeln!(self.out, "{l2}}}")?; } } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } Statement::Loop { ref body, ref continuing, break_if, } => { - write!(self.out, "{}", level)?; + write!(self.out, "{level}")?; writeln!(self.out, "loop {{")?; let l2 = level.next(); @@ -945,7 +939,7 @@ impl Writer { // so even if `continuing` is empty we must generate it if a // `break if` exists if !continuing.is_empty() || break_if.is_some() { - writeln!(self.out, "{}continuing {{", l2)?; + writeln!(self.out, "{l2}continuing {{")?; for sta in continuing.iter() { self.write_stmt(module, sta, func_ctx, l2.next())?; } @@ -960,24 +954,24 @@ impl Writer { writeln!(self.out, ";")?; } - writeln!(self.out, "{}}}", l2)?; + writeln!(self.out, "{l2}}}")?; } - writeln!(self.out, "{}}}", level)? + writeln!(self.out, "{level}}}")? } Statement::Break => { - writeln!(self.out, "{}break;", level)?; + writeln!(self.out, "{level}break;")?; } Statement::Continue => { - writeln!(self.out, "{}continue;", level)?; + writeln!(self.out, "{level}continue;")?; } Statement::Barrier(barrier) => { if barrier.contains(crate::Barrier::STORAGE) { - writeln!(self.out, "{}storageBarrier();", level)?; + writeln!(self.out, "{level}storageBarrier();")?; } if barrier.contains(crate::Barrier::WORK_GROUP) { - writeln!(self.out, "{}workgroupBarrier();", level)?; + writeln!(self.out, "{level}workgroupBarrier();")?; } } } @@ -1052,7 +1046,7 @@ impl Writer { name: &str, ) -> BackendResult { // Write variable name - write!(self.out, "let {}", name)?; + write!(self.out, "let {name}")?; if self.flags.contains(WriterFlags::EXPLICIT_TYPES) { write!(self.out, ": ")?; let ty = &func_ctx.info[handle].ty; @@ -1139,7 +1133,7 @@ impl Writer { use crate::Expression; if let Some(name) = self.named_expressions.get(&expr) { - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; return Ok(()); } @@ -1203,7 +1197,7 @@ impl Writer { Expression::FunctionArgument(pos) => { let name_key = func_ctx.argument_key(pos); let name = &self.names[&name_key]; - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; } Expression::Binary { op, left, right } => { write!(self.out, "(")?; @@ -1240,7 +1234,7 @@ impl Writer { TypeInner::Matrix { .. } | TypeInner::Array { .. } | TypeInner::BindingArray { .. } - | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?, + | TypeInner::ValuePointer { .. } => write!(self.out, "[{index}]")?, TypeInner::Struct { .. } => { // This will never panic in case the type is a `Struct`, this is not true // for other types so we can only check while inside this match arm @@ -1252,7 +1246,7 @@ impl Writer { &self.names[&NameKey::StructMember(ty, index)] )? } - ref other => return Err(Error::Custom(format!("Cannot index {:?}", other))), + ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))), } } Expression::ImageSample { @@ -1278,7 +1272,7 @@ impl Writer { Sl::Gradient { .. } => "Grad", }; - write!(self.out, "textureSample{}{}(", suffix_cmp, suffix_level)?; + write!(self.out, "textureSample{suffix_cmp}{suffix_level}(")?; self.write_expr(module, image, func_ctx)?; write!(self.out, ", ")?; self.write_expr(module, sampler, func_ctx)?; @@ -1341,7 +1335,7 @@ impl Writer { None => "", }; - write!(self.out, "textureGather{}(", suffix_cmp)?; + write!(self.out, "textureGather{suffix_cmp}(")?; match *func_ctx.info[image].ty.inner_with(&module.types) { TypeInner::Image { class: crate::ImageClass::Depth { multi: _ }, @@ -1384,7 +1378,7 @@ impl Writer { Iq::NumSamples => "textureNumSamples", }; - write!(self.out, "{}(", texture_function)?; + write!(self.out, "{texture_function}(")?; self.write_expr(module, image, func_ctx)?; if let Iq::Size { level: Some(level) } = query { write!(self.out, ", ")?; @@ -1415,7 +1409,7 @@ impl Writer { } Expression::GlobalVariable(handle) => { let name = &self.names[&NameKey::GlobalVariable(handle)]; - write!(self.out, "{}", name)?; + write!(self.out, "{name}")?; } Expression::As { expr, @@ -1443,27 +1437,22 @@ impl Writer { let vector_size_str = back::vector_size_str(size); let scalar_kind_str = scalar_kind_str(kind, convert.unwrap_or(width)); if convert.is_some() { - write!(self.out, "vec{}<{}>", vector_size_str, scalar_kind_str)?; + write!(self.out, "vec{vector_size_str}<{scalar_kind_str}>")?; } else { - write!( - self.out, - "bitcast>", - vector_size_str, scalar_kind_str - )?; + write!(self.out, "bitcast>")?; } } TypeInner::Scalar { width, .. } => { let scalar_kind_str = scalar_kind_str(kind, convert.unwrap_or(width)); if convert.is_some() { - write!(self.out, "{}", scalar_kind_str)? + write!(self.out, "{scalar_kind_str}")? } else { - write!(self.out, "bitcast<{}>", scalar_kind_str)? + write!(self.out, "bitcast<{scalar_kind_str}>")? } } _ => { return Err(Error::Unimplemented(format!( - "write_expr expression::as {:?}", - inner + "write_expr expression::as {inner:?}" ))); } }; @@ -1477,15 +1466,14 @@ impl Writer { crate::TypeInner::Scalar { kind, width } => (kind, width), _ => { return Err(Error::Unimplemented(format!( - "write_expr expression::splat {:?}", - inner + "write_expr expression::splat {inner:?}" ))); } }; let scalar = scalar_kind_str(scalar_kind, scalar_width); let size = back::vector_size_str(size); - write!(self.out, "vec{}<{}>(", size, scalar)?; + write!(self.out, "vec{size}<{scalar}>(")?; self.write_expr(module, value, func_ctx)?; write!(self.out, ")")?; } @@ -1615,7 +1603,7 @@ impl Writer { match function { Function::Regular(fun_name) => { - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; self.write_expr(module, arg, func_ctx)?; for arg in IntoIterator::into_iter([arg1, arg2, arg3]).flatten() { write!(self.out, ", ")?; @@ -1651,7 +1639,7 @@ impl Writer { } }; - write!(self.out, "{}(", unary)?; + write!(self.out, "{unary}(")?; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")? @@ -1677,7 +1665,7 @@ impl Writer { Da::Y => "dpdy", Da::Width => "fwidth", }; - write!(self.out, "{}(", op)?; + write!(self.out, "{op}(")?; self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")? } @@ -1689,7 +1677,7 @@ impl Writer { Rf::Any => "any", _ => return Err(Error::UnsupportedRelationalFunction(fun)), }; - write!(self.out, "{}(", fun_name)?; + write!(self.out, "{fun_name}(")?; self.write_expr(module, argument, func_ctx)?; @@ -1724,9 +1712,9 @@ impl Writer { write!(self.out, "var")?; let (address, maybe_access) = address_space_str(global.space); if let Some(space) = address { - write!(self.out, "<{}", space)?; + write!(self.out, "<{space}")?; if let Some(access) = maybe_access { - write!(self.out, ", {}", access)?; + write!(self.out, ", {access}")?; } write!(self.out, ">")?; } @@ -1826,22 +1814,22 @@ impl Writer { } => { let name = &self.names[&NameKey::Constant(handle)]; // First write only constant name - write!(self.out, "const {}: ", name)?; + write!(self.out, "const {name}: ")?; // Next write constant type and value match *value { crate::ScalarValue::Sint(value) => { - write!(self.out, "i32 = {}", value)?; + write!(self.out, "i32 = {value}")?; } crate::ScalarValue::Uint(value) => { - write!(self.out, "u32 = {}u", value)?; + write!(self.out, "u32 = {value}u")?; } crate::ScalarValue::Float(value) => { // Floats are written using `Debug` instead of `Display` because it always appends the // decimal part even it's zero - write!(self.out, "f32 = {:?}", value)?; + write!(self.out, "f32 = {value:?}")?; } crate::ScalarValue::Bool(value) => { - write!(self.out, "bool = {}", value)?; + write!(self.out, "bool = {value}")?; } }; // End with semicolon @@ -1850,7 +1838,7 @@ impl Writer { crate::ConstantInner::Composite { ty, ref components } => { let name = &self.names[&NameKey::Constant(handle)]; // First write only constant name - write!(self.out, "const {}: ", name)?; + write!(self.out, "const {name}: ")?; // Next write constant type self.write_type(module, ty)?; diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 53b3b77a3..cdf7a8f63 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -241,8 +241,7 @@ impl<'a> ConstantSolver<'a> { ), _ => { return Err(ConstantSolvingError::NotImplemented(format!( - "{:?} applied to vector values", - fun + "{fun:?} applied to vector values" ))) } }; @@ -250,7 +249,7 @@ impl<'a> ConstantSolver<'a> { let inner = ConstantInner::Scalar { width, value }; Ok(self.register_constant(inner, span)) } - _ => Err(ConstantSolvingError::NotImplemented(format!("{:?}", fun))), + _ => Err(ConstantSolvingError::NotImplemented(format!("{fun:?}"))), } } Expression::As { diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 44aea8a30..930cd4559 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -591,8 +591,7 @@ impl Context { parser.errors.push(Error { kind: ErrorKind::SemanticError( format!( - "Cannot apply operation to {:?} and {:?}", - left_inner, right_inner + "Cannot apply operation to {left_inner:?} and {right_inner:?}" ) .into(), ), @@ -823,8 +822,7 @@ impl Context { parser.errors.push(Error { kind: ErrorKind::SemanticError( format!( - "Cannot apply operation to {:?} and {:?}", - left_inner, right_inner + "Cannot apply operation to {left_inner:?} and {right_inner:?}" ) .into(), ), @@ -914,8 +912,7 @@ impl Context { parser.errors.push(Error { kind: ErrorKind::SemanticError( format!( - "Cannot apply operation to {:?} and {:?}", - left_inner, right_inner + "Cannot apply operation to {left_inner:?} and {right_inner:?}" ) .into(), ), @@ -1383,7 +1380,7 @@ impl Context { _ => { return Err(Error { kind: ErrorKind::SemanticError( - format!("unknown method '{}'", name).into(), + format!("unknown method '{name}'").into(), ), meta, }); diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 299bf57aa..46b3aecd0 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -43,7 +43,7 @@ impl From for ExpectedToken { impl std::fmt::Display for ExpectedToken { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { - ExpectedToken::Token(ref token) => write!(f, "{:?}", token), + ExpectedToken::Token(ref token) => write!(f, "{token:?}"), ExpectedToken::TypeName => write!(f, "a type"), ExpectedToken::Identifier => write!(f, "identifier"), ExpectedToken::IntLiteral => write!(f, "integer literal"), diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 2c0445bdf..806008e5b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -721,8 +721,7 @@ impl Parser { self.errors.push(Error { kind: ErrorKind::SemanticError( format!( - "'{}': image needs {:?} access but only {:?} was provided", - name, overload_access, call_access + "'{name}': image needs {overload_access:?} access but only {call_access:?} was provided" ) .into(), ), @@ -829,14 +828,14 @@ impl Parser { if ambiguous { self.errors.push(Error { kind: ErrorKind::SemanticError( - format!("Ambiguous best function for '{}'", name).into(), + format!("Ambiguous best function for '{name}'").into(), ), meta, }) } let overload = maybe_overload.ok_or_else(|| Error { - kind: ErrorKind::SemanticError(format!("Unknown function '{}'", name).into()), + kind: ErrorKind::SemanticError(format!("Unknown function '{name}'").into()), meta, })?; diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 427b0b27b..29d6e692b 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -256,7 +256,7 @@ impl Parser { ctx.typifier .grow(expr, &ctx.expressions, &resolve_ctx) .map_err(|error| Error { - kind: ErrorKind::SemanticError(format!("Can't resolve type: {:?}", error).into()), + kind: ErrorKind::SemanticError(format!("Can't resolve type: {error:?}").into()), meta, }) } @@ -322,7 +322,7 @@ impl Parser { ctx.typifier .invalidate(expr, &ctx.expressions, &resolve_ctx) .map_err(|error| Error { - kind: ErrorKind::SemanticError(format!("Can't resolve type: {:?}", error).into()), + kind: ErrorKind::SemanticError(format!("Can't resolve type: {error:?}").into()), meta, }) } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index ea8c9e8b5..e3fba754d 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -317,8 +317,7 @@ impl Parser { kind: ErrorKind::SemanticError( format!( - "swizzle cannot have duplicate components in left-hand-side expression for \"{:?}\"", - name + "swizzle cannot have duplicate components in left-hand-side expression for \"{name:?}\"" ) .into(), ), @@ -379,7 +378,7 @@ impl Parser { _ => { self.errors.push(Error { kind: ErrorKind::SemanticError( - format!("Bad swizzle size for \"{:?}\"", name).into(), + format!("Bad swizzle size for \"{name:?}\"").into(), ), meta, }); @@ -413,7 +412,7 @@ impl Parser { } else { Err(Error { kind: ErrorKind::SemanticError( - format!("Invalid swizzle for vector \"{}\"", name).into(), + format!("Invalid swizzle for vector \"{name}\"").into(), ), meta, }) @@ -421,7 +420,7 @@ impl Parser { } _ => Err(Error { kind: ErrorKind::SemanticError( - format!("Can't lookup field on this type \"{}\"", name).into(), + format!("Can't lookup field on this type \"{name}\"").into(), ), meta, }), diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 956f93cf9..39987e62d 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -170,7 +170,7 @@ impl> super::Parser { None => format!("block_ctx.Fun-{}.txt", module.functions.len()), }; let dest = prefix.join(dump_suffix); - let dump = format!("{:#?}", block_ctx); + let dump = format!("{block_ctx:#?}"); if let Err(e) = std::fs::write(&dest, dump) { log::error!("Unable to dump the block context into {:?}: {}", dest, e); } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index b51f10f23..93a76178b 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1378,7 +1378,7 @@ impl> Parser { let result_type_id = self.next()?; let result_id = self.next()?; - let name = format!("phi_{}", result_id); + let name = format!("phi_{result_id}"); let local = ctx.local_arena.append( crate::LocalVariable { name: Some(name), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index c4821ba62..7e2826845 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -218,20 +218,20 @@ impl<'a> Error<'a> { let expected_str = match expected { ExpectedToken::Token(token) => { match token { - Token::Separator(c) => format!("'{}'", c), - Token::Paren(c) => format!("'{}'", c), + Token::Separator(c) => format!("'{c}'"), + Token::Paren(c) => format!("'{c}'"), Token::Attribute => "@".to_string(), Token::Number(_) => "number".to_string(), Token::Word(s) => s.to_string(), - Token::Operation(c) => format!("operation ('{}')", c), - Token::LogicalOperation(c) => format!("logical operation ('{}')", c), - Token::ShiftOperation(c) => format!("bitshift ('{}{}')", c, c), - Token::AssignmentOperation(c) if c=='<' || c=='>' => format!("bitshift ('{}{}=')", c, c), - Token::AssignmentOperation(c) => format!("operation ('{}=')", c), + Token::Operation(c) => format!("operation ('{c}')"), + Token::LogicalOperation(c) => format!("logical operation ('{c}')"), + Token::ShiftOperation(c) => format!("bitshift ('{c}{c}')"), + Token::AssignmentOperation(c) if c=='<' || c=='>' => format!("bitshift ('{c}{c}=')"), + Token::AssignmentOperation(c) => format!("operation ('{c}=')"), Token::IncrementOperation => "increment operation".to_string(), Token::DecrementOperation => "decrement operation".to_string(), Token::Arrow => "->".to_string(), - Token::Unknown(c) => format!("unknown ('{}')", c), + Token::Unknown(c) => format!("unknown ('{c}')"), Token::Trivia => "trivia".to_string(), Token::End => "end".to_string(), } @@ -261,7 +261,7 @@ impl<'a> Error<'a> { "expected {}, found '{}'", expected_str, &source[unexpected_span], ), - labels: vec![(unexpected_span, format!("expected {}", expected_str).into())], + labels: vec![(unexpected_span, format!("expected {expected_str}").into())], notes: vec![], } } @@ -305,7 +305,7 @@ impl<'a> Error<'a> { notes: vec![], }, Error::UnknownIdent(ident_span, ident) => ParseError { - message: format!("no definition in scope for identifier: '{}'", ident), + message: format!("no definition in scope for identifier: '{ident}'"), labels: vec![(ident_span, "unknown identifier".into())], notes: vec![], }, @@ -342,7 +342,7 @@ impl<'a> Error<'a> { ref from_type, ref to_type, } => { - let msg = format!("cannot cast a {} to a {}", from_type, to_type); + let msg = format!("cannot cast a {from_type} to a {to_type}"); ParseError { message: msg.clone(), labels: vec![(span, msg.into())], @@ -376,10 +376,7 @@ impl<'a> Error<'a> { notes: vec![], }, Error::InvalidConstructorComponentType(bad_span, component) => ParseError { - message: format!( - "invalid type for constructor component at index [{}]", - component - ), + message: format!("invalid type for constructor component at index [{component}]"), labels: vec![(bad_span, "invalid component type".into())], notes: vec![], }, @@ -435,13 +432,13 @@ impl<'a> Error<'a> { notes: vec![], }, Error::SizeAttributeTooLow(bad_span, min_size) => ParseError { - message: format!("struct member size must be at least {}", min_size), - labels: vec![(bad_span, format!("must be at least {}", min_size).into())], + message: format!("struct member size must be at least {min_size}"), + labels: vec![(bad_span, format!("must be at least {min_size}").into())], notes: vec![], }, Error::AlignAttributeTooLow(bad_span, min_align) => ParseError { - message: format!("struct member alignment must be at least {}", min_align), - labels: vec![(bad_span, format!("must be at least {}", min_align).into())], + message: format!("struct member alignment must be at least {min_align}"), + labels: vec![(bad_span, format!("must be at least {min_align}").into())], notes: vec![], }, Error::NonPowerOfTwoAlignAttribute(bad_span) => ParseError { @@ -512,7 +509,7 @@ impl<'a> Error<'a> { notes: vec![], }, Error::NotReference(what, span) => ParseError { - message: format!("{} must be a reference", what), + message: format!("{what} must be a reference"), labels: vec![(span, "expression is not a reference".into())], notes: vec![], }, @@ -532,7 +529,7 @@ impl<'a> Error<'a> { }, }, Error::Pointer(what, span) => ParseError { - message: format!("{} must not be a pointer", what), + message: format!("{what} must not be a pointer"), labels: vec![(span, "expression is a pointer".into())], notes: vec![], }, @@ -733,7 +730,7 @@ impl crate::TypeInner { Ti::Pointer { base, .. } => { let base = &types[base]; let name = base.name.as_deref().unwrap_or("unknown"); - format!("ptr<{}>", name) + format!("ptr<{name}>") } Ti::ValuePointer { kind, width, .. } => { format!("ptr<{}>", kind.to_wgsl(width)) @@ -758,9 +755,9 @@ impl crate::TypeInner { } => size.to_string(), _ => "?".to_string(), }); - format!("array<{}, {}>", base, size) + format!("array<{base}, {size}>") } - crate::ArraySize::Dynamic => format!("array<{}>", base), + crate::ArraySize::Dynamic => format!("array<{base}>"), } } Ti::Struct { .. } => { @@ -794,7 +791,7 @@ impl crate::TypeInner { // The lexer has already verified this, so we can safely assume it here. // https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type let element_type = kind.to_wgsl(4); - format!("<{}>", element_type) + format!("<{element_type}>") } crate::ImageClass::Depth { multi: _ } => String::new(), crate::ImageClass::Storage { format, access } => { @@ -806,10 +803,7 @@ impl crate::TypeInner { } }; - format!( - "texture{}{}{}{}", - class_suffix, dim_suffix, array_suffix, type_in_brackets - ) + format!("texture{class_suffix}{dim_suffix}{array_suffix}{type_in_brackets}") } Ti::Sampler { .. } => "sampler".to_string(), Ti::BindingArray { base, size, .. } => { @@ -818,9 +812,9 @@ impl crate::TypeInner { match size { crate::ArraySize::Constant(size) => { let size = constants[size].name.as_deref().unwrap_or("unknown"); - format!("binding_array<{}, {}>", base, size) + format!("binding_array<{base}, {size}>") } - crate::ArraySize::Dynamic => format!("binding_array<{}>", base), + crate::ArraySize::Dynamic => format!("binding_array<{base}>"), } } } @@ -1681,7 +1675,7 @@ impl ParseError { .with_notes( self.notes .iter() - .map(|note| format!("note: {}", note)) + .map(|note| format!("note: {note}")) .collect(), ); diagnostic diff --git a/src/front/wgsl/number.rs b/src/front/wgsl/number.rs index 6c3d93c39..cd7b88c7e 100644 --- a/src/front/wgsl/number.rs +++ b/src/front/wgsl/number.rs @@ -317,7 +317,7 @@ fn parse_hex_float_missing_period( exponent: &str, kind: Option, ) -> Result { - let hexf_input = format!("{}.{}", significand, exponent); + let hexf_input = format!("{significand}.{exponent}"); parse_hex_float(&hexf_input, kind) } @@ -328,7 +328,7 @@ fn parse_hex_int( kind: Option, ) -> Result { let digits_with_sign = if is_negative { - Cow::Owned(format!("-{}", digits)) + Cow::Owned(format!("-{digits}")) } else { Cow::Borrowed(digits) }; diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 3f4af4788..053126b8a 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -64,7 +64,7 @@ impl Namer { for prefix in &self.reserved_prefixes { if base.starts_with(prefix) { - return format!("gen_{}", base).into(); + return format!("gen_{base}").into(); } } @@ -210,11 +210,11 @@ impl Namer { crate::ConstantInner::Scalar { width: _, value: crate::ScalarValue::Sint(v), - } => write!(temp, "const_{}i", v), + } => write!(temp, "const_{v}i"), crate::ConstantInner::Scalar { width: _, value: crate::ScalarValue::Uint(v), - } => write!(temp, "const_{}u", v), + } => write!(temp, "const_{v}u"), crate::ConstantInner::Scalar { width: _, value: crate::ScalarValue::Float(v), @@ -237,7 +237,7 @@ impl Namer { crate::ConstantInner::Scalar { width: _, value: crate::ScalarValue::Bool(v), - } => write!(temp, "const_{}", v), + } => write!(temp, "const_{v}"), crate::ConstantInner::Composite { ty, components: _ } => { write!(temp, "const_{}", output[&NameKey::Type(ty)]) } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 47ad05e06..4c55d101a 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -601,8 +601,7 @@ impl<'a> ResolveContext<'a> { (&Ti::Vector { .. }, &Ti::Vector { .. }) => res_left.clone(), (tl, tr) => { return Err(ResolveError::IncompatibleOperands(format!( - "{:?} * {:?}", - tl, tr + "{tl:?} * {tr:?}" ))) } } @@ -622,8 +621,7 @@ impl<'a> ResolveContext<'a> { Ti::Vector { size, .. } => Ti::Vector { size, kind, width }, ref other => { return Err(ResolveError::IncompatibleOperands(format!( - "{:?}({:?}, _)", - op, other + "{op:?}({other:?}, _)" ))) } }; @@ -660,8 +658,7 @@ impl<'a> ResolveContext<'a> { }), ref other => { return Err(ResolveError::IncompatibleOperands(format!( - "{:?}({:?})", - fun, other + "{fun:?}({other:?})" ))) } }, @@ -722,18 +719,18 @@ impl<'a> ResolveContext<'a> { } => TypeResolution::Value(Ti::Scalar { kind, width }), ref other => return Err(ResolveError::IncompatibleOperands( - format!("{:?}({:?}, _)", fun, other) + format!("{fun:?}({other:?}, _)") )), }, Mf::Outer => { let arg1 = arg1.ok_or_else(|| ResolveError::IncompatibleOperands( - format!("{:?}(_, None)", fun) + format!("{fun:?}(_, None)") ))?; match (res_arg.inner_with(types), past(arg1)?.inner_with(types)) { (&Ti::Vector {kind: _, size: columns,width}, &Ti::Vector{ size: rows, .. }) => TypeResolution::Value(Ti::Matrix { columns, rows, width }), (left, right) => return Err(ResolveError::IncompatibleOperands( - format!("{:?}({:?}, {:?})", fun, left, right) + format!("{fun:?}({left:?}, {right:?})") )), } }, @@ -743,7 +740,7 @@ impl<'a> ResolveContext<'a> { Ti::Scalar {width,kind} | Ti::Vector {width,kind,size:_} => TypeResolution::Value(Ti::Scalar { kind, width }), ref other => return Err(ResolveError::IncompatibleOperands( - format!("{:?}({:?})", fun, other) + format!("{fun:?}({other:?})") )), }, Mf::Normalize | @@ -769,7 +766,7 @@ impl<'a> ResolveContext<'a> { width, }), ref other => return Err(ResolveError::IncompatibleOperands( - format!("{:?}({:?})", fun, other) + format!("{fun:?}({other:?})") )), }, Mf::Inverse => match *res_arg.inner_with(types) { @@ -783,7 +780,7 @@ impl<'a> ResolveContext<'a> { width, }), ref other => return Err(ResolveError::IncompatibleOperands( - format!("{:?}({:?})", fun, other) + format!("{fun:?}({other:?})") )), }, Mf::Determinant => match *res_arg.inner_with(types) { @@ -792,7 +789,7 @@ impl<'a> ResolveContext<'a> { .. } => TypeResolution::Value(Ti::Scalar { kind: crate::ScalarKind::Float, width }), ref other => return Err(ResolveError::IncompatibleOperands( - format!("{:?}({:?})", fun, other) + format!("{fun:?}({other:?})") )), }, // bits @@ -807,7 +804,7 @@ impl<'a> ResolveContext<'a> { Ti::Vector { size, kind: kind @ (crate::ScalarKind::Sint | crate::ScalarKind::Uint), width } => TypeResolution::Value(Ti::Vector { size, kind, width }), ref other => return Err(ResolveError::IncompatibleOperands( - format!("{:?}({:?})", fun, other) + format!("{fun:?}({other:?})") )), }, // data packing @@ -853,8 +850,7 @@ impl<'a> ResolveContext<'a> { }), ref other => { return Err(ResolveError::IncompatibleOperands(format!( - "{:?} as {:?}", - other, kind + "{other:?} as {kind:?}" ))) } }, diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 00c263946..ad15d614f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -90,7 +90,7 @@ struct Parameters { #[allow(unused_variables)] fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let root = env!("CARGO_MANIFEST_DIR"); - let params = match fs::read_to_string(format!("{}/{}/{}.param.ron", root, BASE_DIR_IN, name)) { + let params = match fs::read_to_string(format!("{root}/{BASE_DIR_IN}/{name}.param.ron")) { Ok(string) => ron::de::from_str(&string).expect("Couldn't parse param file"), Err(_) => Parameters::default(), }; @@ -108,7 +108,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { if targets.contains(Targets::IR) { let config = ron::ser::PrettyConfig::default().new_line("\n".to_string()); let string = ron::ser::to_string_pretty(module, config).unwrap(); - fs::write(dest.join(format!("ir/{}.ron", name)), string).unwrap(); + fs::write(dest.join(format!("ir/{name}.ron")), string).unwrap(); } } @@ -121,7 +121,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { if targets.contains(Targets::ANALYSIS) { let config = ron::ser::PrettyConfig::default().new_line("\n".to_string()); let string = ron::ser::to_string_pretty(&info, config).unwrap(); - fs::write(dest.join(format!("analysis/{}.info.ron", name)), string).unwrap(); + fs::write(dest.join(format!("analysis/{name}.info.ron")), string).unwrap(); } } @@ -177,7 +177,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { { if targets.contains(Targets::DOT) { let string = naga::back::dot::write(module, Some(&info), Default::default()).unwrap(); - fs::write(dest.join(format!("dot/{}.dot", name)), string).unwrap(); + fs::write(dest.join(format!("dot/{name}.dot")), string).unwrap(); } } #[cfg(all(feature = "deserialize", feature = "hlsl-out"))] @@ -248,7 +248,7 @@ fn write_output_spv( let dis = rspirv::dr::load_words(spv) .expect("Produced invalid SPIR-V") .disassemble(); - fs::write(destination.join(format!("spv/{}.spvasm", file_name)), dis).unwrap(); + fs::write(destination.join(format!("spv/{file_name}.spvasm")), dis).unwrap(); } } @@ -269,7 +269,7 @@ fn write_output_msl( let mut options = options.clone(); options.bounds_check_policies = bounds_check_policies; let (string, tr_info) = msl::write_string(module, info, &options, pipeline_options) - .unwrap_or_else(|err| panic!("Metal write failed: {}", err)); + .unwrap_or_else(|err| panic!("Metal write failed: {err}")); for (ep, result) in module.entry_points.iter().zip(tr_info.entry_point_names) { if let Err(error) = result { @@ -277,7 +277,7 @@ fn write_output_msl( } } - fs::write(destination.join(format!("msl/{}.msl", file_name)), string).unwrap(); + fs::write(destination.join(format!("msl/{file_name}.msl")), string).unwrap(); } #[cfg(feature = "glsl-out")] @@ -316,7 +316,7 @@ fn write_output_glsl( writer.write().expect("GLSL write failed"); fs::write( - destination.join(format!("glsl/{}.{}.{:?}.glsl", file_name, ep_name, stage)), + destination.join(format!("glsl/{file_name}.{ep_name}.{stage:?}.glsl")), buffer, ) .unwrap(); @@ -339,7 +339,7 @@ fn write_output_hlsl( let mut writer = hlsl::Writer::new(&mut buffer, options); let reflection_info = writer.write(module, info).expect("HLSL write failed"); - fs::write(destination.join(format!("hlsl/{}.hlsl", file_name)), buffer).unwrap(); + fs::write(destination.join(format!("hlsl/{file_name}.hlsl")), buffer).unwrap(); // We need a config file for validation script // This file contains an info about profiles (shader stages) contains inside generated shader @@ -387,15 +387,10 @@ fn write_output_hlsl( } } - writeln!( - config_str, - "{})\n{})\n{})", - vertex_str, fragment_str, compute_str - ) - .unwrap(); + writeln!(config_str, "{vertex_str})\n{fragment_str})\n{compute_str})").unwrap(); fs::write( - destination.join(format!("hlsl/{}.hlsl.config", file_name)), + destination.join(format!("hlsl/{file_name}.hlsl.config")), config_str, ) .unwrap(); @@ -418,7 +413,7 @@ fn write_output_wgsl( let string = wgsl::write_string(module, info, flags).expect("WGSL write failed"); - fs::write(destination.join(format!("wgsl/{}.wgsl", file_name)), string).unwrap(); + fs::write(destination.join(format!("wgsl/{file_name}.wgsl")), string).unwrap(); } #[cfg(feature = "wgsl-in")] @@ -564,9 +559,9 @@ fn convert_wgsl() { ]; for &(name, targets) in inputs.iter() { - println!("Processing '{}'", name); + println!("Processing '{name}'"); // WGSL shaders lives in root dir as a privileged. - let file = fs::read_to_string(format!("{}/{}/{}.wgsl", root, BASE_DIR_IN, name)) + let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/{name}.wgsl")) .expect("Couldn't find wgsl file"); match naga::front::wgsl::parse_str(&file) { Ok(module) => check_targets(&module, name, targets), @@ -581,8 +576,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { let root = env!("CARGO_MANIFEST_DIR"); let module = naga::front::spv::parse_u8_slice( - &fs::read(format!("{}/{}/spv/{}.spv", root, BASE_DIR_IN, name)) - .expect("Couldn't find spv file"), + &fs::read(format!("{root}/{BASE_DIR_IN}/spv/{name}.spv")).expect("Couldn't find spv file"), &naga::front::spv::Options { adjust_coordinate_space, strict_capabilities: false, @@ -627,7 +621,7 @@ fn convert_spv_all() { #[test] fn convert_glsl_variations_check() { let root = env!("CARGO_MANIFEST_DIR"); - let file = fs::read_to_string(format!("{}/{}/variations.glsl", root, BASE_DIR_IN)) + let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/variations.glsl")) .expect("Couldn't find glsl file"); let mut parser = naga::front::glsl::Parser::default(); let module = parser @@ -650,7 +644,7 @@ fn convert_glsl_folder() { let root = env!("CARGO_MANIFEST_DIR"); - for entry in std::fs::read_dir(format!("{}/{}/glsl", root, BASE_DIR_IN)).unwrap() { + for entry in std::fs::read_dir(format!("{root}/{BASE_DIR_IN}/glsl")).unwrap() { let entry = entry.unwrap(); let file_name = entry.file_name().into_string().unwrap(); @@ -658,7 +652,7 @@ fn convert_glsl_folder() { // No needed to validate ron files continue; } - println!("Processing {}", file_name); + println!("Processing {file_name}"); let mut parser = naga::front::glsl::Parser::default(); let module = parser @@ -668,7 +662,7 @@ fn convert_glsl_folder() { "vert" => naga::ShaderStage::Vertex, "frag" => naga::ShaderStage::Fragment, "comp" => naga::ShaderStage::Compute, - ext => panic!("Unknown extension for glsl file {}", ext), + ext => panic!("Unknown extension for glsl file {ext}"), }, defines: Default::default(), }, diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs index 409768910..0700bce09 100644 --- a/tests/spirv-capabilities.rs +++ b/tests/spirv-capabilities.rs @@ -40,10 +40,7 @@ fn require_and_forbid(required: &[Ca], forbidden: &[Ca], source: &str) { .cloned() .collect(); if !missing_caps.is_empty() { - panic!( - "shader code should have requested these caps: {:?}\n\n{}", - missing_caps, source - ); + panic!("shader code should have requested these caps: {missing_caps:?}\n\n{source}"); } let forbidden_caps: Vec<_> = forbidden @@ -52,10 +49,7 @@ fn require_and_forbid(required: &[Ca], forbidden: &[Ca], source: &str) { .cloned() .collect(); if !forbidden_caps.is_empty() { - panic!( - "shader code should not have requested these caps: {:?}\n\n{}", - forbidden_caps, source - ); + panic!("shader code should not have requested these caps: {forbidden_caps:?}\n\n{source}"); } } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 917628b27..039d4751b 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -10,9 +10,9 @@ fn check(input: &str, snapshot: &str) { if output != snapshot { for diff in diff::lines(&output, snapshot) { match diff { - diff::Result::Left(l) => println!("-{}", l), - diff::Result::Both(l, _) => println!(" {}", l), - diff::Result::Right(r) => println!("+{}", r), + diff::Result::Left(l) => println!("-{l}"), + diff::Result::Both(l, _) => println!(" {l}"), + diff::Result::Right(r) => println!("+{r}"), } } panic!("Error snapshot failed"); @@ -1419,16 +1419,12 @@ fn wrong_access_mode() { #[test] fn io_shareable_types() { for numeric in "i32 u32 f32".split_whitespace() { - let types = format!( - "{} vec2<{}> vec3<{}> vec4<{}>", - numeric, numeric, numeric, numeric - ); + let types = format!("{numeric} vec2<{numeric}> vec3<{numeric}> vec4<{numeric}>"); for ty in types.split_whitespace() { check_one_validation! { &format!("@vertex - fn f(@location(0) arg: {}) -> @builtin(position) vec4 - {{ return vec4(0.0); }}", - ty), + fn f(@location(0) arg: {ty}) -> @builtin(position) vec4 + {{ return vec4(0.0); }}"), Ok(_module) } } @@ -1443,9 +1439,8 @@ fn io_shareable_types() { { check_one_validation! { &format!("@vertex - fn f(@location(0) arg: {}) -> @builtin(position) vec4 - {{ return vec4(0.0); }}", - ty), + fn f(@location(0) arg: {ty}) -> @builtin(position) vec4 + {{ return vec4(0.0); }}"), Err( naga::valid::ValidationError::EntryPoint { stage: naga::ShaderStage::Vertex, @@ -1474,9 +1469,8 @@ fn host_shareable_types() { for ty in types.split_whitespace() { check_one_validation! { &format!("struct AStruct {{ member: array, 8> }}; - @group(0) @binding(0) var ubuf: {}; - @group(0) @binding(1) var sbuf: {};", - ty, ty), + @group(0) @binding(0) var ubuf: {ty}; + @group(0) @binding(1) var sbuf: {ty};"), Ok(_module) } } @@ -1489,8 +1483,7 @@ fn host_shareable_types() { for ty in types.split_whitespace() { check_one_validation! { &format!("struct AStruct {{ member: array, 8> }}; - @group(0) @binding(1) var sbuf: {};", - ty), + @group(0) @binding(1) var sbuf: {ty};"), Ok(_module) } } @@ -1498,7 +1491,7 @@ fn host_shareable_types() { // Types that are neither host-shareable nor constructible. for ty in "bool ptr".split_whitespace() { check_one_validation! { - &format!("@group(0) @binding(0) var sbuf: {};", ty), + &format!("@group(0) @binding(0) var sbuf: {ty};"), Err( naga::valid::ValidationError::GlobalVariable { name, @@ -1510,7 +1503,7 @@ fn host_shareable_types() { } check_one_validation! { - &format!("@group(0) @binding(0) var ubuf: {};", ty), + &format!("@group(0) @binding(0) var ubuf: {ty};"), Err(naga::valid::ValidationError::GlobalVariable { name, handle: _, From 08366c8fd009136957b7d9bd853bcade167d020e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 29 Jan 2023 20:42:22 +0000 Subject: [PATCH 1914/2212] glsl-in: Add bool overloads for relational vector builtins The `equal` and `notEqual` builtins also operate on boolean vectors but the overloads accepting them were not added. This commit fixes that. --- src/front/glsl/builtins.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 7501809c3..4df4cda33 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -850,8 +850,7 @@ fn inject_standard_builtins( declaration.overloads.push(module.add_builtin(args, fun)) } } - "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" - | "notEqual" => { + "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" => { for bits in 0..0b1001 { let (size, kind) = match bits { 0b0000 => (VectorSize::Bi, Sk::Float), @@ -873,6 +872,39 @@ fn inject_standard_builtins( "greaterThan" => BinaryOperator::Greater, "lessThanEqual" => BinaryOperator::LessEqual, "greaterThanEqual" => BinaryOperator::GreaterEqual, + _ => unreachable!(), + }); + + declaration.overloads.push(module.add_builtin(args, fun)) + } + } + "equal" | "notEqual" => { + for bits in 0..0b1100 { + let (size, kind) = match bits { + 0b0000 => (VectorSize::Bi, Sk::Float), + 0b0001 => (VectorSize::Tri, Sk::Float), + 0b0010 => (VectorSize::Quad, Sk::Float), + 0b0011 => (VectorSize::Bi, Sk::Sint), + 0b0100 => (VectorSize::Tri, Sk::Sint), + 0b0101 => (VectorSize::Quad, Sk::Sint), + 0b0110 => (VectorSize::Bi, Sk::Uint), + 0b0111 => (VectorSize::Tri, Sk::Uint), + 0b1000 => (VectorSize::Quad, Sk::Uint), + 0b1001 => (VectorSize::Bi, Sk::Bool), + 0b1010 => (VectorSize::Tri, Sk::Bool), + _ => (VectorSize::Quad, Sk::Bool), + }; + + let width = if let Sk::Bool = kind { + crate::BOOL_WIDTH + } else { + width + }; + + let ty = || TypeInner::Vector { size, kind, width }; + let args = vec![ty(), ty()]; + + let fun = MacroCall::Binary(match name { "equal" => BinaryOperator::Equal, "notEqual" => BinaryOperator::NotEqual, _ => unreachable!(), From 372a715434bd6017d433c9386608c9d5e6d6a85f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 29 Jan 2023 20:50:31 +0000 Subject: [PATCH 1915/2212] glsl-in: Add double overloads for relational vector builtins All relational vector builtins that operate on floats can also operate on doubles but these overloads were not present. This commit fixes that. --- src/front/glsl/builtins.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 4df4cda33..6347732d4 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1189,6 +1189,31 @@ fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Mod .push(module.add_builtin(args, MacroCall::Clamp(size))) } } + "lessThan" | "greaterThan" | "lessThanEqual" | "greaterThanEqual" | "equal" + | "notEqual" => { + for bits in 0..0b11 { + let (size, kind) = match bits { + 0b00 => (VectorSize::Bi, Sk::Float), + 0b01 => (VectorSize::Tri, Sk::Float), + _ => (VectorSize::Quad, Sk::Float), + }; + + let ty = || TypeInner::Vector { size, kind, width }; + let args = vec![ty(), ty()]; + + let fun = MacroCall::Binary(match name { + "lessThan" => BinaryOperator::Less, + "greaterThan" => BinaryOperator::Greater, + "lessThanEqual" => BinaryOperator::LessEqual, + "greaterThanEqual" => BinaryOperator::GreaterEqual, + "equal" => BinaryOperator::Equal, + "notEqual" => BinaryOperator::NotEqual, + _ => unreachable!(), + }); + + declaration.overloads.push(module.add_builtin(args, fun)) + } + } // Add common builtins with doubles _ => inject_common_builtin(declaration, module, name, 8), } From 191d71c107ddc3c2c93f5464dc0aad504327180c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 29 Jan 2023 20:56:42 +0000 Subject: [PATCH 1916/2212] glsl-in: Add test for relational vector builtins --- tests/in/glsl/vector-functions.vert | 46 +++++ tests/out/wgsl/vector-functions-vert.wgsl | 218 ++++++++++++++++++++++ 2 files changed, 264 insertions(+) create mode 100644 tests/in/glsl/vector-functions.vert create mode 100644 tests/out/wgsl/vector-functions-vert.wgsl diff --git a/tests/in/glsl/vector-functions.vert b/tests/in/glsl/vector-functions.vert new file mode 100644 index 000000000..0fe9ec647 --- /dev/null +++ b/tests/in/glsl/vector-functions.vert @@ -0,0 +1,46 @@ +#version 450 + +void ftest(vec4 a, vec4 b) { + bvec4 c = lessThan(a, b); + bvec4 d = lessThanEqual(a, b); + bvec4 e = greaterThan(a, b); + bvec4 f = greaterThanEqual(a, b); + bvec4 g = equal(a, b); + bvec4 h = notEqual(a, b); +} + +void dtest(dvec4 a, dvec4 b) { + bvec4 c = lessThan(a, b); + bvec4 d = lessThanEqual(a, b); + bvec4 e = greaterThan(a, b); + bvec4 f = greaterThanEqual(a, b); + bvec4 g = equal(a, b); + bvec4 h = notEqual(a, b); +} + +void itest(ivec4 a, ivec4 b) { + bvec4 c = lessThan(a, b); + bvec4 d = lessThanEqual(a, b); + bvec4 e = greaterThan(a, b); + bvec4 f = greaterThanEqual(a, b); + bvec4 g = equal(a, b); + bvec4 h = notEqual(a, b); +} + +void utest(uvec4 a, uvec4 b) { + bvec4 c = lessThan(a, b); + bvec4 d = lessThanEqual(a, b); + bvec4 e = greaterThan(a, b); + bvec4 f = greaterThanEqual(a, b); + bvec4 g = equal(a, b); + bvec4 h = notEqual(a, b); +} + +void btest(bvec4 a, bvec4 b) { + bvec4 c = equal(a, b); + bvec4 d = notEqual(a, b); + bool e = any(a); + bool f = all(a); +} + +void main() {} diff --git a/tests/out/wgsl/vector-functions-vert.wgsl b/tests/out/wgsl/vector-functions-vert.wgsl new file mode 100644 index 000000000..a2c16d6a6 --- /dev/null +++ b/tests/out/wgsl/vector-functions-vert.wgsl @@ -0,0 +1,218 @@ +fn ftest(a: vec4, b: vec4) { + var a_1: vec4; + var b_1: vec4; + var c: vec4; + var d: vec4; + var e: vec4; + var f: vec4; + var g: vec4; + var h: vec4; + + a_1 = a; + b_1 = b; + _ = a_1; + _ = b_1; + let _e6 = a_1; + let _e7 = b_1; + c = (_e6 < _e7); + _ = a_1; + _ = b_1; + let _e12 = a_1; + let _e13 = b_1; + d = (_e12 <= _e13); + _ = a_1; + _ = b_1; + let _e18 = a_1; + let _e19 = b_1; + e = (_e18 > _e19); + _ = a_1; + _ = b_1; + let _e24 = a_1; + let _e25 = b_1; + f = (_e24 >= _e25); + _ = a_1; + _ = b_1; + let _e30 = a_1; + let _e31 = b_1; + g = (_e30 == _e31); + _ = a_1; + _ = b_1; + let _e36 = a_1; + let _e37 = b_1; + h = (_e36 != _e37); + return; +} + +fn dtest(a_2: vec4, b_2: vec4) { + var a_3: vec4; + var b_3: vec4; + var c_1: vec4; + var d_1: vec4; + var e_1: vec4; + var f_1: vec4; + var g_1: vec4; + var h_1: vec4; + + a_3 = a_2; + b_3 = b_2; + _ = a_3; + _ = b_3; + let _e6 = a_3; + let _e7 = b_3; + c_1 = (_e6 < _e7); + _ = a_3; + _ = b_3; + let _e12 = a_3; + let _e13 = b_3; + d_1 = (_e12 <= _e13); + _ = a_3; + _ = b_3; + let _e18 = a_3; + let _e19 = b_3; + e_1 = (_e18 > _e19); + _ = a_3; + _ = b_3; + let _e24 = a_3; + let _e25 = b_3; + f_1 = (_e24 >= _e25); + _ = a_3; + _ = b_3; + let _e30 = a_3; + let _e31 = b_3; + g_1 = (_e30 == _e31); + _ = a_3; + _ = b_3; + let _e36 = a_3; + let _e37 = b_3; + h_1 = (_e36 != _e37); + return; +} + +fn itest(a_4: vec4, b_4: vec4) { + var a_5: vec4; + var b_5: vec4; + var c_2: vec4; + var d_2: vec4; + var e_2: vec4; + var f_2: vec4; + var g_2: vec4; + var h_2: vec4; + + a_5 = a_4; + b_5 = b_4; + _ = a_5; + _ = b_5; + let _e6 = a_5; + let _e7 = b_5; + c_2 = (_e6 < _e7); + _ = a_5; + _ = b_5; + let _e12 = a_5; + let _e13 = b_5; + d_2 = (_e12 <= _e13); + _ = a_5; + _ = b_5; + let _e18 = a_5; + let _e19 = b_5; + e_2 = (_e18 > _e19); + _ = a_5; + _ = b_5; + let _e24 = a_5; + let _e25 = b_5; + f_2 = (_e24 >= _e25); + _ = a_5; + _ = b_5; + let _e30 = a_5; + let _e31 = b_5; + g_2 = (_e30 == _e31); + _ = a_5; + _ = b_5; + let _e36 = a_5; + let _e37 = b_5; + h_2 = (_e36 != _e37); + return; +} + +fn utest(a_6: vec4, b_6: vec4) { + var a_7: vec4; + var b_7: vec4; + var c_3: vec4; + var d_3: vec4; + var e_3: vec4; + var f_3: vec4; + var g_3: vec4; + var h_3: vec4; + + a_7 = a_6; + b_7 = b_6; + _ = a_7; + _ = b_7; + let _e6 = a_7; + let _e7 = b_7; + c_3 = (_e6 < _e7); + _ = a_7; + _ = b_7; + let _e12 = a_7; + let _e13 = b_7; + d_3 = (_e12 <= _e13); + _ = a_7; + _ = b_7; + let _e18 = a_7; + let _e19 = b_7; + e_3 = (_e18 > _e19); + _ = a_7; + _ = b_7; + let _e24 = a_7; + let _e25 = b_7; + f_3 = (_e24 >= _e25); + _ = a_7; + _ = b_7; + let _e30 = a_7; + let _e31 = b_7; + g_3 = (_e30 == _e31); + _ = a_7; + _ = b_7; + let _e36 = a_7; + let _e37 = b_7; + h_3 = (_e36 != _e37); + return; +} + +fn btest(a_8: vec4, b_8: vec4) { + var a_9: vec4; + var b_9: vec4; + var c_4: vec4; + var d_4: vec4; + var e_4: bool; + var f_4: bool; + + a_9 = a_8; + b_9 = b_8; + _ = a_9; + _ = b_9; + let _e6 = a_9; + let _e7 = b_9; + c_4 = (_e6 == _e7); + _ = a_9; + _ = b_9; + let _e12 = a_9; + let _e13 = b_9; + d_4 = (_e12 != _e13); + _ = a_9; + let _e17 = a_9; + e_4 = any(_e17); + _ = a_9; + let _e21 = a_9; + f_4 = all(_e21); + return; +} + +fn main_1() { + return; +} + +@vertex +fn main() { + main_1(); + return; +} From ae049edc494991f47630a863b3fe970991dcda8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Sun, 29 Jan 2023 20:57:39 +0000 Subject: [PATCH 1917/2212] glsl-in: Add not vector relational builtin --- src/front/glsl/builtins.rs | 19 +++++++++++++------ tests/in/glsl/vector-functions.vert | 1 + tests/out/wgsl/vector-functions-vert.wgsl | 4 ++++ 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 6347732d4..7206bd2f3 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -9,7 +9,7 @@ use super::{ use crate::{ BinaryOperator, Block, Constant, DerivativeAxis, Expression, Handle, ImageClass, ImageDimension as Dim, ImageQuery, MathFunction, Module, RelationalFunction, SampleLevel, - ScalarKind as Sk, Span, Type, TypeInner, VectorSize, + ScalarKind as Sk, Span, Type, TypeInner, UnaryOperator, VectorSize, }; impl crate::ScalarKind { @@ -825,7 +825,7 @@ fn inject_standard_builtins( .push(module.add_builtin(args, MacroCall::MathFunction(fun))) } } - "all" | "any" => { + "all" | "any" | "not" => { // bits layout // bit 0 trough 1 - dims for bits in 0..0b11 { @@ -841,11 +841,12 @@ fn inject_standard_builtins( width: crate::BOOL_WIDTH, }]; - let fun = MacroCall::Relational(match name { - "all" => RelationalFunction::All, - "any" => RelationalFunction::Any, + let fun = match name { + "all" => MacroCall::Relational(RelationalFunction::All), + "any" => MacroCall::Relational(RelationalFunction::Any), + "not" => MacroCall::Unary(UnaryOperator::Not), _ => unreachable!(), - }); + }; declaration.overloads.push(module.add_builtin(args, fun)) } @@ -1653,6 +1654,7 @@ pub enum MacroCall { BitfieldExtract, BitfieldInsert, Relational(RelationalFunction), + Unary(UnaryOperator), Binary(BinaryOperator), Mod(Option), Splatted(MathFunction, Option, usize), @@ -2020,6 +2022,11 @@ impl MacroCall { Span::default(), body, ), + MacroCall::Unary(op) => ctx.add_expression( + Expression::Unary { op, expr: args[0] }, + Span::default(), + body, + ), MacroCall::Binary(op) => ctx.add_expression( Expression::Binary { op, diff --git a/tests/in/glsl/vector-functions.vert b/tests/in/glsl/vector-functions.vert index 0fe9ec647..bb212cdc9 100644 --- a/tests/in/glsl/vector-functions.vert +++ b/tests/in/glsl/vector-functions.vert @@ -41,6 +41,7 @@ void btest(bvec4 a, bvec4 b) { bvec4 d = notEqual(a, b); bool e = any(a); bool f = all(a); + bvec4 g = not(a); } void main() {} diff --git a/tests/out/wgsl/vector-functions-vert.wgsl b/tests/out/wgsl/vector-functions-vert.wgsl index a2c16d6a6..29915bf2f 100644 --- a/tests/out/wgsl/vector-functions-vert.wgsl +++ b/tests/out/wgsl/vector-functions-vert.wgsl @@ -185,6 +185,7 @@ fn btest(a_8: vec4, b_8: vec4) { var d_4: vec4; var e_4: bool; var f_4: bool; + var g_4: vec4; a_9 = a_8; b_9 = b_8; @@ -204,6 +205,9 @@ fn btest(a_8: vec4, b_8: vec4) { _ = a_9; let _e21 = a_9; f_4 = all(_e21); + _ = a_9; + let _e25 = a_9; + g_4 = !(_e25); return; } From 67ea8f0c0684d80e1f54af9abd875034748d5e07 Mon Sep 17 00:00:00 2001 From: Shaye Garg <64652557+SparkyPotato@users.noreply.github.com> Date: Tue, 31 Jan 2023 20:47:58 +0530 Subject: [PATCH 1918/2212] [wgsl-in] Split into multiple files (#2207) Make changes suggested in #2075, but put off to a separate PR because they would interfere with reviewing the change: - Split the new WGSL front end into modules in a logical way. - Rename `Parser` to `Frontend`. --- benches/criterion.rs | 16 +- cli/src/bin/naga.rs | 2 +- src/front/glsl/builtins.rs | 46 +- src/front/glsl/context.rs | 173 +- src/front/glsl/functions.rs | 8 +- src/front/glsl/mod.rs | 36 +- src/front/glsl/parser.rs | 72 +- src/front/glsl/parser/declarations.rs | 174 +- src/front/glsl/parser/expressions.rs | 134 +- src/front/glsl/parser/functions.rs | 271 +- src/front/glsl/parser/types.rs | 145 +- src/front/glsl/parser_tests.rs | 122 +- src/front/glsl/types.rs | 6 +- src/front/glsl/variables.rs | 6 +- src/front/spv/function.rs | 2 +- src/front/spv/image.rs | 2 +- src/front/spv/mod.rs | 8 +- src/front/wgsl/error.rs | 672 +++ src/front/wgsl/index.rs | 3 +- src/front/wgsl/{ => lower}/construction.rs | 8 +- src/front/wgsl/lower/mod.rs | 2371 +++++++++ src/front/wgsl/mod.rs | 5169 +------------------- src/front/wgsl/{ => parse}/ast.rs | 14 +- src/front/wgsl/{ => parse}/conv.rs | 0 src/front/wgsl/{ => parse}/lexer.rs | 82 +- src/front/wgsl/parse/mod.rs | 2062 ++++++++ src/front/wgsl/{ => parse}/number.rs | 7 +- tests/snapshots.rs | 4 +- 28 files changed, 5843 insertions(+), 5772 deletions(-) create mode 100644 src/front/wgsl/error.rs rename src/front/wgsl/{ => lower}/construction.rs (99%) create mode 100644 src/front/wgsl/lower/mod.rs rename src/front/wgsl/{ => parse}/ast.rs (97%) rename src/front/wgsl/{ => parse}/conv.rs (100%) rename src/front/wgsl/{ => parse}/lexer.rs (90%) create mode 100644 src/front/wgsl/parse/mod.rs rename src/front/wgsl/{ => parse}/number.rs (98%) diff --git a/benches/criterion.rs b/benches/criterion.rs index 5093ab045..ad00cb59e 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -28,7 +28,7 @@ fn gather_inputs(folder: &str, extension: &str) -> Vec> { } fn parse_glsl(stage: naga::ShaderStage, inputs: &[Box<[u8]>]) { - let mut parser = naga::front::glsl::Parser::default(); + let mut parser = naga::front::glsl::Frontend::default(); let options = naga::front::glsl::Options { stage, defines: Default::default(), @@ -44,12 +44,12 @@ fn frontends(c: &mut Criterion) { #[cfg(all(feature = "wgsl-in", feature = "serialize", feature = "deserialize"))] group.bench_function("bin", |b| { let inputs_wgsl = gather_inputs("tests/in", "wgsl"); - let mut parser = naga::front::wgsl::Parser::new(); + let mut frontend = naga::front::wgsl::Frontend::new(); let inputs_bin = inputs_wgsl .iter() .map(|input| { let string = std::str::from_utf8(input).unwrap(); - let module = parser.parse(string).unwrap(); + let module = frontend.parse(string).unwrap(); bincode::serialize(&module).unwrap() }) .collect::>(); @@ -66,10 +66,10 @@ fn frontends(c: &mut Criterion) { .iter() .map(|input| std::str::from_utf8(input).unwrap()) .collect::>(); - let mut parser = naga::front::wgsl::Parser::new(); + let mut frontend = naga::front::wgsl::Frontend::new(); b.iter(move || { for &input in inputs.iter() { - parser.parse(input).unwrap(); + frontend.parse(input).unwrap(); } }); }); @@ -81,7 +81,7 @@ fn frontends(c: &mut Criterion) { for input in inputs.iter() { let spv = unsafe { slice::from_raw_parts(input.as_ptr() as *const u32, input.len() / 4) }; - let parser = naga::front::spv::Parser::new(spv.iter().cloned(), &options); + let parser = naga::front::spv::Frontend::new(spv.iter().cloned(), &options); parser.parse().unwrap(); } }); @@ -101,12 +101,12 @@ fn frontends(c: &mut Criterion) { #[cfg(feature = "wgsl-in")] fn gather_modules() -> Vec { let inputs = gather_inputs("tests/in", "wgsl"); - let mut parser = naga::front::wgsl::Parser::new(); + let mut frontend = naga::front::wgsl::Frontend::new(); inputs .iter() .map(|input| { let string = std::str::from_utf8(input).unwrap(); - parser.parse(string).unwrap() + frontend.parse(string).unwrap() }) .collect() } diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index ddf65f59c..b121dd52d 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -289,7 +289,7 @@ fn run() -> Result<(), Box> { } ext @ ("vert" | "frag" | "comp") => { let input = String::from_utf8(input)?; - let mut parser = naga::front::glsl::Parser::default(); + let mut parser = naga::front::glsl::Frontend::default(); ( parser diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 7206bd2f3..4ff8add9a 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -4,7 +4,7 @@ use super::{ ParameterQualifier, }, context::Context, - Error, ErrorKind, Parser, Result, + Error, ErrorKind, Frontend, Result, }; use crate::{ BinaryOperator, Block, Constant, DerivativeAxis, Expression, Handle, ImageClass, @@ -1676,7 +1676,7 @@ impl MacroCall { /// finally returns the final expression with the correct result pub fn call( &self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, args: &mut [Handle], @@ -1688,8 +1688,14 @@ impl MacroCall { args[0] } MacroCall::SamplerShadow => { - sampled_to_depth(&mut parser.module, ctx, args[0], meta, &mut parser.errors); - parser.invalidate_expression(ctx, args[0], meta)?; + sampled_to_depth( + &mut frontend.module, + ctx, + args[0], + meta, + &mut frontend.errors, + ); + frontend.invalidate_expression(ctx, args[0], meta)?; ctx.samplers.insert(args[0], args[1]); args[0] } @@ -1702,7 +1708,7 @@ impl MacroCall { let mut coords = args[1]; if proj { - let size = match *parser.resolve_type(ctx, coords, meta)? { + let size = match *frontend.resolve_type(ctx, coords, meta)? { TypeInner::Vector { size, .. } => size, _ => unreachable!(), }; @@ -1748,7 +1754,7 @@ impl MacroCall { let extra = args.get(2).copied(); let comps = - parser.coordinate_components(ctx, args[0], coords, extra, meta, body)?; + frontend.coordinate_components(ctx, args[0], coords, extra, meta, body)?; let mut num_args = 2; @@ -1795,10 +1801,10 @@ impl MacroCall { true => { let offset_arg = args[num_args]; num_args += 1; - match parser.solve_constant(ctx, offset_arg, meta) { + match frontend.solve_constant(ctx, offset_arg, meta) { Ok(v) => Some(v), Err(e) => { - parser.errors.push(e); + frontend.errors.push(e); None } } @@ -1832,7 +1838,7 @@ impl MacroCall { if arrayed { let mut components = Vec::with_capacity(4); - let size = match *parser.resolve_type(ctx, expr, meta)? { + let size = match *frontend.resolve_type(ctx, expr, meta)? { TypeInner::Vector { size: ori_size, .. } => { for index in 0..(ori_size as u32) { components.push(ctx.add_expression( @@ -1862,7 +1868,7 @@ impl MacroCall { body, )); - let ty = parser.module.types.insert( + let ty = frontend.module.types.insert( Type { name: None, inner: TypeInner::Vector { @@ -1881,7 +1887,7 @@ impl MacroCall { } MacroCall::ImageLoad { multi } => { let comps = - parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; + frontend.coordinate_components(ctx, args[0], args[1], None, meta, body)?; let (sample, level) = match (multi, args.get(2)) { (_, None) => (None, None), (true, Some(&arg)) => (Some(arg), None), @@ -1901,7 +1907,7 @@ impl MacroCall { } MacroCall::ImageStore => { let comps = - parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; + frontend.coordinate_components(ctx, args[0], args[1], None, meta, body)?; ctx.emit_restart(body); body.push( crate::Statement::ImageStore { @@ -2037,7 +2043,7 @@ impl MacroCall { body, ), MacroCall::Mod(size) => { - ctx.implicit_splat(parser, &mut args[1], meta, size)?; + ctx.implicit_splat(frontend, &mut args[1], meta, size)?; // x - y * floor(x / y) @@ -2081,7 +2087,7 @@ impl MacroCall { ) } MacroCall::Splatted(fun, size, i) => { - ctx.implicit_splat(parser, &mut args[i], meta, size)?; + ctx.implicit_splat(frontend, &mut args[i], meta, size)?; ctx.add_expression( Expression::Math { @@ -2105,8 +2111,8 @@ impl MacroCall { body, ), MacroCall::Clamp(size) => { - ctx.implicit_splat(parser, &mut args[1], meta, size)?; - ctx.implicit_splat(parser, &mut args[2], meta, size)?; + ctx.implicit_splat(frontend, &mut args[1], meta, size)?; + ctx.implicit_splat(frontend, &mut args[2], meta, size)?; ctx.add_expression( Expression::Math { @@ -2143,8 +2149,8 @@ impl MacroCall { return Ok(None); } MacroCall::SmoothStep { splatted } => { - ctx.implicit_splat(parser, &mut args[0], meta, splatted)?; - ctx.implicit_splat(parser, &mut args[1], meta, splatted)?; + ctx.implicit_splat(frontend, &mut args[0], meta, splatted)?; + ctx.implicit_splat(frontend, &mut args[1], meta, splatted)?; ctx.add_expression( Expression::Math { @@ -2202,7 +2208,7 @@ fn texture_call( /// Helper struct for texture calls with the separate components from the vector argument /// -/// Obtained by calling [`coordinate_components`](Parser::coordinate_components) +/// Obtained by calling [`coordinate_components`](Frontend::coordinate_components) #[derive(Debug)] struct CoordComponents { coordinate: Handle, @@ -2211,7 +2217,7 @@ struct CoordComponents { used_extra: bool, } -impl Parser { +impl Frontend { /// Helper function for texture calls, splits the vector argument into it's components fn coordinate_components( &mut self, diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 930cd4559..d7a56051b 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -5,7 +5,7 @@ use super::{ }, error::{Error, ErrorKind}, types::{scalar_components, type_power}, - Parser, Result, + Frontend, Result, }; use crate::{ front::{Emitter, Typifier}, @@ -61,7 +61,7 @@ pub struct Context { } impl Context { - pub fn new(parser: &Parser, body: &mut Block) -> Self { + pub fn new(frontend: &Frontend, body: &mut Block) -> Self { let mut this = Context { expressions: Arena::new(), locals: Arena::new(), @@ -80,8 +80,8 @@ impl Context { this.emit_start(); - for &(ref name, lookup) in parser.global_variables.iter() { - this.add_global(parser, name, lookup, body) + for &(ref name, lookup) in frontend.global_variables.iter() { + this.add_global(frontend, name, lookup, body) } this @@ -89,7 +89,7 @@ impl Context { pub fn add_global( &mut self, - parser: &Parser, + frontend: &Frontend, name: &str, GlobalLookup { kind, @@ -101,10 +101,10 @@ impl Context { self.emit_end(body); let (expr, load, constant) = match kind { GlobalLookupKind::Variable(v) => { - let span = parser.module.global_variables.get_span(v); + let span = frontend.module.global_variables.get_span(v); let res = ( self.expressions.append(Expression::GlobalVariable(v), span), - parser.module.global_variables[v].space != AddressSpace::Handle, + frontend.module.global_variables[v].space != AddressSpace::Handle, None, ); self.emit_start(); @@ -112,7 +112,7 @@ impl Context { res } GlobalLookupKind::BlockSelect(handle, index) => { - let span = parser.module.global_variables.get_span(handle); + let span = frontend.module.global_variables.get_span(handle); let base = self .expressions .append(Expression::GlobalVariable(handle), span); @@ -124,14 +124,14 @@ impl Context { ( expr, { - let ty = parser.module.global_variables[handle].ty; + let ty = frontend.module.global_variables[handle].ty; - match parser.module.types[ty].inner { + match frontend.module.types[ty].inner { TypeInner::Struct { ref members, .. } => { if let TypeInner::Array { size: crate::ArraySize::Dynamic, .. - } = parser.module.types[members[index as usize].ty].inner + } = frontend.module.types[members[index as usize].ty].inner { false } else { @@ -145,7 +145,7 @@ impl Context { ) } GlobalLookupKind::Constant(v, ty) => { - let span = parser.module.constants.get_span(v); + let span = frontend.module.constants.get_span(v); let res = ( self.expressions.append(Expression::Constant(v), span), false, @@ -241,7 +241,7 @@ impl Context { /// Add function argument to current scope pub fn add_function_arg( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, body: &mut Block, name_meta: Option<(String, Span)>, ty: Handle, @@ -255,14 +255,14 @@ impl Context { }; self.parameters.push(ty); - let opaque = match parser.module.types[ty].inner { + let opaque = match frontend.module.types[ty].inner { TypeInner::Image { .. } | TypeInner::Sampler { .. } => true, _ => false, }; if qualifier.is_lhs() { - let span = parser.module.types.get_span(arg.ty); - arg.ty = parser.module.types.insert( + let span = frontend.module.types.get_span(arg.ty); + arg.ty = frontend.module.types.insert( Type { name: None, inner: TypeInner::Pointer { @@ -345,12 +345,12 @@ impl Context { pub fn lower( &mut self, mut stmt: StmtContext, - parser: &mut Parser, + frontend: &mut Frontend, expr: Handle, pos: ExprPos, body: &mut Block, ) -> Result<(Option>, Span)> { - let res = self.lower_inner(&stmt, parser, expr, pos, body); + let res = self.lower_inner(&stmt, frontend, expr, pos, body); stmt.hir_exprs.clear(); self.stmt_ctx = Some(stmt); @@ -366,12 +366,12 @@ impl Context { pub fn lower_expect( &mut self, mut stmt: StmtContext, - parser: &mut Parser, + frontend: &mut Frontend, expr: Handle, pos: ExprPos, body: &mut Block, ) -> Result<(Handle, Span)> { - let res = self.lower_expect_inner(&stmt, parser, expr, pos, body); + let res = self.lower_expect_inner(&stmt, frontend, expr, pos, body); stmt.hir_exprs.clear(); self.stmt_ctx = Some(stmt); @@ -382,17 +382,17 @@ impl Context { /// internal implementation of [`lower_expect`](Self::lower_expect) /// /// this method is only public because it's used in - /// [`function_call`](Parser::function_call), unless you know what + /// [`function_call`](Frontend::function_call), unless you know what /// you're doing use [`lower_expect`](Self::lower_expect) pub fn lower_expect_inner( &mut self, stmt: &StmtContext, - parser: &mut Parser, + frontend: &mut Frontend, expr: Handle, pos: ExprPos, body: &mut Block, ) -> Result<(Handle, Span)> { - let (maybe_expr, meta) = self.lower_inner(stmt, parser, expr, pos, body)?; + let (maybe_expr, meta) = self.lower_inner(stmt, frontend, expr, pos, body)?; let expr = match maybe_expr { Some(e) => e, @@ -472,7 +472,7 @@ impl Context { fn lower_inner( &mut self, stmt: &StmtContext, - parser: &mut Parser, + frontend: &mut Frontend, expr: Handle, pos: ExprPos, body: &mut Block, @@ -484,18 +484,18 @@ impl Context { let handle = match *kind { HirExprKind::Access { base, index } => { let (index, index_meta) = - self.lower_expect_inner(stmt, parser, index, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, index, ExprPos::Rhs, body)?; let maybe_constant_index = match pos { // Don't try to generate `AccessIndex` if in a LHS position, since it // wouldn't produce a pointer. ExprPos::Lhs => None, - _ => parser.solve_constant(self, index, index_meta).ok(), + _ => frontend.solve_constant(self, index, index_meta).ok(), }; let base = self .lower_expect_inner( stmt, - parser, + frontend, base, pos.maybe_access_base(maybe_constant_index.is_some()), body, @@ -507,7 +507,7 @@ impl Context { Some(self.add_expression( Expression::AccessIndex { base, - index: match parser.module.constants[constant].inner { + index: match frontend.module.constants[constant].inner { crate::ConstantInner::Scalar { value: ScalarValue::Uint(i), .. @@ -528,7 +528,7 @@ impl Context { }); if ExprPos::Rhs == pos { - let resolved = parser.resolve_type(self, pointer, meta)?; + let resolved = frontend.resolve_type(self, pointer, meta)?; if resolved.pointer_space().is_some() { return Ok(( Some(self.add_expression(Expression::Load { pointer }, meta, body)), @@ -540,32 +540,38 @@ impl Context { pointer } HirExprKind::Select { base, ref field } => { - let base = self.lower_expect_inner(stmt, parser, base, pos, body)?.0; + let base = self.lower_expect_inner(stmt, frontend, base, pos, body)?.0; - parser.field_selection(self, pos, body, base, field, meta)? + frontend.field_selection(self, pos, body, base, field, meta)? } HirExprKind::Constant(constant) if pos != ExprPos::Lhs => { self.add_expression(Expression::Constant(constant), meta, body) } HirExprKind::Binary { left, op, right } if pos != ExprPos::Lhs => { let (mut left, left_meta) = - self.lower_expect_inner(stmt, parser, left, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, left, ExprPos::Rhs, body)?; let (mut right, right_meta) = - self.lower_expect_inner(stmt, parser, right, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, right, ExprPos::Rhs, body)?; match op { BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self - .implicit_conversion(parser, &mut right, right_meta, ScalarKind::Uint, 4)?, + .implicit_conversion( + frontend, + &mut right, + right_meta, + ScalarKind::Uint, + 4, + )?, _ => self.binary_implicit_conversion( - parser, &mut left, left_meta, &mut right, right_meta, + frontend, &mut left, left_meta, &mut right, right_meta, )?, } - parser.typifier_grow(self, left, left_meta)?; - parser.typifier_grow(self, right, right_meta)?; + frontend.typifier_grow(self, left, left_meta)?; + frontend.typifier_grow(self, right, right_meta)?; - let left_inner = self.typifier.get(left, &parser.module.types); - let right_inner = self.typifier.get(right, &parser.module.types); + let left_inner = self.typifier.get(left, &frontend.module.types); + let right_inner = self.typifier.get(right, &frontend.module.types); match (left_inner, right_inner) { ( @@ -588,7 +594,7 @@ impl Context { // Check that the two arguments have the same dimensions if !dimensions_ok || left_width != right_width { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( format!( "Cannot apply operation to {left_inner:?} and {right_inner:?}" @@ -634,7 +640,7 @@ impl Context { // Rebuild the matrix from the divided vectors self.expressions.append( Expression::Compose { - ty: parser.module.types.insert( + ty: frontend.module.types.insert( Type { name: None, inner: TypeInner::Matrix { @@ -819,7 +825,7 @@ impl Context { ) => { // Check that the two arguments have the same width if left_width != right_width { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( format!( "Cannot apply operation to {left_inner:?} and {right_inner:?}" @@ -874,7 +880,7 @@ impl Context { // Rebuild the matrix from the operation result vectors self.expressions.append( Expression::Compose { - ty: parser.module.types.insert( + ty: frontend.module.types.insert( Type { name: None, inner: TypeInner::Matrix { @@ -909,7 +915,7 @@ impl Context { ) => { // Check that the two arguments have the same width if left_width != right_width { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( format!( "Cannot apply operation to {left_inner:?} and {right_inner:?}" @@ -965,7 +971,7 @@ impl Context { // Rebuild the matrix from the operation result vectors self.expressions.append( Expression::Compose { - ty: parser.module.types.insert( + ty: frontend.module.types.insert( Type { name: None, inner: TypeInner::Matrix { @@ -993,7 +999,7 @@ impl Context { } HirExprKind::Unary { op, expr } if pos != ExprPos::Lhs => { let expr = self - .lower_expect_inner(stmt, parser, expr, ExprPos::Rhs, body)? + .lower_expect_inner(stmt, frontend, expr, ExprPos::Rhs, body)? .0; self.add_expression(Expression::Unary { op, expr }, meta, body) @@ -1001,7 +1007,7 @@ impl Context { HirExprKind::Variable(ref var) => match pos { ExprPos::Lhs => { if !var.mutable { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Variable cannot be used in LHS position".into(), ), @@ -1044,7 +1050,7 @@ impl Context { _ => var.expr, }, HirExprKind::Call(ref call) if pos != ExprPos::Lhs => { - let maybe_expr = parser.function_or_constructor_call( + let maybe_expr = frontend.function_or_constructor_call( self, stmt, body, @@ -1080,7 +1086,7 @@ impl Context { // Lower the condition first to the current bodyy let condition = self - .lower_expect_inner(stmt, parser, condition, ExprPos::Rhs, body)? + .lower_expect_inner(stmt, frontend, condition, ExprPos::Rhs, body)? .0; // Emit all expressions since we will be adding statements to @@ -1093,7 +1099,7 @@ impl Context { // Lower the `true` branch let (mut accept, accept_meta) = - self.lower_expect_inner(stmt, parser, accept, pos, &mut accept_body)?; + self.lower_expect_inner(stmt, frontend, accept, pos, &mut accept_body)?; // Flush the body of the `true` branch, to start emitting on the // `false` branch @@ -1101,7 +1107,7 @@ impl Context { // Lower the `false` branch let (mut reject, reject_meta) = - self.lower_expect_inner(stmt, parser, reject, pos, &mut reject_body)?; + self.lower_expect_inner(stmt, frontend, reject, pos, &mut reject_body)?; // Flush the body of the `false` branch self.emit_restart(&mut reject_body); @@ -1113,9 +1119,9 @@ impl Context { Some((reject_power, reject_width, reject_kind)), ) = ( // Get the components of both branches and calculate the type power - self.expr_scalar_components(parser, accept, accept_meta)? + self.expr_scalar_components(frontend, accept, accept_meta)? .and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), - self.expr_scalar_components(parser, reject, reject_meta)? + self.expr_scalar_components(frontend, reject, reject_meta)? .and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), ) { match accept_power.cmp(&reject_power) { @@ -1146,7 +1152,7 @@ impl Context { // We need to get the type of the resulting expression to create the local, // this must be done after implicit conversions to ensure both branches have // the same type. - let ty = parser.resolve_type_handle(self, accept, accept_meta)?; + let ty = frontend.resolve_type_handle(self, accept, accept_meta)?; // Add the local that will hold the result of our conditional let local = self.locals.append( @@ -1205,17 +1211,17 @@ impl Context { } HirExprKind::Assign { tgt, value } if ExprPos::Lhs != pos => { let (pointer, ptr_meta) = - self.lower_expect_inner(stmt, parser, tgt, ExprPos::Lhs, body)?; + self.lower_expect_inner(stmt, frontend, tgt, ExprPos::Lhs, body)?; let (mut value, value_meta) = - self.lower_expect_inner(stmt, parser, value, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, value, ExprPos::Rhs, body)?; - let ty = match *parser.resolve_type(self, pointer, ptr_meta)? { - TypeInner::Pointer { base, .. } => &parser.module.types[base].inner, + let ty = match *frontend.resolve_type(self, pointer, ptr_meta)? { + TypeInner::Pointer { base, .. } => &frontend.module.types[base].inner, ref ty => ty, }; if let Some((kind, width)) = scalar_components(ty) { - self.implicit_conversion(parser, &mut value, value_meta, kind, width)?; + self.implicit_conversion(frontend, &mut value, value_meta, kind, width)?; } self.lower_store(pointer, value, meta, body); @@ -1224,7 +1230,7 @@ impl Context { } HirExprKind::PrePostfix { op, postfix, expr } if ExprPos::Lhs != pos => { let (pointer, _) = - self.lower_expect_inner(stmt, parser, expr, ExprPos::Lhs, body)?; + self.lower_expect_inner(stmt, frontend, expr, ExprPos::Lhs, body)?; let left = if let Expression::Swizzle { .. } = self.expressions[pointer] { pointer } else { @@ -1241,7 +1247,7 @@ impl Context { Some(crate::ConstantInner::Scalar { width, value }) }; - let res = match *parser.resolve_type(self, left, meta)? { + let res = match *frontend.resolve_type(self, left, meta)? { TypeInner::Scalar { kind, width } => { let ty = TypeInner::Scalar { kind, width }; make_constant_inner(kind, width).map(|i| (ty, i, None, None)) @@ -1268,7 +1274,7 @@ impl Context { let (ty_inner, inner, rows, columns) = match res { Some(res) => res, None => { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Increment/decrement only works on scalar/vector/matrix".into(), ), @@ -1278,7 +1284,7 @@ impl Context { } }; - let constant_1 = parser.module.constants.append( + let constant_1 = frontend.module.constants.append( Constant { name: None, specialization: None, @@ -1297,7 +1303,7 @@ impl Context { self.add_expression(Expression::Splat { size, value: right }, meta, body); if let Some(cols) = columns { - let ty = parser.module.types.insert( + let ty = frontend.module.types.insert( Type { name: None, inner: ty_inner, @@ -1333,21 +1339,22 @@ impl Context { } if ExprPos::Lhs != pos => { let args = args .iter() - .map(|e| self.lower_expect_inner(stmt, parser, *e, ExprPos::Rhs, body)) + .map(|e| self.lower_expect_inner(stmt, frontend, *e, ExprPos::Rhs, body)) .collect::>>()?; match name.as_ref() { "length" => { if !args.is_empty() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( ".length() doesn't take any arguments".into(), ), meta, }); } - let lowered_array = - self.lower_expect_inner(stmt, parser, object, pos, body)?.0; - let array_type = parser.resolve_type(self, lowered_array, meta)?; + let lowered_array = self + .lower_expect_inner(stmt, frontend, object, pos, body)? + .0; + let array_type = frontend.resolve_type(self, lowered_array, meta)?; match *array_type { TypeInner::Array { @@ -1357,7 +1364,7 @@ impl Context { let mut array_length = self.add_expression(Expression::Constant(size), meta, body); self.forced_conversion( - parser, + frontend, &mut array_length, meta, ScalarKind::Sint, @@ -1411,22 +1418,22 @@ impl Context { pub fn expr_scalar_components( &mut self, - parser: &Parser, + frontend: &Frontend, expr: Handle, meta: Span, ) -> Result> { - let ty = parser.resolve_type(self, expr, meta)?; + let ty = frontend.resolve_type(self, expr, meta)?; Ok(scalar_components(ty)) } pub fn expr_power( &mut self, - parser: &Parser, + frontend: &Frontend, expr: Handle, meta: Span, ) -> Result> { Ok(self - .expr_scalar_components(parser, expr, meta)? + .expr_scalar_components(frontend, expr, meta)? .and_then(|(kind, width)| type_power(kind, width))) } @@ -1451,7 +1458,7 @@ impl Context { pub fn implicit_conversion( &mut self, - parser: &Parser, + frontend: &Frontend, expr: &mut Handle, meta: Span, kind: ScalarKind, @@ -1459,7 +1466,7 @@ impl Context { ) -> Result<()> { if let (Some(tgt_power), Some(expr_power)) = ( type_power(kind, width), - self.expr_power(parser, *expr, meta)?, + self.expr_power(frontend, *expr, meta)?, ) { if tgt_power > expr_power { self.conversion(expr, meta, kind, width)?; @@ -1471,14 +1478,14 @@ impl Context { pub fn forced_conversion( &mut self, - parser: &Parser, + frontend: &Frontend, expr: &mut Handle, meta: Span, kind: ScalarKind, width: crate::Bytes, ) -> Result<()> { if let Some((expr_scalar_kind, expr_width)) = - self.expr_scalar_components(parser, *expr, meta)? + self.expr_scalar_components(frontend, *expr, meta)? { if expr_scalar_kind != kind || expr_width != width { self.conversion(expr, meta, kind, width)?; @@ -1490,14 +1497,14 @@ impl Context { pub fn binary_implicit_conversion( &mut self, - parser: &Parser, + frontend: &Frontend, left: &mut Handle, left_meta: Span, right: &mut Handle, right_meta: Span, ) -> Result<()> { - let left_components = self.expr_scalar_components(parser, *left, left_meta)?; - let right_components = self.expr_scalar_components(parser, *right, right_meta)?; + let left_components = self.expr_scalar_components(frontend, *left, left_meta)?; + let right_components = self.expr_scalar_components(frontend, *right, right_meta)?; if let ( Some((left_power, left_width, left_kind)), @@ -1523,12 +1530,12 @@ impl Context { pub fn implicit_splat( &mut self, - parser: &Parser, + frontend: &Frontend, expr: &mut Handle, meta: Span, vector_size: Option, ) -> Result<()> { - let expr_type = parser.resolve_type(self, *expr, meta)?; + let expr_type = frontend.resolve_type(self, *expr, meta)?; if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { *expr = self diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 806008e5b..3718fc7ab 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -4,7 +4,7 @@ use super::{ context::{Context, ExprPos, StmtContext}, error::{Error, ErrorKind}, types::scalar_components, - Parser, Result, + Frontend, Result, }; use crate::{ front::glsl::types::type_power, proc::ensure_block_returns, AddressSpace, Arena, Block, @@ -14,7 +14,7 @@ use crate::{ }; use std::iter; -impl Parser { +impl Frontend { fn add_constant_value( &mut self, scalar_kind: ScalarKind, @@ -1032,7 +1032,7 @@ impl Parser { let void = result.is_none(); - let &mut Parser { + let &mut Frontend { ref mut lookup_function, ref mut module, .. @@ -1121,7 +1121,7 @@ impl Parser { ) { let void = result.is_none(); - let &mut Parser { + let &mut Frontend { ref mut lookup_function, ref mut module, .. diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 0e0b503d3..b799293e5 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,7 +1,7 @@ /*! Frontend for [GLSL][glsl] (OpenGL Shading Language). -To begin, take a look at the documentation for the [`Parser`](Parser). +To begin, take a look at the documentation for the [`Frontend`]. # Supported versions ## Vulkan @@ -37,7 +37,7 @@ mod variables; type Result = std::result::Result; -/// Per-shader options passed to [`parse`](Parser::parse). +/// Per-shader options passed to [`parse`](Frontend::parse). /// /// The [`From`](From) trait is implemented for [`ShaderStage`](ShaderStage) to /// provide a quick way to create a Options instance. @@ -79,7 +79,7 @@ pub struct ShaderMetadata { /// The GLSL profile specified in the shader trough the use of the /// `#version` preprocessor directive. pub profile: Profile, - /// The shader stage in the pipeline, passed to the [`parse`](Parser::parse) + /// The shader stage in the pipeline, passed to the [`parse`](Frontend::parse) /// method via the [`Options`](Options) struct. pub stage: ShaderStage, @@ -124,16 +124,16 @@ impl Default for ShaderMetadata { } } -/// The `Parser` is the central structure of the GLSL frontend. +/// The `Frontend` is the central structure of the GLSL frontend. /// -/// To instantiate a new `Parser` the [`Default`](Default) trait is used, so a -/// call to the associated function [`Parser::default`](Parser::default) will -/// return a new `Parser` instance. +/// To instantiate a new `Frontend` the [`Default`](Default) trait is used, so a +/// call to the associated function [`Frontend::default`](Frontend::default) will +/// return a new `Frontend` instance. /// -/// To parse a shader simply call the [`parse`](Parser::parse) method with a +/// To parse a shader simply call the [`parse`](Frontend::parse) method with a /// [`Options`](Options) struct and a [`&str`](str) holding the glsl code. /// -/// The `Parser` also provides the [`metadata`](Parser::metadata) to get some +/// The `Frontend` also provides the [`metadata`](Frontend::metadata) to get some /// further information about the previously parsed shader, like version and /// extensions used (see the documentation for /// [`ShaderMetadata`](ShaderMetadata) to see all the returned information) @@ -141,7 +141,7 @@ impl Default for ShaderMetadata { /// # Example usage /// ```rust /// use naga::ShaderStage; -/// use naga::front::glsl::{Parser, Options}; +/// use naga::front::glsl::{Frontend, Options}; /// /// let glsl = r#" /// #version 450 core @@ -149,20 +149,20 @@ impl Default for ShaderMetadata { /// void main() {} /// "#; /// -/// let mut parser = Parser::default(); +/// let mut frontend = Frontend::default(); /// let options = Options::from(ShaderStage::Vertex); -/// parser.parse(&options, glsl); +/// frontend.parse(&options, glsl); /// ``` /// /// # Reusability /// -/// If there's a need to parse more than one shader reusing the same `Parser` +/// If there's a need to parse more than one shader reusing the same `Frontend` /// instance may be beneficial since internal allocations will be reused. /// -/// Calling the [`parse`](Parser::parse) method multiple times will reset the -/// `Parser` so no extra care is needed when reusing. +/// Calling the [`parse`](Frontend::parse) method multiple times will reset the +/// `Frontend` so no extra care is needed when reusing. #[derive(Debug, Default)] -pub struct Parser { +pub struct Frontend { meta: ShaderMetadata, lookup_function: FastHashMap, @@ -179,7 +179,7 @@ pub struct Parser { module: Module, } -impl Parser { +impl Frontend { fn reset(&mut self, stage: ShaderStage) { self.meta.reset(stage); @@ -197,7 +197,7 @@ impl Parser { /// Parses a shader either outputting a shader [`Module`](Module) or a list /// of [`Error`](Error)s. /// - /// Multiple calls using the same `Parser` and different shaders are supported. + /// Multiple calls using the same `Frontend` and different shaders are supported. pub fn parse( &mut self, options: &Options, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2705fd904..ebcfc2fec 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -7,7 +7,7 @@ use super::{ token::{Directive, DirectiveKind}, token::{Token, TokenValue}, variables::{GlobalOrConstant, VarDeclaration}, - Parser, Result, + Frontend, Result, }; use crate::{arena::Handle, Block, Constant, ConstantInner, Expression, ScalarValue, Span, Type}; use core::convert::TryFrom; @@ -56,8 +56,8 @@ impl<'source> ParsingContext<'source> { Ok(()) } - pub fn expect_ident(&mut self, parser: &mut Parser) -> Result<(String, Span)> { - let token = self.bump(parser)?; + pub fn expect_ident(&mut self, frontend: &mut Frontend) -> Result<(String, Span)> { + let token = self.bump(frontend)?; match token.value { TokenValue::Identifier(name) => Ok((name, token.meta)), @@ -68,8 +68,8 @@ impl<'source> ParsingContext<'source> { } } - pub fn expect(&mut self, parser: &mut Parser, value: TokenValue) -> Result { - let token = self.bump(parser)?; + pub fn expect(&mut self, frontend: &mut Frontend, value: TokenValue) -> Result { + let token = self.bump(frontend)?; if token.value != value { Err(Error { @@ -81,7 +81,7 @@ impl<'source> ParsingContext<'source> { } } - pub fn next(&mut self, parser: &mut Parser) -> Option { + pub fn next(&mut self, frontend: &mut Frontend) -> Option { loop { if let Some(token) = self.backtracked_token.take() { self.last_meta = token.meta; @@ -96,9 +96,9 @@ impl<'source> ParsingContext<'source> { break Some(token); } LexerResultKind::Directive(directive) => { - parser.handle_directive(directive, res.meta) + frontend.handle_directive(directive, res.meta) } - LexerResultKind::Error(error) => parser.errors.push(Error { + LexerResultKind::Error(error) => frontend.errors.push(Error { kind: ErrorKind::PreprocessorError(error), meta: res.meta, }), @@ -106,23 +106,23 @@ impl<'source> ParsingContext<'source> { } } - pub fn bump(&mut self, parser: &mut Parser) -> Result { - self.next(parser).ok_or(Error { + pub fn bump(&mut self, frontend: &mut Frontend) -> Result { + self.next(frontend).ok_or(Error { kind: ErrorKind::EndOfFile, meta: self.last_meta, }) } /// Returns None on the end of the file rather than an error like other methods - pub fn bump_if(&mut self, parser: &mut Parser, value: TokenValue) -> Option { - if self.peek(parser).filter(|t| t.value == value).is_some() { - self.bump(parser).ok() + pub fn bump_if(&mut self, frontend: &mut Frontend, value: TokenValue) -> Option { + if self.peek(frontend).filter(|t| t.value == value).is_some() { + self.bump(frontend).ok() } else { None } } - pub fn peek(&mut self, parser: &mut Parser) -> Option<&Token> { + pub fn peek(&mut self, frontend: &mut Frontend) -> Option<&Token> { loop { if let Some(ref token) = self.backtracked_token { break Some(token); @@ -142,9 +142,9 @@ impl<'source> ParsingContext<'source> { match res.kind { LexerResultKind::Directive(directive) => { - parser.handle_directive(directive, res.meta) + frontend.handle_directive(directive, res.meta) } - LexerResultKind::Error(error) => parser.errors.push(Error { + LexerResultKind::Error(error) => frontend.errors.push(Error { kind: ErrorKind::PreprocessorError(error), meta: res.meta, }), @@ -155,30 +155,30 @@ impl<'source> ParsingContext<'source> { } } - pub fn expect_peek(&mut self, parser: &mut Parser) -> Result<&Token> { + pub fn expect_peek(&mut self, frontend: &mut Frontend) -> Result<&Token> { let meta = self.last_meta; - self.peek(parser).ok_or(Error { + self.peek(frontend).ok_or(Error { kind: ErrorKind::EndOfFile, meta, }) } - pub fn parse(&mut self, parser: &mut Parser) -> Result<()> { + pub fn parse(&mut self, frontend: &mut Frontend) -> Result<()> { // Body and expression arena for global initialization let mut body = Block::new(); - let mut ctx = Context::new(parser, &mut body); + let mut ctx = Context::new(frontend, &mut body); - while self.peek(parser).is_some() { - self.parse_external_declaration(parser, &mut ctx, &mut body)?; + while self.peek(frontend).is_some() { + self.parse_external_declaration(frontend, &mut ctx, &mut body)?; } // Add an `EntryPoint` to `parser.module` for `main`, if a // suitable overload exists. Error out if we can't find one. - if let Some(declaration) = parser.lookup_function.get("main") { + if let Some(declaration) = frontend.lookup_function.get("main") { for decl in declaration.overloads.iter() { if let FunctionKind::Call(handle) = decl.kind { if decl.defined && decl.parameters.is_empty() { - parser.add_entry_point(handle, body, ctx.expressions); + frontend.add_entry_point(handle, body, ctx.expressions); return Ok(()); } } @@ -191,10 +191,10 @@ impl<'source> ParsingContext<'source> { }) } - fn parse_uint_constant(&mut self, parser: &mut Parser) -> Result<(u32, Span)> { - let (value, meta) = self.parse_constant_expression(parser)?; + fn parse_uint_constant(&mut self, frontend: &mut Frontend) -> Result<(u32, Span)> { + let (value, meta) = self.parse_constant_expression(frontend)?; - let int = match parser.module.constants[value].inner { + let int = match frontend.module.constants[value].inner { ConstantInner::Scalar { value: ScalarValue::Uint(int), .. @@ -222,21 +222,21 @@ impl<'source> ParsingContext<'source> { fn parse_constant_expression( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ) -> Result<(Handle, Span)> { let mut block = Block::new(); - let mut ctx = Context::new(parser, &mut block); + let mut ctx = Context::new(frontend, &mut block); let mut stmt_ctx = ctx.stmt_ctx(); - let expr = self.parse_conditional(parser, &mut ctx, &mut stmt_ctx, &mut block, None)?; - let (root, meta) = ctx.lower_expect(stmt_ctx, parser, expr, ExprPos::Rhs, &mut block)?; + let expr = self.parse_conditional(frontend, &mut ctx, &mut stmt_ctx, &mut block, None)?; + let (root, meta) = ctx.lower_expect(stmt_ctx, frontend, expr, ExprPos::Rhs, &mut block)?; - Ok((parser.solve_constant(&ctx, root, meta)?, meta)) + Ok((frontend.solve_constant(&ctx, root, meta)?, meta)) } } -impl Parser { +impl Frontend { fn handle_directive(&mut self, directive: Directive, meta: Span) { let mut tokens = directive.tokens.into_iter(); @@ -409,7 +409,7 @@ pub struct DeclarationContext<'ctx, 'qualifiers> { impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { fn add_var( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ty: Handle, name: String, init: Option>, @@ -425,14 +425,14 @@ impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { match self.external { true => { - let global = parser.add_global_var(self.ctx, self.body, decl)?; + let global = frontend.add_global_var(self.ctx, self.body, decl)?; let expr = match global { GlobalOrConstant::Global(handle) => Expression::GlobalVariable(handle), GlobalOrConstant::Constant(handle) => Expression::Constant(handle), }; Ok(self.ctx.add_expression(expr, meta, self.body)) } - false => parser.add_local_var(self.ctx, self.body, decl), + false => frontend.add_local_var(self.ctx, self.body, decl), } } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index fe1c66e8f..3ae22559a 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -10,7 +10,7 @@ use crate::{ token::{Token, TokenValue}, types::scalar_components, variables::{GlobalOrConstant, VarDeclaration}, - Error, ErrorKind, Parser, Span, + Error, ErrorKind, Frontend, Span, }, proc::Alignment, AddressSpace, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StructMember, @@ -71,19 +71,19 @@ fn element_or_member_type( impl<'source> ParsingContext<'source> { pub fn parse_external_declaration( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, global_ctx: &mut Context, global_body: &mut Block, ) -> Result<()> { if self - .parse_declaration(parser, global_ctx, global_body, true)? + .parse_declaration(frontend, global_ctx, global_body, true)? .is_none() { - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { - TokenValue::Semicolon if parser.meta.version == 460 => Ok(()), + TokenValue::Semicolon if frontend.meta.version == 460 => Ok(()), _ => { - let expected = match parser.meta.version { + let expected = match frontend.meta.version { 460 => vec![TokenValue::Semicolon.into(), ExpectedToken::Eof], _ => vec![ExpectedToken::Eof], }; @@ -100,7 +100,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_initializer( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ty: Handle, ctx: &mut Context, body: &mut Block, @@ -113,20 +113,21 @@ impl<'source> ParsingContext<'source> { // initializer_list: // initializer // initializer_list COMMA initializer - if let Some(Token { mut meta, .. }) = self.bump_if(parser, TokenValue::LeftBrace) { + if let Some(Token { mut meta, .. }) = self.bump_if(frontend, TokenValue::LeftBrace) { // initializer_list let mut components = Vec::new(); loop { // The type expected to be parsed inside the initializer list - let new_ty = element_or_member_type(ty, components.len(), &mut parser.module.types); + let new_ty = + element_or_member_type(ty, components.len(), &mut frontend.module.types); - components.push(self.parse_initializer(parser, new_ty, ctx, body)?.0); + components.push(self.parse_initializer(frontend, new_ty, ctx, body)?.0); - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { TokenValue::Comma => { if let Some(Token { meta: end_meta, .. }) = - self.bump_if(parser, TokenValue::RightBrace) + self.bump_if(frontend, TokenValue::RightBrace) { meta.subsume(end_meta); break; @@ -154,12 +155,13 @@ impl<'source> ParsingContext<'source> { )) } else { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_assignment(parser, ctx, &mut stmt, body)?; - let (mut init, init_meta) = ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; + let expr = self.parse_assignment(frontend, ctx, &mut stmt, body)?; + let (mut init, init_meta) = + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; - let scalar_components = scalar_components(&parser.module.types[ty].inner); + let scalar_components = scalar_components(&frontend.module.types[ty].inner); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(parser, &mut init, init_meta, kind, width)?; + ctx.implicit_conversion(frontend, &mut init, init_meta, kind, width)?; } Ok((init, init_meta)) @@ -171,7 +173,7 @@ impl<'source> ParsingContext<'source> { // produced Error::InvalidToken if it isn't consumed pub fn parse_init_declarator_list( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, mut ty: Handle, ctx: &mut DeclarationContext, ) -> Result<()> { @@ -191,14 +193,14 @@ impl<'source> ParsingContext<'source> { // Consume any leading comma, e.g. this is valid: `float, a=1;` if self - .peek(parser) + .peek(frontend) .map_or(false, |t| t.value == TokenValue::Comma) { - self.next(parser); + self.next(frontend); } loop { - let token = self.bump(parser)?; + let token = self.bump(frontend)?; let name = match token.value { TokenValue::Semicolon => break, TokenValue::Identifier(name) => name, @@ -221,18 +223,18 @@ impl<'source> ParsingContext<'source> { // parse an array specifier if it exists // NOTE: unlike other parse methods this one doesn't expect an array specifier and // returns Ok(None) rather than an error if there is not one - self.parse_array_specifier(parser, &mut meta, &mut ty)?; + self.parse_array_specifier(frontend, &mut meta, &mut ty)?; let init = self - .bump_if(parser, TokenValue::Assign) + .bump_if(frontend, TokenValue::Assign) .map::, _>(|_| { let (mut expr, init_meta) = - self.parse_initializer(parser, ty, ctx.ctx, ctx.body)?; + self.parse_initializer(frontend, ty, ctx.ctx, ctx.body)?; - let scalar_components = scalar_components(&parser.module.types[ty].inner); + let scalar_components = scalar_components(&frontend.module.types[ty].inner); if let Some((kind, width)) = scalar_components { ctx.ctx - .implicit_conversion(parser, &mut expr, init_meta, kind, width)?; + .implicit_conversion(frontend, &mut expr, init_meta, kind, width)?; } meta.subsume(init_meta); @@ -244,7 +246,7 @@ impl<'source> ParsingContext<'source> { let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; let maybe_constant = if ctx.external { if let Some((root, meta)) = init { - match parser.solve_constant(ctx.ctx, root, meta) { + match frontend.solve_constant(ctx.ctx, root, meta) { Ok(res) => Some(res), // If the declaration is external (global scope) and is constant qualified // then the initializer must be a constant expression @@ -258,14 +260,14 @@ impl<'source> ParsingContext<'source> { None }; - let pointer = ctx.add_var(parser, ty, name, maybe_constant, meta)?; + let pointer = ctx.add_var(frontend, ty, name, maybe_constant, meta)?; if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) { ctx.flush_expressions(); ctx.body.push(Statement::Store { pointer, value }, meta); } - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { TokenValue::Semicolon => break, TokenValue::Comma => {} @@ -287,7 +289,7 @@ impl<'source> ParsingContext<'source> { /// `external` whether or not we are in a global or local context pub fn parse_declaration( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, external: bool, @@ -304,36 +306,36 @@ impl<'source> ParsingContext<'source> { // type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON - if self.peek_type_qualifier(parser) || self.peek_type_name(parser) { - let mut qualifiers = self.parse_type_qualifiers(parser)?; + if self.peek_type_qualifier(frontend) || self.peek_type_name(frontend) { + let mut qualifiers = self.parse_type_qualifiers(frontend)?; - if self.peek_type_name(parser) { + if self.peek_type_name(frontend) { // This branch handles variables and function prototypes and if // external is true also function definitions - let (ty, mut meta) = self.parse_type(parser)?; + let (ty, mut meta) = self.parse_type(frontend)?; - let token = self.bump(parser)?; + let token = self.bump(frontend)?; let token_fallthrough = match token.value { - TokenValue::Identifier(name) => match self.expect_peek(parser)?.value { + TokenValue::Identifier(name) => match self.expect_peek(frontend)?.value { TokenValue::LeftParen => { // This branch handles function definition and prototypes - self.bump(parser)?; + self.bump(frontend)?; let result = ty.map(|ty| FunctionResult { ty, binding: None }); let mut body = Block::new(); - let mut context = Context::new(parser, &mut body); + let mut context = Context::new(frontend, &mut body); - self.parse_function_args(parser, &mut context, &mut body)?; + self.parse_function_args(frontend, &mut context, &mut body)?; - let end_meta = self.expect(parser, TokenValue::RightParen)?.meta; + let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta; meta.subsume(end_meta); - let token = self.bump(parser)?; + let token = self.bump(frontend)?; return match token.value { TokenValue::Semicolon => { // This branch handles function prototypes - parser.add_prototype(context, name, result, meta); + frontend.add_prototype(context, name, result, meta); Ok(Some(meta)) } @@ -345,13 +347,13 @@ impl<'source> ParsingContext<'source> { // parse the body self.parse_compound_statement( token.meta, - parser, + frontend, &mut context, &mut body, &mut None, )?; - parser.add_function(context, name, result, body, meta); + frontend.add_function(context, name, result, body, meta); Ok(Some(meta)) } @@ -396,9 +398,9 @@ impl<'source> ParsingContext<'source> { }; self.backtrack(token_fallthrough)?; - self.parse_init_declarator_list(parser, ty, &mut ctx)?; + self.parse_init_declarator_list(frontend, ty, &mut ctx)?; } else { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError("Declaration cannot have void type".into()), meta, }) @@ -410,12 +412,12 @@ impl<'source> ParsingContext<'source> { // ```glsl // layout(early_fragment_tests); // ``` - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { TokenValue::Identifier(ty_name) => { - if self.bump_if(parser, TokenValue::LeftBrace).is_some() { + if self.bump_if(frontend, TokenValue::LeftBrace).is_some() { self.parse_block_declaration( - parser, + frontend, ctx, body, &mut qualifiers, @@ -425,10 +427,10 @@ impl<'source> ParsingContext<'source> { .map(Some) } else { if qualifiers.invariant.take().is_some() { - parser.make_variable_invariant(ctx, body, &ty_name, token.meta); + frontend.make_variable_invariant(ctx, body, &ty_name, token.meta); - qualifiers.unused_errors(&mut parser.errors); - self.expect(parser, TokenValue::Semicolon)?; + qualifiers.unused_errors(&mut frontend.errors); + self.expect(frontend, TokenValue::Semicolon)?; return Ok(Some(qualifiers.span)); } @@ -443,25 +445,25 @@ impl<'source> ParsingContext<'source> { } TokenValue::Semicolon => { if let Some(value) = - qualifiers.uint_layout_qualifier("local_size_x", &mut parser.errors) + qualifiers.uint_layout_qualifier("local_size_x", &mut frontend.errors) { - parser.meta.workgroup_size[0] = value; + frontend.meta.workgroup_size[0] = value; } if let Some(value) = - qualifiers.uint_layout_qualifier("local_size_y", &mut parser.errors) + qualifiers.uint_layout_qualifier("local_size_y", &mut frontend.errors) { - parser.meta.workgroup_size[1] = value; + frontend.meta.workgroup_size[1] = value; } if let Some(value) = - qualifiers.uint_layout_qualifier("local_size_z", &mut parser.errors) + qualifiers.uint_layout_qualifier("local_size_z", &mut frontend.errors) { - parser.meta.workgroup_size[2] = value; + frontend.meta.workgroup_size[2] = value; } - parser.meta.early_fragment_tests |= qualifiers - .none_layout_qualifier("early_fragment_tests", &mut parser.errors); + frontend.meta.early_fragment_tests |= qualifiers + .none_layout_qualifier("early_fragment_tests", &mut frontend.errors); - qualifiers.unused_errors(&mut parser.errors); + qualifiers.unused_errors(&mut frontend.errors); Ok(Some(qualifiers.span)) } @@ -475,12 +477,12 @@ impl<'source> ParsingContext<'source> { } } } else { - match self.peek(parser).map(|t| &t.value) { + match self.peek(frontend).map(|t| &t.value) { Some(&TokenValue::Precision) => { // PRECISION precision_qualifier type_specifier SEMICOLON - self.bump(parser)?; + self.bump(frontend)?; - let token = self.bump(parser)?; + let token = self.bump(frontend)?; let _ = match token.value { TokenValue::PrecisionQualifier(p) => p, _ => { @@ -498,14 +500,14 @@ impl<'source> ParsingContext<'source> { } }; - let (ty, meta) = self.parse_type_non_void(parser)?; + let (ty, meta) = self.parse_type_non_void(frontend)?; - match parser.module.types[ty].inner { + match frontend.module.types[ty].inner { TypeInner::Scalar { kind: ScalarKind::Float | ScalarKind::Sint, .. } => {} - _ => parser.errors.push(Error { + _ => frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Precision statement can only work on floats and ints".into(), ), @@ -513,7 +515,7 @@ impl<'source> ParsingContext<'source> { }), } - self.expect(parser, TokenValue::Semicolon)?; + self.expect(frontend, TokenValue::Semicolon)?; Ok(Some(meta)) } @@ -524,7 +526,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_block_declaration( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, qualifiers: &mut TypeQualifiers, @@ -546,10 +548,10 @@ impl<'source> ParsingContext<'source> { }; let mut members = Vec::new(); - let span = self.parse_struct_declaration_list(parser, &mut members, layout)?; - self.expect(parser, TokenValue::RightBrace)?; + let span = self.parse_struct_declaration_list(frontend, &mut members, layout)?; + self.expect(frontend, TokenValue::RightBrace)?; - let mut ty = parser.module.types.insert( + let mut ty = frontend.module.types.insert( Type { name: Some(ty_name), inner: TypeInner::Struct { @@ -560,13 +562,13 @@ impl<'source> ParsingContext<'source> { Default::default(), ); - let token = self.bump(parser)?; + let token = self.bump(frontend)?; let name = match token.value { TokenValue::Semicolon => None, TokenValue::Identifier(name) => { - self.parse_array_specifier(parser, &mut meta, &mut ty)?; + self.parse_array_specifier(frontend, &mut meta, &mut ty)?; - self.expect(parser, TokenValue::Semicolon)?; + self.expect(frontend, TokenValue::Semicolon)?; Some(name) } @@ -581,7 +583,7 @@ impl<'source> ParsingContext<'source> { } }; - let global = parser.add_global_var( + let global = frontend.add_global_var( ctx, body, VarDeclaration { @@ -605,9 +607,9 @@ impl<'source> ParsingContext<'source> { entry_arg: None, mutable: true, }; - ctx.add_global(parser, &k, lookup, body); + ctx.add_global(frontend, &k, lookup, body); - parser.global_variables.push((k, lookup)); + frontend.global_variables.push((k, lookup)); } Ok(meta) @@ -616,7 +618,7 @@ impl<'source> ParsingContext<'source> { // TODO: Accept layout arguments pub fn parse_struct_declaration_list( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, members: &mut Vec, layout: StructLayout, ) -> Result { @@ -626,22 +628,22 @@ impl<'source> ParsingContext<'source> { loop { // TODO: type_qualifier - let (mut ty, mut meta) = self.parse_type_non_void(parser)?; - let (name, end_meta) = self.expect_ident(parser)?; + let (mut ty, mut meta) = self.parse_type_non_void(frontend)?; + let (name, end_meta) = self.expect_ident(frontend)?; meta.subsume(end_meta); - self.parse_array_specifier(parser, &mut meta, &mut ty)?; + self.parse_array_specifier(frontend, &mut meta, &mut ty)?; - self.expect(parser, TokenValue::Semicolon)?; + self.expect(frontend, TokenValue::Semicolon)?; let info = offset::calculate_offset( ty, meta, layout, - &mut parser.module.types, - &parser.module.constants, - &mut parser.errors, + &mut frontend.module.types, + &frontend.module.constants, + &mut frontend.errors, ); let member_alignment = info.align; @@ -657,7 +659,7 @@ impl<'source> ParsingContext<'source> { span += info.span; - if let TokenValue::RightBrace = self.expect_peek(parser)?.value { + if let TokenValue::RightBrace = self.expect_peek(frontend)?.value { break; } } diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index ad9cf80a0..f09e58b6f 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -5,7 +5,7 @@ use crate::{ error::{ErrorKind, ExpectedToken}, parser::ParsingContext, token::{Token, TokenValue}, - Error, Parser, Result, Span, + Error, Frontend, Result, Span, }, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Handle, ScalarValue, Type, TypeInner, UnaryOperator, @@ -14,12 +14,12 @@ use crate::{ impl<'source> ParsingContext<'source> { pub fn parse_primary( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let mut token = self.bump(parser)?; + let mut token = self.bump(frontend)?; let (width, value) = match token.value { TokenValue::IntConstant(int) => ( @@ -36,8 +36,8 @@ impl<'source> ParsingContext<'source> { ), TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)), TokenValue::LeftParen => { - let expr = self.parse_expression(parser, ctx, stmt, body)?; - let meta = self.expect(parser, TokenValue::RightParen)?.meta; + let expr = self.parse_expression(frontend, ctx, stmt, body)?; + let meta = self.expect(frontend, TokenValue::RightParen)?.meta; token.meta.subsume(meta); @@ -59,7 +59,7 @@ impl<'source> ParsingContext<'source> { } }; - let handle = parser.module.constants.fetch_or_append( + let handle = frontend.module.constants.fetch_or_append( Constant { name: None, specialization: None, @@ -79,20 +79,20 @@ impl<'source> ParsingContext<'source> { pub fn parse_function_call_args( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, meta: &mut Span, ) -> Result>> { let mut args = Vec::new(); - if let Some(token) = self.bump_if(parser, TokenValue::RightParen) { + if let Some(token) = self.bump_if(frontend, TokenValue::RightParen) { meta.subsume(token.meta); } else { loop { - args.push(self.parse_assignment(parser, ctx, stmt, body)?); + args.push(self.parse_assignment(frontend, ctx, stmt, body)?); - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { TokenValue::Comma => {} TokenValue::RightParen => { @@ -117,26 +117,26 @@ impl<'source> ParsingContext<'source> { pub fn parse_postfix( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let mut base = if self.peek_type_name(parser) { - let (mut handle, mut meta) = self.parse_type_non_void(parser)?; + let mut base = if self.peek_type_name(frontend) { + let (mut handle, mut meta) = self.parse_type_non_void(frontend)?; - self.expect(parser, TokenValue::LeftParen)?; - let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; + self.expect(frontend, TokenValue::LeftParen)?; + let args = self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?; if let TypeInner::Array { size: ArraySize::Dynamic, stride, base, - } = parser.module.types[handle].inner + } = frontend.module.types[handle].inner { - let span = parser.module.types.get_span(handle); + let span = frontend.module.types.get_span(handle); - let constant = parser.module.constants.fetch_or_append( + let constant = frontend.module.constants.fetch_or_append( Constant { name: None, specialization: None, @@ -147,7 +147,7 @@ impl<'source> ParsingContext<'source> { }, Span::default(), ); - handle = parser.module.types.insert( + handle = frontend.module.types.insert( Type { name: None, inner: TypeInner::Array { @@ -170,13 +170,13 @@ impl<'source> ParsingContext<'source> { }, Default::default(), ) - } else if let TokenValue::Identifier(_) = self.expect_peek(parser)?.value { - let (name, mut meta) = self.expect_ident(parser)?; + } else if let TokenValue::Identifier(_) = self.expect_peek(frontend)?.value { + let (name, mut meta) = self.expect_ident(frontend)?; - let expr = if self.bump_if(parser, TokenValue::LeftParen).is_some() { - let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; + let expr = if self.bump_if(frontend, TokenValue::LeftParen).is_some() { + let args = self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?; - let kind = match parser.lookup_type.get(&name) { + let kind = match frontend.lookup_type.get(&name) { Some(ty) => FunctionCallKind::TypeConstructor(*ty), None => FunctionCallKind::Function(name), }; @@ -186,7 +186,7 @@ impl<'source> ParsingContext<'source> { meta, } } else { - let var = match parser.lookup_variable(ctx, body, &name, meta) { + let var = match frontend.lookup_variable(ctx, body, &name, meta) { Some(var) => var, None => { return Err(Error { @@ -204,20 +204,20 @@ impl<'source> ParsingContext<'source> { stmt.hir_exprs.append(expr, Default::default()) } else { - self.parse_primary(parser, ctx, stmt, body)? + self.parse_primary(frontend, ctx, stmt, body)? }; while let TokenValue::LeftBracket | TokenValue::Dot | TokenValue::Increment - | TokenValue::Decrement = self.expect_peek(parser)?.value + | TokenValue::Decrement = self.expect_peek(frontend)?.value { - let Token { value, mut meta } = self.bump(parser)?; + let Token { value, mut meta } = self.bump(frontend)?; match value { TokenValue::LeftBracket => { - let index = self.parse_expression(parser, ctx, stmt, body)?; - let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; + let index = self.parse_expression(frontend, ctx, stmt, body)?; + let end_meta = self.expect(frontend, TokenValue::RightBracket)?.meta; meta.subsume(end_meta); base = stmt.hir_exprs.append( @@ -229,11 +229,11 @@ impl<'source> ParsingContext<'source> { ) } TokenValue::Dot => { - let (field, end_meta) = self.expect_ident(parser)?; + let (field, end_meta) = self.expect_ident(frontend)?; - if self.bump_if(parser, TokenValue::LeftParen).is_some() { + if self.bump_if(frontend, TokenValue::LeftParen).is_some() { let args = - self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; + self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?; base = stmt.hir_exprs.append( HirExpr { @@ -283,16 +283,16 @@ impl<'source> ParsingContext<'source> { pub fn parse_unary( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - Ok(match self.expect_peek(parser)?.value { + Ok(match self.expect_peek(frontend)?.value { TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { - let Token { value, mut meta } = self.bump(parser)?; + let Token { value, mut meta } = self.bump(frontend)?; - let expr = self.parse_unary(parser, ctx, stmt, body)?; + let expr = self.parse_unary(frontend, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[expr].meta; let kind = match value { @@ -312,9 +312,9 @@ impl<'source> ParsingContext<'source> { .append(HirExpr { kind, meta }, Default::default()) } TokenValue::Increment | TokenValue::Decrement => { - let Token { value, meta } = self.bump(parser)?; + let Token { value, meta } = self.bump(frontend)?; - let expr = self.parse_unary(parser, ctx, stmt, body)?; + let expr = self.parse_unary(frontend, ctx, stmt, body)?; stmt.hir_exprs.append( HirExpr { @@ -331,32 +331,32 @@ impl<'source> ParsingContext<'source> { Default::default(), ) } - _ => self.parse_postfix(parser, ctx, stmt, body)?, + _ => self.parse_postfix(frontend, ctx, stmt, body)?, }) } pub fn parse_binary( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, - passtrough: Option>, + passthrough: Option>, min_bp: u8, ) -> Result> { - let mut left = passtrough + let mut left = passthrough .ok_or(ErrorKind::EndOfFile /* Dummy error */) - .or_else(|_| self.parse_unary(parser, ctx, stmt, body))?; + .or_else(|_| self.parse_unary(frontend, ctx, stmt, body))?; let mut meta = stmt.hir_exprs[left].meta; - while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(parser)?.value) { + while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(frontend)?.value) { if l_bp < min_bp { break; } - let Token { value, .. } = self.bump(parser)?; + let Token { value, .. } = self.bump(frontend)?; - let right = self.parse_binary(parser, ctx, stmt, body, None, r_bp)?; + let right = self.parse_binary(frontend, ctx, stmt, body, None, r_bp)?; let end_meta = stmt.hir_exprs[right].meta; meta.subsume(end_meta); @@ -399,19 +399,19 @@ impl<'source> ParsingContext<'source> { pub fn parse_conditional( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, - passtrough: Option>, + passthrough: Option>, ) -> Result> { - let mut condition = self.parse_binary(parser, ctx, stmt, body, passtrough, 0)?; + let mut condition = self.parse_binary(frontend, ctx, stmt, body, passthrough, 0)?; let mut meta = stmt.hir_exprs[condition].meta; - if self.bump_if(parser, TokenValue::Question).is_some() { - let accept = self.parse_expression(parser, ctx, stmt, body)?; - self.expect(parser, TokenValue::Colon)?; - let reject = self.parse_assignment(parser, ctx, stmt, body)?; + if self.bump_if(frontend, TokenValue::Question).is_some() { + let accept = self.parse_expression(frontend, ctx, stmt, body)?; + self.expect(frontend, TokenValue::Colon)?; + let reject = self.parse_assignment(frontend, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[reject].meta; meta.subsume(end_meta); @@ -433,18 +433,18 @@ impl<'source> ParsingContext<'source> { pub fn parse_assignment( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let tgt = self.parse_unary(parser, ctx, stmt, body)?; + let tgt = self.parse_unary(frontend, ctx, stmt, body)?; let mut meta = stmt.hir_exprs[tgt].meta; - Ok(match self.expect_peek(parser)?.value { + Ok(match self.expect_peek(frontend)?.value { TokenValue::Assign => { - self.bump(parser)?; - let value = self.parse_assignment(parser, ctx, stmt, body)?; + self.bump(frontend)?; + let value = self.parse_assignment(frontend, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[value].meta; meta.subsume(end_meta); @@ -466,8 +466,8 @@ impl<'source> ParsingContext<'source> { | TokenValue::LeftShiftAssign | TokenValue::RightShiftAssign | TokenValue::XorAssign => { - let token = self.bump(parser)?; - let right = self.parse_assignment(parser, ctx, stmt, body)?; + let token = self.bump(frontend)?; + let right = self.parse_assignment(frontend, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[right].meta; meta.subsume(end_meta); @@ -503,22 +503,22 @@ impl<'source> ParsingContext<'source> { Default::default(), ) } - _ => self.parse_conditional(parser, ctx, stmt, body, Some(tgt))?, + _ => self.parse_conditional(frontend, ctx, stmt, body, Some(tgt))?, }) } pub fn parse_expression( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let mut expr = self.parse_assignment(parser, ctx, stmt, body)?; + let mut expr = self.parse_assignment(frontend, ctx, stmt, body)?; - while let TokenValue::Comma = self.expect_peek(parser)?.value { - self.bump(parser)?; - expr = self.parse_assignment(parser, ctx, stmt, body)?; + while let TokenValue::Comma = self.expect_peek(frontend)?.value { + self.bump(frontend)?; + expr = self.parse_assignment(frontend, ctx, stmt, body)?; } Ok(expr) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 9ab3400eb..93988f82f 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -7,23 +7,23 @@ use crate::{ parser::ParsingContext, token::{Token, TokenValue}, variables::VarDeclaration, - Error, ErrorKind, Parser, Result, + Error, ErrorKind, Frontend, Result, }, Block, ConstantInner, Expression, ScalarValue, Statement, SwitchCase, UnaryOperator, }; impl<'source> ParsingContext<'source> { - pub fn peek_parameter_qualifier(&mut self, parser: &mut Parser) -> bool { - self.peek(parser).map_or(false, |t| match t.value { + pub fn peek_parameter_qualifier(&mut self, frontend: &mut Frontend) -> bool { + self.peek(frontend).map_or(false, |t| match t.value { TokenValue::In | TokenValue::Out | TokenValue::InOut | TokenValue::Const => true, _ => false, }) } /// Returns the parsed `ParameterQualifier` or `ParameterQualifier::In` - pub fn parse_parameter_qualifier(&mut self, parser: &mut Parser) -> ParameterQualifier { - if self.peek_parameter_qualifier(parser) { - match self.bump(parser).unwrap().value { + pub fn parse_parameter_qualifier(&mut self, frontend: &mut Frontend) -> ParameterQualifier { + if self.peek_parameter_qualifier(frontend) { + match self.bump(frontend).unwrap().value { TokenValue::In => ParameterQualifier::In, TokenValue::Out => ParameterQualifier::Out, TokenValue::InOut => ParameterQualifier::InOut, @@ -37,30 +37,30 @@ impl<'source> ParsingContext<'source> { pub fn parse_statement( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, terminator: &mut Option, ) -> Result> { // Type qualifiers always identify a declaration statement - if self.peek_type_qualifier(parser) { - return self.parse_declaration(parser, ctx, body, false); + if self.peek_type_qualifier(frontend) { + return self.parse_declaration(frontend, ctx, body, false); } // Type names can identify either declaration statements or type constructors // depending on wether the token following the type name is a `(` (LeftParen) - if self.peek_type_name(parser) { + if self.peek_type_name(frontend) { // Start by consuming the type name so that we can peek the token after it - let token = self.bump(parser)?; + let token = self.bump(frontend)?; // Peek the next token and check if it's a `(` (LeftParen) if so the statement // is a constructor, otherwise it's a declaration. We need to do the check // beforehand and not in the if since we will backtrack before the if - let declaration = TokenValue::LeftParen != self.expect_peek(parser)?.value; + let declaration = TokenValue::LeftParen != self.expect_peek(frontend)?.value; self.backtrack(token)?; if declaration { - return self.parse_declaration(parser, ctx, body, false); + return self.parse_declaration(frontend, ctx, body, false); } } @@ -73,32 +73,32 @@ impl<'source> ParsingContext<'source> { let &Token { ref value, mut meta, - } = self.expect_peek(parser)?; + } = self.expect_peek(frontend)?; let meta_rest = match *value { TokenValue::Continue => { - let meta = self.bump(parser)?.meta; + let meta = self.bump(frontend)?.meta; body.push(Statement::Continue, meta); terminator.get_or_insert(body.len()); - self.expect(parser, TokenValue::Semicolon)?.meta + self.expect(frontend, TokenValue::Semicolon)?.meta } TokenValue::Break => { - let meta = self.bump(parser)?.meta; + let meta = self.bump(frontend)?.meta; body.push(Statement::Break, meta); terminator.get_or_insert(body.len()); - self.expect(parser, TokenValue::Semicolon)?.meta + self.expect(frontend, TokenValue::Semicolon)?.meta } TokenValue::Return => { - self.bump(parser)?; - let (value, meta) = match self.expect_peek(parser)?.value { - TokenValue::Semicolon => (None, self.bump(parser)?.meta), + self.bump(frontend)?; + let (value, meta) = match self.expect_peek(frontend)?.value { + TokenValue::Semicolon => (None, self.bump(frontend)?.meta), _ => { // TODO: Implicit conversions let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - self.expect(parser, TokenValue::Semicolon)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + self.expect(frontend, TokenValue::Semicolon)?; let (handle, meta) = - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; (Some(handle), meta) } }; @@ -111,39 +111,39 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::Discard => { - let meta = self.bump(parser)?.meta; + let meta = self.bump(frontend)?.meta; body.push(Statement::Kill, meta); terminator.get_or_insert(body.len()); - self.expect(parser, TokenValue::Semicolon)?.meta + self.expect(frontend, TokenValue::Semicolon)?.meta } TokenValue::If => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; - self.expect(parser, TokenValue::LeftParen)?; + self.expect(frontend, TokenValue::LeftParen)?; let condition = { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; let (handle, more_meta) = - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; meta.subsume(more_meta); handle }; - self.expect(parser, TokenValue::RightParen)?; + self.expect(frontend, TokenValue::RightParen)?; ctx.emit_restart(body); let mut accept = Block::new(); if let Some(more_meta) = - self.parse_statement(parser, ctx, &mut accept, &mut None)? + self.parse_statement(frontend, ctx, &mut accept, &mut None)? { meta.subsume(more_meta) } let mut reject = Block::new(); - if self.bump_if(parser, TokenValue::Else).is_some() { + if self.bump_if(frontend, TokenValue::Else).is_some() { if let Some(more_meta) = - self.parse_statement(parser, ctx, &mut reject, &mut None)? + self.parse_statement(frontend, ctx, &mut reject, &mut None)? { meta.subsume(more_meta); } @@ -161,18 +161,19 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::Switch => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; let end_meta; - self.expect(parser, TokenValue::LeftParen)?; + self.expect(frontend, TokenValue::LeftParen)?; let selector = { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?.0 + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)? + .0 }; - self.expect(parser, TokenValue::RightParen)?; + self.expect(frontend, TokenValue::RightParen)?; ctx.emit_restart(body); @@ -180,19 +181,19 @@ impl<'source> ParsingContext<'source> { // Track if any default case is present in the switch statement. let mut default_present = false; - self.expect(parser, TokenValue::LeftBrace)?; + self.expect(frontend, TokenValue::LeftBrace)?; loop { - let value = match self.expect_peek(parser)?.value { + let value = match self.expect_peek(frontend)?.value { TokenValue::Case => { - self.bump(parser)?; + self.bump(frontend)?; let value = { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; let (root, meta) = - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; - let constant = parser.solve_constant(ctx, root, meta)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; + let constant = frontend.solve_constant(ctx, root, meta)?; - match parser.module.constants[constant].inner { + match frontend.module.constants[constant].inner { ConstantInner::Scalar { value: ScalarValue::Sint(int), .. @@ -202,7 +203,7 @@ impl<'source> ParsingContext<'source> { .. } => int as i32, _ => { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Case values can only be integers".into(), ), @@ -216,16 +217,16 @@ impl<'source> ParsingContext<'source> { crate::SwitchValue::Integer(value) } TokenValue::Default => { - self.bump(parser)?; + self.bump(frontend)?; default_present = true; crate::SwitchValue::Default } TokenValue::RightBrace => { - end_meta = self.bump(parser)?.meta; + end_meta = self.bump(frontend)?.meta; break; } _ => { - let Token { value, meta } = self.bump(parser)?; + let Token { value, meta } = self.bump(frontend)?; return Err(Error { kind: ErrorKind::InvalidToken( value, @@ -240,18 +241,23 @@ impl<'source> ParsingContext<'source> { } }; - self.expect(parser, TokenValue::Colon)?; + self.expect(frontend, TokenValue::Colon)?; let mut body = Block::new(); let mut case_terminator = None; loop { - match self.expect_peek(parser)?.value { + match self.expect_peek(frontend)?.value { TokenValue::Case | TokenValue::Default | TokenValue::RightBrace => { break } _ => { - self.parse_statement(parser, ctx, &mut body, &mut case_terminator)?; + self.parse_statement( + frontend, + ctx, + &mut body, + &mut case_terminator, + )?; } } } @@ -284,7 +290,7 @@ impl<'source> ParsingContext<'source> { // also be checked because `break`s count as statements but // they aren't added to the body) if case.body.is_empty() && case.fall_through { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "last case/default label must be followed by statements".into(), ), @@ -315,17 +321,17 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::While => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; let mut loop_body = Block::new(); let mut stmt = ctx.stmt_ctx(); - self.expect(parser, TokenValue::LeftParen)?; - let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; - meta.subsume(self.expect(parser, TokenValue::RightParen)?.meta); + self.expect(frontend, TokenValue::LeftParen)?; + let root = self.parse_expression(frontend, ctx, &mut stmt, &mut loop_body)?; + meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta); let (expr, expr_meta) = - ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?; + ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut loop_body)?; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -349,7 +355,7 @@ impl<'source> ParsingContext<'source> { meta.subsume(expr_meta); if let Some(body_meta) = - self.parse_statement(parser, ctx, &mut loop_body, &mut None)? + self.parse_statement(frontend, ctx, &mut loop_body, &mut None)? { meta.subsume(body_meta); } @@ -366,24 +372,24 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::Do => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; let mut loop_body = Block::new(); let mut terminator = None; - self.parse_statement(parser, ctx, &mut loop_body, &mut terminator)?; + self.parse_statement(frontend, ctx, &mut loop_body, &mut terminator)?; let mut stmt = ctx.stmt_ctx(); - self.expect(parser, TokenValue::While)?; - self.expect(parser, TokenValue::LeftParen)?; - let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; - let end_meta = self.expect(parser, TokenValue::RightParen)?.meta; + self.expect(frontend, TokenValue::While)?; + self.expect(frontend, TokenValue::LeftParen)?; + let root = self.parse_expression(frontend, ctx, &mut stmt, &mut loop_body)?; + let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta; meta.subsume(end_meta); let (expr, expr_meta) = - ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?; + ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut loop_body)?; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -420,58 +426,59 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::For => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; ctx.symbol_table.push_scope(); - self.expect(parser, TokenValue::LeftParen)?; + self.expect(frontend, TokenValue::LeftParen)?; - if self.bump_if(parser, TokenValue::Semicolon).is_none() { - if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { - self.parse_declaration(parser, ctx, body, false)?; + if self.bump_if(frontend, TokenValue::Semicolon).is_none() { + if self.peek_type_name(frontend) || self.peek_type_qualifier(frontend) { + self.parse_declaration(frontend, ctx, body, false)?; } else { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?; - self.expect(parser, TokenValue::Semicolon)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + ctx.lower(stmt, frontend, expr, ExprPos::Rhs, body)?; + self.expect(frontend, TokenValue::Semicolon)?; } } let (mut block, mut continuing) = (Block::new(), Block::new()); - if self.bump_if(parser, TokenValue::Semicolon).is_none() { - let (expr, expr_meta) = - if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { - let mut qualifiers = self.parse_type_qualifiers(parser)?; - let (ty, mut meta) = self.parse_type_non_void(parser)?; - let name = self.expect_ident(parser)?.0; + if self.bump_if(frontend, TokenValue::Semicolon).is_none() { + let (expr, expr_meta) = if self.peek_type_name(frontend) + || self.peek_type_qualifier(frontend) + { + let mut qualifiers = self.parse_type_qualifiers(frontend)?; + let (ty, mut meta) = self.parse_type_non_void(frontend)?; + let name = self.expect_ident(frontend)?.0; - self.expect(parser, TokenValue::Assign)?; + self.expect(frontend, TokenValue::Assign)?; - let (value, end_meta) = - self.parse_initializer(parser, ty, ctx, &mut block)?; - meta.subsume(end_meta); + let (value, end_meta) = + self.parse_initializer(frontend, ty, ctx, &mut block)?; + meta.subsume(end_meta); - let decl = VarDeclaration { - qualifiers: &mut qualifiers, - ty, - name: Some(name), - init: None, - meta, - }; - - let pointer = parser.add_local_var(ctx, &mut block, decl)?; - - ctx.emit_restart(&mut block); - - block.push(Statement::Store { pointer, value }, meta); - - (value, end_meta) - } else { - let mut stmt = ctx.stmt_ctx(); - let root = self.parse_expression(parser, ctx, &mut stmt, &mut block)?; - ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut block)? + let decl = VarDeclaration { + qualifiers: &mut qualifiers, + ty, + name: Some(name), + init: None, + meta, }; + let pointer = frontend.add_local_var(ctx, &mut block, decl)?; + + ctx.emit_restart(&mut block); + + block.push(Statement::Store { pointer, value }, meta); + + (value, end_meta) + } else { + let mut stmt = ctx.stmt_ctx(); + let root = self.parse_expression(frontend, ctx, &mut stmt, &mut block)?; + ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut block)? + }; + let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -492,22 +499,24 @@ impl<'source> ParsingContext<'source> { crate::Span::default(), ); - self.expect(parser, TokenValue::Semicolon)?; + self.expect(frontend, TokenValue::Semicolon)?; } - match self.expect_peek(parser)?.value { + match self.expect_peek(frontend)?.value { TokenValue::RightParen => {} _ => { let mut stmt = ctx.stmt_ctx(); let rest = - self.parse_expression(parser, ctx, &mut stmt, &mut continuing)?; - ctx.lower(stmt, parser, rest, ExprPos::Rhs, &mut continuing)?; + self.parse_expression(frontend, ctx, &mut stmt, &mut continuing)?; + ctx.lower(stmt, frontend, rest, ExprPos::Rhs, &mut continuing)?; } } - meta.subsume(self.expect(parser, TokenValue::RightParen)?.meta); + meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta); - if let Some(stmt_meta) = self.parse_statement(parser, ctx, &mut block, &mut None)? { + if let Some(stmt_meta) = + self.parse_statement(frontend, ctx, &mut block, &mut None)? + { meta.subsume(stmt_meta); } @@ -525,14 +534,14 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::LeftBrace => { - let meta = self.bump(parser)?.meta; + let meta = self.bump(frontend)?.meta; let mut block = Block::new(); let mut block_terminator = None; let meta = self.parse_compound_statement( meta, - parser, + frontend, ctx, &mut block, &mut block_terminator, @@ -545,15 +554,15 @@ impl<'source> ParsingContext<'source> { meta } - TokenValue::Semicolon => self.bump(parser)?.meta, + TokenValue::Semicolon => self.bump(frontend)?.meta, _ => { // Attempt to force expression parsing for remainder of the // tokens. Unknown or invalid tokens will be caught there and // turned into an error. let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?; - self.expect(parser, TokenValue::Semicolon)?.meta + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + ctx.lower(stmt, frontend, expr, ExprPos::Rhs, body)?; + self.expect(frontend, TokenValue::Semicolon)?.meta } }; @@ -564,7 +573,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_compound_statement( &mut self, mut meta: Span, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, terminator: &mut Option, @@ -574,13 +583,13 @@ impl<'source> ParsingContext<'source> { loop { if let Some(Token { meta: brace_meta, .. - }) = self.bump_if(parser, TokenValue::RightBrace) + }) = self.bump_if(frontend, TokenValue::RightBrace) { meta.subsume(brace_meta); break; } - let stmt = self.parse_statement(parser, ctx, body, terminator)?; + let stmt = self.parse_statement(frontend, ctx, body, terminator)?; if let Some(stmt_meta) = stmt { meta.subsume(stmt_meta); @@ -598,32 +607,32 @@ impl<'source> ParsingContext<'source> { pub fn parse_function_args( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, context: &mut Context, body: &mut Block, ) -> Result<()> { - if self.bump_if(parser, TokenValue::Void).is_some() { + if self.bump_if(frontend, TokenValue::Void).is_some() { return Ok(()); } loop { - if self.peek_type_name(parser) || self.peek_parameter_qualifier(parser) { - let qualifier = self.parse_parameter_qualifier(parser); - let mut ty = self.parse_type_non_void(parser)?.0; + if self.peek_type_name(frontend) || self.peek_parameter_qualifier(frontend) { + let qualifier = self.parse_parameter_qualifier(frontend); + let mut ty = self.parse_type_non_void(frontend)?.0; - match self.expect_peek(parser)?.value { + match self.expect_peek(frontend)?.value { TokenValue::Comma => { - self.bump(parser)?; - context.add_function_arg(parser, body, None, ty, qualifier); + self.bump(frontend)?; + context.add_function_arg(frontend, body, None, ty, qualifier); continue; } TokenValue::Identifier(_) => { - let mut name = self.expect_ident(parser)?; - self.parse_array_specifier(parser, &mut name.1, &mut ty)?; + let mut name = self.expect_ident(frontend)?; + self.parse_array_specifier(frontend, &mut name.1, &mut ty)?; - context.add_function_arg(parser, body, Some(name), ty, qualifier); + context.add_function_arg(frontend, body, Some(name), ty, qualifier); - if self.bump_if(parser, TokenValue::Comma).is_some() { + if self.bump_if(frontend, TokenValue::Comma).is_some() { continue; } diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 93396823e..08a70669a 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -4,7 +4,7 @@ use crate::{ error::ExpectedToken, parser::ParsingContext, token::{Token, TokenValue}, - Error, ErrorKind, Parser, Result, + Error, ErrorKind, Frontend, Result, }, AddressSpace, ArraySize, Handle, Span, Type, TypeInner, }; @@ -14,50 +14,51 @@ impl<'source> ParsingContext<'source> { /// and modifying the type handle if it exists pub fn parse_array_specifier( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, span: &mut Span, ty: &mut Handle, ) -> Result<()> { - while self.parse_array_specifier_single(parser, span, ty)? {} + while self.parse_array_specifier_single(frontend, span, ty)? {} Ok(()) } /// Implementation of [`Self::parse_array_specifier`] for a single array_specifier fn parse_array_specifier_single( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, span: &mut Span, ty: &mut Handle, ) -> Result { - if self.bump_if(parser, TokenValue::LeftBracket).is_some() { - let size = - if let Some(Token { meta, .. }) = self.bump_if(parser, TokenValue::RightBracket) { - span.subsume(meta); - ArraySize::Dynamic - } else { - let (value, constant_span) = self.parse_uint_constant(parser)?; - let constant = parser.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(value as u64), - }, + if self.bump_if(frontend, TokenValue::LeftBracket).is_some() { + let size = if let Some(Token { meta, .. }) = + self.bump_if(frontend, TokenValue::RightBracket) + { + span.subsume(meta); + ArraySize::Dynamic + } else { + let (value, constant_span) = self.parse_uint_constant(frontend)?; + let constant = frontend.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(value as u64), }, - constant_span, - ); - let end_span = self.expect(parser, TokenValue::RightBracket)?.meta; - span.subsume(end_span); - ArraySize::Constant(constant) - }; + }, + constant_span, + ); + let end_span = self.expect(frontend, TokenValue::RightBracket)?.meta; + span.subsume(end_span); + ArraySize::Constant(constant) + }; - parser + frontend .layouter - .update(&parser.module.types, &parser.module.constants) + .update(&frontend.module.types, &frontend.module.constants) .unwrap(); - let stride = parser.layouter[*ty].to_stride(); - *ty = parser.module.types.insert( + let stride = frontend.layouter[*ty].to_stride(); + *ty = frontend.module.types.insert( Type { name: None, inner: TypeInner::Array { @@ -75,31 +76,34 @@ impl<'source> ParsingContext<'source> { } } - pub fn parse_type(&mut self, parser: &mut Parser) -> Result<(Option>, Span)> { - let token = self.bump(parser)?; + pub fn parse_type(&mut self, frontend: &mut Frontend) -> Result<(Option>, Span)> { + let token = self.bump(frontend)?; let mut handle = match token.value { TokenValue::Void => return Ok((None, token.meta)), - TokenValue::TypeName(ty) => parser.module.types.insert(ty, token.meta), + TokenValue::TypeName(ty) => frontend.module.types.insert(ty, token.meta), TokenValue::Struct => { let mut meta = token.meta; - let ty_name = self.expect_ident(parser)?.0; - self.expect(parser, TokenValue::LeftBrace)?; + let ty_name = self.expect_ident(frontend)?.0; + self.expect(frontend, TokenValue::LeftBrace)?; let mut members = Vec::new(); - let span = - self.parse_struct_declaration_list(parser, &mut members, StructLayout::Std140)?; - let end_meta = self.expect(parser, TokenValue::RightBrace)?.meta; + let span = self.parse_struct_declaration_list( + frontend, + &mut members, + StructLayout::Std140, + )?; + let end_meta = self.expect(frontend, TokenValue::RightBrace)?.meta; meta.subsume(end_meta); - let ty = parser.module.types.insert( + let ty = frontend.module.types.insert( Type { name: Some(ty_name.clone()), inner: TypeInner::Struct { members, span }, }, meta, ); - parser.lookup_type.insert(ty_name, ty); + frontend.lookup_type.insert(ty_name, ty); ty } - TokenValue::Identifier(ident) => match parser.lookup_type.get(&ident) { + TokenValue::Identifier(ident) => match frontend.lookup_type.get(&ident) { Some(ty) => *ty, None => { return Err(Error { @@ -124,12 +128,12 @@ impl<'source> ParsingContext<'source> { }; let mut span = token.meta; - self.parse_array_specifier(parser, &mut span, &mut handle)?; + self.parse_array_specifier(frontend, &mut span, &mut handle)?; Ok((Some(handle), span)) } - pub fn parse_type_non_void(&mut self, parser: &mut Parser) -> Result<(Handle, Span)> { - let (maybe_ty, meta) = self.parse_type(parser)?; + pub fn parse_type_non_void(&mut self, frontend: &mut Frontend) -> Result<(Handle, Span)> { + let (maybe_ty, meta) = self.parse_type(frontend)?; let ty = maybe_ty.ok_or_else(|| Error { kind: ErrorKind::SemanticError("Type can't be void".into()), meta, @@ -138,8 +142,8 @@ impl<'source> ParsingContext<'source> { Ok((ty, meta)) } - pub fn peek_type_qualifier(&mut self, parser: &mut Parser) -> bool { - self.peek(parser).map_or(false, |t| match t.value { + pub fn peek_type_qualifier(&mut self, frontend: &mut Frontend) -> bool { + self.peek(frontend).map_or(false, |t| match t.value { TokenValue::Invariant | TokenValue::Interpolation(_) | TokenValue::Sampling(_) @@ -157,15 +161,18 @@ impl<'source> ParsingContext<'source> { }) } - pub fn parse_type_qualifiers<'a>(&mut self, parser: &mut Parser) -> Result> { + pub fn parse_type_qualifiers<'a>( + &mut self, + frontend: &mut Frontend, + ) -> Result> { let mut qualifiers = TypeQualifiers::default(); - while self.peek_type_qualifier(parser) { - let token = self.bump(parser)?; + while self.peek_type_qualifier(frontend) { + let token = self.bump(frontend)?; // Handle layout qualifiers outside the match since this can push multiple values if token.value == TokenValue::Layout { - self.parse_layout_qualifier_id_list(parser, &mut qualifiers)?; + self.parse_layout_qualifier_id_list(frontend, &mut qualifiers)?; continue; } @@ -174,7 +181,7 @@ impl<'source> ParsingContext<'source> { match token.value { TokenValue::Invariant => { if qualifiers.invariant.is_some() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one invariant qualifier per declaration" .into(), @@ -187,7 +194,7 @@ impl<'source> ParsingContext<'source> { } TokenValue::Interpolation(i) => { if qualifiers.interpolation.is_some() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one interpolation qualifier per declaration" .into(), @@ -225,7 +232,7 @@ impl<'source> ParsingContext<'source> { if StorageQualifier::AddressSpace(AddressSpace::Function) != qualifiers.storage.0 { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one storage qualifier per declaration".into(), ), @@ -237,7 +244,7 @@ impl<'source> ParsingContext<'source> { } TokenValue::Sampling(s) => { if qualifiers.sampling.is_some() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one sampling qualifier per declaration" .into(), @@ -250,7 +257,7 @@ impl<'source> ParsingContext<'source> { } TokenValue::PrecisionQualifier(p) => { if qualifiers.precision.is_some() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one precision qualifier per declaration" .into(), @@ -266,7 +273,7 @@ impl<'source> ParsingContext<'source> { .storage_access .get_or_insert((crate::StorageAccess::all(), Span::default())); if !storage_access.0.contains(!access) { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "The same memory qualifier can only be used once".into(), ), @@ -287,20 +294,20 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id_list( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, qualifiers: &mut TypeQualifiers, ) -> Result<()> { - self.expect(parser, TokenValue::LeftParen)?; + self.expect(frontend, TokenValue::LeftParen)?; loop { - self.parse_layout_qualifier_id(parser, &mut qualifiers.layout_qualifiers)?; + self.parse_layout_qualifier_id(frontend, &mut qualifiers.layout_qualifiers)?; - if self.bump_if(parser, TokenValue::Comma).is_some() { + if self.bump_if(frontend, TokenValue::Comma).is_some() { continue; } break; } - let token = self.expect(parser, TokenValue::RightParen)?; + let token = self.expect(frontend, TokenValue::RightParen)?; qualifiers.span.subsume(token.meta); Ok(()) @@ -308,14 +315,14 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, qualifiers: &mut crate::FastHashMap, ) -> Result<()> { // layout_qualifier_id: // IDENTIFIER // IDENTIFIER EQUAL constant_expression // SHARED - let mut token = self.bump(parser)?; + let mut token = self.bump(frontend)?; match token.value { TokenValue::Identifier(name) => { let (key, value) = match name.as_str() { @@ -332,11 +339,11 @@ impl<'source> ParsingContext<'source> { (QualifierKey::Format, QualifierValue::Format(format)) } else { let key = QualifierKey::String(name.into()); - let value = if self.bump_if(parser, TokenValue::Assign).is_some() { - let (value, end_meta) = match self.parse_uint_constant(parser) { + let value = if self.bump_if(frontend, TokenValue::Assign).is_some() { + let (value, end_meta) = match self.parse_uint_constant(frontend) { Ok(v) => v, Err(e) => { - parser.errors.push(e); + frontend.errors.push(e); (0, Span::default()) } }; @@ -354,7 +361,7 @@ impl<'source> ParsingContext<'source> { qualifiers.insert(key, (value, token.meta)); } - _ => parser.errors.push(Error { + _ => frontend.errors.push(Error { kind: ErrorKind::InvalidToken(token.value, vec![ExpectedToken::Identifier]), meta: token.meta, }), @@ -363,11 +370,11 @@ impl<'source> ParsingContext<'source> { Ok(()) } - pub fn peek_type_name(&mut self, parser: &mut Parser) -> bool { - self.peek(parser).map_or(false, |t| match t.value { + pub fn peek_type_name(&mut self, frontend: &mut Frontend) -> bool { + self.peek(frontend).map_or(false, |t| match t.value { TokenValue::TypeName(_) | TokenValue::Void => true, TokenValue::Struct => true, - TokenValue::Identifier(ref ident) => parser.lookup_type.contains_key(ident), + TokenValue::Identifier(ref ident) => frontend.lookup_type.contains_key(ident), _ => false, }) } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index df6edd21d..ae529a6fb 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -3,18 +3,18 @@ use super::{ error::ExpectedToken, error::{Error, ErrorKind}, token::TokenValue, - Options, Parser, Span, + Frontend, Options, Span, }; use crate::ShaderStage; use pp_rs::token::PreprocessorError; #[test] fn version() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); // invalid versions assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 99000\n void main(){}", @@ -28,7 +28,7 @@ fn version() { ); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 449\n void main(){}", @@ -42,7 +42,7 @@ fn version() { ); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 450 smart\n void main(){}", @@ -56,7 +56,7 @@ fn version() { ); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 450\nvoid main(){} #version 450", @@ -79,45 +79,45 @@ fn version() { ); // valid versions - parser + frontend .parse( &Options::from(ShaderStage::Vertex), " # version 450\nvoid main() {}", ) .unwrap(); assert_eq!( - (parser.metadata().version, parser.metadata().profile), + (frontend.metadata().version, frontend.metadata().profile), (450, Profile::Core) ); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 450\nvoid main() {}", ) .unwrap(); assert_eq!( - (parser.metadata().version, parser.metadata().profile), + (frontend.metadata().version, frontend.metadata().profile), (450, Profile::Core) ); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 450 core\nvoid main(void) {}", ) .unwrap(); assert_eq!( - (parser.metadata().version, parser.metadata().profile), + (frontend.metadata().version, frontend.metadata().profile), (450, Profile::Core) ); } #[test] fn control_flow() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -133,7 +133,7 @@ fn control_flow() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -147,7 +147,7 @@ fn control_flow() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -170,7 +170,7 @@ fn control_flow() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -188,7 +188,7 @@ fn control_flow() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -208,9 +208,9 @@ fn control_flow() { #[test] fn declarations() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -227,7 +227,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -244,7 +244,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -261,7 +261,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -278,7 +278,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -297,7 +297,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -309,7 +309,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -324,9 +324,9 @@ fn declarations() { #[test] fn textures() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -346,9 +346,9 @@ fn textures() { #[test] fn functions() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -361,7 +361,7 @@ fn functions() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -375,7 +375,7 @@ fn functions() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -387,7 +387,7 @@ fn functions() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -402,7 +402,7 @@ fn functions() { .unwrap(); // Function overloading - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -429,7 +429,7 @@ fn functions() { .unwrap(); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -455,7 +455,7 @@ fn functions() { println!(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -474,7 +474,7 @@ fn functions() { .unwrap(); // Nested function call - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -489,7 +489,7 @@ fn functions() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -510,9 +510,9 @@ fn functions() { #[test] fn constants() { use crate::{Constant, ConstantInner, ScalarValue}; - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - let module = parser + let module = frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -556,9 +556,9 @@ fn constants() { #[test] fn function_overloading() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -582,9 +582,9 @@ fn function_overloading() { #[test] fn implicit_conversions() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -599,7 +599,7 @@ fn implicit_conversions() { .unwrap(); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -621,7 +621,7 @@ fn implicit_conversions() { ); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -645,9 +645,9 @@ fn implicit_conversions() { #[test] fn structs() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -661,7 +661,7 @@ fn structs() { ) .unwrap_err(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -675,7 +675,7 @@ fn structs() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -690,7 +690,7 @@ fn structs() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -706,7 +706,7 @@ fn structs() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -718,7 +718,7 @@ fn structs() { ) .unwrap_err(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -735,9 +735,9 @@ fn structs() { #[test] fn swizzles() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -752,7 +752,7 @@ fn swizzles() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -765,7 +765,7 @@ fn swizzles() { ) .unwrap_err(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -781,10 +781,10 @@ fn swizzles() { #[test] fn expressions() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); // Vector indexing - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -800,7 +800,7 @@ fn expressions() { .unwrap(); // Prefix increment/decrement - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -816,7 +816,7 @@ fn expressions() { .unwrap(); // Dynamic indexing of array - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 29d6e692b..632378c60 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,4 +1,6 @@ -use super::{constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, Span}; +use super::{ + constants::ConstantSolver, context::Context, Error, ErrorKind, Frontend, Result, Span, +}; use crate::{ proc::ResolveContext, Bytes, Constant, Expression, Handle, ImageClass, ImageDimension, ScalarKind, Type, TypeInner, VectorSize, @@ -224,7 +226,7 @@ pub const fn type_power(kind: ScalarKind, width: Bytes) -> Option { }) } -impl Parser { +impl Frontend { /// Resolves the types of the expressions until `expr` (inclusive) /// /// This needs to be done before the [`typifier`] can be queried for diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index e3fba754d..73fcb6e5e 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -2,7 +2,7 @@ use super::{ ast::*, context::{Context, ExprPos}, error::{Error, ErrorKind}, - Parser, Result, Span, + Frontend, Result, Span, }; use crate::{ AddressSpace, Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, @@ -18,7 +18,7 @@ pub struct VarDeclaration<'a, 'key> { pub meta: Span, } -/// Information about a builtin used in [`add_builtin`](Parser::add_builtin). +/// Information about a builtin used in [`add_builtin`](Frontend::add_builtin). struct BuiltInData { /// The type of the builtin. inner: TypeInner, @@ -35,7 +35,7 @@ pub enum GlobalOrConstant { Constant(Handle), } -impl Parser { +impl Frontend { /// Adds a builtin and returns a variable reference to it fn add_builtin( &mut self, diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 39987e62d..b43abcac3 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -14,7 +14,7 @@ pub struct MergeInstruction { pub continue_block_id: Option, } -impl> super::Parser { +impl> super::Frontend { // Registers a function call. It will generate a dummy handle to call, which // gets resolved after all the functions are processed. pub(super) fn add_call( diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 07681917b..7a70b3339 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -218,7 +218,7 @@ pub(super) fn patch_comparison_type( true } -impl> super::Parser { +impl> super::Frontend { pub(super) fn parse_image_couple(&mut self) -> Result<(), Error> { let _result_type_id = self.next()?; let result_id = self.next()?; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 93a76178b..8b24a8e88 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -514,7 +514,7 @@ enum SignAnchor { Operand, } -pub struct Parser { +pub struct Frontend { data: I, data_offset: usize, state: ModuleState, @@ -565,9 +565,9 @@ pub struct Parser { builtin_usage: FastHashSet, } -impl> Parser { +impl> Frontend { pub fn new(data: I, options: &Options) -> Self { - Parser { + Frontend { data, data_offset: 0, state: ModuleState::Empty, @@ -5095,7 +5095,7 @@ pub fn parse_u8_slice(data: &[u8], options: &Options) -> Result)>, + notes: Vec, +} + +impl ParseError { + pub fn labels(&self) -> impl Iterator + ExactSizeIterator + '_ { + self.labels + .iter() + .map(|&(span, ref msg)| (span, msg.as_ref())) + } + + pub fn message(&self) -> &str { + &self.message + } + + fn diagnostic(&self) -> Diagnostic<()> { + let diagnostic = Diagnostic::error() + .with_message(self.message.to_string()) + .with_labels( + self.labels + .iter() + .map(|label| { + Label::primary((), label.0.to_range().unwrap()) + .with_message(label.1.to_string()) + }) + .collect(), + ) + .with_notes( + self.notes + .iter() + .map(|note| format!("note: {note}")) + .collect(), + ); + diagnostic + } + + /// Emits a summary of the error to standard error stream. + pub fn emit_to_stderr(&self, source: &str) { + self.emit_to_stderr_with_path(source, "wgsl") + } + + /// Emits a summary of the error to standard error stream. + pub fn emit_to_stderr_with_path(&self, source: &str, path: &str) { + let files = SimpleFile::new(path, source); + let config = codespan_reporting::term::Config::default(); + let writer = StandardStream::stderr(ColorChoice::Auto); + term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) + .expect("cannot write error"); + } + + /// Emits a summary of the error to a string. + pub fn emit_to_string(&self, source: &str) -> String { + self.emit_to_string_with_path(source, "wgsl") + } + + /// Emits a summary of the error to a string. + pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String { + let files = SimpleFile::new(path, source); + let config = codespan_reporting::term::Config::default(); + let mut writer = NoColor::new(Vec::new()); + term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); + String::from_utf8(writer.into_inner()).unwrap() + } + + /// Returns a [`SourceLocation`] for the first label in the error message. + pub fn location(&self, source: &str) -> Option { + self.labels.get(0).map(|label| label.0.location(source)) + } +} + +impl std::fmt::Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.message) + } +} + +impl std::error::Error for ParseError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + None + } +} + +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum ExpectedToken<'a> { + Token(Token<'a>), + Identifier, + Number, + Integer, + /// A compile-time constant expression. + Constant, + /// Expected: constant, parenthesized expression, identifier + PrimaryExpression, + /// Expected: assignment, increment/decrement expression + Assignment, + /// Expected: 'case', 'default', '}' + SwitchItem, + /// Expected: ',', ')' + WorkgroupSizeSeparator, + /// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof + GlobalItem, + /// Expected a type. + Type, + /// Access of `var`, `let`, `const`. + Variable, + /// Access of a function + Function, +} + +#[derive(Clone, Copy, Debug, Error, PartialEq)] +pub enum NumberError { + #[error("invalid numeric literal format")] + Invalid, + #[error("numeric literal not representable by target type")] + NotRepresentable, + #[error("unimplemented f16 type")] + UnimplementedF16, +} + +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum InvalidAssignmentType { + Other, + Swizzle, + ImmutableBinding, +} + +#[derive(Clone, Debug)] +pub enum Error<'a> { + Unexpected(Span, ExpectedToken<'a>), + UnexpectedComponents(Span), + BadNumber(Span, NumberError), + /// A negative signed integer literal where both signed and unsigned, + /// but only non-negative literals are allowed. + NegativeInt(Span), + BadU32Constant(Span), + BadMatrixScalarKind(Span, crate::ScalarKind, u8), + BadAccessor(Span), + BadTexture(Span), + BadTypeCast { + span: Span, + from_type: String, + to_type: String, + }, + BadTextureSampleType { + span: Span, + kind: crate::ScalarKind, + width: u8, + }, + BadIncrDecrReferenceType(Span), + InvalidResolve(ResolveError), + InvalidForInitializer(Span), + /// A break if appeared outside of a continuing block + InvalidBreakIf(Span), + InvalidGatherComponent(Span), + InvalidConstructorComponentType(Span, i32), + InvalidIdentifierUnderscore(Span), + ReservedIdentifierPrefix(Span), + UnknownAddressSpace(Span), + UnknownAttribute(Span), + UnknownBuiltin(Span), + UnknownAccess(Span), + UnknownIdent(Span, &'a str), + UnknownScalarType(Span), + UnknownType(Span), + UnknownStorageFormat(Span), + UnknownConservativeDepth(Span), + SizeAttributeTooLow(Span, u32), + AlignAttributeTooLow(Span, Alignment), + NonPowerOfTwoAlignAttribute(Span), + InconsistentBinding(Span), + TypeNotConstructible(Span), + TypeNotInferrable(Span), + InitializationTypeMismatch(Span, String, String), + MissingType(Span), + MissingAttribute(&'static str, Span), + InvalidAtomicPointer(Span), + InvalidAtomicOperandType(Span), + Pointer(&'static str, Span), + NotPointer(Span), + NotReference(&'static str, Span), + InvalidAssignment { + span: Span, + ty: InvalidAssignmentType, + }, + ReservedKeyword(Span), + /// Redefinition of an identifier (used for both module-scope and local redefinitions). + Redefinition { + /// Span of the identifier in the previous definition. + previous: Span, + + /// Span of the identifier in the new definition. + current: Span, + }, + /// A declaration refers to itself directly. + RecursiveDeclaration { + /// The location of the name of the declaration. + ident: Span, + + /// The point at which it is used. + usage: Span, + }, + /// A declaration refers to itself indirectly, through one or more other + /// definitions. + CyclicDeclaration { + /// The location of the name of some declaration in the cycle. + ident: Span, + + /// The edges of the cycle of references. + /// + /// Each `(decl, reference)` pair indicates that the declaration whose + /// name is `decl` has an identifier at `reference` whose definition is + /// the next declaration in the cycle. The last pair's `reference` is + /// the same identifier as `ident`, above. + path: Vec<(Span, Span)>, + }, + ConstExprUnsupported(Span), + InvalidSwitchValue { + uint: bool, + span: Span, + }, + CalledEntryPoint(Span), + WrongArgumentCount { + span: Span, + expected: Range, + found: u32, + }, + FunctionReturnsVoid(Span), + Other, +} + +impl<'a> Error<'a> { + pub(crate) fn as_parse_error(&self, source: &'a str) -> ParseError { + match *self { + Error::Unexpected(unexpected_span, expected) => { + let expected_str = match expected { + ExpectedToken::Token(token) => { + match token { + Token::Separator(c) => format!("'{c}'"), + Token::Paren(c) => format!("'{c}'"), + Token::Attribute => "@".to_string(), + Token::Number(_) => "number".to_string(), + Token::Word(s) => s.to_string(), + Token::Operation(c) => format!("operation ('{c}')"), + Token::LogicalOperation(c) => format!("logical operation ('{c}')"), + Token::ShiftOperation(c) => format!("bitshift ('{c}{c}')"), + Token::AssignmentOperation(c) if c=='<' || c=='>' => format!("bitshift ('{c}{c}=')"), + Token::AssignmentOperation(c) => format!("operation ('{c}=')"), + Token::IncrementOperation => "increment operation".to_string(), + Token::DecrementOperation => "decrement operation".to_string(), + Token::Arrow => "->".to_string(), + Token::Unknown(c) => format!("unknown ('{c}')"), + Token::Trivia => "trivia".to_string(), + Token::End => "end".to_string(), + } + } + ExpectedToken::Identifier => "identifier".to_string(), + ExpectedToken::Number => "32-bit signed integer literal".to_string(), + ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), + ExpectedToken::Constant => "compile-time constant".to_string(), + ExpectedToken::PrimaryExpression => "expression".to_string(), + ExpectedToken::Assignment => "assignment or increment/decrement".to_string(), + ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), + ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), + ExpectedToken::GlobalItem => "global item ('struct', 'const', 'var', 'type', ';', 'fn') or the end of the file".to_string(), + ExpectedToken::Type => "type".to_string(), + ExpectedToken::Variable => "variable access".to_string(), + ExpectedToken::Function => "function name".to_string(), + }; + ParseError { + message: format!( + "expected {}, found '{}'", + expected_str, &source[unexpected_span], + ), + labels: vec![(unexpected_span, format!("expected {expected_str}").into())], + notes: vec![], + } + } + Error::UnexpectedComponents(bad_span) => ParseError { + message: "unexpected components".to_string(), + labels: vec![(bad_span, "unexpected components".into())], + notes: vec![], + }, + Error::BadNumber(bad_span, ref err) => ParseError { + message: format!("{}: `{}`", err, &source[bad_span],), + labels: vec![(bad_span, err.to_string().into())], + notes: vec![], + }, + Error::NegativeInt(bad_span) => ParseError { + message: format!( + "expected non-negative integer literal, found `{}`", + &source[bad_span], + ), + labels: vec![(bad_span, "expected non-negative integer".into())], + notes: vec![], + }, + Error::BadU32Constant(bad_span) => ParseError { + message: format!( + "expected unsigned integer constant expression, found `{}`", + &source[bad_span], + ), + labels: vec![(bad_span, "expected unsigned integer".into())], + notes: vec![], + }, + Error::BadMatrixScalarKind(span, kind, width) => ParseError { + message: format!( + "matrix scalar type must be floating-point, but found `{}`", + kind.to_wgsl(width) + ), + labels: vec![(span, "must be floating-point (e.g. `f32`)".into())], + notes: vec![], + }, + Error::BadAccessor(accessor_span) => ParseError { + message: format!("invalid field accessor `{}`", &source[accessor_span],), + labels: vec![(accessor_span, "invalid accessor".into())], + notes: vec![], + }, + Error::UnknownIdent(ident_span, ident) => ParseError { + message: format!("no definition in scope for identifier: '{ident}'"), + labels: vec![(ident_span, "unknown identifier".into())], + notes: vec![], + }, + Error::UnknownScalarType(bad_span) => ParseError { + message: format!("unknown scalar type: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown scalar type".into())], + notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()], + }, + Error::BadTextureSampleType { span, kind, width } => ParseError { + message: format!( + "texture sample type must be one of f32, i32 or u32, but found {}", + kind.to_wgsl(width) + ), + labels: vec![(span, "must be one of f32, i32 or u32".into())], + notes: vec![], + }, + Error::BadIncrDecrReferenceType(span) => ParseError { + message: + "increment/decrement operation requires reference type to be one of i32 or u32" + .to_string(), + labels: vec![(span, "must be a reference type of i32 or u32".into())], + notes: vec![], + }, + Error::BadTexture(bad_span) => ParseError { + message: format!( + "expected an image, but found '{}' which is not an image", + &source[bad_span] + ), + labels: vec![(bad_span, "not an image".into())], + notes: vec![], + }, + Error::BadTypeCast { + span, + ref from_type, + ref to_type, + } => { + let msg = format!("cannot cast a {from_type} to a {to_type}"); + ParseError { + message: msg.clone(), + labels: vec![(span, msg.into())], + notes: vec![], + } + } + Error::InvalidResolve(ref resolve_error) => ParseError { + message: resolve_error.to_string(), + labels: vec![], + notes: vec![], + }, + Error::InvalidForInitializer(bad_span) => ParseError { + message: format!( + "for(;;) initializer is not an assignment or a function call: '{}'", + &source[bad_span] + ), + labels: vec![(bad_span, "not an assignment or function call".into())], + notes: vec![], + }, + Error::InvalidBreakIf(bad_span) => ParseError { + message: "A break if is only allowed in a continuing block".to_string(), + labels: vec![(bad_span, "not in a continuing block".into())], + notes: vec![], + }, + Error::InvalidGatherComponent(bad_span) => ParseError { + message: format!( + "textureGather component '{}' doesn't exist, must be 0, 1, 2, or 3", + &source[bad_span] + ), + labels: vec![(bad_span, "invalid component".into())], + notes: vec![], + }, + Error::InvalidConstructorComponentType(bad_span, component) => ParseError { + message: format!("invalid type for constructor component at index [{component}]"), + labels: vec![(bad_span, "invalid component type".into())], + notes: vec![], + }, + Error::InvalidIdentifierUnderscore(bad_span) => ParseError { + message: "Identifier can't be '_'".to_string(), + labels: vec![(bad_span, "invalid identifier".into())], + notes: vec![ + "Use phony assignment instead ('_ =' notice the absence of 'let' or 'var')" + .to_string(), + ], + }, + Error::ReservedIdentifierPrefix(bad_span) => ParseError { + message: format!( + "Identifier starts with a reserved prefix: '{}'", + &source[bad_span] + ), + labels: vec![(bad_span, "invalid identifier".into())], + notes: vec![], + }, + Error::UnknownAddressSpace(bad_span) => ParseError { + message: format!("unknown address space: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown address space".into())], + notes: vec![], + }, + Error::UnknownAttribute(bad_span) => ParseError { + message: format!("unknown attribute: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown attribute".into())], + notes: vec![], + }, + Error::UnknownBuiltin(bad_span) => ParseError { + message: format!("unknown builtin: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown builtin".into())], + notes: vec![], + }, + Error::UnknownAccess(bad_span) => ParseError { + message: format!("unknown access: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown access".into())], + notes: vec![], + }, + Error::UnknownStorageFormat(bad_span) => ParseError { + message: format!("unknown storage format: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown storage format".into())], + notes: vec![], + }, + Error::UnknownConservativeDepth(bad_span) => ParseError { + message: format!("unknown conservative depth: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown conservative depth".into())], + notes: vec![], + }, + Error::UnknownType(bad_span) => ParseError { + message: format!("unknown type: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown type".into())], + notes: vec![], + }, + Error::SizeAttributeTooLow(bad_span, min_size) => ParseError { + message: format!("struct member size must be at least {min_size}"), + labels: vec![(bad_span, format!("must be at least {min_size}").into())], + notes: vec![], + }, + Error::AlignAttributeTooLow(bad_span, min_align) => ParseError { + message: format!("struct member alignment must be at least {min_align}"), + labels: vec![(bad_span, format!("must be at least {min_align}").into())], + notes: vec![], + }, + Error::NonPowerOfTwoAlignAttribute(bad_span) => ParseError { + message: "struct member alignment must be a power of 2".to_string(), + labels: vec![(bad_span, "must be a power of 2".into())], + notes: vec![], + }, + Error::InconsistentBinding(span) => ParseError { + message: "input/output binding is not consistent".to_string(), + labels: vec![(span, "input/output binding is not consistent".into())], + notes: vec![], + }, + Error::TypeNotConstructible(span) => ParseError { + message: format!("type `{}` is not constructible", &source[span]), + labels: vec![(span, "type is not constructible".into())], + notes: vec![], + }, + Error::TypeNotInferrable(span) => ParseError { + message: "type can't be inferred".to_string(), + labels: vec![(span, "type can't be inferred".into())], + notes: vec![], + }, + Error::InitializationTypeMismatch(name_span, ref expected_ty, ref got_ty) => { + ParseError { + message: format!( + "the type of `{}` is expected to be `{}`, but got `{}`", + &source[name_span], expected_ty, got_ty, + ), + labels: vec![( + name_span, + format!("definition of `{}`", &source[name_span]).into(), + )], + notes: vec![], + } + } + Error::MissingType(name_span) => ParseError { + message: format!("variable `{}` needs a type", &source[name_span]), + labels: vec![( + name_span, + format!("definition of `{}`", &source[name_span]).into(), + )], + notes: vec![], + }, + Error::MissingAttribute(name, name_span) => ParseError { + message: format!( + "variable `{}` needs a '{}' attribute", + &source[name_span], name + ), + labels: vec![( + name_span, + format!("definition of `{}`", &source[name_span]).into(), + )], + notes: vec![], + }, + Error::InvalidAtomicPointer(span) => ParseError { + message: "atomic operation is done on a pointer to a non-atomic".to_string(), + labels: vec![(span, "atomic pointer is invalid".into())], + notes: vec![], + }, + Error::InvalidAtomicOperandType(span) => ParseError { + message: "atomic operand type is inconsistent with the operation".to_string(), + labels: vec![(span, "atomic operand type is invalid".into())], + notes: vec![], + }, + Error::NotPointer(span) => ParseError { + message: "the operand of the `*` operator must be a pointer".to_string(), + labels: vec![(span, "expression is not a pointer".into())], + notes: vec![], + }, + Error::NotReference(what, span) => ParseError { + message: format!("{what} must be a reference"), + labels: vec![(span, "expression is not a reference".into())], + notes: vec![], + }, + Error::InvalidAssignment { span, ty } => ParseError { + message: "invalid left-hand side of assignment".into(), + labels: vec![(span, "cannot assign to this expression".into())], + notes: match ty { + InvalidAssignmentType::Swizzle => vec![ + "WGSL does not support assignments to swizzles".into(), + "consider assigning each component individually".into(), + ], + InvalidAssignmentType::ImmutableBinding => vec![ + format!("'{}' is an immutable binding", &source[span]), + "consider declaring it with `var` instead of `let`".into(), + ], + InvalidAssignmentType::Other => vec![], + }, + }, + Error::Pointer(what, span) => ParseError { + message: format!("{what} must not be a pointer"), + labels: vec![(span, "expression is a pointer".into())], + notes: vec![], + }, + Error::ReservedKeyword(name_span) => ParseError { + message: format!("name `{}` is a reserved keyword", &source[name_span]), + labels: vec![( + name_span, + format!("definition of `{}`", &source[name_span]).into(), + )], + notes: vec![], + }, + Error::Redefinition { previous, current } => ParseError { + message: format!("redefinition of `{}`", &source[current]), + labels: vec![ + ( + current, + format!("redefinition of `{}`", &source[current]).into(), + ), + ( + previous, + format!("previous definition of `{}`", &source[previous]).into(), + ), + ], + notes: vec![], + }, + Error::RecursiveDeclaration { ident, usage } => ParseError { + message: format!("declaration of `{}` is recursive", &source[ident]), + labels: vec![(ident, "".into()), (usage, "uses itself here".into())], + notes: vec![], + }, + Error::CyclicDeclaration { ident, ref path } => ParseError { + message: format!("declaration of `{}` is cyclic", &source[ident]), + labels: path + .iter() + .enumerate() + .flat_map(|(i, &(ident, usage))| { + [ + (ident, "".into()), + ( + usage, + if i == path.len() - 1 { + "ending the cycle".into() + } else { + format!("uses `{}`", &source[ident]).into() + }, + ), + ] + }) + .collect(), + notes: vec![], + }, + Error::ConstExprUnsupported(span) => ParseError { + message: "this constant expression is not supported".to_string(), + labels: vec![(span, "expression is not supported".into())], + notes: vec![ + "this should be fixed in a future version of Naga".into(), + "https://github.com/gfx-rs/naga/issues/1829".into(), + ], + }, + Error::InvalidSwitchValue { uint, span } => ParseError { + message: "invalid switch value".to_string(), + labels: vec![( + span, + if uint { + "expected unsigned integer" + } else { + "expected signed integer" + } + .into(), + )], + notes: vec![if uint { + format!("suffix the integer with a `u`: '{}u'", &source[span]) + } else { + let span = span.to_range().unwrap(); + format!( + "remove the `u` suffix: '{}'", + &source[span.start..span.end - 1] + ) + }], + }, + Error::CalledEntryPoint(span) => ParseError { + message: "entry point cannot be called".to_string(), + labels: vec![(span, "entry point cannot be called".into())], + notes: vec![], + }, + Error::WrongArgumentCount { + span, + ref expected, + found, + } => ParseError { + message: format!( + "wrong number of arguments: expected {}, found {}", + if expected.len() < 2 { + format!("{}", expected.start) + } else { + format!("{}..{}", expected.start, expected.end) + }, + found + ), + labels: vec![(span, "wrong number of arguments".into())], + notes: vec![], + }, + Error::FunctionReturnsVoid(span) => ParseError { + message: "function does not return any value".to_string(), + labels: vec![(span, "".into())], + notes: vec![ + "perhaps you meant to call the function in a separate statement?".into(), + ], + }, + Error::Other => ParseError { + message: "other error".to_string(), + labels: vec![], + notes: vec![], + }, + } + } +} diff --git a/src/front/wgsl/index.rs b/src/front/wgsl/index.rs index a36273572..a5524fe8f 100644 --- a/src/front/wgsl/index.rs +++ b/src/front/wgsl/index.rs @@ -1,4 +1,5 @@ -use super::{ast, Error}; +use super::Error; +use crate::front::wgsl::parse::ast; use crate::{FastHashMap, Handle, Span}; /// A `GlobalDecl` list in which each definition occurs before all its uses. diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/lower/construction.rs similarity index 99% rename from src/front/wgsl/construction.rs rename to src/front/wgsl/lower/construction.rs index 2fae293c1..723d4441f 100644 --- a/src/front/wgsl/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -1,6 +1,8 @@ +use crate::front::wgsl::parse::ast; use crate::{Handle, Span}; -use super::{ast, Error, ExpressionContext, Lowerer, OutputContext}; +use crate::front::wgsl::error::Error; +use crate::front::wgsl::lower::{ExpressionContext, Lowerer, OutputContext}; use crate::proc::TypeResolution; enum ConcreteConstructorHandle { @@ -133,7 +135,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { /// /// [`Construct`]: ast::Expression::Construct /// [`Call`]: ast::Expression::Call - pub(super) fn construct( + pub fn construct( &mut self, span: Span, constructor: &ast::ConstructorType<'source>, @@ -561,7 +563,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { /// [`Type`]: crate::Type /// [`Constant`]: crate::Constant /// [`ctx.module`]: OutputContext::module - pub(super) fn const_construct( + pub fn const_construct( &mut self, span: Span, constructor: &ast::ConstructorType<'source>, diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs new file mode 100644 index 000000000..7d03c7fb7 --- /dev/null +++ b/src/front/wgsl/lower/mod.rs @@ -0,0 +1,2371 @@ +use crate::front::wgsl::error::{Error, ExpectedToken, InvalidAssignmentType}; +use crate::front::wgsl::index::Index; +use crate::front::wgsl::parse::number::Number; +use crate::front::wgsl::parse::{ast, conv}; +use crate::front::{Emitter, Typifier}; +use crate::proc::{ensure_block_returns, Alignment, Layouter, ResolveContext, TypeResolution}; +use crate::{Arena, FastHashMap, Handle, Span}; + +mod construction; + +/// State for constructing a `crate::Module`. +pub struct OutputContext<'source, 'temp, 'out> { + /// The `TranslationUnit`'s expressions arena. + ast_expressions: &'temp Arena>, + + /// The `TranslationUnit`'s types arena. + types: &'temp Arena>, + + // Naga IR values. + /// The map from the names of module-scope declarations to the Naga IR + /// `Handle`s we have built for them, owned by `Lowerer::lower`. + globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, + + /// The module we're constructing. + module: &'out mut crate::Module, +} + +impl<'source> OutputContext<'source, '_, '_> { + fn reborrow(&mut self) -> OutputContext<'source, '_, '_> { + OutputContext { + ast_expressions: self.ast_expressions, + globals: self.globals, + types: self.types, + module: self.module, + } + } + + fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { + self.module + .types + .insert(crate::Type { inner, name: None }, Span::UNDEFINED) + } +} + +/// State for lowering a statement within a function. +pub struct StatementContext<'source, 'temp, 'out> { + // WGSL AST values. + /// A reference to [`TranslationUnit::expressions`] for the translation unit + /// we're lowering. + /// + /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions + ast_expressions: &'temp Arena>, + + /// A reference to [`TranslationUnit::types`] for the translation unit + /// we're lowering. + /// + /// [`TranslationUnit::types`]: ast::TranslationUnit::types + types: &'temp Arena>, + + // Naga IR values. + /// The map from the names of module-scope declarations to the Naga IR + /// `Handle`s we have built for them, owned by `Lowerer::lower`. + globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, + + /// A map from `ast::Local` handles to the Naga expressions we've built for them. + /// + /// The Naga expressions are either [`LocalVariable`] or + /// [`FunctionArgument`] expressions. + /// + /// [`LocalVariable`]: crate::Expression::LocalVariable + /// [`FunctionArgument`]: crate::Expression::FunctionArgument + local_table: &'temp mut FastHashMap, TypedExpression>, + + typifier: &'temp mut Typifier, + variables: &'out mut Arena, + naga_expressions: &'out mut Arena, + named_expressions: &'out mut FastHashMap, String>, + arguments: &'out [crate::FunctionArgument], + module: &'out mut crate::Module, +} + +impl<'a, 'temp> StatementContext<'a, 'temp, '_> { + fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { + StatementContext { + local_table: self.local_table, + globals: self.globals, + types: self.types, + ast_expressions: self.ast_expressions, + typifier: self.typifier, + variables: self.variables, + naga_expressions: self.naga_expressions, + named_expressions: self.named_expressions, + arguments: self.arguments, + module: self.module, + } + } + + fn as_expression<'t>( + &'t mut self, + block: &'t mut crate::Block, + emitter: &'t mut Emitter, + ) -> ExpressionContext<'a, 't, '_> + where + 'temp: 't, + { + ExpressionContext { + local_table: self.local_table, + globals: self.globals, + types: self.types, + ast_expressions: self.ast_expressions, + typifier: self.typifier, + naga_expressions: self.naga_expressions, + module: self.module, + local_vars: self.variables, + arguments: self.arguments, + block, + emitter, + } + } + + fn as_output(&mut self) -> OutputContext<'a, '_, '_> { + OutputContext { + ast_expressions: self.ast_expressions, + globals: self.globals, + types: self.types, + module: self.module, + } + } +} + +/// State for lowering an `ast::Expression` to Naga IR. +/// +/// Not to be confused with `parser::ExpressionContext`. +pub struct ExpressionContext<'source, 'temp, 'out> { + // WGSL AST values. + local_table: &'temp mut FastHashMap, TypedExpression>, + ast_expressions: &'temp Arena>, + types: &'temp Arena>, + + // Naga IR values. + /// The map from the names of module-scope declarations to the Naga IR + /// `Handle`s we have built for them, owned by `Lowerer::lower`. + globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, + + typifier: &'temp mut Typifier, + naga_expressions: &'out mut Arena, + local_vars: &'out Arena, + arguments: &'out [crate::FunctionArgument], + module: &'out mut crate::Module, + block: &'temp mut crate::Block, + emitter: &'temp mut Emitter, +} + +impl<'a> ExpressionContext<'a, '_, '_> { + fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { + ExpressionContext { + local_table: self.local_table, + globals: self.globals, + types: self.types, + ast_expressions: self.ast_expressions, + typifier: self.typifier, + naga_expressions: self.naga_expressions, + module: self.module, + local_vars: self.local_vars, + arguments: self.arguments, + block: self.block, + emitter: self.emitter, + } + } + + fn as_output(&mut self) -> OutputContext<'a, '_, '_> { + OutputContext { + ast_expressions: self.ast_expressions, + globals: self.globals, + types: self.types, + module: self.module, + } + } + + /// Determine the type of `handle`, and add it to the module's arena. + /// + /// If you just need a `TypeInner` for `handle`'s type, use + /// [`grow_types`] and [`resolved_inner`] instead. This function + /// should only be used when the type of `handle` needs to appear + /// in the module's final `Arena`, for example, if you're + /// creating a [`LocalVariable`] whose type is inferred from its + /// initializer. + /// + /// [`grow_types`]: Self::grow_types + /// [`resolved_inner`]: Self::resolved_inner + /// [`LocalVariable`]: crate::LocalVariable + fn register_type( + &mut self, + handle: Handle, + ) -> Result, Error<'a>> { + self.grow_types(handle)?; + Ok(self.typifier.register_type(handle, &mut self.module.types)) + } + + /// Resolve the types of all expressions up through `handle`. + /// + /// Ensure that [`self.typifier`] has a [`TypeResolution`] for + /// every expression in [`self.naga_expressions`]. + /// + /// This does not add types to any arena. The [`Typifier`] + /// documentation explains the steps we take to avoid filling + /// arenas with intermediate types. + /// + /// This function takes `&mut self`, so it can't conveniently + /// return a shared reference to the resulting `TypeResolution`: + /// the shared reference would extend the mutable borrow, and you + /// wouldn't be able to use `self` for anything else. Instead, you + /// should call `grow_types` to cover the handles you need, and + /// then use `self.typifier[handle]` or + /// [`self.resolved_inner(handle)`] to get at their resolutions. + /// + /// [`self.typifier`]: ExpressionContext::typifier + /// [`self.resolved_inner(handle)`]: ExpressionContext::resolved_inner + /// [`Typifier`]: Typifier + fn grow_types(&mut self, handle: Handle) -> Result<&mut Self, Error<'a>> { + let resolve_ctx = ResolveContext { + constants: &self.module.constants, + types: &self.module.types, + global_vars: &self.module.global_variables, + local_vars: self.local_vars, + functions: &self.module.functions, + arguments: self.arguments, + }; + self.typifier + .grow(handle, self.naga_expressions, &resolve_ctx) + .map_err(Error::InvalidResolve)?; + Ok(self) + } + + fn resolved_inner(&self, handle: Handle) -> &crate::TypeInner { + self.typifier[handle].inner_with(&self.module.types) + } + + fn image_data( + &mut self, + image: Handle, + span: Span, + ) -> Result<(crate::ImageClass, bool), Error<'a>> { + self.grow_types(image)?; + match *self.resolved_inner(image) { + crate::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), + _ => Err(Error::BadTexture(span)), + } + } + + fn prepare_args<'b>( + &mut self, + args: &'b [Handle>], + min_args: u32, + span: Span, + ) -> ArgumentContext<'b, 'a> { + ArgumentContext { + args: args.iter(), + min_args, + args_used: 0, + total_args: args.len() as u32, + span, + } + } + + /// Insert splats, if needed by the non-'*' operations. + fn binary_op_splat( + &mut self, + op: crate::BinaryOperator, + left: &mut Handle, + right: &mut Handle, + ) -> Result<(), Error<'a>> { + if op != crate::BinaryOperator::Multiply { + self.grow_types(*left)?.grow_types(*right)?; + + let left_size = match *self.resolved_inner(*left) { + crate::TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + + match (left_size, self.resolved_inner(*right)) { + (Some(size), &crate::TypeInner::Scalar { .. }) => { + *right = self.naga_expressions.append( + crate::Expression::Splat { + size, + value: *right, + }, + self.naga_expressions.get_span(*right), + ); + } + (None, &crate::TypeInner::Vector { size, .. }) => { + *left = self.naga_expressions.append( + crate::Expression::Splat { size, value: *left }, + self.naga_expressions.get_span(*left), + ); + } + _ => {} + } + } + + Ok(()) + } + + /// Add a single expression to the expression table that is not covered by `self.emitter`. + /// + /// This is useful for `CallResult` and `AtomicResult` expressions, which should not be covered by + /// `Emit` statements. + fn interrupt_emitter( + &mut self, + expression: crate::Expression, + span: Span, + ) -> Handle { + self.block + .extend(self.emitter.finish(self.naga_expressions)); + let result = self.naga_expressions.append(expression, span); + self.emitter.start(self.naga_expressions); + result + } + + /// Apply the WGSL Load Rule to `expr`. + /// + /// If `expr` is has type `ref`, perform a load to produce a value of type + /// `T`. Otherwise, return `expr` unchanged. + fn apply_load_rule(&mut self, expr: TypedExpression) -> Handle { + if expr.is_reference { + let load = crate::Expression::Load { + pointer: expr.handle, + }; + let span = self.naga_expressions.get_span(expr.handle); + self.naga_expressions.append(load, span) + } else { + expr.handle + } + } + + /// Creates a zero value constant of type `ty` + /// + /// Returns `None` if the given `ty` is not a constructible type + fn create_zero_value_constant( + &mut self, + ty: Handle, + ) -> Option> { + let inner = match self.module.types[ty].inner { + crate::TypeInner::Scalar { kind, width } => { + let value = match kind { + crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), + crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), + crate::ScalarKind::Float => crate::ScalarValue::Float(0.), + crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), + }; + crate::ConstantInner::Scalar { width, value } + } + crate::TypeInner::Vector { size, kind, width } => { + let scalar_ty = self.ensure_type_exists(crate::TypeInner::Scalar { width, kind }); + let component = self.create_zero_value_constant(scalar_ty); + crate::ConstantInner::Composite { + ty, + components: (0..size as u8).map(|_| component).collect::>()?, + } + } + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + let vec_ty = self.ensure_type_exists(crate::TypeInner::Vector { + width, + kind: crate::ScalarKind::Float, + size: rows, + }); + let component = self.create_zero_value_constant(vec_ty); + crate::ConstantInner::Composite { + ty, + components: (0..columns as u8) + .map(|_| component) + .collect::>()?, + } + } + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(size), + .. + } => { + let component = self.create_zero_value_constant(base); + crate::ConstantInner::Composite { + ty, + components: (0..self.module.constants[size].to_array_length().unwrap()) + .map(|_| component) + .collect::>()?, + } + } + crate::TypeInner::Struct { ref members, .. } => { + let members = members.clone(); + crate::ConstantInner::Composite { + ty, + components: members + .iter() + .map(|member| self.create_zero_value_constant(member.ty)) + .collect::>()?, + } + } + _ => return None, + }; + + let constant = self.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + Span::UNDEFINED, + ); + Some(constant) + } + + fn format_typeinner(&self, inner: &crate::TypeInner) -> String { + inner.to_wgsl(&self.module.types, &self.module.constants) + } + + fn format_type(&self, handle: Handle) -> String { + let ty = &self.module.types[handle]; + match ty.name { + Some(ref name) => name.clone(), + None => self.format_typeinner(&ty.inner), + } + } + + fn format_type_resolution(&self, resolution: &TypeResolution) -> String { + match *resolution { + TypeResolution::Handle(handle) => self.format_type(handle), + TypeResolution::Value(ref inner) => self.format_typeinner(inner), + } + } + + fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { + self.as_output().ensure_type_exists(inner) + } +} + +struct ArgumentContext<'ctx, 'source> { + args: std::slice::Iter<'ctx, Handle>>, + min_args: u32, + args_used: u32, + total_args: u32, + span: Span, +} + +impl<'source> ArgumentContext<'_, 'source> { + pub fn finish(self) -> Result<(), Error<'source>> { + if self.args.len() == 0 { + Ok(()) + } else { + Err(Error::WrongArgumentCount { + found: self.total_args, + expected: self.min_args..self.args_used + 1, + span: self.span, + }) + } + } + + pub fn next(&mut self) -> Result>, Error<'source>> { + match self.args.next().copied() { + Some(arg) => { + self.args_used += 1; + Ok(arg) + } + None => Err(Error::WrongArgumentCount { + found: self.total_args, + expected: self.min_args..self.args_used + 1, + span: self.span, + }), + } + } +} + +/// A Naga [`Expression`] handle, with WGSL type information. +/// +/// Naga and WGSL types are very close, but Naga lacks WGSL's 'reference' types, +/// which we need to know to apply the Load Rule. This struct carries a Naga +/// `Handle` along with enough information to determine its WGSL type. +/// +/// [`Expression`]: crate::Expression +#[derive(Debug, Copy, Clone)] +struct TypedExpression { + /// The handle of the Naga expression. + handle: Handle, + + /// True if this expression's WGSL type is a reference. + /// + /// When this is true, `handle` must be a pointer. + is_reference: bool, +} + +impl TypedExpression { + const fn non_reference(handle: Handle) -> TypedExpression { + TypedExpression { + handle, + is_reference: false, + } + } +} + +enum Composition { + Single(u32), + Multi(crate::VectorSize, [crate::SwizzleComponent; 4]), +} + +impl Composition { + const fn letter_component(letter: char) -> Option { + use crate::SwizzleComponent as Sc; + match letter { + 'x' | 'r' => Some(Sc::X), + 'y' | 'g' => Some(Sc::Y), + 'z' | 'b' => Some(Sc::Z), + 'w' | 'a' => Some(Sc::W), + _ => None, + } + } + + fn extract_impl(name: &str, name_span: Span) -> Result { + let ch = name.chars().next().ok_or(Error::BadAccessor(name_span))?; + match Self::letter_component(ch) { + Some(sc) => Ok(sc as u32), + None => Err(Error::BadAccessor(name_span)), + } + } + + fn make(name: &str, name_span: Span) -> Result { + if name.len() > 1 { + let mut components = [crate::SwizzleComponent::X; 4]; + for (comp, ch) in components.iter_mut().zip(name.chars()) { + *comp = Self::letter_component(ch).ok_or(Error::BadAccessor(name_span))?; + } + + let size = match name.len() { + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + 4 => crate::VectorSize::Quad, + _ => return Err(Error::BadAccessor(name_span)), + }; + Ok(Composition::Multi(size, components)) + } else { + Self::extract_impl(name, name_span).map(Composition::Single) + } + } +} + +/// An `ast::GlobalDecl` for which we have built the Naga IR equivalent. +enum LoweredGlobalDecl { + Function(Handle), + Var(Handle), + Const(Handle), + Type(Handle), + EntryPoint, +} + +enum ConstantOrInner { + Constant(Handle), + Inner(crate::ConstantInner), +} + +enum Texture { + Gather, + GatherCompare, + + Sample, + SampleBias, + SampleCompare, + SampleCompareLevel, + SampleGrad, + SampleLevel, + // SampleBaseClampToEdge, +} + +impl Texture { + pub fn map(word: &str) -> Option { + Some(match word { + "textureGather" => Self::Gather, + "textureGatherCompare" => Self::GatherCompare, + + "textureSample" => Self::Sample, + "textureSampleBias" => Self::SampleBias, + "textureSampleCompare" => Self::SampleCompare, + "textureSampleCompareLevel" => Self::SampleCompareLevel, + "textureSampleGrad" => Self::SampleGrad, + "textureSampleLevel" => Self::SampleLevel, + // "textureSampleBaseClampToEdge" => Some(Self::SampleBaseClampToEdge), + _ => return None, + }) + } + + pub const fn min_argument_count(&self) -> u32 { + match *self { + Self::Gather => 3, + Self::GatherCompare => 4, + + Self::Sample => 3, + Self::SampleBias => 5, + Self::SampleCompare => 5, + Self::SampleCompareLevel => 5, + Self::SampleGrad => 6, + Self::SampleLevel => 5, + // Self::SampleBaseClampToEdge => 3, + } + } +} + +pub struct Lowerer<'source, 'temp> { + index: &'temp Index<'source>, + layouter: Layouter, +} + +impl<'source, 'temp> Lowerer<'source, 'temp> { + pub fn new(index: &'temp Index<'source>) -> Self { + Self { + index, + layouter: Layouter::default(), + } + } + + pub fn lower( + &mut self, + tu: &'temp ast::TranslationUnit<'source>, + ) -> Result> { + let mut module = crate::Module::default(); + + let mut ctx = OutputContext { + ast_expressions: &tu.expressions, + globals: &mut FastHashMap::default(), + types: &tu.types, + module: &mut module, + }; + + for decl in self.index.visit_ordered() { + let span = tu.decls.get_span(decl); + let decl = &tu.decls[decl]; + + match decl.kind { + ast::GlobalDeclKind::Fn(ref f) => { + let decl = self.function(f, span, ctx.reborrow())?; + ctx.globals.insert(f.name.name, decl); + } + ast::GlobalDeclKind::Var(ref v) => { + let ty = self.resolve_ast_type(v.ty, ctx.reborrow())?; + + let init = v + .init + .map(|init| self.constant(init, ctx.reborrow())) + .transpose()?; + + let handle = ctx.module.global_variables.append( + crate::GlobalVariable { + name: Some(v.name.name.to_string()), + space: v.space, + binding: v.binding.clone(), + ty, + init, + }, + span, + ); + + ctx.globals + .insert(v.name.name, LoweredGlobalDecl::Var(handle)); + } + ast::GlobalDeclKind::Const(ref c) => { + let inner = self.constant_inner(c.init, ctx.reborrow())?; + let inner = match inner { + ConstantOrInner::Constant(c) => ctx.module.constants[c].inner.clone(), + ConstantOrInner::Inner(inner) => inner, + }; + + let inferred_type = match inner { + crate::ConstantInner::Scalar { width, value } => { + ctx.ensure_type_exists(crate::TypeInner::Scalar { + width, + kind: value.scalar_kind(), + }) + } + crate::ConstantInner::Composite { ty, .. } => ty, + }; + + let handle = ctx.module.constants.append( + crate::Constant { + name: Some(c.name.name.to_string()), + specialization: None, + inner, + }, + span, + ); + + let explicit_ty = + c.ty.map(|ty| self.resolve_ast_type(ty, ctx.reborrow())) + .transpose()?; + + if let Some(explicit) = explicit_ty { + if explicit != inferred_type { + let ty = &ctx.module.types[explicit]; + let explicit = ty.name.clone().unwrap_or_else(|| { + ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) + }); + + let ty = &ctx.module.types[inferred_type]; + let inferred = ty.name.clone().unwrap_or_else(|| { + ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) + }); + + return Err(Error::InitializationTypeMismatch( + c.name.span, + explicit, + inferred, + )); + } + } + + ctx.globals + .insert(c.name.name, LoweredGlobalDecl::Const(handle)); + } + ast::GlobalDeclKind::Struct(ref s) => { + let handle = self.r#struct(s, span, ctx.reborrow())?; + ctx.globals + .insert(s.name.name, LoweredGlobalDecl::Type(handle)); + } + ast::GlobalDeclKind::Type(ref alias) => { + let ty = self.resolve_ast_type(alias.ty, ctx.reborrow())?; + ctx.globals + .insert(alias.name.name, LoweredGlobalDecl::Type(ty)); + } + } + } + + Ok(module) + } + + fn function( + &mut self, + f: &ast::Function<'source>, + span: Span, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result> { + let mut local_table = FastHashMap::default(); + let mut local_variables = Arena::new(); + let mut expressions = Arena::new(); + let mut named_expressions = crate::NamedExpressions::default(); + + let arguments = f + .arguments + .iter() + .enumerate() + .map(|(i, arg)| { + let ty = self.resolve_ast_type(arg.ty, ctx.reborrow())?; + let expr = expressions + .append(crate::Expression::FunctionArgument(i as u32), arg.name.span); + local_table.insert(arg.handle, TypedExpression::non_reference(expr)); + named_expressions.insert(expr, arg.name.name.to_string()); + + Ok(crate::FunctionArgument { + name: Some(arg.name.name.to_string()), + ty, + binding: self.interpolate_default(&arg.binding, ty, ctx.reborrow()), + }) + }) + .collect::, _>>()?; + + let result = f + .result + .as_ref() + .map(|res| { + self.resolve_ast_type(res.ty, ctx.reborrow()) + .map(|ty| crate::FunctionResult { + ty, + binding: self.interpolate_default(&res.binding, ty, ctx.reborrow()), + }) + }) + .transpose()?; + + let mut typifier = Typifier::default(); + let mut body = self.block( + &f.body, + StatementContext { + local_table: &mut local_table, + globals: ctx.globals, + ast_expressions: ctx.ast_expressions, + typifier: &mut typifier, + variables: &mut local_variables, + naga_expressions: &mut expressions, + named_expressions: &mut named_expressions, + types: ctx.types, + module: ctx.module, + arguments: &arguments, + }, + )?; + ensure_block_returns(&mut body); + + let function = crate::Function { + name: Some(f.name.name.to_string()), + arguments, + result, + local_variables, + expressions, + named_expressions, + body, + }; + + if let Some(ref entry) = f.entry_point { + ctx.module.entry_points.push(crate::EntryPoint { + name: f.name.name.to_string(), + stage: entry.stage, + early_depth_test: entry.early_depth_test, + workgroup_size: entry.workgroup_size, + function, + }); + Ok(LoweredGlobalDecl::EntryPoint) + } else { + let handle = ctx.module.functions.append(function, span); + Ok(LoweredGlobalDecl::Function(handle)) + } + } + + fn block( + &mut self, + b: &ast::Block<'source>, + mut ctx: StatementContext<'source, '_, '_>, + ) -> Result> { + let mut block = crate::Block::default(); + + for stmt in b.stmts.iter() { + self.statement(stmt, &mut block, ctx.reborrow())?; + } + + Ok(block) + } + + fn statement( + &mut self, + stmt: &ast::Statement<'source>, + block: &mut crate::Block, + mut ctx: StatementContext<'source, '_, '_>, + ) -> Result<(), Error<'source>> { + let out = match stmt.kind { + ast::StatementKind::Block(ref block) => { + let block = self.block(block, ctx.reborrow())?; + crate::Statement::Block(block) + } + ast::StatementKind::LocalDecl(ref decl) => match *decl { + ast::LocalDecl::Let(ref l) => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let value = self.expression(l.init, ctx.as_expression(block, &mut emitter))?; + + let explicit_ty = + l.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) + .transpose()?; + + if let Some(ty) = explicit_ty { + let mut ctx = ctx.as_expression(block, &mut emitter); + let init_ty = ctx.register_type(value)?; + if !ctx.module.types[ty] + .inner + .equivalent(&ctx.module.types[init_ty].inner, &ctx.module.types) + { + return Err(Error::InitializationTypeMismatch( + l.name.span, + ctx.format_type(ty), + ctx.format_type(init_ty), + )); + } + } + + block.extend(emitter.finish(ctx.naga_expressions)); + ctx.local_table + .insert(l.handle, TypedExpression::non_reference(value)); + ctx.named_expressions.insert(value, l.name.name.to_string()); + + return Ok(()); + } + ast::LocalDecl::Var(ref v) => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let initializer = match v.init { + Some(init) => { + let initializer = + self.expression(init, ctx.as_expression(block, &mut emitter))?; + ctx.as_expression(block, &mut emitter) + .grow_types(initializer)?; + Some(initializer) + } + None => None, + }; + + let explicit_ty = + v.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) + .transpose()?; + + let ty = match (explicit_ty, initializer) { + (Some(explicit), Some(initializer)) => { + let ctx = ctx.as_expression(block, &mut emitter); + let initializer_ty = ctx.resolved_inner(initializer); + if !ctx.module.types[explicit] + .inner + .equivalent(initializer_ty, &ctx.module.types) + { + return Err(Error::InitializationTypeMismatch( + v.name.span, + ctx.format_type(explicit), + ctx.format_typeinner(initializer_ty), + )); + } + explicit + } + (Some(explicit), None) => explicit, + (None, Some(initializer)) => ctx + .as_expression(block, &mut emitter) + .register_type(initializer)?, + (None, None) => { + return Err(Error::MissingType(v.name.span)); + } + }; + + let var = ctx.variables.append( + crate::LocalVariable { + name: Some(v.name.name.to_string()), + ty, + init: None, + }, + stmt.span, + ); + + let handle = ctx + .as_expression(block, &mut emitter) + .interrupt_emitter(crate::Expression::LocalVariable(var), Span::UNDEFINED); + block.extend(emitter.finish(ctx.naga_expressions)); + ctx.local_table.insert( + v.handle, + TypedExpression { + handle, + is_reference: true, + }, + ); + + match initializer { + Some(initializer) => crate::Statement::Store { + pointer: handle, + value: initializer, + }, + None => return Ok(()), + } + } + }, + ast::StatementKind::If { + condition, + ref accept, + ref reject, + } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let condition = + self.expression(condition, ctx.as_expression(block, &mut emitter))?; + block.extend(emitter.finish(ctx.naga_expressions)); + + let accept = self.block(accept, ctx.reborrow())?; + let reject = self.block(reject, ctx.reborrow())?; + + crate::Statement::If { + condition, + accept, + reject, + } + } + ast::StatementKind::Switch { + selector, + ref cases, + } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let mut ectx = ctx.as_expression(block, &mut emitter); + let selector = self.expression(selector, ectx.reborrow())?; + + ectx.grow_types(selector)?; + let uint = + ectx.resolved_inner(selector).scalar_kind() == Some(crate::ScalarKind::Uint); + block.extend(emitter.finish(ctx.naga_expressions)); + + let cases = cases + .iter() + .map(|case| { + Ok(crate::SwitchCase { + value: match case.value { + ast::SwitchValue::I32(num) if !uint => { + crate::SwitchValue::Integer(num) + } + ast::SwitchValue::U32(num) if uint => { + crate::SwitchValue::Integer(num as i32) + } + ast::SwitchValue::Default => crate::SwitchValue::Default, + _ => { + return Err(Error::InvalidSwitchValue { + uint, + span: case.value_span, + }); + } + }, + body: self.block(&case.body, ctx.reborrow())?, + fall_through: case.fall_through, + }) + }) + .collect::>()?; + + crate::Statement::Switch { selector, cases } + } + ast::StatementKind::Loop { + ref body, + ref continuing, + break_if, + } => { + let body = self.block(body, ctx.reborrow())?; + let mut continuing = self.block(continuing, ctx.reborrow())?; + + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + let break_if = break_if + .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) + .transpose()?; + continuing.extend(emitter.finish(ctx.naga_expressions)); + + crate::Statement::Loop { + body, + continuing, + break_if, + } + } + ast::StatementKind::Break => crate::Statement::Break, + ast::StatementKind::Continue => crate::Statement::Continue, + ast::StatementKind::Return { value } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let value = value + .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) + .transpose()?; + block.extend(emitter.finish(ctx.naga_expressions)); + + crate::Statement::Return { value } + } + ast::StatementKind::Kill => crate::Statement::Kill, + ast::StatementKind::Call { + ref function, + ref arguments, + } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let _ = self.call( + stmt.span, + function, + arguments, + ctx.as_expression(block, &mut emitter), + )?; + block.extend(emitter.finish(ctx.naga_expressions)); + return Ok(()); + } + ast::StatementKind::Assign { target, op, value } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let expr = + self.expression_for_reference(target, ctx.as_expression(block, &mut emitter))?; + let mut value = self.expression(value, ctx.as_expression(block, &mut emitter))?; + + if !expr.is_reference { + let ty = if ctx.named_expressions.contains_key(&expr.handle) { + InvalidAssignmentType::ImmutableBinding + } else { + match ctx.naga_expressions[expr.handle] { + crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, + _ => InvalidAssignmentType::Other, + } + }; + + return Err(Error::InvalidAssignment { + span: ctx.ast_expressions.get_span(target), + ty, + }); + } + + let value = match op { + Some(op) => { + let mut ctx = ctx.as_expression(block, &mut emitter); + let mut left = ctx.apply_load_rule(expr); + ctx.binary_op_splat(op, &mut left, &mut value)?; + ctx.naga_expressions.append( + crate::Expression::Binary { + op, + left, + right: value, + }, + stmt.span, + ) + } + None => value, + }; + block.extend(emitter.finish(ctx.naga_expressions)); + + crate::Statement::Store { + pointer: expr.handle, + value, + } + } + ast::StatementKind::Increment(value) | ast::StatementKind::Decrement(value) => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let op = match stmt.kind { + ast::StatementKind::Increment(_) => crate::BinaryOperator::Add, + ast::StatementKind::Decrement(_) => crate::BinaryOperator::Subtract, + _ => unreachable!(), + }; + + let value_span = ctx.ast_expressions.get_span(value); + let reference = + self.expression_for_reference(value, ctx.as_expression(block, &mut emitter))?; + let mut ectx = ctx.as_expression(block, &mut emitter); + + ectx.grow_types(reference.handle)?; + let (kind, width) = match *ectx.resolved_inner(reference.handle) { + crate::TypeInner::ValuePointer { + size: None, + kind, + width, + .. + } => (kind, width), + crate::TypeInner::Pointer { base, .. } => match ectx.module.types[base].inner { + crate::TypeInner::Scalar { kind, width } => (kind, width), + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), + }, + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), + }; + let constant_inner = crate::ConstantInner::Scalar { + width, + value: match kind { + crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), + crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), + }, + }; + let constant = ectx.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: constant_inner, + }, + Span::UNDEFINED, + ); + + let left = ectx.naga_expressions.append( + crate::Expression::Load { + pointer: reference.handle, + }, + value_span, + ); + let right = + ectx.interrupt_emitter(crate::Expression::Constant(constant), Span::UNDEFINED); + let value = ectx + .naga_expressions + .append(crate::Expression::Binary { op, left, right }, stmt.span); + + block.extend(emitter.finish(ctx.naga_expressions)); + crate::Statement::Store { + pointer: reference.handle, + value, + } + } + ast::StatementKind::Ignore(expr) => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let _ = self.expression(expr, ctx.as_expression(block, &mut emitter))?; + block.extend(emitter.finish(ctx.naga_expressions)); + return Ok(()); + } + }; + + block.push(out, stmt.span); + + Ok(()) + } + + fn expression( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let expr = self.expression_for_reference(expr, ctx.reborrow())?; + Ok(ctx.apply_load_rule(expr)) + } + + fn expression_for_reference( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result> { + let span = ctx.ast_expressions.get_span(expr); + let expr = &ctx.ast_expressions[expr]; + + let (expr, is_reference) = match *expr { + ast::Expression::Literal(literal) => { + let inner = match literal { + ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Float(f as _), + }, + ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Sint(i as _), + }, + ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(u as _), + }, + ast::Literal::Number(_) => { + unreachable!("got abstract numeric type when not expected"); + } + ast::Literal::Bool(b) => crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(b), + }, + }; + let handle = ctx.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + Span::UNDEFINED, + ); + let handle = ctx.interrupt_emitter(crate::Expression::Constant(handle), span); + return Ok(TypedExpression::non_reference(handle)); + } + ast::Expression::Ident(ast::IdentExpr::Local(local)) => { + return Ok(ctx.local_table[&local]) + } + ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { + return if let Some(global) = ctx.globals.get(name) { + let (expr, is_reference) = match *global { + LoweredGlobalDecl::Var(handle) => ( + crate::Expression::GlobalVariable(handle), + ctx.module.global_variables[handle].space + != crate::AddressSpace::Handle, + ), + LoweredGlobalDecl::Const(handle) => { + (crate::Expression::Constant(handle), false) + } + _ => { + return Err(Error::Unexpected(span, ExpectedToken::Variable)); + } + }; + + let handle = ctx.interrupt_emitter(expr, span); + Ok(TypedExpression { + handle, + is_reference, + }) + } else { + Err(Error::UnknownIdent(span, name)) + } + } + ast::Expression::Construct { + ref ty, + ty_span, + ref components, + } => { + let handle = self.construct(span, ty, ty_span, components, ctx.reborrow())?; + return Ok(TypedExpression::non_reference(handle)); + } + ast::Expression::Unary { op, expr } => { + let expr = self.expression(expr, ctx.reborrow())?; + (crate::Expression::Unary { op, expr }, false) + } + ast::Expression::AddrOf(expr) => { + // The `&` operator simply converts a reference to a pointer. And since a + // reference is required, the Load Rule is not applied. + let expr = self.expression_for_reference(expr, ctx.reborrow())?; + if !expr.is_reference { + return Err(Error::NotReference("the operand of the `&` operator", span)); + } + + // No code is generated. We just declare the pointer a reference now. + return Ok(TypedExpression { + is_reference: false, + ..expr + }); + } + ast::Expression::Deref(expr) => { + // The pointer we dereference must be loaded. + let pointer = self.expression(expr, ctx.reborrow())?; + + ctx.grow_types(pointer)?; + if ctx.resolved_inner(pointer).pointer_space().is_none() { + return Err(Error::NotPointer(span)); + } + + return Ok(TypedExpression { + handle: pointer, + is_reference: true, + }); + } + ast::Expression::Binary { op, left, right } => { + // Load both operands. + let mut left = self.expression(left, ctx.reborrow())?; + let mut right = self.expression(right, ctx.reborrow())?; + ctx.binary_op_splat(op, &mut left, &mut right)?; + (crate::Expression::Binary { op, left, right }, false) + } + ast::Expression::Call { + ref function, + ref arguments, + } => { + let handle = self + .call(span, function, arguments, ctx.reborrow())? + .ok_or(Error::FunctionReturnsVoid(function.span))?; + return Ok(TypedExpression::non_reference(handle)); + } + ast::Expression::Index { base, index } => { + let expr = self.expression_for_reference(base, ctx.reborrow())?; + let index = self.expression(index, ctx.reborrow())?; + + ctx.grow_types(expr.handle)?; + let wgsl_pointer = + ctx.resolved_inner(expr.handle).pointer_space().is_some() && !expr.is_reference; + + if wgsl_pointer { + return Err(Error::Pointer( + "the value indexed by a `[]` subscripting expression", + ctx.ast_expressions.get_span(base), + )); + } + + if let crate::Expression::Constant(constant) = ctx.naga_expressions[index] { + let span = ctx.naga_expressions.get_span(index); + let index = match ctx.module.constants[constant].inner { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Sint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), + _ => Err(Error::BadU32Constant(span)), + }?; + + ( + crate::Expression::AccessIndex { + base: expr.handle, + index, + }, + expr.is_reference, + ) + } else { + ( + crate::Expression::Access { + base: expr.handle, + index, + }, + expr.is_reference, + ) + } + } + ast::Expression::Member { base, ref field } => { + let TypedExpression { + handle, + is_reference, + } = self.expression_for_reference(base, ctx.reborrow())?; + + ctx.grow_types(handle)?; + let temp_inner; + let (composite, wgsl_pointer) = match *ctx.resolved_inner(handle) { + crate::TypeInner::Pointer { base, .. } => { + (&ctx.module.types[base].inner, !is_reference) + } + crate::TypeInner::ValuePointer { + size: None, + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Scalar { kind, width }; + (&temp_inner, !is_reference) + } + crate::TypeInner::ValuePointer { + size: Some(size), + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Vector { size, kind, width }; + (&temp_inner, !is_reference) + } + ref other => (other, false), + }; + + if wgsl_pointer { + return Err(Error::Pointer( + "the value accessed by a `.member` expression", + ctx.ast_expressions.get_span(base), + )); + } + + let access = match *composite { + crate::TypeInner::Struct { ref members, .. } => { + let index = members + .iter() + .position(|m| m.name.as_deref() == Some(field.name)) + .ok_or(Error::BadAccessor(field.span))? + as u32; + + ( + crate::Expression::AccessIndex { + base: handle, + index, + }, + is_reference, + ) + } + crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { + match Composition::make(field.name, field.span)? { + Composition::Multi(size, pattern) => { + let vector = ctx.apply_load_rule(TypedExpression { + handle, + is_reference, + }); + + ( + crate::Expression::Swizzle { + size, + vector, + pattern, + }, + false, + ) + } + Composition::Single(index) => ( + crate::Expression::AccessIndex { + base: handle, + index, + }, + is_reference, + ), + } + } + _ => return Err(Error::BadAccessor(field.span)), + }; + + access + } + ast::Expression::Bitcast { expr, to, ty_span } => { + let expr = self.expression(expr, ctx.reborrow())?; + let to_resolved = self.resolve_ast_type(to, ctx.as_output())?; + + let kind = match ctx.module.types[to_resolved].inner { + crate::TypeInner::Scalar { kind, .. } => kind, + crate::TypeInner::Vector { kind, .. } => kind, + _ => { + let ty = &ctx.typifier[expr]; + return Err(Error::BadTypeCast { + from_type: ctx.format_type_resolution(ty), + span: ty_span, + to_type: ctx.format_type(to_resolved), + }); + } + }; + + ( + crate::Expression::As { + expr, + kind, + convert: None, + }, + false, + ) + } + }; + + let handle = ctx.naga_expressions.append(expr, span); + Ok(TypedExpression { + handle, + is_reference, + }) + } + + /// Generate Naga IR for call expressions and statements, and type + /// constructor expressions. + /// + /// The "function" being called is simply an `Ident` that we know refers to + /// some module-scope definition. + /// + /// - If it is the name of a type, then the expression is a type constructor + /// expression: either constructing a value from components, a conversion + /// expression, or a zero value expression. + /// + /// - If it is the name of a function, then we're generating a [`Call`] + /// statement. We may be in the midst of generating code for an + /// expression, in which case we must generate an `Emit` statement to + /// force evaluation of the IR expressions we've generated so far, add the + /// `Call` statement to the current block, and then resume generating + /// expressions. + /// + /// [`Call`]: crate::Statement::Call + fn call( + &mut self, + span: Span, + function: &ast::Ident<'source>, + arguments: &[Handle>], + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result>, Error<'source>> { + match ctx.globals.get(function.name) { + Some(&LoweredGlobalDecl::Type(ty)) => { + let handle = self.construct( + span, + &ast::ConstructorType::Type(ty), + function.span, + arguments, + ctx.reborrow(), + )?; + Ok(Some(handle)) + } + Some(&LoweredGlobalDecl::Const(_) | &LoweredGlobalDecl::Var(_)) => { + Err(Error::Unexpected(function.span, ExpectedToken::Function)) + } + Some(&LoweredGlobalDecl::EntryPoint) => Err(Error::CalledEntryPoint(function.span)), + Some(&LoweredGlobalDecl::Function(function)) => { + let arguments = arguments + .iter() + .map(|&arg| self.expression(arg, ctx.reborrow())) + .collect::, _>>()?; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + let result = ctx.module.functions[function].result.is_some().then(|| { + ctx.naga_expressions + .append(crate::Expression::CallResult(function), span) + }); + ctx.emitter.start(ctx.naga_expressions); + ctx.block.push( + crate::Statement::Call { + function, + arguments, + result, + }, + span, + ); + + Ok(result) + } + None => { + let span = function.span; + let expr = if let Some(fun) = conv::map_relational_fun(function.name) { + let mut args = ctx.prepare_args(arguments, 1, span); + let argument = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::Relational { fun, argument } + } else if let Some(axis) = conv::map_derivative_axis(function.name) { + let mut args = ctx.prepare_args(arguments, 1, span); + let expr = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::Derivative { axis, expr } + } else if let Some(fun) = conv::map_standard_fun(function.name) { + let expected = fun.argument_count() as _; + let mut args = ctx.prepare_args(arguments, expected, span); + + let arg = self.expression(args.next()?, ctx.reborrow())?; + let arg1 = args + .next() + .map(|x| self.expression(x, ctx.reborrow())) + .ok() + .transpose()?; + let arg2 = args + .next() + .map(|x| self.expression(x, ctx.reborrow())) + .ok() + .transpose()?; + let arg3 = args + .next() + .map(|x| self.expression(x, ctx.reborrow())) + .ok() + .transpose()?; + + args.finish()?; + + crate::Expression::Math { + fun, + arg, + arg1, + arg2, + arg3, + } + } else if let Some(fun) = Texture::map(function.name) { + self.texture_sample_helper(fun, arguments, span, ctx.reborrow())? + } else { + match function.name { + "select" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let reject = self.expression(args.next()?, ctx.reborrow())?; + let accept = self.expression(args.next()?, ctx.reborrow())?; + let condition = self.expression(args.next()?, ctx.reborrow())?; + + args.finish()?; + + crate::Expression::Select { + reject, + accept, + condition, + } + } + "arrayLength" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let expr = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ArrayLength(expr) + } + "atomicLoad" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::Load { pointer } + } + "atomicStore" => { + let mut args = ctx.prepare_args(arguments, 2, span); + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + let value = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + ctx.emitter.start(ctx.naga_expressions); + ctx.block + .push(crate::Statement::Store { pointer, value }, span); + return Ok(None); + } + "atomicAdd" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Add, + arguments, + ctx.reborrow(), + )?)) + } + "atomicSub" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Subtract, + arguments, + ctx.reborrow(), + )?)) + } + "atomicAnd" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::And, + arguments, + ctx.reborrow(), + )?)) + } + "atomicOr" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::InclusiveOr, + arguments, + ctx.reborrow(), + )?)) + } + "atomicXor" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::ExclusiveOr, + arguments, + ctx.reborrow(), + )?)) + } + "atomicMin" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Min, + arguments, + ctx.reborrow(), + )?)) + } + "atomicMax" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Max, + arguments, + ctx.reborrow(), + )?)) + } + "atomicExchange" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Exchange { compare: None }, + arguments, + ctx.reborrow(), + )?)) + } + "atomicCompareExchangeWeak" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + + let compare = self.expression(args.next()?, ctx.reborrow())?; + + let value = args.next()?; + let value_span = ctx.ast_expressions.get_span(value); + let value = self.expression(value, ctx.reborrow())?; + ctx.grow_types(value)?; + + args.finish()?; + + let expression = match *ctx.resolved_inner(value) { + crate::TypeInner::Scalar { kind, width } => { + let bool_ty = ctx.module.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }, + }, + Span::UNDEFINED, + ); + let scalar_ty = ctx.module.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind, width }, + }, + Span::UNDEFINED, + ); + let struct_ty = ctx.module.types.insert( + crate::Type { + name: Some( + "__atomic_compare_exchange_result".to_string(), + ), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("old_value".to_string()), + ty: scalar_ty, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("exchanged".to_string()), + ty: bool_ty, + binding: None, + offset: 4, + }, + ], + span: 8, + }, + }, + Span::UNDEFINED, + ); + crate::Expression::AtomicResult { + ty: struct_ty, + comparison: true, + } + } + _ => return Err(Error::InvalidAtomicOperandType(value_span)), + }; + + let result = ctx.interrupt_emitter(expression, span); + ctx.block.push( + crate::Statement::Atomic { + pointer, + fun: crate::AtomicFunction::Exchange { + compare: Some(compare), + }, + value, + result, + }, + span, + ); + return Ok(Some(result)); + } + "storageBarrier" => { + ctx.prepare_args(arguments, 0, span).finish()?; + + ctx.block + .push(crate::Statement::Barrier(crate::Barrier::STORAGE), span); + return Ok(None); + } + "workgroupBarrier" => { + ctx.prepare_args(arguments, 0, span).finish()?; + + ctx.block + .push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP), span); + return Ok(None); + } + "textureStore" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let image = args.next()?; + let image_span = ctx.ast_expressions.get_span(image); + let image = self.expression(image, ctx.reborrow())?; + + let coordinate = self.expression(args.next()?, ctx.reborrow())?; + + let (_, arrayed) = ctx.image_data(image, image_span)?; + let array_index = arrayed + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let value = self.expression(args.next()?, ctx.reborrow())?; + + args.finish()?; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + ctx.emitter.start(ctx.naga_expressions); + let stmt = crate::Statement::ImageStore { + image, + coordinate, + array_index, + value, + }; + ctx.block.push(stmt, span); + return Ok(None); + } + "textureLoad" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let image = args.next()?; + let image_span = ctx.ast_expressions.get_span(image); + let image = self.expression(image, ctx.reborrow())?; + + let coordinate = self.expression(args.next()?, ctx.reborrow())?; + + let (class, arrayed) = ctx.image_data(image, image_span)?; + let array_index = arrayed + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let level = class + .is_mipmapped() + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let sample = class + .is_multisampled() + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + args.finish()?; + + crate::Expression::ImageLoad { + image, + coordinate, + array_index, + level, + sample, + } + } + "textureDimensions" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + let level = args + .next() + .map(|arg| self.expression(arg, ctx.reborrow())) + .ok() + .transpose()?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::Size { level }, + } + } + "textureNumLevels" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumLevels, + } + } + "textureNumLayers" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumLayers, + } + } + "textureNumSamples" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumSamples, + } + } + _ => return Err(Error::UnknownIdent(function.span, function.name)), + } + }; + + let expr = ctx.naga_expressions.append(expr, span); + Ok(Some(expr)) + } + } + } + + fn atomic_pointer( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let span = ctx.ast_expressions.get_span(expr); + let pointer = self.expression(expr, ctx.reborrow())?; + + ctx.grow_types(pointer)?; + match *ctx.resolved_inner(pointer) { + crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { + crate::TypeInner::Atomic { .. } => Ok(pointer), + ref other => { + log::error!("Pointer type to {:?} passed to atomic op", other); + Err(Error::InvalidAtomicPointer(span)) + } + }, + ref other => { + log::error!("Type {:?} passed to atomic op", other); + Err(Error::InvalidAtomicPointer(span)) + } + } + } + + fn atomic_helper( + &mut self, + span: Span, + fun: crate::AtomicFunction, + args: &[Handle>], + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let mut args = ctx.prepare_args(args, 2, span); + + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + + let value = args.next()?; + let value = self.expression(value, ctx.reborrow())?; + let ty = ctx.register_type(value)?; + + args.finish()?; + + let result = ctx.interrupt_emitter( + crate::Expression::AtomicResult { + ty, + comparison: false, + }, + span, + ); + ctx.block.push( + crate::Statement::Atomic { + pointer, + fun, + value, + result, + }, + span, + ); + Ok(result) + } + + fn texture_sample_helper( + &mut self, + fun: Texture, + args: &[Handle>], + span: Span, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result> { + let mut args = ctx.prepare_args(args, fun.min_argument_count(), span); + + let (image, gather) = match fun { + Texture::Gather => { + let image_or_component = args.next()?; + match self.gather_component(image_or_component, ctx.reborrow())? { + Some(component) => { + let image = args.next()?; + (image, Some(component)) + } + None => (image_or_component, Some(crate::SwizzleComponent::X)), + } + } + Texture::GatherCompare => { + let image = args.next()?; + (image, Some(crate::SwizzleComponent::X)) + } + + _ => { + let image = args.next()?; + (image, None) + } + }; + + let image_span = ctx.ast_expressions.get_span(image); + let image = self.expression(image, ctx.reborrow())?; + + let sampler = self.expression(args.next()?, ctx.reborrow())?; + + let coordinate = self.expression(args.next()?, ctx.reborrow())?; + + let (_, arrayed) = ctx.image_data(image, image_span)?; + let array_index = arrayed + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let (level, depth_ref) = match fun { + Texture::Gather => (crate::SampleLevel::Zero, None), + Texture::GatherCompare => { + let reference = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Zero, Some(reference)) + } + + Texture::Sample => (crate::SampleLevel::Auto, None), + Texture::SampleBias => { + let bias = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Bias(bias), None) + } + Texture::SampleCompare => { + let reference = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Auto, Some(reference)) + } + Texture::SampleCompareLevel => { + let reference = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Zero, Some(reference)) + } + Texture::SampleGrad => { + let x = self.expression(args.next()?, ctx.reborrow())?; + let y = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Gradient { x, y }, None) + } + Texture::SampleLevel => { + let level = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Exact(level), None) + } + }; + + let offset = args + .next() + .map(|arg| self.constant(arg, ctx.as_output())) + .ok() + .transpose()?; + + args.finish()?; + + Ok(crate::Expression::ImageSample { + image, + sampler, + gather, + coordinate, + array_index, + offset, + level, + depth_ref, + }) + } + + fn gather_component( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let span = ctx.ast_expressions.get_span(expr); + + let constant = match self.constant_inner(expr, ctx.as_output()).ok() { + Some(ConstantOrInner::Constant(c)) => ctx.module.constants[c].inner.clone(), + Some(ConstantOrInner::Inner(inner)) => inner, + None => return Ok(None), + }; + + let int = match constant { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Sint(i), + .. + } if i >= 0 => i as u64, + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(i), + .. + } => i, + _ => { + return Err(Error::InvalidGatherComponent(span)); + } + }; + + crate::SwizzleComponent::XYZW + .get(int as usize) + .copied() + .map(Some) + .ok_or(Error::InvalidGatherComponent(span)) + } + + fn r#struct( + &mut self, + s: &ast::Struct<'source>, + span: Span, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let mut offset = 0; + let mut struct_alignment = Alignment::ONE; + let mut members = Vec::with_capacity(s.members.len()); + + for member in s.members.iter() { + let ty = self.resolve_ast_type(member.ty, ctx.reborrow())?; + + self.layouter + .update(&ctx.module.types, &ctx.module.constants) + .unwrap(); + + let member_min_size = self.layouter[ty].size; + let member_min_alignment = self.layouter[ty].alignment; + + let member_size = if let Some((size, span)) = member.size { + if size < member_min_size { + return Err(Error::SizeAttributeTooLow(span, member_min_size)); + } else { + size + } + } else { + member_min_size + }; + + let member_alignment = if let Some((align, span)) = member.align { + if let Some(alignment) = Alignment::new(align) { + if alignment < member_min_alignment { + return Err(Error::AlignAttributeTooLow(span, member_min_alignment)); + } else { + alignment + } + } else { + return Err(Error::NonPowerOfTwoAlignAttribute(span)); + } + } else { + member_min_alignment + }; + + let binding = self.interpolate_default(&member.binding, ty, ctx.reborrow()); + + offset = member_alignment.round_up(offset); + struct_alignment = struct_alignment.max(member_alignment); + + members.push(crate::StructMember { + name: Some(member.name.name.to_owned()), + ty, + binding, + offset, + }); + + offset += member_size; + } + + let size = struct_alignment.round_up(offset); + let inner = crate::TypeInner::Struct { + members, + span: size, + }; + + let handle = ctx.module.types.insert( + crate::Type { + name: Some(s.name.name.to_string()), + inner, + }, + span, + ); + Ok(handle) + } + + /// Return a Naga `Handle` representing the front-end type `handle`. + fn resolve_ast_type( + &mut self, + handle: Handle>, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let inner = match ctx.types[handle] { + ast::Type::Scalar { kind, width } => crate::TypeInner::Scalar { kind, width }, + ast::Type::Vector { size, kind, width } => { + crate::TypeInner::Vector { size, kind, width } + } + ast::Type::Matrix { + rows, + columns, + width, + } => crate::TypeInner::Matrix { + columns, + rows, + width, + }, + ast::Type::Atomic { kind, width } => crate::TypeInner::Atomic { kind, width }, + ast::Type::Pointer { base, space } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + crate::TypeInner::Pointer { base, space } + } + ast::Type::Array { base, size } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + self.layouter + .update(&ctx.module.types, &ctx.module.constants) + .unwrap(); + + crate::TypeInner::Array { + base, + size: match size { + ast::ArraySize::Constant(constant) => { + let constant = self.constant(constant, ctx.reborrow())?; + crate::ArraySize::Constant(constant) + } + ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, + }, + stride: self.layouter[base].to_stride(), + } + } + ast::Type::Image { + dim, + arrayed, + class, + } => crate::TypeInner::Image { + dim, + arrayed, + class, + }, + ast::Type::Sampler { comparison } => crate::TypeInner::Sampler { comparison }, + ast::Type::BindingArray { base, size } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + + crate::TypeInner::BindingArray { + base, + size: match size { + ast::ArraySize::Constant(constant) => { + let constant = self.constant(constant, ctx.reborrow())?; + crate::ArraySize::Constant(constant) + } + ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, + }, + } + } + ast::Type::User(ref ident) => { + return match ctx.globals.get(ident.name) { + Some(&LoweredGlobalDecl::Type(handle)) => Ok(handle), + Some(_) => Err(Error::Unexpected(ident.span, ExpectedToken::Type)), + None => Err(Error::UnknownType(ident.span)), + } + } + }; + + Ok(ctx.ensure_type_exists(inner)) + } + + /// Find or construct a Naga [`Constant`] whose value is `expr`. + /// + /// The `ctx` indicates the Naga [`Module`] to which we should add + /// new `Constant`s or [`Type`]s as needed. + /// + /// [`Module`]: crate::Module + /// [`Constant`]: crate::Constant + /// [`Type`]: crate::Type + fn constant( + &mut self, + expr: Handle>, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let inner = match self.constant_inner(expr, ctx.reborrow())? { + ConstantOrInner::Constant(c) => return Ok(c), + ConstantOrInner::Inner(inner) => inner, + }; + + let c = ctx.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + Span::UNDEFINED, + ); + Ok(c) + } + + fn constant_inner( + &mut self, + expr: Handle>, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result> { + let span = ctx.ast_expressions.get_span(expr); + let inner = match ctx.ast_expressions[expr] { + ast::Expression::Literal(literal) => match literal { + ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Float(f as _), + }, + ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Sint(i as _), + }, + ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(u as _), + }, + ast::Literal::Number(_) => { + unreachable!("got abstract numeric type when not expected"); + } + ast::Literal::Bool(b) => crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(b), + }, + }, + ast::Expression::Ident(ast::IdentExpr::Local(_)) => { + return Err(Error::Unexpected(span, ExpectedToken::Constant)) + } + ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { + return if let Some(global) = ctx.globals.get(name) { + match *global { + LoweredGlobalDecl::Const(handle) => Ok(ConstantOrInner::Constant(handle)), + _ => Err(Error::Unexpected(span, ExpectedToken::Constant)), + } + } else { + Err(Error::UnknownIdent(span, name)) + } + } + ast::Expression::Construct { + ref ty, + ref components, + .. + } => self.const_construct(span, ty, components, ctx.reborrow())?, + ast::Expression::Call { + ref function, + ref arguments, + } => match ctx.globals.get(function.name) { + Some(&LoweredGlobalDecl::Type(ty)) => self.const_construct( + span, + &ast::ConstructorType::Type(ty), + arguments, + ctx.reborrow(), + )?, + Some(_) => return Err(Error::ConstExprUnsupported(span)), + None => return Err(Error::UnknownIdent(function.span, function.name)), + }, + _ => return Err(Error::ConstExprUnsupported(span)), + }; + + Ok(ConstantOrInner::Inner(inner)) + } + + fn interpolate_default( + &mut self, + binding: &Option, + ty: Handle, + ctx: OutputContext<'source, '_, '_>, + ) -> Option { + let mut binding = binding.clone(); + if let Some(ref mut binding) = binding { + binding.apply_default_interpolation(&ctx.module.types[ty].inner); + } + + binding + } +} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7e2826845..8ac82fe45 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -4,648 +4,48 @@ Frontend for [WGSL][wgsl] (WebGPU Shading Language). [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html */ -mod ast; -mod construction; -mod conv; +mod error; mod index; -mod lexer; -mod number; +mod lower; +mod parse; #[cfg(test)] mod tests; -use crate::{ - arena::{Arena, Handle, UniqueArena}, - proc::{ - ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution, - }, - span::SourceLocation, - FastHashMap, FastHashSet, Span, -}; +use crate::arena::{Arena, UniqueArena}; -use self::{lexer::Lexer, number::Number}; -use codespan_reporting::{ - diagnostic::{Diagnostic, Label}, - files::SimpleFile, - term::{ - self, - termcolor::{ColorChoice, NoColor, StandardStream}, - }, -}; -use std::{borrow::Cow, convert::TryFrom, ops::Range}; +use crate::front::wgsl::error::Error; +use crate::front::wgsl::parse::Parser; use thiserror::Error; -type TokenSpan<'a> = (Token<'a>, Span); +pub use crate::front::wgsl::error::ParseError; +use crate::front::wgsl::lower::Lowerer; -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum Token<'a> { - Separator(char), - Paren(char), - Attribute, - Number(Result), - Word(&'a str), - Operation(char), - LogicalOperation(char), - ShiftOperation(char), - AssignmentOperation(char), - IncrementOperation, - DecrementOperation, - Arrow, - Unknown(char), - Trivia, - End, +pub struct Frontend { + parser: Parser, } -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum NumberType { - I32, - U32, - F32, -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum ExpectedToken<'a> { - Token(Token<'a>), - Identifier, - Number(NumberType), - Integer, - /// A compile-time constant expression. - Constant, - /// Expected: constant, parenthesized expression, identifier - PrimaryExpression, - /// Expected: assignment, increment/decrement expression - Assignment, - /// Expected: '}', identifier - FieldName, - /// Expected: 'case', 'default', '}' - SwitchItem, - /// Expected: ',', ')' - WorkgroupSizeSeparator, - /// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof - GlobalItem, - /// Expected a type. - Type, - /// Access of `var`, `let`, `const`. - Variable, - /// Access of a function - Function, -} - -#[derive(Clone, Copy, Debug, Error, PartialEq)] -pub enum NumberError { - #[error("invalid numeric literal format")] - Invalid, - #[error("numeric literal not representable by target type")] - NotRepresentable, - #[error("unimplemented f16 type")] - UnimplementedF16, -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum InvalidAssignmentType { - Other, - Swizzle, - ImmutableBinding, -} - -#[derive(Clone, Debug)] -pub enum Error<'a> { - Unexpected(Span, ExpectedToken<'a>), - UnexpectedComponents(Span), - BadNumber(Span, NumberError), - /// A negative signed integer literal where both signed and unsigned, - /// but only non-negative literals are allowed. - NegativeInt(Span), - BadU32Constant(Span), - BadMatrixScalarKind(Span, crate::ScalarKind, u8), - BadAccessor(Span), - BadTexture(Span), - BadTypeCast { - span: Span, - from_type: String, - to_type: String, - }, - BadTextureSampleType { - span: Span, - kind: crate::ScalarKind, - width: u8, - }, - BadIncrDecrReferenceType(Span), - InvalidResolve(ResolveError), - InvalidForInitializer(Span), - /// A break if appeared outside of a continuing block - InvalidBreakIf(Span), - InvalidGatherComponent(Span), - InvalidConstructorComponentType(Span, i32), - InvalidIdentifierUnderscore(Span), - ReservedIdentifierPrefix(Span), - UnknownAddressSpace(Span), - UnknownAttribute(Span), - UnknownBuiltin(Span), - UnknownAccess(Span), - UnknownIdent(Span, &'a str), - UnknownScalarType(Span), - UnknownType(Span), - UnknownStorageFormat(Span), - UnknownConservativeDepth(Span), - SizeAttributeTooLow(Span, u32), - AlignAttributeTooLow(Span, Alignment), - NonPowerOfTwoAlignAttribute(Span), - InconsistentBinding(Span), - TypeNotConstructible(Span), - TypeNotInferrable(Span), - InitializationTypeMismatch(Span, String, String), - MissingType(Span), - MissingAttribute(&'static str, Span), - InvalidAtomicPointer(Span), - InvalidAtomicOperandType(Span), - Pointer(&'static str, Span), - NotPointer(Span), - NotReference(&'static str, Span), - InvalidAssignment { - span: Span, - ty: InvalidAssignmentType, - }, - ReservedKeyword(Span), - /// Redefinition of an identifier (used for both module-scope and local redefinitions). - Redefinition { - /// Span of the identifier in the previous definition. - previous: Span, - - /// Span of the identifier in the new definition. - current: Span, - }, - /// A declaration refers to itself directly. - RecursiveDeclaration { - /// The location of the name of the declaration. - ident: Span, - - /// The point at which it is used. - usage: Span, - }, - /// A declaration refers to itself indirectly, through one or more other - /// definitions. - CyclicDeclaration { - /// The location of the name of some declaration in the cycle. - ident: Span, - - /// The edges of the cycle of references. - /// - /// Each `(decl, reference)` pair indicates that the declaration whose - /// name is `decl` has an identifier at `reference` whose definition is - /// the next declaration in the cycle. The last pair's `reference` is - /// the same identifier as `ident`, above. - path: Vec<(Span, Span)>, - }, - ConstExprUnsupported(Span), - InvalidSwitchValue { - uint: bool, - span: Span, - }, - CalledEntryPoint(Span), - WrongArgumentCount { - span: Span, - expected: Range, - found: u32, - }, - FunctionReturnsVoid(Span), - Other, -} - -impl<'a> Error<'a> { - fn as_parse_error(&self, source: &'a str) -> ParseError { - match *self { - Error::Unexpected(unexpected_span, expected) => { - let expected_str = match expected { - ExpectedToken::Token(token) => { - match token { - Token::Separator(c) => format!("'{c}'"), - Token::Paren(c) => format!("'{c}'"), - Token::Attribute => "@".to_string(), - Token::Number(_) => "number".to_string(), - Token::Word(s) => s.to_string(), - Token::Operation(c) => format!("operation ('{c}')"), - Token::LogicalOperation(c) => format!("logical operation ('{c}')"), - Token::ShiftOperation(c) => format!("bitshift ('{c}{c}')"), - Token::AssignmentOperation(c) if c=='<' || c=='>' => format!("bitshift ('{c}{c}=')"), - Token::AssignmentOperation(c) => format!("operation ('{c}=')"), - Token::IncrementOperation => "increment operation".to_string(), - Token::DecrementOperation => "decrement operation".to_string(), - Token::Arrow => "->".to_string(), - Token::Unknown(c) => format!("unknown ('{c}')"), - Token::Trivia => "trivia".to_string(), - Token::End => "end".to_string(), - } - } - ExpectedToken::Identifier => "identifier".to_string(), - ExpectedToken::Number(ty) => { - match ty { - NumberType::I32 => "32-bit signed integer literal", - NumberType::U32 => "32-bit unsigned integer literal", - NumberType::F32 => "32-bit floating-point literal", - }.to_string() - }, - ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), - ExpectedToken::Constant => "compile-time constant".to_string(), - ExpectedToken::PrimaryExpression => "expression".to_string(), - ExpectedToken::Assignment => "assignment or increment/decrement".to_string(), - ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(), - ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), - ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), - ExpectedToken::GlobalItem => "global item ('struct', 'const', 'var', 'type', ';', 'fn') or the end of the file".to_string(), - ExpectedToken::Type => "type".to_string(), - ExpectedToken::Variable => "variable access".to_string(), - ExpectedToken::Function => "function name".to_string(), - }; - ParseError { - message: format!( - "expected {}, found '{}'", - expected_str, &source[unexpected_span], - ), - labels: vec![(unexpected_span, format!("expected {expected_str}").into())], - notes: vec![], - } - } - Error::UnexpectedComponents(bad_span) => ParseError { - message: "unexpected components".to_string(), - labels: vec![(bad_span, "unexpected components".into())], - notes: vec![], - }, - Error::BadNumber(bad_span, ref err) => ParseError { - message: format!("{}: `{}`", err, &source[bad_span],), - labels: vec![(bad_span, err.to_string().into())], - notes: vec![], - }, - Error::NegativeInt(bad_span) => ParseError { - message: format!( - "expected non-negative integer literal, found `{}`", - &source[bad_span], - ), - labels: vec![(bad_span, "expected non-negative integer".into())], - notes: vec![], - }, - Error::BadU32Constant(bad_span) => ParseError { - message: format!( - "expected unsigned integer constant expression, found `{}`", - &source[bad_span], - ), - labels: vec![(bad_span, "expected unsigned integer".into())], - notes: vec![], - }, - Error::BadMatrixScalarKind(span, kind, width) => ParseError { - message: format!( - "matrix scalar type must be floating-point, but found `{}`", - kind.to_wgsl(width) - ), - labels: vec![(span, "must be floating-point (e.g. `f32`)".into())], - notes: vec![], - }, - Error::BadAccessor(accessor_span) => ParseError { - message: format!("invalid field accessor `{}`", &source[accessor_span],), - labels: vec![(accessor_span, "invalid accessor".into())], - notes: vec![], - }, - Error::UnknownIdent(ident_span, ident) => ParseError { - message: format!("no definition in scope for identifier: '{ident}'"), - labels: vec![(ident_span, "unknown identifier".into())], - notes: vec![], - }, - Error::UnknownScalarType(bad_span) => ParseError { - message: format!("unknown scalar type: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown scalar type".into())], - notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()], - }, - Error::BadTextureSampleType { span, kind, width } => ParseError { - message: format!( - "texture sample type must be one of f32, i32 or u32, but found {}", - kind.to_wgsl(width) - ), - labels: vec![(span, "must be one of f32, i32 or u32".into())], - notes: vec![], - }, - Error::BadIncrDecrReferenceType(span) => ParseError { - message: - "increment/decrement operation requires reference type to be one of i32 or u32" - .to_string(), - labels: vec![(span, "must be a reference type of i32 or u32".into())], - notes: vec![], - }, - Error::BadTexture(bad_span) => ParseError { - message: format!( - "expected an image, but found '{}' which is not an image", - &source[bad_span] - ), - labels: vec![(bad_span, "not an image".into())], - notes: vec![], - }, - Error::BadTypeCast { - span, - ref from_type, - ref to_type, - } => { - let msg = format!("cannot cast a {from_type} to a {to_type}"); - ParseError { - message: msg.clone(), - labels: vec![(span, msg.into())], - notes: vec![], - } - } - Error::InvalidResolve(ref resolve_error) => ParseError { - message: resolve_error.to_string(), - labels: vec![], - notes: vec![], - }, - Error::InvalidForInitializer(bad_span) => ParseError { - message: format!( - "for(;;) initializer is not an assignment or a function call: '{}'", - &source[bad_span] - ), - labels: vec![(bad_span, "not an assignment or function call".into())], - notes: vec![], - }, - Error::InvalidBreakIf(bad_span) => ParseError { - message: "A break if is only allowed in a continuing block".to_string(), - labels: vec![(bad_span, "not in a continuing block".into())], - notes: vec![], - }, - Error::InvalidGatherComponent(bad_span) => ParseError { - message: format!( - "textureGather component '{}' doesn't exist, must be 0, 1, 2, or 3", - &source[bad_span] - ), - labels: vec![(bad_span, "invalid component".into())], - notes: vec![], - }, - Error::InvalidConstructorComponentType(bad_span, component) => ParseError { - message: format!("invalid type for constructor component at index [{component}]"), - labels: vec![(bad_span, "invalid component type".into())], - notes: vec![], - }, - Error::InvalidIdentifierUnderscore(bad_span) => ParseError { - message: "Identifier can't be '_'".to_string(), - labels: vec![(bad_span, "invalid identifier".into())], - notes: vec![ - "Use phony assignment instead ('_ =' notice the absence of 'let' or 'var')" - .to_string(), - ], - }, - Error::ReservedIdentifierPrefix(bad_span) => ParseError { - message: format!( - "Identifier starts with a reserved prefix: '{}'", - &source[bad_span] - ), - labels: vec![(bad_span, "invalid identifier".into())], - notes: vec![], - }, - Error::UnknownAddressSpace(bad_span) => ParseError { - message: format!("unknown address space: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown address space".into())], - notes: vec![], - }, - Error::UnknownAttribute(bad_span) => ParseError { - message: format!("unknown attribute: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown attribute".into())], - notes: vec![], - }, - Error::UnknownBuiltin(bad_span) => ParseError { - message: format!("unknown builtin: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown builtin".into())], - notes: vec![], - }, - Error::UnknownAccess(bad_span) => ParseError { - message: format!("unknown access: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown access".into())], - notes: vec![], - }, - Error::UnknownStorageFormat(bad_span) => ParseError { - message: format!("unknown storage format: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown storage format".into())], - notes: vec![], - }, - Error::UnknownConservativeDepth(bad_span) => ParseError { - message: format!("unknown conservative depth: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown conservative depth".into())], - notes: vec![], - }, - Error::UnknownType(bad_span) => ParseError { - message: format!("unknown type: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown type".into())], - notes: vec![], - }, - Error::SizeAttributeTooLow(bad_span, min_size) => ParseError { - message: format!("struct member size must be at least {min_size}"), - labels: vec![(bad_span, format!("must be at least {min_size}").into())], - notes: vec![], - }, - Error::AlignAttributeTooLow(bad_span, min_align) => ParseError { - message: format!("struct member alignment must be at least {min_align}"), - labels: vec![(bad_span, format!("must be at least {min_align}").into())], - notes: vec![], - }, - Error::NonPowerOfTwoAlignAttribute(bad_span) => ParseError { - message: "struct member alignment must be a power of 2".to_string(), - labels: vec![(bad_span, "must be a power of 2".into())], - notes: vec![], - }, - Error::InconsistentBinding(span) => ParseError { - message: "input/output binding is not consistent".to_string(), - labels: vec![(span, "input/output binding is not consistent".into())], - notes: vec![], - }, - Error::TypeNotConstructible(span) => ParseError { - message: format!("type `{}` is not constructible", &source[span]), - labels: vec![(span, "type is not constructible".into())], - notes: vec![], - }, - Error::TypeNotInferrable(span) => ParseError { - message: "type can't be inferred".to_string(), - labels: vec![(span, "type can't be inferred".into())], - notes: vec![], - }, - Error::InitializationTypeMismatch(name_span, ref expected_ty, ref got_ty) => { - ParseError { - message: format!( - "the type of `{}` is expected to be `{}`, but got `{}`", - &source[name_span], expected_ty, got_ty, - ), - labels: vec![( - name_span, - format!("definition of `{}`", &source[name_span]).into(), - )], - notes: vec![], - } - } - Error::MissingType(name_span) => ParseError { - message: format!("variable `{}` needs a type", &source[name_span]), - labels: vec![( - name_span, - format!("definition of `{}`", &source[name_span]).into(), - )], - notes: vec![], - }, - Error::MissingAttribute(name, name_span) => ParseError { - message: format!( - "variable `{}` needs a '{}' attribute", - &source[name_span], name - ), - labels: vec![( - name_span, - format!("definition of `{}`", &source[name_span]).into(), - )], - notes: vec![], - }, - Error::InvalidAtomicPointer(span) => ParseError { - message: "atomic operation is done on a pointer to a non-atomic".to_string(), - labels: vec![(span, "atomic pointer is invalid".into())], - notes: vec![], - }, - Error::InvalidAtomicOperandType(span) => ParseError { - message: "atomic operand type is inconsistent with the operation".to_string(), - labels: vec![(span, "atomic operand type is invalid".into())], - notes: vec![], - }, - Error::NotPointer(span) => ParseError { - message: "the operand of the `*` operator must be a pointer".to_string(), - labels: vec![(span, "expression is not a pointer".into())], - notes: vec![], - }, - Error::NotReference(what, span) => ParseError { - message: format!("{what} must be a reference"), - labels: vec![(span, "expression is not a reference".into())], - notes: vec![], - }, - Error::InvalidAssignment { span, ty } => ParseError { - message: "invalid left-hand side of assignment".into(), - labels: vec![(span, "cannot assign to this expression".into())], - notes: match ty { - InvalidAssignmentType::Swizzle => vec![ - "WGSL does not support assignments to swizzles".into(), - "consider assigning each component individually".into(), - ], - InvalidAssignmentType::ImmutableBinding => vec![ - format!("'{}' is an immutable binding", &source[span]), - "consider declaring it with `var` instead of `let`".into(), - ], - InvalidAssignmentType::Other => vec![], - }, - }, - Error::Pointer(what, span) => ParseError { - message: format!("{what} must not be a pointer"), - labels: vec![(span, "expression is a pointer".into())], - notes: vec![], - }, - Error::ReservedKeyword(name_span) => ParseError { - message: format!("name `{}` is a reserved keyword", &source[name_span]), - labels: vec![( - name_span, - format!("definition of `{}`", &source[name_span]).into(), - )], - notes: vec![], - }, - Error::Redefinition { previous, current } => ParseError { - message: format!("redefinition of `{}`", &source[current]), - labels: vec![ - ( - current, - format!("redefinition of `{}`", &source[current]).into(), - ), - ( - previous, - format!("previous definition of `{}`", &source[previous]).into(), - ), - ], - notes: vec![], - }, - Error::RecursiveDeclaration { ident, usage } => ParseError { - message: format!("declaration of `{}` is recursive", &source[ident]), - labels: vec![(ident, "".into()), (usage, "uses itself here".into())], - notes: vec![], - }, - Error::CyclicDeclaration { ident, ref path } => ParseError { - message: format!("declaration of `{}` is cyclic", &source[ident]), - labels: path - .iter() - .enumerate() - .flat_map(|(i, &(ident, usage))| { - [ - (ident, "".into()), - ( - usage, - if i == path.len() - 1 { - "ending the cycle".into() - } else { - format!("uses `{}`", &source[ident]).into() - }, - ), - ] - }) - .collect(), - notes: vec![], - }, - Error::ConstExprUnsupported(span) => ParseError { - message: "this constant expression is not supported".to_string(), - labels: vec![(span, "expression is not supported".into())], - notes: vec![ - "this should be fixed in a future version of Naga".into(), - "https://github.com/gfx-rs/naga/issues/1829".into(), - ], - }, - Error::InvalidSwitchValue { uint, span } => ParseError { - message: "invalid switch value".to_string(), - labels: vec![( - span, - if uint { - "expected unsigned integer" - } else { - "expected signed integer" - } - .into(), - )], - notes: vec![if uint { - format!("suffix the integer with a `u`: '{}u'", &source[span]) - } else { - let span = span.to_range().unwrap(); - format!( - "remove the `u` suffix: '{}'", - &source[span.start..span.end - 1] - ) - }], - }, - Error::CalledEntryPoint(span) => ParseError { - message: "entry point cannot be called".to_string(), - labels: vec![(span, "entry point cannot be called".into())], - notes: vec![], - }, - Error::WrongArgumentCount { - span, - ref expected, - found, - } => ParseError { - message: format!( - "wrong number of arguments: expected {}, found {}", - if expected.len() < 2 { - format!("{}", expected.start) - } else { - format!("{}..{}", expected.start, expected.end) - }, - found - ), - labels: vec![(span, "wrong number of arguments".into())], - notes: vec![], - }, - Error::FunctionReturnsVoid(span) => ParseError { - message: "function does not return any value".to_string(), - labels: vec![(span, "".into())], - notes: vec![ - "perhaps you meant to call the function in a separate statement?".into(), - ], - }, - Error::Other => ParseError { - message: "other error".to_string(), - labels: vec![], - notes: vec![], - }, +impl Frontend { + pub const fn new() -> Self { + Self { + parser: Parser::new(), } } + + pub fn parse(&mut self, source: &str) -> Result { + self.inner(source).map_err(|x| x.as_parse_error(source)) + } + + fn inner<'a>(&mut self, source: &'a str) -> Result> { + let tu = self.parser.parse(source)?; + let index = index::Index::generate(&tu)?; + let module = Lowerer::new(&index).lower(&tu)?; + + Ok(module) + } +} + +pub fn parse_str(source: &str) -> Result { + Frontend::new().parse(source) } impl crate::StorageFormat { @@ -936,4512 +336,3 @@ impl crate::ScalarKind { format!("{}{}", prefix, width * 8) } } - -/// State for constructing an AST expression. -struct ParseExpressionContext<'input, 'temp, 'out> { - /// The [`TranslationUnit::expressions`] arena to which we should contribute - /// expressions. - /// - /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions - expressions: &'out mut Arena>, - - /// The [`TranslationUnit::types`] arena to which we should contribute new - /// types. - /// - /// [`TranslationUnit::types`]: ast::TranslationUnit::types - types: &'out mut Arena>, - - /// A map from identifiers in scope to the locals/arguments they represent. - /// - /// The handles refer to the [`Function::locals`] area; see that field's - /// documentation for details. - /// - /// [`Function::locals`]: ast::Function::locals - local_table: &'temp mut super::SymbolTable<&'input str, Handle>, - - /// The [`Function::locals`] arena for the function we're building. - /// - /// [`Function::locals`]: ast::Function::locals - locals: &'out mut Arena, - - /// Identifiers used by the current global declaration that have no local definition. - /// - /// This becomes the [`GlobalDecl`]'s [`dependencies`] set. - /// - /// Note that we don't know at parse time what kind of [`GlobalDecl`] the - /// name refers to. We can't look up names until we've seen the entire - /// translation unit. - /// - /// [`GlobalDecl`]: ast::GlobalDecl - /// [`dependencies`]: ast::GlobalDecl::dependencies - unresolved: &'out mut FastHashSet>, -} - -impl<'a> ParseExpressionContext<'a, '_, '_> { - fn reborrow(&mut self) -> ParseExpressionContext<'a, '_, '_> { - ParseExpressionContext { - expressions: self.expressions, - types: self.types, - local_table: self.local_table, - locals: self.locals, - unresolved: self.unresolved, - } - } - - fn parse_binary_op( - &mut self, - lexer: &mut Lexer<'a>, - classifier: impl Fn(Token<'a>) -> Option, - mut parser: impl FnMut( - &mut Lexer<'a>, - ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>>, - ) -> Result>, Error<'a>> { - let start = lexer.start_byte_offset(); - let mut accumulator = parser(lexer, self.reborrow())?; - while let Some(op) = classifier(lexer.peek().0) { - let _ = lexer.next(); - let left = accumulator; - let right = parser(lexer, self.reborrow())?; - accumulator = self.expressions.append( - ast::Expression::Binary { op, left, right }, - lexer.span_from(start), - ); - } - Ok(accumulator) - } -} - -/// State for constructing a `crate::Module`. -struct OutputContext<'source, 'temp, 'out> { - /// The `TranslationUnit`'s expressions arena. - ast_expressions: &'temp Arena>, - - /// The `TranslationUnit`'s types arena. - types: &'temp Arena>, - - // Naga IR values. - /// The map from the names of module-scope declarations to the Naga IR - /// `Handle`s we have built for them, owned by `Lowerer::lower`. - globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, - - /// The module we're constructing. - module: &'out mut crate::Module, -} - -impl<'source> OutputContext<'source, '_, '_> { - fn reborrow(&mut self) -> OutputContext<'source, '_, '_> { - OutputContext { - ast_expressions: self.ast_expressions, - globals: self.globals, - types: self.types, - module: self.module, - } - } - - fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { - self.module - .types - .insert(crate::Type { inner, name: None }, Span::UNDEFINED) - } -} - -/// State for lowering a statement within a function. -struct StatementContext<'source, 'temp, 'out> { - // WGSL AST values. - /// A reference to [`TranslationUnit::expressions`] for the translation unit - /// we're lowering. - /// - /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions - ast_expressions: &'temp Arena>, - - /// A reference to [`TranslationUnit::types`] for the translation unit - /// we're lowering. - /// - /// [`TranslationUnit::types`]: ast::TranslationUnit::types - types: &'temp Arena>, - - // Naga IR values. - /// The map from the names of module-scope declarations to the Naga IR - /// `Handle`s we have built for them, owned by `Lowerer::lower`. - globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, - - /// A map from `ast::Local` handles to the Naga expressions we've built for them. - /// - /// The Naga expressions are either [`LocalVariable`] or - /// [`FunctionArgument`] expressions. - /// - /// [`LocalVariable`]: crate::Expression::LocalVariable - /// [`FunctionArgument`]: crate::Expression::FunctionArgument - local_table: &'temp mut FastHashMap, TypedExpression>, - - typifier: &'temp mut super::Typifier, - variables: &'out mut Arena, - naga_expressions: &'out mut Arena, - named_expressions: &'out mut FastHashMap, String>, - arguments: &'out [crate::FunctionArgument], - module: &'out mut crate::Module, -} - -impl<'a, 'temp> StatementContext<'a, 'temp, '_> { - fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { - StatementContext { - local_table: self.local_table, - globals: self.globals, - types: self.types, - ast_expressions: self.ast_expressions, - typifier: self.typifier, - variables: self.variables, - naga_expressions: self.naga_expressions, - named_expressions: self.named_expressions, - arguments: self.arguments, - module: self.module, - } - } - - fn as_expression<'t>( - &'t mut self, - block: &'t mut crate::Block, - emitter: &'t mut super::Emitter, - ) -> ExpressionContext<'a, 't, '_> - where - 'temp: 't, - { - ExpressionContext { - local_table: self.local_table, - globals: self.globals, - types: self.types, - ast_expressions: self.ast_expressions, - typifier: self.typifier, - naga_expressions: self.naga_expressions, - module: self.module, - local_vars: self.variables, - arguments: self.arguments, - block, - emitter, - } - } - - fn as_output(&mut self) -> OutputContext<'a, '_, '_> { - OutputContext { - ast_expressions: self.ast_expressions, - globals: self.globals, - types: self.types, - module: self.module, - } - } -} - -struct ExpressionContext<'source, 'temp, 'out> { - // WGSL AST values. - local_table: &'temp mut FastHashMap, TypedExpression>, - ast_expressions: &'temp Arena>, - types: &'temp Arena>, - - // Naga IR values. - /// The map from the names of module-scope declarations to the Naga IR - /// `Handle`s we have built for them, owned by `Lowerer::lower`. - globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, - - typifier: &'temp mut super::Typifier, - naga_expressions: &'out mut Arena, - local_vars: &'out Arena, - arguments: &'out [crate::FunctionArgument], - module: &'out mut crate::Module, - block: &'temp mut crate::Block, - emitter: &'temp mut super::Emitter, -} - -impl<'a> ExpressionContext<'a, '_, '_> { - fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { - ExpressionContext { - local_table: self.local_table, - globals: self.globals, - types: self.types, - ast_expressions: self.ast_expressions, - typifier: self.typifier, - naga_expressions: self.naga_expressions, - module: self.module, - local_vars: self.local_vars, - arguments: self.arguments, - block: self.block, - emitter: self.emitter, - } - } - - fn as_output(&mut self) -> OutputContext<'a, '_, '_> { - OutputContext { - ast_expressions: self.ast_expressions, - globals: self.globals, - types: self.types, - module: self.module, - } - } - - /// Determine the type of `handle`, and add it to the module's arena. - /// - /// If you just need a `TypeInner` for `handle`'s type, use - /// [`grow_types`] and [`resolved_inner`] instead. This function - /// should only be used when the type of `handle` needs to appear - /// in the module's final `Arena`, for example, if you're - /// creating a [`LocalVariable`] whose type is inferred from its - /// initializer. - /// - /// [`grow_types`]: Self::grow_types - /// [`resolved_inner`]: Self::resolved_inner - /// [`LocalVariable`]: crate::LocalVariable - fn register_type( - &mut self, - handle: Handle, - ) -> Result, Error<'a>> { - self.grow_types(handle)?; - Ok(self.typifier.register_type(handle, &mut self.module.types)) - } - - /// Resolve the types of all expressions up through `handle`. - /// - /// Ensure that [`self.typifier`] has a [`TypeResolution`] for - /// every expression in [`self.naga_expressions`]. - /// - /// This does not add types to any arena. The [`Typifier`] - /// documentation explains the steps we take to avoid filling - /// arenas with intermediate types. - /// - /// This function takes `&mut self`, so it can't conveniently - /// return a shared reference to the resulting `TypeResolution`: - /// the shared reference would extend the mutable borrow, and you - /// wouldn't be able to use `self` for anything else. Instead, you - /// should call `grow_types` to cover the handles you need, and - /// then use `self.typifier[handle]` or - /// [`self.resolved_inner(handle)`] to get at their resolutions. - /// - /// [`self.typifier`]: ExpressionContext::typifier - /// [`self.resolved_inner(handle)`]: ExpressionContext::resolved_inner - /// [`Typifier`]: super::Typifier - fn grow_types(&mut self, handle: Handle) -> Result<&mut Self, Error<'a>> { - let resolve_ctx = ResolveContext { - constants: &self.module.constants, - types: &self.module.types, - global_vars: &self.module.global_variables, - local_vars: self.local_vars, - functions: &self.module.functions, - arguments: self.arguments, - }; - self.typifier - .grow(handle, self.naga_expressions, &resolve_ctx) - .map_err(Error::InvalidResolve)?; - Ok(self) - } - - fn resolved_inner(&self, handle: Handle) -> &crate::TypeInner { - self.typifier[handle].inner_with(&self.module.types) - } - - fn image_data( - &mut self, - image: Handle, - span: Span, - ) -> Result<(crate::ImageClass, bool), Error<'a>> { - self.grow_types(image)?; - match *self.resolved_inner(image) { - crate::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), - _ => Err(Error::BadTexture(span)), - } - } - - fn prepare_args<'b>( - &mut self, - args: &'b [Handle>], - min_args: u32, - span: Span, - ) -> ArgumentContext<'b, 'a> { - ArgumentContext { - args: args.iter(), - min_args, - args_used: 0, - total_args: args.len() as u32, - span, - } - } - - /// Insert splats, if needed by the non-'*' operations. - fn binary_op_splat( - &mut self, - op: crate::BinaryOperator, - left: &mut Handle, - right: &mut Handle, - ) -> Result<(), Error<'a>> { - if op != crate::BinaryOperator::Multiply { - self.grow_types(*left)?.grow_types(*right)?; - - let left_size = match *self.resolved_inner(*left) { - crate::TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - - match (left_size, self.resolved_inner(*right)) { - (Some(size), &crate::TypeInner::Scalar { .. }) => { - *right = self.naga_expressions.append( - crate::Expression::Splat { - size, - value: *right, - }, - self.naga_expressions.get_span(*right), - ); - } - (None, &crate::TypeInner::Vector { size, .. }) => { - *left = self.naga_expressions.append( - crate::Expression::Splat { size, value: *left }, - self.naga_expressions.get_span(*left), - ); - } - _ => {} - } - } - - Ok(()) - } - - /// Add a single expression to the expression table that is not covered by `self.emitter`. - /// - /// This is useful for `CallResult` and `AtomicResult` expressions, which should not be covered by - /// `Emit` statements. - fn interrupt_emitter( - &mut self, - expression: crate::Expression, - span: Span, - ) -> Handle { - self.block - .extend(self.emitter.finish(self.naga_expressions)); - let result = self.naga_expressions.append(expression, span); - self.emitter.start(self.naga_expressions); - result - } - - /// Apply the WGSL Load Rule to `expr`. - /// - /// If `expr` is has type `ref`, perform a load to produce a value of type - /// `T`. Otherwise, return `expr` unchanged. - fn apply_load_rule(&mut self, expr: TypedExpression) -> Handle { - if expr.is_reference { - let load = crate::Expression::Load { - pointer: expr.handle, - }; - let span = self.naga_expressions.get_span(expr.handle); - self.naga_expressions.append(load, span) - } else { - expr.handle - } - } - - /// Creates a zero value constant of type `ty` - /// - /// Returns `None` if the given `ty` is not a constructible type - fn create_zero_value_constant( - &mut self, - ty: Handle, - ) -> Option> { - let inner = match self.module.types[ty].inner { - crate::TypeInner::Scalar { kind, width } => { - let value = match kind { - crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), - crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), - crate::ScalarKind::Float => crate::ScalarValue::Float(0.), - crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), - }; - crate::ConstantInner::Scalar { width, value } - } - crate::TypeInner::Vector { size, kind, width } => { - let scalar_ty = self.ensure_type_exists(crate::TypeInner::Scalar { width, kind }); - let component = self.create_zero_value_constant(scalar_ty); - crate::ConstantInner::Composite { - ty, - components: (0..size as u8).map(|_| component).collect::>()?, - } - } - crate::TypeInner::Matrix { - columns, - rows, - width, - } => { - let vec_ty = self.ensure_type_exists(crate::TypeInner::Vector { - width, - kind: crate::ScalarKind::Float, - size: rows, - }); - let component = self.create_zero_value_constant(vec_ty); - crate::ConstantInner::Composite { - ty, - components: (0..columns as u8) - .map(|_| component) - .collect::>()?, - } - } - crate::TypeInner::Array { - base, - size: crate::ArraySize::Constant(size), - .. - } => { - let component = self.create_zero_value_constant(base); - crate::ConstantInner::Composite { - ty, - components: (0..self.module.constants[size].to_array_length().unwrap()) - .map(|_| component) - .collect::>()?, - } - } - crate::TypeInner::Struct { ref members, .. } => { - let members = members.clone(); - crate::ConstantInner::Composite { - ty, - components: members - .iter() - .map(|member| self.create_zero_value_constant(member.ty)) - .collect::>()?, - } - } - _ => return None, - }; - - let constant = self.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Span::UNDEFINED, - ); - Some(constant) - } - - fn format_typeinner(&self, inner: &crate::TypeInner) -> String { - inner.to_wgsl(&self.module.types, &self.module.constants) - } - - fn format_type(&self, handle: Handle) -> String { - let ty = &self.module.types[handle]; - match ty.name { - Some(ref name) => name.clone(), - None => self.format_typeinner(&ty.inner), - } - } - - fn format_type_resolution(&self, resolution: &TypeResolution) -> String { - match *resolution { - TypeResolution::Handle(handle) => self.format_type(handle), - TypeResolution::Value(ref inner) => self.format_typeinner(inner), - } - } - - fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { - self.as_output().ensure_type_exists(inner) - } -} - -struct ArgumentContext<'ctx, 'source> { - args: std::slice::Iter<'ctx, Handle>>, - min_args: u32, - args_used: u32, - total_args: u32, - span: Span, -} - -impl<'source> ArgumentContext<'_, 'source> { - pub fn finish(self) -> Result<(), Error<'source>> { - if self.args.len() == 0 { - Ok(()) - } else { - Err(Error::WrongArgumentCount { - found: self.total_args, - expected: self.min_args..self.args_used + 1, - span: self.span, - }) - } - } - - pub fn next(&mut self) -> Result>, Error<'source>> { - match self.args.next().copied() { - Some(arg) => { - self.args_used += 1; - Ok(arg) - } - None => Err(Error::WrongArgumentCount { - found: self.total_args, - expected: self.min_args..self.args_used + 1, - span: self.span, - }), - } - } -} - -/// A Naga [`Expression`] handle, with WGSL type information. -/// -/// Naga and WGSL types are very close, but Naga lacks WGSL's 'reference' types, -/// which we need to know to apply the Load Rule. This struct carries a Naga -/// `Handle` along with enough information to determine its WGSL type. -/// -/// [`Expression`]: crate::Expression -#[derive(Debug, Copy, Clone)] -struct TypedExpression { - /// The handle of the Naga expression. - handle: Handle, - - /// True if this expression's WGSL type is a reference. - /// - /// When this is true, `handle` must be a pointer. - is_reference: bool, -} - -impl TypedExpression { - const fn non_reference(handle: Handle) -> TypedExpression { - TypedExpression { - handle, - is_reference: false, - } - } -} - -enum Composition { - Single(u32), - Multi(crate::VectorSize, [crate::SwizzleComponent; 4]), -} - -impl Composition { - const fn letter_component(letter: char) -> Option { - use crate::SwizzleComponent as Sc; - match letter { - 'x' | 'r' => Some(Sc::X), - 'y' | 'g' => Some(Sc::Y), - 'z' | 'b' => Some(Sc::Z), - 'w' | 'a' => Some(Sc::W), - _ => None, - } - } - - fn extract_impl(name: &str, name_span: Span) -> Result { - let ch = name.chars().next().ok_or(Error::BadAccessor(name_span))?; - match Self::letter_component(ch) { - Some(sc) => Ok(sc as u32), - None => Err(Error::BadAccessor(name_span)), - } - } - - fn make(name: &str, name_span: Span) -> Result { - if name.len() > 1 { - let mut components = [crate::SwizzleComponent::X; 4]; - for (comp, ch) in components.iter_mut().zip(name.chars()) { - *comp = Self::letter_component(ch).ok_or(Error::BadAccessor(name_span))?; - } - - let size = match name.len() { - 2 => crate::VectorSize::Bi, - 3 => crate::VectorSize::Tri, - 4 => crate::VectorSize::Quad, - _ => return Err(Error::BadAccessor(name_span)), - }; - Ok(Composition::Multi(size, components)) - } else { - Self::extract_impl(name, name_span).map(Composition::Single) - } - } -} - -/// Which grammar rule we are in the midst of parsing. -/// -/// This is used for error checking. `Parser` maintains a stack of -/// these and (occasionally) checks that it is being pushed and popped -/// as expected. -#[derive(Clone, Debug, PartialEq)] -enum Rule { - Attribute, - VariableDecl, - TypeDecl, - FunctionDecl, - Block, - Statement, - PrimaryExpr, - SingularExpr, - UnaryExpr, - GeneralExpr, -} - -#[derive(Default)] -struct BindingParser { - location: Option, - built_in: Option, - interpolation: Option, - sampling: Option, - invariant: bool, -} - -impl BindingParser { - fn parse<'a>( - &mut self, - lexer: &mut Lexer<'a>, - name: &'a str, - name_span: Span, - ) -> Result<(), Error<'a>> { - match name { - "location" => { - lexer.expect(Token::Paren('('))?; - self.location = Some(Parser::non_negative_i32_literal(lexer)?); - lexer.expect(Token::Paren(')'))?; - } - "builtin" => { - lexer.expect(Token::Paren('('))?; - let (raw, span) = lexer.next_ident_with_span()?; - self.built_in = Some(conv::map_built_in(raw, span)?); - lexer.expect(Token::Paren(')'))?; - } - "interpolate" => { - lexer.expect(Token::Paren('('))?; - let (raw, span) = lexer.next_ident_with_span()?; - self.interpolation = Some(conv::map_interpolation(raw, span)?); - if lexer.skip(Token::Separator(',')) { - let (raw, span) = lexer.next_ident_with_span()?; - self.sampling = Some(conv::map_sampling(raw, span)?); - } - lexer.expect(Token::Paren(')'))?; - } - "invariant" => self.invariant = true, - _ => return Err(Error::UnknownAttribute(name_span)), - } - Ok(()) - } - - const fn finish<'a>(self, span: Span) -> Result, Error<'a>> { - match ( - self.location, - self.built_in, - self.interpolation, - self.sampling, - self.invariant, - ) { - (None, None, None, None, false) => Ok(None), - (Some(location), None, interpolation, sampling, false) => { - // Before handing over the completed `Module`, we call - // `apply_default_interpolation` to ensure that the interpolation and - // sampling have been explicitly specified on all vertex shader output and fragment - // shader input user bindings, so leaving them potentially `None` here is fine. - Ok(Some(crate::Binding::Location { - location, - interpolation, - sampling, - })) - } - (None, Some(crate::BuiltIn::Position { .. }), None, None, invariant) => { - Ok(Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { - invariant, - }))) - } - (None, Some(built_in), None, None, false) => { - Ok(Some(crate::Binding::BuiltIn(built_in))) - } - (_, _, _, _, _) => Err(Error::InconsistentBinding(span)), - } - } -} - -#[derive(Clone, Debug)] -pub struct ParseError { - message: String, - labels: Vec<(Span, Cow<'static, str>)>, - notes: Vec, -} - -impl ParseError { - pub fn labels(&self) -> impl Iterator + ExactSizeIterator + '_ { - self.labels - .iter() - .map(|&(span, ref msg)| (span, msg.as_ref())) - } - - pub fn message(&self) -> &str { - &self.message - } - - fn diagnostic(&self) -> Diagnostic<()> { - let diagnostic = Diagnostic::error() - .with_message(self.message.to_string()) - .with_labels( - self.labels - .iter() - .map(|label| { - Label::primary((), label.0.to_range().unwrap()) - .with_message(label.1.to_string()) - }) - .collect(), - ) - .with_notes( - self.notes - .iter() - .map(|note| format!("note: {note}")) - .collect(), - ); - diagnostic - } - - /// Emits a summary of the error to standard error stream. - pub fn emit_to_stderr(&self, source: &str) { - self.emit_to_stderr_with_path(source, "wgsl") - } - - /// Emits a summary of the error to standard error stream. - pub fn emit_to_stderr_with_path(&self, source: &str, path: &str) { - let files = SimpleFile::new(path, source); - let config = codespan_reporting::term::Config::default(); - let writer = StandardStream::stderr(ColorChoice::Auto); - term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) - .expect("cannot write error"); - } - - /// Emits a summary of the error to a string. - pub fn emit_to_string(&self, source: &str) -> String { - self.emit_to_string_with_path(source, "wgsl") - } - - /// Emits a summary of the error to a string. - pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String { - let files = SimpleFile::new(path, source); - let config = codespan_reporting::term::Config::default(); - let mut writer = NoColor::new(Vec::new()); - term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); - String::from_utf8(writer.into_inner()).unwrap() - } - - /// Returns a [`SourceLocation`] for the first label in the error message. - pub fn location(&self, source: &str) -> Option { - self.labels.get(0).map(|label| label.0.location(source)) - } -} - -impl std::fmt::Display for ParseError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.message) - } -} - -impl std::error::Error for ParseError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - None - } -} - -pub struct Parser { - rules: Vec<(Rule, usize)>, -} - -impl Parser { - pub const fn new() -> Self { - Parser { rules: Vec::new() } - } - - fn reset(&mut self) { - self.rules.clear(); - } - - fn push_rule_span(&mut self, rule: Rule, lexer: &mut Lexer<'_>) { - self.rules.push((rule, lexer.start_byte_offset())); - } - - fn pop_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { - let (_, initial) = self.rules.pop().unwrap(); - lexer.span_from(initial) - } - - fn peek_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { - let &(_, initial) = self.rules.last().unwrap(); - lexer.span_from(initial) - } - - fn switch_value<'a>(lexer: &mut Lexer<'a>) -> Result<(ast::SwitchValue, Span), Error<'a>> { - let token_span = lexer.next(); - match token_span.0 { - Token::Word("default") => Ok((ast::SwitchValue::Default, token_span.1)), - Token::Number(Ok(Number::U32(num))) => Ok((ast::SwitchValue::U32(num), token_span.1)), - Token::Number(Ok(Number::I32(num))) => Ok((ast::SwitchValue::I32(num), token_span.1)), - Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)), - _ => Err(Error::Unexpected(token_span.1, ExpectedToken::Integer)), - } - } - - /// Parse a non-negative signed integer literal. - /// This is for attributes like `size`, `location` and others. - fn non_negative_i32_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { - match lexer.next() { - (Token::Number(Ok(Number::I32(num))), span) => { - u32::try_from(num).map_err(|_| Error::NegativeInt(span)) - } - (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), - other => Err(Error::Unexpected( - other.1, - ExpectedToken::Number(NumberType::I32), - )), - } - } - - /// Parse a non-negative integer literal that may be either signed or unsigned. - /// This is for the `workgroup_size` attribute and array lengths. - /// Note: these values should be no larger than [`i32::MAX`], but this is not checked here. - fn generic_non_negative_int_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { - match lexer.next() { - (Token::Number(Ok(Number::I32(num))), span) => { - u32::try_from(num).map_err(|_| Error::NegativeInt(span)) - } - (Token::Number(Ok(Number::U32(num))), _) => Ok(num), - (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), - other => Err(Error::Unexpected( - other.1, - ExpectedToken::Number(NumberType::I32), - )), - } - } - - /// Decide if we're looking at a construction expression, and return its - /// type if so. - /// - /// If the identifier `word` is a [type-defining keyword], then return a - /// [`ConstructorType`] value describing the type to build. Return an error - /// if the type is not constructible (like `sampler`). - /// - /// If `word` isn't a type name, then return `None`. - /// - /// [type-defining keyword]: https://gpuweb.github.io/gpuweb/wgsl/#type-defining-keywords - /// [`ConstructorType`]: ast::ConstructorType - fn constructor_type<'a>( - &mut self, - lexer: &mut Lexer<'a>, - word: &'a str, - span: Span, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - if let Some((kind, width)) = conv::get_scalar_type(word) { - return Ok(Some(ast::ConstructorType::Scalar { kind, width })); - } - - let partial = match word { - "vec2" => ast::ConstructorType::PartialVector { - size: crate::VectorSize::Bi, - }, - "vec3" => ast::ConstructorType::PartialVector { - size: crate::VectorSize::Tri, - }, - "vec4" => ast::ConstructorType::PartialVector { - size: crate::VectorSize::Quad, - }, - "mat2x2" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Bi, - rows: crate::VectorSize::Bi, - }, - "mat2x3" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Bi, - rows: crate::VectorSize::Tri, - }, - "mat2x4" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Bi, - rows: crate::VectorSize::Quad, - }, - "mat3x2" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Tri, - rows: crate::VectorSize::Bi, - }, - "mat3x3" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Tri, - rows: crate::VectorSize::Tri, - }, - "mat3x4" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Tri, - rows: crate::VectorSize::Quad, - }, - "mat4x2" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Quad, - rows: crate::VectorSize::Bi, - }, - "mat4x3" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Quad, - rows: crate::VectorSize::Tri, - }, - "mat4x4" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Quad, - rows: crate::VectorSize::Quad, - }, - "array" => ast::ConstructorType::PartialArray, - "atomic" - | "binding_array" - | "sampler" - | "sampler_comparison" - | "texture_1d" - | "texture_1d_array" - | "texture_2d" - | "texture_2d_array" - | "texture_3d" - | "texture_cube" - | "texture_cube_array" - | "texture_multisampled_2d" - | "texture_multisampled_2d_array" - | "texture_depth_2d" - | "texture_depth_2d_array" - | "texture_depth_cube" - | "texture_depth_cube_array" - | "texture_depth_multisampled_2d" - | "texture_storage_1d" - | "texture_storage_1d_array" - | "texture_storage_2d" - | "texture_storage_2d_array" - | "texture_storage_3d" => return Err(Error::TypeNotConstructible(span)), - _ => return Ok(None), - }; - - // parse component type if present - match (lexer.peek().0, partial) { - (Token::Paren('<'), ast::ConstructorType::PartialVector { size }) => { - let (kind, width) = lexer.next_scalar_generic()?; - Ok(Some(ast::ConstructorType::Vector { size, kind, width })) - } - (Token::Paren('<'), ast::ConstructorType::PartialMatrix { columns, rows }) => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - match kind { - crate::ScalarKind::Float => Ok(Some(ast::ConstructorType::Matrix { - columns, - rows, - width, - })), - _ => Err(Error::BadMatrixScalarKind(span, kind, width)), - } - } - (Token::Paren('<'), ast::ConstructorType::PartialArray) => { - lexer.expect_generic_paren('<')?; - let base = self.type_decl(lexer, ctx.reborrow())?; - let size = if lexer.skip(Token::Separator(',')) { - let expr = self.unary_expression(lexer, ctx.reborrow())?; - ast::ArraySize::Constant(expr) - } else { - ast::ArraySize::Dynamic - }; - lexer.expect_generic_paren('>')?; - - Ok(Some(ast::ConstructorType::Array { base, size })) - } - (_, partial) => Ok(Some(partial)), - } - } - - /// Expects `name` to be consumed (not in lexer). - fn arguments<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>>, Error<'a>> { - lexer.open_arguments()?; - let mut arguments = Vec::new(); - loop { - if !arguments.is_empty() { - if !lexer.next_argument()? { - break; - } - } else if lexer.skip(Token::Paren(')')) { - break; - } - let arg = self.general_expression(lexer, ctx.reborrow())?; - arguments.push(arg); - } - - Ok(arguments) - } - - /// Expects [`Rule::PrimaryExpr`] or [`Rule::SingularExpr`] on top; does not pop it. - /// Expects `name` to be consumed (not in lexer). - fn function_call<'a>( - &mut self, - lexer: &mut Lexer<'a>, - name: &'a str, - name_span: Span, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - assert!(self.rules.last().is_some()); - - let expr = match name { - // bitcast looks like a function call, but it's an operator and must be handled differently. - "bitcast" => { - lexer.expect_generic_paren('<')?; - let start = lexer.start_byte_offset(); - let to = self.type_decl(lexer, ctx.reborrow())?; - let span = lexer.span_from(start); - lexer.expect_generic_paren('>')?; - - lexer.open_arguments()?; - let expr = self.general_expression(lexer, ctx.reborrow())?; - lexer.close_arguments()?; - - ast::Expression::Bitcast { - expr, - to, - ty_span: span, - } - } - // everything else must be handled later, since they can be hidden by user-defined functions. - _ => { - let arguments = self.arguments(lexer, ctx.reborrow())?; - ctx.unresolved.insert(ast::Dependency { - ident: name, - usage: name_span, - }); - ast::Expression::Call { - function: ast::Ident { - name, - span: name_span, - }, - arguments, - } - } - }; - - let span = self.peek_rule_span(lexer); - let expr = ctx.expressions.append(expr, span); - Ok(expr) - } - - fn ident_expr<'a>( - &mut self, - name: &'a str, - name_span: Span, - ctx: ParseExpressionContext<'a, '_, '_>, - ) -> ast::IdentExpr<'a> { - match ctx.local_table.lookup(name) { - Some(&local) => ast::IdentExpr::Local(local), - None => { - ctx.unresolved.insert(ast::Dependency { - ident: name, - usage: name_span, - }); - ast::IdentExpr::Unresolved(name) - } - } - } - - fn primary_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - self.push_rule_span(Rule::PrimaryExpr, lexer); - - let expr = match lexer.peek() { - (Token::Paren('('), _) => { - let _ = lexer.next(); - let expr = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - self.pop_rule_span(lexer); - return Ok(expr); - } - (Token::Word("true"), _) => { - let _ = lexer.next(); - ast::Expression::Literal(ast::Literal::Bool(true)) - } - (Token::Word("false"), _) => { - let _ = lexer.next(); - ast::Expression::Literal(ast::Literal::Bool(false)) - } - (Token::Number(res), span) => { - let _ = lexer.next(); - let num = res.map_err(|err| Error::BadNumber(span, err))?; - ast::Expression::Literal(ast::Literal::Number(num)) - } - (Token::Word(word), span) => { - let start = lexer.start_byte_offset(); - let _ = lexer.next(); - - if let Some(ty) = self.constructor_type(lexer, word, span, ctx.reborrow())? { - let ty_span = lexer.span_from(start); - let components = self.arguments(lexer, ctx.reborrow())?; - ast::Expression::Construct { - ty, - ty_span, - components, - } - } else if let Token::Paren('(') = lexer.peek().0 { - self.pop_rule_span(lexer); - return self.function_call(lexer, word, span, ctx); - } else if word == "bitcast" { - self.pop_rule_span(lexer); - return self.function_call(lexer, word, span, ctx); - } else { - let ident = self.ident_expr(word, span, ctx.reborrow()); - ast::Expression::Ident(ident) - } - } - other => return Err(Error::Unexpected(other.1, ExpectedToken::PrimaryExpression)), - }; - - let span = self.pop_rule_span(lexer); - let expr = ctx.expressions.append(expr, span); - Ok(expr) - } - - fn postfix<'a>( - &mut self, - span_start: usize, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - expr: Handle>, - ) -> Result>, Error<'a>> { - let mut expr = expr; - - loop { - let expression = match lexer.peek().0 { - Token::Separator('.') => { - let _ = lexer.next(); - let field = lexer.next_ident()?; - - ast::Expression::Member { base: expr, field } - } - Token::Paren('[') => { - let _ = lexer.next(); - let index = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(']'))?; - - ast::Expression::Index { base: expr, index } - } - _ => break, - }; - - let span = lexer.span_from(span_start); - expr = ctx.expressions.append(expression, span); - } - - Ok(expr) - } - - /// Parse a `unary_expression`. - fn unary_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - self.push_rule_span(Rule::UnaryExpr, lexer); - //TODO: refactor this to avoid backing up - let expr = match lexer.peek().0 { - Token::Operation('-') => { - let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; - let expr = ast::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr, - }; - let span = self.peek_rule_span(lexer); - ctx.expressions.append(expr, span) - } - Token::Operation('!' | '~') => { - let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; - let expr = ast::Expression::Unary { - op: crate::UnaryOperator::Not, - expr, - }; - let span = self.peek_rule_span(lexer); - ctx.expressions.append(expr, span) - } - Token::Operation('*') => { - let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; - let expr = ast::Expression::Deref(expr); - let span = self.peek_rule_span(lexer); - ctx.expressions.append(expr, span) - } - Token::Operation('&') => { - let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; - let expr = ast::Expression::AddrOf(expr); - let span = self.peek_rule_span(lexer); - ctx.expressions.append(expr, span) - } - _ => self.singular_expression(lexer, ctx.reborrow())?, - }; - - self.pop_rule_span(lexer); - Ok(expr) - } - - /// Parse a `singular_expression`. - fn singular_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - let start = lexer.start_byte_offset(); - self.push_rule_span(Rule::SingularExpr, lexer); - let primary_expr = self.primary_expression(lexer, ctx.reborrow())?; - let singular_expr = self.postfix(start, lexer, ctx.reborrow(), primary_expr)?; - self.pop_rule_span(lexer); - - Ok(singular_expr) - } - - fn equality_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut context: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - // equality_expression - context.parse_binary_op( - lexer, - |token| match token { - Token::LogicalOperation('=') => Some(crate::BinaryOperator::Equal), - Token::LogicalOperation('!') => Some(crate::BinaryOperator::NotEqual), - _ => None, - }, - // relational_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Paren('<') => Some(crate::BinaryOperator::Less), - Token::Paren('>') => Some(crate::BinaryOperator::Greater), - Token::LogicalOperation('<') => Some(crate::BinaryOperator::LessEqual), - Token::LogicalOperation('>') => Some(crate::BinaryOperator::GreaterEqual), - _ => None, - }, - // shift_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::ShiftOperation('<') => { - Some(crate::BinaryOperator::ShiftLeft) - } - Token::ShiftOperation('>') => { - Some(crate::BinaryOperator::ShiftRight) - } - _ => None, - }, - // additive_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('+') => Some(crate::BinaryOperator::Add), - Token::Operation('-') => { - Some(crate::BinaryOperator::Subtract) - } - _ => None, - }, - // multiplicative_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('*') => { - Some(crate::BinaryOperator::Multiply) - } - Token::Operation('/') => { - Some(crate::BinaryOperator::Divide) - } - Token::Operation('%') => { - Some(crate::BinaryOperator::Modulo) - } - _ => None, - }, - |lexer, context| self.unary_expression(lexer, context), - ) - }, - ) - }, - ) - }, - ) - }, - ) - } - - fn general_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - self.general_expression_with_span(lexer, ctx.reborrow()) - .map(|(expr, _)| expr) - } - - fn general_expression_with_span<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut context: ParseExpressionContext<'a, '_, '_>, - ) -> Result<(Handle>, Span), Error<'a>> { - self.push_rule_span(Rule::GeneralExpr, lexer); - // logical_or_expression - let handle = context.parse_binary_op( - lexer, - |token| match token { - Token::LogicalOperation('|') => Some(crate::BinaryOperator::LogicalOr), - _ => None, - }, - // logical_and_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::LogicalOperation('&') => Some(crate::BinaryOperator::LogicalAnd), - _ => None, - }, - // inclusive_or_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('|') => Some(crate::BinaryOperator::InclusiveOr), - _ => None, - }, - // exclusive_or_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('^') => { - Some(crate::BinaryOperator::ExclusiveOr) - } - _ => None, - }, - // and_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('&') => { - Some(crate::BinaryOperator::And) - } - _ => None, - }, - |lexer, context| { - self.equality_expression(lexer, context) - }, - ) - }, - ) - }, - ) - }, - ) - }, - )?; - Ok((handle, self.pop_rule_span(lexer))) - } - - fn variable_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - self.push_rule_span(Rule::VariableDecl, lexer); - let mut space = crate::AddressSpace::Handle; - - if lexer.skip(Token::Paren('<')) { - let (class_str, span) = lexer.next_ident_with_span()?; - space = match class_str { - "storage" => { - let access = if lexer.skip(Token::Separator(',')) { - lexer.next_storage_access()? - } else { - // defaulting to `read` - crate::StorageAccess::LOAD - }; - crate::AddressSpace::Storage { access } - } - _ => conv::map_address_space(class_str, span)?, - }; - lexer.expect(Token::Paren('>'))?; - } - let name = lexer.next_ident()?; - lexer.expect(Token::Separator(':'))?; - let ty = self.type_decl(lexer, ctx.reborrow())?; - - let init = if lexer.skip(Token::Operation('=')) { - let handle = self.general_expression(lexer, ctx.reborrow())?; - Some(handle) - } else { - None - }; - lexer.expect(Token::Separator(';'))?; - self.pop_rule_span(lexer); - - Ok(ast::GlobalVariable { - name, - space, - binding: None, - ty, - init, - }) - } - - fn struct_body<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - let mut members = Vec::new(); - - lexer.expect(Token::Paren('{'))?; - let mut ready = true; - while !lexer.skip(Token::Paren('}')) { - if !ready { - return Err(Error::Unexpected( - lexer.next().1, - ExpectedToken::Token(Token::Separator(',')), - )); - } - let (mut size, mut align) = (None, None); - self.push_rule_span(Rule::Attribute, lexer); - let mut bind_parser = BindingParser::default(); - while lexer.skip(Token::Attribute) { - match lexer.next_ident_with_span()? { - ("size", _) => { - lexer.expect(Token::Paren('('))?; - let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; - lexer.expect(Token::Paren(')'))?; - size = Some((value, span)); - } - ("align", _) => { - lexer.expect(Token::Paren('('))?; - let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; - lexer.expect(Token::Paren(')'))?; - align = Some((value, span)); - } - (word, word_span) => bind_parser.parse(lexer, word, word_span)?, - } - } - - let bind_span = self.pop_rule_span(lexer); - let binding = bind_parser.finish(bind_span)?; - - let name = lexer.next_ident()?; - lexer.expect(Token::Separator(':'))?; - let ty = self.type_decl(lexer, ctx.reborrow())?; - ready = lexer.skip(Token::Separator(',')); - - members.push(ast::StructMember { - name, - ty, - binding, - size, - align, - }); - } - - Ok(members) - } - - fn matrix_scalar_type<'a>( - &mut self, - lexer: &mut Lexer<'a>, - columns: crate::VectorSize, - rows: crate::VectorSize, - ) -> Result, Error<'a>> { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - match kind { - crate::ScalarKind::Float => Ok(ast::Type::Matrix { - columns, - rows, - width, - }), - _ => Err(Error::BadMatrixScalarKind(span, kind, width)), - } - } - - fn type_decl_impl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - word: &'a str, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - if let Some((kind, width)) = conv::get_scalar_type(word) { - return Ok(Some(ast::Type::Scalar { kind, width })); - } - - Ok(Some(match word { - "vec2" => { - let (kind, width) = lexer.next_scalar_generic()?; - ast::Type::Vector { - size: crate::VectorSize::Bi, - kind, - width, - } - } - "vec3" => { - let (kind, width) = lexer.next_scalar_generic()?; - ast::Type::Vector { - size: crate::VectorSize::Tri, - kind, - width, - } - } - "vec4" => { - let (kind, width) = lexer.next_scalar_generic()?; - ast::Type::Vector { - size: crate::VectorSize::Quad, - kind, - width, - } - } - "mat2x2" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Bi)? - } - "mat2x3" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Tri)? - } - "mat2x4" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Quad)? - } - "mat3x2" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Bi)? - } - "mat3x3" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Tri)? - } - "mat3x4" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Quad)? - } - "mat4x2" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Bi)? - } - "mat4x3" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Tri)? - } - "mat4x4" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Quad)? - } - "atomic" => { - let (kind, width) = lexer.next_scalar_generic()?; - ast::Type::Atomic { kind, width } - } - "ptr" => { - lexer.expect_generic_paren('<')?; - let (ident, span) = lexer.next_ident_with_span()?; - let mut space = conv::map_address_space(ident, span)?; - lexer.expect(Token::Separator(','))?; - let base = self.type_decl(lexer, ctx)?; - if let crate::AddressSpace::Storage { ref mut access } = space { - *access = if lexer.skip(Token::Separator(',')) { - lexer.next_storage_access()? - } else { - crate::StorageAccess::LOAD - }; - } - lexer.expect_generic_paren('>')?; - ast::Type::Pointer { base, space } - } - "array" => { - lexer.expect_generic_paren('<')?; - let base = self.type_decl(lexer, ctx.reborrow())?; - let size = if lexer.skip(Token::Separator(',')) { - let size = self.unary_expression(lexer, ctx.reborrow())?; - ast::ArraySize::Constant(size) - } else { - ast::ArraySize::Dynamic - }; - lexer.expect_generic_paren('>')?; - - ast::Type::Array { base, size } - } - "binding_array" => { - lexer.expect_generic_paren('<')?; - let base = self.type_decl(lexer, ctx.reborrow())?; - let size = if lexer.skip(Token::Separator(',')) { - let size = self.unary_expression(lexer, ctx.reborrow())?; - ast::ArraySize::Constant(size) - } else { - ast::ArraySize::Dynamic - }; - lexer.expect_generic_paren('>')?; - - ast::Type::BindingArray { base, size } - } - "sampler" => ast::Type::Sampler { comparison: false }, - "sampler_comparison" => ast::Type::Sampler { comparison: true }, - "texture_1d" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D1, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_1d_array" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D1, - arrayed: true, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_2d" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_2d_array" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: true, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_3d" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D3, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_cube" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::Cube, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_cube_array" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::Cube, - arrayed: true, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_multisampled_2d" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: true }, - } - } - "texture_multisampled_2d_array" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: true, - class: crate::ImageClass::Sampled { kind, multi: true }, - } - } - "texture_depth_2d" => ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Depth { multi: false }, - }, - "texture_depth_2d_array" => ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: true, - class: crate::ImageClass::Depth { multi: false }, - }, - "texture_depth_cube" => ast::Type::Image { - dim: crate::ImageDimension::Cube, - arrayed: false, - class: crate::ImageClass::Depth { multi: false }, - }, - "texture_depth_cube_array" => ast::Type::Image { - dim: crate::ImageDimension::Cube, - arrayed: true, - class: crate::ImageClass::Depth { multi: false }, - }, - "texture_depth_multisampled_2d" => ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Depth { multi: true }, - }, - "texture_storage_1d" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D1, - arrayed: false, - class: crate::ImageClass::Storage { format, access }, - } - } - "texture_storage_1d_array" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D1, - arrayed: true, - class: crate::ImageClass::Storage { format, access }, - } - } - "texture_storage_2d" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Storage { format, access }, - } - } - "texture_storage_2d_array" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: true, - class: crate::ImageClass::Storage { format, access }, - } - } - "texture_storage_3d" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D3, - arrayed: false, - class: crate::ImageClass::Storage { format, access }, - } - } - _ => return Ok(None), - })) - } - - const fn check_texture_sample_type( - kind: crate::ScalarKind, - width: u8, - span: Span, - ) -> Result<(), Error<'static>> { - use crate::ScalarKind::*; - // Validate according to https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type - match (kind, width) { - (Float | Sint | Uint, 4) => Ok(()), - _ => Err(Error::BadTextureSampleType { span, kind, width }), - } - } - - /// Parse type declaration of a given name. - fn type_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - self.push_rule_span(Rule::TypeDecl, lexer); - - let (name, span) = lexer.next_ident_with_span()?; - - let ty = match self.type_decl_impl(lexer, name, ctx.reborrow())? { - Some(ty) => ty, - None => { - ctx.unresolved.insert(ast::Dependency { - ident: name, - usage: span, - }); - ast::Type::User(ast::Ident { name, span }) - } - }; - - self.pop_rule_span(lexer); - - let handle = ctx.types.append(ty, Span::UNDEFINED); - Ok(handle) - } - - fn assignment_op_and_rhs<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - target: Handle>, - span_start: usize, - ) -> Result<(), Error<'a>> { - use crate::BinaryOperator as Bo; - - let op = lexer.next(); - let (op, value) = match op { - (Token::Operation('='), _) => { - let value = self.general_expression(lexer, ctx.reborrow())?; - (None, value) - } - (Token::AssignmentOperation(c), _) => { - let op = match c { - '<' => Bo::ShiftLeft, - '>' => Bo::ShiftRight, - '+' => Bo::Add, - '-' => Bo::Subtract, - '*' => Bo::Multiply, - '/' => Bo::Divide, - '%' => Bo::Modulo, - '&' => Bo::And, - '|' => Bo::InclusiveOr, - '^' => Bo::ExclusiveOr, - // Note: `consume_token` shouldn't produce any other assignment ops - _ => unreachable!(), - }; - - let value = self.general_expression(lexer, ctx.reborrow())?; - (Some(op), value) - } - token @ (Token::IncrementOperation | Token::DecrementOperation, _) => { - let op = match token.0 { - Token::IncrementOperation => ast::StatementKind::Increment, - Token::DecrementOperation => ast::StatementKind::Decrement, - _ => unreachable!(), - }; - - let span = lexer.span_from(span_start); - block.stmts.push(ast::Statement { - kind: op(target), - span, - }); - return Ok(()); - } - _ => return Err(Error::Unexpected(op.1, ExpectedToken::Assignment)), - }; - - let span = lexer.span_from(span_start); - block.stmts.push(ast::Statement { - kind: ast::StatementKind::Assign { target, op, value }, - span, - }); - Ok(()) - } - - /// Parse an assignment statement (will also parse increment and decrement statements) - fn assignment_statement<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - ) -> Result<(), Error<'a>> { - let span_start = lexer.start_byte_offset(); - let target = self.general_expression(lexer, ctx.reborrow())?; - self.assignment_op_and_rhs(lexer, ctx, block, target, span_start) - } - - /// Parse a function call statement. - /// Expects `ident` to be consumed (not in the lexer). - fn function_statement<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - ident: &'a str, - ident_span: Span, - span_start: usize, - mut context: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - ) -> Result<(), Error<'a>> { - self.push_rule_span(Rule::SingularExpr, lexer); - - context.unresolved.insert(ast::Dependency { - ident, - usage: ident_span, - }); - let arguments = self.arguments(lexer, context.reborrow())?; - let span = lexer.span_from(span_start); - - block.stmts.push(ast::Statement { - kind: ast::StatementKind::Call { - function: ast::Ident { - name: ident, - span: ident_span, - }, - arguments, - }, - span, - }); - - self.pop_rule_span(lexer); - - Ok(()) - } - - fn function_call_or_assignment_statement<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - mut context: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - ) -> Result<(), Error<'a>> { - let span_start = lexer.start_byte_offset(); - match lexer.peek() { - (Token::Word(name), span) => { - // A little hack for 2 token lookahead. - let cloned = lexer.clone(); - let _ = lexer.next(); - match lexer.peek() { - (Token::Paren('('), _) => self.function_statement( - lexer, - name, - span, - span_start, - context.reborrow(), - block, - ), - _ => { - *lexer = cloned; - self.assignment_statement(lexer, context.reborrow(), block) - } - } - } - _ => self.assignment_statement(lexer, context.reborrow(), block), - } - } - - fn statement<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - ) -> Result<(), Error<'a>> { - self.push_rule_span(Rule::Statement, lexer); - match lexer.peek() { - (Token::Separator(';'), _) => { - let _ = lexer.next(); - self.pop_rule_span(lexer); - return Ok(()); - } - (Token::Paren('{'), _) => { - let (inner, span) = self.block(lexer, ctx.reborrow())?; - block.stmts.push(ast::Statement { - kind: ast::StatementKind::Block(inner), - span, - }); - self.pop_rule_span(lexer); - return Ok(()); - } - (Token::Word(word), _) => { - let kind = match word { - "_" => { - let _ = lexer.next(); - lexer.expect(Token::Operation('='))?; - let expr = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(';'))?; - - ast::StatementKind::Ignore(expr) - } - "let" => { - let _ = lexer.next(); - let name = lexer.next_ident()?; - - let given_ty = if lexer.skip(Token::Separator(':')) { - let ty = self.type_decl(lexer, ctx.reborrow())?; - Some(ty) - } else { - None - }; - lexer.expect(Token::Operation('='))?; - let expr_id = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(';'))?; - - let handle = ctx.locals.append(ast::Local, name.span); - if let Some(old) = ctx.local_table.add(name.name, handle) { - return Err(Error::Redefinition { - previous: ctx.locals.get_span(old), - current: name.span, - }); - } - - ast::StatementKind::LocalDecl(ast::LocalDecl::Let(ast::Let { - name, - ty: given_ty, - init: expr_id, - handle, - })) - } - "var" => { - let _ = lexer.next(); - - let name = lexer.next_ident()?; - let ty = if lexer.skip(Token::Separator(':')) { - let ty = self.type_decl(lexer, ctx.reborrow())?; - Some(ty) - } else { - None - }; - - let init = if lexer.skip(Token::Operation('=')) { - let init = self.general_expression(lexer, ctx.reborrow())?; - Some(init) - } else { - None - }; - - lexer.expect(Token::Separator(';'))?; - - let handle = ctx.locals.append(ast::Local, name.span); - if let Some(old) = ctx.local_table.add(name.name, handle) { - return Err(Error::Redefinition { - previous: ctx.locals.get_span(old), - current: name.span, - }); - } - - ast::StatementKind::LocalDecl(ast::LocalDecl::Var(ast::LocalVariable { - name, - ty, - init, - handle, - })) - } - "return" => { - let _ = lexer.next(); - let value = if lexer.peek().0 != Token::Separator(';') { - let handle = self.general_expression(lexer, ctx.reborrow())?; - Some(handle) - } else { - None - }; - lexer.expect(Token::Separator(';'))?; - ast::StatementKind::Return { value } - } - "if" => { - let _ = lexer.next(); - let condition = self.general_expression(lexer, ctx.reborrow())?; - - let accept = self.block(lexer, ctx.reborrow())?.0; - - let mut elsif_stack = Vec::new(); - let mut elseif_span_start = lexer.start_byte_offset(); - let mut reject = loop { - if !lexer.skip(Token::Word("else")) { - break ast::Block::default(); - } - - if !lexer.skip(Token::Word("if")) { - // ... else { ... } - break self.block(lexer, ctx.reborrow())?.0; - } - - // ... else if (...) { ... } - let other_condition = self.general_expression(lexer, ctx.reborrow())?; - let other_block = self.block(lexer, ctx.reborrow())?; - elsif_stack.push((elseif_span_start, other_condition, other_block)); - elseif_span_start = lexer.start_byte_offset(); - }; - - // reverse-fold the else-if blocks - //Note: we may consider uplifting this to the IR - for (other_span_start, other_cond, other_block) in - elsif_stack.into_iter().rev() - { - let sub_stmt = ast::StatementKind::If { - condition: other_cond, - accept: other_block.0, - reject, - }; - reject = ast::Block::default(); - let span = lexer.span_from(other_span_start); - reject.stmts.push(ast::Statement { - kind: sub_stmt, - span, - }) - } - - ast::StatementKind::If { - condition, - accept, - reject, - } - } - "switch" => { - let _ = lexer.next(); - let selector = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren('{'))?; - let mut cases = Vec::new(); - - loop { - // cases + default - match lexer.next() { - (Token::Word("case"), _) => { - // parse a list of values - let (value, value_span) = loop { - let (value, value_span) = Self::switch_value(lexer)?; - if lexer.skip(Token::Separator(',')) { - if lexer.skip(Token::Separator(':')) { - break (value, value_span); - } - } else { - lexer.skip(Token::Separator(':')); - break (value, value_span); - } - cases.push(ast::SwitchCase { - value, - value_span, - body: ast::Block::default(), - fall_through: true, - }); - }; - - let body = self.block(lexer, ctx.reborrow())?.0; - - cases.push(ast::SwitchCase { - value, - value_span, - body, - fall_through: false, - }); - } - (Token::Word("default"), value_span) => { - lexer.skip(Token::Separator(':')); - let body = self.block(lexer, ctx.reborrow())?.0; - cases.push(ast::SwitchCase { - value: ast::SwitchValue::Default, - value_span, - body, - fall_through: false, - }); - } - (Token::Paren('}'), _) => break, - (_, span) => { - return Err(Error::Unexpected(span, ExpectedToken::SwitchItem)) - } - } - } - - ast::StatementKind::Switch { selector, cases } - } - "loop" => self.r#loop(lexer, ctx.reborrow())?, - "while" => { - let _ = lexer.next(); - let mut body = ast::Block::default(); - - let (condition, span) = lexer.capture_span(|lexer| { - let condition = self.general_expression(lexer, ctx.reborrow())?; - Ok(condition) - })?; - let mut reject = ast::Block::default(); - reject.stmts.push(ast::Statement { - kind: ast::StatementKind::Break, - span, - }); - - body.stmts.push(ast::Statement { - kind: ast::StatementKind::If { - condition, - accept: ast::Block::default(), - reject, - }, - span, - }); - - let (block, span) = self.block(lexer, ctx.reborrow())?; - body.stmts.push(ast::Statement { - kind: ast::StatementKind::Block(block), - span, - }); - - ast::StatementKind::Loop { - body, - continuing: ast::Block::default(), - break_if: None, - } - } - "for" => { - let _ = lexer.next(); - lexer.expect(Token::Paren('('))?; - - ctx.local_table.push_scope(); - - if !lexer.skip(Token::Separator(';')) { - let num_statements = block.stmts.len(); - let (_, span) = lexer.capture_span(|lexer| { - self.statement(lexer, ctx.reborrow(), block) - })?; - - if block.stmts.len() != num_statements { - match block.stmts.last().unwrap().kind { - ast::StatementKind::Call { .. } - | ast::StatementKind::Assign { .. } - | ast::StatementKind::LocalDecl(_) => {} - _ => return Err(Error::InvalidForInitializer(span)), - } - } - }; - - let mut body = ast::Block::default(); - if !lexer.skip(Token::Separator(';')) { - let (condition, span) = lexer.capture_span(|lexer| { - let condition = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(';'))?; - Ok(condition) - })?; - let mut reject = ast::Block::default(); - reject.stmts.push(ast::Statement { - kind: ast::StatementKind::Break, - span, - }); - body.stmts.push(ast::Statement { - kind: ast::StatementKind::If { - condition, - accept: ast::Block::default(), - reject, - }, - span, - }); - }; - - let mut continuing = ast::Block::default(); - if !lexer.skip(Token::Paren(')')) { - self.function_call_or_assignment_statement( - lexer, - ctx.reborrow(), - &mut continuing, - )?; - lexer.expect(Token::Paren(')'))?; - } - - let (block, span) = self.block(lexer, ctx.reborrow())?; - body.stmts.push(ast::Statement { - kind: ast::StatementKind::Block(block), - span, - }); - - ctx.local_table.pop_scope(); - - ast::StatementKind::Loop { - body, - continuing, - break_if: None, - } - } - "break" => { - let (_, span) = lexer.next(); - // Check if the next token is an `if`, this indicates - // that the user tried to type out a `break if` which - // is illegal in this position. - let (peeked_token, peeked_span) = lexer.peek(); - if let Token::Word("if") = peeked_token { - let span = span.until(&peeked_span); - return Err(Error::InvalidBreakIf(span)); - } - ast::StatementKind::Break - } - "continue" => { - let _ = lexer.next(); - ast::StatementKind::Continue - } - "discard" => { - let _ = lexer.next(); - ast::StatementKind::Kill - } - // assignment or a function call - _ => { - self.function_call_or_assignment_statement(lexer, ctx.reborrow(), block)?; - lexer.expect(Token::Separator(';'))?; - self.pop_rule_span(lexer); - return Ok(()); - } - }; - - let span = self.pop_rule_span(lexer); - block.stmts.push(ast::Statement { kind, span }); - } - _ => { - self.assignment_statement(lexer, ctx.reborrow(), block)?; - self.pop_rule_span(lexer); - } - } - Ok(()) - } - - fn r#loop<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - let _ = lexer.next(); - let mut body = ast::Block::default(); - let mut continuing = ast::Block::default(); - let mut break_if = None; - - lexer.expect(Token::Paren('{'))?; - - ctx.local_table.push_scope(); - - loop { - if lexer.skip(Token::Word("continuing")) { - // Branch for the `continuing` block, this must be - // the last thing in the loop body - - // Expect a opening brace to start the continuing block - lexer.expect(Token::Paren('{'))?; - loop { - if lexer.skip(Token::Word("break")) { - // Branch for the `break if` statement, this statement - // has the form `break if ;` and must be the last - // statement in a continuing block - - // The break must be followed by an `if` to form - // the break if - lexer.expect(Token::Word("if"))?; - - let condition = self.general_expression(lexer, ctx.reborrow())?; - // Set the condition of the break if to the newly parsed - // expression - break_if = Some(condition); - - // Expect a semicolon to close the statement - lexer.expect(Token::Separator(';'))?; - // Expect a closing brace to close the continuing block, - // since the break if must be the last statement - lexer.expect(Token::Paren('}'))?; - // Stop parsing the continuing block - break; - } else if lexer.skip(Token::Paren('}')) { - // If we encounter a closing brace it means we have reached - // the end of the continuing block and should stop processing - break; - } else { - // Otherwise try to parse a statement - self.statement(lexer, ctx.reborrow(), &mut continuing)?; - } - } - // Since the continuing block must be the last part of the loop body, - // we expect to see a closing brace to end the loop body - lexer.expect(Token::Paren('}'))?; - break; - } - if lexer.skip(Token::Paren('}')) { - // If we encounter a closing brace it means we have reached - // the end of the loop body and should stop processing - break; - } - // Otherwise try to parse a statement - self.statement(lexer, ctx.reborrow(), &mut body)?; - } - - ctx.local_table.pop_scope(); - - Ok(ast::StatementKind::Loop { - body, - continuing, - break_if, - }) - } - - /// compound_statement - fn block<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result<(ast::Block<'a>, Span), Error<'a>> { - self.push_rule_span(Rule::Block, lexer); - - ctx.local_table.push_scope(); - - let _ = lexer.next(); - let mut statements = ast::Block::default(); - while !lexer.skip(Token::Paren('}')) { - self.statement(lexer, ctx.reborrow(), &mut statements)?; - } - - ctx.local_table.pop_scope(); - - let span = self.pop_rule_span(lexer); - Ok((statements, span)) - } - - fn varying_binding<'a>( - &mut self, - lexer: &mut Lexer<'a>, - ) -> Result, Error<'a>> { - let mut bind_parser = BindingParser::default(); - self.push_rule_span(Rule::Attribute, lexer); - - while lexer.skip(Token::Attribute) { - let (word, span) = lexer.next_ident_with_span()?; - bind_parser.parse(lexer, word, span)?; - } - - let span = self.pop_rule_span(lexer); - bind_parser.finish(span) - } - - fn function_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - out: &mut ast::TranslationUnit<'a>, - dependencies: &mut FastHashSet>, - ) -> Result, Error<'a>> { - self.push_rule_span(Rule::FunctionDecl, lexer); - // read function name - let fun_name = lexer.next_ident()?; - - let mut locals = Arena::new(); - - let mut ctx = ParseExpressionContext { - expressions: &mut out.expressions, - local_table: &mut super::SymbolTable::default(), - locals: &mut locals, - types: &mut out.types, - unresolved: dependencies, - }; - - // read parameter list - let mut arguments = Vec::new(); - lexer.expect(Token::Paren('('))?; - let mut ready = true; - while !lexer.skip(Token::Paren(')')) { - if !ready { - return Err(Error::Unexpected( - lexer.next().1, - ExpectedToken::Token(Token::Separator(',')), - )); - } - let binding = self.varying_binding(lexer)?; - - let param_name = lexer.next_ident()?; - - lexer.expect(Token::Separator(':'))?; - let param_type = self.type_decl(lexer, ctx.reborrow())?; - - let handle = ctx.locals.append(ast::Local, param_name.span); - ctx.local_table.add(param_name.name, handle); - arguments.push(ast::FunctionArgument { - name: param_name, - ty: param_type, - binding, - handle, - }); - ready = lexer.skip(Token::Separator(',')); - } - // read return type - let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { - let binding = self.varying_binding(lexer)?; - let ty = self.type_decl(lexer, ctx.reborrow())?; - Some(ast::FunctionResult { ty, binding }) - } else { - None - }; - - // read body - let body = self.block(lexer, ctx)?.0; - - let fun = ast::Function { - entry_point: None, - name: fun_name, - arguments, - result, - body, - locals, - }; - - // done - self.pop_rule_span(lexer); - - Ok(fun) - } - - fn global_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - out: &mut ast::TranslationUnit<'a>, - ) -> Result<(), Error<'a>> { - // read attributes - let mut binding = None; - let mut stage = None; - let mut workgroup_size = [0u32; 3]; - let mut early_depth_test = None; - let (mut bind_index, mut bind_group) = (None, None); - - self.push_rule_span(Rule::Attribute, lexer); - while lexer.skip(Token::Attribute) { - match lexer.next_ident_with_span()? { - ("binding", _) => { - lexer.expect(Token::Paren('('))?; - bind_index = Some(Self::non_negative_i32_literal(lexer)?); - lexer.expect(Token::Paren(')'))?; - } - ("group", _) => { - lexer.expect(Token::Paren('('))?; - bind_group = Some(Self::non_negative_i32_literal(lexer)?); - lexer.expect(Token::Paren(')'))?; - } - ("vertex", _) => { - stage = Some(crate::ShaderStage::Vertex); - } - ("fragment", _) => { - stage = Some(crate::ShaderStage::Fragment); - } - ("compute", _) => { - stage = Some(crate::ShaderStage::Compute); - } - ("workgroup_size", _) => { - lexer.expect(Token::Paren('('))?; - workgroup_size = [1u32; 3]; - for (i, size) in workgroup_size.iter_mut().enumerate() { - *size = Self::generic_non_negative_int_literal(lexer)?; - match lexer.next() { - (Token::Paren(')'), _) => break, - (Token::Separator(','), _) if i != 2 => (), - other => { - return Err(Error::Unexpected( - other.1, - ExpectedToken::WorkgroupSizeSeparator, - )) - } - } - } - } - ("early_depth_test", _) => { - let conservative = if lexer.skip(Token::Paren('(')) { - let (ident, ident_span) = lexer.next_ident_with_span()?; - let value = conv::map_conservative_depth(ident, ident_span)?; - lexer.expect(Token::Paren(')'))?; - Some(value) - } else { - None - }; - early_depth_test = Some(crate::EarlyDepthTest { conservative }); - } - (_, word_span) => return Err(Error::UnknownAttribute(word_span)), - } - } - - let attrib_span = self.pop_rule_span(lexer); - match (bind_group, bind_index) { - (Some(group), Some(index)) => { - binding = Some(crate::ResourceBinding { - group, - binding: index, - }); - } - (Some(_), None) => return Err(Error::MissingAttribute("binding", attrib_span)), - (None, Some(_)) => return Err(Error::MissingAttribute("group", attrib_span)), - (None, None) => {} - } - - let mut dependencies = FastHashSet::default(); - let mut ctx = ParseExpressionContext { - expressions: &mut out.expressions, - local_table: &mut super::SymbolTable::default(), - locals: &mut Arena::new(), - types: &mut out.types, - unresolved: &mut dependencies, - }; - - // read item - let start = lexer.start_byte_offset(); - let kind = match lexer.next() { - (Token::Separator(';'), _) => None, - (Token::Word("struct"), _) => { - let name = lexer.next_ident()?; - - let members = self.struct_body(lexer, ctx)?; - Some(ast::GlobalDeclKind::Struct(ast::Struct { name, members })) - } - (Token::Word("type"), _) => { - let name = lexer.next_ident()?; - - lexer.expect(Token::Operation('='))?; - let ty = self.type_decl(lexer, ctx)?; - lexer.expect(Token::Separator(';'))?; - Some(ast::GlobalDeclKind::Type(ast::TypeAlias { name, ty })) - } - (Token::Word("const"), _) => { - let name = lexer.next_ident()?; - - let ty = if lexer.skip(Token::Separator(':')) { - let ty = self.type_decl(lexer, ctx.reborrow())?; - Some(ty) - } else { - None - }; - - lexer.expect(Token::Operation('='))?; - let init = self.general_expression(lexer, ctx)?; - lexer.expect(Token::Separator(';'))?; - - Some(ast::GlobalDeclKind::Const(ast::Const { name, ty, init })) - } - (Token::Word("var"), _) => { - let mut var = self.variable_decl(lexer, ctx)?; - var.binding = binding.take(); - Some(ast::GlobalDeclKind::Var(var)) - } - (Token::Word("fn"), _) => { - let function = self.function_decl(lexer, out, &mut dependencies)?; - Some(ast::GlobalDeclKind::Fn(ast::Function { - entry_point: stage.map(|stage| ast::EntryPoint { - stage, - early_depth_test, - workgroup_size, - }), - ..function - })) - } - (Token::End, _) => return Ok(()), - other => return Err(Error::Unexpected(other.1, ExpectedToken::GlobalItem)), - }; - - if let Some(kind) = kind { - out.decls.append( - ast::GlobalDecl { kind, dependencies }, - lexer.span_from(start), - ); - } - - if !self.rules.is_empty() { - log::error!("Reached the end of global decl, but rule stack is not empty"); - log::error!("Rules: {:?}", self.rules); - return Err(Error::Other); - }; - - match binding { - None => Ok(()), - // we had the attribute but no var? - Some(_) => Err(Error::Other), - } - } - - pub fn parse(&mut self, source: &str) -> Result { - self.reset(); - - let mut lexer = Lexer::new(source); - let mut tu = ast::TranslationUnit::default(); - loop { - match self.global_decl(&mut lexer, &mut tu) { - Err(error) => return Err(error.as_parse_error(lexer.source)), - Ok(()) => { - if lexer.peek().0 == Token::End { - break; - } - } - } - } - - let index = index::Index::generate(&tu).map_err(|x| x.as_parse_error(source))?; - let module = Lowerer::new(&index) - .lower(&tu) - .map_err(|x| x.as_parse_error(source))?; - - Ok(module) - } -} - -/// An `ast::GlobalDecl` for which we have built the Naga IR equivalent. -enum LoweredGlobalDecl { - Function(Handle), - Var(Handle), - Const(Handle), - Type(Handle), - EntryPoint, -} - -enum ConstantOrInner { - Constant(Handle), - Inner(crate::ConstantInner), -} - -enum Texture { - Gather, - GatherCompare, - - Sample, - SampleBias, - SampleCompare, - SampleCompareLevel, - SampleGrad, - SampleLevel, - // SampleBaseClampToEdge, -} - -impl Texture { - pub fn map(word: &str) -> Option { - Some(match word { - "textureGather" => Self::Gather, - "textureGatherCompare" => Self::GatherCompare, - - "textureSample" => Self::Sample, - "textureSampleBias" => Self::SampleBias, - "textureSampleCompare" => Self::SampleCompare, - "textureSampleCompareLevel" => Self::SampleCompareLevel, - "textureSampleGrad" => Self::SampleGrad, - "textureSampleLevel" => Self::SampleLevel, - // "textureSampleBaseClampToEdge" => Some(Self::SampleBaseClampToEdge), - _ => return None, - }) - } - - pub const fn min_argument_count(&self) -> u32 { - match *self { - Self::Gather => 3, - Self::GatherCompare => 4, - - Self::Sample => 3, - Self::SampleBias => 5, - Self::SampleCompare => 5, - Self::SampleCompareLevel => 5, - Self::SampleGrad => 6, - Self::SampleLevel => 5, - // Self::SampleBaseClampToEdge => 3, - } - } -} - -struct Lowerer<'source, 'temp> { - index: &'temp index::Index<'source>, - layouter: Layouter, -} - -impl<'source, 'temp> Lowerer<'source, 'temp> { - pub fn new(index: &'temp index::Index<'source>) -> Self { - Self { - index, - layouter: Layouter::default(), - } - } - - pub fn lower( - &mut self, - tu: &'temp ast::TranslationUnit<'source>, - ) -> Result> { - let mut module = crate::Module::default(); - - let mut ctx = OutputContext { - ast_expressions: &tu.expressions, - globals: &mut FastHashMap::default(), - types: &tu.types, - module: &mut module, - }; - - for decl in self.index.visit_ordered() { - let span = tu.decls.get_span(decl); - let decl = &tu.decls[decl]; - - match decl.kind { - ast::GlobalDeclKind::Fn(ref f) => { - let decl = self.function(f, span, ctx.reborrow())?; - ctx.globals.insert(f.name.name, decl); - } - ast::GlobalDeclKind::Var(ref v) => { - let ty = self.resolve_ast_type(v.ty, ctx.reborrow())?; - - let init = v - .init - .map(|init| self.constant(init, ctx.reborrow())) - .transpose()?; - - let handle = ctx.module.global_variables.append( - crate::GlobalVariable { - name: Some(v.name.name.to_string()), - space: v.space, - binding: v.binding.clone(), - ty, - init, - }, - span, - ); - - ctx.globals - .insert(v.name.name, LoweredGlobalDecl::Var(handle)); - } - ast::GlobalDeclKind::Const(ref c) => { - let inner = self.constant_inner(c.init, ctx.reborrow())?; - let inner = match inner { - ConstantOrInner::Constant(c) => ctx.module.constants[c].inner.clone(), - ConstantOrInner::Inner(inner) => inner, - }; - - let inferred_type = match inner { - crate::ConstantInner::Scalar { width, value } => { - ctx.ensure_type_exists(crate::TypeInner::Scalar { - width, - kind: value.scalar_kind(), - }) - } - crate::ConstantInner::Composite { ty, .. } => ty, - }; - - let handle = ctx.module.constants.append( - crate::Constant { - name: Some(c.name.name.to_string()), - specialization: None, - inner, - }, - span, - ); - - let explicit_ty = - c.ty.map(|ty| self.resolve_ast_type(ty, ctx.reborrow())) - .transpose()?; - - if let Some(explicit) = explicit_ty { - if explicit != inferred_type { - let ty = &ctx.module.types[explicit]; - let explicit = ty.name.clone().unwrap_or_else(|| { - ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) - }); - - let ty = &ctx.module.types[inferred_type]; - let inferred = ty.name.clone().unwrap_or_else(|| { - ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) - }); - - return Err(Error::InitializationTypeMismatch( - c.name.span, - explicit, - inferred, - )); - } - } - - ctx.globals - .insert(c.name.name, LoweredGlobalDecl::Const(handle)); - } - ast::GlobalDeclKind::Struct(ref s) => { - let handle = self.r#struct(s, span, ctx.reborrow())?; - ctx.globals - .insert(s.name.name, LoweredGlobalDecl::Type(handle)); - } - ast::GlobalDeclKind::Type(ref alias) => { - let ty = self.resolve_ast_type(alias.ty, ctx.reborrow())?; - ctx.globals - .insert(alias.name.name, LoweredGlobalDecl::Type(ty)); - } - } - } - - Ok(module) - } - - fn function( - &mut self, - f: &ast::Function<'source>, - span: Span, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result> { - let mut local_table = FastHashMap::default(); - let mut local_variables = Arena::new(); - let mut expressions = Arena::new(); - let mut named_expressions = crate::NamedExpressions::default(); - - let arguments = f - .arguments - .iter() - .enumerate() - .map(|(i, arg)| { - let ty = self.resolve_ast_type(arg.ty, ctx.reborrow())?; - let expr = expressions - .append(crate::Expression::FunctionArgument(i as u32), arg.name.span); - local_table.insert(arg.handle, TypedExpression::non_reference(expr)); - named_expressions.insert(expr, arg.name.name.to_string()); - - Ok(crate::FunctionArgument { - name: Some(arg.name.name.to_string()), - ty, - binding: self.interpolate_default(&arg.binding, ty, ctx.reborrow()), - }) - }) - .collect::, _>>()?; - - let result = f - .result - .as_ref() - .map(|res| { - self.resolve_ast_type(res.ty, ctx.reborrow()) - .map(|ty| crate::FunctionResult { - ty, - binding: self.interpolate_default(&res.binding, ty, ctx.reborrow()), - }) - }) - .transpose()?; - - let mut typifier = super::Typifier::default(); - let mut body = self.block( - &f.body, - StatementContext { - local_table: &mut local_table, - globals: ctx.globals, - ast_expressions: ctx.ast_expressions, - typifier: &mut typifier, - variables: &mut local_variables, - naga_expressions: &mut expressions, - named_expressions: &mut named_expressions, - types: ctx.types, - module: ctx.module, - arguments: &arguments, - }, - )?; - ensure_block_returns(&mut body); - - let function = crate::Function { - name: Some(f.name.name.to_string()), - arguments, - result, - local_variables, - expressions, - named_expressions, - body, - }; - - if let Some(ref entry) = f.entry_point { - ctx.module.entry_points.push(crate::EntryPoint { - name: f.name.name.to_string(), - stage: entry.stage, - early_depth_test: entry.early_depth_test, - workgroup_size: entry.workgroup_size, - function, - }); - Ok(LoweredGlobalDecl::EntryPoint) - } else { - let handle = ctx.module.functions.append(function, span); - Ok(LoweredGlobalDecl::Function(handle)) - } - } - - fn block( - &mut self, - b: &ast::Block<'source>, - mut ctx: StatementContext<'source, '_, '_>, - ) -> Result> { - let mut block = crate::Block::default(); - - for stmt in b.stmts.iter() { - self.statement(stmt, &mut block, ctx.reborrow())?; - } - - Ok(block) - } - - fn statement( - &mut self, - stmt: &ast::Statement<'source>, - block: &mut crate::Block, - mut ctx: StatementContext<'source, '_, '_>, - ) -> Result<(), Error<'source>> { - let out = match stmt.kind { - ast::StatementKind::Block(ref block) => { - let block = self.block(block, ctx.reborrow())?; - crate::Statement::Block(block) - } - ast::StatementKind::LocalDecl(ref decl) => match *decl { - ast::LocalDecl::Let(ref l) => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let value = self.expression(l.init, ctx.as_expression(block, &mut emitter))?; - - let explicit_ty = - l.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) - .transpose()?; - - if let Some(ty) = explicit_ty { - let mut ctx = ctx.as_expression(block, &mut emitter); - let init_ty = ctx.register_type(value)?; - if !ctx.module.types[ty] - .inner - .equivalent(&ctx.module.types[init_ty].inner, &ctx.module.types) - { - return Err(Error::InitializationTypeMismatch( - l.name.span, - ctx.format_type(ty), - ctx.format_type(init_ty), - )); - } - } - - block.extend(emitter.finish(ctx.naga_expressions)); - ctx.local_table - .insert(l.handle, TypedExpression::non_reference(value)); - ctx.named_expressions.insert(value, l.name.name.to_string()); - - return Ok(()); - } - ast::LocalDecl::Var(ref v) => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let initializer = match v.init { - Some(init) => { - let initializer = - self.expression(init, ctx.as_expression(block, &mut emitter))?; - ctx.as_expression(block, &mut emitter) - .grow_types(initializer)?; - Some(initializer) - } - None => None, - }; - - let explicit_ty = - v.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) - .transpose()?; - - let ty = match (explicit_ty, initializer) { - (Some(explicit), Some(initializer)) => { - let ctx = ctx.as_expression(block, &mut emitter); - let initializer_ty = ctx.resolved_inner(initializer); - if !ctx.module.types[explicit] - .inner - .equivalent(initializer_ty, &ctx.module.types) - { - return Err(Error::InitializationTypeMismatch( - v.name.span, - ctx.format_type(explicit), - ctx.format_typeinner(initializer_ty), - )); - } - explicit - } - (Some(explicit), None) => explicit, - (None, Some(initializer)) => ctx - .as_expression(block, &mut emitter) - .register_type(initializer)?, - (None, None) => { - return Err(Error::MissingType(v.name.span)); - } - }; - - let var = ctx.variables.append( - crate::LocalVariable { - name: Some(v.name.name.to_string()), - ty, - init: None, - }, - stmt.span, - ); - - let handle = ctx - .as_expression(block, &mut emitter) - .interrupt_emitter(crate::Expression::LocalVariable(var), Span::UNDEFINED); - block.extend(emitter.finish(ctx.naga_expressions)); - ctx.local_table.insert( - v.handle, - TypedExpression { - handle, - is_reference: true, - }, - ); - - match initializer { - Some(initializer) => crate::Statement::Store { - pointer: handle, - value: initializer, - }, - None => return Ok(()), - } - } - }, - ast::StatementKind::If { - condition, - ref accept, - ref reject, - } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let condition = - self.expression(condition, ctx.as_expression(block, &mut emitter))?; - block.extend(emitter.finish(ctx.naga_expressions)); - - let accept = self.block(accept, ctx.reborrow())?; - let reject = self.block(reject, ctx.reborrow())?; - - crate::Statement::If { - condition, - accept, - reject, - } - } - ast::StatementKind::Switch { - selector, - ref cases, - } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let mut ectx = ctx.as_expression(block, &mut emitter); - let selector = self.expression(selector, ectx.reborrow())?; - - ectx.grow_types(selector)?; - let uint = - ectx.resolved_inner(selector).scalar_kind() == Some(crate::ScalarKind::Uint); - block.extend(emitter.finish(ctx.naga_expressions)); - - let cases = cases - .iter() - .map(|case| { - Ok(crate::SwitchCase { - value: match case.value { - ast::SwitchValue::I32(num) if !uint => { - crate::SwitchValue::Integer(num) - } - ast::SwitchValue::U32(num) if uint => { - crate::SwitchValue::Integer(num as i32) - } - ast::SwitchValue::Default => crate::SwitchValue::Default, - _ => { - return Err(Error::InvalidSwitchValue { - uint, - span: case.value_span, - }); - } - }, - body: self.block(&case.body, ctx.reborrow())?, - fall_through: case.fall_through, - }) - }) - .collect::>()?; - - crate::Statement::Switch { selector, cases } - } - ast::StatementKind::Loop { - ref body, - ref continuing, - break_if, - } => { - let body = self.block(body, ctx.reborrow())?; - let mut continuing = self.block(continuing, ctx.reborrow())?; - - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - let break_if = break_if - .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) - .transpose()?; - continuing.extend(emitter.finish(ctx.naga_expressions)); - - crate::Statement::Loop { - body, - continuing, - break_if, - } - } - ast::StatementKind::Break => crate::Statement::Break, - ast::StatementKind::Continue => crate::Statement::Continue, - ast::StatementKind::Return { value } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let value = value - .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) - .transpose()?; - block.extend(emitter.finish(ctx.naga_expressions)); - - crate::Statement::Return { value } - } - ast::StatementKind::Kill => crate::Statement::Kill, - ast::StatementKind::Call { - ref function, - ref arguments, - } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let _ = self.call( - stmt.span, - function, - arguments, - ctx.as_expression(block, &mut emitter), - )?; - block.extend(emitter.finish(ctx.naga_expressions)); - return Ok(()); - } - ast::StatementKind::Assign { target, op, value } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let expr = - self.expression_for_reference(target, ctx.as_expression(block, &mut emitter))?; - let mut value = self.expression(value, ctx.as_expression(block, &mut emitter))?; - - if !expr.is_reference { - let ty = if ctx.named_expressions.contains_key(&expr.handle) { - InvalidAssignmentType::ImmutableBinding - } else { - match ctx.naga_expressions[expr.handle] { - crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, - _ => InvalidAssignmentType::Other, - } - }; - - return Err(Error::InvalidAssignment { - span: ctx.ast_expressions.get_span(target), - ty, - }); - } - - let value = match op { - Some(op) => { - let mut ctx = ctx.as_expression(block, &mut emitter); - let mut left = ctx.apply_load_rule(expr); - ctx.binary_op_splat(op, &mut left, &mut value)?; - ctx.naga_expressions.append( - crate::Expression::Binary { - op, - left, - right: value, - }, - stmt.span, - ) - } - None => value, - }; - block.extend(emitter.finish(ctx.naga_expressions)); - - crate::Statement::Store { - pointer: expr.handle, - value, - } - } - ast::StatementKind::Increment(value) | ast::StatementKind::Decrement(value) => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let op = match stmt.kind { - ast::StatementKind::Increment(_) => crate::BinaryOperator::Add, - ast::StatementKind::Decrement(_) => crate::BinaryOperator::Subtract, - _ => unreachable!(), - }; - - let value_span = ctx.ast_expressions.get_span(value); - let reference = - self.expression_for_reference(value, ctx.as_expression(block, &mut emitter))?; - let mut ectx = ctx.as_expression(block, &mut emitter); - - ectx.grow_types(reference.handle)?; - let (kind, width) = match *ectx.resolved_inner(reference.handle) { - crate::TypeInner::ValuePointer { - size: None, - kind, - width, - .. - } => (kind, width), - crate::TypeInner::Pointer { base, .. } => match ectx.module.types[base].inner { - crate::TypeInner::Scalar { kind, width } => (kind, width), - _ => return Err(Error::BadIncrDecrReferenceType(value_span)), - }, - _ => return Err(Error::BadIncrDecrReferenceType(value_span)), - }; - let constant_inner = crate::ConstantInner::Scalar { - width, - value: match kind { - crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), - crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), - _ => return Err(Error::BadIncrDecrReferenceType(value_span)), - }, - }; - let constant = ectx.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: constant_inner, - }, - Span::UNDEFINED, - ); - - let left = ectx.naga_expressions.append( - crate::Expression::Load { - pointer: reference.handle, - }, - value_span, - ); - let right = - ectx.interrupt_emitter(crate::Expression::Constant(constant), Span::UNDEFINED); - let value = ectx - .naga_expressions - .append(crate::Expression::Binary { op, left, right }, stmt.span); - - block.extend(emitter.finish(ctx.naga_expressions)); - crate::Statement::Store { - pointer: reference.handle, - value, - } - } - ast::StatementKind::Ignore(expr) => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let _ = self.expression(expr, ctx.as_expression(block, &mut emitter))?; - block.extend(emitter.finish(ctx.naga_expressions)); - return Ok(()); - } - }; - - block.push(out, stmt.span); - - Ok(()) - } - - fn expression( - &mut self, - expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let expr = self.expression_for_reference(expr, ctx.reborrow())?; - Ok(ctx.apply_load_rule(expr)) - } - - fn expression_for_reference( - &mut self, - expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result> { - let span = ctx.ast_expressions.get_span(expr); - let expr = &ctx.ast_expressions[expr]; - - let (expr, is_reference) = match *expr { - ast::Expression::Literal(literal) => { - let inner = match literal { - ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Float(f as _), - }, - ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Sint(i as _), - }, - ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(u as _), - }, - ast::Literal::Number(_) => { - unreachable!("got abstract numeric type when not expected"); - } - ast::Literal::Bool(b) => crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(b), - }, - }; - let handle = ctx.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Span::UNDEFINED, - ); - let handle = ctx.interrupt_emitter(crate::Expression::Constant(handle), span); - return Ok(TypedExpression::non_reference(handle)); - } - ast::Expression::Ident(ast::IdentExpr::Local(local)) => { - return Ok(ctx.local_table[&local]) - } - ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { - return if let Some(global) = ctx.globals.get(name) { - let (expr, is_reference) = match *global { - LoweredGlobalDecl::Var(handle) => ( - crate::Expression::GlobalVariable(handle), - ctx.module.global_variables[handle].space - != crate::AddressSpace::Handle, - ), - LoweredGlobalDecl::Const(handle) => { - (crate::Expression::Constant(handle), false) - } - _ => { - return Err(Error::Unexpected(span, ExpectedToken::Variable)); - } - }; - - let handle = ctx.interrupt_emitter(expr, span); - Ok(TypedExpression { - handle, - is_reference, - }) - } else { - Err(Error::UnknownIdent(span, name)) - } - } - ast::Expression::Construct { - ref ty, - ty_span, - ref components, - } => { - let handle = self.construct(span, ty, ty_span, components, ctx.reborrow())?; - return Ok(TypedExpression::non_reference(handle)); - } - ast::Expression::Unary { op, expr } => { - let expr = self.expression(expr, ctx.reborrow())?; - (crate::Expression::Unary { op, expr }, false) - } - ast::Expression::AddrOf(expr) => { - // The `&` operator simply converts a reference to a pointer. And since a - // reference is required, the Load Rule is not applied. - let expr = self.expression_for_reference(expr, ctx.reborrow())?; - if !expr.is_reference { - return Err(Error::NotReference("the operand of the `&` operator", span)); - } - - // No code is generated. We just declare the pointer a reference now. - return Ok(TypedExpression { - is_reference: false, - ..expr - }); - } - ast::Expression::Deref(expr) => { - // The pointer we dereference must be loaded. - let pointer = self.expression(expr, ctx.reborrow())?; - - ctx.grow_types(pointer)?; - if ctx.resolved_inner(pointer).pointer_space().is_none() { - return Err(Error::NotPointer(span)); - } - - return Ok(TypedExpression { - handle: pointer, - is_reference: true, - }); - } - ast::Expression::Binary { op, left, right } => { - // Load both operands. - let mut left = self.expression(left, ctx.reborrow())?; - let mut right = self.expression(right, ctx.reborrow())?; - ctx.binary_op_splat(op, &mut left, &mut right)?; - (crate::Expression::Binary { op, left, right }, false) - } - ast::Expression::Call { - ref function, - ref arguments, - } => { - let handle = self - .call(span, function, arguments, ctx.reborrow())? - .ok_or(Error::FunctionReturnsVoid(function.span))?; - return Ok(TypedExpression::non_reference(handle)); - } - ast::Expression::Index { base, index } => { - let expr = self.expression_for_reference(base, ctx.reborrow())?; - let index = self.expression(index, ctx.reborrow())?; - - ctx.grow_types(expr.handle)?; - let wgsl_pointer = - ctx.resolved_inner(expr.handle).pointer_space().is_some() && !expr.is_reference; - - if wgsl_pointer { - return Err(Error::Pointer( - "the value indexed by a `[]` subscripting expression", - ctx.ast_expressions.get_span(base), - )); - } - - if let crate::Expression::Constant(constant) = ctx.naga_expressions[index] { - let span = ctx.naga_expressions.get_span(index); - let index = match ctx.module.constants[constant].inner { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Sint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), - _ => Err(Error::BadU32Constant(span)), - }?; - - ( - crate::Expression::AccessIndex { - base: expr.handle, - index, - }, - expr.is_reference, - ) - } else { - ( - crate::Expression::Access { - base: expr.handle, - index, - }, - expr.is_reference, - ) - } - } - ast::Expression::Member { base, ref field } => { - let TypedExpression { - handle, - is_reference, - } = self.expression_for_reference(base, ctx.reborrow())?; - - ctx.grow_types(handle)?; - let temp_inner; - let (composite, wgsl_pointer) = match *ctx.resolved_inner(handle) { - crate::TypeInner::Pointer { base, .. } => { - (&ctx.module.types[base].inner, !is_reference) - } - crate::TypeInner::ValuePointer { - size: None, - kind, - width, - .. - } => { - temp_inner = crate::TypeInner::Scalar { kind, width }; - (&temp_inner, !is_reference) - } - crate::TypeInner::ValuePointer { - size: Some(size), - kind, - width, - .. - } => { - temp_inner = crate::TypeInner::Vector { size, kind, width }; - (&temp_inner, !is_reference) - } - ref other => (other, false), - }; - - if wgsl_pointer { - return Err(Error::Pointer( - "the value accessed by a `.member` expression", - ctx.ast_expressions.get_span(base), - )); - } - - let access = match *composite { - crate::TypeInner::Struct { ref members, .. } => { - let index = members - .iter() - .position(|m| m.name.as_deref() == Some(field.name)) - .ok_or(Error::BadAccessor(field.span))? - as u32; - - ( - crate::Expression::AccessIndex { - base: handle, - index, - }, - is_reference, - ) - } - crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { - match Composition::make(field.name, field.span)? { - Composition::Multi(size, pattern) => { - let vector = ctx.apply_load_rule(TypedExpression { - handle, - is_reference, - }); - - ( - crate::Expression::Swizzle { - size, - vector, - pattern, - }, - false, - ) - } - Composition::Single(index) => ( - crate::Expression::AccessIndex { - base: handle, - index, - }, - is_reference, - ), - } - } - _ => return Err(Error::BadAccessor(field.span)), - }; - - access - } - ast::Expression::Bitcast { expr, to, ty_span } => { - let expr = self.expression(expr, ctx.reborrow())?; - let to_resolved = self.resolve_ast_type(to, ctx.as_output())?; - - let kind = match ctx.module.types[to_resolved].inner { - crate::TypeInner::Scalar { kind, .. } => kind, - crate::TypeInner::Vector { kind, .. } => kind, - _ => { - let ty = &ctx.typifier[expr]; - return Err(Error::BadTypeCast { - from_type: ctx.format_type_resolution(ty), - span: ty_span, - to_type: ctx.format_type(to_resolved), - }); - } - }; - - ( - crate::Expression::As { - expr, - kind, - convert: None, - }, - false, - ) - } - }; - - let handle = ctx.naga_expressions.append(expr, span); - Ok(TypedExpression { - handle, - is_reference, - }) - } - - /// Generate Naga IR for call expressions and statements, and type - /// constructor expressions. - /// - /// The "function" being called is simply an `Ident` that we know refers to - /// some module-scope definition. - /// - /// - If it is the name of a type, then the expression is a type constructor - /// expression: either constructing a value from components, a conversion - /// expression, or a zero value expression. - /// - /// - If it is the name of a function, then we're generating a [`Call`] - /// statement. We may be in the midst of generating code for an - /// expression, in which case we must generate an `Emit` statement to - /// force evaluation of the IR expressions we've generated so far, add the - /// `Call` statement to the current block, and then resume generating - /// expressions. - /// - /// [`Call`]: crate::Statement::Call - fn call( - &mut self, - span: Span, - function: &ast::Ident<'source>, - arguments: &[Handle>], - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result>, Error<'source>> { - match ctx.globals.get(function.name) { - Some(&LoweredGlobalDecl::Type(ty)) => { - let handle = self.construct( - span, - &ast::ConstructorType::Type(ty), - function.span, - arguments, - ctx.reborrow(), - )?; - Ok(Some(handle)) - } - Some(&LoweredGlobalDecl::Const(_) | &LoweredGlobalDecl::Var(_)) => { - Err(Error::Unexpected(function.span, ExpectedToken::Function)) - } - Some(&LoweredGlobalDecl::EntryPoint) => Err(Error::CalledEntryPoint(function.span)), - Some(&LoweredGlobalDecl::Function(function)) => { - let arguments = arguments - .iter() - .map(|&arg| self.expression(arg, ctx.reborrow())) - .collect::, _>>()?; - - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - let result = ctx.module.functions[function].result.is_some().then(|| { - ctx.naga_expressions - .append(crate::Expression::CallResult(function), span) - }); - ctx.emitter.start(ctx.naga_expressions); - ctx.block.push( - crate::Statement::Call { - function, - arguments, - result, - }, - span, - ); - - Ok(result) - } - None => { - let span = function.span; - let expr = if let Some(fun) = conv::map_relational_fun(function.name) { - let mut args = ctx.prepare_args(arguments, 1, span); - let argument = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::Relational { fun, argument } - } else if let Some(axis) = conv::map_derivative_axis(function.name) { - let mut args = ctx.prepare_args(arguments, 1, span); - let expr = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::Derivative { axis, expr } - } else if let Some(fun) = conv::map_standard_fun(function.name) { - let expected = fun.argument_count() as _; - let mut args = ctx.prepare_args(arguments, expected, span); - - let arg = self.expression(args.next()?, ctx.reborrow())?; - let arg1 = args - .next() - .map(|x| self.expression(x, ctx.reborrow())) - .ok() - .transpose()?; - let arg2 = args - .next() - .map(|x| self.expression(x, ctx.reborrow())) - .ok() - .transpose()?; - let arg3 = args - .next() - .map(|x| self.expression(x, ctx.reborrow())) - .ok() - .transpose()?; - - args.finish()?; - - crate::Expression::Math { - fun, - arg, - arg1, - arg2, - arg3, - } - } else if let Some(fun) = Texture::map(function.name) { - self.texture_sample_helper(fun, arguments, span, ctx.reborrow())? - } else { - match function.name { - "select" => { - let mut args = ctx.prepare_args(arguments, 3, span); - - let reject = self.expression(args.next()?, ctx.reborrow())?; - let accept = self.expression(args.next()?, ctx.reborrow())?; - let condition = self.expression(args.next()?, ctx.reborrow())?; - - args.finish()?; - - crate::Expression::Select { - reject, - accept, - condition, - } - } - "arrayLength" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let expr = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::ArrayLength(expr) - } - "atomicLoad" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::Load { pointer } - } - "atomicStore" => { - let mut args = ctx.prepare_args(arguments, 2, span); - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; - let value = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - ctx.emitter.start(ctx.naga_expressions); - ctx.block - .push(crate::Statement::Store { pointer, value }, span); - return Ok(None); - } - "atomicAdd" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Add, - arguments, - ctx.reborrow(), - )?)) - } - "atomicSub" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Subtract, - arguments, - ctx.reborrow(), - )?)) - } - "atomicAnd" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::And, - arguments, - ctx.reborrow(), - )?)) - } - "atomicOr" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::InclusiveOr, - arguments, - ctx.reborrow(), - )?)) - } - "atomicXor" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::ExclusiveOr, - arguments, - ctx.reborrow(), - )?)) - } - "atomicMin" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Min, - arguments, - ctx.reborrow(), - )?)) - } - "atomicMax" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Max, - arguments, - ctx.reborrow(), - )?)) - } - "atomicExchange" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Exchange { compare: None }, - arguments, - ctx.reborrow(), - )?)) - } - "atomicCompareExchangeWeak" => { - let mut args = ctx.prepare_args(arguments, 3, span); - - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; - - let compare = self.expression(args.next()?, ctx.reborrow())?; - - let value = args.next()?; - let value_span = ctx.ast_expressions.get_span(value); - let value = self.expression(value, ctx.reborrow())?; - ctx.grow_types(value)?; - - args.finish()?; - - let expression = match *ctx.resolved_inner(value) { - crate::TypeInner::Scalar { kind, width } => { - let bool_ty = ctx.module.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: crate::BOOL_WIDTH, - }, - }, - Span::UNDEFINED, - ); - let scalar_ty = ctx.module.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { kind, width }, - }, - Span::UNDEFINED, - ); - let struct_ty = ctx.module.types.insert( - crate::Type { - name: Some( - "__atomic_compare_exchange_result".to_string(), - ), - inner: crate::TypeInner::Struct { - members: vec![ - crate::StructMember { - name: Some("old_value".to_string()), - ty: scalar_ty, - binding: None, - offset: 0, - }, - crate::StructMember { - name: Some("exchanged".to_string()), - ty: bool_ty, - binding: None, - offset: 4, - }, - ], - span: 8, - }, - }, - Span::UNDEFINED, - ); - crate::Expression::AtomicResult { - ty: struct_ty, - comparison: true, - } - } - _ => return Err(Error::InvalidAtomicOperandType(value_span)), - }; - - let result = ctx.interrupt_emitter(expression, span); - ctx.block.push( - crate::Statement::Atomic { - pointer, - fun: crate::AtomicFunction::Exchange { - compare: Some(compare), - }, - value, - result, - }, - span, - ); - return Ok(Some(result)); - } - "storageBarrier" => { - ctx.prepare_args(arguments, 0, span).finish()?; - - ctx.block - .push(crate::Statement::Barrier(crate::Barrier::STORAGE), span); - return Ok(None); - } - "workgroupBarrier" => { - ctx.prepare_args(arguments, 0, span).finish()?; - - ctx.block - .push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP), span); - return Ok(None); - } - "textureStore" => { - let mut args = ctx.prepare_args(arguments, 3, span); - - let image = args.next()?; - let image_span = ctx.ast_expressions.get_span(image); - let image = self.expression(image, ctx.reborrow())?; - - let coordinate = self.expression(args.next()?, ctx.reborrow())?; - - let (_, arrayed) = ctx.image_data(image, image_span)?; - let array_index = arrayed - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - let value = self.expression(args.next()?, ctx.reborrow())?; - - args.finish()?; - - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - ctx.emitter.start(ctx.naga_expressions); - let stmt = crate::Statement::ImageStore { - image, - coordinate, - array_index, - value, - }; - ctx.block.push(stmt, span); - return Ok(None); - } - "textureLoad" => { - let mut args = ctx.prepare_args(arguments, 3, span); - - let image = args.next()?; - let image_span = ctx.ast_expressions.get_span(image); - let image = self.expression(image, ctx.reborrow())?; - - let coordinate = self.expression(args.next()?, ctx.reborrow())?; - - let (class, arrayed) = ctx.image_data(image, image_span)?; - let array_index = arrayed - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - let level = class - .is_mipmapped() - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - let sample = class - .is_multisampled() - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - args.finish()?; - - crate::Expression::ImageLoad { - image, - coordinate, - array_index, - level, - sample, - } - } - "textureDimensions" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; - let level = args - .next() - .map(|arg| self.expression(arg, ctx.reborrow())) - .ok() - .transpose()?; - args.finish()?; - - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::Size { level }, - } - } - "textureNumLevels" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::NumLevels, - } - } - "textureNumLayers" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::NumLayers, - } - } - "textureNumSamples" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::NumSamples, - } - } - _ => return Err(Error::UnknownIdent(function.span, function.name)), - } - }; - - let expr = ctx.naga_expressions.append(expr, span); - Ok(Some(expr)) - } - } - } - - fn atomic_pointer( - &mut self, - expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let span = ctx.ast_expressions.get_span(expr); - let pointer = self.expression(expr, ctx.reborrow())?; - - ctx.grow_types(pointer)?; - match *ctx.resolved_inner(pointer) { - crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { - crate::TypeInner::Atomic { .. } => Ok(pointer), - ref other => { - log::error!("Pointer type to {:?} passed to atomic op", other); - Err(Error::InvalidAtomicPointer(span)) - } - }, - ref other => { - log::error!("Type {:?} passed to atomic op", other); - Err(Error::InvalidAtomicPointer(span)) - } - } - } - - fn atomic_helper( - &mut self, - span: Span, - fun: crate::AtomicFunction, - args: &[Handle>], - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let mut args = ctx.prepare_args(args, 2, span); - - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; - - let value = args.next()?; - let value = self.expression(value, ctx.reborrow())?; - let ty = ctx.register_type(value)?; - - args.finish()?; - - let result = ctx.interrupt_emitter( - crate::Expression::AtomicResult { - ty, - comparison: false, - }, - span, - ); - ctx.block.push( - crate::Statement::Atomic { - pointer, - fun, - value, - result, - }, - span, - ); - Ok(result) - } - - fn texture_sample_helper( - &mut self, - fun: Texture, - args: &[Handle>], - span: Span, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result> { - let mut args = ctx.prepare_args(args, fun.min_argument_count(), span); - - let (image, gather) = match fun { - Texture::Gather => { - let image_or_component = args.next()?; - match self.gather_component(image_or_component, ctx.reborrow())? { - Some(component) => { - let image = args.next()?; - (image, Some(component)) - } - None => (image_or_component, Some(crate::SwizzleComponent::X)), - } - } - Texture::GatherCompare => { - let image = args.next()?; - (image, Some(crate::SwizzleComponent::X)) - } - - _ => { - let image = args.next()?; - (image, None) - } - }; - - let image_span = ctx.ast_expressions.get_span(image); - let image = self.expression(image, ctx.reborrow())?; - - let sampler = self.expression(args.next()?, ctx.reborrow())?; - - let coordinate = self.expression(args.next()?, ctx.reborrow())?; - - let (_, arrayed) = ctx.image_data(image, image_span)?; - let array_index = arrayed - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - let (level, depth_ref) = match fun { - Texture::Gather => (crate::SampleLevel::Zero, None), - Texture::GatherCompare => { - let reference = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Zero, Some(reference)) - } - - Texture::Sample => (crate::SampleLevel::Auto, None), - Texture::SampleBias => { - let bias = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Bias(bias), None) - } - Texture::SampleCompare => { - let reference = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Auto, Some(reference)) - } - Texture::SampleCompareLevel => { - let reference = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Zero, Some(reference)) - } - Texture::SampleGrad => { - let x = self.expression(args.next()?, ctx.reborrow())?; - let y = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Gradient { x, y }, None) - } - Texture::SampleLevel => { - let level = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Exact(level), None) - } - }; - - let offset = args - .next() - .map(|arg| self.constant(arg, ctx.as_output())) - .ok() - .transpose()?; - - args.finish()?; - - Ok(crate::Expression::ImageSample { - image, - sampler, - gather, - coordinate, - array_index, - offset, - level, - depth_ref, - }) - } - - fn gather_component( - &mut self, - expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let span = ctx.ast_expressions.get_span(expr); - - let constant = match self.constant_inner(expr, ctx.as_output()).ok() { - Some(ConstantOrInner::Constant(c)) => ctx.module.constants[c].inner.clone(), - Some(ConstantOrInner::Inner(inner)) => inner, - None => return Ok(None), - }; - - let int = match constant { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Sint(i), - .. - } if i >= 0 => i as u64, - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(i), - .. - } => i, - _ => { - return Err(Error::InvalidGatherComponent(span)); - } - }; - - crate::SwizzleComponent::XYZW - .get(int as usize) - .copied() - .map(Some) - .ok_or(Error::InvalidGatherComponent(span)) - } - - fn r#struct( - &mut self, - s: &ast::Struct<'source>, - span: Span, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let mut offset = 0; - let mut struct_alignment = Alignment::ONE; - let mut members = Vec::with_capacity(s.members.len()); - - for member in s.members.iter() { - let ty = self.resolve_ast_type(member.ty, ctx.reborrow())?; - - self.layouter - .update(&ctx.module.types, &ctx.module.constants) - .unwrap(); - - let member_min_size = self.layouter[ty].size; - let member_min_alignment = self.layouter[ty].alignment; - - let member_size = if let Some((size, span)) = member.size { - if size < member_min_size { - return Err(Error::SizeAttributeTooLow(span, member_min_size)); - } else { - size - } - } else { - member_min_size - }; - - let member_alignment = if let Some((align, span)) = member.align { - if let Some(alignment) = Alignment::new(align) { - if alignment < member_min_alignment { - return Err(Error::AlignAttributeTooLow(span, member_min_alignment)); - } else { - alignment - } - } else { - return Err(Error::NonPowerOfTwoAlignAttribute(span)); - } - } else { - member_min_alignment - }; - - let binding = self.interpolate_default(&member.binding, ty, ctx.reborrow()); - - offset = member_alignment.round_up(offset); - struct_alignment = struct_alignment.max(member_alignment); - - members.push(crate::StructMember { - name: Some(member.name.name.to_owned()), - ty, - binding, - offset, - }); - - offset += member_size; - } - - let size = struct_alignment.round_up(offset); - let inner = crate::TypeInner::Struct { - members, - span: size, - }; - - let handle = ctx.module.types.insert( - crate::Type { - name: Some(s.name.name.to_string()), - inner, - }, - span, - ); - Ok(handle) - } - - /// Return a Naga `Handle` representing the front-end type `handle`. - fn resolve_ast_type( - &mut self, - handle: Handle>, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let inner = match ctx.types[handle] { - ast::Type::Scalar { kind, width } => crate::TypeInner::Scalar { kind, width }, - ast::Type::Vector { size, kind, width } => { - crate::TypeInner::Vector { size, kind, width } - } - ast::Type::Matrix { - rows, - columns, - width, - } => crate::TypeInner::Matrix { - columns, - rows, - width, - }, - ast::Type::Atomic { kind, width } => crate::TypeInner::Atomic { kind, width }, - ast::Type::Pointer { base, space } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; - crate::TypeInner::Pointer { base, space } - } - ast::Type::Array { base, size } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; - self.layouter - .update(&ctx.module.types, &ctx.module.constants) - .unwrap(); - - crate::TypeInner::Array { - base, - size: match size { - ast::ArraySize::Constant(constant) => { - let constant = self.constant(constant, ctx.reborrow())?; - crate::ArraySize::Constant(constant) - } - ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, - }, - stride: self.layouter[base].to_stride(), - } - } - ast::Type::Image { - dim, - arrayed, - class, - } => crate::TypeInner::Image { - dim, - arrayed, - class, - }, - ast::Type::Sampler { comparison } => crate::TypeInner::Sampler { comparison }, - ast::Type::BindingArray { base, size } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; - - crate::TypeInner::BindingArray { - base, - size: match size { - ast::ArraySize::Constant(constant) => { - let constant = self.constant(constant, ctx.reborrow())?; - crate::ArraySize::Constant(constant) - } - ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, - }, - } - } - ast::Type::User(ref ident) => { - return match ctx.globals.get(ident.name) { - Some(&LoweredGlobalDecl::Type(handle)) => Ok(handle), - Some(_) => Err(Error::Unexpected(ident.span, ExpectedToken::Type)), - None => Err(Error::UnknownType(ident.span)), - } - } - }; - - Ok(ctx.ensure_type_exists(inner)) - } - - /// Find or construct a Naga [`Constant`] whose value is `expr`. - /// - /// The `ctx` indicates the Naga [`Module`] to which we should add - /// new `Constant`s or [`Type`]s as needed. - /// - /// [`Module`]: crate::Module - /// [`Constant`]: crate::Constant - /// [`Type`]: crate::Type - fn constant( - &mut self, - expr: Handle>, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let inner = match self.constant_inner(expr, ctx.reborrow())? { - ConstantOrInner::Constant(c) => return Ok(c), - ConstantOrInner::Inner(inner) => inner, - }; - - let c = ctx.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Span::UNDEFINED, - ); - Ok(c) - } - - fn constant_inner( - &mut self, - expr: Handle>, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result> { - let span = ctx.ast_expressions.get_span(expr); - let inner = match ctx.ast_expressions[expr] { - ast::Expression::Literal(literal) => match literal { - ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Float(f as _), - }, - ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Sint(i as _), - }, - ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(u as _), - }, - ast::Literal::Number(_) => { - unreachable!("got abstract numeric type when not expected"); - } - ast::Literal::Bool(b) => crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(b), - }, - }, - ast::Expression::Ident(ast::IdentExpr::Local(_)) => { - return Err(Error::Unexpected(span, ExpectedToken::Constant)) - } - ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { - return if let Some(global) = ctx.globals.get(name) { - match *global { - LoweredGlobalDecl::Const(handle) => Ok(ConstantOrInner::Constant(handle)), - _ => Err(Error::Unexpected(span, ExpectedToken::Constant)), - } - } else { - Err(Error::UnknownIdent(span, name)) - } - } - ast::Expression::Construct { - ref ty, - ref components, - .. - } => self.const_construct(span, ty, components, ctx.reborrow())?, - ast::Expression::Call { - ref function, - ref arguments, - } => match ctx.globals.get(function.name) { - Some(&LoweredGlobalDecl::Type(ty)) => self.const_construct( - span, - &ast::ConstructorType::Type(ty), - arguments, - ctx.reborrow(), - )?, - Some(_) => return Err(Error::ConstExprUnsupported(span)), - None => return Err(Error::UnknownIdent(function.span, function.name)), - }, - _ => return Err(Error::ConstExprUnsupported(span)), - }; - - Ok(ConstantOrInner::Inner(inner)) - } - - fn interpolate_default( - &mut self, - binding: &Option, - ty: Handle, - ctx: OutputContext<'source, '_, '_>, - ) -> Option { - let mut binding = binding.clone(); - if let Some(ref mut binding) = binding { - binding.apply_default_interpolation(&ctx.module.types[ty].inner); - } - - binding - } -} - -pub fn parse_str(source: &str) -> Result { - Parser::new().parse(source) -} diff --git a/src/front/wgsl/ast.rs b/src/front/wgsl/parse/ast.rs similarity index 97% rename from src/front/wgsl/ast.rs rename to src/front/wgsl/parse/ast.rs index eff74530f..734d9769f 100644 --- a/src/front/wgsl/ast.rs +++ b/src/front/wgsl/parse/ast.rs @@ -1,4 +1,4 @@ -use super::Number; +use crate::front::wgsl::parse::number::Number; use crate::{Arena, FastHashSet, Handle, Span}; use std::hash::Hash; @@ -106,6 +106,9 @@ pub struct EntryPoint { pub workgroup_size: [u32; 3], } +#[cfg(doc)] +use crate::front::wgsl::lower::{ExpressionContext, StatementContext}; + #[derive(Debug)] pub struct Function<'a> { pub entry_point: Option, @@ -135,8 +138,8 @@ pub struct Function<'a> { /// [`LocalDecl`]: StatementKind::LocalDecl /// [`arguments`]: Function::arguments /// [`Ident`]: Expression::Ident - /// [`StatementContext::local_table`]: super::StatementContext::local_table - /// [`ExpressionContext::local_table`]: super::ExpressionContext::local_table + /// [`StatementContext::local_table`]: StatementContext::local_table + /// [`ExpressionContext::local_table`]: ExpressionContext::local_table pub locals: Arena, pub body: Block<'a>, @@ -378,6 +381,9 @@ pub enum Literal { Number(Number), } +#[cfg(doc)] +use crate::front::wgsl::lower::Lowerer; + #[derive(Debug)] pub enum Expression<'a> { Literal(Literal), @@ -423,7 +429,7 @@ pub enum Expression<'a> { /// everything's definition in hand, and can decide whether to emit a Naga /// [`Constant`], [`As`], [`Splat`], or [`Compose`] expression. /// - /// [`Lowerer::call`]: super::Lowerer::call + /// [`Lowerer::call`]: Lowerer::call /// [`Constant`]: crate::Expression::Constant /// [`As`]: crate::Expression::As /// [`Splat`]: crate::Expression::Splat diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/parse/conv.rs similarity index 100% rename from src/front/wgsl/conv.rs rename to src/front/wgsl/parse/conv.rs diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/parse/lexer.rs similarity index 90% rename from src/front/wgsl/lexer.rs rename to src/front/wgsl/parse/lexer.rs index d6975bf98..4654d4087 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/parse/lexer.rs @@ -1,6 +1,29 @@ -use super::{conv, number::consume_number, Error, ExpectedToken, Token, TokenSpan}; +use super::{number::consume_number, Error, ExpectedToken}; +use crate::front::wgsl::error::NumberError; +use crate::front::wgsl::parse::{conv, Number}; use crate::Span; +type TokenSpan<'a> = (Token<'a>, Span); + +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum Token<'a> { + Separator(char), + Paren(char), + Attribute, + Number(Result), + Word(&'a str), + Operation(char), + LogicalOperation(char), + ShiftOperation(char), + AssignmentOperation(char), + IncrementOperation, + DecrementOperation, + Arrow, + Unknown(char), + Trivia, + End, +} + fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { let pos = input.find(|c| !what(c)).unwrap_or(input.len()); input.split_at(pos) @@ -176,15 +199,15 @@ fn is_word_part(c: char) -> bool { } #[derive(Clone)] -pub(super) struct Lexer<'a> { +pub(in crate::front::wgsl) struct Lexer<'a> { input: &'a str, - pub(super) source: &'a str, + pub(in crate::front::wgsl) source: &'a str, // The byte offset of the end of the last non-trivia token. last_end_offset: usize, } impl<'a> Lexer<'a> { - pub(super) const fn new(input: &'a str) -> Self { + pub(in crate::front::wgsl) const fn new(input: &'a str) -> Self { Lexer { input, source: input, @@ -211,7 +234,7 @@ impl<'a> Lexer<'a> { Ok((res, Span::from(start..end))) } - pub(super) fn start_byte_offset(&mut self) -> usize { + pub(in crate::front::wgsl) fn start_byte_offset(&mut self) -> usize { loop { // Eat all trivia because `next` doesn't eat trailing trivia. let (token, rest) = consume_token(self.input, false); @@ -234,7 +257,7 @@ impl<'a> Lexer<'a> { self.source.len() - self.input.len() } - pub(super) fn span_from(&self, offset: usize) -> Span { + pub(in crate::front::wgsl) fn span_from(&self, offset: usize) -> Span { Span::from(offset..self.last_end_offset) } @@ -243,7 +266,7 @@ impl<'a> Lexer<'a> { /// Assume we are a parse state where bit shift operators may /// occur, but not angle brackets. #[must_use] - pub(super) fn next(&mut self) -> TokenSpan<'a> { + pub(in crate::front::wgsl) fn next(&mut self) -> TokenSpan<'a> { self.next_impl(false) } @@ -252,7 +275,7 @@ impl<'a> Lexer<'a> { /// Assume we are in a parse state where angle brackets may occur, /// but not bit shift operators. #[must_use] - pub(super) fn next_generic(&mut self) -> TokenSpan<'a> { + pub(in crate::front::wgsl) fn next_generic(&mut self) -> TokenSpan<'a> { self.next_impl(true) } @@ -275,12 +298,15 @@ impl<'a> Lexer<'a> { } #[must_use] - pub(super) fn peek(&mut self) -> TokenSpan<'a> { + pub(in crate::front::wgsl) fn peek(&mut self) -> TokenSpan<'a> { let (token, _) = self.peek_token_and_rest(); token } - pub(super) fn expect_span(&mut self, expected: Token<'a>) -> Result> { + pub(in crate::front::wgsl) fn expect_span( + &mut self, + expected: Token<'a>, + ) -> Result> { let next = self.next(); if next.0 == expected { Ok(next.1) @@ -289,12 +315,15 @@ impl<'a> Lexer<'a> { } } - pub(super) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { + pub(in crate::front::wgsl) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { self.expect_span(expected)?; Ok(()) } - pub(super) fn expect_generic_paren(&mut self, expected: char) -> Result<(), Error<'a>> { + pub(in crate::front::wgsl) fn expect_generic_paren( + &mut self, + expected: char, + ) -> Result<(), Error<'a>> { let next = self.next_generic(); if next.0 == Token::Paren(expected) { Ok(()) @@ -307,7 +336,7 @@ impl<'a> Lexer<'a> { } /// If the next token matches it is skipped and true is returned - pub(super) fn skip(&mut self, what: Token<'_>) -> bool { + pub(in crate::front::wgsl) fn skip(&mut self, what: Token<'_>) -> bool { let (peeked_token, rest) = self.peek_token_and_rest(); if peeked_token.0 == what { self.input = rest; @@ -317,7 +346,9 @@ impl<'a> Lexer<'a> { } } - pub(super) fn next_ident_with_span(&mut self) -> Result<(&'a str, Span), Error<'a>> { + pub(in crate::front::wgsl) fn next_ident_with_span( + &mut self, + ) -> Result<(&'a str, Span), Error<'a>> { match self.next() { (Token::Word(word), span) if word == "_" => { Err(Error::InvalidIdentifierUnderscore(span)) @@ -330,7 +361,9 @@ impl<'a> Lexer<'a> { } } - pub(super) fn next_ident(&mut self) -> Result, Error<'a>> { + pub(in crate::front::wgsl) fn next_ident( + &mut self, + ) -> Result, Error<'a>> { let ident = self .next_ident_with_span() .map(|(name, span)| super::ast::Ident { name, span })?; @@ -343,7 +376,7 @@ impl<'a> Lexer<'a> { } /// Parses a generic scalar type, for example ``. - pub(super) fn next_scalar_generic( + pub(in crate::front::wgsl) fn next_scalar_generic( &mut self, ) -> Result<(crate::ScalarKind, crate::Bytes), Error<'a>> { self.expect_generic_paren('<')?; @@ -360,7 +393,7 @@ impl<'a> Lexer<'a> { /// Parses a generic scalar type, for example ``. /// /// Returns the span covering the inner type, excluding the brackets. - pub(super) fn next_scalar_generic_with_span( + pub(in crate::front::wgsl) fn next_scalar_generic_with_span( &mut self, ) -> Result<(crate::ScalarKind, crate::Bytes, Span), Error<'a>> { self.expect_generic_paren('<')?; @@ -374,7 +407,9 @@ impl<'a> Lexer<'a> { Ok(pair) } - pub(super) fn next_storage_access(&mut self) -> Result> { + pub(in crate::front::wgsl) fn next_storage_access( + &mut self, + ) -> Result> { let (ident, span) = self.next_ident_with_span()?; match ident { "read" => Ok(crate::StorageAccess::LOAD), @@ -384,7 +419,7 @@ impl<'a> Lexer<'a> { } } - pub(super) fn next_format_generic( + pub(in crate::front::wgsl) fn next_format_generic( &mut self, ) -> Result<(crate::StorageFormat, crate::StorageAccess), Error<'a>> { self.expect(Token::Paren('<'))?; @@ -396,16 +431,16 @@ impl<'a> Lexer<'a> { Ok((format, access)) } - pub(super) fn open_arguments(&mut self) -> Result<(), Error<'a>> { + pub(in crate::front::wgsl) fn open_arguments(&mut self) -> Result<(), Error<'a>> { self.expect(Token::Paren('(')) } - pub(super) fn close_arguments(&mut self) -> Result<(), Error<'a>> { + pub(in crate::front::wgsl) fn close_arguments(&mut self) -> Result<(), Error<'a>> { let _ = self.skip(Token::Separator(',')); self.expect(Token::Paren(')')) } - pub(super) fn next_argument(&mut self) -> Result> { + pub(in crate::front::wgsl) fn next_argument(&mut self) -> Result> { let paren = Token::Paren(')'); if self.skip(Token::Separator(',')) { Ok(!self.skip(paren)) @@ -415,9 +450,6 @@ impl<'a> Lexer<'a> { } } -#[cfg(test)] -use super::{number::Number, NumberError}; - #[cfg(test)] fn sub_test(source: &str, expected_tokens: &[Token]) { let mut lex = Lexer::new(source); diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs new file mode 100644 index 000000000..74d7b2030 --- /dev/null +++ b/src/front/wgsl/parse/mod.rs @@ -0,0 +1,2062 @@ +use crate::front::wgsl::error::{Error, ExpectedToken}; +use crate::front::wgsl::parse::lexer::{Lexer, Token}; +use crate::front::wgsl::parse::number::Number; +use crate::front::SymbolTable; +use crate::{Arena, FastHashSet, Handle, Span}; + +pub mod ast; +pub mod conv; +pub mod lexer; +pub mod number; + +/// State for constructing an AST expression. +/// +/// Not to be confused with `lower::ExpressionContext`. +struct ExpressionContext<'input, 'temp, 'out> { + /// The [`TranslationUnit::expressions`] arena to which we should contribute + /// expressions. + /// + /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions + expressions: &'out mut Arena>, + + /// The [`TranslationUnit::types`] arena to which we should contribute new + /// types. + /// + /// [`TranslationUnit::types`]: ast::TranslationUnit::types + types: &'out mut Arena>, + + /// A map from identifiers in scope to the locals/arguments they represent. + /// + /// The handles refer to the [`Function::locals`] area; see that field's + /// documentation for details. + /// + /// [`Function::locals`]: ast::Function::locals + local_table: &'temp mut SymbolTable<&'input str, Handle>, + + /// The [`Function::locals`] arena for the function we're building. + /// + /// [`Function::locals`]: ast::Function::locals + locals: &'out mut Arena, + + /// Identifiers used by the current global declaration that have no local definition. + /// + /// This becomes the [`GlobalDecl`]'s [`dependencies`] set. + /// + /// Note that we don't know at parse time what kind of [`GlobalDecl`] the + /// name refers to. We can't look up names until we've seen the entire + /// translation unit. + /// + /// [`GlobalDecl`]: ast::GlobalDecl + /// [`dependencies`]: ast::GlobalDecl::dependencies + unresolved: &'out mut FastHashSet>, +} + +impl<'a> ExpressionContext<'a, '_, '_> { + fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { + ExpressionContext { + expressions: self.expressions, + types: self.types, + local_table: self.local_table, + locals: self.locals, + unresolved: self.unresolved, + } + } + + fn parse_binary_op( + &mut self, + lexer: &mut Lexer<'a>, + classifier: impl Fn(Token<'a>) -> Option, + mut parser: impl FnMut( + &mut Lexer<'a>, + ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>>, + ) -> Result>, Error<'a>> { + let start = lexer.start_byte_offset(); + let mut accumulator = parser(lexer, self.reborrow())?; + while let Some(op) = classifier(lexer.peek().0) { + let _ = lexer.next(); + let left = accumulator; + let right = parser(lexer, self.reborrow())?; + accumulator = self.expressions.append( + ast::Expression::Binary { op, left, right }, + lexer.span_from(start), + ); + } + Ok(accumulator) + } +} + +/// Which grammar rule we are in the midst of parsing. +/// +/// This is used for error checking. `Parser` maintains a stack of +/// these and (occasionally) checks that it is being pushed and popped +/// as expected. +#[derive(Clone, Debug, PartialEq)] +enum Rule { + Attribute, + VariableDecl, + TypeDecl, + FunctionDecl, + Block, + Statement, + PrimaryExpr, + SingularExpr, + UnaryExpr, + GeneralExpr, +} + +#[derive(Default)] +struct BindingParser { + location: Option, + built_in: Option, + interpolation: Option, + sampling: Option, + invariant: bool, +} + +impl BindingParser { + fn parse<'a>( + &mut self, + lexer: &mut Lexer<'a>, + name: &'a str, + name_span: Span, + ) -> Result<(), Error<'a>> { + match name { + "location" => { + lexer.expect(Token::Paren('('))?; + self.location = Some(Parser::non_negative_i32_literal(lexer)?); + lexer.expect(Token::Paren(')'))?; + } + "builtin" => { + lexer.expect(Token::Paren('('))?; + let (raw, span) = lexer.next_ident_with_span()?; + self.built_in = Some(conv::map_built_in(raw, span)?); + lexer.expect(Token::Paren(')'))?; + } + "interpolate" => { + lexer.expect(Token::Paren('('))?; + let (raw, span) = lexer.next_ident_with_span()?; + self.interpolation = Some(conv::map_interpolation(raw, span)?); + if lexer.skip(Token::Separator(',')) { + let (raw, span) = lexer.next_ident_with_span()?; + self.sampling = Some(conv::map_sampling(raw, span)?); + } + lexer.expect(Token::Paren(')'))?; + } + "invariant" => self.invariant = true, + _ => return Err(Error::UnknownAttribute(name_span)), + } + Ok(()) + } + + const fn finish<'a>(self, span: Span) -> Result, Error<'a>> { + match ( + self.location, + self.built_in, + self.interpolation, + self.sampling, + self.invariant, + ) { + (None, None, None, None, false) => Ok(None), + (Some(location), None, interpolation, sampling, false) => { + // Before handing over the completed `Module`, we call + // `apply_default_interpolation` to ensure that the interpolation and + // sampling have been explicitly specified on all vertex shader output and fragment + // shader input user bindings, so leaving them potentially `None` here is fine. + Ok(Some(crate::Binding::Location { + location, + interpolation, + sampling, + })) + } + (None, Some(crate::BuiltIn::Position { .. }), None, None, invariant) => { + Ok(Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { + invariant, + }))) + } + (None, Some(built_in), None, None, false) => { + Ok(Some(crate::Binding::BuiltIn(built_in))) + } + (_, _, _, _, _) => Err(Error::InconsistentBinding(span)), + } + } +} + +pub struct Parser { + rules: Vec<(Rule, usize)>, +} + +impl Parser { + pub const fn new() -> Self { + Parser { rules: Vec::new() } + } + + fn reset(&mut self) { + self.rules.clear(); + } + + fn push_rule_span(&mut self, rule: Rule, lexer: &mut Lexer<'_>) { + self.rules.push((rule, lexer.start_byte_offset())); + } + + fn pop_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { + let (_, initial) = self.rules.pop().unwrap(); + lexer.span_from(initial) + } + + fn peek_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { + let &(_, initial) = self.rules.last().unwrap(); + lexer.span_from(initial) + } + + fn switch_value<'a>(lexer: &mut Lexer<'a>) -> Result<(ast::SwitchValue, Span), Error<'a>> { + let token_span = lexer.next(); + match token_span.0 { + Token::Word("default") => Ok((ast::SwitchValue::Default, token_span.1)), + Token::Number(Ok(Number::U32(num))) => Ok((ast::SwitchValue::U32(num), token_span.1)), + Token::Number(Ok(Number::I32(num))) => Ok((ast::SwitchValue::I32(num), token_span.1)), + Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)), + _ => Err(Error::Unexpected(token_span.1, ExpectedToken::Integer)), + } + } + + /// Parse a non-negative signed integer literal. + /// This is for attributes like `size`, `location` and others. + fn non_negative_i32_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + match lexer.next() { + (Token::Number(Ok(Number::I32(num))), span) => { + u32::try_from(num).map_err(|_| Error::NegativeInt(span)) + } + (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), + other => Err(Error::Unexpected(other.1, ExpectedToken::Number)), + } + } + + /// Parse a non-negative integer literal that may be either signed or unsigned. + /// This is for the `workgroup_size` attribute and array lengths. + /// Note: these values should be no larger than [`i32::MAX`], but this is not checked here. + fn generic_non_negative_int_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + match lexer.next() { + (Token::Number(Ok(Number::I32(num))), span) => { + u32::try_from(num).map_err(|_| Error::NegativeInt(span)) + } + (Token::Number(Ok(Number::U32(num))), _) => Ok(num), + (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), + other => Err(Error::Unexpected(other.1, ExpectedToken::Number)), + } + } + + /// Decide if we're looking at a construction expression, and return its + /// type if so. + /// + /// If the identifier `word` is a [type-defining keyword], then return a + /// [`ConstructorType`] value describing the type to build. Return an error + /// if the type is not constructible (like `sampler`). + /// + /// If `word` isn't a type name, then return `None`. + /// + /// [type-defining keyword]: https://gpuweb.github.io/gpuweb/wgsl/#type-defining-keywords + /// [`ConstructorType`]: ast::ConstructorType + fn constructor_type<'a>( + &mut self, + lexer: &mut Lexer<'a>, + word: &'a str, + span: Span, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + if let Some((kind, width)) = conv::get_scalar_type(word) { + return Ok(Some(ast::ConstructorType::Scalar { kind, width })); + } + + let partial = match word { + "vec2" => ast::ConstructorType::PartialVector { + size: crate::VectorSize::Bi, + }, + "vec3" => ast::ConstructorType::PartialVector { + size: crate::VectorSize::Tri, + }, + "vec4" => ast::ConstructorType::PartialVector { + size: crate::VectorSize::Quad, + }, + "mat2x2" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Bi, + }, + "mat2x3" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Tri, + }, + "mat2x4" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Quad, + }, + "mat3x2" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Bi, + }, + "mat3x3" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Tri, + }, + "mat3x4" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Quad, + }, + "mat4x2" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Bi, + }, + "mat4x3" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Tri, + }, + "mat4x4" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Quad, + }, + "array" => ast::ConstructorType::PartialArray, + "atomic" + | "binding_array" + | "sampler" + | "sampler_comparison" + | "texture_1d" + | "texture_1d_array" + | "texture_2d" + | "texture_2d_array" + | "texture_3d" + | "texture_cube" + | "texture_cube_array" + | "texture_multisampled_2d" + | "texture_multisampled_2d_array" + | "texture_depth_2d" + | "texture_depth_2d_array" + | "texture_depth_cube" + | "texture_depth_cube_array" + | "texture_depth_multisampled_2d" + | "texture_storage_1d" + | "texture_storage_1d_array" + | "texture_storage_2d" + | "texture_storage_2d_array" + | "texture_storage_3d" => return Err(Error::TypeNotConstructible(span)), + _ => return Ok(None), + }; + + // parse component type if present + match (lexer.peek().0, partial) { + (Token::Paren('<'), ast::ConstructorType::PartialVector { size }) => { + let (kind, width) = lexer.next_scalar_generic()?; + Ok(Some(ast::ConstructorType::Vector { size, kind, width })) + } + (Token::Paren('<'), ast::ConstructorType::PartialMatrix { columns, rows }) => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + match kind { + crate::ScalarKind::Float => Ok(Some(ast::ConstructorType::Matrix { + columns, + rows, + width, + })), + _ => Err(Error::BadMatrixScalarKind(span, kind, width)), + } + } + (Token::Paren('<'), ast::ConstructorType::PartialArray) => { + lexer.expect_generic_paren('<')?; + let base = self.type_decl(lexer, ctx.reborrow())?; + let size = if lexer.skip(Token::Separator(',')) { + let expr = self.unary_expression(lexer, ctx.reborrow())?; + ast::ArraySize::Constant(expr) + } else { + ast::ArraySize::Dynamic + }; + lexer.expect_generic_paren('>')?; + + Ok(Some(ast::ConstructorType::Array { base, size })) + } + (_, partial) => Ok(Some(partial)), + } + } + + /// Expects `name` to be consumed (not in lexer). + fn arguments<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>>, Error<'a>> { + lexer.open_arguments()?; + let mut arguments = Vec::new(); + loop { + if !arguments.is_empty() { + if !lexer.next_argument()? { + break; + } + } else if lexer.skip(Token::Paren(')')) { + break; + } + let arg = self.general_expression(lexer, ctx.reborrow())?; + arguments.push(arg); + } + + Ok(arguments) + } + + /// Expects [`Rule::PrimaryExpr`] or [`Rule::SingularExpr`] on top; does not pop it. + /// Expects `name` to be consumed (not in lexer). + fn function_call<'a>( + &mut self, + lexer: &mut Lexer<'a>, + name: &'a str, + name_span: Span, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + assert!(self.rules.last().is_some()); + + let expr = match name { + // bitcast looks like a function call, but it's an operator and must be handled differently. + "bitcast" => { + lexer.expect_generic_paren('<')?; + let start = lexer.start_byte_offset(); + let to = self.type_decl(lexer, ctx.reborrow())?; + let span = lexer.span_from(start); + lexer.expect_generic_paren('>')?; + + lexer.open_arguments()?; + let expr = self.general_expression(lexer, ctx.reborrow())?; + lexer.close_arguments()?; + + ast::Expression::Bitcast { + expr, + to, + ty_span: span, + } + } + // everything else must be handled later, since they can be hidden by user-defined functions. + _ => { + let arguments = self.arguments(lexer, ctx.reborrow())?; + ctx.unresolved.insert(ast::Dependency { + ident: name, + usage: name_span, + }); + ast::Expression::Call { + function: ast::Ident { + name, + span: name_span, + }, + arguments, + } + } + }; + + let span = self.peek_rule_span(lexer); + let expr = ctx.expressions.append(expr, span); + Ok(expr) + } + + fn ident_expr<'a>( + &mut self, + name: &'a str, + name_span: Span, + ctx: ExpressionContext<'a, '_, '_>, + ) -> ast::IdentExpr<'a> { + match ctx.local_table.lookup(name) { + Some(&local) => ast::IdentExpr::Local(local), + None => { + ctx.unresolved.insert(ast::Dependency { + ident: name, + usage: name_span, + }); + ast::IdentExpr::Unresolved(name) + } + } + } + + fn primary_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + self.push_rule_span(Rule::PrimaryExpr, lexer); + + let expr = match lexer.peek() { + (Token::Paren('('), _) => { + let _ = lexer.next(); + let expr = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + self.pop_rule_span(lexer); + return Ok(expr); + } + (Token::Word("true"), _) => { + let _ = lexer.next(); + ast::Expression::Literal(ast::Literal::Bool(true)) + } + (Token::Word("false"), _) => { + let _ = lexer.next(); + ast::Expression::Literal(ast::Literal::Bool(false)) + } + (Token::Number(res), span) => { + let _ = lexer.next(); + let num = res.map_err(|err| Error::BadNumber(span, err))?; + ast::Expression::Literal(ast::Literal::Number(num)) + } + (Token::Word(word), span) => { + let start = lexer.start_byte_offset(); + let _ = lexer.next(); + + if let Some(ty) = self.constructor_type(lexer, word, span, ctx.reborrow())? { + let ty_span = lexer.span_from(start); + let components = self.arguments(lexer, ctx.reborrow())?; + ast::Expression::Construct { + ty, + ty_span, + components, + } + } else if let Token::Paren('(') = lexer.peek().0 { + self.pop_rule_span(lexer); + return self.function_call(lexer, word, span, ctx); + } else if word == "bitcast" { + self.pop_rule_span(lexer); + return self.function_call(lexer, word, span, ctx); + } else { + let ident = self.ident_expr(word, span, ctx.reborrow()); + ast::Expression::Ident(ident) + } + } + other => return Err(Error::Unexpected(other.1, ExpectedToken::PrimaryExpression)), + }; + + let span = self.pop_rule_span(lexer); + let expr = ctx.expressions.append(expr, span); + Ok(expr) + } + + fn postfix<'a>( + &mut self, + span_start: usize, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + expr: Handle>, + ) -> Result>, Error<'a>> { + let mut expr = expr; + + loop { + let expression = match lexer.peek().0 { + Token::Separator('.') => { + let _ = lexer.next(); + let field = lexer.next_ident()?; + + ast::Expression::Member { base: expr, field } + } + Token::Paren('[') => { + let _ = lexer.next(); + let index = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(']'))?; + + ast::Expression::Index { base: expr, index } + } + _ => break, + }; + + let span = lexer.span_from(span_start); + expr = ctx.expressions.append(expression, span); + } + + Ok(expr) + } + + /// Parse a `unary_expression`. + fn unary_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + self.push_rule_span(Rule::UnaryExpr, lexer); + //TODO: refactor this to avoid backing up + let expr = match lexer.peek().0 { + Token::Operation('-') => { + let _ = lexer.next(); + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr, + }; + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) + } + Token::Operation('!' | '~') => { + let _ = lexer.next(); + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Unary { + op: crate::UnaryOperator::Not, + expr, + }; + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) + } + Token::Operation('*') => { + let _ = lexer.next(); + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Deref(expr); + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) + } + Token::Operation('&') => { + let _ = lexer.next(); + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::AddrOf(expr); + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) + } + _ => self.singular_expression(lexer, ctx.reborrow())?, + }; + + self.pop_rule_span(lexer); + Ok(expr) + } + + /// Parse a `singular_expression`. + fn singular_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + let start = lexer.start_byte_offset(); + self.push_rule_span(Rule::SingularExpr, lexer); + let primary_expr = self.primary_expression(lexer, ctx.reborrow())?; + let singular_expr = self.postfix(start, lexer, ctx.reborrow(), primary_expr)?; + self.pop_rule_span(lexer); + + Ok(singular_expr) + } + + fn equality_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + // equality_expression + context.parse_binary_op( + lexer, + |token| match token { + Token::LogicalOperation('=') => Some(crate::BinaryOperator::Equal), + Token::LogicalOperation('!') => Some(crate::BinaryOperator::NotEqual), + _ => None, + }, + // relational_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Paren('<') => Some(crate::BinaryOperator::Less), + Token::Paren('>') => Some(crate::BinaryOperator::Greater), + Token::LogicalOperation('<') => Some(crate::BinaryOperator::LessEqual), + Token::LogicalOperation('>') => Some(crate::BinaryOperator::GreaterEqual), + _ => None, + }, + // shift_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::ShiftOperation('<') => { + Some(crate::BinaryOperator::ShiftLeft) + } + Token::ShiftOperation('>') => { + Some(crate::BinaryOperator::ShiftRight) + } + _ => None, + }, + // additive_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('+') => Some(crate::BinaryOperator::Add), + Token::Operation('-') => { + Some(crate::BinaryOperator::Subtract) + } + _ => None, + }, + // multiplicative_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('*') => { + Some(crate::BinaryOperator::Multiply) + } + Token::Operation('/') => { + Some(crate::BinaryOperator::Divide) + } + Token::Operation('%') => { + Some(crate::BinaryOperator::Modulo) + } + _ => None, + }, + |lexer, context| self.unary_expression(lexer, context), + ) + }, + ) + }, + ) + }, + ) + }, + ) + } + + fn general_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + self.general_expression_with_span(lexer, ctx.reborrow()) + .map(|(expr, _)| expr) + } + + fn general_expression_with_span<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, '_>, + ) -> Result<(Handle>, Span), Error<'a>> { + self.push_rule_span(Rule::GeneralExpr, lexer); + // logical_or_expression + let handle = context.parse_binary_op( + lexer, + |token| match token { + Token::LogicalOperation('|') => Some(crate::BinaryOperator::LogicalOr), + _ => None, + }, + // logical_and_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::LogicalOperation('&') => Some(crate::BinaryOperator::LogicalAnd), + _ => None, + }, + // inclusive_or_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('|') => Some(crate::BinaryOperator::InclusiveOr), + _ => None, + }, + // exclusive_or_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('^') => { + Some(crate::BinaryOperator::ExclusiveOr) + } + _ => None, + }, + // and_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('&') => { + Some(crate::BinaryOperator::And) + } + _ => None, + }, + |lexer, context| { + self.equality_expression(lexer, context) + }, + ) + }, + ) + }, + ) + }, + ) + }, + )?; + Ok((handle, self.pop_rule_span(lexer))) + } + + fn variable_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + self.push_rule_span(Rule::VariableDecl, lexer); + let mut space = crate::AddressSpace::Handle; + + if lexer.skip(Token::Paren('<')) { + let (class_str, span) = lexer.next_ident_with_span()?; + space = match class_str { + "storage" => { + let access = if lexer.skip(Token::Separator(',')) { + lexer.next_storage_access()? + } else { + // defaulting to `read` + crate::StorageAccess::LOAD + }; + crate::AddressSpace::Storage { access } + } + _ => conv::map_address_space(class_str, span)?, + }; + lexer.expect(Token::Paren('>'))?; + } + let name = lexer.next_ident()?; + lexer.expect(Token::Separator(':'))?; + let ty = self.type_decl(lexer, ctx.reborrow())?; + + let init = if lexer.skip(Token::Operation('=')) { + let handle = self.general_expression(lexer, ctx.reborrow())?; + Some(handle) + } else { + None + }; + lexer.expect(Token::Separator(';'))?; + self.pop_rule_span(lexer); + + Ok(ast::GlobalVariable { + name, + space, + binding: None, + ty, + init, + }) + } + + fn struct_body<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + let mut members = Vec::new(); + + lexer.expect(Token::Paren('{'))?; + let mut ready = true; + while !lexer.skip(Token::Paren('}')) { + if !ready { + return Err(Error::Unexpected( + lexer.next().1, + ExpectedToken::Token(Token::Separator(',')), + )); + } + let (mut size, mut align) = (None, None); + self.push_rule_span(Rule::Attribute, lexer); + let mut bind_parser = BindingParser::default(); + while lexer.skip(Token::Attribute) { + match lexer.next_ident_with_span()? { + ("size", _) => { + lexer.expect(Token::Paren('('))?; + let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; + lexer.expect(Token::Paren(')'))?; + size = Some((value, span)); + } + ("align", _) => { + lexer.expect(Token::Paren('('))?; + let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; + lexer.expect(Token::Paren(')'))?; + align = Some((value, span)); + } + (word, word_span) => bind_parser.parse(lexer, word, word_span)?, + } + } + + let bind_span = self.pop_rule_span(lexer); + let binding = bind_parser.finish(bind_span)?; + + let name = lexer.next_ident()?; + lexer.expect(Token::Separator(':'))?; + let ty = self.type_decl(lexer, ctx.reborrow())?; + ready = lexer.skip(Token::Separator(',')); + + members.push(ast::StructMember { + name, + ty, + binding, + size, + align, + }); + } + + Ok(members) + } + + fn matrix_scalar_type<'a>( + &mut self, + lexer: &mut Lexer<'a>, + columns: crate::VectorSize, + rows: crate::VectorSize, + ) -> Result, Error<'a>> { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + match kind { + crate::ScalarKind::Float => Ok(ast::Type::Matrix { + columns, + rows, + width, + }), + _ => Err(Error::BadMatrixScalarKind(span, kind, width)), + } + } + + fn type_decl_impl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + word: &'a str, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + if let Some((kind, width)) = conv::get_scalar_type(word) { + return Ok(Some(ast::Type::Scalar { kind, width })); + } + + Ok(Some(match word { + "vec2" => { + let (kind, width) = lexer.next_scalar_generic()?; + ast::Type::Vector { + size: crate::VectorSize::Bi, + kind, + width, + } + } + "vec3" => { + let (kind, width) = lexer.next_scalar_generic()?; + ast::Type::Vector { + size: crate::VectorSize::Tri, + kind, + width, + } + } + "vec4" => { + let (kind, width) = lexer.next_scalar_generic()?; + ast::Type::Vector { + size: crate::VectorSize::Quad, + kind, + width, + } + } + "mat2x2" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Bi)? + } + "mat2x3" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Tri)? + } + "mat2x4" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Quad)? + } + "mat3x2" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Bi)? + } + "mat3x3" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Tri)? + } + "mat3x4" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Quad)? + } + "mat4x2" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Bi)? + } + "mat4x3" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Tri)? + } + "mat4x4" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Quad)? + } + "atomic" => { + let (kind, width) = lexer.next_scalar_generic()?; + ast::Type::Atomic { kind, width } + } + "ptr" => { + lexer.expect_generic_paren('<')?; + let (ident, span) = lexer.next_ident_with_span()?; + let mut space = conv::map_address_space(ident, span)?; + lexer.expect(Token::Separator(','))?; + let base = self.type_decl(lexer, ctx)?; + if let crate::AddressSpace::Storage { ref mut access } = space { + *access = if lexer.skip(Token::Separator(',')) { + lexer.next_storage_access()? + } else { + crate::StorageAccess::LOAD + }; + } + lexer.expect_generic_paren('>')?; + ast::Type::Pointer { base, space } + } + "array" => { + lexer.expect_generic_paren('<')?; + let base = self.type_decl(lexer, ctx.reborrow())?; + let size = if lexer.skip(Token::Separator(',')) { + let size = self.unary_expression(lexer, ctx.reborrow())?; + ast::ArraySize::Constant(size) + } else { + ast::ArraySize::Dynamic + }; + lexer.expect_generic_paren('>')?; + + ast::Type::Array { base, size } + } + "binding_array" => { + lexer.expect_generic_paren('<')?; + let base = self.type_decl(lexer, ctx.reborrow())?; + let size = if lexer.skip(Token::Separator(',')) { + let size = self.unary_expression(lexer, ctx.reborrow())?; + ast::ArraySize::Constant(size) + } else { + ast::ArraySize::Dynamic + }; + lexer.expect_generic_paren('>')?; + + ast::Type::BindingArray { base, size } + } + "sampler" => ast::Type::Sampler { comparison: false }, + "sampler_comparison" => ast::Type::Sampler { comparison: true }, + "texture_1d" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D1, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_1d_array" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D1, + arrayed: true, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_2d" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_2d_array" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_3d" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D3, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_cube" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::Cube, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_cube_array" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::Cube, + arrayed: true, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_multisampled_2d" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: true }, + } + } + "texture_multisampled_2d_array" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Sampled { kind, multi: true }, + } + } + "texture_depth_2d" => ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Depth { multi: false }, + }, + "texture_depth_2d_array" => ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Depth { multi: false }, + }, + "texture_depth_cube" => ast::Type::Image { + dim: crate::ImageDimension::Cube, + arrayed: false, + class: crate::ImageClass::Depth { multi: false }, + }, + "texture_depth_cube_array" => ast::Type::Image { + dim: crate::ImageDimension::Cube, + arrayed: true, + class: crate::ImageClass::Depth { multi: false }, + }, + "texture_depth_multisampled_2d" => ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Depth { multi: true }, + }, + "texture_storage_1d" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D1, + arrayed: false, + class: crate::ImageClass::Storage { format, access }, + } + } + "texture_storage_1d_array" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D1, + arrayed: true, + class: crate::ImageClass::Storage { format, access }, + } + } + "texture_storage_2d" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Storage { format, access }, + } + } + "texture_storage_2d_array" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Storage { format, access }, + } + } + "texture_storage_3d" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D3, + arrayed: false, + class: crate::ImageClass::Storage { format, access }, + } + } + _ => return Ok(None), + })) + } + + const fn check_texture_sample_type( + kind: crate::ScalarKind, + width: u8, + span: Span, + ) -> Result<(), Error<'static>> { + use crate::ScalarKind::*; + // Validate according to https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type + match (kind, width) { + (Float | Sint | Uint, 4) => Ok(()), + _ => Err(Error::BadTextureSampleType { span, kind, width }), + } + } + + /// Parse type declaration of a given name. + fn type_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + self.push_rule_span(Rule::TypeDecl, lexer); + + let (name, span) = lexer.next_ident_with_span()?; + + let ty = match self.type_decl_impl(lexer, name, ctx.reborrow())? { + Some(ty) => ty, + None => { + ctx.unresolved.insert(ast::Dependency { + ident: name, + usage: span, + }); + ast::Type::User(ast::Ident { name, span }) + } + }; + + self.pop_rule_span(lexer); + + let handle = ctx.types.append(ty, Span::UNDEFINED); + Ok(handle) + } + + fn assignment_op_and_rhs<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + target: Handle>, + span_start: usize, + ) -> Result<(), Error<'a>> { + use crate::BinaryOperator as Bo; + + let op = lexer.next(); + let (op, value) = match op { + (Token::Operation('='), _) => { + let value = self.general_expression(lexer, ctx.reborrow())?; + (None, value) + } + (Token::AssignmentOperation(c), _) => { + let op = match c { + '<' => Bo::ShiftLeft, + '>' => Bo::ShiftRight, + '+' => Bo::Add, + '-' => Bo::Subtract, + '*' => Bo::Multiply, + '/' => Bo::Divide, + '%' => Bo::Modulo, + '&' => Bo::And, + '|' => Bo::InclusiveOr, + '^' => Bo::ExclusiveOr, + // Note: `consume_token` shouldn't produce any other assignment ops + _ => unreachable!(), + }; + + let value = self.general_expression(lexer, ctx.reborrow())?; + (Some(op), value) + } + token @ (Token::IncrementOperation | Token::DecrementOperation, _) => { + let op = match token.0 { + Token::IncrementOperation => ast::StatementKind::Increment, + Token::DecrementOperation => ast::StatementKind::Decrement, + _ => unreachable!(), + }; + + let span = lexer.span_from(span_start); + block.stmts.push(ast::Statement { + kind: op(target), + span, + }); + return Ok(()); + } + _ => return Err(Error::Unexpected(op.1, ExpectedToken::Assignment)), + }; + + let span = lexer.span_from(span_start); + block.stmts.push(ast::Statement { + kind: ast::StatementKind::Assign { target, op, value }, + span, + }); + Ok(()) + } + + /// Parse an assignment statement (will also parse increment and decrement statements) + fn assignment_statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + let span_start = lexer.start_byte_offset(); + let target = self.general_expression(lexer, ctx.reborrow())?; + self.assignment_op_and_rhs(lexer, ctx, block, target, span_start) + } + + /// Parse a function call statement. + /// Expects `ident` to be consumed (not in the lexer). + fn function_statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + ident: &'a str, + ident_span: Span, + span_start: usize, + mut context: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + self.push_rule_span(Rule::SingularExpr, lexer); + + context.unresolved.insert(ast::Dependency { + ident, + usage: ident_span, + }); + let arguments = self.arguments(lexer, context.reborrow())?; + let span = lexer.span_from(span_start); + + block.stmts.push(ast::Statement { + kind: ast::StatementKind::Call { + function: ast::Ident { + name: ident, + span: ident_span, + }, + arguments, + }, + span, + }); + + self.pop_rule_span(lexer); + + Ok(()) + } + + fn function_call_or_assignment_statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + let span_start = lexer.start_byte_offset(); + match lexer.peek() { + (Token::Word(name), span) => { + // A little hack for 2 token lookahead. + let cloned = lexer.clone(); + let _ = lexer.next(); + match lexer.peek() { + (Token::Paren('('), _) => self.function_statement( + lexer, + name, + span, + span_start, + context.reborrow(), + block, + ), + _ => { + *lexer = cloned; + self.assignment_statement(lexer, context.reborrow(), block) + } + } + } + _ => self.assignment_statement(lexer, context.reborrow(), block), + } + } + + fn statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + self.push_rule_span(Rule::Statement, lexer); + match lexer.peek() { + (Token::Separator(';'), _) => { + let _ = lexer.next(); + self.pop_rule_span(lexer); + return Ok(()); + } + (Token::Paren('{'), _) => { + let (inner, span) = self.block(lexer, ctx.reborrow())?; + block.stmts.push(ast::Statement { + kind: ast::StatementKind::Block(inner), + span, + }); + self.pop_rule_span(lexer); + return Ok(()); + } + (Token::Word(word), _) => { + let kind = match word { + "_" => { + let _ = lexer.next(); + lexer.expect(Token::Operation('='))?; + let expr = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(';'))?; + + ast::StatementKind::Ignore(expr) + } + "let" => { + let _ = lexer.next(); + let name = lexer.next_ident()?; + + let given_ty = if lexer.skip(Token::Separator(':')) { + let ty = self.type_decl(lexer, ctx.reborrow())?; + Some(ty) + } else { + None + }; + lexer.expect(Token::Operation('='))?; + let expr_id = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(';'))?; + + let handle = ctx.locals.append(ast::Local, name.span); + if let Some(old) = ctx.local_table.add(name.name, handle) { + return Err(Error::Redefinition { + previous: ctx.locals.get_span(old), + current: name.span, + }); + } + + ast::StatementKind::LocalDecl(ast::LocalDecl::Let(ast::Let { + name, + ty: given_ty, + init: expr_id, + handle, + })) + } + "var" => { + let _ = lexer.next(); + + let name = lexer.next_ident()?; + let ty = if lexer.skip(Token::Separator(':')) { + let ty = self.type_decl(lexer, ctx.reborrow())?; + Some(ty) + } else { + None + }; + + let init = if lexer.skip(Token::Operation('=')) { + let init = self.general_expression(lexer, ctx.reborrow())?; + Some(init) + } else { + None + }; + + lexer.expect(Token::Separator(';'))?; + + let handle = ctx.locals.append(ast::Local, name.span); + if let Some(old) = ctx.local_table.add(name.name, handle) { + return Err(Error::Redefinition { + previous: ctx.locals.get_span(old), + current: name.span, + }); + } + + ast::StatementKind::LocalDecl(ast::LocalDecl::Var(ast::LocalVariable { + name, + ty, + init, + handle, + })) + } + "return" => { + let _ = lexer.next(); + let value = if lexer.peek().0 != Token::Separator(';') { + let handle = self.general_expression(lexer, ctx.reborrow())?; + Some(handle) + } else { + None + }; + lexer.expect(Token::Separator(';'))?; + ast::StatementKind::Return { value } + } + "if" => { + let _ = lexer.next(); + let condition = self.general_expression(lexer, ctx.reborrow())?; + + let accept = self.block(lexer, ctx.reborrow())?.0; + + let mut elsif_stack = Vec::new(); + let mut elseif_span_start = lexer.start_byte_offset(); + let mut reject = loop { + if !lexer.skip(Token::Word("else")) { + break ast::Block::default(); + } + + if !lexer.skip(Token::Word("if")) { + // ... else { ... } + break self.block(lexer, ctx.reborrow())?.0; + } + + // ... else if (...) { ... } + let other_condition = self.general_expression(lexer, ctx.reborrow())?; + let other_block = self.block(lexer, ctx.reborrow())?; + elsif_stack.push((elseif_span_start, other_condition, other_block)); + elseif_span_start = lexer.start_byte_offset(); + }; + + // reverse-fold the else-if blocks + //Note: we may consider uplifting this to the IR + for (other_span_start, other_cond, other_block) in + elsif_stack.into_iter().rev() + { + let sub_stmt = ast::StatementKind::If { + condition: other_cond, + accept: other_block.0, + reject, + }; + reject = ast::Block::default(); + let span = lexer.span_from(other_span_start); + reject.stmts.push(ast::Statement { + kind: sub_stmt, + span, + }) + } + + ast::StatementKind::If { + condition, + accept, + reject, + } + } + "switch" => { + let _ = lexer.next(); + let selector = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren('{'))?; + let mut cases = Vec::new(); + + loop { + // cases + default + match lexer.next() { + (Token::Word("case"), _) => { + // parse a list of values + let (value, value_span) = loop { + let (value, value_span) = Self::switch_value(lexer)?; + if lexer.skip(Token::Separator(',')) { + if lexer.skip(Token::Separator(':')) { + break (value, value_span); + } + } else { + lexer.skip(Token::Separator(':')); + break (value, value_span); + } + cases.push(ast::SwitchCase { + value, + value_span, + body: ast::Block::default(), + fall_through: true, + }); + }; + + let body = self.block(lexer, ctx.reborrow())?.0; + + cases.push(ast::SwitchCase { + value, + value_span, + body, + fall_through: false, + }); + } + (Token::Word("default"), value_span) => { + lexer.skip(Token::Separator(':')); + let body = self.block(lexer, ctx.reborrow())?.0; + cases.push(ast::SwitchCase { + value: ast::SwitchValue::Default, + value_span, + body, + fall_through: false, + }); + } + (Token::Paren('}'), _) => break, + (_, span) => { + return Err(Error::Unexpected(span, ExpectedToken::SwitchItem)) + } + } + } + + ast::StatementKind::Switch { selector, cases } + } + "loop" => self.r#loop(lexer, ctx.reborrow())?, + "while" => { + let _ = lexer.next(); + let mut body = ast::Block::default(); + + let (condition, span) = lexer.capture_span(|lexer| { + let condition = self.general_expression(lexer, ctx.reborrow())?; + Ok(condition) + })?; + let mut reject = ast::Block::default(); + reject.stmts.push(ast::Statement { + kind: ast::StatementKind::Break, + span, + }); + + body.stmts.push(ast::Statement { + kind: ast::StatementKind::If { + condition, + accept: ast::Block::default(), + reject, + }, + span, + }); + + let (block, span) = self.block(lexer, ctx.reborrow())?; + body.stmts.push(ast::Statement { + kind: ast::StatementKind::Block(block), + span, + }); + + ast::StatementKind::Loop { + body, + continuing: ast::Block::default(), + break_if: None, + } + } + "for" => { + let _ = lexer.next(); + lexer.expect(Token::Paren('('))?; + + ctx.local_table.push_scope(); + + if !lexer.skip(Token::Separator(';')) { + let num_statements = block.stmts.len(); + let (_, span) = lexer.capture_span(|lexer| { + self.statement(lexer, ctx.reborrow(), block) + })?; + + if block.stmts.len() != num_statements { + match block.stmts.last().unwrap().kind { + ast::StatementKind::Call { .. } + | ast::StatementKind::Assign { .. } + | ast::StatementKind::LocalDecl(_) => {} + _ => return Err(Error::InvalidForInitializer(span)), + } + } + }; + + let mut body = ast::Block::default(); + if !lexer.skip(Token::Separator(';')) { + let (condition, span) = lexer.capture_span(|lexer| { + let condition = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(';'))?; + Ok(condition) + })?; + let mut reject = ast::Block::default(); + reject.stmts.push(ast::Statement { + kind: ast::StatementKind::Break, + span, + }); + body.stmts.push(ast::Statement { + kind: ast::StatementKind::If { + condition, + accept: ast::Block::default(), + reject, + }, + span, + }); + }; + + let mut continuing = ast::Block::default(); + if !lexer.skip(Token::Paren(')')) { + self.function_call_or_assignment_statement( + lexer, + ctx.reborrow(), + &mut continuing, + )?; + lexer.expect(Token::Paren(')'))?; + } + + let (block, span) = self.block(lexer, ctx.reborrow())?; + body.stmts.push(ast::Statement { + kind: ast::StatementKind::Block(block), + span, + }); + + ctx.local_table.pop_scope(); + + ast::StatementKind::Loop { + body, + continuing, + break_if: None, + } + } + "break" => { + let (_, span) = lexer.next(); + // Check if the next token is an `if`, this indicates + // that the user tried to type out a `break if` which + // is illegal in this position. + let (peeked_token, peeked_span) = lexer.peek(); + if let Token::Word("if") = peeked_token { + let span = span.until(&peeked_span); + return Err(Error::InvalidBreakIf(span)); + } + ast::StatementKind::Break + } + "continue" => { + let _ = lexer.next(); + ast::StatementKind::Continue + } + "discard" => { + let _ = lexer.next(); + ast::StatementKind::Kill + } + // assignment or a function call + _ => { + self.function_call_or_assignment_statement(lexer, ctx.reborrow(), block)?; + lexer.expect(Token::Separator(';'))?; + self.pop_rule_span(lexer); + return Ok(()); + } + }; + + let span = self.pop_rule_span(lexer); + block.stmts.push(ast::Statement { kind, span }); + } + _ => { + self.assignment_statement(lexer, ctx.reborrow(), block)?; + self.pop_rule_span(lexer); + } + } + Ok(()) + } + + fn r#loop<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + let _ = lexer.next(); + let mut body = ast::Block::default(); + let mut continuing = ast::Block::default(); + let mut break_if = None; + + lexer.expect(Token::Paren('{'))?; + + ctx.local_table.push_scope(); + + loop { + if lexer.skip(Token::Word("continuing")) { + // Branch for the `continuing` block, this must be + // the last thing in the loop body + + // Expect a opening brace to start the continuing block + lexer.expect(Token::Paren('{'))?; + loop { + if lexer.skip(Token::Word("break")) { + // Branch for the `break if` statement, this statement + // has the form `break if ;` and must be the last + // statement in a continuing block + + // The break must be followed by an `if` to form + // the break if + lexer.expect(Token::Word("if"))?; + + let condition = self.general_expression(lexer, ctx.reborrow())?; + // Set the condition of the break if to the newly parsed + // expression + break_if = Some(condition); + + // Expect a semicolon to close the statement + lexer.expect(Token::Separator(';'))?; + // Expect a closing brace to close the continuing block, + // since the break if must be the last statement + lexer.expect(Token::Paren('}'))?; + // Stop parsing the continuing block + break; + } else if lexer.skip(Token::Paren('}')) { + // If we encounter a closing brace it means we have reached + // the end of the continuing block and should stop processing + break; + } else { + // Otherwise try to parse a statement + self.statement(lexer, ctx.reborrow(), &mut continuing)?; + } + } + // Since the continuing block must be the last part of the loop body, + // we expect to see a closing brace to end the loop body + lexer.expect(Token::Paren('}'))?; + break; + } + if lexer.skip(Token::Paren('}')) { + // If we encounter a closing brace it means we have reached + // the end of the loop body and should stop processing + break; + } + // Otherwise try to parse a statement + self.statement(lexer, ctx.reborrow(), &mut body)?; + } + + ctx.local_table.pop_scope(); + + Ok(ast::StatementKind::Loop { + body, + continuing, + break_if, + }) + } + + /// compound_statement + fn block<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result<(ast::Block<'a>, Span), Error<'a>> { + self.push_rule_span(Rule::Block, lexer); + + ctx.local_table.push_scope(); + + let _ = lexer.next(); + let mut statements = ast::Block::default(); + while !lexer.skip(Token::Paren('}')) { + self.statement(lexer, ctx.reborrow(), &mut statements)?; + } + + ctx.local_table.pop_scope(); + + let span = self.pop_rule_span(lexer); + Ok((statements, span)) + } + + fn varying_binding<'a>( + &mut self, + lexer: &mut Lexer<'a>, + ) -> Result, Error<'a>> { + let mut bind_parser = BindingParser::default(); + self.push_rule_span(Rule::Attribute, lexer); + + while lexer.skip(Token::Attribute) { + let (word, span) = lexer.next_ident_with_span()?; + bind_parser.parse(lexer, word, span)?; + } + + let span = self.pop_rule_span(lexer); + bind_parser.finish(span) + } + + fn function_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + out: &mut ast::TranslationUnit<'a>, + dependencies: &mut FastHashSet>, + ) -> Result, Error<'a>> { + self.push_rule_span(Rule::FunctionDecl, lexer); + // read function name + let fun_name = lexer.next_ident()?; + + let mut locals = Arena::new(); + + let mut ctx = ExpressionContext { + expressions: &mut out.expressions, + local_table: &mut SymbolTable::default(), + locals: &mut locals, + types: &mut out.types, + unresolved: dependencies, + }; + + // read parameter list + let mut arguments = Vec::new(); + lexer.expect(Token::Paren('('))?; + let mut ready = true; + while !lexer.skip(Token::Paren(')')) { + if !ready { + return Err(Error::Unexpected( + lexer.next().1, + ExpectedToken::Token(Token::Separator(',')), + )); + } + let binding = self.varying_binding(lexer)?; + + let param_name = lexer.next_ident()?; + + lexer.expect(Token::Separator(':'))?; + let param_type = self.type_decl(lexer, ctx.reborrow())?; + + let handle = ctx.locals.append(ast::Local, param_name.span); + ctx.local_table.add(param_name.name, handle); + arguments.push(ast::FunctionArgument { + name: param_name, + ty: param_type, + binding, + handle, + }); + ready = lexer.skip(Token::Separator(',')); + } + // read return type + let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { + let binding = self.varying_binding(lexer)?; + let ty = self.type_decl(lexer, ctx.reborrow())?; + Some(ast::FunctionResult { ty, binding }) + } else { + None + }; + + // read body + let body = self.block(lexer, ctx)?.0; + + let fun = ast::Function { + entry_point: None, + name: fun_name, + arguments, + result, + body, + locals, + }; + + // done + self.pop_rule_span(lexer); + + Ok(fun) + } + + fn global_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + out: &mut ast::TranslationUnit<'a>, + ) -> Result<(), Error<'a>> { + // read attributes + let mut binding = None; + let mut stage = None; + let mut workgroup_size = [0u32; 3]; + let mut early_depth_test = None; + let (mut bind_index, mut bind_group) = (None, None); + + self.push_rule_span(Rule::Attribute, lexer); + while lexer.skip(Token::Attribute) { + match lexer.next_ident_with_span()? { + ("binding", _) => { + lexer.expect(Token::Paren('('))?; + bind_index = Some(Self::non_negative_i32_literal(lexer)?); + lexer.expect(Token::Paren(')'))?; + } + ("group", _) => { + lexer.expect(Token::Paren('('))?; + bind_group = Some(Self::non_negative_i32_literal(lexer)?); + lexer.expect(Token::Paren(')'))?; + } + ("vertex", _) => { + stage = Some(crate::ShaderStage::Vertex); + } + ("fragment", _) => { + stage = Some(crate::ShaderStage::Fragment); + } + ("compute", _) => { + stage = Some(crate::ShaderStage::Compute); + } + ("workgroup_size", _) => { + lexer.expect(Token::Paren('('))?; + workgroup_size = [1u32; 3]; + for (i, size) in workgroup_size.iter_mut().enumerate() { + *size = Self::generic_non_negative_int_literal(lexer)?; + match lexer.next() { + (Token::Paren(')'), _) => break, + (Token::Separator(','), _) if i != 2 => (), + other => { + return Err(Error::Unexpected( + other.1, + ExpectedToken::WorkgroupSizeSeparator, + )) + } + } + } + } + ("early_depth_test", _) => { + let conservative = if lexer.skip(Token::Paren('(')) { + let (ident, ident_span) = lexer.next_ident_with_span()?; + let value = conv::map_conservative_depth(ident, ident_span)?; + lexer.expect(Token::Paren(')'))?; + Some(value) + } else { + None + }; + early_depth_test = Some(crate::EarlyDepthTest { conservative }); + } + (_, word_span) => return Err(Error::UnknownAttribute(word_span)), + } + } + + let attrib_span = self.pop_rule_span(lexer); + match (bind_group, bind_index) { + (Some(group), Some(index)) => { + binding = Some(crate::ResourceBinding { + group, + binding: index, + }); + } + (Some(_), None) => return Err(Error::MissingAttribute("binding", attrib_span)), + (None, Some(_)) => return Err(Error::MissingAttribute("group", attrib_span)), + (None, None) => {} + } + + let mut dependencies = FastHashSet::default(); + let mut ctx = ExpressionContext { + expressions: &mut out.expressions, + local_table: &mut SymbolTable::default(), + locals: &mut Arena::new(), + types: &mut out.types, + unresolved: &mut dependencies, + }; + + // read item + let start = lexer.start_byte_offset(); + let kind = match lexer.next() { + (Token::Separator(';'), _) => None, + (Token::Word("struct"), _) => { + let name = lexer.next_ident()?; + + let members = self.struct_body(lexer, ctx)?; + Some(ast::GlobalDeclKind::Struct(ast::Struct { name, members })) + } + (Token::Word("type"), _) => { + let name = lexer.next_ident()?; + + lexer.expect(Token::Operation('='))?; + let ty = self.type_decl(lexer, ctx)?; + lexer.expect(Token::Separator(';'))?; + Some(ast::GlobalDeclKind::Type(ast::TypeAlias { name, ty })) + } + (Token::Word("const"), _) => { + let name = lexer.next_ident()?; + + let ty = if lexer.skip(Token::Separator(':')) { + let ty = self.type_decl(lexer, ctx.reborrow())?; + Some(ty) + } else { + None + }; + + lexer.expect(Token::Operation('='))?; + let init = self.general_expression(lexer, ctx)?; + lexer.expect(Token::Separator(';'))?; + + Some(ast::GlobalDeclKind::Const(ast::Const { name, ty, init })) + } + (Token::Word("var"), _) => { + let mut var = self.variable_decl(lexer, ctx)?; + var.binding = binding.take(); + Some(ast::GlobalDeclKind::Var(var)) + } + (Token::Word("fn"), _) => { + let function = self.function_decl(lexer, out, &mut dependencies)?; + Some(ast::GlobalDeclKind::Fn(ast::Function { + entry_point: stage.map(|stage| ast::EntryPoint { + stage, + early_depth_test, + workgroup_size, + }), + ..function + })) + } + (Token::End, _) => return Ok(()), + other => return Err(Error::Unexpected(other.1, ExpectedToken::GlobalItem)), + }; + + if let Some(kind) = kind { + out.decls.append( + ast::GlobalDecl { kind, dependencies }, + lexer.span_from(start), + ); + } + + if !self.rules.is_empty() { + log::error!("Reached the end of global decl, but rule stack is not empty"); + log::error!("Rules: {:?}", self.rules); + return Err(Error::Other); + }; + + match binding { + None => Ok(()), + // we had the attribute but no var? + Some(_) => Err(Error::Other), + } + } + + pub fn parse<'a>(&mut self, source: &'a str) -> Result, Error<'a>> { + self.reset(); + + let mut lexer = Lexer::new(source); + let mut tu = ast::TranslationUnit::default(); + loop { + match self.global_decl(&mut lexer, &mut tu) { + Err(error) => return Err(error), + Ok(()) => { + if lexer.peek().0 == Token::End { + break; + } + } + } + } + + Ok(tu) + } +} diff --git a/src/front/wgsl/number.rs b/src/front/wgsl/parse/number.rs similarity index 98% rename from src/front/wgsl/number.rs rename to src/front/wgsl/parse/number.rs index cd7b88c7e..57a2be614 100644 --- a/src/front/wgsl/number.rs +++ b/src/front/wgsl/parse/number.rs @@ -1,6 +1,7 @@ use std::borrow::Cow; -use super::{NumberError, Token}; +use crate::front::wgsl::error::NumberError; +use crate::front::wgsl::parse::lexer::Token; /// When using this type assume no Abstract Int/Float for now #[derive(Copy, Clone, Debug, PartialEq)] @@ -42,7 +43,7 @@ impl Number { // TODO: when implementing Creation-Time Expressions, remove the ability to match the minus sign -pub(super) fn consume_number(input: &str) -> (Token<'_>, &str) { +pub(in crate::front::wgsl) fn consume_number(input: &str) -> (Token<'_>, &str) { let (result, rest) = parse(input); ( Token::Number(result.and_then(Number::abstract_to_concrete)), @@ -146,7 +147,7 @@ fn parse(input: &str) -> (Result, &str) { impl<'a> ExtractSubStr<'a> { /// given an `input` and a `start` (tail of the `input`) - /// creates a new [ExtractSubStr] + /// creates a new [`ExtractSubStr`](`Self`) fn start(input: &'a str, start: &'a [u8]) -> Self { let start = input.len() - start.len(); Self(&input[start..]) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index ad15d614f..466f1739f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -623,7 +623,7 @@ fn convert_glsl_variations_check() { let root = env!("CARGO_MANIFEST_DIR"); let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/variations.glsl")) .expect("Couldn't find glsl file"); - let mut parser = naga::front::glsl::Parser::default(); + let mut parser = naga::front::glsl::Frontend::default(); let module = parser .parse( &naga::front::glsl::Options { @@ -654,7 +654,7 @@ fn convert_glsl_folder() { } println!("Processing {file_name}"); - let mut parser = naga::front::glsl::Parser::default(); + let mut parser = naga::front::glsl::Frontend::default(); let module = parser .parse( &naga::front::glsl::Options { From bebaac93b6bf3f2a1917733ab5a71293b61b2ffd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 31 Jan 2023 14:49:39 +0000 Subject: [PATCH 1919/2212] valid: Fix handle dependency validation The handle dependency validation code was using the handle's index directly while trying to erase the handle type. This would cause the validator to crash while processing the first handle of the arena since it would be trying to construct a `NonZeroU32` with a zero. This commit fixes the issue by adding 1 to the index which not only fixes this panic but also makes so that the created Handle is equal to the passed handle (minus the type that was erased) It also fixes the error message not including the subject's kind --- src/valid/handles.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 5b3375a87..062624daf 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -532,8 +532,8 @@ pub enum InvalidHandleError { #[derive(Clone, Debug, thiserror::Error)] #[error( - "{subject:?} of kind depends on {depends_on:?} of kind {depends_on_kind}, which has not been \ - processed yet" + "{subject:?} of kind {subject_kind:?} depends on {depends_on:?} of kind {depends_on_kind}, \ + which has not been processed yet" )] pub struct FwdDepError { // This error is used for many `Handle` types, but there's no point in making this generic, so @@ -580,7 +580,7 @@ impl Handle { Ok(self) } else { let erase_handle_type = |handle: Handle<_>| { - Handle::new(NonZeroU32::new(handle.index().try_into().unwrap()).unwrap()) + Handle::new(NonZeroU32::new((handle.index() + 1).try_into().unwrap()).unwrap()) }; Err(FwdDepError { subject: erase_handle_type(self), From 0074c68ec4f435c5dc0ba6d62ff567c1f146e9ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Tue, 31 Jan 2023 14:58:36 +0000 Subject: [PATCH 1920/2212] valid: Check dependencies between functions calls This commit enforces the forward dependency rules on the IR across functions and their calls, this fixes a crash in a later stage of the validator. --- src/valid/handles.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 062624daf..be87e54d4 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -131,7 +131,7 @@ impl super::Validator { } } - let validate_function = |function: &_| -> Result<_, InvalidHandleError> { + let validate_function = |function_handle, function: &_| -> Result<_, InvalidHandleError> { let &crate::Function { name: _, ref arguments, @@ -175,6 +175,7 @@ impl super::Validator { local_variables, global_variables, functions, + function_handle, )?; } @@ -184,11 +185,11 @@ impl super::Validator { }; for entry_point in entry_points.iter() { - validate_function(&entry_point.function)?; + validate_function(None, &entry_point.function)?; } - for (_function_handle, function) in functions.iter() { - validate_function(function)?; + for (function_handle, function) in functions.iter() { + validate_function(Some(function_handle), function)?; } Ok(()) @@ -229,6 +230,8 @@ impl super::Validator { local_variables: &Arena, global_variables: &Arena, functions: &Arena, + // The handle of the current function or `None` if it's an entry point + current_function: Option>, ) -> Result<(), InvalidHandleError> { let validate_constant = |handle| Self::validate_constant_handle(handle, constants); let validate_type = |handle| Self::validate_type_handle(handle, types); @@ -373,6 +376,9 @@ impl super::Validator { } crate::Expression::CallResult(function) => { Self::validate_function_handle(function, functions)?; + if let Some(handle) = current_function { + handle.check_dep(function)?; + } } crate::Expression::AtomicResult { .. } => (), crate::Expression::ArrayLength(array) => { From a2b39e45bf7ba8f6afe417e56d52b4210f6d013c Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 31 Jan 2023 14:22:43 +0100 Subject: [PATCH 1921/2212] [hlsl-out] clear `named_expressions` inserted by duplicated blocks changed the type of `named_expressions` from `HashMap` to `IndexMap` so that insertion order is preserved --- Cargo.toml | 3 ++- src/back/hlsl/writer.rs | 3 +++ src/front/glsl/functions.rs | 7 +++---- src/front/spv/function.rs | 4 ++-- src/front/wgsl/lower/mod.rs | 2 +- src/lib.rs | 6 +++++- tests/out/ir/access.ron | 12 ++++++------ 7 files changed, 22 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a8dc9e0e0..8772fa15a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ glsl-out = [] msl-out = [] serialize = ["serde", "indexmap/serde-1"] deserialize = ["serde", "indexmap/serde-1"] +arbitrary = ["dep:arbitrary", "indexmap/arbitrary"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] wgsl-in = ["codespan-reporting", "hexf-parse", "termcolor", "unicode-xid"] @@ -52,7 +53,7 @@ termcolor = { version = "1.0.4", optional = true } # https://github.com/brendanzab/codespan/commit/e99c867339a877731437e7ee6a903a3d03b5439e codespan-reporting = { version = "0.11.0", optional = true } rustc-hash = "1.1.0" -indexmap = { version = "1.6", features = ["std"] } +indexmap = { version = "1.9.2", features = ["std"] } log = "0.4" num-traits = "0.2" spirv = { version = "0.2", optional = true } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 1641c2ee0..7ac5563aa 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1908,9 +1908,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let indent_level_3 = indent_level_2.next(); for case in &cases[i..=end_case_idx] { writeln!(self.out, "{indent_level_2}{{")?; + let prev_len = self.named_expressions.len(); for sta in case.body.iter() { self.write_stmt(module, sta, func_ctx, indent_level_3)?; } + // Clear all named expressions that were previously inserted by the statements in the block + self.named_expressions.truncate(prev_len); writeln!(self.out, "{indent_level_2}}}")?; } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 3718fc7ab..df4de5e10 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -8,9 +8,8 @@ use super::{ }; use crate::{ front::glsl::types::type_power, proc::ensure_block_returns, AddressSpace, Arena, Block, - Constant, ConstantInner, EntryPoint, Expression, FastHashMap, Function, FunctionArgument, - FunctionResult, Handle, LocalVariable, ScalarKind, ScalarValue, Span, Statement, StructMember, - Type, TypeInner, + Constant, ConstantInner, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, + Handle, LocalVariable, ScalarKind, ScalarValue, Span, Statement, StructMember, Type, TypeInner, }; use std::iter; @@ -1064,7 +1063,7 @@ impl Frontend { result, local_variables: locals, expressions, - named_expressions: FastHashMap::default(), + named_expressions: crate::NamedExpressions::default(), body, }; diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index b43abcac3..8ae9a328d 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -61,7 +61,7 @@ impl> super::Frontend { local_variables: Arena::new(), expressions: self .make_expression_storage(&module.global_variables, &module.constants), - named_expressions: crate::FastHashMap::default(), + named_expressions: crate::NamedExpressions::default(), body: crate::Block::new(), } }; @@ -298,7 +298,7 @@ impl> super::Frontend { result: None, local_variables: Arena::new(), expressions: Arena::new(), - named_expressions: crate::FastHashMap::default(), + named_expressions: crate::NamedExpressions::default(), body: crate::Block::new(), }; diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 7d03c7fb7..877fb3c5e 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -74,7 +74,7 @@ pub struct StatementContext<'source, 'temp, 'out> { typifier: &'temp mut Typifier, variables: &'out mut Arena, naga_expressions: &'out mut Arena, - named_expressions: &'out mut FastHashMap, String>, + named_expressions: &'out mut crate::NamedExpressions, arguments: &'out [crate::FunctionArgument], module: &'out mut crate::Module, } diff --git a/src/lib.rs b/src/lib.rs index 077548aa3..ceae0c14c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -232,7 +232,11 @@ pub type FastHashMap = rustc_hash::FxHashMap; pub type FastHashSet = rustc_hash::FxHashSet; /// Map of expressions that have associated variable names -pub(crate) type NamedExpressions = FastHashMap, String>; +pub(crate) type NamedExpressions = indexmap::IndexMap< + Handle, + String, + std::hash::BuildHasherDefault, +>; /// Early fragment tests. /// diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index d3be85b41..3c3783998 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -2149,17 +2149,17 @@ ), ], named_expressions: { - 29: "c", - 4: "baz", - 17: "b", 1: "vi", - 27: "a", + 4: "baz", 8: "_matrix", 11: "arr", - 34: "data_pointer", - 47: "value", 12: "index", + 17: "b", + 27: "a", + 29: "c", + 34: "data_pointer", 35: "foo_value", + 47: "value", }, body: [ Store( From 6be394dac31bc9796d4ae4bb450a40c6b6ee0b08 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Tue, 31 Jan 2023 15:31:05 -0500 Subject: [PATCH 1922/2212] Add countLeadingZeros (#2226) * Add countLeadingZeros * [glsl-out] Bake countLeadingZeros * [hlsl-out] Bake countLeadingZeros * [hlsl-out] Update Baked expressions * Remove unnecessary bake for sints * [glsl-out] CountLeadingZeros without findMSB * Don't check negatives when uint * Perform the type conv after mix * use log2 * fix clippy lints --------- Co-authored-by: teoxoy <28601907+teoxoy@users.noreply.github.com> --- src/back/glsl/mod.rs | 94 +++++++++++++----- src/back/hlsl/mod.rs | 3 +- src/back/hlsl/writer.rs | 96 +++++++++++++++++-- src/back/msl/writer.rs | 1 + src/back/spv/block.rs | 69 ++++++++++++- src/back/wgsl/writer.rs | 1 + src/front/wgsl/parse/conv.rs | 1 + src/lib.rs | 1 + src/proc/mod.rs | 1 + src/proc/typifier.rs | 1 + src/valid/expression.rs | 6 +- tests/in/math-functions.wgsl | 4 + .../out/glsl/math-functions.main.Vertex.glsl | 6 ++ tests/out/hlsl/math-functions.hlsl | 5 + tests/out/msl/math-functions.msl | 4 + tests/out/spv/math-functions.spvasm | 78 +++++++++------ tests/out/wgsl/math-functions.wgsl | 4 + 17 files changed, 310 insertions(+), 65 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 420885638..6c90fcb26 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1114,33 +1114,33 @@ impl<'a, W: Write> Writer<'a, W> { fn update_expressions_to_bake(&mut self, func: &crate::Function, info: &valid::FunctionInfo) { use crate::Expression; self.need_bake_expressions.clear(); - for expr in func.expressions.iter() { - let expr_info = &info[expr.0]; - let min_ref_count = func.expressions[expr.0].bake_ref_count(); + for (fun_handle, expr) in func.expressions.iter() { + let expr_info = &info[fun_handle]; + let min_ref_count = func.expressions[fun_handle].bake_ref_count(); if min_ref_count <= expr_info.ref_count { - self.need_bake_expressions.insert(expr.0); + self.need_bake_expressions.insert(fun_handle); } - // if the expression is a Dot product with integer arguments, - // then the args needs baking as well - if let ( - fun_handle, - &Expression::Math { - fun: crate::MathFunction::Dot, - arg, - arg1, - .. - }, - ) = expr - { - let inner = info[fun_handle].ty.inner_with(&self.module.types); - if let TypeInner::Scalar { kind, .. } = *inner { - match kind { - crate::ScalarKind::Sint | crate::ScalarKind::Uint => { - self.need_bake_expressions.insert(arg); - self.need_bake_expressions.insert(arg1.unwrap()); + + if let Expression::Math { fun, arg, arg1, .. } = *expr { + match fun { + crate::MathFunction::Dot => { + // if the expression is a Dot product with integer arguments, + // then the args needs baking as well + let inner = info[fun_handle].ty.inner_with(&self.module.types); + if let TypeInner::Scalar { kind, .. } = *inner { + match kind { + crate::ScalarKind::Sint | crate::ScalarKind::Uint => { + self.need_bake_expressions.insert(arg); + self.need_bake_expressions.insert(arg1.unwrap()); + } + _ => {} + } } - _ => {} } + crate::MathFunction::CountLeadingZeros => { + self.need_bake_expressions.insert(arg); + } + _ => {} } } } @@ -2928,6 +2928,54 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Transpose => "transpose", Mf::Determinant => "determinant", // bits + Mf::CountLeadingZeros => { + match *ctx.info[arg].ty.inner_with(&self.module.types) { + crate::TypeInner::Vector { size, kind, .. } => { + let s = back::vector_size_str(size); + + if let crate::ScalarKind::Uint = kind { + write!(self.out, "uvec{s}(")?; + } else { + write!(self.out, "ivec{s}(")?; + } + + write!(self.out, "mix(vec{s}(31.0) - floor(log2(vec{s}(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ") + 0.5)), ")?; + + if let crate::ScalarKind::Uint = kind { + write!(self.out, "vec{s}(32.0), lessThanEqual(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ", uvec{s}(0u))))")?; + } else { + write!(self.out, "mix(vec{s}(0.0), vec{s}(32.0), equal(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ", ivec{s}(0))), lessThanEqual(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ", ivec{s}(0))))")?; + } + } + crate::TypeInner::Scalar { kind, .. } => { + write!(self.out, "(")?; + self.write_expr(arg, ctx)?; + + if let crate::ScalarKind::Uint = kind { + write!(self.out, " == 0u ? 32u : uint(")?; + } else { + write!(self.out, " <= 0 ? (")?; + self.write_expr(arg, ctx)?; + write!(self.out, " == 0 ? 32 : 0) : int(")?; + } + + write!(self.out, "31.0 - floor(log2(float(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ") + 0.5))))")?; + } + _ => unreachable!(), + }; + + return Ok(()); + } Mf::CountOneBits => "bitCount", Mf::ReverseBits => "bitfieldReverse", Mf::ExtractBits => "bitfieldExtract", diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 103127039..6f31ed374 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -107,7 +107,7 @@ mod writer; use std::fmt::Error as FmtError; use thiserror::Error; -use crate::proc; +use crate::{back, proc}; #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -280,4 +280,5 @@ pub struct Writer<'a, W> { named_expressions: crate::NamedExpressions, wrapped: Wrapped, temp_access_chain: Vec, + need_bake_expressions: back::NeedBakeExpressions, } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 7ac5563aa..2af7a3524 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -83,6 +83,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { named_expressions: crate::NamedExpressions::default(), wrapped: super::Wrapped::default(), temp_access_chain: Vec::new(), + need_bake_expressions: Default::default(), } } @@ -93,6 +94,46 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.entry_point_io.clear(); self.named_expressions.clear(); self.wrapped.clear(); + self.need_bake_expressions.clear(); + } + + /// Helper method used to find which expressions of a given function require baking + /// + /// # Notes + /// Clears `need_bake_expressions` set before adding to it + fn update_expressions_to_bake( + &mut self, + module: &Module, + func: &crate::Function, + info: &valid::FunctionInfo, + ) { + use crate::Expression; + self.need_bake_expressions.clear(); + for (fun_handle, expr) in func.expressions.iter() { + let expr_info = &info[fun_handle]; + let min_ref_count = func.expressions[fun_handle].bake_ref_count(); + if min_ref_count <= expr_info.ref_count { + self.need_bake_expressions.insert(fun_handle); + } + + if let Expression::Math { fun, arg, .. } = *expr { + match fun { + crate::MathFunction::Asinh + | crate::MathFunction::Acosh + | crate::MathFunction::Atanh + | crate::MathFunction::Unpack2x16float => { + self.need_bake_expressions.insert(arg); + } + crate::MathFunction::CountLeadingZeros => { + let inner = info[fun_handle].ty.inner_with(&module.types); + if let Some(crate::ScalarKind::Sint) = inner.scalar_kind() { + self.need_bake_expressions.insert(arg); + } + } + _ => {} + } + } + } } pub fn write( @@ -244,7 +285,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // before writing all statements and expressions. self.write_wrapped_functions(module, &ctx)?; - self.write_function(module, name.as_str(), function, &ctx)?; + self.write_function(module, name.as_str(), function, &ctx, info)?; writeln!(self.out)?; } @@ -296,7 +337,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } let name = self.names[&NameKey::EntryPoint(index as u16)].clone(); - self.write_function(module, &name, &ep.function, &ctx)?; + self.write_function(module, &name, &ep.function, &ctx, info)?; if index < module.entry_points.len() - 1 { writeln!(self.out)?; @@ -1034,9 +1075,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { name: &str, func: &crate::Function, func_ctx: &back::FunctionCtx<'_>, + info: &valid::FunctionInfo, ) -> BackendResult { // Function Declaration Syntax - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-function-syntax + self.update_expressions_to_bake(module, func, info); + // Write modifier if let Some(crate::FunctionResult { binding: @@ -1284,15 +1328,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. Some(self.namer.call(name)) + } else if self.need_bake_expressions.contains(&handle) { + Some(format!("_expr{}", handle.index())) } else if info.ref_count == 0 { Some(self.namer.call("")) } else { - let min_ref_count = func_ctx.expressions[handle].bake_ref_count(); - if min_ref_count <= info.ref_count { - Some(format!("_expr{}", handle.index())) - } else { - None - } + None }; if let Some(name) = expr_name { @@ -2510,6 +2551,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Unpack2x16float, Regular(&'static str), MissingIntOverload(&'static str), + CountLeadingZeros, } let fun = match fun { @@ -2572,6 +2614,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::Transpose => Function::Regular("transpose"), Mf::Determinant => Function::Regular("determinant"), // bits + Mf::CountLeadingZeros => Function::CountLeadingZeros, Mf::CountOneBits => Function::MissingIntOverload("countbits"), Mf::ReverseBits => Function::MissingIntOverload("reversebits"), Mf::FindLsb => Function::Regular("firstbitlow"), @@ -2639,6 +2682,43 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; } } + Function::CountLeadingZeros => { + match *func_ctx.info[arg].ty.inner_with(&module.types) { + TypeInner::Vector { size, kind, .. } => { + let s = match size { + crate::VectorSize::Bi => ".xx", + crate::VectorSize::Tri => ".xxx", + crate::VectorSize::Quad => ".xxxx", + }; + + if let ScalarKind::Uint = kind { + write!(self.out, "asuint((31){s} - firstbithigh(")?; + } else { + write!(self.out, "(")?; + self.write_expr(module, arg, func_ctx)?; + write!( + self.out, + " < (0){s} ? (0){s} : (31){s} - firstbithigh(" + )?; + } + } + TypeInner::Scalar { kind, .. } => { + if let ScalarKind::Uint = kind { + write!(self.out, "asuint(31 - firstbithigh(")?; + } else { + write!(self.out, "(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " < 0 ? 0 : 31 - firstbithigh(")?; + } + } + _ => unreachable!(), + } + + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))")?; + + return Ok(()); + } } } Expression::Swizzle { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index b72c76783..04c1fed21 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1689,6 +1689,7 @@ impl Writer { Mf::Transpose => "transpose", Mf::Determinant => "determinant", // bits + Mf::CountLeadingZeros => "clz", Mf::CountOneBits => "popcount", Mf::ReverseBits => "reverse_bits", Mf::ExtractBits => "extract_bits", diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 5ebbf2ea8..bf09fc3ad 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -724,7 +724,7 @@ impl<'w> BlockContext<'w> { self.temp_list.resize(size as _, arg1_id); let id = self.gen_id(); - block.body.push(Instruction::composite_construct( + block.body.push(Instruction::constant_composite( result_type_id, id, &self.temp_list, @@ -735,7 +735,7 @@ impl<'w> BlockContext<'w> { self.temp_list.resize(size as _, arg2_id); let id = self.gen_id(); - block.body.push(Instruction::composite_construct( + block.body.push(Instruction::constant_composite( result_type_id, id, &self.temp_list, @@ -888,6 +888,71 @@ impl<'w> BlockContext<'w> { id, arg0_id, )), + Mf::CountLeadingZeros => { + let int = crate::ScalarValue::Sint(31); + + let (int_type_id, int_id) = match *arg_ty { + crate::TypeInner::Vector { size, width, .. } => { + let ty = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(size), + kind: crate::ScalarKind::Sint, + width, + pointer_space: None, + })); + + self.temp_list.clear(); + self.temp_list + .resize(size as _, self.writer.get_constant_scalar(int, width)); + + let id = self.gen_id(); + block.body.push(Instruction::constant_composite( + ty, + id, + &self.temp_list, + )); + + (ty, id) + } + crate::TypeInner::Scalar { width, .. } => ( + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Sint, + width, + pointer_space: None, + })), + self.writer.get_constant_scalar(int, width), + ), + _ => unreachable!(), + }; + + block.body.push(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + spirv::GLOp::FindUMsb, + int_type_id, + id, + &[arg0_id], + )); + + let sub_id = self.gen_id(); + block.body.push(Instruction::binary( + spirv::Op::ISub, + int_type_id, + sub_id, + int_id, + id, + )); + + if let Some(crate::ScalarKind::Uint) = arg_scalar_kind { + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + result_type_id, + self.gen_id(), + sub_id, + )); + } + + return Ok(()); + } Mf::CountOneBits => MathOp::Custom(Instruction::unary( spirv::Op::BitCount, result_type_id, diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 5524ca9c2..4f58cd9ee 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1578,6 +1578,7 @@ impl Writer { Mf::Transpose => Function::Regular("transpose"), Mf::Determinant => Function::Regular("determinant"), // bits + Mf::CountLeadingZeros => Function::Regular("countLeadingZeros"), Mf::CountOneBits => Function::Regular("countOneBits"), Mf::ReverseBits => Function::Regular("reverseBits"), Mf::ExtractBits => Function::Regular("extractBits"), diff --git a/src/front/wgsl/parse/conv.rs b/src/front/wgsl/parse/conv.rs index ca4cc5519..416433216 100644 --- a/src/front/wgsl/parse/conv.rs +++ b/src/front/wgsl/parse/conv.rs @@ -191,6 +191,7 @@ pub fn map_standard_fun(word: &str) -> Option { "transpose" => Mf::Transpose, "determinant" => Mf::Determinant, // bits + "countLeadingZeros" => Mf::CountLeadingZeros, "countOneBits" => Mf::CountOneBits, "reverseBits" => Mf::ReverseBits, "extractBits" => Mf::ExtractBits, diff --git a/src/lib.rs b/src/lib.rs index ceae0c14c..136205ca1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1066,6 +1066,7 @@ pub enum MathFunction { Transpose, Determinant, // bits + CountLeadingZeros, CountOneBits, ReverseBits, ExtractBits, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index f30158c11..0a8e4a961 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -279,6 +279,7 @@ impl super::MathFunction { Self::Transpose => 1, Self::Determinant => 1, // bits + Self::CountLeadingZeros => 1, Self::CountOneBits => 1, Self::ReverseBits => 1, Self::ExtractBits => 3, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 4c55d101a..64896ec41 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -793,6 +793,7 @@ impl<'a> ResolveContext<'a> { )), }, // bits + Mf::CountLeadingZeros | Mf::CountOneBits | Mf::ReverseBits | Mf::ExtractBits | diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 9853f1d1b..d599e6b62 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1223,7 +1223,11 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } } - Mf::CountOneBits | Mf::ReverseBits | Mf::FindLsb | Mf::FindMsb => { + Mf::CountLeadingZeros + | Mf::CountOneBits + | Mf::ReverseBits + | Mf::FindLsb + | Mf::FindMsb => { if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index 13b080e92..1c2a8e457 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -10,4 +10,8 @@ fn main() { let g = refract(v, v, f); let const_dot = dot(vec2(), vec2()); let first_leading_bit_abs = firstLeadingBit(abs(0u)); + let clz_a = countLeadingZeros(-1); + let clz_b = countLeadingZeros(1u); + let clz_c = countLeadingZeros(vec2(-1)); + let clz_d = countLeadingZeros(vec2(1u)); } diff --git a/tests/out/glsl/math-functions.main.Vertex.glsl b/tests/out/glsl/math-functions.main.Vertex.glsl index 5efa8f27c..d863ada72 100644 --- a/tests/out/glsl/math-functions.main.Vertex.glsl +++ b/tests/out/glsl/math-functions.main.Vertex.glsl @@ -14,5 +14,11 @@ void main() { vec4 g = refract(v, v, 1.0); int const_dot = ( + ivec2(0, 0).x * ivec2(0, 0).x + ivec2(0, 0).y * ivec2(0, 0).y); uint first_leading_bit_abs = uint(findMSB(uint(abs(int(0u))))); + int clz_a = (-1 <= 0 ? (-1 == 0 ? 32 : 0) : int(31.0 - floor(log2(float(-1) + 0.5)))); + uint clz_b = (1u == 0u ? 32u : uint(31.0 - floor(log2(float(1u) + 0.5)))); + ivec2 _e20 = ivec2(-1); + ivec2 clz_c = ivec2(mix(vec2(31.0) - floor(log2(vec2(_e20) + 0.5)), mix(vec2(0.0), vec2(32.0), equal(_e20, ivec2(0))), lessThanEqual(_e20, ivec2(0)))); + uvec2 _e23 = uvec2(1u); + uvec2 clz_d = uvec2(mix(vec2(31.0) - floor(log2(vec2(_e23) + 0.5)), vec2(32.0), lessThanEqual(_e23, uvec2(0u)))); } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index 64c2e87ea..2a95c849c 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -10,4 +10,9 @@ void main() float4 g = refract(v, v, 1.0); int const_dot = dot(int2(0, 0), int2(0, 0)); uint first_leading_bit_abs = firstbithigh(abs(0u)); + int clz_a = (-1 < 0 ? 0 : 31 - firstbithigh(-1)); + uint clz_b = asuint(31 - firstbithigh(1u)); + int2 _expr20 = (-1).xx; + int2 clz_c = (_expr20 < (0).xx ? (0).xx : (31).xx - firstbithigh(_expr20)); + uint2 clz_d = asuint((31).xx - firstbithigh((1u).xx)); } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index d097be47a..0838a338c 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -17,4 +17,8 @@ vertex void main_( metal::float4 g = metal::refract(v, v, 1.0); int const_dot = ( + const_type_1_.x * const_type_1_.x + const_type_1_.y * const_type_1_.y); uint first_leading_bit_abs = (((metal::clz(metal::abs(0u)) + 1) % 33) - 1); + int clz_a = metal::clz(-1); + uint clz_b = metal::clz(1u); + metal::int2 clz_c = metal::clz(metal::int2(-1)); + metal::uint2 clz_d = metal::clz(metal::uint2(1u)); } diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 4fada56c7..131c6cace 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,11 +1,11 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 37 +; Bound: 55 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %14 "main" +OpEntryPoint Vertex %16 "main" %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -14,33 +14,51 @@ OpEntryPoint Vertex %14 "main" %6 = OpConstant %7 0 %9 = OpTypeInt 32 0 %8 = OpConstant %9 0 -%10 = OpTypeVector %4 4 -%11 = OpTypeVector %7 2 -%12 = OpConstantComposite %11 %6 %6 -%15 = OpTypeFunction %2 -%27 = OpConstantNull %7 -%14 = OpFunction %2 None %15 -%13 = OpLabel -OpBranch %16 -%16 = OpLabel -%17 = OpCompositeConstruct %10 %5 %5 %5 %5 -%18 = OpExtInst %4 %1 Degrees %3 -%19 = OpExtInst %4 %1 Radians %3 -%20 = OpExtInst %10 %1 Degrees %17 -%21 = OpExtInst %10 %1 Radians %17 -%23 = OpCompositeConstruct %10 %5 %5 %5 %5 -%24 = OpCompositeConstruct %10 %3 %3 %3 %3 -%22 = OpExtInst %10 %1 FClamp %17 %23 %24 -%25 = OpExtInst %10 %1 Refract %17 %17 %3 -%28 = OpCompositeExtract %7 %12 0 -%29 = OpCompositeExtract %7 %12 0 -%30 = OpIMul %7 %28 %29 -%31 = OpIAdd %7 %27 %30 -%32 = OpCompositeExtract %7 %12 1 -%33 = OpCompositeExtract %7 %12 1 -%34 = OpIMul %7 %32 %33 -%26 = OpIAdd %7 %31 %34 -%35 = OpCopyObject %9 %8 -%36 = OpExtInst %9 %1 FindUMsb %35 +%10 = OpConstant %7 -1 +%11 = OpConstant %9 1 +%12 = OpTypeVector %4 4 +%13 = OpTypeVector %7 2 +%14 = OpConstantComposite %13 %6 %6 +%17 = OpTypeFunction %2 +%40 = OpConstant %7 31 +%49 = OpTypeVector %9 2 +%25 = OpConstantComposite %12 %5 %5 %5 %5 +%26 = OpConstantComposite %12 %3 %3 %3 %3 +%29 = OpConstantNull %7 +%47 = OpConstantComposite %13 %40 %40 +%52 = OpConstantComposite %13 %40 %40 +%16 = OpFunction %2 None %17 +%15 = OpLabel +OpBranch %18 +%18 = OpLabel +%19 = OpCompositeConstruct %12 %5 %5 %5 %5 +%20 = OpExtInst %4 %1 Degrees %3 +%21 = OpExtInst %4 %1 Radians %3 +%22 = OpExtInst %12 %1 Degrees %19 +%23 = OpExtInst %12 %1 Radians %19 +%24 = OpExtInst %12 %1 FClamp %19 %25 %26 +%27 = OpExtInst %12 %1 Refract %19 %19 %3 +%30 = OpCompositeExtract %7 %14 0 +%31 = OpCompositeExtract %7 %14 0 +%32 = OpIMul %7 %30 %31 +%33 = OpIAdd %7 %29 %32 +%34 = OpCompositeExtract %7 %14 1 +%35 = OpCompositeExtract %7 %14 1 +%36 = OpIMul %7 %34 %35 +%28 = OpIAdd %7 %33 %36 +%37 = OpCopyObject %9 %8 +%38 = OpExtInst %9 %1 FindUMsb %37 +%39 = OpExtInst %7 %1 FindUMsb %10 +%41 = OpISub %7 %40 %39 +%42 = OpExtInst %7 %1 FindUMsb %11 +%43 = OpISub %7 %40 %42 +%44 = OpBitcast %9 %43 +%45 = OpCompositeConstruct %13 %10 %10 +%46 = OpExtInst %13 %1 FindUMsb %45 +%48 = OpISub %13 %47 %46 +%50 = OpCompositeConstruct %49 %11 %11 +%51 = OpExtInst %13 %1 FindUMsb %50 +%53 = OpISub %13 %52 %51 +%54 = OpBitcast %49 %53 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 004d9cf5b..d91a26cff 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -9,4 +9,8 @@ fn main() { let g = refract(v, v, 1.0); let const_dot = dot(vec2(0, 0), vec2(0, 0)); let first_leading_bit_abs = firstLeadingBit(abs(0u)); + let clz_a = countLeadingZeros(-1); + let clz_b = countLeadingZeros(1u); + let clz_c = countLeadingZeros(vec2(-1)); + let clz_d = countLeadingZeros(vec2(1u)); } From 16be1a92379d7bdf3d0e88f7f7b2aca2dfd187b4 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 1 Feb 2023 03:24:05 -0800 Subject: [PATCH 1923/2212] spv-out: support version 1.4 (#2230) * spv-out: support version 1.4 * Extract SPV version numner from the comment --- Makefile | 4 +++- src/back/msl/writer.rs | 2 +- src/back/spv/writer.rs | 6 ++++++ tests/in/sprite.param.ron | 5 +++++ tests/in/sprite.wgsl | 7 ++++++ tests/out/spv/sprite.spvasm | 43 +++++++++++++++++++++++++++++++++++++ tests/snapshots.rs | 1 + 7 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 tests/in/sprite.param.ron create mode 100644 tests/in/sprite.wgsl create mode 100644 tests/out/spv/sprite.spvasm diff --git a/Makefile b/Makefile index de27e3049..744d8a225 100644 --- a/Makefile +++ b/Makefile @@ -33,7 +33,9 @@ bench: validate-spv: $(SNAPSHOTS_BASE_OUT)/spv/*.spvasm @set -e && for file in $^ ; do \ echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ - cat $${file} | spirv-as --target-env vulkan1.0 -o - | spirv-val; \ + version_line=$$(head -2 $${file} | tail -1); \ + version=$${version_line#"; Version: "};\ + cat $${file} | spirv-as --target-env spv$${version} -o - | spirv-val; \ done validate-msl: $(SNAPSHOTS_BASE_OUT)/msl/*.msl diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 04c1fed21..d424c11b2 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -4221,7 +4221,7 @@ fn test_stack_size() { let stack_size = addresses_end - addresses_start; // check the size (in debug only) // last observed macOS value: 19152 (CI) - if !(9500..=20000).contains(&stack_size) { + if !(9000..=20000).contains(&stack_size) { panic!("`put_block` stack size {stack_size} has changed!"); } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f19d83e45..caf3f72ce 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -585,6 +585,12 @@ impl Writer { } let mut gv = self.global_variables[handle.index()].clone(); + if let Some(ref mut iface) = interface { + // Have to include global variables in the interface + if self.physical_layout.version >= 0x10400 { + iface.varying_ids.push(gv.var_id); + } + } // Handle globals are pre-emitted and should be loaded automatically. // diff --git a/tests/in/sprite.param.ron b/tests/in/sprite.param.ron new file mode 100644 index 000000000..08598faee --- /dev/null +++ b/tests/in/sprite.param.ron @@ -0,0 +1,5 @@ +( + spv: ( + version: (1, 4), + ), +) diff --git a/tests/in/sprite.wgsl b/tests/in/sprite.wgsl new file mode 100644 index 000000000..6828b2946 --- /dev/null +++ b/tests/in/sprite.wgsl @@ -0,0 +1,7 @@ +@group(0) @binding(0) var u_texture : texture_2d; +@group(0) @binding(1) var u_sampler : sampler; + +@fragment +fn main(@location(0) uv : vec2) -> @location(0) vec4 { + return textureSample(u_texture, u_sampler, uv); +} diff --git a/tests/out/spv/sprite.spvasm b/tests/out/spv/sprite.spvasm new file mode 100644 index 000000000..f3a574b28 --- /dev/null +++ b/tests/out/spv/sprite.spvasm @@ -0,0 +1,43 @@ +; SPIR-V +; Version: 1.4 +; Generator: rspirv +; Bound: 26 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %18 "main" %13 %16 %8 %10 +OpExecutionMode %18 OriginUpperLeft +OpDecorate %8 DescriptorSet 0 +OpDecorate %8 Binding 0 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 1 +OpDecorate %13 Location 0 +OpDecorate %16 Location 0 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpTypeImage %4 2D 0 0 0 1 Unknown +%5 = OpTypeSampler +%6 = OpTypeVector %4 2 +%7 = OpTypeVector %4 4 +%9 = OpTypePointer UniformConstant %3 +%8 = OpVariable %9 UniformConstant +%11 = OpTypePointer UniformConstant %5 +%10 = OpVariable %11 UniformConstant +%14 = OpTypePointer Input %6 +%13 = OpVariable %14 Input +%17 = OpTypePointer Output %7 +%16 = OpVariable %17 Output +%19 = OpTypeFunction %2 +%23 = OpTypeSampledImage %3 +%18 = OpFunction %2 None %19 +%12 = OpLabel +%15 = OpLoad %6 %13 +%20 = OpLoad %3 %8 +%21 = OpLoad %5 %10 +OpBranch %22 +%22 = OpLabel +%24 = OpSampledImage %23 %20 %21 +%25 = OpImageSampleImplicitLod %7 %24 %15 +OpStore %16 %25 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 466f1739f..25f307c11 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -556,6 +556,7 @@ fn convert_wgsl() { "workgroup-var-init", Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, ), + ("sprite", Targets::SPIRV), ]; for &(name, targets) in inputs.iter() { From bb20ae8e796f50f30d164a56067524026cc9ebb8 Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Tue, 31 Jan 2023 21:19:08 +0530 Subject: [PATCH 1924/2212] check for leading { while parsing a block --- src/front/wgsl/parse/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 74d7b2030..ce188819a 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -1776,7 +1776,7 @@ impl Parser { ctx.local_table.push_scope(); - let _ = lexer.next(); + lexer.expect(Token::Paren('{'))?; let mut statements = ast::Block::default(); while !lexer.skip(Token::Paren('}')) { self.statement(lexer, ctx.reborrow(), &mut statements)?; From e6bd2e90714b2fa45d2bb966a63bae96184bed53 Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Tue, 31 Jan 2023 21:28:52 +0530 Subject: [PATCH 1925/2212] fix panic on invalid zero array size --- src/front/wgsl/lower/mod.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 877fb3c5e..94b4469a6 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -352,10 +352,10 @@ impl<'a> ExpressionContext<'a, '_, '_> { } crate::TypeInner::Vector { size, kind, width } => { let scalar_ty = self.ensure_type_exists(crate::TypeInner::Scalar { width, kind }); - let component = self.create_zero_value_constant(scalar_ty); + let component = self.create_zero_value_constant(scalar_ty)?; crate::ConstantInner::Composite { ty, - components: (0..size as u8).map(|_| component).collect::>()?, + components: (0..size as u8).map(|_| component).collect(), } } crate::TypeInner::Matrix { @@ -368,12 +368,10 @@ impl<'a> ExpressionContext<'a, '_, '_> { kind: crate::ScalarKind::Float, size: rows, }); - let component = self.create_zero_value_constant(vec_ty); + let component = self.create_zero_value_constant(vec_ty)?; crate::ConstantInner::Composite { ty, - components: (0..columns as u8) - .map(|_| component) - .collect::>()?, + components: (0..columns as u8).map(|_| component).collect(), } } crate::TypeInner::Array { @@ -381,12 +379,11 @@ impl<'a> ExpressionContext<'a, '_, '_> { size: crate::ArraySize::Constant(size), .. } => { - let component = self.create_zero_value_constant(base); + let size = self.module.constants[size].to_array_length()?; + let component = self.create_zero_value_constant(base)?; crate::ConstantInner::Composite { ty, - components: (0..self.module.constants[size].to_array_length().unwrap()) - .map(|_| component) - .collect::>()?, + components: (0..size).map(|_| component).collect(), } } crate::TypeInner::Struct { ref members, .. } => { From 231af68386d57a1b9ea87b27e8a15eadea0851eb Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Tue, 31 Jan 2023 21:38:20 +0530 Subject: [PATCH 1926/2212] expect semicolons wherever required --- src/front/wgsl/parse/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index ce188819a..74d3741df 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -1661,14 +1661,17 @@ impl Parser { let span = span.until(&peeked_span); return Err(Error::InvalidBreakIf(span)); } + lexer.expect(Token::Separator(';'))?; ast::StatementKind::Break } "continue" => { let _ = lexer.next(); + lexer.expect(Token::Separator(';'))?; ast::StatementKind::Continue } "discard" => { let _ = lexer.next(); + lexer.expect(Token::Separator(';'))?; ast::StatementKind::Kill } // assignment or a function call @@ -1685,6 +1688,7 @@ impl Parser { } _ => { self.assignment_statement(lexer, ctx.reborrow(), block)?; + lexer.expect(Token::Separator(';'))?; self.pop_rule_span(lexer); } } From dcfd5c6f4a2635d9569b82cdd31f8d4bfa96434b Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Tue, 31 Jan 2023 22:01:58 +0530 Subject: [PATCH 1927/2212] improve invalid assignment diagnostic --- src/front/wgsl/error.rs | 44 +++++++++++++++++++++++-------------- src/front/wgsl/lower/mod.rs | 39 +++++++++++++++++++++----------- 2 files changed, 54 insertions(+), 29 deletions(-) diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index 1c965fc26..a4e654023 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -134,7 +134,7 @@ pub enum NumberError { pub enum InvalidAssignmentType { Other, Swizzle, - ImmutableBinding, + ImmutableBinding(Span), } #[derive(Clone, Debug)] @@ -536,21 +536,33 @@ impl<'a> Error<'a> { labels: vec![(span, "expression is not a reference".into())], notes: vec![], }, - Error::InvalidAssignment { span, ty } => ParseError { - message: "invalid left-hand side of assignment".into(), - labels: vec![(span, "cannot assign to this expression".into())], - notes: match ty { - InvalidAssignmentType::Swizzle => vec![ - "WGSL does not support assignments to swizzles".into(), - "consider assigning each component individually".into(), - ], - InvalidAssignmentType::ImmutableBinding => vec![ - format!("'{}' is an immutable binding", &source[span]), - "consider declaring it with `var` instead of `let`".into(), - ], - InvalidAssignmentType::Other => vec![], - }, - }, + Error::InvalidAssignment { span, ty } => { + let (extra_label, notes) = match ty { + InvalidAssignmentType::Swizzle => ( + None, + vec![ + "WGSL does not support assignments to swizzles".into(), + "consider assigning each component individually".into(), + ], + ), + InvalidAssignmentType::ImmutableBinding(binding_span) => ( + Some((binding_span, "this is an immutable binding".into())), + vec![format!( + "consider declaring '{}' with `var` instead of `let`", + &source[binding_span] + )], + ), + InvalidAssignmentType::Other => (None, vec![]), + }; + + ParseError { + message: "invalid left-hand side of assignment".into(), + labels: std::iter::once((span, "cannot assign to this expression".into())) + .chain(extra_label) + .collect(), + notes, + } + } Error::Pointer(what, span) => ParseError { message: format!("{what} must not be a pointer"), labels: vec![(span, "expression is a pointer".into())], diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 94b4469a6..481ea7535 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -5,6 +5,7 @@ use crate::front::wgsl::parse::{ast, conv}; use crate::front::{Emitter, Typifier}; use crate::proc::{ensure_block_returns, Alignment, Layouter, ResolveContext, TypeResolution}; use crate::{Arena, FastHashMap, Handle, Span}; +use indexmap::IndexMap; mod construction; @@ -74,7 +75,9 @@ pub struct StatementContext<'source, 'temp, 'out> { typifier: &'temp mut Typifier, variables: &'out mut Arena, naga_expressions: &'out mut Arena, - named_expressions: &'out mut crate::NamedExpressions, + /// Stores the names of expressions that are assigned in `let` statement + /// Also stores the spans of the names, for use in errors. + named_expressions: &'out mut IndexMap, (String, Span)>, arguments: &'out [crate::FunctionArgument], module: &'out mut crate::Module, } @@ -126,6 +129,19 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { module: self.module, } } + + fn invalid_assignment_type(&self, expr: Handle) -> InvalidAssignmentType { + if let Some(&(_, span)) = self.named_expressions.get(&expr) { + InvalidAssignmentType::ImmutableBinding(span) + } else { + match self.naga_expressions[expr] { + crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, + crate::Expression::Access { base, .. } => self.invalid_assignment_type(base), + crate::Expression::AccessIndex { base, .. } => self.invalid_assignment_type(base), + _ => InvalidAssignmentType::Other, + } + } + } } /// State for lowering an `ast::Expression` to Naga IR. @@ -737,7 +753,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut local_table = FastHashMap::default(); let mut local_variables = Arena::new(); let mut expressions = Arena::new(); - let mut named_expressions = crate::NamedExpressions::default(); + let mut named_expressions = IndexMap::default(); let arguments = f .arguments @@ -748,7 +764,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let expr = expressions .append(crate::Expression::FunctionArgument(i as u32), arg.name.span); local_table.insert(arg.handle, TypedExpression::non_reference(expr)); - named_expressions.insert(expr, arg.name.name.to_string()); + named_expressions.insert(expr, (arg.name.name.to_string(), arg.name.span)); Ok(crate::FunctionArgument { name: Some(arg.name.name.to_string()), @@ -794,7 +810,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { result, local_variables, expressions, - named_expressions, + named_expressions: named_expressions + .into_iter() + .map(|(key, (name, _))| (key, name)) + .collect(), body, }; @@ -867,7 +886,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { block.extend(emitter.finish(ctx.naga_expressions)); ctx.local_table .insert(l.handle, TypedExpression::non_reference(value)); - ctx.named_expressions.insert(value, l.name.name.to_string()); + ctx.named_expressions + .insert(value, (l.name.name.to_string(), l.name.span)); return Ok(()); } @@ -1068,14 +1088,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut value = self.expression(value, ctx.as_expression(block, &mut emitter))?; if !expr.is_reference { - let ty = if ctx.named_expressions.contains_key(&expr.handle) { - InvalidAssignmentType::ImmutableBinding - } else { - match ctx.naga_expressions[expr.handle] { - crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, - _ => InvalidAssignmentType::Other, - } - }; + let ty = ctx.invalid_assignment_type(expr.handle); return Err(Error::InvalidAssignment { span: ctx.ast_expressions.get_span(target), From a5c2cf94b8a68980b73efe4225209731449b5c8e Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Tue, 31 Jan 2023 22:07:01 +0530 Subject: [PATCH 1928/2212] update tests --- tests/wgsl-errors.rs | 49 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 039d4751b..f7c86b403 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1624,13 +1624,56 @@ fn assign_to_let() { } ", r###"error: invalid left-hand side of assignment - ┌─ wgsl:4:10 + ┌─ wgsl:3:17 │ +3 │ let a = 10; + │ ^ this is an immutable binding 4 │ a = 20; │ ^ cannot assign to this expression │ - = note: 'a' is an immutable binding - = note: consider declaring it with `var` instead of `let` + = note: consider declaring 'a' with `var` instead of `let` + +"###, + ); + + check( + " + fn f() { + let a = array(1, 2); + a[0] = 1; + } + ", + r###"error: invalid left-hand side of assignment + ┌─ wgsl:3:17 + │ +3 │ let a = array(1, 2); + │ ^ this is an immutable binding +4 │ a[0] = 1; + │ ^^^^ cannot assign to this expression + │ + = note: consider declaring 'a' with `var` instead of `let` + +"###, + ); + + check( + " + struct S { a: i32 } + + fn f() { + let a = S(10); + a.a = 20; + } + ", + r###"error: invalid left-hand side of assignment + ┌─ wgsl:5:17 + │ +5 │ let a = S(10); + │ ^ this is an immutable binding +6 │ a.a = 20; + │ ^^^ cannot assign to this expression + │ + = note: consider declaring 'a' with `var` instead of `let` "###, ); From fe851fb008c67924ea0569e7a8f83dd2da41ede9 Mon Sep 17 00:00:00 2001 From: Artavazd Balaian Date: Thu, 2 Feb 2023 19:08:18 +0700 Subject: [PATCH 1929/2212] [glsl] Inject default `gl_PointSize = 1.0` in vertex shaders if `FORCE_POINT_SIZE` option was set (#2223) According to https://registry.khronos.org/OpenGL/specs/es/3.2/GLSL_ES_Specification_3.20.html#built-in-language-variables > The variable gl_PointSize is intended for a shader to write the size of the point to be rasterized. It is measured in pixels. If gl_PointSize is not written to, its value is undefined in subsequent pipe stages. - Write warn message if `ClipDistance` and `CullDistance` are used on unsupported version --------- Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> --- src/back/glsl/mod.rs | 57 +++++++++++++------ ...e_point_size_vertex_shader_webgl.param.ron | 11 ++++ .../force_point_size_vertex_shader_webgl.wgsl | 14 +++++ ..._vertex_shader_webgl.fs_main.Fragment.glsl | 12 ++++ ...ze_vertex_shader_webgl.vs_main.Vertex.glsl | 15 +++++ tests/snapshots.rs | 1 + 6 files changed, 94 insertions(+), 16 deletions(-) create mode 100644 tests/in/force_point_size_vertex_shader_webgl.param.ron create mode 100644 tests/in/force_point_size_vertex_shader_webgl.wgsl create mode 100644 tests/out/glsl/force_point_size_vertex_shader_webgl.fs_main.Fragment.glsl create mode 100644 tests/out/glsl/force_point_size_vertex_shader_webgl.vs_main.Vertex.glsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 6c90fcb26..838b32344 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -218,6 +218,13 @@ bitflags::bitflags! { /// global variables that are not used in the specified entrypoint (including indirect use), /// all constant declarations, and functions that use excluded global variables. const INCLUDE_UNUSED_ITEMS = 0x4; + /// Emit `PointSize` output builtin to vertex shaders, which is + /// required for drawing with `PointList` topology. + /// + /// https://registry.khronos.org/OpenGL/specs/es/3.2/GLSL_ES_Specification_3.20.html#built-in-language-variables + /// The variable gl_PointSize is intended for a shader to write the size of the point to be rasterized. It is measured in pixels. + /// If gl_PointSize is not written to, its value is undefined in subsequent pipe stages. + const FORCE_POINT_SIZE = 0x10; } } @@ -1978,6 +1985,7 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ";")?; } back::FunctionType::EntryPoint(ep_index) => { + let mut has_point_size = false; let ep = &self.module.entry_points[ep_index as usize]; if let Some(ref result) = ep.function.result { let value = value.unwrap(); @@ -2005,11 +2013,18 @@ impl<'a, W: Write> Writer<'a, W> { if let Some(crate::Binding::BuiltIn(builtin)) = member.binding { + has_point_size |= builtin == crate::BuiltIn::PointSize; + match builtin { crate::BuiltIn::ClipDistance - | crate::BuiltIn::CullDistance - | crate::BuiltIn::PointSize => { + | crate::BuiltIn::CullDistance => { if self.options.version.is_es() { + // Note that gl_ClipDistance and gl_CullDistance are listed in the GLSL ES 3.2 spec but shouldn't + // See https://github.com/KhronosGroup/GLSL/issues/132#issuecomment-685818465 + log::warn!( + "{:?} is not part of GLSL ES", + builtin + ); continue; } } @@ -2056,20 +2071,30 @@ impl<'a, W: Write> Writer<'a, W> { } } - if let back::FunctionType::EntryPoint(ep_index) = ctx.ty { - if self.module.entry_points[ep_index as usize].stage - == crate::ShaderStage::Vertex - && self - .options - .writer_flags - .contains(WriterFlags::ADJUST_COORDINATE_SPACE) - { - writeln!( - self.out, - "gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);", - )?; - write!(self.out, "{level}")?; - } + let is_vertex_stage = self.module.entry_points[ep_index as usize].stage + == ShaderStage::Vertex; + if is_vertex_stage + && self + .options + .writer_flags + .contains(WriterFlags::ADJUST_COORDINATE_SPACE) + { + writeln!( + self.out, + "gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);", + )?; + write!(self.out, "{level}")?; + } + + if is_vertex_stage + && self + .options + .writer_flags + .contains(WriterFlags::FORCE_POINT_SIZE) + && !has_point_size + { + writeln!(self.out, "gl_PointSize = 1.0;")?; + write!(self.out, "{level}")?; } writeln!(self.out, "return;")?; } diff --git a/tests/in/force_point_size_vertex_shader_webgl.param.ron b/tests/in/force_point_size_vertex_shader_webgl.param.ron new file mode 100644 index 000000000..9499c6b99 --- /dev/null +++ b/tests/in/force_point_size_vertex_shader_webgl.param.ron @@ -0,0 +1,11 @@ +( + glsl: ( + version: Embedded ( + version: 300, + is_webgl: true + ), + writer_flags: (bits: 16), + binding_map: {}, + zero_initialize_workgroup_memory: true, + ), +) diff --git a/tests/in/force_point_size_vertex_shader_webgl.wgsl b/tests/in/force_point_size_vertex_shader_webgl.wgsl new file mode 100644 index 000000000..001468bd5 --- /dev/null +++ b/tests/in/force_point_size_vertex_shader_webgl.wgsl @@ -0,0 +1,14 @@ +// AUTHOR: REASY +// ISSUE: https://github.com/gfx-rs/wgpu/issues/3179 +// FIX: https://github.com/gfx-rs/wgpu/pull/3440 +@vertex +fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4 { + let x = f32(i32(in_vertex_index) - 1); + let y = f32(i32(in_vertex_index & 1u) * 2 - 1); + return vec4(x, y, 0.0, 1.0); +} + +@fragment +fn fs_main() -> @location(0) vec4 { + return vec4(1.0, 0.0, 0.0, 1.0); +} diff --git a/tests/out/glsl/force_point_size_vertex_shader_webgl.fs_main.Fragment.glsl b/tests/out/glsl/force_point_size_vertex_shader_webgl.fs_main.Fragment.glsl new file mode 100644 index 000000000..5d0f7a807 --- /dev/null +++ b/tests/out/glsl/force_point_size_vertex_shader_webgl.fs_main.Fragment.glsl @@ -0,0 +1,12 @@ +#version 300 es + +precision highp float; +precision highp int; + +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + _fs2p_location0 = vec4(1.0, 0.0, 0.0, 1.0); + return; +} + diff --git a/tests/out/glsl/force_point_size_vertex_shader_webgl.vs_main.Vertex.glsl b/tests/out/glsl/force_point_size_vertex_shader_webgl.vs_main.Vertex.glsl new file mode 100644 index 000000000..069595bc8 --- /dev/null +++ b/tests/out/glsl/force_point_size_vertex_shader_webgl.vs_main.Vertex.glsl @@ -0,0 +1,15 @@ +#version 300 es + +precision highp float; +precision highp int; + + +void main() { + uint in_vertex_index = uint(gl_VertexID); + float x = float((int(in_vertex_index) - 1)); + float y = float(((int((in_vertex_index & 1u)) * 2) - 1)); + gl_Position = vec4(x, y, 0.0, 1.0); + gl_PointSize = 1.0; + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 25f307c11..cc2b30055 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -557,6 +557,7 @@ fn convert_wgsl() { Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, ), ("sprite", Targets::SPIRV), + ("force_point_size_vertex_shader_webgl", Targets::GLSL), ]; for &(name, targets) in inputs.iter() { From fb2d438dbda3f9bcddb6ac4e0a0efc0ed6b0b7b3 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Thu, 2 Feb 2023 12:47:17 -0500 Subject: [PATCH 1930/2212] [msl-out] Update firstLeadingBit for signed integers (#2235) The prior code only supported unsigned integers. Also fixes #2236. Co-authored-by: Jim Blandy --- src/back/msl/writer.rs | 102 +++++++++++++++++-------- tests/in/bits.wgsl | 2 + tests/out/glsl/bits.main.Compute.glsl | 70 +++++++++-------- tests/out/msl/bits.msl | 72 ++++++++--------- tests/out/msl/math-functions.msl | 3 +- tests/out/spv/bits.spvasm | 106 ++++++++++++++------------ tests/out/wgsl/bits.wgsl | 70 +++++++++-------- 7 files changed, 243 insertions(+), 182 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index d424c11b2..a4635ac2e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1721,9 +1721,49 @@ impl Writer { self.put_expression(arg, context, true)?; write!(self.out, ") + 1) % 33) - 1)")?; } else if fun == Mf::FindMsb { - write!(self.out, "((({NAMESPACE}::clz(")?; + let inner = context.resolve_type(arg); + + write!(self.out, "{NAMESPACE}::select(31 - {NAMESPACE}::clz(")?; + + if let Some(crate::ScalarKind::Sint) = inner.scalar_kind() { + write!(self.out, "{NAMESPACE}::select(")?; + self.put_expression(arg, context, true)?; + write!(self.out, ", ~")?; + self.put_expression(arg, context, true)?; + write!(self.out, ", ")?; + self.put_expression(arg, context, true)?; + write!(self.out, " < 0)")?; + } else { + self.put_expression(arg, context, true)?; + } + + write!(self.out, "), ")?; + + // or metal will complain that select is ambiguous + match *inner { + crate::TypeInner::Vector { size, kind, .. } => { + let size = back::vector_size_str(size); + if let crate::ScalarKind::Sint = kind { + write!(self.out, "int{size}")?; + } else { + write!(self.out, "uint{size}")?; + } + } + crate::TypeInner::Scalar { kind, .. } => { + if let crate::ScalarKind::Sint = kind { + write!(self.out, "int")?; + } else { + write!(self.out, "uint")?; + } + } + _ => (), + } + + write!(self.out, "(-1), ")?; self.put_expression(arg, context, true)?; - write!(self.out, ") + 1) % 33) - 1)")? + write!(self.out, " == 0 || ")?; + self.put_expression(arg, context, true)?; + write!(self.out, " == -1)")?; } else if fun == Mf::Unpack2x16float { write!(self.out, "float2(as_type(")?; self.put_expression(arg, context, false)?; @@ -2275,42 +2315,42 @@ impl Writer { ) { use crate::Expression; self.need_bake_expressions.clear(); - for expr in func.expressions.iter() { + for (expr_handle, expr) in func.expressions.iter() { // Expressions whose reference count is above the // threshold should always be stored in temporaries. - let expr_info = &info[expr.0]; - let min_ref_count = func.expressions[expr.0].bake_ref_count(); + let expr_info = &info[expr_handle]; + let min_ref_count = func.expressions[expr_handle].bake_ref_count(); if min_ref_count <= expr_info.ref_count { - self.need_bake_expressions.insert(expr.0); + self.need_bake_expressions.insert(expr_handle); } - // WGSL's `dot` function works on any `vecN` type, but Metal's only - // works on floating-point vectors, so we emit inline code for - // integer vector `dot` calls. But that code uses each argument `N` - // times, once for each component (see `put_dot_product`), so to - // avoid duplicated evaluation, we must bake integer operands. - if let ( - fun_handle, - &Expression::Math { - fun: crate::MathFunction::Dot, - arg, - arg1, - .. - }, - ) = expr - { - use crate::TypeInner; - // check what kind of product this is depending - // on the resolve type of the Dot function itself - let inner = context.resolve_type(fun_handle); - if let TypeInner::Scalar { kind, .. } = *inner { - match kind { - crate::ScalarKind::Sint | crate::ScalarKind::Uint => { - self.need_bake_expressions.insert(arg); - self.need_bake_expressions.insert(arg1.unwrap()); + if let Expression::Math { fun, arg, arg1, .. } = *expr { + match fun { + crate::MathFunction::Dot => { + // WGSL's `dot` function works on any `vecN` type, but Metal's only + // works on floating-point vectors, so we emit inline code for + // integer vector `dot` calls. But that code uses each argument `N` + // times, once for each component (see `put_dot_product`), so to + // avoid duplicated evaluation, we must bake integer operands. + + use crate::TypeInner; + // check what kind of product this is depending + // on the resolve type of the Dot function itself + let inner = context.resolve_type(expr_handle); + if let TypeInner::Scalar { kind, .. } = *inner { + match kind { + crate::ScalarKind::Sint | crate::ScalarKind::Uint => { + self.need_bake_expressions.insert(arg); + self.need_bake_expressions.insert(arg1.unwrap()); + } + _ => {} + } } - _ => {} } + crate::MathFunction::FindMsb => { + self.need_bake_expressions.insert(arg); + } + _ => {} } } } diff --git a/tests/in/bits.wgsl b/tests/in/bits.wgsl index 1e05d81f6..549ff08ec 100644 --- a/tests/in/bits.wgsl +++ b/tests/in/bits.wgsl @@ -39,6 +39,8 @@ fn main() { i = firstTrailingBit(i); u2 = firstTrailingBit(u2); i3 = firstLeadingBit(i3); + u3 = firstLeadingBit(u3); + i = firstLeadingBit(i); u = firstLeadingBit(u); i = countOneBits(i); i2 = countOneBits(i2); diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl index 504fb7c94..1c17638fa 100644 --- a/tests/out/glsl/bits.main.Compute.glsl +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -93,40 +93,44 @@ void main() { u2_ = uvec2(findLSB(_e122)); ivec3 _e124 = i3_; i3_ = findMSB(_e124); - uint _e126 = u; - u = uint(findMSB(_e126)); + uvec3 _e126 = u3_; + u3_ = uvec3(findMSB(_e126)); int _e128 = i; - i = bitCount(_e128); - ivec2 _e130 = i2_; - i2_ = bitCount(_e130); - ivec3 _e132 = i3_; - i3_ = bitCount(_e132); - ivec4 _e134 = i4_; - i4_ = bitCount(_e134); - uint _e136 = u; - u = uint(bitCount(_e136)); - uvec2 _e138 = u2_; - u2_ = uvec2(bitCount(_e138)); - uvec3 _e140 = u3_; - u3_ = uvec3(bitCount(_e140)); - uvec4 _e142 = u4_; - u4_ = uvec4(bitCount(_e142)); - int _e144 = i; - i = bitfieldReverse(_e144); - ivec2 _e146 = i2_; - i2_ = bitfieldReverse(_e146); - ivec3 _e148 = i3_; - i3_ = bitfieldReverse(_e148); - ivec4 _e150 = i4_; - i4_ = bitfieldReverse(_e150); - uint _e152 = u; - u = bitfieldReverse(_e152); - uvec2 _e154 = u2_; - u2_ = bitfieldReverse(_e154); - uvec3 _e156 = u3_; - u3_ = bitfieldReverse(_e156); - uvec4 _e158 = u4_; - u4_ = bitfieldReverse(_e158); + i = findMSB(_e128); + uint _e130 = u; + u = uint(findMSB(_e130)); + int _e132 = i; + i = bitCount(_e132); + ivec2 _e134 = i2_; + i2_ = bitCount(_e134); + ivec3 _e136 = i3_; + i3_ = bitCount(_e136); + ivec4 _e138 = i4_; + i4_ = bitCount(_e138); + uint _e140 = u; + u = uint(bitCount(_e140)); + uvec2 _e142 = u2_; + u2_ = uvec2(bitCount(_e142)); + uvec3 _e144 = u3_; + u3_ = uvec3(bitCount(_e144)); + uvec4 _e146 = u4_; + u4_ = uvec4(bitCount(_e146)); + int _e148 = i; + i = bitfieldReverse(_e148); + ivec2 _e150 = i2_; + i2_ = bitfieldReverse(_e150); + ivec3 _e152 = i3_; + i3_ = bitfieldReverse(_e152); + ivec4 _e154 = i4_; + i4_ = bitfieldReverse(_e154); + uint _e156 = u; + u = bitfieldReverse(_e156); + uvec2 _e158 = u2_; + u2_ = bitfieldReverse(_e158); + uvec3 _e160 = u3_; + u3_ = bitfieldReverse(_e160); + uvec4 _e162 = u4_; + u4_ = bitfieldReverse(_e162); return; } diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index 2a95996c7..2a00b6b84 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -92,40 +92,44 @@ kernel void main_( metal::uint2 _e122 = u2_; u2_ = (((metal::ctz(_e122) + 1) % 33) - 1); metal::int3 _e124 = i3_; - i3_ = (((metal::clz(_e124) + 1) % 33) - 1); - uint _e126 = u; - u = (((metal::clz(_e126) + 1) % 33) - 1); + i3_ = metal::select(31 - metal::clz(metal::select(_e124, ~_e124, _e124 < 0)), int3(-1), _e124 == 0 || _e124 == -1); + metal::uint3 _e126 = u3_; + u3_ = metal::select(31 - metal::clz(_e126), uint3(-1), _e126 == 0 || _e126 == -1); int _e128 = i; - i = metal::popcount(_e128); - metal::int2 _e130 = i2_; - i2_ = metal::popcount(_e130); - metal::int3 _e132 = i3_; - i3_ = metal::popcount(_e132); - metal::int4 _e134 = i4_; - i4_ = metal::popcount(_e134); - uint _e136 = u; - u = metal::popcount(_e136); - metal::uint2 _e138 = u2_; - u2_ = metal::popcount(_e138); - metal::uint3 _e140 = u3_; - u3_ = metal::popcount(_e140); - metal::uint4 _e142 = u4_; - u4_ = metal::popcount(_e142); - int _e144 = i; - i = metal::reverse_bits(_e144); - metal::int2 _e146 = i2_; - i2_ = metal::reverse_bits(_e146); - metal::int3 _e148 = i3_; - i3_ = metal::reverse_bits(_e148); - metal::int4 _e150 = i4_; - i4_ = metal::reverse_bits(_e150); - uint _e152 = u; - u = metal::reverse_bits(_e152); - metal::uint2 _e154 = u2_; - u2_ = metal::reverse_bits(_e154); - metal::uint3 _e156 = u3_; - u3_ = metal::reverse_bits(_e156); - metal::uint4 _e158 = u4_; - u4_ = metal::reverse_bits(_e158); + i = metal::select(31 - metal::clz(metal::select(_e128, ~_e128, _e128 < 0)), int(-1), _e128 == 0 || _e128 == -1); + uint _e130 = u; + u = metal::select(31 - metal::clz(_e130), uint(-1), _e130 == 0 || _e130 == -1); + int _e132 = i; + i = metal::popcount(_e132); + metal::int2 _e134 = i2_; + i2_ = metal::popcount(_e134); + metal::int3 _e136 = i3_; + i3_ = metal::popcount(_e136); + metal::int4 _e138 = i4_; + i4_ = metal::popcount(_e138); + uint _e140 = u; + u = metal::popcount(_e140); + metal::uint2 _e142 = u2_; + u2_ = metal::popcount(_e142); + metal::uint3 _e144 = u3_; + u3_ = metal::popcount(_e144); + metal::uint4 _e146 = u4_; + u4_ = metal::popcount(_e146); + int _e148 = i; + i = metal::reverse_bits(_e148); + metal::int2 _e150 = i2_; + i2_ = metal::reverse_bits(_e150); + metal::int3 _e152 = i3_; + i3_ = metal::reverse_bits(_e152); + metal::int4 _e154 = i4_; + i4_ = metal::reverse_bits(_e154); + uint _e156 = u; + u = metal::reverse_bits(_e156); + metal::uint2 _e158 = u2_; + u2_ = metal::reverse_bits(_e158); + metal::uint3 _e160 = u3_; + u3_ = metal::reverse_bits(_e160); + metal::uint4 _e162 = u4_; + u4_ = metal::reverse_bits(_e162); return; } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 0838a338c..3fdb7b75a 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -16,7 +16,8 @@ vertex void main_( metal::float4 e = metal::saturate(v); metal::float4 g = metal::refract(v, v, 1.0); int const_dot = ( + const_type_1_.x * const_type_1_.x + const_type_1_.y * const_type_1_.y); - uint first_leading_bit_abs = (((metal::clz(metal::abs(0u)) + 1) % 33) - 1); + uint _e13 = metal::abs(0u); + uint first_leading_bit_abs = metal::select(31 - metal::clz(_e13), uint(-1), _e13 == 0 || _e13 == -1); int clz_a = metal::clz(-1); uint clz_b = metal::clz(1u); metal::int2 clz_c = metal::clz(metal::int2(-1)); diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm index b8c17d870..750a2545b 100644 --- a/tests/out/spv/bits.spvasm +++ b/tests/out/spv/bits.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 161 +; Bound: 165 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -172,56 +172,62 @@ OpStore %34 %124 %125 = OpLoad %12 %25 %126 = OpExtInst %12 %1 FindSMsb %125 OpStore %25 %126 -%127 = OpLoad %6 %31 -%128 = OpExtInst %6 %1 FindUMsb %127 -OpStore %31 %128 +%127 = OpLoad %15 %37 +%128 = OpExtInst %15 %1 FindUMsb %127 +OpStore %37 %128 %129 = OpLoad %4 %19 -%130 = OpBitCount %4 %129 +%130 = OpExtInst %4 %1 FindSMsb %129 OpStore %19 %130 -%131 = OpLoad %11 %22 -%132 = OpBitCount %11 %131 -OpStore %22 %132 -%133 = OpLoad %12 %25 -%134 = OpBitCount %12 %133 -OpStore %25 %134 -%135 = OpLoad %13 %28 -%136 = OpBitCount %13 %135 -OpStore %28 %136 -%137 = OpLoad %6 %31 -%138 = OpBitCount %6 %137 -OpStore %31 %138 -%139 = OpLoad %14 %34 -%140 = OpBitCount %14 %139 -OpStore %34 %140 -%141 = OpLoad %15 %37 -%142 = OpBitCount %15 %141 -OpStore %37 %142 -%143 = OpLoad %16 %40 -%144 = OpBitCount %16 %143 -OpStore %40 %144 -%145 = OpLoad %4 %19 -%146 = OpBitReverse %4 %145 -OpStore %19 %146 -%147 = OpLoad %11 %22 -%148 = OpBitReverse %11 %147 -OpStore %22 %148 -%149 = OpLoad %12 %25 -%150 = OpBitReverse %12 %149 -OpStore %25 %150 -%151 = OpLoad %13 %28 -%152 = OpBitReverse %13 %151 -OpStore %28 %152 -%153 = OpLoad %6 %31 -%154 = OpBitReverse %6 %153 -OpStore %31 %154 -%155 = OpLoad %14 %34 -%156 = OpBitReverse %14 %155 -OpStore %34 %156 -%157 = OpLoad %15 %37 -%158 = OpBitReverse %15 %157 -OpStore %37 %158 -%159 = OpLoad %16 %40 -%160 = OpBitReverse %16 %159 -OpStore %40 %160 +%131 = OpLoad %6 %31 +%132 = OpExtInst %6 %1 FindUMsb %131 +OpStore %31 %132 +%133 = OpLoad %4 %19 +%134 = OpBitCount %4 %133 +OpStore %19 %134 +%135 = OpLoad %11 %22 +%136 = OpBitCount %11 %135 +OpStore %22 %136 +%137 = OpLoad %12 %25 +%138 = OpBitCount %12 %137 +OpStore %25 %138 +%139 = OpLoad %13 %28 +%140 = OpBitCount %13 %139 +OpStore %28 %140 +%141 = OpLoad %6 %31 +%142 = OpBitCount %6 %141 +OpStore %31 %142 +%143 = OpLoad %14 %34 +%144 = OpBitCount %14 %143 +OpStore %34 %144 +%145 = OpLoad %15 %37 +%146 = OpBitCount %15 %145 +OpStore %37 %146 +%147 = OpLoad %16 %40 +%148 = OpBitCount %16 %147 +OpStore %40 %148 +%149 = OpLoad %4 %19 +%150 = OpBitReverse %4 %149 +OpStore %19 %150 +%151 = OpLoad %11 %22 +%152 = OpBitReverse %11 %151 +OpStore %22 %152 +%153 = OpLoad %12 %25 +%154 = OpBitReverse %12 %153 +OpStore %25 %154 +%155 = OpLoad %13 %28 +%156 = OpBitReverse %13 %155 +OpStore %28 %156 +%157 = OpLoad %6 %31 +%158 = OpBitReverse %6 %157 +OpStore %31 %158 +%159 = OpLoad %14 %34 +%160 = OpBitReverse %14 %159 +OpStore %34 %160 +%161 = OpLoad %15 %37 +%162 = OpBitReverse %15 %161 +OpStore %37 %162 +%163 = OpLoad %16 %40 +%164 = OpBitReverse %16 %163 +OpStore %40 %164 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index 88876ec05..c203ac94d 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -87,39 +87,43 @@ fn main() { u2_ = firstTrailingBit(_e122); let _e124 = i3_; i3_ = firstLeadingBit(_e124); - let _e126 = u; - u = firstLeadingBit(_e126); + let _e126 = u3_; + u3_ = firstLeadingBit(_e126); let _e128 = i; - i = countOneBits(_e128); - let _e130 = i2_; - i2_ = countOneBits(_e130); - let _e132 = i3_; - i3_ = countOneBits(_e132); - let _e134 = i4_; - i4_ = countOneBits(_e134); - let _e136 = u; - u = countOneBits(_e136); - let _e138 = u2_; - u2_ = countOneBits(_e138); - let _e140 = u3_; - u3_ = countOneBits(_e140); - let _e142 = u4_; - u4_ = countOneBits(_e142); - let _e144 = i; - i = reverseBits(_e144); - let _e146 = i2_; - i2_ = reverseBits(_e146); - let _e148 = i3_; - i3_ = reverseBits(_e148); - let _e150 = i4_; - i4_ = reverseBits(_e150); - let _e152 = u; - u = reverseBits(_e152); - let _e154 = u2_; - u2_ = reverseBits(_e154); - let _e156 = u3_; - u3_ = reverseBits(_e156); - let _e158 = u4_; - u4_ = reverseBits(_e158); + i = firstLeadingBit(_e128); + let _e130 = u; + u = firstLeadingBit(_e130); + let _e132 = i; + i = countOneBits(_e132); + let _e134 = i2_; + i2_ = countOneBits(_e134); + let _e136 = i3_; + i3_ = countOneBits(_e136); + let _e138 = i4_; + i4_ = countOneBits(_e138); + let _e140 = u; + u = countOneBits(_e140); + let _e142 = u2_; + u2_ = countOneBits(_e142); + let _e144 = u3_; + u3_ = countOneBits(_e144); + let _e146 = u4_; + u4_ = countOneBits(_e146); + let _e148 = i; + i = reverseBits(_e148); + let _e150 = i2_; + i2_ = reverseBits(_e150); + let _e152 = i3_; + i3_ = reverseBits(_e152); + let _e154 = i4_; + i4_ = reverseBits(_e154); + let _e156 = u; + u = reverseBits(_e156); + let _e158 = u2_; + u2_ = reverseBits(_e158); + let _e160 = u3_; + u3_ = reverseBits(_e160); + let _e162 = u4_; + u4_ = reverseBits(_e162); return; } From 4b796b157cb2b67b0ab166a2238fe4e9473bfd52 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Thu, 2 Feb 2023 16:11:09 -0500 Subject: [PATCH 1931/2212] [glsl-out] Version check countLeadingZeros (#2238) --- src/back/glsl/mod.rs | 109 +++++++++++------- .../out/glsl/math-functions.main.Vertex.glsl | 9 +- 2 files changed, 74 insertions(+), 44 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 838b32344..aaed745f2 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -181,6 +181,10 @@ impl Version { fn supports_fma_function(&self) -> bool { *self >= Version::Desktop(400) || *self >= Version::new_gles(320) } + + fn supports_integer_functions(&self) -> bool { + *self >= Version::Desktop(400) || *self >= Version::new_gles(310) + } } impl PartialOrd for Version { @@ -1128,12 +1132,13 @@ impl<'a, W: Write> Writer<'a, W> { self.need_bake_expressions.insert(fun_handle); } + let inner = expr_info.ty.inner_with(&self.module.types); + if let Expression::Math { fun, arg, arg1, .. } = *expr { match fun { crate::MathFunction::Dot => { // if the expression is a Dot product with integer arguments, // then the args needs baking as well - let inner = info[fun_handle].ty.inner_with(&self.module.types); if let TypeInner::Scalar { kind, .. } = *inner { match kind { crate::ScalarKind::Sint | crate::ScalarKind::Uint => { @@ -1145,7 +1150,9 @@ impl<'a, W: Write> Writer<'a, W> { } } crate::MathFunction::CountLeadingZeros => { - self.need_bake_expressions.insert(arg); + if let Some(crate::ScalarKind::Sint) = inner.scalar_kind() { + self.need_bake_expressions.insert(arg); + } } _ => {} } @@ -2954,50 +2961,74 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Determinant => "determinant", // bits Mf::CountLeadingZeros => { - match *ctx.info[arg].ty.inner_with(&self.module.types) { - crate::TypeInner::Vector { size, kind, .. } => { - let s = back::vector_size_str(size); + if self.options.version.supports_integer_functions() { + match *ctx.info[arg].ty.inner_with(&self.module.types) { + crate::TypeInner::Vector { size, kind, .. } => { + let s = back::vector_size_str(size); - if let crate::ScalarKind::Uint = kind { - write!(self.out, "uvec{s}(")?; - } else { - write!(self.out, "ivec{s}(")?; + if let crate::ScalarKind::Uint = kind { + write!(self.out, "uvec{s}(ivec{s}(31) - findMSB(")?; + self.write_expr(arg, ctx)?; + write!(self.out, "))")?; + } else { + write!(self.out, "mix(ivec{s}(31) - findMSB(")?; + self.write_expr(arg, ctx)?; + write!(self.out, "), ivec{s}(0), lessThan(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ", ivec{s}(0)))")?; + } } + crate::TypeInner::Scalar { kind, .. } => { + if let crate::ScalarKind::Uint = kind { + write!(self.out, "uint(31 - findMSB(")?; + } else { + write!(self.out, "(")?; + self.write_expr(arg, ctx)?; + write!(self.out, " < 0 ? 0 : 31 - findMSB(")?; + } - write!(self.out, "mix(vec{s}(31.0) - floor(log2(vec{s}(")?; - self.write_expr(arg, ctx)?; - write!(self.out, ") + 0.5)), ")?; - - if let crate::ScalarKind::Uint = kind { - write!(self.out, "vec{s}(32.0), lessThanEqual(")?; self.write_expr(arg, ctx)?; - write!(self.out, ", uvec{s}(0u))))")?; - } else { - write!(self.out, "mix(vec{s}(0.0), vec{s}(32.0), equal(")?; - self.write_expr(arg, ctx)?; - write!(self.out, ", ivec{s}(0))), lessThanEqual(")?; - self.write_expr(arg, ctx)?; - write!(self.out, ", ivec{s}(0))))")?; + write!(self.out, "))")?; } - } - crate::TypeInner::Scalar { kind, .. } => { - write!(self.out, "(")?; - self.write_expr(arg, ctx)?; + _ => unreachable!(), + }; + } else { + match *ctx.info[arg].ty.inner_with(&self.module.types) { + crate::TypeInner::Vector { size, kind, .. } => { + let s = back::vector_size_str(size); - if let crate::ScalarKind::Uint = kind { - write!(self.out, " == 0u ? 32u : uint(")?; - } else { - write!(self.out, " <= 0 ? (")?; - self.write_expr(arg, ctx)?; - write!(self.out, " == 0 ? 32 : 0) : int(")?; + if let crate::ScalarKind::Uint = kind { + write!(self.out, "uvec{s}(")?; + write!(self.out, "vec{s}(31.0) - floor(log2(vec{s}(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ") + 0.5)))")?; + } else { + write!(self.out, "ivec{s}(")?; + write!(self.out, "mix(vec{s}(31.0) - floor(log2(vec{s}(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ") + 0.5)), ")?; + write!(self.out, "vec{s}(0.0), lessThan(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ", ivec{s}(0u))))")?; + } } - - write!(self.out, "31.0 - floor(log2(float(")?; - self.write_expr(arg, ctx)?; - write!(self.out, ") + 0.5))))")?; - } - _ => unreachable!(), - }; + crate::TypeInner::Scalar { kind, .. } => { + if let crate::ScalarKind::Uint = kind { + write!(self.out, "uint(31.0 - floor(log2(float(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ") + 0.5)))")?; + } else { + write!(self.out, "(")?; + self.write_expr(arg, ctx)?; + write!(self.out, " < 0 ? 0 : int(")?; + write!(self.out, "31.0 - floor(log2(float(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ") + 0.5))))")?; + } + } + _ => unreachable!(), + }; + } return Ok(()); } diff --git a/tests/out/glsl/math-functions.main.Vertex.glsl b/tests/out/glsl/math-functions.main.Vertex.glsl index d863ada72..8cfa6a10b 100644 --- a/tests/out/glsl/math-functions.main.Vertex.glsl +++ b/tests/out/glsl/math-functions.main.Vertex.glsl @@ -14,11 +14,10 @@ void main() { vec4 g = refract(v, v, 1.0); int const_dot = ( + ivec2(0, 0).x * ivec2(0, 0).x + ivec2(0, 0).y * ivec2(0, 0).y); uint first_leading_bit_abs = uint(findMSB(uint(abs(int(0u))))); - int clz_a = (-1 <= 0 ? (-1 == 0 ? 32 : 0) : int(31.0 - floor(log2(float(-1) + 0.5)))); - uint clz_b = (1u == 0u ? 32u : uint(31.0 - floor(log2(float(1u) + 0.5)))); + int clz_a = (-1 < 0 ? 0 : 31 - findMSB(-1)); + uint clz_b = uint(31 - findMSB(1u)); ivec2 _e20 = ivec2(-1); - ivec2 clz_c = ivec2(mix(vec2(31.0) - floor(log2(vec2(_e20) + 0.5)), mix(vec2(0.0), vec2(32.0), equal(_e20, ivec2(0))), lessThanEqual(_e20, ivec2(0)))); - uvec2 _e23 = uvec2(1u); - uvec2 clz_d = uvec2(mix(vec2(31.0) - floor(log2(vec2(_e23) + 0.5)), vec2(32.0), lessThanEqual(_e23, uvec2(0u)))); + ivec2 clz_c = mix(ivec2(31) - findMSB(_e20), ivec2(0), lessThan(_e20, ivec2(0))); + uvec2 clz_d = uvec2(ivec2(31) - findMSB(uvec2(1u))); } From fc81a20f5305c9bc8d01f62353d148b88251e456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 3 Feb 2023 10:48:23 +0000 Subject: [PATCH 1932/2212] spv-in: Don't apply interpolation to fragment shaders outputs (#2239) SPIR-V doesn't allow the `Flat`, `NoPerspective`, `Sample` or `Centroid` decorations on fragment shaders outputs, but the spirv frontend was applying default interpolation to all outputs unconditionally. This wasn't an issue for most shaders since they output floats and the default values for them don't interfere with SPIR-V semantics, but if the shader returned a uint or int the interpolation would be set to `Flat` which as stated above is disallowed. This commit fixes the issue by only running the default interpolation code when constructing the entry point and if the stage/IO allow it. --- src/front/spv/function.rs | 24 +++++++++++++++++++++--- src/front/spv/mod.rs | 14 +++----------- tests/out/ir/shadow.ron | 4 ++-- 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 8ae9a328d..898d00f79 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -387,7 +387,18 @@ impl> super::Frontend { None => continue, _ => {} } - members.push(sm.clone()); + let mut sm = sm.clone(); + + if let Some(ref mut binding) = sm.binding { + if ep.stage == crate::ShaderStage::Vertex { + binding.apply_default_interpolation( + &module.types[sm.ty].inner, + ); + } + } + + members.push(sm); + components.push(function.expressions.append( crate::Expression::AccessIndex { base: expr_handle, @@ -397,11 +408,18 @@ impl> super::Frontend { )); } } - _ => { + ref inner => { + let mut binding = result.binding.clone(); + if let Some(ref mut binding) = binding { + if ep.stage == crate::ShaderStage::Vertex { + binding.apply_default_interpolation(inner); + } + } + members.push(crate::StructMember { name: None, ty: result.ty, - binding: result.binding.clone(), + binding, offset: 0, }); // populate just the globals first, then do `Load` in a diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 8b24a8e88..e5e9d4700 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -4479,7 +4479,7 @@ impl> Frontend { span = member_alignment.round_up(span); alignment = member_alignment.max(alignment); - let mut binding = decor.io_binding().ok(); + let binding = decor.io_binding().ok(); if let Some(offset) = decor.offset { span = offset; } @@ -4507,9 +4507,6 @@ impl> Frontend { } } - if let Some(ref mut binding) = binding { - binding.apply_default_interpolation(inner); - } members.push(crate::StructMember { name: decor.name, ty, @@ -4943,7 +4940,7 @@ impl> Frontend { (Variable::Global, var) } ExtendedClass::Input => { - let mut binding = dec.io_binding()?; + let binding = dec.io_binding()?; let mut unsigned_ty = ty; if let crate::Binding::BuiltIn(built_in) = binding { let needs_inner_uint = match built_in { @@ -4984,8 +4981,6 @@ impl> Frontend { init: None, }; - binding.apply_default_interpolation(&module.types[unsigned_ty].inner); - let inner = Variable::Input(crate::FunctionArgument { name: dec.name, ty: unsigned_ty, @@ -4995,7 +4990,7 @@ impl> Frontend { } ExtendedClass::Output => { // For output interface blocks, this would be a structure. - let mut binding = dec.io_binding().ok(); + let binding = dec.io_binding().ok(); let init = match binding { Some(crate::Binding::BuiltIn(built_in)) => { match null::generate_default_built_in( @@ -5058,9 +5053,6 @@ impl> Frontend { ty, init, }; - if let Some(ref mut binding) = binding { - binding.apply_default_interpolation(&module.types[ty].inner); - } let inner = Variable::Output(crate::FunctionResult { ty, binding }); (inner, var) } diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 11411c89e..8956076ef 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -1368,8 +1368,8 @@ ty: 4, binding: Some(Location( location: 0, - interpolation: Some(Perspective), - sampling: Some(Center), + interpolation: None, + sampling: None, )), )), local_variables: [], From 2d0aab875ab97b48e502723e86c31bbf34d46186 Mon Sep 17 00:00:00 2001 From: manunio Date: Fri, 3 Feb 2023 19:41:48 +0530 Subject: [PATCH 1933/2212] fuzz: fix build failure (#2240) --- fuzz/fuzz_targets/glsl_parser.rs | 4 ++-- fuzz/fuzz_targets/spv_parser.rs | 4 ++-- fuzz/fuzz_targets/wgsl_parser.rs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/fuzz/fuzz_targets/glsl_parser.rs b/fuzz/fuzz_targets/glsl_parser.rs index b600eb513..18d7175e0 100644 --- a/fuzz/fuzz_targets/glsl_parser.rs +++ b/fuzz/fuzz_targets/glsl_parser.rs @@ -2,7 +2,7 @@ use arbitrary::Arbitrary; use libfuzzer_sys::fuzz_target; use naga::{ - front::glsl::{Options, Parser}, + front::glsl::{Frontend, Options}, FastHashMap, ShaderStage, }; @@ -41,6 +41,6 @@ impl From for Options { fuzz_target!(|data: (OptionsProxy, String)| { let (options, source) = data; // Ensure the parser can handle potentially malformed strings without crashing. - let mut parser = Parser::default(); + let mut parser = Frontend::default(); let _result = parser.parse(&options.into(), &source); }); diff --git a/fuzz/fuzz_targets/spv_parser.rs b/fuzz/fuzz_targets/spv_parser.rs index 0fda11f43..dda3d5e63 100644 --- a/fuzz/fuzz_targets/spv_parser.rs +++ b/fuzz/fuzz_targets/spv_parser.rs @@ -1,9 +1,9 @@ #![no_main] use libfuzzer_sys::fuzz_target; -use naga::front::spv::{Options, Parser}; +use naga::front::spv::{Frontend, Options}; fuzz_target!(|data: Vec| { // Ensure the parser can handle potentially malformed data without crashing. let options = Options::default(); - let _result = Parser::new(data.into_iter(), &options).parse(); + let _result = Frontend::new(data.into_iter(), &options).parse(); }); diff --git a/fuzz/fuzz_targets/wgsl_parser.rs b/fuzz/fuzz_targets/wgsl_parser.rs index 3ff9b15bf..a61e99979 100644 --- a/fuzz/fuzz_targets/wgsl_parser.rs +++ b/fuzz/fuzz_targets/wgsl_parser.rs @@ -1,8 +1,8 @@ #![no_main] use libfuzzer_sys::fuzz_target; -use naga::front::wgsl::Parser; +use naga::front::wgsl::Frontend; fuzz_target!(|data: String| { // Ensure the parser can handle potentially malformed strings without crashing. - let _result = Parser::new().parse(&data); + let _result = Frontend::new().parse(&data); }); From 64f8691e52584eae447f25ed761b9c4218b7efb6 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 6 Feb 2023 17:47:18 +0100 Subject: [PATCH 1934/2212] Improve CI (#2241) * update to actions/checkout@v3 * update to actions/upload-artifact@v3 * remove minor version * remove unmaintained actions-rs actions * update to codecov/codecov-action@v3 * use ubuntu-latest * use extra cargo/rust env vars * use cargo-nextest * check naga-fuzz * only check on MSRV and minimal-versions * add whitespace between steps * rename to CI * use cargo-llvm-cov to generate code coverage --- .github/workflows/ci.yml | 104 +++++++++++++++++++++++ .github/workflows/lazy.yml | 89 ++++++++----------- .github/workflows/pipeline.yml | 100 ---------------------- .github/workflows/validation-linux.yml | 9 +- .github/workflows/validation-macos.yml | 3 +- .github/workflows/validation-windows.yml | 10 ++- 6 files changed, 154 insertions(+), 161 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/pipeline.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..cdc19f3b2 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,104 @@ +name: CI +on: [push, pull_request] + +env: + CARGO_INCREMENTAL: false + CARGO_TERM_COLOR: always + RUST_BACKTRACE: full + MSRV: 1.63 + +jobs: + check-msrv: + name: Check MSRV and minimal-versions + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Install MSRV toolchain + run: rustup toolchain install $MSRV --no-self-update --profile=minimal + + - name: Install nightly toolchain + run: rustup toolchain install nightly --no-self-update --profile=minimal + + - name: Install cargo-hack + uses: taiki-e/install-action@v2 + with: + tool: cargo-hack + + # -Z avoid-dev-deps doesn't work + - run: cargo +nightly hack generate-lockfile --remove-dev-deps -Z minimal-versions --offline + + - name: Test all features + run: cargo +$MSRV check --all-features --workspace + + test: + name: Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Install cargo-nextest and cargo-llvm-cov + uses: taiki-e/install-action@v2 + with: + tool: cargo-nextest,cargo-llvm-cov + + - name: Default test + # Our intention here is to test `naga` with no features enabled. But + # since `cli` is the default package, a plain `cargo test` will build + # `naga` with the features requested in `cli/Cargo.toml`. Passing + # `--package naga` causes us to use the default features in the + # top-level `Cargo.toml` instead. + run: cargo nextest run --package naga + + - name: Test all features + run: cargo llvm-cov --lcov --output-path lcov.info nextest --all-features --workspace + + - name: Upload coverage report to codecov + uses: codecov/codecov-action@v3 + with: + files: lcov.info + + - name: Check snapshots + run: git diff --exit-code -- tests/out + + check: + name: Check benchmarks and naga-fuzz + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Check benchmarks + run: cargo check --benches + + - name: Check naga-fuzz + run: | + cd fuzz + cargo check + + clippy: + name: Clippy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - run: rustup component add clippy + + - run: cargo clippy --all-features --workspace -- -D warnings + + documentation: + name: Documentation + runs-on: ubuntu-latest + env: + RUSTDOCFLAGS: -Dwarnings + steps: + - uses: actions/checkout@v3 + + - run: cargo doc -p naga --all-features --document-private-items + + fmt: + name: Format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - run: cargo fmt -- --check diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index faa1bf05b..6bdb83c80 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -4,49 +4,29 @@ on: push: branches: [master] -jobs: - coverage: - name: Coverage - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - - name: Install binstall - uses: taiki-e/install-action@v2 - with: - tool: cargo-binstall - - name: Install cargo-tarpaulin - run: cargo binstall --no-confirm cargo-tarpaulin - - name: Generate report - run: cargo tarpaulin --tests --all-features --workspace --out Xml - - name: Upload to codecov.io - uses: codecov/codecov-action@v1 - with: - token: ${{ secrets.CODECOV_TOKEN }} - - name: Archive code coverage results - uses: actions/upload-artifact@v1 - with: - name: code-coverage-report - path: cobertura.xml +env: + CARGO_INCREMENTAL: false + CARGO_TERM_COLOR: always + RUST_BACKTRACE: full +jobs: parse-dota2: name: Parse Dota2 shaders runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable + - uses: actions/checkout@v3 + - run: mkdir data + - name: Download shaders run: curl https://user.fm/files/v2-5573e18b9f03f42c6ae53c392083da35/dota2-shaders.zip -o data/all.zip + - name: Unpack shaders run: cd data && unzip all.zip + - name: Build Naga run: cargo build --release --bin naga + - name: Convert shaders run: for file in data/*.spv ; do echo "Translating" ${file} && target/release/naga --validate 27 ${file} ${file}.metal; done @@ -54,15 +34,14 @@ jobs: name: Parse Sascha Willems Vulkan tutorial shaders runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable + - uses: actions/checkout@v3 + - name: Download shaders run: git clone https://github.com/SaschaWillems/Vulkan.git + - name: Build Naga run: cargo build --release --bin naga + - name: Convert metal shaders run: | # No needed to stop workflow if we can't validate one file @@ -87,20 +66,20 @@ jobs: name: Parse dneto0 spirv-samples runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable + - uses: actions/checkout@v3 + - name: Download shaders run: git clone https://github.com/dneto0/spirv-samples.git + - name: Build Naga run: cargo build --release --bin naga + - name: Install spirv-tools run: | wget -q https://storage.googleapis.com/spirv-tools/artifacts/prod/graphics_shader_compiler/spirv-tools/linux-clang-release/continuous/1489/20210629-121459/install.tgz tar zxf install.tgz ./install/bin/spirv-as --version + - name: Compile spv from spvasm run: | cd spirv-samples @@ -111,6 +90,7 @@ jobs: echo "Convert to spv with spirv-as: $fname" ../install/bin/spirv-as --target-env spv1.3 $(realpath ${fname}) -o ./spv/$(basename ${fname}).spv done; + - name: Validate spv and generate wgsl run: | set +e @@ -135,6 +115,7 @@ jobs: echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter done cat counter + - name: Validate output wgsl run: | set +e @@ -161,20 +142,18 @@ jobs: name: Check snapshots (validated or not) runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 + - uses: actions/checkout@v3 + + - name: Install cargo-nextest + uses: taiki-e/install-action@v2 with: - profile: minimal - toolchain: stable - - uses: actions-rs/cargo@v1 - name: Test minimal (without span) - with: - command: test - args: --features validate -p naga - - uses: actions-rs/cargo@v1 - name: Test all (without validation) - with: - command: test - args: --features wgsl-in,wgsl-out,glsl-in,glsl-out,spv-in,spv-out,msl-out,hlsl-out,dot-out --workspace + tool: cargo-nextest + + - name: Test minimal (without span) + run: cargo nextest run --features validate -p naga + + - name: Test all (without validation) + run: cargo nextest run --features wgsl-in,wgsl-out,glsl-in,glsl-out,spv-in,spv-out,msl-out,hlsl-out,dot-out --workspace + - name: Check snapshots (without validation) run: git diff --exit-code -- tests/out diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml deleted file mode 100644 index 512571327..000000000 --- a/.github/workflows/pipeline.yml +++ /dev/null @@ -1,100 +0,0 @@ -# Regular testing. -name: pipeline -on: [push, pull_request] - -jobs: - test-msrv: - name: Test MSRV and dependencies minimal-versions - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: "1.63.0" - override: true - - uses: taiki-e/install-action@cargo-hack - - uses: taiki-e/install-action@cargo-minimal-versions - # nightly is only used by cargo-minimal-versions to regenerate the lock file - - run: rustup toolchain add nightly --no-self-update - - name: Test all features - run: cargo minimal-versions test --all-features --workspace - - name: Check snapshots - run: git diff --exit-code -- tests/out - test: - name: Test Nightly - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: nightly - override: true - - uses: actions-rs/cargo@v1 - name: Default test - with: - # Our intention here is to test `naga` with no features enabled. But - # since `cli` is the default package, a plain `cargo test` will build - # `naga` with the features requested in `cli/Cargo.toml`. Passing - # `--package naga` causes us to use the default features in the - # top-level `Cargo.toml` instead. - command: test - args: --package naga - - uses: actions-rs/cargo@v1 - name: Test all features - with: - command: test - args: --all-features --workspace - - name: Check snapshots - run: git diff --exit-code -- tests/out - - uses: actions-rs/cargo@v1 - name: Check benchmarks - with: - command: check - args: --benches - clippy: - name: Clippy - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true - - run: rustup component add clippy - - uses: actions-rs/cargo@v1 - with: - command: clippy - args: --all-features --workspace -- -D warnings - documentation: - name: Documentation - runs-on: ubuntu-latest - env: - RUSTDOCFLAGS: -Dwarnings - steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true - - uses: actions-rs/cargo@v1 - with: - command: doc - args: -p naga --all-features --document-private-items - fmt: - name: Format - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true - components: rustfmt - - name: run rustfmt - run: | - cargo fmt -- --check diff --git a/.github/workflows/validation-linux.yml b/.github/workflows/validation-linux.yml index 1ac1a4759..8da38da7b 100644 --- a/.github/workflows/validation-linux.yml +++ b/.github/workflows/validation-linux.yml @@ -11,12 +11,17 @@ on: jobs: validate-linux: name: SPIR-V + GLSL - runs-on: ubuntu-20.04 + runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 + - name: Install tools run: sudo apt-get install spirv-tools glslang-tools graphviz + - run: make validate-spv + - run: make validate-glsl + - run: make validate-dot + - run: make validate-wgsl diff --git a/.github/workflows/validation-macos.yml b/.github/workflows/validation-macos.yml index 300d77803..2ec185ea0 100644 --- a/.github/workflows/validation-macos.yml +++ b/.github/workflows/validation-macos.yml @@ -9,5 +9,6 @@ jobs: name: MSL runs-on: macos-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 + - run: make validate-msl diff --git a/.github/workflows/validation-windows.yml b/.github/workflows/validation-windows.yml index 1d1d32401..da6fe7065 100644 --- a/.github/workflows/validation-windows.yml +++ b/.github/workflows/validation-windows.yml @@ -9,9 +9,11 @@ jobs: name: HLSL via DXC runs-on: windows-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 + - name: Add DirectXShaderCompiler - uses: napokue/setup-dxc@v1.1.0 + uses: napokue/setup-dxc@v1.1 + - run: make validate-hlsl-dxc shell: sh @@ -19,7 +21,8 @@ jobs: name: HLSL via FXC runs-on: windows-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 + - name: Add fxc bin to PATH run: | Get-Childitem -Path "C:\Program Files (x86)\Windows Kits\10\bin\**\x64\fxc.exe" ` @@ -28,5 +31,6 @@ jobs: | Split-Path -Parent ` | Out-File -FilePath $Env:GITHUB_PATH -Encoding utf8 -Append shell: powershell + - run: make validate-hlsl-fxc shell: sh \ No newline at end of file From 0a2e93c0985f72829117859f188a6fac15af0864 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 3 Feb 2023 14:33:28 +0000 Subject: [PATCH 1935/2212] glsl-in: Perform output parameters implicit casts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Glsl defines under `Function Definitions` (Paragraph 6.1 in glsl 4.60), the following: > When function calls are resolved, an exact type match for all > the arguments is sought. > (...) > If no exact match is found, then the implicit conversions in > section “Implicit Conversions” will be applied to find a match. > (...) > Mismatched types on output parameters (out or inout) must have a > conversion from the formal parameter type to the calling argument type. The glsl frontend wasn't performing this implicit cast for output parameters. This commit fixes that by using a proxy write, this creates a spill variable with the correct type and in the call prologue a conversion is made back to the original type and the value is stored in the original variable. --- src/front/glsl/functions.rs | 354 +++++++++++++++++++++++------------- 1 file changed, 232 insertions(+), 122 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index df4de5e10..7c6408674 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -13,6 +13,16 @@ use crate::{ }; use std::iter; +/// Struct detailing a store operation that must happen after a function call +struct ProxyWrite { + /// The store target + target: Handle, + /// A pointer to read the value of the store + value: Handle, + /// An optional conversion to be applied + convert: Option<(ScalarKind, crate::Bytes)>, +} + impl Frontend { fn add_constant_value( &mut self, @@ -630,13 +640,15 @@ impl Frontend { // Iterate over all the available overloads to select either an exact match or a // overload which has suitable implicit conversions - 'outer: for overload in declaration.overloads.iter() { + 'outer: for (overload_idx, overload) in declaration.overloads.iter().enumerate() { // If the overload and the function call don't have the same number of arguments // continue to the next overload if args.len() != overload.parameters.len() { continue; } + log::trace!("Testing overload {}", overload_idx); + // Stores whether the current overload matches exactly the function call let mut exact = true; // State of the selection @@ -737,15 +749,32 @@ impl Frontend { continue; } - // If the argument is to be passed as a pointer (i.e. either `out` or - // `inout` where used as qualifiers) no conversion shall be performed - if parameter_info.qualifier.is_lhs() { + // Glsl defines that inout follows both the conversions for input parameters and + // output parameters, this means that the type must have a conversion from both the + // call argument to the function parameter and the function parameter to the call + // argument, the only way this is possible is for the conversion to be an identity + // (i.e. call argument = function parameter) + if let ParameterQualifier::InOut = parameter_info.qualifier { continue 'outer; } - // Try to get the type of conversion needed otherwise this overload can't be used - // since no conversion makes it possible so skip it - let conversion = match conversion(overload_param_ty, call_arg_ty) { + // The function call argument and the function definition + // parameter are not equal at this point, so we need to try + // implicit conversions. + // + // Now there are two cases, the argument is defined as a normal + // parameter (`in` or `const`), in this case an implicit + // conversion is made from the calling argument to the + // definition argument. If the parameter is `out` the + // opposite needs to be done, so the implicit conversion is made + // from the definition argument to the calling argument. + let maybe_conversion = if parameter_info.qualifier.is_lhs() { + conversion(call_arg_ty, overload_param_ty) + } else { + conversion(overload_param_ty, call_arg_ty) + }; + + let conversion = match maybe_conversion { Some(info) => info, None => continue 'outer, }; @@ -845,130 +874,37 @@ impl Frontend { let mut arguments = Vec::with_capacity(args.len()); let mut proxy_writes = Vec::new(); + // Iterate trough the function call arguments applying transformations as needed - for (parameter_info, (expr, parameter)) in parameters_info + for (((parameter_info, call_argument), expr), parameter) in parameters_info .iter() - .zip(raw_args.iter().zip(parameters.iter())) + .zip(&args) + .zip(raw_args) + .zip(¶meters) { let (mut handle, meta) = ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.as_pos(), body)?; if parameter_info.qualifier.is_lhs() { - let (ty, value) = match *self.resolve_type(ctx, handle, meta)? { - // If the argument is to be passed as a pointer but the type of the - // expression returns a vector it must mean that it was for example - // swizzled and it must be spilled into a local before calling - TypeInner::Vector { size, kind, width } => ( - self.module.types.insert( - Type { - name: None, - inner: TypeInner::Vector { size, kind, width }, - }, - Span::default(), - ), - handle, - ), - // If the argument is a pointer whose address space isn't `Function`, an - // indirection through a local variable is needed to align the address - // spaces of the call argument and the overload parameter. - TypeInner::Pointer { base, space } if space != AddressSpace::Function => ( - base, - ctx.add_expression( - Expression::Load { pointer: handle }, - Span::default(), - body, - ), - ), - TypeInner::ValuePointer { - size, - kind, - width, - space, - } if space != AddressSpace::Function => { - let inner = match size { - Some(size) => TypeInner::Vector { size, kind, width }, - None => TypeInner::Scalar { kind, width }, - }; + self.process_lhs_argument( + ctx, + body, + meta, + *parameter, + parameter_info, + handle, + call_argument, + &mut proxy_writes, + &mut arguments, + )?; - ( - self.module - .types - .insert(Type { name: None, inner }, Span::default()), - ctx.add_expression( - Expression::Load { pointer: handle }, - Span::default(), - body, - ), - ) - } - _ => { - arguments.push(handle); - continue; - } - }; - - let temp_var = ctx.locals.append( - LocalVariable { - name: None, - ty, - init: None, - }, - Span::default(), - ); - let temp_expr = - ctx.add_expression(Expression::LocalVariable(temp_var), Span::default(), body); - - body.push( - Statement::Store { - pointer: temp_expr, - value, - }, - Span::default(), - ); - - arguments.push(temp_expr); - // Register the temporary local to be written back to it's original - // place after the function call - if let Expression::Swizzle { - size, - mut vector, - pattern, - } = ctx.expressions[value] - { - if let Expression::Load { pointer } = ctx.expressions[vector] { - vector = pointer; - } - - for (i, component) in pattern.iter().take(size as usize).enumerate() { - let original = ctx.add_expression( - Expression::AccessIndex { - base: vector, - index: *component as u32, - }, - Span::default(), - body, - ); - - let temp = ctx.add_expression( - Expression::AccessIndex { - base: temp_expr, - index: i as u32, - }, - Span::default(), - body, - ); - - proxy_writes.push((original, temp)); - } - } else { - proxy_writes.push((handle, temp_expr)); - } continue; } + let scalar_comps = scalar_components(&self.module.types[*parameter].inner); + // Apply implicit conversions as needed - let scalar_components = scalar_components(&self.module.types[*parameter].inner); - if let Some((kind, width)) = scalar_components { + if let Some((kind, width)) = scalar_comps { ctx.implicit_conversion(self, &mut handle, meta, kind, width)?; } @@ -997,14 +933,24 @@ impl Frontend { ctx.emit_start(); // Write back all the variables that were scheduled to their original place - for (original, pointer) in proxy_writes { - let value = ctx.add_expression(Expression::Load { pointer }, meta, body); + for proxy_write in proxy_writes { + let mut value = ctx.add_expression( + Expression::Load { + pointer: proxy_write.value, + }, + meta, + body, + ); + + if let Some((kind, width)) = proxy_write.convert { + ctx.conversion(&mut value, meta, kind, width)?; + } ctx.emit_restart(body); body.push( Statement::Store { - pointer: original, + pointer: proxy_write.target, value, }, meta, @@ -1019,6 +965,170 @@ impl Frontend { } } + /// Processes a function call argument that appears in place of an output + /// parameter. + #[allow(clippy::too_many_arguments)] + fn process_lhs_argument( + &mut self, + ctx: &mut Context, + body: &mut Block, + meta: Span, + parameter_ty: Handle, + parameter_info: &ParameterInfo, + original: Handle, + call_argument: &(Handle, Span), + proxy_writes: &mut Vec, + arguments: &mut Vec>, + ) -> Result<()> { + let original_ty = self.resolve_type(ctx, original, meta)?; + let original_pointer_space = original_ty.pointer_space(); + + // The type of a possible spill variable needed for a proxy write + let mut maybe_ty = match *original_ty { + // If the argument is to be passed as a pointer but the type of the + // expression returns a vector it must mean that it was for example + // swizzled and it must be spilled into a local before calling + TypeInner::Vector { size, kind, width } => Some(self.module.types.insert( + Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }, + Span::default(), + )), + // If the argument is a pointer whose address space isn't `Function`, an + // indirection through a local variable is needed to align the address + // spaces of the call argument and the overload parameter. + TypeInner::Pointer { base, space } if space != AddressSpace::Function => Some(base), + TypeInner::ValuePointer { + size, + kind, + width, + space, + } if space != AddressSpace::Function => { + let inner = match size { + Some(size) => TypeInner::Vector { size, kind, width }, + None => TypeInner::Scalar { kind, width }, + }; + + Some( + self.module + .types + .insert(Type { name: None, inner }, Span::default()), + ) + } + _ => None, + }; + + // Since the original expression might be a pointer and we want a value + // for the proxy writes, we might need to load the pointer. + let value = if original_pointer_space.is_some() { + ctx.add_expression( + Expression::Load { pointer: original }, + Span::default(), + body, + ) + } else { + original + }; + + let call_arg_ty = self.resolve_type(ctx, call_argument.0, call_argument.1)?; + let overload_param_ty = &self.module.types[parameter_ty].inner; + let needs_conversion = call_arg_ty != overload_param_ty; + + let arg_scalar_comps = scalar_components(call_arg_ty); + + // Since output parameters also allow implicit conversions from the + // parameter to the argument, we need to spill the conversion to a + // variable and create a proxy write for the original variable. + if needs_conversion { + maybe_ty = Some(parameter_ty); + } + + if let Some(ty) = maybe_ty { + // Create the spill variable + let spill_var = ctx.locals.append( + LocalVariable { + name: None, + ty, + init: None, + }, + Span::default(), + ); + let spill_expr = + ctx.add_expression(Expression::LocalVariable(spill_var), Span::default(), body); + + // If the argument is also copied in we must store the value of the + // original variable to the spill variable. + if let ParameterQualifier::InOut = parameter_info.qualifier { + body.push( + Statement::Store { + pointer: spill_expr, + value, + }, + Span::default(), + ); + } + + // Add the spill variable as an argument to the function call + arguments.push(spill_expr); + + let convert = if needs_conversion { + arg_scalar_comps + } else { + None + }; + + // Register the temporary local to be written back to it's original + // place after the function call + if let Expression::Swizzle { + size, + mut vector, + pattern, + } = ctx.expressions[original] + { + if let Expression::Load { pointer } = ctx.expressions[vector] { + vector = pointer; + } + + for (i, component) in pattern.iter().take(size as usize).enumerate() { + let original = ctx.add_expression( + Expression::AccessIndex { + base: vector, + index: *component as u32, + }, + Span::default(), + body, + ); + + let spill_component = ctx.add_expression( + Expression::AccessIndex { + base: spill_expr, + index: i as u32, + }, + Span::default(), + body, + ); + + proxy_writes.push(ProxyWrite { + target: original, + value: spill_component, + convert, + }); + } + } else { + proxy_writes.push(ProxyWrite { + target: original, + value: spill_expr, + convert, + }); + } + } else { + arguments.push(original); + } + + Ok(()) + } + pub(crate) fn add_function( &mut self, ctx: Context, From f038537e6190bbc5f8bbb15daf6d7e7737cde0d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Capucho?= Date: Fri, 3 Feb 2023 14:38:51 +0000 Subject: [PATCH 1936/2212] glsl-in: Add tests for output parameters casts --- tests/in/glsl/expressions.frag | 6 +++ tests/in/glsl/functions_call.frag | 21 ++++++++ tests/in/glsl/swizzle_write.frag | 11 ---- tests/out/wgsl/expressions-frag.wgsl | 24 +++++++++ tests/out/wgsl/functions_call-frag.wgsl | 68 +++++++++++++++++++++++++ tests/out/wgsl/swizzle_write-frag.wgsl | 42 --------------- 6 files changed, 119 insertions(+), 53 deletions(-) create mode 100644 tests/in/glsl/functions_call.frag delete mode 100644 tests/in/glsl/swizzle_write.frag create mode 100644 tests/out/wgsl/functions_call-frag.wgsl delete mode 100644 tests/out/wgsl/swizzle_write-frag.wgsl diff --git a/tests/in/glsl/expressions.frag b/tests/in/glsl/expressions.frag index e9f3c59f8..e1d9fe191 100644 --- a/tests/in/glsl/expressions.frag +++ b/tests/in/glsl/expressions.frag @@ -151,6 +151,12 @@ void indexConstantNonConstantIndex(int i) { const uvec4 a = strct.array[i]; } +void testSwizzleWrites(vec3 a) { + a.zxy.xy = vec2(3.0, 4.0); + a.rg *= 5.0; + a.zy++; +} + out vec4 o_color; void main() { privatePointer(global); diff --git a/tests/in/glsl/functions_call.frag b/tests/in/glsl/functions_call.frag new file mode 100644 index 000000000..74d9c2673 --- /dev/null +++ b/tests/in/glsl/functions_call.frag @@ -0,0 +1,21 @@ +#version 450 + +void swizzleCallee(inout vec2 a) {} + +void swizzleCaller(vec3 a) { + swizzleCallee(a.xz); +} + +void outImplicitCastCallee(out uint a) {} + +void outImplicitCastCaller(float a) { + outImplicitCastCallee(a); +} + +void swizzleImplicitCastCallee(out uvec2 a) {} + +void swizzleImplicitCastCaller(vec3 a) { + swizzleImplicitCastCallee(a.xz); +} + +void main() {} diff --git a/tests/in/glsl/swizzle_write.frag b/tests/in/glsl/swizzle_write.frag deleted file mode 100644 index c5a165590..000000000 --- a/tests/in/glsl/swizzle_write.frag +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 - -void foo(inout vec2 p) {} - -void main() { - vec3 x = vec3(2.0); - x.zxy.xy = vec2(3.0, 4.0); - x.rg *= 5.0; - x.zy++; - foo(x.xz); -} diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 0cad7bf31..0910cdfe2 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -414,6 +414,30 @@ fn indexConstantNonConstantIndex(i: i32) { return; } +fn testSwizzleWrites(a_27: vec3) { + var a_28: vec3; + + _ = (&global_1.a); + a_28 = a_27; + let _e6 = a_28; + _ = _e6.zxy; + _ = _e6.zx; + let _e11 = vec2(3.0, 4.0); + a_28.z = _e11.x; + a_28.x = _e11.y; + let _e16 = a_28; + _ = _e16.xy; + let _e18 = a_28; + let _e21 = (_e18.xy * 5.0); + a_28.x = _e21.x; + a_28.y = _e21.y; + let _e26 = a_28; + let _e30 = (_e26.zy + vec2(1.0)); + a_28.z = _e30.x; + a_28.y = _e30.y; + return; +} + fn main_1() { var local_6: f32; diff --git a/tests/out/wgsl/functions_call-frag.wgsl b/tests/out/wgsl/functions_call-frag.wgsl new file mode 100644 index 000000000..25615db22 --- /dev/null +++ b/tests/out/wgsl/functions_call-frag.wgsl @@ -0,0 +1,68 @@ +fn swizzleCallee(a: ptr>) { + return; +} + +fn swizzleCaller(a_1: vec3) { + var a_2: vec3; + var local: vec2; + + a_2 = a_1; + let _e2 = a_2; + _ = _e2.xz; + let _e4 = a_2; + local = _e4.xz; + swizzleCallee((&local)); + let _e11 = local.x; + a_2.x = _e11; + let _e12 = local.y; + a_2.z = _e12; + return; +} + +fn outImplicitCastCallee(a_3: ptr) { + return; +} + +fn outImplicitCastCaller(a_4: f32) { + var a_5: f32; + var local_1: u32; + + a_5 = a_4; + _ = a_5; + _ = a_5; + outImplicitCastCallee((&local_1)); + let _e5 = local_1; + a_5 = f32(_e5); + return; +} + +fn swizzleImplicitCastCallee(a_6: ptr>) { + return; +} + +fn swizzleImplicitCastCaller(a_7: vec3) { + var a_8: vec3; + var local_2: vec2; + + a_8 = a_7; + let _e2 = a_8; + _ = _e2.xz; + let _e4 = a_8; + _ = _e4.xz; + swizzleImplicitCastCallee((&local_2)); + let _e11 = local_2.x; + a_8.x = f32(_e11); + let _e13 = local_2.y; + a_8.z = f32(_e13); + return; +} + +fn main_1() { + return; +} + +@fragment +fn main() { + main_1(); + return; +} diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl deleted file mode 100644 index e6b29a58e..000000000 --- a/tests/out/wgsl/swizzle_write-frag.wgsl +++ /dev/null @@ -1,42 +0,0 @@ -fn foo(p: ptr>) { - return; -} - -fn main_1() { - var x: vec3; - var local: vec2; - - x = vec3(2.0); - let _e3 = x; - _ = _e3.zxy; - _ = _e3.zx; - let _e8 = vec2(3.0, 4.0); - x.z = _e8.x; - x.x = _e8.y; - let _e13 = x; - _ = _e13.xy; - let _e15 = x; - let _e18 = (_e15.xy * 5.0); - x.x = _e18.x; - x.y = _e18.y; - let _e23 = x; - let _e27 = (_e23.zy + vec2(1.0)); - x.z = _e27.x; - x.y = _e27.y; - let _e32 = x; - _ = _e32.xz; - let _e34 = x; - local = _e34.xz; - foo((&local)); - let _e41 = local.x; - x.x = _e41; - let _e42 = local.y; - x.z = _e42; - return; -} - -@fragment -fn main() { - main_1(); - return; -} From 40b8f661461d6aec0dfbd727586e39fbe295b528 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Fri, 10 Feb 2023 13:44:57 +0100 Subject: [PATCH 1937/2212] Fix `setup-dxc` not found and make sure workflows run if their file was changed (#2247) * fix setup-dxc not found * run validation-windows if its workflow file was changed * run validation-macos if its workflow file was changed * run validation-linux if its workflow file was changed * run lazy if its workflow file was changed --- .github/workflows/lazy.yml | 3 +++ .github/workflows/validation-linux.yml | 11 ++++++----- .github/workflows/validation-macos.yml | 3 ++- .github/workflows/validation-windows.yml | 5 +++-- 4 files changed, 14 insertions(+), 8 deletions(-) diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index 6bdb83c80..ab5e21f12 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -3,6 +3,9 @@ name: lazy on: push: branches: [master] + pull_request: + paths: + - '.github/workflows/lazy.yml' env: CARGO_INCREMENTAL: false diff --git a/.github/workflows/validation-linux.yml b/.github/workflows/validation-linux.yml index 8da38da7b..e253e0a42 100644 --- a/.github/workflows/validation-linux.yml +++ b/.github/workflows/validation-linux.yml @@ -2,11 +2,12 @@ name: validation-linux on: pull_request: paths: - - 'tests/out/spv/*.spvasm' - - 'tests/out/glsl/*.glsl' - - 'tests/out/dot/*.dot' - - 'tests/out/wgsl/*.wgsl' - - 'src/front/wgsl/*' + - '.github/workflows/validation-linux.yml' + - 'tests/out/spv/*.spvasm' + - 'tests/out/glsl/*.glsl' + - 'tests/out/dot/*.dot' + - 'tests/out/wgsl/*.wgsl' + - 'src/front/wgsl/*' jobs: validate-linux: diff --git a/.github/workflows/validation-macos.yml b/.github/workflows/validation-macos.yml index 2ec185ea0..535a0622b 100644 --- a/.github/workflows/validation-macos.yml +++ b/.github/workflows/validation-macos.yml @@ -2,7 +2,8 @@ name: validation-macos on: pull_request: paths: - - 'tests/out/msl/*.msl' + - '.github/workflows/validation-macos.yml' + - 'tests/out/msl/*.msl' jobs: validate-macos: diff --git a/.github/workflows/validation-windows.yml b/.github/workflows/validation-windows.yml index da6fe7065..03942a678 100644 --- a/.github/workflows/validation-windows.yml +++ b/.github/workflows/validation-windows.yml @@ -2,6 +2,7 @@ name: validation-windows on: pull_request: paths: + - '.github/workflows/validation-windows.yml' - 'tests/out/hlsl/*.hlsl' jobs: @@ -12,7 +13,7 @@ jobs: - uses: actions/checkout@v3 - name: Add DirectXShaderCompiler - uses: napokue/setup-dxc@v1.1 + uses: napokue/setup-dxc@v1.1.0 - run: make validate-hlsl-dxc shell: sh @@ -33,4 +34,4 @@ jobs: shell: powershell - run: make validate-hlsl-fxc - shell: sh \ No newline at end of file + shell: sh From 1ad47f732dc1d646cd13daea1059b687a1a90d24 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Mon, 13 Feb 2023 08:13:58 -0500 Subject: [PATCH 1938/2212] Fix texture built-ins where u32 was expected (#2245) - The Typifier was updated to expect `uint` - Both `glsl` and `spv` frontends where updated to cast the result to `sint`. - Both `glsl` and `spv` backends where updated to cast the result to `uint`. - Remove cast in `msl` backend. --- src/back/glsl/mod.rs | 12 + src/back/msl/writer.rs | 11 +- src/back/spv/image.rs | 122 +- src/front/glsl/builtins.rs | 12 +- src/front/spv/image.rs | 10 + src/front/wgsl/tests.rs | 6 +- src/proc/typifier.rs | 8 +- tests/in/binding-arrays.wgsl | 30 +- tests/in/image.wgsl | 6 +- tests/out/glsl/image.main.Compute.glsl | 4 +- tests/out/glsl/image.queries.Vertex.glsl | 28 +- .../glsl/variations-glsl.main.Fragment.glsl | 2 +- tests/out/hlsl/binding-arrays.hlsl | 68 +- tests/out/hlsl/image.hlsl | 98 +- tests/out/msl/binding-arrays.msl | 62 +- tests/out/msl/image.msl | 54 +- tests/out/spv/binding-arrays.spvasm | 1073 +++++++-------- tests/out/spv/image.spvasm | 626 ++++----- tests/out/wgsl/binding-arrays.wgsl | 62 +- tests/out/wgsl/image.wgsl | 4 +- tests/out/wgsl/images-frag.wgsl | 76 +- tests/out/wgsl/samplers-frag.wgsl | 1158 ++++++++--------- tests/spirv-capabilities.rs | 8 +- 23 files changed, 1836 insertions(+), 1704 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index aaed745f2..c9d11dc4b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2534,6 +2534,16 @@ impl<'a, W: Write> Writer<'a, W> { crate::ImageDimension::D3 => 3, crate::ImageDimension::Cube => 2, }; + + if let crate::ImageQuery::Size { .. } = query { + match components { + 1 => write!(self.out, "uint(")?, + _ => write!(self.out, "uvec{components}(")?, + } + } else { + write!(self.out, "uint(")?; + } + match query { crate::ImageQuery::Size { level } => { match class { @@ -2593,6 +2603,8 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")",)?; } } + + write!(self.out, ")")?; } // `Unary` is pretty straightforward // "-" - for `Negate` diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a4635ac2e..040541de4 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1453,24 +1453,21 @@ impl Writer { self.put_image_size_query( image, level.map(LevelOfDetail::Direct), - crate::ScalarKind::Sint, + crate::ScalarKind::Uint, context, )?; } crate::ImageQuery::NumLevels => { - write!(self.out, "int(")?; self.put_expression(image, context, false)?; - write!(self.out, ".get_num_mip_levels())")?; + write!(self.out, ".get_num_mip_levels()")?; } crate::ImageQuery::NumLayers => { - write!(self.out, "int(")?; self.put_expression(image, context, false)?; - write!(self.out, ".get_array_size())")?; + write!(self.out, ".get_array_size()")?; } crate::ImageQuery::NumSamples => { - write!(self.out, "int(")?; self.put_expression(image, context, false)?; - write!(self.out, ".get_num_samples())")?; + write!(self.out, ".get_num_samples()")?; } }, crate::Expression::Unary { op, expr } => { diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index bf2ce28f1..1a136af77 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -1032,21 +1032,19 @@ impl<'w> BlockContext<'w> { Id::D2 | Id::Cube => 2, Id::D3 => 3, }; - let extended_size_type_id = { - let array_coords = usize::from(arrayed); - let vector_size = match dim_coords + array_coords { - 2 => Some(crate::VectorSize::Bi), - 3 => Some(crate::VectorSize::Tri), - 4 => Some(crate::VectorSize::Quad), - _ => None, - }; - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size, - kind: crate::ScalarKind::Sint, - width: 4, - pointer_space: None, - })) + let array_coords = usize::from(arrayed); + let vector_size = match dim_coords + array_coords { + 2 => Some(crate::VectorSize::Bi), + 3 => Some(crate::VectorSize::Tri), + 4 => Some(crate::VectorSize::Quad), + _ => None, }; + let extended_size_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_space: None, + })); let (query_op, level_id) = match class { Ic::Sampled { multi: true, .. } @@ -1075,7 +1073,24 @@ impl<'w> BlockContext<'w> { } block.body.push(inst); - if result_type_id != extended_size_type_id { + let bitcast_type_id = self.get_type_id( + LocalType::Value { + vector_size, + kind: crate::ScalarKind::Uint, + width: 4, + pointer_space: None, + } + .into(), + ); + let bitcast_id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + bitcast_type_id, + bitcast_id, + id_extended, + )); + + if result_type_id != bitcast_type_id { let id = self.gen_id(); let components = match dim { // always pick the first component, and duplicate it for all 3 dimensions @@ -1085,23 +1100,41 @@ impl<'w> BlockContext<'w> { block.body.push(Instruction::vector_shuffle( result_type_id, id, - id_extended, - id_extended, + bitcast_id, + bitcast_id, components, )); + id } else { - id_extended + bitcast_id } } Iq::NumLevels => { - let id = self.gen_id(); + let query_id = self.gen_id(); block.body.push(Instruction::image_query( spirv::Op::ImageQueryLevels, - result_type_id, - id, + self.get_type_id( + LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_space: None, + } + .into(), + ), + query_id, image_id, )); + + let id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + result_type_id, + id, + query_id, + )); + id } Iq::NumLayers => { @@ -1125,23 +1158,58 @@ impl<'w> BlockContext<'w> { ); inst.add_operand(self.get_index_constant(0)); block.body.push(inst); - let id = self.gen_id(); + + let extract_id = self.gen_id(); block.body.push(Instruction::composite_extract( - result_type_id, - id, + self.get_type_id( + LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_space: None, + } + .into(), + ), + extract_id, id_extended, &[vec_size as u32 - 1], )); + + let id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + result_type_id, + id, + extract_id, + )); + id } Iq::NumSamples => { - let id = self.gen_id(); + let query_id = self.gen_id(); block.body.push(Instruction::image_query( spirv::Op::ImageQuerySamples, - result_type_id, - id, + self.get_type_id( + LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Sint, + width: 4, + pointer_space: None, + } + .into(), + ), + query_id, image_id, )); + + let id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + result_type_id, + id, + query_id, + )); + id } }; diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 4ff8add9a..5928e86c5 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1873,7 +1873,7 @@ impl MacroCall { name: None, inner: TypeInner::Vector { size, - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Uint, width: 4, }, }, @@ -1883,7 +1883,15 @@ impl MacroCall { expr = ctx.add_expression(Expression::Compose { components, ty }, meta, body) } - expr + ctx.add_expression( + Expression::As { + expr, + kind: Sk::Sint, + convert: Some(4), + }, + Span::default(), + body, + ) } MacroCall::ImageLoad { multi } => { let comps = diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 7a70b3339..757843f78 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -684,6 +684,11 @@ impl> super::Frontend { image: image_lexp.handle, query: crate::ImageQuery::Size { level }, }; + let expr = crate::Expression::As { + expr: ctx.expressions.append(expr, self.span_from_with_op(start)), + kind: crate::ScalarKind::Sint, + convert: Some(4), + }; self.lookup_expression.insert( result_id, LookupExpression { @@ -714,6 +719,11 @@ impl> super::Frontend { image: image_lexp.handle, query, }; + let expr = crate::Expression::As { + expr: expressions.append(expr, self.span_from_with_op(start)), + kind: crate::ScalarKind::Sint, + convert: Some(4), + }; self.lookup_expression.insert( result_id, LookupExpression { diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 73e843229..98d3f8dc9 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -357,10 +357,10 @@ fn parse_texture_query() { " var t: texture_multisampled_2d_array; fn foo() { - var dim: vec2 = textureDimensions(t); + var dim: vec2 = textureDimensions(t); dim = textureDimensions(t, 0); - let layers: i32 = textureNumLayers(t); - let samples: i32 = textureNumSamples(t); + let layers: u32 = textureNumLayers(t); + let samples: u32 = textureNumSamples(t); } ", ) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 64896ec41..cac32ebb7 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -525,17 +525,17 @@ impl<'a> ResolveContext<'a> { crate::ImageQuery::Size { level: _ } => match *past(image)?.inner_with(types) { Ti::Image { dim, .. } => match dim { crate::ImageDimension::D1 => Ti::Scalar { - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Uint, width: 4, }, crate::ImageDimension::D2 | crate::ImageDimension::Cube => Ti::Vector { size: crate::VectorSize::Bi, - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Uint, width: 4, }, crate::ImageDimension::D3 => Ti::Vector { size: crate::VectorSize::Tri, - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Uint, width: 4, }, }, @@ -547,7 +547,7 @@ impl<'a> ResolveContext<'a> { crate::ImageQuery::NumLevels | crate::ImageQuery::NumLayers | crate::ImageQuery::NumSamples => Ti::Scalar { - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Uint, width: 4, }, }), diff --git a/tests/in/binding-arrays.wgsl b/tests/in/binding-arrays.wgsl index 491621f51..d1bf1210d 100644 --- a/tests/in/binding-arrays.wgsl +++ b/tests/in/binding-arrays.wgsl @@ -30,8 +30,8 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { let uniform_index = uni.index; let non_uniform_index = fragment_in.index; - var i1 = 0; - var i2 = vec2(0); + var u1 = 0u; + var u2 = vec2(0u); var v1 = 0.0; var v4 = vec4(0.0); @@ -46,9 +46,9 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { let uv = vec2(0.0); let pix = vec2(0); - i2 += textureDimensions(texture_array_unbounded[0]); - i2 += textureDimensions(texture_array_unbounded[uniform_index]); - i2 += textureDimensions(texture_array_unbounded[non_uniform_index]); + u2 += textureDimensions(texture_array_unbounded[0]); + u2 += textureDimensions(texture_array_unbounded[uniform_index]); + u2 += textureDimensions(texture_array_unbounded[non_uniform_index]); v4 += textureGather(0, texture_array_bounded[0], samp[0], uv); v4 += textureGather(0, texture_array_bounded[uniform_index], samp[uniform_index], uv); @@ -62,17 +62,17 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { v4 += textureLoad(texture_array_unbounded[uniform_index], pix, 0); v4 += textureLoad(texture_array_unbounded[non_uniform_index], pix, 0); - i1 += textureNumLayers(texture_array_2darray[0]); - i1 += textureNumLayers(texture_array_2darray[uniform_index]); - i1 += textureNumLayers(texture_array_2darray[non_uniform_index]); + u1 += textureNumLayers(texture_array_2darray[0]); + u1 += textureNumLayers(texture_array_2darray[uniform_index]); + u1 += textureNumLayers(texture_array_2darray[non_uniform_index]); - i1 += textureNumLevels(texture_array_bounded[0]); - i1 += textureNumLevels(texture_array_bounded[uniform_index]); - i1 += textureNumLevels(texture_array_bounded[non_uniform_index]); + u1 += textureNumLevels(texture_array_bounded[0]); + u1 += textureNumLevels(texture_array_bounded[uniform_index]); + u1 += textureNumLevels(texture_array_bounded[non_uniform_index]); - i1 += textureNumSamples(texture_array_multisampled[0]); - i1 += textureNumSamples(texture_array_multisampled[uniform_index]); - i1 += textureNumSamples(texture_array_multisampled[non_uniform_index]); + u1 += textureNumSamples(texture_array_multisampled[0]); + u1 += textureNumSamples(texture_array_multisampled[uniform_index]); + u1 += textureNumSamples(texture_array_multisampled[non_uniform_index]); v4 += textureSample(texture_array_bounded[0], samp[0], uv); v4 += textureSample(texture_array_bounded[uniform_index], samp[uniform_index], uv); @@ -102,7 +102,7 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { textureStore(texture_array_storage[uniform_index], pix, v4); textureStore(texture_array_storage[non_uniform_index], pix, v4); - let v2 = vec2(i2 + vec2(i1)); + let v2 = vec2(u2 + vec2(u1)); return v4 + vec4(v2.x, v2.y, v2.x, v2.y) + v1; } diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index d668851be..b61b10164 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -18,7 +18,7 @@ var image_dst: texture_storage_1d; @compute @workgroup_size(16) fn main(@builtin(local_invocation_id) local_id: vec3) { let dim = textureDimensions(image_storage_src); - let itc = dim * vec2(local_id.xy) % vec2(10, 20); + let itc = vec2(dim * local_id.xy) % vec2(10, 20); // loads with ivec2 coords. let value1 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); let value2 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); @@ -39,8 +39,8 @@ fn main(@builtin(local_invocation_id) local_id: vec3) { @compute @workgroup_size(16, 1, 1) fn depth_load(@builtin(local_invocation_id) local_id: vec3) { - let dim: vec2 = textureDimensions(image_storage_src); - let itc: vec2 = ((dim * vec2(local_id.xy)) % vec2(10, 20)); + let dim: vec2 = textureDimensions(image_storage_src); + let itc: vec2 = (vec2(dim * local_id.xy) % vec2(10, 20)); let val: f32 = textureLoad(image_depth_multisampled_src, itc, i32(local_id.z)); textureStore(image_dst, itc.x, vec4(u32(val))); return; diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl index 8244b908d..b03b7ee9c 100644 --- a/tests/out/glsl/image.main.Compute.glsl +++ b/tests/out/glsl/image.main.Compute.glsl @@ -21,8 +21,8 @@ layout(r32ui) writeonly uniform highp uimage2D _group_0_binding_2_cs; void main() { uvec3 local_id = gl_LocalInvocationID; - ivec2 dim = imageSize(_group_0_binding_1_cs).xy; - ivec2 itc = ((dim * ivec2(local_id.xy)) % ivec2(10, 20)); + uvec2 dim = uvec2(imageSize(_group_0_binding_1_cs).xy); + ivec2 itc = (ivec2((dim * local_id.xy)) % ivec2(10, 20)); uvec4 value1_ = texelFetch(_group_0_binding_0_cs, itc, int(local_id.z)); uvec4 value2_ = texelFetch(_group_0_binding_3_cs, itc, int(local_id.z)); uvec4 value4_ = imageLoad(_group_0_binding_1_cs, itc); diff --git a/tests/out/glsl/image.queries.Vertex.glsl b/tests/out/glsl/image.queries.Vertex.glsl index d416c73cf..932a0a3bc 100644 --- a/tests/out/glsl/image.queries.Vertex.glsl +++ b/tests/out/glsl/image.queries.Vertex.glsl @@ -20,20 +20,20 @@ uniform highp sampler2DMS _group_0_binding_8_vs; void main() { - int dim_1d = textureSize(_group_0_binding_0_vs, 0).x; - int dim_1d_lod = textureSize(_group_0_binding_0_vs, int(dim_1d)).x; - ivec2 dim_2d = textureSize(_group_0_binding_1_vs, 0).xy; - ivec2 dim_2d_lod = textureSize(_group_0_binding_1_vs, 1).xy; - ivec2 dim_2d_array = textureSize(_group_0_binding_4_vs, 0).xy; - ivec2 dim_2d_array_lod = textureSize(_group_0_binding_4_vs, 1).xy; - ivec2 dim_cube = textureSize(_group_0_binding_5_vs, 0).xy; - ivec2 dim_cube_lod = textureSize(_group_0_binding_5_vs, 1).xy; - ivec2 dim_cube_array = textureSize(_group_0_binding_6_vs, 0).xy; - ivec2 dim_cube_array_lod = textureSize(_group_0_binding_6_vs, 1).xy; - ivec3 dim_3d = textureSize(_group_0_binding_7_vs, 0).xyz; - ivec3 dim_3d_lod = textureSize(_group_0_binding_7_vs, 1).xyz; - ivec2 dim_2s_ms = textureSize(_group_0_binding_8_vs).xy; - int sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); + uint dim_1d = uint(textureSize(_group_0_binding_0_vs, 0).x); + uint dim_1d_lod = uint(textureSize(_group_0_binding_0_vs, int(dim_1d)).x); + uvec2 dim_2d = uvec2(textureSize(_group_0_binding_1_vs, 0).xy); + uvec2 dim_2d_lod = uvec2(textureSize(_group_0_binding_1_vs, 1).xy); + uvec2 dim_2d_array = uvec2(textureSize(_group_0_binding_4_vs, 0).xy); + uvec2 dim_2d_array_lod = uvec2(textureSize(_group_0_binding_4_vs, 1).xy); + uvec2 dim_cube = uvec2(textureSize(_group_0_binding_5_vs, 0).xy); + uvec2 dim_cube_lod = uvec2(textureSize(_group_0_binding_5_vs, 1).xy); + uvec2 dim_cube_array = uvec2(textureSize(_group_0_binding_6_vs, 0).xy); + uvec2 dim_cube_array_lod = uvec2(textureSize(_group_0_binding_6_vs, 1).xy); + uvec3 dim_3d = uvec3(textureSize(_group_0_binding_7_vs, 0).xyz); + uvec3 dim_3d_lod = uvec3(textureSize(_group_0_binding_7_vs, 1).xyz); + uvec2 dim_2s_ms = uvec2(textureSize(_group_0_binding_8_vs).xy); + uint sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); gl_Position = vec4(float(sum)); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; diff --git a/tests/out/glsl/variations-glsl.main.Fragment.glsl b/tests/out/glsl/variations-glsl.main.Fragment.glsl index d42deaece..5ea3eb03c 100644 --- a/tests/out/glsl/variations-glsl.main.Fragment.glsl +++ b/tests/out/glsl/variations-glsl.main.Fragment.glsl @@ -9,7 +9,7 @@ uniform highp samplerCube _group_0_binding_0_fs; void main_1() { ivec2 sizeCube = ivec2(0); float a = 0.0; - sizeCube = textureSize(_group_0_binding_0_fs, 0).xy; + sizeCube = ivec2(uvec2(textureSize(_group_0_binding_0_fs, 0).xy)); a = ceil(1.0); return; } diff --git a/tests/out/hlsl/binding-arrays.hlsl b/tests/out/hlsl/binding-arrays.hlsl index b596ae28f..7784f2425 100644 --- a/tests/out/hlsl/binding-arrays.hlsl +++ b/tests/out/hlsl/binding-arrays.hlsl @@ -21,28 +21,28 @@ struct FragmentInput_main { nointerpolation uint index : LOC0; }; -int2 NagaDimensions2D(Texture2D tex) +uint2 NagaDimensions2D(Texture2D tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.xy; } -int NagaNumLayers2DArray(Texture2DArray tex) +uint NagaNumLayers2DArray(Texture2DArray tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int NagaNumLevels2D(Texture2D tex) +uint NagaNumLevels2D(Texture2D tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.z; } -int NagaMSNumSamples2D(Texture2DMS tex) +uint NagaMSNumSamples2D(Texture2DMS tex) { uint4 ret; tex.GetDimensions(ret.x, ret.y, ret.z); @@ -52,25 +52,25 @@ int NagaMSNumSamples2D(Texture2DMS tex) float4 main(FragmentInput_main fragmentinput_main) : SV_Target0 { FragmentIn fragment_in = { fragmentinput_main.index }; - int i1_ = (int)0; - int2 i2_ = (int2)0; + uint u1_ = (uint)0; + uint2 u2_ = (uint2)0; float v1_ = (float)0; float4 v4_ = (float4)0; uint uniform_index = uni.index; uint non_uniform_index = fragment_in.index; - i1_ = 0; - i2_ = (0).xx; + u1_ = 0u; + u2_ = (0u).xx; v1_ = 0.0; v4_ = (0.0).xxxx; float2 uv = (0.0).xx; int2 pix = (0).xx; - int2 _expr23 = i2_; - i2_ = (_expr23 + NagaDimensions2D(texture_array_unbounded[0])); - int2 _expr28 = i2_; - i2_ = (_expr28 + NagaDimensions2D(texture_array_unbounded[uniform_index])); - int2 _expr33 = i2_; - i2_ = (_expr33 + NagaDimensions2D(texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)])); + uint2 _expr23 = u2_; + u2_ = (_expr23 + NagaDimensions2D(texture_array_unbounded[0])); + uint2 _expr28 = u2_; + u2_ = (_expr28 + NagaDimensions2D(texture_array_unbounded[uniform_index])); + uint2 _expr33 = u2_; + u2_ = (_expr33 + NagaDimensions2D(texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)])); float4 _expr41 = texture_array_bounded[0].Gather(samp[0], uv); float4 _expr42 = v4_; v4_ = (_expr42 + _expr41); @@ -98,24 +98,24 @@ float4 main(FragmentInput_main fragmentinput_main) : SV_Target0 float4 _expr100 = texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)].Load(int3(pix, 0)); float4 _expr101 = v4_; v4_ = (_expr101 + _expr100); - int _expr107 = i1_; - i1_ = (_expr107 + NagaNumLayers2DArray(texture_array_2darray[0])); - int _expr112 = i1_; - i1_ = (_expr112 + NagaNumLayers2DArray(texture_array_2darray[uniform_index])); - int _expr117 = i1_; - i1_ = (_expr117 + NagaNumLayers2DArray(texture_array_2darray[NonUniformResourceIndex(non_uniform_index)])); - int _expr123 = i1_; - i1_ = (_expr123 + NagaNumLevels2D(texture_array_bounded[0])); - int _expr128 = i1_; - i1_ = (_expr128 + NagaNumLevels2D(texture_array_bounded[uniform_index])); - int _expr133 = i1_; - i1_ = (_expr133 + NagaNumLevels2D(texture_array_bounded[NonUniformResourceIndex(non_uniform_index)])); - int _expr139 = i1_; - i1_ = (_expr139 + NagaMSNumSamples2D(texture_array_multisampled[0])); - int _expr144 = i1_; - i1_ = (_expr144 + NagaMSNumSamples2D(texture_array_multisampled[uniform_index])); - int _expr149 = i1_; - i1_ = (_expr149 + NagaMSNumSamples2D(texture_array_multisampled[NonUniformResourceIndex(non_uniform_index)])); + uint _expr107 = u1_; + u1_ = (_expr107 + NagaNumLayers2DArray(texture_array_2darray[0])); + uint _expr112 = u1_; + u1_ = (_expr112 + NagaNumLayers2DArray(texture_array_2darray[uniform_index])); + uint _expr117 = u1_; + u1_ = (_expr117 + NagaNumLayers2DArray(texture_array_2darray[NonUniformResourceIndex(non_uniform_index)])); + uint _expr123 = u1_; + u1_ = (_expr123 + NagaNumLevels2D(texture_array_bounded[0])); + uint _expr128 = u1_; + u1_ = (_expr128 + NagaNumLevels2D(texture_array_bounded[uniform_index])); + uint _expr133 = u1_; + u1_ = (_expr133 + NagaNumLevels2D(texture_array_bounded[NonUniformResourceIndex(non_uniform_index)])); + uint _expr139 = u1_; + u1_ = (_expr139 + NagaMSNumSamples2D(texture_array_multisampled[0])); + uint _expr144 = u1_; + u1_ = (_expr144 + NagaMSNumSamples2D(texture_array_multisampled[uniform_index])); + uint _expr149 = u1_; + u1_ = (_expr149 + NagaMSNumSamples2D(texture_array_multisampled[NonUniformResourceIndex(non_uniform_index)])); float4 _expr157 = texture_array_bounded[0].Sample(samp[0], uv); float4 _expr158 = v4_; v4_ = (_expr158 + _expr157); @@ -176,8 +176,8 @@ float4 main(FragmentInput_main fragmentinput_main) : SV_Target0 texture_array_storage[uniform_index][pix] = _expr307; float4 _expr310 = v4_; texture_array_storage[NonUniformResourceIndex(non_uniform_index)][pix] = _expr310; - int2 _expr311 = i2_; - int _expr312 = i1_; + uint2 _expr311 = u2_; + uint _expr312 = u1_; float2 v2_ = float2((_expr311 + (_expr312).xx)); float4 _expr316 = v4_; float _expr323 = v1_; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 5ccec5b10..3d774fa73 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -21,7 +21,7 @@ SamplerComparisonState sampler_cmp : register(s1, space1); Texture2D image_2d_depth : register(t2, space1); TextureCube image_cube_depth : register(t3, space1); -int2 NagaRWDimensions2D(RWTexture2D tex) +uint2 NagaRWDimensions2D(RWTexture2D tex) { uint4 ret; tex.GetDimensions(ret.x, ret.y); @@ -31,8 +31,8 @@ int2 NagaRWDimensions2D(RWTexture2D tex) [numthreads(16, 1, 1)] void main(uint3 local_id : SV_GroupThreadID) { - int2 dim = NagaRWDimensions2D(image_storage_src); - int2 itc = ((dim * int2(local_id.xy)) % int2(10, 20)); + uint2 dim = NagaRWDimensions2D(image_storage_src); + int2 itc = (int2((dim * local_id.xy)) % int2(10, 20)); uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(local_id.z))); uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z)); uint4 value4_ = image_storage_src.Load(itc); @@ -51,98 +51,98 @@ void main(uint3 local_id : SV_GroupThreadID) [numthreads(16, 1, 1)] void depth_load(uint3 local_id_1 : SV_GroupThreadID) { - int2 dim_1 = NagaRWDimensions2D(image_storage_src); - int2 itc_1 = ((dim_1 * int2(local_id_1.xy)) % int2(10, 20)); + uint2 dim_1 = NagaRWDimensions2D(image_storage_src); + int2 itc_1 = (int2((dim_1 * local_id_1.xy)) % int2(10, 20)); float val = image_depth_multisampled_src.Load(itc_1, int(local_id_1.z)).x; image_dst[itc_1.x] = (uint(val)).xxxx; return; } -int NagaDimensions1D(Texture1D tex) +uint NagaDimensions1D(Texture1D tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y); return ret.x; } -int NagaMipDimensions1D(Texture1D tex, uint mip_level) +uint NagaMipDimensions1D(Texture1D tex, uint mip_level) { uint4 ret; tex.GetDimensions(mip_level, ret.x, ret.y); return ret.x; } -int2 NagaDimensions2D(Texture2D tex) +uint2 NagaDimensions2D(Texture2D tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.xy; } -int2 NagaMipDimensions2D(Texture2D tex, uint mip_level) +uint2 NagaMipDimensions2D(Texture2D tex, uint mip_level) { uint4 ret; tex.GetDimensions(mip_level, ret.x, ret.y, ret.z); return ret.xy; } -int2 NagaDimensions2DArray(Texture2DArray tex) +uint2 NagaDimensions2DArray(Texture2DArray tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int2 NagaMipDimensions2DArray(Texture2DArray tex, uint mip_level) +uint2 NagaMipDimensions2DArray(Texture2DArray tex, uint mip_level) { uint4 ret; tex.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int2 NagaDimensionsCube(TextureCube tex) +uint2 NagaDimensionsCube(TextureCube tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.xy; } -int2 NagaMipDimensionsCube(TextureCube tex, uint mip_level) +uint2 NagaMipDimensionsCube(TextureCube tex, uint mip_level) { uint4 ret; tex.GetDimensions(mip_level, ret.x, ret.y, ret.z); return ret.xy; } -int2 NagaDimensionsCubeArray(TextureCubeArray tex) +uint2 NagaDimensionsCubeArray(TextureCubeArray tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int2 NagaMipDimensionsCubeArray(TextureCubeArray tex, uint mip_level) +uint2 NagaMipDimensionsCubeArray(TextureCubeArray tex, uint mip_level) { uint4 ret; tex.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); return ret.xy; } -int3 NagaDimensions3D(Texture3D tex) +uint3 NagaDimensions3D(Texture3D tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.xyz; } -int3 NagaMipDimensions3D(Texture3D tex, uint mip_level) +uint3 NagaMipDimensions3D(Texture3D tex, uint mip_level) { uint4 ret; tex.GetDimensions(mip_level, ret.x, ret.y, ret.z, ret.w); return ret.xyz; } -int2 NagaMSDimensions2D(Texture2DMS tex) +uint2 NagaMSDimensions2D(Texture2DMS tex) { uint4 ret; tex.GetDimensions(ret.x, ret.y, ret.z); @@ -151,73 +151,73 @@ int2 NagaMSDimensions2D(Texture2DMS tex) float4 queries() : SV_Position { - int dim_1d = NagaDimensions1D(image_1d); - int dim_1d_lod = NagaMipDimensions1D(image_1d, int(dim_1d)); - int2 dim_2d = NagaDimensions2D(image_2d); - int2 dim_2d_lod = NagaMipDimensions2D(image_2d, 1); - int2 dim_2d_array = NagaDimensions2DArray(image_2d_array); - int2 dim_2d_array_lod = NagaMipDimensions2DArray(image_2d_array, 1); - int2 dim_cube = NagaDimensionsCube(image_cube); - int2 dim_cube_lod = NagaMipDimensionsCube(image_cube, 1); - int2 dim_cube_array = NagaDimensionsCubeArray(image_cube_array); - int2 dim_cube_array_lod = NagaMipDimensionsCubeArray(image_cube_array, 1); - int3 dim_3d = NagaDimensions3D(image_3d); - int3 dim_3d_lod = NagaMipDimensions3D(image_3d, 1); - int2 dim_2s_ms = NagaMSDimensions2D(image_aa); - int sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); + uint dim_1d = NagaDimensions1D(image_1d); + uint dim_1d_lod = NagaMipDimensions1D(image_1d, int(dim_1d)); + uint2 dim_2d = NagaDimensions2D(image_2d); + uint2 dim_2d_lod = NagaMipDimensions2D(image_2d, 1); + uint2 dim_2d_array = NagaDimensions2DArray(image_2d_array); + uint2 dim_2d_array_lod = NagaMipDimensions2DArray(image_2d_array, 1); + uint2 dim_cube = NagaDimensionsCube(image_cube); + uint2 dim_cube_lod = NagaMipDimensionsCube(image_cube, 1); + uint2 dim_cube_array = NagaDimensionsCubeArray(image_cube_array); + uint2 dim_cube_array_lod = NagaMipDimensionsCubeArray(image_cube_array, 1); + uint3 dim_3d = NagaDimensions3D(image_3d); + uint3 dim_3d_lod = NagaMipDimensions3D(image_3d, 1); + uint2 dim_2s_ms = NagaMSDimensions2D(image_aa); + uint sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); return (float(sum)).xxxx; } -int NagaNumLevels2D(Texture2D tex) +uint NagaNumLevels2D(Texture2D tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.z; } -int NagaNumLevels2DArray(Texture2DArray tex) +uint NagaNumLevels2DArray(Texture2DArray tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int NagaNumLayers2DArray(Texture2DArray tex) +uint NagaNumLayers2DArray(Texture2DArray tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int NagaNumLevelsCube(TextureCube tex) +uint NagaNumLevelsCube(TextureCube tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z); return ret.z; } -int NagaNumLevelsCubeArray(TextureCubeArray tex) +uint NagaNumLevelsCubeArray(TextureCubeArray tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int NagaNumLayersCubeArray(TextureCubeArray tex) +uint NagaNumLayersCubeArray(TextureCubeArray tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int NagaNumLevels3D(Texture3D tex) +uint NagaNumLevels3D(Texture3D tex) { uint4 ret; tex.GetDimensions(0, ret.x, ret.y, ret.z, ret.w); return ret.w; } -int NagaMSNumSamples2D(Texture2DMS tex) +uint NagaMSNumSamples2D(Texture2DMS tex) { uint4 ret; tex.GetDimensions(ret.x, ret.y, ret.z); @@ -226,15 +226,15 @@ int NagaMSNumSamples2D(Texture2DMS tex) float4 levels_queries() : SV_Position { - int num_levels_2d = NagaNumLevels2D(image_2d); - int num_levels_2d_array = NagaNumLevels2DArray(image_2d_array); - int num_layers_2d = NagaNumLayers2DArray(image_2d_array); - int num_levels_cube = NagaNumLevelsCube(image_cube); - int num_levels_cube_array = NagaNumLevelsCubeArray(image_cube_array); - int num_layers_cube = NagaNumLayersCubeArray(image_cube_array); - int num_levels_3d = NagaNumLevels3D(image_3d); - int num_samples_aa = NagaMSNumSamples2D(image_aa); - int sum_1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); + uint num_levels_2d = NagaNumLevels2D(image_2d); + uint num_levels_2d_array = NagaNumLevels2DArray(image_2d_array); + uint num_layers_2d = NagaNumLayers2DArray(image_2d_array); + uint num_levels_cube = NagaNumLevelsCube(image_cube); + uint num_levels_cube_array = NagaNumLevelsCubeArray(image_cube_array); + uint num_layers_cube = NagaNumLayersCubeArray(image_cube_array); + uint num_levels_3d = NagaNumLevels3D(image_3d); + uint num_samples_aa = NagaMSNumSamples2D(image_aa); + uint sum_1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); return (float(sum_1)).xxxx; } diff --git a/tests/out/msl/binding-arrays.msl b/tests/out/msl/binding-arrays.msl index d54fc9982..da1078b5d 100644 --- a/tests/out/msl/binding-arrays.msl +++ b/tests/out/msl/binding-arrays.msl @@ -36,24 +36,24 @@ fragment main_Output main_( , constant UniformIndex& uni [[user(fake0)]] ) { const FragmentIn fragment_in = { varyings.index }; - int i1_ = {}; - metal::int2 i2_ = {}; + uint u1_ = {}; + metal::uint2 u2_ = {}; float v1_ = {}; metal::float4 v4_ = {}; uint uniform_index = uni.index; uint non_uniform_index = fragment_in.index; - i1_ = 0; - i2_ = metal::int2(0); + u1_ = 0u; + u2_ = metal::uint2(0u); v1_ = 0.0; v4_ = metal::float4(0.0); metal::float2 uv = metal::float2(0.0); metal::int2 pix = metal::int2(0); - metal::int2 _e23 = i2_; - i2_ = _e23 + metal::int2(texture_array_unbounded[0].get_width(), texture_array_unbounded[0].get_height()); - metal::int2 _e28 = i2_; - i2_ = _e28 + metal::int2(texture_array_unbounded[uniform_index].get_width(), texture_array_unbounded[uniform_index].get_height()); - metal::int2 _e33 = i2_; - i2_ = _e33 + metal::int2(texture_array_unbounded[non_uniform_index].get_width(), texture_array_unbounded[non_uniform_index].get_height()); + metal::uint2 _e23 = u2_; + u2_ = _e23 + metal::uint2(texture_array_unbounded[0].get_width(), texture_array_unbounded[0].get_height()); + metal::uint2 _e28 = u2_; + u2_ = _e28 + metal::uint2(texture_array_unbounded[uniform_index].get_width(), texture_array_unbounded[uniform_index].get_height()); + metal::uint2 _e33 = u2_; + u2_ = _e33 + metal::uint2(texture_array_unbounded[non_uniform_index].get_width(), texture_array_unbounded[non_uniform_index].get_height()); metal::float4 _e41 = texture_array_bounded[0].gather(samp[0], uv); metal::float4 _e42 = v4_; v4_ = _e42 + _e41; @@ -81,24 +81,24 @@ fragment main_Output main_( metal::float4 _e100 = (uint(0) < texture_array_unbounded[non_uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[non_uniform_index].get_width(0), texture_array_unbounded[non_uniform_index].get_height(0))) ? texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); metal::float4 _e101 = v4_; v4_ = _e101 + _e100; - int _e107 = i1_; - i1_ = _e107 + int(texture_array_2darray[0].get_array_size()); - int _e112 = i1_; - i1_ = _e112 + int(texture_array_2darray[uniform_index].get_array_size()); - int _e117 = i1_; - i1_ = _e117 + int(texture_array_2darray[non_uniform_index].get_array_size()); - int _e123 = i1_; - i1_ = _e123 + int(texture_array_bounded[0].get_num_mip_levels()); - int _e128 = i1_; - i1_ = _e128 + int(texture_array_bounded[uniform_index].get_num_mip_levels()); - int _e133 = i1_; - i1_ = _e133 + int(texture_array_bounded[non_uniform_index].get_num_mip_levels()); - int _e139 = i1_; - i1_ = _e139 + int(texture_array_multisampled[0].get_num_samples()); - int _e144 = i1_; - i1_ = _e144 + int(texture_array_multisampled[uniform_index].get_num_samples()); - int _e149 = i1_; - i1_ = _e149 + int(texture_array_multisampled[non_uniform_index].get_num_samples()); + uint _e107 = u1_; + u1_ = _e107 + texture_array_2darray[0].get_array_size(); + uint _e112 = u1_; + u1_ = _e112 + texture_array_2darray[uniform_index].get_array_size(); + uint _e117 = u1_; + u1_ = _e117 + texture_array_2darray[non_uniform_index].get_array_size(); + uint _e123 = u1_; + u1_ = _e123 + texture_array_bounded[0].get_num_mip_levels(); + uint _e128 = u1_; + u1_ = _e128 + texture_array_bounded[uniform_index].get_num_mip_levels(); + uint _e133 = u1_; + u1_ = _e133 + texture_array_bounded[non_uniform_index].get_num_mip_levels(); + uint _e139 = u1_; + u1_ = _e139 + texture_array_multisampled[0].get_num_samples(); + uint _e144 = u1_; + u1_ = _e144 + texture_array_multisampled[uniform_index].get_num_samples(); + uint _e149 = u1_; + u1_ = _e149 + texture_array_multisampled[non_uniform_index].get_num_samples(); metal::float4 _e157 = texture_array_bounded[0].sample(samp[0], uv); metal::float4 _e158 = v4_; v4_ = _e158 + _e157; @@ -165,9 +165,9 @@ fragment main_Output main_( if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[non_uniform_index].get_width(), texture_array_storage[non_uniform_index].get_height()))) { texture_array_storage[non_uniform_index].write(_e310, metal::uint2(pix)); } - metal::int2 _e311 = i2_; - int _e312 = i1_; - metal::float2 v2_ = static_cast(_e311 + metal::int2(_e312)); + metal::uint2 _e311 = u2_; + uint _e312 = u1_; + metal::float2 v2_ = static_cast(_e311 + metal::uint2(_e312)); metal::float4 _e316 = v4_; float _e323 = v1_; return main_Output { (_e316 + metal::float4(v2_.x, v2_.y, v2_.x, v2_.y)) + metal::float4(_e323) }; diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 26675c684..b0de96238 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -17,8 +17,8 @@ kernel void main_( , metal::texture1d image_1d_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 dim = metal::int2(image_storage_src.get_width(), image_storage_src.get_height()); - metal::int2 itc = (dim * static_cast(local_id.xy)) % metal::int2(10, 20); + metal::uint2 dim = metal::uint2(image_storage_src.get_width(), image_storage_src.get_height()); + metal::int2 itc = static_cast(dim * local_id.xy) % metal::int2(10, 20); metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); @@ -43,8 +43,8 @@ kernel void depth_load( , metal::texture2d image_storage_src [[user(fake0)]] , metal::texture1d image_dst [[user(fake0)]] ) { - metal::int2 dim_1 = metal::int2(image_storage_src.get_width(), image_storage_src.get_height()); - metal::int2 itc_1 = (dim_1 * static_cast(local_id_1.xy)) % metal::int2(10, 20); + metal::uint2 dim_1 = metal::uint2(image_storage_src.get_width(), image_storage_src.get_height()); + metal::int2 itc_1 = static_cast(dim_1 * local_id_1.xy) % metal::int2(10, 20); float val = image_depth_multisampled_src.read(metal::uint2(itc_1), static_cast(local_id_1.z)); image_dst.write(metal::uint4(static_cast(val)), uint(itc_1.x)); return; @@ -63,20 +63,20 @@ vertex queriesOutput queries( , metal::texture3d image_3d [[user(fake0)]] , metal::texture2d_ms image_aa [[user(fake0)]] ) { - int dim_1d = int(image_1d.get_width()); - int dim_1d_lod = int(image_1d.get_width()); - metal::int2 dim_2d = metal::int2(image_2d.get_width(), image_2d.get_height()); - metal::int2 dim_2d_lod = metal::int2(image_2d.get_width(1), image_2d.get_height(1)); - metal::int2 dim_2d_array = metal::int2(image_2d_array.get_width(), image_2d_array.get_height()); - metal::int2 dim_2d_array_lod = metal::int2(image_2d_array.get_width(1), image_2d_array.get_height(1)); - metal::int2 dim_cube = metal::int2(image_cube.get_width()); - metal::int2 dim_cube_lod = metal::int2(image_cube.get_width(1)); - metal::int2 dim_cube_array = metal::int2(image_cube_array.get_width()); - metal::int2 dim_cube_array_lod = metal::int2(image_cube_array.get_width(1)); - metal::int3 dim_3d = metal::int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()); - metal::int3 dim_3d_lod = metal::int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)); - metal::int2 dim_2s_ms = metal::int2(image_aa.get_width(), image_aa.get_height()); - int sum = (((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z; + uint dim_1d = image_1d.get_width(); + uint dim_1d_lod = image_1d.get_width(); + metal::uint2 dim_2d = metal::uint2(image_2d.get_width(), image_2d.get_height()); + metal::uint2 dim_2d_lod = metal::uint2(image_2d.get_width(1), image_2d.get_height(1)); + metal::uint2 dim_2d_array = metal::uint2(image_2d_array.get_width(), image_2d_array.get_height()); + metal::uint2 dim_2d_array_lod = metal::uint2(image_2d_array.get_width(1), image_2d_array.get_height(1)); + metal::uint2 dim_cube = metal::uint2(image_cube.get_width()); + metal::uint2 dim_cube_lod = metal::uint2(image_cube.get_width(1)); + metal::uint2 dim_cube_array = metal::uint2(image_cube_array.get_width()); + metal::uint2 dim_cube_array_lod = metal::uint2(image_cube_array.get_width(1)); + metal::uint3 dim_3d = metal::uint3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()); + metal::uint3 dim_3d_lod = metal::uint3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)); + metal::uint2 dim_2s_ms = metal::uint2(image_aa.get_width(), image_aa.get_height()); + uint sum = (((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z; return queriesOutput { metal::float4(static_cast(sum)) }; } @@ -92,15 +92,15 @@ vertex levels_queriesOutput levels_queries( , metal::texture3d image_3d [[user(fake0)]] , metal::texture2d_ms image_aa [[user(fake0)]] ) { - int num_levels_2d = int(image_2d.get_num_mip_levels()); - int num_levels_2d_array = int(image_2d_array.get_num_mip_levels()); - int num_layers_2d = int(image_2d_array.get_array_size()); - int num_levels_cube = int(image_cube.get_num_mip_levels()); - int num_levels_cube_array = int(image_cube_array.get_num_mip_levels()); - int num_layers_cube = int(image_cube_array.get_array_size()); - int num_levels_3d = int(image_3d.get_num_mip_levels()); - int num_samples_aa = int(image_aa.get_num_samples()); - int sum_1 = ((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array; + uint num_levels_2d = image_2d.get_num_mip_levels(); + uint num_levels_2d_array = image_2d_array.get_num_mip_levels(); + uint num_layers_2d = image_2d_array.get_array_size(); + uint num_levels_cube = image_cube.get_num_mip_levels(); + uint num_levels_cube_array = image_cube_array.get_num_mip_levels(); + uint num_layers_cube = image_cube_array.get_array_size(); + uint num_levels_3d = image_3d.get_num_mip_levels(); + uint num_samples_aa = image_aa.get_num_samples(); + uint sum_1 = ((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array; return levels_queriesOutput { metal::float4(static_cast(sum_1)) }; } diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 4c7ad3d22..30cf4847c 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -1,561 +1,574 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 433 +; Bound: 446 OpCapability Shader OpCapability ImageQuery OpCapability ShaderNonUniform OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %68 "main" %63 %66 -OpExecutionMode %68 OriginUpperLeft -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %24 0 Offset 0 -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 0 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 1 +OpEntryPoint Fragment %70 "main" %65 %68 +OpExecutionMode %70 OriginUpperLeft +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %25 0 Offset 0 +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 0 OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 2 +OpDecorate %34 Binding 1 OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 3 +OpDecorate %36 Binding 2 OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 4 +OpDecorate %38 Binding 3 OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 5 +OpDecorate %40 Binding 4 OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 6 +OpDecorate %42 Binding 5 OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 7 +OpDecorate %44 Binding 6 OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 8 -OpDecorate %47 Block -OpMemberDecorate %47 0 Offset 0 -OpDecorate %63 Location 0 -OpDecorate %63 Flat -OpDecorate %66 Location 0 -OpDecorate %94 NonUniform -OpDecorate %117 NonUniform -OpDecorate %119 NonUniform -OpDecorate %144 NonUniform -OpDecorate %146 NonUniform -OpDecorate %184 NonUniform -OpDecorate %213 NonUniform -OpDecorate %229 NonUniform -OpDecorate %245 NonUniform -OpDecorate %266 NonUniform -OpDecorate %268 NonUniform -OpDecorate %290 NonUniform -OpDecorate %292 NonUniform -OpDecorate %314 NonUniform -OpDecorate %316 NonUniform -OpDecorate %338 NonUniform -OpDecorate %340 NonUniform -OpDecorate %362 NonUniform -OpDecorate %364 NonUniform -OpDecorate %386 NonUniform -OpDecorate %388 NonUniform -OpDecorate %411 NonUniform +OpDecorate %46 Binding 7 +OpDecorate %48 DescriptorSet 0 +OpDecorate %48 Binding 8 +OpDecorate %49 Block +OpMemberDecorate %49 0 Offset 0 +OpDecorate %65 Location 0 +OpDecorate %65 Flat +OpDecorate %68 Location 0 +OpDecorate %97 NonUniform +OpDecorate %121 NonUniform +OpDecorate %123 NonUniform +OpDecorate %148 NonUniform +OpDecorate %150 NonUniform +OpDecorate %188 NonUniform +OpDecorate %219 NonUniform +OpDecorate %238 NonUniform +OpDecorate %257 NonUniform +OpDecorate %279 NonUniform +OpDecorate %281 NonUniform +OpDecorate %303 NonUniform +OpDecorate %305 NonUniform +OpDecorate %327 NonUniform +OpDecorate %329 NonUniform +OpDecorate %351 NonUniform +OpDecorate %353 NonUniform +OpDecorate %375 NonUniform +OpDecorate %377 NonUniform +OpDecorate %399 NonUniform +OpDecorate %401 NonUniform +OpDecorate %424 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 5 -%5 = OpConstant %4 0 -%7 = OpTypeFloat 32 -%6 = OpConstant %7 0.0 -%8 = OpTypeInt 32 0 -%9 = OpTypeStruct %8 -%10 = OpTypeImage %7 2D 0 0 0 1 Unknown -%11 = OpTypeRuntimeArray %10 -%12 = OpTypeArray %10 %3 -%13 = OpTypeImage %7 2D 0 1 0 1 Unknown -%14 = OpTypeArray %13 %3 -%15 = OpTypeImage %7 2D 0 0 1 1 Unknown -%16 = OpTypeArray %15 %3 -%17 = OpTypeImage %7 2D 1 0 0 1 Unknown -%18 = OpTypeArray %17 %3 -%19 = OpTypeImage %7 2D 0 0 0 2 Rgba32f -%20 = OpTypeArray %19 %3 -%21 = OpTypeSampler -%22 = OpTypeArray %21 %3 -%23 = OpTypeArray %21 %3 -%24 = OpTypeStruct %8 -%25 = OpTypeVector %7 4 -%26 = OpTypeVector %4 2 -%27 = OpTypeVector %7 2 -%31 = OpConstant %8 10 -%30 = OpTypeArray %10 %31 -%29 = OpTypePointer UniformConstant %30 -%28 = OpVariable %29 UniformConstant -%33 = OpTypePointer UniformConstant %12 -%32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %14 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 0 +%8 = OpTypeFloat 32 +%7 = OpConstant %8 0.0 +%9 = OpConstant %4 0 +%10 = OpTypeStruct %6 +%11 = OpTypeImage %8 2D 0 0 0 1 Unknown +%12 = OpTypeRuntimeArray %11 +%13 = OpTypeArray %11 %3 +%14 = OpTypeImage %8 2D 0 1 0 1 Unknown +%15 = OpTypeArray %14 %3 +%16 = OpTypeImage %8 2D 0 0 1 1 Unknown +%17 = OpTypeArray %16 %3 +%18 = OpTypeImage %8 2D 1 0 0 1 Unknown +%19 = OpTypeArray %18 %3 +%20 = OpTypeImage %8 2D 0 0 0 2 Rgba32f +%21 = OpTypeArray %20 %3 +%22 = OpTypeSampler +%23 = OpTypeArray %22 %3 +%24 = OpTypeArray %22 %3 +%25 = OpTypeStruct %6 +%26 = OpTypeVector %8 4 +%27 = OpTypeVector %6 2 +%28 = OpTypeVector %8 2 +%29 = OpTypeVector %4 2 +%33 = OpConstant %6 10 +%32 = OpTypeArray %11 %33 +%31 = OpTypePointer UniformConstant %32 +%30 = OpVariable %31 UniformConstant +%35 = OpTypePointer UniformConstant %13 %34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %16 +%37 = OpTypePointer UniformConstant %15 %36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %18 +%39 = OpTypePointer UniformConstant %17 %38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %20 +%41 = OpTypePointer UniformConstant %19 %40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %22 +%43 = OpTypePointer UniformConstant %21 %42 = OpVariable %43 UniformConstant %45 = OpTypePointer UniformConstant %23 %44 = OpVariable %45 UniformConstant -%47 = OpTypeStruct %9 -%48 = OpTypePointer Uniform %47 -%46 = OpVariable %48 Uniform -%50 = OpTypePointer Function %4 -%51 = OpConstantNull %4 -%53 = OpTypePointer Function %26 -%54 = OpConstantNull %26 -%56 = OpTypePointer Function %7 -%57 = OpConstantNull %7 -%59 = OpTypePointer Function %25 -%60 = OpConstantNull %25 -%64 = OpTypePointer Input %8 -%63 = OpVariable %64 Input -%67 = OpTypePointer Output %25 -%66 = OpVariable %67 Output -%69 = OpTypeFunction %2 -%70 = OpTypePointer Uniform %9 -%71 = OpConstant %8 0 -%74 = OpTypePointer Uniform %8 -%82 = OpTypePointer UniformConstant %10 -%100 = OpTypePointer UniformConstant %21 -%103 = OpTypeSampledImage %10 -%124 = OpTypePointer UniformConstant %17 -%127 = OpTypePointer UniformConstant %21 -%130 = OpTypeSampledImage %17 -%153 = OpTypeBool -%154 = OpConstantNull %25 -%160 = OpTypeVector %153 2 -%170 = OpConstantNull %25 -%185 = OpConstantNull %25 -%198 = OpTypePointer UniformConstant %13 -%201 = OpTypeVector %4 3 -%233 = OpTypePointer UniformConstant %15 -%393 = OpTypePointer UniformConstant %19 -%68 = OpFunction %2 None %69 -%61 = OpLabel -%52 = OpVariable %53 Function %54 -%58 = OpVariable %59 Function %60 -%49 = OpVariable %50 Function %51 -%55 = OpVariable %56 Function %57 -%65 = OpLoad %8 %63 -%62 = OpCompositeConstruct %24 %65 -%72 = OpAccessChain %70 %46 %71 -OpBranch %73 -%73 = OpLabel -%75 = OpAccessChain %74 %72 %71 -%76 = OpLoad %8 %75 -%77 = OpCompositeExtract %8 %62 0 -OpStore %49 %5 -%78 = OpCompositeConstruct %26 %5 %5 -OpStore %52 %78 -OpStore %55 %6 -%79 = OpCompositeConstruct %25 %6 %6 %6 %6 -OpStore %58 %79 -%80 = OpCompositeConstruct %27 %6 %6 -%81 = OpCompositeConstruct %26 %5 %5 -%83 = OpAccessChain %82 %28 %71 -%84 = OpLoad %10 %83 -%85 = OpImageQuerySizeLod %26 %84 %71 -%86 = OpLoad %26 %52 -%87 = OpIAdd %26 %86 %85 -OpStore %52 %87 -%88 = OpAccessChain %82 %28 %76 -%89 = OpLoad %10 %88 -%90 = OpImageQuerySizeLod %26 %89 %71 -%91 = OpLoad %26 %52 -%92 = OpIAdd %26 %91 %90 -OpStore %52 %92 -%93 = OpAccessChain %82 %28 %77 -%94 = OpLoad %10 %93 -%95 = OpImageQuerySizeLod %26 %94 %71 -%96 = OpLoad %26 %52 -%97 = OpIAdd %26 %96 %95 -OpStore %52 %97 -%98 = OpAccessChain %82 %32 %71 -%99 = OpLoad %10 %98 -%101 = OpAccessChain %100 %42 %71 -%102 = OpLoad %21 %101 -%104 = OpSampledImage %103 %99 %102 -%105 = OpImageGather %25 %104 %80 %71 -%106 = OpLoad %25 %58 -%107 = OpFAdd %25 %106 %105 -OpStore %58 %107 -%108 = OpAccessChain %82 %32 %76 -%109 = OpLoad %10 %108 -%110 = OpAccessChain %100 %42 %76 -%111 = OpLoad %21 %110 -%112 = OpSampledImage %103 %109 %111 -%113 = OpImageGather %25 %112 %80 %71 -%114 = OpLoad %25 %58 -%115 = OpFAdd %25 %114 %113 -OpStore %58 %115 -%116 = OpAccessChain %82 %32 %77 -%117 = OpLoad %10 %116 -%118 = OpAccessChain %100 %42 %77 -%119 = OpLoad %21 %118 -%120 = OpSampledImage %103 %117 %119 -%121 = OpImageGather %25 %120 %80 %71 -%122 = OpLoad %25 %58 -%123 = OpFAdd %25 %122 %121 -OpStore %58 %123 -%125 = OpAccessChain %124 %38 %71 -%126 = OpLoad %17 %125 -%128 = OpAccessChain %127 %44 %71 -%129 = OpLoad %21 %128 -%131 = OpSampledImage %130 %126 %129 -%132 = OpImageDrefGather %25 %131 %80 %6 -%133 = OpLoad %25 %58 -%134 = OpFAdd %25 %133 %132 -OpStore %58 %134 -%135 = OpAccessChain %124 %38 %76 -%136 = OpLoad %17 %135 -%137 = OpAccessChain %127 %44 %76 -%138 = OpLoad %21 %137 -%139 = OpSampledImage %130 %136 %138 -%140 = OpImageDrefGather %25 %139 %80 %6 -%141 = OpLoad %25 %58 -%142 = OpFAdd %25 %141 %140 -OpStore %58 %142 -%143 = OpAccessChain %124 %38 %77 -%144 = OpLoad %17 %143 -%145 = OpAccessChain %127 %44 %77 -%146 = OpLoad %21 %145 -%147 = OpSampledImage %130 %144 %146 -%148 = OpImageDrefGather %25 %147 %80 %6 -%149 = OpLoad %25 %58 -%150 = OpFAdd %25 %149 %148 -OpStore %58 %150 -%151 = OpAccessChain %82 %28 %71 -%152 = OpLoad %10 %151 -%155 = OpImageQueryLevels %4 %152 -%156 = OpULessThan %153 %5 %155 -OpSelectionMerge %157 None -OpBranchConditional %156 %158 %157 -%158 = OpLabel -%159 = OpImageQuerySizeLod %26 %152 %5 -%161 = OpULessThan %160 %81 %159 -%162 = OpAll %153 %161 -OpBranchConditional %162 %163 %157 -%163 = OpLabel -%164 = OpImageFetch %25 %152 %81 Lod %5 -OpBranch %157 -%157 = OpLabel -%165 = OpPhi %25 %154 %73 %154 %158 %164 %163 -%166 = OpLoad %25 %58 -%167 = OpFAdd %25 %166 %165 -OpStore %58 %167 -%168 = OpAccessChain %82 %28 %76 -%169 = OpLoad %10 %168 -%171 = OpImageQueryLevels %4 %169 -%172 = OpULessThan %153 %5 %171 -OpSelectionMerge %173 None -OpBranchConditional %172 %174 %173 -%174 = OpLabel -%175 = OpImageQuerySizeLod %26 %169 %5 -%176 = OpULessThan %160 %81 %175 -%177 = OpAll %153 %176 -OpBranchConditional %177 %178 %173 +%47 = OpTypePointer UniformConstant %24 +%46 = OpVariable %47 UniformConstant +%49 = OpTypeStruct %10 +%50 = OpTypePointer Uniform %49 +%48 = OpVariable %50 Uniform +%52 = OpTypePointer Function %6 +%53 = OpConstantNull %6 +%55 = OpTypePointer Function %27 +%56 = OpConstantNull %27 +%58 = OpTypePointer Function %8 +%59 = OpConstantNull %8 +%61 = OpTypePointer Function %26 +%62 = OpConstantNull %26 +%66 = OpTypePointer Input %6 +%65 = OpVariable %66 Input +%69 = OpTypePointer Output %26 +%68 = OpVariable %69 Output +%71 = OpTypeFunction %2 +%72 = OpTypePointer Uniform %10 +%75 = OpTypePointer Uniform %6 +%83 = OpTypePointer UniformConstant %11 +%104 = OpTypePointer UniformConstant %22 +%107 = OpTypeSampledImage %11 +%128 = OpTypePointer UniformConstant %18 +%131 = OpTypePointer UniformConstant %22 +%134 = OpTypeSampledImage %18 +%157 = OpTypeBool +%158 = OpConstantNull %26 +%164 = OpTypeVector %157 2 +%174 = OpConstantNull %26 +%189 = OpConstantNull %26 +%202 = OpTypePointer UniformConstant %14 +%205 = OpTypeVector %4 3 +%243 = OpTypePointer UniformConstant %16 +%406 = OpTypePointer UniformConstant %20 +%70 = OpFunction %2 None %71 +%63 = OpLabel +%54 = OpVariable %55 Function %56 +%60 = OpVariable %61 Function %62 +%51 = OpVariable %52 Function %53 +%57 = OpVariable %58 Function %59 +%67 = OpLoad %6 %65 +%64 = OpCompositeConstruct %25 %67 +%73 = OpAccessChain %72 %48 %5 +OpBranch %74 +%74 = OpLabel +%76 = OpAccessChain %75 %73 %5 +%77 = OpLoad %6 %76 +%78 = OpCompositeExtract %6 %64 0 +OpStore %51 %5 +%79 = OpCompositeConstruct %27 %5 %5 +OpStore %54 %79 +OpStore %57 %7 +%80 = OpCompositeConstruct %26 %7 %7 %7 %7 +OpStore %60 %80 +%81 = OpCompositeConstruct %28 %7 %7 +%82 = OpCompositeConstruct %29 %9 %9 +%84 = OpAccessChain %83 %30 %5 +%85 = OpLoad %11 %84 +%86 = OpImageQuerySizeLod %29 %85 %5 +%87 = OpBitcast %27 %86 +%88 = OpLoad %27 %54 +%89 = OpIAdd %27 %88 %87 +OpStore %54 %89 +%90 = OpAccessChain %83 %30 %77 +%91 = OpLoad %11 %90 +%92 = OpImageQuerySizeLod %29 %91 %5 +%93 = OpBitcast %27 %92 +%94 = OpLoad %27 %54 +%95 = OpIAdd %27 %94 %93 +OpStore %54 %95 +%96 = OpAccessChain %83 %30 %78 +%97 = OpLoad %11 %96 +%98 = OpImageQuerySizeLod %29 %97 %5 +%99 = OpBitcast %27 %98 +%100 = OpLoad %27 %54 +%101 = OpIAdd %27 %100 %99 +OpStore %54 %101 +%102 = OpAccessChain %83 %34 %5 +%103 = OpLoad %11 %102 +%105 = OpAccessChain %104 %44 %5 +%106 = OpLoad %22 %105 +%108 = OpSampledImage %107 %103 %106 +%109 = OpImageGather %26 %108 %81 %5 +%110 = OpLoad %26 %60 +%111 = OpFAdd %26 %110 %109 +OpStore %60 %111 +%112 = OpAccessChain %83 %34 %77 +%113 = OpLoad %11 %112 +%114 = OpAccessChain %104 %44 %77 +%115 = OpLoad %22 %114 +%116 = OpSampledImage %107 %113 %115 +%117 = OpImageGather %26 %116 %81 %5 +%118 = OpLoad %26 %60 +%119 = OpFAdd %26 %118 %117 +OpStore %60 %119 +%120 = OpAccessChain %83 %34 %78 +%121 = OpLoad %11 %120 +%122 = OpAccessChain %104 %44 %78 +%123 = OpLoad %22 %122 +%124 = OpSampledImage %107 %121 %123 +%125 = OpImageGather %26 %124 %81 %5 +%126 = OpLoad %26 %60 +%127 = OpFAdd %26 %126 %125 +OpStore %60 %127 +%129 = OpAccessChain %128 %40 %5 +%130 = OpLoad %18 %129 +%132 = OpAccessChain %131 %46 %5 +%133 = OpLoad %22 %132 +%135 = OpSampledImage %134 %130 %133 +%136 = OpImageDrefGather %26 %135 %81 %7 +%137 = OpLoad %26 %60 +%138 = OpFAdd %26 %137 %136 +OpStore %60 %138 +%139 = OpAccessChain %128 %40 %77 +%140 = OpLoad %18 %139 +%141 = OpAccessChain %131 %46 %77 +%142 = OpLoad %22 %141 +%143 = OpSampledImage %134 %140 %142 +%144 = OpImageDrefGather %26 %143 %81 %7 +%145 = OpLoad %26 %60 +%146 = OpFAdd %26 %145 %144 +OpStore %60 %146 +%147 = OpAccessChain %128 %40 %78 +%148 = OpLoad %18 %147 +%149 = OpAccessChain %131 %46 %78 +%150 = OpLoad %22 %149 +%151 = OpSampledImage %134 %148 %150 +%152 = OpImageDrefGather %26 %151 %81 %7 +%153 = OpLoad %26 %60 +%154 = OpFAdd %26 %153 %152 +OpStore %60 %154 +%155 = OpAccessChain %83 %30 %5 +%156 = OpLoad %11 %155 +%159 = OpImageQueryLevels %4 %156 +%160 = OpULessThan %157 %9 %159 +OpSelectionMerge %161 None +OpBranchConditional %160 %162 %161 +%162 = OpLabel +%163 = OpImageQuerySizeLod %29 %156 %9 +%165 = OpULessThan %164 %82 %163 +%166 = OpAll %157 %165 +OpBranchConditional %166 %167 %161 +%167 = OpLabel +%168 = OpImageFetch %26 %156 %82 Lod %9 +OpBranch %161 +%161 = OpLabel +%169 = OpPhi %26 %158 %74 %158 %162 %168 %167 +%170 = OpLoad %26 %60 +%171 = OpFAdd %26 %170 %169 +OpStore %60 %171 +%172 = OpAccessChain %83 %30 %77 +%173 = OpLoad %11 %172 +%175 = OpImageQueryLevels %4 %173 +%176 = OpULessThan %157 %9 %175 +OpSelectionMerge %177 None +OpBranchConditional %176 %178 %177 %178 = OpLabel -%179 = OpImageFetch %25 %169 %81 Lod %5 -OpBranch %173 -%173 = OpLabel -%180 = OpPhi %25 %170 %157 %170 %174 %179 %178 -%181 = OpLoad %25 %58 -%182 = OpFAdd %25 %181 %180 -OpStore %58 %182 -%183 = OpAccessChain %82 %28 %77 -%184 = OpLoad %10 %183 -%186 = OpImageQueryLevels %4 %184 -%187 = OpULessThan %153 %5 %186 -OpSelectionMerge %188 None -OpBranchConditional %187 %189 %188 -%189 = OpLabel -%190 = OpImageQuerySizeLod %26 %184 %5 -%191 = OpULessThan %160 %81 %190 -%192 = OpAll %153 %191 -OpBranchConditional %192 %193 %188 +%179 = OpImageQuerySizeLod %29 %173 %9 +%180 = OpULessThan %164 %82 %179 +%181 = OpAll %157 %180 +OpBranchConditional %181 %182 %177 +%182 = OpLabel +%183 = OpImageFetch %26 %173 %82 Lod %9 +OpBranch %177 +%177 = OpLabel +%184 = OpPhi %26 %174 %161 %174 %178 %183 %182 +%185 = OpLoad %26 %60 +%186 = OpFAdd %26 %185 %184 +OpStore %60 %186 +%187 = OpAccessChain %83 %30 %78 +%188 = OpLoad %11 %187 +%190 = OpImageQueryLevels %4 %188 +%191 = OpULessThan %157 %9 %190 +OpSelectionMerge %192 None +OpBranchConditional %191 %193 %192 %193 = OpLabel -%194 = OpImageFetch %25 %184 %81 Lod %5 -OpBranch %188 -%188 = OpLabel -%195 = OpPhi %25 %185 %173 %185 %189 %194 %193 -%196 = OpLoad %25 %58 -%197 = OpFAdd %25 %196 %195 -OpStore %58 %197 -%199 = OpAccessChain %198 %34 %71 -%200 = OpLoad %13 %199 -%202 = OpImageQuerySizeLod %201 %200 %71 -%203 = OpCompositeExtract %4 %202 2 -%204 = OpLoad %4 %49 -%205 = OpIAdd %4 %204 %203 -OpStore %49 %205 -%206 = OpAccessChain %198 %34 %76 -%207 = OpLoad %13 %206 -%208 = OpImageQuerySizeLod %201 %207 %71 -%209 = OpCompositeExtract %4 %208 2 -%210 = OpLoad %4 %49 -%211 = OpIAdd %4 %210 %209 -OpStore %49 %211 -%212 = OpAccessChain %198 %34 %77 -%213 = OpLoad %13 %212 -%214 = OpImageQuerySizeLod %201 %213 %71 -%215 = OpCompositeExtract %4 %214 2 -%216 = OpLoad %4 %49 -%217 = OpIAdd %4 %216 %215 -OpStore %49 %217 -%218 = OpAccessChain %82 %32 %71 -%219 = OpLoad %10 %218 -%220 = OpImageQueryLevels %4 %219 -%221 = OpLoad %4 %49 -%222 = OpIAdd %4 %221 %220 -OpStore %49 %222 -%223 = OpAccessChain %82 %32 %76 -%224 = OpLoad %10 %223 -%225 = OpImageQueryLevels %4 %224 -%226 = OpLoad %4 %49 -%227 = OpIAdd %4 %226 %225 -OpStore %49 %227 -%228 = OpAccessChain %82 %32 %77 -%229 = OpLoad %10 %228 -%230 = OpImageQueryLevels %4 %229 -%231 = OpLoad %4 %49 -%232 = OpIAdd %4 %231 %230 -OpStore %49 %232 -%234 = OpAccessChain %233 %36 %71 -%235 = OpLoad %15 %234 -%236 = OpImageQuerySamples %4 %235 -%237 = OpLoad %4 %49 -%238 = OpIAdd %4 %237 %236 -OpStore %49 %238 -%239 = OpAccessChain %233 %36 %76 -%240 = OpLoad %15 %239 -%241 = OpImageQuerySamples %4 %240 -%242 = OpLoad %4 %49 -%243 = OpIAdd %4 %242 %241 -OpStore %49 %243 -%244 = OpAccessChain %233 %36 %77 -%245 = OpLoad %15 %244 +%194 = OpImageQuerySizeLod %29 %188 %9 +%195 = OpULessThan %164 %82 %194 +%196 = OpAll %157 %195 +OpBranchConditional %196 %197 %192 +%197 = OpLabel +%198 = OpImageFetch %26 %188 %82 Lod %9 +OpBranch %192 +%192 = OpLabel +%199 = OpPhi %26 %189 %177 %189 %193 %198 %197 +%200 = OpLoad %26 %60 +%201 = OpFAdd %26 %200 %199 +OpStore %60 %201 +%203 = OpAccessChain %202 %36 %5 +%204 = OpLoad %14 %203 +%206 = OpImageQuerySizeLod %205 %204 %5 +%207 = OpCompositeExtract %4 %206 2 +%208 = OpBitcast %6 %207 +%209 = OpLoad %6 %51 +%210 = OpIAdd %6 %209 %208 +OpStore %51 %210 +%211 = OpAccessChain %202 %36 %77 +%212 = OpLoad %14 %211 +%213 = OpImageQuerySizeLod %205 %212 %5 +%214 = OpCompositeExtract %4 %213 2 +%215 = OpBitcast %6 %214 +%216 = OpLoad %6 %51 +%217 = OpIAdd %6 %216 %215 +OpStore %51 %217 +%218 = OpAccessChain %202 %36 %78 +%219 = OpLoad %14 %218 +%220 = OpImageQuerySizeLod %205 %219 %5 +%221 = OpCompositeExtract %4 %220 2 +%222 = OpBitcast %6 %221 +%223 = OpLoad %6 %51 +%224 = OpIAdd %6 %223 %222 +OpStore %51 %224 +%225 = OpAccessChain %83 %34 %5 +%226 = OpLoad %11 %225 +%227 = OpImageQueryLevels %4 %226 +%228 = OpBitcast %6 %227 +%229 = OpLoad %6 %51 +%230 = OpIAdd %6 %229 %228 +OpStore %51 %230 +%231 = OpAccessChain %83 %34 %77 +%232 = OpLoad %11 %231 +%233 = OpImageQueryLevels %4 %232 +%234 = OpBitcast %6 %233 +%235 = OpLoad %6 %51 +%236 = OpIAdd %6 %235 %234 +OpStore %51 %236 +%237 = OpAccessChain %83 %34 %78 +%238 = OpLoad %11 %237 +%239 = OpImageQueryLevels %4 %238 +%240 = OpBitcast %6 %239 +%241 = OpLoad %6 %51 +%242 = OpIAdd %6 %241 %240 +OpStore %51 %242 +%244 = OpAccessChain %243 %38 %5 +%245 = OpLoad %16 %244 %246 = OpImageQuerySamples %4 %245 -%247 = OpLoad %4 %49 -%248 = OpIAdd %4 %247 %246 -OpStore %49 %248 -%249 = OpAccessChain %82 %32 %71 -%250 = OpLoad %10 %249 -%251 = OpAccessChain %100 %42 %71 -%252 = OpLoad %21 %251 -%253 = OpSampledImage %103 %250 %252 -%254 = OpImageSampleImplicitLod %25 %253 %80 -%255 = OpLoad %25 %58 -%256 = OpFAdd %25 %255 %254 -OpStore %58 %256 -%257 = OpAccessChain %82 %32 %76 -%258 = OpLoad %10 %257 -%259 = OpAccessChain %100 %42 %76 -%260 = OpLoad %21 %259 -%261 = OpSampledImage %103 %258 %260 -%262 = OpImageSampleImplicitLod %25 %261 %80 -%263 = OpLoad %25 %58 -%264 = OpFAdd %25 %263 %262 -OpStore %58 %264 -%265 = OpAccessChain %82 %32 %77 -%266 = OpLoad %10 %265 -%267 = OpAccessChain %100 %42 %77 -%268 = OpLoad %21 %267 -%269 = OpSampledImage %103 %266 %268 -%270 = OpImageSampleImplicitLod %25 %269 %80 -%271 = OpLoad %25 %58 -%272 = OpFAdd %25 %271 %270 -OpStore %58 %272 -%273 = OpAccessChain %82 %32 %71 -%274 = OpLoad %10 %273 -%275 = OpAccessChain %100 %42 %71 -%276 = OpLoad %21 %275 -%277 = OpSampledImage %103 %274 %276 -%278 = OpImageSampleImplicitLod %25 %277 %80 Bias %6 -%279 = OpLoad %25 %58 -%280 = OpFAdd %25 %279 %278 -OpStore %58 %280 -%281 = OpAccessChain %82 %32 %76 -%282 = OpLoad %10 %281 -%283 = OpAccessChain %100 %42 %76 -%284 = OpLoad %21 %283 -%285 = OpSampledImage %103 %282 %284 -%286 = OpImageSampleImplicitLod %25 %285 %80 Bias %6 -%287 = OpLoad %25 %58 -%288 = OpFAdd %25 %287 %286 -OpStore %58 %288 -%289 = OpAccessChain %82 %32 %77 -%290 = OpLoad %10 %289 -%291 = OpAccessChain %100 %42 %77 -%292 = OpLoad %21 %291 -%293 = OpSampledImage %103 %290 %292 -%294 = OpImageSampleImplicitLod %25 %293 %80 Bias %6 -%295 = OpLoad %25 %58 -%296 = OpFAdd %25 %295 %294 -OpStore %58 %296 -%297 = OpAccessChain %124 %38 %71 -%298 = OpLoad %17 %297 -%299 = OpAccessChain %127 %44 %71 -%300 = OpLoad %21 %299 -%301 = OpSampledImage %130 %298 %300 -%302 = OpImageSampleDrefImplicitLod %7 %301 %80 %6 -%303 = OpLoad %7 %55 -%304 = OpFAdd %7 %303 %302 -OpStore %55 %304 -%305 = OpAccessChain %124 %38 %76 -%306 = OpLoad %17 %305 -%307 = OpAccessChain %127 %44 %76 -%308 = OpLoad %21 %307 -%309 = OpSampledImage %130 %306 %308 -%310 = OpImageSampleDrefImplicitLod %7 %309 %80 %6 -%311 = OpLoad %7 %55 -%312 = OpFAdd %7 %311 %310 -OpStore %55 %312 -%313 = OpAccessChain %124 %38 %77 -%314 = OpLoad %17 %313 -%315 = OpAccessChain %127 %44 %77 -%316 = OpLoad %21 %315 -%317 = OpSampledImage %130 %314 %316 -%318 = OpImageSampleDrefImplicitLod %7 %317 %80 %6 -%319 = OpLoad %7 %55 -%320 = OpFAdd %7 %319 %318 -OpStore %55 %320 -%321 = OpAccessChain %124 %38 %71 -%322 = OpLoad %17 %321 -%323 = OpAccessChain %127 %44 %71 -%324 = OpLoad %21 %323 -%325 = OpSampledImage %130 %322 %324 -%326 = OpImageSampleDrefExplicitLod %7 %325 %80 %6 Lod %6 -%327 = OpLoad %7 %55 -%328 = OpFAdd %7 %327 %326 -OpStore %55 %328 -%329 = OpAccessChain %124 %38 %76 -%330 = OpLoad %17 %329 -%331 = OpAccessChain %127 %44 %76 -%332 = OpLoad %21 %331 -%333 = OpSampledImage %130 %330 %332 -%334 = OpImageSampleDrefExplicitLod %7 %333 %80 %6 Lod %6 -%335 = OpLoad %7 %55 -%336 = OpFAdd %7 %335 %334 -OpStore %55 %336 -%337 = OpAccessChain %124 %38 %77 -%338 = OpLoad %17 %337 -%339 = OpAccessChain %127 %44 %77 -%340 = OpLoad %21 %339 -%341 = OpSampledImage %130 %338 %340 -%342 = OpImageSampleDrefExplicitLod %7 %341 %80 %6 Lod %6 -%343 = OpLoad %7 %55 -%344 = OpFAdd %7 %343 %342 -OpStore %55 %344 -%345 = OpAccessChain %82 %32 %71 -%346 = OpLoad %10 %345 -%347 = OpAccessChain %100 %42 %71 -%348 = OpLoad %21 %347 -%349 = OpSampledImage %103 %346 %348 -%350 = OpImageSampleExplicitLod %25 %349 %80 Grad %80 %80 -%351 = OpLoad %25 %58 -%352 = OpFAdd %25 %351 %350 -OpStore %58 %352 -%353 = OpAccessChain %82 %32 %76 -%354 = OpLoad %10 %353 -%355 = OpAccessChain %100 %42 %76 -%356 = OpLoad %21 %355 -%357 = OpSampledImage %103 %354 %356 -%358 = OpImageSampleExplicitLod %25 %357 %80 Grad %80 %80 -%359 = OpLoad %25 %58 -%360 = OpFAdd %25 %359 %358 -OpStore %58 %360 -%361 = OpAccessChain %82 %32 %77 -%362 = OpLoad %10 %361 -%363 = OpAccessChain %100 %42 %77 -%364 = OpLoad %21 %363 -%365 = OpSampledImage %103 %362 %364 -%366 = OpImageSampleExplicitLod %25 %365 %80 Grad %80 %80 -%367 = OpLoad %25 %58 -%368 = OpFAdd %25 %367 %366 -OpStore %58 %368 -%369 = OpAccessChain %82 %32 %71 -%370 = OpLoad %10 %369 -%371 = OpAccessChain %100 %42 %71 -%372 = OpLoad %21 %371 -%373 = OpSampledImage %103 %370 %372 -%374 = OpImageSampleExplicitLod %25 %373 %80 Lod %6 -%375 = OpLoad %25 %58 -%376 = OpFAdd %25 %375 %374 -OpStore %58 %376 -%377 = OpAccessChain %82 %32 %76 -%378 = OpLoad %10 %377 -%379 = OpAccessChain %100 %42 %76 -%380 = OpLoad %21 %379 -%381 = OpSampledImage %103 %378 %380 -%382 = OpImageSampleExplicitLod %25 %381 %80 Lod %6 -%383 = OpLoad %25 %58 -%384 = OpFAdd %25 %383 %382 -OpStore %58 %384 -%385 = OpAccessChain %82 %32 %77 -%386 = OpLoad %10 %385 -%387 = OpAccessChain %100 %42 %77 -%388 = OpLoad %21 %387 -%389 = OpSampledImage %103 %386 %388 -%390 = OpImageSampleExplicitLod %25 %389 %80 Lod %6 -%391 = OpLoad %25 %58 -%392 = OpFAdd %25 %391 %390 -OpStore %58 %392 -%394 = OpAccessChain %393 %40 %71 -%395 = OpLoad %19 %394 -%396 = OpLoad %25 %58 -%397 = OpImageQuerySize %26 %395 -%398 = OpULessThan %160 %81 %397 -%399 = OpAll %153 %398 -OpSelectionMerge %400 None -OpBranchConditional %399 %401 %400 -%401 = OpLabel -OpImageWrite %395 %81 %396 -OpBranch %400 -%400 = OpLabel -%402 = OpAccessChain %393 %40 %76 -%403 = OpLoad %19 %402 -%404 = OpLoad %25 %58 -%405 = OpImageQuerySize %26 %403 -%406 = OpULessThan %160 %81 %405 -%407 = OpAll %153 %406 -OpSelectionMerge %408 None -OpBranchConditional %407 %409 %408 -%409 = OpLabel -OpImageWrite %403 %81 %404 -OpBranch %408 -%408 = OpLabel -%410 = OpAccessChain %393 %40 %77 -%411 = OpLoad %19 %410 -%412 = OpLoad %25 %58 -%413 = OpImageQuerySize %26 %411 -%414 = OpULessThan %160 %81 %413 -%415 = OpAll %153 %414 -OpSelectionMerge %416 None -OpBranchConditional %415 %417 %416 -%417 = OpLabel -OpImageWrite %411 %81 %412 -OpBranch %416 -%416 = OpLabel -%418 = OpLoad %26 %52 -%419 = OpLoad %4 %49 -%420 = OpCompositeConstruct %26 %419 %419 -%421 = OpIAdd %26 %418 %420 -%422 = OpConvertSToF %27 %421 -%423 = OpLoad %25 %58 -%424 = OpCompositeExtract %7 %422 0 -%425 = OpCompositeExtract %7 %422 1 -%426 = OpCompositeExtract %7 %422 0 -%427 = OpCompositeExtract %7 %422 1 -%428 = OpCompositeConstruct %25 %424 %425 %426 %427 -%429 = OpFAdd %25 %423 %428 -%430 = OpLoad %7 %55 -%431 = OpCompositeConstruct %25 %430 %430 %430 %430 -%432 = OpFAdd %25 %429 %431 -OpStore %66 %432 +%247 = OpBitcast %6 %246 +%248 = OpLoad %6 %51 +%249 = OpIAdd %6 %248 %247 +OpStore %51 %249 +%250 = OpAccessChain %243 %38 %77 +%251 = OpLoad %16 %250 +%252 = OpImageQuerySamples %4 %251 +%253 = OpBitcast %6 %252 +%254 = OpLoad %6 %51 +%255 = OpIAdd %6 %254 %253 +OpStore %51 %255 +%256 = OpAccessChain %243 %38 %78 +%257 = OpLoad %16 %256 +%258 = OpImageQuerySamples %4 %257 +%259 = OpBitcast %6 %258 +%260 = OpLoad %6 %51 +%261 = OpIAdd %6 %260 %259 +OpStore %51 %261 +%262 = OpAccessChain %83 %34 %5 +%263 = OpLoad %11 %262 +%264 = OpAccessChain %104 %44 %5 +%265 = OpLoad %22 %264 +%266 = OpSampledImage %107 %263 %265 +%267 = OpImageSampleImplicitLod %26 %266 %81 +%268 = OpLoad %26 %60 +%269 = OpFAdd %26 %268 %267 +OpStore %60 %269 +%270 = OpAccessChain %83 %34 %77 +%271 = OpLoad %11 %270 +%272 = OpAccessChain %104 %44 %77 +%273 = OpLoad %22 %272 +%274 = OpSampledImage %107 %271 %273 +%275 = OpImageSampleImplicitLod %26 %274 %81 +%276 = OpLoad %26 %60 +%277 = OpFAdd %26 %276 %275 +OpStore %60 %277 +%278 = OpAccessChain %83 %34 %78 +%279 = OpLoad %11 %278 +%280 = OpAccessChain %104 %44 %78 +%281 = OpLoad %22 %280 +%282 = OpSampledImage %107 %279 %281 +%283 = OpImageSampleImplicitLod %26 %282 %81 +%284 = OpLoad %26 %60 +%285 = OpFAdd %26 %284 %283 +OpStore %60 %285 +%286 = OpAccessChain %83 %34 %5 +%287 = OpLoad %11 %286 +%288 = OpAccessChain %104 %44 %5 +%289 = OpLoad %22 %288 +%290 = OpSampledImage %107 %287 %289 +%291 = OpImageSampleImplicitLod %26 %290 %81 Bias %7 +%292 = OpLoad %26 %60 +%293 = OpFAdd %26 %292 %291 +OpStore %60 %293 +%294 = OpAccessChain %83 %34 %77 +%295 = OpLoad %11 %294 +%296 = OpAccessChain %104 %44 %77 +%297 = OpLoad %22 %296 +%298 = OpSampledImage %107 %295 %297 +%299 = OpImageSampleImplicitLod %26 %298 %81 Bias %7 +%300 = OpLoad %26 %60 +%301 = OpFAdd %26 %300 %299 +OpStore %60 %301 +%302 = OpAccessChain %83 %34 %78 +%303 = OpLoad %11 %302 +%304 = OpAccessChain %104 %44 %78 +%305 = OpLoad %22 %304 +%306 = OpSampledImage %107 %303 %305 +%307 = OpImageSampleImplicitLod %26 %306 %81 Bias %7 +%308 = OpLoad %26 %60 +%309 = OpFAdd %26 %308 %307 +OpStore %60 %309 +%310 = OpAccessChain %128 %40 %5 +%311 = OpLoad %18 %310 +%312 = OpAccessChain %131 %46 %5 +%313 = OpLoad %22 %312 +%314 = OpSampledImage %134 %311 %313 +%315 = OpImageSampleDrefImplicitLod %8 %314 %81 %7 +%316 = OpLoad %8 %57 +%317 = OpFAdd %8 %316 %315 +OpStore %57 %317 +%318 = OpAccessChain %128 %40 %77 +%319 = OpLoad %18 %318 +%320 = OpAccessChain %131 %46 %77 +%321 = OpLoad %22 %320 +%322 = OpSampledImage %134 %319 %321 +%323 = OpImageSampleDrefImplicitLod %8 %322 %81 %7 +%324 = OpLoad %8 %57 +%325 = OpFAdd %8 %324 %323 +OpStore %57 %325 +%326 = OpAccessChain %128 %40 %78 +%327 = OpLoad %18 %326 +%328 = OpAccessChain %131 %46 %78 +%329 = OpLoad %22 %328 +%330 = OpSampledImage %134 %327 %329 +%331 = OpImageSampleDrefImplicitLod %8 %330 %81 %7 +%332 = OpLoad %8 %57 +%333 = OpFAdd %8 %332 %331 +OpStore %57 %333 +%334 = OpAccessChain %128 %40 %5 +%335 = OpLoad %18 %334 +%336 = OpAccessChain %131 %46 %5 +%337 = OpLoad %22 %336 +%338 = OpSampledImage %134 %335 %337 +%339 = OpImageSampleDrefExplicitLod %8 %338 %81 %7 Lod %7 +%340 = OpLoad %8 %57 +%341 = OpFAdd %8 %340 %339 +OpStore %57 %341 +%342 = OpAccessChain %128 %40 %77 +%343 = OpLoad %18 %342 +%344 = OpAccessChain %131 %46 %77 +%345 = OpLoad %22 %344 +%346 = OpSampledImage %134 %343 %345 +%347 = OpImageSampleDrefExplicitLod %8 %346 %81 %7 Lod %7 +%348 = OpLoad %8 %57 +%349 = OpFAdd %8 %348 %347 +OpStore %57 %349 +%350 = OpAccessChain %128 %40 %78 +%351 = OpLoad %18 %350 +%352 = OpAccessChain %131 %46 %78 +%353 = OpLoad %22 %352 +%354 = OpSampledImage %134 %351 %353 +%355 = OpImageSampleDrefExplicitLod %8 %354 %81 %7 Lod %7 +%356 = OpLoad %8 %57 +%357 = OpFAdd %8 %356 %355 +OpStore %57 %357 +%358 = OpAccessChain %83 %34 %5 +%359 = OpLoad %11 %358 +%360 = OpAccessChain %104 %44 %5 +%361 = OpLoad %22 %360 +%362 = OpSampledImage %107 %359 %361 +%363 = OpImageSampleExplicitLod %26 %362 %81 Grad %81 %81 +%364 = OpLoad %26 %60 +%365 = OpFAdd %26 %364 %363 +OpStore %60 %365 +%366 = OpAccessChain %83 %34 %77 +%367 = OpLoad %11 %366 +%368 = OpAccessChain %104 %44 %77 +%369 = OpLoad %22 %368 +%370 = OpSampledImage %107 %367 %369 +%371 = OpImageSampleExplicitLod %26 %370 %81 Grad %81 %81 +%372 = OpLoad %26 %60 +%373 = OpFAdd %26 %372 %371 +OpStore %60 %373 +%374 = OpAccessChain %83 %34 %78 +%375 = OpLoad %11 %374 +%376 = OpAccessChain %104 %44 %78 +%377 = OpLoad %22 %376 +%378 = OpSampledImage %107 %375 %377 +%379 = OpImageSampleExplicitLod %26 %378 %81 Grad %81 %81 +%380 = OpLoad %26 %60 +%381 = OpFAdd %26 %380 %379 +OpStore %60 %381 +%382 = OpAccessChain %83 %34 %5 +%383 = OpLoad %11 %382 +%384 = OpAccessChain %104 %44 %5 +%385 = OpLoad %22 %384 +%386 = OpSampledImage %107 %383 %385 +%387 = OpImageSampleExplicitLod %26 %386 %81 Lod %7 +%388 = OpLoad %26 %60 +%389 = OpFAdd %26 %388 %387 +OpStore %60 %389 +%390 = OpAccessChain %83 %34 %77 +%391 = OpLoad %11 %390 +%392 = OpAccessChain %104 %44 %77 +%393 = OpLoad %22 %392 +%394 = OpSampledImage %107 %391 %393 +%395 = OpImageSampleExplicitLod %26 %394 %81 Lod %7 +%396 = OpLoad %26 %60 +%397 = OpFAdd %26 %396 %395 +OpStore %60 %397 +%398 = OpAccessChain %83 %34 %78 +%399 = OpLoad %11 %398 +%400 = OpAccessChain %104 %44 %78 +%401 = OpLoad %22 %400 +%402 = OpSampledImage %107 %399 %401 +%403 = OpImageSampleExplicitLod %26 %402 %81 Lod %7 +%404 = OpLoad %26 %60 +%405 = OpFAdd %26 %404 %403 +OpStore %60 %405 +%407 = OpAccessChain %406 %42 %5 +%408 = OpLoad %20 %407 +%409 = OpLoad %26 %60 +%410 = OpImageQuerySize %29 %408 +%411 = OpULessThan %164 %82 %410 +%412 = OpAll %157 %411 +OpSelectionMerge %413 None +OpBranchConditional %412 %414 %413 +%414 = OpLabel +OpImageWrite %408 %82 %409 +OpBranch %413 +%413 = OpLabel +%415 = OpAccessChain %406 %42 %77 +%416 = OpLoad %20 %415 +%417 = OpLoad %26 %60 +%418 = OpImageQuerySize %29 %416 +%419 = OpULessThan %164 %82 %418 +%420 = OpAll %157 %419 +OpSelectionMerge %421 None +OpBranchConditional %420 %422 %421 +%422 = OpLabel +OpImageWrite %416 %82 %417 +OpBranch %421 +%421 = OpLabel +%423 = OpAccessChain %406 %42 %78 +%424 = OpLoad %20 %423 +%425 = OpLoad %26 %60 +%426 = OpImageQuerySize %29 %424 +%427 = OpULessThan %164 %82 %426 +%428 = OpAll %157 %427 +OpSelectionMerge %429 None +OpBranchConditional %428 %430 %429 +%430 = OpLabel +OpImageWrite %424 %82 %425 +OpBranch %429 +%429 = OpLabel +%431 = OpLoad %27 %54 +%432 = OpLoad %6 %51 +%433 = OpCompositeConstruct %27 %432 %432 +%434 = OpIAdd %27 %431 %433 +%435 = OpConvertUToF %28 %434 +%436 = OpLoad %26 %60 +%437 = OpCompositeExtract %8 %435 0 +%438 = OpCompositeExtract %8 %435 1 +%439 = OpCompositeExtract %8 %435 0 +%440 = OpCompositeExtract %8 %435 1 +%441 = OpCompositeConstruct %26 %437 %438 %439 %440 +%442 = OpFAdd %26 %436 %441 +%443 = OpLoad %8 %57 +%444 = OpCompositeConstruct %26 %443 %443 %443 %443 +%445 = OpFAdd %26 %442 %444 +OpStore %68 %445 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index f6cd159d6..7efb4483e 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 353 +; Bound: 376 OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D @@ -10,19 +10,19 @@ OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %84 "main" %81 -OpEntryPoint GLCompute %157 "depth_load" %155 -OpEntryPoint Vertex %178 "queries" %176 -OpEntryPoint Vertex %230 "levels_queries" %229 -OpEntryPoint Fragment %259 "texture_sample" %258 -OpEntryPoint Fragment %287 "texture_sample_comparison" %285 -OpEntryPoint Fragment %306 "gather" %305 -OpEntryPoint Fragment %341 "depth_no_comparison" %340 +OpEntryPoint GLCompute %158 "depth_load" %156 +OpEntryPoint Vertex %180 "queries" %178 +OpEntryPoint Vertex %245 "levels_queries" %244 +OpEntryPoint Fragment %282 "texture_sample" %281 +OpEntryPoint Fragment %310 "texture_sample_comparison" %308 +OpEntryPoint Fragment %329 "gather" %328 +OpEntryPoint Fragment %364 "depth_no_comparison" %363 OpExecutionMode %84 LocalSize 16 1 1 -OpExecutionMode %157 LocalSize 16 1 1 -OpExecutionMode %259 OriginUpperLeft -OpExecutionMode %287 OriginUpperLeft -OpExecutionMode %306 OriginUpperLeft -OpExecutionMode %341 OriginUpperLeft +OpExecutionMode %158 LocalSize 16 1 1 +OpExecutionMode %282 OriginUpperLeft +OpExecutionMode %310 OriginUpperLeft +OpExecutionMode %329 OriginUpperLeft +OpExecutionMode %364 OriginUpperLeft OpSource GLSL 450 OpName %39 "image_mipmapped_src" OpName %41 "image_multisampled_src" @@ -47,14 +47,14 @@ OpName %76 "image_2d_depth" OpName %78 "image_cube_depth" OpName %81 "local_id" OpName %84 "main" -OpName %155 "local_id" -OpName %157 "depth_load" -OpName %178 "queries" -OpName %230 "levels_queries" -OpName %259 "texture_sample" -OpName %287 "texture_sample_comparison" -OpName %306 "gather" -OpName %341 "depth_no_comparison" +OpName %156 "local_id" +OpName %158 "depth_load" +OpName %180 "queries" +OpName %245 "levels_queries" +OpName %282 "texture_sample" +OpName %310 "texture_sample_comparison" +OpName %329 "gather" +OpName %364 "depth_no_comparison" OpDecorate %39 DescriptorSet 0 OpDecorate %39 Binding 0 OpDecorate %41 DescriptorSet 0 @@ -101,13 +101,13 @@ OpDecorate %76 Binding 2 OpDecorate %78 DescriptorSet 1 OpDecorate %78 Binding 3 OpDecorate %81 BuiltIn LocalInvocationId -OpDecorate %155 BuiltIn LocalInvocationId -OpDecorate %176 BuiltIn Position -OpDecorate %229 BuiltIn Position -OpDecorate %258 Location 0 -OpDecorate %285 Location 0 -OpDecorate %305 Location 0 -OpDecorate %340 Location 0 +OpDecorate %156 BuiltIn LocalInvocationId +OpDecorate %178 BuiltIn Position +OpDecorate %244 BuiltIn Position +OpDecorate %281 Location 0 +OpDecorate %308 Location 0 +OpDecorate %328 Location 0 +OpDecorate %363 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -189,27 +189,27 @@ OpDecorate %340 Location 0 %82 = OpTypePointer Input %20 %81 = OpVariable %82 Input %85 = OpTypeFunction %2 -%111 = OpTypeVector %4 3 -%155 = OpVariable %82 Input -%177 = OpTypePointer Output %32 -%176 = OpVariable %177 Output -%187 = OpConstant %13 0 -%229 = OpVariable %177 Output -%258 = OpVariable %177 Output -%266 = OpTypeSampledImage %24 -%269 = OpTypeSampledImage %25 -%286 = OpTypePointer Output %8 -%285 = OpVariable %286 Output -%293 = OpTypeSampledImage %35 -%298 = OpConstant %8 0.0 -%300 = OpTypeSampledImage %36 -%305 = OpVariable %177 Output -%317 = OpConstant %13 1 -%320 = OpConstant %13 3 -%325 = OpTypeSampledImage %12 -%328 = OpTypeVector %4 4 -%329 = OpTypeSampledImage %26 -%340 = OpVariable %177 Output +%112 = OpTypeVector %4 3 +%156 = OpVariable %82 Input +%179 = OpTypePointer Output %32 +%178 = OpVariable %179 Output +%189 = OpConstant %13 0 +%244 = OpVariable %179 Output +%281 = OpVariable %179 Output +%289 = OpTypeSampledImage %24 +%292 = OpTypeSampledImage %25 +%309 = OpTypePointer Output %8 +%308 = OpVariable %309 Output +%316 = OpTypeSampledImage %35 +%321 = OpConstant %8 0.0 +%323 = OpTypeSampledImage %36 +%328 = OpVariable %179 Output +%340 = OpConstant %13 1 +%343 = OpConstant %13 3 +%348 = OpTypeSampledImage %12 +%351 = OpTypeVector %4 4 +%352 = OpTypeSampledImage %26 +%363 = OpVariable %179 Output %84 = OpFunction %2 None %85 %80 = OpLabel %83 = OpLoad %20 %81 @@ -222,271 +222,295 @@ OpDecorate %340 Location 0 OpBranch %92 %92 = OpLabel %93 = OpImageQuerySize %21 %88 -%94 = OpVectorShuffle %22 %83 %83 0 1 -%95 = OpBitcast %21 %94 -%96 = OpIMul %21 %93 %95 -%97 = OpCompositeConstruct %21 %3 %5 -%98 = OpSRem %21 %96 %97 -%99 = OpCompositeExtract %13 %83 2 -%100 = OpBitcast %4 %99 -%101 = OpImageFetch %23 %86 %98 Lod %100 -%102 = OpCompositeExtract %13 %83 2 -%103 = OpBitcast %4 %102 -%104 = OpImageFetch %23 %87 %98 Sample %103 -%105 = OpImageRead %23 %88 %98 -%106 = OpCompositeExtract %13 %83 2 -%107 = OpBitcast %4 %106 -%108 = OpCompositeExtract %13 %83 2 -%109 = OpBitcast %4 %108 -%110 = OpIAdd %4 %109 %6 -%112 = OpCompositeConstruct %111 %98 %107 -%113 = OpImageFetch %23 %89 %112 Lod %110 -%114 = OpCompositeExtract %13 %83 0 -%115 = OpBitcast %4 %114 -%116 = OpCompositeExtract %13 %83 2 -%117 = OpBitcast %4 %116 -%118 = OpImageFetch %23 %90 %115 Lod %117 -%119 = OpBitcast %22 %98 -%120 = OpCompositeExtract %13 %83 2 -%121 = OpBitcast %4 %120 -%122 = OpImageFetch %23 %86 %119 Lod %121 -%123 = OpBitcast %22 %98 -%124 = OpCompositeExtract %13 %83 2 -%125 = OpBitcast %4 %124 -%126 = OpImageFetch %23 %87 %123 Sample %125 -%127 = OpBitcast %22 %98 -%128 = OpImageRead %23 %88 %127 -%129 = OpBitcast %22 %98 -%130 = OpCompositeExtract %13 %83 2 -%131 = OpBitcast %4 %130 -%132 = OpCompositeExtract %13 %83 2 -%133 = OpBitcast %4 %132 -%134 = OpIAdd %4 %133 %6 -%135 = OpBitcast %13 %131 -%136 = OpCompositeConstruct %20 %129 %135 -%137 = OpImageFetch %23 %89 %136 Lod %134 -%138 = OpCompositeExtract %13 %83 0 -%140 = OpCompositeExtract %13 %83 2 -%141 = OpBitcast %4 %140 -%142 = OpImageFetch %23 %90 %138 Lod %141 -%143 = OpCompositeExtract %4 %98 0 -%144 = OpIAdd %23 %101 %104 -%145 = OpIAdd %23 %144 %105 -%146 = OpIAdd %23 %145 %113 -%147 = OpIAdd %23 %146 %118 -OpImageWrite %91 %143 %147 -%148 = OpCompositeExtract %4 %98 0 -%149 = OpBitcast %13 %148 -%150 = OpIAdd %23 %122 %126 -%151 = OpIAdd %23 %150 %128 -%152 = OpIAdd %23 %151 %137 -%153 = OpIAdd %23 %152 %142 -OpImageWrite %91 %149 %153 +%94 = OpBitcast %22 %93 +%95 = OpVectorShuffle %22 %83 %83 0 1 +%96 = OpIMul %22 %94 %95 +%97 = OpBitcast %21 %96 +%98 = OpCompositeConstruct %21 %3 %5 +%99 = OpSRem %21 %97 %98 +%100 = OpCompositeExtract %13 %83 2 +%101 = OpBitcast %4 %100 +%102 = OpImageFetch %23 %86 %99 Lod %101 +%103 = OpCompositeExtract %13 %83 2 +%104 = OpBitcast %4 %103 +%105 = OpImageFetch %23 %87 %99 Sample %104 +%106 = OpImageRead %23 %88 %99 +%107 = OpCompositeExtract %13 %83 2 +%108 = OpBitcast %4 %107 +%109 = OpCompositeExtract %13 %83 2 +%110 = OpBitcast %4 %109 +%111 = OpIAdd %4 %110 %6 +%113 = OpCompositeConstruct %112 %99 %108 +%114 = OpImageFetch %23 %89 %113 Lod %111 +%115 = OpCompositeExtract %13 %83 0 +%116 = OpBitcast %4 %115 +%117 = OpCompositeExtract %13 %83 2 +%118 = OpBitcast %4 %117 +%119 = OpImageFetch %23 %90 %116 Lod %118 +%120 = OpBitcast %22 %99 +%121 = OpCompositeExtract %13 %83 2 +%122 = OpBitcast %4 %121 +%123 = OpImageFetch %23 %86 %120 Lod %122 +%124 = OpBitcast %22 %99 +%125 = OpCompositeExtract %13 %83 2 +%126 = OpBitcast %4 %125 +%127 = OpImageFetch %23 %87 %124 Sample %126 +%128 = OpBitcast %22 %99 +%129 = OpImageRead %23 %88 %128 +%130 = OpBitcast %22 %99 +%131 = OpCompositeExtract %13 %83 2 +%132 = OpBitcast %4 %131 +%133 = OpCompositeExtract %13 %83 2 +%134 = OpBitcast %4 %133 +%135 = OpIAdd %4 %134 %6 +%136 = OpBitcast %13 %132 +%137 = OpCompositeConstruct %20 %130 %136 +%138 = OpImageFetch %23 %89 %137 Lod %135 +%139 = OpCompositeExtract %13 %83 0 +%141 = OpCompositeExtract %13 %83 2 +%142 = OpBitcast %4 %141 +%143 = OpImageFetch %23 %90 %139 Lod %142 +%144 = OpCompositeExtract %4 %99 0 +%145 = OpIAdd %23 %102 %105 +%146 = OpIAdd %23 %145 %106 +%147 = OpIAdd %23 %146 %114 +%148 = OpIAdd %23 %147 %119 +OpImageWrite %91 %144 %148 +%149 = OpCompositeExtract %4 %99 0 +%150 = OpBitcast %13 %149 +%151 = OpIAdd %23 %123 %127 +%152 = OpIAdd %23 %151 %129 +%153 = OpIAdd %23 %152 %138 +%154 = OpIAdd %23 %153 %143 +OpImageWrite %91 %150 %154 OpReturn OpFunctionEnd -%157 = OpFunction %2 None %85 -%154 = OpLabel -%156 = OpLoad %20 %155 -%158 = OpLoad %15 %43 -%159 = OpLoad %16 %45 -%160 = OpLoad %18 %53 -OpBranch %161 -%161 = OpLabel -%162 = OpImageQuerySize %21 %159 -%163 = OpVectorShuffle %22 %156 %156 0 1 -%164 = OpBitcast %21 %163 -%165 = OpIMul %21 %162 %164 -%166 = OpCompositeConstruct %21 %3 %5 -%167 = OpSRem %21 %165 %166 -%168 = OpCompositeExtract %13 %156 2 -%169 = OpBitcast %4 %168 -%170 = OpImageFetch %32 %158 %167 Sample %169 -%171 = OpCompositeExtract %8 %170 0 -%172 = OpCompositeExtract %4 %167 0 -%173 = OpConvertFToU %13 %171 -%174 = OpCompositeConstruct %23 %173 %173 %173 %173 -OpImageWrite %160 %172 %174 +%158 = OpFunction %2 None %85 +%155 = OpLabel +%157 = OpLoad %20 %156 +%159 = OpLoad %15 %43 +%160 = OpLoad %16 %45 +%161 = OpLoad %18 %53 +OpBranch %162 +%162 = OpLabel +%163 = OpImageQuerySize %21 %160 +%164 = OpBitcast %22 %163 +%165 = OpVectorShuffle %22 %157 %157 0 1 +%166 = OpIMul %22 %164 %165 +%167 = OpBitcast %21 %166 +%168 = OpCompositeConstruct %21 %3 %5 +%169 = OpSRem %21 %167 %168 +%170 = OpCompositeExtract %13 %157 2 +%171 = OpBitcast %4 %170 +%172 = OpImageFetch %32 %159 %169 Sample %171 +%173 = OpCompositeExtract %8 %172 0 +%174 = OpCompositeExtract %4 %169 0 +%175 = OpConvertFToU %13 %173 +%176 = OpCompositeConstruct %23 %175 %175 %175 %175 +OpImageWrite %161 %174 %176 OpReturn OpFunctionEnd -%178 = OpFunction %2 None %85 -%175 = OpLabel -%179 = OpLoad %24 %55 -%180 = OpLoad %25 %57 -%181 = OpLoad %27 %62 -%182 = OpLoad %28 %64 -%183 = OpLoad %29 %66 -%184 = OpLoad %30 %68 -%185 = OpLoad %31 %70 -OpBranch %186 -%186 = OpLabel -%188 = OpImageQuerySizeLod %4 %179 %187 -%190 = OpImageQuerySizeLod %4 %179 %188 -%191 = OpImageQuerySizeLod %21 %180 %187 -%192 = OpImageQuerySizeLod %21 %180 %6 -%193 = OpImageQuerySizeLod %111 %181 %187 -%194 = OpVectorShuffle %21 %193 %193 0 1 -%195 = OpImageQuerySizeLod %111 %181 %6 -%196 = OpVectorShuffle %21 %195 %195 0 1 -%197 = OpImageQuerySizeLod %21 %182 %187 -%198 = OpImageQuerySizeLod %21 %182 %6 -%199 = OpImageQuerySizeLod %111 %183 %187 -%200 = OpVectorShuffle %21 %199 %199 0 0 -%201 = OpImageQuerySizeLod %111 %183 %6 -%202 = OpVectorShuffle %21 %201 %201 0 0 -%203 = OpImageQuerySizeLod %111 %184 %187 -%204 = OpImageQuerySizeLod %111 %184 %6 -%205 = OpImageQuerySize %21 %185 -%206 = OpCompositeExtract %4 %191 1 -%207 = OpIAdd %4 %188 %206 -%208 = OpCompositeExtract %4 %192 1 -%209 = OpIAdd %4 %207 %208 -%210 = OpCompositeExtract %4 %194 1 -%211 = OpIAdd %4 %209 %210 -%212 = OpCompositeExtract %4 %196 1 -%213 = OpIAdd %4 %211 %212 -%214 = OpCompositeExtract %4 %197 1 -%215 = OpIAdd %4 %213 %214 -%216 = OpCompositeExtract %4 %198 1 -%217 = OpIAdd %4 %215 %216 -%218 = OpCompositeExtract %4 %200 1 -%219 = OpIAdd %4 %217 %218 -%220 = OpCompositeExtract %4 %202 1 -%221 = OpIAdd %4 %219 %220 -%222 = OpCompositeExtract %4 %203 2 -%223 = OpIAdd %4 %221 %222 -%224 = OpCompositeExtract %4 %204 2 -%225 = OpIAdd %4 %223 %224 -%226 = OpConvertSToF %8 %225 -%227 = OpCompositeConstruct %32 %226 %226 %226 %226 -OpStore %176 %227 +%180 = OpFunction %2 None %85 +%177 = OpLabel +%181 = OpLoad %24 %55 +%182 = OpLoad %25 %57 +%183 = OpLoad %27 %62 +%184 = OpLoad %28 %64 +%185 = OpLoad %29 %66 +%186 = OpLoad %30 %68 +%187 = OpLoad %31 %70 +OpBranch %188 +%188 = OpLabel +%190 = OpImageQuerySizeLod %4 %181 %189 +%191 = OpBitcast %13 %190 +%192 = OpBitcast %4 %191 +%193 = OpImageQuerySizeLod %4 %181 %192 +%194 = OpBitcast %13 %193 +%195 = OpImageQuerySizeLod %21 %182 %189 +%196 = OpBitcast %22 %195 +%197 = OpImageQuerySizeLod %21 %182 %6 +%198 = OpBitcast %22 %197 +%199 = OpImageQuerySizeLod %112 %183 %189 +%200 = OpBitcast %20 %199 +%201 = OpVectorShuffle %22 %200 %200 0 1 +%202 = OpImageQuerySizeLod %112 %183 %6 +%203 = OpBitcast %20 %202 +%204 = OpVectorShuffle %22 %203 %203 0 1 +%205 = OpImageQuerySizeLod %21 %184 %189 +%206 = OpBitcast %22 %205 +%207 = OpImageQuerySizeLod %21 %184 %6 +%208 = OpBitcast %22 %207 +%209 = OpImageQuerySizeLod %112 %185 %189 +%210 = OpBitcast %20 %209 +%211 = OpVectorShuffle %22 %210 %210 0 0 +%212 = OpImageQuerySizeLod %112 %185 %6 +%213 = OpBitcast %20 %212 +%214 = OpVectorShuffle %22 %213 %213 0 0 +%215 = OpImageQuerySizeLod %112 %186 %189 +%216 = OpBitcast %20 %215 +%217 = OpImageQuerySizeLod %112 %186 %6 +%218 = OpBitcast %20 %217 +%219 = OpImageQuerySize %21 %187 +%220 = OpBitcast %22 %219 +%221 = OpCompositeExtract %13 %196 1 +%222 = OpIAdd %13 %191 %221 +%223 = OpCompositeExtract %13 %198 1 +%224 = OpIAdd %13 %222 %223 +%225 = OpCompositeExtract %13 %201 1 +%226 = OpIAdd %13 %224 %225 +%227 = OpCompositeExtract %13 %204 1 +%228 = OpIAdd %13 %226 %227 +%229 = OpCompositeExtract %13 %206 1 +%230 = OpIAdd %13 %228 %229 +%231 = OpCompositeExtract %13 %208 1 +%232 = OpIAdd %13 %230 %231 +%233 = OpCompositeExtract %13 %211 1 +%234 = OpIAdd %13 %232 %233 +%235 = OpCompositeExtract %13 %214 1 +%236 = OpIAdd %13 %234 %235 +%237 = OpCompositeExtract %13 %216 2 +%238 = OpIAdd %13 %236 %237 +%239 = OpCompositeExtract %13 %218 2 +%240 = OpIAdd %13 %238 %239 +%241 = OpConvertUToF %8 %240 +%242 = OpCompositeConstruct %32 %241 %241 %241 %241 +OpStore %178 %242 OpReturn OpFunctionEnd -%230 = OpFunction %2 None %85 -%228 = OpLabel -%231 = OpLoad %25 %57 -%232 = OpLoad %27 %62 -%233 = OpLoad %28 %64 -%234 = OpLoad %29 %66 -%235 = OpLoad %30 %68 -%236 = OpLoad %31 %70 -OpBranch %237 -%237 = OpLabel -%238 = OpImageQueryLevels %4 %231 -%239 = OpImageQueryLevels %4 %232 -%240 = OpImageQuerySizeLod %111 %232 %187 -%241 = OpCompositeExtract %4 %240 2 -%242 = OpImageQueryLevels %4 %233 -%243 = OpImageQueryLevels %4 %234 -%244 = OpImageQuerySizeLod %111 %234 %187 -%245 = OpCompositeExtract %4 %244 2 -%246 = OpImageQueryLevels %4 %235 -%247 = OpImageQuerySamples %4 %236 -%248 = OpIAdd %4 %241 %245 -%249 = OpIAdd %4 %248 %247 -%250 = OpIAdd %4 %249 %238 -%251 = OpIAdd %4 %250 %239 -%252 = OpIAdd %4 %251 %246 -%253 = OpIAdd %4 %252 %242 -%254 = OpIAdd %4 %253 %243 -%255 = OpConvertSToF %8 %254 -%256 = OpCompositeConstruct %32 %255 %255 %255 %255 -OpStore %229 %256 +%245 = OpFunction %2 None %85 +%243 = OpLabel +%246 = OpLoad %25 %57 +%247 = OpLoad %27 %62 +%248 = OpLoad %28 %64 +%249 = OpLoad %29 %66 +%250 = OpLoad %30 %68 +%251 = OpLoad %31 %70 +OpBranch %252 +%252 = OpLabel +%253 = OpImageQueryLevels %4 %246 +%254 = OpBitcast %13 %253 +%255 = OpImageQueryLevels %4 %247 +%256 = OpBitcast %13 %255 +%257 = OpImageQuerySizeLod %112 %247 %189 +%258 = OpCompositeExtract %4 %257 2 +%259 = OpBitcast %13 %258 +%260 = OpImageQueryLevels %4 %248 +%261 = OpBitcast %13 %260 +%262 = OpImageQueryLevels %4 %249 +%263 = OpBitcast %13 %262 +%264 = OpImageQuerySizeLod %112 %249 %189 +%265 = OpCompositeExtract %4 %264 2 +%266 = OpBitcast %13 %265 +%267 = OpImageQueryLevels %4 %250 +%268 = OpBitcast %13 %267 +%269 = OpImageQuerySamples %4 %251 +%270 = OpBitcast %13 %269 +%271 = OpIAdd %13 %259 %266 +%272 = OpIAdd %13 %271 %270 +%273 = OpIAdd %13 %272 %254 +%274 = OpIAdd %13 %273 %256 +%275 = OpIAdd %13 %274 %268 +%276 = OpIAdd %13 %275 %261 +%277 = OpIAdd %13 %276 %263 +%278 = OpConvertUToF %8 %277 +%279 = OpCompositeConstruct %32 %278 %278 %278 %278 +OpStore %244 %279 OpReturn OpFunctionEnd -%259 = OpFunction %2 None %85 -%257 = OpLabel -%260 = OpLoad %24 %55 -%261 = OpLoad %25 %57 -%262 = OpLoad %33 %72 -OpBranch %263 -%263 = OpLabel -%264 = OpCompositeConstruct %34 %7 %7 -%265 = OpCompositeExtract %8 %264 0 -%267 = OpSampledImage %266 %260 %262 -%268 = OpImageSampleImplicitLod %32 %267 %265 -%270 = OpSampledImage %269 %261 %262 -%271 = OpImageSampleImplicitLod %32 %270 %264 -%272 = OpSampledImage %269 %261 %262 -%273 = OpImageSampleImplicitLod %32 %272 %264 ConstOffset %38 -%274 = OpSampledImage %269 %261 %262 -%275 = OpImageSampleExplicitLod %32 %274 %264 Lod %9 -%276 = OpSampledImage %269 %261 %262 -%277 = OpImageSampleExplicitLod %32 %276 %264 Lod|ConstOffset %9 %38 -%278 = OpSampledImage %269 %261 %262 -%279 = OpImageSampleImplicitLod %32 %278 %264 Bias|ConstOffset %11 %38 -%280 = OpFAdd %32 %268 %271 -%281 = OpFAdd %32 %280 %273 -%282 = OpFAdd %32 %281 %275 -%283 = OpFAdd %32 %282 %277 -OpStore %258 %283 +%282 = OpFunction %2 None %85 +%280 = OpLabel +%283 = OpLoad %24 %55 +%284 = OpLoad %25 %57 +%285 = OpLoad %33 %72 +OpBranch %286 +%286 = OpLabel +%287 = OpCompositeConstruct %34 %7 %7 +%288 = OpCompositeExtract %8 %287 0 +%290 = OpSampledImage %289 %283 %285 +%291 = OpImageSampleImplicitLod %32 %290 %288 +%293 = OpSampledImage %292 %284 %285 +%294 = OpImageSampleImplicitLod %32 %293 %287 +%295 = OpSampledImage %292 %284 %285 +%296 = OpImageSampleImplicitLod %32 %295 %287 ConstOffset %38 +%297 = OpSampledImage %292 %284 %285 +%298 = OpImageSampleExplicitLod %32 %297 %287 Lod %9 +%299 = OpSampledImage %292 %284 %285 +%300 = OpImageSampleExplicitLod %32 %299 %287 Lod|ConstOffset %9 %38 +%301 = OpSampledImage %292 %284 %285 +%302 = OpImageSampleImplicitLod %32 %301 %287 Bias|ConstOffset %11 %38 +%303 = OpFAdd %32 %291 %294 +%304 = OpFAdd %32 %303 %296 +%305 = OpFAdd %32 %304 %298 +%306 = OpFAdd %32 %305 %300 +OpStore %281 %306 OpReturn OpFunctionEnd -%287 = OpFunction %2 None %85 -%284 = OpLabel -%288 = OpLoad %33 %74 -%289 = OpLoad %35 %76 -%290 = OpLoad %36 %78 -OpBranch %291 -%291 = OpLabel -%292 = OpCompositeConstruct %34 %7 %7 -%294 = OpSampledImage %293 %289 %288 -%295 = OpImageSampleDrefImplicitLod %8 %294 %292 %7 -%296 = OpSampledImage %293 %289 %288 -%297 = OpImageSampleDrefExplicitLod %8 %296 %292 %7 Lod %298 -%299 = OpCompositeConstruct %37 %7 %7 %7 -%301 = OpSampledImage %300 %290 %288 -%302 = OpImageSampleDrefExplicitLod %8 %301 %299 %7 Lod %298 -%303 = OpFAdd %8 %295 %297 -OpStore %285 %303 -OpReturn -OpFunctionEnd -%306 = OpFunction %2 None %85 -%304 = OpLabel -%307 = OpLoad %25 %57 -%308 = OpLoad %12 %59 -%309 = OpLoad %26 %60 -%310 = OpLoad %33 %72 +%310 = OpFunction %2 None %85 +%307 = OpLabel %311 = OpLoad %33 %74 %312 = OpLoad %35 %76 -OpBranch %313 -%313 = OpLabel -%314 = OpCompositeConstruct %34 %7 %7 -%315 = OpSampledImage %269 %307 %310 -%316 = OpImageGather %32 %315 %314 %317 -%318 = OpSampledImage %269 %307 %310 -%319 = OpImageGather %32 %318 %314 %320 ConstOffset %38 -%321 = OpSampledImage %293 %312 %311 -%322 = OpImageDrefGather %32 %321 %314 %7 -%323 = OpSampledImage %293 %312 %311 -%324 = OpImageDrefGather %32 %323 %314 %7 ConstOffset %38 -%326 = OpSampledImage %325 %308 %310 -%327 = OpImageGather %23 %326 %314 %187 -%330 = OpSampledImage %329 %309 %310 -%331 = OpImageGather %328 %330 %314 %187 -%332 = OpConvertUToF %32 %327 -%333 = OpConvertSToF %32 %331 -%334 = OpFAdd %32 %332 %333 -%335 = OpFAdd %32 %316 %319 -%336 = OpFAdd %32 %335 %322 -%337 = OpFAdd %32 %336 %324 -%338 = OpFAdd %32 %337 %334 -OpStore %305 %338 +%313 = OpLoad %36 %78 +OpBranch %314 +%314 = OpLabel +%315 = OpCompositeConstruct %34 %7 %7 +%317 = OpSampledImage %316 %312 %311 +%318 = OpImageSampleDrefImplicitLod %8 %317 %315 %7 +%319 = OpSampledImage %316 %312 %311 +%320 = OpImageSampleDrefExplicitLod %8 %319 %315 %7 Lod %321 +%322 = OpCompositeConstruct %37 %7 %7 %7 +%324 = OpSampledImage %323 %313 %311 +%325 = OpImageSampleDrefExplicitLod %8 %324 %322 %7 Lod %321 +%326 = OpFAdd %8 %318 %320 +OpStore %308 %326 OpReturn OpFunctionEnd -%341 = OpFunction %2 None %85 -%339 = OpLabel -%342 = OpLoad %33 %72 -%343 = OpLoad %35 %76 -OpBranch %344 -%344 = OpLabel -%345 = OpCompositeConstruct %34 %7 %7 -%346 = OpSampledImage %293 %343 %342 -%347 = OpImageSampleImplicitLod %32 %346 %345 -%348 = OpCompositeExtract %8 %347 0 -%349 = OpSampledImage %293 %343 %342 -%350 = OpImageGather %32 %349 %345 %187 -%351 = OpCompositeConstruct %32 %348 %348 %348 %348 -%352 = OpFAdd %32 %351 %350 -OpStore %340 %352 +%329 = OpFunction %2 None %85 +%327 = OpLabel +%330 = OpLoad %25 %57 +%331 = OpLoad %12 %59 +%332 = OpLoad %26 %60 +%333 = OpLoad %33 %72 +%334 = OpLoad %33 %74 +%335 = OpLoad %35 %76 +OpBranch %336 +%336 = OpLabel +%337 = OpCompositeConstruct %34 %7 %7 +%338 = OpSampledImage %292 %330 %333 +%339 = OpImageGather %32 %338 %337 %340 +%341 = OpSampledImage %292 %330 %333 +%342 = OpImageGather %32 %341 %337 %343 ConstOffset %38 +%344 = OpSampledImage %316 %335 %334 +%345 = OpImageDrefGather %32 %344 %337 %7 +%346 = OpSampledImage %316 %335 %334 +%347 = OpImageDrefGather %32 %346 %337 %7 ConstOffset %38 +%349 = OpSampledImage %348 %331 %333 +%350 = OpImageGather %23 %349 %337 %189 +%353 = OpSampledImage %352 %332 %333 +%354 = OpImageGather %351 %353 %337 %189 +%355 = OpConvertUToF %32 %350 +%356 = OpConvertSToF %32 %354 +%357 = OpFAdd %32 %355 %356 +%358 = OpFAdd %32 %339 %342 +%359 = OpFAdd %32 %358 %345 +%360 = OpFAdd %32 %359 %347 +%361 = OpFAdd %32 %360 %357 +OpStore %328 %361 +OpReturn +OpFunctionEnd +%364 = OpFunction %2 None %85 +%362 = OpLabel +%365 = OpLoad %33 %72 +%366 = OpLoad %35 %76 +OpBranch %367 +%367 = OpLabel +%368 = OpCompositeConstruct %34 %7 %7 +%369 = OpSampledImage %316 %366 %365 +%370 = OpImageSampleImplicitLod %32 %369 %368 +%371 = OpCompositeExtract %8 %370 0 +%372 = OpSampledImage %316 %366 %365 +%373 = OpImageGather %32 %372 %368 %189 +%374 = OpCompositeConstruct %32 %371 %371 %371 %371 +%375 = OpFAdd %32 %374 %373 +OpStore %363 %375 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/binding-arrays.wgsl b/tests/out/wgsl/binding-arrays.wgsl index e3abd5c35..539773a74 100644 --- a/tests/out/wgsl/binding-arrays.wgsl +++ b/tests/out/wgsl/binding-arrays.wgsl @@ -27,28 +27,28 @@ var uni: UniformIndex; @fragment fn main(fragment_in: FragmentIn) -> @location(0) vec4 { - var i1_: i32; - var i2_: vec2; + var u1_: u32; + var u2_: vec2; var v1_: f32; var v4_: vec4; let uniform_index = uni.index; let non_uniform_index = fragment_in.index; - i1_ = 0; - i2_ = vec2(0); + u1_ = 0u; + u2_ = vec2(0u); v1_ = 0.0; v4_ = vec4(0.0); let uv = vec2(0.0); let pix = vec2(0); let _e22 = textureDimensions(texture_array_unbounded[0]); - let _e23 = i2_; - i2_ = (_e23 + _e22); + let _e23 = u2_; + u2_ = (_e23 + _e22); let _e27 = textureDimensions(texture_array_unbounded[uniform_index]); - let _e28 = i2_; - i2_ = (_e28 + _e27); + let _e28 = u2_; + u2_ = (_e28 + _e27); let _e32 = textureDimensions(texture_array_unbounded[non_uniform_index]); - let _e33 = i2_; - i2_ = (_e33 + _e32); + let _e33 = u2_; + u2_ = (_e33 + _e32); let _e41 = textureGather(0, texture_array_bounded[0], samp[0], uv); let _e42 = v4_; v4_ = (_e42 + _e41); @@ -77,32 +77,32 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { let _e101 = v4_; v4_ = (_e101 + _e100); let _e106 = textureNumLayers(texture_array_2darray[0]); - let _e107 = i1_; - i1_ = (_e107 + _e106); + let _e107 = u1_; + u1_ = (_e107 + _e106); let _e111 = textureNumLayers(texture_array_2darray[uniform_index]); - let _e112 = i1_; - i1_ = (_e112 + _e111); + let _e112 = u1_; + u1_ = (_e112 + _e111); let _e116 = textureNumLayers(texture_array_2darray[non_uniform_index]); - let _e117 = i1_; - i1_ = (_e117 + _e116); + let _e117 = u1_; + u1_ = (_e117 + _e116); let _e122 = textureNumLevels(texture_array_bounded[0]); - let _e123 = i1_; - i1_ = (_e123 + _e122); + let _e123 = u1_; + u1_ = (_e123 + _e122); let _e127 = textureNumLevels(texture_array_bounded[uniform_index]); - let _e128 = i1_; - i1_ = (_e128 + _e127); + let _e128 = u1_; + u1_ = (_e128 + _e127); let _e132 = textureNumLevels(texture_array_bounded[non_uniform_index]); - let _e133 = i1_; - i1_ = (_e133 + _e132); + let _e133 = u1_; + u1_ = (_e133 + _e132); let _e138 = textureNumSamples(texture_array_multisampled[0]); - let _e139 = i1_; - i1_ = (_e139 + _e138); + let _e139 = u1_; + u1_ = (_e139 + _e138); let _e143 = textureNumSamples(texture_array_multisampled[uniform_index]); - let _e144 = i1_; - i1_ = (_e144 + _e143); + let _e144 = u1_; + u1_ = (_e144 + _e143); let _e148 = textureNumSamples(texture_array_multisampled[non_uniform_index]); - let _e149 = i1_; - i1_ = (_e149 + _e148); + let _e149 = u1_; + u1_ = (_e149 + _e148); let _e157 = textureSample(texture_array_bounded[0], samp[0], uv); let _e158 = v4_; v4_ = (_e158 + _e157); @@ -163,9 +163,9 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { textureStore(texture_array_storage[uniform_index], pix, _e307); let _e310 = v4_; textureStore(texture_array_storage[non_uniform_index], pix, _e310); - let _e311 = i2_; - let _e312 = i1_; - let v2_ = vec2((_e311 + vec2(_e312))); + let _e311 = u2_; + let _e312 = u1_; + let v2_ = vec2((_e311 + vec2(_e312))); let _e316 = v4_; let _e323 = v1_; return ((_e316 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e323)); diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 5af7d073a..0dcaf3a4d 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -44,7 +44,7 @@ var image_cube_depth: texture_depth_cube; @compute @workgroup_size(16, 1, 1) fn main(@builtin(local_invocation_id) local_id: vec3) { let dim = textureDimensions(image_storage_src); - let itc = ((dim * vec2(local_id.xy)) % vec2(10, 20)); + let itc = (vec2((dim * local_id.xy)) % vec2(10, 20)); let value1_ = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); let value2_ = textureLoad(image_multisampled_src, itc, i32(local_id.z)); let value4_ = textureLoad(image_storage_src, itc); @@ -63,7 +63,7 @@ fn main(@builtin(local_invocation_id) local_id: vec3) { @compute @workgroup_size(16, 1, 1) fn depth_load(@builtin(local_invocation_id) local_id_1: vec3) { let dim_1 = textureDimensions(image_storage_src); - let itc_1 = ((dim_1 * vec2(local_id_1.xy)) % vec2(10, 20)); + let itc_1 = (vec2((dim_1 * local_id_1.xy)) % vec2(10, 20)); let val = textureLoad(image_depth_multisampled_src, itc_1, i32(local_id_1.z)); textureStore(image_dst, itc_1.x, vec4(u32(val))); return; diff --git a/tests/out/wgsl/images-frag.wgsl b/tests/out/wgsl/images-frag.wgsl index 6b0345923..e5c68dccc 100644 --- a/tests/out/wgsl/images-frag.wgsl +++ b/tests/out/wgsl/images-frag.wgsl @@ -22,15 +22,15 @@ fn testImg1D(coord: i32) { coord_1 = coord; let _e10 = textureDimensions(img1D); - size = _e10; + size = i32(_e10); _ = coord_1; _ = vec4(f32(2)); - let _e16 = coord_1; - textureStore(img1D, _e16, vec4(f32(2))); + let _e17 = coord_1; + textureStore(img1D, _e17, vec4(f32(2))); _ = coord_1; - let _e21 = coord_1; - let _e22 = textureLoad(img1D, _e21); - c = _e22; + let _e22 = coord_1; + let _e23 = textureLoad(img1D, _e22); + c = _e23; return; } @@ -42,15 +42,15 @@ fn testImg1DArray(coord_2: vec2) { coord_3 = coord_2; let _e10 = textureDimensions(img1DArray); let _e11 = textureNumLayers(img1DArray); - size_1 = vec2(vec2(_e10, _e11)); + size_1 = vec2(vec2(vec2(_e10, _e11))); _ = coord_3; - let _e16 = coord_3; - let _e19 = textureLoad(img1DArray, _e16.x, _e16.y); - c_1 = _e19; + let _e17 = coord_3; + let _e20 = textureLoad(img1DArray, _e17.x, _e17.y); + c_1 = _e20; _ = coord_3; _ = vec4(f32(2)); - let _e25 = coord_3; - textureStore(img1DArray, _e25.x, _e25.y, vec4(f32(2))); + let _e26 = coord_3; + textureStore(img1DArray, _e26.x, _e26.y, vec4(f32(2))); return; } @@ -61,15 +61,15 @@ fn testImg2D(coord_4: vec2) { coord_5 = coord_4; let _e10 = textureDimensions(img2D); - size_2 = vec2(_e10); + size_2 = vec2(vec2(_e10)); _ = coord_5; - let _e14 = coord_5; - let _e15 = textureLoad(img2D, _e14); - c_2 = _e15; + let _e15 = coord_5; + let _e16 = textureLoad(img2D, _e15); + c_2 = _e16; _ = coord_5; _ = vec4(f32(2)); - let _e21 = coord_5; - textureStore(img2D, _e21, vec4(f32(2))); + let _e22 = coord_5; + textureStore(img2D, _e22, vec4(f32(2))); return; } @@ -81,15 +81,15 @@ fn testImg2DArray(coord_6: vec3) { coord_7 = coord_6; let _e10 = textureDimensions(img2DArray); let _e13 = textureNumLayers(img2DArray); - size_3 = vec3(vec3(_e10.x, _e10.y, _e13)); + size_3 = vec3(vec3(vec3(_e10.x, _e10.y, _e13))); _ = coord_7; - let _e18 = coord_7; - let _e21 = textureLoad(img2DArray, _e18.xy, _e18.z); - c_3 = _e21; + let _e19 = coord_7; + let _e22 = textureLoad(img2DArray, _e19.xy, _e19.z); + c_3 = _e22; _ = coord_7; _ = vec4(f32(2)); - let _e27 = coord_7; - textureStore(img2DArray, _e27.xy, _e27.z, vec4(f32(2))); + let _e28 = coord_7; + textureStore(img2DArray, _e28.xy, _e28.z, vec4(f32(2))); return; } @@ -100,15 +100,15 @@ fn testImg3D(coord_8: vec3) { coord_9 = coord_8; let _e10 = textureDimensions(img3D); - size_4 = vec3(_e10); + size_4 = vec3(vec3(_e10)); _ = coord_9; - let _e14 = coord_9; - let _e15 = textureLoad(img3D, _e14); - c_4 = _e15; + let _e15 = coord_9; + let _e16 = textureLoad(img3D, _e15); + c_4 = _e16; _ = coord_9; _ = vec4(f32(2)); - let _e21 = coord_9; - textureStore(img3D, _e21, vec4(f32(2))); + let _e22 = coord_9; + textureStore(img3D, _e22, vec4(f32(2))); return; } @@ -119,11 +119,11 @@ fn testImgReadOnly(coord_10: vec2) { coord_11 = coord_10; let _e10 = textureDimensions(img2D); - size_5 = vec2(_e10); + size_5 = vec2(vec2(_e10)); _ = coord_11; - let _e14 = coord_11; - let _e15 = textureLoad(imgReadOnly, _e14); - c_5 = _e15; + let _e15 = coord_11; + let _e16 = textureLoad(imgReadOnly, _e15); + c_5 = _e16; return; } @@ -133,11 +133,11 @@ fn testImgWriteOnly(coord_12: vec2) { coord_13 = coord_12; let _e10 = textureDimensions(img2D); - size_6 = vec2(_e10); + size_6 = vec2(vec2(_e10)); _ = coord_13; _ = vec4(f32(2)); - let _e17 = coord_13; - textureStore(imgWriteOnly, _e17, vec4(f32(2))); + let _e18 = coord_13; + textureStore(imgWriteOnly, _e18, vec4(f32(2))); return; } @@ -147,7 +147,7 @@ fn testImgWriteReadOnly(coord_14: vec2) { coord_15 = coord_14; let _e10 = textureDimensions(imgWriteReadOnly); - size_7 = vec2(_e10); + size_7 = vec2(vec2(_e10)); return; } diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 2961a9dbd..e9c111659 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -38,145 +38,145 @@ fn testTex1D(coord: f32) { coord_1 = coord; let _e20 = textureDimensions(tex1D, 0); - size1D = _e20; + size1D = i32(_e20); _ = coord_1; - let _e24 = coord_1; - let _e25 = textureSample(tex1D, samp, _e24); - c = _e25; + let _e25 = coord_1; + let _e26 = textureSample(tex1D, samp, _e25); + c = _e26; _ = coord_1; - let _e28 = coord_1; - let _e30 = textureSampleBias(tex1D, samp, _e28, 2.0); - c = _e30; + let _e29 = coord_1; + let _e31 = textureSampleBias(tex1D, samp, _e29, 2.0); + c = _e31; _ = coord_1; - let _e34 = coord_1; - let _e37 = textureSampleGrad(tex1D, samp, _e34, 4.0, 4.0); - c = _e37; + let _e35 = coord_1; + let _e38 = textureSampleGrad(tex1D, samp, _e35, 4.0, 4.0); + c = _e38; _ = coord_1; - let _e42 = coord_1; - let _e46 = textureSampleGrad(tex1D, samp, _e42, 4.0, 4.0, 5); - c = _e46; + let _e43 = coord_1; + let _e47 = textureSampleGrad(tex1D, samp, _e43, 4.0, 4.0, 5); + c = _e47; _ = coord_1; - let _e49 = coord_1; - let _e51 = textureSampleLevel(tex1D, samp, _e49, 3.0); - c = _e51; + let _e50 = coord_1; + let _e52 = textureSampleLevel(tex1D, samp, _e50, 3.0); + c = _e52; _ = coord_1; - let _e55 = coord_1; - let _e58 = textureSampleLevel(tex1D, samp, _e55, 3.0, 5); - c = _e58; + let _e56 = coord_1; + let _e59 = textureSampleLevel(tex1D, samp, _e56, 3.0, 5); + c = _e59; _ = coord_1; - let _e61 = coord_1; - let _e63 = textureSample(tex1D, samp, _e61, 5); - c = _e63; + let _e62 = coord_1; + let _e64 = textureSample(tex1D, samp, _e62, 5); + c = _e64; _ = coord_1; - let _e67 = coord_1; - let _e70 = textureSampleBias(tex1D, samp, _e67, 2.0, 5); - c = _e70; - let _e71 = coord_1; - _ = vec2(_e71, 6.0); - let _e74 = coord_1; - let _e76 = vec2(_e74, 6.0); - let _e80 = textureSample(tex1D, samp, (_e76.x / _e76.y)); - c = _e80; - let _e81 = coord_1; - _ = vec4(_e81, 0.0, 0.0, 6.0); - let _e86 = coord_1; - let _e90 = vec4(_e86, 0.0, 0.0, 6.0); - let _e96 = textureSample(tex1D, samp, (_e90.xyz / vec3(_e90.w)).x); - c = _e96; - let _e97 = coord_1; - _ = vec2(_e97, 6.0); - let _e101 = coord_1; - let _e103 = vec2(_e101, 6.0); - let _e108 = textureSampleBias(tex1D, samp, (_e103.x / _e103.y), 2.0); - c = _e108; - let _e109 = coord_1; - _ = vec4(_e109, 0.0, 0.0, 6.0); - let _e115 = coord_1; - let _e119 = vec4(_e115, 0.0, 0.0, 6.0); - let _e126 = textureSampleBias(tex1D, samp, (_e119.xyz / vec3(_e119.w)).x, 2.0); - c = _e126; - let _e127 = coord_1; - _ = vec2(_e127, 6.0); - let _e132 = coord_1; - let _e134 = vec2(_e132, 6.0); - let _e140 = textureSampleGrad(tex1D, samp, (_e134.x / _e134.y), 4.0, 4.0); - c = _e140; - let _e141 = coord_1; - _ = vec4(_e141, 0.0, 0.0, 6.0); - let _e148 = coord_1; - let _e152 = vec4(_e148, 0.0, 0.0, 6.0); - let _e160 = textureSampleGrad(tex1D, samp, (_e152.xyz / vec3(_e152.w)).x, 4.0, 4.0); - c = _e160; - let _e161 = coord_1; - _ = vec2(_e161, 6.0); - let _e167 = coord_1; - let _e169 = vec2(_e167, 6.0); - let _e176 = textureSampleGrad(tex1D, samp, (_e169.x / _e169.y), 4.0, 4.0, 5); - c = _e176; - let _e177 = coord_1; - _ = vec4(_e177, 0.0, 0.0, 6.0); - let _e185 = coord_1; - let _e189 = vec4(_e185, 0.0, 0.0, 6.0); - let _e198 = textureSampleGrad(tex1D, samp, (_e189.xyz / vec3(_e189.w)).x, 4.0, 4.0, 5); - c = _e198; - let _e199 = coord_1; - _ = vec2(_e199, 6.0); - let _e203 = coord_1; - let _e205 = vec2(_e203, 6.0); - let _e210 = textureSampleLevel(tex1D, samp, (_e205.x / _e205.y), 3.0); - c = _e210; - let _e211 = coord_1; - _ = vec4(_e211, 0.0, 0.0, 6.0); - let _e217 = coord_1; - let _e221 = vec4(_e217, 0.0, 0.0, 6.0); - let _e228 = textureSampleLevel(tex1D, samp, (_e221.xyz / vec3(_e221.w)).x, 3.0); - c = _e228; - let _e229 = coord_1; - _ = vec2(_e229, 6.0); - let _e234 = coord_1; - let _e236 = vec2(_e234, 6.0); - let _e242 = textureSampleLevel(tex1D, samp, (_e236.x / _e236.y), 3.0, 5); - c = _e242; - let _e243 = coord_1; - _ = vec4(_e243, 0.0, 0.0, 6.0); - let _e250 = coord_1; - let _e254 = vec4(_e250, 0.0, 0.0, 6.0); - let _e262 = textureSampleLevel(tex1D, samp, (_e254.xyz / vec3(_e254.w)).x, 3.0, 5); - c = _e262; - let _e263 = coord_1; - _ = vec2(_e263, 6.0); - let _e267 = coord_1; - let _e269 = vec2(_e267, 6.0); - let _e274 = textureSample(tex1D, samp, (_e269.x / _e269.y), 5); - c = _e274; - let _e275 = coord_1; - _ = vec4(_e275, 0.0, 0.0, 6.0); - let _e281 = coord_1; - let _e285 = vec4(_e281, 0.0, 0.0, 6.0); - let _e292 = textureSample(tex1D, samp, (_e285.xyz / vec3(_e285.w)).x, 5); - c = _e292; - let _e293 = coord_1; - _ = vec2(_e293, 6.0); - let _e298 = coord_1; - let _e300 = vec2(_e298, 6.0); - let _e306 = textureSampleBias(tex1D, samp, (_e300.x / _e300.y), 2.0, 5); - c = _e306; - let _e307 = coord_1; - _ = vec4(_e307, 0.0, 0.0, 6.0); - let _e314 = coord_1; - let _e318 = vec4(_e314, 0.0, 0.0, 6.0); - let _e326 = textureSampleBias(tex1D, samp, (_e318.xyz / vec3(_e318.w)).x, 2.0, 5); - c = _e326; - let _e327 = coord_1; - _ = i32(_e327); - let _e330 = coord_1; - let _e333 = textureLoad(tex1D, i32(_e330), 3); - c = _e333; - let _e334 = coord_1; - _ = i32(_e334); - let _e338 = coord_1; - let _e342 = textureLoad(tex1D, i32(_e338), 3); - c = _e342; + let _e68 = coord_1; + let _e71 = textureSampleBias(tex1D, samp, _e68, 2.0, 5); + c = _e71; + let _e72 = coord_1; + _ = vec2(_e72, 6.0); + let _e75 = coord_1; + let _e77 = vec2(_e75, 6.0); + let _e81 = textureSample(tex1D, samp, (_e77.x / _e77.y)); + c = _e81; + let _e82 = coord_1; + _ = vec4(_e82, 0.0, 0.0, 6.0); + let _e87 = coord_1; + let _e91 = vec4(_e87, 0.0, 0.0, 6.0); + let _e97 = textureSample(tex1D, samp, (_e91.xyz / vec3(_e91.w)).x); + c = _e97; + let _e98 = coord_1; + _ = vec2(_e98, 6.0); + let _e102 = coord_1; + let _e104 = vec2(_e102, 6.0); + let _e109 = textureSampleBias(tex1D, samp, (_e104.x / _e104.y), 2.0); + c = _e109; + let _e110 = coord_1; + _ = vec4(_e110, 0.0, 0.0, 6.0); + let _e116 = coord_1; + let _e120 = vec4(_e116, 0.0, 0.0, 6.0); + let _e127 = textureSampleBias(tex1D, samp, (_e120.xyz / vec3(_e120.w)).x, 2.0); + c = _e127; + let _e128 = coord_1; + _ = vec2(_e128, 6.0); + let _e133 = coord_1; + let _e135 = vec2(_e133, 6.0); + let _e141 = textureSampleGrad(tex1D, samp, (_e135.x / _e135.y), 4.0, 4.0); + c = _e141; + let _e142 = coord_1; + _ = vec4(_e142, 0.0, 0.0, 6.0); + let _e149 = coord_1; + let _e153 = vec4(_e149, 0.0, 0.0, 6.0); + let _e161 = textureSampleGrad(tex1D, samp, (_e153.xyz / vec3(_e153.w)).x, 4.0, 4.0); + c = _e161; + let _e162 = coord_1; + _ = vec2(_e162, 6.0); + let _e168 = coord_1; + let _e170 = vec2(_e168, 6.0); + let _e177 = textureSampleGrad(tex1D, samp, (_e170.x / _e170.y), 4.0, 4.0, 5); + c = _e177; + let _e178 = coord_1; + _ = vec4(_e178, 0.0, 0.0, 6.0); + let _e186 = coord_1; + let _e190 = vec4(_e186, 0.0, 0.0, 6.0); + let _e199 = textureSampleGrad(tex1D, samp, (_e190.xyz / vec3(_e190.w)).x, 4.0, 4.0, 5); + c = _e199; + let _e200 = coord_1; + _ = vec2(_e200, 6.0); + let _e204 = coord_1; + let _e206 = vec2(_e204, 6.0); + let _e211 = textureSampleLevel(tex1D, samp, (_e206.x / _e206.y), 3.0); + c = _e211; + let _e212 = coord_1; + _ = vec4(_e212, 0.0, 0.0, 6.0); + let _e218 = coord_1; + let _e222 = vec4(_e218, 0.0, 0.0, 6.0); + let _e229 = textureSampleLevel(tex1D, samp, (_e222.xyz / vec3(_e222.w)).x, 3.0); + c = _e229; + let _e230 = coord_1; + _ = vec2(_e230, 6.0); + let _e235 = coord_1; + let _e237 = vec2(_e235, 6.0); + let _e243 = textureSampleLevel(tex1D, samp, (_e237.x / _e237.y), 3.0, 5); + c = _e243; + let _e244 = coord_1; + _ = vec4(_e244, 0.0, 0.0, 6.0); + let _e251 = coord_1; + let _e255 = vec4(_e251, 0.0, 0.0, 6.0); + let _e263 = textureSampleLevel(tex1D, samp, (_e255.xyz / vec3(_e255.w)).x, 3.0, 5); + c = _e263; + let _e264 = coord_1; + _ = vec2(_e264, 6.0); + let _e268 = coord_1; + let _e270 = vec2(_e268, 6.0); + let _e275 = textureSample(tex1D, samp, (_e270.x / _e270.y), 5); + c = _e275; + let _e276 = coord_1; + _ = vec4(_e276, 0.0, 0.0, 6.0); + let _e282 = coord_1; + let _e286 = vec4(_e282, 0.0, 0.0, 6.0); + let _e293 = textureSample(tex1D, samp, (_e286.xyz / vec3(_e286.w)).x, 5); + c = _e293; + let _e294 = coord_1; + _ = vec2(_e294, 6.0); + let _e299 = coord_1; + let _e301 = vec2(_e299, 6.0); + let _e307 = textureSampleBias(tex1D, samp, (_e301.x / _e301.y), 2.0, 5); + c = _e307; + let _e308 = coord_1; + _ = vec4(_e308, 0.0, 0.0, 6.0); + let _e315 = coord_1; + let _e319 = vec4(_e315, 0.0, 0.0, 6.0); + let _e327 = textureSampleBias(tex1D, samp, (_e319.xyz / vec3(_e319.w)).x, 2.0, 5); + c = _e327; + let _e328 = coord_1; + _ = i32(_e328); + let _e331 = coord_1; + let _e334 = textureLoad(tex1D, i32(_e331), 3); + c = _e334; + let _e335 = coord_1; + _ = i32(_e335); + let _e339 = coord_1; + let _e343 = textureLoad(tex1D, i32(_e339), 3); + c = _e343; return; } @@ -188,51 +188,51 @@ fn testTex1DArray(coord_2: vec2) { coord_3 = coord_2; let _e20 = textureDimensions(tex1DArray, 0); let _e21 = textureNumLayers(tex1DArray); - size1DArray = vec2(_e20, _e21); + size1DArray = vec2(vec2(_e20, _e21)); _ = coord_3; - let _e26 = coord_3; - let _e30 = textureSample(tex1DArray, samp, _e26.x, i32(_e26.y)); - c_1 = _e30; + let _e27 = coord_3; + let _e31 = textureSample(tex1DArray, samp, _e27.x, i32(_e27.y)); + c_1 = _e31; _ = coord_3; - let _e33 = coord_3; - let _e38 = textureSampleBias(tex1DArray, samp, _e33.x, i32(_e33.y), 2.0); - c_1 = _e38; + let _e34 = coord_3; + let _e39 = textureSampleBias(tex1DArray, samp, _e34.x, i32(_e34.y), 2.0); + c_1 = _e39; _ = coord_3; - let _e42 = coord_3; - let _e48 = textureSampleGrad(tex1DArray, samp, _e42.x, i32(_e42.y), 4.0, 4.0); - c_1 = _e48; + let _e43 = coord_3; + let _e49 = textureSampleGrad(tex1DArray, samp, _e43.x, i32(_e43.y), 4.0, 4.0); + c_1 = _e49; _ = coord_3; - let _e53 = coord_3; - let _e60 = textureSampleGrad(tex1DArray, samp, _e53.x, i32(_e53.y), 4.0, 4.0, 5); - c_1 = _e60; + let _e54 = coord_3; + let _e61 = textureSampleGrad(tex1DArray, samp, _e54.x, i32(_e54.y), 4.0, 4.0, 5); + c_1 = _e61; _ = coord_3; - let _e63 = coord_3; - let _e68 = textureSampleLevel(tex1DArray, samp, _e63.x, i32(_e63.y), 3.0); - c_1 = _e68; + let _e64 = coord_3; + let _e69 = textureSampleLevel(tex1DArray, samp, _e64.x, i32(_e64.y), 3.0); + c_1 = _e69; _ = coord_3; - let _e72 = coord_3; - let _e78 = textureSampleLevel(tex1DArray, samp, _e72.x, i32(_e72.y), 3.0, 5); - c_1 = _e78; + let _e73 = coord_3; + let _e79 = textureSampleLevel(tex1DArray, samp, _e73.x, i32(_e73.y), 3.0, 5); + c_1 = _e79; _ = coord_3; - let _e81 = coord_3; - let _e86 = textureSample(tex1DArray, samp, _e81.x, i32(_e81.y), 5); - c_1 = _e86; + let _e82 = coord_3; + let _e87 = textureSample(tex1DArray, samp, _e82.x, i32(_e82.y), 5); + c_1 = _e87; _ = coord_3; - let _e90 = coord_3; - let _e96 = textureSampleBias(tex1DArray, samp, _e90.x, i32(_e90.y), 2.0, 5); - c_1 = _e96; - let _e97 = coord_3; - _ = vec2(_e97); - let _e100 = coord_3; - let _e101 = vec2(_e100); - let _e105 = textureLoad(tex1DArray, _e101.x, _e101.y, 3); - c_1 = _e105; - let _e106 = coord_3; - _ = vec2(_e106); - let _e110 = coord_3; - let _e111 = vec2(_e110); - let _e116 = textureLoad(tex1DArray, _e111.x, _e111.y, 3); - c_1 = _e116; + let _e91 = coord_3; + let _e97 = textureSampleBias(tex1DArray, samp, _e91.x, i32(_e91.y), 2.0, 5); + c_1 = _e97; + let _e98 = coord_3; + _ = vec2(_e98); + let _e101 = coord_3; + let _e102 = vec2(_e101); + let _e106 = textureLoad(tex1DArray, _e102.x, _e102.y, 3); + c_1 = _e106; + let _e107 = coord_3; + _ = vec2(_e107); + let _e111 = coord_3; + let _e112 = vec2(_e111); + let _e117 = textureLoad(tex1DArray, _e112.x, _e112.y, 3); + c_1 = _e117; return; } @@ -243,183 +243,183 @@ fn testTex2D(coord_4: vec2) { coord_5 = coord_4; let _e20 = textureDimensions(tex2D, 0); - size2D = _e20; + size2D = vec2(_e20); _ = coord_5; - let _e24 = coord_5; - let _e25 = textureSample(tex2D, samp, _e24); - c_2 = _e25; + let _e25 = coord_5; + let _e26 = textureSample(tex2D, samp, _e25); + c_2 = _e26; _ = coord_5; - let _e28 = coord_5; - let _e30 = textureSampleBias(tex2D, samp, _e28, 2.0); - c_2 = _e30; + let _e29 = coord_5; + let _e31 = textureSampleBias(tex2D, samp, _e29, 2.0); + c_2 = _e31; _ = coord_5; _ = vec2(4.0); _ = vec2(4.0); - let _e36 = coord_5; - let _e41 = textureSampleGrad(tex2D, samp, _e36, vec2(4.0), vec2(4.0)); - c_2 = _e41; + let _e37 = coord_5; + let _e42 = textureSampleGrad(tex2D, samp, _e37, vec2(4.0), vec2(4.0)); + c_2 = _e42; _ = coord_5; _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e49 = coord_5; + let _e50 = coord_5; _ = vec2(5); - let _e56 = textureSampleGrad(tex2D, samp, _e49, vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = _e56; + let _e57 = textureSampleGrad(tex2D, samp, _e50, vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e57; _ = coord_5; - let _e59 = coord_5; - let _e61 = textureSampleLevel(tex2D, samp, _e59, 3.0); - c_2 = _e61; + let _e60 = coord_5; + let _e62 = textureSampleLevel(tex2D, samp, _e60, 3.0); + c_2 = _e62; _ = coord_5; _ = vec2(5); - let _e66 = coord_5; + let _e67 = coord_5; _ = vec2(5); - let _e70 = textureSampleLevel(tex2D, samp, _e66, 3.0, vec2(5, 5)); - c_2 = _e70; + let _e71 = textureSampleLevel(tex2D, samp, _e67, 3.0, vec2(5, 5)); + c_2 = _e71; _ = coord_5; _ = vec2(5); - let _e74 = coord_5; + let _e75 = coord_5; _ = vec2(5); - let _e77 = textureSample(tex2D, samp, _e74, vec2(5, 5)); - c_2 = _e77; + let _e78 = textureSample(tex2D, samp, _e75, vec2(5, 5)); + c_2 = _e78; _ = coord_5; _ = vec2(5); - let _e82 = coord_5; + let _e83 = coord_5; _ = vec2(5); - let _e86 = textureSampleBias(tex2D, samp, _e82, 2.0, vec2(5, 5)); - c_2 = _e86; - let _e87 = coord_5; - _ = vec3(_e87.x, _e87.y, 6.0); - let _e92 = coord_5; - let _e96 = vec3(_e92.x, _e92.y, 6.0); - let _e101 = textureSample(tex2D, samp, (_e96.xy / vec2(_e96.z))); - c_2 = _e101; - let _e102 = coord_5; - _ = vec4(_e102.x, _e102.y, 0.0, 6.0); - let _e108 = coord_5; - let _e113 = vec4(_e108.x, _e108.y, 0.0, 6.0); - let _e119 = textureSample(tex2D, samp, (_e113.xyz / vec3(_e113.w)).xy); - c_2 = _e119; - let _e120 = coord_5; - _ = vec3(_e120.x, _e120.y, 6.0); - let _e126 = coord_5; - let _e130 = vec3(_e126.x, _e126.y, 6.0); - let _e136 = textureSampleBias(tex2D, samp, (_e130.xy / vec2(_e130.z)), 2.0); - c_2 = _e136; - let _e137 = coord_5; - _ = vec4(_e137.x, _e137.y, 0.0, 6.0); - let _e144 = coord_5; - let _e149 = vec4(_e144.x, _e144.y, 0.0, 6.0); - let _e156 = textureSampleBias(tex2D, samp, (_e149.xyz / vec3(_e149.w)).xy, 2.0); - c_2 = _e156; - let _e157 = coord_5; - _ = vec3(_e157.x, _e157.y, 6.0); + let _e87 = textureSampleBias(tex2D, samp, _e83, 2.0, vec2(5, 5)); + c_2 = _e87; + let _e88 = coord_5; + _ = vec3(_e88.x, _e88.y, 6.0); + let _e93 = coord_5; + let _e97 = vec3(_e93.x, _e93.y, 6.0); + let _e102 = textureSample(tex2D, samp, (_e97.xy / vec2(_e97.z))); + c_2 = _e102; + let _e103 = coord_5; + _ = vec4(_e103.x, _e103.y, 0.0, 6.0); + let _e109 = coord_5; + let _e114 = vec4(_e109.x, _e109.y, 0.0, 6.0); + let _e120 = textureSample(tex2D, samp, (_e114.xyz / vec3(_e114.w)).xy); + c_2 = _e120; + let _e121 = coord_5; + _ = vec3(_e121.x, _e121.y, 6.0); + let _e127 = coord_5; + let _e131 = vec3(_e127.x, _e127.y, 6.0); + let _e137 = textureSampleBias(tex2D, samp, (_e131.xy / vec2(_e131.z)), 2.0); + c_2 = _e137; + let _e138 = coord_5; + _ = vec4(_e138.x, _e138.y, 0.0, 6.0); + let _e145 = coord_5; + let _e150 = vec4(_e145.x, _e145.y, 0.0, 6.0); + let _e157 = textureSampleBias(tex2D, samp, (_e150.xyz / vec3(_e150.w)).xy, 2.0); + c_2 = _e157; + let _e158 = coord_5; + _ = vec3(_e158.x, _e158.y, 6.0); _ = vec2(4.0); _ = vec2(4.0); - let _e166 = coord_5; - let _e170 = vec3(_e166.x, _e166.y, 6.0); - let _e179 = textureSampleGrad(tex2D, samp, (_e170.xy / vec2(_e170.z)), vec2(4.0), vec2(4.0)); - c_2 = _e179; - let _e180 = coord_5; - _ = vec4(_e180.x, _e180.y, 0.0, 6.0); + let _e167 = coord_5; + let _e171 = vec3(_e167.x, _e167.y, 6.0); + let _e180 = textureSampleGrad(tex2D, samp, (_e171.xy / vec2(_e171.z)), vec2(4.0), vec2(4.0)); + c_2 = _e180; + let _e181 = coord_5; + _ = vec4(_e181.x, _e181.y, 0.0, 6.0); _ = vec2(4.0); _ = vec2(4.0); - let _e190 = coord_5; - let _e195 = vec4(_e190.x, _e190.y, 0.0, 6.0); - let _e205 = textureSampleGrad(tex2D, samp, (_e195.xyz / vec3(_e195.w)).xy, vec2(4.0), vec2(4.0)); - c_2 = _e205; - let _e206 = coord_5; - _ = vec3(_e206.x, _e206.y, 6.0); + let _e191 = coord_5; + let _e196 = vec4(_e191.x, _e191.y, 0.0, 6.0); + let _e206 = textureSampleGrad(tex2D, samp, (_e196.xyz / vec3(_e196.w)).xy, vec2(4.0), vec2(4.0)); + c_2 = _e206; + let _e207 = coord_5; + _ = vec3(_e207.x, _e207.y, 6.0); _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e217 = coord_5; - let _e221 = vec3(_e217.x, _e217.y, 6.0); + let _e218 = coord_5; + let _e222 = vec3(_e218.x, _e218.y, 6.0); _ = vec2(5); - let _e232 = textureSampleGrad(tex2D, samp, (_e221.xy / vec2(_e221.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = _e232; - let _e233 = coord_5; - _ = vec4(_e233.x, _e233.y, 0.0, 6.0); + let _e233 = textureSampleGrad(tex2D, samp, (_e222.xy / vec2(_e222.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e233; + let _e234 = coord_5; + _ = vec4(_e234.x, _e234.y, 0.0, 6.0); _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e245 = coord_5; - let _e250 = vec4(_e245.x, _e245.y, 0.0, 6.0); + let _e246 = coord_5; + let _e251 = vec4(_e246.x, _e246.y, 0.0, 6.0); _ = vec2(5); - let _e262 = textureSampleGrad(tex2D, samp, (_e250.xyz / vec3(_e250.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); - c_2 = _e262; - let _e263 = coord_5; - _ = vec3(_e263.x, _e263.y, 6.0); - let _e269 = coord_5; - let _e273 = vec3(_e269.x, _e269.y, 6.0); - let _e279 = textureSampleLevel(tex2D, samp, (_e273.xy / vec2(_e273.z)), 3.0); - c_2 = _e279; - let _e280 = coord_5; - _ = vec4(_e280.x, _e280.y, 0.0, 6.0); - let _e287 = coord_5; - let _e292 = vec4(_e287.x, _e287.y, 0.0, 6.0); - let _e299 = textureSampleLevel(tex2D, samp, (_e292.xyz / vec3(_e292.w)).xy, 3.0); - c_2 = _e299; - let _e300 = coord_5; - _ = vec3(_e300.x, _e300.y, 6.0); + let _e263 = textureSampleGrad(tex2D, samp, (_e251.xyz / vec3(_e251.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); + c_2 = _e263; + let _e264 = coord_5; + _ = vec3(_e264.x, _e264.y, 6.0); + let _e270 = coord_5; + let _e274 = vec3(_e270.x, _e270.y, 6.0); + let _e280 = textureSampleLevel(tex2D, samp, (_e274.xy / vec2(_e274.z)), 3.0); + c_2 = _e280; + let _e281 = coord_5; + _ = vec4(_e281.x, _e281.y, 0.0, 6.0); + let _e288 = coord_5; + let _e293 = vec4(_e288.x, _e288.y, 0.0, 6.0); + let _e300 = textureSampleLevel(tex2D, samp, (_e293.xyz / vec3(_e293.w)).xy, 3.0); + c_2 = _e300; + let _e301 = coord_5; + _ = vec3(_e301.x, _e301.y, 6.0); _ = vec2(5); - let _e308 = coord_5; - let _e312 = vec3(_e308.x, _e308.y, 6.0); + let _e309 = coord_5; + let _e313 = vec3(_e309.x, _e309.y, 6.0); _ = vec2(5); - let _e320 = textureSampleLevel(tex2D, samp, (_e312.xy / vec2(_e312.z)), 3.0, vec2(5, 5)); - c_2 = _e320; - let _e321 = coord_5; - _ = vec4(_e321.x, _e321.y, 0.0, 6.0); + let _e321 = textureSampleLevel(tex2D, samp, (_e313.xy / vec2(_e313.z)), 3.0, vec2(5, 5)); + c_2 = _e321; + let _e322 = coord_5; + _ = vec4(_e322.x, _e322.y, 0.0, 6.0); _ = vec2(5); - let _e330 = coord_5; - let _e335 = vec4(_e330.x, _e330.y, 0.0, 6.0); + let _e331 = coord_5; + let _e336 = vec4(_e331.x, _e331.y, 0.0, 6.0); _ = vec2(5); - let _e344 = textureSampleLevel(tex2D, samp, (_e335.xyz / vec3(_e335.w)).xy, 3.0, vec2(5, 5)); - c_2 = _e344; - let _e345 = coord_5; - _ = vec3(_e345.x, _e345.y, 6.0); + let _e345 = textureSampleLevel(tex2D, samp, (_e336.xyz / vec3(_e336.w)).xy, 3.0, vec2(5, 5)); + c_2 = _e345; + let _e346 = coord_5; + _ = vec3(_e346.x, _e346.y, 6.0); _ = vec2(5); - let _e352 = coord_5; - let _e356 = vec3(_e352.x, _e352.y, 6.0); + let _e353 = coord_5; + let _e357 = vec3(_e353.x, _e353.y, 6.0); _ = vec2(5); - let _e363 = textureSample(tex2D, samp, (_e356.xy / vec2(_e356.z)), vec2(5, 5)); - c_2 = _e363; - let _e364 = coord_5; - _ = vec4(_e364.x, _e364.y, 0.0, 6.0); + let _e364 = textureSample(tex2D, samp, (_e357.xy / vec2(_e357.z)), vec2(5, 5)); + c_2 = _e364; + let _e365 = coord_5; + _ = vec4(_e365.x, _e365.y, 0.0, 6.0); _ = vec2(5); - let _e372 = coord_5; - let _e377 = vec4(_e372.x, _e372.y, 0.0, 6.0); + let _e373 = coord_5; + let _e378 = vec4(_e373.x, _e373.y, 0.0, 6.0); _ = vec2(5); - let _e385 = textureSample(tex2D, samp, (_e377.xyz / vec3(_e377.w)).xy, vec2(5, 5)); - c_2 = _e385; - let _e386 = coord_5; - _ = vec3(_e386.x, _e386.y, 6.0); + let _e386 = textureSample(tex2D, samp, (_e378.xyz / vec3(_e378.w)).xy, vec2(5, 5)); + c_2 = _e386; + let _e387 = coord_5; + _ = vec3(_e387.x, _e387.y, 6.0); _ = vec2(5); - let _e394 = coord_5; - let _e398 = vec3(_e394.x, _e394.y, 6.0); + let _e395 = coord_5; + let _e399 = vec3(_e395.x, _e395.y, 6.0); _ = vec2(5); - let _e406 = textureSampleBias(tex2D, samp, (_e398.xy / vec2(_e398.z)), 2.0, vec2(5, 5)); - c_2 = _e406; - let _e407 = coord_5; - _ = vec4(_e407.x, _e407.y, 0.0, 6.0); + let _e407 = textureSampleBias(tex2D, samp, (_e399.xy / vec2(_e399.z)), 2.0, vec2(5, 5)); + c_2 = _e407; + let _e408 = coord_5; + _ = vec4(_e408.x, _e408.y, 0.0, 6.0); _ = vec2(5); - let _e416 = coord_5; - let _e421 = vec4(_e416.x, _e416.y, 0.0, 6.0); + let _e417 = coord_5; + let _e422 = vec4(_e417.x, _e417.y, 0.0, 6.0); _ = vec2(5); - let _e430 = textureSampleBias(tex2D, samp, (_e421.xyz / vec3(_e421.w)).xy, 2.0, vec2(5, 5)); - c_2 = _e430; - let _e431 = coord_5; - _ = vec2(_e431); - let _e434 = coord_5; - let _e437 = textureLoad(tex2D, vec2(_e434), 3); - c_2 = _e437; - let _e438 = coord_5; - _ = vec2(_e438); + let _e431 = textureSampleBias(tex2D, samp, (_e422.xyz / vec3(_e422.w)).xy, 2.0, vec2(5, 5)); + c_2 = _e431; + let _e432 = coord_5; + _ = vec2(_e432); + let _e435 = coord_5; + let _e438 = textureLoad(tex2D, vec2(_e435), 3); + c_2 = _e438; + let _e439 = coord_5; + _ = vec2(_e439); _ = vec2(5); - let _e443 = coord_5; + let _e444 = coord_5; _ = vec2(5); - let _e448 = textureLoad(tex2D, vec2(_e443), 3); - c_2 = _e448; + let _e449 = textureLoad(tex2D, vec2(_e444), 3); + c_2 = _e449; return; } @@ -430,113 +430,113 @@ fn testTex2DShadow(coord_6: vec2) { coord_7 = coord_6; let _e20 = textureDimensions(tex2DShadow, 0); - size2DShadow = _e20; - let _e23 = coord_7; - _ = vec3(_e23.x, _e23.y, 1.0); - let _e28 = coord_7; - let _e32 = vec3(_e28.x, _e28.y, 1.0); - let _e35 = textureSampleCompare(tex2DShadow, sampShadow, _e32.xy, _e32.z); - d = _e35; - let _e36 = coord_7; - _ = vec3(_e36.x, _e36.y, 1.0); + size2DShadow = vec2(_e20); + let _e24 = coord_7; + _ = vec3(_e24.x, _e24.y, 1.0); + let _e29 = coord_7; + let _e33 = vec3(_e29.x, _e29.y, 1.0); + let _e36 = textureSampleCompare(tex2DShadow, sampShadow, _e33.xy, _e33.z); + d = _e36; + let _e37 = coord_7; + _ = vec3(_e37.x, _e37.y, 1.0); _ = vec2(4.0); _ = vec2(4.0); - let _e45 = coord_7; - let _e49 = vec3(_e45.x, _e45.y, 1.0); + let _e46 = coord_7; + let _e50 = vec3(_e46.x, _e46.y, 1.0); _ = vec2(4.0); _ = vec2(4.0); - let _e56 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e49.xy, _e49.z); - d = _e56; - let _e57 = coord_7; - _ = vec3(_e57.x, _e57.y, 1.0); + let _e57 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e50.xy, _e50.z); + d = _e57; + let _e58 = coord_7; + _ = vec3(_e58.x, _e58.y, 1.0); _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e68 = coord_7; - let _e72 = vec3(_e68.x, _e68.y, 1.0); + let _e69 = coord_7; + let _e73 = vec3(_e69.x, _e69.y, 1.0); _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e81 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e72.xy, _e72.z, vec2(5, 5)); - d = _e81; - let _e82 = coord_7; - _ = vec3(_e82.x, _e82.y, 1.0); - let _e88 = coord_7; - let _e92 = vec3(_e88.x, _e88.y, 1.0); - let _e96 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e92.xy, _e92.z); - d = _e96; - let _e97 = coord_7; - _ = vec3(_e97.x, _e97.y, 1.0); + let _e82 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e73.xy, _e73.z, vec2(5, 5)); + d = _e82; + let _e83 = coord_7; + _ = vec3(_e83.x, _e83.y, 1.0); + let _e89 = coord_7; + let _e93 = vec3(_e89.x, _e89.y, 1.0); + let _e97 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e93.xy, _e93.z); + d = _e97; + let _e98 = coord_7; + _ = vec3(_e98.x, _e98.y, 1.0); _ = vec2(5); - let _e105 = coord_7; - let _e109 = vec3(_e105.x, _e105.y, 1.0); + let _e106 = coord_7; + let _e110 = vec3(_e106.x, _e106.y, 1.0); _ = vec2(5); - let _e115 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e109.xy, _e109.z, vec2(5, 5)); - d = _e115; - let _e116 = coord_7; - _ = vec3(_e116.x, _e116.y, 1.0); + let _e116 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e110.xy, _e110.z, vec2(5, 5)); + d = _e116; + let _e117 = coord_7; + _ = vec3(_e117.x, _e117.y, 1.0); _ = vec2(5); - let _e123 = coord_7; - let _e127 = vec3(_e123.x, _e123.y, 1.0); + let _e124 = coord_7; + let _e128 = vec3(_e124.x, _e124.y, 1.0); _ = vec2(5); - let _e132 = textureSampleCompare(tex2DShadow, sampShadow, _e127.xy, _e127.z, vec2(5, 5)); - d = _e132; - let _e133 = coord_7; - _ = vec4(_e133.x, _e133.y, 1.0, 6.0); - let _e139 = coord_7; - let _e144 = vec4(_e139.x, _e139.y, 1.0, 6.0); - let _e148 = (_e144.xyz / vec3(_e144.w)); - let _e151 = textureSampleCompare(tex2DShadow, sampShadow, _e148.xy, _e148.z); - d = _e151; - let _e152 = coord_7; - _ = vec4(_e152.x, _e152.y, 1.0, 6.0); + let _e133 = textureSampleCompare(tex2DShadow, sampShadow, _e128.xy, _e128.z, vec2(5, 5)); + d = _e133; + let _e134 = coord_7; + _ = vec4(_e134.x, _e134.y, 1.0, 6.0); + let _e140 = coord_7; + let _e145 = vec4(_e140.x, _e140.y, 1.0, 6.0); + let _e149 = (_e145.xyz / vec3(_e145.w)); + let _e152 = textureSampleCompare(tex2DShadow, sampShadow, _e149.xy, _e149.z); + d = _e152; + let _e153 = coord_7; + _ = vec4(_e153.x, _e153.y, 1.0, 6.0); _ = vec2(4.0); _ = vec2(4.0); - let _e162 = coord_7; - let _e167 = vec4(_e162.x, _e162.y, 1.0, 6.0); + let _e163 = coord_7; + let _e168 = vec4(_e163.x, _e163.y, 1.0, 6.0); _ = vec2(4.0); _ = vec2(4.0); - let _e175 = (_e167.xyz / vec3(_e167.w)); - let _e178 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e175.xy, _e175.z); - d = _e178; - let _e179 = coord_7; - _ = vec4(_e179.x, _e179.y, 1.0, 6.0); + let _e176 = (_e168.xyz / vec3(_e168.w)); + let _e179 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e176.xy, _e176.z); + d = _e179; + let _e180 = coord_7; + _ = vec4(_e180.x, _e180.y, 1.0, 6.0); _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e191 = coord_7; - let _e196 = vec4(_e191.x, _e191.y, 1.0, 6.0); + let _e192 = coord_7; + let _e197 = vec4(_e192.x, _e192.y, 1.0, 6.0); _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e206 = (_e196.xyz / vec3(_e196.w)); - let _e209 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e206.xy, _e206.z, vec2(5, 5)); - d = _e209; - let _e210 = coord_7; - _ = vec4(_e210.x, _e210.y, 1.0, 6.0); - let _e217 = coord_7; - let _e222 = vec4(_e217.x, _e217.y, 1.0, 6.0); - let _e227 = (_e222.xyz / vec3(_e222.w)); - let _e230 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e227.xy, _e227.z); - d = _e230; - let _e231 = coord_7; - _ = vec4(_e231.x, _e231.y, 1.0, 6.0); + let _e207 = (_e197.xyz / vec3(_e197.w)); + let _e210 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e207.xy, _e207.z, vec2(5, 5)); + d = _e210; + let _e211 = coord_7; + _ = vec4(_e211.x, _e211.y, 1.0, 6.0); + let _e218 = coord_7; + let _e223 = vec4(_e218.x, _e218.y, 1.0, 6.0); + let _e228 = (_e223.xyz / vec3(_e223.w)); + let _e231 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e228.xy, _e228.z); + d = _e231; + let _e232 = coord_7; + _ = vec4(_e232.x, _e232.y, 1.0, 6.0); _ = vec2(5); - let _e240 = coord_7; - let _e245 = vec4(_e240.x, _e240.y, 1.0, 6.0); + let _e241 = coord_7; + let _e246 = vec4(_e241.x, _e241.y, 1.0, 6.0); _ = vec2(5); - let _e252 = (_e245.xyz / vec3(_e245.w)); - let _e255 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e252.xy, _e252.z, vec2(5, 5)); - d = _e255; - let _e256 = coord_7; - _ = vec4(_e256.x, _e256.y, 1.0, 6.0); + let _e253 = (_e246.xyz / vec3(_e246.w)); + let _e256 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e253.xy, _e253.z, vec2(5, 5)); + d = _e256; + let _e257 = coord_7; + _ = vec4(_e257.x, _e257.y, 1.0, 6.0); _ = vec2(5); - let _e264 = coord_7; - let _e269 = vec4(_e264.x, _e264.y, 1.0, 6.0); + let _e265 = coord_7; + let _e270 = vec4(_e265.x, _e265.y, 1.0, 6.0); _ = vec2(5); - let _e275 = (_e269.xyz / vec3(_e269.w)); - let _e278 = textureSampleCompare(tex2DShadow, sampShadow, _e275.xy, _e275.z, vec2(5, 5)); - d = _e278; + let _e276 = (_e270.xyz / vec3(_e270.w)); + let _e279 = textureSampleCompare(tex2DShadow, sampShadow, _e276.xy, _e276.z, vec2(5, 5)); + d = _e279; return; } @@ -548,65 +548,65 @@ fn testTex2DArray(coord_8: vec3) { coord_9 = coord_8; let _e20 = textureDimensions(tex2DArray, 0); let _e23 = textureNumLayers(tex2DArray); - size2DArray = vec3(_e20.x, _e20.y, _e23); + size2DArray = vec3(vec3(_e20.x, _e20.y, _e23)); _ = coord_9; - let _e28 = coord_9; - let _e32 = textureSample(tex2DArray, samp, _e28.xy, i32(_e28.z)); - c_3 = _e32; + let _e29 = coord_9; + let _e33 = textureSample(tex2DArray, samp, _e29.xy, i32(_e29.z)); + c_3 = _e33; _ = coord_9; - let _e35 = coord_9; - let _e40 = textureSampleBias(tex2DArray, samp, _e35.xy, i32(_e35.z), 2.0); - c_3 = _e40; + let _e36 = coord_9; + let _e41 = textureSampleBias(tex2DArray, samp, _e36.xy, i32(_e36.z), 2.0); + c_3 = _e41; _ = coord_9; _ = vec2(4.0); _ = vec2(4.0); - let _e46 = coord_9; - let _e54 = textureSampleGrad(tex2DArray, samp, _e46.xy, i32(_e46.z), vec2(4.0), vec2(4.0)); - c_3 = _e54; + let _e47 = coord_9; + let _e55 = textureSampleGrad(tex2DArray, samp, _e47.xy, i32(_e47.z), vec2(4.0), vec2(4.0)); + c_3 = _e55; _ = coord_9; _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e62 = coord_9; + let _e63 = coord_9; _ = vec2(5); - let _e72 = textureSampleGrad(tex2DArray, samp, _e62.xy, i32(_e62.z), vec2(4.0), vec2(4.0), vec2(5, 5)); - c_3 = _e72; + let _e73 = textureSampleGrad(tex2DArray, samp, _e63.xy, i32(_e63.z), vec2(4.0), vec2(4.0), vec2(5, 5)); + c_3 = _e73; _ = coord_9; - let _e75 = coord_9; - let _e80 = textureSampleLevel(tex2DArray, samp, _e75.xy, i32(_e75.z), 3.0); - c_3 = _e80; + let _e76 = coord_9; + let _e81 = textureSampleLevel(tex2DArray, samp, _e76.xy, i32(_e76.z), 3.0); + c_3 = _e81; _ = coord_9; _ = vec2(5); - let _e85 = coord_9; + let _e86 = coord_9; _ = vec2(5); - let _e92 = textureSampleLevel(tex2DArray, samp, _e85.xy, i32(_e85.z), 3.0, vec2(5, 5)); - c_3 = _e92; + let _e93 = textureSampleLevel(tex2DArray, samp, _e86.xy, i32(_e86.z), 3.0, vec2(5, 5)); + c_3 = _e93; _ = coord_9; _ = vec2(5); - let _e96 = coord_9; + let _e97 = coord_9; _ = vec2(5); - let _e102 = textureSample(tex2DArray, samp, _e96.xy, i32(_e96.z), vec2(5, 5)); - c_3 = _e102; + let _e103 = textureSample(tex2DArray, samp, _e97.xy, i32(_e97.z), vec2(5, 5)); + c_3 = _e103; _ = coord_9; _ = vec2(5); - let _e107 = coord_9; + let _e108 = coord_9; _ = vec2(5); - let _e114 = textureSampleBias(tex2DArray, samp, _e107.xy, i32(_e107.z), 2.0, vec2(5, 5)); - c_3 = _e114; - let _e115 = coord_9; - _ = vec3(_e115); - let _e118 = coord_9; - let _e119 = vec3(_e118); - let _e123 = textureLoad(tex2DArray, _e119.xy, _e119.z, 3); - c_3 = _e123; - let _e124 = coord_9; - _ = vec3(_e124); + let _e115 = textureSampleBias(tex2DArray, samp, _e108.xy, i32(_e108.z), 2.0, vec2(5, 5)); + c_3 = _e115; + let _e116 = coord_9; + _ = vec3(_e116); + let _e119 = coord_9; + let _e120 = vec3(_e119); + let _e124 = textureLoad(tex2DArray, _e120.xy, _e120.z, 3); + c_3 = _e124; + let _e125 = coord_9; + _ = vec3(_e125); _ = vec2(5); - let _e129 = coord_9; - let _e130 = vec3(_e129); + let _e130 = coord_9; + let _e131 = vec3(_e130); _ = vec2(5); - let _e136 = textureLoad(tex2DArray, _e130.xy, _e130.z, 3); - c_3 = _e136; + let _e137 = textureLoad(tex2DArray, _e131.xy, _e131.z, 3); + c_3 = _e137; return; } @@ -618,43 +618,43 @@ fn testTex2DArrayShadow(coord_10: vec3) { coord_11 = coord_10; let _e20 = textureDimensions(tex2DArrayShadow, 0); let _e23 = textureNumLayers(tex2DArrayShadow); - size2DArrayShadow = vec3(_e20.x, _e20.y, _e23); - let _e27 = coord_11; - _ = vec4(_e27.x, _e27.y, _e27.z, 1.0); - let _e33 = coord_11; - let _e38 = vec4(_e33.x, _e33.y, _e33.z, 1.0); - let _e43 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e38.xy, i32(_e38.z), _e38.w); - d_1 = _e43; - let _e44 = coord_11; - _ = vec4(_e44.x, _e44.y, _e44.z, 1.0); + size2DArrayShadow = vec3(vec3(_e20.x, _e20.y, _e23)); + let _e28 = coord_11; + _ = vec4(_e28.x, _e28.y, _e28.z, 1.0); + let _e34 = coord_11; + let _e39 = vec4(_e34.x, _e34.y, _e34.z, 1.0); + let _e44 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e39.xy, i32(_e39.z), _e39.w); + d_1 = _e44; + let _e45 = coord_11; + _ = vec4(_e45.x, _e45.y, _e45.z, 1.0); _ = vec2(4.0); _ = vec2(4.0); - let _e54 = coord_11; - let _e59 = vec4(_e54.x, _e54.y, _e54.z, 1.0); + let _e55 = coord_11; + let _e60 = vec4(_e55.x, _e55.y, _e55.z, 1.0); _ = vec2(4.0); _ = vec2(4.0); - let _e68 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e59.xy, i32(_e59.z), _e59.w); - d_1 = _e68; - let _e69 = coord_11; - _ = vec4(_e69.x, _e69.y, _e69.z, 1.0); + let _e69 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e60.xy, i32(_e60.z), _e60.w); + d_1 = _e69; + let _e70 = coord_11; + _ = vec4(_e70.x, _e70.y, _e70.z, 1.0); _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e81 = coord_11; - let _e86 = vec4(_e81.x, _e81.y, _e81.z, 1.0); + let _e82 = coord_11; + let _e87 = vec4(_e82.x, _e82.y, _e82.z, 1.0); _ = vec2(4.0); _ = vec2(4.0); _ = vec2(5); - let _e97 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e86.xy, i32(_e86.z), _e86.w, vec2(5, 5)); - d_1 = _e97; - let _e98 = coord_11; - _ = vec4(_e98.x, _e98.y, _e98.z, 1.0); + let _e98 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e87.xy, i32(_e87.z), _e87.w, vec2(5, 5)); + d_1 = _e98; + let _e99 = coord_11; + _ = vec4(_e99.x, _e99.y, _e99.z, 1.0); _ = vec2(5); - let _e106 = coord_11; - let _e111 = vec4(_e106.x, _e106.y, _e106.z, 1.0); + let _e107 = coord_11; + let _e112 = vec4(_e107.x, _e107.y, _e107.z, 1.0); _ = vec2(5); - let _e118 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e111.xy, i32(_e111.z), _e111.w, vec2(5, 5)); - d_1 = _e118; + let _e119 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e112.xy, i32(_e112.z), _e112.w, vec2(5, 5)); + d_1 = _e119; return; } @@ -665,25 +665,25 @@ fn testTexCube(coord_12: vec3) { coord_13 = coord_12; let _e20 = textureDimensions(texCube, 0); - sizeCube = _e20; + sizeCube = vec2(_e20); _ = coord_13; - let _e24 = coord_13; - let _e25 = textureSample(texCube, samp, _e24); - c_4 = _e25; + let _e25 = coord_13; + let _e26 = textureSample(texCube, samp, _e25); + c_4 = _e26; _ = coord_13; - let _e28 = coord_13; - let _e30 = textureSampleBias(texCube, samp, _e28, 2.0); - c_4 = _e30; + let _e29 = coord_13; + let _e31 = textureSampleBias(texCube, samp, _e29, 2.0); + c_4 = _e31; _ = coord_13; _ = vec3(4.0); _ = vec3(4.0); - let _e36 = coord_13; - let _e41 = textureSampleGrad(texCube, samp, _e36, vec3(4.0), vec3(4.0)); - c_4 = _e41; + let _e37 = coord_13; + let _e42 = textureSampleGrad(texCube, samp, _e37, vec3(4.0), vec3(4.0)); + c_4 = _e42; _ = coord_13; - let _e44 = coord_13; - let _e46 = textureSampleLevel(texCube, samp, _e44, 3.0); - c_4 = _e46; + let _e45 = coord_13; + let _e47 = textureSampleLevel(texCube, samp, _e45, 3.0); + c_4 = _e47; return; } @@ -694,23 +694,23 @@ fn testTexCubeShadow(coord_14: vec3) { coord_15 = coord_14; let _e20 = textureDimensions(texCubeShadow, 0); - sizeCubeShadow = _e20; - let _e23 = coord_15; - _ = vec4(_e23.x, _e23.y, _e23.z, 1.0); - let _e29 = coord_15; - let _e34 = vec4(_e29.x, _e29.y, _e29.z, 1.0); - let _e37 = textureSampleCompare(texCubeShadow, sampShadow, _e34.xyz, _e34.w); - d_2 = _e37; - let _e38 = coord_15; - _ = vec4(_e38.x, _e38.y, _e38.z, 1.0); + sizeCubeShadow = vec2(_e20); + let _e24 = coord_15; + _ = vec4(_e24.x, _e24.y, _e24.z, 1.0); + let _e30 = coord_15; + let _e35 = vec4(_e30.x, _e30.y, _e30.z, 1.0); + let _e38 = textureSampleCompare(texCubeShadow, sampShadow, _e35.xyz, _e35.w); + d_2 = _e38; + let _e39 = coord_15; + _ = vec4(_e39.x, _e39.y, _e39.z, 1.0); _ = vec3(4.0); _ = vec3(4.0); - let _e48 = coord_15; - let _e53 = vec4(_e48.x, _e48.y, _e48.z, 1.0); + let _e49 = coord_15; + let _e54 = vec4(_e49.x, _e49.y, _e49.z, 1.0); _ = vec3(4.0); _ = vec3(4.0); - let _e60 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e53.xyz, _e53.w); - d_2 = _e60; + let _e61 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e54.xyz, _e54.w); + d_2 = _e61; return; } @@ -722,25 +722,25 @@ fn testTexCubeArray(coord_16: vec4) { coord_17 = coord_16; let _e20 = textureDimensions(texCubeArray, 0); let _e23 = textureNumLayers(texCubeArray); - sizeCubeArray = vec3(_e20.x, _e20.y, _e23); + sizeCubeArray = vec3(vec3(_e20.x, _e20.y, _e23)); _ = coord_17; - let _e28 = coord_17; - let _e32 = textureSample(texCubeArray, samp, _e28.xyz, i32(_e28.w)); - c_5 = _e32; + let _e29 = coord_17; + let _e33 = textureSample(texCubeArray, samp, _e29.xyz, i32(_e29.w)); + c_5 = _e33; _ = coord_17; - let _e35 = coord_17; - let _e40 = textureSampleBias(texCubeArray, samp, _e35.xyz, i32(_e35.w), 2.0); - c_5 = _e40; + let _e36 = coord_17; + let _e41 = textureSampleBias(texCubeArray, samp, _e36.xyz, i32(_e36.w), 2.0); + c_5 = _e41; _ = coord_17; _ = vec3(4.0); _ = vec3(4.0); - let _e46 = coord_17; - let _e54 = textureSampleGrad(texCubeArray, samp, _e46.xyz, i32(_e46.w), vec3(4.0), vec3(4.0)); - c_5 = _e54; + let _e47 = coord_17; + let _e55 = textureSampleGrad(texCubeArray, samp, _e47.xyz, i32(_e47.w), vec3(4.0), vec3(4.0)); + c_5 = _e55; _ = coord_17; - let _e57 = coord_17; - let _e62 = textureSampleLevel(texCubeArray, samp, _e57.xyz, i32(_e57.w), 3.0); - c_5 = _e62; + let _e58 = coord_17; + let _e63 = textureSampleLevel(texCubeArray, samp, _e58.xyz, i32(_e58.w), 3.0); + c_5 = _e63; return; } @@ -752,11 +752,11 @@ fn testTexCubeArrayShadow(coord_18: vec4) { coord_19 = coord_18; let _e20 = textureDimensions(texCubeArrayShadow, 0); let _e23 = textureNumLayers(texCubeArrayShadow); - sizeCubeArrayShadow = vec3(_e20.x, _e20.y, _e23); + sizeCubeArrayShadow = vec3(vec3(_e20.x, _e20.y, _e23)); _ = coord_19; - let _e29 = coord_19; - let _e34 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e29.xyz, i32(_e29.w), 1.0); - d_3 = _e34; + let _e30 = coord_19; + let _e35 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e30.xyz, i32(_e30.w), 1.0); + d_3 = _e35; return; } @@ -767,123 +767,123 @@ fn testTex3D(coord_20: vec3) { coord_21 = coord_20; let _e20 = textureDimensions(tex3D, 0); - size3D = _e20; + size3D = vec3(_e20); _ = coord_21; - let _e24 = coord_21; - let _e25 = textureSample(tex3D, samp, _e24); - c_6 = _e25; + let _e25 = coord_21; + let _e26 = textureSample(tex3D, samp, _e25); + c_6 = _e26; _ = coord_21; - let _e28 = coord_21; - let _e30 = textureSampleBias(tex3D, samp, _e28, 2.0); - c_6 = _e30; - let _e31 = coord_21; - _ = vec4(_e31.x, _e31.y, _e31.z, 6.0); - let _e37 = coord_21; - let _e42 = vec4(_e37.x, _e37.y, _e37.z, 6.0); - let _e47 = textureSample(tex3D, samp, (_e42.xyz / vec3(_e42.w))); - c_6 = _e47; - let _e48 = coord_21; - _ = vec4(_e48.x, _e48.y, _e48.z, 6.0); - let _e55 = coord_21; - let _e60 = vec4(_e55.x, _e55.y, _e55.z, 6.0); - let _e66 = textureSampleBias(tex3D, samp, (_e60.xyz / vec3(_e60.w)), 2.0); - c_6 = _e66; - let _e67 = coord_21; - _ = vec4(_e67.x, _e67.y, _e67.z, 6.0); + let _e29 = coord_21; + let _e31 = textureSampleBias(tex3D, samp, _e29, 2.0); + c_6 = _e31; + let _e32 = coord_21; + _ = vec4(_e32.x, _e32.y, _e32.z, 6.0); + let _e38 = coord_21; + let _e43 = vec4(_e38.x, _e38.y, _e38.z, 6.0); + let _e48 = textureSample(tex3D, samp, (_e43.xyz / vec3(_e43.w))); + c_6 = _e48; + let _e49 = coord_21; + _ = vec4(_e49.x, _e49.y, _e49.z, 6.0); + let _e56 = coord_21; + let _e61 = vec4(_e56.x, _e56.y, _e56.z, 6.0); + let _e67 = textureSampleBias(tex3D, samp, (_e61.xyz / vec3(_e61.w)), 2.0); + c_6 = _e67; + let _e68 = coord_21; + _ = vec4(_e68.x, _e68.y, _e68.z, 6.0); _ = vec3(5); - let _e75 = coord_21; - let _e80 = vec4(_e75.x, _e75.y, _e75.z, 6.0); + let _e76 = coord_21; + let _e81 = vec4(_e76.x, _e76.y, _e76.z, 6.0); _ = vec3(5); - let _e87 = textureSample(tex3D, samp, (_e80.xyz / vec3(_e80.w)), vec3(5, 5, 5)); - c_6 = _e87; - let _e88 = coord_21; - _ = vec4(_e88.x, _e88.y, _e88.z, 6.0); + let _e88 = textureSample(tex3D, samp, (_e81.xyz / vec3(_e81.w)), vec3(5, 5, 5)); + c_6 = _e88; + let _e89 = coord_21; + _ = vec4(_e89.x, _e89.y, _e89.z, 6.0); _ = vec3(5); - let _e97 = coord_21; - let _e102 = vec4(_e97.x, _e97.y, _e97.z, 6.0); + let _e98 = coord_21; + let _e103 = vec4(_e98.x, _e98.y, _e98.z, 6.0); _ = vec3(5); - let _e110 = textureSampleBias(tex3D, samp, (_e102.xyz / vec3(_e102.w)), 2.0, vec3(5, 5, 5)); - c_6 = _e110; - let _e111 = coord_21; - _ = vec4(_e111.x, _e111.y, _e111.z, 6.0); - let _e118 = coord_21; - let _e123 = vec4(_e118.x, _e118.y, _e118.z, 6.0); - let _e129 = textureSampleLevel(tex3D, samp, (_e123.xyz / vec3(_e123.w)), 3.0); - c_6 = _e129; - let _e130 = coord_21; - _ = vec4(_e130.x, _e130.y, _e130.z, 6.0); + let _e111 = textureSampleBias(tex3D, samp, (_e103.xyz / vec3(_e103.w)), 2.0, vec3(5, 5, 5)); + c_6 = _e111; + let _e112 = coord_21; + _ = vec4(_e112.x, _e112.y, _e112.z, 6.0); + let _e119 = coord_21; + let _e124 = vec4(_e119.x, _e119.y, _e119.z, 6.0); + let _e130 = textureSampleLevel(tex3D, samp, (_e124.xyz / vec3(_e124.w)), 3.0); + c_6 = _e130; + let _e131 = coord_21; + _ = vec4(_e131.x, _e131.y, _e131.z, 6.0); _ = vec3(5); - let _e139 = coord_21; - let _e144 = vec4(_e139.x, _e139.y, _e139.z, 6.0); + let _e140 = coord_21; + let _e145 = vec4(_e140.x, _e140.y, _e140.z, 6.0); _ = vec3(5); - let _e152 = textureSampleLevel(tex3D, samp, (_e144.xyz / vec3(_e144.w)), 3.0, vec3(5, 5, 5)); - c_6 = _e152; - let _e153 = coord_21; - _ = vec4(_e153.x, _e153.y, _e153.z, 6.0); + let _e153 = textureSampleLevel(tex3D, samp, (_e145.xyz / vec3(_e145.w)), 3.0, vec3(5, 5, 5)); + c_6 = _e153; + let _e154 = coord_21; + _ = vec4(_e154.x, _e154.y, _e154.z, 6.0); _ = vec3(4.0); _ = vec3(4.0); - let _e163 = coord_21; - let _e168 = vec4(_e163.x, _e163.y, _e163.z, 6.0); - let _e177 = textureSampleGrad(tex3D, samp, (_e168.xyz / vec3(_e168.w)), vec3(4.0), vec3(4.0)); - c_6 = _e177; - let _e178 = coord_21; - _ = vec4(_e178.x, _e178.y, _e178.z, 6.0); + let _e164 = coord_21; + let _e169 = vec4(_e164.x, _e164.y, _e164.z, 6.0); + let _e178 = textureSampleGrad(tex3D, samp, (_e169.xyz / vec3(_e169.w)), vec3(4.0), vec3(4.0)); + c_6 = _e178; + let _e179 = coord_21; + _ = vec4(_e179.x, _e179.y, _e179.z, 6.0); _ = vec3(4.0); _ = vec3(4.0); _ = vec3(5); - let _e190 = coord_21; - let _e195 = vec4(_e190.x, _e190.y, _e190.z, 6.0); + let _e191 = coord_21; + let _e196 = vec4(_e191.x, _e191.y, _e191.z, 6.0); _ = vec3(5); - let _e206 = textureSampleGrad(tex3D, samp, (_e195.xyz / vec3(_e195.w)), vec3(4.0), vec3(4.0), vec3(5, 5, 5)); - c_6 = _e206; + let _e207 = textureSampleGrad(tex3D, samp, (_e196.xyz / vec3(_e196.w)), vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + c_6 = _e207; _ = coord_21; _ = vec3(4.0); _ = vec3(4.0); - let _e212 = coord_21; - let _e217 = textureSampleGrad(tex3D, samp, _e212, vec3(4.0), vec3(4.0)); - c_6 = _e217; + let _e213 = coord_21; + let _e218 = textureSampleGrad(tex3D, samp, _e213, vec3(4.0), vec3(4.0)); + c_6 = _e218; _ = coord_21; _ = vec3(4.0); _ = vec3(4.0); _ = vec3(5); - let _e225 = coord_21; + let _e226 = coord_21; _ = vec3(5); - let _e232 = textureSampleGrad(tex3D, samp, _e225, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); - c_6 = _e232; + let _e233 = textureSampleGrad(tex3D, samp, _e226, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + c_6 = _e233; _ = coord_21; - let _e235 = coord_21; - let _e237 = textureSampleLevel(tex3D, samp, _e235, 3.0); - c_6 = _e237; + let _e236 = coord_21; + let _e238 = textureSampleLevel(tex3D, samp, _e236, 3.0); + c_6 = _e238; _ = coord_21; _ = vec3(5); - let _e242 = coord_21; + let _e243 = coord_21; _ = vec3(5); - let _e246 = textureSampleLevel(tex3D, samp, _e242, 3.0, vec3(5, 5, 5)); - c_6 = _e246; + let _e247 = textureSampleLevel(tex3D, samp, _e243, 3.0, vec3(5, 5, 5)); + c_6 = _e247; _ = coord_21; _ = vec3(5); - let _e250 = coord_21; + let _e251 = coord_21; _ = vec3(5); - let _e253 = textureSample(tex3D, samp, _e250, vec3(5, 5, 5)); - c_6 = _e253; + let _e254 = textureSample(tex3D, samp, _e251, vec3(5, 5, 5)); + c_6 = _e254; _ = coord_21; _ = vec3(5); - let _e258 = coord_21; + let _e259 = coord_21; _ = vec3(5); - let _e262 = textureSampleBias(tex3D, samp, _e258, 2.0, vec3(5, 5, 5)); - c_6 = _e262; - let _e263 = coord_21; - _ = vec3(_e263); - let _e266 = coord_21; - let _e269 = textureLoad(tex3D, vec3(_e266), 3); - c_6 = _e269; - let _e270 = coord_21; - _ = vec3(_e270); + let _e263 = textureSampleBias(tex3D, samp, _e259, 2.0, vec3(5, 5, 5)); + c_6 = _e263; + let _e264 = coord_21; + _ = vec3(_e264); + let _e267 = coord_21; + let _e270 = textureLoad(tex3D, vec3(_e267), 3); + c_6 = _e270; + let _e271 = coord_21; + _ = vec3(_e271); _ = vec3(5); - let _e275 = coord_21; + let _e276 = coord_21; _ = vec3(5); - let _e280 = textureLoad(tex3D, vec3(_e275), 3); - c_6 = _e280; + let _e281 = textureLoad(tex3D, vec3(_e276), 3); + c_6 = _e281; return; } @@ -894,12 +894,12 @@ fn testTex2DMS(coord_22: vec2) { coord_23 = coord_22; let _e18 = textureDimensions(tex2DMS); - size2DMS = _e18; - let _e21 = coord_23; - _ = vec2(_e21); - let _e24 = coord_23; - let _e27 = textureLoad(tex2DMS, vec2(_e24), 3); - c_7 = _e27; + size2DMS = vec2(_e18); + let _e22 = coord_23; + _ = vec2(_e22); + let _e25 = coord_23; + let _e28 = textureLoad(tex2DMS, vec2(_e25), 3); + c_7 = _e28; return; } @@ -911,13 +911,13 @@ fn testTex2DMSArray(coord_24: vec3) { coord_25 = coord_24; let _e18 = textureDimensions(tex2DMSArray); let _e21 = textureNumLayers(tex2DMSArray); - size2DMSArray = vec3(_e18.x, _e18.y, _e21); - let _e25 = coord_25; - _ = vec3(_e25); - let _e28 = coord_25; - let _e29 = vec3(_e28); - let _e33 = textureLoad(tex2DMSArray, _e29.xy, _e29.z, 3); - c_8 = _e33; + size2DMSArray = vec3(vec3(_e18.x, _e18.y, _e21)); + let _e26 = coord_25; + _ = vec3(_e26); + let _e29 = coord_25; + let _e30 = vec3(_e29); + let _e34 = textureLoad(tex2DMSArray, _e30.xy, _e30.z, 3); + c_8 = _e34; return; } diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs index 0700bce09..254590928 100644 --- a/tests/spirv-capabilities.rs +++ b/tests/spirv-capabilities.rs @@ -94,7 +94,7 @@ fn image_queries() { require( &[Ca::ImageQuery], r#" - fn f(i: texture_2d) -> vec2 { + fn f(i: texture_2d) -> vec2 { return textureDimensions(i); } "#, @@ -102,7 +102,7 @@ fn image_queries() { require( &[Ca::ImageQuery], r#" - fn f(i: texture_2d_array) -> i32 { + fn f(i: texture_2d_array) -> u32 { return textureNumLayers(i); } "#, @@ -110,7 +110,7 @@ fn image_queries() { require( &[Ca::ImageQuery], r#" - fn f(i: texture_2d) -> i32 { + fn f(i: texture_2d) -> u32 { return textureNumLevels(i); } "#, @@ -118,7 +118,7 @@ fn image_queries() { require( &[Ca::ImageQuery], r#" - fn f(i: texture_multisampled_2d) -> i32 { + fn f(i: texture_multisampled_2d) -> u32 { return textureNumSamples(i); } "#, From 568d7c4c136dada369ef7f59ee8414a263d6c7b2 Mon Sep 17 00:00:00 2001 From: Josh Groves Date: Wed, 15 Feb 2023 21:24:49 -0330 Subject: [PATCH 1939/2212] Require LF for snapshots (#2253) --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..622c348d1 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +tests/out/**/* text eol=lf From df567a94ebbb553f59613ec4dfa44b40248a5d7a Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 16 Feb 2023 21:42:26 +0100 Subject: [PATCH 1940/2212] add `Capabilities::MULTIVIEW` --- src/valid/interface.rs | 1 + src/valid/mod.rs | 2 ++ tests/in/multiview.param.ron | 1 + tests/in/multiview_webgl.param.ron | 1 + 4 files changed, 5 insertions(+) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 67130ddc6..727480b15 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -140,6 +140,7 @@ impl VaryingContext<'_> { Bi::ClipDistance => Capabilities::CLIP_DISTANCE, Bi::CullDistance => Capabilities::CULL_DISTANCE, Bi::PrimitiveIndex => Capabilities::PRIMITIVE_INDEX, + Bi::ViewIndex => Capabilities::MULTIVIEW, _ => Capabilities::empty(), }; if !self.capabilities.contains(required) { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 033d96781..a4c94bac2 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -106,6 +106,8 @@ bitflags::bitflags! { const CULL_DISTANCE = 0x80; /// Support for 16-bit normalized storage texture formats. const STORAGE_TEXTURE_16BIT_NORM_FORMATS = 0x100; + /// Support for [`BuiltIn::ViewIndex`]. + const MULTIVIEW = 0x200; } } diff --git a/tests/in/multiview.param.ron b/tests/in/multiview.param.ron index 35dd990fd..69390f9fd 100644 --- a/tests/in/multiview.param.ron +++ b/tests/in/multiview.param.ron @@ -1,3 +1,4 @@ ( + god_mode: true, glsl_multiview: Some(2), ) diff --git a/tests/in/multiview_webgl.param.ron b/tests/in/multiview_webgl.param.ron index a8bc09664..98b7fd733 100644 --- a/tests/in/multiview_webgl.param.ron +++ b/tests/in/multiview_webgl.param.ron @@ -1,4 +1,5 @@ ( + god_mode: true, glsl: ( version: Embedded ( version: 300, From 964d9204bca95d9127df68fd6d02cb5f1496fc99 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 16 Feb 2023 21:44:06 +0100 Subject: [PATCH 1941/2212] add `Capabilities::EARLY_DEPTH_TEST` --- src/valid/interface.rs | 14 ++++++++++++-- src/valid/mod.rs | 2 ++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 727480b15..41f266612 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -509,8 +509,18 @@ impl super::Validator { mod_info: &ModuleInfo, ) -> Result> { #[cfg(feature = "validate")] - if ep.early_depth_test.is_some() && ep.stage != crate::ShaderStage::Fragment { - return Err(EntryPointError::UnexpectedEarlyDepthTest.with_span()); + if ep.early_depth_test.is_some() { + let required = Capabilities::EARLY_DEPTH_TEST; + if !self.capabilities.contains(required) { + return Err( + EntryPointError::Result(VaryingError::UnsupportedCapability(required)) + .with_span(), + ); + } + + if ep.stage != crate::ShaderStage::Fragment { + return Err(EntryPointError::UnexpectedEarlyDepthTest.with_span()); + } } #[cfg(feature = "validate")] diff --git a/src/valid/mod.rs b/src/valid/mod.rs index a4c94bac2..ab4d81cb1 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -108,6 +108,8 @@ bitflags::bitflags! { const STORAGE_TEXTURE_16BIT_NORM_FORMATS = 0x100; /// Support for [`BuiltIn::ViewIndex`]. const MULTIVIEW = 0x200; + /// Support for `early_depth_test`. + const EARLY_DEPTH_TEST = 0x400; } } From cc3a8ac73773e2223c3d45fbc1b22607026e2ec0 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 16 Feb 2023 21:44:29 +0100 Subject: [PATCH 1942/2212] add `Capabilities::MULTISAMPLED_SHADING` --- benches/criterion.rs | 2 +- fuzz/fuzz_targets/ir.rs | 2 +- src/valid/interface.rs | 9 +++++++++ src/valid/mod.rs | 9 ++++++++- tests/snapshots.rs | 4 ++-- tests/wgsl-errors.rs | 2 +- 6 files changed, 22 insertions(+), 6 deletions(-) diff --git a/benches/criterion.rs b/benches/criterion.rs index ad00cb59e..624744555 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -149,7 +149,7 @@ fn backends(c: &mut Criterion) { let inputs = { let mut validator = naga::valid::Validator::new( naga::valid::ValidationFlags::empty(), - naga::valid::Capabilities::empty(), + naga::valid::Capabilities::default(), ); let input_modules = gather_modules(); input_modules diff --git a/fuzz/fuzz_targets/ir.rs b/fuzz/fuzz_targets/ir.rs index 86b7a6aa6..ae1d90747 100644 --- a/fuzz/fuzz_targets/ir.rs +++ b/fuzz/fuzz_targets/ir.rs @@ -5,6 +5,6 @@ fuzz_target!(|module: naga::Module| { use naga::valid as v; // Check if the module validates without errors. //TODO: may also fuzz the flags and capabilities - let mut validator = v::Validator::new(v::ValidationFlags::all(), v::Capabilities::empty()); + let mut validator = v::Validator::new(v::ValidationFlags::all(), v::Capabilities::default()); let _result = validator.validate(&module); }); diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 41f266612..7ba60515c 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -141,6 +141,7 @@ impl VaryingContext<'_> { Bi::CullDistance => Capabilities::CULL_DISTANCE, Bi::PrimitiveIndex => Capabilities::PRIMITIVE_INDEX, Bi::ViewIndex => Capabilities::MULTIVIEW, + Bi::SampleIndex => Capabilities::MULTISAMPLED_SHADING, _ => Capabilities::empty(), }; if !self.capabilities.contains(required) { @@ -312,6 +313,14 @@ impl VaryingContext<'_> { // qualifiers, so we won't complain about that here. let _ = sampling; + let required = match sampling { + Some(crate::Sampling::Sample) => Capabilities::MULTISAMPLED_SHADING, + _ => Capabilities::empty(), + }; + if !self.capabilities.contains(required) { + return Err(VaryingError::UnsupportedCapability(required)); + } + match ty_inner.scalar_kind() { Some(crate::ScalarKind::Float) => { if needs_interpolation && interpolation.is_none() { diff --git a/src/valid/mod.rs b/src/valid/mod.rs index ab4d81cb1..9d9c3f885 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -84,7 +84,6 @@ impl Default for ValidationFlags { bitflags::bitflags! { /// Allowed IR capabilities. #[must_use] - #[derive(Default)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct Capabilities: u16 { @@ -110,6 +109,14 @@ bitflags::bitflags! { const MULTIVIEW = 0x200; /// Support for `early_depth_test`. const EARLY_DEPTH_TEST = 0x400; + /// Support for [`Builtin::SampleIndex`] and [`Sampling::Sample`]. + const MULTISAMPLED_SHADING = 0x800; + } +} + +impl Default for Capabilities { + fn default() -> Self { + Self::MULTISAMPLED_SHADING } } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index cc2b30055..7fea12200 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -98,7 +98,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let capabilities = if params.god_mode { naga::valid::Capabilities::all() } else { - naga::valid::Capabilities::empty() + naga::valid::Capabilities::default() }; let dest = PathBuf::from(root).join(BASE_DIR_OUT); @@ -589,7 +589,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { check_targets(&module, name, targets); naga::valid::Validator::new( naga::valid::ValidationFlags::all(), - naga::valid::Capabilities::empty(), + naga::valid::Capabilities::default(), ) .validate(&module) .unwrap(); diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index f7c86b403..d76252ced 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -903,7 +903,7 @@ fn validation_error(source: &str) -> Result Date: Thu, 16 Feb 2023 15:18:13 -0800 Subject: [PATCH 1943/2212] [glsl-in]: Document some fields of `naga::front::glsl::context::Context`. (#2244) --- src/front/glsl/builtins.rs | 58 +++++++++++++-------------- src/front/glsl/context.rs | 22 ++++++++-- src/front/glsl/functions.rs | 4 +- src/front/glsl/mod.rs | 4 +- src/front/glsl/parser/declarations.rs | 2 +- src/front/glsl/parser/functions.rs | 8 ++-- 6 files changed, 57 insertions(+), 41 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 5928e86c5..ef98e47ea 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -536,7 +536,7 @@ fn inject_standard_builtins( | "floatBitsToInt" | "floatBitsToUint" | "dFdx" | "dFdxFine" | "dFdxCoarse" | "dFdy" | "dFdyFine" | "dFdyCoarse" | "fwidth" | "fwidthFine" | "fwidthCoarse" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b100 { let size = match bits { 0b00 => None, @@ -587,7 +587,7 @@ fn inject_standard_builtins( } "intBitsToFloat" | "uintBitsToFloat" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b100 { let size = match bits { 0b00 => None, @@ -611,7 +611,7 @@ fn inject_standard_builtins( } "pow" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b100 { let size = match bits { 0b00 => None, @@ -633,7 +633,7 @@ fn inject_standard_builtins( } "abs" | "sign" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims // bit 2 - float/sint for bits in 0..0b1000 { let size = match bits & 0b11 { @@ -682,7 +682,7 @@ fn inject_standard_builtins( // bits layout // bit 0 - int/uint - // bit 1 trough 2 - dims + // bit 1 through 2 - dims for bits in 0..0b1000 { let kind = match bits & 0b1 { 0b0 => Sk::Sint, @@ -796,7 +796,7 @@ fn inject_standard_builtins( "atan" => { // bits layout // bit 0 - atan/atan2 - // bit 1 trough 2 - dims + // bit 1 through 2 - dims for bits in 0..0b1000 { let fun = match bits & 0b1 { 0b0 => MathFunction::Atan, @@ -827,7 +827,7 @@ fn inject_standard_builtins( } "all" | "any" | "not" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b11 { let size = match bits { 0b00 => VectorSize::Bi, @@ -916,8 +916,8 @@ fn inject_standard_builtins( } "min" | "max" => { // bits layout - // bit 0 trough 1 - scalar kind - // bit 2 trough 4 - dims + // bit 0 through 1 - scalar kind + // bit 2 through 4 - dims for bits in 0..0b11100 { let kind = match bits & 0b11 { 0b00 => Sk::Float, @@ -957,8 +957,8 @@ fn inject_standard_builtins( } "mix" => { // bits layout - // bit 0 trough 1 - dims - // bit 2 trough 4 - types + // bit 0 through 1 - dims + // bit 2 through 4 - types // // 0b10011 is the last element since splatted single elements // were already added @@ -1002,8 +1002,8 @@ fn inject_standard_builtins( } "clamp" => { // bits layout - // bit 0 trough 1 - float/int/uint - // bit 2 trough 3 - dims + // bit 0 through 1 - float/int/uint + // bit 2 through 3 - dims // bit 4 - splatted // // 0b11010 is the last element since splatted single elements @@ -1053,7 +1053,7 @@ fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Mod match name { "abs" | "sign" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b100 { let size = match bits { 0b00 => None, @@ -1080,7 +1080,7 @@ fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Mod } "min" | "max" => { // bits layout - // bit 0 trough 2 - dims + // bit 0 through 2 - dims for bits in 0..0b111 { let (size, second_size) = match bits { 0b000 => (None, None), @@ -1115,8 +1115,8 @@ fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Mod } "mix" => { // bits layout - // bit 0 trough 1 - dims - // bit 2 trough 3 - splatted/boolean + // bit 0 through 1 - dims + // bit 2 through 3 - splatted/boolean // // 0b1010 is the last element since splatted with single elements // is equal to normal single elements @@ -1159,7 +1159,7 @@ fn inject_double_builtin(declaration: &mut FunctionDeclaration, module: &mut Mod } "clamp" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims // bit 2 - splatted // // 0b110 is the last element since splatted with single elements @@ -1231,7 +1231,7 @@ fn inject_common_builtin( "ceil" | "round" | "roundEven" | "floor" | "fract" | "trunc" | "sqrt" | "inversesqrt" | "normalize" | "length" | "isinf" | "isnan" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b100 { let size = match bits { 0b00 => None, @@ -1272,7 +1272,7 @@ fn inject_common_builtin( } "dot" | "reflect" | "distance" | "ldexp" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b100 { let size = match bits { 0b00 => None, @@ -1307,7 +1307,7 @@ fn inject_common_builtin( } "transpose" => { // bits layout - // bit 0 trough 3 - dims + // bit 0 through 3 - dims for bits in 0..0b1001 { let (rows, columns) = match bits { 0b0000 => (VectorSize::Bi, VectorSize::Bi), @@ -1333,7 +1333,7 @@ fn inject_common_builtin( } "inverse" | "determinant" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b11 { let (rows, columns) = match bits { 0b00 => (VectorSize::Bi, VectorSize::Bi), @@ -1359,7 +1359,7 @@ fn inject_common_builtin( } "mod" | "step" => { // bits layout - // bit 0 trough 2 - dims + // bit 0 through 2 - dims for bits in 0..0b111 { let (size, second_size) = match bits { 0b000 => (None, None), @@ -1404,7 +1404,7 @@ fn inject_common_builtin( } "modf" | "frexp" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b100 { let size = match bits { 0b00 => None, @@ -1478,7 +1478,7 @@ fn inject_common_builtin( } "outerProduct" => { // bits layout - // bit 0 trough 3 - dims + // bit 0 through 3 - dims for bits in 0..0b1001 { let (size1, size2) = match bits { 0b0000 => (VectorSize::Bi, VectorSize::Bi), @@ -1512,7 +1512,7 @@ fn inject_common_builtin( } "faceforward" | "fma" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b100 { let size = match bits { 0b00 => None, @@ -1545,7 +1545,7 @@ fn inject_common_builtin( } "refract" => { // bits layout - // bit 0 trough 1 - dims + // bit 0 through 1 - dims for bits in 0..0b100 { let size = match bits { 0b00 => None, @@ -1580,7 +1580,7 @@ fn inject_common_builtin( } "smoothstep" => { // bit 0 - splatted - // bit 1 trough 2 - dims + // bit 1 through 2 - dims for bits in 0..0b1000 { let splatted = bits & 0b1 == 0b1; let size = match bits >> 1 { @@ -2391,7 +2391,7 @@ pub fn sampled_to_depth( // Copy the handle to allow borrowing the `ctx` again let ty = *ty; - // If the image was passed trough a function argument we also need to change + // If the image was passed through a function argument we also need to change // the corresponding parameter if let Expression::FunctionArgument(i) = ctx[image] { ctx.parameters[i as usize] = ty; diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index d7a56051b..6d33ef9f6 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -47,8 +47,24 @@ impl ExprPos { pub struct Context { pub expressions: Arena, pub locals: Arena, + + /// The [`FunctionArgument`]s for the final [`crate::Function`]. + /// + /// Parameters with the `out` and `inout` qualifiers have [`Pointer`] types + /// here. For example, an `inout vec2 a` argument would be a [`Pointer`] to + /// a [`Vector`]. + /// + /// [`Pointer`]: crate::TypeInner::Pointer + /// [`Vector`]: crate::TypeInner::Vector pub arguments: Vec, + /// The parameter types given in the source code. + /// + /// The `out` and `inout` qualifiers don't affect the types that appear + /// here. For example, an `inout vec2 a` argument would simply be a + /// [`Vector`], not a pointer to one. + /// + /// [`Vector`]: crate::TypeInner::Vector pub parameters: Vec>, pub parameters_info: Vec, @@ -1019,7 +1035,7 @@ impl Context { } ExprPos::AccessBase { constant_index } => { // If the index isn't constant all accesses backed by a constant base need - // to be done trough a proxy local variable, since constants have a non + // to be done through a proxy local variable, since constants have a non // pointer type which is required for dynamic indexing if !constant_index { if let Some((constant, ty)) = var.constant { @@ -1575,11 +1591,11 @@ impl Index> for Context { /// Helper struct passed when parsing expressions /// -/// This struct should only be obtained trough [`stmt_ctx`](Context::stmt_ctx) +/// This struct should only be obtained through [`stmt_ctx`](Context::stmt_ctx) /// and only one of these may be active at any time per context. #[derive(Debug)] pub struct StmtContext { - /// A arena of high level expressions which can be lowered trough a + /// A arena of high level expressions which can be lowered through a /// [`Context`](Context) to naga's [`Expression`](crate::Expression)s pub hir_exprs: Arena, } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 7c6408674..1f24d404d 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -660,7 +660,7 @@ impl Frontend { // conversions used for querying the best overload let mut new_conversions = vec![Conversion::None; args.len()]; - // Loop trough the overload parameters and check if the current overload is better + // Loop through the overload parameters and check if the current overload is better // compared to the previous best overload. for (i, overload_parameter) in overload.parameters.iter().enumerate() { let call_argument = &args[i]; @@ -875,7 +875,7 @@ impl Frontend { let mut arguments = Vec::with_capacity(args.len()); let mut proxy_writes = Vec::new(); - // Iterate trough the function call arguments applying transformations as needed + // Iterate through the function call arguments applying transformations as needed for (((parameter_info, call_argument), expr), parameter) in parameters_info .iter() .zip(&args) diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index b799293e5..a1aa4622d 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -73,10 +73,10 @@ impl From for Options { /// stored in the shader [`Module`](Module). #[derive(Debug)] pub struct ShaderMetadata { - /// The GLSL version specified in the shader trough the use of the + /// The GLSL version specified in the shader through the use of the /// `#version` preprocessor directive. pub version: u16, - /// The GLSL profile specified in the shader trough the use of the + /// The GLSL profile specified in the shader through the use of the /// `#version` preprocessor directive. pub profile: Profile, /// The shader stage in the pipeline, passed to the [`parse`](Frontend::parse) diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 3ae22559a..9085469dd 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -388,7 +388,7 @@ impl<'source> ParsingContext<'source> { // If program execution has reached here then this will be a // init_declarator_list - // token_falltrough will have a token that was already bumped + // token_fallthrough will have a token that was already bumped if let Some(ty) = ty { let mut ctx = DeclarationContext { qualifiers, diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 93988f82f..e6c86ad6d 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -286,7 +286,7 @@ impl<'source> ParsingContext<'source> { // to have any cases. if let Some(case) = cases.last_mut() { // GLSL requires that the last case not be empty, so we check - // that here and produce an error otherwise (fall_trough must + // that here and produce an error otherwise (fall_through must // also be checked because `break`s count as statements but // they aren't added to the body) if case.body.is_empty() && case.fall_through { @@ -299,9 +299,9 @@ impl<'source> ParsingContext<'source> { } // GLSL allows the last case to not have any `break` statement, - // this would mark it as fall trough but naga's IR requires that - // the last case must not be fall trough, so we mark need to mark - // the last case as not fall trough always. + // this would mark it as fall through but naga's IR requires that + // the last case must not be fall through, so we mark need to mark + // the last case as not fall through always. case.fall_through = false; } From f48b6bf2a7335135b8fedafe2cc36a047ce6ad8d Mon Sep 17 00:00:00 2001 From: Josh Groves Date: Thu, 16 Feb 2023 20:03:24 -0330 Subject: [PATCH 1944/2212] Skip `invariant` for `gl_FragCoord` on WebGL2 (#2254) --- src/back/glsl/mod.rs | 26 +++++++++++++++---- tests/in/invariant.param.ron | 11 ++++++++ tests/in/invariant.wgsl | 7 +++++ .../glsl/invariant.frag_main.Fragment.glsl | 11 ++++++++ tests/out/glsl/invariant.fs.Fragment.glsl | 11 ++++++++ tests/out/glsl/invariant.vs.Vertex.glsl | 12 +++++++++ tests/snapshots.rs | 1 + 7 files changed, 74 insertions(+), 5 deletions(-) create mode 100644 tests/in/invariant.param.ron create mode 100644 tests/in/invariant.wgsl create mode 100644 tests/out/glsl/invariant.frag_main.Fragment.glsl create mode 100644 tests/out/glsl/invariant.fs.Fragment.glsl create mode 100644 tests/out/glsl/invariant.vs.Vertex.glsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c9d11dc4b..addcbadbc 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1264,11 +1264,27 @@ impl<'a, W: Write> Writer<'a, W> { } => (location, interpolation, sampling), crate::Binding::BuiltIn(built_in) => { if let crate::BuiltIn::Position { invariant: true } = built_in { - writeln!( - self.out, - "invariant {};", - glsl_built_in(built_in, output, self.options.version.is_webgl()) - )?; + match (self.options.version, self.entry_point.stage) { + ( + Version::Embedded { + version: 300, + is_webgl: true, + }, + ShaderStage::Fragment, + ) => { + // `invariant gl_FragCoord` is not allowed in WebGL2 and possibly + // OpenGL ES in general (waiting on confirmation). + // + // See https://github.com/KhronosGroup/WebGL/issues/3518 + } + _ => { + writeln!( + self.out, + "invariant {};", + glsl_built_in(built_in, output, self.options.version.is_webgl()) + )?; + } + } } return Ok(()); } diff --git a/tests/in/invariant.param.ron b/tests/in/invariant.param.ron new file mode 100644 index 000000000..9b90c13ba --- /dev/null +++ b/tests/in/invariant.param.ron @@ -0,0 +1,11 @@ +( + glsl: ( + version: Embedded ( + version: 300, + is_webgl: true + ), + writer_flags: (bits: 0), + binding_map: {}, + zero_initialize_workgroup_memory: true, + ), +) diff --git a/tests/in/invariant.wgsl b/tests/in/invariant.wgsl new file mode 100644 index 000000000..ac6bc09f1 --- /dev/null +++ b/tests/in/invariant.wgsl @@ -0,0 +1,7 @@ +@vertex +fn vs() -> @builtin(position) @invariant vec4 { + return vec4(0.0); +} + +@fragment +fn fs(@builtin(position) @invariant position: vec4) { } diff --git a/tests/out/glsl/invariant.frag_main.Fragment.glsl b/tests/out/glsl/invariant.frag_main.Fragment.glsl new file mode 100644 index 000000000..9936a28ad --- /dev/null +++ b/tests/out/glsl/invariant.frag_main.Fragment.glsl @@ -0,0 +1,11 @@ +#version 300 es + +precision highp float; +precision highp int; + + +void main() { + vec4 position = gl_FragCoord; + return; +} + diff --git a/tests/out/glsl/invariant.fs.Fragment.glsl b/tests/out/glsl/invariant.fs.Fragment.glsl new file mode 100644 index 000000000..9936a28ad --- /dev/null +++ b/tests/out/glsl/invariant.fs.Fragment.glsl @@ -0,0 +1,11 @@ +#version 300 es + +precision highp float; +precision highp int; + + +void main() { + vec4 position = gl_FragCoord; + return; +} + diff --git a/tests/out/glsl/invariant.vs.Vertex.glsl b/tests/out/glsl/invariant.vs.Vertex.glsl new file mode 100644 index 000000000..a34eab347 --- /dev/null +++ b/tests/out/glsl/invariant.vs.Vertex.glsl @@ -0,0 +1,12 @@ +#version 300 es + +precision highp float; +precision highp int; + +invariant gl_Position; + +void main() { + gl_Position = vec4(0.0); + return; +} + diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 7fea12200..c464aa344 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -558,6 +558,7 @@ fn convert_wgsl() { ), ("sprite", Targets::SPIRV), ("force_point_size_vertex_shader_webgl", Targets::GLSL), + ("invariant", Targets::GLSL), ]; for &(name, targets) in inputs.iter() { From 7422ace934b7ed51c1e061eb1d36de8259b5f619 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Thu, 16 Feb 2023 18:49:54 -0500 Subject: [PATCH 1945/2212] [wgsl-in] Add predeclared vector and matrix type aliases (#2251) --- src/front/wgsl/parse/mod.rs | 216 +++++++++++++++++++++++++++++++++ tests/in/operators.wgsl | 2 +- tests/in/type-alias.wgsl | 4 +- tests/out/wgsl/type-alias.wgsl | 1 + 4 files changed, 221 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 74d3741df..7ff762d67 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -272,48 +272,174 @@ impl Parser { "vec2" => ast::ConstructorType::PartialVector { size: crate::VectorSize::Bi, }, + "vec2i" => { + return Ok(Some(ast::ConstructorType::Vector { + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Sint, + width: 4, + })) + } + "vec2u" => { + return Ok(Some(ast::ConstructorType::Vector { + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Uint, + width: 4, + })) + } + "vec2f" => { + return Ok(Some(ast::ConstructorType::Vector { + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Float, + width: 4, + })) + } "vec3" => ast::ConstructorType::PartialVector { size: crate::VectorSize::Tri, }, + "vec3i" => { + return Ok(Some(ast::ConstructorType::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Sint, + width: 4, + })) + } + "vec3u" => { + return Ok(Some(ast::ConstructorType::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Uint, + width: 4, + })) + } + "vec3f" => { + return Ok(Some(ast::ConstructorType::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Float, + width: 4, + })) + } "vec4" => ast::ConstructorType::PartialVector { size: crate::VectorSize::Quad, }, + "vec4i" => { + return Ok(Some(ast::ConstructorType::Vector { + size: crate::VectorSize::Quad, + kind: crate::ScalarKind::Sint, + width: 4, + })) + } + "vec4u" => { + return Ok(Some(ast::ConstructorType::Vector { + size: crate::VectorSize::Quad, + kind: crate::ScalarKind::Uint, + width: 4, + })) + } + "vec4f" => { + return Ok(Some(ast::ConstructorType::Vector { + size: crate::VectorSize::Quad, + kind: crate::ScalarKind::Float, + width: 4, + })) + } "mat2x2" => ast::ConstructorType::PartialMatrix { columns: crate::VectorSize::Bi, rows: crate::VectorSize::Bi, }, + "mat2x2f" => { + return Ok(Some(ast::ConstructorType::Matrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Bi, + width: 4, + })) + } "mat2x3" => ast::ConstructorType::PartialMatrix { columns: crate::VectorSize::Bi, rows: crate::VectorSize::Tri, }, + "mat2x3f" => { + return Ok(Some(ast::ConstructorType::Matrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Tri, + width: 4, + })) + } "mat2x4" => ast::ConstructorType::PartialMatrix { columns: crate::VectorSize::Bi, rows: crate::VectorSize::Quad, }, + "mat2x4f" => { + return Ok(Some(ast::ConstructorType::Matrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Quad, + width: 4, + })) + } "mat3x2" => ast::ConstructorType::PartialMatrix { columns: crate::VectorSize::Tri, rows: crate::VectorSize::Bi, }, + "mat3x2f" => { + return Ok(Some(ast::ConstructorType::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Bi, + width: 4, + })) + } "mat3x3" => ast::ConstructorType::PartialMatrix { columns: crate::VectorSize::Tri, rows: crate::VectorSize::Tri, }, + "mat3x3f" => { + return Ok(Some(ast::ConstructorType::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Tri, + width: 4, + })) + } "mat3x4" => ast::ConstructorType::PartialMatrix { columns: crate::VectorSize::Tri, rows: crate::VectorSize::Quad, }, + "mat3x4f" => { + return Ok(Some(ast::ConstructorType::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Quad, + width: 4, + })) + } "mat4x2" => ast::ConstructorType::PartialMatrix { columns: crate::VectorSize::Quad, rows: crate::VectorSize::Bi, }, + "mat4x2f" => { + return Ok(Some(ast::ConstructorType::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Bi, + width: 4, + })) + } "mat4x3" => ast::ConstructorType::PartialMatrix { columns: crate::VectorSize::Quad, rows: crate::VectorSize::Tri, }, + "mat4x3f" => { + return Ok(Some(ast::ConstructorType::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Tri, + width: 4, + })) + } "mat4x4" => ast::ConstructorType::PartialMatrix { columns: crate::VectorSize::Quad, rows: crate::VectorSize::Quad, }, + "mat4x4f" => { + return Ok(Some(ast::ConstructorType::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Quad, + width: 4, + })) + } "array" => ast::ConstructorType::PartialArray, "atomic" | "binding_array" @@ -914,6 +1040,21 @@ impl Parser { width, } } + "vec2i" => ast::Type::Vector { + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Sint, + width: 4, + }, + "vec2u" => ast::Type::Vector { + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Uint, + width: 4, + }, + "vec2f" => ast::Type::Vector { + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Float, + width: 4, + }, "vec3" => { let (kind, width) = lexer.next_scalar_generic()?; ast::Type::Vector { @@ -922,6 +1063,21 @@ impl Parser { width, } } + "vec3i" => ast::Type::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Sint, + width: 4, + }, + "vec3u" => ast::Type::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Uint, + width: 4, + }, + "vec3f" => ast::Type::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Float, + width: 4, + }, "vec4" => { let (kind, width) = lexer.next_scalar_generic()?; ast::Type::Vector { @@ -930,33 +1086,93 @@ impl Parser { width, } } + "vec4i" => ast::Type::Vector { + size: crate::VectorSize::Quad, + kind: crate::ScalarKind::Sint, + width: 4, + }, + "vec4u" => ast::Type::Vector { + size: crate::VectorSize::Quad, + kind: crate::ScalarKind::Uint, + width: 4, + }, + "vec4f" => ast::Type::Vector { + size: crate::VectorSize::Quad, + kind: crate::ScalarKind::Float, + width: 4, + }, "mat2x2" => { self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Bi)? } + "mat2x2f" => ast::Type::Matrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Bi, + width: 4, + }, "mat2x3" => { self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Tri)? } + "mat2x3f" => ast::Type::Matrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Tri, + width: 4, + }, "mat2x4" => { self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Quad)? } + "mat2x4f" => ast::Type::Matrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Quad, + width: 4, + }, "mat3x2" => { self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Bi)? } + "mat3x2f" => ast::Type::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Bi, + width: 4, + }, "mat3x3" => { self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Tri)? } + "mat3x3f" => ast::Type::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Tri, + width: 4, + }, "mat3x4" => { self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Quad)? } + "mat3x4f" => ast::Type::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Quad, + width: 4, + }, "mat4x2" => { self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Bi)? } + "mat4x2f" => ast::Type::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Bi, + width: 4, + }, "mat4x3" => { self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Tri)? } + "mat4x3f" => ast::Type::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Tri, + width: 4, + }, "mat4x4" => { self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Quad)? } + "mat4x4f" => ast::Type::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Quad, + width: 4, + }, "atomic" => { let (kind, width) = lexer.next_scalar_generic()?; ast::Type::Atomic { kind, width } diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index e5b9a15d5..eadafbdc1 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -194,7 +194,7 @@ fn arithmetic() { _ = 2.0 * mat3x3(); _ = mat4x3() * vec4(1.0); - _ = vec3(2.0) * mat4x3(); + _ = vec3f(2.0) * mat4x3f(); _ = mat4x3() * mat3x4(); } diff --git a/tests/in/type-alias.wgsl b/tests/in/type-alias.wgsl index 429f153b5..cf2c8dcb3 100644 --- a/tests/in/type-alias.wgsl +++ b/tests/in/type-alias.wgsl @@ -1,6 +1,7 @@ type FVec3 = vec3; -type IVec3 = vec3; +type IVec3 = vec3i; type Mat2 = mat2x2; +type Mat3 = mat3x3f; fn main() { let a = FVec3(0.0, 0.0, 0.0); @@ -10,4 +11,5 @@ fn main() { let e = IVec3(d); let f = Mat2(1.0, 2.0, 3.0, 4.0); + let g = Mat3(a, a, a); } diff --git a/tests/out/wgsl/type-alias.wgsl b/tests/out/wgsl/type-alias.wgsl index b9c551cc9..b298c2c93 100644 --- a/tests/out/wgsl/type-alias.wgsl +++ b/tests/out/wgsl/type-alias.wgsl @@ -5,5 +5,6 @@ fn main() { let d = vec3(vec2(0.0), 0.0); let e = vec3(d); let f = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); + let g = mat3x3(a, a, a); } From 58105a06e2bd5aefeb9330984d47976e63c11dc4 Mon Sep 17 00:00:00 2001 From: Leah Date: Fri, 17 Feb 2023 08:40:21 +0800 Subject: [PATCH 1946/2212] [glsl/hlsl-out] Write sizes of arrays behind pointers in function arguments (#2250) arrays can be put behind pointers in inout and out parameters in GLSL and HLSL, whose dimensions must be specified to let array access compile. so, we specify their dimensions. fixes #2248 --- src/back/glsl/mod.rs | 12 +- src/back/hlsl/writer.rs | 2 +- tests/in/access.wgsl | 9 +- tests/out/analysis/access.info.ron | 208 +++++ .../access.assign_through_ptr.Compute.glsl | 8 + tests/out/glsl/access.atomics.Compute.glsl | 5 + tests/out/glsl/access.foo_frag.Fragment.glsl | 5 + tests/out/glsl/access.foo_vert.Vertex.glsl | 7 +- tests/out/hlsl/access.hlsl | 18 +- tests/out/ir/access.ron | 114 ++- tests/out/msl/access.msl | 15 +- tests/out/spv/access.spvasm | 799 +++++++++--------- tests/out/wgsl/access.wgsl | 11 +- 13 files changed, 816 insertions(+), 397 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index addcbadbc..3433c2f1c 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1455,8 +1455,16 @@ impl<'a, W: Write> Writer<'a, W> { write!(this.out, " {}", &this.names[&ctx.argument_key(i as u32)])?; // Write array size - if let TypeInner::Array { base, size, .. } = this.module.types[arg.ty].inner { - this.write_array_size(base, size)?; + match this.module.types[arg.ty].inner { + TypeInner::Array { base, size, .. } => { + this.write_array_size(base, size)?; + } + TypeInner::Pointer { base, .. } => { + if let TypeInner::Array { base, size, .. } = this.module.types[base].inner { + this.write_array_size(base, size)?; + } + } + _ => {} } Ok(()) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 2af7a3524..c075fe3fe 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1143,7 +1143,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Write argument name. Space is important. write!(self.out, " {argument_name}")?; - if let TypeInner::Array { base, size, .. } = module.types[arg.ty].inner { + if let TypeInner::Array { base, size, .. } = module.types[arg_ty].inner { self.write_array_size(module, base, size)?; } } diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index 473f54213..a9c27ee78 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -174,7 +174,14 @@ fn assign_through_ptr_fn(p: ptr) { *p = 42u; } +fn assign_array_through_ptr_fn(foo: ptr, 2>>) { + *foo = array, 2>(vec4(1.0), vec4(2.0)); +} + @compute @workgroup_size(1) fn assign_through_ptr() { + var arr = array, 2>(vec4(6.0), vec4(7.0)); + assign_through_ptr_fn(&val); -} + assign_array_through_ptr_fn(&arr); +} \ No newline at end of file diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron index 75f53126b..01e08a63b 100644 --- a/tests/out/analysis/access.info.ron +++ b/tests/out/analysis/access.info.ron @@ -93,6 +93,12 @@ ( bits: 70, ), + ( + bits: 215, + ), + ( + bits: 70, + ), ], functions: [ ( @@ -3588,6 +3594,125 @@ ], sampling: [], ), + ( + flags: ( + bits: 63, + ), + available_stages: ( + bits: 7, + ), + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ( + bits: 0, + ), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(33), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Quad, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Quad, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(32), + ), + ], + sampling: [], + ), ], entry_points: [ ( @@ -5661,6 +5786,89 @@ ), ], expressions: [ + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Quad, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Quad, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: ( + bits: 0, + ), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(32), + ), + ( + uniformity: ( + non_uniform_result: Some(6), + requirements: ( + bits: 0, + ), + ), + ref_count: 2, + assignable_global: None, + ty: Value(Pointer( + base: 32, + space: Function, + )), + ), ( uniformity: ( non_uniform_result: None, diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/tests/out/glsl/access.assign_through_ptr.Compute.glsl index 1306fe514..f79b30e3e 100644 --- a/tests/out/glsl/access.assign_through_ptr.Compute.glsl +++ b/tests/out/glsl/access.assign_through_ptr.Compute.glsl @@ -36,13 +36,21 @@ void assign_through_ptr_fn(inout uint p) { return; } +void assign_array_through_ptr_fn(inout vec4 foo_2[2]) { + foo_2 = vec4[2](vec4(1.0), vec4(2.0)); + return; +} + void main() { if (gl_GlobalInvocationID == uvec3(0u)) { val = 0u; } memoryBarrierShared(); barrier(); + vec4 arr[2] = vec4[2](vec4(0.0), vec4(0.0)); + arr = vec4[2](vec4(6.0), vec4(7.0)); assign_through_ptr_fn(val); + assign_array_through_ptr_fn(arr); return; } diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl index ab164cf6f..8ccefe422 100644 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ b/tests/out/glsl/access.atomics.Compute.glsl @@ -43,6 +43,11 @@ void assign_through_ptr_fn(inout uint p) { return; } +void assign_array_through_ptr_fn(inout vec4 foo_2[2]) { + foo_2 = vec4[2](vec4(1.0), vec4(2.0)); + return; +} + void main() { int tmp = 0; int value = _group_0_binding_0_cs.atom; diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index e7656b8c1..c71617572 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -44,6 +44,11 @@ void assign_through_ptr_fn(inout uint p) { return; } +void assign_array_through_ptr_fn(inout vec4 foo_2[2]) { + foo_2 = vec4[2](vec4(1.0), vec4(2.0)); + return; +} + void main() { _group_0_binding_0_fs._matrix[1][2] = 1.0; _group_0_binding_0_fs._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index 331b7cda9..03e33ccb8 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -121,6 +121,11 @@ void assign_through_ptr_fn(inout uint p) { return; } +void assign_array_through_ptr_fn(inout vec4 foo_2[2]) { + foo_2 = vec4[2](vec4(1.0), vec4(2.0)); + return; +} + void main() { uint vi = uint(gl_VertexID); float foo = 0.0; @@ -131,7 +136,7 @@ void main() { test_matrix_within_struct_accesses(); test_matrix_within_array_within_struct_accesses(); mat4x3 _matrix = _group_0_binding_0_vs._matrix; - uvec2 arr[2] = _group_0_binding_0_vs.arr; + uvec2 arr_1[2] = _group_0_binding_0_vs.arr; float b = _group_0_binding_0_vs._matrix[3][0]; int a_1 = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; ivec2 c = _group_0_binding_2_vs; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 9f898b0e9..c87f39cf2 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -237,6 +237,18 @@ void assign_through_ptr_fn(inout uint p) return; } +typedef float4 ret_Constructarray2_float4_[2]; +ret_Constructarray2_float4_ Constructarray2_float4_(float4 arg0, float4 arg1) { + float4 ret[2] = { arg0, arg1 }; + return ret; +} + +void assign_array_through_ptr_fn(inout float4 foo_2[2]) +{ + foo_2 = Constructarray2_float4_((1.0).xxxx, (2.0).xxxx); + return; +} + uint NagaBufferLengthRW(RWByteAddressBuffer buffer) { uint ret; @@ -261,7 +273,7 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position test_matrix_within_struct_accesses(); test_matrix_within_array_within_struct_accesses(); float4x3 _matrix = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); - uint2 arr[2] = {asuint(bar.Load2(144+0)), asuint(bar.Load2(144+8))}; + uint2 arr_1[2] = {asuint(bar.Load2(144+0)), asuint(bar.Load2(144+8))}; float b = asfloat(bar.Load(0+48+0)); int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 160) / 8) - 2u)*8+160)); int2 c = asint(qux.Load2(0)); @@ -332,6 +344,10 @@ void assign_through_ptr(uint3 __global_invocation_id : SV_DispatchThreadID) val = (uint)0; } GroupMemoryBarrierWithGroupSync(); + float4 arr[2] = (float4[2])0; + + arr = Constructarray2_float4_((6.0).xxxx, (7.0).xxxx); assign_through_ptr_fn(val); + assign_array_through_ptr_fn(arr); return; } diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 3c3783998..e544ee1a5 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -317,6 +317,21 @@ space: WorkGroup, ), ), + ( + name: None, + inner: Array( + base: 26, + size: Constant(5), + stride: 16, + ), + ), + ( + name: None, + inner: Pointer( + base: 32, + space: Function, + ), + ), ], constants: [ ( @@ -1964,6 +1979,58 @@ ), ], ), + ( + name: Some("assign_array_through_ptr_fn"), + arguments: [ + ( + name: Some("foo"), + ty: 33, + binding: None, + ), + ], + result: None, + local_variables: [], + expressions: [ + FunctionArgument(0), + Constant(8), + Splat( + size: Quad, + value: 2, + ), + Constant(9), + Splat( + size: Quad, + value: 4, + ), + Compose( + ty: 32, + components: [ + 3, + 5, + ], + ), + ], + named_expressions: { + 1: "foo", + }, + body: [ + Emit(( + start: 2, + end: 3, + )), + Emit(( + start: 4, + end: 6, + )), + Store( + pointer: 1, + value: 6, + ), + Return( + value: None, + ), + ], + ), ], entry_points: [ ( @@ -2721,16 +2788,59 @@ name: Some("assign_through_ptr"), arguments: [], result: None, - local_variables: [], + local_variables: [ + ( + name: Some("arr"), + ty: 32, + init: None, + ), + ], expressions: [ + Constant(11), + Splat( + size: Quad, + value: 1, + ), + Constant(25), + Splat( + size: Quad, + value: 3, + ), + Compose( + ty: 32, + components: [ + 2, + 4, + ], + ), + LocalVariable(1), GlobalVariable(6), ], named_expressions: {}, body: [ + Emit(( + start: 1, + end: 2, + )), + Emit(( + start: 3, + end: 5, + )), + Store( + pointer: 6, + value: 5, + ), Call( function: 5, arguments: [ - 1, + 7, + ], + result: None, + ), + Call( + function: 6, + arguments: [ + 6, ], result: None, ), diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 30b2bdbc6..e565643bb 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -54,6 +54,9 @@ struct type_19 { struct type_22 { int inner[5]; }; +struct type_26 { + metal::float4 inner[2]; +}; constant metal::uint3 const_type_1_ = {0u, 0u, 0u}; constant GlobalConst const_GlobalConst = {0u, {}, const_type_1_, 0}; constant metal::float2 const_type_13_ = {0.0, 0.0}; @@ -161,6 +164,13 @@ void assign_through_ptr_fn( return; } +void assign_array_through_ptr_fn( + thread type_26& foo_2 +) { + for(int _i=0; _i<2; ++_i) foo_2.inner[_i] = type_26 {metal::float4(1.0), metal::float4(2.0)}.inner[_i]; + return; +} + struct foo_vertInput { }; struct foo_vertOutput { @@ -182,7 +192,7 @@ vertex foo_vertOutput foo_vert( test_matrix_within_struct_accesses(baz); test_matrix_within_array_within_struct_accesses(nested_mat_cx2_); metal::float4x3 _matrix = bar._matrix; - type_9 arr = bar.arr; + type_9 arr_1 = bar.arr; float b = bar._matrix[3].x; int a_1 = bar.data[(1 + (_buffer_sizes.size1 - 160 - 8) / 8) - 2u].value; metal::int2 c = qux; @@ -247,6 +257,9 @@ kernel void assign_through_ptr( val = {}; } metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + type_26 arr = {}; + for(int _i=0; _i<2; ++_i) arr.inner[_i] = type_26 {metal::float4(6.0), metal::float4(7.0)}.inner[_i]; assign_through_ptr_fn(val); + assign_array_through_ptr_fn(arr); return; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 128e0158b..42ab59eb5 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,18 +1,18 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 338 +; Bound: 354 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %237 "foo_vert" %232 %235 -OpEntryPoint Fragment %279 "foo_frag" %278 -OpEntryPoint GLCompute %298 "atomics" -OpEntryPoint GLCompute %322 "assign_through_ptr" %325 -OpExecutionMode %279 OriginUpperLeft -OpExecutionMode %298 LocalSize 1 1 1 -OpExecutionMode %322 LocalSize 1 1 1 +OpEntryPoint Vertex %247 "foo_vert" %242 %245 +OpEntryPoint Fragment %289 "foo_frag" %288 +OpEntryPoint GLCompute %308 "atomics" +OpEntryPoint GLCompute %334 "assign_through_ptr" %337 +OpExecutionMode %289 OriginUpperLeft +OpExecutionMode %308 LocalSize 1 1 1 +OpExecutionMode %334 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %36 0 "a" OpMemberName %36 1 "b" @@ -31,32 +31,35 @@ OpMemberName %49 0 "m" OpName %49 "Baz" OpMemberName %53 0 "am" OpName %53 "MatCx2InArray" -OpName %70 "global_const" -OpName %72 "bar" -OpName %74 "baz" -OpName %77 "qux" -OpName %80 "nested_mat_cx2" -OpName %83 "val" -OpName %84 "idx" -OpName %87 "t" -OpName %91 "test_matrix_within_struct_accesses" -OpName %148 "idx" -OpName %150 "t" -OpName %154 "test_matrix_within_array_within_struct_accesses" -OpName %209 "foo" -OpName %210 "read_from_private" -OpName %215 "a" -OpName %216 "test_arr_as_arg" -OpName %222 "p" -OpName %223 "assign_through_ptr_fn" -OpName %226 "foo" -OpName %228 "c2" -OpName %232 "vi" -OpName %237 "foo_vert" -OpName %279 "foo_frag" -OpName %295 "tmp" -OpName %298 "atomics" -OpName %322 "assign_through_ptr" +OpName %72 "global_const" +OpName %74 "bar" +OpName %76 "baz" +OpName %79 "qux" +OpName %82 "nested_mat_cx2" +OpName %85 "val" +OpName %86 "idx" +OpName %89 "t" +OpName %93 "test_matrix_within_struct_accesses" +OpName %150 "idx" +OpName %152 "t" +OpName %156 "test_matrix_within_array_within_struct_accesses" +OpName %211 "foo" +OpName %212 "read_from_private" +OpName %217 "a" +OpName %218 "test_arr_as_arg" +OpName %224 "p" +OpName %225 "assign_through_ptr_fn" +OpName %229 "foo" +OpName %230 "assign_array_through_ptr_fn" +OpName %236 "foo" +OpName %238 "c2" +OpName %242 "vi" +OpName %247 "foo_vert" +OpName %289 "foo_frag" +OpName %305 "tmp" +OpName %308 "atomics" +OpName %331 "arr" +OpName %334 "assign_through_ptr" OpMemberDecorate %36 0 Offset 0 OpMemberDecorate %36 1 Offset 16 OpMemberDecorate %36 2 Offset 28 @@ -85,25 +88,26 @@ OpMemberDecorate %53 0 MatrixStride 8 OpDecorate %55 ArrayStride 4 OpDecorate %56 ArrayStride 40 OpDecorate %59 ArrayStride 4 -OpDecorate %72 DescriptorSet 0 -OpDecorate %72 Binding 0 -OpDecorate %47 Block +OpDecorate %62 ArrayStride 16 OpDecorate %74 DescriptorSet 0 -OpDecorate %74 Binding 1 -OpDecorate %75 Block -OpMemberDecorate %75 0 Offset 0 -OpDecorate %77 DescriptorSet 0 -OpDecorate %77 Binding 2 -OpDecorate %78 Block -OpMemberDecorate %78 0 Offset 0 -OpDecorate %80 DescriptorSet 0 -OpDecorate %80 Binding 3 -OpDecorate %81 Block -OpMemberDecorate %81 0 Offset 0 -OpDecorate %232 BuiltIn VertexIndex -OpDecorate %235 BuiltIn Position -OpDecorate %278 Location 0 -OpDecorate %325 BuiltIn GlobalInvocationId +OpDecorate %74 Binding 0 +OpDecorate %47 Block +OpDecorate %76 DescriptorSet 0 +OpDecorate %76 Binding 1 +OpDecorate %77 Block +OpMemberDecorate %77 0 Offset 0 +OpDecorate %79 DescriptorSet 0 +OpDecorate %79 Binding 2 +OpDecorate %80 Block +OpMemberDecorate %80 0 Offset 0 +OpDecorate %82 DescriptorSet 0 +OpDecorate %82 Binding 3 +OpDecorate %83 Block +OpMemberDecorate %83 0 Offset 0 +OpDecorate %242 BuiltIn VertexIndex +OpDecorate %245 BuiltIn Position +OpDecorate %288 Location 0 +OpDecorate %337 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -164,356 +168,377 @@ OpDecorate %325 BuiltIn GlobalInvocationId %59 = OpTypeArray %6 %26 %60 = OpTypeVector %6 4 %61 = OpTypePointer Workgroup %4 -%62 = OpConstantComposite %35 %3 %3 %3 -%63 = OpConstantComposite %36 %3 %62 %5 -%64 = OpConstantComposite %41 %23 %23 -%65 = OpConstantComposite %51 %64 %64 %64 %64 -%66 = OpConstantComposite %52 %65 %65 -%67 = OpConstantComposite %55 %23 %23 %23 %23 %23 %23 %23 %23 %23 %23 -%68 = OpConstantComposite %56 %67 %67 %67 %67 %67 -%69 = OpConstantComposite %50 %5 %5 -%71 = OpTypePointer Private %36 -%70 = OpVariable %71 Private %63 -%73 = OpTypePointer StorageBuffer %47 -%72 = OpVariable %73 StorageBuffer -%75 = OpTypeStruct %49 -%76 = OpTypePointer Uniform %75 -%74 = OpVariable %76 Uniform -%78 = OpTypeStruct %50 -%79 = OpTypePointer StorageBuffer %78 -%77 = OpVariable %79 StorageBuffer -%81 = OpTypeStruct %53 -%82 = OpTypePointer Uniform %81 -%80 = OpVariable %82 Uniform -%83 = OpVariable %61 Workgroup -%85 = OpTypePointer Function %6 -%86 = OpConstantNull %6 -%88 = OpTypePointer Function %49 -%89 = OpConstantNull %49 -%92 = OpTypeFunction %2 -%93 = OpTypePointer Uniform %49 -%98 = OpTypePointer Uniform %48 -%101 = OpTypePointer Uniform %41 -%107 = OpTypePointer Uniform %11 -%127 = OpTypePointer Function %48 -%133 = OpTypePointer Function %41 -%139 = OpTypePointer Function %11 -%149 = OpConstantNull %6 -%151 = OpTypePointer Function %53 -%152 = OpConstantNull %53 -%155 = OpTypePointer Uniform %53 -%160 = OpTypePointer Uniform %52 -%163 = OpTypePointer Uniform %51 -%186 = OpTypePointer Function %52 -%188 = OpTypePointer Function %51 -%211 = OpTypeFunction %11 %54 -%217 = OpTypeFunction %11 %56 -%224 = OpTypeFunction %2 %61 -%227 = OpConstantNull %11 -%229 = OpTypePointer Function %59 -%230 = OpConstantNull %59 -%233 = OpTypePointer Input %4 -%232 = OpVariable %233 Input -%236 = OpTypePointer Output %57 -%235 = OpVariable %236 Output -%239 = OpTypePointer StorageBuffer %50 -%246 = OpTypePointer StorageBuffer %38 -%249 = OpTypePointer StorageBuffer %45 -%250 = OpConstant %4 4 -%253 = OpTypePointer StorageBuffer %39 -%254 = OpTypePointer StorageBuffer %11 -%257 = OpTypePointer StorageBuffer %46 -%260 = OpTypePointer StorageBuffer %37 -%261 = OpConstant %4 5 -%278 = OpVariable %236 Output -%296 = OpConstantNull %6 -%300 = OpTypePointer StorageBuffer %6 -%303 = OpConstant %4 64 -%324 = OpConstantNull %4 -%326 = OpTypePointer Input %35 -%325 = OpVariable %326 Input -%328 = OpConstantNull %35 -%330 = OpTypeBool -%329 = OpTypeVector %330 3 -%335 = OpConstant %4 264 -%91 = OpFunction %2 None %92 -%90 = OpLabel -%84 = OpVariable %85 Function %86 -%87 = OpVariable %88 Function %89 -%94 = OpAccessChain %93 %74 %3 -OpBranch %95 -%95 = OpLabel -OpStore %84 %9 -%96 = OpLoad %6 %84 -%97 = OpISub %6 %96 %9 -OpStore %84 %97 -%99 = OpAccessChain %98 %94 %3 -%100 = OpLoad %48 %99 -%102 = OpAccessChain %101 %94 %3 %3 -%103 = OpLoad %41 %102 -%104 = OpLoad %6 %84 -%105 = OpAccessChain %101 %94 %3 %104 -%106 = OpLoad %41 %105 -%108 = OpAccessChain %107 %94 %3 %3 %32 -%109 = OpLoad %11 %108 -%110 = OpLoad %6 %84 -%111 = OpAccessChain %107 %94 %3 %3 %110 -%112 = OpLoad %11 %111 -%113 = OpLoad %6 %84 -%114 = OpAccessChain %107 %94 %3 %113 %32 -%115 = OpLoad %11 %114 -%116 = OpLoad %6 %84 -%117 = OpLoad %6 %84 -%118 = OpAccessChain %107 %94 %3 %116 %117 -%119 = OpLoad %11 %118 -%120 = OpCompositeConstruct %41 %10 %10 -%121 = OpCompositeConstruct %41 %12 %12 -%122 = OpCompositeConstruct %41 %13 %13 -%123 = OpCompositeConstruct %48 %120 %121 %122 -%124 = OpCompositeConstruct %49 %123 -OpStore %87 %124 -%125 = OpLoad %6 %84 -%126 = OpIAdd %6 %125 %9 -OpStore %84 %126 -%128 = OpCompositeConstruct %41 %14 %14 -%129 = OpCompositeConstruct %41 %15 %15 -%130 = OpCompositeConstruct %41 %16 %16 -%131 = OpCompositeConstruct %48 %128 %129 %130 -%132 = OpAccessChain %127 %87 %3 -OpStore %132 %131 -%134 = OpCompositeConstruct %41 %17 %17 -%135 = OpAccessChain %133 %87 %3 %3 -OpStore %135 %134 -%136 = OpLoad %6 %84 -%137 = OpCompositeConstruct %41 %18 %18 -%138 = OpAccessChain %133 %87 %3 %136 -OpStore %138 %137 -%140 = OpAccessChain %139 %87 %3 %3 %32 -OpStore %140 %19 -%141 = OpLoad %6 %84 -%142 = OpAccessChain %139 %87 %3 %3 %141 -OpStore %142 %20 -%143 = OpLoad %6 %84 -%144 = OpAccessChain %139 %87 %3 %143 %32 -OpStore %144 %21 -%145 = OpLoad %6 %84 -%146 = OpLoad %6 %84 -%147 = OpAccessChain %139 %87 %3 %145 %146 -OpStore %147 %22 +%62 = OpTypeArray %57 %7 +%63 = OpTypePointer Function %62 +%64 = OpConstantComposite %35 %3 %3 %3 +%65 = OpConstantComposite %36 %3 %64 %5 +%66 = OpConstantComposite %41 %23 %23 +%67 = OpConstantComposite %51 %66 %66 %66 %66 +%68 = OpConstantComposite %52 %67 %67 +%69 = OpConstantComposite %55 %23 %23 %23 %23 %23 %23 %23 %23 %23 %23 +%70 = OpConstantComposite %56 %69 %69 %69 %69 %69 +%71 = OpConstantComposite %50 %5 %5 +%73 = OpTypePointer Private %36 +%72 = OpVariable %73 Private %65 +%75 = OpTypePointer StorageBuffer %47 +%74 = OpVariable %75 StorageBuffer +%77 = OpTypeStruct %49 +%78 = OpTypePointer Uniform %77 +%76 = OpVariable %78 Uniform +%80 = OpTypeStruct %50 +%81 = OpTypePointer StorageBuffer %80 +%79 = OpVariable %81 StorageBuffer +%83 = OpTypeStruct %53 +%84 = OpTypePointer Uniform %83 +%82 = OpVariable %84 Uniform +%85 = OpVariable %61 Workgroup +%87 = OpTypePointer Function %6 +%88 = OpConstantNull %6 +%90 = OpTypePointer Function %49 +%91 = OpConstantNull %49 +%94 = OpTypeFunction %2 +%95 = OpTypePointer Uniform %49 +%100 = OpTypePointer Uniform %48 +%103 = OpTypePointer Uniform %41 +%109 = OpTypePointer Uniform %11 +%129 = OpTypePointer Function %48 +%135 = OpTypePointer Function %41 +%141 = OpTypePointer Function %11 +%151 = OpConstantNull %6 +%153 = OpTypePointer Function %53 +%154 = OpConstantNull %53 +%157 = OpTypePointer Uniform %53 +%162 = OpTypePointer Uniform %52 +%165 = OpTypePointer Uniform %51 +%188 = OpTypePointer Function %52 +%190 = OpTypePointer Function %51 +%213 = OpTypeFunction %11 %54 +%219 = OpTypeFunction %11 %56 +%226 = OpTypeFunction %2 %61 +%231 = OpTypeFunction %2 %63 +%237 = OpConstantNull %11 +%239 = OpTypePointer Function %59 +%240 = OpConstantNull %59 +%243 = OpTypePointer Input %4 +%242 = OpVariable %243 Input +%246 = OpTypePointer Output %57 +%245 = OpVariable %246 Output +%249 = OpTypePointer StorageBuffer %50 +%256 = OpTypePointer StorageBuffer %38 +%259 = OpTypePointer StorageBuffer %45 +%260 = OpConstant %4 4 +%263 = OpTypePointer StorageBuffer %39 +%264 = OpTypePointer StorageBuffer %11 +%267 = OpTypePointer StorageBuffer %46 +%270 = OpTypePointer StorageBuffer %37 +%271 = OpConstant %4 5 +%288 = OpVariable %246 Output +%306 = OpConstantNull %6 +%310 = OpTypePointer StorageBuffer %6 +%313 = OpConstant %4 64 +%332 = OpConstantNull %62 +%336 = OpConstantNull %4 +%338 = OpTypePointer Input %35 +%337 = OpVariable %338 Input +%340 = OpConstantNull %35 +%342 = OpTypeBool +%341 = OpTypeVector %342 3 +%347 = OpConstant %4 264 +%93 = OpFunction %2 None %94 +%92 = OpLabel +%86 = OpVariable %87 Function %88 +%89 = OpVariable %90 Function %91 +%96 = OpAccessChain %95 %76 %3 +OpBranch %97 +%97 = OpLabel +OpStore %86 %9 +%98 = OpLoad %6 %86 +%99 = OpISub %6 %98 %9 +OpStore %86 %99 +%101 = OpAccessChain %100 %96 %3 +%102 = OpLoad %48 %101 +%104 = OpAccessChain %103 %96 %3 %3 +%105 = OpLoad %41 %104 +%106 = OpLoad %6 %86 +%107 = OpAccessChain %103 %96 %3 %106 +%108 = OpLoad %41 %107 +%110 = OpAccessChain %109 %96 %3 %3 %32 +%111 = OpLoad %11 %110 +%112 = OpLoad %6 %86 +%113 = OpAccessChain %109 %96 %3 %3 %112 +%114 = OpLoad %11 %113 +%115 = OpLoad %6 %86 +%116 = OpAccessChain %109 %96 %3 %115 %32 +%117 = OpLoad %11 %116 +%118 = OpLoad %6 %86 +%119 = OpLoad %6 %86 +%120 = OpAccessChain %109 %96 %3 %118 %119 +%121 = OpLoad %11 %120 +%122 = OpCompositeConstruct %41 %10 %10 +%123 = OpCompositeConstruct %41 %12 %12 +%124 = OpCompositeConstruct %41 %13 %13 +%125 = OpCompositeConstruct %48 %122 %123 %124 +%126 = OpCompositeConstruct %49 %125 +OpStore %89 %126 +%127 = OpLoad %6 %86 +%128 = OpIAdd %6 %127 %9 +OpStore %86 %128 +%130 = OpCompositeConstruct %41 %14 %14 +%131 = OpCompositeConstruct %41 %15 %15 +%132 = OpCompositeConstruct %41 %16 %16 +%133 = OpCompositeConstruct %48 %130 %131 %132 +%134 = OpAccessChain %129 %89 %3 +OpStore %134 %133 +%136 = OpCompositeConstruct %41 %17 %17 +%137 = OpAccessChain %135 %89 %3 %3 +OpStore %137 %136 +%138 = OpLoad %6 %86 +%139 = OpCompositeConstruct %41 %18 %18 +%140 = OpAccessChain %135 %89 %3 %138 +OpStore %140 %139 +%142 = OpAccessChain %141 %89 %3 %3 %32 +OpStore %142 %19 +%143 = OpLoad %6 %86 +%144 = OpAccessChain %141 %89 %3 %3 %143 +OpStore %144 %20 +%145 = OpLoad %6 %86 +%146 = OpAccessChain %141 %89 %3 %145 %32 +OpStore %146 %21 +%147 = OpLoad %6 %86 +%148 = OpLoad %6 %86 +%149 = OpAccessChain %141 %89 %3 %147 %148 +OpStore %149 %22 OpReturn OpFunctionEnd -%154 = OpFunction %2 None %92 -%153 = OpLabel -%148 = OpVariable %85 Function %149 -%150 = OpVariable %151 Function %152 -%156 = OpAccessChain %155 %80 %3 -OpBranch %157 -%157 = OpLabel -OpStore %148 %9 -%158 = OpLoad %6 %148 -%159 = OpISub %6 %158 %9 -OpStore %148 %159 -%161 = OpAccessChain %160 %156 %3 -%162 = OpLoad %52 %161 -%164 = OpAccessChain %163 %156 %3 %3 -%165 = OpLoad %51 %164 -%166 = OpAccessChain %101 %156 %3 %3 %3 -%167 = OpLoad %41 %166 -%168 = OpLoad %6 %148 -%169 = OpAccessChain %101 %156 %3 %3 %168 -%170 = OpLoad %41 %169 -%171 = OpAccessChain %107 %156 %3 %3 %3 %32 -%172 = OpLoad %11 %171 -%173 = OpLoad %6 %148 -%174 = OpAccessChain %107 %156 %3 %3 %3 %173 -%175 = OpLoad %11 %174 -%176 = OpLoad %6 %148 -%177 = OpAccessChain %107 %156 %3 %3 %176 %32 -%178 = OpLoad %11 %177 -%179 = OpLoad %6 %148 -%180 = OpLoad %6 %148 -%181 = OpAccessChain %107 %156 %3 %3 %179 %180 -%182 = OpLoad %11 %181 -%183 = OpCompositeConstruct %53 %66 -OpStore %150 %183 -%184 = OpLoad %6 %148 -%185 = OpIAdd %6 %184 %9 -OpStore %148 %185 -%187 = OpAccessChain %186 %150 %3 -OpStore %187 %66 -%189 = OpCompositeConstruct %41 %24 %24 -%190 = OpCompositeConstruct %41 %25 %25 -%191 = OpCompositeConstruct %41 %14 %14 -%192 = OpCompositeConstruct %41 %15 %15 -%193 = OpCompositeConstruct %51 %189 %190 %191 %192 -%194 = OpAccessChain %188 %150 %3 %3 -OpStore %194 %193 -%195 = OpCompositeConstruct %41 %17 %17 -%196 = OpAccessChain %133 %150 %3 %3 %3 +%156 = OpFunction %2 None %94 +%155 = OpLabel +%150 = OpVariable %87 Function %151 +%152 = OpVariable %153 Function %154 +%158 = OpAccessChain %157 %82 %3 +OpBranch %159 +%159 = OpLabel +OpStore %150 %9 +%160 = OpLoad %6 %150 +%161 = OpISub %6 %160 %9 +OpStore %150 %161 +%163 = OpAccessChain %162 %158 %3 +%164 = OpLoad %52 %163 +%166 = OpAccessChain %165 %158 %3 %3 +%167 = OpLoad %51 %166 +%168 = OpAccessChain %103 %158 %3 %3 %3 +%169 = OpLoad %41 %168 +%170 = OpLoad %6 %150 +%171 = OpAccessChain %103 %158 %3 %3 %170 +%172 = OpLoad %41 %171 +%173 = OpAccessChain %109 %158 %3 %3 %3 %32 +%174 = OpLoad %11 %173 +%175 = OpLoad %6 %150 +%176 = OpAccessChain %109 %158 %3 %3 %3 %175 +%177 = OpLoad %11 %176 +%178 = OpLoad %6 %150 +%179 = OpAccessChain %109 %158 %3 %3 %178 %32 +%180 = OpLoad %11 %179 +%181 = OpLoad %6 %150 +%182 = OpLoad %6 %150 +%183 = OpAccessChain %109 %158 %3 %3 %181 %182 +%184 = OpLoad %11 %183 +%185 = OpCompositeConstruct %53 %68 +OpStore %152 %185 +%186 = OpLoad %6 %150 +%187 = OpIAdd %6 %186 %9 +OpStore %150 %187 +%189 = OpAccessChain %188 %152 %3 +OpStore %189 %68 +%191 = OpCompositeConstruct %41 %24 %24 +%192 = OpCompositeConstruct %41 %25 %25 +%193 = OpCompositeConstruct %41 %14 %14 +%194 = OpCompositeConstruct %41 %15 %15 +%195 = OpCompositeConstruct %51 %191 %192 %193 %194 +%196 = OpAccessChain %190 %152 %3 %3 OpStore %196 %195 -%197 = OpLoad %6 %148 -%198 = OpCompositeConstruct %41 %18 %18 -%199 = OpAccessChain %133 %150 %3 %3 %197 -OpStore %199 %198 -%200 = OpAccessChain %139 %150 %3 %3 %3 %32 -OpStore %200 %19 -%201 = OpLoad %6 %148 -%202 = OpAccessChain %139 %150 %3 %3 %3 %201 -OpStore %202 %20 -%203 = OpLoad %6 %148 -%204 = OpAccessChain %139 %150 %3 %3 %203 %32 -OpStore %204 %21 -%205 = OpLoad %6 %148 -%206 = OpLoad %6 %148 -%207 = OpAccessChain %139 %150 %3 %3 %205 %206 -OpStore %207 %22 +%197 = OpCompositeConstruct %41 %17 %17 +%198 = OpAccessChain %135 %152 %3 %3 %3 +OpStore %198 %197 +%199 = OpLoad %6 %150 +%200 = OpCompositeConstruct %41 %18 %18 +%201 = OpAccessChain %135 %152 %3 %3 %199 +OpStore %201 %200 +%202 = OpAccessChain %141 %152 %3 %3 %3 %32 +OpStore %202 %19 +%203 = OpLoad %6 %150 +%204 = OpAccessChain %141 %152 %3 %3 %3 %203 +OpStore %204 %20 +%205 = OpLoad %6 %150 +%206 = OpAccessChain %141 %152 %3 %3 %205 %32 +OpStore %206 %21 +%207 = OpLoad %6 %150 +%208 = OpLoad %6 %150 +%209 = OpAccessChain %141 %152 %3 %3 %207 %208 +OpStore %209 %22 OpReturn OpFunctionEnd -%210 = OpFunction %11 None %211 -%209 = OpFunctionParameter %54 -%208 = OpLabel -OpBranch %212 -%212 = OpLabel -%213 = OpLoad %11 %209 -OpReturnValue %213 -OpFunctionEnd -%216 = OpFunction %11 None %217 -%215 = OpFunctionParameter %56 +%212 = OpFunction %11 None %213 +%211 = OpFunctionParameter %54 +%210 = OpLabel +OpBranch %214 %214 = OpLabel -OpBranch %218 -%218 = OpLabel -%219 = OpCompositeExtract %55 %215 4 -%220 = OpCompositeExtract %11 %219 9 -OpReturnValue %220 +%215 = OpLoad %11 %211 +OpReturnValue %215 OpFunctionEnd -%223 = OpFunction %2 None %224 -%222 = OpFunctionParameter %61 -%221 = OpLabel -OpBranch %225 -%225 = OpLabel -OpStore %222 %34 +%218 = OpFunction %11 None %219 +%217 = OpFunctionParameter %56 +%216 = OpLabel +OpBranch %220 +%220 = OpLabel +%221 = OpCompositeExtract %55 %217 4 +%222 = OpCompositeExtract %11 %221 9 +OpReturnValue %222 +OpFunctionEnd +%225 = OpFunction %2 None %226 +%224 = OpFunctionParameter %61 +%223 = OpLabel +OpBranch %227 +%227 = OpLabel +OpStore %224 %34 OpReturn OpFunctionEnd -%237 = OpFunction %2 None %92 -%231 = OpLabel -%226 = OpVariable %54 Function %227 -%228 = OpVariable %229 Function %230 -%234 = OpLoad %4 %232 -%238 = OpAccessChain %93 %74 %3 -%240 = OpAccessChain %239 %77 %3 -%241 = OpAccessChain %155 %80 %3 -OpBranch %242 -%242 = OpLabel -OpStore %226 %23 -%243 = OpLoad %11 %226 -OpStore %226 %10 -%244 = OpFunctionCall %2 %91 -%245 = OpFunctionCall %2 %154 -%247 = OpAccessChain %246 %72 %3 -%248 = OpLoad %38 %247 -%251 = OpAccessChain %249 %72 %250 -%252 = OpLoad %45 %251 -%255 = OpAccessChain %254 %72 %3 %29 %3 -%256 = OpLoad %11 %255 -%258 = OpArrayLength %4 %72 5 -%259 = OpISub %4 %258 %30 -%262 = OpAccessChain %58 %72 %261 %259 %3 -%263 = OpLoad %6 %262 -%264 = OpLoad %50 %240 -%265 = OpFunctionCall %11 %210 %226 -%266 = OpConvertFToS %6 %256 -%267 = OpCompositeConstruct %59 %263 %266 %31 %27 %26 -OpStore %228 %267 -%268 = OpIAdd %4 %234 %32 -%269 = OpAccessChain %85 %228 %268 -OpStore %269 %33 -%270 = OpAccessChain %85 %228 %234 -%271 = OpLoad %6 %270 -%272 = OpFunctionCall %11 %216 %68 -%273 = OpCompositeConstruct %60 %271 %271 %271 %271 -%274 = OpConvertSToF %57 %273 -%275 = OpMatrixTimesVector %39 %248 %274 -%276 = OpCompositeConstruct %57 %275 %12 -OpStore %235 %276 +%230 = OpFunction %2 None %231 +%229 = OpFunctionParameter %63 +%228 = OpLabel +OpBranch %232 +%232 = OpLabel +%233 = OpCompositeConstruct %57 %10 %10 %10 %10 +%234 = OpCompositeConstruct %57 %12 %12 %12 %12 +%235 = OpCompositeConstruct %62 %233 %234 +OpStore %229 %235 OpReturn OpFunctionEnd -%279 = OpFunction %2 None %92 -%277 = OpLabel -%280 = OpAccessChain %239 %77 %3 -OpBranch %281 -%281 = OpLabel -%282 = OpAccessChain %254 %72 %3 %32 %30 -OpStore %282 %10 -%283 = OpCompositeConstruct %39 %23 %23 %23 -%284 = OpCompositeConstruct %39 %10 %10 %10 -%285 = OpCompositeConstruct %39 %12 %12 %12 -%286 = OpCompositeConstruct %39 %13 %13 %13 -%287 = OpCompositeConstruct %38 %283 %284 %285 %286 -%288 = OpAccessChain %246 %72 %3 -OpStore %288 %287 -%289 = OpCompositeConstruct %44 %3 %3 -%290 = OpCompositeConstruct %44 %32 %32 -%291 = OpCompositeConstruct %45 %289 %290 -%292 = OpAccessChain %249 %72 %250 -OpStore %292 %291 -%293 = OpAccessChain %58 %72 %261 %32 %3 -OpStore %293 %9 -OpStore %280 %69 -%294 = OpCompositeConstruct %57 %23 %23 %23 %23 -OpStore %278 %294 +%247 = OpFunction %2 None %94 +%241 = OpLabel +%236 = OpVariable %54 Function %237 +%238 = OpVariable %239 Function %240 +%244 = OpLoad %4 %242 +%248 = OpAccessChain %95 %76 %3 +%250 = OpAccessChain %249 %79 %3 +%251 = OpAccessChain %157 %82 %3 +OpBranch %252 +%252 = OpLabel +OpStore %236 %23 +%253 = OpLoad %11 %236 +OpStore %236 %10 +%254 = OpFunctionCall %2 %93 +%255 = OpFunctionCall %2 %156 +%257 = OpAccessChain %256 %74 %3 +%258 = OpLoad %38 %257 +%261 = OpAccessChain %259 %74 %260 +%262 = OpLoad %45 %261 +%265 = OpAccessChain %264 %74 %3 %29 %3 +%266 = OpLoad %11 %265 +%268 = OpArrayLength %4 %74 5 +%269 = OpISub %4 %268 %30 +%272 = OpAccessChain %58 %74 %271 %269 %3 +%273 = OpLoad %6 %272 +%274 = OpLoad %50 %250 +%275 = OpFunctionCall %11 %212 %236 +%276 = OpConvertFToS %6 %266 +%277 = OpCompositeConstruct %59 %273 %276 %31 %27 %26 +OpStore %238 %277 +%278 = OpIAdd %4 %244 %32 +%279 = OpAccessChain %87 %238 %278 +OpStore %279 %33 +%280 = OpAccessChain %87 %238 %244 +%281 = OpLoad %6 %280 +%282 = OpFunctionCall %11 %218 %70 +%283 = OpCompositeConstruct %60 %281 %281 %281 %281 +%284 = OpConvertSToF %57 %283 +%285 = OpMatrixTimesVector %39 %258 %284 +%286 = OpCompositeConstruct %57 %285 %12 +OpStore %245 %286 OpReturn OpFunctionEnd -%298 = OpFunction %2 None %92 -%297 = OpLabel -%295 = OpVariable %85 Function %296 -OpBranch %299 -%299 = OpLabel -%301 = OpAccessChain %300 %72 %30 -%302 = OpAtomicLoad %6 %301 %9 %303 -%305 = OpAccessChain %300 %72 %30 -%304 = OpAtomicIAdd %6 %305 %9 %303 %26 -OpStore %295 %304 -%307 = OpAccessChain %300 %72 %30 -%306 = OpAtomicISub %6 %307 %9 %303 %26 -OpStore %295 %306 -%309 = OpAccessChain %300 %72 %30 -%308 = OpAtomicAnd %6 %309 %9 %303 %26 -OpStore %295 %308 -%311 = OpAccessChain %300 %72 %30 -%310 = OpAtomicOr %6 %311 %9 %303 %26 -OpStore %295 %310 -%313 = OpAccessChain %300 %72 %30 -%312 = OpAtomicXor %6 %313 %9 %303 %26 -OpStore %295 %312 -%315 = OpAccessChain %300 %72 %30 -%314 = OpAtomicSMin %6 %315 %9 %303 %26 -OpStore %295 %314 -%317 = OpAccessChain %300 %72 %30 -%316 = OpAtomicSMax %6 %317 %9 %303 %26 -OpStore %295 %316 -%319 = OpAccessChain %300 %72 %30 -%318 = OpAtomicExchange %6 %319 %9 %303 %26 -OpStore %295 %318 -%320 = OpAccessChain %300 %72 %30 -OpAtomicStore %320 %9 %303 %302 +%289 = OpFunction %2 None %94 +%287 = OpLabel +%290 = OpAccessChain %249 %79 %3 +OpBranch %291 +%291 = OpLabel +%292 = OpAccessChain %264 %74 %3 %32 %30 +OpStore %292 %10 +%293 = OpCompositeConstruct %39 %23 %23 %23 +%294 = OpCompositeConstruct %39 %10 %10 %10 +%295 = OpCompositeConstruct %39 %12 %12 %12 +%296 = OpCompositeConstruct %39 %13 %13 %13 +%297 = OpCompositeConstruct %38 %293 %294 %295 %296 +%298 = OpAccessChain %256 %74 %3 +OpStore %298 %297 +%299 = OpCompositeConstruct %44 %3 %3 +%300 = OpCompositeConstruct %44 %32 %32 +%301 = OpCompositeConstruct %45 %299 %300 +%302 = OpAccessChain %259 %74 %260 +OpStore %302 %301 +%303 = OpAccessChain %58 %74 %271 %32 %3 +OpStore %303 %9 +OpStore %290 %71 +%304 = OpCompositeConstruct %57 %23 %23 %23 %23 +OpStore %288 %304 OpReturn OpFunctionEnd -%322 = OpFunction %2 None %92 -%321 = OpLabel -OpBranch %323 -%323 = OpLabel -%327 = OpLoad %35 %325 -%331 = OpIEqual %329 %327 %328 -%332 = OpAll %330 %331 -OpSelectionMerge %333 None -OpBranchConditional %332 %334 %333 -%334 = OpLabel -OpStore %83 %324 -OpBranch %333 +%308 = OpFunction %2 None %94 +%307 = OpLabel +%305 = OpVariable %87 Function %306 +OpBranch %309 +%309 = OpLabel +%311 = OpAccessChain %310 %74 %30 +%312 = OpAtomicLoad %6 %311 %9 %313 +%315 = OpAccessChain %310 %74 %30 +%314 = OpAtomicIAdd %6 %315 %9 %313 %26 +OpStore %305 %314 +%317 = OpAccessChain %310 %74 %30 +%316 = OpAtomicISub %6 %317 %9 %313 %26 +OpStore %305 %316 +%319 = OpAccessChain %310 %74 %30 +%318 = OpAtomicAnd %6 %319 %9 %313 %26 +OpStore %305 %318 +%321 = OpAccessChain %310 %74 %30 +%320 = OpAtomicOr %6 %321 %9 %313 %26 +OpStore %305 %320 +%323 = OpAccessChain %310 %74 %30 +%322 = OpAtomicXor %6 %323 %9 %313 %26 +OpStore %305 %322 +%325 = OpAccessChain %310 %74 %30 +%324 = OpAtomicSMin %6 %325 %9 %313 %26 +OpStore %305 %324 +%327 = OpAccessChain %310 %74 %30 +%326 = OpAtomicSMax %6 %327 %9 %313 %26 +OpStore %305 %326 +%329 = OpAccessChain %310 %74 %30 +%328 = OpAtomicExchange %6 %329 %9 %313 %26 +OpStore %305 %328 +%330 = OpAccessChain %310 %74 %30 +OpAtomicStore %330 %9 %313 %312 +OpReturn +OpFunctionEnd +%334 = OpFunction %2 None %94 %333 = OpLabel -OpControlBarrier %30 %30 %335 -OpBranch %336 -%336 = OpLabel -%337 = OpFunctionCall %2 %223 %83 +%331 = OpVariable %63 Function %332 +OpBranch %335 +%335 = OpLabel +%339 = OpLoad %35 %337 +%343 = OpIEqual %341 %339 %340 +%344 = OpAll %342 %343 +OpSelectionMerge %345 None +OpBranchConditional %344 %346 %345 +%346 = OpLabel +OpStore %85 %336 +OpBranch %345 +%345 = OpLabel +OpControlBarrier %30 %30 %347 +OpBranch %348 +%348 = OpLabel +%349 = OpCompositeConstruct %57 %14 %14 %14 %14 +%350 = OpCompositeConstruct %57 %25 %25 %25 %25 +%351 = OpCompositeConstruct %62 %349 %350 +OpStore %331 %351 +%352 = OpFunctionCall %2 %225 %85 +%353 = OpFunctionCall %2 %230 %331 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 5510a7988..7133f53d6 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -126,6 +126,11 @@ fn assign_through_ptr_fn(p: ptr) { return; } +fn assign_array_through_ptr_fn(foo_2: ptr,2>>) { + (*foo_2) = array,2>(vec4(1.0), vec4(2.0)); + return; +} + @vertex fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32; @@ -137,7 +142,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { test_matrix_within_struct_accesses(); test_matrix_within_array_within_struct_accesses(); let _matrix = bar._matrix; - let arr = bar.arr; + let arr_1 = bar.arr; let b = bar._matrix[3][0]; let a_1 = bar.data[(arrayLength((&bar.data)) - 2u)].value; let c = qux; @@ -187,6 +192,10 @@ fn atomics() { @compute @workgroup_size(1, 1, 1) fn assign_through_ptr() { + var arr: array,2>; + + arr = array,2>(vec4(6.0), vec4(7.0)); assign_through_ptr_fn((&val)); + assign_array_through_ptr_fn((&arr)); return; } From 60c0fc0284d52a732a0aa4980a562686f6e81bfa Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Mon, 20 Feb 2023 09:24:20 -0500 Subject: [PATCH 1947/2212] [spv-out] Cache constant composites (#2257) --- src/back/spv/block.rs | 108 ++-- src/back/spv/mod.rs | 14 +- src/back/spv/writer.rs | 72 ++- tests/out/spv/math-functions.spvasm | 13 +- tests/out/spv/operators.spvasm | 903 ++++++++++++++-------------- 5 files changed, 561 insertions(+), 549 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index bf09fc3ad..4b0c52e8e 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -711,36 +711,22 @@ impl<'w> BlockContext<'w> { .get_constant_scalar(crate::ScalarValue::Float(1.0), width); if let Some(size) = maybe_size { - let value = LocalType::Value { + let ty = LocalType::Value { vector_size: Some(size), kind: crate::ScalarKind::Float, width, pointer_space: None, - }; - - let result_type_id = self.get_type_id(LookupType::Local(value)); + } + .into(); self.temp_list.clear(); self.temp_list.resize(size as _, arg1_id); - let id = self.gen_id(); - block.body.push(Instruction::constant_composite( - result_type_id, - id, - &self.temp_list, - )); - arg1_id = id; + arg1_id = self.writer.get_constant_composite(ty, &self.temp_list); - self.temp_list.clear(); - self.temp_list.resize(size as _, arg2_id); + self.temp_list.fill(arg2_id); - let id = self.gen_id(); - block.body.push(Instruction::constant_composite( - result_type_id, - id, - &self.temp_list, - )); - arg2_id = id; + arg2_id = self.writer.get_constant_composite(ty, &self.temp_list); } MathOp::Custom(Instruction::ext_inst( @@ -893,25 +879,22 @@ impl<'w> BlockContext<'w> { let (int_type_id, int_id) = match *arg_ty { crate::TypeInner::Vector { size, width, .. } => { - let ty = self.get_type_id(LookupType::Local(LocalType::Value { + let ty = LocalType::Value { vector_size: Some(size), kind: crate::ScalarKind::Sint, width, pointer_space: None, - })); + } + .into(); self.temp_list.clear(); self.temp_list .resize(size as _, self.writer.get_constant_scalar(int, width)); - let id = self.gen_id(); - block.body.push(Instruction::constant_composite( - ty, - id, - &self.temp_list, - )); - - (ty, id) + ( + self.get_type_id(ty), + self.writer.get_constant_composite(ty, &self.temp_list), + ) } crate::TypeInner::Scalar { width, .. } => ( self.get_type_id(LookupType::Local(LocalType::Value { @@ -1127,22 +1110,18 @@ impl<'w> BlockContext<'w> { let zero_scalar_id = self.writer.get_constant_scalar(value, src_width); let zero_id = match src_size { Some(size) => { - let vector_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(size), - kind: src_kind, - width: src_width, - pointer_space: None, - })); - let components = [zero_scalar_id; 4]; + let ty = LocalType::Value { + vector_size: Some(size), + kind: src_kind, + width: src_width, + pointer_space: None, + } + .into(); - let zero_id = self.gen_id(); - block.body.push(Instruction::composite_construct( - vector_type_id, - zero_id, - &components[..size as usize], - )); - zero_id + self.temp_list.clear(); + self.temp_list.resize(size as _, zero_scalar_id); + + self.writer.get_constant_composite(ty, &self.temp_list) } None => zero_scalar_id, }; @@ -1168,28 +1147,25 @@ impl<'w> BlockContext<'w> { let scalar1_id = self.writer.get_constant_scalar(val1, dst_width); let (accept_id, reject_id) = match src_size { Some(size) => { - let vector_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(size), - kind, - width: dst_width, - pointer_space: None, - })); - let components0 = [scalar0_id; 4]; - let components1 = [scalar1_id; 4]; + let ty = LocalType::Value { + vector_size: Some(size), + kind, + width: dst_width, + pointer_space: None, + } + .into(); + + self.temp_list.clear(); + self.temp_list.resize(size as _, scalar0_id); + + let vec0_id = + self.writer.get_constant_composite(ty, &self.temp_list); + + self.temp_list.fill(scalar1_id); + + let vec1_id = + self.writer.get_constant_composite(ty, &self.temp_list); - let vec0_id = self.gen_id(); - block.body.push(Instruction::composite_construct( - vector_type_id, - vec0_id, - &components0[..size as usize], - )); - let vec1_id = self.gen_id(); - block.body.push(Instruction::composite_construct( - vector_type_id, - vec1_id, - &components1[..size as usize], - )); (vec1_id, vec0_id) } None => (scalar1_id, scalar0_id), diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index e19d825a0..72898219a 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -439,6 +439,18 @@ impl recyclable::Recyclable for CachedExpressions { } } +#[derive(Eq, Hash, PartialEq)] +enum CachedConstant { + Scalar { + value: crate::ScalarValue, + width: crate::Bytes, + }, + Composite { + ty: LookupType, + constituent_ids: Vec, + }, +} + #[derive(Clone)] struct GlobalVariable { /// ID of the OpVariable that declares the global. @@ -589,7 +601,7 @@ pub struct Writer { lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, constant_ids: Vec, - cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>, + cached_constants: crate::FastHashMap, global_variables: Vec, binding_map: BindingMap, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index caf3f72ce..87b005177 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,7 +1,7 @@ use super::{ helpers::{contains_builtin, global_needs_wrapper, map_storage_class}, - make_local, Block, BlockContext, CachedExpressions, EntryPointContext, Error, Function, - FunctionArgument, GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, + make_local, Block, BlockContext, CachedConstant, CachedExpressions, EntryPointContext, Error, + Function, FunctionArgument, GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, LogicalLayout, LookupFunctionType, LookupType, LoopContext, Options, PhysicalLayout, PipelineOptions, ResultMember, Writer, WriterFlags, BITS_PER_BYTE, }; @@ -1101,12 +1101,13 @@ impl Writer { value: crate::ScalarValue, width: crate::Bytes, ) -> Word { - if let Some(&id) = self.cached_constants.get(&(value, width)) { + let scalar = CachedConstant::Scalar { value, width }; + if let Some(&id) = self.cached_constants.get(&scalar) { return id; } let id = self.id_gen.next(); self.write_constant_scalar(id, &value, width, None); - self.cached_constants.insert((value, width), id); + self.cached_constants.insert(scalar, id); id } @@ -1180,22 +1181,39 @@ impl Writer { instruction.to_words(&mut self.logical_layout.declarations); } + pub(super) fn get_constant_composite( + &mut self, + ty: LookupType, + constituent_ids: &[Word], + ) -> Word { + let composite = CachedConstant::Composite { + ty, + constituent_ids: constituent_ids.to_vec(), + }; + if let Some(&id) = self.cached_constants.get(&composite) { + return id; + } + let id = self.id_gen.next(); + self.write_constant_composite(id, ty, constituent_ids, None); + self.cached_constants.insert(composite, id); + id + } + fn write_constant_composite( &mut self, id: Word, - ty: Handle, - components: &[Handle], - ) -> Result<(), Error> { - let mut constituent_ids = Vec::with_capacity(components.len()); - for constituent in components.iter() { - let constituent_id = self.constant_ids[constituent.index()]; - constituent_ids.push(constituent_id); + ty: LookupType, + constituent_ids: &[Word], + debug_name: Option<&String>, + ) { + if self.flags.contains(WriterFlags::DEBUG) { + if let Some(name) = debug_name { + self.debugs.push(Instruction::name(id, name)); + } } - - let type_id = self.get_type_id(LookupType::Handle(ty)); - Instruction::constant_composite(type_id, id, constituent_ids.as_slice()) + let type_id = self.get_type_id(ty); + Instruction::constant_composite(type_id, id, constituent_ids) .to_words(&mut self.logical_layout.declarations); - Ok(()) } pub(super) fn write_constant_null(&mut self, type_id: Word) -> Word { @@ -1776,19 +1794,27 @@ impl Writer { self.write_type_declaration_arena(&ir_module.types, handle)?; } - // the all the composite constants, they rely on types + // then all the composite constants, they rely on types for (handle, constant) in ir_module.constants.iter() { match constant.inner { crate::ConstantInner::Scalar { .. } => continue, crate::ConstantInner::Composite { ty, ref components } => { - let id = self.id_gen.next(); - self.constant_ids[handle.index()] = id; - if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = constant.name { - self.debugs.push(Instruction::name(id, name)); - } + let ty = LookupType::Handle(ty); + + let mut constituent_ids = Vec::with_capacity(components.len()); + for constituent in components.iter() { + let constituent_id = self.constant_ids[constituent.index()]; + constituent_ids.push(constituent_id); } - self.write_constant_composite(id, ty, components)?; + + self.constant_ids[handle.index()] = match constant.name { + Some(ref name) => { + let id = self.id_gen.next(); + self.write_constant_composite(id, ty, &constituent_ids, Some(name)); + id + } + None => self.get_constant_composite(ty, &constituent_ids), + }; } } } diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 131c6cace..a65f53518 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 55 +; Bound: 54 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -20,13 +20,12 @@ OpEntryPoint Vertex %16 "main" %13 = OpTypeVector %7 2 %14 = OpConstantComposite %13 %6 %6 %17 = OpTypeFunction %2 -%40 = OpConstant %7 31 -%49 = OpTypeVector %9 2 %25 = OpConstantComposite %12 %5 %5 %5 %5 %26 = OpConstantComposite %12 %3 %3 %3 %3 -%29 = OpConstantNull %7 +%40 = OpConstant %7 31 %47 = OpConstantComposite %13 %40 %40 -%52 = OpConstantComposite %13 %40 %40 +%49 = OpTypeVector %9 2 +%29 = OpConstantNull %7 %16 = OpFunction %2 None %17 %15 = OpLabel OpBranch %18 @@ -58,7 +57,7 @@ OpBranch %18 %48 = OpISub %13 %47 %46 %50 = OpCompositeConstruct %49 %11 %11 %51 = OpExtInst %13 %1 FindUMsb %50 -%53 = OpISub %13 %52 %51 -%54 = OpBitcast %49 %53 +%52 = OpISub %13 %47 %51 +%53 = OpBitcast %49 %52 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 3263e223f..d3c595e67 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 574 +; Bound: 573 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %562 "main" -OpExecutionMode %562 LocalSize 1 1 1 +OpEntryPoint GLCompute %561 "main" +OpExecutionMode %561 LocalSize 1 1 1 OpMemberDecorate %40 0 Offset 0 OpMemberDecorate %40 1 Offset 16 OpDecorate %44 ArrayStride 32 @@ -81,20 +81,22 @@ OpDecorate %45 ArrayStride 4 %110 = OpConstantNull %37 %113 = OpTypeFunction %37 %129 = OpTypeFunction %38 %38 -%137 = OpTypePointer Function %40 -%138 = OpConstantNull %40 -%141 = OpTypeFunction %4 -%166 = OpTypePointer Function %34 -%167 = OpTypePointer Function %4 -%172 = OpTypeFunction %2 -%175 = OpTypeVector %10 2 -%191 = OpTypeVector %8 2 -%202 = OpTypeVector %20 3 -%497 = OpTypePointer Function %8 -%498 = OpConstantNull %8 -%500 = OpTypePointer Function %50 -%501 = OpConstantNull %50 -%531 = OpTypePointer Function %8 +%131 = OpConstantComposite %38 %5 %5 %5 +%133 = OpConstantComposite %38 %3 %3 %3 +%136 = OpTypePointer Function %40 +%137 = OpConstantNull %40 +%140 = OpTypeFunction %4 +%165 = OpTypePointer Function %34 +%166 = OpTypePointer Function %4 +%171 = OpTypeFunction %2 +%174 = OpTypeVector %10 2 +%190 = OpTypeVector %8 2 +%201 = OpTypeVector %20 3 +%496 = OpTypePointer Function %8 +%497 = OpConstantNull %8 +%499 = OpTypePointer Function %50 +%500 = OpConstantNull %50 +%530 = OpTypePointer Function %8 %68 = OpFunction %34 None %69 %67 = OpLabel OpBranch %70 @@ -168,469 +170,466 @@ OpFunctionEnd %126 = OpLabel OpBranch %130 %130 = OpLabel -%131 = OpCompositeConstruct %38 %5 %5 %5 %132 = OpFUnordNotEqual %39 %127 %131 -%133 = OpCompositeConstruct %38 %5 %5 %5 -%134 = OpCompositeConstruct %38 %3 %3 %3 -%135 = OpSelect %38 %132 %134 %133 -OpReturnValue %135 +%134 = OpSelect %38 %132 %133 %131 +OpReturnValue %134 OpFunctionEnd -%140 = OpFunction %4 None %141 -%139 = OpLabel -%136 = OpVariable %137 Function %138 -OpBranch %142 -%142 = OpLabel -%143 = OpCompositeConstruct %34 %3 %3 %3 %3 -%144 = OpCompositeConstruct %40 %143 %7 -OpStore %136 %144 -%145 = OpCompositeConstruct %37 %3 %5 -%146 = OpCompositeConstruct %37 %5 %3 -%147 = OpCompositeConstruct %41 %145 %146 -%148 = OpCompositeConstruct %34 %3 %5 %5 %5 -%149 = OpCompositeConstruct %34 %5 %3 %5 %5 -%150 = OpCompositeConstruct %34 %5 %5 %3 %5 -%151 = OpCompositeConstruct %34 %5 %5 %5 %3 -%152 = OpCompositeConstruct %42 %148 %149 %150 %151 -%153 = OpCompositeConstruct %43 %19 %19 +%139 = OpFunction %4 None %140 +%138 = OpLabel +%135 = OpVariable %136 Function %137 +OpBranch %141 +%141 = OpLabel +%142 = OpCompositeConstruct %34 %3 %3 %3 %3 +%143 = OpCompositeConstruct %40 %142 %7 +OpStore %135 %143 +%144 = OpCompositeConstruct %37 %3 %5 +%145 = OpCompositeConstruct %37 %5 %3 +%146 = OpCompositeConstruct %41 %144 %145 +%147 = OpCompositeConstruct %34 %3 %5 %5 %5 +%148 = OpCompositeConstruct %34 %5 %3 %5 %5 +%149 = OpCompositeConstruct %34 %5 %5 %3 %5 +%150 = OpCompositeConstruct %34 %5 %5 %5 %3 +%151 = OpCompositeConstruct %42 %147 %148 %149 %150 +%152 = OpCompositeConstruct %43 %19 %19 +%153 = OpCompositeConstruct %37 %5 %5 %154 = OpCompositeConstruct %37 %5 %5 -%155 = OpCompositeConstruct %37 %5 %5 -%156 = OpCompositeConstruct %41 %154 %155 -%157 = OpCompositeConstruct %45 %11 %7 %18 %21 -%163 = OpCopyObject %46 %62 -%165 = OpCopyObject %46 %62 -%168 = OpAccessChain %167 %136 %19 %19 -%169 = OpLoad %4 %168 -OpReturnValue %169 +%155 = OpCompositeConstruct %41 %153 %154 +%156 = OpCompositeConstruct %45 %11 %7 %18 %21 +%162 = OpCopyObject %46 %62 +%164 = OpCopyObject %46 %62 +%167 = OpAccessChain %166 %135 %19 %19 +%168 = OpLoad %4 %167 +OpReturnValue %168 OpFunctionEnd -%171 = OpFunction %2 None %172 -%170 = OpLabel -OpBranch %173 -%173 = OpLabel -%174 = OpLogicalNot %10 %9 -%176 = OpCompositeConstruct %175 %9 %9 -%177 = OpLogicalNot %175 %176 -%178 = OpLogicalOr %10 %9 %12 -%179 = OpLogicalAnd %10 %9 %12 -%180 = OpLogicalOr %10 %9 %12 -%181 = OpCompositeConstruct %39 %9 %9 %9 -%182 = OpCompositeConstruct %39 %12 %12 %12 -%183 = OpLogicalOr %39 %181 %182 -%184 = OpLogicalAnd %10 %9 %12 -%185 = OpCompositeConstruct %36 %9 %9 %9 %9 -%186 = OpCompositeConstruct %36 %12 %12 %12 %12 -%187 = OpLogicalAnd %36 %185 %186 +%170 = OpFunction %2 None %171 +%169 = OpLabel +OpBranch %172 +%172 = OpLabel +%173 = OpLogicalNot %10 %9 +%175 = OpCompositeConstruct %174 %9 %9 +%176 = OpLogicalNot %174 %175 +%177 = OpLogicalOr %10 %9 %12 +%178 = OpLogicalAnd %10 %9 %12 +%179 = OpLogicalOr %10 %9 %12 +%180 = OpCompositeConstruct %39 %9 %9 %9 +%181 = OpCompositeConstruct %39 %12 %12 %12 +%182 = OpLogicalOr %39 %180 %181 +%183 = OpLogicalAnd %10 %9 %12 +%184 = OpCompositeConstruct %36 %9 %9 %9 %9 +%185 = OpCompositeConstruct %36 %12 %12 %12 %12 +%186 = OpLogicalAnd %36 %184 %185 OpReturn OpFunctionEnd -%189 = OpFunction %2 None %172 -%188 = OpLabel -OpBranch %190 -%190 = OpLabel -%192 = OpCompositeConstruct %191 %7 %7 -%193 = OpSNegate %191 %192 -%194 = OpCompositeConstruct %37 %3 %3 -%195 = OpFNegate %37 %194 -%196 = OpIAdd %8 %18 %7 -%197 = OpIAdd %20 %24 %25 -%198 = OpFAdd %4 %14 %3 -%199 = OpCompositeConstruct %191 %18 %18 -%200 = OpCompositeConstruct %191 %7 %7 -%201 = OpIAdd %191 %199 %200 -%203 = OpCompositeConstruct %202 %24 %24 %24 -%204 = OpCompositeConstruct %202 %25 %25 %25 -%205 = OpIAdd %202 %203 %204 -%206 = OpCompositeConstruct %34 %14 %14 %14 %14 -%207 = OpCompositeConstruct %34 %3 %3 %3 %3 -%208 = OpFAdd %34 %206 %207 -%209 = OpISub %8 %18 %7 -%210 = OpISub %20 %24 %25 -%211 = OpFSub %4 %14 %3 -%212 = OpCompositeConstruct %191 %18 %18 -%213 = OpCompositeConstruct %191 %7 %7 -%214 = OpISub %191 %212 %213 -%215 = OpCompositeConstruct %202 %24 %24 %24 -%216 = OpCompositeConstruct %202 %25 %25 %25 -%217 = OpISub %202 %215 %216 -%218 = OpCompositeConstruct %34 %14 %14 %14 %14 -%219 = OpCompositeConstruct %34 %3 %3 %3 %3 -%220 = OpFSub %34 %218 %219 -%221 = OpIMul %8 %18 %7 -%222 = OpIMul %20 %24 %25 -%223 = OpFMul %4 %14 %3 -%224 = OpCompositeConstruct %191 %18 %18 -%225 = OpCompositeConstruct %191 %7 %7 -%226 = OpIMul %191 %224 %225 -%227 = OpCompositeConstruct %202 %24 %24 %24 -%228 = OpCompositeConstruct %202 %25 %25 %25 -%229 = OpIMul %202 %227 %228 -%230 = OpCompositeConstruct %34 %14 %14 %14 %14 -%231 = OpCompositeConstruct %34 %3 %3 %3 %3 -%232 = OpFMul %34 %230 %231 -%233 = OpSDiv %8 %18 %7 -%234 = OpUDiv %20 %24 %25 -%235 = OpFDiv %4 %14 %3 -%236 = OpCompositeConstruct %191 %18 %18 -%237 = OpCompositeConstruct %191 %7 %7 -%238 = OpSDiv %191 %236 %237 -%239 = OpCompositeConstruct %202 %24 %24 %24 -%240 = OpCompositeConstruct %202 %25 %25 %25 -%241 = OpUDiv %202 %239 %240 -%242 = OpCompositeConstruct %34 %14 %14 %14 %14 -%243 = OpCompositeConstruct %34 %3 %3 %3 %3 -%244 = OpFDiv %34 %242 %243 -%245 = OpSRem %8 %18 %7 -%246 = OpUMod %20 %24 %25 -%247 = OpFRem %4 %14 %3 -%248 = OpCompositeConstruct %191 %18 %18 -%249 = OpCompositeConstruct %191 %7 %7 -%250 = OpSRem %191 %248 %249 -%251 = OpCompositeConstruct %202 %24 %24 %24 -%252 = OpCompositeConstruct %202 %25 %25 %25 -%253 = OpUMod %202 %251 %252 -%254 = OpCompositeConstruct %34 %14 %14 %14 %14 -%255 = OpCompositeConstruct %34 %3 %3 %3 %3 -%256 = OpFRem %34 %254 %255 -%257 = OpCompositeConstruct %191 %18 %18 -%258 = OpCompositeConstruct %191 %7 %7 -%259 = OpIAdd %191 %257 %258 -%260 = OpCompositeConstruct %191 %7 %7 -%261 = OpCompositeConstruct %191 %18 %18 -%262 = OpIAdd %191 %261 %260 -%263 = OpCompositeConstruct %43 %24 %24 -%264 = OpCompositeConstruct %43 %25 %25 -%265 = OpIAdd %43 %263 %264 -%266 = OpCompositeConstruct %43 %25 %25 -%267 = OpCompositeConstruct %43 %24 %24 -%268 = OpIAdd %43 %267 %266 -%269 = OpCompositeConstruct %37 %14 %14 -%270 = OpCompositeConstruct %37 %3 %3 -%271 = OpFAdd %37 %269 %270 -%272 = OpCompositeConstruct %37 %3 %3 -%273 = OpCompositeConstruct %37 %14 %14 -%274 = OpFAdd %37 %273 %272 -%275 = OpCompositeConstruct %191 %18 %18 -%276 = OpCompositeConstruct %191 %7 %7 -%277 = OpISub %191 %275 %276 -%278 = OpCompositeConstruct %191 %7 %7 -%279 = OpCompositeConstruct %191 %18 %18 -%280 = OpISub %191 %279 %278 -%281 = OpCompositeConstruct %43 %24 %24 -%282 = OpCompositeConstruct %43 %25 %25 -%283 = OpISub %43 %281 %282 -%284 = OpCompositeConstruct %43 %25 %25 -%285 = OpCompositeConstruct %43 %24 %24 -%286 = OpISub %43 %285 %284 -%287 = OpCompositeConstruct %37 %14 %14 -%288 = OpCompositeConstruct %37 %3 %3 -%289 = OpFSub %37 %287 %288 -%290 = OpCompositeConstruct %37 %3 %3 -%291 = OpCompositeConstruct %37 %14 %14 -%292 = OpFSub %37 %291 %290 -%293 = OpCompositeConstruct %191 %18 %18 -%295 = OpCompositeConstruct %191 %7 %7 -%294 = OpIMul %191 %293 %295 -%296 = OpCompositeConstruct %191 %7 %7 -%298 = OpCompositeConstruct %191 %18 %18 -%297 = OpIMul %191 %296 %298 -%299 = OpCompositeConstruct %43 %24 %24 +%188 = OpFunction %2 None %171 +%187 = OpLabel +OpBranch %189 +%189 = OpLabel +%191 = OpCompositeConstruct %190 %7 %7 +%192 = OpSNegate %190 %191 +%193 = OpCompositeConstruct %37 %3 %3 +%194 = OpFNegate %37 %193 +%195 = OpIAdd %8 %18 %7 +%196 = OpIAdd %20 %24 %25 +%197 = OpFAdd %4 %14 %3 +%198 = OpCompositeConstruct %190 %18 %18 +%199 = OpCompositeConstruct %190 %7 %7 +%200 = OpIAdd %190 %198 %199 +%202 = OpCompositeConstruct %201 %24 %24 %24 +%203 = OpCompositeConstruct %201 %25 %25 %25 +%204 = OpIAdd %201 %202 %203 +%205 = OpCompositeConstruct %34 %14 %14 %14 %14 +%206 = OpCompositeConstruct %34 %3 %3 %3 %3 +%207 = OpFAdd %34 %205 %206 +%208 = OpISub %8 %18 %7 +%209 = OpISub %20 %24 %25 +%210 = OpFSub %4 %14 %3 +%211 = OpCompositeConstruct %190 %18 %18 +%212 = OpCompositeConstruct %190 %7 %7 +%213 = OpISub %190 %211 %212 +%214 = OpCompositeConstruct %201 %24 %24 %24 +%215 = OpCompositeConstruct %201 %25 %25 %25 +%216 = OpISub %201 %214 %215 +%217 = OpCompositeConstruct %34 %14 %14 %14 %14 +%218 = OpCompositeConstruct %34 %3 %3 %3 %3 +%219 = OpFSub %34 %217 %218 +%220 = OpIMul %8 %18 %7 +%221 = OpIMul %20 %24 %25 +%222 = OpFMul %4 %14 %3 +%223 = OpCompositeConstruct %190 %18 %18 +%224 = OpCompositeConstruct %190 %7 %7 +%225 = OpIMul %190 %223 %224 +%226 = OpCompositeConstruct %201 %24 %24 %24 +%227 = OpCompositeConstruct %201 %25 %25 %25 +%228 = OpIMul %201 %226 %227 +%229 = OpCompositeConstruct %34 %14 %14 %14 %14 +%230 = OpCompositeConstruct %34 %3 %3 %3 %3 +%231 = OpFMul %34 %229 %230 +%232 = OpSDiv %8 %18 %7 +%233 = OpUDiv %20 %24 %25 +%234 = OpFDiv %4 %14 %3 +%235 = OpCompositeConstruct %190 %18 %18 +%236 = OpCompositeConstruct %190 %7 %7 +%237 = OpSDiv %190 %235 %236 +%238 = OpCompositeConstruct %201 %24 %24 %24 +%239 = OpCompositeConstruct %201 %25 %25 %25 +%240 = OpUDiv %201 %238 %239 +%241 = OpCompositeConstruct %34 %14 %14 %14 %14 +%242 = OpCompositeConstruct %34 %3 %3 %3 %3 +%243 = OpFDiv %34 %241 %242 +%244 = OpSRem %8 %18 %7 +%245 = OpUMod %20 %24 %25 +%246 = OpFRem %4 %14 %3 +%247 = OpCompositeConstruct %190 %18 %18 +%248 = OpCompositeConstruct %190 %7 %7 +%249 = OpSRem %190 %247 %248 +%250 = OpCompositeConstruct %201 %24 %24 %24 +%251 = OpCompositeConstruct %201 %25 %25 %25 +%252 = OpUMod %201 %250 %251 +%253 = OpCompositeConstruct %34 %14 %14 %14 %14 +%254 = OpCompositeConstruct %34 %3 %3 %3 %3 +%255 = OpFRem %34 %253 %254 +%256 = OpCompositeConstruct %190 %18 %18 +%257 = OpCompositeConstruct %190 %7 %7 +%258 = OpIAdd %190 %256 %257 +%259 = OpCompositeConstruct %190 %7 %7 +%260 = OpCompositeConstruct %190 %18 %18 +%261 = OpIAdd %190 %260 %259 +%262 = OpCompositeConstruct %43 %24 %24 +%263 = OpCompositeConstruct %43 %25 %25 +%264 = OpIAdd %43 %262 %263 +%265 = OpCompositeConstruct %43 %25 %25 +%266 = OpCompositeConstruct %43 %24 %24 +%267 = OpIAdd %43 %266 %265 +%268 = OpCompositeConstruct %37 %14 %14 +%269 = OpCompositeConstruct %37 %3 %3 +%270 = OpFAdd %37 %268 %269 +%271 = OpCompositeConstruct %37 %3 %3 +%272 = OpCompositeConstruct %37 %14 %14 +%273 = OpFAdd %37 %272 %271 +%274 = OpCompositeConstruct %190 %18 %18 +%275 = OpCompositeConstruct %190 %7 %7 +%276 = OpISub %190 %274 %275 +%277 = OpCompositeConstruct %190 %7 %7 +%278 = OpCompositeConstruct %190 %18 %18 +%279 = OpISub %190 %278 %277 +%280 = OpCompositeConstruct %43 %24 %24 +%281 = OpCompositeConstruct %43 %25 %25 +%282 = OpISub %43 %280 %281 +%283 = OpCompositeConstruct %43 %25 %25 +%284 = OpCompositeConstruct %43 %24 %24 +%285 = OpISub %43 %284 %283 +%286 = OpCompositeConstruct %37 %14 %14 +%287 = OpCompositeConstruct %37 %3 %3 +%288 = OpFSub %37 %286 %287 +%289 = OpCompositeConstruct %37 %3 %3 +%290 = OpCompositeConstruct %37 %14 %14 +%291 = OpFSub %37 %290 %289 +%292 = OpCompositeConstruct %190 %18 %18 +%294 = OpCompositeConstruct %190 %7 %7 +%293 = OpIMul %190 %292 %294 +%295 = OpCompositeConstruct %190 %7 %7 +%297 = OpCompositeConstruct %190 %18 %18 +%296 = OpIMul %190 %295 %297 +%298 = OpCompositeConstruct %43 %24 %24 +%300 = OpCompositeConstruct %43 %25 %25 +%299 = OpIMul %43 %298 %300 %301 = OpCompositeConstruct %43 %25 %25 -%300 = OpIMul %43 %299 %301 -%302 = OpCompositeConstruct %43 %25 %25 -%304 = OpCompositeConstruct %43 %24 %24 -%303 = OpIMul %43 %302 %304 -%305 = OpCompositeConstruct %37 %14 %14 -%306 = OpVectorTimesScalar %37 %305 %3 -%307 = OpCompositeConstruct %37 %3 %3 -%308 = OpVectorTimesScalar %37 %307 %14 -%309 = OpCompositeConstruct %191 %18 %18 -%310 = OpCompositeConstruct %191 %7 %7 -%311 = OpSDiv %191 %309 %310 -%312 = OpCompositeConstruct %191 %7 %7 -%313 = OpCompositeConstruct %191 %18 %18 -%314 = OpSDiv %191 %313 %312 -%315 = OpCompositeConstruct %43 %24 %24 -%316 = OpCompositeConstruct %43 %25 %25 -%317 = OpUDiv %43 %315 %316 -%318 = OpCompositeConstruct %43 %25 %25 -%319 = OpCompositeConstruct %43 %24 %24 -%320 = OpUDiv %43 %319 %318 -%321 = OpCompositeConstruct %37 %14 %14 -%322 = OpCompositeConstruct %37 %3 %3 -%323 = OpFDiv %37 %321 %322 -%324 = OpCompositeConstruct %37 %3 %3 -%325 = OpCompositeConstruct %37 %14 %14 -%326 = OpFDiv %37 %325 %324 -%327 = OpCompositeConstruct %191 %18 %18 -%328 = OpCompositeConstruct %191 %7 %7 -%329 = OpSRem %191 %327 %328 -%330 = OpCompositeConstruct %191 %7 %7 -%331 = OpCompositeConstruct %191 %18 %18 -%332 = OpSRem %191 %331 %330 -%333 = OpCompositeConstruct %43 %24 %24 -%334 = OpCompositeConstruct %43 %25 %25 -%335 = OpUMod %43 %333 %334 -%336 = OpCompositeConstruct %43 %25 %25 -%337 = OpCompositeConstruct %43 %24 %24 -%338 = OpUMod %43 %337 %336 -%339 = OpCompositeConstruct %37 %14 %14 -%340 = OpCompositeConstruct %37 %3 %3 -%341 = OpFRem %37 %339 %340 -%342 = OpCompositeConstruct %37 %3 %3 -%343 = OpCompositeConstruct %37 %14 %14 -%344 = OpFRem %37 %343 %342 +%303 = OpCompositeConstruct %43 %24 %24 +%302 = OpIMul %43 %301 %303 +%304 = OpCompositeConstruct %37 %14 %14 +%305 = OpVectorTimesScalar %37 %304 %3 +%306 = OpCompositeConstruct %37 %3 %3 +%307 = OpVectorTimesScalar %37 %306 %14 +%308 = OpCompositeConstruct %190 %18 %18 +%309 = OpCompositeConstruct %190 %7 %7 +%310 = OpSDiv %190 %308 %309 +%311 = OpCompositeConstruct %190 %7 %7 +%312 = OpCompositeConstruct %190 %18 %18 +%313 = OpSDiv %190 %312 %311 +%314 = OpCompositeConstruct %43 %24 %24 +%315 = OpCompositeConstruct %43 %25 %25 +%316 = OpUDiv %43 %314 %315 +%317 = OpCompositeConstruct %43 %25 %25 +%318 = OpCompositeConstruct %43 %24 %24 +%319 = OpUDiv %43 %318 %317 +%320 = OpCompositeConstruct %37 %14 %14 +%321 = OpCompositeConstruct %37 %3 %3 +%322 = OpFDiv %37 %320 %321 +%323 = OpCompositeConstruct %37 %3 %3 +%324 = OpCompositeConstruct %37 %14 %14 +%325 = OpFDiv %37 %324 %323 +%326 = OpCompositeConstruct %190 %18 %18 +%327 = OpCompositeConstruct %190 %7 %7 +%328 = OpSRem %190 %326 %327 +%329 = OpCompositeConstruct %190 %7 %7 +%330 = OpCompositeConstruct %190 %18 %18 +%331 = OpSRem %190 %330 %329 +%332 = OpCompositeConstruct %43 %24 %24 +%333 = OpCompositeConstruct %43 %25 %25 +%334 = OpUMod %43 %332 %333 +%335 = OpCompositeConstruct %43 %25 %25 +%336 = OpCompositeConstruct %43 %24 %24 +%337 = OpUMod %43 %336 %335 +%338 = OpCompositeConstruct %37 %14 %14 +%339 = OpCompositeConstruct %37 %3 %3 +%340 = OpFRem %37 %338 %339 +%341 = OpCompositeConstruct %37 %3 %3 +%342 = OpCompositeConstruct %37 %14 %14 +%343 = OpFRem %37 %342 %341 +%345 = OpCompositeExtract %38 %63 0 %346 = OpCompositeExtract %38 %63 0 -%347 = OpCompositeExtract %38 %63 0 -%348 = OpFAdd %38 %346 %347 +%347 = OpFAdd %38 %345 %346 +%348 = OpCompositeExtract %38 %63 1 %349 = OpCompositeExtract %38 %63 1 -%350 = OpCompositeExtract %38 %63 1 -%351 = OpFAdd %38 %349 %350 +%350 = OpFAdd %38 %348 %349 +%351 = OpCompositeExtract %38 %63 2 %352 = OpCompositeExtract %38 %63 2 -%353 = OpCompositeExtract %38 %63 2 -%354 = OpFAdd %38 %352 %353 -%345 = OpCompositeConstruct %47 %348 %351 %354 +%353 = OpFAdd %38 %351 %352 +%344 = OpCompositeConstruct %47 %347 %350 %353 +%355 = OpCompositeExtract %38 %63 0 %356 = OpCompositeExtract %38 %63 0 -%357 = OpCompositeExtract %38 %63 0 -%358 = OpFSub %38 %356 %357 +%357 = OpFSub %38 %355 %356 +%358 = OpCompositeExtract %38 %63 1 %359 = OpCompositeExtract %38 %63 1 -%360 = OpCompositeExtract %38 %63 1 -%361 = OpFSub %38 %359 %360 +%360 = OpFSub %38 %358 %359 +%361 = OpCompositeExtract %38 %63 2 %362 = OpCompositeExtract %38 %63 2 -%363 = OpCompositeExtract %38 %63 2 -%364 = OpFSub %38 %362 %363 -%355 = OpCompositeConstruct %47 %358 %361 %364 -%365 = OpMatrixTimesScalar %47 %63 %3 -%366 = OpMatrixTimesScalar %47 %63 %14 -%367 = OpCompositeConstruct %34 %3 %3 %3 %3 -%368 = OpMatrixTimesVector %38 %64 %367 -%369 = OpCompositeConstruct %38 %14 %14 %14 -%370 = OpVectorTimesMatrix %34 %369 %64 -%371 = OpMatrixTimesMatrix %47 %64 %65 +%363 = OpFSub %38 %361 %362 +%354 = OpCompositeConstruct %47 %357 %360 %363 +%364 = OpMatrixTimesScalar %47 %63 %3 +%365 = OpMatrixTimesScalar %47 %63 %14 +%366 = OpCompositeConstruct %34 %3 %3 %3 %3 +%367 = OpMatrixTimesVector %38 %64 %366 +%368 = OpCompositeConstruct %38 %14 %14 %14 +%369 = OpVectorTimesMatrix %34 %368 %64 +%370 = OpMatrixTimesMatrix %47 %64 %65 OpReturn OpFunctionEnd -%373 = OpFunction %2 None %172 -%372 = OpLabel -OpBranch %374 -%374 = OpLabel -%375 = OpNot %8 %7 -%376 = OpNot %20 %25 -%377 = OpCompositeConstruct %191 %7 %7 -%378 = OpNot %191 %377 -%379 = OpCompositeConstruct %202 %25 %25 %25 -%380 = OpNot %202 %379 -%381 = OpBitwiseOr %8 %18 %7 -%382 = OpBitwiseOr %20 %24 %25 -%383 = OpCompositeConstruct %191 %18 %18 -%384 = OpCompositeConstruct %191 %7 %7 -%385 = OpBitwiseOr %191 %383 %384 -%386 = OpCompositeConstruct %202 %24 %24 %24 -%387 = OpCompositeConstruct %202 %25 %25 %25 -%388 = OpBitwiseOr %202 %386 %387 -%389 = OpBitwiseAnd %8 %18 %7 -%390 = OpBitwiseAnd %20 %24 %25 -%391 = OpCompositeConstruct %191 %18 %18 -%392 = OpCompositeConstruct %191 %7 %7 -%393 = OpBitwiseAnd %191 %391 %392 -%394 = OpCompositeConstruct %202 %24 %24 %24 -%395 = OpCompositeConstruct %202 %25 %25 %25 -%396 = OpBitwiseAnd %202 %394 %395 -%397 = OpBitwiseXor %8 %18 %7 -%398 = OpBitwiseXor %20 %24 %25 -%399 = OpCompositeConstruct %191 %18 %18 -%400 = OpCompositeConstruct %191 %7 %7 -%401 = OpBitwiseXor %191 %399 %400 -%402 = OpCompositeConstruct %202 %24 %24 %24 -%403 = OpCompositeConstruct %202 %25 %25 %25 -%404 = OpBitwiseXor %202 %402 %403 -%405 = OpShiftLeftLogical %8 %18 %25 -%406 = OpShiftLeftLogical %20 %24 %25 -%407 = OpCompositeConstruct %191 %18 %18 -%408 = OpCompositeConstruct %43 %25 %25 -%409 = OpShiftLeftLogical %191 %407 %408 -%410 = OpCompositeConstruct %202 %24 %24 %24 -%411 = OpCompositeConstruct %202 %25 %25 %25 -%412 = OpShiftLeftLogical %202 %410 %411 -%413 = OpShiftRightArithmetic %8 %18 %25 -%414 = OpShiftRightLogical %20 %24 %25 -%415 = OpCompositeConstruct %191 %18 %18 -%416 = OpCompositeConstruct %43 %25 %25 -%417 = OpShiftRightArithmetic %191 %415 %416 -%418 = OpCompositeConstruct %202 %24 %24 %24 -%419 = OpCompositeConstruct %202 %25 %25 %25 -%420 = OpShiftRightLogical %202 %418 %419 +%372 = OpFunction %2 None %171 +%371 = OpLabel +OpBranch %373 +%373 = OpLabel +%374 = OpNot %8 %7 +%375 = OpNot %20 %25 +%376 = OpCompositeConstruct %190 %7 %7 +%377 = OpNot %190 %376 +%378 = OpCompositeConstruct %201 %25 %25 %25 +%379 = OpNot %201 %378 +%380 = OpBitwiseOr %8 %18 %7 +%381 = OpBitwiseOr %20 %24 %25 +%382 = OpCompositeConstruct %190 %18 %18 +%383 = OpCompositeConstruct %190 %7 %7 +%384 = OpBitwiseOr %190 %382 %383 +%385 = OpCompositeConstruct %201 %24 %24 %24 +%386 = OpCompositeConstruct %201 %25 %25 %25 +%387 = OpBitwiseOr %201 %385 %386 +%388 = OpBitwiseAnd %8 %18 %7 +%389 = OpBitwiseAnd %20 %24 %25 +%390 = OpCompositeConstruct %190 %18 %18 +%391 = OpCompositeConstruct %190 %7 %7 +%392 = OpBitwiseAnd %190 %390 %391 +%393 = OpCompositeConstruct %201 %24 %24 %24 +%394 = OpCompositeConstruct %201 %25 %25 %25 +%395 = OpBitwiseAnd %201 %393 %394 +%396 = OpBitwiseXor %8 %18 %7 +%397 = OpBitwiseXor %20 %24 %25 +%398 = OpCompositeConstruct %190 %18 %18 +%399 = OpCompositeConstruct %190 %7 %7 +%400 = OpBitwiseXor %190 %398 %399 +%401 = OpCompositeConstruct %201 %24 %24 %24 +%402 = OpCompositeConstruct %201 %25 %25 %25 +%403 = OpBitwiseXor %201 %401 %402 +%404 = OpShiftLeftLogical %8 %18 %25 +%405 = OpShiftLeftLogical %20 %24 %25 +%406 = OpCompositeConstruct %190 %18 %18 +%407 = OpCompositeConstruct %43 %25 %25 +%408 = OpShiftLeftLogical %190 %406 %407 +%409 = OpCompositeConstruct %201 %24 %24 %24 +%410 = OpCompositeConstruct %201 %25 %25 %25 +%411 = OpShiftLeftLogical %201 %409 %410 +%412 = OpShiftRightArithmetic %8 %18 %25 +%413 = OpShiftRightLogical %20 %24 %25 +%414 = OpCompositeConstruct %190 %18 %18 +%415 = OpCompositeConstruct %43 %25 %25 +%416 = OpShiftRightArithmetic %190 %414 %415 +%417 = OpCompositeConstruct %201 %24 %24 %24 +%418 = OpCompositeConstruct %201 %25 %25 %25 +%419 = OpShiftRightLogical %201 %417 %418 OpReturn OpFunctionEnd -%422 = OpFunction %2 None %172 -%421 = OpLabel -OpBranch %423 -%423 = OpLabel -%424 = OpIEqual %10 %18 %7 -%425 = OpIEqual %10 %24 %25 -%426 = OpFOrdEqual %10 %14 %3 -%427 = OpCompositeConstruct %191 %18 %18 -%428 = OpCompositeConstruct %191 %7 %7 -%429 = OpIEqual %175 %427 %428 -%430 = OpCompositeConstruct %202 %24 %24 %24 -%431 = OpCompositeConstruct %202 %25 %25 %25 -%432 = OpIEqual %39 %430 %431 -%433 = OpCompositeConstruct %34 %14 %14 %14 %14 -%434 = OpCompositeConstruct %34 %3 %3 %3 %3 -%435 = OpFOrdEqual %36 %433 %434 -%436 = OpINotEqual %10 %18 %7 -%437 = OpINotEqual %10 %24 %25 -%438 = OpFOrdNotEqual %10 %14 %3 -%439 = OpCompositeConstruct %191 %18 %18 -%440 = OpCompositeConstruct %191 %7 %7 -%441 = OpINotEqual %175 %439 %440 -%442 = OpCompositeConstruct %202 %24 %24 %24 -%443 = OpCompositeConstruct %202 %25 %25 %25 -%444 = OpINotEqual %39 %442 %443 -%445 = OpCompositeConstruct %34 %14 %14 %14 %14 -%446 = OpCompositeConstruct %34 %3 %3 %3 %3 -%447 = OpFOrdNotEqual %36 %445 %446 -%448 = OpSLessThan %10 %18 %7 -%449 = OpULessThan %10 %24 %25 -%450 = OpFOrdLessThan %10 %14 %3 -%451 = OpCompositeConstruct %191 %18 %18 -%452 = OpCompositeConstruct %191 %7 %7 -%453 = OpSLessThan %175 %451 %452 -%454 = OpCompositeConstruct %202 %24 %24 %24 -%455 = OpCompositeConstruct %202 %25 %25 %25 -%456 = OpULessThan %39 %454 %455 -%457 = OpCompositeConstruct %34 %14 %14 %14 %14 -%458 = OpCompositeConstruct %34 %3 %3 %3 %3 -%459 = OpFOrdLessThan %36 %457 %458 -%460 = OpSLessThanEqual %10 %18 %7 -%461 = OpULessThanEqual %10 %24 %25 -%462 = OpFOrdLessThanEqual %10 %14 %3 -%463 = OpCompositeConstruct %191 %18 %18 -%464 = OpCompositeConstruct %191 %7 %7 -%465 = OpSLessThanEqual %175 %463 %464 -%466 = OpCompositeConstruct %202 %24 %24 %24 -%467 = OpCompositeConstruct %202 %25 %25 %25 -%468 = OpULessThanEqual %39 %466 %467 -%469 = OpCompositeConstruct %34 %14 %14 %14 %14 -%470 = OpCompositeConstruct %34 %3 %3 %3 %3 -%471 = OpFOrdLessThanEqual %36 %469 %470 -%472 = OpSGreaterThan %10 %18 %7 -%473 = OpUGreaterThan %10 %24 %25 -%474 = OpFOrdGreaterThan %10 %14 %3 -%475 = OpCompositeConstruct %191 %18 %18 -%476 = OpCompositeConstruct %191 %7 %7 -%477 = OpSGreaterThan %175 %475 %476 -%478 = OpCompositeConstruct %202 %24 %24 %24 -%479 = OpCompositeConstruct %202 %25 %25 %25 -%480 = OpUGreaterThan %39 %478 %479 -%481 = OpCompositeConstruct %34 %14 %14 %14 %14 -%482 = OpCompositeConstruct %34 %3 %3 %3 %3 -%483 = OpFOrdGreaterThan %36 %481 %482 -%484 = OpSGreaterThanEqual %10 %18 %7 -%485 = OpUGreaterThanEqual %10 %24 %25 -%486 = OpFOrdGreaterThanEqual %10 %14 %3 -%487 = OpCompositeConstruct %191 %18 %18 -%488 = OpCompositeConstruct %191 %7 %7 -%489 = OpSGreaterThanEqual %175 %487 %488 -%490 = OpCompositeConstruct %202 %24 %24 %24 -%491 = OpCompositeConstruct %202 %25 %25 %25 -%492 = OpUGreaterThanEqual %39 %490 %491 -%493 = OpCompositeConstruct %34 %14 %14 %14 %14 -%494 = OpCompositeConstruct %34 %3 %3 %3 %3 -%495 = OpFOrdGreaterThanEqual %36 %493 %494 +%421 = OpFunction %2 None %171 +%420 = OpLabel +OpBranch %422 +%422 = OpLabel +%423 = OpIEqual %10 %18 %7 +%424 = OpIEqual %10 %24 %25 +%425 = OpFOrdEqual %10 %14 %3 +%426 = OpCompositeConstruct %190 %18 %18 +%427 = OpCompositeConstruct %190 %7 %7 +%428 = OpIEqual %174 %426 %427 +%429 = OpCompositeConstruct %201 %24 %24 %24 +%430 = OpCompositeConstruct %201 %25 %25 %25 +%431 = OpIEqual %39 %429 %430 +%432 = OpCompositeConstruct %34 %14 %14 %14 %14 +%433 = OpCompositeConstruct %34 %3 %3 %3 %3 +%434 = OpFOrdEqual %36 %432 %433 +%435 = OpINotEqual %10 %18 %7 +%436 = OpINotEqual %10 %24 %25 +%437 = OpFOrdNotEqual %10 %14 %3 +%438 = OpCompositeConstruct %190 %18 %18 +%439 = OpCompositeConstruct %190 %7 %7 +%440 = OpINotEqual %174 %438 %439 +%441 = OpCompositeConstruct %201 %24 %24 %24 +%442 = OpCompositeConstruct %201 %25 %25 %25 +%443 = OpINotEqual %39 %441 %442 +%444 = OpCompositeConstruct %34 %14 %14 %14 %14 +%445 = OpCompositeConstruct %34 %3 %3 %3 %3 +%446 = OpFOrdNotEqual %36 %444 %445 +%447 = OpSLessThan %10 %18 %7 +%448 = OpULessThan %10 %24 %25 +%449 = OpFOrdLessThan %10 %14 %3 +%450 = OpCompositeConstruct %190 %18 %18 +%451 = OpCompositeConstruct %190 %7 %7 +%452 = OpSLessThan %174 %450 %451 +%453 = OpCompositeConstruct %201 %24 %24 %24 +%454 = OpCompositeConstruct %201 %25 %25 %25 +%455 = OpULessThan %39 %453 %454 +%456 = OpCompositeConstruct %34 %14 %14 %14 %14 +%457 = OpCompositeConstruct %34 %3 %3 %3 %3 +%458 = OpFOrdLessThan %36 %456 %457 +%459 = OpSLessThanEqual %10 %18 %7 +%460 = OpULessThanEqual %10 %24 %25 +%461 = OpFOrdLessThanEqual %10 %14 %3 +%462 = OpCompositeConstruct %190 %18 %18 +%463 = OpCompositeConstruct %190 %7 %7 +%464 = OpSLessThanEqual %174 %462 %463 +%465 = OpCompositeConstruct %201 %24 %24 %24 +%466 = OpCompositeConstruct %201 %25 %25 %25 +%467 = OpULessThanEqual %39 %465 %466 +%468 = OpCompositeConstruct %34 %14 %14 %14 %14 +%469 = OpCompositeConstruct %34 %3 %3 %3 %3 +%470 = OpFOrdLessThanEqual %36 %468 %469 +%471 = OpSGreaterThan %10 %18 %7 +%472 = OpUGreaterThan %10 %24 %25 +%473 = OpFOrdGreaterThan %10 %14 %3 +%474 = OpCompositeConstruct %190 %18 %18 +%475 = OpCompositeConstruct %190 %7 %7 +%476 = OpSGreaterThan %174 %474 %475 +%477 = OpCompositeConstruct %201 %24 %24 %24 +%478 = OpCompositeConstruct %201 %25 %25 %25 +%479 = OpUGreaterThan %39 %477 %478 +%480 = OpCompositeConstruct %34 %14 %14 %14 %14 +%481 = OpCompositeConstruct %34 %3 %3 %3 %3 +%482 = OpFOrdGreaterThan %36 %480 %481 +%483 = OpSGreaterThanEqual %10 %18 %7 +%484 = OpUGreaterThanEqual %10 %24 %25 +%485 = OpFOrdGreaterThanEqual %10 %14 %3 +%486 = OpCompositeConstruct %190 %18 %18 +%487 = OpCompositeConstruct %190 %7 %7 +%488 = OpSGreaterThanEqual %174 %486 %487 +%489 = OpCompositeConstruct %201 %24 %24 %24 +%490 = OpCompositeConstruct %201 %25 %25 %25 +%491 = OpUGreaterThanEqual %39 %489 %490 +%492 = OpCompositeConstruct %34 %14 %14 %14 %14 +%493 = OpCompositeConstruct %34 %3 %3 %3 %3 +%494 = OpFOrdGreaterThanEqual %36 %492 %493 OpReturn OpFunctionEnd -%503 = OpFunction %2 None %172 -%502 = OpLabel -%496 = OpVariable %497 Function %498 -%499 = OpVariable %500 Function %501 -OpBranch %504 -%504 = OpLabel -OpStore %496 %7 -%505 = OpLoad %8 %496 -%506 = OpIAdd %8 %505 %7 -OpStore %496 %506 -%507 = OpLoad %8 %496 -%508 = OpISub %8 %507 %7 -OpStore %496 %508 -%509 = OpLoad %8 %496 -%510 = OpLoad %8 %496 -%511 = OpIMul %8 %510 %509 -OpStore %496 %511 -%512 = OpLoad %8 %496 -%513 = OpLoad %8 %496 -%514 = OpSDiv %8 %513 %512 -OpStore %496 %514 -%515 = OpLoad %8 %496 -%516 = OpSRem %8 %515 %7 -OpStore %496 %516 -%517 = OpLoad %8 %496 -%518 = OpBitwiseAnd %8 %517 %11 -OpStore %496 %518 -%519 = OpLoad %8 %496 -%520 = OpBitwiseOr %8 %519 %11 -OpStore %496 %520 -%521 = OpLoad %8 %496 -%522 = OpBitwiseXor %8 %521 %11 -OpStore %496 %522 -%523 = OpLoad %8 %496 -%524 = OpShiftLeftLogical %8 %523 %24 -OpStore %496 %524 -%525 = OpLoad %8 %496 -%526 = OpShiftRightArithmetic %8 %525 %25 -OpStore %496 %526 -%527 = OpLoad %8 %496 -%528 = OpIAdd %8 %527 %7 -OpStore %496 %528 -%529 = OpLoad %8 %496 -%530 = OpISub %8 %529 %7 -OpStore %496 %530 -OpStore %499 %66 -%532 = OpAccessChain %531 %499 %25 -%533 = OpLoad %8 %532 -%534 = OpIAdd %8 %533 %7 -%535 = OpAccessChain %531 %499 %25 -OpStore %535 %534 -%536 = OpAccessChain %531 %499 %25 -%537 = OpLoad %8 %536 -%538 = OpISub %8 %537 %7 -%539 = OpAccessChain %531 %499 %25 -OpStore %539 %538 +%502 = OpFunction %2 None %171 +%501 = OpLabel +%495 = OpVariable %496 Function %497 +%498 = OpVariable %499 Function %500 +OpBranch %503 +%503 = OpLabel +OpStore %495 %7 +%504 = OpLoad %8 %495 +%505 = OpIAdd %8 %504 %7 +OpStore %495 %505 +%506 = OpLoad %8 %495 +%507 = OpISub %8 %506 %7 +OpStore %495 %507 +%508 = OpLoad %8 %495 +%509 = OpLoad %8 %495 +%510 = OpIMul %8 %509 %508 +OpStore %495 %510 +%511 = OpLoad %8 %495 +%512 = OpLoad %8 %495 +%513 = OpSDiv %8 %512 %511 +OpStore %495 %513 +%514 = OpLoad %8 %495 +%515 = OpSRem %8 %514 %7 +OpStore %495 %515 +%516 = OpLoad %8 %495 +%517 = OpBitwiseAnd %8 %516 %11 +OpStore %495 %517 +%518 = OpLoad %8 %495 +%519 = OpBitwiseOr %8 %518 %11 +OpStore %495 %519 +%520 = OpLoad %8 %495 +%521 = OpBitwiseXor %8 %520 %11 +OpStore %495 %521 +%522 = OpLoad %8 %495 +%523 = OpShiftLeftLogical %8 %522 %24 +OpStore %495 %523 +%524 = OpLoad %8 %495 +%525 = OpShiftRightArithmetic %8 %524 %25 +OpStore %495 %525 +%526 = OpLoad %8 %495 +%527 = OpIAdd %8 %526 %7 +OpStore %495 %527 +%528 = OpLoad %8 %495 +%529 = OpISub %8 %528 %7 +OpStore %495 %529 +OpStore %498 %66 +%531 = OpAccessChain %530 %498 %25 +%532 = OpLoad %8 %531 +%533 = OpIAdd %8 %532 %7 +%534 = OpAccessChain %530 %498 %25 +OpStore %534 %533 +%535 = OpAccessChain %530 %498 %25 +%536 = OpLoad %8 %535 +%537 = OpISub %8 %536 %7 +%538 = OpAccessChain %530 %498 %25 +OpStore %538 %537 OpReturn OpFunctionEnd -%541 = OpFunction %2 None %172 -%540 = OpLabel -OpBranch %542 -%542 = OpLabel -%543 = OpSNegate %8 %27 -%544 = OpSNegate %8 %28 -%545 = OpSNegate %8 %29 -%546 = OpSNegate %8 %545 -%547 = OpSNegate %8 %30 -%548 = OpSNegate %8 %547 -%549 = OpSNegate %8 %31 +%540 = OpFunction %2 None %171 +%539 = OpLabel +OpBranch %541 +%541 = OpLabel +%542 = OpSNegate %8 %27 +%543 = OpSNegate %8 %28 +%544 = OpSNegate %8 %29 +%545 = OpSNegate %8 %544 +%546 = OpSNegate %8 %30 +%547 = OpSNegate %8 %546 +%548 = OpSNegate %8 %31 +%549 = OpSNegate %8 %548 %550 = OpSNegate %8 %549 %551 = OpSNegate %8 %550 -%552 = OpSNegate %8 %551 -%553 = OpSNegate %8 %32 +%552 = OpSNegate %8 %32 +%553 = OpSNegate %8 %552 %554 = OpSNegate %8 %553 %555 = OpSNegate %8 %554 -%556 = OpSNegate %8 %555 -%557 = OpSNegate %8 %33 +%556 = OpSNegate %8 %33 +%557 = OpSNegate %8 %556 %558 = OpSNegate %8 %557 %559 = OpSNegate %8 %558 -%560 = OpSNegate %8 %559 OpReturn OpFunctionEnd -%562 = OpFunction %2 None %172 -%561 = OpLabel -OpBranch %563 -%563 = OpLabel -%564 = OpFunctionCall %34 %68 -%565 = OpFunctionCall %34 %93 -%566 = OpVectorShuffle %38 %51 %51 0 1 2 -%567 = OpFunctionCall %38 %128 %566 -%568 = OpFunctionCall %4 %140 -%569 = OpFunctionCall %2 %171 -%570 = OpFunctionCall %2 %189 -%571 = OpFunctionCall %2 %373 -%572 = OpFunctionCall %2 %422 -%573 = OpFunctionCall %2 %503 +%561 = OpFunction %2 None %171 +%560 = OpLabel +OpBranch %562 +%562 = OpLabel +%563 = OpFunctionCall %34 %68 +%564 = OpFunctionCall %34 %93 +%565 = OpVectorShuffle %38 %51 %51 0 1 2 +%566 = OpFunctionCall %38 %128 %565 +%567 = OpFunctionCall %4 %139 +%568 = OpFunctionCall %2 %170 +%569 = OpFunctionCall %2 %188 +%570 = OpFunctionCall %2 %372 +%571 = OpFunctionCall %2 %421 +%572 = OpFunctionCall %2 %502 OpReturn OpFunctionEnd \ No newline at end of file From 810e9d26fcfef6483f82e0553f10eb541a74291b Mon Sep 17 00:00:00 2001 From: Mauro Gentile <62186646+gents83@users.noreply.github.com> Date: Mon, 20 Feb 2023 20:40:59 +0100 Subject: [PATCH 1948/2212] Add countTrailingZeros (#2243) Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> --- src/back/glsl/mod.rs | 29 +++++ src/back/hlsl/writer.rs | 37 ++++++ src/back/msl/writer.rs | 1 + src/back/spv/block.rs | 43 +++++++ src/back/wgsl/writer.rs | 1 + src/front/wgsl/parse/conv.rs | 1 + src/lib.rs | 1 + src/proc/mod.rs | 1 + src/proc/typifier.rs | 1 + src/valid/expression.rs | 3 +- tests/in/math-functions.wgsl | 8 ++ .../out/glsl/math-functions.main.Vertex.glsl | 12 +- tests/out/hlsl/math-functions.hlsl | 12 +- tests/out/msl/math-functions.msl | 8 ++ tests/out/spv/math-functions.spvasm | 118 +++++++++++------- tests/out/wgsl/math-functions.wgsl | 8 ++ 16 files changed, 232 insertions(+), 52 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 3433c2f1c..ff00ded34 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2996,6 +2996,35 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Transpose => "transpose", Mf::Determinant => "determinant", // bits + Mf::CountTrailingZeros => { + match *ctx.info[arg].ty.inner_with(&self.module.types) { + crate::TypeInner::Vector { size, kind, .. } => { + let s = back::vector_size_str(size); + if let crate::ScalarKind::Uint = kind { + write!(self.out, "min(uvec{s}(findLSB(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ")), uvec{s}(32u))")?; + } else { + write!(self.out, "ivec{s}(min(uvec{s}(findLSB(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ")), uvec{s}(32u)))")?; + } + } + crate::TypeInner::Scalar { kind, .. } => { + if let crate::ScalarKind::Uint = kind { + write!(self.out, "min(uint(findLSB(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ")), 32u)")?; + } else { + write!(self.out, "int(min(uint(findLSB(")?; + self.write_expr(arg, ctx)?; + write!(self.out, ")), 32u))")?; + } + } + _ => unreachable!(), + }; + return Ok(()); + } Mf::CountLeadingZeros => { if self.options.version.supports_integer_functions() { match *ctx.info[arg].ty.inner_with(&self.module.types) { diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index c075fe3fe..450dfe85c 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2551,6 +2551,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Unpack2x16float, Regular(&'static str), MissingIntOverload(&'static str), + CountTrailingZeros, CountLeadingZeros, } @@ -2614,6 +2615,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::Transpose => Function::Regular("transpose"), Mf::Determinant => Function::Regular("determinant"), // bits + Mf::CountTrailingZeros => Function::CountTrailingZeros, Mf::CountLeadingZeros => Function::CountLeadingZeros, Mf::CountOneBits => Function::MissingIntOverload("countbits"), Mf::ReverseBits => Function::MissingIntOverload("reversebits"), @@ -2682,6 +2684,41 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; } } + Function::CountTrailingZeros => { + match *func_ctx.info[arg].ty.inner_with(&module.types) { + TypeInner::Vector { size, kind, .. } => { + let s = match size { + crate::VectorSize::Bi => ".xx", + crate::VectorSize::Tri => ".xxx", + crate::VectorSize::Quad => ".xxxx", + }; + + if let ScalarKind::Uint = kind { + write!(self.out, "min((32u){s}, firstbitlow(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))")?; + } else { + write!(self.out, "asint(min((32u){s}, asuint(firstbitlow(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))))")?; + } + } + TypeInner::Scalar { kind, .. } => { + if let ScalarKind::Uint = kind { + write!(self.out, "min(32u, firstbitlow(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))")?; + } else { + write!(self.out, "asint(min(32u, asuint(firstbitlow(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))))")?; + } + } + _ => unreachable!(), + } + + return Ok(()); + } Function::CountLeadingZeros => { match *func_ctx.info[arg].ty.inner_with(&module.types) { TypeInner::Vector { size, kind, .. } => { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 040541de4..c11765da9 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1686,6 +1686,7 @@ impl Writer { Mf::Transpose => "transpose", Mf::Determinant => "determinant", // bits + Mf::CountTrailingZeros => "ctz", Mf::CountLeadingZeros => "clz", Mf::CountOneBits => "popcount", Mf::ReverseBits => "reverse_bits", diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 4b0c52e8e..11d578263 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -874,6 +874,49 @@ impl<'w> BlockContext<'w> { id, arg0_id, )), + Mf::CountTrailingZeros => { + let uint = crate::ScalarValue::Uint(32); + let uint_id = match *arg_ty { + crate::TypeInner::Vector { size, width, .. } => { + let ty = LocalType::Value { + vector_size: Some(size), + kind: crate::ScalarKind::Uint, + width, + pointer_space: None, + } + .into(); + + self.temp_list.clear(); + self.temp_list.resize( + size as _, + self.writer.get_constant_scalar(uint, width), + ); + + self.writer.get_constant_composite(ty, &self.temp_list) + } + crate::TypeInner::Scalar { width, .. } => { + self.writer.get_constant_scalar(uint, width) + } + _ => unreachable!(), + }; + + let lsb_id = self.gen_id(); + block.body.push(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + spirv::GLOp::FindILsb, + result_type_id, + lsb_id, + &[arg0_id], + )); + + MathOp::Custom(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + spirv::GLOp::UMin, + result_type_id, + id, + &[uint_id, lsb_id], + )) + } Mf::CountLeadingZeros => { let int = crate::ScalarValue::Sint(31); diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 4f58cd9ee..be4d9e442 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1578,6 +1578,7 @@ impl Writer { Mf::Transpose => Function::Regular("transpose"), Mf::Determinant => Function::Regular("determinant"), // bits + Mf::CountTrailingZeros => Function::Regular("countTrailingZeros"), Mf::CountLeadingZeros => Function::Regular("countLeadingZeros"), Mf::CountOneBits => Function::Regular("countOneBits"), Mf::ReverseBits => Function::Regular("reverseBits"), diff --git a/src/front/wgsl/parse/conv.rs b/src/front/wgsl/parse/conv.rs index 416433216..0e20774dc 100644 --- a/src/front/wgsl/parse/conv.rs +++ b/src/front/wgsl/parse/conv.rs @@ -191,6 +191,7 @@ pub fn map_standard_fun(word: &str) -> Option { "transpose" => Mf::Transpose, "determinant" => Mf::Determinant, // bits + "countTrailingZeros" => Mf::CountTrailingZeros, "countLeadingZeros" => Mf::CountLeadingZeros, "countOneBits" => Mf::CountOneBits, "reverseBits" => Mf::ReverseBits, diff --git a/src/lib.rs b/src/lib.rs index 136205ca1..e60d8e0cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1066,6 +1066,7 @@ pub enum MathFunction { Transpose, Determinant, // bits + CountTrailingZeros, CountLeadingZeros, CountOneBits, ReverseBits, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 0a8e4a961..6a8bfa03c 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -279,6 +279,7 @@ impl super::MathFunction { Self::Transpose => 1, Self::Determinant => 1, // bits + Self::CountTrailingZeros => 1, Self::CountLeadingZeros => 1, Self::CountOneBits => 1, Self::ReverseBits => 1, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index cac32ebb7..3b9fa1d50 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -793,6 +793,7 @@ impl<'a> ResolveContext<'a> { )), }, // bits + Mf::CountTrailingZeros | Mf::CountLeadingZeros | Mf::CountOneBits | Mf::ReverseBits | diff --git a/src/valid/expression.rs b/src/valid/expression.rs index d599e6b62..01d6910eb 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1223,7 +1223,8 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } } - Mf::CountLeadingZeros + Mf::CountTrailingZeros + | Mf::CountLeadingZeros | Mf::CountOneBits | Mf::ReverseBits | Mf::FindLsb diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index 1c2a8e457..db50880d1 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -10,6 +10,14 @@ fn main() { let g = refract(v, v, f); let const_dot = dot(vec2(), vec2()); let first_leading_bit_abs = firstLeadingBit(abs(0u)); + let ctz_a = countTrailingZeros(0u); + let ctz_b = countTrailingZeros(0); + let ctz_c = countTrailingZeros(0xFFFFFFFFu); + let ctz_d = countTrailingZeros(-1); + let ctz_e = countTrailingZeros(vec2(0u)); + let ctz_f = countTrailingZeros(vec2(0)); + let ctz_g = countTrailingZeros(vec2(1u)); + let ctz_h = countTrailingZeros(vec2(1)); let clz_a = countLeadingZeros(-1); let clz_b = countLeadingZeros(1u); let clz_c = countLeadingZeros(vec2(-1)); diff --git a/tests/out/glsl/math-functions.main.Vertex.glsl b/tests/out/glsl/math-functions.main.Vertex.glsl index 8cfa6a10b..3c5c1dd34 100644 --- a/tests/out/glsl/math-functions.main.Vertex.glsl +++ b/tests/out/glsl/math-functions.main.Vertex.glsl @@ -14,10 +14,18 @@ void main() { vec4 g = refract(v, v, 1.0); int const_dot = ( + ivec2(0, 0).x * ivec2(0, 0).x + ivec2(0, 0).y * ivec2(0, 0).y); uint first_leading_bit_abs = uint(findMSB(uint(abs(int(0u))))); + uint ctz_a = min(uint(findLSB(0u)), 32u); + int ctz_b = int(min(uint(findLSB(0)), 32u)); + uint ctz_c = min(uint(findLSB(4294967295u)), 32u); + int ctz_d = int(min(uint(findLSB(-1)), 32u)); + uvec2 ctz_e = min(uvec2(findLSB(uvec2(0u))), uvec2(32u)); + ivec2 ctz_f = ivec2(min(uvec2(findLSB(ivec2(0))), uvec2(32u))); + uvec2 ctz_g = min(uvec2(findLSB(uvec2(1u))), uvec2(32u)); + ivec2 ctz_h = ivec2(min(uvec2(findLSB(ivec2(1))), uvec2(32u))); int clz_a = (-1 < 0 ? 0 : 31 - findMSB(-1)); uint clz_b = uint(31 - findMSB(1u)); - ivec2 _e20 = ivec2(-1); - ivec2 clz_c = mix(ivec2(31) - findMSB(_e20), ivec2(0), lessThan(_e20, ivec2(0))); + ivec2 _e40 = ivec2(-1); + ivec2 clz_c = mix(ivec2(31) - findMSB(_e40), ivec2(0), lessThan(_e40, ivec2(0))); uvec2 clz_d = uvec2(ivec2(31) - findMSB(uvec2(1u))); } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index 2a95c849c..958e77d80 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -10,9 +10,17 @@ void main() float4 g = refract(v, v, 1.0); int const_dot = dot(int2(0, 0), int2(0, 0)); uint first_leading_bit_abs = firstbithigh(abs(0u)); + uint ctz_a = min(32u, firstbitlow(0u)); + int ctz_b = asint(min(32u, asuint(firstbitlow(0)))); + uint ctz_c = min(32u, firstbitlow(4294967295u)); + int ctz_d = asint(min(32u, asuint(firstbitlow(-1)))); + uint2 ctz_e = min((32u).xx, firstbitlow((0u).xx)); + int2 ctz_f = asint(min((32u).xx, asuint(firstbitlow((0).xx)))); + uint2 ctz_g = min((32u).xx, firstbitlow((1u).xx)); + int2 ctz_h = asint(min((32u).xx, asuint(firstbitlow((1).xx)))); int clz_a = (-1 < 0 ? 0 : 31 - firstbithigh(-1)); uint clz_b = asuint(31 - firstbithigh(1u)); - int2 _expr20 = (-1).xx; - int2 clz_c = (_expr20 < (0).xx ? (0).xx : (31).xx - firstbithigh(_expr20)); + int2 _expr40 = (-1).xx; + int2 clz_c = (_expr40 < (0).xx ? (0).xx : (31).xx - firstbithigh(_expr40)); uint2 clz_d = asuint((31).xx - firstbithigh((1u).xx)); } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 3fdb7b75a..c2aac6ef9 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -18,6 +18,14 @@ vertex void main_( int const_dot = ( + const_type_1_.x * const_type_1_.x + const_type_1_.y * const_type_1_.y); uint _e13 = metal::abs(0u); uint first_leading_bit_abs = metal::select(31 - metal::clz(_e13), uint(-1), _e13 == 0 || _e13 == -1); + uint ctz_a = metal::ctz(0u); + int ctz_b = metal::ctz(0); + uint ctz_c = metal::ctz(4294967295u); + int ctz_d = metal::ctz(-1); + metal::uint2 ctz_e = metal::ctz(metal::uint2(0u)); + metal::int2 ctz_f = metal::ctz(metal::int2(0)); + metal::uint2 ctz_g = metal::ctz(metal::uint2(1u)); + metal::int2 ctz_h = metal::ctz(metal::int2(1)); int clz_a = metal::clz(-1); uint clz_b = metal::clz(1u); metal::int2 clz_c = metal::clz(metal::int2(-1)); diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index a65f53518..d1a98b4e4 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,11 +1,11 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 54 +; Bound: 78 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %16 "main" +OpEntryPoint Vertex %18 "main" %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -14,50 +14,74 @@ OpEntryPoint Vertex %16 "main" %6 = OpConstant %7 0 %9 = OpTypeInt 32 0 %8 = OpConstant %9 0 -%10 = OpConstant %7 -1 -%11 = OpConstant %9 1 -%12 = OpTypeVector %4 4 -%13 = OpTypeVector %7 2 -%14 = OpConstantComposite %13 %6 %6 -%17 = OpTypeFunction %2 -%25 = OpConstantComposite %12 %5 %5 %5 %5 -%26 = OpConstantComposite %12 %3 %3 %3 %3 -%40 = OpConstant %7 31 -%47 = OpConstantComposite %13 %40 %40 -%49 = OpTypeVector %9 2 -%29 = OpConstantNull %7 -%16 = OpFunction %2 None %17 -%15 = OpLabel -OpBranch %18 -%18 = OpLabel -%19 = OpCompositeConstruct %12 %5 %5 %5 %5 -%20 = OpExtInst %4 %1 Degrees %3 -%21 = OpExtInst %4 %1 Radians %3 -%22 = OpExtInst %12 %1 Degrees %19 -%23 = OpExtInst %12 %1 Radians %19 -%24 = OpExtInst %12 %1 FClamp %19 %25 %26 -%27 = OpExtInst %12 %1 Refract %19 %19 %3 -%30 = OpCompositeExtract %7 %14 0 -%31 = OpCompositeExtract %7 %14 0 -%32 = OpIMul %7 %30 %31 -%33 = OpIAdd %7 %29 %32 -%34 = OpCompositeExtract %7 %14 1 -%35 = OpCompositeExtract %7 %14 1 -%36 = OpIMul %7 %34 %35 -%28 = OpIAdd %7 %33 %36 -%37 = OpCopyObject %9 %8 -%38 = OpExtInst %9 %1 FindUMsb %37 -%39 = OpExtInst %7 %1 FindUMsb %10 -%41 = OpISub %7 %40 %39 -%42 = OpExtInst %7 %1 FindUMsb %11 -%43 = OpISub %7 %40 %42 -%44 = OpBitcast %9 %43 -%45 = OpCompositeConstruct %13 %10 %10 -%46 = OpExtInst %13 %1 FindUMsb %45 -%48 = OpISub %13 %47 %46 -%50 = OpCompositeConstruct %49 %11 %11 -%51 = OpExtInst %13 %1 FindUMsb %50 -%52 = OpISub %13 %47 %51 -%53 = OpBitcast %49 %52 +%10 = OpConstant %9 4294967295 +%11 = OpConstant %7 -1 +%12 = OpConstant %9 1 +%13 = OpConstant %7 1 +%14 = OpTypeVector %4 4 +%15 = OpTypeVector %7 2 +%16 = OpConstantComposite %15 %6 %6 +%19 = OpTypeFunction %2 +%27 = OpConstantComposite %14 %5 %5 %5 %5 +%28 = OpConstantComposite %14 %3 %3 %3 %3 +%42 = OpConstant %9 32 +%50 = OpTypeVector %9 2 +%53 = OpConstantComposite %50 %42 %42 +%65 = OpConstant %7 31 +%72 = OpConstantComposite %15 %65 %65 +%31 = OpConstantNull %7 +%18 = OpFunction %2 None %19 +%17 = OpLabel +OpBranch %20 +%20 = OpLabel +%21 = OpCompositeConstruct %14 %5 %5 %5 %5 +%22 = OpExtInst %4 %1 Degrees %3 +%23 = OpExtInst %4 %1 Radians %3 +%24 = OpExtInst %14 %1 Degrees %21 +%25 = OpExtInst %14 %1 Radians %21 +%26 = OpExtInst %14 %1 FClamp %21 %27 %28 +%29 = OpExtInst %14 %1 Refract %21 %21 %3 +%32 = OpCompositeExtract %7 %16 0 +%33 = OpCompositeExtract %7 %16 0 +%34 = OpIMul %7 %32 %33 +%35 = OpIAdd %7 %31 %34 +%36 = OpCompositeExtract %7 %16 1 +%37 = OpCompositeExtract %7 %16 1 +%38 = OpIMul %7 %36 %37 +%30 = OpIAdd %7 %35 %38 +%39 = OpCopyObject %9 %8 +%40 = OpExtInst %9 %1 FindUMsb %39 +%43 = OpExtInst %9 %1 FindILsb %8 +%41 = OpExtInst %9 %1 UMin %42 %43 +%45 = OpExtInst %7 %1 FindILsb %6 +%44 = OpExtInst %7 %1 UMin %42 %45 +%47 = OpExtInst %9 %1 FindILsb %10 +%46 = OpExtInst %9 %1 UMin %42 %47 +%49 = OpExtInst %7 %1 FindILsb %11 +%48 = OpExtInst %7 %1 UMin %42 %49 +%51 = OpCompositeConstruct %50 %8 %8 +%54 = OpExtInst %50 %1 FindILsb %51 +%52 = OpExtInst %50 %1 UMin %53 %54 +%55 = OpCompositeConstruct %15 %6 %6 +%57 = OpExtInst %15 %1 FindILsb %55 +%56 = OpExtInst %15 %1 UMin %53 %57 +%58 = OpCompositeConstruct %50 %12 %12 +%60 = OpExtInst %50 %1 FindILsb %58 +%59 = OpExtInst %50 %1 UMin %53 %60 +%61 = OpCompositeConstruct %15 %13 %13 +%63 = OpExtInst %15 %1 FindILsb %61 +%62 = OpExtInst %15 %1 UMin %53 %63 +%64 = OpExtInst %7 %1 FindUMsb %11 +%66 = OpISub %7 %65 %64 +%67 = OpExtInst %7 %1 FindUMsb %12 +%68 = OpISub %7 %65 %67 +%69 = OpBitcast %9 %68 +%70 = OpCompositeConstruct %15 %11 %11 +%71 = OpExtInst %15 %1 FindUMsb %70 +%73 = OpISub %15 %72 %71 +%74 = OpCompositeConstruct %50 %12 %12 +%75 = OpExtInst %15 %1 FindUMsb %74 +%76 = OpISub %15 %72 %75 +%77 = OpBitcast %50 %76 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index d91a26cff..71ae0fd74 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -9,6 +9,14 @@ fn main() { let g = refract(v, v, 1.0); let const_dot = dot(vec2(0, 0), vec2(0, 0)); let first_leading_bit_abs = firstLeadingBit(abs(0u)); + let ctz_a = countTrailingZeros(0u); + let ctz_b = countTrailingZeros(0); + let ctz_c = countTrailingZeros(4294967295u); + let ctz_d = countTrailingZeros(-1); + let ctz_e = countTrailingZeros(vec2(0u)); + let ctz_f = countTrailingZeros(vec2(0)); + let ctz_g = countTrailingZeros(vec2(1u)); + let ctz_h = countTrailingZeros(vec2(1)); let clz_a = countLeadingZeros(-1); let clz_b = countLeadingZeros(1u); let clz_c = countLeadingZeros(vec2(-1)); From cde457ceddb4a34b821df5e5c8b6c76835a638dc Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 20 Feb 2023 21:40:26 +0100 Subject: [PATCH 1949/2212] [spv-out] fix `countLeadingZeros` impl (#2258) --- src/back/spv/block.rs | 25 +++++++------------------ tests/out/spv/math-functions.spvasm | 26 ++++++++++++-------------- 2 files changed, 19 insertions(+), 32 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 11d578263..bf45130ad 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -951,33 +951,22 @@ impl<'w> BlockContext<'w> { _ => unreachable!(), }; + let msb_id = self.gen_id(); block.body.push(Instruction::ext_inst( self.writer.gl450_ext_inst_id, spirv::GLOp::FindUMsb, int_type_id, - id, + msb_id, &[arg0_id], )); - let sub_id = self.gen_id(); - block.body.push(Instruction::binary( + MathOp::Custom(Instruction::binary( spirv::Op::ISub, - int_type_id, - sub_id, - int_id, + result_type_id, id, - )); - - if let Some(crate::ScalarKind::Uint) = arg_scalar_kind { - block.body.push(Instruction::unary( - spirv::Op::Bitcast, - result_type_id, - self.gen_id(), - sub_id, - )); - } - - return Ok(()); + int_id, + msb_id, + )) } Mf::CountOneBits => MathOp::Custom(Instruction::unary( spirv::Op::BitCount, diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index d1a98b4e4..9dbde7ddf 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 78 +; Bound: 76 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -28,7 +28,7 @@ OpEntryPoint Vertex %18 "main" %50 = OpTypeVector %9 2 %53 = OpConstantComposite %50 %42 %42 %65 = OpConstant %7 31 -%72 = OpConstantComposite %15 %65 %65 +%71 = OpConstantComposite %15 %65 %65 %31 = OpConstantNull %7 %18 = OpFunction %2 None %19 %17 = OpLabel @@ -71,17 +71,15 @@ OpBranch %20 %61 = OpCompositeConstruct %15 %13 %13 %63 = OpExtInst %15 %1 FindILsb %61 %62 = OpExtInst %15 %1 UMin %53 %63 -%64 = OpExtInst %7 %1 FindUMsb %11 -%66 = OpISub %7 %65 %64 -%67 = OpExtInst %7 %1 FindUMsb %12 -%68 = OpISub %7 %65 %67 -%69 = OpBitcast %9 %68 -%70 = OpCompositeConstruct %15 %11 %11 -%71 = OpExtInst %15 %1 FindUMsb %70 -%73 = OpISub %15 %72 %71 -%74 = OpCompositeConstruct %50 %12 %12 -%75 = OpExtInst %15 %1 FindUMsb %74 -%76 = OpISub %15 %72 %75 -%77 = OpBitcast %50 %76 +%66 = OpExtInst %7 %1 FindUMsb %11 +%64 = OpISub %7 %65 %66 +%68 = OpExtInst %7 %1 FindUMsb %12 +%67 = OpISub %9 %65 %68 +%69 = OpCompositeConstruct %15 %11 %11 +%72 = OpExtInst %15 %1 FindUMsb %69 +%70 = OpISub %15 %71 %72 +%73 = OpCompositeConstruct %50 %12 %12 +%75 = OpExtInst %15 %1 FindUMsb %73 +%74 = OpISub %50 %71 %75 OpReturn OpFunctionEnd \ No newline at end of file From 9742f1616c3e3dd2cc9a5880616fc886c391bb9f Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 21 Feb 2023 04:56:24 +0100 Subject: [PATCH 1950/2212] fix zero initialization of workgroup memory (#2259) Use the local (not global) invocation id to decide which invocation should do the initialization, so that every workgroup gets initialized, not just the first. --- src/back/glsl/mod.rs | 5 +---- src/back/hlsl/writer.rs | 7 ++----- src/back/msl/writer.rs | 18 ++++++++--------- src/back/spv/writer.rs | 20 +++++++++---------- .../access.assign_through_ptr.Compute.glsl | 2 +- tests/out/glsl/globals.main.Compute.glsl | 2 +- .../glsl/workgroup-var-init.main.Compute.glsl | 2 +- tests/out/hlsl/access.hlsl | 4 ++-- tests/out/hlsl/globals.hlsl | 4 ++-- tests/out/hlsl/interface.hlsl | 4 ++-- tests/out/hlsl/workgroup-var-init.hlsl | 4 ++-- tests/out/msl/access.msl | 4 ++-- tests/out/msl/globals.msl | 4 ++-- tests/out/msl/interface.msl | 2 +- tests/out/msl/workgroup-var-init.msl | 4 ++-- tests/out/spv/access.spvasm | 2 +- tests/out/spv/globals.spvasm | 2 +- tests/out/spv/interface.compute.spvasm | 2 +- tests/out/spv/workgroup-var-init.spvasm | 2 +- 19 files changed, 44 insertions(+), 50 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ff00ded34..a75188b4d 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1583,10 +1583,7 @@ impl<'a, W: Write> Writer<'a, W> { if vars.peek().is_some() { let level = back::Level(1); - writeln!( - self.out, - "{level}if (gl_GlobalInvocationID == uvec3(0u)) {{" - )?; + writeln!(self.out, "{level}if (gl_LocalInvocationID == uvec3(0u)) {{")?; for (handle, var) in vars { let name = &self.names[&NameKey::GlobalVariable(handle)]; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 450dfe85c..7b08ddf74 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1176,10 +1176,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if !func.arguments.is_empty() { write!(self.out, ", ")?; } - write!( - self.out, - "uint3 __global_invocation_id : SV_DispatchThreadID" - )?; + write!(self.out, "uint3 __local_invocation_id : SV_GroupThreadID")?; } } } @@ -1281,7 +1278,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!( self.out, - "{level}if (all(__global_invocation_id == uint3(0u, 0u, 0u))) {{" + "{level}if (all(__local_invocation_id == uint3(0u, 0u, 0u))) {{" )?; let vars = module.global_variables.iter().filter(|&(handle, var)| { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c11765da9..99e29b444 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3633,7 +3633,7 @@ impl Writer { is_first_argument = false; } - let mut global_invocation_id = None; + let mut local_invocation_id = None; // Then pass the remaining arguments not included in the varyings // struct. @@ -3660,8 +3660,8 @@ impl Writer { &self.names[name_key] }; - if binding == &crate::Binding::BuiltIn(crate::BuiltIn::GlobalInvocationId) { - global_invocation_id = Some(name_key); + if binding == &crate::Binding::BuiltIn(crate::BuiltIn::LocalInvocationId) { + local_invocation_id = Some(name_key); } let ty_name = TypeContext { @@ -3687,7 +3687,7 @@ impl Writer { let need_workgroup_variables_initialization = self.need_workgroup_variables_initialization(options, ep, module, fun_info); - if need_workgroup_variables_initialization && global_invocation_id.is_none() { + if need_workgroup_variables_initialization && local_invocation_id.is_none() { let separator = if is_first_argument { is_first_argument = false; ' ' @@ -3696,7 +3696,7 @@ impl Writer { }; writeln!( self.out, - "{separator} {NAMESPACE}::uint3 __global_invocation_id [[thread_position_in_grid]]" + "{separator} {NAMESPACE}::uint3 __local_invocation_id [[thread_position_in_threadgroup]]" )?; } @@ -3786,7 +3786,7 @@ impl Writer { module, mod_info, fun_info, - global_invocation_id, + local_invocation_id, )?; } @@ -4075,7 +4075,7 @@ mod workgroup_mem_init { module: &crate::Module, module_info: &valid::ModuleInfo, fun_info: &valid::FunctionInfo, - global_invocation_id: Option<&NameKey>, + local_invocation_id: Option<&NameKey>, ) -> BackendResult { let level = back::Level(1); @@ -4084,9 +4084,9 @@ mod workgroup_mem_init { "{}if ({}::all({} == {}::uint3(0u))) {{", level, NAMESPACE, - global_invocation_id + local_invocation_id .map(|name_key| self.names[name_key].as_str()) - .unwrap_or("__global_invocation_id"), + .unwrap_or("__local_invocation_id"), NAMESPACE, )?; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 87b005177..a56dc0508 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -367,7 +367,7 @@ impl Writer { results: Vec::new(), }; - let mut global_invocation_id = None; + let mut local_invocation_id = None; let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len()); for argument in ir_function.arguments.iter() { @@ -400,8 +400,8 @@ impl Writer { .body .push(Instruction::load(argument_type_id, id, varying_id, None)); - if binding == &crate::Binding::BuiltIn(crate::BuiltIn::GlobalInvocationId) { - global_invocation_id = Some(id); + if binding == &crate::Binding::BuiltIn(crate::BuiltIn::LocalInvocationId) { + local_invocation_id = Some(id); } id @@ -430,7 +430,7 @@ impl Writer { constituent_ids.push(id); if binding == &crate::Binding::BuiltIn(crate::BuiltIn::GlobalInvocationId) { - global_invocation_id = Some(id); + local_invocation_id = Some(id); } } prelude.body.push(Instruction::composite_construct( @@ -673,7 +673,7 @@ impl Writer { next_id, ir_module, info, - global_invocation_id, + local_invocation_id, interface, context.function, ), @@ -1253,7 +1253,7 @@ impl Writer { entry_id: Word, ir_module: &crate::Module, info: &FunctionInfo, - global_invocation_id: Option, + local_invocation_id: Option, interface: &mut FunctionInterface, function: &mut Function, ) -> Option { @@ -1282,8 +1282,8 @@ impl Writer { let mut pre_if_block = Block::new(entry_id); - let global_invocation_id = if let Some(global_invocation_id) = global_invocation_id { - global_invocation_id + let local_invocation_id = if let Some(local_invocation_id) = local_invocation_id { + local_invocation_id } else { let varying_id = self.id_gen.next(); let class = spirv::StorageClass::Input; @@ -1295,7 +1295,7 @@ impl Writer { self.decorate( varying_id, spirv::Decoration::BuiltIn, - &[spirv::BuiltIn::GlobalInvocationId as u32], + &[spirv::BuiltIn::LocalInvocationId as u32], ); interface.varying_ids.push(varying_id); @@ -1315,7 +1315,7 @@ impl Writer { spirv::Op::IEqual, bool3_type_id, eq_id, - global_invocation_id, + local_invocation_id, zero_id, )); diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/tests/out/glsl/access.assign_through_ptr.Compute.glsl index f79b30e3e..ab5bd9a3f 100644 --- a/tests/out/glsl/access.assign_through_ptr.Compute.glsl +++ b/tests/out/glsl/access.assign_through_ptr.Compute.glsl @@ -42,7 +42,7 @@ void assign_array_through_ptr_fn(inout vec4 foo_2[2]) { } void main() { - if (gl_GlobalInvocationID == uvec3(0u)) { + if (gl_LocalInvocationID == uvec3(0u)) { val = 0u; } memoryBarrierShared(); diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index b5b357105..f72bde3de 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -51,7 +51,7 @@ void test_msl_packed_vec3_() { } void main() { - if (gl_GlobalInvocationID == uvec3(0u)) { + if (gl_LocalInvocationID == uvec3(0u)) { wg = float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); at_1 = 0u; } diff --git a/tests/out/glsl/workgroup-var-init.main.Compute.glsl b/tests/out/glsl/workgroup-var-init.main.Compute.glsl index da55fea95..de136c110 100644 --- a/tests/out/glsl/workgroup-var-init.main.Compute.glsl +++ b/tests/out/glsl/workgroup-var-init.main.Compute.glsl @@ -16,7 +16,7 @@ layout(std430) buffer type_1_block_0Compute { uint _group_0_binding_0_cs[512]; } void main() { - if (gl_GlobalInvocationID == uvec3(0u)) { + if (gl_LocalInvocationID == uvec3(0u)) { w_mem = WStruct(uint[512](0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u), 0, int[8][8](int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0), int[8](0, 0, 0, 0, 0, 0, 0, 0))); } memoryBarrierShared(); diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index c87f39cf2..a8d7d80c9 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -338,9 +338,9 @@ void atomics() } [numthreads(1, 1, 1)] -void assign_through_ptr(uint3 __global_invocation_id : SV_DispatchThreadID) +void assign_through_ptr(uint3 __local_invocation_id : SV_GroupThreadID) { - if (all(__global_invocation_id == uint3(0u, 0u, 0u))) { + if (all(__local_invocation_id == uint3(0u, 0u, 0u))) { val = (uint)0; } GroupMemoryBarrierWithGroupSync(); diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 6047b8dca..273889fdb 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -106,9 +106,9 @@ uint NagaBufferLength(ByteAddressBuffer buffer) } [numthreads(1, 1, 1)] -void main(uint3 __global_invocation_id : SV_DispatchThreadID) +void main(uint3 __local_invocation_id : SV_GroupThreadID) { - if (all(__global_invocation_id == uint3(0u, 0u, 0u))) { + if (all(__local_invocation_id == uint3(0u, 0u, 0u))) { wg = (float[10])0; at_1 = (uint)0; } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 34ef1ccb4..9251396c7 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -75,9 +75,9 @@ FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment) } [numthreads(1, 1, 1)] -void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThreadID, uint local_index : SV_GroupIndex, uint3 wg_id : SV_GroupID, uint3 num_wgs : SV_GroupID, uint3 __global_invocation_id : SV_DispatchThreadID) +void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThreadID, uint local_index : SV_GroupIndex, uint3 wg_id : SV_GroupID, uint3 num_wgs : SV_GroupID, uint3 __local_invocation_id : SV_GroupThreadID) { - if (all(__global_invocation_id == uint3(0u, 0u, 0u))) { + if (all(__local_invocation_id == uint3(0u, 0u, 0u))) { output = (uint[1])0; } GroupMemoryBarrierWithGroupSync(); diff --git a/tests/out/hlsl/workgroup-var-init.hlsl b/tests/out/hlsl/workgroup-var-init.hlsl index db48d36c0..3e70d6e09 100644 --- a/tests/out/hlsl/workgroup-var-init.hlsl +++ b/tests/out/hlsl/workgroup-var-init.hlsl @@ -9,9 +9,9 @@ groupshared WStruct w_mem; RWByteAddressBuffer output : register(u0); [numthreads(1, 1, 1)] -void main(uint3 __global_invocation_id : SV_DispatchThreadID) +void main(uint3 __local_invocation_id : SV_GroupThreadID) { - if (all(__global_invocation_id == uint3(0u, 0u, 0u))) { + if (all(__local_invocation_id == uint3(0u, 0u, 0u))) { w_mem = (WStruct)0; } GroupMemoryBarrierWithGroupSync(); diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index e565643bb..8ad40973f 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -250,10 +250,10 @@ kernel void atomics( kernel void assign_through_ptr( - metal::uint3 __global_invocation_id [[thread_position_in_grid]] + metal::uint3 __local_invocation_id [[thread_position_in_threadgroup]] , threadgroup uint& val ) { - if (metal::all(__global_invocation_id == metal::uint3(0u))) { + if (metal::all(__local_invocation_id == metal::uint3(0u))) { val = {}; } metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 62dc1c4ac..b57d09492 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -62,7 +62,7 @@ void test_msl_packed_vec3_( } kernel void main_( - metal::uint3 __global_invocation_id [[thread_position_in_grid]] + metal::uint3 __local_invocation_id [[thread_position_in_threadgroup]] , threadgroup type_2& wg , threadgroup metal::atomic_uint& at_1 , device FooStruct& alignment [[user(fake0)]] @@ -74,7 +74,7 @@ kernel void main_( , constant type_15& global_nested_arrays_of_matrices_4x2_ [[user(fake0)]] , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { - if (metal::all(__global_invocation_id == metal::uint3(0u))) { + if (metal::all(__local_invocation_id == metal::uint3(0u))) { wg = {}; metal::atomic_store_explicit(&at_1, 0, metal::memory_order_relaxed); } diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index 368c8218c..c9b93d86a 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -76,7 +76,7 @@ kernel void compute_( , metal::uint3 num_wgs [[threadgroups_per_grid]] , threadgroup type_4& output ) { - if (metal::all(global_id == metal::uint3(0u))) { + if (metal::all(local_id == metal::uint3(0u))) { output = {}; } metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); diff --git a/tests/out/msl/workgroup-var-init.msl b/tests/out/msl/workgroup-var-init.msl index 8f8bb14f1..0d61e96f7 100644 --- a/tests/out/msl/workgroup-var-init.msl +++ b/tests/out/msl/workgroup-var-init.msl @@ -20,11 +20,11 @@ struct WStruct { }; kernel void main_( - metal::uint3 __global_invocation_id [[thread_position_in_grid]] + metal::uint3 __local_invocation_id [[thread_position_in_threadgroup]] , threadgroup WStruct& w_mem , device type_1& output [[buffer(0)]] ) { - if (metal::all(__global_invocation_id == metal::uint3(0u))) { + if (metal::all(__local_invocation_id == metal::uint3(0u))) { w_mem.arr = {}; metal::atomic_store_explicit(&w_mem.atom, 0, metal::memory_order_relaxed); for (int __i0 = 0; __i0 < 8; __i0++) { diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 42ab59eb5..a88232292 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -107,7 +107,7 @@ OpMemberDecorate %83 0 Offset 0 OpDecorate %242 BuiltIn VertexIndex OpDecorate %245 BuiltIn Position OpDecorate %288 Location 0 -OpDecorate %337 BuiltIn GlobalInvocationId +OpDecorate %337 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 0a6cf9d72..a69852e7e 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -48,7 +48,7 @@ OpDecorate %64 DescriptorSet 0 OpDecorate %64 Binding 7 OpDecorate %65 Block OpMemberDecorate %65 0 Offset 0 -OpDecorate %129 BuiltIn GlobalInvocationId +OpDecorate %129 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index f99174536..a37437a96 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -63,7 +63,7 @@ OpDecorate %33 BuiltIn NumWorkgroups %34 = OpLoad %17 %33 OpBranch %37 %37 = OpLabel -%41 = OpIEqual %40 %25 %39 +%41 = OpIEqual %40 %27 %39 %42 = OpAll %15 %41 OpSelectionMerge %43 None OpBranchConditional %42 %44 %43 diff --git a/tests/out/spv/workgroup-var-init.spvasm b/tests/out/spv/workgroup-var-init.spvasm index 1cccc889d..ee62929c9 100644 --- a/tests/out/spv/workgroup-var-init.spvasm +++ b/tests/out/spv/workgroup-var-init.spvasm @@ -26,7 +26,7 @@ OpDecorate %13 DescriptorSet 0 OpDecorate %13 Binding 0 OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 -OpDecorate %25 BuiltIn GlobalInvocationId +OpDecorate %25 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 512 From 00be08e9f82a7bc2a4b8f8f3645d0191d9a89ec2 Mon Sep 17 00:00:00 2001 From: Arman Uguray Date: Wed, 22 Feb 2023 09:15:39 -0800 Subject: [PATCH 1951/2212] [msl-out] Replace `per_stage_map` with `per_entry_point_map` (#2237) The existing `per_stage_map` field of MSL backend options specifies resource binding maps that apply to all entry points of each stage type. It is useful to have the ability to provide a separate binding index map for each entry point, especially when the same shader module defines multiple entry points of the same stage kind. This patch replaces `per_stage_map` with a new `per_entry_point_map` option where resources are keyed by the entry-point function name. --- src/back/msl/mod.rs | 70 +++++++++++------------ src/back/msl/writer.rs | 17 +++--- tests/in/access.param.ron | 10 ++-- tests/in/binding-arrays.param.ron | 6 +- tests/in/bitcast.params.ron | 6 +- tests/in/bits.param.ron | 6 +- tests/in/boids.param.ron | 6 +- tests/in/extra.param.ron | 6 +- tests/in/interface.param.ron | 2 +- tests/in/padding.param.ron | 6 +- tests/in/resource-binding-map.param.ron | 53 ++++++++++++++++++ tests/in/resource-binding-map.wgsl | 23 ++++++++ tests/in/skybox.param.ron | 8 +-- tests/in/workgroup-var-init.param.ron | 8 +-- tests/out/msl/resource-binding-map.msl | 74 +++++++++++++++++++++++++ tests/snapshots.rs | 8 ++- 16 files changed, 227 insertions(+), 82 deletions(-) create mode 100644 tests/in/resource-binding-map.param.ron create mode 100644 tests/in/resource-binding-map.wgsl create mode 100644 tests/out/msl/resource-binding-map.msl diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 271557fbf..d79497660 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -27,10 +27,7 @@ holding the result. */ use crate::{arena::Handle, proc::index, valid::ModuleInfo}; -use std::{ - fmt::{Error as FmtError, Write}, - ops, -}; +use std::fmt::{Error as FmtError, Write}; mod keywords; pub mod sampler; @@ -69,7 +66,7 @@ pub type BindingMap = std::collections::BTreeMap, @@ -80,26 +77,7 @@ pub struct PerStageResources { pub sizes_buffer: Option, } -#[derive(Clone, Debug, Default, Hash, Eq, PartialEq)] -#[cfg_attr(feature = "serialize", derive(serde::Serialize))] -#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] -#[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(default))] -pub struct PerStageMap { - pub vs: PerStageResources, - pub fs: PerStageResources, - pub cs: PerStageResources, -} - -impl ops::Index for PerStageMap { - type Output = PerStageResources; - fn index(&self, stage: crate::ShaderStage) -> &PerStageResources { - match stage { - crate::ShaderStage::Vertex => &self.vs, - crate::ShaderStage::Fragment => &self.fs, - crate::ShaderStage::Compute => &self.cs, - } - } -} +pub type EntryPointResourceMap = std::collections::BTreeMap; enum ResolvedBinding { BuiltIn(crate::BuiltIn), @@ -198,8 +176,8 @@ enum LocationMode { pub struct Options { /// (Major, Minor) target version of the Metal Shading Language. pub lang_version: (u8, u8), - /// Map of per-stage resources to slots. - pub per_stage_map: PerStageMap, + /// Map of entry-point resources, indexed by entry point function name, to slots. + pub per_entry_point_map: EntryPointResourceMap, /// Samplers to be inlined into the code. pub inline_samplers: Vec, /// Make it possible to link different stages via SPIRV-Cross. @@ -217,7 +195,7 @@ impl Default for Options { fn default() -> Self { Options { lang_version: (2, 0), - per_stage_map: PerStageMap::default(), + per_entry_point_map: EntryPointResourceMap::default(), inline_samplers: Vec::new(), spirv_cross_compatibility: false, fake_missing_bindings: true, @@ -296,12 +274,26 @@ impl Options { } } + fn get_entry_point_resources(&self, ep: &crate::EntryPoint) -> Option<&EntryPointResources> { + self.per_entry_point_map.get(&ep.name) + } + + fn get_resource_binding_target( + &self, + ep: &crate::EntryPoint, + res_binding: &crate::ResourceBinding, + ) -> Option<&BindTarget> { + self.get_entry_point_resources(ep) + .and_then(|res| res.resources.get(res_binding)) + } + fn resolve_resource_binding( &self, - stage: crate::ShaderStage, + ep: &crate::EntryPoint, res_binding: &crate::ResourceBinding, ) -> Result { - match self.per_stage_map[stage].resources.get(res_binding) { + let target = self.get_resource_binding_target(ep, res_binding); + match target { Some(target) => Ok(ResolvedBinding::Resource(target.clone())), None if self.fake_missing_bindings => Ok(ResolvedBinding::User { prefix: "fake", @@ -312,15 +304,13 @@ impl Options { } } - const fn resolve_push_constants( + fn resolve_push_constants( &self, - stage: crate::ShaderStage, + ep: &crate::EntryPoint, ) -> Result { - let slot = match stage { - crate::ShaderStage::Vertex => self.per_stage_map.vs.push_constant_buffer, - crate::ShaderStage::Fragment => self.per_stage_map.fs.push_constant_buffer, - crate::ShaderStage::Compute => self.per_stage_map.cs.push_constant_buffer, - }; + let slot = self + .get_entry_point_resources(ep) + .and_then(|res| res.push_constant_buffer); match slot { Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { buffer: Some(slot), @@ -340,9 +330,11 @@ impl Options { fn resolve_sizes_buffer( &self, - stage: crate::ShaderStage, + ep: &crate::EntryPoint, ) -> Result { - let slot = self.per_stage_map[stage].sizes_buffer; + let slot = self + .get_entry_point_resources(ep) + .and_then(|res| res.sizes_buffer); match slot { Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { buffer: Some(slot), diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 99e29b444..cb1ec2499 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3406,7 +3406,8 @@ impl Writer { break; } }; - let good = match options.per_stage_map[ep.stage].resources.get(br) { + let target = options.get_resource_binding_target(ep, br); + let good = match target { Some(target) => { let binding_ty = match module.types[var.ty].inner { crate::TypeInner::BindingArray { base, .. } => { @@ -3431,7 +3432,7 @@ impl Writer { } } crate::AddressSpace::PushConstant => { - if let Err(e) = options.resolve_push_constants(ep.stage) { + if let Err(e) = options.resolve_push_constants(ep) { ep_error = Some(e); break; } @@ -3442,7 +3443,7 @@ impl Writer { } } if supports_array_length { - if let Err(err) = options.resolve_sizes_buffer(ep.stage) { + if let Err(err) = options.resolve_sizes_buffer(ep) { ep_error = Some(err); } } @@ -3711,15 +3712,13 @@ impl Writer { } // the resolves have already been checked for `!fake_missing_bindings` case let resolved = match var.space { - crate::AddressSpace::PushConstant => { - options.resolve_push_constants(ep.stage).ok() - } + crate::AddressSpace::PushConstant => options.resolve_push_constants(ep).ok(), crate::AddressSpace::WorkGroup => None, crate::AddressSpace::Storage { .. } if options.lang_version < (2, 0) => { return Err(Error::UnsupportedAddressSpace(var.space)) } _ => options - .resolve_resource_binding(ep.stage, var.binding.as_ref().unwrap()) + .resolve_resource_binding(ep, var.binding.as_ref().unwrap()) .ok(), }; if let Some(ref resolved) = resolved { @@ -3764,7 +3763,7 @@ impl Writer { // passed as a final struct-typed argument. if supports_array_length { // this is checked earlier - let resolved = options.resolve_sizes_buffer(ep.stage).unwrap(); + let resolved = options.resolve_sizes_buffer(ep).unwrap(); let separator = if module.global_variables.is_empty() { ' ' } else { @@ -3824,7 +3823,7 @@ impl Writer { }; } else if let Some(ref binding) = var.binding { // write an inline sampler - let resolved = options.resolve_resource_binding(ep.stage, binding).unwrap(); + let resolved = options.resolve_resource_binding(ep, binding).unwrap(); if let Some(sampler) = resolved.as_inline_sampler(options) { let name = &self.names[&NameKey::GlobalVariable(handle)]; writeln!( diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index af45e4f97..5cd8e79a4 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -6,8 +6,8 @@ ), msl: ( lang_version: (2, 0), - per_stage_map: ( - vs: ( + per_entry_point_map: { + "foo_vert": ( resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: false), (group: 0, binding: 1): (buffer: Some(1), mutable: false), @@ -16,20 +16,20 @@ }, sizes_buffer: Some(24), ), - fs: ( + "foo_frag": ( resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: true), (group: 0, binding: 2): (buffer: Some(2), mutable: true), }, sizes_buffer: Some(24), ), - cs: ( + "atomics": ( resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: true), }, sizes_buffer: Some(24), ), - ), + }, inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, diff --git a/tests/in/binding-arrays.param.ron b/tests/in/binding-arrays.param.ron index ad5b0ee31..1f2ac686b 100644 --- a/tests/in/binding-arrays.param.ron +++ b/tests/in/binding-arrays.param.ron @@ -19,14 +19,14 @@ ), msl: ( lang_version: (2, 0), - per_stage_map: ( - fs: ( + per_entry_point_map: { + "main": ( resources: { (group: 0, binding: 0): (texture: Some(0), binding_array_size: Some(10), mutable: false), }, sizes_buffer: None, ) - ), + }, inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: true, diff --git a/tests/in/bitcast.params.ron b/tests/in/bitcast.params.ron index 324cd4a51..b40cf9fa0 100644 --- a/tests/in/bitcast.params.ron +++ b/tests/in/bitcast.params.ron @@ -1,13 +1,13 @@ ( msl: ( lang_version: (1, 2), - per_stage_map: ( - cs: ( + per_entry_point_map: { + "main": ( resources: { }, sizes_buffer: Some(0), ) - ), + }, inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, diff --git a/tests/in/bits.param.ron b/tests/in/bits.param.ron index 324cd4a51..b40cf9fa0 100644 --- a/tests/in/bits.param.ron +++ b/tests/in/bits.param.ron @@ -1,13 +1,13 @@ ( msl: ( lang_version: (1, 2), - per_stage_map: ( - cs: ( + per_entry_point_map: { + "main": ( resources: { }, sizes_buffer: Some(0), ) - ), + }, inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index e6d752fca..976b457ed 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -6,8 +6,8 @@ ), msl: ( lang_version: (2, 0), - per_stage_map: ( - cs: ( + per_entry_point_map: { + "main": ( resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: false), (group: 0, binding: 1): (buffer: Some(1), mutable: true), @@ -15,7 +15,7 @@ }, sizes_buffer: Some(3), ) - ), + }, inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, diff --git a/tests/in/extra.param.ron b/tests/in/extra.param.ron index 051dee643..581c6d6bd 100644 --- a/tests/in/extra.param.ron +++ b/tests/in/extra.param.ron @@ -5,11 +5,11 @@ ), msl: ( lang_version: (2, 2), - per_stage_map: ( - fs: ( + per_entry_point_map: { + "main": ( push_constant_buffer: Some(1), ), - ), + }, inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index 5df3e3b9c..1c910d2b8 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -19,7 +19,7 @@ ), msl: ( lang_version: (2, 1), - per_stage_map: (), + per_entry_point_map: {}, inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, diff --git a/tests/in/padding.param.ron b/tests/in/padding.param.ron index 41af2916a..14859bba3 100644 --- a/tests/in/padding.param.ron +++ b/tests/in/padding.param.ron @@ -6,15 +6,15 @@ ), msl: ( lang_version: (2, 0), - per_stage_map: ( - vs: ( + per_entry_point_map: { + "vertex": ( resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: false), (group: 0, binding: 1): (buffer: Some(1), mutable: false), (group: 0, binding: 2): (buffer: Some(2), mutable: false), }, ), - ), + }, inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, diff --git a/tests/in/resource-binding-map.param.ron b/tests/in/resource-binding-map.param.ron new file mode 100644 index 000000000..6b0b43c2a --- /dev/null +++ b/tests/in/resource-binding-map.param.ron @@ -0,0 +1,53 @@ +( + god_mode: true, + msl: ( + lang_version: (2, 0), + per_entry_point_map: { + "entry_point_one": ( + resources: { + (group: 0, binding: 0): (texture: Some(0)), + (group: 0, binding: 2): (sampler: Some(Inline(0))), + (group: 0, binding: 4): (buffer: Some(0)), + } + ), + "entry_point_two": ( + resources: { + (group: 0, binding: 0): (texture: Some(0)), + (group: 0, binding: 2): (sampler: Some(Resource(0))), + (group: 0, binding: 4): (buffer: Some(0)), + } + ), + "entry_point_three": ( + resources: { + (group: 0, binding: 0): (texture: Some(0)), + (group: 0, binding: 1): (texture: Some(1)), + (group: 0, binding: 2): (sampler: Some(Inline(0))), + (group: 0, binding: 3): (sampler: Some(Resource(1))), + (group: 0, binding: 4): (buffer: Some(0)), + (group: 1, binding: 0): (buffer: Some(1)), + } + ) + }, + inline_samplers: [ + ( + coord: Normalized, + address: (ClampToEdge, ClampToEdge, ClampToEdge), + mag_filter: Linear, + min_filter: Linear, + mip_filter: None, + border_color: TransparentBlack, + compare_func: Never, + lod_clamp: Some((start: 0.5, end: 10.0)), + max_anisotropy: Some(8), + ), + ], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, + ), + bounds_check_policies: ( + index: ReadZeroSkipWrite, + buffer: ReadZeroSkipWrite, + image: ReadZeroSkipWrite, + ) +) diff --git a/tests/in/resource-binding-map.wgsl b/tests/in/resource-binding-map.wgsl new file mode 100644 index 000000000..fa5fce4ee --- /dev/null +++ b/tests/in/resource-binding-map.wgsl @@ -0,0 +1,23 @@ +@group(0) @binding(0) var t1: texture_2d; +@group(0) @binding(1) var t2: texture_2d; +@group(0) @binding(2) var s1: sampler; +@group(0) @binding(3) var s2: sampler; + +@group(0) @binding(4) var uniformOne: vec2; +@group(1) @binding(0) var uniformTwo: vec2; + +@fragment +fn entry_point_one(@builtin(position) pos: vec4) -> @location(0) vec4 { + return textureSample(t1, s1, pos.xy); +} + +@fragment +fn entry_point_two() -> @location(0) vec4 { + return textureSample(t1, s1, uniformOne); +} + +@fragment +fn entry_point_three() -> @location(0) vec4 { + return textureSample(t1, s1, uniformTwo + uniformOne) + + textureSample(t2, s2, uniformOne); +} diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 905721c91..6bca28fc6 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -7,19 +7,19 @@ ), msl: ( lang_version: (2, 1), - per_stage_map: ( - vs: ( + per_entry_point_map: { + "vs_main": ( resources: { (group: 0, binding: 0): (buffer: Some(0)), }, ), - fs: ( + "fs_main": ( resources: { (group: 0, binding: 1): (texture: Some(0)), (group: 0, binding: 2): (sampler: Some(Inline(0))), }, ), - ), + }, inline_samplers: [ ( coord: Normalized, diff --git a/tests/in/workgroup-var-init.param.ron b/tests/in/workgroup-var-init.param.ron index fd10e95d6..be5302284 100644 --- a/tests/in/workgroup-var-init.param.ron +++ b/tests/in/workgroup-var-init.param.ron @@ -6,17 +6,17 @@ ), msl: ( lang_version: (2, 0), - per_stage_map: ( - cs: ( + per_entry_point_map: { + "main": ( resources: { (group: 0, binding: 0): (buffer: Some(0), mutable: true), }, sizes_buffer: None, ), - ), + }, inline_samplers: [], spirv_cross_compatibility: false, fake_missing_bindings: false, zero_initialize_workgroup_memory: true, ), -) \ No newline at end of file +) diff --git a/tests/out/msl/resource-binding-map.msl b/tests/out/msl/resource-binding-map.msl new file mode 100644 index 000000000..4e0b60132 --- /dev/null +++ b/tests/out/msl/resource-binding-map.msl @@ -0,0 +1,74 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct DefaultConstructible { + template + operator T() && { + return T {}; + } +}; + +struct entry_point_oneInput { +}; +struct entry_point_oneOutput { + metal::float4 member [[color(0)]]; +}; +fragment entry_point_oneOutput entry_point_one( + metal::float4 pos [[position]] +, metal::texture2d t1_ [[texture(0)]] +) { + constexpr metal::sampler s1_( + metal::s_address::clamp_to_edge, + metal::t_address::clamp_to_edge, + metal::r_address::clamp_to_edge, + metal::mag_filter::linear, + metal::min_filter::linear, + metal::coord::normalized + ); + metal::float4 _e4 = t1_.sample(s1_, pos.xy); + return entry_point_oneOutput { _e4 }; +} + + +struct entry_point_twoOutput { + metal::float4 member_1 [[color(0)]]; +}; +fragment entry_point_twoOutput entry_point_two( + metal::texture2d t1_ [[texture(0)]] +, metal::sampler s1_ [[sampler(0)]] +, constant metal::float2& uniformOne [[buffer(0)]] +) { + metal::float2 _e3 = uniformOne; + metal::float4 _e4 = t1_.sample(s1_, _e3); + return entry_point_twoOutput { _e4 }; +} + + +struct entry_point_threeOutput { + metal::float4 member_2 [[color(0)]]; +}; +fragment entry_point_threeOutput entry_point_three( + metal::texture2d t1_ [[texture(0)]] +, metal::texture2d t2_ [[texture(1)]] +, metal::sampler s2_ [[sampler(1)]] +, constant metal::float2& uniformOne [[buffer(0)]] +, constant metal::float2& uniformTwo [[buffer(1)]] +) { + constexpr metal::sampler s1_( + metal::s_address::clamp_to_edge, + metal::t_address::clamp_to_edge, + metal::r_address::clamp_to_edge, + metal::mag_filter::linear, + metal::min_filter::linear, + metal::coord::normalized + ); + metal::float2 _e3 = uniformTwo; + metal::float2 _e5 = uniformOne; + metal::float4 _e7 = t1_.sample(s1_, _e3 + _e5); + metal::float2 _e11 = uniformOne; + metal::float4 _e12 = t2_.sample(s2_, _e11); + return entry_point_threeOutput { _e7 + _e12 }; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index c464aa344..a0b9ed53a 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -90,8 +90,11 @@ struct Parameters { #[allow(unused_variables)] fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let root = env!("CARGO_MANIFEST_DIR"); - let params = match fs::read_to_string(format!("{root}/{BASE_DIR_IN}/{name}.param.ron")) { - Ok(string) => ron::de::from_str(&string).expect("Couldn't parse param file"), + let filepath = format!("{root}/{BASE_DIR_IN}/{name}.param.ron"); + let params = match fs::read_to_string(&filepath) { + Ok(string) => { + ron::de::from_str(&string).expect(&format!("Couldn't parse param file: {}", filepath)) + } Err(_) => Parameters::default(), }; @@ -543,6 +546,7 @@ fn convert_wgsl() { "binding-arrays", Targets::WGSL | Targets::HLSL | Targets::METAL | Targets::SPIRV, ), + ("resource-binding-map", Targets::METAL), ("multiview", Targets::SPIRV | Targets::GLSL | Targets::WGSL), ("multiview_webgl", Targets::GLSL), ( From a7b52b8663a09506dc417e9149d64abcf637f9f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A2ris=20DOUADY?= Date: Mon, 27 Feb 2023 10:47:10 +0100 Subject: [PATCH 1952/2212] enforce discard only in fragment (#2262) --- src/valid/function.rs | 1 + tests/wgsl-errors.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/valid/function.rs b/src/valid/function.rs index b615895ae..386937d70 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -595,6 +595,7 @@ impl super::Validator { finished = true; } S::Kill => { + stages &= super::ShaderStages::FRAGMENT; finished = true; } S::Barrier(_) => { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index d76252ced..d44dd97f3 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -943,6 +943,35 @@ fn invalid_arrays() { } } +#[test] +fn discard_in_wrong_stage() { + check_validation! { + "@compute @workgroup_size(1) +fn main(@builtin(global_invocation_id) global_id: vec3) { + if global_id.x == 3u { + discard; + } +}": + Err(naga::valid::ValidationError::EntryPoint { + stage: naga::ShaderStage::Compute, + source: naga::valid::EntryPointError::ForbiddenStageOperations, + .. + }) + } + + check_validation! { + "@vertex +fn main() { + discard; +}": + Err(naga::valid::ValidationError::EntryPoint { + stage: naga::ShaderStage::Vertex, + source: naga::valid::EntryPointError::ForbiddenStageOperations, + .. + }) + } +} + #[test] fn invalid_structs() { check_validation! { From 8a72b7a8ad997c61a82e9b6b9284ca8811722d06 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Fri, 10 Mar 2023 11:53:11 -0500 Subject: [PATCH 1953/2212] Differentiate between i32 and u32 in switch (#2269) * Differentiate between i32 and u32 in switch * Use similar wording to other error messages * Remove duplicate enum --- src/back/dot/mod.rs | 2 +- src/back/glsl/mod.rs | 12 +---- src/back/hlsl/writer.rs | 14 ++---- src/back/msl/writer.rs | 14 ++---- src/back/spv/block.rs | 5 +- src/back/wgsl/writer.rs | 18 +++---- src/front/glsl/parser/functions.rs | 50 +++++++++--------- src/front/spv/function.rs | 2 +- src/front/wgsl/lower/mod.rs | 8 +-- src/lib.rs | 5 +- src/valid/function.rs | 81 ++++++++++++++++-------------- src/valid/mod.rs | 6 +-- 12 files changed, 103 insertions(+), 114 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 5da9029ab..4799012ab 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -157,8 +157,8 @@ impl StatementGraph { for case in cases { let (case_id, case_last) = self.add(&case.body, targets); let label = match case.value { - crate::SwitchValue::Integer(_) => "case", crate::SwitchValue::Default => "default", + _ => "case", }; self.flow.push((id, case_id, label)); // Link the last node of the branch to the merge node diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a75188b4d..dbcda3ada 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1906,21 +1906,13 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "switch(")?; self.write_expr(selector, ctx)?; writeln!(self.out, ") {{")?; - let type_postfix = match *ctx.info[selector].ty.inner_with(&self.module.types) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - .. - } => "u", - _ => "", - }; // Write all cases let l2 = level.next(); for case in cases { match case.value { - crate::SwitchValue::Integer(value) => { - write!(self.out, "{l2}case {value}{type_postfix}:")? - } + crate::SwitchValue::I32(value) => write!(self.out, "{l2}case {value}:")?, + crate::SwitchValue::U32(value) => write!(self.out, "{l2}case {value}u:")?, crate::SwitchValue::Default => write!(self.out, "{l2}default:")?, } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 7b08ddf74..3326c1c96 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1883,13 +1883,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "switch(")?; self.write_expr(module, selector, func_ctx)?; writeln!(self.out, ") {{")?; - let type_postfix = match *func_ctx.info[selector].ty.inner_with(&module.types) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - .. - } => "u", - _ => "", - }; // Write all cases let indent_level_1 = level.next(); @@ -1897,8 +1890,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { for (i, case) in cases.iter().enumerate() { match case.value { - crate::SwitchValue::Integer(value) => { - write!(self.out, "{indent_level_1}case {value}{type_postfix}:")? + crate::SwitchValue::I32(value) => { + write!(self.out, "{indent_level_1}case {value}:")? + } + crate::SwitchValue::U32(value) => { + write!(self.out, "{indent_level_1}case {value}u:")? } crate::SwitchValue::Default => { write!(self.out, "{indent_level_1}default:")? diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index cb1ec2499..fb4b0929c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2551,19 +2551,15 @@ impl Writer { } => { write!(self.out, "{level}switch(")?; self.put_expression(selector, &context.expression, true)?; - let type_postfix = match *context.expression.resolve_type(selector) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - .. - } => "u", - _ => "", - }; writeln!(self.out, ") {{")?; let lcase = level.next(); for case in cases.iter() { match case.value { - crate::SwitchValue::Integer(value) => { - write!(self.out, "{lcase}case {value}{type_postfix}:")?; + crate::SwitchValue::I32(value) => { + write!(self.out, "{lcase}case {value}:")?; + } + crate::SwitchValue::U32(value) => { + write!(self.out, "{lcase}case {value}u:")?; } crate::SwitchValue::Default => { write!(self.out, "{lcase}default:")?; diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index bf45130ad..ccf597917 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1770,12 +1770,15 @@ impl<'w> BlockContext<'w> { case_ids.push(label_id); match case.value { - crate::SwitchValue::Integer(value) => { + crate::SwitchValue::I32(value) => { raw_cases.push(super::instructions::Case { value: value as Word, label_id, }); } + crate::SwitchValue::U32(value) => { + raw_cases.push(super::instructions::Case { value, label_id }); + } crate::SwitchValue::Default => { default_id = Some(label_id); } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index be4d9e442..828cd79b0 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -865,14 +865,6 @@ impl Writer { self.write_expr(module, selector, func_ctx)?; writeln!(self.out, " {{")?; - let type_postfix = match *func_ctx.info[selector].ty.inner_with(&module.types) { - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Uint, - .. - } => "u", - _ => "", - }; - let l2 = level.next(); let mut new_case = true; for case in cases { @@ -884,11 +876,17 @@ impl Writer { } match case.value { - crate::SwitchValue::Integer(value) => { + crate::SwitchValue::I32(value) => { if new_case { write!(self.out, "{l2}case ")?; } - write!(self.out, "{value}{type_postfix}")?; + write!(self.out, "{value}")?; + } + crate::SwitchValue::U32(value) => { + if new_case { + write!(self.out, "{l2}case ")?; + } + write!(self.out, "{value}u")?; } crate::SwitchValue::Default => { if new_case { diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index e6c86ad6d..8bfb9040b 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -186,35 +186,33 @@ impl<'source> ParsingContext<'source> { let value = match self.expect_peek(frontend)?.value { TokenValue::Case => { self.bump(frontend)?; - let value = { - let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; - let (root, meta) = - ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; - let constant = frontend.solve_constant(ctx, root, meta)?; - match frontend.module.constants[constant].inner { - ConstantInner::Scalar { - value: ScalarValue::Sint(int), - .. - } => int as i32, - ConstantInner::Scalar { - value: ScalarValue::Uint(int), - .. - } => int as i32, - _ => { - frontend.errors.push(Error { - kind: ErrorKind::SemanticError( - "Case values can only be integers".into(), - ), - meta, - }); + let mut stmt = ctx.stmt_ctx(); + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + let (root, meta) = + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; + let constant = frontend.solve_constant(ctx, root, meta)?; - 0 - } + match frontend.module.constants[constant].inner { + ConstantInner::Scalar { + value: ScalarValue::Sint(int), + .. + } => crate::SwitchValue::I32(int as i32), + ConstantInner::Scalar { + value: ScalarValue::Uint(int), + .. + } => crate::SwitchValue::U32(int as u32), + _ => { + frontend.errors.push(Error { + kind: ErrorKind::SemanticError( + "Case values can only be integers".into(), + ), + meta, + }); + + crate::SwitchValue::I32(0) } - }; - crate::SwitchValue::Integer(value) + } } TokenValue::Default => { self.bump(frontend)?; diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 898d00f79..c26c61e1e 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -596,7 +596,7 @@ impl<'function> BlockContext<'function> { let fall_through = body.last().map_or(true, |s| !s.is_terminator()); crate::SwitchCase { - value: crate::SwitchValue::Integer(value), + value: crate::SwitchValue::I32(value), body, fall_through, } diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 481ea7535..01a46f28c 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1006,11 +1006,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .map(|case| { Ok(crate::SwitchCase { value: match case.value { - ast::SwitchValue::I32(num) if !uint => { - crate::SwitchValue::Integer(num) + ast::SwitchValue::I32(value) if !uint => { + crate::SwitchValue::I32(value) } - ast::SwitchValue::U32(num) if uint => { - crate::SwitchValue::Integer(num as i32) + ast::SwitchValue::U32(value) if uint => { + crate::SwitchValue::U32(value) } ast::SwitchValue::Default => crate::SwitchValue::Default, _ => { diff --git a/src/lib.rs b/src/lib.rs index e60d8e0cc..e370b81a6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1429,12 +1429,13 @@ pub use block::Block; /// The value of the switch case. // Clone is used only for error reporting and is not intended for end users -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum SwitchValue { - Integer(i32), + I32(i32), + U32(u32), Default, } diff --git a/src/valid/function.rs b/src/valid/function.rs index 386937d70..464496f6d 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -103,7 +103,9 @@ pub enum FunctionError { #[error("The `switch` value {0:?} is not an integer scalar")] InvalidSwitchType(Handle), #[error("Multiple `switch` cases for {0:?} are present")] - ConflictingSwitchCase(i32), + ConflictingSwitchCase(crate::SwitchValue), + #[error("The `switch` contains cases with conflicting types")] + ConflictingCaseType, #[error("The `switch` is missing a `default` case")] MissingDefaultCase, #[error("Multiple `default` cases are present")] @@ -434,52 +436,55 @@ impl super::Validator { selector, ref cases, } => { - match *context.resolve_type(selector, &self.valid_expression_set)? { - Ti::Scalar { - kind: crate::ScalarKind::Uint, - width: _, - } => {} - Ti::Scalar { - kind: crate::ScalarKind::Sint, - width: _, - } => {} + let uint = match context + .resolve_type(selector, &self.valid_expression_set)? + .scalar_kind() + { + Some(crate::ScalarKind::Uint) => true, + Some(crate::ScalarKind::Sint) => false, _ => { return Err(FunctionError::InvalidSwitchType(selector) .with_span_handle(selector, context.expressions)) } - } - self.select_cases.clear(); - let mut default = false; + }; + self.switch_values.clear(); for case in cases { match case.value { - crate::SwitchValue::Integer(value) => { - if !self.select_cases.insert(value) { - return Err(FunctionError::ConflictingSwitchCase(value) - .with_span_static( - case.body - .span_iter() - .next() - .map_or(Default::default(), |(_, s)| *s), - "conflicting switch arm here", - )); - } - } - crate::SwitchValue::Default => { - if default { - return Err(FunctionError::MultipleDefaultCases - .with_span_static( - case.body - .span_iter() - .next() - .map_or(Default::default(), |(_, s)| *s), - "duplicated switch arm here", - )); - } - default = true + crate::SwitchValue::I32(_) if !uint => {} + crate::SwitchValue::U32(_) if uint => {} + crate::SwitchValue::Default => {} + _ => { + return Err(FunctionError::ConflictingCaseType.with_span_static( + case.body + .span_iter() + .next() + .map_or(Default::default(), |(_, s)| *s), + "conflicting switch arm here", + )); } + }; + if !self.switch_values.insert(case.value) { + return Err(match case.value { + crate::SwitchValue::Default => FunctionError::MultipleDefaultCases + .with_span_static( + case.body + .span_iter() + .next() + .map_or(Default::default(), |(_, s)| *s), + "duplicated switch arm here", + ), + _ => FunctionError::ConflictingSwitchCase(case.value) + .with_span_static( + case.body + .span_iter() + .next() + .map_or(Default::default(), |(_, s)| *s), + "conflicting switch arm here", + ), + }); } } - if !default { + if !self.switch_values.contains(&crate::SwitchValue::Default) { return Err(FunctionError::MissingDefaultCase .with_span_static(span, "missing default case")); } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 9d9c3f885..eb92e8892 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -163,7 +163,7 @@ pub struct Validator { location_mask: BitSet, bind_group_masks: Vec, #[allow(dead_code)] - select_cases: FastHashSet, + switch_values: FastHashSet, valid_expression_list: Vec>, valid_expression_set: BitSet, } @@ -275,7 +275,7 @@ impl Validator { layouter: Layouter::default(), location_mask: BitSet::new(), bind_group_masks: Vec::new(), - select_cases: FastHashSet::default(), + switch_values: FastHashSet::default(), valid_expression_list: Vec::new(), valid_expression_set: BitSet::new(), } @@ -287,7 +287,7 @@ impl Validator { self.layouter.clear(); self.location_mask.clear(); self.bind_group_masks.clear(); - self.select_cases.clear(); + self.switch_values.clear(); self.valid_expression_list.clear(); self.valid_expression_set.clear(); } From 7f829c6ac6aabda426a083cc7a6a854c1abd98f6 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Tue, 14 Mar 2023 05:11:03 -0400 Subject: [PATCH 1954/2212] [glsl-in] Switch implicit type conversion (#2273) --- src/front/glsl/parser/functions.rs | 14 ++++++++++---- tests/in/glsl/statements.frag | 9 +++++++++ tests/out/wgsl/statements-frag.wgsl | 22 ++++++++++++++++++---- 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 8bfb9040b..781f4cffe 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -166,11 +166,14 @@ impl<'source> ParsingContext<'source> { self.expect(frontend, TokenValue::LeftParen)?; - let selector = { + let (selector, uint) = { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; - ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)? - .0 + let (root, meta) = + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; + let uint = frontend.resolve_type(ctx, root, meta)?.scalar_kind() + == Some(crate::ScalarKind::Uint); + (root, uint) }; self.expect(frontend, TokenValue::RightParen)?; @@ -197,7 +200,10 @@ impl<'source> ParsingContext<'source> { ConstantInner::Scalar { value: ScalarValue::Sint(int), .. - } => crate::SwitchValue::I32(int as i32), + } => match uint { + true => crate::SwitchValue::U32(int as u32), + false => crate::SwitchValue::I32(int as i32), + }, ConstantInner::Scalar { value: ScalarValue::Uint(int), .. diff --git a/tests/in/glsl/statements.frag b/tests/in/glsl/statements.frag index c9e276c87..3423e73b8 100644 --- a/tests/in/glsl/statements.frag +++ b/tests/in/glsl/statements.frag @@ -15,6 +15,15 @@ void switchNoDefault(int a) { return; } +void switchCaseImplConv(uint a) { + switch (a) { + case 0: + break; + } + + return; +} + void switchNoLastBreak(int a) { switch (a) { default: diff --git a/tests/out/wgsl/statements-frag.wgsl b/tests/out/wgsl/statements-frag.wgsl index b79995932..bc36eb207 100644 --- a/tests/out/wgsl/statements-frag.wgsl +++ b/tests/out/wgsl/statements-frag.wgsl @@ -24,15 +24,29 @@ fn switchNoDefault(a_2: i32) { return; } -fn switchNoLastBreak(a_4: i32) { - var a_5: i32; - var b: i32; +fn switchCaseImplConv(a_4: u32) { + var a_5: u32; a_5 = a_4; let _e2 = a_5; switch _e2 { + case 0u: { + } default: { - let _e3 = a_5; + } + } + return; +} + +fn switchNoLastBreak(a_6: i32) { + var a_7: i32; + var b: i32; + + a_7 = a_6; + let _e2 = a_7; + switch _e2 { + default: { + let _e3 = a_7; b = _e3; } } From 63e91faecbd69aabb3dc0c6658182f40292ebbe4 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 15 Mar 2023 18:46:25 +0100 Subject: [PATCH 1955/2212] Skip `gl_PerVertex` unused builtins in the SPIR-V frontend (#2272) Co-authored-by: Jim Blandy --- src/arena.rs | 13 +++ src/back/glsl/features.rs | 8 +- src/back/glsl/mod.rs | 24 +---- src/back/hlsl/conv.rs | 5 +- src/back/msl/writer.rs | 34 ++----- src/back/wgsl/writer.rs | 164 +++++++--------------------------- src/front/glsl/variables.rs | 4 +- src/front/spv/function.rs | 48 +++++++--- src/front/spv/mod.rs | 27 ++++-- tests/out/hlsl/quad-vert.hlsl | 7 +- tests/out/wgsl/quad-vert.wgsl | 5 +- 11 files changed, 125 insertions(+), 214 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 1e7b65937..5c2681c83 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -590,6 +590,19 @@ impl UniqueArena { Handle::from_usize(index) } + /// Replace an old value with a new value. + /// + /// # Panics + /// + /// - if the old value is not in the arena + /// - if the new value already exists in the arena + pub fn replace(&mut self, old: Handle, new: T) { + let (index, added) = self.set.insert_full(new); + assert!(added && index == self.set.len() - 1); + + self.set.swap_remove_index(old.index()).unwrap(); + } + /// Return this arena's handle for `value`, if present. /// /// If this arena already contains an element equal to `value`, diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index ca292364f..8392969b5 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -99,9 +99,8 @@ impl FeaturesManager { check_feature!(CONSERVATIVE_DEPTH, 130, 300); check_feature!(NOPERSPECTIVE_QUALIFIER, 130); check_feature!(SAMPLE_QUALIFIER, 400, 320); - // gl_ClipDistance is supported by core versions > 1.3 and aren't supported by an es versions without extensions - check_feature!(CLIP_DISTANCE, 130, 300); - check_feature!(CULL_DISTANCE, 450, 300); + check_feature!(CLIP_DISTANCE, 130, 300 /* with extension */); + check_feature!(CULL_DISTANCE, 450, 300 /* with extension */); check_feature!(SAMPLE_VARIABLES, 400, 300); check_feature!(DYNAMIC_ARRAY_SIZE, 430, 310); match version { @@ -197,9 +196,8 @@ impl FeaturesManager { if (self.0.contains(Features::CLIP_DISTANCE) || self.0.contains(Features::CULL_DISTANCE)) && version.is_es() { - // TODO: handle gl_ClipDistance and gl_CullDistance usage in better way // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_clip_cull_distance.txt - // writeln!(out, "#extension GL_EXT_clip_cull_distance : require")?; + writeln!(out, "#extension GL_EXT_clip_cull_distance : require")?; } if self.0.contains(Features::SAMPLE_VARIABLES) && version.is_es() { diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index dbcda3ada..467d680f9 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2029,27 +2029,11 @@ impl<'a, W: Write> Writer<'a, W> { }; for (index, member) in members.iter().enumerate() { - // TODO: handle builtin in better way - if let Some(crate::Binding::BuiltIn(builtin)) = - member.binding + if let Some(crate::Binding::BuiltIn( + crate::BuiltIn::PointSize, + )) = member.binding { - has_point_size |= builtin == crate::BuiltIn::PointSize; - - match builtin { - crate::BuiltIn::ClipDistance - | crate::BuiltIn::CullDistance => { - if self.options.version.is_es() { - // Note that gl_ClipDistance and gl_CullDistance are listed in the GLSL ES 3.2 spec but shouldn't - // See https://github.com/KhronosGroup/GLSL/issues/132#issuecomment-685818465 - log::warn!( - "{:?} is not part of GLSL ES", - builtin - ); - continue; - } - } - _ => {} - } + has_point_size = true; } let varying_name = VaryingName { diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 1773ed71b..5eb24962f 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -155,9 +155,6 @@ impl crate::BuiltIn { Self::ClipDistance => "SV_ClipDistance", Self::CullDistance => "SV_CullDistance", Self::InstanceIndex => "SV_InstanceID", - // based on this page https://docs.microsoft.com/en-us/windows/uwp/gaming/glsl-to-hlsl-reference#comparing-opengl-es-20-with-direct3d-11 - // No meaning unless you target Direct3D 9 - Self::PointSize => "PSIZE", Self::VertexIndex => "SV_VertexID", // fragment Self::FragDepth => "SV_Depth", @@ -177,7 +174,7 @@ impl crate::BuiltIn { Self::BaseInstance | Self::BaseVertex | Self::WorkGroupSize => { return Err(Error::Unimplemented(format!("builtin {self:?}"))) } - Self::ViewIndex | Self::PointCoord => { + Self::PointSize | Self::ViewIndex | Self::PointCoord => { return Err(Error::Custom(format!("Unsupported builtin {self:?}"))) } }) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index fb4b0929c..bac178729 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2233,18 +2233,13 @@ impl Writer { let mut is_first = true; for (index, member) in members.iter().enumerate() { - match member.binding { - Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) => { - has_point_size = true; - if !context.pipeline_options.allow_point_size { - continue; - } - } - Some(crate::Binding::BuiltIn(crate::BuiltIn::CullDistance)) => { - log::warn!("Ignoring CullDistance built-in"); + if let Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) = + member.binding + { + has_point_size = true; + if !context.pipeline_options.allow_point_size { continue; } - _ => {} } let comma = if is_first { "" } else { "," }; @@ -3563,24 +3558,11 @@ impl Writer { }; let binding = binding.ok_or(Error::Validation)?; - match *binding { - // Point size is only supported in VS of pipelines with - // point primitive topology. - crate::Binding::BuiltIn(crate::BuiltIn::PointSize) => { - has_point_size = true; - if !pipeline_options.allow_point_size { - continue; - } - } - // Cull Distance is not supported in Metal. - // But we can't return UnsupportedBuiltIn error to user. - // Because otherwise we can't generate msl shader from any glslang SPIR-V shaders. - // glslang generates gl_PerVertex struct with gl_CullDistance builtin inside by default. - crate::Binding::BuiltIn(crate::BuiltIn::CullDistance) => { - log::warn!("Ignoring CullDistance BuiltIn"); + if let crate::Binding::BuiltIn(crate::BuiltIn::PointSize) = *binding { + has_point_size = true; + if !pipeline_options.allow_point_size { continue; } - _ => {} } let array_len = match module.types[ty].inner { diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 828cd79b0..05f5b1094 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -335,11 +335,8 @@ impl Writer { match *attribute { Attribute::Location(id) => write!(self.out, "@location({id}) ")?, Attribute::BuiltIn(builtin_attrib) => { - if let Some(builtin) = builtin_str(builtin_attrib) { - write!(self.out, "@builtin({builtin}) ")?; - } else { - log::warn!("Unsupported builtin attribute: {:?}", builtin_attrib); - } + let builtin = builtin_str(builtin_attrib)?; + write!(self.out, "@builtin({builtin}) ")?; } Attribute::Stage(shader_stage) => { let stage_str = match shader_stage { @@ -401,14 +398,6 @@ impl Writer { write!(self.out, " {{")?; writeln!(self.out)?; for (index, member) in members.iter().enumerate() { - // Skip struct member with unsupported built in - if let Some(crate::Binding::BuiltIn(built_in)) = member.binding { - if builtin_str(built_in).is_none() { - log::warn!("Skip member with unsupported builtin {:?}", built_in); - continue; - } - } - // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; if let Some(ref binding) = member.binding { @@ -669,22 +658,6 @@ impl Writer { _ => false, }; if min_ref_count <= info.ref_count || required_baking_expr { - // If expression contains unsupported builtin we should skip it - if let Expression::Load { pointer } = func_ctx.expressions[handle] { - if let Expression::AccessIndex { base, index } = - func_ctx.expressions[pointer] - { - if access_to_unsupported_builtin( - base, - index, - module, - func_ctx.info, - ) { - return Ok(()); - } - } - } - Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) } else { None @@ -746,14 +719,6 @@ impl Writer { writeln!(self.out, "discard;")? } Statement::Store { pointer, value } => { - // WGSL does not support all SPIR-V builtins and we should skip it in generated shaders. - // We already skip them when we generate struct type. - // Now we need to find expression that used struct with ignored builtins - if let Expression::AccessIndex { base, index } = func_ctx.expressions[pointer] { - if access_to_unsupported_builtin(base, index, module, func_ctx.info) { - return Ok(()); - } - } write!(self.out, "{level}")?; let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { @@ -1150,42 +1115,10 @@ impl Writer { Expression::Compose { ty, ref components } => { self.write_type(module, ty)?; write!(self.out, "(")?; - // !spv-in specific notes! - // WGSL does not support all SPIR-V builtins and we should skip it in generated shaders. - // We already skip them when we generate struct type. - // Now we need to find components that used struct with ignored builtins. - - // So, why we can't just return the error to a user? - // We can, but otherwise, we can't generate WGSL shader from any glslang SPIR-V shaders. - // glslang generates gl_PerVertex struct with gl_CullDistance, gl_ClipDistance and gl_PointSize builtin inside by default. - // All of them are not supported by WGSL. - - // We need to copy components to another vec because we don't know which of them we should write. - let mut components_to_write = Vec::with_capacity(components.len()); - for component in components { - let mut skip_component = false; - if let Expression::Load { pointer } = func_ctx.expressions[*component] { - if let Expression::AccessIndex { base, index } = - func_ctx.expressions[pointer] - { - if access_to_unsupported_builtin(base, index, module, func_ctx.info) { - skip_component = true; - } - } - } - if skip_component { - continue; - } else { - components_to_write.push(*component); - } - } - - // non spv-in specific notes! - // Real `Expression::Compose` logic generates here. - for (index, component) in components_to_write.iter().enumerate() { + for (index, component) in components.iter().enumerate() { self.write_expr(module, *component, func_ctx)?; // Only write a comma if isn't the last element - if index != components_to_write.len().saturating_sub(1) { + if index != components.len().saturating_sub(1) { // The leading space is for readability only write!(self.out, ", ")?; } @@ -1764,25 +1697,8 @@ impl Writer { self.write_type(module, ty)?; write!(self.out, "(")?; - let members = match module.types[ty].inner { - TypeInner::Struct { ref members, .. } => Some(members), - _ => None, - }; - // Write the comma separated constants for (index, constant) in components.iter().enumerate() { - if let Some(&crate::Binding::BuiltIn(built_in)) = - members.and_then(|members| members.get(index)?.binding.as_ref()) - { - if builtin_str(built_in).is_none() { - log::warn!( - "Skip constant for struct member with unsupported builtin {:?}", - built_in - ); - continue; - } - } - self.write_constant(module, *constant)?; // Only write a comma if isn't the last element if index != components.len().saturating_sub(1) { @@ -1869,26 +1785,34 @@ impl Writer { } } -const fn builtin_str(built_in: crate::BuiltIn) -> Option<&'static str> { +fn builtin_str(built_in: crate::BuiltIn) -> Result<&'static str, Error> { use crate::BuiltIn as Bi; - match built_in { - Bi::VertexIndex => Some("vertex_index"), - Bi::InstanceIndex => Some("instance_index"), - Bi::Position { .. } => Some("position"), - Bi::FrontFacing => Some("front_facing"), - Bi::FragDepth => Some("frag_depth"), - Bi::LocalInvocationId => Some("local_invocation_id"), - Bi::LocalInvocationIndex => Some("local_invocation_index"), - Bi::GlobalInvocationId => Some("global_invocation_id"), - Bi::WorkGroupId => Some("workgroup_id"), - Bi::NumWorkGroups => Some("num_workgroups"), - Bi::SampleIndex => Some("sample_index"), - Bi::SampleMask => Some("sample_mask"), - Bi::PrimitiveIndex => Some("primitive_index"), - Bi::ViewIndex => Some("view_index"), - _ => None, - } + Ok(match built_in { + Bi::VertexIndex => "vertex_index", + Bi::InstanceIndex => "instance_index", + Bi::Position { .. } => "position", + Bi::FrontFacing => "front_facing", + Bi::FragDepth => "frag_depth", + Bi::LocalInvocationId => "local_invocation_id", + Bi::LocalInvocationIndex => "local_invocation_index", + Bi::GlobalInvocationId => "global_invocation_id", + Bi::WorkGroupId => "workgroup_id", + Bi::NumWorkGroups => "num_workgroups", + Bi::SampleIndex => "sample_index", + Bi::SampleMask => "sample_mask", + Bi::PrimitiveIndex => "primitive_index", + Bi::ViewIndex => "view_index", + Bi::BaseInstance + | Bi::BaseVertex + | Bi::ClipDistance + | Bi::CullDistance + | Bi::PointSize + | Bi::PointCoord + | Bi::WorkGroupSize => { + return Err(Error::Custom(format!("Unsupported builtin {built_in:?}"))) + } + }) } const fn image_dimension_str(dim: crate::ImageDimension) -> &'static str { @@ -2032,31 +1956,3 @@ fn map_binding_to_attribute( }, } } - -/// Helper function that check that expression don't access to structure member with unsupported builtin. -fn access_to_unsupported_builtin( - expr: Handle, - index: u32, - module: &Module, - info: &valid::FunctionInfo, -) -> bool { - let base_ty_res = &info[expr].ty; - let resolved = base_ty_res.inner_with(&module.types); - if let TypeInner::Pointer { - base: pointer_base_handle, - .. - } = *resolved - { - // Let's check that we try to access a struct member with unsupported built-in and skip it. - if let TypeInner::Struct { ref members, .. } = module.types[pointer_base_handle].inner { - if let Some(crate::Binding::BuiltIn(built_in)) = members[index as usize].binding { - if builtin_str(built_in).is_none() { - log::warn!("Skip component with unsupported builtin {:?}", built_in); - return true; - } - } - } - } - - false -} diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 73fcb6e5e..4c0e0a927 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -200,8 +200,8 @@ impl Frontend { stride: 4, }, builtin: match name { - "gl_ClipDistance" => BuiltIn::PointSize, - "gl_CullDistance" => BuiltIn::FragDepth, + "gl_ClipDistance" => BuiltIn::ClipDistance, + "gl_CullDistance" => BuiltIn::CullDistance, _ => unreachable!(), }, mutable: self.meta.stage == ShaderStage::Vertex, diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index c26c61e1e..5dc781504 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -370,22 +370,50 @@ impl> super::Frontend { let expr_handle = function .expressions .append(crate::Expression::GlobalVariable(lvar.handle), span); + + // Cull problematic builtins of gl_PerVertex. + // See the docs for `Frontend::gl_per_vertex_builtin_access`. + { + let ty = &module.types[result.ty]; + match ty.inner { + crate::TypeInner::Struct { + members: ref original_members, + span, + } if ty.name.as_deref() == Some("gl_PerVertex") => { + let mut new_members = original_members.clone(); + for member in &mut new_members { + if let Some(crate::Binding::BuiltIn(built_in)) = member.binding + { + if !self.gl_per_vertex_builtin_access.contains(&built_in) { + member.binding = None + } + } + } + if &new_members != original_members { + module.types.replace( + result.ty, + crate::Type { + name: ty.name.clone(), + inner: crate::TypeInner::Struct { + members: new_members, + span, + }, + }, + ); + } + } + _ => {} + } + } + match module.types[result.ty].inner { crate::TypeInner::Struct { members: ref sub_members, .. } => { for (index, sm) in sub_members.iter().enumerate() { - match sm.binding { - Some(crate::Binding::BuiltIn(built_in)) => { - // Cull unused builtins to preserve performances - if !self.builtin_usage.contains(&built_in) { - continue; - } - } - // unrecognized binding, skip - None => continue, - _ => {} + if sm.binding.is_none() { + continue; } let mut sm = sm.clone(); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e5e9d4700..82a86a36a 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -560,9 +560,15 @@ pub struct Frontend { std::hash::BuildHasherDefault, >, - /// Tracks usage of builtins, used to cull unused builtins since they can - /// have serious performance implications. - builtin_usage: FastHashSet, + /// Tracks access to gl_PerVertex's builtins, it is used to cull unused builtins since initializing those can + /// affect performance and the mere presence of some of these builtins might cause backends to error since they + /// might be unsupported. + /// + /// The problematic builtins are: PointSize, ClipDistance and CullDistance. + /// + /// glslang declares those by default even though they are never written to + /// (see ) + gl_per_vertex_builtin_access: FastHashSet, } impl> Frontend { @@ -596,7 +602,7 @@ impl> Frontend { index_constants: Vec::new(), index_constant_expressions: Vec::new(), switch_cases: indexmap::IndexMap::default(), - builtin_usage: FastHashSet::default(), + gl_per_vertex_builtin_access: FastHashSet::default(), } } @@ -1480,7 +1486,8 @@ impl> Frontend { log::trace!("\t\t\tlooking up type {:?}", acex.type_id); let type_lookup = self.lookup_type.lookup(acex.type_id)?; - acex = match ctx.type_arena[type_lookup.handle].inner { + let ty = &ctx.type_arena[type_lookup.handle]; + acex = match ty.inner { // can only index a struct with a constant crate::TypeInner::Struct { ref members, .. } => { let index = index_maybe @@ -1498,10 +1505,12 @@ impl> Frontend { span, ); - if let Some(crate::Binding::BuiltIn(built_in)) = - members[index as usize].binding - { - self.builtin_usage.insert(built_in); + if ty.name.as_deref() == Some("gl_PerVertex") { + if let Some(crate::Binding::BuiltIn(built_in)) = + members[index as usize].binding + { + self.gl_per_vertex_builtin_access.insert(built_in); + } } AccessExpression { diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index a6c7a23b8..1fdcc43f5 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -1,9 +1,10 @@ struct gl_PerVertex { float4 gl_Position : SV_Position; - float gl_PointSize : PSIZE; - float gl_ClipDistance[1] : SV_ClipDistance; - float gl_CullDistance[1] : SV_CullDistance; + float gl_PointSize; + float gl_ClipDistance[1]; + float gl_CullDistance[1]; + int _end_pad_0; }; struct type_9 { diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index fec0c94af..97eee6a75 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -1,5 +1,8 @@ struct gl_PerVertex { @builtin(position) gl_Position: vec4, + gl_PointSize: f32, + gl_ClipDistance: array, + gl_CullDistance: array, } struct VertexOutput { @@ -9,7 +12,7 @@ struct VertexOutput { var v_uv: vec2; var a_uv_1: vec2; -var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), ); +var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), 1.0, array(0.0), array(0.0)); var a_pos_1: vec2; fn main_1() { From 4a03280e6c409de1f6c8ca09fadb49b1565957ff Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 15 Mar 2023 17:43:24 +0100 Subject: [PATCH 1956/2212] remove old `clippy::if_same_then_else` lint --- src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index e370b81a6..6a35e93d7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -189,7 +189,6 @@ tree. clippy::new_without_default, clippy::unneeded_field_pattern, clippy::match_like_matches_macro, - clippy::if_same_then_else, clippy::collapsible_if, clippy::derive_partial_eq_without_eq, clippy::needless_borrowed_reference From bdc25dd68939093c63004e976ab618e8a2026ca1 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 15 Mar 2023 17:43:41 +0100 Subject: [PATCH 1957/2212] fix rust 1.68 lints --- src/front/glsl/functions.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 1f24d404d..c565b3464 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -301,7 +301,6 @@ impl Frontend { Expression::Compose { ty: vector_ty, components: (0..rows as u32) - .into_iter() .map(|r| match r == i { true => value, false => zero, @@ -376,7 +375,6 @@ impl Frontend { components.push(match ori_rows.cmp(&rows) { Ordering::Less => { let components = (0..rows as u32) - .into_iter() .map(|r| { if r < ori_rows as u32 { ctx.add_expression( @@ -415,7 +413,6 @@ impl Frontend { inner: ConstantInner::Composite { ty: vector_ty, components: (0..rows as u32) - .into_iter() .map(|r| match r == i { true => one_constant, false => zero_constant, From 3450e795bc56afe26218ef5912c1789f6d0417bd Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 15 Mar 2023 17:46:50 +0100 Subject: [PATCH 1958/2212] enable `clippy::rest_pat_in_fully_bound_structs` lint --- src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 6a35e93d7..f072d5938 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -199,7 +199,8 @@ tree. unused_extern_crates, unused_qualifications, clippy::pattern_type_mismatch, - clippy::missing_const_for_fn + clippy::missing_const_for_fn, + clippy::rest_pat_in_fully_bound_structs )] #![cfg_attr(not(test), deny(clippy::panic))] From 6b0c2a532ad818edf77b4c0c372a5f0bd4209b4b Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 15 Mar 2023 17:52:13 +0100 Subject: [PATCH 1959/2212] enable `clippy::match_wildcard_for_single_variants` lint --- src/back/glsl/mod.rs | 2 +- src/back/hlsl/writer.rs | 2 +- src/back/mod.rs | 2 +- src/back/spv/writer.rs | 2 +- src/back/wgsl/writer.rs | 2 +- src/front/glsl/builtins.rs | 6 +++--- src/front/glsl/constants.rs | 2 +- src/front/glsl/context.rs | 2 +- src/front/glsl/functions.rs | 6 +++--- src/front/glsl/parser.rs | 2 +- src/lib.rs | 3 ++- src/valid/interface.rs | 2 +- 12 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 467d680f9..20c3f7930 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1297,7 +1297,7 @@ impl<'a, W: Write> Writer<'a, W> { let emit_interpolation_and_auxiliary = match self.entry_point.stage { ShaderStage::Vertex => output, ShaderStage::Fragment => !output, - _ => false, + ShaderStage::Compute => false, }; // Write the I/O locations, if allowed diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 3326c1c96..1f0491c58 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -371,7 +371,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } } - _ => {} + crate::Binding::BuiltIn(_) => {} } Ok(()) diff --git a/src/back/mod.rs b/src/back/mod.rs index 56223ac2b..6755983c0 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -53,7 +53,7 @@ impl FunctionType { FunctionType::EntryPoint(index) => { module.entry_points[index as usize].stage == crate::ShaderStage::Compute } - _ => false, + FunctionType::Function(_) => false, } } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index a56dc0508..e1a8d6976 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1702,7 +1702,7 @@ impl Writer { .entry(lookup_function_type.clone()) { Entry::Occupied(e) => *e.get(), - _ => { + Entry::Vacant(_) => { let id = self.id_gen.next(); let instruction = Instruction::type_function( id, diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 05f5b1094..7bfb0e964 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1529,7 +1529,7 @@ impl Writer { Mf::Unpack2x16snorm => Function::Regular("unpack2x16snorm"), Mf::Unpack2x16unorm => Function::Regular("unpack2x16unorm"), Mf::Unpack2x16float => Function::Regular("unpack2x16float"), - _ => { + Mf::Inverse => { return Err(Error::UnsupportedMathFunction(fun)); } }; diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index ef98e47ea..387ecf012 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -252,7 +252,7 @@ pub fn inject_builtin( args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); args.push(make_coords_arg(num_coords_from_dim, Sk::Float)); } - _ => {} + TextureLevelType::None => {} }; if offset { @@ -2255,7 +2255,7 @@ impl Frontend { let (shadow, storage) = match class { ImageClass::Depth { .. } => (true, false), ImageClass::Storage { .. } => (false, true), - _ => (false, false), + ImageClass::Sampled { .. } => (false, false), }; let coordinate = match (image_size, coord_size) { @@ -2377,7 +2377,7 @@ pub fn sampled_to_depth( } ImageClass::Depth { .. } => {} // Other image classes aren't allowed to be transformed to depth - _ => errors.push(Error { + ImageClass::Storage { .. } => errors.push(Error { kind: ErrorKind::SemanticError("Not a texture".into()), meta, }), diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index cdf7a8f63..d9a6fc7cd 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -413,7 +413,7 @@ impl<'a> ConstantSolver<'a> { ScalarValue::Sint(ref mut v) => *v = !*v, ScalarValue::Uint(ref mut v) => *v = !*v, ScalarValue::Bool(ref mut v) => *v = !*v, - _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + ScalarValue::Float(_) => return Err(ConstantSolvingError::InvalidUnaryOpArg), }, }, ConstantInner::Composite { diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 6d33ef9f6..6df4850ef 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -1063,7 +1063,7 @@ impl Context { _ if var.load => { self.add_expression(Expression::Load { pointer: var.expr }, meta, body) } - _ => var.expr, + ExprPos::Rhs => var.expr, }, HirExprKind::Call(ref call) if pos != ExprPos::Lhs => { let maybe_expr = frontend.function_or_constructor_call( diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index c565b3464..10c964b5e 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -34,7 +34,7 @@ impl Frontend { ScalarKind::Uint => ScalarValue::Uint(value), ScalarKind::Sint => ScalarValue::Sint(value as i64), ScalarKind::Float => ScalarValue::Float(value as f64), - _ => unreachable!(), + ScalarKind::Bool => unreachable!(), }; self.module.constants.fetch_or_append( @@ -1323,7 +1323,7 @@ impl Frontend { } => { let mut location = match binding { crate::Binding::Location { location, .. } => location, - _ => return, + crate::Binding::BuiltIn(_) => return, }; // TODO: Better error reporting @@ -1372,7 +1372,7 @@ impl Frontend { TypeInner::Struct { ref members, .. } => { let mut location = match binding { crate::Binding::Location { location, .. } => location, - _ => return, + crate::Binding::BuiltIn(_) => return, }; for (i, member) in members.iter().enumerate() { diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index ebcfc2fec..ed139e799 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -148,7 +148,7 @@ impl<'source> ParsingContext<'source> { kind: ErrorKind::PreprocessorError(error), meta: res.meta, }), - _ => unreachable!(), + LexerResultKind::Token(_) => unreachable!(), } } } diff --git a/src/lib.rs b/src/lib.rs index f072d5938..259a529a4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -200,7 +200,8 @@ tree. unused_qualifications, clippy::pattern_type_mismatch, clippy::missing_const_for_fn, - clippy::rest_pat_in_fully_bound_structs + clippy::rest_pat_in_fully_bound_structs, + clippy::match_wildcard_for_single_variants )] #![cfg_attr(not(test), deny(clippy::panic))] diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 7ba60515c..13dbd7576 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -305,7 +305,7 @@ impl VaryingContext<'_> { let needs_interpolation = match self.stage { crate::ShaderStage::Vertex => self.output, crate::ShaderStage::Fragment => !self.output, - _ => false, + crate::ShaderStage::Compute => false, }; // It doesn't make sense to specify a sampling when `interpolation` is `Flat`, but From 6fcd04ec0644ab01475b59717fd0f2c5e7cafa95 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 15 Mar 2023 19:02:00 +0100 Subject: [PATCH 1960/2212] run clippy on MSRV + tweak to get CI to run again --- .github/workflows/ci.yml | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cdc19f3b2..ce951216b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,7 +15,7 @@ jobs: - uses: actions/checkout@v3 - name: Install MSRV toolchain - run: rustup toolchain install $MSRV --no-self-update --profile=minimal + run: rustup toolchain install $MSRV --no-self-update --profile=minimal --component clippy - name: Install nightly toolchain run: rustup toolchain install nightly --no-self-update --profile=minimal @@ -29,7 +29,7 @@ jobs: - run: cargo +nightly hack generate-lockfile --remove-dev-deps -Z minimal-versions --offline - name: Test all features - run: cargo +$MSRV check --all-features --workspace + run: cargo +$MSRV clippy --all-features --workspace -- -D warnings test: name: Test @@ -75,16 +75,6 @@ jobs: cd fuzz cargo check - clippy: - name: Clippy - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - run: rustup component add clippy - - - run: cargo clippy --all-features --workspace -- -D warnings - documentation: name: Documentation runs-on: ubuntu-latest From 6db8da72ca5063612face3b5f79805392b68c9df Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Thu, 16 Mar 2023 19:15:44 -0400 Subject: [PATCH 1961/2212] Add partial derivative builtins (#2277) * Add partial derivative builtins * [dot] emit derivative control * Fix fmt --------- Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> --- src/back/dot/mod.rs | 4 +- src/back/glsl/mod.rs | 36 ++++++--- src/back/hlsl/writer.rs | 46 ++++++++--- src/back/msl/writer.rs | 9 ++- src/back/spv/block.rs | 28 +++++-- src/back/wgsl/writer.rs | 19 +++-- src/front/glsl/builtins.rs | 30 +++---- src/front/spv/mod.rs | 80 ++++++++++++++++--- src/front/wgsl/lower/mod.rs | 4 +- src/front/wgsl/parse/conv.rs | 15 +++- src/lib.rs | 12 +++ src/proc/typifier.rs | 2 +- src/valid/analyzer.rs | 1 + src/valid/expression.rs | 2 +- src/valid/handles.rs | 5 +- tests/in/standard.wgsl | 15 +++- .../glsl/standard.derivatives.Fragment.glsl | 29 ++++++- tests/out/hlsl/standard.hlsl | 30 ++++++- tests/out/msl/standard.msl | 29 ++++++- tests/out/spv/standard.spvasm | 68 +++++++++++----- tests/out/wgsl/standard.wgsl | 30 ++++++- 21 files changed, 377 insertions(+), 117 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 4799012ab..1167357e8 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -505,9 +505,9 @@ fn write_function_expressions( edges.insert("reject", reject); ("Select".into(), 3) } - E::Derivative { axis, expr } => { + E::Derivative { axis, ctrl, expr } => { edges.insert("", expr); - (format!("d{axis:?}").into(), 8) + (format!("d{axis:?}{ctrl:?}").into(), 8) } E::Relational { fun, argument } => { edges.insert("arg", argument); diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 20c3f7930..44685fb99 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -185,6 +185,10 @@ impl Version { fn supports_integer_functions(&self) -> bool { *self >= Version::Desktop(400) || *self >= Version::new_gles(310) } + + fn supports_derivative_control(&self) -> bool { + *self >= Version::Desktop(450) + } } impl PartialOrd for Version { @@ -2812,18 +2816,28 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")? } // `Derivative` is a function call to a glsl provided function - Expression::Derivative { axis, expr } => { - use crate::DerivativeAxis as Da; - - write!( - self.out, - "{}(", - match axis { - Da::X => "dFdx", - Da::Y => "dFdy", - Da::Width => "fwidth", + Expression::Derivative { axis, ctrl, expr } => { + use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl}; + let fun_name = if self.options.version.supports_derivative_control() { + match (axis, ctrl) { + (Axis::X, Ctrl::Coarse) => "dFdxCoarse", + (Axis::X, Ctrl::Fine) => "dFdxFine", + (Axis::X, Ctrl::None) => "dFdx", + (Axis::Y, Ctrl::Coarse) => "dFdyCoarse", + (Axis::Y, Ctrl::Fine) => "dFdyFine", + (Axis::Y, Ctrl::None) => "dFdy", + (Axis::Width, Ctrl::Coarse) => "fwidthCoarse", + (Axis::Width, Ctrl::Fine) => "fwidthFine", + (Axis::Width, Ctrl::None) => "fwidth", } - )?; + } else { + match axis { + Axis::X => "dFdx", + Axis::Y => "dFdy", + Axis::Width => "fwidth", + } + }; + write!(self.out, "{fun_name}(")?; self.write_expr(expr, ctx)?; write!(self.out, ")")? } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 1f0491c58..d11032bbf 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -133,6 +133,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { _ => {} } } + + if let Expression::Derivative { axis, ctrl, expr } = *expr { + use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl}; + if axis == Axis::Width && (ctrl == Ctrl::Coarse || ctrl == Ctrl::Fine) { + self.need_bake_expressions.insert(expr); + } + } } } @@ -2801,17 +2808,34 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; write!(self.out, "({var_name}) - {offset}) / {stride})")? } - Expression::Derivative { axis, expr } => { - use crate::DerivativeAxis as Da; - - let fun_str = match axis { - Da::X => "ddx", - Da::Y => "ddy", - Da::Width => "fwidth", - }; - write!(self.out, "{fun_str}(")?; - self.write_expr(module, expr, func_ctx)?; - write!(self.out, ")")? + Expression::Derivative { axis, ctrl, expr } => { + use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl}; + if axis == Axis::Width && (ctrl == Ctrl::Coarse || ctrl == Ctrl::Fine) { + let tail = match ctrl { + Ctrl::Coarse => "coarse", + Ctrl::Fine => "fine", + Ctrl::None => unreachable!(), + }; + write!(self.out, "abs(ddx_{tail}(")?; + self.write_expr(module, expr, func_ctx)?; + write!(self.out, ")) + abs(ddy_{tail}(")?; + self.write_expr(module, expr, func_ctx)?; + write!(self.out, "))")? + } else { + let fun_str = match (axis, ctrl) { + (Axis::X, Ctrl::Coarse) => "ddx_coarse", + (Axis::X, Ctrl::Fine) => "ddx_fine", + (Axis::X, Ctrl::None) => "ddx", + (Axis::Y, Ctrl::Coarse) => "ddy_coarse", + (Axis::Y, Ctrl::Fine) => "ddy_fine", + (Axis::Y, Ctrl::None) => "ddy", + (Axis::Width, Ctrl::Coarse | Ctrl::Fine) => unreachable!(), + (Axis::Width, Ctrl::None) => "fwidth", + }; + write!(self.out, "{fun_str}(")?; + self.write_expr(module, expr, func_ctx)?; + write!(self.out, ")")? + } } Expression::Relational { fun, argument } => { use crate::RelationalFunction as Rf; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index bac178729..ee23ca294 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1579,11 +1579,12 @@ impl Writer { } _ => return Err(Error::Validation), }, - crate::Expression::Derivative { axis, expr } => { + crate::Expression::Derivative { axis, expr, .. } => { + use crate::DerivativeAxis as Axis; let op = match axis { - crate::DerivativeAxis::X => "dfdx", - crate::DerivativeAxis::Y => "dfdy", - crate::DerivativeAxis::Width => "fwidth", + Axis::X => "dfdx", + Axis::Y => "dfdy", + Axis::Width => "fwidth", }; write!(self.out, "{NAMESPACE}::{op}")?; self.put_call_parameters(iter::once(expr), context)?; diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index ccf597917..c3fa8455e 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1334,15 +1334,29 @@ impl<'w> BlockContext<'w> { block.body.push(instruction); id } - crate::Expression::Derivative { axis, expr } => { - use crate::DerivativeAxis as Da; - + crate::Expression::Derivative { axis, ctrl, expr } => { + use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl}; + match ctrl { + Ctrl::Coarse | Ctrl::Fine => { + self.writer.require_any( + "DerivativeControl", + &[spirv::Capability::DerivativeControl], + )?; + } + Ctrl::None => {} + } let id = self.gen_id(); let expr_id = self.cached[expr]; - let op = match axis { - Da::X => spirv::Op::DPdx, - Da::Y => spirv::Op::DPdy, - Da::Width => spirv::Op::Fwidth, + let op = match (axis, ctrl) { + (Axis::X, Ctrl::Coarse) => spirv::Op::DPdxCoarse, + (Axis::X, Ctrl::Fine) => spirv::Op::DPdxFine, + (Axis::X, Ctrl::None) => spirv::Op::DPdx, + (Axis::Y, Ctrl::Coarse) => spirv::Op::DPdyCoarse, + (Axis::Y, Ctrl::Fine) => spirv::Op::DPdyFine, + (Axis::Y, Ctrl::None) => spirv::Op::DPdy, + (Axis::Width, Ctrl::Coarse) => spirv::Op::FwidthCoarse, + (Axis::Width, Ctrl::Fine) => spirv::Op::FwidthFine, + (Axis::Width, Ctrl::None) => spirv::Op::Fwidth, }; block .body diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 7bfb0e964..f24f4a9c2 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1590,13 +1590,18 @@ impl Writer { self.write_expr(module, condition, func_ctx)?; write!(self.out, ")")? } - Expression::Derivative { axis, expr } => { - use crate::DerivativeAxis as Da; - - let op = match axis { - Da::X => "dpdx", - Da::Y => "dpdy", - Da::Width => "fwidth", + Expression::Derivative { axis, ctrl, expr } => { + use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl}; + let op = match (axis, ctrl) { + (Axis::X, Ctrl::Coarse) => "dpdxCoarse", + (Axis::X, Ctrl::Fine) => "dpdxFine", + (Axis::X, Ctrl::None) => "dpdx", + (Axis::Y, Ctrl::Coarse) => "dpdyCoarse", + (Axis::Y, Ctrl::Fine) => "dpdyFine", + (Axis::Y, Ctrl::None) => "dpdy", + (Axis::Width, Ctrl::Coarse) => "fwidthCoarse", + (Axis::Width, Ctrl::Fine) => "fwidthFine", + (Axis::Width, Ctrl::None) => "fwidth", }; write!(self.out, "{op}(")?; self.write_expr(module, expr, func_ctx)?; diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 387ecf012..14e223d6a 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -7,9 +7,10 @@ use super::{ Error, ErrorKind, Frontend, Result, }; use crate::{ - BinaryOperator, Block, Constant, DerivativeAxis, Expression, Handle, ImageClass, - ImageDimension as Dim, ImageQuery, MathFunction, Module, RelationalFunction, SampleLevel, - ScalarKind as Sk, Span, Type, TypeInner, UnaryOperator, VectorSize, + BinaryOperator, Block, Constant, DerivativeAxis as Axis, DerivativeControl as Ctrl, Expression, + Handle, ImageClass, ImageDimension as Dim, ImageQuery, MathFunction, Module, + RelationalFunction, SampleLevel, ScalarKind as Sk, Span, Type, TypeInner, UnaryOperator, + VectorSize, }; impl crate::ScalarKind { @@ -571,15 +572,15 @@ fn inject_standard_builtins( "degrees" => MacroCall::MathFunction(MathFunction::Degrees), "floatBitsToInt" => MacroCall::BitCast(Sk::Sint), "floatBitsToUint" => MacroCall::BitCast(Sk::Uint), - "dFdx" | "dFdxFine" | "dFdxCoarse" => { - MacroCall::Derivate(DerivativeAxis::X) - } - "dFdy" | "dFdyFine" | "dFdyCoarse" => { - MacroCall::Derivate(DerivativeAxis::Y) - } - "fwidth" | "fwidthFine" | "fwidthCoarse" => { - MacroCall::Derivate(DerivativeAxis::Width) - } + "dFdxCoarse" => MacroCall::Derivate(Axis::X, Ctrl::Coarse), + "dFdyCoarse" => MacroCall::Derivate(Axis::Y, Ctrl::Coarse), + "fwidthCoarse" => MacroCall::Derivate(Axis::Width, Ctrl::Coarse), + "dFdxFine" => MacroCall::Derivate(Axis::X, Ctrl::Fine), + "dFdyFine" => MacroCall::Derivate(Axis::Y, Ctrl::Fine), + "fwidthFine" => MacroCall::Derivate(Axis::Width, Ctrl::Fine), + "dFdx" => MacroCall::Derivate(Axis::X, Ctrl::None), + "dFdy" => MacroCall::Derivate(Axis::Y, Ctrl::None), + "fwidth" => MacroCall::Derivate(Axis::Width, Ctrl::None), _ => unreachable!(), }, )) @@ -1661,7 +1662,7 @@ pub enum MacroCall { MixBoolean, Clamp(Option), BitCast(Sk), - Derivate(DerivativeAxis), + Derivate(Axis, Ctrl), Barrier, /// SmoothStep needs a separate variant because it might need it's inputs /// to be splatted depending on the overload @@ -2143,9 +2144,10 @@ impl MacroCall { Span::default(), body, ), - MacroCall::Derivate(axis) => ctx.add_expression( + MacroCall::Derivate(axis, ctrl) => ctx.add_expression( Expression::Derivative { axis, + ctrl, expr: args[0], }, Span::default(), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 82a86a36a..ce42be35b 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1129,7 +1129,7 @@ impl> Frontend { block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, - axis: crate::DerivativeAxis, + (axis, ctrl): (crate::DerivativeAxis, crate::DerivativeControl), ) -> Result<(), Error> { let start = self.data_offset; let result_type_id = self.next()?; @@ -1141,6 +1141,7 @@ impl> Frontend { let expr = crate::Expression::Derivative { axis, + ctrl, expr: arg_handle, }; self.lookup_expression.insert( @@ -1294,8 +1295,15 @@ impl> Frontend { ($op:expr, UNARY) => { self.parse_expr_unary_op(ctx, &mut emitter, &mut block, block_id, body_idx, $op) }; - ($axis:expr, DERIVATIVE) => { - self.parse_expr_derivative(ctx, &mut emitter, &mut block, block_id, body_idx, $axis) + ($axis:expr, $ctrl:expr, DERIVATIVE) => { + self.parse_expr_derivative( + ctx, + &mut emitter, + &mut block, + block_id, + body_idx, + ($axis, $ctrl), + ) }; } @@ -3346,14 +3354,68 @@ impl> Frontend { }); body_idx = loop_body_idx; } - Op::DPdx | Op::DPdxFine | Op::DPdxCoarse => { - parse_expr_op!(crate::DerivativeAxis::X, DERIVATIVE)?; + Op::DPdxCoarse => { + parse_expr_op!( + crate::DerivativeAxis::X, + crate::DerivativeControl::Coarse, + DERIVATIVE + )?; } - Op::DPdy | Op::DPdyFine | Op::DPdyCoarse => { - parse_expr_op!(crate::DerivativeAxis::Y, DERIVATIVE)?; + Op::DPdyCoarse => { + parse_expr_op!( + crate::DerivativeAxis::Y, + crate::DerivativeControl::Coarse, + DERIVATIVE + )?; } - Op::Fwidth | Op::FwidthFine | Op::FwidthCoarse => { - parse_expr_op!(crate::DerivativeAxis::Width, DERIVATIVE)?; + Op::FwidthCoarse => { + parse_expr_op!( + crate::DerivativeAxis::Width, + crate::DerivativeControl::Coarse, + DERIVATIVE + )?; + } + Op::DPdxFine => { + parse_expr_op!( + crate::DerivativeAxis::X, + crate::DerivativeControl::Fine, + DERIVATIVE + )?; + } + Op::DPdyFine => { + parse_expr_op!( + crate::DerivativeAxis::Y, + crate::DerivativeControl::Fine, + DERIVATIVE + )?; + } + Op::FwidthFine => { + parse_expr_op!( + crate::DerivativeAxis::Width, + crate::DerivativeControl::Fine, + DERIVATIVE + )?; + } + Op::DPdx => { + parse_expr_op!( + crate::DerivativeAxis::X, + crate::DerivativeControl::None, + DERIVATIVE + )?; + } + Op::DPdy => { + parse_expr_op!( + crate::DerivativeAxis::Y, + crate::DerivativeControl::None, + DERIVATIVE + )?; + } + Op::Fwidth => { + parse_expr_op!( + crate::DerivativeAxis::Width, + crate::DerivativeControl::None, + DERIVATIVE + )?; } Op::ArrayLength => { inst.expect(5)?; diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 01a46f28c..f3b157caa 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1572,12 +1572,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args.finish()?; crate::Expression::Relational { fun, argument } - } else if let Some(axis) = conv::map_derivative_axis(function.name) { + } else if let Some((axis, ctrl)) = conv::map_derivative(function.name) { let mut args = ctx.prepare_args(arguments, 1, span); let expr = self.expression(args.next()?, ctx.reborrow())?; args.finish()?; - crate::Expression::Derivative { axis, expr } + crate::Expression::Derivative { axis, ctrl, expr } } else if let Some(fun) = conv::map_standard_fun(function.name) { let expected = fun.argument_count() as _; let mut args = ctx.prepare_args(arguments, expected, span); diff --git a/src/front/wgsl/parse/conv.rs b/src/front/wgsl/parse/conv.rs index 0e20774dc..a69dbbe47 100644 --- a/src/front/wgsl/parse/conv.rs +++ b/src/front/wgsl/parse/conv.rs @@ -113,11 +113,18 @@ pub fn get_scalar_type(word: &str) -> Option<(crate::ScalarKind, crate::Bytes)> } } -pub fn map_derivative_axis(word: &str) -> Option { +pub fn map_derivative(word: &str) -> Option<(crate::DerivativeAxis, crate::DerivativeControl)> { + use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl}; match word { - "dpdx" => Some(crate::DerivativeAxis::X), - "dpdy" => Some(crate::DerivativeAxis::Y), - "fwidth" => Some(crate::DerivativeAxis::Width), + "dpdxCoarse" => Some((Axis::X, Ctrl::Coarse)), + "dpdyCoarse" => Some((Axis::Y, Ctrl::Coarse)), + "fwidthCoarse" => Some((Axis::Width, Ctrl::Coarse)), + "dpdxFine" => Some((Axis::X, Ctrl::Fine)), + "dpdyFine" => Some((Axis::Y, Ctrl::Fine)), + "fwidthFine" => Some((Axis::Width, Ctrl::Fine)), + "dpdx" => Some((Axis::X, Ctrl::None)), + "dpdy" => Some((Axis::Y, Ctrl::None)), + "fwidth" => Some((Axis::Width, Ctrl::None)), _ => None, } } diff --git a/src/lib.rs b/src/lib.rs index 259a529a4..c1b48b899 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -977,6 +977,17 @@ pub enum AtomicFunction { Exchange { compare: Option> }, } +/// Hint at which precision to compute a derivative. +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +pub enum DerivativeControl { + Coarse, + Fine, + None, +} + /// Axis on which to compute a derivative. #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -1388,6 +1399,7 @@ pub enum Expression { /// Compute the derivative on an axis. Derivative { axis: DerivativeAxis, + ctrl: DerivativeControl, //modifier, expr: Handle, }, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 3b9fa1d50..b9ac46831 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -635,7 +635,7 @@ impl<'a> ResolveContext<'a> { }, crate::Expression::AtomicResult { ty, .. } => TypeResolution::Handle(ty), crate::Expression::Select { accept, .. } => past(accept)?.clone(), - crate::Expression::Derivative { axis: _, expr } => past(expr)?.clone(), + crate::Expression::Derivative { expr, .. } => past(expr)?.clone(), crate::Expression::Relational { fun, argument } => match fun { crate::RelationalFunction::All | crate::RelationalFunction::Any => { TypeResolution::Value(Ti::Scalar { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 30fb32d07..40d5f95c1 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -1015,6 +1015,7 @@ fn uniform_control_flow() { let derivative_expr = expressions.append( E::Derivative { axis: crate::DerivativeAxis::X, + ctrl: crate::DerivativeControl::None, expr: constant_expr, }, Default::default(), diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 01d6910eb..af080fc18 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -832,7 +832,7 @@ impl super::Validator { } ShaderStages::all() } - E::Derivative { axis: _, expr } => { + E::Derivative { expr, .. } => { match resolver[expr] { Ti::Scalar { kind: Sk::Float, .. diff --git a/src/valid/handles.rs b/src/valid/handles.rs index be87e54d4..e3f9fe253 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -345,10 +345,7 @@ impl super::Validator { .check_dep(accept)? .check_dep(reject)?; } - crate::Expression::Derivative { - axis: _, - expr: argument, - } => { + crate::Expression::Derivative { expr: argument, .. } => { handle.check_dep(argument)?; } crate::Expression::Relational { fun: _, argument } => { diff --git a/tests/in/standard.wgsl b/tests/in/standard.wgsl index 5b40b683a..79f5632ce 100644 --- a/tests/in/standard.wgsl +++ b/tests/in/standard.wgsl @@ -2,8 +2,17 @@ @fragment fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { - let x = dpdx(foo); - let y = dpdy(foo); - let z = fwidth(foo); + var x = dpdxCoarse(foo); + var y = dpdyCoarse(foo); + var z = fwidthCoarse(foo); + + x = dpdxFine(foo); + y = dpdyFine(foo); + z = fwidthFine(foo); + + x = dpdx(foo); + y = dpdy(foo); + z = fwidth(foo); + return (x + y) * z; } diff --git a/tests/out/glsl/standard.derivatives.Fragment.glsl b/tests/out/glsl/standard.derivatives.Fragment.glsl index 4a084add1..331ffb5c0 100644 --- a/tests/out/glsl/standard.derivatives.Fragment.glsl +++ b/tests/out/glsl/standard.derivatives.Fragment.glsl @@ -7,10 +7,31 @@ layout(location = 0) out vec4 _fs2p_location0; void main() { vec4 foo = gl_FragCoord; - vec4 x = dFdx(foo); - vec4 y = dFdy(foo); - vec4 z = fwidth(foo); - _fs2p_location0 = ((x + y) * z); + vec4 x = vec4(0.0); + vec4 y = vec4(0.0); + vec4 z = vec4(0.0); + vec4 _e1 = dFdx(foo); + x = _e1; + vec4 _e3 = dFdy(foo); + y = _e3; + vec4 _e5 = fwidth(foo); + z = _e5; + vec4 _e7 = dFdx(foo); + x = _e7; + vec4 _e8 = dFdy(foo); + y = _e8; + vec4 _e9 = fwidth(foo); + z = _e9; + vec4 _e10 = dFdx(foo); + x = _e10; + vec4 _e11 = dFdy(foo); + y = _e11; + vec4 _e12 = fwidth(foo); + z = _e12; + vec4 _e13 = x; + vec4 _e14 = y; + vec4 _e16 = z; + _fs2p_location0 = ((_e13 + _e14) * _e16); return; } diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl index e4077b5f0..aacb25012 100644 --- a/tests/out/hlsl/standard.hlsl +++ b/tests/out/hlsl/standard.hlsl @@ -6,8 +6,30 @@ struct FragmentInput_derivatives { float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Target0 { float4 foo = fragmentinput_derivatives.foo_1; - float4 x = ddx(foo); - float4 y = ddy(foo); - float4 z = fwidth(foo); - return ((x + y) * z); + float4 x = (float4)0; + float4 y = (float4)0; + float4 z = (float4)0; + + float4 _expr1 = ddx_coarse(foo); + x = _expr1; + float4 _expr3 = ddy_coarse(foo); + y = _expr3; + float4 _expr5 = abs(ddx_coarse(foo)) + abs(ddy_coarse(foo)); + z = _expr5; + float4 _expr7 = ddx_fine(foo); + x = _expr7; + float4 _expr8 = ddy_fine(foo); + y = _expr8; + float4 _expr9 = abs(ddx_fine(foo)) + abs(ddy_fine(foo)); + z = _expr9; + float4 _expr10 = ddx(foo); + x = _expr10; + float4 _expr11 = ddy(foo); + y = _expr11; + float4 _expr12 = fwidth(foo); + z = _expr12; + float4 _expr13 = x; + float4 _expr14 = y; + float4 _expr16 = z; + return ((_expr13 + _expr14) * _expr16); } diff --git a/tests/out/msl/standard.msl b/tests/out/msl/standard.msl index d21930c06..bca5f0cb0 100644 --- a/tests/out/msl/standard.msl +++ b/tests/out/msl/standard.msl @@ -13,8 +13,29 @@ struct derivativesOutput { fragment derivativesOutput derivatives( metal::float4 foo [[position]] ) { - metal::float4 x = metal::dfdx(foo); - metal::float4 y = metal::dfdy(foo); - metal::float4 z = metal::fwidth(foo); - return derivativesOutput { (x + y) * z }; + metal::float4 x = {}; + metal::float4 y = {}; + metal::float4 z = {}; + metal::float4 _e1 = metal::dfdx(foo); + x = _e1; + metal::float4 _e3 = metal::dfdy(foo); + y = _e3; + metal::float4 _e5 = metal::fwidth(foo); + z = _e5; + metal::float4 _e7 = metal::dfdx(foo); + x = _e7; + metal::float4 _e8 = metal::dfdy(foo); + y = _e8; + metal::float4 _e9 = metal::fwidth(foo); + z = _e9; + metal::float4 _e10 = metal::dfdx(foo); + x = _e10; + metal::float4 _e11 = metal::dfdy(foo); + y = _e11; + metal::float4 _e12 = metal::fwidth(foo); + z = _e12; + metal::float4 _e13 = x; + metal::float4 _e14 = y; + metal::float4 _e16 = z; + return derivativesOutput { (_e13 + _e14) * _e16 }; } diff --git a/tests/out/spv/standard.spvasm b/tests/out/spv/standard.spvasm index ef0bac6c9..518be0a22 100644 --- a/tests/out/spv/standard.spvasm +++ b/tests/out/spv/standard.spvasm @@ -1,32 +1,58 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 19 +; Bound: 35 OpCapability Shader +OpCapability DerivativeControl %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %11 "derivatives" %6 %9 -OpExecutionMode %11 OriginUpperLeft -OpDecorate %6 BuiltIn FragCoord -OpDecorate %9 Location 0 +OpEntryPoint Fragment %18 "derivatives" %13 %16 +OpExecutionMode %18 OriginUpperLeft +OpDecorate %13 BuiltIn FragCoord +OpDecorate %16 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 -%7 = OpTypePointer Input %3 -%6 = OpVariable %7 Input -%10 = OpTypePointer Output %3 -%9 = OpVariable %10 Output -%12 = OpTypeFunction %2 -%11 = OpFunction %2 None %12 -%5 = OpLabel -%8 = OpLoad %3 %6 -OpBranch %13 -%13 = OpLabel -%14 = OpDPdx %3 %8 -%15 = OpDPdy %3 %8 -%16 = OpFwidth %3 %8 -%17 = OpFAdd %3 %14 %15 -%18 = OpFMul %3 %17 %16 -OpStore %9 %18 +%6 = OpTypePointer Function %3 +%7 = OpConstantNull %3 +%9 = OpConstantNull %3 +%11 = OpConstantNull %3 +%14 = OpTypePointer Input %3 +%13 = OpVariable %14 Input +%17 = OpTypePointer Output %3 +%16 = OpVariable %17 Output +%19 = OpTypeFunction %2 +%18 = OpFunction %2 None %19 +%12 = OpLabel +%5 = OpVariable %6 Function %7 +%8 = OpVariable %6 Function %9 +%10 = OpVariable %6 Function %11 +%15 = OpLoad %3 %13 +OpBranch %20 +%20 = OpLabel +%21 = OpDPdxCoarse %3 %15 +OpStore %5 %21 +%22 = OpDPdyCoarse %3 %15 +OpStore %8 %22 +%23 = OpFwidthCoarse %3 %15 +OpStore %10 %23 +%24 = OpDPdxFine %3 %15 +OpStore %5 %24 +%25 = OpDPdyFine %3 %15 +OpStore %8 %25 +%26 = OpFwidthFine %3 %15 +OpStore %10 %26 +%27 = OpDPdx %3 %15 +OpStore %5 %27 +%28 = OpDPdy %3 %15 +OpStore %8 %28 +%29 = OpFwidth %3 %15 +OpStore %10 %29 +%30 = OpLoad %3 %5 +%31 = OpLoad %3 %8 +%32 = OpFAdd %3 %30 %31 +%33 = OpLoad %3 %10 +%34 = OpFMul %3 %32 %33 +OpStore %16 %34 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/standard.wgsl b/tests/out/wgsl/standard.wgsl index a121d6f9a..80e8f2498 100644 --- a/tests/out/wgsl/standard.wgsl +++ b/tests/out/wgsl/standard.wgsl @@ -1,7 +1,29 @@ @fragment fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { - let x = dpdx(foo); - let y = dpdy(foo); - let z = fwidth(foo); - return ((x + y) * z); + var x: vec4; + var y: vec4; + var z: vec4; + + let _e1 = dpdxCoarse(foo); + x = _e1; + let _e3 = dpdyCoarse(foo); + y = _e3; + let _e5 = fwidthCoarse(foo); + z = _e5; + let _e7 = dpdxFine(foo); + x = _e7; + let _e8 = dpdyFine(foo); + y = _e8; + let _e9 = fwidthFine(foo); + z = _e9; + let _e10 = dpdx(foo); + x = _e10; + let _e11 = dpdy(foo); + y = _e11; + let _e12 = fwidth(foo); + z = _e12; + let _e13 = x; + let _e14 = y; + let _e16 = z; + return ((_e13 + _e14) * _e16); } From 67c081bebe7a27a98103ddb7b5af34863c593616 Mon Sep 17 00:00:00 2001 From: Andreas Reich Date: Mon, 20 Mar 2023 13:43:13 +0100 Subject: [PATCH 1962/2212] [spirv-out] Fix adding illegal decorators on fragment outputs. (#2286) * [spirv-out] Fix adding illegal decorators on fragment outputs. Furthermore, fix allowing to add `Centroid` and `Sample` decorator to vertex inputs. Fixes #2270 * Add test for fragment outputs * Fix fragment-output.wgsl test using more than 8 outputs in a single shader Breaks HLSL & MSL validation * formatting --- src/back/spv/writer.rs | 44 +++-- tests/in/fragment-output.wgsl | 41 +++++ .../glsl/fragment-output.main.Fragment.glsl | 62 +++++++ ...gment-output.main_vec2scalar.Fragment.glsl | 46 +++++ ...ragment-output.main_vec4vec3.Fragment.glsl | 46 +++++ tests/out/hlsl/fragment-output.hlsl | 48 +++++ tests/out/hlsl/fragment-output.hlsl.config | 3 + tests/out/msl/fragment-output.msl | 67 +++++++ tests/out/spv/fragment-output.spvasm | 172 ++++++++++++++++++ tests/out/wgsl/fragment-output.wgsl | 45 +++++ tests/snapshots.rs | 4 + 11 files changed, 558 insertions(+), 20 deletions(-) create mode 100644 tests/in/fragment-output.wgsl create mode 100644 tests/out/glsl/fragment-output.main.Fragment.glsl create mode 100644 tests/out/glsl/fragment-output.main_vec2scalar.Fragment.glsl create mode 100644 tests/out/glsl/fragment-output.main_vec4vec3.Fragment.glsl create mode 100644 tests/out/hlsl/fragment-output.hlsl create mode 100644 tests/out/hlsl/fragment-output.hlsl.config create mode 100644 tests/out/msl/fragment-output.msl create mode 100644 tests/out/spv/fragment-output.spvasm create mode 100644 tests/out/wgsl/fragment-output.wgsl diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e1a8d6976..f264c107d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1407,12 +1407,17 @@ impl Writer { } => { self.decorate(id, Decoration::Location, &[location]); - // The Vulkan spec says: VUID-StandaloneSpirv-Flat-06202 - // - // > The Flat, NoPerspective, Sample, and Centroid decorations - // > must not be used on variables with the Input storage class in - // > a vertex shader - if class != spirv::StorageClass::Input || stage != crate::ShaderStage::Vertex { + let no_decorations = + // VUID-StandaloneSpirv-Flat-06202 + // > The Flat, NoPerspective, Sample, and Centroid decorations + // > must not be used on variables with the Input storage class in a vertex shader + (class == spirv::StorageClass::Input && stage == crate::ShaderStage::Vertex) || + // VUID-StandaloneSpirv-Flat-06201 + // > The Flat, NoPerspective, Sample, and Centroid decorations + // > must not be used on variables with the Output storage class in a fragment shader + (class == spirv::StorageClass::Output && stage == crate::ShaderStage::Fragment); + + if !no_decorations { match interpolation { // Perspective-correct interpolation is the default in SPIR-V. None | Some(crate::Interpolation::Perspective) => (), @@ -1423,20 +1428,19 @@ impl Writer { self.decorate(id, Decoration::NoPerspective, &[]); } } - } - - match sampling { - // Center sampling is the default in SPIR-V. - None | Some(crate::Sampling::Center) => (), - Some(crate::Sampling::Centroid) => { - self.decorate(id, Decoration::Centroid, &[]); - } - Some(crate::Sampling::Sample) => { - self.require_any( - "per-sample interpolation", - &[spirv::Capability::SampleRateShading], - )?; - self.decorate(id, Decoration::Sample, &[]); + match sampling { + // Center sampling is the default in SPIR-V. + None | Some(crate::Sampling::Center) => (), + Some(crate::Sampling::Centroid) => { + self.decorate(id, Decoration::Centroid, &[]); + } + Some(crate::Sampling::Sample) => { + self.require_any( + "per-sample interpolation", + &[spirv::Capability::SampleRateShading], + )?; + self.decorate(id, Decoration::Sample, &[]); + } } } } diff --git a/tests/in/fragment-output.wgsl b/tests/in/fragment-output.wgsl new file mode 100644 index 000000000..d2d75e789 --- /dev/null +++ b/tests/in/fragment-output.wgsl @@ -0,0 +1,41 @@ +// Split up because some output languages limit number of locations to 8. +struct FragmentOutputVec4Vec3 { + @location(0) vec4f: vec4, + @location(1) vec4i: vec4, + @location(2) vec4u: vec4, + @location(3) vec3f: vec3, + @location(4) vec3i: vec3, + @location(5) vec3u: vec3, +} +@fragment +fn main_vec4vec3() -> FragmentOutputVec4Vec3 { + var output: FragmentOutputVec4Vec3; + output.vec4f = vec4(0.0); + output.vec4i = vec4(0); + output.vec4u = vec4(0u); + output.vec3f = vec3(0.0); + output.vec3i = vec3(0); + output.vec3u = vec3(0u); + return output; +} + +struct FragmentOutputVec2Scalar { + @location(0) vec2f: vec2, + @location(1) vec2i: vec2, + @location(2) vec2u: vec2, + @location(3) scalarf: f32, + @location(4) scalari: i32, + @location(5) scalaru: u32, +} + +@fragment +fn main_vec2scalar() -> FragmentOutputVec2Scalar { + var output: FragmentOutputVec2Scalar; + output.vec2f = vec2(0.0); + output.vec2i = vec2(0); + output.vec2u = vec2(0u); + output.scalarf = 0.0; + output.scalari = 0; + output.scalaru = 0u; + return output; +} diff --git a/tests/out/glsl/fragment-output.main.Fragment.glsl b/tests/out/glsl/fragment-output.main.Fragment.glsl new file mode 100644 index 000000000..f8299e2ba --- /dev/null +++ b/tests/out/glsl/fragment-output.main.Fragment.glsl @@ -0,0 +1,62 @@ +#version 310 es + +precision highp float; +precision highp int; + +struct FragmentOutput { + vec4 vec4f; + ivec4 vec4i; + uvec4 vec4u; + vec3 vec3f; + ivec3 vec3i; + uvec3 vec3u; + vec2 vec2f; + ivec2 vec2i; + uvec2 vec2u; + float scalarf; + int scalari; + uint scalaru; +}; +layout(location = 0) out vec4 _fs2p_location0; +layout(location = 1) out ivec4 _fs2p_location1; +layout(location = 2) out uvec4 _fs2p_location2; +layout(location = 3) out vec3 _fs2p_location3; +layout(location = 4) out ivec3 _fs2p_location4; +layout(location = 5) out uvec3 _fs2p_location5; +layout(location = 6) out vec2 _fs2p_location6; +layout(location = 7) out ivec2 _fs2p_location7; +layout(location = 8) out uvec2 _fs2p_location8; +layout(location = 9) out float _fs2p_location9; +layout(location = 10) out int _fs2p_location10; +layout(location = 11) out uint _fs2p_location11; + +void main() { + FragmentOutput output_ = FragmentOutput(vec4(0.0), ivec4(0), uvec4(0u), vec3(0.0), ivec3(0), uvec3(0u), vec2(0.0), ivec2(0), uvec2(0u), 0.0, 0, 0u); + output_.vec4f = vec4(0.0); + output_.vec4i = ivec4(0); + output_.vec4u = uvec4(0u); + output_.vec3f = vec3(0.0); + output_.vec3i = ivec3(0); + output_.vec3u = uvec3(0u); + output_.vec2f = vec2(0.0); + output_.vec2i = ivec2(0); + output_.vec2u = uvec2(0u); + output_.scalarf = 0.0; + output_.scalari = 0; + output_.scalaru = 0u; + FragmentOutput _e34 = output_; + _fs2p_location0 = _e34.vec4f; + _fs2p_location1 = _e34.vec4i; + _fs2p_location2 = _e34.vec4u; + _fs2p_location3 = _e34.vec3f; + _fs2p_location4 = _e34.vec3i; + _fs2p_location5 = _e34.vec3u; + _fs2p_location6 = _e34.vec2f; + _fs2p_location7 = _e34.vec2i; + _fs2p_location8 = _e34.vec2u; + _fs2p_location9 = _e34.scalarf; + _fs2p_location10 = _e34.scalari; + _fs2p_location11 = _e34.scalaru; + return; +} + diff --git a/tests/out/glsl/fragment-output.main_vec2scalar.Fragment.glsl b/tests/out/glsl/fragment-output.main_vec2scalar.Fragment.glsl new file mode 100644 index 000000000..c68a89f16 --- /dev/null +++ b/tests/out/glsl/fragment-output.main_vec2scalar.Fragment.glsl @@ -0,0 +1,46 @@ +#version 310 es + +precision highp float; +precision highp int; + +struct FragmentOutputVec4Vec3_ { + vec4 vec4f; + ivec4 vec4i; + uvec4 vec4u; + vec3 vec3f; + ivec3 vec3i; + uvec3 vec3u; +}; +struct FragmentOutputVec2Scalar { + vec2 vec2f; + ivec2 vec2i; + uvec2 vec2u; + float scalarf; + int scalari; + uint scalaru; +}; +layout(location = 0) out vec2 _fs2p_location0; +layout(location = 1) out ivec2 _fs2p_location1; +layout(location = 2) out uvec2 _fs2p_location2; +layout(location = 3) out float _fs2p_location3; +layout(location = 4) out int _fs2p_location4; +layout(location = 5) out uint _fs2p_location5; + +void main() { + FragmentOutputVec2Scalar output_1 = FragmentOutputVec2Scalar(vec2(0.0), ivec2(0), uvec2(0u), 0.0, 0, 0u); + output_1.vec2f = vec2(0.0); + output_1.vec2i = ivec2(0); + output_1.vec2u = uvec2(0u); + output_1.scalarf = 0.0; + output_1.scalari = 0; + output_1.scalaru = 0u; + FragmentOutputVec2Scalar _e16 = output_1; + _fs2p_location0 = _e16.vec2f; + _fs2p_location1 = _e16.vec2i; + _fs2p_location2 = _e16.vec2u; + _fs2p_location3 = _e16.scalarf; + _fs2p_location4 = _e16.scalari; + _fs2p_location5 = _e16.scalaru; + return; +} + diff --git a/tests/out/glsl/fragment-output.main_vec4vec3.Fragment.glsl b/tests/out/glsl/fragment-output.main_vec4vec3.Fragment.glsl new file mode 100644 index 000000000..c0398f399 --- /dev/null +++ b/tests/out/glsl/fragment-output.main_vec4vec3.Fragment.glsl @@ -0,0 +1,46 @@ +#version 310 es + +precision highp float; +precision highp int; + +struct FragmentOutputVec4Vec3_ { + vec4 vec4f; + ivec4 vec4i; + uvec4 vec4u; + vec3 vec3f; + ivec3 vec3i; + uvec3 vec3u; +}; +struct FragmentOutputVec2Scalar { + vec2 vec2f; + ivec2 vec2i; + uvec2 vec2u; + float scalarf; + int scalari; + uint scalaru; +}; +layout(location = 0) out vec4 _fs2p_location0; +layout(location = 1) out ivec4 _fs2p_location1; +layout(location = 2) out uvec4 _fs2p_location2; +layout(location = 3) out vec3 _fs2p_location3; +layout(location = 4) out ivec3 _fs2p_location4; +layout(location = 5) out uvec3 _fs2p_location5; + +void main() { + FragmentOutputVec4Vec3_ output_ = FragmentOutputVec4Vec3_(vec4(0.0), ivec4(0), uvec4(0u), vec3(0.0), ivec3(0), uvec3(0u)); + output_.vec4f = vec4(0.0); + output_.vec4i = ivec4(0); + output_.vec4u = uvec4(0u); + output_.vec3f = vec3(0.0); + output_.vec3i = ivec3(0); + output_.vec3u = uvec3(0u); + FragmentOutputVec4Vec3_ _e19 = output_; + _fs2p_location0 = _e19.vec4f; + _fs2p_location1 = _e19.vec4i; + _fs2p_location2 = _e19.vec4u; + _fs2p_location3 = _e19.vec3f; + _fs2p_location4 = _e19.vec3i; + _fs2p_location5 = _e19.vec3u; + return; +} + diff --git a/tests/out/hlsl/fragment-output.hlsl b/tests/out/hlsl/fragment-output.hlsl new file mode 100644 index 000000000..a4ba428a6 --- /dev/null +++ b/tests/out/hlsl/fragment-output.hlsl @@ -0,0 +1,48 @@ + +struct FragmentOutputVec4Vec3_ { + float4 vec4f : SV_Target0; + nointerpolation int4 vec4i : SV_Target1; + nointerpolation uint4 vec4u : SV_Target2; + float3 vec3f : SV_Target3; + nointerpolation int3 vec3i : SV_Target4; + nointerpolation uint3 vec3u : SV_Target5; +}; + +struct FragmentOutputVec2Scalar { + float2 vec2f : SV_Target0; + nointerpolation int2 vec2i : SV_Target1; + nointerpolation uint2 vec2u : SV_Target2; + float scalarf : SV_Target3; + nointerpolation int scalari : SV_Target4; + nointerpolation uint scalaru : SV_Target5; +}; + +FragmentOutputVec4Vec3_ main_vec4vec3_() +{ + FragmentOutputVec4Vec3_ output = (FragmentOutputVec4Vec3_)0; + + output.vec4f = (0.0).xxxx; + output.vec4i = (0).xxxx; + output.vec4u = (0u).xxxx; + output.vec3f = (0.0).xxx; + output.vec3i = (0).xxx; + output.vec3u = (0u).xxx; + FragmentOutputVec4Vec3_ _expr19 = output; + const FragmentOutputVec4Vec3_ fragmentoutputvec4vec3_ = _expr19; + return fragmentoutputvec4vec3_; +} + +FragmentOutputVec2Scalar main_vec2scalar() +{ + FragmentOutputVec2Scalar output_1 = (FragmentOutputVec2Scalar)0; + + output_1.vec2f = (0.0).xx; + output_1.vec2i = (0).xx; + output_1.vec2u = (0u).xx; + output_1.scalarf = 0.0; + output_1.scalari = 0; + output_1.scalaru = 0u; + FragmentOutputVec2Scalar _expr16 = output_1; + const FragmentOutputVec2Scalar fragmentoutputvec2scalar = _expr16; + return fragmentoutputvec2scalar; +} diff --git a/tests/out/hlsl/fragment-output.hlsl.config b/tests/out/hlsl/fragment-output.hlsl.config new file mode 100644 index 000000000..2bf0efbf7 --- /dev/null +++ b/tests/out/hlsl/fragment-output.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=(main_vec4vec3_:ps_5_1 main_vec2scalar:ps_5_1 ) +compute=() diff --git a/tests/out/msl/fragment-output.msl b/tests/out/msl/fragment-output.msl new file mode 100644 index 000000000..4d25809e4 --- /dev/null +++ b/tests/out/msl/fragment-output.msl @@ -0,0 +1,67 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct FragmentOutputVec4Vec3_ { + metal::float4 vec4f; + metal::int4 vec4i; + metal::uint4 vec4u; + metal::float3 vec3f; + metal::int3 vec3i; + metal::uint3 vec3u; +}; +struct FragmentOutputVec2Scalar { + metal::float2 vec2f; + metal::int2 vec2i; + metal::uint2 vec2u; + float scalarf; + int scalari; + uint scalaru; +}; + +struct main_vec4vec3_Output { + metal::float4 vec4f [[color(0)]]; + metal::int4 vec4i [[color(1)]]; + metal::uint4 vec4u [[color(2)]]; + metal::float3 vec3f [[color(3)]]; + metal::int3 vec3i [[color(4)]]; + metal::uint3 vec3u [[color(5)]]; +}; +fragment main_vec4vec3_Output main_vec4vec3_( +) { + FragmentOutputVec4Vec3_ output = {}; + output.vec4f = metal::float4(0.0); + output.vec4i = metal::int4(0); + output.vec4u = metal::uint4(0u); + output.vec3f = metal::float3(0.0); + output.vec3i = metal::int3(0); + output.vec3u = metal::uint3(0u); + FragmentOutputVec4Vec3_ _e19 = output; + const auto _tmp = _e19; + return main_vec4vec3_Output { _tmp.vec4f, _tmp.vec4i, _tmp.vec4u, _tmp.vec3f, _tmp.vec3i, _tmp.vec3u }; +} + + +struct main_vec2scalarOutput { + metal::float2 vec2f [[color(0)]]; + metal::int2 vec2i [[color(1)]]; + metal::uint2 vec2u [[color(2)]]; + float scalarf [[color(3)]]; + int scalari [[color(4)]]; + uint scalaru [[color(5)]]; +}; +fragment main_vec2scalarOutput main_vec2scalar( +) { + FragmentOutputVec2Scalar output_1 = {}; + output_1.vec2f = metal::float2(0.0); + output_1.vec2i = metal::int2(0); + output_1.vec2u = metal::uint2(0u); + output_1.scalarf = 0.0; + output_1.scalari = 0; + output_1.scalaru = 0u; + FragmentOutputVec2Scalar _e16 = output_1; + const auto _tmp = _e16; + return main_vec2scalarOutput { _tmp.vec2f, _tmp.vec2i, _tmp.vec2u, _tmp.scalarf, _tmp.scalari, _tmp.scalaru }; +} diff --git a/tests/out/spv/fragment-output.spvasm b/tests/out/spv/fragment-output.spvasm new file mode 100644 index 000000000..aafc8c2d1 --- /dev/null +++ b/tests/out/spv/fragment-output.spvasm @@ -0,0 +1,172 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 109 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %36 "main_vec4vec3" %24 %26 %28 %30 %32 %34 +OpEntryPoint Fragment %85 "main_vec2scalar" %73 %75 %77 %79 %81 %83 +OpExecutionMode %36 OriginUpperLeft +OpExecutionMode %85 OriginUpperLeft +OpMemberDecorate %15 0 Offset 0 +OpMemberDecorate %15 1 Offset 16 +OpMemberDecorate %15 2 Offset 32 +OpMemberDecorate %15 3 Offset 48 +OpMemberDecorate %15 4 Offset 64 +OpMemberDecorate %15 5 Offset 80 +OpMemberDecorate %19 0 Offset 0 +OpMemberDecorate %19 1 Offset 8 +OpMemberDecorate %19 2 Offset 16 +OpMemberDecorate %19 3 Offset 24 +OpMemberDecorate %19 4 Offset 28 +OpMemberDecorate %19 5 Offset 32 +OpDecorate %24 Location 0 +OpDecorate %26 Location 1 +OpDecorate %28 Location 2 +OpDecorate %30 Location 3 +OpDecorate %32 Location 4 +OpDecorate %34 Location 5 +OpDecorate %73 Location 0 +OpDecorate %75 Location 1 +OpDecorate %77 Location 2 +OpDecorate %79 Location 3 +OpDecorate %81 Location 4 +OpDecorate %83 Location 5 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpConstant %4 0.0 +%6 = OpTypeInt 32 1 +%5 = OpConstant %6 0 +%8 = OpTypeInt 32 0 +%7 = OpConstant %8 0 +%9 = OpTypeVector %4 4 +%10 = OpTypeVector %6 4 +%11 = OpTypeVector %8 4 +%12 = OpTypeVector %4 3 +%13 = OpTypeVector %6 3 +%14 = OpTypeVector %8 3 +%15 = OpTypeStruct %9 %10 %11 %12 %13 %14 +%16 = OpTypeVector %4 2 +%17 = OpTypeVector %6 2 +%18 = OpTypeVector %8 2 +%19 = OpTypeStruct %16 %17 %18 %4 %6 %8 +%21 = OpTypePointer Function %15 +%22 = OpConstantNull %15 +%25 = OpTypePointer Output %9 +%24 = OpVariable %25 Output +%27 = OpTypePointer Output %10 +%26 = OpVariable %27 Output +%29 = OpTypePointer Output %11 +%28 = OpVariable %29 Output +%31 = OpTypePointer Output %12 +%30 = OpVariable %31 Output +%33 = OpTypePointer Output %13 +%32 = OpVariable %33 Output +%35 = OpTypePointer Output %14 +%34 = OpVariable %35 Output +%37 = OpTypeFunction %2 +%39 = OpTypePointer Function %9 +%42 = OpTypePointer Function %10 +%44 = OpConstant %8 1 +%46 = OpTypePointer Function %11 +%48 = OpConstant %8 2 +%50 = OpTypePointer Function %12 +%52 = OpConstant %8 3 +%54 = OpTypePointer Function %13 +%56 = OpConstant %8 4 +%58 = OpTypePointer Function %14 +%60 = OpConstant %8 5 +%70 = OpTypePointer Function %19 +%71 = OpConstantNull %19 +%74 = OpTypePointer Output %16 +%73 = OpVariable %74 Output +%76 = OpTypePointer Output %17 +%75 = OpVariable %76 Output +%78 = OpTypePointer Output %18 +%77 = OpVariable %78 Output +%80 = OpTypePointer Output %4 +%79 = OpVariable %80 Output +%82 = OpTypePointer Output %6 +%81 = OpVariable %82 Output +%84 = OpTypePointer Output %8 +%83 = OpVariable %84 Output +%87 = OpTypePointer Function %16 +%90 = OpTypePointer Function %17 +%93 = OpTypePointer Function %18 +%96 = OpTypePointer Function %4 +%98 = OpTypePointer Function %6 +%100 = OpTypePointer Function %8 +%36 = OpFunction %2 None %37 +%23 = OpLabel +%20 = OpVariable %21 Function %22 +OpBranch %38 +%38 = OpLabel +%40 = OpCompositeConstruct %9 %3 %3 %3 %3 +%41 = OpAccessChain %39 %20 %7 +OpStore %41 %40 +%43 = OpCompositeConstruct %10 %5 %5 %5 %5 +%45 = OpAccessChain %42 %20 %44 +OpStore %45 %43 +%47 = OpCompositeConstruct %11 %7 %7 %7 %7 +%49 = OpAccessChain %46 %20 %48 +OpStore %49 %47 +%51 = OpCompositeConstruct %12 %3 %3 %3 +%53 = OpAccessChain %50 %20 %52 +OpStore %53 %51 +%55 = OpCompositeConstruct %13 %5 %5 %5 +%57 = OpAccessChain %54 %20 %56 +OpStore %57 %55 +%59 = OpCompositeConstruct %14 %7 %7 %7 +%61 = OpAccessChain %58 %20 %60 +OpStore %61 %59 +%62 = OpLoad %15 %20 +%63 = OpCompositeExtract %9 %62 0 +OpStore %24 %63 +%64 = OpCompositeExtract %10 %62 1 +OpStore %26 %64 +%65 = OpCompositeExtract %11 %62 2 +OpStore %28 %65 +%66 = OpCompositeExtract %12 %62 3 +OpStore %30 %66 +%67 = OpCompositeExtract %13 %62 4 +OpStore %32 %67 +%68 = OpCompositeExtract %14 %62 5 +OpStore %34 %68 +OpReturn +OpFunctionEnd +%85 = OpFunction %2 None %37 +%72 = OpLabel +%69 = OpVariable %70 Function %71 +OpBranch %86 +%86 = OpLabel +%88 = OpCompositeConstruct %16 %3 %3 +%89 = OpAccessChain %87 %69 %7 +OpStore %89 %88 +%91 = OpCompositeConstruct %17 %5 %5 +%92 = OpAccessChain %90 %69 %44 +OpStore %92 %91 +%94 = OpCompositeConstruct %18 %7 %7 +%95 = OpAccessChain %93 %69 %48 +OpStore %95 %94 +%97 = OpAccessChain %96 %69 %52 +OpStore %97 %3 +%99 = OpAccessChain %98 %69 %56 +OpStore %99 %5 +%101 = OpAccessChain %100 %69 %60 +OpStore %101 %7 +%102 = OpLoad %19 %69 +%103 = OpCompositeExtract %16 %102 0 +OpStore %73 %103 +%104 = OpCompositeExtract %17 %102 1 +OpStore %75 %104 +%105 = OpCompositeExtract %18 %102 2 +OpStore %77 %105 +%106 = OpCompositeExtract %4 %102 3 +OpStore %79 %106 +%107 = OpCompositeExtract %6 %102 4 +OpStore %81 %107 +%108 = OpCompositeExtract %8 %102 5 +OpStore %83 %108 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/fragment-output.wgsl b/tests/out/wgsl/fragment-output.wgsl new file mode 100644 index 000000000..ea0932023 --- /dev/null +++ b/tests/out/wgsl/fragment-output.wgsl @@ -0,0 +1,45 @@ +struct FragmentOutputVec4Vec3_ { + @location(0) vec4f: vec4, + @location(1) vec4i: vec4, + @location(2) vec4u: vec4, + @location(3) vec3f: vec3, + @location(4) vec3i: vec3, + @location(5) vec3u: vec3, +} + +struct FragmentOutputVec2Scalar { + @location(0) vec2f: vec2, + @location(1) vec2i: vec2, + @location(2) vec2u: vec2, + @location(3) scalarf: f32, + @location(4) scalari: i32, + @location(5) scalaru: u32, +} + +@fragment +fn main_vec4vec3_() -> FragmentOutputVec4Vec3_ { + var output: FragmentOutputVec4Vec3_; + + output.vec4f = vec4(0.0); + output.vec4i = vec4(0); + output.vec4u = vec4(0u); + output.vec3f = vec3(0.0); + output.vec3i = vec3(0); + output.vec3u = vec3(0u); + let _e19 = output; + return _e19; +} + +@fragment +fn main_vec2scalar() -> FragmentOutputVec2Scalar { + var output_1: FragmentOutputVec2Scalar; + + output_1.vec2f = vec2(0.0); + output_1.vec2i = vec2(0); + output_1.vec2u = vec2(0u); + output_1.scalarf = 0.0; + output_1.scalari = 0; + output_1.scalaru = 0u; + let _e16 = output_1; + return _e16; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index a0b9ed53a..16be39589 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -482,6 +482,10 @@ fn convert_wgsl() { "functions", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ( + "fragment-output", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + ), ("functions-webgl", Targets::GLSL), ( "interpolate", From 0b87d1918a906da57341366de4d2b875e09753ee Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Mon, 20 Mar 2023 12:21:52 -0400 Subject: [PATCH 1963/2212] fix(hlsl): emit constructor functions for arrays (#2281) * test(hlsl-out): add failing case for array as ctor arg See issue #2184. * fix(hlsl): emit constructor functions for arrays --- src/back/hlsl/help.rs | 6 +++ src/back/hlsl/storage.rs | 8 +++- tests/in/array-in-ctor.param.ron | 2 + tests/in/array-in-ctor.wgsl | 10 +++++ .../glsl/array-in-ctor.cs_main.Compute.glsl | 17 +++++++++ tests/out/hlsl/access.hlsl | 14 +++---- tests/out/hlsl/array-in-ctor.hlsl | 24 ++++++++++++ tests/out/hlsl/array-in-ctor.hlsl.config | 3 ++ tests/out/msl/array-in-ctor.msl | 18 +++++++++ tests/out/spv/array-in-ctor.spvasm | 38 +++++++++++++++++++ tests/out/wgsl/array-in-ctor.wgsl | 11 ++++++ tests/snapshots.rs | 4 ++ 12 files changed, 146 insertions(+), 9 deletions(-) create mode 100644 tests/in/array-in-ctor.param.ron create mode 100644 tests/in/array-in-ctor.wgsl create mode 100644 tests/out/glsl/array-in-ctor.cs_main.Compute.glsl create mode 100644 tests/out/hlsl/array-in-ctor.hlsl create mode 100644 tests/out/hlsl/array-in-ctor.hlsl.config create mode 100644 tests/out/msl/array-in-ctor.msl create mode 100644 tests/out/spv/array-in-ctor.spvasm create mode 100644 tests/out/wgsl/array-in-ctor.wgsl diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index bb18bf3ab..8ae9baf62 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -882,6 +882,12 @@ impl<'a, W: Write> super::Writer<'a, W> { } crate::TypeInner::Array { base, .. } => { write_wrapped_constructor(writer, base, module)?; + let constructor = WrappedConstructor { ty }; + if !writer.wrapped.constructors.contains(&constructor) { + writer + .write_wrapped_constructor_function(module, constructor)?; + writer.wrapped.constructors.insert(constructor); + } } _ => {} }; diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 21396c953..647a6bf87 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -147,12 +147,16 @@ impl super::Writer<'_, W> { size: crate::ArraySize::Constant(const_handle), .. } => { - write!(self.out, "{{")?; + let constructor = super::help::WrappedConstructor { + ty: result_ty.handle().unwrap(), + }; + self.write_wrapped_constructor_function_name(module, constructor)?; + write!(self.out, "(")?; let count = module.constants[const_handle].to_array_length().unwrap(); let stride = module.types[base].inner.size(&module.constants); let iter = (0..count).map(|i| (TypeResolution::Handle(base), stride * i)); self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; - write!(self.out, "}}")?; + write!(self.out, ")")?; } crate::TypeInner::Struct { ref members, .. } => { let constructor = super::help::WrappedConstructor { diff --git a/tests/in/array-in-ctor.param.ron b/tests/in/array-in-ctor.param.ron new file mode 100644 index 000000000..72873dd66 --- /dev/null +++ b/tests/in/array-in-ctor.param.ron @@ -0,0 +1,2 @@ +( +) diff --git a/tests/in/array-in-ctor.wgsl b/tests/in/array-in-ctor.wgsl new file mode 100644 index 000000000..a7ca66be6 --- /dev/null +++ b/tests/in/array-in-ctor.wgsl @@ -0,0 +1,10 @@ +struct Ah { + inner: array, +}; +@group(0) @binding(0) +var ah: Ah; + +@compute @workgroup_size(1) +fn cs_main() { + _ = ah; +} diff --git a/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl b/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl new file mode 100644 index 000000000..e8245d55e --- /dev/null +++ b/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl @@ -0,0 +1,17 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +struct Ah { + float inner[2]; +}; +layout(std430) readonly buffer Ah_block_0Compute { Ah _group_0_binding_0_cs; }; + + +void main() { + Ah unnamed = _group_0_binding_0_cs; +} + diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index a8d7d80c9..f20cb726d 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -249,6 +249,12 @@ void assign_array_through_ptr_fn(inout float4 foo_2[2]) return; } +typedef uint2 ret_Constructarray2_uint2_[2]; +ret_Constructarray2_uint2_ Constructarray2_uint2_(uint2 arg0, uint2 arg1) { + uint2 ret[2] = { arg0, arg1 }; + return ret; +} + uint NagaBufferLengthRW(RWByteAddressBuffer buffer) { uint ret; @@ -273,7 +279,7 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position test_matrix_within_struct_accesses(); test_matrix_within_array_within_struct_accesses(); float4x3 _matrix = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); - uint2 arr_1[2] = {asuint(bar.Load2(144+0)), asuint(bar.Load2(144+8))}; + uint2 arr_1[2] = Constructarray2_uint2_(asuint(bar.Load2(144+0)), asuint(bar.Load2(144+8))); float b = asfloat(bar.Load(0+48+0)); int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 160) / 8) - 2u)*8+160)); int2 c = asint(qux.Load2(0)); @@ -285,12 +291,6 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position return float4(mul(float4((value).xxxx), _matrix), 2.0); } -typedef uint2 ret_Constructarray2_uint2_[2]; -ret_Constructarray2_uint2_ Constructarray2_uint2_(uint2 arg0, uint2 arg1) { - uint2 ret[2] = { arg0, arg1 }; - return ret; -} - float4 foo_frag() : SV_Target0 { bar.Store(8+16+0, asuint(1.0)); diff --git a/tests/out/hlsl/array-in-ctor.hlsl b/tests/out/hlsl/array-in-ctor.hlsl new file mode 100644 index 000000000..edaa95473 --- /dev/null +++ b/tests/out/hlsl/array-in-ctor.hlsl @@ -0,0 +1,24 @@ + +struct Ah { + float inner[2]; +}; + +ByteAddressBuffer ah : register(t0); + +typedef float ret_Constructarray2_float_[2]; +ret_Constructarray2_float_ Constructarray2_float_(float arg0, float arg1) { + float ret[2] = { arg0, arg1 }; + return ret; +} + +Ah ConstructAh(float arg0[2]) { + Ah ret = (Ah)0; + ret.inner = arg0; + return ret; +} + +[numthreads(1, 1, 1)] +void cs_main() +{ + Ah unnamed = ConstructAh(Constructarray2_float_(asfloat(ah.Load(0+0)), asfloat(ah.Load(0+4)))); +} diff --git a/tests/out/hlsl/array-in-ctor.hlsl.config b/tests/out/hlsl/array-in-ctor.hlsl.config new file mode 100644 index 000000000..522d99ed1 --- /dev/null +++ b/tests/out/hlsl/array-in-ctor.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(cs_main:cs_5_1 ) diff --git a/tests/out/msl/array-in-ctor.msl b/tests/out/msl/array-in-ctor.msl new file mode 100644 index 000000000..eab190df7 --- /dev/null +++ b/tests/out/msl/array-in-ctor.msl @@ -0,0 +1,18 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct type_1 { + float inner[2]; +}; +struct Ah { + type_1 inner; +}; + +kernel void cs_main( + device Ah const& ah [[user(fake0)]] +) { + Ah unnamed = ah; +} diff --git a/tests/out/spv/array-in-ctor.spvasm b/tests/out/spv/array-in-ctor.spvasm new file mode 100644 index 000000000..8ad438ce0 --- /dev/null +++ b/tests/out/spv/array-in-ctor.spvasm @@ -0,0 +1,38 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 20 +OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %12 "cs_main" +OpExecutionMode %12 LocalSize 1 1 1 +OpDecorate %6 ArrayStride 4 +OpMemberDecorate %7 0 Offset 0 +OpDecorate %8 NonWritable +OpDecorate %8 DescriptorSet 0 +OpDecorate %8 Binding 0 +OpDecorate %9 Block +OpMemberDecorate %9 0 Offset 0 +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 2 +%5 = OpTypeFloat 32 +%6 = OpTypeArray %5 %3 +%7 = OpTypeStruct %6 +%9 = OpTypeStruct %7 +%10 = OpTypePointer StorageBuffer %9 +%8 = OpVariable %10 StorageBuffer +%13 = OpTypeFunction %2 +%14 = OpTypePointer StorageBuffer %7 +%16 = OpTypeInt 32 0 +%15 = OpConstant %16 0 +%12 = OpFunction %2 None %13 +%11 = OpLabel +%17 = OpAccessChain %14 %8 %15 +OpBranch %18 +%18 = OpLabel +%19 = OpLoad %7 %17 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/array-in-ctor.wgsl b/tests/out/wgsl/array-in-ctor.wgsl new file mode 100644 index 000000000..f4a8f4ddd --- /dev/null +++ b/tests/out/wgsl/array-in-ctor.wgsl @@ -0,0 +1,11 @@ +struct Ah { + inner: array, +} + +@group(0) @binding(0) +var ah: Ah; + +@compute @workgroup_size(1, 1, 1) +fn cs_main() { + _ = ah; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 16be39589..691c074a9 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -426,6 +426,10 @@ fn convert_wgsl() { let root = env!("CARGO_MANIFEST_DIR"); let inputs = [ + ( + "array-in-ctor", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + ), ( "empty", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From 432b4990a797942fca746b379aaeb2de6743b61e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 1 Feb 2023 22:19:42 -0800 Subject: [PATCH 1964/2212] Add ray query types to the IR --- src/back/glsl/mod.rs | 2 ++ src/back/msl/writer.rs | 9 ++++++- src/back/spv/writer.rs | 4 ++- src/front/wgsl/lower/mod.rs | 2 ++ src/front/wgsl/mod.rs | 2 ++ src/front/wgsl/parse/ast.rs | 2 ++ src/front/wgsl/parse/mod.rs | 2 ++ src/lib.rs | 5 ++++ src/proc/layouter.rs | 6 ++++- src/proc/mod.rs | 6 ++++- src/valid/expression.rs | 4 +-- src/valid/handles.rs | 4 ++- src/valid/mod.rs | 6 ++++- src/valid/type.rs | 50 +++++++++++++++++++++++++----------- tests/in/ray-query.param.ron | 6 +++++ tests/in/ray-query.wgsl | 17 ++++++++++++ tests/snapshots.rs | 1 + 17 files changed, 105 insertions(+), 23 deletions(-) create mode 100644 tests/in/ray-query.param.ron create mode 100644 tests/in/ray-query.wgsl diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 44685fb99..419f4c438 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -879,6 +879,8 @@ impl<'a, W: Write> Writer<'a, W> { | TypeInner::Struct { .. } | TypeInner::Image { .. } | TypeInner::Sampler { .. } + | TypeInner::AccelerationStructure + | TypeInner::RayQuery | TypeInner::BindingArray { .. } => { return Err(Error::Custom(format!("Unable to write type {inner:?}"))) } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ee23ca294..68945315c 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -194,6 +194,9 @@ impl<'a> Display for TypeContext<'a> { crate::TypeInner::Sampler { comparison: _ } => { write!(out, "{NAMESPACE}::sampler") } + crate::TypeInner::AccelerationStructure | crate::TypeInner::RayQuery => { + unreachable!("Ray queries are not supported yet"); + } crate::TypeInner::BindingArray { base, size } => { let base_tyname = Self { handle: base, @@ -485,7 +488,11 @@ impl crate::Type { // composite types are better to be aliased, regardless of the name Ti::Struct { .. } | Ti::Array { .. } => true, // handle types may be different, depending on the global var access, so we always inline them - Ti::Image { .. } | Ti::Sampler { .. } | Ti::BindingArray { .. } => false, + Ti::Image { .. } + | Ti::Sampler { .. } + | Ti::AccelerationStructure + | Ti::RayQuery + | Ti::BindingArray { .. } => false, } } } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f264c107d..fbc53feed 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1017,7 +1017,9 @@ impl Writer { | crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Image { .. } - | crate::TypeInner::Sampler { .. } => unreachable!(), + | crate::TypeInner::Sampler { .. } + | crate::TypeInner::AccelerationStructure + | crate::TypeInner::RayQuery => unreachable!(), }; instruction.to_words(&mut self.logical_layout.declarations); diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index f3b157caa..8dfb735af 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -2245,6 +2245,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { class, }, ast::Type::Sampler { comparison } => crate::TypeInner::Sampler { comparison }, + ast::Type::AccelerationStructure => crate::TypeInner::AccelerationStructure, + ast::Type::RayQuery => crate::TypeInner::RayQuery, ast::Type::BindingArray { base, size } => { let base = self.resolve_ast_type(base, ctx.reborrow())?; diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 8ac82fe45..eb21fae6c 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -206,6 +206,8 @@ impl crate::TypeInner { format!("texture{class_suffix}{dim_suffix}{array_suffix}{type_in_brackets}") } Ti::Sampler { .. } => "sampler".to_string(), + Ti::AccelerationStructure => "acceleration_structure".to_string(), + Ti::RayQuery => "ray_query".to_string(), Ti::BindingArray { base, size, .. } => { let member_type = &types[base]; let base = member_type.name.as_deref().unwrap_or("unknown"); diff --git a/src/front/wgsl/parse/ast.rs b/src/front/wgsl/parse/ast.rs index 734d9769f..a5da4a49c 100644 --- a/src/front/wgsl/parse/ast.rs +++ b/src/front/wgsl/parse/ast.rs @@ -229,6 +229,8 @@ pub enum Type<'a> { Sampler { comparison: bool, }, + AccelerationStructure, + RayQuery, BindingArray { base: Handle>, size: ArraySize<'a>, diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 7ff762d67..f082ec1c4 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -1367,6 +1367,8 @@ impl Parser { class: crate::ImageClass::Storage { format, access }, } } + "acceleration_structure" => ast::Type::AccelerationStructure, + "ray_query" => ast::Type::RayQuery, _ => return Ok(None), })) } diff --git a/src/lib.rs b/src/lib.rs index c1b48b899..f8491f3a3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -721,6 +721,11 @@ pub enum TypeInner { /// Can be used to sample values from images. Sampler { comparison: bool }, + /// Opaque object representing an acceleration structure of geometry. + AccelerationStructure, + /// Locally used handle for ray queries. + RayQuery, + /// Array of bindings. /// /// A `BindingArray` represents an array where each element draws its value diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index db07f261a..65369d1cc 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -238,7 +238,11 @@ impl Layouter { alignment, } } - Ti::Image { .. } | Ti::Sampler { .. } | Ti::BindingArray { .. } => TypeLayout { + Ti::Image { .. } + | Ti::Sampler { .. } + | Ti::AccelerationStructure + | Ti::RayQuery + | Ti::BindingArray { .. } => TypeLayout { size, alignment: Alignment::ONE, }, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 6a8bfa03c..a775272a1 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -134,7 +134,11 @@ impl super::TypeInner { count * stride } Self::Struct { span, .. } => span, - Self::Image { .. } | Self::Sampler { .. } | Self::BindingArray { .. } => 0, + Self::Image { .. } + | Self::Sampler { .. } + | Self::AccelerationStructure + | Self::RayQuery + | Self::BindingArray { .. } => 0, } } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index af080fc18..9063eb061 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1379,7 +1379,7 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidCastArgument), }; let width = convert.unwrap_or(base_width); - if !self.check_width(kind, width) { + if self.check_width(kind, width).is_err() { return Err(ExpressionError::InvalidCastArgument); } ShaderStages::all() @@ -1390,7 +1390,7 @@ impl super::Validator { &crate::TypeInner::Scalar { kind: kind @ (crate::ScalarKind::Uint | crate::ScalarKind::Sint), width, - } => self.check_width(kind, width), + } => self.check_width(kind, width).is_ok(), _ => false, }; let good = match &module.types[ty].inner { diff --git a/src/valid/handles.rs b/src/valid/handles.rs index e3f9fe253..871a73a21 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -76,7 +76,9 @@ impl super::Validator { | crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Atomic { .. } | crate::TypeInner::Image { .. } - | crate::TypeInner::Sampler { .. } => (), + | crate::TypeInner::Sampler { .. } + | crate::TypeInner::AccelerationStructure + | crate::TypeInner::RayQuery => (), crate::TypeInner::Pointer { base, space: _ } => { this_handle.check_dep(base)?; } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index eb92e8892..6b3a2e145 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -111,6 +111,8 @@ bitflags::bitflags! { const EARLY_DEPTH_TEST = 0x400; /// Support for [`Builtin::SampleIndex`] and [`Sampling::Sample`]. const MULTISAMPLED_SHADING = 0x800; + /// Support for ray queries and acceleration structures. + const RAY_QUERY = 0x1000; } } @@ -238,6 +240,8 @@ impl crate::TypeInner { Self::Array { .. } | Self::Image { .. } | Self::Sampler { .. } + | Self::AccelerationStructure + | Self::RayQuery | Self::BindingArray { .. } => false, } } @@ -302,7 +306,7 @@ impl Validator { let con = &constants[handle]; match con.inner { crate::ConstantInner::Scalar { width, ref value } => { - if !self.check_width(value.scalar_kind(), width) { + if self.check_width(value.scalar_kind(), width).is_err() { return Err(ConstantError::InvalidType); } } diff --git a/src/valid/type.rs b/src/valid/type.rs index 4fcc1a1c5..23f6ef4d1 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -90,6 +90,8 @@ pub enum Disalignment { #[derive(Clone, Debug, thiserror::Error)] pub enum TypeError { + #[error("Capability {0:?} is required")] + MissingCapability(Capabilities), #[error("The {0:?} scalar width {1} is not supported")] InvalidWidth(crate::ScalarKind, crate::Bytes), #[error("The {0:?} scalar width {1} is not supported for an atomic")] @@ -203,13 +205,35 @@ impl TypeInfo { } impl super::Validator { - pub(super) const fn check_width(&self, kind: crate::ScalarKind, width: crate::Bytes) -> bool { - match kind { + fn require_type_capability(&self, capability: Capabilities) -> Result<(), TypeError> { + if self.capabilities.contains(capability) { + Ok(()) + } else { + Err(TypeError::MissingCapability(capability)) + } + } + + pub(super) fn check_width( + &self, + kind: crate::ScalarKind, + width: crate::Bytes, + ) -> Result<(), TypeError> { + let good = match kind { crate::ScalarKind::Bool => width == crate::BOOL_WIDTH, crate::ScalarKind::Float => { - width == 4 || (width == 8 && self.capabilities.contains(Capabilities::FLOAT64)) + if width == 8 { + self.require_type_capability(Capabilities::FLOAT64)?; + true + } else { + width == 4 + } } crate::ScalarKind::Sint | crate::ScalarKind::Uint => width == 4, + }; + if good { + Ok(()) + } else { + Err(TypeError::InvalidWidth(kind, width)) } } @@ -228,9 +252,7 @@ impl super::Validator { use crate::TypeInner as Ti; Ok(match types[handle].inner { Ti::Scalar { kind, width } => { - if !self.check_width(kind, width) { - return Err(TypeError::InvalidWidth(kind, width)); - } + self.check_width(kind, width)?; let shareable = if kind.is_numeric() { TypeFlags::IO_SHAREABLE | TypeFlags::HOST_SHAREABLE } else { @@ -247,9 +269,7 @@ impl super::Validator { ) } Ti::Vector { size, kind, width } => { - if !self.check_width(kind, width) { - return Err(TypeError::InvalidWidth(kind, width)); - } + self.check_width(kind, width)?; let shareable = if kind.is_numeric() { TypeFlags::IO_SHAREABLE | TypeFlags::HOST_SHAREABLE } else { @@ -271,9 +291,7 @@ impl super::Validator { rows, width, } => { - if !self.check_width(crate::ScalarKind::Float, width) { - return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width)); - } + self.check_width(crate::ScalarKind::Float, width)?; TypeInfo::new( TypeFlags::DATA | TypeFlags::SIZED @@ -355,9 +373,7 @@ impl super::Validator { // However, some cases are trivial: All our implicit base types // are DATA and SIZED, so we can never return // `InvalidPointerBase` or `InvalidPointerToUnsized`. - if !self.check_width(kind, width) { - return Err(TypeError::InvalidWidth(kind, width)); - } + self.check_width(kind, width)?; // `Validator::validate_function` actually checks the storage // space of pointer arguments explicitly before checking the @@ -606,6 +622,10 @@ impl super::Validator { Ti::Image { .. } | Ti::Sampler { .. } => { TypeInfo::new(TypeFlags::ARGUMENT, Alignment::ONE) } + Ti::AccelerationStructure | Ti::RayQuery => { + self.require_type_capability(Capabilities::RAY_QUERY)?; + TypeInfo::new(TypeFlags::empty(), Alignment::ONE) + } Ti::BindingArray { .. } => TypeInfo::new(TypeFlags::empty(), Alignment::ONE), }) } diff --git a/tests/in/ray-query.param.ron b/tests/in/ray-query.param.ron new file mode 100644 index 000000000..9d8666954 --- /dev/null +++ b/tests/in/ray-query.param.ron @@ -0,0 +1,6 @@ +( + god_mode: true, + spv: ( + version: (1, 4), + ), +) diff --git a/tests/in/ray-query.wgsl b/tests/in/ray-query.wgsl new file mode 100644 index 000000000..26023ff2f --- /dev/null +++ b/tests/in/ray-query.wgsl @@ -0,0 +1,17 @@ +var acc_struct: acceleration_structure; + +struct Output { + visible: u32, +} +var output: Output; + +@compute +fn main() { + var rq: ray_query; + + rayQueryInitialize(rq, acceleration_structure, RAY_FLAGS_TERMINATE_ON_FIRST_HIT, 0xFF, vec3(0.0), 0.1, vec3(0.0, 1.0, 0.0), 100.0); + + rayQueryProceed(rq); + + output.visible = rayQueryGetCommittedIntersectionType(rq) == RAY_QUERY_COMMITTED_INTERSECTION_NONE; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 691c074a9..df94130a7 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -571,6 +571,7 @@ fn convert_wgsl() { ("sprite", Targets::SPIRV), ("force_point_size_vertex_shader_webgl", Targets::GLSL), ("invariant", Targets::GLSL), + ("ray-query", Targets::SPIRV), ]; for &(name, targets) in inputs.iter() { From e46c53d212c6d8fe29fa730c9484bdb240b0b013 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 13 Feb 2023 21:12:06 -0800 Subject: [PATCH 1965/2212] Add ray query statements to the IR --- src/back/dot/mod.rs | 16 ++++++++++++++++ src/back/glsl/mod.rs | 1 + src/back/hlsl/writer.rs | 1 + src/back/msl/writer.rs | 1 + src/back/spv/block.rs | 11 +++++++++++ src/back/wgsl/writer.rs | 1 + src/front/spv/mod.rs | 3 ++- src/lib.rs | 17 +++++++++++++++++ src/proc/terminator.rs | 1 + src/valid/analyzer.rs | 12 ++++++++++++ src/valid/function.rs | 3 +++ src/valid/handles.rs | 14 ++++++++++++++ tests/in/ray-query.wgsl | 20 +++++++++++++++++++- 13 files changed, 99 insertions(+), 2 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 1167357e8..f53d2faa1 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -252,6 +252,22 @@ impl StatementGraph { } "Atomic" } + S::RayQuery { query, ref fun } => { + self.dependencies.push((id, query, "query")); + if let crate::RayQueryFunction::Initialize { + acceleration_structure, + descriptor, + } = *fun + { + self.dependencies.push(( + id, + acceleration_structure, + "acceleration_structure", + )); + self.dependencies.push((id, descriptor, "descriptor")); + } + "RayQuery" + } }; // Set the last node to the merge node last_node = merge_id; diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 419f4c438..e81c27c50 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2197,6 +2197,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(value, ctx)?; writeln!(self.out, ");")?; } + Statement::RayQuery { .. } => unreachable!(), } Ok(()) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index d11032bbf..9e9aa19d7 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1980,6 +1980,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, "{level}}}")? } + Statement::RayQuery { .. } => unreachable!(), } Ok(()) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 68945315c..fa222d8d4 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2759,6 +2759,7 @@ impl Writer { // done writeln!(self.out, ";")?; } + crate::Statement::RayQuery { .. } => unreachable!(), } } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index c3fa8455e..02a83a19a 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -2196,6 +2196,17 @@ impl<'w> BlockContext<'w> { block.body.push(instruction); } + crate::Statement::RayQuery { query, ref fun } => { + let query_id = self.cached[query]; + match *fun { + crate::RayQueryFunction::Initialize { + acceleration_structure, + descriptor, + } => {} + crate::RayQueryFunction::Proceed => {} + crate::RayQueryFunction::Terminate => {} + } + } } } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index f24f4a9c2..90d3b5330 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -937,6 +937,7 @@ impl Writer { writeln!(self.out, "{level}workgroupBarrier();")?; } } + Statement::RayQuery { .. } => unreachable!(), } Ok(()) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index ce42be35b..c69a230cb 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3672,7 +3672,8 @@ impl> Frontend { | S::Barrier(_) | S::Store { .. } | S::ImageStore { .. } - | S::Atomic { .. } => {} + | S::Atomic { .. } + | S::RayQuery { .. } => {} S::Call { function: ref mut callee, ref arguments, diff --git a/src/lib.rs b/src/lib.rs index f8491f3a3..efb05c8ff 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1473,6 +1473,19 @@ pub struct SwitchCase { pub fall_through: bool, } +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +pub enum RayQueryFunction { + Initialize { + acceleration_structure: Handle, + descriptor: Handle, + }, + Proceed, + Terminate, +} + //TODO: consider removing `Clone`. It's not valid to clone `Statement::Emit` anyway. /// Instructions which make up an executable block. // Clone is used only for error reporting and is not intended for end users @@ -1646,6 +1659,10 @@ pub enum Statement { arguments: Vec>, result: Option>, }, + RayQuery { + query: Handle, + fun: RayQueryFunction, + }, } /// A function argument. diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index 5915616cc..ca0c3f10b 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -34,6 +34,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) { | S::Store { .. } | S::ImageStore { .. } | S::Call { .. } + | S::RayQuery { .. } | S::Atomic { .. } | S::Barrier(_)), ) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 40d5f95c1..8d1943098 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -893,6 +893,18 @@ impl FunctionInfo { } FunctionUniformity::new() } + S::RayQuery { query, ref fun } => { + let _ = self.add_ref(query); + if let crate::RayQueryFunction::Initialize { + acceleration_structure, + descriptor, + } = *fun + { + let _ = self.add_ref(acceleration_structure); + let _ = self.add_ref(descriptor); + } + FunctionUniformity::new() + } }; disruptor = disruptor.or(uniformity.exit_disruptor()); diff --git a/src/valid/function.rs b/src/valid/function.rs index 464496f6d..a13a07bcf 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -807,6 +807,9 @@ impl super::Validator { } => { self.validate_atomic(pointer, fun, value, result, context)?; } + S::RayQuery { query: _, fun: _ } => { + //TODO + } } } Ok(BlockInfo { stages, finished }) diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 871a73a21..20d8448a1 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -496,6 +496,20 @@ impl super::Validator { validate_expr_opt(result)?; Ok(()) } + crate::Statement::RayQuery { query, ref fun } => { + validate_expr(query)?; + match *fun { + crate::RayQueryFunction::Initialize { + acceleration_structure, + descriptor, + } => { + validate_expr(acceleration_structure)?; + validate_expr(descriptor)?; + } + crate::RayQueryFunction::Proceed | crate::RayQueryFunction::Terminate => {} + } + Ok(()) + } crate::Statement::Break | crate::Statement::Continue | crate::Statement::Kill diff --git a/tests/in/ray-query.wgsl b/tests/in/ray-query.wgsl index 26023ff2f..b772e69d7 100644 --- a/tests/in/ray-query.wgsl +++ b/tests/in/ray-query.wgsl @@ -1,5 +1,23 @@ var acc_struct: acceleration_structure; +/* +let RAY_FLAG_NONE = 0u; +let RAY_FLAG_TERMINATE_ON_FIRST_HIT = 4u; + +let RAY_QUERY_INTERSECTION_NONE = 0u; +let RAY_QUERY_INTERSECTION_TRIANGLE = 1u; +let RAY_QUERY_INTERSECTION_GENERATED = 2u; +let RAY_QUERY_INTERSECTION_AABB = 4u; + +struct RayDesc { + flags: u32, + cull_mask: u32, + origin: vec3, + t_min: f32, + dir: vec3, + t_max: f32, +}*/ + struct Output { visible: u32, } @@ -9,7 +27,7 @@ var output: Output; fn main() { var rq: ray_query; - rayQueryInitialize(rq, acceleration_structure, RAY_FLAGS_TERMINATE_ON_FIRST_HIT, 0xFF, vec3(0.0), 0.1, vec3(0.0, 1.0, 0.0), 100.0); + rayQueryInitialize(rq, acceleration_structure, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xFF, vec3(0.0), 0.1, vec3(0.0, 1.0, 0.0), 100.0)); rayQueryProceed(rq); From b856625821b5b5aac8b85c66fc03054f6e670c19 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 15 Feb 2023 23:35:03 -0800 Subject: [PATCH 1966/2212] Ray query expressions and special types --- src/back/dot/mod.rs | 6 ++ src/back/glsl/mod.rs | 6 +- src/back/hlsl/writer.rs | 6 +- src/back/msl/writer.rs | 6 +- src/back/spv/block.rs | 4 + src/back/wgsl/writer.rs | 6 +- src/front/glsl/constants.rs | 5 + src/front/glsl/types.rs | 18 +--- src/front/mod.rs | 1 + src/front/type_gen.rs | 153 +++++++++++++++++++++++++++ src/front/wgsl/lower/construction.rs | 4 + src/front/wgsl/lower/mod.rs | 58 ++++++++-- src/front/wgsl/parse/ast.rs | 3 + src/front/wgsl/parse/mod.rs | 13 +++ src/lib.rs | 25 +++++ src/proc/typifier.rs | 31 ++++++ src/valid/analyzer.rs | 20 ++-- src/valid/expression.rs | 1 + src/valid/handles.rs | 16 ++- src/valid/interface.rs | 4 +- src/valid/type.rs | 6 +- tests/in/ray-query.wgsl | 30 ++++-- tests/out/ir/access.ron | 4 + tests/out/ir/collatz.ron | 4 + tests/out/ir/shadow.ron | 4 + 25 files changed, 388 insertions(+), 46 deletions(-) create mode 100644 src/front/type_gen.rs diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index f53d2faa1..d293c3adc 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -566,6 +566,12 @@ fn write_function_expressions( edges.insert("", expr); ("ArrayLength".into(), 7) } + E::RayQueryProceedResult => ("rayQueryProceedResult".into(), 4), + E::RayQueryGetIntersection { query, committed } => { + edges.insert("", query); + let ty = if committed { "Committed" } else { "Candidate" }; + (format!("rayQueryGet{}Intersection", ty).into(), 4) + } }; // give uniform expressions an outline diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index e81c27c50..9195b9683 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -3280,13 +3280,17 @@ impl<'a, W: Write> Writer<'a, W> { } } // These expressions never show up in `Emit`. - Expression::CallResult(_) | Expression::AtomicResult { .. } => unreachable!(), + Expression::CallResult(_) + | Expression::AtomicResult { .. } + | Expression::RayQueryProceedResult => unreachable!(), // `ArrayLength` is written as `expr.length()` and we convert it to a uint Expression::ArrayLength(expr) => { write!(self.out, "uint(")?; self.write_expr(expr, ctx)?; write!(self.out, ".length())")? } + // not supported yet + Expression::RayQueryGetIntersection { .. } => unreachable!(), } Ok(()) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 9e9aa19d7..f9e52914f 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2879,8 +2879,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, reject, func_ctx)?; write!(self.out, ")")? } + // Not supported yet + Expression::RayQueryGetIntersection { .. } => unreachable!(), // Nothing to do here, since call expression already cached - Expression::CallResult(_) | Expression::AtomicResult { .. } => {} + Expression::CallResult(_) + | Expression::AtomicResult { .. } + | Expression::RayQueryProceedResult => {} } if !closing_bracket.is_empty() { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index fa222d8d4..2ec5bad33 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1838,7 +1838,9 @@ impl Writer { _ => return Err(Error::Validation), }, // has to be a named expression - crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } => { + crate::Expression::CallResult(_) + | crate::Expression::AtomicResult { .. } + | crate::Expression::RayQueryProceedResult => { unreachable!() } crate::Expression::ArrayLength(expr) => { @@ -1863,6 +1865,8 @@ impl Writer { write!(self.out, ")")?; } } + // hot supported yet + crate::Expression::RayQueryGetIntersection { .. } => unreachable!(), } Ok(()) } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 02a83a19a..090899b4a 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1386,6 +1386,10 @@ impl<'w> BlockContext<'w> { id } crate::Expression::ArrayLength(expr) => self.write_runtime_array_length(expr, block)?, + //TODO + crate::Expression::RayQueryProceedResult => unreachable!(), + //TODO + crate::Expression::RayQueryGetIntersection { .. } => unreachable!(), }; self.cached[expr_handle] = id; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 90d3b5330..92086c94a 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1622,8 +1622,12 @@ impl Writer { write!(self.out, ")")? } + // Not supported yet + Expression::RayQueryGetIntersection { .. } => unreachable!(), // Nothing to do here, since call expression already cached - Expression::CallResult(_) | Expression::AtomicResult { .. } => {} + Expression::CallResult(_) + | Expression::AtomicResult { .. } + | Expression::RayQueryProceedResult => {} } Ok(()) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index d9a6fc7cd..045a9c6ff 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -37,6 +37,8 @@ pub enum ConstantSolvingError { Load, #[error("Constants don't support image expressions")] ImageExpression, + #[error("Constants don't support ray query expressions")] + RayQueryExpression, #[error("Cannot access the type")] InvalidAccessBase, #[error("Cannot access at the index")] @@ -295,6 +297,9 @@ impl<'a> ConstantSolver<'a> { Expression::ImageSample { .. } | Expression::ImageLoad { .. } | Expression::ImageQuery { .. } => Err(ConstantSolvingError::ImageExpression), + Expression::RayQueryProceedResult | Expression::RayQueryGetIntersection { .. } => { + Err(ConstantSolvingError::RayQueryExpression) + } } } diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 632378c60..a7967848d 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -246,14 +246,7 @@ impl Frontend { expr: Handle, meta: Span, ) -> Result<()> { - let resolve_ctx = ResolveContext { - constants: &self.module.constants, - types: &self.module.types, - global_vars: &self.module.global_variables, - local_vars: &ctx.locals, - functions: &self.module.functions, - arguments: &ctx.arguments, - }; + let resolve_ctx = ResolveContext::with_locals(&self.module, &ctx.locals, &ctx.arguments); ctx.typifier .grow(expr, &ctx.expressions, &resolve_ctx) @@ -312,14 +305,7 @@ impl Frontend { expr: Handle, meta: Span, ) -> Result<()> { - let resolve_ctx = ResolveContext { - constants: &self.module.constants, - types: &self.module.types, - global_vars: &self.module.global_variables, - local_vars: &ctx.locals, - functions: &self.module.functions, - arguments: &ctx.arguments, - }; + let resolve_ctx = ResolveContext::with_locals(&self.module, &ctx.locals, &ctx.arguments); ctx.typifier .invalidate(expr, &ctx.expressions, &resolve_ctx) diff --git a/src/front/mod.rs b/src/front/mod.rs index 071e805a6..d6f38671e 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -3,6 +3,7 @@ Frontend parsers that consume binary and text shaders and load them into [`Modul */ mod interpolator; +mod type_gen; #[cfg(feature = "glsl-in")] pub mod glsl; diff --git a/src/front/type_gen.rs b/src/front/type_gen.rs new file mode 100644 index 000000000..18d9ddd54 --- /dev/null +++ b/src/front/type_gen.rs @@ -0,0 +1,153 @@ +/*! +Type generators. +*/ + +use crate::{arena::Handle, span::Span}; + +impl crate::Module { + pub(super) fn generate_ray_desc_type(&mut self) -> Handle { + if let Some(handle) = self.special_types.ray_desc { + return handle; + } + + let width = 4; + let ty_flag = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + width, + kind: crate::ScalarKind::Uint, + }, + }, + Span::UNDEFINED, + ); + let ty_scalar = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + width, + kind: crate::ScalarKind::Float, + }, + }, + Span::UNDEFINED, + ); + let ty_vector = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + kind: crate::ScalarKind::Float, + width, + }, + }, + Span::UNDEFINED, + ); + + let handle = self.types.insert( + crate::Type { + name: Some("RayDesc".to_string()), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("flags".to_string()), + ty: ty_flag, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("cull_mask".to_string()), + ty: ty_flag, + binding: None, + offset: 4, + }, + crate::StructMember { + name: Some("tmin".to_string()), + ty: ty_scalar, + binding: None, + offset: 8, + }, + crate::StructMember { + name: Some("tmax".to_string()), + ty: ty_scalar, + binding: None, + offset: 12, + }, + crate::StructMember { + name: Some("origin".to_string()), + ty: ty_vector, + binding: None, + offset: 16, + }, + crate::StructMember { + name: Some("dir".to_string()), + ty: ty_vector, + binding: None, + offset: 32, + }, + ], + span: 48, + }, + }, + Span::UNDEFINED, + ); + + self.special_types.ray_desc = Some(handle); + handle + } + + pub(super) fn generate_ray_intersection_type(&mut self) -> Handle { + if let Some(handle) = self.special_types.ray_intersection { + return handle; + } + + let width = 4; + let ty_flag = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + width, + kind: crate::ScalarKind::Uint, + }, + }, + Span::UNDEFINED, + ); + let ty_scalar = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + width, + kind: crate::ScalarKind::Float, + }, + }, + Span::UNDEFINED, + ); + + let handle = self.types.insert( + crate::Type { + name: Some("RayIntersection".to_string()), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("kind".to_string()), + ty: ty_flag, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("t".to_string()), + ty: ty_scalar, + binding: None, + offset: 4, + }, + //TODO: the rest + ], + span: 8, + }, + }, + Span::UNDEFINED, + ); + + self.special_types.ray_intersection = Some(handle); + handle + } +} diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 723d4441f..4b0371573 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -660,6 +660,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }); ConcreteConstructorHandle::Type(ty) } + ast::ConstructorType::RayDesc => { + let ty = ctx.module.generate_ray_desc_type(); + ConcreteConstructorHandle::Type(ty) + } ast::ConstructorType::Type(ty) => ConcreteConstructorHandle::Type(ty), }; diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 8dfb735af..971b3032b 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -234,14 +234,8 @@ impl<'a> ExpressionContext<'a, '_, '_> { /// [`self.resolved_inner(handle)`]: ExpressionContext::resolved_inner /// [`Typifier`]: Typifier fn grow_types(&mut self, handle: Handle) -> Result<&mut Self, Error<'a>> { - let resolve_ctx = ResolveContext { - constants: &self.module.constants, - types: &self.module.types, - global_vars: &self.module.global_variables, - local_vars: self.local_vars, - functions: &self.module.functions, - arguments: self.arguments, - }; + let resolve_ctx = + ResolveContext::with_locals(&self.module, self.local_vars, self.arguments); self.typifier .grow(handle, self.naga_expressions, &resolve_ctx) .map_err(Error::InvalidResolve)?; @@ -1919,6 +1913,54 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { query: crate::ImageQuery::NumSamples, } } + "rayQueryInitialize" => { + let mut args = ctx.prepare_args(arguments, 3, span); + let query = self.expression(args.next()?, ctx.reborrow())?; + let acceleration_structure = + self.expression(args.next()?, ctx.reborrow())?; + let descriptor = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + let _ = ctx.module.generate_ray_desc_type(); + let fun = crate::RayQueryFunction::Initialize { + acceleration_structure, + descriptor, + }; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + ctx.emitter.start(ctx.naga_expressions); + ctx.block + .push(crate::Statement::RayQuery { query, fun }, span); + return Ok(None); + } + "rayQueryProceed" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let query = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + let fun = crate::RayQueryFunction::Proceed; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + let result = ctx + .naga_expressions + .append(crate::Expression::RayQueryProceedResult, span); + ctx.emitter.start(ctx.naga_expressions); + ctx.block + .push(crate::Statement::RayQuery { query, fun }, span); + return Ok(Some(result)); + } + "rayQueryGetCommittedIntersection" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let query = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + let _ = ctx.module.generate_ray_intersection_type(); + + crate::Expression::RayQueryGetIntersection { + query, + committed: true, + } + } _ => return Err(Error::UnknownIdent(function.span, function.name)), } }; diff --git a/src/front/wgsl/parse/ast.rs b/src/front/wgsl/parse/ast.rs index a5da4a49c..9354c6c76 100644 --- a/src/front/wgsl/parse/ast.rs +++ b/src/front/wgsl/parse/ast.rs @@ -370,6 +370,9 @@ pub enum ConstructorType<'a> { size: ArraySize<'a>, }, + /// Ray description. + RayDesc, + /// Constructing a value of a known Naga IR type. /// /// This variant is produced only during lowering, when we have Naga types diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index f082ec1c4..e4a0d160f 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -441,6 +441,7 @@ impl Parser { })) } "array" => ast::ConstructorType::PartialArray, + "RayDesc" => ast::ConstructorType::RayDesc, "atomic" | "binding_array" | "sampler" @@ -622,6 +623,18 @@ impl Parser { let num = res.map_err(|err| Error::BadNumber(span, err))?; ast::Expression::Literal(ast::Literal::Number(num)) } + (Token::Word("RAY_FLAG_NONE"), _) => { + let _ = lexer.next(); + ast::Expression::Literal(ast::Literal::Number(Number::U32(0))) + } + (Token::Word("RAY_FLAG_TERMINATE_ON_FIRST_HIT"), _) => { + let _ = lexer.next(); + ast::Expression::Literal(ast::Literal::Number(Number::U32(4))) + } + (Token::Word("RAY_QUERY_INTERSECTION_NONE"), _) => { + let _ = lexer.next(); + ast::Expression::Literal(ast::Literal::Number(Number::U32(0))) + } (Token::Word(word), span) => { let start = lexer.start_byte_offset(); let _ = lexer.next(); diff --git a/src/lib.rs b/src/lib.rs index efb05c8ff..9344fd0a5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -107,6 +107,9 @@ Naga's rules for when `Expression`s are evaluated are as follows: [`Atomic`] statement, representing the result of the atomic operation, is evaluated when the `Atomic` statement is executed. +- Similarly, an [`RayQueryProceedResult`] expression, which is a boolean + indicating if the ray query is finished. + - All other expressions are evaluated when the (unique) [`Statement::Emit`] statement that covers them is executed. @@ -1441,6 +1444,13 @@ pub enum Expression { /// This doesn't match the semantics of spirv's `OpArrayLength`, which must be passed /// a pointer to a structure containing a runtime array in its' last field. ArrayLength(Handle), + /// Result of `rayQueryProceed`. + RayQueryProceedResult, + /// Result of `rayQueryGet*Intersection`. + RayQueryGetIntersection { + query: Handle, + committed: bool, + }, } pub use block::Block; @@ -1779,6 +1789,19 @@ pub struct EntryPoint { pub function: Function, } +/// Set of special types that can be optionally generated by the frontends. +#[derive(Debug, Default)] +#[cfg_attr(feature = "clone", derive(Clone))] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +pub struct SpecialTypes { + /// Type for `RayDesc`. + ray_desc: Option>, + /// Type for `RayIntersection`. + ray_intersection: Option>, +} + /// Shader module. /// /// A module is a set of constants, global variables and functions, as well as @@ -1798,6 +1821,8 @@ pub struct EntryPoint { pub struct Module { /// Arena for the types defined in this module. pub types: UniqueArena, + /// Dictionary of special type handles. + pub special_types: SpecialTypes, /// Arena for the constants defined in this module. pub constants: Arena, /// Arena for the global variables defined in this module. diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index b9ac46831..f7a4ba94d 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -193,11 +193,14 @@ pub enum ResolveError { IncompatibleOperands(String), #[error("Function argument {0} doesn't exist")] FunctionArgumentNotFound(u32), + #[error("Special type is not registered within the module")] + MissingSpecialType, } pub struct ResolveContext<'a> { pub constants: &'a Arena, pub types: &'a UniqueArena, + pub special_types: &'a crate::SpecialTypes, pub global_vars: &'a Arena, pub local_vars: &'a Arena, pub functions: &'a Arena, @@ -205,6 +208,23 @@ pub struct ResolveContext<'a> { } impl<'a> ResolveContext<'a> { + /// Initialize a resolve context from the module. + pub fn with_locals( + module: &'a crate::Module, + local_vars: &'a Arena, + arguments: &'a [crate::FunctionArgument], + ) -> Self { + Self { + constants: &module.constants, + types: &module.types, + special_types: &module.special_types, + global_vars: &module.global_variables, + local_vars, + functions: &module.functions, + arguments, + } + } + /// Determine the type of `expr`. /// /// The `past` argument must be a closure that can resolve the types of any @@ -867,6 +887,17 @@ impl<'a> ResolveContext<'a> { kind: crate::ScalarKind::Uint, width: 4, }), + crate::Expression::RayQueryProceedResult => TypeResolution::Value(Ti::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }), + crate::Expression::RayQueryGetIntersection { .. } => { + let result = self + .special_types + .ray_intersection + .ok_or(ResolveError::MissingSpecialType)?; + TypeResolution::Handle(result) + } }) } } diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 8d1943098..e9b155b6e 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -686,7 +686,7 @@ impl FunctionInfo { requirements: UniformityRequirements::empty(), }, E::CallResult(function) => other_functions[function.index()].uniformity.clone(), - E::AtomicResult { .. } => Uniformity { + E::AtomicResult { .. } | E::RayQueryProceedResult => Uniformity { non_uniform_result: Some(handle), requirements: UniformityRequirements::empty(), }, @@ -694,6 +694,13 @@ impl FunctionInfo { non_uniform_result: self.add_ref_impl(expr, GlobalUse::QUERY), requirements: UniformityRequirements::empty(), }, + E::RayQueryGetIntersection { + query, + committed: _, + } => Uniformity { + non_uniform_result: self.add_ref(query), + requirements: UniformityRequirements::empty(), + }, }; let ty = resolve_context.resolve(expression, |h| Ok(&self[h].ty))?; @@ -934,14 +941,8 @@ impl ModuleInfo { expressions: vec![ExpressionInfo::new(); fun.expressions.len()].into_boxed_slice(), sampling: crate::FastHashSet::default(), }; - let resolve_context = ResolveContext { - constants: &module.constants, - types: &module.types, - global_vars: &module.global_variables, - local_vars: &fun.local_variables, - functions: &module.functions, - arguments: &fun.arguments, - }; + let resolve_context = + ResolveContext::with_locals(module, &fun.local_variables, &fun.arguments); for (handle, expr) in fun.expressions.iter() { if let Err(source) = info.process_expression( @@ -1064,6 +1065,7 @@ fn uniform_control_flow() { let resolve_context = ResolveContext { constants: &constant_arena, types: &type_arena, + special_types: &crate::SpecialTypes::default(), global_vars: &global_var_arena, local_vars: &Arena::new(), functions: &Arena::new(), diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 9063eb061..408dccaf1 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1427,6 +1427,7 @@ impl super::Validator { return Err(ExpressionError::InvalidArrayType(expr)); } }, + E::RayQueryProceedResult | E::RayQueryGetIntersection { .. } => ShaderStages::all(), }; Ok(stages) } diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 20d8448a1..1257eb1bd 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -39,6 +39,7 @@ impl super::Validator { ref functions, ref global_variables, ref types, + ref special_types, } = module; // NOTE: Types being first is important. All other forms of validation depend on this. @@ -194,6 +195,13 @@ impl super::Validator { validate_function(Some(function_handle), function)?; } + if let Some(ty) = special_types.ray_desc { + validate_type(ty)?; + } + if let Some(ty) = special_types.ray_intersection { + validate_type(ty)?; + } + Ok(()) } @@ -379,10 +387,16 @@ impl super::Validator { handle.check_dep(function)?; } } - crate::Expression::AtomicResult { .. } => (), + crate::Expression::AtomicResult { .. } | crate::Expression::RayQueryProceedResult => (), crate::Expression::ArrayLength(array) => { handle.check_dep(array)?; } + crate::Expression::RayQueryGetIntersection { + query, + committed: _, + } => { + handle.check_dep(query)?; + } } Ok(()) } diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 13dbd7576..d9ee9f540 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -440,7 +440,9 @@ impl super::Validator { match types[var.ty].inner { crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } - | crate::TypeInner::BindingArray { .. } => {} + | crate::TypeInner::BindingArray { .. } + | crate::TypeInner::AccelerationStructure + | crate::TypeInner::RayQuery => {} _ => { return Err(GlobalVariableError::InvalidType(var.space)); } diff --git a/src/valid/type.rs b/src/valid/type.rs index 23f6ef4d1..2a2d5e733 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -622,10 +622,14 @@ impl super::Validator { Ti::Image { .. } | Ti::Sampler { .. } => { TypeInfo::new(TypeFlags::ARGUMENT, Alignment::ONE) } - Ti::AccelerationStructure | Ti::RayQuery => { + Ti::AccelerationStructure => { self.require_type_capability(Capabilities::RAY_QUERY)?; TypeInfo::new(TypeFlags::empty(), Alignment::ONE) } + Ti::RayQuery => { + self.require_type_capability(Capabilities::RAY_QUERY)?; + TypeInfo::new(TypeFlags::DATA | TypeFlags::SIZED, Alignment::ONE) + } Ti::BindingArray { .. } => TypeInfo::new(TypeFlags::empty(), Alignment::ONE), }) } diff --git a/tests/in/ray-query.wgsl b/tests/in/ray-query.wgsl index b772e69d7..0aec9ca14 100644 --- a/tests/in/ray-query.wgsl +++ b/tests/in/ray-query.wgsl @@ -1,3 +1,4 @@ +@group(0) @binding(0) var acc_struct: acceleration_structure; /* @@ -12,24 +13,41 @@ let RAY_QUERY_INTERSECTION_AABB = 4u; struct RayDesc { flags: u32, cull_mask: u32, - origin: vec3, t_min: f32, - dir: vec3, t_max: f32, -}*/ + origin: vec3, + dir: vec3, +} + +struct RayIntersection { + kind: u32, + t: f32, + instance_custom_index: u32, + instance_id: u32, + sbt_record_offset: u32, + geometry_index: u32, + primitive_index: u32, + barycentrics: vec2, + front_face: bool, + //TODO: object ray direction, origin, matrices +} +*/ struct Output { visible: u32, } + +@group(0) @binding(1) var output: Output; -@compute +@compute @workgroup_size(1) fn main() { var rq: ray_query; - rayQueryInitialize(rq, acceleration_structure, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xFF, vec3(0.0), 0.1, vec3(0.0, 1.0, 0.0), 100.0)); + rayQueryInitialize(rq, acc_struct, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xFFu, 0.1, 100.0, vec3(0.0), vec3(0.0, 1.0, 0.0))); rayQueryProceed(rq); - output.visible = rayQueryGetCommittedIntersectionType(rq) == RAY_QUERY_COMMITTED_INTERSECTION_NONE; + let intersection = rayQueryGetCommittedIntersection(rq); + output.visible = u32(intersection.kind == RAY_QUERY_INTERSECTION_NONE); } diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index e544ee1a5..41772b933 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -333,6 +333,10 @@ ), ), ], + special_types: ( + ray_desc: None, + ray_intersection: None, + ), constants: [ ( name: None, diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 00cab8e88..1be31e6ef 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -38,6 +38,10 @@ ), ), ], + special_types: ( + ray_desc: None, + ray_intersection: None, + ), constants: [ ( name: None, diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 8956076ef..9311f9e18 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -286,6 +286,10 @@ ), ), ], + special_types: ( + ray_desc: None, + ray_intersection: None, + ), constants: [ ( name: None, From 67d31b8e8c639c96bbac289428751c5abed2f433 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 16 Feb 2023 23:03:56 -0800 Subject: [PATCH 1967/2212] spv-out: basic ray query support --- src/back/spv/block.rs | 162 +++++++++++++++++++++++++++++++-- src/back/spv/image.rs | 2 +- src/back/spv/instructions.rs | 60 ++++++++++++ src/back/spv/mod.rs | 8 +- src/back/spv/writer.rs | 100 +++++++++++--------- src/front/wgsl/lower/mod.rs | 34 ++++++- src/lib.rs | 4 +- src/valid/handles.rs | 5 +- tests/in/ray-query.wgsl | 6 +- tests/out/spv/ray-query.spvasm | 81 +++++++++++++++++ 10 files changed, 400 insertions(+), 62 deletions(-) create mode 100644 tests/out/spv/ray-query.spvasm diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 090899b4a..77d7267fd 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1084,9 +1084,9 @@ impl<'w> BlockContext<'w> { } } crate::Expression::FunctionArgument(index) => self.function.parameter_id(index), - crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } => { - self.cached[expr_handle] - } + crate::Expression::CallResult(_) + | crate::Expression::AtomicResult { .. } + | crate::Expression::RayQueryProceedResult => self.cached[expr_handle], crate::Expression::As { expr, kind, @@ -1386,10 +1386,61 @@ impl<'w> BlockContext<'w> { id } crate::Expression::ArrayLength(expr) => self.write_runtime_array_length(expr, block)?, - //TODO - crate::Expression::RayQueryProceedResult => unreachable!(), - //TODO - crate::Expression::RayQueryGetIntersection { .. } => unreachable!(), + crate::Expression::RayQueryGetIntersection { query, committed } => { + let width = 4; + let query_id = self.cached[query]; + let intersection_id = self.writer.get_constant_scalar( + crate::ScalarValue::Uint( + spirv::RayQueryIntersection::RayQueryCommittedIntersectionKHR as _, + ), + width, + ); + if !committed { + return Err(Error::FeatureNotImplemented("candidate intersection")); + } + + let flag_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Uint, + width, + pointer_space: None, + })); + let kind_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionTypeKHR, + flag_type_id, + kind_id, + query_id, + intersection_id, + )); + + let scalar_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width, + pointer_space: None, + })); + let t_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionTKHR, + scalar_type_id, + t_id, + query_id, + intersection_id, + )); + + let id = self.gen_id(); + let intersection_type_id = self.get_type_id(LookupType::Handle( + self.ir_module.special_types.ray_intersection.unwrap(), + )); + //Note: the arguments must match `generate_ray_intersection_type` layout + block.body.push(Instruction::composite_construct( + intersection_type_id, + id, + &[kind_id, t_id], + )); + id + } }; self.cached[expr_handle] = id; @@ -2206,8 +2257,101 @@ impl<'w> BlockContext<'w> { crate::RayQueryFunction::Initialize { acceleration_structure, descriptor, - } => {} - crate::RayQueryFunction::Proceed => {} + } => { + //Note: composite extract indices and types must match `generate_ray_desc_type` + let desc_id = self.cached[descriptor]; + let acc_struct_id = self.get_image_id(acceleration_structure); + let width = 4; + + let flag_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Uint, + width, + pointer_space: None, + })); + let ray_flags_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + flag_type_id, + ray_flags_id, + desc_id, + &[0], + )); + let cull_mask_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + flag_type_id, + cull_mask_id, + desc_id, + &[1], + )); + + let scalar_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width, + pointer_space: None, + })); + let tmin_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + scalar_type_id, + tmin_id, + desc_id, + &[2], + )); + let tmax_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + scalar_type_id, + tmax_id, + desc_id, + &[3], + )); + + let vector_type_id = + self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Tri), + kind: crate::ScalarKind::Float, + width, + pointer_space: None, + })); + let ray_origin_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + vector_type_id, + ray_origin_id, + desc_id, + &[4], + )); + let ray_dir_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + vector_type_id, + ray_dir_id, + desc_id, + &[5], + )); + + block.body.push(Instruction::ray_query_initialize( + query_id, + acc_struct_id, + ray_flags_id, + cull_mask_id, + ray_origin_id, + tmin_id, + ray_dir_id, + tmax_id, + )); + } + crate::RayQueryFunction::Proceed { result } => { + let id = self.gen_id(); + self.cached[result] = id; + let result_type_id = + self.get_expression_type_id(&self.fun_info[result].ty); + + block.body.push(Instruction::ray_query_proceed( + result_type_id, + id, + query_id, + )); + } crate::RayQueryFunction::Terminate => {} } } diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 1a136af77..dc4f24994 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -373,7 +373,7 @@ impl<'w> BlockContext<'w> { }) } - fn get_image_id(&mut self, expr_handle: Handle) -> Word { + pub(super) fn get_image_id(&mut self, expr_handle: Handle) -> Word { let id = match self.ir_function.expressions[expr_handle] { crate::Expression::GlobalVariable(handle) => { self.writer.global_variables[handle.index()].handle_id diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index c21379018..3038d60d4 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -249,6 +249,18 @@ impl super::Instruction { instruction } + pub(super) fn type_acceleration_structure(id: Word) -> Self { + let mut instruction = Self::new(Op::TypeAccelerationStructureKHR); + instruction.set_result(id); + instruction + } + + pub(super) fn type_ray_query(id: Word) -> Self { + let mut instruction = Self::new(Op::TypeRayQueryKHR); + instruction.set_result(id); + instruction + } + pub(super) fn type_sampled_image(id: Word, image_type_id: Word) -> Self { let mut instruction = Self::new(Op::TypeSampledImage); instruction.set_result(id); @@ -627,6 +639,54 @@ impl super::Instruction { instruction } + // + // Ray Query Instructions + // + pub(super) fn ray_query_initialize( + query: Word, + acceleration_structure: Word, + ray_flags: Word, + cull_mask: Word, + ray_origin: Word, + ray_tmin: Word, + ray_dir: Word, + ray_tmax: Word, + ) -> Self { + let mut instruction = Self::new(Op::RayQueryInitializeKHR); + instruction.add_operand(query); + instruction.add_operand(acceleration_structure); + instruction.add_operand(ray_flags); + instruction.add_operand(cull_mask); + instruction.add_operand(ray_origin); + instruction.add_operand(ray_tmin); + instruction.add_operand(ray_dir); + instruction.add_operand(ray_tmax); + instruction + } + + pub(super) fn ray_query_proceed(result_type_id: Word, id: Word, query: Word) -> Self { + let mut instruction = Self::new(Op::RayQueryProceedKHR); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(query); + instruction + } + + pub(super) fn ray_query_get_intersection( + op: Op, + result_type_id: Word, + id: Word, + query: Word, + intersection: Word, + ) -> Self { + let mut instruction = Self::new(op); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(query); + instruction.add_operand(intersection); + instruction + } + // // Conversion Instructions // diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 72898219a..5fba4f0de 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -295,6 +295,8 @@ enum LocalType { base: Handle, size: u64, }, + AccelerationStructure, + RayQuery, } /// A type encountered during SPIR-V generation. @@ -383,7 +385,11 @@ fn make_local(inner: &crate::TypeInner) -> Option { class, } => LocalType::Image(LocalImageType::from_inner(dim, arrayed, class)), crate::TypeInner::Sampler { comparison: _ } => LocalType::Sampler, - _ => return None, + crate::TypeInner::AccelerationStructure => LocalType::AccelerationStructure, + crate::TypeInner::RayQuery => LocalType::RayQuery, + crate::TypeInner::Array { .. } + | crate::TypeInner::Struct { .. } + | crate::TypeInner::BindingArray { .. } => return None, }) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index fbc53feed..800a40ed6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -350,9 +350,12 @@ impl Writer { pointer_type_id, id, spirv::StorageClass::Function, - init_word.or_else(|| { - let type_id = self.get_type_id(LookupType::Handle(variable.ty)); - Some(self.write_constant_null(type_id)) + init_word.or_else(|| match ir_module.types[variable.ty].inner { + crate::TypeInner::RayQuery => None, + _ => { + let type_id = self.get_type_id(LookupType::Handle(variable.ty)); + Some(self.write_constant_null(type_id)) + } }), ); function @@ -814,47 +817,54 @@ impl Writer { } } - fn request_image_capabilities(&mut self, inner: &crate::TypeInner) -> Result<(), Error> { - if let crate::TypeInner::Image { - dim, - arrayed, - class, - } = *inner - { - let sampled = match class { - crate::ImageClass::Sampled { .. } => true, - crate::ImageClass::Depth { .. } => true, - crate::ImageClass::Storage { format, .. } => { - self.request_image_format_capabilities(format.into())?; - false - } - }; + fn request_type_capabilities(&mut self, inner: &crate::TypeInner) -> Result<(), Error> { + match *inner { + crate::TypeInner::Image { + dim, + arrayed, + class, + } => { + let sampled = match class { + crate::ImageClass::Sampled { .. } => true, + crate::ImageClass::Depth { .. } => true, + crate::ImageClass::Storage { format, .. } => { + self.request_image_format_capabilities(format.into())?; + false + } + }; - match dim { - crate::ImageDimension::D1 => { - if sampled { - self.require_any("sampled 1D images", &[spirv::Capability::Sampled1D])?; - } else { - self.require_any("1D storage images", &[spirv::Capability::Image1D])?; + match dim { + crate::ImageDimension::D1 => { + if sampled { + self.require_any("sampled 1D images", &[spirv::Capability::Sampled1D])?; + } else { + self.require_any("1D storage images", &[spirv::Capability::Image1D])?; + } } - } - crate::ImageDimension::Cube if arrayed => { - if sampled { - self.require_any( - "sampled cube array images", - &[spirv::Capability::SampledCubeArray], - )?; - } else { - self.require_any( - "cube array storage images", - &[spirv::Capability::ImageCubeArray], - )?; + crate::ImageDimension::Cube if arrayed => { + if sampled { + self.require_any( + "sampled cube array images", + &[spirv::Capability::SampledCubeArray], + )?; + } else { + self.require_any( + "cube array storage images", + &[spirv::Capability::ImageCubeArray], + )?; + } } + _ => {} } - _ => {} } + crate::TypeInner::AccelerationStructure => { + self.require_any("Acceleration Structure", &[spirv::Capability::RayQueryKHR])?; + } + crate::TypeInner::RayQuery => { + self.require_any("Ray Query", &[spirv::Capability::RayQueryKHR])?; + } + _ => {} } - Ok(()) } @@ -935,6 +945,8 @@ impl Writer { self.get_type_id(LookupType::Local(LocalType::BindingArray { base, size })); Instruction::type_pointer(id, spirv::StorageClass::UniformConstant, inner_ty) } + LocalType::AccelerationStructure => Instruction::type_acceleration_structure(id), + LocalType::RayQuery => Instruction::type_ray_query(id), }; instruction.to_words(&mut self.logical_layout.declarations); @@ -961,9 +973,9 @@ impl Writer { self.write_type_declaration_local(id, local); - // If it's an image type, request SPIR-V capabilities here, so - // write_type_declaration_local can stay infallible. - self.request_image_capabilities(&ty.inner)?; + // If it's an type that needs SPIR-V capabilities, request them now, + // so write_type_declaration_local can stay infallible. + self.request_type_capabilities(&ty.inner)?; id } @@ -1758,6 +1770,8 @@ impl Writer { .iter() .flat_map(|entry| entry.function.arguments.iter()) .any(|arg| has_view_index_check(ir_module, arg.binding.as_ref(), arg.ty)); + let has_ray_query = ir_module.special_types.ray_desc.is_some() + | ir_module.special_types.ray_intersection.is_some(); if self.physical_layout.version < 0x10300 && has_storage_buffers { // enable the storage buffer class on < SPV-1.3 @@ -1768,6 +1782,10 @@ impl Writer { Instruction::extension("SPV_KHR_multiview") .to_words(&mut self.logical_layout.extensions) } + if has_ray_query { + Instruction::extension("SPV_KHR_ray_query") + .to_words(&mut self.logical_layout.extensions) + } Instruction::type_void(self.void_type).to_words(&mut self.logical_layout.declarations); Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 971b3032b..8cba80fb5 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1915,7 +1915,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "rayQueryInitialize" => { let mut args = ctx.prepare_args(arguments, 3, span); - let query = self.expression(args.next()?, ctx.reborrow())?; + let query = self.ray_query_pointer(args.next()?, ctx.reborrow())?; let acceleration_structure = self.expression(args.next()?, ctx.reborrow())?; let descriptor = self.expression(args.next()?, ctx.reborrow())?; @@ -1935,15 +1935,15 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "rayQueryProceed" => { let mut args = ctx.prepare_args(arguments, 1, span); - let query = self.expression(args.next()?, ctx.reborrow())?; + let query = self.ray_query_pointer(args.next()?, ctx.reborrow())?; args.finish()?; - let fun = crate::RayQueryFunction::Proceed; - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); let result = ctx .naga_expressions .append(crate::Expression::RayQueryProceedResult, span); + let fun = crate::RayQueryFunction::Proceed { result }; + ctx.emitter.start(ctx.naga_expressions); ctx.block .push(crate::Statement::RayQuery { query, fun }, span); @@ -1951,7 +1951,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "rayQueryGetCommittedIntersection" => { let mut args = ctx.prepare_args(arguments, 1, span); - let query = self.expression(args.next()?, ctx.reborrow())?; + let query = self.ray_query_pointer(args.next()?, ctx.reborrow())?; args.finish()?; let _ = ctx.module.generate_ray_intersection_type(); @@ -2422,4 +2422,28 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { binding } + + fn ray_query_pointer( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let span = ctx.ast_expressions.get_span(expr); + let pointer = self.expression(expr, ctx.reborrow())?; + + ctx.grow_types(pointer)?; + match *ctx.resolved_inner(pointer) { + crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { + crate::TypeInner::RayQuery => Ok(pointer), + ref other => { + log::error!("Pointer type to {:?} passed to ray query op", other); + Err(Error::InvalidAtomicPointer(span)) + } + }, + ref other => { + log::error!("Type {:?} passed to ray query op", other); + Err(Error::InvalidAtomicPointer(span)) + } + } + } } diff --git a/src/lib.rs b/src/lib.rs index 9344fd0a5..162c23cd6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1492,7 +1492,9 @@ pub enum RayQueryFunction { acceleration_structure: Handle, descriptor: Handle, }, - Proceed, + Proceed { + result: Handle, + }, Terminate, } diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 1257eb1bd..c9e6cad50 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -520,7 +520,10 @@ impl super::Validator { validate_expr(acceleration_structure)?; validate_expr(descriptor)?; } - crate::RayQueryFunction::Proceed | crate::RayQueryFunction::Terminate => {} + crate::RayQueryFunction::Proceed { result } => { + validate_expr(result)?; + } + crate::RayQueryFunction::Terminate => {} } Ok(()) } diff --git a/tests/in/ray-query.wgsl b/tests/in/ray-query.wgsl index 0aec9ca14..7b1053bdc 100644 --- a/tests/in/ray-query.wgsl +++ b/tests/in/ray-query.wgsl @@ -44,10 +44,10 @@ var output: Output; fn main() { var rq: ray_query; - rayQueryInitialize(rq, acc_struct, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xFFu, 0.1, 100.0, vec3(0.0), vec3(0.0, 1.0, 0.0))); + rayQueryInitialize(&rq, acc_struct, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xFFu, 0.1, 100.0, vec3(0.0), vec3(0.0, 1.0, 0.0))); - rayQueryProceed(rq); + rayQueryProceed(&rq); - let intersection = rayQueryGetCommittedIntersection(rq); + let intersection = rayQueryGetCommittedIntersection(&rq); output.visible = u32(intersection.kind == RAY_QUERY_INTERSECTION_NONE); } diff --git a/tests/out/spv/ray-query.spvasm b/tests/out/spv/ray-query.spvasm new file mode 100644 index 000000000..455a8bffe --- /dev/null +++ b/tests/out/spv/ray-query.spvasm @@ -0,0 +1,81 @@ +; SPIR-V +; Version: 1.4 +; Generator: rspirv +; Bound: 52 +OpCapability RayQueryKHR +OpCapability Shader +OpExtension "SPV_KHR_ray_query" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %26 "main" %18 %20 +OpExecutionMode %26 LocalSize 1 1 1 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %16 0 Offset 0 +OpMemberDecorate %16 1 Offset 4 +OpMemberDecorate %16 2 Offset 8 +OpMemberDecorate %16 3 Offset 12 +OpMemberDecorate %16 4 Offset 16 +OpMemberDecorate %16 5 Offset 32 +OpMemberDecorate %17 0 Offset 0 +OpMemberDecorate %17 1 Offset 4 +OpDecorate %18 DescriptorSet 0 +OpDecorate %18 Binding 0 +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 1 +OpDecorate %21 Block +OpMemberDecorate %21 0 Offset 0 +%2 = OpTypeVoid +%4 = OpTypeInt 32 0 +%3 = OpConstant %4 4 +%5 = OpConstant %4 255 +%7 = OpTypeFloat 32 +%6 = OpConstant %7 0.1 +%8 = OpConstant %7 100.0 +%9 = OpConstant %7 0.0 +%10 = OpConstant %7 1.0 +%11 = OpConstant %4 0 +%12 = OpTypeAccelerationStructureNV +%13 = OpTypeStruct %4 +%14 = OpTypeRayQueryKHR +%15 = OpTypeVector %7 3 +%16 = OpTypeStruct %4 %4 %7 %7 %15 %15 +%17 = OpTypeStruct %4 %7 +%19 = OpTypePointer UniformConstant %12 +%18 = OpVariable %19 UniformConstant +%21 = OpTypeStruct %13 +%22 = OpTypePointer StorageBuffer %21 +%20 = OpVariable %22 StorageBuffer +%24 = OpTypePointer Function %14 +%27 = OpTypeFunction %2 +%29 = OpTypePointer StorageBuffer %13 +%42 = OpTypeBool +%43 = OpConstant %4 1 +%47 = OpTypePointer StorageBuffer %4 +%26 = OpFunction %2 None %27 +%25 = OpLabel +%23 = OpVariable %24 Function +%28 = OpLoad %12 %18 +%30 = OpAccessChain %29 %20 %11 +OpBranch %31 +%31 = OpLabel +%32 = OpCompositeConstruct %15 %9 %9 %9 +%33 = OpCompositeConstruct %15 %9 %10 %9 +%34 = OpCompositeConstruct %16 %3 %5 %6 %8 %32 %33 +%35 = OpCompositeExtract %4 %34 0 +%36 = OpCompositeExtract %4 %34 1 +%37 = OpCompositeExtract %7 %34 2 +%38 = OpCompositeExtract %7 %34 3 +%39 = OpCompositeExtract %15 %34 4 +%40 = OpCompositeExtract %15 %34 5 +OpRayQueryInitializeKHR %23 %28 %35 %36 %39 %37 %40 %38 +%41 = OpRayQueryProceedKHR %42 %23 +%44 = OpRayQueryGetIntersectionTypeKHR %4 %23 %43 +%45 = OpRayQueryGetIntersectionTKHR %7 %23 %43 +%46 = OpCompositeConstruct %17 %44 %45 +%48 = OpCompositeExtract %4 %46 0 +%49 = OpIEqual %42 %48 %11 +%50 = OpSelect %4 %49 %43 %11 +%51 = OpAccessChain %47 %30 %11 +OpStore %51 %50 +OpReturn +OpFunctionEnd \ No newline at end of file From 13ee4369cccd03666fcb52f1b6da43d6f4e9feaa Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 17 Feb 2023 21:50:31 -0800 Subject: [PATCH 1968/2212] clippy fixes --- src/back/spv/instructions.rs | 1 + src/front/wgsl/lower/mod.rs | 3 +-- src/lib.rs | 1 + src/proc/typifier.rs | 2 +- src/valid/type.rs | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 3038d60d4..96d027828 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -642,6 +642,7 @@ impl super::Instruction { // // Ray Query Instructions // + #[allow(clippy::too_many_arguments)] pub(super) fn ray_query_initialize( query: Word, acceleration_structure: Word, diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 8cba80fb5..730a33815 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -234,8 +234,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { /// [`self.resolved_inner(handle)`]: ExpressionContext::resolved_inner /// [`Typifier`]: Typifier fn grow_types(&mut self, handle: Handle) -> Result<&mut Self, Error<'a>> { - let resolve_ctx = - ResolveContext::with_locals(&self.module, self.local_vars, self.arguments); + let resolve_ctx = ResolveContext::with_locals(self.module, self.local_vars, self.arguments); self.typifier .grow(handle, self.naga_expressions, &resolve_ctx) .map_err(Error::InvalidResolve)?; diff --git a/src/lib.rs b/src/lib.rs index 162c23cd6..bf5f9a3a2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -169,6 +169,7 @@ need to be stored in a local variable to be carried upwards in the statement tree. [`AtomicResult`]: Expression::AtomicResult +[`RayQueryProceedResult`]: Expression::RayQueryProceedResult [`CallResult`]: Expression::CallResult [`Constant`]: Expression::Constant [`Derivative`]: Expression::Derivative diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index f7a4ba94d..0bb9019a2 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -209,7 +209,7 @@ pub struct ResolveContext<'a> { impl<'a> ResolveContext<'a> { /// Initialize a resolve context from the module. - pub fn with_locals( + pub const fn with_locals( module: &'a crate::Module, local_vars: &'a Arena, arguments: &'a [crate::FunctionArgument], diff --git a/src/valid/type.rs b/src/valid/type.rs index 2a2d5e733..d8dd37d09 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -205,7 +205,7 @@ impl TypeInfo { } impl super::Validator { - fn require_type_capability(&self, capability: Capabilities) -> Result<(), TypeError> { + const fn require_type_capability(&self, capability: Capabilities) -> Result<(), TypeError> { if self.capabilities.contains(capability) { Ok(()) } else { From ab9c36441fc80f73394cf8152b52218860f5eafb Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 21 Feb 2023 23:31:32 -0800 Subject: [PATCH 1969/2212] fill up the ray query intersection struct --- src/back/spv/block.rs | 154 +------------------ src/back/spv/mod.rs | 1 + src/back/spv/ray.rs | 273 +++++++++++++++++++++++++++++++++ src/front/type_gen.rs | 91 ++++++++++- tests/in/ray-query.wgsl | 3 +- tests/out/spv/ray-query.spvasm | 122 +++++++++------ 6 files changed, 440 insertions(+), 204 deletions(-) create mode 100644 src/back/spv/ray.rs diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 77d7267fd..b28b94fe9 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1387,59 +1387,10 @@ impl<'w> BlockContext<'w> { } crate::Expression::ArrayLength(expr) => self.write_runtime_array_length(expr, block)?, crate::Expression::RayQueryGetIntersection { query, committed } => { - let width = 4; - let query_id = self.cached[query]; - let intersection_id = self.writer.get_constant_scalar( - crate::ScalarValue::Uint( - spirv::RayQueryIntersection::RayQueryCommittedIntersectionKHR as _, - ), - width, - ); if !committed { return Err(Error::FeatureNotImplemented("candidate intersection")); } - - let flag_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Uint, - width, - pointer_space: None, - })); - let kind_id = self.gen_id(); - block.body.push(Instruction::ray_query_get_intersection( - spirv::Op::RayQueryGetIntersectionTypeKHR, - flag_type_id, - kind_id, - query_id, - intersection_id, - )); - - let scalar_type_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width, - pointer_space: None, - })); - let t_id = self.gen_id(); - block.body.push(Instruction::ray_query_get_intersection( - spirv::Op::RayQueryGetIntersectionTKHR, - scalar_type_id, - t_id, - query_id, - intersection_id, - )); - - let id = self.gen_id(); - let intersection_type_id = self.get_type_id(LookupType::Handle( - self.ir_module.special_types.ray_intersection.unwrap(), - )); - //Note: the arguments must match `generate_ray_intersection_type` layout - block.body.push(Instruction::composite_construct( - intersection_type_id, - id, - &[kind_id, t_id], - )); - id + self.write_ray_query_get_intersection(query, block) } }; @@ -2252,108 +2203,7 @@ impl<'w> BlockContext<'w> { block.body.push(instruction); } crate::Statement::RayQuery { query, ref fun } => { - let query_id = self.cached[query]; - match *fun { - crate::RayQueryFunction::Initialize { - acceleration_structure, - descriptor, - } => { - //Note: composite extract indices and types must match `generate_ray_desc_type` - let desc_id = self.cached[descriptor]; - let acc_struct_id = self.get_image_id(acceleration_structure); - let width = 4; - - let flag_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Uint, - width, - pointer_space: None, - })); - let ray_flags_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - flag_type_id, - ray_flags_id, - desc_id, - &[0], - )); - let cull_mask_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - flag_type_id, - cull_mask_id, - desc_id, - &[1], - )); - - let scalar_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Float, - width, - pointer_space: None, - })); - let tmin_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - scalar_type_id, - tmin_id, - desc_id, - &[2], - )); - let tmax_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - scalar_type_id, - tmax_id, - desc_id, - &[3], - )); - - let vector_type_id = - self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: Some(crate::VectorSize::Tri), - kind: crate::ScalarKind::Float, - width, - pointer_space: None, - })); - let ray_origin_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - vector_type_id, - ray_origin_id, - desc_id, - &[4], - )); - let ray_dir_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - vector_type_id, - ray_dir_id, - desc_id, - &[5], - )); - - block.body.push(Instruction::ray_query_initialize( - query_id, - acc_struct_id, - ray_flags_id, - cull_mask_id, - ray_origin_id, - tmin_id, - ray_dir_id, - tmax_id, - )); - } - crate::RayQueryFunction::Proceed { result } => { - let id = self.gen_id(); - self.cached[result] = id; - let result_type_id = - self.get_expression_type_id(&self.fun_info[result].ty); - - block.body.push(Instruction::ray_query_proceed( - result_type_id, - id, - query_id, - )); - } - crate::RayQueryFunction::Terminate => {} - } + self.write_ray_query_function(query, fun, &mut block); } } } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 5fba4f0de..9b084911b 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -10,6 +10,7 @@ mod image; mod index; mod instructions; mod layout; +mod ray; mod recyclable; mod selection; mod writer; diff --git a/src/back/spv/ray.rs b/src/back/spv/ray.rs new file mode 100644 index 000000000..79eb2ff97 --- /dev/null +++ b/src/back/spv/ray.rs @@ -0,0 +1,273 @@ +/*! +Generating SPIR-V for ray query operations. +*/ + +use super::{Block, BlockContext, Instruction, LocalType, LookupType}; +use crate::arena::Handle; + +impl<'w> BlockContext<'w> { + pub(super) fn write_ray_query_function( + &mut self, + query: Handle, + function: &crate::RayQueryFunction, + block: &mut Block, + ) { + let query_id = self.cached[query]; + match *function { + crate::RayQueryFunction::Initialize { + acceleration_structure, + descriptor, + } => { + //Note: composite extract indices and types must match `generate_ray_desc_type` + let desc_id = self.cached[descriptor]; + let acc_struct_id = self.get_image_id(acceleration_structure); + let width = 4; + + let flag_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Uint, + width, + pointer_space: None, + })); + let ray_flags_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + flag_type_id, + ray_flags_id, + desc_id, + &[0], + )); + let cull_mask_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + flag_type_id, + cull_mask_id, + desc_id, + &[1], + )); + + let scalar_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width, + pointer_space: None, + })); + let tmin_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + scalar_type_id, + tmin_id, + desc_id, + &[2], + )); + let tmax_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + scalar_type_id, + tmax_id, + desc_id, + &[3], + )); + + let vector_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Tri), + kind: crate::ScalarKind::Float, + width, + pointer_space: None, + })); + let ray_origin_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + vector_type_id, + ray_origin_id, + desc_id, + &[4], + )); + let ray_dir_id = self.gen_id(); + block.body.push(Instruction::composite_extract( + vector_type_id, + ray_dir_id, + desc_id, + &[5], + )); + + block.body.push(Instruction::ray_query_initialize( + query_id, + acc_struct_id, + ray_flags_id, + cull_mask_id, + ray_origin_id, + tmin_id, + ray_dir_id, + tmax_id, + )); + } + crate::RayQueryFunction::Proceed { result } => { + let id = self.gen_id(); + self.cached[result] = id; + let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty); + + block + .body + .push(Instruction::ray_query_proceed(result_type_id, id, query_id)); + } + crate::RayQueryFunction::Terminate => {} + } + } + + pub(super) fn write_ray_query_get_intersection( + &mut self, + query: Handle, + block: &mut Block, + ) -> spirv::Word { + let width = 4; + let query_id = self.cached[query]; + let intersection_id = self.writer.get_constant_scalar( + crate::ScalarValue::Uint( + spirv::RayQueryIntersection::RayQueryCommittedIntersectionKHR as _, + ), + width, + ); + + let flag_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Uint, + width, + pointer_space: None, + })); + let kind_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionTypeKHR, + flag_type_id, + kind_id, + query_id, + intersection_id, + )); + let instance_custom_index_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionInstanceCustomIndexKHR, + flag_type_id, + instance_custom_index_id, + query_id, + intersection_id, + )); + let instance_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionInstanceIdKHR, + flag_type_id, + instance_id, + query_id, + intersection_id, + )); + let sbt_record_offset_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR, + flag_type_id, + sbt_record_offset_id, + query_id, + intersection_id, + )); + let geometry_index_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionGeometryIndexKHR, + flag_type_id, + geometry_index_id, + query_id, + intersection_id, + )); + let primitive_index_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionPrimitiveIndexKHR, + flag_type_id, + primitive_index_id, + query_id, + intersection_id, + )); + + let scalar_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Float, + width, + pointer_space: None, + })); + let t_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionTKHR, + scalar_type_id, + t_id, + query_id, + intersection_id, + )); + + let barycentrics_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: Some(crate::VectorSize::Bi), + kind: crate::ScalarKind::Float, + width, + pointer_space: None, + })); + let barycentrics_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionBarycentricsKHR, + barycentrics_type_id, + barycentrics_id, + query_id, + intersection_id, + )); + + let bool_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + vector_size: None, + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + pointer_space: None, + })); + let front_face_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionFrontFaceKHR, + bool_type_id, + front_face_id, + query_id, + intersection_id, + )); + + let transform_type_id = self.get_type_id(LookupType::Local(LocalType::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Tri, + width, + })); + let object_to_world_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionObjectToWorldKHR, + transform_type_id, + object_to_world_id, + query_id, + intersection_id, + )); + let world_to_object_id = self.gen_id(); + block.body.push(Instruction::ray_query_get_intersection( + spirv::Op::RayQueryGetIntersectionWorldToObjectKHR, + transform_type_id, + world_to_object_id, + query_id, + intersection_id, + )); + + let id = self.gen_id(); + let intersection_type_id = self.get_type_id(LookupType::Handle( + self.ir_module.special_types.ray_intersection.unwrap(), + )); + //Note: the arguments must match `generate_ray_intersection_type` layout + block.body.push(Instruction::composite_construct( + intersection_type_id, + id, + &[ + kind_id, + t_id, + instance_custom_index_id, + instance_id, + sbt_record_offset_id, + geometry_index_id, + primitive_index_id, + barycentrics_id, + front_face_id, + object_to_world_id, + world_to_object_id, + ], + )); + id + } +} diff --git a/src/front/type_gen.rs b/src/front/type_gen.rs index 18d9ddd54..bb734ac69 100644 --- a/src/front/type_gen.rs +++ b/src/front/type_gen.rs @@ -5,6 +5,7 @@ Type generators. use crate::{arena::Handle, span::Span}; impl crate::Module { + //Note: has to match `struct RayDesc` pub(super) fn generate_ray_desc_type(&mut self) -> Handle { if let Some(handle) = self.special_types.ray_desc { return handle; @@ -95,6 +96,7 @@ impl crate::Module { handle } + //Note: has to match `struct RayIntersection` pub(super) fn generate_ray_intersection_type(&mut self) -> Handle { if let Some(handle) = self.special_types.ray_intersection { return handle; @@ -121,6 +123,38 @@ impl crate::Module { }, Span::UNDEFINED, ); + let ty_barycentrics = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + width, + size: crate::VectorSize::Bi, + kind: crate::ScalarKind::Float, + }, + }, + Span::UNDEFINED, + ); + let ty_bool = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + width: crate::BOOL_WIDTH, + kind: crate::ScalarKind::Bool, + }, + }, + Span::UNDEFINED, + ); + let ty_transform = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Tri, + width, + }, + }, + Span::UNDEFINED, + ); let handle = self.types.insert( crate::Type { @@ -139,9 +173,62 @@ impl crate::Module { binding: None, offset: 4, }, - //TODO: the rest + crate::StructMember { + name: Some("instance_custom_index".to_string()), + ty: ty_flag, + binding: None, + offset: 8, + }, + crate::StructMember { + name: Some("instance_id".to_string()), + ty: ty_flag, + binding: None, + offset: 12, + }, + crate::StructMember { + name: Some("sbt_record_offset".to_string()), + ty: ty_flag, + binding: None, + offset: 16, + }, + crate::StructMember { + name: Some("geometry_index".to_string()), + ty: ty_flag, + binding: None, + offset: 20, + }, + crate::StructMember { + name: Some("primitive_index".to_string()), + ty: ty_flag, + binding: None, + offset: 24, + }, + crate::StructMember { + name: Some("barycentrics".to_string()), + ty: ty_barycentrics, + binding: None, + offset: 28, + }, + crate::StructMember { + name: Some("front_face".to_string()), + ty: ty_bool, + binding: None, + offset: 36, + }, + crate::StructMember { + name: Some("object_to_world".to_string()), + ty: ty_transform, + binding: None, + offset: 48, + }, + crate::StructMember { + name: Some("world_to_object".to_string()), + ty: ty_transform, + binding: None, + offset: 112, + }, ], - span: 8, + span: 176, }, }, Span::UNDEFINED, diff --git a/tests/in/ray-query.wgsl b/tests/in/ray-query.wgsl index 7b1053bdc..5eabf3a2d 100644 --- a/tests/in/ray-query.wgsl +++ b/tests/in/ray-query.wgsl @@ -29,7 +29,8 @@ struct RayIntersection { primitive_index: u32, barycentrics: vec2, front_face: bool, - //TODO: object ray direction, origin, matrices + object_to_world: mat4x3, + world_to_object: mat4x3, } */ diff --git a/tests/out/spv/ray-query.spvasm b/tests/out/spv/ray-query.spvasm index 455a8bffe..6bc41ee30 100644 --- a/tests/out/spv/ray-query.spvasm +++ b/tests/out/spv/ray-query.spvasm @@ -1,14 +1,14 @@ ; SPIR-V ; Version: 1.4 ; Generator: rspirv -; Bound: 52 +; Bound: 63 OpCapability RayQueryKHR OpCapability Shader OpExtension "SPV_KHR_ray_query" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %26 "main" %18 %20 -OpExecutionMode %26 LocalSize 1 1 1 +OpEntryPoint GLCompute %29 "main" %21 %23 +OpExecutionMode %29 LocalSize 1 1 1 OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %16 0 Offset 0 OpMemberDecorate %16 1 Offset 4 @@ -16,14 +16,27 @@ OpMemberDecorate %16 2 Offset 8 OpMemberDecorate %16 3 Offset 12 OpMemberDecorate %16 4 Offset 16 OpMemberDecorate %16 5 Offset 32 -OpMemberDecorate %17 0 Offset 0 -OpMemberDecorate %17 1 Offset 4 -OpDecorate %18 DescriptorSet 0 -OpDecorate %18 Binding 0 -OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 1 -OpDecorate %21 Block -OpMemberDecorate %21 0 Offset 0 +OpMemberDecorate %20 0 Offset 0 +OpMemberDecorate %20 1 Offset 4 +OpMemberDecorate %20 2 Offset 8 +OpMemberDecorate %20 3 Offset 12 +OpMemberDecorate %20 4 Offset 16 +OpMemberDecorate %20 5 Offset 20 +OpMemberDecorate %20 6 Offset 24 +OpMemberDecorate %20 7 Offset 28 +OpMemberDecorate %20 8 Offset 36 +OpMemberDecorate %20 9 Offset 48 +OpMemberDecorate %20 9 ColMajor +OpMemberDecorate %20 9 MatrixStride 16 +OpMemberDecorate %20 10 Offset 112 +OpMemberDecorate %20 10 ColMajor +OpMemberDecorate %20 10 MatrixStride 16 +OpDecorate %21 DescriptorSet 0 +OpDecorate %21 Binding 0 +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 1 +OpDecorate %24 Block +OpMemberDecorate %24 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 4 @@ -39,43 +52,54 @@ OpMemberDecorate %21 0 Offset 0 %14 = OpTypeRayQueryKHR %15 = OpTypeVector %7 3 %16 = OpTypeStruct %4 %4 %7 %7 %15 %15 -%17 = OpTypeStruct %4 %7 -%19 = OpTypePointer UniformConstant %12 -%18 = OpVariable %19 UniformConstant -%21 = OpTypeStruct %13 -%22 = OpTypePointer StorageBuffer %21 -%20 = OpVariable %22 StorageBuffer -%24 = OpTypePointer Function %14 -%27 = OpTypeFunction %2 -%29 = OpTypePointer StorageBuffer %13 -%42 = OpTypeBool -%43 = OpConstant %4 1 -%47 = OpTypePointer StorageBuffer %4 -%26 = OpFunction %2 None %27 -%25 = OpLabel -%23 = OpVariable %24 Function -%28 = OpLoad %12 %18 -%30 = OpAccessChain %29 %20 %11 -OpBranch %31 -%31 = OpLabel -%32 = OpCompositeConstruct %15 %9 %9 %9 -%33 = OpCompositeConstruct %15 %9 %10 %9 -%34 = OpCompositeConstruct %16 %3 %5 %6 %8 %32 %33 -%35 = OpCompositeExtract %4 %34 0 -%36 = OpCompositeExtract %4 %34 1 -%37 = OpCompositeExtract %7 %34 2 -%38 = OpCompositeExtract %7 %34 3 -%39 = OpCompositeExtract %15 %34 4 -%40 = OpCompositeExtract %15 %34 5 -OpRayQueryInitializeKHR %23 %28 %35 %36 %39 %37 %40 %38 -%41 = OpRayQueryProceedKHR %42 %23 -%44 = OpRayQueryGetIntersectionTypeKHR %4 %23 %43 -%45 = OpRayQueryGetIntersectionTKHR %7 %23 %43 -%46 = OpCompositeConstruct %17 %44 %45 -%48 = OpCompositeExtract %4 %46 0 -%49 = OpIEqual %42 %48 %11 -%50 = OpSelect %4 %49 %43 %11 -%51 = OpAccessChain %47 %30 %11 -OpStore %51 %50 +%17 = OpTypeVector %7 2 +%18 = OpTypeBool +%19 = OpTypeMatrix %15 4 +%20 = OpTypeStruct %4 %7 %4 %4 %4 %4 %4 %17 %18 %19 %19 +%22 = OpTypePointer UniformConstant %12 +%21 = OpVariable %22 UniformConstant +%24 = OpTypeStruct %13 +%25 = OpTypePointer StorageBuffer %24 +%23 = OpVariable %25 StorageBuffer +%27 = OpTypePointer Function %14 +%30 = OpTypeFunction %2 +%32 = OpTypePointer StorageBuffer %13 +%45 = OpConstant %4 1 +%58 = OpTypePointer StorageBuffer %4 +%29 = OpFunction %2 None %30 +%28 = OpLabel +%26 = OpVariable %27 Function +%31 = OpLoad %12 %21 +%33 = OpAccessChain %32 %23 %11 +OpBranch %34 +%34 = OpLabel +%35 = OpCompositeConstruct %15 %9 %9 %9 +%36 = OpCompositeConstruct %15 %9 %10 %9 +%37 = OpCompositeConstruct %16 %3 %5 %6 %8 %35 %36 +%38 = OpCompositeExtract %4 %37 0 +%39 = OpCompositeExtract %4 %37 1 +%40 = OpCompositeExtract %7 %37 2 +%41 = OpCompositeExtract %7 %37 3 +%42 = OpCompositeExtract %15 %37 4 +%43 = OpCompositeExtract %15 %37 5 +OpRayQueryInitializeKHR %26 %31 %38 %39 %42 %40 %43 %41 +%44 = OpRayQueryProceedKHR %18 %26 +%46 = OpRayQueryGetIntersectionTypeKHR %4 %26 %45 +%47 = OpRayQueryGetIntersectionInstanceCustomIndexKHR %4 %26 %45 +%48 = OpRayQueryGetIntersectionInstanceIdKHR %4 %26 %45 +%49 = OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR %4 %26 %45 +%50 = OpRayQueryGetIntersectionGeometryIndexKHR %4 %26 %45 +%51 = OpRayQueryGetIntersectionPrimitiveIndexKHR %4 %26 %45 +%52 = OpRayQueryGetIntersectionTKHR %7 %26 %45 +%53 = OpRayQueryGetIntersectionBarycentricsKHR %17 %26 %45 +%54 = OpRayQueryGetIntersectionFrontFaceKHR %18 %26 %45 +%55 = OpRayQueryGetIntersectionObjectToWorldKHR %19 %26 %45 +%56 = OpRayQueryGetIntersectionWorldToObjectKHR %19 %26 %45 +%57 = OpCompositeConstruct %20 %46 %52 %47 %48 %49 %50 %51 %53 %54 %55 %56 +%59 = OpCompositeExtract %4 %57 0 +%60 = OpIEqual %18 %59 %11 +%61 = OpSelect %4 %60 %45 %11 +%62 = OpAccessChain %58 %33 %11 +OpStore %62 %61 OpReturn OpFunctionEnd \ No newline at end of file From 22e341b039a8cf7dde6b789f20ff6cca0926ba69 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Wed, 22 Feb 2023 23:14:49 -0800 Subject: [PATCH 1970/2212] wgsl: handle RayDesc/RayIntersection at the type decl level instead of an AST constructor --- src/front/wgsl/lower/construction.rs | 4 ---- src/front/wgsl/lower/mod.rs | 23 +++++++++++++++----- src/front/wgsl/parse/ast.rs | 5 ++--- src/front/wgsl/parse/mod.rs | 3 ++- tests/out/spv/ray-query.spvasm | 32 ++++++++++++++-------------- 5 files changed, 38 insertions(+), 29 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 4b0371573..723d4441f 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -660,10 +660,6 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }); ConcreteConstructorHandle::Type(ty) } - ast::ConstructorType::RayDesc => { - let ty = ctx.module.generate_ray_desc_type(); - ConcreteConstructorHandle::Type(ty) - } ast::ConstructorType::Type(ty) => ConcreteConstructorHandle::Type(ty), }; diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 730a33815..8df3460b2 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -637,14 +637,21 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { module: &mut module, }; - for decl in self.index.visit_ordered() { - let span = tu.decls.get_span(decl); - let decl = &tu.decls[decl]; + for decl_handle in self.index.visit_ordered() { + let span = tu.decls.get_span(decl_handle); + let decl = &tu.decls[decl_handle]; + + //TODO: find a nicer way? + if let Some(dep) = decl.dependencies.iter().find(|dep| dep.ident == "RayDesc") { + let ty_handle = ctx.module.generate_ray_desc_type(); + ctx.globals + .insert(dep.ident, LoweredGlobalDecl::Type(ty_handle)); + } match decl.kind { ast::GlobalDeclKind::Fn(ref f) => { - let decl = self.function(f, span, ctx.reborrow())?; - ctx.globals.insert(f.name.name, decl); + let lowered_decl = self.function(f, span, ctx.reborrow())?; + ctx.globals.insert(f.name.name, lowered_decl); } ast::GlobalDeclKind::Var(ref v) => { let ty = self.resolve_ast_type(v.ty, ctx.reborrow())?; @@ -2302,6 +2309,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }, } } + ast::Type::RayDesc => { + return Ok(ctx.module.generate_ray_desc_type()); + } + ast::Type::RayIntersection => { + return Ok(ctx.module.generate_ray_intersection_type()); + } ast::Type::User(ref ident) => { return match ctx.globals.get(ident.name) { Some(&LoweredGlobalDecl::Type(handle)) => Ok(handle), diff --git a/src/front/wgsl/parse/ast.rs b/src/front/wgsl/parse/ast.rs index 9354c6c76..2a56ac6f8 100644 --- a/src/front/wgsl/parse/ast.rs +++ b/src/front/wgsl/parse/ast.rs @@ -231,6 +231,8 @@ pub enum Type<'a> { }, AccelerationStructure, RayQuery, + RayDesc, + RayIntersection, BindingArray { base: Handle>, size: ArraySize<'a>, @@ -370,9 +372,6 @@ pub enum ConstructorType<'a> { size: ArraySize<'a>, }, - /// Ray description. - RayDesc, - /// Constructing a value of a known Naga IR type. /// /// This variant is produced only during lowering, when we have Naga types diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index e4a0d160f..7a030259b 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -441,7 +441,6 @@ impl Parser { })) } "array" => ast::ConstructorType::PartialArray, - "RayDesc" => ast::ConstructorType::RayDesc, "atomic" | "binding_array" | "sampler" @@ -1382,6 +1381,8 @@ impl Parser { } "acceleration_structure" => ast::Type::AccelerationStructure, "ray_query" => ast::Type::RayQuery, + "RayDesc" => ast::Type::RayDesc, + "RayIntersection" => ast::Type::RayIntersection, _ => return Ok(None), })) } diff --git a/tests/out/spv/ray-query.spvasm b/tests/out/spv/ray-query.spvasm index 6bc41ee30..1a1a18bba 100644 --- a/tests/out/spv/ray-query.spvasm +++ b/tests/out/spv/ray-query.spvasm @@ -10,12 +10,12 @@ OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %29 "main" %21 %23 OpExecutionMode %29 LocalSize 1 1 1 OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %16 0 Offset 0 -OpMemberDecorate %16 1 Offset 4 -OpMemberDecorate %16 2 Offset 8 -OpMemberDecorate %16 3 Offset 12 -OpMemberDecorate %16 4 Offset 16 -OpMemberDecorate %16 5 Offset 32 +OpMemberDecorate %15 0 Offset 0 +OpMemberDecorate %15 1 Offset 4 +OpMemberDecorate %15 2 Offset 8 +OpMemberDecorate %15 3 Offset 12 +OpMemberDecorate %15 4 Offset 16 +OpMemberDecorate %15 5 Offset 32 OpMemberDecorate %20 0 Offset 0 OpMemberDecorate %20 1 Offset 4 OpMemberDecorate %20 2 Offset 8 @@ -49,19 +49,19 @@ OpMemberDecorate %24 0 Offset 0 %11 = OpConstant %4 0 %12 = OpTypeAccelerationStructureNV %13 = OpTypeStruct %4 -%14 = OpTypeRayQueryKHR -%15 = OpTypeVector %7 3 -%16 = OpTypeStruct %4 %4 %7 %7 %15 %15 +%14 = OpTypeVector %7 3 +%15 = OpTypeStruct %4 %4 %7 %7 %14 %14 +%16 = OpTypeRayQueryKHR %17 = OpTypeVector %7 2 %18 = OpTypeBool -%19 = OpTypeMatrix %15 4 +%19 = OpTypeMatrix %14 4 %20 = OpTypeStruct %4 %7 %4 %4 %4 %4 %4 %17 %18 %19 %19 %22 = OpTypePointer UniformConstant %12 %21 = OpVariable %22 UniformConstant %24 = OpTypeStruct %13 %25 = OpTypePointer StorageBuffer %24 %23 = OpVariable %25 StorageBuffer -%27 = OpTypePointer Function %14 +%27 = OpTypePointer Function %16 %30 = OpTypeFunction %2 %32 = OpTypePointer StorageBuffer %13 %45 = OpConstant %4 1 @@ -73,15 +73,15 @@ OpMemberDecorate %24 0 Offset 0 %33 = OpAccessChain %32 %23 %11 OpBranch %34 %34 = OpLabel -%35 = OpCompositeConstruct %15 %9 %9 %9 -%36 = OpCompositeConstruct %15 %9 %10 %9 -%37 = OpCompositeConstruct %16 %3 %5 %6 %8 %35 %36 +%35 = OpCompositeConstruct %14 %9 %9 %9 +%36 = OpCompositeConstruct %14 %9 %10 %9 +%37 = OpCompositeConstruct %15 %3 %5 %6 %8 %35 %36 %38 = OpCompositeExtract %4 %37 0 %39 = OpCompositeExtract %4 %37 1 %40 = OpCompositeExtract %7 %37 2 %41 = OpCompositeExtract %7 %37 3 -%42 = OpCompositeExtract %15 %37 4 -%43 = OpCompositeExtract %15 %37 5 +%42 = OpCompositeExtract %14 %37 4 +%43 = OpCompositeExtract %14 %37 5 OpRayQueryInitializeKHR %26 %31 %38 %39 %42 %40 %43 %41 %44 = OpRayQueryProceedKHR %18 %26 %46 = OpRayQueryGetIntersectionTypeKHR %4 %26 %45 From 532d1ad51017f7c62b0b2f79c2b4d1eab658249d Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 26 Feb 2023 00:27:03 -0800 Subject: [PATCH 1971/2212] msl: ray query support --- src/back/mod.rs | 23 +++ src/back/msl/mod.rs | 10 +- src/back/msl/writer.rs | 199 +++++++++++++++++++-- tests/in/ray-query.param.ron | 8 + tests/in/ray-query.wgsl | 13 +- tests/out/msl/binding-arrays.msl | 2 +- tests/out/msl/bounds-check-image-rzsw.msl | 2 +- tests/out/msl/bounds-check-zero-atomic.msl | 2 +- tests/out/msl/bounds-check-zero.msl | 2 +- tests/out/msl/policy-mix.msl | 2 +- tests/out/msl/ray-query.msl | 58 ++++++ tests/out/msl/resource-binding-map.msl | 2 +- tests/snapshots.rs | 2 +- 13 files changed, 295 insertions(+), 30 deletions(-) create mode 100644 tests/out/msl/ray-query.msl diff --git a/src/back/mod.rs b/src/back/mod.rs index 6755983c0..ac37a498a 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -218,3 +218,26 @@ impl crate::Statement { } } } + +bitflags::bitflags! { + /// Ray flags. + #[derive(Default)] + pub struct RayFlag: u32 { + const OPAQUE = 0x01; + const NO_OPAQUE = 0x02; + const TERMINATE_ON_FIRST_HIT = 0x04; + const SKIP_CLOSEST_HIT_SHADER = 0x08; + const CULL_FRONT_FACING = 0x10; + const CULL_BACK_FACING = 0x20; + const CULL_OPAQUE = 0x40; + const CULL_NO_OPAQUE = 0x80; + const SKIP_TRIANGLES = 0x100; + const SKIP_AABBS = 0x200; + } +} + +#[repr(u32)] +enum RayIntersectionType { + Triangle = 1, + BoundingBox = 4, +} diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index d79497660..3174d4b75 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -314,10 +314,7 @@ impl Options { match slot { Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { buffer: Some(slot), - texture: None, - sampler: None, - binding_array_size: None, - mutable: false, + ..Default::default() })), None if self.fake_missing_bindings => Ok(ResolvedBinding::User { prefix: "fake", @@ -338,10 +335,7 @@ impl Options { match slot { Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { buffer: Some(slot), - texture: None, - sampler: None, - binding_array_size: None, - mutable: false, + ..Default::default() })), None if self.fake_missing_bindings => Ok(ResolvedBinding::User { prefix: "fake", diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 2ec5bad33..88600a8f1 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -25,6 +25,13 @@ const WRAPPED_ARRAY_FIELD: &str = "inner"; // Some more general handling of pointers is needed to be implemented here. const ATOMIC_REFERENCE: &str = "&"; +const RT_NAMESPACE: &str = "metal::raytracing"; +const RAY_QUERY_TYPE: &str = "_RayQuery"; +const RAY_QUERY_FIELD_INTERSECTOR: &str = "intersector"; +const RAY_QUERY_FIELD_INTERSECTION: &str = "intersection"; +const RAY_QUERY_FIELD_READY: &str = "ready"; +const RAY_QUERY_FUN_MAP_INTERSECTION: &str = "_map_intersection_type"; + /// Write the Metal name for a Naga numeric type: scalar, vector, or matrix. /// /// The `sizes` slice determines whether this function writes a @@ -194,8 +201,11 @@ impl<'a> Display for TypeContext<'a> { crate::TypeInner::Sampler { comparison: _ } => { write!(out, "{NAMESPACE}::sampler") } - crate::TypeInner::AccelerationStructure | crate::TypeInner::RayQuery => { - unreachable!("Ray queries are not supported yet"); + crate::TypeInner::AccelerationStructure => { + write!(out, "{RT_NAMESPACE}::instance_acceleration_structure") + } + crate::TypeInner::RayQuery => { + write!(out, "{RAY_QUERY_TYPE}") } crate::TypeInner::BindingArray { base, size } => { let base_tyname = Self { @@ -1865,8 +1875,39 @@ impl Writer { write!(self.out, ")")?; } } - // hot supported yet - crate::Expression::RayQueryGetIntersection { .. } => unreachable!(), + crate::Expression::RayQueryGetIntersection { query, committed } => { + if !committed { + unimplemented!() + } + let ty = context.module.special_types.ray_intersection.unwrap(); + let type_name = &self.names[&NameKey::Type(ty)]; + write!(self.out, "{type_name} {{{RAY_QUERY_FUN_MAP_INTERSECTION}(")?; + self.put_expression(query, context, true)?; + write!(self.out, ".{RAY_QUERY_FIELD_INTERSECTION}.type)")?; + let fields = [ + "distance", + "user_instance_id", + "instance_id", + "", // SBT offset + "geometry_id", + "primitive_id", + "triangle_barycentric_coord", + "triangle_front_facing", + "", // padding + "object_to_world_transform", + "world_to_object_transform", + ]; + for field in fields { + write!(self.out, ", ")?; + if field.is_empty() { + write!(self.out, "{{}}")?; + } else { + self.put_expression(query, context, true)?; + write!(self.out, ".{RAY_QUERY_FIELD_INTERSECTION}.{field}")?; + } + } + write!(self.out, "}}")?; + } } Ok(()) } @@ -2320,6 +2361,7 @@ impl Writer { ) { use crate::Expression; self.need_bake_expressions.clear(); + for (expr_handle, expr) in func.expressions.iter() { // Expressions whose reference count is above the // threshold should always be stored in temporaries. @@ -2327,6 +2369,16 @@ impl Writer { let min_ref_count = func.expressions[expr_handle].bake_ref_count(); if min_ref_count <= expr_info.ref_count { self.need_bake_expressions.insert(expr_handle); + } else { + match expr_info.ty { + // force ray desc to be baked: it's used multiple times internally + TypeResolution::Handle(h) + if Some(h) == context.module.special_types.ray_desc => + { + self.need_bake_expressions.insert(expr_handle); + } + _ => {} + } } if let Expression::Math { fun, arg, arg1, .. } = *expr { @@ -2338,11 +2390,11 @@ impl Writer { // times, once for each component (see `put_dot_product`), so to // avoid duplicated evaluation, we must bake integer operands. - use crate::TypeInner; // check what kind of product this is depending // on the resolve type of the Dot function itself - let inner = context.resolve_type(expr_handle); - if let TypeInner::Scalar { kind, .. } = *inner { + if let crate::TypeInner::Scalar { kind, .. } = + *context.resolve_type(expr_handle) + { match kind { crate::ScalarKind::Sint | crate::ScalarKind::Uint => { self.need_bake_expressions.insert(arg); @@ -2763,7 +2815,100 @@ impl Writer { // done writeln!(self.out, ";")?; } - crate::Statement::RayQuery { .. } => unreachable!(), + crate::Statement::RayQuery { query, ref fun } => { + match *fun { + crate::RayQueryFunction::Initialize { + acceleration_structure, + descriptor, + } => { + //TODO: how to deal with winding? + write!(self.out, "{level}")?; + self.put_expression(query, &context.expression, true)?; + writeln!(self.out, ".{RAY_QUERY_FIELD_INTERSECTOR}.assume_geometry_type({RT_NAMESPACE}::geometry_type::triangle);")?; + { + let f_opaque = back::RayFlag::CULL_OPAQUE.bits(); + let f_no_opaque = back::RayFlag::CULL_NO_OPAQUE.bits(); + write!(self.out, "{level}")?; + self.put_expression(query, &context.expression, true)?; + write!( + self.out, + ".{RAY_QUERY_FIELD_INTERSECTOR}.set_opacity_cull_mode((" + )?; + self.put_expression(descriptor, &context.expression, true)?; + write!(self.out, ".flags & {f_opaque}) != 0 ? {RT_NAMESPACE}::opacity_cull_mode::opaque : (")?; + self.put_expression(descriptor, &context.expression, true)?; + write!(self.out, ".flags & {f_no_opaque}) != 0 ? {RT_NAMESPACE}::opacity_cull_mode::non_opaque : ")?; + writeln!(self.out, "{RT_NAMESPACE}::opacity_cull_mode::none);")?; + } + { + let f_opaque = back::RayFlag::OPAQUE.bits(); + let f_no_opaque = back::RayFlag::NO_OPAQUE.bits(); + write!(self.out, "{level}")?; + self.put_expression(query, &context.expression, true)?; + write!(self.out, ".{RAY_QUERY_FIELD_INTERSECTOR}.force_opacity((")?; + self.put_expression(descriptor, &context.expression, true)?; + write!(self.out, ".flags & {f_opaque}) != 0 ? {RT_NAMESPACE}::forced_opacity::opaque : (")?; + self.put_expression(descriptor, &context.expression, true)?; + write!(self.out, ".flags & {f_no_opaque}) != 0 ? {RT_NAMESPACE}::forced_opacity::non_opaque : ")?; + writeln!(self.out, "{RT_NAMESPACE}::forced_opacity::none);")?; + } + { + let flag = back::RayFlag::TERMINATE_ON_FIRST_HIT.bits(); + write!(self.out, "{level}")?; + self.put_expression(query, &context.expression, true)?; + write!( + self.out, + ".{RAY_QUERY_FIELD_INTERSECTOR}.accept_any_intersection((" + )?; + self.put_expression(descriptor, &context.expression, true)?; + writeln!(self.out, ".flags & {flag}) != 0);")?; + } + + write!(self.out, "{level}")?; + self.put_expression(query, &context.expression, true)?; + write!(self.out, ".{RAY_QUERY_FIELD_INTERSECTION} = ")?; + self.put_expression(query, &context.expression, true)?; + write!( + self.out, + ".{RAY_QUERY_FIELD_INTERSECTOR}.intersect({RT_NAMESPACE}::ray(" + )?; + self.put_expression(descriptor, &context.expression, true)?; + write!(self.out, ".origin, ")?; + self.put_expression(descriptor, &context.expression, true)?; + write!(self.out, ".dir, ")?; + self.put_expression(descriptor, &context.expression, true)?; + write!(self.out, ".tmin, ")?; + self.put_expression(descriptor, &context.expression, true)?; + write!(self.out, ".tmax), ")?; + self.put_expression(acceleration_structure, &context.expression, true)?; + write!(self.out, ", ")?; + self.put_expression(descriptor, &context.expression, true)?; + write!(self.out, ".cull_mask);")?; + + write!(self.out, "{level}")?; + self.put_expression(query, &context.expression, true)?; + writeln!(self.out, ".{RAY_QUERY_FIELD_READY} = true;")?; + } + crate::RayQueryFunction::Proceed { result } => { + write!(self.out, "{level}")?; + let name = format!("{}{}", back::BAKE_PREFIX, result.index()); + self.start_baking_expression(result, &context.expression, &name)?; + self.named_expressions.insert(result, name); + self.put_expression(query, &context.expression, true)?; + writeln!(self.out, ".{RAY_QUERY_FIELD_READY};")?; + //TODO: actually proceed? + + write!(self.out, "{level}")?; + self.put_expression(query, &context.expression, true)?; + writeln!(self.out, ".{RAY_QUERY_FIELD_READY} = false;")?; + } + crate::RayQueryFunction::Terminate => { + write!(self.out, "{level}")?; + self.put_expression(query, &context.expression, true)?; + writeln!(self.out, ".{RAY_QUERY_FIELD_INTERSECTION}.abort();")?; + } + } + } } } @@ -2875,14 +3020,41 @@ impl Writer { writeln!(self.out)?; // Work around Metal bug where `uint` is not available by default writeln!(self.out, "using {NAMESPACE}::uint;")?; - writeln!(self.out)?; + if module.types.iter().any(|(_, t)| match t.inner { + crate::TypeInner::RayQuery => true, + _ => false, + }) { + let tab = back::INDENT; + writeln!(self.out, "struct {RAY_QUERY_TYPE} {{")?; + let full_type = format!("{RT_NAMESPACE}::intersector<{RT_NAMESPACE}::instancing, {RT_NAMESPACE}::triangle_data, {RT_NAMESPACE}::world_space_data>"); + writeln!(self.out, "{tab}{full_type} {RAY_QUERY_FIELD_INTERSECTOR};")?; + writeln!( + self.out, + "{tab}{full_type}::result_type {RAY_QUERY_FIELD_INTERSECTION};" + )?; + writeln!(self.out, "{tab}bool {RAY_QUERY_FIELD_READY} = false;")?; + writeln!(self.out, "}};")?; + writeln!(self.out, "constexpr {NAMESPACE}::uint {RAY_QUERY_FUN_MAP_INTERSECTION}(const {RT_NAMESPACE}::intersection_type ty) {{")?; + let v_triangle = back::RayIntersectionType::Triangle as u32; + let v_bbox = back::RayIntersectionType::BoundingBox as u32; + writeln!( + self.out, + "{tab}return ty=={RT_NAMESPACE}::intersection_type::triangle ? {v_triangle} : " + )?; + writeln!( + self.out, + "{tab}{tab}ty=={RT_NAMESPACE}::intersection_type::bounding_box ? {v_bbox} : 0;" + )?; + writeln!(self.out, "}}")?; + } if options .bounds_check_policies .contains(index::BoundsCheckPolicy::ReadZeroSkipWrite) { self.put_default_constructible()?; } + writeln!(self.out)?; { let mut indices = vec![]; @@ -2924,11 +3096,12 @@ impl Writer { /// /// [`ReadZeroSkipWrite`]: index::BoundsCheckPolicy::ReadZeroSkipWrite fn put_default_constructible(&mut self) -> BackendResult { + let tab = back::INDENT; writeln!(self.out, "struct DefaultConstructible {{")?; - writeln!(self.out, " template")?; - writeln!(self.out, " operator T() && {{")?; - writeln!(self.out, " return T {{}};")?; - writeln!(self.out, " }}")?; + writeln!(self.out, "{tab}template")?; + writeln!(self.out, "{tab}operator T() && {{")?; + writeln!(self.out, "{tab}{tab}return T {{}};")?; + writeln!(self.out, "{tab}}}")?; writeln!(self.out, "}};")?; Ok(()) } diff --git a/tests/in/ray-query.param.ron b/tests/in/ray-query.param.ron index 9d8666954..c400db8c6 100644 --- a/tests/in/ray-query.param.ron +++ b/tests/in/ray-query.param.ron @@ -3,4 +3,12 @@ spv: ( version: (1, 4), ), + msl: ( + lang_version: (2, 4), + spirv_cross_compatibility: false, + fake_missing_bindings: true, + zero_initialize_workgroup_memory: false, + per_entry_point_map: {}, + inline_samplers: [], + ), ) diff --git a/tests/in/ray-query.wgsl b/tests/in/ray-query.wgsl index 5eabf3a2d..b755d8f60 100644 --- a/tests/in/ray-query.wgsl +++ b/tests/in/ray-query.wgsl @@ -2,8 +2,17 @@ var acc_struct: acceleration_structure; /* -let RAY_FLAG_NONE = 0u; -let RAY_FLAG_TERMINATE_ON_FIRST_HIT = 4u; +let RAY_FLAG_NONE = 0x00u; +let RAY_FLAG_OPAQUE = 0x01u; +let RAY_FLAG_NO_OPAQUE = 0x02u; +let RAY_FLAG_TERMINATE_ON_FIRST_HIT = 0x04u; +let RAY_FLAG_SKIP_CLOSEST_HIT_SHADER = 0x08u; +let RAY_FLAG_CULL_FRONT_FACING = 0x10u; +let RAY_FLAG_CULL_BACK_FACING = 0x20u; +let RAY_FLAG_CULL_OPAQUE = 0x40u; +let RAY_FLAG_CULL_NO_OPAQUE = 0x80u; +let RAY_FLAG_SKIP_TRIANGLES = 0x100u; +let RAY_FLAG_SKIP_AABBS = 0x200u; let RAY_QUERY_INTERSECTION_NONE = 0u; let RAY_QUERY_INTERSECTION_TRIANGLE = 1u; diff --git a/tests/out/msl/binding-arrays.msl b/tests/out/msl/binding-arrays.msl index da1078b5d..694f79452 100644 --- a/tests/out/msl/binding-arrays.msl +++ b/tests/out/msl/binding-arrays.msl @@ -3,13 +3,13 @@ #include using metal::uint; - struct DefaultConstructible { template operator T() && { return T {}; } }; + struct UniformIndex { uint index; }; diff --git a/tests/out/msl/bounds-check-image-rzsw.msl b/tests/out/msl/bounds-check-image-rzsw.msl index 9032af14c..eeb03c984 100644 --- a/tests/out/msl/bounds-check-image-rzsw.msl +++ b/tests/out/msl/bounds-check-image-rzsw.msl @@ -3,13 +3,13 @@ #include using metal::uint; - struct DefaultConstructible { template operator T() && { return T {}; } }; + constant metal::int2 const_type_4_ = {0, 0}; constant metal::int3 const_type_7_ = {0, 0, 0}; constant metal::float4 const_type_2_ = {0.0, 0.0, 0.0, 0.0}; diff --git a/tests/out/msl/bounds-check-zero-atomic.msl b/tests/out/msl/bounds-check-zero-atomic.msl index 95028ee79..daaa07923 100644 --- a/tests/out/msl/bounds-check-zero-atomic.msl +++ b/tests/out/msl/bounds-check-zero-atomic.msl @@ -3,13 +3,13 @@ #include using metal::uint; - struct DefaultConstructible { template operator T() && { return T {}; } }; + struct _mslBufferSizes { uint size0; }; diff --git a/tests/out/msl/bounds-check-zero.msl b/tests/out/msl/bounds-check-zero.msl index fece92de3..816983d98 100644 --- a/tests/out/msl/bounds-check-zero.msl +++ b/tests/out/msl/bounds-check-zero.msl @@ -3,13 +3,13 @@ #include using metal::uint; - struct DefaultConstructible { template operator T() && { return T {}; } }; + struct _mslBufferSizes { uint size0; }; diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index 842c57e58..7eb0c61ed 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -3,13 +3,13 @@ #include using metal::uint; - struct DefaultConstructible { template operator T() && { return T {}; } }; + struct type_1 { metal::float4 inner[10]; }; diff --git a/tests/out/msl/ray-query.msl b/tests/out/msl/ray-query.msl new file mode 100644 index 000000000..2a0973787 --- /dev/null +++ b/tests/out/msl/ray-query.msl @@ -0,0 +1,58 @@ +// language: metal2.4 +#include +#include + +using metal::uint; +struct _RayQuery { + metal::raytracing::intersector intersector; + metal::raytracing::intersector::result_type intersection; + bool ready = false; +}; +constexpr metal::uint _map_intersection_type(const metal::raytracing::intersection_type ty) { + return ty==metal::raytracing::intersection_type::triangle ? 1 : + ty==metal::raytracing::intersection_type::bounding_box ? 4 : 0; +} + +struct Output { + uint visible_; +}; +struct RayDesc { + uint flags; + uint cull_mask; + float tmin; + float tmax; + metal::float3 origin; + metal::float3 dir; +}; +struct RayIntersection { + uint kind; + float t; + uint instance_custom_index; + uint instance_id; + uint sbt_record_offset; + uint geometry_index; + uint primitive_index; + metal::float2 barycentrics; + bool front_face; + char _pad9[11]; + metal::float4x3 object_to_world; + metal::float4x3 world_to_object; +}; + +kernel void main_( + metal::raytracing::instance_acceleration_structure acc_struct [[user(fake0)]] +, device Output& output [[user(fake0)]] +) { + _RayQuery rq = {}; + RayDesc _e12 = RayDesc {4u, 255u, 0.10000000149011612, 100.0, metal::float3(0.0), metal::float3(0.0, 1.0, 0.0)}; + rq.intersector.assume_geometry_type(metal::raytracing::geometry_type::triangle); + rq.intersector.set_opacity_cull_mode((_e12.flags & 64) != 0 ? metal::raytracing::opacity_cull_mode::opaque : (_e12.flags & 128) != 0 ? metal::raytracing::opacity_cull_mode::non_opaque : metal::raytracing::opacity_cull_mode::none); + rq.intersector.force_opacity((_e12.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (_e12.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none); + rq.intersector.accept_any_intersection((_e12.flags & 4) != 0); + rq.intersection = rq.intersector.intersect(metal::raytracing::ray(_e12.origin, _e12.dir, _e12.tmin, _e12.tmax), acc_struct, _e12.cull_mask); rq.ready = true; + bool _e13 = rq.ready; + rq.ready = false; + RayIntersection intersection = RayIntersection {_map_intersection_type(rq.intersection.type), rq.intersection.distance, rq.intersection.user_instance_id, rq.intersection.instance_id, {}, rq.intersection.geometry_id, rq.intersection.primitive_id, rq.intersection.triangle_barycentric_coord, rq.intersection.triangle_front_facing, {}, rq.intersection.object_to_world_transform, rq.intersection.world_to_object_transform}; + output.visible_ = static_cast(intersection.kind == 0u); + return; +} diff --git a/tests/out/msl/resource-binding-map.msl b/tests/out/msl/resource-binding-map.msl index 4e0b60132..b4a53d97b 100644 --- a/tests/out/msl/resource-binding-map.msl +++ b/tests/out/msl/resource-binding-map.msl @@ -3,7 +3,6 @@ #include using metal::uint; - struct DefaultConstructible { template operator T() && { @@ -11,6 +10,7 @@ struct DefaultConstructible { } }; + struct entry_point_oneInput { }; struct entry_point_oneOutput { diff --git a/tests/snapshots.rs b/tests/snapshots.rs index df94130a7..d968a0dfc 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -571,7 +571,7 @@ fn convert_wgsl() { ("sprite", Targets::SPIRV), ("force_point_size_vertex_shader_webgl", Targets::GLSL), ("invariant", Targets::GLSL), - ("ray-query", Targets::SPIRV), + ("ray-query", Targets::SPIRV | Targets::METAL), ]; for &(name, targets) in inputs.iter() { From 18710fee1ef98b492d2d29b5eec53faeab931c3c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 27 Feb 2023 12:42:57 -0800 Subject: [PATCH 1972/2212] Expand on the documentation for ray-tracing features. --- src/back/mod.rs | 9 ++++++- src/front/type_gen.rs | 29 +++++++++++++++++++-- src/lib.rs | 60 ++++++++++++++++++++++++++++++++++++++++--- src/valid/handles.rs | 2 +- 4 files changed, 92 insertions(+), 8 deletions(-) diff --git a/src/back/mod.rs b/src/back/mod.rs index ac37a498a..f51262524 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -220,7 +220,14 @@ impl crate::Statement { } bitflags::bitflags! { - /// Ray flags. + /// Ray flags, for a [`RayDesc`]'s `flags` field. + /// + /// Note that these exactly correspond to the SPIR-V "Ray Flags" mask, and + /// the SPIR-V backend passes them directly through to the + /// `OpRayQueryInitializeKHR` instruction. (We have to choose something, so + /// we might as well make one back end's life easier.) + /// + /// [`RayDesc`]: crate::Module::generate_ray_desc_type #[derive(Default)] pub struct RayFlag: u32 { const OPAQUE = 0x01; diff --git a/src/front/type_gen.rs b/src/front/type_gen.rs index bb734ac69..b695b5279 100644 --- a/src/front/type_gen.rs +++ b/src/front/type_gen.rs @@ -5,7 +5,21 @@ Type generators. use crate::{arena::Handle, span::Span}; impl crate::Module { - //Note: has to match `struct RayDesc` + /// Populate this module's [`SpecialTypes::ray_desc`] type. + /// + /// [`SpecialTypes::ray_desc`] is the type of the [`descriptor`] operand of + /// an [`Initialize`] [`RayQuery`] statement. In WGSL, it is a struct type + /// referred to as `RayDesc`. + /// + /// Backends consume values of this type to drive platform APIs, so if you + /// change any its fields, you must update the backends to match. Look for + /// backend code dealing with [`RayQueryFunction::Initialize`]. + /// + /// [`SpecialTypes::ray_desc`]: crate::SpecialTypes::ray_desc + /// [`descriptor`]: crate::RayQueryFunction::Initialize::descriptor + /// [`Initialize`]: crate::RayQueryFunction::Initialize + /// [`RayQuery`]: crate::Statement::RayQuery + /// [`RayQueryFunction::Initialize`]: crate::RayQueryFunction::Initialize pub(super) fn generate_ray_desc_type(&mut self) -> Handle { if let Some(handle) = self.special_types.ray_desc { return handle; @@ -96,7 +110,18 @@ impl crate::Module { handle } - //Note: has to match `struct RayIntersection` + /// Populate this module's [`SpecialTypes::ray_intersection`] type. + /// + /// [`SpecialTypes::ray_intersection`] is the type of a + /// `RayQueryGetIntersection` expression. In WGSL, it is a struct type + /// referred to as `RayIntersection`. + /// + /// Backends construct values of this type based on platform APIs, so if you + /// change any its fields, you must update the backends to match. Look for + /// the backend's handling for [`Expression::RayQueryGetIntersection`]. + /// + /// [`SpecialTypes::ray_intersection`]: crate::SpecialTypes::ray_intersection + /// [`Expression::RayQueryGetIntersection`]: crate::Expression::RayQueryGetIntersection pub(super) fn generate_ray_intersection_type(&mut self) -> Handle { if let Some(handle) = self.special_types.ray_intersection { return handle; diff --git a/src/lib.rs b/src/lib.rs index bf5f9a3a2..f91dc7ce5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -107,8 +107,10 @@ Naga's rules for when `Expression`s are evaluated are as follows: [`Atomic`] statement, representing the result of the atomic operation, is evaluated when the `Atomic` statement is executed. -- Similarly, an [`RayQueryProceedResult`] expression, which is a boolean - indicating if the ray query is finished. +- A [`RayQueryProceedResult`] expression, which is a boolean + indicating if the ray query is finished, is evaluated when the + [`RayQuery`] statement whose [`Proceed::result`] points to it is + executed. - All other expressions are evaluated when the (unique) [`Statement::Emit`] statement that covers them is executed. @@ -184,6 +186,9 @@ tree. [`Call`]: Statement::Call [`Emit`]: Statement::Emit [`Store`]: Statement::Store +[`RayQuery`]: Statement::RayQuery + +[`Proceed::result`]: RayQueryFunction::Proceed::result [`Validator::validate`]: valid::Validator::validate [`ModuleInfo`]: valid::ModuleInfo @@ -727,6 +732,7 @@ pub enum TypeInner { /// Opaque object representing an acceleration structure of geometry. AccelerationStructure, + /// Locally used handle for ray queries. RayQuery, @@ -1445,9 +1451,16 @@ pub enum Expression { /// This doesn't match the semantics of spirv's `OpArrayLength`, which must be passed /// a pointer to a structure containing a runtime array in its' last field. ArrayLength(Handle), - /// Result of `rayQueryProceed`. + + /// Result of a [`Proceed`] [`RayQuery`] statement. + /// + /// [`Proceed`]: RayQueryFunction::Proceed + /// [`RayQuery`]: Statement::RayQuery RayQueryProceedResult, - /// Result of `rayQueryGet*Intersection`. + + /// Return an intersection found by `query`. + /// + /// If `committed` is true, return the committed result available when RayQueryGetIntersection { query: Handle, committed: bool, @@ -1484,18 +1497,45 @@ pub struct SwitchCase { pub fall_through: bool, } +/// An operation that a [`RayQuery` statement] applies to its [`query`] operand. +/// +/// [`RayQuery` statement]: Statement::RayQuery +/// [`query`]: Statement::RayQuery::query #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum RayQueryFunction { + /// Initialize the `RayQuery` object. Initialize { + /// The acceleration structure within which this query should search for hits. + /// + /// The expression must be an [`AccelerationStructure`]. + /// + /// [`AccelerationStructure`]: TypeInner::AccelerationStructure acceleration_structure: Handle, + + #[allow(rustdoc::private_intra_doc_links)] + /// A struct of detailed parameters for the ray query. + /// + /// This expression should have the struct type given in + /// [`SpecialTypes::ray_desc`]. This is available in the WGSL + /// front end as the `RayDesc` type. descriptor: Handle, }, + + /// Start or continue the query given by the statement's [`query`] operand. + /// + /// After executing this statement, the `result` expression is a + /// [`Bool`] scalar indicating whether there are more intersection + /// candidates to consider. + /// + /// [`query`]: Statement::RayQuery::query + /// [`Bool`]: ScalarKind::Bool Proceed { result: Handle, }, + Terminate, } @@ -1673,7 +1713,12 @@ pub enum Statement { result: Option>, }, RayQuery { + /// The [`RayQuery`] object this statement operates on. + /// + /// [`RayQuery`]: TypeInner::RayQuery query: Handle, + + /// The specific operation we're performing on `query`. fun: RayQueryFunction, }, } @@ -1800,8 +1845,15 @@ pub struct EntryPoint { #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct SpecialTypes { /// Type for `RayDesc`. + /// + /// Call [`Module::generate_ray_desc_type`] to populate this if + /// needed and return the handle. ray_desc: Option>, + /// Type for `RayIntersection`. + /// + /// Call [`Module::generate_ray_intersection_type`] to populate + /// this if needed and return the handle. ray_intersection: Option>, } diff --git a/src/valid/handles.rs b/src/valid/handles.rs index c9e6cad50..fdd43cd58 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -1,4 +1,4 @@ -//! Implementation of [`super::Validator::validate_module_handles`]. +//! Implementation of `Validator::validate_module_handles`. use crate::{ arena::{BadHandle, BadRangeError}, From 024c197cc87fd39e20b03479446d015c60e3101e Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Fri, 17 Mar 2023 22:53:13 -0700 Subject: [PATCH 1973/2212] ray query: validation, better test --- src/valid/expression.rs | 23 +++- src/valid/function.rs | 95 +++++++++++--- tests/in/ray-query.wgsl | 14 +- tests/out/msl/ray-query.msl | 47 +++++-- tests/out/spv/ray-query.spvasm | 229 ++++++++++++++++++++------------- 5 files changed, 284 insertions(+), 124 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 408dccaf1..1a91fe4d0 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -35,6 +35,8 @@ pub enum ExpressionError { InvalidPointerType(Handle), #[error("Array length of {0:?} can't be done")] InvalidArrayType(Handle), + #[error("Get intersection of {0:?} can't be done")] + InvalidRayQueryType(Handle), #[error("Splatting {0:?} can't be done")] InvalidSplatType(Handle), #[error("Swizzling {0:?} can't be done")] @@ -1427,7 +1429,26 @@ impl super::Validator { return Err(ExpressionError::InvalidArrayType(expr)); } }, - E::RayQueryProceedResult | E::RayQueryGetIntersection { .. } => ShaderStages::all(), + E::RayQueryProceedResult => ShaderStages::all(), + E::RayQueryGetIntersection { + query, + committed: _, + } => match resolver[query] { + Ti::Pointer { + base, + space: crate::AddressSpace::Function, + } => match resolver.types[base].inner { + Ti::RayQuery => ShaderStages::all(), + ref other => { + log::error!("Intersection result of a pointer to {:?}", other); + return Err(ExpressionError::InvalidRayQueryType(query)); + } + }, + ref other => { + log::error!("Intersection result of {:?}", other); + return Err(ExpressionError::InvalidRayQueryType(query)); + } + }, }; Ok(stages) } diff --git a/src/valid/function.rs b/src/valid/function.rs index a13a07bcf..737f33dc2 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -47,8 +47,6 @@ pub enum AtomicError { InvalidPointer(Handle), #[error("Operand {0:?} has invalid type.")] InvalidOperand(Handle), - #[error("Result expression {0:?} has already been introduced earlier")] - ResultAlreadyInScope(Handle), #[error("Result type for {0:?} doesn't match the statement")] ResultTypeMismatch(Handle), } @@ -131,6 +129,14 @@ pub enum FunctionError { }, #[error("Atomic operation is invalid")] InvalidAtomic(#[from] AtomicError), + #[error("Ray Query {0:?} is not a local variable")] + InvalidRayQueryExpression(Handle), + #[error("Acceleration structure {0:?} is not a matching expression")] + InvalidAccelerationStructure(Handle), + #[error("Ray descriptor {0:?} is not a matching expression")] + InvalidRayDescriptor(Handle), + #[error("Ray Query {0:?} does not have a matching type")] + InvalidRayQueryType(Handle), #[error( "Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}" )] @@ -169,8 +175,10 @@ struct BlockContext<'a> { info: &'a FunctionInfo, expressions: &'a Arena, types: &'a UniqueArena, + local_vars: &'a Arena, global_vars: &'a Arena, functions: &'a Arena, + special_types: &'a crate::SpecialTypes, prev_infos: &'a [FunctionInfo], return_type: Option>, } @@ -188,8 +196,10 @@ impl<'a> BlockContext<'a> { info, expressions: &fun.expressions, types: &module.types, + local_vars: &fun.local_variables, global_vars: &module.global_variables, functions: &module.functions, + special_types: &module.special_types, prev_infos, return_type: fun.result.as_ref().map(|fr| fr.ty), } @@ -299,6 +309,21 @@ impl super::Validator { Ok(callee_info.available_stages) } + #[cfg(feature = "validate")] + fn emit_expression( + &mut self, + handle: Handle, + context: &BlockContext, + ) -> Result<(), WithSpan> { + if self.valid_expression_set.insert(handle.index()) { + self.valid_expression_list.push(handle); + Ok(()) + } else { + Err(FunctionError::ExpressionAlreadyInScope(handle) + .with_span_handle(handle, context.expressions)) + } + } + #[cfg(feature = "validate")] fn validate_atomic( &mut self, @@ -347,13 +372,7 @@ impl super::Validator { } } - if self.valid_expression_set.insert(result.index()) { - self.valid_expression_list.push(result); - } else { - return Err(AtomicError::ResultAlreadyInScope(result) - .with_span_handle(result, context.expressions) - .into_other()); - } + self.emit_expression(result, context)?; match context.expressions[result] { crate::Expression::AtomicResult { ty, comparison } if { @@ -401,12 +420,7 @@ impl super::Validator { match *statement { S::Emit(ref range) => { for handle in range.clone() { - if self.valid_expression_set.insert(handle.index()) { - self.valid_expression_list.push(handle); - } else { - return Err(FunctionError::ExpressionAlreadyInScope(handle) - .with_span_handle(handle, context.expressions)); - } + self.emit_expression(handle, context)?; } } S::Block(ref block) => { @@ -807,8 +821,55 @@ impl super::Validator { } => { self.validate_atomic(pointer, fun, value, result, context)?; } - S::RayQuery { query: _, fun: _ } => { - //TODO + S::RayQuery { query, ref fun } => { + let query_var = match *context.get_expression(query) { + crate::Expression::LocalVariable(var) => &context.local_vars[var], + ref other => { + log::error!("Unexpected ray query expression {other:?}"); + return Err(FunctionError::InvalidRayQueryExpression(query) + .with_span_static(span, "invalid query expression")); + } + }; + match context.types[query_var.ty].inner { + Ti::RayQuery => {} + ref other => { + log::error!("Unexpected ray query type {other:?}"); + return Err(FunctionError::InvalidRayQueryType(query_var.ty) + .with_span_static(span, "invalid query type")); + } + } + match *fun { + crate::RayQueryFunction::Initialize { + acceleration_structure, + descriptor, + } => { + match *context + .resolve_type(acceleration_structure, &self.valid_expression_set)? + { + Ti::AccelerationStructure => {} + _ => { + return Err(FunctionError::InvalidAccelerationStructure( + acceleration_structure, + ) + .with_span_static(span, "invalid acceleration structure")) + } + } + let desc_ty_given = + context.resolve_type(descriptor, &self.valid_expression_set)?; + let desc_ty_expected = context + .special_types + .ray_desc + .map(|handle| &context.types[handle].inner); + if Some(desc_ty_given) != desc_ty_expected { + return Err(FunctionError::InvalidRayDescriptor(descriptor) + .with_span_static(span, "invalid ray descriptor")); + } + } + crate::RayQueryFunction::Proceed { result } => { + self.emit_expression(result, context)?; + } + crate::RayQueryFunction::Terminate => {} + } } } } diff --git a/tests/in/ray-query.wgsl b/tests/in/ray-query.wgsl index b755d8f60..1a9c96749 100644 --- a/tests/in/ray-query.wgsl +++ b/tests/in/ray-query.wgsl @@ -45,19 +45,29 @@ struct RayIntersection { struct Output { visible: u32, + normal: vec3, } @group(0) @binding(1) var output: Output; +fn get_torus_normal(world_point: vec3, intersection: RayIntersection) -> vec3 { + let local_point = intersection.world_to_object * vec4(world_point, 1.0); + let point_on_guiding_line = normalize(local_point.xy) * 2.4; + let world_point_on_guiding_line = intersection.object_to_world * vec4(point_on_guiding_line, 0.0, 1.0); + return normalize(world_point - world_point_on_guiding_line); +} + @compute @workgroup_size(1) fn main() { var rq: ray_query; - rayQueryInitialize(&rq, acc_struct, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xFFu, 0.1, 100.0, vec3(0.0), vec3(0.0, 1.0, 0.0))); + let dir = vec3(0.0, 1.0, 0.0); + rayQueryInitialize(&rq, acc_struct, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xFFu, 0.1, 100.0, vec3(0.0), dir)); - rayQueryProceed(&rq); + while (rayQueryProceed(&rq)) {} let intersection = rayQueryGetCommittedIntersection(&rq); output.visible = u32(intersection.kind == RAY_QUERY_INTERSECTION_NONE); + output.normal = get_torus_normal(dir * intersection.t, intersection); } diff --git a/tests/out/msl/ray-query.msl b/tests/out/msl/ray-query.msl index 2a0973787..dc24f8067 100644 --- a/tests/out/msl/ray-query.msl +++ b/tests/out/msl/ray-query.msl @@ -15,14 +15,8 @@ constexpr metal::uint _map_intersection_type(const metal::raytracing::intersecti struct Output { uint visible_; -}; -struct RayDesc { - uint flags; - uint cull_mask; - float tmin; - float tmax; - metal::float3 origin; - metal::float3 dir; + char _pad1[12]; + metal::float3 normal; }; struct RayIntersection { uint kind; @@ -38,21 +32,48 @@ struct RayIntersection { metal::float4x3 object_to_world; metal::float4x3 world_to_object; }; +struct RayDesc { + uint flags; + uint cull_mask; + float tmin; + float tmax; + metal::float3 origin; + metal::float3 dir; +}; + +metal::float3 get_torus_normal( + metal::float3 world_point, + RayIntersection intersection +) { + metal::float3 local_point = intersection.world_to_object * metal::float4(world_point, 1.0); + metal::float2 point_on_guiding_line = metal::normalize(local_point.xy) * 2.4000000953674316; + metal::float3 world_point_on_guiding_line = intersection.object_to_world * metal::float4(point_on_guiding_line, 0.0, 1.0); + return metal::normalize(world_point - world_point_on_guiding_line); +} kernel void main_( metal::raytracing::instance_acceleration_structure acc_struct [[user(fake0)]] , device Output& output [[user(fake0)]] ) { _RayQuery rq = {}; - RayDesc _e12 = RayDesc {4u, 255u, 0.10000000149011612, 100.0, metal::float3(0.0), metal::float3(0.0, 1.0, 0.0)}; + metal::float3 dir = metal::float3(0.0, 1.0, 0.0); + RayDesc _e12 = RayDesc {4u, 255u, 0.10000000149011612, 100.0, metal::float3(0.0), dir}; rq.intersector.assume_geometry_type(metal::raytracing::geometry_type::triangle); rq.intersector.set_opacity_cull_mode((_e12.flags & 64) != 0 ? metal::raytracing::opacity_cull_mode::opaque : (_e12.flags & 128) != 0 ? metal::raytracing::opacity_cull_mode::non_opaque : metal::raytracing::opacity_cull_mode::none); rq.intersector.force_opacity((_e12.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (_e12.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none); rq.intersector.accept_any_intersection((_e12.flags & 4) != 0); rq.intersection = rq.intersector.intersect(metal::raytracing::ray(_e12.origin, _e12.dir, _e12.tmin, _e12.tmax), acc_struct, _e12.cull_mask); rq.ready = true; - bool _e13 = rq.ready; - rq.ready = false; - RayIntersection intersection = RayIntersection {_map_intersection_type(rq.intersection.type), rq.intersection.distance, rq.intersection.user_instance_id, rq.intersection.instance_id, {}, rq.intersection.geometry_id, rq.intersection.primitive_id, rq.intersection.triangle_barycentric_coord, rq.intersection.triangle_front_facing, {}, rq.intersection.object_to_world_transform, rq.intersection.world_to_object_transform}; - output.visible_ = static_cast(intersection.kind == 0u); + while(true) { + bool _e13 = rq.ready; + rq.ready = false; + if (_e13) { + } else { + break; + } + } + RayIntersection intersection_1 = RayIntersection {_map_intersection_type(rq.intersection.type), rq.intersection.distance, rq.intersection.user_instance_id, rq.intersection.instance_id, {}, rq.intersection.geometry_id, rq.intersection.primitive_id, rq.intersection.triangle_barycentric_coord, rq.intersection.triangle_front_facing, {}, rq.intersection.object_to_world_transform, rq.intersection.world_to_object_transform}; + output.visible_ = static_cast(intersection_1.kind == 0u); + metal::float3 _e25 = get_torus_normal(dir * intersection_1.t, intersection_1); + output.normal = _e25; return; } diff --git a/tests/out/spv/ray-query.spvasm b/tests/out/spv/ray-query.spvasm index 1a1a18bba..306cda758 100644 --- a/tests/out/spv/ray-query.spvasm +++ b/tests/out/spv/ray-query.spvasm @@ -1,105 +1,152 @@ ; SPIR-V ; Version: 1.4 ; Generator: rspirv -; Bound: 63 +; Bound: 95 OpCapability RayQueryKHR OpCapability Shader OpExtension "SPV_KHR_ray_query" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %29 "main" %21 %23 -OpExecutionMode %29 LocalSize 1 1 1 -OpMemberDecorate %13 0 Offset 0 +OpEntryPoint GLCompute %48 "main" %23 %25 +OpExecutionMode %48 LocalSize 1 1 1 OpMemberDecorate %15 0 Offset 0 -OpMemberDecorate %15 1 Offset 4 -OpMemberDecorate %15 2 Offset 8 -OpMemberDecorate %15 3 Offset 12 -OpMemberDecorate %15 4 Offset 16 -OpMemberDecorate %15 5 Offset 32 -OpMemberDecorate %20 0 Offset 0 -OpMemberDecorate %20 1 Offset 4 -OpMemberDecorate %20 2 Offset 8 -OpMemberDecorate %20 3 Offset 12 -OpMemberDecorate %20 4 Offset 16 -OpMemberDecorate %20 5 Offset 20 -OpMemberDecorate %20 6 Offset 24 -OpMemberDecorate %20 7 Offset 28 -OpMemberDecorate %20 8 Offset 36 -OpMemberDecorate %20 9 Offset 48 -OpMemberDecorate %20 9 ColMajor -OpMemberDecorate %20 9 MatrixStride 16 -OpMemberDecorate %20 10 Offset 112 -OpMemberDecorate %20 10 ColMajor -OpMemberDecorate %20 10 MatrixStride 16 -OpDecorate %21 DescriptorSet 0 -OpDecorate %21 Binding 0 +OpMemberDecorate %15 1 Offset 16 +OpMemberDecorate %19 0 Offset 0 +OpMemberDecorate %19 1 Offset 4 +OpMemberDecorate %19 2 Offset 8 +OpMemberDecorate %19 3 Offset 12 +OpMemberDecorate %19 4 Offset 16 +OpMemberDecorate %19 5 Offset 20 +OpMemberDecorate %19 6 Offset 24 +OpMemberDecorate %19 7 Offset 28 +OpMemberDecorate %19 8 Offset 36 +OpMemberDecorate %19 9 Offset 48 +OpMemberDecorate %19 9 ColMajor +OpMemberDecorate %19 9 MatrixStride 16 +OpMemberDecorate %19 10 Offset 112 +OpMemberDecorate %19 10 ColMajor +OpMemberDecorate %19 10 MatrixStride 16 +OpMemberDecorate %21 0 Offset 0 +OpMemberDecorate %21 1 Offset 4 +OpMemberDecorate %21 2 Offset 8 +OpMemberDecorate %21 3 Offset 12 +OpMemberDecorate %21 4 Offset 16 +OpMemberDecorate %21 5 Offset 32 OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 1 -OpDecorate %24 Block -OpMemberDecorate %24 0 Offset 0 +OpDecorate %23 Binding 0 +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 1 +OpDecorate %26 Block +OpMemberDecorate %26 0 Offset 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpConstant %4 4 -%5 = OpConstant %4 255 -%7 = OpTypeFloat 32 -%6 = OpConstant %7 0.1 -%8 = OpConstant %7 100.0 -%9 = OpConstant %7 0.0 -%10 = OpConstant %7 1.0 -%11 = OpConstant %4 0 -%12 = OpTypeAccelerationStructureNV -%13 = OpTypeStruct %4 -%14 = OpTypeVector %7 3 -%15 = OpTypeStruct %4 %4 %7 %7 %14 %14 -%16 = OpTypeRayQueryKHR -%17 = OpTypeVector %7 2 -%18 = OpTypeBool -%19 = OpTypeMatrix %14 4 -%20 = OpTypeStruct %4 %7 %4 %4 %4 %4 %4 %17 %18 %19 %19 -%22 = OpTypePointer UniformConstant %12 -%21 = OpVariable %22 UniformConstant -%24 = OpTypeStruct %13 -%25 = OpTypePointer StorageBuffer %24 -%23 = OpVariable %25 StorageBuffer -%27 = OpTypePointer Function %16 -%30 = OpTypeFunction %2 -%32 = OpTypePointer StorageBuffer %13 -%45 = OpConstant %4 1 -%58 = OpTypePointer StorageBuffer %4 -%29 = OpFunction %2 None %30 +%4 = OpTypeFloat 32 +%3 = OpConstant %4 1.0 +%5 = OpConstant %4 2.4 +%6 = OpConstant %4 0.0 +%8 = OpTypeInt 32 0 +%7 = OpConstant %8 4 +%9 = OpConstant %8 255 +%10 = OpConstant %4 0.1 +%11 = OpConstant %4 100.0 +%12 = OpConstant %8 0 +%13 = OpTypeAccelerationStructureNV +%14 = OpTypeVector %4 3 +%15 = OpTypeStruct %8 %14 +%16 = OpTypeVector %4 2 +%17 = OpTypeBool +%18 = OpTypeMatrix %14 4 +%19 = OpTypeStruct %8 %4 %8 %8 %8 %8 %8 %16 %17 %18 %18 +%20 = OpTypeVector %4 4 +%21 = OpTypeStruct %8 %8 %4 %4 %14 %14 +%22 = OpTypeRayQueryKHR +%24 = OpTypePointer UniformConstant %13 +%23 = OpVariable %24 UniformConstant +%26 = OpTypeStruct %15 +%27 = OpTypePointer StorageBuffer %26 +%25 = OpVariable %27 StorageBuffer +%32 = OpTypeFunction %14 %14 %19 +%46 = OpTypePointer Function %22 +%49 = OpTypeFunction %2 +%51 = OpTypePointer StorageBuffer %15 +%72 = OpConstant %8 1 +%85 = OpTypePointer StorageBuffer %8 +%90 = OpTypePointer StorageBuffer %14 +%31 = OpFunction %14 None %32 +%29 = OpFunctionParameter %14 +%30 = OpFunctionParameter %19 %28 = OpLabel -%26 = OpVariable %27 Function -%31 = OpLoad %12 %21 -%33 = OpAccessChain %32 %23 %11 -OpBranch %34 -%34 = OpLabel -%35 = OpCompositeConstruct %14 %9 %9 %9 -%36 = OpCompositeConstruct %14 %9 %10 %9 -%37 = OpCompositeConstruct %15 %3 %5 %6 %8 %35 %36 -%38 = OpCompositeExtract %4 %37 0 -%39 = OpCompositeExtract %4 %37 1 -%40 = OpCompositeExtract %7 %37 2 -%41 = OpCompositeExtract %7 %37 3 -%42 = OpCompositeExtract %14 %37 4 -%43 = OpCompositeExtract %14 %37 5 -OpRayQueryInitializeKHR %26 %31 %38 %39 %42 %40 %43 %41 -%44 = OpRayQueryProceedKHR %18 %26 -%46 = OpRayQueryGetIntersectionTypeKHR %4 %26 %45 -%47 = OpRayQueryGetIntersectionInstanceCustomIndexKHR %4 %26 %45 -%48 = OpRayQueryGetIntersectionInstanceIdKHR %4 %26 %45 -%49 = OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR %4 %26 %45 -%50 = OpRayQueryGetIntersectionGeometryIndexKHR %4 %26 %45 -%51 = OpRayQueryGetIntersectionPrimitiveIndexKHR %4 %26 %45 -%52 = OpRayQueryGetIntersectionTKHR %7 %26 %45 -%53 = OpRayQueryGetIntersectionBarycentricsKHR %17 %26 %45 -%54 = OpRayQueryGetIntersectionFrontFaceKHR %18 %26 %45 -%55 = OpRayQueryGetIntersectionObjectToWorldKHR %19 %26 %45 -%56 = OpRayQueryGetIntersectionWorldToObjectKHR %19 %26 %45 -%57 = OpCompositeConstruct %20 %46 %52 %47 %48 %49 %50 %51 %53 %54 %55 %56 -%59 = OpCompositeExtract %4 %57 0 -%60 = OpIEqual %18 %59 %11 -%61 = OpSelect %4 %60 %45 %11 -%62 = OpAccessChain %58 %33 %11 -OpStore %62 %61 +OpBranch %33 +%33 = OpLabel +%34 = OpCompositeExtract %18 %30 10 +%35 = OpCompositeConstruct %20 %29 %3 +%36 = OpMatrixTimesVector %14 %34 %35 +%37 = OpVectorShuffle %16 %36 %36 0 1 +%38 = OpExtInst %16 %1 Normalize %37 +%39 = OpVectorTimesScalar %16 %38 %5 +%40 = OpCompositeExtract %18 %30 9 +%41 = OpCompositeConstruct %20 %39 %6 %3 +%42 = OpMatrixTimesVector %14 %40 %41 +%43 = OpFSub %14 %29 %42 +%44 = OpExtInst %14 %1 Normalize %43 +OpReturnValue %44 +OpFunctionEnd +%48 = OpFunction %2 None %49 +%47 = OpLabel +%45 = OpVariable %46 Function +%50 = OpLoad %13 %23 +%52 = OpAccessChain %51 %25 %12 +OpBranch %53 +%53 = OpLabel +%54 = OpCompositeConstruct %14 %6 %3 %6 +%55 = OpCompositeConstruct %14 %6 %6 %6 +%56 = OpCompositeConstruct %21 %7 %9 %10 %11 %55 %54 +%57 = OpCompositeExtract %8 %56 0 +%58 = OpCompositeExtract %8 %56 1 +%59 = OpCompositeExtract %4 %56 2 +%60 = OpCompositeExtract %4 %56 3 +%61 = OpCompositeExtract %14 %56 4 +%62 = OpCompositeExtract %14 %56 5 +OpRayQueryInitializeKHR %45 %50 %57 %58 %61 %59 %62 %60 +OpBranch %63 +%63 = OpLabel +OpLoopMerge %64 %66 None +OpBranch %65 +%65 = OpLabel +%67 = OpRayQueryProceedKHR %17 %45 +OpSelectionMerge %68 None +OpBranchConditional %67 %68 %69 +%69 = OpLabel +OpBranch %64 +%68 = OpLabel +OpBranch %70 +%70 = OpLabel +OpBranch %71 +%71 = OpLabel +OpBranch %66 +%66 = OpLabel +OpBranch %63 +%64 = OpLabel +%73 = OpRayQueryGetIntersectionTypeKHR %8 %45 %72 +%74 = OpRayQueryGetIntersectionInstanceCustomIndexKHR %8 %45 %72 +%75 = OpRayQueryGetIntersectionInstanceIdKHR %8 %45 %72 +%76 = OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR %8 %45 %72 +%77 = OpRayQueryGetIntersectionGeometryIndexKHR %8 %45 %72 +%78 = OpRayQueryGetIntersectionPrimitiveIndexKHR %8 %45 %72 +%79 = OpRayQueryGetIntersectionTKHR %4 %45 %72 +%80 = OpRayQueryGetIntersectionBarycentricsKHR %16 %45 %72 +%81 = OpRayQueryGetIntersectionFrontFaceKHR %17 %45 %72 +%82 = OpRayQueryGetIntersectionObjectToWorldKHR %18 %45 %72 +%83 = OpRayQueryGetIntersectionWorldToObjectKHR %18 %45 %72 +%84 = OpCompositeConstruct %19 %73 %79 %74 %75 %76 %77 %78 %80 %81 %82 %83 +%86 = OpCompositeExtract %8 %84 0 +%87 = OpIEqual %17 %86 %12 +%88 = OpSelect %8 %87 %72 %12 +%89 = OpAccessChain %85 %52 %12 +OpStore %89 %88 +%91 = OpCompositeExtract %4 %84 1 +%92 = OpVectorTimesScalar %14 %54 %91 +%93 = OpFunctionCall %14 %31 %92 %84 +%94 = OpAccessChain %90 %52 %72 +OpStore %94 %93 OpReturn OpFunctionEnd \ No newline at end of file From c34eed5e47f38cb0679906ce86833f110bbf9354 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 21 Mar 2023 22:47:53 -0700 Subject: [PATCH 1974/2212] Address Jim's review notes, use typegen module for atomic struct --- src/back/dot/mod.rs | 28 +++++++----- src/back/mod.rs | 4 +- src/back/spv/writer.rs | 2 +- src/front/type_gen.rs | 53 ++++++++++++++++++++++- src/front/wgsl/error.rs | 6 +++ src/front/wgsl/lower/mod.rs | 53 ++++------------------- src/lib.rs | 6 +-- tests/in/ray-query.wgsl | 4 +- tests/out/wgsl/atomicCompareExchange.wgsl | 4 +- 9 files changed, 92 insertions(+), 68 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index d293c3adc..1eebbee06 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -254,19 +254,25 @@ impl StatementGraph { } S::RayQuery { query, ref fun } => { self.dependencies.push((id, query, "query")); - if let crate::RayQueryFunction::Initialize { - acceleration_structure, - descriptor, - } = *fun - { - self.dependencies.push(( - id, + match *fun { + crate::RayQueryFunction::Initialize { acceleration_structure, - "acceleration_structure", - )); - self.dependencies.push((id, descriptor, "descriptor")); + descriptor, + } => { + self.dependencies.push(( + id, + acceleration_structure, + "acceleration_structure", + )); + self.dependencies.push((id, descriptor, "descriptor")); + "RayQueryInitialize" + } + crate::RayQueryFunction::Proceed { result } => { + self.emits.push((id, result)); + "RayQueryProceed" + } + crate::RayQueryFunction::Terminate => "RayQueryTerminate", } - "RayQuery" } }; // Set the last node to the merge node diff --git a/src/back/mod.rs b/src/back/mod.rs index f51262524..8467ee787 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -234,8 +234,8 @@ bitflags::bitflags! { const NO_OPAQUE = 0x02; const TERMINATE_ON_FIRST_HIT = 0x04; const SKIP_CLOSEST_HIT_SHADER = 0x08; - const CULL_FRONT_FACING = 0x10; - const CULL_BACK_FACING = 0x20; + const CULL_BACK_FACING = 0x10; + const CULL_FRONT_FACING = 0x20; const CULL_OPAQUE = 0x40; const CULL_NO_OPAQUE = 0x80; const SKIP_TRIANGLES = 0x100; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 800a40ed6..ba235e6d0 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -973,7 +973,7 @@ impl Writer { self.write_type_declaration_local(id, local); - // If it's an type that needs SPIR-V capabilities, request them now, + // If it's a type that needs SPIR-V capabilities, request them now, // so write_type_declaration_local can stay infallible. self.request_type_capabilities(&ty.inner)?; diff --git a/src/front/type_gen.rs b/src/front/type_gen.rs index b695b5279..1ee454c44 100644 --- a/src/front/type_gen.rs +++ b/src/front/type_gen.rs @@ -5,6 +5,55 @@ Type generators. use crate::{arena::Handle, span::Span}; impl crate::Module { + pub fn generate_atomic_compare_exchange_result( + &mut self, + kind: crate::ScalarKind, + width: crate::Bytes, + ) -> Handle { + let bool_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }, + }, + Span::UNDEFINED, + ); + let scalar_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind, width }, + }, + Span::UNDEFINED, + ); + + self.types.insert( + crate::Type { + name: Some(format!( + "__atomic_compare_exchange_result<{kind:?},{width}>" + )), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("old_value".to_string()), + ty: scalar_ty, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("exchanged".to_string()), + ty: bool_ty, + binding: None, + offset: 4, + }, + ], + span: 8, + }, + }, + Span::UNDEFINED, + ) + } /// Populate this module's [`SpecialTypes::ray_desc`] type. /// /// [`SpecialTypes::ray_desc`] is the type of the [`descriptor`] operand of @@ -20,7 +69,7 @@ impl crate::Module { /// [`Initialize`]: crate::RayQueryFunction::Initialize /// [`RayQuery`]: crate::Statement::RayQuery /// [`RayQueryFunction::Initialize`]: crate::RayQueryFunction::Initialize - pub(super) fn generate_ray_desc_type(&mut self) -> Handle { + pub fn generate_ray_desc_type(&mut self) -> Handle { if let Some(handle) = self.special_types.ray_desc { return handle; } @@ -122,7 +171,7 @@ impl crate::Module { /// /// [`SpecialTypes::ray_intersection`]: crate::SpecialTypes::ray_intersection /// [`Expression::RayQueryGetIntersection`]: crate::Expression::RayQueryGetIntersection - pub(super) fn generate_ray_intersection_type(&mut self) -> Handle { + pub fn generate_ray_intersection_type(&mut self) -> Handle { if let Some(handle) = self.special_types.ray_intersection { return handle; } diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index a4e654023..2e71a7662 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -188,6 +188,7 @@ pub enum Error<'a> { MissingAttribute(&'static str, Span), InvalidAtomicPointer(Span), InvalidAtomicOperandType(Span), + InvalidRayQueryPointer(Span), Pointer(&'static str, Span), NotPointer(Span), NotReference(&'static str, Span), @@ -526,6 +527,11 @@ impl<'a> Error<'a> { labels: vec![(span, "atomic operand type is invalid".into())], notes: vec![], }, + Error::InvalidRayQueryPointer(span) => ParseError { + message: "ray query operation is done on a pointer to a non-ray-query".to_string(), + labels: vec![(span, "ray query pointer is invalid".into())], + notes: vec![], + }, Error::NotPointer(span) => ParseError { message: "the operand of the `*` operator must be a pointer".to_string(), labels: vec![(span, "expression is not a pointer".into())], diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 8df3460b2..314eea52e 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -641,6 +641,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let span = tu.decls.get_span(decl_handle); let decl = &tu.decls[decl_handle]; + //NOTE: This is done separately from `resolve_ast_type` because `RayDesc` may be + // first encountered in a local constructor invocation. //TODO: find a nicer way? if let Some(dep) = decl.dependencies.iter().find(|dep| dep.ident == "RayDesc") { let ty_handle = ctx.module.generate_ray_desc_type(); @@ -1733,50 +1735,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let expression = match *ctx.resolved_inner(value) { crate::TypeInner::Scalar { kind, width } => { - let bool_ty = ctx.module.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: crate::BOOL_WIDTH, - }, - }, - Span::UNDEFINED, - ); - let scalar_ty = ctx.module.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { kind, width }, - }, - Span::UNDEFINED, - ); - let struct_ty = ctx.module.types.insert( - crate::Type { - name: Some( - "__atomic_compare_exchange_result".to_string(), - ), - inner: crate::TypeInner::Struct { - members: vec![ - crate::StructMember { - name: Some("old_value".to_string()), - ty: scalar_ty, - binding: None, - offset: 0, - }, - crate::StructMember { - name: Some("exchanged".to_string()), - ty: bool_ty, - binding: None, - offset: 4, - }, - ], - span: 8, - }, - }, - Span::UNDEFINED, - ); crate::Expression::AtomicResult { - ty: struct_ty, + //TODO: cache this to avoid generating duplicate types + ty: ctx + .module + .generate_atomic_compare_exchange_result(kind, width), comparison: true, } } @@ -2449,12 +2412,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { crate::TypeInner::RayQuery => Ok(pointer), ref other => { log::error!("Pointer type to {:?} passed to ray query op", other); - Err(Error::InvalidAtomicPointer(span)) + Err(Error::InvalidRayQueryPointer(span)) } }, ref other => { log::error!("Type {:?} passed to ray query op", other); - Err(Error::InvalidAtomicPointer(span)) + Err(Error::InvalidRayQueryPointer(span)) } } } diff --git a/src/lib.rs b/src/lib.rs index f91dc7ce5..a70015d16 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1460,7 +1460,7 @@ pub enum Expression { /// Return an intersection found by `query`. /// - /// If `committed` is true, return the committed result available when + /// If `committed` is true, return the committed result available when RayQueryGetIntersection { query: Handle, committed: bool, @@ -1848,13 +1848,13 @@ pub struct SpecialTypes { /// /// Call [`Module::generate_ray_desc_type`] to populate this if /// needed and return the handle. - ray_desc: Option>, + pub ray_desc: Option>, /// Type for `RayIntersection`. /// /// Call [`Module::generate_ray_intersection_type`] to populate /// this if needed and return the handle. - ray_intersection: Option>, + pub ray_intersection: Option>, } /// Shader module. diff --git a/tests/in/ray-query.wgsl b/tests/in/ray-query.wgsl index 1a9c96749..4826547de 100644 --- a/tests/in/ray-query.wgsl +++ b/tests/in/ray-query.wgsl @@ -7,8 +7,8 @@ let RAY_FLAG_OPAQUE = 0x01u; let RAY_FLAG_NO_OPAQUE = 0x02u; let RAY_FLAG_TERMINATE_ON_FIRST_HIT = 0x04u; let RAY_FLAG_SKIP_CLOSEST_HIT_SHADER = 0x08u; -let RAY_FLAG_CULL_FRONT_FACING = 0x10u; -let RAY_FLAG_CULL_BACK_FACING = 0x20u; +let RAY_FLAG_CULL_BACK_FACING = 0x10u; +let RAY_FLAG_CULL_FRONT_FACING = 0x20u; let RAY_FLAG_CULL_OPAQUE = 0x40u; let RAY_FLAG_CULL_NO_OPAQUE = 0x80u; let RAY_FLAG_SKIP_TRIANGLES = 0x100u; diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/tests/out/wgsl/atomicCompareExchange.wgsl index 2c213c8fe..bfad298fa 100644 --- a/tests/out/wgsl/atomicCompareExchange.wgsl +++ b/tests/out/wgsl/atomicCompareExchange.wgsl @@ -1,9 +1,9 @@ -struct gen___atomic_compare_exchange_result { +struct gen___atomic_compare_exchange_resultSint4_ { old_value: i32, exchanged: bool, } -struct gen___atomic_compare_exchange_result_1 { +struct gen___atomic_compare_exchange_resultUint4_ { old_value: u32, exchanged: bool, } From 53d62b9ede64898681c0dbc70d04296caf90ed16 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 22 Mar 2023 09:00:08 -0700 Subject: [PATCH 1975/2212] Clean up handling of `RayDesc` builtin type, somewhat. --- src/front/wgsl/lower/mod.rs | 20 +++++++++++--------- tests/out/spv/ray-query.spvasm | 20 ++++++++++---------- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 314eea52e..bc9cce1be 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -641,15 +641,6 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let span = tu.decls.get_span(decl_handle); let decl = &tu.decls[decl_handle]; - //NOTE: This is done separately from `resolve_ast_type` because `RayDesc` may be - // first encountered in a local constructor invocation. - //TODO: find a nicer way? - if let Some(dep) = decl.dependencies.iter().find(|dep| dep.ident == "RayDesc") { - let ty_handle = ctx.module.generate_ray_desc_type(); - ctx.globals - .insert(dep.ident, LoweredGlobalDecl::Type(ty_handle)); - } - match decl.kind { ast::GlobalDeclKind::Fn(ref f) => { let lowered_decl = self.function(f, span, ctx.reborrow())?; @@ -1930,6 +1921,17 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { committed: true, } } + "RayDesc" => { + let ty = ctx.module.generate_ray_desc_type(); + let handle = self.construct( + span, + &ast::ConstructorType::Type(ty), + function.span, + arguments, + ctx.reborrow(), + )?; + return Ok(Some(handle)); + } _ => return Err(Error::UnknownIdent(function.span, function.name)), } }; diff --git a/tests/out/spv/ray-query.spvasm b/tests/out/spv/ray-query.spvasm index 306cda758..31dc7d75e 100644 --- a/tests/out/spv/ray-query.spvasm +++ b/tests/out/spv/ray-query.spvasm @@ -26,12 +26,12 @@ OpMemberDecorate %19 9 MatrixStride 16 OpMemberDecorate %19 10 Offset 112 OpMemberDecorate %19 10 ColMajor OpMemberDecorate %19 10 MatrixStride 16 -OpMemberDecorate %21 0 Offset 0 -OpMemberDecorate %21 1 Offset 4 -OpMemberDecorate %21 2 Offset 8 -OpMemberDecorate %21 3 Offset 12 -OpMemberDecorate %21 4 Offset 16 -OpMemberDecorate %21 5 Offset 32 +OpMemberDecorate %22 0 Offset 0 +OpMemberDecorate %22 1 Offset 4 +OpMemberDecorate %22 2 Offset 8 +OpMemberDecorate %22 3 Offset 12 +OpMemberDecorate %22 4 Offset 16 +OpMemberDecorate %22 5 Offset 32 OpDecorate %23 DescriptorSet 0 OpDecorate %23 Binding 0 OpDecorate %25 DescriptorSet 0 @@ -57,15 +57,15 @@ OpMemberDecorate %26 0 Offset 0 %18 = OpTypeMatrix %14 4 %19 = OpTypeStruct %8 %4 %8 %8 %8 %8 %8 %16 %17 %18 %18 %20 = OpTypeVector %4 4 -%21 = OpTypeStruct %8 %8 %4 %4 %14 %14 -%22 = OpTypeRayQueryKHR +%21 = OpTypeRayQueryKHR +%22 = OpTypeStruct %8 %8 %4 %4 %14 %14 %24 = OpTypePointer UniformConstant %13 %23 = OpVariable %24 UniformConstant %26 = OpTypeStruct %15 %27 = OpTypePointer StorageBuffer %26 %25 = OpVariable %27 StorageBuffer %32 = OpTypeFunction %14 %14 %19 -%46 = OpTypePointer Function %22 +%46 = OpTypePointer Function %21 %49 = OpTypeFunction %2 %51 = OpTypePointer StorageBuffer %15 %72 = OpConstant %8 1 @@ -99,7 +99,7 @@ OpBranch %53 %53 = OpLabel %54 = OpCompositeConstruct %14 %6 %3 %6 %55 = OpCompositeConstruct %14 %6 %6 %6 -%56 = OpCompositeConstruct %21 %7 %9 %10 %11 %55 %54 +%56 = OpCompositeConstruct %22 %7 %9 %10 %11 %55 %54 %57 = OpCompositeExtract %8 %56 0 %58 = OpCompositeExtract %8 %56 1 %59 = OpCompositeExtract %4 %56 2 From 52043be00489d6dedb08c36bb97d018d11cb1e13 Mon Sep 17 00:00:00 2001 From: PyryM Date: Thu, 30 Mar 2023 10:02:54 -0400 Subject: [PATCH 1976/2212] [spv-out] Fix invalid spirv being generated from integer dot products (#2291) * Fix invalid spirv generation in int dotprod constants cannot be declared inside of a function block, so instead use `write_constant_null` to produce a correctly-declared constant 0. * autogenerated test snapshots --- src/back/spv/block.rs | 7 +------ tests/out/spv/functions.spvasm | 2 +- tests/out/spv/math-functions.spvasm | 2 +- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index b28b94fe9..8366df415 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1627,12 +1627,7 @@ impl<'w> BlockContext<'w> { size: u32, block: &mut Block, ) { - let const_null = self.gen_id(); - block - .body - .push(Instruction::constant_null(result_type_id, const_null)); - - let mut partial_sum = const_null; + let mut partial_sum = self.writer.write_constant_null(result_type_id); let last_component = size - 1; for index in 0..=last_component { // compute the product of the current components diff --git a/tests/out/spv/functions.spvasm b/tests/out/spv/functions.spvasm index bfebd09f8..ef3a2cd23 100644 --- a/tests/out/spv/functions.spvasm +++ b/tests/out/spv/functions.spvasm @@ -23,10 +23,10 @@ OpExecutionMode %74 LocalSize 1 1 1 %15 = OpTypeVector %7 4 %18 = OpTypeFunction %12 %26 = OpTypeFunction %7 -%75 = OpTypeFunction %2 %31 = OpConstantNull %7 %42 = OpConstantNull %9 %57 = OpConstantNull %7 +%75 = OpTypeFunction %2 %17 = OpFunction %12 None %18 %16 = OpLabel OpBranch %19 diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 9dbde7ddf..bee60f29e 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -24,12 +24,12 @@ OpEntryPoint Vertex %18 "main" %19 = OpTypeFunction %2 %27 = OpConstantComposite %14 %5 %5 %5 %5 %28 = OpConstantComposite %14 %3 %3 %3 %3 +%31 = OpConstantNull %7 %42 = OpConstant %9 32 %50 = OpTypeVector %9 2 %53 = OpConstantComposite %50 %42 %42 %65 = OpConstant %7 31 %71 = OpConstantComposite %15 %65 %65 -%31 = OpConstantNull %7 %18 = OpFunction %2 None %19 %17 = OpLabel OpBranch %20 From da8e911d9d207a7571241e875f7ac066856e8b3f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 31 Mar 2023 17:30:43 -0700 Subject: [PATCH 1977/2212] [hlsl-out]: Document storage access generation. (#2295) --- src/back/hlsl/mod.rs | 18 +++++++++ src/back/hlsl/storage.rs | 82 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 97 insertions(+), 3 deletions(-) diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs index 6f31ed374..f3a6f9106 100644 --- a/src/back/hlsl/mod.rs +++ b/src/back/hlsl/mod.rs @@ -279,6 +279,24 @@ pub struct Writer<'a, W> { /// Set of expressions that have associated temporary variables named_expressions: crate::NamedExpressions, wrapped: Wrapped, + + /// A reference to some part of a global variable, lowered to a series of + /// byte offset calculations. + /// + /// See the [`storage`] module for background on why we need this. + /// + /// Each [`SubAccess`] in the vector is a lowering of some [`Access`] or + /// [`AccessIndex`] expression to the level of byte strides and offsets. See + /// [`SubAccess`] for details. + /// + /// This field is a member of [`Writer`] solely to allow re-use of + /// the `Vec`'s dynamic allocation. The value is no longer needed + /// once HLSL for the access has been generated. + /// + /// [`Storage`]: crate::AddressSpace::Storage + /// [`SubAccess`]: storage::SubAccess + /// [`Access`]: crate::Expression::Access + /// [`AccessIndex`]: crate::Expression::AccessIndex temp_access_chain: Vec, need_bake_expressions: back::NeedBakeExpressions, } diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 647a6bf87..813dd7364 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -1,7 +1,47 @@ /*! -Logic related to `ByteAddressBuffer` operations. +Generating accesses to [`ByteAddressBuffer`] contents. -HLSL backend uses byte address buffers for all storage buffers in IR. +Naga IR globals in the [`Storage`] address space are rendered as +[`ByteAddressBuffer`]s or [`RWByteAddressBuffer`]s in HLSL. These +buffers don't have HLSL types (structs, arrays, etc.); instead, they +are just raw blocks of bytes, with methods to load and store values of +specific types at particular byte offsets. This means that Naga must +translate chains of [`Access`] and [`AccessIndex`] expressions into +HLSL expressions that compute byte offsets into the buffer. + +To generate code for a [`Storage`] access: + +- Call [`Writer::fill_access_chain`] on the expression referring to + the value. This populates [`Writer::temp_access_chain`] with the + appropriate byte offset calculations, as a vector of [`SubAccess`] + values. + +- Call [`Writer::write_storage_address`] to emit an HLSL expression + for a given slice of [`SubAccess`] values. + +Naga IR expressions can operate on composite values of any type, but +[`ByteAddressBuffer`] and [`RWByteAddressBuffer`] have only a fixed +set of `Load` and `Store` methods, to access one through four +consecutive 32-bit values. To synthesize a Naga access, you can +initialize [`temp_access_chain`] to refer to the composite, and then +temporarily push and pop additional steps on +[`Writer::temp_access_chain`] to generate accesses to the individual +elements/members. + +The [`temp_access_chain`] field is a member of [`Writer`] solely to +allow re-use of the `Vec`'s dynamic allocation. Its value is no longer +needed once HLSL for the access has been generated. + +[`Storage`]: crate::AddressSpace::Storage +[`ByteAddressBuffer`]: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-byteaddressbuffer +[`RWByteAddressBuffer`]: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-rwbyteaddressbuffer +[`Access`]: crate::Expression::Access +[`AccessIndex`]: crate::Expression::AccessIndex +[`Writer::fill_access_chain`]: super::Writer::fill_access_chain +[`Writer::write_storage_address`]: super::Writer::write_storage_address +[`Writer::temp_access_chain`]: super::Writer::temp_access_chain +[`temp_access_chain`]: super::Writer::temp_access_chain +[`Writer`]: super::Writer */ use super::{super::FunctionCtx, BackendResult, Error}; @@ -14,9 +54,25 @@ use std::{fmt, mem}; const STORE_TEMP_NAME: &str = "_value"; +/// One step in accessing a [`Storage`] global's component or element. +/// +/// [`Writer::temp_access_chain`] holds a series of these structures, +/// describing how to compute the byte offset of a particular element +/// or member of some global variable in the [`Storage`] address +/// space. +/// +/// [`Writer::temp_access_chain`]: super::Writer::temp_access_chain +/// [`Storage`]: crate::AddressSpace::Storage #[derive(Debug)] pub(super) enum SubAccess { + /// Add the given byte offset. This is used for struct members, or + /// known components of a vector or matrix. In all those cases, + /// the byte offset is a compile-time constant. Offset(u32), + + /// Scale `value` by `stride`, and add that to the current byte + /// offset. This is used to compute the offset of an array element + /// whose index is computed at runtime. Index { value: Handle, stride: u32, @@ -83,7 +139,16 @@ impl super::Writer<'_, W> { Ok(()) } - /// Helper function to write down the Load operation on a `ByteAddressBuffer`. + /// Emit code to access a [`Storage`] global's component. + /// + /// Emit HLSL to access the component of `var_handle`, a global + /// variable in the [`Storage`] address space, whose type is + /// `result_ty` and whose location within the global is given by + /// [`self.temp_access_chain`]. See the [`storage`] module's + /// documentation for background. + /// + /// [`Storage`]: crate::AddressSpace::Storage + /// [`self.temp_access_chain`]: super::Writer::temp_access_chain pub(super) fn write_storage_load( &mut self, module: &crate::Module, @@ -366,6 +431,17 @@ impl super::Writer<'_, W> { Ok(()) } + /// Set [`temp_access_chain`] to compute the byte offset of `cur_expr`. + /// + /// The `cur_expr` expression must be a reference to a global + /// variable in the [`Storage`] address space, or a chain of + /// [`Access`] and [`AccessIndex`] expressions referring to some + /// component of such a global. + /// + /// [`temp_access_chain`]: super::Writer::temp_access_chain + /// [`Storage`]: crate::AddressSpace::Storage + /// [`Access`]: crate::Expression::Access + /// [`AccessIndex`]: crate::Expression::AccessIndex pub(super) fn fill_access_chain( &mut self, module: &crate::Module, From 7c00548075f51dc8c80ab8abdb4de6569ea59d46 Mon Sep 17 00:00:00 2001 From: Christopher Fleetwood <45471420+FL33TW00D@users.noreply.github.com> Date: Tue, 4 Apr 2023 11:35:32 +0100 Subject: [PATCH 1978/2212] [wgsl] Use `alias` instead of `type` for type aliases (#2299) --- src/front/wgsl/error.rs | 2 +- src/front/wgsl/parse/mod.rs | 2 +- src/front/wgsl/tests.rs | 10 ++++++++++ src/keywords/wgsl.rs | 1 + tests/in/module-scope.wgsl | 2 +- tests/in/type-alias.wgsl | 8 ++++---- tests/wgsl-errors.rs | 14 +++++++------- 7 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index 2e71a7662..82f7c609e 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -275,7 +275,7 @@ impl<'a> Error<'a> { ExpectedToken::Assignment => "assignment or increment/decrement".to_string(), ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), - ExpectedToken::GlobalItem => "global item ('struct', 'const', 'var', 'type', ';', 'fn') or the end of the file".to_string(), + ExpectedToken::GlobalItem => "global item ('struct', 'const', 'var', 'alias', ';', 'fn') or the end of the file".to_string(), ExpectedToken::Type => "type".to_string(), ExpectedToken::Variable => "variable access".to_string(), ExpectedToken::Function => "function name".to_string(), diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 7a030259b..cf9892a1f 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -2213,7 +2213,7 @@ impl Parser { let members = self.struct_body(lexer, ctx)?; Some(ast::GlobalDeclKind::Struct(ast::Struct { name, members })) } - (Token::Word("type"), _) => { + (Token::Word("alias"), _) => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 98d3f8dc9..31b589070 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -471,3 +471,13 @@ fn parse_storage_buffers() { ) .unwrap(); } + +#[test] +fn parse_alias() { + parse_str( + " + alias Vec4 = vec4; + ", + ) + .unwrap(); +} diff --git a/src/keywords/wgsl.rs b/src/keywords/wgsl.rs index 0a2abbfd2..7b47a1312 100644 --- a/src/keywords/wgsl.rs +++ b/src/keywords/wgsl.rs @@ -47,6 +47,7 @@ pub const RESERVED: &[&str] = &[ "vec3", "vec4", // Other Keywords + "alias", "bitcast", "break", "case", diff --git a/tests/in/module-scope.wgsl b/tests/in/module-scope.wgsl index 54638cb40..6d1e3c95e 100644 --- a/tests/in/module-scope.wgsl +++ b/tests/in/module-scope.wgsl @@ -23,4 +23,4 @@ var Texture: texture_2d; @group(0) @binding(1) var Sampler: sampler; -type Vec2 = vec2; +alias Vec2 = vec2; diff --git a/tests/in/type-alias.wgsl b/tests/in/type-alias.wgsl index cf2c8dcb3..69c1eae4e 100644 --- a/tests/in/type-alias.wgsl +++ b/tests/in/type-alias.wgsl @@ -1,7 +1,7 @@ -type FVec3 = vec3; -type IVec3 = vec3i; -type Mat2 = mat2x2; -type Mat3 = mat3x3f; +alias FVec3 = vec3; +alias IVec3 = vec3i; +alias Mat2 = mat2x2; +alias Mat3 = mat3x3f; fn main() { let a = FVec3(0.0, 0.0, 0.0); diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index d44dd97f3..8baa8e29d 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -912,9 +912,9 @@ fn validation_error(source: &str) -> Result, 4>;", - "type Bad = array;", - "type Bad = array, 4>;": + "alias Bad = array, 4>;", + "alias Bad = array;", + "alias Bad = array, 4>;": Err(naga::valid::ValidationError::Type { source: naga::valid::TypeError::InvalidArrayBaseType(_), .. @@ -922,10 +922,10 @@ fn invalid_arrays() { } check_validation! { - "type Bad = array;", + "alias Bad = array;", r#" const length: f32 = 2.718; - type Bad = array; + alias Bad = array; "#: Err(naga::valid::ValidationError::Type { source: naga::valid::TypeError::InvalidArraySizeConstant(_), @@ -934,8 +934,8 @@ fn invalid_arrays() { } check_validation! { - "type Bad = array;", - "type Bad = array;": + "alias Bad = array;", + "alias Bad = array;": Err(naga::valid::ValidationError::Type { source: naga::valid::TypeError::NonPositiveArrayLength(_), .. From 115870974701d22c4d3c5c7e1f6524cc5c668a35 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 5 Apr 2023 17:54:07 +0200 Subject: [PATCH 1979/2212] stop code coverage comments (#2283) --- codecov.yml | 1 + 1 file changed, 1 insertion(+) create mode 100644 codecov.yml diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 000000000..959972a69 --- /dev/null +++ b/codecov.yml @@ -0,0 +1 @@ +comment: false \ No newline at end of file From 99a7773e65f855ecdefc6fc0fffa6f0aacd3f867 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Wed, 5 Apr 2023 22:37:22 -0400 Subject: [PATCH 1980/2212] fix(hlsl-out): use `Interlocked` intrinsic for atomic integers (#2294) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We currently assume that we are using raw `RWByteAddressBuffer` methods for all atomic operations (`.Interlocked(, …)`), which is only true when we use `var` globals. For `var` globals, we need `Interlocked(, …)`, using the original expression as the first argument. Fix this by branching on the `pointer`'s address space in `Atomic` statements, and implementing the workgroup address space case with intrinsics. Remove atomic ops from `access`, add new `atomicOps` test. Fixes #2284 --- src/back/hlsl/writer.rs | 36 +- tests/in/access.wgsl | 19 +- tests/in/atomicOps.wgsl | 141 ++++ tests/out/analysis/access.info.ron | 627 ------------------ tests/out/glsl/atomicOps.cs_main.Compute.glsl | 132 ++++ tests/out/hlsl/access.hlsl | 26 - tests/out/hlsl/access.hlsl.config | 2 +- tests/out/hlsl/atomicOps.hlsl | 112 ++++ tests/out/hlsl/atomicOps.hlsl.config | 3 + tests/out/ir/access.ron | 248 ------- tests/out/msl/access.msl | 27 - tests/out/msl/atomicOps.msl | 126 ++++ tests/out/spv/access.spvasm | 106 +-- tests/out/spv/atomicOps.spvasm | 240 +++++++ tests/out/wgsl/access.wgsl | 25 - tests/out/wgsl/atomicOps.wgsl | 107 +++ tests/snapshots.rs | 4 + 17 files changed, 928 insertions(+), 1053 deletions(-) create mode 100644 tests/in/atomicOps.wgsl create mode 100644 tests/out/glsl/atomicOps.cs_main.Compute.glsl create mode 100644 tests/out/hlsl/atomicOps.hlsl create mode 100644 tests/out/hlsl/atomicOps.hlsl.config create mode 100644 tests/out/msl/atomicOps.msl create mode 100644 tests/out/spv/atomicOps.spvasm create mode 100644 tests/out/wgsl/atomicOps.wgsl diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index f9e52914f..a3810c5da 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1856,14 +1856,37 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } }; - let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; - // working around the borrow checker in `self.write_expr` - let chain = mem::take(&mut self.temp_access_chain); - let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + // Validation ensures that `pointer` has a `Pointer` type. + let pointer_space = func_ctx.info[pointer] + .ty + .inner_with(&module.types) + .pointer_space() + .unwrap(); let fun_str = fun.to_hlsl_suffix(); - write!(self.out, " {res_name}; {var_name}.Interlocked{fun_str}(")?; - self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, " {res_name}; ")?; + match pointer_space { + crate::AddressSpace::WorkGroup => { + write!(self.out, "Interlocked{fun_str}(")?; + self.write_expr(module, pointer, func_ctx)?; + } + crate::AddressSpace::Storage { .. } => { + let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; + // The call to `self.write_storage_address` wants + // mutable access to all of `self`, so temporarily take + // ownership of our reusable access chain buffer. + let chain = mem::take(&mut self.temp_access_chain); + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + write!(self.out, "{var_name}.Interlocked{fun_str}(")?; + self.write_storage_address(module, &chain, func_ctx)?; + self.temp_access_chain = chain; + } + ref other => { + return Err(Error::Custom(format!( + "invalid address space {other:?} for atomic statement" + ))) + } + } write!(self.out, ", ")?; // handle the special cases match *fun { @@ -1878,7 +1901,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } self.write_expr(module, value, func_ctx)?; writeln!(self.out, ", {res_name});")?; - self.temp_access_chain = chain; self.named_expressions.insert(result, res_name); } Statement::Switch { diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index a9c27ee78..ed4988532 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -151,23 +151,6 @@ fn foo_frag() -> @location(0) vec4 { return vec4(0.0); } -@compute @workgroup_size(1) -fn atomics() { - var tmp: i32; - let value = atomicLoad(&bar.atom); - tmp = atomicAdd(&bar.atom, 5); - tmp = atomicSub(&bar.atom, 5); - tmp = atomicAnd(&bar.atom, 5); - tmp = atomicOr(&bar.atom, 5); - tmp = atomicXor(&bar.atom, 5); - tmp = atomicMin(&bar.atom, 5); - tmp = atomicMax(&bar.atom, 5); - tmp = atomicExchange(&bar.atom, 5); - // https://github.com/gpuweb/gpuweb/issues/2021 - // tmp = atomicCompareExchangeWeak(&bar.atom, 5, 5); - atomicStore(&bar.atom, value); -} - var val: u32; fn assign_through_ptr_fn(p: ptr) { @@ -184,4 +167,4 @@ fn assign_through_ptr() { assign_through_ptr_fn(&val); assign_array_through_ptr_fn(&arr); -} \ No newline at end of file +} diff --git a/tests/in/atomicOps.wgsl b/tests/in/atomicOps.wgsl new file mode 100644 index 000000000..111a9abbc --- /dev/null +++ b/tests/in/atomicOps.wgsl @@ -0,0 +1,141 @@ +// This test covers the cross product of: +// +// * All atomic operations. +// * On all applicable scopes (storage read-write, workgroup). +// * For all shapes of modeling atomic data. + +struct Struct { + atomic_scalar: atomic, + atomic_arr: array, 2>, +} + +@group(0) @binding(0) +var storage_atomic_scalar: atomic; +@group(0) @binding(1) +var storage_atomic_arr: array, 2>; +@group(0) @binding(2) +var storage_struct: Struct; + +var workgroup_atomic_scalar: atomic; +var workgroup_atomic_arr: array, 2>; +var workgroup_struct: Struct; + +@compute +@workgroup_size(2) +fn cs_main(@builtin(local_invocation_id) id: vec3) { + atomicStore(&storage_atomic_scalar, 1u); + atomicStore(&storage_atomic_arr[1], 1i); + atomicStore(&storage_struct.atomic_scalar, 1u); + atomicStore(&storage_struct.atomic_arr[1], 1i); + atomicStore(&workgroup_atomic_scalar, 1u); + atomicStore(&workgroup_atomic_arr[1], 1i); + atomicStore(&workgroup_struct.atomic_scalar, 1u); + atomicStore(&workgroup_struct.atomic_arr[1], 1i); + + workgroupBarrier(); + + atomicLoad(&storage_atomic_scalar); + atomicLoad(&storage_atomic_arr[1]); + atomicLoad(&storage_struct.atomic_scalar); + atomicLoad(&storage_struct.atomic_arr[1]); + atomicLoad(&workgroup_atomic_scalar); + atomicLoad(&workgroup_atomic_arr[1]); + atomicLoad(&workgroup_struct.atomic_scalar); + atomicLoad(&workgroup_struct.atomic_arr[1]); + + workgroupBarrier(); + + atomicAdd(&storage_atomic_scalar, 1u); + atomicAdd(&storage_atomic_arr[1], 1i); + atomicAdd(&storage_struct.atomic_scalar, 1u); + atomicAdd(&storage_struct.atomic_arr[1], 1i); + atomicAdd(&workgroup_atomic_scalar, 1u); + atomicAdd(&workgroup_atomic_arr[1], 1i); + atomicAdd(&workgroup_struct.atomic_scalar, 1u); + atomicAdd(&workgroup_struct.atomic_arr[1], 1i); + + workgroupBarrier(); + + atomicSub(&storage_atomic_scalar, 1u); + atomicSub(&storage_atomic_arr[1], 1i); + atomicSub(&storage_struct.atomic_scalar, 1u); + atomicSub(&storage_struct.atomic_arr[1], 1i); + atomicSub(&workgroup_atomic_scalar, 1u); + atomicSub(&workgroup_atomic_arr[1], 1i); + atomicSub(&workgroup_struct.atomic_scalar, 1u); + atomicSub(&workgroup_struct.atomic_arr[1], 1i); + + workgroupBarrier(); + + atomicMax(&storage_atomic_scalar, 1u); + atomicMax(&storage_atomic_arr[1], 1i); + atomicMax(&storage_struct.atomic_scalar, 1u); + atomicMax(&storage_struct.atomic_arr[1], 1i); + atomicMax(&workgroup_atomic_scalar, 1u); + atomicMax(&workgroup_atomic_arr[1], 1i); + atomicMax(&workgroup_struct.atomic_scalar, 1u); + atomicMax(&workgroup_struct.atomic_arr[1], 1i); + + workgroupBarrier(); + + atomicMin(&storage_atomic_scalar, 1u); + atomicMin(&storage_atomic_arr[1], 1i); + atomicMin(&storage_struct.atomic_scalar, 1u); + atomicMin(&storage_struct.atomic_arr[1], 1i); + atomicMin(&workgroup_atomic_scalar, 1u); + atomicMin(&workgroup_atomic_arr[1], 1i); + atomicMin(&workgroup_struct.atomic_scalar, 1u); + atomicMin(&workgroup_struct.atomic_arr[1], 1i); + + workgroupBarrier(); + + atomicAnd(&storage_atomic_scalar, 1u); + atomicAnd(&storage_atomic_arr[1], 1i); + atomicAnd(&storage_struct.atomic_scalar, 1u); + atomicAnd(&storage_struct.atomic_arr[1], 1i); + atomicAnd(&workgroup_atomic_scalar, 1u); + atomicAnd(&workgroup_atomic_arr[1], 1i); + atomicAnd(&workgroup_struct.atomic_scalar, 1u); + atomicAnd(&workgroup_struct.atomic_arr[1], 1i); + + workgroupBarrier(); + + atomicOr(&storage_atomic_scalar, 1u); + atomicOr(&storage_atomic_arr[1], 1i); + atomicOr(&storage_struct.atomic_scalar, 1u); + atomicOr(&storage_struct.atomic_arr[1], 1i); + atomicOr(&workgroup_atomic_scalar, 1u); + atomicOr(&workgroup_atomic_arr[1], 1i); + atomicOr(&workgroup_struct.atomic_scalar, 1u); + atomicOr(&workgroup_struct.atomic_arr[1], 1i); + + workgroupBarrier(); + + atomicXor(&storage_atomic_scalar, 1u); + atomicXor(&storage_atomic_arr[1], 1i); + atomicXor(&storage_struct.atomic_scalar, 1u); + atomicXor(&storage_struct.atomic_arr[1], 1i); + atomicXor(&workgroup_atomic_scalar, 1u); + atomicXor(&workgroup_atomic_arr[1], 1i); + atomicXor(&workgroup_struct.atomic_scalar, 1u); + atomicXor(&workgroup_struct.atomic_arr[1], 1i); + + atomicExchange(&storage_atomic_scalar, 1u); + atomicExchange(&storage_atomic_arr[1], 1i); + atomicExchange(&storage_struct.atomic_scalar, 1u); + atomicExchange(&storage_struct.atomic_arr[1], 1i); + atomicExchange(&workgroup_atomic_scalar, 1u); + atomicExchange(&workgroup_atomic_arr[1], 1i); + atomicExchange(&workgroup_struct.atomic_scalar, 1u); + atomicExchange(&workgroup_struct.atomic_arr[1], 1i); + + // // TODO: https://github.com/gpuweb/gpuweb/issues/2021 + // atomicCompareExchangeWeak(&storage_atomic_scalar, 1u); + // atomicCompareExchangeWeak(&storage_atomic_arr[1], 1i); + // atomicCompareExchangeWeak(&storage_struct.atomic_scalar, 1u); + // atomicCompareExchangeWeak(&storage_struct.atomic_arr[1], 1i); + // atomicCompareExchangeWeak(&workgroup_atomic_scalar, 1u); + // atomicCompareExchangeWeak(&workgroup_atomic_arr[1], 1i); + // atomicCompareExchangeWeak(&workgroup_struct.atomic_scalar, 1u); + // atomicCompareExchangeWeak(&workgroup_struct.atomic_arr[1], 1i); +} diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron index 01e08a63b..8c5097f65 100644 --- a/tests/out/analysis/access.info.ron +++ b/tests/out/analysis/access.info.ron @@ -5123,633 +5123,6 @@ ], sampling: [], ), - ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), - uniformity: ( - non_uniform_result: None, - requirements: ( - bits: 0, - ), - ), - may_kill: false, - sampling_set: [], - global_uses: [ - ( - bits: 0, - ), - ( - bits: 3, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ], - expressions: [ - ( - uniformity: ( - non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), - ), - ref_count: 8, - assignable_global: None, - ty: Value(Pointer( - base: 3, - space: Function, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(5), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(5), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(8), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: Some(9), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(9), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(12), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: Some(13), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(13), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(16), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: Some(17), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(17), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(20), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: Some(21), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(21), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(24), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: Some(25), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(25), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(28), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: Some(29), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(29), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(32), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: Some(33), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(33), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(36), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: Some(37), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 14, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(37), - requirements: ( - bits: 0, - ), - ), - ref_count: 1, - assignable_global: Some(2), - ty: Value(Pointer( - base: 9, - space: Storage( - access: ( - bits: 3, - ), - ), - )), - ), - ], - sampling: [], - ), ( flags: ( bits: 63, diff --git a/tests/out/glsl/atomicOps.cs_main.Compute.glsl b/tests/out/glsl/atomicOps.cs_main.Compute.glsl new file mode 100644 index 000000000..30086fa8e --- /dev/null +++ b/tests/out/glsl/atomicOps.cs_main.Compute.glsl @@ -0,0 +1,132 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 2, local_size_y = 1, local_size_z = 1) in; + +struct Struct { + uint atomic_scalar; + int atomic_arr[2]; +}; +layout(std430) buffer type_block_0Compute { uint _group_0_binding_0_cs; }; + +layout(std430) buffer type_2_block_1Compute { int _group_0_binding_1_cs[2]; }; + +layout(std430) buffer Struct_block_2Compute { Struct _group_0_binding_2_cs; }; + +shared uint workgroup_atomic_scalar; + +shared int workgroup_atomic_arr[2]; + +shared Struct workgroup_struct; + + +void main() { + if (gl_LocalInvocationID == uvec3(0u)) { + workgroup_atomic_scalar = 0u; + workgroup_atomic_arr = int[2](0, 0); + workgroup_struct = Struct(0u, int[2](0, 0)); + } + memoryBarrierShared(); + barrier(); + uvec3 id = gl_LocalInvocationID; + _group_0_binding_0_cs = 1u; + _group_0_binding_1_cs[1] = 1; + _group_0_binding_2_cs.atomic_scalar = 1u; + _group_0_binding_2_cs.atomic_arr[1] = 1; + workgroup_atomic_scalar = 1u; + workgroup_atomic_arr[1] = 1; + workgroup_struct.atomic_scalar = 1u; + workgroup_struct.atomic_arr[1] = 1; + memoryBarrierShared(); + barrier(); + uint unnamed = _group_0_binding_0_cs; + int unnamed_1 = _group_0_binding_1_cs[1]; + uint unnamed_2 = _group_0_binding_2_cs.atomic_scalar; + int unnamed_3 = _group_0_binding_2_cs.atomic_arr[1]; + uint unnamed_4 = workgroup_atomic_scalar; + int unnamed_5 = workgroup_atomic_arr[1]; + uint unnamed_6 = workgroup_struct.atomic_scalar; + int unnamed_7 = workgroup_struct.atomic_arr[1]; + memoryBarrierShared(); + barrier(); + uint _e59 = atomicAdd(_group_0_binding_0_cs, 1u); + int _e64 = atomicAdd(_group_0_binding_1_cs[1], 1); + uint _e68 = atomicAdd(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e74 = atomicAdd(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e77 = atomicAdd(workgroup_atomic_scalar, 1u); + int _e82 = atomicAdd(workgroup_atomic_arr[1], 1); + uint _e86 = atomicAdd(workgroup_struct.atomic_scalar, 1u); + int _e92 = atomicAdd(workgroup_struct.atomic_arr[1], 1); + memoryBarrierShared(); + barrier(); + uint _e95 = atomicAdd(_group_0_binding_0_cs, -1u); + int _e100 = atomicAdd(_group_0_binding_1_cs[1], -1); + uint _e104 = atomicAdd(_group_0_binding_2_cs.atomic_scalar, -1u); + int _e110 = atomicAdd(_group_0_binding_2_cs.atomic_arr[1], -1); + uint _e113 = atomicAdd(workgroup_atomic_scalar, -1u); + int _e118 = atomicAdd(workgroup_atomic_arr[1], -1); + uint _e122 = atomicAdd(workgroup_struct.atomic_scalar, -1u); + int _e128 = atomicAdd(workgroup_struct.atomic_arr[1], -1); + memoryBarrierShared(); + barrier(); + uint _e131 = atomicMax(_group_0_binding_0_cs, 1u); + int _e136 = atomicMax(_group_0_binding_1_cs[1], 1); + uint _e140 = atomicMax(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e146 = atomicMax(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e149 = atomicMax(workgroup_atomic_scalar, 1u); + int _e154 = atomicMax(workgroup_atomic_arr[1], 1); + uint _e158 = atomicMax(workgroup_struct.atomic_scalar, 1u); + int _e164 = atomicMax(workgroup_struct.atomic_arr[1], 1); + memoryBarrierShared(); + barrier(); + uint _e167 = atomicMin(_group_0_binding_0_cs, 1u); + int _e172 = atomicMin(_group_0_binding_1_cs[1], 1); + uint _e176 = atomicMin(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e182 = atomicMin(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e185 = atomicMin(workgroup_atomic_scalar, 1u); + int _e190 = atomicMin(workgroup_atomic_arr[1], 1); + uint _e194 = atomicMin(workgroup_struct.atomic_scalar, 1u); + int _e200 = atomicMin(workgroup_struct.atomic_arr[1], 1); + memoryBarrierShared(); + barrier(); + uint _e203 = atomicAnd(_group_0_binding_0_cs, 1u); + int _e208 = atomicAnd(_group_0_binding_1_cs[1], 1); + uint _e212 = atomicAnd(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e218 = atomicAnd(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e221 = atomicAnd(workgroup_atomic_scalar, 1u); + int _e226 = atomicAnd(workgroup_atomic_arr[1], 1); + uint _e230 = atomicAnd(workgroup_struct.atomic_scalar, 1u); + int _e236 = atomicAnd(workgroup_struct.atomic_arr[1], 1); + memoryBarrierShared(); + barrier(); + uint _e239 = atomicOr(_group_0_binding_0_cs, 1u); + int _e244 = atomicOr(_group_0_binding_1_cs[1], 1); + uint _e248 = atomicOr(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e254 = atomicOr(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e257 = atomicOr(workgroup_atomic_scalar, 1u); + int _e262 = atomicOr(workgroup_atomic_arr[1], 1); + uint _e266 = atomicOr(workgroup_struct.atomic_scalar, 1u); + int _e272 = atomicOr(workgroup_struct.atomic_arr[1], 1); + memoryBarrierShared(); + barrier(); + uint _e275 = atomicXor(_group_0_binding_0_cs, 1u); + int _e280 = atomicXor(_group_0_binding_1_cs[1], 1); + uint _e284 = atomicXor(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e290 = atomicXor(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e293 = atomicXor(workgroup_atomic_scalar, 1u); + int _e298 = atomicXor(workgroup_atomic_arr[1], 1); + uint _e302 = atomicXor(workgroup_struct.atomic_scalar, 1u); + int _e308 = atomicXor(workgroup_struct.atomic_arr[1], 1); + uint _e311 = atomicExchange(_group_0_binding_0_cs, 1u); + int _e316 = atomicExchange(_group_0_binding_1_cs[1], 1); + uint _e320 = atomicExchange(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e326 = atomicExchange(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e329 = atomicExchange(workgroup_atomic_scalar, 1u); + int _e334 = atomicExchange(workgroup_atomic_arr[1], 1); + uint _e338 = atomicExchange(workgroup_struct.atomic_scalar, 1u); + int _e344 = atomicExchange(workgroup_struct.atomic_arr[1], 1); + return; +} + diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index f20cb726d..27786717d 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -311,32 +311,6 @@ float4 foo_frag() : SV_Target0 return (0.0).xxxx; } -[numthreads(1, 1, 1)] -void atomics() -{ - int tmp = (int)0; - - int value_1 = asint(bar.Load(96)); - int _e7; bar.InterlockedAdd(96, 5, _e7); - tmp = _e7; - int _e11; bar.InterlockedAdd(96, -5, _e11); - tmp = _e11; - int _e15; bar.InterlockedAnd(96, 5, _e15); - tmp = _e15; - int _e19; bar.InterlockedOr(96, 5, _e19); - tmp = _e19; - int _e23; bar.InterlockedXor(96, 5, _e23); - tmp = _e23; - int _e27; bar.InterlockedMin(96, 5, _e27); - tmp = _e27; - int _e31; bar.InterlockedMax(96, 5, _e31); - tmp = _e31; - int _e35; bar.InterlockedExchange(96, 5, _e35); - tmp = _e35; - bar.Store(96, asuint(value_1)); - return; -} - [numthreads(1, 1, 1)] void assign_through_ptr(uint3 __local_invocation_id : SV_GroupThreadID) { diff --git a/tests/out/hlsl/access.hlsl.config b/tests/out/hlsl/access.hlsl.config index b68dda72d..de7719bdf 100644 --- a/tests/out/hlsl/access.hlsl.config +++ b/tests/out/hlsl/access.hlsl.config @@ -1,3 +1,3 @@ vertex=(foo_vert:vs_5_1 ) fragment=(foo_frag:ps_5_1 ) -compute=(atomics:cs_5_1 assign_through_ptr:cs_5_1 ) +compute=(assign_through_ptr:cs_5_1 ) diff --git a/tests/out/hlsl/atomicOps.hlsl b/tests/out/hlsl/atomicOps.hlsl new file mode 100644 index 000000000..f6322cd92 --- /dev/null +++ b/tests/out/hlsl/atomicOps.hlsl @@ -0,0 +1,112 @@ + +struct Struct { + uint atomic_scalar; + int atomic_arr[2]; +}; + +RWByteAddressBuffer storage_atomic_scalar : register(u0); +RWByteAddressBuffer storage_atomic_arr : register(u1); +RWByteAddressBuffer storage_struct : register(u2); +groupshared uint workgroup_atomic_scalar; +groupshared int workgroup_atomic_arr[2]; +groupshared Struct workgroup_struct; + +[numthreads(2, 1, 1)] +void cs_main(uint3 id : SV_GroupThreadID, uint3 __local_invocation_id : SV_GroupThreadID) +{ + if (all(__local_invocation_id == uint3(0u, 0u, 0u))) { + workgroup_atomic_scalar = (uint)0; + workgroup_atomic_arr = (int[2])0; + workgroup_struct = (Struct)0; + } + GroupMemoryBarrierWithGroupSync(); + storage_atomic_scalar.Store(0, asuint(1u)); + storage_atomic_arr.Store(4, asuint(1)); + storage_struct.Store(0, asuint(1u)); + storage_struct.Store(4+4, asuint(1)); + workgroup_atomic_scalar = 1u; + workgroup_atomic_arr[1] = 1; + workgroup_struct.atomic_scalar = 1u; + workgroup_struct.atomic_arr[1] = 1; + GroupMemoryBarrierWithGroupSync(); + uint unnamed = asuint(storage_atomic_scalar.Load(0)); + int unnamed_1 = asint(storage_atomic_arr.Load(4)); + uint unnamed_2 = asuint(storage_struct.Load(0)); + int unnamed_3 = asint(storage_struct.Load(4+4)); + uint unnamed_4 = workgroup_atomic_scalar; + int unnamed_5 = workgroup_atomic_arr[1]; + uint unnamed_6 = workgroup_struct.atomic_scalar; + int unnamed_7 = workgroup_struct.atomic_arr[1]; + GroupMemoryBarrierWithGroupSync(); + uint _e59; storage_atomic_scalar.InterlockedAdd(0, 1u, _e59); + int _e64; storage_atomic_arr.InterlockedAdd(4, 1, _e64); + uint _e68; storage_struct.InterlockedAdd(0, 1u, _e68); + int _e74; storage_struct.InterlockedAdd(4+4, 1, _e74); + uint _e77; InterlockedAdd(workgroup_atomic_scalar, 1u, _e77); + int _e82; InterlockedAdd(workgroup_atomic_arr[1], 1, _e82); + uint _e86; InterlockedAdd(workgroup_struct.atomic_scalar, 1u, _e86); + int _e92; InterlockedAdd(workgroup_struct.atomic_arr[1], 1, _e92); + GroupMemoryBarrierWithGroupSync(); + uint _e95; storage_atomic_scalar.InterlockedAdd(0, -1u, _e95); + int _e100; storage_atomic_arr.InterlockedAdd(4, -1, _e100); + uint _e104; storage_struct.InterlockedAdd(0, -1u, _e104); + int _e110; storage_struct.InterlockedAdd(4+4, -1, _e110); + uint _e113; InterlockedAdd(workgroup_atomic_scalar, -1u, _e113); + int _e118; InterlockedAdd(workgroup_atomic_arr[1], -1, _e118); + uint _e122; InterlockedAdd(workgroup_struct.atomic_scalar, -1u, _e122); + int _e128; InterlockedAdd(workgroup_struct.atomic_arr[1], -1, _e128); + GroupMemoryBarrierWithGroupSync(); + uint _e131; storage_atomic_scalar.InterlockedMax(0, 1u, _e131); + int _e136; storage_atomic_arr.InterlockedMax(4, 1, _e136); + uint _e140; storage_struct.InterlockedMax(0, 1u, _e140); + int _e146; storage_struct.InterlockedMax(4+4, 1, _e146); + uint _e149; InterlockedMax(workgroup_atomic_scalar, 1u, _e149); + int _e154; InterlockedMax(workgroup_atomic_arr[1], 1, _e154); + uint _e158; InterlockedMax(workgroup_struct.atomic_scalar, 1u, _e158); + int _e164; InterlockedMax(workgroup_struct.atomic_arr[1], 1, _e164); + GroupMemoryBarrierWithGroupSync(); + uint _e167; storage_atomic_scalar.InterlockedMin(0, 1u, _e167); + int _e172; storage_atomic_arr.InterlockedMin(4, 1, _e172); + uint _e176; storage_struct.InterlockedMin(0, 1u, _e176); + int _e182; storage_struct.InterlockedMin(4+4, 1, _e182); + uint _e185; InterlockedMin(workgroup_atomic_scalar, 1u, _e185); + int _e190; InterlockedMin(workgroup_atomic_arr[1], 1, _e190); + uint _e194; InterlockedMin(workgroup_struct.atomic_scalar, 1u, _e194); + int _e200; InterlockedMin(workgroup_struct.atomic_arr[1], 1, _e200); + GroupMemoryBarrierWithGroupSync(); + uint _e203; storage_atomic_scalar.InterlockedAnd(0, 1u, _e203); + int _e208; storage_atomic_arr.InterlockedAnd(4, 1, _e208); + uint _e212; storage_struct.InterlockedAnd(0, 1u, _e212); + int _e218; storage_struct.InterlockedAnd(4+4, 1, _e218); + uint _e221; InterlockedAnd(workgroup_atomic_scalar, 1u, _e221); + int _e226; InterlockedAnd(workgroup_atomic_arr[1], 1, _e226); + uint _e230; InterlockedAnd(workgroup_struct.atomic_scalar, 1u, _e230); + int _e236; InterlockedAnd(workgroup_struct.atomic_arr[1], 1, _e236); + GroupMemoryBarrierWithGroupSync(); + uint _e239; storage_atomic_scalar.InterlockedOr(0, 1u, _e239); + int _e244; storage_atomic_arr.InterlockedOr(4, 1, _e244); + uint _e248; storage_struct.InterlockedOr(0, 1u, _e248); + int _e254; storage_struct.InterlockedOr(4+4, 1, _e254); + uint _e257; InterlockedOr(workgroup_atomic_scalar, 1u, _e257); + int _e262; InterlockedOr(workgroup_atomic_arr[1], 1, _e262); + uint _e266; InterlockedOr(workgroup_struct.atomic_scalar, 1u, _e266); + int _e272; InterlockedOr(workgroup_struct.atomic_arr[1], 1, _e272); + GroupMemoryBarrierWithGroupSync(); + uint _e275; storage_atomic_scalar.InterlockedXor(0, 1u, _e275); + int _e280; storage_atomic_arr.InterlockedXor(4, 1, _e280); + uint _e284; storage_struct.InterlockedXor(0, 1u, _e284); + int _e290; storage_struct.InterlockedXor(4+4, 1, _e290); + uint _e293; InterlockedXor(workgroup_atomic_scalar, 1u, _e293); + int _e298; InterlockedXor(workgroup_atomic_arr[1], 1, _e298); + uint _e302; InterlockedXor(workgroup_struct.atomic_scalar, 1u, _e302); + int _e308; InterlockedXor(workgroup_struct.atomic_arr[1], 1, _e308); + uint _e311; storage_atomic_scalar.InterlockedExchange(0, 1u, _e311); + int _e316; storage_atomic_arr.InterlockedExchange(4, 1, _e316); + uint _e320; storage_struct.InterlockedExchange(0, 1u, _e320); + int _e326; storage_struct.InterlockedExchange(4+4, 1, _e326); + uint _e329; InterlockedExchange(workgroup_atomic_scalar, 1u, _e329); + int _e334; InterlockedExchange(workgroup_atomic_arr[1], 1, _e334); + uint _e338; InterlockedExchange(workgroup_struct.atomic_scalar, 1u, _e338); + int _e344; InterlockedExchange(workgroup_struct.atomic_arr[1], 1, _e344); + return; +} diff --git a/tests/out/hlsl/atomicOps.hlsl.config b/tests/out/hlsl/atomicOps.hlsl.config new file mode 100644 index 000000000..522d99ed1 --- /dev/null +++ b/tests/out/hlsl/atomicOps.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(cs_main:cs_5_1 ) diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 41772b933..0c1f9df1c 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -2535,254 +2535,6 @@ ], ), ), - ( - name: "atomics", - stage: Compute, - early_depth_test: None, - workgroup_size: (1, 1, 1), - function: ( - name: Some("atomics"), - arguments: [], - result: None, - local_variables: [ - ( - name: Some("tmp"), - ty: 3, - init: None, - ), - ], - expressions: [ - LocalVariable(1), - GlobalVariable(2), - AccessIndex( - base: 2, - index: 2, - ), - Load( - pointer: 3, - ), - GlobalVariable(2), - AccessIndex( - base: 5, - index: 2, - ), - Constant(26), - AtomicResult( - ty: 3, - comparison: false, - ), - GlobalVariable(2), - AccessIndex( - base: 9, - index: 2, - ), - Constant(26), - AtomicResult( - ty: 3, - comparison: false, - ), - GlobalVariable(2), - AccessIndex( - base: 13, - index: 2, - ), - Constant(26), - AtomicResult( - ty: 3, - comparison: false, - ), - GlobalVariable(2), - AccessIndex( - base: 17, - index: 2, - ), - Constant(26), - AtomicResult( - ty: 3, - comparison: false, - ), - GlobalVariable(2), - AccessIndex( - base: 21, - index: 2, - ), - Constant(26), - AtomicResult( - ty: 3, - comparison: false, - ), - GlobalVariable(2), - AccessIndex( - base: 25, - index: 2, - ), - Constant(26), - AtomicResult( - ty: 3, - comparison: false, - ), - GlobalVariable(2), - AccessIndex( - base: 29, - index: 2, - ), - Constant(26), - AtomicResult( - ty: 3, - comparison: false, - ), - GlobalVariable(2), - AccessIndex( - base: 33, - index: 2, - ), - Constant(26), - AtomicResult( - ty: 3, - comparison: false, - ), - GlobalVariable(2), - AccessIndex( - base: 37, - index: 2, - ), - ], - named_expressions: { - 4: "value", - }, - body: [ - Emit(( - start: 2, - end: 4, - )), - Emit(( - start: 5, - end: 6, - )), - Atomic( - pointer: 6, - fun: Add, - value: 7, - result: 8, - ), - Store( - pointer: 1, - value: 8, - ), - Emit(( - start: 9, - end: 10, - )), - Atomic( - pointer: 10, - fun: Subtract, - value: 11, - result: 12, - ), - Store( - pointer: 1, - value: 12, - ), - Emit(( - start: 13, - end: 14, - )), - Atomic( - pointer: 14, - fun: And, - value: 15, - result: 16, - ), - Store( - pointer: 1, - value: 16, - ), - Emit(( - start: 17, - end: 18, - )), - Atomic( - pointer: 18, - fun: InclusiveOr, - value: 19, - result: 20, - ), - Store( - pointer: 1, - value: 20, - ), - Emit(( - start: 21, - end: 22, - )), - Atomic( - pointer: 22, - fun: ExclusiveOr, - value: 23, - result: 24, - ), - Store( - pointer: 1, - value: 24, - ), - Emit(( - start: 25, - end: 26, - )), - Atomic( - pointer: 26, - fun: Min, - value: 27, - result: 28, - ), - Store( - pointer: 1, - value: 28, - ), - Emit(( - start: 29, - end: 30, - )), - Atomic( - pointer: 30, - fun: Max, - value: 31, - result: 32, - ), - Store( - pointer: 1, - value: 32, - ), - Emit(( - start: 33, - end: 34, - )), - Atomic( - pointer: 34, - fun: Exchange( - compare: None, - ), - value: 35, - result: 36, - ), - Store( - pointer: 1, - value: 36, - ), - Emit(( - start: 37, - end: 38, - )), - Store( - pointer: 38, - value: 4, - ), - Return( - value: None, - ), - ], - ), - ), ( name: "assign_through_ptr", stage: Compute, diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 8ad40973f..a4967117f 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -222,33 +222,6 @@ fragment foo_fragOutput foo_frag( } -kernel void atomics( - device Bar& bar [[buffer(0)]] -, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] -) { - int tmp = {}; - int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed); - int _e7 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e7; - int _e11 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e11; - int _e15 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e15; - int _e19 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e19; - int _e23 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e23; - int _e27 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e27; - int _e31 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e31; - int _e35 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed); - tmp = _e35; - metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed); - return; -} - - kernel void assign_through_ptr( metal::uint3 __local_invocation_id [[thread_position_in_threadgroup]] , threadgroup uint& val diff --git a/tests/out/msl/atomicOps.msl b/tests/out/msl/atomicOps.msl new file mode 100644 index 000000000..feed8fb74 --- /dev/null +++ b/tests/out/msl/atomicOps.msl @@ -0,0 +1,126 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct type_2 { + metal::atomic_int inner[2]; +}; +struct Struct { + metal::atomic_uint atomic_scalar; + type_2 atomic_arr; +}; + +struct cs_mainInput { +}; +kernel void cs_main( + metal::uint3 id [[thread_position_in_threadgroup]] +, device metal::atomic_uint& storage_atomic_scalar [[user(fake0)]] +, device type_2& storage_atomic_arr [[user(fake0)]] +, device Struct& storage_struct [[user(fake0)]] +, threadgroup metal::atomic_uint& workgroup_atomic_scalar +, threadgroup type_2& workgroup_atomic_arr +, threadgroup Struct& workgroup_struct +) { + if (metal::all(id == metal::uint3(0u))) { + metal::atomic_store_explicit(&workgroup_atomic_scalar, 0, metal::memory_order_relaxed); + for (int __i0 = 0; __i0 < 2; __i0++) { + metal::atomic_store_explicit(&workgroup_atomic_arr.inner[__i0], 0, metal::memory_order_relaxed); + } + metal::atomic_store_explicit(&workgroup_struct.atomic_scalar, 0, metal::memory_order_relaxed); + for (int __i0 = 0; __i0 < 2; __i0++) { + metal::atomic_store_explicit(&workgroup_struct.atomic_arr.inner[__i0], 0, metal::memory_order_relaxed); + } + } + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + metal::atomic_store_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + metal::atomic_store_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::atomic_store_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + metal::atomic_store_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::atomic_store_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + metal::atomic_store_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::atomic_store_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + metal::atomic_store_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + uint unnamed = metal::atomic_load_explicit(&storage_atomic_scalar, metal::memory_order_relaxed); + int unnamed_1 = metal::atomic_load_explicit(&storage_atomic_arr.inner[1], metal::memory_order_relaxed); + uint unnamed_2 = metal::atomic_load_explicit(&storage_struct.atomic_scalar, metal::memory_order_relaxed); + int unnamed_3 = metal::atomic_load_explicit(&storage_struct.atomic_arr.inner[1], metal::memory_order_relaxed); + uint unnamed_4 = metal::atomic_load_explicit(&workgroup_atomic_scalar, metal::memory_order_relaxed); + int unnamed_5 = metal::atomic_load_explicit(&workgroup_atomic_arr.inner[1], metal::memory_order_relaxed); + uint unnamed_6 = metal::atomic_load_explicit(&workgroup_struct.atomic_scalar, metal::memory_order_relaxed); + int unnamed_7 = metal::atomic_load_explicit(&workgroup_struct.atomic_arr.inner[1], metal::memory_order_relaxed); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + uint _e59 = metal::atomic_fetch_add_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e64 = metal::atomic_fetch_add_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e68 = metal::atomic_fetch_add_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e74 = metal::atomic_fetch_add_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e77 = metal::atomic_fetch_add_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e82 = metal::atomic_fetch_add_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e86 = metal::atomic_fetch_add_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e92 = metal::atomic_fetch_add_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + uint _e95 = metal::atomic_fetch_sub_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e100 = metal::atomic_fetch_sub_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e104 = metal::atomic_fetch_sub_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e110 = metal::atomic_fetch_sub_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e113 = metal::atomic_fetch_sub_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e118 = metal::atomic_fetch_sub_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e122 = metal::atomic_fetch_sub_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e128 = metal::atomic_fetch_sub_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + uint _e131 = metal::atomic_fetch_max_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e136 = metal::atomic_fetch_max_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e140 = metal::atomic_fetch_max_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e146 = metal::atomic_fetch_max_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e149 = metal::atomic_fetch_max_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e154 = metal::atomic_fetch_max_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e158 = metal::atomic_fetch_max_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e164 = metal::atomic_fetch_max_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + uint _e167 = metal::atomic_fetch_min_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e172 = metal::atomic_fetch_min_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e176 = metal::atomic_fetch_min_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e182 = metal::atomic_fetch_min_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e185 = metal::atomic_fetch_min_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e190 = metal::atomic_fetch_min_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e194 = metal::atomic_fetch_min_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e200 = metal::atomic_fetch_min_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + uint _e203 = metal::atomic_fetch_and_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e208 = metal::atomic_fetch_and_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e212 = metal::atomic_fetch_and_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e218 = metal::atomic_fetch_and_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e221 = metal::atomic_fetch_and_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e226 = metal::atomic_fetch_and_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e230 = metal::atomic_fetch_and_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e236 = metal::atomic_fetch_and_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + uint _e239 = metal::atomic_fetch_or_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e244 = metal::atomic_fetch_or_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e248 = metal::atomic_fetch_or_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e254 = metal::atomic_fetch_or_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e257 = metal::atomic_fetch_or_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e262 = metal::atomic_fetch_or_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e266 = metal::atomic_fetch_or_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e272 = metal::atomic_fetch_or_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + uint _e275 = metal::atomic_fetch_xor_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e280 = metal::atomic_fetch_xor_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e284 = metal::atomic_fetch_xor_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e290 = metal::atomic_fetch_xor_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e293 = metal::atomic_fetch_xor_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e298 = metal::atomic_fetch_xor_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e302 = metal::atomic_fetch_xor_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e308 = metal::atomic_fetch_xor_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e311 = metal::atomic_exchange_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e316 = metal::atomic_exchange_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e320 = metal::atomic_exchange_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e326 = metal::atomic_exchange_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e329 = metal::atomic_exchange_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e334 = metal::atomic_exchange_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e338 = metal::atomic_exchange_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e344 = metal::atomic_exchange_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + return; +} diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index a88232292..fa828b4d8 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,18 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 354 +; Bound: 328 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %247 "foo_vert" %242 %245 OpEntryPoint Fragment %289 "foo_frag" %288 -OpEntryPoint GLCompute %308 "atomics" -OpEntryPoint GLCompute %334 "assign_through_ptr" %337 +OpEntryPoint GLCompute %308 "assign_through_ptr" %311 OpExecutionMode %289 OriginUpperLeft OpExecutionMode %308 LocalSize 1 1 1 -OpExecutionMode %334 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %36 0 "a" OpMemberName %36 1 "b" @@ -56,10 +54,8 @@ OpName %238 "c2" OpName %242 "vi" OpName %247 "foo_vert" OpName %289 "foo_frag" -OpName %305 "tmp" -OpName %308 "atomics" -OpName %331 "arr" -OpName %334 "assign_through_ptr" +OpName %305 "arr" +OpName %308 "assign_through_ptr" OpMemberDecorate %36 0 Offset 0 OpMemberDecorate %36 1 Offset 16 OpMemberDecorate %36 2 Offset 28 @@ -107,7 +103,7 @@ OpMemberDecorate %83 0 Offset 0 OpDecorate %242 BuiltIn VertexIndex OpDecorate %245 BuiltIn Position OpDecorate %288 Location 0 -OpDecorate %337 BuiltIn LocalInvocationId +OpDecorate %311 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -233,17 +229,14 @@ OpDecorate %337 BuiltIn LocalInvocationId %270 = OpTypePointer StorageBuffer %37 %271 = OpConstant %4 5 %288 = OpVariable %246 Output -%306 = OpConstantNull %6 -%310 = OpTypePointer StorageBuffer %6 -%313 = OpConstant %4 64 -%332 = OpConstantNull %62 -%336 = OpConstantNull %4 -%338 = OpTypePointer Input %35 -%337 = OpVariable %338 Input -%340 = OpConstantNull %35 -%342 = OpTypeBool -%341 = OpTypeVector %342 3 -%347 = OpConstant %4 264 +%306 = OpConstantNull %62 +%310 = OpConstantNull %4 +%312 = OpTypePointer Input %35 +%311 = OpVariable %312 Input +%314 = OpConstantNull %35 +%316 = OpTypeBool +%315 = OpTypeVector %316 3 +%321 = OpConstant %4 264 %93 = OpFunction %2 None %94 %92 = OpLabel %86 = OpVariable %87 Function %88 @@ -484,61 +477,26 @@ OpReturn OpFunctionEnd %308 = OpFunction %2 None %94 %307 = OpLabel -%305 = OpVariable %87 Function %306 +%305 = OpVariable %63 Function %306 OpBranch %309 %309 = OpLabel -%311 = OpAccessChain %310 %74 %30 -%312 = OpAtomicLoad %6 %311 %9 %313 -%315 = OpAccessChain %310 %74 %30 -%314 = OpAtomicIAdd %6 %315 %9 %313 %26 -OpStore %305 %314 -%317 = OpAccessChain %310 %74 %30 -%316 = OpAtomicISub %6 %317 %9 %313 %26 -OpStore %305 %316 -%319 = OpAccessChain %310 %74 %30 -%318 = OpAtomicAnd %6 %319 %9 %313 %26 -OpStore %305 %318 -%321 = OpAccessChain %310 %74 %30 -%320 = OpAtomicOr %6 %321 %9 %313 %26 -OpStore %305 %320 -%323 = OpAccessChain %310 %74 %30 -%322 = OpAtomicXor %6 %323 %9 %313 %26 -OpStore %305 %322 -%325 = OpAccessChain %310 %74 %30 -%324 = OpAtomicSMin %6 %325 %9 %313 %26 -OpStore %305 %324 -%327 = OpAccessChain %310 %74 %30 -%326 = OpAtomicSMax %6 %327 %9 %313 %26 -OpStore %305 %326 -%329 = OpAccessChain %310 %74 %30 -%328 = OpAtomicExchange %6 %329 %9 %313 %26 -OpStore %305 %328 -%330 = OpAccessChain %310 %74 %30 -OpAtomicStore %330 %9 %313 %312 -OpReturn -OpFunctionEnd -%334 = OpFunction %2 None %94 -%333 = OpLabel -%331 = OpVariable %63 Function %332 -OpBranch %335 -%335 = OpLabel -%339 = OpLoad %35 %337 -%343 = OpIEqual %341 %339 %340 -%344 = OpAll %342 %343 -OpSelectionMerge %345 None -OpBranchConditional %344 %346 %345 -%346 = OpLabel -OpStore %85 %336 -OpBranch %345 -%345 = OpLabel -OpControlBarrier %30 %30 %347 -OpBranch %348 -%348 = OpLabel -%349 = OpCompositeConstruct %57 %14 %14 %14 %14 -%350 = OpCompositeConstruct %57 %25 %25 %25 %25 -%351 = OpCompositeConstruct %62 %349 %350 -OpStore %331 %351 -%352 = OpFunctionCall %2 %225 %85 -%353 = OpFunctionCall %2 %230 %331 +%313 = OpLoad %35 %311 +%317 = OpIEqual %315 %313 %314 +%318 = OpAll %316 %317 +OpSelectionMerge %319 None +OpBranchConditional %318 %320 %319 +%320 = OpLabel +OpStore %85 %310 +OpBranch %319 +%319 = OpLabel +OpControlBarrier %30 %30 %321 +OpBranch %322 +%322 = OpLabel +%323 = OpCompositeConstruct %57 %14 %14 %14 %14 +%324 = OpCompositeConstruct %57 %25 %25 %25 %25 +%325 = OpCompositeConstruct %62 %323 %324 +OpStore %305 %325 +%326 = OpFunctionCall %2 %225 %85 +%327 = OpFunctionCall %2 %230 %305 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/atomicOps.spvasm b/tests/out/spv/atomicOps.spvasm new file mode 100644 index 000000000..8e9bad660 --- /dev/null +++ b/tests/out/spv/atomicOps.spvasm @@ -0,0 +1,240 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 189 +OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %30 "cs_main" %27 +OpExecutionMode %30 LocalSize 2 1 1 +OpDecorate %8 ArrayStride 4 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 4 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 0 +OpDecorate %12 Block +OpMemberDecorate %12 0 Offset 0 +OpDecorate %14 DescriptorSet 0 +OpDecorate %14 Binding 1 +OpDecorate %15 Block +OpMemberDecorate %15 0 Offset 0 +OpDecorate %17 DescriptorSet 0 +OpDecorate %17 Binding 2 +OpDecorate %18 Block +OpMemberDecorate %18 0 Offset 0 +OpDecorate %27 BuiltIn LocalInvocationId +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 2 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 1 +%7 = OpConstant %4 1 +%8 = OpTypeArray %4 %3 +%9 = OpTypeStruct %6 %8 +%10 = OpTypeVector %6 3 +%12 = OpTypeStruct %6 +%13 = OpTypePointer StorageBuffer %12 +%11 = OpVariable %13 StorageBuffer +%15 = OpTypeStruct %8 +%16 = OpTypePointer StorageBuffer %15 +%14 = OpVariable %16 StorageBuffer +%18 = OpTypeStruct %9 +%19 = OpTypePointer StorageBuffer %18 +%17 = OpVariable %19 StorageBuffer +%21 = OpTypePointer Workgroup %6 +%20 = OpVariable %21 Workgroup +%23 = OpTypePointer Workgroup %8 +%22 = OpVariable %23 Workgroup +%25 = OpTypePointer Workgroup %9 +%24 = OpVariable %25 Workgroup +%28 = OpTypePointer Input %10 +%27 = OpVariable %28 Input +%31 = OpTypeFunction %2 +%32 = OpTypePointer StorageBuffer %6 +%33 = OpConstant %6 0 +%35 = OpTypePointer StorageBuffer %8 +%37 = OpTypePointer StorageBuffer %9 +%40 = OpConstantNull %6 +%41 = OpConstantNull %8 +%42 = OpConstantNull %9 +%43 = OpConstantNull %10 +%45 = OpTypeBool +%44 = OpTypeVector %45 3 +%50 = OpConstant %6 2 +%51 = OpConstant %6 264 +%53 = OpConstant %6 64 +%54 = OpTypePointer StorageBuffer %4 +%58 = OpConstant %6 256 +%59 = OpTypePointer Workgroup %4 +%30 = OpFunction %2 None %31 +%26 = OpLabel +%29 = OpLoad %10 %27 +%34 = OpAccessChain %32 %11 %33 +%36 = OpAccessChain %35 %14 %33 +%38 = OpAccessChain %37 %17 %33 +OpBranch %39 +%39 = OpLabel +%46 = OpIEqual %44 %29 %43 +%47 = OpAll %45 %46 +OpSelectionMerge %48 None +OpBranchConditional %47 %49 %48 +%49 = OpLabel +OpStore %20 %40 +OpStore %22 %41 +OpStore %24 %42 +OpBranch %48 +%48 = OpLabel +OpControlBarrier %50 %50 %51 +OpBranch %52 +%52 = OpLabel +OpAtomicStore %34 %7 %53 %5 +%55 = OpAccessChain %54 %36 %5 +OpAtomicStore %55 %7 %53 %7 +%56 = OpAccessChain %32 %38 %33 +OpAtomicStore %56 %7 %53 %5 +%57 = OpAccessChain %54 %38 %5 %5 +OpAtomicStore %57 %7 %53 %7 +OpAtomicStore %20 %3 %58 %5 +%60 = OpAccessChain %59 %22 %5 +OpAtomicStore %60 %3 %58 %7 +%61 = OpAccessChain %21 %24 %33 +OpAtomicStore %61 %3 %58 %5 +%62 = OpAccessChain %59 %24 %5 %5 +OpAtomicStore %62 %3 %58 %7 +OpControlBarrier %50 %50 %51 +%63 = OpAtomicLoad %6 %34 %7 %53 +%64 = OpAccessChain %54 %36 %5 +%65 = OpAtomicLoad %4 %64 %7 %53 +%66 = OpAccessChain %32 %38 %33 +%67 = OpAtomicLoad %6 %66 %7 %53 +%68 = OpAccessChain %54 %38 %5 %5 +%69 = OpAtomicLoad %4 %68 %7 %53 +%70 = OpAtomicLoad %6 %20 %3 %58 +%71 = OpAccessChain %59 %22 %5 +%72 = OpAtomicLoad %4 %71 %3 %58 +%73 = OpAccessChain %21 %24 %33 +%74 = OpAtomicLoad %6 %73 %3 %58 +%75 = OpAccessChain %59 %24 %5 %5 +%76 = OpAtomicLoad %4 %75 %3 %58 +OpControlBarrier %50 %50 %51 +%77 = OpAtomicIAdd %6 %34 %7 %53 %5 +%79 = OpAccessChain %54 %36 %5 +%78 = OpAtomicIAdd %4 %79 %7 %53 %7 +%81 = OpAccessChain %32 %38 %33 +%80 = OpAtomicIAdd %6 %81 %7 %53 %5 +%83 = OpAccessChain %54 %38 %5 %5 +%82 = OpAtomicIAdd %4 %83 %7 %53 %7 +%84 = OpAtomicIAdd %6 %20 %3 %58 %5 +%86 = OpAccessChain %59 %22 %5 +%85 = OpAtomicIAdd %4 %86 %3 %58 %7 +%88 = OpAccessChain %21 %24 %33 +%87 = OpAtomicIAdd %6 %88 %3 %58 %5 +%90 = OpAccessChain %59 %24 %5 %5 +%89 = OpAtomicIAdd %4 %90 %3 %58 %7 +OpControlBarrier %50 %50 %51 +%91 = OpAtomicISub %6 %34 %7 %53 %5 +%93 = OpAccessChain %54 %36 %5 +%92 = OpAtomicISub %4 %93 %7 %53 %7 +%95 = OpAccessChain %32 %38 %33 +%94 = OpAtomicISub %6 %95 %7 %53 %5 +%97 = OpAccessChain %54 %38 %5 %5 +%96 = OpAtomicISub %4 %97 %7 %53 %7 +%98 = OpAtomicISub %6 %20 %3 %58 %5 +%100 = OpAccessChain %59 %22 %5 +%99 = OpAtomicISub %4 %100 %3 %58 %7 +%102 = OpAccessChain %21 %24 %33 +%101 = OpAtomicISub %6 %102 %3 %58 %5 +%104 = OpAccessChain %59 %24 %5 %5 +%103 = OpAtomicISub %4 %104 %3 %58 %7 +OpControlBarrier %50 %50 %51 +%105 = OpAtomicUMax %6 %34 %7 %53 %5 +%107 = OpAccessChain %54 %36 %5 +%106 = OpAtomicSMax %4 %107 %7 %53 %7 +%109 = OpAccessChain %32 %38 %33 +%108 = OpAtomicUMax %6 %109 %7 %53 %5 +%111 = OpAccessChain %54 %38 %5 %5 +%110 = OpAtomicSMax %4 %111 %7 %53 %7 +%112 = OpAtomicUMax %6 %20 %3 %58 %5 +%114 = OpAccessChain %59 %22 %5 +%113 = OpAtomicSMax %4 %114 %3 %58 %7 +%116 = OpAccessChain %21 %24 %33 +%115 = OpAtomicUMax %6 %116 %3 %58 %5 +%118 = OpAccessChain %59 %24 %5 %5 +%117 = OpAtomicSMax %4 %118 %3 %58 %7 +OpControlBarrier %50 %50 %51 +%119 = OpAtomicUMin %6 %34 %7 %53 %5 +%121 = OpAccessChain %54 %36 %5 +%120 = OpAtomicSMin %4 %121 %7 %53 %7 +%123 = OpAccessChain %32 %38 %33 +%122 = OpAtomicUMin %6 %123 %7 %53 %5 +%125 = OpAccessChain %54 %38 %5 %5 +%124 = OpAtomicSMin %4 %125 %7 %53 %7 +%126 = OpAtomicUMin %6 %20 %3 %58 %5 +%128 = OpAccessChain %59 %22 %5 +%127 = OpAtomicSMin %4 %128 %3 %58 %7 +%130 = OpAccessChain %21 %24 %33 +%129 = OpAtomicUMin %6 %130 %3 %58 %5 +%132 = OpAccessChain %59 %24 %5 %5 +%131 = OpAtomicSMin %4 %132 %3 %58 %7 +OpControlBarrier %50 %50 %51 +%133 = OpAtomicAnd %6 %34 %7 %53 %5 +%135 = OpAccessChain %54 %36 %5 +%134 = OpAtomicAnd %4 %135 %7 %53 %7 +%137 = OpAccessChain %32 %38 %33 +%136 = OpAtomicAnd %6 %137 %7 %53 %5 +%139 = OpAccessChain %54 %38 %5 %5 +%138 = OpAtomicAnd %4 %139 %7 %53 %7 +%140 = OpAtomicAnd %6 %20 %3 %58 %5 +%142 = OpAccessChain %59 %22 %5 +%141 = OpAtomicAnd %4 %142 %3 %58 %7 +%144 = OpAccessChain %21 %24 %33 +%143 = OpAtomicAnd %6 %144 %3 %58 %5 +%146 = OpAccessChain %59 %24 %5 %5 +%145 = OpAtomicAnd %4 %146 %3 %58 %7 +OpControlBarrier %50 %50 %51 +%147 = OpAtomicOr %6 %34 %7 %53 %5 +%149 = OpAccessChain %54 %36 %5 +%148 = OpAtomicOr %4 %149 %7 %53 %7 +%151 = OpAccessChain %32 %38 %33 +%150 = OpAtomicOr %6 %151 %7 %53 %5 +%153 = OpAccessChain %54 %38 %5 %5 +%152 = OpAtomicOr %4 %153 %7 %53 %7 +%154 = OpAtomicOr %6 %20 %3 %58 %5 +%156 = OpAccessChain %59 %22 %5 +%155 = OpAtomicOr %4 %156 %3 %58 %7 +%158 = OpAccessChain %21 %24 %33 +%157 = OpAtomicOr %6 %158 %3 %58 %5 +%160 = OpAccessChain %59 %24 %5 %5 +%159 = OpAtomicOr %4 %160 %3 %58 %7 +OpControlBarrier %50 %50 %51 +%161 = OpAtomicXor %6 %34 %7 %53 %5 +%163 = OpAccessChain %54 %36 %5 +%162 = OpAtomicXor %4 %163 %7 %53 %7 +%165 = OpAccessChain %32 %38 %33 +%164 = OpAtomicXor %6 %165 %7 %53 %5 +%167 = OpAccessChain %54 %38 %5 %5 +%166 = OpAtomicXor %4 %167 %7 %53 %7 +%168 = OpAtomicXor %6 %20 %3 %58 %5 +%170 = OpAccessChain %59 %22 %5 +%169 = OpAtomicXor %4 %170 %3 %58 %7 +%172 = OpAccessChain %21 %24 %33 +%171 = OpAtomicXor %6 %172 %3 %58 %5 +%174 = OpAccessChain %59 %24 %5 %5 +%173 = OpAtomicXor %4 %174 %3 %58 %7 +%175 = OpAtomicExchange %6 %34 %7 %53 %5 +%177 = OpAccessChain %54 %36 %5 +%176 = OpAtomicExchange %4 %177 %7 %53 %7 +%179 = OpAccessChain %32 %38 %33 +%178 = OpAtomicExchange %6 %179 %7 %53 %5 +%181 = OpAccessChain %54 %38 %5 %5 +%180 = OpAtomicExchange %4 %181 %7 %53 %7 +%182 = OpAtomicExchange %6 %20 %3 %58 %5 +%184 = OpAccessChain %59 %22 %5 +%183 = OpAtomicExchange %4 %184 %3 %58 %7 +%186 = OpAccessChain %21 %24 %33 +%185 = OpAtomicExchange %6 %186 %3 %58 %5 +%188 = OpAccessChain %59 %24 %5 %5 +%187 = OpAtomicExchange %4 %188 %3 %58 %7 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 7133f53d6..0bbd1a775 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -165,31 +165,6 @@ fn foo_frag() -> @location(0) vec4 { return vec4(0.0); } -@compute @workgroup_size(1, 1, 1) -fn atomics() { - var tmp: i32; - - let value_1 = atomicLoad((&bar.atom)); - let _e7 = atomicAdd((&bar.atom), 5); - tmp = _e7; - let _e11 = atomicSub((&bar.atom), 5); - tmp = _e11; - let _e15 = atomicAnd((&bar.atom), 5); - tmp = _e15; - let _e19 = atomicOr((&bar.atom), 5); - tmp = _e19; - let _e23 = atomicXor((&bar.atom), 5); - tmp = _e23; - let _e27 = atomicMin((&bar.atom), 5); - tmp = _e27; - let _e31 = atomicMax((&bar.atom), 5); - tmp = _e31; - let _e35 = atomicExchange((&bar.atom), 5); - tmp = _e35; - atomicStore((&bar.atom), value_1); - return; -} - @compute @workgroup_size(1, 1, 1) fn assign_through_ptr() { var arr: array,2>; diff --git a/tests/out/wgsl/atomicOps.wgsl b/tests/out/wgsl/atomicOps.wgsl new file mode 100644 index 000000000..80d177654 --- /dev/null +++ b/tests/out/wgsl/atomicOps.wgsl @@ -0,0 +1,107 @@ +struct Struct { + atomic_scalar: atomic, + atomic_arr: array,2>, +} + +@group(0) @binding(0) +var storage_atomic_scalar: atomic; +@group(0) @binding(1) +var storage_atomic_arr: array,2>; +@group(0) @binding(2) +var storage_struct: Struct; +var workgroup_atomic_scalar: atomic; +var workgroup_atomic_arr: array,2>; +var workgroup_struct: Struct; + +@compute @workgroup_size(2, 1, 1) +fn cs_main(@builtin(local_invocation_id) id: vec3) { + atomicStore((&storage_atomic_scalar), 1u); + atomicStore((&storage_atomic_arr[1]), 1); + atomicStore((&storage_struct.atomic_scalar), 1u); + atomicStore((&storage_struct.atomic_arr[1]), 1); + atomicStore((&workgroup_atomic_scalar), 1u); + atomicStore((&workgroup_atomic_arr[1]), 1); + atomicStore((&workgroup_struct.atomic_scalar), 1u); + atomicStore((&workgroup_struct.atomic_arr[1]), 1); + workgroupBarrier(); + _ = atomicLoad((&storage_atomic_scalar)); + _ = atomicLoad((&storage_atomic_arr[1])); + _ = atomicLoad((&storage_struct.atomic_scalar)); + _ = atomicLoad((&storage_struct.atomic_arr[1])); + _ = atomicLoad((&workgroup_atomic_scalar)); + _ = atomicLoad((&workgroup_atomic_arr[1])); + _ = atomicLoad((&workgroup_struct.atomic_scalar)); + _ = atomicLoad((&workgroup_struct.atomic_arr[1])); + workgroupBarrier(); + let _e59 = atomicAdd((&storage_atomic_scalar), 1u); + let _e64 = atomicAdd((&storage_atomic_arr[1]), 1); + let _e68 = atomicAdd((&storage_struct.atomic_scalar), 1u); + let _e74 = atomicAdd((&storage_struct.atomic_arr[1]), 1); + let _e77 = atomicAdd((&workgroup_atomic_scalar), 1u); + let _e82 = atomicAdd((&workgroup_atomic_arr[1]), 1); + let _e86 = atomicAdd((&workgroup_struct.atomic_scalar), 1u); + let _e92 = atomicAdd((&workgroup_struct.atomic_arr[1]), 1); + workgroupBarrier(); + let _e95 = atomicSub((&storage_atomic_scalar), 1u); + let _e100 = atomicSub((&storage_atomic_arr[1]), 1); + let _e104 = atomicSub((&storage_struct.atomic_scalar), 1u); + let _e110 = atomicSub((&storage_struct.atomic_arr[1]), 1); + let _e113 = atomicSub((&workgroup_atomic_scalar), 1u); + let _e118 = atomicSub((&workgroup_atomic_arr[1]), 1); + let _e122 = atomicSub((&workgroup_struct.atomic_scalar), 1u); + let _e128 = atomicSub((&workgroup_struct.atomic_arr[1]), 1); + workgroupBarrier(); + let _e131 = atomicMax((&storage_atomic_scalar), 1u); + let _e136 = atomicMax((&storage_atomic_arr[1]), 1); + let _e140 = atomicMax((&storage_struct.atomic_scalar), 1u); + let _e146 = atomicMax((&storage_struct.atomic_arr[1]), 1); + let _e149 = atomicMax((&workgroup_atomic_scalar), 1u); + let _e154 = atomicMax((&workgroup_atomic_arr[1]), 1); + let _e158 = atomicMax((&workgroup_struct.atomic_scalar), 1u); + let _e164 = atomicMax((&workgroup_struct.atomic_arr[1]), 1); + workgroupBarrier(); + let _e167 = atomicMin((&storage_atomic_scalar), 1u); + let _e172 = atomicMin((&storage_atomic_arr[1]), 1); + let _e176 = atomicMin((&storage_struct.atomic_scalar), 1u); + let _e182 = atomicMin((&storage_struct.atomic_arr[1]), 1); + let _e185 = atomicMin((&workgroup_atomic_scalar), 1u); + let _e190 = atomicMin((&workgroup_atomic_arr[1]), 1); + let _e194 = atomicMin((&workgroup_struct.atomic_scalar), 1u); + let _e200 = atomicMin((&workgroup_struct.atomic_arr[1]), 1); + workgroupBarrier(); + let _e203 = atomicAnd((&storage_atomic_scalar), 1u); + let _e208 = atomicAnd((&storage_atomic_arr[1]), 1); + let _e212 = atomicAnd((&storage_struct.atomic_scalar), 1u); + let _e218 = atomicAnd((&storage_struct.atomic_arr[1]), 1); + let _e221 = atomicAnd((&workgroup_atomic_scalar), 1u); + let _e226 = atomicAnd((&workgroup_atomic_arr[1]), 1); + let _e230 = atomicAnd((&workgroup_struct.atomic_scalar), 1u); + let _e236 = atomicAnd((&workgroup_struct.atomic_arr[1]), 1); + workgroupBarrier(); + let _e239 = atomicOr((&storage_atomic_scalar), 1u); + let _e244 = atomicOr((&storage_atomic_arr[1]), 1); + let _e248 = atomicOr((&storage_struct.atomic_scalar), 1u); + let _e254 = atomicOr((&storage_struct.atomic_arr[1]), 1); + let _e257 = atomicOr((&workgroup_atomic_scalar), 1u); + let _e262 = atomicOr((&workgroup_atomic_arr[1]), 1); + let _e266 = atomicOr((&workgroup_struct.atomic_scalar), 1u); + let _e272 = atomicOr((&workgroup_struct.atomic_arr[1]), 1); + workgroupBarrier(); + let _e275 = atomicXor((&storage_atomic_scalar), 1u); + let _e280 = atomicXor((&storage_atomic_arr[1]), 1); + let _e284 = atomicXor((&storage_struct.atomic_scalar), 1u); + let _e290 = atomicXor((&storage_struct.atomic_arr[1]), 1); + let _e293 = atomicXor((&workgroup_atomic_scalar), 1u); + let _e298 = atomicXor((&workgroup_atomic_arr[1]), 1); + let _e302 = atomicXor((&workgroup_struct.atomic_scalar), 1u); + let _e308 = atomicXor((&workgroup_struct.atomic_arr[1]), 1); + let _e311 = atomicExchange((&storage_atomic_scalar), 1u); + let _e316 = atomicExchange((&storage_atomic_arr[1]), 1); + let _e320 = atomicExchange((&storage_struct.atomic_scalar), 1u); + let _e326 = atomicExchange((&storage_struct.atomic_arr[1]), 1); + let _e329 = atomicExchange((&workgroup_atomic_scalar), 1u); + let _e334 = atomicExchange((&workgroup_atomic_arr[1]), 1); + let _e338 = atomicExchange((&workgroup_struct.atomic_scalar), 1u); + let _e344 = atomicExchange((&workgroup_struct.atomic_arr[1]), 1); + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index d968a0dfc..877b2597b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -505,6 +505,10 @@ fn convert_wgsl() { | Targets::IR | Targets::ANALYSIS, ), + ( + "atomicOps", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + ), ("atomicCompareExchange", Targets::SPIRV | Targets::WGSL), ( "padding", From f59668ccfaf7bdb3a7e43d84363a21c77357b2fe Mon Sep 17 00:00:00 2001 From: daxpedda Date: Fri, 7 Apr 2023 16:01:55 +0200 Subject: [PATCH 1981/2212] Allow `array_index` to be unsigned (#2298) --- src/back/spv/image.rs | 52 +- src/valid/expression.rs | 4 +- src/valid/function.rs | 2 +- tests/in/bounds-check-image-restrict.wgsl | 27 +- tests/in/bounds-check-image-rzsw.wgsl | 27 +- tests/in/image.wgsl | 59 +- ...age-restrict.fragment_shader.Fragment.glsl | 49 +- ...k-image-rzsw.fragment_shader.Fragment.glsl | 46 +- tests/out/glsl/image.main.Compute.glsl | 10 +- .../glsl/image.texture_sample.Fragment.glsl | 81 +- ...ge.texture_sample_comparison.Fragment.glsl | 36 +- tests/out/hlsl/image.hlsl | 136 +- tests/out/msl/bounds-check-image-restrict.msl | 108 +- tests/out/msl/bounds-check-image-rzsw.msl | 110 +- tests/out/msl/image.msl | 134 +- .../spv/bounds-check-image-restrict.spvasm | 723 ++++++----- tests/out/spv/bounds-check-image-rzsw.spvasm | 873 +++++++------ tests/out/spv/image.spvasm | 1151 ++++++++++------- tests/out/spv/shadow.spvasm | 2 +- tests/out/wgsl/image.wgsl | 135 +- 20 files changed, 2336 insertions(+), 1429 deletions(-) diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index dc4f24994..27f352050 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -314,41 +314,47 @@ impl<'w> BlockContext<'w> { }; // Convert the index to the coordinate component type, if necessary. - let array_index_i32_id = self.cached[array_index]; - let reconciled_array_index_id = if component_kind == crate::ScalarKind::Sint { - array_index_i32_id - } else if component_kind == crate::ScalarKind::Uint { - let u32_id = self.get_type_id(LookupType::Local(LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Uint, - width: 4, - pointer_space: None, - })); - - let reconciled_id = self.gen_id(); - block.body.push(Instruction::unary( - spirv::Op::Bitcast, - u32_id, - reconciled_id, - array_index_i32_id, + let array_index_id = self.cached[array_index]; + let ty = &self.fun_info[array_index].ty; + let inner_ty = ty.inner_with(&self.ir_module.types); + let array_index_kind = if let Ti::Scalar { kind, width: 4 } = *inner_ty { + debug_assert!(matches!( + kind, + crate::ScalarKind::Sint | crate::ScalarKind::Uint )); - reconciled_id + kind } else { - let component_type_id = self.get_type_id(LookupType::Local(LocalType::Value { + unreachable!("we only allow i32 and u32"); + }; + let cast = match (component_kind, array_index_kind) { + (crate::ScalarKind::Sint, crate::ScalarKind::Sint) + | (crate::ScalarKind::Uint, crate::ScalarKind::Uint) => None, + (crate::ScalarKind::Sint, crate::ScalarKind::Uint) + | (crate::ScalarKind::Uint, crate::ScalarKind::Sint) => Some(spirv::Op::Bitcast), + (crate::ScalarKind::Float, crate::ScalarKind::Sint) => Some(spirv::Op::ConvertSToF), + (crate::ScalarKind::Float, crate::ScalarKind::Uint) => Some(spirv::Op::ConvertUToF), + (crate::ScalarKind::Bool, _) => unreachable!("we don't allow bool for component"), + (_, crate::ScalarKind::Bool | crate::ScalarKind::Float) => { + unreachable!("we don't allow bool or float for array index") + } + }; + let reconciled_array_index_id = if let Some(cast) = cast { + let component_ty_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size: None, kind: component_kind, width: 4, pointer_space: None, })); - let reconciled_id = self.gen_id(); block.body.push(Instruction::unary( - spirv::Op::ConvertUToF, - component_type_id, + cast, + component_ty_id, reconciled_id, - array_index_i32_id, + array_index_id, )); reconciled_id + } else { + array_index_id }; // Find the SPIR-V type for the combined coordinates/index vector. diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 1a91fe4d0..3a8170790 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -359,7 +359,7 @@ impl super::Validator { if let Some(expr) = array_index { match resolver[expr] { Ti::Scalar { - kind: Sk::Sint, + kind: Sk::Sint | Sk::Uint, width: _, } => {} _ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)), @@ -548,7 +548,7 @@ impl super::Validator { if let Some(expr) = array_index { match resolver[expr] { Ti::Scalar { - kind: Sk::Sint, + kind: Sk::Sint | Sk::Uint, width: _, } => {} _ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)), diff --git a/src/valid/function.rs b/src/valid/function.rs index 737f33dc2..8ebcddd9e 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -758,7 +758,7 @@ impl super::Validator { if let Some(expr) = array_index { match *context.resolve_type(expr, &self.valid_expression_set)? { Ti::Scalar { - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint, width: _, } => {} _ => { diff --git a/tests/in/bounds-check-image-restrict.wgsl b/tests/in/bounds-check-image-restrict.wgsl index 0cce20eaf..4bd8d117c 100644 --- a/tests/in/bounds-check-image-restrict.wgsl +++ b/tests/in/bounds-check-image-restrict.wgsl @@ -15,7 +15,11 @@ fn test_textureLoad_2d(coords: vec2, level: i32) -> vec4 { @group(0) @binding(2) var image_2d_array: texture_2d_array; -fn test_textureLoad_2d_array(coords: vec2, index: i32, level: i32) -> vec4 { +fn test_textureLoad_2d_array_u(coords: vec2, index: u32, level: i32) -> vec4 { + return textureLoad(image_2d_array, coords, index, level); +} + +fn test_textureLoad_2d_array_s(coords: vec2, index: i32, level: i32) -> vec4 { return textureLoad(image_2d_array, coords, index, level); } @@ -43,7 +47,11 @@ fn test_textureLoad_depth_2d(coords: vec2, level: i32) -> f32 { @group(0) @binding(6) var image_depth_2d_array: texture_depth_2d_array; -fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> f32 { +fn test_textureLoad_depth_2d_array_u(coords: vec2, index: u32, level: i32) -> f32 { + return textureLoad(image_depth_2d_array, coords, index, level); +} + +fn test_textureLoad_depth_2d_array_s(coords: vec2, index: i32, level: i32) -> f32 { return textureLoad(image_depth_2d_array, coords, index, level); } @@ -71,7 +79,11 @@ fn test_textureStore_2d(coords: vec2, value: vec4) { @group(0) @binding(10) var image_storage_2d_array: texture_storage_2d_array; -fn test_textureStore_2d_array(coords: vec2, array_index: i32, value: vec4) { +fn test_textureStore_2d_array_u(coords: vec2, array_index: u32, value: vec4) { + textureStore(image_storage_2d_array, coords, array_index, value); +} + +fn test_textureStore_2d_array_s(coords: vec2, array_index: i32, value: vec4) { textureStore(image_storage_2d_array, coords, array_index, value); } @@ -88,16 +100,19 @@ fn test_textureStore_3d(coords: vec3, value: vec4) { fn fragment_shader() -> @location(0) vec4 { test_textureLoad_1d(0, 0); test_textureLoad_2d(vec2(), 0); - test_textureLoad_2d_array(vec2(), 0, 0); + test_textureLoad_2d_array_u(vec2(), 0u, 0); + test_textureLoad_2d_array_s(vec2(), 0, 0); test_textureLoad_3d(vec3(), 0); test_textureLoad_multisampled_2d(vec2(), 0); // Not yet implemented for GLSL: // test_textureLoad_depth_2d(vec2(), 0); - // test_textureLoad_depth_2d_array(vec2(), 0, 0); + // test_textureLoad_depth_2d_array_u(vec2(), 0u, 0); + // test_textureLoad_depth_2d_array_s(vec2(), 0, 0); // test_textureLoad_depth_multisampled_2d(vec2(), 0); test_textureStore_1d(0, vec4()); test_textureStore_2d(vec2(), vec4()); - test_textureStore_2d_array(vec2(), 0, vec4()); + test_textureStore_2d_array_u(vec2(), 0u, vec4()); + test_textureStore_2d_array_s(vec2(), 0, vec4()); test_textureStore_3d(vec3(), vec4()); return vec4(0.,0.,0.,0.); diff --git a/tests/in/bounds-check-image-rzsw.wgsl b/tests/in/bounds-check-image-rzsw.wgsl index 0cce20eaf..4bd8d117c 100644 --- a/tests/in/bounds-check-image-rzsw.wgsl +++ b/tests/in/bounds-check-image-rzsw.wgsl @@ -15,7 +15,11 @@ fn test_textureLoad_2d(coords: vec2, level: i32) -> vec4 { @group(0) @binding(2) var image_2d_array: texture_2d_array; -fn test_textureLoad_2d_array(coords: vec2, index: i32, level: i32) -> vec4 { +fn test_textureLoad_2d_array_u(coords: vec2, index: u32, level: i32) -> vec4 { + return textureLoad(image_2d_array, coords, index, level); +} + +fn test_textureLoad_2d_array_s(coords: vec2, index: i32, level: i32) -> vec4 { return textureLoad(image_2d_array, coords, index, level); } @@ -43,7 +47,11 @@ fn test_textureLoad_depth_2d(coords: vec2, level: i32) -> f32 { @group(0) @binding(6) var image_depth_2d_array: texture_depth_2d_array; -fn test_textureLoad_depth_2d_array(coords: vec2, index: i32, level: i32) -> f32 { +fn test_textureLoad_depth_2d_array_u(coords: vec2, index: u32, level: i32) -> f32 { + return textureLoad(image_depth_2d_array, coords, index, level); +} + +fn test_textureLoad_depth_2d_array_s(coords: vec2, index: i32, level: i32) -> f32 { return textureLoad(image_depth_2d_array, coords, index, level); } @@ -71,7 +79,11 @@ fn test_textureStore_2d(coords: vec2, value: vec4) { @group(0) @binding(10) var image_storage_2d_array: texture_storage_2d_array; -fn test_textureStore_2d_array(coords: vec2, array_index: i32, value: vec4) { +fn test_textureStore_2d_array_u(coords: vec2, array_index: u32, value: vec4) { + textureStore(image_storage_2d_array, coords, array_index, value); +} + +fn test_textureStore_2d_array_s(coords: vec2, array_index: i32, value: vec4) { textureStore(image_storage_2d_array, coords, array_index, value); } @@ -88,16 +100,19 @@ fn test_textureStore_3d(coords: vec3, value: vec4) { fn fragment_shader() -> @location(0) vec4 { test_textureLoad_1d(0, 0); test_textureLoad_2d(vec2(), 0); - test_textureLoad_2d_array(vec2(), 0, 0); + test_textureLoad_2d_array_u(vec2(), 0u, 0); + test_textureLoad_2d_array_s(vec2(), 0, 0); test_textureLoad_3d(vec3(), 0); test_textureLoad_multisampled_2d(vec2(), 0); // Not yet implemented for GLSL: // test_textureLoad_depth_2d(vec2(), 0); - // test_textureLoad_depth_2d_array(vec2(), 0, 0); + // test_textureLoad_depth_2d_array_u(vec2(), 0u, 0); + // test_textureLoad_depth_2d_array_s(vec2(), 0, 0); // test_textureLoad_depth_multisampled_2d(vec2(), 0); test_textureStore_1d(0, vec4()); test_textureStore_2d(vec2(), vec4()); - test_textureStore_2d_array(vec2(), 0, vec4()); + test_textureStore_2d_array_u(vec2(), 0u, vec4()); + test_textureStore_2d_array_s(vec2(), 0, vec4()); test_textureStore_3d(vec3(), vec4()); return vec4(0.,0.,0.,0.); diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl index b61b10164..2bae8f9d8 100644 --- a/tests/in/image.wgsl +++ b/tests/in/image.wgsl @@ -23,14 +23,16 @@ fn main(@builtin(local_invocation_id) local_id: vec3) { let value1 = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); let value2 = textureLoad(image_multisampled_src, itc, i32(local_id.z)); let value4 = textureLoad(image_storage_src, itc); - let value5 = textureLoad(image_array_src, itc, i32(local_id.z), i32(local_id.z) + 1); - let value6 = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z)); + let value5 = textureLoad(image_array_src, itc, local_id.z, i32(local_id.z) + 1); + let value6 = textureLoad(image_array_src, itc, i32(local_id.z), i32(local_id.z) + 1); + let value7 = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z)); // loads with uvec2 coords. let value1u = textureLoad(image_mipmapped_src, vec2(itc), i32(local_id.z)); let value2u = textureLoad(image_multisampled_src, vec2(itc), i32(local_id.z)); let value4u = textureLoad(image_storage_src, vec2(itc)); - let value5u = textureLoad(image_array_src, vec2(itc), i32(local_id.z), i32(local_id.z) + 1); - let value6u = textureLoad(image_1d_src, u32(local_id.x), i32(local_id.z)); + let value5u = textureLoad(image_array_src, vec2(itc), local_id.z, i32(local_id.z) + 1); + let value6u = textureLoad(image_array_src, vec2(itc), i32(local_id.z), i32(local_id.z) + 1); + let value7u = textureLoad(image_1d_src, u32(local_id.x), i32(local_id.z)); // store with ivec2 coords. textureStore(image_dst, itc.x, value1 + value2 + value4 + value5 + value6); // store with uvec2 coords. @@ -109,14 +111,32 @@ var sampler_reg: sampler; @fragment fn texture_sample() -> @location(0) vec4 { let tc = vec2(0.5); + let tc3 = vec3(0.5); let level = 2.3; - let s1d = textureSample(image_1d, sampler_reg, tc.x); - let s2d = textureSample(image_2d, sampler_reg, tc); - let s2d_offset = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); - let s2d_level = textureSampleLevel(image_2d, sampler_reg, tc, level); - let s2d_level_offset = textureSampleLevel(image_2d, sampler_reg, tc, level, vec2(3, 1)); - let s2d_bias_offset = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); - return s1d + s2d + s2d_offset + s2d_level + s2d_level_offset; + var a: vec4; + a += textureSample(image_1d, sampler_reg, tc.x); + a += textureSample(image_2d, sampler_reg, tc); + a += textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); + a += textureSampleLevel(image_2d, sampler_reg, tc, level); + a += textureSampleLevel(image_2d, sampler_reg, tc, level, vec2(3, 1)); + a += textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); + a += textureSample(image_2d_array, sampler_reg, tc, 0u); + a += textureSample(image_2d_array, sampler_reg, tc, 0u, vec2(3, 1)); + a += textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, level); + a += textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, level, vec2(3, 1)); + a += textureSampleBias(image_2d_array, sampler_reg, tc, 0u, 2.0, vec2(3, 1)); + a += textureSample(image_2d_array, sampler_reg, tc, 0); + a += textureSample(image_2d_array, sampler_reg, tc, 0, vec2(3, 1)); + a += textureSampleLevel(image_2d_array, sampler_reg, tc, 0, level); + a += textureSampleLevel(image_2d_array, sampler_reg, tc, 0, level, vec2(3, 1)); + a += textureSampleBias(image_2d_array, sampler_reg, tc, 0, 2.0, vec2(3, 1)); + a += textureSample(image_cube_array, sampler_reg, tc3, 0u); + a += textureSampleLevel(image_cube_array, sampler_reg, tc3, 0u, level); + a += textureSampleBias(image_cube_array, sampler_reg, tc3, 0u, 2.0); + a += textureSample(image_cube_array, sampler_reg, tc3, 0); + a += textureSampleLevel(image_cube_array, sampler_reg, tc3, 0, level); + a += textureSampleBias(image_cube_array, sampler_reg, tc3, 0, 2.0); + return a; } @group(1) @binding(1) @@ -124,16 +144,25 @@ var sampler_cmp: sampler_comparison; @group(1) @binding(2) var image_2d_depth: texture_depth_2d; @group(1) @binding(3) +var image_2d_array_depth: texture_depth_2d_array; +@group(1) @binding(4) var image_cube_depth: texture_depth_cube; @fragment fn texture_sample_comparison() -> @location(0) f32 { let tc = vec2(0.5); + let tc3 = vec3(0.5); let dref = 0.5; - let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc, dref); - let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc, dref); - let scube_depth_level = textureSampleCompareLevel(image_cube_depth, sampler_cmp, vec3(0.5), dref); - return s2d_depth + s2d_depth_level; + var a: f32; + a += textureSampleCompare(image_2d_depth, sampler_cmp, tc, dref); + a += textureSampleCompare(image_2d_array_depth, sampler_cmp, tc, 0u, dref); + a += textureSampleCompare(image_2d_array_depth, sampler_cmp, tc, 0, dref); + a += textureSampleCompare(image_cube_depth, sampler_cmp, tc3, dref); + a += textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc, dref); + a += textureSampleCompareLevel(image_2d_array_depth, sampler_cmp, tc, 0u, dref); + a += textureSampleCompareLevel(image_2d_array_depth, sampler_cmp, tc, 0, dref); + a += textureSampleCompareLevel(image_cube_depth, sampler_cmp, tc3, dref); + return a; } @fragment diff --git a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl index 8196d197d..ba7854322 100644 --- a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl +++ b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl @@ -32,53 +32,66 @@ vec4 test_textureLoad_2d(ivec2 coords_1, int level_1) { return _e3; } -vec4 test_textureLoad_2d_array(ivec2 coords_2, int index, int level_2) { +vec4 test_textureLoad_2d_array_u(ivec2 coords_2, uint index, int level_2) { int _e4_clamped_lod = clamp(level_2, 0, textureQueryLevels(_group_0_binding_2_fs) - 1); vec4 _e4 = texelFetch(_group_0_binding_2_fs, clamp(ivec3(coords_2, index), ivec3(0), textureSize(_group_0_binding_2_fs, _e4_clamped_lod) - ivec3(1)), _e4_clamped_lod); return _e4; } -vec4 test_textureLoad_3d(ivec3 coords_3, int level_3) { - int _e3_clamped_lod = clamp(level_3, 0, textureQueryLevels(_group_0_binding_3_fs) - 1); - vec4 _e3 = texelFetch(_group_0_binding_3_fs, clamp(coords_3, ivec3(0), textureSize(_group_0_binding_3_fs, _e3_clamped_lod) - ivec3(1)), _e3_clamped_lod); +vec4 test_textureLoad_2d_array_s(ivec2 coords_3, int index_1, int level_3) { + int _e4_clamped_lod = clamp(level_3, 0, textureQueryLevels(_group_0_binding_2_fs) - 1); + vec4 _e4 = texelFetch(_group_0_binding_2_fs, clamp(ivec3(coords_3, index_1), ivec3(0), textureSize(_group_0_binding_2_fs, _e4_clamped_lod) - ivec3(1)), _e4_clamped_lod); + return _e4; +} + +vec4 test_textureLoad_3d(ivec3 coords_4, int level_4) { + int _e3_clamped_lod = clamp(level_4, 0, textureQueryLevels(_group_0_binding_3_fs) - 1); + vec4 _e3 = texelFetch(_group_0_binding_3_fs, clamp(coords_4, ivec3(0), textureSize(_group_0_binding_3_fs, _e3_clamped_lod) - ivec3(1)), _e3_clamped_lod); return _e3; } -vec4 test_textureLoad_multisampled_2d(ivec2 coords_4, int _sample) { - vec4 _e3 = texelFetch(_group_0_binding_4_fs, clamp(coords_4, ivec2(0), textureSize(_group_0_binding_4_fs) - ivec2(1)), clamp(_sample, 0, textureSamples(_group_0_binding_4_fs) - 1) +vec4 test_textureLoad_multisampled_2d(ivec2 coords_5, int _sample) { + vec4 _e3 = texelFetch(_group_0_binding_4_fs, clamp(coords_5, ivec2(0), textureSize(_group_0_binding_4_fs) - ivec2(1)), clamp(_sample, 0, textureSamples(_group_0_binding_4_fs) - 1) ); return _e3; } -void test_textureStore_1d(int coords_8, vec4 value) { - imageStore(_group_0_binding_8_fs, coords_8, value); +void test_textureStore_1d(int coords_10, vec4 value) { + imageStore(_group_0_binding_8_fs, coords_10, value); return; } -void test_textureStore_2d(ivec2 coords_9, vec4 value_1) { - imageStore(_group_0_binding_9_fs, coords_9, value_1); +void test_textureStore_2d(ivec2 coords_11, vec4 value_1) { + imageStore(_group_0_binding_9_fs, coords_11, value_1); return; } -void test_textureStore_2d_array(ivec2 coords_10, int array_index, vec4 value_2) { - imageStore(_group_0_binding_10_fs, ivec3(coords_10, array_index), value_2); +void test_textureStore_2d_array_u(ivec2 coords_12, uint array_index, vec4 value_2) { + imageStore(_group_0_binding_10_fs, ivec3(coords_12, array_index), value_2); return; } -void test_textureStore_3d(ivec3 coords_11, vec4 value_3) { - imageStore(_group_0_binding_11_fs, coords_11, value_3); +void test_textureStore_2d_array_s(ivec2 coords_13, int array_index_1, vec4 value_3) { + imageStore(_group_0_binding_10_fs, ivec3(coords_13, array_index_1), value_3); + return; +} + +void test_textureStore_3d(ivec3 coords_14, vec4 value_4) { + imageStore(_group_0_binding_11_fs, coords_14, value_4); return; } void main() { vec4 _e2 = test_textureLoad_1d(0, 0); vec4 _e5 = test_textureLoad_2d(ivec2(0, 0), 0); - vec4 _e9 = test_textureLoad_2d_array(ivec2(0, 0), 0, 0); - vec4 _e12 = test_textureLoad_3d(ivec3(0, 0, 0), 0); - vec4 _e15 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); + vec4 _e9 = test_textureLoad_2d_array_u(ivec2(0, 0), 0u, 0); + vec4 _e13 = test_textureLoad_2d_array_s(ivec2(0, 0), 0, 0); + vec4 _e16 = test_textureLoad_3d(ivec3(0, 0, 0), 0); + vec4 _e19 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); test_textureStore_1d(0, vec4(0.0, 0.0, 0.0, 0.0)); test_textureStore_2d(ivec2(0, 0), vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_2d_array(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_2d_array_u(ivec2(0, 0), 0u, vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_2d_array_s(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); test_textureStore_3d(ivec3(0, 0, 0), vec4(0.0, 0.0, 0.0, 0.0)); _fs2p_location0 = vec4(0.0, 0.0, 0.0, 0.0); return; diff --git a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl index 50d1590d2..7d8aba65c 100644 --- a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl +++ b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl @@ -30,50 +30,62 @@ vec4 test_textureLoad_2d(ivec2 coords_1, int level_1) { return _e3; } -vec4 test_textureLoad_2d_array(ivec2 coords_2, int index, int level_2) { +vec4 test_textureLoad_2d_array_u(ivec2 coords_2, uint index, int level_2) { vec4 _e4 = (level_2 < textureQueryLevels(_group_0_binding_2_fs) && all(lessThan(ivec3(coords_2, index), textureSize(_group_0_binding_2_fs, level_2))) ? texelFetch(_group_0_binding_2_fs, ivec3(coords_2, index), level_2) : vec4(0.0)); return _e4; } -vec4 test_textureLoad_3d(ivec3 coords_3, int level_3) { - vec4 _e3 = (level_3 < textureQueryLevels(_group_0_binding_3_fs) && all(lessThan(coords_3, textureSize(_group_0_binding_3_fs, level_3))) ? texelFetch(_group_0_binding_3_fs, coords_3, level_3) : vec4(0.0)); +vec4 test_textureLoad_2d_array_s(ivec2 coords_3, int index_1, int level_3) { + vec4 _e4 = (level_3 < textureQueryLevels(_group_0_binding_2_fs) && all(lessThan(ivec3(coords_3, index_1), textureSize(_group_0_binding_2_fs, level_3))) ? texelFetch(_group_0_binding_2_fs, ivec3(coords_3, index_1), level_3) : vec4(0.0)); + return _e4; +} + +vec4 test_textureLoad_3d(ivec3 coords_4, int level_4) { + vec4 _e3 = (level_4 < textureQueryLevels(_group_0_binding_3_fs) && all(lessThan(coords_4, textureSize(_group_0_binding_3_fs, level_4))) ? texelFetch(_group_0_binding_3_fs, coords_4, level_4) : vec4(0.0)); return _e3; } -vec4 test_textureLoad_multisampled_2d(ivec2 coords_4, int _sample) { - vec4 _e3 = (_sample < textureSamples(_group_0_binding_4_fs) && all(lessThan(coords_4, textureSize(_group_0_binding_4_fs))) ? texelFetch(_group_0_binding_4_fs, coords_4, _sample) : vec4(0.0)); +vec4 test_textureLoad_multisampled_2d(ivec2 coords_5, int _sample) { + vec4 _e3 = (_sample < textureSamples(_group_0_binding_4_fs) && all(lessThan(coords_5, textureSize(_group_0_binding_4_fs))) ? texelFetch(_group_0_binding_4_fs, coords_5, _sample) : vec4(0.0)); return _e3; } -void test_textureStore_1d(int coords_8, vec4 value) { - imageStore(_group_0_binding_8_fs, coords_8, value); +void test_textureStore_1d(int coords_10, vec4 value) { + imageStore(_group_0_binding_8_fs, coords_10, value); return; } -void test_textureStore_2d(ivec2 coords_9, vec4 value_1) { - imageStore(_group_0_binding_9_fs, coords_9, value_1); +void test_textureStore_2d(ivec2 coords_11, vec4 value_1) { + imageStore(_group_0_binding_9_fs, coords_11, value_1); return; } -void test_textureStore_2d_array(ivec2 coords_10, int array_index, vec4 value_2) { - imageStore(_group_0_binding_10_fs, ivec3(coords_10, array_index), value_2); +void test_textureStore_2d_array_u(ivec2 coords_12, uint array_index, vec4 value_2) { + imageStore(_group_0_binding_10_fs, ivec3(coords_12, array_index), value_2); return; } -void test_textureStore_3d(ivec3 coords_11, vec4 value_3) { - imageStore(_group_0_binding_11_fs, coords_11, value_3); +void test_textureStore_2d_array_s(ivec2 coords_13, int array_index_1, vec4 value_3) { + imageStore(_group_0_binding_10_fs, ivec3(coords_13, array_index_1), value_3); + return; +} + +void test_textureStore_3d(ivec3 coords_14, vec4 value_4) { + imageStore(_group_0_binding_11_fs, coords_14, value_4); return; } void main() { vec4 _e2 = test_textureLoad_1d(0, 0); vec4 _e5 = test_textureLoad_2d(ivec2(0, 0), 0); - vec4 _e9 = test_textureLoad_2d_array(ivec2(0, 0), 0, 0); - vec4 _e12 = test_textureLoad_3d(ivec3(0, 0, 0), 0); - vec4 _e15 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); + vec4 _e9 = test_textureLoad_2d_array_u(ivec2(0, 0), 0u, 0); + vec4 _e13 = test_textureLoad_2d_array_s(ivec2(0, 0), 0, 0); + vec4 _e16 = test_textureLoad_3d(ivec3(0, 0, 0), 0); + vec4 _e19 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); test_textureStore_1d(0, vec4(0.0, 0.0, 0.0, 0.0)); test_textureStore_2d(ivec2(0, 0), vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_2d_array(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_2d_array_u(ivec2(0, 0), 0u, vec4(0.0, 0.0, 0.0, 0.0)); + test_textureStore_2d_array_s(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); test_textureStore_3d(ivec3(0, 0, 0), vec4(0.0, 0.0, 0.0, 0.0)); _fs2p_location0 = vec4(0.0, 0.0, 0.0, 0.0); return; diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl index b03b7ee9c..78324dd4c 100644 --- a/tests/out/glsl/image.main.Compute.glsl +++ b/tests/out/glsl/image.main.Compute.glsl @@ -26,13 +26,15 @@ void main() { uvec4 value1_ = texelFetch(_group_0_binding_0_cs, itc, int(local_id.z)); uvec4 value2_ = texelFetch(_group_0_binding_3_cs, itc, int(local_id.z)); uvec4 value4_ = imageLoad(_group_0_binding_1_cs, itc); - uvec4 value5_ = texelFetch(_group_0_binding_5_cs, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); - uvec4 value6_ = texelFetch(_group_0_binding_7_cs, ivec2(int(local_id.x), 0), int(local_id.z)); + uvec4 value5_ = texelFetch(_group_0_binding_5_cs, ivec3(itc, local_id.z), (int(local_id.z) + 1)); + uvec4 value6_ = texelFetch(_group_0_binding_5_cs, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1)); + uvec4 value7_ = texelFetch(_group_0_binding_7_cs, ivec2(int(local_id.x), 0), int(local_id.z)); uvec4 value1u = texelFetch(_group_0_binding_0_cs, ivec2(uvec2(itc)), int(local_id.z)); uvec4 value2u = texelFetch(_group_0_binding_3_cs, ivec2(uvec2(itc)), int(local_id.z)); uvec4 value4u = imageLoad(_group_0_binding_1_cs, ivec2(uvec2(itc))); - uvec4 value5u = texelFetch(_group_0_binding_5_cs, ivec3(uvec2(itc), int(local_id.z)), (int(local_id.z) + 1)); - uvec4 value6u = texelFetch(_group_0_binding_7_cs, ivec2(uint(local_id.x), 0), int(local_id.z)); + uvec4 value5u = texelFetch(_group_0_binding_5_cs, ivec3(uvec2(itc), local_id.z), (int(local_id.z) + 1)); + uvec4 value6u = texelFetch(_group_0_binding_5_cs, ivec3(uvec2(itc), int(local_id.z)), (int(local_id.z) + 1)); + uvec4 value7u = texelFetch(_group_0_binding_7_cs, ivec2(uint(local_id.x), 0), int(local_id.z)); imageStore(_group_0_binding_2_cs, ivec2(itc.x, 0), ((((value1_ + value2_) + value4_) + value5_) + value6_)); imageStore(_group_0_binding_2_cs, ivec2(uint(itc.x), 0), ((((value1u + value2u) + value4u) + value5u) + value6u)); return; diff --git a/tests/out/glsl/image.texture_sample.Fragment.glsl b/tests/out/glsl/image.texture_sample.Fragment.glsl index 5ebec0fc4..72aa8fa16 100644 --- a/tests/out/glsl/image.texture_sample.Fragment.glsl +++ b/tests/out/glsl/image.texture_sample.Fragment.glsl @@ -8,17 +8,84 @@ uniform highp sampler2D _group_0_binding_0_fs; uniform highp sampler2D _group_0_binding_1_fs; +uniform highp sampler2DArray _group_0_binding_4_fs; + +uniform highp samplerCubeArray _group_0_binding_6_fs; + layout(location = 0) out vec4 _fs2p_location0; void main() { + vec4 a = vec4(0.0); vec2 tc = vec2(0.5); - vec4 s1d = texture(_group_0_binding_0_fs, vec2(tc.x, 0.0)); - vec4 s2d = texture(_group_0_binding_1_fs, vec2(tc)); - vec4 s2d_offset = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1)); - vec4 s2d_level = textureLod(_group_0_binding_1_fs, vec2(tc), 2.299999952316284); - vec4 s2d_level_offset = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.299999952316284, ivec2(3, 1)); - vec4 s2d_bias_offset = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 2.0); - _fs2p_location0 = ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); + vec3 tc3_ = vec3(0.5); + vec4 _e9 = texture(_group_0_binding_0_fs, vec2(tc.x, 0.0)); + vec4 _e10 = a; + a = (_e10 + _e9); + vec4 _e14 = texture(_group_0_binding_1_fs, vec2(tc)); + vec4 _e15 = a; + a = (_e15 + _e14); + vec4 _e19 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1)); + vec4 _e20 = a; + a = (_e20 + _e19); + vec4 _e24 = textureLod(_group_0_binding_1_fs, vec2(tc), 2.299999952316284); + vec4 _e25 = a; + a = (_e25 + _e24); + vec4 _e29 = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.299999952316284, ivec2(3, 1)); + vec4 _e30 = a; + a = (_e30 + _e29); + vec4 _e35 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 2.0); + vec4 _e36 = a; + a = (_e36 + _e35); + vec4 _e41 = texture(_group_0_binding_4_fs, vec3(tc, 0u)); + vec4 _e42 = a; + a = (_e42 + _e41); + vec4 _e47 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1)); + vec4 _e48 = a; + a = (_e48 + _e47); + vec4 _e53 = textureLod(_group_0_binding_4_fs, vec3(tc, 0u), 2.299999952316284); + vec4 _e54 = a; + a = (_e54 + _e53); + vec4 _e59 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0u), 2.299999952316284, ivec2(3, 1)); + vec4 _e60 = a; + a = (_e60 + _e59); + vec4 _e66 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1), 2.0); + vec4 _e67 = a; + a = (_e67 + _e66); + vec4 _e72 = texture(_group_0_binding_4_fs, vec3(tc, 0)); + vec4 _e73 = a; + a = (_e73 + _e72); + vec4 _e78 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1)); + vec4 _e79 = a; + a = (_e79 + _e78); + vec4 _e84 = textureLod(_group_0_binding_4_fs, vec3(tc, 0), 2.299999952316284); + vec4 _e85 = a; + a = (_e85 + _e84); + vec4 _e90 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0), 2.299999952316284, ivec2(3, 1)); + vec4 _e91 = a; + a = (_e91 + _e90); + vec4 _e97 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1), 2.0); + vec4 _e98 = a; + a = (_e98 + _e97); + vec4 _e103 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u)); + vec4 _e104 = a; + a = (_e104 + _e103); + vec4 _e109 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.299999952316284); + vec4 _e110 = a; + a = (_e110 + _e109); + vec4 _e116 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.0); + vec4 _e117 = a; + a = (_e117 + _e116); + vec4 _e122 = texture(_group_0_binding_6_fs, vec4(tc3_, 0)); + vec4 _e123 = a; + a = (_e123 + _e122); + vec4 _e128 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0), 2.299999952316284); + vec4 _e129 = a; + a = (_e129 + _e128); + vec4 _e135 = texture(_group_0_binding_6_fs, vec4(tc3_, 0), 2.0); + vec4 _e136 = a; + a = (_e136 + _e135); + vec4 _e138 = a; + _fs2p_location0 = _e138; return; } diff --git a/tests/out/glsl/image.texture_sample_comparison.Fragment.glsl b/tests/out/glsl/image.texture_sample_comparison.Fragment.glsl index ab7fda49f..1dc303ed6 100644 --- a/tests/out/glsl/image.texture_sample_comparison.Fragment.glsl +++ b/tests/out/glsl/image.texture_sample_comparison.Fragment.glsl @@ -6,16 +6,42 @@ precision highp int; uniform highp sampler2DShadow _group_1_binding_2_fs; -uniform highp samplerCubeShadow _group_1_binding_3_fs; +uniform highp sampler2DArrayShadow _group_1_binding_3_fs; + +uniform highp samplerCubeShadow _group_1_binding_4_fs; layout(location = 0) out float _fs2p_location0; void main() { + float a_1 = 0.0; vec2 tc = vec2(0.5); - float s2d_depth = texture(_group_1_binding_2_fs, vec3(tc, 0.5)); - float s2d_depth_level = textureLod(_group_1_binding_2_fs, vec3(tc, 0.5), 0.0); - float scube_depth_level = textureGrad(_group_1_binding_3_fs, vec4(vec3(0.5), 0.5), vec3(0.0), vec3(0.0)); - _fs2p_location0 = (s2d_depth + s2d_depth_level); + vec3 tc3_ = vec3(0.5); + float _e8 = texture(_group_1_binding_2_fs, vec3(tc, 0.5)); + float _e9 = a_1; + a_1 = (_e9 + _e8); + float _e14 = texture(_group_1_binding_3_fs, vec4(tc, 0u, 0.5)); + float _e15 = a_1; + a_1 = (_e15 + _e14); + float _e20 = texture(_group_1_binding_3_fs, vec4(tc, 0, 0.5)); + float _e21 = a_1; + a_1 = (_e21 + _e20); + float _e25 = texture(_group_1_binding_4_fs, vec4(tc3_, 0.5)); + float _e26 = a_1; + a_1 = (_e26 + _e25); + float _e30 = textureLod(_group_1_binding_2_fs, vec3(tc, 0.5), 0.0); + float _e31 = a_1; + a_1 = (_e31 + _e30); + float _e36 = textureGrad(_group_1_binding_3_fs, vec4(tc, 0u, 0.5), vec2(0.0), vec2(0.0)); + float _e37 = a_1; + a_1 = (_e37 + _e36); + float _e42 = textureGrad(_group_1_binding_3_fs, vec4(tc, 0, 0.5), vec2(0.0), vec2(0.0)); + float _e43 = a_1; + a_1 = (_e43 + _e42); + float _e47 = textureGrad(_group_1_binding_4_fs, vec4(tc3_, 0.5), vec3(0.0), vec3(0.0)); + float _e48 = a_1; + a_1 = (_e48 + _e47); + float _e50 = a_1; + _fs2p_location0 = _e50; return; } diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 3d774fa73..79e490e24 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -19,7 +19,8 @@ Texture2DMS image_aa : register(t8); SamplerState sampler_reg : register(s0, space1); SamplerComparisonState sampler_cmp : register(s1, space1); Texture2D image_2d_depth : register(t2, space1); -TextureCube image_cube_depth : register(t3, space1); +Texture2DArray image_2d_array_depth : register(t3, space1); +TextureCube image_cube_depth : register(t4, space1); uint2 NagaRWDimensions2D(RWTexture2D tex) { @@ -36,13 +37,15 @@ void main(uint3 local_id : SV_GroupThreadID) uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(local_id.z))); uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z)); uint4 value4_ = image_storage_src.Load(itc); - uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); - uint4 value6_ = image_1d_src.Load(int2(int(local_id.x), int(local_id.z))); + uint4 value5_ = image_array_src.Load(int4(itc, local_id.z, (int(local_id.z) + 1))); + uint4 value6_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1))); + uint4 value7_ = image_1d_src.Load(int2(int(local_id.x), int(local_id.z))); uint4 value1u = image_mipmapped_src.Load(int3(uint2(itc), int(local_id.z))); uint4 value2u = image_multisampled_src.Load(uint2(itc), int(local_id.z)); uint4 value4u = image_storage_src.Load(uint2(itc)); - uint4 value5u = image_array_src.Load(int4(uint2(itc), int(local_id.z), (int(local_id.z) + 1))); - uint4 value6u = image_1d_src.Load(int2(uint(local_id.x), int(local_id.z))); + uint4 value5u = image_array_src.Load(int4(uint2(itc), local_id.z, (int(local_id.z) + 1))); + uint4 value6u = image_array_src.Load(int4(uint2(itc), int(local_id.z), (int(local_id.z) + 1))); + uint4 value7u = image_1d_src.Load(int2(uint(local_id.x), int(local_id.z))); image_dst[itc.x] = ((((value1_ + value2_) + value4_) + value5_) + value6_); image_dst[uint(itc.x)] = ((((value1u + value2u) + value4u) + value5u) + value6u); return; @@ -240,42 +243,131 @@ float4 levels_queries() : SV_Position float4 texture_sample() : SV_Target0 { + float4 a = (float4)0; + float2 tc = (0.5).xx; - float4 s1d = image_1d.Sample(sampler_reg, tc.x); - float4 s2d = image_2d.Sample(sampler_reg, tc); - float4 s2d_offset = image_2d.Sample(sampler_reg, tc, int2(3, 1)); - float4 s2d_level = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284); - float4 s2d_level_offset = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284, int2(3, 1)); - float4 s2d_bias_offset = image_2d.SampleBias(sampler_reg, tc, 2.0, int2(3, 1)); - return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); + float3 tc3_ = (0.5).xxx; + float4 _expr9 = image_1d.Sample(sampler_reg, tc.x); + float4 _expr10 = a; + a = (_expr10 + _expr9); + float4 _expr14 = image_2d.Sample(sampler_reg, tc); + float4 _expr15 = a; + a = (_expr15 + _expr14); + float4 _expr19 = image_2d.Sample(sampler_reg, tc, int2(3, 1)); + float4 _expr20 = a; + a = (_expr20 + _expr19); + float4 _expr24 = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284); + float4 _expr25 = a; + a = (_expr25 + _expr24); + float4 _expr29 = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284, int2(3, 1)); + float4 _expr30 = a; + a = (_expr30 + _expr29); + float4 _expr35 = image_2d.SampleBias(sampler_reg, tc, 2.0, int2(3, 1)); + float4 _expr36 = a; + a = (_expr36 + _expr35); + float4 _expr41 = image_2d_array.Sample(sampler_reg, float3(tc, 0u)); + float4 _expr42 = a; + a = (_expr42 + _expr41); + float4 _expr47 = image_2d_array.Sample(sampler_reg, float3(tc, 0u), int2(3, 1)); + float4 _expr48 = a; + a = (_expr48 + _expr47); + float4 _expr53 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.299999952316284); + float4 _expr54 = a; + a = (_expr54 + _expr53); + float4 _expr59 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.299999952316284, int2(3, 1)); + float4 _expr60 = a; + a = (_expr60 + _expr59); + float4 _expr66 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0u), 2.0, int2(3, 1)); + float4 _expr67 = a; + a = (_expr67 + _expr66); + float4 _expr72 = image_2d_array.Sample(sampler_reg, float3(tc, 0)); + float4 _expr73 = a; + a = (_expr73 + _expr72); + float4 _expr78 = image_2d_array.Sample(sampler_reg, float3(tc, 0), int2(3, 1)); + float4 _expr79 = a; + a = (_expr79 + _expr78); + float4 _expr84 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.299999952316284); + float4 _expr85 = a; + a = (_expr85 + _expr84); + float4 _expr90 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.299999952316284, int2(3, 1)); + float4 _expr91 = a; + a = (_expr91 + _expr90); + float4 _expr97 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0), 2.0, int2(3, 1)); + float4 _expr98 = a; + a = (_expr98 + _expr97); + float4 _expr103 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0u)); + float4 _expr104 = a; + a = (_expr104 + _expr103); + float4 _expr109 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0u), 2.299999952316284); + float4 _expr110 = a; + a = (_expr110 + _expr109); + float4 _expr116 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0u), 2.0); + float4 _expr117 = a; + a = (_expr117 + _expr116); + float4 _expr122 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0)); + float4 _expr123 = a; + a = (_expr123 + _expr122); + float4 _expr128 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0), 2.299999952316284); + float4 _expr129 = a; + a = (_expr129 + _expr128); + float4 _expr135 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0), 2.0); + float4 _expr136 = a; + a = (_expr136 + _expr135); + float4 _expr138 = a; + return _expr138; } float texture_sample_comparison() : SV_Target0 { + float a_1 = (float)0; + float2 tc_1 = (0.5).xx; - float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc_1, 0.5); - float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc_1, 0.5); - float scube_depth_level = image_cube_depth.SampleCmpLevelZero(sampler_cmp, (0.5).xxx, 0.5); - return (s2d_depth + s2d_depth_level); + float3 tc3_1 = (0.5).xxx; + float _expr8 = image_2d_depth.SampleCmp(sampler_cmp, tc_1, 0.5); + float _expr9 = a_1; + a_1 = (_expr9 + _expr8); + float _expr14 = image_2d_array_depth.SampleCmp(sampler_cmp, float3(tc_1, 0u), 0.5); + float _expr15 = a_1; + a_1 = (_expr15 + _expr14); + float _expr20 = image_2d_array_depth.SampleCmp(sampler_cmp, float3(tc_1, 0), 0.5); + float _expr21 = a_1; + a_1 = (_expr21 + _expr20); + float _expr25 = image_cube_depth.SampleCmp(sampler_cmp, tc3_1, 0.5); + float _expr26 = a_1; + a_1 = (_expr26 + _expr25); + float _expr30 = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc_1, 0.5); + float _expr31 = a_1; + a_1 = (_expr31 + _expr30); + float _expr36 = image_2d_array_depth.SampleCmpLevelZero(sampler_cmp, float3(tc_1, 0u), 0.5); + float _expr37 = a_1; + a_1 = (_expr37 + _expr36); + float _expr42 = image_2d_array_depth.SampleCmpLevelZero(sampler_cmp, float3(tc_1, 0), 0.5); + float _expr43 = a_1; + a_1 = (_expr43 + _expr42); + float _expr47 = image_cube_depth.SampleCmpLevelZero(sampler_cmp, tc3_1, 0.5); + float _expr48 = a_1; + a_1 = (_expr48 + _expr47); + float _expr50 = a_1; + return _expr50; } float4 gather() : SV_Target0 { float2 tc_2 = (0.5).xx; - float4 s2d_1 = image_2d.GatherGreen(sampler_reg, tc_2); - float4 s2d_offset_1 = image_2d.GatherAlpha(sampler_reg, tc_2, int2(3, 1)); - float4 s2d_depth_1 = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5); + float4 s2d = image_2d.GatherGreen(sampler_reg, tc_2); + float4 s2d_offset = image_2d.GatherAlpha(sampler_reg, tc_2, int2(3, 1)); + float4 s2d_depth = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5); float4 s2d_depth_offset = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5, int2(3, 1)); uint4 u = image_2d_u32_.Gather(sampler_reg, tc_2); int4 i = image_2d_i32_.Gather(sampler_reg, tc_2); float4 f = (float4(u) + float4(i)); - return ((((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset) + f); + return ((((s2d + s2d_offset) + s2d_depth) + s2d_depth_offset) + f); } float4 depth_no_comparison() : SV_Target0 { float2 tc_3 = (0.5).xx; - float s2d_2 = image_2d_depth.Sample(sampler_reg, tc_3); + float s2d_1 = image_2d_depth.Sample(sampler_reg, tc_3); float4 s2d_gather = image_2d_depth.Gather(sampler_reg, tc_3); - return ((s2d_2).xxxx + s2d_gather); + return ((s2d_1).xxxx + s2d_gather); } diff --git a/tests/out/msl/bounds-check-image-restrict.msl b/tests/out/msl/bounds-check-image-restrict.msl index c1e5b99df..f52fc844e 100644 --- a/tests/out/msl/bounds-check-image-restrict.msl +++ b/tests/out/msl/bounds-check-image-restrict.msl @@ -5,7 +5,7 @@ using metal::uint; constant metal::int2 const_type_4_ = {0, 0}; -constant metal::int3 const_type_7_ = {0, 0, 0}; +constant metal::int3 const_type_8_ = {0, 0, 0}; constant metal::float4 const_type_2_ = {0.0, 0.0, 0.0, 0.0}; metal::float4 test_textureLoad_1d( @@ -27,9 +27,9 @@ metal::float4 test_textureLoad_2d( return _e3; } -metal::float4 test_textureLoad_2d_array( +metal::float4 test_textureLoad_2d_array_u( metal::int2 coords_2, - int index, + uint index, int level_2, metal::texture2d_array image_2d_array ) { @@ -38,89 +38,121 @@ metal::float4 test_textureLoad_2d_array( return _e4; } -metal::float4 test_textureLoad_3d( - metal::int3 coords_3, +metal::float4 test_textureLoad_2d_array_s( + metal::int2 coords_3, + int index_1, int level_3, + metal::texture2d_array image_2d_array +) { + uint clamped_lod_e4 = metal::min(uint(level_3), image_2d_array.get_num_mip_levels() - 1); + metal::float4 _e4 = image_2d_array.read(metal::min(metal::uint2(coords_3), metal::uint2(image_2d_array.get_width(clamped_lod_e4), image_2d_array.get_height(clamped_lod_e4)) - 1), metal::min(uint(index_1), image_2d_array.get_array_size() - 1), clamped_lod_e4); + return _e4; +} + +metal::float4 test_textureLoad_3d( + metal::int3 coords_4, + int level_4, metal::texture3d image_3d ) { - uint clamped_lod_e3 = metal::min(uint(level_3), image_3d.get_num_mip_levels() - 1); - metal::float4 _e3 = image_3d.read(metal::min(metal::uint3(coords_3), metal::uint3(image_3d.get_width(clamped_lod_e3), image_3d.get_height(clamped_lod_e3), image_3d.get_depth(clamped_lod_e3)) - 1), clamped_lod_e3); + uint clamped_lod_e3 = metal::min(uint(level_4), image_3d.get_num_mip_levels() - 1); + metal::float4 _e3 = image_3d.read(metal::min(metal::uint3(coords_4), metal::uint3(image_3d.get_width(clamped_lod_e3), image_3d.get_height(clamped_lod_e3), image_3d.get_depth(clamped_lod_e3)) - 1), clamped_lod_e3); return _e3; } metal::float4 test_textureLoad_multisampled_2d( - metal::int2 coords_4, + metal::int2 coords_5, int _sample, metal::texture2d_ms image_multisampled_2d ) { - metal::float4 _e3 = image_multisampled_2d.read(metal::min(metal::uint2(coords_4), metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height()) - 1), metal::min(uint(_sample), image_multisampled_2d.get_num_samples() - 1)); + metal::float4 _e3 = image_multisampled_2d.read(metal::min(metal::uint2(coords_5), metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height()) - 1), metal::min(uint(_sample), image_multisampled_2d.get_num_samples() - 1)); return _e3; } float test_textureLoad_depth_2d( - metal::int2 coords_5, - int level_4, + metal::int2 coords_6, + int level_5, metal::depth2d image_depth_2d ) { - uint clamped_lod_e3 = metal::min(uint(level_4), image_depth_2d.get_num_mip_levels() - 1); - float _e3 = image_depth_2d.read(metal::min(metal::uint2(coords_5), metal::uint2(image_depth_2d.get_width(clamped_lod_e3), image_depth_2d.get_height(clamped_lod_e3)) - 1), clamped_lod_e3); + uint clamped_lod_e3 = metal::min(uint(level_5), image_depth_2d.get_num_mip_levels() - 1); + float _e3 = image_depth_2d.read(metal::min(metal::uint2(coords_6), metal::uint2(image_depth_2d.get_width(clamped_lod_e3), image_depth_2d.get_height(clamped_lod_e3)) - 1), clamped_lod_e3); return _e3; } -float test_textureLoad_depth_2d_array( - metal::int2 coords_6, - int index_1, - int level_5, +float test_textureLoad_depth_2d_array_u( + metal::int2 coords_7, + uint index_2, + int level_6, metal::depth2d_array image_depth_2d_array ) { - uint clamped_lod_e4 = metal::min(uint(level_5), image_depth_2d_array.get_num_mip_levels() - 1); - float _e4 = image_depth_2d_array.read(metal::min(metal::uint2(coords_6), metal::uint2(image_depth_2d_array.get_width(clamped_lod_e4), image_depth_2d_array.get_height(clamped_lod_e4)) - 1), metal::min(uint(index_1), image_depth_2d_array.get_array_size() - 1), clamped_lod_e4); + uint clamped_lod_e4 = metal::min(uint(level_6), image_depth_2d_array.get_num_mip_levels() - 1); + float _e4 = image_depth_2d_array.read(metal::min(metal::uint2(coords_7), metal::uint2(image_depth_2d_array.get_width(clamped_lod_e4), image_depth_2d_array.get_height(clamped_lod_e4)) - 1), metal::min(uint(index_2), image_depth_2d_array.get_array_size() - 1), clamped_lod_e4); + return _e4; +} + +float test_textureLoad_depth_2d_array_s( + metal::int2 coords_8, + int index_3, + int level_7, + metal::depth2d_array image_depth_2d_array +) { + uint clamped_lod_e4 = metal::min(uint(level_7), image_depth_2d_array.get_num_mip_levels() - 1); + float _e4 = image_depth_2d_array.read(metal::min(metal::uint2(coords_8), metal::uint2(image_depth_2d_array.get_width(clamped_lod_e4), image_depth_2d_array.get_height(clamped_lod_e4)) - 1), metal::min(uint(index_3), image_depth_2d_array.get_array_size() - 1), clamped_lod_e4); return _e4; } float test_textureLoad_depth_multisampled_2d( - metal::int2 coords_7, + metal::int2 coords_9, int _sample_1, metal::depth2d_ms image_depth_multisampled_2d ) { - float _e3 = image_depth_multisampled_2d.read(metal::min(metal::uint2(coords_7), metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height()) - 1), metal::min(uint(_sample_1), image_depth_multisampled_2d.get_num_samples() - 1)); + float _e3 = image_depth_multisampled_2d.read(metal::min(metal::uint2(coords_9), metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height()) - 1), metal::min(uint(_sample_1), image_depth_multisampled_2d.get_num_samples() - 1)); return _e3; } void test_textureStore_1d( - int coords_8, + int coords_10, metal::float4 value, metal::texture1d image_storage_1d ) { - image_storage_1d.write(value, metal::min(uint(coords_8), image_storage_1d.get_width() - 1)); + image_storage_1d.write(value, metal::min(uint(coords_10), image_storage_1d.get_width() - 1)); return; } void test_textureStore_2d( - metal::int2 coords_9, + metal::int2 coords_11, metal::float4 value_1, metal::texture2d image_storage_2d ) { - image_storage_2d.write(value_1, metal::min(metal::uint2(coords_9), metal::uint2(image_storage_2d.get_width(), image_storage_2d.get_height()) - 1)); + image_storage_2d.write(value_1, metal::min(metal::uint2(coords_11), metal::uint2(image_storage_2d.get_width(), image_storage_2d.get_height()) - 1)); return; } -void test_textureStore_2d_array( - metal::int2 coords_10, - int array_index, +void test_textureStore_2d_array_u( + metal::int2 coords_12, + uint array_index, metal::float4 value_2, metal::texture2d_array image_storage_2d_array ) { - image_storage_2d_array.write(value_2, metal::min(metal::uint2(coords_10), metal::uint2(image_storage_2d_array.get_width(), image_storage_2d_array.get_height()) - 1), metal::min(uint(array_index), image_storage_2d_array.get_array_size() - 1)); + image_storage_2d_array.write(value_2, metal::min(metal::uint2(coords_12), metal::uint2(image_storage_2d_array.get_width(), image_storage_2d_array.get_height()) - 1), metal::min(uint(array_index), image_storage_2d_array.get_array_size() - 1)); + return; +} + +void test_textureStore_2d_array_s( + metal::int2 coords_13, + int array_index_1, + metal::float4 value_3, + metal::texture2d_array image_storage_2d_array +) { + image_storage_2d_array.write(value_3, metal::min(metal::uint2(coords_13), metal::uint2(image_storage_2d_array.get_width(), image_storage_2d_array.get_height()) - 1), metal::min(uint(array_index_1), image_storage_2d_array.get_array_size() - 1)); return; } void test_textureStore_3d( - metal::int3 coords_11, - metal::float4 value_3, + metal::int3 coords_14, + metal::float4 value_4, metal::texture3d image_storage_3d ) { - image_storage_3d.write(value_3, metal::min(metal::uint3(coords_11), metal::uint3(image_storage_3d.get_width(), image_storage_3d.get_height(), image_storage_3d.get_depth()) - 1)); + image_storage_3d.write(value_4, metal::min(metal::uint3(coords_14), metal::uint3(image_storage_3d.get_width(), image_storage_3d.get_height(), image_storage_3d.get_depth()) - 1)); return; } @@ -140,12 +172,14 @@ fragment fragment_shaderOutput fragment_shader( ) { metal::float4 _e2 = test_textureLoad_1d(0, 0, image_1d); metal::float4 _e5 = test_textureLoad_2d(const_type_4_, 0, image_2d); - metal::float4 _e9 = test_textureLoad_2d_array(const_type_4_, 0, 0, image_2d_array); - metal::float4 _e12 = test_textureLoad_3d(const_type_7_, 0, image_3d); - metal::float4 _e15 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); + metal::float4 _e9 = test_textureLoad_2d_array_u(const_type_4_, 0u, 0, image_2d_array); + metal::float4 _e13 = test_textureLoad_2d_array_s(const_type_4_, 0, 0, image_2d_array); + metal::float4 _e16 = test_textureLoad_3d(const_type_8_, 0, image_3d); + metal::float4 _e19 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); test_textureStore_1d(0, const_type_2_, image_storage_1d); test_textureStore_2d(const_type_4_, const_type_2_, image_storage_2d); - test_textureStore_2d_array(const_type_4_, 0, const_type_2_, image_storage_2d_array); - test_textureStore_3d(const_type_7_, const_type_2_, image_storage_3d); + test_textureStore_2d_array_u(const_type_4_, 0u, const_type_2_, image_storage_2d_array); + test_textureStore_2d_array_s(const_type_4_, 0, const_type_2_, image_storage_2d_array); + test_textureStore_3d(const_type_8_, const_type_2_, image_storage_3d); return fragment_shaderOutput { metal::float4(0.0, 0.0, 0.0, 0.0) }; } diff --git a/tests/out/msl/bounds-check-image-rzsw.msl b/tests/out/msl/bounds-check-image-rzsw.msl index eeb03c984..db631d713 100644 --- a/tests/out/msl/bounds-check-image-rzsw.msl +++ b/tests/out/msl/bounds-check-image-rzsw.msl @@ -11,7 +11,7 @@ struct DefaultConstructible { }; constant metal::int2 const_type_4_ = {0, 0}; -constant metal::int3 const_type_7_ = {0, 0, 0}; +constant metal::int3 const_type_8_ = {0, 0, 0}; constant metal::float4 const_type_2_ = {0.0, 0.0, 0.0, 0.0}; metal::float4 test_textureLoad_1d( @@ -32,9 +32,9 @@ metal::float4 test_textureLoad_2d( return _e3; } -metal::float4 test_textureLoad_2d_array( +metal::float4 test_textureLoad_2d_array_u( metal::int2 coords_2, - int index, + uint index, int level_2, metal::texture2d_array image_2d_array ) { @@ -42,93 +42,125 @@ metal::float4 test_textureLoad_2d_array( return _e4; } -metal::float4 test_textureLoad_3d( - metal::int3 coords_3, +metal::float4 test_textureLoad_2d_array_s( + metal::int2 coords_3, + int index_1, int level_3, + metal::texture2d_array image_2d_array +) { + metal::float4 _e4 = (uint(level_3) < image_2d_array.get_num_mip_levels() && uint(index_1) < image_2d_array.get_array_size() && metal::all(metal::uint2(coords_3) < metal::uint2(image_2d_array.get_width(level_3), image_2d_array.get_height(level_3))) ? image_2d_array.read(metal::uint2(coords_3), index_1, level_3): DefaultConstructible()); + return _e4; +} + +metal::float4 test_textureLoad_3d( + metal::int3 coords_4, + int level_4, metal::texture3d image_3d ) { - metal::float4 _e3 = (uint(level_3) < image_3d.get_num_mip_levels() && metal::all(metal::uint3(coords_3) < metal::uint3(image_3d.get_width(level_3), image_3d.get_height(level_3), image_3d.get_depth(level_3))) ? image_3d.read(metal::uint3(coords_3), level_3): DefaultConstructible()); + metal::float4 _e3 = (uint(level_4) < image_3d.get_num_mip_levels() && metal::all(metal::uint3(coords_4) < metal::uint3(image_3d.get_width(level_4), image_3d.get_height(level_4), image_3d.get_depth(level_4))) ? image_3d.read(metal::uint3(coords_4), level_4): DefaultConstructible()); return _e3; } metal::float4 test_textureLoad_multisampled_2d( - metal::int2 coords_4, + metal::int2 coords_5, int _sample, metal::texture2d_ms image_multisampled_2d ) { - metal::float4 _e3 = (uint(_sample) < image_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_4) < metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height())) ? image_multisampled_2d.read(metal::uint2(coords_4), _sample): DefaultConstructible()); + metal::float4 _e3 = (uint(_sample) < image_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_5) < metal::uint2(image_multisampled_2d.get_width(), image_multisampled_2d.get_height())) ? image_multisampled_2d.read(metal::uint2(coords_5), _sample): DefaultConstructible()); return _e3; } float test_textureLoad_depth_2d( - metal::int2 coords_5, - int level_4, + metal::int2 coords_6, + int level_5, metal::depth2d image_depth_2d ) { - float _e3 = (uint(level_4) < image_depth_2d.get_num_mip_levels() && metal::all(metal::uint2(coords_5) < metal::uint2(image_depth_2d.get_width(level_4), image_depth_2d.get_height(level_4))) ? image_depth_2d.read(metal::uint2(coords_5), level_4): DefaultConstructible()); + float _e3 = (uint(level_5) < image_depth_2d.get_num_mip_levels() && metal::all(metal::uint2(coords_6) < metal::uint2(image_depth_2d.get_width(level_5), image_depth_2d.get_height(level_5))) ? image_depth_2d.read(metal::uint2(coords_6), level_5): DefaultConstructible()); return _e3; } -float test_textureLoad_depth_2d_array( - metal::int2 coords_6, - int index_1, - int level_5, +float test_textureLoad_depth_2d_array_u( + metal::int2 coords_7, + uint index_2, + int level_6, metal::depth2d_array image_depth_2d_array ) { - float _e4 = (uint(level_5) < image_depth_2d_array.get_num_mip_levels() && uint(index_1) < image_depth_2d_array.get_array_size() && metal::all(metal::uint2(coords_6) < metal::uint2(image_depth_2d_array.get_width(level_5), image_depth_2d_array.get_height(level_5))) ? image_depth_2d_array.read(metal::uint2(coords_6), index_1, level_5): DefaultConstructible()); + float _e4 = (uint(level_6) < image_depth_2d_array.get_num_mip_levels() && uint(index_2) < image_depth_2d_array.get_array_size() && metal::all(metal::uint2(coords_7) < metal::uint2(image_depth_2d_array.get_width(level_6), image_depth_2d_array.get_height(level_6))) ? image_depth_2d_array.read(metal::uint2(coords_7), index_2, level_6): DefaultConstructible()); + return _e4; +} + +float test_textureLoad_depth_2d_array_s( + metal::int2 coords_8, + int index_3, + int level_7, + metal::depth2d_array image_depth_2d_array +) { + float _e4 = (uint(level_7) < image_depth_2d_array.get_num_mip_levels() && uint(index_3) < image_depth_2d_array.get_array_size() && metal::all(metal::uint2(coords_8) < metal::uint2(image_depth_2d_array.get_width(level_7), image_depth_2d_array.get_height(level_7))) ? image_depth_2d_array.read(metal::uint2(coords_8), index_3, level_7): DefaultConstructible()); return _e4; } float test_textureLoad_depth_multisampled_2d( - metal::int2 coords_7, + metal::int2 coords_9, int _sample_1, metal::depth2d_ms image_depth_multisampled_2d ) { - float _e3 = (uint(_sample_1) < image_depth_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_7) < metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height())) ? image_depth_multisampled_2d.read(metal::uint2(coords_7), _sample_1): DefaultConstructible()); + float _e3 = (uint(_sample_1) < image_depth_multisampled_2d.get_num_samples() && metal::all(metal::uint2(coords_9) < metal::uint2(image_depth_multisampled_2d.get_width(), image_depth_multisampled_2d.get_height())) ? image_depth_multisampled_2d.read(metal::uint2(coords_9), _sample_1): DefaultConstructible()); return _e3; } void test_textureStore_1d( - int coords_8, + int coords_10, metal::float4 value, metal::texture1d image_storage_1d ) { - if (uint(coords_8) < image_storage_1d.get_width()) { - image_storage_1d.write(value, uint(coords_8)); + if (uint(coords_10) < image_storage_1d.get_width()) { + image_storage_1d.write(value, uint(coords_10)); } return; } void test_textureStore_2d( - metal::int2 coords_9, + metal::int2 coords_11, metal::float4 value_1, metal::texture2d image_storage_2d ) { - if (metal::all(metal::uint2(coords_9) < metal::uint2(image_storage_2d.get_width(), image_storage_2d.get_height()))) { - image_storage_2d.write(value_1, metal::uint2(coords_9)); + if (metal::all(metal::uint2(coords_11) < metal::uint2(image_storage_2d.get_width(), image_storage_2d.get_height()))) { + image_storage_2d.write(value_1, metal::uint2(coords_11)); } return; } -void test_textureStore_2d_array( - metal::int2 coords_10, - int array_index, +void test_textureStore_2d_array_u( + metal::int2 coords_12, + uint array_index, metal::float4 value_2, metal::texture2d_array image_storage_2d_array ) { - if (uint(array_index) < image_storage_2d_array.get_array_size() && metal::all(metal::uint2(coords_10) < metal::uint2(image_storage_2d_array.get_width(), image_storage_2d_array.get_height()))) { - image_storage_2d_array.write(value_2, metal::uint2(coords_10), array_index); + if (uint(array_index) < image_storage_2d_array.get_array_size() && metal::all(metal::uint2(coords_12) < metal::uint2(image_storage_2d_array.get_width(), image_storage_2d_array.get_height()))) { + image_storage_2d_array.write(value_2, metal::uint2(coords_12), array_index); + } + return; +} + +void test_textureStore_2d_array_s( + metal::int2 coords_13, + int array_index_1, + metal::float4 value_3, + metal::texture2d_array image_storage_2d_array +) { + if (uint(array_index_1) < image_storage_2d_array.get_array_size() && metal::all(metal::uint2(coords_13) < metal::uint2(image_storage_2d_array.get_width(), image_storage_2d_array.get_height()))) { + image_storage_2d_array.write(value_3, metal::uint2(coords_13), array_index_1); } return; } void test_textureStore_3d( - metal::int3 coords_11, - metal::float4 value_3, + metal::int3 coords_14, + metal::float4 value_4, metal::texture3d image_storage_3d ) { - if (metal::all(metal::uint3(coords_11) < metal::uint3(image_storage_3d.get_width(), image_storage_3d.get_height(), image_storage_3d.get_depth()))) { - image_storage_3d.write(value_3, metal::uint3(coords_11)); + if (metal::all(metal::uint3(coords_14) < metal::uint3(image_storage_3d.get_width(), image_storage_3d.get_height(), image_storage_3d.get_depth()))) { + image_storage_3d.write(value_4, metal::uint3(coords_14)); } return; } @@ -149,12 +181,14 @@ fragment fragment_shaderOutput fragment_shader( ) { metal::float4 _e2 = test_textureLoad_1d(0, 0, image_1d); metal::float4 _e5 = test_textureLoad_2d(const_type_4_, 0, image_2d); - metal::float4 _e9 = test_textureLoad_2d_array(const_type_4_, 0, 0, image_2d_array); - metal::float4 _e12 = test_textureLoad_3d(const_type_7_, 0, image_3d); - metal::float4 _e15 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); + metal::float4 _e9 = test_textureLoad_2d_array_u(const_type_4_, 0u, 0, image_2d_array); + metal::float4 _e13 = test_textureLoad_2d_array_s(const_type_4_, 0, 0, image_2d_array); + metal::float4 _e16 = test_textureLoad_3d(const_type_8_, 0, image_3d); + metal::float4 _e19 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); test_textureStore_1d(0, const_type_2_, image_storage_1d); test_textureStore_2d(const_type_4_, const_type_2_, image_storage_2d); - test_textureStore_2d_array(const_type_4_, 0, const_type_2_, image_storage_2d_array); - test_textureStore_3d(const_type_7_, const_type_2_, image_storage_3d); + test_textureStore_2d_array_u(const_type_4_, 0u, const_type_2_, image_storage_2d_array); + test_textureStore_2d_array_s(const_type_4_, 0, const_type_2_, image_storage_2d_array); + test_textureStore_3d(const_type_8_, const_type_2_, image_storage_3d); return fragment_shaderOutput { metal::float4(0.0, 0.0, 0.0, 0.0) }; } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index b0de96238..685867175 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -22,13 +22,15 @@ kernel void main_( metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast(local_id.z)); metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc)); - metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); - metal::uint4 value6_ = image_1d_src.read(uint(static_cast(local_id.x))); + metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), local_id.z, static_cast(local_id.z) + 1); + metal::uint4 value6_ = image_array_src.read(metal::uint2(itc), static_cast(local_id.z), static_cast(local_id.z) + 1); + metal::uint4 value7_ = image_1d_src.read(uint(static_cast(local_id.x))); metal::uint4 value1u = image_mipmapped_src.read(metal::uint2(static_cast(itc)), static_cast(local_id.z)); metal::uint4 value2u = image_multisampled_src.read(metal::uint2(static_cast(itc)), static_cast(local_id.z)); metal::uint4 value4u = image_storage_src.read(metal::uint2(static_cast(itc))); - metal::uint4 value5u = image_array_src.read(metal::uint2(static_cast(itc)), static_cast(local_id.z), static_cast(local_id.z) + 1); - metal::uint4 value6u = image_1d_src.read(uint(static_cast(local_id.x))); + metal::uint4 value5u = image_array_src.read(metal::uint2(static_cast(itc)), local_id.z, static_cast(local_id.z) + 1); + metal::uint4 value6u = image_array_src.read(metal::uint2(static_cast(itc)), static_cast(local_id.z), static_cast(local_id.z) + 1); + metal::uint4 value7u = image_1d_src.read(uint(static_cast(local_id.x))); image_dst.write((((value1_ + value2_) + value4_) + value5_) + value6_, uint(itc.x)); image_dst.write((((value1u + value2u) + value4u) + value5u) + value6u, uint(static_cast(itc.x))); return; @@ -111,16 +113,81 @@ struct texture_sampleOutput { fragment texture_sampleOutput texture_sample( metal::texture1d image_1d [[user(fake0)]] , metal::texture2d image_2d [[user(fake0)]] +, metal::texture2d_array image_2d_array [[user(fake0)]] +, metal::texturecube_array image_cube_array [[user(fake0)]] , metal::sampler sampler_reg [[user(fake0)]] ) { + metal::float4 a = {}; metal::float2 tc = metal::float2(0.5); - metal::float4 s1d = image_1d.sample(sampler_reg, tc.x); - metal::float4 s2d = image_2d.sample(sampler_reg, tc); - metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type_9_); - metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); - metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_9_); - metal::float4 s2d_bias_offset = image_2d.sample(sampler_reg, tc, metal::bias(2.0), const_type_9_); - return texture_sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset }; + metal::float3 tc3_ = metal::float3(0.5); + metal::float4 _e9 = image_1d.sample(sampler_reg, tc.x); + metal::float4 _e10 = a; + a = _e10 + _e9; + metal::float4 _e14 = image_2d.sample(sampler_reg, tc); + metal::float4 _e15 = a; + a = _e15 + _e14; + metal::float4 _e19 = image_2d.sample(sampler_reg, tc, const_type_9_); + metal::float4 _e20 = a; + a = _e20 + _e19; + metal::float4 _e24 = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); + metal::float4 _e25 = a; + a = _e25 + _e24; + metal::float4 _e29 = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_9_); + metal::float4 _e30 = a; + a = _e30 + _e29; + metal::float4 _e35 = image_2d.sample(sampler_reg, tc, metal::bias(2.0), const_type_9_); + metal::float4 _e36 = a; + a = _e36 + _e35; + metal::float4 _e41 = image_2d_array.sample(sampler_reg, tc, 0u); + metal::float4 _e42 = a; + a = _e42 + _e41; + metal::float4 _e47 = image_2d_array.sample(sampler_reg, tc, 0u, const_type_9_); + metal::float4 _e48 = a; + a = _e48 + _e47; + metal::float4 _e53 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.299999952316284)); + metal::float4 _e54 = a; + a = _e54 + _e53; + metal::float4 _e59 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.299999952316284), const_type_9_); + metal::float4 _e60 = a; + a = _e60 + _e59; + metal::float4 _e66 = image_2d_array.sample(sampler_reg, tc, 0u, metal::bias(2.0), const_type_9_); + metal::float4 _e67 = a; + a = _e67 + _e66; + metal::float4 _e72 = image_2d_array.sample(sampler_reg, tc, 0); + metal::float4 _e73 = a; + a = _e73 + _e72; + metal::float4 _e78 = image_2d_array.sample(sampler_reg, tc, 0, const_type_9_); + metal::float4 _e79 = a; + a = _e79 + _e78; + metal::float4 _e84 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.299999952316284)); + metal::float4 _e85 = a; + a = _e85 + _e84; + metal::float4 _e90 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.299999952316284), const_type_9_); + metal::float4 _e91 = a; + a = _e91 + _e90; + metal::float4 _e97 = image_2d_array.sample(sampler_reg, tc, 0, metal::bias(2.0), const_type_9_); + metal::float4 _e98 = a; + a = _e98 + _e97; + metal::float4 _e103 = image_cube_array.sample(sampler_reg, tc3_, 0u); + metal::float4 _e104 = a; + a = _e104 + _e103; + metal::float4 _e109 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::level(2.299999952316284)); + metal::float4 _e110 = a; + a = _e110 + _e109; + metal::float4 _e116 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::bias(2.0)); + metal::float4 _e117 = a; + a = _e117 + _e116; + metal::float4 _e122 = image_cube_array.sample(sampler_reg, tc3_, 0); + metal::float4 _e123 = a; + a = _e123 + _e122; + metal::float4 _e128 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::level(2.299999952316284)); + metal::float4 _e129 = a; + a = _e129 + _e128; + metal::float4 _e135 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::bias(2.0)); + metal::float4 _e136 = a; + a = _e136 + _e135; + metal::float4 _e138 = a; + return texture_sampleOutput { _e138 }; } @@ -130,13 +197,38 @@ struct texture_sample_comparisonOutput { fragment texture_sample_comparisonOutput texture_sample_comparison( metal::sampler sampler_cmp [[user(fake0)]] , metal::depth2d image_2d_depth [[user(fake0)]] +, metal::depth2d_array image_2d_array_depth [[user(fake0)]] , metal::depthcube image_cube_depth [[user(fake0)]] ) { + float a_1 = {}; metal::float2 tc_1 = metal::float2(0.5); - float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); - float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); - float scube_depth_level = image_cube_depth.sample_compare(sampler_cmp, metal::float3(0.5), 0.5); - return texture_sample_comparisonOutput { s2d_depth + s2d_depth_level }; + metal::float3 tc3_1 = metal::float3(0.5); + float _e8 = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); + float _e9 = a_1; + a_1 = _e9 + _e8; + float _e14 = image_2d_array_depth.sample_compare(sampler_cmp, tc_1, 0u, 0.5); + float _e15 = a_1; + a_1 = _e15 + _e14; + float _e20 = image_2d_array_depth.sample_compare(sampler_cmp, tc_1, 0, 0.5); + float _e21 = a_1; + a_1 = _e21 + _e20; + float _e25 = image_cube_depth.sample_compare(sampler_cmp, tc3_1, 0.5); + float _e26 = a_1; + a_1 = _e26 + _e25; + float _e30 = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5); + float _e31 = a_1; + a_1 = _e31 + _e30; + float _e36 = image_2d_array_depth.sample_compare(sampler_cmp, tc_1, 0u, 0.5); + float _e37 = a_1; + a_1 = _e37 + _e36; + float _e42 = image_2d_array_depth.sample_compare(sampler_cmp, tc_1, 0, 0.5); + float _e43 = a_1; + a_1 = _e43 + _e42; + float _e47 = image_cube_depth.sample_compare(sampler_cmp, tc3_1, 0.5); + float _e48 = a_1; + a_1 = _e48 + _e47; + float _e50 = a_1; + return texture_sample_comparisonOutput { _e50 }; } @@ -152,14 +244,14 @@ fragment gatherOutput gather( , metal::depth2d image_2d_depth [[user(fake0)]] ) { metal::float2 tc_2 = metal::float2(0.5); - metal::float4 s2d_1 = image_2d.gather(sampler_reg, tc_2, metal::int2(0), metal::component::y); - metal::float4 s2d_offset_1 = image_2d.gather(sampler_reg, tc_2, const_type_9_, metal::component::w); - metal::float4 s2d_depth_1 = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5); + metal::float4 s2d = image_2d.gather(sampler_reg, tc_2, metal::int2(0), metal::component::y); + metal::float4 s2d_offset = image_2d.gather(sampler_reg, tc_2, const_type_9_, metal::component::w); + metal::float4 s2d_depth = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5); metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, const_type_9_); metal::uint4 u = image_2d_u32_.gather(sampler_reg, tc_2); metal::int4 i = image_2d_i32_.gather(sampler_reg, tc_2); metal::float4 f = static_cast(u) + static_cast(i); - return gatherOutput { (((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset) + f }; + return gatherOutput { (((s2d + s2d_offset) + s2d_depth) + s2d_depth_offset) + f }; } @@ -171,7 +263,7 @@ fragment depth_no_comparisonOutput depth_no_comparison( , metal::depth2d image_2d_depth [[user(fake0)]] ) { metal::float2 tc_3 = metal::float2(0.5); - float s2d_2 = image_2d_depth.sample(sampler_reg, tc_3); + float s2d_1 = image_2d_depth.sample(sampler_reg, tc_3); metal::float4 s2d_gather = image_2d_depth.gather(sampler_reg, tc_3); - return depth_no_comparisonOutput { metal::float4(s2d_2) + s2d_gather }; + return depth_no_comparisonOutput { metal::float4(s2d_1) + s2d_gather }; } diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index 51d53f3d0..09d6ad2f4 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -1,380 +1,457 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 244 +; Bound: 299 OpCapability ImageQuery OpCapability Image1D OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %222 "fragment_shader" %220 -OpExecutionMode %222 OriginUpperLeft +OpEntryPoint Fragment %275 "fragment_shader" %273 +OpExecutionMode %275 OriginUpperLeft OpSource GLSL 450 -OpName %25 "image_1d" -OpName %27 "image_2d" -OpName %29 "image_2d_array" -OpName %31 "image_3d" -OpName %33 "image_multisampled_2d" -OpName %35 "image_depth_2d" -OpName %37 "image_depth_2d_array" -OpName %39 "image_depth_multisampled_2d" -OpName %41 "image_storage_1d" -OpName %43 "image_storage_2d" -OpName %45 "image_storage_2d_array" -OpName %47 "image_storage_3d" -OpName %50 "coords" -OpName %51 "level" -OpName %52 "test_textureLoad_1d" -OpName %65 "coords" -OpName %66 "level" -OpName %67 "test_textureLoad_2d" -OpName %80 "coords" -OpName %81 "index" -OpName %82 "level" -OpName %83 "test_textureLoad_2d_array" -OpName %97 "coords" -OpName %98 "level" -OpName %99 "test_textureLoad_3d" -OpName %112 "coords" -OpName %113 "_sample" -OpName %114 "test_textureLoad_multisampled_2d" -OpName %126 "coords" -OpName %127 "level" -OpName %128 "test_textureLoad_depth_2d" -OpName %142 "coords" -OpName %143 "index" -OpName %144 "level" -OpName %145 "test_textureLoad_depth_2d_array" -OpName %160 "coords" -OpName %161 "_sample" -OpName %162 "test_textureLoad_depth_multisampled_2d" -OpName %175 "coords" -OpName %176 "value" -OpName %177 "test_textureStore_1d" -OpName %185 "coords" -OpName %186 "value" -OpName %187 "test_textureStore_2d" -OpName %196 "coords" -OpName %197 "array_index" -OpName %198 "value" -OpName %199 "test_textureStore_2d_array" -OpName %209 "coords" -OpName %210 "value" -OpName %211 "test_textureStore_3d" -OpName %222 "fragment_shader" -OpDecorate %25 DescriptorSet 0 -OpDecorate %25 Binding 0 +OpName %27 "image_1d" +OpName %29 "image_2d" +OpName %31 "image_2d_array" +OpName %33 "image_3d" +OpName %35 "image_multisampled_2d" +OpName %37 "image_depth_2d" +OpName %39 "image_depth_2d_array" +OpName %41 "image_depth_multisampled_2d" +OpName %43 "image_storage_1d" +OpName %45 "image_storage_2d" +OpName %47 "image_storage_2d_array" +OpName %49 "image_storage_3d" +OpName %52 "coords" +OpName %53 "level" +OpName %54 "test_textureLoad_1d" +OpName %67 "coords" +OpName %68 "level" +OpName %69 "test_textureLoad_2d" +OpName %82 "coords" +OpName %83 "index" +OpName %84 "level" +OpName %85 "test_textureLoad_2d_array_u" +OpName %100 "coords" +OpName %101 "index" +OpName %102 "level" +OpName %103 "test_textureLoad_2d_array_s" +OpName %117 "coords" +OpName %118 "level" +OpName %119 "test_textureLoad_3d" +OpName %132 "coords" +OpName %133 "_sample" +OpName %134 "test_textureLoad_multisampled_2d" +OpName %146 "coords" +OpName %147 "level" +OpName %148 "test_textureLoad_depth_2d" +OpName %162 "coords" +OpName %163 "index" +OpName %164 "level" +OpName %165 "test_textureLoad_depth_2d_array_u" +OpName %181 "coords" +OpName %182 "index" +OpName %183 "level" +OpName %184 "test_textureLoad_depth_2d_array_s" +OpName %199 "coords" +OpName %200 "_sample" +OpName %201 "test_textureLoad_depth_multisampled_2d" +OpName %214 "coords" +OpName %215 "value" +OpName %216 "test_textureStore_1d" +OpName %224 "coords" +OpName %225 "value" +OpName %226 "test_textureStore_2d" +OpName %235 "coords" +OpName %236 "array_index" +OpName %237 "value" +OpName %238 "test_textureStore_2d_array_u" +OpName %249 "coords" +OpName %250 "array_index" +OpName %251 "value" +OpName %252 "test_textureStore_2d_array_s" +OpName %262 "coords" +OpName %263 "value" +OpName %264 "test_textureStore_3d" +OpName %275 "fragment_shader" OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 1 +OpDecorate %27 Binding 0 OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 2 +OpDecorate %29 Binding 1 OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 3 +OpDecorate %31 Binding 2 OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 4 +OpDecorate %33 Binding 3 OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 5 +OpDecorate %35 Binding 4 OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 6 +OpDecorate %37 Binding 5 OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 7 -OpDecorate %41 NonReadable +OpDecorate %39 Binding 6 OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 8 +OpDecorate %41 Binding 7 OpDecorate %43 NonReadable OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 9 +OpDecorate %43 Binding 8 OpDecorate %45 NonReadable OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 10 +OpDecorate %45 Binding 9 OpDecorate %47 NonReadable OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 11 -OpDecorate %220 Location 0 +OpDecorate %47 Binding 10 +OpDecorate %49 NonReadable +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 11 +OpDecorate %273 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 0 -%6 = OpTypeFloat 32 -%5 = OpConstant %6 0.0 -%7 = OpTypeImage %6 1D 0 0 0 1 Unknown -%8 = OpTypeVector %6 4 -%9 = OpTypeImage %6 2D 0 0 0 1 Unknown -%10 = OpTypeVector %4 2 -%11 = OpTypeImage %6 2D 0 1 0 1 Unknown -%12 = OpTypeImage %6 3D 0 0 0 1 Unknown -%13 = OpTypeVector %4 3 -%14 = OpTypeImage %6 2D 0 0 1 1 Unknown -%15 = OpTypeImage %6 2D 1 0 0 1 Unknown -%16 = OpTypeImage %6 2D 1 1 0 1 Unknown -%17 = OpTypeImage %6 2D 1 0 1 1 Unknown -%18 = OpTypeImage %6 1D 0 0 0 2 Rgba8 -%19 = OpTypeImage %6 2D 0 0 0 2 Rgba8 -%20 = OpTypeImage %6 2D 0 1 0 2 Rgba8 -%21 = OpTypeImage %6 3D 0 0 0 2 Rgba8 -%22 = OpConstantComposite %10 %3 %3 -%23 = OpConstantComposite %13 %3 %3 %3 -%24 = OpConstantComposite %8 %5 %5 %5 %5 -%26 = OpTypePointer UniformConstant %7 -%25 = OpVariable %26 UniformConstant +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 0 +%8 = OpTypeFloat 32 +%7 = OpConstant %8 0.0 +%9 = OpTypeImage %8 1D 0 0 0 1 Unknown +%10 = OpTypeVector %8 4 +%11 = OpTypeImage %8 2D 0 0 0 1 Unknown +%12 = OpTypeVector %4 2 +%13 = OpTypeImage %8 2D 0 1 0 1 Unknown +%14 = OpTypeImage %8 3D 0 0 0 1 Unknown +%15 = OpTypeVector %4 3 +%16 = OpTypeImage %8 2D 0 0 1 1 Unknown +%17 = OpTypeImage %8 2D 1 0 0 1 Unknown +%18 = OpTypeImage %8 2D 1 1 0 1 Unknown +%19 = OpTypeImage %8 2D 1 0 1 1 Unknown +%20 = OpTypeImage %8 1D 0 0 0 2 Rgba8 +%21 = OpTypeImage %8 2D 0 0 0 2 Rgba8 +%22 = OpTypeImage %8 2D 0 1 0 2 Rgba8 +%23 = OpTypeImage %8 3D 0 0 0 2 Rgba8 +%24 = OpConstantComposite %12 %3 %3 +%25 = OpConstantComposite %15 %3 %3 %3 +%26 = OpConstantComposite %10 %7 %7 %7 %7 %28 = OpTypePointer UniformConstant %9 %27 = OpVariable %28 UniformConstant %30 = OpTypePointer UniformConstant %11 %29 = OpVariable %30 UniformConstant -%32 = OpTypePointer UniformConstant %12 +%32 = OpTypePointer UniformConstant %13 %31 = OpVariable %32 UniformConstant %34 = OpTypePointer UniformConstant %14 %33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %15 +%36 = OpTypePointer UniformConstant %16 %35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %16 +%38 = OpTypePointer UniformConstant %17 %37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %17 +%40 = OpTypePointer UniformConstant %18 %39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %18 +%42 = OpTypePointer UniformConstant %19 %41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %19 +%44 = OpTypePointer UniformConstant %20 %43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %20 +%46 = OpTypePointer UniformConstant %21 %45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %21 +%48 = OpTypePointer UniformConstant %22 %47 = OpVariable %48 UniformConstant -%53 = OpTypeFunction %8 %4 %4 -%57 = OpConstant %4 1 -%68 = OpTypeFunction %8 %10 %4 -%75 = OpConstantComposite %10 %57 %57 -%84 = OpTypeFunction %8 %10 %4 %4 -%92 = OpConstantComposite %13 %57 %57 %57 -%100 = OpTypeFunction %8 %13 %4 -%107 = OpConstantComposite %13 %57 %57 %57 -%121 = OpConstantComposite %10 %57 %57 -%129 = OpTypeFunction %6 %10 %4 -%136 = OpConstantComposite %10 %57 %57 -%146 = OpTypeFunction %6 %10 %4 %4 -%154 = OpConstantComposite %13 %57 %57 %57 -%169 = OpConstantComposite %10 %57 %57 -%178 = OpTypeFunction %2 %4 %8 -%188 = OpTypeFunction %2 %10 %8 -%192 = OpConstantComposite %10 %57 %57 -%200 = OpTypeFunction %2 %10 %4 %8 -%205 = OpConstantComposite %13 %57 %57 %57 -%212 = OpTypeFunction %2 %13 %8 -%216 = OpConstantComposite %13 %57 %57 %57 -%221 = OpTypePointer Output %8 -%220 = OpVariable %221 Output -%223 = OpTypeFunction %2 -%52 = OpFunction %8 None %53 -%50 = OpFunctionParameter %4 -%51 = OpFunctionParameter %4 -%49 = OpLabel -%54 = OpLoad %7 %25 -OpBranch %55 -%55 = OpLabel -%56 = OpImageQueryLevels %4 %54 -%58 = OpISub %4 %56 %57 -%59 = OpExtInst %4 %1 UMin %51 %58 -%60 = OpImageQuerySizeLod %4 %54 %59 -%61 = OpISub %4 %60 %57 -%62 = OpExtInst %4 %1 UMin %50 %61 -%63 = OpImageFetch %8 %54 %62 Lod %59 -OpReturnValue %63 +%50 = OpTypePointer UniformConstant %23 +%49 = OpVariable %50 UniformConstant +%55 = OpTypeFunction %10 %4 %4 +%59 = OpConstant %4 1 +%70 = OpTypeFunction %10 %12 %4 +%77 = OpConstantComposite %12 %59 %59 +%86 = OpTypeFunction %10 %12 %6 %4 +%95 = OpConstantComposite %15 %59 %59 %59 +%104 = OpTypeFunction %10 %12 %4 %4 +%112 = OpConstantComposite %15 %59 %59 %59 +%120 = OpTypeFunction %10 %15 %4 +%127 = OpConstantComposite %15 %59 %59 %59 +%141 = OpConstantComposite %12 %59 %59 +%149 = OpTypeFunction %8 %12 %4 +%156 = OpConstantComposite %12 %59 %59 +%166 = OpTypeFunction %8 %12 %6 %4 +%175 = OpConstantComposite %15 %59 %59 %59 +%185 = OpTypeFunction %8 %12 %4 %4 +%193 = OpConstantComposite %15 %59 %59 %59 +%208 = OpConstantComposite %12 %59 %59 +%217 = OpTypeFunction %2 %4 %10 +%227 = OpTypeFunction %2 %12 %10 +%231 = OpConstantComposite %12 %59 %59 +%239 = OpTypeFunction %2 %12 %6 %10 +%245 = OpConstantComposite %15 %59 %59 %59 +%253 = OpTypeFunction %2 %12 %4 %10 +%258 = OpConstantComposite %15 %59 %59 %59 +%265 = OpTypeFunction %2 %15 %10 +%269 = OpConstantComposite %15 %59 %59 %59 +%274 = OpTypePointer Output %10 +%273 = OpVariable %274 Output +%276 = OpTypeFunction %2 +%54 = OpFunction %10 None %55 +%52 = OpFunctionParameter %4 +%53 = OpFunctionParameter %4 +%51 = OpLabel +%56 = OpLoad %9 %27 +OpBranch %57 +%57 = OpLabel +%58 = OpImageQueryLevels %4 %56 +%60 = OpISub %4 %58 %59 +%61 = OpExtInst %4 %1 UMin %53 %60 +%62 = OpImageQuerySizeLod %4 %56 %61 +%63 = OpISub %4 %62 %59 +%64 = OpExtInst %4 %1 UMin %52 %63 +%65 = OpImageFetch %10 %56 %64 Lod %61 +OpReturnValue %65 OpFunctionEnd -%67 = OpFunction %8 None %68 -%65 = OpFunctionParameter %10 -%66 = OpFunctionParameter %4 -%64 = OpLabel -%69 = OpLoad %9 %27 -OpBranch %70 -%70 = OpLabel -%71 = OpImageQueryLevels %4 %69 -%72 = OpISub %4 %71 %57 -%73 = OpExtInst %4 %1 UMin %66 %72 -%74 = OpImageQuerySizeLod %10 %69 %73 -%76 = OpISub %10 %74 %75 -%77 = OpExtInst %10 %1 UMin %65 %76 -%78 = OpImageFetch %8 %69 %77 Lod %73 -OpReturnValue %78 +%69 = OpFunction %10 None %70 +%67 = OpFunctionParameter %12 +%68 = OpFunctionParameter %4 +%66 = OpLabel +%71 = OpLoad %11 %29 +OpBranch %72 +%72 = OpLabel +%73 = OpImageQueryLevels %4 %71 +%74 = OpISub %4 %73 %59 +%75 = OpExtInst %4 %1 UMin %68 %74 +%76 = OpImageQuerySizeLod %12 %71 %75 +%78 = OpISub %12 %76 %77 +%79 = OpExtInst %12 %1 UMin %67 %78 +%80 = OpImageFetch %10 %71 %79 Lod %75 +OpReturnValue %80 OpFunctionEnd -%83 = OpFunction %8 None %84 -%80 = OpFunctionParameter %10 -%81 = OpFunctionParameter %4 -%82 = OpFunctionParameter %4 -%79 = OpLabel -%85 = OpLoad %11 %29 -OpBranch %86 -%86 = OpLabel -%87 = OpCompositeConstruct %13 %80 %81 -%88 = OpImageQueryLevels %4 %85 -%89 = OpISub %4 %88 %57 -%90 = OpExtInst %4 %1 UMin %82 %89 -%91 = OpImageQuerySizeLod %13 %85 %90 -%93 = OpISub %13 %91 %92 -%94 = OpExtInst %13 %1 UMin %87 %93 -%95 = OpImageFetch %8 %85 %94 Lod %90 -OpReturnValue %95 +%85 = OpFunction %10 None %86 +%82 = OpFunctionParameter %12 +%83 = OpFunctionParameter %6 +%84 = OpFunctionParameter %4 +%81 = OpLabel +%87 = OpLoad %13 %31 +OpBranch %88 +%88 = OpLabel +%89 = OpBitcast %4 %83 +%90 = OpCompositeConstruct %15 %82 %89 +%91 = OpImageQueryLevels %4 %87 +%92 = OpISub %4 %91 %59 +%93 = OpExtInst %4 %1 UMin %84 %92 +%94 = OpImageQuerySizeLod %15 %87 %93 +%96 = OpISub %15 %94 %95 +%97 = OpExtInst %15 %1 UMin %90 %96 +%98 = OpImageFetch %10 %87 %97 Lod %93 +OpReturnValue %98 OpFunctionEnd -%99 = OpFunction %8 None %100 -%97 = OpFunctionParameter %13 -%98 = OpFunctionParameter %4 -%96 = OpLabel -%101 = OpLoad %12 %31 -OpBranch %102 -%102 = OpLabel -%103 = OpImageQueryLevels %4 %101 -%104 = OpISub %4 %103 %57 -%105 = OpExtInst %4 %1 UMin %98 %104 -%106 = OpImageQuerySizeLod %13 %101 %105 -%108 = OpISub %13 %106 %107 -%109 = OpExtInst %13 %1 UMin %97 %108 -%110 = OpImageFetch %8 %101 %109 Lod %105 -OpReturnValue %110 +%103 = OpFunction %10 None %104 +%100 = OpFunctionParameter %12 +%101 = OpFunctionParameter %4 +%102 = OpFunctionParameter %4 +%99 = OpLabel +%105 = OpLoad %13 %31 +OpBranch %106 +%106 = OpLabel +%107 = OpCompositeConstruct %15 %100 %101 +%108 = OpImageQueryLevels %4 %105 +%109 = OpISub %4 %108 %59 +%110 = OpExtInst %4 %1 UMin %102 %109 +%111 = OpImageQuerySizeLod %15 %105 %110 +%113 = OpISub %15 %111 %112 +%114 = OpExtInst %15 %1 UMin %107 %113 +%115 = OpImageFetch %10 %105 %114 Lod %110 +OpReturnValue %115 OpFunctionEnd -%114 = OpFunction %8 None %68 -%112 = OpFunctionParameter %10 -%113 = OpFunctionParameter %4 -%111 = OpLabel -%115 = OpLoad %14 %33 -OpBranch %116 +%119 = OpFunction %10 None %120 +%117 = OpFunctionParameter %15 +%118 = OpFunctionParameter %4 %116 = OpLabel -%117 = OpImageQuerySamples %4 %115 -%118 = OpISub %4 %117 %57 -%119 = OpExtInst %4 %1 UMin %113 %118 -%120 = OpImageQuerySize %10 %115 -%122 = OpISub %10 %120 %121 -%123 = OpExtInst %10 %1 UMin %112 %122 -%124 = OpImageFetch %8 %115 %123 Sample %119 -OpReturnValue %124 +%121 = OpLoad %14 %33 +OpBranch %122 +%122 = OpLabel +%123 = OpImageQueryLevels %4 %121 +%124 = OpISub %4 %123 %59 +%125 = OpExtInst %4 %1 UMin %118 %124 +%126 = OpImageQuerySizeLod %15 %121 %125 +%128 = OpISub %15 %126 %127 +%129 = OpExtInst %15 %1 UMin %117 %128 +%130 = OpImageFetch %10 %121 %129 Lod %125 +OpReturnValue %130 OpFunctionEnd -%128 = OpFunction %6 None %129 -%126 = OpFunctionParameter %10 -%127 = OpFunctionParameter %4 -%125 = OpLabel -%130 = OpLoad %15 %35 -OpBranch %131 +%134 = OpFunction %10 None %70 +%132 = OpFunctionParameter %12 +%133 = OpFunctionParameter %4 %131 = OpLabel -%132 = OpImageQueryLevels %4 %130 -%133 = OpISub %4 %132 %57 -%134 = OpExtInst %4 %1 UMin %127 %133 -%135 = OpImageQuerySizeLod %10 %130 %134 -%137 = OpISub %10 %135 %136 -%138 = OpExtInst %10 %1 UMin %126 %137 -%139 = OpImageFetch %8 %130 %138 Lod %134 -%140 = OpCompositeExtract %6 %139 0 -OpReturnValue %140 +%135 = OpLoad %16 %35 +OpBranch %136 +%136 = OpLabel +%137 = OpImageQuerySamples %4 %135 +%138 = OpISub %4 %137 %59 +%139 = OpExtInst %4 %1 UMin %133 %138 +%140 = OpImageQuerySize %12 %135 +%142 = OpISub %12 %140 %141 +%143 = OpExtInst %12 %1 UMin %132 %142 +%144 = OpImageFetch %10 %135 %143 Sample %139 +OpReturnValue %144 OpFunctionEnd -%145 = OpFunction %6 None %146 -%142 = OpFunctionParameter %10 -%143 = OpFunctionParameter %4 -%144 = OpFunctionParameter %4 -%141 = OpLabel -%147 = OpLoad %16 %37 -OpBranch %148 -%148 = OpLabel -%149 = OpCompositeConstruct %13 %142 %143 -%150 = OpImageQueryLevels %4 %147 -%151 = OpISub %4 %150 %57 -%152 = OpExtInst %4 %1 UMin %144 %151 -%153 = OpImageQuerySizeLod %13 %147 %152 -%155 = OpISub %13 %153 %154 -%156 = OpExtInst %13 %1 UMin %149 %155 -%157 = OpImageFetch %8 %147 %156 Lod %152 -%158 = OpCompositeExtract %6 %157 0 -OpReturnValue %158 +%148 = OpFunction %8 None %149 +%146 = OpFunctionParameter %12 +%147 = OpFunctionParameter %4 +%145 = OpLabel +%150 = OpLoad %17 %37 +OpBranch %151 +%151 = OpLabel +%152 = OpImageQueryLevels %4 %150 +%153 = OpISub %4 %152 %59 +%154 = OpExtInst %4 %1 UMin %147 %153 +%155 = OpImageQuerySizeLod %12 %150 %154 +%157 = OpISub %12 %155 %156 +%158 = OpExtInst %12 %1 UMin %146 %157 +%159 = OpImageFetch %10 %150 %158 Lod %154 +%160 = OpCompositeExtract %8 %159 0 +OpReturnValue %160 OpFunctionEnd -%162 = OpFunction %6 None %129 -%160 = OpFunctionParameter %10 -%161 = OpFunctionParameter %4 -%159 = OpLabel -%163 = OpLoad %17 %39 -OpBranch %164 -%164 = OpLabel -%165 = OpImageQuerySamples %4 %163 -%166 = OpISub %4 %165 %57 -%167 = OpExtInst %4 %1 UMin %161 %166 -%168 = OpImageQuerySize %10 %163 -%170 = OpISub %10 %168 %169 -%171 = OpExtInst %10 %1 UMin %160 %170 -%172 = OpImageFetch %8 %163 %171 Sample %167 -%173 = OpCompositeExtract %6 %172 0 -OpReturnValue %173 +%165 = OpFunction %8 None %166 +%162 = OpFunctionParameter %12 +%163 = OpFunctionParameter %6 +%164 = OpFunctionParameter %4 +%161 = OpLabel +%167 = OpLoad %18 %39 +OpBranch %168 +%168 = OpLabel +%169 = OpBitcast %4 %163 +%170 = OpCompositeConstruct %15 %162 %169 +%171 = OpImageQueryLevels %4 %167 +%172 = OpISub %4 %171 %59 +%173 = OpExtInst %4 %1 UMin %164 %172 +%174 = OpImageQuerySizeLod %15 %167 %173 +%176 = OpISub %15 %174 %175 +%177 = OpExtInst %15 %1 UMin %170 %176 +%178 = OpImageFetch %10 %167 %177 Lod %173 +%179 = OpCompositeExtract %8 %178 0 +OpReturnValue %179 OpFunctionEnd -%177 = OpFunction %2 None %178 -%175 = OpFunctionParameter %4 -%176 = OpFunctionParameter %8 -%174 = OpLabel -%179 = OpLoad %18 %41 -OpBranch %180 +%184 = OpFunction %8 None %185 +%181 = OpFunctionParameter %12 +%182 = OpFunctionParameter %4 +%183 = OpFunctionParameter %4 %180 = OpLabel -%181 = OpImageQuerySize %4 %179 -%182 = OpISub %4 %181 %57 -%183 = OpExtInst %4 %1 UMin %175 %182 -OpImageWrite %179 %183 %176 -OpReturn +%186 = OpLoad %18 %39 +OpBranch %187 +%187 = OpLabel +%188 = OpCompositeConstruct %15 %181 %182 +%189 = OpImageQueryLevels %4 %186 +%190 = OpISub %4 %189 %59 +%191 = OpExtInst %4 %1 UMin %183 %190 +%192 = OpImageQuerySizeLod %15 %186 %191 +%194 = OpISub %15 %192 %193 +%195 = OpExtInst %15 %1 UMin %188 %194 +%196 = OpImageFetch %10 %186 %195 Lod %191 +%197 = OpCompositeExtract %8 %196 0 +OpReturnValue %197 OpFunctionEnd -%187 = OpFunction %2 None %188 -%185 = OpFunctionParameter %10 -%186 = OpFunctionParameter %8 -%184 = OpLabel -%189 = OpLoad %19 %43 -OpBranch %190 -%190 = OpLabel -%191 = OpImageQuerySize %10 %189 -%193 = OpISub %10 %191 %192 -%194 = OpExtInst %10 %1 UMin %185 %193 -OpImageWrite %189 %194 %186 -OpReturn +%201 = OpFunction %8 None %149 +%199 = OpFunctionParameter %12 +%200 = OpFunctionParameter %4 +%198 = OpLabel +%202 = OpLoad %19 %41 +OpBranch %203 +%203 = OpLabel +%204 = OpImageQuerySamples %4 %202 +%205 = OpISub %4 %204 %59 +%206 = OpExtInst %4 %1 UMin %200 %205 +%207 = OpImageQuerySize %12 %202 +%209 = OpISub %12 %207 %208 +%210 = OpExtInst %12 %1 UMin %199 %209 +%211 = OpImageFetch %10 %202 %210 Sample %206 +%212 = OpCompositeExtract %8 %211 0 +OpReturnValue %212 OpFunctionEnd -%199 = OpFunction %2 None %200 -%196 = OpFunctionParameter %10 -%197 = OpFunctionParameter %4 -%198 = OpFunctionParameter %8 -%195 = OpLabel -%201 = OpLoad %20 %45 -OpBranch %202 -%202 = OpLabel -%203 = OpCompositeConstruct %13 %196 %197 -%204 = OpImageQuerySize %13 %201 -%206 = OpISub %13 %204 %205 -%207 = OpExtInst %13 %1 UMin %203 %206 -OpImageWrite %201 %207 %198 -OpReturn -OpFunctionEnd -%211 = OpFunction %2 None %212 -%209 = OpFunctionParameter %13 -%210 = OpFunctionParameter %8 -%208 = OpLabel -%213 = OpLoad %21 %47 -OpBranch %214 -%214 = OpLabel -%215 = OpImageQuerySize %13 %213 -%217 = OpISub %13 %215 %216 -%218 = OpExtInst %13 %1 UMin %209 %217 -OpImageWrite %213 %218 %210 -OpReturn -OpFunctionEnd -%222 = OpFunction %2 None %223 +%216 = OpFunction %2 None %217 +%214 = OpFunctionParameter %4 +%215 = OpFunctionParameter %10 +%213 = OpLabel +%218 = OpLoad %20 %43 +OpBranch %219 %219 = OpLabel -%224 = OpLoad %7 %25 -%225 = OpLoad %9 %27 -%226 = OpLoad %11 %29 -%227 = OpLoad %12 %31 -%228 = OpLoad %14 %33 -%229 = OpLoad %18 %41 -%230 = OpLoad %19 %43 -%231 = OpLoad %20 %45 -%232 = OpLoad %21 %47 -OpBranch %233 -%233 = OpLabel -%234 = OpFunctionCall %8 %52 %3 %3 -%235 = OpFunctionCall %8 %67 %22 %3 -%236 = OpFunctionCall %8 %83 %22 %3 %3 -%237 = OpFunctionCall %8 %99 %23 %3 -%238 = OpFunctionCall %8 %114 %22 %3 -%239 = OpFunctionCall %2 %177 %3 %24 -%240 = OpFunctionCall %2 %187 %22 %24 -%241 = OpFunctionCall %2 %199 %22 %3 %24 -%242 = OpFunctionCall %2 %211 %23 %24 -%243 = OpCompositeConstruct %8 %5 %5 %5 %5 -OpStore %220 %243 +%220 = OpImageQuerySize %4 %218 +%221 = OpISub %4 %220 %59 +%222 = OpExtInst %4 %1 UMin %214 %221 +OpImageWrite %218 %222 %215 +OpReturn +OpFunctionEnd +%226 = OpFunction %2 None %227 +%224 = OpFunctionParameter %12 +%225 = OpFunctionParameter %10 +%223 = OpLabel +%228 = OpLoad %21 %45 +OpBranch %229 +%229 = OpLabel +%230 = OpImageQuerySize %12 %228 +%232 = OpISub %12 %230 %231 +%233 = OpExtInst %12 %1 UMin %224 %232 +OpImageWrite %228 %233 %225 +OpReturn +OpFunctionEnd +%238 = OpFunction %2 None %239 +%235 = OpFunctionParameter %12 +%236 = OpFunctionParameter %6 +%237 = OpFunctionParameter %10 +%234 = OpLabel +%240 = OpLoad %22 %47 +OpBranch %241 +%241 = OpLabel +%242 = OpBitcast %4 %236 +%243 = OpCompositeConstruct %15 %235 %242 +%244 = OpImageQuerySize %15 %240 +%246 = OpISub %15 %244 %245 +%247 = OpExtInst %15 %1 UMin %243 %246 +OpImageWrite %240 %247 %237 +OpReturn +OpFunctionEnd +%252 = OpFunction %2 None %253 +%249 = OpFunctionParameter %12 +%250 = OpFunctionParameter %4 +%251 = OpFunctionParameter %10 +%248 = OpLabel +%254 = OpLoad %22 %47 +OpBranch %255 +%255 = OpLabel +%256 = OpCompositeConstruct %15 %249 %250 +%257 = OpImageQuerySize %15 %254 +%259 = OpISub %15 %257 %258 +%260 = OpExtInst %15 %1 UMin %256 %259 +OpImageWrite %254 %260 %251 +OpReturn +OpFunctionEnd +%264 = OpFunction %2 None %265 +%262 = OpFunctionParameter %15 +%263 = OpFunctionParameter %10 +%261 = OpLabel +%266 = OpLoad %23 %49 +OpBranch %267 +%267 = OpLabel +%268 = OpImageQuerySize %15 %266 +%270 = OpISub %15 %268 %269 +%271 = OpExtInst %15 %1 UMin %262 %270 +OpImageWrite %266 %271 %263 +OpReturn +OpFunctionEnd +%275 = OpFunction %2 None %276 +%272 = OpLabel +%277 = OpLoad %9 %27 +%278 = OpLoad %11 %29 +%279 = OpLoad %13 %31 +%280 = OpLoad %14 %33 +%281 = OpLoad %16 %35 +%282 = OpLoad %20 %43 +%283 = OpLoad %21 %45 +%284 = OpLoad %22 %47 +%285 = OpLoad %23 %49 +OpBranch %286 +%286 = OpLabel +%287 = OpFunctionCall %10 %54 %3 %3 +%288 = OpFunctionCall %10 %69 %24 %3 +%289 = OpFunctionCall %10 %85 %24 %5 %3 +%290 = OpFunctionCall %10 %103 %24 %3 %3 +%291 = OpFunctionCall %10 %119 %25 %3 +%292 = OpFunctionCall %10 %134 %24 %3 +%293 = OpFunctionCall %2 %216 %3 %26 +%294 = OpFunctionCall %2 %226 %24 %26 +%295 = OpFunctionCall %2 %238 %24 %5 %26 +%296 = OpFunctionCall %2 %252 %24 %3 %26 +%297 = OpFunctionCall %2 %264 %25 %26 +%298 = OpCompositeConstruct %10 %7 %7 %7 %7 +OpStore %273 %298 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index 3c8e79009..ce64a3dfc 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -1,454 +1,549 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 274 +; Bound: 336 OpCapability ImageQuery OpCapability Image1D OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %252 "fragment_shader" %250 -OpExecutionMode %252 OriginUpperLeft +OpEntryPoint Fragment %312 "fragment_shader" %310 +OpExecutionMode %312 OriginUpperLeft OpSource GLSL 450 -OpName %25 "image_1d" -OpName %27 "image_2d" -OpName %29 "image_2d_array" -OpName %31 "image_3d" -OpName %33 "image_multisampled_2d" -OpName %35 "image_depth_2d" -OpName %37 "image_depth_2d_array" -OpName %39 "image_depth_multisampled_2d" -OpName %41 "image_storage_1d" -OpName %43 "image_storage_2d" -OpName %45 "image_storage_2d_array" -OpName %47 "image_storage_3d" -OpName %50 "coords" -OpName %51 "level" -OpName %52 "test_textureLoad_1d" -OpName %68 "coords" -OpName %69 "level" -OpName %70 "test_textureLoad_2d" -OpName %87 "coords" -OpName %88 "index" -OpName %89 "level" -OpName %90 "test_textureLoad_2d_array" -OpName %108 "coords" -OpName %109 "level" -OpName %110 "test_textureLoad_3d" -OpName %126 "coords" -OpName %127 "_sample" -OpName %128 "test_textureLoad_multisampled_2d" -OpName %143 "coords" -OpName %144 "level" -OpName %145 "test_textureLoad_depth_2d" -OpName %162 "coords" -OpName %163 "index" -OpName %164 "level" -OpName %165 "test_textureLoad_depth_2d_array" -OpName %183 "coords" -OpName %184 "_sample" -OpName %185 "test_textureLoad_depth_multisampled_2d" -OpName %201 "coords" -OpName %202 "value" -OpName %203 "test_textureStore_1d" -OpName %212 "coords" -OpName %213 "value" -OpName %214 "test_textureStore_2d" -OpName %224 "coords" -OpName %225 "array_index" -OpName %226 "value" -OpName %227 "test_textureStore_2d_array" -OpName %238 "coords" -OpName %239 "value" -OpName %240 "test_textureStore_3d" -OpName %252 "fragment_shader" -OpDecorate %25 DescriptorSet 0 -OpDecorate %25 Binding 0 +OpName %27 "image_1d" +OpName %29 "image_2d" +OpName %31 "image_2d_array" +OpName %33 "image_3d" +OpName %35 "image_multisampled_2d" +OpName %37 "image_depth_2d" +OpName %39 "image_depth_2d_array" +OpName %41 "image_depth_multisampled_2d" +OpName %43 "image_storage_1d" +OpName %45 "image_storage_2d" +OpName %47 "image_storage_2d_array" +OpName %49 "image_storage_3d" +OpName %52 "coords" +OpName %53 "level" +OpName %54 "test_textureLoad_1d" +OpName %70 "coords" +OpName %71 "level" +OpName %72 "test_textureLoad_2d" +OpName %89 "coords" +OpName %90 "index" +OpName %91 "level" +OpName %92 "test_textureLoad_2d_array_u" +OpName %111 "coords" +OpName %112 "index" +OpName %113 "level" +OpName %114 "test_textureLoad_2d_array_s" +OpName %131 "coords" +OpName %132 "level" +OpName %133 "test_textureLoad_3d" +OpName %149 "coords" +OpName %150 "_sample" +OpName %151 "test_textureLoad_multisampled_2d" +OpName %166 "coords" +OpName %167 "level" +OpName %168 "test_textureLoad_depth_2d" +OpName %185 "coords" +OpName %186 "index" +OpName %187 "level" +OpName %188 "test_textureLoad_depth_2d_array_u" +OpName %207 "coords" +OpName %208 "index" +OpName %209 "level" +OpName %210 "test_textureLoad_depth_2d_array_s" +OpName %228 "coords" +OpName %229 "_sample" +OpName %230 "test_textureLoad_depth_multisampled_2d" +OpName %246 "coords" +OpName %247 "value" +OpName %248 "test_textureStore_1d" +OpName %257 "coords" +OpName %258 "value" +OpName %259 "test_textureStore_2d" +OpName %269 "coords" +OpName %270 "array_index" +OpName %271 "value" +OpName %272 "test_textureStore_2d_array_u" +OpName %284 "coords" +OpName %285 "array_index" +OpName %286 "value" +OpName %287 "test_textureStore_2d_array_s" +OpName %298 "coords" +OpName %299 "value" +OpName %300 "test_textureStore_3d" +OpName %312 "fragment_shader" OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 1 +OpDecorate %27 Binding 0 OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 2 +OpDecorate %29 Binding 1 OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 3 +OpDecorate %31 Binding 2 OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 4 +OpDecorate %33 Binding 3 OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 5 +OpDecorate %35 Binding 4 OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 6 +OpDecorate %37 Binding 5 OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 7 -OpDecorate %41 NonReadable +OpDecorate %39 Binding 6 OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 8 +OpDecorate %41 Binding 7 OpDecorate %43 NonReadable OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 9 +OpDecorate %43 Binding 8 OpDecorate %45 NonReadable OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 10 +OpDecorate %45 Binding 9 OpDecorate %47 NonReadable OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 11 -OpDecorate %250 Location 0 +OpDecorate %47 Binding 10 +OpDecorate %49 NonReadable +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 11 +OpDecorate %310 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 0 -%6 = OpTypeFloat 32 -%5 = OpConstant %6 0.0 -%7 = OpTypeImage %6 1D 0 0 0 1 Unknown -%8 = OpTypeVector %6 4 -%9 = OpTypeImage %6 2D 0 0 0 1 Unknown -%10 = OpTypeVector %4 2 -%11 = OpTypeImage %6 2D 0 1 0 1 Unknown -%12 = OpTypeImage %6 3D 0 0 0 1 Unknown -%13 = OpTypeVector %4 3 -%14 = OpTypeImage %6 2D 0 0 1 1 Unknown -%15 = OpTypeImage %6 2D 1 0 0 1 Unknown -%16 = OpTypeImage %6 2D 1 1 0 1 Unknown -%17 = OpTypeImage %6 2D 1 0 1 1 Unknown -%18 = OpTypeImage %6 1D 0 0 0 2 Rgba8 -%19 = OpTypeImage %6 2D 0 0 0 2 Rgba8 -%20 = OpTypeImage %6 2D 0 1 0 2 Rgba8 -%21 = OpTypeImage %6 3D 0 0 0 2 Rgba8 -%22 = OpConstantComposite %10 %3 %3 -%23 = OpConstantComposite %13 %3 %3 %3 -%24 = OpConstantComposite %8 %5 %5 %5 %5 -%26 = OpTypePointer UniformConstant %7 -%25 = OpVariable %26 UniformConstant +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 0 +%8 = OpTypeFloat 32 +%7 = OpConstant %8 0.0 +%9 = OpTypeImage %8 1D 0 0 0 1 Unknown +%10 = OpTypeVector %8 4 +%11 = OpTypeImage %8 2D 0 0 0 1 Unknown +%12 = OpTypeVector %4 2 +%13 = OpTypeImage %8 2D 0 1 0 1 Unknown +%14 = OpTypeImage %8 3D 0 0 0 1 Unknown +%15 = OpTypeVector %4 3 +%16 = OpTypeImage %8 2D 0 0 1 1 Unknown +%17 = OpTypeImage %8 2D 1 0 0 1 Unknown +%18 = OpTypeImage %8 2D 1 1 0 1 Unknown +%19 = OpTypeImage %8 2D 1 0 1 1 Unknown +%20 = OpTypeImage %8 1D 0 0 0 2 Rgba8 +%21 = OpTypeImage %8 2D 0 0 0 2 Rgba8 +%22 = OpTypeImage %8 2D 0 1 0 2 Rgba8 +%23 = OpTypeImage %8 3D 0 0 0 2 Rgba8 +%24 = OpConstantComposite %12 %3 %3 +%25 = OpConstantComposite %15 %3 %3 %3 +%26 = OpConstantComposite %10 %7 %7 %7 %7 %28 = OpTypePointer UniformConstant %9 %27 = OpVariable %28 UniformConstant %30 = OpTypePointer UniformConstant %11 %29 = OpVariable %30 UniformConstant -%32 = OpTypePointer UniformConstant %12 +%32 = OpTypePointer UniformConstant %13 %31 = OpVariable %32 UniformConstant %34 = OpTypePointer UniformConstant %14 %33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %15 +%36 = OpTypePointer UniformConstant %16 %35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %16 +%38 = OpTypePointer UniformConstant %17 %37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %17 +%40 = OpTypePointer UniformConstant %18 %39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %18 +%42 = OpTypePointer UniformConstant %19 %41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %19 +%44 = OpTypePointer UniformConstant %20 %43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %20 +%46 = OpTypePointer UniformConstant %21 %45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %21 +%48 = OpTypePointer UniformConstant %22 %47 = OpVariable %48 UniformConstant -%53 = OpTypeFunction %8 %4 %4 -%56 = OpTypeBool -%57 = OpConstantNull %8 -%71 = OpTypeFunction %8 %10 %4 -%74 = OpConstantNull %8 -%80 = OpTypeVector %56 2 -%91 = OpTypeFunction %8 %10 %4 %4 -%95 = OpConstantNull %8 -%101 = OpTypeVector %56 3 -%111 = OpTypeFunction %8 %13 %4 -%114 = OpConstantNull %8 -%131 = OpConstantNull %8 -%146 = OpTypeFunction %6 %10 %4 -%149 = OpConstantNull %8 -%166 = OpTypeFunction %6 %10 %4 %4 -%170 = OpConstantNull %8 -%188 = OpConstantNull %8 -%204 = OpTypeFunction %2 %4 %8 -%215 = OpTypeFunction %2 %10 %8 -%228 = OpTypeFunction %2 %10 %4 %8 -%241 = OpTypeFunction %2 %13 %8 -%251 = OpTypePointer Output %8 -%250 = OpVariable %251 Output -%253 = OpTypeFunction %2 -%52 = OpFunction %8 None %53 -%50 = OpFunctionParameter %4 -%51 = OpFunctionParameter %4 -%49 = OpLabel -%54 = OpLoad %7 %25 -OpBranch %55 -%55 = OpLabel -%58 = OpImageQueryLevels %4 %54 -%59 = OpULessThan %56 %51 %58 -OpSelectionMerge %60 None -OpBranchConditional %59 %61 %60 -%61 = OpLabel -%62 = OpImageQuerySizeLod %4 %54 %51 -%63 = OpULessThan %56 %50 %62 -OpBranchConditional %63 %64 %60 -%64 = OpLabel -%65 = OpImageFetch %8 %54 %50 Lod %51 -OpBranch %60 -%60 = OpLabel -%66 = OpPhi %8 %57 %55 %57 %61 %65 %64 -OpReturnValue %66 +%50 = OpTypePointer UniformConstant %23 +%49 = OpVariable %50 UniformConstant +%55 = OpTypeFunction %10 %4 %4 +%58 = OpTypeBool +%59 = OpConstantNull %10 +%73 = OpTypeFunction %10 %12 %4 +%76 = OpConstantNull %10 +%82 = OpTypeVector %58 2 +%93 = OpTypeFunction %10 %12 %6 %4 +%98 = OpConstantNull %10 +%104 = OpTypeVector %58 3 +%115 = OpTypeFunction %10 %12 %4 %4 +%119 = OpConstantNull %10 +%134 = OpTypeFunction %10 %15 %4 +%137 = OpConstantNull %10 +%154 = OpConstantNull %10 +%169 = OpTypeFunction %8 %12 %4 +%172 = OpConstantNull %10 +%189 = OpTypeFunction %8 %12 %6 %4 +%194 = OpConstantNull %10 +%211 = OpTypeFunction %8 %12 %4 %4 +%215 = OpConstantNull %10 +%233 = OpConstantNull %10 +%249 = OpTypeFunction %2 %4 %10 +%260 = OpTypeFunction %2 %12 %10 +%273 = OpTypeFunction %2 %12 %6 %10 +%288 = OpTypeFunction %2 %12 %4 %10 +%301 = OpTypeFunction %2 %15 %10 +%311 = OpTypePointer Output %10 +%310 = OpVariable %311 Output +%313 = OpTypeFunction %2 +%54 = OpFunction %10 None %55 +%52 = OpFunctionParameter %4 +%53 = OpFunctionParameter %4 +%51 = OpLabel +%56 = OpLoad %9 %27 +OpBranch %57 +%57 = OpLabel +%60 = OpImageQueryLevels %4 %56 +%61 = OpULessThan %58 %53 %60 +OpSelectionMerge %62 None +OpBranchConditional %61 %63 %62 +%63 = OpLabel +%64 = OpImageQuerySizeLod %4 %56 %53 +%65 = OpULessThan %58 %52 %64 +OpBranchConditional %65 %66 %62 +%66 = OpLabel +%67 = OpImageFetch %10 %56 %52 Lod %53 +OpBranch %62 +%62 = OpLabel +%68 = OpPhi %10 %59 %57 %59 %63 %67 %66 +OpReturnValue %68 OpFunctionEnd -%70 = OpFunction %8 None %71 -%68 = OpFunctionParameter %10 -%69 = OpFunctionParameter %4 -%67 = OpLabel -%72 = OpLoad %9 %27 -OpBranch %73 -%73 = OpLabel -%75 = OpImageQueryLevels %4 %72 -%76 = OpULessThan %56 %69 %75 -OpSelectionMerge %77 None -OpBranchConditional %76 %78 %77 -%78 = OpLabel -%79 = OpImageQuerySizeLod %10 %72 %69 -%81 = OpULessThan %80 %68 %79 -%82 = OpAll %56 %81 -OpBranchConditional %82 %83 %77 -%83 = OpLabel -%84 = OpImageFetch %8 %72 %68 Lod %69 -OpBranch %77 -%77 = OpLabel -%85 = OpPhi %8 %74 %73 %74 %78 %84 %83 -OpReturnValue %85 +%72 = OpFunction %10 None %73 +%70 = OpFunctionParameter %12 +%71 = OpFunctionParameter %4 +%69 = OpLabel +%74 = OpLoad %11 %29 +OpBranch %75 +%75 = OpLabel +%77 = OpImageQueryLevels %4 %74 +%78 = OpULessThan %58 %71 %77 +OpSelectionMerge %79 None +OpBranchConditional %78 %80 %79 +%80 = OpLabel +%81 = OpImageQuerySizeLod %12 %74 %71 +%83 = OpULessThan %82 %70 %81 +%84 = OpAll %58 %83 +OpBranchConditional %84 %85 %79 +%85 = OpLabel +%86 = OpImageFetch %10 %74 %70 Lod %71 +OpBranch %79 +%79 = OpLabel +%87 = OpPhi %10 %76 %75 %76 %80 %86 %85 +OpReturnValue %87 OpFunctionEnd -%90 = OpFunction %8 None %91 -%87 = OpFunctionParameter %10 -%88 = OpFunctionParameter %4 -%89 = OpFunctionParameter %4 -%86 = OpLabel -%92 = OpLoad %11 %29 -OpBranch %93 -%93 = OpLabel -%94 = OpCompositeConstruct %13 %87 %88 -%96 = OpImageQueryLevels %4 %92 -%97 = OpULessThan %56 %89 %96 -OpSelectionMerge %98 None -OpBranchConditional %97 %99 %98 -%99 = OpLabel -%100 = OpImageQuerySizeLod %13 %92 %89 -%102 = OpULessThan %101 %94 %100 -%103 = OpAll %56 %102 -OpBranchConditional %103 %104 %98 -%104 = OpLabel -%105 = OpImageFetch %8 %92 %94 Lod %89 -OpBranch %98 -%98 = OpLabel -%106 = OpPhi %8 %95 %93 %95 %99 %105 %104 -OpReturnValue %106 -OpFunctionEnd -%110 = OpFunction %8 None %111 -%108 = OpFunctionParameter %13 -%109 = OpFunctionParameter %4 +%92 = OpFunction %10 None %93 +%89 = OpFunctionParameter %12 +%90 = OpFunctionParameter %6 +%91 = OpFunctionParameter %4 +%88 = OpLabel +%94 = OpLoad %13 %31 +OpBranch %95 +%95 = OpLabel +%96 = OpBitcast %4 %90 +%97 = OpCompositeConstruct %15 %89 %96 +%99 = OpImageQueryLevels %4 %94 +%100 = OpULessThan %58 %91 %99 +OpSelectionMerge %101 None +OpBranchConditional %100 %102 %101 +%102 = OpLabel +%103 = OpImageQuerySizeLod %15 %94 %91 +%105 = OpULessThan %104 %97 %103 +%106 = OpAll %58 %105 +OpBranchConditional %106 %107 %101 %107 = OpLabel -%112 = OpLoad %12 %31 -OpBranch %113 -%113 = OpLabel -%115 = OpImageQueryLevels %4 %112 -%116 = OpULessThan %56 %109 %115 -OpSelectionMerge %117 None -OpBranchConditional %116 %118 %117 -%118 = OpLabel -%119 = OpImageQuerySizeLod %13 %112 %109 -%120 = OpULessThan %101 %108 %119 -%121 = OpAll %56 %120 -OpBranchConditional %121 %122 %117 -%122 = OpLabel -%123 = OpImageFetch %8 %112 %108 Lod %109 +%108 = OpImageFetch %10 %94 %97 Lod %91 +OpBranch %101 +%101 = OpLabel +%109 = OpPhi %10 %98 %95 %98 %102 %108 %107 +OpReturnValue %109 +OpFunctionEnd +%114 = OpFunction %10 None %115 +%111 = OpFunctionParameter %12 +%112 = OpFunctionParameter %4 +%113 = OpFunctionParameter %4 +%110 = OpLabel +%116 = OpLoad %13 %31 OpBranch %117 %117 = OpLabel -%124 = OpPhi %8 %114 %113 %114 %118 %123 %122 -OpReturnValue %124 +%118 = OpCompositeConstruct %15 %111 %112 +%120 = OpImageQueryLevels %4 %116 +%121 = OpULessThan %58 %113 %120 +OpSelectionMerge %122 None +OpBranchConditional %121 %123 %122 +%123 = OpLabel +%124 = OpImageQuerySizeLod %15 %116 %113 +%125 = OpULessThan %104 %118 %124 +%126 = OpAll %58 %125 +OpBranchConditional %126 %127 %122 +%127 = OpLabel +%128 = OpImageFetch %10 %116 %118 Lod %113 +OpBranch %122 +%122 = OpLabel +%129 = OpPhi %10 %119 %117 %119 %123 %128 %127 +OpReturnValue %129 OpFunctionEnd -%128 = OpFunction %8 None %71 -%126 = OpFunctionParameter %10 -%127 = OpFunctionParameter %4 -%125 = OpLabel -%129 = OpLoad %14 %33 -OpBranch %130 +%133 = OpFunction %10 None %134 +%131 = OpFunctionParameter %15 +%132 = OpFunctionParameter %4 %130 = OpLabel -%132 = OpImageQuerySamples %4 %129 -%133 = OpULessThan %56 %127 %132 -OpSelectionMerge %134 None -OpBranchConditional %133 %135 %134 -%135 = OpLabel -%136 = OpImageQuerySize %10 %129 -%137 = OpULessThan %80 %126 %136 -%138 = OpAll %56 %137 -OpBranchConditional %138 %139 %134 -%139 = OpLabel -%140 = OpImageFetch %8 %129 %126 Sample %127 -OpBranch %134 -%134 = OpLabel -%141 = OpPhi %8 %131 %130 %131 %135 %140 %139 -OpReturnValue %141 +%135 = OpLoad %14 %33 +OpBranch %136 +%136 = OpLabel +%138 = OpImageQueryLevels %4 %135 +%139 = OpULessThan %58 %132 %138 +OpSelectionMerge %140 None +OpBranchConditional %139 %141 %140 +%141 = OpLabel +%142 = OpImageQuerySizeLod %15 %135 %132 +%143 = OpULessThan %104 %131 %142 +%144 = OpAll %58 %143 +OpBranchConditional %144 %145 %140 +%145 = OpLabel +%146 = OpImageFetch %10 %135 %131 Lod %132 +OpBranch %140 +%140 = OpLabel +%147 = OpPhi %10 %137 %136 %137 %141 %146 %145 +OpReturnValue %147 OpFunctionEnd -%145 = OpFunction %6 None %146 -%143 = OpFunctionParameter %10 -%144 = OpFunctionParameter %4 -%142 = OpLabel -%147 = OpLoad %15 %35 -OpBranch %148 +%151 = OpFunction %10 None %73 +%149 = OpFunctionParameter %12 +%150 = OpFunctionParameter %4 %148 = OpLabel -%150 = OpImageQueryLevels %4 %147 -%151 = OpULessThan %56 %144 %150 -OpSelectionMerge %152 None -OpBranchConditional %151 %153 %152 +%152 = OpLoad %16 %35 +OpBranch %153 %153 = OpLabel -%154 = OpImageQuerySizeLod %10 %147 %144 -%155 = OpULessThan %80 %143 %154 -%156 = OpAll %56 %155 -OpBranchConditional %156 %157 %152 +%155 = OpImageQuerySamples %4 %152 +%156 = OpULessThan %58 %150 %155 +OpSelectionMerge %157 None +OpBranchConditional %156 %158 %157 +%158 = OpLabel +%159 = OpImageQuerySize %12 %152 +%160 = OpULessThan %82 %149 %159 +%161 = OpAll %58 %160 +OpBranchConditional %161 %162 %157 +%162 = OpLabel +%163 = OpImageFetch %10 %152 %149 Sample %150 +OpBranch %157 %157 = OpLabel -%158 = OpImageFetch %8 %147 %143 Lod %144 -OpBranch %152 -%152 = OpLabel -%159 = OpPhi %8 %149 %148 %149 %153 %158 %157 -%160 = OpCompositeExtract %6 %159 0 -OpReturnValue %160 +%164 = OpPhi %10 %154 %153 %154 %158 %163 %162 +OpReturnValue %164 OpFunctionEnd -%165 = OpFunction %6 None %166 -%162 = OpFunctionParameter %10 -%163 = OpFunctionParameter %4 -%164 = OpFunctionParameter %4 -%161 = OpLabel -%167 = OpLoad %16 %37 -OpBranch %168 -%168 = OpLabel -%169 = OpCompositeConstruct %13 %162 %163 -%171 = OpImageQueryLevels %4 %167 -%172 = OpULessThan %56 %164 %171 -OpSelectionMerge %173 None -OpBranchConditional %172 %174 %173 -%174 = OpLabel -%175 = OpImageQuerySizeLod %13 %167 %164 -%176 = OpULessThan %101 %169 %175 -%177 = OpAll %56 %176 -OpBranchConditional %177 %178 %173 -%178 = OpLabel -%179 = OpImageFetch %8 %167 %169 Lod %164 -OpBranch %173 -%173 = OpLabel -%180 = OpPhi %8 %170 %168 %170 %174 %179 %178 -%181 = OpCompositeExtract %6 %180 0 -OpReturnValue %181 +%168 = OpFunction %8 None %169 +%166 = OpFunctionParameter %12 +%167 = OpFunctionParameter %4 +%165 = OpLabel +%170 = OpLoad %17 %37 +OpBranch %171 +%171 = OpLabel +%173 = OpImageQueryLevels %4 %170 +%174 = OpULessThan %58 %167 %173 +OpSelectionMerge %175 None +OpBranchConditional %174 %176 %175 +%176 = OpLabel +%177 = OpImageQuerySizeLod %12 %170 %167 +%178 = OpULessThan %82 %166 %177 +%179 = OpAll %58 %178 +OpBranchConditional %179 %180 %175 +%180 = OpLabel +%181 = OpImageFetch %10 %170 %166 Lod %167 +OpBranch %175 +%175 = OpLabel +%182 = OpPhi %10 %172 %171 %172 %176 %181 %180 +%183 = OpCompositeExtract %8 %182 0 +OpReturnValue %183 OpFunctionEnd -%185 = OpFunction %6 None %146 -%183 = OpFunctionParameter %10 -%184 = OpFunctionParameter %4 -%182 = OpLabel -%186 = OpLoad %17 %39 -OpBranch %187 -%187 = OpLabel -%189 = OpImageQuerySamples %4 %186 -%190 = OpULessThan %56 %184 %189 -OpSelectionMerge %191 None -OpBranchConditional %190 %192 %191 -%192 = OpLabel -%193 = OpImageQuerySize %10 %186 -%194 = OpULessThan %80 %183 %193 -%195 = OpAll %56 %194 -OpBranchConditional %195 %196 %191 -%196 = OpLabel -%197 = OpImageFetch %8 %186 %183 Sample %184 +%188 = OpFunction %8 None %189 +%185 = OpFunctionParameter %12 +%186 = OpFunctionParameter %6 +%187 = OpFunctionParameter %4 +%184 = OpLabel +%190 = OpLoad %18 %39 OpBranch %191 %191 = OpLabel -%198 = OpPhi %8 %188 %187 %188 %192 %197 %196 -%199 = OpCompositeExtract %6 %198 0 -OpReturnValue %199 +%192 = OpBitcast %4 %186 +%193 = OpCompositeConstruct %15 %185 %192 +%195 = OpImageQueryLevels %4 %190 +%196 = OpULessThan %58 %187 %195 +OpSelectionMerge %197 None +OpBranchConditional %196 %198 %197 +%198 = OpLabel +%199 = OpImageQuerySizeLod %15 %190 %187 +%200 = OpULessThan %104 %193 %199 +%201 = OpAll %58 %200 +OpBranchConditional %201 %202 %197 +%202 = OpLabel +%203 = OpImageFetch %10 %190 %193 Lod %187 +OpBranch %197 +%197 = OpLabel +%204 = OpPhi %10 %194 %191 %194 %198 %203 %202 +%205 = OpCompositeExtract %8 %204 0 +OpReturnValue %205 OpFunctionEnd -%203 = OpFunction %2 None %204 -%201 = OpFunctionParameter %4 -%202 = OpFunctionParameter %8 -%200 = OpLabel -%205 = OpLoad %18 %41 -OpBranch %206 +%210 = OpFunction %8 None %211 +%207 = OpFunctionParameter %12 +%208 = OpFunctionParameter %4 +%209 = OpFunctionParameter %4 %206 = OpLabel -%207 = OpImageQuerySize %4 %205 -%208 = OpULessThan %56 %201 %207 -OpSelectionMerge %209 None -OpBranchConditional %208 %210 %209 -%210 = OpLabel -OpImageWrite %205 %201 %202 -OpBranch %209 -%209 = OpLabel -OpReturn -OpFunctionEnd -%214 = OpFunction %2 None %215 -%212 = OpFunctionParameter %10 -%213 = OpFunctionParameter %8 -%211 = OpLabel -%216 = OpLoad %19 %43 -OpBranch %217 -%217 = OpLabel -%218 = OpImageQuerySize %10 %216 -%219 = OpULessThan %80 %212 %218 -%220 = OpAll %56 %219 -OpSelectionMerge %221 None -OpBranchConditional %220 %222 %221 -%222 = OpLabel -OpImageWrite %216 %212 %213 -OpBranch %221 -%221 = OpLabel -OpReturn -OpFunctionEnd -%227 = OpFunction %2 None %228 -%224 = OpFunctionParameter %10 -%225 = OpFunctionParameter %4 -%226 = OpFunctionParameter %8 +%212 = OpLoad %18 %39 +OpBranch %213 +%213 = OpLabel +%214 = OpCompositeConstruct %15 %207 %208 +%216 = OpImageQueryLevels %4 %212 +%217 = OpULessThan %58 %209 %216 +OpSelectionMerge %218 None +OpBranchConditional %217 %219 %218 +%219 = OpLabel +%220 = OpImageQuerySizeLod %15 %212 %209 +%221 = OpULessThan %104 %214 %220 +%222 = OpAll %58 %221 +OpBranchConditional %222 %223 %218 %223 = OpLabel -%229 = OpLoad %20 %45 -OpBranch %230 -%230 = OpLabel -%231 = OpCompositeConstruct %13 %224 %225 -%232 = OpImageQuerySize %13 %229 -%233 = OpULessThan %101 %231 %232 -%234 = OpAll %56 %233 -OpSelectionMerge %235 None -OpBranchConditional %234 %236 %235 -%236 = OpLabel -OpImageWrite %229 %231 %226 -OpBranch %235 -%235 = OpLabel -OpReturn +%224 = OpImageFetch %10 %212 %214 Lod %209 +OpBranch %218 +%218 = OpLabel +%225 = OpPhi %10 %215 %213 %215 %219 %224 %223 +%226 = OpCompositeExtract %8 %225 0 +OpReturnValue %226 OpFunctionEnd -%240 = OpFunction %2 None %241 -%238 = OpFunctionParameter %13 -%239 = OpFunctionParameter %8 +%230 = OpFunction %8 None %169 +%228 = OpFunctionParameter %12 +%229 = OpFunctionParameter %4 +%227 = OpLabel +%231 = OpLoad %19 %41 +OpBranch %232 +%232 = OpLabel +%234 = OpImageQuerySamples %4 %231 +%235 = OpULessThan %58 %229 %234 +OpSelectionMerge %236 None +OpBranchConditional %235 %237 %236 %237 = OpLabel -%242 = OpLoad %21 %47 -OpBranch %243 -%243 = OpLabel -%244 = OpImageQuerySize %13 %242 -%245 = OpULessThan %101 %238 %244 -%246 = OpAll %56 %245 -OpSelectionMerge %247 None -OpBranchConditional %246 %248 %247 -%248 = OpLabel -OpImageWrite %242 %238 %239 -OpBranch %247 -%247 = OpLabel +%238 = OpImageQuerySize %12 %231 +%239 = OpULessThan %82 %228 %238 +%240 = OpAll %58 %239 +OpBranchConditional %240 %241 %236 +%241 = OpLabel +%242 = OpImageFetch %10 %231 %228 Sample %229 +OpBranch %236 +%236 = OpLabel +%243 = OpPhi %10 %233 %232 %233 %237 %242 %241 +%244 = OpCompositeExtract %8 %243 0 +OpReturnValue %244 +OpFunctionEnd +%248 = OpFunction %2 None %249 +%246 = OpFunctionParameter %4 +%247 = OpFunctionParameter %10 +%245 = OpLabel +%250 = OpLoad %20 %43 +OpBranch %251 +%251 = OpLabel +%252 = OpImageQuerySize %4 %250 +%253 = OpULessThan %58 %246 %252 +OpSelectionMerge %254 None +OpBranchConditional %253 %255 %254 +%255 = OpLabel +OpImageWrite %250 %246 %247 +OpBranch %254 +%254 = OpLabel OpReturn OpFunctionEnd -%252 = OpFunction %2 None %253 -%249 = OpLabel -%254 = OpLoad %7 %25 -%255 = OpLoad %9 %27 -%256 = OpLoad %11 %29 -%257 = OpLoad %12 %31 -%258 = OpLoad %14 %33 -%259 = OpLoad %18 %41 -%260 = OpLoad %19 %43 -%261 = OpLoad %20 %45 -%262 = OpLoad %21 %47 -OpBranch %263 -%263 = OpLabel -%264 = OpFunctionCall %8 %52 %3 %3 -%265 = OpFunctionCall %8 %70 %22 %3 -%266 = OpFunctionCall %8 %90 %22 %3 %3 -%267 = OpFunctionCall %8 %110 %23 %3 -%268 = OpFunctionCall %8 %128 %22 %3 -%269 = OpFunctionCall %2 %203 %3 %24 -%270 = OpFunctionCall %2 %214 %22 %24 -%271 = OpFunctionCall %2 %227 %22 %3 %24 -%272 = OpFunctionCall %2 %240 %23 %24 -%273 = OpCompositeConstruct %8 %5 %5 %5 %5 -OpStore %250 %273 +%259 = OpFunction %2 None %260 +%257 = OpFunctionParameter %12 +%258 = OpFunctionParameter %10 +%256 = OpLabel +%261 = OpLoad %21 %45 +OpBranch %262 +%262 = OpLabel +%263 = OpImageQuerySize %12 %261 +%264 = OpULessThan %82 %257 %263 +%265 = OpAll %58 %264 +OpSelectionMerge %266 None +OpBranchConditional %265 %267 %266 +%267 = OpLabel +OpImageWrite %261 %257 %258 +OpBranch %266 +%266 = OpLabel +OpReturn +OpFunctionEnd +%272 = OpFunction %2 None %273 +%269 = OpFunctionParameter %12 +%270 = OpFunctionParameter %6 +%271 = OpFunctionParameter %10 +%268 = OpLabel +%274 = OpLoad %22 %47 +OpBranch %275 +%275 = OpLabel +%276 = OpBitcast %4 %270 +%277 = OpCompositeConstruct %15 %269 %276 +%278 = OpImageQuerySize %15 %274 +%279 = OpULessThan %104 %277 %278 +%280 = OpAll %58 %279 +OpSelectionMerge %281 None +OpBranchConditional %280 %282 %281 +%282 = OpLabel +OpImageWrite %274 %277 %271 +OpBranch %281 +%281 = OpLabel +OpReturn +OpFunctionEnd +%287 = OpFunction %2 None %288 +%284 = OpFunctionParameter %12 +%285 = OpFunctionParameter %4 +%286 = OpFunctionParameter %10 +%283 = OpLabel +%289 = OpLoad %22 %47 +OpBranch %290 +%290 = OpLabel +%291 = OpCompositeConstruct %15 %284 %285 +%292 = OpImageQuerySize %15 %289 +%293 = OpULessThan %104 %291 %292 +%294 = OpAll %58 %293 +OpSelectionMerge %295 None +OpBranchConditional %294 %296 %295 +%296 = OpLabel +OpImageWrite %289 %291 %286 +OpBranch %295 +%295 = OpLabel +OpReturn +OpFunctionEnd +%300 = OpFunction %2 None %301 +%298 = OpFunctionParameter %15 +%299 = OpFunctionParameter %10 +%297 = OpLabel +%302 = OpLoad %23 %49 +OpBranch %303 +%303 = OpLabel +%304 = OpImageQuerySize %15 %302 +%305 = OpULessThan %104 %298 %304 +%306 = OpAll %58 %305 +OpSelectionMerge %307 None +OpBranchConditional %306 %308 %307 +%308 = OpLabel +OpImageWrite %302 %298 %299 +OpBranch %307 +%307 = OpLabel +OpReturn +OpFunctionEnd +%312 = OpFunction %2 None %313 +%309 = OpLabel +%314 = OpLoad %9 %27 +%315 = OpLoad %11 %29 +%316 = OpLoad %13 %31 +%317 = OpLoad %14 %33 +%318 = OpLoad %16 %35 +%319 = OpLoad %20 %43 +%320 = OpLoad %21 %45 +%321 = OpLoad %22 %47 +%322 = OpLoad %23 %49 +OpBranch %323 +%323 = OpLabel +%324 = OpFunctionCall %10 %54 %3 %3 +%325 = OpFunctionCall %10 %72 %24 %3 +%326 = OpFunctionCall %10 %92 %24 %5 %3 +%327 = OpFunctionCall %10 %114 %24 %3 %3 +%328 = OpFunctionCall %10 %133 %25 %3 +%329 = OpFunctionCall %10 %151 %24 %3 +%330 = OpFunctionCall %2 %248 %3 %26 +%331 = OpFunctionCall %2 %259 %24 %26 +%332 = OpFunctionCall %2 %272 %24 %5 %26 +%333 = OpFunctionCall %2 %287 %24 %3 %26 +%334 = OpFunctionCall %2 %300 %25 %26 +%335 = OpCompositeConstruct %10 %7 %7 %7 %7 +OpStore %310 %335 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 7efb4483e..040ded2af 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 376 +; Bound: 546 OpCapability SampledCubeArray OpCapability ImageQuery OpCapability Image1D @@ -9,105 +9,110 @@ OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %84 "main" %81 -OpEntryPoint GLCompute %158 "depth_load" %156 -OpEntryPoint Vertex %180 "queries" %178 -OpEntryPoint Vertex %245 "levels_queries" %244 -OpEntryPoint Fragment %282 "texture_sample" %281 -OpEntryPoint Fragment %310 "texture_sample_comparison" %308 -OpEntryPoint Fragment %329 "gather" %328 -OpEntryPoint Fragment %364 "depth_no_comparison" %363 -OpExecutionMode %84 LocalSize 16 1 1 -OpExecutionMode %158 LocalSize 16 1 1 -OpExecutionMode %282 OriginUpperLeft -OpExecutionMode %310 OriginUpperLeft -OpExecutionMode %329 OriginUpperLeft -OpExecutionMode %364 OriginUpperLeft +OpEntryPoint GLCompute %89 "main" %86 +OpEntryPoint GLCompute %177 "depth_load" %175 +OpEntryPoint Vertex %199 "queries" %197 +OpEntryPoint Vertex %263 "levels_queries" %262 +OpEntryPoint Fragment %303 "texture_sample" %302 +OpEntryPoint Fragment %444 "texture_sample_comparison" %442 +OpEntryPoint Fragment %499 "gather" %498 +OpEntryPoint Fragment %534 "depth_no_comparison" %533 +OpExecutionMode %89 LocalSize 16 1 1 +OpExecutionMode %177 LocalSize 16 1 1 +OpExecutionMode %303 OriginUpperLeft +OpExecutionMode %444 OriginUpperLeft +OpExecutionMode %499 OriginUpperLeft +OpExecutionMode %534 OriginUpperLeft OpSource GLSL 450 -OpName %39 "image_mipmapped_src" -OpName %41 "image_multisampled_src" -OpName %43 "image_depth_multisampled_src" -OpName %45 "image_storage_src" -OpName %47 "image_array_src" -OpName %49 "image_dup_src" -OpName %51 "image_1d_src" -OpName %53 "image_dst" -OpName %55 "image_1d" -OpName %57 "image_2d" -OpName %59 "image_2d_u32" -OpName %60 "image_2d_i32" -OpName %62 "image_2d_array" -OpName %64 "image_cube" -OpName %66 "image_cube_array" -OpName %68 "image_3d" -OpName %70 "image_aa" -OpName %72 "sampler_reg" -OpName %74 "sampler_cmp" -OpName %76 "image_2d_depth" -OpName %78 "image_cube_depth" -OpName %81 "local_id" -OpName %84 "main" -OpName %156 "local_id" -OpName %158 "depth_load" -OpName %180 "queries" -OpName %245 "levels_queries" -OpName %282 "texture_sample" -OpName %310 "texture_sample_comparison" -OpName %329 "gather" -OpName %364 "depth_no_comparison" -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 0 -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 3 -OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 4 -OpDecorate %45 NonWritable -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 1 -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 5 -OpDecorate %49 NonWritable -OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 6 -OpDecorate %51 DescriptorSet 0 -OpDecorate %51 Binding 7 -OpDecorate %53 NonReadable -OpDecorate %53 DescriptorSet 0 -OpDecorate %53 Binding 2 -OpDecorate %55 DescriptorSet 0 -OpDecorate %55 Binding 0 -OpDecorate %57 DescriptorSet 0 -OpDecorate %57 Binding 1 -OpDecorate %59 DescriptorSet 0 -OpDecorate %59 Binding 2 +OpName %42 "image_mipmapped_src" +OpName %44 "image_multisampled_src" +OpName %46 "image_depth_multisampled_src" +OpName %48 "image_storage_src" +OpName %50 "image_array_src" +OpName %52 "image_dup_src" +OpName %54 "image_1d_src" +OpName %56 "image_dst" +OpName %58 "image_1d" +OpName %60 "image_2d" +OpName %62 "image_2d_u32" +OpName %63 "image_2d_i32" +OpName %65 "image_2d_array" +OpName %67 "image_cube" +OpName %69 "image_cube_array" +OpName %71 "image_3d" +OpName %73 "image_aa" +OpName %75 "sampler_reg" +OpName %77 "sampler_cmp" +OpName %79 "image_2d_depth" +OpName %81 "image_2d_array_depth" +OpName %83 "image_cube_depth" +OpName %86 "local_id" +OpName %89 "main" +OpName %175 "local_id" +OpName %177 "depth_load" +OpName %199 "queries" +OpName %263 "levels_queries" +OpName %298 "a" +OpName %303 "texture_sample" +OpName %438 "a" +OpName %444 "texture_sample_comparison" +OpName %499 "gather" +OpName %534 "depth_no_comparison" +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 0 +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 3 +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 4 +OpDecorate %48 NonWritable +OpDecorate %48 DescriptorSet 0 +OpDecorate %48 Binding 1 +OpDecorate %50 DescriptorSet 0 +OpDecorate %50 Binding 5 +OpDecorate %52 NonWritable +OpDecorate %52 DescriptorSet 0 +OpDecorate %52 Binding 6 +OpDecorate %54 DescriptorSet 0 +OpDecorate %54 Binding 7 +OpDecorate %56 NonReadable +OpDecorate %56 DescriptorSet 0 +OpDecorate %56 Binding 2 +OpDecorate %58 DescriptorSet 0 +OpDecorate %58 Binding 0 OpDecorate %60 DescriptorSet 0 -OpDecorate %60 Binding 3 +OpDecorate %60 Binding 1 OpDecorate %62 DescriptorSet 0 -OpDecorate %62 Binding 4 -OpDecorate %64 DescriptorSet 0 -OpDecorate %64 Binding 5 -OpDecorate %66 DescriptorSet 0 -OpDecorate %66 Binding 6 -OpDecorate %68 DescriptorSet 0 -OpDecorate %68 Binding 7 -OpDecorate %70 DescriptorSet 0 -OpDecorate %70 Binding 8 -OpDecorate %72 DescriptorSet 1 -OpDecorate %72 Binding 0 -OpDecorate %74 DescriptorSet 1 -OpDecorate %74 Binding 1 -OpDecorate %76 DescriptorSet 1 -OpDecorate %76 Binding 2 -OpDecorate %78 DescriptorSet 1 -OpDecorate %78 Binding 3 -OpDecorate %81 BuiltIn LocalInvocationId -OpDecorate %156 BuiltIn LocalInvocationId -OpDecorate %178 BuiltIn Position -OpDecorate %244 BuiltIn Position -OpDecorate %281 Location 0 -OpDecorate %308 Location 0 -OpDecorate %328 Location 0 -OpDecorate %363 Location 0 +OpDecorate %62 Binding 2 +OpDecorate %63 DescriptorSet 0 +OpDecorate %63 Binding 3 +OpDecorate %65 DescriptorSet 0 +OpDecorate %65 Binding 4 +OpDecorate %67 DescriptorSet 0 +OpDecorate %67 Binding 5 +OpDecorate %69 DescriptorSet 0 +OpDecorate %69 Binding 6 +OpDecorate %71 DescriptorSet 0 +OpDecorate %71 Binding 7 +OpDecorate %73 DescriptorSet 0 +OpDecorate %73 Binding 8 +OpDecorate %75 DescriptorSet 1 +OpDecorate %75 Binding 0 +OpDecorate %77 DescriptorSet 1 +OpDecorate %77 Binding 1 +OpDecorate %79 DescriptorSet 1 +OpDecorate %79 Binding 2 +OpDecorate %81 DescriptorSet 1 +OpDecorate %81 Binding 3 +OpDecorate %83 DescriptorSet 1 +OpDecorate %83 Binding 4 +OpDecorate %86 BuiltIn LocalInvocationId +OpDecorate %175 BuiltIn LocalInvocationId +OpDecorate %197 BuiltIn Position +OpDecorate %262 BuiltIn Position +OpDecorate %302 Location 0 +OpDecorate %442 Location 0 +OpDecorate %498 Location 0 +OpDecorate %533 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -119,398 +124,598 @@ OpDecorate %363 Location 0 %10 = OpConstant %4 3 %11 = OpConstant %8 2.0 %13 = OpTypeInt 32 0 -%12 = OpTypeImage %13 2D 0 0 0 1 Unknown -%14 = OpTypeImage %13 2D 0 0 1 1 Unknown -%15 = OpTypeImage %8 2D 1 0 1 1 Unknown -%16 = OpTypeImage %13 2D 0 0 0 2 Rgba8ui -%17 = OpTypeImage %13 2D 0 1 0 1 Unknown -%18 = OpTypeImage %13 1D 0 0 0 2 R32ui -%19 = OpTypeImage %13 1D 0 0 0 1 Unknown -%20 = OpTypeVector %13 3 -%21 = OpTypeVector %4 2 -%22 = OpTypeVector %13 2 -%23 = OpTypeVector %13 4 -%24 = OpTypeImage %8 1D 0 0 0 1 Unknown -%25 = OpTypeImage %8 2D 0 0 0 1 Unknown -%26 = OpTypeImage %4 2D 0 0 0 1 Unknown -%27 = OpTypeImage %8 2D 0 1 0 1 Unknown -%28 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%29 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%30 = OpTypeImage %8 3D 0 0 0 1 Unknown -%31 = OpTypeImage %8 2D 0 0 1 1 Unknown -%32 = OpTypeVector %8 4 -%33 = OpTypeSampler -%34 = OpTypeVector %8 2 -%35 = OpTypeImage %8 2D 1 0 0 1 Unknown -%36 = OpTypeImage %8 Cube 1 0 0 1 Unknown +%12 = OpConstant %13 0 +%14 = OpConstant %4 0 +%15 = OpTypeImage %13 2D 0 0 0 1 Unknown +%16 = OpTypeImage %13 2D 0 0 1 1 Unknown +%17 = OpTypeImage %8 2D 1 0 1 1 Unknown +%18 = OpTypeImage %13 2D 0 0 0 2 Rgba8ui +%19 = OpTypeImage %13 2D 0 1 0 1 Unknown +%20 = OpTypeImage %13 1D 0 0 0 2 R32ui +%21 = OpTypeImage %13 1D 0 0 0 1 Unknown +%22 = OpTypeVector %13 3 +%23 = OpTypeVector %4 2 +%24 = OpTypeVector %13 2 +%25 = OpTypeVector %13 4 +%26 = OpTypeImage %8 1D 0 0 0 1 Unknown +%27 = OpTypeImage %8 2D 0 0 0 1 Unknown +%28 = OpTypeImage %4 2D 0 0 0 1 Unknown +%29 = OpTypeImage %8 2D 0 1 0 1 Unknown +%30 = OpTypeImage %8 Cube 0 0 0 1 Unknown +%31 = OpTypeImage %8 Cube 0 1 0 1 Unknown +%32 = OpTypeImage %8 3D 0 0 0 1 Unknown +%33 = OpTypeImage %8 2D 0 0 1 1 Unknown +%34 = OpTypeVector %8 4 +%35 = OpTypeSampler +%36 = OpTypeVector %8 2 %37 = OpTypeVector %8 3 -%38 = OpConstantComposite %21 %10 %6 -%40 = OpTypePointer UniformConstant %12 -%39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %14 -%41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %15 -%43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %16 -%45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %17 -%47 = OpVariable %48 UniformConstant -%50 = OpTypePointer UniformConstant %18 -%49 = OpVariable %50 UniformConstant -%52 = OpTypePointer UniformConstant %19 -%51 = OpVariable %52 UniformConstant -%54 = OpTypePointer UniformConstant %18 -%53 = OpVariable %54 UniformConstant -%56 = OpTypePointer UniformConstant %24 -%55 = OpVariable %56 UniformConstant -%58 = OpTypePointer UniformConstant %25 -%57 = OpVariable %58 UniformConstant -%59 = OpVariable %40 UniformConstant -%61 = OpTypePointer UniformConstant %26 +%38 = OpTypeImage %8 2D 1 0 0 1 Unknown +%39 = OpTypeImage %8 2D 1 1 0 1 Unknown +%40 = OpTypeImage %8 Cube 1 0 0 1 Unknown +%41 = OpConstantComposite %23 %10 %6 +%43 = OpTypePointer UniformConstant %15 +%42 = OpVariable %43 UniformConstant +%45 = OpTypePointer UniformConstant %16 +%44 = OpVariable %45 UniformConstant +%47 = OpTypePointer UniformConstant %17 +%46 = OpVariable %47 UniformConstant +%49 = OpTypePointer UniformConstant %18 +%48 = OpVariable %49 UniformConstant +%51 = OpTypePointer UniformConstant %19 +%50 = OpVariable %51 UniformConstant +%53 = OpTypePointer UniformConstant %20 +%52 = OpVariable %53 UniformConstant +%55 = OpTypePointer UniformConstant %21 +%54 = OpVariable %55 UniformConstant +%57 = OpTypePointer UniformConstant %20 +%56 = OpVariable %57 UniformConstant +%59 = OpTypePointer UniformConstant %26 +%58 = OpVariable %59 UniformConstant +%61 = OpTypePointer UniformConstant %27 %60 = OpVariable %61 UniformConstant -%63 = OpTypePointer UniformConstant %27 -%62 = OpVariable %63 UniformConstant -%65 = OpTypePointer UniformConstant %28 -%64 = OpVariable %65 UniformConstant -%67 = OpTypePointer UniformConstant %29 -%66 = OpVariable %67 UniformConstant -%69 = OpTypePointer UniformConstant %30 -%68 = OpVariable %69 UniformConstant -%71 = OpTypePointer UniformConstant %31 -%70 = OpVariable %71 UniformConstant -%73 = OpTypePointer UniformConstant %33 -%72 = OpVariable %73 UniformConstant -%75 = OpTypePointer UniformConstant %33 -%74 = OpVariable %75 UniformConstant -%77 = OpTypePointer UniformConstant %35 -%76 = OpVariable %77 UniformConstant -%79 = OpTypePointer UniformConstant %36 -%78 = OpVariable %79 UniformConstant -%82 = OpTypePointer Input %20 -%81 = OpVariable %82 Input -%85 = OpTypeFunction %2 -%112 = OpTypeVector %4 3 -%156 = OpVariable %82 Input -%179 = OpTypePointer Output %32 -%178 = OpVariable %179 Output -%189 = OpConstant %13 0 -%244 = OpVariable %179 Output -%281 = OpVariable %179 Output -%289 = OpTypeSampledImage %24 -%292 = OpTypeSampledImage %25 -%309 = OpTypePointer Output %8 -%308 = OpVariable %309 Output -%316 = OpTypeSampledImage %35 -%321 = OpConstant %8 0.0 -%323 = OpTypeSampledImage %36 -%328 = OpVariable %179 Output -%340 = OpConstant %13 1 -%343 = OpConstant %13 3 -%348 = OpTypeSampledImage %12 -%351 = OpTypeVector %4 4 -%352 = OpTypeSampledImage %26 -%363 = OpVariable %179 Output -%84 = OpFunction %2 None %85 -%80 = OpLabel -%83 = OpLoad %20 %81 -%86 = OpLoad %12 %39 -%87 = OpLoad %14 %41 -%88 = OpLoad %16 %45 -%89 = OpLoad %17 %47 -%90 = OpLoad %19 %51 -%91 = OpLoad %18 %53 -OpBranch %92 -%92 = OpLabel -%93 = OpImageQuerySize %21 %88 -%94 = OpBitcast %22 %93 -%95 = OpVectorShuffle %22 %83 %83 0 1 -%96 = OpIMul %22 %94 %95 -%97 = OpBitcast %21 %96 -%98 = OpCompositeConstruct %21 %3 %5 -%99 = OpSRem %21 %97 %98 -%100 = OpCompositeExtract %13 %83 2 -%101 = OpBitcast %4 %100 -%102 = OpImageFetch %23 %86 %99 Lod %101 -%103 = OpCompositeExtract %13 %83 2 -%104 = OpBitcast %4 %103 -%105 = OpImageFetch %23 %87 %99 Sample %104 -%106 = OpImageRead %23 %88 %99 -%107 = OpCompositeExtract %13 %83 2 -%108 = OpBitcast %4 %107 -%109 = OpCompositeExtract %13 %83 2 -%110 = OpBitcast %4 %109 -%111 = OpIAdd %4 %110 %6 -%113 = OpCompositeConstruct %112 %99 %108 -%114 = OpImageFetch %23 %89 %113 Lod %111 -%115 = OpCompositeExtract %13 %83 0 -%116 = OpBitcast %4 %115 -%117 = OpCompositeExtract %13 %83 2 -%118 = OpBitcast %4 %117 -%119 = OpImageFetch %23 %90 %116 Lod %118 -%120 = OpBitcast %22 %99 -%121 = OpCompositeExtract %13 %83 2 -%122 = OpBitcast %4 %121 -%123 = OpImageFetch %23 %86 %120 Lod %122 -%124 = OpBitcast %22 %99 -%125 = OpCompositeExtract %13 %83 2 -%126 = OpBitcast %4 %125 -%127 = OpImageFetch %23 %87 %124 Sample %126 -%128 = OpBitcast %22 %99 -%129 = OpImageRead %23 %88 %128 -%130 = OpBitcast %22 %99 -%131 = OpCompositeExtract %13 %83 2 -%132 = OpBitcast %4 %131 -%133 = OpCompositeExtract %13 %83 2 +%62 = OpVariable %43 UniformConstant +%64 = OpTypePointer UniformConstant %28 +%63 = OpVariable %64 UniformConstant +%66 = OpTypePointer UniformConstant %29 +%65 = OpVariable %66 UniformConstant +%68 = OpTypePointer UniformConstant %30 +%67 = OpVariable %68 UniformConstant +%70 = OpTypePointer UniformConstant %31 +%69 = OpVariable %70 UniformConstant +%72 = OpTypePointer UniformConstant %32 +%71 = OpVariable %72 UniformConstant +%74 = OpTypePointer UniformConstant %33 +%73 = OpVariable %74 UniformConstant +%76 = OpTypePointer UniformConstant %35 +%75 = OpVariable %76 UniformConstant +%78 = OpTypePointer UniformConstant %35 +%77 = OpVariable %78 UniformConstant +%80 = OpTypePointer UniformConstant %38 +%79 = OpVariable %80 UniformConstant +%82 = OpTypePointer UniformConstant %39 +%81 = OpVariable %82 UniformConstant +%84 = OpTypePointer UniformConstant %40 +%83 = OpVariable %84 UniformConstant +%87 = OpTypePointer Input %22 +%86 = OpVariable %87 Input +%90 = OpTypeFunction %2 +%117 = OpTypeVector %4 3 +%175 = OpVariable %87 Input +%198 = OpTypePointer Output %34 +%197 = OpVariable %198 Output +%262 = OpVariable %198 Output +%299 = OpTypePointer Function %34 +%300 = OpConstantNull %34 +%302 = OpVariable %198 Output +%313 = OpTypeSampledImage %26 +%318 = OpTypeSampledImage %27 +%339 = OpTypeSampledImage %29 +%400 = OpTypeSampledImage %31 +%439 = OpTypePointer Function %8 +%440 = OpConstantNull %8 +%443 = OpTypePointer Output %8 +%442 = OpVariable %443 Output +%452 = OpTypeSampledImage %38 +%457 = OpTypeSampledImage %39 +%470 = OpTypeSampledImage %40 +%477 = OpConstant %8 0.0 +%498 = OpVariable %198 Output +%510 = OpConstant %13 1 +%513 = OpConstant %13 3 +%518 = OpTypeSampledImage %15 +%521 = OpTypeVector %4 4 +%522 = OpTypeSampledImage %28 +%533 = OpVariable %198 Output +%89 = OpFunction %2 None %90 +%85 = OpLabel +%88 = OpLoad %22 %86 +%91 = OpLoad %15 %42 +%92 = OpLoad %16 %44 +%93 = OpLoad %18 %48 +%94 = OpLoad %19 %50 +%95 = OpLoad %21 %54 +%96 = OpLoad %20 %56 +OpBranch %97 +%97 = OpLabel +%98 = OpImageQuerySize %23 %93 +%99 = OpBitcast %24 %98 +%100 = OpVectorShuffle %24 %88 %88 0 1 +%101 = OpIMul %24 %99 %100 +%102 = OpBitcast %23 %101 +%103 = OpCompositeConstruct %23 %3 %5 +%104 = OpSRem %23 %102 %103 +%105 = OpCompositeExtract %13 %88 2 +%106 = OpBitcast %4 %105 +%107 = OpImageFetch %25 %91 %104 Lod %106 +%108 = OpCompositeExtract %13 %88 2 +%109 = OpBitcast %4 %108 +%110 = OpImageFetch %25 %92 %104 Sample %109 +%111 = OpImageRead %25 %93 %104 +%112 = OpCompositeExtract %13 %88 2 +%113 = OpCompositeExtract %13 %88 2 +%114 = OpBitcast %4 %113 +%115 = OpIAdd %4 %114 %6 +%116 = OpBitcast %4 %112 +%118 = OpCompositeConstruct %117 %104 %116 +%119 = OpImageFetch %25 %94 %118 Lod %115 +%120 = OpCompositeExtract %13 %88 2 +%121 = OpBitcast %4 %120 +%122 = OpCompositeExtract %13 %88 2 +%123 = OpBitcast %4 %122 +%124 = OpIAdd %4 %123 %6 +%125 = OpCompositeConstruct %117 %104 %121 +%126 = OpImageFetch %25 %94 %125 Lod %124 +%127 = OpCompositeExtract %13 %88 0 +%128 = OpBitcast %4 %127 +%129 = OpCompositeExtract %13 %88 2 +%130 = OpBitcast %4 %129 +%131 = OpImageFetch %25 %95 %128 Lod %130 +%132 = OpBitcast %24 %104 +%133 = OpCompositeExtract %13 %88 2 %134 = OpBitcast %4 %133 -%135 = OpIAdd %4 %134 %6 -%136 = OpBitcast %13 %132 -%137 = OpCompositeConstruct %20 %130 %136 -%138 = OpImageFetch %23 %89 %137 Lod %135 -%139 = OpCompositeExtract %13 %83 0 -%141 = OpCompositeExtract %13 %83 2 -%142 = OpBitcast %4 %141 -%143 = OpImageFetch %23 %90 %139 Lod %142 -%144 = OpCompositeExtract %4 %99 0 -%145 = OpIAdd %23 %102 %105 -%146 = OpIAdd %23 %145 %106 -%147 = OpIAdd %23 %146 %114 -%148 = OpIAdd %23 %147 %119 -OpImageWrite %91 %144 %148 -%149 = OpCompositeExtract %4 %99 0 -%150 = OpBitcast %13 %149 -%151 = OpIAdd %23 %123 %127 -%152 = OpIAdd %23 %151 %129 -%153 = OpIAdd %23 %152 %138 -%154 = OpIAdd %23 %153 %143 -OpImageWrite %91 %150 %154 +%135 = OpImageFetch %25 %91 %132 Lod %134 +%136 = OpBitcast %24 %104 +%137 = OpCompositeExtract %13 %88 2 +%138 = OpBitcast %4 %137 +%139 = OpImageFetch %25 %92 %136 Sample %138 +%140 = OpBitcast %24 %104 +%141 = OpImageRead %25 %93 %140 +%142 = OpBitcast %24 %104 +%143 = OpCompositeExtract %13 %88 2 +%144 = OpCompositeExtract %13 %88 2 +%145 = OpBitcast %4 %144 +%146 = OpIAdd %4 %145 %6 +%147 = OpCompositeConstruct %22 %142 %143 +%148 = OpImageFetch %25 %94 %147 Lod %146 +%149 = OpBitcast %24 %104 +%150 = OpCompositeExtract %13 %88 2 +%151 = OpBitcast %4 %150 +%152 = OpCompositeExtract %13 %88 2 +%153 = OpBitcast %4 %152 +%154 = OpIAdd %4 %153 %6 +%155 = OpBitcast %13 %151 +%156 = OpCompositeConstruct %22 %149 %155 +%157 = OpImageFetch %25 %94 %156 Lod %154 +%158 = OpCompositeExtract %13 %88 0 +%160 = OpCompositeExtract %13 %88 2 +%161 = OpBitcast %4 %160 +%162 = OpImageFetch %25 %95 %158 Lod %161 +%163 = OpCompositeExtract %4 %104 0 +%164 = OpIAdd %25 %107 %110 +%165 = OpIAdd %25 %164 %111 +%166 = OpIAdd %25 %165 %119 +%167 = OpIAdd %25 %166 %126 +OpImageWrite %96 %163 %167 +%168 = OpCompositeExtract %4 %104 0 +%169 = OpBitcast %13 %168 +%170 = OpIAdd %25 %135 %139 +%171 = OpIAdd %25 %170 %141 +%172 = OpIAdd %25 %171 %148 +%173 = OpIAdd %25 %172 %157 +OpImageWrite %96 %169 %173 OpReturn OpFunctionEnd -%158 = OpFunction %2 None %85 -%155 = OpLabel -%157 = OpLoad %20 %156 -%159 = OpLoad %15 %43 -%160 = OpLoad %16 %45 -%161 = OpLoad %18 %53 -OpBranch %162 -%162 = OpLabel -%163 = OpImageQuerySize %21 %160 -%164 = OpBitcast %22 %163 -%165 = OpVectorShuffle %22 %157 %157 0 1 -%166 = OpIMul %22 %164 %165 -%167 = OpBitcast %21 %166 -%168 = OpCompositeConstruct %21 %3 %5 -%169 = OpSRem %21 %167 %168 -%170 = OpCompositeExtract %13 %157 2 -%171 = OpBitcast %4 %170 -%172 = OpImageFetch %32 %159 %169 Sample %171 -%173 = OpCompositeExtract %8 %172 0 -%174 = OpCompositeExtract %4 %169 0 -%175 = OpConvertFToU %13 %173 -%176 = OpCompositeConstruct %23 %175 %175 %175 %175 -OpImageWrite %161 %174 %176 +%177 = OpFunction %2 None %90 +%174 = OpLabel +%176 = OpLoad %22 %175 +%178 = OpLoad %17 %46 +%179 = OpLoad %18 %48 +%180 = OpLoad %20 %56 +OpBranch %181 +%181 = OpLabel +%182 = OpImageQuerySize %23 %179 +%183 = OpBitcast %24 %182 +%184 = OpVectorShuffle %24 %176 %176 0 1 +%185 = OpIMul %24 %183 %184 +%186 = OpBitcast %23 %185 +%187 = OpCompositeConstruct %23 %3 %5 +%188 = OpSRem %23 %186 %187 +%189 = OpCompositeExtract %13 %176 2 +%190 = OpBitcast %4 %189 +%191 = OpImageFetch %34 %178 %188 Sample %190 +%192 = OpCompositeExtract %8 %191 0 +%193 = OpCompositeExtract %4 %188 0 +%194 = OpConvertFToU %13 %192 +%195 = OpCompositeConstruct %25 %194 %194 %194 %194 +OpImageWrite %180 %193 %195 OpReturn OpFunctionEnd -%180 = OpFunction %2 None %85 -%177 = OpLabel -%181 = OpLoad %24 %55 -%182 = OpLoad %25 %57 -%183 = OpLoad %27 %62 -%184 = OpLoad %28 %64 -%185 = OpLoad %29 %66 -%186 = OpLoad %30 %68 -%187 = OpLoad %31 %70 -OpBranch %188 -%188 = OpLabel -%190 = OpImageQuerySizeLod %4 %181 %189 -%191 = OpBitcast %13 %190 -%192 = OpBitcast %4 %191 -%193 = OpImageQuerySizeLod %4 %181 %192 -%194 = OpBitcast %13 %193 -%195 = OpImageQuerySizeLod %21 %182 %189 -%196 = OpBitcast %22 %195 -%197 = OpImageQuerySizeLod %21 %182 %6 -%198 = OpBitcast %22 %197 -%199 = OpImageQuerySizeLod %112 %183 %189 -%200 = OpBitcast %20 %199 -%201 = OpVectorShuffle %22 %200 %200 0 1 -%202 = OpImageQuerySizeLod %112 %183 %6 -%203 = OpBitcast %20 %202 -%204 = OpVectorShuffle %22 %203 %203 0 1 -%205 = OpImageQuerySizeLod %21 %184 %189 -%206 = OpBitcast %22 %205 -%207 = OpImageQuerySizeLod %21 %184 %6 -%208 = OpBitcast %22 %207 -%209 = OpImageQuerySizeLod %112 %185 %189 -%210 = OpBitcast %20 %209 -%211 = OpVectorShuffle %22 %210 %210 0 0 -%212 = OpImageQuerySizeLod %112 %185 %6 -%213 = OpBitcast %20 %212 -%214 = OpVectorShuffle %22 %213 %213 0 0 -%215 = OpImageQuerySizeLod %112 %186 %189 -%216 = OpBitcast %20 %215 -%217 = OpImageQuerySizeLod %112 %186 %6 -%218 = OpBitcast %20 %217 -%219 = OpImageQuerySize %21 %187 -%220 = OpBitcast %22 %219 -%221 = OpCompositeExtract %13 %196 1 -%222 = OpIAdd %13 %191 %221 -%223 = OpCompositeExtract %13 %198 1 -%224 = OpIAdd %13 %222 %223 -%225 = OpCompositeExtract %13 %201 1 -%226 = OpIAdd %13 %224 %225 -%227 = OpCompositeExtract %13 %204 1 -%228 = OpIAdd %13 %226 %227 -%229 = OpCompositeExtract %13 %206 1 -%230 = OpIAdd %13 %228 %229 -%231 = OpCompositeExtract %13 %208 1 -%232 = OpIAdd %13 %230 %231 -%233 = OpCompositeExtract %13 %211 1 -%234 = OpIAdd %13 %232 %233 -%235 = OpCompositeExtract %13 %214 1 -%236 = OpIAdd %13 %234 %235 -%237 = OpCompositeExtract %13 %216 2 -%238 = OpIAdd %13 %236 %237 -%239 = OpCompositeExtract %13 %218 2 -%240 = OpIAdd %13 %238 %239 -%241 = OpConvertUToF %8 %240 -%242 = OpCompositeConstruct %32 %241 %241 %241 %241 -OpStore %178 %242 +%199 = OpFunction %2 None %90 +%196 = OpLabel +%200 = OpLoad %26 %58 +%201 = OpLoad %27 %60 +%202 = OpLoad %29 %65 +%203 = OpLoad %30 %67 +%204 = OpLoad %31 %69 +%205 = OpLoad %32 %71 +%206 = OpLoad %33 %73 +OpBranch %207 +%207 = OpLabel +%208 = OpImageQuerySizeLod %4 %200 %12 +%209 = OpBitcast %13 %208 +%210 = OpBitcast %4 %209 +%211 = OpImageQuerySizeLod %4 %200 %210 +%212 = OpBitcast %13 %211 +%213 = OpImageQuerySizeLod %23 %201 %12 +%214 = OpBitcast %24 %213 +%215 = OpImageQuerySizeLod %23 %201 %6 +%216 = OpBitcast %24 %215 +%217 = OpImageQuerySizeLod %117 %202 %12 +%218 = OpBitcast %22 %217 +%219 = OpVectorShuffle %24 %218 %218 0 1 +%220 = OpImageQuerySizeLod %117 %202 %6 +%221 = OpBitcast %22 %220 +%222 = OpVectorShuffle %24 %221 %221 0 1 +%223 = OpImageQuerySizeLod %23 %203 %12 +%224 = OpBitcast %24 %223 +%225 = OpImageQuerySizeLod %23 %203 %6 +%226 = OpBitcast %24 %225 +%227 = OpImageQuerySizeLod %117 %204 %12 +%228 = OpBitcast %22 %227 +%229 = OpVectorShuffle %24 %228 %228 0 0 +%230 = OpImageQuerySizeLod %117 %204 %6 +%231 = OpBitcast %22 %230 +%232 = OpVectorShuffle %24 %231 %231 0 0 +%233 = OpImageQuerySizeLod %117 %205 %12 +%234 = OpBitcast %22 %233 +%235 = OpImageQuerySizeLod %117 %205 %6 +%236 = OpBitcast %22 %235 +%237 = OpImageQuerySize %23 %206 +%238 = OpBitcast %24 %237 +%239 = OpCompositeExtract %13 %214 1 +%240 = OpIAdd %13 %209 %239 +%241 = OpCompositeExtract %13 %216 1 +%242 = OpIAdd %13 %240 %241 +%243 = OpCompositeExtract %13 %219 1 +%244 = OpIAdd %13 %242 %243 +%245 = OpCompositeExtract %13 %222 1 +%246 = OpIAdd %13 %244 %245 +%247 = OpCompositeExtract %13 %224 1 +%248 = OpIAdd %13 %246 %247 +%249 = OpCompositeExtract %13 %226 1 +%250 = OpIAdd %13 %248 %249 +%251 = OpCompositeExtract %13 %229 1 +%252 = OpIAdd %13 %250 %251 +%253 = OpCompositeExtract %13 %232 1 +%254 = OpIAdd %13 %252 %253 +%255 = OpCompositeExtract %13 %234 2 +%256 = OpIAdd %13 %254 %255 +%257 = OpCompositeExtract %13 %236 2 +%258 = OpIAdd %13 %256 %257 +%259 = OpConvertUToF %8 %258 +%260 = OpCompositeConstruct %34 %259 %259 %259 %259 +OpStore %197 %260 OpReturn OpFunctionEnd -%245 = OpFunction %2 None %85 -%243 = OpLabel -%246 = OpLoad %25 %57 -%247 = OpLoad %27 %62 -%248 = OpLoad %28 %64 -%249 = OpLoad %29 %66 -%250 = OpLoad %30 %68 -%251 = OpLoad %31 %70 -OpBranch %252 -%252 = OpLabel -%253 = OpImageQueryLevels %4 %246 -%254 = OpBitcast %13 %253 -%255 = OpImageQueryLevels %4 %247 -%256 = OpBitcast %13 %255 -%257 = OpImageQuerySizeLod %112 %247 %189 -%258 = OpCompositeExtract %4 %257 2 -%259 = OpBitcast %13 %258 -%260 = OpImageQueryLevels %4 %248 -%261 = OpBitcast %13 %260 -%262 = OpImageQueryLevels %4 %249 -%263 = OpBitcast %13 %262 -%264 = OpImageQuerySizeLod %112 %249 %189 -%265 = OpCompositeExtract %4 %264 2 -%266 = OpBitcast %13 %265 -%267 = OpImageQueryLevels %4 %250 -%268 = OpBitcast %13 %267 -%269 = OpImageQuerySamples %4 %251 -%270 = OpBitcast %13 %269 -%271 = OpIAdd %13 %259 %266 -%272 = OpIAdd %13 %271 %270 -%273 = OpIAdd %13 %272 %254 -%274 = OpIAdd %13 %273 %256 -%275 = OpIAdd %13 %274 %268 -%276 = OpIAdd %13 %275 %261 -%277 = OpIAdd %13 %276 %263 -%278 = OpConvertUToF %8 %277 -%279 = OpCompositeConstruct %32 %278 %278 %278 %278 -OpStore %244 %279 +%263 = OpFunction %2 None %90 +%261 = OpLabel +%264 = OpLoad %27 %60 +%265 = OpLoad %29 %65 +%266 = OpLoad %30 %67 +%267 = OpLoad %31 %69 +%268 = OpLoad %32 %71 +%269 = OpLoad %33 %73 +OpBranch %270 +%270 = OpLabel +%271 = OpImageQueryLevels %4 %264 +%272 = OpBitcast %13 %271 +%273 = OpImageQueryLevels %4 %265 +%274 = OpBitcast %13 %273 +%275 = OpImageQuerySizeLod %117 %265 %12 +%276 = OpCompositeExtract %4 %275 2 +%277 = OpBitcast %13 %276 +%278 = OpImageQueryLevels %4 %266 +%279 = OpBitcast %13 %278 +%280 = OpImageQueryLevels %4 %267 +%281 = OpBitcast %13 %280 +%282 = OpImageQuerySizeLod %117 %267 %12 +%283 = OpCompositeExtract %4 %282 2 +%284 = OpBitcast %13 %283 +%285 = OpImageQueryLevels %4 %268 +%286 = OpBitcast %13 %285 +%287 = OpImageQuerySamples %4 %269 +%288 = OpBitcast %13 %287 +%289 = OpIAdd %13 %277 %284 +%290 = OpIAdd %13 %289 %288 +%291 = OpIAdd %13 %290 %272 +%292 = OpIAdd %13 %291 %274 +%293 = OpIAdd %13 %292 %286 +%294 = OpIAdd %13 %293 %279 +%295 = OpIAdd %13 %294 %281 +%296 = OpConvertUToF %8 %295 +%297 = OpCompositeConstruct %34 %296 %296 %296 %296 +OpStore %262 %297 OpReturn OpFunctionEnd -%282 = OpFunction %2 None %85 -%280 = OpLabel -%283 = OpLoad %24 %55 -%284 = OpLoad %25 %57 -%285 = OpLoad %33 %72 -OpBranch %286 -%286 = OpLabel -%287 = OpCompositeConstruct %34 %7 %7 -%288 = OpCompositeExtract %8 %287 0 -%290 = OpSampledImage %289 %283 %285 -%291 = OpImageSampleImplicitLod %32 %290 %288 -%293 = OpSampledImage %292 %284 %285 -%294 = OpImageSampleImplicitLod %32 %293 %287 -%295 = OpSampledImage %292 %284 %285 -%296 = OpImageSampleImplicitLod %32 %295 %287 ConstOffset %38 -%297 = OpSampledImage %292 %284 %285 -%298 = OpImageSampleExplicitLod %32 %297 %287 Lod %9 -%299 = OpSampledImage %292 %284 %285 -%300 = OpImageSampleExplicitLod %32 %299 %287 Lod|ConstOffset %9 %38 -%301 = OpSampledImage %292 %284 %285 -%302 = OpImageSampleImplicitLod %32 %301 %287 Bias|ConstOffset %11 %38 -%303 = OpFAdd %32 %291 %294 -%304 = OpFAdd %32 %303 %296 -%305 = OpFAdd %32 %304 %298 -%306 = OpFAdd %32 %305 %300 -OpStore %281 %306 +%303 = OpFunction %2 None %90 +%301 = OpLabel +%298 = OpVariable %299 Function %300 +%304 = OpLoad %26 %58 +%305 = OpLoad %27 %60 +%306 = OpLoad %29 %65 +%307 = OpLoad %31 %69 +%308 = OpLoad %35 %75 +OpBranch %309 +%309 = OpLabel +%310 = OpCompositeConstruct %36 %7 %7 +%311 = OpCompositeConstruct %37 %7 %7 %7 +%312 = OpCompositeExtract %8 %310 0 +%314 = OpSampledImage %313 %304 %308 +%315 = OpImageSampleImplicitLod %34 %314 %312 +%316 = OpLoad %34 %298 +%317 = OpFAdd %34 %316 %315 +OpStore %298 %317 +%319 = OpSampledImage %318 %305 %308 +%320 = OpImageSampleImplicitLod %34 %319 %310 +%321 = OpLoad %34 %298 +%322 = OpFAdd %34 %321 %320 +OpStore %298 %322 +%323 = OpSampledImage %318 %305 %308 +%324 = OpImageSampleImplicitLod %34 %323 %310 ConstOffset %41 +%325 = OpLoad %34 %298 +%326 = OpFAdd %34 %325 %324 +OpStore %298 %326 +%327 = OpSampledImage %318 %305 %308 +%328 = OpImageSampleExplicitLod %34 %327 %310 Lod %9 +%329 = OpLoad %34 %298 +%330 = OpFAdd %34 %329 %328 +OpStore %298 %330 +%331 = OpSampledImage %318 %305 %308 +%332 = OpImageSampleExplicitLod %34 %331 %310 Lod|ConstOffset %9 %41 +%333 = OpLoad %34 %298 +%334 = OpFAdd %34 %333 %332 +OpStore %298 %334 +%335 = OpSampledImage %318 %305 %308 +%336 = OpImageSampleImplicitLod %34 %335 %310 Bias|ConstOffset %11 %41 +%337 = OpLoad %34 %298 +%338 = OpFAdd %34 %337 %336 +OpStore %298 %338 +%340 = OpConvertUToF %8 %12 +%341 = OpCompositeConstruct %37 %310 %340 +%342 = OpSampledImage %339 %306 %308 +%343 = OpImageSampleImplicitLod %34 %342 %341 +%344 = OpLoad %34 %298 +%345 = OpFAdd %34 %344 %343 +OpStore %298 %345 +%346 = OpConvertUToF %8 %12 +%347 = OpCompositeConstruct %37 %310 %346 +%348 = OpSampledImage %339 %306 %308 +%349 = OpImageSampleImplicitLod %34 %348 %347 ConstOffset %41 +%350 = OpLoad %34 %298 +%351 = OpFAdd %34 %350 %349 +OpStore %298 %351 +%352 = OpConvertUToF %8 %12 +%353 = OpCompositeConstruct %37 %310 %352 +%354 = OpSampledImage %339 %306 %308 +%355 = OpImageSampleExplicitLod %34 %354 %353 Lod %9 +%356 = OpLoad %34 %298 +%357 = OpFAdd %34 %356 %355 +OpStore %298 %357 +%358 = OpConvertUToF %8 %12 +%359 = OpCompositeConstruct %37 %310 %358 +%360 = OpSampledImage %339 %306 %308 +%361 = OpImageSampleExplicitLod %34 %360 %359 Lod|ConstOffset %9 %41 +%362 = OpLoad %34 %298 +%363 = OpFAdd %34 %362 %361 +OpStore %298 %363 +%364 = OpConvertUToF %8 %12 +%365 = OpCompositeConstruct %37 %310 %364 +%366 = OpSampledImage %339 %306 %308 +%367 = OpImageSampleImplicitLod %34 %366 %365 Bias|ConstOffset %11 %41 +%368 = OpLoad %34 %298 +%369 = OpFAdd %34 %368 %367 +OpStore %298 %369 +%370 = OpConvertSToF %8 %14 +%371 = OpCompositeConstruct %37 %310 %370 +%372 = OpSampledImage %339 %306 %308 +%373 = OpImageSampleImplicitLod %34 %372 %371 +%374 = OpLoad %34 %298 +%375 = OpFAdd %34 %374 %373 +OpStore %298 %375 +%376 = OpConvertSToF %8 %14 +%377 = OpCompositeConstruct %37 %310 %376 +%378 = OpSampledImage %339 %306 %308 +%379 = OpImageSampleImplicitLod %34 %378 %377 ConstOffset %41 +%380 = OpLoad %34 %298 +%381 = OpFAdd %34 %380 %379 +OpStore %298 %381 +%382 = OpConvertSToF %8 %14 +%383 = OpCompositeConstruct %37 %310 %382 +%384 = OpSampledImage %339 %306 %308 +%385 = OpImageSampleExplicitLod %34 %384 %383 Lod %9 +%386 = OpLoad %34 %298 +%387 = OpFAdd %34 %386 %385 +OpStore %298 %387 +%388 = OpConvertSToF %8 %14 +%389 = OpCompositeConstruct %37 %310 %388 +%390 = OpSampledImage %339 %306 %308 +%391 = OpImageSampleExplicitLod %34 %390 %389 Lod|ConstOffset %9 %41 +%392 = OpLoad %34 %298 +%393 = OpFAdd %34 %392 %391 +OpStore %298 %393 +%394 = OpConvertSToF %8 %14 +%395 = OpCompositeConstruct %37 %310 %394 +%396 = OpSampledImage %339 %306 %308 +%397 = OpImageSampleImplicitLod %34 %396 %395 Bias|ConstOffset %11 %41 +%398 = OpLoad %34 %298 +%399 = OpFAdd %34 %398 %397 +OpStore %298 %399 +%401 = OpConvertUToF %8 %12 +%402 = OpCompositeConstruct %34 %311 %401 +%403 = OpSampledImage %400 %307 %308 +%404 = OpImageSampleImplicitLod %34 %403 %402 +%405 = OpLoad %34 %298 +%406 = OpFAdd %34 %405 %404 +OpStore %298 %406 +%407 = OpConvertUToF %8 %12 +%408 = OpCompositeConstruct %34 %311 %407 +%409 = OpSampledImage %400 %307 %308 +%410 = OpImageSampleExplicitLod %34 %409 %408 Lod %9 +%411 = OpLoad %34 %298 +%412 = OpFAdd %34 %411 %410 +OpStore %298 %412 +%413 = OpConvertUToF %8 %12 +%414 = OpCompositeConstruct %34 %311 %413 +%415 = OpSampledImage %400 %307 %308 +%416 = OpImageSampleImplicitLod %34 %415 %414 Bias %11 +%417 = OpLoad %34 %298 +%418 = OpFAdd %34 %417 %416 +OpStore %298 %418 +%419 = OpConvertSToF %8 %14 +%420 = OpCompositeConstruct %34 %311 %419 +%421 = OpSampledImage %400 %307 %308 +%422 = OpImageSampleImplicitLod %34 %421 %420 +%423 = OpLoad %34 %298 +%424 = OpFAdd %34 %423 %422 +OpStore %298 %424 +%425 = OpConvertSToF %8 %14 +%426 = OpCompositeConstruct %34 %311 %425 +%427 = OpSampledImage %400 %307 %308 +%428 = OpImageSampleExplicitLod %34 %427 %426 Lod %9 +%429 = OpLoad %34 %298 +%430 = OpFAdd %34 %429 %428 +OpStore %298 %430 +%431 = OpConvertSToF %8 %14 +%432 = OpCompositeConstruct %34 %311 %431 +%433 = OpSampledImage %400 %307 %308 +%434 = OpImageSampleImplicitLod %34 %433 %432 Bias %11 +%435 = OpLoad %34 %298 +%436 = OpFAdd %34 %435 %434 +OpStore %298 %436 +%437 = OpLoad %34 %298 +OpStore %302 %437 OpReturn OpFunctionEnd -%310 = OpFunction %2 None %85 -%307 = OpLabel -%311 = OpLoad %33 %74 -%312 = OpLoad %35 %76 -%313 = OpLoad %36 %78 -OpBranch %314 -%314 = OpLabel -%315 = OpCompositeConstruct %34 %7 %7 -%317 = OpSampledImage %316 %312 %311 -%318 = OpImageSampleDrefImplicitLod %8 %317 %315 %7 -%319 = OpSampledImage %316 %312 %311 -%320 = OpImageSampleDrefExplicitLod %8 %319 %315 %7 Lod %321 -%322 = OpCompositeConstruct %37 %7 %7 %7 -%324 = OpSampledImage %323 %313 %311 -%325 = OpImageSampleDrefExplicitLod %8 %324 %322 %7 Lod %321 -%326 = OpFAdd %8 %318 %320 -OpStore %308 %326 +%444 = OpFunction %2 None %90 +%441 = OpLabel +%438 = OpVariable %439 Function %440 +%445 = OpLoad %35 %77 +%446 = OpLoad %38 %79 +%447 = OpLoad %39 %81 +%448 = OpLoad %40 %83 +OpBranch %449 +%449 = OpLabel +%450 = OpCompositeConstruct %36 %7 %7 +%451 = OpCompositeConstruct %37 %7 %7 %7 +%453 = OpSampledImage %452 %446 %445 +%454 = OpImageSampleDrefImplicitLod %8 %453 %450 %7 +%455 = OpLoad %8 %438 +%456 = OpFAdd %8 %455 %454 +OpStore %438 %456 +%458 = OpConvertUToF %8 %12 +%459 = OpCompositeConstruct %37 %450 %458 +%460 = OpSampledImage %457 %447 %445 +%461 = OpImageSampleDrefImplicitLod %8 %460 %459 %7 +%462 = OpLoad %8 %438 +%463 = OpFAdd %8 %462 %461 +OpStore %438 %463 +%464 = OpConvertSToF %8 %14 +%465 = OpCompositeConstruct %37 %450 %464 +%466 = OpSampledImage %457 %447 %445 +%467 = OpImageSampleDrefImplicitLod %8 %466 %465 %7 +%468 = OpLoad %8 %438 +%469 = OpFAdd %8 %468 %467 +OpStore %438 %469 +%471 = OpSampledImage %470 %448 %445 +%472 = OpImageSampleDrefImplicitLod %8 %471 %451 %7 +%473 = OpLoad %8 %438 +%474 = OpFAdd %8 %473 %472 +OpStore %438 %474 +%475 = OpSampledImage %452 %446 %445 +%476 = OpImageSampleDrefExplicitLod %8 %475 %450 %7 Lod %477 +%478 = OpLoad %8 %438 +%479 = OpFAdd %8 %478 %476 +OpStore %438 %479 +%480 = OpConvertUToF %8 %12 +%481 = OpCompositeConstruct %37 %450 %480 +%482 = OpSampledImage %457 %447 %445 +%483 = OpImageSampleDrefExplicitLod %8 %482 %481 %7 Lod %477 +%484 = OpLoad %8 %438 +%485 = OpFAdd %8 %484 %483 +OpStore %438 %485 +%486 = OpConvertSToF %8 %14 +%487 = OpCompositeConstruct %37 %450 %486 +%488 = OpSampledImage %457 %447 %445 +%489 = OpImageSampleDrefExplicitLod %8 %488 %487 %7 Lod %477 +%490 = OpLoad %8 %438 +%491 = OpFAdd %8 %490 %489 +OpStore %438 %491 +%492 = OpSampledImage %470 %448 %445 +%493 = OpImageSampleDrefExplicitLod %8 %492 %451 %7 Lod %477 +%494 = OpLoad %8 %438 +%495 = OpFAdd %8 %494 %493 +OpStore %438 %495 +%496 = OpLoad %8 %438 +OpStore %442 %496 OpReturn OpFunctionEnd -%329 = OpFunction %2 None %85 -%327 = OpLabel -%330 = OpLoad %25 %57 -%331 = OpLoad %12 %59 -%332 = OpLoad %26 %60 -%333 = OpLoad %33 %72 -%334 = OpLoad %33 %74 -%335 = OpLoad %35 %76 -OpBranch %336 -%336 = OpLabel -%337 = OpCompositeConstruct %34 %7 %7 -%338 = OpSampledImage %292 %330 %333 -%339 = OpImageGather %32 %338 %337 %340 -%341 = OpSampledImage %292 %330 %333 -%342 = OpImageGather %32 %341 %337 %343 ConstOffset %38 -%344 = OpSampledImage %316 %335 %334 -%345 = OpImageDrefGather %32 %344 %337 %7 -%346 = OpSampledImage %316 %335 %334 -%347 = OpImageDrefGather %32 %346 %337 %7 ConstOffset %38 -%349 = OpSampledImage %348 %331 %333 -%350 = OpImageGather %23 %349 %337 %189 -%353 = OpSampledImage %352 %332 %333 -%354 = OpImageGather %351 %353 %337 %189 -%355 = OpConvertUToF %32 %350 -%356 = OpConvertSToF %32 %354 -%357 = OpFAdd %32 %355 %356 -%358 = OpFAdd %32 %339 %342 -%359 = OpFAdd %32 %358 %345 -%360 = OpFAdd %32 %359 %347 -%361 = OpFAdd %32 %360 %357 -OpStore %328 %361 +%499 = OpFunction %2 None %90 +%497 = OpLabel +%500 = OpLoad %27 %60 +%501 = OpLoad %15 %62 +%502 = OpLoad %28 %63 +%503 = OpLoad %35 %75 +%504 = OpLoad %35 %77 +%505 = OpLoad %38 %79 +OpBranch %506 +%506 = OpLabel +%507 = OpCompositeConstruct %36 %7 %7 +%508 = OpSampledImage %318 %500 %503 +%509 = OpImageGather %34 %508 %507 %510 +%511 = OpSampledImage %318 %500 %503 +%512 = OpImageGather %34 %511 %507 %513 ConstOffset %41 +%514 = OpSampledImage %452 %505 %504 +%515 = OpImageDrefGather %34 %514 %507 %7 +%516 = OpSampledImage %452 %505 %504 +%517 = OpImageDrefGather %34 %516 %507 %7 ConstOffset %41 +%519 = OpSampledImage %518 %501 %503 +%520 = OpImageGather %25 %519 %507 %12 +%523 = OpSampledImage %522 %502 %503 +%524 = OpImageGather %521 %523 %507 %12 +%525 = OpConvertUToF %34 %520 +%526 = OpConvertSToF %34 %524 +%527 = OpFAdd %34 %525 %526 +%528 = OpFAdd %34 %509 %512 +%529 = OpFAdd %34 %528 %515 +%530 = OpFAdd %34 %529 %517 +%531 = OpFAdd %34 %530 %527 +OpStore %498 %531 OpReturn OpFunctionEnd -%364 = OpFunction %2 None %85 -%362 = OpLabel -%365 = OpLoad %33 %72 -%366 = OpLoad %35 %76 -OpBranch %367 -%367 = OpLabel -%368 = OpCompositeConstruct %34 %7 %7 -%369 = OpSampledImage %316 %366 %365 -%370 = OpImageSampleImplicitLod %32 %369 %368 -%371 = OpCompositeExtract %8 %370 0 -%372 = OpSampledImage %316 %366 %365 -%373 = OpImageGather %32 %372 %368 %189 -%374 = OpCompositeConstruct %32 %371 %371 %371 %371 -%375 = OpFAdd %32 %374 %373 -OpStore %363 %375 +%534 = OpFunction %2 None %90 +%532 = OpLabel +%535 = OpLoad %35 %75 +%536 = OpLoad %38 %79 +OpBranch %537 +%537 = OpLabel +%538 = OpCompositeConstruct %36 %7 %7 +%539 = OpSampledImage %452 %536 %535 +%540 = OpImageSampleImplicitLod %34 %539 %538 +%541 = OpCompositeExtract %8 %540 0 +%542 = OpSampledImage %452 %536 %535 +%543 = OpImageGather %34 %542 %538 %12 +%544 = OpCompositeConstruct %34 %541 %541 %541 %541 +%545 = OpFAdd %34 %544 %543 +OpStore %533 %545 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index 15f18c4f5..15cbf4b91 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -223,7 +223,7 @@ OpReturnValue %7 %68 = OpBitcast %4 %48 %69 = OpCompositeExtract %6 %49 2 %70 = OpFMul %6 %69 %62 -%72 = OpConvertUToF %6 %68 +%72 = OpConvertSToF %6 %68 %73 = OpCompositeConstruct %20 %67 %72 %74 = OpSampledImage %71 %52 %53 %75 = OpImageSampleDrefExplicitLod %6 %74 %73 %70 Lod %5 diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 0dcaf3a4d..3409712bc 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -39,6 +39,8 @@ var sampler_cmp: sampler_comparison; @group(1) @binding(2) var image_2d_depth: texture_depth_2d; @group(1) @binding(3) +var image_2d_array_depth: texture_depth_2d_array; +@group(1) @binding(4) var image_cube_depth: texture_depth_cube; @compute @workgroup_size(16, 1, 1) @@ -48,13 +50,15 @@ fn main(@builtin(local_invocation_id) local_id: vec3) { let value1_ = textureLoad(image_mipmapped_src, itc, i32(local_id.z)); let value2_ = textureLoad(image_multisampled_src, itc, i32(local_id.z)); let value4_ = textureLoad(image_storage_src, itc); - let value5_ = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); - let value6_ = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z)); + let value5_ = textureLoad(image_array_src, itc, local_id.z, (i32(local_id.z) + 1)); + let value6_ = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1)); + let value7_ = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z)); let value1u = textureLoad(image_mipmapped_src, vec2(itc), i32(local_id.z)); let value2u = textureLoad(image_multisampled_src, vec2(itc), i32(local_id.z)); let value4u = textureLoad(image_storage_src, vec2(itc)); - let value5u = textureLoad(image_array_src, vec2(itc), i32(local_id.z), (i32(local_id.z) + 1)); - let value6u = textureLoad(image_1d_src, u32(local_id.x), i32(local_id.z)); + let value5u = textureLoad(image_array_src, vec2(itc), local_id.z, (i32(local_id.z) + 1)); + let value6u = textureLoad(image_array_src, vec2(itc), i32(local_id.z), (i32(local_id.z) + 1)); + let value7u = textureLoad(image_1d_src, u32(local_id.x), i32(local_id.z)); textureStore(image_dst, itc.x, ((((value1_ + value2_) + value4_) + value5_) + value6_)); textureStore(image_dst, u32(itc.x), ((((value1u + value2u) + value4u) + value5u) + value6u)); return; @@ -104,42 +108,131 @@ fn levels_queries() -> @builtin(position) vec4 { @fragment fn texture_sample() -> @location(0) vec4 { + var a: vec4; + let tc = vec2(0.5); - let s1d = textureSample(image_1d, sampler_reg, tc.x); - let s2d = textureSample(image_2d, sampler_reg, tc); - let s2d_offset = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); - let s2d_level = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284); - let s2d_level_offset = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284, vec2(3, 1)); - let s2d_bias_offset = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); - return ((((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset); + let tc3_ = vec3(0.5); + let _e9 = textureSample(image_1d, sampler_reg, tc.x); + let _e10 = a; + a = (_e10 + _e9); + let _e14 = textureSample(image_2d, sampler_reg, tc); + let _e15 = a; + a = (_e15 + _e14); + let _e19 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); + let _e20 = a; + a = (_e20 + _e19); + let _e24 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284); + let _e25 = a; + a = (_e25 + _e24); + let _e29 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284, vec2(3, 1)); + let _e30 = a; + a = (_e30 + _e29); + let _e35 = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); + let _e36 = a; + a = (_e36 + _e35); + let _e41 = textureSample(image_2d_array, sampler_reg, tc, 0u); + let _e42 = a; + a = (_e42 + _e41); + let _e47 = textureSample(image_2d_array, sampler_reg, tc, 0u, vec2(3, 1)); + let _e48 = a; + a = (_e48 + _e47); + let _e53 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.299999952316284); + let _e54 = a; + a = (_e54 + _e53); + let _e59 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.299999952316284, vec2(3, 1)); + let _e60 = a; + a = (_e60 + _e59); + let _e66 = textureSampleBias(image_2d_array, sampler_reg, tc, 0u, 2.0, vec2(3, 1)); + let _e67 = a; + a = (_e67 + _e66); + let _e72 = textureSample(image_2d_array, sampler_reg, tc, 0); + let _e73 = a; + a = (_e73 + _e72); + let _e78 = textureSample(image_2d_array, sampler_reg, tc, 0, vec2(3, 1)); + let _e79 = a; + a = (_e79 + _e78); + let _e84 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.299999952316284); + let _e85 = a; + a = (_e85 + _e84); + let _e90 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.299999952316284, vec2(3, 1)); + let _e91 = a; + a = (_e91 + _e90); + let _e97 = textureSampleBias(image_2d_array, sampler_reg, tc, 0, 2.0, vec2(3, 1)); + let _e98 = a; + a = (_e98 + _e97); + let _e103 = textureSample(image_cube_array, sampler_reg, tc3_, 0u); + let _e104 = a; + a = (_e104 + _e103); + let _e109 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0u, 2.299999952316284); + let _e110 = a; + a = (_e110 + _e109); + let _e116 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0u, 2.0); + let _e117 = a; + a = (_e117 + _e116); + let _e122 = textureSample(image_cube_array, sampler_reg, tc3_, 0); + let _e123 = a; + a = (_e123 + _e122); + let _e128 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0, 2.299999952316284); + let _e129 = a; + a = (_e129 + _e128); + let _e135 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0, 2.0); + let _e136 = a; + a = (_e136 + _e135); + let _e138 = a; + return _e138; } @fragment fn texture_sample_comparison() -> @location(0) f32 { + var a_1: f32; + let tc_1 = vec2(0.5); - let s2d_depth = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); - let s2d_depth_level = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5); - let scube_depth_level = textureSampleCompareLevel(image_cube_depth, sampler_cmp, vec3(0.5), 0.5); - return (s2d_depth + s2d_depth_level); + let tc3_1 = vec3(0.5); + let _e8 = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); + let _e9 = a_1; + a_1 = (_e9 + _e8); + let _e14 = textureSampleCompare(image_2d_array_depth, sampler_cmp, tc_1, 0u, 0.5); + let _e15 = a_1; + a_1 = (_e15 + _e14); + let _e20 = textureSampleCompare(image_2d_array_depth, sampler_cmp, tc_1, 0, 0.5); + let _e21 = a_1; + a_1 = (_e21 + _e20); + let _e25 = textureSampleCompare(image_cube_depth, sampler_cmp, tc3_1, 0.5); + let _e26 = a_1; + a_1 = (_e26 + _e25); + let _e30 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5); + let _e31 = a_1; + a_1 = (_e31 + _e30); + let _e36 = textureSampleCompareLevel(image_2d_array_depth, sampler_cmp, tc_1, 0u, 0.5); + let _e37 = a_1; + a_1 = (_e37 + _e36); + let _e42 = textureSampleCompareLevel(image_2d_array_depth, sampler_cmp, tc_1, 0, 0.5); + let _e43 = a_1; + a_1 = (_e43 + _e42); + let _e47 = textureSampleCompareLevel(image_cube_depth, sampler_cmp, tc3_1, 0.5); + let _e48 = a_1; + a_1 = (_e48 + _e47); + let _e50 = a_1; + return _e50; } @fragment fn gather() -> @location(0) vec4 { let tc_2 = vec2(0.5); - let s2d_1 = textureGather(1, image_2d, sampler_reg, tc_2); - let s2d_offset_1 = textureGather(3, image_2d, sampler_reg, tc_2, vec2(3, 1)); - let s2d_depth_1 = textureGatherCompare(image_2d_depth, sampler_cmp, tc_2, 0.5); + let s2d = textureGather(1, image_2d, sampler_reg, tc_2); + let s2d_offset = textureGather(3, image_2d, sampler_reg, tc_2, vec2(3, 1)); + let s2d_depth = textureGatherCompare(image_2d_depth, sampler_cmp, tc_2, 0.5); let s2d_depth_offset = textureGatherCompare(image_2d_depth, sampler_cmp, tc_2, 0.5, vec2(3, 1)); let u = textureGather(0, image_2d_u32_, sampler_reg, tc_2); let i = textureGather(0, image_2d_i32_, sampler_reg, tc_2); let f = (vec4(u) + vec4(i)); - return ((((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset) + f); + return ((((s2d + s2d_offset) + s2d_depth) + s2d_depth_offset) + f); } @fragment fn depth_no_comparison() -> @location(0) vec4 { let tc_3 = vec2(0.5); - let s2d_2 = textureSample(image_2d_depth, sampler_reg, tc_3); + let s2d_1 = textureSample(image_2d_depth, sampler_reg, tc_3); let s2d_gather = textureGather(image_2d_depth, sampler_reg, tc_3); - return (vec4(s2d_2) + s2d_gather); + return (vec4(s2d_1) + s2d_gather); } From b9c5cb5a7841a8728137a58840fbbdbb9b310267 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 12 Apr 2023 16:48:57 +0200 Subject: [PATCH 1982/2212] validate vertex stage returns the position built-in --- src/valid/interface.rs | 14 +- tests/in/functions-webgl.wgsl | 2 +- .../{277-casting.vert => 277-casting.frag} | 0 ...-matrix-cast.vert => 280-matrix-cast.frag} | 0 ...essor-if.vert => 484-preprocessor-if.frag} | 0 ...h-constant.vert => 896-push-constant.frag} | 0 ...ons.vert => 900-implicit-conversions.frag} | 0 ...-select.vert => 901-lhs-field-select.frag} | 0 ...itting.vert => 931-constant-emitting.frag} | 0 ...-for-loop-if.vert => 932-for-loop-if.frag} | 0 ...ray-size.vert => constant-array-size.frag} | 0 .../{declarations.vert => declarations.frag} | 0 ...-array.vert => global-constant-array.frag} | 0 ...form-matrix.vert => long-form-matrix.frag} | 0 ...ath-functions.vert => math-functions.frag} | 0 ...r-functions.vert => vector-functions.frag} | 0 tests/in/math-functions.wgsl | 2 +- tests/in/multiview.wgsl | 2 +- tests/in/multiview_webgl.wgsl | 2 +- tests/in/spv/degrees.spv | Bin 676 -> 676 bytes tests/in/spv/degrees.spvasm | 47 +++ .../in/spv/inv-hyperbolic-trig-functions.spv | Bin 480 -> 480 bytes .../spv/inv-hyperbolic-trig-functions.spvasm | 37 +++ tests/in/spv/quad-vert.spvasm | 61 ++++ tests/in/spv/shadow.spvasm | 291 ++++++++++++++++++ ...lsl => functions-webgl.main.Fragment.glsl} | 0 ...glsl => math-functions.main.Fragment.glsl} | 0 ...rtex.glsl => multiview.main.Fragment.glsl} | 1 - ...lsl => multiview_webgl.main.Fragment.glsl} | 2 - .../inv-hyperbolic-trig-functions.hlsl.config | 4 +- tests/out/hlsl/math-functions.hlsl.config | 4 +- tests/out/msl/math-functions.msl | 2 +- tests/out/spv/math-functions.spvasm | 3 +- tests/out/spv/multiview.spvasm | 4 +- ...asting-vert.wgsl => 277-casting-frag.wgsl} | 2 +- ...st-vert.wgsl => 280-matrix-cast-frag.wgsl} | 2 +- ...ert.wgsl => 484-preprocessor-if-frag.wgsl} | 2 +- ...-vert.wgsl => 896-push-constant-frag.wgsl} | 2 +- ...gsl => 900-implicit-conversions-frag.wgsl} | 2 +- ...rt.wgsl => 901-lhs-field-select-frag.wgsl} | 2 +- ...t.wgsl => 931-constant-emitting-frag.wgsl} | 2 +- ...if-vert.wgsl => 932-for-loop-if-frag.wgsl} | 2 +- tests/out/wgsl/binop-frag.wgsl | 187 ----------- ...ert.wgsl => constant-array-size-frag.wgsl} | 2 +- ...tions-vert.wgsl => declarations-frag.wgsl} | 8 +- ...t.wgsl => global-constant-array-frag.wgsl} | 2 +- .../wgsl/inv-hyperbolic-trig-functions.wgsl | 2 +- ...x-vert.wgsl => long-form-matrix-frag.wgsl} | 2 +- ...ons-vert.wgsl => math-functions-frag.wgsl} | 2 +- tests/out/wgsl/math-functions.wgsl | 2 +- tests/out/wgsl/multiview.wgsl | 2 +- ...s-vert.wgsl => vector-functions-frag.wgsl} | 2 +- tests/snapshots.rs | 3 +- tests/wgsl-errors.rs | 66 +++- 54 files changed, 535 insertions(+), 239 deletions(-) rename tests/in/glsl/{277-casting.vert => 277-casting.frag} (100%) rename tests/in/glsl/{280-matrix-cast.vert => 280-matrix-cast.frag} (100%) rename tests/in/glsl/{484-preprocessor-if.vert => 484-preprocessor-if.frag} (100%) rename tests/in/glsl/{896-push-constant.vert => 896-push-constant.frag} (100%) rename tests/in/glsl/{900-implicit-conversions.vert => 900-implicit-conversions.frag} (100%) rename tests/in/glsl/{901-lhs-field-select.vert => 901-lhs-field-select.frag} (100%) rename tests/in/glsl/{931-constant-emitting.vert => 931-constant-emitting.frag} (100%) rename tests/in/glsl/{932-for-loop-if.vert => 932-for-loop-if.frag} (100%) rename tests/in/glsl/{constant-array-size.vert => constant-array-size.frag} (100%) rename tests/in/glsl/{declarations.vert => declarations.frag} (100%) rename tests/in/glsl/{global-constant-array.vert => global-constant-array.frag} (100%) rename tests/in/glsl/{long-form-matrix.vert => long-form-matrix.frag} (100%) rename tests/in/glsl/{math-functions.vert => math-functions.frag} (100%) rename tests/in/glsl/{vector-functions.vert => vector-functions.frag} (100%) create mode 100644 tests/in/spv/degrees.spvasm create mode 100644 tests/in/spv/inv-hyperbolic-trig-functions.spvasm create mode 100644 tests/in/spv/quad-vert.spvasm create mode 100644 tests/in/spv/shadow.spvasm rename tests/out/glsl/{functions-webgl.main.Vertex.glsl => functions-webgl.main.Fragment.glsl} (100%) rename tests/out/glsl/{math-functions.main.Vertex.glsl => math-functions.main.Fragment.glsl} (100%) rename tests/out/glsl/{multiview.main.Vertex.glsl => multiview.main.Fragment.glsl} (67%) rename tests/out/glsl/{multiview_webgl.main.Vertex.glsl => multiview_webgl.main.Fragment.glsl} (86%) rename tests/out/wgsl/{277-casting-vert.wgsl => 277-casting-frag.wgsl} (90%) rename tests/out/wgsl/{280-matrix-cast-vert.wgsl => 280-matrix-cast-frag.wgsl} (95%) rename tests/out/wgsl/{484-preprocessor-if-vert.wgsl => 484-preprocessor-if-frag.wgsl} (86%) rename tests/out/wgsl/{896-push-constant-vert.wgsl => 896-push-constant-frag.wgsl} (93%) rename tests/out/wgsl/{900-implicit-conversions-vert.wgsl => 900-implicit-conversions-frag.wgsl} (98%) rename tests/out/wgsl/{901-lhs-field-select-vert.wgsl => 901-lhs-field-select-frag.wgsl} (92%) rename tests/out/wgsl/{931-constant-emitting-vert.wgsl => 931-constant-emitting-frag.wgsl} (92%) rename tests/out/wgsl/{932-for-loop-if-vert.wgsl => 932-for-loop-if-frag.wgsl} (96%) delete mode 100644 tests/out/wgsl/binop-frag.wgsl rename tests/out/wgsl/{constant-array-size-vert.wgsl => constant-array-size-frag.wgsl} (98%) rename tests/out/wgsl/{declarations-vert.wgsl => declarations-frag.wgsl} (93%) rename tests/out/wgsl/{global-constant-array-vert.wgsl => global-constant-array-frag.wgsl} (95%) rename tests/out/wgsl/{long-form-matrix-vert.wgsl => long-form-matrix-frag.wgsl} (99%) rename tests/out/wgsl/{math-functions-vert.wgsl => math-functions-frag.wgsl} (99%) rename tests/out/wgsl/{vector-functions-vert.wgsl => vector-functions-frag.wgsl} (99%) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index d9ee9f540..268490c52 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -63,6 +63,8 @@ pub enum VaryingError { pub enum EntryPointError { #[error("Multiple conflicting entry points")] Conflict, + #[error("Vertex shaders must return a `@builtin(position)` output value")] + MissingVertexOutputPosition, #[error("Early depth test is not applicable")] UnexpectedEarlyDepthTest, #[error("Workgroup size is not applicable")] @@ -353,7 +355,6 @@ impl VaryingContext<'_> { .map_err(|e| e.with_span_context(span_context)), None => { match self.types[ty].inner { - //TODO: check the member types crate::TypeInner::Struct { ref members, .. } => { for (index, member) in members.iter().enumerate() { let span_context = self.types.get_span_context(ty); @@ -369,7 +370,6 @@ impl VaryingContext<'_> { #[cfg(not(feature = "validate"))] let _ = index; } - // TODO: shouldn't this be validate? Some(ref binding) => self .validate_impl(member.ty, binding) .map_err(|e| e.with_span_context(span_context))?, @@ -603,6 +603,16 @@ impl super::Validator { }; ctx.validate(fr.ty, fr.binding.as_ref()) .map_err_inner(|e| EntryPointError::Result(e).with_span())?; + + #[cfg(feature = "validate")] + if ep.stage == crate::ShaderStage::Vertex + && !result_built_ins.contains(&crate::BuiltIn::Position { invariant: false }) + { + return Err(EntryPointError::MissingVertexOutputPosition.with_span()); + } + } else if ep.stage == crate::ShaderStage::Vertex { + #[cfg(feature = "validate")] + return Err(EntryPointError::MissingVertexOutputPosition.with_span()); } for bg in self.bind_group_masks.iter_mut() { diff --git a/tests/in/functions-webgl.wgsl b/tests/in/functions-webgl.wgsl index 9192f6868..2355aa2c9 100644 --- a/tests/in/functions-webgl.wgsl +++ b/tests/in/functions-webgl.wgsl @@ -7,7 +7,7 @@ fn test_fma() -> vec2 { } -@vertex +@fragment fn main() { let a = test_fma(); } diff --git a/tests/in/glsl/277-casting.vert b/tests/in/glsl/277-casting.frag similarity index 100% rename from tests/in/glsl/277-casting.vert rename to tests/in/glsl/277-casting.frag diff --git a/tests/in/glsl/280-matrix-cast.vert b/tests/in/glsl/280-matrix-cast.frag similarity index 100% rename from tests/in/glsl/280-matrix-cast.vert rename to tests/in/glsl/280-matrix-cast.frag diff --git a/tests/in/glsl/484-preprocessor-if.vert b/tests/in/glsl/484-preprocessor-if.frag similarity index 100% rename from tests/in/glsl/484-preprocessor-if.vert rename to tests/in/glsl/484-preprocessor-if.frag diff --git a/tests/in/glsl/896-push-constant.vert b/tests/in/glsl/896-push-constant.frag similarity index 100% rename from tests/in/glsl/896-push-constant.vert rename to tests/in/glsl/896-push-constant.frag diff --git a/tests/in/glsl/900-implicit-conversions.vert b/tests/in/glsl/900-implicit-conversions.frag similarity index 100% rename from tests/in/glsl/900-implicit-conversions.vert rename to tests/in/glsl/900-implicit-conversions.frag diff --git a/tests/in/glsl/901-lhs-field-select.vert b/tests/in/glsl/901-lhs-field-select.frag similarity index 100% rename from tests/in/glsl/901-lhs-field-select.vert rename to tests/in/glsl/901-lhs-field-select.frag diff --git a/tests/in/glsl/931-constant-emitting.vert b/tests/in/glsl/931-constant-emitting.frag similarity index 100% rename from tests/in/glsl/931-constant-emitting.vert rename to tests/in/glsl/931-constant-emitting.frag diff --git a/tests/in/glsl/932-for-loop-if.vert b/tests/in/glsl/932-for-loop-if.frag similarity index 100% rename from tests/in/glsl/932-for-loop-if.vert rename to tests/in/glsl/932-for-loop-if.frag diff --git a/tests/in/glsl/constant-array-size.vert b/tests/in/glsl/constant-array-size.frag similarity index 100% rename from tests/in/glsl/constant-array-size.vert rename to tests/in/glsl/constant-array-size.frag diff --git a/tests/in/glsl/declarations.vert b/tests/in/glsl/declarations.frag similarity index 100% rename from tests/in/glsl/declarations.vert rename to tests/in/glsl/declarations.frag diff --git a/tests/in/glsl/global-constant-array.vert b/tests/in/glsl/global-constant-array.frag similarity index 100% rename from tests/in/glsl/global-constant-array.vert rename to tests/in/glsl/global-constant-array.frag diff --git a/tests/in/glsl/long-form-matrix.vert b/tests/in/glsl/long-form-matrix.frag similarity index 100% rename from tests/in/glsl/long-form-matrix.vert rename to tests/in/glsl/long-form-matrix.frag diff --git a/tests/in/glsl/math-functions.vert b/tests/in/glsl/math-functions.frag similarity index 100% rename from tests/in/glsl/math-functions.vert rename to tests/in/glsl/math-functions.frag diff --git a/tests/in/glsl/vector-functions.vert b/tests/in/glsl/vector-functions.frag similarity index 100% rename from tests/in/glsl/vector-functions.vert rename to tests/in/glsl/vector-functions.frag diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index db50880d1..da67ca23e 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -1,4 +1,4 @@ -@vertex +@fragment fn main() { let f = 1.0; let v = vec4(0.0); diff --git a/tests/in/multiview.wgsl b/tests/in/multiview.wgsl index b4531c8a7..0eedd0878 100644 --- a/tests/in/multiview.wgsl +++ b/tests/in/multiview.wgsl @@ -1,2 +1,2 @@ -@vertex +@fragment fn main(@builtin(view_index) view_index: i32) {} diff --git a/tests/in/multiview_webgl.wgsl b/tests/in/multiview_webgl.wgsl index b4531c8a7..0eedd0878 100644 --- a/tests/in/multiview_webgl.wgsl +++ b/tests/in/multiview_webgl.wgsl @@ -1,2 +1,2 @@ -@vertex +@fragment fn main(@builtin(view_index) view_index: i32) {} diff --git a/tests/in/spv/degrees.spv b/tests/in/spv/degrees.spv index 0e5eeab4801959135ed79998e86f119fe85e56dc..b7aa393c0718857ef1208f33562be45711a18f21 100644 GIT binary patch delta 12 TcmZ3&x`cIt3nR-$*LWrX8Bqg+ delta 12 TcmZ3&x`cIt3nRlu*LWrX89f7k diff --git a/tests/in/spv/degrees.spvasm b/tests/in/spv/degrees.spvasm new file mode 100644 index 000000000..de2605a51 --- /dev/null +++ b/tests/in/spv/degrees.spvasm @@ -0,0 +1,47 @@ +; SPIR-V +; Version: 1.0 +; Generator: Khronos Glslang Reference Front End; 10 +; Bound: 27 +; Schema: 0 + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %colour + OpSource GLSL 450 + OpName %main "main" + OpName %deg "deg" + OpName %rad "rad" + OpName %deg_again "deg_again" + OpName %colour "colour" + OpDecorate %colour Location 0 + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 +%_ptr_Function_float = OpTypePointer Function %float + %float_15 = OpConstant %float 15 + %v4float = OpTypeVector %float 4 +%_ptr_Output_v4float = OpTypePointer Output %v4float + %colour = OpVariable %_ptr_Output_v4float Output + %v3float = OpTypeVector %float 3 + %float_1 = OpConstant %float 1 + %main = OpFunction %void None %3 + %5 = OpLabel + %deg = OpVariable %_ptr_Function_float Function + %rad = OpVariable %_ptr_Function_float Function + %deg_again = OpVariable %_ptr_Function_float Function + OpStore %deg %float_15 + %11 = OpLoad %float %deg + %12 = OpExtInst %float %1 Radians %11 + OpStore %rad %12 + %14 = OpLoad %float %rad + %15 = OpExtInst %float %1 Degrees %14 + OpStore %deg_again %15 + %19 = OpLoad %float %deg_again + %21 = OpCompositeConstruct %v3float %19 %19 %19 + %23 = OpCompositeExtract %float %21 0 + %24 = OpCompositeExtract %float %21 1 + %25 = OpCompositeExtract %float %21 2 + %26 = OpCompositeConstruct %v4float %23 %24 %25 %float_1 + OpStore %colour %26 + OpReturn + OpFunctionEnd diff --git a/tests/in/spv/inv-hyperbolic-trig-functions.spv b/tests/in/spv/inv-hyperbolic-trig-functions.spv index a87d8deec536a7f8691a77be664e6f194e751217..da365355e8651a576c503a55132b726766f9715e 100644 GIT binary patch delta 12 TcmaFB{D66a3nR-$*V&8!9>@eT delta 12 TcmaFB{D66a3nRlu*V&8!9<&55 diff --git a/tests/in/spv/inv-hyperbolic-trig-functions.spvasm b/tests/in/spv/inv-hyperbolic-trig-functions.spvasm new file mode 100644 index 000000000..efa962089 --- /dev/null +++ b/tests/in/spv/inv-hyperbolic-trig-functions.spvasm @@ -0,0 +1,37 @@ +; SPIR-V +; Version: 1.0 +; Generator: Khronos Glslang Reference Front End; 10 +; Bound: 19 +; Schema: 0 + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" + OpSource GLSL 450 + OpName %main "main" + OpName %b "b" + OpName %a "a" + OpName %c "c" + OpName %d "d" + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 +%_ptr_Function_float = OpTypePointer Function %float +%_ptr_Private_float = OpTypePointer Private %float + %a = OpVariable %_ptr_Private_float Private + %main = OpFunction %void None %3 + %5 = OpLabel + %b = OpVariable %_ptr_Function_float Function + %c = OpVariable %_ptr_Function_float Function + %d = OpVariable %_ptr_Function_float Function + %11 = OpLoad %float %a + %12 = OpExtInst %float %1 Asinh %11 + OpStore %b %12 + %14 = OpLoad %float %a + %15 = OpExtInst %float %1 Acosh %14 + OpStore %c %15 + %17 = OpLoad %float %a + %18 = OpExtInst %float %1 Atanh %17 + OpStore %d %18 + OpReturn + OpFunctionEnd diff --git a/tests/in/spv/quad-vert.spvasm b/tests/in/spv/quad-vert.spvasm new file mode 100644 index 000000000..7633c94c5 --- /dev/null +++ b/tests/in/spv/quad-vert.spvasm @@ -0,0 +1,61 @@ +; SPIR-V +; Version: 1.0 +; Generator: Khronos Glslang Reference Front End; 10 +; Bound: 31 +; Schema: 0 + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Vertex %main "main" %v_uv %a_uv %_ %a_pos + OpSource GLSL 460 + OpName %main "main" + OpName %v_uv "v_uv" + OpName %a_uv "a_uv" + OpName %gl_PerVertex "gl_PerVertex" + OpMemberName %gl_PerVertex 0 "gl_Position" + OpMemberName %gl_PerVertex 1 "gl_PointSize" + OpMemberName %gl_PerVertex 2 "gl_ClipDistance" + OpMemberName %gl_PerVertex 3 "gl_CullDistance" + OpName %_ "" + OpName %a_pos "a_pos" + OpDecorate %v_uv Location 0 + OpDecorate %a_uv Location 1 + OpMemberDecorate %gl_PerVertex 0 BuiltIn Position + OpMemberDecorate %gl_PerVertex 1 BuiltIn PointSize + OpMemberDecorate %gl_PerVertex 2 BuiltIn ClipDistance + OpMemberDecorate %gl_PerVertex 3 BuiltIn CullDistance + OpDecorate %gl_PerVertex Block + OpDecorate %a_pos Location 0 + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v2float = OpTypeVector %float 2 +%_ptr_Output_v2float = OpTypePointer Output %v2float + %v_uv = OpVariable %_ptr_Output_v2float Output +%_ptr_Input_v2float = OpTypePointer Input %v2float + %a_uv = OpVariable %_ptr_Input_v2float Input + %v4float = OpTypeVector %float 4 + %uint = OpTypeInt 32 0 + %uint_1 = OpConstant %uint 1 +%_arr_float_uint_1 = OpTypeArray %float %uint_1 +%gl_PerVertex = OpTypeStruct %v4float %float %_arr_float_uint_1 %_arr_float_uint_1 +%_ptr_Output_gl_PerVertex = OpTypePointer Output %gl_PerVertex + %_ = OpVariable %_ptr_Output_gl_PerVertex Output + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 + %a_pos = OpVariable %_ptr_Input_v2float Input + %float_0 = OpConstant %float 0 + %float_1 = OpConstant %float 1 +%_ptr_Output_v4float = OpTypePointer Output %v4float + %main = OpFunction %void None %3 + %5 = OpLabel + %12 = OpLoad %v2float %a_uv + OpStore %v_uv %12 + %23 = OpLoad %v2float %a_pos + %26 = OpCompositeExtract %float %23 0 + %27 = OpCompositeExtract %float %23 1 + %28 = OpCompositeConstruct %v4float %26 %27 %float_0 %float_1 + %30 = OpAccessChain %_ptr_Output_v4float %_ %int_0 + OpStore %30 %28 + OpReturn + OpFunctionEnd diff --git a/tests/in/spv/shadow.spvasm b/tests/in/spv/shadow.spvasm new file mode 100644 index 000000000..e928b71c4 --- /dev/null +++ b/tests/in/spv/shadow.spvasm @@ -0,0 +1,291 @@ +; SPIR-V +; Version: 1.0 +; Generator: Khronos SPIR-V Tools Assembler; 0 +; Bound: 221 +; Schema: 0 + OpCapability Shader + OpExtension "SPV_KHR_storage_buffer_storage_class" + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %fs_main "fs_main" %in_normal_fs %in_position_fs %out_color_fs + OpExecutionMode %fs_main OriginUpperLeft + OpSource GLSL 450 + OpName %t_shadow "t_shadow" + OpName %sampler_shadow "sampler_shadow" + OpName %color "color" + OpName %i "i" + OpName %Globals "Globals" + OpMemberName %Globals 0 "num_lights" + OpName %u_globals "u_globals" + OpName %Light "Light" + OpMemberName %Light 0 "proj" + OpMemberName %Light 1 "pos" + OpMemberName %Light 2 "color" + OpName %Lights "Lights" + OpMemberName %Lights 0 "data" + OpName %s_lights "s_lights" + OpName %in_position_fs "in_position_fs" + OpName %in_normal_fs "in_normal_fs" + OpName %out_color_fs "out_color_fs" + OpName %fs_main "fs_main" + OpDecorate %t_shadow DescriptorSet 0 + OpDecorate %t_shadow Binding 2 + OpDecorate %sampler_shadow DescriptorSet 0 + OpDecorate %sampler_shadow Binding 3 + OpDecorate %Globals Block + OpMemberDecorate %Globals 0 Offset 0 + OpDecorate %u_globals DescriptorSet 0 + OpDecorate %u_globals Binding 0 + OpMemberDecorate %Light 0 Offset 0 + OpMemberDecorate %Light 0 ColMajor + OpMemberDecorate %Light 0 MatrixStride 16 + OpMemberDecorate %Light 1 Offset 64 + OpMemberDecorate %Light 2 Offset 80 + OpDecorate %_runtimearr_Light ArrayStride 96 + OpDecorate %Lights BufferBlock + OpMemberDecorate %Lights 0 Offset 0 + OpMemberDecorate %Lights 0 NonWritable + OpDecorate %s_lights DescriptorSet 0 + OpDecorate %s_lights Binding 1 + OpDecorate %in_position_fs Location 1 + OpDecorate %in_normal_fs Location 0 + OpDecorate %out_color_fs Location 0 + %void = OpTypeVoid + %float = OpTypeFloat 32 + %float_0 = OpConstant %float 0 + %float_1 = OpConstant %float 1 + %float_0_5 = OpConstant %float 0.5 + %float_n0_5 = OpConstant %float -0.5 +%float_0_0500000007 = OpConstant %float 0.0500000007 + %v3float = OpTypeVector %float 3 + %9 = OpConstantComposite %v3float %float_0_0500000007 %float_0_0500000007 %float_0_0500000007 + %uint = OpTypeInt 32 0 + %uint_10 = OpConstant %uint 10 + %uint_0 = OpConstant %uint 0 + %uint_1 = OpConstant %uint 1 + %v4float = OpTypeVector %float 4 + %19 = OpTypeFunction %float %uint %v4float + %bool = OpTypeBool + %27 = OpTypeImage %float 2D 1 1 0 1 Unknown +%_ptr_UniformConstant_27 = OpTypePointer UniformConstant %27 + %t_shadow = OpVariable %_ptr_UniformConstant_27 UniformConstant + %31 = OpTypeSampledImage %27 + %32 = OpTypeSampler +%_ptr_UniformConstant_32 = OpTypePointer UniformConstant %32 +%sampler_shadow = OpVariable %_ptr_UniformConstant_32 UniformConstant + %v2float = OpTypeVector %float 2 + %int = OpTypeInt 32 1 + %float_0_0 = OpConstant %float 0 +%_ptr_Function_v3float = OpTypePointer Function %v3float +%_ptr_Function_uint = OpTypePointer Function %uint + %65 = OpTypeFunction %void + %v4uint = OpTypeVector %uint 4 + %Globals = OpTypeStruct %v4uint +%_ptr_Uniform_Globals = OpTypePointer Uniform %Globals + %u_globals = OpVariable %_ptr_Uniform_Globals Uniform +%_ptr_Uniform_v4uint = OpTypePointer Uniform %v4uint + %int_0 = OpConstant %int 0 +%_ptr_Uniform_uint = OpTypePointer Uniform %uint + %int_0_0 = OpConstant %int 0 +%mat4v4float = OpTypeMatrix %v4float 4 + %Light = OpTypeStruct %mat4v4float %v4float %v4float +%_runtimearr_Light = OpTypeRuntimeArray %Light + %Lights = OpTypeStruct %_runtimearr_Light +%_ptr_StorageBuffer_Lights = OpTypePointer StorageBuffer %Lights + %s_lights = OpVariable %_ptr_StorageBuffer_Lights StorageBuffer +%_ptr_StorageBuffer__runtimearr_Light = OpTypePointer StorageBuffer %_runtimearr_Light + %int_0_1 = OpConstant %int 0 +%_ptr_StorageBuffer_Light = OpTypePointer StorageBuffer %Light +%_ptr_StorageBuffer_mat4v4float = OpTypePointer StorageBuffer %mat4v4float + %int_0_2 = OpConstant %int 0 +%_ptr_Input_v4float = OpTypePointer Input %v4float +%in_position_fs = OpVariable %_ptr_Input_v4float Input +%_ptr_Input_v3float = OpTypePointer Input %v3float +%in_normal_fs = OpVariable %_ptr_Input_v3float Input +%_ptr_StorageBuffer__runtimearr_Light_0 = OpTypePointer StorageBuffer %_runtimearr_Light + %int_0_3 = OpConstant %int 0 +%_ptr_StorageBuffer_Light_0 = OpTypePointer StorageBuffer %Light +%_ptr_StorageBuffer_v4float = OpTypePointer StorageBuffer %v4float + %int_1 = OpConstant %int 1 +%_ptr_StorageBuffer_float = OpTypePointer StorageBuffer %float + %int_0_4 = OpConstant %int 0 +%_ptr_StorageBuffer__runtimearr_Light_1 = OpTypePointer StorageBuffer %_runtimearr_Light + %int_0_5 = OpConstant %int 0 +%_ptr_StorageBuffer_Light_1 = OpTypePointer StorageBuffer %Light +%_ptr_StorageBuffer_v4float_0 = OpTypePointer StorageBuffer %v4float + %int_1_0 = OpConstant %int 1 +%_ptr_StorageBuffer_float_0 = OpTypePointer StorageBuffer %float + %int_1_1 = OpConstant %int 1 +%_ptr_StorageBuffer__runtimearr_Light_2 = OpTypePointer StorageBuffer %_runtimearr_Light + %int_0_6 = OpConstant %int 0 +%_ptr_StorageBuffer_Light_2 = OpTypePointer StorageBuffer %Light +%_ptr_StorageBuffer_v4float_1 = OpTypePointer StorageBuffer %v4float + %int_1_2 = OpConstant %int 1 +%_ptr_StorageBuffer_float_1 = OpTypePointer StorageBuffer %float + %int_2 = OpConstant %int 2 +%_ptr_Input_float = OpTypePointer Input %float + %int_0_7 = OpConstant %int 0 +%_ptr_Input_float_0 = OpTypePointer Input %float + %int_1_3 = OpConstant %int 1 +%_ptr_Input_float_1 = OpTypePointer Input %float + %int_2_0 = OpConstant %int 2 +%_ptr_StorageBuffer__runtimearr_Light_3 = OpTypePointer StorageBuffer %_runtimearr_Light + %int_0_8 = OpConstant %int 0 +%_ptr_StorageBuffer_Light_3 = OpTypePointer StorageBuffer %Light +%_ptr_StorageBuffer_v4float_2 = OpTypePointer StorageBuffer %v4float + %int_2_1 = OpConstant %int 2 +%_ptr_StorageBuffer_float_2 = OpTypePointer StorageBuffer %float + %int_0_9 = OpConstant %int 0 +%_ptr_StorageBuffer__runtimearr_Light_4 = OpTypePointer StorageBuffer %_runtimearr_Light + %int_0_10 = OpConstant %int 0 +%_ptr_StorageBuffer_Light_4 = OpTypePointer StorageBuffer %Light +%_ptr_StorageBuffer_v4float_3 = OpTypePointer StorageBuffer %v4float + %int_2_2 = OpConstant %int 2 +%_ptr_StorageBuffer_float_3 = OpTypePointer StorageBuffer %float + %int_1_4 = OpConstant %int 1 +%_ptr_StorageBuffer__runtimearr_Light_5 = OpTypePointer StorageBuffer %_runtimearr_Light + %int_0_11 = OpConstant %int 0 +%_ptr_StorageBuffer_Light_5 = OpTypePointer StorageBuffer %Light +%_ptr_StorageBuffer_v4float_4 = OpTypePointer StorageBuffer %v4float + %int_2_3 = OpConstant %int 2 +%_ptr_StorageBuffer_float_4 = OpTypePointer StorageBuffer %float + %int_2_4 = OpConstant %int 2 +%_ptr_Output_v4float = OpTypePointer Output %v4float +%out_color_fs = OpVariable %_ptr_Output_v4float Output + %18 = OpFunction %float None %19 + %15 = OpFunctionParameter %uint + %16 = OpFunctionParameter %v4float + %20 = OpLabel + %23 = OpCompositeExtract %float %16 3 + %22 = OpFOrdLessThanEqual %bool %23 %float_0 + OpSelectionMerge %24 None + OpBranchConditional %22 %25 %26 + %25 = OpLabel + OpReturnValue %float_1 + %26 = OpLabel + OpBranch %24 + %24 = OpLabel + %30 = OpLoad %27 %t_shadow + %35 = OpLoad %32 %sampler_shadow + %40 = OpCompositeExtract %float %16 0 + %41 = OpCompositeExtract %float %16 1 + %42 = OpCompositeConstruct %v2float %40 %41 + %43 = OpCompositeConstruct %v2float %float_0_5 %float_n0_5 + %39 = OpFMul %v2float %42 %43 + %45 = OpCompositeExtract %float %16 3 + %44 = OpFDiv %float %float_1 %45 + %38 = OpVectorTimesScalar %v2float %39 %44 + %46 = OpCompositeConstruct %v2float %float_0_5 %float_0_5 + %37 = OpFAdd %v2float %38 %46 + %47 = OpCompositeExtract %float %37 0 + %48 = OpCompositeExtract %float %37 1 + %51 = OpBitcast %int %15 + %49 = OpConvertUToF %float %51 + %52 = OpCompositeConstruct %v3float %47 %48 %49 + %53 = OpSampledImage %31 %30 %35 + %56 = OpCompositeExtract %float %16 2 + %58 = OpCompositeExtract %float %16 3 + %57 = OpFDiv %float %float_1 %58 + %55 = OpFMul %float %56 %57 + %54 = OpImageSampleDrefExplicitLod %float %53 %52 %55 Lod %float_0_0 + OpReturnValue %54 + OpFunctionEnd + %fs_main = OpFunction %void None %65 + %66 = OpLabel + %color = OpVariable %_ptr_Function_v3float Function %9 + %i = OpVariable %_ptr_Function_uint Function %uint_0 + OpBranch %67 + %67 = OpLabel + OpLoopMerge %68 %70 None + OpBranch %69 + %69 = OpLabel + %72 = OpLoad %uint %i + %75 = OpAccessChain %_ptr_Uniform_v4uint %u_globals %int_0 + %73 = OpAccessChain %_ptr_Uniform_uint %75 %int_0_0 + %83 = OpLoad %uint %73 + %84 = OpExtInst %uint %1 UMin %83 %uint_10 + %71 = OpUGreaterThanEqual %bool %72 %84 + OpSelectionMerge %85 None + OpBranchConditional %71 %86 %87 + %86 = OpLabel + OpBranch %68 + %87 = OpLabel + OpBranch %85 + %85 = OpLabel + %89 = OpLoad %v3float %color + %93 = OpLoad %uint %i + %100 = OpAccessChain %_ptr_StorageBuffer__runtimearr_Light %s_lights %int_0_1 + %106 = OpLoad %uint %i + %98 = OpAccessChain %_ptr_StorageBuffer_Light %100 %106 + %96 = OpAccessChain %_ptr_StorageBuffer_mat4v4float %98 %int_0_2 + %110 = OpLoad %mat4v4float %96 + %113 = OpLoad %v4float %in_position_fs + %94 = OpMatrixTimesVector %v4float %110 %113 + %92 = OpFunctionCall %float %18 %93 %94 + %116 = OpLoad %v3float %in_normal_fs + %117 = OpExtInst %v3float %1 Normalize %116 + %122 = OpAccessChain %_ptr_StorageBuffer__runtimearr_Light_0 %s_lights %int_0_3 + %125 = OpLoad %uint %i + %121 = OpAccessChain %_ptr_StorageBuffer_Light_0 %122 %125 + %120 = OpAccessChain %_ptr_StorageBuffer_v4float %121 %int_1 + %119 = OpAccessChain %_ptr_StorageBuffer_float %120 %int_0_4 + %131 = OpLoad %float %119 + %135 = OpAccessChain %_ptr_StorageBuffer__runtimearr_Light_1 %s_lights %int_0_5 + %138 = OpLoad %uint %i + %134 = OpAccessChain %_ptr_StorageBuffer_Light_1 %135 %138 + %133 = OpAccessChain %_ptr_StorageBuffer_v4float_0 %134 %int_1_0 + %132 = OpAccessChain %_ptr_StorageBuffer_float_0 %133 %int_1_1 + %144 = OpLoad %float %132 + %148 = OpAccessChain %_ptr_StorageBuffer__runtimearr_Light_2 %s_lights %int_0_6 + %151 = OpLoad %uint %i + %147 = OpAccessChain %_ptr_StorageBuffer_Light_2 %148 %151 + %146 = OpAccessChain %_ptr_StorageBuffer_v4float_1 %147 %int_1_2 + %145 = OpAccessChain %_ptr_StorageBuffer_float_1 %146 %int_2 + %157 = OpLoad %float %145 + %158 = OpCompositeConstruct %v3float %131 %144 %157 + %159 = OpAccessChain %_ptr_Input_float %in_position_fs %int_0_7 + %162 = OpLoad %float %159 + %163 = OpAccessChain %_ptr_Input_float_0 %in_position_fs %int_1_3 + %166 = OpLoad %float %163 + %167 = OpAccessChain %_ptr_Input_float_1 %in_position_fs %int_2_0 + %170 = OpLoad %float %167 + %171 = OpCompositeConstruct %v3float %162 %166 %170 + %118 = OpFSub %v3float %158 %171 + %172 = OpExtInst %v3float %1 Normalize %118 + %173 = OpDot %float %117 %172 + %174 = OpExtInst %float %1 FMax %float_0 %173 + %91 = OpFMul %float %92 %174 + %178 = OpAccessChain %_ptr_StorageBuffer__runtimearr_Light_3 %s_lights %int_0_8 + %181 = OpLoad %uint %i + %177 = OpAccessChain %_ptr_StorageBuffer_Light_3 %178 %181 + %176 = OpAccessChain %_ptr_StorageBuffer_v4float_2 %177 %int_2_1 + %175 = OpAccessChain %_ptr_StorageBuffer_float_2 %176 %int_0_9 + %187 = OpLoad %float %175 + %191 = OpAccessChain %_ptr_StorageBuffer__runtimearr_Light_4 %s_lights %int_0_10 + %194 = OpLoad %uint %i + %190 = OpAccessChain %_ptr_StorageBuffer_Light_4 %191 %194 + %189 = OpAccessChain %_ptr_StorageBuffer_v4float_3 %190 %int_2_2 + %188 = OpAccessChain %_ptr_StorageBuffer_float_3 %189 %int_1_4 + %200 = OpLoad %float %188 + %204 = OpAccessChain %_ptr_StorageBuffer__runtimearr_Light_5 %s_lights %int_0_11 + %207 = OpLoad %uint %i + %203 = OpAccessChain %_ptr_StorageBuffer_Light_5 %204 %207 + %202 = OpAccessChain %_ptr_StorageBuffer_v4float_4 %203 %int_2_3 + %201 = OpAccessChain %_ptr_StorageBuffer_float_4 %202 %int_2_4 + %213 = OpLoad %float %201 + %214 = OpCompositeConstruct %v3float %187 %200 %213 + %90 = OpVectorTimesScalar %v3float %214 %91 + %88 = OpFAdd %v3float %89 %90 + OpStore %color %88 + OpBranch %70 + %70 = OpLabel + %216 = OpLoad %uint %i + %215 = OpIAdd %uint %216 %uint_1 + OpStore %i %215 + OpBranch %67 + %68 = OpLabel + %219 = OpLoad %v3float %color + %220 = OpCompositeConstruct %v4float %219 %float_1 + OpStore %out_color_fs %220 + OpReturn + OpFunctionEnd diff --git a/tests/out/glsl/functions-webgl.main.Vertex.glsl b/tests/out/glsl/functions-webgl.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/functions-webgl.main.Vertex.glsl rename to tests/out/glsl/functions-webgl.main.Fragment.glsl diff --git a/tests/out/glsl/math-functions.main.Vertex.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/math-functions.main.Vertex.glsl rename to tests/out/glsl/math-functions.main.Fragment.glsl diff --git a/tests/out/glsl/multiview.main.Vertex.glsl b/tests/out/glsl/multiview.main.Fragment.glsl similarity index 67% rename from tests/out/glsl/multiview.main.Vertex.glsl rename to tests/out/glsl/multiview.main.Fragment.glsl index a466f7df9..466aea062 100644 --- a/tests/out/glsl/multiview.main.Vertex.glsl +++ b/tests/out/glsl/multiview.main.Fragment.glsl @@ -7,7 +7,6 @@ precision highp int; void main() { int view_index = gl_ViewIndex; - gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; } diff --git a/tests/out/glsl/multiview_webgl.main.Vertex.glsl b/tests/out/glsl/multiview_webgl.main.Fragment.glsl similarity index 86% rename from tests/out/glsl/multiview_webgl.main.Vertex.glsl rename to tests/out/glsl/multiview_webgl.main.Fragment.glsl index bb8b6e687..30515289c 100644 --- a/tests/out/glsl/multiview_webgl.main.Vertex.glsl +++ b/tests/out/glsl/multiview_webgl.main.Fragment.glsl @@ -4,8 +4,6 @@ precision highp float; precision highp int; -layout(num_views = 2) in; - void main() { int view_index = int(gl_ViewID_OVR); diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config index f72fafd91..98453a04e 100644 --- a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config +++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config @@ -1,3 +1,3 @@ -vertex=(main:vs_5_1 ) -fragment=() +vertex=() +fragment=(main:ps_5_1 ) compute=() diff --git a/tests/out/hlsl/math-functions.hlsl.config b/tests/out/hlsl/math-functions.hlsl.config index f72fafd91..98453a04e 100644 --- a/tests/out/hlsl/math-functions.hlsl.config +++ b/tests/out/hlsl/math-functions.hlsl.config @@ -1,3 +1,3 @@ -vertex=(main:vs_5_1 ) -fragment=() +vertex=() +fragment=(main:ps_5_1 ) compute=() diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index c2aac6ef9..3db4644cd 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -6,7 +6,7 @@ using metal::uint; constant metal::int2 const_type_1_ = {0, 0}; -vertex void main_( +fragment void main_( ) { metal::float4 v = metal::float4(0.0); float a = ((1.0) * 57.295779513082322865); diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index bee60f29e..5f06ee288 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -5,7 +5,8 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %18 "main" +OpEntryPoint Fragment %18 "main" +OpExecutionMode %18 OriginUpperLeft %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 diff --git a/tests/out/spv/multiview.spvasm b/tests/out/spv/multiview.spvasm index bb67d7eba..792dea559 100644 --- a/tests/out/spv/multiview.spvasm +++ b/tests/out/spv/multiview.spvasm @@ -7,8 +7,10 @@ OpCapability MultiView OpExtension "SPV_KHR_multiview" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %8 "main" %5 +OpEntryPoint Fragment %8 "main" %5 +OpExecutionMode %8 OriginUpperLeft OpDecorate %5 BuiltIn ViewIndex +OpDecorate %5 Flat %2 = OpTypeVoid %3 = OpTypeInt 32 1 %6 = OpTypePointer Input %3 diff --git a/tests/out/wgsl/277-casting-vert.wgsl b/tests/out/wgsl/277-casting-frag.wgsl similarity index 90% rename from tests/out/wgsl/277-casting-vert.wgsl rename to tests/out/wgsl/277-casting-frag.wgsl index 045edd83f..26a3db792 100644 --- a/tests/out/wgsl/277-casting-vert.wgsl +++ b/tests/out/wgsl/277-casting-frag.wgsl @@ -5,7 +5,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-frag.wgsl similarity index 95% rename from tests/out/wgsl/280-matrix-cast-vert.wgsl rename to tests/out/wgsl/280-matrix-cast-frag.wgsl index 86df4628e..316d93651 100644 --- a/tests/out/wgsl/280-matrix-cast-vert.wgsl +++ b/tests/out/wgsl/280-matrix-cast-frag.wgsl @@ -6,7 +6,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/484-preprocessor-if-vert.wgsl b/tests/out/wgsl/484-preprocessor-if-frag.wgsl similarity index 86% rename from tests/out/wgsl/484-preprocessor-if-vert.wgsl rename to tests/out/wgsl/484-preprocessor-if-frag.wgsl index 58eb963ce..6b3c4ac97 100644 --- a/tests/out/wgsl/484-preprocessor-if-vert.wgsl +++ b/tests/out/wgsl/484-preprocessor-if-frag.wgsl @@ -2,7 +2,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-frag.wgsl similarity index 93% rename from tests/out/wgsl/896-push-constant-vert.wgsl rename to tests/out/wgsl/896-push-constant-frag.wgsl index eec2204e0..729e35a43 100644 --- a/tests/out/wgsl/896-push-constant-vert.wgsl +++ b/tests/out/wgsl/896-push-constant-frag.wgsl @@ -8,7 +8,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/900-implicit-conversions-vert.wgsl b/tests/out/wgsl/900-implicit-conversions-frag.wgsl similarity index 98% rename from tests/out/wgsl/900-implicit-conversions-vert.wgsl rename to tests/out/wgsl/900-implicit-conversions-frag.wgsl index a5369f98c..97ff5a4fe 100644 --- a/tests/out/wgsl/900-implicit-conversions-vert.wgsl +++ b/tests/out/wgsl/900-implicit-conversions-frag.wgsl @@ -62,7 +62,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-frag.wgsl similarity index 92% rename from tests/out/wgsl/901-lhs-field-select-vert.wgsl rename to tests/out/wgsl/901-lhs-field-select-frag.wgsl index 1b4175809..196f21d79 100644 --- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl +++ b/tests/out/wgsl/901-lhs-field-select-frag.wgsl @@ -6,7 +6,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-frag.wgsl similarity index 92% rename from tests/out/wgsl/931-constant-emitting-vert.wgsl rename to tests/out/wgsl/931-constant-emitting-frag.wgsl index c6b2687e8..ba5d223ef 100644 --- a/tests/out/wgsl/931-constant-emitting-vert.wgsl +++ b/tests/out/wgsl/931-constant-emitting-frag.wgsl @@ -8,7 +8,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-frag.wgsl similarity index 96% rename from tests/out/wgsl/932-for-loop-if-vert.wgsl rename to tests/out/wgsl/932-for-loop-if-frag.wgsl index 7fdd3c613..f9a29ae87 100644 --- a/tests/out/wgsl/932-for-loop-if-vert.wgsl +++ b/tests/out/wgsl/932-for-loop-if-frag.wgsl @@ -17,7 +17,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/binop-frag.wgsl b/tests/out/wgsl/binop-frag.wgsl deleted file mode 100644 index e61d2e0fb..000000000 --- a/tests/out/wgsl/binop-frag.wgsl +++ /dev/null @@ -1,187 +0,0 @@ -var o_color: vec4; - -fn testBinOpVecFloat(a: vec4, b: f32) { - var a1: vec4; - var b1: f32; - var v: vec4; - - a1 = a; - b1 = b; - let e5: vec4 = a1; - v = (e5 * 2.0); - let e8: vec4 = a1; - v = (e8 / vec4(2.0)); - let e12: vec4 = a1; - v = (e12 + vec4(2.0)); - let e16: vec4 = a1; - v = (e16 - vec4(2.0)); - return; -} - -fn testBinOpFloatVec(a2: vec4, b2: f32) { - var a3: vec4; - var b3: f32; - var v1: vec4; - - a3 = a2; - b3 = b2; - let e5: vec4 = a3; - let e6: f32 = b3; - v1 = (e5 * e6); - let e8: vec4 = a3; - let e9: f32 = b3; - v1 = (e8 / vec4(e9)); - let e12: vec4 = a3; - let e13: f32 = b3; - v1 = (e12 + vec4(e13)); - let e16: vec4 = a3; - let e17: f32 = b3; - v1 = (e16 - vec4(e17)); - return; -} - -fn testBinOpIVecInt(a4: vec4, b4: i32) { - var a5: vec4; - var b5: i32; - var v2: vec4; - - a5 = a4; - b5 = b4; - let e5: vec4 = a5; - let e6: i32 = b5; - v2 = (e5 * e6); - let e8: vec4 = a5; - let e9: i32 = b5; - v2 = (e8 / vec4(e9)); - let e12: vec4 = a5; - let e13: i32 = b5; - v2 = (e12 + vec4(e13)); - let e16: vec4 = a5; - let e17: i32 = b5; - v2 = (e16 - vec4(e17)); - let e20: vec4 = a5; - let e21: i32 = b5; - v2 = (e20 & vec4(e21)); - let e24: vec4 = a5; - let e25: i32 = b5; - v2 = (e24 | vec4(e25)); - let e28: vec4 = a5; - let e29: i32 = b5; - v2 = (e28 ^ vec4(e29)); - let e32: vec4 = a5; - let e33: i32 = b5; - v2 = (e32 >> vec4(u32(e33))); - let e37: vec4 = a5; - let e38: i32 = b5; - v2 = (e37 << vec4(u32(e38))); - return; -} - -fn testBinOpIntIVec(a6: i32, b6: vec4) { - var a7: i32; - var b7: vec4; - var v3: vec4; - - a7 = a6; - b7 = b6; - let e5: i32 = a7; - let e6: vec4 = b7; - v3 = (e5 * e6); - let e8: i32 = a7; - let e9: vec4 = b7; - v3 = (vec4(e8) + e9); - let e12: i32 = a7; - let e13: vec4 = b7; - v3 = (vec4(e12) - e13); - let e16: i32 = a7; - let e17: vec4 = b7; - v3 = (vec4(e16) & e17); - let e20: i32 = a7; - let e21: vec4 = b7; - v3 = (vec4(e20) | e21); - let e24: i32 = a7; - let e25: vec4 = b7; - v3 = (vec4(e24) ^ e25); - return; -} - -fn testBinOpUVecUint(a8: vec4, b8: u32) { - var a9: vec4; - var b9: u32; - var v4: vec4; - - a9 = a8; - b9 = b8; - let e5: vec4 = a9; - let e6: u32 = b9; - v4 = (e5 * e6); - let e8: vec4 = a9; - let e9: u32 = b9; - v4 = (e8 / vec4(e9)); - let e12: vec4 = a9; - let e13: u32 = b9; - v4 = (e12 + vec4(e13)); - let e16: vec4 = a9; - let e17: u32 = b9; - v4 = (e16 - vec4(e17)); - let e20: vec4 = a9; - let e21: u32 = b9; - v4 = (e20 & vec4(e21)); - let e24: vec4 = a9; - let e25: u32 = b9; - v4 = (e24 | vec4(e25)); - let e28: vec4 = a9; - let e29: u32 = b9; - v4 = (e28 ^ vec4(e29)); - let e32: vec4 = a9; - let e33: u32 = b9; - v4 = (e32 >> vec4(e33)); - let e36: vec4 = a9; - let e37: u32 = b9; - v4 = (e36 << vec4(e37)); - return; -} - -fn testBinOpUintUVec(a10: u32, b10: vec4) { - var a11: u32; - var b11: vec4; - var v5: vec4; - - a11 = a10; - b11 = b10; - let e5: u32 = a11; - let e6: vec4 = b11; - v5 = (e5 * e6); - let e8: u32 = a11; - let e9: vec4 = b11; - v5 = (vec4(e8) + e9); - let e12: u32 = a11; - let e13: vec4 = b11; - v5 = (vec4(e12) - e13); - let e16: u32 = a11; - let e17: vec4 = b11; - v5 = (vec4(e16) & e17); - let e20: u32 = a11; - let e21: vec4 = b11; - v5 = (vec4(e20) | e21); - let e24: u32 = a11; - let e25: vec4 = b11; - v5 = (vec4(e24) ^ e25); - return; -} - -fn main1() { - let e1: vec4 = o_color; - let e4: vec4 = vec4(1.0); - o_color.x = e4.x; - o_color.y = e4.y; - o_color.z = e4.z; - o_color.w = e4.w; - return; -} - -@fragment -fn main() { - main1(); - return; -} diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-frag.wgsl similarity index 98% rename from tests/out/wgsl/constant-array-size-vert.wgsl rename to tests/out/wgsl/constant-array-size-frag.wgsl index d9ed86654..98d413bdf 100644 --- a/tests/out/wgsl/constant-array-size-vert.wgsl +++ b/tests/out/wgsl/constant-array-size-frag.wgsl @@ -37,7 +37,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/declarations-vert.wgsl b/tests/out/wgsl/declarations-frag.wgsl similarity index 93% rename from tests/out/wgsl/declarations-vert.wgsl rename to tests/out/wgsl/declarations-frag.wgsl index 4b61704b9..107bcaa4f 100644 --- a/tests/out/wgsl/declarations-vert.wgsl +++ b/tests/out/wgsl/declarations-frag.wgsl @@ -13,7 +13,7 @@ struct TestStruct { b: f32, } -struct VertexOutput { +struct FragmentOutput { @location(0) position: vec2, @location(1) a: vec2, @location(2) out_array: vec4, @@ -50,8 +50,8 @@ fn main_1() { return; } -@vertex -fn main(@location(0) position: vec2, @location(1) a: vec2, @location(2) in_array: vec4, @location(3) in_array_1: vec4) -> VertexOutput { +@fragment +fn main(@location(0) position: vec2, @location(1) a: vec2, @location(2) in_array: vec4, @location(3) in_array_1: vec4) -> FragmentOutput { vert.position = position; vert.a = a; in_array_2[0] = in_array; @@ -65,5 +65,5 @@ fn main(@location(0) position: vec2, @location(1) a: vec2, @location(2 let _e32 = frag.a; let _e35 = out_array[0]; let _e37 = out_array[1]; - return VertexOutput(_e30, _e32, _e35, _e37); + return FragmentOutput(_e30, _e32, _e35, _e37); } diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-frag.wgsl similarity index 95% rename from tests/out/wgsl/global-constant-array-vert.wgsl rename to tests/out/wgsl/global-constant-array-frag.wgsl index 880556812..bda27f3f5 100644 --- a/tests/out/wgsl/global-constant-array-vert.wgsl +++ b/tests/out/wgsl/global-constant-array-frag.wgsl @@ -7,7 +7,7 @@ fn main_1() { let _e2 = i; } -@vertex +@fragment fn main() { _ = array(1.0, 2.0); main_1(); diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl index 2ac357020..10f5d2594 100644 --- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -14,7 +14,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); } diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-frag.wgsl similarity index 99% rename from tests/out/wgsl/long-form-matrix-vert.wgsl rename to tests/out/wgsl/long-form-matrix-frag.wgsl index 5048a419a..4a173b63c 100644 --- a/tests/out/wgsl/long-form-matrix-vert.wgsl +++ b/tests/out/wgsl/long-form-matrix-frag.wgsl @@ -34,7 +34,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-frag.wgsl similarity index 99% rename from tests/out/wgsl/math-functions-vert.wgsl rename to tests/out/wgsl/math-functions-frag.wgsl index 0d499fc58..b9049ef23 100644 --- a/tests/out/wgsl/math-functions-vert.wgsl +++ b/tests/out/wgsl/math-functions-frag.wgsl @@ -219,7 +219,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 71ae0fd74..e03648e1c 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -1,4 +1,4 @@ -@vertex +@fragment fn main() { let v = vec4(0.0); let a = degrees(1.0); diff --git a/tests/out/wgsl/multiview.wgsl b/tests/out/wgsl/multiview.wgsl index 3ea9676b8..51192d2f7 100644 --- a/tests/out/wgsl/multiview.wgsl +++ b/tests/out/wgsl/multiview.wgsl @@ -1,4 +1,4 @@ -@vertex +@fragment fn main(@builtin(view_index) view_index: i32) { return; } diff --git a/tests/out/wgsl/vector-functions-vert.wgsl b/tests/out/wgsl/vector-functions-frag.wgsl similarity index 99% rename from tests/out/wgsl/vector-functions-vert.wgsl rename to tests/out/wgsl/vector-functions-frag.wgsl index 29915bf2f..f7dfdd15c 100644 --- a/tests/out/wgsl/vector-functions-vert.wgsl +++ b/tests/out/wgsl/vector-functions-frag.wgsl @@ -215,7 +215,7 @@ fn main_1() { return; } -@vertex +@fragment fn main() { main_1(); return; diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 877b2597b..555dc1239 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -117,7 +117,7 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities) .validate(module) - .expect("Naga module validation failed"); + .expect(&format!("Naga module validation failed on test '{name}'")); #[cfg(feature = "serialize")] { @@ -595,6 +595,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { let _ = env_logger::try_init(); let root = env!("CARGO_MANIFEST_DIR"); + let module = naga::front::spv::parse_u8_slice( &fs::read(format!("{root}/{BASE_DIR_IN}/spv/{name}.spv")).expect("Couldn't find spv file"), &naga::front::spv::Options { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 8baa8e29d..a981d92dd 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -961,8 +961,11 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { check_validation! { "@vertex -fn main() { - discard; +fn main() -> @builtin(position) vec4 { + if true { + discard; + } + return vec4(); }": Err(naga::valid::ValidationError::EntryPoint { stage: naga::ShaderStage::Vertex, @@ -1124,13 +1127,13 @@ fn pointer_type_equivalence() { fn missing_bindings() { check_validation! { " - @vertex - fn vertex(_input: vec4) -> @location(0) vec4 { + @fragment + fn fragment(_input: vec4) -> @location(0) vec4 { return _input; } ": Err(naga::valid::ValidationError::EntryPoint { - stage: naga::ShaderStage::Vertex, + stage: naga::ShaderStage::Fragment, source: naga::valid::EntryPointError::Argument( 0, naga::valid::VaryingError::MissingBinding, @@ -1141,13 +1144,13 @@ fn missing_bindings() { check_validation! { " - @vertex - fn vertex(@location(0) _input: vec4, more_input: f32) -> @location(0) vec4 { + @fragment + fn fragment(@location(0) _input: vec4, more_input: f32) -> @location(0) vec4 { return _input + more_input; } ": Err(naga::valid::ValidationError::EntryPoint { - stage: naga::ShaderStage::Vertex, + stage: naga::ShaderStage::Fragment, source: naga::valid::EntryPointError::Argument( 1, naga::valid::VaryingError::MissingBinding, @@ -1158,13 +1161,13 @@ fn missing_bindings() { check_validation! { " - @vertex - fn vertex(@location(0) _input: vec4) -> vec4 { + @fragment + fn fragment(@location(0) _input: vec4) -> vec4 { return _input; } ": Err(naga::valid::ValidationError::EntryPoint { - stage: naga::ShaderStage::Vertex, + stage: naga::ShaderStage::Fragment, source: naga::valid::EntryPointError::Result( naga::valid::VaryingError::MissingBinding, ), @@ -1174,18 +1177,18 @@ fn missing_bindings() { check_validation! { " - struct VertexIn { + struct FragmentIn { @location(0) pos: vec4, uv: vec2 } - @vertex - fn vertex(_input: VertexIn) -> @location(0) vec4 { + @fragment + fn fragment(_input: FragmentIn) -> @location(0) vec4 { return _input.pos; } ": Err(naga::valid::ValidationError::EntryPoint { - stage: naga::ShaderStage::Vertex, + stage: naga::ShaderStage::Fragment, source: naga::valid::EntryPointError::Argument( 0, naga::valid::VaryingError::MemberMissingBinding(1), @@ -1195,6 +1198,39 @@ fn missing_bindings() { } } +#[test] +fn missing_bindings2() { + check_validation! { + " + @vertex + fn vertex() {} + ": + Err(naga::valid::ValidationError::EntryPoint { + stage: naga::ShaderStage::Vertex, + source: naga::valid::EntryPointError::MissingVertexOutputPosition, + .. + }) + } + + check_validation! { + " + struct VertexOut { + @location(0) a: vec4, + } + + @vertex + fn vertex() -> VertexOut { + return VertexOut(vec4()); + } + ": + Err(naga::valid::ValidationError::EntryPoint { + stage: naga::ShaderStage::Vertex, + source: naga::valid::EntryPointError::MissingVertexOutputPosition, + .. + }) + } +} + #[test] fn invalid_access() { check_validation! { From b99d58ea435090e561377949f428bce2c18451bb Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Wed, 19 Apr 2023 16:59:00 -0400 Subject: [PATCH 1983/2212] Update to version 0.12 --- Cargo.toml | 2 +- cli/Cargo.toml | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8772fa15a..0ddef7b93 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.11.0" +version = "0.12.0" authors = ["Naga Developers"] edition = "2021" description = "Shader translation infrastructure" diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 865130516..ef6f6aff4 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga-cli" -version = "0.11.0" +version = "0.12.0" authors = ["Naga Developers"] edition = "2021" description = "Shader translation command line tool" @@ -10,9 +10,9 @@ keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" [dependencies] -naga = { version = "0.11", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } +naga = { version = "0.12", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } bincode = "1" log = "0.4" codespan-reporting = "0.11" -env_logger = "0.9" +env_logger = "0.10" argh = "0.1.5" From 1421a5e1ab5ca66ecdd1c03998fb0a712ec92bdf Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Thu, 20 Apr 2023 13:39:38 -0400 Subject: [PATCH 1984/2212] refactor(valid)!: remove `TypeError::UnresolvedBase` (#2308) Resolves #2303. --- src/valid/type.rs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/valid/type.rs b/src/valid/type.rs index d8dd37d09..d24cbe958 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -96,8 +96,6 @@ pub enum TypeError { InvalidWidth(crate::ScalarKind, crate::Bytes), #[error("The {0:?} scalar width {1} is not supported for an atomic")] InvalidAtomicWidth(crate::ScalarKind, crate::Bytes), - #[error("The base handle {0:?} can not be resolved")] - UnresolvedBase(Handle), #[error("Invalid type for pointer target {0:?}")] InvalidPointerBase(Handle), #[error("Unsized types like {base:?} must be in the `Storage` address space, not `{space:?}`")] @@ -318,10 +316,6 @@ impl super::Validator { Ti::Pointer { base, space } => { use crate::AddressSpace as As; - if base >= handle { - return Err(TypeError::UnresolvedBase(base)); - } - let base_info = &self.types[base.index()]; if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidPointerBase(base)); @@ -389,9 +383,6 @@ impl super::Validator { ) } Ti::Array { base, size, stride } => { - if base >= handle { - return Err(TypeError::UnresolvedBase(base)); - } let base_info = &self.types[base.index()]; if !base_info.flags.contains(TypeFlags::DATA | TypeFlags::SIZED) { return Err(TypeError::InvalidArrayBaseType(base)); @@ -514,9 +505,6 @@ impl super::Validator { let mut prev_struct_data: Option<(u32, u32)> = None; for (i, member) in members.iter().enumerate() { - if member.ty >= handle { - return Err(TypeError::UnresolvedBase(member.ty)); - } let base_info = &self.types[member.ty.index()]; if !base_info.flags.contains(TypeFlags::DATA) { return Err(TypeError::InvalidData(member.ty)); From 37b3c36a8f1aaa611e0dcfc4892333e83ac3a919 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 24 Apr 2023 21:30:49 -0700 Subject: [PATCH 1985/2212] Support array bindings of buffers (#2282) * Support buffer resource arrays in IR, wgsl-in, and spv-out * spv-out: refactor non-uniform indexing semantics to support buffers * Update the doc comment on BindingArray type * Improve TypeInfo restrictions on binding arrays * Strip DATA out of binding arrays * Include suggested documentation, more binding array tests, enforce structs --- src/back/spv/block.rs | 77 +++++++++------ src/back/spv/helpers.rs | 3 +- src/back/spv/mod.rs | 6 ++ src/back/spv/writer.rs | 24 ++++- src/lib.rs | 17 ++-- src/proc/index.rs | 4 +- src/proc/typifier.rs | 2 + src/valid/interface.rs | 55 ++++++----- src/valid/type.rs | 28 +++++- tests/in/binding-buffer-arrays.param.ron | 14 +++ tests/in/binding-buffer-arrays.wgsl | 27 ++++++ tests/out/spv/binding-arrays.spvasm | 44 ++++----- tests/out/spv/binding-buffer-arrays.spvasm | 105 +++++++++++++++++++++ tests/out/wgsl/binding-buffer-arrays.wgsl | 36 +++++++ tests/snapshots.rs | 4 + tests/wgsl-errors.rs | 27 ++++++ 16 files changed, 380 insertions(+), 93 deletions(-) create mode 100644 tests/in/binding-buffer-arrays.param.ron create mode 100644 tests/in/binding-buffer-arrays.wgsl create mode 100644 tests/out/spv/binding-buffer-arrays.spvasm create mode 100644 tests/out/wgsl/binding-buffer-arrays.wgsl diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 8366df415..37c78bdf9 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -3,8 +3,9 @@ Implementations for `BlockContext` methods. */ use super::{ - index::BoundsCheckResult, make_local, selection::Selection, Block, BlockContext, Dimension, - Error, Instruction, LocalType, LookupType, LoopContext, ResultMember, Writer, WriterFlags, + helpers, index::BoundsCheckResult, make_local, selection::Selection, Block, BlockContext, + Dimension, Error, Instruction, LocalType, LookupType, LoopContext, ResultMember, Writer, + WriterFlags, }; use crate::{arena::Handle, proc::TypeResolution}; use spirv::Word; @@ -196,9 +197,8 @@ impl<'w> BlockContext<'w> { fn is_intermediate(&self, expr_handle: Handle) -> bool { match self.ir_function.expressions[expr_handle] { crate::Expression::GlobalVariable(handle) => { - let ty = self.ir_module.global_variables[handle].ty; - match self.ir_module.types[ty].inner { - crate::TypeInner::BindingArray { .. } => false, + match self.ir_module.global_variables[handle].space { + crate::AddressSpace::Handle => false, _ => true, } } @@ -221,7 +221,6 @@ impl<'w> BlockContext<'w> { block: &mut Block, ) -> Result<(), Error> { let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty); - let id = match self.ir_function.expressions[expr_handle] { crate::Expression::Access { base, index: _ } if self.is_intermediate(base) => { // See `is_intermediate`; we'll handle this later in @@ -237,9 +236,15 @@ impl<'w> BlockContext<'w> { crate::TypeInner::BindingArray { base: binding_type, .. } => { + let space = match self.ir_function.expressions[base] { + crate::Expression::GlobalVariable(gvar) => { + self.ir_module.global_variables[gvar].space + } + _ => unreachable!(), + }; let binding_array_false_pointer = LookupType::Local(LocalType::Pointer { base: binding_type, - class: spirv::StorageClass::UniformConstant, + class: helpers::map_storage_class(space), }); let result_id = match self.write_expression_pointer( @@ -265,15 +270,6 @@ impl<'w> BlockContext<'w> { None, )); - if self.fun_info[index].uniformity.non_uniform_result.is_some() { - self.writer.require_any( - "NonUniformEXT", - &[spirv::Capability::ShaderNonUniform], - )?; - self.writer.use_extension("SPV_EXT_descriptor_indexing"); - self.writer - .decorate(load_id, spirv::Decoration::NonUniform, &[]); - } load_id } ref other => { @@ -316,9 +312,15 @@ impl<'w> BlockContext<'w> { crate::TypeInner::BindingArray { base: binding_type, .. } => { + let space = match self.ir_function.expressions[base] { + crate::Expression::GlobalVariable(gvar) => { + self.ir_module.global_variables[gvar].space + } + _ => unreachable!(), + }; let binding_array_false_pointer = LookupType::Local(LocalType::Pointer { base: binding_type, - class: spirv::StorageClass::UniformConstant, + class: helpers::map_storage_class(space), }); let result_id = match self.write_expression_pointer( @@ -1403,8 +1405,8 @@ impl<'w> BlockContext<'w> { /// Emit any needed bounds-checking expressions to `block`. /// /// Some cases we need to generate a different return type than what the IR gives us. - /// This is because pointers to binding arrays don't exist in the IR, but we need to - /// create them to create an access chain in SPIRV. + /// This is because pointers to binding arrays of handles (such as images or samplers) + /// don't exist in the IR, but we need to create them to create an access chain in SPIRV. /// /// On success, the return value is an [`ExpressionPointer`] value; see the /// documentation for that type. @@ -1434,11 +1436,25 @@ impl<'w> BlockContext<'w> { // but we expect these checks to almost always succeed, and keeping branches to a // minimum is essential. let mut accumulated_checks = None; + // Is true if we are accessing into a binding array of buffers with a non-uniform index. + let mut is_non_uniform_binding_array = false; self.temp_list.clear(); let root_id = loop { expr_handle = match self.ir_function.expressions[expr_handle] { crate::Expression::Access { base, index } => { + if let crate::Expression::GlobalVariable(var_handle) = + self.ir_function.expressions[base] + { + let gvar = &self.ir_module.global_variables[var_handle]; + if let crate::TypeInner::BindingArray { .. } = + self.ir_module.types[gvar.ty].inner + { + is_non_uniform_binding_array |= + self.fun_info[index].uniformity.non_uniform_result.is_some(); + } + } + let index_id = match self.write_bounds_check(base, index, block)? { BoundsCheckResult::KnownInBounds(known_index) => { // Even if the index is known, `OpAccessIndex` @@ -1471,7 +1487,6 @@ impl<'w> BlockContext<'w> { } }; self.temp_list.push(index_id); - base } crate::Expression::AccessIndex { base, index } => { @@ -1494,10 +1509,13 @@ impl<'w> BlockContext<'w> { } }; - let pointer = if self.temp_list.is_empty() { - ExpressionPointer::Ready { - pointer_id: root_id, - } + let (pointer_id, expr_pointer) = if self.temp_list.is_empty() { + ( + root_id, + ExpressionPointer::Ready { + pointer_id: root_id, + }, + ) } else { self.temp_list.reverse(); let pointer_id = self.gen_id(); @@ -1508,16 +1526,21 @@ impl<'w> BlockContext<'w> { // caller to generate the branch, the access, the load or store, and // the zero value (for loads). Otherwise, we can emit the access // ourselves, and just hand them the id of the pointer. - match accumulated_checks { + let expr_pointer = match accumulated_checks { Some(condition) => ExpressionPointer::Conditional { condition, access }, None => { block.body.push(access); ExpressionPointer::Ready { pointer_id } } - } + }; + (pointer_id, expr_pointer) }; + if is_non_uniform_binding_array { + self.writer + .decorate_non_uniform_binding_array_access(pointer_id)?; + } - Ok(pointer) + Ok(expr_pointer) } /// Build the instructions for matrix - matrix column operations diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs index 1ef0db191..5b6226db8 100644 --- a/src/back/spv/helpers.rs +++ b/src/back/spv/helpers.rs @@ -102,7 +102,8 @@ pub fn global_needs_wrapper(ir_module: &crate::Module, var: &crate::GlobalVariab }, None => false, }, - // if it's not a structure, let's wrap it to be able to put "Block" + crate::TypeInner::BindingArray { .. } => false, + // if it's not a structure or a binding array, let's wrap it to be able to put "Block" _ => true, } } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 9b084911b..adc3dd7a7 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -288,9 +288,15 @@ enum LocalType { image_type_id: Word, }, Sampler, + /// Equivalent to a [`LocalType::Pointer`] whose `base` is a Naga IR [`BindingArray`]. SPIR-V + /// permits duplicated `OpTypePointer` ids, so it's fine to have two different [`LocalType`] + /// representations for pointer types. + /// + /// [`BindingArray`]: crate::TypeInner::BindingArray PointerToBindingArray { base: Handle, size: u64, + space: crate::AddressSpace, }, BindingArray { base: Handle, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index ba235e6d0..90c6b5089 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -940,10 +940,11 @@ impl Writer { let scalar_id = self.get_constant_scalar(crate::ScalarValue::Uint(size), 4); Instruction::type_array(id, inner_ty, scalar_id) } - LocalType::PointerToBindingArray { base, size } => { + LocalType::PointerToBindingArray { base, size, space } => { let inner_ty = self.get_type_id(LookupType::Local(LocalType::BindingArray { base, size })); - Instruction::type_pointer(id, spirv::StorageClass::UniformConstant, inner_ty) + let class = map_storage_class(space); + Instruction::type_pointer(id, class, inner_ty) } LocalType::AccelerationStructure => Instruction::type_acceleration_structure(id), LocalType::RayQuery => Instruction::type_ray_query(id), @@ -1579,6 +1580,9 @@ impl Writer { } } + // Note: we should be able to substitute `binding_array`, + // but there is still code that tries to register the pre-substituted type, + // and it is failing on 0. let mut substitute_inner_type_lookup = None; if let Some(ref res_binding) = global_variable.binding { self.decorate(id, Decoration::DescriptorSet, &[res_binding.group]); @@ -1595,6 +1599,7 @@ impl Writer { Some(LookupType::Local(LocalType::PointerToBindingArray { base, size: remapped_binding_array_size as u64, + space: global_variable.space, })) } } else { @@ -1635,7 +1640,13 @@ impl Writer { // a runtime-sized array. In this case, we need to decorate it with // Block. if let crate::AddressSpace::Storage { .. } = global_variable.space { - self.decorate(inner_type_id, Decoration::Block, &[]); + let decorated_id = match ir_module.types[global_variable.ty].inner { + crate::TypeInner::BindingArray { base, .. } => { + self.get_type_id(LookupType::Handle(base)) + } + _ => inner_type_id, + }; + self.decorate(decorated_id, Decoration::Block, &[]); } if substitute_inner_type_lookup.is_some() { inner_type_id @@ -1955,6 +1966,13 @@ impl Writer { pub const fn get_capabilities_used(&self) -> &crate::FastHashSet { &self.capabilities_used } + + pub fn decorate_non_uniform_binding_array_access(&mut self, id: Word) -> Result<(), Error> { + self.require_any("NonUniformEXT", &[spirv::Capability::ShaderNonUniform])?; + self.use_extension("SPV_EXT_descriptor_indexing"); + self.decorate(id, spirv::Decoration::NonUniform, &[]); + Ok(()) + } } #[test] diff --git a/src/lib.rs b/src/lib.rs index a70015d16..e744b7d40 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -200,7 +200,8 @@ tree. clippy::match_like_matches_macro, clippy::collapsible_if, clippy::derive_partial_eq_without_eq, - clippy::needless_borrowed_reference + clippy::needless_borrowed_reference, + clippy::single_match )] #![warn( trivial_casts, @@ -752,13 +753,12 @@ pub enum TypeInner { /// buffers could have elements that are dynamically sized arrays, each with /// a different length. /// - /// Binding arrays are not [`DATA`]. This means that all binding array - /// globals must be placed in the [`Handle`] address space. Referring to - /// such a global produces a `BindingArray` value directly; there are never - /// pointers to binding arrays. The only operation permitted on - /// `BindingArray` values is indexing, which yields the element by value, - /// not a pointer to the element. (This means that buffer array contents - /// cannot be stored to; [naga#1864] covers lifting this restriction.) + /// Binding arrays are in the same address spaces as their underlying type. + /// As such, referring to an array of images produces an [`Image`] value + /// directly (as opposed to a pointer). The only operation permitted on + /// `BindingArray` values is indexing, which works transparently: indexing + /// a binding array of samplers yields a [`Sampler`], indexing a pointer to the + /// binding array of storage buffers produces a pointer to the storage struct. /// /// Unlike textures and samplers, binding arrays are not [`ARGUMENT`], so /// they cannot be passed as arguments to functions. @@ -774,7 +774,6 @@ pub enum TypeInner { /// [`SamplerArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.SamplerArray /// [`BufferArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.BufferArray /// [`DATA`]: crate::valid::TypeFlags::DATA - /// [`Handle`]: AddressSpace::Handle /// [`ARGUMENT`]: crate::valid::TypeFlags::ARGUMENT /// [naga#1864]: https://github.com/gfx-rs/naga/issues/1864 BindingArray { base: Handle, size: ArraySize }, diff --git a/src/proc/index.rs b/src/proc/index.rs index 3fea79ec0..aaf8ee11b 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -390,7 +390,9 @@ impl crate::TypeInner { match *base_inner { Ti::Vector { size, .. } => size as _, Ti::Matrix { columns, .. } => columns as _, - Ti::Array { size, .. } => return size.to_indexable_length(module), + Ti::Array { size, .. } | Ti::BindingArray { size, .. } => { + return size.to_indexable_length(module) + } _ => return Err(IndexableLengthError::TypeNotIndexable), } } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 0bb9019a2..ad77b0ed6 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -298,6 +298,7 @@ impl<'a> ResolveContext<'a> { width, space, }, + Ti::BindingArray { base, .. } => Ti::Pointer { base, space }, ref other => { log::error!("Access sub-type {:?}", other); return Err(ResolveError::InvalidSubAccess { @@ -401,6 +402,7 @@ impl<'a> ResolveContext<'a> { space, } } + Ti::BindingArray { base, .. } => Ti::Pointer { base, space }, ref other => { log::error!("Access index sub-type {:?}", other); return Err(ResolveError::InvalidSubAccess { diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 268490c52..1fafef2f6 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -400,7 +400,14 @@ impl super::Validator { use super::TypeFlags; log::debug!("var {:?}", var); - let type_info = &self.types[var.ty.index()]; + let inner_ty = match types[var.ty].inner { + // A binding array is (mostly) supposed to behave the same as a + // series of individually bound resources, so we can (mostly) + // validate a `binding_array` as if it were just a plain `T`. + crate::TypeInner::BindingArray { base, .. } => base, + _ => var.ty, + }; + let type_info = &self.types[inner_ty.index()]; let (required_type_flags, is_resource) = match var.space { crate::AddressSpace::Function => { @@ -437,22 +444,8 @@ impl super::Validator { ) } crate::AddressSpace::Handle => { - match types[var.ty].inner { - crate::TypeInner::Image { .. } - | crate::TypeInner::Sampler { .. } - | crate::TypeInner::BindingArray { .. } - | crate::TypeInner::AccelerationStructure - | crate::TypeInner::RayQuery => {} - _ => { - return Err(GlobalVariableError::InvalidType(var.space)); - } - }; - let inner_ty = match &types[var.ty].inner { - &crate::TypeInner::BindingArray { base, .. } => &types[base].inner, - ty => ty, - }; - if let crate::TypeInner::Image { - class: + match types[inner_ty].inner { + crate::TypeInner::Image { class, .. } => match class { crate::ImageClass::Storage { format: crate::StorageFormat::R16Unorm @@ -462,17 +455,23 @@ impl super::Validator { | crate::StorageFormat::Rgba16Unorm | crate::StorageFormat::Rgba16Snorm, .. - }, - .. - } = *inner_ty - { - if !self - .capabilities - .contains(Capabilities::STORAGE_TEXTURE_16BIT_NORM_FORMATS) - { - return Err(GlobalVariableError::UnsupportedCapability( - Capabilities::STORAGE_TEXTURE_16BIT_NORM_FORMATS, - )); + } => { + if !self + .capabilities + .contains(Capabilities::STORAGE_TEXTURE_16BIT_NORM_FORMATS) + { + return Err(GlobalVariableError::UnsupportedCapability( + Capabilities::STORAGE_TEXTURE_16BIT_NORM_FORMATS, + )); + } + } + _ => {} + }, + crate::TypeInner::Sampler { .. } + | crate::TypeInner::AccelerationStructure + | crate::TypeInner::RayQuery => {} + _ => { + return Err(GlobalVariableError::InvalidType(var.space)); } } diff --git a/src/valid/type.rs b/src/valid/type.rs index d24cbe958..1838ce88a 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -117,6 +117,8 @@ pub enum TypeError { InvalidArrayStride { stride: u32, expected: u32 }, #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] InvalidDynamicArray(String, Handle), + #[error("The base handle {0:?} has to be a struct")] + BindingArrayBaseTypeNotStruct(Handle), #[error("Structure member[{index}] at {offset} overlaps the previous member")] MemberOverlap { index: u32, offset: u32 }, #[error( @@ -612,13 +614,35 @@ impl super::Validator { } Ti::AccelerationStructure => { self.require_type_capability(Capabilities::RAY_QUERY)?; - TypeInfo::new(TypeFlags::empty(), Alignment::ONE) + TypeInfo::new(TypeFlags::ARGUMENT, Alignment::ONE) } Ti::RayQuery => { self.require_type_capability(Capabilities::RAY_QUERY)?; TypeInfo::new(TypeFlags::DATA | TypeFlags::SIZED, Alignment::ONE) } - Ti::BindingArray { .. } => TypeInfo::new(TypeFlags::empty(), Alignment::ONE), + Ti::BindingArray { base, size } => { + if base >= handle { + return Err(TypeError::InvalidArrayBaseType(base)); + } + let type_info_mask = match size { + crate::ArraySize::Constant(_) => TypeFlags::SIZED | TypeFlags::HOST_SHAREABLE, + crate::ArraySize::Dynamic => { + // Final type is non-sized + TypeFlags::HOST_SHAREABLE + } + }; + let base_info = &self.types[base.index()]; + + if base_info.flags.contains(TypeFlags::DATA) { + // Currently Naga only supports binding arrays of structs for non-handle types. + match types[base].inner { + crate::TypeInner::Struct { .. } => {} + _ => return Err(TypeError::BindingArrayBaseTypeNotStruct(base)), + }; + } + + TypeInfo::new(base_info.flags & type_info_mask, Alignment::ONE) + } }) } } diff --git a/tests/in/binding-buffer-arrays.param.ron b/tests/in/binding-buffer-arrays.param.ron new file mode 100644 index 000000000..4f653bb21 --- /dev/null +++ b/tests/in/binding-buffer-arrays.param.ron @@ -0,0 +1,14 @@ +( + god_mode: false, + spv: ( + version: (1, 1), + binding_map: { + (group: 0, binding: 0): (binding_array_size: Some(10)), + }, + ), + bounds_check_policies: ( + index: ReadZeroSkipWrite, + buffer: ReadZeroSkipWrite, + image: ReadZeroSkipWrite, + ) +) diff --git a/tests/in/binding-buffer-arrays.wgsl b/tests/in/binding-buffer-arrays.wgsl new file mode 100644 index 000000000..a76d52c20 --- /dev/null +++ b/tests/in/binding-buffer-arrays.wgsl @@ -0,0 +1,27 @@ +struct UniformIndex { + index: u32 +} + +struct Foo { x: u32 } +@group(0) @binding(0) +var storage_array: binding_array; +@group(0) @binding(10) +var uni: UniformIndex; + +struct FragmentIn { + @location(0) index: u32, +} + +@fragment +fn main(fragment_in: FragmentIn) -> @location(0) u32 { + let uniform_index = uni.index; + let non_uniform_index = fragment_in.index; + + var u1 = 0u; + + u1 += storage_array[0].x; + u1 += storage_array[uniform_index].x; + u1 += storage_array[non_uniform_index].x; + + return u1; +} diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 30cf4847c..31929d155 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -35,28 +35,28 @@ OpMemberDecorate %49 0 Offset 0 OpDecorate %65 Location 0 OpDecorate %65 Flat OpDecorate %68 Location 0 -OpDecorate %97 NonUniform -OpDecorate %121 NonUniform -OpDecorate %123 NonUniform -OpDecorate %148 NonUniform -OpDecorate %150 NonUniform -OpDecorate %188 NonUniform -OpDecorate %219 NonUniform -OpDecorate %238 NonUniform -OpDecorate %257 NonUniform -OpDecorate %279 NonUniform -OpDecorate %281 NonUniform -OpDecorate %303 NonUniform -OpDecorate %305 NonUniform -OpDecorate %327 NonUniform -OpDecorate %329 NonUniform -OpDecorate %351 NonUniform -OpDecorate %353 NonUniform -OpDecorate %375 NonUniform -OpDecorate %377 NonUniform -OpDecorate %399 NonUniform -OpDecorate %401 NonUniform -OpDecorate %424 NonUniform +OpDecorate %96 NonUniform +OpDecorate %120 NonUniform +OpDecorate %122 NonUniform +OpDecorate %147 NonUniform +OpDecorate %149 NonUniform +OpDecorate %187 NonUniform +OpDecorate %218 NonUniform +OpDecorate %237 NonUniform +OpDecorate %256 NonUniform +OpDecorate %278 NonUniform +OpDecorate %280 NonUniform +OpDecorate %302 NonUniform +OpDecorate %304 NonUniform +OpDecorate %326 NonUniform +OpDecorate %328 NonUniform +OpDecorate %350 NonUniform +OpDecorate %352 NonUniform +OpDecorate %374 NonUniform +OpDecorate %376 NonUniform +OpDecorate %398 NonUniform +OpDecorate %400 NonUniform +OpDecorate %423 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 5 diff --git a/tests/out/spv/binding-buffer-arrays.spvasm b/tests/out/spv/binding-buffer-arrays.spvasm new file mode 100644 index 000000000..cd73bd756 --- /dev/null +++ b/tests/out/spv/binding-buffer-arrays.spvasm @@ -0,0 +1,105 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 66 +OpCapability Shader +OpCapability ShaderNonUniform +OpExtension "SPV_KHR_storage_buffer_storage_class" +OpExtension "SPV_EXT_descriptor_indexing" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %29 "main" %24 %27 +OpExecutionMode %29 OriginUpperLeft +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %11 0 Offset 0 +OpDecorate %12 NonWritable +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 0 +OpDecorate %9 Block +OpDecorate %16 DescriptorSet 0 +OpDecorate %16 Binding 10 +OpDecorate %17 Block +OpMemberDecorate %17 0 Offset 0 +OpDecorate %24 Location 0 +OpDecorate %24 Flat +OpDecorate %27 Location 0 +OpDecorate %57 NonUniform +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 1 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 0 +%7 = OpConstant %4 0 +%8 = OpTypeStruct %6 +%9 = OpTypeStruct %6 +%10 = OpTypeArray %9 %3 +%11 = OpTypeStruct %6 +%15 = OpConstant %6 10 +%14 = OpTypeArray %9 %15 +%13 = OpTypePointer StorageBuffer %14 +%12 = OpVariable %13 StorageBuffer +%17 = OpTypeStruct %8 +%18 = OpTypePointer Uniform %17 +%16 = OpVariable %18 Uniform +%20 = OpTypePointer Function %6 +%21 = OpConstantNull %6 +%25 = OpTypePointer Input %6 +%24 = OpVariable %25 Input +%28 = OpTypePointer Output %6 +%27 = OpVariable %28 Output +%30 = OpTypeFunction %2 +%31 = OpTypePointer Uniform %8 +%33 = OpTypePointer StorageBuffer %10 +%35 = OpTypePointer Uniform %6 +%39 = OpTypePointer StorageBuffer %9 +%40 = OpTypePointer StorageBuffer %6 +%45 = OpConstant %6 1 +%47 = OpTypeBool +%49 = OpConstantNull %6 +%58 = OpConstantNull %6 +%29 = OpFunction %2 None %30 +%22 = OpLabel +%19 = OpVariable %20 Function %21 +%26 = OpLoad %6 %24 +%23 = OpCompositeConstruct %11 %26 +%32 = OpAccessChain %31 %16 %5 +OpBranch %34 +%34 = OpLabel +%36 = OpAccessChain %35 %32 %5 +%37 = OpLoad %6 %36 +%38 = OpCompositeExtract %6 %23 0 +OpStore %19 %5 +%41 = OpAccessChain %40 %12 %5 %5 +%42 = OpLoad %6 %41 +%43 = OpLoad %6 %19 +%44 = OpIAdd %6 %43 %42 +OpStore %19 %44 +%46 = OpULessThan %47 %37 %45 +OpSelectionMerge %50 None +OpBranchConditional %46 %51 %50 +%51 = OpLabel +%48 = OpAccessChain %40 %12 %37 %5 +%52 = OpLoad %6 %48 +OpBranch %50 +%50 = OpLabel +%53 = OpPhi %6 %49 %34 %52 %51 +%54 = OpLoad %6 %19 +%55 = OpIAdd %6 %54 %53 +OpStore %19 %55 +%56 = OpULessThan %47 %38 %45 +OpSelectionMerge %59 None +OpBranchConditional %56 %60 %59 +%60 = OpLabel +%57 = OpAccessChain %40 %12 %38 %5 +%61 = OpLoad %6 %57 +OpBranch %59 +%59 = OpLabel +%62 = OpPhi %6 %58 %50 %61 %60 +%63 = OpLoad %6 %19 +%64 = OpIAdd %6 %63 %62 +OpStore %19 %64 +%65 = OpLoad %6 %19 +OpStore %27 %65 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/binding-buffer-arrays.wgsl b/tests/out/wgsl/binding-buffer-arrays.wgsl new file mode 100644 index 000000000..0c9cd5003 --- /dev/null +++ b/tests/out/wgsl/binding-buffer-arrays.wgsl @@ -0,0 +1,36 @@ +struct UniformIndex { + index: u32, +} + +struct Foo { + x: u32, +} + +struct FragmentIn { + @location(0) index: u32, +} + +@group(0) @binding(0) +var storage_array: binding_array; +@group(0) @binding(10) +var uni: UniformIndex; + +@fragment +fn main(fragment_in: FragmentIn) -> @location(0) u32 { + var u1_: u32; + + let uniform_index = uni.index; + let non_uniform_index = fragment_in.index; + u1_ = 0u; + let _e11 = storage_array[0].x; + let _e12 = u1_; + u1_ = (_e12 + _e11); + let _e17 = storage_array[uniform_index].x; + let _e18 = u1_; + u1_ = (_e18 + _e17); + let _e23 = storage_array[non_uniform_index].x; + let _e24 = u1_; + u1_ = (_e24 + _e23); + let _e26 = u1_; + return _e26; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 555dc1239..8e75f5b74 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -558,6 +558,10 @@ fn convert_wgsl() { "binding-arrays", Targets::WGSL | Targets::HLSL | Targets::METAL | Targets::SPIRV, ), + ( + "binding-buffer-arrays", + Targets::WGSL | Targets::SPIRV, //TODO: more backends, eventually merge into "binding-arrays" + ), ("resource-binding-map", Targets::METAL), ("multiview", Targets::SPIRV | Targets::GLSL | Targets::WGSL), ("multiview_webgl", Targets::GLSL), diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index a981d92dd..8bd13dacf 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1856,3 +1856,30 @@ fn function_returns_void() { "###, ) } + +#[test] +fn binding_array_local() { + check_validation! { + "fn f() { var x: binding_array; }": + Err(_) + } +} + +#[test] +fn binding_array_private() { + check_validation! { + "var x: binding_array;": + Err(_) + } +} + +#[test] +fn binding_array_non_struct() { + check_validation! { + "var x: binding_array;": + Err(naga::valid::ValidationError::Type { + source: naga::valid::TypeError::BindingArrayBaseTypeNotStruct(_), + .. + }) + } +} From 9befaed7e985fb9a23322e9f19baf2a95bfd8b9c Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Tue, 25 Apr 2023 08:49:26 -0400 Subject: [PATCH 1986/2212] [hlsl-out] Fix return type for firstbitlow/high (#2315) --- src/back/hlsl/writer.rs | 47 +++++++--- tests/in/math-functions.wgsl | 7 ++ .../glsl/math-functions.main.Fragment.glsl | 11 ++- tests/out/hlsl/math-functions.hlsl | 25 ++++-- tests/out/msl/math-functions.msl | 9 ++ tests/out/spv/math-functions.spvasm | 89 +++++++++++-------- tests/out/wgsl/math-functions.wgsl | 7 ++ 7 files changed, 132 insertions(+), 63 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index a3810c5da..9e541ae0a 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2574,6 +2574,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Unpack2x16float, Regular(&'static str), MissingIntOverload(&'static str), + MissingIntReturnType(&'static str), CountTrailingZeros, CountLeadingZeros, } @@ -2642,8 +2643,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::CountLeadingZeros => Function::CountLeadingZeros, Mf::CountOneBits => Function::MissingIntOverload("countbits"), Mf::ReverseBits => Function::MissingIntOverload("reversebits"), - Mf::FindLsb => Function::Regular("firstbitlow"), - Mf::FindMsb => Function::Regular("firstbithigh"), + Mf::FindLsb => Function::MissingIntReturnType("firstbitlow"), + Mf::FindMsb => Function::MissingIntReturnType("firstbithigh"), Mf::Unpack2x16float => Function::Unpack2x16float, _ => return Err(Error::Unimplemented(format!("write_expr_math {fun:?}"))), }; @@ -2707,6 +2708,21 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; } } + Function::MissingIntReturnType(fun_name) => { + let scalar_kind = &func_ctx.info[arg] + .ty + .inner_with(&module.types) + .scalar_kind(); + if let Some(ScalarKind::Sint) = *scalar_kind { + write!(self.out, "asint({fun_name}(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))")?; + } else { + write!(self.out, "{fun_name}(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ")")?; + } + } Function::CountTrailingZeros => { match *func_ctx.info[arg].ty.inner_with(&module.types) { TypeInner::Vector { size, kind, .. } => { @@ -2721,9 +2737,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, arg, func_ctx)?; write!(self.out, "))")?; } else { - write!(self.out, "asint(min((32u){s}, asuint(firstbitlow(")?; + write!(self.out, "asint(min((32u){s}, firstbitlow(")?; self.write_expr(module, arg, func_ctx)?; - write!(self.out, "))))")?; + write!(self.out, ")))")?; } } TypeInner::Scalar { kind, .. } => { @@ -2732,9 +2748,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, arg, func_ctx)?; write!(self.out, "))")?; } else { - write!(self.out, "asint(min(32u, asuint(firstbitlow(")?; + write!(self.out, "asint(min(32u, firstbitlow(")?; self.write_expr(module, arg, func_ctx)?; - write!(self.out, "))))")?; + write!(self.out, ")))")?; } } _ => unreachable!(), @@ -2752,31 +2768,36 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; if let ScalarKind::Uint = kind { - write!(self.out, "asuint((31){s} - firstbithigh(")?; + write!(self.out, "((31u){s} - firstbithigh(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))")?; } else { write!(self.out, "(")?; self.write_expr(module, arg, func_ctx)?; write!( self.out, - " < (0){s} ? (0){s} : (31){s} - firstbithigh(" + " < (0){s} ? (0){s} : (31){s} - asint(firstbithigh(" )?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ")))")?; } } TypeInner::Scalar { kind, .. } => { if let ScalarKind::Uint = kind { - write!(self.out, "asuint(31 - firstbithigh(")?; + write!(self.out, "(31u - firstbithigh(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "))")?; } else { write!(self.out, "(")?; self.write_expr(module, arg, func_ctx)?; - write!(self.out, " < 0 ? 0 : 31 - firstbithigh(")?; + write!(self.out, " < 0 ? 0 : 31 - asint(firstbithigh(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ")))")?; } } _ => unreachable!(), } - self.write_expr(module, arg, func_ctx)?; - write!(self.out, "))")?; - return Ok(()); } } diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index da67ca23e..efeb988f5 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -10,6 +10,13 @@ fn main() { let g = refract(v, v, f); let const_dot = dot(vec2(), vec2()); let first_leading_bit_abs = firstLeadingBit(abs(0u)); + let flb_a = firstLeadingBit(-1); + let flb_b = firstLeadingBit(vec2(-1)); + let flb_c = firstLeadingBit(vec2(1u)); + let ftb_a = firstTrailingBit(-1); + let ftb_b = firstTrailingBit(1u); + let ftb_c = firstTrailingBit(vec2(-1)); + let ftb_d = firstTrailingBit(vec2(1u)); let ctz_a = countTrailingZeros(0u); let ctz_b = countTrailingZeros(0); let ctz_c = countTrailingZeros(0xFFFFFFFFu); diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl index 3c5c1dd34..11c3be188 100644 --- a/tests/out/glsl/math-functions.main.Fragment.glsl +++ b/tests/out/glsl/math-functions.main.Fragment.glsl @@ -14,6 +14,13 @@ void main() { vec4 g = refract(v, v, 1.0); int const_dot = ( + ivec2(0, 0).x * ivec2(0, 0).x + ivec2(0, 0).y * ivec2(0, 0).y); uint first_leading_bit_abs = uint(findMSB(uint(abs(int(0u))))); + int flb_a = findMSB(-1); + ivec2 flb_b = findMSB(ivec2(-1)); + uvec2 flb_c = uvec2(findMSB(uvec2(1u))); + int ftb_a = findLSB(-1); + uint ftb_b = uint(findLSB(1u)); + ivec2 ftb_c = findLSB(ivec2(-1)); + uvec2 ftb_d = uvec2(findLSB(uvec2(1u))); uint ctz_a = min(uint(findLSB(0u)), 32u); int ctz_b = int(min(uint(findLSB(0)), 32u)); uint ctz_c = min(uint(findLSB(4294967295u)), 32u); @@ -24,8 +31,8 @@ void main() { ivec2 ctz_h = ivec2(min(uvec2(findLSB(ivec2(1))), uvec2(32u))); int clz_a = (-1 < 0 ? 0 : 31 - findMSB(-1)); uint clz_b = uint(31 - findMSB(1u)); - ivec2 _e40 = ivec2(-1); - ivec2 clz_c = mix(ivec2(31) - findMSB(_e40), ivec2(0), lessThan(_e40, ivec2(0))); + ivec2 _e58 = ivec2(-1); + ivec2 clz_c = mix(ivec2(31) - findMSB(_e58), ivec2(0), lessThan(_e58, ivec2(0))); uvec2 clz_d = uvec2(ivec2(31) - findMSB(uvec2(1u))); } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index 958e77d80..04a9843cb 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -10,17 +10,24 @@ void main() float4 g = refract(v, v, 1.0); int const_dot = dot(int2(0, 0), int2(0, 0)); uint first_leading_bit_abs = firstbithigh(abs(0u)); + int flb_a = asint(firstbithigh(-1)); + int2 flb_b = asint(firstbithigh((-1).xx)); + uint2 flb_c = firstbithigh((1u).xx); + int ftb_a = asint(firstbitlow(-1)); + uint ftb_b = firstbitlow(1u); + int2 ftb_c = asint(firstbitlow((-1).xx)); + uint2 ftb_d = firstbitlow((1u).xx); uint ctz_a = min(32u, firstbitlow(0u)); - int ctz_b = asint(min(32u, asuint(firstbitlow(0)))); + int ctz_b = asint(min(32u, firstbitlow(0))); uint ctz_c = min(32u, firstbitlow(4294967295u)); - int ctz_d = asint(min(32u, asuint(firstbitlow(-1)))); + int ctz_d = asint(min(32u, firstbitlow(-1))); uint2 ctz_e = min((32u).xx, firstbitlow((0u).xx)); - int2 ctz_f = asint(min((32u).xx, asuint(firstbitlow((0).xx)))); + int2 ctz_f = asint(min((32u).xx, firstbitlow((0).xx))); uint2 ctz_g = min((32u).xx, firstbitlow((1u).xx)); - int2 ctz_h = asint(min((32u).xx, asuint(firstbitlow((1).xx)))); - int clz_a = (-1 < 0 ? 0 : 31 - firstbithigh(-1)); - uint clz_b = asuint(31 - firstbithigh(1u)); - int2 _expr40 = (-1).xx; - int2 clz_c = (_expr40 < (0).xx ? (0).xx : (31).xx - firstbithigh(_expr40)); - uint2 clz_d = asuint((31).xx - firstbithigh((1u).xx)); + int2 ctz_h = asint(min((32u).xx, firstbitlow((1).xx))); + int clz_a = (-1 < 0 ? 0 : 31 - asint(firstbithigh(-1))); + uint clz_b = (31u - firstbithigh(1u)); + int2 _expr58 = (-1).xx; + int2 clz_c = (_expr58 < (0).xx ? (0).xx : (31).xx - asint(firstbithigh(_expr58))); + uint2 clz_d = ((31u).xx - firstbithigh((1u).xx)); } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 3db4644cd..04eb9d85f 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -18,6 +18,15 @@ fragment void main_( int const_dot = ( + const_type_1_.x * const_type_1_.x + const_type_1_.y * const_type_1_.y); uint _e13 = metal::abs(0u); uint first_leading_bit_abs = metal::select(31 - metal::clz(_e13), uint(-1), _e13 == 0 || _e13 == -1); + int flb_a = metal::select(31 - metal::clz(metal::select(-1, ~-1, -1 < 0)), int(-1), -1 == 0 || -1 == -1); + metal::int2 _e18 = metal::int2(-1); + metal::int2 flb_b = metal::select(31 - metal::clz(metal::select(_e18, ~_e18, _e18 < 0)), int2(-1), _e18 == 0 || _e18 == -1); + metal::uint2 _e21 = metal::uint2(1u); + metal::uint2 flb_c = metal::select(31 - metal::clz(_e21), uint2(-1), _e21 == 0 || _e21 == -1); + int ftb_a = (((metal::ctz(-1) + 1) % 33) - 1); + uint ftb_b = (((metal::ctz(1u) + 1) % 33) - 1); + metal::int2 ftb_c = (((metal::ctz(metal::int2(-1)) + 1) % 33) - 1); + metal::uint2 ftb_d = (((metal::ctz(metal::uint2(1u)) + 1) % 33) - 1); uint ctz_a = metal::ctz(0u); int ctz_b = metal::ctz(0); uint ctz_c = metal::ctz(4294967295u); diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 5f06ee288..8dc763c0d 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 76 +; Bound: 87 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -15,9 +15,9 @@ OpExecutionMode %18 OriginUpperLeft %6 = OpConstant %7 0 %9 = OpTypeInt 32 0 %8 = OpConstant %9 0 -%10 = OpConstant %9 4294967295 -%11 = OpConstant %7 -1 -%12 = OpConstant %9 1 +%10 = OpConstant %7 -1 +%11 = OpConstant %9 1 +%12 = OpConstant %9 4294967295 %13 = OpConstant %7 1 %14 = OpTypeVector %4 4 %15 = OpTypeVector %7 2 @@ -26,11 +26,11 @@ OpExecutionMode %18 OriginUpperLeft %27 = OpConstantComposite %14 %5 %5 %5 %5 %28 = OpConstantComposite %14 %3 %3 %3 %3 %31 = OpConstantNull %7 -%42 = OpConstant %9 32 -%50 = OpTypeVector %9 2 -%53 = OpConstantComposite %50 %42 %42 -%65 = OpConstant %7 31 -%71 = OpConstantComposite %15 %65 %65 +%44 = OpTypeVector %9 2 +%54 = OpConstant %9 32 +%64 = OpConstantComposite %44 %54 %54 +%76 = OpConstant %7 31 +%82 = OpConstantComposite %15 %76 %76 %18 = OpFunction %2 None %19 %17 = OpLabel OpBranch %20 @@ -52,35 +52,46 @@ OpBranch %20 %30 = OpIAdd %7 %35 %38 %39 = OpCopyObject %9 %8 %40 = OpExtInst %9 %1 FindUMsb %39 -%43 = OpExtInst %9 %1 FindILsb %8 -%41 = OpExtInst %9 %1 UMin %42 %43 -%45 = OpExtInst %7 %1 FindILsb %6 -%44 = OpExtInst %7 %1 UMin %42 %45 -%47 = OpExtInst %9 %1 FindILsb %10 -%46 = OpExtInst %9 %1 UMin %42 %47 -%49 = OpExtInst %7 %1 FindILsb %11 -%48 = OpExtInst %7 %1 UMin %42 %49 -%51 = OpCompositeConstruct %50 %8 %8 -%54 = OpExtInst %50 %1 FindILsb %51 -%52 = OpExtInst %50 %1 UMin %53 %54 -%55 = OpCompositeConstruct %15 %6 %6 -%57 = OpExtInst %15 %1 FindILsb %55 -%56 = OpExtInst %15 %1 UMin %53 %57 -%58 = OpCompositeConstruct %50 %12 %12 -%60 = OpExtInst %50 %1 FindILsb %58 -%59 = OpExtInst %50 %1 UMin %53 %60 -%61 = OpCompositeConstruct %15 %13 %13 -%63 = OpExtInst %15 %1 FindILsb %61 -%62 = OpExtInst %15 %1 UMin %53 %63 -%66 = OpExtInst %7 %1 FindUMsb %11 -%64 = OpISub %7 %65 %66 -%68 = OpExtInst %7 %1 FindUMsb %12 -%67 = OpISub %9 %65 %68 -%69 = OpCompositeConstruct %15 %11 %11 -%72 = OpExtInst %15 %1 FindUMsb %69 -%70 = OpISub %15 %71 %72 -%73 = OpCompositeConstruct %50 %12 %12 -%75 = OpExtInst %15 %1 FindUMsb %73 -%74 = OpISub %50 %71 %75 +%41 = OpExtInst %7 %1 FindSMsb %10 +%42 = OpCompositeConstruct %15 %10 %10 +%43 = OpExtInst %15 %1 FindSMsb %42 +%45 = OpCompositeConstruct %44 %11 %11 +%46 = OpExtInst %44 %1 FindUMsb %45 +%47 = OpExtInst %7 %1 FindILsb %10 +%48 = OpExtInst %9 %1 FindILsb %11 +%49 = OpCompositeConstruct %15 %10 %10 +%50 = OpExtInst %15 %1 FindILsb %49 +%51 = OpCompositeConstruct %44 %11 %11 +%52 = OpExtInst %44 %1 FindILsb %51 +%55 = OpExtInst %9 %1 FindILsb %8 +%53 = OpExtInst %9 %1 UMin %54 %55 +%57 = OpExtInst %7 %1 FindILsb %6 +%56 = OpExtInst %7 %1 UMin %54 %57 +%59 = OpExtInst %9 %1 FindILsb %12 +%58 = OpExtInst %9 %1 UMin %54 %59 +%61 = OpExtInst %7 %1 FindILsb %10 +%60 = OpExtInst %7 %1 UMin %54 %61 +%62 = OpCompositeConstruct %44 %8 %8 +%65 = OpExtInst %44 %1 FindILsb %62 +%63 = OpExtInst %44 %1 UMin %64 %65 +%66 = OpCompositeConstruct %15 %6 %6 +%68 = OpExtInst %15 %1 FindILsb %66 +%67 = OpExtInst %15 %1 UMin %64 %68 +%69 = OpCompositeConstruct %44 %11 %11 +%71 = OpExtInst %44 %1 FindILsb %69 +%70 = OpExtInst %44 %1 UMin %64 %71 +%72 = OpCompositeConstruct %15 %13 %13 +%74 = OpExtInst %15 %1 FindILsb %72 +%73 = OpExtInst %15 %1 UMin %64 %74 +%77 = OpExtInst %7 %1 FindUMsb %10 +%75 = OpISub %7 %76 %77 +%79 = OpExtInst %7 %1 FindUMsb %11 +%78 = OpISub %9 %76 %79 +%80 = OpCompositeConstruct %15 %10 %10 +%83 = OpExtInst %15 %1 FindUMsb %80 +%81 = OpISub %15 %82 %83 +%84 = OpCompositeConstruct %44 %11 %11 +%86 = OpExtInst %15 %1 FindUMsb %84 +%85 = OpISub %44 %82 %86 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index e03648e1c..acd925ac9 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -9,6 +9,13 @@ fn main() { let g = refract(v, v, 1.0); let const_dot = dot(vec2(0, 0), vec2(0, 0)); let first_leading_bit_abs = firstLeadingBit(abs(0u)); + let flb_a = firstLeadingBit(-1); + let flb_b = firstLeadingBit(vec2(-1)); + let flb_c = firstLeadingBit(vec2(1u)); + let ftb_a = firstTrailingBit(-1); + let ftb_b = firstTrailingBit(1u); + let ftb_c = firstTrailingBit(vec2(-1)); + let ftb_d = firstTrailingBit(vec2(1u)); let ctz_a = countTrailingZeros(0u); let ctz_b = countTrailingZeros(0); let ctz_c = countTrailingZeros(4294967295u); From da3f43394f3afd12b2776c3e29f69abaca7ca582 Mon Sep 17 00:00:00 2001 From: Ashley Date: Tue, 2 May 2023 23:50:59 +1200 Subject: [PATCH 1987/2212] [wgsl-out] Simplify map_binding_to_attribute to always return an interpolate attribute (#2318) --- src/back/wgsl/writer.rs | 31 ++++++----------------- tests/out/wgsl/binding-arrays.wgsl | 2 +- tests/out/wgsl/binding-buffer-arrays.wgsl | 4 +-- tests/out/wgsl/fragment-output.wgsl | 16 ++++++------ tests/out/wgsl/interface.wgsl | 2 +- tests/out/wgsl/interpolate.wgsl | 2 +- tests/out/wgsl/shadow.wgsl | 2 +- 7 files changed, 22 insertions(+), 37 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 92086c94a..3fef1992d 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -244,10 +244,7 @@ impl Writer { for (index, arg) in func.arguments.iter().enumerate() { // Write argument attribute if a binding is present if let Some(ref binding) = arg.binding { - self.write_attributes(&map_binding_to_attribute( - binding, - module.types[arg.ty].inner.scalar_kind(), - ))?; + self.write_attributes(&map_binding_to_attribute(binding))?; } // Write argument name let argument_name = match func_ctx.ty { @@ -274,10 +271,7 @@ impl Writer { if let Some(ref result) = func.result { write!(self.out, " -> ")?; if let Some(ref binding) = result.binding { - self.write_attributes(&map_binding_to_attribute( - binding, - module.types[result.ty].inner.scalar_kind(), - ))?; + self.write_attributes(&map_binding_to_attribute(binding))?; } self.write_type(module, result.ty)?; } @@ -401,10 +395,7 @@ impl Writer { // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; if let Some(ref binding) = member.binding { - self.write_attributes(&map_binding_to_attribute( - binding, - module.types[member.ty].inner.scalar_kind(), - ))?; + self.write_attributes(&map_binding_to_attribute(binding))?; } // Write struct member name and type let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; @@ -1941,10 +1932,7 @@ const fn address_space_str( ) } -fn map_binding_to_attribute( - binding: &crate::Binding, - scalar_kind: Option, -) -> Vec { +fn map_binding_to_attribute(binding: &crate::Binding) -> Vec { match *binding { crate::Binding::BuiltIn(built_in) => { if let crate::BuiltIn::Position { invariant: true } = built_in { @@ -1957,12 +1945,9 @@ fn map_binding_to_attribute( location, interpolation, sampling, - } => match scalar_kind { - Some(crate::ScalarKind::Float) => vec![ - Attribute::Location(location), - Attribute::Interpolate(interpolation, sampling), - ], - _ => vec![Attribute::Location(location)], - }, + } => vec![ + Attribute::Location(location), + Attribute::Interpolate(interpolation, sampling), + ], } } diff --git a/tests/out/wgsl/binding-arrays.wgsl b/tests/out/wgsl/binding-arrays.wgsl index 539773a74..a7c64fe62 100644 --- a/tests/out/wgsl/binding-arrays.wgsl +++ b/tests/out/wgsl/binding-arrays.wgsl @@ -3,7 +3,7 @@ struct UniformIndex { } struct FragmentIn { - @location(0) index: u32, + @location(0) @interpolate(flat) index: u32, } @group(0) @binding(0) diff --git a/tests/out/wgsl/binding-buffer-arrays.wgsl b/tests/out/wgsl/binding-buffer-arrays.wgsl index 0c9cd5003..60ad84caf 100644 --- a/tests/out/wgsl/binding-buffer-arrays.wgsl +++ b/tests/out/wgsl/binding-buffer-arrays.wgsl @@ -7,7 +7,7 @@ struct Foo { } struct FragmentIn { - @location(0) index: u32, + @location(0) @interpolate(flat) index: u32, } @group(0) @binding(0) @@ -16,7 +16,7 @@ var storage_array: binding_array; var uni: UniformIndex; @fragment -fn main(fragment_in: FragmentIn) -> @location(0) u32 { +fn main(fragment_in: FragmentIn) -> @location(0) @interpolate(flat) u32 { var u1_: u32; let uniform_index = uni.index; diff --git a/tests/out/wgsl/fragment-output.wgsl b/tests/out/wgsl/fragment-output.wgsl index ea0932023..45cfdc8e8 100644 --- a/tests/out/wgsl/fragment-output.wgsl +++ b/tests/out/wgsl/fragment-output.wgsl @@ -1,19 +1,19 @@ struct FragmentOutputVec4Vec3_ { @location(0) vec4f: vec4, - @location(1) vec4i: vec4, - @location(2) vec4u: vec4, + @location(1) @interpolate(flat) vec4i: vec4, + @location(2) @interpolate(flat) vec4u: vec4, @location(3) vec3f: vec3, - @location(4) vec3i: vec3, - @location(5) vec3u: vec3, + @location(4) @interpolate(flat) vec3i: vec3, + @location(5) @interpolate(flat) vec3u: vec3, } struct FragmentOutputVec2Scalar { @location(0) vec2f: vec2, - @location(1) vec2i: vec2, - @location(2) vec2u: vec2, + @location(1) @interpolate(flat) vec2i: vec2, + @location(2) @interpolate(flat) vec2u: vec2, @location(3) scalarf: f32, - @location(4) scalari: i32, - @location(5) scalaru: u32, + @location(4) @interpolate(flat) scalari: i32, + @location(5) @interpolate(flat) scalaru: u32, } @fragment diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index 7c06d1db5..5ba5bce19 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -20,7 +20,7 @@ struct Input2_ { var output: array; @vertex -fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) instance_index: u32, @location(10) color: u32) -> VertexOutput { +fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) instance_index: u32, @location(10) @interpolate(flat) color: u32) -> VertexOutput { let tmp: u32 = ((vertex_index + instance_index) + color); return VertexOutput(vec4(1.0), f32(tmp)); } diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl index d566aae80..e2c4ce28b 100644 --- a/tests/out/wgsl/interpolate.wgsl +++ b/tests/out/wgsl/interpolate.wgsl @@ -1,6 +1,6 @@ struct FragmentInput { @builtin(position) position: vec4, - @location(0) _flat: u32, + @location(0) @interpolate(flat) _flat: u32, @location(1) @interpolate(linear) _linear: f32, @location(2) @interpolate(linear, centroid) linear_centroid: vec2, @location(3) @interpolate(linear, sample) linear_sample: vec3, diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index df042d9e1..de4aace6f 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -48,7 +48,7 @@ fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { } @vertex -fn vs_main(@location(0) position: vec4, @location(1) normal: vec4) -> VertexOutput { +fn vs_main(@location(0) @interpolate(flat) position: vec4, @location(1) @interpolate(flat) normal: vec4) -> VertexOutput { var out: VertexOutput; let w = u_entity.world; From 875df5899b837c952558bf3da82a7582c4d3cd1f Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 9 May 2023 17:29:33 +0200 Subject: [PATCH 1988/2212] add changelog for v0.12 (#2310) --- CHANGELOG.md | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51f0231a9..376bbf898 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,76 @@ # Change Log +## v0.12 (2023-04-19) + +#### GENERAL + +- Allow `array_index` to be unsigned. ([#2298](https://github.com/gfx-rs/naga/pull/2298)) **@daxpedda** +- Add ray query support. ([#2256](https://github.com/gfx-rs/naga/pull/2256)) **@kvark** +- Add partial derivative builtins. ([#2277](https://github.com/gfx-rs/naga/pull/2277)) **@evahop** +- Skip `gl_PerVertex` unused builtins in the SPIR-V frontend. ([#2272](https://github.com/gfx-rs/naga/pull/2272)) **@teoxoy** +- Differentiate between `i32` and `u32` in switch statement cases. ([#2269](https://github.com/gfx-rs/naga/pull/2269)) **@evahop** +- Fix zero initialization of workgroup memory. ([#2259](https://github.com/gfx-rs/naga/pull/2259)) **@teoxoy** +- Add `countTrailingZeros`. ([#2243](https://github.com/gfx-rs/naga/pull/2243)) **@gents83** +- Fix texture built-ins where u32 was expected. ([#2245](https://github.com/gfx-rs/naga/pull/2245)) **@evahop** +- Add `countLeadingZeros`. ([#2226](https://github.com/gfx-rs/naga/pull/2226)) **@evahop** +- [glsl/hlsl-out] Write sizes of arrays behind pointers in function arguments. ([#2250](https://github.com/gfx-rs/naga/pull/2250)) **@pluiedev** + +#### VALIDATOR + +- Validate vertex stage returns the position built-in. ([#2264](https://github.com/gfx-rs/naga/pull/2264)) **@teoxoy** +- Enforce discard is only used in the fragment stage. ([#2262](https://github.com/gfx-rs/naga/pull/2262)) **@Uriopass** +- Add `Capabilities::MULTISAMPLED_SHADING`. ([#2255](https://github.com/gfx-rs/naga/pull/2255)) **@teoxoy** +- Add `Capabilities::EARLY_DEPTH_TEST`. ([#2255](https://github.com/gfx-rs/naga/pull/2255)) **@teoxoy** +- Add `Capabilities::MULTIVIEW`. ([#2255](https://github.com/gfx-rs/naga/pull/2255)) **@teoxoy** +- Improve forward declaration validation. ([#2232](https://github.com/gfx-rs/naga/pull/2232)) **@JCapucho** + +#### WGSL-IN + +- Use `alias` instead of `type` for type aliases. ([#2299](https://github.com/gfx-rs/naga/pull/2299)) **@FL33TW00D** +- Add predeclared vector and matrix type aliases. ([#2251](https://github.com/gfx-rs/naga/pull/2251)) **@evahop** +- Improve invalid assignment diagnostic. ([#2233](https://github.com/gfx-rs/naga/pull/2233)) **@SparkyPotato** +- Expect semicolons wherever required. ([#2233](https://github.com/gfx-rs/naga/pull/2233)) **@SparkyPotato** +- Fix panic on invalid zero array size. ([#2233](https://github.com/gfx-rs/naga/pull/2233)) **@SparkyPotato** +- Check for leading `{` while parsing a block. ([#2233](https://github.com/gfx-rs/naga/pull/2233)) **@SparkyPotato** + +#### SPV-IN + +- Don't apply interpolation to fragment shaders outputs. ([#2239](https://github.com/gfx-rs/naga/pull/2239)) **@JCapucho** + +#### GLSL-IN + +- Add switch implicit type conversion. ([#2273](https://github.com/gfx-rs/naga/pull/2273)) **@evahop** +- Document some fields of `naga::front::glsl::context::Context`. ([#2244](https://github.com/gfx-rs/naga/pull/2244)) **@jimblandy** +- Perform output parameters implicit casts. ([#2063](https://github.com/gfx-rs/naga/pull/2063)) **@JCapucho** +- Add `not` vector relational builtin. ([#2227](https://github.com/gfx-rs/naga/pull/2227)) **@JCapucho** +- Add double overloads for relational vector builtins. ([#2227](https://github.com/gfx-rs/naga/pull/2227)) **@JCapucho** +- Add bool overloads for relational vector builtins. ([#2227](https://github.com/gfx-rs/naga/pull/2227)) **@JCapucho** + +#### SPV-OUT + +- Fix invalid spirv being generated from integer dot products. ([#2291](https://github.com/gfx-rs/naga/pull/2291)) **@PyryM** +- Fix adding illegal decorators on fragment outputs. ([#2286](https://github.com/gfx-rs/naga/pull/2286)) **@Wumpf** +- Fix `countLeadingZeros` impl. ([#2258](https://github.com/gfx-rs/naga/pull/2258)) **@teoxoy** +- Cache constant composites. ([#2257](https://github.com/gfx-rs/naga/pull/2257)) **@evahop** +- Support SPIR-V version 1.4. ([#2230](https://github.com/gfx-rs/naga/pull/2230)) **@kvark** + +#### MSL-OUT + +- Replace `per_stage_map` with `per_entry_point_map` ([#2237](https://github.com/gfx-rs/naga/pull/2237)) **@armansito** +- Update `firstLeadingBit` for signed integers ([#2235](https://github.com/gfx-rs/naga/pull/2235)) **@evahop** + +#### HLSL-OUT + +- Use `Interlocked` intrinsic for atomic integers (#2294) ([#2294](https://github.com/gfx-rs/naga/pull/2294)) **@ErichDonGubler** +- Document storage access generation. ([#2295](https://github.com/gfx-rs/naga/pull/2295)) **@jimblandy** +- Emit constructor functions for arrays. ([#2281](https://github.com/gfx-rs/naga/pull/2281)) **@ErichDonGubler** +- Clear `named_expressions` inserted by duplicated blocks. ([#2116](https://github.com/gfx-rs/naga/pull/2116)) **@teoxoy** + +#### GLSL-OUT + +- Skip `invariant` for `gl_FragCoord` on WebGL2. ([#2254](https://github.com/gfx-rs/naga/pull/2254)) **@grovesNL** +- Inject default `gl_PointSize = 1.0` in vertex shaders if `FORCE_POINT_SIZE` option was set. ([#2223](https://github.com/gfx-rs/naga/pull/2223)) **@REASY** + ## v0.11 (2023-01-25) - Move to the Rust 2021 edition ([#2085](https://github.com/gfx-rs/naga/pull/2085)) **@ErichDonGubler** From 59a2441a432e96bf174fac814cede612f9fb0c41 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 9 May 2023 16:20:15 -0700 Subject: [PATCH 1989/2212] [msl-out] Revert af4d989 since #764 removes the need for it (#2331) Assigning arrays by value works fine since all arrays are now wrapped by a struct. Co-authored-by: teoxoy <28601907+teoxoy@users.noreply.github.com> --- src/back/msl/writer.rs | 24 +++++------------------- tests/out/msl/access.msl | 10 +++++----- tests/out/msl/policy-mix.msl | 2 +- tests/out/msl/workgroup-var-init.msl | 2 +- 4 files changed, 12 insertions(+), 26 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 88600a8f1..26db61eed 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2954,31 +2954,17 @@ impl Writer { context: &StatementContext, ) -> BackendResult { let pointer_inner = context.expression.resolve_type(pointer); - let (array_size, is_atomic) = match *pointer_inner { + let is_atomic = match *pointer_inner { crate::TypeInner::Pointer { base, .. } => { match context.expression.module.types[base].inner { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(ch), - .. - } => (Some(ch), false), - crate::TypeInner::Atomic { .. } => (None, true), - _ => (None, false), + crate::TypeInner::Atomic { .. } => true, + _ => false, } } - _ => (None, false), + _ => false, }; - // we can't assign fixed-size arrays - if let Some(const_handle) = array_size { - let size = context.expression.module.constants[const_handle] - .to_array_length() - .unwrap(); - write!(self.out, "{level}for(int _i=0; _i<{size}; ++_i) ")?; - self.put_access_chain(pointer, policy, &context.expression)?; - write!(self.out, ".{WRAPPED_ARRAY_FIELD}[_i] = ")?; - self.put_expression(value, &context.expression, true)?; - writeln!(self.out, ".{WRAPPED_ARRAY_FIELD}[_i];")?; - } else if is_atomic { + if is_atomic { write!( self.out, "{level}{NAMESPACE}::atomic_store_explicit({ATOMIC_REFERENCE}" diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index a4967117f..4e51de80a 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -128,7 +128,7 @@ void test_matrix_within_array_within_struct_accesses( t_1 = MatCx2InArray {const_type_15_}; int _e66 = idx_1; idx_1 = _e66 + 1; - for(int _i=0; _i<2; ++_i) t_1.am.inner[_i] = const_type_15_.inner[_i]; + t_1.am = const_type_15_; t_1.am.inner[0] = metal::float4x2(metal::float2(8.0), metal::float2(7.0), metal::float2(6.0), metal::float2(5.0)); t_1.am.inner[0][0] = metal::float2(9.0); int _e93 = idx_1; @@ -167,7 +167,7 @@ void assign_through_ptr_fn( void assign_array_through_ptr_fn( thread type_26& foo_2 ) { - for(int _i=0; _i<2; ++_i) foo_2.inner[_i] = type_26 {metal::float4(1.0), metal::float4(2.0)}.inner[_i]; + foo_2 = type_26 {metal::float4(1.0), metal::float4(2.0)}; return; } @@ -197,7 +197,7 @@ vertex foo_vertOutput foo_vert( int a_1 = bar.data[(1 + (_buffer_sizes.size1 - 160 - 8) / 8) - 2u].value; metal::int2 c = qux; float _e34 = read_from_private(foo); - for(int _i=0; _i<5; ++_i) c2_.inner[_i] = type_22 {a_1, static_cast(b), 3, 4, 5}.inner[_i]; + c2_ = type_22 {a_1, static_cast(b), 3, 4, 5}; c2_.inner[vi + 1u] = 42; int value = c2_.inner[vi]; float _e48 = test_arr_as_arg(const_type_19_); @@ -215,7 +215,7 @@ fragment foo_fragOutput foo_frag( ) { bar._matrix[1].z = 1.0; bar._matrix = metal::float4x3(metal::float3(0.0), metal::float3(1.0), metal::float3(2.0), metal::float3(3.0)); - for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_9 {metal::uint2(0u), metal::uint2(1u)}.inner[_i]; + bar.arr = type_9 {metal::uint2(0u), metal::uint2(1u)}; bar.data[1].value = 1; qux = const_type_12_; return foo_fragOutput { metal::float4(0.0) }; @@ -231,7 +231,7 @@ kernel void assign_through_ptr( } metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); type_26 arr = {}; - for(int _i=0; _i<2; ++_i) arr.inner[_i] = type_26 {metal::float4(6.0), metal::float4(7.0)}.inner[_i]; + arr = type_26 {metal::float4(6.0), metal::float4(7.0)}; assign_through_ptr_fn(val); assign_array_through_ptr_fn(arr); return; diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index 7eb0c61ed..7f270e304 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -43,7 +43,7 @@ metal::float4 mock_function( thread type_6& in_private ) { type_9 in_function = {}; - for(int _i=0; _i<2; ++_i) in_function.inner[_i] = type_9 {metal::float4(0.7070000171661377, 0.0, 0.0, 1.0), metal::float4(0.0, 0.7070000171661377, 0.0, 1.0)}.inner[_i]; + in_function = type_9 {metal::float4(0.7070000171661377, 0.0, 0.0, 1.0), metal::float4(0.0, 0.7070000171661377, 0.0, 1.0)}; metal::float4 _e18 = in_storage.a.inner[i]; metal::float4 _e22 = in_uniform.a.inner[i]; metal::float4 _e25 = (uint(l) < image_2d_array.get_num_mip_levels() && uint(i) < image_2d_array.get_array_size() && metal::all(metal::uint2(c) < metal::uint2(image_2d_array.get_width(l), image_2d_array.get_height(l))) ? image_2d_array.read(metal::uint2(c), i, l): DefaultConstructible()); diff --git a/tests/out/msl/workgroup-var-init.msl b/tests/out/msl/workgroup-var-init.msl index 0d61e96f7..ac300d433 100644 --- a/tests/out/msl/workgroup-var-init.msl +++ b/tests/out/msl/workgroup-var-init.msl @@ -35,6 +35,6 @@ kernel void main_( } metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); type_1 _e3 = w_mem.arr; - for(int _i=0; _i<512; ++_i) output.inner[_i] = _e3.inner[_i]; + output = _e3; return; } From dd54aaf26062384db0ecc7553c0fbe9534bb491e Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Wed, 10 May 2023 01:10:09 -0400 Subject: [PATCH 1990/2212] refactor(valid)!: remove unneeded `ConstantError::Unresolved{Component,Size}` (#2330) Resolves #2329. --- src/valid/mod.rs | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 6b3a2e145..bed067db8 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -174,10 +174,6 @@ pub struct Validator { pub enum ConstantError { #[error("The type doesn't match the constant")] InvalidType, - #[error("The component handle {0:?} can not be resolved")] - UnresolvedComponent(Handle), - #[error("The array size handle {0:?} can not be resolved")] - UnresolvedSize(Handle), #[error(transparent)] Compose(#[from] ComposeError), } @@ -311,18 +307,6 @@ impl Validator { } } crate::ConstantInner::Composite { ty, ref components } => { - match types[ty].inner { - crate::TypeInner::Array { - size: crate::ArraySize::Constant(size_handle), - .. - } if handle <= size_handle => { - return Err(ConstantError::UnresolvedSize(size_handle)); - } - _ => {} - } - if let Some(&comp) = components.iter().find(|&&comp| handle <= comp) { - return Err(ConstantError::UnresolvedComponent(comp)); - } compose::validate_compose( ty, constants, From dcc8615c5b1712bb6a78ff3e6f92c47798a06861 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 9 May 2023 14:15:45 -0700 Subject: [PATCH 1991/2212] Introduce `Expression::ZeroValue`. --- src/back/dot/mod.rs | 3 +- src/back/glsl/mod.rs | 3 ++ src/back/hlsl/writer.rs | 1 + src/back/msl/writer.rs | 11 ++++ src/back/spv/block.rs | 1 + src/back/wgsl/writer.rs | 4 ++ src/front/glsl/constants.rs | 101 ++++++++++++++++++++++++++++++++++++ src/lib.rs | 10 ++-- src/proc/typifier.rs | 1 + src/valid/analyzer.rs | 1 + src/valid/expression.rs | 1 + src/valid/handles.rs | 3 ++ 12 files changed, 136 insertions(+), 4 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 1eebbee06..8667cd725 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -397,6 +397,8 @@ fn write_function_expressions( for (handle, expression) in fun.expressions.iter() { use crate::Expression as E; let (label, color_id) = match *expression { + E::Constant(_) => ("Constant".into(), 2), + E::ZeroValue(_) => ("ZeroValue".into(), 2), E::Access { base, index } => { edges.insert("base", base); edges.insert("index", index); @@ -406,7 +408,6 @@ fn write_function_expressions( edges.insert("base", base); (format!("AccessIndex[{index}]").into(), 1) } - E::Constant(_) => ("Constant".into(), 2), E::Splat { size, value } => { edges.insert("value", value); (format!("Splat{size:?}").into(), 3) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 9195b9683..030dba4e6 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2267,6 +2267,9 @@ impl<'a, W: Write> Writer<'a, W> { } // Constants are delegated to `write_constant` Expression::Constant(constant) => self.write_constant(constant)?, + Expression::ZeroValue(ty) => { + self.write_zero_init_value(ty)?; + } // `Splat` needs to actually write down a vector, it's not always inferred in GLSL. Expression::Splat { size: _, value } => { let resolved = ctx.info[expr].ty.inner_with(&self.module.types); diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 9e541ae0a..c5bda6607 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2057,6 +2057,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, + Expression::ZeroValue(ty) => self.write_default_init(module, ty)?, Expression::Compose { ty, ref components } => { match module.types[ty].inner { TypeInner::Struct { .. } | TypeInner::Array { .. } => { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 26db61eed..1c474a5e4 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1333,6 +1333,17 @@ impl Writer { }; write!(self.out, "{coco}")?; } + crate::Expression::ZeroValue(ty) => { + let ty_name = TypeContext { + handle: ty, + module: context.module, + names: &self.names, + access: crate::StorageAccess::empty(), + binding: None, + first_time: false, + }; + write!(self.out, "{ty_name} {{}}")?; + } crate::Expression::Splat { size, value } => { let scalar_kind = match *context.resolve_type(value) { crate::TypeInner::Scalar { kind, .. } => kind, diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 37c78bdf9..a8afa8997 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -358,6 +358,7 @@ impl<'w> BlockContext<'w> { self.writer.global_variables[handle.index()].access_id } crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], + crate::Expression::ZeroValue(_) => self.writer.write_constant_null(result_type_id), crate::Expression::Splat { size, value } => { let value_id = self.cached[value]; let components = [value_id; 4]; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 3fef1992d..97a271dbb 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1104,6 +1104,10 @@ impl Writer { // subscripting. match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, + Expression::ZeroValue(ty) => { + self.write_type(module, ty)?; + write!(self.out, "()")?; + } Expression::Compose { ty, ref components } => { self.write_type(module, ty)?; write!(self.out, "(")?; diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 045a9c6ff..5f7fc4f89 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -71,6 +71,7 @@ impl<'a> ConstantSolver<'a> { let span = self.expressions.get_span(expr); match self.expressions[expr] { Expression::Constant(constant) => Ok(constant), + Expression::ZeroValue(ty) => self.register_zero_constant(ty, span), Expression::AccessIndex { base, index } => self.access(base, index as usize), Expression::Access { base, index } => { let index = self.solve(index)?; @@ -547,6 +548,106 @@ impl<'a> ConstantSolver<'a> { Ok(self.register_constant(inner, span)) } + fn register_zero_constant( + &mut self, + ty: Handle, + span: crate::Span, + ) -> Result, ConstantSolvingError> { + let inner = match self.types[ty].inner { + TypeInner::Scalar { kind, width } => { + let value = match kind { + ScalarKind::Sint => ScalarValue::Sint(0), + ScalarKind::Uint => ScalarValue::Uint(0), + ScalarKind::Float => ScalarValue::Float(1.0), + ScalarKind::Bool => ScalarValue::Bool(false), + }; + ConstantInner::Scalar { width, value } + } + TypeInner::Vector { size, kind, width } => { + let element_type = self.types.insert( + Type { + name: None, + inner: TypeInner::Scalar { kind, width }, + }, + span, + ); + let element = self.register_zero_constant(element_type, span)?; + let components = std::iter::repeat(element) + .take(size as u8 as usize) + .collect(); + ConstantInner::Composite { ty, components } + } + TypeInner::Matrix { + columns, + rows, + width, + } => { + let column_type = self.types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size: rows, + kind: ScalarKind::Float, + width, + }, + }, + span, + ); + let column = self.register_zero_constant(column_type, span)?; + let components = std::iter::repeat(column) + .take(columns as u8 as usize) + .collect(); + ConstantInner::Composite { ty, components } + } + TypeInner::Array { base, size, .. } => { + let length = match size { + crate::ArraySize::Constant(handle) => match self.constants[handle].inner { + ConstantInner::Scalar { + value: ScalarValue::Uint(length), + .. + } => length as usize, + ConstantInner::Scalar { + value: ScalarValue::Sint(length), + .. + } => { + if length < 0 { + return Err(ConstantSolvingError::InvalidArrayLengthArg); + } + length as usize + } + _ => return Err(ConstantSolvingError::InvalidArrayLengthArg), + }, + crate::ArraySize::Dynamic => { + return Err(ConstantSolvingError::ArrayLengthDynamic) + } + }; + let element = self.register_zero_constant(base, span)?; + let components = std::iter::repeat(element) + .take(length as u8 as usize) + .collect(); + ConstantInner::Composite { ty, components } + } + TypeInner::Struct { ref members, .. } => { + // Make a copy of the member types, for the borrow checker. + let types: Vec> = members.iter().map(|member| member.ty).collect(); + let mut components = vec![]; + for member_ty in types { + let value = self.register_zero_constant(member_ty, span)?; + components.push(value); + } + ConstantInner::Composite { ty, components } + } + ref inner => { + return Err(ConstantSolvingError::NotImplemented(format!( + "zero-value construction for types: {:?}", + inner + ))); + } + }; + + Ok(self.register_constant(inner, span)) + } + fn register_constant(&mut self, inner: ConstantInner, span: crate::Span) -> Handle { self.constants.fetch_or_append( Constant { diff --git a/src/lib.rs b/src/lib.rs index e744b7d40..6a5bc8e0a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,7 +75,7 @@ of `Statement`s and other `Expression`s. Naga's rules for when `Expression`s are evaluated are as follows: -- [`Constant`](Expression::Constant) expressions are considered to be +- [`Constant`] and [`ZeroValue`] expressions are considered to be implicitly evaluated before execution begins. - [`FunctionArgument`] and [`LocalVariable`] expressions are considered @@ -174,6 +174,7 @@ tree. [`RayQueryProceedResult`]: Expression::RayQueryProceedResult [`CallResult`]: Expression::CallResult [`Constant`]: Expression::Constant +[`ZeroValue`]: Expression::ZeroValue [`Derivative`]: Expression::Derivative [`FunctionArgument`]: Expression::FunctionArgument [`GlobalVariable`]: Expression::GlobalVariable @@ -1189,6 +1190,11 @@ bitflags::bitflags! { #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Expression { + /// Constant value. + Constant(Handle), + /// Zero value of a type. + ZeroValue(Handle), + /// Array access with a computed index. /// /// ## Typing rules @@ -1247,8 +1253,6 @@ pub enum Expression { base: Handle, index: u32, }, - /// Constant value. - Constant(Handle), /// Splat scalar into a vector. Splat { size: VectorSize, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index ad77b0ed6..414749ee0 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -430,6 +430,7 @@ impl<'a> ResolveContext<'a> { } crate::ConstantInner::Composite { ty, components: _ } => TypeResolution::Handle(ty), }, + crate::Expression::ZeroValue(ty) => TypeResolution::Handle(ty), crate::Expression::Splat { size, value } => match *past(value)?.inner_with(types) { Ti::Scalar { kind, width } => { TypeResolution::Value(Ti::Vector { size, kind, width }) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index e9b155b6e..4860435ce 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -493,6 +493,7 @@ impl FunctionInfo { }, // always uniform E::Constant(_) => Uniformity::new(), + E::ZeroValue(_) => Uniformity::new(), E::Splat { size: _, value } => Uniformity { non_uniform_result: self.add_ref(value), requirements: UniformityRequirements::empty(), diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 3a8170790..7f9e277cf 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -270,6 +270,7 @@ impl super::Validator { ShaderStages::all() } E::Constant(_handle) => ShaderStages::all(), + E::ZeroValue(_type) => ShaderStages::all(), E::Splat { size: _, value } => match resolver[value] { Ti::Scalar { .. } => ShaderStages::all(), ref other => { diff --git a/src/valid/handles.rs b/src/valid/handles.rs index fdd43cd58..0115cd85d 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -256,6 +256,9 @@ impl super::Validator { crate::Expression::Constant(constant) => { validate_constant(constant)?; } + crate::Expression::ZeroValue(ty) => { + validate_type(ty)?; + } crate::Expression::Splat { value, .. } => { handle.check_dep(value)?; } From 4d87401fac27967b24ca92a12a866365668cfbd8 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 9 May 2023 14:40:52 -0700 Subject: [PATCH 1992/2212] Use `Expression::ZeroValue` in SPIR-V and WGSL front ends. --- src/front/spv/mod.rs | 9 +- src/front/wgsl/lower/construction.rs | 7 +- src/front/wgsl/lower/mod.rs | 77 -- src/proc/mod.rs | 1 + tests/out/glsl/access.foo_frag.Fragment.glsl | 2 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 4 +- ...age-restrict.fragment_shader.Fragment.glsl | 20 +- ...k-image-rzsw.fragment_shader.Fragment.glsl | 20 +- tests/out/glsl/globals.main.Compute.glsl | 4 +- .../glsl/math-functions.main.Fragment.glsl | 2 +- tests/out/glsl/operators.main.Compute.glsl | 24 +- tests/out/hlsl/access.hlsl | 26 +- tests/out/hlsl/globals.hlsl | 4 +- tests/out/hlsl/math-functions.hlsl | 2 +- tests/out/hlsl/operators.hlsl | 52 +- tests/out/ir/access.ron | 141 +-- tests/out/msl/access.msl | 14 +- tests/out/msl/bounds-check-image-restrict.msl | 23 +- tests/out/msl/bounds-check-image-rzsw.msl | 23 +- tests/out/msl/globals.msl | 6 +- tests/out/msl/math-functions.msl | 3 +- tests/out/msl/operators.msl | 44 +- tests/out/spv/access.spvasm | 718 ++++++----- .../spv/bounds-check-image-restrict.spvasm | 817 ++++++------ tests/out/spv/bounds-check-image-rzsw.spvasm | 985 ++++++++------- tests/out/spv/globals.spvasm | 417 +++--- tests/out/spv/math-functions.spvasm | 167 +-- tests/out/spv/operators.spvasm | 1121 +++++++++-------- tests/out/wgsl/access.wgsl | 8 +- tests/out/wgsl/globals.wgsl | 4 +- tests/out/wgsl/math-functions.wgsl | 2 +- tests/out/wgsl/operators.wgsl | 32 +- 32 files changed, 2303 insertions(+), 2476 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index c69a230cb..a301ac141 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1324,14 +1324,17 @@ impl> Frontend { Op::NoLine => inst.expect(1)?, Op::Undef => { inst.expect(3)?; - let (type_id, id, handle) = - self.parse_null_constant(inst, ctx.type_arena, ctx.const_arena)?; + let type_id = self.next()?; + let id = self.next()?; + let type_lookup = self.lookup_type.lookup(type_id)?; + let ty = type_lookup.handle; + self.lookup_expression.insert( id, LookupExpression { handle: ctx .expressions - .append(crate::Expression::Constant(handle), span), + .append(crate::Expression::ZeroValue(ty), span), type_id, block_id, }, diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 723d4441f..0c2f29bd9 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -199,12 +199,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { _ => return Err(Error::TypeNotInferrable(ty_span)), }; - return match ctx.create_zero_value_constant(ty) { - Some(constant) => { - Ok(ctx.interrupt_emitter(crate::Expression::Constant(constant), span)) - } - None => Err(Error::TypeNotConstructible(ty_span)), - }; + return Ok(ctx.interrupt_emitter(crate::Expression::ZeroValue(ty), span)); } // Scalar constructor & conversion (scalar -> scalar) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index bc9cce1be..f6c27caa8 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -342,83 +342,6 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } - /// Creates a zero value constant of type `ty` - /// - /// Returns `None` if the given `ty` is not a constructible type - fn create_zero_value_constant( - &mut self, - ty: Handle, - ) -> Option> { - let inner = match self.module.types[ty].inner { - crate::TypeInner::Scalar { kind, width } => { - let value = match kind { - crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), - crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), - crate::ScalarKind::Float => crate::ScalarValue::Float(0.), - crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), - }; - crate::ConstantInner::Scalar { width, value } - } - crate::TypeInner::Vector { size, kind, width } => { - let scalar_ty = self.ensure_type_exists(crate::TypeInner::Scalar { width, kind }); - let component = self.create_zero_value_constant(scalar_ty)?; - crate::ConstantInner::Composite { - ty, - components: (0..size as u8).map(|_| component).collect(), - } - } - crate::TypeInner::Matrix { - columns, - rows, - width, - } => { - let vec_ty = self.ensure_type_exists(crate::TypeInner::Vector { - width, - kind: crate::ScalarKind::Float, - size: rows, - }); - let component = self.create_zero_value_constant(vec_ty)?; - crate::ConstantInner::Composite { - ty, - components: (0..columns as u8).map(|_| component).collect(), - } - } - crate::TypeInner::Array { - base, - size: crate::ArraySize::Constant(size), - .. - } => { - let size = self.module.constants[size].to_array_length()?; - let component = self.create_zero_value_constant(base)?; - crate::ConstantInner::Composite { - ty, - components: (0..size).map(|_| component).collect(), - } - } - crate::TypeInner::Struct { ref members, .. } => { - let members = members.clone(); - crate::ConstantInner::Composite { - ty, - components: members - .iter() - .map(|member| self.create_zero_value_constant(member.ty)) - .collect::>()?, - } - } - _ => return None, - }; - - let constant = self.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Span::UNDEFINED, - ); - Some(constant) - } - fn format_typeinner(&self, inner: &crate::TypeInner) -> String { inner.to_wgsl(&self.module.types, &self.module.constants) } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index a775272a1..c4c6d4f4e 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -312,6 +312,7 @@ impl crate::Expression { pub const fn needs_pre_emit(&self) -> bool { match *self { Self::Constant(_) + | Self::ZeroValue(_) | Self::FunctionArgument(_) | Self::GlobalVariable(_) | Self::LocalVariable(_) => true, diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/tests/out/glsl/access.foo_frag.Fragment.glsl index c71617572..3d52fa56b 100644 --- a/tests/out/glsl/access.foo_frag.Fragment.glsl +++ b/tests/out/glsl/access.foo_frag.Fragment.glsl @@ -54,7 +54,7 @@ void main() { _group_0_binding_0_fs._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); _group_0_binding_0_fs.arr = uvec2[2](uvec2(0u), uvec2(1u)); _group_0_binding_0_fs.data[1].value = 1; - _group_0_binding_2_fs = ivec2(0, 0); + _group_0_binding_2_fs = ivec2(0); _fs2p_location0 = vec4(0.0); return; } diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index 03e33ccb8..f3754247b 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -88,10 +88,10 @@ void test_matrix_within_array_within_struct_accesses() { int _e58 = idx_1; int _e60 = idx_1; float unnamed_14 = _group_0_binding_3_vs.am[0][_e58][_e60]; - t_1 = MatCx2InArray(mat4x2[2](mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)))); + t_1 = MatCx2InArray(mat4x2[2](mat4x2(0.0), mat4x2(0.0))); int _e66 = idx_1; idx_1 = (_e66 + 1); - t_1.am = mat4x2[2](mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0))); + t_1.am = mat4x2[2](mat4x2(0.0), mat4x2(0.0)); t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); t_1.am[0][0] = vec2(9.0); int _e93 = idx_1; diff --git a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl index ba7854322..cf5a2806f 100644 --- a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl +++ b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl @@ -83,16 +83,16 @@ void test_textureStore_3d(ivec3 coords_14, vec4 value_4) { void main() { vec4 _e2 = test_textureLoad_1d(0, 0); - vec4 _e5 = test_textureLoad_2d(ivec2(0, 0), 0); - vec4 _e9 = test_textureLoad_2d_array_u(ivec2(0, 0), 0u, 0); - vec4 _e13 = test_textureLoad_2d_array_s(ivec2(0, 0), 0, 0); - vec4 _e16 = test_textureLoad_3d(ivec3(0, 0, 0), 0); - vec4 _e19 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); - test_textureStore_1d(0, vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_2d(ivec2(0, 0), vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_2d_array_u(ivec2(0, 0), 0u, vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_2d_array_s(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_3d(ivec3(0, 0, 0), vec4(0.0, 0.0, 0.0, 0.0)); + vec4 _e5 = test_textureLoad_2d(ivec2(0), 0); + vec4 _e9 = test_textureLoad_2d_array_u(ivec2(0), 0u, 0); + vec4 _e13 = test_textureLoad_2d_array_s(ivec2(0), 0, 0); + vec4 _e16 = test_textureLoad_3d(ivec3(0), 0); + vec4 _e19 = test_textureLoad_multisampled_2d(ivec2(0), 0); + test_textureStore_1d(0, vec4(0.0)); + test_textureStore_2d(ivec2(0), vec4(0.0)); + test_textureStore_2d_array_u(ivec2(0), 0u, vec4(0.0)); + test_textureStore_2d_array_s(ivec2(0), 0, vec4(0.0)); + test_textureStore_3d(ivec3(0), vec4(0.0)); _fs2p_location0 = vec4(0.0, 0.0, 0.0, 0.0); return; } diff --git a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl index 7d8aba65c..4a6718e39 100644 --- a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl +++ b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl @@ -77,16 +77,16 @@ void test_textureStore_3d(ivec3 coords_14, vec4 value_4) { void main() { vec4 _e2 = test_textureLoad_1d(0, 0); - vec4 _e5 = test_textureLoad_2d(ivec2(0, 0), 0); - vec4 _e9 = test_textureLoad_2d_array_u(ivec2(0, 0), 0u, 0); - vec4 _e13 = test_textureLoad_2d_array_s(ivec2(0, 0), 0, 0); - vec4 _e16 = test_textureLoad_3d(ivec3(0, 0, 0), 0); - vec4 _e19 = test_textureLoad_multisampled_2d(ivec2(0, 0), 0); - test_textureStore_1d(0, vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_2d(ivec2(0, 0), vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_2d_array_u(ivec2(0, 0), 0u, vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_2d_array_s(ivec2(0, 0), 0, vec4(0.0, 0.0, 0.0, 0.0)); - test_textureStore_3d(ivec3(0, 0, 0), vec4(0.0, 0.0, 0.0, 0.0)); + vec4 _e5 = test_textureLoad_2d(ivec2(0), 0); + vec4 _e9 = test_textureLoad_2d_array_u(ivec2(0), 0u, 0); + vec4 _e13 = test_textureLoad_2d_array_s(ivec2(0), 0, 0); + vec4 _e16 = test_textureLoad_3d(ivec3(0), 0); + vec4 _e19 = test_textureLoad_multisampled_2d(ivec2(0), 0); + test_textureStore_1d(0, vec4(0.0)); + test_textureStore_2d(ivec2(0), vec4(0.0)); + test_textureStore_2d_array_u(ivec2(0), 0u, vec4(0.0)); + test_textureStore_2d_array_s(ivec2(0), 0, vec4(0.0)); + test_textureStore_3d(ivec3(0), vec4(0.0)); _fs2p_location0 = vec4(0.0, 0.0, 0.0, 0.0); return; } diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index f72bde3de..cb695ac1d 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -44,8 +44,8 @@ void test_msl_packed_vec3_() { vec3 unnamed = data.v3_; vec2 unnamed_1 = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); - vec3 unnamed_2 = (data.v3_ * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - vec3 unnamed_3 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * data.v3_); + vec3 unnamed_2 = (data.v3_ * mat3x3(0.0)); + vec3 unnamed_3 = (mat3x3(0.0) * data.v3_); vec3 unnamed_4 = (data.v3_ * 2.0); vec3 unnamed_5 = (2.0 * data.v3_); } diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl index 11c3be188..70ad0b199 100644 --- a/tests/out/glsl/math-functions.main.Fragment.glsl +++ b/tests/out/glsl/math-functions.main.Fragment.glsl @@ -12,7 +12,7 @@ void main() { vec4 d = radians(v); vec4 e = clamp(v, vec4(0.0), vec4(1.0)); vec4 g = refract(v, v, 1.0); - int const_dot = ( + ivec2(0, 0).x * ivec2(0, 0).x + ivec2(0, 0).y * ivec2(0, 0).y); + int const_dot = ( + ivec2(0).x * ivec2(0).x + ivec2(0).y * ivec2(0).y); uint first_leading_bit_abs = uint(findMSB(uint(abs(int(0u))))); int flb_a = findMSB(-1); ivec2 flb_b = findMSB(ivec2(-1)); diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 385792339..a76465d95 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -58,10 +58,10 @@ float constructors() { int unnamed_4 = int(0); uint unnamed_5 = uint(0u); float unnamed_6 = float(0.0); - uvec2 unnamed_7 = uvec2(uvec2(0u, 0u)); - mat2x3 unnamed_8 = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - uvec2 unnamed_9 = uvec2(0u, 0u); - mat2x3 unnamed_10 = mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); + uvec2 unnamed_7 = uvec2(uvec2(0u)); + mat2x3 unnamed_8 = mat2x3(mat2x3(0.0)); + uvec2 unnamed_9 = uvec2(0u); + mat2x3 unnamed_10 = mat2x3(0.0); float _e71 = foo.a.x; return _e71; } @@ -140,13 +140,13 @@ void arithmetic() { uvec2 unnamed_78 = (uvec2(2u) % uvec2(1u)); vec2 unnamed_79 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); vec2 unnamed_80 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); - mat3x3 unnamed_81 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_82 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_83 = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - mat3x3 unnamed_84 = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - vec3 unnamed_85 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - vec4 unnamed_86 = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - mat3x3 unnamed_87 = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + mat3x3 unnamed_81 = (mat3x3(0.0) + mat3x3(0.0)); + mat3x3 unnamed_82 = (mat3x3(0.0) - mat3x3(0.0)); + mat3x3 unnamed_83 = (mat3x3(0.0) * 1.0); + mat3x3 unnamed_84 = (2.0 * mat3x3(0.0)); + vec3 unnamed_85 = (mat4x3(0.0) * vec4(1.0)); + vec4 unnamed_86 = (vec3(2.0) * mat4x3(0.0)); + mat3x3 unnamed_87 = (mat4x3(0.0) * mat3x4(0.0)); } void bit() { @@ -245,7 +245,7 @@ void assignment() { a_1 = (_e32 + 1); int _e35 = a_1; a_1 = (_e35 - 1); - vec0_ = ivec3(0, 0, 0); + vec0_ = ivec3(0); int _e42 = vec0_.y; vec0_.y = (_e42 + 1); int _e47 = vec0_.y; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 27786717d..63814754e 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -77,24 +77,6 @@ GlobalConst ConstructGlobalConst(uint arg0, uint3 arg1, int arg2) { return ret; } -typedef float4x2 ret_Constructarray2_float4x2_[2]; -ret_Constructarray2_float4x2_ Constructarray2_float4x2_(float4x2 arg0, float4x2 arg1) { - float4x2 ret[2] = { arg0, arg1 }; - return ret; -} - -typedef float ret_Constructarray10_float_[10]; -ret_Constructarray10_float_ Constructarray10_float_(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5, float arg6, float arg7, float arg8, float arg9) { - float ret[10] = { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 }; - return ret; -} - -typedef float ret_Constructarray5_array10_float__[5][10]; -ret_Constructarray5_array10_float__ Constructarray5_array10_float__(float arg0[10], float arg1[10], float arg2[10], float arg3[10], float arg4[10]) { - float ret[5][10] = { arg0, arg1, arg2, arg3, arg4 }; - return ret; -} - static GlobalConst global_const = ConstructGlobalConst(0u, uint3(0u, 0u, 0u), 0); RWByteAddressBuffer bar : register(u0); cbuffer baz : register(b1) { Baz baz; } @@ -201,10 +183,10 @@ void test_matrix_within_array_within_struct_accesses() int _expr58 = idx_1; int _expr60 = idx_1; float unnamed_14 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr58)[_expr60]; - t_1 = ConstructMatCx2InArray(Constructarray2_float4x2_(float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0)), float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0)))); + t_1 = ConstructMatCx2InArray((float4x2[2])0); int _expr66 = idx_1; idx_1 = (_expr66 + 1); - t_1.am = (__mat4x2[2])Constructarray2_float4x2_(float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0)), float4x2(float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0), float2(0.0, 0.0))); + t_1.am = (__mat4x2[2])(float4x2[2])0; t_1.am[0] = (__mat4x2)float4x2((8.0).xx, (7.0).xx, (6.0).xx, (5.0).xx); t_1.am[0]._0 = (9.0).xx; int _expr93 = idx_1; @@ -287,7 +269,7 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position c2_ = Constructarray5_int_(a_1, int(b), 3, 4, 5); c2_[(vi + 1u)] = 42; int value = c2_[vi]; - const float _e48 = test_arr_as_arg(Constructarray5_array10_float__(Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), Constructarray10_float_(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + const float _e48 = test_arr_as_arg((float[5][10])0); return float4(mul(float4((value).xxxx), _matrix), 2.0); } @@ -307,7 +289,7 @@ float4 foo_frag() : SV_Target0 bar.Store2(144+8, asuint(_value2[1])); } bar.Store(0+8+160, asuint(1)); - qux.Store2(0, asuint(int2(0, 0))); + qux.Store2(0, asuint((int2)0)); return (0.0).xxxx; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 273889fdb..9d7eb2e99 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -92,8 +92,8 @@ void test_msl_packed_vec3_() float3 unnamed = data.v3_; float2 unnamed_1 = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); - float3 unnamed_2 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), data.v3_); - float3 unnamed_3 = mul(data.v3_, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3 unnamed_2 = mul((float3x3)0, data.v3_); + float3 unnamed_3 = mul(data.v3_, (float3x3)0); float3 unnamed_4 = (data.v3_ * 2.0); float3 unnamed_5 = (2.0 * data.v3_); } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index 04a9843cb..e3443604f 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -8,7 +8,7 @@ void main() float4 d = radians(v); float4 e = saturate(v); float4 g = refract(v, v, 1.0); - int const_dot = dot(int2(0, 0), int2(0, 0)); + int const_dot = dot((int2)0, (int2)0); uint first_leading_bit_abs = firstbithigh(abs(0u)); int flb_a = asint(firstbithigh(-1)); int2 flb_b = asint(firstbithigh((-1).xx)); diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 3136972d4..73d7211c3 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -11,19 +11,6 @@ struct Foo { int _end_pad_2; }; -Foo ConstructFoo(float4 arg0, int arg1) { - Foo ret = (Foo)0; - ret.a = arg0; - ret.b = arg1; - return ret; -} - -typedef Foo ret_Constructarray3_Foo_[3]; -ret_Constructarray3_Foo_ Constructarray3_Foo_(Foo arg0, Foo arg1, Foo arg2) { - Foo ret[3] = { arg0, arg1, arg2 }; - return ret; -} - float4 builtins() { int s1_ = (true ? 1 : 0); @@ -65,6 +52,13 @@ float3 bool_cast(float3 x) return float3(y); } +Foo ConstructFoo(float4 arg0, int arg1) { + Foo ret = (Foo)0; + ret.a = arg0; + ret.b = arg1; + return ret; +} + typedef int ret_Constructarray4_int_[4]; ret_Constructarray4_int_ Constructarray4_int_(int arg0, int arg1, int arg2, int arg3) { int ret[4] = { arg0, arg1, arg2, arg3 }; @@ -81,14 +75,14 @@ float constructors() uint2 unnamed = (0u).xx; float2x2 unnamed_1 = float2x2((0.0).xx, (0.0).xx); int unnamed_2[4] = Constructarray4_int_(0, 1, 2, 3); - bool unnamed_3 = bool(false); - int unnamed_4 = int(0); - uint unnamed_5 = uint(0u); - float unnamed_6 = float(0.0); - uint2 unnamed_7 = uint2(uint2(0u, 0u)); - float2x3 unnamed_8 = float2x3(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - uint2 unnamed_9 = asuint(uint2(0u, 0u)); - float2x3 unnamed_10 = asfloat(float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + bool unnamed_3 = bool((bool)0); + int unnamed_4 = int((int)0); + uint unnamed_5 = uint((uint)0); + float unnamed_6 = float((float)0); + uint2 unnamed_7 = uint2((uint2)0); + float2x3 unnamed_8 = float2x3((float2x3)0); + uint2 unnamed_9 = asuint((uint2)0); + float2x3 unnamed_10 = asfloat((float2x3)0); float _expr71 = foo.a.x; return _expr71; } @@ -169,13 +163,13 @@ void arithmetic() uint2 unnamed_78 = ((2u).xx % (1u).xx); float2 unnamed_79 = fmod((2.0).xx, (1.0).xx); float2 unnamed_80 = fmod((2.0).xx, (1.0).xx); - float3x3 unnamed_81 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) + float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_82 = (float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)) - float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_83 = mul(1.0, float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float3x3 unnamed_84 = mul(float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), 2.0); - float3 unnamed_85 = mul((1.0).xxxx, float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); - float4 unnamed_86 = mul(float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)), (2.0).xxx); - float3x3 unnamed_87 = mul(float3x4(float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0), float4(0.0, 0.0, 0.0, 0.0)), float4x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0))); + float3x3 unnamed_81 = ((float3x3)0 + (float3x3)0); + float3x3 unnamed_82 = ((float3x3)0 - (float3x3)0); + float3x3 unnamed_83 = mul(1.0, (float3x3)0); + float3x3 unnamed_84 = mul((float3x3)0, 2.0); + float3 unnamed_85 = mul((1.0).xxxx, (float4x3)0); + float4 unnamed_86 = mul((float4x3)0, (2.0).xxx); + float3x3 unnamed_87 = mul((float3x4)0, (float4x3)0); } void bit() @@ -278,7 +272,7 @@ void assignment() a_1 = (_expr32 + 1); int _expr35 = a_1; a_1 = (_expr35 - 1); - vec0_ = int3(0, 0, 0); + vec0_ = (int3)0; int _expr42 = vec0_.y; vec0_.y = (_expr42 + 1); int _expr47 = vec0_.y; diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 0c1f9df1c..8b1874601 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -263,7 +263,7 @@ name: None, inner: Array( base: 24, - size: Constant(26), + size: Constant(22), stride: 40, ), ), @@ -290,7 +290,7 @@ name: None, inner: Array( base: 3, - size: Constant(26), + size: Constant(22), stride: 4, ), ), @@ -498,49 +498,6 @@ value: Float(40.0), ), ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(0.0), - ), - ), - ( - name: None, - specialization: None, - inner: Composite( - ty: 18, - components: [ - 20, - 20, - ], - ), - ), - ( - name: None, - specialization: None, - inner: Composite( - ty: 19, - components: [ - 21, - 21, - 21, - 21, - ], - ), - ), - ( - name: None, - specialization: None, - inner: Composite( - ty: 20, - components: [ - 22, - 22, - ], - ), - ), ( name: None, specialization: None, @@ -581,6 +538,14 @@ value: Sint(9), ), ), + ( + name: None, + specialization: None, + inner: Scalar( + width: 4, + value: Float(0.0), + ), + ), ( name: None, specialization: None, @@ -621,50 +586,6 @@ value: Sint(42), ), ), - ( - name: None, - specialization: None, - inner: Composite( - ty: 24, - components: [ - 20, - 20, - 20, - 20, - 20, - 20, - 20, - 20, - 20, - 20, - ], - ), - ), - ( - name: None, - specialization: None, - inner: Composite( - ty: 25, - components: [ - 34, - 34, - 34, - 34, - 34, - ], - ), - ), - ( - name: None, - specialization: None, - inner: Composite( - ty: 17, - components: [ - 3, - 3, - ], - ), - ), ( name: None, specialization: None, @@ -1430,7 +1351,7 @@ Load( pointer: 62, ), - Constant(23), + ZeroValue(20), Compose( ty: 21, components: [ @@ -1451,7 +1372,7 @@ base: 66, index: 0, ), - Constant(23), + ZeroValue(20), AccessIndex( base: 66, index: 0, @@ -1461,12 +1382,12 @@ base: 72, index: 0, ), - Constant(24), + Constant(20), Splat( size: Bi, value: 75, ), - Constant(25), + Constant(21), Splat( size: Bi, value: 77, @@ -1927,12 +1848,12 @@ local_variables: [], expressions: [ FunctionArgument(0), - Constant(27), + Constant(23), AccessIndex( base: 1, index: 4, ), - Constant(28), + Constant(24), AccessIndex( base: 3, index: 9, @@ -1968,7 +1889,7 @@ local_variables: [], expressions: [ FunctionArgument(0), - Constant(37), + Constant(31), ], named_expressions: { 1: "p", @@ -2071,7 +1992,7 @@ ], expressions: [ FunctionArgument(0), - Constant(20), + Constant(25), LocalVariable(1), Load( pointer: 3, @@ -2093,7 +2014,7 @@ Load( pointer: 10, ), - Constant(29), + Constant(26), GlobalVariable(2), AccessIndex( base: 13, @@ -2121,7 +2042,7 @@ index: 5, ), ArrayLength(21), - Constant(30), + Constant(27), Binary( op: Subtract, left: 22, @@ -2162,9 +2083,9 @@ kind: Sint, convert: Some(4), ), - Constant(31), - Constant(27), - Constant(26), + Constant(28), + Constant(23), + Constant(22), Compose( ty: 28, components: [ @@ -2176,7 +2097,7 @@ ], ), LocalVariable(2), - Constant(32), + Constant(29), Binary( op: Add, left: 1, @@ -2186,7 +2107,7 @@ base: 41, index: 43, ), - Constant(33), + Constant(30), Access( base: 41, index: 1, @@ -2194,7 +2115,7 @@ Load( pointer: 46, ), - Constant(35), + ZeroValue(25), CallResult(4), Splat( size: Quad, @@ -2381,7 +2302,7 @@ base: 7, index: 0, ), - Constant(20), + Constant(25), Splat( size: Tri, value: 9, @@ -2420,7 +2341,7 @@ size: Bi, value: 20, ), - Constant(32), + Constant(29), Splat( size: Bi, value: 22, @@ -2448,8 +2369,8 @@ ), Constant(7), GlobalVariable(4), - Constant(36), - Constant(20), + ZeroValue(17), + Constant(25), Splat( size: Quad, value: 33, @@ -2557,7 +2478,7 @@ size: Quad, value: 1, ), - Constant(25), + Constant(21), Splat( size: Quad, value: 3, diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 4e51de80a..2e9dc72f0 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -59,12 +59,6 @@ struct type_26 { }; constant metal::uint3 const_type_1_ = {0u, 0u, 0u}; constant GlobalConst const_GlobalConst = {0u, {}, const_type_1_, 0}; -constant metal::float2 const_type_13_ = {0.0, 0.0}; -constant metal::float4x2 const_type_14_ = {const_type_13_, const_type_13_, const_type_13_, const_type_13_}; -constant type_15 const_type_15_ = {const_type_14_, const_type_14_}; -constant type_18 const_type_18_ = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; -constant type_19 const_type_19_ = {const_type_18_, const_type_18_, const_type_18_, const_type_18_, const_type_18_}; -constant metal::int2 const_type_12_ = {0, 0}; void test_matrix_within_struct_accesses( constant Baz& baz @@ -125,10 +119,10 @@ void test_matrix_within_array_within_struct_accesses( int _e58 = idx_1; int _e60 = idx_1; float unnamed_14 = nested_mat_cx2_.am.inner[0][_e58][_e60]; - t_1 = MatCx2InArray {const_type_15_}; + t_1 = MatCx2InArray {type_15 {}}; int _e66 = idx_1; idx_1 = _e66 + 1; - t_1.am = const_type_15_; + t_1.am = type_15 {}; t_1.am.inner[0] = metal::float4x2(metal::float2(8.0), metal::float2(7.0), metal::float2(6.0), metal::float2(5.0)); t_1.am.inner[0][0] = metal::float2(9.0); int _e93 = idx_1; @@ -200,7 +194,7 @@ vertex foo_vertOutput foo_vert( c2_ = type_22 {a_1, static_cast(b), 3, 4, 5}; c2_.inner[vi + 1u] = 42; int value = c2_.inner[vi]; - float _e48 = test_arr_as_arg(const_type_19_); + float _e48 = test_arr_as_arg(type_19 {}); return foo_vertOutput { metal::float4(_matrix * static_cast(metal::int4(value)), 2.0) }; } @@ -217,7 +211,7 @@ fragment foo_fragOutput foo_frag( bar._matrix = metal::float4x3(metal::float3(0.0), metal::float3(1.0), metal::float3(2.0), metal::float3(3.0)); bar.arr = type_9 {metal::uint2(0u), metal::uint2(1u)}; bar.data[1].value = 1; - qux = const_type_12_; + qux = metal::int2 {}; return foo_fragOutput { metal::float4(0.0) }; } diff --git a/tests/out/msl/bounds-check-image-restrict.msl b/tests/out/msl/bounds-check-image-restrict.msl index f52fc844e..9f94ef0a6 100644 --- a/tests/out/msl/bounds-check-image-restrict.msl +++ b/tests/out/msl/bounds-check-image-restrict.msl @@ -4,9 +4,6 @@ using metal::uint; -constant metal::int2 const_type_4_ = {0, 0}; -constant metal::int3 const_type_8_ = {0, 0, 0}; -constant metal::float4 const_type_2_ = {0.0, 0.0, 0.0, 0.0}; metal::float4 test_textureLoad_1d( int coords, @@ -171,15 +168,15 @@ fragment fragment_shaderOutput fragment_shader( , metal::texture3d image_storage_3d [[user(fake0)]] ) { metal::float4 _e2 = test_textureLoad_1d(0, 0, image_1d); - metal::float4 _e5 = test_textureLoad_2d(const_type_4_, 0, image_2d); - metal::float4 _e9 = test_textureLoad_2d_array_u(const_type_4_, 0u, 0, image_2d_array); - metal::float4 _e13 = test_textureLoad_2d_array_s(const_type_4_, 0, 0, image_2d_array); - metal::float4 _e16 = test_textureLoad_3d(const_type_8_, 0, image_3d); - metal::float4 _e19 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); - test_textureStore_1d(0, const_type_2_, image_storage_1d); - test_textureStore_2d(const_type_4_, const_type_2_, image_storage_2d); - test_textureStore_2d_array_u(const_type_4_, 0u, const_type_2_, image_storage_2d_array); - test_textureStore_2d_array_s(const_type_4_, 0, const_type_2_, image_storage_2d_array); - test_textureStore_3d(const_type_8_, const_type_2_, image_storage_3d); + metal::float4 _e5 = test_textureLoad_2d(metal::int2 {}, 0, image_2d); + metal::float4 _e9 = test_textureLoad_2d_array_u(metal::int2 {}, 0u, 0, image_2d_array); + metal::float4 _e13 = test_textureLoad_2d_array_s(metal::int2 {}, 0, 0, image_2d_array); + metal::float4 _e16 = test_textureLoad_3d(metal::int3 {}, 0, image_3d); + metal::float4 _e19 = test_textureLoad_multisampled_2d(metal::int2 {}, 0, image_multisampled_2d); + test_textureStore_1d(0, metal::float4 {}, image_storage_1d); + test_textureStore_2d(metal::int2 {}, metal::float4 {}, image_storage_2d); + test_textureStore_2d_array_u(metal::int2 {}, 0u, metal::float4 {}, image_storage_2d_array); + test_textureStore_2d_array_s(metal::int2 {}, 0, metal::float4 {}, image_storage_2d_array); + test_textureStore_3d(metal::int3 {}, metal::float4 {}, image_storage_3d); return fragment_shaderOutput { metal::float4(0.0, 0.0, 0.0, 0.0) }; } diff --git a/tests/out/msl/bounds-check-image-rzsw.msl b/tests/out/msl/bounds-check-image-rzsw.msl index db631d713..a93014cb2 100644 --- a/tests/out/msl/bounds-check-image-rzsw.msl +++ b/tests/out/msl/bounds-check-image-rzsw.msl @@ -10,9 +10,6 @@ struct DefaultConstructible { } }; -constant metal::int2 const_type_4_ = {0, 0}; -constant metal::int3 const_type_8_ = {0, 0, 0}; -constant metal::float4 const_type_2_ = {0.0, 0.0, 0.0, 0.0}; metal::float4 test_textureLoad_1d( int coords, @@ -180,15 +177,15 @@ fragment fragment_shaderOutput fragment_shader( , metal::texture3d image_storage_3d [[user(fake0)]] ) { metal::float4 _e2 = test_textureLoad_1d(0, 0, image_1d); - metal::float4 _e5 = test_textureLoad_2d(const_type_4_, 0, image_2d); - metal::float4 _e9 = test_textureLoad_2d_array_u(const_type_4_, 0u, 0, image_2d_array); - metal::float4 _e13 = test_textureLoad_2d_array_s(const_type_4_, 0, 0, image_2d_array); - metal::float4 _e16 = test_textureLoad_3d(const_type_8_, 0, image_3d); - metal::float4 _e19 = test_textureLoad_multisampled_2d(const_type_4_, 0, image_multisampled_2d); - test_textureStore_1d(0, const_type_2_, image_storage_1d); - test_textureStore_2d(const_type_4_, const_type_2_, image_storage_2d); - test_textureStore_2d_array_u(const_type_4_, 0u, const_type_2_, image_storage_2d_array); - test_textureStore_2d_array_s(const_type_4_, 0, const_type_2_, image_storage_2d_array); - test_textureStore_3d(const_type_8_, const_type_2_, image_storage_3d); + metal::float4 _e5 = test_textureLoad_2d(metal::int2 {}, 0, image_2d); + metal::float4 _e9 = test_textureLoad_2d_array_u(metal::int2 {}, 0u, 0, image_2d_array); + metal::float4 _e13 = test_textureLoad_2d_array_s(metal::int2 {}, 0, 0, image_2d_array); + metal::float4 _e16 = test_textureLoad_3d(metal::int3 {}, 0, image_3d); + metal::float4 _e19 = test_textureLoad_multisampled_2d(metal::int2 {}, 0, image_multisampled_2d); + test_textureStore_1d(0, metal::float4 {}, image_storage_1d); + test_textureStore_2d(metal::int2 {}, metal::float4 {}, image_storage_2d); + test_textureStore_2d_array_u(metal::int2 {}, 0u, metal::float4 {}, image_storage_2d_array); + test_textureStore_2d_array_s(metal::int2 {}, 0, metal::float4 {}, image_storage_2d_array); + test_textureStore_3d(metal::int3 {}, metal::float4 {}, image_storage_3d); return fragment_shaderOutput { metal::float4(0.0, 0.0, 0.0, 0.0) }; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index b57d09492..b2f4af0fc 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -32,8 +32,6 @@ struct type_14 { struct type_15 { type_14 inner[2]; }; -constant metal::float3 const_type_4_ = {0.0, 0.0, 0.0}; -constant metal::float3x3 const_type_17_ = {const_type_4_, const_type_4_, const_type_4_}; void test_msl_packed_vec3_as_arg( metal::float3 arg @@ -55,8 +53,8 @@ void test_msl_packed_vec3_( metal::float3 unnamed = data.v3_; metal::float2 unnamed_1 = metal::float3(data.v3_).zx; test_msl_packed_vec3_as_arg(data.v3_); - metal::float3 unnamed_2 = metal::float3(data.v3_) * const_type_17_; - metal::float3 unnamed_3 = const_type_17_ * metal::float3(data.v3_); + metal::float3 unnamed_2 = metal::float3(data.v3_) * metal::float3x3 {}; + metal::float3 unnamed_3 = metal::float3x3 {} * metal::float3(data.v3_); metal::float3 unnamed_4 = data.v3_ * 2.0; metal::float3 unnamed_5 = 2.0 * data.v3_; } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 04eb9d85f..120d526d4 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -4,7 +4,6 @@ using metal::uint; -constant metal::int2 const_type_1_ = {0, 0}; fragment void main_( ) { @@ -15,7 +14,7 @@ fragment void main_( metal::float4 d = ((v) * 0.017453292519943295474); metal::float4 e = metal::saturate(v); metal::float4 g = metal::refract(v, v, 1.0); - int const_dot = ( + const_type_1_.x * const_type_1_.x + const_type_1_.y * const_type_1_.y); + int const_dot = ( + metal::int2 {}.x * metal::int2 {}.x + metal::int2 {}.y * metal::int2 {}.y); uint _e13 = metal::abs(0u); uint first_leading_bit_abs = metal::select(31 - metal::clz(_e13), uint(-1), _e13 == 0 || _e13 == -1); int flb_a = metal::select(31 - metal::clz(metal::select(-1, ~-1, -1 < 0)), int(-1), -1 == 0 || -1 == -1); diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 549ed49ef..e8ae513cb 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -18,18 +18,6 @@ constant metal::float4 v_f32_one = {1.0, 1.0, 1.0, 1.0}; constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0}; constant metal::float4 v_f32_half = {0.5, 0.5, 0.5, 0.5}; constant metal::int4 v_i32_one = {1, 1, 1, 1}; -constant metal::uint2 const_type_12_ = {0u, 0u}; -constant metal::float2 const_type_4_ = {0.0, 0.0}; -constant metal::float2x2 const_type_8_ = {const_type_4_, const_type_4_}; -constant metal::float4 const_type = {0.0, 0.0, 0.0, 0.0}; -constant Foo const_Foo = {const_type, 0}; -constant type_13 const_type_13_ = {const_Foo, const_Foo, const_Foo}; -constant metal::float3 const_type_5_ = {0.0, 0.0, 0.0}; -constant metal::float2x3 const_type_15_ = {const_type_5_, const_type_5_}; -constant metal::float3x3 const_type_16_ = {const_type_5_, const_type_5_, const_type_5_}; -constant metal::float4x3 const_type_17_ = {const_type_5_, const_type_5_, const_type_5_, const_type_5_}; -constant metal::float3x4 const_type_18_ = {const_type, const_type, const_type}; -constant metal::int3 const_type_19_ = {0, 0, 0}; metal::float4 builtins( ) { @@ -81,14 +69,14 @@ float constructors( metal::uint2 unnamed = metal::uint2(0u); metal::float2x2 unnamed_1 = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); type_14 unnamed_2 = type_14 {0, 1, 2, 3}; - bool unnamed_3 = static_cast(false); - int unnamed_4 = static_cast(0); - uint unnamed_5 = static_cast(0u); - float unnamed_6 = static_cast(0.0); - metal::uint2 unnamed_7 = static_cast(const_type_12_); - metal::float2x3 unnamed_8 = metal::float2x3(const_type_15_); - metal::uint2 unnamed_9 = as_type(const_type_12_); - metal::float2x3 unnamed_10 = metal::float2x3(const_type_15_); + bool unnamed_3 = static_cast(bool {}); + int unnamed_4 = static_cast(int {}); + uint unnamed_5 = static_cast(uint {}); + float unnamed_6 = static_cast(float {}); + metal::uint2 unnamed_7 = static_cast(metal::uint2 {}); + metal::float2x3 unnamed_8 = metal::float2x3(metal::float2x3 {}); + metal::uint2 unnamed_9 = as_type(metal::uint2 {}); + metal::float2x3 unnamed_10 = metal::float2x3(metal::float2x3 {}); float _e71 = foo.a.x; return _e71; } @@ -169,13 +157,13 @@ void arithmetic( metal::uint2 unnamed_78 = metal::uint2(2u) % metal::uint2(1u); metal::float2 unnamed_79 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); metal::float2 unnamed_80 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float3x3 unnamed_81 = const_type_16_ + const_type_16_; - metal::float3x3 unnamed_82 = const_type_16_ - const_type_16_; - metal::float3x3 unnamed_83 = const_type_16_ * 1.0; - metal::float3x3 unnamed_84 = 2.0 * const_type_16_; - metal::float3 unnamed_85 = const_type_17_ * metal::float4(1.0); - metal::float4 unnamed_86 = metal::float3(2.0) * const_type_17_; - metal::float3x3 unnamed_87 = const_type_17_ * const_type_18_; + metal::float3x3 unnamed_81 = metal::float3x3 {} + metal::float3x3 {}; + metal::float3x3 unnamed_82 = metal::float3x3 {} - metal::float3x3 {}; + metal::float3x3 unnamed_83 = metal::float3x3 {} * 1.0; + metal::float3x3 unnamed_84 = 2.0 * metal::float3x3 {}; + metal::float3 unnamed_85 = metal::float4x3 {} * metal::float4(1.0); + metal::float4 unnamed_86 = metal::float3(2.0) * metal::float4x3 {}; + metal::float3x3 unnamed_87 = metal::float4x3 {} * metal::float3x4 {}; } void bit( @@ -277,7 +265,7 @@ void assignment( a_1 = _e32 + 1; int _e35 = a_1; a_1 = _e35 - 1; - vec0_ = const_type_19_; + vec0_ = metal::int3 {}; int _e42 = vec0_.y; vec0_.y = _e42 + 1; int _e47 = vec0_.y; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index fa828b4d8..18de89ac1 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 328 +; Bound: 326 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %247 "foo_vert" %242 %245 -OpEntryPoint Fragment %289 "foo_frag" %288 -OpEntryPoint GLCompute %308 "assign_through_ptr" %311 -OpExecutionMode %289 OriginUpperLeft -OpExecutionMode %308 LocalSize 1 1 1 +OpEntryPoint Vertex %243 "foo_vert" %238 %241 +OpEntryPoint Fragment %286 "foo_frag" %285 +OpEntryPoint GLCompute %306 "assign_through_ptr" %309 +OpExecutionMode %286 OriginUpperLeft +OpExecutionMode %306 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %36 0 "a" OpMemberName %36 1 "b" @@ -29,33 +29,33 @@ OpMemberName %49 0 "m" OpName %49 "Baz" OpMemberName %53 0 "am" OpName %53 "MatCx2InArray" -OpName %72 "global_const" -OpName %74 "bar" -OpName %76 "baz" -OpName %79 "qux" -OpName %82 "nested_mat_cx2" -OpName %85 "val" -OpName %86 "idx" -OpName %89 "t" -OpName %93 "test_matrix_within_struct_accesses" -OpName %150 "idx" -OpName %152 "t" -OpName %156 "test_matrix_within_array_within_struct_accesses" -OpName %211 "foo" -OpName %212 "read_from_private" -OpName %217 "a" -OpName %218 "test_arr_as_arg" -OpName %224 "p" -OpName %225 "assign_through_ptr_fn" -OpName %229 "foo" -OpName %230 "assign_array_through_ptr_fn" -OpName %236 "foo" -OpName %238 "c2" -OpName %242 "vi" -OpName %247 "foo_vert" -OpName %289 "foo_frag" -OpName %305 "arr" -OpName %308 "assign_through_ptr" +OpName %66 "global_const" +OpName %68 "bar" +OpName %70 "baz" +OpName %73 "qux" +OpName %76 "nested_mat_cx2" +OpName %79 "val" +OpName %80 "idx" +OpName %83 "t" +OpName %87 "test_matrix_within_struct_accesses" +OpName %144 "idx" +OpName %146 "t" +OpName %150 "test_matrix_within_array_within_struct_accesses" +OpName %207 "foo" +OpName %208 "read_from_private" +OpName %213 "a" +OpName %214 "test_arr_as_arg" +OpName %220 "p" +OpName %221 "assign_through_ptr_fn" +OpName %225 "foo" +OpName %226 "assign_array_through_ptr_fn" +OpName %232 "foo" +OpName %234 "c2" +OpName %238 "vi" +OpName %243 "foo_vert" +OpName %286 "foo_frag" +OpName %303 "arr" +OpName %306 "assign_through_ptr" OpMemberDecorate %36 0 Offset 0 OpMemberDecorate %36 1 Offset 16 OpMemberDecorate %36 2 Offset 28 @@ -85,25 +85,25 @@ OpDecorate %55 ArrayStride 4 OpDecorate %56 ArrayStride 40 OpDecorate %59 ArrayStride 4 OpDecorate %62 ArrayStride 16 -OpDecorate %74 DescriptorSet 0 -OpDecorate %74 Binding 0 +OpDecorate %68 DescriptorSet 0 +OpDecorate %68 Binding 0 OpDecorate %47 Block +OpDecorate %70 DescriptorSet 0 +OpDecorate %70 Binding 1 +OpDecorate %71 Block +OpMemberDecorate %71 0 Offset 0 +OpDecorate %73 DescriptorSet 0 +OpDecorate %73 Binding 2 +OpDecorate %74 Block +OpMemberDecorate %74 0 Offset 0 OpDecorate %76 DescriptorSet 0 -OpDecorate %76 Binding 1 +OpDecorate %76 Binding 3 OpDecorate %77 Block OpMemberDecorate %77 0 Offset 0 -OpDecorate %79 DescriptorSet 0 -OpDecorate %79 Binding 2 -OpDecorate %80 Block -OpMemberDecorate %80 0 Offset 0 -OpDecorate %82 DescriptorSet 0 -OpDecorate %82 Binding 3 -OpDecorate %83 Block -OpMemberDecorate %83 0 Offset 0 -OpDecorate %242 BuiltIn VertexIndex -OpDecorate %245 BuiltIn Position -OpDecorate %288 Location 0 -OpDecorate %311 BuiltIn LocalInvocationId +OpDecorate %238 BuiltIn VertexIndex +OpDecorate %241 BuiltIn Position +OpDecorate %285 Location 0 +OpDecorate %309 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -125,12 +125,12 @@ OpDecorate %311 BuiltIn LocalInvocationId %20 = OpConstant %11 20.0 %21 = OpConstant %11 30.0 %22 = OpConstant %11 40.0 -%23 = OpConstant %11 0.0 -%24 = OpConstant %11 8.0 -%25 = OpConstant %11 7.0 -%26 = OpConstant %6 5 -%27 = OpConstant %6 4 -%28 = OpConstant %6 9 +%23 = OpConstant %11 8.0 +%24 = OpConstant %11 7.0 +%25 = OpConstant %6 5 +%26 = OpConstant %6 4 +%27 = OpConstant %6 9 +%28 = OpConstant %11 0.0 %29 = OpConstant %4 3 %30 = OpConstant %4 2 %31 = OpConstant %6 3 @@ -158,345 +158,343 @@ OpDecorate %311 BuiltIn LocalInvocationId %53 = OpTypeStruct %52 %54 = OpTypePointer Function %11 %55 = OpTypeArray %11 %8 -%56 = OpTypeArray %55 %26 +%56 = OpTypeArray %55 %25 %57 = OpTypeVector %11 4 %58 = OpTypePointer StorageBuffer %6 -%59 = OpTypeArray %6 %26 +%59 = OpTypeArray %6 %25 %60 = OpTypeVector %6 4 %61 = OpTypePointer Workgroup %4 %62 = OpTypeArray %57 %7 %63 = OpTypePointer Function %62 %64 = OpConstantComposite %35 %3 %3 %3 %65 = OpConstantComposite %36 %3 %64 %5 -%66 = OpConstantComposite %41 %23 %23 -%67 = OpConstantComposite %51 %66 %66 %66 %66 -%68 = OpConstantComposite %52 %67 %67 -%69 = OpConstantComposite %55 %23 %23 %23 %23 %23 %23 %23 %23 %23 %23 -%70 = OpConstantComposite %56 %69 %69 %69 %69 %69 -%71 = OpConstantComposite %50 %5 %5 -%73 = OpTypePointer Private %36 -%72 = OpVariable %73 Private %65 -%75 = OpTypePointer StorageBuffer %47 -%74 = OpVariable %75 StorageBuffer -%77 = OpTypeStruct %49 +%67 = OpTypePointer Private %36 +%66 = OpVariable %67 Private %65 +%69 = OpTypePointer StorageBuffer %47 +%68 = OpVariable %69 StorageBuffer +%71 = OpTypeStruct %49 +%72 = OpTypePointer Uniform %71 +%70 = OpVariable %72 Uniform +%74 = OpTypeStruct %50 +%75 = OpTypePointer StorageBuffer %74 +%73 = OpVariable %75 StorageBuffer +%77 = OpTypeStruct %53 %78 = OpTypePointer Uniform %77 %76 = OpVariable %78 Uniform -%80 = OpTypeStruct %50 -%81 = OpTypePointer StorageBuffer %80 -%79 = OpVariable %81 StorageBuffer -%83 = OpTypeStruct %53 -%84 = OpTypePointer Uniform %83 -%82 = OpVariable %84 Uniform -%85 = OpVariable %61 Workgroup -%87 = OpTypePointer Function %6 -%88 = OpConstantNull %6 -%90 = OpTypePointer Function %49 -%91 = OpConstantNull %49 -%94 = OpTypeFunction %2 -%95 = OpTypePointer Uniform %49 -%100 = OpTypePointer Uniform %48 -%103 = OpTypePointer Uniform %41 -%109 = OpTypePointer Uniform %11 -%129 = OpTypePointer Function %48 -%135 = OpTypePointer Function %41 -%141 = OpTypePointer Function %11 -%151 = OpConstantNull %6 -%153 = OpTypePointer Function %53 -%154 = OpConstantNull %53 -%157 = OpTypePointer Uniform %53 -%162 = OpTypePointer Uniform %52 -%165 = OpTypePointer Uniform %51 -%188 = OpTypePointer Function %52 -%190 = OpTypePointer Function %51 -%213 = OpTypeFunction %11 %54 -%219 = OpTypeFunction %11 %56 -%226 = OpTypeFunction %2 %61 -%231 = OpTypeFunction %2 %63 -%237 = OpConstantNull %11 -%239 = OpTypePointer Function %59 -%240 = OpConstantNull %59 -%243 = OpTypePointer Input %4 -%242 = OpVariable %243 Input -%246 = OpTypePointer Output %57 -%245 = OpVariable %246 Output -%249 = OpTypePointer StorageBuffer %50 -%256 = OpTypePointer StorageBuffer %38 -%259 = OpTypePointer StorageBuffer %45 -%260 = OpConstant %4 4 -%263 = OpTypePointer StorageBuffer %39 -%264 = OpTypePointer StorageBuffer %11 -%267 = OpTypePointer StorageBuffer %46 -%270 = OpTypePointer StorageBuffer %37 -%271 = OpConstant %4 5 -%288 = OpVariable %246 Output -%306 = OpConstantNull %62 -%310 = OpConstantNull %4 -%312 = OpTypePointer Input %35 -%311 = OpVariable %312 Input -%314 = OpConstantNull %35 -%316 = OpTypeBool -%315 = OpTypeVector %316 3 -%321 = OpConstant %4 264 -%93 = OpFunction %2 None %94 -%92 = OpLabel -%86 = OpVariable %87 Function %88 -%89 = OpVariable %90 Function %91 -%96 = OpAccessChain %95 %76 %3 -OpBranch %97 -%97 = OpLabel -OpStore %86 %9 -%98 = OpLoad %6 %86 -%99 = OpISub %6 %98 %9 -OpStore %86 %99 -%101 = OpAccessChain %100 %96 %3 -%102 = OpLoad %48 %101 -%104 = OpAccessChain %103 %96 %3 %3 -%105 = OpLoad %41 %104 -%106 = OpLoad %6 %86 -%107 = OpAccessChain %103 %96 %3 %106 -%108 = OpLoad %41 %107 -%110 = OpAccessChain %109 %96 %3 %3 %32 +%79 = OpVariable %61 Workgroup +%81 = OpTypePointer Function %6 +%82 = OpConstantNull %6 +%84 = OpTypePointer Function %49 +%85 = OpConstantNull %49 +%88 = OpTypeFunction %2 +%89 = OpTypePointer Uniform %49 +%94 = OpTypePointer Uniform %48 +%97 = OpTypePointer Uniform %41 +%103 = OpTypePointer Uniform %11 +%123 = OpTypePointer Function %48 +%129 = OpTypePointer Function %41 +%135 = OpTypePointer Function %11 +%145 = OpConstantNull %6 +%147 = OpTypePointer Function %53 +%148 = OpConstantNull %53 +%151 = OpTypePointer Uniform %53 +%153 = OpConstantNull %52 +%154 = OpConstantNull %52 +%158 = OpTypePointer Uniform %52 +%161 = OpTypePointer Uniform %51 +%184 = OpTypePointer Function %52 +%186 = OpTypePointer Function %51 +%209 = OpTypeFunction %11 %54 +%215 = OpTypeFunction %11 %56 +%222 = OpTypeFunction %2 %61 +%227 = OpTypeFunction %2 %63 +%233 = OpConstantNull %11 +%235 = OpTypePointer Function %59 +%236 = OpConstantNull %59 +%239 = OpTypePointer Input %4 +%238 = OpVariable %239 Input +%242 = OpTypePointer Output %57 +%241 = OpVariable %242 Output +%245 = OpTypePointer StorageBuffer %50 +%248 = OpConstantNull %56 +%253 = OpTypePointer StorageBuffer %38 +%256 = OpTypePointer StorageBuffer %45 +%257 = OpConstant %4 4 +%260 = OpTypePointer StorageBuffer %39 +%261 = OpTypePointer StorageBuffer %11 +%264 = OpTypePointer StorageBuffer %46 +%267 = OpTypePointer StorageBuffer %37 +%268 = OpConstant %4 5 +%285 = OpVariable %242 Output +%288 = OpConstantNull %50 +%304 = OpConstantNull %62 +%308 = OpConstantNull %4 +%310 = OpTypePointer Input %35 +%309 = OpVariable %310 Input +%312 = OpConstantNull %35 +%314 = OpTypeBool +%313 = OpTypeVector %314 3 +%319 = OpConstant %4 264 +%87 = OpFunction %2 None %88 +%86 = OpLabel +%80 = OpVariable %81 Function %82 +%83 = OpVariable %84 Function %85 +%90 = OpAccessChain %89 %70 %3 +OpBranch %91 +%91 = OpLabel +OpStore %80 %9 +%92 = OpLoad %6 %80 +%93 = OpISub %6 %92 %9 +OpStore %80 %93 +%95 = OpAccessChain %94 %90 %3 +%96 = OpLoad %48 %95 +%98 = OpAccessChain %97 %90 %3 %3 +%99 = OpLoad %41 %98 +%100 = OpLoad %6 %80 +%101 = OpAccessChain %97 %90 %3 %100 +%102 = OpLoad %41 %101 +%104 = OpAccessChain %103 %90 %3 %3 %32 +%105 = OpLoad %11 %104 +%106 = OpLoad %6 %80 +%107 = OpAccessChain %103 %90 %3 %3 %106 +%108 = OpLoad %11 %107 +%109 = OpLoad %6 %80 +%110 = OpAccessChain %103 %90 %3 %109 %32 %111 = OpLoad %11 %110 -%112 = OpLoad %6 %86 -%113 = OpAccessChain %109 %96 %3 %3 %112 -%114 = OpLoad %11 %113 -%115 = OpLoad %6 %86 -%116 = OpAccessChain %109 %96 %3 %115 %32 -%117 = OpLoad %11 %116 -%118 = OpLoad %6 %86 -%119 = OpLoad %6 %86 -%120 = OpAccessChain %109 %96 %3 %118 %119 -%121 = OpLoad %11 %120 -%122 = OpCompositeConstruct %41 %10 %10 -%123 = OpCompositeConstruct %41 %12 %12 -%124 = OpCompositeConstruct %41 %13 %13 -%125 = OpCompositeConstruct %48 %122 %123 %124 -%126 = OpCompositeConstruct %49 %125 -OpStore %89 %126 -%127 = OpLoad %6 %86 -%128 = OpIAdd %6 %127 %9 -OpStore %86 %128 -%130 = OpCompositeConstruct %41 %14 %14 -%131 = OpCompositeConstruct %41 %15 %15 -%132 = OpCompositeConstruct %41 %16 %16 -%133 = OpCompositeConstruct %48 %130 %131 %132 -%134 = OpAccessChain %129 %89 %3 +%112 = OpLoad %6 %80 +%113 = OpLoad %6 %80 +%114 = OpAccessChain %103 %90 %3 %112 %113 +%115 = OpLoad %11 %114 +%116 = OpCompositeConstruct %41 %10 %10 +%117 = OpCompositeConstruct %41 %12 %12 +%118 = OpCompositeConstruct %41 %13 %13 +%119 = OpCompositeConstruct %48 %116 %117 %118 +%120 = OpCompositeConstruct %49 %119 +OpStore %83 %120 +%121 = OpLoad %6 %80 +%122 = OpIAdd %6 %121 %9 +OpStore %80 %122 +%124 = OpCompositeConstruct %41 %14 %14 +%125 = OpCompositeConstruct %41 %15 %15 +%126 = OpCompositeConstruct %41 %16 %16 +%127 = OpCompositeConstruct %48 %124 %125 %126 +%128 = OpAccessChain %123 %83 %3 +OpStore %128 %127 +%130 = OpCompositeConstruct %41 %17 %17 +%131 = OpAccessChain %129 %83 %3 %3 +OpStore %131 %130 +%132 = OpLoad %6 %80 +%133 = OpCompositeConstruct %41 %18 %18 +%134 = OpAccessChain %129 %83 %3 %132 OpStore %134 %133 -%136 = OpCompositeConstruct %41 %17 %17 -%137 = OpAccessChain %135 %89 %3 %3 -OpStore %137 %136 -%138 = OpLoad %6 %86 -%139 = OpCompositeConstruct %41 %18 %18 -%140 = OpAccessChain %135 %89 %3 %138 -OpStore %140 %139 -%142 = OpAccessChain %141 %89 %3 %3 %32 -OpStore %142 %19 -%143 = OpLoad %6 %86 -%144 = OpAccessChain %141 %89 %3 %3 %143 -OpStore %144 %20 -%145 = OpLoad %6 %86 -%146 = OpAccessChain %141 %89 %3 %145 %32 -OpStore %146 %21 -%147 = OpLoad %6 %86 -%148 = OpLoad %6 %86 -%149 = OpAccessChain %141 %89 %3 %147 %148 -OpStore %149 %22 +%136 = OpAccessChain %135 %83 %3 %3 %32 +OpStore %136 %19 +%137 = OpLoad %6 %80 +%138 = OpAccessChain %135 %83 %3 %3 %137 +OpStore %138 %20 +%139 = OpLoad %6 %80 +%140 = OpAccessChain %135 %83 %3 %139 %32 +OpStore %140 %21 +%141 = OpLoad %6 %80 +%142 = OpLoad %6 %80 +%143 = OpAccessChain %135 %83 %3 %141 %142 +OpStore %143 %22 OpReturn OpFunctionEnd -%156 = OpFunction %2 None %94 +%150 = OpFunction %2 None %88 +%149 = OpLabel +%144 = OpVariable %81 Function %145 +%146 = OpVariable %147 Function %148 +%152 = OpAccessChain %151 %76 %3 +OpBranch %155 %155 = OpLabel -%150 = OpVariable %87 Function %151 -%152 = OpVariable %153 Function %154 -%158 = OpAccessChain %157 %82 %3 -OpBranch %159 -%159 = OpLabel -OpStore %150 %9 -%160 = OpLoad %6 %150 -%161 = OpISub %6 %160 %9 -OpStore %150 %161 -%163 = OpAccessChain %162 %158 %3 -%164 = OpLoad %52 %163 -%166 = OpAccessChain %165 %158 %3 %3 -%167 = OpLoad %51 %166 -%168 = OpAccessChain %103 %158 %3 %3 %3 -%169 = OpLoad %41 %168 -%170 = OpLoad %6 %150 -%171 = OpAccessChain %103 %158 %3 %3 %170 -%172 = OpLoad %41 %171 -%173 = OpAccessChain %109 %158 %3 %3 %3 %32 -%174 = OpLoad %11 %173 -%175 = OpLoad %6 %150 -%176 = OpAccessChain %109 %158 %3 %3 %3 %175 -%177 = OpLoad %11 %176 -%178 = OpLoad %6 %150 -%179 = OpAccessChain %109 %158 %3 %3 %178 %32 +OpStore %144 %9 +%156 = OpLoad %6 %144 +%157 = OpISub %6 %156 %9 +OpStore %144 %157 +%159 = OpAccessChain %158 %152 %3 +%160 = OpLoad %52 %159 +%162 = OpAccessChain %161 %152 %3 %3 +%163 = OpLoad %51 %162 +%164 = OpAccessChain %97 %152 %3 %3 %3 +%165 = OpLoad %41 %164 +%166 = OpLoad %6 %144 +%167 = OpAccessChain %97 %152 %3 %3 %166 +%168 = OpLoad %41 %167 +%169 = OpAccessChain %103 %152 %3 %3 %3 %32 +%170 = OpLoad %11 %169 +%171 = OpLoad %6 %144 +%172 = OpAccessChain %103 %152 %3 %3 %3 %171 +%173 = OpLoad %11 %172 +%174 = OpLoad %6 %144 +%175 = OpAccessChain %103 %152 %3 %3 %174 %32 +%176 = OpLoad %11 %175 +%177 = OpLoad %6 %144 +%178 = OpLoad %6 %144 +%179 = OpAccessChain %103 %152 %3 %3 %177 %178 %180 = OpLoad %11 %179 -%181 = OpLoad %6 %150 -%182 = OpLoad %6 %150 -%183 = OpAccessChain %109 %158 %3 %3 %181 %182 -%184 = OpLoad %11 %183 -%185 = OpCompositeConstruct %53 %68 -OpStore %152 %185 -%186 = OpLoad %6 %150 -%187 = OpIAdd %6 %186 %9 -OpStore %150 %187 -%189 = OpAccessChain %188 %152 %3 -OpStore %189 %68 -%191 = OpCompositeConstruct %41 %24 %24 -%192 = OpCompositeConstruct %41 %25 %25 -%193 = OpCompositeConstruct %41 %14 %14 -%194 = OpCompositeConstruct %41 %15 %15 -%195 = OpCompositeConstruct %51 %191 %192 %193 %194 -%196 = OpAccessChain %190 %152 %3 %3 -OpStore %196 %195 -%197 = OpCompositeConstruct %41 %17 %17 -%198 = OpAccessChain %135 %152 %3 %3 %3 -OpStore %198 %197 -%199 = OpLoad %6 %150 -%200 = OpCompositeConstruct %41 %18 %18 -%201 = OpAccessChain %135 %152 %3 %3 %199 -OpStore %201 %200 -%202 = OpAccessChain %141 %152 %3 %3 %3 %32 -OpStore %202 %19 -%203 = OpLoad %6 %150 -%204 = OpAccessChain %141 %152 %3 %3 %3 %203 -OpStore %204 %20 -%205 = OpLoad %6 %150 -%206 = OpAccessChain %141 %152 %3 %3 %205 %32 -OpStore %206 %21 -%207 = OpLoad %6 %150 -%208 = OpLoad %6 %150 -%209 = OpAccessChain %141 %152 %3 %3 %207 %208 -OpStore %209 %22 +%181 = OpCompositeConstruct %53 %153 +OpStore %146 %181 +%182 = OpLoad %6 %144 +%183 = OpIAdd %6 %182 %9 +OpStore %144 %183 +%185 = OpAccessChain %184 %146 %3 +OpStore %185 %154 +%187 = OpCompositeConstruct %41 %23 %23 +%188 = OpCompositeConstruct %41 %24 %24 +%189 = OpCompositeConstruct %41 %14 %14 +%190 = OpCompositeConstruct %41 %15 %15 +%191 = OpCompositeConstruct %51 %187 %188 %189 %190 +%192 = OpAccessChain %186 %146 %3 %3 +OpStore %192 %191 +%193 = OpCompositeConstruct %41 %17 %17 +%194 = OpAccessChain %129 %146 %3 %3 %3 +OpStore %194 %193 +%195 = OpLoad %6 %144 +%196 = OpCompositeConstruct %41 %18 %18 +%197 = OpAccessChain %129 %146 %3 %3 %195 +OpStore %197 %196 +%198 = OpAccessChain %135 %146 %3 %3 %3 %32 +OpStore %198 %19 +%199 = OpLoad %6 %144 +%200 = OpAccessChain %135 %146 %3 %3 %3 %199 +OpStore %200 %20 +%201 = OpLoad %6 %144 +%202 = OpAccessChain %135 %146 %3 %3 %201 %32 +OpStore %202 %21 +%203 = OpLoad %6 %144 +%204 = OpLoad %6 %144 +%205 = OpAccessChain %135 %146 %3 %3 %203 %204 +OpStore %205 %22 OpReturn OpFunctionEnd -%212 = OpFunction %11 None %213 -%211 = OpFunctionParameter %54 +%208 = OpFunction %11 None %209 +%207 = OpFunctionParameter %54 +%206 = OpLabel +OpBranch %210 %210 = OpLabel -OpBranch %214 -%214 = OpLabel -%215 = OpLoad %11 %211 -OpReturnValue %215 +%211 = OpLoad %11 %207 +OpReturnValue %211 OpFunctionEnd -%218 = OpFunction %11 None %219 -%217 = OpFunctionParameter %56 +%214 = OpFunction %11 None %215 +%213 = OpFunctionParameter %56 +%212 = OpLabel +OpBranch %216 %216 = OpLabel -OpBranch %220 -%220 = OpLabel -%221 = OpCompositeExtract %55 %217 4 -%222 = OpCompositeExtract %11 %221 9 -OpReturnValue %222 +%217 = OpCompositeExtract %55 %213 4 +%218 = OpCompositeExtract %11 %217 9 +OpReturnValue %218 OpFunctionEnd -%225 = OpFunction %2 None %226 -%224 = OpFunctionParameter %61 +%221 = OpFunction %2 None %222 +%220 = OpFunctionParameter %61 +%219 = OpLabel +OpBranch %223 %223 = OpLabel -OpBranch %227 -%227 = OpLabel -OpStore %224 %34 +OpStore %220 %34 OpReturn OpFunctionEnd -%230 = OpFunction %2 None %231 -%229 = OpFunctionParameter %63 +%226 = OpFunction %2 None %227 +%225 = OpFunctionParameter %63 +%224 = OpLabel +OpBranch %228 %228 = OpLabel -OpBranch %232 -%232 = OpLabel -%233 = OpCompositeConstruct %57 %10 %10 %10 %10 -%234 = OpCompositeConstruct %57 %12 %12 %12 %12 -%235 = OpCompositeConstruct %62 %233 %234 -OpStore %229 %235 +%229 = OpCompositeConstruct %57 %10 %10 %10 %10 +%230 = OpCompositeConstruct %57 %12 %12 %12 %12 +%231 = OpCompositeConstruct %62 %229 %230 +OpStore %225 %231 OpReturn OpFunctionEnd -%247 = OpFunction %2 None %94 -%241 = OpLabel -%236 = OpVariable %54 Function %237 -%238 = OpVariable %239 Function %240 -%244 = OpLoad %4 %242 -%248 = OpAccessChain %95 %76 %3 -%250 = OpAccessChain %249 %79 %3 -%251 = OpAccessChain %157 %82 %3 -OpBranch %252 -%252 = OpLabel -OpStore %236 %23 -%253 = OpLoad %11 %236 -OpStore %236 %10 -%254 = OpFunctionCall %2 %93 -%255 = OpFunctionCall %2 %156 -%257 = OpAccessChain %256 %74 %3 -%258 = OpLoad %38 %257 -%261 = OpAccessChain %259 %74 %260 -%262 = OpLoad %45 %261 -%265 = OpAccessChain %264 %74 %3 %29 %3 -%266 = OpLoad %11 %265 -%268 = OpArrayLength %4 %74 5 -%269 = OpISub %4 %268 %30 -%272 = OpAccessChain %58 %74 %271 %269 %3 -%273 = OpLoad %6 %272 -%274 = OpLoad %50 %250 -%275 = OpFunctionCall %11 %212 %236 -%276 = OpConvertFToS %6 %266 -%277 = OpCompositeConstruct %59 %273 %276 %31 %27 %26 -OpStore %238 %277 -%278 = OpIAdd %4 %244 %32 -%279 = OpAccessChain %87 %238 %278 -OpStore %279 %33 -%280 = OpAccessChain %87 %238 %244 -%281 = OpLoad %6 %280 -%282 = OpFunctionCall %11 %218 %70 -%283 = OpCompositeConstruct %60 %281 %281 %281 %281 -%284 = OpConvertSToF %57 %283 -%285 = OpMatrixTimesVector %39 %258 %284 -%286 = OpCompositeConstruct %57 %285 %12 -OpStore %245 %286 +%243 = OpFunction %2 None %88 +%237 = OpLabel +%232 = OpVariable %54 Function %233 +%234 = OpVariable %235 Function %236 +%240 = OpLoad %4 %238 +%244 = OpAccessChain %89 %70 %3 +%246 = OpAccessChain %245 %73 %3 +%247 = OpAccessChain %151 %76 %3 +OpBranch %249 +%249 = OpLabel +OpStore %232 %28 +%250 = OpLoad %11 %232 +OpStore %232 %10 +%251 = OpFunctionCall %2 %87 +%252 = OpFunctionCall %2 %150 +%254 = OpAccessChain %253 %68 %3 +%255 = OpLoad %38 %254 +%258 = OpAccessChain %256 %68 %257 +%259 = OpLoad %45 %258 +%262 = OpAccessChain %261 %68 %3 %29 %3 +%263 = OpLoad %11 %262 +%265 = OpArrayLength %4 %68 5 +%266 = OpISub %4 %265 %30 +%269 = OpAccessChain %58 %68 %268 %266 %3 +%270 = OpLoad %6 %269 +%271 = OpLoad %50 %246 +%272 = OpFunctionCall %11 %208 %232 +%273 = OpConvertFToS %6 %263 +%274 = OpCompositeConstruct %59 %270 %273 %31 %26 %25 +OpStore %234 %274 +%275 = OpIAdd %4 %240 %32 +%276 = OpAccessChain %81 %234 %275 +OpStore %276 %33 +%277 = OpAccessChain %81 %234 %240 +%278 = OpLoad %6 %277 +%279 = OpFunctionCall %11 %214 %248 +%280 = OpCompositeConstruct %60 %278 %278 %278 %278 +%281 = OpConvertSToF %57 %280 +%282 = OpMatrixTimesVector %39 %255 %281 +%283 = OpCompositeConstruct %57 %282 %12 +OpStore %241 %283 OpReturn OpFunctionEnd -%289 = OpFunction %2 None %94 -%287 = OpLabel -%290 = OpAccessChain %249 %79 %3 -OpBranch %291 -%291 = OpLabel -%292 = OpAccessChain %264 %74 %3 %32 %30 -OpStore %292 %10 -%293 = OpCompositeConstruct %39 %23 %23 %23 -%294 = OpCompositeConstruct %39 %10 %10 %10 -%295 = OpCompositeConstruct %39 %12 %12 %12 -%296 = OpCompositeConstruct %39 %13 %13 %13 -%297 = OpCompositeConstruct %38 %293 %294 %295 %296 -%298 = OpAccessChain %256 %74 %3 -OpStore %298 %297 -%299 = OpCompositeConstruct %44 %3 %3 -%300 = OpCompositeConstruct %44 %32 %32 -%301 = OpCompositeConstruct %45 %299 %300 -%302 = OpAccessChain %259 %74 %260 -OpStore %302 %301 -%303 = OpAccessChain %58 %74 %271 %32 %3 -OpStore %303 %9 -OpStore %290 %71 -%304 = OpCompositeConstruct %57 %23 %23 %23 %23 -OpStore %288 %304 +%286 = OpFunction %2 None %88 +%284 = OpLabel +%287 = OpAccessChain %245 %73 %3 +OpBranch %289 +%289 = OpLabel +%290 = OpAccessChain %261 %68 %3 %32 %30 +OpStore %290 %10 +%291 = OpCompositeConstruct %39 %28 %28 %28 +%292 = OpCompositeConstruct %39 %10 %10 %10 +%293 = OpCompositeConstruct %39 %12 %12 %12 +%294 = OpCompositeConstruct %39 %13 %13 %13 +%295 = OpCompositeConstruct %38 %291 %292 %293 %294 +%296 = OpAccessChain %253 %68 %3 +OpStore %296 %295 +%297 = OpCompositeConstruct %44 %3 %3 +%298 = OpCompositeConstruct %44 %32 %32 +%299 = OpCompositeConstruct %45 %297 %298 +%300 = OpAccessChain %256 %68 %257 +OpStore %300 %299 +%301 = OpAccessChain %58 %68 %268 %32 %3 +OpStore %301 %9 +OpStore %287 %288 +%302 = OpCompositeConstruct %57 %28 %28 %28 %28 +OpStore %285 %302 OpReturn OpFunctionEnd -%308 = OpFunction %2 None %94 +%306 = OpFunction %2 None %88 +%305 = OpLabel +%303 = OpVariable %63 Function %304 +OpBranch %307 %307 = OpLabel -%305 = OpVariable %63 Function %306 -OpBranch %309 -%309 = OpLabel -%313 = OpLoad %35 %311 -%317 = OpIEqual %315 %313 %314 -%318 = OpAll %316 %317 -OpSelectionMerge %319 None -OpBranchConditional %318 %320 %319 +%311 = OpLoad %35 %309 +%315 = OpIEqual %313 %311 %312 +%316 = OpAll %314 %315 +OpSelectionMerge %317 None +OpBranchConditional %316 %318 %317 +%318 = OpLabel +OpStore %79 %308 +OpBranch %317 +%317 = OpLabel +OpControlBarrier %30 %30 %319 +OpBranch %320 %320 = OpLabel -OpStore %85 %310 -OpBranch %319 -%319 = OpLabel -OpControlBarrier %30 %30 %321 -OpBranch %322 -%322 = OpLabel -%323 = OpCompositeConstruct %57 %14 %14 %14 %14 -%324 = OpCompositeConstruct %57 %25 %25 %25 %25 -%325 = OpCompositeConstruct %62 %323 %324 -OpStore %305 %325 -%326 = OpFunctionCall %2 %225 %85 -%327 = OpFunctionCall %2 %230 %305 +%321 = OpCompositeConstruct %57 %14 %14 %14 %14 +%322 = OpCompositeConstruct %57 %24 %24 %24 %24 +%323 = OpCompositeConstruct %62 %321 %322 +OpStore %303 %323 +%324 = OpFunctionCall %2 %221 %79 +%325 = OpFunctionCall %2 %226 %303 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index 09d6ad2f4..33f900023 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -1,109 +1,109 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 299 +; Bound: 310 OpCapability ImageQuery OpCapability Image1D OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %275 "fragment_shader" %273 -OpExecutionMode %275 OriginUpperLeft +OpEntryPoint Fragment %272 "fragment_shader" %270 +OpExecutionMode %272 OriginUpperLeft OpSource GLSL 450 -OpName %27 "image_1d" -OpName %29 "image_2d" -OpName %31 "image_2d_array" -OpName %33 "image_3d" -OpName %35 "image_multisampled_2d" -OpName %37 "image_depth_2d" -OpName %39 "image_depth_2d_array" -OpName %41 "image_depth_multisampled_2d" -OpName %43 "image_storage_1d" -OpName %45 "image_storage_2d" -OpName %47 "image_storage_2d_array" -OpName %49 "image_storage_3d" -OpName %52 "coords" -OpName %53 "level" -OpName %54 "test_textureLoad_1d" -OpName %67 "coords" -OpName %68 "level" -OpName %69 "test_textureLoad_2d" -OpName %82 "coords" -OpName %83 "index" -OpName %84 "level" -OpName %85 "test_textureLoad_2d_array_u" -OpName %100 "coords" -OpName %101 "index" -OpName %102 "level" -OpName %103 "test_textureLoad_2d_array_s" -OpName %117 "coords" -OpName %118 "level" -OpName %119 "test_textureLoad_3d" -OpName %132 "coords" -OpName %133 "_sample" -OpName %134 "test_textureLoad_multisampled_2d" -OpName %146 "coords" -OpName %147 "level" -OpName %148 "test_textureLoad_depth_2d" -OpName %162 "coords" -OpName %163 "index" -OpName %164 "level" -OpName %165 "test_textureLoad_depth_2d_array_u" -OpName %181 "coords" -OpName %182 "index" -OpName %183 "level" -OpName %184 "test_textureLoad_depth_2d_array_s" -OpName %199 "coords" -OpName %200 "_sample" -OpName %201 "test_textureLoad_depth_multisampled_2d" -OpName %214 "coords" -OpName %215 "value" -OpName %216 "test_textureStore_1d" -OpName %224 "coords" -OpName %225 "value" -OpName %226 "test_textureStore_2d" -OpName %235 "coords" -OpName %236 "array_index" -OpName %237 "value" -OpName %238 "test_textureStore_2d_array_u" -OpName %249 "coords" -OpName %250 "array_index" -OpName %251 "value" -OpName %252 "test_textureStore_2d_array_s" -OpName %262 "coords" -OpName %263 "value" -OpName %264 "test_textureStore_3d" -OpName %275 "fragment_shader" -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 0 -OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 1 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 2 -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 3 -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 4 -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 5 -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 6 -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 7 -OpDecorate %43 NonReadable -OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 8 -OpDecorate %45 NonReadable -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 9 -OpDecorate %47 NonReadable -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 10 -OpDecorate %49 NonReadable -OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 11 -OpDecorate %273 Location 0 +OpName %24 "image_1d" +OpName %26 "image_2d" +OpName %28 "image_2d_array" +OpName %30 "image_3d" +OpName %32 "image_multisampled_2d" +OpName %34 "image_depth_2d" +OpName %36 "image_depth_2d_array" +OpName %38 "image_depth_multisampled_2d" +OpName %40 "image_storage_1d" +OpName %42 "image_storage_2d" +OpName %44 "image_storage_2d_array" +OpName %46 "image_storage_3d" +OpName %49 "coords" +OpName %50 "level" +OpName %51 "test_textureLoad_1d" +OpName %64 "coords" +OpName %65 "level" +OpName %66 "test_textureLoad_2d" +OpName %79 "coords" +OpName %80 "index" +OpName %81 "level" +OpName %82 "test_textureLoad_2d_array_u" +OpName %97 "coords" +OpName %98 "index" +OpName %99 "level" +OpName %100 "test_textureLoad_2d_array_s" +OpName %114 "coords" +OpName %115 "level" +OpName %116 "test_textureLoad_3d" +OpName %129 "coords" +OpName %130 "_sample" +OpName %131 "test_textureLoad_multisampled_2d" +OpName %143 "coords" +OpName %144 "level" +OpName %145 "test_textureLoad_depth_2d" +OpName %159 "coords" +OpName %160 "index" +OpName %161 "level" +OpName %162 "test_textureLoad_depth_2d_array_u" +OpName %178 "coords" +OpName %179 "index" +OpName %180 "level" +OpName %181 "test_textureLoad_depth_2d_array_s" +OpName %196 "coords" +OpName %197 "_sample" +OpName %198 "test_textureLoad_depth_multisampled_2d" +OpName %211 "coords" +OpName %212 "value" +OpName %213 "test_textureStore_1d" +OpName %221 "coords" +OpName %222 "value" +OpName %223 "test_textureStore_2d" +OpName %232 "coords" +OpName %233 "array_index" +OpName %234 "value" +OpName %235 "test_textureStore_2d_array_u" +OpName %246 "coords" +OpName %247 "array_index" +OpName %248 "value" +OpName %249 "test_textureStore_2d_array_s" +OpName %259 "coords" +OpName %260 "value" +OpName %261 "test_textureStore_3d" +OpName %272 "fragment_shader" +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 0 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 1 +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 2 +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 3 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 4 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 5 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 6 +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 7 +OpDecorate %40 NonReadable +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 8 +OpDecorate %42 NonReadable +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 9 +OpDecorate %44 NonReadable +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 10 +OpDecorate %46 NonReadable +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 11 +OpDecorate %270 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 0 @@ -126,332 +126,343 @@ OpDecorate %273 Location 0 %21 = OpTypeImage %8 2D 0 0 0 2 Rgba8 %22 = OpTypeImage %8 2D 0 1 0 2 Rgba8 %23 = OpTypeImage %8 3D 0 0 0 2 Rgba8 -%24 = OpConstantComposite %12 %3 %3 -%25 = OpConstantComposite %15 %3 %3 %3 -%26 = OpConstantComposite %10 %7 %7 %7 %7 -%28 = OpTypePointer UniformConstant %9 -%27 = OpVariable %28 UniformConstant -%30 = OpTypePointer UniformConstant %11 -%29 = OpVariable %30 UniformConstant -%32 = OpTypePointer UniformConstant %13 -%31 = OpVariable %32 UniformConstant -%34 = OpTypePointer UniformConstant %14 -%33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %16 -%35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %17 -%37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %18 -%39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %19 -%41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %20 -%43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %21 -%45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %22 -%47 = OpVariable %48 UniformConstant -%50 = OpTypePointer UniformConstant %23 -%49 = OpVariable %50 UniformConstant -%55 = OpTypeFunction %10 %4 %4 -%59 = OpConstant %4 1 -%70 = OpTypeFunction %10 %12 %4 -%77 = OpConstantComposite %12 %59 %59 -%86 = OpTypeFunction %10 %12 %6 %4 -%95 = OpConstantComposite %15 %59 %59 %59 -%104 = OpTypeFunction %10 %12 %4 %4 -%112 = OpConstantComposite %15 %59 %59 %59 -%120 = OpTypeFunction %10 %15 %4 -%127 = OpConstantComposite %15 %59 %59 %59 -%141 = OpConstantComposite %12 %59 %59 -%149 = OpTypeFunction %8 %12 %4 -%156 = OpConstantComposite %12 %59 %59 -%166 = OpTypeFunction %8 %12 %6 %4 -%175 = OpConstantComposite %15 %59 %59 %59 -%185 = OpTypeFunction %8 %12 %4 %4 -%193 = OpConstantComposite %15 %59 %59 %59 -%208 = OpConstantComposite %12 %59 %59 -%217 = OpTypeFunction %2 %4 %10 -%227 = OpTypeFunction %2 %12 %10 -%231 = OpConstantComposite %12 %59 %59 -%239 = OpTypeFunction %2 %12 %6 %10 -%245 = OpConstantComposite %15 %59 %59 %59 -%253 = OpTypeFunction %2 %12 %4 %10 -%258 = OpConstantComposite %15 %59 %59 %59 -%265 = OpTypeFunction %2 %15 %10 -%269 = OpConstantComposite %15 %59 %59 %59 -%274 = OpTypePointer Output %10 -%273 = OpVariable %274 Output -%276 = OpTypeFunction %2 -%54 = OpFunction %10 None %55 -%52 = OpFunctionParameter %4 -%53 = OpFunctionParameter %4 -%51 = OpLabel -%56 = OpLoad %9 %27 -OpBranch %57 -%57 = OpLabel -%58 = OpImageQueryLevels %4 %56 -%60 = OpISub %4 %58 %59 -%61 = OpExtInst %4 %1 UMin %53 %60 -%62 = OpImageQuerySizeLod %4 %56 %61 -%63 = OpISub %4 %62 %59 -%64 = OpExtInst %4 %1 UMin %52 %63 -%65 = OpImageFetch %10 %56 %64 Lod %61 -OpReturnValue %65 +%25 = OpTypePointer UniformConstant %9 +%24 = OpVariable %25 UniformConstant +%27 = OpTypePointer UniformConstant %11 +%26 = OpVariable %27 UniformConstant +%29 = OpTypePointer UniformConstant %13 +%28 = OpVariable %29 UniformConstant +%31 = OpTypePointer UniformConstant %14 +%30 = OpVariable %31 UniformConstant +%33 = OpTypePointer UniformConstant %16 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer UniformConstant %17 +%34 = OpVariable %35 UniformConstant +%37 = OpTypePointer UniformConstant %18 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %19 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %20 +%40 = OpVariable %41 UniformConstant +%43 = OpTypePointer UniformConstant %21 +%42 = OpVariable %43 UniformConstant +%45 = OpTypePointer UniformConstant %22 +%44 = OpVariable %45 UniformConstant +%47 = OpTypePointer UniformConstant %23 +%46 = OpVariable %47 UniformConstant +%52 = OpTypeFunction %10 %4 %4 +%56 = OpConstant %4 1 +%67 = OpTypeFunction %10 %12 %4 +%74 = OpConstantComposite %12 %56 %56 +%83 = OpTypeFunction %10 %12 %6 %4 +%92 = OpConstantComposite %15 %56 %56 %56 +%101 = OpTypeFunction %10 %12 %4 %4 +%109 = OpConstantComposite %15 %56 %56 %56 +%117 = OpTypeFunction %10 %15 %4 +%124 = OpConstantComposite %15 %56 %56 %56 +%138 = OpConstantComposite %12 %56 %56 +%146 = OpTypeFunction %8 %12 %4 +%153 = OpConstantComposite %12 %56 %56 +%163 = OpTypeFunction %8 %12 %6 %4 +%172 = OpConstantComposite %15 %56 %56 %56 +%182 = OpTypeFunction %8 %12 %4 %4 +%190 = OpConstantComposite %15 %56 %56 %56 +%205 = OpConstantComposite %12 %56 %56 +%214 = OpTypeFunction %2 %4 %10 +%224 = OpTypeFunction %2 %12 %10 +%228 = OpConstantComposite %12 %56 %56 +%236 = OpTypeFunction %2 %12 %6 %10 +%242 = OpConstantComposite %15 %56 %56 %56 +%250 = OpTypeFunction %2 %12 %4 %10 +%255 = OpConstantComposite %15 %56 %56 %56 +%262 = OpTypeFunction %2 %15 %10 +%266 = OpConstantComposite %15 %56 %56 %56 +%271 = OpTypePointer Output %10 +%270 = OpVariable %271 Output +%273 = OpTypeFunction %2 +%283 = OpConstantNull %12 +%284 = OpConstantNull %12 +%285 = OpConstantNull %12 +%286 = OpConstantNull %15 +%287 = OpConstantNull %12 +%288 = OpConstantNull %10 +%289 = OpConstantNull %12 +%290 = OpConstantNull %10 +%291 = OpConstantNull %12 +%292 = OpConstantNull %10 +%293 = OpConstantNull %12 +%294 = OpConstantNull %10 +%295 = OpConstantNull %15 +%296 = OpConstantNull %10 +%51 = OpFunction %10 None %52 +%49 = OpFunctionParameter %4 +%50 = OpFunctionParameter %4 +%48 = OpLabel +%53 = OpLoad %9 %24 +OpBranch %54 +%54 = OpLabel +%55 = OpImageQueryLevels %4 %53 +%57 = OpISub %4 %55 %56 +%58 = OpExtInst %4 %1 UMin %50 %57 +%59 = OpImageQuerySizeLod %4 %53 %58 +%60 = OpISub %4 %59 %56 +%61 = OpExtInst %4 %1 UMin %49 %60 +%62 = OpImageFetch %10 %53 %61 Lod %58 +OpReturnValue %62 OpFunctionEnd -%69 = OpFunction %10 None %70 -%67 = OpFunctionParameter %12 -%68 = OpFunctionParameter %4 -%66 = OpLabel -%71 = OpLoad %11 %29 -OpBranch %72 -%72 = OpLabel -%73 = OpImageQueryLevels %4 %71 -%74 = OpISub %4 %73 %59 -%75 = OpExtInst %4 %1 UMin %68 %74 -%76 = OpImageQuerySizeLod %12 %71 %75 -%78 = OpISub %12 %76 %77 -%79 = OpExtInst %12 %1 UMin %67 %78 -%80 = OpImageFetch %10 %71 %79 Lod %75 -OpReturnValue %80 +%66 = OpFunction %10 None %67 +%64 = OpFunctionParameter %12 +%65 = OpFunctionParameter %4 +%63 = OpLabel +%68 = OpLoad %11 %26 +OpBranch %69 +%69 = OpLabel +%70 = OpImageQueryLevels %4 %68 +%71 = OpISub %4 %70 %56 +%72 = OpExtInst %4 %1 UMin %65 %71 +%73 = OpImageQuerySizeLod %12 %68 %72 +%75 = OpISub %12 %73 %74 +%76 = OpExtInst %12 %1 UMin %64 %75 +%77 = OpImageFetch %10 %68 %76 Lod %72 +OpReturnValue %77 OpFunctionEnd -%85 = OpFunction %10 None %86 -%82 = OpFunctionParameter %12 -%83 = OpFunctionParameter %6 -%84 = OpFunctionParameter %4 -%81 = OpLabel -%87 = OpLoad %13 %31 -OpBranch %88 -%88 = OpLabel -%89 = OpBitcast %4 %83 -%90 = OpCompositeConstruct %15 %82 %89 -%91 = OpImageQueryLevels %4 %87 -%92 = OpISub %4 %91 %59 -%93 = OpExtInst %4 %1 UMin %84 %92 -%94 = OpImageQuerySizeLod %15 %87 %93 -%96 = OpISub %15 %94 %95 -%97 = OpExtInst %15 %1 UMin %90 %96 -%98 = OpImageFetch %10 %87 %97 Lod %93 -OpReturnValue %98 +%82 = OpFunction %10 None %83 +%79 = OpFunctionParameter %12 +%80 = OpFunctionParameter %6 +%81 = OpFunctionParameter %4 +%78 = OpLabel +%84 = OpLoad %13 %28 +OpBranch %85 +%85 = OpLabel +%86 = OpBitcast %4 %80 +%87 = OpCompositeConstruct %15 %79 %86 +%88 = OpImageQueryLevels %4 %84 +%89 = OpISub %4 %88 %56 +%90 = OpExtInst %4 %1 UMin %81 %89 +%91 = OpImageQuerySizeLod %15 %84 %90 +%93 = OpISub %15 %91 %92 +%94 = OpExtInst %15 %1 UMin %87 %93 +%95 = OpImageFetch %10 %84 %94 Lod %90 +OpReturnValue %95 OpFunctionEnd -%103 = OpFunction %10 None %104 -%100 = OpFunctionParameter %12 -%101 = OpFunctionParameter %4 -%102 = OpFunctionParameter %4 -%99 = OpLabel -%105 = OpLoad %13 %31 -OpBranch %106 -%106 = OpLabel -%107 = OpCompositeConstruct %15 %100 %101 -%108 = OpImageQueryLevels %4 %105 -%109 = OpISub %4 %108 %59 -%110 = OpExtInst %4 %1 UMin %102 %109 -%111 = OpImageQuerySizeLod %15 %105 %110 -%113 = OpISub %15 %111 %112 -%114 = OpExtInst %15 %1 UMin %107 %113 -%115 = OpImageFetch %10 %105 %114 Lod %110 -OpReturnValue %115 +%100 = OpFunction %10 None %101 +%97 = OpFunctionParameter %12 +%98 = OpFunctionParameter %4 +%99 = OpFunctionParameter %4 +%96 = OpLabel +%102 = OpLoad %13 %28 +OpBranch %103 +%103 = OpLabel +%104 = OpCompositeConstruct %15 %97 %98 +%105 = OpImageQueryLevels %4 %102 +%106 = OpISub %4 %105 %56 +%107 = OpExtInst %4 %1 UMin %99 %106 +%108 = OpImageQuerySizeLod %15 %102 %107 +%110 = OpISub %15 %108 %109 +%111 = OpExtInst %15 %1 UMin %104 %110 +%112 = OpImageFetch %10 %102 %111 Lod %107 +OpReturnValue %112 OpFunctionEnd -%119 = OpFunction %10 None %120 -%117 = OpFunctionParameter %15 -%118 = OpFunctionParameter %4 -%116 = OpLabel -%121 = OpLoad %14 %33 -OpBranch %122 -%122 = OpLabel -%123 = OpImageQueryLevels %4 %121 -%124 = OpISub %4 %123 %59 -%125 = OpExtInst %4 %1 UMin %118 %124 -%126 = OpImageQuerySizeLod %15 %121 %125 -%128 = OpISub %15 %126 %127 -%129 = OpExtInst %15 %1 UMin %117 %128 -%130 = OpImageFetch %10 %121 %129 Lod %125 -OpReturnValue %130 +%116 = OpFunction %10 None %117 +%114 = OpFunctionParameter %15 +%115 = OpFunctionParameter %4 +%113 = OpLabel +%118 = OpLoad %14 %30 +OpBranch %119 +%119 = OpLabel +%120 = OpImageQueryLevels %4 %118 +%121 = OpISub %4 %120 %56 +%122 = OpExtInst %4 %1 UMin %115 %121 +%123 = OpImageQuerySizeLod %15 %118 %122 +%125 = OpISub %15 %123 %124 +%126 = OpExtInst %15 %1 UMin %114 %125 +%127 = OpImageFetch %10 %118 %126 Lod %122 +OpReturnValue %127 OpFunctionEnd -%134 = OpFunction %10 None %70 -%132 = OpFunctionParameter %12 -%133 = OpFunctionParameter %4 -%131 = OpLabel -%135 = OpLoad %16 %35 -OpBranch %136 -%136 = OpLabel -%137 = OpImageQuerySamples %4 %135 -%138 = OpISub %4 %137 %59 -%139 = OpExtInst %4 %1 UMin %133 %138 -%140 = OpImageQuerySize %12 %135 -%142 = OpISub %12 %140 %141 -%143 = OpExtInst %12 %1 UMin %132 %142 -%144 = OpImageFetch %10 %135 %143 Sample %139 -OpReturnValue %144 +%131 = OpFunction %10 None %67 +%129 = OpFunctionParameter %12 +%130 = OpFunctionParameter %4 +%128 = OpLabel +%132 = OpLoad %16 %32 +OpBranch %133 +%133 = OpLabel +%134 = OpImageQuerySamples %4 %132 +%135 = OpISub %4 %134 %56 +%136 = OpExtInst %4 %1 UMin %130 %135 +%137 = OpImageQuerySize %12 %132 +%139 = OpISub %12 %137 %138 +%140 = OpExtInst %12 %1 UMin %129 %139 +%141 = OpImageFetch %10 %132 %140 Sample %136 +OpReturnValue %141 OpFunctionEnd -%148 = OpFunction %8 None %149 -%146 = OpFunctionParameter %12 -%147 = OpFunctionParameter %4 -%145 = OpLabel -%150 = OpLoad %17 %37 -OpBranch %151 -%151 = OpLabel -%152 = OpImageQueryLevels %4 %150 -%153 = OpISub %4 %152 %59 -%154 = OpExtInst %4 %1 UMin %147 %153 -%155 = OpImageQuerySizeLod %12 %150 %154 -%157 = OpISub %12 %155 %156 -%158 = OpExtInst %12 %1 UMin %146 %157 -%159 = OpImageFetch %10 %150 %158 Lod %154 -%160 = OpCompositeExtract %8 %159 0 -OpReturnValue %160 +%145 = OpFunction %8 None %146 +%143 = OpFunctionParameter %12 +%144 = OpFunctionParameter %4 +%142 = OpLabel +%147 = OpLoad %17 %34 +OpBranch %148 +%148 = OpLabel +%149 = OpImageQueryLevels %4 %147 +%150 = OpISub %4 %149 %56 +%151 = OpExtInst %4 %1 UMin %144 %150 +%152 = OpImageQuerySizeLod %12 %147 %151 +%154 = OpISub %12 %152 %153 +%155 = OpExtInst %12 %1 UMin %143 %154 +%156 = OpImageFetch %10 %147 %155 Lod %151 +%157 = OpCompositeExtract %8 %156 0 +OpReturnValue %157 OpFunctionEnd -%165 = OpFunction %8 None %166 -%162 = OpFunctionParameter %12 -%163 = OpFunctionParameter %6 -%164 = OpFunctionParameter %4 -%161 = OpLabel -%167 = OpLoad %18 %39 -OpBranch %168 -%168 = OpLabel -%169 = OpBitcast %4 %163 -%170 = OpCompositeConstruct %15 %162 %169 -%171 = OpImageQueryLevels %4 %167 -%172 = OpISub %4 %171 %59 -%173 = OpExtInst %4 %1 UMin %164 %172 -%174 = OpImageQuerySizeLod %15 %167 %173 -%176 = OpISub %15 %174 %175 -%177 = OpExtInst %15 %1 UMin %170 %176 -%178 = OpImageFetch %10 %167 %177 Lod %173 -%179 = OpCompositeExtract %8 %178 0 -OpReturnValue %179 +%162 = OpFunction %8 None %163 +%159 = OpFunctionParameter %12 +%160 = OpFunctionParameter %6 +%161 = OpFunctionParameter %4 +%158 = OpLabel +%164 = OpLoad %18 %36 +OpBranch %165 +%165 = OpLabel +%166 = OpBitcast %4 %160 +%167 = OpCompositeConstruct %15 %159 %166 +%168 = OpImageQueryLevels %4 %164 +%169 = OpISub %4 %168 %56 +%170 = OpExtInst %4 %1 UMin %161 %169 +%171 = OpImageQuerySizeLod %15 %164 %170 +%173 = OpISub %15 %171 %172 +%174 = OpExtInst %15 %1 UMin %167 %173 +%175 = OpImageFetch %10 %164 %174 Lod %170 +%176 = OpCompositeExtract %8 %175 0 +OpReturnValue %176 OpFunctionEnd -%184 = OpFunction %8 None %185 -%181 = OpFunctionParameter %12 -%182 = OpFunctionParameter %4 -%183 = OpFunctionParameter %4 -%180 = OpLabel -%186 = OpLoad %18 %39 -OpBranch %187 -%187 = OpLabel -%188 = OpCompositeConstruct %15 %181 %182 -%189 = OpImageQueryLevels %4 %186 -%190 = OpISub %4 %189 %59 -%191 = OpExtInst %4 %1 UMin %183 %190 -%192 = OpImageQuerySizeLod %15 %186 %191 -%194 = OpISub %15 %192 %193 -%195 = OpExtInst %15 %1 UMin %188 %194 -%196 = OpImageFetch %10 %186 %195 Lod %191 -%197 = OpCompositeExtract %8 %196 0 -OpReturnValue %197 +%181 = OpFunction %8 None %182 +%178 = OpFunctionParameter %12 +%179 = OpFunctionParameter %4 +%180 = OpFunctionParameter %4 +%177 = OpLabel +%183 = OpLoad %18 %36 +OpBranch %184 +%184 = OpLabel +%185 = OpCompositeConstruct %15 %178 %179 +%186 = OpImageQueryLevels %4 %183 +%187 = OpISub %4 %186 %56 +%188 = OpExtInst %4 %1 UMin %180 %187 +%189 = OpImageQuerySizeLod %15 %183 %188 +%191 = OpISub %15 %189 %190 +%192 = OpExtInst %15 %1 UMin %185 %191 +%193 = OpImageFetch %10 %183 %192 Lod %188 +%194 = OpCompositeExtract %8 %193 0 +OpReturnValue %194 OpFunctionEnd -%201 = OpFunction %8 None %149 -%199 = OpFunctionParameter %12 -%200 = OpFunctionParameter %4 -%198 = OpLabel -%202 = OpLoad %19 %41 -OpBranch %203 -%203 = OpLabel -%204 = OpImageQuerySamples %4 %202 -%205 = OpISub %4 %204 %59 -%206 = OpExtInst %4 %1 UMin %200 %205 -%207 = OpImageQuerySize %12 %202 -%209 = OpISub %12 %207 %208 -%210 = OpExtInst %12 %1 UMin %199 %209 -%211 = OpImageFetch %10 %202 %210 Sample %206 -%212 = OpCompositeExtract %8 %211 0 -OpReturnValue %212 +%198 = OpFunction %8 None %146 +%196 = OpFunctionParameter %12 +%197 = OpFunctionParameter %4 +%195 = OpLabel +%199 = OpLoad %19 %38 +OpBranch %200 +%200 = OpLabel +%201 = OpImageQuerySamples %4 %199 +%202 = OpISub %4 %201 %56 +%203 = OpExtInst %4 %1 UMin %197 %202 +%204 = OpImageQuerySize %12 %199 +%206 = OpISub %12 %204 %205 +%207 = OpExtInst %12 %1 UMin %196 %206 +%208 = OpImageFetch %10 %199 %207 Sample %203 +%209 = OpCompositeExtract %8 %208 0 +OpReturnValue %209 OpFunctionEnd -%216 = OpFunction %2 None %217 -%214 = OpFunctionParameter %4 -%215 = OpFunctionParameter %10 -%213 = OpLabel -%218 = OpLoad %20 %43 -OpBranch %219 -%219 = OpLabel -%220 = OpImageQuerySize %4 %218 -%221 = OpISub %4 %220 %59 -%222 = OpExtInst %4 %1 UMin %214 %221 -OpImageWrite %218 %222 %215 +%213 = OpFunction %2 None %214 +%211 = OpFunctionParameter %4 +%212 = OpFunctionParameter %10 +%210 = OpLabel +%215 = OpLoad %20 %40 +OpBranch %216 +%216 = OpLabel +%217 = OpImageQuerySize %4 %215 +%218 = OpISub %4 %217 %56 +%219 = OpExtInst %4 %1 UMin %211 %218 +OpImageWrite %215 %219 %212 OpReturn OpFunctionEnd -%226 = OpFunction %2 None %227 -%224 = OpFunctionParameter %12 -%225 = OpFunctionParameter %10 -%223 = OpLabel -%228 = OpLoad %21 %45 -OpBranch %229 -%229 = OpLabel -%230 = OpImageQuerySize %12 %228 -%232 = OpISub %12 %230 %231 -%233 = OpExtInst %12 %1 UMin %224 %232 -OpImageWrite %228 %233 %225 +%223 = OpFunction %2 None %224 +%221 = OpFunctionParameter %12 +%222 = OpFunctionParameter %10 +%220 = OpLabel +%225 = OpLoad %21 %42 +OpBranch %226 +%226 = OpLabel +%227 = OpImageQuerySize %12 %225 +%229 = OpISub %12 %227 %228 +%230 = OpExtInst %12 %1 UMin %221 %229 +OpImageWrite %225 %230 %222 OpReturn OpFunctionEnd -%238 = OpFunction %2 None %239 -%235 = OpFunctionParameter %12 -%236 = OpFunctionParameter %6 -%237 = OpFunctionParameter %10 -%234 = OpLabel -%240 = OpLoad %22 %47 -OpBranch %241 -%241 = OpLabel -%242 = OpBitcast %4 %236 -%243 = OpCompositeConstruct %15 %235 %242 -%244 = OpImageQuerySize %15 %240 -%246 = OpISub %15 %244 %245 -%247 = OpExtInst %15 %1 UMin %243 %246 -OpImageWrite %240 %247 %237 +%235 = OpFunction %2 None %236 +%232 = OpFunctionParameter %12 +%233 = OpFunctionParameter %6 +%234 = OpFunctionParameter %10 +%231 = OpLabel +%237 = OpLoad %22 %44 +OpBranch %238 +%238 = OpLabel +%239 = OpBitcast %4 %233 +%240 = OpCompositeConstruct %15 %232 %239 +%241 = OpImageQuerySize %15 %237 +%243 = OpISub %15 %241 %242 +%244 = OpExtInst %15 %1 UMin %240 %243 +OpImageWrite %237 %244 %234 OpReturn OpFunctionEnd -%252 = OpFunction %2 None %253 -%249 = OpFunctionParameter %12 -%250 = OpFunctionParameter %4 -%251 = OpFunctionParameter %10 -%248 = OpLabel -%254 = OpLoad %22 %47 -OpBranch %255 -%255 = OpLabel -%256 = OpCompositeConstruct %15 %249 %250 -%257 = OpImageQuerySize %15 %254 -%259 = OpISub %15 %257 %258 -%260 = OpExtInst %15 %1 UMin %256 %259 -OpImageWrite %254 %260 %251 +%249 = OpFunction %2 None %250 +%246 = OpFunctionParameter %12 +%247 = OpFunctionParameter %4 +%248 = OpFunctionParameter %10 +%245 = OpLabel +%251 = OpLoad %22 %44 +OpBranch %252 +%252 = OpLabel +%253 = OpCompositeConstruct %15 %246 %247 +%254 = OpImageQuerySize %15 %251 +%256 = OpISub %15 %254 %255 +%257 = OpExtInst %15 %1 UMin %253 %256 +OpImageWrite %251 %257 %248 OpReturn OpFunctionEnd -%264 = OpFunction %2 None %265 -%262 = OpFunctionParameter %15 -%263 = OpFunctionParameter %10 -%261 = OpLabel -%266 = OpLoad %23 %49 -OpBranch %267 -%267 = OpLabel -%268 = OpImageQuerySize %15 %266 -%270 = OpISub %15 %268 %269 -%271 = OpExtInst %15 %1 UMin %262 %270 -OpImageWrite %266 %271 %263 +%261 = OpFunction %2 None %262 +%259 = OpFunctionParameter %15 +%260 = OpFunctionParameter %10 +%258 = OpLabel +%263 = OpLoad %23 %46 +OpBranch %264 +%264 = OpLabel +%265 = OpImageQuerySize %15 %263 +%267 = OpISub %15 %265 %266 +%268 = OpExtInst %15 %1 UMin %259 %267 +OpImageWrite %263 %268 %260 OpReturn OpFunctionEnd -%275 = OpFunction %2 None %276 -%272 = OpLabel -%277 = OpLoad %9 %27 -%278 = OpLoad %11 %29 -%279 = OpLoad %13 %31 -%280 = OpLoad %14 %33 -%281 = OpLoad %16 %35 -%282 = OpLoad %20 %43 -%283 = OpLoad %21 %45 -%284 = OpLoad %22 %47 -%285 = OpLoad %23 %49 -OpBranch %286 -%286 = OpLabel -%287 = OpFunctionCall %10 %54 %3 %3 -%288 = OpFunctionCall %10 %69 %24 %3 -%289 = OpFunctionCall %10 %85 %24 %5 %3 -%290 = OpFunctionCall %10 %103 %24 %3 %3 -%291 = OpFunctionCall %10 %119 %25 %3 -%292 = OpFunctionCall %10 %134 %24 %3 -%293 = OpFunctionCall %2 %216 %3 %26 -%294 = OpFunctionCall %2 %226 %24 %26 -%295 = OpFunctionCall %2 %238 %24 %5 %26 -%296 = OpFunctionCall %2 %252 %24 %3 %26 -%297 = OpFunctionCall %2 %264 %25 %26 -%298 = OpCompositeConstruct %10 %7 %7 %7 %7 -OpStore %273 %298 +%272 = OpFunction %2 None %273 +%269 = OpLabel +%274 = OpLoad %9 %24 +%275 = OpLoad %11 %26 +%276 = OpLoad %13 %28 +%277 = OpLoad %14 %30 +%278 = OpLoad %16 %32 +%279 = OpLoad %20 %40 +%280 = OpLoad %21 %42 +%281 = OpLoad %22 %44 +%282 = OpLoad %23 %46 +OpBranch %297 +%297 = OpLabel +%298 = OpFunctionCall %10 %51 %3 %3 +%299 = OpFunctionCall %10 %66 %283 %3 +%300 = OpFunctionCall %10 %82 %284 %5 %3 +%301 = OpFunctionCall %10 %100 %285 %3 %3 +%302 = OpFunctionCall %10 %116 %286 %3 +%303 = OpFunctionCall %10 %131 %287 %3 +%304 = OpFunctionCall %2 %213 %3 %288 +%305 = OpFunctionCall %2 %223 %289 %290 +%306 = OpFunctionCall %2 %235 %291 %5 %292 +%307 = OpFunctionCall %2 %249 %293 %3 %294 +%308 = OpFunctionCall %2 %261 %295 %296 +%309 = OpCompositeConstruct %10 %7 %7 %7 %7 +OpStore %270 %309 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index ce64a3dfc..29a132a22 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -1,109 +1,109 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 336 +; Bound: 347 OpCapability ImageQuery OpCapability Image1D OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %312 "fragment_shader" %310 -OpExecutionMode %312 OriginUpperLeft +OpEntryPoint Fragment %309 "fragment_shader" %307 +OpExecutionMode %309 OriginUpperLeft OpSource GLSL 450 -OpName %27 "image_1d" -OpName %29 "image_2d" -OpName %31 "image_2d_array" -OpName %33 "image_3d" -OpName %35 "image_multisampled_2d" -OpName %37 "image_depth_2d" -OpName %39 "image_depth_2d_array" -OpName %41 "image_depth_multisampled_2d" -OpName %43 "image_storage_1d" -OpName %45 "image_storage_2d" -OpName %47 "image_storage_2d_array" -OpName %49 "image_storage_3d" -OpName %52 "coords" -OpName %53 "level" -OpName %54 "test_textureLoad_1d" -OpName %70 "coords" -OpName %71 "level" -OpName %72 "test_textureLoad_2d" -OpName %89 "coords" -OpName %90 "index" -OpName %91 "level" -OpName %92 "test_textureLoad_2d_array_u" -OpName %111 "coords" -OpName %112 "index" -OpName %113 "level" -OpName %114 "test_textureLoad_2d_array_s" -OpName %131 "coords" -OpName %132 "level" -OpName %133 "test_textureLoad_3d" -OpName %149 "coords" -OpName %150 "_sample" -OpName %151 "test_textureLoad_multisampled_2d" -OpName %166 "coords" -OpName %167 "level" -OpName %168 "test_textureLoad_depth_2d" -OpName %185 "coords" -OpName %186 "index" -OpName %187 "level" -OpName %188 "test_textureLoad_depth_2d_array_u" -OpName %207 "coords" -OpName %208 "index" -OpName %209 "level" -OpName %210 "test_textureLoad_depth_2d_array_s" -OpName %228 "coords" -OpName %229 "_sample" -OpName %230 "test_textureLoad_depth_multisampled_2d" -OpName %246 "coords" -OpName %247 "value" -OpName %248 "test_textureStore_1d" -OpName %257 "coords" -OpName %258 "value" -OpName %259 "test_textureStore_2d" -OpName %269 "coords" -OpName %270 "array_index" -OpName %271 "value" -OpName %272 "test_textureStore_2d_array_u" -OpName %284 "coords" -OpName %285 "array_index" -OpName %286 "value" -OpName %287 "test_textureStore_2d_array_s" -OpName %298 "coords" -OpName %299 "value" -OpName %300 "test_textureStore_3d" -OpName %312 "fragment_shader" -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 0 -OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 1 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 2 -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 3 -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 4 -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 5 -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 6 -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 7 -OpDecorate %43 NonReadable -OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 8 -OpDecorate %45 NonReadable -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 9 -OpDecorate %47 NonReadable -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 10 -OpDecorate %49 NonReadable -OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 11 -OpDecorate %310 Location 0 +OpName %24 "image_1d" +OpName %26 "image_2d" +OpName %28 "image_2d_array" +OpName %30 "image_3d" +OpName %32 "image_multisampled_2d" +OpName %34 "image_depth_2d" +OpName %36 "image_depth_2d_array" +OpName %38 "image_depth_multisampled_2d" +OpName %40 "image_storage_1d" +OpName %42 "image_storage_2d" +OpName %44 "image_storage_2d_array" +OpName %46 "image_storage_3d" +OpName %49 "coords" +OpName %50 "level" +OpName %51 "test_textureLoad_1d" +OpName %67 "coords" +OpName %68 "level" +OpName %69 "test_textureLoad_2d" +OpName %86 "coords" +OpName %87 "index" +OpName %88 "level" +OpName %89 "test_textureLoad_2d_array_u" +OpName %108 "coords" +OpName %109 "index" +OpName %110 "level" +OpName %111 "test_textureLoad_2d_array_s" +OpName %128 "coords" +OpName %129 "level" +OpName %130 "test_textureLoad_3d" +OpName %146 "coords" +OpName %147 "_sample" +OpName %148 "test_textureLoad_multisampled_2d" +OpName %163 "coords" +OpName %164 "level" +OpName %165 "test_textureLoad_depth_2d" +OpName %182 "coords" +OpName %183 "index" +OpName %184 "level" +OpName %185 "test_textureLoad_depth_2d_array_u" +OpName %204 "coords" +OpName %205 "index" +OpName %206 "level" +OpName %207 "test_textureLoad_depth_2d_array_s" +OpName %225 "coords" +OpName %226 "_sample" +OpName %227 "test_textureLoad_depth_multisampled_2d" +OpName %243 "coords" +OpName %244 "value" +OpName %245 "test_textureStore_1d" +OpName %254 "coords" +OpName %255 "value" +OpName %256 "test_textureStore_2d" +OpName %266 "coords" +OpName %267 "array_index" +OpName %268 "value" +OpName %269 "test_textureStore_2d_array_u" +OpName %281 "coords" +OpName %282 "array_index" +OpName %283 "value" +OpName %284 "test_textureStore_2d_array_s" +OpName %295 "coords" +OpName %296 "value" +OpName %297 "test_textureStore_3d" +OpName %309 "fragment_shader" +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 0 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 1 +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 2 +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 3 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 4 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 5 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 6 +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 7 +OpDecorate %40 NonReadable +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 8 +OpDecorate %42 NonReadable +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 9 +OpDecorate %44 NonReadable +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 10 +OpDecorate %46 NonReadable +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 11 +OpDecorate %307 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 0 @@ -126,424 +126,435 @@ OpDecorate %310 Location 0 %21 = OpTypeImage %8 2D 0 0 0 2 Rgba8 %22 = OpTypeImage %8 2D 0 1 0 2 Rgba8 %23 = OpTypeImage %8 3D 0 0 0 2 Rgba8 -%24 = OpConstantComposite %12 %3 %3 -%25 = OpConstantComposite %15 %3 %3 %3 -%26 = OpConstantComposite %10 %7 %7 %7 %7 -%28 = OpTypePointer UniformConstant %9 -%27 = OpVariable %28 UniformConstant -%30 = OpTypePointer UniformConstant %11 -%29 = OpVariable %30 UniformConstant -%32 = OpTypePointer UniformConstant %13 -%31 = OpVariable %32 UniformConstant -%34 = OpTypePointer UniformConstant %14 -%33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %16 -%35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %17 -%37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %18 -%39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %19 -%41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %20 -%43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %21 -%45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %22 -%47 = OpVariable %48 UniformConstant -%50 = OpTypePointer UniformConstant %23 -%49 = OpVariable %50 UniformConstant -%55 = OpTypeFunction %10 %4 %4 -%58 = OpTypeBool -%59 = OpConstantNull %10 -%73 = OpTypeFunction %10 %12 %4 -%76 = OpConstantNull %10 -%82 = OpTypeVector %58 2 -%93 = OpTypeFunction %10 %12 %6 %4 -%98 = OpConstantNull %10 -%104 = OpTypeVector %58 3 -%115 = OpTypeFunction %10 %12 %4 %4 -%119 = OpConstantNull %10 -%134 = OpTypeFunction %10 %15 %4 -%137 = OpConstantNull %10 -%154 = OpConstantNull %10 -%169 = OpTypeFunction %8 %12 %4 -%172 = OpConstantNull %10 -%189 = OpTypeFunction %8 %12 %6 %4 -%194 = OpConstantNull %10 -%211 = OpTypeFunction %8 %12 %4 %4 -%215 = OpConstantNull %10 -%233 = OpConstantNull %10 -%249 = OpTypeFunction %2 %4 %10 -%260 = OpTypeFunction %2 %12 %10 -%273 = OpTypeFunction %2 %12 %6 %10 -%288 = OpTypeFunction %2 %12 %4 %10 -%301 = OpTypeFunction %2 %15 %10 -%311 = OpTypePointer Output %10 -%310 = OpVariable %311 Output -%313 = OpTypeFunction %2 -%54 = OpFunction %10 None %55 -%52 = OpFunctionParameter %4 -%53 = OpFunctionParameter %4 -%51 = OpLabel -%56 = OpLoad %9 %27 -OpBranch %57 -%57 = OpLabel -%60 = OpImageQueryLevels %4 %56 -%61 = OpULessThan %58 %53 %60 -OpSelectionMerge %62 None -OpBranchConditional %61 %63 %62 +%25 = OpTypePointer UniformConstant %9 +%24 = OpVariable %25 UniformConstant +%27 = OpTypePointer UniformConstant %11 +%26 = OpVariable %27 UniformConstant +%29 = OpTypePointer UniformConstant %13 +%28 = OpVariable %29 UniformConstant +%31 = OpTypePointer UniformConstant %14 +%30 = OpVariable %31 UniformConstant +%33 = OpTypePointer UniformConstant %16 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer UniformConstant %17 +%34 = OpVariable %35 UniformConstant +%37 = OpTypePointer UniformConstant %18 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %19 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %20 +%40 = OpVariable %41 UniformConstant +%43 = OpTypePointer UniformConstant %21 +%42 = OpVariable %43 UniformConstant +%45 = OpTypePointer UniformConstant %22 +%44 = OpVariable %45 UniformConstant +%47 = OpTypePointer UniformConstant %23 +%46 = OpVariable %47 UniformConstant +%52 = OpTypeFunction %10 %4 %4 +%55 = OpTypeBool +%56 = OpConstantNull %10 +%70 = OpTypeFunction %10 %12 %4 +%73 = OpConstantNull %10 +%79 = OpTypeVector %55 2 +%90 = OpTypeFunction %10 %12 %6 %4 +%95 = OpConstantNull %10 +%101 = OpTypeVector %55 3 +%112 = OpTypeFunction %10 %12 %4 %4 +%116 = OpConstantNull %10 +%131 = OpTypeFunction %10 %15 %4 +%134 = OpConstantNull %10 +%151 = OpConstantNull %10 +%166 = OpTypeFunction %8 %12 %4 +%169 = OpConstantNull %10 +%186 = OpTypeFunction %8 %12 %6 %4 +%191 = OpConstantNull %10 +%208 = OpTypeFunction %8 %12 %4 %4 +%212 = OpConstantNull %10 +%230 = OpConstantNull %10 +%246 = OpTypeFunction %2 %4 %10 +%257 = OpTypeFunction %2 %12 %10 +%270 = OpTypeFunction %2 %12 %6 %10 +%285 = OpTypeFunction %2 %12 %4 %10 +%298 = OpTypeFunction %2 %15 %10 +%308 = OpTypePointer Output %10 +%307 = OpVariable %308 Output +%310 = OpTypeFunction %2 +%320 = OpConstantNull %12 +%321 = OpConstantNull %12 +%322 = OpConstantNull %12 +%323 = OpConstantNull %15 +%324 = OpConstantNull %12 +%325 = OpConstantNull %10 +%326 = OpConstantNull %12 +%327 = OpConstantNull %10 +%328 = OpConstantNull %12 +%329 = OpConstantNull %10 +%330 = OpConstantNull %12 +%331 = OpConstantNull %10 +%332 = OpConstantNull %15 +%333 = OpConstantNull %10 +%51 = OpFunction %10 None %52 +%49 = OpFunctionParameter %4 +%50 = OpFunctionParameter %4 +%48 = OpLabel +%53 = OpLoad %9 %24 +OpBranch %54 +%54 = OpLabel +%57 = OpImageQueryLevels %4 %53 +%58 = OpULessThan %55 %50 %57 +OpSelectionMerge %59 None +OpBranchConditional %58 %60 %59 +%60 = OpLabel +%61 = OpImageQuerySizeLod %4 %53 %50 +%62 = OpULessThan %55 %49 %61 +OpBranchConditional %62 %63 %59 %63 = OpLabel -%64 = OpImageQuerySizeLod %4 %56 %53 -%65 = OpULessThan %58 %52 %64 -OpBranchConditional %65 %66 %62 +%64 = OpImageFetch %10 %53 %49 Lod %50 +OpBranch %59 +%59 = OpLabel +%65 = OpPhi %10 %56 %54 %56 %60 %64 %63 +OpReturnValue %65 +OpFunctionEnd +%69 = OpFunction %10 None %70 +%67 = OpFunctionParameter %12 +%68 = OpFunctionParameter %4 %66 = OpLabel -%67 = OpImageFetch %10 %56 %52 Lod %53 -OpBranch %62 -%62 = OpLabel -%68 = OpPhi %10 %59 %57 %59 %63 %67 %66 -OpReturnValue %68 +%71 = OpLoad %11 %26 +OpBranch %72 +%72 = OpLabel +%74 = OpImageQueryLevels %4 %71 +%75 = OpULessThan %55 %68 %74 +OpSelectionMerge %76 None +OpBranchConditional %75 %77 %76 +%77 = OpLabel +%78 = OpImageQuerySizeLod %12 %71 %68 +%80 = OpULessThan %79 %67 %78 +%81 = OpAll %55 %80 +OpBranchConditional %81 %82 %76 +%82 = OpLabel +%83 = OpImageFetch %10 %71 %67 Lod %68 +OpBranch %76 +%76 = OpLabel +%84 = OpPhi %10 %73 %72 %73 %77 %83 %82 +OpReturnValue %84 OpFunctionEnd -%72 = OpFunction %10 None %73 -%70 = OpFunctionParameter %12 -%71 = OpFunctionParameter %4 -%69 = OpLabel -%74 = OpLoad %11 %29 -OpBranch %75 -%75 = OpLabel -%77 = OpImageQueryLevels %4 %74 -%78 = OpULessThan %58 %71 %77 -OpSelectionMerge %79 None -OpBranchConditional %78 %80 %79 -%80 = OpLabel -%81 = OpImageQuerySizeLod %12 %74 %71 -%83 = OpULessThan %82 %70 %81 -%84 = OpAll %58 %83 -OpBranchConditional %84 %85 %79 +%89 = OpFunction %10 None %90 +%86 = OpFunctionParameter %12 +%87 = OpFunctionParameter %6 +%88 = OpFunctionParameter %4 %85 = OpLabel -%86 = OpImageFetch %10 %74 %70 Lod %71 -OpBranch %79 -%79 = OpLabel -%87 = OpPhi %10 %76 %75 %76 %80 %86 %85 -OpReturnValue %87 +%91 = OpLoad %13 %28 +OpBranch %92 +%92 = OpLabel +%93 = OpBitcast %4 %87 +%94 = OpCompositeConstruct %15 %86 %93 +%96 = OpImageQueryLevels %4 %91 +%97 = OpULessThan %55 %88 %96 +OpSelectionMerge %98 None +OpBranchConditional %97 %99 %98 +%99 = OpLabel +%100 = OpImageQuerySizeLod %15 %91 %88 +%102 = OpULessThan %101 %94 %100 +%103 = OpAll %55 %102 +OpBranchConditional %103 %104 %98 +%104 = OpLabel +%105 = OpImageFetch %10 %91 %94 Lod %88 +OpBranch %98 +%98 = OpLabel +%106 = OpPhi %10 %95 %92 %95 %99 %105 %104 +OpReturnValue %106 OpFunctionEnd -%92 = OpFunction %10 None %93 -%89 = OpFunctionParameter %12 -%90 = OpFunctionParameter %6 -%91 = OpFunctionParameter %4 -%88 = OpLabel -%94 = OpLoad %13 %31 -OpBranch %95 -%95 = OpLabel -%96 = OpBitcast %4 %90 -%97 = OpCompositeConstruct %15 %89 %96 -%99 = OpImageQueryLevels %4 %94 -%100 = OpULessThan %58 %91 %99 -OpSelectionMerge %101 None -OpBranchConditional %100 %102 %101 -%102 = OpLabel -%103 = OpImageQuerySizeLod %15 %94 %91 -%105 = OpULessThan %104 %97 %103 -%106 = OpAll %58 %105 -OpBranchConditional %106 %107 %101 +%111 = OpFunction %10 None %112 +%108 = OpFunctionParameter %12 +%109 = OpFunctionParameter %4 +%110 = OpFunctionParameter %4 %107 = OpLabel -%108 = OpImageFetch %10 %94 %97 Lod %91 -OpBranch %101 -%101 = OpLabel -%109 = OpPhi %10 %98 %95 %98 %102 %108 %107 -OpReturnValue %109 +%113 = OpLoad %13 %28 +OpBranch %114 +%114 = OpLabel +%115 = OpCompositeConstruct %15 %108 %109 +%117 = OpImageQueryLevels %4 %113 +%118 = OpULessThan %55 %110 %117 +OpSelectionMerge %119 None +OpBranchConditional %118 %120 %119 +%120 = OpLabel +%121 = OpImageQuerySizeLod %15 %113 %110 +%122 = OpULessThan %101 %115 %121 +%123 = OpAll %55 %122 +OpBranchConditional %123 %124 %119 +%124 = OpLabel +%125 = OpImageFetch %10 %113 %115 Lod %110 +OpBranch %119 +%119 = OpLabel +%126 = OpPhi %10 %116 %114 %116 %120 %125 %124 +OpReturnValue %126 OpFunctionEnd -%114 = OpFunction %10 None %115 -%111 = OpFunctionParameter %12 -%112 = OpFunctionParameter %4 -%113 = OpFunctionParameter %4 -%110 = OpLabel -%116 = OpLoad %13 %31 -OpBranch %117 -%117 = OpLabel -%118 = OpCompositeConstruct %15 %111 %112 -%120 = OpImageQueryLevels %4 %116 -%121 = OpULessThan %58 %113 %120 -OpSelectionMerge %122 None -OpBranchConditional %121 %123 %122 -%123 = OpLabel -%124 = OpImageQuerySizeLod %15 %116 %113 -%125 = OpULessThan %104 %118 %124 -%126 = OpAll %58 %125 -OpBranchConditional %126 %127 %122 +%130 = OpFunction %10 None %131 +%128 = OpFunctionParameter %15 +%129 = OpFunctionParameter %4 %127 = OpLabel -%128 = OpImageFetch %10 %116 %118 Lod %113 -OpBranch %122 -%122 = OpLabel -%129 = OpPhi %10 %119 %117 %119 %123 %128 %127 -OpReturnValue %129 +%132 = OpLoad %14 %30 +OpBranch %133 +%133 = OpLabel +%135 = OpImageQueryLevels %4 %132 +%136 = OpULessThan %55 %129 %135 +OpSelectionMerge %137 None +OpBranchConditional %136 %138 %137 +%138 = OpLabel +%139 = OpImageQuerySizeLod %15 %132 %129 +%140 = OpULessThan %101 %128 %139 +%141 = OpAll %55 %140 +OpBranchConditional %141 %142 %137 +%142 = OpLabel +%143 = OpImageFetch %10 %132 %128 Lod %129 +OpBranch %137 +%137 = OpLabel +%144 = OpPhi %10 %134 %133 %134 %138 %143 %142 +OpReturnValue %144 OpFunctionEnd -%133 = OpFunction %10 None %134 -%131 = OpFunctionParameter %15 -%132 = OpFunctionParameter %4 -%130 = OpLabel -%135 = OpLoad %14 %33 -OpBranch %136 -%136 = OpLabel -%138 = OpImageQueryLevels %4 %135 -%139 = OpULessThan %58 %132 %138 -OpSelectionMerge %140 None -OpBranchConditional %139 %141 %140 -%141 = OpLabel -%142 = OpImageQuerySizeLod %15 %135 %132 -%143 = OpULessThan %104 %131 %142 -%144 = OpAll %58 %143 -OpBranchConditional %144 %145 %140 +%148 = OpFunction %10 None %70 +%146 = OpFunctionParameter %12 +%147 = OpFunctionParameter %4 %145 = OpLabel -%146 = OpImageFetch %10 %135 %131 Lod %132 -OpBranch %140 -%140 = OpLabel -%147 = OpPhi %10 %137 %136 %137 %141 %146 %145 -OpReturnValue %147 +%149 = OpLoad %16 %32 +OpBranch %150 +%150 = OpLabel +%152 = OpImageQuerySamples %4 %149 +%153 = OpULessThan %55 %147 %152 +OpSelectionMerge %154 None +OpBranchConditional %153 %155 %154 +%155 = OpLabel +%156 = OpImageQuerySize %12 %149 +%157 = OpULessThan %79 %146 %156 +%158 = OpAll %55 %157 +OpBranchConditional %158 %159 %154 +%159 = OpLabel +%160 = OpImageFetch %10 %149 %146 Sample %147 +OpBranch %154 +%154 = OpLabel +%161 = OpPhi %10 %151 %150 %151 %155 %160 %159 +OpReturnValue %161 OpFunctionEnd -%151 = OpFunction %10 None %73 -%149 = OpFunctionParameter %12 -%150 = OpFunctionParameter %4 -%148 = OpLabel -%152 = OpLoad %16 %35 -OpBranch %153 -%153 = OpLabel -%155 = OpImageQuerySamples %4 %152 -%156 = OpULessThan %58 %150 %155 -OpSelectionMerge %157 None -OpBranchConditional %156 %158 %157 -%158 = OpLabel -%159 = OpImageQuerySize %12 %152 -%160 = OpULessThan %82 %149 %159 -%161 = OpAll %58 %160 -OpBranchConditional %161 %162 %157 +%165 = OpFunction %8 None %166 +%163 = OpFunctionParameter %12 +%164 = OpFunctionParameter %4 %162 = OpLabel -%163 = OpImageFetch %10 %152 %149 Sample %150 -OpBranch %157 -%157 = OpLabel -%164 = OpPhi %10 %154 %153 %154 %158 %163 %162 -OpReturnValue %164 +%167 = OpLoad %17 %34 +OpBranch %168 +%168 = OpLabel +%170 = OpImageQueryLevels %4 %167 +%171 = OpULessThan %55 %164 %170 +OpSelectionMerge %172 None +OpBranchConditional %171 %173 %172 +%173 = OpLabel +%174 = OpImageQuerySizeLod %12 %167 %164 +%175 = OpULessThan %79 %163 %174 +%176 = OpAll %55 %175 +OpBranchConditional %176 %177 %172 +%177 = OpLabel +%178 = OpImageFetch %10 %167 %163 Lod %164 +OpBranch %172 +%172 = OpLabel +%179 = OpPhi %10 %169 %168 %169 %173 %178 %177 +%180 = OpCompositeExtract %8 %179 0 +OpReturnValue %180 OpFunctionEnd -%168 = OpFunction %8 None %169 -%166 = OpFunctionParameter %12 -%167 = OpFunctionParameter %4 -%165 = OpLabel -%170 = OpLoad %17 %37 -OpBranch %171 -%171 = OpLabel -%173 = OpImageQueryLevels %4 %170 -%174 = OpULessThan %58 %167 %173 -OpSelectionMerge %175 None -OpBranchConditional %174 %176 %175 -%176 = OpLabel -%177 = OpImageQuerySizeLod %12 %170 %167 -%178 = OpULessThan %82 %166 %177 -%179 = OpAll %58 %178 -OpBranchConditional %179 %180 %175 -%180 = OpLabel -%181 = OpImageFetch %10 %170 %166 Lod %167 -OpBranch %175 -%175 = OpLabel -%182 = OpPhi %10 %172 %171 %172 %176 %181 %180 -%183 = OpCompositeExtract %8 %182 0 -OpReturnValue %183 +%185 = OpFunction %8 None %186 +%182 = OpFunctionParameter %12 +%183 = OpFunctionParameter %6 +%184 = OpFunctionParameter %4 +%181 = OpLabel +%187 = OpLoad %18 %36 +OpBranch %188 +%188 = OpLabel +%189 = OpBitcast %4 %183 +%190 = OpCompositeConstruct %15 %182 %189 +%192 = OpImageQueryLevels %4 %187 +%193 = OpULessThan %55 %184 %192 +OpSelectionMerge %194 None +OpBranchConditional %193 %195 %194 +%195 = OpLabel +%196 = OpImageQuerySizeLod %15 %187 %184 +%197 = OpULessThan %101 %190 %196 +%198 = OpAll %55 %197 +OpBranchConditional %198 %199 %194 +%199 = OpLabel +%200 = OpImageFetch %10 %187 %190 Lod %184 +OpBranch %194 +%194 = OpLabel +%201 = OpPhi %10 %191 %188 %191 %195 %200 %199 +%202 = OpCompositeExtract %8 %201 0 +OpReturnValue %202 OpFunctionEnd -%188 = OpFunction %8 None %189 -%185 = OpFunctionParameter %12 -%186 = OpFunctionParameter %6 -%187 = OpFunctionParameter %4 -%184 = OpLabel -%190 = OpLoad %18 %39 -OpBranch %191 -%191 = OpLabel -%192 = OpBitcast %4 %186 -%193 = OpCompositeConstruct %15 %185 %192 -%195 = OpImageQueryLevels %4 %190 -%196 = OpULessThan %58 %187 %195 -OpSelectionMerge %197 None -OpBranchConditional %196 %198 %197 -%198 = OpLabel -%199 = OpImageQuerySizeLod %15 %190 %187 -%200 = OpULessThan %104 %193 %199 -%201 = OpAll %58 %200 -OpBranchConditional %201 %202 %197 -%202 = OpLabel -%203 = OpImageFetch %10 %190 %193 Lod %187 -OpBranch %197 -%197 = OpLabel -%204 = OpPhi %10 %194 %191 %194 %198 %203 %202 -%205 = OpCompositeExtract %8 %204 0 -OpReturnValue %205 +%207 = OpFunction %8 None %208 +%204 = OpFunctionParameter %12 +%205 = OpFunctionParameter %4 +%206 = OpFunctionParameter %4 +%203 = OpLabel +%209 = OpLoad %18 %36 +OpBranch %210 +%210 = OpLabel +%211 = OpCompositeConstruct %15 %204 %205 +%213 = OpImageQueryLevels %4 %209 +%214 = OpULessThan %55 %206 %213 +OpSelectionMerge %215 None +OpBranchConditional %214 %216 %215 +%216 = OpLabel +%217 = OpImageQuerySizeLod %15 %209 %206 +%218 = OpULessThan %101 %211 %217 +%219 = OpAll %55 %218 +OpBranchConditional %219 %220 %215 +%220 = OpLabel +%221 = OpImageFetch %10 %209 %211 Lod %206 +OpBranch %215 +%215 = OpLabel +%222 = OpPhi %10 %212 %210 %212 %216 %221 %220 +%223 = OpCompositeExtract %8 %222 0 +OpReturnValue %223 OpFunctionEnd -%210 = OpFunction %8 None %211 -%207 = OpFunctionParameter %12 -%208 = OpFunctionParameter %4 -%209 = OpFunctionParameter %4 -%206 = OpLabel -%212 = OpLoad %18 %39 -OpBranch %213 -%213 = OpLabel -%214 = OpCompositeConstruct %15 %207 %208 -%216 = OpImageQueryLevels %4 %212 -%217 = OpULessThan %58 %209 %216 -OpSelectionMerge %218 None -OpBranchConditional %217 %219 %218 -%219 = OpLabel -%220 = OpImageQuerySizeLod %15 %212 %209 -%221 = OpULessThan %104 %214 %220 -%222 = OpAll %58 %221 -OpBranchConditional %222 %223 %218 -%223 = OpLabel -%224 = OpImageFetch %10 %212 %214 Lod %209 -OpBranch %218 -%218 = OpLabel -%225 = OpPhi %10 %215 %213 %215 %219 %224 %223 -%226 = OpCompositeExtract %8 %225 0 -OpReturnValue %226 +%227 = OpFunction %8 None %166 +%225 = OpFunctionParameter %12 +%226 = OpFunctionParameter %4 +%224 = OpLabel +%228 = OpLoad %19 %38 +OpBranch %229 +%229 = OpLabel +%231 = OpImageQuerySamples %4 %228 +%232 = OpULessThan %55 %226 %231 +OpSelectionMerge %233 None +OpBranchConditional %232 %234 %233 +%234 = OpLabel +%235 = OpImageQuerySize %12 %228 +%236 = OpULessThan %79 %225 %235 +%237 = OpAll %55 %236 +OpBranchConditional %237 %238 %233 +%238 = OpLabel +%239 = OpImageFetch %10 %228 %225 Sample %226 +OpBranch %233 +%233 = OpLabel +%240 = OpPhi %10 %230 %229 %230 %234 %239 %238 +%241 = OpCompositeExtract %8 %240 0 +OpReturnValue %241 OpFunctionEnd -%230 = OpFunction %8 None %169 -%228 = OpFunctionParameter %12 -%229 = OpFunctionParameter %4 -%227 = OpLabel -%231 = OpLoad %19 %41 -OpBranch %232 -%232 = OpLabel -%234 = OpImageQuerySamples %4 %231 -%235 = OpULessThan %58 %229 %234 -OpSelectionMerge %236 None -OpBranchConditional %235 %237 %236 -%237 = OpLabel -%238 = OpImageQuerySize %12 %231 -%239 = OpULessThan %82 %228 %238 -%240 = OpAll %58 %239 -OpBranchConditional %240 %241 %236 -%241 = OpLabel -%242 = OpImageFetch %10 %231 %228 Sample %229 -OpBranch %236 -%236 = OpLabel -%243 = OpPhi %10 %233 %232 %233 %237 %242 %241 -%244 = OpCompositeExtract %8 %243 0 -OpReturnValue %244 -OpFunctionEnd -%248 = OpFunction %2 None %249 -%246 = OpFunctionParameter %4 -%247 = OpFunctionParameter %10 -%245 = OpLabel -%250 = OpLoad %20 %43 +%245 = OpFunction %2 None %246 +%243 = OpFunctionParameter %4 +%244 = OpFunctionParameter %10 +%242 = OpLabel +%247 = OpLoad %20 %40 +OpBranch %248 +%248 = OpLabel +%249 = OpImageQuerySize %4 %247 +%250 = OpULessThan %55 %243 %249 +OpSelectionMerge %251 None +OpBranchConditional %250 %252 %251 +%252 = OpLabel +OpImageWrite %247 %243 %244 OpBranch %251 %251 = OpLabel -%252 = OpImageQuerySize %4 %250 -%253 = OpULessThan %58 %246 %252 -OpSelectionMerge %254 None -OpBranchConditional %253 %255 %254 -%255 = OpLabel -OpImageWrite %250 %246 %247 -OpBranch %254 -%254 = OpLabel OpReturn OpFunctionEnd -%259 = OpFunction %2 None %260 -%257 = OpFunctionParameter %12 -%258 = OpFunctionParameter %10 -%256 = OpLabel -%261 = OpLoad %21 %45 -OpBranch %262 -%262 = OpLabel -%263 = OpImageQuerySize %12 %261 -%264 = OpULessThan %82 %257 %263 -%265 = OpAll %58 %264 -OpSelectionMerge %266 None -OpBranchConditional %265 %267 %266 -%267 = OpLabel -OpImageWrite %261 %257 %258 -OpBranch %266 -%266 = OpLabel +%256 = OpFunction %2 None %257 +%254 = OpFunctionParameter %12 +%255 = OpFunctionParameter %10 +%253 = OpLabel +%258 = OpLoad %21 %42 +OpBranch %259 +%259 = OpLabel +%260 = OpImageQuerySize %12 %258 +%261 = OpULessThan %79 %254 %260 +%262 = OpAll %55 %261 +OpSelectionMerge %263 None +OpBranchConditional %262 %264 %263 +%264 = OpLabel +OpImageWrite %258 %254 %255 +OpBranch %263 +%263 = OpLabel OpReturn OpFunctionEnd -%272 = OpFunction %2 None %273 -%269 = OpFunctionParameter %12 -%270 = OpFunctionParameter %6 -%271 = OpFunctionParameter %10 -%268 = OpLabel -%274 = OpLoad %22 %47 -OpBranch %275 -%275 = OpLabel -%276 = OpBitcast %4 %270 -%277 = OpCompositeConstruct %15 %269 %276 -%278 = OpImageQuerySize %15 %274 -%279 = OpULessThan %104 %277 %278 -%280 = OpAll %58 %279 -OpSelectionMerge %281 None -OpBranchConditional %280 %282 %281 -%282 = OpLabel -OpImageWrite %274 %277 %271 -OpBranch %281 -%281 = OpLabel +%269 = OpFunction %2 None %270 +%266 = OpFunctionParameter %12 +%267 = OpFunctionParameter %6 +%268 = OpFunctionParameter %10 +%265 = OpLabel +%271 = OpLoad %22 %44 +OpBranch %272 +%272 = OpLabel +%273 = OpBitcast %4 %267 +%274 = OpCompositeConstruct %15 %266 %273 +%275 = OpImageQuerySize %15 %271 +%276 = OpULessThan %101 %274 %275 +%277 = OpAll %55 %276 +OpSelectionMerge %278 None +OpBranchConditional %277 %279 %278 +%279 = OpLabel +OpImageWrite %271 %274 %268 +OpBranch %278 +%278 = OpLabel OpReturn OpFunctionEnd -%287 = OpFunction %2 None %288 -%284 = OpFunctionParameter %12 -%285 = OpFunctionParameter %4 -%286 = OpFunctionParameter %10 -%283 = OpLabel -%289 = OpLoad %22 %47 -OpBranch %290 -%290 = OpLabel -%291 = OpCompositeConstruct %15 %284 %285 -%292 = OpImageQuerySize %15 %289 -%293 = OpULessThan %104 %291 %292 -%294 = OpAll %58 %293 -OpSelectionMerge %295 None -OpBranchConditional %294 %296 %295 -%296 = OpLabel -OpImageWrite %289 %291 %286 -OpBranch %295 -%295 = OpLabel +%284 = OpFunction %2 None %285 +%281 = OpFunctionParameter %12 +%282 = OpFunctionParameter %4 +%283 = OpFunctionParameter %10 +%280 = OpLabel +%286 = OpLoad %22 %44 +OpBranch %287 +%287 = OpLabel +%288 = OpCompositeConstruct %15 %281 %282 +%289 = OpImageQuerySize %15 %286 +%290 = OpULessThan %101 %288 %289 +%291 = OpAll %55 %290 +OpSelectionMerge %292 None +OpBranchConditional %291 %293 %292 +%293 = OpLabel +OpImageWrite %286 %288 %283 +OpBranch %292 +%292 = OpLabel OpReturn OpFunctionEnd -%300 = OpFunction %2 None %301 -%298 = OpFunctionParameter %15 -%299 = OpFunctionParameter %10 -%297 = OpLabel -%302 = OpLoad %23 %49 -OpBranch %303 -%303 = OpLabel -%304 = OpImageQuerySize %15 %302 -%305 = OpULessThan %104 %298 %304 -%306 = OpAll %58 %305 -OpSelectionMerge %307 None -OpBranchConditional %306 %308 %307 -%308 = OpLabel -OpImageWrite %302 %298 %299 -OpBranch %307 -%307 = OpLabel +%297 = OpFunction %2 None %298 +%295 = OpFunctionParameter %15 +%296 = OpFunctionParameter %10 +%294 = OpLabel +%299 = OpLoad %23 %46 +OpBranch %300 +%300 = OpLabel +%301 = OpImageQuerySize %15 %299 +%302 = OpULessThan %101 %295 %301 +%303 = OpAll %55 %302 +OpSelectionMerge %304 None +OpBranchConditional %303 %305 %304 +%305 = OpLabel +OpImageWrite %299 %295 %296 +OpBranch %304 +%304 = OpLabel OpReturn OpFunctionEnd -%312 = OpFunction %2 None %313 -%309 = OpLabel -%314 = OpLoad %9 %27 -%315 = OpLoad %11 %29 -%316 = OpLoad %13 %31 -%317 = OpLoad %14 %33 -%318 = OpLoad %16 %35 -%319 = OpLoad %20 %43 -%320 = OpLoad %21 %45 -%321 = OpLoad %22 %47 -%322 = OpLoad %23 %49 -OpBranch %323 -%323 = OpLabel -%324 = OpFunctionCall %10 %54 %3 %3 -%325 = OpFunctionCall %10 %72 %24 %3 -%326 = OpFunctionCall %10 %92 %24 %5 %3 -%327 = OpFunctionCall %10 %114 %24 %3 %3 -%328 = OpFunctionCall %10 %133 %25 %3 -%329 = OpFunctionCall %10 %151 %24 %3 -%330 = OpFunctionCall %2 %248 %3 %26 -%331 = OpFunctionCall %2 %259 %24 %26 -%332 = OpFunctionCall %2 %272 %24 %5 %26 -%333 = OpFunctionCall %2 %287 %24 %3 %26 -%334 = OpFunctionCall %2 %300 %25 %26 -%335 = OpCompositeConstruct %10 %7 %7 %7 %7 -OpStore %310 %335 +%309 = OpFunction %2 None %310 +%306 = OpLabel +%311 = OpLoad %9 %24 +%312 = OpLoad %11 %26 +%313 = OpLoad %13 %28 +%314 = OpLoad %14 %30 +%315 = OpLoad %16 %32 +%316 = OpLoad %20 %40 +%317 = OpLoad %21 %42 +%318 = OpLoad %22 %44 +%319 = OpLoad %23 %46 +OpBranch %334 +%334 = OpLabel +%335 = OpFunctionCall %10 %51 %3 %3 +%336 = OpFunctionCall %10 %69 %320 %3 +%337 = OpFunctionCall %10 %89 %321 %5 %3 +%338 = OpFunctionCall %10 %111 %322 %3 %3 +%339 = OpFunctionCall %10 %130 %323 %3 +%340 = OpFunctionCall %10 %148 %324 %3 +%341 = OpFunctionCall %2 %245 %3 %325 +%342 = OpFunctionCall %2 %256 %326 %327 +%343 = OpFunctionCall %2 %269 %328 %5 %329 +%344 = OpFunctionCall %2 %284 %330 %3 %331 +%345 = OpFunctionCall %2 %297 %332 %333 +%346 = OpCompositeConstruct %10 %7 %7 %7 %7 +OpStore %307 %346 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index a69852e7e..5b801db0f 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,54 +1,54 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 186 +; Bound: 185 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %111 "main" %129 -OpExecutionMode %111 LocalSize 1 1 1 -OpDecorate %25 ArrayStride 4 -OpMemberDecorate %27 0 Offset 0 -OpMemberDecorate %27 1 Offset 12 -OpDecorate %29 ArrayStride 8 -OpDecorate %31 ArrayStride 16 -OpDecorate %34 ArrayStride 32 -OpDecorate %35 ArrayStride 64 -OpDecorate %37 ArrayStride 32 -OpDecorate %38 ArrayStride 64 +OpEntryPoint GLCompute %110 "main" %128 +OpExecutionMode %110 LocalSize 1 1 1 +OpDecorate %24 ArrayStride 4 +OpMemberDecorate %26 0 Offset 0 +OpMemberDecorate %26 1 Offset 12 +OpDecorate %28 ArrayStride 8 +OpDecorate %30 ArrayStride 16 +OpDecorate %33 ArrayStride 32 +OpDecorate %34 ArrayStride 64 +OpDecorate %36 ArrayStride 32 +OpDecorate %37 ArrayStride 64 +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 1 +OpDecorate %44 Block +OpMemberDecorate %44 0 Offset 0 +OpDecorate %46 NonWritable OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 1 +OpDecorate %46 Binding 2 OpDecorate %47 Block OpMemberDecorate %47 0 Offset 0 -OpDecorate %49 NonWritable OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 2 +OpDecorate %49 Binding 3 OpDecorate %50 Block OpMemberDecorate %50 0 Offset 0 OpDecorate %52 DescriptorSet 0 -OpDecorate %52 Binding 3 +OpDecorate %52 Binding 4 OpDecorate %53 Block OpMemberDecorate %53 0 Offset 0 OpDecorate %55 DescriptorSet 0 -OpDecorate %55 Binding 4 +OpDecorate %55 Binding 5 OpDecorate %56 Block OpMemberDecorate %56 0 Offset 0 +OpMemberDecorate %56 0 ColMajor +OpMemberDecorate %56 0 MatrixStride 8 OpDecorate %58 DescriptorSet 0 -OpDecorate %58 Binding 5 +OpDecorate %58 Binding 6 OpDecorate %59 Block OpMemberDecorate %59 0 Offset 0 -OpMemberDecorate %59 0 ColMajor -OpMemberDecorate %59 0 MatrixStride 8 OpDecorate %61 DescriptorSet 0 -OpDecorate %61 Binding 6 +OpDecorate %61 Binding 7 OpDecorate %62 Block OpMemberDecorate %62 0 Offset 0 -OpDecorate %64 DescriptorSet 0 -OpDecorate %64 Binding 7 -OpDecorate %65 Block -OpMemberDecorate %65 0 Offset 0 -OpDecorate %129 BuiltIn LocalInvocationId +OpDecorate %128 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -63,205 +63,204 @@ OpDecorate %129 BuiltIn LocalInvocationId %13 = OpConstant %8 0 %14 = OpConstant %11 2.0 %15 = OpConstant %11 3.0 -%16 = OpConstant %11 0.0 -%17 = OpConstant %8 7 -%18 = OpConstant %8 6 -%19 = OpConstant %8 5 -%20 = OpConstant %8 4 -%21 = OpConstant %8 3 -%22 = OpConstant %11 4.0 -%23 = OpConstant %6 2 -%24 = OpConstantTrue %4 -%25 = OpTypeArray %11 %5 -%26 = OpTypeVector %11 3 -%27 = OpTypeStruct %26 %11 -%28 = OpTypeVector %11 2 -%29 = OpTypeRuntimeArray %28 -%30 = OpTypeVector %11 4 -%31 = OpTypeArray %30 %7 -%32 = OpTypeMatrix %28 3 -%33 = OpTypeMatrix %30 2 +%16 = OpConstant %8 7 +%17 = OpConstant %8 6 +%18 = OpConstant %8 5 +%19 = OpConstant %8 4 +%20 = OpConstant %8 3 +%21 = OpConstant %11 4.0 +%22 = OpConstant %6 2 +%23 = OpConstantTrue %4 +%24 = OpTypeArray %11 %5 +%25 = OpTypeVector %11 3 +%26 = OpTypeStruct %25 %11 +%27 = OpTypeVector %11 2 +%28 = OpTypeRuntimeArray %27 +%29 = OpTypeVector %11 4 +%30 = OpTypeArray %29 %7 +%31 = OpTypeMatrix %27 3 +%32 = OpTypeMatrix %29 2 +%33 = OpTypeArray %32 %9 %34 = OpTypeArray %33 %9 -%35 = OpTypeArray %34 %9 -%36 = OpTypeMatrix %28 4 +%35 = OpTypeMatrix %27 4 +%36 = OpTypeArray %35 %9 %37 = OpTypeArray %36 %9 -%38 = OpTypeArray %37 %9 -%39 = OpTypeMatrix %26 3 -%40 = OpConstantComposite %26 %16 %16 %16 -%41 = OpConstantComposite %39 %40 %40 %40 -%43 = OpTypePointer Workgroup %25 -%42 = OpVariable %43 Workgroup -%45 = OpTypePointer Workgroup %6 -%44 = OpVariable %45 Workgroup -%47 = OpTypeStruct %27 +%38 = OpTypeMatrix %25 3 +%40 = OpTypePointer Workgroup %24 +%39 = OpVariable %40 Workgroup +%42 = OpTypePointer Workgroup %6 +%41 = OpVariable %42 Workgroup +%44 = OpTypeStruct %26 +%45 = OpTypePointer StorageBuffer %44 +%43 = OpVariable %45 StorageBuffer +%47 = OpTypeStruct %28 %48 = OpTypePointer StorageBuffer %47 %46 = OpVariable %48 StorageBuffer -%50 = OpTypeStruct %29 -%51 = OpTypePointer StorageBuffer %50 -%49 = OpVariable %51 StorageBuffer -%53 = OpTypeStruct %31 +%50 = OpTypeStruct %30 +%51 = OpTypePointer Uniform %50 +%49 = OpVariable %51 Uniform +%53 = OpTypeStruct %25 %54 = OpTypePointer Uniform %53 %52 = OpVariable %54 Uniform -%56 = OpTypeStruct %26 +%56 = OpTypeStruct %31 %57 = OpTypePointer Uniform %56 %55 = OpVariable %57 Uniform -%59 = OpTypeStruct %32 +%59 = OpTypeStruct %34 %60 = OpTypePointer Uniform %59 %58 = OpVariable %60 Uniform -%62 = OpTypeStruct %35 +%62 = OpTypeStruct %37 %63 = OpTypePointer Uniform %62 %61 = OpVariable %63 Uniform -%65 = OpTypeStruct %38 -%66 = OpTypePointer Uniform %65 -%64 = OpVariable %66 Uniform -%70 = OpTypeFunction %2 %26 -%73 = OpTypePointer Function %8 -%74 = OpConstantNull %8 -%77 = OpTypeFunction %2 -%78 = OpTypePointer StorageBuffer %27 -%79 = OpConstant %6 0 -%82 = OpTypePointer StorageBuffer %26 -%85 = OpTypePointer StorageBuffer %11 -%105 = OpTypePointer Function %11 -%106 = OpConstantNull %11 -%108 = OpTypePointer Function %4 -%109 = OpConstantNull %4 -%113 = OpTypePointer StorageBuffer %29 -%115 = OpTypePointer Uniform %31 -%117 = OpTypePointer Uniform %26 -%119 = OpTypePointer Uniform %32 -%121 = OpTypePointer Uniform %35 -%123 = OpTypePointer Uniform %38 -%126 = OpConstantNull %25 -%127 = OpConstantNull %6 -%128 = OpTypeVector %6 3 -%130 = OpTypePointer Input %128 -%129 = OpVariable %130 Input -%132 = OpConstantNull %128 -%133 = OpTypeVector %4 3 -%138 = OpConstant %6 264 -%141 = OpTypePointer Workgroup %11 -%142 = OpTypePointer Uniform %37 -%143 = OpTypePointer Uniform %36 -%146 = OpTypePointer Uniform %34 -%147 = OpTypePointer Uniform %33 -%148 = OpTypePointer Uniform %30 -%153 = OpConstant %6 7 -%159 = OpConstant %6 6 -%161 = OpTypePointer StorageBuffer %28 -%162 = OpConstant %6 1 -%165 = OpConstant %6 5 -%167 = OpTypePointer Uniform %30 -%168 = OpTypePointer Uniform %11 -%169 = OpConstant %6 3 -%172 = OpConstant %6 4 -%174 = OpTypePointer StorageBuffer %11 -%185 = OpConstant %6 256 -%69 = OpFunction %2 None %70 -%68 = OpFunctionParameter %26 -%67 = OpLabel -OpBranch %71 -%71 = OpLabel +%67 = OpTypeFunction %2 %25 +%70 = OpTypePointer Function %8 +%71 = OpConstantNull %8 +%74 = OpTypeFunction %2 +%75 = OpTypePointer StorageBuffer %26 +%76 = OpConstant %6 0 +%78 = OpConstantNull %38 +%79 = OpConstantNull %38 +%81 = OpTypePointer StorageBuffer %25 +%84 = OpTypePointer StorageBuffer %11 +%104 = OpTypePointer Function %11 +%105 = OpConstantNull %11 +%107 = OpTypePointer Function %4 +%108 = OpConstantNull %4 +%112 = OpTypePointer StorageBuffer %28 +%114 = OpTypePointer Uniform %30 +%116 = OpTypePointer Uniform %25 +%118 = OpTypePointer Uniform %31 +%120 = OpTypePointer Uniform %34 +%122 = OpTypePointer Uniform %37 +%125 = OpConstantNull %24 +%126 = OpConstantNull %6 +%127 = OpTypeVector %6 3 +%129 = OpTypePointer Input %127 +%128 = OpVariable %129 Input +%131 = OpConstantNull %127 +%132 = OpTypeVector %4 3 +%137 = OpConstant %6 264 +%140 = OpTypePointer Workgroup %11 +%141 = OpTypePointer Uniform %36 +%142 = OpTypePointer Uniform %35 +%145 = OpTypePointer Uniform %33 +%146 = OpTypePointer Uniform %32 +%147 = OpTypePointer Uniform %29 +%152 = OpConstant %6 7 +%158 = OpConstant %6 6 +%160 = OpTypePointer StorageBuffer %27 +%161 = OpConstant %6 1 +%164 = OpConstant %6 5 +%166 = OpTypePointer Uniform %29 +%167 = OpTypePointer Uniform %11 +%168 = OpConstant %6 3 +%171 = OpConstant %6 4 +%173 = OpTypePointer StorageBuffer %11 +%184 = OpConstant %6 256 +%66 = OpFunction %2 None %67 +%65 = OpFunctionParameter %25 +%64 = OpLabel +OpBranch %68 +%68 = OpLabel OpReturn OpFunctionEnd -%76 = OpFunction %2 None %77 -%75 = OpLabel -%72 = OpVariable %73 Function %74 -%80 = OpAccessChain %78 %46 %79 -OpBranch %81 -%81 = OpLabel -%83 = OpCompositeConstruct %26 %10 %10 %10 -%84 = OpAccessChain %82 %80 %79 -OpStore %84 %83 -OpStore %72 %12 -%86 = OpAccessChain %85 %80 %79 %79 -OpStore %86 %10 -%87 = OpAccessChain %85 %80 %79 %79 -OpStore %87 %14 -%88 = OpLoad %8 %72 -%89 = OpAccessChain %85 %80 %79 %88 -OpStore %89 %15 -%90 = OpLoad %27 %80 -%91 = OpCompositeExtract %26 %90 0 -%92 = OpCompositeExtract %26 %90 0 -%93 = OpVectorShuffle %28 %92 %92 2 0 -%94 = OpCompositeExtract %26 %90 0 -%95 = OpFunctionCall %2 %69 %94 -%96 = OpCompositeExtract %26 %90 0 -%97 = OpVectorTimesMatrix %26 %96 %41 -%98 = OpCompositeExtract %26 %90 0 -%99 = OpMatrixTimesVector %26 %41 %98 -%100 = OpCompositeExtract %26 %90 0 -%101 = OpVectorTimesScalar %26 %100 %14 -%102 = OpCompositeExtract %26 %90 0 -%103 = OpVectorTimesScalar %26 %102 %14 +%73 = OpFunction %2 None %74 +%72 = OpLabel +%69 = OpVariable %70 Function %71 +%77 = OpAccessChain %75 %43 %76 +OpBranch %80 +%80 = OpLabel +%82 = OpCompositeConstruct %25 %10 %10 %10 +%83 = OpAccessChain %81 %77 %76 +OpStore %83 %82 +OpStore %69 %12 +%85 = OpAccessChain %84 %77 %76 %76 +OpStore %85 %10 +%86 = OpAccessChain %84 %77 %76 %76 +OpStore %86 %14 +%87 = OpLoad %8 %69 +%88 = OpAccessChain %84 %77 %76 %87 +OpStore %88 %15 +%89 = OpLoad %26 %77 +%90 = OpCompositeExtract %25 %89 0 +%91 = OpCompositeExtract %25 %89 0 +%92 = OpVectorShuffle %27 %91 %91 2 0 +%93 = OpCompositeExtract %25 %89 0 +%94 = OpFunctionCall %2 %66 %93 +%95 = OpCompositeExtract %25 %89 0 +%96 = OpVectorTimesMatrix %25 %95 %78 +%97 = OpCompositeExtract %25 %89 0 +%98 = OpMatrixTimesVector %25 %79 %97 +%99 = OpCompositeExtract %25 %89 0 +%100 = OpVectorTimesScalar %25 %99 %14 +%101 = OpCompositeExtract %25 %89 0 +%102 = OpVectorTimesScalar %25 %101 %14 OpReturn OpFunctionEnd -%111 = OpFunction %2 None %77 -%110 = OpLabel -%104 = OpVariable %105 Function %106 -%107 = OpVariable %108 Function %109 -%112 = OpAccessChain %78 %46 %79 -%114 = OpAccessChain %113 %49 %79 -%116 = OpAccessChain %115 %52 %79 -%118 = OpAccessChain %117 %55 %79 -%120 = OpAccessChain %119 %58 %79 -%122 = OpAccessChain %121 %61 %79 -%124 = OpAccessChain %123 %64 %79 -OpBranch %125 -%125 = OpLabel -%131 = OpLoad %128 %129 -%134 = OpIEqual %133 %131 %132 -%135 = OpAll %4 %134 -OpSelectionMerge %136 None -OpBranchConditional %135 %137 %136 -%137 = OpLabel -OpStore %42 %126 -OpStore %44 %127 -OpBranch %136 +%110 = OpFunction %2 None %74 +%109 = OpLabel +%103 = OpVariable %104 Function %105 +%106 = OpVariable %107 Function %108 +%111 = OpAccessChain %75 %43 %76 +%113 = OpAccessChain %112 %46 %76 +%115 = OpAccessChain %114 %49 %76 +%117 = OpAccessChain %116 %52 %76 +%119 = OpAccessChain %118 %55 %76 +%121 = OpAccessChain %120 %58 %76 +%123 = OpAccessChain %122 %61 %76 +OpBranch %124 +%124 = OpLabel +%130 = OpLoad %127 %128 +%133 = OpIEqual %132 %130 %131 +%134 = OpAll %4 %133 +OpSelectionMerge %135 None +OpBranchConditional %134 %136 %135 %136 = OpLabel -OpControlBarrier %23 %23 %138 -OpBranch %139 -%139 = OpLabel -%140 = OpFunctionCall %2 %76 -%144 = OpAccessChain %143 %124 %79 %79 -%145 = OpLoad %36 %144 -%149 = OpAccessChain %148 %122 %79 %79 %79 -%150 = OpLoad %30 %149 -%151 = OpMatrixTimesVector %28 %145 %150 -%152 = OpCompositeExtract %11 %151 0 -%154 = OpAccessChain %141 %42 %153 -OpStore %154 %152 -%155 = OpLoad %32 %120 -%156 = OpLoad %26 %118 -%157 = OpMatrixTimesVector %28 %155 %156 -%158 = OpCompositeExtract %11 %157 0 -%160 = OpAccessChain %141 %42 %159 -OpStore %160 %158 -%163 = OpAccessChain %85 %114 %162 %162 -%164 = OpLoad %11 %163 -%166 = OpAccessChain %141 %42 %165 -OpStore %166 %164 -%170 = OpAccessChain %168 %116 %79 %169 -%171 = OpLoad %11 %170 -%173 = OpAccessChain %141 %42 %172 -OpStore %173 %171 -%175 = OpAccessChain %174 %112 %162 -%176 = OpLoad %11 %175 -%177 = OpAccessChain %141 %42 %169 -OpStore %177 %176 -%178 = OpAccessChain %85 %112 %79 %79 -%179 = OpLoad %11 %178 -%180 = OpAccessChain %141 %42 %23 -OpStore %180 %179 -%181 = OpAccessChain %174 %112 %162 -OpStore %181 %22 -%182 = OpArrayLength %6 %49 0 -%183 = OpConvertUToF %11 %182 -%184 = OpAccessChain %141 %42 %162 -OpStore %184 %183 -OpAtomicStore %44 %9 %185 %23 -OpStore %104 %10 -OpStore %107 %24 +OpStore %39 %125 +OpStore %41 %126 +OpBranch %135 +%135 = OpLabel +OpControlBarrier %22 %22 %137 +OpBranch %138 +%138 = OpLabel +%139 = OpFunctionCall %2 %73 +%143 = OpAccessChain %142 %123 %76 %76 +%144 = OpLoad %35 %143 +%148 = OpAccessChain %147 %121 %76 %76 %76 +%149 = OpLoad %29 %148 +%150 = OpMatrixTimesVector %27 %144 %149 +%151 = OpCompositeExtract %11 %150 0 +%153 = OpAccessChain %140 %39 %152 +OpStore %153 %151 +%154 = OpLoad %31 %119 +%155 = OpLoad %25 %117 +%156 = OpMatrixTimesVector %27 %154 %155 +%157 = OpCompositeExtract %11 %156 0 +%159 = OpAccessChain %140 %39 %158 +OpStore %159 %157 +%162 = OpAccessChain %84 %113 %161 %161 +%163 = OpLoad %11 %162 +%165 = OpAccessChain %140 %39 %164 +OpStore %165 %163 +%169 = OpAccessChain %167 %115 %76 %168 +%170 = OpLoad %11 %169 +%172 = OpAccessChain %140 %39 %171 +OpStore %172 %170 +%174 = OpAccessChain %173 %111 %161 +%175 = OpLoad %11 %174 +%176 = OpAccessChain %140 %39 %168 +OpStore %176 %175 +%177 = OpAccessChain %84 %111 %76 %76 +%178 = OpLoad %11 %177 +%179 = OpAccessChain %140 %39 %22 +OpStore %179 %178 +%180 = OpAccessChain %173 %111 %161 +OpStore %180 %21 +%181 = OpArrayLength %6 %46 0 +%182 = OpConvertUToF %11 %181 +%183 = OpAccessChain %140 %39 %161 +OpStore %183 %182 +OpAtomicStore %41 %9 %184 %22 +OpStore %103 %10 +OpStore %106 %23 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 8dc763c0d..ecf925bdd 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,97 +1,98 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 87 +; Bound: 88 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %18 "main" -OpExecutionMode %18 OriginUpperLeft +OpEntryPoint Fragment %17 "main" +OpExecutionMode %17 OriginUpperLeft %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 %5 = OpConstant %4 0.0 -%7 = OpTypeInt 32 1 +%7 = OpTypeInt 32 0 %6 = OpConstant %7 0 -%9 = OpTypeInt 32 0 -%8 = OpConstant %9 0 -%10 = OpConstant %7 -1 -%11 = OpConstant %9 1 -%12 = OpConstant %9 4294967295 -%13 = OpConstant %7 1 +%9 = OpTypeInt 32 1 +%8 = OpConstant %9 -1 +%10 = OpConstant %7 1 +%11 = OpConstant %9 0 +%12 = OpConstant %7 4294967295 +%13 = OpConstant %9 1 %14 = OpTypeVector %4 4 -%15 = OpTypeVector %7 2 -%16 = OpConstantComposite %15 %6 %6 -%19 = OpTypeFunction %2 -%27 = OpConstantComposite %14 %5 %5 %5 %5 -%28 = OpConstantComposite %14 %3 %3 %3 %3 -%31 = OpConstantNull %7 -%44 = OpTypeVector %9 2 -%54 = OpConstant %9 32 -%64 = OpConstantComposite %44 %54 %54 -%76 = OpConstant %7 31 -%82 = OpConstantComposite %15 %76 %76 -%18 = OpFunction %2 None %19 -%17 = OpLabel -OpBranch %20 -%20 = OpLabel -%21 = OpCompositeConstruct %14 %5 %5 %5 %5 -%22 = OpExtInst %4 %1 Degrees %3 -%23 = OpExtInst %4 %1 Radians %3 -%24 = OpExtInst %14 %1 Degrees %21 -%25 = OpExtInst %14 %1 Radians %21 -%26 = OpExtInst %14 %1 FClamp %21 %27 %28 -%29 = OpExtInst %14 %1 Refract %21 %21 %3 -%32 = OpCompositeExtract %7 %16 0 -%33 = OpCompositeExtract %7 %16 0 -%34 = OpIMul %7 %32 %33 -%35 = OpIAdd %7 %31 %34 -%36 = OpCompositeExtract %7 %16 1 -%37 = OpCompositeExtract %7 %16 1 -%38 = OpIMul %7 %36 %37 -%30 = OpIAdd %7 %35 %38 -%39 = OpCopyObject %9 %8 -%40 = OpExtInst %9 %1 FindUMsb %39 -%41 = OpExtInst %7 %1 FindSMsb %10 -%42 = OpCompositeConstruct %15 %10 %10 -%43 = OpExtInst %15 %1 FindSMsb %42 -%45 = OpCompositeConstruct %44 %11 %11 -%46 = OpExtInst %44 %1 FindUMsb %45 -%47 = OpExtInst %7 %1 FindILsb %10 -%48 = OpExtInst %9 %1 FindILsb %11 -%49 = OpCompositeConstruct %15 %10 %10 -%50 = OpExtInst %15 %1 FindILsb %49 -%51 = OpCompositeConstruct %44 %11 %11 -%52 = OpExtInst %44 %1 FindILsb %51 -%55 = OpExtInst %9 %1 FindILsb %8 -%53 = OpExtInst %9 %1 UMin %54 %55 -%57 = OpExtInst %7 %1 FindILsb %6 -%56 = OpExtInst %7 %1 UMin %54 %57 -%59 = OpExtInst %9 %1 FindILsb %12 -%58 = OpExtInst %9 %1 UMin %54 %59 -%61 = OpExtInst %7 %1 FindILsb %10 -%60 = OpExtInst %7 %1 UMin %54 %61 -%62 = OpCompositeConstruct %44 %8 %8 -%65 = OpExtInst %44 %1 FindILsb %62 -%63 = OpExtInst %44 %1 UMin %64 %65 -%66 = OpCompositeConstruct %15 %6 %6 -%68 = OpExtInst %15 %1 FindILsb %66 -%67 = OpExtInst %15 %1 UMin %64 %68 -%69 = OpCompositeConstruct %44 %11 %11 -%71 = OpExtInst %44 %1 FindILsb %69 -%70 = OpExtInst %44 %1 UMin %64 %71 -%72 = OpCompositeConstruct %15 %13 %13 -%74 = OpExtInst %15 %1 FindILsb %72 -%73 = OpExtInst %15 %1 UMin %64 %74 -%77 = OpExtInst %7 %1 FindUMsb %10 -%75 = OpISub %7 %76 %77 -%79 = OpExtInst %7 %1 FindUMsb %11 -%78 = OpISub %9 %76 %79 -%80 = OpCompositeConstruct %15 %10 %10 -%83 = OpExtInst %15 %1 FindUMsb %80 -%81 = OpISub %15 %82 %83 -%84 = OpCompositeConstruct %44 %11 %11 -%86 = OpExtInst %15 %1 FindUMsb %84 -%85 = OpISub %44 %82 %86 +%15 = OpTypeVector %9 2 +%18 = OpTypeFunction %2 +%19 = OpConstantNull %15 +%20 = OpConstantNull %15 +%28 = OpConstantComposite %14 %5 %5 %5 %5 +%29 = OpConstantComposite %14 %3 %3 %3 %3 +%32 = OpConstantNull %9 +%45 = OpTypeVector %7 2 +%55 = OpConstant %7 32 +%65 = OpConstantComposite %45 %55 %55 +%77 = OpConstant %9 31 +%83 = OpConstantComposite %15 %77 %77 +%17 = OpFunction %2 None %18 +%16 = OpLabel +OpBranch %21 +%21 = OpLabel +%22 = OpCompositeConstruct %14 %5 %5 %5 %5 +%23 = OpExtInst %4 %1 Degrees %3 +%24 = OpExtInst %4 %1 Radians %3 +%25 = OpExtInst %14 %1 Degrees %22 +%26 = OpExtInst %14 %1 Radians %22 +%27 = OpExtInst %14 %1 FClamp %22 %28 %29 +%30 = OpExtInst %14 %1 Refract %22 %22 %3 +%33 = OpCompositeExtract %9 %19 0 +%34 = OpCompositeExtract %9 %20 0 +%35 = OpIMul %9 %33 %34 +%36 = OpIAdd %9 %32 %35 +%37 = OpCompositeExtract %9 %19 1 +%38 = OpCompositeExtract %9 %20 1 +%39 = OpIMul %9 %37 %38 +%31 = OpIAdd %9 %36 %39 +%40 = OpCopyObject %7 %6 +%41 = OpExtInst %7 %1 FindUMsb %40 +%42 = OpExtInst %9 %1 FindSMsb %8 +%43 = OpCompositeConstruct %15 %8 %8 +%44 = OpExtInst %15 %1 FindSMsb %43 +%46 = OpCompositeConstruct %45 %10 %10 +%47 = OpExtInst %45 %1 FindUMsb %46 +%48 = OpExtInst %9 %1 FindILsb %8 +%49 = OpExtInst %7 %1 FindILsb %10 +%50 = OpCompositeConstruct %15 %8 %8 +%51 = OpExtInst %15 %1 FindILsb %50 +%52 = OpCompositeConstruct %45 %10 %10 +%53 = OpExtInst %45 %1 FindILsb %52 +%56 = OpExtInst %7 %1 FindILsb %6 +%54 = OpExtInst %7 %1 UMin %55 %56 +%58 = OpExtInst %9 %1 FindILsb %11 +%57 = OpExtInst %9 %1 UMin %55 %58 +%60 = OpExtInst %7 %1 FindILsb %12 +%59 = OpExtInst %7 %1 UMin %55 %60 +%62 = OpExtInst %9 %1 FindILsb %8 +%61 = OpExtInst %9 %1 UMin %55 %62 +%63 = OpCompositeConstruct %45 %6 %6 +%66 = OpExtInst %45 %1 FindILsb %63 +%64 = OpExtInst %45 %1 UMin %65 %66 +%67 = OpCompositeConstruct %15 %11 %11 +%69 = OpExtInst %15 %1 FindILsb %67 +%68 = OpExtInst %15 %1 UMin %65 %69 +%70 = OpCompositeConstruct %45 %10 %10 +%72 = OpExtInst %45 %1 FindILsb %70 +%71 = OpExtInst %45 %1 UMin %65 %72 +%73 = OpCompositeConstruct %15 %13 %13 +%75 = OpExtInst %15 %1 FindILsb %73 +%74 = OpExtInst %15 %1 UMin %65 %75 +%78 = OpExtInst %9 %1 FindUMsb %8 +%76 = OpISub %9 %77 %78 +%80 = OpExtInst %9 %1 FindUMsb %10 +%79 = OpISub %7 %77 %80 +%81 = OpCompositeConstruct %15 %8 %8 +%84 = OpExtInst %15 %1 FindUMsb %81 +%82 = OpISub %15 %83 %84 +%85 = OpCompositeConstruct %45 %10 %10 +%87 = OpExtInst %15 %1 FindUMsb %85 +%86 = OpISub %45 %83 %87 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index d3c595e67..64a2ed2f4 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 573 +; Bound: 588 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %561 "main" -OpExecutionMode %561 LocalSize 1 1 1 +OpEntryPoint GLCompute %576 "main" +OpExecutionMode %576 LocalSize 1 1 1 OpMemberDecorate %40 0 Offset 0 OpMemberDecorate %40 1 Offset 16 OpDecorate %44 ArrayStride 32 @@ -28,13 +28,13 @@ OpDecorate %45 ArrayStride 4 %16 = OpConstant %4 4.0 %17 = OpConstant %8 5 %18 = OpConstant %8 2 -%20 = OpTypeInt 32 0 -%19 = OpConstant %20 0 -%21 = OpConstant %8 3 -%22 = OpConstant %20 4 +%19 = OpConstant %8 3 +%21 = OpTypeInt 32 0 +%20 = OpConstant %21 0 +%22 = OpConstant %21 4 %23 = OpConstant %4 -1.0 -%24 = OpConstant %20 2 -%25 = OpConstant %20 1 +%24 = OpConstant %21 2 +%25 = OpConstant %21 1 %26 = OpConstant %8 -1 %27 = OpConstant %8 -2 %28 = OpConstant %8 -3 @@ -52,8 +52,8 @@ OpDecorate %45 ArrayStride 4 %40 = OpTypeStruct %34 %8 %41 = OpTypeMatrix %37 2 %42 = OpTypeMatrix %34 4 -%43 = OpTypeVector %20 2 -%44 = OpTypeArray %40 %21 +%43 = OpTypeVector %21 2 +%44 = OpTypeArray %40 %19 %45 = OpTypeArray %8 %22 %46 = OpTypeMatrix %38 2 %47 = OpTypeMatrix %38 3 @@ -64,572 +64,587 @@ OpDecorate %45 ArrayStride 4 %52 = OpConstantComposite %34 %5 %5 %5 %5 %53 = OpConstantComposite %34 %6 %6 %6 %6 %54 = OpConstantComposite %35 %7 %7 %7 %7 -%55 = OpConstantComposite %43 %19 %19 -%56 = OpConstantComposite %37 %5 %5 -%57 = OpConstantComposite %41 %56 %56 -%58 = OpConstantComposite %34 %5 %5 %5 %5 -%59 = OpConstantComposite %40 %58 %11 -%60 = OpConstantComposite %44 %59 %59 %59 -%61 = OpConstantComposite %38 %5 %5 %5 -%62 = OpConstantComposite %46 %61 %61 -%63 = OpConstantComposite %47 %61 %61 %61 -%64 = OpConstantComposite %48 %61 %61 %61 %61 -%65 = OpConstantComposite %49 %58 %58 %58 -%66 = OpConstantComposite %50 %11 %11 %11 -%69 = OpTypeFunction %34 -%109 = OpTypePointer Function %37 -%110 = OpConstantNull %37 -%113 = OpTypeFunction %37 -%129 = OpTypeFunction %38 %38 -%131 = OpConstantComposite %38 %5 %5 %5 -%133 = OpConstantComposite %38 %3 %3 %3 -%136 = OpTypePointer Function %40 -%137 = OpConstantNull %40 -%140 = OpTypeFunction %4 -%165 = OpTypePointer Function %34 -%166 = OpTypePointer Function %4 -%171 = OpTypeFunction %2 -%174 = OpTypeVector %10 2 -%190 = OpTypeVector %8 2 -%201 = OpTypeVector %20 3 -%496 = OpTypePointer Function %8 -%497 = OpConstantNull %8 -%499 = OpTypePointer Function %50 -%500 = OpConstantNull %50 -%530 = OpTypePointer Function %8 -%68 = OpFunction %34 None %69 -%67 = OpLabel -OpBranch %70 -%70 = OpLabel -%71 = OpSelect %8 %9 %7 %11 -%73 = OpCompositeConstruct %36 %9 %9 %9 %9 -%72 = OpSelect %34 %73 %51 %52 -%74 = OpCompositeConstruct %36 %12 %12 %12 %12 -%75 = OpSelect %34 %74 %52 %51 -%76 = OpExtInst %34 %1 FMix %52 %51 %53 -%78 = OpCompositeConstruct %34 %13 %13 %13 %13 -%77 = OpExtInst %34 %1 FMix %52 %51 %78 -%79 = OpCompositeExtract %8 %54 0 -%80 = OpBitcast %4 %79 -%81 = OpBitcast %34 %54 -%82 = OpConvertFToS %35 %52 -%83 = OpCompositeConstruct %35 %71 %71 %71 %71 -%84 = OpIAdd %35 %83 %82 -%85 = OpConvertSToF %34 %84 -%86 = OpFAdd %34 %85 %72 -%87 = OpFAdd %34 %86 %76 -%88 = OpFAdd %34 %87 %77 -%89 = OpCompositeConstruct %34 %80 %80 %80 %80 -%90 = OpFAdd %34 %88 %89 -%91 = OpFAdd %34 %90 %81 -OpReturnValue %91 +%57 = OpTypeFunction %34 +%97 = OpTypePointer Function %37 +%98 = OpConstantNull %37 +%101 = OpTypeFunction %37 +%117 = OpTypeFunction %38 %38 +%119 = OpConstantComposite %38 %5 %5 %5 +%121 = OpConstantComposite %38 %3 %3 %3 +%124 = OpTypePointer Function %40 +%125 = OpConstantNull %40 +%128 = OpTypeFunction %4 +%129 = OpConstantNull %10 +%130 = OpConstantNull %8 +%131 = OpConstantNull %21 +%132 = OpConstantNull %4 +%133 = OpConstantNull %43 +%134 = OpConstantNull %41 +%135 = OpConstantNull %44 +%136 = OpConstantNull %40 +%137 = OpConstantNull %10 +%138 = OpConstantNull %8 +%139 = OpConstantNull %21 +%140 = OpConstantNull %4 +%141 = OpConstantNull %43 +%142 = OpConstantNull %46 +%143 = OpConstantNull %43 +%144 = OpConstantNull %46 +%169 = OpTypePointer Function %34 +%170 = OpTypePointer Function %4 +%175 = OpTypeFunction %2 +%178 = OpTypeVector %10 2 +%193 = OpConstantNull %47 +%194 = OpConstantNull %47 +%195 = OpConstantNull %47 +%196 = OpConstantNull %47 +%197 = OpConstantNull %47 +%198 = OpConstantNull %47 +%199 = OpConstantNull %48 +%200 = OpConstantNull %48 +%201 = OpConstantNull %48 +%202 = OpConstantNull %49 +%204 = OpTypeVector %8 2 +%215 = OpTypeVector %21 3 +%510 = OpTypePointer Function %8 +%511 = OpConstantNull %8 +%513 = OpTypePointer Function %50 +%514 = OpConstantNull %50 +%517 = OpConstantNull %50 +%545 = OpTypePointer Function %8 +%56 = OpFunction %34 None %57 +%55 = OpLabel +OpBranch %58 +%58 = OpLabel +%59 = OpSelect %8 %9 %7 %11 +%61 = OpCompositeConstruct %36 %9 %9 %9 %9 +%60 = OpSelect %34 %61 %51 %52 +%62 = OpCompositeConstruct %36 %12 %12 %12 %12 +%63 = OpSelect %34 %62 %52 %51 +%64 = OpExtInst %34 %1 FMix %52 %51 %53 +%66 = OpCompositeConstruct %34 %13 %13 %13 %13 +%65 = OpExtInst %34 %1 FMix %52 %51 %66 +%67 = OpCompositeExtract %8 %54 0 +%68 = OpBitcast %4 %67 +%69 = OpBitcast %34 %54 +%70 = OpConvertFToS %35 %52 +%71 = OpCompositeConstruct %35 %59 %59 %59 %59 +%72 = OpIAdd %35 %71 %70 +%73 = OpConvertSToF %34 %72 +%74 = OpFAdd %34 %73 %60 +%75 = OpFAdd %34 %74 %64 +%76 = OpFAdd %34 %75 %65 +%77 = OpCompositeConstruct %34 %68 %68 %68 %68 +%78 = OpFAdd %34 %76 %77 +%79 = OpFAdd %34 %78 %69 +OpReturnValue %79 OpFunctionEnd -%93 = OpFunction %34 None %69 -%92 = OpLabel -OpBranch %94 -%94 = OpLabel -%95 = OpCompositeConstruct %37 %14 %14 -%96 = OpCompositeConstruct %37 %3 %3 -%97 = OpFAdd %37 %96 %95 -%98 = OpCompositeConstruct %37 %15 %15 -%99 = OpFSub %37 %97 %98 -%100 = OpCompositeConstruct %37 %16 %16 -%101 = OpFDiv %37 %99 %100 -%102 = OpCompositeConstruct %35 %17 %17 %17 %17 -%103 = OpCompositeConstruct %35 %18 %18 %18 %18 -%104 = OpSRem %35 %102 %103 -%105 = OpVectorShuffle %34 %101 %101 0 1 0 1 -%106 = OpConvertSToF %34 %104 -%107 = OpFAdd %34 %105 %106 -OpReturnValue %107 +%81 = OpFunction %34 None %57 +%80 = OpLabel +OpBranch %82 +%82 = OpLabel +%83 = OpCompositeConstruct %37 %14 %14 +%84 = OpCompositeConstruct %37 %3 %3 +%85 = OpFAdd %37 %84 %83 +%86 = OpCompositeConstruct %37 %15 %15 +%87 = OpFSub %37 %85 %86 +%88 = OpCompositeConstruct %37 %16 %16 +%89 = OpFDiv %37 %87 %88 +%90 = OpCompositeConstruct %35 %17 %17 %17 %17 +%91 = OpCompositeConstruct %35 %18 %18 %18 %18 +%92 = OpSRem %35 %90 %91 +%93 = OpVectorShuffle %34 %89 %89 0 1 0 1 +%94 = OpConvertSToF %34 %92 +%95 = OpFAdd %34 %93 %94 +OpReturnValue %95 OpFunctionEnd -%112 = OpFunction %37 None %113 -%111 = OpLabel -%108 = OpVariable %109 Function %110 -OpBranch %114 +%100 = OpFunction %37 None %101 +%99 = OpLabel +%96 = OpVariable %97 Function %98 +OpBranch %102 +%102 = OpLabel +%103 = OpCompositeConstruct %37 %14 %14 +OpStore %96 %103 +%104 = OpLoad %37 %96 +%105 = OpCompositeConstruct %37 %3 %3 +%106 = OpFAdd %37 %104 %105 +OpStore %96 %106 +%107 = OpLoad %37 %96 +%108 = OpCompositeConstruct %37 %15 %15 +%109 = OpFSub %37 %107 %108 +OpStore %96 %109 +%110 = OpLoad %37 %96 +%111 = OpCompositeConstruct %37 %16 %16 +%112 = OpFDiv %37 %110 %111 +OpStore %96 %112 +%113 = OpLoad %37 %96 +OpReturnValue %113 +OpFunctionEnd +%116 = OpFunction %38 None %117 +%115 = OpFunctionParameter %38 %114 = OpLabel -%115 = OpCompositeConstruct %37 %14 %14 -OpStore %108 %115 -%116 = OpLoad %37 %108 -%117 = OpCompositeConstruct %37 %3 %3 -%118 = OpFAdd %37 %116 %117 -OpStore %108 %118 -%119 = OpLoad %37 %108 -%120 = OpCompositeConstruct %37 %15 %15 -%121 = OpFSub %37 %119 %120 -OpStore %108 %121 -%122 = OpLoad %37 %108 -%123 = OpCompositeConstruct %37 %16 %16 -%124 = OpFDiv %37 %122 %123 -OpStore %108 %124 -%125 = OpLoad %37 %108 -OpReturnValue %125 +OpBranch %118 +%118 = OpLabel +%120 = OpFUnordNotEqual %39 %115 %119 +%122 = OpSelect %38 %120 %121 %119 +OpReturnValue %122 OpFunctionEnd -%128 = OpFunction %38 None %129 -%127 = OpFunctionParameter %38 +%127 = OpFunction %4 None %128 %126 = OpLabel -OpBranch %130 -%130 = OpLabel -%132 = OpFUnordNotEqual %39 %127 %131 -%134 = OpSelect %38 %132 %133 %131 -OpReturnValue %134 +%123 = OpVariable %124 Function %125 +OpBranch %145 +%145 = OpLabel +%146 = OpCompositeConstruct %34 %3 %3 %3 %3 +%147 = OpCompositeConstruct %40 %146 %7 +OpStore %123 %147 +%148 = OpCompositeConstruct %37 %3 %5 +%149 = OpCompositeConstruct %37 %5 %3 +%150 = OpCompositeConstruct %41 %148 %149 +%151 = OpCompositeConstruct %34 %3 %5 %5 %5 +%152 = OpCompositeConstruct %34 %5 %3 %5 %5 +%153 = OpCompositeConstruct %34 %5 %5 %3 %5 +%154 = OpCompositeConstruct %34 %5 %5 %5 %3 +%155 = OpCompositeConstruct %42 %151 %152 %153 %154 +%156 = OpCompositeConstruct %43 %20 %20 +%157 = OpCompositeConstruct %37 %5 %5 +%158 = OpCompositeConstruct %37 %5 %5 +%159 = OpCompositeConstruct %41 %157 %158 +%160 = OpCompositeConstruct %45 %11 %7 %18 %19 +%166 = OpCopyObject %46 %142 +%168 = OpCopyObject %46 %144 +%171 = OpAccessChain %170 %123 %20 %20 +%172 = OpLoad %4 %171 +OpReturnValue %172 OpFunctionEnd -%139 = OpFunction %4 None %140 -%138 = OpLabel -%135 = OpVariable %136 Function %137 -OpBranch %141 -%141 = OpLabel -%142 = OpCompositeConstruct %34 %3 %3 %3 %3 -%143 = OpCompositeConstruct %40 %142 %7 -OpStore %135 %143 -%144 = OpCompositeConstruct %37 %3 %5 -%145 = OpCompositeConstruct %37 %5 %3 -%146 = OpCompositeConstruct %41 %144 %145 -%147 = OpCompositeConstruct %34 %3 %5 %5 %5 -%148 = OpCompositeConstruct %34 %5 %3 %5 %5 -%149 = OpCompositeConstruct %34 %5 %5 %3 %5 -%150 = OpCompositeConstruct %34 %5 %5 %5 %3 -%151 = OpCompositeConstruct %42 %147 %148 %149 %150 -%152 = OpCompositeConstruct %43 %19 %19 -%153 = OpCompositeConstruct %37 %5 %5 -%154 = OpCompositeConstruct %37 %5 %5 -%155 = OpCompositeConstruct %41 %153 %154 -%156 = OpCompositeConstruct %45 %11 %7 %18 %21 -%162 = OpCopyObject %46 %62 -%164 = OpCopyObject %46 %62 -%167 = OpAccessChain %166 %135 %19 %19 -%168 = OpLoad %4 %167 -OpReturnValue %168 -OpFunctionEnd -%170 = OpFunction %2 None %171 -%169 = OpLabel -OpBranch %172 -%172 = OpLabel -%173 = OpLogicalNot %10 %9 -%175 = OpCompositeConstruct %174 %9 %9 -%176 = OpLogicalNot %174 %175 -%177 = OpLogicalOr %10 %9 %12 -%178 = OpLogicalAnd %10 %9 %12 -%179 = OpLogicalOr %10 %9 %12 -%180 = OpCompositeConstruct %39 %9 %9 %9 -%181 = OpCompositeConstruct %39 %12 %12 %12 -%182 = OpLogicalOr %39 %180 %181 -%183 = OpLogicalAnd %10 %9 %12 -%184 = OpCompositeConstruct %36 %9 %9 %9 %9 -%185 = OpCompositeConstruct %36 %12 %12 %12 %12 -%186 = OpLogicalAnd %36 %184 %185 +%174 = OpFunction %2 None %175 +%173 = OpLabel +OpBranch %176 +%176 = OpLabel +%177 = OpLogicalNot %10 %9 +%179 = OpCompositeConstruct %178 %9 %9 +%180 = OpLogicalNot %178 %179 +%181 = OpLogicalOr %10 %9 %12 +%182 = OpLogicalAnd %10 %9 %12 +%183 = OpLogicalOr %10 %9 %12 +%184 = OpCompositeConstruct %39 %9 %9 %9 +%185 = OpCompositeConstruct %39 %12 %12 %12 +%186 = OpLogicalOr %39 %184 %185 +%187 = OpLogicalAnd %10 %9 %12 +%188 = OpCompositeConstruct %36 %9 %9 %9 %9 +%189 = OpCompositeConstruct %36 %12 %12 %12 %12 +%190 = OpLogicalAnd %36 %188 %189 OpReturn OpFunctionEnd -%188 = OpFunction %2 None %171 -%187 = OpLabel -OpBranch %189 -%189 = OpLabel -%191 = OpCompositeConstruct %190 %7 %7 -%192 = OpSNegate %190 %191 -%193 = OpCompositeConstruct %37 %3 %3 -%194 = OpFNegate %37 %193 -%195 = OpIAdd %8 %18 %7 -%196 = OpIAdd %20 %24 %25 -%197 = OpFAdd %4 %14 %3 -%198 = OpCompositeConstruct %190 %18 %18 -%199 = OpCompositeConstruct %190 %7 %7 -%200 = OpIAdd %190 %198 %199 -%202 = OpCompositeConstruct %201 %24 %24 %24 -%203 = OpCompositeConstruct %201 %25 %25 %25 -%204 = OpIAdd %201 %202 %203 -%205 = OpCompositeConstruct %34 %14 %14 %14 %14 -%206 = OpCompositeConstruct %34 %3 %3 %3 %3 -%207 = OpFAdd %34 %205 %206 -%208 = OpISub %8 %18 %7 -%209 = OpISub %20 %24 %25 -%210 = OpFSub %4 %14 %3 -%211 = OpCompositeConstruct %190 %18 %18 -%212 = OpCompositeConstruct %190 %7 %7 -%213 = OpISub %190 %211 %212 -%214 = OpCompositeConstruct %201 %24 %24 %24 -%215 = OpCompositeConstruct %201 %25 %25 %25 -%216 = OpISub %201 %214 %215 -%217 = OpCompositeConstruct %34 %14 %14 %14 %14 -%218 = OpCompositeConstruct %34 %3 %3 %3 %3 -%219 = OpFSub %34 %217 %218 -%220 = OpIMul %8 %18 %7 -%221 = OpIMul %20 %24 %25 -%222 = OpFMul %4 %14 %3 -%223 = OpCompositeConstruct %190 %18 %18 -%224 = OpCompositeConstruct %190 %7 %7 -%225 = OpIMul %190 %223 %224 -%226 = OpCompositeConstruct %201 %24 %24 %24 -%227 = OpCompositeConstruct %201 %25 %25 %25 -%228 = OpIMul %201 %226 %227 -%229 = OpCompositeConstruct %34 %14 %14 %14 %14 -%230 = OpCompositeConstruct %34 %3 %3 %3 %3 -%231 = OpFMul %34 %229 %230 -%232 = OpSDiv %8 %18 %7 -%233 = OpUDiv %20 %24 %25 -%234 = OpFDiv %4 %14 %3 -%235 = OpCompositeConstruct %190 %18 %18 -%236 = OpCompositeConstruct %190 %7 %7 -%237 = OpSDiv %190 %235 %236 -%238 = OpCompositeConstruct %201 %24 %24 %24 -%239 = OpCompositeConstruct %201 %25 %25 %25 -%240 = OpUDiv %201 %238 %239 -%241 = OpCompositeConstruct %34 %14 %14 %14 %14 -%242 = OpCompositeConstruct %34 %3 %3 %3 %3 -%243 = OpFDiv %34 %241 %242 -%244 = OpSRem %8 %18 %7 -%245 = OpUMod %20 %24 %25 -%246 = OpFRem %4 %14 %3 -%247 = OpCompositeConstruct %190 %18 %18 -%248 = OpCompositeConstruct %190 %7 %7 -%249 = OpSRem %190 %247 %248 -%250 = OpCompositeConstruct %201 %24 %24 %24 -%251 = OpCompositeConstruct %201 %25 %25 %25 -%252 = OpUMod %201 %250 %251 -%253 = OpCompositeConstruct %34 %14 %14 %14 %14 -%254 = OpCompositeConstruct %34 %3 %3 %3 %3 -%255 = OpFRem %34 %253 %254 -%256 = OpCompositeConstruct %190 %18 %18 -%257 = OpCompositeConstruct %190 %7 %7 -%258 = OpIAdd %190 %256 %257 -%259 = OpCompositeConstruct %190 %7 %7 -%260 = OpCompositeConstruct %190 %18 %18 -%261 = OpIAdd %190 %260 %259 -%262 = OpCompositeConstruct %43 %24 %24 -%263 = OpCompositeConstruct %43 %25 %25 -%264 = OpIAdd %43 %262 %263 -%265 = OpCompositeConstruct %43 %25 %25 -%266 = OpCompositeConstruct %43 %24 %24 -%267 = OpIAdd %43 %266 %265 -%268 = OpCompositeConstruct %37 %14 %14 -%269 = OpCompositeConstruct %37 %3 %3 -%270 = OpFAdd %37 %268 %269 -%271 = OpCompositeConstruct %37 %3 %3 -%272 = OpCompositeConstruct %37 %14 %14 -%273 = OpFAdd %37 %272 %271 -%274 = OpCompositeConstruct %190 %18 %18 -%275 = OpCompositeConstruct %190 %7 %7 -%276 = OpISub %190 %274 %275 -%277 = OpCompositeConstruct %190 %7 %7 -%278 = OpCompositeConstruct %190 %18 %18 -%279 = OpISub %190 %278 %277 +%192 = OpFunction %2 None %175 +%191 = OpLabel +OpBranch %203 +%203 = OpLabel +%205 = OpCompositeConstruct %204 %7 %7 +%206 = OpSNegate %204 %205 +%207 = OpCompositeConstruct %37 %3 %3 +%208 = OpFNegate %37 %207 +%209 = OpIAdd %8 %18 %7 +%210 = OpIAdd %21 %24 %25 +%211 = OpFAdd %4 %14 %3 +%212 = OpCompositeConstruct %204 %18 %18 +%213 = OpCompositeConstruct %204 %7 %7 +%214 = OpIAdd %204 %212 %213 +%216 = OpCompositeConstruct %215 %24 %24 %24 +%217 = OpCompositeConstruct %215 %25 %25 %25 +%218 = OpIAdd %215 %216 %217 +%219 = OpCompositeConstruct %34 %14 %14 %14 %14 +%220 = OpCompositeConstruct %34 %3 %3 %3 %3 +%221 = OpFAdd %34 %219 %220 +%222 = OpISub %8 %18 %7 +%223 = OpISub %21 %24 %25 +%224 = OpFSub %4 %14 %3 +%225 = OpCompositeConstruct %204 %18 %18 +%226 = OpCompositeConstruct %204 %7 %7 +%227 = OpISub %204 %225 %226 +%228 = OpCompositeConstruct %215 %24 %24 %24 +%229 = OpCompositeConstruct %215 %25 %25 %25 +%230 = OpISub %215 %228 %229 +%231 = OpCompositeConstruct %34 %14 %14 %14 %14 +%232 = OpCompositeConstruct %34 %3 %3 %3 %3 +%233 = OpFSub %34 %231 %232 +%234 = OpIMul %8 %18 %7 +%235 = OpIMul %21 %24 %25 +%236 = OpFMul %4 %14 %3 +%237 = OpCompositeConstruct %204 %18 %18 +%238 = OpCompositeConstruct %204 %7 %7 +%239 = OpIMul %204 %237 %238 +%240 = OpCompositeConstruct %215 %24 %24 %24 +%241 = OpCompositeConstruct %215 %25 %25 %25 +%242 = OpIMul %215 %240 %241 +%243 = OpCompositeConstruct %34 %14 %14 %14 %14 +%244 = OpCompositeConstruct %34 %3 %3 %3 %3 +%245 = OpFMul %34 %243 %244 +%246 = OpSDiv %8 %18 %7 +%247 = OpUDiv %21 %24 %25 +%248 = OpFDiv %4 %14 %3 +%249 = OpCompositeConstruct %204 %18 %18 +%250 = OpCompositeConstruct %204 %7 %7 +%251 = OpSDiv %204 %249 %250 +%252 = OpCompositeConstruct %215 %24 %24 %24 +%253 = OpCompositeConstruct %215 %25 %25 %25 +%254 = OpUDiv %215 %252 %253 +%255 = OpCompositeConstruct %34 %14 %14 %14 %14 +%256 = OpCompositeConstruct %34 %3 %3 %3 %3 +%257 = OpFDiv %34 %255 %256 +%258 = OpSRem %8 %18 %7 +%259 = OpUMod %21 %24 %25 +%260 = OpFRem %4 %14 %3 +%261 = OpCompositeConstruct %204 %18 %18 +%262 = OpCompositeConstruct %204 %7 %7 +%263 = OpSRem %204 %261 %262 +%264 = OpCompositeConstruct %215 %24 %24 %24 +%265 = OpCompositeConstruct %215 %25 %25 %25 +%266 = OpUMod %215 %264 %265 +%267 = OpCompositeConstruct %34 %14 %14 %14 %14 +%268 = OpCompositeConstruct %34 %3 %3 %3 %3 +%269 = OpFRem %34 %267 %268 +%270 = OpCompositeConstruct %204 %18 %18 +%271 = OpCompositeConstruct %204 %7 %7 +%272 = OpIAdd %204 %270 %271 +%273 = OpCompositeConstruct %204 %7 %7 +%274 = OpCompositeConstruct %204 %18 %18 +%275 = OpIAdd %204 %274 %273 +%276 = OpCompositeConstruct %43 %24 %24 +%277 = OpCompositeConstruct %43 %25 %25 +%278 = OpIAdd %43 %276 %277 +%279 = OpCompositeConstruct %43 %25 %25 %280 = OpCompositeConstruct %43 %24 %24 -%281 = OpCompositeConstruct %43 %25 %25 -%282 = OpISub %43 %280 %281 -%283 = OpCompositeConstruct %43 %25 %25 -%284 = OpCompositeConstruct %43 %24 %24 -%285 = OpISub %43 %284 %283 +%281 = OpIAdd %43 %280 %279 +%282 = OpCompositeConstruct %37 %14 %14 +%283 = OpCompositeConstruct %37 %3 %3 +%284 = OpFAdd %37 %282 %283 +%285 = OpCompositeConstruct %37 %3 %3 %286 = OpCompositeConstruct %37 %14 %14 -%287 = OpCompositeConstruct %37 %3 %3 -%288 = OpFSub %37 %286 %287 -%289 = OpCompositeConstruct %37 %3 %3 -%290 = OpCompositeConstruct %37 %14 %14 -%291 = OpFSub %37 %290 %289 -%292 = OpCompositeConstruct %190 %18 %18 -%294 = OpCompositeConstruct %190 %7 %7 -%293 = OpIMul %190 %292 %294 -%295 = OpCompositeConstruct %190 %7 %7 -%297 = OpCompositeConstruct %190 %18 %18 -%296 = OpIMul %190 %295 %297 +%287 = OpFAdd %37 %286 %285 +%288 = OpCompositeConstruct %204 %18 %18 +%289 = OpCompositeConstruct %204 %7 %7 +%290 = OpISub %204 %288 %289 +%291 = OpCompositeConstruct %204 %7 %7 +%292 = OpCompositeConstruct %204 %18 %18 +%293 = OpISub %204 %292 %291 +%294 = OpCompositeConstruct %43 %24 %24 +%295 = OpCompositeConstruct %43 %25 %25 +%296 = OpISub %43 %294 %295 +%297 = OpCompositeConstruct %43 %25 %25 %298 = OpCompositeConstruct %43 %24 %24 -%300 = OpCompositeConstruct %43 %25 %25 -%299 = OpIMul %43 %298 %300 -%301 = OpCompositeConstruct %43 %25 %25 -%303 = OpCompositeConstruct %43 %24 %24 -%302 = OpIMul %43 %301 %303 +%299 = OpISub %43 %298 %297 +%300 = OpCompositeConstruct %37 %14 %14 +%301 = OpCompositeConstruct %37 %3 %3 +%302 = OpFSub %37 %300 %301 +%303 = OpCompositeConstruct %37 %3 %3 %304 = OpCompositeConstruct %37 %14 %14 -%305 = OpVectorTimesScalar %37 %304 %3 -%306 = OpCompositeConstruct %37 %3 %3 -%307 = OpVectorTimesScalar %37 %306 %14 -%308 = OpCompositeConstruct %190 %18 %18 -%309 = OpCompositeConstruct %190 %7 %7 -%310 = OpSDiv %190 %308 %309 -%311 = OpCompositeConstruct %190 %7 %7 -%312 = OpCompositeConstruct %190 %18 %18 -%313 = OpSDiv %190 %312 %311 -%314 = OpCompositeConstruct %43 %24 %24 +%305 = OpFSub %37 %304 %303 +%306 = OpCompositeConstruct %204 %18 %18 +%308 = OpCompositeConstruct %204 %7 %7 +%307 = OpIMul %204 %306 %308 +%309 = OpCompositeConstruct %204 %7 %7 +%311 = OpCompositeConstruct %204 %18 %18 +%310 = OpIMul %204 %309 %311 +%312 = OpCompositeConstruct %43 %24 %24 +%314 = OpCompositeConstruct %43 %25 %25 +%313 = OpIMul %43 %312 %314 %315 = OpCompositeConstruct %43 %25 %25 -%316 = OpUDiv %43 %314 %315 -%317 = OpCompositeConstruct %43 %25 %25 -%318 = OpCompositeConstruct %43 %24 %24 -%319 = OpUDiv %43 %318 %317 -%320 = OpCompositeConstruct %37 %14 %14 -%321 = OpCompositeConstruct %37 %3 %3 -%322 = OpFDiv %37 %320 %321 -%323 = OpCompositeConstruct %37 %3 %3 -%324 = OpCompositeConstruct %37 %14 %14 -%325 = OpFDiv %37 %324 %323 -%326 = OpCompositeConstruct %190 %18 %18 -%327 = OpCompositeConstruct %190 %7 %7 -%328 = OpSRem %190 %326 %327 -%329 = OpCompositeConstruct %190 %7 %7 -%330 = OpCompositeConstruct %190 %18 %18 -%331 = OpSRem %190 %330 %329 +%317 = OpCompositeConstruct %43 %24 %24 +%316 = OpIMul %43 %315 %317 +%318 = OpCompositeConstruct %37 %14 %14 +%319 = OpVectorTimesScalar %37 %318 %3 +%320 = OpCompositeConstruct %37 %3 %3 +%321 = OpVectorTimesScalar %37 %320 %14 +%322 = OpCompositeConstruct %204 %18 %18 +%323 = OpCompositeConstruct %204 %7 %7 +%324 = OpSDiv %204 %322 %323 +%325 = OpCompositeConstruct %204 %7 %7 +%326 = OpCompositeConstruct %204 %18 %18 +%327 = OpSDiv %204 %326 %325 +%328 = OpCompositeConstruct %43 %24 %24 +%329 = OpCompositeConstruct %43 %25 %25 +%330 = OpUDiv %43 %328 %329 +%331 = OpCompositeConstruct %43 %25 %25 %332 = OpCompositeConstruct %43 %24 %24 -%333 = OpCompositeConstruct %43 %25 %25 -%334 = OpUMod %43 %332 %333 -%335 = OpCompositeConstruct %43 %25 %25 -%336 = OpCompositeConstruct %43 %24 %24 -%337 = OpUMod %43 %336 %335 +%333 = OpUDiv %43 %332 %331 +%334 = OpCompositeConstruct %37 %14 %14 +%335 = OpCompositeConstruct %37 %3 %3 +%336 = OpFDiv %37 %334 %335 +%337 = OpCompositeConstruct %37 %3 %3 %338 = OpCompositeConstruct %37 %14 %14 -%339 = OpCompositeConstruct %37 %3 %3 -%340 = OpFRem %37 %338 %339 -%341 = OpCompositeConstruct %37 %3 %3 -%342 = OpCompositeConstruct %37 %14 %14 -%343 = OpFRem %37 %342 %341 -%345 = OpCompositeExtract %38 %63 0 -%346 = OpCompositeExtract %38 %63 0 -%347 = OpFAdd %38 %345 %346 -%348 = OpCompositeExtract %38 %63 1 -%349 = OpCompositeExtract %38 %63 1 -%350 = OpFAdd %38 %348 %349 -%351 = OpCompositeExtract %38 %63 2 -%352 = OpCompositeExtract %38 %63 2 -%353 = OpFAdd %38 %351 %352 -%344 = OpCompositeConstruct %47 %347 %350 %353 -%355 = OpCompositeExtract %38 %63 0 -%356 = OpCompositeExtract %38 %63 0 -%357 = OpFSub %38 %355 %356 -%358 = OpCompositeExtract %38 %63 1 -%359 = OpCompositeExtract %38 %63 1 -%360 = OpFSub %38 %358 %359 -%361 = OpCompositeExtract %38 %63 2 -%362 = OpCompositeExtract %38 %63 2 -%363 = OpFSub %38 %361 %362 -%354 = OpCompositeConstruct %47 %357 %360 %363 -%364 = OpMatrixTimesScalar %47 %63 %3 -%365 = OpMatrixTimesScalar %47 %63 %14 -%366 = OpCompositeConstruct %34 %3 %3 %3 %3 -%367 = OpMatrixTimesVector %38 %64 %366 -%368 = OpCompositeConstruct %38 %14 %14 %14 -%369 = OpVectorTimesMatrix %34 %368 %64 -%370 = OpMatrixTimesMatrix %47 %64 %65 +%339 = OpFDiv %37 %338 %337 +%340 = OpCompositeConstruct %204 %18 %18 +%341 = OpCompositeConstruct %204 %7 %7 +%342 = OpSRem %204 %340 %341 +%343 = OpCompositeConstruct %204 %7 %7 +%344 = OpCompositeConstruct %204 %18 %18 +%345 = OpSRem %204 %344 %343 +%346 = OpCompositeConstruct %43 %24 %24 +%347 = OpCompositeConstruct %43 %25 %25 +%348 = OpUMod %43 %346 %347 +%349 = OpCompositeConstruct %43 %25 %25 +%350 = OpCompositeConstruct %43 %24 %24 +%351 = OpUMod %43 %350 %349 +%352 = OpCompositeConstruct %37 %14 %14 +%353 = OpCompositeConstruct %37 %3 %3 +%354 = OpFRem %37 %352 %353 +%355 = OpCompositeConstruct %37 %3 %3 +%356 = OpCompositeConstruct %37 %14 %14 +%357 = OpFRem %37 %356 %355 +%359 = OpCompositeExtract %38 %193 0 +%360 = OpCompositeExtract %38 %194 0 +%361 = OpFAdd %38 %359 %360 +%362 = OpCompositeExtract %38 %193 1 +%363 = OpCompositeExtract %38 %194 1 +%364 = OpFAdd %38 %362 %363 +%365 = OpCompositeExtract %38 %193 2 +%366 = OpCompositeExtract %38 %194 2 +%367 = OpFAdd %38 %365 %366 +%358 = OpCompositeConstruct %47 %361 %364 %367 +%369 = OpCompositeExtract %38 %195 0 +%370 = OpCompositeExtract %38 %196 0 +%371 = OpFSub %38 %369 %370 +%372 = OpCompositeExtract %38 %195 1 +%373 = OpCompositeExtract %38 %196 1 +%374 = OpFSub %38 %372 %373 +%375 = OpCompositeExtract %38 %195 2 +%376 = OpCompositeExtract %38 %196 2 +%377 = OpFSub %38 %375 %376 +%368 = OpCompositeConstruct %47 %371 %374 %377 +%378 = OpMatrixTimesScalar %47 %197 %3 +%379 = OpMatrixTimesScalar %47 %198 %14 +%380 = OpCompositeConstruct %34 %3 %3 %3 %3 +%381 = OpMatrixTimesVector %38 %199 %380 +%382 = OpCompositeConstruct %38 %14 %14 %14 +%383 = OpVectorTimesMatrix %34 %382 %200 +%384 = OpMatrixTimesMatrix %47 %201 %202 OpReturn OpFunctionEnd -%372 = OpFunction %2 None %171 -%371 = OpLabel -OpBranch %373 -%373 = OpLabel -%374 = OpNot %8 %7 -%375 = OpNot %20 %25 -%376 = OpCompositeConstruct %190 %7 %7 -%377 = OpNot %190 %376 -%378 = OpCompositeConstruct %201 %25 %25 %25 -%379 = OpNot %201 %378 -%380 = OpBitwiseOr %8 %18 %7 -%381 = OpBitwiseOr %20 %24 %25 -%382 = OpCompositeConstruct %190 %18 %18 -%383 = OpCompositeConstruct %190 %7 %7 -%384 = OpBitwiseOr %190 %382 %383 -%385 = OpCompositeConstruct %201 %24 %24 %24 -%386 = OpCompositeConstruct %201 %25 %25 %25 -%387 = OpBitwiseOr %201 %385 %386 -%388 = OpBitwiseAnd %8 %18 %7 -%389 = OpBitwiseAnd %20 %24 %25 -%390 = OpCompositeConstruct %190 %18 %18 -%391 = OpCompositeConstruct %190 %7 %7 -%392 = OpBitwiseAnd %190 %390 %391 -%393 = OpCompositeConstruct %201 %24 %24 %24 -%394 = OpCompositeConstruct %201 %25 %25 %25 -%395 = OpBitwiseAnd %201 %393 %394 -%396 = OpBitwiseXor %8 %18 %7 -%397 = OpBitwiseXor %20 %24 %25 -%398 = OpCompositeConstruct %190 %18 %18 -%399 = OpCompositeConstruct %190 %7 %7 -%400 = OpBitwiseXor %190 %398 %399 -%401 = OpCompositeConstruct %201 %24 %24 %24 -%402 = OpCompositeConstruct %201 %25 %25 %25 -%403 = OpBitwiseXor %201 %401 %402 -%404 = OpShiftLeftLogical %8 %18 %25 -%405 = OpShiftLeftLogical %20 %24 %25 -%406 = OpCompositeConstruct %190 %18 %18 -%407 = OpCompositeConstruct %43 %25 %25 -%408 = OpShiftLeftLogical %190 %406 %407 -%409 = OpCompositeConstruct %201 %24 %24 %24 -%410 = OpCompositeConstruct %201 %25 %25 %25 -%411 = OpShiftLeftLogical %201 %409 %410 -%412 = OpShiftRightArithmetic %8 %18 %25 -%413 = OpShiftRightLogical %20 %24 %25 -%414 = OpCompositeConstruct %190 %18 %18 -%415 = OpCompositeConstruct %43 %25 %25 -%416 = OpShiftRightArithmetic %190 %414 %415 -%417 = OpCompositeConstruct %201 %24 %24 %24 -%418 = OpCompositeConstruct %201 %25 %25 %25 -%419 = OpShiftRightLogical %201 %417 %418 +%386 = OpFunction %2 None %175 +%385 = OpLabel +OpBranch %387 +%387 = OpLabel +%388 = OpNot %8 %7 +%389 = OpNot %21 %25 +%390 = OpCompositeConstruct %204 %7 %7 +%391 = OpNot %204 %390 +%392 = OpCompositeConstruct %215 %25 %25 %25 +%393 = OpNot %215 %392 +%394 = OpBitwiseOr %8 %18 %7 +%395 = OpBitwiseOr %21 %24 %25 +%396 = OpCompositeConstruct %204 %18 %18 +%397 = OpCompositeConstruct %204 %7 %7 +%398 = OpBitwiseOr %204 %396 %397 +%399 = OpCompositeConstruct %215 %24 %24 %24 +%400 = OpCompositeConstruct %215 %25 %25 %25 +%401 = OpBitwiseOr %215 %399 %400 +%402 = OpBitwiseAnd %8 %18 %7 +%403 = OpBitwiseAnd %21 %24 %25 +%404 = OpCompositeConstruct %204 %18 %18 +%405 = OpCompositeConstruct %204 %7 %7 +%406 = OpBitwiseAnd %204 %404 %405 +%407 = OpCompositeConstruct %215 %24 %24 %24 +%408 = OpCompositeConstruct %215 %25 %25 %25 +%409 = OpBitwiseAnd %215 %407 %408 +%410 = OpBitwiseXor %8 %18 %7 +%411 = OpBitwiseXor %21 %24 %25 +%412 = OpCompositeConstruct %204 %18 %18 +%413 = OpCompositeConstruct %204 %7 %7 +%414 = OpBitwiseXor %204 %412 %413 +%415 = OpCompositeConstruct %215 %24 %24 %24 +%416 = OpCompositeConstruct %215 %25 %25 %25 +%417 = OpBitwiseXor %215 %415 %416 +%418 = OpShiftLeftLogical %8 %18 %25 +%419 = OpShiftLeftLogical %21 %24 %25 +%420 = OpCompositeConstruct %204 %18 %18 +%421 = OpCompositeConstruct %43 %25 %25 +%422 = OpShiftLeftLogical %204 %420 %421 +%423 = OpCompositeConstruct %215 %24 %24 %24 +%424 = OpCompositeConstruct %215 %25 %25 %25 +%425 = OpShiftLeftLogical %215 %423 %424 +%426 = OpShiftRightArithmetic %8 %18 %25 +%427 = OpShiftRightLogical %21 %24 %25 +%428 = OpCompositeConstruct %204 %18 %18 +%429 = OpCompositeConstruct %43 %25 %25 +%430 = OpShiftRightArithmetic %204 %428 %429 +%431 = OpCompositeConstruct %215 %24 %24 %24 +%432 = OpCompositeConstruct %215 %25 %25 %25 +%433 = OpShiftRightLogical %215 %431 %432 OpReturn OpFunctionEnd -%421 = OpFunction %2 None %171 -%420 = OpLabel -OpBranch %422 -%422 = OpLabel -%423 = OpIEqual %10 %18 %7 -%424 = OpIEqual %10 %24 %25 -%425 = OpFOrdEqual %10 %14 %3 -%426 = OpCompositeConstruct %190 %18 %18 -%427 = OpCompositeConstruct %190 %7 %7 -%428 = OpIEqual %174 %426 %427 -%429 = OpCompositeConstruct %201 %24 %24 %24 -%430 = OpCompositeConstruct %201 %25 %25 %25 -%431 = OpIEqual %39 %429 %430 -%432 = OpCompositeConstruct %34 %14 %14 %14 %14 -%433 = OpCompositeConstruct %34 %3 %3 %3 %3 -%434 = OpFOrdEqual %36 %432 %433 -%435 = OpINotEqual %10 %18 %7 -%436 = OpINotEqual %10 %24 %25 -%437 = OpFOrdNotEqual %10 %14 %3 -%438 = OpCompositeConstruct %190 %18 %18 -%439 = OpCompositeConstruct %190 %7 %7 -%440 = OpINotEqual %174 %438 %439 -%441 = OpCompositeConstruct %201 %24 %24 %24 -%442 = OpCompositeConstruct %201 %25 %25 %25 -%443 = OpINotEqual %39 %441 %442 -%444 = OpCompositeConstruct %34 %14 %14 %14 %14 -%445 = OpCompositeConstruct %34 %3 %3 %3 %3 -%446 = OpFOrdNotEqual %36 %444 %445 -%447 = OpSLessThan %10 %18 %7 -%448 = OpULessThan %10 %24 %25 -%449 = OpFOrdLessThan %10 %14 %3 -%450 = OpCompositeConstruct %190 %18 %18 -%451 = OpCompositeConstruct %190 %7 %7 -%452 = OpSLessThan %174 %450 %451 -%453 = OpCompositeConstruct %201 %24 %24 %24 -%454 = OpCompositeConstruct %201 %25 %25 %25 -%455 = OpULessThan %39 %453 %454 -%456 = OpCompositeConstruct %34 %14 %14 %14 %14 -%457 = OpCompositeConstruct %34 %3 %3 %3 %3 -%458 = OpFOrdLessThan %36 %456 %457 -%459 = OpSLessThanEqual %10 %18 %7 -%460 = OpULessThanEqual %10 %24 %25 -%461 = OpFOrdLessThanEqual %10 %14 %3 -%462 = OpCompositeConstruct %190 %18 %18 -%463 = OpCompositeConstruct %190 %7 %7 -%464 = OpSLessThanEqual %174 %462 %463 -%465 = OpCompositeConstruct %201 %24 %24 %24 -%466 = OpCompositeConstruct %201 %25 %25 %25 -%467 = OpULessThanEqual %39 %465 %466 -%468 = OpCompositeConstruct %34 %14 %14 %14 %14 -%469 = OpCompositeConstruct %34 %3 %3 %3 %3 -%470 = OpFOrdLessThanEqual %36 %468 %469 -%471 = OpSGreaterThan %10 %18 %7 -%472 = OpUGreaterThan %10 %24 %25 -%473 = OpFOrdGreaterThan %10 %14 %3 -%474 = OpCompositeConstruct %190 %18 %18 -%475 = OpCompositeConstruct %190 %7 %7 -%476 = OpSGreaterThan %174 %474 %475 -%477 = OpCompositeConstruct %201 %24 %24 %24 -%478 = OpCompositeConstruct %201 %25 %25 %25 -%479 = OpUGreaterThan %39 %477 %478 -%480 = OpCompositeConstruct %34 %14 %14 %14 %14 -%481 = OpCompositeConstruct %34 %3 %3 %3 %3 -%482 = OpFOrdGreaterThan %36 %480 %481 -%483 = OpSGreaterThanEqual %10 %18 %7 -%484 = OpUGreaterThanEqual %10 %24 %25 -%485 = OpFOrdGreaterThanEqual %10 %14 %3 -%486 = OpCompositeConstruct %190 %18 %18 -%487 = OpCompositeConstruct %190 %7 %7 -%488 = OpSGreaterThanEqual %174 %486 %487 -%489 = OpCompositeConstruct %201 %24 %24 %24 -%490 = OpCompositeConstruct %201 %25 %25 %25 -%491 = OpUGreaterThanEqual %39 %489 %490 -%492 = OpCompositeConstruct %34 %14 %14 %14 %14 -%493 = OpCompositeConstruct %34 %3 %3 %3 %3 -%494 = OpFOrdGreaterThanEqual %36 %492 %493 +%435 = OpFunction %2 None %175 +%434 = OpLabel +OpBranch %436 +%436 = OpLabel +%437 = OpIEqual %10 %18 %7 +%438 = OpIEqual %10 %24 %25 +%439 = OpFOrdEqual %10 %14 %3 +%440 = OpCompositeConstruct %204 %18 %18 +%441 = OpCompositeConstruct %204 %7 %7 +%442 = OpIEqual %178 %440 %441 +%443 = OpCompositeConstruct %215 %24 %24 %24 +%444 = OpCompositeConstruct %215 %25 %25 %25 +%445 = OpIEqual %39 %443 %444 +%446 = OpCompositeConstruct %34 %14 %14 %14 %14 +%447 = OpCompositeConstruct %34 %3 %3 %3 %3 +%448 = OpFOrdEqual %36 %446 %447 +%449 = OpINotEqual %10 %18 %7 +%450 = OpINotEqual %10 %24 %25 +%451 = OpFOrdNotEqual %10 %14 %3 +%452 = OpCompositeConstruct %204 %18 %18 +%453 = OpCompositeConstruct %204 %7 %7 +%454 = OpINotEqual %178 %452 %453 +%455 = OpCompositeConstruct %215 %24 %24 %24 +%456 = OpCompositeConstruct %215 %25 %25 %25 +%457 = OpINotEqual %39 %455 %456 +%458 = OpCompositeConstruct %34 %14 %14 %14 %14 +%459 = OpCompositeConstruct %34 %3 %3 %3 %3 +%460 = OpFOrdNotEqual %36 %458 %459 +%461 = OpSLessThan %10 %18 %7 +%462 = OpULessThan %10 %24 %25 +%463 = OpFOrdLessThan %10 %14 %3 +%464 = OpCompositeConstruct %204 %18 %18 +%465 = OpCompositeConstruct %204 %7 %7 +%466 = OpSLessThan %178 %464 %465 +%467 = OpCompositeConstruct %215 %24 %24 %24 +%468 = OpCompositeConstruct %215 %25 %25 %25 +%469 = OpULessThan %39 %467 %468 +%470 = OpCompositeConstruct %34 %14 %14 %14 %14 +%471 = OpCompositeConstruct %34 %3 %3 %3 %3 +%472 = OpFOrdLessThan %36 %470 %471 +%473 = OpSLessThanEqual %10 %18 %7 +%474 = OpULessThanEqual %10 %24 %25 +%475 = OpFOrdLessThanEqual %10 %14 %3 +%476 = OpCompositeConstruct %204 %18 %18 +%477 = OpCompositeConstruct %204 %7 %7 +%478 = OpSLessThanEqual %178 %476 %477 +%479 = OpCompositeConstruct %215 %24 %24 %24 +%480 = OpCompositeConstruct %215 %25 %25 %25 +%481 = OpULessThanEqual %39 %479 %480 +%482 = OpCompositeConstruct %34 %14 %14 %14 %14 +%483 = OpCompositeConstruct %34 %3 %3 %3 %3 +%484 = OpFOrdLessThanEqual %36 %482 %483 +%485 = OpSGreaterThan %10 %18 %7 +%486 = OpUGreaterThan %10 %24 %25 +%487 = OpFOrdGreaterThan %10 %14 %3 +%488 = OpCompositeConstruct %204 %18 %18 +%489 = OpCompositeConstruct %204 %7 %7 +%490 = OpSGreaterThan %178 %488 %489 +%491 = OpCompositeConstruct %215 %24 %24 %24 +%492 = OpCompositeConstruct %215 %25 %25 %25 +%493 = OpUGreaterThan %39 %491 %492 +%494 = OpCompositeConstruct %34 %14 %14 %14 %14 +%495 = OpCompositeConstruct %34 %3 %3 %3 %3 +%496 = OpFOrdGreaterThan %36 %494 %495 +%497 = OpSGreaterThanEqual %10 %18 %7 +%498 = OpUGreaterThanEqual %10 %24 %25 +%499 = OpFOrdGreaterThanEqual %10 %14 %3 +%500 = OpCompositeConstruct %204 %18 %18 +%501 = OpCompositeConstruct %204 %7 %7 +%502 = OpSGreaterThanEqual %178 %500 %501 +%503 = OpCompositeConstruct %215 %24 %24 %24 +%504 = OpCompositeConstruct %215 %25 %25 %25 +%505 = OpUGreaterThanEqual %39 %503 %504 +%506 = OpCompositeConstruct %34 %14 %14 %14 %14 +%507 = OpCompositeConstruct %34 %3 %3 %3 %3 +%508 = OpFOrdGreaterThanEqual %36 %506 %507 OpReturn OpFunctionEnd -%502 = OpFunction %2 None %171 -%501 = OpLabel -%495 = OpVariable %496 Function %497 -%498 = OpVariable %499 Function %500 -OpBranch %503 -%503 = OpLabel -OpStore %495 %7 -%504 = OpLoad %8 %495 -%505 = OpIAdd %8 %504 %7 -OpStore %495 %505 -%506 = OpLoad %8 %495 -%507 = OpISub %8 %506 %7 -OpStore %495 %507 -%508 = OpLoad %8 %495 -%509 = OpLoad %8 %495 -%510 = OpIMul %8 %509 %508 -OpStore %495 %510 -%511 = OpLoad %8 %495 -%512 = OpLoad %8 %495 -%513 = OpSDiv %8 %512 %511 -OpStore %495 %513 -%514 = OpLoad %8 %495 -%515 = OpSRem %8 %514 %7 -OpStore %495 %515 -%516 = OpLoad %8 %495 -%517 = OpBitwiseAnd %8 %516 %11 -OpStore %495 %517 -%518 = OpLoad %8 %495 -%519 = OpBitwiseOr %8 %518 %11 -OpStore %495 %519 -%520 = OpLoad %8 %495 -%521 = OpBitwiseXor %8 %520 %11 -OpStore %495 %521 -%522 = OpLoad %8 %495 -%523 = OpShiftLeftLogical %8 %522 %24 -OpStore %495 %523 -%524 = OpLoad %8 %495 -%525 = OpShiftRightArithmetic %8 %524 %25 -OpStore %495 %525 -%526 = OpLoad %8 %495 -%527 = OpIAdd %8 %526 %7 -OpStore %495 %527 -%528 = OpLoad %8 %495 -%529 = OpISub %8 %528 %7 -OpStore %495 %529 -OpStore %498 %66 -%531 = OpAccessChain %530 %498 %25 -%532 = OpLoad %8 %531 -%533 = OpIAdd %8 %532 %7 -%534 = OpAccessChain %530 %498 %25 -OpStore %534 %533 -%535 = OpAccessChain %530 %498 %25 -%536 = OpLoad %8 %535 -%537 = OpISub %8 %536 %7 -%538 = OpAccessChain %530 %498 %25 -OpStore %538 %537 +%516 = OpFunction %2 None %175 +%515 = OpLabel +%509 = OpVariable %510 Function %511 +%512 = OpVariable %513 Function %514 +OpBranch %518 +%518 = OpLabel +OpStore %509 %7 +%519 = OpLoad %8 %509 +%520 = OpIAdd %8 %519 %7 +OpStore %509 %520 +%521 = OpLoad %8 %509 +%522 = OpISub %8 %521 %7 +OpStore %509 %522 +%523 = OpLoad %8 %509 +%524 = OpLoad %8 %509 +%525 = OpIMul %8 %524 %523 +OpStore %509 %525 +%526 = OpLoad %8 %509 +%527 = OpLoad %8 %509 +%528 = OpSDiv %8 %527 %526 +OpStore %509 %528 +%529 = OpLoad %8 %509 +%530 = OpSRem %8 %529 %7 +OpStore %509 %530 +%531 = OpLoad %8 %509 +%532 = OpBitwiseAnd %8 %531 %11 +OpStore %509 %532 +%533 = OpLoad %8 %509 +%534 = OpBitwiseOr %8 %533 %11 +OpStore %509 %534 +%535 = OpLoad %8 %509 +%536 = OpBitwiseXor %8 %535 %11 +OpStore %509 %536 +%537 = OpLoad %8 %509 +%538 = OpShiftLeftLogical %8 %537 %24 +OpStore %509 %538 +%539 = OpLoad %8 %509 +%540 = OpShiftRightArithmetic %8 %539 %25 +OpStore %509 %540 +%541 = OpLoad %8 %509 +%542 = OpIAdd %8 %541 %7 +OpStore %509 %542 +%543 = OpLoad %8 %509 +%544 = OpISub %8 %543 %7 +OpStore %509 %544 +OpStore %512 %517 +%546 = OpAccessChain %545 %512 %25 +%547 = OpLoad %8 %546 +%548 = OpIAdd %8 %547 %7 +%549 = OpAccessChain %545 %512 %25 +OpStore %549 %548 +%550 = OpAccessChain %545 %512 %25 +%551 = OpLoad %8 %550 +%552 = OpISub %8 %551 %7 +%553 = OpAccessChain %545 %512 %25 +OpStore %553 %552 OpReturn OpFunctionEnd -%540 = OpFunction %2 None %171 -%539 = OpLabel -OpBranch %541 -%541 = OpLabel -%542 = OpSNegate %8 %27 -%543 = OpSNegate %8 %28 -%544 = OpSNegate %8 %29 -%545 = OpSNegate %8 %544 -%546 = OpSNegate %8 %30 -%547 = OpSNegate %8 %546 -%548 = OpSNegate %8 %31 -%549 = OpSNegate %8 %548 -%550 = OpSNegate %8 %549 -%551 = OpSNegate %8 %550 -%552 = OpSNegate %8 %32 -%553 = OpSNegate %8 %552 -%554 = OpSNegate %8 %553 -%555 = OpSNegate %8 %554 -%556 = OpSNegate %8 %33 -%557 = OpSNegate %8 %556 -%558 = OpSNegate %8 %557 -%559 = OpSNegate %8 %558 +%555 = OpFunction %2 None %175 +%554 = OpLabel +OpBranch %556 +%556 = OpLabel +%557 = OpSNegate %8 %27 +%558 = OpSNegate %8 %28 +%559 = OpSNegate %8 %29 +%560 = OpSNegate %8 %559 +%561 = OpSNegate %8 %30 +%562 = OpSNegate %8 %561 +%563 = OpSNegate %8 %31 +%564 = OpSNegate %8 %563 +%565 = OpSNegate %8 %564 +%566 = OpSNegate %8 %565 +%567 = OpSNegate %8 %32 +%568 = OpSNegate %8 %567 +%569 = OpSNegate %8 %568 +%570 = OpSNegate %8 %569 +%571 = OpSNegate %8 %33 +%572 = OpSNegate %8 %571 +%573 = OpSNegate %8 %572 +%574 = OpSNegate %8 %573 OpReturn OpFunctionEnd -%561 = OpFunction %2 None %171 -%560 = OpLabel -OpBranch %562 -%562 = OpLabel -%563 = OpFunctionCall %34 %68 -%564 = OpFunctionCall %34 %93 -%565 = OpVectorShuffle %38 %51 %51 0 1 2 -%566 = OpFunctionCall %38 %128 %565 -%567 = OpFunctionCall %4 %139 -%568 = OpFunctionCall %2 %170 -%569 = OpFunctionCall %2 %188 -%570 = OpFunctionCall %2 %372 -%571 = OpFunctionCall %2 %421 -%572 = OpFunctionCall %2 %502 +%576 = OpFunction %2 None %175 +%575 = OpLabel +OpBranch %577 +%577 = OpLabel +%578 = OpFunctionCall %34 %56 +%579 = OpFunctionCall %34 %81 +%580 = OpVectorShuffle %38 %51 %51 0 1 2 +%581 = OpFunctionCall %38 %116 %580 +%582 = OpFunctionCall %4 %127 +%583 = OpFunctionCall %2 %174 +%584 = OpFunctionCall %2 %192 +%585 = OpFunctionCall %2 %386 +%586 = OpFunctionCall %2 %435 +%587 = OpFunctionCall %2 %516 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 0bbd1a775..f82521a75 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -93,10 +93,10 @@ fn test_matrix_within_array_within_struct_accesses() { let _e58 = idx_1; let _e60 = idx_1; _ = nested_mat_cx2_.am[0][_e58][_e60]; - t_1 = MatCx2InArray(array,2>(mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)))); + t_1 = MatCx2InArray(array,2>()); let _e66 = idx_1; idx_1 = (_e66 + 1); - t_1.am = array,2>(mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0)), mat4x2(vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 0.0))); + t_1.am = array,2>(); t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); t_1.am[0][0] = vec2(9.0); let _e93 = idx_1; @@ -151,7 +151,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { c2_ = array(a_1, i32(b), 3, 4, 5); c2_[(vi + 1u)] = 42; let value = c2_[vi]; - let _e48 = test_arr_as_arg(array,5>(array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + let _e48 = test_arr_as_arg(array,5>()); return vec4((_matrix * vec4(vec4(value))), 2.0); } @@ -161,7 +161,7 @@ fn foo_frag() -> @location(0) vec4 { bar._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); bar.arr = array,2>(vec2(0u), vec2(1u)); bar.data[1].value = 1; - qux = vec2(0, 0); + qux = vec2(); return vec4(0.0); } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index d961db81b..3ce0be881 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -39,8 +39,8 @@ fn test_msl_packed_vec3_() { _ = data.v3_; _ = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); - _ = (data.v3_ * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - _ = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * data.v3_); + _ = (data.v3_ * mat3x3()); + _ = (mat3x3() * data.v3_); _ = (data.v3_ * 2.0); _ = (2.0 * data.v3_); } diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index acd925ac9..5faccba7b 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -7,7 +7,7 @@ fn main() { let d = radians(v); let e = saturate(v); let g = refract(v, v, 1.0); - let const_dot = dot(vec2(0, 0), vec2(0, 0)); + let const_dot = dot(vec2(), vec2()); let first_leading_bit_abs = firstLeadingBit(abs(0u)); let flb_a = firstLeadingBit(-1); let flb_b = firstLeadingBit(vec2(-1)); diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 487704927..11e7fd92d 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -53,14 +53,14 @@ fn constructors() -> f32 { _ = vec2(0u); _ = mat2x2(vec2(0.0), vec2(0.0)); _ = array(0, 1, 2, 3); - _ = bool(false); - _ = i32(0); - _ = u32(0u); - _ = f32(0.0); - _ = vec2(vec2(0u, 0u)); - _ = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - _ = bitcast>(vec2(0u, 0u)); - _ = mat2x3(mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); + _ = bool(bool()); + _ = i32(i32()); + _ = u32(u32()); + _ = f32(f32()); + _ = vec2(vec2()); + _ = mat2x3(mat2x3()); + _ = bitcast>(vec2()); + _ = mat2x3(mat2x3()); let _e71 = foo.a.x; return _e71; } @@ -139,13 +139,13 @@ fn arithmetic() { _ = (vec2(2u) % vec2(1u)); _ = (vec2(2.0) % vec2(1.0)); _ = (vec2(2.0) % vec2(1.0)); - _ = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) + mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - _ = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) - mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - _ = (mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * 1.0); - _ = (2.0 * mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - _ = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * vec4(1.0)); - _ = (vec3(2.0) * mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0))); - _ = (mat4x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)) * mat3x4(vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(0.0, 0.0, 0.0, 0.0))); + _ = (mat3x3() + mat3x3()); + _ = (mat3x3() - mat3x3()); + _ = (mat3x3() * 1.0); + _ = (2.0 * mat3x3()); + _ = (mat4x3() * vec4(1.0)); + _ = (vec3(2.0) * mat4x3()); + _ = (mat4x3() * mat3x4()); } fn bit() { @@ -245,7 +245,7 @@ fn assignment() { a_1 = (_e32 + 1); let _e35 = a_1; a_1 = (_e35 - 1); - vec0_ = vec3(0, 0, 0); + vec0_ = vec3(); let _e42 = vec0_.y; vec0_.y = (_e42 + 1); let _e47 = vec0_.y; From 02ddf6532c4befd90444188979e1a595b459bfe4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 9 May 2023 18:16:01 -0700 Subject: [PATCH 1993/2212] Introduce `Expression::Literal`. --- src/back/dot/mod.rs | 1 + src/back/glsl/mod.rs | 15 ++++++ src/back/hlsl/writer.rs | 9 ++++ src/back/msl/writer.rs | 25 +++++++++ src/back/spv/block.rs | 84 +++++++++++++------------------ src/back/spv/image.rs | 4 +- src/back/spv/instructions.rs | 8 +++ src/back/spv/mod.rs | 14 ++---- src/back/spv/ray.rs | 9 ++-- src/back/spv/writer.rs | 93 ++++++++++++---------------------- src/back/wgsl/writer.rs | 13 +++++ src/front/glsl/constants.rs | 13 +++++ src/lib.rs | 19 ++++++- src/proc/mod.rs | 98 +++++++++++++++++++++++++++++++++++- src/proc/typifier.rs | 1 + src/valid/analyzer.rs | 3 +- src/valid/expression.rs | 1 + src/valid/handles.rs | 1 + 18 files changed, 280 insertions(+), 131 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 8667cd725..1494e9a82 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -397,6 +397,7 @@ fn write_function_expressions( for (handle, expression) in fun.expressions.iter() { use crate::Expression as E; let (label, color_id) = match *expression { + E::Literal(_) => ("Literal".into(), 2), E::Constant(_) => ("Constant".into(), 2), E::ZeroValue(_) => ("ZeroValue".into(), 2), E::Access { base, index } => { diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 030dba4e6..ad76705b8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2270,6 +2270,21 @@ impl<'a, W: Write> Writer<'a, W> { Expression::ZeroValue(ty) => { self.write_zero_init_value(ty)?; } + Expression::Literal(literal) => { + match literal { + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero which is needed for a valid glsl float constant + crate::Literal::F64(value) => write!(self.out, "{:?}LF", value)?, + crate::Literal::F32(value) => write!(self.out, "{:?}", value)?, + // Unsigned integers need a `u` at the end + // + // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we + // always write it as the extra branch wouldn't have any benefit in readability + crate::Literal::U32(value) => write!(self.out, "{}u", value)?, + crate::Literal::I32(value) => write!(self.out, "{}", value)?, + crate::Literal::Bool(value) => write!(self.out, "{}", value)?, + } + } // `Splat` needs to actually write down a vector, it's not always inferred in GLSL. Expression::Splat { size: _, value } => { let resolved = ctx.info[expr].ty.inner_with(&self.module.types); diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index c5bda6607..3d0ed9cd3 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2058,6 +2058,15 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *expression { Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::ZeroValue(ty) => self.write_default_init(module, ty)?, + Expression::Literal(literal) => match literal { + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero + crate::Literal::F64(value) => write!(self.out, "{value:?}L")?, + crate::Literal::F32(value) => write!(self.out, "{value:?}")?, + crate::Literal::U32(value) => write!(self.out, "{}u", value)?, + crate::Literal::I32(value) => write!(self.out, "{}", value)?, + crate::Literal::Bool(value) => write!(self.out, "{}", value)?, + }, Expression::Compose { ty, ref components } => { match module.types[ty].inner { TypeInner::Struct { .. } | TypeInner::Array { .. } => { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 1c474a5e4..7e41e8a7e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1344,6 +1344,31 @@ impl Writer { }; write!(self.out, "{ty_name} {{}}")?; } + crate::Expression::Literal(literal) => match literal { + crate::Literal::F64(_) => { + return Err(Error::CapabilityNotSupported(valid::Capabilities::FLOAT64)) + } + crate::Literal::F32(value) => { + if value.is_infinite() { + let sign = if value.is_sign_negative() { "-" } else { "" }; + write!(self.out, "{sign}INFINITY")?; + } else if value.is_nan() { + write!(self.out, "NAN")?; + } else { + let suffix = if value.fract() == 0.0 { ".0" } else { "" }; + write!(self.out, "{value}{suffix}")?; + } + } + crate::Literal::U32(value) => { + write!(self.out, "{value}u")?; + } + crate::Literal::I32(value) => { + write!(self.out, "{value}")?; + } + crate::Literal::Bool(value) => { + write!(self.out, "{value}")?; + } + }, crate::Expression::Splat { size, value } => { let scalar_kind = match *context.resolve_type(value) { crate::TypeInner::Scalar { kind, .. } => kind, diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index a8afa8997..be5fa5da0 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -118,8 +118,8 @@ impl Writer { width: 4, pointer_space: None, })); - let value0_id = self.get_constant_scalar(crate::ScalarValue::Float(0.0), 4); - let value1_id = self.get_constant_scalar(crate::ScalarValue::Float(1.0), 4); + let zero_scalar_id = self.get_constant_scalar(crate::Literal::F32(0.0)); + let one_scalar_id = self.get_constant_scalar(crate::Literal::F32(1.0)); let original_id = self.id_gen.next(); body.push(Instruction::load( @@ -135,7 +135,7 @@ impl Writer { spirv::GLOp::FClamp, float_type_id, clamp_id, - &[original_id, value0_id, value1_id], + &[original_id, zero_scalar_id, one_scalar_id], )); body.push(Instruction::store(frag_depth_id, clamp_id, None)); @@ -359,6 +359,7 @@ impl<'w> BlockContext<'w> { } crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], crate::Expression::ZeroValue(_) => self.writer.write_constant_null(result_type_id), + crate::Expression::Literal(literal) => self.writer.get_constant_scalar(literal), crate::Expression::Splat { size, value } => { let value_id = self.cached[value]; let components = [value_id; 4]; @@ -705,18 +706,14 @@ impl<'w> BlockContext<'w> { crate::TypeInner::Scalar { width, .. } => (None, width), ref other => unimplemented!("Unexpected saturate({:?})", other), }; - - let mut arg1_id = self - .writer - .get_constant_scalar(crate::ScalarValue::Float(0.0), width); - let mut arg2_id = self - .writer - .get_constant_scalar(crate::ScalarValue::Float(1.0), width); + let kind = crate::ScalarKind::Float; + let mut arg1_id = self.writer.get_constant_scalar_with(0, kind, width)?; + let mut arg2_id = self.writer.get_constant_scalar_with(1, kind, width)?; if let Some(size) = maybe_size { let ty = LocalType::Value { vector_size: Some(size), - kind: crate::ScalarKind::Float, + kind, width, pointer_space: None, } @@ -878,12 +875,13 @@ impl<'w> BlockContext<'w> { arg0_id, )), Mf::CountTrailingZeros => { - let uint = crate::ScalarValue::Uint(32); + let kind = crate::ScalarKind::Uint; + let uint_id = match *arg_ty { crate::TypeInner::Vector { size, width, .. } => { let ty = LocalType::Value { vector_size: Some(size), - kind: crate::ScalarKind::Uint, + kind, width, pointer_space: None, } @@ -892,13 +890,13 @@ impl<'w> BlockContext<'w> { self.temp_list.clear(); self.temp_list.resize( size as _, - self.writer.get_constant_scalar(uint, width), + self.writer.get_constant_scalar_with(32, kind, width)?, ); self.writer.get_constant_composite(ty, &self.temp_list) } crate::TypeInner::Scalar { width, .. } => { - self.writer.get_constant_scalar(uint, width) + self.writer.get_constant_scalar_with(32, kind, width)? } _ => unreachable!(), }; @@ -921,21 +919,23 @@ impl<'w> BlockContext<'w> { )) } Mf::CountLeadingZeros => { - let int = crate::ScalarValue::Sint(31); + let kind = crate::ScalarKind::Sint; let (int_type_id, int_id) = match *arg_ty { crate::TypeInner::Vector { size, width, .. } => { let ty = LocalType::Value { vector_size: Some(size), - kind: crate::ScalarKind::Sint, + kind, width, pointer_space: None, } .into(); self.temp_list.clear(); - self.temp_list - .resize(size as _, self.writer.get_constant_scalar(int, width)); + self.temp_list.resize( + size as _, + self.writer.get_constant_scalar_with(31, kind, width)?, + ); ( self.get_type_id(ty), @@ -945,11 +945,11 @@ impl<'w> BlockContext<'w> { crate::TypeInner::Scalar { width, .. } => ( self.get_type_id(LookupType::Local(LocalType::Value { vector_size: None, - kind: crate::ScalarKind::Sint, + kind, width, pointer_space: None, })), - self.writer.get_constant_scalar(int, width), + self.writer.get_constant_scalar_with(31, kind, width)?, ), _ => unreachable!(), }; @@ -1134,15 +1134,14 @@ impl<'w> BlockContext<'w> { (_, _, None) => Cast::Unary(spirv::Op::Bitcast), // casting to a bool - generate `OpXxxNotEqual` (_, Sk::Bool, Some(_)) => { - let (op, value) = match src_kind { - Sk::Sint => (spirv::Op::INotEqual, crate::ScalarValue::Sint(0)), - Sk::Uint => (spirv::Op::INotEqual, crate::ScalarValue::Uint(0)), - Sk::Float => { - (spirv::Op::FUnordNotEqual, crate::ScalarValue::Float(0.0)) - } + let op = match src_kind { + Sk::Sint | Sk::Uint => spirv::Op::INotEqual, + Sk::Float => spirv::Op::FUnordNotEqual, Sk::Bool => unreachable!(), }; - let zero_scalar_id = self.writer.get_constant_scalar(value, src_width); + let zero_scalar_id = self + .writer + .get_constant_scalar_with(0, src_kind, src_width)?; let zero_id = match src_size { Some(size) => { let ty = LocalType::Value { @@ -1165,21 +1164,10 @@ impl<'w> BlockContext<'w> { } // casting from a bool - generate `OpSelect` (Sk::Bool, _, Some(dst_width)) => { - let (val0, val1) = match kind { - Sk::Sint => { - (crate::ScalarValue::Sint(0), crate::ScalarValue::Sint(1)) - } - Sk::Uint => { - (crate::ScalarValue::Uint(0), crate::ScalarValue::Uint(1)) - } - Sk::Float => ( - crate::ScalarValue::Float(0.0), - crate::ScalarValue::Float(1.0), - ), - Sk::Bool => unreachable!(), - }; - let scalar0_id = self.writer.get_constant_scalar(val0, dst_width); - let scalar1_id = self.writer.get_constant_scalar(val1, dst_width); + let zero_scalar_id = + self.writer.get_constant_scalar_with(0, kind, dst_width)?; + let one_scalar_id = + self.writer.get_constant_scalar_with(1, kind, dst_width)?; let (accept_id, reject_id) = match src_size { Some(size) => { let ty = LocalType::Value { @@ -1191,19 +1179,19 @@ impl<'w> BlockContext<'w> { .into(); self.temp_list.clear(); - self.temp_list.resize(size as _, scalar0_id); + self.temp_list.resize(size as _, zero_scalar_id); let vec0_id = self.writer.get_constant_composite(ty, &self.temp_list); - self.temp_list.fill(scalar1_id); + self.temp_list.fill(one_scalar_id); let vec1_id = self.writer.get_constant_composite(ty, &self.temp_list); (vec1_id, vec0_id) } - None => (scalar1_id, scalar0_id), + None => (one_scalar_id, zero_scalar_id), }; Cast::Ternary(spirv::Op::Select, accept_id, reject_id) @@ -1460,8 +1448,8 @@ impl<'w> BlockContext<'w> { BoundsCheckResult::KnownInBounds(known_index) => { // Even if the index is known, `OpAccessIndex` // requires expression operands, not literals. - let scalar = crate::ScalarValue::Uint(known_index as u64); - self.writer.get_constant_scalar(scalar, 4) + let scalar = crate::Literal::U32(known_index); + self.writer.get_constant_scalar(scalar) } BoundsCheckResult::Computed(computed_index_id) => computed_index_id, BoundsCheckResult::Conditional(comparison_id) => { diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 27f352050..81c9de375 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -901,9 +901,7 @@ impl<'w> BlockContext<'w> { depth_id, ); - let zero_id = self - .writer - .get_constant_scalar(crate::ScalarValue::Float(0.0), 4); + let zero_id = self.writer.get_constant_scalar(crate::Literal::F32(0.0)); mask |= spirv::ImageOperands::LOD; inst.add_operand(mask.bits()); diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 96d027828..31ed6e231 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -343,6 +343,14 @@ impl super::Instruction { instruction } + pub(super) fn constant_32bit(result_type_id: Word, id: Word, value: Word) -> Self { + Self::constant(result_type_id, id, &[value]) + } + + pub(super) fn constant_64bit(result_type_id: Word, id: Word, low: Word, high: Word) -> Self { + Self::constant(result_type_id, id, &[low, high]) + } + pub(super) fn constant(result_type_id: Word, id: Word, values: &[Word]) -> Self { let mut instruction = Self::new(Op::Constant); instruction.set_type(result_type_id); diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index adc3dd7a7..613912ef8 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -295,12 +295,12 @@ enum LocalType { /// [`BindingArray`]: crate::TypeInner::BindingArray PointerToBindingArray { base: Handle, - size: u64, + size: u32, space: crate::AddressSpace, }, BindingArray { base: Handle, - size: u64, + size: u32, }, AccelerationStructure, RayQuery, @@ -454,10 +454,7 @@ impl recyclable::Recyclable for CachedExpressions { #[derive(Eq, Hash, PartialEq)] enum CachedConstant { - Scalar { - value: crate::ScalarValue, - width: crate::Bytes, - }, + Literal(crate::Literal), Composite { ty: LookupType, constituent_ids: Vec, @@ -568,13 +565,12 @@ impl BlockContext<'_> { } fn get_index_constant(&mut self, index: Word) -> Word { - self.writer - .get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) + self.writer.get_constant_scalar(crate::Literal::U32(index)) } fn get_scope_constant(&mut self, scope: Word) -> Word { self.writer - .get_constant_scalar(crate::ScalarValue::Sint(scope as _), 4) + .get_constant_scalar(crate::Literal::I32(scope as _)) } } diff --git a/src/back/spv/ray.rs b/src/back/spv/ray.rs index 79eb2ff97..0b53b9cc5 100644 --- a/src/back/spv/ray.rs +++ b/src/back/spv/ray.rs @@ -117,12 +117,9 @@ impl<'w> BlockContext<'w> { ) -> spirv::Word { let width = 4; let query_id = self.cached[query]; - let intersection_id = self.writer.get_constant_scalar( - crate::ScalarValue::Uint( - spirv::RayQueryIntersection::RayQueryCommittedIntersectionKHR as _, - ), - width, - ); + let intersection_id = self.writer.get_constant_scalar(crate::Literal::U32( + spirv::RayQueryIntersection::RayQueryCommittedIntersectionKHR as _, + )); let flag_type_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size: None, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 90c6b5089..3e3dfc60a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -540,8 +540,7 @@ impl Writer { ); iface.varying_ids.push(varying_id); - let default_value_id = - self.get_constant_scalar(crate::ScalarValue::Float(1.0), 4); + let default_value_id = self.get_constant_scalar(crate::Literal::F32(1.0)); prelude .body .push(Instruction::store(varying_id, default_value_id, None)); @@ -937,7 +936,7 @@ impl Writer { } LocalType::BindingArray { base, size } => { let inner_ty = self.get_type_id(LookupType::Handle(base)); - let scalar_id = self.get_constant_scalar(crate::ScalarValue::Uint(size), 4); + let scalar_id = self.get_constant_scalar(crate::Literal::U32(size)); Instruction::type_array(id, inner_ty, scalar_id) } LocalType::PointerToBindingArray { base, size, space } => { @@ -1108,20 +1107,29 @@ impl Writer { } pub(super) fn get_index_constant(&mut self, index: Word) -> Word { - self.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4) + self.get_constant_scalar(crate::Literal::U32(index)) } - pub(super) fn get_constant_scalar( + pub(super) fn get_constant_scalar_with( &mut self, - value: crate::ScalarValue, + value: u8, + kind: crate::ScalarKind, width: crate::Bytes, - ) -> Word { - let scalar = CachedConstant::Scalar { value, width }; + ) -> Result { + Ok( + self.get_constant_scalar(crate::Literal::new(value, kind, width).ok_or( + Error::Validation("Unexpected kind and/or width for Literal"), + )?), + ) + } + + pub(super) fn get_constant_scalar(&mut self, value: crate::Literal) -> Word { + let scalar = CachedConstant::Literal(value); if let Some(&id) = self.cached_constants.get(&scalar) { return id; } let id = self.id_gen.next(); - self.write_constant_scalar(id, &value, width, None); + self.write_constant_scalar(id, &value, None); self.cached_constants.insert(scalar, id); id } @@ -1129,8 +1137,7 @@ impl Writer { fn write_constant_scalar( &mut self, id: Word, - value: &crate::ScalarValue, - width: crate::Bytes, + value: &crate::Literal, debug_name: Option<&String>, ) { if self.flags.contains(WriterFlags::DEBUG) { @@ -1141,56 +1148,19 @@ impl Writer { let type_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size: None, kind: value.scalar_kind(), - width, + width: value.width(), pointer_space: None, })); - let (solo, pair); let instruction = match *value { - crate::ScalarValue::Sint(val) => { - let words = match width { - 4 => { - solo = [val as u32]; - &solo[..] - } - 8 => { - pair = [val as u32, (val >> 32) as u32]; - &pair - } - _ => unreachable!(), - }; - Instruction::constant(type_id, id, words) + crate::Literal::F64(value) => { + let bits = value.to_bits(); + Instruction::constant_64bit(type_id, id, bits as u32, (bits >> 32) as u32) } - crate::ScalarValue::Uint(val) => { - let words = match width { - 4 => { - solo = [val as u32]; - &solo[..] - } - 8 => { - pair = [val as u32, (val >> 32) as u32]; - &pair - } - _ => unreachable!(), - }; - Instruction::constant(type_id, id, words) - } - crate::ScalarValue::Float(val) => { - let words = match width { - 4 => { - solo = [(val as f32).to_bits()]; - &solo[..] - } - 8 => { - let bits = f64::to_bits(val); - pair = [bits as u32, (bits >> 32) as u32]; - &pair - } - _ => unreachable!(), - }; - Instruction::constant(type_id, id, words) - } - crate::ScalarValue::Bool(true) => Instruction::constant_true(type_id, id), - crate::ScalarValue::Bool(false) => Instruction::constant_false(type_id, id), + crate::Literal::F32(value) => Instruction::constant_32bit(type_id, id, value.to_bits()), + crate::Literal::U32(value) => Instruction::constant_32bit(type_id, id, value), + crate::Literal::I32(value) => Instruction::constant_32bit(type_id, id, value as u32), + crate::Literal::Bool(true) => Instruction::constant_true(type_id, id), + crate::Literal::Bool(false) => Instruction::constant_false(type_id, id), }; instruction.to_words(&mut self.logical_layout.declarations); @@ -1598,7 +1568,7 @@ impl Writer { substitute_inner_type_lookup = Some(LookupType::Local(LocalType::PointerToBindingArray { base, - size: remapped_binding_array_size as u64, + size: remapped_binding_array_size, space: global_variable.space, })) } @@ -1812,13 +1782,16 @@ impl Writer { match constant.inner { crate::ConstantInner::Composite { .. } => continue, crate::ConstantInner::Scalar { width, ref value } => { + let literal = crate::Literal::from_scalar(*value, width).ok_or( + Error::Validation("Unexpected kind and/or width for Literal"), + )?; self.constant_ids[handle.index()] = match constant.name { Some(ref name) => { let id = self.id_gen.next(); - self.write_constant_scalar(id, value, width, Some(name)); + self.write_constant_scalar(id, &literal, Some(name)); id } - None => self.get_constant_scalar(*value, width), + None => self.get_constant_scalar(literal), }; } } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 97a271dbb..93909ab7a 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1103,6 +1103,19 @@ impl Writer { // `postfix_expression` forms for member/component access and // subscripting. match *expression { + Expression::Literal(literal) => { + match literal { + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero + crate::Literal::F64(_) => { + return Err(Error::Custom("unsupported f64 literal".to_string())); + } + crate::Literal::F32(value) => write!(self.out, "{:?}", value)?, + crate::Literal::U32(value) => write!(self.out, "{}u", value)?, + crate::Literal::I32(value) => write!(self.out, "{}", value)?, + crate::Literal::Bool(value) => write!(self.out, "{}", value)?, + } + } Expression::Constant(constant) => self.write_constant(module, constant)?, Expression::ZeroValue(ty) => { self.write_type(module, ty)?; diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 5f7fc4f89..9f763f9f0 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -72,6 +72,7 @@ impl<'a> ConstantSolver<'a> { match self.expressions[expr] { Expression::Constant(constant) => Ok(constant), Expression::ZeroValue(ty) => self.register_zero_constant(ty, span), + Expression::Literal(literal) => Ok(self.register_literal(literal, span)), Expression::AccessIndex { base, index } => self.access(base, index as usize), Expression::Access { base, index } => { let index = self.solve(index)?; @@ -648,6 +649,18 @@ impl<'a> ConstantSolver<'a> { Ok(self.register_constant(inner, span)) } + fn register_literal(&mut self, literal: crate::Literal, span: crate::Span) -> Handle { + let (width, value) = match literal { + crate::Literal::F64(n) => (8, ScalarValue::Float(n)), + crate::Literal::F32(n) => (4, ScalarValue::Float(n as f64)), + crate::Literal::U32(n) => (4, ScalarValue::Uint(n as u64)), + crate::Literal::I32(n) => (4, ScalarValue::Sint(n as i64)), + crate::Literal::Bool(b) => (1, ScalarValue::Bool(b)), + }; + + self.register_constant(ConstantInner::Scalar { width, value }, span) + } + fn register_constant(&mut self, inner: ConstantInner, span: crate::Span) -> Handle { self.constants.fetch_or_append( Constant { diff --git a/src/lib.rs b/src/lib.rs index 6a5bc8e0a..1cf4c8b1a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,8 +75,8 @@ of `Statement`s and other `Expression`s. Naga's rules for when `Expression`s are evaluated are as follows: -- [`Constant`] and [`ZeroValue`] expressions are considered to be - implicitly evaluated before execution begins. +- [`Literal`], [`Constant`], and [`ZeroValue`] expressions are + considered to be implicitly evaluated before execution begins. - [`FunctionArgument`] and [`LocalVariable`] expressions are considered implicitly evaluated upon entry to the function to which they belong. @@ -175,6 +175,7 @@ tree. [`CallResult`]: Expression::CallResult [`Constant`]: Expression::Constant [`ZeroValue`]: Expression::ZeroValue +[`Literal`]: Expression::Literal [`Derivative`]: Expression::Derivative [`FunctionArgument`]: Expression::FunctionArgument [`GlobalVariable`]: Expression::GlobalVariable @@ -792,6 +793,18 @@ pub struct Constant { pub inner: ConstantInner, } +#[derive(Debug, Clone, Copy, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +pub enum Literal { + F64(f64), + F32(f32), + U32(u32), + I32(i32), + Bool(bool), +} + /// A literal scalar value, used in constants. #[derive(Debug, Clone, Copy, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -1190,6 +1203,8 @@ bitflags::bitflags! { #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Expression { + /// Literal. + Literal(Literal), /// Constant value. Constant(Handle), /// Zero value of a type. diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c4c6d4f4e..ed501693d 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -82,6 +82,101 @@ impl super::ScalarKind { } } +impl PartialEq for crate::Literal { + fn eq(&self, other: &Self) -> bool { + match (*self, *other) { + (Self::F64(a), Self::F64(b)) => a.to_bits() == b.to_bits(), + (Self::F32(a), Self::F32(b)) => a.to_bits() == b.to_bits(), + (Self::U32(a), Self::U32(b)) => a == b, + (Self::I32(a), Self::I32(b)) => a == b, + (Self::Bool(a), Self::Bool(b)) => a == b, + _ => false, + } + } +} +impl Eq for crate::Literal {} +impl std::hash::Hash for crate::Literal { + fn hash(&self, hasher: &mut H) { + match *self { + Self::F64(v) => { + hasher.write_u8(0); + v.to_bits().hash(hasher); + } + Self::F32(v) => { + hasher.write_u8(1); + v.to_bits().hash(hasher); + } + Self::U32(v) => { + hasher.write_u8(2); + v.hash(hasher); + } + Self::I32(v) => { + hasher.write_u8(3); + v.hash(hasher); + } + Self::Bool(v) => { + hasher.write_u8(4); + v.hash(hasher); + } + } + } +} + +impl crate::Literal { + pub const fn new(value: u8, kind: crate::ScalarKind, width: crate::Bytes) -> Option { + match (value, kind, width) { + (value, crate::ScalarKind::Float, 8) => Some(Self::F64(value as _)), + (value, crate::ScalarKind::Float, 4) => Some(Self::F32(value as _)), + (value, crate::ScalarKind::Uint, 4) => Some(Self::U32(value as _)), + (value, crate::ScalarKind::Sint, 4) => Some(Self::I32(value as _)), + (1, crate::ScalarKind::Bool, 4) => Some(Self::Bool(true)), + (0, crate::ScalarKind::Bool, 4) => Some(Self::Bool(false)), + _ => None, + } + } + + pub const fn from_scalar(scalar: crate::ScalarValue, width: crate::Bytes) -> Option { + match (scalar, width) { + (crate::ScalarValue::Sint(n), 4) => Some(Self::I32(n as _)), + (crate::ScalarValue::Uint(n), 4) => Some(Self::U32(n as _)), + (crate::ScalarValue::Float(n), 4) => Some(Self::F32(n as _)), + (crate::ScalarValue::Float(n), 8) => Some(Self::F64(n)), + (crate::ScalarValue::Bool(b), _) => Some(Self::Bool(b)), + _ => None, + } + } + + pub const fn zero(kind: crate::ScalarKind, width: crate::Bytes) -> Option { + Self::new(0, kind, width) + } + + pub const fn one(kind: crate::ScalarKind, width: crate::Bytes) -> Option { + Self::new(1, kind, width) + } + + pub const fn width(&self) -> crate::Bytes { + match *self { + Self::F64(_) => 8, + Self::F32(_) | Self::U32(_) | Self::I32(_) => 4, + Self::Bool(_) => 1, + } + } + pub const fn scalar_kind(&self) -> crate::ScalarKind { + match *self { + Self::F64(_) | Self::F32(_) => crate::ScalarKind::Float, + Self::U32(_) => crate::ScalarKind::Uint, + Self::I32(_) => crate::ScalarKind::Sint, + Self::Bool(_) => crate::ScalarKind::Bool, + } + } + pub const fn ty_inner(&self) -> crate::TypeInner { + crate::TypeInner::Scalar { + kind: self.scalar_kind(), + width: self.width(), + } + } +} + pub const POINTER_SPAN: u32 = 4; impl super::TypeInner { @@ -311,7 +406,8 @@ impl crate::Expression { /// Returns true if the expression is considered emitted at the start of a function. pub const fn needs_pre_emit(&self) -> bool { match *self { - Self::Constant(_) + Self::Literal(_) + | Self::Constant(_) | Self::ZeroValue(_) | Self::FunctionArgument(_) | Self::GlobalVariable(_) diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 414749ee0..2345cccf8 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -421,6 +421,7 @@ impl<'a> ResolveContext<'a> { } } } + crate::Expression::Literal(lit) => TypeResolution::Value(lit.ty_inner()), crate::Expression::Constant(h) => match self.constants[h].inner { crate::ConstantInner::Scalar { width, ref value } => { TypeResolution::Value(Ti::Scalar { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 4860435ce..b93f444a9 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -492,8 +492,7 @@ impl FunctionInfo { requirements: UniformityRequirements::empty(), }, // always uniform - E::Constant(_) => Uniformity::new(), - E::ZeroValue(_) => Uniformity::new(), + E::Literal(_) | E::Constant(_) | E::ZeroValue(_) => Uniformity::new(), E::Splat { size: _, value } => Uniformity { non_uniform_result: self.add_ref(value), requirements: UniformityRequirements::empty(), diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 7f9e277cf..ece98d70f 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -269,6 +269,7 @@ impl super::Validator { } ShaderStages::all() } + E::Literal(_value) => ShaderStages::all(), E::Constant(_handle) => ShaderStages::all(), E::ZeroValue(_type) => ShaderStages::all(), E::Splat { size: _, value } => match resolver[value] { diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 0115cd85d..24e485277 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -253,6 +253,7 @@ impl super::Validator { crate::Expression::AccessIndex { base, .. } => { handle.check_dep(base)?; } + crate::Expression::Literal(_value) => {} crate::Expression::Constant(constant) => { validate_constant(constant)?; } From 412d5aa62e7d4f9c22dfe3e57ef1c648d646d808 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 10 May 2023 22:23:10 -0700 Subject: [PATCH 1994/2212] [wgsl-in] Generate `Expression::Literal`. --- src/front/wgsl/lower/mod.rs | 97 +- tests/out/dot/quad.dot | 14 +- tests/out/glsl/boids.main.Compute.glsl | 2 +- .../glsl/image.texture_sample.Fragment.glsl | 16 +- tests/out/glsl/operators.main.Compute.glsl | 2 +- tests/out/hlsl/boids.hlsl | 2 +- tests/out/hlsl/image.hlsl | 16 +- tests/out/hlsl/operators.hlsl | 2 +- tests/out/ir/access.ron | 362 ++--- tests/out/ir/collatz.ron | 51 +- tests/out/msl/boids.msl | 2 +- tests/out/msl/image.msl | 16 +- tests/out/msl/operators.msl | 2 +- tests/out/msl/policy-mix.msl | 2 +- tests/out/msl/ray-query.msl | 4 +- tests/out/spv/access.spvasm | 842 +++++------ tests/out/spv/atomicCompareExchange.spvasm | 172 +-- tests/out/spv/atomicOps.spvasm | 398 +++--- tests/out/spv/binding-arrays.spvasm | 862 +++++------ tests/out/spv/binding-buffer-arrays.spvasm | 146 +- tests/out/spv/bitcast.spvasm | 170 +-- tests/out/spv/bits.spvasm | 442 +++--- tests/out/spv/boids.spvasm | 456 +++--- .../spv/bounds-check-image-restrict.spvasm | 862 +++++------ tests/out/spv/bounds-check-image-rzsw.spvasm | 1030 +++++++------- tests/out/spv/bounds-check-restrict.spvasm | 306 ++-- tests/out/spv/bounds-check-zero.spvasm | 402 +++--- tests/out/spv/break-if.spvasm | 46 +- tests/out/spv/collatz.spvasm | 118 +- tests/out/spv/control-flow.spvasm | 156 +- tests/out/spv/extra.spvasm | 106 +- tests/out/spv/fragment-output.spvasm | 206 +-- tests/out/spv/functions.spvasm | 144 +- tests/out/spv/globals.spvasm | 418 +++--- tests/out/spv/image.spvasm | 1256 ++++++++--------- tests/out/spv/interface.compute.spvasm | 145 +- tests/out/spv/interface.fragment.spvasm | 154 +- tests/out/spv/interface.vertex.spvasm | 116 +- .../spv/interface.vertex_two_structs.spvasm | 116 +- tests/out/spv/interpolate.spvasm | 288 ++-- tests/out/spv/math-functions.spvasm | 154 +- tests/out/spv/operators.spvasm | 1194 ++++++++-------- tests/out/spv/padding.spvasm | 154 +- tests/out/spv/pointers.spvasm | 78 +- tests/out/spv/policy-mix.spvasm | 214 +-- tests/out/spv/quad.spvasm | 196 +-- tests/out/spv/ray-query.spvasm | 232 +-- tests/out/spv/shadow.spvasm | 612 ++++---- tests/out/spv/skybox.spvasm | 224 +-- tests/out/spv/texture-arg.spvasm | 66 +- tests/out/wgsl/boids.wgsl | 2 +- tests/out/wgsl/image.wgsl | 16 +- tests/out/wgsl/operators.wgsl | 2 +- 53 files changed, 6431 insertions(+), 6660 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index f6c27caa8..e066a29f1 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1133,36 +1133,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let (expr, is_reference) = match *expr { ast::Expression::Literal(literal) => { - let inner = match literal { - ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Float(f as _), - }, - ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Sint(i as _), - }, - ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(u as _), - }, + let literal = match literal { + ast::Literal::Number(Number::F32(f)) => crate::Literal::F32(f), + ast::Literal::Number(Number::I32(i)) => crate::Literal::I32(i), + ast::Literal::Number(Number::U32(u)) => crate::Literal::U32(u), ast::Literal::Number(_) => { unreachable!("got abstract numeric type when not expected"); } - ast::Literal::Bool(b) => crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(b), - }, + ast::Literal::Bool(b) => crate::Literal::Bool(b), }; - let handle = ctx.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Span::UNDEFINED, - ); - let handle = ctx.interrupt_emitter(crate::Expression::Constant(handle), span); + let handle = ctx.interrupt_emitter(crate::Expression::Literal(literal), span); return Ok(TypedExpression::non_reference(handle)); } ast::Expression::Ident(ast::IdentExpr::Local(local)) => { @@ -1264,35 +1244,54 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { )); } - if let crate::Expression::Constant(constant) = ctx.naga_expressions[index] { - let span = ctx.naga_expressions.get_span(index); - let index = match ctx.module.constants[constant].inner { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Sint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), - _ => Err(Error::BadU32Constant(span)), - }?; + match ctx.naga_expressions[index] { + crate::Expression::Constant(constant) => { + let span = ctx.naga_expressions.get_span(index); + let index = match ctx.module.constants[constant].inner { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Sint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), + _ => Err(Error::BadU32Constant(span)), + }?; - ( - crate::Expression::AccessIndex { - base: expr.handle, - index, - }, - expr.is_reference, - ) - } else { - ( + ( + crate::Expression::AccessIndex { + base: expr.handle, + index, + }, + expr.is_reference, + ) + } + crate::Expression::Literal(literal) => { + let span = ctx.naga_expressions.get_span(index); + let index = match literal { + crate::Literal::U32(n) => n, + crate::Literal::I32(n) => { + u32::try_from(n).map_err(|_| Error::BadU32Constant(span))? + } + _ => return Err(Error::BadU32Constant(span)), + }; + + ( + crate::Expression::AccessIndex { + base: expr.handle, + index, + }, + expr.is_reference, + ) + } + _ => ( crate::Expression::Access { base: expr.handle, index, }, expr.is_reference, - ) + ), } } ast::Expression::Member { base, ref field } => { diff --git a/tests/out/dot/quad.dot b/tests/out/dot/quad.dot index 4f2cde18c..986408978 100644 --- a/tests/out/dot/quad.dot +++ b/tests/out/dot/quad.dot @@ -13,8 +13,8 @@ digraph Module { ep0_e3 [ color="#fdb462" label="[4] Multiply" ] ep0_e0 -> ep0_e3 [ label="right" ] ep0_e2 -> ep0_e3 [ label="left" ] - ep0_e4 [ fillcolor="#ffffb3" label="[5] Constant" ] - ep0_e5 [ fillcolor="#ffffb3" label="[6] Constant" ] + ep0_e4 [ fillcolor="#ffffb3" label="[5] Literal" ] + ep0_e5 [ fillcolor="#ffffb3" label="[6] Literal" ] ep0_e6 [ color="#bebada" label="[7] Compose" ] { ep0_e3 ep0_e4 ep0_e5 } -> ep0_e6 ep0_e7 [ color="#bebada" label="[8] Compose" ] @@ -45,7 +45,7 @@ digraph Module { ep1_e0 -> ep1_e3 [ label="coordinate" ] ep1_e4 [ color="#8dd3c7" label="[5] AccessIndex[3]" ] ep1_e3 -> ep1_e4 [ label="base" ] - ep1_e5 [ fillcolor="#ffffb3" label="[6] Constant" ] + ep1_e5 [ fillcolor="#ffffb3" label="[6] Literal" ] ep1_e6 [ color="#fdb462" label="[7] Equal" ] ep1_e5 -> ep1_e6 [ label="right" ] ep1_e4 -> ep1_e6 [ label="left" ] @@ -87,10 +87,10 @@ digraph Module { subgraph cluster_ep2 { label="Fragment/'fs_extra'" node [ style=filled ] - ep2_e0 [ fillcolor="#ffffb3" label="[1] Constant" ] - ep2_e1 [ fillcolor="#ffffb3" label="[2] Constant" ] - ep2_e2 [ fillcolor="#ffffb3" label="[3] Constant" ] - ep2_e3 [ fillcolor="#ffffb3" label="[4] Constant" ] + ep2_e0 [ fillcolor="#ffffb3" label="[1] Literal" ] + ep2_e1 [ fillcolor="#ffffb3" label="[2] Literal" ] + ep2_e2 [ fillcolor="#ffffb3" label="[3] Literal" ] + ep2_e3 [ fillcolor="#ffffb3" label="[4] Literal" ] ep2_e4 [ fillcolor="#bebada" label="[5] Compose" ] { ep2_e0 ep2_e1 ep2_e2 ep2_e3 } -> ep2_e4 ep2_s0 [ shape=square label="Root" ] diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index c8df993f5..0f6485361 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -129,7 +129,7 @@ void main() { vVel = (((_e112 + (_e113 * _e116)) + (_e119 * _e122)) + (_e125 * _e128)); vec2 _e131 = vVel; vec2 _e133 = vVel; - vVel = (normalize(_e131) * clamp(length(_e133), 0.0, 0.10000000149011612)); + vVel = (normalize(_e131) * clamp(length(_e133), 0.0, 0.1)); vec2 _e139 = vPos; vec2 _e140 = vVel; float _e143 = _group_0_binding_0_cs.deltaT; diff --git a/tests/out/glsl/image.texture_sample.Fragment.glsl b/tests/out/glsl/image.texture_sample.Fragment.glsl index 72aa8fa16..97be5a59d 100644 --- a/tests/out/glsl/image.texture_sample.Fragment.glsl +++ b/tests/out/glsl/image.texture_sample.Fragment.glsl @@ -27,10 +27,10 @@ void main() { vec4 _e19 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1)); vec4 _e20 = a; a = (_e20 + _e19); - vec4 _e24 = textureLod(_group_0_binding_1_fs, vec2(tc), 2.299999952316284); + vec4 _e24 = textureLod(_group_0_binding_1_fs, vec2(tc), 2.3); vec4 _e25 = a; a = (_e25 + _e24); - vec4 _e29 = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.299999952316284, ivec2(3, 1)); + vec4 _e29 = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.3, ivec2(3, 1)); vec4 _e30 = a; a = (_e30 + _e29); vec4 _e35 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 2.0); @@ -42,10 +42,10 @@ void main() { vec4 _e47 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1)); vec4 _e48 = a; a = (_e48 + _e47); - vec4 _e53 = textureLod(_group_0_binding_4_fs, vec3(tc, 0u), 2.299999952316284); + vec4 _e53 = textureLod(_group_0_binding_4_fs, vec3(tc, 0u), 2.3); vec4 _e54 = a; a = (_e54 + _e53); - vec4 _e59 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0u), 2.299999952316284, ivec2(3, 1)); + vec4 _e59 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0u), 2.3, ivec2(3, 1)); vec4 _e60 = a; a = (_e60 + _e59); vec4 _e66 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1), 2.0); @@ -57,10 +57,10 @@ void main() { vec4 _e78 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1)); vec4 _e79 = a; a = (_e79 + _e78); - vec4 _e84 = textureLod(_group_0_binding_4_fs, vec3(tc, 0), 2.299999952316284); + vec4 _e84 = textureLod(_group_0_binding_4_fs, vec3(tc, 0), 2.3); vec4 _e85 = a; a = (_e85 + _e84); - vec4 _e90 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0), 2.299999952316284, ivec2(3, 1)); + vec4 _e90 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0), 2.3, ivec2(3, 1)); vec4 _e91 = a; a = (_e91 + _e90); vec4 _e97 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1), 2.0); @@ -69,7 +69,7 @@ void main() { vec4 _e103 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u)); vec4 _e104 = a; a = (_e104 + _e103); - vec4 _e109 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.299999952316284); + vec4 _e109 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.3); vec4 _e110 = a; a = (_e110 + _e109); vec4 _e116 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.0); @@ -78,7 +78,7 @@ void main() { vec4 _e122 = texture(_group_0_binding_6_fs, vec4(tc3_, 0)); vec4 _e123 = a; a = (_e123 + _e122); - vec4 _e128 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0), 2.299999952316284); + vec4 _e128 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0), 2.3); vec4 _e129 = a; a = (_e129 + _e128); vec4 _e135 = texture(_group_0_binding_6_fs, vec4(tc3_, 0), 2.0); diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index a76465d95..9754ae2bb 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -15,7 +15,7 @@ vec4 builtins() { vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); vec4 s3_ = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), bvec4(false, false, false, false)); vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); float b1_ = intBitsToFloat(ivec4(1, 1, 1, 1).x); vec4 b2_ = intBitsToFloat(ivec4(1, 1, 1, 1)); ivec4 v_i32_zero = ivec4(vec4(0.0, 0.0, 0.0, 0.0)); diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index d9f134048..d6bac1cb2 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -121,7 +121,7 @@ void main(uint3 global_invocation_id : SV_DispatchThreadID) vVel = (((_expr112 + (_expr113 * _expr116)) + (_expr119 * _expr122)) + (_expr125 * _expr128)); float2 _expr131 = vVel; float2 _expr133 = vVel; - vVel = (normalize(_expr131) * clamp(length(_expr133), 0.0, 0.10000000149011612)); + vVel = (normalize(_expr131) * clamp(length(_expr133), 0.0, 0.1)); float2 _expr139 = vPos; float2 _expr140 = vVel; float _expr143 = params.deltaT; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 79e490e24..75672b9be 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -256,10 +256,10 @@ float4 texture_sample() : SV_Target0 float4 _expr19 = image_2d.Sample(sampler_reg, tc, int2(3, 1)); float4 _expr20 = a; a = (_expr20 + _expr19); - float4 _expr24 = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284); + float4 _expr24 = image_2d.SampleLevel(sampler_reg, tc, 2.3); float4 _expr25 = a; a = (_expr25 + _expr24); - float4 _expr29 = image_2d.SampleLevel(sampler_reg, tc, 2.299999952316284, int2(3, 1)); + float4 _expr29 = image_2d.SampleLevel(sampler_reg, tc, 2.3, int2(3, 1)); float4 _expr30 = a; a = (_expr30 + _expr29); float4 _expr35 = image_2d.SampleBias(sampler_reg, tc, 2.0, int2(3, 1)); @@ -271,10 +271,10 @@ float4 texture_sample() : SV_Target0 float4 _expr47 = image_2d_array.Sample(sampler_reg, float3(tc, 0u), int2(3, 1)); float4 _expr48 = a; a = (_expr48 + _expr47); - float4 _expr53 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.299999952316284); + float4 _expr53 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3); float4 _expr54 = a; a = (_expr54 + _expr53); - float4 _expr59 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.299999952316284, int2(3, 1)); + float4 _expr59 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3, int2(3, 1)); float4 _expr60 = a; a = (_expr60 + _expr59); float4 _expr66 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0u), 2.0, int2(3, 1)); @@ -286,10 +286,10 @@ float4 texture_sample() : SV_Target0 float4 _expr78 = image_2d_array.Sample(sampler_reg, float3(tc, 0), int2(3, 1)); float4 _expr79 = a; a = (_expr79 + _expr78); - float4 _expr84 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.299999952316284); + float4 _expr84 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3); float4 _expr85 = a; a = (_expr85 + _expr84); - float4 _expr90 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.299999952316284, int2(3, 1)); + float4 _expr90 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3, int2(3, 1)); float4 _expr91 = a; a = (_expr91 + _expr90); float4 _expr97 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0), 2.0, int2(3, 1)); @@ -298,7 +298,7 @@ float4 texture_sample() : SV_Target0 float4 _expr103 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0u)); float4 _expr104 = a; a = (_expr104 + _expr103); - float4 _expr109 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0u), 2.299999952316284); + float4 _expr109 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0u), 2.3); float4 _expr110 = a; a = (_expr110 + _expr109); float4 _expr116 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0u), 2.0); @@ -307,7 +307,7 @@ float4 texture_sample() : SV_Target0 float4 _expr122 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0)); float4 _expr123 = a; a = (_expr123 + _expr122); - float4 _expr128 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0), 2.299999952316284); + float4 _expr128 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0), 2.3); float4 _expr129 = a; a = (_expr129 + _expr128); float4 _expr135 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0), 2.0); diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 73d7211c3..abfbec61e 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -17,7 +17,7 @@ float4 builtins() float4 s2_ = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0)); float4 s3_ = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); - float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.1); float b1_ = asfloat(int4(1, 1, 1, 1).x); float4 b2_ = asfloat(int4(1, 1, 1, 1)); int4 v_i32_zero = int4(float4(0.0, 0.0, 0.0, 0.0)); diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 8b1874601..417a706ff 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -263,7 +263,7 @@ name: None, inner: Array( base: 24, - size: Constant(22), + size: Constant(8), stride: 40, ), ), @@ -290,7 +290,7 @@ name: None, inner: Array( base: 3, - size: Constant(22), + size: Constant(8), stride: 4, ), ), @@ -402,118 +402,6 @@ value: Sint(1), ), ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(1.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(2.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(3.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(6.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(5.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(4.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(9.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(90.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(10.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(20.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(30.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(40.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(8.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(7.0), - ), - ), ( name: None, specialization: None, @@ -522,78 +410,6 @@ value: Sint(5), ), ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(4), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(9), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(0.0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(3), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(2), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(3), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(1), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(42), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(42), - ), - ), ], global_variables: [ ( @@ -677,7 +493,7 @@ ), ], expressions: [ - Constant(7), + Literal(I32(1)), LocalVariable(1), Load( pointer: 2, @@ -701,7 +517,7 @@ base: 9, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 10, index: 0, @@ -729,12 +545,12 @@ base: 19, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 20, index: 0, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 22, index: 1, @@ -747,7 +563,7 @@ base: 26, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 27, index: 0, @@ -774,7 +590,7 @@ base: 34, index: 35, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 36, index: 1, @@ -804,17 +620,17 @@ Load( pointer: 45, ), - Constant(8), + Literal(F32(1.0)), Splat( size: Bi, value: 47, ), - Constant(9), + Literal(F32(2.0)), Splat( size: Bi, value: 49, ), - Constant(10), + Literal(F32(3.0)), Splat( size: Bi, value: 51, @@ -847,17 +663,17 @@ base: 55, index: 0, ), - Constant(11), + Literal(F32(6.0)), Splat( size: Bi, value: 60, ), - Constant(12), + Literal(F32(5.0)), Splat( size: Bi, value: 62, ), - Constant(13), + Literal(F32(4.0)), Splat( size: Bi, value: 64, @@ -874,12 +690,12 @@ base: 55, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 67, index: 0, ), - Constant(14), + Literal(F32(9.0)), Splat( size: Bi, value: 70, @@ -895,7 +711,7 @@ base: 72, index: 73, ), - Constant(15), + Literal(F32(90.0)), Splat( size: Bi, value: 75, @@ -904,22 +720,22 @@ base: 55, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 77, index: 0, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 79, index: 1, ), - Constant(16), + Literal(F32(10.0)), AccessIndex( base: 55, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 83, index: 0, @@ -931,7 +747,7 @@ base: 85, index: 86, ), - Constant(17), + Literal(F32(20.0)), AccessIndex( base: 55, index: 0, @@ -943,12 +759,12 @@ base: 89, index: 90, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 91, index: 1, ), - Constant(18), + Literal(F32(30.0)), AccessIndex( base: 55, index: 0, @@ -967,7 +783,7 @@ base: 97, index: 98, ), - Constant(19), + Literal(F32(40.0)), ], named_expressions: {}, body: [ @@ -1181,7 +997,7 @@ ), ], expressions: [ - Constant(7), + Literal(I32(1)), LocalVariable(1), Load( pointer: 2, @@ -1205,7 +1021,7 @@ base: 9, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 10, index: 0, @@ -1218,12 +1034,12 @@ base: 14, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 15, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 17, index: 0, @@ -1236,7 +1052,7 @@ base: 21, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 22, index: 0, @@ -1256,17 +1072,17 @@ base: 28, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 29, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 31, index: 0, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 33, index: 1, @@ -1279,12 +1095,12 @@ base: 37, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 38, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 40, index: 0, @@ -1304,7 +1120,7 @@ base: 46, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 47, index: 0, @@ -1316,7 +1132,7 @@ base: 49, index: 50, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 51, index: 1, @@ -1329,7 +1145,7 @@ base: 55, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 56, index: 0, @@ -1377,27 +1193,27 @@ base: 66, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 72, index: 0, ), - Constant(20), + Literal(F32(8.0)), Splat( size: Bi, value: 75, ), - Constant(21), + Literal(F32(7.0)), Splat( size: Bi, value: 77, ), - Constant(11), + Literal(F32(6.0)), Splat( size: Bi, value: 79, ), - Constant(12), + Literal(F32(5.0)), Splat( size: Bi, value: 81, @@ -1415,17 +1231,17 @@ base: 66, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 84, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 86, index: 0, ), - Constant(14), + Literal(F32(9.0)), Splat( size: Bi, value: 89, @@ -1434,7 +1250,7 @@ base: 66, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 91, index: 0, @@ -1446,7 +1262,7 @@ base: 93, index: 94, ), - Constant(15), + Literal(F32(90.0)), Splat( size: Bi, value: 96, @@ -1455,32 +1271,32 @@ base: 66, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 98, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 100, index: 0, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 102, index: 1, ), - Constant(16), + Literal(F32(10.0)), AccessIndex( base: 66, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 106, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 108, index: 0, @@ -1492,12 +1308,12 @@ base: 110, index: 111, ), - Constant(17), + Literal(F32(20.0)), AccessIndex( base: 66, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 114, index: 0, @@ -1509,17 +1325,17 @@ base: 116, index: 117, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 118, index: 1, ), - Constant(18), + Literal(F32(30.0)), AccessIndex( base: 66, index: 0, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 122, index: 0, @@ -1538,7 +1354,7 @@ base: 126, index: 127, ), - Constant(19), + Literal(F32(40.0)), ], named_expressions: {}, body: [ @@ -1848,12 +1664,12 @@ local_variables: [], expressions: [ FunctionArgument(0), - Constant(23), + Literal(I32(4)), AccessIndex( base: 1, index: 4, ), - Constant(24), + Literal(I32(9)), AccessIndex( base: 3, index: 9, @@ -1889,7 +1705,7 @@ local_variables: [], expressions: [ FunctionArgument(0), - Constant(31), + Literal(U32(42)), ], named_expressions: { 1: "p", @@ -1917,12 +1733,12 @@ local_variables: [], expressions: [ FunctionArgument(0), - Constant(8), + Literal(F32(1.0)), Splat( size: Quad, value: 2, ), - Constant(9), + Literal(F32(2.0)), Splat( size: Quad, value: 4, @@ -1992,12 +1808,12 @@ ], expressions: [ FunctionArgument(0), - Constant(25), + Literal(F32(0.0)), LocalVariable(1), Load( pointer: 3, ), - Constant(8), + Literal(F32(1.0)), GlobalVariable(2), AccessIndex( base: 6, @@ -2014,7 +1830,7 @@ Load( pointer: 10, ), - Constant(26), + Literal(U32(3)), GlobalVariable(2), AccessIndex( base: 13, @@ -2042,7 +1858,7 @@ index: 5, ), ArrayLength(21), - Constant(27), + Literal(U32(2)), Binary( op: Subtract, left: 22, @@ -2068,7 +1884,7 @@ base: 30, index: 5, ), - Constant(3), + Literal(I32(0)), AccessIndex( base: 31, index: 0, @@ -2083,9 +1899,9 @@ kind: Sint, convert: Some(4), ), - Constant(28), - Constant(23), - Constant(22), + Literal(I32(3)), + Literal(I32(4)), + Literal(I32(5)), Compose( ty: 28, components: [ @@ -2097,7 +1913,7 @@ ], ), LocalVariable(2), - Constant(29), + Literal(U32(1)), Binary( op: Add, left: 1, @@ -2107,7 +1923,7 @@ base: 41, index: 43, ), - Constant(30), + Literal(I32(42)), Access( base: 41, index: 1, @@ -2131,7 +1947,7 @@ left: 8, right: 51, ), - Constant(9), + Literal(F32(2.0)), Compose( ty: 26, components: [ @@ -2287,7 +2103,7 @@ base: 1, index: 0, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 2, index: 1, @@ -2296,28 +2112,28 @@ base: 4, index: 2, ), - Constant(8), + Literal(F32(1.0)), GlobalVariable(2), AccessIndex( base: 7, index: 0, ), - Constant(25), + Literal(F32(0.0)), Splat( size: Tri, value: 9, ), - Constant(8), + Literal(F32(1.0)), Splat( size: Tri, value: 11, ), - Constant(9), + Literal(F32(2.0)), Splat( size: Tri, value: 13, ), - Constant(10), + Literal(F32(3.0)), Splat( size: Tri, value: 15, @@ -2336,12 +2152,12 @@ base: 18, index: 4, ), - Constant(1), + Literal(U32(0)), Splat( size: Bi, value: 20, ), - Constant(29), + Literal(U32(1)), Splat( size: Bi, value: 22, @@ -2358,7 +2174,7 @@ base: 25, index: 5, ), - Constant(7), + Literal(I32(1)), AccessIndex( base: 26, index: 1, @@ -2367,10 +2183,10 @@ base: 28, index: 0, ), - Constant(7), + Literal(I32(1)), GlobalVariable(4), ZeroValue(17), - Constant(25), + Literal(F32(0.0)), Splat( size: Quad, value: 33, @@ -2473,12 +2289,12 @@ ), ], expressions: [ - Constant(11), + Literal(F32(6.0)), Splat( size: Quad, value: 1, ), - Constant(21), + Literal(F32(7.0)), Splat( size: Quad, value: 3, diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 1be31e6ef..a01f07d14 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -42,40 +42,7 @@ ray_desc: None, ray_intersection: None, ), - constants: [ - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(1), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(2), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(3), - ), - ), - ], + constants: [], global_variables: [ ( name: Some("v_indices"), @@ -121,12 +88,12 @@ expressions: [ FunctionArgument(0), LocalVariable(1), - Constant(1), + Literal(U32(0)), LocalVariable(2), Load( pointer: 2, ), - Constant(2), + Literal(U32(1)), Binary( op: Greater, left: 5, @@ -135,13 +102,13 @@ Load( pointer: 2, ), - Constant(3), + Literal(U32(2)), Binary( op: Modulo, left: 8, right: 9, ), - Constant(1), + Literal(U32(0)), Binary( op: Equal, left: 10, @@ -150,13 +117,13 @@ Load( pointer: 2, ), - Constant(3), + Literal(U32(2)), Binary( op: Divide, left: 13, right: 14, ), - Constant(4), + Literal(U32(3)), Load( pointer: 2, ), @@ -165,7 +132,7 @@ left: 16, right: 17, ), - Constant(2), + Literal(U32(1)), Binary( op: Add, left: 18, @@ -174,7 +141,7 @@ Load( pointer: 4, ), - Constant(2), + Literal(U32(1)), Binary( op: Add, left: 21, diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index 2b832c0f2..100a6dc1e 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -135,7 +135,7 @@ kernel void main_( vVel = ((_e112 + (_e113 * _e116)) + (_e119 * _e122)) + (_e125 * _e128); metal::float2 _e131 = vVel; metal::float2 _e133 = vVel; - vVel = metal::normalize(_e131) * metal::clamp(metal::length(_e133), 0.0, 0.10000000149011612); + vVel = metal::normalize(_e131) * metal::clamp(metal::length(_e133), 0.0, 0.1); metal::float2 _e139 = vPos; metal::float2 _e140 = vVel; float _e143 = params.deltaT; diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 685867175..77c0a8679 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -129,10 +129,10 @@ fragment texture_sampleOutput texture_sample( metal::float4 _e19 = image_2d.sample(sampler_reg, tc, const_type_9_); metal::float4 _e20 = a; a = _e20 + _e19; - metal::float4 _e24 = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284)); + metal::float4 _e24 = image_2d.sample(sampler_reg, tc, metal::level(2.3)); metal::float4 _e25 = a; a = _e25 + _e24; - metal::float4 _e29 = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_9_); + metal::float4 _e29 = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type_9_); metal::float4 _e30 = a; a = _e30 + _e29; metal::float4 _e35 = image_2d.sample(sampler_reg, tc, metal::bias(2.0), const_type_9_); @@ -144,10 +144,10 @@ fragment texture_sampleOutput texture_sample( metal::float4 _e47 = image_2d_array.sample(sampler_reg, tc, 0u, const_type_9_); metal::float4 _e48 = a; a = _e48 + _e47; - metal::float4 _e53 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.299999952316284)); + metal::float4 _e53 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3)); metal::float4 _e54 = a; a = _e54 + _e53; - metal::float4 _e59 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.299999952316284), const_type_9_); + metal::float4 _e59 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3), const_type_9_); metal::float4 _e60 = a; a = _e60 + _e59; metal::float4 _e66 = image_2d_array.sample(sampler_reg, tc, 0u, metal::bias(2.0), const_type_9_); @@ -159,10 +159,10 @@ fragment texture_sampleOutput texture_sample( metal::float4 _e78 = image_2d_array.sample(sampler_reg, tc, 0, const_type_9_); metal::float4 _e79 = a; a = _e79 + _e78; - metal::float4 _e84 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.299999952316284)); + metal::float4 _e84 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3)); metal::float4 _e85 = a; a = _e85 + _e84; - metal::float4 _e90 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.299999952316284), const_type_9_); + metal::float4 _e90 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3), const_type_9_); metal::float4 _e91 = a; a = _e91 + _e90; metal::float4 _e97 = image_2d_array.sample(sampler_reg, tc, 0, metal::bias(2.0), const_type_9_); @@ -171,7 +171,7 @@ fragment texture_sampleOutput texture_sample( metal::float4 _e103 = image_cube_array.sample(sampler_reg, tc3_, 0u); metal::float4 _e104 = a; a = _e104 + _e103; - metal::float4 _e109 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::level(2.299999952316284)); + metal::float4 _e109 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::level(2.3)); metal::float4 _e110 = a; a = _e110 + _e109; metal::float4 _e116 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::bias(2.0)); @@ -180,7 +180,7 @@ fragment texture_sampleOutput texture_sample( metal::float4 _e122 = image_cube_array.sample(sampler_reg, tc3_, 0); metal::float4 _e123 = a; a = _e123 + _e122; - metal::float4 _e128 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::level(2.299999952316284)); + metal::float4 _e128 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::level(2.3)); metal::float4 _e129 = a; a = _e129 + _e128; metal::float4 _e135 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::bias(2.0)); diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index e8ae513cb..81f56ff3a 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -25,7 +25,7 @@ metal::float4 builtins( metal::float4 s2_ = true ? v_f32_one : v_f32_zero; metal::float4 s3_ = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false)); metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half); - metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.10000000149011612); + metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.1); float b1_ = as_type(v_i32_one.x); metal::float4 b2_ = as_type(v_i32_one); metal::int4 v_i32_zero = static_cast(v_f32_zero); diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index 7f270e304..f6a4fe5d6 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -43,7 +43,7 @@ metal::float4 mock_function( thread type_6& in_private ) { type_9 in_function = {}; - in_function = type_9 {metal::float4(0.7070000171661377, 0.0, 0.0, 1.0), metal::float4(0.0, 0.7070000171661377, 0.0, 1.0)}; + in_function = type_9 {metal::float4(0.707, 0.0, 0.0, 1.0), metal::float4(0.0, 0.707, 0.0, 1.0)}; metal::float4 _e18 = in_storage.a.inner[i]; metal::float4 _e22 = in_uniform.a.inner[i]; metal::float4 _e25 = (uint(l) < image_2d_array.get_num_mip_levels() && uint(i) < image_2d_array.get_array_size() && metal::all(metal::uint2(c) < metal::uint2(image_2d_array.get_width(l), image_2d_array.get_height(l))) ? image_2d_array.read(metal::uint2(c), i, l): DefaultConstructible()); diff --git a/tests/out/msl/ray-query.msl b/tests/out/msl/ray-query.msl index dc24f8067..0d4560f31 100644 --- a/tests/out/msl/ray-query.msl +++ b/tests/out/msl/ray-query.msl @@ -46,7 +46,7 @@ metal::float3 get_torus_normal( RayIntersection intersection ) { metal::float3 local_point = intersection.world_to_object * metal::float4(world_point, 1.0); - metal::float2 point_on_guiding_line = metal::normalize(local_point.xy) * 2.4000000953674316; + metal::float2 point_on_guiding_line = metal::normalize(local_point.xy) * 2.4; metal::float3 world_point_on_guiding_line = intersection.object_to_world * metal::float4(point_on_guiding_line, 0.0, 1.0); return metal::normalize(world_point - world_point_on_guiding_line); } @@ -57,7 +57,7 @@ kernel void main_( ) { _RayQuery rq = {}; metal::float3 dir = metal::float3(0.0, 1.0, 0.0); - RayDesc _e12 = RayDesc {4u, 255u, 0.10000000149011612, 100.0, metal::float3(0.0), dir}; + RayDesc _e12 = RayDesc {4u, 255u, 0.1, 100.0, metal::float3(0.0), dir}; rq.intersector.assume_geometry_type(metal::raytracing::geometry_type::triangle); rq.intersector.set_opacity_cull_mode((_e12.flags & 64) != 0 ? metal::raytracing::opacity_cull_mode::opaque : (_e12.flags & 128) != 0 ? metal::raytracing::opacity_cull_mode::non_opaque : metal::raytracing::opacity_cull_mode::none); rq.intersector.force_opacity((_e12.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (_e12.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none); diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 18de89ac1..80e248040 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -6,102 +6,102 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %243 "foo_vert" %238 %241 +OpEntryPoint Vertex %238 "foo_vert" %233 %236 OpEntryPoint Fragment %286 "foo_frag" %285 OpEntryPoint GLCompute %306 "assign_through_ptr" %309 OpExecutionMode %286 OriginUpperLeft OpExecutionMode %306 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %36 0 "a" -OpMemberName %36 1 "b" -OpMemberName %36 2 "c" -OpName %36 "GlobalConst" -OpMemberName %37 0 "value" -OpName %37 "AlignedWrapper" -OpMemberName %47 0 "_matrix" -OpMemberName %47 1 "matrix_array" -OpMemberName %47 2 "atom" -OpMemberName %47 3 "atom_arr" -OpMemberName %47 4 "arr" -OpMemberName %47 5 "data" -OpName %47 "Bar" -OpMemberName %49 0 "m" -OpName %49 "Baz" -OpMemberName %53 0 "am" -OpName %53 "MatCx2InArray" -OpName %66 "global_const" -OpName %68 "bar" -OpName %70 "baz" -OpName %73 "qux" -OpName %76 "nested_mat_cx2" -OpName %79 "val" -OpName %80 "idx" -OpName %83 "t" -OpName %87 "test_matrix_within_struct_accesses" -OpName %144 "idx" -OpName %146 "t" -OpName %150 "test_matrix_within_array_within_struct_accesses" -OpName %207 "foo" -OpName %208 "read_from_private" -OpName %213 "a" -OpName %214 "test_arr_as_arg" -OpName %220 "p" -OpName %221 "assign_through_ptr_fn" -OpName %225 "foo" -OpName %226 "assign_array_through_ptr_fn" -OpName %232 "foo" -OpName %234 "c2" -OpName %238 "vi" -OpName %243 "foo_vert" +OpMemberName %12 0 "a" +OpMemberName %12 1 "b" +OpMemberName %12 2 "c" +OpName %12 "GlobalConst" +OpMemberName %13 0 "value" +OpName %13 "AlignedWrapper" +OpMemberName %24 0 "_matrix" +OpMemberName %24 1 "matrix_array" +OpMemberName %24 2 "atom" +OpMemberName %24 3 "atom_arr" +OpMemberName %24 4 "arr" +OpMemberName %24 5 "data" +OpName %24 "Bar" +OpMemberName %26 0 "m" +OpName %26 "Baz" +OpMemberName %30 0 "am" +OpName %30 "MatCx2InArray" +OpName %43 "global_const" +OpName %45 "bar" +OpName %47 "baz" +OpName %50 "qux" +OpName %53 "nested_mat_cx2" +OpName %56 "val" +OpName %57 "idx" +OpName %60 "t" +OpName %64 "test_matrix_within_struct_accesses" +OpName %134 "idx" +OpName %136 "t" +OpName %140 "test_matrix_within_array_within_struct_accesses" +OpName %199 "foo" +OpName %200 "read_from_private" +OpName %205 "a" +OpName %206 "test_arr_as_arg" +OpName %214 "p" +OpName %215 "assign_through_ptr_fn" +OpName %220 "foo" +OpName %221 "assign_array_through_ptr_fn" +OpName %227 "foo" +OpName %229 "c2" +OpName %233 "vi" +OpName %238 "foo_vert" OpName %286 "foo_frag" OpName %303 "arr" OpName %306 "assign_through_ptr" -OpMemberDecorate %36 0 Offset 0 -OpMemberDecorate %36 1 Offset 16 -OpMemberDecorate %36 2 Offset 28 -OpMemberDecorate %37 0 Offset 0 -OpDecorate %42 ArrayStride 16 -OpDecorate %43 ArrayStride 4 -OpDecorate %45 ArrayStride 8 -OpDecorate %46 ArrayStride 8 -OpMemberDecorate %47 0 Offset 0 -OpMemberDecorate %47 0 ColMajor -OpMemberDecorate %47 0 MatrixStride 16 -OpMemberDecorate %47 1 Offset 64 -OpMemberDecorate %47 1 ColMajor -OpMemberDecorate %47 1 MatrixStride 8 -OpMemberDecorate %47 2 Offset 96 -OpMemberDecorate %47 3 Offset 100 -OpMemberDecorate %47 4 Offset 144 -OpMemberDecorate %47 5 Offset 160 -OpMemberDecorate %49 0 Offset 0 -OpMemberDecorate %49 0 ColMajor -OpMemberDecorate %49 0 MatrixStride 8 -OpDecorate %52 ArrayStride 32 -OpMemberDecorate %53 0 Offset 0 -OpMemberDecorate %53 0 ColMajor -OpMemberDecorate %53 0 MatrixStride 8 -OpDecorate %55 ArrayStride 4 -OpDecorate %56 ArrayStride 40 -OpDecorate %59 ArrayStride 4 -OpDecorate %62 ArrayStride 16 -OpDecorate %68 DescriptorSet 0 -OpDecorate %68 Binding 0 -OpDecorate %47 Block -OpDecorate %70 DescriptorSet 0 -OpDecorate %70 Binding 1 -OpDecorate %71 Block -OpMemberDecorate %71 0 Offset 0 -OpDecorate %73 DescriptorSet 0 -OpDecorate %73 Binding 2 -OpDecorate %74 Block -OpMemberDecorate %74 0 Offset 0 -OpDecorate %76 DescriptorSet 0 -OpDecorate %76 Binding 3 -OpDecorate %77 Block -OpMemberDecorate %77 0 Offset 0 -OpDecorate %238 BuiltIn VertexIndex -OpDecorate %241 BuiltIn Position +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 16 +OpMemberDecorate %12 2 Offset 28 +OpMemberDecorate %13 0 Offset 0 +OpDecorate %19 ArrayStride 16 +OpDecorate %20 ArrayStride 4 +OpDecorate %22 ArrayStride 8 +OpDecorate %23 ArrayStride 8 +OpMemberDecorate %24 0 Offset 0 +OpMemberDecorate %24 0 ColMajor +OpMemberDecorate %24 0 MatrixStride 16 +OpMemberDecorate %24 1 Offset 64 +OpMemberDecorate %24 1 ColMajor +OpMemberDecorate %24 1 MatrixStride 8 +OpMemberDecorate %24 2 Offset 96 +OpMemberDecorate %24 3 Offset 100 +OpMemberDecorate %24 4 Offset 144 +OpMemberDecorate %24 5 Offset 160 +OpMemberDecorate %26 0 Offset 0 +OpMemberDecorate %26 0 ColMajor +OpMemberDecorate %26 0 MatrixStride 8 +OpDecorate %29 ArrayStride 32 +OpMemberDecorate %30 0 Offset 0 +OpMemberDecorate %30 0 ColMajor +OpMemberDecorate %30 0 MatrixStride 8 +OpDecorate %32 ArrayStride 4 +OpDecorate %33 ArrayStride 40 +OpDecorate %36 ArrayStride 4 +OpDecorate %39 ArrayStride 16 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 0 +OpDecorate %24 Block +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 1 +OpDecorate %48 Block +OpMemberDecorate %48 0 Offset 0 +OpDecorate %50 DescriptorSet 0 +OpDecorate %50 Binding 2 +OpDecorate %51 Block +OpMemberDecorate %51 0 Offset 0 +OpDecorate %53 DescriptorSet 0 +OpDecorate %53 Binding 3 +OpDecorate %54 Block +OpMemberDecorate %54 0 Offset 0 +OpDecorate %233 BuiltIn VertexIndex +OpDecorate %236 BuiltIn Position OpDecorate %285 Location 0 OpDecorate %309 BuiltIn LocalInvocationId %2 = OpTypeVoid @@ -112,389 +112,389 @@ OpDecorate %309 BuiltIn LocalInvocationId %7 = OpConstant %6 2 %8 = OpConstant %6 10 %9 = OpConstant %6 1 -%11 = OpTypeFloat 32 -%10 = OpConstant %11 1.0 -%12 = OpConstant %11 2.0 -%13 = OpConstant %11 3.0 -%14 = OpConstant %11 6.0 -%15 = OpConstant %11 5.0 -%16 = OpConstant %11 4.0 -%17 = OpConstant %11 9.0 -%18 = OpConstant %11 90.0 -%19 = OpConstant %11 10.0 -%20 = OpConstant %11 20.0 -%21 = OpConstant %11 30.0 -%22 = OpConstant %11 40.0 -%23 = OpConstant %11 8.0 -%24 = OpConstant %11 7.0 -%25 = OpConstant %6 5 -%26 = OpConstant %6 4 -%27 = OpConstant %6 9 -%28 = OpConstant %11 0.0 -%29 = OpConstant %4 3 -%30 = OpConstant %4 2 -%31 = OpConstant %6 3 -%32 = OpConstant %4 1 -%33 = OpConstant %6 42 -%34 = OpConstant %4 42 -%35 = OpTypeVector %4 3 -%36 = OpTypeStruct %4 %35 %6 -%37 = OpTypeStruct %6 -%39 = OpTypeVector %11 3 -%38 = OpTypeMatrix %39 4 -%41 = OpTypeVector %11 2 -%40 = OpTypeMatrix %41 2 -%42 = OpTypeArray %40 %7 -%43 = OpTypeArray %6 %8 -%44 = OpTypeVector %4 2 -%45 = OpTypeArray %44 %7 -%46 = OpTypeRuntimeArray %37 -%47 = OpTypeStruct %38 %42 %6 %43 %45 %46 -%48 = OpTypeMatrix %41 3 -%49 = OpTypeStruct %48 -%50 = OpTypeVector %6 2 -%51 = OpTypeMatrix %41 4 -%52 = OpTypeArray %51 %7 -%53 = OpTypeStruct %52 -%54 = OpTypePointer Function %11 -%55 = OpTypeArray %11 %8 -%56 = OpTypeArray %55 %25 -%57 = OpTypeVector %11 4 -%58 = OpTypePointer StorageBuffer %6 -%59 = OpTypeArray %6 %25 -%60 = OpTypeVector %6 4 -%61 = OpTypePointer Workgroup %4 -%62 = OpTypeArray %57 %7 -%63 = OpTypePointer Function %62 -%64 = OpConstantComposite %35 %3 %3 %3 -%65 = OpConstantComposite %36 %3 %64 %5 -%67 = OpTypePointer Private %36 -%66 = OpVariable %67 Private %65 -%69 = OpTypePointer StorageBuffer %47 -%68 = OpVariable %69 StorageBuffer -%71 = OpTypeStruct %49 -%72 = OpTypePointer Uniform %71 -%70 = OpVariable %72 Uniform -%74 = OpTypeStruct %50 -%75 = OpTypePointer StorageBuffer %74 -%73 = OpVariable %75 StorageBuffer -%77 = OpTypeStruct %53 -%78 = OpTypePointer Uniform %77 -%76 = OpVariable %78 Uniform -%79 = OpVariable %61 Workgroup -%81 = OpTypePointer Function %6 -%82 = OpConstantNull %6 -%84 = OpTypePointer Function %49 -%85 = OpConstantNull %49 -%88 = OpTypeFunction %2 -%89 = OpTypePointer Uniform %49 -%94 = OpTypePointer Uniform %48 -%97 = OpTypePointer Uniform %41 -%103 = OpTypePointer Uniform %11 -%123 = OpTypePointer Function %48 -%129 = OpTypePointer Function %41 -%135 = OpTypePointer Function %11 -%145 = OpConstantNull %6 -%147 = OpTypePointer Function %53 -%148 = OpConstantNull %53 -%151 = OpTypePointer Uniform %53 -%153 = OpConstantNull %52 -%154 = OpConstantNull %52 -%158 = OpTypePointer Uniform %52 -%161 = OpTypePointer Uniform %51 -%184 = OpTypePointer Function %52 -%186 = OpTypePointer Function %51 -%209 = OpTypeFunction %11 %54 -%215 = OpTypeFunction %11 %56 -%222 = OpTypeFunction %2 %61 -%227 = OpTypeFunction %2 %63 -%233 = OpConstantNull %11 -%235 = OpTypePointer Function %59 -%236 = OpConstantNull %59 -%239 = OpTypePointer Input %4 -%238 = OpVariable %239 Input -%242 = OpTypePointer Output %57 -%241 = OpVariable %242 Output -%245 = OpTypePointer StorageBuffer %50 -%248 = OpConstantNull %56 -%253 = OpTypePointer StorageBuffer %38 -%256 = OpTypePointer StorageBuffer %45 +%10 = OpConstant %6 5 +%11 = OpTypeVector %4 3 +%12 = OpTypeStruct %4 %11 %6 +%13 = OpTypeStruct %6 +%16 = OpTypeFloat 32 +%15 = OpTypeVector %16 3 +%14 = OpTypeMatrix %15 4 +%18 = OpTypeVector %16 2 +%17 = OpTypeMatrix %18 2 +%19 = OpTypeArray %17 %7 +%20 = OpTypeArray %6 %8 +%21 = OpTypeVector %4 2 +%22 = OpTypeArray %21 %7 +%23 = OpTypeRuntimeArray %13 +%24 = OpTypeStruct %14 %19 %6 %20 %22 %23 +%25 = OpTypeMatrix %18 3 +%26 = OpTypeStruct %25 +%27 = OpTypeVector %6 2 +%28 = OpTypeMatrix %18 4 +%29 = OpTypeArray %28 %7 +%30 = OpTypeStruct %29 +%31 = OpTypePointer Function %16 +%32 = OpTypeArray %16 %8 +%33 = OpTypeArray %32 %10 +%34 = OpTypeVector %16 4 +%35 = OpTypePointer StorageBuffer %6 +%36 = OpTypeArray %6 %10 +%37 = OpTypeVector %6 4 +%38 = OpTypePointer Workgroup %4 +%39 = OpTypeArray %34 %7 +%40 = OpTypePointer Function %39 +%41 = OpConstantComposite %11 %3 %3 %3 +%42 = OpConstantComposite %12 %3 %41 %5 +%44 = OpTypePointer Private %12 +%43 = OpVariable %44 Private %42 +%46 = OpTypePointer StorageBuffer %24 +%45 = OpVariable %46 StorageBuffer +%48 = OpTypeStruct %26 +%49 = OpTypePointer Uniform %48 +%47 = OpVariable %49 Uniform +%51 = OpTypeStruct %27 +%52 = OpTypePointer StorageBuffer %51 +%50 = OpVariable %52 StorageBuffer +%54 = OpTypeStruct %30 +%55 = OpTypePointer Uniform %54 +%53 = OpVariable %55 Uniform +%56 = OpVariable %38 Workgroup +%58 = OpTypePointer Function %6 +%59 = OpConstantNull %6 +%61 = OpTypePointer Function %26 +%62 = OpConstantNull %26 +%65 = OpTypeFunction %2 +%66 = OpTypePointer Uniform %26 +%68 = OpConstant %16 1.0 +%69 = OpConstant %16 2.0 +%70 = OpConstant %16 3.0 +%71 = OpConstant %16 6.0 +%72 = OpConstant %16 5.0 +%73 = OpConstant %16 4.0 +%74 = OpConstant %16 9.0 +%75 = OpConstant %16 90.0 +%76 = OpConstant %16 10.0 +%77 = OpConstant %16 20.0 +%78 = OpConstant %16 30.0 +%79 = OpConstant %16 40.0 +%83 = OpTypePointer Uniform %25 +%86 = OpTypePointer Uniform %18 +%92 = OpTypePointer Uniform %16 +%93 = OpConstant %4 1 +%113 = OpTypePointer Function %25 +%119 = OpTypePointer Function %18 +%125 = OpTypePointer Function %16 +%135 = OpConstantNull %6 +%137 = OpTypePointer Function %30 +%138 = OpConstantNull %30 +%141 = OpTypePointer Uniform %30 +%143 = OpConstantNull %29 +%144 = OpConstantNull %29 +%145 = OpConstant %16 8.0 +%146 = OpConstant %16 7.0 +%150 = OpTypePointer Uniform %29 +%153 = OpTypePointer Uniform %28 +%176 = OpTypePointer Function %29 +%178 = OpTypePointer Function %28 +%201 = OpTypeFunction %16 %31 +%207 = OpTypeFunction %16 %33 +%208 = OpConstant %6 4 +%209 = OpConstant %6 9 +%216 = OpTypeFunction %2 %38 +%217 = OpConstant %4 42 +%222 = OpTypeFunction %2 %40 +%228 = OpConstantNull %16 +%230 = OpTypePointer Function %36 +%231 = OpConstantNull %36 +%234 = OpTypePointer Input %4 +%233 = OpVariable %234 Input +%237 = OpTypePointer Output %34 +%236 = OpVariable %237 Output +%240 = OpTypePointer StorageBuffer %27 +%243 = OpConstant %16 0.0 +%244 = OpConstant %4 3 +%245 = OpConstant %4 2 +%246 = OpConstant %6 3 +%247 = OpConstant %6 42 +%248 = OpConstantNull %33 +%253 = OpTypePointer StorageBuffer %14 +%256 = OpTypePointer StorageBuffer %22 %257 = OpConstant %4 4 -%260 = OpTypePointer StorageBuffer %39 -%261 = OpTypePointer StorageBuffer %11 -%264 = OpTypePointer StorageBuffer %46 -%267 = OpTypePointer StorageBuffer %37 +%260 = OpTypePointer StorageBuffer %15 +%261 = OpTypePointer StorageBuffer %16 +%264 = OpTypePointer StorageBuffer %23 +%267 = OpTypePointer StorageBuffer %13 %268 = OpConstant %4 5 -%285 = OpVariable %242 Output -%288 = OpConstantNull %50 -%304 = OpConstantNull %62 +%285 = OpVariable %237 Output +%288 = OpConstantNull %27 +%304 = OpConstantNull %39 %308 = OpConstantNull %4 -%310 = OpTypePointer Input %35 +%310 = OpTypePointer Input %11 %309 = OpVariable %310 Input -%312 = OpConstantNull %35 +%312 = OpConstantNull %11 %314 = OpTypeBool %313 = OpTypeVector %314 3 %319 = OpConstant %4 264 -%87 = OpFunction %2 None %88 -%86 = OpLabel -%80 = OpVariable %81 Function %82 -%83 = OpVariable %84 Function %85 -%90 = OpAccessChain %89 %70 %3 -OpBranch %91 -%91 = OpLabel -OpStore %80 %9 -%92 = OpLoad %6 %80 -%93 = OpISub %6 %92 %9 -OpStore %80 %93 -%95 = OpAccessChain %94 %90 %3 -%96 = OpLoad %48 %95 -%98 = OpAccessChain %97 %90 %3 %3 -%99 = OpLoad %41 %98 -%100 = OpLoad %6 %80 -%101 = OpAccessChain %97 %90 %3 %100 -%102 = OpLoad %41 %101 -%104 = OpAccessChain %103 %90 %3 %3 %32 -%105 = OpLoad %11 %104 -%106 = OpLoad %6 %80 -%107 = OpAccessChain %103 %90 %3 %3 %106 -%108 = OpLoad %11 %107 -%109 = OpLoad %6 %80 -%110 = OpAccessChain %103 %90 %3 %109 %32 -%111 = OpLoad %11 %110 -%112 = OpLoad %6 %80 -%113 = OpLoad %6 %80 -%114 = OpAccessChain %103 %90 %3 %112 %113 -%115 = OpLoad %11 %114 -%116 = OpCompositeConstruct %41 %10 %10 -%117 = OpCompositeConstruct %41 %12 %12 -%118 = OpCompositeConstruct %41 %13 %13 -%119 = OpCompositeConstruct %48 %116 %117 %118 -%120 = OpCompositeConstruct %49 %119 -OpStore %83 %120 -%121 = OpLoad %6 %80 -%122 = OpIAdd %6 %121 %9 -OpStore %80 %122 -%124 = OpCompositeConstruct %41 %14 %14 -%125 = OpCompositeConstruct %41 %15 %15 -%126 = OpCompositeConstruct %41 %16 %16 -%127 = OpCompositeConstruct %48 %124 %125 %126 -%128 = OpAccessChain %123 %83 %3 -OpStore %128 %127 -%130 = OpCompositeConstruct %41 %17 %17 -%131 = OpAccessChain %129 %83 %3 %3 -OpStore %131 %130 -%132 = OpLoad %6 %80 -%133 = OpCompositeConstruct %41 %18 %18 -%134 = OpAccessChain %129 %83 %3 %132 -OpStore %134 %133 -%136 = OpAccessChain %135 %83 %3 %3 %32 -OpStore %136 %19 -%137 = OpLoad %6 %80 -%138 = OpAccessChain %135 %83 %3 %3 %137 -OpStore %138 %20 -%139 = OpLoad %6 %80 -%140 = OpAccessChain %135 %83 %3 %139 %32 -OpStore %140 %21 -%141 = OpLoad %6 %80 -%142 = OpLoad %6 %80 -%143 = OpAccessChain %135 %83 %3 %141 %142 -OpStore %143 %22 +%64 = OpFunction %2 None %65 +%63 = OpLabel +%57 = OpVariable %58 Function %59 +%60 = OpVariable %61 Function %62 +%67 = OpAccessChain %66 %47 %3 +OpBranch %80 +%80 = OpLabel +OpStore %57 %9 +%81 = OpLoad %6 %57 +%82 = OpISub %6 %81 %9 +OpStore %57 %82 +%84 = OpAccessChain %83 %67 %3 +%85 = OpLoad %25 %84 +%87 = OpAccessChain %86 %67 %3 %3 +%88 = OpLoad %18 %87 +%89 = OpLoad %6 %57 +%90 = OpAccessChain %86 %67 %3 %89 +%91 = OpLoad %18 %90 +%94 = OpAccessChain %92 %67 %3 %3 %93 +%95 = OpLoad %16 %94 +%96 = OpLoad %6 %57 +%97 = OpAccessChain %92 %67 %3 %3 %96 +%98 = OpLoad %16 %97 +%99 = OpLoad %6 %57 +%100 = OpAccessChain %92 %67 %3 %99 %93 +%101 = OpLoad %16 %100 +%102 = OpLoad %6 %57 +%103 = OpLoad %6 %57 +%104 = OpAccessChain %92 %67 %3 %102 %103 +%105 = OpLoad %16 %104 +%106 = OpCompositeConstruct %18 %68 %68 +%107 = OpCompositeConstruct %18 %69 %69 +%108 = OpCompositeConstruct %18 %70 %70 +%109 = OpCompositeConstruct %25 %106 %107 %108 +%110 = OpCompositeConstruct %26 %109 +OpStore %60 %110 +%111 = OpLoad %6 %57 +%112 = OpIAdd %6 %111 %9 +OpStore %57 %112 +%114 = OpCompositeConstruct %18 %71 %71 +%115 = OpCompositeConstruct %18 %72 %72 +%116 = OpCompositeConstruct %18 %73 %73 +%117 = OpCompositeConstruct %25 %114 %115 %116 +%118 = OpAccessChain %113 %60 %3 +OpStore %118 %117 +%120 = OpCompositeConstruct %18 %74 %74 +%121 = OpAccessChain %119 %60 %3 %3 +OpStore %121 %120 +%122 = OpLoad %6 %57 +%123 = OpCompositeConstruct %18 %75 %75 +%124 = OpAccessChain %119 %60 %3 %122 +OpStore %124 %123 +%126 = OpAccessChain %125 %60 %3 %3 %93 +OpStore %126 %76 +%127 = OpLoad %6 %57 +%128 = OpAccessChain %125 %60 %3 %3 %127 +OpStore %128 %77 +%129 = OpLoad %6 %57 +%130 = OpAccessChain %125 %60 %3 %129 %93 +OpStore %130 %78 +%131 = OpLoad %6 %57 +%132 = OpLoad %6 %57 +%133 = OpAccessChain %125 %60 %3 %131 %132 +OpStore %133 %79 OpReturn OpFunctionEnd -%150 = OpFunction %2 None %88 -%149 = OpLabel -%144 = OpVariable %81 Function %145 -%146 = OpVariable %147 Function %148 -%152 = OpAccessChain %151 %76 %3 -OpBranch %155 -%155 = OpLabel -OpStore %144 %9 -%156 = OpLoad %6 %144 -%157 = OpISub %6 %156 %9 -OpStore %144 %157 -%159 = OpAccessChain %158 %152 %3 -%160 = OpLoad %52 %159 -%162 = OpAccessChain %161 %152 %3 %3 -%163 = OpLoad %51 %162 -%164 = OpAccessChain %97 %152 %3 %3 %3 -%165 = OpLoad %41 %164 -%166 = OpLoad %6 %144 -%167 = OpAccessChain %97 %152 %3 %3 %166 -%168 = OpLoad %41 %167 -%169 = OpAccessChain %103 %152 %3 %3 %3 %32 -%170 = OpLoad %11 %169 -%171 = OpLoad %6 %144 -%172 = OpAccessChain %103 %152 %3 %3 %3 %171 -%173 = OpLoad %11 %172 -%174 = OpLoad %6 %144 -%175 = OpAccessChain %103 %152 %3 %3 %174 %32 -%176 = OpLoad %11 %175 -%177 = OpLoad %6 %144 -%178 = OpLoad %6 %144 -%179 = OpAccessChain %103 %152 %3 %3 %177 %178 -%180 = OpLoad %11 %179 -%181 = OpCompositeConstruct %53 %153 -OpStore %146 %181 -%182 = OpLoad %6 %144 -%183 = OpIAdd %6 %182 %9 -OpStore %144 %183 -%185 = OpAccessChain %184 %146 %3 -OpStore %185 %154 -%187 = OpCompositeConstruct %41 %23 %23 -%188 = OpCompositeConstruct %41 %24 %24 -%189 = OpCompositeConstruct %41 %14 %14 -%190 = OpCompositeConstruct %41 %15 %15 -%191 = OpCompositeConstruct %51 %187 %188 %189 %190 -%192 = OpAccessChain %186 %146 %3 %3 -OpStore %192 %191 -%193 = OpCompositeConstruct %41 %17 %17 -%194 = OpAccessChain %129 %146 %3 %3 %3 -OpStore %194 %193 -%195 = OpLoad %6 %144 -%196 = OpCompositeConstruct %41 %18 %18 -%197 = OpAccessChain %129 %146 %3 %3 %195 -OpStore %197 %196 -%198 = OpAccessChain %135 %146 %3 %3 %3 %32 -OpStore %198 %19 -%199 = OpLoad %6 %144 -%200 = OpAccessChain %135 %146 %3 %3 %3 %199 -OpStore %200 %20 -%201 = OpLoad %6 %144 -%202 = OpAccessChain %135 %146 %3 %3 %201 %32 -OpStore %202 %21 -%203 = OpLoad %6 %144 -%204 = OpLoad %6 %144 -%205 = OpAccessChain %135 %146 %3 %3 %203 %204 -OpStore %205 %22 +%140 = OpFunction %2 None %65 +%139 = OpLabel +%134 = OpVariable %58 Function %135 +%136 = OpVariable %137 Function %138 +%142 = OpAccessChain %141 %53 %3 +OpBranch %147 +%147 = OpLabel +OpStore %134 %9 +%148 = OpLoad %6 %134 +%149 = OpISub %6 %148 %9 +OpStore %134 %149 +%151 = OpAccessChain %150 %142 %3 +%152 = OpLoad %29 %151 +%154 = OpAccessChain %153 %142 %3 %3 +%155 = OpLoad %28 %154 +%156 = OpAccessChain %86 %142 %3 %3 %3 +%157 = OpLoad %18 %156 +%158 = OpLoad %6 %134 +%159 = OpAccessChain %86 %142 %3 %3 %158 +%160 = OpLoad %18 %159 +%161 = OpAccessChain %92 %142 %3 %3 %3 %93 +%162 = OpLoad %16 %161 +%163 = OpLoad %6 %134 +%164 = OpAccessChain %92 %142 %3 %3 %3 %163 +%165 = OpLoad %16 %164 +%166 = OpLoad %6 %134 +%167 = OpAccessChain %92 %142 %3 %3 %166 %93 +%168 = OpLoad %16 %167 +%169 = OpLoad %6 %134 +%170 = OpLoad %6 %134 +%171 = OpAccessChain %92 %142 %3 %3 %169 %170 +%172 = OpLoad %16 %171 +%173 = OpCompositeConstruct %30 %143 +OpStore %136 %173 +%174 = OpLoad %6 %134 +%175 = OpIAdd %6 %174 %9 +OpStore %134 %175 +%177 = OpAccessChain %176 %136 %3 +OpStore %177 %144 +%179 = OpCompositeConstruct %18 %145 %145 +%180 = OpCompositeConstruct %18 %146 %146 +%181 = OpCompositeConstruct %18 %71 %71 +%182 = OpCompositeConstruct %18 %72 %72 +%183 = OpCompositeConstruct %28 %179 %180 %181 %182 +%184 = OpAccessChain %178 %136 %3 %3 +OpStore %184 %183 +%185 = OpCompositeConstruct %18 %74 %74 +%186 = OpAccessChain %119 %136 %3 %3 %3 +OpStore %186 %185 +%187 = OpLoad %6 %134 +%188 = OpCompositeConstruct %18 %75 %75 +%189 = OpAccessChain %119 %136 %3 %3 %187 +OpStore %189 %188 +%190 = OpAccessChain %125 %136 %3 %3 %3 %93 +OpStore %190 %76 +%191 = OpLoad %6 %134 +%192 = OpAccessChain %125 %136 %3 %3 %3 %191 +OpStore %192 %77 +%193 = OpLoad %6 %134 +%194 = OpAccessChain %125 %136 %3 %3 %193 %93 +OpStore %194 %78 +%195 = OpLoad %6 %134 +%196 = OpLoad %6 %134 +%197 = OpAccessChain %125 %136 %3 %3 %195 %196 +OpStore %197 %79 OpReturn OpFunctionEnd -%208 = OpFunction %11 None %209 -%207 = OpFunctionParameter %54 -%206 = OpLabel +%200 = OpFunction %16 None %201 +%199 = OpFunctionParameter %31 +%198 = OpLabel +OpBranch %202 +%202 = OpLabel +%203 = OpLoad %16 %199 +OpReturnValue %203 +OpFunctionEnd +%206 = OpFunction %16 None %207 +%205 = OpFunctionParameter %33 +%204 = OpLabel OpBranch %210 %210 = OpLabel -%211 = OpLoad %11 %207 -OpReturnValue %211 +%211 = OpCompositeExtract %32 %205 4 +%212 = OpCompositeExtract %16 %211 9 +OpReturnValue %212 OpFunctionEnd -%214 = OpFunction %11 None %215 -%213 = OpFunctionParameter %56 -%212 = OpLabel -OpBranch %216 -%216 = OpLabel -%217 = OpCompositeExtract %55 %213 4 -%218 = OpCompositeExtract %11 %217 9 -OpReturnValue %218 +%215 = OpFunction %2 None %216 +%214 = OpFunctionParameter %38 +%213 = OpLabel +OpBranch %218 +%218 = OpLabel +OpStore %214 %217 +OpReturn OpFunctionEnd %221 = OpFunction %2 None %222 -%220 = OpFunctionParameter %61 +%220 = OpFunctionParameter %40 %219 = OpLabel OpBranch %223 %223 = OpLabel -OpStore %220 %34 +%224 = OpCompositeConstruct %34 %68 %68 %68 %68 +%225 = OpCompositeConstruct %34 %69 %69 %69 %69 +%226 = OpCompositeConstruct %39 %224 %225 +OpStore %220 %226 OpReturn OpFunctionEnd -%226 = OpFunction %2 None %227 -%225 = OpFunctionParameter %63 -%224 = OpLabel -OpBranch %228 -%228 = OpLabel -%229 = OpCompositeConstruct %57 %10 %10 %10 %10 -%230 = OpCompositeConstruct %57 %12 %12 %12 %12 -%231 = OpCompositeConstruct %62 %229 %230 -OpStore %225 %231 -OpReturn -OpFunctionEnd -%243 = OpFunction %2 None %88 -%237 = OpLabel -%232 = OpVariable %54 Function %233 -%234 = OpVariable %235 Function %236 -%240 = OpLoad %4 %238 -%244 = OpAccessChain %89 %70 %3 -%246 = OpAccessChain %245 %73 %3 -%247 = OpAccessChain %151 %76 %3 +%238 = OpFunction %2 None %65 +%232 = OpLabel +%227 = OpVariable %31 Function %228 +%229 = OpVariable %230 Function %231 +%235 = OpLoad %4 %233 +%239 = OpAccessChain %66 %47 %3 +%241 = OpAccessChain %240 %50 %3 +%242 = OpAccessChain %141 %53 %3 OpBranch %249 %249 = OpLabel -OpStore %232 %28 -%250 = OpLoad %11 %232 -OpStore %232 %10 -%251 = OpFunctionCall %2 %87 -%252 = OpFunctionCall %2 %150 -%254 = OpAccessChain %253 %68 %3 -%255 = OpLoad %38 %254 -%258 = OpAccessChain %256 %68 %257 -%259 = OpLoad %45 %258 -%262 = OpAccessChain %261 %68 %3 %29 %3 -%263 = OpLoad %11 %262 -%265 = OpArrayLength %4 %68 5 -%266 = OpISub %4 %265 %30 -%269 = OpAccessChain %58 %68 %268 %266 %3 +OpStore %227 %243 +%250 = OpLoad %16 %227 +OpStore %227 %68 +%251 = OpFunctionCall %2 %64 +%252 = OpFunctionCall %2 %140 +%254 = OpAccessChain %253 %45 %3 +%255 = OpLoad %14 %254 +%258 = OpAccessChain %256 %45 %257 +%259 = OpLoad %22 %258 +%262 = OpAccessChain %261 %45 %3 %244 %3 +%263 = OpLoad %16 %262 +%265 = OpArrayLength %4 %45 5 +%266 = OpISub %4 %265 %245 +%269 = OpAccessChain %35 %45 %268 %266 %3 %270 = OpLoad %6 %269 -%271 = OpLoad %50 %246 -%272 = OpFunctionCall %11 %208 %232 +%271 = OpLoad %27 %241 +%272 = OpFunctionCall %16 %200 %227 %273 = OpConvertFToS %6 %263 -%274 = OpCompositeConstruct %59 %270 %273 %31 %26 %25 -OpStore %234 %274 -%275 = OpIAdd %4 %240 %32 -%276 = OpAccessChain %81 %234 %275 -OpStore %276 %33 -%277 = OpAccessChain %81 %234 %240 +%274 = OpCompositeConstruct %36 %270 %273 %246 %208 %10 +OpStore %229 %274 +%275 = OpIAdd %4 %235 %93 +%276 = OpAccessChain %58 %229 %275 +OpStore %276 %247 +%277 = OpAccessChain %58 %229 %235 %278 = OpLoad %6 %277 -%279 = OpFunctionCall %11 %214 %248 -%280 = OpCompositeConstruct %60 %278 %278 %278 %278 -%281 = OpConvertSToF %57 %280 -%282 = OpMatrixTimesVector %39 %255 %281 -%283 = OpCompositeConstruct %57 %282 %12 -OpStore %241 %283 +%279 = OpFunctionCall %16 %206 %248 +%280 = OpCompositeConstruct %37 %278 %278 %278 %278 +%281 = OpConvertSToF %34 %280 +%282 = OpMatrixTimesVector %15 %255 %281 +%283 = OpCompositeConstruct %34 %282 %69 +OpStore %236 %283 OpReturn OpFunctionEnd -%286 = OpFunction %2 None %88 +%286 = OpFunction %2 None %65 %284 = OpLabel -%287 = OpAccessChain %245 %73 %3 +%287 = OpAccessChain %240 %50 %3 OpBranch %289 %289 = OpLabel -%290 = OpAccessChain %261 %68 %3 %32 %30 -OpStore %290 %10 -%291 = OpCompositeConstruct %39 %28 %28 %28 -%292 = OpCompositeConstruct %39 %10 %10 %10 -%293 = OpCompositeConstruct %39 %12 %12 %12 -%294 = OpCompositeConstruct %39 %13 %13 %13 -%295 = OpCompositeConstruct %38 %291 %292 %293 %294 -%296 = OpAccessChain %253 %68 %3 +%290 = OpAccessChain %261 %45 %3 %93 %245 +OpStore %290 %68 +%291 = OpCompositeConstruct %15 %243 %243 %243 +%292 = OpCompositeConstruct %15 %68 %68 %68 +%293 = OpCompositeConstruct %15 %69 %69 %69 +%294 = OpCompositeConstruct %15 %70 %70 %70 +%295 = OpCompositeConstruct %14 %291 %292 %293 %294 +%296 = OpAccessChain %253 %45 %3 OpStore %296 %295 -%297 = OpCompositeConstruct %44 %3 %3 -%298 = OpCompositeConstruct %44 %32 %32 -%299 = OpCompositeConstruct %45 %297 %298 -%300 = OpAccessChain %256 %68 %257 +%297 = OpCompositeConstruct %21 %3 %3 +%298 = OpCompositeConstruct %21 %93 %93 +%299 = OpCompositeConstruct %22 %297 %298 +%300 = OpAccessChain %256 %45 %257 OpStore %300 %299 -%301 = OpAccessChain %58 %68 %268 %32 %3 +%301 = OpAccessChain %35 %45 %268 %93 %3 OpStore %301 %9 OpStore %287 %288 -%302 = OpCompositeConstruct %57 %28 %28 %28 %28 +%302 = OpCompositeConstruct %34 %243 %243 %243 %243 OpStore %285 %302 OpReturn OpFunctionEnd -%306 = OpFunction %2 None %88 +%306 = OpFunction %2 None %65 %305 = OpLabel -%303 = OpVariable %63 Function %304 +%303 = OpVariable %40 Function %304 OpBranch %307 %307 = OpLabel -%311 = OpLoad %35 %309 +%311 = OpLoad %11 %309 %315 = OpIEqual %313 %311 %312 %316 = OpAll %314 %315 OpSelectionMerge %317 None OpBranchConditional %316 %318 %317 %318 = OpLabel -OpStore %79 %308 +OpStore %56 %308 OpBranch %317 %317 = OpLabel -OpControlBarrier %30 %30 %319 +OpControlBarrier %245 %245 %319 OpBranch %320 %320 = OpLabel -%321 = OpCompositeConstruct %57 %14 %14 %14 %14 -%322 = OpCompositeConstruct %57 %24 %24 %24 %24 -%323 = OpCompositeConstruct %62 %321 %322 +%321 = OpCompositeConstruct %34 %71 %71 %71 %71 +%322 = OpCompositeConstruct %34 %146 %146 %146 %146 +%323 = OpCompositeConstruct %39 %321 %322 OpStore %303 %323 -%324 = OpFunctionCall %2 %221 %79 -%325 = OpFunctionCall %2 %226 %303 +%324 = OpFunctionCall %2 %215 %56 +%325 = OpFunctionCall %2 %221 %303 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/tests/out/spv/atomicCompareExchange.spvasm index 5af859324..1269436ed 100644 --- a/tests/out/spv/atomicCompareExchange.spvasm +++ b/tests/out/spv/atomicCompareExchange.spvasm @@ -6,76 +6,76 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %32 "test_atomic_compare_exchange_i32" +OpEntryPoint GLCompute %29 "test_atomic_compare_exchange_i32" OpEntryPoint GLCompute %84 "test_atomic_compare_exchange_u32" -OpExecutionMode %32 LocalSize 1 1 1 +OpExecutionMode %29 LocalSize 1 1 1 OpExecutionMode %84 LocalSize 1 1 1 -OpDecorate %12 ArrayStride 4 -OpDecorate %13 ArrayStride 4 +OpDecorate %7 ArrayStride 4 +OpDecorate %8 ArrayStride 4 +OpMemberDecorate %11 0 Offset 0 +OpMemberDecorate %11 1 Offset 4 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 4 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 0 +OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 1 Offset 4 -OpMemberDecorate %15 0 Offset 0 -OpMemberDecorate %15 1 Offset 4 OpDecorate %16 DescriptorSet 0 -OpDecorate %16 Binding 0 +OpDecorate %16 Binding 1 OpDecorate %17 Block OpMemberDecorate %17 0 Offset 0 -OpDecorate %19 DescriptorSet 0 -OpDecorate %19 Binding 1 -OpDecorate %20 Block -OpMemberDecorate %20 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 128 -%5 = OpConstant %4 0 -%7 = OpTypeBool -%6 = OpConstantFalse %7 -%9 = OpTypeFloat 32 -%8 = OpConstant %9 1.0 -%10 = OpConstant %4 1 -%11 = OpTypeInt 32 1 -%12 = OpTypeArray %11 %3 -%13 = OpTypeArray %4 %3 -%14 = OpTypeStruct %11 %7 -%15 = OpTypeStruct %4 %7 -%17 = OpTypeStruct %12 +%5 = OpConstant %4 1 +%6 = OpTypeInt 32 1 +%7 = OpTypeArray %6 %3 +%8 = OpTypeArray %4 %3 +%9 = OpTypeBool +%10 = OpTypeFloat 32 +%11 = OpTypeStruct %6 %9 +%12 = OpTypeStruct %4 %9 +%14 = OpTypeStruct %7 +%15 = OpTypePointer StorageBuffer %14 +%13 = OpVariable %15 StorageBuffer +%17 = OpTypeStruct %8 %18 = OpTypePointer StorageBuffer %17 %16 = OpVariable %18 StorageBuffer -%20 = OpTypeStruct %13 -%21 = OpTypePointer StorageBuffer %20 -%19 = OpVariable %21 StorageBuffer -%23 = OpTypePointer Function %4 -%24 = OpConstantNull %4 -%26 = OpTypePointer Function %11 -%27 = OpConstantNull %11 -%29 = OpTypePointer Function %7 -%30 = OpConstantNull %7 -%33 = OpTypeFunction %2 -%34 = OpTypePointer StorageBuffer %12 -%48 = OpTypePointer StorageBuffer %11 -%51 = OpConstant %11 1 +%20 = OpTypePointer Function %4 +%21 = OpConstantNull %4 +%23 = OpTypePointer Function %6 +%24 = OpConstantNull %6 +%26 = OpTypePointer Function %9 +%27 = OpConstantNull %9 +%30 = OpTypeFunction %2 +%31 = OpTypePointer StorageBuffer %7 +%32 = OpConstant %4 0 +%34 = OpConstantFalse %9 +%35 = OpConstant %10 1.0 +%48 = OpTypePointer StorageBuffer %6 +%51 = OpConstant %6 1 %52 = OpConstant %4 64 %78 = OpConstantNull %4 %80 = OpConstantNull %4 -%82 = OpConstantNull %7 -%85 = OpTypePointer StorageBuffer %13 +%82 = OpConstantNull %9 +%85 = OpTypePointer StorageBuffer %8 %99 = OpTypePointer StorageBuffer %4 -%32 = OpFunction %2 None %33 -%31 = OpLabel +%29 = OpFunction %2 None %30 +%28 = OpLabel +%19 = OpVariable %20 Function %21 %22 = OpVariable %23 Function %24 %25 = OpVariable %26 Function %27 -%28 = OpVariable %29 Function %30 -%35 = OpAccessChain %34 %16 %5 +%33 = OpAccessChain %31 %13 %32 OpBranch %36 %36 = OpLabel -OpStore %22 %5 +OpStore %19 %32 OpBranch %37 %37 = OpLabel OpLoopMerge %38 %40 None OpBranch %39 %39 = OpLabel -%41 = OpLoad %4 %22 -%42 = OpULessThan %7 %41 %3 +%41 = OpLoad %4 %19 +%42 = OpULessThan %9 %41 %3 OpSelectionMerge %43 None OpBranchConditional %42 %43 %44 %44 = OpLabel @@ -83,18 +83,18 @@ OpBranch %38 %43 = OpLabel OpBranch %45 %45 = OpLabel -%47 = OpLoad %4 %22 -%49 = OpAccessChain %48 %35 %47 -%50 = OpAtomicLoad %11 %49 %51 %52 -OpStore %25 %50 -OpStore %28 %6 +%47 = OpLoad %4 %19 +%49 = OpAccessChain %48 %33 %47 +%50 = OpAtomicLoad %6 %49 %51 %52 +OpStore %22 %50 +OpStore %25 %34 OpBranch %53 %53 = OpLabel OpLoopMerge %54 %56 None OpBranch %55 %55 = OpLabel -%57 = OpLoad %7 %28 -%58 = OpLogicalNot %7 %57 +%57 = OpLoad %9 %25 +%58 = OpLogicalNot %9 %57 OpSelectionMerge %59 None OpBranchConditional %58 %59 %60 %60 = OpLabel @@ -102,20 +102,20 @@ OpBranch %54 %59 = OpLabel OpBranch %61 %61 = OpLabel -%63 = OpLoad %11 %25 -%64 = OpBitcast %9 %63 -%65 = OpFAdd %9 %64 %8 -%66 = OpBitcast %11 %65 -%67 = OpLoad %4 %22 -%68 = OpLoad %11 %25 -%70 = OpAccessChain %48 %35 %67 -%71 = OpAtomicCompareExchange %11 %70 %51 %52 %52 %66 %68 -%72 = OpIEqual %7 %71 %68 -%69 = OpCompositeConstruct %14 %71 %72 -%73 = OpCompositeExtract %11 %69 0 -OpStore %25 %73 -%74 = OpCompositeExtract %7 %69 1 -OpStore %28 %74 +%63 = OpLoad %6 %22 +%64 = OpBitcast %10 %63 +%65 = OpFAdd %10 %64 %35 +%66 = OpBitcast %6 %65 +%67 = OpLoad %4 %19 +%68 = OpLoad %6 %22 +%70 = OpAccessChain %48 %33 %67 +%71 = OpAtomicCompareExchange %6 %70 %51 %52 %52 %66 %68 +%72 = OpIEqual %9 %71 %68 +%69 = OpCompositeConstruct %11 %71 %72 +%73 = OpCompositeExtract %6 %69 0 +OpStore %22 %73 +%74 = OpCompositeExtract %9 %69 1 +OpStore %25 %74 OpBranch %62 %62 = OpLabel OpBranch %56 @@ -126,29 +126,29 @@ OpBranch %46 %46 = OpLabel OpBranch %40 %40 = OpLabel -%75 = OpLoad %4 %22 -%76 = OpIAdd %4 %75 %10 -OpStore %22 %76 +%75 = OpLoad %4 %19 +%76 = OpIAdd %4 %75 %5 +OpStore %19 %76 OpBranch %37 %38 = OpLabel OpReturn OpFunctionEnd -%84 = OpFunction %2 None %33 +%84 = OpFunction %2 None %30 %83 = OpLabel -%77 = OpVariable %23 Function %78 -%79 = OpVariable %23 Function %80 -%81 = OpVariable %29 Function %82 -%86 = OpAccessChain %85 %19 %5 +%77 = OpVariable %20 Function %78 +%79 = OpVariable %20 Function %80 +%81 = OpVariable %26 Function %82 +%86 = OpAccessChain %85 %16 %32 OpBranch %87 %87 = OpLabel -OpStore %77 %5 +OpStore %77 %32 OpBranch %88 %88 = OpLabel OpLoopMerge %89 %91 None OpBranch %90 %90 = OpLabel %92 = OpLoad %4 %77 -%93 = OpULessThan %7 %92 %3 +%93 = OpULessThan %9 %92 %3 OpSelectionMerge %94 None OpBranchConditional %93 %94 %95 %95 = OpLabel @@ -160,14 +160,14 @@ OpBranch %96 %100 = OpAccessChain %99 %86 %98 %101 = OpAtomicLoad %4 %100 %51 %52 OpStore %79 %101 -OpStore %81 %6 +OpStore %81 %34 OpBranch %102 %102 = OpLabel OpLoopMerge %103 %105 None OpBranch %104 %104 = OpLabel -%106 = OpLoad %7 %81 -%107 = OpLogicalNot %7 %106 +%106 = OpLoad %9 %81 +%107 = OpLogicalNot %9 %106 OpSelectionMerge %108 None OpBranchConditional %107 %108 %109 %109 = OpLabel @@ -176,18 +176,18 @@ OpBranch %103 OpBranch %110 %110 = OpLabel %112 = OpLoad %4 %79 -%113 = OpBitcast %9 %112 -%114 = OpFAdd %9 %113 %8 +%113 = OpBitcast %10 %112 +%114 = OpFAdd %10 %113 %35 %115 = OpBitcast %4 %114 %116 = OpLoad %4 %77 %117 = OpLoad %4 %79 %119 = OpAccessChain %99 %86 %116 %120 = OpAtomicCompareExchange %4 %119 %51 %52 %52 %115 %117 -%121 = OpIEqual %7 %120 %117 -%118 = OpCompositeConstruct %15 %120 %121 +%121 = OpIEqual %9 %120 %117 +%118 = OpCompositeConstruct %12 %120 %121 %122 = OpCompositeExtract %4 %118 0 OpStore %79 %122 -%123 = OpCompositeExtract %7 %118 1 +%123 = OpCompositeExtract %9 %118 1 OpStore %81 %123 OpBranch %111 %111 = OpLabel @@ -200,7 +200,7 @@ OpBranch %97 OpBranch %91 %91 = OpLabel %124 = OpLoad %4 %77 -%125 = OpIAdd %4 %124 %10 +%125 = OpIAdd %4 %124 %5 OpStore %77 %125 OpBranch %88 %89 = OpLabel diff --git a/tests/out/spv/atomicOps.spvasm b/tests/out/spv/atomicOps.spvasm index 8e9bad660..aa2d6aa68 100644 --- a/tests/out/spv/atomicOps.spvasm +++ b/tests/out/spv/atomicOps.spvasm @@ -6,235 +6,235 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %30 "cs_main" %27 -OpExecutionMode %30 LocalSize 2 1 1 -OpDecorate %8 ArrayStride 4 -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 4 -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 0 -OpDecorate %12 Block -OpMemberDecorate %12 0 Offset 0 -OpDecorate %14 DescriptorSet 0 -OpDecorate %14 Binding 1 -OpDecorate %15 Block -OpMemberDecorate %15 0 Offset 0 -OpDecorate %17 DescriptorSet 0 -OpDecorate %17 Binding 2 -OpDecorate %18 Block -OpMemberDecorate %18 0 Offset 0 -OpDecorate %27 BuiltIn LocalInvocationId +OpEntryPoint GLCompute %28 "cs_main" %25 +OpExecutionMode %28 LocalSize 2 1 1 +OpDecorate %6 ArrayStride 4 +OpMemberDecorate %7 0 Offset 0 +OpMemberDecorate %7 1 Offset 4 +OpDecorate %9 DescriptorSet 0 +OpDecorate %9 Binding 0 +OpDecorate %10 Block +OpMemberDecorate %10 0 Offset 0 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 1 +OpDecorate %13 Block +OpMemberDecorate %13 0 Offset 0 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 2 +OpDecorate %16 Block +OpMemberDecorate %16 0 Offset 0 +OpDecorate %25 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 1 -%7 = OpConstant %4 1 -%8 = OpTypeArray %4 %3 -%9 = OpTypeStruct %6 %8 -%10 = OpTypeVector %6 3 -%12 = OpTypeStruct %6 -%13 = OpTypePointer StorageBuffer %12 -%11 = OpVariable %13 StorageBuffer -%15 = OpTypeStruct %8 -%16 = OpTypePointer StorageBuffer %15 -%14 = OpVariable %16 StorageBuffer -%18 = OpTypeStruct %9 -%19 = OpTypePointer StorageBuffer %18 -%17 = OpVariable %19 StorageBuffer +%5 = OpTypeInt 32 0 +%6 = OpTypeArray %4 %3 +%7 = OpTypeStruct %5 %6 +%8 = OpTypeVector %5 3 +%10 = OpTypeStruct %5 +%11 = OpTypePointer StorageBuffer %10 +%9 = OpVariable %11 StorageBuffer +%13 = OpTypeStruct %6 +%14 = OpTypePointer StorageBuffer %13 +%12 = OpVariable %14 StorageBuffer +%16 = OpTypeStruct %7 +%17 = OpTypePointer StorageBuffer %16 +%15 = OpVariable %17 StorageBuffer +%19 = OpTypePointer Workgroup %5 +%18 = OpVariable %19 Workgroup %21 = OpTypePointer Workgroup %6 %20 = OpVariable %21 Workgroup -%23 = OpTypePointer Workgroup %8 +%23 = OpTypePointer Workgroup %7 %22 = OpVariable %23 Workgroup -%25 = OpTypePointer Workgroup %9 -%24 = OpVariable %25 Workgroup -%28 = OpTypePointer Input %10 -%27 = OpVariable %28 Input -%31 = OpTypeFunction %2 -%32 = OpTypePointer StorageBuffer %6 -%33 = OpConstant %6 0 -%35 = OpTypePointer StorageBuffer %8 -%37 = OpTypePointer StorageBuffer %9 -%40 = OpConstantNull %6 -%41 = OpConstantNull %8 -%42 = OpConstantNull %9 -%43 = OpConstantNull %10 +%26 = OpTypePointer Input %8 +%25 = OpVariable %26 Input +%29 = OpTypeFunction %2 +%30 = OpTypePointer StorageBuffer %5 +%31 = OpConstant %5 0 +%33 = OpTypePointer StorageBuffer %6 +%35 = OpTypePointer StorageBuffer %7 +%37 = OpConstant %5 1 +%38 = OpConstant %4 1 +%40 = OpConstantNull %5 +%41 = OpConstantNull %6 +%42 = OpConstantNull %7 +%43 = OpConstantNull %8 %45 = OpTypeBool %44 = OpTypeVector %45 3 -%50 = OpConstant %6 2 -%51 = OpConstant %6 264 -%53 = OpConstant %6 64 +%50 = OpConstant %5 2 +%51 = OpConstant %5 264 +%53 = OpConstant %5 64 %54 = OpTypePointer StorageBuffer %4 -%58 = OpConstant %6 256 +%58 = OpConstant %5 256 %59 = OpTypePointer Workgroup %4 -%30 = OpFunction %2 None %31 -%26 = OpLabel -%29 = OpLoad %10 %27 -%34 = OpAccessChain %32 %11 %33 -%36 = OpAccessChain %35 %14 %33 -%38 = OpAccessChain %37 %17 %33 +%28 = OpFunction %2 None %29 +%24 = OpLabel +%27 = OpLoad %8 %25 +%32 = OpAccessChain %30 %9 %31 +%34 = OpAccessChain %33 %12 %31 +%36 = OpAccessChain %35 %15 %31 OpBranch %39 %39 = OpLabel -%46 = OpIEqual %44 %29 %43 +%46 = OpIEqual %44 %27 %43 %47 = OpAll %45 %46 OpSelectionMerge %48 None OpBranchConditional %47 %49 %48 %49 = OpLabel -OpStore %20 %40 -OpStore %22 %41 -OpStore %24 %42 +OpStore %18 %40 +OpStore %20 %41 +OpStore %22 %42 OpBranch %48 %48 = OpLabel OpControlBarrier %50 %50 %51 OpBranch %52 %52 = OpLabel -OpAtomicStore %34 %7 %53 %5 -%55 = OpAccessChain %54 %36 %5 -OpAtomicStore %55 %7 %53 %7 -%56 = OpAccessChain %32 %38 %33 -OpAtomicStore %56 %7 %53 %5 -%57 = OpAccessChain %54 %38 %5 %5 -OpAtomicStore %57 %7 %53 %7 -OpAtomicStore %20 %3 %58 %5 -%60 = OpAccessChain %59 %22 %5 -OpAtomicStore %60 %3 %58 %7 -%61 = OpAccessChain %21 %24 %33 -OpAtomicStore %61 %3 %58 %5 -%62 = OpAccessChain %59 %24 %5 %5 -OpAtomicStore %62 %3 %58 %7 +OpAtomicStore %32 %38 %53 %37 +%55 = OpAccessChain %54 %34 %37 +OpAtomicStore %55 %38 %53 %38 +%56 = OpAccessChain %30 %36 %31 +OpAtomicStore %56 %38 %53 %37 +%57 = OpAccessChain %54 %36 %37 %37 +OpAtomicStore %57 %38 %53 %38 +OpAtomicStore %18 %3 %58 %37 +%60 = OpAccessChain %59 %20 %37 +OpAtomicStore %60 %3 %58 %38 +%61 = OpAccessChain %19 %22 %31 +OpAtomicStore %61 %3 %58 %37 +%62 = OpAccessChain %59 %22 %37 %37 +OpAtomicStore %62 %3 %58 %38 OpControlBarrier %50 %50 %51 -%63 = OpAtomicLoad %6 %34 %7 %53 -%64 = OpAccessChain %54 %36 %5 -%65 = OpAtomicLoad %4 %64 %7 %53 -%66 = OpAccessChain %32 %38 %33 -%67 = OpAtomicLoad %6 %66 %7 %53 -%68 = OpAccessChain %54 %38 %5 %5 -%69 = OpAtomicLoad %4 %68 %7 %53 -%70 = OpAtomicLoad %6 %20 %3 %58 -%71 = OpAccessChain %59 %22 %5 +%63 = OpAtomicLoad %5 %32 %38 %53 +%64 = OpAccessChain %54 %34 %37 +%65 = OpAtomicLoad %4 %64 %38 %53 +%66 = OpAccessChain %30 %36 %31 +%67 = OpAtomicLoad %5 %66 %38 %53 +%68 = OpAccessChain %54 %36 %37 %37 +%69 = OpAtomicLoad %4 %68 %38 %53 +%70 = OpAtomicLoad %5 %18 %3 %58 +%71 = OpAccessChain %59 %20 %37 %72 = OpAtomicLoad %4 %71 %3 %58 -%73 = OpAccessChain %21 %24 %33 -%74 = OpAtomicLoad %6 %73 %3 %58 -%75 = OpAccessChain %59 %24 %5 %5 +%73 = OpAccessChain %19 %22 %31 +%74 = OpAtomicLoad %5 %73 %3 %58 +%75 = OpAccessChain %59 %22 %37 %37 %76 = OpAtomicLoad %4 %75 %3 %58 OpControlBarrier %50 %50 %51 -%77 = OpAtomicIAdd %6 %34 %7 %53 %5 -%79 = OpAccessChain %54 %36 %5 -%78 = OpAtomicIAdd %4 %79 %7 %53 %7 -%81 = OpAccessChain %32 %38 %33 -%80 = OpAtomicIAdd %6 %81 %7 %53 %5 -%83 = OpAccessChain %54 %38 %5 %5 -%82 = OpAtomicIAdd %4 %83 %7 %53 %7 -%84 = OpAtomicIAdd %6 %20 %3 %58 %5 -%86 = OpAccessChain %59 %22 %5 -%85 = OpAtomicIAdd %4 %86 %3 %58 %7 -%88 = OpAccessChain %21 %24 %33 -%87 = OpAtomicIAdd %6 %88 %3 %58 %5 -%90 = OpAccessChain %59 %24 %5 %5 -%89 = OpAtomicIAdd %4 %90 %3 %58 %7 +%77 = OpAtomicIAdd %5 %32 %38 %53 %37 +%79 = OpAccessChain %54 %34 %37 +%78 = OpAtomicIAdd %4 %79 %38 %53 %38 +%81 = OpAccessChain %30 %36 %31 +%80 = OpAtomicIAdd %5 %81 %38 %53 %37 +%83 = OpAccessChain %54 %36 %37 %37 +%82 = OpAtomicIAdd %4 %83 %38 %53 %38 +%84 = OpAtomicIAdd %5 %18 %3 %58 %37 +%86 = OpAccessChain %59 %20 %37 +%85 = OpAtomicIAdd %4 %86 %3 %58 %38 +%88 = OpAccessChain %19 %22 %31 +%87 = OpAtomicIAdd %5 %88 %3 %58 %37 +%90 = OpAccessChain %59 %22 %37 %37 +%89 = OpAtomicIAdd %4 %90 %3 %58 %38 OpControlBarrier %50 %50 %51 -%91 = OpAtomicISub %6 %34 %7 %53 %5 -%93 = OpAccessChain %54 %36 %5 -%92 = OpAtomicISub %4 %93 %7 %53 %7 -%95 = OpAccessChain %32 %38 %33 -%94 = OpAtomicISub %6 %95 %7 %53 %5 -%97 = OpAccessChain %54 %38 %5 %5 -%96 = OpAtomicISub %4 %97 %7 %53 %7 -%98 = OpAtomicISub %6 %20 %3 %58 %5 -%100 = OpAccessChain %59 %22 %5 -%99 = OpAtomicISub %4 %100 %3 %58 %7 -%102 = OpAccessChain %21 %24 %33 -%101 = OpAtomicISub %6 %102 %3 %58 %5 -%104 = OpAccessChain %59 %24 %5 %5 -%103 = OpAtomicISub %4 %104 %3 %58 %7 +%91 = OpAtomicISub %5 %32 %38 %53 %37 +%93 = OpAccessChain %54 %34 %37 +%92 = OpAtomicISub %4 %93 %38 %53 %38 +%95 = OpAccessChain %30 %36 %31 +%94 = OpAtomicISub %5 %95 %38 %53 %37 +%97 = OpAccessChain %54 %36 %37 %37 +%96 = OpAtomicISub %4 %97 %38 %53 %38 +%98 = OpAtomicISub %5 %18 %3 %58 %37 +%100 = OpAccessChain %59 %20 %37 +%99 = OpAtomicISub %4 %100 %3 %58 %38 +%102 = OpAccessChain %19 %22 %31 +%101 = OpAtomicISub %5 %102 %3 %58 %37 +%104 = OpAccessChain %59 %22 %37 %37 +%103 = OpAtomicISub %4 %104 %3 %58 %38 OpControlBarrier %50 %50 %51 -%105 = OpAtomicUMax %6 %34 %7 %53 %5 -%107 = OpAccessChain %54 %36 %5 -%106 = OpAtomicSMax %4 %107 %7 %53 %7 -%109 = OpAccessChain %32 %38 %33 -%108 = OpAtomicUMax %6 %109 %7 %53 %5 -%111 = OpAccessChain %54 %38 %5 %5 -%110 = OpAtomicSMax %4 %111 %7 %53 %7 -%112 = OpAtomicUMax %6 %20 %3 %58 %5 -%114 = OpAccessChain %59 %22 %5 -%113 = OpAtomicSMax %4 %114 %3 %58 %7 -%116 = OpAccessChain %21 %24 %33 -%115 = OpAtomicUMax %6 %116 %3 %58 %5 -%118 = OpAccessChain %59 %24 %5 %5 -%117 = OpAtomicSMax %4 %118 %3 %58 %7 +%105 = OpAtomicUMax %5 %32 %38 %53 %37 +%107 = OpAccessChain %54 %34 %37 +%106 = OpAtomicSMax %4 %107 %38 %53 %38 +%109 = OpAccessChain %30 %36 %31 +%108 = OpAtomicUMax %5 %109 %38 %53 %37 +%111 = OpAccessChain %54 %36 %37 %37 +%110 = OpAtomicSMax %4 %111 %38 %53 %38 +%112 = OpAtomicUMax %5 %18 %3 %58 %37 +%114 = OpAccessChain %59 %20 %37 +%113 = OpAtomicSMax %4 %114 %3 %58 %38 +%116 = OpAccessChain %19 %22 %31 +%115 = OpAtomicUMax %5 %116 %3 %58 %37 +%118 = OpAccessChain %59 %22 %37 %37 +%117 = OpAtomicSMax %4 %118 %3 %58 %38 OpControlBarrier %50 %50 %51 -%119 = OpAtomicUMin %6 %34 %7 %53 %5 -%121 = OpAccessChain %54 %36 %5 -%120 = OpAtomicSMin %4 %121 %7 %53 %7 -%123 = OpAccessChain %32 %38 %33 -%122 = OpAtomicUMin %6 %123 %7 %53 %5 -%125 = OpAccessChain %54 %38 %5 %5 -%124 = OpAtomicSMin %4 %125 %7 %53 %7 -%126 = OpAtomicUMin %6 %20 %3 %58 %5 -%128 = OpAccessChain %59 %22 %5 -%127 = OpAtomicSMin %4 %128 %3 %58 %7 -%130 = OpAccessChain %21 %24 %33 -%129 = OpAtomicUMin %6 %130 %3 %58 %5 -%132 = OpAccessChain %59 %24 %5 %5 -%131 = OpAtomicSMin %4 %132 %3 %58 %7 +%119 = OpAtomicUMin %5 %32 %38 %53 %37 +%121 = OpAccessChain %54 %34 %37 +%120 = OpAtomicSMin %4 %121 %38 %53 %38 +%123 = OpAccessChain %30 %36 %31 +%122 = OpAtomicUMin %5 %123 %38 %53 %37 +%125 = OpAccessChain %54 %36 %37 %37 +%124 = OpAtomicSMin %4 %125 %38 %53 %38 +%126 = OpAtomicUMin %5 %18 %3 %58 %37 +%128 = OpAccessChain %59 %20 %37 +%127 = OpAtomicSMin %4 %128 %3 %58 %38 +%130 = OpAccessChain %19 %22 %31 +%129 = OpAtomicUMin %5 %130 %3 %58 %37 +%132 = OpAccessChain %59 %22 %37 %37 +%131 = OpAtomicSMin %4 %132 %3 %58 %38 OpControlBarrier %50 %50 %51 -%133 = OpAtomicAnd %6 %34 %7 %53 %5 -%135 = OpAccessChain %54 %36 %5 -%134 = OpAtomicAnd %4 %135 %7 %53 %7 -%137 = OpAccessChain %32 %38 %33 -%136 = OpAtomicAnd %6 %137 %7 %53 %5 -%139 = OpAccessChain %54 %38 %5 %5 -%138 = OpAtomicAnd %4 %139 %7 %53 %7 -%140 = OpAtomicAnd %6 %20 %3 %58 %5 -%142 = OpAccessChain %59 %22 %5 -%141 = OpAtomicAnd %4 %142 %3 %58 %7 -%144 = OpAccessChain %21 %24 %33 -%143 = OpAtomicAnd %6 %144 %3 %58 %5 -%146 = OpAccessChain %59 %24 %5 %5 -%145 = OpAtomicAnd %4 %146 %3 %58 %7 +%133 = OpAtomicAnd %5 %32 %38 %53 %37 +%135 = OpAccessChain %54 %34 %37 +%134 = OpAtomicAnd %4 %135 %38 %53 %38 +%137 = OpAccessChain %30 %36 %31 +%136 = OpAtomicAnd %5 %137 %38 %53 %37 +%139 = OpAccessChain %54 %36 %37 %37 +%138 = OpAtomicAnd %4 %139 %38 %53 %38 +%140 = OpAtomicAnd %5 %18 %3 %58 %37 +%142 = OpAccessChain %59 %20 %37 +%141 = OpAtomicAnd %4 %142 %3 %58 %38 +%144 = OpAccessChain %19 %22 %31 +%143 = OpAtomicAnd %5 %144 %3 %58 %37 +%146 = OpAccessChain %59 %22 %37 %37 +%145 = OpAtomicAnd %4 %146 %3 %58 %38 OpControlBarrier %50 %50 %51 -%147 = OpAtomicOr %6 %34 %7 %53 %5 -%149 = OpAccessChain %54 %36 %5 -%148 = OpAtomicOr %4 %149 %7 %53 %7 -%151 = OpAccessChain %32 %38 %33 -%150 = OpAtomicOr %6 %151 %7 %53 %5 -%153 = OpAccessChain %54 %38 %5 %5 -%152 = OpAtomicOr %4 %153 %7 %53 %7 -%154 = OpAtomicOr %6 %20 %3 %58 %5 -%156 = OpAccessChain %59 %22 %5 -%155 = OpAtomicOr %4 %156 %3 %58 %7 -%158 = OpAccessChain %21 %24 %33 -%157 = OpAtomicOr %6 %158 %3 %58 %5 -%160 = OpAccessChain %59 %24 %5 %5 -%159 = OpAtomicOr %4 %160 %3 %58 %7 +%147 = OpAtomicOr %5 %32 %38 %53 %37 +%149 = OpAccessChain %54 %34 %37 +%148 = OpAtomicOr %4 %149 %38 %53 %38 +%151 = OpAccessChain %30 %36 %31 +%150 = OpAtomicOr %5 %151 %38 %53 %37 +%153 = OpAccessChain %54 %36 %37 %37 +%152 = OpAtomicOr %4 %153 %38 %53 %38 +%154 = OpAtomicOr %5 %18 %3 %58 %37 +%156 = OpAccessChain %59 %20 %37 +%155 = OpAtomicOr %4 %156 %3 %58 %38 +%158 = OpAccessChain %19 %22 %31 +%157 = OpAtomicOr %5 %158 %3 %58 %37 +%160 = OpAccessChain %59 %22 %37 %37 +%159 = OpAtomicOr %4 %160 %3 %58 %38 OpControlBarrier %50 %50 %51 -%161 = OpAtomicXor %6 %34 %7 %53 %5 -%163 = OpAccessChain %54 %36 %5 -%162 = OpAtomicXor %4 %163 %7 %53 %7 -%165 = OpAccessChain %32 %38 %33 -%164 = OpAtomicXor %6 %165 %7 %53 %5 -%167 = OpAccessChain %54 %38 %5 %5 -%166 = OpAtomicXor %4 %167 %7 %53 %7 -%168 = OpAtomicXor %6 %20 %3 %58 %5 -%170 = OpAccessChain %59 %22 %5 -%169 = OpAtomicXor %4 %170 %3 %58 %7 -%172 = OpAccessChain %21 %24 %33 -%171 = OpAtomicXor %6 %172 %3 %58 %5 -%174 = OpAccessChain %59 %24 %5 %5 -%173 = OpAtomicXor %4 %174 %3 %58 %7 -%175 = OpAtomicExchange %6 %34 %7 %53 %5 -%177 = OpAccessChain %54 %36 %5 -%176 = OpAtomicExchange %4 %177 %7 %53 %7 -%179 = OpAccessChain %32 %38 %33 -%178 = OpAtomicExchange %6 %179 %7 %53 %5 -%181 = OpAccessChain %54 %38 %5 %5 -%180 = OpAtomicExchange %4 %181 %7 %53 %7 -%182 = OpAtomicExchange %6 %20 %3 %58 %5 -%184 = OpAccessChain %59 %22 %5 -%183 = OpAtomicExchange %4 %184 %3 %58 %7 -%186 = OpAccessChain %21 %24 %33 -%185 = OpAtomicExchange %6 %186 %3 %58 %5 -%188 = OpAccessChain %59 %24 %5 %5 -%187 = OpAtomicExchange %4 %188 %3 %58 %7 +%161 = OpAtomicXor %5 %32 %38 %53 %37 +%163 = OpAccessChain %54 %34 %37 +%162 = OpAtomicXor %4 %163 %38 %53 %38 +%165 = OpAccessChain %30 %36 %31 +%164 = OpAtomicXor %5 %165 %38 %53 %37 +%167 = OpAccessChain %54 %36 %37 %37 +%166 = OpAtomicXor %4 %167 %38 %53 %38 +%168 = OpAtomicXor %5 %18 %3 %58 %37 +%170 = OpAccessChain %59 %20 %37 +%169 = OpAtomicXor %4 %170 %3 %58 %38 +%172 = OpAccessChain %19 %22 %31 +%171 = OpAtomicXor %5 %172 %3 %58 %37 +%174 = OpAccessChain %59 %22 %37 %37 +%173 = OpAtomicXor %4 %174 %3 %58 %38 +%175 = OpAtomicExchange %5 %32 %38 %53 %37 +%177 = OpAccessChain %54 %34 %37 +%176 = OpAtomicExchange %4 %177 %38 %53 %38 +%179 = OpAccessChain %30 %36 %31 +%178 = OpAtomicExchange %5 %179 %38 %53 %37 +%181 = OpAccessChain %54 %36 %37 %37 +%180 = OpAtomicExchange %4 %181 %38 %53 %38 +%182 = OpAtomicExchange %5 %18 %3 %58 %37 +%184 = OpAccessChain %59 %20 %37 +%183 = OpAtomicExchange %4 %184 %3 %58 %38 +%186 = OpAccessChain %19 %22 %31 +%185 = OpAtomicExchange %5 %186 %3 %58 %37 +%188 = OpAccessChain %59 %22 %37 %37 +%187 = OpAtomicExchange %4 %188 %3 %58 %38 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 31929d155..5173208dc 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -8,33 +8,33 @@ OpCapability ShaderNonUniform OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %70 "main" %65 %68 -OpExecutionMode %70 OriginUpperLeft -OpMemberDecorate %10 0 Offset 0 -OpMemberDecorate %25 0 Offset 0 -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 0 -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 1 -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 2 -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 3 -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 4 -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 5 -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 6 -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 7 -OpDecorate %48 DescriptorSet 0 -OpDecorate %48 Binding 8 -OpDecorate %49 Block -OpMemberDecorate %49 0 Offset 0 +OpEntryPoint Fragment %67 "main" %62 %65 +OpExecutionMode %67 OriginUpperLeft +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %22 0 Offset 0 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 0 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 1 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 2 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 3 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 4 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 5 +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 6 +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 7 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 8 +OpDecorate %46 Block +OpMemberDecorate %46 0 Offset 0 +OpDecorate %62 Location 0 +OpDecorate %62 Flat OpDecorate %65 Location 0 -OpDecorate %65 Flat -OpDecorate %68 Location 0 OpDecorate %96 NonUniform OpDecorate %120 NonUniform OpDecorate %122 NonUniform @@ -60,468 +60,468 @@ OpDecorate %423 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 5 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 0 +%5 = OpTypeInt 32 0 +%6 = OpTypeStruct %5 %8 = OpTypeFloat 32 -%7 = OpConstant %8 0.0 -%9 = OpConstant %4 0 -%10 = OpTypeStruct %6 -%11 = OpTypeImage %8 2D 0 0 0 1 Unknown -%12 = OpTypeRuntimeArray %11 -%13 = OpTypeArray %11 %3 -%14 = OpTypeImage %8 2D 0 1 0 1 Unknown -%15 = OpTypeArray %14 %3 -%16 = OpTypeImage %8 2D 0 0 1 1 Unknown -%17 = OpTypeArray %16 %3 -%18 = OpTypeImage %8 2D 1 0 0 1 Unknown -%19 = OpTypeArray %18 %3 -%20 = OpTypeImage %8 2D 0 0 0 2 Rgba32f -%21 = OpTypeArray %20 %3 -%22 = OpTypeSampler -%23 = OpTypeArray %22 %3 -%24 = OpTypeArray %22 %3 -%25 = OpTypeStruct %6 -%26 = OpTypeVector %8 4 -%27 = OpTypeVector %6 2 -%28 = OpTypeVector %8 2 -%29 = OpTypeVector %4 2 -%33 = OpConstant %6 10 -%32 = OpTypeArray %11 %33 -%31 = OpTypePointer UniformConstant %32 -%30 = OpVariable %31 UniformConstant -%35 = OpTypePointer UniformConstant %13 -%34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %15 -%36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %17 -%38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %19 -%40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %21 -%42 = OpVariable %43 UniformConstant -%45 = OpTypePointer UniformConstant %23 -%44 = OpVariable %45 UniformConstant -%47 = OpTypePointer UniformConstant %24 -%46 = OpVariable %47 UniformConstant -%49 = OpTypeStruct %10 -%50 = OpTypePointer Uniform %49 -%48 = OpVariable %50 Uniform -%52 = OpTypePointer Function %6 -%53 = OpConstantNull %6 -%55 = OpTypePointer Function %27 -%56 = OpConstantNull %27 -%58 = OpTypePointer Function %8 -%59 = OpConstantNull %8 -%61 = OpTypePointer Function %26 -%62 = OpConstantNull %26 -%66 = OpTypePointer Input %6 -%65 = OpVariable %66 Input -%69 = OpTypePointer Output %26 -%68 = OpVariable %69 Output -%71 = OpTypeFunction %2 -%72 = OpTypePointer Uniform %10 -%75 = OpTypePointer Uniform %6 -%83 = OpTypePointer UniformConstant %11 -%104 = OpTypePointer UniformConstant %22 -%107 = OpTypeSampledImage %11 -%128 = OpTypePointer UniformConstant %18 -%131 = OpTypePointer UniformConstant %22 -%134 = OpTypeSampledImage %18 +%7 = OpTypeImage %8 2D 0 0 0 1 Unknown +%9 = OpTypeRuntimeArray %7 +%10 = OpTypeArray %7 %3 +%11 = OpTypeImage %8 2D 0 1 0 1 Unknown +%12 = OpTypeArray %11 %3 +%13 = OpTypeImage %8 2D 0 0 1 1 Unknown +%14 = OpTypeArray %13 %3 +%15 = OpTypeImage %8 2D 1 0 0 1 Unknown +%16 = OpTypeArray %15 %3 +%17 = OpTypeImage %8 2D 0 0 0 2 Rgba32f +%18 = OpTypeArray %17 %3 +%19 = OpTypeSampler +%20 = OpTypeArray %19 %3 +%21 = OpTypeArray %19 %3 +%22 = OpTypeStruct %5 +%23 = OpTypeVector %8 4 +%24 = OpTypeVector %5 2 +%25 = OpTypeVector %8 2 +%26 = OpTypeVector %4 2 +%30 = OpConstant %5 10 +%29 = OpTypeArray %7 %30 +%28 = OpTypePointer UniformConstant %29 +%27 = OpVariable %28 UniformConstant +%32 = OpTypePointer UniformConstant %10 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %12 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %14 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %16 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %18 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %20 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %21 +%43 = OpVariable %44 UniformConstant +%46 = OpTypeStruct %6 +%47 = OpTypePointer Uniform %46 +%45 = OpVariable %47 Uniform +%49 = OpTypePointer Function %5 +%50 = OpConstantNull %5 +%52 = OpTypePointer Function %24 +%53 = OpConstantNull %24 +%55 = OpTypePointer Function %8 +%56 = OpConstantNull %8 +%58 = OpTypePointer Function %23 +%59 = OpConstantNull %23 +%63 = OpTypePointer Input %5 +%62 = OpVariable %63 Input +%66 = OpTypePointer Output %23 +%65 = OpVariable %66 Output +%68 = OpTypeFunction %2 +%69 = OpTypePointer Uniform %6 +%70 = OpConstant %5 0 +%72 = OpConstant %8 0.0 +%73 = OpConstant %4 0 +%75 = OpTypePointer Uniform %5 +%83 = OpTypePointer UniformConstant %7 +%104 = OpTypePointer UniformConstant %19 +%107 = OpTypeSampledImage %7 +%128 = OpTypePointer UniformConstant %15 +%131 = OpTypePointer UniformConstant %19 +%134 = OpTypeSampledImage %15 %157 = OpTypeBool -%158 = OpConstantNull %26 +%158 = OpConstantNull %23 %164 = OpTypeVector %157 2 -%174 = OpConstantNull %26 -%189 = OpConstantNull %26 -%202 = OpTypePointer UniformConstant %14 +%174 = OpConstantNull %23 +%189 = OpConstantNull %23 +%202 = OpTypePointer UniformConstant %11 %205 = OpTypeVector %4 3 -%243 = OpTypePointer UniformConstant %16 -%406 = OpTypePointer UniformConstant %20 -%70 = OpFunction %2 None %71 -%63 = OpLabel -%54 = OpVariable %55 Function %56 -%60 = OpVariable %61 Function %62 +%243 = OpTypePointer UniformConstant %13 +%406 = OpTypePointer UniformConstant %17 +%67 = OpFunction %2 None %68 +%60 = OpLabel %51 = OpVariable %52 Function %53 %57 = OpVariable %58 Function %59 -%67 = OpLoad %6 %65 -%64 = OpCompositeConstruct %25 %67 -%73 = OpAccessChain %72 %48 %5 +%48 = OpVariable %49 Function %50 +%54 = OpVariable %55 Function %56 +%64 = OpLoad %5 %62 +%61 = OpCompositeConstruct %22 %64 +%71 = OpAccessChain %69 %45 %70 OpBranch %74 %74 = OpLabel -%76 = OpAccessChain %75 %73 %5 -%77 = OpLoad %6 %76 -%78 = OpCompositeExtract %6 %64 0 -OpStore %51 %5 -%79 = OpCompositeConstruct %27 %5 %5 -OpStore %54 %79 -OpStore %57 %7 -%80 = OpCompositeConstruct %26 %7 %7 %7 %7 -OpStore %60 %80 -%81 = OpCompositeConstruct %28 %7 %7 -%82 = OpCompositeConstruct %29 %9 %9 -%84 = OpAccessChain %83 %30 %5 -%85 = OpLoad %11 %84 -%86 = OpImageQuerySizeLod %29 %85 %5 -%87 = OpBitcast %27 %86 -%88 = OpLoad %27 %54 -%89 = OpIAdd %27 %88 %87 -OpStore %54 %89 -%90 = OpAccessChain %83 %30 %77 -%91 = OpLoad %11 %90 -%92 = OpImageQuerySizeLod %29 %91 %5 -%93 = OpBitcast %27 %92 -%94 = OpLoad %27 %54 -%95 = OpIAdd %27 %94 %93 -OpStore %54 %95 -%96 = OpAccessChain %83 %30 %78 -%97 = OpLoad %11 %96 -%98 = OpImageQuerySizeLod %29 %97 %5 -%99 = OpBitcast %27 %98 -%100 = OpLoad %27 %54 -%101 = OpIAdd %27 %100 %99 -OpStore %54 %101 -%102 = OpAccessChain %83 %34 %5 -%103 = OpLoad %11 %102 -%105 = OpAccessChain %104 %44 %5 -%106 = OpLoad %22 %105 +%76 = OpAccessChain %75 %71 %70 +%77 = OpLoad %5 %76 +%78 = OpCompositeExtract %5 %61 0 +OpStore %48 %70 +%79 = OpCompositeConstruct %24 %70 %70 +OpStore %51 %79 +OpStore %54 %72 +%80 = OpCompositeConstruct %23 %72 %72 %72 %72 +OpStore %57 %80 +%81 = OpCompositeConstruct %25 %72 %72 +%82 = OpCompositeConstruct %26 %73 %73 +%84 = OpAccessChain %83 %27 %70 +%85 = OpLoad %7 %84 +%86 = OpImageQuerySizeLod %26 %85 %70 +%87 = OpBitcast %24 %86 +%88 = OpLoad %24 %51 +%89 = OpIAdd %24 %88 %87 +OpStore %51 %89 +%90 = OpAccessChain %83 %27 %77 +%91 = OpLoad %7 %90 +%92 = OpImageQuerySizeLod %26 %91 %70 +%93 = OpBitcast %24 %92 +%94 = OpLoad %24 %51 +%95 = OpIAdd %24 %94 %93 +OpStore %51 %95 +%96 = OpAccessChain %83 %27 %78 +%97 = OpLoad %7 %96 +%98 = OpImageQuerySizeLod %26 %97 %70 +%99 = OpBitcast %24 %98 +%100 = OpLoad %24 %51 +%101 = OpIAdd %24 %100 %99 +OpStore %51 %101 +%102 = OpAccessChain %83 %31 %70 +%103 = OpLoad %7 %102 +%105 = OpAccessChain %104 %41 %70 +%106 = OpLoad %19 %105 %108 = OpSampledImage %107 %103 %106 -%109 = OpImageGather %26 %108 %81 %5 -%110 = OpLoad %26 %60 -%111 = OpFAdd %26 %110 %109 -OpStore %60 %111 -%112 = OpAccessChain %83 %34 %77 -%113 = OpLoad %11 %112 -%114 = OpAccessChain %104 %44 %77 -%115 = OpLoad %22 %114 +%109 = OpImageGather %23 %108 %81 %70 +%110 = OpLoad %23 %57 +%111 = OpFAdd %23 %110 %109 +OpStore %57 %111 +%112 = OpAccessChain %83 %31 %77 +%113 = OpLoad %7 %112 +%114 = OpAccessChain %104 %41 %77 +%115 = OpLoad %19 %114 %116 = OpSampledImage %107 %113 %115 -%117 = OpImageGather %26 %116 %81 %5 -%118 = OpLoad %26 %60 -%119 = OpFAdd %26 %118 %117 -OpStore %60 %119 -%120 = OpAccessChain %83 %34 %78 -%121 = OpLoad %11 %120 -%122 = OpAccessChain %104 %44 %78 -%123 = OpLoad %22 %122 +%117 = OpImageGather %23 %116 %81 %70 +%118 = OpLoad %23 %57 +%119 = OpFAdd %23 %118 %117 +OpStore %57 %119 +%120 = OpAccessChain %83 %31 %78 +%121 = OpLoad %7 %120 +%122 = OpAccessChain %104 %41 %78 +%123 = OpLoad %19 %122 %124 = OpSampledImage %107 %121 %123 -%125 = OpImageGather %26 %124 %81 %5 -%126 = OpLoad %26 %60 -%127 = OpFAdd %26 %126 %125 -OpStore %60 %127 -%129 = OpAccessChain %128 %40 %5 -%130 = OpLoad %18 %129 -%132 = OpAccessChain %131 %46 %5 -%133 = OpLoad %22 %132 +%125 = OpImageGather %23 %124 %81 %70 +%126 = OpLoad %23 %57 +%127 = OpFAdd %23 %126 %125 +OpStore %57 %127 +%129 = OpAccessChain %128 %37 %70 +%130 = OpLoad %15 %129 +%132 = OpAccessChain %131 %43 %70 +%133 = OpLoad %19 %132 %135 = OpSampledImage %134 %130 %133 -%136 = OpImageDrefGather %26 %135 %81 %7 -%137 = OpLoad %26 %60 -%138 = OpFAdd %26 %137 %136 -OpStore %60 %138 -%139 = OpAccessChain %128 %40 %77 -%140 = OpLoad %18 %139 -%141 = OpAccessChain %131 %46 %77 -%142 = OpLoad %22 %141 +%136 = OpImageDrefGather %23 %135 %81 %72 +%137 = OpLoad %23 %57 +%138 = OpFAdd %23 %137 %136 +OpStore %57 %138 +%139 = OpAccessChain %128 %37 %77 +%140 = OpLoad %15 %139 +%141 = OpAccessChain %131 %43 %77 +%142 = OpLoad %19 %141 %143 = OpSampledImage %134 %140 %142 -%144 = OpImageDrefGather %26 %143 %81 %7 -%145 = OpLoad %26 %60 -%146 = OpFAdd %26 %145 %144 -OpStore %60 %146 -%147 = OpAccessChain %128 %40 %78 -%148 = OpLoad %18 %147 -%149 = OpAccessChain %131 %46 %78 -%150 = OpLoad %22 %149 +%144 = OpImageDrefGather %23 %143 %81 %72 +%145 = OpLoad %23 %57 +%146 = OpFAdd %23 %145 %144 +OpStore %57 %146 +%147 = OpAccessChain %128 %37 %78 +%148 = OpLoad %15 %147 +%149 = OpAccessChain %131 %43 %78 +%150 = OpLoad %19 %149 %151 = OpSampledImage %134 %148 %150 -%152 = OpImageDrefGather %26 %151 %81 %7 -%153 = OpLoad %26 %60 -%154 = OpFAdd %26 %153 %152 -OpStore %60 %154 -%155 = OpAccessChain %83 %30 %5 -%156 = OpLoad %11 %155 +%152 = OpImageDrefGather %23 %151 %81 %72 +%153 = OpLoad %23 %57 +%154 = OpFAdd %23 %153 %152 +OpStore %57 %154 +%155 = OpAccessChain %83 %27 %70 +%156 = OpLoad %7 %155 %159 = OpImageQueryLevels %4 %156 -%160 = OpULessThan %157 %9 %159 +%160 = OpULessThan %157 %73 %159 OpSelectionMerge %161 None OpBranchConditional %160 %162 %161 %162 = OpLabel -%163 = OpImageQuerySizeLod %29 %156 %9 +%163 = OpImageQuerySizeLod %26 %156 %73 %165 = OpULessThan %164 %82 %163 %166 = OpAll %157 %165 OpBranchConditional %166 %167 %161 %167 = OpLabel -%168 = OpImageFetch %26 %156 %82 Lod %9 +%168 = OpImageFetch %23 %156 %82 Lod %73 OpBranch %161 %161 = OpLabel -%169 = OpPhi %26 %158 %74 %158 %162 %168 %167 -%170 = OpLoad %26 %60 -%171 = OpFAdd %26 %170 %169 -OpStore %60 %171 -%172 = OpAccessChain %83 %30 %77 -%173 = OpLoad %11 %172 +%169 = OpPhi %23 %158 %74 %158 %162 %168 %167 +%170 = OpLoad %23 %57 +%171 = OpFAdd %23 %170 %169 +OpStore %57 %171 +%172 = OpAccessChain %83 %27 %77 +%173 = OpLoad %7 %172 %175 = OpImageQueryLevels %4 %173 -%176 = OpULessThan %157 %9 %175 +%176 = OpULessThan %157 %73 %175 OpSelectionMerge %177 None OpBranchConditional %176 %178 %177 %178 = OpLabel -%179 = OpImageQuerySizeLod %29 %173 %9 +%179 = OpImageQuerySizeLod %26 %173 %73 %180 = OpULessThan %164 %82 %179 %181 = OpAll %157 %180 OpBranchConditional %181 %182 %177 %182 = OpLabel -%183 = OpImageFetch %26 %173 %82 Lod %9 +%183 = OpImageFetch %23 %173 %82 Lod %73 OpBranch %177 %177 = OpLabel -%184 = OpPhi %26 %174 %161 %174 %178 %183 %182 -%185 = OpLoad %26 %60 -%186 = OpFAdd %26 %185 %184 -OpStore %60 %186 -%187 = OpAccessChain %83 %30 %78 -%188 = OpLoad %11 %187 +%184 = OpPhi %23 %174 %161 %174 %178 %183 %182 +%185 = OpLoad %23 %57 +%186 = OpFAdd %23 %185 %184 +OpStore %57 %186 +%187 = OpAccessChain %83 %27 %78 +%188 = OpLoad %7 %187 %190 = OpImageQueryLevels %4 %188 -%191 = OpULessThan %157 %9 %190 +%191 = OpULessThan %157 %73 %190 OpSelectionMerge %192 None OpBranchConditional %191 %193 %192 %193 = OpLabel -%194 = OpImageQuerySizeLod %29 %188 %9 +%194 = OpImageQuerySizeLod %26 %188 %73 %195 = OpULessThan %164 %82 %194 %196 = OpAll %157 %195 OpBranchConditional %196 %197 %192 %197 = OpLabel -%198 = OpImageFetch %26 %188 %82 Lod %9 +%198 = OpImageFetch %23 %188 %82 Lod %73 OpBranch %192 %192 = OpLabel -%199 = OpPhi %26 %189 %177 %189 %193 %198 %197 -%200 = OpLoad %26 %60 -%201 = OpFAdd %26 %200 %199 -OpStore %60 %201 -%203 = OpAccessChain %202 %36 %5 -%204 = OpLoad %14 %203 -%206 = OpImageQuerySizeLod %205 %204 %5 +%199 = OpPhi %23 %189 %177 %189 %193 %198 %197 +%200 = OpLoad %23 %57 +%201 = OpFAdd %23 %200 %199 +OpStore %57 %201 +%203 = OpAccessChain %202 %33 %70 +%204 = OpLoad %11 %203 +%206 = OpImageQuerySizeLod %205 %204 %70 %207 = OpCompositeExtract %4 %206 2 -%208 = OpBitcast %6 %207 -%209 = OpLoad %6 %51 -%210 = OpIAdd %6 %209 %208 -OpStore %51 %210 -%211 = OpAccessChain %202 %36 %77 -%212 = OpLoad %14 %211 -%213 = OpImageQuerySizeLod %205 %212 %5 +%208 = OpBitcast %5 %207 +%209 = OpLoad %5 %48 +%210 = OpIAdd %5 %209 %208 +OpStore %48 %210 +%211 = OpAccessChain %202 %33 %77 +%212 = OpLoad %11 %211 +%213 = OpImageQuerySizeLod %205 %212 %70 %214 = OpCompositeExtract %4 %213 2 -%215 = OpBitcast %6 %214 -%216 = OpLoad %6 %51 -%217 = OpIAdd %6 %216 %215 -OpStore %51 %217 -%218 = OpAccessChain %202 %36 %78 -%219 = OpLoad %14 %218 -%220 = OpImageQuerySizeLod %205 %219 %5 +%215 = OpBitcast %5 %214 +%216 = OpLoad %5 %48 +%217 = OpIAdd %5 %216 %215 +OpStore %48 %217 +%218 = OpAccessChain %202 %33 %78 +%219 = OpLoad %11 %218 +%220 = OpImageQuerySizeLod %205 %219 %70 %221 = OpCompositeExtract %4 %220 2 -%222 = OpBitcast %6 %221 -%223 = OpLoad %6 %51 -%224 = OpIAdd %6 %223 %222 -OpStore %51 %224 -%225 = OpAccessChain %83 %34 %5 -%226 = OpLoad %11 %225 +%222 = OpBitcast %5 %221 +%223 = OpLoad %5 %48 +%224 = OpIAdd %5 %223 %222 +OpStore %48 %224 +%225 = OpAccessChain %83 %31 %70 +%226 = OpLoad %7 %225 %227 = OpImageQueryLevels %4 %226 -%228 = OpBitcast %6 %227 -%229 = OpLoad %6 %51 -%230 = OpIAdd %6 %229 %228 -OpStore %51 %230 -%231 = OpAccessChain %83 %34 %77 -%232 = OpLoad %11 %231 +%228 = OpBitcast %5 %227 +%229 = OpLoad %5 %48 +%230 = OpIAdd %5 %229 %228 +OpStore %48 %230 +%231 = OpAccessChain %83 %31 %77 +%232 = OpLoad %7 %231 %233 = OpImageQueryLevels %4 %232 -%234 = OpBitcast %6 %233 -%235 = OpLoad %6 %51 -%236 = OpIAdd %6 %235 %234 -OpStore %51 %236 -%237 = OpAccessChain %83 %34 %78 -%238 = OpLoad %11 %237 +%234 = OpBitcast %5 %233 +%235 = OpLoad %5 %48 +%236 = OpIAdd %5 %235 %234 +OpStore %48 %236 +%237 = OpAccessChain %83 %31 %78 +%238 = OpLoad %7 %237 %239 = OpImageQueryLevels %4 %238 -%240 = OpBitcast %6 %239 -%241 = OpLoad %6 %51 -%242 = OpIAdd %6 %241 %240 -OpStore %51 %242 -%244 = OpAccessChain %243 %38 %5 -%245 = OpLoad %16 %244 +%240 = OpBitcast %5 %239 +%241 = OpLoad %5 %48 +%242 = OpIAdd %5 %241 %240 +OpStore %48 %242 +%244 = OpAccessChain %243 %35 %70 +%245 = OpLoad %13 %244 %246 = OpImageQuerySamples %4 %245 -%247 = OpBitcast %6 %246 -%248 = OpLoad %6 %51 -%249 = OpIAdd %6 %248 %247 -OpStore %51 %249 -%250 = OpAccessChain %243 %38 %77 -%251 = OpLoad %16 %250 +%247 = OpBitcast %5 %246 +%248 = OpLoad %5 %48 +%249 = OpIAdd %5 %248 %247 +OpStore %48 %249 +%250 = OpAccessChain %243 %35 %77 +%251 = OpLoad %13 %250 %252 = OpImageQuerySamples %4 %251 -%253 = OpBitcast %6 %252 -%254 = OpLoad %6 %51 -%255 = OpIAdd %6 %254 %253 -OpStore %51 %255 -%256 = OpAccessChain %243 %38 %78 -%257 = OpLoad %16 %256 +%253 = OpBitcast %5 %252 +%254 = OpLoad %5 %48 +%255 = OpIAdd %5 %254 %253 +OpStore %48 %255 +%256 = OpAccessChain %243 %35 %78 +%257 = OpLoad %13 %256 %258 = OpImageQuerySamples %4 %257 -%259 = OpBitcast %6 %258 -%260 = OpLoad %6 %51 -%261 = OpIAdd %6 %260 %259 -OpStore %51 %261 -%262 = OpAccessChain %83 %34 %5 -%263 = OpLoad %11 %262 -%264 = OpAccessChain %104 %44 %5 -%265 = OpLoad %22 %264 +%259 = OpBitcast %5 %258 +%260 = OpLoad %5 %48 +%261 = OpIAdd %5 %260 %259 +OpStore %48 %261 +%262 = OpAccessChain %83 %31 %70 +%263 = OpLoad %7 %262 +%264 = OpAccessChain %104 %41 %70 +%265 = OpLoad %19 %264 %266 = OpSampledImage %107 %263 %265 -%267 = OpImageSampleImplicitLod %26 %266 %81 -%268 = OpLoad %26 %60 -%269 = OpFAdd %26 %268 %267 -OpStore %60 %269 -%270 = OpAccessChain %83 %34 %77 -%271 = OpLoad %11 %270 -%272 = OpAccessChain %104 %44 %77 -%273 = OpLoad %22 %272 +%267 = OpImageSampleImplicitLod %23 %266 %81 +%268 = OpLoad %23 %57 +%269 = OpFAdd %23 %268 %267 +OpStore %57 %269 +%270 = OpAccessChain %83 %31 %77 +%271 = OpLoad %7 %270 +%272 = OpAccessChain %104 %41 %77 +%273 = OpLoad %19 %272 %274 = OpSampledImage %107 %271 %273 -%275 = OpImageSampleImplicitLod %26 %274 %81 -%276 = OpLoad %26 %60 -%277 = OpFAdd %26 %276 %275 -OpStore %60 %277 -%278 = OpAccessChain %83 %34 %78 -%279 = OpLoad %11 %278 -%280 = OpAccessChain %104 %44 %78 -%281 = OpLoad %22 %280 +%275 = OpImageSampleImplicitLod %23 %274 %81 +%276 = OpLoad %23 %57 +%277 = OpFAdd %23 %276 %275 +OpStore %57 %277 +%278 = OpAccessChain %83 %31 %78 +%279 = OpLoad %7 %278 +%280 = OpAccessChain %104 %41 %78 +%281 = OpLoad %19 %280 %282 = OpSampledImage %107 %279 %281 -%283 = OpImageSampleImplicitLod %26 %282 %81 -%284 = OpLoad %26 %60 -%285 = OpFAdd %26 %284 %283 -OpStore %60 %285 -%286 = OpAccessChain %83 %34 %5 -%287 = OpLoad %11 %286 -%288 = OpAccessChain %104 %44 %5 -%289 = OpLoad %22 %288 +%283 = OpImageSampleImplicitLod %23 %282 %81 +%284 = OpLoad %23 %57 +%285 = OpFAdd %23 %284 %283 +OpStore %57 %285 +%286 = OpAccessChain %83 %31 %70 +%287 = OpLoad %7 %286 +%288 = OpAccessChain %104 %41 %70 +%289 = OpLoad %19 %288 %290 = OpSampledImage %107 %287 %289 -%291 = OpImageSampleImplicitLod %26 %290 %81 Bias %7 -%292 = OpLoad %26 %60 -%293 = OpFAdd %26 %292 %291 -OpStore %60 %293 -%294 = OpAccessChain %83 %34 %77 -%295 = OpLoad %11 %294 -%296 = OpAccessChain %104 %44 %77 -%297 = OpLoad %22 %296 +%291 = OpImageSampleImplicitLod %23 %290 %81 Bias %72 +%292 = OpLoad %23 %57 +%293 = OpFAdd %23 %292 %291 +OpStore %57 %293 +%294 = OpAccessChain %83 %31 %77 +%295 = OpLoad %7 %294 +%296 = OpAccessChain %104 %41 %77 +%297 = OpLoad %19 %296 %298 = OpSampledImage %107 %295 %297 -%299 = OpImageSampleImplicitLod %26 %298 %81 Bias %7 -%300 = OpLoad %26 %60 -%301 = OpFAdd %26 %300 %299 -OpStore %60 %301 -%302 = OpAccessChain %83 %34 %78 -%303 = OpLoad %11 %302 -%304 = OpAccessChain %104 %44 %78 -%305 = OpLoad %22 %304 +%299 = OpImageSampleImplicitLod %23 %298 %81 Bias %72 +%300 = OpLoad %23 %57 +%301 = OpFAdd %23 %300 %299 +OpStore %57 %301 +%302 = OpAccessChain %83 %31 %78 +%303 = OpLoad %7 %302 +%304 = OpAccessChain %104 %41 %78 +%305 = OpLoad %19 %304 %306 = OpSampledImage %107 %303 %305 -%307 = OpImageSampleImplicitLod %26 %306 %81 Bias %7 -%308 = OpLoad %26 %60 -%309 = OpFAdd %26 %308 %307 -OpStore %60 %309 -%310 = OpAccessChain %128 %40 %5 -%311 = OpLoad %18 %310 -%312 = OpAccessChain %131 %46 %5 -%313 = OpLoad %22 %312 +%307 = OpImageSampleImplicitLod %23 %306 %81 Bias %72 +%308 = OpLoad %23 %57 +%309 = OpFAdd %23 %308 %307 +OpStore %57 %309 +%310 = OpAccessChain %128 %37 %70 +%311 = OpLoad %15 %310 +%312 = OpAccessChain %131 %43 %70 +%313 = OpLoad %19 %312 %314 = OpSampledImage %134 %311 %313 -%315 = OpImageSampleDrefImplicitLod %8 %314 %81 %7 -%316 = OpLoad %8 %57 +%315 = OpImageSampleDrefImplicitLod %8 %314 %81 %72 +%316 = OpLoad %8 %54 %317 = OpFAdd %8 %316 %315 -OpStore %57 %317 -%318 = OpAccessChain %128 %40 %77 -%319 = OpLoad %18 %318 -%320 = OpAccessChain %131 %46 %77 -%321 = OpLoad %22 %320 +OpStore %54 %317 +%318 = OpAccessChain %128 %37 %77 +%319 = OpLoad %15 %318 +%320 = OpAccessChain %131 %43 %77 +%321 = OpLoad %19 %320 %322 = OpSampledImage %134 %319 %321 -%323 = OpImageSampleDrefImplicitLod %8 %322 %81 %7 -%324 = OpLoad %8 %57 +%323 = OpImageSampleDrefImplicitLod %8 %322 %81 %72 +%324 = OpLoad %8 %54 %325 = OpFAdd %8 %324 %323 -OpStore %57 %325 -%326 = OpAccessChain %128 %40 %78 -%327 = OpLoad %18 %326 -%328 = OpAccessChain %131 %46 %78 -%329 = OpLoad %22 %328 +OpStore %54 %325 +%326 = OpAccessChain %128 %37 %78 +%327 = OpLoad %15 %326 +%328 = OpAccessChain %131 %43 %78 +%329 = OpLoad %19 %328 %330 = OpSampledImage %134 %327 %329 -%331 = OpImageSampleDrefImplicitLod %8 %330 %81 %7 -%332 = OpLoad %8 %57 +%331 = OpImageSampleDrefImplicitLod %8 %330 %81 %72 +%332 = OpLoad %8 %54 %333 = OpFAdd %8 %332 %331 -OpStore %57 %333 -%334 = OpAccessChain %128 %40 %5 -%335 = OpLoad %18 %334 -%336 = OpAccessChain %131 %46 %5 -%337 = OpLoad %22 %336 +OpStore %54 %333 +%334 = OpAccessChain %128 %37 %70 +%335 = OpLoad %15 %334 +%336 = OpAccessChain %131 %43 %70 +%337 = OpLoad %19 %336 %338 = OpSampledImage %134 %335 %337 -%339 = OpImageSampleDrefExplicitLod %8 %338 %81 %7 Lod %7 -%340 = OpLoad %8 %57 +%339 = OpImageSampleDrefExplicitLod %8 %338 %81 %72 Lod %72 +%340 = OpLoad %8 %54 %341 = OpFAdd %8 %340 %339 -OpStore %57 %341 -%342 = OpAccessChain %128 %40 %77 -%343 = OpLoad %18 %342 -%344 = OpAccessChain %131 %46 %77 -%345 = OpLoad %22 %344 +OpStore %54 %341 +%342 = OpAccessChain %128 %37 %77 +%343 = OpLoad %15 %342 +%344 = OpAccessChain %131 %43 %77 +%345 = OpLoad %19 %344 %346 = OpSampledImage %134 %343 %345 -%347 = OpImageSampleDrefExplicitLod %8 %346 %81 %7 Lod %7 -%348 = OpLoad %8 %57 +%347 = OpImageSampleDrefExplicitLod %8 %346 %81 %72 Lod %72 +%348 = OpLoad %8 %54 %349 = OpFAdd %8 %348 %347 -OpStore %57 %349 -%350 = OpAccessChain %128 %40 %78 -%351 = OpLoad %18 %350 -%352 = OpAccessChain %131 %46 %78 -%353 = OpLoad %22 %352 +OpStore %54 %349 +%350 = OpAccessChain %128 %37 %78 +%351 = OpLoad %15 %350 +%352 = OpAccessChain %131 %43 %78 +%353 = OpLoad %19 %352 %354 = OpSampledImage %134 %351 %353 -%355 = OpImageSampleDrefExplicitLod %8 %354 %81 %7 Lod %7 -%356 = OpLoad %8 %57 +%355 = OpImageSampleDrefExplicitLod %8 %354 %81 %72 Lod %72 +%356 = OpLoad %8 %54 %357 = OpFAdd %8 %356 %355 -OpStore %57 %357 -%358 = OpAccessChain %83 %34 %5 -%359 = OpLoad %11 %358 -%360 = OpAccessChain %104 %44 %5 -%361 = OpLoad %22 %360 +OpStore %54 %357 +%358 = OpAccessChain %83 %31 %70 +%359 = OpLoad %7 %358 +%360 = OpAccessChain %104 %41 %70 +%361 = OpLoad %19 %360 %362 = OpSampledImage %107 %359 %361 -%363 = OpImageSampleExplicitLod %26 %362 %81 Grad %81 %81 -%364 = OpLoad %26 %60 -%365 = OpFAdd %26 %364 %363 -OpStore %60 %365 -%366 = OpAccessChain %83 %34 %77 -%367 = OpLoad %11 %366 -%368 = OpAccessChain %104 %44 %77 -%369 = OpLoad %22 %368 +%363 = OpImageSampleExplicitLod %23 %362 %81 Grad %81 %81 +%364 = OpLoad %23 %57 +%365 = OpFAdd %23 %364 %363 +OpStore %57 %365 +%366 = OpAccessChain %83 %31 %77 +%367 = OpLoad %7 %366 +%368 = OpAccessChain %104 %41 %77 +%369 = OpLoad %19 %368 %370 = OpSampledImage %107 %367 %369 -%371 = OpImageSampleExplicitLod %26 %370 %81 Grad %81 %81 -%372 = OpLoad %26 %60 -%373 = OpFAdd %26 %372 %371 -OpStore %60 %373 -%374 = OpAccessChain %83 %34 %78 -%375 = OpLoad %11 %374 -%376 = OpAccessChain %104 %44 %78 -%377 = OpLoad %22 %376 +%371 = OpImageSampleExplicitLod %23 %370 %81 Grad %81 %81 +%372 = OpLoad %23 %57 +%373 = OpFAdd %23 %372 %371 +OpStore %57 %373 +%374 = OpAccessChain %83 %31 %78 +%375 = OpLoad %7 %374 +%376 = OpAccessChain %104 %41 %78 +%377 = OpLoad %19 %376 %378 = OpSampledImage %107 %375 %377 -%379 = OpImageSampleExplicitLod %26 %378 %81 Grad %81 %81 -%380 = OpLoad %26 %60 -%381 = OpFAdd %26 %380 %379 -OpStore %60 %381 -%382 = OpAccessChain %83 %34 %5 -%383 = OpLoad %11 %382 -%384 = OpAccessChain %104 %44 %5 -%385 = OpLoad %22 %384 +%379 = OpImageSampleExplicitLod %23 %378 %81 Grad %81 %81 +%380 = OpLoad %23 %57 +%381 = OpFAdd %23 %380 %379 +OpStore %57 %381 +%382 = OpAccessChain %83 %31 %70 +%383 = OpLoad %7 %382 +%384 = OpAccessChain %104 %41 %70 +%385 = OpLoad %19 %384 %386 = OpSampledImage %107 %383 %385 -%387 = OpImageSampleExplicitLod %26 %386 %81 Lod %7 -%388 = OpLoad %26 %60 -%389 = OpFAdd %26 %388 %387 -OpStore %60 %389 -%390 = OpAccessChain %83 %34 %77 -%391 = OpLoad %11 %390 -%392 = OpAccessChain %104 %44 %77 -%393 = OpLoad %22 %392 +%387 = OpImageSampleExplicitLod %23 %386 %81 Lod %72 +%388 = OpLoad %23 %57 +%389 = OpFAdd %23 %388 %387 +OpStore %57 %389 +%390 = OpAccessChain %83 %31 %77 +%391 = OpLoad %7 %390 +%392 = OpAccessChain %104 %41 %77 +%393 = OpLoad %19 %392 %394 = OpSampledImage %107 %391 %393 -%395 = OpImageSampleExplicitLod %26 %394 %81 Lod %7 -%396 = OpLoad %26 %60 -%397 = OpFAdd %26 %396 %395 -OpStore %60 %397 -%398 = OpAccessChain %83 %34 %78 -%399 = OpLoad %11 %398 -%400 = OpAccessChain %104 %44 %78 -%401 = OpLoad %22 %400 +%395 = OpImageSampleExplicitLod %23 %394 %81 Lod %72 +%396 = OpLoad %23 %57 +%397 = OpFAdd %23 %396 %395 +OpStore %57 %397 +%398 = OpAccessChain %83 %31 %78 +%399 = OpLoad %7 %398 +%400 = OpAccessChain %104 %41 %78 +%401 = OpLoad %19 %400 %402 = OpSampledImage %107 %399 %401 -%403 = OpImageSampleExplicitLod %26 %402 %81 Lod %7 -%404 = OpLoad %26 %60 -%405 = OpFAdd %26 %404 %403 -OpStore %60 %405 -%407 = OpAccessChain %406 %42 %5 -%408 = OpLoad %20 %407 -%409 = OpLoad %26 %60 -%410 = OpImageQuerySize %29 %408 +%403 = OpImageSampleExplicitLod %23 %402 %81 Lod %72 +%404 = OpLoad %23 %57 +%405 = OpFAdd %23 %404 %403 +OpStore %57 %405 +%407 = OpAccessChain %406 %39 %70 +%408 = OpLoad %17 %407 +%409 = OpLoad %23 %57 +%410 = OpImageQuerySize %26 %408 %411 = OpULessThan %164 %82 %410 %412 = OpAll %157 %411 OpSelectionMerge %413 None @@ -530,10 +530,10 @@ OpBranchConditional %412 %414 %413 OpImageWrite %408 %82 %409 OpBranch %413 %413 = OpLabel -%415 = OpAccessChain %406 %42 %77 -%416 = OpLoad %20 %415 -%417 = OpLoad %26 %60 -%418 = OpImageQuerySize %29 %416 +%415 = OpAccessChain %406 %39 %77 +%416 = OpLoad %17 %415 +%417 = OpLoad %23 %57 +%418 = OpImageQuerySize %26 %416 %419 = OpULessThan %164 %82 %418 %420 = OpAll %157 %419 OpSelectionMerge %421 None @@ -542,10 +542,10 @@ OpBranchConditional %420 %422 %421 OpImageWrite %416 %82 %417 OpBranch %421 %421 = OpLabel -%423 = OpAccessChain %406 %42 %78 -%424 = OpLoad %20 %423 -%425 = OpLoad %26 %60 -%426 = OpImageQuerySize %29 %424 +%423 = OpAccessChain %406 %39 %78 +%424 = OpLoad %17 %423 +%425 = OpLoad %23 %57 +%426 = OpImageQuerySize %26 %424 %427 = OpULessThan %164 %82 %426 %428 = OpAll %157 %427 OpSelectionMerge %429 None @@ -554,21 +554,21 @@ OpBranchConditional %428 %430 %429 OpImageWrite %424 %82 %425 OpBranch %429 %429 = OpLabel -%431 = OpLoad %27 %54 -%432 = OpLoad %6 %51 -%433 = OpCompositeConstruct %27 %432 %432 -%434 = OpIAdd %27 %431 %433 -%435 = OpConvertUToF %28 %434 -%436 = OpLoad %26 %60 +%431 = OpLoad %24 %51 +%432 = OpLoad %5 %48 +%433 = OpCompositeConstruct %24 %432 %432 +%434 = OpIAdd %24 %431 %433 +%435 = OpConvertUToF %25 %434 +%436 = OpLoad %23 %57 %437 = OpCompositeExtract %8 %435 0 %438 = OpCompositeExtract %8 %435 1 %439 = OpCompositeExtract %8 %435 0 %440 = OpCompositeExtract %8 %435 1 -%441 = OpCompositeConstruct %26 %437 %438 %439 %440 -%442 = OpFAdd %26 %436 %441 -%443 = OpLoad %8 %57 -%444 = OpCompositeConstruct %26 %443 %443 %443 %443 -%445 = OpFAdd %26 %442 %444 -OpStore %68 %445 +%441 = OpCompositeConstruct %23 %437 %438 %439 %440 +%442 = OpFAdd %23 %436 %441 +%443 = OpLoad %8 %54 +%444 = OpCompositeConstruct %23 %443 %443 %443 %443 +%445 = OpFAdd %23 %442 %444 +OpStore %65 %445 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-buffer-arrays.spvasm b/tests/out/spv/binding-buffer-arrays.spvasm index cd73bd756..28f32415f 100644 --- a/tests/out/spv/binding-buffer-arrays.spvasm +++ b/tests/out/spv/binding-buffer-arrays.spvasm @@ -8,98 +8,98 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %29 "main" %24 %27 -OpExecutionMode %29 OriginUpperLeft -OpMemberDecorate %8 0 Offset 0 +OpEntryPoint Fragment %27 "main" %22 %25 +OpExecutionMode %27 OriginUpperLeft +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %7 0 Offset 0 OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %11 0 Offset 0 -OpDecorate %12 NonWritable -OpDecorate %12 DescriptorSet 0 -OpDecorate %12 Binding 0 -OpDecorate %9 Block -OpDecorate %16 DescriptorSet 0 -OpDecorate %16 Binding 10 -OpDecorate %17 Block -OpMemberDecorate %17 0 Offset 0 -OpDecorate %24 Location 0 -OpDecorate %24 Flat -OpDecorate %27 Location 0 +OpDecorate %10 NonWritable +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 0 +OpDecorate %7 Block +OpDecorate %14 DescriptorSet 0 +OpDecorate %14 Binding 10 +OpDecorate %15 Block +OpMemberDecorate %15 0 Offset 0 +OpDecorate %22 Location 0 +OpDecorate %22 Flat +OpDecorate %25 Location 0 OpDecorate %57 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 0 -%7 = OpConstant %4 0 -%8 = OpTypeStruct %6 -%9 = OpTypeStruct %6 -%10 = OpTypeArray %9 %3 -%11 = OpTypeStruct %6 -%15 = OpConstant %6 10 -%14 = OpTypeArray %9 %15 -%13 = OpTypePointer StorageBuffer %14 -%12 = OpVariable %13 StorageBuffer -%17 = OpTypeStruct %8 -%18 = OpTypePointer Uniform %17 -%16 = OpVariable %18 Uniform -%20 = OpTypePointer Function %6 -%21 = OpConstantNull %6 -%25 = OpTypePointer Input %6 -%24 = OpVariable %25 Input -%28 = OpTypePointer Output %6 -%27 = OpVariable %28 Output -%30 = OpTypeFunction %2 -%31 = OpTypePointer Uniform %8 -%33 = OpTypePointer StorageBuffer %10 -%35 = OpTypePointer Uniform %6 -%39 = OpTypePointer StorageBuffer %9 -%40 = OpTypePointer StorageBuffer %6 -%45 = OpConstant %6 1 +%5 = OpTypeInt 32 0 +%6 = OpTypeStruct %5 +%7 = OpTypeStruct %5 +%8 = OpTypeArray %7 %3 +%9 = OpTypeStruct %5 +%13 = OpConstant %5 10 +%12 = OpTypeArray %7 %13 +%11 = OpTypePointer StorageBuffer %12 +%10 = OpVariable %11 StorageBuffer +%15 = OpTypeStruct %6 +%16 = OpTypePointer Uniform %15 +%14 = OpVariable %16 Uniform +%18 = OpTypePointer Function %5 +%19 = OpConstantNull %5 +%23 = OpTypePointer Input %5 +%22 = OpVariable %23 Input +%26 = OpTypePointer Output %5 +%25 = OpVariable %26 Output +%28 = OpTypeFunction %2 +%29 = OpTypePointer Uniform %6 +%30 = OpConstant %5 0 +%32 = OpTypePointer StorageBuffer %8 +%33 = OpConstant %4 0 +%35 = OpTypePointer Uniform %5 +%39 = OpTypePointer StorageBuffer %7 +%40 = OpTypePointer StorageBuffer %5 +%45 = OpConstant %5 1 %47 = OpTypeBool -%49 = OpConstantNull %6 -%58 = OpConstantNull %6 -%29 = OpFunction %2 None %30 -%22 = OpLabel -%19 = OpVariable %20 Function %21 -%26 = OpLoad %6 %24 -%23 = OpCompositeConstruct %11 %26 -%32 = OpAccessChain %31 %16 %5 +%49 = OpConstantNull %5 +%58 = OpConstantNull %5 +%27 = OpFunction %2 None %28 +%20 = OpLabel +%17 = OpVariable %18 Function %19 +%24 = OpLoad %5 %22 +%21 = OpCompositeConstruct %9 %24 +%31 = OpAccessChain %29 %14 %30 OpBranch %34 %34 = OpLabel -%36 = OpAccessChain %35 %32 %5 -%37 = OpLoad %6 %36 -%38 = OpCompositeExtract %6 %23 0 -OpStore %19 %5 -%41 = OpAccessChain %40 %12 %5 %5 -%42 = OpLoad %6 %41 -%43 = OpLoad %6 %19 -%44 = OpIAdd %6 %43 %42 -OpStore %19 %44 +%36 = OpAccessChain %35 %31 %30 +%37 = OpLoad %5 %36 +%38 = OpCompositeExtract %5 %21 0 +OpStore %17 %30 +%41 = OpAccessChain %40 %10 %30 %30 +%42 = OpLoad %5 %41 +%43 = OpLoad %5 %17 +%44 = OpIAdd %5 %43 %42 +OpStore %17 %44 %46 = OpULessThan %47 %37 %45 OpSelectionMerge %50 None OpBranchConditional %46 %51 %50 %51 = OpLabel -%48 = OpAccessChain %40 %12 %37 %5 -%52 = OpLoad %6 %48 +%48 = OpAccessChain %40 %10 %37 %30 +%52 = OpLoad %5 %48 OpBranch %50 %50 = OpLabel -%53 = OpPhi %6 %49 %34 %52 %51 -%54 = OpLoad %6 %19 -%55 = OpIAdd %6 %54 %53 -OpStore %19 %55 +%53 = OpPhi %5 %49 %34 %52 %51 +%54 = OpLoad %5 %17 +%55 = OpIAdd %5 %54 %53 +OpStore %17 %55 %56 = OpULessThan %47 %38 %45 OpSelectionMerge %59 None OpBranchConditional %56 %60 %59 %60 = OpLabel -%57 = OpAccessChain %40 %12 %38 %5 -%61 = OpLoad %6 %57 +%57 = OpAccessChain %40 %10 %38 %30 +%61 = OpLoad %5 %57 OpBranch %59 %59 = OpLabel -%62 = OpPhi %6 %58 %50 %61 %60 -%63 = OpLoad %6 %19 -%64 = OpIAdd %6 %63 %62 -OpStore %19 %64 -%65 = OpLoad %6 %19 -OpStore %27 %65 +%62 = OpPhi %5 %58 %50 %61 %60 +%63 = OpLoad %5 %17 +%64 = OpIAdd %5 %63 %62 +OpStore %17 %64 +%65 = OpLoad %5 %17 +OpStore %25 %65 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bitcast.spvasm b/tests/out/spv/bitcast.spvasm index 6fffef8dc..f8b0c9327 100644 --- a/tests/out/spv/bitcast.spvasm +++ b/tests/out/spv/bitcast.spvasm @@ -5,100 +5,100 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %46 "main" -OpExecutionMode %46 LocalSize 1 1 1 +OpEntryPoint GLCompute %43 "main" +OpExecutionMode %43 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeInt 32 1 -%3 = OpConstant %4 0 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 0 -%8 = OpTypeFloat 32 -%7 = OpConstant %8 0.0 -%9 = OpTypeVector %4 2 -%10 = OpTypeVector %4 3 -%11 = OpTypeVector %4 4 -%12 = OpTypeVector %6 2 -%13 = OpTypeVector %6 3 -%14 = OpTypeVector %6 4 -%15 = OpTypeVector %8 2 -%16 = OpTypeVector %8 3 -%17 = OpTypeVector %8 4 -%19 = OpTypePointer Function %9 -%20 = OpConstantNull %9 -%22 = OpTypePointer Function %10 -%23 = OpConstantNull %10 -%25 = OpTypePointer Function %11 -%26 = OpConstantNull %11 -%28 = OpTypePointer Function %12 -%29 = OpConstantNull %12 -%31 = OpTypePointer Function %13 -%32 = OpConstantNull %13 -%34 = OpTypePointer Function %14 -%35 = OpConstantNull %14 -%37 = OpTypePointer Function %15 -%38 = OpConstantNull %15 -%40 = OpTypePointer Function %16 -%41 = OpConstantNull %16 -%43 = OpTypePointer Function %17 -%44 = OpConstantNull %17 -%47 = OpTypeFunction %2 -%46 = OpFunction %2 None %47 -%45 = OpLabel +%3 = OpTypeVector %4 2 +%5 = OpTypeVector %4 3 +%6 = OpTypeVector %4 4 +%8 = OpTypeInt 32 0 +%7 = OpTypeVector %8 2 +%9 = OpTypeVector %8 3 +%10 = OpTypeVector %8 4 +%12 = OpTypeFloat 32 +%11 = OpTypeVector %12 2 +%13 = OpTypeVector %12 3 +%14 = OpTypeVector %12 4 +%16 = OpTypePointer Function %3 +%17 = OpConstantNull %3 +%19 = OpTypePointer Function %5 +%20 = OpConstantNull %5 +%22 = OpTypePointer Function %6 +%23 = OpConstantNull %6 +%25 = OpTypePointer Function %7 +%26 = OpConstantNull %7 +%28 = OpTypePointer Function %9 +%29 = OpConstantNull %9 +%31 = OpTypePointer Function %10 +%32 = OpConstantNull %10 +%34 = OpTypePointer Function %11 +%35 = OpConstantNull %11 +%37 = OpTypePointer Function %13 +%38 = OpConstantNull %13 +%40 = OpTypePointer Function %14 +%41 = OpConstantNull %14 +%44 = OpTypeFunction %2 +%45 = OpConstant %4 0 +%46 = OpConstant %8 0 +%47 = OpConstant %12 0.0 +%43 = OpFunction %2 None %44 +%42 = OpLabel +%33 = OpVariable %34 Function %35 +%24 = OpVariable %25 Function %26 +%15 = OpVariable %16 Function %17 %36 = OpVariable %37 Function %38 %27 = OpVariable %28 Function %29 %18 = OpVariable %19 Function %20 %39 = OpVariable %40 Function %41 %30 = OpVariable %31 Function %32 %21 = OpVariable %22 Function %23 -%42 = OpVariable %43 Function %44 -%33 = OpVariable %34 Function %35 -%24 = OpVariable %25 Function %26 OpBranch %48 %48 = OpLabel -%49 = OpCompositeConstruct %9 %3 %3 -OpStore %18 %49 -%50 = OpCompositeConstruct %10 %3 %3 %3 -OpStore %21 %50 -%51 = OpCompositeConstruct %11 %3 %3 %3 %3 -OpStore %24 %51 -%52 = OpCompositeConstruct %12 %5 %5 -OpStore %27 %52 -%53 = OpCompositeConstruct %13 %5 %5 %5 -OpStore %30 %53 -%54 = OpCompositeConstruct %14 %5 %5 %5 %5 -OpStore %33 %54 -%55 = OpCompositeConstruct %15 %7 %7 -OpStore %36 %55 -%56 = OpCompositeConstruct %16 %7 %7 %7 -OpStore %39 %56 -%57 = OpCompositeConstruct %17 %7 %7 %7 %7 -OpStore %42 %57 -%58 = OpLoad %9 %18 -%59 = OpBitcast %12 %58 -OpStore %27 %59 -%60 = OpLoad %10 %21 -%61 = OpBitcast %13 %60 -OpStore %30 %61 -%62 = OpLoad %11 %24 -%63 = OpBitcast %14 %62 -OpStore %33 %63 -%64 = OpLoad %12 %27 -%65 = OpBitcast %9 %64 -OpStore %18 %65 -%66 = OpLoad %13 %30 -%67 = OpBitcast %10 %66 -OpStore %21 %67 -%68 = OpLoad %14 %33 -%69 = OpBitcast %11 %68 -OpStore %24 %69 -%70 = OpLoad %9 %18 -%71 = OpBitcast %15 %70 -OpStore %36 %71 -%72 = OpLoad %10 %21 -%73 = OpBitcast %16 %72 -OpStore %39 %73 -%74 = OpLoad %11 %24 -%75 = OpBitcast %17 %74 -OpStore %42 %75 +%49 = OpCompositeConstruct %3 %45 %45 +OpStore %15 %49 +%50 = OpCompositeConstruct %5 %45 %45 %45 +OpStore %18 %50 +%51 = OpCompositeConstruct %6 %45 %45 %45 %45 +OpStore %21 %51 +%52 = OpCompositeConstruct %7 %46 %46 +OpStore %24 %52 +%53 = OpCompositeConstruct %9 %46 %46 %46 +OpStore %27 %53 +%54 = OpCompositeConstruct %10 %46 %46 %46 %46 +OpStore %30 %54 +%55 = OpCompositeConstruct %11 %47 %47 +OpStore %33 %55 +%56 = OpCompositeConstruct %13 %47 %47 %47 +OpStore %36 %56 +%57 = OpCompositeConstruct %14 %47 %47 %47 %47 +OpStore %39 %57 +%58 = OpLoad %3 %15 +%59 = OpBitcast %7 %58 +OpStore %24 %59 +%60 = OpLoad %5 %18 +%61 = OpBitcast %9 %60 +OpStore %27 %61 +%62 = OpLoad %6 %21 +%63 = OpBitcast %10 %62 +OpStore %30 %63 +%64 = OpLoad %7 %24 +%65 = OpBitcast %3 %64 +OpStore %15 %65 +%66 = OpLoad %9 %27 +%67 = OpBitcast %5 %66 +OpStore %18 %67 +%68 = OpLoad %10 %30 +%69 = OpBitcast %6 %68 +OpStore %21 %69 +%70 = OpLoad %3 %15 +%71 = OpBitcast %11 %70 +OpStore %33 %71 +%72 = OpLoad %5 %18 +%73 = OpBitcast %13 %72 +OpStore %36 %73 +%74 = OpLoad %6 %21 +%75 = OpBitcast %14 %74 +OpStore %39 %75 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm index 750a2545b..674167359 100644 --- a/tests/out/spv/bits.spvasm +++ b/tests/out/spv/bits.spvasm @@ -5,229 +5,229 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %50 "main" -OpExecutionMode %50 LocalSize 1 1 1 +OpEntryPoint GLCompute %45 "main" +OpExecutionMode %45 LocalSize 1 1 1 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 0 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 0 -%8 = OpTypeFloat 32 -%7 = OpConstant %8 0.0 -%9 = OpConstant %6 5 -%10 = OpConstant %6 10 -%11 = OpTypeVector %4 2 -%12 = OpTypeVector %4 3 -%13 = OpTypeVector %4 4 -%14 = OpTypeVector %6 2 -%15 = OpTypeVector %6 3 -%16 = OpTypeVector %6 4 -%17 = OpTypeVector %8 2 -%18 = OpTypeVector %8 4 -%20 = OpTypePointer Function %4 -%21 = OpConstantNull %4 -%23 = OpTypePointer Function %11 -%24 = OpConstantNull %11 -%26 = OpTypePointer Function %12 -%27 = OpConstantNull %12 -%29 = OpTypePointer Function %13 -%30 = OpConstantNull %13 -%32 = OpTypePointer Function %6 -%33 = OpConstantNull %6 -%35 = OpTypePointer Function %14 -%36 = OpConstantNull %14 -%38 = OpTypePointer Function %15 -%39 = OpConstantNull %15 -%41 = OpTypePointer Function %16 -%42 = OpConstantNull %16 -%44 = OpTypePointer Function %17 -%45 = OpConstantNull %17 -%47 = OpTypePointer Function %18 -%48 = OpConstantNull %18 -%51 = OpTypeFunction %2 -%50 = OpFunction %2 None %51 -%49 = OpLabel -%46 = OpVariable %47 Function %48 -%37 = OpVariable %38 Function %39 -%28 = OpVariable %29 Function %30 -%19 = OpVariable %20 Function %21 -%40 = OpVariable %41 Function %42 -%31 = OpVariable %32 Function %33 -%22 = OpVariable %23 Function %24 -%43 = OpVariable %44 Function %45 -%34 = OpVariable %35 Function %36 -%25 = OpVariable %26 Function %27 +%3 = OpTypeInt 32 1 +%4 = OpTypeVector %3 2 +%5 = OpTypeVector %3 3 +%6 = OpTypeVector %3 4 +%7 = OpTypeInt 32 0 +%8 = OpTypeVector %7 2 +%9 = OpTypeVector %7 3 +%10 = OpTypeVector %7 4 +%12 = OpTypeFloat 32 +%11 = OpTypeVector %12 2 +%13 = OpTypeVector %12 4 +%15 = OpTypePointer Function %3 +%16 = OpConstantNull %3 +%18 = OpTypePointer Function %4 +%19 = OpConstantNull %4 +%21 = OpTypePointer Function %5 +%22 = OpConstantNull %5 +%24 = OpTypePointer Function %6 +%25 = OpConstantNull %6 +%27 = OpTypePointer Function %7 +%28 = OpConstantNull %7 +%30 = OpTypePointer Function %8 +%31 = OpConstantNull %8 +%33 = OpTypePointer Function %9 +%34 = OpConstantNull %9 +%36 = OpTypePointer Function %10 +%37 = OpConstantNull %10 +%39 = OpTypePointer Function %11 +%40 = OpConstantNull %11 +%42 = OpTypePointer Function %13 +%43 = OpConstantNull %13 +%46 = OpTypeFunction %2 +%47 = OpConstant %3 0 +%48 = OpConstant %7 0 +%49 = OpConstant %12 0.0 +%50 = OpConstant %7 5 +%51 = OpConstant %7 10 +%45 = OpFunction %2 None %46 +%44 = OpLabel +%41 = OpVariable %42 Function %43 +%32 = OpVariable %33 Function %34 +%23 = OpVariable %24 Function %25 +%14 = OpVariable %15 Function %16 +%35 = OpVariable %36 Function %37 +%26 = OpVariable %27 Function %28 +%17 = OpVariable %18 Function %19 +%38 = OpVariable %39 Function %40 +%29 = OpVariable %30 Function %31 +%20 = OpVariable %21 Function %22 OpBranch %52 %52 = OpLabel -OpStore %19 %3 -%53 = OpCompositeConstruct %11 %3 %3 -OpStore %22 %53 -%54 = OpCompositeConstruct %12 %3 %3 %3 -OpStore %25 %54 -%55 = OpCompositeConstruct %13 %3 %3 %3 %3 -OpStore %28 %55 -OpStore %31 %5 -%56 = OpCompositeConstruct %14 %5 %5 -OpStore %34 %56 -%57 = OpCompositeConstruct %15 %5 %5 %5 -OpStore %37 %57 -%58 = OpCompositeConstruct %16 %5 %5 %5 %5 -OpStore %40 %58 -%59 = OpCompositeConstruct %17 %7 %7 -OpStore %43 %59 -%60 = OpCompositeConstruct %18 %7 %7 %7 %7 -OpStore %46 %60 -%61 = OpLoad %18 %46 -%62 = OpExtInst %6 %1 PackSnorm4x8 %61 -OpStore %31 %62 -%63 = OpLoad %18 %46 -%64 = OpExtInst %6 %1 PackUnorm4x8 %63 -OpStore %31 %64 -%65 = OpLoad %17 %43 -%66 = OpExtInst %6 %1 PackSnorm2x16 %65 -OpStore %31 %66 -%67 = OpLoad %17 %43 -%68 = OpExtInst %6 %1 PackUnorm2x16 %67 -OpStore %31 %68 -%69 = OpLoad %17 %43 -%70 = OpExtInst %6 %1 PackHalf2x16 %69 -OpStore %31 %70 -%71 = OpLoad %6 %31 -%72 = OpExtInst %18 %1 UnpackSnorm4x8 %71 -OpStore %46 %72 -%73 = OpLoad %6 %31 -%74 = OpExtInst %18 %1 UnpackUnorm4x8 %73 -OpStore %46 %74 -%75 = OpLoad %6 %31 -%76 = OpExtInst %17 %1 UnpackSnorm2x16 %75 -OpStore %43 %76 -%77 = OpLoad %6 %31 -%78 = OpExtInst %17 %1 UnpackUnorm2x16 %77 -OpStore %43 %78 -%79 = OpLoad %6 %31 -%80 = OpExtInst %17 %1 UnpackHalf2x16 %79 -OpStore %43 %80 -%81 = OpLoad %4 %19 -%82 = OpLoad %4 %19 -%83 = OpBitFieldInsert %4 %81 %82 %9 %10 -OpStore %19 %83 -%84 = OpLoad %11 %22 -%85 = OpLoad %11 %22 -%86 = OpBitFieldInsert %11 %84 %85 %9 %10 -OpStore %22 %86 -%87 = OpLoad %12 %25 -%88 = OpLoad %12 %25 -%89 = OpBitFieldInsert %12 %87 %88 %9 %10 -OpStore %25 %89 -%90 = OpLoad %13 %28 -%91 = OpLoad %13 %28 -%92 = OpBitFieldInsert %13 %90 %91 %9 %10 -OpStore %28 %92 -%93 = OpLoad %6 %31 -%94 = OpLoad %6 %31 -%95 = OpBitFieldInsert %6 %93 %94 %9 %10 -OpStore %31 %95 -%96 = OpLoad %14 %34 -%97 = OpLoad %14 %34 -%98 = OpBitFieldInsert %14 %96 %97 %9 %10 -OpStore %34 %98 -%99 = OpLoad %15 %37 -%100 = OpLoad %15 %37 -%101 = OpBitFieldInsert %15 %99 %100 %9 %10 -OpStore %37 %101 -%102 = OpLoad %16 %40 -%103 = OpLoad %16 %40 -%104 = OpBitFieldInsert %16 %102 %103 %9 %10 -OpStore %40 %104 -%105 = OpLoad %4 %19 -%106 = OpBitFieldSExtract %4 %105 %9 %10 -OpStore %19 %106 -%107 = OpLoad %11 %22 -%108 = OpBitFieldSExtract %11 %107 %9 %10 -OpStore %22 %108 -%109 = OpLoad %12 %25 -%110 = OpBitFieldSExtract %12 %109 %9 %10 -OpStore %25 %110 -%111 = OpLoad %13 %28 -%112 = OpBitFieldSExtract %13 %111 %9 %10 -OpStore %28 %112 -%113 = OpLoad %6 %31 -%114 = OpBitFieldUExtract %6 %113 %9 %10 -OpStore %31 %114 -%115 = OpLoad %14 %34 -%116 = OpBitFieldUExtract %14 %115 %9 %10 -OpStore %34 %116 -%117 = OpLoad %15 %37 -%118 = OpBitFieldUExtract %15 %117 %9 %10 -OpStore %37 %118 -%119 = OpLoad %16 %40 -%120 = OpBitFieldUExtract %16 %119 %9 %10 -OpStore %40 %120 -%121 = OpLoad %4 %19 -%122 = OpExtInst %4 %1 FindILsb %121 -OpStore %19 %122 -%123 = OpLoad %14 %34 -%124 = OpExtInst %14 %1 FindILsb %123 -OpStore %34 %124 -%125 = OpLoad %12 %25 -%126 = OpExtInst %12 %1 FindSMsb %125 -OpStore %25 %126 -%127 = OpLoad %15 %37 -%128 = OpExtInst %15 %1 FindUMsb %127 -OpStore %37 %128 -%129 = OpLoad %4 %19 -%130 = OpExtInst %4 %1 FindSMsb %129 -OpStore %19 %130 -%131 = OpLoad %6 %31 -%132 = OpExtInst %6 %1 FindUMsb %131 -OpStore %31 %132 -%133 = OpLoad %4 %19 -%134 = OpBitCount %4 %133 -OpStore %19 %134 -%135 = OpLoad %11 %22 -%136 = OpBitCount %11 %135 -OpStore %22 %136 -%137 = OpLoad %12 %25 -%138 = OpBitCount %12 %137 -OpStore %25 %138 -%139 = OpLoad %13 %28 -%140 = OpBitCount %13 %139 -OpStore %28 %140 -%141 = OpLoad %6 %31 -%142 = OpBitCount %6 %141 -OpStore %31 %142 -%143 = OpLoad %14 %34 -%144 = OpBitCount %14 %143 -OpStore %34 %144 -%145 = OpLoad %15 %37 -%146 = OpBitCount %15 %145 -OpStore %37 %146 -%147 = OpLoad %16 %40 -%148 = OpBitCount %16 %147 -OpStore %40 %148 -%149 = OpLoad %4 %19 -%150 = OpBitReverse %4 %149 -OpStore %19 %150 -%151 = OpLoad %11 %22 -%152 = OpBitReverse %11 %151 -OpStore %22 %152 -%153 = OpLoad %12 %25 -%154 = OpBitReverse %12 %153 -OpStore %25 %154 -%155 = OpLoad %13 %28 -%156 = OpBitReverse %13 %155 -OpStore %28 %156 -%157 = OpLoad %6 %31 -%158 = OpBitReverse %6 %157 -OpStore %31 %158 -%159 = OpLoad %14 %34 -%160 = OpBitReverse %14 %159 -OpStore %34 %160 -%161 = OpLoad %15 %37 -%162 = OpBitReverse %15 %161 -OpStore %37 %162 -%163 = OpLoad %16 %40 -%164 = OpBitReverse %16 %163 -OpStore %40 %164 +OpStore %14 %47 +%53 = OpCompositeConstruct %4 %47 %47 +OpStore %17 %53 +%54 = OpCompositeConstruct %5 %47 %47 %47 +OpStore %20 %54 +%55 = OpCompositeConstruct %6 %47 %47 %47 %47 +OpStore %23 %55 +OpStore %26 %48 +%56 = OpCompositeConstruct %8 %48 %48 +OpStore %29 %56 +%57 = OpCompositeConstruct %9 %48 %48 %48 +OpStore %32 %57 +%58 = OpCompositeConstruct %10 %48 %48 %48 %48 +OpStore %35 %58 +%59 = OpCompositeConstruct %11 %49 %49 +OpStore %38 %59 +%60 = OpCompositeConstruct %13 %49 %49 %49 %49 +OpStore %41 %60 +%61 = OpLoad %13 %41 +%62 = OpExtInst %7 %1 PackSnorm4x8 %61 +OpStore %26 %62 +%63 = OpLoad %13 %41 +%64 = OpExtInst %7 %1 PackUnorm4x8 %63 +OpStore %26 %64 +%65 = OpLoad %11 %38 +%66 = OpExtInst %7 %1 PackSnorm2x16 %65 +OpStore %26 %66 +%67 = OpLoad %11 %38 +%68 = OpExtInst %7 %1 PackUnorm2x16 %67 +OpStore %26 %68 +%69 = OpLoad %11 %38 +%70 = OpExtInst %7 %1 PackHalf2x16 %69 +OpStore %26 %70 +%71 = OpLoad %7 %26 +%72 = OpExtInst %13 %1 UnpackSnorm4x8 %71 +OpStore %41 %72 +%73 = OpLoad %7 %26 +%74 = OpExtInst %13 %1 UnpackUnorm4x8 %73 +OpStore %41 %74 +%75 = OpLoad %7 %26 +%76 = OpExtInst %11 %1 UnpackSnorm2x16 %75 +OpStore %38 %76 +%77 = OpLoad %7 %26 +%78 = OpExtInst %11 %1 UnpackUnorm2x16 %77 +OpStore %38 %78 +%79 = OpLoad %7 %26 +%80 = OpExtInst %11 %1 UnpackHalf2x16 %79 +OpStore %38 %80 +%81 = OpLoad %3 %14 +%82 = OpLoad %3 %14 +%83 = OpBitFieldInsert %3 %81 %82 %50 %51 +OpStore %14 %83 +%84 = OpLoad %4 %17 +%85 = OpLoad %4 %17 +%86 = OpBitFieldInsert %4 %84 %85 %50 %51 +OpStore %17 %86 +%87 = OpLoad %5 %20 +%88 = OpLoad %5 %20 +%89 = OpBitFieldInsert %5 %87 %88 %50 %51 +OpStore %20 %89 +%90 = OpLoad %6 %23 +%91 = OpLoad %6 %23 +%92 = OpBitFieldInsert %6 %90 %91 %50 %51 +OpStore %23 %92 +%93 = OpLoad %7 %26 +%94 = OpLoad %7 %26 +%95 = OpBitFieldInsert %7 %93 %94 %50 %51 +OpStore %26 %95 +%96 = OpLoad %8 %29 +%97 = OpLoad %8 %29 +%98 = OpBitFieldInsert %8 %96 %97 %50 %51 +OpStore %29 %98 +%99 = OpLoad %9 %32 +%100 = OpLoad %9 %32 +%101 = OpBitFieldInsert %9 %99 %100 %50 %51 +OpStore %32 %101 +%102 = OpLoad %10 %35 +%103 = OpLoad %10 %35 +%104 = OpBitFieldInsert %10 %102 %103 %50 %51 +OpStore %35 %104 +%105 = OpLoad %3 %14 +%106 = OpBitFieldSExtract %3 %105 %50 %51 +OpStore %14 %106 +%107 = OpLoad %4 %17 +%108 = OpBitFieldSExtract %4 %107 %50 %51 +OpStore %17 %108 +%109 = OpLoad %5 %20 +%110 = OpBitFieldSExtract %5 %109 %50 %51 +OpStore %20 %110 +%111 = OpLoad %6 %23 +%112 = OpBitFieldSExtract %6 %111 %50 %51 +OpStore %23 %112 +%113 = OpLoad %7 %26 +%114 = OpBitFieldUExtract %7 %113 %50 %51 +OpStore %26 %114 +%115 = OpLoad %8 %29 +%116 = OpBitFieldUExtract %8 %115 %50 %51 +OpStore %29 %116 +%117 = OpLoad %9 %32 +%118 = OpBitFieldUExtract %9 %117 %50 %51 +OpStore %32 %118 +%119 = OpLoad %10 %35 +%120 = OpBitFieldUExtract %10 %119 %50 %51 +OpStore %35 %120 +%121 = OpLoad %3 %14 +%122 = OpExtInst %3 %1 FindILsb %121 +OpStore %14 %122 +%123 = OpLoad %8 %29 +%124 = OpExtInst %8 %1 FindILsb %123 +OpStore %29 %124 +%125 = OpLoad %5 %20 +%126 = OpExtInst %5 %1 FindSMsb %125 +OpStore %20 %126 +%127 = OpLoad %9 %32 +%128 = OpExtInst %9 %1 FindUMsb %127 +OpStore %32 %128 +%129 = OpLoad %3 %14 +%130 = OpExtInst %3 %1 FindSMsb %129 +OpStore %14 %130 +%131 = OpLoad %7 %26 +%132 = OpExtInst %7 %1 FindUMsb %131 +OpStore %26 %132 +%133 = OpLoad %3 %14 +%134 = OpBitCount %3 %133 +OpStore %14 %134 +%135 = OpLoad %4 %17 +%136 = OpBitCount %4 %135 +OpStore %17 %136 +%137 = OpLoad %5 %20 +%138 = OpBitCount %5 %137 +OpStore %20 %138 +%139 = OpLoad %6 %23 +%140 = OpBitCount %6 %139 +OpStore %23 %140 +%141 = OpLoad %7 %26 +%142 = OpBitCount %7 %141 +OpStore %26 %142 +%143 = OpLoad %8 %29 +%144 = OpBitCount %8 %143 +OpStore %29 %144 +%145 = OpLoad %9 %32 +%146 = OpBitCount %9 %145 +OpStore %32 %146 +%147 = OpLoad %10 %35 +%148 = OpBitCount %10 %147 +OpStore %35 %148 +%149 = OpLoad %3 %14 +%150 = OpBitReverse %3 %149 +OpStore %14 %150 +%151 = OpLoad %4 %17 +%152 = OpBitReverse %4 %151 +OpStore %17 %152 +%153 = OpLoad %5 %20 +%154 = OpBitReverse %5 %153 +OpStore %20 %154 +%155 = OpLoad %6 %23 +%156 = OpBitReverse %6 %155 +OpStore %23 %156 +%157 = OpLoad %7 %26 +%158 = OpBitReverse %7 %157 +OpStore %26 %158 +%159 = OpLoad %8 %29 +%160 = OpBitReverse %8 %159 +OpStore %29 %160 +%161 = OpLoad %9 %32 +%162 = OpBitReverse %9 %161 +OpStore %32 %162 +%163 = OpLoad %10 %35 +%164 = OpBitReverse %10 %163 +OpStore %35 %164 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 070504436..002959167 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -6,107 +6,107 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %54 "main" %51 -OpExecutionMode %54 LocalSize 64 1 1 +OpEntryPoint GLCompute %46 "main" %43 +OpExecutionMode %46 LocalSize 64 1 1 OpSource GLSL 450 OpName %3 "NUM_PARTICLES" -OpMemberName %16 0 "pos" -OpMemberName %16 1 "vel" -OpName %16 "Particle" -OpMemberName %17 0 "deltaT" -OpMemberName %17 1 "rule1Distance" -OpMemberName %17 2 "rule2Distance" -OpMemberName %17 3 "rule3Distance" -OpMemberName %17 4 "rule1Scale" -OpMemberName %17 5 "rule2Scale" -OpMemberName %17 6 "rule3Scale" -OpName %17 "SimParams" -OpMemberName %19 0 "particles" -OpName %19 "Particles" -OpName %21 "params" -OpName %24 "particlesSrc" -OpName %26 "particlesDst" -OpName %27 "vPos" -OpName %30 "vVel" -OpName %32 "cMass" -OpName %34 "cVel" -OpName %36 "colVel" -OpName %38 "cMassCount" -OpName %41 "cVelCount" -OpName %43 "pos" -OpName %45 "vel" -OpName %47 "i" -OpName %51 "global_invocation_id" -OpName %54 "main" -OpMemberDecorate %16 0 Offset 0 -OpMemberDecorate %16 1 Offset 8 -OpMemberDecorate %17 0 Offset 0 -OpMemberDecorate %17 1 Offset 4 -OpMemberDecorate %17 2 Offset 8 -OpMemberDecorate %17 3 Offset 12 -OpMemberDecorate %17 4 Offset 16 -OpMemberDecorate %17 5 Offset 20 -OpMemberDecorate %17 6 Offset 24 -OpDecorate %18 ArrayStride 16 -OpMemberDecorate %19 0 Offset 0 -OpDecorate %21 DescriptorSet 0 -OpDecorate %21 Binding 0 -OpDecorate %22 Block -OpMemberDecorate %22 0 Offset 0 -OpDecorate %24 NonWritable -OpDecorate %24 DescriptorSet 0 -OpDecorate %24 Binding 1 -OpDecorate %19 Block -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 2 -OpDecorate %19 Block -OpDecorate %51 BuiltIn GlobalInvocationId +OpMemberName %7 0 "pos" +OpMemberName %7 1 "vel" +OpName %7 "Particle" +OpMemberName %8 0 "deltaT" +OpMemberName %8 1 "rule1Distance" +OpMemberName %8 2 "rule2Distance" +OpMemberName %8 3 "rule3Distance" +OpMemberName %8 4 "rule1Scale" +OpMemberName %8 5 "rule2Scale" +OpMemberName %8 6 "rule3Scale" +OpName %8 "SimParams" +OpMemberName %10 0 "particles" +OpName %10 "Particles" +OpName %13 "params" +OpName %16 "particlesSrc" +OpName %18 "particlesDst" +OpName %19 "vPos" +OpName %22 "vVel" +OpName %24 "cMass" +OpName %26 "cVel" +OpName %28 "colVel" +OpName %30 "cMassCount" +OpName %33 "cVelCount" +OpName %35 "pos" +OpName %37 "vel" +OpName %39 "i" +OpName %43 "global_invocation_id" +OpName %46 "main" +OpMemberDecorate %7 0 Offset 0 +OpMemberDecorate %7 1 Offset 8 +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %8 1 Offset 4 +OpMemberDecorate %8 2 Offset 8 +OpMemberDecorate %8 3 Offset 12 +OpMemberDecorate %8 4 Offset 16 +OpMemberDecorate %8 5 Offset 20 +OpMemberDecorate %8 6 Offset 24 +OpDecorate %9 ArrayStride 16 +OpMemberDecorate %10 0 Offset 0 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 0 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpDecorate %16 NonWritable +OpDecorate %16 DescriptorSet 0 +OpDecorate %16 Binding 1 +OpDecorate %10 Block +OpDecorate %18 DescriptorSet 0 +OpDecorate %18 Binding 2 +OpDecorate %10 Block +OpDecorate %43 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 1500 %6 = OpTypeFloat 32 -%5 = OpConstant %6 0.0 -%8 = OpTypeInt 32 1 -%7 = OpConstant %8 0 -%9 = OpConstant %4 0 -%10 = OpConstant %8 1 -%11 = OpConstant %4 1 -%12 = OpConstant %6 0.1 -%13 = OpConstant %6 -1.0 -%14 = OpConstant %6 1.0 -%15 = OpTypeVector %6 2 -%16 = OpTypeStruct %15 %15 -%17 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 -%18 = OpTypeRuntimeArray %16 -%19 = OpTypeStruct %18 -%20 = OpTypeVector %4 3 -%22 = OpTypeStruct %17 -%23 = OpTypePointer Uniform %22 -%21 = OpVariable %23 Uniform -%25 = OpTypePointer StorageBuffer %19 -%24 = OpVariable %25 StorageBuffer -%26 = OpVariable %25 StorageBuffer -%28 = OpTypePointer Function %15 -%29 = OpConstantNull %15 -%31 = OpConstantNull %15 -%33 = OpConstantNull %15 -%35 = OpConstantNull %15 -%37 = OpConstantNull %15 -%39 = OpTypePointer Function %8 -%40 = OpConstantNull %8 -%42 = OpConstantNull %8 -%44 = OpConstantNull %15 -%46 = OpConstantNull %15 -%48 = OpTypePointer Function %4 -%49 = OpConstantNull %4 -%52 = OpTypePointer Input %20 -%51 = OpVariable %52 Input -%55 = OpTypeFunction %2 -%56 = OpTypePointer Uniform %17 +%5 = OpTypeVector %6 2 +%7 = OpTypeStruct %5 %5 +%8 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 +%9 = OpTypeRuntimeArray %7 +%10 = OpTypeStruct %9 +%11 = OpTypeVector %4 3 +%12 = OpTypeInt 32 1 +%14 = OpTypeStruct %8 +%15 = OpTypePointer Uniform %14 +%13 = OpVariable %15 Uniform +%17 = OpTypePointer StorageBuffer %10 +%16 = OpVariable %17 StorageBuffer +%18 = OpVariable %17 StorageBuffer +%20 = OpTypePointer Function %5 +%21 = OpConstantNull %5 +%23 = OpConstantNull %5 +%25 = OpConstantNull %5 +%27 = OpConstantNull %5 +%29 = OpConstantNull %5 +%31 = OpTypePointer Function %12 +%32 = OpConstantNull %12 +%34 = OpConstantNull %12 +%36 = OpConstantNull %5 +%38 = OpConstantNull %5 +%40 = OpTypePointer Function %4 +%41 = OpConstantNull %4 +%44 = OpTypePointer Input %11 +%43 = OpVariable %44 Input +%47 = OpTypeFunction %2 +%48 = OpTypePointer Uniform %8 +%49 = OpConstant %4 0 +%51 = OpConstant %6 0.0 +%52 = OpConstant %12 0 +%53 = OpConstant %12 1 +%54 = OpConstant %4 1 +%55 = OpConstant %6 0.1 +%56 = OpConstant %6 -1.0 +%57 = OpConstant %6 1.0 %60 = OpTypeBool -%64 = OpTypePointer StorageBuffer %18 -%65 = OpTypePointer StorageBuffer %16 -%66 = OpTypePointer StorageBuffer %15 +%64 = OpTypePointer StorageBuffer %9 +%65 = OpTypePointer StorageBuffer %7 +%66 = OpTypePointer StorageBuffer %5 %95 = OpTypePointer Uniform %6 %109 = OpConstant %4 2 %123 = OpConstant %4 3 @@ -114,235 +114,235 @@ OpDecorate %51 BuiltIn GlobalInvocationId %164 = OpConstant %4 5 %170 = OpConstant %4 6 %187 = OpTypePointer Function %6 -%54 = OpFunction %2 None %55 -%50 = OpLabel -%47 = OpVariable %48 Function %49 -%41 = OpVariable %39 Function %42 -%34 = OpVariable %28 Function %35 -%27 = OpVariable %28 Function %29 -%43 = OpVariable %28 Function %44 -%36 = OpVariable %28 Function %37 -%30 = OpVariable %28 Function %31 -%45 = OpVariable %28 Function %46 -%38 = OpVariable %39 Function %40 -%32 = OpVariable %28 Function %33 -%53 = OpLoad %20 %51 -%57 = OpAccessChain %56 %21 %9 +%46 = OpFunction %2 None %47 +%42 = OpLabel +%39 = OpVariable %40 Function %41 +%33 = OpVariable %31 Function %34 +%26 = OpVariable %20 Function %27 +%19 = OpVariable %20 Function %21 +%35 = OpVariable %20 Function %36 +%28 = OpVariable %20 Function %29 +%22 = OpVariable %20 Function %23 +%37 = OpVariable %20 Function %38 +%30 = OpVariable %31 Function %32 +%24 = OpVariable %20 Function %25 +%45 = OpLoad %11 %43 +%50 = OpAccessChain %48 %13 %49 OpBranch %58 %58 = OpLabel -%59 = OpCompositeExtract %4 %53 0 +%59 = OpCompositeExtract %4 %45 0 %61 = OpUGreaterThanEqual %60 %59 %3 OpSelectionMerge %62 None OpBranchConditional %61 %63 %62 %63 = OpLabel OpReturn %62 = OpLabel -%67 = OpAccessChain %66 %24 %9 %59 %9 -%68 = OpLoad %15 %67 -OpStore %27 %68 -%69 = OpAccessChain %66 %24 %9 %59 %11 -%70 = OpLoad %15 %69 -OpStore %30 %70 -%71 = OpCompositeConstruct %15 %5 %5 -OpStore %32 %71 -%72 = OpCompositeConstruct %15 %5 %5 -OpStore %34 %72 -%73 = OpCompositeConstruct %15 %5 %5 -OpStore %36 %73 -OpStore %38 %7 -OpStore %41 %7 -OpStore %47 %9 +%67 = OpAccessChain %66 %16 %49 %59 %49 +%68 = OpLoad %5 %67 +OpStore %19 %68 +%69 = OpAccessChain %66 %16 %49 %59 %54 +%70 = OpLoad %5 %69 +OpStore %22 %70 +%71 = OpCompositeConstruct %5 %51 %51 +OpStore %24 %71 +%72 = OpCompositeConstruct %5 %51 %51 +OpStore %26 %72 +%73 = OpCompositeConstruct %5 %51 %51 +OpStore %28 %73 +OpStore %30 %52 +OpStore %33 %52 +OpStore %39 %49 OpBranch %74 %74 = OpLabel OpLoopMerge %75 %77 None OpBranch %76 %76 = OpLabel -%78 = OpLoad %4 %47 +%78 = OpLoad %4 %39 %79 = OpUGreaterThanEqual %60 %78 %3 OpSelectionMerge %80 None OpBranchConditional %79 %81 %80 %81 = OpLabel OpBranch %75 %80 = OpLabel -%82 = OpLoad %4 %47 +%82 = OpLoad %4 %39 %83 = OpIEqual %60 %82 %59 OpSelectionMerge %84 None OpBranchConditional %83 %85 %84 %85 = OpLabel OpBranch %77 %84 = OpLabel -%86 = OpLoad %4 %47 -%87 = OpAccessChain %66 %24 %9 %86 %9 -%88 = OpLoad %15 %87 -OpStore %43 %88 -%89 = OpLoad %4 %47 -%90 = OpAccessChain %66 %24 %9 %89 %11 -%91 = OpLoad %15 %90 -OpStore %45 %91 -%92 = OpLoad %15 %43 -%93 = OpLoad %15 %27 +%86 = OpLoad %4 %39 +%87 = OpAccessChain %66 %16 %49 %86 %49 +%88 = OpLoad %5 %87 +OpStore %35 %88 +%89 = OpLoad %4 %39 +%90 = OpAccessChain %66 %16 %49 %89 %54 +%91 = OpLoad %5 %90 +OpStore %37 %91 +%92 = OpLoad %5 %35 +%93 = OpLoad %5 %19 %94 = OpExtInst %6 %1 Distance %92 %93 -%96 = OpAccessChain %95 %57 %11 +%96 = OpAccessChain %95 %50 %54 %97 = OpLoad %6 %96 %98 = OpFOrdLessThan %60 %94 %97 OpSelectionMerge %99 None OpBranchConditional %98 %100 %99 %100 = OpLabel -%101 = OpLoad %15 %32 -%102 = OpLoad %15 %43 -%103 = OpFAdd %15 %101 %102 -OpStore %32 %103 -%104 = OpLoad %8 %38 -%105 = OpIAdd %8 %104 %10 -OpStore %38 %105 +%101 = OpLoad %5 %24 +%102 = OpLoad %5 %35 +%103 = OpFAdd %5 %101 %102 +OpStore %24 %103 +%104 = OpLoad %12 %30 +%105 = OpIAdd %12 %104 %53 +OpStore %30 %105 OpBranch %99 %99 = OpLabel -%106 = OpLoad %15 %43 -%107 = OpLoad %15 %27 +%106 = OpLoad %5 %35 +%107 = OpLoad %5 %19 %108 = OpExtInst %6 %1 Distance %106 %107 -%110 = OpAccessChain %95 %57 %109 +%110 = OpAccessChain %95 %50 %109 %111 = OpLoad %6 %110 %112 = OpFOrdLessThan %60 %108 %111 OpSelectionMerge %113 None OpBranchConditional %112 %114 %113 %114 = OpLabel -%115 = OpLoad %15 %36 -%116 = OpLoad %15 %43 -%117 = OpLoad %15 %27 -%118 = OpFSub %15 %116 %117 -%119 = OpFSub %15 %115 %118 -OpStore %36 %119 +%115 = OpLoad %5 %28 +%116 = OpLoad %5 %35 +%117 = OpLoad %5 %19 +%118 = OpFSub %5 %116 %117 +%119 = OpFSub %5 %115 %118 +OpStore %28 %119 OpBranch %113 %113 = OpLabel -%120 = OpLoad %15 %43 -%121 = OpLoad %15 %27 +%120 = OpLoad %5 %35 +%121 = OpLoad %5 %19 %122 = OpExtInst %6 %1 Distance %120 %121 -%124 = OpAccessChain %95 %57 %123 +%124 = OpAccessChain %95 %50 %123 %125 = OpLoad %6 %124 %126 = OpFOrdLessThan %60 %122 %125 OpSelectionMerge %127 None OpBranchConditional %126 %128 %127 %128 = OpLabel -%129 = OpLoad %15 %34 -%130 = OpLoad %15 %45 -%131 = OpFAdd %15 %129 %130 -OpStore %34 %131 -%132 = OpLoad %8 %41 -%133 = OpIAdd %8 %132 %10 -OpStore %41 %133 +%129 = OpLoad %5 %26 +%130 = OpLoad %5 %37 +%131 = OpFAdd %5 %129 %130 +OpStore %26 %131 +%132 = OpLoad %12 %33 +%133 = OpIAdd %12 %132 %53 +OpStore %33 %133 OpBranch %127 %127 = OpLabel OpBranch %77 %77 = OpLabel -%134 = OpLoad %4 %47 -%135 = OpIAdd %4 %134 %11 -OpStore %47 %135 +%134 = OpLoad %4 %39 +%135 = OpIAdd %4 %134 %54 +OpStore %39 %135 OpBranch %74 %75 = OpLabel -%136 = OpLoad %8 %38 -%137 = OpSGreaterThan %60 %136 %7 +%136 = OpLoad %12 %30 +%137 = OpSGreaterThan %60 %136 %52 OpSelectionMerge %138 None OpBranchConditional %137 %139 %138 %139 = OpLabel -%140 = OpLoad %15 %32 -%141 = OpLoad %8 %38 +%140 = OpLoad %5 %24 +%141 = OpLoad %12 %30 %142 = OpConvertSToF %6 %141 -%143 = OpCompositeConstruct %15 %142 %142 -%144 = OpFDiv %15 %140 %143 -%145 = OpLoad %15 %27 -%146 = OpFSub %15 %144 %145 -OpStore %32 %146 +%143 = OpCompositeConstruct %5 %142 %142 +%144 = OpFDiv %5 %140 %143 +%145 = OpLoad %5 %19 +%146 = OpFSub %5 %144 %145 +OpStore %24 %146 OpBranch %138 %138 = OpLabel -%147 = OpLoad %8 %41 -%148 = OpSGreaterThan %60 %147 %7 +%147 = OpLoad %12 %33 +%148 = OpSGreaterThan %60 %147 %52 OpSelectionMerge %149 None OpBranchConditional %148 %150 %149 %150 = OpLabel -%151 = OpLoad %15 %34 -%152 = OpLoad %8 %41 +%151 = OpLoad %5 %26 +%152 = OpLoad %12 %33 %153 = OpConvertSToF %6 %152 -%154 = OpCompositeConstruct %15 %153 %153 -%155 = OpFDiv %15 %151 %154 -OpStore %34 %155 +%154 = OpCompositeConstruct %5 %153 %153 +%155 = OpFDiv %5 %151 %154 +OpStore %26 %155 OpBranch %149 %149 = OpLabel -%156 = OpLoad %15 %30 -%157 = OpLoad %15 %32 -%159 = OpAccessChain %95 %57 %158 +%156 = OpLoad %5 %22 +%157 = OpLoad %5 %24 +%159 = OpAccessChain %95 %50 %158 %160 = OpLoad %6 %159 -%161 = OpVectorTimesScalar %15 %157 %160 -%162 = OpFAdd %15 %156 %161 -%163 = OpLoad %15 %36 -%165 = OpAccessChain %95 %57 %164 +%161 = OpVectorTimesScalar %5 %157 %160 +%162 = OpFAdd %5 %156 %161 +%163 = OpLoad %5 %28 +%165 = OpAccessChain %95 %50 %164 %166 = OpLoad %6 %165 -%167 = OpVectorTimesScalar %15 %163 %166 -%168 = OpFAdd %15 %162 %167 -%169 = OpLoad %15 %34 -%171 = OpAccessChain %95 %57 %170 +%167 = OpVectorTimesScalar %5 %163 %166 +%168 = OpFAdd %5 %162 %167 +%169 = OpLoad %5 %26 +%171 = OpAccessChain %95 %50 %170 %172 = OpLoad %6 %171 -%173 = OpVectorTimesScalar %15 %169 %172 -%174 = OpFAdd %15 %168 %173 -OpStore %30 %174 -%175 = OpLoad %15 %30 -%176 = OpExtInst %15 %1 Normalize %175 -%177 = OpLoad %15 %30 +%173 = OpVectorTimesScalar %5 %169 %172 +%174 = OpFAdd %5 %168 %173 +OpStore %22 %174 +%175 = OpLoad %5 %22 +%176 = OpExtInst %5 %1 Normalize %175 +%177 = OpLoad %5 %22 %178 = OpExtInst %6 %1 Length %177 -%179 = OpExtInst %6 %1 FClamp %178 %5 %12 -%180 = OpVectorTimesScalar %15 %176 %179 -OpStore %30 %180 -%181 = OpLoad %15 %27 -%182 = OpLoad %15 %30 -%183 = OpAccessChain %95 %57 %9 +%179 = OpExtInst %6 %1 FClamp %178 %51 %55 +%180 = OpVectorTimesScalar %5 %176 %179 +OpStore %22 %180 +%181 = OpLoad %5 %19 +%182 = OpLoad %5 %22 +%183 = OpAccessChain %95 %50 %49 %184 = OpLoad %6 %183 -%185 = OpVectorTimesScalar %15 %182 %184 -%186 = OpFAdd %15 %181 %185 -OpStore %27 %186 -%188 = OpAccessChain %187 %27 %9 +%185 = OpVectorTimesScalar %5 %182 %184 +%186 = OpFAdd %5 %181 %185 +OpStore %19 %186 +%188 = OpAccessChain %187 %19 %49 %189 = OpLoad %6 %188 -%190 = OpFOrdLessThan %60 %189 %13 +%190 = OpFOrdLessThan %60 %189 %56 OpSelectionMerge %191 None OpBranchConditional %190 %192 %191 %192 = OpLabel -%193 = OpAccessChain %187 %27 %9 -OpStore %193 %14 +%193 = OpAccessChain %187 %19 %49 +OpStore %193 %57 OpBranch %191 %191 = OpLabel -%194 = OpAccessChain %187 %27 %9 +%194 = OpAccessChain %187 %19 %49 %195 = OpLoad %6 %194 -%196 = OpFOrdGreaterThan %60 %195 %14 +%196 = OpFOrdGreaterThan %60 %195 %57 OpSelectionMerge %197 None OpBranchConditional %196 %198 %197 %198 = OpLabel -%199 = OpAccessChain %187 %27 %9 -OpStore %199 %13 +%199 = OpAccessChain %187 %19 %49 +OpStore %199 %56 OpBranch %197 %197 = OpLabel -%200 = OpAccessChain %187 %27 %11 +%200 = OpAccessChain %187 %19 %54 %201 = OpLoad %6 %200 -%202 = OpFOrdLessThan %60 %201 %13 +%202 = OpFOrdLessThan %60 %201 %56 OpSelectionMerge %203 None OpBranchConditional %202 %204 %203 %204 = OpLabel -%205 = OpAccessChain %187 %27 %11 -OpStore %205 %14 +%205 = OpAccessChain %187 %19 %54 +OpStore %205 %57 OpBranch %203 %203 = OpLabel -%206 = OpAccessChain %187 %27 %11 +%206 = OpAccessChain %187 %19 %54 %207 = OpLoad %6 %206 -%208 = OpFOrdGreaterThan %60 %207 %14 +%208 = OpFOrdGreaterThan %60 %207 %57 OpSelectionMerge %209 None OpBranchConditional %208 %210 %209 %210 = OpLabel -%211 = OpAccessChain %187 %27 %11 -OpStore %211 %13 +%211 = OpAccessChain %187 %19 %54 +OpStore %211 %56 OpBranch %209 %209 = OpLabel -%212 = OpLoad %15 %27 -%213 = OpAccessChain %66 %26 %9 %59 %9 +%212 = OpLoad %5 %19 +%213 = OpAccessChain %66 %18 %49 %59 %49 OpStore %213 %212 -%214 = OpLoad %15 %30 -%215 = OpAccessChain %66 %26 %9 %59 %11 +%214 = OpLoad %5 %22 +%215 = OpAccessChain %66 %18 %49 %59 %54 OpStore %215 %214 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index 33f900023..bfddef393 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -8,461 +8,461 @@ OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %272 "fragment_shader" %270 -OpExecutionMode %272 OriginUpperLeft +OpEntryPoint Fragment %269 "fragment_shader" %267 +OpExecutionMode %269 OriginUpperLeft OpSource GLSL 450 -OpName %24 "image_1d" -OpName %26 "image_2d" -OpName %28 "image_2d_array" -OpName %30 "image_3d" -OpName %32 "image_multisampled_2d" -OpName %34 "image_depth_2d" -OpName %36 "image_depth_2d_array" -OpName %38 "image_depth_multisampled_2d" -OpName %40 "image_storage_1d" -OpName %42 "image_storage_2d" -OpName %44 "image_storage_2d_array" -OpName %46 "image_storage_3d" -OpName %49 "coords" -OpName %50 "level" -OpName %51 "test_textureLoad_1d" -OpName %64 "coords" -OpName %65 "level" -OpName %66 "test_textureLoad_2d" -OpName %79 "coords" -OpName %80 "index" -OpName %81 "level" -OpName %82 "test_textureLoad_2d_array_u" -OpName %97 "coords" -OpName %98 "index" -OpName %99 "level" -OpName %100 "test_textureLoad_2d_array_s" -OpName %114 "coords" -OpName %115 "level" -OpName %116 "test_textureLoad_3d" -OpName %129 "coords" -OpName %130 "_sample" -OpName %131 "test_textureLoad_multisampled_2d" -OpName %143 "coords" -OpName %144 "level" -OpName %145 "test_textureLoad_depth_2d" -OpName %159 "coords" -OpName %160 "index" -OpName %161 "level" -OpName %162 "test_textureLoad_depth_2d_array_u" -OpName %178 "coords" -OpName %179 "index" -OpName %180 "level" -OpName %181 "test_textureLoad_depth_2d_array_s" -OpName %196 "coords" -OpName %197 "_sample" -OpName %198 "test_textureLoad_depth_multisampled_2d" -OpName %211 "coords" -OpName %212 "value" -OpName %213 "test_textureStore_1d" -OpName %221 "coords" -OpName %222 "value" -OpName %223 "test_textureStore_2d" -OpName %232 "coords" -OpName %233 "array_index" -OpName %234 "value" -OpName %235 "test_textureStore_2d_array_u" -OpName %246 "coords" -OpName %247 "array_index" -OpName %248 "value" -OpName %249 "test_textureStore_2d_array_s" -OpName %259 "coords" -OpName %260 "value" -OpName %261 "test_textureStore_3d" -OpName %272 "fragment_shader" -OpDecorate %24 DescriptorSet 0 -OpDecorate %24 Binding 0 -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 1 -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 2 -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 3 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 4 -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 5 -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 6 -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 7 -OpDecorate %40 NonReadable -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 8 -OpDecorate %42 NonReadable -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 9 -OpDecorate %44 NonReadable -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 10 -OpDecorate %46 NonReadable -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 11 -OpDecorate %270 Location 0 +OpName %21 "image_1d" +OpName %23 "image_2d" +OpName %25 "image_2d_array" +OpName %27 "image_3d" +OpName %29 "image_multisampled_2d" +OpName %31 "image_depth_2d" +OpName %33 "image_depth_2d_array" +OpName %35 "image_depth_multisampled_2d" +OpName %37 "image_storage_1d" +OpName %39 "image_storage_2d" +OpName %41 "image_storage_2d_array" +OpName %43 "image_storage_3d" +OpName %46 "coords" +OpName %47 "level" +OpName %48 "test_textureLoad_1d" +OpName %61 "coords" +OpName %62 "level" +OpName %63 "test_textureLoad_2d" +OpName %76 "coords" +OpName %77 "index" +OpName %78 "level" +OpName %79 "test_textureLoad_2d_array_u" +OpName %94 "coords" +OpName %95 "index" +OpName %96 "level" +OpName %97 "test_textureLoad_2d_array_s" +OpName %111 "coords" +OpName %112 "level" +OpName %113 "test_textureLoad_3d" +OpName %126 "coords" +OpName %127 "_sample" +OpName %128 "test_textureLoad_multisampled_2d" +OpName %140 "coords" +OpName %141 "level" +OpName %142 "test_textureLoad_depth_2d" +OpName %156 "coords" +OpName %157 "index" +OpName %158 "level" +OpName %159 "test_textureLoad_depth_2d_array_u" +OpName %175 "coords" +OpName %176 "index" +OpName %177 "level" +OpName %178 "test_textureLoad_depth_2d_array_s" +OpName %193 "coords" +OpName %194 "_sample" +OpName %195 "test_textureLoad_depth_multisampled_2d" +OpName %208 "coords" +OpName %209 "value" +OpName %210 "test_textureStore_1d" +OpName %218 "coords" +OpName %219 "value" +OpName %220 "test_textureStore_2d" +OpName %229 "coords" +OpName %230 "array_index" +OpName %231 "value" +OpName %232 "test_textureStore_2d_array_u" +OpName %243 "coords" +OpName %244 "array_index" +OpName %245 "value" +OpName %246 "test_textureStore_2d_array_s" +OpName %256 "coords" +OpName %257 "value" +OpName %258 "test_textureStore_3d" +OpName %269 "fragment_shader" +OpDecorate %21 DescriptorSet 0 +OpDecorate %21 Binding 0 +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 1 +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 2 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 3 +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 4 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 5 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 6 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 7 +OpDecorate %37 NonReadable +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 8 +OpDecorate %39 NonReadable +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 9 +OpDecorate %41 NonReadable +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 10 +OpDecorate %43 NonReadable +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 11 +OpDecorate %267 Location 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 0 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 0 -%8 = OpTypeFloat 32 -%7 = OpConstant %8 0.0 -%9 = OpTypeImage %8 1D 0 0 0 1 Unknown -%10 = OpTypeVector %8 4 -%11 = OpTypeImage %8 2D 0 0 0 1 Unknown -%12 = OpTypeVector %4 2 -%13 = OpTypeImage %8 2D 0 1 0 1 Unknown -%14 = OpTypeImage %8 3D 0 0 0 1 Unknown -%15 = OpTypeVector %4 3 -%16 = OpTypeImage %8 2D 0 0 1 1 Unknown -%17 = OpTypeImage %8 2D 1 0 0 1 Unknown -%18 = OpTypeImage %8 2D 1 1 0 1 Unknown -%19 = OpTypeImage %8 2D 1 0 1 1 Unknown -%20 = OpTypeImage %8 1D 0 0 0 2 Rgba8 -%21 = OpTypeImage %8 2D 0 0 0 2 Rgba8 -%22 = OpTypeImage %8 2D 0 1 0 2 Rgba8 -%23 = OpTypeImage %8 3D 0 0 0 2 Rgba8 -%25 = OpTypePointer UniformConstant %9 -%24 = OpVariable %25 UniformConstant -%27 = OpTypePointer UniformConstant %11 -%26 = OpVariable %27 UniformConstant -%29 = OpTypePointer UniformConstant %13 -%28 = OpVariable %29 UniformConstant -%31 = OpTypePointer UniformConstant %14 -%30 = OpVariable %31 UniformConstant -%33 = OpTypePointer UniformConstant %16 -%32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %17 -%34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %18 -%36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %19 -%38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %20 -%40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %21 -%42 = OpVariable %43 UniformConstant -%45 = OpTypePointer UniformConstant %22 -%44 = OpVariable %45 UniformConstant -%47 = OpTypePointer UniformConstant %23 -%46 = OpVariable %47 UniformConstant -%52 = OpTypeFunction %10 %4 %4 -%56 = OpConstant %4 1 -%67 = OpTypeFunction %10 %12 %4 -%74 = OpConstantComposite %12 %56 %56 -%83 = OpTypeFunction %10 %12 %6 %4 -%92 = OpConstantComposite %15 %56 %56 %56 -%101 = OpTypeFunction %10 %12 %4 %4 -%109 = OpConstantComposite %15 %56 %56 %56 -%117 = OpTypeFunction %10 %15 %4 -%124 = OpConstantComposite %15 %56 %56 %56 -%138 = OpConstantComposite %12 %56 %56 -%146 = OpTypeFunction %8 %12 %4 -%153 = OpConstantComposite %12 %56 %56 -%163 = OpTypeFunction %8 %12 %6 %4 -%172 = OpConstantComposite %15 %56 %56 %56 -%182 = OpTypeFunction %8 %12 %4 %4 -%190 = OpConstantComposite %15 %56 %56 %56 -%205 = OpConstantComposite %12 %56 %56 -%214 = OpTypeFunction %2 %4 %10 -%224 = OpTypeFunction %2 %12 %10 -%228 = OpConstantComposite %12 %56 %56 -%236 = OpTypeFunction %2 %12 %6 %10 -%242 = OpConstantComposite %15 %56 %56 %56 -%250 = OpTypeFunction %2 %12 %4 %10 -%255 = OpConstantComposite %15 %56 %56 %56 -%262 = OpTypeFunction %2 %15 %10 -%266 = OpConstantComposite %15 %56 %56 %56 -%271 = OpTypePointer Output %10 -%270 = OpVariable %271 Output -%273 = OpTypeFunction %2 -%283 = OpConstantNull %12 -%284 = OpConstantNull %12 +%4 = OpTypeFloat 32 +%3 = OpTypeImage %4 1D 0 0 0 1 Unknown +%5 = OpTypeInt 32 1 +%6 = OpTypeVector %4 4 +%7 = OpTypeImage %4 2D 0 0 0 1 Unknown +%8 = OpTypeVector %5 2 +%9 = OpTypeImage %4 2D 0 1 0 1 Unknown +%10 = OpTypeInt 32 0 +%11 = OpTypeImage %4 3D 0 0 0 1 Unknown +%12 = OpTypeVector %5 3 +%13 = OpTypeImage %4 2D 0 0 1 1 Unknown +%14 = OpTypeImage %4 2D 1 0 0 1 Unknown +%15 = OpTypeImage %4 2D 1 1 0 1 Unknown +%16 = OpTypeImage %4 2D 1 0 1 1 Unknown +%17 = OpTypeImage %4 1D 0 0 0 2 Rgba8 +%18 = OpTypeImage %4 2D 0 0 0 2 Rgba8 +%19 = OpTypeImage %4 2D 0 1 0 2 Rgba8 +%20 = OpTypeImage %4 3D 0 0 0 2 Rgba8 +%22 = OpTypePointer UniformConstant %3 +%21 = OpVariable %22 UniformConstant +%24 = OpTypePointer UniformConstant %7 +%23 = OpVariable %24 UniformConstant +%26 = OpTypePointer UniformConstant %9 +%25 = OpVariable %26 UniformConstant +%28 = OpTypePointer UniformConstant %11 +%27 = OpVariable %28 UniformConstant +%30 = OpTypePointer UniformConstant %13 +%29 = OpVariable %30 UniformConstant +%32 = OpTypePointer UniformConstant %14 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %15 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %16 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %17 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %18 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %19 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %20 +%43 = OpVariable %44 UniformConstant +%49 = OpTypeFunction %6 %5 %5 +%53 = OpConstant %5 1 +%64 = OpTypeFunction %6 %8 %5 +%71 = OpConstantComposite %8 %53 %53 +%80 = OpTypeFunction %6 %8 %10 %5 +%89 = OpConstantComposite %12 %53 %53 %53 +%98 = OpTypeFunction %6 %8 %5 %5 +%106 = OpConstantComposite %12 %53 %53 %53 +%114 = OpTypeFunction %6 %12 %5 +%121 = OpConstantComposite %12 %53 %53 %53 +%135 = OpConstantComposite %8 %53 %53 +%143 = OpTypeFunction %4 %8 %5 +%150 = OpConstantComposite %8 %53 %53 +%160 = OpTypeFunction %4 %8 %10 %5 +%169 = OpConstantComposite %12 %53 %53 %53 +%179 = OpTypeFunction %4 %8 %5 %5 +%187 = OpConstantComposite %12 %53 %53 %53 +%202 = OpConstantComposite %8 %53 %53 +%211 = OpTypeFunction %2 %5 %6 +%221 = OpTypeFunction %2 %8 %6 +%225 = OpConstantComposite %8 %53 %53 +%233 = OpTypeFunction %2 %8 %10 %6 +%239 = OpConstantComposite %12 %53 %53 %53 +%247 = OpTypeFunction %2 %8 %5 %6 +%252 = OpConstantComposite %12 %53 %53 %53 +%259 = OpTypeFunction %2 %12 %6 +%263 = OpConstantComposite %12 %53 %53 %53 +%268 = OpTypePointer Output %6 +%267 = OpVariable %268 Output +%270 = OpTypeFunction %2 +%280 = OpConstant %5 0 +%281 = OpConstantNull %8 +%282 = OpConstantNull %8 +%283 = OpConstant %10 0 +%284 = OpConstantNull %8 %285 = OpConstantNull %12 -%286 = OpConstantNull %15 -%287 = OpConstantNull %12 -%288 = OpConstantNull %10 -%289 = OpConstantNull %12 -%290 = OpConstantNull %10 -%291 = OpConstantNull %12 -%292 = OpConstantNull %10 -%293 = OpConstantNull %12 -%294 = OpConstantNull %10 -%295 = OpConstantNull %15 -%296 = OpConstantNull %10 -%51 = OpFunction %10 None %52 -%49 = OpFunctionParameter %4 -%50 = OpFunctionParameter %4 -%48 = OpLabel -%53 = OpLoad %9 %24 -OpBranch %54 -%54 = OpLabel -%55 = OpImageQueryLevels %4 %53 -%57 = OpISub %4 %55 %56 -%58 = OpExtInst %4 %1 UMin %50 %57 -%59 = OpImageQuerySizeLod %4 %53 %58 -%60 = OpISub %4 %59 %56 -%61 = OpExtInst %4 %1 UMin %49 %60 -%62 = OpImageFetch %10 %53 %61 Lod %58 -OpReturnValue %62 +%286 = OpConstantNull %8 +%287 = OpConstantNull %6 +%288 = OpConstantNull %8 +%289 = OpConstantNull %6 +%290 = OpConstantNull %8 +%291 = OpConstantNull %6 +%292 = OpConstantNull %8 +%293 = OpConstantNull %6 +%294 = OpConstantNull %12 +%295 = OpConstantNull %6 +%296 = OpConstant %4 0.0 +%48 = OpFunction %6 None %49 +%46 = OpFunctionParameter %5 +%47 = OpFunctionParameter %5 +%45 = OpLabel +%50 = OpLoad %3 %21 +OpBranch %51 +%51 = OpLabel +%52 = OpImageQueryLevels %5 %50 +%54 = OpISub %5 %52 %53 +%55 = OpExtInst %5 %1 UMin %47 %54 +%56 = OpImageQuerySizeLod %5 %50 %55 +%57 = OpISub %5 %56 %53 +%58 = OpExtInst %5 %1 UMin %46 %57 +%59 = OpImageFetch %6 %50 %58 Lod %55 +OpReturnValue %59 OpFunctionEnd -%66 = OpFunction %10 None %67 -%64 = OpFunctionParameter %12 -%65 = OpFunctionParameter %4 -%63 = OpLabel -%68 = OpLoad %11 %26 -OpBranch %69 -%69 = OpLabel -%70 = OpImageQueryLevels %4 %68 -%71 = OpISub %4 %70 %56 -%72 = OpExtInst %4 %1 UMin %65 %71 -%73 = OpImageQuerySizeLod %12 %68 %72 -%75 = OpISub %12 %73 %74 -%76 = OpExtInst %12 %1 UMin %64 %75 -%77 = OpImageFetch %10 %68 %76 Lod %72 -OpReturnValue %77 +%63 = OpFunction %6 None %64 +%61 = OpFunctionParameter %8 +%62 = OpFunctionParameter %5 +%60 = OpLabel +%65 = OpLoad %7 %23 +OpBranch %66 +%66 = OpLabel +%67 = OpImageQueryLevels %5 %65 +%68 = OpISub %5 %67 %53 +%69 = OpExtInst %5 %1 UMin %62 %68 +%70 = OpImageQuerySizeLod %8 %65 %69 +%72 = OpISub %8 %70 %71 +%73 = OpExtInst %8 %1 UMin %61 %72 +%74 = OpImageFetch %6 %65 %73 Lod %69 +OpReturnValue %74 OpFunctionEnd -%82 = OpFunction %10 None %83 -%79 = OpFunctionParameter %12 -%80 = OpFunctionParameter %6 -%81 = OpFunctionParameter %4 -%78 = OpLabel -%84 = OpLoad %13 %28 -OpBranch %85 -%85 = OpLabel -%86 = OpBitcast %4 %80 -%87 = OpCompositeConstruct %15 %79 %86 -%88 = OpImageQueryLevels %4 %84 -%89 = OpISub %4 %88 %56 -%90 = OpExtInst %4 %1 UMin %81 %89 -%91 = OpImageQuerySizeLod %15 %84 %90 -%93 = OpISub %15 %91 %92 -%94 = OpExtInst %15 %1 UMin %87 %93 -%95 = OpImageFetch %10 %84 %94 Lod %90 -OpReturnValue %95 +%79 = OpFunction %6 None %80 +%76 = OpFunctionParameter %8 +%77 = OpFunctionParameter %10 +%78 = OpFunctionParameter %5 +%75 = OpLabel +%81 = OpLoad %9 %25 +OpBranch %82 +%82 = OpLabel +%83 = OpBitcast %5 %77 +%84 = OpCompositeConstruct %12 %76 %83 +%85 = OpImageQueryLevels %5 %81 +%86 = OpISub %5 %85 %53 +%87 = OpExtInst %5 %1 UMin %78 %86 +%88 = OpImageQuerySizeLod %12 %81 %87 +%90 = OpISub %12 %88 %89 +%91 = OpExtInst %12 %1 UMin %84 %90 +%92 = OpImageFetch %6 %81 %91 Lod %87 +OpReturnValue %92 OpFunctionEnd -%100 = OpFunction %10 None %101 -%97 = OpFunctionParameter %12 -%98 = OpFunctionParameter %4 -%99 = OpFunctionParameter %4 -%96 = OpLabel -%102 = OpLoad %13 %28 -OpBranch %103 -%103 = OpLabel -%104 = OpCompositeConstruct %15 %97 %98 -%105 = OpImageQueryLevels %4 %102 -%106 = OpISub %4 %105 %56 -%107 = OpExtInst %4 %1 UMin %99 %106 -%108 = OpImageQuerySizeLod %15 %102 %107 -%110 = OpISub %15 %108 %109 -%111 = OpExtInst %15 %1 UMin %104 %110 -%112 = OpImageFetch %10 %102 %111 Lod %107 -OpReturnValue %112 +%97 = OpFunction %6 None %98 +%94 = OpFunctionParameter %8 +%95 = OpFunctionParameter %5 +%96 = OpFunctionParameter %5 +%93 = OpLabel +%99 = OpLoad %9 %25 +OpBranch %100 +%100 = OpLabel +%101 = OpCompositeConstruct %12 %94 %95 +%102 = OpImageQueryLevels %5 %99 +%103 = OpISub %5 %102 %53 +%104 = OpExtInst %5 %1 UMin %96 %103 +%105 = OpImageQuerySizeLod %12 %99 %104 +%107 = OpISub %12 %105 %106 +%108 = OpExtInst %12 %1 UMin %101 %107 +%109 = OpImageFetch %6 %99 %108 Lod %104 +OpReturnValue %109 OpFunctionEnd -%116 = OpFunction %10 None %117 -%114 = OpFunctionParameter %15 -%115 = OpFunctionParameter %4 -%113 = OpLabel -%118 = OpLoad %14 %30 -OpBranch %119 -%119 = OpLabel -%120 = OpImageQueryLevels %4 %118 -%121 = OpISub %4 %120 %56 -%122 = OpExtInst %4 %1 UMin %115 %121 -%123 = OpImageQuerySizeLod %15 %118 %122 -%125 = OpISub %15 %123 %124 -%126 = OpExtInst %15 %1 UMin %114 %125 -%127 = OpImageFetch %10 %118 %126 Lod %122 -OpReturnValue %127 +%113 = OpFunction %6 None %114 +%111 = OpFunctionParameter %12 +%112 = OpFunctionParameter %5 +%110 = OpLabel +%115 = OpLoad %11 %27 +OpBranch %116 +%116 = OpLabel +%117 = OpImageQueryLevels %5 %115 +%118 = OpISub %5 %117 %53 +%119 = OpExtInst %5 %1 UMin %112 %118 +%120 = OpImageQuerySizeLod %12 %115 %119 +%122 = OpISub %12 %120 %121 +%123 = OpExtInst %12 %1 UMin %111 %122 +%124 = OpImageFetch %6 %115 %123 Lod %119 +OpReturnValue %124 OpFunctionEnd -%131 = OpFunction %10 None %67 -%129 = OpFunctionParameter %12 -%130 = OpFunctionParameter %4 -%128 = OpLabel -%132 = OpLoad %16 %32 -OpBranch %133 -%133 = OpLabel -%134 = OpImageQuerySamples %4 %132 -%135 = OpISub %4 %134 %56 -%136 = OpExtInst %4 %1 UMin %130 %135 -%137 = OpImageQuerySize %12 %132 -%139 = OpISub %12 %137 %138 -%140 = OpExtInst %12 %1 UMin %129 %139 -%141 = OpImageFetch %10 %132 %140 Sample %136 -OpReturnValue %141 +%128 = OpFunction %6 None %64 +%126 = OpFunctionParameter %8 +%127 = OpFunctionParameter %5 +%125 = OpLabel +%129 = OpLoad %13 %29 +OpBranch %130 +%130 = OpLabel +%131 = OpImageQuerySamples %5 %129 +%132 = OpISub %5 %131 %53 +%133 = OpExtInst %5 %1 UMin %127 %132 +%134 = OpImageQuerySize %8 %129 +%136 = OpISub %8 %134 %135 +%137 = OpExtInst %8 %1 UMin %126 %136 +%138 = OpImageFetch %6 %129 %137 Sample %133 +OpReturnValue %138 OpFunctionEnd -%145 = OpFunction %8 None %146 -%143 = OpFunctionParameter %12 -%144 = OpFunctionParameter %4 -%142 = OpLabel -%147 = OpLoad %17 %34 -OpBranch %148 -%148 = OpLabel -%149 = OpImageQueryLevels %4 %147 -%150 = OpISub %4 %149 %56 -%151 = OpExtInst %4 %1 UMin %144 %150 -%152 = OpImageQuerySizeLod %12 %147 %151 -%154 = OpISub %12 %152 %153 -%155 = OpExtInst %12 %1 UMin %143 %154 -%156 = OpImageFetch %10 %147 %155 Lod %151 -%157 = OpCompositeExtract %8 %156 0 -OpReturnValue %157 +%142 = OpFunction %4 None %143 +%140 = OpFunctionParameter %8 +%141 = OpFunctionParameter %5 +%139 = OpLabel +%144 = OpLoad %14 %31 +OpBranch %145 +%145 = OpLabel +%146 = OpImageQueryLevels %5 %144 +%147 = OpISub %5 %146 %53 +%148 = OpExtInst %5 %1 UMin %141 %147 +%149 = OpImageQuerySizeLod %8 %144 %148 +%151 = OpISub %8 %149 %150 +%152 = OpExtInst %8 %1 UMin %140 %151 +%153 = OpImageFetch %6 %144 %152 Lod %148 +%154 = OpCompositeExtract %4 %153 0 +OpReturnValue %154 OpFunctionEnd -%162 = OpFunction %8 None %163 -%159 = OpFunctionParameter %12 -%160 = OpFunctionParameter %6 -%161 = OpFunctionParameter %4 -%158 = OpLabel -%164 = OpLoad %18 %36 -OpBranch %165 -%165 = OpLabel -%166 = OpBitcast %4 %160 -%167 = OpCompositeConstruct %15 %159 %166 -%168 = OpImageQueryLevels %4 %164 -%169 = OpISub %4 %168 %56 -%170 = OpExtInst %4 %1 UMin %161 %169 -%171 = OpImageQuerySizeLod %15 %164 %170 -%173 = OpISub %15 %171 %172 -%174 = OpExtInst %15 %1 UMin %167 %173 -%175 = OpImageFetch %10 %164 %174 Lod %170 -%176 = OpCompositeExtract %8 %175 0 -OpReturnValue %176 +%159 = OpFunction %4 None %160 +%156 = OpFunctionParameter %8 +%157 = OpFunctionParameter %10 +%158 = OpFunctionParameter %5 +%155 = OpLabel +%161 = OpLoad %15 %33 +OpBranch %162 +%162 = OpLabel +%163 = OpBitcast %5 %157 +%164 = OpCompositeConstruct %12 %156 %163 +%165 = OpImageQueryLevels %5 %161 +%166 = OpISub %5 %165 %53 +%167 = OpExtInst %5 %1 UMin %158 %166 +%168 = OpImageQuerySizeLod %12 %161 %167 +%170 = OpISub %12 %168 %169 +%171 = OpExtInst %12 %1 UMin %164 %170 +%172 = OpImageFetch %6 %161 %171 Lod %167 +%173 = OpCompositeExtract %4 %172 0 +OpReturnValue %173 OpFunctionEnd -%181 = OpFunction %8 None %182 -%178 = OpFunctionParameter %12 -%179 = OpFunctionParameter %4 -%180 = OpFunctionParameter %4 -%177 = OpLabel -%183 = OpLoad %18 %36 -OpBranch %184 -%184 = OpLabel -%185 = OpCompositeConstruct %15 %178 %179 -%186 = OpImageQueryLevels %4 %183 -%187 = OpISub %4 %186 %56 -%188 = OpExtInst %4 %1 UMin %180 %187 -%189 = OpImageQuerySizeLod %15 %183 %188 -%191 = OpISub %15 %189 %190 -%192 = OpExtInst %15 %1 UMin %185 %191 -%193 = OpImageFetch %10 %183 %192 Lod %188 -%194 = OpCompositeExtract %8 %193 0 -OpReturnValue %194 +%178 = OpFunction %4 None %179 +%175 = OpFunctionParameter %8 +%176 = OpFunctionParameter %5 +%177 = OpFunctionParameter %5 +%174 = OpLabel +%180 = OpLoad %15 %33 +OpBranch %181 +%181 = OpLabel +%182 = OpCompositeConstruct %12 %175 %176 +%183 = OpImageQueryLevels %5 %180 +%184 = OpISub %5 %183 %53 +%185 = OpExtInst %5 %1 UMin %177 %184 +%186 = OpImageQuerySizeLod %12 %180 %185 +%188 = OpISub %12 %186 %187 +%189 = OpExtInst %12 %1 UMin %182 %188 +%190 = OpImageFetch %6 %180 %189 Lod %185 +%191 = OpCompositeExtract %4 %190 0 +OpReturnValue %191 OpFunctionEnd -%198 = OpFunction %8 None %146 -%196 = OpFunctionParameter %12 -%197 = OpFunctionParameter %4 -%195 = OpLabel -%199 = OpLoad %19 %38 -OpBranch %200 -%200 = OpLabel -%201 = OpImageQuerySamples %4 %199 -%202 = OpISub %4 %201 %56 -%203 = OpExtInst %4 %1 UMin %197 %202 -%204 = OpImageQuerySize %12 %199 -%206 = OpISub %12 %204 %205 -%207 = OpExtInst %12 %1 UMin %196 %206 -%208 = OpImageFetch %10 %199 %207 Sample %203 -%209 = OpCompositeExtract %8 %208 0 -OpReturnValue %209 +%195 = OpFunction %4 None %143 +%193 = OpFunctionParameter %8 +%194 = OpFunctionParameter %5 +%192 = OpLabel +%196 = OpLoad %16 %35 +OpBranch %197 +%197 = OpLabel +%198 = OpImageQuerySamples %5 %196 +%199 = OpISub %5 %198 %53 +%200 = OpExtInst %5 %1 UMin %194 %199 +%201 = OpImageQuerySize %8 %196 +%203 = OpISub %8 %201 %202 +%204 = OpExtInst %8 %1 UMin %193 %203 +%205 = OpImageFetch %6 %196 %204 Sample %200 +%206 = OpCompositeExtract %4 %205 0 +OpReturnValue %206 OpFunctionEnd -%213 = OpFunction %2 None %214 -%211 = OpFunctionParameter %4 -%212 = OpFunctionParameter %10 -%210 = OpLabel -%215 = OpLoad %20 %40 -OpBranch %216 -%216 = OpLabel -%217 = OpImageQuerySize %4 %215 -%218 = OpISub %4 %217 %56 -%219 = OpExtInst %4 %1 UMin %211 %218 -OpImageWrite %215 %219 %212 +%210 = OpFunction %2 None %211 +%208 = OpFunctionParameter %5 +%209 = OpFunctionParameter %6 +%207 = OpLabel +%212 = OpLoad %17 %37 +OpBranch %213 +%213 = OpLabel +%214 = OpImageQuerySize %5 %212 +%215 = OpISub %5 %214 %53 +%216 = OpExtInst %5 %1 UMin %208 %215 +OpImageWrite %212 %216 %209 OpReturn OpFunctionEnd -%223 = OpFunction %2 None %224 -%221 = OpFunctionParameter %12 -%222 = OpFunctionParameter %10 -%220 = OpLabel -%225 = OpLoad %21 %42 -OpBranch %226 -%226 = OpLabel -%227 = OpImageQuerySize %12 %225 -%229 = OpISub %12 %227 %228 -%230 = OpExtInst %12 %1 UMin %221 %229 -OpImageWrite %225 %230 %222 +%220 = OpFunction %2 None %221 +%218 = OpFunctionParameter %8 +%219 = OpFunctionParameter %6 +%217 = OpLabel +%222 = OpLoad %18 %39 +OpBranch %223 +%223 = OpLabel +%224 = OpImageQuerySize %8 %222 +%226 = OpISub %8 %224 %225 +%227 = OpExtInst %8 %1 UMin %218 %226 +OpImageWrite %222 %227 %219 OpReturn OpFunctionEnd -%235 = OpFunction %2 None %236 -%232 = OpFunctionParameter %12 -%233 = OpFunctionParameter %6 -%234 = OpFunctionParameter %10 -%231 = OpLabel -%237 = OpLoad %22 %44 -OpBranch %238 -%238 = OpLabel -%239 = OpBitcast %4 %233 -%240 = OpCompositeConstruct %15 %232 %239 -%241 = OpImageQuerySize %15 %237 -%243 = OpISub %15 %241 %242 -%244 = OpExtInst %15 %1 UMin %240 %243 -OpImageWrite %237 %244 %234 +%232 = OpFunction %2 None %233 +%229 = OpFunctionParameter %8 +%230 = OpFunctionParameter %10 +%231 = OpFunctionParameter %6 +%228 = OpLabel +%234 = OpLoad %19 %41 +OpBranch %235 +%235 = OpLabel +%236 = OpBitcast %5 %230 +%237 = OpCompositeConstruct %12 %229 %236 +%238 = OpImageQuerySize %12 %234 +%240 = OpISub %12 %238 %239 +%241 = OpExtInst %12 %1 UMin %237 %240 +OpImageWrite %234 %241 %231 OpReturn OpFunctionEnd -%249 = OpFunction %2 None %250 -%246 = OpFunctionParameter %12 -%247 = OpFunctionParameter %4 -%248 = OpFunctionParameter %10 -%245 = OpLabel -%251 = OpLoad %22 %44 -OpBranch %252 -%252 = OpLabel -%253 = OpCompositeConstruct %15 %246 %247 -%254 = OpImageQuerySize %15 %251 -%256 = OpISub %15 %254 %255 -%257 = OpExtInst %15 %1 UMin %253 %256 -OpImageWrite %251 %257 %248 +%246 = OpFunction %2 None %247 +%243 = OpFunctionParameter %8 +%244 = OpFunctionParameter %5 +%245 = OpFunctionParameter %6 +%242 = OpLabel +%248 = OpLoad %19 %41 +OpBranch %249 +%249 = OpLabel +%250 = OpCompositeConstruct %12 %243 %244 +%251 = OpImageQuerySize %12 %248 +%253 = OpISub %12 %251 %252 +%254 = OpExtInst %12 %1 UMin %250 %253 +OpImageWrite %248 %254 %245 OpReturn OpFunctionEnd -%261 = OpFunction %2 None %262 -%259 = OpFunctionParameter %15 -%260 = OpFunctionParameter %10 -%258 = OpLabel -%263 = OpLoad %23 %46 -OpBranch %264 -%264 = OpLabel -%265 = OpImageQuerySize %15 %263 -%267 = OpISub %15 %265 %266 -%268 = OpExtInst %15 %1 UMin %259 %267 -OpImageWrite %263 %268 %260 +%258 = OpFunction %2 None %259 +%256 = OpFunctionParameter %12 +%257 = OpFunctionParameter %6 +%255 = OpLabel +%260 = OpLoad %20 %43 +OpBranch %261 +%261 = OpLabel +%262 = OpImageQuerySize %12 %260 +%264 = OpISub %12 %262 %263 +%265 = OpExtInst %12 %1 UMin %256 %264 +OpImageWrite %260 %265 %257 OpReturn OpFunctionEnd -%272 = OpFunction %2 None %273 -%269 = OpLabel -%274 = OpLoad %9 %24 -%275 = OpLoad %11 %26 -%276 = OpLoad %13 %28 -%277 = OpLoad %14 %30 -%278 = OpLoad %16 %32 -%279 = OpLoad %20 %40 -%280 = OpLoad %21 %42 -%281 = OpLoad %22 %44 -%282 = OpLoad %23 %46 +%269 = OpFunction %2 None %270 +%266 = OpLabel +%271 = OpLoad %3 %21 +%272 = OpLoad %7 %23 +%273 = OpLoad %9 %25 +%274 = OpLoad %11 %27 +%275 = OpLoad %13 %29 +%276 = OpLoad %17 %37 +%277 = OpLoad %18 %39 +%278 = OpLoad %19 %41 +%279 = OpLoad %20 %43 OpBranch %297 %297 = OpLabel -%298 = OpFunctionCall %10 %51 %3 %3 -%299 = OpFunctionCall %10 %66 %283 %3 -%300 = OpFunctionCall %10 %82 %284 %5 %3 -%301 = OpFunctionCall %10 %100 %285 %3 %3 -%302 = OpFunctionCall %10 %116 %286 %3 -%303 = OpFunctionCall %10 %131 %287 %3 -%304 = OpFunctionCall %2 %213 %3 %288 -%305 = OpFunctionCall %2 %223 %289 %290 -%306 = OpFunctionCall %2 %235 %291 %5 %292 -%307 = OpFunctionCall %2 %249 %293 %3 %294 -%308 = OpFunctionCall %2 %261 %295 %296 -%309 = OpCompositeConstruct %10 %7 %7 %7 %7 -OpStore %270 %309 +%298 = OpFunctionCall %6 %48 %280 %280 +%299 = OpFunctionCall %6 %63 %281 %280 +%300 = OpFunctionCall %6 %79 %282 %283 %280 +%301 = OpFunctionCall %6 %97 %284 %280 %280 +%302 = OpFunctionCall %6 %113 %285 %280 +%303 = OpFunctionCall %6 %128 %286 %280 +%304 = OpFunctionCall %2 %210 %280 %287 +%305 = OpFunctionCall %2 %220 %288 %289 +%306 = OpFunctionCall %2 %232 %290 %283 %291 +%307 = OpFunctionCall %2 %246 %292 %280 %293 +%308 = OpFunctionCall %2 %258 %294 %295 +%309 = OpCompositeConstruct %6 %296 %296 %296 %296 +OpStore %267 %309 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index 29a132a22..6228f45f9 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -8,553 +8,553 @@ OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %309 "fragment_shader" %307 -OpExecutionMode %309 OriginUpperLeft +OpEntryPoint Fragment %306 "fragment_shader" %304 +OpExecutionMode %306 OriginUpperLeft OpSource GLSL 450 -OpName %24 "image_1d" -OpName %26 "image_2d" -OpName %28 "image_2d_array" -OpName %30 "image_3d" -OpName %32 "image_multisampled_2d" -OpName %34 "image_depth_2d" -OpName %36 "image_depth_2d_array" -OpName %38 "image_depth_multisampled_2d" -OpName %40 "image_storage_1d" -OpName %42 "image_storage_2d" -OpName %44 "image_storage_2d_array" -OpName %46 "image_storage_3d" -OpName %49 "coords" -OpName %50 "level" -OpName %51 "test_textureLoad_1d" -OpName %67 "coords" -OpName %68 "level" -OpName %69 "test_textureLoad_2d" -OpName %86 "coords" -OpName %87 "index" -OpName %88 "level" -OpName %89 "test_textureLoad_2d_array_u" -OpName %108 "coords" -OpName %109 "index" -OpName %110 "level" -OpName %111 "test_textureLoad_2d_array_s" -OpName %128 "coords" -OpName %129 "level" -OpName %130 "test_textureLoad_3d" -OpName %146 "coords" -OpName %147 "_sample" -OpName %148 "test_textureLoad_multisampled_2d" -OpName %163 "coords" -OpName %164 "level" -OpName %165 "test_textureLoad_depth_2d" -OpName %182 "coords" -OpName %183 "index" -OpName %184 "level" -OpName %185 "test_textureLoad_depth_2d_array_u" -OpName %204 "coords" -OpName %205 "index" -OpName %206 "level" -OpName %207 "test_textureLoad_depth_2d_array_s" -OpName %225 "coords" -OpName %226 "_sample" -OpName %227 "test_textureLoad_depth_multisampled_2d" -OpName %243 "coords" -OpName %244 "value" -OpName %245 "test_textureStore_1d" -OpName %254 "coords" -OpName %255 "value" -OpName %256 "test_textureStore_2d" -OpName %266 "coords" -OpName %267 "array_index" -OpName %268 "value" -OpName %269 "test_textureStore_2d_array_u" -OpName %281 "coords" -OpName %282 "array_index" -OpName %283 "value" -OpName %284 "test_textureStore_2d_array_s" -OpName %295 "coords" -OpName %296 "value" -OpName %297 "test_textureStore_3d" -OpName %309 "fragment_shader" -OpDecorate %24 DescriptorSet 0 -OpDecorate %24 Binding 0 -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 1 -OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 2 -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 3 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 4 -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 5 -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 6 -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 7 -OpDecorate %40 NonReadable -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 8 -OpDecorate %42 NonReadable -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 9 -OpDecorate %44 NonReadable -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 10 -OpDecorate %46 NonReadable -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 11 -OpDecorate %307 Location 0 +OpName %21 "image_1d" +OpName %23 "image_2d" +OpName %25 "image_2d_array" +OpName %27 "image_3d" +OpName %29 "image_multisampled_2d" +OpName %31 "image_depth_2d" +OpName %33 "image_depth_2d_array" +OpName %35 "image_depth_multisampled_2d" +OpName %37 "image_storage_1d" +OpName %39 "image_storage_2d" +OpName %41 "image_storage_2d_array" +OpName %43 "image_storage_3d" +OpName %46 "coords" +OpName %47 "level" +OpName %48 "test_textureLoad_1d" +OpName %64 "coords" +OpName %65 "level" +OpName %66 "test_textureLoad_2d" +OpName %83 "coords" +OpName %84 "index" +OpName %85 "level" +OpName %86 "test_textureLoad_2d_array_u" +OpName %105 "coords" +OpName %106 "index" +OpName %107 "level" +OpName %108 "test_textureLoad_2d_array_s" +OpName %125 "coords" +OpName %126 "level" +OpName %127 "test_textureLoad_3d" +OpName %143 "coords" +OpName %144 "_sample" +OpName %145 "test_textureLoad_multisampled_2d" +OpName %160 "coords" +OpName %161 "level" +OpName %162 "test_textureLoad_depth_2d" +OpName %179 "coords" +OpName %180 "index" +OpName %181 "level" +OpName %182 "test_textureLoad_depth_2d_array_u" +OpName %201 "coords" +OpName %202 "index" +OpName %203 "level" +OpName %204 "test_textureLoad_depth_2d_array_s" +OpName %222 "coords" +OpName %223 "_sample" +OpName %224 "test_textureLoad_depth_multisampled_2d" +OpName %240 "coords" +OpName %241 "value" +OpName %242 "test_textureStore_1d" +OpName %251 "coords" +OpName %252 "value" +OpName %253 "test_textureStore_2d" +OpName %263 "coords" +OpName %264 "array_index" +OpName %265 "value" +OpName %266 "test_textureStore_2d_array_u" +OpName %278 "coords" +OpName %279 "array_index" +OpName %280 "value" +OpName %281 "test_textureStore_2d_array_s" +OpName %292 "coords" +OpName %293 "value" +OpName %294 "test_textureStore_3d" +OpName %306 "fragment_shader" +OpDecorate %21 DescriptorSet 0 +OpDecorate %21 Binding 0 +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 1 +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 2 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 3 +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 4 +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 5 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 6 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 7 +OpDecorate %37 NonReadable +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 8 +OpDecorate %39 NonReadable +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 9 +OpDecorate %41 NonReadable +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 10 +OpDecorate %43 NonReadable +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 11 +OpDecorate %304 Location 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 0 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 0 -%8 = OpTypeFloat 32 -%7 = OpConstant %8 0.0 -%9 = OpTypeImage %8 1D 0 0 0 1 Unknown -%10 = OpTypeVector %8 4 -%11 = OpTypeImage %8 2D 0 0 0 1 Unknown -%12 = OpTypeVector %4 2 -%13 = OpTypeImage %8 2D 0 1 0 1 Unknown -%14 = OpTypeImage %8 3D 0 0 0 1 Unknown -%15 = OpTypeVector %4 3 -%16 = OpTypeImage %8 2D 0 0 1 1 Unknown -%17 = OpTypeImage %8 2D 1 0 0 1 Unknown -%18 = OpTypeImage %8 2D 1 1 0 1 Unknown -%19 = OpTypeImage %8 2D 1 0 1 1 Unknown -%20 = OpTypeImage %8 1D 0 0 0 2 Rgba8 -%21 = OpTypeImage %8 2D 0 0 0 2 Rgba8 -%22 = OpTypeImage %8 2D 0 1 0 2 Rgba8 -%23 = OpTypeImage %8 3D 0 0 0 2 Rgba8 -%25 = OpTypePointer UniformConstant %9 -%24 = OpVariable %25 UniformConstant -%27 = OpTypePointer UniformConstant %11 -%26 = OpVariable %27 UniformConstant -%29 = OpTypePointer UniformConstant %13 -%28 = OpVariable %29 UniformConstant -%31 = OpTypePointer UniformConstant %14 -%30 = OpVariable %31 UniformConstant -%33 = OpTypePointer UniformConstant %16 -%32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %17 -%34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %18 -%36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %19 -%38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %20 -%40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %21 -%42 = OpVariable %43 UniformConstant -%45 = OpTypePointer UniformConstant %22 -%44 = OpVariable %45 UniformConstant -%47 = OpTypePointer UniformConstant %23 -%46 = OpVariable %47 UniformConstant -%52 = OpTypeFunction %10 %4 %4 -%55 = OpTypeBool -%56 = OpConstantNull %10 -%70 = OpTypeFunction %10 %12 %4 -%73 = OpConstantNull %10 -%79 = OpTypeVector %55 2 -%90 = OpTypeFunction %10 %12 %6 %4 -%95 = OpConstantNull %10 -%101 = OpTypeVector %55 3 -%112 = OpTypeFunction %10 %12 %4 %4 -%116 = OpConstantNull %10 -%131 = OpTypeFunction %10 %15 %4 -%134 = OpConstantNull %10 -%151 = OpConstantNull %10 -%166 = OpTypeFunction %8 %12 %4 -%169 = OpConstantNull %10 -%186 = OpTypeFunction %8 %12 %6 %4 -%191 = OpConstantNull %10 -%208 = OpTypeFunction %8 %12 %4 %4 -%212 = OpConstantNull %10 -%230 = OpConstantNull %10 -%246 = OpTypeFunction %2 %4 %10 -%257 = OpTypeFunction %2 %12 %10 -%270 = OpTypeFunction %2 %12 %6 %10 -%285 = OpTypeFunction %2 %12 %4 %10 -%298 = OpTypeFunction %2 %15 %10 -%308 = OpTypePointer Output %10 -%307 = OpVariable %308 Output -%310 = OpTypeFunction %2 -%320 = OpConstantNull %12 -%321 = OpConstantNull %12 +%4 = OpTypeFloat 32 +%3 = OpTypeImage %4 1D 0 0 0 1 Unknown +%5 = OpTypeInt 32 1 +%6 = OpTypeVector %4 4 +%7 = OpTypeImage %4 2D 0 0 0 1 Unknown +%8 = OpTypeVector %5 2 +%9 = OpTypeImage %4 2D 0 1 0 1 Unknown +%10 = OpTypeInt 32 0 +%11 = OpTypeImage %4 3D 0 0 0 1 Unknown +%12 = OpTypeVector %5 3 +%13 = OpTypeImage %4 2D 0 0 1 1 Unknown +%14 = OpTypeImage %4 2D 1 0 0 1 Unknown +%15 = OpTypeImage %4 2D 1 1 0 1 Unknown +%16 = OpTypeImage %4 2D 1 0 1 1 Unknown +%17 = OpTypeImage %4 1D 0 0 0 2 Rgba8 +%18 = OpTypeImage %4 2D 0 0 0 2 Rgba8 +%19 = OpTypeImage %4 2D 0 1 0 2 Rgba8 +%20 = OpTypeImage %4 3D 0 0 0 2 Rgba8 +%22 = OpTypePointer UniformConstant %3 +%21 = OpVariable %22 UniformConstant +%24 = OpTypePointer UniformConstant %7 +%23 = OpVariable %24 UniformConstant +%26 = OpTypePointer UniformConstant %9 +%25 = OpVariable %26 UniformConstant +%28 = OpTypePointer UniformConstant %11 +%27 = OpVariable %28 UniformConstant +%30 = OpTypePointer UniformConstant %13 +%29 = OpVariable %30 UniformConstant +%32 = OpTypePointer UniformConstant %14 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %15 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %16 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %17 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %18 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %19 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %20 +%43 = OpVariable %44 UniformConstant +%49 = OpTypeFunction %6 %5 %5 +%52 = OpTypeBool +%53 = OpConstantNull %6 +%67 = OpTypeFunction %6 %8 %5 +%70 = OpConstantNull %6 +%76 = OpTypeVector %52 2 +%87 = OpTypeFunction %6 %8 %10 %5 +%92 = OpConstantNull %6 +%98 = OpTypeVector %52 3 +%109 = OpTypeFunction %6 %8 %5 %5 +%113 = OpConstantNull %6 +%128 = OpTypeFunction %6 %12 %5 +%131 = OpConstantNull %6 +%148 = OpConstantNull %6 +%163 = OpTypeFunction %4 %8 %5 +%166 = OpConstantNull %6 +%183 = OpTypeFunction %4 %8 %10 %5 +%188 = OpConstantNull %6 +%205 = OpTypeFunction %4 %8 %5 %5 +%209 = OpConstantNull %6 +%227 = OpConstantNull %6 +%243 = OpTypeFunction %2 %5 %6 +%254 = OpTypeFunction %2 %8 %6 +%267 = OpTypeFunction %2 %8 %10 %6 +%282 = OpTypeFunction %2 %8 %5 %6 +%295 = OpTypeFunction %2 %12 %6 +%305 = OpTypePointer Output %6 +%304 = OpVariable %305 Output +%307 = OpTypeFunction %2 +%317 = OpConstant %5 0 +%318 = OpConstantNull %8 +%319 = OpConstantNull %8 +%320 = OpConstant %10 0 +%321 = OpConstantNull %8 %322 = OpConstantNull %12 -%323 = OpConstantNull %15 -%324 = OpConstantNull %12 -%325 = OpConstantNull %10 -%326 = OpConstantNull %12 -%327 = OpConstantNull %10 -%328 = OpConstantNull %12 -%329 = OpConstantNull %10 -%330 = OpConstantNull %12 -%331 = OpConstantNull %10 -%332 = OpConstantNull %15 -%333 = OpConstantNull %10 -%51 = OpFunction %10 None %52 -%49 = OpFunctionParameter %4 -%50 = OpFunctionParameter %4 -%48 = OpLabel -%53 = OpLoad %9 %24 -OpBranch %54 -%54 = OpLabel -%57 = OpImageQueryLevels %4 %53 -%58 = OpULessThan %55 %50 %57 -OpSelectionMerge %59 None -OpBranchConditional %58 %60 %59 +%323 = OpConstantNull %8 +%324 = OpConstantNull %6 +%325 = OpConstantNull %8 +%326 = OpConstantNull %6 +%327 = OpConstantNull %8 +%328 = OpConstantNull %6 +%329 = OpConstantNull %8 +%330 = OpConstantNull %6 +%331 = OpConstantNull %12 +%332 = OpConstantNull %6 +%333 = OpConstant %4 0.0 +%48 = OpFunction %6 None %49 +%46 = OpFunctionParameter %5 +%47 = OpFunctionParameter %5 +%45 = OpLabel +%50 = OpLoad %3 %21 +OpBranch %51 +%51 = OpLabel +%54 = OpImageQueryLevels %5 %50 +%55 = OpULessThan %52 %47 %54 +OpSelectionMerge %56 None +OpBranchConditional %55 %57 %56 +%57 = OpLabel +%58 = OpImageQuerySizeLod %5 %50 %47 +%59 = OpULessThan %52 %46 %58 +OpBranchConditional %59 %60 %56 %60 = OpLabel -%61 = OpImageQuerySizeLod %4 %53 %50 -%62 = OpULessThan %55 %49 %61 -OpBranchConditional %62 %63 %59 +%61 = OpImageFetch %6 %50 %46 Lod %47 +OpBranch %56 +%56 = OpLabel +%62 = OpPhi %6 %53 %51 %53 %57 %61 %60 +OpReturnValue %62 +OpFunctionEnd +%66 = OpFunction %6 None %67 +%64 = OpFunctionParameter %8 +%65 = OpFunctionParameter %5 %63 = OpLabel -%64 = OpImageFetch %10 %53 %49 Lod %50 -OpBranch %59 -%59 = OpLabel -%65 = OpPhi %10 %56 %54 %56 %60 %64 %63 -OpReturnValue %65 +%68 = OpLoad %7 %23 +OpBranch %69 +%69 = OpLabel +%71 = OpImageQueryLevels %5 %68 +%72 = OpULessThan %52 %65 %71 +OpSelectionMerge %73 None +OpBranchConditional %72 %74 %73 +%74 = OpLabel +%75 = OpImageQuerySizeLod %8 %68 %65 +%77 = OpULessThan %76 %64 %75 +%78 = OpAll %52 %77 +OpBranchConditional %78 %79 %73 +%79 = OpLabel +%80 = OpImageFetch %6 %68 %64 Lod %65 +OpBranch %73 +%73 = OpLabel +%81 = OpPhi %6 %70 %69 %70 %74 %80 %79 +OpReturnValue %81 OpFunctionEnd -%69 = OpFunction %10 None %70 -%67 = OpFunctionParameter %12 -%68 = OpFunctionParameter %4 -%66 = OpLabel -%71 = OpLoad %11 %26 -OpBranch %72 -%72 = OpLabel -%74 = OpImageQueryLevels %4 %71 -%75 = OpULessThan %55 %68 %74 -OpSelectionMerge %76 None -OpBranchConditional %75 %77 %76 -%77 = OpLabel -%78 = OpImageQuerySizeLod %12 %71 %68 -%80 = OpULessThan %79 %67 %78 -%81 = OpAll %55 %80 -OpBranchConditional %81 %82 %76 +%86 = OpFunction %6 None %87 +%83 = OpFunctionParameter %8 +%84 = OpFunctionParameter %10 +%85 = OpFunctionParameter %5 %82 = OpLabel -%83 = OpImageFetch %10 %71 %67 Lod %68 -OpBranch %76 -%76 = OpLabel -%84 = OpPhi %10 %73 %72 %73 %77 %83 %82 -OpReturnValue %84 +%88 = OpLoad %9 %25 +OpBranch %89 +%89 = OpLabel +%90 = OpBitcast %5 %84 +%91 = OpCompositeConstruct %12 %83 %90 +%93 = OpImageQueryLevels %5 %88 +%94 = OpULessThan %52 %85 %93 +OpSelectionMerge %95 None +OpBranchConditional %94 %96 %95 +%96 = OpLabel +%97 = OpImageQuerySizeLod %12 %88 %85 +%99 = OpULessThan %98 %91 %97 +%100 = OpAll %52 %99 +OpBranchConditional %100 %101 %95 +%101 = OpLabel +%102 = OpImageFetch %6 %88 %91 Lod %85 +OpBranch %95 +%95 = OpLabel +%103 = OpPhi %6 %92 %89 %92 %96 %102 %101 +OpReturnValue %103 OpFunctionEnd -%89 = OpFunction %10 None %90 -%86 = OpFunctionParameter %12 -%87 = OpFunctionParameter %6 -%88 = OpFunctionParameter %4 -%85 = OpLabel -%91 = OpLoad %13 %28 -OpBranch %92 -%92 = OpLabel -%93 = OpBitcast %4 %87 -%94 = OpCompositeConstruct %15 %86 %93 -%96 = OpImageQueryLevels %4 %91 -%97 = OpULessThan %55 %88 %96 -OpSelectionMerge %98 None -OpBranchConditional %97 %99 %98 -%99 = OpLabel -%100 = OpImageQuerySizeLod %15 %91 %88 -%102 = OpULessThan %101 %94 %100 -%103 = OpAll %55 %102 -OpBranchConditional %103 %104 %98 +%108 = OpFunction %6 None %109 +%105 = OpFunctionParameter %8 +%106 = OpFunctionParameter %5 +%107 = OpFunctionParameter %5 %104 = OpLabel -%105 = OpImageFetch %10 %91 %94 Lod %88 -OpBranch %98 -%98 = OpLabel -%106 = OpPhi %10 %95 %92 %95 %99 %105 %104 -OpReturnValue %106 +%110 = OpLoad %9 %25 +OpBranch %111 +%111 = OpLabel +%112 = OpCompositeConstruct %12 %105 %106 +%114 = OpImageQueryLevels %5 %110 +%115 = OpULessThan %52 %107 %114 +OpSelectionMerge %116 None +OpBranchConditional %115 %117 %116 +%117 = OpLabel +%118 = OpImageQuerySizeLod %12 %110 %107 +%119 = OpULessThan %98 %112 %118 +%120 = OpAll %52 %119 +OpBranchConditional %120 %121 %116 +%121 = OpLabel +%122 = OpImageFetch %6 %110 %112 Lod %107 +OpBranch %116 +%116 = OpLabel +%123 = OpPhi %6 %113 %111 %113 %117 %122 %121 +OpReturnValue %123 OpFunctionEnd -%111 = OpFunction %10 None %112 -%108 = OpFunctionParameter %12 -%109 = OpFunctionParameter %4 -%110 = OpFunctionParameter %4 -%107 = OpLabel -%113 = OpLoad %13 %28 -OpBranch %114 -%114 = OpLabel -%115 = OpCompositeConstruct %15 %108 %109 -%117 = OpImageQueryLevels %4 %113 -%118 = OpULessThan %55 %110 %117 -OpSelectionMerge %119 None -OpBranchConditional %118 %120 %119 -%120 = OpLabel -%121 = OpImageQuerySizeLod %15 %113 %110 -%122 = OpULessThan %101 %115 %121 -%123 = OpAll %55 %122 -OpBranchConditional %123 %124 %119 +%127 = OpFunction %6 None %128 +%125 = OpFunctionParameter %12 +%126 = OpFunctionParameter %5 %124 = OpLabel -%125 = OpImageFetch %10 %113 %115 Lod %110 -OpBranch %119 -%119 = OpLabel -%126 = OpPhi %10 %116 %114 %116 %120 %125 %124 -OpReturnValue %126 +%129 = OpLoad %11 %27 +OpBranch %130 +%130 = OpLabel +%132 = OpImageQueryLevels %5 %129 +%133 = OpULessThan %52 %126 %132 +OpSelectionMerge %134 None +OpBranchConditional %133 %135 %134 +%135 = OpLabel +%136 = OpImageQuerySizeLod %12 %129 %126 +%137 = OpULessThan %98 %125 %136 +%138 = OpAll %52 %137 +OpBranchConditional %138 %139 %134 +%139 = OpLabel +%140 = OpImageFetch %6 %129 %125 Lod %126 +OpBranch %134 +%134 = OpLabel +%141 = OpPhi %6 %131 %130 %131 %135 %140 %139 +OpReturnValue %141 OpFunctionEnd -%130 = OpFunction %10 None %131 -%128 = OpFunctionParameter %15 -%129 = OpFunctionParameter %4 -%127 = OpLabel -%132 = OpLoad %14 %30 -OpBranch %133 -%133 = OpLabel -%135 = OpImageQueryLevels %4 %132 -%136 = OpULessThan %55 %129 %135 -OpSelectionMerge %137 None -OpBranchConditional %136 %138 %137 -%138 = OpLabel -%139 = OpImageQuerySizeLod %15 %132 %129 -%140 = OpULessThan %101 %128 %139 -%141 = OpAll %55 %140 -OpBranchConditional %141 %142 %137 +%145 = OpFunction %6 None %67 +%143 = OpFunctionParameter %8 +%144 = OpFunctionParameter %5 %142 = OpLabel -%143 = OpImageFetch %10 %132 %128 Lod %129 -OpBranch %137 -%137 = OpLabel -%144 = OpPhi %10 %134 %133 %134 %138 %143 %142 -OpReturnValue %144 +%146 = OpLoad %13 %29 +OpBranch %147 +%147 = OpLabel +%149 = OpImageQuerySamples %5 %146 +%150 = OpULessThan %52 %144 %149 +OpSelectionMerge %151 None +OpBranchConditional %150 %152 %151 +%152 = OpLabel +%153 = OpImageQuerySize %8 %146 +%154 = OpULessThan %76 %143 %153 +%155 = OpAll %52 %154 +OpBranchConditional %155 %156 %151 +%156 = OpLabel +%157 = OpImageFetch %6 %146 %143 Sample %144 +OpBranch %151 +%151 = OpLabel +%158 = OpPhi %6 %148 %147 %148 %152 %157 %156 +OpReturnValue %158 OpFunctionEnd -%148 = OpFunction %10 None %70 -%146 = OpFunctionParameter %12 -%147 = OpFunctionParameter %4 -%145 = OpLabel -%149 = OpLoad %16 %32 -OpBranch %150 -%150 = OpLabel -%152 = OpImageQuerySamples %4 %149 -%153 = OpULessThan %55 %147 %152 -OpSelectionMerge %154 None -OpBranchConditional %153 %155 %154 -%155 = OpLabel -%156 = OpImageQuerySize %12 %149 -%157 = OpULessThan %79 %146 %156 -%158 = OpAll %55 %157 -OpBranchConditional %158 %159 %154 +%162 = OpFunction %4 None %163 +%160 = OpFunctionParameter %8 +%161 = OpFunctionParameter %5 %159 = OpLabel -%160 = OpImageFetch %10 %149 %146 Sample %147 -OpBranch %154 -%154 = OpLabel -%161 = OpPhi %10 %151 %150 %151 %155 %160 %159 -OpReturnValue %161 +%164 = OpLoad %14 %31 +OpBranch %165 +%165 = OpLabel +%167 = OpImageQueryLevels %5 %164 +%168 = OpULessThan %52 %161 %167 +OpSelectionMerge %169 None +OpBranchConditional %168 %170 %169 +%170 = OpLabel +%171 = OpImageQuerySizeLod %8 %164 %161 +%172 = OpULessThan %76 %160 %171 +%173 = OpAll %52 %172 +OpBranchConditional %173 %174 %169 +%174 = OpLabel +%175 = OpImageFetch %6 %164 %160 Lod %161 +OpBranch %169 +%169 = OpLabel +%176 = OpPhi %6 %166 %165 %166 %170 %175 %174 +%177 = OpCompositeExtract %4 %176 0 +OpReturnValue %177 OpFunctionEnd -%165 = OpFunction %8 None %166 -%163 = OpFunctionParameter %12 -%164 = OpFunctionParameter %4 -%162 = OpLabel -%167 = OpLoad %17 %34 -OpBranch %168 -%168 = OpLabel -%170 = OpImageQueryLevels %4 %167 -%171 = OpULessThan %55 %164 %170 -OpSelectionMerge %172 None -OpBranchConditional %171 %173 %172 -%173 = OpLabel -%174 = OpImageQuerySizeLod %12 %167 %164 -%175 = OpULessThan %79 %163 %174 -%176 = OpAll %55 %175 -OpBranchConditional %176 %177 %172 -%177 = OpLabel -%178 = OpImageFetch %10 %167 %163 Lod %164 -OpBranch %172 -%172 = OpLabel -%179 = OpPhi %10 %169 %168 %169 %173 %178 %177 -%180 = OpCompositeExtract %8 %179 0 -OpReturnValue %180 +%182 = OpFunction %4 None %183 +%179 = OpFunctionParameter %8 +%180 = OpFunctionParameter %10 +%181 = OpFunctionParameter %5 +%178 = OpLabel +%184 = OpLoad %15 %33 +OpBranch %185 +%185 = OpLabel +%186 = OpBitcast %5 %180 +%187 = OpCompositeConstruct %12 %179 %186 +%189 = OpImageQueryLevels %5 %184 +%190 = OpULessThan %52 %181 %189 +OpSelectionMerge %191 None +OpBranchConditional %190 %192 %191 +%192 = OpLabel +%193 = OpImageQuerySizeLod %12 %184 %181 +%194 = OpULessThan %98 %187 %193 +%195 = OpAll %52 %194 +OpBranchConditional %195 %196 %191 +%196 = OpLabel +%197 = OpImageFetch %6 %184 %187 Lod %181 +OpBranch %191 +%191 = OpLabel +%198 = OpPhi %6 %188 %185 %188 %192 %197 %196 +%199 = OpCompositeExtract %4 %198 0 +OpReturnValue %199 OpFunctionEnd -%185 = OpFunction %8 None %186 -%182 = OpFunctionParameter %12 -%183 = OpFunctionParameter %6 -%184 = OpFunctionParameter %4 -%181 = OpLabel -%187 = OpLoad %18 %36 -OpBranch %188 -%188 = OpLabel -%189 = OpBitcast %4 %183 -%190 = OpCompositeConstruct %15 %182 %189 -%192 = OpImageQueryLevels %4 %187 -%193 = OpULessThan %55 %184 %192 -OpSelectionMerge %194 None -OpBranchConditional %193 %195 %194 -%195 = OpLabel -%196 = OpImageQuerySizeLod %15 %187 %184 -%197 = OpULessThan %101 %190 %196 -%198 = OpAll %55 %197 -OpBranchConditional %198 %199 %194 -%199 = OpLabel -%200 = OpImageFetch %10 %187 %190 Lod %184 -OpBranch %194 -%194 = OpLabel -%201 = OpPhi %10 %191 %188 %191 %195 %200 %199 -%202 = OpCompositeExtract %8 %201 0 -OpReturnValue %202 +%204 = OpFunction %4 None %205 +%201 = OpFunctionParameter %8 +%202 = OpFunctionParameter %5 +%203 = OpFunctionParameter %5 +%200 = OpLabel +%206 = OpLoad %15 %33 +OpBranch %207 +%207 = OpLabel +%208 = OpCompositeConstruct %12 %201 %202 +%210 = OpImageQueryLevels %5 %206 +%211 = OpULessThan %52 %203 %210 +OpSelectionMerge %212 None +OpBranchConditional %211 %213 %212 +%213 = OpLabel +%214 = OpImageQuerySizeLod %12 %206 %203 +%215 = OpULessThan %98 %208 %214 +%216 = OpAll %52 %215 +OpBranchConditional %216 %217 %212 +%217 = OpLabel +%218 = OpImageFetch %6 %206 %208 Lod %203 +OpBranch %212 +%212 = OpLabel +%219 = OpPhi %6 %209 %207 %209 %213 %218 %217 +%220 = OpCompositeExtract %4 %219 0 +OpReturnValue %220 OpFunctionEnd -%207 = OpFunction %8 None %208 -%204 = OpFunctionParameter %12 -%205 = OpFunctionParameter %4 -%206 = OpFunctionParameter %4 -%203 = OpLabel -%209 = OpLoad %18 %36 -OpBranch %210 -%210 = OpLabel -%211 = OpCompositeConstruct %15 %204 %205 -%213 = OpImageQueryLevels %4 %209 -%214 = OpULessThan %55 %206 %213 -OpSelectionMerge %215 None -OpBranchConditional %214 %216 %215 -%216 = OpLabel -%217 = OpImageQuerySizeLod %15 %209 %206 -%218 = OpULessThan %101 %211 %217 -%219 = OpAll %55 %218 -OpBranchConditional %219 %220 %215 -%220 = OpLabel -%221 = OpImageFetch %10 %209 %211 Lod %206 -OpBranch %215 -%215 = OpLabel -%222 = OpPhi %10 %212 %210 %212 %216 %221 %220 -%223 = OpCompositeExtract %8 %222 0 -OpReturnValue %223 +%224 = OpFunction %4 None %163 +%222 = OpFunctionParameter %8 +%223 = OpFunctionParameter %5 +%221 = OpLabel +%225 = OpLoad %16 %35 +OpBranch %226 +%226 = OpLabel +%228 = OpImageQuerySamples %5 %225 +%229 = OpULessThan %52 %223 %228 +OpSelectionMerge %230 None +OpBranchConditional %229 %231 %230 +%231 = OpLabel +%232 = OpImageQuerySize %8 %225 +%233 = OpULessThan %76 %222 %232 +%234 = OpAll %52 %233 +OpBranchConditional %234 %235 %230 +%235 = OpLabel +%236 = OpImageFetch %6 %225 %222 Sample %223 +OpBranch %230 +%230 = OpLabel +%237 = OpPhi %6 %227 %226 %227 %231 %236 %235 +%238 = OpCompositeExtract %4 %237 0 +OpReturnValue %238 OpFunctionEnd -%227 = OpFunction %8 None %166 -%225 = OpFunctionParameter %12 -%226 = OpFunctionParameter %4 -%224 = OpLabel -%228 = OpLoad %19 %38 -OpBranch %229 -%229 = OpLabel -%231 = OpImageQuerySamples %4 %228 -%232 = OpULessThan %55 %226 %231 -OpSelectionMerge %233 None -OpBranchConditional %232 %234 %233 -%234 = OpLabel -%235 = OpImageQuerySize %12 %228 -%236 = OpULessThan %79 %225 %235 -%237 = OpAll %55 %236 -OpBranchConditional %237 %238 %233 -%238 = OpLabel -%239 = OpImageFetch %10 %228 %225 Sample %226 -OpBranch %233 -%233 = OpLabel -%240 = OpPhi %10 %230 %229 %230 %234 %239 %238 -%241 = OpCompositeExtract %8 %240 0 -OpReturnValue %241 -OpFunctionEnd -%245 = OpFunction %2 None %246 -%243 = OpFunctionParameter %4 -%244 = OpFunctionParameter %10 -%242 = OpLabel -%247 = OpLoad %20 %40 +%242 = OpFunction %2 None %243 +%240 = OpFunctionParameter %5 +%241 = OpFunctionParameter %6 +%239 = OpLabel +%244 = OpLoad %17 %37 +OpBranch %245 +%245 = OpLabel +%246 = OpImageQuerySize %5 %244 +%247 = OpULessThan %52 %240 %246 +OpSelectionMerge %248 None +OpBranchConditional %247 %249 %248 +%249 = OpLabel +OpImageWrite %244 %240 %241 OpBranch %248 %248 = OpLabel -%249 = OpImageQuerySize %4 %247 -%250 = OpULessThan %55 %243 %249 -OpSelectionMerge %251 None -OpBranchConditional %250 %252 %251 -%252 = OpLabel -OpImageWrite %247 %243 %244 -OpBranch %251 -%251 = OpLabel OpReturn OpFunctionEnd -%256 = OpFunction %2 None %257 -%254 = OpFunctionParameter %12 -%255 = OpFunctionParameter %10 -%253 = OpLabel -%258 = OpLoad %21 %42 -OpBranch %259 -%259 = OpLabel -%260 = OpImageQuerySize %12 %258 -%261 = OpULessThan %79 %254 %260 -%262 = OpAll %55 %261 -OpSelectionMerge %263 None -OpBranchConditional %262 %264 %263 -%264 = OpLabel -OpImageWrite %258 %254 %255 -OpBranch %263 -%263 = OpLabel +%253 = OpFunction %2 None %254 +%251 = OpFunctionParameter %8 +%252 = OpFunctionParameter %6 +%250 = OpLabel +%255 = OpLoad %18 %39 +OpBranch %256 +%256 = OpLabel +%257 = OpImageQuerySize %8 %255 +%258 = OpULessThan %76 %251 %257 +%259 = OpAll %52 %258 +OpSelectionMerge %260 None +OpBranchConditional %259 %261 %260 +%261 = OpLabel +OpImageWrite %255 %251 %252 +OpBranch %260 +%260 = OpLabel OpReturn OpFunctionEnd -%269 = OpFunction %2 None %270 -%266 = OpFunctionParameter %12 -%267 = OpFunctionParameter %6 -%268 = OpFunctionParameter %10 -%265 = OpLabel -%271 = OpLoad %22 %44 -OpBranch %272 -%272 = OpLabel -%273 = OpBitcast %4 %267 -%274 = OpCompositeConstruct %15 %266 %273 -%275 = OpImageQuerySize %15 %271 -%276 = OpULessThan %101 %274 %275 -%277 = OpAll %55 %276 -OpSelectionMerge %278 None -OpBranchConditional %277 %279 %278 -%279 = OpLabel -OpImageWrite %271 %274 %268 -OpBranch %278 -%278 = OpLabel +%266 = OpFunction %2 None %267 +%263 = OpFunctionParameter %8 +%264 = OpFunctionParameter %10 +%265 = OpFunctionParameter %6 +%262 = OpLabel +%268 = OpLoad %19 %41 +OpBranch %269 +%269 = OpLabel +%270 = OpBitcast %5 %264 +%271 = OpCompositeConstruct %12 %263 %270 +%272 = OpImageQuerySize %12 %268 +%273 = OpULessThan %98 %271 %272 +%274 = OpAll %52 %273 +OpSelectionMerge %275 None +OpBranchConditional %274 %276 %275 +%276 = OpLabel +OpImageWrite %268 %271 %265 +OpBranch %275 +%275 = OpLabel OpReturn OpFunctionEnd -%284 = OpFunction %2 None %285 -%281 = OpFunctionParameter %12 -%282 = OpFunctionParameter %4 -%283 = OpFunctionParameter %10 -%280 = OpLabel -%286 = OpLoad %22 %44 -OpBranch %287 -%287 = OpLabel -%288 = OpCompositeConstruct %15 %281 %282 -%289 = OpImageQuerySize %15 %286 -%290 = OpULessThan %101 %288 %289 -%291 = OpAll %55 %290 -OpSelectionMerge %292 None -OpBranchConditional %291 %293 %292 -%293 = OpLabel -OpImageWrite %286 %288 %283 -OpBranch %292 -%292 = OpLabel +%281 = OpFunction %2 None %282 +%278 = OpFunctionParameter %8 +%279 = OpFunctionParameter %5 +%280 = OpFunctionParameter %6 +%277 = OpLabel +%283 = OpLoad %19 %41 +OpBranch %284 +%284 = OpLabel +%285 = OpCompositeConstruct %12 %278 %279 +%286 = OpImageQuerySize %12 %283 +%287 = OpULessThan %98 %285 %286 +%288 = OpAll %52 %287 +OpSelectionMerge %289 None +OpBranchConditional %288 %290 %289 +%290 = OpLabel +OpImageWrite %283 %285 %280 +OpBranch %289 +%289 = OpLabel OpReturn OpFunctionEnd -%297 = OpFunction %2 None %298 -%295 = OpFunctionParameter %15 -%296 = OpFunctionParameter %10 -%294 = OpLabel -%299 = OpLoad %23 %46 -OpBranch %300 -%300 = OpLabel -%301 = OpImageQuerySize %15 %299 -%302 = OpULessThan %101 %295 %301 -%303 = OpAll %55 %302 -OpSelectionMerge %304 None -OpBranchConditional %303 %305 %304 -%305 = OpLabel -OpImageWrite %299 %295 %296 -OpBranch %304 -%304 = OpLabel +%294 = OpFunction %2 None %295 +%292 = OpFunctionParameter %12 +%293 = OpFunctionParameter %6 +%291 = OpLabel +%296 = OpLoad %20 %43 +OpBranch %297 +%297 = OpLabel +%298 = OpImageQuerySize %12 %296 +%299 = OpULessThan %98 %292 %298 +%300 = OpAll %52 %299 +OpSelectionMerge %301 None +OpBranchConditional %300 %302 %301 +%302 = OpLabel +OpImageWrite %296 %292 %293 +OpBranch %301 +%301 = OpLabel OpReturn OpFunctionEnd -%309 = OpFunction %2 None %310 -%306 = OpLabel -%311 = OpLoad %9 %24 -%312 = OpLoad %11 %26 -%313 = OpLoad %13 %28 -%314 = OpLoad %14 %30 -%315 = OpLoad %16 %32 -%316 = OpLoad %20 %40 -%317 = OpLoad %21 %42 -%318 = OpLoad %22 %44 -%319 = OpLoad %23 %46 +%306 = OpFunction %2 None %307 +%303 = OpLabel +%308 = OpLoad %3 %21 +%309 = OpLoad %7 %23 +%310 = OpLoad %9 %25 +%311 = OpLoad %11 %27 +%312 = OpLoad %13 %29 +%313 = OpLoad %17 %37 +%314 = OpLoad %18 %39 +%315 = OpLoad %19 %41 +%316 = OpLoad %20 %43 OpBranch %334 %334 = OpLabel -%335 = OpFunctionCall %10 %51 %3 %3 -%336 = OpFunctionCall %10 %69 %320 %3 -%337 = OpFunctionCall %10 %89 %321 %5 %3 -%338 = OpFunctionCall %10 %111 %322 %3 %3 -%339 = OpFunctionCall %10 %130 %323 %3 -%340 = OpFunctionCall %10 %148 %324 %3 -%341 = OpFunctionCall %2 %245 %3 %325 -%342 = OpFunctionCall %2 %256 %326 %327 -%343 = OpFunctionCall %2 %269 %328 %5 %329 -%344 = OpFunctionCall %2 %284 %330 %3 %331 -%345 = OpFunctionCall %2 %297 %332 %333 -%346 = OpCompositeConstruct %10 %7 %7 %7 %7 -OpStore %307 %346 +%335 = OpFunctionCall %6 %48 %317 %317 +%336 = OpFunctionCall %6 %66 %318 %317 +%337 = OpFunctionCall %6 %86 %319 %320 %317 +%338 = OpFunctionCall %6 %108 %321 %317 %317 +%339 = OpFunctionCall %6 %127 %322 %317 +%340 = OpFunctionCall %6 %145 %323 %317 +%341 = OpFunctionCall %2 %242 %317 %324 +%342 = OpFunctionCall %2 %253 %325 %326 +%343 = OpFunctionCall %2 %266 %327 %320 %328 +%344 = OpFunctionCall %2 %281 %329 %317 %330 +%345 = OpFunctionCall %2 %294 %331 %332 +%346 = OpCompositeConstruct %6 %333 %333 %333 %333 +OpStore %304 %346 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-restrict.spvasm b/tests/out/spv/bounds-check-restrict.spvasm index 192712346..7977495aa 100644 --- a/tests/out/spv/bounds-check-restrict.spvasm +++ b/tests/out/spv/bounds-check-restrict.spvasm @@ -7,232 +7,232 @@ OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpDecorate %10 ArrayStride 4 -OpDecorate %13 ArrayStride 4 -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 1 Offset 48 -OpMemberDecorate %14 2 Offset 64 -OpMemberDecorate %14 2 ColMajor -OpMemberDecorate %14 2 MatrixStride 16 -OpMemberDecorate %14 3 Offset 112 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 0 -OpDecorate %14 Block +OpDecorate %6 ArrayStride 4 +OpDecorate %9 ArrayStride 4 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 48 +OpMemberDecorate %10 2 Offset 64 +OpMemberDecorate %10 2 ColMajor +OpMemberDecorate %10 2 MatrixStride 16 +OpMemberDecorate %10 3 Offset 112 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 0 +OpDecorate %10 Block %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 -%6 = OpTypeFloat 32 -%5 = OpConstant %6 100.0 -%7 = OpConstant %4 9 -%8 = OpConstant %4 3 -%9 = OpConstant %4 2 -%10 = OpTypeArray %6 %3 -%11 = OpTypeVector %6 4 -%12 = OpTypeMatrix %11 3 -%13 = OpTypeRuntimeArray %6 -%14 = OpTypeStruct %10 %11 %12 %13 -%16 = OpTypePointer StorageBuffer %14 -%15 = OpVariable %16 StorageBuffer -%20 = OpTypeFunction %6 %4 -%22 = OpTypePointer StorageBuffer %10 -%23 = OpTypePointer StorageBuffer %6 -%25 = OpTypeInt 32 0 -%24 = OpConstant %25 9 -%27 = OpConstant %25 0 -%34 = OpTypePointer StorageBuffer %13 -%36 = OpConstant %25 1 -%39 = OpConstant %25 3 -%46 = OpTypePointer StorageBuffer %11 -%47 = OpTypePointer StorageBuffer %6 -%55 = OpTypeFunction %6 %11 %4 -%62 = OpTypeFunction %11 %4 -%64 = OpTypePointer StorageBuffer %12 -%65 = OpTypePointer StorageBuffer %11 -%66 = OpConstant %25 2 -%74 = OpTypeFunction %6 %4 %4 -%94 = OpTypeFunction %6 -%108 = OpTypeFunction %2 %4 %6 -%132 = OpTypeFunction %2 %4 %11 -%141 = OpTypeFunction %2 %4 %4 %6 -%161 = OpTypeFunction %2 %6 -%19 = OpFunction %6 None %20 -%18 = OpFunctionParameter %4 +%5 = OpTypeFloat 32 +%6 = OpTypeArray %5 %3 +%7 = OpTypeVector %5 4 +%8 = OpTypeMatrix %7 3 +%9 = OpTypeRuntimeArray %5 +%10 = OpTypeStruct %6 %7 %8 %9 +%12 = OpTypePointer StorageBuffer %10 +%11 = OpVariable %12 StorageBuffer +%16 = OpTypeFunction %5 %4 +%18 = OpTypePointer StorageBuffer %6 +%19 = OpTypePointer StorageBuffer %5 +%21 = OpTypeInt 32 0 +%20 = OpConstant %21 9 +%23 = OpConstant %21 0 +%30 = OpTypePointer StorageBuffer %9 +%32 = OpConstant %21 1 +%35 = OpConstant %21 3 +%42 = OpTypePointer StorageBuffer %7 +%43 = OpTypePointer StorageBuffer %5 +%51 = OpTypeFunction %5 %7 %4 +%58 = OpTypeFunction %7 %4 +%60 = OpTypePointer StorageBuffer %8 +%61 = OpTypePointer StorageBuffer %7 +%62 = OpConstant %21 2 +%70 = OpTypeFunction %5 %4 %4 +%79 = OpConstant %5 100.0 +%91 = OpTypeFunction %5 +%92 = OpConstant %4 9 +%93 = OpConstant %4 3 +%94 = OpConstant %4 2 +%108 = OpTypeFunction %2 %4 %5 +%132 = OpTypeFunction %2 %4 %7 +%141 = OpTypeFunction %2 %4 %4 %5 +%161 = OpTypeFunction %2 %5 +%15 = OpFunction %5 None %16 +%14 = OpFunctionParameter %4 +%13 = OpLabel +OpBranch %17 %17 = OpLabel -OpBranch %21 -%21 = OpLabel -%26 = OpExtInst %25 %1 UMin %18 %24 -%28 = OpAccessChain %23 %15 %27 %26 -%29 = OpLoad %6 %28 -OpReturnValue %29 +%22 = OpExtInst %21 %1 UMin %14 %20 +%24 = OpAccessChain %19 %11 %23 %22 +%25 = OpLoad %5 %24 +OpReturnValue %25 OpFunctionEnd -%32 = OpFunction %6 None %20 -%31 = OpFunctionParameter %4 -%30 = OpLabel -OpBranch %33 -%33 = OpLabel -%35 = OpArrayLength %25 %15 3 -%37 = OpISub %25 %35 %36 -%38 = OpExtInst %25 %1 UMin %31 %37 -%40 = OpAccessChain %23 %15 %39 %38 -%41 = OpLoad %6 %40 -OpReturnValue %41 +%28 = OpFunction %5 None %16 +%27 = OpFunctionParameter %4 +%26 = OpLabel +OpBranch %29 +%29 = OpLabel +%31 = OpArrayLength %21 %11 3 +%33 = OpISub %21 %31 %32 +%34 = OpExtInst %21 %1 UMin %27 %33 +%36 = OpAccessChain %19 %11 %35 %34 +%37 = OpLoad %5 %36 +OpReturnValue %37 OpFunctionEnd -%44 = OpFunction %6 None %20 -%43 = OpFunctionParameter %4 -%42 = OpLabel -OpBranch %45 -%45 = OpLabel -%48 = OpExtInst %25 %1 UMin %43 %39 -%49 = OpAccessChain %47 %15 %36 %48 -%50 = OpLoad %6 %49 -OpReturnValue %50 +%40 = OpFunction %5 None %16 +%39 = OpFunctionParameter %4 +%38 = OpLabel +OpBranch %41 +%41 = OpLabel +%44 = OpExtInst %21 %1 UMin %39 %35 +%45 = OpAccessChain %43 %11 %32 %44 +%46 = OpLoad %5 %45 +OpReturnValue %46 OpFunctionEnd -%54 = OpFunction %6 None %55 -%52 = OpFunctionParameter %11 -%53 = OpFunctionParameter %4 -%51 = OpLabel -OpBranch %56 -%56 = OpLabel -%57 = OpExtInst %25 %1 UMin %53 %39 -%58 = OpVectorExtractDynamic %6 %52 %57 -OpReturnValue %58 +%50 = OpFunction %5 None %51 +%48 = OpFunctionParameter %7 +%49 = OpFunctionParameter %4 +%47 = OpLabel +OpBranch %52 +%52 = OpLabel +%53 = OpExtInst %21 %1 UMin %49 %35 +%54 = OpVectorExtractDynamic %5 %48 %53 +OpReturnValue %54 OpFunctionEnd -%61 = OpFunction %11 None %62 -%60 = OpFunctionParameter %4 +%57 = OpFunction %7 None %58 +%56 = OpFunctionParameter %4 +%55 = OpLabel +OpBranch %59 %59 = OpLabel -OpBranch %63 -%63 = OpLabel -%67 = OpExtInst %25 %1 UMin %60 %66 -%68 = OpAccessChain %65 %15 %66 %67 -%69 = OpLoad %11 %68 -OpReturnValue %69 +%63 = OpExtInst %21 %1 UMin %56 %62 +%64 = OpAccessChain %61 %11 %62 %63 +%65 = OpLoad %7 %64 +OpReturnValue %65 OpFunctionEnd -%73 = OpFunction %6 None %74 -%71 = OpFunctionParameter %4 -%72 = OpFunctionParameter %4 -%70 = OpLabel -OpBranch %75 -%75 = OpLabel -%76 = OpExtInst %25 %1 UMin %72 %39 -%77 = OpExtInst %25 %1 UMin %71 %66 -%78 = OpAccessChain %47 %15 %66 %77 %76 -%79 = OpLoad %6 %78 -OpReturnValue %79 +%69 = OpFunction %5 None %70 +%67 = OpFunctionParameter %4 +%68 = OpFunctionParameter %4 +%66 = OpLabel +OpBranch %71 +%71 = OpLabel +%72 = OpExtInst %21 %1 UMin %68 %35 +%73 = OpExtInst %21 %1 UMin %67 %62 +%74 = OpAccessChain %43 %11 %62 %73 %72 +%75 = OpLoad %5 %74 +OpReturnValue %75 OpFunctionEnd -%82 = OpFunction %6 None %20 -%81 = OpFunctionParameter %4 +%78 = OpFunction %5 None %16 +%77 = OpFunctionParameter %4 +%76 = OpLabel +OpBranch %80 %80 = OpLabel -OpBranch %83 -%83 = OpLabel -%84 = OpConvertSToF %6 %81 -%85 = OpFDiv %6 %84 %5 -%86 = OpExtInst %6 %1 Sin %85 -%87 = OpFMul %6 %86 %5 -%88 = OpConvertFToS %4 %87 -%89 = OpExtInst %25 %1 UMin %88 %24 -%90 = OpAccessChain %23 %15 %27 %89 -%91 = OpLoad %6 %90 -OpReturnValue %91 +%81 = OpConvertSToF %5 %77 +%82 = OpFDiv %5 %81 %79 +%83 = OpExtInst %5 %1 Sin %82 +%84 = OpFMul %5 %83 %79 +%85 = OpConvertFToS %4 %84 +%86 = OpExtInst %21 %1 UMin %85 %20 +%87 = OpAccessChain %19 %11 %23 %86 +%88 = OpLoad %5 %87 +OpReturnValue %88 OpFunctionEnd -%93 = OpFunction %6 None %94 -%92 = OpLabel +%90 = OpFunction %5 None %91 +%89 = OpLabel OpBranch %95 %95 = OpLabel -%96 = OpAccessChain %23 %15 %27 %24 -%97 = OpLoad %6 %96 -%98 = OpAccessChain %47 %15 %36 %39 -%99 = OpLoad %6 %98 -%100 = OpFAdd %6 %97 %99 -%101 = OpAccessChain %47 %15 %66 %66 %39 -%102 = OpLoad %6 %101 -%103 = OpFAdd %6 %100 %102 +%96 = OpAccessChain %19 %11 %23 %20 +%97 = OpLoad %5 %96 +%98 = OpAccessChain %43 %11 %32 %35 +%99 = OpLoad %5 %98 +%100 = OpFAdd %5 %97 %99 +%101 = OpAccessChain %43 %11 %62 %62 %35 +%102 = OpLoad %5 %101 +%103 = OpFAdd %5 %100 %102 OpReturnValue %103 OpFunctionEnd %107 = OpFunction %2 None %108 %105 = OpFunctionParameter %4 -%106 = OpFunctionParameter %6 +%106 = OpFunctionParameter %5 %104 = OpLabel OpBranch %109 %109 = OpLabel -%110 = OpExtInst %25 %1 UMin %105 %24 -%111 = OpAccessChain %23 %15 %27 %110 +%110 = OpExtInst %21 %1 UMin %105 %20 +%111 = OpAccessChain %19 %11 %23 %110 OpStore %111 %106 OpReturn OpFunctionEnd %115 = OpFunction %2 None %108 %113 = OpFunctionParameter %4 -%114 = OpFunctionParameter %6 +%114 = OpFunctionParameter %5 %112 = OpLabel OpBranch %116 %116 = OpLabel -%117 = OpArrayLength %25 %15 3 -%118 = OpISub %25 %117 %36 -%119 = OpExtInst %25 %1 UMin %113 %118 -%120 = OpAccessChain %23 %15 %39 %119 +%117 = OpArrayLength %21 %11 3 +%118 = OpISub %21 %117 %32 +%119 = OpExtInst %21 %1 UMin %113 %118 +%120 = OpAccessChain %19 %11 %35 %119 OpStore %120 %114 OpReturn OpFunctionEnd %124 = OpFunction %2 None %108 %122 = OpFunctionParameter %4 -%123 = OpFunctionParameter %6 +%123 = OpFunctionParameter %5 %121 = OpLabel OpBranch %125 %125 = OpLabel -%126 = OpExtInst %25 %1 UMin %122 %39 -%127 = OpAccessChain %47 %15 %36 %126 +%126 = OpExtInst %21 %1 UMin %122 %35 +%127 = OpAccessChain %43 %11 %32 %126 OpStore %127 %123 OpReturn OpFunctionEnd %131 = OpFunction %2 None %132 %129 = OpFunctionParameter %4 -%130 = OpFunctionParameter %11 +%130 = OpFunctionParameter %7 %128 = OpLabel OpBranch %133 %133 = OpLabel -%134 = OpExtInst %25 %1 UMin %129 %66 -%135 = OpAccessChain %65 %15 %66 %134 +%134 = OpExtInst %21 %1 UMin %129 %62 +%135 = OpAccessChain %61 %11 %62 %134 OpStore %135 %130 OpReturn OpFunctionEnd %140 = OpFunction %2 None %141 %137 = OpFunctionParameter %4 %138 = OpFunctionParameter %4 -%139 = OpFunctionParameter %6 +%139 = OpFunctionParameter %5 %136 = OpLabel OpBranch %142 %142 = OpLabel -%143 = OpExtInst %25 %1 UMin %138 %39 -%144 = OpExtInst %25 %1 UMin %137 %66 -%145 = OpAccessChain %47 %15 %66 %144 %143 +%143 = OpExtInst %21 %1 UMin %138 %35 +%144 = OpExtInst %21 %1 UMin %137 %62 +%145 = OpAccessChain %43 %11 %62 %144 %143 OpStore %145 %139 OpReturn OpFunctionEnd %149 = OpFunction %2 None %108 %147 = OpFunctionParameter %4 -%148 = OpFunctionParameter %6 +%148 = OpFunctionParameter %5 %146 = OpLabel OpBranch %150 %150 = OpLabel -%151 = OpConvertSToF %6 %147 -%152 = OpFDiv %6 %151 %5 -%153 = OpExtInst %6 %1 Sin %152 -%154 = OpFMul %6 %153 %5 +%151 = OpConvertSToF %5 %147 +%152 = OpFDiv %5 %151 %79 +%153 = OpExtInst %5 %1 Sin %152 +%154 = OpFMul %5 %153 %79 %155 = OpConvertFToS %4 %154 -%156 = OpExtInst %25 %1 UMin %155 %24 -%157 = OpAccessChain %23 %15 %27 %156 +%156 = OpExtInst %21 %1 UMin %155 %20 +%157 = OpAccessChain %19 %11 %23 %156 OpStore %157 %148 OpReturn OpFunctionEnd %160 = OpFunction %2 None %161 -%159 = OpFunctionParameter %6 +%159 = OpFunctionParameter %5 %158 = OpLabel OpBranch %162 %162 = OpLabel -%163 = OpAccessChain %23 %15 %27 %24 +%163 = OpAccessChain %19 %11 %23 %20 OpStore %163 %159 -%164 = OpAccessChain %47 %15 %36 %39 +%164 = OpAccessChain %43 %11 %32 %35 OpStore %164 %159 -%165 = OpAccessChain %47 %15 %66 %66 %39 +%165 = OpAccessChain %43 %11 %62 %62 %35 OpStore %165 %159 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index 5e5aac07f..3879709a5 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -7,210 +7,210 @@ OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpDecorate %10 ArrayStride 4 -OpDecorate %13 ArrayStride 4 -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 1 Offset 48 -OpMemberDecorate %14 2 Offset 64 -OpMemberDecorate %14 2 ColMajor -OpMemberDecorate %14 2 MatrixStride 16 -OpMemberDecorate %14 3 Offset 112 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 0 -OpDecorate %14 Block +OpDecorate %6 ArrayStride 4 +OpDecorate %9 ArrayStride 4 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 48 +OpMemberDecorate %10 2 Offset 64 +OpMemberDecorate %10 2 ColMajor +OpMemberDecorate %10 2 MatrixStride 16 +OpMemberDecorate %10 3 Offset 112 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 0 +OpDecorate %10 Block %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 -%6 = OpTypeFloat 32 -%5 = OpConstant %6 100.0 -%7 = OpConstant %4 9 -%8 = OpConstant %4 3 -%9 = OpConstant %4 2 -%10 = OpTypeArray %6 %3 -%11 = OpTypeVector %6 4 -%12 = OpTypeMatrix %11 3 -%13 = OpTypeRuntimeArray %6 -%14 = OpTypeStruct %10 %11 %12 %13 -%16 = OpTypePointer StorageBuffer %14 -%15 = OpVariable %16 StorageBuffer -%20 = OpTypeFunction %6 %4 -%22 = OpTypePointer StorageBuffer %10 -%23 = OpTypePointer StorageBuffer %6 -%25 = OpTypeInt 32 0 -%24 = OpConstant %25 10 -%27 = OpTypeBool -%28 = OpConstant %25 0 -%30 = OpConstantNull %6 -%39 = OpTypePointer StorageBuffer %13 -%42 = OpConstant %25 3 -%44 = OpConstantNull %6 -%53 = OpTypePointer StorageBuffer %11 -%54 = OpTypePointer StorageBuffer %6 -%55 = OpConstant %25 4 -%57 = OpConstant %25 1 -%59 = OpConstantNull %6 -%68 = OpTypeFunction %6 %11 %4 -%71 = OpConstantNull %6 -%79 = OpTypeFunction %11 %4 -%81 = OpTypePointer StorageBuffer %12 -%82 = OpTypePointer StorageBuffer %11 -%84 = OpConstant %25 2 -%86 = OpConstantNull %11 -%95 = OpTypeFunction %6 %4 %4 -%101 = OpConstantNull %6 -%117 = OpConstantNull %6 -%124 = OpTypeFunction %6 -%126 = OpConstant %25 9 -%139 = OpTypeFunction %2 %4 %6 -%168 = OpTypeFunction %2 %4 %11 -%179 = OpTypeFunction %2 %4 %4 %6 -%204 = OpTypeFunction %2 %6 -%19 = OpFunction %6 None %20 -%18 = OpFunctionParameter %4 +%5 = OpTypeFloat 32 +%6 = OpTypeArray %5 %3 +%7 = OpTypeVector %5 4 +%8 = OpTypeMatrix %7 3 +%9 = OpTypeRuntimeArray %5 +%10 = OpTypeStruct %6 %7 %8 %9 +%12 = OpTypePointer StorageBuffer %10 +%11 = OpVariable %12 StorageBuffer +%16 = OpTypeFunction %5 %4 +%18 = OpTypePointer StorageBuffer %6 +%19 = OpTypePointer StorageBuffer %5 +%21 = OpTypeInt 32 0 +%20 = OpConstant %21 10 +%23 = OpTypeBool +%24 = OpConstant %21 0 +%26 = OpConstantNull %5 +%35 = OpTypePointer StorageBuffer %9 +%38 = OpConstant %21 3 +%40 = OpConstantNull %5 +%49 = OpTypePointer StorageBuffer %7 +%50 = OpTypePointer StorageBuffer %5 +%51 = OpConstant %21 4 +%53 = OpConstant %21 1 +%55 = OpConstantNull %5 +%64 = OpTypeFunction %5 %7 %4 +%67 = OpConstantNull %5 +%75 = OpTypeFunction %7 %4 +%77 = OpTypePointer StorageBuffer %8 +%78 = OpTypePointer StorageBuffer %7 +%80 = OpConstant %21 2 +%82 = OpConstantNull %7 +%91 = OpTypeFunction %5 %4 %4 +%97 = OpConstantNull %5 +%105 = OpConstant %5 100.0 +%114 = OpConstantNull %5 +%121 = OpTypeFunction %5 +%122 = OpConstant %4 9 +%123 = OpConstant %4 3 +%124 = OpConstant %4 2 +%126 = OpConstant %21 9 +%139 = OpTypeFunction %2 %4 %5 +%168 = OpTypeFunction %2 %4 %7 +%179 = OpTypeFunction %2 %4 %4 %5 +%204 = OpTypeFunction %2 %5 +%15 = OpFunction %5 None %16 +%14 = OpFunctionParameter %4 +%13 = OpLabel +OpBranch %17 %17 = OpLabel -OpBranch %21 -%21 = OpLabel -%26 = OpULessThan %27 %18 %24 -OpSelectionMerge %31 None -OpBranchConditional %26 %32 %31 -%32 = OpLabel -%29 = OpAccessChain %23 %15 %28 %18 -%33 = OpLoad %6 %29 -OpBranch %31 +%22 = OpULessThan %23 %14 %20 +OpSelectionMerge %27 None +OpBranchConditional %22 %28 %27 +%28 = OpLabel +%25 = OpAccessChain %19 %11 %24 %14 +%29 = OpLoad %5 %25 +OpBranch %27 +%27 = OpLabel +%30 = OpPhi %5 %26 %17 %29 %28 +OpReturnValue %30 +OpFunctionEnd +%33 = OpFunction %5 None %16 +%32 = OpFunctionParameter %4 %31 = OpLabel -%34 = OpPhi %6 %30 %21 %33 %32 -OpReturnValue %34 +OpBranch %34 +%34 = OpLabel +%36 = OpArrayLength %21 %11 3 +%37 = OpULessThan %23 %32 %36 +OpSelectionMerge %41 None +OpBranchConditional %37 %42 %41 +%42 = OpLabel +%39 = OpAccessChain %19 %11 %38 %32 +%43 = OpLoad %5 %39 +OpBranch %41 +%41 = OpLabel +%44 = OpPhi %5 %40 %34 %43 %42 +OpReturnValue %44 OpFunctionEnd -%37 = OpFunction %6 None %20 -%36 = OpFunctionParameter %4 -%35 = OpLabel -OpBranch %38 -%38 = OpLabel -%40 = OpArrayLength %25 %15 3 -%41 = OpULessThan %27 %36 %40 -OpSelectionMerge %45 None -OpBranchConditional %41 %46 %45 -%46 = OpLabel -%43 = OpAccessChain %23 %15 %42 %36 -%47 = OpLoad %6 %43 -OpBranch %45 +%47 = OpFunction %5 None %16 +%46 = OpFunctionParameter %4 %45 = OpLabel -%48 = OpPhi %6 %44 %38 %47 %46 -OpReturnValue %48 +OpBranch %48 +%48 = OpLabel +%52 = OpULessThan %23 %46 %51 +OpSelectionMerge %56 None +OpBranchConditional %52 %57 %56 +%57 = OpLabel +%54 = OpAccessChain %50 %11 %53 %46 +%58 = OpLoad %5 %54 +OpBranch %56 +%56 = OpLabel +%59 = OpPhi %5 %55 %48 %58 %57 +OpReturnValue %59 OpFunctionEnd -%51 = OpFunction %6 None %20 -%50 = OpFunctionParameter %4 -%49 = OpLabel -OpBranch %52 -%52 = OpLabel -%56 = OpULessThan %27 %50 %55 -OpSelectionMerge %60 None -OpBranchConditional %56 %61 %60 -%61 = OpLabel -%58 = OpAccessChain %54 %15 %57 %50 -%62 = OpLoad %6 %58 -OpBranch %60 +%63 = OpFunction %5 None %64 +%61 = OpFunctionParameter %7 +%62 = OpFunctionParameter %4 %60 = OpLabel -%63 = OpPhi %6 %59 %52 %62 %61 -OpReturnValue %63 -OpFunctionEnd -%67 = OpFunction %6 None %68 -%65 = OpFunctionParameter %11 -%66 = OpFunctionParameter %4 -%64 = OpLabel -OpBranch %69 +OpBranch %65 +%65 = OpLabel +%66 = OpULessThan %23 %62 %51 +OpSelectionMerge %68 None +OpBranchConditional %66 %69 %68 %69 = OpLabel -%70 = OpULessThan %27 %66 %55 -OpSelectionMerge %72 None -OpBranchConditional %70 %73 %72 -%73 = OpLabel -%74 = OpVectorExtractDynamic %6 %65 %66 -OpBranch %72 +%70 = OpVectorExtractDynamic %5 %61 %62 +OpBranch %68 +%68 = OpLabel +%71 = OpPhi %5 %67 %65 %70 %69 +OpReturnValue %71 +OpFunctionEnd +%74 = OpFunction %7 None %75 +%73 = OpFunctionParameter %4 %72 = OpLabel -%75 = OpPhi %6 %71 %69 %74 %73 -OpReturnValue %75 -OpFunctionEnd -%78 = OpFunction %11 None %79 -%77 = OpFunctionParameter %4 +OpBranch %76 %76 = OpLabel -OpBranch %80 -%80 = OpLabel -%83 = OpULessThan %27 %77 %42 -OpSelectionMerge %87 None -OpBranchConditional %83 %88 %87 -%88 = OpLabel -%85 = OpAccessChain %82 %15 %84 %77 -%89 = OpLoad %11 %85 -OpBranch %87 +%79 = OpULessThan %23 %73 %38 +OpSelectionMerge %83 None +OpBranchConditional %79 %84 %83 +%84 = OpLabel +%81 = OpAccessChain %78 %11 %80 %73 +%85 = OpLoad %7 %81 +OpBranch %83 +%83 = OpLabel +%86 = OpPhi %7 %82 %76 %85 %84 +OpReturnValue %86 +OpFunctionEnd +%90 = OpFunction %5 None %91 +%88 = OpFunctionParameter %4 +%89 = OpFunctionParameter %4 %87 = OpLabel -%90 = OpPhi %11 %86 %80 %89 %88 -OpReturnValue %90 +OpBranch %92 +%92 = OpLabel +%93 = OpULessThan %23 %89 %51 +%94 = OpULessThan %23 %88 %38 +%95 = OpLogicalAnd %23 %93 %94 +OpSelectionMerge %98 None +OpBranchConditional %95 %99 %98 +%99 = OpLabel +%96 = OpAccessChain %50 %11 %80 %88 %89 +%100 = OpLoad %5 %96 +OpBranch %98 +%98 = OpLabel +%101 = OpPhi %5 %97 %92 %100 %99 +OpReturnValue %101 OpFunctionEnd -%94 = OpFunction %6 None %95 -%92 = OpFunctionParameter %4 -%93 = OpFunctionParameter %4 -%91 = OpLabel -OpBranch %96 -%96 = OpLabel -%97 = OpULessThan %27 %93 %55 -%98 = OpULessThan %27 %92 %42 -%99 = OpLogicalAnd %27 %97 %98 -OpSelectionMerge %102 None -OpBranchConditional %99 %103 %102 -%103 = OpLabel -%100 = OpAccessChain %54 %15 %84 %92 %93 -%104 = OpLoad %6 %100 -OpBranch %102 +%104 = OpFunction %5 None %16 +%103 = OpFunctionParameter %4 %102 = OpLabel -%105 = OpPhi %6 %101 %96 %104 %103 -OpReturnValue %105 -OpFunctionEnd -%108 = OpFunction %6 None %20 -%107 = OpFunctionParameter %4 +OpBranch %106 %106 = OpLabel -OpBranch %109 -%109 = OpLabel -%110 = OpConvertSToF %6 %107 -%111 = OpFDiv %6 %110 %5 -%112 = OpExtInst %6 %1 Sin %111 -%113 = OpFMul %6 %112 %5 -%114 = OpConvertFToS %4 %113 -%115 = OpULessThan %27 %114 %24 -OpSelectionMerge %118 None -OpBranchConditional %115 %119 %118 -%119 = OpLabel -%116 = OpAccessChain %23 %15 %28 %114 -%120 = OpLoad %6 %116 -OpBranch %118 -%118 = OpLabel -%121 = OpPhi %6 %117 %109 %120 %119 -OpReturnValue %121 +%107 = OpConvertSToF %5 %103 +%108 = OpFDiv %5 %107 %105 +%109 = OpExtInst %5 %1 Sin %108 +%110 = OpFMul %5 %109 %105 +%111 = OpConvertFToS %4 %110 +%112 = OpULessThan %23 %111 %20 +OpSelectionMerge %115 None +OpBranchConditional %112 %116 %115 +%116 = OpLabel +%113 = OpAccessChain %19 %11 %24 %111 +%117 = OpLoad %5 %113 +OpBranch %115 +%115 = OpLabel +%118 = OpPhi %5 %114 %106 %117 %116 +OpReturnValue %118 OpFunctionEnd -%123 = OpFunction %6 None %124 -%122 = OpLabel +%120 = OpFunction %5 None %121 +%119 = OpLabel OpBranch %125 %125 = OpLabel -%127 = OpAccessChain %23 %15 %28 %126 -%128 = OpLoad %6 %127 -%129 = OpAccessChain %54 %15 %57 %42 -%130 = OpLoad %6 %129 -%131 = OpFAdd %6 %128 %130 -%132 = OpAccessChain %54 %15 %84 %84 %42 -%133 = OpLoad %6 %132 -%134 = OpFAdd %6 %131 %133 +%127 = OpAccessChain %19 %11 %24 %126 +%128 = OpLoad %5 %127 +%129 = OpAccessChain %50 %11 %53 %38 +%130 = OpLoad %5 %129 +%131 = OpFAdd %5 %128 %130 +%132 = OpAccessChain %50 %11 %80 %80 %38 +%133 = OpLoad %5 %132 +%134 = OpFAdd %5 %131 %133 OpReturnValue %134 OpFunctionEnd %138 = OpFunction %2 None %139 %136 = OpFunctionParameter %4 -%137 = OpFunctionParameter %6 +%137 = OpFunctionParameter %5 %135 = OpLabel OpBranch %140 %140 = OpLabel -%141 = OpULessThan %27 %136 %24 +%141 = OpULessThan %23 %136 %20 OpSelectionMerge %143 None OpBranchConditional %141 %144 %143 %144 = OpLabel -%142 = OpAccessChain %23 %15 %28 %136 +%142 = OpAccessChain %19 %11 %24 %136 OpStore %142 %137 OpBranch %143 %143 = OpLabel @@ -218,16 +218,16 @@ OpReturn OpFunctionEnd %148 = OpFunction %2 None %139 %146 = OpFunctionParameter %4 -%147 = OpFunctionParameter %6 +%147 = OpFunctionParameter %5 %145 = OpLabel OpBranch %149 %149 = OpLabel -%150 = OpArrayLength %25 %15 3 -%151 = OpULessThan %27 %146 %150 +%150 = OpArrayLength %21 %11 3 +%151 = OpULessThan %23 %146 %150 OpSelectionMerge %153 None OpBranchConditional %151 %154 %153 %154 = OpLabel -%152 = OpAccessChain %23 %15 %42 %146 +%152 = OpAccessChain %19 %11 %38 %146 OpStore %152 %147 OpBranch %153 %153 = OpLabel @@ -235,15 +235,15 @@ OpReturn OpFunctionEnd %158 = OpFunction %2 None %139 %156 = OpFunctionParameter %4 -%157 = OpFunctionParameter %6 +%157 = OpFunctionParameter %5 %155 = OpLabel OpBranch %159 %159 = OpLabel -%160 = OpULessThan %27 %156 %55 +%160 = OpULessThan %23 %156 %51 OpSelectionMerge %162 None OpBranchConditional %160 %163 %162 %163 = OpLabel -%161 = OpAccessChain %54 %15 %57 %156 +%161 = OpAccessChain %50 %11 %53 %156 OpStore %161 %157 OpBranch %162 %162 = OpLabel @@ -251,15 +251,15 @@ OpReturn OpFunctionEnd %167 = OpFunction %2 None %168 %165 = OpFunctionParameter %4 -%166 = OpFunctionParameter %11 +%166 = OpFunctionParameter %7 %164 = OpLabel OpBranch %169 %169 = OpLabel -%170 = OpULessThan %27 %165 %42 +%170 = OpULessThan %23 %165 %38 OpSelectionMerge %172 None OpBranchConditional %170 %173 %172 %173 = OpLabel -%171 = OpAccessChain %82 %15 %84 %165 +%171 = OpAccessChain %78 %11 %80 %165 OpStore %171 %166 OpBranch %172 %172 = OpLabel @@ -268,17 +268,17 @@ OpFunctionEnd %178 = OpFunction %2 None %179 %175 = OpFunctionParameter %4 %176 = OpFunctionParameter %4 -%177 = OpFunctionParameter %6 +%177 = OpFunctionParameter %5 %174 = OpLabel OpBranch %180 %180 = OpLabel -%181 = OpULessThan %27 %176 %55 -%182 = OpULessThan %27 %175 %42 -%183 = OpLogicalAnd %27 %181 %182 +%181 = OpULessThan %23 %176 %51 +%182 = OpULessThan %23 %175 %38 +%183 = OpLogicalAnd %23 %181 %182 OpSelectionMerge %185 None OpBranchConditional %183 %186 %185 %186 = OpLabel -%184 = OpAccessChain %54 %15 %84 %175 %176 +%184 = OpAccessChain %50 %11 %80 %175 %176 OpStore %184 %177 OpBranch %185 %185 = OpLabel @@ -286,35 +286,35 @@ OpReturn OpFunctionEnd %190 = OpFunction %2 None %139 %188 = OpFunctionParameter %4 -%189 = OpFunctionParameter %6 +%189 = OpFunctionParameter %5 %187 = OpLabel OpBranch %191 %191 = OpLabel -%192 = OpConvertSToF %6 %188 -%193 = OpFDiv %6 %192 %5 -%194 = OpExtInst %6 %1 Sin %193 -%195 = OpFMul %6 %194 %5 +%192 = OpConvertSToF %5 %188 +%193 = OpFDiv %5 %192 %105 +%194 = OpExtInst %5 %1 Sin %193 +%195 = OpFMul %5 %194 %105 %196 = OpConvertFToS %4 %195 -%197 = OpULessThan %27 %196 %24 +%197 = OpULessThan %23 %196 %20 OpSelectionMerge %199 None OpBranchConditional %197 %200 %199 %200 = OpLabel -%198 = OpAccessChain %23 %15 %28 %196 +%198 = OpAccessChain %19 %11 %24 %196 OpStore %198 %189 OpBranch %199 %199 = OpLabel OpReturn OpFunctionEnd %203 = OpFunction %2 None %204 -%202 = OpFunctionParameter %6 +%202 = OpFunctionParameter %5 %201 = OpLabel OpBranch %205 %205 = OpLabel -%206 = OpAccessChain %23 %15 %28 %126 +%206 = OpAccessChain %19 %11 %24 %126 OpStore %206 %202 -%207 = OpAccessChain %54 %15 %57 %42 +%207 = OpAccessChain %50 %11 %53 %38 OpStore %207 %202 -%208 = OpAccessChain %54 %15 %84 %84 %42 +%208 = OpAccessChain %50 %11 %80 %80 %38 OpStore %208 %202 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/break-if.spvasm b/tests/out/spv/break-if.spvasm index 138fb0b61..081cd21cc 100644 --- a/tests/out/spv/break-if.spvasm +++ b/tests/out/spv/break-if.spvasm @@ -8,17 +8,17 @@ OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %48 "main" OpExecutionMode %48 LocalSize 1 1 1 %2 = OpTypeVoid -%4 = OpTypeBool -%3 = OpConstantTrue %4 -%7 = OpTypeFunction %2 -%14 = OpTypePointer Function %4 -%15 = OpConstantNull %4 -%17 = OpConstantNull %4 -%21 = OpTypeFunction %2 %4 -%32 = OpConstantNull %4 -%34 = OpConstantNull %4 -%6 = OpFunction %2 None %7 -%5 = OpLabel +%3 = OpTypeBool +%6 = OpTypeFunction %2 +%7 = OpConstantTrue %3 +%14 = OpTypePointer Function %3 +%15 = OpConstantNull %3 +%17 = OpConstantNull %3 +%21 = OpTypeFunction %2 %3 +%32 = OpConstantNull %3 +%34 = OpConstantNull %3 +%5 = OpFunction %2 None %6 +%4 = OpLabel OpBranch %8 %8 = OpLabel OpBranch %9 @@ -28,12 +28,12 @@ OpBranch %11 %11 = OpLabel OpBranch %12 %12 = OpLabel -OpBranchConditional %3 %10 %9 +OpBranchConditional %7 %10 %9 %10 = OpLabel OpReturn OpFunctionEnd %20 = OpFunction %2 None %21 -%19 = OpFunctionParameter %4 +%19 = OpFunctionParameter %3 %18 = OpLabel %13 = OpVariable %14 Function %15 %16 = OpVariable %14 Function %17 @@ -47,17 +47,17 @@ OpBranch %25 OpBranch %26 %26 = OpLabel OpStore %13 %19 -%27 = OpLoad %4 %13 -%28 = OpLogicalNotEqual %4 %19 %27 +%27 = OpLoad %3 %13 +%28 = OpLogicalNotEqual %3 %19 %27 OpStore %16 %28 -%29 = OpLoad %4 %16 -%30 = OpLogicalEqual %4 %19 %29 +%29 = OpLoad %3 %16 +%30 = OpLogicalEqual %3 %19 %29 OpBranchConditional %30 %24 %23 %24 = OpLabel OpReturn OpFunctionEnd %37 = OpFunction %2 None %21 -%36 = OpFunctionParameter %4 +%36 = OpFunctionParameter %3 %35 = OpLabel %31 = OpVariable %14 Function %32 %33 = OpVariable %14 Function %34 @@ -69,18 +69,18 @@ OpLoopMerge %40 %42 None OpBranch %41 %41 = OpLabel OpStore %31 %36 -%43 = OpLoad %4 %31 -%44 = OpLogicalNotEqual %4 %36 %43 +%43 = OpLoad %3 %31 +%44 = OpLogicalNotEqual %3 %36 %43 OpStore %33 %44 OpBranch %42 %42 = OpLabel -%45 = OpLoad %4 %33 -%46 = OpLogicalEqual %4 %36 %45 +%45 = OpLoad %3 %33 +%46 = OpLogicalEqual %3 %36 %45 OpBranchConditional %46 %40 %39 %40 = OpLabel OpReturn OpFunctionEnd -%48 = OpFunction %2 None %7 +%48 = OpFunction %2 None %6 %47 = OpLabel OpBranch %49 %49 = OpLabel diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index 7be8c912c..a08b44670 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -9,58 +9,58 @@ OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %52 "main" %49 OpExecutionMode %52 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %9 0 "data" -OpName %9 "PrimeIndices" -OpName %11 "v_indices" -OpName %13 "n" -OpName %16 "i" -OpName %19 "n_base" -OpName %20 "collatz_iterations" +OpMemberName %5 0 "data" +OpName %5 "PrimeIndices" +OpName %7 "v_indices" +OpName %9 "n" +OpName %12 "i" +OpName %15 "n_base" +OpName %16 "collatz_iterations" OpName %49 "global_id" OpName %52 "main" -OpDecorate %8 ArrayStride 4 -OpMemberDecorate %9 0 Offset 0 -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 0 -OpDecorate %9 Block +OpDecorate %4 ArrayStride 4 +OpMemberDecorate %5 0 Offset 0 +OpDecorate %7 DescriptorSet 0 +OpDecorate %7 Binding 0 +OpDecorate %5 Block OpDecorate %49 BuiltIn GlobalInvocationId %2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpConstant %4 0 -%5 = OpConstant %4 1 -%6 = OpConstant %4 2 -%7 = OpConstant %4 3 -%8 = OpTypeRuntimeArray %4 -%9 = OpTypeStruct %8 -%10 = OpTypeVector %4 3 -%12 = OpTypePointer StorageBuffer %9 -%11 = OpVariable %12 StorageBuffer -%14 = OpTypePointer Function %4 -%15 = OpConstantNull %4 -%17 = OpConstantNull %4 -%21 = OpTypeFunction %4 %4 +%3 = OpTypeInt 32 0 +%4 = OpTypeRuntimeArray %3 +%5 = OpTypeStruct %4 +%6 = OpTypeVector %3 3 +%8 = OpTypePointer StorageBuffer %5 +%7 = OpVariable %8 StorageBuffer +%10 = OpTypePointer Function %3 +%11 = OpConstantNull %3 +%13 = OpConstantNull %3 +%17 = OpTypeFunction %3 %3 +%18 = OpConstant %3 0 +%19 = OpConstant %3 1 +%20 = OpConstant %3 2 +%21 = OpConstant %3 3 %28 = OpTypeBool -%50 = OpTypePointer Input %10 +%50 = OpTypePointer Input %6 %49 = OpVariable %50 Input %53 = OpTypeFunction %2 -%55 = OpTypePointer StorageBuffer %8 -%57 = OpTypePointer StorageBuffer %4 -%20 = OpFunction %4 None %21 -%19 = OpFunctionParameter %4 -%18 = OpLabel -%13 = OpVariable %14 Function %15 -%16 = OpVariable %14 Function %17 +%55 = OpTypePointer StorageBuffer %4 +%57 = OpTypePointer StorageBuffer %3 +%16 = OpFunction %3 None %17 +%15 = OpFunctionParameter %3 +%14 = OpLabel +%9 = OpVariable %10 Function %11 +%12 = OpVariable %10 Function %13 OpBranch %22 %22 = OpLabel -OpStore %13 %19 -OpStore %16 %3 +OpStore %9 %15 +OpStore %12 %18 OpBranch %23 %23 = OpLabel OpLoopMerge %24 %26 None OpBranch %25 %25 = OpLabel -%27 = OpLoad %4 %13 -%29 = OpUGreaterThan %28 %27 %5 +%27 = OpLoad %3 %9 +%29 = OpUGreaterThan %28 %27 %19 OpSelectionMerge %30 None OpBranchConditional %29 %30 %31 %31 = OpLabel @@ -68,46 +68,46 @@ OpBranch %24 %30 = OpLabel OpBranch %32 %32 = OpLabel -%34 = OpLoad %4 %13 -%35 = OpUMod %4 %34 %6 -%36 = OpIEqual %28 %35 %3 +%34 = OpLoad %3 %9 +%35 = OpUMod %3 %34 %20 +%36 = OpIEqual %28 %35 %18 OpSelectionMerge %37 None OpBranchConditional %36 %38 %39 %38 = OpLabel -%40 = OpLoad %4 %13 -%41 = OpUDiv %4 %40 %6 -OpStore %13 %41 +%40 = OpLoad %3 %9 +%41 = OpUDiv %3 %40 %20 +OpStore %9 %41 OpBranch %37 %39 = OpLabel -%42 = OpLoad %4 %13 -%43 = OpIMul %4 %7 %42 -%44 = OpIAdd %4 %43 %5 -OpStore %13 %44 +%42 = OpLoad %3 %9 +%43 = OpIMul %3 %21 %42 +%44 = OpIAdd %3 %43 %19 +OpStore %9 %44 OpBranch %37 %37 = OpLabel -%45 = OpLoad %4 %16 -%46 = OpIAdd %4 %45 %5 -OpStore %16 %46 +%45 = OpLoad %3 %12 +%46 = OpIAdd %3 %45 %19 +OpStore %12 %46 OpBranch %33 %33 = OpLabel OpBranch %26 %26 = OpLabel OpBranch %23 %24 = OpLabel -%47 = OpLoad %4 %16 +%47 = OpLoad %3 %12 OpReturnValue %47 OpFunctionEnd %52 = OpFunction %2 None %53 %48 = OpLabel -%51 = OpLoad %10 %49 +%51 = OpLoad %6 %49 OpBranch %54 %54 = OpLabel -%56 = OpCompositeExtract %4 %51 0 -%58 = OpCompositeExtract %4 %51 0 -%59 = OpAccessChain %57 %11 %3 %58 -%60 = OpLoad %4 %59 -%61 = OpFunctionCall %4 %20 %60 -%62 = OpAccessChain %57 %11 %3 %56 +%56 = OpCompositeExtract %3 %51 0 +%58 = OpCompositeExtract %3 %51 0 +%59 = OpAccessChain %57 %7 %18 %58 +%60 = OpLoad %3 %59 +%61 = OpFunctionCall %3 %16 %60 +%62 = OpAccessChain %57 %7 %18 %56 OpStore %62 %61 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index e1885e715..eb2f3b62e 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -5,133 +5,133 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %44 "main" %41 -OpExecutionMode %44 LocalSize 1 1 1 -OpDecorate %41 BuiltIn GlobalInvocationId +OpEntryPoint GLCompute %39 "main" %36 +OpExecutionMode %39 LocalSize 1 1 1 +OpDecorate %36 BuiltIn GlobalInvocationId %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 1 -%5 = OpConstant %4 0 -%6 = OpConstant %4 2 -%7 = OpConstant %4 3 -%8 = OpConstant %4 4 -%10 = OpTypeInt 32 0 -%9 = OpConstant %10 0 -%11 = OpTypeVector %10 3 -%15 = OpTypeFunction %2 %4 -%21 = OpTypeFunction %2 -%38 = OpTypePointer Function %4 -%39 = OpConstantNull %4 -%42 = OpTypePointer Input %11 -%41 = OpVariable %42 Input -%46 = OpConstant %10 2 -%47 = OpConstant %10 1 -%48 = OpConstant %10 72 -%49 = OpConstant %10 264 -%14 = OpFunction %2 None %15 -%13 = OpFunctionParameter %4 +%4 = OpTypeInt 32 0 +%3 = OpTypeVector %4 3 +%5 = OpTypeInt 32 1 +%9 = OpTypeFunction %2 %5 +%15 = OpTypeFunction %2 +%16 = OpConstant %5 0 +%33 = OpTypePointer Function %5 +%34 = OpConstantNull %5 +%37 = OpTypePointer Input %3 +%36 = OpVariable %37 Input +%40 = OpConstant %5 1 +%41 = OpConstant %5 2 +%42 = OpConstant %5 3 +%43 = OpConstant %5 4 +%44 = OpConstant %4 0 +%46 = OpConstant %4 2 +%47 = OpConstant %4 1 +%48 = OpConstant %4 72 +%49 = OpConstant %4 264 +%8 = OpFunction %2 None %9 +%7 = OpFunctionParameter %5 +%6 = OpLabel +OpBranch %10 +%10 = OpLabel +OpSelectionMerge %11 None +OpSwitch %7 %12 %12 = OpLabel -OpBranch %16 -%16 = OpLabel -OpSelectionMerge %17 None -OpSwitch %13 %18 -%18 = OpLabel +OpBranch %11 +%11 = OpLabel +OpReturn +OpFunctionEnd +%14 = OpFunction %2 None %15 +%13 = OpLabel OpBranch %17 %17 = OpLabel -OpReturn -OpFunctionEnd -%20 = OpFunction %2 None %21 +OpSelectionMerge %18 None +OpSwitch %16 %20 0 %19 %19 = OpLabel -OpBranch %22 -%22 = OpLabel -OpSelectionMerge %23 None -OpSwitch %5 %25 0 %24 -%24 = OpLabel -OpBranch %23 -%25 = OpLabel -OpBranch %23 -%23 = OpLabel +OpBranch %18 +%20 = OpLabel +OpBranch %18 +%18 = OpLabel OpReturn OpFunctionEnd -%28 = OpFunction %2 None %15 -%27 = OpFunctionParameter %4 -%26 = OpLabel +%23 = OpFunction %2 None %9 +%22 = OpFunctionParameter %5 +%21 = OpLabel +OpBranch %24 +%24 = OpLabel +OpBranch %25 +%25 = OpLabel +OpLoopMerge %26 %28 None +OpBranch %27 +%27 = OpLabel +OpSelectionMerge %29 None +OpSwitch %22 %31 1 %30 +%30 = OpLabel +OpBranch %28 +%31 = OpLabel OpBranch %29 %29 = OpLabel -OpBranch %30 -%30 = OpLabel -OpLoopMerge %31 %33 None -OpBranch %32 -%32 = OpLabel -OpSelectionMerge %34 None -OpSwitch %27 %36 1 %35 -%35 = OpLabel -OpBranch %33 -%36 = OpLabel -OpBranch %34 -%34 = OpLabel -OpBranch %33 -%33 = OpLabel -OpBranch %30 -%31 = OpLabel +OpBranch %28 +%28 = OpLabel +OpBranch %25 +%26 = OpLabel OpReturn OpFunctionEnd -%44 = OpFunction %2 None %21 -%40 = OpLabel -%37 = OpVariable %38 Function %39 -%43 = OpLoad %11 %41 +%39 = OpFunction %2 None %15 +%35 = OpLabel +%32 = OpVariable %33 Function %34 +%38 = OpLoad %3 %36 OpBranch %45 %45 = OpLabel OpControlBarrier %46 %47 %48 OpControlBarrier %46 %46 %49 OpSelectionMerge %50 None -OpSwitch %3 %51 +OpSwitch %40 %51 %51 = OpLabel -OpStore %37 %3 +OpStore %32 %40 OpBranch %50 %50 = OpLabel -%52 = OpLoad %4 %37 +%52 = OpLoad %5 %32 OpSelectionMerge %53 None OpSwitch %52 %58 1 %54 2 %55 3 %56 4 %56 5 %57 6 %58 %54 = OpLabel -OpStore %37 %5 +OpStore %32 %16 OpBranch %53 %55 = OpLabel -OpStore %37 %3 +OpStore %32 %40 OpBranch %53 %56 = OpLabel -OpStore %37 %6 +OpStore %32 %41 OpBranch %53 %57 = OpLabel -OpStore %37 %7 +OpStore %32 %42 OpBranch %53 %58 = OpLabel -OpStore %37 %8 +OpStore %32 %43 OpBranch %53 %53 = OpLabel OpSelectionMerge %59 None -OpSwitch %9 %61 0 %60 +OpSwitch %44 %61 0 %60 %60 = OpLabel OpBranch %59 %61 = OpLabel OpBranch %59 %59 = OpLabel -%62 = OpLoad %4 %37 +%62 = OpLoad %5 %32 OpSelectionMerge %63 None OpSwitch %62 %68 1 %64 2 %65 3 %66 4 %67 %64 = OpLabel -OpStore %37 %5 +OpStore %32 %16 OpBranch %63 %65 = OpLabel -OpStore %37 %3 +OpStore %32 %40 OpReturn %66 = OpLabel -OpStore %37 %6 +OpStore %32 %41 OpReturn %67 = OpLabel OpReturn %68 = OpLabel -OpStore %37 %7 +OpStore %32 %42 OpReturn %63 = OpLabel OpReturn diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index 0c4f7a1d7..16b9b750c 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -7,69 +7,69 @@ OpCapability Float64 OpCapability Geometry %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %25 "main" %17 %20 %23 -OpExecutionMode %25 OriginUpperLeft -OpMemberDecorate %8 0 Offset 0 -OpMemberDecorate %8 1 Offset 16 -OpMemberDecorate %10 0 Offset 0 -OpMemberDecorate %10 1 Offset 16 -OpDecorate %13 Block -OpMemberDecorate %13 0 Offset 0 -OpDecorate %17 Location 0 -OpDecorate %20 BuiltIn PrimitiveId -OpDecorate %20 Flat -OpDecorate %23 Location 0 +OpEntryPoint Fragment %24 "main" %16 %19 %22 +OpExecutionMode %24 OriginUpperLeft +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %6 1 Offset 16 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 16 +OpDecorate %12 Block +OpMemberDecorate %12 0 Offset 0 +OpDecorate %16 Location 0 +OpDecorate %19 BuiltIn PrimitiveId +OpDecorate %19 Flat +OpDecorate %22 Location 0 %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 1.0 -%5 = OpTypeInt 32 0 -%7 = OpTypeFloat 64 -%6 = OpTypeVector %7 2 -%8 = OpTypeStruct %5 %6 -%9 = OpTypeVector %4 4 -%10 = OpTypeStruct %9 %5 -%11 = OpTypeVector %4 3 -%13 = OpTypeStruct %8 -%14 = OpTypePointer PushConstant %13 -%12 = OpVariable %14 PushConstant -%18 = OpTypePointer Input %9 -%17 = OpVariable %18 Input -%21 = OpTypePointer Input %5 -%20 = OpVariable %21 Input -%24 = OpTypePointer Output %9 -%23 = OpVariable %24 Output -%26 = OpTypeFunction %2 -%27 = OpTypePointer PushConstant %8 -%28 = OpConstant %5 0 -%32 = OpTypePointer PushConstant %5 +%3 = OpTypeInt 32 0 +%5 = OpTypeFloat 64 +%4 = OpTypeVector %5 2 +%6 = OpTypeStruct %3 %4 +%8 = OpTypeFloat 32 +%7 = OpTypeVector %8 4 +%9 = OpTypeStruct %7 %3 +%10 = OpTypeVector %8 3 +%12 = OpTypeStruct %6 +%13 = OpTypePointer PushConstant %12 +%11 = OpVariable %13 PushConstant +%17 = OpTypePointer Input %7 +%16 = OpVariable %17 Input +%20 = OpTypePointer Input %3 +%19 = OpVariable %20 Input +%23 = OpTypePointer Output %7 +%22 = OpVariable %23 Output +%25 = OpTypeFunction %2 +%26 = OpTypePointer PushConstant %6 +%27 = OpConstant %3 0 +%29 = OpConstant %8 1.0 +%32 = OpTypePointer PushConstant %3 %35 = OpTypeBool -%25 = OpFunction %2 None %26 -%15 = OpLabel -%19 = OpLoad %9 %17 -%22 = OpLoad %5 %20 -%16 = OpCompositeConstruct %10 %19 %22 -%29 = OpAccessChain %27 %12 %28 +%24 = OpFunction %2 None %25 +%14 = OpLabel +%18 = OpLoad %7 %16 +%21 = OpLoad %3 %19 +%15 = OpCompositeConstruct %9 %18 %21 +%28 = OpAccessChain %26 %11 %27 OpBranch %30 %30 = OpLabel -%31 = OpCompositeExtract %5 %16 1 -%33 = OpAccessChain %32 %29 %28 -%34 = OpLoad %5 %33 +%31 = OpCompositeExtract %3 %15 1 +%33 = OpAccessChain %32 %28 %27 +%34 = OpLoad %3 %33 %36 = OpIEqual %35 %31 %34 OpSelectionMerge %37 None OpBranchConditional %36 %38 %39 %38 = OpLabel -%40 = OpCompositeExtract %9 %16 0 -OpStore %23 %40 +%40 = OpCompositeExtract %7 %15 0 +OpStore %22 %40 OpReturn %39 = OpLabel -%41 = OpCompositeConstruct %11 %3 %3 %3 -%42 = OpCompositeExtract %9 %16 0 -%43 = OpVectorShuffle %11 %42 %42 0 1 2 -%44 = OpFSub %11 %41 %43 -%45 = OpCompositeExtract %9 %16 0 -%46 = OpCompositeExtract %4 %45 3 -%47 = OpCompositeConstruct %9 %44 %46 -OpStore %23 %47 +%41 = OpCompositeConstruct %10 %29 %29 %29 +%42 = OpCompositeExtract %7 %15 0 +%43 = OpVectorShuffle %10 %42 %42 0 1 2 +%44 = OpFSub %10 %41 %43 +%45 = OpCompositeExtract %7 %15 0 +%46 = OpCompositeExtract %8 %45 3 +%47 = OpCompositeConstruct %7 %44 %46 +OpStore %22 %47 OpReturn %37 = OpLabel OpReturn diff --git a/tests/out/spv/fragment-output.spvasm b/tests/out/spv/fragment-output.spvasm index aafc8c2d1..0a6541799 100644 --- a/tests/out/spv/fragment-output.spvasm +++ b/tests/out/spv/fragment-output.spvasm @@ -5,28 +5,28 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %36 "main_vec4vec3" %24 %26 %28 %30 %32 %34 +OpEntryPoint Fragment %33 "main_vec4vec3" %21 %23 %25 %27 %29 %31 OpEntryPoint Fragment %85 "main_vec2scalar" %73 %75 %77 %79 %81 %83 -OpExecutionMode %36 OriginUpperLeft +OpExecutionMode %33 OriginUpperLeft OpExecutionMode %85 OriginUpperLeft -OpMemberDecorate %15 0 Offset 0 -OpMemberDecorate %15 1 Offset 16 -OpMemberDecorate %15 2 Offset 32 -OpMemberDecorate %15 3 Offset 48 -OpMemberDecorate %15 4 Offset 64 -OpMemberDecorate %15 5 Offset 80 -OpMemberDecorate %19 0 Offset 0 -OpMemberDecorate %19 1 Offset 8 -OpMemberDecorate %19 2 Offset 16 -OpMemberDecorate %19 3 Offset 24 -OpMemberDecorate %19 4 Offset 28 -OpMemberDecorate %19 5 Offset 32 -OpDecorate %24 Location 0 -OpDecorate %26 Location 1 -OpDecorate %28 Location 2 -OpDecorate %30 Location 3 -OpDecorate %32 Location 4 -OpDecorate %34 Location 5 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 16 +OpMemberDecorate %12 2 Offset 32 +OpMemberDecorate %12 3 Offset 48 +OpMemberDecorate %12 4 Offset 64 +OpMemberDecorate %12 5 Offset 80 +OpMemberDecorate %16 0 Offset 0 +OpMemberDecorate %16 1 Offset 8 +OpMemberDecorate %16 2 Offset 16 +OpMemberDecorate %16 3 Offset 24 +OpMemberDecorate %16 4 Offset 28 +OpMemberDecorate %16 5 Offset 32 +OpDecorate %21 Location 0 +OpDecorate %23 Location 1 +OpDecorate %25 Location 2 +OpDecorate %27 Location 3 +OpDecorate %29 Location 4 +OpDecorate %31 Location 5 OpDecorate %73 Location 0 OpDecorate %75 Location 1 OpDecorate %77 Location 2 @@ -35,55 +35,55 @@ OpDecorate %81 Location 4 OpDecorate %83 Location 5 %2 = OpTypeVoid %4 = OpTypeFloat 32 -%3 = OpConstant %4 0.0 +%3 = OpTypeVector %4 4 %6 = OpTypeInt 32 1 -%5 = OpConstant %6 0 +%5 = OpTypeVector %6 4 %8 = OpTypeInt 32 0 -%7 = OpConstant %8 0 -%9 = OpTypeVector %4 4 -%10 = OpTypeVector %6 4 -%11 = OpTypeVector %8 4 -%12 = OpTypeVector %4 3 -%13 = OpTypeVector %6 3 -%14 = OpTypeVector %8 3 -%15 = OpTypeStruct %9 %10 %11 %12 %13 %14 -%16 = OpTypeVector %4 2 -%17 = OpTypeVector %6 2 -%18 = OpTypeVector %8 2 -%19 = OpTypeStruct %16 %17 %18 %4 %6 %8 -%21 = OpTypePointer Function %15 -%22 = OpConstantNull %15 -%25 = OpTypePointer Output %9 -%24 = OpVariable %25 Output -%27 = OpTypePointer Output %10 -%26 = OpVariable %27 Output -%29 = OpTypePointer Output %11 -%28 = OpVariable %29 Output -%31 = OpTypePointer Output %12 -%30 = OpVariable %31 Output -%33 = OpTypePointer Output %13 -%32 = OpVariable %33 Output -%35 = OpTypePointer Output %14 -%34 = OpVariable %35 Output -%37 = OpTypeFunction %2 -%39 = OpTypePointer Function %9 -%42 = OpTypePointer Function %10 +%7 = OpTypeVector %8 4 +%9 = OpTypeVector %4 3 +%10 = OpTypeVector %6 3 +%11 = OpTypeVector %8 3 +%12 = OpTypeStruct %3 %5 %7 %9 %10 %11 +%13 = OpTypeVector %4 2 +%14 = OpTypeVector %6 2 +%15 = OpTypeVector %8 2 +%16 = OpTypeStruct %13 %14 %15 %4 %6 %8 +%18 = OpTypePointer Function %12 +%19 = OpConstantNull %12 +%22 = OpTypePointer Output %3 +%21 = OpVariable %22 Output +%24 = OpTypePointer Output %5 +%23 = OpVariable %24 Output +%26 = OpTypePointer Output %7 +%25 = OpVariable %26 Output +%28 = OpTypePointer Output %9 +%27 = OpVariable %28 Output +%30 = OpTypePointer Output %10 +%29 = OpVariable %30 Output +%32 = OpTypePointer Output %11 +%31 = OpVariable %32 Output +%34 = OpTypeFunction %2 +%35 = OpConstant %4 0.0 +%36 = OpConstant %6 0 +%37 = OpConstant %8 0 +%39 = OpTypePointer Function %3 +%42 = OpTypePointer Function %5 %44 = OpConstant %8 1 -%46 = OpTypePointer Function %11 +%46 = OpTypePointer Function %7 %48 = OpConstant %8 2 -%50 = OpTypePointer Function %12 +%50 = OpTypePointer Function %9 %52 = OpConstant %8 3 -%54 = OpTypePointer Function %13 +%54 = OpTypePointer Function %10 %56 = OpConstant %8 4 -%58 = OpTypePointer Function %14 +%58 = OpTypePointer Function %11 %60 = OpConstant %8 5 -%70 = OpTypePointer Function %19 -%71 = OpConstantNull %19 -%74 = OpTypePointer Output %16 +%70 = OpTypePointer Function %16 +%71 = OpConstantNull %16 +%74 = OpTypePointer Output %13 %73 = OpVariable %74 Output -%76 = OpTypePointer Output %17 +%76 = OpTypePointer Output %14 %75 = OpVariable %76 Output -%78 = OpTypePointer Output %18 +%78 = OpTypePointer Output %15 %77 = OpVariable %78 Output %80 = OpTypePointer Output %4 %79 = OpVariable %80 Output @@ -91,76 +91,76 @@ OpDecorate %83 Location 5 %81 = OpVariable %82 Output %84 = OpTypePointer Output %8 %83 = OpVariable %84 Output -%87 = OpTypePointer Function %16 -%90 = OpTypePointer Function %17 -%93 = OpTypePointer Function %18 +%87 = OpTypePointer Function %13 +%90 = OpTypePointer Function %14 +%93 = OpTypePointer Function %15 %96 = OpTypePointer Function %4 %98 = OpTypePointer Function %6 %100 = OpTypePointer Function %8 -%36 = OpFunction %2 None %37 -%23 = OpLabel -%20 = OpVariable %21 Function %22 +%33 = OpFunction %2 None %34 +%20 = OpLabel +%17 = OpVariable %18 Function %19 OpBranch %38 %38 = OpLabel -%40 = OpCompositeConstruct %9 %3 %3 %3 %3 -%41 = OpAccessChain %39 %20 %7 +%40 = OpCompositeConstruct %3 %35 %35 %35 %35 +%41 = OpAccessChain %39 %17 %37 OpStore %41 %40 -%43 = OpCompositeConstruct %10 %5 %5 %5 %5 -%45 = OpAccessChain %42 %20 %44 +%43 = OpCompositeConstruct %5 %36 %36 %36 %36 +%45 = OpAccessChain %42 %17 %44 OpStore %45 %43 -%47 = OpCompositeConstruct %11 %7 %7 %7 %7 -%49 = OpAccessChain %46 %20 %48 +%47 = OpCompositeConstruct %7 %37 %37 %37 %37 +%49 = OpAccessChain %46 %17 %48 OpStore %49 %47 -%51 = OpCompositeConstruct %12 %3 %3 %3 -%53 = OpAccessChain %50 %20 %52 +%51 = OpCompositeConstruct %9 %35 %35 %35 +%53 = OpAccessChain %50 %17 %52 OpStore %53 %51 -%55 = OpCompositeConstruct %13 %5 %5 %5 -%57 = OpAccessChain %54 %20 %56 +%55 = OpCompositeConstruct %10 %36 %36 %36 +%57 = OpAccessChain %54 %17 %56 OpStore %57 %55 -%59 = OpCompositeConstruct %14 %7 %7 %7 -%61 = OpAccessChain %58 %20 %60 +%59 = OpCompositeConstruct %11 %37 %37 %37 +%61 = OpAccessChain %58 %17 %60 OpStore %61 %59 -%62 = OpLoad %15 %20 -%63 = OpCompositeExtract %9 %62 0 -OpStore %24 %63 -%64 = OpCompositeExtract %10 %62 1 -OpStore %26 %64 -%65 = OpCompositeExtract %11 %62 2 -OpStore %28 %65 -%66 = OpCompositeExtract %12 %62 3 -OpStore %30 %66 -%67 = OpCompositeExtract %13 %62 4 -OpStore %32 %67 -%68 = OpCompositeExtract %14 %62 5 -OpStore %34 %68 +%62 = OpLoad %12 %17 +%63 = OpCompositeExtract %3 %62 0 +OpStore %21 %63 +%64 = OpCompositeExtract %5 %62 1 +OpStore %23 %64 +%65 = OpCompositeExtract %7 %62 2 +OpStore %25 %65 +%66 = OpCompositeExtract %9 %62 3 +OpStore %27 %66 +%67 = OpCompositeExtract %10 %62 4 +OpStore %29 %67 +%68 = OpCompositeExtract %11 %62 5 +OpStore %31 %68 OpReturn OpFunctionEnd -%85 = OpFunction %2 None %37 +%85 = OpFunction %2 None %34 %72 = OpLabel %69 = OpVariable %70 Function %71 OpBranch %86 %86 = OpLabel -%88 = OpCompositeConstruct %16 %3 %3 -%89 = OpAccessChain %87 %69 %7 +%88 = OpCompositeConstruct %13 %35 %35 +%89 = OpAccessChain %87 %69 %37 OpStore %89 %88 -%91 = OpCompositeConstruct %17 %5 %5 +%91 = OpCompositeConstruct %14 %36 %36 %92 = OpAccessChain %90 %69 %44 OpStore %92 %91 -%94 = OpCompositeConstruct %18 %7 %7 +%94 = OpCompositeConstruct %15 %37 %37 %95 = OpAccessChain %93 %69 %48 OpStore %95 %94 %97 = OpAccessChain %96 %69 %52 -OpStore %97 %3 +OpStore %97 %35 %99 = OpAccessChain %98 %69 %56 -OpStore %99 %5 +OpStore %99 %36 %101 = OpAccessChain %100 %69 %60 -OpStore %101 %7 -%102 = OpLoad %19 %69 -%103 = OpCompositeExtract %16 %102 0 +OpStore %101 %37 +%102 = OpLoad %16 %69 +%103 = OpCompositeExtract %13 %102 0 OpStore %73 %103 -%104 = OpCompositeExtract %17 %102 1 +%104 = OpCompositeExtract %14 %102 1 OpStore %75 %104 -%105 = OpCompositeExtract %18 %102 2 +%105 = OpCompositeExtract %15 %102 2 OpStore %77 %105 %106 = OpCompositeExtract %4 %102 3 OpStore %79 %106 diff --git a/tests/out/spv/functions.spvasm b/tests/out/spv/functions.spvasm index ef3a2cd23..c3fd23891 100644 --- a/tests/out/spv/functions.spvasm +++ b/tests/out/spv/functions.spvasm @@ -9,87 +9,87 @@ OpEntryPoint GLCompute %74 "main" OpExecutionMode %74 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 -%3 = OpConstant %4 2.0 -%5 = OpConstant %4 0.5 -%7 = OpTypeInt 32 1 -%6 = OpConstant %7 1 -%9 = OpTypeInt 32 0 -%8 = OpConstant %9 1 -%10 = OpConstant %7 4 -%11 = OpConstant %7 2 -%12 = OpTypeVector %4 2 -%13 = OpTypeVector %7 2 -%14 = OpTypeVector %9 3 -%15 = OpTypeVector %7 4 -%18 = OpTypeFunction %12 -%26 = OpTypeFunction %7 -%31 = OpConstantNull %7 -%42 = OpConstantNull %9 -%57 = OpConstantNull %7 +%3 = OpTypeVector %4 2 +%5 = OpTypeInt 32 1 +%6 = OpTypeVector %5 2 +%8 = OpTypeInt 32 0 +%7 = OpTypeVector %8 3 +%9 = OpTypeVector %5 4 +%12 = OpTypeFunction %3 +%13 = OpConstant %4 2.0 +%14 = OpConstant %4 0.5 +%22 = OpTypeFunction %5 +%23 = OpConstant %5 1 +%24 = OpConstant %8 1 +%25 = OpConstant %5 4 +%26 = OpConstant %5 2 +%31 = OpConstantNull %5 +%42 = OpConstantNull %8 +%57 = OpConstantNull %5 %75 = OpTypeFunction %2 -%17 = OpFunction %12 None %18 -%16 = OpLabel -OpBranch %19 -%19 = OpLabel -%20 = OpCompositeConstruct %12 %3 %3 -%21 = OpCompositeConstruct %12 %5 %5 -%22 = OpCompositeConstruct %12 %5 %5 -%23 = OpExtInst %12 %1 Fma %20 %21 %22 -OpReturnValue %23 +%11 = OpFunction %3 None %12 +%10 = OpLabel +OpBranch %15 +%15 = OpLabel +%16 = OpCompositeConstruct %3 %13 %13 +%17 = OpCompositeConstruct %3 %14 %14 +%18 = OpCompositeConstruct %3 %14 %14 +%19 = OpExtInst %3 %1 Fma %16 %17 %18 +OpReturnValue %19 OpFunctionEnd -%25 = OpFunction %7 None %26 -%24 = OpLabel +%21 = OpFunction %5 None %22 +%20 = OpLabel OpBranch %27 %27 = OpLabel -%28 = OpCompositeConstruct %13 %6 %6 -%29 = OpCompositeConstruct %13 %6 %6 -%32 = OpCompositeExtract %7 %28 0 -%33 = OpCompositeExtract %7 %29 0 -%34 = OpIMul %7 %32 %33 -%35 = OpIAdd %7 %31 %34 -%36 = OpCompositeExtract %7 %28 1 -%37 = OpCompositeExtract %7 %29 1 -%38 = OpIMul %7 %36 %37 -%30 = OpIAdd %7 %35 %38 -%39 = OpCompositeConstruct %14 %8 %8 %8 -%40 = OpCompositeConstruct %14 %8 %8 %8 -%43 = OpCompositeExtract %9 %39 0 -%44 = OpCompositeExtract %9 %40 0 -%45 = OpIMul %9 %43 %44 -%46 = OpIAdd %9 %42 %45 -%47 = OpCompositeExtract %9 %39 1 -%48 = OpCompositeExtract %9 %40 1 -%49 = OpIMul %9 %47 %48 -%50 = OpIAdd %9 %46 %49 -%51 = OpCompositeExtract %9 %39 2 -%52 = OpCompositeExtract %9 %40 2 -%53 = OpIMul %9 %51 %52 -%41 = OpIAdd %9 %50 %53 -%54 = OpCompositeConstruct %15 %10 %10 %10 %10 -%55 = OpCompositeConstruct %15 %11 %11 %11 %11 -%58 = OpCompositeExtract %7 %54 0 -%59 = OpCompositeExtract %7 %55 0 -%60 = OpIMul %7 %58 %59 -%61 = OpIAdd %7 %57 %60 -%62 = OpCompositeExtract %7 %54 1 -%63 = OpCompositeExtract %7 %55 1 -%64 = OpIMul %7 %62 %63 -%65 = OpIAdd %7 %61 %64 -%66 = OpCompositeExtract %7 %54 2 -%67 = OpCompositeExtract %7 %55 2 -%68 = OpIMul %7 %66 %67 -%69 = OpIAdd %7 %65 %68 -%70 = OpCompositeExtract %7 %54 3 -%71 = OpCompositeExtract %7 %55 3 -%72 = OpIMul %7 %70 %71 -%56 = OpIAdd %7 %69 %72 +%28 = OpCompositeConstruct %6 %23 %23 +%29 = OpCompositeConstruct %6 %23 %23 +%32 = OpCompositeExtract %5 %28 0 +%33 = OpCompositeExtract %5 %29 0 +%34 = OpIMul %5 %32 %33 +%35 = OpIAdd %5 %31 %34 +%36 = OpCompositeExtract %5 %28 1 +%37 = OpCompositeExtract %5 %29 1 +%38 = OpIMul %5 %36 %37 +%30 = OpIAdd %5 %35 %38 +%39 = OpCompositeConstruct %7 %24 %24 %24 +%40 = OpCompositeConstruct %7 %24 %24 %24 +%43 = OpCompositeExtract %8 %39 0 +%44 = OpCompositeExtract %8 %40 0 +%45 = OpIMul %8 %43 %44 +%46 = OpIAdd %8 %42 %45 +%47 = OpCompositeExtract %8 %39 1 +%48 = OpCompositeExtract %8 %40 1 +%49 = OpIMul %8 %47 %48 +%50 = OpIAdd %8 %46 %49 +%51 = OpCompositeExtract %8 %39 2 +%52 = OpCompositeExtract %8 %40 2 +%53 = OpIMul %8 %51 %52 +%41 = OpIAdd %8 %50 %53 +%54 = OpCompositeConstruct %9 %25 %25 %25 %25 +%55 = OpCompositeConstruct %9 %26 %26 %26 %26 +%58 = OpCompositeExtract %5 %54 0 +%59 = OpCompositeExtract %5 %55 0 +%60 = OpIMul %5 %58 %59 +%61 = OpIAdd %5 %57 %60 +%62 = OpCompositeExtract %5 %54 1 +%63 = OpCompositeExtract %5 %55 1 +%64 = OpIMul %5 %62 %63 +%65 = OpIAdd %5 %61 %64 +%66 = OpCompositeExtract %5 %54 2 +%67 = OpCompositeExtract %5 %55 2 +%68 = OpIMul %5 %66 %67 +%69 = OpIAdd %5 %65 %68 +%70 = OpCompositeExtract %5 %54 3 +%71 = OpCompositeExtract %5 %55 3 +%72 = OpIMul %5 %70 %71 +%56 = OpIAdd %5 %69 %72 OpReturnValue %56 OpFunctionEnd %74 = OpFunction %2 None %75 %73 = OpLabel OpBranch %76 %76 = OpLabel -%77 = OpFunctionCall %12 %17 -%78 = OpFunctionCall %7 %25 +%77 = OpFunctionCall %3 %11 +%78 = OpFunctionCall %5 %21 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 5b801db0f..f2cc50b3d 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -6,48 +6,48 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %110 "main" %128 -OpExecutionMode %110 LocalSize 1 1 1 -OpDecorate %24 ArrayStride 4 -OpMemberDecorate %26 0 Offset 0 -OpMemberDecorate %26 1 Offset 12 -OpDecorate %28 ArrayStride 8 -OpDecorate %30 ArrayStride 16 -OpDecorate %33 ArrayStride 32 -OpDecorate %34 ArrayStride 64 -OpDecorate %36 ArrayStride 32 -OpDecorate %37 ArrayStride 64 -OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 1 -OpDecorate %44 Block -OpMemberDecorate %44 0 Offset 0 -OpDecorate %46 NonWritable -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 2 -OpDecorate %47 Block -OpMemberDecorate %47 0 Offset 0 -OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 3 -OpDecorate %50 Block -OpMemberDecorate %50 0 Offset 0 -OpDecorate %52 DescriptorSet 0 -OpDecorate %52 Binding 4 -OpDecorate %53 Block -OpMemberDecorate %53 0 Offset 0 -OpDecorate %55 DescriptorSet 0 -OpDecorate %55 Binding 5 -OpDecorate %56 Block -OpMemberDecorate %56 0 Offset 0 -OpMemberDecorate %56 0 ColMajor -OpMemberDecorate %56 0 MatrixStride 8 -OpDecorate %58 DescriptorSet 0 -OpDecorate %58 Binding 6 -OpDecorate %59 Block -OpMemberDecorate %59 0 Offset 0 -OpDecorate %61 DescriptorSet 0 -OpDecorate %61 Binding 7 -OpDecorate %62 Block -OpMemberDecorate %62 0 Offset 0 +OpEntryPoint GLCompute %102 "main" %128 +OpExecutionMode %102 LocalSize 1 1 1 +OpDecorate %11 ArrayStride 4 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 1 Offset 12 +OpDecorate %15 ArrayStride 8 +OpDecorate %17 ArrayStride 16 +OpDecorate %20 ArrayStride 32 +OpDecorate %21 ArrayStride 64 +OpDecorate %23 ArrayStride 32 +OpDecorate %24 ArrayStride 64 +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 1 +OpDecorate %31 Block +OpMemberDecorate %31 0 Offset 0 +OpDecorate %33 NonWritable +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 2 +OpDecorate %34 Block +OpMemberDecorate %34 0 Offset 0 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 3 +OpDecorate %37 Block +OpMemberDecorate %37 0 Offset 0 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 4 +OpDecorate %40 Block +OpMemberDecorate %40 0 Offset 0 +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 5 +OpDecorate %43 Block +OpMemberDecorate %43 0 Offset 0 +OpMemberDecorate %43 0 ColMajor +OpMemberDecorate %43 0 MatrixStride 8 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 6 +OpDecorate %46 Block +OpMemberDecorate %46 0 Offset 0 +OpDecorate %48 DescriptorSet 0 +OpDecorate %48 Binding 7 +OpDecorate %49 Block +OpMemberDecorate %49 0 Offset 0 OpDecorate %128 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeBool @@ -57,81 +57,81 @@ OpDecorate %128 BuiltIn LocalInvocationId %8 = OpTypeInt 32 1 %7 = OpConstant %8 20 %9 = OpConstant %8 2 -%11 = OpTypeFloat 32 -%10 = OpConstant %11 1.0 -%12 = OpConstant %8 1 -%13 = OpConstant %8 0 -%14 = OpConstant %11 2.0 -%15 = OpConstant %11 3.0 -%16 = OpConstant %8 7 -%17 = OpConstant %8 6 -%18 = OpConstant %8 5 -%19 = OpConstant %8 4 -%20 = OpConstant %8 3 -%21 = OpConstant %11 4.0 -%22 = OpConstant %6 2 -%23 = OpConstantTrue %4 -%24 = OpTypeArray %11 %5 -%25 = OpTypeVector %11 3 -%26 = OpTypeStruct %25 %11 -%27 = OpTypeVector %11 2 -%28 = OpTypeRuntimeArray %27 -%29 = OpTypeVector %11 4 -%30 = OpTypeArray %29 %7 -%31 = OpTypeMatrix %27 3 -%32 = OpTypeMatrix %29 2 -%33 = OpTypeArray %32 %9 -%34 = OpTypeArray %33 %9 -%35 = OpTypeMatrix %27 4 -%36 = OpTypeArray %35 %9 -%37 = OpTypeArray %36 %9 -%38 = OpTypeMatrix %25 3 -%40 = OpTypePointer Workgroup %24 -%39 = OpVariable %40 Workgroup -%42 = OpTypePointer Workgroup %6 -%41 = OpVariable %42 Workgroup -%44 = OpTypeStruct %26 -%45 = OpTypePointer StorageBuffer %44 -%43 = OpVariable %45 StorageBuffer -%47 = OpTypeStruct %28 -%48 = OpTypePointer StorageBuffer %47 -%46 = OpVariable %48 StorageBuffer -%50 = OpTypeStruct %30 -%51 = OpTypePointer Uniform %50 -%49 = OpVariable %51 Uniform -%53 = OpTypeStruct %25 -%54 = OpTypePointer Uniform %53 -%52 = OpVariable %54 Uniform -%56 = OpTypeStruct %31 -%57 = OpTypePointer Uniform %56 -%55 = OpVariable %57 Uniform -%59 = OpTypeStruct %34 -%60 = OpTypePointer Uniform %59 -%58 = OpVariable %60 Uniform -%62 = OpTypeStruct %37 -%63 = OpTypePointer Uniform %62 -%61 = OpVariable %63 Uniform -%67 = OpTypeFunction %2 %25 -%70 = OpTypePointer Function %8 -%71 = OpConstantNull %8 -%74 = OpTypeFunction %2 -%75 = OpTypePointer StorageBuffer %26 -%76 = OpConstant %6 0 -%78 = OpConstantNull %38 -%79 = OpConstantNull %38 -%81 = OpTypePointer StorageBuffer %25 -%84 = OpTypePointer StorageBuffer %11 -%104 = OpTypePointer Function %11 -%105 = OpConstantNull %11 -%107 = OpTypePointer Function %4 -%108 = OpConstantNull %4 -%112 = OpTypePointer StorageBuffer %28 -%114 = OpTypePointer Uniform %30 -%116 = OpTypePointer Uniform %25 -%118 = OpTypePointer Uniform %31 -%120 = OpTypePointer Uniform %34 -%122 = OpTypePointer Uniform %37 -%125 = OpConstantNull %24 +%10 = OpTypeFloat 32 +%11 = OpTypeArray %10 %5 +%12 = OpTypeVector %10 3 +%13 = OpTypeStruct %12 %10 +%14 = OpTypeVector %10 2 +%15 = OpTypeRuntimeArray %14 +%16 = OpTypeVector %10 4 +%17 = OpTypeArray %16 %7 +%18 = OpTypeMatrix %14 3 +%19 = OpTypeMatrix %16 2 +%20 = OpTypeArray %19 %9 +%21 = OpTypeArray %20 %9 +%22 = OpTypeMatrix %14 4 +%23 = OpTypeArray %22 %9 +%24 = OpTypeArray %23 %9 +%25 = OpTypeMatrix %12 3 +%27 = OpTypePointer Workgroup %11 +%26 = OpVariable %27 Workgroup +%29 = OpTypePointer Workgroup %6 +%28 = OpVariable %29 Workgroup +%31 = OpTypeStruct %13 +%32 = OpTypePointer StorageBuffer %31 +%30 = OpVariable %32 StorageBuffer +%34 = OpTypeStruct %15 +%35 = OpTypePointer StorageBuffer %34 +%33 = OpVariable %35 StorageBuffer +%37 = OpTypeStruct %17 +%38 = OpTypePointer Uniform %37 +%36 = OpVariable %38 Uniform +%40 = OpTypeStruct %12 +%41 = OpTypePointer Uniform %40 +%39 = OpVariable %41 Uniform +%43 = OpTypeStruct %18 +%44 = OpTypePointer Uniform %43 +%42 = OpVariable %44 Uniform +%46 = OpTypeStruct %21 +%47 = OpTypePointer Uniform %46 +%45 = OpVariable %47 Uniform +%49 = OpTypeStruct %24 +%50 = OpTypePointer Uniform %49 +%48 = OpVariable %50 Uniform +%54 = OpTypeFunction %2 %12 +%57 = OpTypePointer Function %8 +%58 = OpConstantNull %8 +%61 = OpTypeFunction %2 +%62 = OpTypePointer StorageBuffer %13 +%63 = OpConstant %6 0 +%65 = OpConstant %10 1.0 +%66 = OpConstant %8 1 +%67 = OpConstant %8 0 +%68 = OpConstant %10 2.0 +%69 = OpConstant %10 3.0 +%70 = OpConstantNull %25 +%71 = OpConstantNull %25 +%73 = OpTypePointer StorageBuffer %12 +%76 = OpTypePointer StorageBuffer %10 +%96 = OpTypePointer Function %10 +%97 = OpConstantNull %10 +%99 = OpTypePointer Function %4 +%100 = OpConstantNull %4 +%104 = OpTypePointer StorageBuffer %15 +%106 = OpTypePointer Uniform %17 +%108 = OpTypePointer Uniform %12 +%110 = OpTypePointer Uniform %18 +%112 = OpTypePointer Uniform %21 +%114 = OpTypePointer Uniform %24 +%116 = OpConstant %8 7 +%117 = OpConstant %8 6 +%118 = OpConstant %8 5 +%119 = OpConstant %8 4 +%120 = OpConstant %8 3 +%121 = OpConstant %10 4.0 +%122 = OpConstant %6 2 +%123 = OpConstantTrue %4 +%125 = OpConstantNull %11 %126 = OpConstantNull %6 %127 = OpTypeVector %6 3 %129 = OpTypePointer Input %127 @@ -139,74 +139,74 @@ OpDecorate %128 BuiltIn LocalInvocationId %131 = OpConstantNull %127 %132 = OpTypeVector %4 3 %137 = OpConstant %6 264 -%140 = OpTypePointer Workgroup %11 -%141 = OpTypePointer Uniform %36 -%142 = OpTypePointer Uniform %35 -%145 = OpTypePointer Uniform %33 -%146 = OpTypePointer Uniform %32 -%147 = OpTypePointer Uniform %29 +%140 = OpTypePointer Workgroup %10 +%141 = OpTypePointer Uniform %23 +%142 = OpTypePointer Uniform %22 +%145 = OpTypePointer Uniform %20 +%146 = OpTypePointer Uniform %19 +%147 = OpTypePointer Uniform %16 %152 = OpConstant %6 7 %158 = OpConstant %6 6 -%160 = OpTypePointer StorageBuffer %27 +%160 = OpTypePointer StorageBuffer %14 %161 = OpConstant %6 1 %164 = OpConstant %6 5 -%166 = OpTypePointer Uniform %29 -%167 = OpTypePointer Uniform %11 +%166 = OpTypePointer Uniform %16 +%167 = OpTypePointer Uniform %10 %168 = OpConstant %6 3 %171 = OpConstant %6 4 -%173 = OpTypePointer StorageBuffer %11 +%173 = OpTypePointer StorageBuffer %10 %184 = OpConstant %6 256 -%66 = OpFunction %2 None %67 -%65 = OpFunctionParameter %25 -%64 = OpLabel -OpBranch %68 -%68 = OpLabel +%53 = OpFunction %2 None %54 +%52 = OpFunctionParameter %12 +%51 = OpLabel +OpBranch %55 +%55 = OpLabel OpReturn OpFunctionEnd -%73 = OpFunction %2 None %74 +%60 = OpFunction %2 None %61 +%59 = OpLabel +%56 = OpVariable %57 Function %58 +%64 = OpAccessChain %62 %30 %63 +OpBranch %72 %72 = OpLabel -%69 = OpVariable %70 Function %71 -%77 = OpAccessChain %75 %43 %76 -OpBranch %80 -%80 = OpLabel -%82 = OpCompositeConstruct %25 %10 %10 %10 -%83 = OpAccessChain %81 %77 %76 -OpStore %83 %82 -OpStore %69 %12 -%85 = OpAccessChain %84 %77 %76 %76 -OpStore %85 %10 -%86 = OpAccessChain %84 %77 %76 %76 -OpStore %86 %14 -%87 = OpLoad %8 %69 -%88 = OpAccessChain %84 %77 %76 %87 -OpStore %88 %15 -%89 = OpLoad %26 %77 -%90 = OpCompositeExtract %25 %89 0 -%91 = OpCompositeExtract %25 %89 0 -%92 = OpVectorShuffle %27 %91 %91 2 0 -%93 = OpCompositeExtract %25 %89 0 -%94 = OpFunctionCall %2 %66 %93 -%95 = OpCompositeExtract %25 %89 0 -%96 = OpVectorTimesMatrix %25 %95 %78 -%97 = OpCompositeExtract %25 %89 0 -%98 = OpMatrixTimesVector %25 %79 %97 -%99 = OpCompositeExtract %25 %89 0 -%100 = OpVectorTimesScalar %25 %99 %14 -%101 = OpCompositeExtract %25 %89 0 -%102 = OpVectorTimesScalar %25 %101 %14 +%74 = OpCompositeConstruct %12 %65 %65 %65 +%75 = OpAccessChain %73 %64 %63 +OpStore %75 %74 +OpStore %56 %66 +%77 = OpAccessChain %76 %64 %63 %63 +OpStore %77 %65 +%78 = OpAccessChain %76 %64 %63 %63 +OpStore %78 %68 +%79 = OpLoad %8 %56 +%80 = OpAccessChain %76 %64 %63 %79 +OpStore %80 %69 +%81 = OpLoad %13 %64 +%82 = OpCompositeExtract %12 %81 0 +%83 = OpCompositeExtract %12 %81 0 +%84 = OpVectorShuffle %14 %83 %83 2 0 +%85 = OpCompositeExtract %12 %81 0 +%86 = OpFunctionCall %2 %53 %85 +%87 = OpCompositeExtract %12 %81 0 +%88 = OpVectorTimesMatrix %12 %87 %70 +%89 = OpCompositeExtract %12 %81 0 +%90 = OpMatrixTimesVector %12 %71 %89 +%91 = OpCompositeExtract %12 %81 0 +%92 = OpVectorTimesScalar %12 %91 %68 +%93 = OpCompositeExtract %12 %81 0 +%94 = OpVectorTimesScalar %12 %93 %68 OpReturn OpFunctionEnd -%110 = OpFunction %2 None %74 -%109 = OpLabel -%103 = OpVariable %104 Function %105 -%106 = OpVariable %107 Function %108 -%111 = OpAccessChain %75 %43 %76 -%113 = OpAccessChain %112 %46 %76 -%115 = OpAccessChain %114 %49 %76 -%117 = OpAccessChain %116 %52 %76 -%119 = OpAccessChain %118 %55 %76 -%121 = OpAccessChain %120 %58 %76 -%123 = OpAccessChain %122 %61 %76 +%102 = OpFunction %2 None %61 +%101 = OpLabel +%95 = OpVariable %96 Function %97 +%98 = OpVariable %99 Function %100 +%103 = OpAccessChain %62 %30 %63 +%105 = OpAccessChain %104 %33 %63 +%107 = OpAccessChain %106 %36 %63 +%109 = OpAccessChain %108 %39 %63 +%111 = OpAccessChain %110 %42 %63 +%113 = OpAccessChain %112 %45 %63 +%115 = OpAccessChain %114 %48 %63 OpBranch %124 %124 = OpLabel %130 = OpLoad %127 %128 @@ -215,52 +215,52 @@ OpBranch %124 OpSelectionMerge %135 None OpBranchConditional %134 %136 %135 %136 = OpLabel -OpStore %39 %125 -OpStore %41 %126 +OpStore %26 %125 +OpStore %28 %126 OpBranch %135 %135 = OpLabel -OpControlBarrier %22 %22 %137 +OpControlBarrier %122 %122 %137 OpBranch %138 %138 = OpLabel -%139 = OpFunctionCall %2 %73 -%143 = OpAccessChain %142 %123 %76 %76 -%144 = OpLoad %35 %143 -%148 = OpAccessChain %147 %121 %76 %76 %76 -%149 = OpLoad %29 %148 -%150 = OpMatrixTimesVector %27 %144 %149 -%151 = OpCompositeExtract %11 %150 0 -%153 = OpAccessChain %140 %39 %152 +%139 = OpFunctionCall %2 %60 +%143 = OpAccessChain %142 %115 %63 %63 +%144 = OpLoad %22 %143 +%148 = OpAccessChain %147 %113 %63 %63 %63 +%149 = OpLoad %16 %148 +%150 = OpMatrixTimesVector %14 %144 %149 +%151 = OpCompositeExtract %10 %150 0 +%153 = OpAccessChain %140 %26 %152 OpStore %153 %151 -%154 = OpLoad %31 %119 -%155 = OpLoad %25 %117 -%156 = OpMatrixTimesVector %27 %154 %155 -%157 = OpCompositeExtract %11 %156 0 -%159 = OpAccessChain %140 %39 %158 +%154 = OpLoad %18 %111 +%155 = OpLoad %12 %109 +%156 = OpMatrixTimesVector %14 %154 %155 +%157 = OpCompositeExtract %10 %156 0 +%159 = OpAccessChain %140 %26 %158 OpStore %159 %157 -%162 = OpAccessChain %84 %113 %161 %161 -%163 = OpLoad %11 %162 -%165 = OpAccessChain %140 %39 %164 +%162 = OpAccessChain %76 %105 %161 %161 +%163 = OpLoad %10 %162 +%165 = OpAccessChain %140 %26 %164 OpStore %165 %163 -%169 = OpAccessChain %167 %115 %76 %168 -%170 = OpLoad %11 %169 -%172 = OpAccessChain %140 %39 %171 +%169 = OpAccessChain %167 %107 %63 %168 +%170 = OpLoad %10 %169 +%172 = OpAccessChain %140 %26 %171 OpStore %172 %170 -%174 = OpAccessChain %173 %111 %161 -%175 = OpLoad %11 %174 -%176 = OpAccessChain %140 %39 %168 +%174 = OpAccessChain %173 %103 %161 +%175 = OpLoad %10 %174 +%176 = OpAccessChain %140 %26 %168 OpStore %176 %175 -%177 = OpAccessChain %84 %111 %76 %76 -%178 = OpLoad %11 %177 -%179 = OpAccessChain %140 %39 %22 +%177 = OpAccessChain %76 %103 %63 %63 +%178 = OpLoad %10 %177 +%179 = OpAccessChain %140 %26 %122 OpStore %179 %178 -%180 = OpAccessChain %173 %111 %161 -OpStore %180 %21 -%181 = OpArrayLength %6 %46 0 -%182 = OpConvertUToF %11 %181 -%183 = OpAccessChain %140 %39 %161 +%180 = OpAccessChain %173 %103 %161 +OpStore %180 %121 +%181 = OpArrayLength %6 %33 0 +%182 = OpConvertUToF %10 %181 +%183 = OpAccessChain %140 %26 %161 OpStore %183 %182 -OpAtomicStore %41 %9 %184 %22 -OpStore %103 %10 -OpStore %106 %23 +OpAtomicStore %28 %9 %184 %122 +OpStore %95 %65 +OpStore %98 %123 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 040ded2af..7b9aa5ed6 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -9,713 +9,713 @@ OpCapability Shader OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %89 "main" %86 -OpEntryPoint GLCompute %177 "depth_load" %175 -OpEntryPoint Vertex %199 "queries" %197 -OpEntryPoint Vertex %263 "levels_queries" %262 -OpEntryPoint Fragment %303 "texture_sample" %302 +OpEntryPoint GLCompute %82 "main" %79 +OpEntryPoint GLCompute %172 "depth_load" %170 +OpEntryPoint Vertex %194 "queries" %192 +OpEntryPoint Vertex %259 "levels_queries" %258 +OpEntryPoint Fragment %299 "texture_sample" %298 OpEntryPoint Fragment %444 "texture_sample_comparison" %442 OpEntryPoint Fragment %499 "gather" %498 OpEntryPoint Fragment %534 "depth_no_comparison" %533 -OpExecutionMode %89 LocalSize 16 1 1 -OpExecutionMode %177 LocalSize 16 1 1 -OpExecutionMode %303 OriginUpperLeft +OpExecutionMode %82 LocalSize 16 1 1 +OpExecutionMode %172 LocalSize 16 1 1 +OpExecutionMode %299 OriginUpperLeft OpExecutionMode %444 OriginUpperLeft OpExecutionMode %499 OriginUpperLeft OpExecutionMode %534 OriginUpperLeft OpSource GLSL 450 -OpName %42 "image_mipmapped_src" -OpName %44 "image_multisampled_src" -OpName %46 "image_depth_multisampled_src" -OpName %48 "image_storage_src" -OpName %50 "image_array_src" -OpName %52 "image_dup_src" -OpName %54 "image_1d_src" -OpName %56 "image_dst" -OpName %58 "image_1d" -OpName %60 "image_2d" -OpName %62 "image_2d_u32" -OpName %63 "image_2d_i32" -OpName %65 "image_2d_array" -OpName %67 "image_cube" -OpName %69 "image_cube_array" -OpName %71 "image_3d" -OpName %73 "image_aa" -OpName %75 "sampler_reg" -OpName %77 "sampler_cmp" -OpName %79 "image_2d_depth" -OpName %81 "image_2d_array_depth" -OpName %83 "image_cube_depth" -OpName %86 "local_id" -OpName %89 "main" -OpName %175 "local_id" -OpName %177 "depth_load" -OpName %199 "queries" -OpName %263 "levels_queries" -OpName %298 "a" -OpName %303 "texture_sample" +OpName %35 "image_mipmapped_src" +OpName %37 "image_multisampled_src" +OpName %39 "image_depth_multisampled_src" +OpName %41 "image_storage_src" +OpName %43 "image_array_src" +OpName %45 "image_dup_src" +OpName %47 "image_1d_src" +OpName %49 "image_dst" +OpName %51 "image_1d" +OpName %53 "image_2d" +OpName %55 "image_2d_u32" +OpName %56 "image_2d_i32" +OpName %58 "image_2d_array" +OpName %60 "image_cube" +OpName %62 "image_cube_array" +OpName %64 "image_3d" +OpName %66 "image_aa" +OpName %68 "sampler_reg" +OpName %70 "sampler_cmp" +OpName %72 "image_2d_depth" +OpName %74 "image_2d_array_depth" +OpName %76 "image_cube_depth" +OpName %79 "local_id" +OpName %82 "main" +OpName %170 "local_id" +OpName %172 "depth_load" +OpName %194 "queries" +OpName %259 "levels_queries" +OpName %294 "a" +OpName %299 "texture_sample" OpName %438 "a" OpName %444 "texture_sample_comparison" OpName %499 "gather" OpName %534 "depth_no_comparison" -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 0 -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 3 -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 4 -OpDecorate %48 NonWritable -OpDecorate %48 DescriptorSet 0 -OpDecorate %48 Binding 1 -OpDecorate %50 DescriptorSet 0 -OpDecorate %50 Binding 5 -OpDecorate %52 NonWritable -OpDecorate %52 DescriptorSet 0 -OpDecorate %52 Binding 6 -OpDecorate %54 DescriptorSet 0 -OpDecorate %54 Binding 7 -OpDecorate %56 NonReadable +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 0 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 3 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 4 +OpDecorate %41 NonWritable +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 1 +OpDecorate %43 DescriptorSet 0 +OpDecorate %43 Binding 5 +OpDecorate %45 NonWritable +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 6 +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 7 +OpDecorate %49 NonReadable +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 2 +OpDecorate %51 DescriptorSet 0 +OpDecorate %51 Binding 0 +OpDecorate %53 DescriptorSet 0 +OpDecorate %53 Binding 1 +OpDecorate %55 DescriptorSet 0 +OpDecorate %55 Binding 2 OpDecorate %56 DescriptorSet 0 -OpDecorate %56 Binding 2 +OpDecorate %56 Binding 3 OpDecorate %58 DescriptorSet 0 -OpDecorate %58 Binding 0 +OpDecorate %58 Binding 4 OpDecorate %60 DescriptorSet 0 -OpDecorate %60 Binding 1 +OpDecorate %60 Binding 5 OpDecorate %62 DescriptorSet 0 -OpDecorate %62 Binding 2 -OpDecorate %63 DescriptorSet 0 -OpDecorate %63 Binding 3 -OpDecorate %65 DescriptorSet 0 -OpDecorate %65 Binding 4 -OpDecorate %67 DescriptorSet 0 -OpDecorate %67 Binding 5 -OpDecorate %69 DescriptorSet 0 -OpDecorate %69 Binding 6 -OpDecorate %71 DescriptorSet 0 -OpDecorate %71 Binding 7 -OpDecorate %73 DescriptorSet 0 -OpDecorate %73 Binding 8 -OpDecorate %75 DescriptorSet 1 -OpDecorate %75 Binding 0 -OpDecorate %77 DescriptorSet 1 -OpDecorate %77 Binding 1 -OpDecorate %79 DescriptorSet 1 -OpDecorate %79 Binding 2 -OpDecorate %81 DescriptorSet 1 -OpDecorate %81 Binding 3 -OpDecorate %83 DescriptorSet 1 -OpDecorate %83 Binding 4 -OpDecorate %86 BuiltIn LocalInvocationId -OpDecorate %175 BuiltIn LocalInvocationId -OpDecorate %197 BuiltIn Position -OpDecorate %262 BuiltIn Position -OpDecorate %302 Location 0 +OpDecorate %62 Binding 6 +OpDecorate %64 DescriptorSet 0 +OpDecorate %64 Binding 7 +OpDecorate %66 DescriptorSet 0 +OpDecorate %66 Binding 8 +OpDecorate %68 DescriptorSet 1 +OpDecorate %68 Binding 0 +OpDecorate %70 DescriptorSet 1 +OpDecorate %70 Binding 1 +OpDecorate %72 DescriptorSet 1 +OpDecorate %72 Binding 2 +OpDecorate %74 DescriptorSet 1 +OpDecorate %74 Binding 3 +OpDecorate %76 DescriptorSet 1 +OpDecorate %76 Binding 4 +OpDecorate %79 BuiltIn LocalInvocationId +OpDecorate %170 BuiltIn LocalInvocationId +OpDecorate %192 BuiltIn Position +OpDecorate %258 BuiltIn Position +OpDecorate %298 Location 0 OpDecorate %442 Location 0 OpDecorate %498 Location 0 OpDecorate %533 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 -%3 = OpConstant %4 10 -%5 = OpConstant %4 20 -%6 = OpConstant %4 1 -%8 = OpTypeFloat 32 -%7 = OpConstant %8 0.5 -%9 = OpConstant %8 2.3 -%10 = OpConstant %4 3 -%11 = OpConstant %8 2.0 -%13 = OpTypeInt 32 0 -%12 = OpConstant %13 0 -%14 = OpConstant %4 0 -%15 = OpTypeImage %13 2D 0 0 0 1 Unknown -%16 = OpTypeImage %13 2D 0 0 1 1 Unknown -%17 = OpTypeImage %8 2D 1 0 1 1 Unknown -%18 = OpTypeImage %13 2D 0 0 0 2 Rgba8ui -%19 = OpTypeImage %13 2D 0 1 0 1 Unknown -%20 = OpTypeImage %13 1D 0 0 0 2 R32ui -%21 = OpTypeImage %13 1D 0 0 0 1 Unknown -%22 = OpTypeVector %13 3 -%23 = OpTypeVector %4 2 -%24 = OpTypeVector %13 2 -%25 = OpTypeVector %13 4 -%26 = OpTypeImage %8 1D 0 0 0 1 Unknown -%27 = OpTypeImage %8 2D 0 0 0 1 Unknown -%28 = OpTypeImage %4 2D 0 0 0 1 Unknown -%29 = OpTypeImage %8 2D 0 1 0 1 Unknown -%30 = OpTypeImage %8 Cube 0 0 0 1 Unknown -%31 = OpTypeImage %8 Cube 0 1 0 1 Unknown -%32 = OpTypeImage %8 3D 0 0 0 1 Unknown -%33 = OpTypeImage %8 2D 0 0 1 1 Unknown -%34 = OpTypeVector %8 4 -%35 = OpTypeSampler -%36 = OpTypeVector %8 2 -%37 = OpTypeVector %8 3 -%38 = OpTypeImage %8 2D 1 0 0 1 Unknown -%39 = OpTypeImage %8 2D 1 1 0 1 Unknown -%40 = OpTypeImage %8 Cube 1 0 0 1 Unknown -%41 = OpConstantComposite %23 %10 %6 -%43 = OpTypePointer UniformConstant %15 -%42 = OpVariable %43 UniformConstant -%45 = OpTypePointer UniformConstant %16 -%44 = OpVariable %45 UniformConstant -%47 = OpTypePointer UniformConstant %17 -%46 = OpVariable %47 UniformConstant -%49 = OpTypePointer UniformConstant %18 -%48 = OpVariable %49 UniformConstant -%51 = OpTypePointer UniformConstant %19 -%50 = OpVariable %51 UniformConstant -%53 = OpTypePointer UniformConstant %20 -%52 = OpVariable %53 UniformConstant -%55 = OpTypePointer UniformConstant %21 -%54 = OpVariable %55 UniformConstant -%57 = OpTypePointer UniformConstant %20 +%3 = OpConstant %4 3 +%5 = OpConstant %4 1 +%7 = OpTypeInt 32 0 +%6 = OpTypeImage %7 2D 0 0 0 1 Unknown +%8 = OpTypeImage %7 2D 0 0 1 1 Unknown +%10 = OpTypeFloat 32 +%9 = OpTypeImage %10 2D 1 0 1 1 Unknown +%11 = OpTypeImage %7 2D 0 0 0 2 Rgba8ui +%12 = OpTypeImage %7 2D 0 1 0 1 Unknown +%13 = OpTypeImage %7 1D 0 0 0 2 R32ui +%14 = OpTypeImage %7 1D 0 0 0 1 Unknown +%15 = OpTypeVector %7 3 +%16 = OpTypeVector %4 2 +%17 = OpTypeVector %7 2 +%18 = OpTypeVector %7 4 +%19 = OpTypeImage %10 1D 0 0 0 1 Unknown +%20 = OpTypeImage %10 2D 0 0 0 1 Unknown +%21 = OpTypeImage %4 2D 0 0 0 1 Unknown +%22 = OpTypeImage %10 2D 0 1 0 1 Unknown +%23 = OpTypeImage %10 Cube 0 0 0 1 Unknown +%24 = OpTypeImage %10 Cube 0 1 0 1 Unknown +%25 = OpTypeImage %10 3D 0 0 0 1 Unknown +%26 = OpTypeImage %10 2D 0 0 1 1 Unknown +%27 = OpTypeVector %10 4 +%28 = OpTypeSampler +%29 = OpTypeVector %10 2 +%30 = OpTypeVector %10 3 +%31 = OpTypeImage %10 2D 1 0 0 1 Unknown +%32 = OpTypeImage %10 2D 1 1 0 1 Unknown +%33 = OpTypeImage %10 Cube 1 0 0 1 Unknown +%34 = OpConstantComposite %16 %3 %5 +%36 = OpTypePointer UniformConstant %6 +%35 = OpVariable %36 UniformConstant +%38 = OpTypePointer UniformConstant %8 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %9 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %11 +%41 = OpVariable %42 UniformConstant +%44 = OpTypePointer UniformConstant %12 +%43 = OpVariable %44 UniformConstant +%46 = OpTypePointer UniformConstant %13 +%45 = OpVariable %46 UniformConstant +%48 = OpTypePointer UniformConstant %14 +%47 = OpVariable %48 UniformConstant +%50 = OpTypePointer UniformConstant %13 +%49 = OpVariable %50 UniformConstant +%52 = OpTypePointer UniformConstant %19 +%51 = OpVariable %52 UniformConstant +%54 = OpTypePointer UniformConstant %20 +%53 = OpVariable %54 UniformConstant +%55 = OpVariable %36 UniformConstant +%57 = OpTypePointer UniformConstant %21 %56 = OpVariable %57 UniformConstant -%59 = OpTypePointer UniformConstant %26 +%59 = OpTypePointer UniformConstant %22 %58 = OpVariable %59 UniformConstant -%61 = OpTypePointer UniformConstant %27 +%61 = OpTypePointer UniformConstant %23 %60 = OpVariable %61 UniformConstant -%62 = OpVariable %43 UniformConstant -%64 = OpTypePointer UniformConstant %28 -%63 = OpVariable %64 UniformConstant -%66 = OpTypePointer UniformConstant %29 -%65 = OpVariable %66 UniformConstant -%68 = OpTypePointer UniformConstant %30 -%67 = OpVariable %68 UniformConstant -%70 = OpTypePointer UniformConstant %31 -%69 = OpVariable %70 UniformConstant -%72 = OpTypePointer UniformConstant %32 -%71 = OpVariable %72 UniformConstant -%74 = OpTypePointer UniformConstant %33 -%73 = OpVariable %74 UniformConstant -%76 = OpTypePointer UniformConstant %35 -%75 = OpVariable %76 UniformConstant -%78 = OpTypePointer UniformConstant %35 -%77 = OpVariable %78 UniformConstant -%80 = OpTypePointer UniformConstant %38 -%79 = OpVariable %80 UniformConstant -%82 = OpTypePointer UniformConstant %39 -%81 = OpVariable %82 UniformConstant -%84 = OpTypePointer UniformConstant %40 -%83 = OpVariable %84 UniformConstant -%87 = OpTypePointer Input %22 -%86 = OpVariable %87 Input -%90 = OpTypeFunction %2 -%117 = OpTypeVector %4 3 -%175 = OpVariable %87 Input -%198 = OpTypePointer Output %34 -%197 = OpVariable %198 Output -%262 = OpVariable %198 Output -%299 = OpTypePointer Function %34 -%300 = OpConstantNull %34 -%302 = OpVariable %198 Output -%313 = OpTypeSampledImage %26 -%318 = OpTypeSampledImage %27 -%339 = OpTypeSampledImage %29 -%400 = OpTypeSampledImage %31 -%439 = OpTypePointer Function %8 -%440 = OpConstantNull %8 -%443 = OpTypePointer Output %8 +%63 = OpTypePointer UniformConstant %24 +%62 = OpVariable %63 UniformConstant +%65 = OpTypePointer UniformConstant %25 +%64 = OpVariable %65 UniformConstant +%67 = OpTypePointer UniformConstant %26 +%66 = OpVariable %67 UniformConstant +%69 = OpTypePointer UniformConstant %28 +%68 = OpVariable %69 UniformConstant +%71 = OpTypePointer UniformConstant %28 +%70 = OpVariable %71 UniformConstant +%73 = OpTypePointer UniformConstant %31 +%72 = OpVariable %73 UniformConstant +%75 = OpTypePointer UniformConstant %32 +%74 = OpVariable %75 UniformConstant +%77 = OpTypePointer UniformConstant %33 +%76 = OpVariable %77 UniformConstant +%80 = OpTypePointer Input %15 +%79 = OpVariable %80 Input +%83 = OpTypeFunction %2 +%90 = OpConstant %4 10 +%91 = OpConstant %4 20 +%112 = OpTypeVector %4 3 +%170 = OpVariable %80 Input +%193 = OpTypePointer Output %27 +%192 = OpVariable %193 Output +%203 = OpConstant %7 0 +%258 = OpVariable %193 Output +%295 = OpTypePointer Function %27 +%296 = OpConstantNull %27 +%298 = OpVariable %193 Output +%305 = OpConstant %10 0.5 +%306 = OpConstant %10 2.3 +%307 = OpConstant %10 2.0 +%308 = OpConstant %4 0 +%313 = OpTypeSampledImage %19 +%318 = OpTypeSampledImage %20 +%339 = OpTypeSampledImage %22 +%400 = OpTypeSampledImage %24 +%439 = OpTypePointer Function %10 +%440 = OpConstantNull %10 +%443 = OpTypePointer Output %10 %442 = OpVariable %443 Output -%452 = OpTypeSampledImage %38 -%457 = OpTypeSampledImage %39 -%470 = OpTypeSampledImage %40 -%477 = OpConstant %8 0.0 -%498 = OpVariable %198 Output -%510 = OpConstant %13 1 -%513 = OpConstant %13 3 -%518 = OpTypeSampledImage %15 +%452 = OpTypeSampledImage %31 +%457 = OpTypeSampledImage %32 +%470 = OpTypeSampledImage %33 +%477 = OpConstant %10 0.0 +%498 = OpVariable %193 Output +%510 = OpConstant %7 1 +%513 = OpConstant %7 3 +%518 = OpTypeSampledImage %6 %521 = OpTypeVector %4 4 -%522 = OpTypeSampledImage %28 -%533 = OpVariable %198 Output -%89 = OpFunction %2 None %90 -%85 = OpLabel -%88 = OpLoad %22 %86 -%91 = OpLoad %15 %42 -%92 = OpLoad %16 %44 -%93 = OpLoad %18 %48 -%94 = OpLoad %19 %50 -%95 = OpLoad %21 %54 -%96 = OpLoad %20 %56 -OpBranch %97 -%97 = OpLabel -%98 = OpImageQuerySize %23 %93 -%99 = OpBitcast %24 %98 -%100 = OpVectorShuffle %24 %88 %88 0 1 -%101 = OpIMul %24 %99 %100 -%102 = OpBitcast %23 %101 -%103 = OpCompositeConstruct %23 %3 %5 -%104 = OpSRem %23 %102 %103 -%105 = OpCompositeExtract %13 %88 2 -%106 = OpBitcast %4 %105 -%107 = OpImageFetch %25 %91 %104 Lod %106 -%108 = OpCompositeExtract %13 %88 2 +%522 = OpTypeSampledImage %21 +%533 = OpVariable %193 Output +%82 = OpFunction %2 None %83 +%78 = OpLabel +%81 = OpLoad %15 %79 +%84 = OpLoad %6 %35 +%85 = OpLoad %8 %37 +%86 = OpLoad %11 %41 +%87 = OpLoad %12 %43 +%88 = OpLoad %14 %47 +%89 = OpLoad %13 %49 +OpBranch %92 +%92 = OpLabel +%93 = OpImageQuerySize %16 %86 +%94 = OpBitcast %17 %93 +%95 = OpVectorShuffle %17 %81 %81 0 1 +%96 = OpIMul %17 %94 %95 +%97 = OpBitcast %16 %96 +%98 = OpCompositeConstruct %16 %90 %91 +%99 = OpSRem %16 %97 %98 +%100 = OpCompositeExtract %7 %81 2 +%101 = OpBitcast %4 %100 +%102 = OpImageFetch %18 %84 %99 Lod %101 +%103 = OpCompositeExtract %7 %81 2 +%104 = OpBitcast %4 %103 +%105 = OpImageFetch %18 %85 %99 Sample %104 +%106 = OpImageRead %18 %86 %99 +%107 = OpCompositeExtract %7 %81 2 +%108 = OpCompositeExtract %7 %81 2 %109 = OpBitcast %4 %108 -%110 = OpImageFetch %25 %92 %104 Sample %109 -%111 = OpImageRead %25 %93 %104 -%112 = OpCompositeExtract %13 %88 2 -%113 = OpCompositeExtract %13 %88 2 -%114 = OpBitcast %4 %113 -%115 = OpIAdd %4 %114 %6 -%116 = OpBitcast %4 %112 -%118 = OpCompositeConstruct %117 %104 %116 -%119 = OpImageFetch %25 %94 %118 Lod %115 -%120 = OpCompositeExtract %13 %88 2 -%121 = OpBitcast %4 %120 -%122 = OpCompositeExtract %13 %88 2 +%110 = OpIAdd %4 %109 %5 +%111 = OpBitcast %4 %107 +%113 = OpCompositeConstruct %112 %99 %111 +%114 = OpImageFetch %18 %87 %113 Lod %110 +%115 = OpCompositeExtract %7 %81 2 +%116 = OpBitcast %4 %115 +%117 = OpCompositeExtract %7 %81 2 +%118 = OpBitcast %4 %117 +%119 = OpIAdd %4 %118 %5 +%120 = OpCompositeConstruct %112 %99 %116 +%121 = OpImageFetch %18 %87 %120 Lod %119 +%122 = OpCompositeExtract %7 %81 0 %123 = OpBitcast %4 %122 -%124 = OpIAdd %4 %123 %6 -%125 = OpCompositeConstruct %117 %104 %121 -%126 = OpImageFetch %25 %94 %125 Lod %124 -%127 = OpCompositeExtract %13 %88 0 -%128 = OpBitcast %4 %127 -%129 = OpCompositeExtract %13 %88 2 -%130 = OpBitcast %4 %129 -%131 = OpImageFetch %25 %95 %128 Lod %130 -%132 = OpBitcast %24 %104 -%133 = OpCompositeExtract %13 %88 2 -%134 = OpBitcast %4 %133 -%135 = OpImageFetch %25 %91 %132 Lod %134 -%136 = OpBitcast %24 %104 -%137 = OpCompositeExtract %13 %88 2 -%138 = OpBitcast %4 %137 -%139 = OpImageFetch %25 %92 %136 Sample %138 -%140 = OpBitcast %24 %104 -%141 = OpImageRead %25 %93 %140 -%142 = OpBitcast %24 %104 -%143 = OpCompositeExtract %13 %88 2 -%144 = OpCompositeExtract %13 %88 2 -%145 = OpBitcast %4 %144 -%146 = OpIAdd %4 %145 %6 -%147 = OpCompositeConstruct %22 %142 %143 -%148 = OpImageFetch %25 %94 %147 Lod %146 -%149 = OpBitcast %24 %104 -%150 = OpCompositeExtract %13 %88 2 -%151 = OpBitcast %4 %150 -%152 = OpCompositeExtract %13 %88 2 -%153 = OpBitcast %4 %152 -%154 = OpIAdd %4 %153 %6 -%155 = OpBitcast %13 %151 -%156 = OpCompositeConstruct %22 %149 %155 -%157 = OpImageFetch %25 %94 %156 Lod %154 -%158 = OpCompositeExtract %13 %88 0 -%160 = OpCompositeExtract %13 %88 2 -%161 = OpBitcast %4 %160 -%162 = OpImageFetch %25 %95 %158 Lod %161 -%163 = OpCompositeExtract %4 %104 0 -%164 = OpIAdd %25 %107 %110 -%165 = OpIAdd %25 %164 %111 -%166 = OpIAdd %25 %165 %119 -%167 = OpIAdd %25 %166 %126 -OpImageWrite %96 %163 %167 -%168 = OpCompositeExtract %4 %104 0 -%169 = OpBitcast %13 %168 -%170 = OpIAdd %25 %135 %139 -%171 = OpIAdd %25 %170 %141 -%172 = OpIAdd %25 %171 %148 -%173 = OpIAdd %25 %172 %157 -OpImageWrite %96 %169 %173 +%124 = OpCompositeExtract %7 %81 2 +%125 = OpBitcast %4 %124 +%126 = OpImageFetch %18 %88 %123 Lod %125 +%127 = OpBitcast %17 %99 +%128 = OpCompositeExtract %7 %81 2 +%129 = OpBitcast %4 %128 +%130 = OpImageFetch %18 %84 %127 Lod %129 +%131 = OpBitcast %17 %99 +%132 = OpCompositeExtract %7 %81 2 +%133 = OpBitcast %4 %132 +%134 = OpImageFetch %18 %85 %131 Sample %133 +%135 = OpBitcast %17 %99 +%136 = OpImageRead %18 %86 %135 +%137 = OpBitcast %17 %99 +%138 = OpCompositeExtract %7 %81 2 +%139 = OpCompositeExtract %7 %81 2 +%140 = OpBitcast %4 %139 +%141 = OpIAdd %4 %140 %5 +%142 = OpCompositeConstruct %15 %137 %138 +%143 = OpImageFetch %18 %87 %142 Lod %141 +%144 = OpBitcast %17 %99 +%145 = OpCompositeExtract %7 %81 2 +%146 = OpBitcast %4 %145 +%147 = OpCompositeExtract %7 %81 2 +%148 = OpBitcast %4 %147 +%149 = OpIAdd %4 %148 %5 +%150 = OpBitcast %7 %146 +%151 = OpCompositeConstruct %15 %144 %150 +%152 = OpImageFetch %18 %87 %151 Lod %149 +%153 = OpCompositeExtract %7 %81 0 +%155 = OpCompositeExtract %7 %81 2 +%156 = OpBitcast %4 %155 +%157 = OpImageFetch %18 %88 %153 Lod %156 +%158 = OpCompositeExtract %4 %99 0 +%159 = OpIAdd %18 %102 %105 +%160 = OpIAdd %18 %159 %106 +%161 = OpIAdd %18 %160 %114 +%162 = OpIAdd %18 %161 %121 +OpImageWrite %89 %158 %162 +%163 = OpCompositeExtract %4 %99 0 +%164 = OpBitcast %7 %163 +%165 = OpIAdd %18 %130 %134 +%166 = OpIAdd %18 %165 %136 +%167 = OpIAdd %18 %166 %143 +%168 = OpIAdd %18 %167 %152 +OpImageWrite %89 %164 %168 OpReturn OpFunctionEnd -%177 = OpFunction %2 None %90 -%174 = OpLabel -%176 = OpLoad %22 %175 -%178 = OpLoad %17 %46 -%179 = OpLoad %18 %48 -%180 = OpLoad %20 %56 -OpBranch %181 -%181 = OpLabel -%182 = OpImageQuerySize %23 %179 -%183 = OpBitcast %24 %182 -%184 = OpVectorShuffle %24 %176 %176 0 1 -%185 = OpIMul %24 %183 %184 -%186 = OpBitcast %23 %185 -%187 = OpCompositeConstruct %23 %3 %5 -%188 = OpSRem %23 %186 %187 -%189 = OpCompositeExtract %13 %176 2 -%190 = OpBitcast %4 %189 -%191 = OpImageFetch %34 %178 %188 Sample %190 -%192 = OpCompositeExtract %8 %191 0 -%193 = OpCompositeExtract %4 %188 0 -%194 = OpConvertFToU %13 %192 -%195 = OpCompositeConstruct %25 %194 %194 %194 %194 -OpImageWrite %180 %193 %195 +%172 = OpFunction %2 None %83 +%169 = OpLabel +%171 = OpLoad %15 %170 +%173 = OpLoad %9 %39 +%174 = OpLoad %11 %41 +%175 = OpLoad %13 %49 +OpBranch %176 +%176 = OpLabel +%177 = OpImageQuerySize %16 %174 +%178 = OpBitcast %17 %177 +%179 = OpVectorShuffle %17 %171 %171 0 1 +%180 = OpIMul %17 %178 %179 +%181 = OpBitcast %16 %180 +%182 = OpCompositeConstruct %16 %90 %91 +%183 = OpSRem %16 %181 %182 +%184 = OpCompositeExtract %7 %171 2 +%185 = OpBitcast %4 %184 +%186 = OpImageFetch %27 %173 %183 Sample %185 +%187 = OpCompositeExtract %10 %186 0 +%188 = OpCompositeExtract %4 %183 0 +%189 = OpConvertFToU %7 %187 +%190 = OpCompositeConstruct %18 %189 %189 %189 %189 +OpImageWrite %175 %188 %190 OpReturn OpFunctionEnd -%199 = OpFunction %2 None %90 -%196 = OpLabel -%200 = OpLoad %26 %58 -%201 = OpLoad %27 %60 -%202 = OpLoad %29 %65 -%203 = OpLoad %30 %67 -%204 = OpLoad %31 %69 -%205 = OpLoad %32 %71 -%206 = OpLoad %33 %73 -OpBranch %207 -%207 = OpLabel -%208 = OpImageQuerySizeLod %4 %200 %12 -%209 = OpBitcast %13 %208 -%210 = OpBitcast %4 %209 -%211 = OpImageQuerySizeLod %4 %200 %210 -%212 = OpBitcast %13 %211 -%213 = OpImageQuerySizeLod %23 %201 %12 -%214 = OpBitcast %24 %213 -%215 = OpImageQuerySizeLod %23 %201 %6 -%216 = OpBitcast %24 %215 -%217 = OpImageQuerySizeLod %117 %202 %12 -%218 = OpBitcast %22 %217 -%219 = OpVectorShuffle %24 %218 %218 0 1 -%220 = OpImageQuerySizeLod %117 %202 %6 -%221 = OpBitcast %22 %220 -%222 = OpVectorShuffle %24 %221 %221 0 1 -%223 = OpImageQuerySizeLod %23 %203 %12 -%224 = OpBitcast %24 %223 -%225 = OpImageQuerySizeLod %23 %203 %6 -%226 = OpBitcast %24 %225 -%227 = OpImageQuerySizeLod %117 %204 %12 -%228 = OpBitcast %22 %227 -%229 = OpVectorShuffle %24 %228 %228 0 0 -%230 = OpImageQuerySizeLod %117 %204 %6 -%231 = OpBitcast %22 %230 -%232 = OpVectorShuffle %24 %231 %231 0 0 -%233 = OpImageQuerySizeLod %117 %205 %12 -%234 = OpBitcast %22 %233 -%235 = OpImageQuerySizeLod %117 %205 %6 -%236 = OpBitcast %22 %235 -%237 = OpImageQuerySize %23 %206 -%238 = OpBitcast %24 %237 -%239 = OpCompositeExtract %13 %214 1 -%240 = OpIAdd %13 %209 %239 -%241 = OpCompositeExtract %13 %216 1 -%242 = OpIAdd %13 %240 %241 -%243 = OpCompositeExtract %13 %219 1 -%244 = OpIAdd %13 %242 %243 -%245 = OpCompositeExtract %13 %222 1 -%246 = OpIAdd %13 %244 %245 -%247 = OpCompositeExtract %13 %224 1 -%248 = OpIAdd %13 %246 %247 -%249 = OpCompositeExtract %13 %226 1 -%250 = OpIAdd %13 %248 %249 -%251 = OpCompositeExtract %13 %229 1 -%252 = OpIAdd %13 %250 %251 -%253 = OpCompositeExtract %13 %232 1 -%254 = OpIAdd %13 %252 %253 -%255 = OpCompositeExtract %13 %234 2 -%256 = OpIAdd %13 %254 %255 -%257 = OpCompositeExtract %13 %236 2 -%258 = OpIAdd %13 %256 %257 -%259 = OpConvertUToF %8 %258 -%260 = OpCompositeConstruct %34 %259 %259 %259 %259 -OpStore %197 %260 +%194 = OpFunction %2 None %83 +%191 = OpLabel +%195 = OpLoad %19 %51 +%196 = OpLoad %20 %53 +%197 = OpLoad %22 %58 +%198 = OpLoad %23 %60 +%199 = OpLoad %24 %62 +%200 = OpLoad %25 %64 +%201 = OpLoad %26 %66 +OpBranch %202 +%202 = OpLabel +%204 = OpImageQuerySizeLod %4 %195 %203 +%205 = OpBitcast %7 %204 +%206 = OpBitcast %4 %205 +%207 = OpImageQuerySizeLod %4 %195 %206 +%208 = OpBitcast %7 %207 +%209 = OpImageQuerySizeLod %16 %196 %203 +%210 = OpBitcast %17 %209 +%211 = OpImageQuerySizeLod %16 %196 %5 +%212 = OpBitcast %17 %211 +%213 = OpImageQuerySizeLod %112 %197 %203 +%214 = OpBitcast %15 %213 +%215 = OpVectorShuffle %17 %214 %214 0 1 +%216 = OpImageQuerySizeLod %112 %197 %5 +%217 = OpBitcast %15 %216 +%218 = OpVectorShuffle %17 %217 %217 0 1 +%219 = OpImageQuerySizeLod %16 %198 %203 +%220 = OpBitcast %17 %219 +%221 = OpImageQuerySizeLod %16 %198 %5 +%222 = OpBitcast %17 %221 +%223 = OpImageQuerySizeLod %112 %199 %203 +%224 = OpBitcast %15 %223 +%225 = OpVectorShuffle %17 %224 %224 0 0 +%226 = OpImageQuerySizeLod %112 %199 %5 +%227 = OpBitcast %15 %226 +%228 = OpVectorShuffle %17 %227 %227 0 0 +%229 = OpImageQuerySizeLod %112 %200 %203 +%230 = OpBitcast %15 %229 +%231 = OpImageQuerySizeLod %112 %200 %5 +%232 = OpBitcast %15 %231 +%233 = OpImageQuerySize %16 %201 +%234 = OpBitcast %17 %233 +%235 = OpCompositeExtract %7 %210 1 +%236 = OpIAdd %7 %205 %235 +%237 = OpCompositeExtract %7 %212 1 +%238 = OpIAdd %7 %236 %237 +%239 = OpCompositeExtract %7 %215 1 +%240 = OpIAdd %7 %238 %239 +%241 = OpCompositeExtract %7 %218 1 +%242 = OpIAdd %7 %240 %241 +%243 = OpCompositeExtract %7 %220 1 +%244 = OpIAdd %7 %242 %243 +%245 = OpCompositeExtract %7 %222 1 +%246 = OpIAdd %7 %244 %245 +%247 = OpCompositeExtract %7 %225 1 +%248 = OpIAdd %7 %246 %247 +%249 = OpCompositeExtract %7 %228 1 +%250 = OpIAdd %7 %248 %249 +%251 = OpCompositeExtract %7 %230 2 +%252 = OpIAdd %7 %250 %251 +%253 = OpCompositeExtract %7 %232 2 +%254 = OpIAdd %7 %252 %253 +%255 = OpConvertUToF %10 %254 +%256 = OpCompositeConstruct %27 %255 %255 %255 %255 +OpStore %192 %256 OpReturn OpFunctionEnd -%263 = OpFunction %2 None %90 -%261 = OpLabel -%264 = OpLoad %27 %60 -%265 = OpLoad %29 %65 -%266 = OpLoad %30 %67 -%267 = OpLoad %31 %69 -%268 = OpLoad %32 %71 -%269 = OpLoad %33 %73 -OpBranch %270 -%270 = OpLabel -%271 = OpImageQueryLevels %4 %264 -%272 = OpBitcast %13 %271 -%273 = OpImageQueryLevels %4 %265 -%274 = OpBitcast %13 %273 -%275 = OpImageQuerySizeLod %117 %265 %12 -%276 = OpCompositeExtract %4 %275 2 -%277 = OpBitcast %13 %276 -%278 = OpImageQueryLevels %4 %266 -%279 = OpBitcast %13 %278 -%280 = OpImageQueryLevels %4 %267 -%281 = OpBitcast %13 %280 -%282 = OpImageQuerySizeLod %117 %267 %12 -%283 = OpCompositeExtract %4 %282 2 -%284 = OpBitcast %13 %283 -%285 = OpImageQueryLevels %4 %268 -%286 = OpBitcast %13 %285 -%287 = OpImageQuerySamples %4 %269 -%288 = OpBitcast %13 %287 -%289 = OpIAdd %13 %277 %284 -%290 = OpIAdd %13 %289 %288 -%291 = OpIAdd %13 %290 %272 -%292 = OpIAdd %13 %291 %274 -%293 = OpIAdd %13 %292 %286 -%294 = OpIAdd %13 %293 %279 -%295 = OpIAdd %13 %294 %281 -%296 = OpConvertUToF %8 %295 -%297 = OpCompositeConstruct %34 %296 %296 %296 %296 -OpStore %262 %297 +%259 = OpFunction %2 None %83 +%257 = OpLabel +%260 = OpLoad %20 %53 +%261 = OpLoad %22 %58 +%262 = OpLoad %23 %60 +%263 = OpLoad %24 %62 +%264 = OpLoad %25 %64 +%265 = OpLoad %26 %66 +OpBranch %266 +%266 = OpLabel +%267 = OpImageQueryLevels %4 %260 +%268 = OpBitcast %7 %267 +%269 = OpImageQueryLevels %4 %261 +%270 = OpBitcast %7 %269 +%271 = OpImageQuerySizeLod %112 %261 %203 +%272 = OpCompositeExtract %4 %271 2 +%273 = OpBitcast %7 %272 +%274 = OpImageQueryLevels %4 %262 +%275 = OpBitcast %7 %274 +%276 = OpImageQueryLevels %4 %263 +%277 = OpBitcast %7 %276 +%278 = OpImageQuerySizeLod %112 %263 %203 +%279 = OpCompositeExtract %4 %278 2 +%280 = OpBitcast %7 %279 +%281 = OpImageQueryLevels %4 %264 +%282 = OpBitcast %7 %281 +%283 = OpImageQuerySamples %4 %265 +%284 = OpBitcast %7 %283 +%285 = OpIAdd %7 %273 %280 +%286 = OpIAdd %7 %285 %284 +%287 = OpIAdd %7 %286 %268 +%288 = OpIAdd %7 %287 %270 +%289 = OpIAdd %7 %288 %282 +%290 = OpIAdd %7 %289 %275 +%291 = OpIAdd %7 %290 %277 +%292 = OpConvertUToF %10 %291 +%293 = OpCompositeConstruct %27 %292 %292 %292 %292 +OpStore %258 %293 OpReturn OpFunctionEnd -%303 = OpFunction %2 None %90 -%301 = OpLabel -%298 = OpVariable %299 Function %300 -%304 = OpLoad %26 %58 -%305 = OpLoad %27 %60 -%306 = OpLoad %29 %65 -%307 = OpLoad %31 %69 -%308 = OpLoad %35 %75 +%299 = OpFunction %2 None %83 +%297 = OpLabel +%294 = OpVariable %295 Function %296 +%300 = OpLoad %19 %51 +%301 = OpLoad %20 %53 +%302 = OpLoad %22 %58 +%303 = OpLoad %24 %62 +%304 = OpLoad %28 %68 OpBranch %309 %309 = OpLabel -%310 = OpCompositeConstruct %36 %7 %7 -%311 = OpCompositeConstruct %37 %7 %7 %7 -%312 = OpCompositeExtract %8 %310 0 -%314 = OpSampledImage %313 %304 %308 -%315 = OpImageSampleImplicitLod %34 %314 %312 -%316 = OpLoad %34 %298 -%317 = OpFAdd %34 %316 %315 -OpStore %298 %317 -%319 = OpSampledImage %318 %305 %308 -%320 = OpImageSampleImplicitLod %34 %319 %310 -%321 = OpLoad %34 %298 -%322 = OpFAdd %34 %321 %320 -OpStore %298 %322 -%323 = OpSampledImage %318 %305 %308 -%324 = OpImageSampleImplicitLod %34 %323 %310 ConstOffset %41 -%325 = OpLoad %34 %298 -%326 = OpFAdd %34 %325 %324 -OpStore %298 %326 -%327 = OpSampledImage %318 %305 %308 -%328 = OpImageSampleExplicitLod %34 %327 %310 Lod %9 -%329 = OpLoad %34 %298 -%330 = OpFAdd %34 %329 %328 -OpStore %298 %330 -%331 = OpSampledImage %318 %305 %308 -%332 = OpImageSampleExplicitLod %34 %331 %310 Lod|ConstOffset %9 %41 -%333 = OpLoad %34 %298 -%334 = OpFAdd %34 %333 %332 -OpStore %298 %334 -%335 = OpSampledImage %318 %305 %308 -%336 = OpImageSampleImplicitLod %34 %335 %310 Bias|ConstOffset %11 %41 -%337 = OpLoad %34 %298 -%338 = OpFAdd %34 %337 %336 -OpStore %298 %338 -%340 = OpConvertUToF %8 %12 -%341 = OpCompositeConstruct %37 %310 %340 -%342 = OpSampledImage %339 %306 %308 -%343 = OpImageSampleImplicitLod %34 %342 %341 -%344 = OpLoad %34 %298 -%345 = OpFAdd %34 %344 %343 -OpStore %298 %345 -%346 = OpConvertUToF %8 %12 -%347 = OpCompositeConstruct %37 %310 %346 -%348 = OpSampledImage %339 %306 %308 -%349 = OpImageSampleImplicitLod %34 %348 %347 ConstOffset %41 -%350 = OpLoad %34 %298 -%351 = OpFAdd %34 %350 %349 -OpStore %298 %351 -%352 = OpConvertUToF %8 %12 -%353 = OpCompositeConstruct %37 %310 %352 -%354 = OpSampledImage %339 %306 %308 -%355 = OpImageSampleExplicitLod %34 %354 %353 Lod %9 -%356 = OpLoad %34 %298 -%357 = OpFAdd %34 %356 %355 -OpStore %298 %357 -%358 = OpConvertUToF %8 %12 -%359 = OpCompositeConstruct %37 %310 %358 -%360 = OpSampledImage %339 %306 %308 -%361 = OpImageSampleExplicitLod %34 %360 %359 Lod|ConstOffset %9 %41 -%362 = OpLoad %34 %298 -%363 = OpFAdd %34 %362 %361 -OpStore %298 %363 -%364 = OpConvertUToF %8 %12 -%365 = OpCompositeConstruct %37 %310 %364 -%366 = OpSampledImage %339 %306 %308 -%367 = OpImageSampleImplicitLod %34 %366 %365 Bias|ConstOffset %11 %41 -%368 = OpLoad %34 %298 -%369 = OpFAdd %34 %368 %367 -OpStore %298 %369 -%370 = OpConvertSToF %8 %14 -%371 = OpCompositeConstruct %37 %310 %370 -%372 = OpSampledImage %339 %306 %308 -%373 = OpImageSampleImplicitLod %34 %372 %371 -%374 = OpLoad %34 %298 -%375 = OpFAdd %34 %374 %373 -OpStore %298 %375 -%376 = OpConvertSToF %8 %14 -%377 = OpCompositeConstruct %37 %310 %376 -%378 = OpSampledImage %339 %306 %308 -%379 = OpImageSampleImplicitLod %34 %378 %377 ConstOffset %41 -%380 = OpLoad %34 %298 -%381 = OpFAdd %34 %380 %379 -OpStore %298 %381 -%382 = OpConvertSToF %8 %14 -%383 = OpCompositeConstruct %37 %310 %382 -%384 = OpSampledImage %339 %306 %308 -%385 = OpImageSampleExplicitLod %34 %384 %383 Lod %9 -%386 = OpLoad %34 %298 -%387 = OpFAdd %34 %386 %385 -OpStore %298 %387 -%388 = OpConvertSToF %8 %14 -%389 = OpCompositeConstruct %37 %310 %388 -%390 = OpSampledImage %339 %306 %308 -%391 = OpImageSampleExplicitLod %34 %390 %389 Lod|ConstOffset %9 %41 -%392 = OpLoad %34 %298 -%393 = OpFAdd %34 %392 %391 -OpStore %298 %393 -%394 = OpConvertSToF %8 %14 -%395 = OpCompositeConstruct %37 %310 %394 -%396 = OpSampledImage %339 %306 %308 -%397 = OpImageSampleImplicitLod %34 %396 %395 Bias|ConstOffset %11 %41 -%398 = OpLoad %34 %298 -%399 = OpFAdd %34 %398 %397 -OpStore %298 %399 -%401 = OpConvertUToF %8 %12 -%402 = OpCompositeConstruct %34 %311 %401 -%403 = OpSampledImage %400 %307 %308 -%404 = OpImageSampleImplicitLod %34 %403 %402 -%405 = OpLoad %34 %298 -%406 = OpFAdd %34 %405 %404 -OpStore %298 %406 -%407 = OpConvertUToF %8 %12 -%408 = OpCompositeConstruct %34 %311 %407 -%409 = OpSampledImage %400 %307 %308 -%410 = OpImageSampleExplicitLod %34 %409 %408 Lod %9 -%411 = OpLoad %34 %298 -%412 = OpFAdd %34 %411 %410 -OpStore %298 %412 -%413 = OpConvertUToF %8 %12 -%414 = OpCompositeConstruct %34 %311 %413 -%415 = OpSampledImage %400 %307 %308 -%416 = OpImageSampleImplicitLod %34 %415 %414 Bias %11 -%417 = OpLoad %34 %298 -%418 = OpFAdd %34 %417 %416 -OpStore %298 %418 -%419 = OpConvertSToF %8 %14 -%420 = OpCompositeConstruct %34 %311 %419 -%421 = OpSampledImage %400 %307 %308 -%422 = OpImageSampleImplicitLod %34 %421 %420 -%423 = OpLoad %34 %298 -%424 = OpFAdd %34 %423 %422 -OpStore %298 %424 -%425 = OpConvertSToF %8 %14 -%426 = OpCompositeConstruct %34 %311 %425 -%427 = OpSampledImage %400 %307 %308 -%428 = OpImageSampleExplicitLod %34 %427 %426 Lod %9 -%429 = OpLoad %34 %298 -%430 = OpFAdd %34 %429 %428 -OpStore %298 %430 -%431 = OpConvertSToF %8 %14 -%432 = OpCompositeConstruct %34 %311 %431 -%433 = OpSampledImage %400 %307 %308 -%434 = OpImageSampleImplicitLod %34 %433 %432 Bias %11 -%435 = OpLoad %34 %298 -%436 = OpFAdd %34 %435 %434 -OpStore %298 %436 -%437 = OpLoad %34 %298 -OpStore %302 %437 +%310 = OpCompositeConstruct %29 %305 %305 +%311 = OpCompositeConstruct %30 %305 %305 %305 +%312 = OpCompositeExtract %10 %310 0 +%314 = OpSampledImage %313 %300 %304 +%315 = OpImageSampleImplicitLod %27 %314 %312 +%316 = OpLoad %27 %294 +%317 = OpFAdd %27 %316 %315 +OpStore %294 %317 +%319 = OpSampledImage %318 %301 %304 +%320 = OpImageSampleImplicitLod %27 %319 %310 +%321 = OpLoad %27 %294 +%322 = OpFAdd %27 %321 %320 +OpStore %294 %322 +%323 = OpSampledImage %318 %301 %304 +%324 = OpImageSampleImplicitLod %27 %323 %310 ConstOffset %34 +%325 = OpLoad %27 %294 +%326 = OpFAdd %27 %325 %324 +OpStore %294 %326 +%327 = OpSampledImage %318 %301 %304 +%328 = OpImageSampleExplicitLod %27 %327 %310 Lod %306 +%329 = OpLoad %27 %294 +%330 = OpFAdd %27 %329 %328 +OpStore %294 %330 +%331 = OpSampledImage %318 %301 %304 +%332 = OpImageSampleExplicitLod %27 %331 %310 Lod|ConstOffset %306 %34 +%333 = OpLoad %27 %294 +%334 = OpFAdd %27 %333 %332 +OpStore %294 %334 +%335 = OpSampledImage %318 %301 %304 +%336 = OpImageSampleImplicitLod %27 %335 %310 Bias|ConstOffset %307 %34 +%337 = OpLoad %27 %294 +%338 = OpFAdd %27 %337 %336 +OpStore %294 %338 +%340 = OpConvertUToF %10 %203 +%341 = OpCompositeConstruct %30 %310 %340 +%342 = OpSampledImage %339 %302 %304 +%343 = OpImageSampleImplicitLod %27 %342 %341 +%344 = OpLoad %27 %294 +%345 = OpFAdd %27 %344 %343 +OpStore %294 %345 +%346 = OpConvertUToF %10 %203 +%347 = OpCompositeConstruct %30 %310 %346 +%348 = OpSampledImage %339 %302 %304 +%349 = OpImageSampleImplicitLod %27 %348 %347 ConstOffset %34 +%350 = OpLoad %27 %294 +%351 = OpFAdd %27 %350 %349 +OpStore %294 %351 +%352 = OpConvertUToF %10 %203 +%353 = OpCompositeConstruct %30 %310 %352 +%354 = OpSampledImage %339 %302 %304 +%355 = OpImageSampleExplicitLod %27 %354 %353 Lod %306 +%356 = OpLoad %27 %294 +%357 = OpFAdd %27 %356 %355 +OpStore %294 %357 +%358 = OpConvertUToF %10 %203 +%359 = OpCompositeConstruct %30 %310 %358 +%360 = OpSampledImage %339 %302 %304 +%361 = OpImageSampleExplicitLod %27 %360 %359 Lod|ConstOffset %306 %34 +%362 = OpLoad %27 %294 +%363 = OpFAdd %27 %362 %361 +OpStore %294 %363 +%364 = OpConvertUToF %10 %203 +%365 = OpCompositeConstruct %30 %310 %364 +%366 = OpSampledImage %339 %302 %304 +%367 = OpImageSampleImplicitLod %27 %366 %365 Bias|ConstOffset %307 %34 +%368 = OpLoad %27 %294 +%369 = OpFAdd %27 %368 %367 +OpStore %294 %369 +%370 = OpConvertSToF %10 %308 +%371 = OpCompositeConstruct %30 %310 %370 +%372 = OpSampledImage %339 %302 %304 +%373 = OpImageSampleImplicitLod %27 %372 %371 +%374 = OpLoad %27 %294 +%375 = OpFAdd %27 %374 %373 +OpStore %294 %375 +%376 = OpConvertSToF %10 %308 +%377 = OpCompositeConstruct %30 %310 %376 +%378 = OpSampledImage %339 %302 %304 +%379 = OpImageSampleImplicitLod %27 %378 %377 ConstOffset %34 +%380 = OpLoad %27 %294 +%381 = OpFAdd %27 %380 %379 +OpStore %294 %381 +%382 = OpConvertSToF %10 %308 +%383 = OpCompositeConstruct %30 %310 %382 +%384 = OpSampledImage %339 %302 %304 +%385 = OpImageSampleExplicitLod %27 %384 %383 Lod %306 +%386 = OpLoad %27 %294 +%387 = OpFAdd %27 %386 %385 +OpStore %294 %387 +%388 = OpConvertSToF %10 %308 +%389 = OpCompositeConstruct %30 %310 %388 +%390 = OpSampledImage %339 %302 %304 +%391 = OpImageSampleExplicitLod %27 %390 %389 Lod|ConstOffset %306 %34 +%392 = OpLoad %27 %294 +%393 = OpFAdd %27 %392 %391 +OpStore %294 %393 +%394 = OpConvertSToF %10 %308 +%395 = OpCompositeConstruct %30 %310 %394 +%396 = OpSampledImage %339 %302 %304 +%397 = OpImageSampleImplicitLod %27 %396 %395 Bias|ConstOffset %307 %34 +%398 = OpLoad %27 %294 +%399 = OpFAdd %27 %398 %397 +OpStore %294 %399 +%401 = OpConvertUToF %10 %203 +%402 = OpCompositeConstruct %27 %311 %401 +%403 = OpSampledImage %400 %303 %304 +%404 = OpImageSampleImplicitLod %27 %403 %402 +%405 = OpLoad %27 %294 +%406 = OpFAdd %27 %405 %404 +OpStore %294 %406 +%407 = OpConvertUToF %10 %203 +%408 = OpCompositeConstruct %27 %311 %407 +%409 = OpSampledImage %400 %303 %304 +%410 = OpImageSampleExplicitLod %27 %409 %408 Lod %306 +%411 = OpLoad %27 %294 +%412 = OpFAdd %27 %411 %410 +OpStore %294 %412 +%413 = OpConvertUToF %10 %203 +%414 = OpCompositeConstruct %27 %311 %413 +%415 = OpSampledImage %400 %303 %304 +%416 = OpImageSampleImplicitLod %27 %415 %414 Bias %307 +%417 = OpLoad %27 %294 +%418 = OpFAdd %27 %417 %416 +OpStore %294 %418 +%419 = OpConvertSToF %10 %308 +%420 = OpCompositeConstruct %27 %311 %419 +%421 = OpSampledImage %400 %303 %304 +%422 = OpImageSampleImplicitLod %27 %421 %420 +%423 = OpLoad %27 %294 +%424 = OpFAdd %27 %423 %422 +OpStore %294 %424 +%425 = OpConvertSToF %10 %308 +%426 = OpCompositeConstruct %27 %311 %425 +%427 = OpSampledImage %400 %303 %304 +%428 = OpImageSampleExplicitLod %27 %427 %426 Lod %306 +%429 = OpLoad %27 %294 +%430 = OpFAdd %27 %429 %428 +OpStore %294 %430 +%431 = OpConvertSToF %10 %308 +%432 = OpCompositeConstruct %27 %311 %431 +%433 = OpSampledImage %400 %303 %304 +%434 = OpImageSampleImplicitLod %27 %433 %432 Bias %307 +%435 = OpLoad %27 %294 +%436 = OpFAdd %27 %435 %434 +OpStore %294 %436 +%437 = OpLoad %27 %294 +OpStore %298 %437 OpReturn OpFunctionEnd -%444 = OpFunction %2 None %90 +%444 = OpFunction %2 None %83 %441 = OpLabel %438 = OpVariable %439 Function %440 -%445 = OpLoad %35 %77 -%446 = OpLoad %38 %79 -%447 = OpLoad %39 %81 -%448 = OpLoad %40 %83 +%445 = OpLoad %28 %70 +%446 = OpLoad %31 %72 +%447 = OpLoad %32 %74 +%448 = OpLoad %33 %76 OpBranch %449 %449 = OpLabel -%450 = OpCompositeConstruct %36 %7 %7 -%451 = OpCompositeConstruct %37 %7 %7 %7 +%450 = OpCompositeConstruct %29 %305 %305 +%451 = OpCompositeConstruct %30 %305 %305 %305 %453 = OpSampledImage %452 %446 %445 -%454 = OpImageSampleDrefImplicitLod %8 %453 %450 %7 -%455 = OpLoad %8 %438 -%456 = OpFAdd %8 %455 %454 +%454 = OpImageSampleDrefImplicitLod %10 %453 %450 %305 +%455 = OpLoad %10 %438 +%456 = OpFAdd %10 %455 %454 OpStore %438 %456 -%458 = OpConvertUToF %8 %12 -%459 = OpCompositeConstruct %37 %450 %458 +%458 = OpConvertUToF %10 %203 +%459 = OpCompositeConstruct %30 %450 %458 %460 = OpSampledImage %457 %447 %445 -%461 = OpImageSampleDrefImplicitLod %8 %460 %459 %7 -%462 = OpLoad %8 %438 -%463 = OpFAdd %8 %462 %461 +%461 = OpImageSampleDrefImplicitLod %10 %460 %459 %305 +%462 = OpLoad %10 %438 +%463 = OpFAdd %10 %462 %461 OpStore %438 %463 -%464 = OpConvertSToF %8 %14 -%465 = OpCompositeConstruct %37 %450 %464 +%464 = OpConvertSToF %10 %308 +%465 = OpCompositeConstruct %30 %450 %464 %466 = OpSampledImage %457 %447 %445 -%467 = OpImageSampleDrefImplicitLod %8 %466 %465 %7 -%468 = OpLoad %8 %438 -%469 = OpFAdd %8 %468 %467 +%467 = OpImageSampleDrefImplicitLod %10 %466 %465 %305 +%468 = OpLoad %10 %438 +%469 = OpFAdd %10 %468 %467 OpStore %438 %469 %471 = OpSampledImage %470 %448 %445 -%472 = OpImageSampleDrefImplicitLod %8 %471 %451 %7 -%473 = OpLoad %8 %438 -%474 = OpFAdd %8 %473 %472 +%472 = OpImageSampleDrefImplicitLod %10 %471 %451 %305 +%473 = OpLoad %10 %438 +%474 = OpFAdd %10 %473 %472 OpStore %438 %474 %475 = OpSampledImage %452 %446 %445 -%476 = OpImageSampleDrefExplicitLod %8 %475 %450 %7 Lod %477 -%478 = OpLoad %8 %438 -%479 = OpFAdd %8 %478 %476 +%476 = OpImageSampleDrefExplicitLod %10 %475 %450 %305 Lod %477 +%478 = OpLoad %10 %438 +%479 = OpFAdd %10 %478 %476 OpStore %438 %479 -%480 = OpConvertUToF %8 %12 -%481 = OpCompositeConstruct %37 %450 %480 +%480 = OpConvertUToF %10 %203 +%481 = OpCompositeConstruct %30 %450 %480 %482 = OpSampledImage %457 %447 %445 -%483 = OpImageSampleDrefExplicitLod %8 %482 %481 %7 Lod %477 -%484 = OpLoad %8 %438 -%485 = OpFAdd %8 %484 %483 +%483 = OpImageSampleDrefExplicitLod %10 %482 %481 %305 Lod %477 +%484 = OpLoad %10 %438 +%485 = OpFAdd %10 %484 %483 OpStore %438 %485 -%486 = OpConvertSToF %8 %14 -%487 = OpCompositeConstruct %37 %450 %486 +%486 = OpConvertSToF %10 %308 +%487 = OpCompositeConstruct %30 %450 %486 %488 = OpSampledImage %457 %447 %445 -%489 = OpImageSampleDrefExplicitLod %8 %488 %487 %7 Lod %477 -%490 = OpLoad %8 %438 -%491 = OpFAdd %8 %490 %489 +%489 = OpImageSampleDrefExplicitLod %10 %488 %487 %305 Lod %477 +%490 = OpLoad %10 %438 +%491 = OpFAdd %10 %490 %489 OpStore %438 %491 %492 = OpSampledImage %470 %448 %445 -%493 = OpImageSampleDrefExplicitLod %8 %492 %451 %7 Lod %477 -%494 = OpLoad %8 %438 -%495 = OpFAdd %8 %494 %493 +%493 = OpImageSampleDrefExplicitLod %10 %492 %451 %305 Lod %477 +%494 = OpLoad %10 %438 +%495 = OpFAdd %10 %494 %493 OpStore %438 %495 -%496 = OpLoad %8 %438 +%496 = OpLoad %10 %438 OpStore %442 %496 OpReturn OpFunctionEnd -%499 = OpFunction %2 None %90 +%499 = OpFunction %2 None %83 %497 = OpLabel -%500 = OpLoad %27 %60 -%501 = OpLoad %15 %62 -%502 = OpLoad %28 %63 -%503 = OpLoad %35 %75 -%504 = OpLoad %35 %77 -%505 = OpLoad %38 %79 +%500 = OpLoad %20 %53 +%501 = OpLoad %6 %55 +%502 = OpLoad %21 %56 +%503 = OpLoad %28 %68 +%504 = OpLoad %28 %70 +%505 = OpLoad %31 %72 OpBranch %506 %506 = OpLabel -%507 = OpCompositeConstruct %36 %7 %7 +%507 = OpCompositeConstruct %29 %305 %305 %508 = OpSampledImage %318 %500 %503 -%509 = OpImageGather %34 %508 %507 %510 +%509 = OpImageGather %27 %508 %507 %510 %511 = OpSampledImage %318 %500 %503 -%512 = OpImageGather %34 %511 %507 %513 ConstOffset %41 +%512 = OpImageGather %27 %511 %507 %513 ConstOffset %34 %514 = OpSampledImage %452 %505 %504 -%515 = OpImageDrefGather %34 %514 %507 %7 +%515 = OpImageDrefGather %27 %514 %507 %305 %516 = OpSampledImage %452 %505 %504 -%517 = OpImageDrefGather %34 %516 %507 %7 ConstOffset %41 +%517 = OpImageDrefGather %27 %516 %507 %305 ConstOffset %34 %519 = OpSampledImage %518 %501 %503 -%520 = OpImageGather %25 %519 %507 %12 +%520 = OpImageGather %18 %519 %507 %203 %523 = OpSampledImage %522 %502 %503 -%524 = OpImageGather %521 %523 %507 %12 -%525 = OpConvertUToF %34 %520 -%526 = OpConvertSToF %34 %524 -%527 = OpFAdd %34 %525 %526 -%528 = OpFAdd %34 %509 %512 -%529 = OpFAdd %34 %528 %515 -%530 = OpFAdd %34 %529 %517 -%531 = OpFAdd %34 %530 %527 +%524 = OpImageGather %521 %523 %507 %203 +%525 = OpConvertUToF %27 %520 +%526 = OpConvertSToF %27 %524 +%527 = OpFAdd %27 %525 %526 +%528 = OpFAdd %27 %509 %512 +%529 = OpFAdd %27 %528 %515 +%530 = OpFAdd %27 %529 %517 +%531 = OpFAdd %27 %530 %527 OpStore %498 %531 OpReturn OpFunctionEnd -%534 = OpFunction %2 None %90 +%534 = OpFunction %2 None %83 %532 = OpLabel -%535 = OpLoad %35 %75 -%536 = OpLoad %38 %79 +%535 = OpLoad %28 %68 +%536 = OpLoad %31 %72 OpBranch %537 %537 = OpLabel -%538 = OpCompositeConstruct %36 %7 %7 +%538 = OpCompositeConstruct %29 %305 %305 %539 = OpSampledImage %452 %536 %535 -%540 = OpImageSampleImplicitLod %34 %539 %538 -%541 = OpCompositeExtract %8 %540 0 +%540 = OpImageSampleImplicitLod %27 %539 %538 +%541 = OpCompositeExtract %10 %540 0 %542 = OpSampledImage %452 %536 %535 -%543 = OpImageGather %34 %542 %538 %12 -%544 = OpCompositeConstruct %34 %541 %541 %541 %541 -%545 = OpFAdd %34 %544 %543 +%543 = OpImageGather %27 %542 %538 %203 +%544 = OpCompositeConstruct %27 %541 %541 %541 %541 +%545 = OpFAdd %27 %544 %543 OpStore %533 %545 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index a37437a96..f42fb1255 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -1,88 +1,85 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 58 +; Bound: 55 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %35 "compute" %23 %26 %28 %31 %33 -OpExecutionMode %35 LocalSize 1 1 1 +OpEntryPoint GLCompute %30 "compute" %18 %21 %23 %26 %28 +OpExecutionMode %30 LocalSize 1 1 1 +OpMemberDecorate %7 0 Offset 0 +OpMemberDecorate %7 1 Offset 16 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 4 +OpMemberDecorate %9 2 Offset 8 +OpDecorate %11 ArrayStride 4 OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 16 OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 1 Offset 4 -OpMemberDecorate %14 2 Offset 8 -OpDecorate %16 ArrayStride 4 -OpMemberDecorate %18 0 Offset 0 -OpMemberDecorate %19 0 Offset 0 -OpDecorate %23 BuiltIn GlobalInvocationId -OpDecorate %26 BuiltIn LocalInvocationId -OpDecorate %28 BuiltIn LocalInvocationIndex -OpDecorate %31 BuiltIn WorkgroupId -OpDecorate %33 BuiltIn NumWorkgroups +OpDecorate %18 BuiltIn GlobalInvocationId +OpDecorate %21 BuiltIn LocalInvocationId +OpDecorate %23 BuiltIn LocalInvocationIndex +OpDecorate %26 BuiltIn WorkgroupId +OpDecorate %28 BuiltIn NumWorkgroups %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 1.0 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 1 -%7 = OpConstant %4 0.0 -%9 = OpTypeInt 32 1 -%8 = OpConstant %9 1 -%10 = OpConstant %9 0 -%11 = OpConstant %6 2 -%12 = OpTypeVector %4 4 -%13 = OpTypeStruct %12 %4 -%14 = OpTypeStruct %4 %6 %4 -%15 = OpTypeBool -%16 = OpTypeArray %6 %8 -%17 = OpTypeVector %6 3 -%18 = OpTypeStruct %6 -%19 = OpTypeStruct %6 -%21 = OpTypePointer Workgroup %16 -%20 = OpVariable %21 Workgroup -%24 = OpTypePointer Input %17 +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 1 +%6 = OpTypeFloat 32 +%5 = OpTypeVector %6 4 +%7 = OpTypeStruct %5 %6 +%8 = OpTypeInt 32 0 +%9 = OpTypeStruct %6 %8 %6 +%10 = OpTypeBool +%11 = OpTypeArray %8 %3 +%12 = OpTypeVector %8 3 +%13 = OpTypeStruct %8 +%14 = OpTypeStruct %8 +%16 = OpTypePointer Workgroup %11 +%15 = OpVariable %16 Workgroup +%19 = OpTypePointer Input %12 +%18 = OpVariable %19 Input +%21 = OpVariable %19 Input +%24 = OpTypePointer Input %8 %23 = OpVariable %24 Input -%26 = OpVariable %24 Input -%29 = OpTypePointer Input %6 -%28 = OpVariable %29 Input -%31 = OpVariable %24 Input -%33 = OpVariable %24 Input -%36 = OpTypeFunction %2 -%38 = OpConstantNull %16 -%39 = OpConstantNull %17 -%40 = OpTypeVector %15 3 -%45 = OpConstant %6 264 -%47 = OpTypePointer Workgroup %6 -%56 = OpConstant %6 0 -%35 = OpFunction %2 None %36 -%22 = OpLabel -%25 = OpLoad %17 %23 -%27 = OpLoad %17 %26 -%30 = OpLoad %6 %28 -%32 = OpLoad %17 %31 -%34 = OpLoad %17 %33 -OpBranch %37 -%37 = OpLabel -%41 = OpIEqual %40 %27 %39 -%42 = OpAll %15 %41 -OpSelectionMerge %43 None -OpBranchConditional %42 %44 %43 -%44 = OpLabel -OpStore %20 %38 +%26 = OpVariable %19 Input +%28 = OpVariable %19 Input +%31 = OpTypeFunction %2 +%32 = OpConstant %4 0 +%34 = OpConstantNull %11 +%35 = OpConstantNull %12 +%36 = OpTypeVector %10 3 +%41 = OpConstant %8 2 +%42 = OpConstant %8 264 +%44 = OpTypePointer Workgroup %8 +%53 = OpConstant %8 0 +%30 = OpFunction %2 None %31 +%17 = OpLabel +%20 = OpLoad %12 %18 +%22 = OpLoad %12 %21 +%25 = OpLoad %8 %23 +%27 = OpLoad %12 %26 +%29 = OpLoad %12 %28 +OpBranch %33 +%33 = OpLabel +%37 = OpIEqual %36 %22 %35 +%38 = OpAll %10 %37 +OpSelectionMerge %39 None +OpBranchConditional %38 %40 %39 +%40 = OpLabel +OpStore %15 %34 +OpBranch %39 +%39 = OpLabel +OpControlBarrier %41 %41 %42 OpBranch %43 %43 = OpLabel -OpControlBarrier %11 %11 %45 -OpBranch %46 -%46 = OpLabel -%48 = OpCompositeExtract %6 %25 0 -%49 = OpCompositeExtract %6 %27 0 -%50 = OpIAdd %6 %48 %49 -%51 = OpIAdd %6 %50 %30 -%52 = OpCompositeExtract %6 %32 0 -%53 = OpIAdd %6 %51 %52 -%54 = OpCompositeExtract %6 %34 0 -%55 = OpIAdd %6 %53 %54 -%57 = OpAccessChain %47 %20 %56 -OpStore %57 %55 +%45 = OpCompositeExtract %8 %20 0 +%46 = OpCompositeExtract %8 %22 0 +%47 = OpIAdd %8 %45 %46 +%48 = OpIAdd %8 %47 %25 +%49 = OpCompositeExtract %8 %27 0 +%50 = OpIAdd %8 %48 %49 +%51 = OpCompositeExtract %8 %29 0 +%52 = OpIAdd %8 %50 %51 +%54 = OpAccessChain %44 %15 %53 +OpStore %54 %52 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 424208def..682fa7ca6 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -1,90 +1,88 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 54 +; Bound: 52 OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %41 "fragment" %22 %25 %28 %31 %34 %36 %38 %40 -OpExecutionMode %41 OriginUpperLeft -OpExecutionMode %41 DepthReplacing +OpEntryPoint Fragment %36 "fragment" %17 %20 %23 %26 %29 %31 %33 %35 +OpExecutionMode %36 OriginUpperLeft +OpExecutionMode %36 DepthReplacing +OpMemberDecorate %7 0 Offset 0 +OpMemberDecorate %7 1 Offset 16 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 4 +OpMemberDecorate %9 2 Offset 8 +OpDecorate %11 ArrayStride 4 OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 16 OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 1 Offset 4 -OpMemberDecorate %14 2 Offset 8 -OpDecorate %16 ArrayStride 4 -OpMemberDecorate %18 0 Offset 0 -OpMemberDecorate %19 0 Offset 0 -OpDecorate %22 Invariant -OpDecorate %22 BuiltIn FragCoord -OpDecorate %25 Location 1 -OpDecorate %28 BuiltIn FrontFacing -OpDecorate %28 Flat -OpDecorate %31 BuiltIn SampleId -OpDecorate %31 Flat -OpDecorate %34 BuiltIn SampleMask -OpDecorate %34 Flat -OpDecorate %36 BuiltIn FragDepth -OpDecorate %38 BuiltIn SampleMask -OpDecorate %40 Location 0 +OpDecorate %17 Invariant +OpDecorate %17 BuiltIn FragCoord +OpDecorate %20 Location 1 +OpDecorate %23 BuiltIn FrontFacing +OpDecorate %23 Flat +OpDecorate %26 BuiltIn SampleId +OpDecorate %26 Flat +OpDecorate %29 BuiltIn SampleMask +OpDecorate %29 Flat +OpDecorate %31 BuiltIn FragDepth +OpDecorate %33 BuiltIn SampleMask +OpDecorate %35 Location 0 %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 1.0 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 1 -%7 = OpConstant %4 0.0 -%9 = OpTypeInt 32 1 -%8 = OpConstant %9 1 -%10 = OpConstant %9 0 -%11 = OpConstant %6 2 -%12 = OpTypeVector %4 4 -%13 = OpTypeStruct %12 %4 -%14 = OpTypeStruct %4 %6 %4 -%15 = OpTypeBool -%16 = OpTypeArray %6 %8 -%17 = OpTypeVector %6 3 -%18 = OpTypeStruct %6 -%19 = OpTypeStruct %6 -%23 = OpTypePointer Input %12 -%22 = OpVariable %23 Input -%26 = OpTypePointer Input %4 -%25 = OpVariable %26 Input -%29 = OpTypePointer Input %15 -%28 = OpVariable %29 Input -%32 = OpTypePointer Input %6 -%31 = OpVariable %32 Input -%34 = OpVariable %32 Input -%37 = OpTypePointer Output %4 -%36 = OpVariable %37 Output -%39 = OpTypePointer Output %6 -%38 = OpVariable %39 Output -%40 = OpVariable %37 Output -%42 = OpTypeFunction %2 -%41 = OpFunction %2 None %42 -%20 = OpLabel -%24 = OpLoad %12 %22 -%27 = OpLoad %4 %25 -%21 = OpCompositeConstruct %13 %24 %27 -%30 = OpLoad %15 %28 -%33 = OpLoad %6 %31 -%35 = OpLoad %6 %34 -OpBranch %43 -%43 = OpLabel -%44 = OpShiftLeftLogical %6 %5 %33 -%45 = OpBitwiseAnd %6 %35 %44 -%46 = OpSelect %4 %30 %3 %7 -%47 = OpCompositeExtract %4 %21 1 -%48 = OpCompositeConstruct %14 %47 %45 %46 -%49 = OpCompositeExtract %4 %48 0 -OpStore %36 %49 -%50 = OpLoad %4 %36 -%51 = OpExtInst %4 %1 FClamp %50 %7 %3 -OpStore %36 %51 -%52 = OpCompositeExtract %6 %48 1 -OpStore %38 %52 -%53 = OpCompositeExtract %4 %48 2 -OpStore %40 %53 +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 1 +%6 = OpTypeFloat 32 +%5 = OpTypeVector %6 4 +%7 = OpTypeStruct %5 %6 +%8 = OpTypeInt 32 0 +%9 = OpTypeStruct %6 %8 %6 +%10 = OpTypeBool +%11 = OpTypeArray %8 %3 +%12 = OpTypeVector %8 3 +%13 = OpTypeStruct %8 +%14 = OpTypeStruct %8 +%18 = OpTypePointer Input %5 +%17 = OpVariable %18 Input +%21 = OpTypePointer Input %6 +%20 = OpVariable %21 Input +%24 = OpTypePointer Input %10 +%23 = OpVariable %24 Input +%27 = OpTypePointer Input %8 +%26 = OpVariable %27 Input +%29 = OpVariable %27 Input +%32 = OpTypePointer Output %6 +%31 = OpVariable %32 Output +%34 = OpTypePointer Output %8 +%33 = OpVariable %34 Output +%35 = OpVariable %32 Output +%37 = OpTypeFunction %2 +%38 = OpConstant %8 1 +%39 = OpConstant %6 0.0 +%40 = OpConstant %6 1.0 +%36 = OpFunction %2 None %37 +%15 = OpLabel +%19 = OpLoad %5 %17 +%22 = OpLoad %6 %20 +%16 = OpCompositeConstruct %7 %19 %22 +%25 = OpLoad %10 %23 +%28 = OpLoad %8 %26 +%30 = OpLoad %8 %29 +OpBranch %41 +%41 = OpLabel +%42 = OpShiftLeftLogical %8 %38 %28 +%43 = OpBitwiseAnd %8 %30 %42 +%44 = OpSelect %6 %25 %40 %39 +%45 = OpCompositeExtract %6 %16 1 +%46 = OpCompositeConstruct %9 %45 %43 %44 +%47 = OpCompositeExtract %6 %46 0 +OpStore %31 %47 +%48 = OpLoad %6 %31 +%49 = OpExtInst %6 %1 FClamp %48 %39 %40 +OpStore %31 %49 +%50 = OpCompositeExtract %8 %46 1 +OpStore %33 %50 +%51 = OpCompositeExtract %6 %46 2 +OpStore %35 %51 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index 62e4acb1b..f1b2bb51a 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -1,71 +1,67 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 44 +; Bound: 40 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %34 "vertex" %21 %24 %26 %28 %30 %32 +OpEntryPoint Vertex %30 "vertex" %16 %19 %21 %23 %25 %27 +OpMemberDecorate %7 0 Offset 0 +OpMemberDecorate %7 1 Offset 16 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 4 +OpMemberDecorate %9 2 Offset 8 +OpDecorate %11 ArrayStride 4 OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 16 OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 1 Offset 4 -OpMemberDecorate %14 2 Offset 8 -OpDecorate %16 ArrayStride 4 -OpMemberDecorate %18 0 Offset 0 -OpMemberDecorate %19 0 Offset 0 -OpDecorate %21 BuiltIn VertexIndex -OpDecorate %24 BuiltIn InstanceIndex -OpDecorate %26 Location 10 -OpDecorate %28 Invariant -OpDecorate %28 BuiltIn Position -OpDecorate %30 Location 1 -OpDecorate %32 BuiltIn PointSize +OpDecorate %16 BuiltIn VertexIndex +OpDecorate %19 BuiltIn InstanceIndex +OpDecorate %21 Location 10 +OpDecorate %23 Invariant +OpDecorate %23 BuiltIn Position +OpDecorate %25 Location 1 +OpDecorate %27 BuiltIn PointSize %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 1.0 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 1 -%7 = OpConstant %4 0.0 -%9 = OpTypeInt 32 1 -%8 = OpConstant %9 1 -%10 = OpConstant %9 0 -%11 = OpConstant %6 2 -%12 = OpTypeVector %4 4 -%13 = OpTypeStruct %12 %4 -%14 = OpTypeStruct %4 %6 %4 -%15 = OpTypeBool -%16 = OpTypeArray %6 %8 -%17 = OpTypeVector %6 3 -%18 = OpTypeStruct %6 -%19 = OpTypeStruct %6 -%22 = OpTypePointer Input %6 -%21 = OpVariable %22 Input -%24 = OpVariable %22 Input -%26 = OpVariable %22 Input -%29 = OpTypePointer Output %12 -%28 = OpVariable %29 Output -%31 = OpTypePointer Output %4 -%30 = OpVariable %31 Output -%33 = OpTypePointer Output %4 -%32 = OpVariable %33 Output -%35 = OpTypeFunction %2 -%34 = OpFunction %2 None %35 -%20 = OpLabel -%23 = OpLoad %6 %21 -%25 = OpLoad %6 %24 -%27 = OpLoad %6 %26 -OpStore %32 %3 -OpBranch %36 -%36 = OpLabel -%37 = OpIAdd %6 %23 %25 -%38 = OpIAdd %6 %37 %27 -%39 = OpCompositeConstruct %12 %3 %3 %3 %3 -%40 = OpConvertUToF %4 %38 -%41 = OpCompositeConstruct %13 %39 %40 -%42 = OpCompositeExtract %12 %41 0 -OpStore %28 %42 -%43 = OpCompositeExtract %4 %41 1 -OpStore %30 %43 +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 1 +%6 = OpTypeFloat 32 +%5 = OpTypeVector %6 4 +%7 = OpTypeStruct %5 %6 +%8 = OpTypeInt 32 0 +%9 = OpTypeStruct %6 %8 %6 +%10 = OpTypeBool +%11 = OpTypeArray %8 %3 +%12 = OpTypeVector %8 3 +%13 = OpTypeStruct %8 +%14 = OpTypeStruct %8 +%17 = OpTypePointer Input %8 +%16 = OpVariable %17 Input +%19 = OpVariable %17 Input +%21 = OpVariable %17 Input +%24 = OpTypePointer Output %5 +%23 = OpVariable %24 Output +%26 = OpTypePointer Output %6 +%25 = OpVariable %26 Output +%28 = OpTypePointer Output %6 +%27 = OpVariable %28 Output +%29 = OpConstant %6 1.0 +%31 = OpTypeFunction %2 +%30 = OpFunction %2 None %31 +%15 = OpLabel +%18 = OpLoad %8 %16 +%20 = OpLoad %8 %19 +%22 = OpLoad %8 %21 +OpStore %27 %29 +OpBranch %32 +%32 = OpLabel +%33 = OpIAdd %8 %18 %20 +%34 = OpIAdd %8 %33 %22 +%35 = OpCompositeConstruct %5 %29 %29 %29 %29 +%36 = OpConvertUToF %6 %34 +%37 = OpCompositeConstruct %7 %35 %36 +%38 = OpCompositeExtract %5 %37 0 +OpStore %23 %38 +%39 = OpCompositeExtract %6 %37 1 +OpStore %25 %39 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index 1455090ab..7c6c8fd1e 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -1,70 +1,68 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 45 +; Bound: 43 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %35 "vertex_two_structs" %25 %29 %31 %33 +OpEntryPoint Vertex %31 "vertex_two_structs" %20 %24 %26 %28 +OpMemberDecorate %7 0 Offset 0 +OpMemberDecorate %7 1 Offset 16 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 4 +OpMemberDecorate %9 2 Offset 8 +OpDecorate %11 ArrayStride 4 OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 16 OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 1 Offset 4 -OpMemberDecorate %14 2 Offset 8 -OpDecorate %16 ArrayStride 4 -OpMemberDecorate %18 0 Offset 0 -OpMemberDecorate %19 0 Offset 0 -OpDecorate %25 BuiltIn VertexIndex -OpDecorate %29 BuiltIn InstanceIndex -OpDecorate %31 Invariant -OpDecorate %31 BuiltIn Position -OpDecorate %33 BuiltIn PointSize +OpDecorate %20 BuiltIn VertexIndex +OpDecorate %24 BuiltIn InstanceIndex +OpDecorate %26 Invariant +OpDecorate %26 BuiltIn Position +OpDecorate %28 BuiltIn PointSize %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 1.0 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 1 -%7 = OpConstant %4 0.0 -%9 = OpTypeInt 32 1 -%8 = OpConstant %9 1 -%10 = OpConstant %9 0 -%11 = OpConstant %6 2 -%12 = OpTypeVector %4 4 -%13 = OpTypeStruct %12 %4 -%14 = OpTypeStruct %4 %6 %4 -%15 = OpTypeBool -%16 = OpTypeArray %6 %8 -%17 = OpTypeVector %6 3 -%18 = OpTypeStruct %6 -%19 = OpTypeStruct %6 -%21 = OpTypePointer Function %6 -%22 = OpConstantNull %6 -%26 = OpTypePointer Input %6 -%25 = OpVariable %26 Input -%29 = OpVariable %26 Input -%32 = OpTypePointer Output %12 -%31 = OpVariable %32 Output -%34 = OpTypePointer Output %4 -%33 = OpVariable %34 Output -%36 = OpTypeFunction %2 -%35 = OpFunction %2 None %36 -%23 = OpLabel -%20 = OpVariable %21 Function %22 -%27 = OpLoad %6 %25 -%24 = OpCompositeConstruct %18 %27 -%30 = OpLoad %6 %29 -%28 = OpCompositeConstruct %19 %30 -OpStore %33 %3 -OpBranch %37 -%37 = OpLabel -OpStore %20 %11 -%38 = OpCompositeExtract %6 %24 0 -%39 = OpConvertUToF %4 %38 -%40 = OpCompositeExtract %6 %28 0 -%41 = OpConvertUToF %4 %40 -%42 = OpLoad %6 %20 -%43 = OpConvertUToF %4 %42 -%44 = OpCompositeConstruct %12 %39 %41 %43 %7 -OpStore %31 %44 +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 1 +%6 = OpTypeFloat 32 +%5 = OpTypeVector %6 4 +%7 = OpTypeStruct %5 %6 +%8 = OpTypeInt 32 0 +%9 = OpTypeStruct %6 %8 %6 +%10 = OpTypeBool +%11 = OpTypeArray %8 %3 +%12 = OpTypeVector %8 3 +%13 = OpTypeStruct %8 +%14 = OpTypeStruct %8 +%16 = OpTypePointer Function %8 +%17 = OpConstantNull %8 +%21 = OpTypePointer Input %8 +%20 = OpVariable %21 Input +%24 = OpVariable %21 Input +%27 = OpTypePointer Output %5 +%26 = OpVariable %27 Output +%29 = OpTypePointer Output %6 +%28 = OpVariable %29 Output +%30 = OpConstant %6 1.0 +%32 = OpTypeFunction %2 +%33 = OpConstant %8 2 +%34 = OpConstant %6 0.0 +%31 = OpFunction %2 None %32 +%18 = OpLabel +%15 = OpVariable %16 Function %17 +%22 = OpLoad %8 %20 +%19 = OpCompositeConstruct %13 %22 +%25 = OpLoad %8 %24 +%23 = OpCompositeConstruct %14 %25 +OpStore %28 %30 +OpBranch %35 +%35 = OpLabel +OpStore %15 %33 +%36 = OpCompositeExtract %8 %19 0 +%37 = OpConvertUToF %6 %36 +%38 = OpCompositeExtract %8 %23 0 +%39 = OpConvertUToF %6 %38 +%40 = OpLoad %8 %15 +%41 = OpConvertUToF %6 %40 +%42 = OpCompositeConstruct %5 %37 %39 %41 %34 +OpStore %26 %42 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interpolate.spvasm b/tests/out/spv/interpolate.spvasm index a6fae2b2d..b9df1e059 100644 --- a/tests/out/spv/interpolate.spvasm +++ b/tests/out/spv/interpolate.spvasm @@ -6,29 +6,29 @@ OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %46 "vert_main" %30 %32 %34 %36 %38 %40 %41 %42 %43 +OpEntryPoint Vertex %29 "vert_main" %13 %15 %17 %19 %21 %23 %24 %25 %26 OpEntryPoint Fragment %109 "frag_main" %88 %91 %94 %97 %100 %103 %105 %107 OpExecutionMode %109 OriginUpperLeft OpSource GLSL 450 -OpMemberName %25 0 "position" -OpMemberName %25 1 "_flat" -OpMemberName %25 2 "_linear" -OpMemberName %25 3 "linear_centroid" -OpMemberName %25 4 "linear_sample" -OpMemberName %25 5 "perspective" -OpMemberName %25 6 "perspective_centroid" -OpMemberName %25 7 "perspective_sample" -OpName %25 "FragmentInput" -OpName %26 "out" -OpName %30 "position" -OpName %32 "_flat" -OpName %34 "_linear" -OpName %36 "linear_centroid" -OpName %38 "linear_sample" -OpName %40 "perspective" -OpName %41 "perspective_centroid" -OpName %42 "perspective_sample" -OpName %46 "vert_main" +OpMemberName %8 0 "position" +OpMemberName %8 1 "_flat" +OpMemberName %8 2 "_linear" +OpMemberName %8 3 "linear_centroid" +OpMemberName %8 4 "linear_sample" +OpMemberName %8 5 "perspective" +OpMemberName %8 6 "perspective_centroid" +OpMemberName %8 7 "perspective_sample" +OpName %8 "FragmentInput" +OpName %9 "out" +OpName %13 "position" +OpName %15 "_flat" +OpName %17 "_linear" +OpName %19 "linear_centroid" +OpName %21 "linear_sample" +OpName %23 "perspective" +OpName %24 "perspective_centroid" +OpName %25 "perspective_sample" +OpName %29 "vert_main" OpName %88 "position" OpName %91 "_flat" OpName %94 "_linear" @@ -38,31 +38,31 @@ OpName %103 "perspective" OpName %105 "perspective_centroid" OpName %107 "perspective_sample" OpName %109 "frag_main" -OpMemberDecorate %25 0 Offset 0 -OpMemberDecorate %25 1 Offset 16 -OpMemberDecorate %25 2 Offset 20 -OpMemberDecorate %25 3 Offset 24 -OpMemberDecorate %25 4 Offset 32 -OpMemberDecorate %25 5 Offset 48 -OpMemberDecorate %25 6 Offset 64 -OpMemberDecorate %25 7 Offset 68 -OpDecorate %30 BuiltIn Position -OpDecorate %32 Location 0 -OpDecorate %32 Flat -OpDecorate %34 Location 1 -OpDecorate %34 NoPerspective -OpDecorate %36 Location 2 -OpDecorate %36 NoPerspective -OpDecorate %36 Centroid -OpDecorate %38 Location 3 -OpDecorate %38 NoPerspective -OpDecorate %38 Sample -OpDecorate %40 Location 4 -OpDecorate %41 Location 5 -OpDecorate %41 Centroid -OpDecorate %42 Location 6 -OpDecorate %42 Sample -OpDecorate %43 BuiltIn PointSize +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %8 1 Offset 16 +OpMemberDecorate %8 2 Offset 20 +OpMemberDecorate %8 3 Offset 24 +OpMemberDecorate %8 4 Offset 32 +OpMemberDecorate %8 5 Offset 48 +OpMemberDecorate %8 6 Offset 64 +OpMemberDecorate %8 7 Offset 68 +OpDecorate %13 BuiltIn Position +OpDecorate %15 Location 0 +OpDecorate %15 Flat +OpDecorate %17 Location 1 +OpDecorate %17 NoPerspective +OpDecorate %19 Location 2 +OpDecorate %19 NoPerspective +OpDecorate %19 Centroid +OpDecorate %21 Location 3 +OpDecorate %21 NoPerspective +OpDecorate %21 Sample +OpDecorate %23 Location 4 +OpDecorate %24 Location 5 +OpDecorate %24 Centroid +OpDecorate %25 Location 6 +OpDecorate %25 Sample +OpDecorate %26 BuiltIn PointSize OpDecorate %88 BuiltIn FragCoord OpDecorate %91 Location 0 OpDecorate %91 Flat @@ -81,133 +81,133 @@ OpDecorate %107 Location 6 OpDecorate %107 Sample %2 = OpTypeVoid %4 = OpTypeFloat 32 -%3 = OpConstant %4 2.0 -%5 = OpConstant %4 4.0 -%6 = OpConstant %4 5.0 -%7 = OpConstant %4 6.0 -%9 = OpTypeInt 32 0 -%8 = OpConstant %9 8 -%10 = OpConstant %4 27.0 -%11 = OpConstant %4 64.0 -%12 = OpConstant %4 125.0 -%13 = OpConstant %4 216.0 -%14 = OpConstant %4 343.0 -%15 = OpConstant %4 512.0 -%16 = OpConstant %4 729.0 -%17 = OpConstant %4 1000.0 -%18 = OpConstant %4 1331.0 -%19 = OpConstant %4 1728.0 -%20 = OpConstant %4 2197.0 -%21 = OpConstant %4 2744.0 -%22 = OpTypeVector %4 4 -%23 = OpTypeVector %4 2 -%24 = OpTypeVector %4 3 -%25 = OpTypeStruct %22 %9 %4 %23 %24 %22 %4 %4 -%27 = OpTypePointer Function %25 -%28 = OpConstantNull %25 -%31 = OpTypePointer Output %22 -%30 = OpVariable %31 Output -%33 = OpTypePointer Output %9 -%32 = OpVariable %33 Output -%35 = OpTypePointer Output %4 -%34 = OpVariable %35 Output -%37 = OpTypePointer Output %23 -%36 = OpVariable %37 Output -%39 = OpTypePointer Output %24 -%38 = OpVariable %39 Output -%40 = OpVariable %31 Output -%41 = OpVariable %35 Output -%42 = OpVariable %35 Output -%44 = OpTypePointer Output %4 -%43 = OpVariable %44 Output -%45 = OpConstant %4 1.0 -%47 = OpTypeFunction %2 -%49 = OpTypePointer Function %22 -%51 = OpConstant %9 0 -%53 = OpTypePointer Function %9 -%54 = OpConstant %9 1 +%3 = OpTypeVector %4 4 +%5 = OpTypeInt 32 0 +%6 = OpTypeVector %4 2 +%7 = OpTypeVector %4 3 +%8 = OpTypeStruct %3 %5 %4 %6 %7 %3 %4 %4 +%10 = OpTypePointer Function %8 +%11 = OpConstantNull %8 +%14 = OpTypePointer Output %3 +%13 = OpVariable %14 Output +%16 = OpTypePointer Output %5 +%15 = OpVariable %16 Output +%18 = OpTypePointer Output %4 +%17 = OpVariable %18 Output +%20 = OpTypePointer Output %6 +%19 = OpVariable %20 Output +%22 = OpTypePointer Output %7 +%21 = OpVariable %22 Output +%23 = OpVariable %14 Output +%24 = OpVariable %18 Output +%25 = OpVariable %18 Output +%27 = OpTypePointer Output %4 +%26 = OpVariable %27 Output +%28 = OpConstant %4 1.0 +%30 = OpTypeFunction %2 +%31 = OpConstant %4 2.0 +%32 = OpConstant %4 4.0 +%33 = OpConstant %4 5.0 +%34 = OpConstant %4 6.0 +%35 = OpConstant %5 8 +%36 = OpConstant %4 27.0 +%37 = OpConstant %4 64.0 +%38 = OpConstant %4 125.0 +%39 = OpConstant %4 216.0 +%40 = OpConstant %4 343.0 +%41 = OpConstant %4 512.0 +%42 = OpConstant %4 729.0 +%43 = OpConstant %4 1000.0 +%44 = OpConstant %4 1331.0 +%45 = OpConstant %4 1728.0 +%46 = OpConstant %4 2197.0 +%47 = OpConstant %4 2744.0 +%49 = OpTypePointer Function %3 +%51 = OpConstant %5 0 +%53 = OpTypePointer Function %5 +%54 = OpConstant %5 1 %56 = OpTypePointer Function %4 -%57 = OpConstant %9 2 -%59 = OpTypePointer Function %23 -%61 = OpConstant %9 3 -%63 = OpTypePointer Function %24 -%65 = OpConstant %9 4 -%68 = OpConstant %9 5 -%70 = OpConstant %9 6 -%72 = OpConstant %9 7 -%89 = OpTypePointer Input %22 +%57 = OpConstant %5 2 +%59 = OpTypePointer Function %6 +%61 = OpConstant %5 3 +%63 = OpTypePointer Function %7 +%65 = OpConstant %5 4 +%68 = OpConstant %5 5 +%70 = OpConstant %5 6 +%72 = OpConstant %5 7 +%89 = OpTypePointer Input %3 %88 = OpVariable %89 Input -%92 = OpTypePointer Input %9 +%92 = OpTypePointer Input %5 %91 = OpVariable %92 Input %95 = OpTypePointer Input %4 %94 = OpVariable %95 Input -%98 = OpTypePointer Input %23 +%98 = OpTypePointer Input %6 %97 = OpVariable %98 Input -%101 = OpTypePointer Input %24 +%101 = OpTypePointer Input %7 %100 = OpVariable %101 Input %103 = OpVariable %89 Input %105 = OpVariable %95 Input %107 = OpVariable %95 Input -%46 = OpFunction %2 None %47 -%29 = OpLabel -%26 = OpVariable %27 Function %28 -OpStore %43 %45 +%29 = OpFunction %2 None %30 +%12 = OpLabel +%9 = OpVariable %10 Function %11 +OpStore %26 %28 OpBranch %48 %48 = OpLabel -%50 = OpCompositeConstruct %22 %3 %5 %6 %7 -%52 = OpAccessChain %49 %26 %51 +%50 = OpCompositeConstruct %3 %31 %32 %33 %34 +%52 = OpAccessChain %49 %9 %51 OpStore %52 %50 -%55 = OpAccessChain %53 %26 %54 -OpStore %55 %8 -%58 = OpAccessChain %56 %26 %57 -OpStore %58 %10 -%60 = OpCompositeConstruct %23 %11 %12 -%62 = OpAccessChain %59 %26 %61 +%55 = OpAccessChain %53 %9 %54 +OpStore %55 %35 +%58 = OpAccessChain %56 %9 %57 +OpStore %58 %36 +%60 = OpCompositeConstruct %6 %37 %38 +%62 = OpAccessChain %59 %9 %61 OpStore %62 %60 -%64 = OpCompositeConstruct %24 %13 %14 %15 -%66 = OpAccessChain %63 %26 %65 +%64 = OpCompositeConstruct %7 %39 %40 %41 +%66 = OpAccessChain %63 %9 %65 OpStore %66 %64 -%67 = OpCompositeConstruct %22 %16 %17 %18 %19 -%69 = OpAccessChain %49 %26 %68 +%67 = OpCompositeConstruct %3 %42 %43 %44 %45 +%69 = OpAccessChain %49 %9 %68 OpStore %69 %67 -%71 = OpAccessChain %56 %26 %70 -OpStore %71 %20 -%73 = OpAccessChain %56 %26 %72 -OpStore %73 %21 -%74 = OpLoad %25 %26 -%75 = OpCompositeExtract %22 %74 0 -OpStore %30 %75 -%76 = OpAccessChain %44 %30 %54 +%71 = OpAccessChain %56 %9 %70 +OpStore %71 %46 +%73 = OpAccessChain %56 %9 %72 +OpStore %73 %47 +%74 = OpLoad %8 %9 +%75 = OpCompositeExtract %3 %74 0 +OpStore %13 %75 +%76 = OpAccessChain %27 %13 %54 %77 = OpLoad %4 %76 %78 = OpFNegate %4 %77 OpStore %76 %78 -%79 = OpCompositeExtract %9 %74 1 -OpStore %32 %79 +%79 = OpCompositeExtract %5 %74 1 +OpStore %15 %79 %80 = OpCompositeExtract %4 %74 2 -OpStore %34 %80 -%81 = OpCompositeExtract %23 %74 3 -OpStore %36 %81 -%82 = OpCompositeExtract %24 %74 4 -OpStore %38 %82 -%83 = OpCompositeExtract %22 %74 5 -OpStore %40 %83 +OpStore %17 %80 +%81 = OpCompositeExtract %6 %74 3 +OpStore %19 %81 +%82 = OpCompositeExtract %7 %74 4 +OpStore %21 %82 +%83 = OpCompositeExtract %3 %74 5 +OpStore %23 %83 %84 = OpCompositeExtract %4 %74 6 -OpStore %41 %84 +OpStore %24 %84 %85 = OpCompositeExtract %4 %74 7 -OpStore %42 %85 +OpStore %25 %85 OpReturn OpFunctionEnd -%109 = OpFunction %2 None %47 +%109 = OpFunction %2 None %30 %86 = OpLabel -%90 = OpLoad %22 %88 -%93 = OpLoad %9 %91 +%90 = OpLoad %3 %88 +%93 = OpLoad %5 %91 %96 = OpLoad %4 %94 -%99 = OpLoad %23 %97 -%102 = OpLoad %24 %100 -%104 = OpLoad %22 %103 +%99 = OpLoad %6 %97 +%102 = OpLoad %7 %100 +%104 = OpLoad %3 %103 %106 = OpLoad %4 %105 %108 = OpLoad %4 %107 -%87 = OpCompositeConstruct %25 %90 %93 %96 %99 %102 %104 %106 %108 +%87 = OpCompositeConstruct %8 %90 %93 %96 %99 %102 %104 %106 %108 OpBranch %110 %110 = OpLabel OpReturn diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index ecf925bdd..0fa6bf529 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -5,94 +5,94 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %17 "main" -OpExecutionMode %17 OriginUpperLeft +OpEntryPoint Fragment %8 "main" +OpExecutionMode %8 OriginUpperLeft %2 = OpTypeVoid %4 = OpTypeFloat 32 -%3 = OpConstant %4 1.0 -%5 = OpConstant %4 0.0 -%7 = OpTypeInt 32 0 -%6 = OpConstant %7 0 -%9 = OpTypeInt 32 1 -%8 = OpConstant %9 -1 -%10 = OpConstant %7 1 -%11 = OpConstant %9 0 -%12 = OpConstant %7 4294967295 -%13 = OpConstant %9 1 -%14 = OpTypeVector %4 4 -%15 = OpTypeVector %9 2 -%18 = OpTypeFunction %2 -%19 = OpConstantNull %15 -%20 = OpConstantNull %15 -%28 = OpConstantComposite %14 %5 %5 %5 %5 -%29 = OpConstantComposite %14 %3 %3 %3 %3 -%32 = OpConstantNull %9 -%45 = OpTypeVector %7 2 -%55 = OpConstant %7 32 +%3 = OpTypeVector %4 4 +%6 = OpTypeInt 32 1 +%5 = OpTypeVector %6 2 +%9 = OpTypeFunction %2 +%10 = OpConstant %4 1.0 +%11 = OpConstant %4 0.0 +%12 = OpConstantNull %5 +%13 = OpConstantNull %5 +%14 = OpTypeInt 32 0 +%15 = OpConstant %14 0 +%16 = OpConstant %6 -1 +%17 = OpConstant %14 1 +%18 = OpConstant %6 0 +%19 = OpConstant %14 4294967295 +%20 = OpConstant %6 1 +%28 = OpConstantComposite %3 %11 %11 %11 %11 +%29 = OpConstantComposite %3 %10 %10 %10 %10 +%32 = OpConstantNull %6 +%45 = OpTypeVector %14 2 +%55 = OpConstant %14 32 %65 = OpConstantComposite %45 %55 %55 -%77 = OpConstant %9 31 -%83 = OpConstantComposite %15 %77 %77 -%17 = OpFunction %2 None %18 -%16 = OpLabel +%77 = OpConstant %6 31 +%83 = OpConstantComposite %5 %77 %77 +%8 = OpFunction %2 None %9 +%7 = OpLabel OpBranch %21 %21 = OpLabel -%22 = OpCompositeConstruct %14 %5 %5 %5 %5 -%23 = OpExtInst %4 %1 Degrees %3 -%24 = OpExtInst %4 %1 Radians %3 -%25 = OpExtInst %14 %1 Degrees %22 -%26 = OpExtInst %14 %1 Radians %22 -%27 = OpExtInst %14 %1 FClamp %22 %28 %29 -%30 = OpExtInst %14 %1 Refract %22 %22 %3 -%33 = OpCompositeExtract %9 %19 0 -%34 = OpCompositeExtract %9 %20 0 -%35 = OpIMul %9 %33 %34 -%36 = OpIAdd %9 %32 %35 -%37 = OpCompositeExtract %9 %19 1 -%38 = OpCompositeExtract %9 %20 1 -%39 = OpIMul %9 %37 %38 -%31 = OpIAdd %9 %36 %39 -%40 = OpCopyObject %7 %6 -%41 = OpExtInst %7 %1 FindUMsb %40 -%42 = OpExtInst %9 %1 FindSMsb %8 -%43 = OpCompositeConstruct %15 %8 %8 -%44 = OpExtInst %15 %1 FindSMsb %43 -%46 = OpCompositeConstruct %45 %10 %10 +%22 = OpCompositeConstruct %3 %11 %11 %11 %11 +%23 = OpExtInst %4 %1 Degrees %10 +%24 = OpExtInst %4 %1 Radians %10 +%25 = OpExtInst %3 %1 Degrees %22 +%26 = OpExtInst %3 %1 Radians %22 +%27 = OpExtInst %3 %1 FClamp %22 %28 %29 +%30 = OpExtInst %3 %1 Refract %22 %22 %10 +%33 = OpCompositeExtract %6 %12 0 +%34 = OpCompositeExtract %6 %13 0 +%35 = OpIMul %6 %33 %34 +%36 = OpIAdd %6 %32 %35 +%37 = OpCompositeExtract %6 %12 1 +%38 = OpCompositeExtract %6 %13 1 +%39 = OpIMul %6 %37 %38 +%31 = OpIAdd %6 %36 %39 +%40 = OpCopyObject %14 %15 +%41 = OpExtInst %14 %1 FindUMsb %40 +%42 = OpExtInst %6 %1 FindSMsb %16 +%43 = OpCompositeConstruct %5 %16 %16 +%44 = OpExtInst %5 %1 FindSMsb %43 +%46 = OpCompositeConstruct %45 %17 %17 %47 = OpExtInst %45 %1 FindUMsb %46 -%48 = OpExtInst %9 %1 FindILsb %8 -%49 = OpExtInst %7 %1 FindILsb %10 -%50 = OpCompositeConstruct %15 %8 %8 -%51 = OpExtInst %15 %1 FindILsb %50 -%52 = OpCompositeConstruct %45 %10 %10 +%48 = OpExtInst %6 %1 FindILsb %16 +%49 = OpExtInst %14 %1 FindILsb %17 +%50 = OpCompositeConstruct %5 %16 %16 +%51 = OpExtInst %5 %1 FindILsb %50 +%52 = OpCompositeConstruct %45 %17 %17 %53 = OpExtInst %45 %1 FindILsb %52 -%56 = OpExtInst %7 %1 FindILsb %6 -%54 = OpExtInst %7 %1 UMin %55 %56 -%58 = OpExtInst %9 %1 FindILsb %11 -%57 = OpExtInst %9 %1 UMin %55 %58 -%60 = OpExtInst %7 %1 FindILsb %12 -%59 = OpExtInst %7 %1 UMin %55 %60 -%62 = OpExtInst %9 %1 FindILsb %8 -%61 = OpExtInst %9 %1 UMin %55 %62 -%63 = OpCompositeConstruct %45 %6 %6 +%56 = OpExtInst %14 %1 FindILsb %15 +%54 = OpExtInst %14 %1 UMin %55 %56 +%58 = OpExtInst %6 %1 FindILsb %18 +%57 = OpExtInst %6 %1 UMin %55 %58 +%60 = OpExtInst %14 %1 FindILsb %19 +%59 = OpExtInst %14 %1 UMin %55 %60 +%62 = OpExtInst %6 %1 FindILsb %16 +%61 = OpExtInst %6 %1 UMin %55 %62 +%63 = OpCompositeConstruct %45 %15 %15 %66 = OpExtInst %45 %1 FindILsb %63 %64 = OpExtInst %45 %1 UMin %65 %66 -%67 = OpCompositeConstruct %15 %11 %11 -%69 = OpExtInst %15 %1 FindILsb %67 -%68 = OpExtInst %15 %1 UMin %65 %69 -%70 = OpCompositeConstruct %45 %10 %10 +%67 = OpCompositeConstruct %5 %18 %18 +%69 = OpExtInst %5 %1 FindILsb %67 +%68 = OpExtInst %5 %1 UMin %65 %69 +%70 = OpCompositeConstruct %45 %17 %17 %72 = OpExtInst %45 %1 FindILsb %70 %71 = OpExtInst %45 %1 UMin %65 %72 -%73 = OpCompositeConstruct %15 %13 %13 -%75 = OpExtInst %15 %1 FindILsb %73 -%74 = OpExtInst %15 %1 UMin %65 %75 -%78 = OpExtInst %9 %1 FindUMsb %8 -%76 = OpISub %9 %77 %78 -%80 = OpExtInst %9 %1 FindUMsb %10 -%79 = OpISub %7 %77 %80 -%81 = OpCompositeConstruct %15 %8 %8 -%84 = OpExtInst %15 %1 FindUMsb %81 -%82 = OpISub %15 %83 %84 -%85 = OpCompositeConstruct %45 %10 %10 -%87 = OpExtInst %15 %1 FindUMsb %85 +%73 = OpCompositeConstruct %5 %20 %20 +%75 = OpExtInst %5 %1 FindILsb %73 +%74 = OpExtInst %5 %1 UMin %65 %75 +%78 = OpExtInst %6 %1 FindUMsb %16 +%76 = OpISub %6 %77 %78 +%80 = OpExtInst %6 %1 FindUMsb %17 +%79 = OpISub %14 %77 %80 +%81 = OpCompositeConstruct %5 %16 %16 +%84 = OpExtInst %5 %1 FindUMsb %81 +%82 = OpISub %5 %83 %84 +%85 = OpCompositeConstruct %45 %17 %17 +%87 = OpExtInst %5 %1 FindUMsb %85 %86 = OpISub %45 %83 %87 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 64a2ed2f4..1fc38dea9 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -7,10 +7,10 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %576 "main" OpExecutionMode %576 LocalSize 1 1 1 -OpMemberDecorate %40 0 Offset 0 -OpMemberDecorate %40 1 Offset 16 -OpDecorate %44 ArrayStride 32 -OpDecorate %45 ArrayStride 4 +OpMemberDecorate %19 0 Offset 0 +OpMemberDecorate %19 1 Offset 16 +OpDecorate %23 ArrayStride 32 +OpDecorate %24 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.0 @@ -18,633 +18,633 @@ OpDecorate %45 ArrayStride 4 %6 = OpConstant %4 0.5 %8 = OpTypeInt 32 1 %7 = OpConstant %8 1 -%10 = OpTypeBool -%9 = OpConstantTrue %10 -%11 = OpConstant %8 0 -%12 = OpConstantFalse %10 -%13 = OpConstant %4 0.1 -%14 = OpConstant %4 2.0 -%15 = OpConstant %4 3.0 -%16 = OpConstant %4 4.0 -%17 = OpConstant %8 5 -%18 = OpConstant %8 2 -%19 = OpConstant %8 3 -%21 = OpTypeInt 32 0 -%20 = OpConstant %21 0 -%22 = OpConstant %21 4 -%23 = OpConstant %4 -1.0 -%24 = OpConstant %21 2 -%25 = OpConstant %21 1 -%26 = OpConstant %8 -1 -%27 = OpConstant %8 -2 -%28 = OpConstant %8 -3 -%29 = OpConstant %8 4 -%30 = OpConstant %8 -5 -%31 = OpConstant %8 6 -%32 = OpConstant %8 -7 -%33 = OpConstant %8 -8 -%34 = OpTypeVector %4 4 -%35 = OpTypeVector %8 4 -%36 = OpTypeVector %10 4 -%37 = OpTypeVector %4 2 -%38 = OpTypeVector %4 3 -%39 = OpTypeVector %10 3 -%40 = OpTypeStruct %34 %8 -%41 = OpTypeMatrix %37 2 -%42 = OpTypeMatrix %34 4 -%43 = OpTypeVector %21 2 -%44 = OpTypeArray %40 %19 -%45 = OpTypeArray %8 %22 -%46 = OpTypeMatrix %38 2 -%47 = OpTypeMatrix %38 3 -%48 = OpTypeMatrix %38 4 -%49 = OpTypeMatrix %34 3 -%50 = OpTypeVector %8 3 -%51 = OpConstantComposite %34 %3 %3 %3 %3 -%52 = OpConstantComposite %34 %5 %5 %5 %5 -%53 = OpConstantComposite %34 %6 %6 %6 %6 -%54 = OpConstantComposite %35 %7 %7 %7 %7 -%57 = OpTypeFunction %34 -%97 = OpTypePointer Function %37 -%98 = OpConstantNull %37 -%101 = OpTypeFunction %37 -%117 = OpTypeFunction %38 %38 -%119 = OpConstantComposite %38 %5 %5 %5 -%121 = OpConstantComposite %38 %3 %3 %3 -%124 = OpTypePointer Function %40 -%125 = OpConstantNull %40 -%128 = OpTypeFunction %4 -%129 = OpConstantNull %10 -%130 = OpConstantNull %8 -%131 = OpConstantNull %21 -%132 = OpConstantNull %4 -%133 = OpConstantNull %43 -%134 = OpConstantNull %41 -%135 = OpConstantNull %44 -%136 = OpConstantNull %40 -%137 = OpConstantNull %10 -%138 = OpConstantNull %8 -%139 = OpConstantNull %21 -%140 = OpConstantNull %4 -%141 = OpConstantNull %43 -%142 = OpConstantNull %46 -%143 = OpConstantNull %43 -%144 = OpConstantNull %46 -%169 = OpTypePointer Function %34 -%170 = OpTypePointer Function %4 -%175 = OpTypeFunction %2 -%178 = OpTypeVector %10 2 -%193 = OpConstantNull %47 -%194 = OpConstantNull %47 -%195 = OpConstantNull %47 -%196 = OpConstantNull %47 -%197 = OpConstantNull %47 -%198 = OpConstantNull %47 -%199 = OpConstantNull %48 -%200 = OpConstantNull %48 -%201 = OpConstantNull %48 -%202 = OpConstantNull %49 -%204 = OpTypeVector %8 2 -%215 = OpTypeVector %21 3 -%510 = OpTypePointer Function %8 -%511 = OpConstantNull %8 -%513 = OpTypePointer Function %50 -%514 = OpConstantNull %50 -%517 = OpConstantNull %50 -%545 = OpTypePointer Function %8 -%56 = OpFunction %34 None %57 -%55 = OpLabel -OpBranch %58 -%58 = OpLabel -%59 = OpSelect %8 %9 %7 %11 -%61 = OpCompositeConstruct %36 %9 %9 %9 %9 -%60 = OpSelect %34 %61 %51 %52 -%62 = OpCompositeConstruct %36 %12 %12 %12 %12 -%63 = OpSelect %34 %62 %52 %51 -%64 = OpExtInst %34 %1 FMix %52 %51 %53 -%66 = OpCompositeConstruct %34 %13 %13 %13 %13 -%65 = OpExtInst %34 %1 FMix %52 %51 %66 -%67 = OpCompositeExtract %8 %54 0 -%68 = OpBitcast %4 %67 -%69 = OpBitcast %34 %54 -%70 = OpConvertFToS %35 %52 -%71 = OpCompositeConstruct %35 %59 %59 %59 %59 -%72 = OpIAdd %35 %71 %70 -%73 = OpConvertSToF %34 %72 -%74 = OpFAdd %34 %73 %60 -%75 = OpFAdd %34 %74 %64 -%76 = OpFAdd %34 %75 %65 -%77 = OpCompositeConstruct %34 %68 %68 %68 %68 -%78 = OpFAdd %34 %76 %77 -%79 = OpFAdd %34 %78 %69 -OpReturnValue %79 +%9 = OpConstant %8 3 +%11 = OpTypeInt 32 0 +%10 = OpConstant %11 4 +%12 = OpTypeVector %4 4 +%13 = OpTypeVector %8 4 +%15 = OpTypeBool +%14 = OpTypeVector %15 4 +%16 = OpTypeVector %4 2 +%17 = OpTypeVector %4 3 +%18 = OpTypeVector %15 3 +%19 = OpTypeStruct %12 %8 +%20 = OpTypeMatrix %16 2 +%21 = OpTypeMatrix %12 4 +%22 = OpTypeVector %11 2 +%23 = OpTypeArray %19 %9 +%24 = OpTypeArray %8 %10 +%25 = OpTypeMatrix %17 2 +%26 = OpTypeMatrix %17 3 +%27 = OpTypeMatrix %17 4 +%28 = OpTypeMatrix %12 3 +%29 = OpTypeVector %8 3 +%30 = OpConstantComposite %12 %3 %3 %3 %3 +%31 = OpConstantComposite %12 %5 %5 %5 %5 +%32 = OpConstantComposite %12 %6 %6 %6 %6 +%33 = OpConstantComposite %13 %7 %7 %7 %7 +%36 = OpTypeFunction %12 +%37 = OpConstantTrue %15 +%38 = OpConstant %8 0 +%39 = OpConstantFalse %15 +%40 = OpConstant %4 0.1 +%65 = OpConstant %4 2.0 +%66 = OpConstant %4 3.0 +%67 = OpConstant %4 4.0 +%68 = OpConstant %8 5 +%69 = OpConstant %8 2 +%85 = OpTypePointer Function %16 +%86 = OpConstantNull %16 +%89 = OpTypeFunction %16 +%105 = OpTypeFunction %17 %17 +%107 = OpConstantComposite %17 %5 %5 %5 +%109 = OpConstantComposite %17 %3 %3 %3 +%112 = OpTypePointer Function %19 +%113 = OpConstantNull %19 +%116 = OpTypeFunction %4 +%117 = OpConstantNull %15 +%118 = OpConstantNull %8 +%119 = OpConstantNull %11 +%120 = OpConstantNull %4 +%121 = OpConstantNull %22 +%122 = OpConstantNull %20 +%123 = OpConstantNull %23 +%124 = OpConstantNull %19 +%125 = OpConstant %11 0 +%126 = OpConstantNull %15 +%127 = OpConstantNull %8 +%128 = OpConstantNull %11 +%129 = OpConstantNull %4 +%130 = OpConstantNull %22 +%131 = OpConstantNull %25 +%132 = OpConstantNull %22 +%133 = OpConstantNull %25 +%158 = OpTypePointer Function %12 +%159 = OpTypePointer Function %4 +%164 = OpTypeFunction %2 +%167 = OpTypeVector %15 2 +%182 = OpConstant %4 -1.0 +%183 = OpConstant %11 2 +%184 = OpConstant %11 1 +%185 = OpConstantNull %26 +%186 = OpConstantNull %26 +%187 = OpConstantNull %26 +%188 = OpConstantNull %26 +%189 = OpConstantNull %26 +%190 = OpConstantNull %26 +%191 = OpConstantNull %27 +%192 = OpConstantNull %27 +%193 = OpConstantNull %27 +%194 = OpConstantNull %28 +%196 = OpTypeVector %8 2 +%207 = OpTypeVector %11 3 +%502 = OpTypePointer Function %8 +%503 = OpConstantNull %8 +%505 = OpTypePointer Function %29 +%506 = OpConstantNull %29 +%509 = OpConstantNull %29 +%537 = OpTypePointer Function %8 +%548 = OpConstant %8 -1 +%549 = OpConstant %8 -2 +%550 = OpConstant %8 -3 +%551 = OpConstant %8 4 +%552 = OpConstant %8 -5 +%553 = OpConstant %8 6 +%554 = OpConstant %8 -7 +%555 = OpConstant %8 -8 +%35 = OpFunction %12 None %36 +%34 = OpLabel +OpBranch %41 +%41 = OpLabel +%42 = OpSelect %8 %37 %7 %38 +%44 = OpCompositeConstruct %14 %37 %37 %37 %37 +%43 = OpSelect %12 %44 %30 %31 +%45 = OpCompositeConstruct %14 %39 %39 %39 %39 +%46 = OpSelect %12 %45 %31 %30 +%47 = OpExtInst %12 %1 FMix %31 %30 %32 +%49 = OpCompositeConstruct %12 %40 %40 %40 %40 +%48 = OpExtInst %12 %1 FMix %31 %30 %49 +%50 = OpCompositeExtract %8 %33 0 +%51 = OpBitcast %4 %50 +%52 = OpBitcast %12 %33 +%53 = OpConvertFToS %13 %31 +%54 = OpCompositeConstruct %13 %42 %42 %42 %42 +%55 = OpIAdd %13 %54 %53 +%56 = OpConvertSToF %12 %55 +%57 = OpFAdd %12 %56 %43 +%58 = OpFAdd %12 %57 %47 +%59 = OpFAdd %12 %58 %48 +%60 = OpCompositeConstruct %12 %51 %51 %51 %51 +%61 = OpFAdd %12 %59 %60 +%62 = OpFAdd %12 %61 %52 +OpReturnValue %62 OpFunctionEnd -%81 = OpFunction %34 None %57 -%80 = OpLabel -OpBranch %82 -%82 = OpLabel -%83 = OpCompositeConstruct %37 %14 %14 -%84 = OpCompositeConstruct %37 %3 %3 -%85 = OpFAdd %37 %84 %83 -%86 = OpCompositeConstruct %37 %15 %15 -%87 = OpFSub %37 %85 %86 -%88 = OpCompositeConstruct %37 %16 %16 -%89 = OpFDiv %37 %87 %88 -%90 = OpCompositeConstruct %35 %17 %17 %17 %17 -%91 = OpCompositeConstruct %35 %18 %18 %18 %18 -%92 = OpSRem %35 %90 %91 -%93 = OpVectorShuffle %34 %89 %89 0 1 0 1 -%94 = OpConvertSToF %34 %92 -%95 = OpFAdd %34 %93 %94 -OpReturnValue %95 +%64 = OpFunction %12 None %36 +%63 = OpLabel +OpBranch %70 +%70 = OpLabel +%71 = OpCompositeConstruct %16 %65 %65 +%72 = OpCompositeConstruct %16 %3 %3 +%73 = OpFAdd %16 %72 %71 +%74 = OpCompositeConstruct %16 %66 %66 +%75 = OpFSub %16 %73 %74 +%76 = OpCompositeConstruct %16 %67 %67 +%77 = OpFDiv %16 %75 %76 +%78 = OpCompositeConstruct %13 %68 %68 %68 %68 +%79 = OpCompositeConstruct %13 %69 %69 %69 %69 +%80 = OpSRem %13 %78 %79 +%81 = OpVectorShuffle %12 %77 %77 0 1 0 1 +%82 = OpConvertSToF %12 %80 +%83 = OpFAdd %12 %81 %82 +OpReturnValue %83 OpFunctionEnd -%100 = OpFunction %37 None %101 -%99 = OpLabel -%96 = OpVariable %97 Function %98 -OpBranch %102 +%88 = OpFunction %16 None %89 +%87 = OpLabel +%84 = OpVariable %85 Function %86 +OpBranch %90 +%90 = OpLabel +%91 = OpCompositeConstruct %16 %65 %65 +OpStore %84 %91 +%92 = OpLoad %16 %84 +%93 = OpCompositeConstruct %16 %3 %3 +%94 = OpFAdd %16 %92 %93 +OpStore %84 %94 +%95 = OpLoad %16 %84 +%96 = OpCompositeConstruct %16 %66 %66 +%97 = OpFSub %16 %95 %96 +OpStore %84 %97 +%98 = OpLoad %16 %84 +%99 = OpCompositeConstruct %16 %67 %67 +%100 = OpFDiv %16 %98 %99 +OpStore %84 %100 +%101 = OpLoad %16 %84 +OpReturnValue %101 +OpFunctionEnd +%104 = OpFunction %17 None %105 +%103 = OpFunctionParameter %17 %102 = OpLabel -%103 = OpCompositeConstruct %37 %14 %14 -OpStore %96 %103 -%104 = OpLoad %37 %96 -%105 = OpCompositeConstruct %37 %3 %3 -%106 = OpFAdd %37 %104 %105 -OpStore %96 %106 -%107 = OpLoad %37 %96 -%108 = OpCompositeConstruct %37 %15 %15 -%109 = OpFSub %37 %107 %108 -OpStore %96 %109 -%110 = OpLoad %37 %96 -%111 = OpCompositeConstruct %37 %16 %16 -%112 = OpFDiv %37 %110 %111 -OpStore %96 %112 -%113 = OpLoad %37 %96 -OpReturnValue %113 +OpBranch %106 +%106 = OpLabel +%108 = OpFUnordNotEqual %18 %103 %107 +%110 = OpSelect %17 %108 %109 %107 +OpReturnValue %110 OpFunctionEnd -%116 = OpFunction %38 None %117 -%115 = OpFunctionParameter %38 +%115 = OpFunction %4 None %116 %114 = OpLabel -OpBranch %118 -%118 = OpLabel -%120 = OpFUnordNotEqual %39 %115 %119 -%122 = OpSelect %38 %120 %121 %119 -OpReturnValue %122 +%111 = OpVariable %112 Function %113 +OpBranch %134 +%134 = OpLabel +%135 = OpCompositeConstruct %12 %3 %3 %3 %3 +%136 = OpCompositeConstruct %19 %135 %7 +OpStore %111 %136 +%137 = OpCompositeConstruct %16 %3 %5 +%138 = OpCompositeConstruct %16 %5 %3 +%139 = OpCompositeConstruct %20 %137 %138 +%140 = OpCompositeConstruct %12 %3 %5 %5 %5 +%141 = OpCompositeConstruct %12 %5 %3 %5 %5 +%142 = OpCompositeConstruct %12 %5 %5 %3 %5 +%143 = OpCompositeConstruct %12 %5 %5 %5 %3 +%144 = OpCompositeConstruct %21 %140 %141 %142 %143 +%145 = OpCompositeConstruct %22 %125 %125 +%146 = OpCompositeConstruct %16 %5 %5 +%147 = OpCompositeConstruct %16 %5 %5 +%148 = OpCompositeConstruct %20 %146 %147 +%149 = OpCompositeConstruct %24 %38 %7 %69 %9 +%155 = OpCopyObject %25 %131 +%157 = OpCopyObject %25 %133 +%160 = OpAccessChain %159 %111 %125 %125 +%161 = OpLoad %4 %160 +OpReturnValue %161 OpFunctionEnd -%127 = OpFunction %4 None %128 -%126 = OpLabel -%123 = OpVariable %124 Function %125 -OpBranch %145 -%145 = OpLabel -%146 = OpCompositeConstruct %34 %3 %3 %3 %3 -%147 = OpCompositeConstruct %40 %146 %7 -OpStore %123 %147 -%148 = OpCompositeConstruct %37 %3 %5 -%149 = OpCompositeConstruct %37 %5 %3 -%150 = OpCompositeConstruct %41 %148 %149 -%151 = OpCompositeConstruct %34 %3 %5 %5 %5 -%152 = OpCompositeConstruct %34 %5 %3 %5 %5 -%153 = OpCompositeConstruct %34 %5 %5 %3 %5 -%154 = OpCompositeConstruct %34 %5 %5 %5 %3 -%155 = OpCompositeConstruct %42 %151 %152 %153 %154 -%156 = OpCompositeConstruct %43 %20 %20 -%157 = OpCompositeConstruct %37 %5 %5 -%158 = OpCompositeConstruct %37 %5 %5 -%159 = OpCompositeConstruct %41 %157 %158 -%160 = OpCompositeConstruct %45 %11 %7 %18 %19 -%166 = OpCopyObject %46 %142 -%168 = OpCopyObject %46 %144 -%171 = OpAccessChain %170 %123 %20 %20 -%172 = OpLoad %4 %171 -OpReturnValue %172 -OpFunctionEnd -%174 = OpFunction %2 None %175 -%173 = OpLabel -OpBranch %176 -%176 = OpLabel -%177 = OpLogicalNot %10 %9 -%179 = OpCompositeConstruct %178 %9 %9 -%180 = OpLogicalNot %178 %179 -%181 = OpLogicalOr %10 %9 %12 -%182 = OpLogicalAnd %10 %9 %12 -%183 = OpLogicalOr %10 %9 %12 -%184 = OpCompositeConstruct %39 %9 %9 %9 -%185 = OpCompositeConstruct %39 %12 %12 %12 -%186 = OpLogicalOr %39 %184 %185 -%187 = OpLogicalAnd %10 %9 %12 -%188 = OpCompositeConstruct %36 %9 %9 %9 %9 -%189 = OpCompositeConstruct %36 %12 %12 %12 %12 -%190 = OpLogicalAnd %36 %188 %189 +%163 = OpFunction %2 None %164 +%162 = OpLabel +OpBranch %165 +%165 = OpLabel +%166 = OpLogicalNot %15 %37 +%168 = OpCompositeConstruct %167 %37 %37 +%169 = OpLogicalNot %167 %168 +%170 = OpLogicalOr %15 %37 %39 +%171 = OpLogicalAnd %15 %37 %39 +%172 = OpLogicalOr %15 %37 %39 +%173 = OpCompositeConstruct %18 %37 %37 %37 +%174 = OpCompositeConstruct %18 %39 %39 %39 +%175 = OpLogicalOr %18 %173 %174 +%176 = OpLogicalAnd %15 %37 %39 +%177 = OpCompositeConstruct %14 %37 %37 %37 %37 +%178 = OpCompositeConstruct %14 %39 %39 %39 %39 +%179 = OpLogicalAnd %14 %177 %178 OpReturn OpFunctionEnd -%192 = OpFunction %2 None %175 -%191 = OpLabel -OpBranch %203 -%203 = OpLabel -%205 = OpCompositeConstruct %204 %7 %7 -%206 = OpSNegate %204 %205 -%207 = OpCompositeConstruct %37 %3 %3 -%208 = OpFNegate %37 %207 -%209 = OpIAdd %8 %18 %7 -%210 = OpIAdd %21 %24 %25 -%211 = OpFAdd %4 %14 %3 -%212 = OpCompositeConstruct %204 %18 %18 -%213 = OpCompositeConstruct %204 %7 %7 -%214 = OpIAdd %204 %212 %213 -%216 = OpCompositeConstruct %215 %24 %24 %24 -%217 = OpCompositeConstruct %215 %25 %25 %25 -%218 = OpIAdd %215 %216 %217 -%219 = OpCompositeConstruct %34 %14 %14 %14 %14 -%220 = OpCompositeConstruct %34 %3 %3 %3 %3 -%221 = OpFAdd %34 %219 %220 -%222 = OpISub %8 %18 %7 -%223 = OpISub %21 %24 %25 -%224 = OpFSub %4 %14 %3 -%225 = OpCompositeConstruct %204 %18 %18 -%226 = OpCompositeConstruct %204 %7 %7 -%227 = OpISub %204 %225 %226 -%228 = OpCompositeConstruct %215 %24 %24 %24 -%229 = OpCompositeConstruct %215 %25 %25 %25 -%230 = OpISub %215 %228 %229 -%231 = OpCompositeConstruct %34 %14 %14 %14 %14 -%232 = OpCompositeConstruct %34 %3 %3 %3 %3 -%233 = OpFSub %34 %231 %232 -%234 = OpIMul %8 %18 %7 -%235 = OpIMul %21 %24 %25 -%236 = OpFMul %4 %14 %3 -%237 = OpCompositeConstruct %204 %18 %18 -%238 = OpCompositeConstruct %204 %7 %7 -%239 = OpIMul %204 %237 %238 -%240 = OpCompositeConstruct %215 %24 %24 %24 -%241 = OpCompositeConstruct %215 %25 %25 %25 -%242 = OpIMul %215 %240 %241 -%243 = OpCompositeConstruct %34 %14 %14 %14 %14 -%244 = OpCompositeConstruct %34 %3 %3 %3 %3 -%245 = OpFMul %34 %243 %244 -%246 = OpSDiv %8 %18 %7 -%247 = OpUDiv %21 %24 %25 -%248 = OpFDiv %4 %14 %3 -%249 = OpCompositeConstruct %204 %18 %18 -%250 = OpCompositeConstruct %204 %7 %7 -%251 = OpSDiv %204 %249 %250 -%252 = OpCompositeConstruct %215 %24 %24 %24 -%253 = OpCompositeConstruct %215 %25 %25 %25 -%254 = OpUDiv %215 %252 %253 -%255 = OpCompositeConstruct %34 %14 %14 %14 %14 -%256 = OpCompositeConstruct %34 %3 %3 %3 %3 -%257 = OpFDiv %34 %255 %256 -%258 = OpSRem %8 %18 %7 -%259 = OpUMod %21 %24 %25 -%260 = OpFRem %4 %14 %3 -%261 = OpCompositeConstruct %204 %18 %18 -%262 = OpCompositeConstruct %204 %7 %7 -%263 = OpSRem %204 %261 %262 -%264 = OpCompositeConstruct %215 %24 %24 %24 -%265 = OpCompositeConstruct %215 %25 %25 %25 -%266 = OpUMod %215 %264 %265 -%267 = OpCompositeConstruct %34 %14 %14 %14 %14 -%268 = OpCompositeConstruct %34 %3 %3 %3 %3 -%269 = OpFRem %34 %267 %268 -%270 = OpCompositeConstruct %204 %18 %18 -%271 = OpCompositeConstruct %204 %7 %7 -%272 = OpIAdd %204 %270 %271 -%273 = OpCompositeConstruct %204 %7 %7 -%274 = OpCompositeConstruct %204 %18 %18 -%275 = OpIAdd %204 %274 %273 -%276 = OpCompositeConstruct %43 %24 %24 -%277 = OpCompositeConstruct %43 %25 %25 -%278 = OpIAdd %43 %276 %277 -%279 = OpCompositeConstruct %43 %25 %25 -%280 = OpCompositeConstruct %43 %24 %24 -%281 = OpIAdd %43 %280 %279 -%282 = OpCompositeConstruct %37 %14 %14 -%283 = OpCompositeConstruct %37 %3 %3 -%284 = OpFAdd %37 %282 %283 -%285 = OpCompositeConstruct %37 %3 %3 -%286 = OpCompositeConstruct %37 %14 %14 -%287 = OpFAdd %37 %286 %285 -%288 = OpCompositeConstruct %204 %18 %18 -%289 = OpCompositeConstruct %204 %7 %7 -%290 = OpISub %204 %288 %289 -%291 = OpCompositeConstruct %204 %7 %7 -%292 = OpCompositeConstruct %204 %18 %18 -%293 = OpISub %204 %292 %291 -%294 = OpCompositeConstruct %43 %24 %24 -%295 = OpCompositeConstruct %43 %25 %25 -%296 = OpISub %43 %294 %295 -%297 = OpCompositeConstruct %43 %25 %25 -%298 = OpCompositeConstruct %43 %24 %24 -%299 = OpISub %43 %298 %297 -%300 = OpCompositeConstruct %37 %14 %14 -%301 = OpCompositeConstruct %37 %3 %3 -%302 = OpFSub %37 %300 %301 -%303 = OpCompositeConstruct %37 %3 %3 -%304 = OpCompositeConstruct %37 %14 %14 -%305 = OpFSub %37 %304 %303 -%306 = OpCompositeConstruct %204 %18 %18 -%308 = OpCompositeConstruct %204 %7 %7 -%307 = OpIMul %204 %306 %308 -%309 = OpCompositeConstruct %204 %7 %7 -%311 = OpCompositeConstruct %204 %18 %18 -%310 = OpIMul %204 %309 %311 -%312 = OpCompositeConstruct %43 %24 %24 -%314 = OpCompositeConstruct %43 %25 %25 -%313 = OpIMul %43 %312 %314 -%315 = OpCompositeConstruct %43 %25 %25 -%317 = OpCompositeConstruct %43 %24 %24 -%316 = OpIMul %43 %315 %317 -%318 = OpCompositeConstruct %37 %14 %14 -%319 = OpVectorTimesScalar %37 %318 %3 -%320 = OpCompositeConstruct %37 %3 %3 -%321 = OpVectorTimesScalar %37 %320 %14 -%322 = OpCompositeConstruct %204 %18 %18 -%323 = OpCompositeConstruct %204 %7 %7 -%324 = OpSDiv %204 %322 %323 -%325 = OpCompositeConstruct %204 %7 %7 -%326 = OpCompositeConstruct %204 %18 %18 -%327 = OpSDiv %204 %326 %325 -%328 = OpCompositeConstruct %43 %24 %24 -%329 = OpCompositeConstruct %43 %25 %25 -%330 = OpUDiv %43 %328 %329 -%331 = OpCompositeConstruct %43 %25 %25 -%332 = OpCompositeConstruct %43 %24 %24 -%333 = OpUDiv %43 %332 %331 -%334 = OpCompositeConstruct %37 %14 %14 -%335 = OpCompositeConstruct %37 %3 %3 -%336 = OpFDiv %37 %334 %335 -%337 = OpCompositeConstruct %37 %3 %3 -%338 = OpCompositeConstruct %37 %14 %14 -%339 = OpFDiv %37 %338 %337 -%340 = OpCompositeConstruct %204 %18 %18 -%341 = OpCompositeConstruct %204 %7 %7 -%342 = OpSRem %204 %340 %341 -%343 = OpCompositeConstruct %204 %7 %7 -%344 = OpCompositeConstruct %204 %18 %18 -%345 = OpSRem %204 %344 %343 -%346 = OpCompositeConstruct %43 %24 %24 -%347 = OpCompositeConstruct %43 %25 %25 -%348 = OpUMod %43 %346 %347 -%349 = OpCompositeConstruct %43 %25 %25 -%350 = OpCompositeConstruct %43 %24 %24 -%351 = OpUMod %43 %350 %349 -%352 = OpCompositeConstruct %37 %14 %14 -%353 = OpCompositeConstruct %37 %3 %3 -%354 = OpFRem %37 %352 %353 -%355 = OpCompositeConstruct %37 %3 %3 -%356 = OpCompositeConstruct %37 %14 %14 -%357 = OpFRem %37 %356 %355 -%359 = OpCompositeExtract %38 %193 0 -%360 = OpCompositeExtract %38 %194 0 -%361 = OpFAdd %38 %359 %360 -%362 = OpCompositeExtract %38 %193 1 -%363 = OpCompositeExtract %38 %194 1 -%364 = OpFAdd %38 %362 %363 -%365 = OpCompositeExtract %38 %193 2 -%366 = OpCompositeExtract %38 %194 2 -%367 = OpFAdd %38 %365 %366 -%358 = OpCompositeConstruct %47 %361 %364 %367 -%369 = OpCompositeExtract %38 %195 0 -%370 = OpCompositeExtract %38 %196 0 -%371 = OpFSub %38 %369 %370 -%372 = OpCompositeExtract %38 %195 1 -%373 = OpCompositeExtract %38 %196 1 -%374 = OpFSub %38 %372 %373 -%375 = OpCompositeExtract %38 %195 2 -%376 = OpCompositeExtract %38 %196 2 -%377 = OpFSub %38 %375 %376 -%368 = OpCompositeConstruct %47 %371 %374 %377 -%378 = OpMatrixTimesScalar %47 %197 %3 -%379 = OpMatrixTimesScalar %47 %198 %14 -%380 = OpCompositeConstruct %34 %3 %3 %3 %3 -%381 = OpMatrixTimesVector %38 %199 %380 -%382 = OpCompositeConstruct %38 %14 %14 %14 -%383 = OpVectorTimesMatrix %34 %382 %200 -%384 = OpMatrixTimesMatrix %47 %201 %202 +%181 = OpFunction %2 None %164 +%180 = OpLabel +OpBranch %195 +%195 = OpLabel +%197 = OpCompositeConstruct %196 %7 %7 +%198 = OpSNegate %196 %197 +%199 = OpCompositeConstruct %16 %3 %3 +%200 = OpFNegate %16 %199 +%201 = OpIAdd %8 %69 %7 +%202 = OpIAdd %11 %183 %184 +%203 = OpFAdd %4 %65 %3 +%204 = OpCompositeConstruct %196 %69 %69 +%205 = OpCompositeConstruct %196 %7 %7 +%206 = OpIAdd %196 %204 %205 +%208 = OpCompositeConstruct %207 %183 %183 %183 +%209 = OpCompositeConstruct %207 %184 %184 %184 +%210 = OpIAdd %207 %208 %209 +%211 = OpCompositeConstruct %12 %65 %65 %65 %65 +%212 = OpCompositeConstruct %12 %3 %3 %3 %3 +%213 = OpFAdd %12 %211 %212 +%214 = OpISub %8 %69 %7 +%215 = OpISub %11 %183 %184 +%216 = OpFSub %4 %65 %3 +%217 = OpCompositeConstruct %196 %69 %69 +%218 = OpCompositeConstruct %196 %7 %7 +%219 = OpISub %196 %217 %218 +%220 = OpCompositeConstruct %207 %183 %183 %183 +%221 = OpCompositeConstruct %207 %184 %184 %184 +%222 = OpISub %207 %220 %221 +%223 = OpCompositeConstruct %12 %65 %65 %65 %65 +%224 = OpCompositeConstruct %12 %3 %3 %3 %3 +%225 = OpFSub %12 %223 %224 +%226 = OpIMul %8 %69 %7 +%227 = OpIMul %11 %183 %184 +%228 = OpFMul %4 %65 %3 +%229 = OpCompositeConstruct %196 %69 %69 +%230 = OpCompositeConstruct %196 %7 %7 +%231 = OpIMul %196 %229 %230 +%232 = OpCompositeConstruct %207 %183 %183 %183 +%233 = OpCompositeConstruct %207 %184 %184 %184 +%234 = OpIMul %207 %232 %233 +%235 = OpCompositeConstruct %12 %65 %65 %65 %65 +%236 = OpCompositeConstruct %12 %3 %3 %3 %3 +%237 = OpFMul %12 %235 %236 +%238 = OpSDiv %8 %69 %7 +%239 = OpUDiv %11 %183 %184 +%240 = OpFDiv %4 %65 %3 +%241 = OpCompositeConstruct %196 %69 %69 +%242 = OpCompositeConstruct %196 %7 %7 +%243 = OpSDiv %196 %241 %242 +%244 = OpCompositeConstruct %207 %183 %183 %183 +%245 = OpCompositeConstruct %207 %184 %184 %184 +%246 = OpUDiv %207 %244 %245 +%247 = OpCompositeConstruct %12 %65 %65 %65 %65 +%248 = OpCompositeConstruct %12 %3 %3 %3 %3 +%249 = OpFDiv %12 %247 %248 +%250 = OpSRem %8 %69 %7 +%251 = OpUMod %11 %183 %184 +%252 = OpFRem %4 %65 %3 +%253 = OpCompositeConstruct %196 %69 %69 +%254 = OpCompositeConstruct %196 %7 %7 +%255 = OpSRem %196 %253 %254 +%256 = OpCompositeConstruct %207 %183 %183 %183 +%257 = OpCompositeConstruct %207 %184 %184 %184 +%258 = OpUMod %207 %256 %257 +%259 = OpCompositeConstruct %12 %65 %65 %65 %65 +%260 = OpCompositeConstruct %12 %3 %3 %3 %3 +%261 = OpFRem %12 %259 %260 +%262 = OpCompositeConstruct %196 %69 %69 +%263 = OpCompositeConstruct %196 %7 %7 +%264 = OpIAdd %196 %262 %263 +%265 = OpCompositeConstruct %196 %7 %7 +%266 = OpCompositeConstruct %196 %69 %69 +%267 = OpIAdd %196 %266 %265 +%268 = OpCompositeConstruct %22 %183 %183 +%269 = OpCompositeConstruct %22 %184 %184 +%270 = OpIAdd %22 %268 %269 +%271 = OpCompositeConstruct %22 %184 %184 +%272 = OpCompositeConstruct %22 %183 %183 +%273 = OpIAdd %22 %272 %271 +%274 = OpCompositeConstruct %16 %65 %65 +%275 = OpCompositeConstruct %16 %3 %3 +%276 = OpFAdd %16 %274 %275 +%277 = OpCompositeConstruct %16 %3 %3 +%278 = OpCompositeConstruct %16 %65 %65 +%279 = OpFAdd %16 %278 %277 +%280 = OpCompositeConstruct %196 %69 %69 +%281 = OpCompositeConstruct %196 %7 %7 +%282 = OpISub %196 %280 %281 +%283 = OpCompositeConstruct %196 %7 %7 +%284 = OpCompositeConstruct %196 %69 %69 +%285 = OpISub %196 %284 %283 +%286 = OpCompositeConstruct %22 %183 %183 +%287 = OpCompositeConstruct %22 %184 %184 +%288 = OpISub %22 %286 %287 +%289 = OpCompositeConstruct %22 %184 %184 +%290 = OpCompositeConstruct %22 %183 %183 +%291 = OpISub %22 %290 %289 +%292 = OpCompositeConstruct %16 %65 %65 +%293 = OpCompositeConstruct %16 %3 %3 +%294 = OpFSub %16 %292 %293 +%295 = OpCompositeConstruct %16 %3 %3 +%296 = OpCompositeConstruct %16 %65 %65 +%297 = OpFSub %16 %296 %295 +%298 = OpCompositeConstruct %196 %69 %69 +%300 = OpCompositeConstruct %196 %7 %7 +%299 = OpIMul %196 %298 %300 +%301 = OpCompositeConstruct %196 %7 %7 +%303 = OpCompositeConstruct %196 %69 %69 +%302 = OpIMul %196 %301 %303 +%304 = OpCompositeConstruct %22 %183 %183 +%306 = OpCompositeConstruct %22 %184 %184 +%305 = OpIMul %22 %304 %306 +%307 = OpCompositeConstruct %22 %184 %184 +%309 = OpCompositeConstruct %22 %183 %183 +%308 = OpIMul %22 %307 %309 +%310 = OpCompositeConstruct %16 %65 %65 +%311 = OpVectorTimesScalar %16 %310 %3 +%312 = OpCompositeConstruct %16 %3 %3 +%313 = OpVectorTimesScalar %16 %312 %65 +%314 = OpCompositeConstruct %196 %69 %69 +%315 = OpCompositeConstruct %196 %7 %7 +%316 = OpSDiv %196 %314 %315 +%317 = OpCompositeConstruct %196 %7 %7 +%318 = OpCompositeConstruct %196 %69 %69 +%319 = OpSDiv %196 %318 %317 +%320 = OpCompositeConstruct %22 %183 %183 +%321 = OpCompositeConstruct %22 %184 %184 +%322 = OpUDiv %22 %320 %321 +%323 = OpCompositeConstruct %22 %184 %184 +%324 = OpCompositeConstruct %22 %183 %183 +%325 = OpUDiv %22 %324 %323 +%326 = OpCompositeConstruct %16 %65 %65 +%327 = OpCompositeConstruct %16 %3 %3 +%328 = OpFDiv %16 %326 %327 +%329 = OpCompositeConstruct %16 %3 %3 +%330 = OpCompositeConstruct %16 %65 %65 +%331 = OpFDiv %16 %330 %329 +%332 = OpCompositeConstruct %196 %69 %69 +%333 = OpCompositeConstruct %196 %7 %7 +%334 = OpSRem %196 %332 %333 +%335 = OpCompositeConstruct %196 %7 %7 +%336 = OpCompositeConstruct %196 %69 %69 +%337 = OpSRem %196 %336 %335 +%338 = OpCompositeConstruct %22 %183 %183 +%339 = OpCompositeConstruct %22 %184 %184 +%340 = OpUMod %22 %338 %339 +%341 = OpCompositeConstruct %22 %184 %184 +%342 = OpCompositeConstruct %22 %183 %183 +%343 = OpUMod %22 %342 %341 +%344 = OpCompositeConstruct %16 %65 %65 +%345 = OpCompositeConstruct %16 %3 %3 +%346 = OpFRem %16 %344 %345 +%347 = OpCompositeConstruct %16 %3 %3 +%348 = OpCompositeConstruct %16 %65 %65 +%349 = OpFRem %16 %348 %347 +%351 = OpCompositeExtract %17 %185 0 +%352 = OpCompositeExtract %17 %186 0 +%353 = OpFAdd %17 %351 %352 +%354 = OpCompositeExtract %17 %185 1 +%355 = OpCompositeExtract %17 %186 1 +%356 = OpFAdd %17 %354 %355 +%357 = OpCompositeExtract %17 %185 2 +%358 = OpCompositeExtract %17 %186 2 +%359 = OpFAdd %17 %357 %358 +%350 = OpCompositeConstruct %26 %353 %356 %359 +%361 = OpCompositeExtract %17 %187 0 +%362 = OpCompositeExtract %17 %188 0 +%363 = OpFSub %17 %361 %362 +%364 = OpCompositeExtract %17 %187 1 +%365 = OpCompositeExtract %17 %188 1 +%366 = OpFSub %17 %364 %365 +%367 = OpCompositeExtract %17 %187 2 +%368 = OpCompositeExtract %17 %188 2 +%369 = OpFSub %17 %367 %368 +%360 = OpCompositeConstruct %26 %363 %366 %369 +%370 = OpMatrixTimesScalar %26 %189 %3 +%371 = OpMatrixTimesScalar %26 %190 %65 +%372 = OpCompositeConstruct %12 %3 %3 %3 %3 +%373 = OpMatrixTimesVector %17 %191 %372 +%374 = OpCompositeConstruct %17 %65 %65 %65 +%375 = OpVectorTimesMatrix %12 %374 %192 +%376 = OpMatrixTimesMatrix %26 %193 %194 OpReturn OpFunctionEnd -%386 = OpFunction %2 None %175 -%385 = OpLabel -OpBranch %387 -%387 = OpLabel -%388 = OpNot %8 %7 -%389 = OpNot %21 %25 -%390 = OpCompositeConstruct %204 %7 %7 -%391 = OpNot %204 %390 -%392 = OpCompositeConstruct %215 %25 %25 %25 -%393 = OpNot %215 %392 -%394 = OpBitwiseOr %8 %18 %7 -%395 = OpBitwiseOr %21 %24 %25 -%396 = OpCompositeConstruct %204 %18 %18 -%397 = OpCompositeConstruct %204 %7 %7 -%398 = OpBitwiseOr %204 %396 %397 -%399 = OpCompositeConstruct %215 %24 %24 %24 -%400 = OpCompositeConstruct %215 %25 %25 %25 -%401 = OpBitwiseOr %215 %399 %400 -%402 = OpBitwiseAnd %8 %18 %7 -%403 = OpBitwiseAnd %21 %24 %25 -%404 = OpCompositeConstruct %204 %18 %18 -%405 = OpCompositeConstruct %204 %7 %7 -%406 = OpBitwiseAnd %204 %404 %405 -%407 = OpCompositeConstruct %215 %24 %24 %24 -%408 = OpCompositeConstruct %215 %25 %25 %25 -%409 = OpBitwiseAnd %215 %407 %408 -%410 = OpBitwiseXor %8 %18 %7 -%411 = OpBitwiseXor %21 %24 %25 -%412 = OpCompositeConstruct %204 %18 %18 -%413 = OpCompositeConstruct %204 %7 %7 -%414 = OpBitwiseXor %204 %412 %413 -%415 = OpCompositeConstruct %215 %24 %24 %24 -%416 = OpCompositeConstruct %215 %25 %25 %25 -%417 = OpBitwiseXor %215 %415 %416 -%418 = OpShiftLeftLogical %8 %18 %25 -%419 = OpShiftLeftLogical %21 %24 %25 -%420 = OpCompositeConstruct %204 %18 %18 -%421 = OpCompositeConstruct %43 %25 %25 -%422 = OpShiftLeftLogical %204 %420 %421 -%423 = OpCompositeConstruct %215 %24 %24 %24 -%424 = OpCompositeConstruct %215 %25 %25 %25 -%425 = OpShiftLeftLogical %215 %423 %424 -%426 = OpShiftRightArithmetic %8 %18 %25 -%427 = OpShiftRightLogical %21 %24 %25 -%428 = OpCompositeConstruct %204 %18 %18 -%429 = OpCompositeConstruct %43 %25 %25 -%430 = OpShiftRightArithmetic %204 %428 %429 -%431 = OpCompositeConstruct %215 %24 %24 %24 -%432 = OpCompositeConstruct %215 %25 %25 %25 -%433 = OpShiftRightLogical %215 %431 %432 +%378 = OpFunction %2 None %164 +%377 = OpLabel +OpBranch %379 +%379 = OpLabel +%380 = OpNot %8 %7 +%381 = OpNot %11 %184 +%382 = OpCompositeConstruct %196 %7 %7 +%383 = OpNot %196 %382 +%384 = OpCompositeConstruct %207 %184 %184 %184 +%385 = OpNot %207 %384 +%386 = OpBitwiseOr %8 %69 %7 +%387 = OpBitwiseOr %11 %183 %184 +%388 = OpCompositeConstruct %196 %69 %69 +%389 = OpCompositeConstruct %196 %7 %7 +%390 = OpBitwiseOr %196 %388 %389 +%391 = OpCompositeConstruct %207 %183 %183 %183 +%392 = OpCompositeConstruct %207 %184 %184 %184 +%393 = OpBitwiseOr %207 %391 %392 +%394 = OpBitwiseAnd %8 %69 %7 +%395 = OpBitwiseAnd %11 %183 %184 +%396 = OpCompositeConstruct %196 %69 %69 +%397 = OpCompositeConstruct %196 %7 %7 +%398 = OpBitwiseAnd %196 %396 %397 +%399 = OpCompositeConstruct %207 %183 %183 %183 +%400 = OpCompositeConstruct %207 %184 %184 %184 +%401 = OpBitwiseAnd %207 %399 %400 +%402 = OpBitwiseXor %8 %69 %7 +%403 = OpBitwiseXor %11 %183 %184 +%404 = OpCompositeConstruct %196 %69 %69 +%405 = OpCompositeConstruct %196 %7 %7 +%406 = OpBitwiseXor %196 %404 %405 +%407 = OpCompositeConstruct %207 %183 %183 %183 +%408 = OpCompositeConstruct %207 %184 %184 %184 +%409 = OpBitwiseXor %207 %407 %408 +%410 = OpShiftLeftLogical %8 %69 %184 +%411 = OpShiftLeftLogical %11 %183 %184 +%412 = OpCompositeConstruct %196 %69 %69 +%413 = OpCompositeConstruct %22 %184 %184 +%414 = OpShiftLeftLogical %196 %412 %413 +%415 = OpCompositeConstruct %207 %183 %183 %183 +%416 = OpCompositeConstruct %207 %184 %184 %184 +%417 = OpShiftLeftLogical %207 %415 %416 +%418 = OpShiftRightArithmetic %8 %69 %184 +%419 = OpShiftRightLogical %11 %183 %184 +%420 = OpCompositeConstruct %196 %69 %69 +%421 = OpCompositeConstruct %22 %184 %184 +%422 = OpShiftRightArithmetic %196 %420 %421 +%423 = OpCompositeConstruct %207 %183 %183 %183 +%424 = OpCompositeConstruct %207 %184 %184 %184 +%425 = OpShiftRightLogical %207 %423 %424 OpReturn OpFunctionEnd -%435 = OpFunction %2 None %175 -%434 = OpLabel -OpBranch %436 -%436 = OpLabel -%437 = OpIEqual %10 %18 %7 -%438 = OpIEqual %10 %24 %25 -%439 = OpFOrdEqual %10 %14 %3 -%440 = OpCompositeConstruct %204 %18 %18 -%441 = OpCompositeConstruct %204 %7 %7 -%442 = OpIEqual %178 %440 %441 -%443 = OpCompositeConstruct %215 %24 %24 %24 -%444 = OpCompositeConstruct %215 %25 %25 %25 -%445 = OpIEqual %39 %443 %444 -%446 = OpCompositeConstruct %34 %14 %14 %14 %14 -%447 = OpCompositeConstruct %34 %3 %3 %3 %3 -%448 = OpFOrdEqual %36 %446 %447 -%449 = OpINotEqual %10 %18 %7 -%450 = OpINotEqual %10 %24 %25 -%451 = OpFOrdNotEqual %10 %14 %3 -%452 = OpCompositeConstruct %204 %18 %18 -%453 = OpCompositeConstruct %204 %7 %7 -%454 = OpINotEqual %178 %452 %453 -%455 = OpCompositeConstruct %215 %24 %24 %24 -%456 = OpCompositeConstruct %215 %25 %25 %25 -%457 = OpINotEqual %39 %455 %456 -%458 = OpCompositeConstruct %34 %14 %14 %14 %14 -%459 = OpCompositeConstruct %34 %3 %3 %3 %3 -%460 = OpFOrdNotEqual %36 %458 %459 -%461 = OpSLessThan %10 %18 %7 -%462 = OpULessThan %10 %24 %25 -%463 = OpFOrdLessThan %10 %14 %3 -%464 = OpCompositeConstruct %204 %18 %18 -%465 = OpCompositeConstruct %204 %7 %7 -%466 = OpSLessThan %178 %464 %465 -%467 = OpCompositeConstruct %215 %24 %24 %24 -%468 = OpCompositeConstruct %215 %25 %25 %25 -%469 = OpULessThan %39 %467 %468 -%470 = OpCompositeConstruct %34 %14 %14 %14 %14 -%471 = OpCompositeConstruct %34 %3 %3 %3 %3 -%472 = OpFOrdLessThan %36 %470 %471 -%473 = OpSLessThanEqual %10 %18 %7 -%474 = OpULessThanEqual %10 %24 %25 -%475 = OpFOrdLessThanEqual %10 %14 %3 -%476 = OpCompositeConstruct %204 %18 %18 -%477 = OpCompositeConstruct %204 %7 %7 -%478 = OpSLessThanEqual %178 %476 %477 -%479 = OpCompositeConstruct %215 %24 %24 %24 -%480 = OpCompositeConstruct %215 %25 %25 %25 -%481 = OpULessThanEqual %39 %479 %480 -%482 = OpCompositeConstruct %34 %14 %14 %14 %14 -%483 = OpCompositeConstruct %34 %3 %3 %3 %3 -%484 = OpFOrdLessThanEqual %36 %482 %483 -%485 = OpSGreaterThan %10 %18 %7 -%486 = OpUGreaterThan %10 %24 %25 -%487 = OpFOrdGreaterThan %10 %14 %3 -%488 = OpCompositeConstruct %204 %18 %18 -%489 = OpCompositeConstruct %204 %7 %7 -%490 = OpSGreaterThan %178 %488 %489 -%491 = OpCompositeConstruct %215 %24 %24 %24 -%492 = OpCompositeConstruct %215 %25 %25 %25 -%493 = OpUGreaterThan %39 %491 %492 -%494 = OpCompositeConstruct %34 %14 %14 %14 %14 -%495 = OpCompositeConstruct %34 %3 %3 %3 %3 -%496 = OpFOrdGreaterThan %36 %494 %495 -%497 = OpSGreaterThanEqual %10 %18 %7 -%498 = OpUGreaterThanEqual %10 %24 %25 -%499 = OpFOrdGreaterThanEqual %10 %14 %3 -%500 = OpCompositeConstruct %204 %18 %18 -%501 = OpCompositeConstruct %204 %7 %7 -%502 = OpSGreaterThanEqual %178 %500 %501 -%503 = OpCompositeConstruct %215 %24 %24 %24 -%504 = OpCompositeConstruct %215 %25 %25 %25 -%505 = OpUGreaterThanEqual %39 %503 %504 -%506 = OpCompositeConstruct %34 %14 %14 %14 %14 -%507 = OpCompositeConstruct %34 %3 %3 %3 %3 -%508 = OpFOrdGreaterThanEqual %36 %506 %507 +%427 = OpFunction %2 None %164 +%426 = OpLabel +OpBranch %428 +%428 = OpLabel +%429 = OpIEqual %15 %69 %7 +%430 = OpIEqual %15 %183 %184 +%431 = OpFOrdEqual %15 %65 %3 +%432 = OpCompositeConstruct %196 %69 %69 +%433 = OpCompositeConstruct %196 %7 %7 +%434 = OpIEqual %167 %432 %433 +%435 = OpCompositeConstruct %207 %183 %183 %183 +%436 = OpCompositeConstruct %207 %184 %184 %184 +%437 = OpIEqual %18 %435 %436 +%438 = OpCompositeConstruct %12 %65 %65 %65 %65 +%439 = OpCompositeConstruct %12 %3 %3 %3 %3 +%440 = OpFOrdEqual %14 %438 %439 +%441 = OpINotEqual %15 %69 %7 +%442 = OpINotEqual %15 %183 %184 +%443 = OpFOrdNotEqual %15 %65 %3 +%444 = OpCompositeConstruct %196 %69 %69 +%445 = OpCompositeConstruct %196 %7 %7 +%446 = OpINotEqual %167 %444 %445 +%447 = OpCompositeConstruct %207 %183 %183 %183 +%448 = OpCompositeConstruct %207 %184 %184 %184 +%449 = OpINotEqual %18 %447 %448 +%450 = OpCompositeConstruct %12 %65 %65 %65 %65 +%451 = OpCompositeConstruct %12 %3 %3 %3 %3 +%452 = OpFOrdNotEqual %14 %450 %451 +%453 = OpSLessThan %15 %69 %7 +%454 = OpULessThan %15 %183 %184 +%455 = OpFOrdLessThan %15 %65 %3 +%456 = OpCompositeConstruct %196 %69 %69 +%457 = OpCompositeConstruct %196 %7 %7 +%458 = OpSLessThan %167 %456 %457 +%459 = OpCompositeConstruct %207 %183 %183 %183 +%460 = OpCompositeConstruct %207 %184 %184 %184 +%461 = OpULessThan %18 %459 %460 +%462 = OpCompositeConstruct %12 %65 %65 %65 %65 +%463 = OpCompositeConstruct %12 %3 %3 %3 %3 +%464 = OpFOrdLessThan %14 %462 %463 +%465 = OpSLessThanEqual %15 %69 %7 +%466 = OpULessThanEqual %15 %183 %184 +%467 = OpFOrdLessThanEqual %15 %65 %3 +%468 = OpCompositeConstruct %196 %69 %69 +%469 = OpCompositeConstruct %196 %7 %7 +%470 = OpSLessThanEqual %167 %468 %469 +%471 = OpCompositeConstruct %207 %183 %183 %183 +%472 = OpCompositeConstruct %207 %184 %184 %184 +%473 = OpULessThanEqual %18 %471 %472 +%474 = OpCompositeConstruct %12 %65 %65 %65 %65 +%475 = OpCompositeConstruct %12 %3 %3 %3 %3 +%476 = OpFOrdLessThanEqual %14 %474 %475 +%477 = OpSGreaterThan %15 %69 %7 +%478 = OpUGreaterThan %15 %183 %184 +%479 = OpFOrdGreaterThan %15 %65 %3 +%480 = OpCompositeConstruct %196 %69 %69 +%481 = OpCompositeConstruct %196 %7 %7 +%482 = OpSGreaterThan %167 %480 %481 +%483 = OpCompositeConstruct %207 %183 %183 %183 +%484 = OpCompositeConstruct %207 %184 %184 %184 +%485 = OpUGreaterThan %18 %483 %484 +%486 = OpCompositeConstruct %12 %65 %65 %65 %65 +%487 = OpCompositeConstruct %12 %3 %3 %3 %3 +%488 = OpFOrdGreaterThan %14 %486 %487 +%489 = OpSGreaterThanEqual %15 %69 %7 +%490 = OpUGreaterThanEqual %15 %183 %184 +%491 = OpFOrdGreaterThanEqual %15 %65 %3 +%492 = OpCompositeConstruct %196 %69 %69 +%493 = OpCompositeConstruct %196 %7 %7 +%494 = OpSGreaterThanEqual %167 %492 %493 +%495 = OpCompositeConstruct %207 %183 %183 %183 +%496 = OpCompositeConstruct %207 %184 %184 %184 +%497 = OpUGreaterThanEqual %18 %495 %496 +%498 = OpCompositeConstruct %12 %65 %65 %65 %65 +%499 = OpCompositeConstruct %12 %3 %3 %3 %3 +%500 = OpFOrdGreaterThanEqual %14 %498 %499 OpReturn OpFunctionEnd -%516 = OpFunction %2 None %175 -%515 = OpLabel -%509 = OpVariable %510 Function %511 -%512 = OpVariable %513 Function %514 -OpBranch %518 -%518 = OpLabel -OpStore %509 %7 -%519 = OpLoad %8 %509 -%520 = OpIAdd %8 %519 %7 -OpStore %509 %520 -%521 = OpLoad %8 %509 -%522 = OpISub %8 %521 %7 -OpStore %509 %522 -%523 = OpLoad %8 %509 -%524 = OpLoad %8 %509 -%525 = OpIMul %8 %524 %523 -OpStore %509 %525 -%526 = OpLoad %8 %509 -%527 = OpLoad %8 %509 -%528 = OpSDiv %8 %527 %526 -OpStore %509 %528 -%529 = OpLoad %8 %509 -%530 = OpSRem %8 %529 %7 -OpStore %509 %530 -%531 = OpLoad %8 %509 -%532 = OpBitwiseAnd %8 %531 %11 -OpStore %509 %532 -%533 = OpLoad %8 %509 -%534 = OpBitwiseOr %8 %533 %11 -OpStore %509 %534 -%535 = OpLoad %8 %509 -%536 = OpBitwiseXor %8 %535 %11 -OpStore %509 %536 -%537 = OpLoad %8 %509 -%538 = OpShiftLeftLogical %8 %537 %24 -OpStore %509 %538 -%539 = OpLoad %8 %509 -%540 = OpShiftRightArithmetic %8 %539 %25 -OpStore %509 %540 -%541 = OpLoad %8 %509 -%542 = OpIAdd %8 %541 %7 -OpStore %509 %542 -%543 = OpLoad %8 %509 +%508 = OpFunction %2 None %164 +%507 = OpLabel +%501 = OpVariable %502 Function %503 +%504 = OpVariable %505 Function %506 +OpBranch %510 +%510 = OpLabel +OpStore %501 %7 +%511 = OpLoad %8 %501 +%512 = OpIAdd %8 %511 %7 +OpStore %501 %512 +%513 = OpLoad %8 %501 +%514 = OpISub %8 %513 %7 +OpStore %501 %514 +%515 = OpLoad %8 %501 +%516 = OpLoad %8 %501 +%517 = OpIMul %8 %516 %515 +OpStore %501 %517 +%518 = OpLoad %8 %501 +%519 = OpLoad %8 %501 +%520 = OpSDiv %8 %519 %518 +OpStore %501 %520 +%521 = OpLoad %8 %501 +%522 = OpSRem %8 %521 %7 +OpStore %501 %522 +%523 = OpLoad %8 %501 +%524 = OpBitwiseAnd %8 %523 %38 +OpStore %501 %524 +%525 = OpLoad %8 %501 +%526 = OpBitwiseOr %8 %525 %38 +OpStore %501 %526 +%527 = OpLoad %8 %501 +%528 = OpBitwiseXor %8 %527 %38 +OpStore %501 %528 +%529 = OpLoad %8 %501 +%530 = OpShiftLeftLogical %8 %529 %183 +OpStore %501 %530 +%531 = OpLoad %8 %501 +%532 = OpShiftRightArithmetic %8 %531 %184 +OpStore %501 %532 +%533 = OpLoad %8 %501 +%534 = OpIAdd %8 %533 %7 +OpStore %501 %534 +%535 = OpLoad %8 %501 +%536 = OpISub %8 %535 %7 +OpStore %501 %536 +OpStore %504 %509 +%538 = OpAccessChain %537 %504 %184 +%539 = OpLoad %8 %538 +%540 = OpIAdd %8 %539 %7 +%541 = OpAccessChain %537 %504 %184 +OpStore %541 %540 +%542 = OpAccessChain %537 %504 %184 +%543 = OpLoad %8 %542 %544 = OpISub %8 %543 %7 -OpStore %509 %544 -OpStore %512 %517 -%546 = OpAccessChain %545 %512 %25 -%547 = OpLoad %8 %546 -%548 = OpIAdd %8 %547 %7 -%549 = OpAccessChain %545 %512 %25 -OpStore %549 %548 -%550 = OpAccessChain %545 %512 %25 -%551 = OpLoad %8 %550 -%552 = OpISub %8 %551 %7 -%553 = OpAccessChain %545 %512 %25 -OpStore %553 %552 +%545 = OpAccessChain %537 %504 %184 +OpStore %545 %544 OpReturn OpFunctionEnd -%555 = OpFunction %2 None %175 -%554 = OpLabel +%547 = OpFunction %2 None %164 +%546 = OpLabel OpBranch %556 %556 = OpLabel -%557 = OpSNegate %8 %27 -%558 = OpSNegate %8 %28 -%559 = OpSNegate %8 %29 +%557 = OpSNegate %8 %549 +%558 = OpSNegate %8 %550 +%559 = OpSNegate %8 %551 %560 = OpSNegate %8 %559 -%561 = OpSNegate %8 %30 +%561 = OpSNegate %8 %552 %562 = OpSNegate %8 %561 -%563 = OpSNegate %8 %31 +%563 = OpSNegate %8 %553 %564 = OpSNegate %8 %563 %565 = OpSNegate %8 %564 %566 = OpSNegate %8 %565 -%567 = OpSNegate %8 %32 +%567 = OpSNegate %8 %554 %568 = OpSNegate %8 %567 %569 = OpSNegate %8 %568 %570 = OpSNegate %8 %569 -%571 = OpSNegate %8 %33 +%571 = OpSNegate %8 %555 %572 = OpSNegate %8 %571 %573 = OpSNegate %8 %572 %574 = OpSNegate %8 %573 OpReturn OpFunctionEnd -%576 = OpFunction %2 None %175 +%576 = OpFunction %2 None %164 %575 = OpLabel OpBranch %577 %577 = OpLabel -%578 = OpFunctionCall %34 %56 -%579 = OpFunctionCall %34 %81 -%580 = OpVectorShuffle %38 %51 %51 0 1 2 -%581 = OpFunctionCall %38 %116 %580 -%582 = OpFunctionCall %4 %127 -%583 = OpFunctionCall %2 %174 -%584 = OpFunctionCall %2 %192 -%585 = OpFunctionCall %2 %386 -%586 = OpFunctionCall %2 %435 -%587 = OpFunctionCall %2 %516 +%578 = OpFunctionCall %12 %35 +%579 = OpFunctionCall %12 %64 +%580 = OpVectorShuffle %17 %30 %30 0 1 2 +%581 = OpFunctionCall %17 %104 %580 +%582 = OpFunctionCall %4 %115 +%583 = OpFunctionCall %2 %163 +%584 = OpFunctionCall %2 %181 +%585 = OpFunctionCall %2 %378 +%586 = OpFunctionCall %2 %427 +%587 = OpFunctionCall %2 %508 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/padding.spvasm b/tests/out/spv/padding.spvasm index 44ec6a4d1..713979b35 100644 --- a/tests/out/spv/padding.spvasm +++ b/tests/out/spv/padding.spvasm @@ -5,95 +5,95 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %27 "vertex" %25 +OpEntryPoint Vertex %26 "vertex" %24 OpSource GLSL 450 +OpMemberName %7 0 "a" +OpName %7 "S" OpMemberName %8 0 "a" -OpName %8 "S" -OpMemberName %9 0 "a" -OpMemberName %9 1 "b" -OpName %9 "Test" -OpMemberName %11 0 "a" -OpMemberName %11 1 "b" -OpName %11 "Test2" -OpMemberName %13 0 "a" -OpMemberName %13 1 "b" -OpName %13 "Test3" -OpName %15 "input1" -OpName %18 "input2" -OpName %21 "input3" -OpName %27 "vertex" +OpMemberName %8 1 "b" +OpName %8 "Test" +OpMemberName %10 0 "a" +OpMemberName %10 1 "b" +OpName %10 "Test2" +OpMemberName %12 0 "a" +OpMemberName %12 1 "b" +OpName %12 "Test3" +OpName %14 "input1" +OpName %17 "input2" +OpName %20 "input3" +OpName %26 "vertex" +OpMemberDecorate %7 0 Offset 0 OpMemberDecorate %8 0 Offset 0 -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 16 -OpDecorate %10 ArrayStride 16 -OpMemberDecorate %11 0 Offset 0 -OpMemberDecorate %11 1 Offset 32 -OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 0 ColMajor -OpMemberDecorate %13 0 MatrixStride 16 -OpMemberDecorate %13 1 Offset 64 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 0 -OpDecorate %16 Block -OpMemberDecorate %16 0 Offset 0 -OpDecorate %18 DescriptorSet 0 -OpDecorate %18 Binding 1 -OpDecorate %19 Block -OpMemberDecorate %19 0 Offset 0 -OpDecorate %21 DescriptorSet 0 -OpDecorate %21 Binding 2 -OpDecorate %22 Block -OpMemberDecorate %22 0 Offset 0 -OpDecorate %25 BuiltIn Position +OpMemberDecorate %8 1 Offset 16 +OpDecorate %9 ArrayStride 16 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 32 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 0 ColMajor +OpMemberDecorate %12 0 MatrixStride 16 +OpMemberDecorate %12 1 Offset 64 +OpDecorate %14 DescriptorSet 0 +OpDecorate %14 Binding 0 +OpDecorate %15 Block +OpMemberDecorate %15 0 Offset 0 +OpDecorate %17 DescriptorSet 0 +OpDecorate %17 Binding 1 +OpDecorate %18 Block +OpMemberDecorate %18 0 Offset 0 +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 2 +OpDecorate %21 Block +OpMemberDecorate %21 0 Offset 0 +OpDecorate %24 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 %6 = OpTypeFloat 32 -%5 = OpConstant %6 1.0 -%7 = OpTypeVector %6 3 -%8 = OpTypeStruct %7 -%9 = OpTypeStruct %8 %6 -%10 = OpTypeArray %7 %3 -%11 = OpTypeStruct %10 %6 -%12 = OpTypeMatrix %7 4 -%13 = OpTypeStruct %12 %6 -%14 = OpTypeVector %6 4 -%16 = OpTypeStruct %9 -%17 = OpTypePointer Uniform %16 -%15 = OpVariable %17 Uniform -%19 = OpTypeStruct %11 -%20 = OpTypePointer Uniform %19 -%18 = OpVariable %20 Uniform -%22 = OpTypeStruct %13 -%23 = OpTypePointer Uniform %22 -%21 = OpVariable %23 Uniform -%26 = OpTypePointer Output %14 -%25 = OpVariable %26 Output -%28 = OpTypeFunction %2 -%29 = OpTypePointer Uniform %9 -%31 = OpTypeInt 32 0 -%30 = OpConstant %31 0 -%33 = OpTypePointer Uniform %11 -%35 = OpTypePointer Uniform %13 +%5 = OpTypeVector %6 3 +%7 = OpTypeStruct %5 +%8 = OpTypeStruct %7 %6 +%9 = OpTypeArray %5 %3 +%10 = OpTypeStruct %9 %6 +%11 = OpTypeMatrix %5 4 +%12 = OpTypeStruct %11 %6 +%13 = OpTypeVector %6 4 +%15 = OpTypeStruct %8 +%16 = OpTypePointer Uniform %15 +%14 = OpVariable %16 Uniform +%18 = OpTypeStruct %10 +%19 = OpTypePointer Uniform %18 +%17 = OpVariable %19 Uniform +%21 = OpTypeStruct %12 +%22 = OpTypePointer Uniform %21 +%20 = OpVariable %22 Uniform +%25 = OpTypePointer Output %13 +%24 = OpVariable %25 Output +%27 = OpTypeFunction %2 +%28 = OpTypePointer Uniform %8 +%30 = OpTypeInt 32 0 +%29 = OpConstant %30 0 +%32 = OpTypePointer Uniform %10 +%34 = OpTypePointer Uniform %12 +%36 = OpConstant %6 1.0 %39 = OpTypePointer Uniform %6 -%40 = OpConstant %31 1 -%27 = OpFunction %2 None %28 -%24 = OpLabel -%32 = OpAccessChain %29 %15 %30 -%34 = OpAccessChain %33 %18 %30 -%36 = OpAccessChain %35 %21 %30 +%40 = OpConstant %30 1 +%26 = OpFunction %2 None %27 +%23 = OpLabel +%31 = OpAccessChain %28 %14 %29 +%33 = OpAccessChain %32 %17 %29 +%35 = OpAccessChain %34 %20 %29 OpBranch %37 %37 = OpLabel -%38 = OpCompositeConstruct %14 %5 %5 %5 %5 -%41 = OpAccessChain %39 %32 %40 +%38 = OpCompositeConstruct %13 %36 %36 %36 %36 +%41 = OpAccessChain %39 %31 %40 %42 = OpLoad %6 %41 -%43 = OpVectorTimesScalar %14 %38 %42 -%44 = OpAccessChain %39 %34 %40 +%43 = OpVectorTimesScalar %13 %38 %42 +%44 = OpAccessChain %39 %33 %40 %45 = OpLoad %6 %44 -%46 = OpVectorTimesScalar %14 %43 %45 -%47 = OpAccessChain %39 %36 %40 +%46 = OpVectorTimesScalar %13 %43 %45 +%47 = OpAccessChain %39 %35 %40 %48 = OpLoad %6 %47 -%49 = OpVectorTimesScalar %14 %46 %48 -OpStore %25 %49 +%49 = OpVectorTimesScalar %13 %46 %48 +OpStore %24 %49 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index 81a17b558..71a680aa7 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -8,71 +8,71 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpSource GLSL 450 -OpMemberName %8 0 "arr" -OpName %8 "DynamicArray" -OpName %11 "dynamic_array" -OpName %12 "v" -OpName %16 "f" +OpMemberName %7 0 "arr" +OpName %7 "DynamicArray" +OpName %10 "dynamic_array" +OpName %11 "v" +OpName %15 "f" OpName %23 "i" OpName %24 "v" OpName %25 "index_unsized" OpName %34 "i" OpName %35 "v" OpName %36 "index_dynamic_array" -OpDecorate %7 ArrayStride 4 -OpMemberDecorate %8 0 Offset 0 -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 0 -OpDecorate %8 Block +OpDecorate %6 ArrayStride 4 +OpMemberDecorate %7 0 Offset 0 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 0 +OpDecorate %7 Block %2 = OpTypeVoid %4 = OpTypeInt 32 1 -%3 = OpConstant %4 10 -%5 = OpTypeVector %4 2 -%6 = OpTypeInt 32 0 -%7 = OpTypeRuntimeArray %6 -%8 = OpTypeStruct %7 -%9 = OpTypePointer StorageBuffer %8 -%10 = OpTypePointer StorageBuffer %7 -%11 = OpVariable %9 StorageBuffer -%13 = OpTypePointer Function %5 -%14 = OpConstantNull %5 -%17 = OpTypeFunction %2 +%3 = OpTypeVector %4 2 +%5 = OpTypeInt 32 0 +%6 = OpTypeRuntimeArray %5 +%7 = OpTypeStruct %6 +%8 = OpTypePointer StorageBuffer %7 +%9 = OpTypePointer StorageBuffer %6 +%10 = OpVariable %8 StorageBuffer +%12 = OpTypePointer Function %3 +%13 = OpConstantNull %3 +%16 = OpTypeFunction %2 +%17 = OpConstant %4 10 %19 = OpTypePointer Function %4 -%20 = OpConstant %6 0 -%26 = OpTypeFunction %2 %4 %6 -%28 = OpTypePointer StorageBuffer %6 -%16 = OpFunction %2 None %17 -%15 = OpLabel -%12 = OpVariable %13 Function %14 +%20 = OpConstant %5 0 +%26 = OpTypeFunction %2 %4 %5 +%28 = OpTypePointer StorageBuffer %5 +%15 = OpFunction %2 None %16 +%14 = OpLabel +%11 = OpVariable %12 Function %13 OpBranch %18 %18 = OpLabel -%21 = OpAccessChain %19 %12 %20 -OpStore %21 %3 +%21 = OpAccessChain %19 %11 %20 +OpStore %21 %17 OpReturn OpFunctionEnd %25 = OpFunction %2 None %26 %23 = OpFunctionParameter %4 -%24 = OpFunctionParameter %6 +%24 = OpFunctionParameter %5 %22 = OpLabel OpBranch %27 %27 = OpLabel -%29 = OpAccessChain %28 %11 %20 %23 -%30 = OpLoad %6 %29 -%31 = OpIAdd %6 %30 %24 -%32 = OpAccessChain %28 %11 %20 %23 +%29 = OpAccessChain %28 %10 %20 %23 +%30 = OpLoad %5 %29 +%31 = OpIAdd %5 %30 %24 +%32 = OpAccessChain %28 %10 %20 %23 OpStore %32 %31 OpReturn OpFunctionEnd %36 = OpFunction %2 None %26 %34 = OpFunctionParameter %4 -%35 = OpFunctionParameter %6 +%35 = OpFunctionParameter %5 %33 = OpLabel OpBranch %37 %37 = OpLabel -%38 = OpAccessChain %28 %11 %20 %34 -%39 = OpLoad %6 %38 -%40 = OpIAdd %6 %39 %35 -%41 = OpAccessChain %28 %11 %20 %34 +%38 = OpAccessChain %28 %10 %20 %34 +%39 = OpLoad %5 %38 +%40 = OpIAdd %5 %39 %35 +%41 = OpAccessChain %28 %10 %20 %34 OpStore %41 %40 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index c082d3d46..3ba407ded 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -9,38 +9,38 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpSource GLSL 450 -OpMemberName %15 0 "a" -OpName %15 "InStorage" -OpMemberName %17 0 "a" -OpName %17 "InUniform" -OpName %23 "in_storage" -OpName %26 "in_uniform" -OpName %29 "image_2d_array" -OpName %31 "in_workgroup" -OpName %33 "in_private" -OpName %36 "in_function" -OpName %40 "c" -OpName %41 "i" -OpName %42 "l" -OpName %43 "mock_function" -OpDecorate %14 ArrayStride 16 -OpMemberDecorate %15 0 Offset 0 -OpDecorate %16 ArrayStride 16 -OpMemberDecorate %17 0 Offset 0 -OpDecorate %19 ArrayStride 4 -OpDecorate %20 ArrayStride 4 -OpDecorate %22 ArrayStride 16 -OpDecorate %23 NonWritable +OpMemberName %12 0 "a" +OpName %12 "InStorage" +OpMemberName %14 0 "a" +OpName %14 "InUniform" +OpName %20 "in_storage" +OpName %23 "in_uniform" +OpName %26 "image_2d_array" +OpName %28 "in_workgroup" +OpName %30 "in_private" +OpName %33 "in_function" +OpName %37 "c" +OpName %38 "i" +OpName %39 "l" +OpName %40 "mock_function" +OpDecorate %11 ArrayStride 16 +OpMemberDecorate %12 0 Offset 0 +OpDecorate %13 ArrayStride 16 +OpMemberDecorate %14 0 Offset 0 +OpDecorate %16 ArrayStride 4 +OpDecorate %17 ArrayStride 4 +OpDecorate %19 ArrayStride 16 +OpDecorate %20 NonWritable +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 0 +OpDecorate %21 Block +OpMemberDecorate %21 0 Offset 0 OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 0 +OpDecorate %23 Binding 1 OpDecorate %24 Block OpMemberDecorate %24 0 Offset 0 OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 1 -OpDecorate %27 Block -OpMemberDecorate %27 0 Offset 0 -OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 2 +OpDecorate %26 Binding 2 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -49,102 +49,102 @@ OpDecorate %29 Binding 2 %7 = OpConstant %4 40 %8 = OpConstant %4 2 %10 = OpTypeFloat 32 -%9 = OpConstant %10 0.707 -%11 = OpConstant %10 0.0 -%12 = OpConstant %10 1.0 -%13 = OpTypeVector %10 4 -%14 = OpTypeArray %13 %3 -%15 = OpTypeStruct %14 -%16 = OpTypeArray %13 %5 -%17 = OpTypeStruct %16 -%18 = OpTypeImage %10 2D 0 1 0 1 Unknown -%19 = OpTypeArray %10 %6 -%20 = OpTypeArray %10 %7 -%21 = OpTypeVector %4 2 -%22 = OpTypeArray %13 %8 -%24 = OpTypeStruct %15 -%25 = OpTypePointer StorageBuffer %24 -%23 = OpVariable %25 StorageBuffer -%27 = OpTypeStruct %17 -%28 = OpTypePointer Uniform %27 -%26 = OpVariable %28 Uniform -%30 = OpTypePointer UniformConstant %18 -%29 = OpVariable %30 UniformConstant -%32 = OpTypePointer Workgroup %19 -%31 = OpVariable %32 Workgroup -%34 = OpTypePointer Private %20 -%35 = OpConstantNull %20 -%33 = OpVariable %34 Private %35 -%37 = OpTypePointer Function %22 -%38 = OpConstantNull %22 -%44 = OpTypeFunction %13 %21 %4 %4 -%45 = OpTypePointer StorageBuffer %15 -%47 = OpTypeInt 32 0 -%46 = OpConstant %47 0 -%49 = OpTypePointer Uniform %17 -%56 = OpTypePointer StorageBuffer %14 -%57 = OpTypePointer StorageBuffer %13 -%60 = OpTypePointer Uniform %16 -%61 = OpTypePointer Uniform %13 +%9 = OpTypeVector %10 4 +%11 = OpTypeArray %9 %3 +%12 = OpTypeStruct %11 +%13 = OpTypeArray %9 %5 +%14 = OpTypeStruct %13 +%15 = OpTypeImage %10 2D 0 1 0 1 Unknown +%16 = OpTypeArray %10 %6 +%17 = OpTypeArray %10 %7 +%18 = OpTypeVector %4 2 +%19 = OpTypeArray %9 %8 +%21 = OpTypeStruct %12 +%22 = OpTypePointer StorageBuffer %21 +%20 = OpVariable %22 StorageBuffer +%24 = OpTypeStruct %14 +%25 = OpTypePointer Uniform %24 +%23 = OpVariable %25 Uniform +%27 = OpTypePointer UniformConstant %15 +%26 = OpVariable %27 UniformConstant +%29 = OpTypePointer Workgroup %16 +%28 = OpVariable %29 Workgroup +%31 = OpTypePointer Private %17 +%32 = OpConstantNull %17 +%30 = OpVariable %31 Private %32 +%34 = OpTypePointer Function %19 +%35 = OpConstantNull %19 +%41 = OpTypeFunction %9 %18 %4 %4 +%42 = OpTypePointer StorageBuffer %12 +%44 = OpTypeInt 32 0 +%43 = OpConstant %44 0 +%46 = OpTypePointer Uniform %14 +%49 = OpConstant %10 0.707 +%50 = OpConstant %10 0.0 +%51 = OpConstant %10 1.0 +%56 = OpTypePointer StorageBuffer %11 +%57 = OpTypePointer StorageBuffer %9 +%60 = OpTypePointer Uniform %13 +%61 = OpTypePointer Uniform %9 %65 = OpTypeVector %4 3 %67 = OpTypeBool -%68 = OpConstantNull %13 +%68 = OpConstantNull %9 %74 = OpTypeVector %67 3 %81 = OpTypePointer Workgroup %10 -%82 = OpConstant %47 29 +%82 = OpConstant %44 29 %88 = OpTypePointer Private %10 -%89 = OpConstant %47 39 -%95 = OpTypePointer Function %13 -%96 = OpConstant %47 1 -%43 = OpFunction %13 None %44 -%40 = OpFunctionParameter %21 -%41 = OpFunctionParameter %4 -%42 = OpFunctionParameter %4 -%39 = OpLabel -%36 = OpVariable %37 Function %38 -%48 = OpAccessChain %45 %23 %46 -%50 = OpAccessChain %49 %26 %46 -%51 = OpLoad %18 %29 +%89 = OpConstant %44 39 +%95 = OpTypePointer Function %9 +%96 = OpConstant %44 1 +%40 = OpFunction %9 None %41 +%37 = OpFunctionParameter %18 +%38 = OpFunctionParameter %4 +%39 = OpFunctionParameter %4 +%36 = OpLabel +%33 = OpVariable %34 Function %35 +%45 = OpAccessChain %42 %20 %43 +%47 = OpAccessChain %46 %23 %43 +%48 = OpLoad %15 %26 OpBranch %52 %52 = OpLabel -%53 = OpCompositeConstruct %13 %9 %11 %11 %12 -%54 = OpCompositeConstruct %13 %11 %9 %11 %12 -%55 = OpCompositeConstruct %22 %53 %54 -OpStore %36 %55 -%58 = OpAccessChain %57 %48 %46 %41 -%59 = OpLoad %13 %58 -%62 = OpAccessChain %61 %50 %46 %41 -%63 = OpLoad %13 %62 -%64 = OpFAdd %13 %59 %63 -%66 = OpCompositeConstruct %65 %40 %41 -%69 = OpImageQueryLevels %4 %51 -%70 = OpULessThan %67 %42 %69 +%53 = OpCompositeConstruct %9 %49 %50 %50 %51 +%54 = OpCompositeConstruct %9 %50 %49 %50 %51 +%55 = OpCompositeConstruct %19 %53 %54 +OpStore %33 %55 +%58 = OpAccessChain %57 %45 %43 %38 +%59 = OpLoad %9 %58 +%62 = OpAccessChain %61 %47 %43 %38 +%63 = OpLoad %9 %62 +%64 = OpFAdd %9 %59 %63 +%66 = OpCompositeConstruct %65 %37 %38 +%69 = OpImageQueryLevels %4 %48 +%70 = OpULessThan %67 %39 %69 OpSelectionMerge %71 None OpBranchConditional %70 %72 %71 %72 = OpLabel -%73 = OpImageQuerySizeLod %65 %51 %42 +%73 = OpImageQuerySizeLod %65 %48 %39 %75 = OpULessThan %74 %66 %73 %76 = OpAll %67 %75 OpBranchConditional %76 %77 %71 %77 = OpLabel -%78 = OpImageFetch %13 %51 %66 Lod %42 +%78 = OpImageFetch %9 %48 %66 Lod %39 OpBranch %71 %71 = OpLabel -%79 = OpPhi %13 %68 %52 %68 %72 %78 %77 -%80 = OpFAdd %13 %64 %79 -%83 = OpExtInst %47 %1 UMin %41 %82 -%84 = OpAccessChain %81 %31 %83 +%79 = OpPhi %9 %68 %52 %68 %72 %78 %77 +%80 = OpFAdd %9 %64 %79 +%83 = OpExtInst %44 %1 UMin %38 %82 +%84 = OpAccessChain %81 %28 %83 %85 = OpLoad %10 %84 -%86 = OpCompositeConstruct %13 %85 %85 %85 %85 -%87 = OpFAdd %13 %80 %86 -%90 = OpExtInst %47 %1 UMin %41 %89 -%91 = OpAccessChain %88 %33 %90 +%86 = OpCompositeConstruct %9 %85 %85 %85 %85 +%87 = OpFAdd %9 %80 %86 +%90 = OpExtInst %44 %1 UMin %38 %89 +%91 = OpAccessChain %88 %30 %90 %92 = OpLoad %10 %91 -%93 = OpCompositeConstruct %13 %92 %92 %92 %92 -%94 = OpFAdd %13 %87 %93 -%97 = OpExtInst %47 %1 UMin %41 %96 -%98 = OpAccessChain %95 %36 %97 -%99 = OpLoad %13 %98 -%100 = OpFAdd %13 %94 %99 +%93 = OpCompositeConstruct %9 %92 %92 %92 %92 +%94 = OpFAdd %9 %87 %93 +%97 = OpExtInst %44 %1 UMin %38 %96 +%98 = OpAccessChain %95 %33 %97 +%99 = OpLoad %9 %98 +%100 = OpFAdd %9 %94 %99 OpReturnValue %100 OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/quad.spvasm b/tests/out/spv/quad.spvasm index bb0409d14..9d4ba0226 100644 --- a/tests/out/spv/quad.spvasm +++ b/tests/out/spv/quad.spvasm @@ -5,115 +5,115 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %27 "vert_main" %18 %21 %23 %25 -OpEntryPoint Fragment %45 "frag_main" %42 %44 -OpEntryPoint Fragment %61 "fs_extra" %60 -OpExecutionMode %45 OriginUpperLeft -OpExecutionMode %61 OriginUpperLeft +OpEntryPoint Vertex %24 "vert_main" %15 %18 %20 %22 +OpEntryPoint Fragment %44 "frag_main" %41 %43 +OpEntryPoint Fragment %60 "fs_extra" %59 +OpExecutionMode %44 OriginUpperLeft +OpExecutionMode %60 OriginUpperLeft OpSource GLSL 450 OpName %3 "c_scale" -OpMemberName %10 0 "uv" -OpMemberName %10 1 "position" -OpName %10 "VertexOutput" -OpName %13 "u_texture" -OpName %15 "u_sampler" -OpName %18 "pos" -OpName %21 "uv" -OpName %23 "uv" -OpName %25 "position" -OpName %27 "vert_main" -OpName %42 "uv" -OpName %45 "frag_main" -OpName %61 "fs_extra" -OpMemberDecorate %10 0 Offset 0 -OpMemberDecorate %10 1 Offset 16 -OpDecorate %13 DescriptorSet 0 -OpDecorate %13 Binding 0 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 1 -OpDecorate %18 Location 0 -OpDecorate %21 Location 1 -OpDecorate %23 Location 0 -OpDecorate %25 BuiltIn Position -OpDecorate %42 Location 0 -OpDecorate %44 Location 0 -OpDecorate %60 Location 0 +OpMemberName %7 0 "uv" +OpMemberName %7 1 "position" +OpName %7 "VertexOutput" +OpName %10 "u_texture" +OpName %12 "u_sampler" +OpName %15 "pos" +OpName %18 "uv" +OpName %20 "uv" +OpName %22 "position" +OpName %24 "vert_main" +OpName %41 "uv" +OpName %44 "frag_main" +OpName %60 "fs_extra" +OpMemberDecorate %7 0 Offset 0 +OpMemberDecorate %7 1 Offset 16 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 0 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 1 +OpDecorate %15 Location 0 +OpDecorate %18 Location 1 +OpDecorate %20 Location 0 +OpDecorate %22 BuiltIn Position +OpDecorate %41 Location 0 +OpDecorate %43 Location 0 +OpDecorate %59 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpConstant %4 1.2 -%5 = OpConstant %4 0.0 -%6 = OpConstant %4 1.0 -%7 = OpConstant %4 0.5 -%8 = OpTypeVector %4 2 -%9 = OpTypeVector %4 4 -%10 = OpTypeStruct %8 %9 -%11 = OpTypeImage %4 2D 0 0 0 1 Unknown -%12 = OpTypeSampler -%14 = OpTypePointer UniformConstant %11 -%13 = OpVariable %14 UniformConstant -%16 = OpTypePointer UniformConstant %12 -%15 = OpVariable %16 UniformConstant -%19 = OpTypePointer Input %8 -%18 = OpVariable %19 Input -%21 = OpVariable %19 Input -%24 = OpTypePointer Output %8 -%23 = OpVariable %24 Output -%26 = OpTypePointer Output %9 -%25 = OpVariable %26 Output -%28 = OpTypeFunction %2 -%35 = OpTypePointer Output %4 -%37 = OpTypeInt 32 0 -%36 = OpConstant %37 1 -%42 = OpVariable %19 Input -%44 = OpVariable %26 Output -%49 = OpTypeSampledImage %11 -%53 = OpTypeBool -%60 = OpVariable %26 Output -%27 = OpFunction %2 None %28 -%17 = OpLabel -%20 = OpLoad %8 %18 -%22 = OpLoad %8 %21 -OpBranch %29 -%29 = OpLabel -%30 = OpVectorTimesScalar %8 %20 %3 -%31 = OpCompositeConstruct %9 %30 %5 %6 -%32 = OpCompositeConstruct %10 %22 %31 -%33 = OpCompositeExtract %8 %32 0 -OpStore %23 %33 -%34 = OpCompositeExtract %9 %32 1 -OpStore %25 %34 -%38 = OpAccessChain %35 %25 %36 -%39 = OpLoad %4 %38 -%40 = OpFNegate %4 %39 -OpStore %38 %40 +%5 = OpTypeVector %4 2 +%6 = OpTypeVector %4 4 +%7 = OpTypeStruct %5 %6 +%8 = OpTypeImage %4 2D 0 0 0 1 Unknown +%9 = OpTypeSampler +%11 = OpTypePointer UniformConstant %8 +%10 = OpVariable %11 UniformConstant +%13 = OpTypePointer UniformConstant %9 +%12 = OpVariable %13 UniformConstant +%16 = OpTypePointer Input %5 +%15 = OpVariable %16 Input +%18 = OpVariable %16 Input +%21 = OpTypePointer Output %5 +%20 = OpVariable %21 Output +%23 = OpTypePointer Output %6 +%22 = OpVariable %23 Output +%25 = OpTypeFunction %2 +%26 = OpConstant %4 0.0 +%27 = OpConstant %4 1.0 +%34 = OpTypePointer Output %4 +%36 = OpTypeInt 32 0 +%35 = OpConstant %36 1 +%41 = OpVariable %16 Input +%43 = OpVariable %23 Output +%48 = OpTypeSampledImage %8 +%52 = OpTypeBool +%59 = OpVariable %23 Output +%61 = OpConstant %4 0.5 +%24 = OpFunction %2 None %25 +%14 = OpLabel +%17 = OpLoad %5 %15 +%19 = OpLoad %5 %18 +OpBranch %28 +%28 = OpLabel +%29 = OpVectorTimesScalar %5 %17 %3 +%30 = OpCompositeConstruct %6 %29 %26 %27 +%31 = OpCompositeConstruct %7 %19 %30 +%32 = OpCompositeExtract %5 %31 0 +OpStore %20 %32 +%33 = OpCompositeExtract %6 %31 1 +OpStore %22 %33 +%37 = OpAccessChain %34 %22 %35 +%38 = OpLoad %4 %37 +%39 = OpFNegate %4 %38 +OpStore %37 %39 OpReturn OpFunctionEnd -%45 = OpFunction %2 None %28 -%41 = OpLabel -%43 = OpLoad %8 %42 -%46 = OpLoad %11 %13 -%47 = OpLoad %12 %15 -OpBranch %48 -%48 = OpLabel -%50 = OpSampledImage %49 %46 %47 -%51 = OpImageSampleImplicitLod %9 %50 %43 -%52 = OpCompositeExtract %4 %51 3 -%54 = OpFOrdEqual %53 %52 %5 -OpSelectionMerge %55 None -OpBranchConditional %54 %56 %55 -%56 = OpLabel -OpKill +%44 = OpFunction %2 None %25 +%40 = OpLabel +%42 = OpLoad %5 %41 +%45 = OpLoad %8 %10 +%46 = OpLoad %9 %12 +OpBranch %47 +%47 = OpLabel +%49 = OpSampledImage %48 %45 %46 +%50 = OpImageSampleImplicitLod %6 %49 %42 +%51 = OpCompositeExtract %4 %50 3 +%53 = OpFOrdEqual %52 %51 %26 +OpSelectionMerge %54 None +OpBranchConditional %53 %55 %54 %55 = OpLabel -%57 = OpCompositeExtract %4 %51 3 -%58 = OpVectorTimesScalar %9 %51 %57 -OpStore %44 %58 +OpKill +%54 = OpLabel +%56 = OpCompositeExtract %4 %50 3 +%57 = OpVectorTimesScalar %6 %50 %56 +OpStore %43 %57 OpReturn OpFunctionEnd -%61 = OpFunction %2 None %28 -%59 = OpLabel +%60 = OpFunction %2 None %25 +%58 = OpLabel OpBranch %62 %62 = OpLabel -%63 = OpCompositeConstruct %9 %5 %7 %5 %7 -OpStore %60 %63 +%63 = OpCompositeConstruct %6 %26 %61 %26 %61 +OpStore %59 %63 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/ray-query.spvasm b/tests/out/spv/ray-query.spvasm index 31dc7d75e..03a43966e 100644 --- a/tests/out/spv/ray-query.spvasm +++ b/tests/out/spv/ray-query.spvasm @@ -7,112 +7,112 @@ OpCapability Shader OpExtension "SPV_KHR_ray_query" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %48 "main" %23 %25 -OpExecutionMode %48 LocalSize 1 1 1 -OpMemberDecorate %15 0 Offset 0 -OpMemberDecorate %15 1 Offset 16 -OpMemberDecorate %19 0 Offset 0 -OpMemberDecorate %19 1 Offset 4 -OpMemberDecorate %19 2 Offset 8 -OpMemberDecorate %19 3 Offset 12 -OpMemberDecorate %19 4 Offset 16 -OpMemberDecorate %19 5 Offset 20 -OpMemberDecorate %19 6 Offset 24 -OpMemberDecorate %19 7 Offset 28 -OpMemberDecorate %19 8 Offset 36 -OpMemberDecorate %19 9 Offset 48 -OpMemberDecorate %19 9 ColMajor -OpMemberDecorate %19 9 MatrixStride 16 -OpMemberDecorate %19 10 Offset 112 -OpMemberDecorate %19 10 ColMajor -OpMemberDecorate %19 10 MatrixStride 16 -OpMemberDecorate %22 0 Offset 0 -OpMemberDecorate %22 1 Offset 4 -OpMemberDecorate %22 2 Offset 8 -OpMemberDecorate %22 3 Offset 12 -OpMemberDecorate %22 4 Offset 16 -OpMemberDecorate %22 5 Offset 32 -OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 0 -OpDecorate %25 DescriptorSet 0 -OpDecorate %25 Binding 1 -OpDecorate %26 Block -OpMemberDecorate %26 0 Offset 0 +OpEntryPoint GLCompute %43 "main" %15 %17 +OpExecutionMode %43 LocalSize 1 1 1 +OpMemberDecorate %7 0 Offset 0 +OpMemberDecorate %7 1 Offset 16 +OpMemberDecorate %11 0 Offset 0 +OpMemberDecorate %11 1 Offset 4 +OpMemberDecorate %11 2 Offset 8 +OpMemberDecorate %11 3 Offset 12 +OpMemberDecorate %11 4 Offset 16 +OpMemberDecorate %11 5 Offset 20 +OpMemberDecorate %11 6 Offset 24 +OpMemberDecorate %11 7 Offset 28 +OpMemberDecorate %11 8 Offset 36 +OpMemberDecorate %11 9 Offset 48 +OpMemberDecorate %11 9 ColMajor +OpMemberDecorate %11 9 MatrixStride 16 +OpMemberDecorate %11 10 Offset 112 +OpMemberDecorate %11 10 ColMajor +OpMemberDecorate %11 10 MatrixStride 16 +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 1 Offset 4 +OpMemberDecorate %14 2 Offset 8 +OpMemberDecorate %14 3 Offset 12 +OpMemberDecorate %14 4 Offset 16 +OpMemberDecorate %14 5 Offset 32 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 0 +OpDecorate %17 DescriptorSet 0 +OpDecorate %17 Binding 1 +OpDecorate %18 Block +OpMemberDecorate %18 0 Offset 0 %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 1.0 -%5 = OpConstant %4 2.4 -%6 = OpConstant %4 0.0 -%8 = OpTypeInt 32 0 -%7 = OpConstant %8 4 -%9 = OpConstant %8 255 -%10 = OpConstant %4 0.1 -%11 = OpConstant %4 100.0 -%12 = OpConstant %8 0 -%13 = OpTypeAccelerationStructureNV -%14 = OpTypeVector %4 3 -%15 = OpTypeStruct %8 %14 -%16 = OpTypeVector %4 2 -%17 = OpTypeBool -%18 = OpTypeMatrix %14 4 -%19 = OpTypeStruct %8 %4 %8 %8 %8 %8 %8 %16 %17 %18 %18 -%20 = OpTypeVector %4 4 -%21 = OpTypeRayQueryKHR -%22 = OpTypeStruct %8 %8 %4 %4 %14 %14 -%24 = OpTypePointer UniformConstant %13 -%23 = OpVariable %24 UniformConstant -%26 = OpTypeStruct %15 -%27 = OpTypePointer StorageBuffer %26 -%25 = OpVariable %27 StorageBuffer -%32 = OpTypeFunction %14 %14 %19 -%46 = OpTypePointer Function %21 -%49 = OpTypeFunction %2 -%51 = OpTypePointer StorageBuffer %15 -%72 = OpConstant %8 1 -%85 = OpTypePointer StorageBuffer %8 -%90 = OpTypePointer StorageBuffer %14 -%31 = OpFunction %14 None %32 -%29 = OpFunctionParameter %14 -%30 = OpFunctionParameter %19 +%3 = OpTypeAccelerationStructureNV +%4 = OpTypeInt 32 0 +%6 = OpTypeFloat 32 +%5 = OpTypeVector %6 3 +%7 = OpTypeStruct %4 %5 +%8 = OpTypeVector %6 2 +%9 = OpTypeBool +%10 = OpTypeMatrix %5 4 +%11 = OpTypeStruct %4 %6 %4 %4 %4 %4 %4 %8 %9 %10 %10 +%12 = OpTypeVector %6 4 +%13 = OpTypeRayQueryKHR +%14 = OpTypeStruct %4 %4 %6 %6 %5 %5 +%16 = OpTypePointer UniformConstant %3 +%15 = OpVariable %16 UniformConstant +%18 = OpTypeStruct %7 +%19 = OpTypePointer StorageBuffer %18 +%17 = OpVariable %19 StorageBuffer +%24 = OpTypeFunction %5 %5 %11 +%25 = OpConstant %6 1.0 +%26 = OpConstant %6 2.4 +%27 = OpConstant %6 0.0 +%41 = OpTypePointer Function %13 +%44 = OpTypeFunction %2 +%46 = OpTypePointer StorageBuffer %7 +%47 = OpConstant %4 0 +%49 = OpConstant %4 4 +%50 = OpConstant %4 255 +%51 = OpConstant %6 0.1 +%52 = OpConstant %6 100.0 +%72 = OpConstant %4 1 +%85 = OpTypePointer StorageBuffer %4 +%90 = OpTypePointer StorageBuffer %5 +%23 = OpFunction %5 None %24 +%21 = OpFunctionParameter %5 +%22 = OpFunctionParameter %11 +%20 = OpLabel +OpBranch %28 %28 = OpLabel -OpBranch %33 -%33 = OpLabel -%34 = OpCompositeExtract %18 %30 10 -%35 = OpCompositeConstruct %20 %29 %3 -%36 = OpMatrixTimesVector %14 %34 %35 -%37 = OpVectorShuffle %16 %36 %36 0 1 -%38 = OpExtInst %16 %1 Normalize %37 -%39 = OpVectorTimesScalar %16 %38 %5 -%40 = OpCompositeExtract %18 %30 9 -%41 = OpCompositeConstruct %20 %39 %6 %3 -%42 = OpMatrixTimesVector %14 %40 %41 -%43 = OpFSub %14 %29 %42 -%44 = OpExtInst %14 %1 Normalize %43 -OpReturnValue %44 +%29 = OpCompositeExtract %10 %22 10 +%30 = OpCompositeConstruct %12 %21 %25 +%31 = OpMatrixTimesVector %5 %29 %30 +%32 = OpVectorShuffle %8 %31 %31 0 1 +%33 = OpExtInst %8 %1 Normalize %32 +%34 = OpVectorTimesScalar %8 %33 %26 +%35 = OpCompositeExtract %10 %22 9 +%36 = OpCompositeConstruct %12 %34 %27 %25 +%37 = OpMatrixTimesVector %5 %35 %36 +%38 = OpFSub %5 %21 %37 +%39 = OpExtInst %5 %1 Normalize %38 +OpReturnValue %39 OpFunctionEnd -%48 = OpFunction %2 None %49 -%47 = OpLabel -%45 = OpVariable %46 Function -%50 = OpLoad %13 %23 -%52 = OpAccessChain %51 %25 %12 +%43 = OpFunction %2 None %44 +%42 = OpLabel +%40 = OpVariable %41 Function +%45 = OpLoad %3 %15 +%48 = OpAccessChain %46 %17 %47 OpBranch %53 %53 = OpLabel -%54 = OpCompositeConstruct %14 %6 %3 %6 -%55 = OpCompositeConstruct %14 %6 %6 %6 -%56 = OpCompositeConstruct %22 %7 %9 %10 %11 %55 %54 -%57 = OpCompositeExtract %8 %56 0 -%58 = OpCompositeExtract %8 %56 1 -%59 = OpCompositeExtract %4 %56 2 -%60 = OpCompositeExtract %4 %56 3 -%61 = OpCompositeExtract %14 %56 4 -%62 = OpCompositeExtract %14 %56 5 -OpRayQueryInitializeKHR %45 %50 %57 %58 %61 %59 %62 %60 +%54 = OpCompositeConstruct %5 %27 %25 %27 +%55 = OpCompositeConstruct %5 %27 %27 %27 +%56 = OpCompositeConstruct %14 %49 %50 %51 %52 %55 %54 +%57 = OpCompositeExtract %4 %56 0 +%58 = OpCompositeExtract %4 %56 1 +%59 = OpCompositeExtract %6 %56 2 +%60 = OpCompositeExtract %6 %56 3 +%61 = OpCompositeExtract %5 %56 4 +%62 = OpCompositeExtract %5 %56 5 +OpRayQueryInitializeKHR %40 %45 %57 %58 %61 %59 %62 %60 OpBranch %63 %63 = OpLabel OpLoopMerge %64 %66 None OpBranch %65 %65 = OpLabel -%67 = OpRayQueryProceedKHR %17 %45 +%67 = OpRayQueryProceedKHR %9 %40 OpSelectionMerge %68 None OpBranchConditional %67 %68 %69 %69 = OpLabel @@ -126,27 +126,27 @@ OpBranch %66 %66 = OpLabel OpBranch %63 %64 = OpLabel -%73 = OpRayQueryGetIntersectionTypeKHR %8 %45 %72 -%74 = OpRayQueryGetIntersectionInstanceCustomIndexKHR %8 %45 %72 -%75 = OpRayQueryGetIntersectionInstanceIdKHR %8 %45 %72 -%76 = OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR %8 %45 %72 -%77 = OpRayQueryGetIntersectionGeometryIndexKHR %8 %45 %72 -%78 = OpRayQueryGetIntersectionPrimitiveIndexKHR %8 %45 %72 -%79 = OpRayQueryGetIntersectionTKHR %4 %45 %72 -%80 = OpRayQueryGetIntersectionBarycentricsKHR %16 %45 %72 -%81 = OpRayQueryGetIntersectionFrontFaceKHR %17 %45 %72 -%82 = OpRayQueryGetIntersectionObjectToWorldKHR %18 %45 %72 -%83 = OpRayQueryGetIntersectionWorldToObjectKHR %18 %45 %72 -%84 = OpCompositeConstruct %19 %73 %79 %74 %75 %76 %77 %78 %80 %81 %82 %83 -%86 = OpCompositeExtract %8 %84 0 -%87 = OpIEqual %17 %86 %12 -%88 = OpSelect %8 %87 %72 %12 -%89 = OpAccessChain %85 %52 %12 +%73 = OpRayQueryGetIntersectionTypeKHR %4 %40 %72 +%74 = OpRayQueryGetIntersectionInstanceCustomIndexKHR %4 %40 %72 +%75 = OpRayQueryGetIntersectionInstanceIdKHR %4 %40 %72 +%76 = OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR %4 %40 %72 +%77 = OpRayQueryGetIntersectionGeometryIndexKHR %4 %40 %72 +%78 = OpRayQueryGetIntersectionPrimitiveIndexKHR %4 %40 %72 +%79 = OpRayQueryGetIntersectionTKHR %6 %40 %72 +%80 = OpRayQueryGetIntersectionBarycentricsKHR %8 %40 %72 +%81 = OpRayQueryGetIntersectionFrontFaceKHR %9 %40 %72 +%82 = OpRayQueryGetIntersectionObjectToWorldKHR %10 %40 %72 +%83 = OpRayQueryGetIntersectionWorldToObjectKHR %10 %40 %72 +%84 = OpCompositeConstruct %11 %73 %79 %74 %75 %76 %77 %78 %80 %81 %82 %83 +%86 = OpCompositeExtract %4 %84 0 +%87 = OpIEqual %9 %86 %47 +%88 = OpSelect %4 %87 %72 %47 +%89 = OpAccessChain %85 %48 %47 OpStore %89 %88 -%91 = OpCompositeExtract %4 %84 1 -%92 = OpVectorTimesScalar %14 %54 %91 -%93 = OpFunctionCall %14 %31 %92 %84 -%94 = OpAccessChain %90 %52 %72 +%91 = OpCompositeExtract %6 %84 1 +%92 = OpVectorTimesScalar %5 %54 %91 +%93 = OpFunctionCall %5 %23 %92 %84 +%94 = OpAccessChain %90 %48 %72 OpStore %94 %93 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index 15cbf4b91..a1705891c 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -6,44 +6,44 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %90 "vs_main" %80 %83 %85 %87 %89 +OpEntryPoint Vertex %89 "vs_main" %79 %82 %84 %86 %88 OpEntryPoint Fragment %148 "fs_main" %139 %142 %145 %147 OpEntryPoint Fragment %217 "fs_main_without_storage" %210 %212 %214 %216 OpExecutionMode %148 OriginUpperLeft OpExecutionMode %217 OriginUpperLeft OpSource GLSL 450 -OpName %11 "c_max_lights" -OpMemberName %18 0 "view_proj" -OpMemberName %18 1 "num_lights" -OpName %18 "Globals" -OpMemberName %19 0 "world" -OpMemberName %19 1 "color" -OpName %19 "Entity" -OpMemberName %21 0 "proj_position" -OpMemberName %21 1 "world_normal" -OpMemberName %21 2 "world_position" -OpName %21 "VertexOutput" -OpMemberName %24 0 "proj" -OpMemberName %24 1 "pos" -OpMemberName %24 2 "color" -OpName %24 "Light" -OpName %30 "c_ambient" -OpName %31 "u_globals" -OpName %34 "u_entity" -OpName %37 "s_lights" -OpName %40 "u_lights" -OpName %43 "t_shadow" -OpName %45 "sampler_shadow" -OpName %48 "light_id" -OpName %49 "homogeneous_coords" -OpName %50 "fetch_shadow" -OpName %76 "out" -OpName %80 "position" -OpName %83 "normal" -OpName %85 "proj_position" -OpName %87 "world_normal" -OpName %89 "world_position" -OpName %90 "vs_main" +OpName %7 "c_max_lights" +OpMemberName %13 0 "view_proj" +OpMemberName %13 1 "num_lights" +OpName %13 "Globals" +OpMemberName %14 0 "world" +OpMemberName %14 1 "color" +OpName %14 "Entity" +OpMemberName %16 0 "proj_position" +OpMemberName %16 1 "world_normal" +OpMemberName %16 2 "world_position" +OpName %16 "VertexOutput" +OpMemberName %19 0 "proj" +OpMemberName %19 1 "pos" +OpMemberName %19 2 "color" +OpName %19 "Light" +OpName %25 "c_ambient" +OpName %26 "u_globals" +OpName %29 "u_entity" +OpName %32 "s_lights" +OpName %35 "u_lights" +OpName %38 "t_shadow" +OpName %40 "sampler_shadow" +OpName %43 "light_id" +OpName %44 "homogeneous_coords" +OpName %45 "fetch_shadow" +OpName %75 "out" +OpName %79 "position" +OpName %82 "normal" +OpName %84 "proj_position" +OpName %86 "world_normal" +OpName %88 "world_position" +OpName %89 "vs_main" OpName %132 "color" OpName %134 "i" OpName %139 "proj_position" @@ -56,50 +56,50 @@ OpName %210 "proj_position" OpName %212 "world_normal" OpName %214 "world_position" OpName %217 "fs_main_without_storage" -OpMemberDecorate %18 0 Offset 0 -OpMemberDecorate %18 0 ColMajor -OpMemberDecorate %18 0 MatrixStride 16 -OpMemberDecorate %18 1 Offset 64 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 0 ColMajor +OpMemberDecorate %13 0 MatrixStride 16 +OpMemberDecorate %13 1 Offset 64 +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 0 ColMajor +OpMemberDecorate %14 0 MatrixStride 16 +OpMemberDecorate %14 1 Offset 64 +OpMemberDecorate %16 0 Offset 0 +OpMemberDecorate %16 1 Offset 16 +OpMemberDecorate %16 2 Offset 32 OpMemberDecorate %19 0 Offset 0 OpMemberDecorate %19 0 ColMajor OpMemberDecorate %19 0 MatrixStride 16 OpMemberDecorate %19 1 Offset 64 -OpMemberDecorate %21 0 Offset 0 -OpMemberDecorate %21 1 Offset 16 -OpMemberDecorate %21 2 Offset 32 -OpMemberDecorate %24 0 Offset 0 -OpMemberDecorate %24 0 ColMajor -OpMemberDecorate %24 0 MatrixStride 16 -OpMemberDecorate %24 1 Offset 64 -OpMemberDecorate %24 2 Offset 80 -OpDecorate %25 ArrayStride 96 -OpDecorate %26 ArrayStride 96 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 0 -OpDecorate %32 Block -OpMemberDecorate %32 0 Offset 0 -OpDecorate %34 DescriptorSet 1 -OpDecorate %34 Binding 0 -OpDecorate %35 Block -OpMemberDecorate %35 0 Offset 0 -OpDecorate %37 NonWritable -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 1 -OpDecorate %38 Block -OpMemberDecorate %38 0 Offset 0 +OpMemberDecorate %19 2 Offset 80 +OpDecorate %20 ArrayStride 96 +OpDecorate %21 ArrayStride 96 +OpDecorate %26 DescriptorSet 0 +OpDecorate %26 Binding 0 +OpDecorate %27 Block +OpMemberDecorate %27 0 Offset 0 +OpDecorate %29 DescriptorSet 1 +OpDecorate %29 Binding 0 +OpDecorate %30 Block +OpMemberDecorate %30 0 Offset 0 +OpDecorate %32 NonWritable +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 1 +OpDecorate %33 Block +OpMemberDecorate %33 0 Offset 0 +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 1 +OpDecorate %36 Block +OpMemberDecorate %36 0 Offset 0 +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 2 OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 1 -OpDecorate %41 Block -OpMemberDecorate %41 0 Offset 0 -OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 2 -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 3 -OpDecorate %80 Location 0 -OpDecorate %83 Location 1 -OpDecorate %85 BuiltIn Position -OpDecorate %87 Location 0 -OpDecorate %89 Location 1 +OpDecorate %40 Binding 3 +OpDecorate %79 Location 0 +OpDecorate %82 Location 1 +OpDecorate %84 BuiltIn Position +OpDecorate %86 Location 0 +OpDecorate %88 Location 1 OpDecorate %139 BuiltIn FragCoord OpDecorate %142 Location 0 OpDecorate %145 Location 1 @@ -112,199 +112,199 @@ OpDecorate %216 Location 0 %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 %6 = OpTypeFloat 32 -%5 = OpConstant %6 0.0 -%7 = OpConstant %6 1.0 -%8 = OpConstant %6 0.5 -%9 = OpConstant %6 -0.5 -%10 = OpConstant %6 0.05 -%12 = OpTypeInt 32 0 -%11 = OpConstant %12 10 -%13 = OpConstant %12 0 -%14 = OpConstant %12 1 -%16 = OpTypeVector %6 4 -%15 = OpTypeMatrix %16 4 -%17 = OpTypeVector %12 4 -%18 = OpTypeStruct %15 %17 -%19 = OpTypeStruct %15 %16 -%20 = OpTypeVector %6 3 -%21 = OpTypeStruct %16 %20 %16 -%22 = OpTypeVector %4 4 -%23 = OpTypeMatrix %20 3 -%24 = OpTypeStruct %15 %16 %16 -%25 = OpTypeRuntimeArray %24 -%26 = OpTypeArray %24 %3 -%27 = OpTypeImage %6 2D 1 1 0 1 Unknown -%28 = OpTypeSampler -%29 = OpTypeVector %6 2 -%30 = OpConstantComposite %20 %10 %10 %10 -%32 = OpTypeStruct %18 -%33 = OpTypePointer Uniform %32 -%31 = OpVariable %33 Uniform -%35 = OpTypeStruct %19 -%36 = OpTypePointer Uniform %35 -%34 = OpVariable %36 Uniform -%38 = OpTypeStruct %25 -%39 = OpTypePointer StorageBuffer %38 -%37 = OpVariable %39 StorageBuffer -%41 = OpTypeStruct %26 -%42 = OpTypePointer Uniform %41 -%40 = OpVariable %42 Uniform -%44 = OpTypePointer UniformConstant %27 -%43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %28 -%45 = OpVariable %46 UniformConstant -%51 = OpTypeFunction %6 %12 %16 -%56 = OpTypeBool -%71 = OpTypeSampledImage %27 -%77 = OpTypePointer Function %21 -%78 = OpConstantNull %21 -%81 = OpTypePointer Input %22 -%80 = OpVariable %81 Input -%83 = OpVariable %81 Input -%86 = OpTypePointer Output %16 -%85 = OpVariable %86 Output -%88 = OpTypePointer Output %20 -%87 = OpVariable %88 Output -%89 = OpVariable %86 Output -%91 = OpTypeFunction %2 -%92 = OpTypePointer Uniform %18 -%94 = OpTypePointer Uniform %19 -%97 = OpTypePointer Uniform %15 -%104 = OpTypePointer Function %20 +%5 = OpConstant %6 0.05 +%8 = OpTypeInt 32 0 +%7 = OpConstant %8 10 +%9 = OpConstant %8 1 +%11 = OpTypeVector %6 4 +%10 = OpTypeMatrix %11 4 +%12 = OpTypeVector %8 4 +%13 = OpTypeStruct %10 %12 +%14 = OpTypeStruct %10 %11 +%15 = OpTypeVector %6 3 +%16 = OpTypeStruct %11 %15 %11 +%17 = OpTypeVector %4 4 +%18 = OpTypeMatrix %15 3 +%19 = OpTypeStruct %10 %11 %11 +%20 = OpTypeRuntimeArray %19 +%21 = OpTypeArray %19 %3 +%22 = OpTypeImage %6 2D 1 1 0 1 Unknown +%23 = OpTypeSampler +%24 = OpTypeVector %6 2 +%25 = OpConstantComposite %15 %5 %5 %5 +%27 = OpTypeStruct %13 +%28 = OpTypePointer Uniform %27 +%26 = OpVariable %28 Uniform +%30 = OpTypeStruct %14 +%31 = OpTypePointer Uniform %30 +%29 = OpVariable %31 Uniform +%33 = OpTypeStruct %20 +%34 = OpTypePointer StorageBuffer %33 +%32 = OpVariable %34 StorageBuffer +%36 = OpTypeStruct %21 +%37 = OpTypePointer Uniform %36 +%35 = OpVariable %37 Uniform +%39 = OpTypePointer UniformConstant %22 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %23 +%40 = OpVariable %41 UniformConstant +%46 = OpTypeFunction %6 %8 %11 +%49 = OpConstant %6 0.0 +%50 = OpConstant %6 1.0 +%51 = OpConstant %6 0.5 +%52 = OpConstant %6 -0.5 +%55 = OpTypeBool +%70 = OpTypeSampledImage %22 +%76 = OpTypePointer Function %16 +%77 = OpConstantNull %16 +%80 = OpTypePointer Input %17 +%79 = OpVariable %80 Input +%82 = OpVariable %80 Input +%85 = OpTypePointer Output %11 +%84 = OpVariable %85 Output +%87 = OpTypePointer Output %15 +%86 = OpVariable %87 Output +%88 = OpVariable %85 Output +%90 = OpTypeFunction %2 +%91 = OpTypePointer Uniform %13 +%92 = OpConstant %8 0 +%94 = OpTypePointer Uniform %14 +%97 = OpTypePointer Uniform %10 +%104 = OpTypePointer Function %15 %112 = OpTypeVector %4 3 -%117 = OpTypePointer Function %16 -%118 = OpConstant %12 2 +%117 = OpTypePointer Function %11 +%118 = OpConstant %8 2 %126 = OpTypePointer Output %6 -%133 = OpConstantNull %20 -%135 = OpTypePointer Function %12 -%136 = OpConstantNull %12 -%140 = OpTypePointer Input %16 +%133 = OpConstantNull %15 +%135 = OpTypePointer Function %8 +%136 = OpConstantNull %8 +%140 = OpTypePointer Input %11 %139 = OpVariable %140 Input -%143 = OpTypePointer Input %20 +%143 = OpTypePointer Input %15 %142 = OpVariable %143 Input %145 = OpVariable %140 Input -%147 = OpVariable %86 Output -%151 = OpTypePointer StorageBuffer %25 -%163 = OpTypePointer Uniform %17 -%164 = OpTypePointer Uniform %12 -%174 = OpTypePointer StorageBuffer %24 -%200 = OpTypePointer Uniform %16 -%205 = OpConstantNull %20 -%207 = OpConstantNull %12 +%147 = OpVariable %85 Output +%151 = OpTypePointer StorageBuffer %20 +%163 = OpTypePointer Uniform %12 +%164 = OpTypePointer Uniform %8 +%174 = OpTypePointer StorageBuffer %19 +%200 = OpTypePointer Uniform %11 +%205 = OpConstantNull %15 +%207 = OpConstantNull %8 %210 = OpVariable %140 Input %212 = OpVariable %143 Input %214 = OpVariable %140 Input -%216 = OpVariable %86 Output -%220 = OpTypePointer Uniform %26 -%241 = OpTypePointer Uniform %24 -%50 = OpFunction %6 None %51 -%48 = OpFunctionParameter %12 -%49 = OpFunctionParameter %16 -%47 = OpLabel -%52 = OpLoad %27 %43 -%53 = OpLoad %28 %45 -OpBranch %54 -%54 = OpLabel -%55 = OpCompositeExtract %6 %49 3 -%57 = OpFOrdLessThanEqual %56 %55 %5 -OpSelectionMerge %58 None -OpBranchConditional %57 %59 %58 -%59 = OpLabel -OpReturnValue %7 +%216 = OpVariable %85 Output +%220 = OpTypePointer Uniform %21 +%241 = OpTypePointer Uniform %19 +%45 = OpFunction %6 None %46 +%43 = OpFunctionParameter %8 +%44 = OpFunctionParameter %11 +%42 = OpLabel +%47 = OpLoad %22 %38 +%48 = OpLoad %23 %40 +OpBranch %53 +%53 = OpLabel +%54 = OpCompositeExtract %6 %44 3 +%56 = OpFOrdLessThanEqual %55 %54 %49 +OpSelectionMerge %57 None +OpBranchConditional %56 %58 %57 %58 = OpLabel -%60 = OpCompositeConstruct %29 %8 %9 -%61 = OpCompositeExtract %6 %49 3 -%62 = OpFDiv %6 %7 %61 -%63 = OpVectorShuffle %29 %49 %49 0 1 -%64 = OpFMul %29 %63 %60 -%65 = OpVectorTimesScalar %29 %64 %62 -%66 = OpCompositeConstruct %29 %8 %8 -%67 = OpFAdd %29 %65 %66 -%68 = OpBitcast %4 %48 -%69 = OpCompositeExtract %6 %49 2 -%70 = OpFMul %6 %69 %62 -%72 = OpConvertSToF %6 %68 -%73 = OpCompositeConstruct %20 %67 %72 -%74 = OpSampledImage %71 %52 %53 -%75 = OpImageSampleDrefExplicitLod %6 %74 %73 %70 Lod %5 -OpReturnValue %75 +OpReturnValue %50 +%57 = OpLabel +%59 = OpCompositeConstruct %24 %51 %52 +%60 = OpCompositeExtract %6 %44 3 +%61 = OpFDiv %6 %50 %60 +%62 = OpVectorShuffle %24 %44 %44 0 1 +%63 = OpFMul %24 %62 %59 +%64 = OpVectorTimesScalar %24 %63 %61 +%65 = OpCompositeConstruct %24 %51 %51 +%66 = OpFAdd %24 %64 %65 +%67 = OpBitcast %4 %43 +%68 = OpCompositeExtract %6 %44 2 +%69 = OpFMul %6 %68 %61 +%71 = OpConvertSToF %6 %67 +%72 = OpCompositeConstruct %15 %66 %71 +%73 = OpSampledImage %70 %47 %48 +%74 = OpImageSampleDrefExplicitLod %6 %73 %72 %69 Lod %49 +OpReturnValue %74 OpFunctionEnd -%90 = OpFunction %2 None %91 -%79 = OpLabel -%76 = OpVariable %77 Function %78 -%82 = OpLoad %22 %80 -%84 = OpLoad %22 %83 -%93 = OpAccessChain %92 %31 %13 -%95 = OpAccessChain %94 %34 %13 +%89 = OpFunction %2 None %90 +%78 = OpLabel +%75 = OpVariable %76 Function %77 +%81 = OpLoad %17 %79 +%83 = OpLoad %17 %82 +%93 = OpAccessChain %91 %26 %92 +%95 = OpAccessChain %94 %29 %92 OpBranch %96 %96 = OpLabel -%98 = OpAccessChain %97 %95 %13 -%99 = OpLoad %15 %98 -%100 = OpAccessChain %97 %95 %13 -%101 = OpLoad %15 %100 -%102 = OpConvertSToF %16 %82 -%103 = OpMatrixTimesVector %16 %101 %102 -%105 = OpCompositeExtract %16 %99 0 -%106 = OpVectorShuffle %20 %105 %105 0 1 2 -%107 = OpCompositeExtract %16 %99 1 -%108 = OpVectorShuffle %20 %107 %107 0 1 2 -%109 = OpCompositeExtract %16 %99 2 -%110 = OpVectorShuffle %20 %109 %109 0 1 2 -%111 = OpCompositeConstruct %23 %106 %108 %110 -%113 = OpVectorShuffle %112 %84 %84 0 1 2 -%114 = OpConvertSToF %20 %113 -%115 = OpMatrixTimesVector %20 %111 %114 -%116 = OpAccessChain %104 %76 %14 +%98 = OpAccessChain %97 %95 %92 +%99 = OpLoad %10 %98 +%100 = OpAccessChain %97 %95 %92 +%101 = OpLoad %10 %100 +%102 = OpConvertSToF %11 %81 +%103 = OpMatrixTimesVector %11 %101 %102 +%105 = OpCompositeExtract %11 %99 0 +%106 = OpVectorShuffle %15 %105 %105 0 1 2 +%107 = OpCompositeExtract %11 %99 1 +%108 = OpVectorShuffle %15 %107 %107 0 1 2 +%109 = OpCompositeExtract %11 %99 2 +%110 = OpVectorShuffle %15 %109 %109 0 1 2 +%111 = OpCompositeConstruct %18 %106 %108 %110 +%113 = OpVectorShuffle %112 %83 %83 0 1 2 +%114 = OpConvertSToF %15 %113 +%115 = OpMatrixTimesVector %15 %111 %114 +%116 = OpAccessChain %104 %75 %9 OpStore %116 %115 -%119 = OpAccessChain %117 %76 %118 +%119 = OpAccessChain %117 %75 %118 OpStore %119 %103 -%120 = OpAccessChain %97 %93 %13 -%121 = OpLoad %15 %120 -%122 = OpMatrixTimesVector %16 %121 %103 -%123 = OpAccessChain %117 %76 %13 +%120 = OpAccessChain %97 %93 %92 +%121 = OpLoad %10 %120 +%122 = OpMatrixTimesVector %11 %121 %103 +%123 = OpAccessChain %117 %75 %92 OpStore %123 %122 -%124 = OpLoad %21 %76 -%125 = OpCompositeExtract %16 %124 0 -OpStore %85 %125 -%127 = OpAccessChain %126 %85 %14 +%124 = OpLoad %16 %75 +%125 = OpCompositeExtract %11 %124 0 +OpStore %84 %125 +%127 = OpAccessChain %126 %84 %9 %128 = OpLoad %6 %127 %129 = OpFNegate %6 %128 OpStore %127 %129 -%130 = OpCompositeExtract %20 %124 1 -OpStore %87 %130 -%131 = OpCompositeExtract %16 %124 2 -OpStore %89 %131 +%130 = OpCompositeExtract %15 %124 1 +OpStore %86 %130 +%131 = OpCompositeExtract %11 %124 2 +OpStore %88 %131 OpReturn OpFunctionEnd -%148 = OpFunction %2 None %91 +%148 = OpFunction %2 None %90 %137 = OpLabel %132 = OpVariable %104 Function %133 %134 = OpVariable %135 Function %136 -%141 = OpLoad %16 %139 -%144 = OpLoad %20 %142 -%146 = OpLoad %16 %145 -%138 = OpCompositeConstruct %21 %141 %144 %146 -%149 = OpAccessChain %92 %31 %13 -%150 = OpAccessChain %94 %34 %13 -%152 = OpAccessChain %151 %37 %13 -%153 = OpLoad %27 %43 -%154 = OpLoad %28 %45 +%141 = OpLoad %11 %139 +%144 = OpLoad %15 %142 +%146 = OpLoad %11 %145 +%138 = OpCompositeConstruct %16 %141 %144 %146 +%149 = OpAccessChain %91 %26 %92 +%150 = OpAccessChain %94 %29 %92 +%152 = OpAccessChain %151 %32 %92 +%153 = OpLoad %22 %38 +%154 = OpLoad %23 %40 OpBranch %155 %155 = OpLabel -%156 = OpCompositeExtract %20 %138 1 -%157 = OpExtInst %20 %1 Normalize %156 -OpStore %132 %30 -OpStore %134 %13 +%156 = OpCompositeExtract %15 %138 1 +%157 = OpExtInst %15 %1 Normalize %156 +OpStore %132 %25 +OpStore %134 %92 OpBranch %158 %158 = OpLabel OpLoopMerge %159 %161 None OpBranch %160 %160 = OpLabel -%162 = OpLoad %12 %134 -%165 = OpAccessChain %164 %149 %14 %13 -%166 = OpLoad %12 %165 -%167 = OpExtInst %12 %1 UMin %166 %11 -%168 = OpULessThan %56 %162 %167 +%162 = OpLoad %8 %134 +%165 = OpAccessChain %164 %149 %9 %92 +%166 = OpLoad %8 %165 +%167 = OpExtInst %8 %1 UMin %166 %7 +%168 = OpULessThan %55 %162 %167 OpSelectionMerge %169 None OpBranchConditional %168 %169 %170 %170 = OpLabel @@ -312,75 +312,75 @@ OpBranch %159 %169 = OpLabel OpBranch %171 %171 = OpLabel -%173 = OpLoad %12 %134 +%173 = OpLoad %8 %134 %175 = OpAccessChain %174 %152 %173 -%176 = OpLoad %24 %175 -%177 = OpLoad %12 %134 -%178 = OpCompositeExtract %15 %176 0 -%179 = OpCompositeExtract %16 %138 2 -%180 = OpMatrixTimesVector %16 %178 %179 -%181 = OpFunctionCall %6 %50 %177 %180 -%182 = OpCompositeExtract %16 %176 1 -%183 = OpVectorShuffle %20 %182 %182 0 1 2 -%184 = OpCompositeExtract %16 %138 2 -%185 = OpVectorShuffle %20 %184 %184 0 1 2 -%186 = OpFSub %20 %183 %185 -%187 = OpExtInst %20 %1 Normalize %186 +%176 = OpLoad %19 %175 +%177 = OpLoad %8 %134 +%178 = OpCompositeExtract %10 %176 0 +%179 = OpCompositeExtract %11 %138 2 +%180 = OpMatrixTimesVector %11 %178 %179 +%181 = OpFunctionCall %6 %45 %177 %180 +%182 = OpCompositeExtract %11 %176 1 +%183 = OpVectorShuffle %15 %182 %182 0 1 2 +%184 = OpCompositeExtract %11 %138 2 +%185 = OpVectorShuffle %15 %184 %184 0 1 2 +%186 = OpFSub %15 %183 %185 +%187 = OpExtInst %15 %1 Normalize %186 %188 = OpDot %6 %157 %187 -%189 = OpExtInst %6 %1 FMax %5 %188 +%189 = OpExtInst %6 %1 FMax %49 %188 %190 = OpFMul %6 %181 %189 -%191 = OpCompositeExtract %16 %176 2 -%192 = OpVectorShuffle %20 %191 %191 0 1 2 -%193 = OpVectorTimesScalar %20 %192 %190 -%194 = OpLoad %20 %132 -%195 = OpFAdd %20 %194 %193 +%191 = OpCompositeExtract %11 %176 2 +%192 = OpVectorShuffle %15 %191 %191 0 1 2 +%193 = OpVectorTimesScalar %15 %192 %190 +%194 = OpLoad %15 %132 +%195 = OpFAdd %15 %194 %193 OpStore %132 %195 OpBranch %172 %172 = OpLabel OpBranch %161 %161 = OpLabel -%196 = OpLoad %12 %134 -%197 = OpIAdd %12 %196 %14 +%196 = OpLoad %8 %134 +%197 = OpIAdd %8 %196 %9 OpStore %134 %197 OpBranch %158 %159 = OpLabel -%198 = OpLoad %20 %132 -%199 = OpCompositeConstruct %16 %198 %7 -%201 = OpAccessChain %200 %150 %14 -%202 = OpLoad %16 %201 -%203 = OpFMul %16 %199 %202 +%198 = OpLoad %15 %132 +%199 = OpCompositeConstruct %11 %198 %50 +%201 = OpAccessChain %200 %150 %9 +%202 = OpLoad %11 %201 +%203 = OpFMul %11 %199 %202 OpStore %147 %203 OpReturn OpFunctionEnd -%217 = OpFunction %2 None %91 +%217 = OpFunction %2 None %90 %208 = OpLabel %204 = OpVariable %104 Function %205 %206 = OpVariable %135 Function %207 -%211 = OpLoad %16 %210 -%213 = OpLoad %20 %212 -%215 = OpLoad %16 %214 -%209 = OpCompositeConstruct %21 %211 %213 %215 -%218 = OpAccessChain %92 %31 %13 -%219 = OpAccessChain %94 %34 %13 -%221 = OpAccessChain %220 %40 %13 -%222 = OpLoad %27 %43 -%223 = OpLoad %28 %45 +%211 = OpLoad %11 %210 +%213 = OpLoad %15 %212 +%215 = OpLoad %11 %214 +%209 = OpCompositeConstruct %16 %211 %213 %215 +%218 = OpAccessChain %91 %26 %92 +%219 = OpAccessChain %94 %29 %92 +%221 = OpAccessChain %220 %35 %92 +%222 = OpLoad %22 %38 +%223 = OpLoad %23 %40 OpBranch %224 %224 = OpLabel -%225 = OpCompositeExtract %20 %209 1 -%226 = OpExtInst %20 %1 Normalize %225 -OpStore %204 %30 -OpStore %206 %13 +%225 = OpCompositeExtract %15 %209 1 +%226 = OpExtInst %15 %1 Normalize %225 +OpStore %204 %25 +OpStore %206 %92 OpBranch %227 %227 = OpLabel OpLoopMerge %228 %230 None OpBranch %229 %229 = OpLabel -%231 = OpLoad %12 %206 -%232 = OpAccessChain %164 %218 %14 %13 -%233 = OpLoad %12 %232 -%234 = OpExtInst %12 %1 UMin %233 %11 -%235 = OpULessThan %56 %231 %234 +%231 = OpLoad %8 %206 +%232 = OpAccessChain %164 %218 %9 %92 +%233 = OpLoad %8 %232 +%234 = OpExtInst %8 %1 UMin %233 %7 +%235 = OpULessThan %55 %231 %234 OpSelectionMerge %236 None OpBranchConditional %235 %236 %237 %237 = OpLabel @@ -388,43 +388,43 @@ OpBranch %228 %236 = OpLabel OpBranch %238 %238 = OpLabel -%240 = OpLoad %12 %206 +%240 = OpLoad %8 %206 %242 = OpAccessChain %241 %221 %240 -%243 = OpLoad %24 %242 -%244 = OpLoad %12 %206 -%245 = OpCompositeExtract %15 %243 0 -%246 = OpCompositeExtract %16 %209 2 -%247 = OpMatrixTimesVector %16 %245 %246 -%248 = OpFunctionCall %6 %50 %244 %247 -%249 = OpCompositeExtract %16 %243 1 -%250 = OpVectorShuffle %20 %249 %249 0 1 2 -%251 = OpCompositeExtract %16 %209 2 -%252 = OpVectorShuffle %20 %251 %251 0 1 2 -%253 = OpFSub %20 %250 %252 -%254 = OpExtInst %20 %1 Normalize %253 +%243 = OpLoad %19 %242 +%244 = OpLoad %8 %206 +%245 = OpCompositeExtract %10 %243 0 +%246 = OpCompositeExtract %11 %209 2 +%247 = OpMatrixTimesVector %11 %245 %246 +%248 = OpFunctionCall %6 %45 %244 %247 +%249 = OpCompositeExtract %11 %243 1 +%250 = OpVectorShuffle %15 %249 %249 0 1 2 +%251 = OpCompositeExtract %11 %209 2 +%252 = OpVectorShuffle %15 %251 %251 0 1 2 +%253 = OpFSub %15 %250 %252 +%254 = OpExtInst %15 %1 Normalize %253 %255 = OpDot %6 %226 %254 -%256 = OpExtInst %6 %1 FMax %5 %255 +%256 = OpExtInst %6 %1 FMax %49 %255 %257 = OpFMul %6 %248 %256 -%258 = OpCompositeExtract %16 %243 2 -%259 = OpVectorShuffle %20 %258 %258 0 1 2 -%260 = OpVectorTimesScalar %20 %259 %257 -%261 = OpLoad %20 %204 -%262 = OpFAdd %20 %261 %260 +%258 = OpCompositeExtract %11 %243 2 +%259 = OpVectorShuffle %15 %258 %258 0 1 2 +%260 = OpVectorTimesScalar %15 %259 %257 +%261 = OpLoad %15 %204 +%262 = OpFAdd %15 %261 %260 OpStore %204 %262 OpBranch %239 %239 = OpLabel OpBranch %230 %230 = OpLabel -%263 = OpLoad %12 %206 -%264 = OpIAdd %12 %263 %14 +%263 = OpLoad %8 %206 +%264 = OpIAdd %8 %263 %9 OpStore %206 %264 OpBranch %227 %228 = OpLabel -%265 = OpLoad %20 %204 -%266 = OpCompositeConstruct %16 %265 %7 -%267 = OpAccessChain %200 %219 %14 -%268 = OpLoad %16 %267 -%269 = OpFMul %16 %266 %268 +%265 = OpLoad %15 %204 +%266 = OpCompositeConstruct %11 %265 %50 +%267 = OpAccessChain %200 %219 %9 +%268 = OpLoad %11 %267 +%269 = OpFMul %11 %266 %268 OpStore %216 %269 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/skybox.spvasm b/tests/out/spv/skybox.spvasm index ca51a06dd..3c3ed8ba7 100644 --- a/tests/out/spv/skybox.spvasm +++ b/tests/out/spv/skybox.spvasm @@ -5,135 +5,135 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %39 "vs_main" %32 %35 %37 +OpEntryPoint Vertex %34 "vs_main" %27 %30 %32 OpEntryPoint Fragment %90 "fs_main" %83 %86 %89 OpExecutionMode %90 OriginUpperLeft -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 16 -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 0 ColMajor -OpMemberDecorate %14 0 MatrixStride 16 -OpMemberDecorate %14 1 Offset 64 -OpMemberDecorate %14 1 ColMajor -OpMemberDecorate %14 1 MatrixStride 16 +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %6 1 Offset 16 +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %8 0 ColMajor +OpMemberDecorate %8 0 MatrixStride 16 +OpMemberDecorate %8 1 Offset 64 +OpMemberDecorate %8 1 ColMajor +OpMemberDecorate %8 1 MatrixStride 16 +OpDecorate %14 DescriptorSet 0 +OpDecorate %14 Binding 0 +OpDecorate %15 Block +OpMemberDecorate %15 0 Offset 0 +OpDecorate %17 DescriptorSet 0 +OpDecorate %17 Binding 1 OpDecorate %19 DescriptorSet 0 -OpDecorate %19 Binding 0 -OpDecorate %20 Block -OpMemberDecorate %20 0 Offset 0 -OpDecorate %22 DescriptorSet 0 -OpDecorate %22 Binding 1 -OpDecorate %24 DescriptorSet 0 -OpDecorate %24 Binding 2 -OpDecorate %32 BuiltIn VertexIndex -OpDecorate %35 BuiltIn Position -OpDecorate %37 Location 0 +OpDecorate %19 Binding 2 +OpDecorate %27 BuiltIn VertexIndex +OpDecorate %30 BuiltIn Position +OpDecorate %32 Location 0 OpDecorate %83 BuiltIn FragCoord OpDecorate %86 Location 0 OpDecorate %89 Location 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 2 -%5 = OpConstant %4 1 -%7 = OpTypeFloat 32 -%6 = OpConstant %7 4.0 -%8 = OpConstant %7 1.0 -%9 = OpConstant %7 0.0 -%10 = OpTypeVector %7 4 -%11 = OpTypeVector %7 3 -%12 = OpTypeStruct %10 %11 -%13 = OpTypeMatrix %10 4 -%14 = OpTypeStruct %13 %13 -%15 = OpTypeInt 32 0 -%16 = OpTypeMatrix %11 3 -%17 = OpTypeImage %7 Cube 0 0 0 1 Unknown -%18 = OpTypeSampler -%20 = OpTypeStruct %14 -%21 = OpTypePointer Uniform %20 -%19 = OpVariable %21 Uniform -%23 = OpTypePointer UniformConstant %17 -%22 = OpVariable %23 UniformConstant -%25 = OpTypePointer UniformConstant %18 -%24 = OpVariable %25 UniformConstant -%27 = OpTypePointer Function %4 -%28 = OpConstantNull %4 -%30 = OpConstantNull %4 -%33 = OpTypePointer Input %15 -%32 = OpVariable %33 Input -%36 = OpTypePointer Output %10 -%35 = OpVariable %36 Output -%38 = OpTypePointer Output %11 -%37 = OpVariable %38 Output -%40 = OpTypeFunction %2 -%41 = OpTypePointer Uniform %14 -%42 = OpConstant %15 0 -%58 = OpTypePointer Uniform %13 -%59 = OpTypePointer Uniform %10 -%60 = OpConstant %15 1 -%67 = OpConstant %15 2 -%84 = OpTypePointer Input %10 +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%5 = OpTypeVector %4 3 +%6 = OpTypeStruct %3 %5 +%7 = OpTypeMatrix %3 4 +%8 = OpTypeStruct %7 %7 +%9 = OpTypeInt 32 0 +%10 = OpTypeInt 32 1 +%11 = OpTypeMatrix %5 3 +%12 = OpTypeImage %4 Cube 0 0 0 1 Unknown +%13 = OpTypeSampler +%15 = OpTypeStruct %8 +%16 = OpTypePointer Uniform %15 +%14 = OpVariable %16 Uniform +%18 = OpTypePointer UniformConstant %12 +%17 = OpVariable %18 UniformConstant +%20 = OpTypePointer UniformConstant %13 +%19 = OpVariable %20 UniformConstant +%22 = OpTypePointer Function %10 +%23 = OpConstantNull %10 +%25 = OpConstantNull %10 +%28 = OpTypePointer Input %9 +%27 = OpVariable %28 Input +%31 = OpTypePointer Output %3 +%30 = OpVariable %31 Output +%33 = OpTypePointer Output %5 +%32 = OpVariable %33 Output +%35 = OpTypeFunction %2 +%36 = OpTypePointer Uniform %8 +%37 = OpConstant %9 0 +%39 = OpConstant %10 2 +%40 = OpConstant %10 1 +%41 = OpConstant %4 4.0 +%42 = OpConstant %4 1.0 +%43 = OpConstant %4 0.0 +%58 = OpTypePointer Uniform %7 +%59 = OpTypePointer Uniform %3 +%60 = OpConstant %9 1 +%67 = OpConstant %9 2 +%84 = OpTypePointer Input %3 %83 = OpVariable %84 Input -%87 = OpTypePointer Input %11 +%87 = OpTypePointer Input %5 %86 = OpVariable %87 Input -%89 = OpVariable %36 Output -%95 = OpTypeSampledImage %17 -%39 = OpFunction %2 None %40 -%31 = OpLabel -%26 = OpVariable %27 Function %28 -%29 = OpVariable %27 Function %30 -%34 = OpLoad %15 %32 -%43 = OpAccessChain %41 %19 %42 +%89 = OpVariable %31 Output +%95 = OpTypeSampledImage %12 +%34 = OpFunction %2 None %35 +%26 = OpLabel +%21 = OpVariable %22 Function %23 +%24 = OpVariable %22 Function %25 +%29 = OpLoad %9 %27 +%38 = OpAccessChain %36 %14 %37 OpBranch %44 %44 = OpLabel -%45 = OpBitcast %4 %34 -%46 = OpSDiv %4 %45 %3 -OpStore %26 %46 -%47 = OpBitcast %4 %34 -%48 = OpBitwiseAnd %4 %47 %5 -OpStore %29 %48 -%49 = OpLoad %4 %26 -%50 = OpConvertSToF %7 %49 -%51 = OpFMul %7 %50 %6 -%52 = OpFSub %7 %51 %8 -%53 = OpLoad %4 %29 -%54 = OpConvertSToF %7 %53 -%55 = OpFMul %7 %54 %6 -%56 = OpFSub %7 %55 %8 -%57 = OpCompositeConstruct %10 %52 %56 %9 %8 -%61 = OpAccessChain %59 %43 %60 %42 -%62 = OpLoad %10 %61 -%63 = OpVectorShuffle %11 %62 %62 0 1 2 -%64 = OpAccessChain %59 %43 %60 %60 -%65 = OpLoad %10 %64 -%66 = OpVectorShuffle %11 %65 %65 0 1 2 -%68 = OpAccessChain %59 %43 %60 %67 -%69 = OpLoad %10 %68 -%70 = OpVectorShuffle %11 %69 %69 0 1 2 -%71 = OpCompositeConstruct %16 %63 %66 %70 -%72 = OpTranspose %16 %71 -%73 = OpAccessChain %58 %43 %42 -%74 = OpLoad %13 %73 -%75 = OpMatrixTimesVector %10 %74 %57 -%76 = OpVectorShuffle %11 %75 %75 0 1 2 -%77 = OpMatrixTimesVector %11 %72 %76 -%78 = OpCompositeConstruct %12 %57 %77 -%79 = OpCompositeExtract %10 %78 0 -OpStore %35 %79 -%80 = OpCompositeExtract %11 %78 1 -OpStore %37 %80 +%45 = OpBitcast %10 %29 +%46 = OpSDiv %10 %45 %39 +OpStore %21 %46 +%47 = OpBitcast %10 %29 +%48 = OpBitwiseAnd %10 %47 %40 +OpStore %24 %48 +%49 = OpLoad %10 %21 +%50 = OpConvertSToF %4 %49 +%51 = OpFMul %4 %50 %41 +%52 = OpFSub %4 %51 %42 +%53 = OpLoad %10 %24 +%54 = OpConvertSToF %4 %53 +%55 = OpFMul %4 %54 %41 +%56 = OpFSub %4 %55 %42 +%57 = OpCompositeConstruct %3 %52 %56 %43 %42 +%61 = OpAccessChain %59 %38 %60 %37 +%62 = OpLoad %3 %61 +%63 = OpVectorShuffle %5 %62 %62 0 1 2 +%64 = OpAccessChain %59 %38 %60 %60 +%65 = OpLoad %3 %64 +%66 = OpVectorShuffle %5 %65 %65 0 1 2 +%68 = OpAccessChain %59 %38 %60 %67 +%69 = OpLoad %3 %68 +%70 = OpVectorShuffle %5 %69 %69 0 1 2 +%71 = OpCompositeConstruct %11 %63 %66 %70 +%72 = OpTranspose %11 %71 +%73 = OpAccessChain %58 %38 %37 +%74 = OpLoad %7 %73 +%75 = OpMatrixTimesVector %3 %74 %57 +%76 = OpVectorShuffle %5 %75 %75 0 1 2 +%77 = OpMatrixTimesVector %5 %72 %76 +%78 = OpCompositeConstruct %6 %57 %77 +%79 = OpCompositeExtract %3 %78 0 +OpStore %30 %79 +%80 = OpCompositeExtract %5 %78 1 +OpStore %32 %80 OpReturn OpFunctionEnd -%90 = OpFunction %2 None %40 +%90 = OpFunction %2 None %35 %81 = OpLabel -%85 = OpLoad %10 %83 -%88 = OpLoad %11 %86 -%82 = OpCompositeConstruct %12 %85 %88 -%91 = OpLoad %17 %22 -%92 = OpLoad %18 %24 +%85 = OpLoad %3 %83 +%88 = OpLoad %5 %86 +%82 = OpCompositeConstruct %6 %85 %88 +%91 = OpLoad %12 %17 +%92 = OpLoad %13 %19 OpBranch %93 %93 = OpLabel -%94 = OpCompositeExtract %11 %82 1 +%94 = OpCompositeExtract %5 %82 1 %96 = OpSampledImage %95 %91 %92 -%97 = OpImageSampleImplicitLod %10 %96 %94 +%97 = OpImageSampleImplicitLod %3 %96 %94 OpStore %89 %97 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/texture-arg.spvasm b/tests/out/spv/texture-arg.spvasm index eca3f80c6..f761edf70 100644 --- a/tests/out/spv/texture-arg.spvasm +++ b/tests/out/spv/texture-arg.spvasm @@ -8,53 +8,53 @@ OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %28 "main" %26 OpExecutionMode %28 OriginUpperLeft OpSource GLSL 450 -OpName %9 "Texture" -OpName %11 "Sampler" -OpName %14 "Passed_Texture" -OpName %16 "Passed_Sampler" -OpName %18 "test" +OpName %8 "Texture" +OpName %10 "Sampler" +OpName %13 "Passed_Texture" +OpName %15 "Passed_Sampler" +OpName %17 "test" OpName %28 "main" -OpDecorate %9 DescriptorSet 0 -OpDecorate %9 Binding 0 -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 1 +OpDecorate %8 DescriptorSet 0 +OpDecorate %8 Binding 0 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 1 OpDecorate %26 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 -%3 = OpConstant %4 0.0 -%5 = OpTypeImage %4 2D 0 0 0 1 Unknown -%6 = OpTypeSampler -%7 = OpTypeVector %4 4 -%8 = OpTypeVector %4 2 -%10 = OpTypePointer UniformConstant %5 -%9 = OpVariable %10 UniformConstant -%12 = OpTypePointer UniformConstant %6 -%11 = OpVariable %12 UniformConstant -%19 = OpTypeFunction %7 %10 %12 -%22 = OpTypeSampledImage %5 -%27 = OpTypePointer Output %7 +%3 = OpTypeImage %4 2D 0 0 0 1 Unknown +%5 = OpTypeSampler +%6 = OpTypeVector %4 4 +%7 = OpTypeVector %4 2 +%9 = OpTypePointer UniformConstant %3 +%8 = OpVariable %9 UniformConstant +%11 = OpTypePointer UniformConstant %5 +%10 = OpVariable %11 UniformConstant +%18 = OpTypeFunction %6 %9 %11 +%19 = OpConstant %4 0.0 +%22 = OpTypeSampledImage %3 +%27 = OpTypePointer Output %6 %26 = OpVariable %27 Output %29 = OpTypeFunction %2 -%18 = OpFunction %7 None %19 -%14 = OpFunctionParameter %10 -%16 = OpFunctionParameter %12 -%13 = OpLabel -%15 = OpLoad %5 %14 -%17 = OpLoad %6 %16 +%17 = OpFunction %6 None %18 +%13 = OpFunctionParameter %9 +%15 = OpFunctionParameter %11 +%12 = OpLabel +%14 = OpLoad %3 %13 +%16 = OpLoad %5 %15 OpBranch %20 %20 = OpLabel -%21 = OpCompositeConstruct %8 %3 %3 -%23 = OpSampledImage %22 %15 %17 -%24 = OpImageSampleImplicitLod %7 %23 %21 +%21 = OpCompositeConstruct %7 %19 %19 +%23 = OpSampledImage %22 %14 %16 +%24 = OpImageSampleImplicitLod %6 %23 %21 OpReturnValue %24 OpFunctionEnd %28 = OpFunction %2 None %29 %25 = OpLabel -%30 = OpLoad %5 %9 -%31 = OpLoad %6 %11 +%30 = OpLoad %3 %8 +%31 = OpLoad %5 %10 OpBranch %32 %32 = OpLabel -%33 = OpFunctionCall %7 %18 %9 %11 +%33 = OpFunctionCall %6 %17 %8 %10 OpStore %26 %33 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index a3f03dd2d..26502a9e6 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -125,7 +125,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { vVel = (((_e112 + (_e113 * _e116)) + (_e119 * _e122)) + (_e125 * _e128)); let _e131 = vVel; let _e133 = vVel; - vVel = (normalize(_e131) * clamp(length(_e133), 0.0, 0.10000000149011612)); + vVel = (normalize(_e131) * clamp(length(_e133), 0.0, 0.1)); let _e139 = vPos; let _e140 = vVel; let _e143 = params.deltaT; diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 3409712bc..ddfd0b216 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -121,10 +121,10 @@ fn texture_sample() -> @location(0) vec4 { let _e19 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); let _e20 = a; a = (_e20 + _e19); - let _e24 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284); + let _e24 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3); let _e25 = a; a = (_e25 + _e24); - let _e29 = textureSampleLevel(image_2d, sampler_reg, tc, 2.299999952316284, vec2(3, 1)); + let _e29 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3, vec2(3, 1)); let _e30 = a; a = (_e30 + _e29); let _e35 = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); @@ -136,10 +136,10 @@ fn texture_sample() -> @location(0) vec4 { let _e47 = textureSample(image_2d_array, sampler_reg, tc, 0u, vec2(3, 1)); let _e48 = a; a = (_e48 + _e47); - let _e53 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.299999952316284); + let _e53 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3); let _e54 = a; a = (_e54 + _e53); - let _e59 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.299999952316284, vec2(3, 1)); + let _e59 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3, vec2(3, 1)); let _e60 = a; a = (_e60 + _e59); let _e66 = textureSampleBias(image_2d_array, sampler_reg, tc, 0u, 2.0, vec2(3, 1)); @@ -151,10 +151,10 @@ fn texture_sample() -> @location(0) vec4 { let _e78 = textureSample(image_2d_array, sampler_reg, tc, 0, vec2(3, 1)); let _e79 = a; a = (_e79 + _e78); - let _e84 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.299999952316284); + let _e84 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3); let _e85 = a; a = (_e85 + _e84); - let _e90 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.299999952316284, vec2(3, 1)); + let _e90 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3, vec2(3, 1)); let _e91 = a; a = (_e91 + _e90); let _e97 = textureSampleBias(image_2d_array, sampler_reg, tc, 0, 2.0, vec2(3, 1)); @@ -163,7 +163,7 @@ fn texture_sample() -> @location(0) vec4 { let _e103 = textureSample(image_cube_array, sampler_reg, tc3_, 0u); let _e104 = a; a = (_e104 + _e103); - let _e109 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0u, 2.299999952316284); + let _e109 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0u, 2.3); let _e110 = a; a = (_e110 + _e109); let _e116 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0u, 2.0); @@ -172,7 +172,7 @@ fn texture_sample() -> @location(0) vec4 { let _e122 = textureSample(image_cube_array, sampler_reg, tc3_, 0); let _e123 = a; a = (_e123 + _e122); - let _e128 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0, 2.299999952316284); + let _e128 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0, 2.3); let _e129 = a; a = (_e129 + _e128); let _e135 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0, 2.0); diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 11e7fd92d..d2fb888d7 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -12,7 +12,7 @@ fn builtins() -> vec4 { let s2_ = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); let s3_ = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); let m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - let m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612); + let m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); let b1_ = bitcast(vec4(1, 1, 1, 1).x); let b2_ = bitcast>(vec4(1, 1, 1, 1)); let v_i32_zero = vec4(vec4(0.0, 0.0, 0.0, 0.0)); From 959c84f039c0cb33b07182de11c6a588ff967d3e Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 10 May 2023 22:54:24 -0700 Subject: [PATCH 1995/2212] [glsl-in] Generate `Expression::Literal`. --- src/front/glsl/ast.rs | 4 +-- src/front/glsl/context.rs | 38 ++++++---------------- src/front/glsl/parser/expressions.rs | 47 ++++++++++++++-------------- tests/out/wgsl/bevy-pbr-frag.wgsl | 34 ++++++++++---------- 4 files changed, 53 insertions(+), 70 deletions(-) diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index cbb21f6de..47c5a9e80 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -3,7 +3,7 @@ use std::{borrow::Cow, fmt}; use super::{builtins::MacroCall, context::ExprPos, Span}; use crate::{ AddressSpace, BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, - Interpolation, Sampling, StorageAccess, Type, UnaryOperator, + Interpolation, Literal, Sampling, StorageAccess, Type, UnaryOperator, }; #[derive(Debug, Clone, Copy)] @@ -121,7 +121,7 @@ pub enum HirExprKind { base: Handle, field: String, }, - Constant(Handle), + Literal(Literal), Binary { left: Handle, op: BinaryOperator, diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 6df4850ef..4f3c27b55 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -9,9 +9,9 @@ use super::{ }; use crate::{ front::{Emitter, Typifier}, - AddressSpace, Arena, BinaryOperator, Block, Constant, Expression, FastHashMap, - FunctionArgument, Handle, LocalVariable, RelationalFunction, ScalarKind, ScalarValue, Span, - Statement, Type, TypeInner, VectorSize, + AddressSpace, Arena, BinaryOperator, Block, Expression, FastHashMap, FunctionArgument, Handle, + Literal, LocalVariable, RelationalFunction, ScalarKind, ScalarValue, Span, Statement, Type, + TypeInner, VectorSize, }; use std::{convert::TryFrom, ops::Index}; @@ -560,8 +560,8 @@ impl Context { frontend.field_selection(self, pos, body, base, field, meta)? } - HirExprKind::Constant(constant) if pos != ExprPos::Lhs => { - self.add_expression(Expression::Constant(constant), meta, body) + HirExprKind::Literal(literal) if pos != ExprPos::Lhs => { + self.add_expression(Expression::Literal(literal), meta, body) } HirExprKind::Binary { left, op, right } if pos != ExprPos::Lhs => { let (mut left, left_meta) = @@ -1253,24 +1253,14 @@ impl Context { self.add_expression(Expression::Load { pointer }, meta, body) }; - let make_constant_inner = |kind, width| { - let value = match kind { - ScalarKind::Sint => crate::ScalarValue::Sint(1), - ScalarKind::Uint => crate::ScalarValue::Uint(1), - ScalarKind::Float => crate::ScalarValue::Float(1.0), - ScalarKind::Bool => return None, - }; - - Some(crate::ConstantInner::Scalar { width, value }) - }; let res = match *frontend.resolve_type(self, left, meta)? { TypeInner::Scalar { kind, width } => { let ty = TypeInner::Scalar { kind, width }; - make_constant_inner(kind, width).map(|i| (ty, i, None, None)) + Literal::one(kind, width).map(|i| (ty, i, None, None)) } TypeInner::Vector { size, kind, width } => { let ty = TypeInner::Vector { size, kind, width }; - make_constant_inner(kind, width).map(|i| (ty, i, Some(size), None)) + Literal::one(kind, width).map(|i| (ty, i, Some(size), None)) } TypeInner::Matrix { columns, @@ -1282,12 +1272,12 @@ impl Context { rows, width, }; - make_constant_inner(ScalarKind::Float, width) + Literal::one(ScalarKind::Float, width) .map(|i| (ty, i, Some(rows), Some(columns))) } _ => None, }; - let (ty_inner, inner, rows, columns) = match res { + let (ty_inner, literal, rows, columns) = match res { Some(res) => res, None => { frontend.errors.push(Error { @@ -1300,15 +1290,7 @@ impl Context { } }; - let constant_1 = frontend.module.constants.append( - Constant { - name: None, - specialization: None, - inner, - }, - Default::default(), - ); - let mut right = self.add_expression(Expression::Constant(constant_1), meta, body); + let mut right = self.add_expression(Expression::Literal(literal), meta, body); // Glsl allows pre/postfixes operations on vectors and matrices, so if the // target is either of them change the right side of the addition to be splatted diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index f09e58b6f..72b5a2ddc 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -7,7 +7,7 @@ use crate::{ token::{Token, TokenValue}, Error, Frontend, Result, Span, }, - ArraySize, BinaryOperator, Block, Constant, ConstantInner, Handle, ScalarValue, Type, + ArraySize, BinaryOperator, Block, Constant, ConstantInner, Handle, Literal, ScalarValue, Type, TypeInner, UnaryOperator, }; @@ -21,20 +21,30 @@ impl<'source> ParsingContext<'source> { ) -> Result> { let mut token = self.bump(frontend)?; - let (width, value) = match token.value { - TokenValue::IntConstant(int) => ( - (int.width / 8) as u8, + let literal = match token.value { + TokenValue::IntConstant(int) => { + if int.width != 32 { + frontend.errors.push(Error { + kind: ErrorKind::SemanticError("Unsupported non-32bit integer".into()), + meta: token.meta, + }); + } if int.signed { - ScalarValue::Sint(int.value as i64) + Literal::I32(int.value as i32) } else { - ScalarValue::Uint(int.value) - }, - ), - TokenValue::FloatConstant(float) => ( - (float.width / 8) as u8, - ScalarValue::Float(float.value as f64), - ), - TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)), + Literal::U32(int.value as u32) + } + } + TokenValue::FloatConstant(float) => { + if float.width != 32 { + frontend.errors.push(Error { + kind: ErrorKind::SemanticError("Unsupported floating-point value (expected single-precision floating-point number)".into()), + meta: token.meta, + }); + } + Literal::F32(float.value) + } + TokenValue::BoolConstant(value) => Literal::Bool(value), TokenValue::LeftParen => { let expr = self.parse_expression(frontend, ctx, stmt, body)?; let meta = self.expect(frontend, TokenValue::RightParen)?.meta; @@ -59,18 +69,9 @@ impl<'source> ParsingContext<'source> { } }; - let handle = frontend.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { width, value }, - }, - token.meta, - ); - Ok(stmt.hir_exprs.append( HirExpr { - kind: HirExprKind::Constant(handle), + kind: HirExprKind::Literal(literal), meta: token.meta, }, Default::default(), diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 4b9467e56..646eb615d 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -157,7 +157,7 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 let _e68 = attenuation; _ = distanceSquare_1; let _e73 = distanceSquare_1; - return ((_e68 * 1.0) / max(_e73, 0.0010000000474974513)); + return ((_e68 * 1.0) / max(_e73, 0.001)); } fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { @@ -331,13 +331,13 @@ fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { f0_4 = f0_3; LoH_1 = LoH; _ = f0_4; - _ = vec3((50.0 * 0.33000001311302185)); + _ = vec3((50.0 * 0.33)); let _e49 = f0_4; - _ = dot(_e49, vec3((50.0 * 0.33000001311302185))); + _ = dot(_e49, vec3((50.0 * 0.33))); _ = f0_4; - _ = vec3((50.0 * 0.33000001311302185)); + _ = vec3((50.0 * 0.33)); let _e62 = f0_4; - f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33000001311302185))), 0.0, 1.0); + f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33))), 0.0, 1.0); _ = f0_4; _ = f90_4; _ = LoH_1; @@ -474,8 +474,8 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 f0_8 = f0_7; perceptual_roughness_1 = perceptual_roughness; NoV_7 = NoV_6; - c0_ = vec4(-(1.0), -(0.027499999850988388), -(0.5720000267028809), 0.02199999988079071); - c1_ = vec4(1.0, 0.042500000447034836, 1.0399999618530273, -(0.03999999910593033)); + c0_ = vec4(-(1.0), -(0.0275), -(0.572), 0.022); + c1_ = vec4(1.0, 0.0425, 1.04, -(0.04)); let _e62 = perceptual_roughness_1; let _e64 = c0_; let _e66 = c1_; @@ -484,20 +484,20 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 let _e71 = r; _ = (_e69.x * _e71.x); let _e76 = NoV_7; - _ = (-(9.279999732971191) * _e76); + _ = (-(9.28) * _e76); let _e80 = NoV_7; - _ = exp2((-(9.279999732971191) * _e80)); + _ = exp2((-(9.28) * _e80)); let _e83 = r; let _e85 = r; let _e90 = NoV_7; - _ = (-(9.279999732971191) * _e90); + _ = (-(9.28) * _e90); let _e94 = NoV_7; let _e98 = r; let _e101 = r; - a004_ = ((min((_e83.x * _e85.x), exp2((-(9.279999732971191) * _e94))) * _e98.x) + _e101.y); + a004_ = ((min((_e83.x * _e85.x), exp2((-(9.28) * _e94))) * _e98.x) + _e101.y); let _e109 = a004_; let _e112 = r; - AB = ((vec2(-(1.0399999618530273), 1.0399999618530273) * vec2(_e109)) + _e112.zw); + AB = ((vec2(-(1.04), 1.04) * vec2(_e109)) + _e112.zw); let _e116 = f0_8; let _e117 = AB; let _e121 = AB; @@ -522,7 +522,7 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { perceptualRoughness_1 = perceptualRoughness; _ = perceptualRoughness_1; let _e45 = perceptualRoughness_1; - clampedPerceptualRoughness = clamp(_e45, 0.08900000154972076, 1.0); + clampedPerceptualRoughness = clamp(_e45, 0.089, 1.0); let _e50 = clampedPerceptualRoughness; let _e51 = clampedPerceptualRoughness; return (_e50 * _e51); @@ -592,9 +592,9 @@ fn luminance(v_1: vec3) -> f32 { _ = (&global_7.emissive); v_2 = v_1; _ = v_2; - _ = vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023); + _ = vec3(0.2126, 0.7152, 0.0722); let _e47 = v_2; - return dot(_e47, vec3(0.2125999927520752, 0.7152000069618225, 0.0722000002861023)); + return dot(_e47, vec3(0.2126, 0.7152, 0.0722)); } fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { @@ -1177,13 +1177,13 @@ fn main_1() { _ = V_3; let _e183 = N_2; let _e184 = V_3; - NdotV_4 = max(dot(_e183, _e184), 0.0010000000474974513); + NdotV_4 = max(dot(_e183, _e184), 0.001); let _e190 = global_6.reflectance; let _e192 = global_6.reflectance; let _e195 = metallic; let _e199 = output_color; let _e201 = metallic; - F0_4 = (vec3((((0.1599999964237213 * _e190) * _e192) * (1.0 - _e195))) + (_e199.xyz * vec3(_e201))); + F0_4 = (vec3((((0.16 * _e190) * _e192) * (1.0 - _e195))) + (_e199.xyz * vec3(_e201))); let _e206 = output_color; let _e209 = metallic; diffuseColor_4 = (_e206.xyz * vec3((1.0 - _e209))); From d763fb31e244944b0acd6dce1e7e9328770a3bcc Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 10 May 2023 23:11:56 -0700 Subject: [PATCH 1996/2212] [spv-in] Generate `Expression::Literal` in some limited cases. --- src/front/spv/mod.rs | 45 +++++++++++++++++++++----------------------- 1 file changed, 21 insertions(+), 24 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a301ac141..e920db145 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1680,18 +1680,25 @@ impl> Frontend { let index_handle = get_expr_handle!(index_id, index_lexp); let num_components = match ctx.type_arena[root_type_lookup.handle].inner { - crate::TypeInner::Vector { size, .. } => size as usize, + crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), }; + let make_index = |ctx: &mut BlockContext, index: u32| { + ctx.expressions + .append(crate::Expression::Literal(crate::Literal::U32(index)), span) + }; + + let index_expr = make_index(ctx, 0); let mut handle = ctx.expressions.append( crate::Expression::Access { base: root_handle, - index: self.index_constant_expressions[0], + index: index_expr, }, span, ); - for &index_expr in self.index_constant_expressions[1..num_components].iter() { + for index in 1..num_components { + let index_expr = make_index(ctx, index); let access_expr = ctx.expressions.append( crate::Expression::Access { base: root_handle, @@ -1741,31 +1748,21 @@ impl> Frontend { let root_handle = get_expr_handle!(composite_id, root_lexp); let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; let index_lexp = self.lookup_expression.lookup(index_id)?; - let mut index_handle = get_expr_handle!(index_id, index_lexp); - let index_type = self.lookup_type.lookup(index_lexp.type_id)?.handle; - - // SPIR-V allows signed and unsigned indices but naga's is strict about - // types and since the `index_constants` are all signed integers, we need - // to cast the index to a signed integer if it's unsigned. - if let Some(crate::ScalarKind::Uint) = - ctx.type_arena[index_type].inner.scalar_kind() - { - index_handle = ctx.expressions.append( - crate::Expression::As { - expr: index_handle, - kind: crate::ScalarKind::Sint, - convert: None, - }, - span, - ) - } + let index_handle = get_expr_handle!(index_id, index_lexp); let num_components = match ctx.type_arena[root_type_lookup.handle].inner { - crate::TypeInner::Vector { size, .. } => size as usize, + crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), }; - let mut components = Vec::with_capacity(num_components); - for &index_expr in self.index_constant_expressions[..num_components].iter() { + + let make_index = |ctx: &mut BlockContext, index: u32| { + ctx.expressions + .append(crate::Expression::Literal(crate::Literal::U32(index)), span) + }; + + let mut components = Vec::with_capacity(num_components as usize); + for index in 0..num_components { + let index_expr = make_index(ctx, index); let access_expr = ctx.expressions.append( crate::Expression::Access { base: root_handle, From d842d6688d5cf02e6efb2fce6d4dc599f2d4f33c Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 11 May 2023 18:09:05 +0200 Subject: [PATCH 1997/2212] Introduce `GlobalCtx` --- src/back/hlsl/conv.rs | 21 +++++-------- src/back/hlsl/help.rs | 7 +---- src/back/hlsl/storage.rs | 4 +-- src/back/hlsl/writer.rs | 2 +- src/back/msl/writer.rs | 40 ++++++++++++------------- src/front/glsl/functions.rs | 2 +- src/front/glsl/parser/types.rs | 5 +--- src/front/spv/function.rs | 7 +++++ src/front/spv/mod.rs | 14 +++------ src/front/wgsl/lower/construction.rs | 8 ++--- src/front/wgsl/lower/mod.rs | 24 +++++++-------- src/front/wgsl/mod.rs | 45 +++++++++++----------------- src/proc/layouter.rs | 12 +++----- src/proc/mod.rs | 23 +++++++++++--- src/valid/compose.rs | 28 ++++++++--------- src/valid/expression.rs | 3 +- src/valid/function.rs | 9 +++--- src/valid/interface.rs | 6 ++-- src/valid/mod.rs | 28 ++++++++--------- src/valid/type.rs | 20 +++++-------- 20 files changed, 138 insertions(+), 170 deletions(-) diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 5eb24962f..69334ecb1 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -40,11 +40,7 @@ impl crate::TypeInner { } } - pub(super) fn size_hlsl( - &self, - types: &crate::UniqueArena, - constants: &crate::Arena, - ) -> u32 { + pub(super) fn size_hlsl(&self, gctx: crate::proc::GlobalCtx) -> u32 { match *self { Self::Matrix { columns, @@ -58,26 +54,25 @@ impl crate::TypeInner { Self::Array { base, size, stride } => { let count = match size { crate::ArraySize::Constant(handle) => { - constants[handle].to_array_length().unwrap_or(1) + gctx.constants[handle].to_array_length().unwrap_or(1) } // A dynamically-sized array has to have at least one element crate::ArraySize::Dynamic => 1, }; - let last_el_size = types[base].inner.size_hlsl(types, constants); + let last_el_size = gctx.types[base].inner.size_hlsl(gctx); ((count - 1) * stride) + last_el_size } - _ => self.size(constants), + _ => self.size(gctx), } } /// Used to generate the name of the wrapped type constructor pub(super) fn hlsl_type_id<'a>( base: crate::Handle, - types: &crate::UniqueArena, - constants: &crate::Arena, + gctx: crate::proc::GlobalCtx, names: &'a crate::FastHashMap, ) -> Result, Error> { - Ok(match types[base].inner { + Ok(match gctx.types[base].inner { crate::TypeInner::Scalar { kind, width } => Cow::Borrowed(kind.to_hlsl_str(width)?), crate::TypeInner::Vector { size, kind, width } => Cow::Owned(format!( "{}{}", @@ -100,8 +95,8 @@ impl crate::TypeInner { .. } => Cow::Owned(format!( "array{}_{}_", - constants[size].to_array_length().unwrap(), - Self::hlsl_type_id(base, types, constants, names)? + gctx.constants[size].to_array_length().unwrap(), + Self::hlsl_type_id(base, gctx, names)? )), crate::TypeInner::Struct { .. } => { Cow::Borrowed(&names[&crate::proc::NameKey::Type(base)]) diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 8ae9baf62..51ec5ef4d 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -347,12 +347,7 @@ impl<'a, W: Write> super::Writer<'a, W> { module: &crate::Module, constructor: WrappedConstructor, ) -> BackendResult { - let name = crate::TypeInner::hlsl_type_id( - constructor.ty, - &module.types, - &module.constants, - &self.names, - )?; + let name = crate::TypeInner::hlsl_type_id(constructor.ty, module.to_ctx(), &self.names)?; write!(self.out, "Construct{name}")?; Ok(()) } diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 813dd7364..833a6dce9 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -218,7 +218,7 @@ impl super::Writer<'_, W> { self.write_wrapped_constructor_function_name(module, constructor)?; write!(self.out, "(")?; let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.size(&module.constants); + let stride = module.types[base].inner.size(module.to_ctx()); let iter = (0..count).map(|i| (TypeResolution::Handle(base), stride * i)); self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; write!(self.out, ")")?; @@ -381,7 +381,7 @@ impl super::Writer<'_, W> { writeln!(self.out, ";")?; // then iterate the stores let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.size(&module.constants); + let stride = module.types[base].inner.size(module.to_ctx()); for i in 0..count { self.temp_access_chain.push(SubAccess::Offset(i * stride)); let sv = StoreValue::TempIndex { diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 3d0ed9cd3..a97b5eb3b 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -877,7 +877,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } let ty_inner = &module.types[member.ty].inner; - last_offset = member.offset + ty_inner.size_hlsl(&module.types, &module.constants); + last_offset = member.offset + ty_inner.size_hlsl(module.to_ctx()); // The indentation is only for readability write!(self.out, "{}", back::INDENT)?; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 7e41e8a7e..0621bbdf9 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -77,7 +77,7 @@ const CLAMPED_LOD_LOAD_PREFIX: &str = "clamped_lod_e"; struct TypeContext<'a> { handle: Handle, - module: &'a crate::Module, + gctx: proc::GlobalCtx<'a>, names: &'a FastHashMap, access: crate::StorageAccess, binding: Option<&'a super::ResolvedBinding>, @@ -86,7 +86,7 @@ struct TypeContext<'a> { impl<'a> Display for TypeContext<'a> { fn fmt(&self, out: &mut Formatter<'_>) -> Result<(), FmtError> { - let ty = &self.module.types[self.handle]; + let ty = &self.gctx.types[self.handle]; if ty.needs_alias() && !self.first_time { let name = &self.names[&NameKey::Type(self.handle)]; return write!(out, "{name}"); @@ -223,7 +223,7 @@ impl<'a> Display for TypeContext<'a> { } else if let crate::ArraySize::Constant(size) = size { let constant_ctx = ConstantContext { handle: size, - arena: &self.module.constants, + arena: self.gctx.constants, names: self.names, first_time: false, }; @@ -271,7 +271,7 @@ impl<'a> TypedGlobalVariable<'a> { }; let ty_name = TypeContext { handle: var.ty, - module: self.module, + gctx: self.module.to_ctx(), names: self.names, access: storage_access, binding: self.binding, @@ -399,7 +399,7 @@ fn should_pack_struct_member( } let ty_inner = &module.types[member.ty].inner; - let last_offset = member.offset + ty_inner.size(&module.constants); + let last_offset = member.offset + ty_inner.size(module.to_ctx()); let next_offset = match members.get(index + 1) { Some(next) => next.offset, None => span, @@ -1153,7 +1153,7 @@ impl Writer { crate::TypeInner::Array { base, stride, .. } => ( context.module.types[base] .inner - .size(&context.module.constants), + .size(context.module.to_ctx()), stride, ), _ => return Err(Error::Validation), @@ -1336,7 +1336,7 @@ impl Writer { crate::Expression::ZeroValue(ty) => { let ty_name = TypeContext { handle: ty, - module: context.module, + gctx: context.module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -2459,7 +2459,7 @@ impl Writer { TypeResolution::Handle(ty_handle) => { let ty_name = TypeContext { handle: ty_handle, - module: context.module, + gctx: context.module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3155,7 +3155,7 @@ impl Writer { } => { let base_name = TypeContext { handle: base, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3200,7 +3200,7 @@ impl Writer { writeln!(self.out, "{}char _pad{}[{}];", back::INDENT, index, pad)?; } let ty_inner = &module.types[member.ty].inner; - last_offset = member.offset + ty_inner.size(&module.constants); + last_offset = member.offset + ty_inner.size(module.to_ctx()); let member_name = &self.names[&NameKey::StructMember(handle, index as u32)]; @@ -3219,7 +3219,7 @@ impl Writer { None => { let base_name = TypeContext { handle: member.ty, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3250,7 +3250,7 @@ impl Writer { _ => { let ty_name = TypeContext { handle, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3310,7 +3310,7 @@ impl Writer { let name = &self.names[&NameKey::Constant(handle)]; let ty_name = TypeContext { handle: ty, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3450,7 +3450,7 @@ impl Writer { Some(ref result) => { let ty_name = TypeContext { handle: result.ty, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3468,7 +3468,7 @@ impl Writer { let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)]; let param_type_name = TypeContext { handle: arg.ty, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3517,7 +3517,7 @@ impl Writer { for (local_handle, local) in fun.local_variables.iter() { let ty_name = TypeContext { handle: local.ty, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3714,7 +3714,7 @@ impl Writer { let name = &self.names[name_key]; let ty_name = TypeContext { handle: ty, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3758,7 +3758,7 @@ impl Writer { for (name, ty, binding) in result_members { let ty_name = TypeContext { handle: ty, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -3853,7 +3853,7 @@ impl Writer { let ty_name = TypeContext { handle: ty, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, @@ -4090,7 +4090,7 @@ impl Writer { let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; let ty_name = TypeContext { handle: local.ty, - module, + gctx: module.to_ctx(), names: &self.names, access: crate::StorageAccess::empty(), binding: None, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 10c964b5e..355b1453b 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1501,7 +1501,7 @@ impl Frontend { offset: span, }); - span += self.module.types[ty].inner.size(&self.module.constants); + span += self.module.types[ty].inner.size(self.module.to_ctx()); let len = expressions.len(); let load = expressions.append(Expression::Load { pointer }, Default::default()); diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 08a70669a..5c92b4f3d 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -53,10 +53,7 @@ impl<'source> ParsingContext<'source> { ArraySize::Constant(constant) }; - frontend - .layouter - .update(&frontend.module.types, &frontend.module.constants) - .unwrap(); + frontend.layouter.update(frontend.module.to_ctx()).unwrap(); let stride = frontend.layouter[*ty].to_stride(); *ty = frontend.module.types.insert( Type { diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 5dc781504..89ad4a0e1 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -568,6 +568,13 @@ impl> super::Frontend { } impl<'function> BlockContext<'function> { + pub(super) fn gctx(&self) -> crate::proc::GlobalCtx { + crate::proc::GlobalCtx { + types: self.type_arena, + constants: self.const_arena, + } + } + /// Consumes the `BlockContext` producing a Ir [`Block`](crate::Block) fn lower(mut self) -> crate::Block { fn lower_impl( diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e920db145..14bae2a9c 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2089,7 +2089,7 @@ impl> Frontend { let result_ty = self.lookup_type.lookup(result_type_id)?; let inner = &ctx.type_arena[result_ty.handle].inner; let kind = inner.scalar_kind().unwrap(); - let size = inner.size(ctx.const_arena) as u8; + let size = inner.size(ctx.gctx()) as u8; let left_cast = ctx.expressions.append( crate::Expression::As { @@ -4387,9 +4387,7 @@ impl> Frontend { let decor = self.future_decor.remove(&id).unwrap_or_default(); let base = self.lookup_type.lookup(type_id)?.handle; - self.layouter - .update(&module.types, &module.constants) - .unwrap(); + self.layouter.update(module.to_ctx()).unwrap(); // HACK if the underlying type is an image or a sampler, let's assume // that we're dealing with a binding-array @@ -4470,9 +4468,7 @@ impl> Frontend { let decor = self.future_decor.remove(&id).unwrap_or_default(); let base = self.lookup_type.lookup(type_id)?.handle; - self.layouter - .update(&module.types, &module.constants) - .unwrap(); + self.layouter.update(module.to_ctx()).unwrap(); // HACK same case as in `parse_type_array()` let inner = if let crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } = @@ -4523,9 +4519,7 @@ impl> Frontend { .as_ref() .map_or(false, |decor| decor.storage_buffer); - self.layouter - .update(&module.types, &module.constants) - .unwrap(); + self.layouter.update(module.to_ctx()).unwrap(); let mut members = Vec::::with_capacity(inst.wc as usize - 2); let mut member_lookups = Vec::with_capacity(members.capacity()); diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 0c2f29bd9..c1457b0d9 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -471,9 +471,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ctx.module.constants.fetch_or_append(size, Span::UNDEFINED), ), stride: { - self.layouter - .update(&ctx.module.types, &ctx.module.constants) - .unwrap(); + self.layouter.update(ctx.module.to_ctx()).unwrap(); self.layouter[base].to_stride() }, }; @@ -645,9 +643,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, }; - self.layouter - .update(&ctx.module.types, &ctx.module.constants) - .unwrap(); + self.layouter.update(ctx.module.to_ctx()).unwrap(); let ty = ctx.ensure_type_exists(crate::TypeInner::Array { base, size, diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index e066a29f1..6e1d2f24e 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -343,7 +343,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { } fn format_typeinner(&self, inner: &crate::TypeInner) -> String { - inner.to_wgsl(&self.module.types, &self.module.constants) + inner.to_wgsl(self.module.to_ctx()) } fn format_type(&self, handle: Handle) -> String { @@ -624,14 +624,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { if let Some(explicit) = explicit_ty { if explicit != inferred_type { let ty = &ctx.module.types[explicit]; - let explicit = ty.name.clone().unwrap_or_else(|| { - ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) - }); + let explicit = ty + .name + .clone() + .unwrap_or_else(|| ty.inner.to_wgsl(ctx.module.to_ctx())); let ty = &ctx.module.types[inferred_type]; - let inferred = ty.name.clone().unwrap_or_else(|| { - ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) - }); + let inferred = ty + .name + .clone() + .unwrap_or_else(|| ty.inner.to_wgsl(ctx.module.to_ctx())); return Err(Error::InitializationTypeMismatch( c.name.span, @@ -2065,9 +2067,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { for member in s.members.iter() { let ty = self.resolve_ast_type(member.ty, ctx.reborrow())?; - self.layouter - .update(&ctx.module.types, &ctx.module.constants) - .unwrap(); + self.layouter.update(ctx.module.to_ctx()).unwrap(); let member_min_size = self.layouter[ty].size; let member_min_alignment = self.layouter[ty].alignment; @@ -2154,9 +2154,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::Type::Array { base, size } => { let base = self.resolve_ast_type(base, ctx.reborrow())?; - self.layouter - .update(&ctx.module.types, &ctx.module.constants) - .unwrap(); + self.layouter.update(ctx.module.to_ctx()).unwrap(); crate::TypeInner::Array { base, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index eb21fae6c..a64f1f8f1 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -11,8 +11,6 @@ mod parse; #[cfg(test)] mod tests; -use crate::arena::{Arena, UniqueArena}; - use crate::front::wgsl::error::Error; use crate::front::wgsl::parse::Parser; use thiserror::Error; @@ -100,11 +98,7 @@ impl crate::TypeInner { /// For example `vec3`. /// /// Note: The names of a `TypeInner::Struct` is not known. Therefore this method will simply return "struct" for them. - fn to_wgsl( - &self, - types: &UniqueArena, - constants: &Arena, - ) -> String { + fn to_wgsl(&self, gctx: crate::proc::GlobalCtx) -> String { use crate::TypeInner as Ti; match *self { @@ -128,7 +122,7 @@ impl crate::TypeInner { format!("atomic<{}>", kind.to_wgsl(width)) } Ti::Pointer { base, .. } => { - let base = &types[base]; + let base = &gctx.types[base]; let name = base.name.as_deref().unwrap_or("unknown"); format!("ptr<{name}>") } @@ -136,11 +130,11 @@ impl crate::TypeInner { format!("ptr<{}>", kind.to_wgsl(width)) } Ti::Array { base, size, .. } => { - let member_type = &types[base]; + let member_type = &gctx.types[base]; let base = member_type.name.as_deref().unwrap_or("unknown"); match size { crate::ArraySize::Constant(size) => { - let constant = &constants[size]; + let constant = &gctx.constants[size]; let size = constant .name .clone() @@ -209,11 +203,11 @@ impl crate::TypeInner { Ti::AccelerationStructure => "acceleration_structure".to_string(), Ti::RayQuery => "ray_query".to_string(), Ti::BindingArray { base, size, .. } => { - let member_type = &types[base]; + let member_type = &gctx.types[base]; let base = member_type.name.as_deref().unwrap_or("unknown"); match size { crate::ArraySize::Constant(size) => { - let size = constants[size].name.as_deref().unwrap_or("unknown"); + let size = gctx.constants[size].name.as_deref().unwrap_or("unknown"); format!("binding_array<{base}, {size}>") } crate::ArraySize::Dynamic => format!("binding_array<{base}>"), @@ -261,19 +255,23 @@ mod type_inner_tests { Default::default(), ); + let gctx = crate::proc::GlobalCtx { + types: &types, + constants: &constants, + }; let array = crate::TypeInner::Array { base: mytype1, stride: 4, size: crate::ArraySize::Constant(c), }; - assert_eq!(array.to_wgsl(&types, &constants), "array"); + assert_eq!(array.to_wgsl(gctx), "array"); let mat = crate::TypeInner::Matrix { rows: crate::VectorSize::Quad, columns: crate::VectorSize::Bi, width: 8, }; - assert_eq!(mat.to_wgsl(&types, &constants), "mat2x4"); + assert_eq!(mat.to_wgsl(gctx), "mat2x4"); let ptr = crate::TypeInner::Pointer { base: mytype2, @@ -281,7 +279,7 @@ mod type_inner_tests { access: crate::StorageAccess::default(), }, }; - assert_eq!(ptr.to_wgsl(&types, &constants), "ptr"); + assert_eq!(ptr.to_wgsl(gctx), "ptr"); let img1 = crate::TypeInner::Image { dim: crate::ImageDimension::D2, @@ -291,36 +289,27 @@ mod type_inner_tests { multi: true, }, }; - assert_eq!( - img1.to_wgsl(&types, &constants), - "texture_multisampled_2d" - ); + assert_eq!(img1.to_wgsl(gctx), "texture_multisampled_2d"); let img2 = crate::TypeInner::Image { dim: crate::ImageDimension::Cube, arrayed: true, class: crate::ImageClass::Depth { multi: false }, }; - assert_eq!(img2.to_wgsl(&types, &constants), "texture_depth_cube_array"); + assert_eq!(img2.to_wgsl(gctx), "texture_depth_cube_array"); let img3 = crate::TypeInner::Image { dim: crate::ImageDimension::D2, arrayed: false, class: crate::ImageClass::Depth { multi: true }, }; - assert_eq!( - img3.to_wgsl(&types, &constants), - "texture_depth_multisampled_2d" - ); + assert_eq!(img3.to_wgsl(gctx), "texture_depth_multisampled_2d"); let array = crate::TypeInner::BindingArray { base: mytype1, size: crate::ArraySize::Constant(c), }; - assert_eq!( - array.to_wgsl(&types, &constants), - "binding_array" - ); + assert_eq!(array.to_wgsl(gctx), "binding_array"); } } diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 65369d1cc..11b2250e9 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -1,4 +1,4 @@ -use crate::arena::{Arena, Handle, UniqueArena}; +use crate::arena::Handle; use std::{fmt::Display, num::NonZeroU32, ops}; /// A newtype struct where its only valid values are powers of 2 @@ -165,15 +165,11 @@ impl Layouter { /// constant arenas, and then assume that layouts are available for all /// types. #[allow(clippy::or_fun_call)] - pub fn update( - &mut self, - types: &UniqueArena, - constants: &Arena, - ) -> Result<(), LayoutError> { + pub fn update(&mut self, gctx: super::GlobalCtx) -> Result<(), LayoutError> { use crate::TypeInner as Ti; - for (ty_handle, ty) in types.iter().skip(self.layouts.len()) { - let size = ty.inner.size(constants); + for (ty_handle, ty) in gctx.types.iter().skip(self.layouts.len()) { + let size = ty.inner.size(gctx); let layout = match ty.inner { Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => { let alignment = Alignment::new(width as u32) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index ed501693d..80ae567ee 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -199,7 +199,7 @@ impl super::TypeInner { } /// Get the size of this type. - pub fn size(&self, constants: &super::Arena) -> u32 { + pub fn size(&self, gctx: GlobalCtx) -> u32 { match *self { Self::Scalar { kind: _, width } | Self::Atomic { kind: _, width } => width as u32, Self::Vector { @@ -221,7 +221,7 @@ impl super::TypeInner { } => { let count = match size { super::ArraySize::Constant(handle) => { - constants[handle].to_array_length().unwrap_or(1) + gctx.constants[handle].to_array_length().unwrap_or(1) } // A dynamically-sized array has to have at least one element super::ArraySize::Dynamic => 1, @@ -575,16 +575,31 @@ impl super::ImageClass { } } +impl crate::Module { + pub const fn to_ctx(&self) -> GlobalCtx<'_> { + GlobalCtx { + types: &self.types, + constants: &self.constants, + } + } +} + +#[derive(Clone, Copy)] +pub struct GlobalCtx<'a> { + pub types: &'a crate::UniqueArena, + pub constants: &'a crate::Arena, +} + #[test] fn test_matrix_size() { - let constants = crate::Arena::new(); + let module = crate::Module::default(); assert_eq!( crate::TypeInner::Matrix { columns: crate::VectorSize::Tri, rows: crate::VectorSize::Tri, width: 4 } - .size(&constants), + .size(module.to_ctx()), 48, ); } diff --git a/src/valid/compose.rs b/src/valid/compose.rs index e77d53825..a7a961979 100644 --- a/src/valid/compose.rs +++ b/src/valid/compose.rs @@ -1,8 +1,5 @@ #[cfg(feature = "validate")] -use crate::{ - arena::{Arena, UniqueArena}, - proc::TypeResolution, -}; +use crate::proc::TypeResolution; use crate::arena::Handle; @@ -20,18 +17,17 @@ pub enum ComposeError { #[cfg(feature = "validate")] pub fn validate_compose( self_ty_handle: Handle, - constant_arena: &Arena, - type_arena: &UniqueArena, + gctx: crate::proc::GlobalCtx, component_resolutions: impl ExactSizeIterator, ) -> Result<(), ComposeError> { use crate::TypeInner as Ti; - match type_arena[self_ty_handle].inner { + match gctx.types[self_ty_handle].inner { // vectors are composed from scalars or other vectors Ti::Vector { size, kind, width } => { let mut total = 0; for (index, comp_res) in component_resolutions.enumerate() { - total += match *comp_res.inner_with(type_arena) { + total += match *comp_res.inner_with(gctx.types) { Ti::Scalar { kind: comp_kind, width: comp_width, @@ -74,7 +70,7 @@ pub fn validate_compose( }); } for (index, comp_res) in component_resolutions.enumerate() { - if comp_res.inner_with(type_arena) != &inner { + if comp_res.inner_with(gctx.types) != &inner { log::error!("Matrix component[{}] type {:?}", index, comp_res); return Err(ComposeError::ComponentType { index: index as u32, @@ -87,7 +83,7 @@ pub fn validate_compose( size: crate::ArraySize::Constant(handle), stride: _, } => { - let count = constant_arena[handle].to_array_length().unwrap(); + let count = gctx.constants[handle].to_array_length().unwrap(); if count as usize != component_resolutions.len() { return Err(ComposeError::ComponentCount { expected: count, @@ -95,11 +91,11 @@ pub fn validate_compose( }); } for (index, comp_res) in component_resolutions.enumerate() { - let base_inner = &type_arena[base].inner; - let comp_res_inner = comp_res.inner_with(type_arena); + let base_inner = &gctx.types[base].inner; + let comp_res_inner = comp_res.inner_with(gctx.types); // We don't support arrays of pointers, but it seems best not to // embed that assumption here, so use `TypeInner::equivalent`. - if !base_inner.equivalent(comp_res_inner, type_arena) { + if !base_inner.equivalent(comp_res_inner, gctx.types) { log::error!("Array component[{}] type {:?}", index, comp_res); return Err(ComposeError::ComponentType { index: index as u32, @@ -116,11 +112,11 @@ pub fn validate_compose( } for (index, (member, comp_res)) in members.iter().zip(component_resolutions).enumerate() { - let member_inner = &type_arena[member.ty].inner; - let comp_res_inner = comp_res.inner_with(type_arena); + let member_inner = &gctx.types[member.ty].inner; + let comp_res_inner = comp_res.inner_with(gctx.types); // We don't support pointers in structs, but it seems best not to embed // that assumption here, so use `TypeInner::equivalent`. - if !comp_res_inner.equivalent(member_inner, type_arena) { + if !comp_res_inner.equivalent(member_inner, gctx.types) { log::error!("Struct component[{}] type {:?}", index, comp_res); return Err(ComposeError::ComponentType { index: index as u32, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index ece98d70f..b5cea3194 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -301,8 +301,7 @@ impl super::Validator { E::Compose { ref components, ty } => { validate_compose( ty, - &module.constants, - &module.types, + module.to_ctx(), components.iter().map(|&handle| info[handle].ty.clone()), )?; ShaderStages::all() diff --git a/src/valid/function.rs b/src/valid/function.rs index 8ebcddd9e..c18f86555 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -894,8 +894,7 @@ impl super::Validator { fn validate_local_var( &self, var: &crate::LocalVariable, - types: &UniqueArena, - constants: &Arena, + gctx: crate::proc::GlobalCtx, ) -> Result<(), LocalVariableError> { log::debug!("var {:?}", var); let type_info = self @@ -910,13 +909,13 @@ impl super::Validator { } if let Some(const_handle) = var.init { - match constants[const_handle].inner { + match gctx.constants[const_handle].inner { crate::ConstantInner::Scalar { width, ref value } => { let ty_inner = crate::TypeInner::Scalar { width, kind: value.scalar_kind(), }; - if types[var.ty].inner != ty_inner { + if gctx.types[var.ty].inner != ty_inner { return Err(LocalVariableError::InitializerType); } } @@ -942,7 +941,7 @@ impl super::Validator { #[cfg(feature = "validate")] for (var_handle, var) in fun.local_variables.iter() { - self.validate_local_var(var, &module.types, &module.constants) + self.validate_local_var(var, module.to_ctx()) .map_err(|source| { FunctionError::LocalVariable { handle: var_handle, diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 1fafef2f6..47e2f201c 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -395,12 +395,12 @@ impl super::Validator { pub(super) fn validate_global_var( &self, var: &crate::GlobalVariable, - types: &UniqueArena, + gctx: crate::proc::GlobalCtx, ) -> Result<(), GlobalVariableError> { use super::TypeFlags; log::debug!("var {:?}", var); - let inner_ty = match types[var.ty].inner { + let inner_ty = match gctx.types[var.ty].inner { // A binding array is (mostly) supposed to behave the same as a // series of individually bound resources, so we can (mostly) // validate a `binding_array` as if it were just a plain `T`. @@ -444,7 +444,7 @@ impl super::Validator { ) } crate::AddressSpace::Handle => { - match types[inner_ty].inner { + match gctx.types[inner_ty].inner { crate::TypeInner::Image { class, .. } => match class { crate::ImageClass::Storage { format: diff --git a/src/valid/mod.rs b/src/valid/mod.rs index bed067db8..3e689160b 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -11,7 +11,7 @@ mod interface; mod r#type; #[cfg(feature = "validate")] -use crate::arena::{Arena, UniqueArena}; +use crate::arena::UniqueArena; use crate::{ arena::Handle, @@ -296,10 +296,9 @@ impl Validator { fn validate_constant( &self, handle: Handle, - constants: &Arena, - types: &UniqueArena, + gctx: crate::proc::GlobalCtx, ) -> Result<(), ConstantError> { - let con = &constants[handle]; + let con = &gctx.constants[handle]; match con.inner { crate::ConstantInner::Scalar { width, ref value } => { if self.check_width(value.scalar_kind(), width).is_err() { @@ -309,11 +308,10 @@ impl Validator { crate::ConstantInner::Composite { ty, ref components } => { compose::validate_compose( ty, - constants, - types, + gctx, components .iter() - .map(|&component| constants[component].inner.resolve_type()), + .map(|&component| gctx.constants[component].inner.resolve_type()), )?; } } @@ -331,17 +329,15 @@ impl Validator { #[cfg(feature = "validate")] Self::validate_module_handles(module).map_err(|e| e.with_span())?; - self.layouter - .update(&module.types, &module.constants) - .map_err(|e| { - let handle = e.ty; - ValidationError::from(e).with_span_handle(handle, &module.types) - })?; + self.layouter.update(module.to_ctx()).map_err(|e| { + let handle = e.ty; + ValidationError::from(e).with_span_handle(handle, &module.types) + })?; #[cfg(feature = "validate")] if self.flags.contains(ValidationFlags::CONSTANTS) { for (handle, constant) in module.constants.iter() { - self.validate_constant(handle, &module.constants, &module.types) + self.validate_constant(handle, module.to_ctx()) .map_err(|source| { ValidationError::Constant { handle, @@ -361,7 +357,7 @@ impl Validator { for (handle, ty) in module.types.iter() { let ty_info = self - .validate_type(handle, &module.types, &module.constants) + .validate_type(handle, module.to_ctx()) .map_err(|source| { ValidationError::Type { handle, @@ -376,7 +372,7 @@ impl Validator { #[cfg(feature = "validate")] for (var_handle, var) in module.global_variables.iter() { - self.validate_global_var(var, &module.types) + self.validate_global_var(var, module.to_ctx()) .map_err(|source| { ValidationError::GlobalVariable { handle: var_handle, diff --git a/src/valid/type.rs b/src/valid/type.rs index 1838ce88a..e122fec44 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -1,8 +1,5 @@ use super::Capabilities; -use crate::{ - arena::{Arena, Handle, UniqueArena}, - proc::Alignment, -}; +use crate::{arena::Handle, proc::Alignment}; bitflags::bitflags! { /// Flags associated with [`Type`]s by [`Validator`]. @@ -246,11 +243,10 @@ impl super::Validator { pub(super) fn validate_type( &self, handle: Handle, - types: &UniqueArena, - constants: &Arena, + gctx: crate::proc::GlobalCtx, ) -> Result { use crate::TypeInner as Ti; - Ok(match types[handle].inner { + Ok(match gctx.types[handle].inner { Ti::Scalar { kind, width } => { self.check_width(kind, width)?; let shareable = if kind.is_numeric() { @@ -419,7 +415,7 @@ impl super::Validator { let type_info_mask = match size { crate::ArraySize::Constant(const_handle) => { - let constant = &constants[const_handle]; + let constant = &gctx.constants[const_handle]; let length_is_positive = match *constant { crate::Constant { specialization: Some(_), @@ -535,7 +531,7 @@ impl super::Validator { } } - let base_size = types[member.ty].inner.size(constants); + let base_size = gctx.types[member.ty].inner.size(gctx); min_offset = member.offset + base_size; if min_offset > span { return Err(TypeError::MemberOutOfBounds { @@ -579,14 +575,14 @@ impl super::Validator { } }; - prev_struct_data = match types[member.ty].inner { + prev_struct_data = match gctx.types[member.ty].inner { crate::TypeInner::Struct { span, .. } => Some((span, member.offset)), _ => None, }; // The last field may be an unsized array. if !base_info.flags.contains(TypeFlags::SIZED) { - let is_array = match types[member.ty].inner { + let is_array = match gctx.types[member.ty].inner { crate::TypeInner::Array { .. } => true, _ => false, }; @@ -635,7 +631,7 @@ impl super::Validator { if base_info.flags.contains(TypeFlags::DATA) { // Currently Naga only supports binding arrays of structs for non-handle types. - match types[base].inner { + match gctx.types[base].inner { crate::TypeInner::Struct { .. } => {} _ => return Err(TypeError::BindingArrayBaseTypeNotStruct(base)), }; From 405413452d9b6cdcd0865a6fc5f866a0deef7cf3 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 11 May 2023 21:39:49 +0200 Subject: [PATCH 1998/2212] Correct type of index and flush the emitter --- src/front/spv/error.rs | 2 ++ src/front/spv/mod.rs | 58 ++++++++++++++++++++++++++++++++++-------- 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index 6c9cf384f..2f9bf2d1b 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -78,6 +78,8 @@ pub enum Error { InvalidAccess(crate::Expression), #[error("invalid access index %{0}")] InvalidAccessIndex(spirv::Word), + #[error("invalid index type %{0}")] + InvalidIndexType(spirv::Word), #[error("invalid binding %{0}")] InvalidBinding(spirv::Word), #[error("invalid global var {0:?}")] diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 14bae2a9c..65423db03 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1678,18 +1678,26 @@ impl> Frontend { let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; let index_lexp = self.lookup_expression.lookup(index_id)?; let index_handle = get_expr_handle!(index_id, index_lexp); + let index_type = self.lookup_type.lookup(index_lexp.type_id)?.handle; let num_components = match ctx.type_arena[root_type_lookup.handle].inner { crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), }; - let make_index = |ctx: &mut BlockContext, index: u32| { - ctx.expressions - .append(crate::Expression::Literal(crate::Literal::U32(index)), span) + let mut make_index = |ctx: &mut BlockContext, index: u32| { + make_index_literal( + ctx, + index, + &mut block, + &mut emitter, + index_type, + index_lexp.type_id, + span, + ) }; - let index_expr = make_index(ctx, 0); + let index_expr = make_index(ctx, 0)?; let mut handle = ctx.expressions.append( crate::Expression::Access { base: root_handle, @@ -1698,7 +1706,7 @@ impl> Frontend { span, ); for index in 1..num_components { - let index_expr = make_index(ctx, index); + let index_expr = make_index(ctx, index)?; let access_expr = ctx.expressions.append( crate::Expression::Access { base: root_handle, @@ -1749,20 +1757,24 @@ impl> Frontend { let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; let index_lexp = self.lookup_expression.lookup(index_id)?; let index_handle = get_expr_handle!(index_id, index_lexp); + let index_type = self.lookup_type.lookup(index_lexp.type_id)?.handle; let num_components = match ctx.type_arena[root_type_lookup.handle].inner { crate::TypeInner::Vector { size, .. } => size as u32, _ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), }; - let make_index = |ctx: &mut BlockContext, index: u32| { - ctx.expressions - .append(crate::Expression::Literal(crate::Literal::U32(index)), span) - }; - let mut components = Vec::with_capacity(num_components as usize); for index in 0..num_components { - let index_expr = make_index(ctx, index); + let index_expr = make_index_literal( + ctx, + index, + &mut block, + &mut emitter, + index_type, + index_lexp.type_id, + span, + )?; let access_expr = ctx.expressions.append( crate::Expression::Access { base: root_handle, @@ -5145,6 +5157,30 @@ impl> Frontend { } } +fn make_index_literal( + ctx: &mut BlockContext, + index: u32, + block: &mut crate::Block, + emitter: &mut super::Emitter, + index_type: Handle, + index_type_id: spirv::Word, + span: crate::Span, +) -> Result, Error> { + block.extend(emitter.finish(ctx.expressions)); + + let literal = match ctx.type_arena[index_type].inner.scalar_kind() { + Some(crate::ScalarKind::Uint) => crate::Literal::U32(index), + Some(crate::ScalarKind::Sint) => crate::Literal::I32(index as i32), + _ => return Err(Error::InvalidIndexType(index_type_id)), + }; + let expr = ctx + .expressions + .append(crate::Expression::Literal(literal), span); + + emitter.start(ctx.expressions); + Ok(expr) +} + pub fn parse_u8_slice(data: &[u8], options: &Options) -> Result { if data.len() % 4 != 0 { return Err(Error::IncompleteData); From 62b287e761b9aefb311287862cbd78c046a9a793 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Fri, 12 May 2023 14:38:50 +0200 Subject: [PATCH 1999/2212] Change type of constant sized arrays to `NonZeroU32` (#2337) --- src/back/glsl/mod.rs | 15 +- src/back/hlsl/conv.rs | 7 +- src/back/hlsl/help.rs | 6 +- src/back/hlsl/storage.rs | 18 +- src/back/hlsl/writer.rs | 8 +- src/back/msl/writer.rs | 30 +- src/back/spv/writer.rs | 8 +- src/back/wgsl/writer.rs | 10 +- src/front/glsl/constants.rs | 29 +- src/front/glsl/context.rs | 7 +- src/front/glsl/functions.rs | 15 +- src/front/glsl/offset.rs | 11 +- src/front/glsl/parser/declarations.rs | 1 - src/front/glsl/parser/expressions.rs | 28 +- src/front/glsl/parser/types.rs | 19 +- src/front/spv/mod.rs | 49 +- src/front/spv/null.rs | 7 +- src/front/wgsl/error.rs | 13 + src/front/wgsl/lower/construction.rs | 22 +- src/front/wgsl/lower/mod.rs | 18 +- src/front/wgsl/mod.rs | 48 +- src/lib.rs | 2 +- src/proc/index.rs | 17 +- src/proc/mod.rs | 6 +- src/valid/compose.rs | 7 +- src/valid/expression.rs | 4 +- src/valid/handles.rs | 39 +- src/valid/type.rs | 51 +- tests/out/ir/access.ron | 16 +- tests/out/msl/globals.msl | 2 +- tests/out/msl/operators.msl | 2 +- tests/out/msl/quad-vert.msl | 2 +- tests/out/spv/access.spvasm | 859 ++++++------ tests/out/spv/array-in-ctor.spvasm | 47 +- tests/out/spv/atomicCompareExchange.spvasm | 359 ++--- tests/out/spv/atomicOps.spvasm | 426 +++--- tests/out/spv/binding-arrays.spvasm | 1095 +++++++-------- tests/out/spv/binding-buffer-arrays.spvasm | 130 +- tests/out/spv/bounds-check-restrict.spvasm | 403 +++--- tests/out/spv/bounds-check-zero.spvasm | 148 +- tests/out/spv/globals.spvasm | 463 +++---- tests/out/spv/interface.compute.spvasm | 119 +- tests/out/spv/interface.fragment.spvasm | 104 +- tests/out/spv/interface.vertex.spvasm | 85 +- .../spv/interface.vertex_two_structs.spvasm | 87 +- tests/out/spv/operators.spvasm | 1213 +++++++++-------- tests/out/spv/padding.spvasm | 143 +- tests/out/spv/policy-mix.spvasm | 255 ++-- tests/out/spv/shadow.spvasm | 713 +++++----- tests/out/spv/workgroup-var-init.spvasm | 126 +- tests/out/wgsl/access.wgsl | 30 +- tests/out/wgsl/array-in-ctor.wgsl | 2 +- tests/out/wgsl/atomicCompareExchange.wgsl | 4 +- tests/out/wgsl/atomicOps.wgsl | 6 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 4 +- tests/out/wgsl/binding-arrays.static.wgsl | 4 +- tests/out/wgsl/binding-arrays.wgsl | 14 +- tests/out/wgsl/binding-buffer-arrays.wgsl | 2 +- tests/out/wgsl/constant-array-size-frag.wgsl | 2 +- tests/out/wgsl/declarations-frag.wgsl | 12 +- tests/out/wgsl/expressions-frag.wgsl | 16 +- .../out/wgsl/global-constant-array-frag.wgsl | 6 +- tests/out/wgsl/globals.wgsl | 8 +- tests/out/wgsl/interface.wgsl | 2 +- tests/out/wgsl/operators.wgsl | 2 +- tests/out/wgsl/padding.wgsl | 2 +- tests/out/wgsl/quad-vert.wgsl | 6 +- tests/out/wgsl/shadow.wgsl | 2 +- tests/out/wgsl/workgroup-var-init.wgsl | 6 +- tests/wgsl-errors.rs | 54 +- 70 files changed, 3675 insertions(+), 3801 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ad76705b8..030ec2191 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -785,20 +785,9 @@ impl<'a, W: Write> Writer<'a, W> { // Write the array size // Writes nothing if `ArraySize::Dynamic` - // Panics if `ArraySize::Constant` has a constant that isn't an sint or uint match size { - crate::ArraySize::Constant(const_handle) => { - match self.module.constants[const_handle].inner { - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(size), - } => write!(self.out, "{size}")?, - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Sint(size), - } => write!(self.out, "{size}")?, - _ => unreachable!(), - } + crate::ArraySize::Constant(size) => { + write!(self.out, "{size}")?; } crate::ArraySize::Dynamic => (), } diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index 69334ecb1..aed2dc0ed 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -53,9 +53,7 @@ impl crate::TypeInner { } Self::Array { base, size, stride } => { let count = match size { - crate::ArraySize::Constant(handle) => { - gctx.constants[handle].to_array_length().unwrap_or(1) - } + crate::ArraySize::Constant(size) => size.get(), // A dynamically-sized array has to have at least one element crate::ArraySize::Dynamic => 1, }; @@ -94,8 +92,7 @@ impl crate::TypeInner { size: crate::ArraySize::Constant(size), .. } => Cow::Owned(format!( - "array{}_{}_", - gctx.constants[size].to_array_length().unwrap(), + "array{size}_{}_", Self::hlsl_type_id(base, gctx, names)? )), crate::TypeInner::Struct { .. } => { diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 51ec5ef4d..c59816550 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -406,8 +406,7 @@ impl<'a, W: Write> super::Writer<'a, W> { size: crate::ArraySize::Constant(size), .. } => { - let count = module.constants[size].to_array_length().unwrap(); - for i in 0..count as usize { + for i in 0..size.get() as usize { write_arg(i, base)?; } } @@ -481,8 +480,7 @@ impl<'a, W: Write> super::Writer<'a, W> { write!(self.out, " {RETURN_VARIABLE_NAME}")?; self.write_array_size(module, base, crate::ArraySize::Constant(size))?; write!(self.out, " = {{ ")?; - let count = module.constants[size].to_array_length().unwrap(); - for i in 0..count { + for i in 0..size.get() { if i != 0 { write!(self.out, ", ")?; } diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index 833a6dce9..d4eeefe3e 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -209,17 +209,15 @@ impl super::Writer<'_, W> { } crate::TypeInner::Array { base, - size: crate::ArraySize::Constant(const_handle), - .. + size: crate::ArraySize::Constant(size), + stride, } => { let constructor = super::help::WrappedConstructor { ty: result_ty.handle().unwrap(), }; self.write_wrapped_constructor_function_name(module, constructor)?; write!(self.out, "(")?; - let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.size(module.to_ctx()); - let iter = (0..count).map(|i| (TypeResolution::Handle(base), stride * i)); + let iter = (0..size.get()).map(|i| (TypeResolution::Handle(base), stride * i)); self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?; write!(self.out, ")")?; } @@ -366,8 +364,8 @@ impl super::Writer<'_, W> { } crate::TypeInner::Array { base, - size: crate::ArraySize::Constant(const_handle), - .. + size: crate::ArraySize::Constant(size), + stride, } => { // first, assign the value to a temporary writeln!(self.out, "{level}{{")?; @@ -375,14 +373,12 @@ impl super::Writer<'_, W> { self.write_value_type(module, &module.types[base].inner)?; let depth = level.next().0; write!(self.out, " {STORE_TEMP_NAME}{depth}")?; - self.write_array_size(module, base, crate::ArraySize::Constant(const_handle))?; + self.write_array_size(module, base, crate::ArraySize::Constant(size))?; write!(self.out, " = ")?; self.write_store_value(module, &value, func_ctx)?; writeln!(self.out, ";")?; // then iterate the stores - let count = module.constants[const_handle].to_array_length().unwrap(); - let stride = module.types[base].inner.size(module.to_ctx()); - for i in 0..count { + for i in 0..size.get() { self.temp_access_chain.push(SubAccess::Offset(i * stride)); let sv = StoreValue::TempIndex { depth, diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index a97b5eb3b..007da0d09 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -824,15 +824,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ) -> BackendResult { write!(self.out, "[")?; - // Write the array size - // Writes nothing if `ArraySize::Dynamic` - // Panics if `ArraySize::Constant` has a constant that isn't an sint or uint match size { - crate::ArraySize::Constant(const_handle) => { - let size = module.constants[const_handle].to_array_length().unwrap(); + crate::ArraySize::Constant(size) => { write!(self.out, "{size}")?; } - crate::ArraySize::Dynamic => {} + crate::ArraySize::Dynamic => unreachable!(), } write!(self.out, "]")?; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 0621bbdf9..2123d0c30 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -221,13 +221,7 @@ impl<'a> Display for TypeContext<'a> { { write!(out, "{NAMESPACE}::array<{base_tyname}, {override_size}>") } else if let crate::ArraySize::Constant(size) = size { - let constant_ctx = ConstantContext { - handle: size, - arena: self.gctx.constants, - names: self.names, - first_time: false, - }; - write!(out, "{NAMESPACE}::array<{base_tyname}, {constant_ctx}>") + write!(out, "{NAMESPACE}::array<{base_tyname}, {size}>") } else { unreachable!("metal requires all arrays be constant sized"); } @@ -2338,15 +2332,12 @@ impl Writer { // to convert from a wrapped struct to a raw array, e.g. // `float gl_ClipDistance1 [[clip_distance]] [1];`. if let crate::TypeInner::Array { - size: crate::ArraySize::Constant(const_handle), + size: crate::ArraySize::Constant(size), .. } = context.module.types[member.ty].inner { - let size = context.module.constants[const_handle] - .to_array_length() - .unwrap(); write!(self.out, "{comma} {{")?; - for j in 0..size { + for j in 0..size.get() { if j != 0 { write!(self.out, ",")?; } @@ -3163,14 +3154,7 @@ impl Writer { }; match size { - crate::ArraySize::Constant(const_handle) => { - let coco = ConstantContext { - handle: const_handle, - arena: &module.constants, - names: &self.names, - first_time: false, - }; - + crate::ArraySize::Constant(size) => { writeln!(self.out, "struct {name} {{")?; writeln!( self.out, @@ -3178,7 +3162,7 @@ impl Writer { back::INDENT, base_name, WRAPPED_ARRAY_FIELD, - coco + size )?; writeln!(self.out, "}};")?; } @@ -3775,9 +3759,9 @@ impl Writer { let array_len = match module.types[ty].inner { crate::TypeInner::Array { - size: crate::ArraySize::Constant(handle), + size: crate::ArraySize::Constant(size), .. - } => module.constants[handle].to_array_length(), + } => Some(size), _ => None, }; let resolved = options.resolve_local_binding(binding, out_mode)?; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 3e3dfc60a..64e27fae1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -990,8 +990,8 @@ impl Writer { let type_id = self.get_type_id(LookupType::Handle(base)); match size { - crate::ArraySize::Constant(const_handle) => { - let length_id = self.constant_ids[const_handle.index()]; + crate::ArraySize::Constant(length) => { + let length_id = self.get_index_constant(length.get()); Instruction::type_array(id, type_id, length_id) } crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), @@ -1000,8 +1000,8 @@ impl Writer { crate::TypeInner::BindingArray { base, size } => { let type_id = self.get_type_id(LookupType::Handle(base)); match size { - crate::ArraySize::Constant(const_handle) => { - let length_id = self.constant_ids[const_handle.index()]; + crate::ArraySize::Constant(length) => { + let length_id = self.get_index_constant(length.get()); Instruction::type_array(id, type_id, length_id) } crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id), diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 93909ab7a..2c2bb34e6 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -503,10 +503,9 @@ impl Writer { // array -- Dynamic array write!(self.out, "array<")?; match size { - crate::ArraySize::Constant(handle) => { + crate::ArraySize::Constant(len) => { self.write_type(module, base)?; - write!(self.out, ",")?; - self.write_constant(module, handle)?; + write!(self.out, ", {len}")?; } crate::ArraySize::Dynamic => { self.write_type(module, base)?; @@ -518,10 +517,9 @@ impl Writer { // More info https://github.com/gpuweb/gpuweb/issues/2105 write!(self.out, "binding_array<")?; match size { - crate::ArraySize::Constant(handle) => { + crate::ArraySize::Constant(len) => { self.write_type(module, base)?; - write!(self.out, ",")?; - self.write_constant(module, handle)?; + write!(self.out, ", {len}")?; } crate::ArraySize::Dynamic => { self.write_type(module, base)?; diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 9f763f9f0..af3cc5396 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -277,7 +277,13 @@ impl<'a> ConstantSolver<'a> { } ConstantInner::Composite { ty, .. } => match self.types[ty].inner { TypeInner::Array { size, .. } => match size { - crate::ArraySize::Constant(constant) => Ok(constant), + crate::ArraySize::Constant(size) => Ok(self.register_constant( + ConstantInner::Scalar { + width: 4, + value: ScalarValue::Uint(size.get() as u64), + }, + span, + )), crate::ArraySize::Dynamic => { Err(ConstantSolvingError::ArrayLengthDynamic) } @@ -602,30 +608,13 @@ impl<'a> ConstantSolver<'a> { } TypeInner::Array { base, size, .. } => { let length = match size { - crate::ArraySize::Constant(handle) => match self.constants[handle].inner { - ConstantInner::Scalar { - value: ScalarValue::Uint(length), - .. - } => length as usize, - ConstantInner::Scalar { - value: ScalarValue::Sint(length), - .. - } => { - if length < 0 { - return Err(ConstantSolvingError::InvalidArrayLengthArg); - } - length as usize - } - _ => return Err(ConstantSolvingError::InvalidArrayLengthArg), - }, + crate::ArraySize::Constant(size) => size.get(), crate::ArraySize::Dynamic => { return Err(ConstantSolvingError::ArrayLengthDynamic) } }; let element = self.register_zero_constant(base, span)?; - let components = std::iter::repeat(element) - .take(length as u8 as usize) - .collect(); + let components = std::iter::repeat(element).take(length as usize).collect(); ConstantInner::Composite { ty, components } } TypeInner::Struct { ref members, .. } => { diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 4f3c27b55..93b7e03b6 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -1359,8 +1359,11 @@ impl Context { size: crate::ArraySize::Constant(size), .. } => { - let mut array_length = - self.add_expression(Expression::Constant(size), meta, body); + let mut array_length = self.add_expression( + Expression::Literal(Literal::U32(size.get())), + meta, + body, + ); self.forced_conversion( frontend, &mut array_length, diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 355b1453b..b7b4be8a6 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1316,9 +1316,12 @@ impl Frontend { ), ) { match self.module.types[ty].inner { + // TODO: Better error reporting + // right now we just don't walk the array if the size isn't known at + // compile time and let validation catch it TypeInner::Array { base, - size: crate::ArraySize::Constant(constant), + size: crate::ArraySize::Constant(size), .. } => { let mut location = match binding { @@ -1326,14 +1329,6 @@ impl Frontend { crate::Binding::BuiltIn(_) => return, }; - // TODO: Better error reporting - // right now we just don't walk the array if the size isn't known at - // compile time and let validation catch it - let size = match self.module.constants[constant].to_array_length() { - Some(val) => val, - None => return f(name, pointer, ty, binding, expressions), - }; - let interpolation = self.module.types[base] .inner @@ -1343,7 +1338,7 @@ impl Frontend { _ => crate::Interpolation::Flat, }); - for index in 0..size { + for index in 0..size.get() { let member_pointer = expressions.append( Expression::AccessIndex { base: pointer, diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index d7950489c..21481372b 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -16,7 +16,7 @@ use super::{ error::{Error, ErrorKind}, Span, }; -use crate::{proc::Alignment, Arena, Constant, Handle, Type, TypeInner, UniqueArena}; +use crate::{proc::Alignment, Handle, Type, TypeInner, UniqueArena}; /// Struct with information needed for defining a struct member. /// @@ -43,7 +43,6 @@ pub fn calculate_offset( meta: Span, layout: StructLayout, types: &mut UniqueArena, - constants: &Arena, errors: &mut Vec, ) -> TypeAlignSpan { // When using the std430 storage layout, shader storage blocks will be laid out in buffer storage @@ -68,7 +67,7 @@ pub fn calculate_offset( // to rules (1), (2), and (3), and rounded up to the base alignment of a vec4. // TODO: Matrices array TypeInner::Array { base, size, .. } => { - let info = calculate_offset(base, meta, layout, types, constants, errors); + let info = calculate_offset(base, meta, layout, types, errors); let name = types[ty].name.clone(); @@ -81,9 +80,7 @@ pub fn calculate_offset( }; let span = match size { - crate::ArraySize::Constant(s) => { - constants[s].to_array_length().unwrap_or(1) * stride - } + crate::ArraySize::Constant(size) => size.get() * stride, crate::ArraySize::Dynamic => stride, }; @@ -135,7 +132,7 @@ pub fn calculate_offset( let name = types[ty].name.clone(); for member in members.iter_mut() { - let info = calculate_offset(member.ty, meta, layout, types, constants, errors); + let info = calculate_offset(member.ty, meta, layout, types, errors); let member_alignment = info.align; span = member_alignment.round_up(span); diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 9085469dd..79bf1bc8c 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -642,7 +642,6 @@ impl<'source> ParsingContext<'source> { meta, layout, &mut frontend.module.types, - &frontend.module.constants, &mut frontend.errors, ); diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 72b5a2ddc..7e47b2eea 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -1,3 +1,5 @@ +use std::num::NonZeroU32; + use crate::{ front::glsl::{ ast::{FunctionCall, FunctionCallKind, HirExpr, HirExprKind}, @@ -7,8 +9,7 @@ use crate::{ token::{Token, TokenValue}, Error, Frontend, Result, Span, }, - ArraySize, BinaryOperator, Block, Constant, ConstantInner, Handle, Literal, ScalarValue, Type, - TypeInner, UnaryOperator, + ArraySize, BinaryOperator, Block, Handle, Literal, Type, TypeInner, UnaryOperator, }; impl<'source> ParsingContext<'source> { @@ -137,24 +138,23 @@ impl<'source> ParsingContext<'source> { { let span = frontend.module.types.get_span(handle); - let constant = frontend.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Uint(args.len() as u64), - }, - }, - Span::default(), - ); + let size = u32::try_from(args.len()) + .ok() + .and_then(NonZeroU32::new) + .ok_or(Error { + kind: ErrorKind::SemanticError( + "There must be at least one argument".into(), + ), + meta, + })?; + handle = frontend.module.types.insert( Type { name: None, inner: TypeInner::Array { stride, base, - size: ArraySize::Constant(constant), + size: ArraySize::Constant(size), }, }, span, diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 5c92b4f3d..4761e8bc5 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -1,3 +1,5 @@ +use std::num::NonZeroU32; + use crate::{ front::glsl::{ ast::{QualifierKey, QualifierValue, StorageQualifier, StructLayout, TypeQualifiers}, @@ -37,20 +39,13 @@ impl<'source> ParsingContext<'source> { ArraySize::Dynamic } else { let (value, constant_span) = self.parse_uint_constant(frontend)?; - let constant = frontend.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(value as u64), - }, - }, - constant_span, - ); + let size = NonZeroU32::new(value).ok_or(Error { + kind: ErrorKind::SemanticError("Array size must be greater than zero".into()), + meta: constant_span, + })?; let end_span = self.expect(frontend, TokenValue::RightBracket)?.meta; span.subsume(end_span); - ArraySize::Constant(constant) + ArraySize::Constant(size) }; frontend.layouter.update(frontend.module.to_ctx()).unwrap(); diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 65423db03..143af4a43 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1164,7 +1164,6 @@ impl> Frontend { selections: &[spirv::Word], type_arena: &UniqueArena, expressions: &mut Arena, - constants: &Arena, span: crate::Span, ) -> Result, Error> { let selection = match selections.first() { @@ -1173,6 +1172,7 @@ impl> Frontend { }; let root_span = expressions.get_span(root_expr); let root_lookup = self.lookup_type.lookup(root_type_id)?; + let (count, child_type_id) = match type_arena[root_lookup.handle].inner { crate::TypeInner::Struct { ref members, .. } => { let child_member = self @@ -1183,15 +1183,7 @@ impl> Frontend { } crate::TypeInner::Array { size, .. } => { let size = match size { - crate::ArraySize::Constant(handle) => match constants[handle] { - crate::Constant { - specialization: Some(_), - .. - } => return Err(Error::UnsupportedType(root_lookup.handle)), - ref unspecialized => unspecialized - .to_array_length() - .ok_or(Error::InvalidArraySize(handle))?, - }, + crate::ArraySize::Constant(size) => size.get(), // A runtime sized array is not a composite type crate::ArraySize::Dynamic => { return Err(Error::InvalidAccessType(root_type_id)) @@ -1232,7 +1224,6 @@ impl> Frontend { &selections[1..], type_arena, expressions, - constants, span, )?; @@ -1892,7 +1883,6 @@ impl> Frontend { &selections, ctx.type_arena, ctx.expressions, - ctx.const_arena, span, )?; @@ -3507,20 +3497,12 @@ impl> Frontend { let semantics_id = self.next()?; let exec_scope_const = self.lookup_constant.lookup(exec_scope_id)?; let semantics_const = self.lookup_constant.lookup(semantics_id)?; - let exec_scope = match ctx.const_arena[exec_scope_const.handle].inner { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(raw), - width: _, - } => raw as u32, - _ => return Err(Error::InvalidBarrierScope(exec_scope_id)), - }; - let semantics = match ctx.const_arena[semantics_const.handle].inner { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(raw), - width: _, - } => raw as u32, - _ => return Err(Error::InvalidBarrierMemorySemantics(semantics_id)), - }; + + let exec_scope = resolve_constant(ctx.gctx(), exec_scope_const.handle) + .ok_or(Error::InvalidBarrierScope(exec_scope_id))?; + let semantics = resolve_constant(ctx.gctx(), semantics_const.handle) + .ok_or(Error::InvalidBarrierMemorySemantics(semantics_id))?; + if exec_scope == spirv::Scope::Workgroup as u32 { let mut flags = crate::Barrier::empty(); flags.set( @@ -4396,6 +4378,10 @@ impl> Frontend { let length_id = self.next()?; let length_const = self.lookup_constant.lookup(length_id)?; + let size = resolve_constant(module.to_ctx(), length_const.handle) + .and_then(NonZeroU32::new) + .ok_or(Error::InvalidArraySize(length_const.handle))?; + let decor = self.future_decor.remove(&id).unwrap_or_default(); let base = self.lookup_type.lookup(type_id)?.handle; @@ -4437,12 +4423,12 @@ impl> Frontend { { crate::TypeInner::BindingArray { base, - size: crate::ArraySize::Constant(length_const.handle), + size: crate::ArraySize::Constant(size), } } else { crate::TypeInner::Array { base, - size: crate::ArraySize::Constant(length_const.handle), + size: crate::ArraySize::Constant(size), stride: match decor.array_stride { Some(stride) => stride.get(), None => self.layouter[base].to_stride(), @@ -5181,6 +5167,13 @@ fn make_index_literal( Ok(expr) } +fn resolve_constant( + gctx: crate::proc::GlobalCtx, + constant: Handle, +) -> Option { + gctx.constants[constant].to_array_length() +} + pub fn parse_u8_slice(data: &[u8], options: &Options) -> Result { if data.len() % 4 != 0 { return Err(Error::IncompleteData); diff --git a/src/front/spv/null.rs b/src/front/spv/null.rs index 85350c563..eb0b418aa 100644 --- a/src/front/spv/null.rs +++ b/src/front/spv/null.rs @@ -84,12 +84,9 @@ pub fn generate_null_constant( } crate::TypeInner::Array { base, - size: crate::ArraySize::Constant(handle), + size: crate::ArraySize::Constant(size), .. } => { - let size = constant_arena[handle] - .to_array_length() - .ok_or(Error::InvalidArraySize(handle))?; let inner = generate_null_constant(base, type_arena, constant_arena, span)?; let value = constant_arena.fetch_or_append( crate::Constant { @@ -101,7 +98,7 @@ pub fn generate_null_constant( ); crate::ConstantInner::Composite { ty, - components: vec![value; size as usize], + components: vec![value; size.get() as usize], } } ref other => { diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index 82f7c609e..ed3e5318b 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -240,6 +240,8 @@ pub enum Error<'a> { }, FunctionReturnsVoid(Span), Other, + ExpectedArraySize(Span), + NonPositiveArrayLength(Span), } impl<'a> Error<'a> { @@ -685,6 +687,17 @@ impl<'a> Error<'a> { labels: vec![], notes: vec![], }, + Error::ExpectedArraySize(span) => ParseError { + message: "array element count must resolve to an integer scalar (u32 or i32)" + .to_string(), + labels: vec![(span, "must resolve to u32/i32".into())], + notes: vec![], + }, + Error::NonPositiveArrayLength(span) => ParseError { + message: "array element count must be greater than zero".to_string(), + labels: vec![(span, "must be positive".into())], + notes: vec![], + }, } } } diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index c1457b0d9..8d7a5cdc2 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -1,3 +1,5 @@ +use std::num::NonZeroU32; + use crate::front::wgsl::parse::ast; use crate::{Handle, Span}; @@ -456,19 +458,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let base = ctx.register_type(components[0])?; - let size = crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(components.len() as _), - }, - }; - let inner = crate::TypeInner::Array { base, size: crate::ArraySize::Constant( - ctx.module.constants.fetch_or_append(size, Span::UNDEFINED), + NonZeroU32::new(u32::try_from(components.len()).unwrap()).unwrap(), ), stride: { self.layouter.update(ctx.module.to_ctx()).unwrap(); @@ -638,7 +631,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let base = self.resolve_ast_type(base, ctx.reborrow())?; let size = match size { ast::ArraySize::Constant(expr) => { - crate::ArraySize::Constant(self.constant(expr, ctx.reborrow())?) + let span = ctx.ast_expressions.get_span(expr); + let constant = self.constant(expr, ctx.reborrow())?; + let size = ctx.module.constants[constant] + .to_array_length() + .ok_or(Error::ExpectedArraySize(span))?; + let size = + NonZeroU32::new(size).ok_or(Error::NonPositiveArrayLength(span))?; + crate::ArraySize::Constant(size) } ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, }; diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 6e1d2f24e..fc3f6a136 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1,3 +1,5 @@ +use std::num::NonZeroU32; + use crate::front::wgsl::error::{Error, ExpectedToken, InvalidAssignmentType}; use crate::front::wgsl::index::Index; use crate::front::wgsl::parse::number::Number; @@ -2160,8 +2162,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { base, size: match size { ast::ArraySize::Constant(constant) => { + let span = ctx.ast_expressions.get_span(constant); let constant = self.constant(constant, ctx.reborrow())?; - crate::ArraySize::Constant(constant) + let size = ctx.module.constants[constant] + .to_array_length() + .ok_or(Error::ExpectedArraySize(span))?; + let size = + NonZeroU32::new(size).ok_or(Error::NonPositiveArrayLength(span))?; + crate::ArraySize::Constant(size) } ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, }, @@ -2187,8 +2195,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { base, size: match size { ast::ArraySize::Constant(constant) => { + let span = ctx.ast_expressions.get_span(constant); let constant = self.constant(constant, ctx.reborrow())?; - crate::ArraySize::Constant(constant) + let size = ctx.module.constants[constant] + .to_array_length() + .ok_or(Error::ExpectedArraySize(span))?; + let size = + NonZeroU32::new(size).ok_or(Error::NonPositiveArrayLength(span))?; + crate::ArraySize::Constant(size) } ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, }, diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index a64f1f8f1..b60f6fe65 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -133,24 +133,7 @@ impl crate::TypeInner { let member_type = &gctx.types[base]; let base = member_type.name.as_deref().unwrap_or("unknown"); match size { - crate::ArraySize::Constant(size) => { - let constant = &gctx.constants[size]; - let size = constant - .name - .clone() - .unwrap_or_else(|| match constant.inner { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(size), - .. - } => size.to_string(), - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Sint(size), - .. - } => size.to_string(), - _ => "?".to_string(), - }); - format!("array<{base}, {size}>") - } + crate::ArraySize::Constant(size) => format!("array<{base}, {size}>"), crate::ArraySize::Dynamic => format!("array<{base}>"), } } @@ -206,10 +189,7 @@ impl crate::TypeInner { let member_type = &gctx.types[base]; let base = member_type.name.as_deref().unwrap_or("unknown"); match size { - crate::ArraySize::Constant(size) => { - let size = gctx.constants[size].name.as_deref().unwrap_or("unknown"); - format!("binding_array<{base}, {size}>") - } + crate::ArraySize::Constant(size) => format!("binding_array<{base}, {size}>"), crate::ArraySize::Dynamic => format!("binding_array<{base}>"), } } @@ -220,19 +200,9 @@ impl crate::TypeInner { mod type_inner_tests { #[test] fn to_wgsl() { + use std::num::NonZeroU32; + let mut types = crate::UniqueArena::new(); - let mut constants = crate::Arena::new(); - let c = constants.append( - crate::Constant { - name: Some("C".to_string()), - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(32), - }, - }, - Default::default(), - ); let mytype1 = types.insert( crate::Type { @@ -257,14 +227,14 @@ mod type_inner_tests { let gctx = crate::proc::GlobalCtx { types: &types, - constants: &constants, + constants: &crate::Arena::new(), }; let array = crate::TypeInner::Array { base: mytype1, stride: 4, - size: crate::ArraySize::Constant(c), + size: crate::ArraySize::Constant(unsafe { NonZeroU32::new_unchecked(32) }), }; - assert_eq!(array.to_wgsl(gctx), "array"); + assert_eq!(array.to_wgsl(gctx), "array"); let mat = crate::TypeInner::Matrix { rows: crate::VectorSize::Quad, @@ -307,9 +277,9 @@ mod type_inner_tests { let array = crate::TypeInner::BindingArray { base: mytype1, - size: crate::ArraySize::Constant(c), + size: crate::ArraySize::Constant(unsafe { NonZeroU32::new_unchecked(32) }), }; - assert_eq!(array.to_wgsl(gctx), "binding_array"); + assert_eq!(array.to_wgsl(gctx), "binding_array"); } } diff --git a/src/lib.rs b/src/lib.rs index 1cf4c8b1a..e0645a30f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -413,7 +413,7 @@ pub enum ScalarKind { #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum ArraySize { /// The array size is constant. - Constant(Handle), + Constant(std::num::NonZeroU32), /// The array size can change at runtime. Dynamic, } diff --git a/src/proc/index.rs b/src/proc/index.rs index aaf8ee11b..0ccdfdca5 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -416,23 +416,12 @@ pub enum IndexableLength { } impl crate::ArraySize { - pub fn to_indexable_length( + pub const fn to_indexable_length( self, - module: &crate::Module, + _module: &crate::Module, ) -> Result { Ok(match self { - Self::Constant(k) => { - let constant = &module.constants[k]; - if constant.specialization.is_some() { - // Specializable constants are not supported as array lengths. - // See valid::TypeError::UnsupportedSpecializedArrayLength. - return Err(IndexableLengthError::InvalidArrayLength(k)); - } - let length = constant - .to_array_length() - .ok_or(IndexableLengthError::InvalidArrayLength(k))?; - IndexableLength::Known(length) - } + Self::Constant(length) => IndexableLength::Known(length.get()), Self::Dynamic => IndexableLength::Dynamic, }) } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 80ae567ee..ddcca263c 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -199,7 +199,7 @@ impl super::TypeInner { } /// Get the size of this type. - pub fn size(&self, gctx: GlobalCtx) -> u32 { + pub fn size(&self, _gctx: GlobalCtx) -> u32 { match *self { Self::Scalar { kind: _, width } | Self::Atomic { kind: _, width } => width as u32, Self::Vector { @@ -220,9 +220,7 @@ impl super::TypeInner { stride, } => { let count = match size { - super::ArraySize::Constant(handle) => { - gctx.constants[handle].to_array_length().unwrap_or(1) - } + super::ArraySize::Constant(count) => count.get(), // A dynamically-sized array has to have at least one element super::ArraySize::Dynamic => 1, }; diff --git a/src/valid/compose.rs b/src/valid/compose.rs index a7a961979..87bc2352c 100644 --- a/src/valid/compose.rs +++ b/src/valid/compose.rs @@ -80,13 +80,12 @@ pub fn validate_compose( } Ti::Array { base, - size: crate::ArraySize::Constant(handle), + size: crate::ArraySize::Constant(count), stride: _, } => { - let count = gctx.constants[handle].to_array_length().unwrap(); - if count as usize != component_resolutions.len() { + if count.get() as usize != component_resolutions.len() { return Err(ComposeError::ComponentCount { - expected: count, + expected: count.get(), given: component_resolutions.len() as u32, }); } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index b5cea3194..eb39a84ea 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -244,9 +244,9 @@ impl super::Validator { } => size as u32, Ti::Matrix { columns, .. } => columns as u32, Ti::Array { - size: crate::ArraySize::Constant(handle), + size: crate::ArraySize::Constant(len), .. - } => module.constants[handle].to_array_length().unwrap(), + } => len.get(), Ti::Array { .. } | Ti::BindingArray { .. } => u32::MAX, // can't statically know, but need run-time checks Ti::Pointer { base, .. } if top_level => { resolve_index_limit(module, top, &module.types[base].inner, false)? diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 24e485277..22dadaf60 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -9,7 +9,7 @@ use crate::{ use crate::{Arena, UniqueArena}; #[cfg(feature = "validate")] -use super::{TypeError, ValidationError}; +use super::ValidationError; #[cfg(feature = "validate")] use std::{convert::TryInto, hash::Hash, num::NonZeroU32}; @@ -44,33 +44,7 @@ impl super::Validator { // NOTE: Types being first is important. All other forms of validation depend on this. for (this_handle, ty) in types.iter() { - let &crate::Type { - ref name, - ref inner, - } = ty; - - let validate_array_size = |size| { - match size { - crate::ArraySize::Constant(constant) => { - let &crate::Constant { - name: _, - specialization: _, - ref inner, - } = constants.try_get(constant)?; - if !matches!(inner, &crate::ConstantInner::Scalar { .. }) { - return Err(ValidationError::Type { - handle: this_handle, - name: name.clone().unwrap_or_default(), - source: TypeError::InvalidArraySizeConstant(constant), - }); - } - } - crate::ArraySize::Dynamic => (), - }; - Ok(this_handle) - }; - - match *inner { + match ty.inner { crate::TypeInner::Scalar { .. } | crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } @@ -83,14 +57,9 @@ impl super::Validator { crate::TypeInner::Pointer { base, space: _ } => { this_handle.check_dep(base)?; } - crate::TypeInner::Array { - base, - size, - stride: _, - } - | crate::TypeInner::BindingArray { base, size } => { + crate::TypeInner::Array { base, .. } + | crate::TypeInner::BindingArray { base, .. } => { this_handle.check_dep(base)?; - validate_array_size(size)?; } crate::TypeInner::Struct { ref members, diff --git a/src/valid/type.rs b/src/valid/type.rs index e122fec44..db7eec92a 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -104,12 +104,8 @@ pub enum TypeError { InvalidData(Handle), #[error("Base type {0:?} for the array is invalid")] InvalidArrayBaseType(Handle), - #[error("The constant {0:?} can not be used for an array size")] - InvalidArraySizeConstant(Handle), #[error("The constant {0:?} is specialized, and cannot be used as an array size")] UnsupportedSpecializedArrayLength(Handle), - #[error("Array type {0:?} must have a length of one or more")] - NonPositiveArrayLength(Handle), #[error("Array stride {stride} does not match the expected {expected}")] InvalidArrayStride { stride: u32, expected: u32 }, #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")] @@ -414,52 +410,7 @@ impl super::Validator { }; let type_info_mask = match size { - crate::ArraySize::Constant(const_handle) => { - let constant = &gctx.constants[const_handle]; - let length_is_positive = match *constant { - crate::Constant { - specialization: Some(_), - .. - } => { - // Many of our back ends don't seem to support - // specializable array lengths. If you want to try to make - // this work, be sure to address all uses of - // `Constant::to_array_length`, which ignores - // specialization. - return Err(TypeError::UnsupportedSpecializedArrayLength( - const_handle, - )); - } - crate::Constant { - inner: - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(length), - }, - .. - } => length > 0, - // Accept a signed integer size to avoid - // requiring an explicit uint - // literal. Type inference should make - // this unnecessary. - crate::Constant { - inner: - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Sint(length), - }, - .. - } => length > 0, - _ => { - log::warn!("Array size {:?}", constant); - return Err(TypeError::InvalidArraySizeConstant(const_handle)); - } - }; - - if !length_is_positive { - return Err(TypeError::NonPositiveArrayLength(const_handle)); - } - + crate::ArraySize::Constant(_) => { TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 417a706ff..41d5cb916 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -82,7 +82,7 @@ name: None, inner: Array( base: 7, - size: Constant(5), + size: Constant(2), stride: 16, ), ), @@ -97,7 +97,7 @@ name: None, inner: Array( base: 9, - size: Constant(6), + size: Constant(10), stride: 4, ), ), @@ -113,7 +113,7 @@ name: None, inner: Array( base: 11, - size: Constant(5), + size: Constant(2), stride: 8, ), ), @@ -219,7 +219,7 @@ name: None, inner: Array( base: 19, - size: Constant(5), + size: Constant(2), stride: 32, ), ), @@ -255,7 +255,7 @@ name: None, inner: Array( base: 22, - size: Constant(6), + size: Constant(10), stride: 4, ), ), @@ -263,7 +263,7 @@ name: None, inner: Array( base: 24, - size: Constant(8), + size: Constant(5), stride: 40, ), ), @@ -290,7 +290,7 @@ name: None, inner: Array( base: 3, - size: Constant(8), + size: Constant(5), stride: 4, ), ), @@ -321,7 +321,7 @@ name: None, inner: Array( base: 26, - size: Constant(5), + size: Constant(2), stride: 16, ), ), diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index b2f4af0fc..7ebf5c9be 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -10,7 +10,7 @@ struct _mslBufferSizes { constexpr constant bool Foo_1 = true; struct type_2 { - float inner[10u]; + float inner[10]; }; struct FooStruct { metal::packed_float3 v3_; diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 81f56ff3a..18a3d256c 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -12,7 +12,7 @@ struct type_13 { Foo inner[3]; }; struct type_14 { - int inner[4u]; + int inner[4]; }; constant metal::float4 v_f32_one = {1.0, 1.0, 1.0, 1.0}; constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0}; diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index 918396a08..d5e62774e 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -5,7 +5,7 @@ using metal::uint; struct type_5 { - float inner[1u]; + float inner[1]; }; struct gl_PerVertex { metal::float4 gl_Position; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 80e248040..e3a2b7564 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 326 +; Bound: 327 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %238 "foo_vert" %233 %236 -OpEntryPoint Fragment %286 "foo_frag" %285 -OpEntryPoint GLCompute %306 "assign_through_ptr" %309 -OpExecutionMode %286 OriginUpperLeft -OpExecutionMode %306 LocalSize 1 1 1 +OpEntryPoint Vertex %241 "foo_vert" %236 %239 +OpEntryPoint Fragment %287 "foo_frag" %286 +OpEntryPoint GLCompute %307 "assign_through_ptr" %310 +OpExecutionMode %287 OriginUpperLeft +OpExecutionMode %307 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %12 0 "a" OpMemberName %12 1 "b" @@ -18,92 +18,92 @@ OpMemberName %12 2 "c" OpName %12 "GlobalConst" OpMemberName %13 0 "value" OpName %13 "AlignedWrapper" -OpMemberName %24 0 "_matrix" -OpMemberName %24 1 "matrix_array" -OpMemberName %24 2 "atom" -OpMemberName %24 3 "atom_arr" -OpMemberName %24 4 "arr" -OpMemberName %24 5 "data" -OpName %24 "Bar" -OpMemberName %26 0 "m" -OpName %26 "Baz" -OpMemberName %30 0 "am" -OpName %30 "MatCx2InArray" -OpName %43 "global_const" -OpName %45 "bar" -OpName %47 "baz" -OpName %50 "qux" -OpName %53 "nested_mat_cx2" -OpName %56 "val" -OpName %57 "idx" -OpName %60 "t" -OpName %64 "test_matrix_within_struct_accesses" -OpName %134 "idx" -OpName %136 "t" -OpName %140 "test_matrix_within_array_within_struct_accesses" -OpName %199 "foo" -OpName %200 "read_from_private" -OpName %205 "a" -OpName %206 "test_arr_as_arg" -OpName %214 "p" -OpName %215 "assign_through_ptr_fn" -OpName %220 "foo" -OpName %221 "assign_array_through_ptr_fn" -OpName %227 "foo" -OpName %229 "c2" -OpName %233 "vi" -OpName %238 "foo_vert" -OpName %286 "foo_frag" -OpName %303 "arr" -OpName %306 "assign_through_ptr" +OpMemberName %26 0 "_matrix" +OpMemberName %26 1 "matrix_array" +OpMemberName %26 2 "atom" +OpMemberName %26 3 "atom_arr" +OpMemberName %26 4 "arr" +OpMemberName %26 5 "data" +OpName %26 "Bar" +OpMemberName %28 0 "m" +OpName %28 "Baz" +OpMemberName %32 0 "am" +OpName %32 "MatCx2InArray" +OpName %46 "global_const" +OpName %48 "bar" +OpName %50 "baz" +OpName %53 "qux" +OpName %56 "nested_mat_cx2" +OpName %59 "val" +OpName %60 "idx" +OpName %63 "t" +OpName %67 "test_matrix_within_struct_accesses" +OpName %137 "idx" +OpName %139 "t" +OpName %143 "test_matrix_within_array_within_struct_accesses" +OpName %202 "foo" +OpName %203 "read_from_private" +OpName %208 "a" +OpName %209 "test_arr_as_arg" +OpName %217 "p" +OpName %218 "assign_through_ptr_fn" +OpName %223 "foo" +OpName %224 "assign_array_through_ptr_fn" +OpName %230 "foo" +OpName %232 "c2" +OpName %236 "vi" +OpName %241 "foo_vert" +OpName %287 "foo_frag" +OpName %304 "arr" +OpName %307 "assign_through_ptr" OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpMemberDecorate %12 2 Offset 28 OpMemberDecorate %13 0 Offset 0 OpDecorate %19 ArrayStride 16 -OpDecorate %20 ArrayStride 4 -OpDecorate %22 ArrayStride 8 -OpDecorate %23 ArrayStride 8 -OpMemberDecorate %24 0 Offset 0 -OpMemberDecorate %24 0 ColMajor -OpMemberDecorate %24 0 MatrixStride 16 -OpMemberDecorate %24 1 Offset 64 -OpMemberDecorate %24 1 ColMajor -OpMemberDecorate %24 1 MatrixStride 8 -OpMemberDecorate %24 2 Offset 96 -OpMemberDecorate %24 3 Offset 100 -OpMemberDecorate %24 4 Offset 144 -OpMemberDecorate %24 5 Offset 160 +OpDecorate %21 ArrayStride 4 +OpDecorate %24 ArrayStride 8 +OpDecorate %25 ArrayStride 8 OpMemberDecorate %26 0 Offset 0 OpMemberDecorate %26 0 ColMajor -OpMemberDecorate %26 0 MatrixStride 8 -OpDecorate %29 ArrayStride 32 -OpMemberDecorate %30 0 Offset 0 -OpMemberDecorate %30 0 ColMajor -OpMemberDecorate %30 0 MatrixStride 8 -OpDecorate %32 ArrayStride 4 -OpDecorate %33 ArrayStride 40 -OpDecorate %36 ArrayStride 4 -OpDecorate %39 ArrayStride 16 -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 0 -OpDecorate %24 Block -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 1 -OpDecorate %48 Block -OpMemberDecorate %48 0 Offset 0 +OpMemberDecorate %26 0 MatrixStride 16 +OpMemberDecorate %26 1 Offset 64 +OpMemberDecorate %26 1 ColMajor +OpMemberDecorate %26 1 MatrixStride 8 +OpMemberDecorate %26 2 Offset 96 +OpMemberDecorate %26 3 Offset 100 +OpMemberDecorate %26 4 Offset 144 +OpMemberDecorate %26 5 Offset 160 +OpMemberDecorate %28 0 Offset 0 +OpMemberDecorate %28 0 ColMajor +OpMemberDecorate %28 0 MatrixStride 8 +OpDecorate %31 ArrayStride 32 +OpMemberDecorate %32 0 Offset 0 +OpMemberDecorate %32 0 ColMajor +OpMemberDecorate %32 0 MatrixStride 8 +OpDecorate %34 ArrayStride 4 +OpDecorate %35 ArrayStride 40 +OpDecorate %39 ArrayStride 4 +OpDecorate %42 ArrayStride 16 +OpDecorate %48 DescriptorSet 0 +OpDecorate %48 Binding 0 +OpDecorate %26 Block OpDecorate %50 DescriptorSet 0 -OpDecorate %50 Binding 2 +OpDecorate %50 Binding 1 OpDecorate %51 Block OpMemberDecorate %51 0 Offset 0 OpDecorate %53 DescriptorSet 0 -OpDecorate %53 Binding 3 +OpDecorate %53 Binding 2 OpDecorate %54 Block OpMemberDecorate %54 0 Offset 0 -OpDecorate %233 BuiltIn VertexIndex -OpDecorate %236 BuiltIn Position -OpDecorate %285 Location 0 -OpDecorate %309 BuiltIn LocalInvocationId +OpDecorate %56 DescriptorSet 0 +OpDecorate %56 Binding 3 +OpDecorate %57 Block +OpMemberDecorate %57 0 Offset 0 +OpDecorate %236 BuiltIn VertexIndex +OpDecorate %239 BuiltIn Position +OpDecorate %286 Location 0 +OpDecorate %310 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -121,380 +121,381 @@ OpDecorate %309 BuiltIn LocalInvocationId %14 = OpTypeMatrix %15 4 %18 = OpTypeVector %16 2 %17 = OpTypeMatrix %18 2 -%19 = OpTypeArray %17 %7 -%20 = OpTypeArray %6 %8 -%21 = OpTypeVector %4 2 -%22 = OpTypeArray %21 %7 -%23 = OpTypeRuntimeArray %13 -%24 = OpTypeStruct %14 %19 %6 %20 %22 %23 -%25 = OpTypeMatrix %18 3 -%26 = OpTypeStruct %25 -%27 = OpTypeVector %6 2 -%28 = OpTypeMatrix %18 4 -%29 = OpTypeArray %28 %7 -%30 = OpTypeStruct %29 -%31 = OpTypePointer Function %16 -%32 = OpTypeArray %16 %8 -%33 = OpTypeArray %32 %10 -%34 = OpTypeVector %16 4 -%35 = OpTypePointer StorageBuffer %6 -%36 = OpTypeArray %6 %10 -%37 = OpTypeVector %6 4 -%38 = OpTypePointer Workgroup %4 -%39 = OpTypeArray %34 %7 -%40 = OpTypePointer Function %39 -%41 = OpConstantComposite %11 %3 %3 %3 -%42 = OpConstantComposite %12 %3 %41 %5 -%44 = OpTypePointer Private %12 -%43 = OpVariable %44 Private %42 -%46 = OpTypePointer StorageBuffer %24 -%45 = OpVariable %46 StorageBuffer -%48 = OpTypeStruct %26 -%49 = OpTypePointer Uniform %48 -%47 = OpVariable %49 Uniform -%51 = OpTypeStruct %27 -%52 = OpTypePointer StorageBuffer %51 -%50 = OpVariable %52 StorageBuffer -%54 = OpTypeStruct %30 -%55 = OpTypePointer Uniform %54 -%53 = OpVariable %55 Uniform -%56 = OpVariable %38 Workgroup -%58 = OpTypePointer Function %6 -%59 = OpConstantNull %6 -%61 = OpTypePointer Function %26 -%62 = OpConstantNull %26 -%65 = OpTypeFunction %2 -%66 = OpTypePointer Uniform %26 -%68 = OpConstant %16 1.0 -%69 = OpConstant %16 2.0 -%70 = OpConstant %16 3.0 -%71 = OpConstant %16 6.0 -%72 = OpConstant %16 5.0 -%73 = OpConstant %16 4.0 -%74 = OpConstant %16 9.0 -%75 = OpConstant %16 90.0 -%76 = OpConstant %16 10.0 -%77 = OpConstant %16 20.0 -%78 = OpConstant %16 30.0 -%79 = OpConstant %16 40.0 -%83 = OpTypePointer Uniform %25 -%86 = OpTypePointer Uniform %18 -%92 = OpTypePointer Uniform %16 -%93 = OpConstant %4 1 -%113 = OpTypePointer Function %25 -%119 = OpTypePointer Function %18 -%125 = OpTypePointer Function %16 -%135 = OpConstantNull %6 -%137 = OpTypePointer Function %30 -%138 = OpConstantNull %30 -%141 = OpTypePointer Uniform %30 -%143 = OpConstantNull %29 -%144 = OpConstantNull %29 -%145 = OpConstant %16 8.0 -%146 = OpConstant %16 7.0 -%150 = OpTypePointer Uniform %29 -%153 = OpTypePointer Uniform %28 -%176 = OpTypePointer Function %29 -%178 = OpTypePointer Function %28 -%201 = OpTypeFunction %16 %31 -%207 = OpTypeFunction %16 %33 -%208 = OpConstant %6 4 -%209 = OpConstant %6 9 -%216 = OpTypeFunction %2 %38 -%217 = OpConstant %4 42 -%222 = OpTypeFunction %2 %40 -%228 = OpConstantNull %16 -%230 = OpTypePointer Function %36 -%231 = OpConstantNull %36 -%234 = OpTypePointer Input %4 -%233 = OpVariable %234 Input -%237 = OpTypePointer Output %34 -%236 = OpVariable %237 Output -%240 = OpTypePointer StorageBuffer %27 -%243 = OpConstant %16 0.0 -%244 = OpConstant %4 3 -%245 = OpConstant %4 2 -%246 = OpConstant %6 3 -%247 = OpConstant %6 42 -%248 = OpConstantNull %33 -%253 = OpTypePointer StorageBuffer %14 -%256 = OpTypePointer StorageBuffer %22 -%257 = OpConstant %4 4 -%260 = OpTypePointer StorageBuffer %15 -%261 = OpTypePointer StorageBuffer %16 -%264 = OpTypePointer StorageBuffer %23 -%267 = OpTypePointer StorageBuffer %13 -%268 = OpConstant %4 5 -%285 = OpVariable %237 Output -%288 = OpConstantNull %27 -%304 = OpConstantNull %39 -%308 = OpConstantNull %4 -%310 = OpTypePointer Input %11 -%309 = OpVariable %310 Input -%312 = OpConstantNull %11 -%314 = OpTypeBool -%313 = OpTypeVector %314 3 -%319 = OpConstant %4 264 -%64 = OpFunction %2 None %65 -%63 = OpLabel -%57 = OpVariable %58 Function %59 +%20 = OpConstant %4 2 +%19 = OpTypeArray %17 %20 +%22 = OpConstant %4 10 +%21 = OpTypeArray %6 %22 +%23 = OpTypeVector %4 2 +%24 = OpTypeArray %23 %20 +%25 = OpTypeRuntimeArray %13 +%26 = OpTypeStruct %14 %19 %6 %21 %24 %25 +%27 = OpTypeMatrix %18 3 +%28 = OpTypeStruct %27 +%29 = OpTypeVector %6 2 +%30 = OpTypeMatrix %18 4 +%31 = OpTypeArray %30 %20 +%32 = OpTypeStruct %31 +%33 = OpTypePointer Function %16 +%34 = OpTypeArray %16 %22 +%36 = OpConstant %4 5 +%35 = OpTypeArray %34 %36 +%37 = OpTypeVector %16 4 +%38 = OpTypePointer StorageBuffer %6 +%39 = OpTypeArray %6 %36 +%40 = OpTypeVector %6 4 +%41 = OpTypePointer Workgroup %4 +%42 = OpTypeArray %37 %20 +%43 = OpTypePointer Function %42 +%44 = OpConstantComposite %11 %3 %3 %3 +%45 = OpConstantComposite %12 %3 %44 %5 +%47 = OpTypePointer Private %12 +%46 = OpVariable %47 Private %45 +%49 = OpTypePointer StorageBuffer %26 +%48 = OpVariable %49 StorageBuffer +%51 = OpTypeStruct %28 +%52 = OpTypePointer Uniform %51 +%50 = OpVariable %52 Uniform +%54 = OpTypeStruct %29 +%55 = OpTypePointer StorageBuffer %54 +%53 = OpVariable %55 StorageBuffer +%57 = OpTypeStruct %32 +%58 = OpTypePointer Uniform %57 +%56 = OpVariable %58 Uniform +%59 = OpVariable %41 Workgroup +%61 = OpTypePointer Function %6 +%62 = OpConstantNull %6 +%64 = OpTypePointer Function %28 +%65 = OpConstantNull %28 +%68 = OpTypeFunction %2 +%69 = OpTypePointer Uniform %28 +%71 = OpConstant %16 1.0 +%72 = OpConstant %16 2.0 +%73 = OpConstant %16 3.0 +%74 = OpConstant %16 6.0 +%75 = OpConstant %16 5.0 +%76 = OpConstant %16 4.0 +%77 = OpConstant %16 9.0 +%78 = OpConstant %16 90.0 +%79 = OpConstant %16 10.0 +%80 = OpConstant %16 20.0 +%81 = OpConstant %16 30.0 +%82 = OpConstant %16 40.0 +%86 = OpTypePointer Uniform %27 +%89 = OpTypePointer Uniform %18 +%95 = OpTypePointer Uniform %16 +%96 = OpConstant %4 1 +%116 = OpTypePointer Function %27 +%122 = OpTypePointer Function %18 +%128 = OpTypePointer Function %16 +%138 = OpConstantNull %6 +%140 = OpTypePointer Function %32 +%141 = OpConstantNull %32 +%144 = OpTypePointer Uniform %32 +%146 = OpConstantNull %31 +%147 = OpConstantNull %31 +%148 = OpConstant %16 8.0 +%149 = OpConstant %16 7.0 +%153 = OpTypePointer Uniform %31 +%156 = OpTypePointer Uniform %30 +%179 = OpTypePointer Function %31 +%181 = OpTypePointer Function %30 +%204 = OpTypeFunction %16 %33 +%210 = OpTypeFunction %16 %35 +%211 = OpConstant %6 4 +%212 = OpConstant %6 9 +%219 = OpTypeFunction %2 %41 +%220 = OpConstant %4 42 +%225 = OpTypeFunction %2 %43 +%231 = OpConstantNull %16 +%233 = OpTypePointer Function %39 +%234 = OpConstantNull %39 +%237 = OpTypePointer Input %4 +%236 = OpVariable %237 Input +%240 = OpTypePointer Output %37 +%239 = OpVariable %240 Output +%243 = OpTypePointer StorageBuffer %29 +%246 = OpConstant %16 0.0 +%247 = OpConstant %4 3 +%248 = OpConstant %6 3 +%249 = OpConstant %6 42 +%250 = OpConstantNull %35 +%255 = OpTypePointer StorageBuffer %14 +%258 = OpTypePointer StorageBuffer %24 +%259 = OpConstant %4 4 +%262 = OpTypePointer StorageBuffer %15 +%263 = OpTypePointer StorageBuffer %16 +%266 = OpTypePointer StorageBuffer %25 +%269 = OpTypePointer StorageBuffer %13 +%286 = OpVariable %240 Output +%289 = OpConstantNull %29 +%305 = OpConstantNull %42 +%309 = OpConstantNull %4 +%311 = OpTypePointer Input %11 +%310 = OpVariable %311 Input +%313 = OpConstantNull %11 +%315 = OpTypeBool +%314 = OpTypeVector %315 3 +%320 = OpConstant %4 264 +%67 = OpFunction %2 None %68 +%66 = OpLabel %60 = OpVariable %61 Function %62 -%67 = OpAccessChain %66 %47 %3 -OpBranch %80 -%80 = OpLabel -OpStore %57 %9 -%81 = OpLoad %6 %57 -%82 = OpISub %6 %81 %9 -OpStore %57 %82 -%84 = OpAccessChain %83 %67 %3 -%85 = OpLoad %25 %84 -%87 = OpAccessChain %86 %67 %3 %3 -%88 = OpLoad %18 %87 -%89 = OpLoad %6 %57 -%90 = OpAccessChain %86 %67 %3 %89 +%63 = OpVariable %64 Function %65 +%70 = OpAccessChain %69 %50 %3 +OpBranch %83 +%83 = OpLabel +OpStore %60 %9 +%84 = OpLoad %6 %60 +%85 = OpISub %6 %84 %9 +OpStore %60 %85 +%87 = OpAccessChain %86 %70 %3 +%88 = OpLoad %27 %87 +%90 = OpAccessChain %89 %70 %3 %3 %91 = OpLoad %18 %90 -%94 = OpAccessChain %92 %67 %3 %3 %93 -%95 = OpLoad %16 %94 -%96 = OpLoad %6 %57 -%97 = OpAccessChain %92 %67 %3 %3 %96 +%92 = OpLoad %6 %60 +%93 = OpAccessChain %89 %70 %3 %92 +%94 = OpLoad %18 %93 +%97 = OpAccessChain %95 %70 %3 %3 %96 %98 = OpLoad %16 %97 -%99 = OpLoad %6 %57 -%100 = OpAccessChain %92 %67 %3 %99 %93 +%99 = OpLoad %6 %60 +%100 = OpAccessChain %95 %70 %3 %3 %99 %101 = OpLoad %16 %100 -%102 = OpLoad %6 %57 -%103 = OpLoad %6 %57 -%104 = OpAccessChain %92 %67 %3 %102 %103 -%105 = OpLoad %16 %104 -%106 = OpCompositeConstruct %18 %68 %68 -%107 = OpCompositeConstruct %18 %69 %69 -%108 = OpCompositeConstruct %18 %70 %70 -%109 = OpCompositeConstruct %25 %106 %107 %108 -%110 = OpCompositeConstruct %26 %109 -OpStore %60 %110 -%111 = OpLoad %6 %57 -%112 = OpIAdd %6 %111 %9 -OpStore %57 %112 -%114 = OpCompositeConstruct %18 %71 %71 -%115 = OpCompositeConstruct %18 %72 %72 -%116 = OpCompositeConstruct %18 %73 %73 -%117 = OpCompositeConstruct %25 %114 %115 %116 -%118 = OpAccessChain %113 %60 %3 -OpStore %118 %117 -%120 = OpCompositeConstruct %18 %74 %74 -%121 = OpAccessChain %119 %60 %3 %3 +%102 = OpLoad %6 %60 +%103 = OpAccessChain %95 %70 %3 %102 %96 +%104 = OpLoad %16 %103 +%105 = OpLoad %6 %60 +%106 = OpLoad %6 %60 +%107 = OpAccessChain %95 %70 %3 %105 %106 +%108 = OpLoad %16 %107 +%109 = OpCompositeConstruct %18 %71 %71 +%110 = OpCompositeConstruct %18 %72 %72 +%111 = OpCompositeConstruct %18 %73 %73 +%112 = OpCompositeConstruct %27 %109 %110 %111 +%113 = OpCompositeConstruct %28 %112 +OpStore %63 %113 +%114 = OpLoad %6 %60 +%115 = OpIAdd %6 %114 %9 +OpStore %60 %115 +%117 = OpCompositeConstruct %18 %74 %74 +%118 = OpCompositeConstruct %18 %75 %75 +%119 = OpCompositeConstruct %18 %76 %76 +%120 = OpCompositeConstruct %27 %117 %118 %119 +%121 = OpAccessChain %116 %63 %3 OpStore %121 %120 -%122 = OpLoad %6 %57 -%123 = OpCompositeConstruct %18 %75 %75 -%124 = OpAccessChain %119 %60 %3 %122 +%123 = OpCompositeConstruct %18 %77 %77 +%124 = OpAccessChain %122 %63 %3 %3 OpStore %124 %123 -%126 = OpAccessChain %125 %60 %3 %3 %93 -OpStore %126 %76 -%127 = OpLoad %6 %57 -%128 = OpAccessChain %125 %60 %3 %3 %127 -OpStore %128 %77 -%129 = OpLoad %6 %57 -%130 = OpAccessChain %125 %60 %3 %129 %93 -OpStore %130 %78 -%131 = OpLoad %6 %57 -%132 = OpLoad %6 %57 -%133 = OpAccessChain %125 %60 %3 %131 %132 -OpStore %133 %79 +%125 = OpLoad %6 %60 +%126 = OpCompositeConstruct %18 %78 %78 +%127 = OpAccessChain %122 %63 %3 %125 +OpStore %127 %126 +%129 = OpAccessChain %128 %63 %3 %3 %96 +OpStore %129 %79 +%130 = OpLoad %6 %60 +%131 = OpAccessChain %128 %63 %3 %3 %130 +OpStore %131 %80 +%132 = OpLoad %6 %60 +%133 = OpAccessChain %128 %63 %3 %132 %96 +OpStore %133 %81 +%134 = OpLoad %6 %60 +%135 = OpLoad %6 %60 +%136 = OpAccessChain %128 %63 %3 %134 %135 +OpStore %136 %82 OpReturn OpFunctionEnd -%140 = OpFunction %2 None %65 -%139 = OpLabel -%134 = OpVariable %58 Function %135 -%136 = OpVariable %137 Function %138 -%142 = OpAccessChain %141 %53 %3 -OpBranch %147 -%147 = OpLabel -OpStore %134 %9 -%148 = OpLoad %6 %134 -%149 = OpISub %6 %148 %9 -OpStore %134 %149 -%151 = OpAccessChain %150 %142 %3 -%152 = OpLoad %29 %151 -%154 = OpAccessChain %153 %142 %3 %3 -%155 = OpLoad %28 %154 -%156 = OpAccessChain %86 %142 %3 %3 %3 -%157 = OpLoad %18 %156 -%158 = OpLoad %6 %134 -%159 = OpAccessChain %86 %142 %3 %3 %158 +%143 = OpFunction %2 None %68 +%142 = OpLabel +%137 = OpVariable %61 Function %138 +%139 = OpVariable %140 Function %141 +%145 = OpAccessChain %144 %56 %3 +OpBranch %150 +%150 = OpLabel +OpStore %137 %9 +%151 = OpLoad %6 %137 +%152 = OpISub %6 %151 %9 +OpStore %137 %152 +%154 = OpAccessChain %153 %145 %3 +%155 = OpLoad %31 %154 +%157 = OpAccessChain %156 %145 %3 %3 +%158 = OpLoad %30 %157 +%159 = OpAccessChain %89 %145 %3 %3 %3 %160 = OpLoad %18 %159 -%161 = OpAccessChain %92 %142 %3 %3 %3 %93 -%162 = OpLoad %16 %161 -%163 = OpLoad %6 %134 -%164 = OpAccessChain %92 %142 %3 %3 %3 %163 +%161 = OpLoad %6 %137 +%162 = OpAccessChain %89 %145 %3 %3 %161 +%163 = OpLoad %18 %162 +%164 = OpAccessChain %95 %145 %3 %3 %3 %96 %165 = OpLoad %16 %164 -%166 = OpLoad %6 %134 -%167 = OpAccessChain %92 %142 %3 %3 %166 %93 +%166 = OpLoad %6 %137 +%167 = OpAccessChain %95 %145 %3 %3 %3 %166 %168 = OpLoad %16 %167 -%169 = OpLoad %6 %134 -%170 = OpLoad %6 %134 -%171 = OpAccessChain %92 %142 %3 %3 %169 %170 -%172 = OpLoad %16 %171 -%173 = OpCompositeConstruct %30 %143 -OpStore %136 %173 -%174 = OpLoad %6 %134 -%175 = OpIAdd %6 %174 %9 -OpStore %134 %175 -%177 = OpAccessChain %176 %136 %3 -OpStore %177 %144 -%179 = OpCompositeConstruct %18 %145 %145 -%180 = OpCompositeConstruct %18 %146 %146 -%181 = OpCompositeConstruct %18 %71 %71 -%182 = OpCompositeConstruct %18 %72 %72 -%183 = OpCompositeConstruct %28 %179 %180 %181 %182 -%184 = OpAccessChain %178 %136 %3 %3 -OpStore %184 %183 -%185 = OpCompositeConstruct %18 %74 %74 -%186 = OpAccessChain %119 %136 %3 %3 %3 -OpStore %186 %185 -%187 = OpLoad %6 %134 -%188 = OpCompositeConstruct %18 %75 %75 -%189 = OpAccessChain %119 %136 %3 %3 %187 +%169 = OpLoad %6 %137 +%170 = OpAccessChain %95 %145 %3 %3 %169 %96 +%171 = OpLoad %16 %170 +%172 = OpLoad %6 %137 +%173 = OpLoad %6 %137 +%174 = OpAccessChain %95 %145 %3 %3 %172 %173 +%175 = OpLoad %16 %174 +%176 = OpCompositeConstruct %32 %146 +OpStore %139 %176 +%177 = OpLoad %6 %137 +%178 = OpIAdd %6 %177 %9 +OpStore %137 %178 +%180 = OpAccessChain %179 %139 %3 +OpStore %180 %147 +%182 = OpCompositeConstruct %18 %148 %148 +%183 = OpCompositeConstruct %18 %149 %149 +%184 = OpCompositeConstruct %18 %74 %74 +%185 = OpCompositeConstruct %18 %75 %75 +%186 = OpCompositeConstruct %30 %182 %183 %184 %185 +%187 = OpAccessChain %181 %139 %3 %3 +OpStore %187 %186 +%188 = OpCompositeConstruct %18 %77 %77 +%189 = OpAccessChain %122 %139 %3 %3 %3 OpStore %189 %188 -%190 = OpAccessChain %125 %136 %3 %3 %3 %93 -OpStore %190 %76 -%191 = OpLoad %6 %134 -%192 = OpAccessChain %125 %136 %3 %3 %3 %191 -OpStore %192 %77 -%193 = OpLoad %6 %134 -%194 = OpAccessChain %125 %136 %3 %3 %193 %93 -OpStore %194 %78 -%195 = OpLoad %6 %134 -%196 = OpLoad %6 %134 -%197 = OpAccessChain %125 %136 %3 %3 %195 %196 -OpStore %197 %79 +%190 = OpLoad %6 %137 +%191 = OpCompositeConstruct %18 %78 %78 +%192 = OpAccessChain %122 %139 %3 %3 %190 +OpStore %192 %191 +%193 = OpAccessChain %128 %139 %3 %3 %3 %96 +OpStore %193 %79 +%194 = OpLoad %6 %137 +%195 = OpAccessChain %128 %139 %3 %3 %3 %194 +OpStore %195 %80 +%196 = OpLoad %6 %137 +%197 = OpAccessChain %128 %139 %3 %3 %196 %96 +OpStore %197 %81 +%198 = OpLoad %6 %137 +%199 = OpLoad %6 %137 +%200 = OpAccessChain %128 %139 %3 %3 %198 %199 +OpStore %200 %82 OpReturn OpFunctionEnd -%200 = OpFunction %16 None %201 -%199 = OpFunctionParameter %31 -%198 = OpLabel -OpBranch %202 -%202 = OpLabel -%203 = OpLoad %16 %199 -OpReturnValue %203 +%203 = OpFunction %16 None %204 +%202 = OpFunctionParameter %33 +%201 = OpLabel +OpBranch %205 +%205 = OpLabel +%206 = OpLoad %16 %202 +OpReturnValue %206 OpFunctionEnd -%206 = OpFunction %16 None %207 -%205 = OpFunctionParameter %33 -%204 = OpLabel -OpBranch %210 -%210 = OpLabel -%211 = OpCompositeExtract %32 %205 4 -%212 = OpCompositeExtract %16 %211 9 -OpReturnValue %212 -OpFunctionEnd -%215 = OpFunction %2 None %216 -%214 = OpFunctionParameter %38 +%209 = OpFunction %16 None %210 +%208 = OpFunctionParameter %35 +%207 = OpLabel +OpBranch %213 %213 = OpLabel -OpBranch %218 -%218 = OpLabel -OpStore %214 %217 +%214 = OpCompositeExtract %34 %208 4 +%215 = OpCompositeExtract %16 %214 9 +OpReturnValue %215 +OpFunctionEnd +%218 = OpFunction %2 None %219 +%217 = OpFunctionParameter %41 +%216 = OpLabel +OpBranch %221 +%221 = OpLabel +OpStore %217 %220 OpReturn OpFunctionEnd -%221 = OpFunction %2 None %222 -%220 = OpFunctionParameter %40 -%219 = OpLabel -OpBranch %223 -%223 = OpLabel -%224 = OpCompositeConstruct %34 %68 %68 %68 %68 -%225 = OpCompositeConstruct %34 %69 %69 %69 %69 -%226 = OpCompositeConstruct %39 %224 %225 -OpStore %220 %226 +%224 = OpFunction %2 None %225 +%223 = OpFunctionParameter %43 +%222 = OpLabel +OpBranch %226 +%226 = OpLabel +%227 = OpCompositeConstruct %37 %71 %71 %71 %71 +%228 = OpCompositeConstruct %37 %72 %72 %72 %72 +%229 = OpCompositeConstruct %42 %227 %228 +OpStore %223 %229 OpReturn OpFunctionEnd -%238 = OpFunction %2 None %65 -%232 = OpLabel -%227 = OpVariable %31 Function %228 -%229 = OpVariable %230 Function %231 -%235 = OpLoad %4 %233 -%239 = OpAccessChain %66 %47 %3 -%241 = OpAccessChain %240 %50 %3 -%242 = OpAccessChain %141 %53 %3 -OpBranch %249 -%249 = OpLabel -OpStore %227 %243 -%250 = OpLoad %16 %227 -OpStore %227 %68 -%251 = OpFunctionCall %2 %64 -%252 = OpFunctionCall %2 %140 -%254 = OpAccessChain %253 %45 %3 -%255 = OpLoad %14 %254 -%258 = OpAccessChain %256 %45 %257 -%259 = OpLoad %22 %258 -%262 = OpAccessChain %261 %45 %3 %244 %3 -%263 = OpLoad %16 %262 -%265 = OpArrayLength %4 %45 5 -%266 = OpISub %4 %265 %245 -%269 = OpAccessChain %35 %45 %268 %266 %3 -%270 = OpLoad %6 %269 -%271 = OpLoad %27 %241 -%272 = OpFunctionCall %16 %200 %227 -%273 = OpConvertFToS %6 %263 -%274 = OpCompositeConstruct %36 %270 %273 %246 %208 %10 -OpStore %229 %274 -%275 = OpIAdd %4 %235 %93 -%276 = OpAccessChain %58 %229 %275 -OpStore %276 %247 -%277 = OpAccessChain %58 %229 %235 -%278 = OpLoad %6 %277 -%279 = OpFunctionCall %16 %206 %248 -%280 = OpCompositeConstruct %37 %278 %278 %278 %278 -%281 = OpConvertSToF %34 %280 -%282 = OpMatrixTimesVector %15 %255 %281 -%283 = OpCompositeConstruct %34 %282 %69 -OpStore %236 %283 +%241 = OpFunction %2 None %68 +%235 = OpLabel +%230 = OpVariable %33 Function %231 +%232 = OpVariable %233 Function %234 +%238 = OpLoad %4 %236 +%242 = OpAccessChain %69 %50 %3 +%244 = OpAccessChain %243 %53 %3 +%245 = OpAccessChain %144 %56 %3 +OpBranch %251 +%251 = OpLabel +OpStore %230 %246 +%252 = OpLoad %16 %230 +OpStore %230 %71 +%253 = OpFunctionCall %2 %67 +%254 = OpFunctionCall %2 %143 +%256 = OpAccessChain %255 %48 %3 +%257 = OpLoad %14 %256 +%260 = OpAccessChain %258 %48 %259 +%261 = OpLoad %24 %260 +%264 = OpAccessChain %263 %48 %3 %247 %3 +%265 = OpLoad %16 %264 +%267 = OpArrayLength %4 %48 5 +%268 = OpISub %4 %267 %20 +%270 = OpAccessChain %38 %48 %36 %268 %3 +%271 = OpLoad %6 %270 +%272 = OpLoad %29 %244 +%273 = OpFunctionCall %16 %203 %230 +%274 = OpConvertFToS %6 %265 +%275 = OpCompositeConstruct %39 %271 %274 %248 %211 %10 +OpStore %232 %275 +%276 = OpIAdd %4 %238 %96 +%277 = OpAccessChain %61 %232 %276 +OpStore %277 %249 +%278 = OpAccessChain %61 %232 %238 +%279 = OpLoad %6 %278 +%280 = OpFunctionCall %16 %209 %250 +%281 = OpCompositeConstruct %40 %279 %279 %279 %279 +%282 = OpConvertSToF %37 %281 +%283 = OpMatrixTimesVector %15 %257 %282 +%284 = OpCompositeConstruct %37 %283 %72 +OpStore %239 %284 OpReturn OpFunctionEnd -%286 = OpFunction %2 None %65 -%284 = OpLabel -%287 = OpAccessChain %240 %50 %3 -OpBranch %289 -%289 = OpLabel -%290 = OpAccessChain %261 %45 %3 %93 %245 -OpStore %290 %68 -%291 = OpCompositeConstruct %15 %243 %243 %243 -%292 = OpCompositeConstruct %15 %68 %68 %68 -%293 = OpCompositeConstruct %15 %69 %69 %69 -%294 = OpCompositeConstruct %15 %70 %70 %70 -%295 = OpCompositeConstruct %14 %291 %292 %293 %294 -%296 = OpAccessChain %253 %45 %3 -OpStore %296 %295 -%297 = OpCompositeConstruct %21 %3 %3 -%298 = OpCompositeConstruct %21 %93 %93 -%299 = OpCompositeConstruct %22 %297 %298 -%300 = OpAccessChain %256 %45 %257 -OpStore %300 %299 -%301 = OpAccessChain %35 %45 %268 %93 %3 -OpStore %301 %9 -OpStore %287 %288 -%302 = OpCompositeConstruct %34 %243 %243 %243 %243 -OpStore %285 %302 +%287 = OpFunction %2 None %68 +%285 = OpLabel +%288 = OpAccessChain %243 %53 %3 +OpBranch %290 +%290 = OpLabel +%291 = OpAccessChain %263 %48 %3 %96 %20 +OpStore %291 %71 +%292 = OpCompositeConstruct %15 %246 %246 %246 +%293 = OpCompositeConstruct %15 %71 %71 %71 +%294 = OpCompositeConstruct %15 %72 %72 %72 +%295 = OpCompositeConstruct %15 %73 %73 %73 +%296 = OpCompositeConstruct %14 %292 %293 %294 %295 +%297 = OpAccessChain %255 %48 %3 +OpStore %297 %296 +%298 = OpCompositeConstruct %23 %3 %3 +%299 = OpCompositeConstruct %23 %96 %96 +%300 = OpCompositeConstruct %24 %298 %299 +%301 = OpAccessChain %258 %48 %259 +OpStore %301 %300 +%302 = OpAccessChain %38 %48 %36 %96 %3 +OpStore %302 %9 +OpStore %288 %289 +%303 = OpCompositeConstruct %37 %246 %246 %246 %246 +OpStore %286 %303 OpReturn OpFunctionEnd -%306 = OpFunction %2 None %65 -%305 = OpLabel -%303 = OpVariable %40 Function %304 -OpBranch %307 -%307 = OpLabel -%311 = OpLoad %11 %309 -%315 = OpIEqual %313 %311 %312 -%316 = OpAll %314 %315 -OpSelectionMerge %317 None -OpBranchConditional %316 %318 %317 +%307 = OpFunction %2 None %68 +%306 = OpLabel +%304 = OpVariable %43 Function %305 +OpBranch %308 +%308 = OpLabel +%312 = OpLoad %11 %310 +%316 = OpIEqual %314 %312 %313 +%317 = OpAll %315 %316 +OpSelectionMerge %318 None +OpBranchConditional %317 %319 %318 +%319 = OpLabel +OpStore %59 %309 +OpBranch %318 %318 = OpLabel -OpStore %56 %308 -OpBranch %317 -%317 = OpLabel -OpControlBarrier %245 %245 %319 -OpBranch %320 -%320 = OpLabel -%321 = OpCompositeConstruct %34 %71 %71 %71 %71 -%322 = OpCompositeConstruct %34 %146 %146 %146 %146 -%323 = OpCompositeConstruct %39 %321 %322 -OpStore %303 %323 -%324 = OpFunctionCall %2 %215 %56 -%325 = OpFunctionCall %2 %221 %303 +OpControlBarrier %20 %20 %320 +OpBranch %321 +%321 = OpLabel +%322 = OpCompositeConstruct %37 %74 %74 %74 %74 +%323 = OpCompositeConstruct %37 %149 %149 %149 %149 +%324 = OpCompositeConstruct %42 %322 %323 +OpStore %304 %324 +%325 = OpFunctionCall %2 %218 %59 +%326 = OpFunctionCall %2 %224 %304 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/array-in-ctor.spvasm b/tests/out/spv/array-in-ctor.spvasm index 8ad438ce0..5511954fc 100644 --- a/tests/out/spv/array-in-ctor.spvasm +++ b/tests/out/spv/array-in-ctor.spvasm @@ -1,38 +1,39 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 20 +; Bound: 21 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %12 "cs_main" -OpExecutionMode %12 LocalSize 1 1 1 +OpEntryPoint GLCompute %14 "cs_main" +OpExecutionMode %14 LocalSize 1 1 1 OpDecorate %6 ArrayStride 4 -OpMemberDecorate %7 0 Offset 0 -OpDecorate %8 NonWritable -OpDecorate %8 DescriptorSet 0 -OpDecorate %8 Binding 0 -OpDecorate %9 Block OpMemberDecorate %9 0 Offset 0 +OpDecorate %10 NonWritable +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 0 +OpDecorate %11 Block +OpMemberDecorate %11 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 %5 = OpTypeFloat 32 -%6 = OpTypeArray %5 %3 -%7 = OpTypeStruct %6 -%9 = OpTypeStruct %7 -%10 = OpTypePointer StorageBuffer %9 -%8 = OpVariable %10 StorageBuffer -%13 = OpTypeFunction %2 -%14 = OpTypePointer StorageBuffer %7 -%16 = OpTypeInt 32 0 -%15 = OpConstant %16 0 -%12 = OpFunction %2 None %13 -%11 = OpLabel -%17 = OpAccessChain %14 %8 %15 -OpBranch %18 -%18 = OpLabel -%19 = OpLoad %7 %17 +%8 = OpTypeInt 32 0 +%7 = OpConstant %8 2 +%6 = OpTypeArray %5 %7 +%9 = OpTypeStruct %6 +%11 = OpTypeStruct %9 +%12 = OpTypePointer StorageBuffer %11 +%10 = OpVariable %12 StorageBuffer +%15 = OpTypeFunction %2 +%16 = OpTypePointer StorageBuffer %9 +%17 = OpConstant %8 0 +%14 = OpFunction %2 None %15 +%13 = OpLabel +%18 = OpAccessChain %16 %10 %17 +OpBranch %19 +%19 = OpLabel +%20 = OpLoad %9 %18 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/tests/out/spv/atomicCompareExchange.spvasm index 1269436ed..1812f1a90 100644 --- a/tests/out/spv/atomicCompareExchange.spvasm +++ b/tests/out/spv/atomicCompareExchange.spvasm @@ -1,208 +1,209 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 126 +; Bound: 127 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %29 "test_atomic_compare_exchange_i32" -OpEntryPoint GLCompute %84 "test_atomic_compare_exchange_u32" -OpExecutionMode %29 LocalSize 1 1 1 -OpExecutionMode %84 LocalSize 1 1 1 +OpEntryPoint GLCompute %30 "test_atomic_compare_exchange_i32" +OpEntryPoint GLCompute %85 "test_atomic_compare_exchange_u32" +OpExecutionMode %30 LocalSize 1 1 1 +OpExecutionMode %85 LocalSize 1 1 1 OpDecorate %7 ArrayStride 4 -OpDecorate %8 ArrayStride 4 -OpMemberDecorate %11 0 Offset 0 -OpMemberDecorate %11 1 Offset 4 +OpDecorate %9 ArrayStride 4 OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 4 -OpDecorate %13 DescriptorSet 0 -OpDecorate %13 Binding 0 -OpDecorate %14 Block -OpMemberDecorate %14 0 Offset 0 -OpDecorate %16 DescriptorSet 0 -OpDecorate %16 Binding 1 -OpDecorate %17 Block -OpMemberDecorate %17 0 Offset 0 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 1 Offset 4 +OpDecorate %14 DescriptorSet 0 +OpDecorate %14 Binding 0 +OpDecorate %15 Block +OpMemberDecorate %15 0 Offset 0 +OpDecorate %17 DescriptorSet 0 +OpDecorate %17 Binding 1 +OpDecorate %18 Block +OpMemberDecorate %18 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 128 %5 = OpConstant %4 1 %6 = OpTypeInt 32 1 -%7 = OpTypeArray %6 %3 -%8 = OpTypeArray %4 %3 -%9 = OpTypeBool -%10 = OpTypeFloat 32 -%11 = OpTypeStruct %6 %9 -%12 = OpTypeStruct %4 %9 -%14 = OpTypeStruct %7 -%15 = OpTypePointer StorageBuffer %14 -%13 = OpVariable %15 StorageBuffer -%17 = OpTypeStruct %8 -%18 = OpTypePointer StorageBuffer %17 -%16 = OpVariable %18 StorageBuffer -%20 = OpTypePointer Function %4 -%21 = OpConstantNull %4 -%23 = OpTypePointer Function %6 -%24 = OpConstantNull %6 -%26 = OpTypePointer Function %9 -%27 = OpConstantNull %9 -%30 = OpTypeFunction %2 -%31 = OpTypePointer StorageBuffer %7 -%32 = OpConstant %4 0 -%34 = OpConstantFalse %9 -%35 = OpConstant %10 1.0 -%48 = OpTypePointer StorageBuffer %6 -%51 = OpConstant %6 1 -%52 = OpConstant %4 64 -%78 = OpConstantNull %4 -%80 = OpConstantNull %4 -%82 = OpConstantNull %9 -%85 = OpTypePointer StorageBuffer %8 -%99 = OpTypePointer StorageBuffer %4 -%29 = OpFunction %2 None %30 -%28 = OpLabel -%19 = OpVariable %20 Function %21 -%22 = OpVariable %23 Function %24 -%25 = OpVariable %26 Function %27 -%33 = OpAccessChain %31 %13 %32 -OpBranch %36 -%36 = OpLabel -OpStore %19 %32 +%8 = OpConstant %4 128 +%7 = OpTypeArray %6 %8 +%9 = OpTypeArray %4 %8 +%10 = OpTypeBool +%11 = OpTypeFloat 32 +%12 = OpTypeStruct %6 %10 +%13 = OpTypeStruct %4 %10 +%15 = OpTypeStruct %7 +%16 = OpTypePointer StorageBuffer %15 +%14 = OpVariable %16 StorageBuffer +%18 = OpTypeStruct %9 +%19 = OpTypePointer StorageBuffer %18 +%17 = OpVariable %19 StorageBuffer +%21 = OpTypePointer Function %4 +%22 = OpConstantNull %4 +%24 = OpTypePointer Function %6 +%25 = OpConstantNull %6 +%27 = OpTypePointer Function %10 +%28 = OpConstantNull %10 +%31 = OpTypeFunction %2 +%32 = OpTypePointer StorageBuffer %7 +%33 = OpConstant %4 0 +%35 = OpConstantFalse %10 +%36 = OpConstant %11 1.0 +%49 = OpTypePointer StorageBuffer %6 +%52 = OpConstant %6 1 +%53 = OpConstant %4 64 +%79 = OpConstantNull %4 +%81 = OpConstantNull %4 +%83 = OpConstantNull %10 +%86 = OpTypePointer StorageBuffer %9 +%100 = OpTypePointer StorageBuffer %4 +%30 = OpFunction %2 None %31 +%29 = OpLabel +%20 = OpVariable %21 Function %22 +%23 = OpVariable %24 Function %25 +%26 = OpVariable %27 Function %28 +%34 = OpAccessChain %32 %14 %33 OpBranch %37 %37 = OpLabel -OpLoopMerge %38 %40 None -OpBranch %39 -%39 = OpLabel -%41 = OpLoad %4 %19 -%42 = OpULessThan %9 %41 %3 -OpSelectionMerge %43 None -OpBranchConditional %42 %43 %44 -%44 = OpLabel +OpStore %20 %33 OpBranch %38 -%43 = OpLabel -OpBranch %45 -%45 = OpLabel -%47 = OpLoad %4 %19 -%49 = OpAccessChain %48 %33 %47 -%50 = OpAtomicLoad %6 %49 %51 %52 -OpStore %22 %50 -OpStore %25 %34 -OpBranch %53 -%53 = OpLabel -OpLoopMerge %54 %56 None -OpBranch %55 -%55 = OpLabel -%57 = OpLoad %9 %25 -%58 = OpLogicalNot %9 %57 -OpSelectionMerge %59 None -OpBranchConditional %58 %59 %60 -%60 = OpLabel -OpBranch %54 -%59 = OpLabel -OpBranch %61 -%61 = OpLabel -%63 = OpLoad %6 %22 -%64 = OpBitcast %10 %63 -%65 = OpFAdd %10 %64 %35 -%66 = OpBitcast %6 %65 -%67 = OpLoad %4 %19 -%68 = OpLoad %6 %22 -%70 = OpAccessChain %48 %33 %67 -%71 = OpAtomicCompareExchange %6 %70 %51 %52 %52 %66 %68 -%72 = OpIEqual %9 %71 %68 -%69 = OpCompositeConstruct %11 %71 %72 -%73 = OpCompositeExtract %6 %69 0 -OpStore %22 %73 -%74 = OpCompositeExtract %9 %69 1 -OpStore %25 %74 -OpBranch %62 -%62 = OpLabel -OpBranch %56 -%56 = OpLabel -OpBranch %53 -%54 = OpLabel -OpBranch %46 -%46 = OpLabel +%38 = OpLabel +OpLoopMerge %39 %41 None OpBranch %40 %40 = OpLabel -%75 = OpLoad %4 %19 -%76 = OpIAdd %4 %75 %5 -OpStore %19 %76 -OpBranch %37 -%38 = OpLabel +%42 = OpLoad %4 %20 +%43 = OpULessThan %10 %42 %3 +OpSelectionMerge %44 None +OpBranchConditional %43 %44 %45 +%45 = OpLabel +OpBranch %39 +%44 = OpLabel +OpBranch %46 +%46 = OpLabel +%48 = OpLoad %4 %20 +%50 = OpAccessChain %49 %34 %48 +%51 = OpAtomicLoad %6 %50 %52 %53 +OpStore %23 %51 +OpStore %26 %35 +OpBranch %54 +%54 = OpLabel +OpLoopMerge %55 %57 None +OpBranch %56 +%56 = OpLabel +%58 = OpLoad %10 %26 +%59 = OpLogicalNot %10 %58 +OpSelectionMerge %60 None +OpBranchConditional %59 %60 %61 +%61 = OpLabel +OpBranch %55 +%60 = OpLabel +OpBranch %62 +%62 = OpLabel +%64 = OpLoad %6 %23 +%65 = OpBitcast %11 %64 +%66 = OpFAdd %11 %65 %36 +%67 = OpBitcast %6 %66 +%68 = OpLoad %4 %20 +%69 = OpLoad %6 %23 +%71 = OpAccessChain %49 %34 %68 +%72 = OpAtomicCompareExchange %6 %71 %52 %53 %53 %67 %69 +%73 = OpIEqual %10 %72 %69 +%70 = OpCompositeConstruct %12 %72 %73 +%74 = OpCompositeExtract %6 %70 0 +OpStore %23 %74 +%75 = OpCompositeExtract %10 %70 1 +OpStore %26 %75 +OpBranch %63 +%63 = OpLabel +OpBranch %57 +%57 = OpLabel +OpBranch %54 +%55 = OpLabel +OpBranch %47 +%47 = OpLabel +OpBranch %41 +%41 = OpLabel +%76 = OpLoad %4 %20 +%77 = OpIAdd %4 %76 %5 +OpStore %20 %77 +OpBranch %38 +%39 = OpLabel OpReturn OpFunctionEnd -%84 = OpFunction %2 None %30 -%83 = OpLabel -%77 = OpVariable %20 Function %78 -%79 = OpVariable %20 Function %80 -%81 = OpVariable %26 Function %82 -%86 = OpAccessChain %85 %16 %32 -OpBranch %87 -%87 = OpLabel -OpStore %77 %32 +%85 = OpFunction %2 None %31 +%84 = OpLabel +%78 = OpVariable %21 Function %79 +%80 = OpVariable %21 Function %81 +%82 = OpVariable %27 Function %83 +%87 = OpAccessChain %86 %17 %33 OpBranch %88 %88 = OpLabel -OpLoopMerge %89 %91 None -OpBranch %90 -%90 = OpLabel -%92 = OpLoad %4 %77 -%93 = OpULessThan %9 %92 %3 -OpSelectionMerge %94 None -OpBranchConditional %93 %94 %95 -%95 = OpLabel +OpStore %78 %33 OpBranch %89 -%94 = OpLabel -OpBranch %96 -%96 = OpLabel -%98 = OpLoad %4 %77 -%100 = OpAccessChain %99 %86 %98 -%101 = OpAtomicLoad %4 %100 %51 %52 -OpStore %79 %101 -OpStore %81 %34 -OpBranch %102 -%102 = OpLabel -OpLoopMerge %103 %105 None -OpBranch %104 -%104 = OpLabel -%106 = OpLoad %9 %81 -%107 = OpLogicalNot %9 %106 -OpSelectionMerge %108 None -OpBranchConditional %107 %108 %109 -%109 = OpLabel -OpBranch %103 -%108 = OpLabel -OpBranch %110 -%110 = OpLabel -%112 = OpLoad %4 %79 -%113 = OpBitcast %10 %112 -%114 = OpFAdd %10 %113 %35 -%115 = OpBitcast %4 %114 -%116 = OpLoad %4 %77 -%117 = OpLoad %4 %79 -%119 = OpAccessChain %99 %86 %116 -%120 = OpAtomicCompareExchange %4 %119 %51 %52 %52 %115 %117 -%121 = OpIEqual %9 %120 %117 -%118 = OpCompositeConstruct %12 %120 %121 -%122 = OpCompositeExtract %4 %118 0 -OpStore %79 %122 -%123 = OpCompositeExtract %9 %118 1 -OpStore %81 %123 -OpBranch %111 -%111 = OpLabel -OpBranch %105 -%105 = OpLabel -OpBranch %102 -%103 = OpLabel -OpBranch %97 -%97 = OpLabel +%89 = OpLabel +OpLoopMerge %90 %92 None OpBranch %91 %91 = OpLabel -%124 = OpLoad %4 %77 -%125 = OpIAdd %4 %124 %5 -OpStore %77 %125 -OpBranch %88 -%89 = OpLabel +%93 = OpLoad %4 %78 +%94 = OpULessThan %10 %93 %3 +OpSelectionMerge %95 None +OpBranchConditional %94 %95 %96 +%96 = OpLabel +OpBranch %90 +%95 = OpLabel +OpBranch %97 +%97 = OpLabel +%99 = OpLoad %4 %78 +%101 = OpAccessChain %100 %87 %99 +%102 = OpAtomicLoad %4 %101 %52 %53 +OpStore %80 %102 +OpStore %82 %35 +OpBranch %103 +%103 = OpLabel +OpLoopMerge %104 %106 None +OpBranch %105 +%105 = OpLabel +%107 = OpLoad %10 %82 +%108 = OpLogicalNot %10 %107 +OpSelectionMerge %109 None +OpBranchConditional %108 %109 %110 +%110 = OpLabel +OpBranch %104 +%109 = OpLabel +OpBranch %111 +%111 = OpLabel +%113 = OpLoad %4 %80 +%114 = OpBitcast %11 %113 +%115 = OpFAdd %11 %114 %36 +%116 = OpBitcast %4 %115 +%117 = OpLoad %4 %78 +%118 = OpLoad %4 %80 +%120 = OpAccessChain %100 %87 %117 +%121 = OpAtomicCompareExchange %4 %120 %52 %53 %53 %116 %118 +%122 = OpIEqual %10 %121 %118 +%119 = OpCompositeConstruct %13 %121 %122 +%123 = OpCompositeExtract %4 %119 0 +OpStore %80 %123 +%124 = OpCompositeExtract %10 %119 1 +OpStore %82 %124 +OpBranch %112 +%112 = OpLabel +OpBranch %106 +%106 = OpLabel +OpBranch %103 +%104 = OpLabel +OpBranch %98 +%98 = OpLabel +OpBranch %92 +%92 = OpLabel +%125 = OpLoad %4 %78 +%126 = OpIAdd %4 %125 %5 +OpStore %78 %126 +OpBranch %89 +%90 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/atomicOps.spvasm b/tests/out/spv/atomicOps.spvasm index aa2d6aa68..a30a92a30 100644 --- a/tests/out/spv/atomicOps.spvasm +++ b/tests/out/spv/atomicOps.spvasm @@ -6,235 +6,235 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %28 "cs_main" %25 -OpExecutionMode %28 LocalSize 2 1 1 +OpEntryPoint GLCompute %29 "cs_main" %26 +OpExecutionMode %29 LocalSize 2 1 1 OpDecorate %6 ArrayStride 4 -OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %7 1 Offset 4 -OpDecorate %9 DescriptorSet 0 -OpDecorate %9 Binding 0 -OpDecorate %10 Block -OpMemberDecorate %10 0 Offset 0 -OpDecorate %12 DescriptorSet 0 -OpDecorate %12 Binding 1 -OpDecorate %13 Block -OpMemberDecorate %13 0 Offset 0 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 2 -OpDecorate %16 Block -OpMemberDecorate %16 0 Offset 0 -OpDecorate %25 BuiltIn LocalInvocationId +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %8 1 Offset 4 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 0 +OpDecorate %11 Block +OpMemberDecorate %11 0 Offset 0 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 1 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpDecorate %16 DescriptorSet 0 +OpDecorate %16 Binding 2 +OpDecorate %17 Block +OpMemberDecorate %17 0 Offset 0 +OpDecorate %26 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 %5 = OpTypeInt 32 0 -%6 = OpTypeArray %4 %3 -%7 = OpTypeStruct %5 %6 -%8 = OpTypeVector %5 3 -%10 = OpTypeStruct %5 -%11 = OpTypePointer StorageBuffer %10 -%9 = OpVariable %11 StorageBuffer -%13 = OpTypeStruct %6 -%14 = OpTypePointer StorageBuffer %13 -%12 = OpVariable %14 StorageBuffer -%16 = OpTypeStruct %7 -%17 = OpTypePointer StorageBuffer %16 -%15 = OpVariable %17 StorageBuffer -%19 = OpTypePointer Workgroup %5 -%18 = OpVariable %19 Workgroup -%21 = OpTypePointer Workgroup %6 -%20 = OpVariable %21 Workgroup -%23 = OpTypePointer Workgroup %7 -%22 = OpVariable %23 Workgroup -%26 = OpTypePointer Input %8 -%25 = OpVariable %26 Input -%29 = OpTypeFunction %2 -%30 = OpTypePointer StorageBuffer %5 -%31 = OpConstant %5 0 -%33 = OpTypePointer StorageBuffer %6 -%35 = OpTypePointer StorageBuffer %7 -%37 = OpConstant %5 1 -%38 = OpConstant %4 1 -%40 = OpConstantNull %5 -%41 = OpConstantNull %6 -%42 = OpConstantNull %7 +%7 = OpConstant %5 2 +%6 = OpTypeArray %4 %7 +%8 = OpTypeStruct %5 %6 +%9 = OpTypeVector %5 3 +%11 = OpTypeStruct %5 +%12 = OpTypePointer StorageBuffer %11 +%10 = OpVariable %12 StorageBuffer +%14 = OpTypeStruct %6 +%15 = OpTypePointer StorageBuffer %14 +%13 = OpVariable %15 StorageBuffer +%17 = OpTypeStruct %8 +%18 = OpTypePointer StorageBuffer %17 +%16 = OpVariable %18 StorageBuffer +%20 = OpTypePointer Workgroup %5 +%19 = OpVariable %20 Workgroup +%22 = OpTypePointer Workgroup %6 +%21 = OpVariable %22 Workgroup +%24 = OpTypePointer Workgroup %8 +%23 = OpVariable %24 Workgroup +%27 = OpTypePointer Input %9 +%26 = OpVariable %27 Input +%30 = OpTypeFunction %2 +%31 = OpTypePointer StorageBuffer %5 +%32 = OpConstant %5 0 +%34 = OpTypePointer StorageBuffer %6 +%36 = OpTypePointer StorageBuffer %8 +%38 = OpConstant %5 1 +%39 = OpConstant %4 1 +%41 = OpConstantNull %5 +%42 = OpConstantNull %6 %43 = OpConstantNull %8 -%45 = OpTypeBool -%44 = OpTypeVector %45 3 -%50 = OpConstant %5 2 +%44 = OpConstantNull %9 +%46 = OpTypeBool +%45 = OpTypeVector %46 3 %51 = OpConstant %5 264 %53 = OpConstant %5 64 %54 = OpTypePointer StorageBuffer %4 %58 = OpConstant %5 256 %59 = OpTypePointer Workgroup %4 -%28 = OpFunction %2 None %29 -%24 = OpLabel -%27 = OpLoad %8 %25 -%32 = OpAccessChain %30 %9 %31 -%34 = OpAccessChain %33 %12 %31 -%36 = OpAccessChain %35 %15 %31 -OpBranch %39 -%39 = OpLabel -%46 = OpIEqual %44 %27 %43 -%47 = OpAll %45 %46 -OpSelectionMerge %48 None -OpBranchConditional %47 %49 %48 +%29 = OpFunction %2 None %30 +%25 = OpLabel +%28 = OpLoad %9 %26 +%33 = OpAccessChain %31 %10 %32 +%35 = OpAccessChain %34 %13 %32 +%37 = OpAccessChain %36 %16 %32 +OpBranch %40 +%40 = OpLabel +%47 = OpIEqual %45 %28 %44 +%48 = OpAll %46 %47 +OpSelectionMerge %49 None +OpBranchConditional %48 %50 %49 +%50 = OpLabel +OpStore %19 %41 +OpStore %21 %42 +OpStore %23 %43 +OpBranch %49 %49 = OpLabel -OpStore %18 %40 -OpStore %20 %41 -OpStore %22 %42 -OpBranch %48 -%48 = OpLabel -OpControlBarrier %50 %50 %51 +OpControlBarrier %7 %7 %51 OpBranch %52 %52 = OpLabel -OpAtomicStore %32 %38 %53 %37 -%55 = OpAccessChain %54 %34 %37 -OpAtomicStore %55 %38 %53 %38 -%56 = OpAccessChain %30 %36 %31 -OpAtomicStore %56 %38 %53 %37 -%57 = OpAccessChain %54 %36 %37 %37 -OpAtomicStore %57 %38 %53 %38 -OpAtomicStore %18 %3 %58 %37 -%60 = OpAccessChain %59 %20 %37 -OpAtomicStore %60 %3 %58 %38 -%61 = OpAccessChain %19 %22 %31 -OpAtomicStore %61 %3 %58 %37 -%62 = OpAccessChain %59 %22 %37 %37 -OpAtomicStore %62 %3 %58 %38 -OpControlBarrier %50 %50 %51 -%63 = OpAtomicLoad %5 %32 %38 %53 -%64 = OpAccessChain %54 %34 %37 -%65 = OpAtomicLoad %4 %64 %38 %53 -%66 = OpAccessChain %30 %36 %31 -%67 = OpAtomicLoad %5 %66 %38 %53 -%68 = OpAccessChain %54 %36 %37 %37 -%69 = OpAtomicLoad %4 %68 %38 %53 -%70 = OpAtomicLoad %5 %18 %3 %58 -%71 = OpAccessChain %59 %20 %37 +OpAtomicStore %33 %39 %53 %38 +%55 = OpAccessChain %54 %35 %38 +OpAtomicStore %55 %39 %53 %39 +%56 = OpAccessChain %31 %37 %32 +OpAtomicStore %56 %39 %53 %38 +%57 = OpAccessChain %54 %37 %38 %38 +OpAtomicStore %57 %39 %53 %39 +OpAtomicStore %19 %3 %58 %38 +%60 = OpAccessChain %59 %21 %38 +OpAtomicStore %60 %3 %58 %39 +%61 = OpAccessChain %20 %23 %32 +OpAtomicStore %61 %3 %58 %38 +%62 = OpAccessChain %59 %23 %38 %38 +OpAtomicStore %62 %3 %58 %39 +OpControlBarrier %7 %7 %51 +%63 = OpAtomicLoad %5 %33 %39 %53 +%64 = OpAccessChain %54 %35 %38 +%65 = OpAtomicLoad %4 %64 %39 %53 +%66 = OpAccessChain %31 %37 %32 +%67 = OpAtomicLoad %5 %66 %39 %53 +%68 = OpAccessChain %54 %37 %38 %38 +%69 = OpAtomicLoad %4 %68 %39 %53 +%70 = OpAtomicLoad %5 %19 %3 %58 +%71 = OpAccessChain %59 %21 %38 %72 = OpAtomicLoad %4 %71 %3 %58 -%73 = OpAccessChain %19 %22 %31 +%73 = OpAccessChain %20 %23 %32 %74 = OpAtomicLoad %5 %73 %3 %58 -%75 = OpAccessChain %59 %22 %37 %37 +%75 = OpAccessChain %59 %23 %38 %38 %76 = OpAtomicLoad %4 %75 %3 %58 -OpControlBarrier %50 %50 %51 -%77 = OpAtomicIAdd %5 %32 %38 %53 %37 -%79 = OpAccessChain %54 %34 %37 -%78 = OpAtomicIAdd %4 %79 %38 %53 %38 -%81 = OpAccessChain %30 %36 %31 -%80 = OpAtomicIAdd %5 %81 %38 %53 %37 -%83 = OpAccessChain %54 %36 %37 %37 -%82 = OpAtomicIAdd %4 %83 %38 %53 %38 -%84 = OpAtomicIAdd %5 %18 %3 %58 %37 -%86 = OpAccessChain %59 %20 %37 -%85 = OpAtomicIAdd %4 %86 %3 %58 %38 -%88 = OpAccessChain %19 %22 %31 -%87 = OpAtomicIAdd %5 %88 %3 %58 %37 -%90 = OpAccessChain %59 %22 %37 %37 -%89 = OpAtomicIAdd %4 %90 %3 %58 %38 -OpControlBarrier %50 %50 %51 -%91 = OpAtomicISub %5 %32 %38 %53 %37 -%93 = OpAccessChain %54 %34 %37 -%92 = OpAtomicISub %4 %93 %38 %53 %38 -%95 = OpAccessChain %30 %36 %31 -%94 = OpAtomicISub %5 %95 %38 %53 %37 -%97 = OpAccessChain %54 %36 %37 %37 -%96 = OpAtomicISub %4 %97 %38 %53 %38 -%98 = OpAtomicISub %5 %18 %3 %58 %37 -%100 = OpAccessChain %59 %20 %37 -%99 = OpAtomicISub %4 %100 %3 %58 %38 -%102 = OpAccessChain %19 %22 %31 -%101 = OpAtomicISub %5 %102 %3 %58 %37 -%104 = OpAccessChain %59 %22 %37 %37 -%103 = OpAtomicISub %4 %104 %3 %58 %38 -OpControlBarrier %50 %50 %51 -%105 = OpAtomicUMax %5 %32 %38 %53 %37 -%107 = OpAccessChain %54 %34 %37 -%106 = OpAtomicSMax %4 %107 %38 %53 %38 -%109 = OpAccessChain %30 %36 %31 -%108 = OpAtomicUMax %5 %109 %38 %53 %37 -%111 = OpAccessChain %54 %36 %37 %37 -%110 = OpAtomicSMax %4 %111 %38 %53 %38 -%112 = OpAtomicUMax %5 %18 %3 %58 %37 -%114 = OpAccessChain %59 %20 %37 -%113 = OpAtomicSMax %4 %114 %3 %58 %38 -%116 = OpAccessChain %19 %22 %31 -%115 = OpAtomicUMax %5 %116 %3 %58 %37 -%118 = OpAccessChain %59 %22 %37 %37 -%117 = OpAtomicSMax %4 %118 %3 %58 %38 -OpControlBarrier %50 %50 %51 -%119 = OpAtomicUMin %5 %32 %38 %53 %37 -%121 = OpAccessChain %54 %34 %37 -%120 = OpAtomicSMin %4 %121 %38 %53 %38 -%123 = OpAccessChain %30 %36 %31 -%122 = OpAtomicUMin %5 %123 %38 %53 %37 -%125 = OpAccessChain %54 %36 %37 %37 -%124 = OpAtomicSMin %4 %125 %38 %53 %38 -%126 = OpAtomicUMin %5 %18 %3 %58 %37 -%128 = OpAccessChain %59 %20 %37 -%127 = OpAtomicSMin %4 %128 %3 %58 %38 -%130 = OpAccessChain %19 %22 %31 -%129 = OpAtomicUMin %5 %130 %3 %58 %37 -%132 = OpAccessChain %59 %22 %37 %37 -%131 = OpAtomicSMin %4 %132 %3 %58 %38 -OpControlBarrier %50 %50 %51 -%133 = OpAtomicAnd %5 %32 %38 %53 %37 -%135 = OpAccessChain %54 %34 %37 -%134 = OpAtomicAnd %4 %135 %38 %53 %38 -%137 = OpAccessChain %30 %36 %31 -%136 = OpAtomicAnd %5 %137 %38 %53 %37 -%139 = OpAccessChain %54 %36 %37 %37 -%138 = OpAtomicAnd %4 %139 %38 %53 %38 -%140 = OpAtomicAnd %5 %18 %3 %58 %37 -%142 = OpAccessChain %59 %20 %37 -%141 = OpAtomicAnd %4 %142 %3 %58 %38 -%144 = OpAccessChain %19 %22 %31 -%143 = OpAtomicAnd %5 %144 %3 %58 %37 -%146 = OpAccessChain %59 %22 %37 %37 -%145 = OpAtomicAnd %4 %146 %3 %58 %38 -OpControlBarrier %50 %50 %51 -%147 = OpAtomicOr %5 %32 %38 %53 %37 -%149 = OpAccessChain %54 %34 %37 -%148 = OpAtomicOr %4 %149 %38 %53 %38 -%151 = OpAccessChain %30 %36 %31 -%150 = OpAtomicOr %5 %151 %38 %53 %37 -%153 = OpAccessChain %54 %36 %37 %37 -%152 = OpAtomicOr %4 %153 %38 %53 %38 -%154 = OpAtomicOr %5 %18 %3 %58 %37 -%156 = OpAccessChain %59 %20 %37 -%155 = OpAtomicOr %4 %156 %3 %58 %38 -%158 = OpAccessChain %19 %22 %31 -%157 = OpAtomicOr %5 %158 %3 %58 %37 -%160 = OpAccessChain %59 %22 %37 %37 -%159 = OpAtomicOr %4 %160 %3 %58 %38 -OpControlBarrier %50 %50 %51 -%161 = OpAtomicXor %5 %32 %38 %53 %37 -%163 = OpAccessChain %54 %34 %37 -%162 = OpAtomicXor %4 %163 %38 %53 %38 -%165 = OpAccessChain %30 %36 %31 -%164 = OpAtomicXor %5 %165 %38 %53 %37 -%167 = OpAccessChain %54 %36 %37 %37 -%166 = OpAtomicXor %4 %167 %38 %53 %38 -%168 = OpAtomicXor %5 %18 %3 %58 %37 -%170 = OpAccessChain %59 %20 %37 -%169 = OpAtomicXor %4 %170 %3 %58 %38 -%172 = OpAccessChain %19 %22 %31 -%171 = OpAtomicXor %5 %172 %3 %58 %37 -%174 = OpAccessChain %59 %22 %37 %37 -%173 = OpAtomicXor %4 %174 %3 %58 %38 -%175 = OpAtomicExchange %5 %32 %38 %53 %37 -%177 = OpAccessChain %54 %34 %37 -%176 = OpAtomicExchange %4 %177 %38 %53 %38 -%179 = OpAccessChain %30 %36 %31 -%178 = OpAtomicExchange %5 %179 %38 %53 %37 -%181 = OpAccessChain %54 %36 %37 %37 -%180 = OpAtomicExchange %4 %181 %38 %53 %38 -%182 = OpAtomicExchange %5 %18 %3 %58 %37 -%184 = OpAccessChain %59 %20 %37 -%183 = OpAtomicExchange %4 %184 %3 %58 %38 -%186 = OpAccessChain %19 %22 %31 -%185 = OpAtomicExchange %5 %186 %3 %58 %37 -%188 = OpAccessChain %59 %22 %37 %37 -%187 = OpAtomicExchange %4 %188 %3 %58 %38 +OpControlBarrier %7 %7 %51 +%77 = OpAtomicIAdd %5 %33 %39 %53 %38 +%79 = OpAccessChain %54 %35 %38 +%78 = OpAtomicIAdd %4 %79 %39 %53 %39 +%81 = OpAccessChain %31 %37 %32 +%80 = OpAtomicIAdd %5 %81 %39 %53 %38 +%83 = OpAccessChain %54 %37 %38 %38 +%82 = OpAtomicIAdd %4 %83 %39 %53 %39 +%84 = OpAtomicIAdd %5 %19 %3 %58 %38 +%86 = OpAccessChain %59 %21 %38 +%85 = OpAtomicIAdd %4 %86 %3 %58 %39 +%88 = OpAccessChain %20 %23 %32 +%87 = OpAtomicIAdd %5 %88 %3 %58 %38 +%90 = OpAccessChain %59 %23 %38 %38 +%89 = OpAtomicIAdd %4 %90 %3 %58 %39 +OpControlBarrier %7 %7 %51 +%91 = OpAtomicISub %5 %33 %39 %53 %38 +%93 = OpAccessChain %54 %35 %38 +%92 = OpAtomicISub %4 %93 %39 %53 %39 +%95 = OpAccessChain %31 %37 %32 +%94 = OpAtomicISub %5 %95 %39 %53 %38 +%97 = OpAccessChain %54 %37 %38 %38 +%96 = OpAtomicISub %4 %97 %39 %53 %39 +%98 = OpAtomicISub %5 %19 %3 %58 %38 +%100 = OpAccessChain %59 %21 %38 +%99 = OpAtomicISub %4 %100 %3 %58 %39 +%102 = OpAccessChain %20 %23 %32 +%101 = OpAtomicISub %5 %102 %3 %58 %38 +%104 = OpAccessChain %59 %23 %38 %38 +%103 = OpAtomicISub %4 %104 %3 %58 %39 +OpControlBarrier %7 %7 %51 +%105 = OpAtomicUMax %5 %33 %39 %53 %38 +%107 = OpAccessChain %54 %35 %38 +%106 = OpAtomicSMax %4 %107 %39 %53 %39 +%109 = OpAccessChain %31 %37 %32 +%108 = OpAtomicUMax %5 %109 %39 %53 %38 +%111 = OpAccessChain %54 %37 %38 %38 +%110 = OpAtomicSMax %4 %111 %39 %53 %39 +%112 = OpAtomicUMax %5 %19 %3 %58 %38 +%114 = OpAccessChain %59 %21 %38 +%113 = OpAtomicSMax %4 %114 %3 %58 %39 +%116 = OpAccessChain %20 %23 %32 +%115 = OpAtomicUMax %5 %116 %3 %58 %38 +%118 = OpAccessChain %59 %23 %38 %38 +%117 = OpAtomicSMax %4 %118 %3 %58 %39 +OpControlBarrier %7 %7 %51 +%119 = OpAtomicUMin %5 %33 %39 %53 %38 +%121 = OpAccessChain %54 %35 %38 +%120 = OpAtomicSMin %4 %121 %39 %53 %39 +%123 = OpAccessChain %31 %37 %32 +%122 = OpAtomicUMin %5 %123 %39 %53 %38 +%125 = OpAccessChain %54 %37 %38 %38 +%124 = OpAtomicSMin %4 %125 %39 %53 %39 +%126 = OpAtomicUMin %5 %19 %3 %58 %38 +%128 = OpAccessChain %59 %21 %38 +%127 = OpAtomicSMin %4 %128 %3 %58 %39 +%130 = OpAccessChain %20 %23 %32 +%129 = OpAtomicUMin %5 %130 %3 %58 %38 +%132 = OpAccessChain %59 %23 %38 %38 +%131 = OpAtomicSMin %4 %132 %3 %58 %39 +OpControlBarrier %7 %7 %51 +%133 = OpAtomicAnd %5 %33 %39 %53 %38 +%135 = OpAccessChain %54 %35 %38 +%134 = OpAtomicAnd %4 %135 %39 %53 %39 +%137 = OpAccessChain %31 %37 %32 +%136 = OpAtomicAnd %5 %137 %39 %53 %38 +%139 = OpAccessChain %54 %37 %38 %38 +%138 = OpAtomicAnd %4 %139 %39 %53 %39 +%140 = OpAtomicAnd %5 %19 %3 %58 %38 +%142 = OpAccessChain %59 %21 %38 +%141 = OpAtomicAnd %4 %142 %3 %58 %39 +%144 = OpAccessChain %20 %23 %32 +%143 = OpAtomicAnd %5 %144 %3 %58 %38 +%146 = OpAccessChain %59 %23 %38 %38 +%145 = OpAtomicAnd %4 %146 %3 %58 %39 +OpControlBarrier %7 %7 %51 +%147 = OpAtomicOr %5 %33 %39 %53 %38 +%149 = OpAccessChain %54 %35 %38 +%148 = OpAtomicOr %4 %149 %39 %53 %39 +%151 = OpAccessChain %31 %37 %32 +%150 = OpAtomicOr %5 %151 %39 %53 %38 +%153 = OpAccessChain %54 %37 %38 %38 +%152 = OpAtomicOr %4 %153 %39 %53 %39 +%154 = OpAtomicOr %5 %19 %3 %58 %38 +%156 = OpAccessChain %59 %21 %38 +%155 = OpAtomicOr %4 %156 %3 %58 %39 +%158 = OpAccessChain %20 %23 %32 +%157 = OpAtomicOr %5 %158 %3 %58 %38 +%160 = OpAccessChain %59 %23 %38 %38 +%159 = OpAtomicOr %4 %160 %3 %58 %39 +OpControlBarrier %7 %7 %51 +%161 = OpAtomicXor %5 %33 %39 %53 %38 +%163 = OpAccessChain %54 %35 %38 +%162 = OpAtomicXor %4 %163 %39 %53 %39 +%165 = OpAccessChain %31 %37 %32 +%164 = OpAtomicXor %5 %165 %39 %53 %38 +%167 = OpAccessChain %54 %37 %38 %38 +%166 = OpAtomicXor %4 %167 %39 %53 %39 +%168 = OpAtomicXor %5 %19 %3 %58 %38 +%170 = OpAccessChain %59 %21 %38 +%169 = OpAtomicXor %4 %170 %3 %58 %39 +%172 = OpAccessChain %20 %23 %32 +%171 = OpAtomicXor %5 %172 %3 %58 %38 +%174 = OpAccessChain %59 %23 %38 %38 +%173 = OpAtomicXor %4 %174 %3 %58 %39 +%175 = OpAtomicExchange %5 %33 %39 %53 %38 +%177 = OpAccessChain %54 %35 %38 +%176 = OpAtomicExchange %4 %177 %39 %53 %39 +%179 = OpAccessChain %31 %37 %32 +%178 = OpAtomicExchange %5 %179 %39 %53 %38 +%181 = OpAccessChain %54 %37 %38 %38 +%180 = OpAtomicExchange %4 %181 %39 %53 %39 +%182 = OpAtomicExchange %5 %19 %3 %58 %38 +%184 = OpAccessChain %59 %21 %38 +%183 = OpAtomicExchange %4 %184 %3 %58 %39 +%186 = OpAccessChain %20 %23 %32 +%185 = OpAtomicExchange %5 %186 %3 %58 %38 +%188 = OpAccessChain %59 %23 %38 %38 +%187 = OpAtomicExchange %4 %188 %3 %58 %39 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 5173208dc..4574eb108 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -1,62 +1,62 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 446 +; Bound: 447 OpCapability Shader OpCapability ImageQuery OpCapability ShaderNonUniform OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %67 "main" %62 %65 -OpExecutionMode %67 OriginUpperLeft +OpEntryPoint Fragment %68 "main" %63 %66 +OpExecutionMode %68 OriginUpperLeft OpMemberDecorate %6 0 Offset 0 -OpMemberDecorate %22 0 Offset 0 -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 0 -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 1 -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 2 -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 3 -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 4 -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 5 -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 6 -OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 7 -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 8 -OpDecorate %46 Block -OpMemberDecorate %46 0 Offset 0 -OpDecorate %62 Location 0 -OpDecorate %62 Flat -OpDecorate %65 Location 0 -OpDecorate %96 NonUniform -OpDecorate %120 NonUniform -OpDecorate %122 NonUniform -OpDecorate %147 NonUniform -OpDecorate %149 NonUniform -OpDecorate %187 NonUniform -OpDecorate %218 NonUniform -OpDecorate %237 NonUniform -OpDecorate %256 NonUniform -OpDecorate %278 NonUniform -OpDecorate %280 NonUniform -OpDecorate %302 NonUniform -OpDecorate %304 NonUniform -OpDecorate %326 NonUniform -OpDecorate %328 NonUniform -OpDecorate %350 NonUniform -OpDecorate %352 NonUniform -OpDecorate %374 NonUniform -OpDecorate %376 NonUniform -OpDecorate %398 NonUniform -OpDecorate %400 NonUniform -OpDecorate %423 NonUniform +OpMemberDecorate %23 0 Offset 0 +OpDecorate %28 DescriptorSet 0 +OpDecorate %28 Binding 0 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 1 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 2 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 3 +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 4 +OpDecorate %40 DescriptorSet 0 +OpDecorate %40 Binding 5 +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 6 +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 7 +OpDecorate %46 DescriptorSet 0 +OpDecorate %46 Binding 8 +OpDecorate %47 Block +OpMemberDecorate %47 0 Offset 0 +OpDecorate %63 Location 0 +OpDecorate %63 Flat +OpDecorate %66 Location 0 +OpDecorate %97 NonUniform +OpDecorate %121 NonUniform +OpDecorate %123 NonUniform +OpDecorate %148 NonUniform +OpDecorate %150 NonUniform +OpDecorate %188 NonUniform +OpDecorate %219 NonUniform +OpDecorate %238 NonUniform +OpDecorate %257 NonUniform +OpDecorate %279 NonUniform +OpDecorate %281 NonUniform +OpDecorate %303 NonUniform +OpDecorate %305 NonUniform +OpDecorate %327 NonUniform +OpDecorate %329 NonUniform +OpDecorate %351 NonUniform +OpDecorate %353 NonUniform +OpDecorate %375 NonUniform +OpDecorate %377 NonUniform +OpDecorate %399 NonUniform +OpDecorate %401 NonUniform +OpDecorate %424 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 5 @@ -65,510 +65,511 @@ OpDecorate %423 NonUniform %8 = OpTypeFloat 32 %7 = OpTypeImage %8 2D 0 0 0 1 Unknown %9 = OpTypeRuntimeArray %7 -%10 = OpTypeArray %7 %3 -%11 = OpTypeImage %8 2D 0 1 0 1 Unknown -%12 = OpTypeArray %11 %3 -%13 = OpTypeImage %8 2D 0 0 1 1 Unknown -%14 = OpTypeArray %13 %3 -%15 = OpTypeImage %8 2D 1 0 0 1 Unknown -%16 = OpTypeArray %15 %3 -%17 = OpTypeImage %8 2D 0 0 0 2 Rgba32f -%18 = OpTypeArray %17 %3 -%19 = OpTypeSampler -%20 = OpTypeArray %19 %3 -%21 = OpTypeArray %19 %3 -%22 = OpTypeStruct %5 -%23 = OpTypeVector %8 4 -%24 = OpTypeVector %5 2 -%25 = OpTypeVector %8 2 -%26 = OpTypeVector %4 2 -%30 = OpConstant %5 10 -%29 = OpTypeArray %7 %30 -%28 = OpTypePointer UniformConstant %29 -%27 = OpVariable %28 UniformConstant -%32 = OpTypePointer UniformConstant %10 -%31 = OpVariable %32 UniformConstant -%34 = OpTypePointer UniformConstant %12 -%33 = OpVariable %34 UniformConstant -%36 = OpTypePointer UniformConstant %14 -%35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %16 -%37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %18 -%39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %20 -%41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %21 -%43 = OpVariable %44 UniformConstant -%46 = OpTypeStruct %6 -%47 = OpTypePointer Uniform %46 -%45 = OpVariable %47 Uniform -%49 = OpTypePointer Function %5 -%50 = OpConstantNull %5 -%52 = OpTypePointer Function %24 -%53 = OpConstantNull %24 -%55 = OpTypePointer Function %8 -%56 = OpConstantNull %8 -%58 = OpTypePointer Function %23 -%59 = OpConstantNull %23 -%63 = OpTypePointer Input %5 -%62 = OpVariable %63 Input -%66 = OpTypePointer Output %23 -%65 = OpVariable %66 Output -%68 = OpTypeFunction %2 -%69 = OpTypePointer Uniform %6 -%70 = OpConstant %5 0 -%72 = OpConstant %8 0.0 -%73 = OpConstant %4 0 -%75 = OpTypePointer Uniform %5 -%83 = OpTypePointer UniformConstant %7 -%104 = OpTypePointer UniformConstant %19 -%107 = OpTypeSampledImage %7 -%128 = OpTypePointer UniformConstant %15 -%131 = OpTypePointer UniformConstant %19 -%134 = OpTypeSampledImage %15 -%157 = OpTypeBool -%158 = OpConstantNull %23 -%164 = OpTypeVector %157 2 -%174 = OpConstantNull %23 -%189 = OpConstantNull %23 -%202 = OpTypePointer UniformConstant %11 -%205 = OpTypeVector %4 3 -%243 = OpTypePointer UniformConstant %13 -%406 = OpTypePointer UniformConstant %17 -%67 = OpFunction %2 None %68 -%60 = OpLabel -%51 = OpVariable %52 Function %53 -%57 = OpVariable %58 Function %59 -%48 = OpVariable %49 Function %50 -%54 = OpVariable %55 Function %56 -%64 = OpLoad %5 %62 -%61 = OpCompositeConstruct %22 %64 -%71 = OpAccessChain %69 %45 %70 -OpBranch %74 -%74 = OpLabel -%76 = OpAccessChain %75 %71 %70 -%77 = OpLoad %5 %76 -%78 = OpCompositeExtract %5 %61 0 -OpStore %48 %70 -%79 = OpCompositeConstruct %24 %70 %70 -OpStore %51 %79 -OpStore %54 %72 -%80 = OpCompositeConstruct %23 %72 %72 %72 %72 -OpStore %57 %80 -%81 = OpCompositeConstruct %25 %72 %72 +%11 = OpConstant %5 5 +%10 = OpTypeArray %7 %11 +%12 = OpTypeImage %8 2D 0 1 0 1 Unknown +%13 = OpTypeArray %12 %11 +%14 = OpTypeImage %8 2D 0 0 1 1 Unknown +%15 = OpTypeArray %14 %11 +%16 = OpTypeImage %8 2D 1 0 0 1 Unknown +%17 = OpTypeArray %16 %11 +%18 = OpTypeImage %8 2D 0 0 0 2 Rgba32f +%19 = OpTypeArray %18 %11 +%20 = OpTypeSampler +%21 = OpTypeArray %20 %11 +%22 = OpTypeArray %20 %11 +%23 = OpTypeStruct %5 +%24 = OpTypeVector %8 4 +%25 = OpTypeVector %5 2 +%26 = OpTypeVector %8 2 +%27 = OpTypeVector %4 2 +%31 = OpConstant %5 10 +%30 = OpTypeArray %7 %31 +%29 = OpTypePointer UniformConstant %30 +%28 = OpVariable %29 UniformConstant +%33 = OpTypePointer UniformConstant %10 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer UniformConstant %13 +%34 = OpVariable %35 UniformConstant +%37 = OpTypePointer UniformConstant %15 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %17 +%38 = OpVariable %39 UniformConstant +%41 = OpTypePointer UniformConstant %19 +%40 = OpVariable %41 UniformConstant +%43 = OpTypePointer UniformConstant %21 +%42 = OpVariable %43 UniformConstant +%45 = OpTypePointer UniformConstant %22 +%44 = OpVariable %45 UniformConstant +%47 = OpTypeStruct %6 +%48 = OpTypePointer Uniform %47 +%46 = OpVariable %48 Uniform +%50 = OpTypePointer Function %5 +%51 = OpConstantNull %5 +%53 = OpTypePointer Function %25 +%54 = OpConstantNull %25 +%56 = OpTypePointer Function %8 +%57 = OpConstantNull %8 +%59 = OpTypePointer Function %24 +%60 = OpConstantNull %24 +%64 = OpTypePointer Input %5 +%63 = OpVariable %64 Input +%67 = OpTypePointer Output %24 +%66 = OpVariable %67 Output +%69 = OpTypeFunction %2 +%70 = OpTypePointer Uniform %6 +%71 = OpConstant %5 0 +%73 = OpConstant %8 0.0 +%74 = OpConstant %4 0 +%76 = OpTypePointer Uniform %5 +%84 = OpTypePointer UniformConstant %7 +%105 = OpTypePointer UniformConstant %20 +%108 = OpTypeSampledImage %7 +%129 = OpTypePointer UniformConstant %16 +%132 = OpTypePointer UniformConstant %20 +%135 = OpTypeSampledImage %16 +%158 = OpTypeBool +%159 = OpConstantNull %24 +%165 = OpTypeVector %158 2 +%175 = OpConstantNull %24 +%190 = OpConstantNull %24 +%203 = OpTypePointer UniformConstant %12 +%206 = OpTypeVector %4 3 +%244 = OpTypePointer UniformConstant %14 +%407 = OpTypePointer UniformConstant %18 +%68 = OpFunction %2 None %69 +%61 = OpLabel +%52 = OpVariable %53 Function %54 +%58 = OpVariable %59 Function %60 +%49 = OpVariable %50 Function %51 +%55 = OpVariable %56 Function %57 +%65 = OpLoad %5 %63 +%62 = OpCompositeConstruct %23 %65 +%72 = OpAccessChain %70 %46 %71 +OpBranch %75 +%75 = OpLabel +%77 = OpAccessChain %76 %72 %71 +%78 = OpLoad %5 %77 +%79 = OpCompositeExtract %5 %62 0 +OpStore %49 %71 +%80 = OpCompositeConstruct %25 %71 %71 +OpStore %52 %80 +OpStore %55 %73 +%81 = OpCompositeConstruct %24 %73 %73 %73 %73 +OpStore %58 %81 %82 = OpCompositeConstruct %26 %73 %73 -%84 = OpAccessChain %83 %27 %70 -%85 = OpLoad %7 %84 -%86 = OpImageQuerySizeLod %26 %85 %70 -%87 = OpBitcast %24 %86 -%88 = OpLoad %24 %51 -%89 = OpIAdd %24 %88 %87 -OpStore %51 %89 -%90 = OpAccessChain %83 %27 %77 -%91 = OpLoad %7 %90 -%92 = OpImageQuerySizeLod %26 %91 %70 -%93 = OpBitcast %24 %92 -%94 = OpLoad %24 %51 -%95 = OpIAdd %24 %94 %93 -OpStore %51 %95 -%96 = OpAccessChain %83 %27 %78 -%97 = OpLoad %7 %96 -%98 = OpImageQuerySizeLod %26 %97 %70 -%99 = OpBitcast %24 %98 -%100 = OpLoad %24 %51 -%101 = OpIAdd %24 %100 %99 -OpStore %51 %101 -%102 = OpAccessChain %83 %31 %70 -%103 = OpLoad %7 %102 -%105 = OpAccessChain %104 %41 %70 -%106 = OpLoad %19 %105 -%108 = OpSampledImage %107 %103 %106 -%109 = OpImageGather %23 %108 %81 %70 -%110 = OpLoad %23 %57 -%111 = OpFAdd %23 %110 %109 -OpStore %57 %111 -%112 = OpAccessChain %83 %31 %77 -%113 = OpLoad %7 %112 -%114 = OpAccessChain %104 %41 %77 -%115 = OpLoad %19 %114 -%116 = OpSampledImage %107 %113 %115 -%117 = OpImageGather %23 %116 %81 %70 -%118 = OpLoad %23 %57 -%119 = OpFAdd %23 %118 %117 -OpStore %57 %119 -%120 = OpAccessChain %83 %31 %78 -%121 = OpLoad %7 %120 -%122 = OpAccessChain %104 %41 %78 -%123 = OpLoad %19 %122 -%124 = OpSampledImage %107 %121 %123 -%125 = OpImageGather %23 %124 %81 %70 -%126 = OpLoad %23 %57 -%127 = OpFAdd %23 %126 %125 -OpStore %57 %127 -%129 = OpAccessChain %128 %37 %70 -%130 = OpLoad %15 %129 -%132 = OpAccessChain %131 %43 %70 -%133 = OpLoad %19 %132 -%135 = OpSampledImage %134 %130 %133 -%136 = OpImageDrefGather %23 %135 %81 %72 -%137 = OpLoad %23 %57 -%138 = OpFAdd %23 %137 %136 -OpStore %57 %138 -%139 = OpAccessChain %128 %37 %77 -%140 = OpLoad %15 %139 -%141 = OpAccessChain %131 %43 %77 -%142 = OpLoad %19 %141 -%143 = OpSampledImage %134 %140 %142 -%144 = OpImageDrefGather %23 %143 %81 %72 -%145 = OpLoad %23 %57 -%146 = OpFAdd %23 %145 %144 -OpStore %57 %146 -%147 = OpAccessChain %128 %37 %78 -%148 = OpLoad %15 %147 -%149 = OpAccessChain %131 %43 %78 -%150 = OpLoad %19 %149 -%151 = OpSampledImage %134 %148 %150 -%152 = OpImageDrefGather %23 %151 %81 %72 -%153 = OpLoad %23 %57 -%154 = OpFAdd %23 %153 %152 -OpStore %57 %154 -%155 = OpAccessChain %83 %27 %70 -%156 = OpLoad %7 %155 -%159 = OpImageQueryLevels %4 %156 -%160 = OpULessThan %157 %73 %159 -OpSelectionMerge %161 None -OpBranchConditional %160 %162 %161 +%83 = OpCompositeConstruct %27 %74 %74 +%85 = OpAccessChain %84 %28 %71 +%86 = OpLoad %7 %85 +%87 = OpImageQuerySizeLod %27 %86 %71 +%88 = OpBitcast %25 %87 +%89 = OpLoad %25 %52 +%90 = OpIAdd %25 %89 %88 +OpStore %52 %90 +%91 = OpAccessChain %84 %28 %78 +%92 = OpLoad %7 %91 +%93 = OpImageQuerySizeLod %27 %92 %71 +%94 = OpBitcast %25 %93 +%95 = OpLoad %25 %52 +%96 = OpIAdd %25 %95 %94 +OpStore %52 %96 +%97 = OpAccessChain %84 %28 %79 +%98 = OpLoad %7 %97 +%99 = OpImageQuerySizeLod %27 %98 %71 +%100 = OpBitcast %25 %99 +%101 = OpLoad %25 %52 +%102 = OpIAdd %25 %101 %100 +OpStore %52 %102 +%103 = OpAccessChain %84 %32 %71 +%104 = OpLoad %7 %103 +%106 = OpAccessChain %105 %42 %71 +%107 = OpLoad %20 %106 +%109 = OpSampledImage %108 %104 %107 +%110 = OpImageGather %24 %109 %82 %71 +%111 = OpLoad %24 %58 +%112 = OpFAdd %24 %111 %110 +OpStore %58 %112 +%113 = OpAccessChain %84 %32 %78 +%114 = OpLoad %7 %113 +%115 = OpAccessChain %105 %42 %78 +%116 = OpLoad %20 %115 +%117 = OpSampledImage %108 %114 %116 +%118 = OpImageGather %24 %117 %82 %71 +%119 = OpLoad %24 %58 +%120 = OpFAdd %24 %119 %118 +OpStore %58 %120 +%121 = OpAccessChain %84 %32 %79 +%122 = OpLoad %7 %121 +%123 = OpAccessChain %105 %42 %79 +%124 = OpLoad %20 %123 +%125 = OpSampledImage %108 %122 %124 +%126 = OpImageGather %24 %125 %82 %71 +%127 = OpLoad %24 %58 +%128 = OpFAdd %24 %127 %126 +OpStore %58 %128 +%130 = OpAccessChain %129 %38 %71 +%131 = OpLoad %16 %130 +%133 = OpAccessChain %132 %44 %71 +%134 = OpLoad %20 %133 +%136 = OpSampledImage %135 %131 %134 +%137 = OpImageDrefGather %24 %136 %82 %73 +%138 = OpLoad %24 %58 +%139 = OpFAdd %24 %138 %137 +OpStore %58 %139 +%140 = OpAccessChain %129 %38 %78 +%141 = OpLoad %16 %140 +%142 = OpAccessChain %132 %44 %78 +%143 = OpLoad %20 %142 +%144 = OpSampledImage %135 %141 %143 +%145 = OpImageDrefGather %24 %144 %82 %73 +%146 = OpLoad %24 %58 +%147 = OpFAdd %24 %146 %145 +OpStore %58 %147 +%148 = OpAccessChain %129 %38 %79 +%149 = OpLoad %16 %148 +%150 = OpAccessChain %132 %44 %79 +%151 = OpLoad %20 %150 +%152 = OpSampledImage %135 %149 %151 +%153 = OpImageDrefGather %24 %152 %82 %73 +%154 = OpLoad %24 %58 +%155 = OpFAdd %24 %154 %153 +OpStore %58 %155 +%156 = OpAccessChain %84 %28 %71 +%157 = OpLoad %7 %156 +%160 = OpImageQueryLevels %4 %157 +%161 = OpULessThan %158 %74 %160 +OpSelectionMerge %162 None +OpBranchConditional %161 %163 %162 +%163 = OpLabel +%164 = OpImageQuerySizeLod %27 %157 %74 +%166 = OpULessThan %165 %83 %164 +%167 = OpAll %158 %166 +OpBranchConditional %167 %168 %162 +%168 = OpLabel +%169 = OpImageFetch %24 %157 %83 Lod %74 +OpBranch %162 %162 = OpLabel -%163 = OpImageQuerySizeLod %26 %156 %73 -%165 = OpULessThan %164 %82 %163 -%166 = OpAll %157 %165 -OpBranchConditional %166 %167 %161 -%167 = OpLabel -%168 = OpImageFetch %23 %156 %82 Lod %73 -OpBranch %161 -%161 = OpLabel -%169 = OpPhi %23 %158 %74 %158 %162 %168 %167 -%170 = OpLoad %23 %57 -%171 = OpFAdd %23 %170 %169 -OpStore %57 %171 -%172 = OpAccessChain %83 %27 %77 -%173 = OpLoad %7 %172 -%175 = OpImageQueryLevels %4 %173 -%176 = OpULessThan %157 %73 %175 -OpSelectionMerge %177 None -OpBranchConditional %176 %178 %177 +%170 = OpPhi %24 %159 %75 %159 %163 %169 %168 +%171 = OpLoad %24 %58 +%172 = OpFAdd %24 %171 %170 +OpStore %58 %172 +%173 = OpAccessChain %84 %28 %78 +%174 = OpLoad %7 %173 +%176 = OpImageQueryLevels %4 %174 +%177 = OpULessThan %158 %74 %176 +OpSelectionMerge %178 None +OpBranchConditional %177 %179 %178 +%179 = OpLabel +%180 = OpImageQuerySizeLod %27 %174 %74 +%181 = OpULessThan %165 %83 %180 +%182 = OpAll %158 %181 +OpBranchConditional %182 %183 %178 +%183 = OpLabel +%184 = OpImageFetch %24 %174 %83 Lod %74 +OpBranch %178 %178 = OpLabel -%179 = OpImageQuerySizeLod %26 %173 %73 -%180 = OpULessThan %164 %82 %179 -%181 = OpAll %157 %180 -OpBranchConditional %181 %182 %177 -%182 = OpLabel -%183 = OpImageFetch %23 %173 %82 Lod %73 -OpBranch %177 -%177 = OpLabel -%184 = OpPhi %23 %174 %161 %174 %178 %183 %182 -%185 = OpLoad %23 %57 -%186 = OpFAdd %23 %185 %184 -OpStore %57 %186 -%187 = OpAccessChain %83 %27 %78 -%188 = OpLoad %7 %187 -%190 = OpImageQueryLevels %4 %188 -%191 = OpULessThan %157 %73 %190 -OpSelectionMerge %192 None -OpBranchConditional %191 %193 %192 +%185 = OpPhi %24 %175 %162 %175 %179 %184 %183 +%186 = OpLoad %24 %58 +%187 = OpFAdd %24 %186 %185 +OpStore %58 %187 +%188 = OpAccessChain %84 %28 %79 +%189 = OpLoad %7 %188 +%191 = OpImageQueryLevels %4 %189 +%192 = OpULessThan %158 %74 %191 +OpSelectionMerge %193 None +OpBranchConditional %192 %194 %193 +%194 = OpLabel +%195 = OpImageQuerySizeLod %27 %189 %74 +%196 = OpULessThan %165 %83 %195 +%197 = OpAll %158 %196 +OpBranchConditional %197 %198 %193 +%198 = OpLabel +%199 = OpImageFetch %24 %189 %83 Lod %74 +OpBranch %193 %193 = OpLabel -%194 = OpImageQuerySizeLod %26 %188 %73 -%195 = OpULessThan %164 %82 %194 -%196 = OpAll %157 %195 -OpBranchConditional %196 %197 %192 -%197 = OpLabel -%198 = OpImageFetch %23 %188 %82 Lod %73 -OpBranch %192 -%192 = OpLabel -%199 = OpPhi %23 %189 %177 %189 %193 %198 %197 -%200 = OpLoad %23 %57 -%201 = OpFAdd %23 %200 %199 -OpStore %57 %201 -%203 = OpAccessChain %202 %33 %70 -%204 = OpLoad %11 %203 -%206 = OpImageQuerySizeLod %205 %204 %70 -%207 = OpCompositeExtract %4 %206 2 -%208 = OpBitcast %5 %207 -%209 = OpLoad %5 %48 -%210 = OpIAdd %5 %209 %208 -OpStore %48 %210 -%211 = OpAccessChain %202 %33 %77 -%212 = OpLoad %11 %211 -%213 = OpImageQuerySizeLod %205 %212 %70 -%214 = OpCompositeExtract %4 %213 2 -%215 = OpBitcast %5 %214 -%216 = OpLoad %5 %48 -%217 = OpIAdd %5 %216 %215 -OpStore %48 %217 -%218 = OpAccessChain %202 %33 %78 -%219 = OpLoad %11 %218 -%220 = OpImageQuerySizeLod %205 %219 %70 -%221 = OpCompositeExtract %4 %220 2 -%222 = OpBitcast %5 %221 -%223 = OpLoad %5 %48 -%224 = OpIAdd %5 %223 %222 -OpStore %48 %224 -%225 = OpAccessChain %83 %31 %70 -%226 = OpLoad %7 %225 -%227 = OpImageQueryLevels %4 %226 -%228 = OpBitcast %5 %227 -%229 = OpLoad %5 %48 -%230 = OpIAdd %5 %229 %228 -OpStore %48 %230 -%231 = OpAccessChain %83 %31 %77 -%232 = OpLoad %7 %231 -%233 = OpImageQueryLevels %4 %232 -%234 = OpBitcast %5 %233 -%235 = OpLoad %5 %48 -%236 = OpIAdd %5 %235 %234 -OpStore %48 %236 -%237 = OpAccessChain %83 %31 %78 -%238 = OpLoad %7 %237 -%239 = OpImageQueryLevels %4 %238 -%240 = OpBitcast %5 %239 -%241 = OpLoad %5 %48 -%242 = OpIAdd %5 %241 %240 -OpStore %48 %242 -%244 = OpAccessChain %243 %35 %70 -%245 = OpLoad %13 %244 -%246 = OpImageQuerySamples %4 %245 -%247 = OpBitcast %5 %246 -%248 = OpLoad %5 %48 -%249 = OpIAdd %5 %248 %247 -OpStore %48 %249 -%250 = OpAccessChain %243 %35 %77 -%251 = OpLoad %13 %250 -%252 = OpImageQuerySamples %4 %251 -%253 = OpBitcast %5 %252 -%254 = OpLoad %5 %48 -%255 = OpIAdd %5 %254 %253 -OpStore %48 %255 -%256 = OpAccessChain %243 %35 %78 -%257 = OpLoad %13 %256 -%258 = OpImageQuerySamples %4 %257 -%259 = OpBitcast %5 %258 -%260 = OpLoad %5 %48 -%261 = OpIAdd %5 %260 %259 -OpStore %48 %261 -%262 = OpAccessChain %83 %31 %70 -%263 = OpLoad %7 %262 -%264 = OpAccessChain %104 %41 %70 -%265 = OpLoad %19 %264 -%266 = OpSampledImage %107 %263 %265 -%267 = OpImageSampleImplicitLod %23 %266 %81 -%268 = OpLoad %23 %57 -%269 = OpFAdd %23 %268 %267 -OpStore %57 %269 -%270 = OpAccessChain %83 %31 %77 -%271 = OpLoad %7 %270 -%272 = OpAccessChain %104 %41 %77 -%273 = OpLoad %19 %272 -%274 = OpSampledImage %107 %271 %273 -%275 = OpImageSampleImplicitLod %23 %274 %81 -%276 = OpLoad %23 %57 -%277 = OpFAdd %23 %276 %275 -OpStore %57 %277 -%278 = OpAccessChain %83 %31 %78 -%279 = OpLoad %7 %278 -%280 = OpAccessChain %104 %41 %78 -%281 = OpLoad %19 %280 -%282 = OpSampledImage %107 %279 %281 -%283 = OpImageSampleImplicitLod %23 %282 %81 -%284 = OpLoad %23 %57 -%285 = OpFAdd %23 %284 %283 -OpStore %57 %285 -%286 = OpAccessChain %83 %31 %70 -%287 = OpLoad %7 %286 -%288 = OpAccessChain %104 %41 %70 -%289 = OpLoad %19 %288 -%290 = OpSampledImage %107 %287 %289 -%291 = OpImageSampleImplicitLod %23 %290 %81 Bias %72 -%292 = OpLoad %23 %57 -%293 = OpFAdd %23 %292 %291 -OpStore %57 %293 -%294 = OpAccessChain %83 %31 %77 -%295 = OpLoad %7 %294 -%296 = OpAccessChain %104 %41 %77 -%297 = OpLoad %19 %296 -%298 = OpSampledImage %107 %295 %297 -%299 = OpImageSampleImplicitLod %23 %298 %81 Bias %72 -%300 = OpLoad %23 %57 -%301 = OpFAdd %23 %300 %299 -OpStore %57 %301 -%302 = OpAccessChain %83 %31 %78 -%303 = OpLoad %7 %302 -%304 = OpAccessChain %104 %41 %78 -%305 = OpLoad %19 %304 -%306 = OpSampledImage %107 %303 %305 -%307 = OpImageSampleImplicitLod %23 %306 %81 Bias %72 -%308 = OpLoad %23 %57 -%309 = OpFAdd %23 %308 %307 -OpStore %57 %309 -%310 = OpAccessChain %128 %37 %70 -%311 = OpLoad %15 %310 -%312 = OpAccessChain %131 %43 %70 -%313 = OpLoad %19 %312 -%314 = OpSampledImage %134 %311 %313 -%315 = OpImageSampleDrefImplicitLod %8 %314 %81 %72 -%316 = OpLoad %8 %54 -%317 = OpFAdd %8 %316 %315 -OpStore %54 %317 -%318 = OpAccessChain %128 %37 %77 -%319 = OpLoad %15 %318 -%320 = OpAccessChain %131 %43 %77 -%321 = OpLoad %19 %320 -%322 = OpSampledImage %134 %319 %321 -%323 = OpImageSampleDrefImplicitLod %8 %322 %81 %72 -%324 = OpLoad %8 %54 -%325 = OpFAdd %8 %324 %323 -OpStore %54 %325 -%326 = OpAccessChain %128 %37 %78 -%327 = OpLoad %15 %326 -%328 = OpAccessChain %131 %43 %78 -%329 = OpLoad %19 %328 -%330 = OpSampledImage %134 %327 %329 -%331 = OpImageSampleDrefImplicitLod %8 %330 %81 %72 -%332 = OpLoad %8 %54 -%333 = OpFAdd %8 %332 %331 -OpStore %54 %333 -%334 = OpAccessChain %128 %37 %70 -%335 = OpLoad %15 %334 -%336 = OpAccessChain %131 %43 %70 -%337 = OpLoad %19 %336 -%338 = OpSampledImage %134 %335 %337 -%339 = OpImageSampleDrefExplicitLod %8 %338 %81 %72 Lod %72 -%340 = OpLoad %8 %54 -%341 = OpFAdd %8 %340 %339 -OpStore %54 %341 -%342 = OpAccessChain %128 %37 %77 -%343 = OpLoad %15 %342 -%344 = OpAccessChain %131 %43 %77 -%345 = OpLoad %19 %344 -%346 = OpSampledImage %134 %343 %345 -%347 = OpImageSampleDrefExplicitLod %8 %346 %81 %72 Lod %72 -%348 = OpLoad %8 %54 -%349 = OpFAdd %8 %348 %347 -OpStore %54 %349 -%350 = OpAccessChain %128 %37 %78 -%351 = OpLoad %15 %350 -%352 = OpAccessChain %131 %43 %78 -%353 = OpLoad %19 %352 -%354 = OpSampledImage %134 %351 %353 -%355 = OpImageSampleDrefExplicitLod %8 %354 %81 %72 Lod %72 -%356 = OpLoad %8 %54 -%357 = OpFAdd %8 %356 %355 -OpStore %54 %357 -%358 = OpAccessChain %83 %31 %70 -%359 = OpLoad %7 %358 -%360 = OpAccessChain %104 %41 %70 -%361 = OpLoad %19 %360 -%362 = OpSampledImage %107 %359 %361 -%363 = OpImageSampleExplicitLod %23 %362 %81 Grad %81 %81 -%364 = OpLoad %23 %57 -%365 = OpFAdd %23 %364 %363 -OpStore %57 %365 -%366 = OpAccessChain %83 %31 %77 -%367 = OpLoad %7 %366 -%368 = OpAccessChain %104 %41 %77 -%369 = OpLoad %19 %368 -%370 = OpSampledImage %107 %367 %369 -%371 = OpImageSampleExplicitLod %23 %370 %81 Grad %81 %81 -%372 = OpLoad %23 %57 -%373 = OpFAdd %23 %372 %371 -OpStore %57 %373 -%374 = OpAccessChain %83 %31 %78 -%375 = OpLoad %7 %374 -%376 = OpAccessChain %104 %41 %78 -%377 = OpLoad %19 %376 -%378 = OpSampledImage %107 %375 %377 -%379 = OpImageSampleExplicitLod %23 %378 %81 Grad %81 %81 -%380 = OpLoad %23 %57 -%381 = OpFAdd %23 %380 %379 -OpStore %57 %381 -%382 = OpAccessChain %83 %31 %70 -%383 = OpLoad %7 %382 -%384 = OpAccessChain %104 %41 %70 -%385 = OpLoad %19 %384 -%386 = OpSampledImage %107 %383 %385 -%387 = OpImageSampleExplicitLod %23 %386 %81 Lod %72 -%388 = OpLoad %23 %57 -%389 = OpFAdd %23 %388 %387 -OpStore %57 %389 -%390 = OpAccessChain %83 %31 %77 -%391 = OpLoad %7 %390 -%392 = OpAccessChain %104 %41 %77 -%393 = OpLoad %19 %392 -%394 = OpSampledImage %107 %391 %393 -%395 = OpImageSampleExplicitLod %23 %394 %81 Lod %72 -%396 = OpLoad %23 %57 -%397 = OpFAdd %23 %396 %395 -OpStore %57 %397 -%398 = OpAccessChain %83 %31 %78 -%399 = OpLoad %7 %398 -%400 = OpAccessChain %104 %41 %78 -%401 = OpLoad %19 %400 -%402 = OpSampledImage %107 %399 %401 -%403 = OpImageSampleExplicitLod %23 %402 %81 Lod %72 -%404 = OpLoad %23 %57 -%405 = OpFAdd %23 %404 %403 -OpStore %57 %405 -%407 = OpAccessChain %406 %39 %70 -%408 = OpLoad %17 %407 -%409 = OpLoad %23 %57 -%410 = OpImageQuerySize %26 %408 -%411 = OpULessThan %164 %82 %410 -%412 = OpAll %157 %411 -OpSelectionMerge %413 None -OpBranchConditional %412 %414 %413 +%200 = OpPhi %24 %190 %178 %190 %194 %199 %198 +%201 = OpLoad %24 %58 +%202 = OpFAdd %24 %201 %200 +OpStore %58 %202 +%204 = OpAccessChain %203 %34 %71 +%205 = OpLoad %12 %204 +%207 = OpImageQuerySizeLod %206 %205 %71 +%208 = OpCompositeExtract %4 %207 2 +%209 = OpBitcast %5 %208 +%210 = OpLoad %5 %49 +%211 = OpIAdd %5 %210 %209 +OpStore %49 %211 +%212 = OpAccessChain %203 %34 %78 +%213 = OpLoad %12 %212 +%214 = OpImageQuerySizeLod %206 %213 %71 +%215 = OpCompositeExtract %4 %214 2 +%216 = OpBitcast %5 %215 +%217 = OpLoad %5 %49 +%218 = OpIAdd %5 %217 %216 +OpStore %49 %218 +%219 = OpAccessChain %203 %34 %79 +%220 = OpLoad %12 %219 +%221 = OpImageQuerySizeLod %206 %220 %71 +%222 = OpCompositeExtract %4 %221 2 +%223 = OpBitcast %5 %222 +%224 = OpLoad %5 %49 +%225 = OpIAdd %5 %224 %223 +OpStore %49 %225 +%226 = OpAccessChain %84 %32 %71 +%227 = OpLoad %7 %226 +%228 = OpImageQueryLevels %4 %227 +%229 = OpBitcast %5 %228 +%230 = OpLoad %5 %49 +%231 = OpIAdd %5 %230 %229 +OpStore %49 %231 +%232 = OpAccessChain %84 %32 %78 +%233 = OpLoad %7 %232 +%234 = OpImageQueryLevels %4 %233 +%235 = OpBitcast %5 %234 +%236 = OpLoad %5 %49 +%237 = OpIAdd %5 %236 %235 +OpStore %49 %237 +%238 = OpAccessChain %84 %32 %79 +%239 = OpLoad %7 %238 +%240 = OpImageQueryLevels %4 %239 +%241 = OpBitcast %5 %240 +%242 = OpLoad %5 %49 +%243 = OpIAdd %5 %242 %241 +OpStore %49 %243 +%245 = OpAccessChain %244 %36 %71 +%246 = OpLoad %14 %245 +%247 = OpImageQuerySamples %4 %246 +%248 = OpBitcast %5 %247 +%249 = OpLoad %5 %49 +%250 = OpIAdd %5 %249 %248 +OpStore %49 %250 +%251 = OpAccessChain %244 %36 %78 +%252 = OpLoad %14 %251 +%253 = OpImageQuerySamples %4 %252 +%254 = OpBitcast %5 %253 +%255 = OpLoad %5 %49 +%256 = OpIAdd %5 %255 %254 +OpStore %49 %256 +%257 = OpAccessChain %244 %36 %79 +%258 = OpLoad %14 %257 +%259 = OpImageQuerySamples %4 %258 +%260 = OpBitcast %5 %259 +%261 = OpLoad %5 %49 +%262 = OpIAdd %5 %261 %260 +OpStore %49 %262 +%263 = OpAccessChain %84 %32 %71 +%264 = OpLoad %7 %263 +%265 = OpAccessChain %105 %42 %71 +%266 = OpLoad %20 %265 +%267 = OpSampledImage %108 %264 %266 +%268 = OpImageSampleImplicitLod %24 %267 %82 +%269 = OpLoad %24 %58 +%270 = OpFAdd %24 %269 %268 +OpStore %58 %270 +%271 = OpAccessChain %84 %32 %78 +%272 = OpLoad %7 %271 +%273 = OpAccessChain %105 %42 %78 +%274 = OpLoad %20 %273 +%275 = OpSampledImage %108 %272 %274 +%276 = OpImageSampleImplicitLod %24 %275 %82 +%277 = OpLoad %24 %58 +%278 = OpFAdd %24 %277 %276 +OpStore %58 %278 +%279 = OpAccessChain %84 %32 %79 +%280 = OpLoad %7 %279 +%281 = OpAccessChain %105 %42 %79 +%282 = OpLoad %20 %281 +%283 = OpSampledImage %108 %280 %282 +%284 = OpImageSampleImplicitLod %24 %283 %82 +%285 = OpLoad %24 %58 +%286 = OpFAdd %24 %285 %284 +OpStore %58 %286 +%287 = OpAccessChain %84 %32 %71 +%288 = OpLoad %7 %287 +%289 = OpAccessChain %105 %42 %71 +%290 = OpLoad %20 %289 +%291 = OpSampledImage %108 %288 %290 +%292 = OpImageSampleImplicitLod %24 %291 %82 Bias %73 +%293 = OpLoad %24 %58 +%294 = OpFAdd %24 %293 %292 +OpStore %58 %294 +%295 = OpAccessChain %84 %32 %78 +%296 = OpLoad %7 %295 +%297 = OpAccessChain %105 %42 %78 +%298 = OpLoad %20 %297 +%299 = OpSampledImage %108 %296 %298 +%300 = OpImageSampleImplicitLod %24 %299 %82 Bias %73 +%301 = OpLoad %24 %58 +%302 = OpFAdd %24 %301 %300 +OpStore %58 %302 +%303 = OpAccessChain %84 %32 %79 +%304 = OpLoad %7 %303 +%305 = OpAccessChain %105 %42 %79 +%306 = OpLoad %20 %305 +%307 = OpSampledImage %108 %304 %306 +%308 = OpImageSampleImplicitLod %24 %307 %82 Bias %73 +%309 = OpLoad %24 %58 +%310 = OpFAdd %24 %309 %308 +OpStore %58 %310 +%311 = OpAccessChain %129 %38 %71 +%312 = OpLoad %16 %311 +%313 = OpAccessChain %132 %44 %71 +%314 = OpLoad %20 %313 +%315 = OpSampledImage %135 %312 %314 +%316 = OpImageSampleDrefImplicitLod %8 %315 %82 %73 +%317 = OpLoad %8 %55 +%318 = OpFAdd %8 %317 %316 +OpStore %55 %318 +%319 = OpAccessChain %129 %38 %78 +%320 = OpLoad %16 %319 +%321 = OpAccessChain %132 %44 %78 +%322 = OpLoad %20 %321 +%323 = OpSampledImage %135 %320 %322 +%324 = OpImageSampleDrefImplicitLod %8 %323 %82 %73 +%325 = OpLoad %8 %55 +%326 = OpFAdd %8 %325 %324 +OpStore %55 %326 +%327 = OpAccessChain %129 %38 %79 +%328 = OpLoad %16 %327 +%329 = OpAccessChain %132 %44 %79 +%330 = OpLoad %20 %329 +%331 = OpSampledImage %135 %328 %330 +%332 = OpImageSampleDrefImplicitLod %8 %331 %82 %73 +%333 = OpLoad %8 %55 +%334 = OpFAdd %8 %333 %332 +OpStore %55 %334 +%335 = OpAccessChain %129 %38 %71 +%336 = OpLoad %16 %335 +%337 = OpAccessChain %132 %44 %71 +%338 = OpLoad %20 %337 +%339 = OpSampledImage %135 %336 %338 +%340 = OpImageSampleDrefExplicitLod %8 %339 %82 %73 Lod %73 +%341 = OpLoad %8 %55 +%342 = OpFAdd %8 %341 %340 +OpStore %55 %342 +%343 = OpAccessChain %129 %38 %78 +%344 = OpLoad %16 %343 +%345 = OpAccessChain %132 %44 %78 +%346 = OpLoad %20 %345 +%347 = OpSampledImage %135 %344 %346 +%348 = OpImageSampleDrefExplicitLod %8 %347 %82 %73 Lod %73 +%349 = OpLoad %8 %55 +%350 = OpFAdd %8 %349 %348 +OpStore %55 %350 +%351 = OpAccessChain %129 %38 %79 +%352 = OpLoad %16 %351 +%353 = OpAccessChain %132 %44 %79 +%354 = OpLoad %20 %353 +%355 = OpSampledImage %135 %352 %354 +%356 = OpImageSampleDrefExplicitLod %8 %355 %82 %73 Lod %73 +%357 = OpLoad %8 %55 +%358 = OpFAdd %8 %357 %356 +OpStore %55 %358 +%359 = OpAccessChain %84 %32 %71 +%360 = OpLoad %7 %359 +%361 = OpAccessChain %105 %42 %71 +%362 = OpLoad %20 %361 +%363 = OpSampledImage %108 %360 %362 +%364 = OpImageSampleExplicitLod %24 %363 %82 Grad %82 %82 +%365 = OpLoad %24 %58 +%366 = OpFAdd %24 %365 %364 +OpStore %58 %366 +%367 = OpAccessChain %84 %32 %78 +%368 = OpLoad %7 %367 +%369 = OpAccessChain %105 %42 %78 +%370 = OpLoad %20 %369 +%371 = OpSampledImage %108 %368 %370 +%372 = OpImageSampleExplicitLod %24 %371 %82 Grad %82 %82 +%373 = OpLoad %24 %58 +%374 = OpFAdd %24 %373 %372 +OpStore %58 %374 +%375 = OpAccessChain %84 %32 %79 +%376 = OpLoad %7 %375 +%377 = OpAccessChain %105 %42 %79 +%378 = OpLoad %20 %377 +%379 = OpSampledImage %108 %376 %378 +%380 = OpImageSampleExplicitLod %24 %379 %82 Grad %82 %82 +%381 = OpLoad %24 %58 +%382 = OpFAdd %24 %381 %380 +OpStore %58 %382 +%383 = OpAccessChain %84 %32 %71 +%384 = OpLoad %7 %383 +%385 = OpAccessChain %105 %42 %71 +%386 = OpLoad %20 %385 +%387 = OpSampledImage %108 %384 %386 +%388 = OpImageSampleExplicitLod %24 %387 %82 Lod %73 +%389 = OpLoad %24 %58 +%390 = OpFAdd %24 %389 %388 +OpStore %58 %390 +%391 = OpAccessChain %84 %32 %78 +%392 = OpLoad %7 %391 +%393 = OpAccessChain %105 %42 %78 +%394 = OpLoad %20 %393 +%395 = OpSampledImage %108 %392 %394 +%396 = OpImageSampleExplicitLod %24 %395 %82 Lod %73 +%397 = OpLoad %24 %58 +%398 = OpFAdd %24 %397 %396 +OpStore %58 %398 +%399 = OpAccessChain %84 %32 %79 +%400 = OpLoad %7 %399 +%401 = OpAccessChain %105 %42 %79 +%402 = OpLoad %20 %401 +%403 = OpSampledImage %108 %400 %402 +%404 = OpImageSampleExplicitLod %24 %403 %82 Lod %73 +%405 = OpLoad %24 %58 +%406 = OpFAdd %24 %405 %404 +OpStore %58 %406 +%408 = OpAccessChain %407 %40 %71 +%409 = OpLoad %18 %408 +%410 = OpLoad %24 %58 +%411 = OpImageQuerySize %27 %409 +%412 = OpULessThan %165 %83 %411 +%413 = OpAll %158 %412 +OpSelectionMerge %414 None +OpBranchConditional %413 %415 %414 +%415 = OpLabel +OpImageWrite %409 %83 %410 +OpBranch %414 %414 = OpLabel -OpImageWrite %408 %82 %409 -OpBranch %413 -%413 = OpLabel -%415 = OpAccessChain %406 %39 %77 -%416 = OpLoad %17 %415 -%417 = OpLoad %23 %57 -%418 = OpImageQuerySize %26 %416 -%419 = OpULessThan %164 %82 %418 -%420 = OpAll %157 %419 -OpSelectionMerge %421 None -OpBranchConditional %420 %422 %421 +%416 = OpAccessChain %407 %40 %78 +%417 = OpLoad %18 %416 +%418 = OpLoad %24 %58 +%419 = OpImageQuerySize %27 %417 +%420 = OpULessThan %165 %83 %419 +%421 = OpAll %158 %420 +OpSelectionMerge %422 None +OpBranchConditional %421 %423 %422 +%423 = OpLabel +OpImageWrite %417 %83 %418 +OpBranch %422 %422 = OpLabel -OpImageWrite %416 %82 %417 -OpBranch %421 -%421 = OpLabel -%423 = OpAccessChain %406 %39 %78 -%424 = OpLoad %17 %423 -%425 = OpLoad %23 %57 -%426 = OpImageQuerySize %26 %424 -%427 = OpULessThan %164 %82 %426 -%428 = OpAll %157 %427 -OpSelectionMerge %429 None -OpBranchConditional %428 %430 %429 +%424 = OpAccessChain %407 %40 %79 +%425 = OpLoad %18 %424 +%426 = OpLoad %24 %58 +%427 = OpImageQuerySize %27 %425 +%428 = OpULessThan %165 %83 %427 +%429 = OpAll %158 %428 +OpSelectionMerge %430 None +OpBranchConditional %429 %431 %430 +%431 = OpLabel +OpImageWrite %425 %83 %426 +OpBranch %430 %430 = OpLabel -OpImageWrite %424 %82 %425 -OpBranch %429 -%429 = OpLabel -%431 = OpLoad %24 %51 -%432 = OpLoad %5 %48 -%433 = OpCompositeConstruct %24 %432 %432 -%434 = OpIAdd %24 %431 %433 -%435 = OpConvertUToF %25 %434 -%436 = OpLoad %23 %57 -%437 = OpCompositeExtract %8 %435 0 -%438 = OpCompositeExtract %8 %435 1 -%439 = OpCompositeExtract %8 %435 0 -%440 = OpCompositeExtract %8 %435 1 -%441 = OpCompositeConstruct %23 %437 %438 %439 %440 -%442 = OpFAdd %23 %436 %441 -%443 = OpLoad %8 %54 -%444 = OpCompositeConstruct %23 %443 %443 %443 %443 -%445 = OpFAdd %23 %442 %444 -OpStore %65 %445 +%432 = OpLoad %25 %52 +%433 = OpLoad %5 %49 +%434 = OpCompositeConstruct %25 %433 %433 +%435 = OpIAdd %25 %432 %434 +%436 = OpConvertUToF %26 %435 +%437 = OpLoad %24 %58 +%438 = OpCompositeExtract %8 %436 0 +%439 = OpCompositeExtract %8 %436 1 +%440 = OpCompositeExtract %8 %436 0 +%441 = OpCompositeExtract %8 %436 1 +%442 = OpCompositeConstruct %24 %438 %439 %440 %441 +%443 = OpFAdd %24 %437 %442 +%444 = OpLoad %8 %55 +%445 = OpCompositeConstruct %24 %444 %444 %444 %444 +%446 = OpFAdd %24 %443 %445 +OpStore %66 %446 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-buffer-arrays.spvasm b/tests/out/spv/binding-buffer-arrays.spvasm index 28f32415f..cd20c1dd7 100644 --- a/tests/out/spv/binding-buffer-arrays.spvasm +++ b/tests/out/spv/binding-buffer-arrays.spvasm @@ -8,22 +8,22 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %27 "main" %22 %25 -OpExecutionMode %27 OriginUpperLeft +OpEntryPoint Fragment %28 "main" %23 %26 +OpExecutionMode %28 OriginUpperLeft OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %9 0 Offset 0 -OpDecorate %10 NonWritable -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 0 +OpMemberDecorate %10 0 Offset 0 +OpDecorate %11 NonWritable +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 0 OpDecorate %7 Block -OpDecorate %14 DescriptorSet 0 -OpDecorate %14 Binding 10 -OpDecorate %15 Block -OpMemberDecorate %15 0 Offset 0 -OpDecorate %22 Location 0 -OpDecorate %22 Flat -OpDecorate %25 Location 0 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 10 +OpDecorate %16 Block +OpMemberDecorate %16 0 Offset 0 +OpDecorate %23 Location 0 +OpDecorate %23 Flat +OpDecorate %26 Location 0 OpDecorate %57 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 @@ -31,75 +31,75 @@ OpDecorate %57 NonUniform %5 = OpTypeInt 32 0 %6 = OpTypeStruct %5 %7 = OpTypeStruct %5 -%8 = OpTypeArray %7 %3 -%9 = OpTypeStruct %5 -%13 = OpConstant %5 10 -%12 = OpTypeArray %7 %13 -%11 = OpTypePointer StorageBuffer %12 -%10 = OpVariable %11 StorageBuffer -%15 = OpTypeStruct %6 -%16 = OpTypePointer Uniform %15 -%14 = OpVariable %16 Uniform -%18 = OpTypePointer Function %5 -%19 = OpConstantNull %5 -%23 = OpTypePointer Input %5 -%22 = OpVariable %23 Input -%26 = OpTypePointer Output %5 -%25 = OpVariable %26 Output -%28 = OpTypeFunction %2 -%29 = OpTypePointer Uniform %6 -%30 = OpConstant %5 0 -%32 = OpTypePointer StorageBuffer %8 -%33 = OpConstant %4 0 -%35 = OpTypePointer Uniform %5 -%39 = OpTypePointer StorageBuffer %7 -%40 = OpTypePointer StorageBuffer %5 -%45 = OpConstant %5 1 +%9 = OpConstant %5 1 +%8 = OpTypeArray %7 %9 +%10 = OpTypeStruct %5 +%14 = OpConstant %5 10 +%13 = OpTypeArray %7 %14 +%12 = OpTypePointer StorageBuffer %13 +%11 = OpVariable %12 StorageBuffer +%16 = OpTypeStruct %6 +%17 = OpTypePointer Uniform %16 +%15 = OpVariable %17 Uniform +%19 = OpTypePointer Function %5 +%20 = OpConstantNull %5 +%24 = OpTypePointer Input %5 +%23 = OpVariable %24 Input +%27 = OpTypePointer Output %5 +%26 = OpVariable %27 Output +%29 = OpTypeFunction %2 +%30 = OpTypePointer Uniform %6 +%31 = OpConstant %5 0 +%33 = OpTypePointer StorageBuffer %8 +%34 = OpConstant %4 0 +%36 = OpTypePointer Uniform %5 +%40 = OpTypePointer StorageBuffer %7 +%41 = OpTypePointer StorageBuffer %5 %47 = OpTypeBool %49 = OpConstantNull %5 %58 = OpConstantNull %5 -%27 = OpFunction %2 None %28 -%20 = OpLabel -%17 = OpVariable %18 Function %19 -%24 = OpLoad %5 %22 -%21 = OpCompositeConstruct %9 %24 -%31 = OpAccessChain %29 %14 %30 -OpBranch %34 -%34 = OpLabel -%36 = OpAccessChain %35 %31 %30 -%37 = OpLoad %5 %36 -%38 = OpCompositeExtract %5 %21 0 -OpStore %17 %30 -%41 = OpAccessChain %40 %10 %30 %30 -%42 = OpLoad %5 %41 -%43 = OpLoad %5 %17 -%44 = OpIAdd %5 %43 %42 -OpStore %17 %44 -%46 = OpULessThan %47 %37 %45 +%28 = OpFunction %2 None %29 +%21 = OpLabel +%18 = OpVariable %19 Function %20 +%25 = OpLoad %5 %23 +%22 = OpCompositeConstruct %10 %25 +%32 = OpAccessChain %30 %15 %31 +OpBranch %35 +%35 = OpLabel +%37 = OpAccessChain %36 %32 %31 +%38 = OpLoad %5 %37 +%39 = OpCompositeExtract %5 %22 0 +OpStore %18 %31 +%42 = OpAccessChain %41 %11 %31 %31 +%43 = OpLoad %5 %42 +%44 = OpLoad %5 %18 +%45 = OpIAdd %5 %44 %43 +OpStore %18 %45 +%46 = OpULessThan %47 %38 %9 OpSelectionMerge %50 None OpBranchConditional %46 %51 %50 %51 = OpLabel -%48 = OpAccessChain %40 %10 %37 %30 +%48 = OpAccessChain %41 %11 %38 %31 %52 = OpLoad %5 %48 OpBranch %50 %50 = OpLabel -%53 = OpPhi %5 %49 %34 %52 %51 -%54 = OpLoad %5 %17 +%53 = OpPhi %5 %49 %35 %52 %51 +%54 = OpLoad %5 %18 %55 = OpIAdd %5 %54 %53 -OpStore %17 %55 -%56 = OpULessThan %47 %38 %45 +OpStore %18 %55 +%56 = OpULessThan %47 %39 %9 OpSelectionMerge %59 None OpBranchConditional %56 %60 %59 %60 = OpLabel -%57 = OpAccessChain %40 %10 %38 %30 +%57 = OpAccessChain %41 %11 %39 %31 %61 = OpLoad %5 %57 OpBranch %59 %59 = OpLabel %62 = OpPhi %5 %58 %50 %61 %60 -%63 = OpLoad %5 %17 +%63 = OpLoad %5 %18 %64 = OpIAdd %5 %63 %62 -OpStore %17 %64 -%65 = OpLoad %5 %17 -OpStore %25 %65 +OpStore %18 %64 +%65 = OpLoad %5 %18 +OpStore %26 %65 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-restrict.spvasm b/tests/out/spv/bounds-check-restrict.spvasm index 7977495aa..bc0a00135 100644 --- a/tests/out/spv/bounds-check-restrict.spvasm +++ b/tests/out/spv/bounds-check-restrict.spvasm @@ -1,238 +1,239 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 166 +; Bound: 167 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpDecorate %6 ArrayStride 4 -OpDecorate %9 ArrayStride 4 -OpMemberDecorate %10 0 Offset 0 -OpMemberDecorate %10 1 Offset 48 -OpMemberDecorate %10 2 Offset 64 -OpMemberDecorate %10 2 ColMajor -OpMemberDecorate %10 2 MatrixStride 16 -OpMemberDecorate %10 3 Offset 112 -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 0 -OpDecorate %10 Block +OpDecorate %11 ArrayStride 4 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 48 +OpMemberDecorate %12 2 Offset 64 +OpMemberDecorate %12 2 ColMajor +OpMemberDecorate %12 2 MatrixStride 16 +OpMemberDecorate %12 3 Offset 112 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 0 +OpDecorate %12 Block %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 %5 = OpTypeFloat 32 -%6 = OpTypeArray %5 %3 -%7 = OpTypeVector %5 4 -%8 = OpTypeMatrix %7 3 -%9 = OpTypeRuntimeArray %5 -%10 = OpTypeStruct %6 %7 %8 %9 -%12 = OpTypePointer StorageBuffer %10 -%11 = OpVariable %12 StorageBuffer -%16 = OpTypeFunction %5 %4 -%18 = OpTypePointer StorageBuffer %6 -%19 = OpTypePointer StorageBuffer %5 -%21 = OpTypeInt 32 0 -%20 = OpConstant %21 9 -%23 = OpConstant %21 0 -%30 = OpTypePointer StorageBuffer %9 -%32 = OpConstant %21 1 -%35 = OpConstant %21 3 -%42 = OpTypePointer StorageBuffer %7 -%43 = OpTypePointer StorageBuffer %5 -%51 = OpTypeFunction %5 %7 %4 -%58 = OpTypeFunction %7 %4 -%60 = OpTypePointer StorageBuffer %8 -%61 = OpTypePointer StorageBuffer %7 -%62 = OpConstant %21 2 -%70 = OpTypeFunction %5 %4 %4 -%79 = OpConstant %5 100.0 -%91 = OpTypeFunction %5 -%92 = OpConstant %4 9 -%93 = OpConstant %4 3 -%94 = OpConstant %4 2 -%108 = OpTypeFunction %2 %4 %5 -%132 = OpTypeFunction %2 %4 %7 -%141 = OpTypeFunction %2 %4 %4 %5 -%161 = OpTypeFunction %2 %5 -%15 = OpFunction %5 None %16 -%14 = OpFunctionParameter %4 -%13 = OpLabel -OpBranch %17 -%17 = OpLabel -%22 = OpExtInst %21 %1 UMin %14 %20 -%24 = OpAccessChain %19 %11 %23 %22 -%25 = OpLoad %5 %24 -OpReturnValue %25 +%8 = OpTypeInt 32 0 +%7 = OpConstant %8 10 +%6 = OpTypeArray %5 %7 +%9 = OpTypeVector %5 4 +%10 = OpTypeMatrix %9 3 +%11 = OpTypeRuntimeArray %5 +%12 = OpTypeStruct %6 %9 %10 %11 +%14 = OpTypePointer StorageBuffer %12 +%13 = OpVariable %14 StorageBuffer +%18 = OpTypeFunction %5 %4 +%20 = OpTypePointer StorageBuffer %6 +%21 = OpTypePointer StorageBuffer %5 +%22 = OpConstant %8 9 +%24 = OpConstant %8 0 +%31 = OpTypePointer StorageBuffer %11 +%33 = OpConstant %8 1 +%36 = OpConstant %8 3 +%43 = OpTypePointer StorageBuffer %9 +%44 = OpTypePointer StorageBuffer %5 +%52 = OpTypeFunction %5 %9 %4 +%59 = OpTypeFunction %9 %4 +%61 = OpTypePointer StorageBuffer %10 +%62 = OpTypePointer StorageBuffer %9 +%63 = OpConstant %8 2 +%71 = OpTypeFunction %5 %4 %4 +%80 = OpConstant %5 100.0 +%92 = OpTypeFunction %5 +%93 = OpConstant %4 9 +%94 = OpConstant %4 3 +%95 = OpConstant %4 2 +%109 = OpTypeFunction %2 %4 %5 +%133 = OpTypeFunction %2 %4 %9 +%142 = OpTypeFunction %2 %4 %4 %5 +%162 = OpTypeFunction %2 %5 +%17 = OpFunction %5 None %18 +%16 = OpFunctionParameter %4 +%15 = OpLabel +OpBranch %19 +%19 = OpLabel +%23 = OpExtInst %8 %1 UMin %16 %22 +%25 = OpAccessChain %21 %13 %24 %23 +%26 = OpLoad %5 %25 +OpReturnValue %26 OpFunctionEnd -%28 = OpFunction %5 None %16 -%27 = OpFunctionParameter %4 -%26 = OpLabel -OpBranch %29 -%29 = OpLabel -%31 = OpArrayLength %21 %11 3 -%33 = OpISub %21 %31 %32 -%34 = OpExtInst %21 %1 UMin %27 %33 -%36 = OpAccessChain %19 %11 %35 %34 -%37 = OpLoad %5 %36 -OpReturnValue %37 +%29 = OpFunction %5 None %18 +%28 = OpFunctionParameter %4 +%27 = OpLabel +OpBranch %30 +%30 = OpLabel +%32 = OpArrayLength %8 %13 3 +%34 = OpISub %8 %32 %33 +%35 = OpExtInst %8 %1 UMin %28 %34 +%37 = OpAccessChain %21 %13 %36 %35 +%38 = OpLoad %5 %37 +OpReturnValue %38 OpFunctionEnd -%40 = OpFunction %5 None %16 -%39 = OpFunctionParameter %4 -%38 = OpLabel -OpBranch %41 -%41 = OpLabel -%44 = OpExtInst %21 %1 UMin %39 %35 -%45 = OpAccessChain %43 %11 %32 %44 -%46 = OpLoad %5 %45 -OpReturnValue %46 +%41 = OpFunction %5 None %18 +%40 = OpFunctionParameter %4 +%39 = OpLabel +OpBranch %42 +%42 = OpLabel +%45 = OpExtInst %8 %1 UMin %40 %36 +%46 = OpAccessChain %44 %13 %33 %45 +%47 = OpLoad %5 %46 +OpReturnValue %47 OpFunctionEnd -%50 = OpFunction %5 None %51 -%48 = OpFunctionParameter %7 -%49 = OpFunctionParameter %4 -%47 = OpLabel -OpBranch %52 -%52 = OpLabel -%53 = OpExtInst %21 %1 UMin %49 %35 -%54 = OpVectorExtractDynamic %5 %48 %53 -OpReturnValue %54 +%51 = OpFunction %5 None %52 +%49 = OpFunctionParameter %9 +%50 = OpFunctionParameter %4 +%48 = OpLabel +OpBranch %53 +%53 = OpLabel +%54 = OpExtInst %8 %1 UMin %50 %36 +%55 = OpVectorExtractDynamic %5 %49 %54 +OpReturnValue %55 OpFunctionEnd -%57 = OpFunction %7 None %58 -%56 = OpFunctionParameter %4 -%55 = OpLabel -OpBranch %59 -%59 = OpLabel -%63 = OpExtInst %21 %1 UMin %56 %62 -%64 = OpAccessChain %61 %11 %62 %63 -%65 = OpLoad %7 %64 -OpReturnValue %65 +%58 = OpFunction %9 None %59 +%57 = OpFunctionParameter %4 +%56 = OpLabel +OpBranch %60 +%60 = OpLabel +%64 = OpExtInst %8 %1 UMin %57 %63 +%65 = OpAccessChain %62 %13 %63 %64 +%66 = OpLoad %9 %65 +OpReturnValue %66 OpFunctionEnd -%69 = OpFunction %5 None %70 -%67 = OpFunctionParameter %4 +%70 = OpFunction %5 None %71 %68 = OpFunctionParameter %4 -%66 = OpLabel -OpBranch %71 -%71 = OpLabel -%72 = OpExtInst %21 %1 UMin %68 %35 -%73 = OpExtInst %21 %1 UMin %67 %62 -%74 = OpAccessChain %43 %11 %62 %73 %72 -%75 = OpLoad %5 %74 -OpReturnValue %75 +%69 = OpFunctionParameter %4 +%67 = OpLabel +OpBranch %72 +%72 = OpLabel +%73 = OpExtInst %8 %1 UMin %69 %36 +%74 = OpExtInst %8 %1 UMin %68 %63 +%75 = OpAccessChain %44 %13 %63 %74 %73 +%76 = OpLoad %5 %75 +OpReturnValue %76 OpFunctionEnd -%78 = OpFunction %5 None %16 -%77 = OpFunctionParameter %4 -%76 = OpLabel -OpBranch %80 -%80 = OpLabel -%81 = OpConvertSToF %5 %77 -%82 = OpFDiv %5 %81 %79 -%83 = OpExtInst %5 %1 Sin %82 -%84 = OpFMul %5 %83 %79 -%85 = OpConvertFToS %4 %84 -%86 = OpExtInst %21 %1 UMin %85 %20 -%87 = OpAccessChain %19 %11 %23 %86 -%88 = OpLoad %5 %87 -OpReturnValue %88 +%79 = OpFunction %5 None %18 +%78 = OpFunctionParameter %4 +%77 = OpLabel +OpBranch %81 +%81 = OpLabel +%82 = OpConvertSToF %5 %78 +%83 = OpFDiv %5 %82 %80 +%84 = OpExtInst %5 %1 Sin %83 +%85 = OpFMul %5 %84 %80 +%86 = OpConvertFToS %4 %85 +%87 = OpExtInst %8 %1 UMin %86 %22 +%88 = OpAccessChain %21 %13 %24 %87 +%89 = OpLoad %5 %88 +OpReturnValue %89 OpFunctionEnd -%90 = OpFunction %5 None %91 -%89 = OpLabel -OpBranch %95 -%95 = OpLabel -%96 = OpAccessChain %19 %11 %23 %20 -%97 = OpLoad %5 %96 -%98 = OpAccessChain %43 %11 %32 %35 -%99 = OpLoad %5 %98 -%100 = OpFAdd %5 %97 %99 -%101 = OpAccessChain %43 %11 %62 %62 %35 -%102 = OpLoad %5 %101 -%103 = OpFAdd %5 %100 %102 -OpReturnValue %103 +%91 = OpFunction %5 None %92 +%90 = OpLabel +OpBranch %96 +%96 = OpLabel +%97 = OpAccessChain %21 %13 %24 %22 +%98 = OpLoad %5 %97 +%99 = OpAccessChain %44 %13 %33 %36 +%100 = OpLoad %5 %99 +%101 = OpFAdd %5 %98 %100 +%102 = OpAccessChain %44 %13 %63 %63 %36 +%103 = OpLoad %5 %102 +%104 = OpFAdd %5 %101 %103 +OpReturnValue %104 OpFunctionEnd -%107 = OpFunction %2 None %108 -%105 = OpFunctionParameter %4 -%106 = OpFunctionParameter %5 -%104 = OpLabel -OpBranch %109 -%109 = OpLabel -%110 = OpExtInst %21 %1 UMin %105 %20 -%111 = OpAccessChain %19 %11 %23 %110 -OpStore %111 %106 +%108 = OpFunction %2 None %109 +%106 = OpFunctionParameter %4 +%107 = OpFunctionParameter %5 +%105 = OpLabel +OpBranch %110 +%110 = OpLabel +%111 = OpExtInst %8 %1 UMin %106 %22 +%112 = OpAccessChain %21 %13 %24 %111 +OpStore %112 %107 OpReturn OpFunctionEnd -%115 = OpFunction %2 None %108 -%113 = OpFunctionParameter %4 -%114 = OpFunctionParameter %5 -%112 = OpLabel -OpBranch %116 -%116 = OpLabel -%117 = OpArrayLength %21 %11 3 -%118 = OpISub %21 %117 %32 -%119 = OpExtInst %21 %1 UMin %113 %118 -%120 = OpAccessChain %19 %11 %35 %119 -OpStore %120 %114 +%116 = OpFunction %2 None %109 +%114 = OpFunctionParameter %4 +%115 = OpFunctionParameter %5 +%113 = OpLabel +OpBranch %117 +%117 = OpLabel +%118 = OpArrayLength %8 %13 3 +%119 = OpISub %8 %118 %33 +%120 = OpExtInst %8 %1 UMin %114 %119 +%121 = OpAccessChain %21 %13 %36 %120 +OpStore %121 %115 OpReturn OpFunctionEnd -%124 = OpFunction %2 None %108 -%122 = OpFunctionParameter %4 -%123 = OpFunctionParameter %5 -%121 = OpLabel -OpBranch %125 -%125 = OpLabel -%126 = OpExtInst %21 %1 UMin %122 %35 -%127 = OpAccessChain %43 %11 %32 %126 -OpStore %127 %123 +%125 = OpFunction %2 None %109 +%123 = OpFunctionParameter %4 +%124 = OpFunctionParameter %5 +%122 = OpLabel +OpBranch %126 +%126 = OpLabel +%127 = OpExtInst %8 %1 UMin %123 %36 +%128 = OpAccessChain %44 %13 %33 %127 +OpStore %128 %124 OpReturn OpFunctionEnd -%131 = OpFunction %2 None %132 -%129 = OpFunctionParameter %4 -%130 = OpFunctionParameter %7 -%128 = OpLabel -OpBranch %133 -%133 = OpLabel -%134 = OpExtInst %21 %1 UMin %129 %62 -%135 = OpAccessChain %61 %11 %62 %134 -OpStore %135 %130 +%132 = OpFunction %2 None %133 +%130 = OpFunctionParameter %4 +%131 = OpFunctionParameter %9 +%129 = OpLabel +OpBranch %134 +%134 = OpLabel +%135 = OpExtInst %8 %1 UMin %130 %63 +%136 = OpAccessChain %62 %13 %63 %135 +OpStore %136 %131 OpReturn OpFunctionEnd -%140 = OpFunction %2 None %141 -%137 = OpFunctionParameter %4 +%141 = OpFunction %2 None %142 %138 = OpFunctionParameter %4 -%139 = OpFunctionParameter %5 -%136 = OpLabel -OpBranch %142 -%142 = OpLabel -%143 = OpExtInst %21 %1 UMin %138 %35 -%144 = OpExtInst %21 %1 UMin %137 %62 -%145 = OpAccessChain %43 %11 %62 %144 %143 -OpStore %145 %139 +%139 = OpFunctionParameter %4 +%140 = OpFunctionParameter %5 +%137 = OpLabel +OpBranch %143 +%143 = OpLabel +%144 = OpExtInst %8 %1 UMin %139 %36 +%145 = OpExtInst %8 %1 UMin %138 %63 +%146 = OpAccessChain %44 %13 %63 %145 %144 +OpStore %146 %140 OpReturn OpFunctionEnd -%149 = OpFunction %2 None %108 -%147 = OpFunctionParameter %4 -%148 = OpFunctionParameter %5 -%146 = OpLabel -OpBranch %150 -%150 = OpLabel -%151 = OpConvertSToF %5 %147 -%152 = OpFDiv %5 %151 %79 -%153 = OpExtInst %5 %1 Sin %152 -%154 = OpFMul %5 %153 %79 -%155 = OpConvertFToS %4 %154 -%156 = OpExtInst %21 %1 UMin %155 %20 -%157 = OpAccessChain %19 %11 %23 %156 -OpStore %157 %148 +%150 = OpFunction %2 None %109 +%148 = OpFunctionParameter %4 +%149 = OpFunctionParameter %5 +%147 = OpLabel +OpBranch %151 +%151 = OpLabel +%152 = OpConvertSToF %5 %148 +%153 = OpFDiv %5 %152 %80 +%154 = OpExtInst %5 %1 Sin %153 +%155 = OpFMul %5 %154 %80 +%156 = OpConvertFToS %4 %155 +%157 = OpExtInst %8 %1 UMin %156 %22 +%158 = OpAccessChain %21 %13 %24 %157 +OpStore %158 %149 OpReturn OpFunctionEnd -%160 = OpFunction %2 None %161 -%159 = OpFunctionParameter %5 -%158 = OpLabel -OpBranch %162 -%162 = OpLabel -%163 = OpAccessChain %19 %11 %23 %20 -OpStore %163 %159 -%164 = OpAccessChain %43 %11 %32 %35 -OpStore %164 %159 -%165 = OpAccessChain %43 %11 %62 %62 %35 -OpStore %165 %159 +%161 = OpFunction %2 None %162 +%160 = OpFunctionParameter %5 +%159 = OpLabel +OpBranch %163 +%163 = OpLabel +%164 = OpAccessChain %21 %13 %24 %22 +OpStore %164 %160 +%165 = OpAccessChain %44 %13 %33 %36 +OpStore %165 %160 +%166 = OpAccessChain %44 %13 %63 %63 %36 +OpStore %166 %160 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index 3879709a5..b2a82f673 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -8,50 +8,50 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpDecorate %6 ArrayStride 4 -OpDecorate %9 ArrayStride 4 -OpMemberDecorate %10 0 Offset 0 -OpMemberDecorate %10 1 Offset 48 -OpMemberDecorate %10 2 Offset 64 -OpMemberDecorate %10 2 ColMajor -OpMemberDecorate %10 2 MatrixStride 16 -OpMemberDecorate %10 3 Offset 112 -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 0 -OpDecorate %10 Block +OpDecorate %11 ArrayStride 4 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 48 +OpMemberDecorate %12 2 Offset 64 +OpMemberDecorate %12 2 ColMajor +OpMemberDecorate %12 2 MatrixStride 16 +OpMemberDecorate %12 3 Offset 112 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 0 +OpDecorate %12 Block %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 %5 = OpTypeFloat 32 -%6 = OpTypeArray %5 %3 -%7 = OpTypeVector %5 4 -%8 = OpTypeMatrix %7 3 -%9 = OpTypeRuntimeArray %5 -%10 = OpTypeStruct %6 %7 %8 %9 -%12 = OpTypePointer StorageBuffer %10 -%11 = OpVariable %12 StorageBuffer -%16 = OpTypeFunction %5 %4 -%18 = OpTypePointer StorageBuffer %6 -%19 = OpTypePointer StorageBuffer %5 -%21 = OpTypeInt 32 0 -%20 = OpConstant %21 10 +%8 = OpTypeInt 32 0 +%7 = OpConstant %8 10 +%6 = OpTypeArray %5 %7 +%9 = OpTypeVector %5 4 +%10 = OpTypeMatrix %9 3 +%11 = OpTypeRuntimeArray %5 +%12 = OpTypeStruct %6 %9 %10 %11 +%14 = OpTypePointer StorageBuffer %12 +%13 = OpVariable %14 StorageBuffer +%18 = OpTypeFunction %5 %4 +%20 = OpTypePointer StorageBuffer %6 +%21 = OpTypePointer StorageBuffer %5 %23 = OpTypeBool -%24 = OpConstant %21 0 +%24 = OpConstant %8 0 %26 = OpConstantNull %5 -%35 = OpTypePointer StorageBuffer %9 -%38 = OpConstant %21 3 +%35 = OpTypePointer StorageBuffer %11 +%38 = OpConstant %8 3 %40 = OpConstantNull %5 -%49 = OpTypePointer StorageBuffer %7 +%49 = OpTypePointer StorageBuffer %9 %50 = OpTypePointer StorageBuffer %5 -%51 = OpConstant %21 4 -%53 = OpConstant %21 1 +%51 = OpConstant %8 4 +%53 = OpConstant %8 1 %55 = OpConstantNull %5 -%64 = OpTypeFunction %5 %7 %4 +%64 = OpTypeFunction %5 %9 %4 %67 = OpConstantNull %5 -%75 = OpTypeFunction %7 %4 -%77 = OpTypePointer StorageBuffer %8 -%78 = OpTypePointer StorageBuffer %7 -%80 = OpConstant %21 2 -%82 = OpConstantNull %7 +%75 = OpTypeFunction %9 %4 +%77 = OpTypePointer StorageBuffer %10 +%78 = OpTypePointer StorageBuffer %9 +%80 = OpConstant %8 2 +%82 = OpConstantNull %9 %91 = OpTypeFunction %5 %4 %4 %97 = OpConstantNull %5 %105 = OpConstant %5 100.0 @@ -60,45 +60,45 @@ OpDecorate %10 Block %122 = OpConstant %4 9 %123 = OpConstant %4 3 %124 = OpConstant %4 2 -%126 = OpConstant %21 9 +%126 = OpConstant %8 9 %139 = OpTypeFunction %2 %4 %5 -%168 = OpTypeFunction %2 %4 %7 +%168 = OpTypeFunction %2 %4 %9 %179 = OpTypeFunction %2 %4 %4 %5 %204 = OpTypeFunction %2 %5 -%15 = OpFunction %5 None %16 -%14 = OpFunctionParameter %4 -%13 = OpLabel -OpBranch %17 -%17 = OpLabel -%22 = OpULessThan %23 %14 %20 +%17 = OpFunction %5 None %18 +%16 = OpFunctionParameter %4 +%15 = OpLabel +OpBranch %19 +%19 = OpLabel +%22 = OpULessThan %23 %16 %7 OpSelectionMerge %27 None OpBranchConditional %22 %28 %27 %28 = OpLabel -%25 = OpAccessChain %19 %11 %24 %14 +%25 = OpAccessChain %21 %13 %24 %16 %29 = OpLoad %5 %25 OpBranch %27 %27 = OpLabel -%30 = OpPhi %5 %26 %17 %29 %28 +%30 = OpPhi %5 %26 %19 %29 %28 OpReturnValue %30 OpFunctionEnd -%33 = OpFunction %5 None %16 +%33 = OpFunction %5 None %18 %32 = OpFunctionParameter %4 %31 = OpLabel OpBranch %34 %34 = OpLabel -%36 = OpArrayLength %21 %11 3 +%36 = OpArrayLength %8 %13 3 %37 = OpULessThan %23 %32 %36 OpSelectionMerge %41 None OpBranchConditional %37 %42 %41 %42 = OpLabel -%39 = OpAccessChain %19 %11 %38 %32 +%39 = OpAccessChain %21 %13 %38 %32 %43 = OpLoad %5 %39 OpBranch %41 %41 = OpLabel %44 = OpPhi %5 %40 %34 %43 %42 OpReturnValue %44 OpFunctionEnd -%47 = OpFunction %5 None %16 +%47 = OpFunction %5 None %18 %46 = OpFunctionParameter %4 %45 = OpLabel OpBranch %48 @@ -107,7 +107,7 @@ OpBranch %48 OpSelectionMerge %56 None OpBranchConditional %52 %57 %56 %57 = OpLabel -%54 = OpAccessChain %50 %11 %53 %46 +%54 = OpAccessChain %50 %13 %53 %46 %58 = OpLoad %5 %54 OpBranch %56 %56 = OpLabel @@ -115,7 +115,7 @@ OpBranch %56 OpReturnValue %59 OpFunctionEnd %63 = OpFunction %5 None %64 -%61 = OpFunctionParameter %7 +%61 = OpFunctionParameter %9 %62 = OpFunctionParameter %4 %60 = OpLabel OpBranch %65 @@ -130,7 +130,7 @@ OpBranch %68 %71 = OpPhi %5 %67 %65 %70 %69 OpReturnValue %71 OpFunctionEnd -%74 = OpFunction %7 None %75 +%74 = OpFunction %9 None %75 %73 = OpFunctionParameter %4 %72 = OpLabel OpBranch %76 @@ -139,11 +139,11 @@ OpBranch %76 OpSelectionMerge %83 None OpBranchConditional %79 %84 %83 %84 = OpLabel -%81 = OpAccessChain %78 %11 %80 %73 -%85 = OpLoad %7 %81 +%81 = OpAccessChain %78 %13 %80 %73 +%85 = OpLoad %9 %81 OpBranch %83 %83 = OpLabel -%86 = OpPhi %7 %82 %76 %85 %84 +%86 = OpPhi %9 %82 %76 %85 %84 OpReturnValue %86 OpFunctionEnd %90 = OpFunction %5 None %91 @@ -158,14 +158,14 @@ OpBranch %92 OpSelectionMerge %98 None OpBranchConditional %95 %99 %98 %99 = OpLabel -%96 = OpAccessChain %50 %11 %80 %88 %89 +%96 = OpAccessChain %50 %13 %80 %88 %89 %100 = OpLoad %5 %96 OpBranch %98 %98 = OpLabel %101 = OpPhi %5 %97 %92 %100 %99 OpReturnValue %101 OpFunctionEnd -%104 = OpFunction %5 None %16 +%104 = OpFunction %5 None %18 %103 = OpFunctionParameter %4 %102 = OpLabel OpBranch %106 @@ -175,11 +175,11 @@ OpBranch %106 %109 = OpExtInst %5 %1 Sin %108 %110 = OpFMul %5 %109 %105 %111 = OpConvertFToS %4 %110 -%112 = OpULessThan %23 %111 %20 +%112 = OpULessThan %23 %111 %7 OpSelectionMerge %115 None OpBranchConditional %112 %116 %115 %116 = OpLabel -%113 = OpAccessChain %19 %11 %24 %111 +%113 = OpAccessChain %21 %13 %24 %111 %117 = OpLoad %5 %113 OpBranch %115 %115 = OpLabel @@ -190,12 +190,12 @@ OpFunctionEnd %119 = OpLabel OpBranch %125 %125 = OpLabel -%127 = OpAccessChain %19 %11 %24 %126 +%127 = OpAccessChain %21 %13 %24 %126 %128 = OpLoad %5 %127 -%129 = OpAccessChain %50 %11 %53 %38 +%129 = OpAccessChain %50 %13 %53 %38 %130 = OpLoad %5 %129 %131 = OpFAdd %5 %128 %130 -%132 = OpAccessChain %50 %11 %80 %80 %38 +%132 = OpAccessChain %50 %13 %80 %80 %38 %133 = OpLoad %5 %132 %134 = OpFAdd %5 %131 %133 OpReturnValue %134 @@ -206,11 +206,11 @@ OpFunctionEnd %135 = OpLabel OpBranch %140 %140 = OpLabel -%141 = OpULessThan %23 %136 %20 +%141 = OpULessThan %23 %136 %7 OpSelectionMerge %143 None OpBranchConditional %141 %144 %143 %144 = OpLabel -%142 = OpAccessChain %19 %11 %24 %136 +%142 = OpAccessChain %21 %13 %24 %136 OpStore %142 %137 OpBranch %143 %143 = OpLabel @@ -222,12 +222,12 @@ OpFunctionEnd %145 = OpLabel OpBranch %149 %149 = OpLabel -%150 = OpArrayLength %21 %11 3 +%150 = OpArrayLength %8 %13 3 %151 = OpULessThan %23 %146 %150 OpSelectionMerge %153 None OpBranchConditional %151 %154 %153 %154 = OpLabel -%152 = OpAccessChain %19 %11 %38 %146 +%152 = OpAccessChain %21 %13 %38 %146 OpStore %152 %147 OpBranch %153 %153 = OpLabel @@ -243,7 +243,7 @@ OpBranch %159 OpSelectionMerge %162 None OpBranchConditional %160 %163 %162 %163 = OpLabel -%161 = OpAccessChain %50 %11 %53 %156 +%161 = OpAccessChain %50 %13 %53 %156 OpStore %161 %157 OpBranch %162 %162 = OpLabel @@ -251,7 +251,7 @@ OpReturn OpFunctionEnd %167 = OpFunction %2 None %168 %165 = OpFunctionParameter %4 -%166 = OpFunctionParameter %7 +%166 = OpFunctionParameter %9 %164 = OpLabel OpBranch %169 %169 = OpLabel @@ -259,7 +259,7 @@ OpBranch %169 OpSelectionMerge %172 None OpBranchConditional %170 %173 %172 %173 = OpLabel -%171 = OpAccessChain %78 %11 %80 %165 +%171 = OpAccessChain %78 %13 %80 %165 OpStore %171 %166 OpBranch %172 %172 = OpLabel @@ -278,7 +278,7 @@ OpBranch %180 OpSelectionMerge %185 None OpBranchConditional %183 %186 %185 %186 = OpLabel -%184 = OpAccessChain %50 %11 %80 %175 %176 +%184 = OpAccessChain %50 %13 %80 %175 %176 OpStore %184 %177 OpBranch %185 %185 = OpLabel @@ -295,11 +295,11 @@ OpBranch %191 %194 = OpExtInst %5 %1 Sin %193 %195 = OpFMul %5 %194 %105 %196 = OpConvertFToS %4 %195 -%197 = OpULessThan %23 %196 %20 +%197 = OpULessThan %23 %196 %7 OpSelectionMerge %199 None OpBranchConditional %197 %200 %199 %200 = OpLabel -%198 = OpAccessChain %19 %11 %24 %196 +%198 = OpAccessChain %21 %13 %24 %196 OpStore %198 %189 OpBranch %199 %199 = OpLabel @@ -310,11 +310,11 @@ OpFunctionEnd %201 = OpLabel OpBranch %205 %205 = OpLabel -%206 = OpAccessChain %19 %11 %24 %126 +%206 = OpAccessChain %21 %13 %24 %126 OpStore %206 %202 -%207 = OpAccessChain %50 %11 %53 %38 +%207 = OpAccessChain %50 %13 %53 %38 OpStore %207 %202 -%208 = OpAccessChain %50 %11 %80 %80 %38 +%208 = OpAccessChain %50 %13 %80 %80 %38 OpStore %208 %202 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index f2cc50b3d..9f5c1d495 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,54 +1,54 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 185 +; Bound: 186 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %102 "main" %128 -OpExecutionMode %102 LocalSize 1 1 1 +OpEntryPoint GLCompute %104 "main" %129 +OpExecutionMode %104 LocalSize 1 1 1 OpDecorate %11 ArrayStride 4 OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %13 1 Offset 12 OpDecorate %15 ArrayStride 8 OpDecorate %17 ArrayStride 16 -OpDecorate %20 ArrayStride 32 -OpDecorate %21 ArrayStride 64 -OpDecorate %23 ArrayStride 32 -OpDecorate %24 ArrayStride 64 -OpDecorate %30 DescriptorSet 0 -OpDecorate %30 Binding 1 -OpDecorate %31 Block -OpMemberDecorate %31 0 Offset 0 -OpDecorate %33 NonWritable -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 2 -OpDecorate %34 Block -OpMemberDecorate %34 0 Offset 0 -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 3 -OpDecorate %37 Block -OpMemberDecorate %37 0 Offset 0 -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 4 -OpDecorate %40 Block -OpMemberDecorate %40 0 Offset 0 -OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 5 -OpDecorate %43 Block -OpMemberDecorate %43 0 Offset 0 -OpMemberDecorate %43 0 ColMajor -OpMemberDecorate %43 0 MatrixStride 8 -OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 6 -OpDecorate %46 Block -OpMemberDecorate %46 0 Offset 0 -OpDecorate %48 DescriptorSet 0 -OpDecorate %48 Binding 7 -OpDecorate %49 Block -OpMemberDecorate %49 0 Offset 0 -OpDecorate %128 BuiltIn LocalInvocationId +OpDecorate %21 ArrayStride 32 +OpDecorate %23 ArrayStride 64 +OpDecorate %25 ArrayStride 32 +OpDecorate %26 ArrayStride 64 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 1 +OpDecorate %33 Block +OpMemberDecorate %33 0 Offset 0 +OpDecorate %35 NonWritable +OpDecorate %35 DescriptorSet 0 +OpDecorate %35 Binding 2 +OpDecorate %36 Block +OpMemberDecorate %36 0 Offset 0 +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 3 +OpDecorate %39 Block +OpMemberDecorate %39 0 Offset 0 +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 4 +OpDecorate %42 Block +OpMemberDecorate %42 0 Offset 0 +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 5 +OpDecorate %45 Block +OpMemberDecorate %45 0 Offset 0 +OpMemberDecorate %45 0 ColMajor +OpMemberDecorate %45 0 MatrixStride 8 +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 6 +OpDecorate %48 Block +OpMemberDecorate %48 0 Offset 0 +OpDecorate %50 DescriptorSet 0 +OpDecorate %50 Binding 7 +OpDecorate %51 Block +OpMemberDecorate %51 0 Offset 0 +OpDecorate %129 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -64,203 +64,204 @@ OpDecorate %128 BuiltIn LocalInvocationId %14 = OpTypeVector %10 2 %15 = OpTypeRuntimeArray %14 %16 = OpTypeVector %10 4 -%17 = OpTypeArray %16 %7 -%18 = OpTypeMatrix %14 3 -%19 = OpTypeMatrix %16 2 -%20 = OpTypeArray %19 %9 -%21 = OpTypeArray %20 %9 -%22 = OpTypeMatrix %14 4 -%23 = OpTypeArray %22 %9 -%24 = OpTypeArray %23 %9 -%25 = OpTypeMatrix %12 3 -%27 = OpTypePointer Workgroup %11 -%26 = OpVariable %27 Workgroup -%29 = OpTypePointer Workgroup %6 +%18 = OpConstant %6 20 +%17 = OpTypeArray %16 %18 +%19 = OpTypeMatrix %14 3 +%20 = OpTypeMatrix %16 2 +%22 = OpConstant %6 2 +%21 = OpTypeArray %20 %22 +%23 = OpTypeArray %21 %22 +%24 = OpTypeMatrix %14 4 +%25 = OpTypeArray %24 %22 +%26 = OpTypeArray %25 %22 +%27 = OpTypeMatrix %12 3 +%29 = OpTypePointer Workgroup %11 %28 = OpVariable %29 Workgroup -%31 = OpTypeStruct %13 -%32 = OpTypePointer StorageBuffer %31 -%30 = OpVariable %32 StorageBuffer -%34 = OpTypeStruct %15 -%35 = OpTypePointer StorageBuffer %34 -%33 = OpVariable %35 StorageBuffer -%37 = OpTypeStruct %17 -%38 = OpTypePointer Uniform %37 -%36 = OpVariable %38 Uniform -%40 = OpTypeStruct %12 -%41 = OpTypePointer Uniform %40 -%39 = OpVariable %41 Uniform -%43 = OpTypeStruct %18 -%44 = OpTypePointer Uniform %43 -%42 = OpVariable %44 Uniform -%46 = OpTypeStruct %21 -%47 = OpTypePointer Uniform %46 -%45 = OpVariable %47 Uniform -%49 = OpTypeStruct %24 -%50 = OpTypePointer Uniform %49 -%48 = OpVariable %50 Uniform -%54 = OpTypeFunction %2 %12 -%57 = OpTypePointer Function %8 -%58 = OpConstantNull %8 -%61 = OpTypeFunction %2 -%62 = OpTypePointer StorageBuffer %13 -%63 = OpConstant %6 0 -%65 = OpConstant %10 1.0 -%66 = OpConstant %8 1 -%67 = OpConstant %8 0 -%68 = OpConstant %10 2.0 -%69 = OpConstant %10 3.0 -%70 = OpConstantNull %25 -%71 = OpConstantNull %25 -%73 = OpTypePointer StorageBuffer %12 -%76 = OpTypePointer StorageBuffer %10 -%96 = OpTypePointer Function %10 -%97 = OpConstantNull %10 -%99 = OpTypePointer Function %4 -%100 = OpConstantNull %4 -%104 = OpTypePointer StorageBuffer %15 -%106 = OpTypePointer Uniform %17 -%108 = OpTypePointer Uniform %12 -%110 = OpTypePointer Uniform %18 -%112 = OpTypePointer Uniform %21 -%114 = OpTypePointer Uniform %24 -%116 = OpConstant %8 7 -%117 = OpConstant %8 6 -%118 = OpConstant %8 5 -%119 = OpConstant %8 4 -%120 = OpConstant %8 3 -%121 = OpConstant %10 4.0 -%122 = OpConstant %6 2 -%123 = OpConstantTrue %4 -%125 = OpConstantNull %11 -%126 = OpConstantNull %6 -%127 = OpTypeVector %6 3 -%129 = OpTypePointer Input %127 -%128 = OpVariable %129 Input -%131 = OpConstantNull %127 -%132 = OpTypeVector %4 3 -%137 = OpConstant %6 264 -%140 = OpTypePointer Workgroup %10 -%141 = OpTypePointer Uniform %23 -%142 = OpTypePointer Uniform %22 -%145 = OpTypePointer Uniform %20 -%146 = OpTypePointer Uniform %19 -%147 = OpTypePointer Uniform %16 -%152 = OpConstant %6 7 -%158 = OpConstant %6 6 -%160 = OpTypePointer StorageBuffer %14 -%161 = OpConstant %6 1 -%164 = OpConstant %6 5 -%166 = OpTypePointer Uniform %16 -%167 = OpTypePointer Uniform %10 -%168 = OpConstant %6 3 -%171 = OpConstant %6 4 -%173 = OpTypePointer StorageBuffer %10 -%184 = OpConstant %6 256 -%53 = OpFunction %2 None %54 -%52 = OpFunctionParameter %12 -%51 = OpLabel -OpBranch %55 -%55 = OpLabel +%31 = OpTypePointer Workgroup %6 +%30 = OpVariable %31 Workgroup +%33 = OpTypeStruct %13 +%34 = OpTypePointer StorageBuffer %33 +%32 = OpVariable %34 StorageBuffer +%36 = OpTypeStruct %15 +%37 = OpTypePointer StorageBuffer %36 +%35 = OpVariable %37 StorageBuffer +%39 = OpTypeStruct %17 +%40 = OpTypePointer Uniform %39 +%38 = OpVariable %40 Uniform +%42 = OpTypeStruct %12 +%43 = OpTypePointer Uniform %42 +%41 = OpVariable %43 Uniform +%45 = OpTypeStruct %19 +%46 = OpTypePointer Uniform %45 +%44 = OpVariable %46 Uniform +%48 = OpTypeStruct %23 +%49 = OpTypePointer Uniform %48 +%47 = OpVariable %49 Uniform +%51 = OpTypeStruct %26 +%52 = OpTypePointer Uniform %51 +%50 = OpVariable %52 Uniform +%56 = OpTypeFunction %2 %12 +%59 = OpTypePointer Function %8 +%60 = OpConstantNull %8 +%63 = OpTypeFunction %2 +%64 = OpTypePointer StorageBuffer %13 +%65 = OpConstant %6 0 +%67 = OpConstant %10 1.0 +%68 = OpConstant %8 1 +%69 = OpConstant %8 0 +%70 = OpConstant %10 2.0 +%71 = OpConstant %10 3.0 +%72 = OpConstantNull %27 +%73 = OpConstantNull %27 +%75 = OpTypePointer StorageBuffer %12 +%78 = OpTypePointer StorageBuffer %10 +%98 = OpTypePointer Function %10 +%99 = OpConstantNull %10 +%101 = OpTypePointer Function %4 +%102 = OpConstantNull %4 +%106 = OpTypePointer StorageBuffer %15 +%108 = OpTypePointer Uniform %17 +%110 = OpTypePointer Uniform %12 +%112 = OpTypePointer Uniform %19 +%114 = OpTypePointer Uniform %23 +%116 = OpTypePointer Uniform %26 +%118 = OpConstant %8 7 +%119 = OpConstant %8 6 +%120 = OpConstant %8 5 +%121 = OpConstant %8 4 +%122 = OpConstant %8 3 +%123 = OpConstant %10 4.0 +%124 = OpConstantTrue %4 +%126 = OpConstantNull %11 +%127 = OpConstantNull %6 +%128 = OpTypeVector %6 3 +%130 = OpTypePointer Input %128 +%129 = OpVariable %130 Input +%132 = OpConstantNull %128 +%133 = OpTypeVector %4 3 +%138 = OpConstant %6 264 +%141 = OpTypePointer Workgroup %10 +%142 = OpTypePointer Uniform %25 +%143 = OpTypePointer Uniform %24 +%146 = OpTypePointer Uniform %21 +%147 = OpTypePointer Uniform %20 +%148 = OpTypePointer Uniform %16 +%153 = OpConstant %6 7 +%159 = OpConstant %6 6 +%161 = OpTypePointer StorageBuffer %14 +%162 = OpConstant %6 1 +%165 = OpConstant %6 5 +%167 = OpTypePointer Uniform %16 +%168 = OpTypePointer Uniform %10 +%169 = OpConstant %6 3 +%172 = OpConstant %6 4 +%174 = OpTypePointer StorageBuffer %10 +%185 = OpConstant %6 256 +%55 = OpFunction %2 None %56 +%54 = OpFunctionParameter %12 +%53 = OpLabel +OpBranch %57 +%57 = OpLabel OpReturn OpFunctionEnd -%60 = OpFunction %2 None %61 -%59 = OpLabel -%56 = OpVariable %57 Function %58 -%64 = OpAccessChain %62 %30 %63 -OpBranch %72 -%72 = OpLabel -%74 = OpCompositeConstruct %12 %65 %65 %65 -%75 = OpAccessChain %73 %64 %63 -OpStore %75 %74 -OpStore %56 %66 -%77 = OpAccessChain %76 %64 %63 %63 -OpStore %77 %65 -%78 = OpAccessChain %76 %64 %63 %63 -OpStore %78 %68 -%79 = OpLoad %8 %56 -%80 = OpAccessChain %76 %64 %63 %79 -OpStore %80 %69 -%81 = OpLoad %13 %64 -%82 = OpCompositeExtract %12 %81 0 -%83 = OpCompositeExtract %12 %81 0 -%84 = OpVectorShuffle %14 %83 %83 2 0 -%85 = OpCompositeExtract %12 %81 0 -%86 = OpFunctionCall %2 %53 %85 -%87 = OpCompositeExtract %12 %81 0 -%88 = OpVectorTimesMatrix %12 %87 %70 -%89 = OpCompositeExtract %12 %81 0 -%90 = OpMatrixTimesVector %12 %71 %89 -%91 = OpCompositeExtract %12 %81 0 -%92 = OpVectorTimesScalar %12 %91 %68 -%93 = OpCompositeExtract %12 %81 0 -%94 = OpVectorTimesScalar %12 %93 %68 +%62 = OpFunction %2 None %63 +%61 = OpLabel +%58 = OpVariable %59 Function %60 +%66 = OpAccessChain %64 %32 %65 +OpBranch %74 +%74 = OpLabel +%76 = OpCompositeConstruct %12 %67 %67 %67 +%77 = OpAccessChain %75 %66 %65 +OpStore %77 %76 +OpStore %58 %68 +%79 = OpAccessChain %78 %66 %65 %65 +OpStore %79 %67 +%80 = OpAccessChain %78 %66 %65 %65 +OpStore %80 %70 +%81 = OpLoad %8 %58 +%82 = OpAccessChain %78 %66 %65 %81 +OpStore %82 %71 +%83 = OpLoad %13 %66 +%84 = OpCompositeExtract %12 %83 0 +%85 = OpCompositeExtract %12 %83 0 +%86 = OpVectorShuffle %14 %85 %85 2 0 +%87 = OpCompositeExtract %12 %83 0 +%88 = OpFunctionCall %2 %55 %87 +%89 = OpCompositeExtract %12 %83 0 +%90 = OpVectorTimesMatrix %12 %89 %72 +%91 = OpCompositeExtract %12 %83 0 +%92 = OpMatrixTimesVector %12 %73 %91 +%93 = OpCompositeExtract %12 %83 0 +%94 = OpVectorTimesScalar %12 %93 %70 +%95 = OpCompositeExtract %12 %83 0 +%96 = OpVectorTimesScalar %12 %95 %70 OpReturn OpFunctionEnd -%102 = OpFunction %2 None %61 -%101 = OpLabel -%95 = OpVariable %96 Function %97 -%98 = OpVariable %99 Function %100 -%103 = OpAccessChain %62 %30 %63 -%105 = OpAccessChain %104 %33 %63 -%107 = OpAccessChain %106 %36 %63 -%109 = OpAccessChain %108 %39 %63 -%111 = OpAccessChain %110 %42 %63 -%113 = OpAccessChain %112 %45 %63 -%115 = OpAccessChain %114 %48 %63 -OpBranch %124 -%124 = OpLabel -%130 = OpLoad %127 %128 -%133 = OpIEqual %132 %130 %131 -%134 = OpAll %4 %133 -OpSelectionMerge %135 None -OpBranchConditional %134 %136 %135 -%136 = OpLabel -OpStore %26 %125 +%104 = OpFunction %2 None %63 +%103 = OpLabel +%97 = OpVariable %98 Function %99 +%100 = OpVariable %101 Function %102 +%105 = OpAccessChain %64 %32 %65 +%107 = OpAccessChain %106 %35 %65 +%109 = OpAccessChain %108 %38 %65 +%111 = OpAccessChain %110 %41 %65 +%113 = OpAccessChain %112 %44 %65 +%115 = OpAccessChain %114 %47 %65 +%117 = OpAccessChain %116 %50 %65 +OpBranch %125 +%125 = OpLabel +%131 = OpLoad %128 %129 +%134 = OpIEqual %133 %131 %132 +%135 = OpAll %4 %134 +OpSelectionMerge %136 None +OpBranchConditional %135 %137 %136 +%137 = OpLabel OpStore %28 %126 -OpBranch %135 -%135 = OpLabel -OpControlBarrier %122 %122 %137 -OpBranch %138 -%138 = OpLabel -%139 = OpFunctionCall %2 %60 -%143 = OpAccessChain %142 %115 %63 %63 -%144 = OpLoad %22 %143 -%148 = OpAccessChain %147 %113 %63 %63 %63 -%149 = OpLoad %16 %148 -%150 = OpMatrixTimesVector %14 %144 %149 -%151 = OpCompositeExtract %10 %150 0 -%153 = OpAccessChain %140 %26 %152 -OpStore %153 %151 -%154 = OpLoad %18 %111 -%155 = OpLoad %12 %109 -%156 = OpMatrixTimesVector %14 %154 %155 -%157 = OpCompositeExtract %10 %156 0 -%159 = OpAccessChain %140 %26 %158 -OpStore %159 %157 -%162 = OpAccessChain %76 %105 %161 %161 -%163 = OpLoad %10 %162 -%165 = OpAccessChain %140 %26 %164 -OpStore %165 %163 -%169 = OpAccessChain %167 %107 %63 %168 -%170 = OpLoad %10 %169 -%172 = OpAccessChain %140 %26 %171 -OpStore %172 %170 -%174 = OpAccessChain %173 %103 %161 -%175 = OpLoad %10 %174 -%176 = OpAccessChain %140 %26 %168 -OpStore %176 %175 -%177 = OpAccessChain %76 %103 %63 %63 -%178 = OpLoad %10 %177 -%179 = OpAccessChain %140 %26 %122 -OpStore %179 %178 -%180 = OpAccessChain %173 %103 %161 -OpStore %180 %121 -%181 = OpArrayLength %6 %33 0 -%182 = OpConvertUToF %10 %181 -%183 = OpAccessChain %140 %26 %161 -OpStore %183 %182 -OpAtomicStore %28 %9 %184 %122 -OpStore %95 %65 -OpStore %98 %123 +OpStore %30 %127 +OpBranch %136 +%136 = OpLabel +OpControlBarrier %22 %22 %138 +OpBranch %139 +%139 = OpLabel +%140 = OpFunctionCall %2 %62 +%144 = OpAccessChain %143 %117 %65 %65 +%145 = OpLoad %24 %144 +%149 = OpAccessChain %148 %115 %65 %65 %65 +%150 = OpLoad %16 %149 +%151 = OpMatrixTimesVector %14 %145 %150 +%152 = OpCompositeExtract %10 %151 0 +%154 = OpAccessChain %141 %28 %153 +OpStore %154 %152 +%155 = OpLoad %19 %113 +%156 = OpLoad %12 %111 +%157 = OpMatrixTimesVector %14 %155 %156 +%158 = OpCompositeExtract %10 %157 0 +%160 = OpAccessChain %141 %28 %159 +OpStore %160 %158 +%163 = OpAccessChain %78 %107 %162 %162 +%164 = OpLoad %10 %163 +%166 = OpAccessChain %141 %28 %165 +OpStore %166 %164 +%170 = OpAccessChain %168 %109 %65 %169 +%171 = OpLoad %10 %170 +%173 = OpAccessChain %141 %28 %172 +OpStore %173 %171 +%175 = OpAccessChain %174 %105 %162 +%176 = OpLoad %10 %175 +%177 = OpAccessChain %141 %28 %169 +OpStore %177 %176 +%178 = OpAccessChain %78 %105 %65 %65 +%179 = OpLoad %10 %178 +%180 = OpAccessChain %141 %28 %22 +OpStore %180 %179 +%181 = OpAccessChain %174 %105 %162 +OpStore %181 %123 +%182 = OpArrayLength %6 %35 0 +%183 = OpConvertUToF %10 %182 +%184 = OpAccessChain %141 %28 %162 +OpStore %184 %183 +OpAtomicStore %30 %9 %185 %22 +OpStore %97 %67 +OpStore %100 %124 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index f42fb1255..3e2e2a348 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -1,25 +1,25 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 55 +; Bound: 56 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %30 "compute" %18 %21 %23 %26 %28 -OpExecutionMode %30 LocalSize 1 1 1 +OpEntryPoint GLCompute %31 "compute" %19 %22 %24 %27 %29 +OpExecutionMode %31 LocalSize 1 1 1 OpMemberDecorate %7 0 Offset 0 OpMemberDecorate %7 1 Offset 16 OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 4 OpMemberDecorate %9 2 Offset 8 OpDecorate %11 ArrayStride 4 -OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %14 0 Offset 0 -OpDecorate %18 BuiltIn GlobalInvocationId -OpDecorate %21 BuiltIn LocalInvocationId -OpDecorate %23 BuiltIn LocalInvocationIndex -OpDecorate %26 BuiltIn WorkgroupId -OpDecorate %28 BuiltIn NumWorkgroups +OpMemberDecorate %15 0 Offset 0 +OpDecorate %19 BuiltIn GlobalInvocationId +OpDecorate %22 BuiltIn LocalInvocationId +OpDecorate %24 BuiltIn LocalInvocationIndex +OpDecorate %27 BuiltIn WorkgroupId +OpDecorate %29 BuiltIn NumWorkgroups %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 @@ -29,57 +29,58 @@ OpDecorate %28 BuiltIn NumWorkgroups %8 = OpTypeInt 32 0 %9 = OpTypeStruct %6 %8 %6 %10 = OpTypeBool -%11 = OpTypeArray %8 %3 -%12 = OpTypeVector %8 3 -%13 = OpTypeStruct %8 +%12 = OpConstant %8 1 +%11 = OpTypeArray %8 %12 +%13 = OpTypeVector %8 3 %14 = OpTypeStruct %8 -%16 = OpTypePointer Workgroup %11 -%15 = OpVariable %16 Workgroup -%19 = OpTypePointer Input %12 -%18 = OpVariable %19 Input -%21 = OpVariable %19 Input -%24 = OpTypePointer Input %8 -%23 = OpVariable %24 Input -%26 = OpVariable %19 Input -%28 = OpVariable %19 Input -%31 = OpTypeFunction %2 -%32 = OpConstant %4 0 -%34 = OpConstantNull %11 -%35 = OpConstantNull %12 -%36 = OpTypeVector %10 3 -%41 = OpConstant %8 2 -%42 = OpConstant %8 264 -%44 = OpTypePointer Workgroup %8 -%53 = OpConstant %8 0 -%30 = OpFunction %2 None %31 -%17 = OpLabel -%20 = OpLoad %12 %18 -%22 = OpLoad %12 %21 -%25 = OpLoad %8 %23 -%27 = OpLoad %12 %26 -%29 = OpLoad %12 %28 -OpBranch %33 -%33 = OpLabel -%37 = OpIEqual %36 %22 %35 -%38 = OpAll %10 %37 -OpSelectionMerge %39 None -OpBranchConditional %38 %40 %39 +%15 = OpTypeStruct %8 +%17 = OpTypePointer Workgroup %11 +%16 = OpVariable %17 Workgroup +%20 = OpTypePointer Input %13 +%19 = OpVariable %20 Input +%22 = OpVariable %20 Input +%25 = OpTypePointer Input %8 +%24 = OpVariable %25 Input +%27 = OpVariable %20 Input +%29 = OpVariable %20 Input +%32 = OpTypeFunction %2 +%33 = OpConstant %4 0 +%35 = OpConstantNull %11 +%36 = OpConstantNull %13 +%37 = OpTypeVector %10 3 +%42 = OpConstant %8 2 +%43 = OpConstant %8 264 +%45 = OpTypePointer Workgroup %8 +%54 = OpConstant %8 0 +%31 = OpFunction %2 None %32 +%18 = OpLabel +%21 = OpLoad %13 %19 +%23 = OpLoad %13 %22 +%26 = OpLoad %8 %24 +%28 = OpLoad %13 %27 +%30 = OpLoad %13 %29 +OpBranch %34 +%34 = OpLabel +%38 = OpIEqual %37 %23 %36 +%39 = OpAll %10 %38 +OpSelectionMerge %40 None +OpBranchConditional %39 %41 %40 +%41 = OpLabel +OpStore %16 %35 +OpBranch %40 %40 = OpLabel -OpStore %15 %34 -OpBranch %39 -%39 = OpLabel -OpControlBarrier %41 %41 %42 -OpBranch %43 -%43 = OpLabel -%45 = OpCompositeExtract %8 %20 0 -%46 = OpCompositeExtract %8 %22 0 -%47 = OpIAdd %8 %45 %46 -%48 = OpIAdd %8 %47 %25 -%49 = OpCompositeExtract %8 %27 0 -%50 = OpIAdd %8 %48 %49 -%51 = OpCompositeExtract %8 %29 0 -%52 = OpIAdd %8 %50 %51 -%54 = OpAccessChain %44 %15 %53 -OpStore %54 %52 +OpControlBarrier %42 %42 %43 +OpBranch %44 +%44 = OpLabel +%46 = OpCompositeExtract %8 %21 0 +%47 = OpCompositeExtract %8 %23 0 +%48 = OpIAdd %8 %46 %47 +%49 = OpIAdd %8 %48 %26 +%50 = OpCompositeExtract %8 %28 0 +%51 = OpIAdd %8 %49 %50 +%52 = OpCompositeExtract %8 %30 0 +%53 = OpIAdd %8 %51 %52 +%55 = OpAccessChain %45 %16 %54 +OpStore %55 %53 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 682fa7ca6..795ed31d7 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -6,29 +6,29 @@ OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %36 "fragment" %17 %20 %23 %26 %29 %31 %33 %35 -OpExecutionMode %36 OriginUpperLeft -OpExecutionMode %36 DepthReplacing +OpEntryPoint Fragment %37 "fragment" %18 %21 %24 %27 %30 %32 %34 %36 +OpExecutionMode %37 OriginUpperLeft +OpExecutionMode %37 DepthReplacing OpMemberDecorate %7 0 Offset 0 OpMemberDecorate %7 1 Offset 16 OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 4 OpMemberDecorate %9 2 Offset 8 OpDecorate %11 ArrayStride 4 -OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %14 0 Offset 0 -OpDecorate %17 Invariant -OpDecorate %17 BuiltIn FragCoord -OpDecorate %20 Location 1 -OpDecorate %23 BuiltIn FrontFacing -OpDecorate %23 Flat -OpDecorate %26 BuiltIn SampleId -OpDecorate %26 Flat -OpDecorate %29 BuiltIn SampleMask -OpDecorate %29 Flat -OpDecorate %31 BuiltIn FragDepth -OpDecorate %33 BuiltIn SampleMask -OpDecorate %35 Location 0 +OpMemberDecorate %15 0 Offset 0 +OpDecorate %18 Invariant +OpDecorate %18 BuiltIn FragCoord +OpDecorate %21 Location 1 +OpDecorate %24 BuiltIn FrontFacing +OpDecorate %24 Flat +OpDecorate %27 BuiltIn SampleId +OpDecorate %27 Flat +OpDecorate %30 BuiltIn SampleMask +OpDecorate %30 Flat +OpDecorate %32 BuiltIn FragDepth +OpDecorate %34 BuiltIn SampleMask +OpDecorate %36 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 @@ -38,51 +38,51 @@ OpDecorate %35 Location 0 %8 = OpTypeInt 32 0 %9 = OpTypeStruct %6 %8 %6 %10 = OpTypeBool -%11 = OpTypeArray %8 %3 -%12 = OpTypeVector %8 3 -%13 = OpTypeStruct %8 +%12 = OpConstant %8 1 +%11 = OpTypeArray %8 %12 +%13 = OpTypeVector %8 3 %14 = OpTypeStruct %8 -%18 = OpTypePointer Input %5 -%17 = OpVariable %18 Input -%21 = OpTypePointer Input %6 -%20 = OpVariable %21 Input -%24 = OpTypePointer Input %10 -%23 = OpVariable %24 Input -%27 = OpTypePointer Input %8 -%26 = OpVariable %27 Input -%29 = OpVariable %27 Input -%32 = OpTypePointer Output %6 -%31 = OpVariable %32 Output -%34 = OpTypePointer Output %8 -%33 = OpVariable %34 Output -%35 = OpVariable %32 Output -%37 = OpTypeFunction %2 -%38 = OpConstant %8 1 +%15 = OpTypeStruct %8 +%19 = OpTypePointer Input %5 +%18 = OpVariable %19 Input +%22 = OpTypePointer Input %6 +%21 = OpVariable %22 Input +%25 = OpTypePointer Input %10 +%24 = OpVariable %25 Input +%28 = OpTypePointer Input %8 +%27 = OpVariable %28 Input +%30 = OpVariable %28 Input +%33 = OpTypePointer Output %6 +%32 = OpVariable %33 Output +%35 = OpTypePointer Output %8 +%34 = OpVariable %35 Output +%36 = OpVariable %33 Output +%38 = OpTypeFunction %2 %39 = OpConstant %6 0.0 %40 = OpConstant %6 1.0 -%36 = OpFunction %2 None %37 -%15 = OpLabel -%19 = OpLoad %5 %17 -%22 = OpLoad %6 %20 -%16 = OpCompositeConstruct %7 %19 %22 -%25 = OpLoad %10 %23 -%28 = OpLoad %8 %26 -%30 = OpLoad %8 %29 +%37 = OpFunction %2 None %38 +%16 = OpLabel +%20 = OpLoad %5 %18 +%23 = OpLoad %6 %21 +%17 = OpCompositeConstruct %7 %20 %23 +%26 = OpLoad %10 %24 +%29 = OpLoad %8 %27 +%31 = OpLoad %8 %30 OpBranch %41 %41 = OpLabel -%42 = OpShiftLeftLogical %8 %38 %28 -%43 = OpBitwiseAnd %8 %30 %42 -%44 = OpSelect %6 %25 %40 %39 -%45 = OpCompositeExtract %6 %16 1 +%42 = OpShiftLeftLogical %8 %12 %29 +%43 = OpBitwiseAnd %8 %31 %42 +%44 = OpSelect %6 %26 %40 %39 +%45 = OpCompositeExtract %6 %17 1 %46 = OpCompositeConstruct %9 %45 %43 %44 %47 = OpCompositeExtract %6 %46 0 -OpStore %31 %47 -%48 = OpLoad %6 %31 +OpStore %32 %47 +%48 = OpLoad %6 %32 %49 = OpExtInst %6 %1 FClamp %48 %39 %40 -OpStore %31 %49 +OpStore %32 %49 %50 = OpCompositeExtract %8 %46 1 -OpStore %33 %50 +OpStore %34 %50 %51 = OpCompositeExtract %6 %46 2 -OpStore %35 %51 +OpStore %36 %51 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index f1b2bb51a..28b842dbe 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -1,26 +1,26 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 40 +; Bound: 41 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %30 "vertex" %16 %19 %21 %23 %25 %27 +OpEntryPoint Vertex %31 "vertex" %17 %20 %22 %24 %26 %28 OpMemberDecorate %7 0 Offset 0 OpMemberDecorate %7 1 Offset 16 OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 4 OpMemberDecorate %9 2 Offset 8 OpDecorate %11 ArrayStride 4 -OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %14 0 Offset 0 -OpDecorate %16 BuiltIn VertexIndex -OpDecorate %19 BuiltIn InstanceIndex -OpDecorate %21 Location 10 -OpDecorate %23 Invariant -OpDecorate %23 BuiltIn Position -OpDecorate %25 Location 1 -OpDecorate %27 BuiltIn PointSize +OpMemberDecorate %15 0 Offset 0 +OpDecorate %17 BuiltIn VertexIndex +OpDecorate %20 BuiltIn InstanceIndex +OpDecorate %22 Location 10 +OpDecorate %24 Invariant +OpDecorate %24 BuiltIn Position +OpDecorate %26 Location 1 +OpDecorate %28 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 @@ -30,38 +30,39 @@ OpDecorate %27 BuiltIn PointSize %8 = OpTypeInt 32 0 %9 = OpTypeStruct %6 %8 %6 %10 = OpTypeBool -%11 = OpTypeArray %8 %3 -%12 = OpTypeVector %8 3 -%13 = OpTypeStruct %8 +%12 = OpConstant %8 1 +%11 = OpTypeArray %8 %12 +%13 = OpTypeVector %8 3 %14 = OpTypeStruct %8 -%17 = OpTypePointer Input %8 -%16 = OpVariable %17 Input -%19 = OpVariable %17 Input -%21 = OpVariable %17 Input -%24 = OpTypePointer Output %5 -%23 = OpVariable %24 Output -%26 = OpTypePointer Output %6 -%25 = OpVariable %26 Output -%28 = OpTypePointer Output %6 -%27 = OpVariable %28 Output -%29 = OpConstant %6 1.0 -%31 = OpTypeFunction %2 -%30 = OpFunction %2 None %31 -%15 = OpLabel -%18 = OpLoad %8 %16 -%20 = OpLoad %8 %19 -%22 = OpLoad %8 %21 -OpStore %27 %29 -OpBranch %32 -%32 = OpLabel -%33 = OpIAdd %8 %18 %20 -%34 = OpIAdd %8 %33 %22 -%35 = OpCompositeConstruct %5 %29 %29 %29 %29 -%36 = OpConvertUToF %6 %34 -%37 = OpCompositeConstruct %7 %35 %36 -%38 = OpCompositeExtract %5 %37 0 -OpStore %23 %38 -%39 = OpCompositeExtract %6 %37 1 -OpStore %25 %39 +%15 = OpTypeStruct %8 +%18 = OpTypePointer Input %8 +%17 = OpVariable %18 Input +%20 = OpVariable %18 Input +%22 = OpVariable %18 Input +%25 = OpTypePointer Output %5 +%24 = OpVariable %25 Output +%27 = OpTypePointer Output %6 +%26 = OpVariable %27 Output +%29 = OpTypePointer Output %6 +%28 = OpVariable %29 Output +%30 = OpConstant %6 1.0 +%32 = OpTypeFunction %2 +%31 = OpFunction %2 None %32 +%16 = OpLabel +%19 = OpLoad %8 %17 +%21 = OpLoad %8 %20 +%23 = OpLoad %8 %22 +OpStore %28 %30 +OpBranch %33 +%33 = OpLabel +%34 = OpIAdd %8 %19 %21 +%35 = OpIAdd %8 %34 %23 +%36 = OpCompositeConstruct %5 %30 %30 %30 %30 +%37 = OpConvertUToF %6 %35 +%38 = OpCompositeConstruct %7 %36 %37 +%39 = OpCompositeExtract %5 %38 0 +OpStore %24 %39 +%40 = OpCompositeExtract %6 %38 1 +OpStore %26 %40 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index 7c6c8fd1e..5f555c019 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -1,24 +1,24 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 43 +; Bound: 44 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %31 "vertex_two_structs" %20 %24 %26 %28 +OpEntryPoint Vertex %32 "vertex_two_structs" %21 %25 %27 %29 OpMemberDecorate %7 0 Offset 0 OpMemberDecorate %7 1 Offset 16 OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 4 OpMemberDecorate %9 2 Offset 8 OpDecorate %11 ArrayStride 4 -OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %14 0 Offset 0 -OpDecorate %20 BuiltIn VertexIndex -OpDecorate %24 BuiltIn InstanceIndex -OpDecorate %26 Invariant -OpDecorate %26 BuiltIn Position -OpDecorate %28 BuiltIn PointSize +OpMemberDecorate %15 0 Offset 0 +OpDecorate %21 BuiltIn VertexIndex +OpDecorate %25 BuiltIn InstanceIndex +OpDecorate %27 Invariant +OpDecorate %27 BuiltIn Position +OpDecorate %29 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 @@ -28,41 +28,42 @@ OpDecorate %28 BuiltIn PointSize %8 = OpTypeInt 32 0 %9 = OpTypeStruct %6 %8 %6 %10 = OpTypeBool -%11 = OpTypeArray %8 %3 -%12 = OpTypeVector %8 3 -%13 = OpTypeStruct %8 +%12 = OpConstant %8 1 +%11 = OpTypeArray %8 %12 +%13 = OpTypeVector %8 3 %14 = OpTypeStruct %8 -%16 = OpTypePointer Function %8 -%17 = OpConstantNull %8 -%21 = OpTypePointer Input %8 -%20 = OpVariable %21 Input -%24 = OpVariable %21 Input -%27 = OpTypePointer Output %5 -%26 = OpVariable %27 Output -%29 = OpTypePointer Output %6 -%28 = OpVariable %29 Output -%30 = OpConstant %6 1.0 -%32 = OpTypeFunction %2 -%33 = OpConstant %8 2 -%34 = OpConstant %6 0.0 -%31 = OpFunction %2 None %32 -%18 = OpLabel -%15 = OpVariable %16 Function %17 -%22 = OpLoad %8 %20 -%19 = OpCompositeConstruct %13 %22 -%25 = OpLoad %8 %24 -%23 = OpCompositeConstruct %14 %25 -OpStore %28 %30 -OpBranch %35 -%35 = OpLabel -OpStore %15 %33 -%36 = OpCompositeExtract %8 %19 0 -%37 = OpConvertUToF %6 %36 -%38 = OpCompositeExtract %8 %23 0 -%39 = OpConvertUToF %6 %38 -%40 = OpLoad %8 %15 -%41 = OpConvertUToF %6 %40 -%42 = OpCompositeConstruct %5 %37 %39 %41 %34 -OpStore %26 %42 +%15 = OpTypeStruct %8 +%17 = OpTypePointer Function %8 +%18 = OpConstantNull %8 +%22 = OpTypePointer Input %8 +%21 = OpVariable %22 Input +%25 = OpVariable %22 Input +%28 = OpTypePointer Output %5 +%27 = OpVariable %28 Output +%30 = OpTypePointer Output %6 +%29 = OpVariable %30 Output +%31 = OpConstant %6 1.0 +%33 = OpTypeFunction %2 +%34 = OpConstant %8 2 +%35 = OpConstant %6 0.0 +%32 = OpFunction %2 None %33 +%19 = OpLabel +%16 = OpVariable %17 Function %18 +%23 = OpLoad %8 %21 +%20 = OpCompositeConstruct %14 %23 +%26 = OpLoad %8 %25 +%24 = OpCompositeConstruct %15 %26 +OpStore %29 %31 +OpBranch %36 +%36 = OpLabel +OpStore %16 %34 +%37 = OpCompositeExtract %8 %20 0 +%38 = OpConvertUToF %6 %37 +%39 = OpCompositeExtract %8 %24 0 +%40 = OpConvertUToF %6 %39 +%41 = OpLoad %8 %16 +%42 = OpConvertUToF %6 %41 +%43 = OpCompositeConstruct %5 %38 %40 %42 %35 +OpStore %27 %43 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 1fc38dea9..945775292 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,15 +1,15 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 588 +; Bound: 589 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %576 "main" -OpExecutionMode %576 LocalSize 1 1 1 -OpMemberDecorate %19 0 Offset 0 -OpMemberDecorate %19 1 Offset 16 -OpDecorate %23 ArrayStride 32 +OpEntryPoint GLCompute %577 "main" +OpExecutionMode %577 LocalSize 1 1 1 +OpMemberDecorate %17 0 Offset 0 +OpMemberDecorate %17 1 Offset 16 +OpDecorate %22 ArrayStride 32 OpDecorate %24 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeFloat 32 @@ -19,632 +19,633 @@ OpDecorate %24 ArrayStride 4 %8 = OpTypeInt 32 1 %7 = OpConstant %8 1 %9 = OpConstant %8 3 -%11 = OpTypeInt 32 0 -%10 = OpConstant %11 4 -%12 = OpTypeVector %4 4 -%13 = OpTypeVector %8 4 -%15 = OpTypeBool -%14 = OpTypeVector %15 4 -%16 = OpTypeVector %4 2 -%17 = OpTypeVector %4 3 -%18 = OpTypeVector %15 3 -%19 = OpTypeStruct %12 %8 -%20 = OpTypeMatrix %16 2 -%21 = OpTypeMatrix %12 4 -%22 = OpTypeVector %11 2 -%23 = OpTypeArray %19 %9 -%24 = OpTypeArray %8 %10 -%25 = OpTypeMatrix %17 2 -%26 = OpTypeMatrix %17 3 -%27 = OpTypeMatrix %17 4 -%28 = OpTypeMatrix %12 3 -%29 = OpTypeVector %8 3 -%30 = OpConstantComposite %12 %3 %3 %3 %3 -%31 = OpConstantComposite %12 %5 %5 %5 %5 -%32 = OpConstantComposite %12 %6 %6 %6 %6 -%33 = OpConstantComposite %13 %7 %7 %7 %7 -%36 = OpTypeFunction %12 -%37 = OpConstantTrue %15 -%38 = OpConstant %8 0 -%39 = OpConstantFalse %15 -%40 = OpConstant %4 0.1 -%65 = OpConstant %4 2.0 -%66 = OpConstant %4 3.0 -%67 = OpConstant %4 4.0 -%68 = OpConstant %8 5 -%69 = OpConstant %8 2 -%85 = OpTypePointer Function %16 -%86 = OpConstantNull %16 -%89 = OpTypeFunction %16 -%105 = OpTypeFunction %17 %17 -%107 = OpConstantComposite %17 %5 %5 %5 -%109 = OpConstantComposite %17 %3 %3 %3 -%112 = OpTypePointer Function %19 -%113 = OpConstantNull %19 -%116 = OpTypeFunction %4 -%117 = OpConstantNull %15 -%118 = OpConstantNull %8 -%119 = OpConstantNull %11 -%120 = OpConstantNull %4 -%121 = OpConstantNull %22 -%122 = OpConstantNull %20 -%123 = OpConstantNull %23 -%124 = OpConstantNull %19 -%125 = OpConstant %11 0 -%126 = OpConstantNull %15 -%127 = OpConstantNull %8 -%128 = OpConstantNull %11 -%129 = OpConstantNull %4 -%130 = OpConstantNull %22 -%131 = OpConstantNull %25 -%132 = OpConstantNull %22 -%133 = OpConstantNull %25 -%158 = OpTypePointer Function %12 -%159 = OpTypePointer Function %4 -%164 = OpTypeFunction %2 -%167 = OpTypeVector %15 2 -%182 = OpConstant %4 -1.0 -%183 = OpConstant %11 2 -%184 = OpConstant %11 1 -%185 = OpConstantNull %26 -%186 = OpConstantNull %26 -%187 = OpConstantNull %26 -%188 = OpConstantNull %26 -%189 = OpConstantNull %26 -%190 = OpConstantNull %26 +%10 = OpTypeVector %4 4 +%11 = OpTypeVector %8 4 +%13 = OpTypeBool +%12 = OpTypeVector %13 4 +%14 = OpTypeVector %4 2 +%15 = OpTypeVector %4 3 +%16 = OpTypeVector %13 3 +%17 = OpTypeStruct %10 %8 +%18 = OpTypeMatrix %14 2 +%19 = OpTypeMatrix %10 4 +%20 = OpTypeInt 32 0 +%21 = OpTypeVector %20 2 +%23 = OpConstant %20 3 +%22 = OpTypeArray %17 %23 +%25 = OpConstant %20 4 +%24 = OpTypeArray %8 %25 +%26 = OpTypeMatrix %15 2 +%27 = OpTypeMatrix %15 3 +%28 = OpTypeMatrix %15 4 +%29 = OpTypeMatrix %10 3 +%30 = OpTypeVector %8 3 +%31 = OpConstantComposite %10 %3 %3 %3 %3 +%32 = OpConstantComposite %10 %5 %5 %5 %5 +%33 = OpConstantComposite %10 %6 %6 %6 %6 +%34 = OpConstantComposite %11 %7 %7 %7 %7 +%37 = OpTypeFunction %10 +%38 = OpConstantTrue %13 +%39 = OpConstant %8 0 +%40 = OpConstantFalse %13 +%41 = OpConstant %4 0.1 +%66 = OpConstant %4 2.0 +%67 = OpConstant %4 3.0 +%68 = OpConstant %4 4.0 +%69 = OpConstant %8 5 +%70 = OpConstant %8 2 +%86 = OpTypePointer Function %14 +%87 = OpConstantNull %14 +%90 = OpTypeFunction %14 +%106 = OpTypeFunction %15 %15 +%108 = OpConstantComposite %15 %5 %5 %5 +%110 = OpConstantComposite %15 %3 %3 %3 +%113 = OpTypePointer Function %17 +%114 = OpConstantNull %17 +%117 = OpTypeFunction %4 +%118 = OpConstantNull %13 +%119 = OpConstantNull %8 +%120 = OpConstantNull %20 +%121 = OpConstantNull %4 +%122 = OpConstantNull %21 +%123 = OpConstantNull %18 +%124 = OpConstantNull %22 +%125 = OpConstantNull %17 +%126 = OpConstant %20 0 +%127 = OpConstantNull %13 +%128 = OpConstantNull %8 +%129 = OpConstantNull %20 +%130 = OpConstantNull %4 +%131 = OpConstantNull %21 +%132 = OpConstantNull %26 +%133 = OpConstantNull %21 +%134 = OpConstantNull %26 +%159 = OpTypePointer Function %10 +%160 = OpTypePointer Function %4 +%165 = OpTypeFunction %2 +%168 = OpTypeVector %13 2 +%183 = OpConstant %4 -1.0 +%184 = OpConstant %20 2 +%185 = OpConstant %20 1 +%186 = OpConstantNull %27 +%187 = OpConstantNull %27 +%188 = OpConstantNull %27 +%189 = OpConstantNull %27 +%190 = OpConstantNull %27 %191 = OpConstantNull %27 -%192 = OpConstantNull %27 -%193 = OpConstantNull %27 +%192 = OpConstantNull %28 +%193 = OpConstantNull %28 %194 = OpConstantNull %28 -%196 = OpTypeVector %8 2 -%207 = OpTypeVector %11 3 -%502 = OpTypePointer Function %8 -%503 = OpConstantNull %8 -%505 = OpTypePointer Function %29 -%506 = OpConstantNull %29 -%509 = OpConstantNull %29 -%537 = OpTypePointer Function %8 -%548 = OpConstant %8 -1 -%549 = OpConstant %8 -2 -%550 = OpConstant %8 -3 -%551 = OpConstant %8 4 -%552 = OpConstant %8 -5 -%553 = OpConstant %8 6 -%554 = OpConstant %8 -7 -%555 = OpConstant %8 -8 -%35 = OpFunction %12 None %36 -%34 = OpLabel -OpBranch %41 -%41 = OpLabel -%42 = OpSelect %8 %37 %7 %38 -%44 = OpCompositeConstruct %14 %37 %37 %37 %37 -%43 = OpSelect %12 %44 %30 %31 -%45 = OpCompositeConstruct %14 %39 %39 %39 %39 -%46 = OpSelect %12 %45 %31 %30 -%47 = OpExtInst %12 %1 FMix %31 %30 %32 -%49 = OpCompositeConstruct %12 %40 %40 %40 %40 -%48 = OpExtInst %12 %1 FMix %31 %30 %49 -%50 = OpCompositeExtract %8 %33 0 -%51 = OpBitcast %4 %50 -%52 = OpBitcast %12 %33 -%53 = OpConvertFToS %13 %31 -%54 = OpCompositeConstruct %13 %42 %42 %42 %42 -%55 = OpIAdd %13 %54 %53 -%56 = OpConvertSToF %12 %55 -%57 = OpFAdd %12 %56 %43 -%58 = OpFAdd %12 %57 %47 -%59 = OpFAdd %12 %58 %48 -%60 = OpCompositeConstruct %12 %51 %51 %51 %51 -%61 = OpFAdd %12 %59 %60 -%62 = OpFAdd %12 %61 %52 -OpReturnValue %62 +%195 = OpConstantNull %29 +%197 = OpTypeVector %8 2 +%208 = OpTypeVector %20 3 +%503 = OpTypePointer Function %8 +%504 = OpConstantNull %8 +%506 = OpTypePointer Function %30 +%507 = OpConstantNull %30 +%510 = OpConstantNull %30 +%538 = OpTypePointer Function %8 +%549 = OpConstant %8 -1 +%550 = OpConstant %8 -2 +%551 = OpConstant %8 -3 +%552 = OpConstant %8 4 +%553 = OpConstant %8 -5 +%554 = OpConstant %8 6 +%555 = OpConstant %8 -7 +%556 = OpConstant %8 -8 +%36 = OpFunction %10 None %37 +%35 = OpLabel +OpBranch %42 +%42 = OpLabel +%43 = OpSelect %8 %38 %7 %39 +%45 = OpCompositeConstruct %12 %38 %38 %38 %38 +%44 = OpSelect %10 %45 %31 %32 +%46 = OpCompositeConstruct %12 %40 %40 %40 %40 +%47 = OpSelect %10 %46 %32 %31 +%48 = OpExtInst %10 %1 FMix %32 %31 %33 +%50 = OpCompositeConstruct %10 %41 %41 %41 %41 +%49 = OpExtInst %10 %1 FMix %32 %31 %50 +%51 = OpCompositeExtract %8 %34 0 +%52 = OpBitcast %4 %51 +%53 = OpBitcast %10 %34 +%54 = OpConvertFToS %11 %32 +%55 = OpCompositeConstruct %11 %43 %43 %43 %43 +%56 = OpIAdd %11 %55 %54 +%57 = OpConvertSToF %10 %56 +%58 = OpFAdd %10 %57 %44 +%59 = OpFAdd %10 %58 %48 +%60 = OpFAdd %10 %59 %49 +%61 = OpCompositeConstruct %10 %52 %52 %52 %52 +%62 = OpFAdd %10 %60 %61 +%63 = OpFAdd %10 %62 %53 +OpReturnValue %63 OpFunctionEnd -%64 = OpFunction %12 None %36 -%63 = OpLabel -OpBranch %70 -%70 = OpLabel -%71 = OpCompositeConstruct %16 %65 %65 -%72 = OpCompositeConstruct %16 %3 %3 -%73 = OpFAdd %16 %72 %71 -%74 = OpCompositeConstruct %16 %66 %66 -%75 = OpFSub %16 %73 %74 -%76 = OpCompositeConstruct %16 %67 %67 -%77 = OpFDiv %16 %75 %76 -%78 = OpCompositeConstruct %13 %68 %68 %68 %68 -%79 = OpCompositeConstruct %13 %69 %69 %69 %69 -%80 = OpSRem %13 %78 %79 -%81 = OpVectorShuffle %12 %77 %77 0 1 0 1 -%82 = OpConvertSToF %12 %80 -%83 = OpFAdd %12 %81 %82 -OpReturnValue %83 +%65 = OpFunction %10 None %37 +%64 = OpLabel +OpBranch %71 +%71 = OpLabel +%72 = OpCompositeConstruct %14 %66 %66 +%73 = OpCompositeConstruct %14 %3 %3 +%74 = OpFAdd %14 %73 %72 +%75 = OpCompositeConstruct %14 %67 %67 +%76 = OpFSub %14 %74 %75 +%77 = OpCompositeConstruct %14 %68 %68 +%78 = OpFDiv %14 %76 %77 +%79 = OpCompositeConstruct %11 %69 %69 %69 %69 +%80 = OpCompositeConstruct %11 %70 %70 %70 %70 +%81 = OpSRem %11 %79 %80 +%82 = OpVectorShuffle %10 %78 %78 0 1 0 1 +%83 = OpConvertSToF %10 %81 +%84 = OpFAdd %10 %82 %83 +OpReturnValue %84 OpFunctionEnd -%88 = OpFunction %16 None %89 -%87 = OpLabel -%84 = OpVariable %85 Function %86 -OpBranch %90 -%90 = OpLabel -%91 = OpCompositeConstruct %16 %65 %65 -OpStore %84 %91 -%92 = OpLoad %16 %84 -%93 = OpCompositeConstruct %16 %3 %3 -%94 = OpFAdd %16 %92 %93 -OpStore %84 %94 -%95 = OpLoad %16 %84 -%96 = OpCompositeConstruct %16 %66 %66 -%97 = OpFSub %16 %95 %96 -OpStore %84 %97 -%98 = OpLoad %16 %84 -%99 = OpCompositeConstruct %16 %67 %67 -%100 = OpFDiv %16 %98 %99 -OpStore %84 %100 -%101 = OpLoad %16 %84 -OpReturnValue %101 +%89 = OpFunction %14 None %90 +%88 = OpLabel +%85 = OpVariable %86 Function %87 +OpBranch %91 +%91 = OpLabel +%92 = OpCompositeConstruct %14 %66 %66 +OpStore %85 %92 +%93 = OpLoad %14 %85 +%94 = OpCompositeConstruct %14 %3 %3 +%95 = OpFAdd %14 %93 %94 +OpStore %85 %95 +%96 = OpLoad %14 %85 +%97 = OpCompositeConstruct %14 %67 %67 +%98 = OpFSub %14 %96 %97 +OpStore %85 %98 +%99 = OpLoad %14 %85 +%100 = OpCompositeConstruct %14 %68 %68 +%101 = OpFDiv %14 %99 %100 +OpStore %85 %101 +%102 = OpLoad %14 %85 +OpReturnValue %102 OpFunctionEnd -%104 = OpFunction %17 None %105 -%103 = OpFunctionParameter %17 -%102 = OpLabel -OpBranch %106 -%106 = OpLabel -%108 = OpFUnordNotEqual %18 %103 %107 -%110 = OpSelect %17 %108 %109 %107 -OpReturnValue %110 +%105 = OpFunction %15 None %106 +%104 = OpFunctionParameter %15 +%103 = OpLabel +OpBranch %107 +%107 = OpLabel +%109 = OpFUnordNotEqual %16 %104 %108 +%111 = OpSelect %15 %109 %110 %108 +OpReturnValue %111 OpFunctionEnd -%115 = OpFunction %4 None %116 -%114 = OpLabel -%111 = OpVariable %112 Function %113 -OpBranch %134 -%134 = OpLabel -%135 = OpCompositeConstruct %12 %3 %3 %3 %3 -%136 = OpCompositeConstruct %19 %135 %7 -OpStore %111 %136 -%137 = OpCompositeConstruct %16 %3 %5 -%138 = OpCompositeConstruct %16 %5 %3 -%139 = OpCompositeConstruct %20 %137 %138 -%140 = OpCompositeConstruct %12 %3 %5 %5 %5 -%141 = OpCompositeConstruct %12 %5 %3 %5 %5 -%142 = OpCompositeConstruct %12 %5 %5 %3 %5 -%143 = OpCompositeConstruct %12 %5 %5 %5 %3 -%144 = OpCompositeConstruct %21 %140 %141 %142 %143 -%145 = OpCompositeConstruct %22 %125 %125 -%146 = OpCompositeConstruct %16 %5 %5 -%147 = OpCompositeConstruct %16 %5 %5 -%148 = OpCompositeConstruct %20 %146 %147 -%149 = OpCompositeConstruct %24 %38 %7 %69 %9 -%155 = OpCopyObject %25 %131 -%157 = OpCopyObject %25 %133 -%160 = OpAccessChain %159 %111 %125 %125 -%161 = OpLoad %4 %160 -OpReturnValue %161 +%116 = OpFunction %4 None %117 +%115 = OpLabel +%112 = OpVariable %113 Function %114 +OpBranch %135 +%135 = OpLabel +%136 = OpCompositeConstruct %10 %3 %3 %3 %3 +%137 = OpCompositeConstruct %17 %136 %7 +OpStore %112 %137 +%138 = OpCompositeConstruct %14 %3 %5 +%139 = OpCompositeConstruct %14 %5 %3 +%140 = OpCompositeConstruct %18 %138 %139 +%141 = OpCompositeConstruct %10 %3 %5 %5 %5 +%142 = OpCompositeConstruct %10 %5 %3 %5 %5 +%143 = OpCompositeConstruct %10 %5 %5 %3 %5 +%144 = OpCompositeConstruct %10 %5 %5 %5 %3 +%145 = OpCompositeConstruct %19 %141 %142 %143 %144 +%146 = OpCompositeConstruct %21 %126 %126 +%147 = OpCompositeConstruct %14 %5 %5 +%148 = OpCompositeConstruct %14 %5 %5 +%149 = OpCompositeConstruct %18 %147 %148 +%150 = OpCompositeConstruct %24 %39 %7 %70 %9 +%156 = OpCopyObject %26 %132 +%158 = OpCopyObject %26 %134 +%161 = OpAccessChain %160 %112 %126 %126 +%162 = OpLoad %4 %161 +OpReturnValue %162 OpFunctionEnd -%163 = OpFunction %2 None %164 -%162 = OpLabel -OpBranch %165 -%165 = OpLabel -%166 = OpLogicalNot %15 %37 -%168 = OpCompositeConstruct %167 %37 %37 -%169 = OpLogicalNot %167 %168 -%170 = OpLogicalOr %15 %37 %39 -%171 = OpLogicalAnd %15 %37 %39 -%172 = OpLogicalOr %15 %37 %39 -%173 = OpCompositeConstruct %18 %37 %37 %37 -%174 = OpCompositeConstruct %18 %39 %39 %39 -%175 = OpLogicalOr %18 %173 %174 -%176 = OpLogicalAnd %15 %37 %39 -%177 = OpCompositeConstruct %14 %37 %37 %37 %37 -%178 = OpCompositeConstruct %14 %39 %39 %39 %39 -%179 = OpLogicalAnd %14 %177 %178 +%164 = OpFunction %2 None %165 +%163 = OpLabel +OpBranch %166 +%166 = OpLabel +%167 = OpLogicalNot %13 %38 +%169 = OpCompositeConstruct %168 %38 %38 +%170 = OpLogicalNot %168 %169 +%171 = OpLogicalOr %13 %38 %40 +%172 = OpLogicalAnd %13 %38 %40 +%173 = OpLogicalOr %13 %38 %40 +%174 = OpCompositeConstruct %16 %38 %38 %38 +%175 = OpCompositeConstruct %16 %40 %40 %40 +%176 = OpLogicalOr %16 %174 %175 +%177 = OpLogicalAnd %13 %38 %40 +%178 = OpCompositeConstruct %12 %38 %38 %38 %38 +%179 = OpCompositeConstruct %12 %40 %40 %40 %40 +%180 = OpLogicalAnd %12 %178 %179 OpReturn OpFunctionEnd -%181 = OpFunction %2 None %164 -%180 = OpLabel -OpBranch %195 -%195 = OpLabel -%197 = OpCompositeConstruct %196 %7 %7 -%198 = OpSNegate %196 %197 -%199 = OpCompositeConstruct %16 %3 %3 -%200 = OpFNegate %16 %199 -%201 = OpIAdd %8 %69 %7 -%202 = OpIAdd %11 %183 %184 -%203 = OpFAdd %4 %65 %3 -%204 = OpCompositeConstruct %196 %69 %69 -%205 = OpCompositeConstruct %196 %7 %7 -%206 = OpIAdd %196 %204 %205 -%208 = OpCompositeConstruct %207 %183 %183 %183 -%209 = OpCompositeConstruct %207 %184 %184 %184 -%210 = OpIAdd %207 %208 %209 -%211 = OpCompositeConstruct %12 %65 %65 %65 %65 -%212 = OpCompositeConstruct %12 %3 %3 %3 %3 -%213 = OpFAdd %12 %211 %212 -%214 = OpISub %8 %69 %7 -%215 = OpISub %11 %183 %184 -%216 = OpFSub %4 %65 %3 -%217 = OpCompositeConstruct %196 %69 %69 -%218 = OpCompositeConstruct %196 %7 %7 -%219 = OpISub %196 %217 %218 -%220 = OpCompositeConstruct %207 %183 %183 %183 -%221 = OpCompositeConstruct %207 %184 %184 %184 -%222 = OpISub %207 %220 %221 -%223 = OpCompositeConstruct %12 %65 %65 %65 %65 -%224 = OpCompositeConstruct %12 %3 %3 %3 %3 -%225 = OpFSub %12 %223 %224 -%226 = OpIMul %8 %69 %7 -%227 = OpIMul %11 %183 %184 -%228 = OpFMul %4 %65 %3 -%229 = OpCompositeConstruct %196 %69 %69 -%230 = OpCompositeConstruct %196 %7 %7 -%231 = OpIMul %196 %229 %230 -%232 = OpCompositeConstruct %207 %183 %183 %183 -%233 = OpCompositeConstruct %207 %184 %184 %184 -%234 = OpIMul %207 %232 %233 -%235 = OpCompositeConstruct %12 %65 %65 %65 %65 -%236 = OpCompositeConstruct %12 %3 %3 %3 %3 -%237 = OpFMul %12 %235 %236 -%238 = OpSDiv %8 %69 %7 -%239 = OpUDiv %11 %183 %184 -%240 = OpFDiv %4 %65 %3 -%241 = OpCompositeConstruct %196 %69 %69 -%242 = OpCompositeConstruct %196 %7 %7 -%243 = OpSDiv %196 %241 %242 -%244 = OpCompositeConstruct %207 %183 %183 %183 -%245 = OpCompositeConstruct %207 %184 %184 %184 -%246 = OpUDiv %207 %244 %245 -%247 = OpCompositeConstruct %12 %65 %65 %65 %65 -%248 = OpCompositeConstruct %12 %3 %3 %3 %3 -%249 = OpFDiv %12 %247 %248 -%250 = OpSRem %8 %69 %7 -%251 = OpUMod %11 %183 %184 -%252 = OpFRem %4 %65 %3 -%253 = OpCompositeConstruct %196 %69 %69 -%254 = OpCompositeConstruct %196 %7 %7 -%255 = OpSRem %196 %253 %254 -%256 = OpCompositeConstruct %207 %183 %183 %183 -%257 = OpCompositeConstruct %207 %184 %184 %184 -%258 = OpUMod %207 %256 %257 -%259 = OpCompositeConstruct %12 %65 %65 %65 %65 -%260 = OpCompositeConstruct %12 %3 %3 %3 %3 -%261 = OpFRem %12 %259 %260 -%262 = OpCompositeConstruct %196 %69 %69 -%263 = OpCompositeConstruct %196 %7 %7 -%264 = OpIAdd %196 %262 %263 -%265 = OpCompositeConstruct %196 %7 %7 -%266 = OpCompositeConstruct %196 %69 %69 -%267 = OpIAdd %196 %266 %265 -%268 = OpCompositeConstruct %22 %183 %183 -%269 = OpCompositeConstruct %22 %184 %184 -%270 = OpIAdd %22 %268 %269 -%271 = OpCompositeConstruct %22 %184 %184 -%272 = OpCompositeConstruct %22 %183 %183 -%273 = OpIAdd %22 %272 %271 -%274 = OpCompositeConstruct %16 %65 %65 -%275 = OpCompositeConstruct %16 %3 %3 -%276 = OpFAdd %16 %274 %275 -%277 = OpCompositeConstruct %16 %3 %3 -%278 = OpCompositeConstruct %16 %65 %65 -%279 = OpFAdd %16 %278 %277 -%280 = OpCompositeConstruct %196 %69 %69 -%281 = OpCompositeConstruct %196 %7 %7 -%282 = OpISub %196 %280 %281 -%283 = OpCompositeConstruct %196 %7 %7 -%284 = OpCompositeConstruct %196 %69 %69 -%285 = OpISub %196 %284 %283 -%286 = OpCompositeConstruct %22 %183 %183 -%287 = OpCompositeConstruct %22 %184 %184 -%288 = OpISub %22 %286 %287 -%289 = OpCompositeConstruct %22 %184 %184 -%290 = OpCompositeConstruct %22 %183 %183 -%291 = OpISub %22 %290 %289 -%292 = OpCompositeConstruct %16 %65 %65 -%293 = OpCompositeConstruct %16 %3 %3 -%294 = OpFSub %16 %292 %293 -%295 = OpCompositeConstruct %16 %3 %3 -%296 = OpCompositeConstruct %16 %65 %65 -%297 = OpFSub %16 %296 %295 -%298 = OpCompositeConstruct %196 %69 %69 -%300 = OpCompositeConstruct %196 %7 %7 -%299 = OpIMul %196 %298 %300 -%301 = OpCompositeConstruct %196 %7 %7 -%303 = OpCompositeConstruct %196 %69 %69 -%302 = OpIMul %196 %301 %303 -%304 = OpCompositeConstruct %22 %183 %183 -%306 = OpCompositeConstruct %22 %184 %184 -%305 = OpIMul %22 %304 %306 -%307 = OpCompositeConstruct %22 %184 %184 -%309 = OpCompositeConstruct %22 %183 %183 -%308 = OpIMul %22 %307 %309 -%310 = OpCompositeConstruct %16 %65 %65 -%311 = OpVectorTimesScalar %16 %310 %3 -%312 = OpCompositeConstruct %16 %3 %3 -%313 = OpVectorTimesScalar %16 %312 %65 -%314 = OpCompositeConstruct %196 %69 %69 -%315 = OpCompositeConstruct %196 %7 %7 -%316 = OpSDiv %196 %314 %315 -%317 = OpCompositeConstruct %196 %7 %7 -%318 = OpCompositeConstruct %196 %69 %69 -%319 = OpSDiv %196 %318 %317 -%320 = OpCompositeConstruct %22 %183 %183 -%321 = OpCompositeConstruct %22 %184 %184 -%322 = OpUDiv %22 %320 %321 -%323 = OpCompositeConstruct %22 %184 %184 -%324 = OpCompositeConstruct %22 %183 %183 -%325 = OpUDiv %22 %324 %323 -%326 = OpCompositeConstruct %16 %65 %65 -%327 = OpCompositeConstruct %16 %3 %3 -%328 = OpFDiv %16 %326 %327 -%329 = OpCompositeConstruct %16 %3 %3 -%330 = OpCompositeConstruct %16 %65 %65 -%331 = OpFDiv %16 %330 %329 -%332 = OpCompositeConstruct %196 %69 %69 -%333 = OpCompositeConstruct %196 %7 %7 -%334 = OpSRem %196 %332 %333 -%335 = OpCompositeConstruct %196 %7 %7 -%336 = OpCompositeConstruct %196 %69 %69 -%337 = OpSRem %196 %336 %335 -%338 = OpCompositeConstruct %22 %183 %183 -%339 = OpCompositeConstruct %22 %184 %184 -%340 = OpUMod %22 %338 %339 -%341 = OpCompositeConstruct %22 %184 %184 -%342 = OpCompositeConstruct %22 %183 %183 -%343 = OpUMod %22 %342 %341 -%344 = OpCompositeConstruct %16 %65 %65 -%345 = OpCompositeConstruct %16 %3 %3 -%346 = OpFRem %16 %344 %345 -%347 = OpCompositeConstruct %16 %3 %3 -%348 = OpCompositeConstruct %16 %65 %65 -%349 = OpFRem %16 %348 %347 -%351 = OpCompositeExtract %17 %185 0 -%352 = OpCompositeExtract %17 %186 0 -%353 = OpFAdd %17 %351 %352 -%354 = OpCompositeExtract %17 %185 1 -%355 = OpCompositeExtract %17 %186 1 -%356 = OpFAdd %17 %354 %355 -%357 = OpCompositeExtract %17 %185 2 -%358 = OpCompositeExtract %17 %186 2 -%359 = OpFAdd %17 %357 %358 -%350 = OpCompositeConstruct %26 %353 %356 %359 -%361 = OpCompositeExtract %17 %187 0 -%362 = OpCompositeExtract %17 %188 0 -%363 = OpFSub %17 %361 %362 -%364 = OpCompositeExtract %17 %187 1 -%365 = OpCompositeExtract %17 %188 1 -%366 = OpFSub %17 %364 %365 -%367 = OpCompositeExtract %17 %187 2 -%368 = OpCompositeExtract %17 %188 2 -%369 = OpFSub %17 %367 %368 -%360 = OpCompositeConstruct %26 %363 %366 %369 -%370 = OpMatrixTimesScalar %26 %189 %3 -%371 = OpMatrixTimesScalar %26 %190 %65 -%372 = OpCompositeConstruct %12 %3 %3 %3 %3 -%373 = OpMatrixTimesVector %17 %191 %372 -%374 = OpCompositeConstruct %17 %65 %65 %65 -%375 = OpVectorTimesMatrix %12 %374 %192 -%376 = OpMatrixTimesMatrix %26 %193 %194 +%182 = OpFunction %2 None %165 +%181 = OpLabel +OpBranch %196 +%196 = OpLabel +%198 = OpCompositeConstruct %197 %7 %7 +%199 = OpSNegate %197 %198 +%200 = OpCompositeConstruct %14 %3 %3 +%201 = OpFNegate %14 %200 +%202 = OpIAdd %8 %70 %7 +%203 = OpIAdd %20 %184 %185 +%204 = OpFAdd %4 %66 %3 +%205 = OpCompositeConstruct %197 %70 %70 +%206 = OpCompositeConstruct %197 %7 %7 +%207 = OpIAdd %197 %205 %206 +%209 = OpCompositeConstruct %208 %184 %184 %184 +%210 = OpCompositeConstruct %208 %185 %185 %185 +%211 = OpIAdd %208 %209 %210 +%212 = OpCompositeConstruct %10 %66 %66 %66 %66 +%213 = OpCompositeConstruct %10 %3 %3 %3 %3 +%214 = OpFAdd %10 %212 %213 +%215 = OpISub %8 %70 %7 +%216 = OpISub %20 %184 %185 +%217 = OpFSub %4 %66 %3 +%218 = OpCompositeConstruct %197 %70 %70 +%219 = OpCompositeConstruct %197 %7 %7 +%220 = OpISub %197 %218 %219 +%221 = OpCompositeConstruct %208 %184 %184 %184 +%222 = OpCompositeConstruct %208 %185 %185 %185 +%223 = OpISub %208 %221 %222 +%224 = OpCompositeConstruct %10 %66 %66 %66 %66 +%225 = OpCompositeConstruct %10 %3 %3 %3 %3 +%226 = OpFSub %10 %224 %225 +%227 = OpIMul %8 %70 %7 +%228 = OpIMul %20 %184 %185 +%229 = OpFMul %4 %66 %3 +%230 = OpCompositeConstruct %197 %70 %70 +%231 = OpCompositeConstruct %197 %7 %7 +%232 = OpIMul %197 %230 %231 +%233 = OpCompositeConstruct %208 %184 %184 %184 +%234 = OpCompositeConstruct %208 %185 %185 %185 +%235 = OpIMul %208 %233 %234 +%236 = OpCompositeConstruct %10 %66 %66 %66 %66 +%237 = OpCompositeConstruct %10 %3 %3 %3 %3 +%238 = OpFMul %10 %236 %237 +%239 = OpSDiv %8 %70 %7 +%240 = OpUDiv %20 %184 %185 +%241 = OpFDiv %4 %66 %3 +%242 = OpCompositeConstruct %197 %70 %70 +%243 = OpCompositeConstruct %197 %7 %7 +%244 = OpSDiv %197 %242 %243 +%245 = OpCompositeConstruct %208 %184 %184 %184 +%246 = OpCompositeConstruct %208 %185 %185 %185 +%247 = OpUDiv %208 %245 %246 +%248 = OpCompositeConstruct %10 %66 %66 %66 %66 +%249 = OpCompositeConstruct %10 %3 %3 %3 %3 +%250 = OpFDiv %10 %248 %249 +%251 = OpSRem %8 %70 %7 +%252 = OpUMod %20 %184 %185 +%253 = OpFRem %4 %66 %3 +%254 = OpCompositeConstruct %197 %70 %70 +%255 = OpCompositeConstruct %197 %7 %7 +%256 = OpSRem %197 %254 %255 +%257 = OpCompositeConstruct %208 %184 %184 %184 +%258 = OpCompositeConstruct %208 %185 %185 %185 +%259 = OpUMod %208 %257 %258 +%260 = OpCompositeConstruct %10 %66 %66 %66 %66 +%261 = OpCompositeConstruct %10 %3 %3 %3 %3 +%262 = OpFRem %10 %260 %261 +%263 = OpCompositeConstruct %197 %70 %70 +%264 = OpCompositeConstruct %197 %7 %7 +%265 = OpIAdd %197 %263 %264 +%266 = OpCompositeConstruct %197 %7 %7 +%267 = OpCompositeConstruct %197 %70 %70 +%268 = OpIAdd %197 %267 %266 +%269 = OpCompositeConstruct %21 %184 %184 +%270 = OpCompositeConstruct %21 %185 %185 +%271 = OpIAdd %21 %269 %270 +%272 = OpCompositeConstruct %21 %185 %185 +%273 = OpCompositeConstruct %21 %184 %184 +%274 = OpIAdd %21 %273 %272 +%275 = OpCompositeConstruct %14 %66 %66 +%276 = OpCompositeConstruct %14 %3 %3 +%277 = OpFAdd %14 %275 %276 +%278 = OpCompositeConstruct %14 %3 %3 +%279 = OpCompositeConstruct %14 %66 %66 +%280 = OpFAdd %14 %279 %278 +%281 = OpCompositeConstruct %197 %70 %70 +%282 = OpCompositeConstruct %197 %7 %7 +%283 = OpISub %197 %281 %282 +%284 = OpCompositeConstruct %197 %7 %7 +%285 = OpCompositeConstruct %197 %70 %70 +%286 = OpISub %197 %285 %284 +%287 = OpCompositeConstruct %21 %184 %184 +%288 = OpCompositeConstruct %21 %185 %185 +%289 = OpISub %21 %287 %288 +%290 = OpCompositeConstruct %21 %185 %185 +%291 = OpCompositeConstruct %21 %184 %184 +%292 = OpISub %21 %291 %290 +%293 = OpCompositeConstruct %14 %66 %66 +%294 = OpCompositeConstruct %14 %3 %3 +%295 = OpFSub %14 %293 %294 +%296 = OpCompositeConstruct %14 %3 %3 +%297 = OpCompositeConstruct %14 %66 %66 +%298 = OpFSub %14 %297 %296 +%299 = OpCompositeConstruct %197 %70 %70 +%301 = OpCompositeConstruct %197 %7 %7 +%300 = OpIMul %197 %299 %301 +%302 = OpCompositeConstruct %197 %7 %7 +%304 = OpCompositeConstruct %197 %70 %70 +%303 = OpIMul %197 %302 %304 +%305 = OpCompositeConstruct %21 %184 %184 +%307 = OpCompositeConstruct %21 %185 %185 +%306 = OpIMul %21 %305 %307 +%308 = OpCompositeConstruct %21 %185 %185 +%310 = OpCompositeConstruct %21 %184 %184 +%309 = OpIMul %21 %308 %310 +%311 = OpCompositeConstruct %14 %66 %66 +%312 = OpVectorTimesScalar %14 %311 %3 +%313 = OpCompositeConstruct %14 %3 %3 +%314 = OpVectorTimesScalar %14 %313 %66 +%315 = OpCompositeConstruct %197 %70 %70 +%316 = OpCompositeConstruct %197 %7 %7 +%317 = OpSDiv %197 %315 %316 +%318 = OpCompositeConstruct %197 %7 %7 +%319 = OpCompositeConstruct %197 %70 %70 +%320 = OpSDiv %197 %319 %318 +%321 = OpCompositeConstruct %21 %184 %184 +%322 = OpCompositeConstruct %21 %185 %185 +%323 = OpUDiv %21 %321 %322 +%324 = OpCompositeConstruct %21 %185 %185 +%325 = OpCompositeConstruct %21 %184 %184 +%326 = OpUDiv %21 %325 %324 +%327 = OpCompositeConstruct %14 %66 %66 +%328 = OpCompositeConstruct %14 %3 %3 +%329 = OpFDiv %14 %327 %328 +%330 = OpCompositeConstruct %14 %3 %3 +%331 = OpCompositeConstruct %14 %66 %66 +%332 = OpFDiv %14 %331 %330 +%333 = OpCompositeConstruct %197 %70 %70 +%334 = OpCompositeConstruct %197 %7 %7 +%335 = OpSRem %197 %333 %334 +%336 = OpCompositeConstruct %197 %7 %7 +%337 = OpCompositeConstruct %197 %70 %70 +%338 = OpSRem %197 %337 %336 +%339 = OpCompositeConstruct %21 %184 %184 +%340 = OpCompositeConstruct %21 %185 %185 +%341 = OpUMod %21 %339 %340 +%342 = OpCompositeConstruct %21 %185 %185 +%343 = OpCompositeConstruct %21 %184 %184 +%344 = OpUMod %21 %343 %342 +%345 = OpCompositeConstruct %14 %66 %66 +%346 = OpCompositeConstruct %14 %3 %3 +%347 = OpFRem %14 %345 %346 +%348 = OpCompositeConstruct %14 %3 %3 +%349 = OpCompositeConstruct %14 %66 %66 +%350 = OpFRem %14 %349 %348 +%352 = OpCompositeExtract %15 %186 0 +%353 = OpCompositeExtract %15 %187 0 +%354 = OpFAdd %15 %352 %353 +%355 = OpCompositeExtract %15 %186 1 +%356 = OpCompositeExtract %15 %187 1 +%357 = OpFAdd %15 %355 %356 +%358 = OpCompositeExtract %15 %186 2 +%359 = OpCompositeExtract %15 %187 2 +%360 = OpFAdd %15 %358 %359 +%351 = OpCompositeConstruct %27 %354 %357 %360 +%362 = OpCompositeExtract %15 %188 0 +%363 = OpCompositeExtract %15 %189 0 +%364 = OpFSub %15 %362 %363 +%365 = OpCompositeExtract %15 %188 1 +%366 = OpCompositeExtract %15 %189 1 +%367 = OpFSub %15 %365 %366 +%368 = OpCompositeExtract %15 %188 2 +%369 = OpCompositeExtract %15 %189 2 +%370 = OpFSub %15 %368 %369 +%361 = OpCompositeConstruct %27 %364 %367 %370 +%371 = OpMatrixTimesScalar %27 %190 %3 +%372 = OpMatrixTimesScalar %27 %191 %66 +%373 = OpCompositeConstruct %10 %3 %3 %3 %3 +%374 = OpMatrixTimesVector %15 %192 %373 +%375 = OpCompositeConstruct %15 %66 %66 %66 +%376 = OpVectorTimesMatrix %10 %375 %193 +%377 = OpMatrixTimesMatrix %27 %194 %195 OpReturn OpFunctionEnd -%378 = OpFunction %2 None %164 -%377 = OpLabel -OpBranch %379 -%379 = OpLabel -%380 = OpNot %8 %7 -%381 = OpNot %11 %184 -%382 = OpCompositeConstruct %196 %7 %7 -%383 = OpNot %196 %382 -%384 = OpCompositeConstruct %207 %184 %184 %184 -%385 = OpNot %207 %384 -%386 = OpBitwiseOr %8 %69 %7 -%387 = OpBitwiseOr %11 %183 %184 -%388 = OpCompositeConstruct %196 %69 %69 -%389 = OpCompositeConstruct %196 %7 %7 -%390 = OpBitwiseOr %196 %388 %389 -%391 = OpCompositeConstruct %207 %183 %183 %183 -%392 = OpCompositeConstruct %207 %184 %184 %184 -%393 = OpBitwiseOr %207 %391 %392 -%394 = OpBitwiseAnd %8 %69 %7 -%395 = OpBitwiseAnd %11 %183 %184 -%396 = OpCompositeConstruct %196 %69 %69 -%397 = OpCompositeConstruct %196 %7 %7 -%398 = OpBitwiseAnd %196 %396 %397 -%399 = OpCompositeConstruct %207 %183 %183 %183 -%400 = OpCompositeConstruct %207 %184 %184 %184 -%401 = OpBitwiseAnd %207 %399 %400 -%402 = OpBitwiseXor %8 %69 %7 -%403 = OpBitwiseXor %11 %183 %184 -%404 = OpCompositeConstruct %196 %69 %69 -%405 = OpCompositeConstruct %196 %7 %7 -%406 = OpBitwiseXor %196 %404 %405 -%407 = OpCompositeConstruct %207 %183 %183 %183 -%408 = OpCompositeConstruct %207 %184 %184 %184 -%409 = OpBitwiseXor %207 %407 %408 -%410 = OpShiftLeftLogical %8 %69 %184 -%411 = OpShiftLeftLogical %11 %183 %184 -%412 = OpCompositeConstruct %196 %69 %69 -%413 = OpCompositeConstruct %22 %184 %184 -%414 = OpShiftLeftLogical %196 %412 %413 -%415 = OpCompositeConstruct %207 %183 %183 %183 -%416 = OpCompositeConstruct %207 %184 %184 %184 -%417 = OpShiftLeftLogical %207 %415 %416 -%418 = OpShiftRightArithmetic %8 %69 %184 -%419 = OpShiftRightLogical %11 %183 %184 -%420 = OpCompositeConstruct %196 %69 %69 -%421 = OpCompositeConstruct %22 %184 %184 -%422 = OpShiftRightArithmetic %196 %420 %421 -%423 = OpCompositeConstruct %207 %183 %183 %183 -%424 = OpCompositeConstruct %207 %184 %184 %184 -%425 = OpShiftRightLogical %207 %423 %424 +%379 = OpFunction %2 None %165 +%378 = OpLabel +OpBranch %380 +%380 = OpLabel +%381 = OpNot %8 %7 +%382 = OpNot %20 %185 +%383 = OpCompositeConstruct %197 %7 %7 +%384 = OpNot %197 %383 +%385 = OpCompositeConstruct %208 %185 %185 %185 +%386 = OpNot %208 %385 +%387 = OpBitwiseOr %8 %70 %7 +%388 = OpBitwiseOr %20 %184 %185 +%389 = OpCompositeConstruct %197 %70 %70 +%390 = OpCompositeConstruct %197 %7 %7 +%391 = OpBitwiseOr %197 %389 %390 +%392 = OpCompositeConstruct %208 %184 %184 %184 +%393 = OpCompositeConstruct %208 %185 %185 %185 +%394 = OpBitwiseOr %208 %392 %393 +%395 = OpBitwiseAnd %8 %70 %7 +%396 = OpBitwiseAnd %20 %184 %185 +%397 = OpCompositeConstruct %197 %70 %70 +%398 = OpCompositeConstruct %197 %7 %7 +%399 = OpBitwiseAnd %197 %397 %398 +%400 = OpCompositeConstruct %208 %184 %184 %184 +%401 = OpCompositeConstruct %208 %185 %185 %185 +%402 = OpBitwiseAnd %208 %400 %401 +%403 = OpBitwiseXor %8 %70 %7 +%404 = OpBitwiseXor %20 %184 %185 +%405 = OpCompositeConstruct %197 %70 %70 +%406 = OpCompositeConstruct %197 %7 %7 +%407 = OpBitwiseXor %197 %405 %406 +%408 = OpCompositeConstruct %208 %184 %184 %184 +%409 = OpCompositeConstruct %208 %185 %185 %185 +%410 = OpBitwiseXor %208 %408 %409 +%411 = OpShiftLeftLogical %8 %70 %185 +%412 = OpShiftLeftLogical %20 %184 %185 +%413 = OpCompositeConstruct %197 %70 %70 +%414 = OpCompositeConstruct %21 %185 %185 +%415 = OpShiftLeftLogical %197 %413 %414 +%416 = OpCompositeConstruct %208 %184 %184 %184 +%417 = OpCompositeConstruct %208 %185 %185 %185 +%418 = OpShiftLeftLogical %208 %416 %417 +%419 = OpShiftRightArithmetic %8 %70 %185 +%420 = OpShiftRightLogical %20 %184 %185 +%421 = OpCompositeConstruct %197 %70 %70 +%422 = OpCompositeConstruct %21 %185 %185 +%423 = OpShiftRightArithmetic %197 %421 %422 +%424 = OpCompositeConstruct %208 %184 %184 %184 +%425 = OpCompositeConstruct %208 %185 %185 %185 +%426 = OpShiftRightLogical %208 %424 %425 OpReturn OpFunctionEnd -%427 = OpFunction %2 None %164 -%426 = OpLabel -OpBranch %428 -%428 = OpLabel -%429 = OpIEqual %15 %69 %7 -%430 = OpIEqual %15 %183 %184 -%431 = OpFOrdEqual %15 %65 %3 -%432 = OpCompositeConstruct %196 %69 %69 -%433 = OpCompositeConstruct %196 %7 %7 -%434 = OpIEqual %167 %432 %433 -%435 = OpCompositeConstruct %207 %183 %183 %183 -%436 = OpCompositeConstruct %207 %184 %184 %184 -%437 = OpIEqual %18 %435 %436 -%438 = OpCompositeConstruct %12 %65 %65 %65 %65 -%439 = OpCompositeConstruct %12 %3 %3 %3 %3 -%440 = OpFOrdEqual %14 %438 %439 -%441 = OpINotEqual %15 %69 %7 -%442 = OpINotEqual %15 %183 %184 -%443 = OpFOrdNotEqual %15 %65 %3 -%444 = OpCompositeConstruct %196 %69 %69 -%445 = OpCompositeConstruct %196 %7 %7 -%446 = OpINotEqual %167 %444 %445 -%447 = OpCompositeConstruct %207 %183 %183 %183 -%448 = OpCompositeConstruct %207 %184 %184 %184 -%449 = OpINotEqual %18 %447 %448 -%450 = OpCompositeConstruct %12 %65 %65 %65 %65 -%451 = OpCompositeConstruct %12 %3 %3 %3 %3 -%452 = OpFOrdNotEqual %14 %450 %451 -%453 = OpSLessThan %15 %69 %7 -%454 = OpULessThan %15 %183 %184 -%455 = OpFOrdLessThan %15 %65 %3 -%456 = OpCompositeConstruct %196 %69 %69 -%457 = OpCompositeConstruct %196 %7 %7 -%458 = OpSLessThan %167 %456 %457 -%459 = OpCompositeConstruct %207 %183 %183 %183 -%460 = OpCompositeConstruct %207 %184 %184 %184 -%461 = OpULessThan %18 %459 %460 -%462 = OpCompositeConstruct %12 %65 %65 %65 %65 -%463 = OpCompositeConstruct %12 %3 %3 %3 %3 -%464 = OpFOrdLessThan %14 %462 %463 -%465 = OpSLessThanEqual %15 %69 %7 -%466 = OpULessThanEqual %15 %183 %184 -%467 = OpFOrdLessThanEqual %15 %65 %3 -%468 = OpCompositeConstruct %196 %69 %69 -%469 = OpCompositeConstruct %196 %7 %7 -%470 = OpSLessThanEqual %167 %468 %469 -%471 = OpCompositeConstruct %207 %183 %183 %183 -%472 = OpCompositeConstruct %207 %184 %184 %184 -%473 = OpULessThanEqual %18 %471 %472 -%474 = OpCompositeConstruct %12 %65 %65 %65 %65 -%475 = OpCompositeConstruct %12 %3 %3 %3 %3 -%476 = OpFOrdLessThanEqual %14 %474 %475 -%477 = OpSGreaterThan %15 %69 %7 -%478 = OpUGreaterThan %15 %183 %184 -%479 = OpFOrdGreaterThan %15 %65 %3 -%480 = OpCompositeConstruct %196 %69 %69 -%481 = OpCompositeConstruct %196 %7 %7 -%482 = OpSGreaterThan %167 %480 %481 -%483 = OpCompositeConstruct %207 %183 %183 %183 -%484 = OpCompositeConstruct %207 %184 %184 %184 -%485 = OpUGreaterThan %18 %483 %484 -%486 = OpCompositeConstruct %12 %65 %65 %65 %65 -%487 = OpCompositeConstruct %12 %3 %3 %3 %3 -%488 = OpFOrdGreaterThan %14 %486 %487 -%489 = OpSGreaterThanEqual %15 %69 %7 -%490 = OpUGreaterThanEqual %15 %183 %184 -%491 = OpFOrdGreaterThanEqual %15 %65 %3 -%492 = OpCompositeConstruct %196 %69 %69 -%493 = OpCompositeConstruct %196 %7 %7 -%494 = OpSGreaterThanEqual %167 %492 %493 -%495 = OpCompositeConstruct %207 %183 %183 %183 -%496 = OpCompositeConstruct %207 %184 %184 %184 -%497 = OpUGreaterThanEqual %18 %495 %496 -%498 = OpCompositeConstruct %12 %65 %65 %65 %65 -%499 = OpCompositeConstruct %12 %3 %3 %3 %3 -%500 = OpFOrdGreaterThanEqual %14 %498 %499 +%428 = OpFunction %2 None %165 +%427 = OpLabel +OpBranch %429 +%429 = OpLabel +%430 = OpIEqual %13 %70 %7 +%431 = OpIEqual %13 %184 %185 +%432 = OpFOrdEqual %13 %66 %3 +%433 = OpCompositeConstruct %197 %70 %70 +%434 = OpCompositeConstruct %197 %7 %7 +%435 = OpIEqual %168 %433 %434 +%436 = OpCompositeConstruct %208 %184 %184 %184 +%437 = OpCompositeConstruct %208 %185 %185 %185 +%438 = OpIEqual %16 %436 %437 +%439 = OpCompositeConstruct %10 %66 %66 %66 %66 +%440 = OpCompositeConstruct %10 %3 %3 %3 %3 +%441 = OpFOrdEqual %12 %439 %440 +%442 = OpINotEqual %13 %70 %7 +%443 = OpINotEqual %13 %184 %185 +%444 = OpFOrdNotEqual %13 %66 %3 +%445 = OpCompositeConstruct %197 %70 %70 +%446 = OpCompositeConstruct %197 %7 %7 +%447 = OpINotEqual %168 %445 %446 +%448 = OpCompositeConstruct %208 %184 %184 %184 +%449 = OpCompositeConstruct %208 %185 %185 %185 +%450 = OpINotEqual %16 %448 %449 +%451 = OpCompositeConstruct %10 %66 %66 %66 %66 +%452 = OpCompositeConstruct %10 %3 %3 %3 %3 +%453 = OpFOrdNotEqual %12 %451 %452 +%454 = OpSLessThan %13 %70 %7 +%455 = OpULessThan %13 %184 %185 +%456 = OpFOrdLessThan %13 %66 %3 +%457 = OpCompositeConstruct %197 %70 %70 +%458 = OpCompositeConstruct %197 %7 %7 +%459 = OpSLessThan %168 %457 %458 +%460 = OpCompositeConstruct %208 %184 %184 %184 +%461 = OpCompositeConstruct %208 %185 %185 %185 +%462 = OpULessThan %16 %460 %461 +%463 = OpCompositeConstruct %10 %66 %66 %66 %66 +%464 = OpCompositeConstruct %10 %3 %3 %3 %3 +%465 = OpFOrdLessThan %12 %463 %464 +%466 = OpSLessThanEqual %13 %70 %7 +%467 = OpULessThanEqual %13 %184 %185 +%468 = OpFOrdLessThanEqual %13 %66 %3 +%469 = OpCompositeConstruct %197 %70 %70 +%470 = OpCompositeConstruct %197 %7 %7 +%471 = OpSLessThanEqual %168 %469 %470 +%472 = OpCompositeConstruct %208 %184 %184 %184 +%473 = OpCompositeConstruct %208 %185 %185 %185 +%474 = OpULessThanEqual %16 %472 %473 +%475 = OpCompositeConstruct %10 %66 %66 %66 %66 +%476 = OpCompositeConstruct %10 %3 %3 %3 %3 +%477 = OpFOrdLessThanEqual %12 %475 %476 +%478 = OpSGreaterThan %13 %70 %7 +%479 = OpUGreaterThan %13 %184 %185 +%480 = OpFOrdGreaterThan %13 %66 %3 +%481 = OpCompositeConstruct %197 %70 %70 +%482 = OpCompositeConstruct %197 %7 %7 +%483 = OpSGreaterThan %168 %481 %482 +%484 = OpCompositeConstruct %208 %184 %184 %184 +%485 = OpCompositeConstruct %208 %185 %185 %185 +%486 = OpUGreaterThan %16 %484 %485 +%487 = OpCompositeConstruct %10 %66 %66 %66 %66 +%488 = OpCompositeConstruct %10 %3 %3 %3 %3 +%489 = OpFOrdGreaterThan %12 %487 %488 +%490 = OpSGreaterThanEqual %13 %70 %7 +%491 = OpUGreaterThanEqual %13 %184 %185 +%492 = OpFOrdGreaterThanEqual %13 %66 %3 +%493 = OpCompositeConstruct %197 %70 %70 +%494 = OpCompositeConstruct %197 %7 %7 +%495 = OpSGreaterThanEqual %168 %493 %494 +%496 = OpCompositeConstruct %208 %184 %184 %184 +%497 = OpCompositeConstruct %208 %185 %185 %185 +%498 = OpUGreaterThanEqual %16 %496 %497 +%499 = OpCompositeConstruct %10 %66 %66 %66 %66 +%500 = OpCompositeConstruct %10 %3 %3 %3 %3 +%501 = OpFOrdGreaterThanEqual %12 %499 %500 OpReturn OpFunctionEnd -%508 = OpFunction %2 None %164 -%507 = OpLabel -%501 = OpVariable %502 Function %503 -%504 = OpVariable %505 Function %506 -OpBranch %510 -%510 = OpLabel -OpStore %501 %7 -%511 = OpLoad %8 %501 -%512 = OpIAdd %8 %511 %7 -OpStore %501 %512 -%513 = OpLoad %8 %501 -%514 = OpISub %8 %513 %7 -OpStore %501 %514 -%515 = OpLoad %8 %501 -%516 = OpLoad %8 %501 -%517 = OpIMul %8 %516 %515 -OpStore %501 %517 -%518 = OpLoad %8 %501 -%519 = OpLoad %8 %501 -%520 = OpSDiv %8 %519 %518 -OpStore %501 %520 -%521 = OpLoad %8 %501 -%522 = OpSRem %8 %521 %7 -OpStore %501 %522 -%523 = OpLoad %8 %501 -%524 = OpBitwiseAnd %8 %523 %38 -OpStore %501 %524 -%525 = OpLoad %8 %501 -%526 = OpBitwiseOr %8 %525 %38 -OpStore %501 %526 -%527 = OpLoad %8 %501 -%528 = OpBitwiseXor %8 %527 %38 -OpStore %501 %528 -%529 = OpLoad %8 %501 -%530 = OpShiftLeftLogical %8 %529 %183 -OpStore %501 %530 -%531 = OpLoad %8 %501 -%532 = OpShiftRightArithmetic %8 %531 %184 -OpStore %501 %532 -%533 = OpLoad %8 %501 -%534 = OpIAdd %8 %533 %7 -OpStore %501 %534 -%535 = OpLoad %8 %501 -%536 = OpISub %8 %535 %7 -OpStore %501 %536 -OpStore %504 %509 -%538 = OpAccessChain %537 %504 %184 -%539 = OpLoad %8 %538 -%540 = OpIAdd %8 %539 %7 -%541 = OpAccessChain %537 %504 %184 -OpStore %541 %540 -%542 = OpAccessChain %537 %504 %184 -%543 = OpLoad %8 %542 -%544 = OpISub %8 %543 %7 -%545 = OpAccessChain %537 %504 %184 -OpStore %545 %544 +%509 = OpFunction %2 None %165 +%508 = OpLabel +%502 = OpVariable %503 Function %504 +%505 = OpVariable %506 Function %507 +OpBranch %511 +%511 = OpLabel +OpStore %502 %7 +%512 = OpLoad %8 %502 +%513 = OpIAdd %8 %512 %7 +OpStore %502 %513 +%514 = OpLoad %8 %502 +%515 = OpISub %8 %514 %7 +OpStore %502 %515 +%516 = OpLoad %8 %502 +%517 = OpLoad %8 %502 +%518 = OpIMul %8 %517 %516 +OpStore %502 %518 +%519 = OpLoad %8 %502 +%520 = OpLoad %8 %502 +%521 = OpSDiv %8 %520 %519 +OpStore %502 %521 +%522 = OpLoad %8 %502 +%523 = OpSRem %8 %522 %7 +OpStore %502 %523 +%524 = OpLoad %8 %502 +%525 = OpBitwiseAnd %8 %524 %39 +OpStore %502 %525 +%526 = OpLoad %8 %502 +%527 = OpBitwiseOr %8 %526 %39 +OpStore %502 %527 +%528 = OpLoad %8 %502 +%529 = OpBitwiseXor %8 %528 %39 +OpStore %502 %529 +%530 = OpLoad %8 %502 +%531 = OpShiftLeftLogical %8 %530 %184 +OpStore %502 %531 +%532 = OpLoad %8 %502 +%533 = OpShiftRightArithmetic %8 %532 %185 +OpStore %502 %533 +%534 = OpLoad %8 %502 +%535 = OpIAdd %8 %534 %7 +OpStore %502 %535 +%536 = OpLoad %8 %502 +%537 = OpISub %8 %536 %7 +OpStore %502 %537 +OpStore %505 %510 +%539 = OpAccessChain %538 %505 %185 +%540 = OpLoad %8 %539 +%541 = OpIAdd %8 %540 %7 +%542 = OpAccessChain %538 %505 %185 +OpStore %542 %541 +%543 = OpAccessChain %538 %505 %185 +%544 = OpLoad %8 %543 +%545 = OpISub %8 %544 %7 +%546 = OpAccessChain %538 %505 %185 +OpStore %546 %545 OpReturn OpFunctionEnd -%547 = OpFunction %2 None %164 -%546 = OpLabel -OpBranch %556 -%556 = OpLabel -%557 = OpSNegate %8 %549 +%548 = OpFunction %2 None %165 +%547 = OpLabel +OpBranch %557 +%557 = OpLabel %558 = OpSNegate %8 %550 %559 = OpSNegate %8 %551 -%560 = OpSNegate %8 %559 -%561 = OpSNegate %8 %552 -%562 = OpSNegate %8 %561 -%563 = OpSNegate %8 %553 -%564 = OpSNegate %8 %563 +%560 = OpSNegate %8 %552 +%561 = OpSNegate %8 %560 +%562 = OpSNegate %8 %553 +%563 = OpSNegate %8 %562 +%564 = OpSNegate %8 %554 %565 = OpSNegate %8 %564 %566 = OpSNegate %8 %565 -%567 = OpSNegate %8 %554 -%568 = OpSNegate %8 %567 +%567 = OpSNegate %8 %566 +%568 = OpSNegate %8 %555 %569 = OpSNegate %8 %568 %570 = OpSNegate %8 %569 -%571 = OpSNegate %8 %555 -%572 = OpSNegate %8 %571 +%571 = OpSNegate %8 %570 +%572 = OpSNegate %8 %556 %573 = OpSNegate %8 %572 %574 = OpSNegate %8 %573 +%575 = OpSNegate %8 %574 OpReturn OpFunctionEnd -%576 = OpFunction %2 None %164 -%575 = OpLabel -OpBranch %577 -%577 = OpLabel -%578 = OpFunctionCall %12 %35 -%579 = OpFunctionCall %12 %64 -%580 = OpVectorShuffle %17 %30 %30 0 1 2 -%581 = OpFunctionCall %17 %104 %580 -%582 = OpFunctionCall %4 %115 -%583 = OpFunctionCall %2 %163 -%584 = OpFunctionCall %2 %181 -%585 = OpFunctionCall %2 %378 -%586 = OpFunctionCall %2 %427 -%587 = OpFunctionCall %2 %508 +%577 = OpFunction %2 None %165 +%576 = OpLabel +OpBranch %578 +%578 = OpLabel +%579 = OpFunctionCall %10 %36 +%580 = OpFunctionCall %10 %65 +%581 = OpVectorShuffle %15 %31 %31 0 1 2 +%582 = OpFunctionCall %15 %105 %581 +%583 = OpFunctionCall %4 %116 +%584 = OpFunctionCall %2 %164 +%585 = OpFunctionCall %2 %182 +%586 = OpFunctionCall %2 %379 +%587 = OpFunctionCall %2 %428 +%588 = OpFunctionCall %2 %509 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/padding.spvasm b/tests/out/spv/padding.spvasm index 713979b35..485ac9367 100644 --- a/tests/out/spv/padding.spvasm +++ b/tests/out/spv/padding.spvasm @@ -1,50 +1,50 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 50 +; Bound: 51 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %26 "vertex" %24 +OpEntryPoint Vertex %28 "vertex" %26 OpSource GLSL 450 OpMemberName %7 0 "a" OpName %7 "S" OpMemberName %8 0 "a" OpMemberName %8 1 "b" OpName %8 "Test" -OpMemberName %10 0 "a" -OpMemberName %10 1 "b" -OpName %10 "Test2" OpMemberName %12 0 "a" OpMemberName %12 1 "b" -OpName %12 "Test3" -OpName %14 "input1" -OpName %17 "input2" -OpName %20 "input3" -OpName %26 "vertex" +OpName %12 "Test2" +OpMemberName %14 0 "a" +OpMemberName %14 1 "b" +OpName %14 "Test3" +OpName %16 "input1" +OpName %19 "input2" +OpName %22 "input3" +OpName %28 "vertex" OpMemberDecorate %7 0 Offset 0 OpMemberDecorate %8 0 Offset 0 OpMemberDecorate %8 1 Offset 16 OpDecorate %9 ArrayStride 16 -OpMemberDecorate %10 0 Offset 0 -OpMemberDecorate %10 1 Offset 32 OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 0 ColMajor -OpMemberDecorate %12 0 MatrixStride 16 -OpMemberDecorate %12 1 Offset 64 -OpDecorate %14 DescriptorSet 0 -OpDecorate %14 Binding 0 -OpDecorate %15 Block -OpMemberDecorate %15 0 Offset 0 -OpDecorate %17 DescriptorSet 0 -OpDecorate %17 Binding 1 -OpDecorate %18 Block -OpMemberDecorate %18 0 Offset 0 -OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 2 -OpDecorate %21 Block -OpMemberDecorate %21 0 Offset 0 -OpDecorate %24 BuiltIn Position +OpMemberDecorate %12 1 Offset 32 +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 0 ColMajor +OpMemberDecorate %14 0 MatrixStride 16 +OpMemberDecorate %14 1 Offset 64 +OpDecorate %16 DescriptorSet 0 +OpDecorate %16 Binding 0 +OpDecorate %17 Block +OpMemberDecorate %17 0 Offset 0 +OpDecorate %19 DescriptorSet 0 +OpDecorate %19 Binding 1 +OpDecorate %20 Block +OpMemberDecorate %20 0 Offset 0 +OpDecorate %22 DescriptorSet 0 +OpDecorate %22 Binding 2 +OpDecorate %23 Block +OpMemberDecorate %23 0 Offset 0 +OpDecorate %26 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 2 @@ -52,48 +52,49 @@ OpDecorate %24 BuiltIn Position %5 = OpTypeVector %6 3 %7 = OpTypeStruct %5 %8 = OpTypeStruct %7 %6 -%9 = OpTypeArray %5 %3 -%10 = OpTypeStruct %9 %6 -%11 = OpTypeMatrix %5 4 -%12 = OpTypeStruct %11 %6 -%13 = OpTypeVector %6 4 -%15 = OpTypeStruct %8 -%16 = OpTypePointer Uniform %15 -%14 = OpVariable %16 Uniform -%18 = OpTypeStruct %10 -%19 = OpTypePointer Uniform %18 -%17 = OpVariable %19 Uniform -%21 = OpTypeStruct %12 -%22 = OpTypePointer Uniform %21 -%20 = OpVariable %22 Uniform -%25 = OpTypePointer Output %13 -%24 = OpVariable %25 Output -%27 = OpTypeFunction %2 -%28 = OpTypePointer Uniform %8 -%30 = OpTypeInt 32 0 -%29 = OpConstant %30 0 -%32 = OpTypePointer Uniform %10 -%34 = OpTypePointer Uniform %12 -%36 = OpConstant %6 1.0 -%39 = OpTypePointer Uniform %6 -%40 = OpConstant %30 1 -%26 = OpFunction %2 None %27 -%23 = OpLabel -%31 = OpAccessChain %28 %14 %29 -%33 = OpAccessChain %32 %17 %29 -%35 = OpAccessChain %34 %20 %29 -OpBranch %37 -%37 = OpLabel -%38 = OpCompositeConstruct %13 %36 %36 %36 %36 -%41 = OpAccessChain %39 %31 %40 -%42 = OpLoad %6 %41 -%43 = OpVectorTimesScalar %13 %38 %42 -%44 = OpAccessChain %39 %33 %40 -%45 = OpLoad %6 %44 -%46 = OpVectorTimesScalar %13 %43 %45 -%47 = OpAccessChain %39 %35 %40 -%48 = OpLoad %6 %47 -%49 = OpVectorTimesScalar %13 %46 %48 -OpStore %24 %49 +%11 = OpTypeInt 32 0 +%10 = OpConstant %11 2 +%9 = OpTypeArray %5 %10 +%12 = OpTypeStruct %9 %6 +%13 = OpTypeMatrix %5 4 +%14 = OpTypeStruct %13 %6 +%15 = OpTypeVector %6 4 +%17 = OpTypeStruct %8 +%18 = OpTypePointer Uniform %17 +%16 = OpVariable %18 Uniform +%20 = OpTypeStruct %12 +%21 = OpTypePointer Uniform %20 +%19 = OpVariable %21 Uniform +%23 = OpTypeStruct %14 +%24 = OpTypePointer Uniform %23 +%22 = OpVariable %24 Uniform +%27 = OpTypePointer Output %15 +%26 = OpVariable %27 Output +%29 = OpTypeFunction %2 +%30 = OpTypePointer Uniform %8 +%31 = OpConstant %11 0 +%33 = OpTypePointer Uniform %12 +%35 = OpTypePointer Uniform %14 +%37 = OpConstant %6 1.0 +%40 = OpTypePointer Uniform %6 +%41 = OpConstant %11 1 +%28 = OpFunction %2 None %29 +%25 = OpLabel +%32 = OpAccessChain %30 %16 %31 +%34 = OpAccessChain %33 %19 %31 +%36 = OpAccessChain %35 %22 %31 +OpBranch %38 +%38 = OpLabel +%39 = OpCompositeConstruct %15 %37 %37 %37 %37 +%42 = OpAccessChain %40 %32 %41 +%43 = OpLoad %6 %42 +%44 = OpVectorTimesScalar %15 %39 %43 +%45 = OpAccessChain %40 %34 %41 +%46 = OpLoad %6 %45 +%47 = OpVectorTimesScalar %15 %44 %46 +%48 = OpAccessChain %40 %36 %41 +%49 = OpLoad %6 %48 +%50 = OpVectorTimesScalar %15 %47 %49 +OpStore %26 %50 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index 3ba407ded..d11747605 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 101 +; Bound: 106 OpCapability Shader OpCapability ImageQuery OpCapability Linkage @@ -9,38 +9,38 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpSource GLSL 450 -OpMemberName %12 0 "a" -OpName %12 "InStorage" OpMemberName %14 0 "a" -OpName %14 "InUniform" -OpName %20 "in_storage" -OpName %23 "in_uniform" -OpName %26 "image_2d_array" -OpName %28 "in_workgroup" -OpName %30 "in_private" -OpName %33 "in_function" -OpName %37 "c" -OpName %38 "i" -OpName %39 "l" -OpName %40 "mock_function" +OpName %14 "InStorage" +OpMemberName %17 0 "a" +OpName %17 "InUniform" +OpName %26 "in_storage" +OpName %29 "in_uniform" +OpName %32 "image_2d_array" +OpName %34 "in_workgroup" +OpName %36 "in_private" +OpName %39 "in_function" +OpName %43 "c" +OpName %44 "i" +OpName %45 "l" +OpName %46 "mock_function" OpDecorate %11 ArrayStride 16 -OpMemberDecorate %12 0 Offset 0 -OpDecorate %13 ArrayStride 16 OpMemberDecorate %14 0 Offset 0 -OpDecorate %16 ArrayStride 4 -OpDecorate %17 ArrayStride 4 -OpDecorate %19 ArrayStride 16 -OpDecorate %20 NonWritable -OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 0 -OpDecorate %21 Block -OpMemberDecorate %21 0 Offset 0 -OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 1 -OpDecorate %24 Block -OpMemberDecorate %24 0 Offset 0 +OpDecorate %15 ArrayStride 16 +OpMemberDecorate %17 0 Offset 0 +OpDecorate %19 ArrayStride 4 +OpDecorate %21 ArrayStride 4 +OpDecorate %24 ArrayStride 16 +OpDecorate %26 NonWritable OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 2 +OpDecorate %26 Binding 0 +OpDecorate %27 Block +OpMemberDecorate %27 0 Offset 0 +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 1 +OpDecorate %30 Block +OpMemberDecorate %30 0 Offset 0 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 2 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -50,101 +50,106 @@ OpDecorate %26 Binding 2 %8 = OpConstant %4 2 %10 = OpTypeFloat 32 %9 = OpTypeVector %10 4 -%11 = OpTypeArray %9 %3 -%12 = OpTypeStruct %11 -%13 = OpTypeArray %9 %5 -%14 = OpTypeStruct %13 -%15 = OpTypeImage %10 2D 0 1 0 1 Unknown -%16 = OpTypeArray %10 %6 -%17 = OpTypeArray %10 %7 -%18 = OpTypeVector %4 2 -%19 = OpTypeArray %9 %8 -%21 = OpTypeStruct %12 -%22 = OpTypePointer StorageBuffer %21 -%20 = OpVariable %22 StorageBuffer -%24 = OpTypeStruct %14 -%25 = OpTypePointer Uniform %24 -%23 = OpVariable %25 Uniform -%27 = OpTypePointer UniformConstant %15 -%26 = OpVariable %27 UniformConstant -%29 = OpTypePointer Workgroup %16 -%28 = OpVariable %29 Workgroup -%31 = OpTypePointer Private %17 -%32 = OpConstantNull %17 -%30 = OpVariable %31 Private %32 -%34 = OpTypePointer Function %19 -%35 = OpConstantNull %19 -%41 = OpTypeFunction %9 %18 %4 %4 -%42 = OpTypePointer StorageBuffer %12 -%44 = OpTypeInt 32 0 -%43 = OpConstant %44 0 -%46 = OpTypePointer Uniform %14 -%49 = OpConstant %10 0.707 -%50 = OpConstant %10 0.0 -%51 = OpConstant %10 1.0 -%56 = OpTypePointer StorageBuffer %11 -%57 = OpTypePointer StorageBuffer %9 -%60 = OpTypePointer Uniform %13 -%61 = OpTypePointer Uniform %9 -%65 = OpTypeVector %4 3 -%67 = OpTypeBool -%68 = OpConstantNull %9 -%74 = OpTypeVector %67 3 -%81 = OpTypePointer Workgroup %10 -%82 = OpConstant %44 29 -%88 = OpTypePointer Private %10 -%89 = OpConstant %44 39 -%95 = OpTypePointer Function %9 -%96 = OpConstant %44 1 -%40 = OpFunction %9 None %41 -%37 = OpFunctionParameter %18 -%38 = OpFunctionParameter %4 -%39 = OpFunctionParameter %4 -%36 = OpLabel -%33 = OpVariable %34 Function %35 -%45 = OpAccessChain %42 %20 %43 -%47 = OpAccessChain %46 %23 %43 -%48 = OpLoad %15 %26 -OpBranch %52 -%52 = OpLabel -%53 = OpCompositeConstruct %9 %49 %50 %50 %51 -%54 = OpCompositeConstruct %9 %50 %49 %50 %51 -%55 = OpCompositeConstruct %19 %53 %54 -OpStore %33 %55 -%58 = OpAccessChain %57 %45 %43 %38 -%59 = OpLoad %9 %58 -%62 = OpAccessChain %61 %47 %43 %38 -%63 = OpLoad %9 %62 -%64 = OpFAdd %9 %59 %63 -%66 = OpCompositeConstruct %65 %37 %38 -%69 = OpImageQueryLevels %4 %48 -%70 = OpULessThan %67 %39 %69 -OpSelectionMerge %71 None -OpBranchConditional %70 %72 %71 -%72 = OpLabel -%73 = OpImageQuerySizeLod %65 %48 %39 -%75 = OpULessThan %74 %66 %73 -%76 = OpAll %67 %75 -OpBranchConditional %76 %77 %71 +%13 = OpTypeInt 32 0 +%12 = OpConstant %13 10 +%11 = OpTypeArray %9 %12 +%14 = OpTypeStruct %11 +%16 = OpConstant %13 20 +%15 = OpTypeArray %9 %16 +%17 = OpTypeStruct %15 +%18 = OpTypeImage %10 2D 0 1 0 1 Unknown +%20 = OpConstant %13 30 +%19 = OpTypeArray %10 %20 +%22 = OpConstant %13 40 +%21 = OpTypeArray %10 %22 +%23 = OpTypeVector %4 2 +%25 = OpConstant %13 2 +%24 = OpTypeArray %9 %25 +%27 = OpTypeStruct %14 +%28 = OpTypePointer StorageBuffer %27 +%26 = OpVariable %28 StorageBuffer +%30 = OpTypeStruct %17 +%31 = OpTypePointer Uniform %30 +%29 = OpVariable %31 Uniform +%33 = OpTypePointer UniformConstant %18 +%32 = OpVariable %33 UniformConstant +%35 = OpTypePointer Workgroup %19 +%34 = OpVariable %35 Workgroup +%37 = OpTypePointer Private %21 +%38 = OpConstantNull %21 +%36 = OpVariable %37 Private %38 +%40 = OpTypePointer Function %24 +%41 = OpConstantNull %24 +%47 = OpTypeFunction %9 %23 %4 %4 +%48 = OpTypePointer StorageBuffer %14 +%49 = OpConstant %13 0 +%51 = OpTypePointer Uniform %17 +%54 = OpConstant %10 0.707 +%55 = OpConstant %10 0.0 +%56 = OpConstant %10 1.0 +%61 = OpTypePointer StorageBuffer %11 +%62 = OpTypePointer StorageBuffer %9 +%65 = OpTypePointer Uniform %15 +%66 = OpTypePointer Uniform %9 +%70 = OpTypeVector %4 3 +%72 = OpTypeBool +%73 = OpConstantNull %9 +%79 = OpTypeVector %72 3 +%86 = OpTypePointer Workgroup %10 +%87 = OpConstant %13 29 +%93 = OpTypePointer Private %10 +%94 = OpConstant %13 39 +%100 = OpTypePointer Function %9 +%101 = OpConstant %13 1 +%46 = OpFunction %9 None %47 +%43 = OpFunctionParameter %23 +%44 = OpFunctionParameter %4 +%45 = OpFunctionParameter %4 +%42 = OpLabel +%39 = OpVariable %40 Function %41 +%50 = OpAccessChain %48 %26 %49 +%52 = OpAccessChain %51 %29 %49 +%53 = OpLoad %18 %32 +OpBranch %57 +%57 = OpLabel +%58 = OpCompositeConstruct %9 %54 %55 %55 %56 +%59 = OpCompositeConstruct %9 %55 %54 %55 %56 +%60 = OpCompositeConstruct %24 %58 %59 +OpStore %39 %60 +%63 = OpAccessChain %62 %50 %49 %44 +%64 = OpLoad %9 %63 +%67 = OpAccessChain %66 %52 %49 %44 +%68 = OpLoad %9 %67 +%69 = OpFAdd %9 %64 %68 +%71 = OpCompositeConstruct %70 %43 %44 +%74 = OpImageQueryLevels %4 %53 +%75 = OpULessThan %72 %45 %74 +OpSelectionMerge %76 None +OpBranchConditional %75 %77 %76 %77 = OpLabel -%78 = OpImageFetch %9 %48 %66 Lod %39 -OpBranch %71 -%71 = OpLabel -%79 = OpPhi %9 %68 %52 %68 %72 %78 %77 -%80 = OpFAdd %9 %64 %79 -%83 = OpExtInst %44 %1 UMin %38 %82 -%84 = OpAccessChain %81 %28 %83 -%85 = OpLoad %10 %84 -%86 = OpCompositeConstruct %9 %85 %85 %85 %85 -%87 = OpFAdd %9 %80 %86 -%90 = OpExtInst %44 %1 UMin %38 %89 -%91 = OpAccessChain %88 %30 %90 -%92 = OpLoad %10 %91 -%93 = OpCompositeConstruct %9 %92 %92 %92 %92 -%94 = OpFAdd %9 %87 %93 -%97 = OpExtInst %44 %1 UMin %38 %96 -%98 = OpAccessChain %95 %33 %97 -%99 = OpLoad %9 %98 -%100 = OpFAdd %9 %94 %99 -OpReturnValue %100 +%78 = OpImageQuerySizeLod %70 %53 %45 +%80 = OpULessThan %79 %71 %78 +%81 = OpAll %72 %80 +OpBranchConditional %81 %82 %76 +%82 = OpLabel +%83 = OpImageFetch %9 %53 %71 Lod %45 +OpBranch %76 +%76 = OpLabel +%84 = OpPhi %9 %73 %57 %73 %77 %83 %82 +%85 = OpFAdd %9 %69 %84 +%88 = OpExtInst %13 %1 UMin %44 %87 +%89 = OpAccessChain %86 %34 %88 +%90 = OpLoad %10 %89 +%91 = OpCompositeConstruct %9 %90 %90 %90 %90 +%92 = OpFAdd %9 %85 %91 +%95 = OpExtInst %13 %1 UMin %44 %94 +%96 = OpAccessChain %93 %36 %95 +%97 = OpLoad %10 %96 +%98 = OpCompositeConstruct %9 %97 %97 %97 %97 +%99 = OpFAdd %9 %92 %98 +%102 = OpExtInst %13 %1 UMin %44 %101 +%103 = OpAccessChain %100 %39 %102 +%104 = OpLoad %9 %103 +%105 = OpFAdd %9 %99 %104 +OpReturnValue %105 OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index a1705891c..d087a25c9 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 270 +; Bound: 271 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %89 "vs_main" %79 %82 %84 %86 %88 -OpEntryPoint Fragment %148 "fs_main" %139 %142 %145 %147 -OpEntryPoint Fragment %217 "fs_main_without_storage" %210 %212 %214 %216 -OpExecutionMode %148 OriginUpperLeft -OpExecutionMode %217 OriginUpperLeft +OpEntryPoint Vertex %90 "vs_main" %80 %83 %85 %87 %89 +OpEntryPoint Fragment %149 "fs_main" %140 %143 %146 %148 +OpEntryPoint Fragment %218 "fs_main_without_storage" %211 %213 %215 %217 +OpExecutionMode %149 OriginUpperLeft +OpExecutionMode %218 OriginUpperLeft OpSource GLSL 450 OpName %7 "c_max_lights" OpMemberName %13 0 "view_proj" @@ -27,35 +27,35 @@ OpMemberName %19 0 "proj" OpMemberName %19 1 "pos" OpMemberName %19 2 "color" OpName %19 "Light" -OpName %25 "c_ambient" -OpName %26 "u_globals" -OpName %29 "u_entity" -OpName %32 "s_lights" -OpName %35 "u_lights" -OpName %38 "t_shadow" -OpName %40 "sampler_shadow" -OpName %43 "light_id" -OpName %44 "homogeneous_coords" -OpName %45 "fetch_shadow" -OpName %75 "out" -OpName %79 "position" -OpName %82 "normal" -OpName %84 "proj_position" -OpName %86 "world_normal" -OpName %88 "world_position" -OpName %89 "vs_main" -OpName %132 "color" -OpName %134 "i" -OpName %139 "proj_position" -OpName %142 "world_normal" -OpName %145 "world_position" -OpName %148 "fs_main" -OpName %204 "color" -OpName %206 "i" -OpName %210 "proj_position" -OpName %212 "world_normal" -OpName %214 "world_position" -OpName %217 "fs_main_without_storage" +OpName %26 "c_ambient" +OpName %27 "u_globals" +OpName %30 "u_entity" +OpName %33 "s_lights" +OpName %36 "u_lights" +OpName %39 "t_shadow" +OpName %41 "sampler_shadow" +OpName %44 "light_id" +OpName %45 "homogeneous_coords" +OpName %46 "fetch_shadow" +OpName %76 "out" +OpName %80 "position" +OpName %83 "normal" +OpName %85 "proj_position" +OpName %87 "world_normal" +OpName %89 "world_position" +OpName %90 "vs_main" +OpName %133 "color" +OpName %135 "i" +OpName %140 "proj_position" +OpName %143 "world_normal" +OpName %146 "world_position" +OpName %149 "fs_main" +OpName %205 "color" +OpName %207 "i" +OpName %211 "proj_position" +OpName %213 "world_normal" +OpName %215 "world_position" +OpName %218 "fs_main_without_storage" OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %13 0 ColMajor OpMemberDecorate %13 0 MatrixStride 16 @@ -74,40 +74,40 @@ OpMemberDecorate %19 1 Offset 64 OpMemberDecorate %19 2 Offset 80 OpDecorate %20 ArrayStride 96 OpDecorate %21 ArrayStride 96 -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 0 -OpDecorate %27 Block -OpMemberDecorate %27 0 Offset 0 -OpDecorate %29 DescriptorSet 1 -OpDecorate %29 Binding 0 -OpDecorate %30 Block -OpMemberDecorate %30 0 Offset 0 -OpDecorate %32 NonWritable -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 1 -OpDecorate %33 Block -OpMemberDecorate %33 0 Offset 0 -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 1 -OpDecorate %36 Block -OpMemberDecorate %36 0 Offset 0 -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 2 -OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 3 -OpDecorate %79 Location 0 -OpDecorate %82 Location 1 -OpDecorate %84 BuiltIn Position -OpDecorate %86 Location 0 -OpDecorate %88 Location 1 -OpDecorate %139 BuiltIn FragCoord -OpDecorate %142 Location 0 -OpDecorate %145 Location 1 -OpDecorate %147 Location 0 -OpDecorate %210 BuiltIn FragCoord -OpDecorate %212 Location 0 -OpDecorate %214 Location 1 -OpDecorate %216 Location 0 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 0 +OpDecorate %28 Block +OpMemberDecorate %28 0 Offset 0 +OpDecorate %30 DescriptorSet 1 +OpDecorate %30 Binding 0 +OpDecorate %31 Block +OpMemberDecorate %31 0 Offset 0 +OpDecorate %33 NonWritable +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 1 +OpDecorate %34 Block +OpMemberDecorate %34 0 Offset 0 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 1 +OpDecorate %37 Block +OpMemberDecorate %37 0 Offset 0 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 2 +OpDecorate %41 DescriptorSet 0 +OpDecorate %41 Binding 3 +OpDecorate %80 Location 0 +OpDecorate %83 Location 1 +OpDecorate %85 BuiltIn Position +OpDecorate %87 Location 0 +OpDecorate %89 Location 1 +OpDecorate %140 BuiltIn FragCoord +OpDecorate %143 Location 0 +OpDecorate %146 Location 1 +OpDecorate %148 Location 0 +OpDecorate %211 BuiltIn FragCoord +OpDecorate %213 Location 0 +OpDecorate %215 Location 1 +OpDecorate %217 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 10 @@ -127,304 +127,305 @@ OpDecorate %216 Location 0 %18 = OpTypeMatrix %15 3 %19 = OpTypeStruct %10 %11 %11 %20 = OpTypeRuntimeArray %19 -%21 = OpTypeArray %19 %3 -%22 = OpTypeImage %6 2D 1 1 0 1 Unknown -%23 = OpTypeSampler -%24 = OpTypeVector %6 2 -%25 = OpConstantComposite %15 %5 %5 %5 -%27 = OpTypeStruct %13 -%28 = OpTypePointer Uniform %27 -%26 = OpVariable %28 Uniform -%30 = OpTypeStruct %14 -%31 = OpTypePointer Uniform %30 -%29 = OpVariable %31 Uniform -%33 = OpTypeStruct %20 -%34 = OpTypePointer StorageBuffer %33 -%32 = OpVariable %34 StorageBuffer -%36 = OpTypeStruct %21 -%37 = OpTypePointer Uniform %36 -%35 = OpVariable %37 Uniform -%39 = OpTypePointer UniformConstant %22 -%38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %23 -%40 = OpVariable %41 UniformConstant -%46 = OpTypeFunction %6 %8 %11 -%49 = OpConstant %6 0.0 -%50 = OpConstant %6 1.0 -%51 = OpConstant %6 0.5 -%52 = OpConstant %6 -0.5 -%55 = OpTypeBool -%70 = OpTypeSampledImage %22 -%76 = OpTypePointer Function %16 -%77 = OpConstantNull %16 -%80 = OpTypePointer Input %17 -%79 = OpVariable %80 Input -%82 = OpVariable %80 Input -%85 = OpTypePointer Output %11 -%84 = OpVariable %85 Output -%87 = OpTypePointer Output %15 -%86 = OpVariable %87 Output -%88 = OpVariable %85 Output -%90 = OpTypeFunction %2 -%91 = OpTypePointer Uniform %13 -%92 = OpConstant %8 0 -%94 = OpTypePointer Uniform %14 -%97 = OpTypePointer Uniform %10 -%104 = OpTypePointer Function %15 -%112 = OpTypeVector %4 3 -%117 = OpTypePointer Function %11 -%118 = OpConstant %8 2 -%126 = OpTypePointer Output %6 -%133 = OpConstantNull %15 -%135 = OpTypePointer Function %8 -%136 = OpConstantNull %8 -%140 = OpTypePointer Input %11 -%139 = OpVariable %140 Input -%143 = OpTypePointer Input %15 -%142 = OpVariable %143 Input -%145 = OpVariable %140 Input -%147 = OpVariable %85 Output -%151 = OpTypePointer StorageBuffer %20 -%163 = OpTypePointer Uniform %12 -%164 = OpTypePointer Uniform %8 -%174 = OpTypePointer StorageBuffer %19 -%200 = OpTypePointer Uniform %11 -%205 = OpConstantNull %15 -%207 = OpConstantNull %8 -%210 = OpVariable %140 Input -%212 = OpVariable %143 Input -%214 = OpVariable %140 Input -%216 = OpVariable %85 Output -%220 = OpTypePointer Uniform %21 -%241 = OpTypePointer Uniform %19 -%45 = OpFunction %6 None %46 -%43 = OpFunctionParameter %8 -%44 = OpFunctionParameter %11 -%42 = OpLabel -%47 = OpLoad %22 %38 -%48 = OpLoad %23 %40 -OpBranch %53 -%53 = OpLabel -%54 = OpCompositeExtract %6 %44 3 -%56 = OpFOrdLessThanEqual %55 %54 %49 -OpSelectionMerge %57 None -OpBranchConditional %56 %58 %57 +%22 = OpConstant %8 10 +%21 = OpTypeArray %19 %22 +%23 = OpTypeImage %6 2D 1 1 0 1 Unknown +%24 = OpTypeSampler +%25 = OpTypeVector %6 2 +%26 = OpConstantComposite %15 %5 %5 %5 +%28 = OpTypeStruct %13 +%29 = OpTypePointer Uniform %28 +%27 = OpVariable %29 Uniform +%31 = OpTypeStruct %14 +%32 = OpTypePointer Uniform %31 +%30 = OpVariable %32 Uniform +%34 = OpTypeStruct %20 +%35 = OpTypePointer StorageBuffer %34 +%33 = OpVariable %35 StorageBuffer +%37 = OpTypeStruct %21 +%38 = OpTypePointer Uniform %37 +%36 = OpVariable %38 Uniform +%40 = OpTypePointer UniformConstant %23 +%39 = OpVariable %40 UniformConstant +%42 = OpTypePointer UniformConstant %24 +%41 = OpVariable %42 UniformConstant +%47 = OpTypeFunction %6 %8 %11 +%50 = OpConstant %6 0.0 +%51 = OpConstant %6 1.0 +%52 = OpConstant %6 0.5 +%53 = OpConstant %6 -0.5 +%56 = OpTypeBool +%71 = OpTypeSampledImage %23 +%77 = OpTypePointer Function %16 +%78 = OpConstantNull %16 +%81 = OpTypePointer Input %17 +%80 = OpVariable %81 Input +%83 = OpVariable %81 Input +%86 = OpTypePointer Output %11 +%85 = OpVariable %86 Output +%88 = OpTypePointer Output %15 +%87 = OpVariable %88 Output +%89 = OpVariable %86 Output +%91 = OpTypeFunction %2 +%92 = OpTypePointer Uniform %13 +%93 = OpConstant %8 0 +%95 = OpTypePointer Uniform %14 +%98 = OpTypePointer Uniform %10 +%105 = OpTypePointer Function %15 +%113 = OpTypeVector %4 3 +%118 = OpTypePointer Function %11 +%119 = OpConstant %8 2 +%127 = OpTypePointer Output %6 +%134 = OpConstantNull %15 +%136 = OpTypePointer Function %8 +%137 = OpConstantNull %8 +%141 = OpTypePointer Input %11 +%140 = OpVariable %141 Input +%144 = OpTypePointer Input %15 +%143 = OpVariable %144 Input +%146 = OpVariable %141 Input +%148 = OpVariable %86 Output +%152 = OpTypePointer StorageBuffer %20 +%164 = OpTypePointer Uniform %12 +%165 = OpTypePointer Uniform %8 +%175 = OpTypePointer StorageBuffer %19 +%201 = OpTypePointer Uniform %11 +%206 = OpConstantNull %15 +%208 = OpConstantNull %8 +%211 = OpVariable %141 Input +%213 = OpVariable %144 Input +%215 = OpVariable %141 Input +%217 = OpVariable %86 Output +%221 = OpTypePointer Uniform %21 +%242 = OpTypePointer Uniform %19 +%46 = OpFunction %6 None %47 +%44 = OpFunctionParameter %8 +%45 = OpFunctionParameter %11 +%43 = OpLabel +%48 = OpLoad %23 %39 +%49 = OpLoad %24 %41 +OpBranch %54 +%54 = OpLabel +%55 = OpCompositeExtract %6 %45 3 +%57 = OpFOrdLessThanEqual %56 %55 %50 +OpSelectionMerge %58 None +OpBranchConditional %57 %59 %58 +%59 = OpLabel +OpReturnValue %51 %58 = OpLabel -OpReturnValue %50 -%57 = OpLabel -%59 = OpCompositeConstruct %24 %51 %52 -%60 = OpCompositeExtract %6 %44 3 -%61 = OpFDiv %6 %50 %60 -%62 = OpVectorShuffle %24 %44 %44 0 1 -%63 = OpFMul %24 %62 %59 -%64 = OpVectorTimesScalar %24 %63 %61 -%65 = OpCompositeConstruct %24 %51 %51 -%66 = OpFAdd %24 %64 %65 -%67 = OpBitcast %4 %43 -%68 = OpCompositeExtract %6 %44 2 -%69 = OpFMul %6 %68 %61 -%71 = OpConvertSToF %6 %67 -%72 = OpCompositeConstruct %15 %66 %71 -%73 = OpSampledImage %70 %47 %48 -%74 = OpImageSampleDrefExplicitLod %6 %73 %72 %69 Lod %49 -OpReturnValue %74 +%60 = OpCompositeConstruct %25 %52 %53 +%61 = OpCompositeExtract %6 %45 3 +%62 = OpFDiv %6 %51 %61 +%63 = OpVectorShuffle %25 %45 %45 0 1 +%64 = OpFMul %25 %63 %60 +%65 = OpVectorTimesScalar %25 %64 %62 +%66 = OpCompositeConstruct %25 %52 %52 +%67 = OpFAdd %25 %65 %66 +%68 = OpBitcast %4 %44 +%69 = OpCompositeExtract %6 %45 2 +%70 = OpFMul %6 %69 %62 +%72 = OpConvertSToF %6 %68 +%73 = OpCompositeConstruct %15 %67 %72 +%74 = OpSampledImage %71 %48 %49 +%75 = OpImageSampleDrefExplicitLod %6 %74 %73 %70 Lod %50 +OpReturnValue %75 OpFunctionEnd -%89 = OpFunction %2 None %90 -%78 = OpLabel -%75 = OpVariable %76 Function %77 -%81 = OpLoad %17 %79 -%83 = OpLoad %17 %82 -%93 = OpAccessChain %91 %26 %92 -%95 = OpAccessChain %94 %29 %92 -OpBranch %96 -%96 = OpLabel -%98 = OpAccessChain %97 %95 %92 -%99 = OpLoad %10 %98 -%100 = OpAccessChain %97 %95 %92 -%101 = OpLoad %10 %100 -%102 = OpConvertSToF %11 %81 -%103 = OpMatrixTimesVector %11 %101 %102 -%105 = OpCompositeExtract %11 %99 0 -%106 = OpVectorShuffle %15 %105 %105 0 1 2 -%107 = OpCompositeExtract %11 %99 1 -%108 = OpVectorShuffle %15 %107 %107 0 1 2 -%109 = OpCompositeExtract %11 %99 2 -%110 = OpVectorShuffle %15 %109 %109 0 1 2 -%111 = OpCompositeConstruct %18 %106 %108 %110 -%113 = OpVectorShuffle %112 %83 %83 0 1 2 -%114 = OpConvertSToF %15 %113 -%115 = OpMatrixTimesVector %15 %111 %114 -%116 = OpAccessChain %104 %75 %9 -OpStore %116 %115 -%119 = OpAccessChain %117 %75 %118 -OpStore %119 %103 -%120 = OpAccessChain %97 %93 %92 -%121 = OpLoad %10 %120 -%122 = OpMatrixTimesVector %11 %121 %103 -%123 = OpAccessChain %117 %75 %92 -OpStore %123 %122 -%124 = OpLoad %16 %75 -%125 = OpCompositeExtract %11 %124 0 -OpStore %84 %125 -%127 = OpAccessChain %126 %84 %9 -%128 = OpLoad %6 %127 -%129 = OpFNegate %6 %128 -OpStore %127 %129 -%130 = OpCompositeExtract %15 %124 1 -OpStore %86 %130 -%131 = OpCompositeExtract %11 %124 2 -OpStore %88 %131 +%90 = OpFunction %2 None %91 +%79 = OpLabel +%76 = OpVariable %77 Function %78 +%82 = OpLoad %17 %80 +%84 = OpLoad %17 %83 +%94 = OpAccessChain %92 %27 %93 +%96 = OpAccessChain %95 %30 %93 +OpBranch %97 +%97 = OpLabel +%99 = OpAccessChain %98 %96 %93 +%100 = OpLoad %10 %99 +%101 = OpAccessChain %98 %96 %93 +%102 = OpLoad %10 %101 +%103 = OpConvertSToF %11 %82 +%104 = OpMatrixTimesVector %11 %102 %103 +%106 = OpCompositeExtract %11 %100 0 +%107 = OpVectorShuffle %15 %106 %106 0 1 2 +%108 = OpCompositeExtract %11 %100 1 +%109 = OpVectorShuffle %15 %108 %108 0 1 2 +%110 = OpCompositeExtract %11 %100 2 +%111 = OpVectorShuffle %15 %110 %110 0 1 2 +%112 = OpCompositeConstruct %18 %107 %109 %111 +%114 = OpVectorShuffle %113 %84 %84 0 1 2 +%115 = OpConvertSToF %15 %114 +%116 = OpMatrixTimesVector %15 %112 %115 +%117 = OpAccessChain %105 %76 %9 +OpStore %117 %116 +%120 = OpAccessChain %118 %76 %119 +OpStore %120 %104 +%121 = OpAccessChain %98 %94 %93 +%122 = OpLoad %10 %121 +%123 = OpMatrixTimesVector %11 %122 %104 +%124 = OpAccessChain %118 %76 %93 +OpStore %124 %123 +%125 = OpLoad %16 %76 +%126 = OpCompositeExtract %11 %125 0 +OpStore %85 %126 +%128 = OpAccessChain %127 %85 %9 +%129 = OpLoad %6 %128 +%130 = OpFNegate %6 %129 +OpStore %128 %130 +%131 = OpCompositeExtract %15 %125 1 +OpStore %87 %131 +%132 = OpCompositeExtract %11 %125 2 +OpStore %89 %132 OpReturn OpFunctionEnd -%148 = OpFunction %2 None %90 -%137 = OpLabel -%132 = OpVariable %104 Function %133 -%134 = OpVariable %135 Function %136 -%141 = OpLoad %11 %139 -%144 = OpLoad %15 %142 -%146 = OpLoad %11 %145 -%138 = OpCompositeConstruct %16 %141 %144 %146 -%149 = OpAccessChain %91 %26 %92 -%150 = OpAccessChain %94 %29 %92 -%152 = OpAccessChain %151 %32 %92 -%153 = OpLoad %22 %38 -%154 = OpLoad %23 %40 -OpBranch %155 -%155 = OpLabel -%156 = OpCompositeExtract %15 %138 1 -%157 = OpExtInst %15 %1 Normalize %156 -OpStore %132 %25 -OpStore %134 %92 -OpBranch %158 -%158 = OpLabel -OpLoopMerge %159 %161 None -OpBranch %160 -%160 = OpLabel -%162 = OpLoad %8 %134 -%165 = OpAccessChain %164 %149 %9 %92 -%166 = OpLoad %8 %165 -%167 = OpExtInst %8 %1 UMin %166 %7 -%168 = OpULessThan %55 %162 %167 -OpSelectionMerge %169 None -OpBranchConditional %168 %169 %170 -%170 = OpLabel +%149 = OpFunction %2 None %91 +%138 = OpLabel +%133 = OpVariable %105 Function %134 +%135 = OpVariable %136 Function %137 +%142 = OpLoad %11 %140 +%145 = OpLoad %15 %143 +%147 = OpLoad %11 %146 +%139 = OpCompositeConstruct %16 %142 %145 %147 +%150 = OpAccessChain %92 %27 %93 +%151 = OpAccessChain %95 %30 %93 +%153 = OpAccessChain %152 %33 %93 +%154 = OpLoad %23 %39 +%155 = OpLoad %24 %41 +OpBranch %156 +%156 = OpLabel +%157 = OpCompositeExtract %15 %139 1 +%158 = OpExtInst %15 %1 Normalize %157 +OpStore %133 %26 +OpStore %135 %93 OpBranch %159 -%169 = OpLabel -OpBranch %171 -%171 = OpLabel -%173 = OpLoad %8 %134 -%175 = OpAccessChain %174 %152 %173 -%176 = OpLoad %19 %175 -%177 = OpLoad %8 %134 -%178 = OpCompositeExtract %10 %176 0 -%179 = OpCompositeExtract %11 %138 2 -%180 = OpMatrixTimesVector %11 %178 %179 -%181 = OpFunctionCall %6 %45 %177 %180 -%182 = OpCompositeExtract %11 %176 1 -%183 = OpVectorShuffle %15 %182 %182 0 1 2 -%184 = OpCompositeExtract %11 %138 2 -%185 = OpVectorShuffle %15 %184 %184 0 1 2 -%186 = OpFSub %15 %183 %185 -%187 = OpExtInst %15 %1 Normalize %186 -%188 = OpDot %6 %157 %187 -%189 = OpExtInst %6 %1 FMax %49 %188 -%190 = OpFMul %6 %181 %189 -%191 = OpCompositeExtract %11 %176 2 -%192 = OpVectorShuffle %15 %191 %191 0 1 2 -%193 = OpVectorTimesScalar %15 %192 %190 -%194 = OpLoad %15 %132 -%195 = OpFAdd %15 %194 %193 -OpStore %132 %195 -OpBranch %172 -%172 = OpLabel +%159 = OpLabel +OpLoopMerge %160 %162 None OpBranch %161 %161 = OpLabel -%196 = OpLoad %8 %134 -%197 = OpIAdd %8 %196 %9 -OpStore %134 %197 -OpBranch %158 -%159 = OpLabel -%198 = OpLoad %15 %132 -%199 = OpCompositeConstruct %11 %198 %50 -%201 = OpAccessChain %200 %150 %9 -%202 = OpLoad %11 %201 -%203 = OpFMul %11 %199 %202 -OpStore %147 %203 +%163 = OpLoad %8 %135 +%166 = OpAccessChain %165 %150 %9 %93 +%167 = OpLoad %8 %166 +%168 = OpExtInst %8 %1 UMin %167 %7 +%169 = OpULessThan %56 %163 %168 +OpSelectionMerge %170 None +OpBranchConditional %169 %170 %171 +%171 = OpLabel +OpBranch %160 +%170 = OpLabel +OpBranch %172 +%172 = OpLabel +%174 = OpLoad %8 %135 +%176 = OpAccessChain %175 %153 %174 +%177 = OpLoad %19 %176 +%178 = OpLoad %8 %135 +%179 = OpCompositeExtract %10 %177 0 +%180 = OpCompositeExtract %11 %139 2 +%181 = OpMatrixTimesVector %11 %179 %180 +%182 = OpFunctionCall %6 %46 %178 %181 +%183 = OpCompositeExtract %11 %177 1 +%184 = OpVectorShuffle %15 %183 %183 0 1 2 +%185 = OpCompositeExtract %11 %139 2 +%186 = OpVectorShuffle %15 %185 %185 0 1 2 +%187 = OpFSub %15 %184 %186 +%188 = OpExtInst %15 %1 Normalize %187 +%189 = OpDot %6 %158 %188 +%190 = OpExtInst %6 %1 FMax %50 %189 +%191 = OpFMul %6 %182 %190 +%192 = OpCompositeExtract %11 %177 2 +%193 = OpVectorShuffle %15 %192 %192 0 1 2 +%194 = OpVectorTimesScalar %15 %193 %191 +%195 = OpLoad %15 %133 +%196 = OpFAdd %15 %195 %194 +OpStore %133 %196 +OpBranch %173 +%173 = OpLabel +OpBranch %162 +%162 = OpLabel +%197 = OpLoad %8 %135 +%198 = OpIAdd %8 %197 %9 +OpStore %135 %198 +OpBranch %159 +%160 = OpLabel +%199 = OpLoad %15 %133 +%200 = OpCompositeConstruct %11 %199 %51 +%202 = OpAccessChain %201 %151 %9 +%203 = OpLoad %11 %202 +%204 = OpFMul %11 %200 %203 +OpStore %148 %204 OpReturn OpFunctionEnd -%217 = OpFunction %2 None %90 -%208 = OpLabel -%204 = OpVariable %104 Function %205 -%206 = OpVariable %135 Function %207 -%211 = OpLoad %11 %210 -%213 = OpLoad %15 %212 -%215 = OpLoad %11 %214 -%209 = OpCompositeConstruct %16 %211 %213 %215 -%218 = OpAccessChain %91 %26 %92 -%219 = OpAccessChain %94 %29 %92 -%221 = OpAccessChain %220 %35 %92 -%222 = OpLoad %22 %38 -%223 = OpLoad %23 %40 -OpBranch %224 -%224 = OpLabel -%225 = OpCompositeExtract %15 %209 1 -%226 = OpExtInst %15 %1 Normalize %225 -OpStore %204 %25 -OpStore %206 %92 -OpBranch %227 -%227 = OpLabel -OpLoopMerge %228 %230 None -OpBranch %229 -%229 = OpLabel -%231 = OpLoad %8 %206 -%232 = OpAccessChain %164 %218 %9 %92 -%233 = OpLoad %8 %232 -%234 = OpExtInst %8 %1 UMin %233 %7 -%235 = OpULessThan %55 %231 %234 -OpSelectionMerge %236 None -OpBranchConditional %235 %236 %237 -%237 = OpLabel +%218 = OpFunction %2 None %91 +%209 = OpLabel +%205 = OpVariable %105 Function %206 +%207 = OpVariable %136 Function %208 +%212 = OpLoad %11 %211 +%214 = OpLoad %15 %213 +%216 = OpLoad %11 %215 +%210 = OpCompositeConstruct %16 %212 %214 %216 +%219 = OpAccessChain %92 %27 %93 +%220 = OpAccessChain %95 %30 %93 +%222 = OpAccessChain %221 %36 %93 +%223 = OpLoad %23 %39 +%224 = OpLoad %24 %41 +OpBranch %225 +%225 = OpLabel +%226 = OpCompositeExtract %15 %210 1 +%227 = OpExtInst %15 %1 Normalize %226 +OpStore %205 %26 +OpStore %207 %93 OpBranch %228 -%236 = OpLabel -OpBranch %238 -%238 = OpLabel -%240 = OpLoad %8 %206 -%242 = OpAccessChain %241 %221 %240 -%243 = OpLoad %19 %242 -%244 = OpLoad %8 %206 -%245 = OpCompositeExtract %10 %243 0 -%246 = OpCompositeExtract %11 %209 2 -%247 = OpMatrixTimesVector %11 %245 %246 -%248 = OpFunctionCall %6 %45 %244 %247 -%249 = OpCompositeExtract %11 %243 1 -%250 = OpVectorShuffle %15 %249 %249 0 1 2 -%251 = OpCompositeExtract %11 %209 2 -%252 = OpVectorShuffle %15 %251 %251 0 1 2 -%253 = OpFSub %15 %250 %252 -%254 = OpExtInst %15 %1 Normalize %253 -%255 = OpDot %6 %226 %254 -%256 = OpExtInst %6 %1 FMax %49 %255 -%257 = OpFMul %6 %248 %256 -%258 = OpCompositeExtract %11 %243 2 -%259 = OpVectorShuffle %15 %258 %258 0 1 2 -%260 = OpVectorTimesScalar %15 %259 %257 -%261 = OpLoad %15 %204 -%262 = OpFAdd %15 %261 %260 -OpStore %204 %262 -OpBranch %239 -%239 = OpLabel +%228 = OpLabel +OpLoopMerge %229 %231 None OpBranch %230 %230 = OpLabel -%263 = OpLoad %8 %206 -%264 = OpIAdd %8 %263 %9 -OpStore %206 %264 -OpBranch %227 -%228 = OpLabel -%265 = OpLoad %15 %204 -%266 = OpCompositeConstruct %11 %265 %50 -%267 = OpAccessChain %200 %219 %9 -%268 = OpLoad %11 %267 -%269 = OpFMul %11 %266 %268 -OpStore %216 %269 +%232 = OpLoad %8 %207 +%233 = OpAccessChain %165 %219 %9 %93 +%234 = OpLoad %8 %233 +%235 = OpExtInst %8 %1 UMin %234 %7 +%236 = OpULessThan %56 %232 %235 +OpSelectionMerge %237 None +OpBranchConditional %236 %237 %238 +%238 = OpLabel +OpBranch %229 +%237 = OpLabel +OpBranch %239 +%239 = OpLabel +%241 = OpLoad %8 %207 +%243 = OpAccessChain %242 %222 %241 +%244 = OpLoad %19 %243 +%245 = OpLoad %8 %207 +%246 = OpCompositeExtract %10 %244 0 +%247 = OpCompositeExtract %11 %210 2 +%248 = OpMatrixTimesVector %11 %246 %247 +%249 = OpFunctionCall %6 %46 %245 %248 +%250 = OpCompositeExtract %11 %244 1 +%251 = OpVectorShuffle %15 %250 %250 0 1 2 +%252 = OpCompositeExtract %11 %210 2 +%253 = OpVectorShuffle %15 %252 %252 0 1 2 +%254 = OpFSub %15 %251 %253 +%255 = OpExtInst %15 %1 Normalize %254 +%256 = OpDot %6 %227 %255 +%257 = OpExtInst %6 %1 FMax %50 %256 +%258 = OpFMul %6 %249 %257 +%259 = OpCompositeExtract %11 %244 2 +%260 = OpVectorShuffle %15 %259 %259 0 1 2 +%261 = OpVectorTimesScalar %15 %260 %258 +%262 = OpLoad %15 %205 +%263 = OpFAdd %15 %262 %261 +OpStore %205 %263 +OpBranch %240 +%240 = OpLabel +OpBranch %231 +%231 = OpLabel +%264 = OpLoad %8 %207 +%265 = OpIAdd %8 %264 %9 +OpStore %207 %265 +OpBranch %228 +%229 = OpLabel +%266 = OpLoad %15 %205 +%267 = OpCompositeConstruct %11 %266 %51 +%268 = OpAccessChain %201 %220 %9 +%269 = OpLoad %11 %268 +%270 = OpFMul %11 %267 %269 +OpStore %217 %270 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/workgroup-var-init.spvasm b/tests/out/spv/workgroup-var-init.spvasm index ee62929c9..122a61283 100644 --- a/tests/out/spv/workgroup-var-init.spvasm +++ b/tests/out/spv/workgroup-var-init.spvasm @@ -1,78 +1,80 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 41 +; Bound: 43 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %17 "main" %25 -OpExecutionMode %17 LocalSize 1 1 1 +OpEntryPoint GLCompute %19 "main" %27 +OpExecutionMode %19 LocalSize 1 1 1 OpSource GLSL 450 -OpMemberName %10 0 "arr" -OpMemberName %10 1 "atom" -OpMemberName %10 2 "atom_arr" -OpName %10 "WStruct" -OpName %11 "w_mem" -OpName %13 "output" -OpName %17 "main" +OpMemberName %12 0 "arr" +OpMemberName %12 1 "atom" +OpMemberName %12 2 "atom_arr" +OpName %12 "WStruct" +OpName %13 "w_mem" +OpName %15 "output" +OpName %19 "main" OpDecorate %7 ArrayStride 4 -OpDecorate %8 ArrayStride 4 -OpDecorate %9 ArrayStride 32 -OpMemberDecorate %10 0 Offset 0 -OpMemberDecorate %10 1 Offset 2048 -OpMemberDecorate %10 2 Offset 2052 -OpDecorate %13 DescriptorSet 0 -OpDecorate %13 Binding 0 -OpDecorate %14 Block -OpMemberDecorate %14 0 Offset 0 -OpDecorate %25 BuiltIn LocalInvocationId +OpDecorate %9 ArrayStride 4 +OpDecorate %11 ArrayStride 32 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 2048 +OpMemberDecorate %12 2 Offset 2052 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 0 +OpDecorate %16 Block +OpMemberDecorate %16 0 Offset 0 +OpDecorate %27 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 512 %5 = OpConstant %4 8 %6 = OpTypeInt 32 0 -%7 = OpTypeArray %6 %3 -%8 = OpTypeArray %4 %5 -%9 = OpTypeArray %8 %5 -%10 = OpTypeStruct %7 %4 %9 -%12 = OpTypePointer Workgroup %10 -%11 = OpVariable %12 Workgroup -%14 = OpTypeStruct %7 -%15 = OpTypePointer StorageBuffer %14 -%13 = OpVariable %15 StorageBuffer -%18 = OpTypeFunction %2 -%19 = OpTypePointer StorageBuffer %7 -%20 = OpConstant %6 0 -%23 = OpConstantNull %10 -%24 = OpTypeVector %6 3 -%26 = OpTypePointer Input %24 -%25 = OpVariable %26 Input -%28 = OpConstantNull %24 -%30 = OpTypeBool -%29 = OpTypeVector %30 3 -%35 = OpConstant %6 2 -%36 = OpConstant %6 264 -%38 = OpTypePointer Workgroup %7 -%17 = OpFunction %2 None %18 -%16 = OpLabel -%21 = OpAccessChain %19 %13 %20 -OpBranch %22 -%22 = OpLabel -%27 = OpLoad %24 %25 -%31 = OpIEqual %29 %27 %28 -%32 = OpAll %30 %31 -OpSelectionMerge %33 None -OpBranchConditional %32 %34 %33 -%34 = OpLabel -OpStore %11 %23 -OpBranch %33 -%33 = OpLabel -OpControlBarrier %35 %35 %36 -OpBranch %37 -%37 = OpLabel -%39 = OpAccessChain %38 %11 %20 -%40 = OpLoad %7 %39 -OpStore %21 %40 +%8 = OpConstant %6 512 +%7 = OpTypeArray %6 %8 +%10 = OpConstant %6 8 +%9 = OpTypeArray %4 %10 +%11 = OpTypeArray %9 %10 +%12 = OpTypeStruct %7 %4 %11 +%14 = OpTypePointer Workgroup %12 +%13 = OpVariable %14 Workgroup +%16 = OpTypeStruct %7 +%17 = OpTypePointer StorageBuffer %16 +%15 = OpVariable %17 StorageBuffer +%20 = OpTypeFunction %2 +%21 = OpTypePointer StorageBuffer %7 +%22 = OpConstant %6 0 +%25 = OpConstantNull %12 +%26 = OpTypeVector %6 3 +%28 = OpTypePointer Input %26 +%27 = OpVariable %28 Input +%30 = OpConstantNull %26 +%32 = OpTypeBool +%31 = OpTypeVector %32 3 +%37 = OpConstant %6 2 +%38 = OpConstant %6 264 +%40 = OpTypePointer Workgroup %7 +%19 = OpFunction %2 None %20 +%18 = OpLabel +%23 = OpAccessChain %21 %15 %22 +OpBranch %24 +%24 = OpLabel +%29 = OpLoad %26 %27 +%33 = OpIEqual %31 %29 %30 +%34 = OpAll %32 %33 +OpSelectionMerge %35 None +OpBranchConditional %34 %36 %35 +%36 = OpLabel +OpStore %13 %25 +OpBranch %35 +%35 = OpLabel +OpControlBarrier %37 %37 %38 +OpBranch %39 +%39 = OpLabel +%41 = OpAccessChain %40 %13 %22 +%42 = OpLoad %7 %41 +OpStore %23 %42 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index f82521a75..d7358b267 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -10,10 +10,10 @@ struct AlignedWrapper { struct Bar { _matrix: mat4x3, - matrix_array: array,2>, + matrix_array: array, 2>, atom: atomic, - atom_arr: array,10>, - arr: array,2>, + atom_arr: array, 10>, + arr: array, 2>, data: array, } @@ -22,7 +22,7 @@ struct Baz { } struct MatCx2InArray { - am: array,2>, + am: array, 2>, } var global_const: GlobalConst = GlobalConst(0u, vec3(0u, 0u, 0u), 0); @@ -93,10 +93,10 @@ fn test_matrix_within_array_within_struct_accesses() { let _e58 = idx_1; let _e60 = idx_1; _ = nested_mat_cx2_.am[0][_e58][_e60]; - t_1 = MatCx2InArray(array,2>()); + t_1 = MatCx2InArray(array, 2>()); let _e66 = idx_1; idx_1 = (_e66 + 1); - t_1.am = array,2>(); + t_1.am = array, 2>(); t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); t_1.am[0][0] = vec2(9.0); let _e93 = idx_1; @@ -117,7 +117,7 @@ fn read_from_private(foo_1: ptr) -> f32 { return _e1; } -fn test_arr_as_arg(a: array,5>) -> f32 { +fn test_arr_as_arg(a: array, 5>) -> f32 { return a[4][9]; } @@ -126,15 +126,15 @@ fn assign_through_ptr_fn(p: ptr) { return; } -fn assign_array_through_ptr_fn(foo_2: ptr,2>>) { - (*foo_2) = array,2>(vec4(1.0), vec4(2.0)); +fn assign_array_through_ptr_fn(foo_2: ptr, 2>>) { + (*foo_2) = array, 2>(vec4(1.0), vec4(2.0)); return; } @vertex fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var foo: f32; - var c2_: array; + var c2_: array; foo = 0.0; let baz_1 = foo; @@ -148,10 +148,10 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let c = qux; let data_pointer = (&bar.data[0].value); let _e34 = read_from_private((&foo)); - c2_ = array(a_1, i32(b), 3, 4, 5); + c2_ = array(a_1, i32(b), 3, 4, 5); c2_[(vi + 1u)] = 42; let value = c2_[vi]; - let _e48 = test_arr_as_arg(array,5>()); + let _e48 = test_arr_as_arg(array, 5>()); return vec4((_matrix * vec4(vec4(value))), 2.0); } @@ -159,7 +159,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { fn foo_frag() -> @location(0) vec4 { bar._matrix[1][2] = 1.0; bar._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); - bar.arr = array,2>(vec2(0u), vec2(1u)); + bar.arr = array, 2>(vec2(0u), vec2(1u)); bar.data[1].value = 1; qux = vec2(); return vec4(0.0); @@ -167,9 +167,9 @@ fn foo_frag() -> @location(0) vec4 { @compute @workgroup_size(1, 1, 1) fn assign_through_ptr() { - var arr: array,2>; + var arr: array, 2>; - arr = array,2>(vec4(6.0), vec4(7.0)); + arr = array, 2>(vec4(6.0), vec4(7.0)); assign_through_ptr_fn((&val)); assign_array_through_ptr_fn((&arr)); return; diff --git a/tests/out/wgsl/array-in-ctor.wgsl b/tests/out/wgsl/array-in-ctor.wgsl index f4a8f4ddd..290442d6f 100644 --- a/tests/out/wgsl/array-in-ctor.wgsl +++ b/tests/out/wgsl/array-in-ctor.wgsl @@ -1,5 +1,5 @@ struct Ah { - inner: array, + inner: array, } @group(0) @binding(0) diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/tests/out/wgsl/atomicCompareExchange.wgsl index bfad298fa..d9f0c0add 100644 --- a/tests/out/wgsl/atomicCompareExchange.wgsl +++ b/tests/out/wgsl/atomicCompareExchange.wgsl @@ -11,9 +11,9 @@ struct gen___atomic_compare_exchange_resultUint4_ { const SIZE: u32 = 128u; @group(0) @binding(0) -var arr_i32_: array,SIZE>; +var arr_i32_: array, 128>; @group(0) @binding(1) -var arr_u32_: array,SIZE>; +var arr_u32_: array, 128>; @compute @workgroup_size(1, 1, 1) fn test_atomic_compare_exchange_i32_() { diff --git a/tests/out/wgsl/atomicOps.wgsl b/tests/out/wgsl/atomicOps.wgsl index 80d177654..86f877666 100644 --- a/tests/out/wgsl/atomicOps.wgsl +++ b/tests/out/wgsl/atomicOps.wgsl @@ -1,16 +1,16 @@ struct Struct { atomic_scalar: atomic, - atomic_arr: array,2>, + atomic_arr: array, 2>, } @group(0) @binding(0) var storage_atomic_scalar: atomic; @group(0) @binding(1) -var storage_atomic_arr: array,2>; +var storage_atomic_arr: array, 2>; @group(0) @binding(2) var storage_struct: Struct; var workgroup_atomic_scalar: atomic; -var workgroup_atomic_arr: array,2>; +var workgroup_atomic_arr: array, 2>; var workgroup_struct: Struct; @compute @workgroup_size(2, 1, 1) diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 646eb615d..9f55e5f16 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -20,8 +20,8 @@ struct CameraPosition { struct Lights { AmbientColor: vec4, NumLights: vec4, - PointLights: array, - DirectionalLights: array, + PointLights: array, + DirectionalLights: array, } struct StandardMaterial_base_color { diff --git a/tests/out/wgsl/binding-arrays.static.wgsl b/tests/out/wgsl/binding-arrays.static.wgsl index c669e9aa6..2c1fb2be7 100644 --- a/tests/out/wgsl/binding-arrays.static.wgsl +++ b/tests/out/wgsl/binding-arrays.static.wgsl @@ -1,7 +1,7 @@ @group(0) @binding(0) -var global: binding_array,256u>; +var global: binding_array, 256>; @group(0) @binding(1) -var global_1: binding_array; +var global_1: binding_array; var global_2: vec4; fn function() { diff --git a/tests/out/wgsl/binding-arrays.wgsl b/tests/out/wgsl/binding-arrays.wgsl index a7c64fe62..97c992e4e 100644 --- a/tests/out/wgsl/binding-arrays.wgsl +++ b/tests/out/wgsl/binding-arrays.wgsl @@ -9,19 +9,19 @@ struct FragmentIn { @group(0) @binding(0) var texture_array_unbounded: binding_array>; @group(0) @binding(1) -var texture_array_bounded: binding_array,5>; +var texture_array_bounded: binding_array, 5>; @group(0) @binding(2) -var texture_array_2darray: binding_array,5>; +var texture_array_2darray: binding_array, 5>; @group(0) @binding(3) -var texture_array_multisampled: binding_array,5>; +var texture_array_multisampled: binding_array, 5>; @group(0) @binding(4) -var texture_array_depth: binding_array; +var texture_array_depth: binding_array; @group(0) @binding(5) -var texture_array_storage: binding_array,5>; +var texture_array_storage: binding_array, 5>; @group(0) @binding(6) -var samp: binding_array; +var samp: binding_array; @group(0) @binding(7) -var samp_comp: binding_array; +var samp_comp: binding_array; @group(0) @binding(8) var uni: UniformIndex; diff --git a/tests/out/wgsl/binding-buffer-arrays.wgsl b/tests/out/wgsl/binding-buffer-arrays.wgsl index 60ad84caf..4a36faa39 100644 --- a/tests/out/wgsl/binding-buffer-arrays.wgsl +++ b/tests/out/wgsl/binding-buffer-arrays.wgsl @@ -11,7 +11,7 @@ struct FragmentIn { } @group(0) @binding(0) -var storage_array: binding_array; +var storage_array: binding_array; @group(0) @binding(10) var uni: UniformIndex; diff --git a/tests/out/wgsl/constant-array-size-frag.wgsl b/tests/out/wgsl/constant-array-size-frag.wgsl index 98d413bdf..fb706acf2 100644 --- a/tests/out/wgsl/constant-array-size-frag.wgsl +++ b/tests/out/wgsl/constant-array-size-frag.wgsl @@ -1,5 +1,5 @@ struct Data { - vecs: array,42u>, + vecs: array, 42>, } const NUM_VECS: i32 = 42; diff --git a/tests/out/wgsl/declarations-frag.wgsl b/tests/out/wgsl/declarations-frag.wgsl index 107bcaa4f..a004823b6 100644 --- a/tests/out/wgsl/declarations-frag.wgsl +++ b/tests/out/wgsl/declarations-frag.wgsl @@ -22,13 +22,13 @@ struct FragmentOutput { var vert: VertexData; var frag: FragmentData; -var in_array_2: array,2u>; -var out_array: array,2u>; -var array_2d: array,2u>; -var array_toomanyd: array,2u>,2u>,2u>,2u>,2u>,2u>; +var in_array_2: array, 2>; +var out_array: array, 2>; +var array_2d: array, 2>; +var array_toomanyd: array, 2>, 2>, 2>, 2>, 2>, 2>; fn main_1() { - var positions: array,2u>; + var positions: array, 2>; var strct: TestStruct; var from_input_array: vec4; var a_1: f32; @@ -38,7 +38,7 @@ fn main_1() { _ = (&vert.a); _ = (&frag.position); _ = (&frag.a); - positions = array,2u>(vec3(-(1.0), 1.0, 0.0), vec3(-(1.0), -(1.0), 0.0)); + positions = array, 2>(vec3(-(1.0), 1.0, 0.0), vec3(-(1.0), -(1.0), 0.0)); strct = TestStruct(f32(1), f32(2)); let _e35 = in_array_2[1]; from_input_array = _e35; diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index 0910cdfe2..d32860d55 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -7,14 +7,14 @@ struct a_buf { } struct TestStruct { - array_: array,2u>, + array_: array, 2>, } struct FragmentOutput { @location(0) o_color: vec4, } -const strct: TestStruct = TestStruct(array,2u>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); +const strct: TestStruct = TestStruct(array, 2>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); var global: f32; @group(0) @binding(0) var global_1: a_buf; @@ -293,9 +293,9 @@ fn testNonScalarToScalarConstructor() { } fn testArrayConstructor() { - var tree_1: array; + var tree_1: array; - tree_1 = array(0.0); + tree_1 = array(0.0); return; } @@ -390,8 +390,8 @@ fn testLength() { return; } -fn testConstantLength(a_24: array) { - var a_25: array; +fn testConstantLength(a_24: array) { + var a_25: array; var len_1: i32; _ = (&global_1.a); @@ -403,7 +403,7 @@ fn testConstantLength(a_24: array) { fn indexConstantNonConstantIndex(i: i32) { var i_1: i32; - var local_5: TestStruct = TestStruct(array,2u>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); + var local_5: TestStruct = TestStruct(array, 2>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); var a_26: vec4; _ = (&global_1.a); @@ -461,7 +461,7 @@ fn main_1() { @fragment fn main() -> FragmentOutput { _ = (&global_1.a); - _ = TestStruct(array,2u>(vec4(u32(0)), vec4(u32(1)))); + _ = TestStruct(array, 2>(vec4(u32(0)), vec4(u32(1)))); main_1(); let _e17 = o_color; return FragmentOutput(_e17); diff --git a/tests/out/wgsl/global-constant-array-frag.wgsl b/tests/out/wgsl/global-constant-array-frag.wgsl index bda27f3f5..85b871c2a 100644 --- a/tests/out/wgsl/global-constant-array-frag.wgsl +++ b/tests/out/wgsl/global-constant-array-frag.wgsl @@ -1,15 +1,15 @@ -const array_: array = array(1.0, 2.0); +const array_: array = array(1.0, 2.0); var i: u32; fn main_1() { - var local: array = array(1.0, 2.0); + var local: array = array(1.0, 2.0); let _e2 = i; } @fragment fn main() { - _ = array(1.0, 2.0); + _ = array(1.0, 2.0); main_1(); return; } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 3ce0be881..7acdbfec7 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -5,22 +5,22 @@ struct FooStruct { const Foo_1: bool = true; -var wg: array; +var wg: array; var at_1: atomic; @group(0) @binding(1) var alignment: FooStruct; @group(0) @binding(2) var dummy: array>; @group(0) @binding(3) -var float_vecs: array,20>; +var float_vecs: array, 20>; @group(0) @binding(4) var global_vec: vec3; @group(0) @binding(5) var global_mat: mat3x2; @group(0) @binding(6) -var global_nested_arrays_of_matrices_2x4_: array,2>,2>; +var global_nested_arrays_of_matrices_2x4_: array, 2>, 2>; @group(0) @binding(7) -var global_nested_arrays_of_matrices_4x2_: array,2>,2>; +var global_nested_arrays_of_matrices_4x2_: array, 2>, 2>; fn test_msl_packed_vec3_as_arg(arg: vec3) { return; diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index 5ba5bce19..68fe28cd4 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -17,7 +17,7 @@ struct Input2_ { @builtin(instance_index) index: u32, } -var output: array; +var output: array; @vertex fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) instance_index: u32, @location(10) @interpolate(flat) color: u32) -> VertexOutput { diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index d2fb888d7..a5aba2064 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -52,7 +52,7 @@ fn constructors() -> f32 { let mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); _ = vec2(0u); _ = mat2x2(vec2(0.0), vec2(0.0)); - _ = array(0, 1, 2, 3); + _ = array(0, 1, 2, 3); _ = bool(bool()); _ = i32(i32()); _ = u32(u32()); diff --git a/tests/out/wgsl/padding.wgsl b/tests/out/wgsl/padding.wgsl index a4c0a968d..7f77c3531 100644 --- a/tests/out/wgsl/padding.wgsl +++ b/tests/out/wgsl/padding.wgsl @@ -8,7 +8,7 @@ struct Test { } struct Test2_ { - a: array,2>, + a: array, 2>, b: f32, } diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index 97eee6a75..2c824e873 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -1,8 +1,8 @@ struct gl_PerVertex { @builtin(position) gl_Position: vec4, gl_PointSize: f32, - gl_ClipDistance: array, - gl_CullDistance: array, + gl_ClipDistance: array, + gl_CullDistance: array, } struct VertexOutput { @@ -12,7 +12,7 @@ struct VertexOutput { var v_uv: vec2; var a_uv_1: vec2; -var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), 1.0, array(0.0), array(0.0)); +var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), 1.0, array(0.0), array(0.0)); var a_pos_1: vec2; fn main_1() { diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index de4aace6f..d93c716ba 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -30,7 +30,7 @@ var u_entity: Entity; @group(0) @binding(1) var s_lights: array; @group(0) @binding(1) -var u_lights: array; +var u_lights: array; @group(0) @binding(2) var t_shadow: texture_depth_2d_array; @group(0) @binding(3) diff --git a/tests/out/wgsl/workgroup-var-init.wgsl b/tests/out/wgsl/workgroup-var-init.wgsl index 6197108cb..fdad0477d 100644 --- a/tests/out/wgsl/workgroup-var-init.wgsl +++ b/tests/out/wgsl/workgroup-var-init.wgsl @@ -1,12 +1,12 @@ struct WStruct { - arr: array, + arr: array, atom: atomic, - atom_arr: array,8>,8>, + atom_arr: array, 8>, 8>, } var w_mem: WStruct; @group(0) @binding(0) -var output: array; +var output: array; @compute @workgroup_size(1, 1, 1) fn main() { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 8bd13dacf..369ff4a4d 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -921,26 +921,52 @@ fn invalid_arrays() { }) } - check_validation! { + check( "alias Bad = array;", + r###"error: array element count must resolve to an integer scalar (u32 or i32) + ┌─ wgsl:1:24 + │ +1 │ alias Bad = array; + │ ^^^^ must resolve to u32/i32 + +"###, + ); + + check( r#" const length: f32 = 2.718; alias Bad = array; - "#: - Err(naga::valid::ValidationError::Type { - source: naga::valid::TypeError::InvalidArraySizeConstant(_), - .. - }) - } + "#, + r###"error: array element count must resolve to an integer scalar (u32 or i32) + ┌─ wgsl:3:36 + │ +3 │ alias Bad = array; + │ ^^^^^^ must resolve to u32/i32 - check_validation! { +"###, + ); + + check( "alias Bad = array;", - "alias Bad = array;": - Err(naga::valid::ValidationError::Type { - source: naga::valid::TypeError::NonPositiveArrayLength(_), - .. - }) - } + r###"error: array element count must be greater than zero + ┌─ wgsl:1:24 + │ +1 │ alias Bad = array; + │ ^ must be positive + +"###, + ); + + check( + "alias Bad = array;", + r###"error: array element count must resolve to an integer scalar (u32 or i32) + ┌─ wgsl:1:24 + │ +1 │ alias Bad = array; + │ ^^ must resolve to u32/i32 + +"###, + ); } #[test] From 423a069dcddc790fdf27d8c389fa4487f07fcc0a Mon Sep 17 00:00:00 2001 From: Eduard-Mihai Burtescu Date: Thu, 27 Apr 2023 12:54:43 +0300 Subject: [PATCH 2000/2212] [spv-in] Convert conditional backedges to `break if`. --- src/front/spv/function.rs | 8 +- src/front/spv/mod.rs | 121 ++++++++++++++++++--- tests/in/spv/do-while.spv | Bin 0 -> 480 bytes tests/in/spv/do-while.spvasm | 64 +++++++++++ tests/out/glsl/do-while.main.Fragment.glsl | 33 ++++++ tests/out/hlsl/do-while.hlsl | 31 ++++++ tests/out/hlsl/do-while.hlsl.config | 3 + tests/out/msl/do-while.msl | 37 +++++++ tests/out/wgsl/do-while.wgsl | 24 ++++ tests/snapshots.rs | 5 + 10 files changed, 307 insertions(+), 19 deletions(-) create mode 100644 tests/in/spv/do-while.spv create mode 100644 tests/in/spv/do-while.spvasm create mode 100644 tests/out/glsl/do-while.main.Fragment.glsl create mode 100644 tests/out/hlsl/do-while.hlsl create mode 100644 tests/out/hlsl/do-while.hlsl.config create mode 100644 tests/out/msl/do-while.msl create mode 100644 tests/out/wgsl/do-while.wgsl diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 89ad4a0e1..97a197497 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -604,7 +604,11 @@ impl<'function> BlockContext<'function> { crate::Span::default(), ) } - super::BodyFragment::Loop { body, continuing } => { + super::BodyFragment::Loop { + body, + continuing, + break_if, + } => { let body = lower_impl(blocks, bodies, body); let continuing = lower_impl(blocks, bodies, continuing); @@ -612,7 +616,7 @@ impl<'function> BlockContext<'function> { crate::Statement::Loop { body, continuing, - break_if: None, + break_if, }, crate::Span::default(), ) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 143af4a43..e450ea5e9 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -388,6 +388,11 @@ enum BodyFragment { Loop { body: BodyIndex, continuing: BodyIndex, + + /// If the SPIR-V loop's back-edge branch is conditional, this is the + /// expression that must be `false` for the back-edge to be taken, with + /// `true` being for the "loop merge" (which breaks out of the loop). + break_if: Option>, }, Switch { selector: Handle, @@ -429,7 +434,7 @@ struct PhiExpression { expressions: Vec<(spirv::Word, spirv::Word)>, } -#[derive(Debug)] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] enum MergeBlockInformation { LoopMerge, LoopContinue, @@ -3116,35 +3121,121 @@ impl> Frontend { get_expr_handle!(condition_id, lexp) }; + // HACK(eddyb) Naga doesn't seem to have this helper, + // so it's declared on the fly here for convenience. + #[derive(Copy, Clone)] + struct BranchTarget { + label_id: spirv::Word, + merge_info: Option, + } + let branch_target = |label_id| BranchTarget { + label_id, + merge_info: ctx.mergers.get(&label_id).copied(), + }; + + let true_target = branch_target(self.next()?); + let false_target = branch_target(self.next()?); + + // Consume branch weights + for _ in 4..inst.wc { + let _ = self.next()?; + } + + // Handle `OpBranchConditional`s used at the end of a loop + // body's "continuing" section as a "conditional backedge", + // i.e. a `do`-`while` condition, or `break if` in WGSL. + + // HACK(eddyb) this has to go to the parent *twice*, because + // `OpLoopMerge` left the "continuing" section nested in the + // loop body in terms of `parent`, but not `BodyFragment`. + let parent_body_idx = ctx.bodies[body_idx].parent; + let parent_parent_body_idx = ctx.bodies[parent_body_idx].parent; + match ctx.bodies[parent_parent_body_idx].data[..] { + // The `OpLoopMerge`'s `continuing` block and the loop's + // backedge block may not be the same, but they'll both + // belong to the same body. + [.., BodyFragment::Loop { + body: loop_body_idx, + continuing: loop_continuing_idx, + break_if: ref mut break_if_slot @ None, + }] if body_idx == loop_continuing_idx => { + // Try both orderings of break-vs-backedge, because + // SPIR-V is symmetrical here, unlike WGSL `break if`. + let break_if_cond = [true, false].into_iter().find_map(|true_breaks| { + let (break_candidate, backedge_candidate) = if true_breaks { + (true_target, false_target) + } else { + (false_target, true_target) + }; + + if break_candidate.merge_info + != Some(MergeBlockInformation::LoopMerge) + { + return None; + } + + // HACK(eddyb) since Naga doesn't explicitly track + // backedges, this is checking for the outcome of + // `OpLoopMerge` below (even if it looks weird). + let backedge_candidate_is_backedge = + backedge_candidate.merge_info.is_none() + && ctx.body_for_label.get(&backedge_candidate.label_id) + == Some(&loop_body_idx); + if !backedge_candidate_is_backedge { + return None; + } + + Some(if true_breaks { + condition + } else { + ctx.expressions.append( + crate::Expression::Unary { + op: crate::UnaryOperator::Not, + expr: condition, + }, + span, + ) + }) + }); + + if let Some(break_if_cond) = break_if_cond { + *break_if_slot = Some(break_if_cond); + + // This `OpBranchConditional` ends the "continuing" + // section of the loop body as normal, with the + // `break if` condition having been stashed above. + break None; + } + } + _ => {} + } + block.extend(emitter.finish(ctx.expressions)); ctx.blocks.insert(block_id, block); let body = &mut ctx.bodies[body_idx]; body.data.push(BodyFragment::BlockId(block_id)); - let true_id = self.next()?; - let false_id = self.next()?; - - let same_target = true_id == false_id; + let same_target = true_target.label_id == false_target.label_id; // Start a body block for the `accept` branch. let accept = ctx.bodies.len(); let mut accept_block = Body::with_parent(body_idx); - // If the `OpBranchConditional`target is somebody else's + // If the `OpBranchConditional` target is somebody else's // merge or continue block, then put a `Break` or `Continue` // statement in this new body block. - if let Some(info) = ctx.mergers.get(&true_id) { + if let Some(info) = true_target.merge_info { merger( match same_target { true => &mut ctx.bodies[body_idx], false => &mut accept_block, }, - info, + &info, ) } else { // Note the body index for the block we're branching to. let prev = ctx.body_for_label.insert( - true_id, + true_target.label_id, match same_target { true => body_idx, false => accept, @@ -3163,10 +3254,10 @@ impl> Frontend { let reject = ctx.bodies.len(); let mut reject_block = Body::with_parent(body_idx); - if let Some(info) = ctx.mergers.get(&false_id) { - merger(&mut reject_block, info) + if let Some(info) = false_target.merge_info { + merger(&mut reject_block, &info) } else { - let prev = ctx.body_for_label.insert(false_id, reject); + let prev = ctx.body_for_label.insert(false_target.label_id, reject); debug_assert!(prev.is_none()); } @@ -3179,11 +3270,6 @@ impl> Frontend { reject, }); - // Consume branch weights - for _ in 4..inst.wc { - let _ = self.next()?; - } - return Ok(()); } Op::Switch => { @@ -3353,6 +3439,7 @@ impl> Frontend { parent_body.data.push(BodyFragment::Loop { body: loop_body_idx, continuing: continue_idx, + break_if: None, }); body_idx = loop_body_idx; } diff --git a/tests/in/spv/do-while.spv b/tests/in/spv/do-while.spv new file mode 100644 index 0000000000000000000000000000000000000000..23d45958b9e0f61ef777f5c63975ccf8a311a542 GIT binary patch literal 480 zcmYk2+e!ja6oywbIg?o)(g#Soi7up|BT~2Bc-Iq*iQt76~Bp z{Ij=tc2-8Q7ZGI)`1SN63oETC5}zk8lhNmTHoCsKwBL?gq+TZ)u}_{6%WAQ*-leZD ziM-A?7&^H-r*?OKKD`=4bpc=BRx^;a9`DshwS;}Pn{b$1Bjp2Xhty8l?Lp_&L-YZ3 z-ueYQ)=!9AoUMBokFWVgHQ;#1N3SQk(!GazuTSp1t^e^a+!I?*>mI*-$FAS@P5QUs n4?L>1{KBaXJA}vnF?3$4?WyG>^S+}?==+N{*GnJg +#include + +using metal::uint; + + +void fb1_( + thread bool& cond +) { + bool loop_init = true; + while(true) { + if (!loop_init) { + bool _e6 = cond; + bool unnamed = !(_e6); + if (!(cond)) { + break; + } + } + loop_init = false; + continue; + } + return; +} + +void main_1( +) { + bool param = {}; + param = false; + fb1_(param); + return; +} + +fragment void main_( +) { + main_1(); +} diff --git a/tests/out/wgsl/do-while.wgsl b/tests/out/wgsl/do-while.wgsl new file mode 100644 index 000000000..d444169e4 --- /dev/null +++ b/tests/out/wgsl/do-while.wgsl @@ -0,0 +1,24 @@ +fn fb1_(cond: ptr) { + loop { + continue; + continuing { + let _e6 = (*cond); + _ = !(_e6); + break if !(_e6); + } + } + return; +} + +fn main_1() { + var param: bool; + + param = false; + fb1_((¶m)); + return; +} + +@fragment +fn main() { + main_1(); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 8e75f5b74..09e98607b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -640,6 +640,11 @@ fn convert_spv_all() { convert_spv("degrees", false, Targets::empty()); convert_spv("binding-arrays.dynamic", true, Targets::WGSL); convert_spv("binding-arrays.static", true, Targets::WGSL); + convert_spv( + "do-while", + true, + Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + ); } #[cfg(feature = "glsl-in")] From ce48588d74c55c7e63fe9f7f50c8d703d65c2a32 Mon Sep 17 00:00:00 2001 From: Ashley Date: Tue, 23 May 2023 04:35:58 +1200 Subject: [PATCH 2001/2212] [front/spir-v] Obey the `is_depth` field of `OpTypeImage` (#2341) * [front/spir-v] Obey the is_depth field of OpTypeImage * Add changed tests --- src/front/spv/mod.rs | 6 ++++-- tests/out/analysis/shadow.info.ron | 11 ++++------- tests/out/ir/shadow.ron | 17 +++-------------- 3 files changed, 11 insertions(+), 23 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index e450ea5e9..55a5cc57c 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -4708,7 +4708,7 @@ impl> Frontend { let id = self.next()?; let sample_type_id = self.next()?; let dim = self.next()?; - let _is_depth = self.next()?; + let is_depth = self.next()?; let is_array = self.next()? != 0; let is_msaa = self.next()? != 0; let _is_sampled = self.next()?; @@ -4740,7 +4740,9 @@ impl> Frontend { .ok_or(Error::InvalidImageBaseType(base_handle))?; let inner = crate::TypeInner::Image { - class: if format != 0 { + class: if is_depth == 1 { + crate::ImageClass::Depth { multi: is_msaa } + } else if format != 0 { crate::ImageClass::Storage { format: map_image_format(format)?, access: crate::StorageAccess::default(), diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 54731d00e..bff3013e0 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -90,9 +90,6 @@ ( bits: 64, ), - ( - bits: 64, - ), ], functions: [ ( @@ -190,7 +187,7 @@ ), ref_count: 1, assignable_global: Some(1), - ty: Handle(30), + ty: Handle(7), ), ( uniformity: ( @@ -201,7 +198,7 @@ ), ref_count: 1, assignable_global: Some(2), - ty: Handle(31), + ty: Handle(30), ), ( uniformity: ( @@ -1256,7 +1253,7 @@ ), ref_count: 0, assignable_global: Some(1), - ty: Handle(30), + ty: Handle(7), ), ( uniformity: ( @@ -1267,7 +1264,7 @@ ), ref_count: 0, assignable_global: Some(2), - ty: Handle(31), + ty: Handle(30), ), ( uniformity: ( diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 9311f9e18..76f4f0527 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -50,8 +50,7 @@ inner: Image( dim: D2, arrayed: true, - class: Sampled( - kind: Float, + class: Depth( multi: false, ), ), @@ -269,16 +268,6 @@ space: Private, ), ), - ( - name: None, - inner: Image( - dim: D2, - arrayed: true, - class: Depth( - multi: false, - ), - ), - ), ( name: None, inner: Sampler( @@ -616,7 +605,7 @@ group: 0, binding: 2, )), - ty: 30, + ty: 7, init: None, ), ( @@ -626,7 +615,7 @@ group: 0, binding: 3, )), - ty: 31, + ty: 30, init: None, ), ( From 4b41e07a9922d511ed4e288067e066b04caede20 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Wed, 24 May 2023 11:23:24 -0400 Subject: [PATCH 2002/2212] refactor: add several `clippy` lints (#2296) --- src/lib.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index e0645a30f..26e0eaf38 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -215,7 +215,17 @@ tree. clippy::rest_pat_in_fully_bound_structs, clippy::match_wildcard_for_single_variants )] -#![cfg_attr(not(test), deny(clippy::panic))] +#![deny(clippy::exit)] +#![cfg_attr( + not(test), + warn( + clippy::dbg_macro, + clippy::panic, + clippy::print_stderr, + clippy::print_stdout, + clippy::todo + ) +)] mod arena; pub mod back; From 201c0e2999c7c47eeecd880bf4425b577223e892 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 25 May 2023 04:06:21 -0700 Subject: [PATCH 2003/2212] [spv-in] Improve documentation for SPIR-V control flow parsing. (#2324) --- src/front/spv/mod.rs | 95 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 78 insertions(+), 17 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 55a5cc57c..a1b973886 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -386,7 +386,12 @@ enum BodyFragment { reject: BodyIndex, }, Loop { + /// The body of the loop. Its [`Body::parent`] is the block containing + /// this `Loop` fragment. body: BodyIndex, + + /// The loop's continuing block. This is a grandchild: its + /// [`Body::parent`] is the loop body block, whose index is above. continuing: BodyIndex, /// If the SPIR-V loop's back-edge branch is conditional, this is the @@ -445,9 +450,17 @@ enum MergeBlockInformation { /// Fragments of Naga IR, to be assembled into `Statements` once data flow is /// resolved. /// -/// We can't build a Naga `Statement` tree directly from SPIR-V blocks for two +/// We can't build a Naga `Statement` tree directly from SPIR-V blocks for three /// main reasons: /// +/// - We parse a function's SPIR-V blocks in the order they appear in the file. +/// Within a function, SPIR-V requires that a block must precede any blocks it +/// structurally dominates, but doesn't say much else about the order in which +/// they must appear. So while we know we'll see control flow header blocks +/// before their child constructs and merge blocks, those children and the +/// merge blocks may appear in any order - perhaps even intermingled with +/// children of other constructs. +/// /// - A SPIR-V expression can be used in any SPIR-V block dominated by its /// definition, whereas Naga expressions are scoped to the rest of their /// subtree. This means that discovering an expression use later in the @@ -457,7 +470,7 @@ enum MergeBlockInformation { /// - We translate SPIR-V OpPhi expressions as Naga local variables in which we /// store the appropriate value before jumping to the OpPhi's block. /// -/// Both cases require us to go back and amend previously generated Naga IR +/// All these cases require us to go back and amend previously generated Naga IR /// based on things we discover later. But modifying old blocks in arbitrary /// spots in a `Statement` tree is awkward. /// @@ -482,18 +495,37 @@ struct BlockContext<'function> { /// Fragments of control-flow-free Naga IR. /// - /// These will be stitched together into a proper `Statement` tree according + /// These will be stitched together into a proper [`Statement`] tree according /// to `bodies`, once parsing is complete. + /// + /// [`Statement`]: crate::Statement blocks: FastHashMap, - /// Map from block label ids to the index of the corresponding `Body` in - /// `bodies`. + /// Map from each SPIR-V block's label id to the index of the [`Body`] in + /// [`bodies`] the block should append its contents to. + /// + /// Since each statement in a Naga [`Block`] dominates the next, we are sure + /// to encounter their SPIR-V blocks in order. Thus, by having this table + /// map a SPIR-V structured control flow construct's merge block to the same + /// body index as its header block, when we encounter the merge block, we + /// will simply pick up building the [`Body`] where the header left off. + /// + /// A function's first block is special: it is the only block we encounter + /// without having seen its label mentioned in advance. (It's simply the + /// first `OpLabel` after the `OpFunction`.) We thus assume that any block + /// missing an entry here must be the first block, which always has body + /// index zero. + /// + /// [`bodies`]: BlockContext::bodies + /// [`Block`]: crate::Block body_for_label: FastHashMap, /// SPIR-V metadata about merge/continue blocks. mergers: FastHashMap, /// A table of `Body` values, each representing a block in the final IR. + /// + /// The first element is always the function's top-level block. bodies: Vec, /// Id of the function currently being processed @@ -1264,10 +1296,26 @@ impl> Frontend { let mut emitter = super::Emitter::default(); emitter.start(ctx.expressions); - // Find the `Body` that this block belongs to. Index zero is the - // function's root `Body`, corresponding to `Function::body`. + // Find the `Body` to which this block contributes. + // + // If this is some SPIR-V structured control flow construct's merge + // block, then `body_idx` will refer to the same `Body` as the header, + // so that we simply pick up accumulating the `Body` where the header + // left off. Each of the statements in a block dominates the next, so + // we're sure to encounter their SPIR-V blocks in order, ensuring that + // the `Body` will be assembled in the proper order. + // + // Note that, unlike every other kind of SPIR-V block, we don't know the + // function's first block's label in advance. Thus, we assume that if + // this block has no entry in `ctx.body_for_label`, it must be the + // function's first block. This always has body index zero. let mut body_idx = *ctx.body_for_label.entry(block_id).or_default(); + + // The Naga IR block this call builds. This will end up as + // `ctx.blocks[&block_id]`, and `ctx.bodies[body_idx]` will refer to it + // via a `BodyFragment::BlockId`. let mut block = crate::Block::new(); + // Stores the merge block as defined by a `OpSelectionMerge` otherwise is `None` // // This is used in `OpSwitch` to promote the `MergeBlockInformation` from @@ -3086,8 +3134,14 @@ impl> Frontend { inst.expect(2)?; let target_id = self.next()?; - // If this is a branch to a merge or continue block, - // then that ends the current body. + // If this is a branch to a merge or continue block, then + // that ends the current body. + // + // Why can we count on finding an entry here when it's + // needed? SPIR-V requires dominators to appear before + // blocks they dominate, so we will have visited a + // structured control construct's header block before + // anything that could exit it. if let Some(info) = ctx.mergers.get(&target_id) { block.extend(emitter.finish(ctx.expressions)); ctx.blocks.insert(block_id, block); @@ -3099,15 +3153,22 @@ impl> Frontend { return Ok(()); } - // Since the target of the branch has no merge information, - // this must be the only branch to that block. This means - // we can treat it as an extension of the current `Body`. + // If `target_id` has no entry in `ctx.body_for_label`, then + // this must be the only branch to it: // - // NOTE: it's possible that another branch was already made to this block - // setting the body index in which case it SHOULD NOT be overridden. - // For example a switch with falltrough, the OpSwitch will set the body to - // the respective case and the case may branch to another case in which case - // the body index shouldn't be changed + // - We've already established that it's not anybody's merge + // block. + // + // - It can't be a switch case. Only switch header blocks + // and other switch cases can branch to a switch case. + // Switch header blocks must dominate all their cases, so + // they must appear in the file before them, and when we + // see `Op::Switch` we populate `ctx.body_for_label` for + // every switch case. + // + // Thus, `target_id` must be a simple extension of the + // current block, which we dominate, so we know we'll + // encounter it later in the file. ctx.body_for_label.entry(target_id).or_insert(body_idx); break None; From baed251cb12e0c1ab433d006da39328aa9608991 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 25 May 2023 04:08:24 -0700 Subject: [PATCH 2004/2212] Document which expressions are in scope for a `break_if` expression. (#2326) --- src/lib.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 26e0eaf38..32210ac95 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1626,14 +1626,16 @@ pub enum Statement { /// The `continuing` block and its substatements must not contain `Return` /// or `Kill` statements, or any `Break` or `Continue` statements targeting /// this loop. (It may have `Break` and `Continue` statements targeting - /// loops or switches nested within the `continuing` block.) + /// loops or switches nested within the `continuing` block.) Expressions + /// emitted in `body` are in scope in `continuing`. /// /// If present, `break_if` is an expression which is evaluated after the - /// continuing block. If its value is true, control continues after the - /// `Loop` statement, rather than branching back to the top of body as - /// usual. The `break_if` expression corresponds to a "break if" statement - /// in WGSL, or a loop whose back edge is an `OpBranchConditional` - /// instruction in SPIR-V. + /// continuing block. Expressions emitted in `body` or `continuing` are + /// considered to be in scope. If the expression's value is true, control + /// continues after the `Loop` statement, rather than branching back to the + /// top of body as usual. The `break_if` expression corresponds to a "break + /// if" statement in WGSL, or a loop whose back edge is an + /// `OpBranchConditional` instruction in SPIR-V. /// /// [`Break`]: Statement::Break /// [`Continue`]: Statement::Continue From 1c17fa82d4a8f4b2c596f7abbe4dd9e4f1ad18a8 Mon Sep 17 00:00:00 2001 From: Shaye Garg <64652557+SparkyPotato@users.noreply.github.com> Date: Thu, 25 May 2023 16:43:27 +0530 Subject: [PATCH 2005/2212] [wgsl-in] Error on param redefinition (#2342) * error on param redefinition * also fix #2312 --- src/front/wgsl/parse/mod.rs | 52 +++++++++++++++++------------- tests/in/lexical-scopes.wgsl | 26 +++++++-------- tests/out/wgsl/lexical-scopes.wgsl | 25 +++++++------- tests/wgsl-errors.rs | 38 ++++++++++++++++++++++ 4 files changed, 91 insertions(+), 50 deletions(-) diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index cf9892a1f..8e7abed70 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -84,6 +84,18 @@ impl<'a> ExpressionContext<'a, '_, '_> { } Ok(accumulator) } + + fn declare_local(&mut self, name: ast::Ident<'a>) -> Result, Error<'a>> { + let handle = self.locals.append(ast::Local, name.span); + if let Some(old) = self.local_table.add(name.name, handle) { + Err(Error::Redefinition { + previous: self.locals.get_span(old), + current: name.span, + }) + } else { + Ok(handle) + } + } } /// Which grammar rule we are in the midst of parsing. @@ -1612,14 +1624,7 @@ impl Parser { let expr_id = self.general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Separator(';'))?; - let handle = ctx.locals.append(ast::Local, name.span); - if let Some(old) = ctx.local_table.add(name.name, handle) { - return Err(Error::Redefinition { - previous: ctx.locals.get_span(old), - current: name.span, - }); - } - + let handle = ctx.declare_local(name)?; ast::StatementKind::LocalDecl(ast::LocalDecl::Let(ast::Let { name, ty: given_ty, @@ -1647,14 +1652,7 @@ impl Parser { lexer.expect(Token::Separator(';'))?; - let handle = ctx.locals.append(ast::Local, name.span); - if let Some(old) = ctx.local_table.add(name.name, handle) { - return Err(Error::Redefinition { - previous: ctx.locals.get_span(old), - current: name.span, - }); - } - + let handle = ctx.declare_local(name)?; ast::StatementKind::LocalDecl(ast::LocalDecl::Var(ast::LocalVariable { name, ty, @@ -2013,15 +2011,15 @@ impl Parser { ctx.local_table.push_scope(); lexer.expect(Token::Paren('{'))?; - let mut statements = ast::Block::default(); + let mut block = ast::Block::default(); while !lexer.skip(Token::Paren('}')) { - self.statement(lexer, ctx.reborrow(), &mut statements)?; + self.statement(lexer, ctx.reborrow(), &mut block)?; } ctx.local_table.pop_scope(); let span = self.pop_rule_span(lexer); - Ok((statements, span)) + Ok((block, span)) } fn varying_binding<'a>( @@ -2060,6 +2058,9 @@ impl Parser { unresolved: dependencies, }; + // start a scope that contains arguments as well as the function body + ctx.local_table.push_scope(); + // read parameter list let mut arguments = Vec::new(); lexer.expect(Token::Paren('('))?; @@ -2078,8 +2079,7 @@ impl Parser { lexer.expect(Token::Separator(':'))?; let param_type = self.type_decl(lexer, ctx.reborrow())?; - let handle = ctx.locals.append(ast::Local, param_name.span); - ctx.local_table.add(param_name.name, handle); + let handle = ctx.declare_local(param_name)?; arguments.push(ast::FunctionArgument { name: param_name, ty: param_type, @@ -2097,8 +2097,14 @@ impl Parser { None }; - // read body - let body = self.block(lexer, ctx)?.0; + // do not use `self.block` here, since we must not push a new scope + lexer.expect(Token::Paren('{'))?; + let mut body = ast::Block::default(); + while !lexer.skip(Token::Paren('}')) { + self.statement(lexer, ctx.reborrow(), &mut body)?; + } + + ctx.local_table.pop_scope(); let fun = ast::Function { entry_point: None, diff --git a/tests/in/lexical-scopes.wgsl b/tests/in/lexical-scopes.wgsl index 70a18a488..9aee919d3 100644 --- a/tests/in/lexical-scopes.wgsl +++ b/tests/in/lexical-scopes.wgsl @@ -1,45 +1,41 @@ fn blockLexicalScope(a: bool) { - let a = 1.0; { let a = 2; { - let a = true; + let a = 2.0; } - let test = a == 3; + let test: i32 = a; } - let test = a == 2.0; + let test: bool = a; } fn ifLexicalScope(a: bool) { - let a = 1.0; - if (a == 1.0) { - let a = true; + if (a) { + let a = 2.0; } - let test = a == 2.0; + let test: bool = a; } fn loopLexicalScope(a: bool) { - let a = 1.0; loop { - let a = true; + let a = 2.0; } - let test = a == 2.0; + let test: bool = a; } fn forLexicalScope(a: f32) { - let a = false; for (var a = 0; a < 1; a++) { - let a = 3.0; + let a = true; } - let test = a == true; + let test: f32 = a; } fn whileLexicalScope(a: i32) { while (a > 2) { let a = false; } - let test = a == 1; + let test: i32 = a; } fn switchLexicalScope(a: i32) { diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/tests/out/wgsl/lexical-scopes.wgsl index 3d645f5ae..d44f6679f 100644 --- a/tests/out/wgsl/lexical-scopes.wgsl +++ b/tests/out/wgsl/lexical-scopes.wgsl @@ -1,22 +1,23 @@ fn blockLexicalScope(a: bool) { { { + return; } - let test = (2 == 3); } - let test_1 = (1.0 == 2.0); } fn ifLexicalScope(a_1: bool) { - if (1.0 == 1.0) { + if a_1 { + return; + } else { + return; } - let test_2 = (1.0 == 2.0); } fn loopLexicalScope(a_2: bool) { loop { } - let test_3 = (1.0 == 2.0); + return; } fn forLexicalScope(a_3: f32) { @@ -24,19 +25,19 @@ fn forLexicalScope(a_3: f32) { a_4 = 0; loop { - let _e4 = a_4; - if (_e4 < 1) { + let _e3 = a_4; + if (_e3 < 1) { } else { break; } { } continuing { - let _e8 = a_4; - a_4 = (_e8 + 1); + let _e7 = a_4; + a_4 = (_e7 + 1); } } - let test_4 = (false == true); + return; } fn whileLexicalScope(a_5: i32) { @@ -48,7 +49,7 @@ fn whileLexicalScope(a_5: i32) { { } } - let test_5 = (a_5 == 1); + return; } fn switchLexicalScope(a_6: i32) { @@ -60,6 +61,6 @@ fn switchLexicalScope(a_6: i32) { default: { } } - let test_6 = (a_6 == 2); + let test = (a_6 == 2); } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 369ff4a4d..9ae76837e 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1883,6 +1883,44 @@ fn function_returns_void() { ) } +#[test] +fn function_param_redefinition_as_param() { + check( + " + fn x(a: f32, a: vec2) {} + ", + r###"error: redefinition of `a` + ┌─ wgsl:2:14 + │ +2 │ fn x(a: f32, a: vec2) {} + │ ^ ^ redefinition of `a` + │ │ + │ previous definition of `a` + +"###, + ) +} + +#[test] +fn function_param_redefinition_as_local() { + check( + " + fn x(a: f32) { + let a = 0.0; + } + ", + r###"error: redefinition of `a` + ┌─ wgsl:2:14 + │ +2 │ fn x(a: f32) { + │ ^ previous definition of `a` +3 │ let a = 0.0; + │ ^ redefinition of `a` + +"###, + ) +} + #[test] fn binding_array_local() { check_validation! { From 907b7c7cda2447f2869820a27b8f331d7c512fab Mon Sep 17 00:00:00 2001 From: Daniel McNab <36049421+DJMcNab@users.noreply.github.com> Date: Fri, 26 May 2023 21:32:22 +0100 Subject: [PATCH 2006/2212] Workgroup uniform load (#2201) Implement the WGSL `workgroupUniformLoad` function. --- src/back/dot/mod.rs | 6 ++ src/back/glsl/mod.rs | 27 ++++++-- src/back/hlsl/writer.rs | 20 ++++-- src/back/msl/writer.rs | 13 ++++ src/back/spv/block.rs | 41 ++++++++++++ src/back/wgsl/writer.rs | 13 +++- src/front/glsl/constants.rs | 1 + src/front/spv/mod.rs | 1 + src/front/wgsl/error.rs | 6 ++ src/front/wgsl/lower/mod.rs | 30 +++++++++ src/lib.rs | 22 +++++++ src/proc/terminator.rs | 1 + src/proc/typifier.rs | 1 + src/valid/analyzer.rs | 36 ++++++++++ src/valid/expression.rs | 17 ++++- src/valid/function.rs | 47 ++++++++++++- src/valid/handles.rs | 9 ++- tests/in/workgroup-uniform-load.wgsl | 12 ++++ ...oad.test_workgroupUniformLoad.Compute.glsl | 31 +++++++++ tests/out/hlsl/workgroup-uniform-load.hlsl | 21 ++++++ .../hlsl/workgroup-uniform-load.hlsl.config | 3 + tests/out/msl/workgroup-uniform-load.msl | 32 +++++++++ tests/out/spv/workgroup-uniform-load.spvasm | 66 +++++++++++++++++++ tests/out/wgsl/workgroup-uniform-load.wgsl | 15 +++++ tests/snapshots.rs | 4 ++ 25 files changed, 462 insertions(+), 13 deletions(-) create mode 100644 tests/in/workgroup-uniform-load.wgsl create mode 100644 tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl create mode 100644 tests/out/hlsl/workgroup-uniform-load.hlsl create mode 100644 tests/out/hlsl/workgroup-uniform-load.hlsl.config create mode 100644 tests/out/msl/workgroup-uniform-load.msl create mode 100644 tests/out/spv/workgroup-uniform-load.spvasm create mode 100644 tests/out/wgsl/workgroup-uniform-load.wgsl diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 1494e9a82..85f382d26 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -252,6 +252,11 @@ impl StatementGraph { } "Atomic" } + S::WorkGroupUniformLoad { pointer, result } => { + self.emits.push((id, result)); + self.dependencies.push((id, pointer, "pointer")); + "WorkGroupUniformLoad" + } S::RayQuery { query, ref fun } => { self.dependencies.push((id, query, "query")); match *fun { @@ -570,6 +575,7 @@ fn write_function_expressions( } E::CallResult(_function) => ("CallResult".into(), 4), E::AtomicResult { .. } => ("AtomicResult".into(), 4), + E::WorkGroupUniformLoadResult { .. } => ("WorkGroupUniformLoadResult".into(), 4), E::ArrayLength(expr) => { edges.insert("", expr); ("ArrayLength".into(), 7) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 030ec2191..d6aff795c 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1824,7 +1824,7 @@ impl<'a, W: Write> Writer<'a, W> { if let Some(name) = expr_name { write!(self.out, "{level}")?; - self.write_named_expr(handle, name, ctx)?; + self.write_named_expr(handle, name, handle, ctx)?; } } } @@ -2114,6 +2114,19 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(value, ctx)?; writeln!(self.out, ";")? } + Statement::WorkGroupUniformLoad { pointer, result } => { + // GLSL doesn't have pointers, which means that this backend needs to ensure that + // the actual "loading" is happening between the two barriers. + // This is done in `Emit` by never emitting a variable name for pointer variables + self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + + let result_name = format!("{}{}", back::BAKE_PREFIX, result.index()); + write!(self.out, "{level}")?; + // Expressions cannot have side effects, so just writing the expression here is fine. + self.write_named_expr(pointer, result_name, result, ctx)?; + + self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + } // Stores a value into an image. Statement::ImageStore { image, @@ -3289,7 +3302,8 @@ impl<'a, W: Write> Writer<'a, W> { // These expressions never show up in `Emit`. Expression::CallResult(_) | Expression::AtomicResult { .. } - | Expression::RayQueryProceedResult => unreachable!(), + | Expression::RayQueryProceedResult + | Expression::WorkGroupUniformLoadResult { .. } => unreachable!(), // `ArrayLength` is written as `expr.length()` and we convert it to a uint Expression::ArrayLength(expr) => { write!(self.out, "uint(")?; @@ -3725,9 +3739,12 @@ impl<'a, W: Write> Writer<'a, W> { &mut self, handle: Handle, name: String, + // The expression which is being named. + // Generally, this is the same as handle, except in WorkGroupUniformLoad + named: Handle, ctx: &back::FunctionCtx, ) -> BackendResult { - match ctx.info[handle].ty { + match ctx.info[named].ty { proc::TypeResolution::Handle(ty_handle) => match self.module.types[ty_handle].inner { TypeInner::Struct { .. } => { let ty_name = &self.names[&NameKey::Type(ty_handle)]; @@ -3742,7 +3759,7 @@ impl<'a, W: Write> Writer<'a, W> { } } - let base_ty_res = &ctx.info[handle].ty; + let base_ty_res = &ctx.info[named].ty; let resolved = base_ty_res.inner_with(&self.module.types); write!(self.out, " {name}")?; @@ -3752,7 +3769,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, " = ")?; self.write_expr(handle, ctx)?; writeln!(self.out, ";")?; - self.named_expressions.insert(handle, name); + self.named_expressions.insert(named, name); Ok(()) } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 007da0d09..0b08dbe0a 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1338,7 +1338,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if let Some(name) = expr_name { write!(self.out, "{level}")?; - self.write_named_expr(module, handle, name, func_ctx)?; + self.write_named_expr(module, handle, name, handle, func_ctx)?; } } } @@ -1899,6 +1899,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, ", {res_name});")?; self.named_expressions.insert(result, res_name); } + Statement::WorkGroupUniformLoad { pointer, result } => { + self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + write!(self.out, "{level}")?; + let name = format!("_expr{}", result.index()); + self.write_named_expr(module, pointer, name, result, func_ctx)?; + + self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + } Statement::Switch { selector, ref cases, @@ -2933,6 +2941,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Nothing to do here, since call expression already cached Expression::CallResult(_) | Expression::AtomicResult { .. } + | Expression::WorkGroupUniformLoadResult { .. } | Expression::RayQueryProceedResult => {} } @@ -3023,9 +3032,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { module: &Module, handle: Handle, name: String, + // The expression which is being named. + // Generally, this is the same as handle, except in WorkGroupUniformLoad + named: Handle, ctx: &back::FunctionCtx, ) -> BackendResult { - match ctx.info[handle].ty { + match ctx.info[named].ty { proc::TypeResolution::Handle(ty_handle) => match module.types[ty_handle].inner { TypeInner::Struct { .. } => { let ty_name = &self.names[&NameKey::Type(ty_handle)]; @@ -3040,7 +3052,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - let base_ty_res = &ctx.info[handle].ty; + let base_ty_res = &ctx.info[named].ty; let resolved = base_ty_res.inner_with(&module.types); write!(self.out, " {name}")?; @@ -3051,7 +3063,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, " = ")?; self.write_expr(module, handle, ctx)?; writeln!(self.out, ";")?; - self.named_expressions.insert(handle, name); + self.named_expressions.insert(named, name); Ok(()) } diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 2123d0c30..07a79f749 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1880,6 +1880,7 @@ impl Writer { // has to be a named expression crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } + | crate::Expression::WorkGroupUniformLoadResult { .. } | crate::Expression::RayQueryProceedResult => { unreachable!() } @@ -2842,6 +2843,18 @@ impl Writer { // done writeln!(self.out, ";")?; } + crate::Statement::WorkGroupUniformLoad { pointer, result } => { + self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + + write!(self.out, "{level}")?; + let name = self.namer.call(""); + self.start_baking_expression(result, &context.expression, &name)?; + self.put_load(pointer, &context.expression, true)?; + self.named_expressions.insert(result, name); + + writeln!(self.out, ";")?; + self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + } crate::Statement::RayQuery { query, ref fun } => { match *fun { crate::RayQueryFunction::Initialize { diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index be5fa5da0..1ba61ad39 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1089,6 +1089,7 @@ impl<'w> BlockContext<'w> { crate::Expression::FunctionArgument(index) => self.function.parameter_id(index), crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } + | crate::Expression::WorkGroupUniformLoadResult { .. } | crate::Expression::RayQueryProceedResult => self.cached[expr_handle], crate::Expression::As { expr, @@ -2209,6 +2210,46 @@ impl<'w> BlockContext<'w> { block.body.push(instruction); } + crate::Statement::WorkGroupUniformLoad { pointer, result } => { + self.writer + .write_barrier(crate::Barrier::WORK_GROUP, &mut block); + let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty); + // Embed the body of + match self.write_expression_pointer(pointer, &mut block, None)? { + ExpressionPointer::Ready { pointer_id } => { + let id = self.gen_id(); + block.body.push(Instruction::load( + result_type_id, + id, + pointer_id, + None, + )); + self.cached[result] = id; + } + ExpressionPointer::Conditional { condition, access } => { + self.cached[result] = self.write_conditional_indexed_load( + result_type_id, + condition, + &mut block, + move |id_gen, block| { + // The in-bounds path. Perform the access and the load. + let pointer_id = access.result_id.unwrap(); + let value_id = id_gen.next(); + block.body.push(access); + block.body.push(Instruction::load( + result_type_id, + value_id, + pointer_id, + None, + )); + value_id + }, + ) + } + } + self.writer + .write_barrier(crate::Barrier::WORK_GROUP, &mut block); + } crate::Statement::RayQuery { query, ref fun } => { self.write_ray_query_function(query, fun, &mut block); } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 2c2bb34e6..da9f605fe 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -780,6 +780,16 @@ impl Writer { self.write_expr(module, value, func_ctx)?; writeln!(self.out, ");")? } + Statement::WorkGroupUniformLoad { pointer, result } => { + write!(self.out, "{level}")?; + // TODO: Obey named expressions here. + let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); + self.start_named_expr(module, result, func_ctx, &res_name)?; + self.named_expressions.insert(result, res_name); + write!(self.out, "workgroupUniformLoad(")?; + self.write_expr(module, pointer, func_ctx)?; + writeln!(self.out, ");")?; + } Statement::ImageStore { image, coordinate, @@ -1633,7 +1643,8 @@ impl Writer { // Nothing to do here, since call expression already cached Expression::CallResult(_) | Expression::AtomicResult { .. } - | Expression::RayQueryProceedResult => {} + | Expression::RayQueryProceedResult + | Expression::WorkGroupUniformLoadResult { .. } => {} } Ok(()) diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index af3cc5396..35569926c 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -299,6 +299,7 @@ impl<'a> ConstantSolver<'a> { Expression::Derivative { .. } => Err(ConstantSolvingError::Derivative), Expression::Relational { .. } => Err(ConstantSolvingError::Relational), Expression::CallResult { .. } => Err(ConstantSolvingError::Call), + Expression::WorkGroupUniformLoadResult { .. } => unreachable!(), Expression::AtomicResult { .. } => Err(ConstantSolvingError::Atomic), Expression::FunctionArgument(_) => Err(ConstantSolvingError::FunctionArg), Expression::GlobalVariable(_) => Err(ConstantSolvingError::GlobalVariable), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a1b973886..dbab5bb00 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -3845,6 +3845,7 @@ impl> Frontend { } } } + S::WorkGroupUniformLoad { .. } => unreachable!(), } i += 1; } diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index ed3e5318b..dc9a3b178 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -239,6 +239,7 @@ pub enum Error<'a> { found: u32, }, FunctionReturnsVoid(Span), + InvalidWorkGroupUniformLoad(Span), Other, ExpectedArraySize(Span), NonPositiveArrayLength(Span), @@ -682,6 +683,11 @@ impl<'a> Error<'a> { "perhaps you meant to call the function in a separate statement?".into(), ], }, + Error::InvalidWorkGroupUniformLoad(span) => ParseError { + message: "incorrect type passed to workgroupUniformLoad".into(), + labels: vec![(span, "".into())], + notes: vec!["passed type must be a workgroup pointer".into()], + }, Error::Other => ParseError { message: "other error".to_string(), labels: vec![], diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index fc3f6a136..0de078353 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1691,6 +1691,36 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP), span); return Ok(None); } + "workgroupUniformLoad" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let expr = args.next()?; + args.finish()?; + + let pointer = self.expression(expr, ctx.reborrow())?; + ctx.grow_types(pointer)?; + let result_ty = match *ctx.resolved_inner(pointer) { + crate::TypeInner::Pointer { + base, + space: crate::AddressSpace::WorkGroup, + } => base, + ref other => { + log::error!("Type {other:?} passed to workgroupUniformLoad"); + let span = ctx.ast_expressions.get_span(expr); + return Err(Error::InvalidWorkGroupUniformLoad(span)); + } + }; + let result = ctx.interrupt_emitter( + crate::Expression::WorkGroupUniformLoadResult { ty: result_ty }, + span, + ); + ctx.block.push( + crate::Statement::WorkGroupUniformLoad { pointer, result }, + span, + ); + + ctx.grow_types(pointer)?; + return Ok(Some(result)); + } "textureStore" => { let mut args = ctx.prepare_args(arguments, 3, span); diff --git a/src/lib.rs b/src/lib.rs index 32210ac95..2d4c3b338 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1473,6 +1473,13 @@ pub enum Expression { CallResult(Handle), /// Result of an atomic operation. AtomicResult { ty: Handle, comparison: bool }, + /// Result of a [`WorkGroupUniformLoad`] statement. + /// + /// [`WorkGroupUniformLoad`]: Statement::WorkGroupUniformLoad + WorkGroupUniformLoadResult { + /// The type of the result + ty: Handle, + }, /// Get the length of an array. /// The expression must resolve to a pointer to an array with a dynamic size. /// @@ -1732,6 +1739,21 @@ pub enum Statement { /// [`AtomicResult`]: crate::Expression::AtomicResult result: Handle, }, + /// Load uniformly from a uniform pointer in the workgroup address space. + /// + /// Corresponds to the [`workgroupUniformLoad`](https://www.w3.org/TR/WGSL/#workgroupUniformLoad-builtin) + /// built-in function of wgsl, and has the same barrier semantics + WorkGroupUniformLoad { + /// This must be of type [`Pointer`] in the [`WorkGroup`] address space + /// + /// [`Pointer`]: TypeInner::Pointer + /// [`WorkGroup`]: AddressSpace::WorkGroup + pointer: Handle, + /// The [`WorkGroupUniformLoadResult`] expression representing this load's result. + /// + /// [`WorkGroupUniformLoadResult`]: Expression::WorkGroupUniformLoadResult + result: Handle, + }, /// Calls a function. /// /// If the `result` is `Some`, the corresponding expression has to be diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs index ca0c3f10b..a5239d4ec 100644 --- a/src/proc/terminator.rs +++ b/src/proc/terminator.rs @@ -36,6 +36,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) { | S::Call { .. } | S::RayQuery { .. } | S::Atomic { .. } + | S::WorkGroupUniformLoad { .. } | S::Barrier(_)), ) | None => block.push(S::Return { value: None }, Default::default()), diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 2345cccf8..f0030f340 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -658,6 +658,7 @@ impl<'a> ResolveContext<'a> { | crate::BinaryOperator::ShiftRight => past(left)?.clone(), }, crate::Expression::AtomicResult { ty, .. } => TypeResolution::Handle(ty), + crate::Expression::WorkGroupUniformLoadResult { ty } => TypeResolution::Handle(ty), crate::Expression::Select { accept, .. } => past(accept)?.clone(), crate::Expression::Derivative { expr, .. } => past(expr)?.clone(), crate::Expression::Relational { fun, argument } => match fun { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index b93f444a9..e3ada109c 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -690,6 +690,13 @@ impl FunctionInfo { non_uniform_result: Some(handle), requirements: UniformityRequirements::empty(), }, + E::WorkGroupUniformLoadResult { .. } => Uniformity { + // The result of WorkGroupUniformLoad is always uniform by definition + non_uniform_result: None, + // The call is what cares about uniformity, not the expression + // This expression is never emitted, so this requirement should never be used anyway? + requirements: UniformityRequirements::empty(), + }, E::ArrayLength(expr) => Uniformity { non_uniform_result: self.add_ref_impl(expr, GlobalUse::QUERY), requirements: UniformityRequirements::empty(), @@ -776,6 +783,35 @@ impl FunctionInfo { }, exit: ExitFlags::empty(), }, + S::WorkGroupUniformLoad { pointer, .. } => { + let _condition_nur = self.add_ref(pointer); + + // Don't check that this call occurs in uniform control flow until Naga implements WGSL's standard + // uniformity analysis (https://github.com/gfx-rs/naga/issues/1744). + // The uniformity analysis Naga uses now is less accurate than the one in the WGSL standard, + // causing Naga to reject correct uses of `workgroupUniformLoad` in some interesting programs. + + /* #[cfg(feature = "validate")] + if self + .flags + .contains(super::ValidationFlags::CONTROL_FLOW_UNIFORMITY) + { + let condition_nur = self.add_ref(pointer); + let this_disruptor = + disruptor.or(condition_nur.map(UniformityDisruptor::Expression)); + if let Some(cause) = this_disruptor { + return Err(FunctionError::NonUniformWorkgroupUniformLoad(cause) + .with_span_static(*span, "WorkGroupUniformLoad")); + } + } */ + FunctionUniformity { + result: Uniformity { + non_uniform_result: None, + requirements: UniformityRequirements::WORK_GROUP_BARRIER, + }, + exit: ExitFlags::empty(), + } + } S::Block(ref b) => { self.process_block(b, other_functions, disruptor, expression_arena)? } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index eb39a84ea..0cf40c232 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,4 +1,3 @@ -#[cfg(feature = "validate")] use std::ops::Index; #[cfg(feature = "validate")] @@ -119,6 +118,10 @@ pub enum ExpressionError { InvalidArgumentType(crate::MathFunction, u32, Handle), #[error("Atomic result type can't be {0:?}")] InvalidAtomicResultType(Handle), + #[error( + "workgroupUniformLoad result type can't be {0:?}. It can only be a constructible type." + )] + InvalidWorkGroupUniformLoadResultType(Handle), #[error("Shader requires capability {0:?}")] MissingCapabilities(super::Capabilities), } @@ -1412,6 +1415,18 @@ impl super::Validator { } ShaderStages::all() } + E::WorkGroupUniformLoadResult { ty } => { + if self.types[ty.index()] + .flags + // Sized | Constructible is exactly the types currently supported by + // WorkGroupUniformLoad + .contains(TypeFlags::SIZED | TypeFlags::CONSTRUCTIBLE) + { + ShaderStages::COMPUTE + } else { + return Err(ExpressionError::InvalidWorkGroupUniformLoadResultType(ty)); + } + } E::ArrayLength(expr) => match resolver[expr] { Ti::Pointer { base, .. } => { let base_ty = &resolver.types[base]; diff --git a/src/valid/function.rs b/src/valid/function.rs index c18f86555..280ca06c6 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -149,6 +149,14 @@ pub enum FunctionError { PipelineInputRegularFunction { name: String }, #[error("Functions that are not entry points cannot have `@location` or `@builtin` attributes on their return value types")] PipelineOutputRegularFunction, + #[error("Required uniformity for WorkGroupUniformLoad is not fulfilled because of {0:?}")] + // The actual load statement will be "pointed to" by the span + NonUniformWorkgroupUniformLoad(UniformityDisruptor), + // This is only possible with a misbehaving frontend + #[error("The expression {0:?} for a WorkGroupUniformLoad isn't a WorkgroupUniformLoadResult")] + WorkgroupUniformLoadExpressionMismatch(Handle), + #[error("The expression {0:?} is not valid as a WorkGroupUniformLoad argument. It should be a Pointer in Workgroup address space")] + WorkgroupUniformLoadInvalidPointer(Handle), } bitflags::bitflags! { @@ -409,7 +417,7 @@ impl super::Validator { statements: &crate::Block, context: &BlockContext, ) -> Result> { - use crate::{Statement as S, TypeInner as Ti}; + use crate::{AddressSpace, Statement as S, TypeInner as Ti}; let mut finished = false; let mut stages = super::ShaderStages::all(); for (statement, &span) in statements.span_iter() { @@ -821,6 +829,43 @@ impl super::Validator { } => { self.validate_atomic(pointer, fun, value, result, context)?; } + S::WorkGroupUniformLoad { pointer, result } => { + stages &= super::ShaderStages::COMPUTE; + let pointer_inner = + context.resolve_type(pointer, &self.valid_expression_set)?; + match *pointer_inner { + Ti::Pointer { + space: AddressSpace::WorkGroup, + .. + } => {} + Ti::ValuePointer { + space: AddressSpace::WorkGroup, + .. + } => {} + _ => { + return Err(FunctionError::WorkgroupUniformLoadInvalidPointer(pointer) + .with_span_static(span, "WorkGroupUniformLoad")) + } + } + self.emit_expression(result, context)?; + let ty = match &context.expressions[result] { + &crate::Expression::WorkGroupUniformLoadResult { ty } => ty, + _ => { + return Err(FunctionError::WorkgroupUniformLoadExpressionMismatch( + result, + ) + .with_span_static(span, "WorkGroupUniformLoad")); + } + }; + let expected_pointer_inner = Ti::Pointer { + base: ty, + space: AddressSpace::WorkGroup, + }; + if !expected_pointer_inner.equivalent(pointer_inner, context.types) { + return Err(FunctionError::WorkgroupUniformLoadInvalidPointer(pointer) + .with_span_static(span, "WorkGroupUniformLoad")); + } + } S::RayQuery { query, ref fun } => { let query_var = match *context.get_expression(query) { crate::Expression::LocalVariable(var) => &context.local_vars[var], diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 22dadaf60..2b0d10762 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -360,7 +360,9 @@ impl super::Validator { handle.check_dep(function)?; } } - crate::Expression::AtomicResult { .. } | crate::Expression::RayQueryProceedResult => (), + crate::Expression::AtomicResult { .. } + | crate::Expression::RayQueryProceedResult + | crate::Expression::WorkGroupUniformLoadResult { .. } => (), crate::Expression::ArrayLength(array) => { handle.check_dep(array)?; } @@ -471,6 +473,11 @@ impl super::Validator { validate_expr(result)?; Ok(()) } + crate::Statement::WorkGroupUniformLoad { pointer, result } => { + validate_expr(pointer)?; + validate_expr(result)?; + Ok(()) + } crate::Statement::Call { function, ref arguments, diff --git a/tests/in/workgroup-uniform-load.wgsl b/tests/in/workgroup-uniform-load.wgsl new file mode 100644 index 000000000..4b7f22a09 --- /dev/null +++ b/tests/in/workgroup-uniform-load.wgsl @@ -0,0 +1,12 @@ +const SIZE: u32 = 128u; + +var arr_i32: array; + +@compute @workgroup_size(4) +fn test_workgroupUniformLoad(@builtin(workgroup_id) workgroup_id: vec3) { + let x = &arr_i32[workgroup_id.x]; + let val = workgroupUniformLoad(x); + if val > 10 { + workgroupBarrier(); + } +} diff --git a/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl b/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl new file mode 100644 index 000000000..03857ec79 --- /dev/null +++ b/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl @@ -0,0 +1,31 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 4, local_size_y = 1, local_size_z = 1) in; + +shared int arr_i32_[128]; + + +void main() { + if (gl_LocalInvocationID == uvec3(0u)) { + arr_i32_ = int[128](0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + memoryBarrierShared(); + barrier(); + uvec3 workgroup_id = gl_WorkGroupID; + memoryBarrierShared(); + barrier(); + int _e4 = arr_i32_[workgroup_id.x]; + memoryBarrierShared(); + barrier(); + if ((_e4 > 10)) { + memoryBarrierShared(); + barrier(); + return; + } else { + return; + } +} + diff --git a/tests/out/hlsl/workgroup-uniform-load.hlsl b/tests/out/hlsl/workgroup-uniform-load.hlsl new file mode 100644 index 000000000..ad049461f --- /dev/null +++ b/tests/out/hlsl/workgroup-uniform-load.hlsl @@ -0,0 +1,21 @@ +static const uint SIZE = 128; + +groupshared int arr_i32_[128]; + +[numthreads(4, 1, 1)] +void test_workgroupUniformLoad(uint3 workgroup_id : SV_GroupID, uint3 __local_invocation_id : SV_GroupThreadID) +{ + if (all(__local_invocation_id == uint3(0u, 0u, 0u))) { + arr_i32_ = (int[128])0; + } + GroupMemoryBarrierWithGroupSync(); + GroupMemoryBarrierWithGroupSync(); + int _expr4 = arr_i32_[workgroup_id.x]; + GroupMemoryBarrierWithGroupSync(); + if ((_expr4 > 10)) { + GroupMemoryBarrierWithGroupSync(); + return; + } else { + return; + } +} diff --git a/tests/out/hlsl/workgroup-uniform-load.hlsl.config b/tests/out/hlsl/workgroup-uniform-load.hlsl.config new file mode 100644 index 000000000..648d3b0d9 --- /dev/null +++ b/tests/out/hlsl/workgroup-uniform-load.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(test_workgroupUniformLoad:cs_5_1 ) diff --git a/tests/out/msl/workgroup-uniform-load.msl b/tests/out/msl/workgroup-uniform-load.msl new file mode 100644 index 000000000..29df3fff4 --- /dev/null +++ b/tests/out/msl/workgroup-uniform-load.msl @@ -0,0 +1,32 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +constexpr constant unsigned SIZE = 128u; +struct type_2 { + int inner[SIZE]; +}; + +struct test_workgroupUniformLoadInput { +}; +kernel void test_workgroupUniformLoad( + metal::uint3 workgroup_id [[threadgroup_position_in_grid]] +, metal::uint3 __local_invocation_id [[thread_position_in_threadgroup]] +, threadgroup type_2& arr_i32_ +) { + if (metal::all(__local_invocation_id == metal::uint3(0u))) { + arr_i32_ = {}; + } + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + int unnamed = arr_i32_.inner[workgroup_id.x]; + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + if (unnamed > 10) { + metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + return; + } else { + return; + } +} diff --git a/tests/out/spv/workgroup-uniform-load.spvasm b/tests/out/spv/workgroup-uniform-load.spvasm new file mode 100644 index 000000000..8f30b48ac --- /dev/null +++ b/tests/out/spv/workgroup-uniform-load.spvasm @@ -0,0 +1,66 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 40 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %15 "test_workgroupUniformLoad" %12 %19 +OpExecutionMode %15 LocalSize 4 1 1 +OpDecorate %7 ArrayStride 4 +OpDecorate %12 BuiltIn WorkgroupId +OpDecorate %19 BuiltIn LocalInvocationId +%2 = OpTypeVoid +%4 = OpTypeInt 32 0 +%3 = OpConstant %4 128 +%6 = OpTypeInt 32 1 +%5 = OpConstant %6 10 +%7 = OpTypeArray %6 %3 +%8 = OpTypeVector %4 3 +%10 = OpTypePointer Workgroup %7 +%9 = OpVariable %10 Workgroup +%13 = OpTypePointer Input %8 +%12 = OpVariable %13 Input +%16 = OpTypeFunction %2 +%18 = OpConstantNull %7 +%20 = OpTypePointer Input %8 +%19 = OpVariable %20 Input +%22 = OpConstantNull %8 +%24 = OpTypeBool +%23 = OpTypeVector %24 3 +%29 = OpConstant %4 2 +%30 = OpConstant %4 264 +%33 = OpTypePointer Workgroup %6 +%15 = OpFunction %2 None %16 +%11 = OpLabel +%14 = OpLoad %8 %12 +OpBranch %17 +%17 = OpLabel +%21 = OpLoad %8 %19 +%25 = OpIEqual %23 %21 %22 +%26 = OpAll %24 %25 +OpSelectionMerge %27 None +OpBranchConditional %26 %28 %27 +%28 = OpLabel +OpStore %9 %18 +OpBranch %27 +%27 = OpLabel +OpControlBarrier %29 %29 %30 +OpBranch %31 +%31 = OpLabel +%32 = OpCompositeExtract %4 %14 0 +OpControlBarrier %29 %29 %30 +%34 = OpAccessChain %33 %9 %32 +%35 = OpLoad %6 %34 +OpControlBarrier %29 %29 %30 +%36 = OpSGreaterThan %24 %35 %5 +OpSelectionMerge %37 None +OpBranchConditional %36 %38 %39 +%38 = OpLabel +OpControlBarrier %29 %29 %30 +OpReturn +%39 = OpLabel +OpReturn +%37 = OpLabel +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/workgroup-uniform-load.wgsl b/tests/out/wgsl/workgroup-uniform-load.wgsl new file mode 100644 index 000000000..aafd2cdc5 --- /dev/null +++ b/tests/out/wgsl/workgroup-uniform-load.wgsl @@ -0,0 +1,15 @@ +const SIZE: u32 = 128u; + +var arr_i32_: array; + +@compute @workgroup_size(4, 1, 1) +fn test_workgroupUniformLoad(@builtin(workgroup_id) workgroup_id: vec3) { + let x = (&arr_i32_[workgroup_id.x]); + let _e4 = workgroupUniformLoad(x); + if (_e4 > 10) { + workgroupBarrier(); + return; + } else { + return; + } +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 09e98607b..7a0d4333d 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -576,6 +576,10 @@ fn convert_wgsl() { "workgroup-var-init", Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, ), + ( + "workgroup-uniform-load", + Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, + ), ("sprite", Targets::SPIRV), ("force_point_size_vertex_shader_webgl", Targets::GLSL), ("invariant", Targets::GLSL), From 5206c59509d29825c8f6edef57e70533d9eebd87 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 30 May 2023 14:03:10 +0200 Subject: [PATCH 2007/2212] update snapshots (#2363) --- tests/out/msl/workgroup-uniform-load.msl | 2 +- tests/out/spv/workgroup-uniform-load.spvasm | 85 +++++++++++---------- tests/out/wgsl/workgroup-uniform-load.wgsl | 2 +- 3 files changed, 45 insertions(+), 44 deletions(-) diff --git a/tests/out/msl/workgroup-uniform-load.msl b/tests/out/msl/workgroup-uniform-load.msl index 29df3fff4..cd85811d9 100644 --- a/tests/out/msl/workgroup-uniform-load.msl +++ b/tests/out/msl/workgroup-uniform-load.msl @@ -6,7 +6,7 @@ using metal::uint; constexpr constant unsigned SIZE = 128u; struct type_2 { - int inner[SIZE]; + int inner[128]; }; struct test_workgroupUniformLoadInput { diff --git a/tests/out/spv/workgroup-uniform-load.spvasm b/tests/out/spv/workgroup-uniform-load.spvasm index 8f30b48ac..c8ae47c2f 100644 --- a/tests/out/spv/workgroup-uniform-load.spvasm +++ b/tests/out/spv/workgroup-uniform-load.spvasm @@ -1,66 +1,67 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 40 +; Bound: 41 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %15 "test_workgroupUniformLoad" %12 %19 +OpEntryPoint GLCompute %15 "test_workgroupUniformLoad" %12 %20 OpExecutionMode %15 LocalSize 4 1 1 -OpDecorate %7 ArrayStride 4 +OpDecorate %6 ArrayStride 4 OpDecorate %12 BuiltIn WorkgroupId -OpDecorate %19 BuiltIn LocalInvocationId +OpDecorate %20 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 128 -%6 = OpTypeInt 32 1 -%5 = OpConstant %6 10 -%7 = OpTypeArray %6 %3 +%5 = OpTypeInt 32 1 +%7 = OpConstant %4 128 +%6 = OpTypeArray %5 %7 %8 = OpTypeVector %4 3 -%10 = OpTypePointer Workgroup %7 +%10 = OpTypePointer Workgroup %6 %9 = OpVariable %10 Workgroup %13 = OpTypePointer Input %8 %12 = OpVariable %13 Input %16 = OpTypeFunction %2 -%18 = OpConstantNull %7 -%20 = OpTypePointer Input %8 -%19 = OpVariable %20 Input -%22 = OpConstantNull %8 -%24 = OpTypeBool -%23 = OpTypeVector %24 3 -%29 = OpConstant %4 2 -%30 = OpConstant %4 264 -%33 = OpTypePointer Workgroup %6 +%17 = OpConstant %5 10 +%19 = OpConstantNull %6 +%21 = OpTypePointer Input %8 +%20 = OpVariable %21 Input +%23 = OpConstantNull %8 +%25 = OpTypeBool +%24 = OpTypeVector %25 3 +%30 = OpConstant %4 2 +%31 = OpConstant %4 264 +%34 = OpTypePointer Workgroup %5 %15 = OpFunction %2 None %16 %11 = OpLabel %14 = OpLoad %8 %12 -OpBranch %17 -%17 = OpLabel -%21 = OpLoad %8 %19 -%25 = OpIEqual %23 %21 %22 -%26 = OpAll %24 %25 -OpSelectionMerge %27 None -OpBranchConditional %26 %28 %27 +OpBranch %18 +%18 = OpLabel +%22 = OpLoad %8 %20 +%26 = OpIEqual %24 %22 %23 +%27 = OpAll %25 %26 +OpSelectionMerge %28 None +OpBranchConditional %27 %29 %28 +%29 = OpLabel +OpStore %9 %19 +OpBranch %28 %28 = OpLabel -OpStore %9 %18 -OpBranch %27 -%27 = OpLabel -OpControlBarrier %29 %29 %30 -OpBranch %31 -%31 = OpLabel -%32 = OpCompositeExtract %4 %14 0 -OpControlBarrier %29 %29 %30 -%34 = OpAccessChain %33 %9 %32 -%35 = OpLoad %6 %34 -OpControlBarrier %29 %29 %30 -%36 = OpSGreaterThan %24 %35 %5 -OpSelectionMerge %37 None -OpBranchConditional %36 %38 %39 -%38 = OpLabel -OpControlBarrier %29 %29 %30 -OpReturn +OpControlBarrier %30 %30 %31 +OpBranch %32 +%32 = OpLabel +%33 = OpCompositeExtract %4 %14 0 +OpControlBarrier %30 %30 %31 +%35 = OpAccessChain %34 %9 %33 +%36 = OpLoad %5 %35 +OpControlBarrier %30 %30 %31 +%37 = OpSGreaterThan %25 %36 %17 +OpSelectionMerge %38 None +OpBranchConditional %37 %39 %40 %39 = OpLabel +OpControlBarrier %30 %30 %31 OpReturn -%37 = OpLabel +%40 = OpLabel +OpReturn +%38 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/workgroup-uniform-load.wgsl b/tests/out/wgsl/workgroup-uniform-load.wgsl index aafd2cdc5..727ced8d6 100644 --- a/tests/out/wgsl/workgroup-uniform-load.wgsl +++ b/tests/out/wgsl/workgroup-uniform-load.wgsl @@ -1,6 +1,6 @@ const SIZE: u32 = 128u; -var arr_i32_: array; +var arr_i32_: array; @compute @workgroup_size(4, 1, 1) fn test_workgroupUniformLoad(@builtin(workgroup_id) workgroup_id: vec3) { From 544ccf88daeede7614f8cbae7126496f04cbac68 Mon Sep 17 00:00:00 2001 From: Pieter-Jan Briers Date: Wed, 31 May 2023 15:00:23 +0200 Subject: [PATCH 2008/2212] Handle case insensitive FXC HLSL keywords. (#2347) There are a few keywords like "pass" in HLSL that are actually case-insensitive for FXC. This can be disabled with strict mode, but even if you do that FXC will continue to give an error if you try to use them in identifiers (at all, with any casing). This changes the namer code to escape these keywords even if the casing is different. If you're wondering where I got the list from: I looked at the list of strings in D3DCompiler_47.dll. --- src/back/glsl/mod.rs | 8 ++++- src/back/hlsl/keywords.rs | 22 ++++++++---- src/back/hlsl/writer.rs | 9 +++-- src/back/msl/writer.rs | 2 +- src/back/wgsl/writer.rs | 1 + src/proc/namer.rs | 48 ++++++++++++++++++++++++- tests/in/hlsl-keyword.wgsl | 6 ++++ tests/out/hlsl/hlsl-keyword.hlsl | 9 +++++ tests/out/hlsl/hlsl-keyword.hlsl.config | 3 ++ tests/snapshots.rs | 1 + 10 files changed, 97 insertions(+), 12 deletions(-) create mode 100644 tests/in/hlsl-keyword.wgsl create mode 100644 tests/out/hlsl/hlsl-keyword.hlsl create mode 100644 tests/out/hlsl/hlsl-keyword.hlsl.config diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index d6aff795c..653826ae4 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -484,7 +484,13 @@ impl<'a, W: Write> Writer<'a, W> { // Generate a map with names required to write the module let mut names = crate::FastHashMap::default(); let mut namer = proc::Namer::default(); - namer.reset(module, keywords::RESERVED_KEYWORDS, &["gl_"], &mut names); + namer.reset( + module, + keywords::RESERVED_KEYWORDS, + &[], + &["gl_"], + &mut names, + ); // Build the instance let mut this = Self { diff --git a/src/back/hlsl/keywords.rs b/src/back/hlsl/keywords.rs index 7519b767a..459db245e 100644 --- a/src/back/hlsl/keywords.rs +++ b/src/back/hlsl/keywords.rs @@ -4,9 +4,23 @@ HLSL Reserved Words - */ +// When compiling with FXC without strict mode, these keywords are actually case insensitive. +// If you compile with strict mode and specify a different casing like "Pass" instead in an identifier, FXC will give this error: +// "error X3086: alternate cases for 'pass' are deprecated in strict mode" +// This behavior is not documented anywhere, but as far as I can tell this is the full list. +pub const RESERVED_CASE_INSENSITIVE: &[&str] = &[ + "asm", + "decl", + "pass", + "technique", + "Texture1D", + "Texture2D", + "Texture3D", + "TextureCube", +]; + pub const RESERVED: &[&str] = &[ "AppendStructuredBuffer", - "asm", "asm_fragment", "BlendState", "bool", @@ -68,7 +82,6 @@ pub const RESERVED: &[&str] = &[ "out", "OutputPatch", "packoffset", - "pass", "pixelfragment", "PixelShader", "point", @@ -101,18 +114,13 @@ pub const RESERVED: &[&str] = &[ "switch", "StructuredBuffer", "tbuffer", - "technique", "technique10", "technique11", "texture", - "Texture1D", "Texture1DArray", - "Texture2D", "Texture2DArray", "Texture2DMS", "Texture2DMSArray", - "Texture3D", - "TextureCube", "TextureCubeArray", "true", "typedef", diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 0b08dbe0a..940f0ae37 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -89,8 +89,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { fn reset(&mut self, module: &Module) { self.names.clear(); - self.namer - .reset(module, super::keywords::RESERVED, &[], &mut self.names); + self.namer.reset( + module, + super::keywords::RESERVED, + super::keywords::RESERVED_CASE_INSENSITIVE, + &[], + &mut self.names, + ); self.entry_point_io.clear(); self.named_expressions.clear(); self.wrapped.clear(); diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 07a79f749..cfef6645b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3033,7 +3033,7 @@ impl Writer { ) -> Result { self.names.clear(); self.namer - .reset(module, super::keywords::RESERVED, &[], &mut self.names); + .reset(module, super::keywords::RESERVED, &[], &[], &mut self.names); self.struct_member_pads.clear(); writeln!( diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index da9f605fe..d26ceda48 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -86,6 +86,7 @@ impl Writer { module, crate::keywords::wgsl::RESERVED, // an identifier must not start with two underscore + &[], &["__"], &mut self.names, ); diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 053126b8a..8227b50d8 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -1,5 +1,6 @@ use crate::{arena::Handle, FastHashMap, FastHashSet}; use std::borrow::Cow; +use std::hash::{Hash, Hasher}; pub type EntryPointIndex = u16; const SEPARATOR: char = '_'; @@ -25,6 +26,7 @@ pub struct Namer { /// The last numeric suffix used for each base name. Zero means "no suffix". unique: FastHashMap, keywords: FastHashSet, + keywords_case_insensitive: FastHashSet>, reserved_prefixes: Vec, } @@ -102,7 +104,12 @@ impl Namer { } None => { let mut suffixed = base.to_string(); - if base.ends_with(char::is_numeric) || self.keywords.contains(base.as_ref()) { + if base.ends_with(char::is_numeric) + || self.keywords.contains(base.as_ref()) + || self + .keywords_case_insensitive + .contains(&AsciiUniCase(base.as_ref())) + { suffixed.push(SEPARATOR); } debug_assert!(!self.keywords.contains(&suffixed)); @@ -137,6 +144,7 @@ impl Namer { &mut self, module: &crate::Module, reserved_keywords: &[&str], + reserved_keywords_case_insensitive: &[&'static str], reserved_prefixes: &[&str], output: &mut FastHashMap, ) { @@ -148,6 +156,17 @@ impl Namer { self.keywords.clear(); self.keywords .extend(reserved_keywords.iter().map(|string| (string.to_string()))); + + debug_assert!(reserved_keywords_case_insensitive + .iter() + .all(|s| s.is_ascii())); + self.keywords_case_insensitive.clear(); + self.keywords_case_insensitive.extend( + reserved_keywords_case_insensitive + .iter() + .map(|string| (AsciiUniCase(*string))), + ); + let mut temp = String::new(); for (ty_handle, ty) in module.types.iter() { @@ -252,6 +271,33 @@ impl Namer { } } +/// A string wrapper type with an ascii case insensitive Eq and Hash impl +struct AsciiUniCase + ?Sized>(S); + +impl> PartialEq for AsciiUniCase { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.0.as_ref().eq_ignore_ascii_case(other.0.as_ref()) + } +} + +impl> Eq for AsciiUniCase {} + +impl> Hash for AsciiUniCase { + #[inline] + fn hash(&self, hasher: &mut H) { + for byte in self + .0 + .as_ref() + .as_bytes() + .iter() + .map(|b| b.to_ascii_lowercase()) + { + hasher.write_u8(byte); + } + } +} + #[test] fn test() { let mut namer = Namer::default(); diff --git a/tests/in/hlsl-keyword.wgsl b/tests/in/hlsl-keyword.wgsl new file mode 100644 index 000000000..e2e4e722d --- /dev/null +++ b/tests/in/hlsl-keyword.wgsl @@ -0,0 +1,6 @@ +@fragment +fn fs_main() -> @location(0) vec4f { + // Make sure case-insensitive keywords are escaped in HLSL. + var Pass = vec4(1.0,1.0,1.0,1.0); + return Pass; +} \ No newline at end of file diff --git a/tests/out/hlsl/hlsl-keyword.hlsl b/tests/out/hlsl/hlsl-keyword.hlsl new file mode 100644 index 000000000..efdeb9960 --- /dev/null +++ b/tests/out/hlsl/hlsl-keyword.hlsl @@ -0,0 +1,9 @@ + +float4 fs_main() : SV_Target0 +{ + float4 Pass_ = (float4)0; + + Pass_ = float4(1.0, 1.0, 1.0, 1.0); + float4 _expr6 = Pass_; + return _expr6; +} diff --git a/tests/out/hlsl/hlsl-keyword.hlsl.config b/tests/out/hlsl/hlsl-keyword.hlsl.config new file mode 100644 index 000000000..b9f047558 --- /dev/null +++ b/tests/out/hlsl/hlsl-keyword.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=(fs_main:ps_5_1 ) +compute=() diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 7a0d4333d..8f6fa3a8f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -584,6 +584,7 @@ fn convert_wgsl() { ("force_point_size_vertex_shader_webgl", Targets::GLSL), ("invariant", Targets::GLSL), ("ray-query", Targets::SPIRV | Targets::METAL), + ("hlsl-keyword", Targets::HLSL), ]; for &(name, targets) in inputs.iter() { From b7f4006e46313da063f8f2f930230767c9740239 Mon Sep 17 00:00:00 2001 From: daxpedda Date: Thu, 1 Jun 2023 15:40:47 +0200 Subject: [PATCH 2009/2212] Bump `bitflags` to v2 (#2358) --- Cargo.toml | 8 +- src/back/glsl/features.rs | 1 + src/back/glsl/mod.rs | 1 + src/back/mod.rs | 2 +- src/back/spv/mod.rs | 2 + src/back/wgsl/writer.rs | 1 + src/front/glsl/ast.rs | 1 + src/front/spv/image.rs | 1 + src/front/spv/mod.rs | 2 +- src/lib.rs | 4 +- src/valid/analyzer.rs | 3 + src/valid/function.rs | 1 + src/valid/mod.rs | 3 + src/valid/type.rs | 1 + .../in/bounds-check-image-restrict.param.ron | 2 +- tests/in/bounds-check-image-rzsw.param.ron | 2 +- ...e_point_size_vertex_shader_webgl.param.ron | 2 +- tests/in/functions-webgl.param.ron | 2 +- tests/in/interpolate.param.ron | 2 +- tests/in/invariant.param.ron | 2 +- tests/in/multiview_webgl.param.ron | 2 +- tests/in/push-constants.param.ron | 2 +- tests/in/quad.param.ron | 2 +- tests/in/skybox.param.ron | 2 +- tests/out/analysis/access.info.ron | 1940 +++++------------ tests/out/analysis/collatz.info.ron | 212 +- tests/out/analysis/shadow.info.ron | 1168 +++------- tests/out/ir/access.ron | 12 +- tests/out/ir/collatz.ron | 4 +- tests/out/ir/shadow.ron | 28 +- tests/snapshots.rs | 1 + 31 files changed, 875 insertions(+), 2541 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0ddef7b93..7417995dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,9 +28,9 @@ dot-out = [] glsl-in = ["pp-rs"] glsl-out = [] msl-out = [] -serialize = ["serde", "indexmap/serde-1"] -deserialize = ["serde", "indexmap/serde-1"] -arbitrary = ["dep:arbitrary", "indexmap/arbitrary"] +serialize = ["serde", "bitflags/serde", "indexmap/serde-1"] +deserialize = ["serde", "bitflags/serde", "indexmap/serde-1"] +arbitrary = ["dep:arbitrary", "bitflags/arbitrary", "indexmap/arbitrary"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] wgsl-in = ["codespan-reporting", "hexf-parse", "termcolor", "unicode-xid"] @@ -45,7 +45,7 @@ harness = false [dependencies] arbitrary = { version = "1.0.2", features = ["derive"], optional = true } -bitflags = "1.0.5" +bitflags = "2" bit-set = "0.5" termcolor = { version = "1.0.4", optional = true } # remove termcolor dep when updating to the next version of codespan-reporting diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 8392969b5..c175d9a23 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -7,6 +7,7 @@ use std::fmt::Write; bitflags::bitflags! { /// Structure used to encode additions to GLSL that aren't supported by all versions. + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Features: u32 { /// Buffer address space support. const BUFFER_STORAGE = 1; diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 653826ae4..6298315c5 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -216,6 +216,7 @@ bitflags::bitflags! { /// Configuration flags for the [`Writer`]. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct WriterFlags: u32 { /// Flip output Y and extend Z from (0, 1) to (-1, 1). const ADJUST_COORDINATE_SPACE = 0x1; diff --git a/src/back/mod.rs b/src/back/mod.rs index 8467ee787..76fbaf764 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -228,7 +228,7 @@ bitflags::bitflags! { /// we might as well make one back end's life easier.) /// /// [`RayDesc`]: crate::Module::generate_ray_desc_type - #[derive(Default)] + #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct RayFlag: u32 { const OPAQUE = 0x01; const NO_OPAQUE = 0x02; diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 613912ef8..1e10d2e9c 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -176,6 +176,7 @@ struct LocalImageType { bitflags::bitflags! { /// Flags corresponding to the boolean(-ish) parameters to OpTypeImage. + #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct ImageTypeFlags: u8 { const DEPTH = 0x1; const ARRAYED = 0x2; @@ -624,6 +625,7 @@ pub struct Writer { } bitflags::bitflags! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct WriterFlags: u32 { /// Include debug labels for everything. const DEBUG = 0x1; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index d26ceda48..2d048cd9c 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -53,6 +53,7 @@ enum Indirection { bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct WriterFlags: u32 { /// Always annotate the type information instead of inferring. const EXPLICIT_TYPES = 0x1; diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 47c5a9e80..138a22767 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -67,6 +67,7 @@ bitflags::bitflags! { /// builtins overloads can't be generated unless explicitly used, since they might cause /// unneeded capabilities to be requested #[derive(Default)] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct BuiltinVariations: u32 { /// Request the standard overloads const STANDARD = 1 << 0; diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 757843f78..ddbc8c19b 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -10,6 +10,7 @@ pub(super) struct LookupSampledImage { bitflags::bitflags! { /// Flags describing sampling method. + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct SamplingFlags: u32 { /// Regular sampling. const REGULAR = 0x1; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index dbab5bb00..a2124bfa8 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -168,7 +168,7 @@ impl crate::ImageDimension { type MemberIndex = u32; bitflags::bitflags! { - #[derive(Default)] + #[derive(Clone, Copy, Debug, Default)] struct DecorationFlags: u32 { const NON_READABLE = 0x1; const NON_WRITABLE = 0x2; diff --git a/src/lib.rs b/src/lib.rs index 2d4c3b338..7ac59be50 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -501,7 +501,7 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] - #[derive(Default)] + #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct StorageAccess: u32 { /// Storage can be used as a source for load ops. const LOAD = 0x1; @@ -1195,7 +1195,7 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] - #[derive(Default)] + #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct Barrier: u32 { /// Barrier affects all `AddressSpace::Storage` accesses. const STORAGE = 0x1; diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index e3ada109c..18d6ace2e 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -20,6 +20,7 @@ bitflags::bitflags! { /// Kinds of expressions that require uniform control flow. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct UniformityRequirements: u8 { const WORK_GROUP_BARRIER = 0x1; const DERIVATIVE = 0x2; @@ -59,6 +60,7 @@ impl Uniformity { } bitflags::bitflags! { + #[derive(Clone, Copy, Debug, PartialEq)] struct ExitFlags: u8 { /// Control flow may return from the function, which makes all the /// subsequent statements within the current function (only!) @@ -117,6 +119,7 @@ bitflags::bitflags! { /// Indicates how a global variable is used. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct GlobalUse: u8 { /// Data will be read from the variable. const READ = 0x1; diff --git a/src/valid/function.rs b/src/valid/function.rs index 280ca06c6..41f31b565 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -161,6 +161,7 @@ pub enum FunctionError { bitflags::bitflags! { #[repr(transparent)] + #[derive(Clone, Copy)] struct ControlFlowAbility: u8 { /// The control can return out of this block. const RETURN = 0x1; diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 3e689160b..2c83e1a8d 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -53,6 +53,7 @@ bitflags::bitflags! { /// by default.) #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ValidationFlags: u8 { /// Expressions. #[cfg(feature = "validate")] @@ -86,6 +87,7 @@ bitflags::bitflags! { #[must_use] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Capabilities: u16 { /// Support for [`AddressSpace:PushConstant`]. const PUSH_CONSTANT = 0x1; @@ -126,6 +128,7 @@ bitflags::bitflags! { /// Validation flags. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ShaderStages: u8 { const VERTEX = 0x1; const FRAGMENT = 0x2; diff --git a/src/valid/type.rs b/src/valid/type.rs index db7eec92a..f8ceb463c 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -9,6 +9,7 @@ bitflags::bitflags! { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[repr(transparent)] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct TypeFlags: u8 { /// Can be used for data variables. /// diff --git a/tests/in/bounds-check-image-restrict.param.ron b/tests/in/bounds-check-image-restrict.param.ron index fedcf8407..8d45e982e 100644 --- a/tests/in/bounds-check-image-restrict.param.ron +++ b/tests/in/bounds-check-image-restrict.param.ron @@ -8,7 +8,7 @@ ), glsl: ( version: Desktop(430), - writer_flags: (bits: 0), + writer_flags: (""), binding_map: { }, zero_initialize_workgroup_memory: true, ), diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/tests/in/bounds-check-image-rzsw.param.ron index 40974004c..88978a733 100644 --- a/tests/in/bounds-check-image-rzsw.param.ron +++ b/tests/in/bounds-check-image-rzsw.param.ron @@ -8,7 +8,7 @@ ), glsl: ( version: Desktop(430), - writer_flags: (bits: 0), + writer_flags: (""), binding_map: { }, zero_initialize_workgroup_memory: true, ), diff --git a/tests/in/force_point_size_vertex_shader_webgl.param.ron b/tests/in/force_point_size_vertex_shader_webgl.param.ron index 9499c6b99..c0b7a4d45 100644 --- a/tests/in/force_point_size_vertex_shader_webgl.param.ron +++ b/tests/in/force_point_size_vertex_shader_webgl.param.ron @@ -4,7 +4,7 @@ version: 300, is_webgl: true ), - writer_flags: (bits: 16), + writer_flags: ("FORCE_POINT_SIZE"), binding_map: {}, zero_initialize_workgroup_memory: true, ), diff --git a/tests/in/functions-webgl.param.ron b/tests/in/functions-webgl.param.ron index 862e6a5d0..ddb54c093 100644 --- a/tests/in/functions-webgl.param.ron +++ b/tests/in/functions-webgl.param.ron @@ -4,7 +4,7 @@ version: 320, is_webgl: false ), - writer_flags: (bits: 0), + writer_flags: (""), binding_map: {}, zero_initialize_workgroup_memory: true, ), diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron index a885c9032..b6d629c4e 100644 --- a/tests/in/interpolate.param.ron +++ b/tests/in/interpolate.param.ron @@ -8,7 +8,7 @@ ), glsl: ( version: Desktop(400), - writer_flags: (bits: 0), + writer_flags: (""), binding_map: {}, zero_initialize_workgroup_memory: true, ), diff --git a/tests/in/invariant.param.ron b/tests/in/invariant.param.ron index 9b90c13ba..b622806ad 100644 --- a/tests/in/invariant.param.ron +++ b/tests/in/invariant.param.ron @@ -4,7 +4,7 @@ version: 300, is_webgl: true ), - writer_flags: (bits: 0), + writer_flags: (""), binding_map: {}, zero_initialize_workgroup_memory: true, ), diff --git a/tests/in/multiview_webgl.param.ron b/tests/in/multiview_webgl.param.ron index 98b7fd733..bea71aa41 100644 --- a/tests/in/multiview_webgl.param.ron +++ b/tests/in/multiview_webgl.param.ron @@ -5,7 +5,7 @@ version: 300, is_webgl: true ), - writer_flags: (bits: 0), + writer_flags: (""), binding_map: {}, zero_initialize_workgroup_memory: true, ), diff --git a/tests/in/push-constants.param.ron b/tests/in/push-constants.param.ron index 46874a15a..083d028bb 100644 --- a/tests/in/push-constants.param.ron +++ b/tests/in/push-constants.param.ron @@ -5,7 +5,7 @@ version: 320, is_webgl: false ), - writer_flags: (bits: 0), + writer_flags: (""), binding_map: {}, zero_initialize_workgroup_memory: true, ), diff --git a/tests/in/quad.param.ron b/tests/in/quad.param.ron index db93369f6..7e3f5504d 100644 --- a/tests/in/quad.param.ron +++ b/tests/in/quad.param.ron @@ -9,7 +9,7 @@ version: 300, is_webgl: false ), - writer_flags: (bits: 0), + writer_flags: (""), binding_map: {}, zero_initialize_workgroup_memory: true, ), diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron index 6bca28fc6..4d7fdf734 100644 --- a/tests/in/skybox.param.ron +++ b/tests/in/skybox.param.ron @@ -42,7 +42,7 @@ version: 320, is_webgl: false ), - writer_flags: (bits: 0), + writer_flags: (""), binding_map: { (group: 0, binding: 0): 0, (group: 0, binding: 1): 0, diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron index 8c5097f65..66b38e35a 100644 --- a/tests/out/analysis/access.info.ron +++ b/tests/out/analysis/access.info.ron @@ -1,148 +1,62 @@ ( type_flags: [ - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 215, - ), - ( - bits: 215, - ), - ( - bits: 215, - ), - ( - bits: 19, - ), - ( - bits: 19, - ), - ( - bits: 223, - ), - ( - bits: 215, - ), - ( - bits: 21, - ), - ( - bits: 17, - ), - ( - bits: 215, - ), - ( - bits: 215, - ), - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 215, - ), - ( - bits: 215, - ), - ( - bits: 215, - ), - ( - bits: 223, - ), - ( - bits: 70, - ), - ( - bits: 215, - ), - ( - bits: 215, - ), - ( - bits: 223, - ), - ( - bits: 6, - ), - ( - bits: 215, - ), - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 70, - ), - ( - bits: 215, - ), - ( - bits: 70, - ), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | HOST_SHAREABLE"), + ("DATA | SIZED | HOST_SHAREABLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | COPY | HOST_SHAREABLE"), + ("DATA | HOST_SHAREABLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("SIZED | COPY | ARGUMENT"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("SIZED | COPY"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("SIZED | COPY | ARGUMENT"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("SIZED | COPY | ARGUMENT"), ], functions: [ ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 1, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), + (""), + (""), + ("READ"), + (""), + (""), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -154,9 +68,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 15, assignable_global: None, @@ -168,9 +80,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -179,9 +89,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -193,9 +101,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -204,9 +110,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -218,9 +122,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -232,9 +134,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -243,9 +143,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -257,9 +155,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -271,9 +167,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -285,9 +179,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -301,9 +193,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -316,9 +206,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -330,9 +218,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -344,9 +230,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -355,9 +239,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -371,9 +253,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -386,9 +266,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -400,9 +278,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -414,9 +290,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -428,9 +302,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -444,9 +316,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -458,9 +328,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -474,9 +342,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -488,9 +354,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -502,9 +366,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -516,9 +378,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -530,9 +390,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -546,9 +404,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -557,9 +413,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -573,9 +427,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -587,9 +439,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -601,9 +451,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -615,9 +463,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -626,9 +472,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -642,9 +486,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -656,9 +498,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -672,9 +512,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -686,9 +524,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -700,9 +536,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -714,9 +548,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -725,9 +557,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -741,9 +571,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -752,9 +580,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -768,9 +594,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -782,9 +606,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -796,9 +618,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -811,9 +631,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -825,9 +643,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -840,9 +656,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -854,9 +668,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -869,9 +681,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -880,9 +690,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -891,9 +699,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 8, assignable_global: None, @@ -905,9 +711,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -916,9 +720,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -930,9 +732,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -941,9 +741,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -955,9 +753,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -969,9 +765,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -984,9 +778,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -998,9 +790,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1013,9 +803,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1027,9 +815,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1042,9 +828,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1053,9 +837,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1067,9 +849,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1081,9 +861,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1097,9 +875,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1111,9 +887,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1126,9 +900,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1140,9 +912,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1151,9 +921,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1167,9 +935,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1181,9 +947,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1196,9 +960,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1210,9 +972,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1224,9 +984,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1240,9 +998,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1254,9 +1010,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1270,9 +1024,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1284,9 +1036,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1298,9 +1048,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1312,9 +1060,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1328,9 +1074,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1339,9 +1083,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1355,9 +1097,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1369,9 +1109,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1383,9 +1121,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1394,9 +1130,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1410,9 +1144,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1424,9 +1156,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1440,9 +1170,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1454,9 +1182,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1468,9 +1194,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1479,9 +1203,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1495,9 +1217,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1506,9 +1226,7 @@ ( uniformity: ( non_uniform_result: Some(55), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1522,9 +1240,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1537,47 +1253,27 @@ sampling: [], ), ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 1, - ), - ( - bits: 0, - ), + (""), + (""), + (""), + (""), + ("READ"), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1589,9 +1285,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 15, assignable_global: None, @@ -1603,9 +1297,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1614,9 +1306,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1628,9 +1318,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1639,9 +1327,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1653,9 +1339,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1667,9 +1351,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1678,9 +1360,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1692,9 +1372,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1706,9 +1384,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1720,9 +1396,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1734,9 +1408,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1745,9 +1417,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1759,9 +1429,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1773,9 +1441,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1787,9 +1453,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1801,9 +1465,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1815,9 +1477,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1831,9 +1491,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1846,9 +1504,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1860,9 +1516,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1874,9 +1528,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1888,9 +1540,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1902,9 +1552,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1913,9 +1561,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1929,9 +1575,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1944,9 +1588,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1958,9 +1600,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -1972,9 +1612,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1986,9 +1624,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2000,9 +1636,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2014,9 +1648,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2030,9 +1662,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2044,9 +1674,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2060,9 +1688,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2074,9 +1700,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2088,9 +1712,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2102,9 +1724,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2116,9 +1736,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2130,9 +1748,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2144,9 +1760,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2160,9 +1774,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2171,9 +1783,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2187,9 +1797,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2201,9 +1809,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2215,9 +1821,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2229,9 +1833,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2243,9 +1845,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2257,9 +1857,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2268,9 +1866,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2284,9 +1880,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2298,9 +1892,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2314,9 +1906,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2328,9 +1918,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2342,9 +1930,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2356,9 +1942,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2370,9 +1954,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2384,9 +1966,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2395,9 +1975,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2411,9 +1989,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2422,9 +1998,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2438,9 +2012,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2452,9 +2024,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2463,9 +2033,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2474,9 +2042,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 9, assignable_global: None, @@ -2488,9 +2054,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2499,9 +2063,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2513,9 +2075,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2524,9 +2084,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2538,9 +2096,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2549,9 +2105,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2563,9 +2117,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2577,9 +2129,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2591,9 +2141,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2605,9 +2153,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2620,9 +2166,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2634,9 +2178,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2649,9 +2191,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2663,9 +2203,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2678,9 +2216,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2692,9 +2228,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2707,9 +2241,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2718,9 +2250,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2732,9 +2262,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2746,9 +2274,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2760,9 +2286,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2774,9 +2298,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2790,9 +2312,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2804,9 +2324,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2819,9 +2337,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2833,9 +2349,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2847,9 +2361,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2861,9 +2373,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2872,9 +2382,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2888,9 +2396,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2902,9 +2408,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2917,9 +2421,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2931,9 +2433,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2945,9 +2445,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2959,9 +2457,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -2973,9 +2469,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2989,9 +2483,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3003,9 +2495,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3019,9 +2509,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3033,9 +2521,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3047,9 +2533,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3061,9 +2545,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3075,9 +2557,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3089,9 +2569,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3105,9 +2583,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3116,9 +2592,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3132,9 +2606,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3146,9 +2618,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3160,9 +2630,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3174,9 +2642,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3188,9 +2654,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3199,9 +2663,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3215,9 +2677,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3229,9 +2689,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3245,9 +2703,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3259,9 +2715,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3273,9 +2727,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3287,9 +2739,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3301,9 +2751,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3312,9 +2760,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3328,9 +2774,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3339,9 +2783,7 @@ ( uniformity: ( non_uniform_result: Some(66), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3355,9 +2797,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3370,47 +2810,27 @@ sampling: [], ), ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), + (""), + (""), + (""), + (""), + (""), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3419,9 +2839,7 @@ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3431,47 +2849,27 @@ sampling: [], ), ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), + (""), + (""), + (""), + (""), + (""), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3480,9 +2878,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3494,9 +2890,7 @@ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3505,9 +2899,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3519,9 +2911,7 @@ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3531,47 +2921,27 @@ sampling: [], ), ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), + (""), + (""), + (""), + (""), + (""), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3580,9 +2950,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3595,47 +2963,27 @@ sampling: [], ), ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), + (""), + (""), + (""), + (""), + (""), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3644,9 +2992,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3658,9 +3004,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3673,9 +3017,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3687,9 +3029,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3702,9 +3042,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3716,47 +3054,27 @@ ], entry_points: [ ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), - ( - bits: 5, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 0, - ), + (""), + ("READ | QUERY"), + ("READ"), + ("READ"), + ("READ"), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 2, assignable_global: None, @@ -3765,9 +3083,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3779,9 +3095,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 4, assignable_global: None, @@ -3793,9 +3107,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3804,9 +3116,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3818,45 +3128,35 @@ ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 6, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3865,45 +3165,35 @@ ( uniformity: ( non_uniform_result: Some(9), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(9), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 12, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(9), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3912,9 +3202,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -3926,45 +3214,35 @@ ( uniformity: ( non_uniform_result: Some(13), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(13), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 6, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(13), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), @@ -3973,18 +3251,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(13), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), @@ -3993,18 +3267,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(13), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4016,81 +3286,63 @@ ( uniformity: ( non_uniform_result: Some(18), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(18), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 13, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(20), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(20), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 13, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(20), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4102,9 +3354,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4116,9 +3366,7 @@ ( uniformity: ( non_uniform_result: Some(20), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4130,45 +3378,35 @@ ( uniformity: ( non_uniform_result: Some(18), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 5, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(18), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 3, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(18), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4177,27 +3415,21 @@ ( uniformity: ( non_uniform_result: Some(28), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 17, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(28), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -4206,45 +3438,35 @@ ( uniformity: ( non_uniform_result: Some(30), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(30), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 13, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -4256,45 +3478,35 @@ ( uniformity: ( non_uniform_result: Some(30), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 5, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(30), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: Some(2), ty: Value(Pointer( base: 3, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -4303,9 +3515,7 @@ ( uniformity: ( non_uniform_result: Some(13), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4317,9 +3527,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4331,9 +3539,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4345,9 +3551,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4359,9 +3563,7 @@ ( uniformity: ( non_uniform_result: Some(18), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4370,9 +3572,7 @@ ( uniformity: ( non_uniform_result: Some(41), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 3, assignable_global: None, @@ -4384,9 +3584,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4398,9 +3596,7 @@ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4409,9 +3605,7 @@ ( uniformity: ( non_uniform_result: Some(41), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4423,9 +3617,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4437,9 +3629,7 @@ ( uniformity: ( non_uniform_result: Some(41), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4451,9 +3641,7 @@ ( uniformity: ( non_uniform_result: Some(41), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4462,9 +3650,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4473,9 +3659,7 @@ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -4484,9 +3668,7 @@ ( uniformity: ( non_uniform_result: Some(41), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4499,9 +3681,7 @@ ( uniformity: ( non_uniform_result: Some(41), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4514,9 +3694,7 @@ ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4529,9 +3707,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4543,9 +3719,7 @@ ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4555,83 +3729,55 @@ sampling: [], ), ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), - ( - bits: 2, - ), - ( - bits: 0, - ), - ( - bits: 2, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), + (""), + ("WRITE"), + (""), + ("WRITE"), + (""), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 6, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -4643,9 +3789,7 @@ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), @@ -4654,18 +3798,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), @@ -4674,18 +3814,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4697,45 +3833,35 @@ ( uniformity: ( non_uniform_result: Some(7), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(7), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 6, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4747,9 +3873,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4762,9 +3886,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4776,9 +3898,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4791,9 +3911,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4805,9 +3923,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4820,9 +3936,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4834,9 +3948,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4849,9 +3961,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4860,45 +3970,35 @@ ( uniformity: ( non_uniform_result: Some(18), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(18), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 12, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4910,9 +4010,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4925,9 +4023,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4939,9 +4035,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4954,9 +4048,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -4965,45 +4057,35 @@ ( uniformity: ( non_uniform_result: Some(25), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 14, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(25), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 13, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -5015,45 +4097,35 @@ ( uniformity: ( non_uniform_result: Some(25), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 5, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(25), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), ty: Value(Pointer( base: 3, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -5065,27 +4137,21 @@ ( uniformity: ( non_uniform_result: Some(31), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 17, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -5094,9 +4160,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -5108,9 +4172,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -5124,47 +4186,27 @@ sampling: [], ), ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 1, - ), + (""), + (""), + (""), + (""), + (""), + ("READ"), ], expressions: [ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -5176,9 +4218,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -5191,9 +4231,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -5205,9 +4243,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -5220,9 +4256,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -5231,9 +4265,7 @@ ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 2, assignable_global: None, @@ -5245,9 +4277,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(6), diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index 3896cd943..f060e3b3f 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -1,46 +1,28 @@ ( type_flags: [ - ( - bits: 223, - ), - ( - bits: 21, - ), - ( - bits: 21, - ), - ( - bits: 223, - ), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | COPY | HOST_SHAREABLE"), + ("DATA | COPY | HOST_SHAREABLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ], functions: [ ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 0, - ), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -49,9 +31,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 7, assignable_global: None, @@ -63,9 +43,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -77,9 +55,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 4, assignable_global: None, @@ -91,9 +67,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -102,9 +76,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -116,9 +88,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -130,9 +100,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -141,9 +109,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -155,9 +121,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -166,9 +130,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -180,9 +142,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -194,9 +154,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -205,9 +163,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -219,9 +175,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -230,9 +184,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -244,9 +196,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -255,9 +205,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -266,9 +214,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -280,9 +226,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -291,9 +235,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -302,9 +244,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -316,9 +256,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -327,9 +265,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -341,32 +277,22 @@ ], entry_points: [ ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [], global_uses: [ - ( - bits: 3, - ), + ("READ | WRITE"), ], expressions: [ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 2, assignable_global: None, @@ -375,45 +301,35 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(1), ty: Value(Pointer( base: 3, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(1), ty: Value(Pointer( base: 2, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -425,63 +341,49 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(1), ty: Value(Pointer( base: 1, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(1), ty: Value(Pointer( base: 3, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(1), ty: Value(Pointer( base: 2, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -493,27 +395,21 @@ ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(1), ty: Value(Pointer( base: 1, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), )), ), ( uniformity: ( non_uniform_result: Some(6), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -522,9 +418,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index bff3013e0..fdafe5107 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -1,109 +1,43 @@ ( type_flags: [ - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 199, - ), - ( - bits: 223, - ), - ( - bits: 64, - ), - ( - bits: 64, - ), - ( - bits: 223, - ), - ( - bits: 70, - ), - ( - bits: 70, - ), - ( - bits: 223, - ), - ( - bits: 223, - ), - ( - bits: 6, - ), - ( - bits: 6, - ), - ( - bits: 6, - ), - ( - bits: 215, - ), - ( - bits: 215, - ), - ( - bits: 21, - ), - ( - bits: 21, - ), - ( - bits: 6, - ), - ( - bits: 6, - ), - ( - bits: 6, - ), - ( - bits: 6, - ), - ( - bits: 70, - ), - ( - bits: 70, - ), - ( - bits: 6, - ), - ( - bits: 6, - ), - ( - bits: 70, - ), - ( - bits: 64, - ), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("ARGUMENT"), + ("ARGUMENT"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("SIZED | COPY | ARGUMENT"), + ("SIZED | COPY | ARGUMENT"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("SIZED | COPY"), + ("SIZED | COPY"), + ("SIZED | COPY"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), + ("DATA | COPY | HOST_SHAREABLE"), + ("DATA | COPY | HOST_SHAREABLE"), + ("SIZED | COPY"), + ("SIZED | COPY"), + ("SIZED | COPY"), + ("SIZED | COPY"), + ("SIZED | COPY | ARGUMENT"), + ("SIZED | COPY | ARGUMENT"), + ("SIZED | COPY"), + ("SIZED | COPY"), + ("SIZED | COPY | ARGUMENT"), + ("ARGUMENT"), ], functions: [ ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [ @@ -113,35 +47,19 @@ ), ], global_uses: [ - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), - ( - bits: 0, - ), + ("READ"), + ("READ"), + (""), + (""), + (""), + (""), + (""), ], expressions: [ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: Some(3), @@ -153,9 +71,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: Some(6), @@ -167,9 +83,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: Some(5), @@ -181,9 +95,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(1), @@ -192,9 +104,7 @@ ( uniformity: ( non_uniform_result: Some(5), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(2), @@ -203,27 +113,21 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: Some(4), ty: Value(Pointer( base: 20, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(7), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: Some(7), @@ -235,9 +139,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -249,9 +151,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -263,9 +163,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -277,9 +175,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -291,9 +187,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -305,9 +199,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 2, assignable_global: None, @@ -319,9 +211,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -333,9 +223,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -347,9 +235,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -361,9 +247,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -375,9 +259,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -389,9 +271,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -403,9 +283,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -417,9 +295,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -431,9 +307,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -445,9 +319,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -459,9 +331,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -473,9 +343,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -487,9 +355,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -501,9 +367,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -515,9 +379,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -529,9 +391,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -543,9 +403,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -557,9 +415,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -571,9 +427,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -585,9 +439,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -599,9 +451,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 3, assignable_global: None, @@ -613,9 +463,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -627,9 +475,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -641,9 +487,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -655,9 +499,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -669,9 +511,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -683,9 +523,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -697,9 +535,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -711,9 +547,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -725,9 +559,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -739,9 +571,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -753,9 +583,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -764,9 +592,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -778,9 +604,7 @@ ( uniformity: ( non_uniform_result: Some(47), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -789,9 +613,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 6, assignable_global: None, @@ -800,9 +622,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -814,9 +634,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -828,9 +646,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -842,9 +658,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -856,9 +670,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -867,9 +679,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -878,9 +688,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -889,9 +697,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -903,9 +709,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -917,9 +721,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -928,9 +730,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -943,9 +743,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 2, assignable_global: None, @@ -954,9 +752,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -968,9 +764,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -982,9 +776,7 @@ ( uniformity: ( non_uniform_result: Some(47), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -996,9 +788,7 @@ ( uniformity: ( non_uniform_result: Some(47), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1010,9 +800,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 3, assignable_global: None, @@ -1021,9 +809,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1035,9 +821,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1049,9 +833,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1063,9 +845,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1077,9 +857,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1091,9 +869,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1105,9 +881,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1116,9 +890,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1130,9 +902,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1144,9 +914,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1159,17 +927,11 @@ sampling: [], ), ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [ @@ -1179,35 +941,19 @@ ), ], global_uses: [ - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 2, - ), + ("READ"), + ("READ"), + ("READ"), + ("READ"), + ("READ"), + ("READ"), + ("WRITE"), ], expressions: [ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -1219,9 +965,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(6), @@ -1233,9 +977,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 4, assignable_global: Some(5), @@ -1247,9 +989,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: Some(1), @@ -1258,9 +998,7 @@ ( uniformity: ( non_uniform_result: Some(5), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: Some(2), @@ -1269,27 +1007,21 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 7, assignable_global: Some(4), ty: Value(Pointer( base: 20, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(7), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(7), @@ -1301,9 +1033,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1315,9 +1045,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1329,9 +1057,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1343,9 +1069,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1357,9 +1081,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1371,9 +1093,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1385,9 +1105,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1399,9 +1117,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1413,9 +1129,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1427,9 +1141,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1441,9 +1153,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1455,9 +1165,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1469,9 +1177,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1483,9 +1189,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1497,9 +1201,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1511,9 +1213,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1525,9 +1225,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1539,9 +1237,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1553,9 +1249,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1567,9 +1261,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1581,9 +1273,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1595,9 +1285,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1609,9 +1297,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1623,9 +1309,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1637,9 +1321,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1651,9 +1333,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1665,9 +1345,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1679,9 +1357,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1693,9 +1369,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1707,9 +1381,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1721,9 +1393,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1735,9 +1405,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1749,9 +1417,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1763,9 +1429,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1777,9 +1441,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1791,9 +1453,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1805,9 +1465,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1819,9 +1477,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 0, assignable_global: None, @@ -1830,9 +1486,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1844,9 +1498,7 @@ ( uniformity: ( non_uniform_result: Some(47), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 3, assignable_global: None, @@ -1858,9 +1510,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 11, assignable_global: None, @@ -1872,9 +1522,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1883,9 +1531,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -1897,9 +1543,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(3), @@ -1913,9 +1557,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1927,9 +1569,7 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1941,9 +1581,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1955,9 +1593,7 @@ ( uniformity: ( non_uniform_result: Some(47), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1966,9 +1602,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -1977,27 +1611,21 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 19, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2006,45 +1634,35 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 18, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 17, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2053,9 +1671,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2064,9 +1680,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2079,9 +1693,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2090,9 +1702,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2101,9 +1711,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2112,27 +1720,21 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 19, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2141,45 +1743,35 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 18, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), @@ -2188,18 +1780,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2211,27 +1799,21 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 19, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2240,45 +1822,35 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 18, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), @@ -2287,18 +1859,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2310,27 +1878,21 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 19, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2339,45 +1901,35 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 18, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), @@ -2386,18 +1938,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2409,9 +1957,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2420,9 +1966,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2436,9 +1980,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2450,9 +1992,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2466,9 +2006,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2480,9 +2018,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -2496,9 +2032,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2510,9 +2044,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2521,9 +2053,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2532,9 +2062,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2543,9 +2071,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2557,9 +2083,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2571,9 +2095,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2585,27 +2107,21 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 19, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2614,45 +2130,35 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 18, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), @@ -2661,18 +2167,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2684,27 +2186,21 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 19, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2713,45 +2209,35 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 18, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), @@ -2760,18 +2246,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2783,27 +2265,21 @@ ( uniformity: ( non_uniform_result: None, - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 19, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2812,45 +2288,35 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 18, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( base: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(4), @@ -2859,18 +2325,14 @@ kind: Float, width: 4, space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), )), ), ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2882,9 +2344,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2893,9 +2353,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2904,9 +2362,7 @@ ( uniformity: ( non_uniform_result: Some(47), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2915,9 +2371,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2926,9 +2380,7 @@ ( uniformity: ( non_uniform_result: Some(48), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2937,9 +2389,7 @@ ( uniformity: ( non_uniform_result: Some(47), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2948,9 +2398,7 @@ ( uniformity: ( non_uniform_result: Some(47), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -2962,17 +2410,11 @@ ], entry_points: [ ( - flags: ( - bits: 63, - ), - available_stages: ( - bits: 7, - ), + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), may_kill: false, sampling_set: [ @@ -2982,35 +2424,19 @@ ), ], global_uses: [ - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 1, - ), - ( - bits: 3, - ), - ( - bits: 3, - ), - ( - bits: 3, - ), + ("READ"), + ("READ"), + ("READ"), + ("READ"), + ("READ | WRITE"), + ("READ | WRITE"), + ("READ | WRITE"), ], expressions: [ ( uniformity: ( non_uniform_result: Some(1), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3019,9 +2445,7 @@ ( uniformity: ( non_uniform_result: Some(2), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(6), @@ -3033,9 +2457,7 @@ ( uniformity: ( non_uniform_result: Some(3), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, @@ -3044,9 +2466,7 @@ ( uniformity: ( non_uniform_result: Some(4), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(5), @@ -3058,9 +2478,7 @@ ( uniformity: ( non_uniform_result: Some(5), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: Some(7), @@ -3072,9 +2490,7 @@ ( uniformity: ( non_uniform_result: Some(5), - requirements: ( - bits: 0, - ), + requirements: (""), ), ref_count: 1, assignable_global: None, diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 41d5cb916..b314d9fe1 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -280,9 +280,7 @@ inner: Pointer( base: 3, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), ), ), @@ -422,9 +420,7 @@ ( name: Some("bar"), space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), binding: Some(( group: 0, @@ -446,9 +442,7 @@ ( name: Some("qux"), space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), binding: Some(( group: 0, diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index a01f07d14..1d38cc34f 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -47,9 +47,7 @@ ( name: Some("v_indices"), space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), binding: Some(( group: 0, diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 76f4f0527..103e69b5f 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -186,9 +186,7 @@ inner: Pointer( base: 20, space: Storage( - access: ( - bits: 0, - ), + access: (""), ), ), ), @@ -197,9 +195,7 @@ inner: Pointer( base: 19, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), ), ), @@ -208,9 +204,7 @@ inner: Pointer( base: 18, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), ), ), @@ -219,9 +213,7 @@ inner: Pointer( base: 17, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), ), ), @@ -244,9 +236,7 @@ inner: Pointer( base: 4, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), ), ), @@ -255,9 +245,7 @@ inner: Pointer( base: 1, space: Storage( - access: ( - bits: 3, - ), + access: ("LOAD | STORE"), ), ), ), @@ -631,9 +619,7 @@ ( name: Some("s_lights"), space: Storage( - access: ( - bits: 1, - ), + access: ("LOAD"), ), binding: Some(( group: 0, diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 8f6fa3a8f..e51c6ced4 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -11,6 +11,7 @@ const BASE_DIR_IN: &str = "tests/in"; const BASE_DIR_OUT: &str = "tests/out"; bitflags::bitflags! { + #[derive(Clone, Copy)] struct Targets: u32 { const IR = 0x1; const ANALYSIS = 0x2; From e8a7e50f0f93b7657da099abdbfd7f2503912745 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 6 Jun 2023 08:02:10 -0700 Subject: [PATCH 2010/2212] Makefile: validate-spv: update spirv-as and spirv-val invocations. (#2374) Newer versions of these programs require `-` as a filename argument to read from standard input. --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 744d8a225..606e616bd 100644 --- a/Makefile +++ b/Makefile @@ -35,7 +35,7 @@ validate-spv: $(SNAPSHOTS_BASE_OUT)/spv/*.spvasm echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ version_line=$$(head -2 $${file} | tail -1); \ version=$${version_line#"; Version: "};\ - cat $${file} | spirv-as --target-env spv$${version} -o - | spirv-val; \ + cat $${file} | spirv-as --target-env spv$${version} - -o - | spirv-val -; \ done validate-msl: $(SNAPSHOTS_BASE_OUT)/msl/*.msl From 91d48b29231edd6c26d516cff265127d6702b0ba Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Mon, 20 Mar 2023 10:42:39 -0400 Subject: [PATCH 2011/2212] build: move from `make` to `cargo xtask` workflows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Re-implement `naga` development workflows using [`cargo xtask`]. Convert `make` logic and shader test configuration as file with Bash variables into an `xtask` crate and YAML files, respectively. Pros: * We now have a _portable_ workflow everywhere, which means Windows folks and people who don't install `make` don't have to suffer. 😮‍💨 * Workflow logic is now relatively easy to inspect and change. Whew! 💁🏻‍♂️💦 * Contributors can use their existing Rust knowledge to contribute to developer experience. 🎉 * `cargo xtask` is a relatively well-known convention for workflows in the ecosystem. * We can do fancy things like allow folks to run at different log levels for workflows, depending on their tastes. Cons: * There's now a non-trivial compile step to project workflow. Incremental rebuilds seem to be pretty short, though! * Code is much more verbose than the (very) terse `make` implementation. [`cargo xtask`]: https://github.com/matklad/cargo-xtask --- .cargo/config.toml | 2 + .github/workflows/validation-linux.yml | 14 +- .github/workflows/validation-macos.yml | 8 +- .github/workflows/validation-windows.yml | 17 +- Cargo.toml | 1 + Makefile | 131 -------- tests/out/hlsl/access.hlsl.config | 3 - tests/out/hlsl/access.ron | 20 ++ tests/out/hlsl/array-in-ctor.hlsl.config | 3 - tests/out/hlsl/array-in-ctor.ron | 12 + tests/out/hlsl/atomicOps.hlsl.config | 3 - tests/out/hlsl/atomicOps.ron | 12 + tests/out/hlsl/binding-arrays.hlsl.config | 3 - tests/out/hlsl/binding-arrays.ron | 12 + tests/out/hlsl/bitcast.hlsl.config | 3 - tests/out/hlsl/bitcast.ron | 12 + tests/out/hlsl/boids.hlsl.config | 3 - tests/out/hlsl/boids.ron | 12 + tests/out/hlsl/break-if.hlsl.config | 3 - tests/out/hlsl/break-if.ron | 12 + tests/out/hlsl/collatz.hlsl.config | 3 - tests/out/hlsl/collatz.ron | 12 + tests/out/hlsl/control-flow.hlsl.config | 3 - tests/out/hlsl/control-flow.ron | 12 + tests/out/hlsl/do-while.hlsl.config | 3 - tests/out/hlsl/do-while.ron | 12 + tests/out/hlsl/empty-global-name.hlsl.config | 3 - tests/out/hlsl/empty-global-name.ron | 12 + tests/out/hlsl/empty.hlsl.config | 3 - tests/out/hlsl/empty.ron | 12 + tests/out/hlsl/fragment-output.hlsl.config | 3 - tests/out/hlsl/fragment-output.ron | 16 + tests/out/hlsl/functions.hlsl.config | 3 - tests/out/hlsl/functions.ron | 12 + tests/out/hlsl/globals.hlsl.config | 3 - tests/out/hlsl/globals.ron | 12 + tests/out/hlsl/hlsl-keyword.hlsl.config | 3 - tests/out/hlsl/hlsl-keyword.ron | 12 + tests/out/hlsl/image.hlsl.config | 3 - tests/out/hlsl/image.ron | 40 +++ tests/out/hlsl/interface.hlsl.config | 3 - tests/out/hlsl/interface.ron | 24 ++ tests/out/hlsl/interpolate.hlsl.config | 3 - tests/out/hlsl/interpolate.ron | 16 + .../inv-hyperbolic-trig-functions.hlsl.config | 3 - .../hlsl/inv-hyperbolic-trig-functions.ron | 12 + tests/out/hlsl/math-functions.hlsl.config | 3 - tests/out/hlsl/math-functions.ron | 12 + tests/out/hlsl/operators.hlsl.config | 3 - tests/out/hlsl/operators.ron | 12 + tests/out/hlsl/padding.hlsl.config | 3 - tests/out/hlsl/padding.ron | 12 + tests/out/hlsl/push-constants.hlsl.config | 3 - tests/out/hlsl/push-constants.ron | 16 + tests/out/hlsl/quad-vert.hlsl.config | 3 - tests/out/hlsl/quad-vert.ron | 12 + tests/out/hlsl/quad.hlsl.config | 3 - tests/out/hlsl/quad.ron | 20 ++ tests/out/hlsl/shadow.hlsl.config | 3 - tests/out/hlsl/shadow.ron | 20 ++ tests/out/hlsl/skybox.hlsl.config | 3 - tests/out/hlsl/skybox.ron | 16 + tests/out/hlsl/standard.hlsl.config | 3 - tests/out/hlsl/standard.ron | 12 + tests/out/hlsl/texture-arg.hlsl.config | 3 - tests/out/hlsl/texture-arg.ron | 12 + .../hlsl/workgroup-uniform-load.hlsl.config | 3 - tests/out/hlsl/workgroup-uniform-load.ron | 12 + tests/out/hlsl/workgroup-var-init.hlsl.config | 3 - tests/out/hlsl/workgroup-var-init.ron | 12 + tests/snapshots.rs | 56 +--- xtask/.gitignore | 2 + xtask/Cargo.lock | 117 +++++++ xtask/Cargo.toml | 19 ++ xtask/hlsl-snapshots/Cargo.toml | 8 + xtask/hlsl-snapshots/src/lib.rs | 97 ++++++ xtask/src/cli.rs | 160 +++++++++ xtask/src/fs.rs | 10 + xtask/src/glob.rs | 37 +++ xtask/src/main.rs | 305 ++++++++++++++++++ xtask/src/path.rs | 11 + xtask/src/process.rs | 78 +++++ xtask/src/result.rs | 33 ++ 83 files changed, 1389 insertions(+), 277 deletions(-) create mode 100644 .cargo/config.toml delete mode 100644 Makefile delete mode 100644 tests/out/hlsl/access.hlsl.config create mode 100644 tests/out/hlsl/access.ron delete mode 100644 tests/out/hlsl/array-in-ctor.hlsl.config create mode 100644 tests/out/hlsl/array-in-ctor.ron delete mode 100644 tests/out/hlsl/atomicOps.hlsl.config create mode 100644 tests/out/hlsl/atomicOps.ron delete mode 100644 tests/out/hlsl/binding-arrays.hlsl.config create mode 100644 tests/out/hlsl/binding-arrays.ron delete mode 100644 tests/out/hlsl/bitcast.hlsl.config create mode 100644 tests/out/hlsl/bitcast.ron delete mode 100644 tests/out/hlsl/boids.hlsl.config create mode 100644 tests/out/hlsl/boids.ron delete mode 100644 tests/out/hlsl/break-if.hlsl.config create mode 100644 tests/out/hlsl/break-if.ron delete mode 100644 tests/out/hlsl/collatz.hlsl.config create mode 100644 tests/out/hlsl/collatz.ron delete mode 100644 tests/out/hlsl/control-flow.hlsl.config create mode 100644 tests/out/hlsl/control-flow.ron delete mode 100644 tests/out/hlsl/do-while.hlsl.config create mode 100644 tests/out/hlsl/do-while.ron delete mode 100644 tests/out/hlsl/empty-global-name.hlsl.config create mode 100644 tests/out/hlsl/empty-global-name.ron delete mode 100644 tests/out/hlsl/empty.hlsl.config create mode 100644 tests/out/hlsl/empty.ron delete mode 100644 tests/out/hlsl/fragment-output.hlsl.config create mode 100644 tests/out/hlsl/fragment-output.ron delete mode 100644 tests/out/hlsl/functions.hlsl.config create mode 100644 tests/out/hlsl/functions.ron delete mode 100644 tests/out/hlsl/globals.hlsl.config create mode 100644 tests/out/hlsl/globals.ron delete mode 100644 tests/out/hlsl/hlsl-keyword.hlsl.config create mode 100644 tests/out/hlsl/hlsl-keyword.ron delete mode 100644 tests/out/hlsl/image.hlsl.config create mode 100644 tests/out/hlsl/image.ron delete mode 100644 tests/out/hlsl/interface.hlsl.config create mode 100644 tests/out/hlsl/interface.ron delete mode 100644 tests/out/hlsl/interpolate.hlsl.config create mode 100644 tests/out/hlsl/interpolate.ron delete mode 100644 tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config create mode 100644 tests/out/hlsl/inv-hyperbolic-trig-functions.ron delete mode 100644 tests/out/hlsl/math-functions.hlsl.config create mode 100644 tests/out/hlsl/math-functions.ron delete mode 100644 tests/out/hlsl/operators.hlsl.config create mode 100644 tests/out/hlsl/operators.ron delete mode 100644 tests/out/hlsl/padding.hlsl.config create mode 100644 tests/out/hlsl/padding.ron delete mode 100644 tests/out/hlsl/push-constants.hlsl.config create mode 100644 tests/out/hlsl/push-constants.ron delete mode 100644 tests/out/hlsl/quad-vert.hlsl.config create mode 100644 tests/out/hlsl/quad-vert.ron delete mode 100644 tests/out/hlsl/quad.hlsl.config create mode 100644 tests/out/hlsl/quad.ron delete mode 100644 tests/out/hlsl/shadow.hlsl.config create mode 100644 tests/out/hlsl/shadow.ron delete mode 100644 tests/out/hlsl/skybox.hlsl.config create mode 100644 tests/out/hlsl/skybox.ron delete mode 100644 tests/out/hlsl/standard.hlsl.config create mode 100644 tests/out/hlsl/standard.ron delete mode 100644 tests/out/hlsl/texture-arg.hlsl.config create mode 100644 tests/out/hlsl/texture-arg.ron delete mode 100644 tests/out/hlsl/workgroup-uniform-load.hlsl.config create mode 100644 tests/out/hlsl/workgroup-uniform-load.ron delete mode 100644 tests/out/hlsl/workgroup-var-init.hlsl.config create mode 100644 tests/out/hlsl/workgroup-var-init.ron create mode 100644 xtask/.gitignore create mode 100644 xtask/Cargo.lock create mode 100644 xtask/Cargo.toml create mode 100644 xtask/hlsl-snapshots/Cargo.toml create mode 100644 xtask/hlsl-snapshots/src/lib.rs create mode 100644 xtask/src/cli.rs create mode 100644 xtask/src/fs.rs create mode 100644 xtask/src/glob.rs create mode 100644 xtask/src/main.rs create mode 100644 xtask/src/path.rs create mode 100644 xtask/src/process.rs create mode 100644 xtask/src/result.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 000000000..4b0140061 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run --manifest-path xtask/Cargo.toml --" diff --git a/.github/workflows/validation-linux.yml b/.github/workflows/validation-linux.yml index e253e0a42..0c1525e7d 100644 --- a/.github/workflows/validation-linux.yml +++ b/.github/workflows/validation-linux.yml @@ -8,6 +8,7 @@ on: - 'tests/out/dot/*.dot' - 'tests/out/wgsl/*.wgsl' - 'src/front/wgsl/*' + - 'xtask/**' jobs: validate-linux: @@ -19,10 +20,15 @@ jobs: - name: Install tools run: sudo apt-get install spirv-tools glslang-tools graphviz - - run: make validate-spv + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + xtask -> target - - run: make validate-glsl + - run: cargo xtask validate spv - - run: make validate-dot + - run: cargo xtask validate glsl - - run: make validate-wgsl + - run: cargo xtask validate dot + + - run: cargo xtask validate wgsl diff --git a/.github/workflows/validation-macos.yml b/.github/workflows/validation-macos.yml index 535a0622b..c06563dc1 100644 --- a/.github/workflows/validation-macos.yml +++ b/.github/workflows/validation-macos.yml @@ -4,6 +4,7 @@ on: paths: - '.github/workflows/validation-macos.yml' - 'tests/out/msl/*.msl' + - 'xtask/**' jobs: validate-macos: @@ -12,4 +13,9 @@ jobs: steps: - uses: actions/checkout@v3 - - run: make validate-msl + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + xtask -> target + + - run: cargo xtask validate msl diff --git a/.github/workflows/validation-windows.yml b/.github/workflows/validation-windows.yml index 03942a678..9278f89df 100644 --- a/.github/workflows/validation-windows.yml +++ b/.github/workflows/validation-windows.yml @@ -4,6 +4,7 @@ on: paths: - '.github/workflows/validation-windows.yml' - 'tests/out/hlsl/*.hlsl' + - 'xtask/**' jobs: validate-windows-dxc: @@ -15,8 +16,12 @@ jobs: - name: Add DirectXShaderCompiler uses: napokue/setup-dxc@v1.1.0 - - run: make validate-hlsl-dxc - shell: sh + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + xtask -> target + + - run: cargo xtask validate hlsl dxc validate-windows-fxc: name: HLSL via FXC @@ -33,5 +38,9 @@ jobs: | Out-File -FilePath $Env:GITHUB_PATH -Encoding utf8 -Append shell: powershell - - run: make validate-hlsl-fxc - shell: sh + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + xtask -> target + + - run: cargo xtask validate hlsl fxc diff --git a/Cargo.toml b/Cargo.toml index 7417995dc..e01d50688 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,7 @@ unicode-xid = { version = "0.2.3", optional = true } bincode = "1" criterion = { version = "0.3", features = [] } diff = "0.1" +hlsl-snapshots = { path = "./xtask/hlsl-snapshots"} # Require at least version 0.7.1 of ron, this version changed how floating points are # serialized by forcing them to always have the decimal part, this makes it backwards # incompatible with our tests because we do a syntatic diff and not a semantic one. diff --git a/Makefile b/Makefile deleted file mode 100644 index 606e616bd..000000000 --- a/Makefile +++ /dev/null @@ -1,131 +0,0 @@ -.PHONY: all clean validate-spv validate-msl validate-glsl validate-dot validate-wgsl validate-hlsl-dxc validate-hlsl-fxc -.SECONDARY: boids.metal quad.metal -SNAPSHOTS_BASE_IN=tests/in -SNAPSHOTS_BASE_OUT=tests/out - -all: - cargo fmt - cargo test --all-features --workspace - cargo clippy --all-features --workspace -- -D warnings - -clean: - rm *.metal *.air *.metallib *.vert *.frag *.comp *.spv - -bench: - #rm -Rf target/criterion - cargo bench - -%.metal: $(SNAPSHOTS_BASE_IN)/%.wgsl $(wildcard src/*.rs src/**/*.rs examples/*.rs) - cargo run --features wgsl-in,msl-out -- $< $@ - -%.air: %.metal - xcrun -sdk macosx metal -c $< -mmacosx-version-min=10.11 - -%.metallib: %.air - xcrun -sdk macosx metallib $< -o $@ - -%.dot: $(SNAPSHOTS_BASE_IN)/%.wgsl $(wildcard src/*.rs src/front/wgsl/*.rs src/back/dot/*.rs bin/naga.rs) - cargo run --features wgsl-in,dot-out -- $< $@ - -%.png: %.dot - dot -Tpng $< -o $@ - -validate-spv: $(SNAPSHOTS_BASE_OUT)/spv/*.spvasm - @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ - version_line=$$(head -2 $${file} | tail -1); \ - version=$${version_line#"; Version: "};\ - cat $${file} | spirv-as --target-env spv$${version} - -o - | spirv-val -; \ - done - -validate-msl: $(SNAPSHOTS_BASE_OUT)/msl/*.msl - @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ - header=$$(head -n1 $${file}); \ - cat $${file} | xcrun -sdk macosx metal -mmacosx-version-min=10.11 -std=macos-$${header:13:8} -x metal - -o /dev/null; \ - done - -validate-glsl: $(SNAPSHOTS_BASE_OUT)/glsl/*.glsl - @set -e && for file in $(SNAPSHOTS_BASE_OUT)/glsl/*.Vertex.glsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"};\ - cat $${file} | glslangValidator --stdin -S vert; \ - done - @set -e && for file in $(SNAPSHOTS_BASE_OUT)/glsl/*.Fragment.glsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"};\ - cat $${file} | glslangValidator --stdin -S frag; \ - done - @set -e && for file in $(SNAPSHOTS_BASE_OUT)/glsl/*.Compute.glsl ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"};\ - cat $${file} | glslangValidator --stdin -S comp; \ - done - -validate-dot: $(SNAPSHOTS_BASE_OUT)/dot/*.dot - @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ - cat $${file} | dot -o /dev/null; \ - done - -validate-wgsl: $(SNAPSHOTS_BASE_OUT)/wgsl/*.wgsl - @set -e && for file in $^ ; do \ - echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ - cargo run $${file}; \ - done - -validate-hlsl-dxc: SHELL:=/usr/bin/env bash # required because config files uses arrays -validate-hlsl-dxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl - @set -e && for file in $^ ; do \ - DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug -Od"; \ - echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ - config="$$(dirname $${file})/$$(basename $${file}).config"; \ - . $${config}; \ - for (( i=0; i<$${#vertex[@]}; i++ )); do \ - name=`echo $${vertex[i]} | cut -d \: -f 1`; \ - profile=`echo $${vertex[i]} | cut -d \: -f 2`; \ - (set -x; dxc $${file} -T $${profile} -E $${name} $${DXC_PARAMS} > /dev/null); \ - done; \ - for (( i=0; i<$${#fragment[@]}; i++ )); do \ - name=`echo $${fragment[i]} | cut -d \: -f 1`; \ - profile=`echo $${fragment[i]} | cut -d \: -f 2`; \ - (set -x; dxc $${file} -T $${profile} -E $${name} $${DXC_PARAMS} > /dev/null); \ - done; \ - for (( i=0; i<$${#compute[@]}; i++ )); do \ - name=`echo $${compute[i]} | cut -d \: -f 1`; \ - profile=`echo $${compute[i]} | cut -d \: -f 2`; \ - (set -x; dxc $${file} -T $${profile} -E $${name} $${DXC_PARAMS} > /dev/null); \ - done; \ - echo "======================"; \ - done - -validate-hlsl-fxc: SHELL:=/usr/bin/env bash # required because config files uses arrays -validate-hlsl-fxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl - @set -e && for file in $^ ; do \ - FXC_PARAMS="-Zi -Od"; \ - echo "Validating" $${file#"$(SNAPSHOTS_BASE_OUT)/"}; \ - config="$$(dirname $${file})/$$(basename $${file}).config"; \ - . $${config}; \ - for (( i=0; i<$${#vertex[@]}; i++ )); do \ - name=`echo $${vertex[i]} | cut -d \: -f 1`; \ - profile=`echo $${vertex[i]} | cut -d \: -f 2`; \ - sm=`echo $${profile} | cut -d \_ -f 2`; \ - if (( sm < 6 )); then \ - (set -x; fxc $${file} -T $${profile} -E $${name} $${FXC_PARAMS} > /dev/null); \ - fi \ - done; \ - for (( i=0; i<$${#fragment[@]}; i++ )); do \ - name=`echo $${fragment[i]} | cut -d \: -f 1`; \ - profile=`echo $${fragment[i]} | cut -d \: -f 2`; \ - sm=`echo $${profile} | cut -d \_ -f 2`; \ - if (( sm < 6 )); then \ - (set -x; fxc $${file} -T $${profile} -E $${name} $${FXC_PARAMS} > /dev/null); \ - fi \ - done; \ - for (( i=0; i<$${#compute[@]}; i++ )); do \ - name=`echo $${compute[i]} | cut -d \: -f 1`; \ - profile=`echo $${compute[i]} | cut -d \: -f 2`; \ - sm=`echo $${profile} | cut -d \_ -f 2`; \ - if (( sm < 6 )); then \ - (set -x; fxc $${file} -T $${profile} -E $${name} $${FXC_PARAMS} > /dev/null); \ - fi \ - done; \ - echo "======================"; \ - done diff --git a/tests/out/hlsl/access.hlsl.config b/tests/out/hlsl/access.hlsl.config deleted file mode 100644 index de7719bdf..000000000 --- a/tests/out/hlsl/access.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(foo_vert:vs_5_1 ) -fragment=(foo_frag:ps_5_1 ) -compute=(assign_through_ptr:cs_5_1 ) diff --git a/tests/out/hlsl/access.ron b/tests/out/hlsl/access.ron new file mode 100644 index 000000000..73c9e4444 --- /dev/null +++ b/tests/out/hlsl/access.ron @@ -0,0 +1,20 @@ +( + vertex:[ + ( + entry_point:"foo_vert", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ( + entry_point:"foo_frag", + target_profile:"ps_5_1", + ), + ], + compute:[ + ( + entry_point:"assign_through_ptr", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/array-in-ctor.hlsl.config b/tests/out/hlsl/array-in-ctor.hlsl.config deleted file mode 100644 index 522d99ed1..000000000 --- a/tests/out/hlsl/array-in-ctor.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(cs_main:cs_5_1 ) diff --git a/tests/out/hlsl/array-in-ctor.ron b/tests/out/hlsl/array-in-ctor.ron new file mode 100644 index 000000000..5c261e59b --- /dev/null +++ b/tests/out/hlsl/array-in-ctor.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"cs_main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/atomicOps.hlsl.config b/tests/out/hlsl/atomicOps.hlsl.config deleted file mode 100644 index 522d99ed1..000000000 --- a/tests/out/hlsl/atomicOps.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(cs_main:cs_5_1 ) diff --git a/tests/out/hlsl/atomicOps.ron b/tests/out/hlsl/atomicOps.ron new file mode 100644 index 000000000..5c261e59b --- /dev/null +++ b/tests/out/hlsl/atomicOps.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"cs_main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/binding-arrays.hlsl.config b/tests/out/hlsl/binding-arrays.hlsl.config deleted file mode 100644 index 98453a04e..000000000 --- a/tests/out/hlsl/binding-arrays.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=(main:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/binding-arrays.ron b/tests/out/hlsl/binding-arrays.ron new file mode 100644 index 000000000..341a4c528 --- /dev/null +++ b/tests/out/hlsl/binding-arrays.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/bitcast.hlsl.config b/tests/out/hlsl/bitcast.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/bitcast.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/bitcast.ron b/tests/out/hlsl/bitcast.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/bitcast.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/boids.hlsl.config b/tests/out/hlsl/boids.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/boids.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/boids.ron b/tests/out/hlsl/boids.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/boids.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/break-if.hlsl.config b/tests/out/hlsl/break-if.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/break-if.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/break-if.ron b/tests/out/hlsl/break-if.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/break-if.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/collatz.hlsl.config b/tests/out/hlsl/collatz.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/collatz.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/collatz.ron b/tests/out/hlsl/collatz.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/collatz.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/control-flow.hlsl.config b/tests/out/hlsl/control-flow.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/control-flow.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/control-flow.ron b/tests/out/hlsl/control-flow.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/control-flow.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/do-while.hlsl.config b/tests/out/hlsl/do-while.hlsl.config deleted file mode 100644 index 98453a04e..000000000 --- a/tests/out/hlsl/do-while.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=(main:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/do-while.ron b/tests/out/hlsl/do-while.ron new file mode 100644 index 000000000..341a4c528 --- /dev/null +++ b/tests/out/hlsl/do-while.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/empty-global-name.hlsl.config b/tests/out/hlsl/empty-global-name.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/empty-global-name.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/empty-global-name.ron b/tests/out/hlsl/empty-global-name.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/empty-global-name.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/empty.hlsl.config b/tests/out/hlsl/empty.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/empty.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/empty.ron b/tests/out/hlsl/empty.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/empty.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/fragment-output.hlsl.config b/tests/out/hlsl/fragment-output.hlsl.config deleted file mode 100644 index 2bf0efbf7..000000000 --- a/tests/out/hlsl/fragment-output.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=(main_vec4vec3_:ps_5_1 main_vec2scalar:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/fragment-output.ron b/tests/out/hlsl/fragment-output.ron new file mode 100644 index 000000000..9dfaf7393 --- /dev/null +++ b/tests/out/hlsl/fragment-output.ron @@ -0,0 +1,16 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"main_vec4vec3_", + target_profile:"ps_5_1", + ), + ( + entry_point:"main_vec2scalar", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/functions.hlsl.config b/tests/out/hlsl/functions.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/functions.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/functions.ron b/tests/out/hlsl/functions.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/functions.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/globals.hlsl.config b/tests/out/hlsl/globals.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/globals.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/globals.ron b/tests/out/hlsl/globals.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/globals.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/hlsl-keyword.hlsl.config b/tests/out/hlsl/hlsl-keyword.hlsl.config deleted file mode 100644 index b9f047558..000000000 --- a/tests/out/hlsl/hlsl-keyword.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=(fs_main:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/hlsl-keyword.ron b/tests/out/hlsl/hlsl-keyword.ron new file mode 100644 index 000000000..eac1b945d --- /dev/null +++ b/tests/out/hlsl/hlsl-keyword.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"fs_main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config deleted file mode 100644 index 8194e213f..000000000 --- a/tests/out/hlsl/image.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(queries:vs_5_1 levels_queries:vs_5_1 ) -fragment=(texture_sample:ps_5_1 texture_sample_comparison:ps_5_1 gather:ps_5_1 depth_no_comparison:ps_5_1 ) -compute=(main:cs_5_1 depth_load:cs_5_1 ) diff --git a/tests/out/hlsl/image.ron b/tests/out/hlsl/image.ron new file mode 100644 index 000000000..f5ca4931d --- /dev/null +++ b/tests/out/hlsl/image.ron @@ -0,0 +1,40 @@ +( + vertex:[ + ( + entry_point:"queries", + target_profile:"vs_5_1", + ), + ( + entry_point:"levels_queries", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ( + entry_point:"texture_sample", + target_profile:"ps_5_1", + ), + ( + entry_point:"texture_sample_comparison", + target_profile:"ps_5_1", + ), + ( + entry_point:"gather", + target_profile:"ps_5_1", + ), + ( + entry_point:"depth_no_comparison", + target_profile:"ps_5_1", + ), + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ( + entry_point:"depth_load", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/interface.hlsl.config b/tests/out/hlsl/interface.hlsl.config deleted file mode 100644 index d7e51aecf..000000000 --- a/tests/out/hlsl/interface.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(vertex:vs_5_1 vertex_two_structs:vs_5_1 ) -fragment=(fragment:ps_5_1 ) -compute=(compute:cs_5_1 ) diff --git a/tests/out/hlsl/interface.ron b/tests/out/hlsl/interface.ron new file mode 100644 index 000000000..948962b99 --- /dev/null +++ b/tests/out/hlsl/interface.ron @@ -0,0 +1,24 @@ +( + vertex:[ + ( + entry_point:"vertex", + target_profile:"vs_5_1", + ), + ( + entry_point:"vertex_two_structs", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ( + entry_point:"fragment", + target_profile:"ps_5_1", + ), + ], + compute:[ + ( + entry_point:"compute", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/interpolate.hlsl.config b/tests/out/hlsl/interpolate.hlsl.config deleted file mode 100644 index e08910d1e..000000000 --- a/tests/out/hlsl/interpolate.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(vert_main:vs_5_1 ) -fragment=(frag_main:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/interpolate.ron b/tests/out/hlsl/interpolate.ron new file mode 100644 index 000000000..d0046b04d --- /dev/null +++ b/tests/out/hlsl/interpolate.ron @@ -0,0 +1,16 @@ +( + vertex:[ + ( + entry_point:"vert_main", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ( + entry_point:"frag_main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config deleted file mode 100644 index 98453a04e..000000000 --- a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=(main:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.ron b/tests/out/hlsl/inv-hyperbolic-trig-functions.ron new file mode 100644 index 000000000..341a4c528 --- /dev/null +++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/math-functions.hlsl.config b/tests/out/hlsl/math-functions.hlsl.config deleted file mode 100644 index 98453a04e..000000000 --- a/tests/out/hlsl/math-functions.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=(main:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/math-functions.ron b/tests/out/hlsl/math-functions.ron new file mode 100644 index 000000000..341a4c528 --- /dev/null +++ b/tests/out/hlsl/math-functions.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/operators.hlsl.config b/tests/out/hlsl/operators.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/operators.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/operators.ron b/tests/out/hlsl/operators.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/operators.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/padding.hlsl.config b/tests/out/hlsl/padding.hlsl.config deleted file mode 100644 index 875a4fa4a..000000000 --- a/tests/out/hlsl/padding.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(vertex:vs_5_1 ) -fragment=() -compute=() diff --git a/tests/out/hlsl/padding.ron b/tests/out/hlsl/padding.ron new file mode 100644 index 000000000..46dfdd83e --- /dev/null +++ b/tests/out/hlsl/padding.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ( + entry_point:"vertex", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/push-constants.hlsl.config b/tests/out/hlsl/push-constants.hlsl.config deleted file mode 100644 index f214655f7..000000000 --- a/tests/out/hlsl/push-constants.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(vert_main:vs_5_1 ) -fragment=(main:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/push-constants.ron b/tests/out/hlsl/push-constants.ron new file mode 100644 index 000000000..e44448655 --- /dev/null +++ b/tests/out/hlsl/push-constants.ron @@ -0,0 +1,16 @@ +( + vertex:[ + ( + entry_point:"vert_main", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ( + entry_point:"main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/quad-vert.hlsl.config b/tests/out/hlsl/quad-vert.hlsl.config deleted file mode 100644 index f72fafd91..000000000 --- a/tests/out/hlsl/quad-vert.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(main:vs_5_1 ) -fragment=() -compute=() diff --git a/tests/out/hlsl/quad-vert.ron b/tests/out/hlsl/quad-vert.ron new file mode 100644 index 000000000..8240856a5 --- /dev/null +++ b/tests/out/hlsl/quad-vert.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ( + entry_point:"main", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config deleted file mode 100644 index 7a37fc4b0..000000000 --- a/tests/out/hlsl/quad.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(vert_main:vs_5_1 ) -fragment=(frag_main:ps_5_1 fs_extra:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/quad.ron b/tests/out/hlsl/quad.ron new file mode 100644 index 000000000..de9055235 --- /dev/null +++ b/tests/out/hlsl/quad.ron @@ -0,0 +1,20 @@ +( + vertex:[ + ( + entry_point:"vert_main", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ( + entry_point:"frag_main", + target_profile:"ps_5_1", + ), + ( + entry_point:"fs_extra", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/shadow.hlsl.config b/tests/out/hlsl/shadow.hlsl.config deleted file mode 100644 index 40d109c83..000000000 --- a/tests/out/hlsl/shadow.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(vs_main:vs_5_1 ) -fragment=(fs_main:ps_5_1 fs_main_without_storage:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/shadow.ron b/tests/out/hlsl/shadow.ron new file mode 100644 index 000000000..69be5b25e --- /dev/null +++ b/tests/out/hlsl/shadow.ron @@ -0,0 +1,20 @@ +( + vertex:[ + ( + entry_point:"vs_main", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ( + entry_point:"fs_main", + target_profile:"ps_5_1", + ), + ( + entry_point:"fs_main_without_storage", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/skybox.hlsl.config b/tests/out/hlsl/skybox.hlsl.config deleted file mode 100644 index 541ec2175..000000000 --- a/tests/out/hlsl/skybox.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=(vs_main:vs_5_1 ) -fragment=(fs_main:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/skybox.ron b/tests/out/hlsl/skybox.ron new file mode 100644 index 000000000..27b0c4af4 --- /dev/null +++ b/tests/out/hlsl/skybox.ron @@ -0,0 +1,16 @@ +( + vertex:[ + ( + entry_point:"vs_main", + target_profile:"vs_5_1", + ), + ], + fragment:[ + ( + entry_point:"fs_main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/standard.hlsl.config b/tests/out/hlsl/standard.hlsl.config deleted file mode 100644 index a2606f3ab..000000000 --- a/tests/out/hlsl/standard.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=(derivatives:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/standard.ron b/tests/out/hlsl/standard.ron new file mode 100644 index 000000000..82373299d --- /dev/null +++ b/tests/out/hlsl/standard.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"derivatives", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/texture-arg.hlsl.config b/tests/out/hlsl/texture-arg.hlsl.config deleted file mode 100644 index 98453a04e..000000000 --- a/tests/out/hlsl/texture-arg.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=(main:ps_5_1 ) -compute=() diff --git a/tests/out/hlsl/texture-arg.ron b/tests/out/hlsl/texture-arg.ron new file mode 100644 index 000000000..341a4c528 --- /dev/null +++ b/tests/out/hlsl/texture-arg.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/hlsl/workgroup-uniform-load.hlsl.config b/tests/out/hlsl/workgroup-uniform-load.hlsl.config deleted file mode 100644 index 648d3b0d9..000000000 --- a/tests/out/hlsl/workgroup-uniform-load.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(test_workgroupUniformLoad:cs_5_1 ) diff --git a/tests/out/hlsl/workgroup-uniform-load.ron b/tests/out/hlsl/workgroup-uniform-load.ron new file mode 100644 index 000000000..17e926cde --- /dev/null +++ b/tests/out/hlsl/workgroup-uniform-load.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"test_workgroupUniformLoad", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/workgroup-var-init.hlsl.config b/tests/out/hlsl/workgroup-var-init.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/workgroup-var-init.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/workgroup-var-init.ron b/tests/out/hlsl/workgroup-var-init.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/workgroup-var-init.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e51c6ced4..1ea52b46c 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -348,56 +348,30 @@ fn write_output_hlsl( // We need a config file for validation script // This file contains an info about profiles (shader stages) contains inside generated shader // This info will be passed to dxc - let mut config_str = String::new(); - let mut vertex_str = String::from("vertex=("); - let mut fragment_str = String::from("fragment=("); - let mut compute_str = String::from("compute=("); + let mut config = hlsl_snapshots::Config::empty(); for (index, ep) in module.entry_points.iter().enumerate() { let name = match reflection_info.entry_point_names[index] { Ok(ref name) => name, Err(_) => continue, }; match ep.stage { - naga::ShaderStage::Vertex => { - write!( - vertex_str, - "{}:{}_{} ", - name, - ep.stage.to_hlsl_str(), - options.shader_model.to_str(), - ) - .unwrap(); - } - naga::ShaderStage::Fragment => { - write!( - fragment_str, - "{}:{}_{} ", - name, - ep.stage.to_hlsl_str(), - options.shader_model.to_str(), - ) - .unwrap(); - } - naga::ShaderStage::Compute => { - write!( - compute_str, - "{}:{}_{} ", - name, - ep.stage.to_hlsl_str(), - options.shader_model.to_str(), - ) - .unwrap(); - } + naga::ShaderStage::Vertex => &mut config.vertex, + naga::ShaderStage::Fragment => &mut config.fragment, + naga::ShaderStage::Compute => &mut config.compute, } + .push(hlsl_snapshots::ConfigItem { + entry_point: name.clone(), + target_profile: format!( + "{}_{}", + ep.stage.to_hlsl_str(), + options.shader_model.to_str() + ), + }); } - writeln!(config_str, "{vertex_str})\n{fragment_str})\n{compute_str})").unwrap(); - - fs::write( - destination.join(format!("hlsl/{file_name}.hlsl.config")), - config_str, - ) - .unwrap(); + config + .to_file(destination.join(format!("hlsl/{file_name}.ron"))) + .unwrap(); } #[cfg(feature = "wgsl-out")] diff --git a/xtask/.gitignore b/xtask/.gitignore new file mode 100644 index 000000000..c7ee281fa --- /dev/null +++ b/xtask/.gitignore @@ -0,0 +1,2 @@ +!Cargo.lock +target/ diff --git a/xtask/Cargo.lock b/xtask/Cargo.lock new file mode 100644 index 000000000..88ece956b --- /dev/null +++ b/xtask/Cargo.lock @@ -0,0 +1,117 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "anyhow" +version = "1.0.70" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de8ce5e0f9f8d88245311066a578d72b7af3e7088f32783804676302df237e4" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "either" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" + +[[package]] +name = "env_logger" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" +dependencies = [ + "log", +] + +[[package]] +name = "glob" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" + +[[package]] +name = "hlsl-snapshots" +version = "0.1.0" +dependencies = [ + "anyhow", + "nanoserde", +] + +[[package]] +name = "libc" +version = "0.2.140" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99227334921fae1a979cf0bfdfcc6b3e5ce376ef57e16fb6fb3ea2ed6095f80c" + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "nanoserde" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "755e7965536bc54d7c9fba2df5ada5bf835b0443fd613f0a53fa199a301839d3" +dependencies = [ + "nanoserde-derive", +] + +[[package]] +name = "nanoserde-derive" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed7a94da6c6181c35d043fc61c43ac96d3a5d739e7b8027f77650ba41504d6ab" + +[[package]] +name = "once_cell" +version = "1.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "shell-words" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" + +[[package]] +name = "which" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2441c784c52b289a054b7201fc93253e288f094e2f4be9058343127c4226a269" +dependencies = [ + "either", + "libc", + "once_cell", +] + +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "env_logger", + "glob", + "hlsl-snapshots", + "log", + "pico-args", + "shell-words", + "which", +] diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 000000000..4214df66f --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "xtask" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] +anyhow = "1" +env_logger = { version = "0.10.0", default-features = false } +glob = "0.3.1" +hlsl-snapshots = { path = "./hlsl-snapshots"} +log = "0.4.17" +pico-args = "0.5.0" +shell-words = "1.1.0" +which = "4.4.0" + +[workspace] + +members = [".", "./hlsl-snapshots"] diff --git a/xtask/hlsl-snapshots/Cargo.toml b/xtask/hlsl-snapshots/Cargo.toml new file mode 100644 index 000000000..8cd662ef4 --- /dev/null +++ b/xtask/hlsl-snapshots/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "hlsl-snapshots" +version = "0.1.0" +edition = "2021" + +[dependencies] +anyhow = "1" +nanoserde = "0.1.32" diff --git a/xtask/hlsl-snapshots/src/lib.rs b/xtask/hlsl-snapshots/src/lib.rs new file mode 100644 index 000000000..616aa73f0 --- /dev/null +++ b/xtask/hlsl-snapshots/src/lib.rs @@ -0,0 +1,97 @@ +use std::{error::Error, fmt::Display, fs, io, path::Path}; + +use anyhow::{anyhow, ensure}; +use nanoserde::{self, DeRon, DeRonErr, SerRon}; + +#[derive(Debug)] +struct BadRonParse(BadRonParseKind); + +impl Display for BadRonParse { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "failed to read RON configuration of HLSL snapshot test") + } +} + +impl Error for BadRonParse { + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(&self.0) + } +} + +#[derive(Debug)] +enum BadRonParseKind { + Read { source: io::Error }, + Parse { source: DeRonErr }, + Empty, +} + +impl Display for BadRonParseKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + BadRonParseKind::Read { source } => Display::fmt(source, f), + BadRonParseKind::Parse { source } => Display::fmt(source, f), + BadRonParseKind::Empty => write!(f, "no configuration was specified"), + } + } +} + +impl Error for BadRonParseKind { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + BadRonParseKind::Read { source } => source.source(), + BadRonParseKind::Parse { source } => source.source(), + BadRonParseKind::Empty => None, + } + } +} + +#[derive(Debug, DeRon, SerRon)] +pub struct Config { + pub vertex: Vec, + pub fragment: Vec, + pub compute: Vec, +} + +impl Config { + pub fn empty() -> Self { + Self { + vertex: Default::default(), + fragment: Default::default(), + compute: Default::default(), + } + } + + pub fn from_path(path: impl AsRef) -> anyhow::Result { + let path = path.as_ref(); + let raw_config = fs::read_to_string(path) + .map_err(|source| BadRonParse(BadRonParseKind::Read { source }))?; + let config = Config::deserialize_ron(&raw_config) + .map_err(|source| BadRonParse(BadRonParseKind::Parse { source }))?; + ensure!(!config.is_empty(), BadRonParse(BadRonParseKind::Empty)); + Ok(config) + } + + pub fn to_file(&self, path: impl AsRef) -> anyhow::Result<()> { + let path = path.as_ref(); + let mut s = self.serialize_ron(); + s.push('\n'); + fs::write(path, &s).map_err(|e| anyhow!("failed to write to {}: {e}", path.display())) + } + + pub fn is_empty(&self) -> bool { + let Self { + vertex, + fragment, + compute, + } = self; + vertex.is_empty() && fragment.is_empty() && compute.is_empty() + } +} + +#[derive(Debug, DeRon, SerRon)] +pub struct ConfigItem { + pub entry_point: String, + /// See also + /// . + pub target_profile: String, +} diff --git a/xtask/src/cli.rs b/xtask/src/cli.rs new file mode 100644 index 000000000..c6fd6d2a6 --- /dev/null +++ b/xtask/src/cli.rs @@ -0,0 +1,160 @@ +use std::process::exit; + +use anyhow::{anyhow, bail, ensure, Context}; +use pico_args::Arguments; + +const HELP: &str = "\ +Usage: xtask + +Commands: + all + bench [--clean] + validate + dot + glsl + hlsl + dxc + fxc + msl + spv + +Options: + -h, --help Print help +"; + +#[derive(Debug)] +pub(crate) struct Args { + pub subcommand: Subcommand, +} + +impl Args { + pub fn parse() -> Self { + let mut args = Arguments::from_env(); + log::debug!("parsing args: {args:?}"); + if args.contains("--help") { + eprint!("{HELP}"); + exit(101); + } + match (|| -> anyhow::Result<_> { + let subcommand = Subcommand::parse(args)?; + Ok(Self { subcommand }) + })() { + Ok(this) => this, + Err(e) => { + eprintln!("{:?}", anyhow!(e)); + exit(1) + } + } + } +} + +#[derive(Debug)] +pub(crate) enum Subcommand { + All, + Bench { clean: bool }, + Validate(ValidateSubcommand), +} + +impl Subcommand { + fn parse(mut args: Arguments) -> anyhow::Result { + args.subcommand() + .context("failed to parse subcommand") + .and_then(|parsed| match parsed.as_deref() { + None => bail!("no subcommand specified; see `--help` for more details"), + Some("all") => { + ensure_remaining_args_empty(args)?; + Ok(Self::All) + } + Some("bench") => { + let clean = args.contains("--clean"); + ensure_remaining_args_empty(args)?; + Ok(Self::Bench { clean }) + } + Some("validate") => Ok(Self::Validate(ValidateSubcommand::parse(args)?)), + Some(other) => { + bail!("unrecognized subcommand {other:?}; see `--help` for more details") + } + }) + } +} + +#[derive(Debug)] +pub(crate) enum ValidateSubcommand { + Spirv, + Metal, + Glsl, + Dot, + Wgsl, + Hlsl(ValidateHlslCommand), +} + +impl ValidateSubcommand { + fn parse(mut args: Arguments) -> Result { + args.subcommand() + .context("failed to parse `validate` subcommand") + .and_then(|parsed| match parsed.as_deref() { + None => bail!("no `validate` subcommand specified; see `--help` for more details"), + Some("spv") => { + ensure_remaining_args_empty(args)?; + Ok(Self::Spirv) + } + Some("msl") => { + ensure_remaining_args_empty(args)?; + Ok(Self::Metal) + } + Some("glsl") => { + ensure_remaining_args_empty(args)?; + Ok(Self::Glsl) + } + Some("dot") => { + ensure_remaining_args_empty(args)?; + Ok(Self::Dot) + } + Some("wgsl") => { + ensure_remaining_args_empty(args)?; + Ok(Self::Wgsl) + } + Some("hlsl") => Ok(Self::Hlsl(ValidateHlslCommand::parse(args)?)), + Some(other) => bail!( + "unrecognized `validate` subcommand {other:?}; see `--help` for more details" + ), + }) + } +} + +#[derive(Debug)] +pub(crate) enum ValidateHlslCommand { + Dxc, + Fxc, +} + +impl ValidateHlslCommand { + fn parse(mut args: Arguments) -> anyhow::Result { + args.subcommand() + .context("failed to parse `hlsl` subcommand") + .and_then(|parsed| match parsed.as_deref() { + None => bail!("no `hlsl` subcommand specified; see `--help` for more details"), + Some("dxc") => { + ensure_remaining_args_empty(args)?; + Ok(Self::Dxc) + } + Some("fxc") => { + ensure_remaining_args_empty(args)?; + Ok(Self::Fxc) + } + Some(other) => { + bail!("unrecognized `hlsl` subcommand {other:?}; see `--help` for more details") + } + }) + } +} + +fn ensure_remaining_args_empty(args: Arguments) -> anyhow::Result<()> { + let remaining_args = args.finish(); + ensure!( + remaining_args.is_empty(), + "not all arguments were parsed (remaining: {remaining_args:?}); fix your invocation, \ + please!" + ); + Ok(()) +} diff --git a/xtask/src/fs.rs b/xtask/src/fs.rs new file mode 100644 index 000000000..98870fc9f --- /dev/null +++ b/xtask/src/fs.rs @@ -0,0 +1,10 @@ +use std::{fs::File, path::Path}; + +use anyhow::Context; + +pub(crate) use std::fs::*; + +pub(crate) fn open_file(path: impl AsRef) -> anyhow::Result { + let path = path.as_ref(); + File::open(path).with_context(|| format!("failed to open {path:?}")) +} diff --git a/xtask/src/glob.rs b/xtask/src/glob.rs new file mode 100644 index 000000000..d69891e78 --- /dev/null +++ b/xtask/src/glob.rs @@ -0,0 +1,37 @@ +use std::path::Path; + +use anyhow::Context; +use glob::glob; + +use crate::result::{ErrorStatus, LogIfError}; + +pub(crate) fn visit_files( + path: impl AsRef, + glob_expr: &str, + mut f: impl FnMut(&Path) -> anyhow::Result<()>, +) -> ErrorStatus { + let path = path.as_ref(); + let glob_expr = path.join(glob_expr); + let glob_expr = glob_expr.to_str().unwrap(); + + let mut status = ErrorStatus::NoFailuresFound; + glob(glob_expr) + .context("glob pattern {path:?} is invalid") + .unwrap() + .for_each(|path_res| { + if let Some(path) = path_res + .with_context(|| format!("error while iterating over glob {path:?}")) + .log_if_err_found(&mut status) + { + if path + .metadata() + .with_context(|| format!("failed to fetch metadata for {path:?}")) + .log_if_err_found(&mut status) + .map_or(false, |m| m.is_file()) + { + f(&path).log_if_err_found(&mut status); + } + } + }); + status +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 000000000..17156db73 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,305 @@ +use std::{ + io::{BufRead, BufReader}, + path::Path, + process::{ExitCode, Stdio}, +}; + +use anyhow::{bail, Context}; +use cli::Args; + +use crate::{ + cli::{Subcommand, ValidateHlslCommand, ValidateSubcommand}, + fs::{open_file, remove_dir_all}, + glob::visit_files, + path::join_path, + process::{which, EasyCommand}, + result::{ErrorStatus, LogIfError}, +}; + +mod cli; +mod fs; +mod glob; +mod path; +mod process; +mod result; + +fn main() -> ExitCode { + env_logger::builder() + .filter_level(log::LevelFilter::Info) + .parse_default_env() + .format_indent(Some(0)) + .init(); + + let args = Args::parse(); + + match run(args) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + log::error!("{e:?}"); + ExitCode::FAILURE + } + } +} + +fn run(args: Args) -> anyhow::Result<()> { + let snapshots_base_out = join_path(["tests", "out"]); + + let Args { subcommand } = args; + + assert!(which("cargo").is_ok()); + + match subcommand { + Subcommand::All => { + EasyCommand::simple("cargo", ["fmt"]).success()?; + EasyCommand::simple("cargo", ["test", "--all-features", "--workspace"]).success()?; + EasyCommand::simple( + "cargo", + [ + "clippy", + "--all-features", + "--workspace", + "--", + "-D", + "warnings", + ], + ) + .success()?; + Ok(()) + } + Subcommand::Bench { clean } => { + if clean { + let criterion_artifact_dir = join_path(["target", "criterion"]); + log::info!("removing {}", criterion_artifact_dir.display()); + remove_dir_all(&criterion_artifact_dir) + .with_context(|| format!("failed to remove {criterion_artifact_dir:?}"))?; + } + EasyCommand::simple("cargo", ["bench"]).success() + } + Subcommand::Validate(cmd) => { + let ack_visiting = |path: &Path| log::info!("Validating {}", path.display()); + let err_status = match cmd { + ValidateSubcommand::Spirv => { + let spirv_as = "spirv-as"; + which(spirv_as)?; + + let spirv_val = "spirv-val"; + which(spirv_val)?; + + visit_files(snapshots_base_out, "spv/*.spvasm", |path| { + ack_visiting(path); + let second_line = { + let mut file = BufReader::new(open_file(path)?); + let mut buf = String::new(); + file.read_line(&mut buf).with_context(|| { + format!("failed to read first line from {path:?}") + })?; + buf.clear(); + file.read_line(&mut buf).with_context(|| { + format!("failed to read second line from {path:?}") + })?; + buf + }; + let expected_header_prefix = "; Version: "; + let Some(version) = + second_line.strip_prefix(expected_header_prefix) else { + bail!( + "no {expected_header_prefix:?} header found in {path:?}" + ); + }; + let file = open_file(path)?; + let mut spirv_as_cmd = EasyCommand::new(spirv_as, |cmd| { + cmd.stdin(Stdio::from(file)) + .stdout(Stdio::piped()) + .arg("--target-env") + .arg(format!("spv{version}")) + .args(["-", "-o", "-"]) + }); + let child = spirv_as_cmd + .spawn() + .with_context(|| format!("failed to spawn {cmd:?}"))?; + EasyCommand::new(spirv_val, |cmd| cmd.stdin(child.stdout.unwrap())) + .success() + }) + } + ValidateSubcommand::Metal => { + let xcrun = "xcrun"; + which(xcrun)?; + visit_files(snapshots_base_out, "msl/*.msl", |path| { + ack_visiting(path); + let first_line = { + let mut file = BufReader::new(open_file(path)?); + let mut buf = String::new(); + file.read_line(&mut buf) + .with_context(|| format!("failed to read header from {path:?}"))?; + buf + }; + let expected_header_prefix = "// language: "; + let Some(language) = + first_line.strip_prefix(expected_header_prefix) else { + bail!( + "no {expected_header_prefix:?} header found in {path:?}" + ); + }; + let language = language.strip_suffix('\n').unwrap_or(language); + + let file = open_file(path)?; + EasyCommand::new(xcrun, |cmd| { + cmd.stdin(Stdio::from(file)) + .args(["-sdk", "macosx", "metal", "-mmacosx-version-min=10.11"]) + .arg(format!("-std=macos-{language}")) + .args(["-x", "metal", "-", "-o", "/dev/null"]) + }) + .success() + }) + } + ValidateSubcommand::Glsl => { + let glslang_validator = "glslangValidator"; + which(glslang_validator)?; + let mut err_status = ErrorStatus::NoFailuresFound; + for (glob, type_arg) in [ + ("glsl/*.Vertex.glsl", "vert"), + ("glsl/*.Fragment.glsl", "frag"), + ("glsl/*.Compute.glsl", "comp"), + ] { + let type_err_status = visit_files(&snapshots_base_out, glob, |path| { + ack_visiting(path); + let file = open_file(path)?; + EasyCommand::new(glslang_validator, |cmd| { + cmd.stdin(Stdio::from(file)) + .args(["--stdin", "-S"]) + .arg(type_arg) + }) + .success() + }); + err_status = err_status.merge(type_err_status); + } + err_status + } + ValidateSubcommand::Dot => { + let dot = "dot"; + which(dot)?; + visit_files(snapshots_base_out, "dot/*.dot", |path| { + ack_visiting(path); + let file = open_file(path)?; + EasyCommand::new(dot, |cmd| { + cmd.stdin(Stdio::from(file)).stdout(Stdio::null()) + }) + .success() + }) + } + ValidateSubcommand::Wgsl => { + visit_files(snapshots_base_out, "wgsl/*.wgsl", |path| { + ack_visiting(path); + EasyCommand::new("cargo", |cmd| cmd.args(["run", "--"]).arg(path)).success() + }) + } + ValidateSubcommand::Hlsl(cmd) => { + let visit_hlsl = |consume_config_item: &mut dyn FnMut( + &Path, + hlsl_snapshots::ConfigItem, + ) + -> anyhow::Result<()>| { + visit_files(snapshots_base_out, "hlsl/*.hlsl", |path| { + ack_visiting(path); + let hlsl_snapshots::Config { + vertex, + fragment, + compute, + } = hlsl_snapshots::Config::from_path(path.with_extension("ron"))?; + let mut status = ErrorStatus::NoFailuresFound; + [vertex, fragment, compute] + .into_iter() + .flatten() + .for_each(|shader| { + consume_config_item(path, shader).log_if_err_found(&mut status); + }); + match status { + ErrorStatus::NoFailuresFound => Ok(()), + ErrorStatus::OneOrMoreFailuresFound => bail!( + "one or more shader HLSL shader tests failed for {}", + path.display() + ), + } + }) + }; + let validate = |bin, file: &_, config_item, params: &[_]| { + let hlsl_snapshots::ConfigItem { + entry_point, + target_profile, + } = config_item; + EasyCommand::new(bin, |cmd| { + cmd.arg(file) + .arg("-T") + .arg(&target_profile) + .arg("-E") + .arg(&entry_point) + .args(params) + .stdout(Stdio::null()) + }) + .success() + .with_context(|| { + format!( + "failed to validate entry point {entry_point:?} with profile \ + {target_profile:?}" + ) + }) + }; + match cmd { + ValidateHlslCommand::Dxc => { + let bin = "dxc"; + which(bin)?; + visit_hlsl(&mut |file, config_item| { + // Reference: + // . + validate( + bin, + file, + config_item, + &["-Wno-parentheses-equality", "-Zi", "-Qembed_debug", "-Od"], + ) + }) + } + ValidateHlslCommand::Fxc => { + let bin = "fxc"; + which(bin)?; + visit_hlsl(&mut |file, config_item| { + let Some(Ok(shader_model_major_version)) = config_item + .target_profile + .split('_') + .nth(1) + .map(|segment| segment.parse::()) else { + bail!( + "expected target profile of the form \ + `{{model}}_{{major}}_{{minor}}`, found invalid target \ + profile {:?} in file {}", + config_item.target_profile, + file.display() + ) + }; + // NOTE: This isn't implemented by `fxc.exe`; see + // . + if shader_model_major_version < 6 { + // Reference: + // . + validate(bin, file, config_item, &["-Zi", "-Od"]) + } else { + log::debug!( + "skipping config. item {config_item:?} because the \ + shader model major version is > 6" + ); + Ok(()) + } + }) + } + } + } + }; + match err_status { + ErrorStatus::NoFailuresFound => Ok(()), + ErrorStatus::OneOrMoreFailuresFound => { + bail!("failed to validate one or more files, see above output for more details") + } + } + } + } +} diff --git a/xtask/src/path.rs b/xtask/src/path.rs new file mode 100644 index 000000000..4ba3a0ba4 --- /dev/null +++ b/xtask/src/path.rs @@ -0,0 +1,11 @@ +use std::path::{Path, PathBuf}; + +pub(crate) fn join_path(iter: I) -> PathBuf +where + P: AsRef, + I: IntoIterator, +{ + let mut path = PathBuf::new(); + path.extend(iter); + path +} diff --git a/xtask/src/process.rs b/xtask/src/process.rs new file mode 100644 index 000000000..37a24f1b6 --- /dev/null +++ b/xtask/src/process.rs @@ -0,0 +1,78 @@ +use std::{ + ffi::{OsStr, OsString}, + fmt::{self, Display}, + iter::once, + ops::{Deref, DerefMut}, + process::Command, +}; + +use anyhow::{ensure, Context}; + +#[derive(Debug)] +pub(crate) struct EasyCommand { + inner: Command, +} + +impl EasyCommand { + pub fn new(cmd: C, config: impl FnOnce(&mut Command) -> &mut Command) -> Self + where + C: AsRef, + { + let mut inner = Command::new(cmd); + config(&mut inner); + Self { inner } + } + + pub fn simple(cmd: C, args: I) -> Self + where + C: AsRef, + A: AsRef, + I: IntoIterator, + { + Self::new(cmd, |cmd| cmd.args(args)) + } + + pub fn success(&mut self) -> anyhow::Result<()> { + let Self { inner } = self; + log::debug!("running {inner:?}"); + let status = inner + .status() + .with_context(|| format!("failed to run {self}"))?; + ensure!( + status.success(), + "{self} failed to run; exit code: {:?}", + status.code() + ); + Ok(()) + } +} + +impl Deref for EasyCommand { + type Target = Command; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl DerefMut for EasyCommand { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } +} + +pub(crate) fn which(binary_name: &str) -> anyhow::Result { + ::which::which(binary_name) + .with_context(|| format!("unable to find `{binary_name}` binary")) + .map(|buf| buf.file_name().unwrap().to_owned()) +} + +impl Display for EasyCommand { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { inner } = self; + let prog = inner.get_program().to_string_lossy(); + let args = inner.get_args().map(|a| a.to_string_lossy()); + let shell_words = shell_words::join(once(prog).chain(args)); + write!(f, "`{shell_words}`") + } +} diff --git a/xtask/src/result.rs b/xtask/src/result.rs new file mode 100644 index 000000000..e351ebf4c --- /dev/null +++ b/xtask/src/result.rs @@ -0,0 +1,33 @@ +#[derive(Clone, Copy, Debug)] +pub(crate) enum ErrorStatus { + NoFailuresFound, + OneOrMoreFailuresFound, +} + +impl ErrorStatus { + pub(crate) fn merge(self, other: Self) -> Self { + match (self, other) { + (Self::OneOrMoreFailuresFound, _) | (_, Self::OneOrMoreFailuresFound) => { + Self::OneOrMoreFailuresFound + } + (Self::NoFailuresFound, Self::NoFailuresFound) => Self::NoFailuresFound, + } + } +} + +pub(crate) trait LogIfError { + fn log_if_err_found(self, status: &mut ErrorStatus) -> Option; +} + +impl LogIfError for anyhow::Result { + fn log_if_err_found(self, status: &mut ErrorStatus) -> Option { + match self { + Ok(t) => Some(t), + Err(e) => { + log::error!("{e:?}"); + *status = status.merge(ErrorStatus::OneOrMoreFailuresFound); + None + } + } + } +} From daeb64c4298eef47b54de61b4acb9213bbc4f561 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Mon, 3 Apr 2023 14:34:16 -0400 Subject: [PATCH 2012/2212] build(ci): trigger for `ron` files in HLSL shader snapshot test config. --- .github/workflows/validation-windows.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/validation-windows.yml b/.github/workflows/validation-windows.yml index 9278f89df..d84b44f62 100644 --- a/.github/workflows/validation-windows.yml +++ b/.github/workflows/validation-windows.yml @@ -4,6 +4,7 @@ on: paths: - '.github/workflows/validation-windows.yml' - 'tests/out/hlsl/*.hlsl' + - 'tests/out/hlsl/*.ron' - 'xtask/**' jobs: From 273ff5d829f8207d8d93b70e32e2889362246d33 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Mon, 3 Apr 2023 16:01:16 -0400 Subject: [PATCH 2013/2212] style: alphabetize `dev-dependencies` --- Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e01d50688..c7ee98e27 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,15 +68,15 @@ unicode-xid = { version = "0.2.3", optional = true } bincode = "1" criterion = { version = "0.3", features = [] } diff = "0.1" +env_logger = "0.9" hlsl-snapshots = { path = "./xtask/hlsl-snapshots"} # Require at least version 0.7.1 of ron, this version changed how floating points are # serialized by forcing them to always have the decimal part, this makes it backwards # incompatible with our tests because we do a syntatic diff and not a semantic one. ron = "~0.7.1" +rspirv = { version = "0.11", git = "https://github.com/gfx-rs/rspirv", rev = "b969f175d5663258b4891e44b76c1544da9661ab" } serde = { version = "1.0", features = ["derive"] } spirv = { version = "0.2", features = ["deserialize"] } -rspirv = { version = "0.11", git = "https://github.com/gfx-rs/rspirv", rev = "b969f175d5663258b4891e44b76c1544da9661ab" } -env_logger = "0.9" [workspace] members = [".", "cli"] From cd7b8aca4756685ac5560a05371d620e88678638 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Thu, 8 Jun 2023 10:52:58 -0400 Subject: [PATCH 2014/2212] refactor(xtask): avoid unnecessary IIFE --- xtask/src/cli.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/xtask/src/cli.rs b/xtask/src/cli.rs index c6fd6d2a6..d1511dcb9 100644 --- a/xtask/src/cli.rs +++ b/xtask/src/cli.rs @@ -35,10 +35,7 @@ impl Args { eprint!("{HELP}"); exit(101); } - match (|| -> anyhow::Result<_> { - let subcommand = Subcommand::parse(args)?; - Ok(Self { subcommand }) - })() { + match Subcommand::parse(args).map(|subcommand| Self { subcommand }) { Ok(this) => this, Err(e) => { eprintln!("{:?}", anyhow!(e)); From 3e11b4a3cda61298bad09fbf4df3394699231cec Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Thu, 8 Jun 2023 10:52:58 -0400 Subject: [PATCH 2015/2212] refactor(xtask): prefer `?` to `Result::map` in subcmd. parsing --- xtask/src/cli.rs | 129 ++++++++++++++++++++++++----------------------- 1 file changed, 66 insertions(+), 63 deletions(-) diff --git a/xtask/src/cli.rs b/xtask/src/cli.rs index d1511dcb9..01d60dfa1 100644 --- a/xtask/src/cli.rs +++ b/xtask/src/cli.rs @@ -54,24 +54,25 @@ pub(crate) enum Subcommand { impl Subcommand { fn parse(mut args: Arguments) -> anyhow::Result { - args.subcommand() - .context("failed to parse subcommand") - .and_then(|parsed| match parsed.as_deref() { - None => bail!("no subcommand specified; see `--help` for more details"), - Some("all") => { - ensure_remaining_args_empty(args)?; - Ok(Self::All) - } - Some("bench") => { - let clean = args.contains("--clean"); - ensure_remaining_args_empty(args)?; - Ok(Self::Bench { clean }) - } - Some("validate") => Ok(Self::Validate(ValidateSubcommand::parse(args)?)), - Some(other) => { - bail!("unrecognized subcommand {other:?}; see `--help` for more details") - } - }) + let subcmd = args + .subcommand() + .context("failed to parse subcommand")? + .context("no subcommand specified; see `--help` for more details")?; + match &*subcmd { + "all" => { + ensure_remaining_args_empty(args)?; + Ok(Self::All) + } + "bench" => { + let clean = args.contains("--clean"); + ensure_remaining_args_empty(args)?; + Ok(Self::Bench { clean }) + } + "validate" => Ok(Self::Validate(ValidateSubcommand::parse(args)?)), + other => { + bail!("unrecognized subcommand {other:?}; see `--help` for more details") + } + } } } @@ -87,35 +88,36 @@ pub(crate) enum ValidateSubcommand { impl ValidateSubcommand { fn parse(mut args: Arguments) -> Result { - args.subcommand() - .context("failed to parse `validate` subcommand") - .and_then(|parsed| match parsed.as_deref() { - None => bail!("no `validate` subcommand specified; see `--help` for more details"), - Some("spv") => { - ensure_remaining_args_empty(args)?; - Ok(Self::Spirv) - } - Some("msl") => { - ensure_remaining_args_empty(args)?; - Ok(Self::Metal) - } - Some("glsl") => { - ensure_remaining_args_empty(args)?; - Ok(Self::Glsl) - } - Some("dot") => { - ensure_remaining_args_empty(args)?; - Ok(Self::Dot) - } - Some("wgsl") => { - ensure_remaining_args_empty(args)?; - Ok(Self::Wgsl) - } - Some("hlsl") => Ok(Self::Hlsl(ValidateHlslCommand::parse(args)?)), - Some(other) => bail!( - "unrecognized `validate` subcommand {other:?}; see `--help` for more details" - ), - }) + let subcmd = args + .subcommand() + .context("failed to parse `validate` subcommand")? + .context("no `validate` subcommand specified; see `--help` for more details")?; + match &*subcmd { + "spv" => { + ensure_remaining_args_empty(args)?; + Ok(Self::Spirv) + } + "msl" => { + ensure_remaining_args_empty(args)?; + Ok(Self::Metal) + } + "glsl" => { + ensure_remaining_args_empty(args)?; + Ok(Self::Glsl) + } + "dot" => { + ensure_remaining_args_empty(args)?; + Ok(Self::Dot) + } + "wgsl" => { + ensure_remaining_args_empty(args)?; + Ok(Self::Wgsl) + } + "hlsl" => return Ok(Self::Hlsl(ValidateHlslCommand::parse(args)?)), + other => { + bail!("unrecognized `validate` subcommand {other:?}; see `--help` for more details") + } + } } } @@ -127,22 +129,23 @@ pub(crate) enum ValidateHlslCommand { impl ValidateHlslCommand { fn parse(mut args: Arguments) -> anyhow::Result { - args.subcommand() - .context("failed to parse `hlsl` subcommand") - .and_then(|parsed| match parsed.as_deref() { - None => bail!("no `hlsl` subcommand specified; see `--help` for more details"), - Some("dxc") => { - ensure_remaining_args_empty(args)?; - Ok(Self::Dxc) - } - Some("fxc") => { - ensure_remaining_args_empty(args)?; - Ok(Self::Fxc) - } - Some(other) => { - bail!("unrecognized `hlsl` subcommand {other:?}; see `--help` for more details") - } - }) + let subcmd = args + .subcommand() + .context("failed to parse `hlsl` subcommand")? + .context("no `hlsl` subcommand specified; see `--help` for more details")?; + match &*subcmd { + "dxc" => { + ensure_remaining_args_empty(args)?; + Ok(Self::Dxc) + } + "fxc" => { + ensure_remaining_args_empty(args)?; + Ok(Self::Fxc) + } + other => { + bail!("unrecognized `hlsl` subcommand {other:?}; see `--help` for more details") + } + } } } From 9b6e74813ffb2fceb964144f38ad5aebb272e220 Mon Sep 17 00:00:00 2001 From: Erich Gubler Date: Thu, 8 Jun 2023 15:55:56 -0400 Subject: [PATCH 2016/2212] build: mark `hlsl-snapshots` as `publish = false` --- xtask/hlsl-snapshots/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/xtask/hlsl-snapshots/Cargo.toml b/xtask/hlsl-snapshots/Cargo.toml index 8cd662ef4..07620dcfd 100644 --- a/xtask/hlsl-snapshots/Cargo.toml +++ b/xtask/hlsl-snapshots/Cargo.toml @@ -2,6 +2,7 @@ name = "hlsl-snapshots" version = "0.1.0" edition = "2021" +publish = false [dependencies] anyhow = "1" From dbb6d8e814999c81e6bf06fda4121ca6682a494f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 2 Jun 2023 21:01:00 +0200 Subject: [PATCH 2017/2212] avoid allocating --- src/proc/namer.rs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 8227b50d8..c1e1fba8a 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -25,9 +25,9 @@ pub enum NameKey { pub struct Namer { /// The last numeric suffix used for each base name. Zero means "no suffix". unique: FastHashMap, - keywords: FastHashSet, + keywords: FastHashSet<&'static str>, keywords_case_insensitive: FastHashSet>, - reserved_prefixes: Vec, + reserved_prefixes: Vec<&'static str>, } impl Namer { @@ -112,7 +112,7 @@ impl Namer { { suffixed.push(SEPARATOR); } - debug_assert!(!self.keywords.contains(&suffixed)); + debug_assert!(!self.keywords.contains::(&suffixed)); // `self.unique` wants to own its keys. This allocates only if we haven't // already done so earlier. self.unique.insert(base.into_owned(), 0); @@ -143,19 +143,17 @@ impl Namer { pub fn reset( &mut self, module: &crate::Module, - reserved_keywords: &[&str], + reserved_keywords: &[&'static str], reserved_keywords_case_insensitive: &[&'static str], - reserved_prefixes: &[&str], + reserved_prefixes: &[&'static str], output: &mut FastHashMap, ) { self.reserved_prefixes.clear(); - self.reserved_prefixes - .extend(reserved_prefixes.iter().map(|string| string.to_string())); + self.reserved_prefixes.extend(reserved_prefixes.iter()); self.unique.clear(); self.keywords.clear(); - self.keywords - .extend(reserved_keywords.iter().map(|string| (string.to_string()))); + self.keywords.extend(reserved_keywords.iter()); debug_assert!(reserved_keywords_case_insensitive .iter() From 763ec5d1a56196ea1b5af39846e61ba6404098f4 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 2 Jun 2023 21:06:36 +0200 Subject: [PATCH 2018/2212] complete HLSL reserved symbols --- src/back/glsl/mod.rs | 1 + src/back/hlsl/keywords.rs | 741 +++++++++++++++++++++++++++++++++++++- src/back/hlsl/writer.rs | 1 + src/back/msl/writer.rs | 10 +- src/back/wgsl/writer.rs | 1 + src/proc/namer.rs | 2 + 6 files changed, 748 insertions(+), 8 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 6298315c5..ea13d8706 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -489,6 +489,7 @@ impl<'a, W: Write> Writer<'a, W> { module, keywords::RESERVED_KEYWORDS, &[], + &[], &["gl_"], &mut names, ); diff --git a/src/back/hlsl/keywords.rs b/src/back/hlsl/keywords.rs index 459db245e..eb358f31b 100644 --- a/src/back/hlsl/keywords.rs +++ b/src/back/hlsl/keywords.rs @@ -1,9 +1,3 @@ -/*! -HLSL Reserved Words -- -- -*/ - // When compiling with FXC without strict mode, these keywords are actually case insensitive. // If you compile with strict mode and specify a different casing like "Pass" instead in an identifier, FXC will give this error: // "error X3086: alternate cases for 'pass' are deprecated in strict mode" @@ -20,7 +14,9 @@ pub const RESERVED_CASE_INSENSITIVE: &[&str] = &[ ]; pub const RESERVED: &[&str] = &[ + // FXC keywords, from https://github.com/MicrosoftDocs/win32/blob/c885cb0c63b0e9be80c6a0e6512473ac6f4e771e/desktop-src/direct3dhlsl/dx-graphics-hlsl-appendix-keywords.md?plain=1#L99-L118 "AppendStructuredBuffer", + "asm", "asm_fragment", "BlendState", "bool", @@ -82,6 +78,7 @@ pub const RESERVED: &[&str] = &[ "out", "OutputPatch", "packoffset", + "pass", "pixelfragment", "PixelShader", "point", @@ -114,13 +111,18 @@ pub const RESERVED: &[&str] = &[ "switch", "StructuredBuffer", "tbuffer", + "technique", "technique10", "technique11", "texture", + "Texture1D", "Texture1DArray", + "Texture2D", "Texture2DArray", "Texture2DMS", "Texture2DMSArray", + "Texture3D", + "TextureCube", "TextureCubeArray", "true", "typedef", @@ -137,6 +139,7 @@ pub const RESERVED: &[&str] = &[ "void", "volatile", "while", + // FXC reserved keywords, from https://github.com/MicrosoftDocs/win32/blob/c885cb0c63b0e9be80c6a0e6512473ac6f4e771e/desktop-src/direct3dhlsl/dx-graphics-hlsl-appendix-reserved-words.md?plain=1#L19-L38 "auto", "case", "catch", @@ -171,4 +174,730 @@ pub const RESERVED: &[&str] = &[ "unsigned", "using", "virtual", + // FXC intrinsics, from https://github.com/MicrosoftDocs/win32/blob/1682b99e203708f6f5eda972d966e30f3c1588de/desktop-src/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions.md?plain=1#L26-L165 + "abort", + "abs", + "acos", + "all", + "AllMemoryBarrier", + "AllMemoryBarrierWithGroupSync", + "any", + "asdouble", + "asfloat", + "asin", + "asint", + "asuint", + "atan", + "atan2", + "ceil", + "CheckAccessFullyMapped", + "clamp", + "clip", + "cos", + "cosh", + "countbits", + "cross", + "D3DCOLORtoUBYTE4", + "ddx", + "ddx_coarse", + "ddx_fine", + "ddy", + "ddy_coarse", + "ddy_fine", + "degrees", + "determinant", + "DeviceMemoryBarrier", + "DeviceMemoryBarrierWithGroupSync", + "distance", + "dot", + "dst", + "errorf", + "EvaluateAttributeCentroid", + "EvaluateAttributeAtSample", + "EvaluateAttributeSnapped", + "exp", + "exp2", + "f16tof32", + "f32tof16", + "faceforward", + "firstbithigh", + "firstbitlow", + "floor", + "fma", + "fmod", + "frac", + "frexp", + "fwidth", + "GetRenderTargetSampleCount", + "GetRenderTargetSamplePosition", + "GroupMemoryBarrier", + "GroupMemoryBarrierWithGroupSync", + "InterlockedAdd", + "InterlockedAnd", + "InterlockedCompareExchange", + "InterlockedCompareStore", + "InterlockedExchange", + "InterlockedMax", + "InterlockedMin", + "InterlockedOr", + "InterlockedXor", + "isfinite", + "isinf", + "isnan", + "ldexp", + "length", + "lerp", + "lit", + "log", + "log10", + "log2", + "mad", + "max", + "min", + "modf", + "msad4", + "mul", + "noise", + "normalize", + "pow", + "printf", + "Process2DQuadTessFactorsAvg", + "Process2DQuadTessFactorsMax", + "Process2DQuadTessFactorsMin", + "ProcessIsolineTessFactors", + "ProcessQuadTessFactorsAvg", + "ProcessQuadTessFactorsMax", + "ProcessQuadTessFactorsMin", + "ProcessTriTessFactorsAvg", + "ProcessTriTessFactorsMax", + "ProcessTriTessFactorsMin", + "radians", + "rcp", + "reflect", + "refract", + "reversebits", + "round", + "rsqrt", + "saturate", + "sign", + "sin", + "sincos", + "sinh", + "smoothstep", + "sqrt", + "step", + "tan", + "tanh", + "tex1D", + "tex1Dbias", + "tex1Dgrad", + "tex1Dlod", + "tex1Dproj", + "tex2D", + "tex2Dbias", + "tex2Dgrad", + "tex2Dlod", + "tex2Dproj", + "tex3D", + "tex3Dbias", + "tex3Dgrad", + "tex3Dlod", + "tex3Dproj", + "texCUBE", + "texCUBEbias", + "texCUBEgrad", + "texCUBElod", + "texCUBEproj", + "transpose", + "trunc", + // DXC (reserved) keywords, from https://github.com/microsoft/DirectXShaderCompiler/blob/d5d478470d3020a438d3cb810b8d3fe0992e6709/tools/clang/include/clang/Basic/TokenKinds.def#L222-L648 + // with the KEYALL, KEYCXX, BOOLSUPPORT, WCHARSUPPORT, KEYHLSL options enabled (see https://github.com/microsoft/DirectXShaderCompiler/blob/d5d478470d3020a438d3cb810b8d3fe0992e6709/tools/clang/lib/Frontend/CompilerInvocation.cpp#L1199) + "auto", + "break", + "case", + "char", + "const", + "continue", + "default", + "do", + "double", + "else", + "enum", + "extern", + "float", + "for", + "goto", + "if", + "inline", + "int", + "long", + "register", + "return", + "short", + "signed", + "sizeof", + "static", + "struct", + "switch", + "typedef", + "union", + "unsigned", + "void", + "volatile", + "while", + "_Alignas", + "_Alignof", + "_Atomic", + "_Complex", + "_Generic", + "_Imaginary", + "_Noreturn", + "_Static_assert", + "_Thread_local", + "__func__", + "__objc_yes", + "__objc_no", + "asm", + "bool", + "catch", + "class", + "const_cast", + "delete", + "dynamic_cast", + "explicit", + "export", + "false", + "friend", + "mutable", + "namespace", + "new", + "operator", + "private", + "protected", + "public", + "reinterpret_cast", + "static_cast", + "template", + "this", + "throw", + "true", + "try", + "typename", + "typeid", + "using", + "virtual", + "wchar_t", + "_Decimal32", + "_Decimal64", + "_Decimal128", + "__null", + "__alignof", + "__attribute", + "__builtin_choose_expr", + "__builtin_offsetof", + "__builtin_va_arg", + "__extension__", + "__imag", + "__int128", + "__label__", + "__real", + "__thread", + "__FUNCTION__", + "__PRETTY_FUNCTION__", + "__is_nothrow_assignable", + "__is_constructible", + "__is_nothrow_constructible", + "__has_nothrow_assign", + "__has_nothrow_move_assign", + "__has_nothrow_copy", + "__has_nothrow_constructor", + "__has_trivial_assign", + "__has_trivial_move_assign", + "__has_trivial_copy", + "__has_trivial_constructor", + "__has_trivial_move_constructor", + "__has_trivial_destructor", + "__has_virtual_destructor", + "__is_abstract", + "__is_base_of", + "__is_class", + "__is_convertible_to", + "__is_empty", + "__is_enum", + "__is_final", + "__is_literal", + "__is_literal_type", + "__is_pod", + "__is_polymorphic", + "__is_trivial", + "__is_union", + "__is_trivially_constructible", + "__is_trivially_copyable", + "__is_trivially_assignable", + "__underlying_type", + "__is_lvalue_expr", + "__is_rvalue_expr", + "__is_arithmetic", + "__is_floating_point", + "__is_integral", + "__is_complete_type", + "__is_void", + "__is_array", + "__is_function", + "__is_reference", + "__is_lvalue_reference", + "__is_rvalue_reference", + "__is_fundamental", + "__is_object", + "__is_scalar", + "__is_compound", + "__is_pointer", + "__is_member_object_pointer", + "__is_member_function_pointer", + "__is_member_pointer", + "__is_const", + "__is_volatile", + "__is_standard_layout", + "__is_signed", + "__is_unsigned", + "__is_same", + "__is_convertible", + "__array_rank", + "__array_extent", + "__private_extern__", + "__module_private__", + "__declspec", + "__cdecl", + "__stdcall", + "__fastcall", + "__thiscall", + "__vectorcall", + "cbuffer", + "tbuffer", + "packoffset", + "linear", + "centroid", + "nointerpolation", + "noperspective", + "sample", + "column_major", + "row_major", + "in", + "out", + "inout", + "uniform", + "precise", + "center", + "shared", + "groupshared", + "discard", + "snorm", + "unorm", + "point", + "line", + "lineadj", + "triangle", + "triangleadj", + "globallycoherent", + "interface", + "sampler_state", + "technique", + "indices", + "vertices", + "primitives", + "payload", + "Technique", + "technique10", + "technique11", + "__builtin_omp_required_simd_align", + "__pascal", + "__fp16", + "__alignof__", + "__asm", + "__asm__", + "__attribute__", + "__complex", + "__complex__", + "__const", + "__const__", + "__decltype", + "__imag__", + "__inline", + "__inline__", + "__nullptr", + "__real__", + "__restrict", + "__restrict__", + "__signed", + "__signed__", + "__typeof", + "__typeof__", + "__volatile", + "__volatile__", + "_Nonnull", + "_Nullable", + "_Null_unspecified", + "__builtin_convertvector", + "__char16_t", + "__char32_t", + // DXC intrinsics, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/utils/hct/gen_intrin_main.txt#L86-L376 + "D3DCOLORtoUBYTE4", + "GetRenderTargetSampleCount", + "GetRenderTargetSamplePosition", + "abort", + "abs", + "acos", + "all", + "AllMemoryBarrier", + "AllMemoryBarrierWithGroupSync", + "any", + "asdouble", + "asfloat", + "asfloat16", + "asint16", + "asin", + "asint", + "asuint", + "asuint16", + "atan", + "atan2", + "ceil", + "clamp", + "clip", + "cos", + "cosh", + "countbits", + "cross", + "ddx", + "ddx_coarse", + "ddx_fine", + "ddy", + "ddy_coarse", + "ddy_fine", + "degrees", + "determinant", + "DeviceMemoryBarrier", + "DeviceMemoryBarrierWithGroupSync", + "distance", + "dot", + "dst", + "EvaluateAttributeAtSample", + "EvaluateAttributeCentroid", + "EvaluateAttributeSnapped", + "GetAttributeAtVertex", + "exp", + "exp2", + "f16tof32", + "f32tof16", + "faceforward", + "firstbithigh", + "firstbitlow", + "floor", + "fma", + "fmod", + "frac", + "frexp", + "fwidth", + "GroupMemoryBarrier", + "GroupMemoryBarrierWithGroupSync", + "InterlockedAdd", + "InterlockedMin", + "InterlockedMax", + "InterlockedAnd", + "InterlockedOr", + "InterlockedXor", + "InterlockedCompareStore", + "InterlockedExchange", + "InterlockedCompareExchange", + "InterlockedCompareStoreFloatBitwise", + "InterlockedCompareExchangeFloatBitwise", + "isfinite", + "isinf", + "isnan", + "ldexp", + "length", + "lerp", + "lit", + "log", + "log10", + "log2", + "mad", + "max", + "min", + "modf", + "msad4", + "mul", + "normalize", + "pow", + "printf", + "Process2DQuadTessFactorsAvg", + "Process2DQuadTessFactorsMax", + "Process2DQuadTessFactorsMin", + "ProcessIsolineTessFactors", + "ProcessQuadTessFactorsAvg", + "ProcessQuadTessFactorsMax", + "ProcessQuadTessFactorsMin", + "ProcessTriTessFactorsAvg", + "ProcessTriTessFactorsMax", + "ProcessTriTessFactorsMin", + "radians", + "rcp", + "reflect", + "refract", + "reversebits", + "round", + "rsqrt", + "saturate", + "sign", + "sin", + "sincos", + "sinh", + "smoothstep", + "source_mark", + "sqrt", + "step", + "tan", + "tanh", + "tex1D", + "tex1Dbias", + "tex1Dgrad", + "tex1Dlod", + "tex1Dproj", + "tex2D", + "tex2Dbias", + "tex2Dgrad", + "tex2Dlod", + "tex2Dproj", + "tex3D", + "tex3Dbias", + "tex3Dgrad", + "tex3Dlod", + "tex3Dproj", + "texCUBE", + "texCUBEbias", + "texCUBEgrad", + "texCUBElod", + "texCUBEproj", + "transpose", + "trunc", + "CheckAccessFullyMapped", + "AddUint64", + "NonUniformResourceIndex", + "WaveIsFirstLane", + "WaveGetLaneIndex", + "WaveGetLaneCount", + "WaveActiveAnyTrue", + "WaveActiveAllTrue", + "WaveActiveAllEqual", + "WaveActiveBallot", + "WaveReadLaneAt", + "WaveReadLaneFirst", + "WaveActiveCountBits", + "WaveActiveSum", + "WaveActiveProduct", + "WaveActiveBitAnd", + "WaveActiveBitOr", + "WaveActiveBitXor", + "WaveActiveMin", + "WaveActiveMax", + "WavePrefixCountBits", + "WavePrefixSum", + "WavePrefixProduct", + "WaveMatch", + "WaveMultiPrefixBitAnd", + "WaveMultiPrefixBitOr", + "WaveMultiPrefixBitXor", + "WaveMultiPrefixCountBits", + "WaveMultiPrefixProduct", + "WaveMultiPrefixSum", + "QuadReadLaneAt", + "QuadReadAcrossX", + "QuadReadAcrossY", + "QuadReadAcrossDiagonal", + "QuadAny", + "QuadAll", + "TraceRay", + "ReportHit", + "CallShader", + "IgnoreHit", + "AcceptHitAndEndSearch", + "DispatchRaysIndex", + "DispatchRaysDimensions", + "WorldRayOrigin", + "WorldRayDirection", + "ObjectRayOrigin", + "ObjectRayDirection", + "RayTMin", + "RayTCurrent", + "PrimitiveIndex", + "InstanceID", + "InstanceIndex", + "GeometryIndex", + "HitKind", + "RayFlags", + "ObjectToWorld", + "WorldToObject", + "ObjectToWorld3x4", + "WorldToObject3x4", + "ObjectToWorld4x3", + "WorldToObject4x3", + "dot4add_u8packed", + "dot4add_i8packed", + "dot2add", + "unpack_s8s16", + "unpack_u8u16", + "unpack_s8s32", + "unpack_u8u32", + "pack_s8", + "pack_u8", + "pack_clamp_s8", + "pack_clamp_u8", + "SetMeshOutputCounts", + "DispatchMesh", + "IsHelperLane", + "AllocateRayQuery", + "CreateResourceFromHeap", + "and", + "or", + "select", + // DXC resource and other types, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/tools/clang/lib/AST/HlslTypes.cpp#L441-#L572 + "InputPatch", + "OutputPatch", + "PointStream", + "LineStream", + "TriangleStream", + "Texture1D", + "RWTexture1D", + "Texture2D", + "RWTexture2D", + "Texture2DMS", + "RWTexture2DMS", + "Texture3D", + "RWTexture3D", + "TextureCube", + "RWTextureCube", + "Texture1DArray", + "RWTexture1DArray", + "Texture2DArray", + "RWTexture2DArray", + "Texture2DMSArray", + "RWTexture2DMSArray", + "TextureCubeArray", + "RWTextureCubeArray", + "FeedbackTexture2D", + "FeedbackTexture2DArray", + "RasterizerOrderedTexture1D", + "RasterizerOrderedTexture2D", + "RasterizerOrderedTexture3D", + "RasterizerOrderedTexture1DArray", + "RasterizerOrderedTexture2DArray", + "RasterizerOrderedBuffer", + "RasterizerOrderedByteAddressBuffer", + "RasterizerOrderedStructuredBuffer", + "ByteAddressBuffer", + "RWByteAddressBuffer", + "StructuredBuffer", + "RWStructuredBuffer", + "AppendStructuredBuffer", + "ConsumeStructuredBuffer", + "Buffer", + "RWBuffer", + "SamplerState", + "SamplerComparisonState", + "ConstantBuffer", + "TextureBuffer", + "RaytracingAccelerationStructure", + // DXC templated types, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/tools/clang/lib/AST/ASTContextHLSL.cpp + // look for `BuiltinTypeDeclBuilder` + "matrix", + "vector", + "TextureBuffer", + "ConstantBuffer", + "RayQuery", ]; + +// DXC scalar types, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/tools/clang/lib/AST/ASTContextHLSL.cpp#L48-L254 +// + vector and matrix shorthands +pub const TYPES: &[&str] = &{ + const L: usize = 23 * (1 + 4 + 4 * 4); + let mut res = [""; L]; + let mut c = 0; + + /// For each scalar type, it will additionally generate vector and matrix shorthands + macro_rules! generate { + ($a:ident, $i:ident, [$($roots:literal),*], $x:tt) => { + $( + generate!(@inner push $a, $i, $roots); + generate!(@inner $a, $i, $roots, $x); + )* + }; + + (@inner $a:ident, $i:ident, $root:literal, [$($x:literal),*]) => { + generate!(@inner vector $a, $i, $root, $($x)*); + generate!(@inner matrix $a, $i, $root, $($x)*); + }; + + (@inner vector $a:ident, $i:ident, $root:literal, $($x:literal)*) => { + $( + generate!(@inner push $a, $i, concat!($root, $x)); + )* + }; + + (@inner matrix $a:ident, $i:ident, $root:literal, $($x:literal)*) => { + // Duplicate the list + generate!(@inner matrix $a, $i, $root, $($x)*; $($x)*); + }; + + // The head/tail recursion: pick the first element of the first list and recursively do it for the tail. + (@inner matrix $a:ident, $i:ident, $root:literal, $head:literal $($tail:literal)*; $($x:literal)*) => { + $( + generate!(@inner push $a, $i, concat!($root, $head, "x", $x)); + )* + generate!(@inner matrix $a, $i, $root, $($tail)*; $($x)*); + + }; + + // The end of iteration: we exhausted the list + (@inner matrix $a:ident, $i:ident, $root:literal, ; $($x:literal)*) => {}; + + (@inner push $a:ident, $i:ident, $v:expr) => { + $a[$i] = $v; + $i += 1; + }; + } + + generate!( + res, + c, + [ + "bool", + "int", + "uint", + "dword", + "half", + "float", + "double", + "min10float", + "min16float", + "min12int", + "min16int", + "min16uint", + "int16_t", + "int32_t", + "int64_t", + "uint16_t", + "uint32_t", + "uint64_t", + "float16_t", + "float32_t", + "float64_t", + "int8_t4_packed", + "uint8_t4_packed" + ], + ["1", "2", "3", "4"] + ); + + debug_assert!(c == L); + + res +}; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 940f0ae37..5547e94ce 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -92,6 +92,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.namer.reset( module, super::keywords::RESERVED, + super::keywords::TYPES, super::keywords::RESERVED_CASE_INSENSITIVE, &[], &mut self.names, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index cfef6645b..16a3ab888 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3032,8 +3032,14 @@ impl Writer { pipeline_options: &PipelineOptions, ) -> Result { self.names.clear(); - self.namer - .reset(module, super::keywords::RESERVED, &[], &[], &mut self.names); + self.namer.reset( + module, + super::keywords::RESERVED, + &[], + &[], + &[], + &mut self.names, + ); self.struct_member_pads.clear(); writeln!( diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 2d048cd9c..46393c643 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -88,6 +88,7 @@ impl Writer { crate::keywords::wgsl::RESERVED, // an identifier must not start with two underscore &[], + &[], &["__"], &mut self.names, ); diff --git a/src/proc/namer.rs b/src/proc/namer.rs index c1e1fba8a..de98f601c 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -144,6 +144,7 @@ impl Namer { &mut self, module: &crate::Module, reserved_keywords: &[&'static str], + extra_reserved_keywords: &[&'static str], reserved_keywords_case_insensitive: &[&'static str], reserved_prefixes: &[&'static str], output: &mut FastHashMap, @@ -154,6 +155,7 @@ impl Namer { self.unique.clear(); self.keywords.clear(); self.keywords.extend(reserved_keywords.iter()); + self.keywords.extend(extra_reserved_keywords.iter()); debug_assert!(reserved_keywords_case_insensitive .iter() From 08105461ce58be9442253b4f4e7e186a25a078fa Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 12 Jun 2023 17:02:27 +0200 Subject: [PATCH 2019/2212] omit non referenced expressions --- src/back/glsl/mod.rs | 2 - src/back/hlsl/writer.rs | 2 - src/back/msl/writer.rs | 2 - src/back/spv/block.rs | 9 + src/back/wgsl/writer.rs | 5 - src/valid/analyzer.rs | 14 +- tests/in/access.wgsl | 32 +- tests/in/array-in-ctor.wgsl | 2 +- tests/in/atomicOps.wgsl | 16 +- tests/in/globals.wgsl | 12 +- tests/in/operators.wgsl | 344 ++++----- tests/out/glsl/access.foo_vert.Vertex.glsl | 30 +- .../glsl/array-in-ctor.cs_main.Compute.glsl | 2 +- tests/out/glsl/atomicOps.cs_main.Compute.glsl | 16 +- tests/out/glsl/break-if.main.Compute.glsl | 6 +- tests/out/glsl/do-while.main.Fragment.glsl | 3 +- tests/out/glsl/globals.main.Compute.glsl | 12 +- tests/out/glsl/operators.main.Compute.glsl | 316 ++++----- tests/out/hlsl/access.hlsl | 30 +- tests/out/hlsl/array-in-ctor.hlsl | 2 +- tests/out/hlsl/atomicOps.hlsl | 16 +- tests/out/hlsl/break-if.hlsl | 6 +- tests/out/hlsl/do-while.hlsl | 3 +- tests/out/hlsl/globals.hlsl | 12 +- tests/out/hlsl/operators.hlsl | 316 ++++----- tests/out/ir/access.ron | 21 +- tests/out/msl/access.msl | 30 +- tests/out/msl/array-in-ctor.msl | 2 +- tests/out/msl/atomicOps.msl | 16 +- tests/out/msl/break-if.msl | 2 - tests/out/msl/do-while.msl | 1 - tests/out/msl/globals.msl | 12 +- tests/out/msl/operators.msl | 316 ++++----- tests/out/spv/access.spvasm | 325 +++++---- tests/out/spv/binding-buffer-arrays.spvasm | 85 ++- tests/out/spv/bounds-check-restrict.spvasm | 177 +++-- tests/out/spv/bounds-check-zero.spvasm | 229 +++--- tests/out/spv/globals.spvasm | 276 ++++---- tests/out/spv/interface.compute.spvasm | 61 +- tests/out/spv/operators.spvasm | 658 +++++++++--------- tests/out/wgsl/210-bevy-2d-shader-vert.wgsl | 2 - tests/out/wgsl/210-bevy-shader-vert.wgsl | 1 - tests/out/wgsl/246-collatz-comp.wgsl | 3 - .../wgsl/800-out-of-bounds-panic-vert.wgsl | 2 - .../wgsl/900-implicit-conversions-frag.wgsl | 1 - tests/out/wgsl/access.wgsl | 30 +- tests/out/wgsl/array-in-ctor.wgsl | 2 +- tests/out/wgsl/atomicOps.wgsl | 16 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 403 ----------- tests/out/wgsl/bevy-pbr-vert.wgsl | 1 - tests/out/wgsl/bits_glsl-frag.wgsl | 58 -- tests/out/wgsl/bool-select-frag.wgsl | 5 - tests/out/wgsl/break-if.wgsl | 2 - tests/out/wgsl/buffer-frag.wgsl | 5 - tests/out/wgsl/clamp-splat-vert.wgsl | 1 - tests/out/wgsl/declarations-frag.wgsl | 8 - tests/out/wgsl/do-while.wgsl | 1 - tests/out/wgsl/expressions-frag.wgsl | 12 - tests/out/wgsl/fma-frag.wgsl | 1 - tests/out/wgsl/functions_call-frag.wgsl | 5 - .../out/wgsl/global-constant-array-frag.wgsl | 1 - tests/out/wgsl/globals.wgsl | 12 +- tests/out/wgsl/images-frag.wgsl | 18 - tests/out/wgsl/math-functions-frag.wgsl | 56 -- tests/out/wgsl/operators.wgsl | 316 ++++----- tests/out/wgsl/sampler-functions-frag.wgsl | 2 - tests/out/wgsl/samplers-frag.wgsl | 245 ------- tests/out/wgsl/vector-functions-frag.wgsl | 55 -- 68 files changed, 1905 insertions(+), 2780 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ea13d8706..d5fc89bca 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1803,8 +1803,6 @@ impl<'a, W: Write> Writer<'a, W> { Some(self.namer.call(name)) } else if self.need_bake_expressions.contains(&handle) { Some(format!("{}{}", back::BAKE_PREFIX, handle.index())) - } else if info.ref_count == 0 { - Some(self.namer.call("")) } else { None }; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 5547e94ce..45c0a464a 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1336,8 +1336,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Some(self.namer.call(name)) } else if self.need_bake_expressions.contains(&handle) { Some(format!("_expr{}", handle.index())) - } else if info.ref_count == 0 { - Some(self.namer.call("")) } else { None }; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 16a3ab888..22a5f56b7 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2581,8 +2581,6 @@ impl Writer { // Don't assume the names in `named_expressions` are unique, // or even valid. Use the `Namer`. Some(self.namer.call(name)) - } else if info.ref_count == 0 { - Some(self.namer.call("")) } else { // If this expression is an index that we're going to first compare // against a limit, and then actually use as an index, then we may diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 1ba61ad39..fa9596655 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -220,6 +220,15 @@ impl<'w> BlockContext<'w> { expr_handle: Handle, block: &mut Block, ) -> Result<(), Error> { + let is_named_expression = self + .ir_function + .named_expressions + .contains_key(&expr_handle); + + if self.fun_info[expr_handle].ref_count == 0 && !is_named_expression { + return Ok(()); + } + let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty); let id = match self.ir_function.expressions[expr_handle] { crate::Expression::Access { base, index: _ } if self.is_intermediate(base) => { diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 46393c643..225df0b89 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -634,11 +634,6 @@ impl Writer { // Otherwise, we could accidentally write variable name instead of full expression. // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords. Some(self.namer.call(name)) - } else if info.ref_count == 0 { - write!(self.out, "{level}_ = ")?; - self.write_expr(module, handle, func_ctx)?; - writeln!(self.out, ";")?; - continue; } else { let expr = &func_ctx.expressions[handle]; let min_ref_count = expr.bake_ref_count(); diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 18d6ace2e..8ce63eaf3 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -675,12 +675,17 @@ impl FunctionInfo { requirements: UniformityRequirements::empty(), }, E::Math { - arg, arg1, arg2, .. + fun: _, + arg, + arg1, + arg2, + arg3, } => { let arg1_nur = arg1.and_then(|h| self.add_ref(h)); let arg2_nur = arg2.and_then(|h| self.add_ref(h)); + let arg3_nur = arg3.and_then(|h| self.add_ref(h)); Uniformity { - non_uniform_result: self.add_ref(arg).or(arg1_nur).or(arg2_nur), + non_uniform_result: self.add_ref(arg).or(arg1_nur).or(arg2_nur).or(arg3_nur), requirements: UniformityRequirements::empty(), } } @@ -868,7 +873,7 @@ impl FunctionInfo { S::Loop { ref body, ref continuing, - break_if: _, + break_if, } => { let body_uniformity = self.process_block(body, other_functions, disruptor, expression_arena)?; @@ -879,6 +884,9 @@ impl FunctionInfo { continuing_disruptor, expression_arena, )?; + if let Some(expr) = break_if { + let _ = self.add_ref(expr); + } body_uniformity | continuing_uniformity } S::Return { value } => FunctionUniformity { diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index ed4988532..c9097f913 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -40,13 +40,13 @@ fn test_matrix_within_struct_accesses() { idx--; // loads - _ = baz.m; - _ = baz.m[0]; - _ = baz.m[idx]; - _ = baz.m[0][1]; - _ = baz.m[0][idx]; - _ = baz.m[idx][1]; - _ = baz.m[idx][idx]; + let l0 = baz.m; + let l1 = baz.m[0]; + let l2 = baz.m[idx]; + let l3 = baz.m[0][1]; + let l4 = baz.m[0][idx]; + let l5 = baz.m[idx][1]; + let l6 = baz.m[idx][idx]; var t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); @@ -75,14 +75,14 @@ fn test_matrix_within_array_within_struct_accesses() { idx--; // loads - _ = nested_mat_cx2.am; - _ = nested_mat_cx2.am[0]; - _ = nested_mat_cx2.am[0][0]; - _ = nested_mat_cx2.am[0][idx]; - _ = nested_mat_cx2.am[0][0][1]; - _ = nested_mat_cx2.am[0][0][idx]; - _ = nested_mat_cx2.am[0][idx][1]; - _ = nested_mat_cx2.am[0][idx][idx]; + let l0 = nested_mat_cx2.am; + let l1 = nested_mat_cx2.am[0]; + let l2 = nested_mat_cx2.am[0][0]; + let l3 = nested_mat_cx2.am[0][idx]; + let l4 = nested_mat_cx2.am[0][0][1]; + let l5 = nested_mat_cx2.am[0][0][idx]; + let l6 = nested_mat_cx2.am[0][idx][1]; + let l7 = nested_mat_cx2.am[0][idx][idx]; var t = MatCx2InArray(array, 2>()); @@ -134,7 +134,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { c2[vi + 1u] = 42; let value = c2[vi]; - _ = test_arr_as_arg(array, 5>()); + test_arr_as_arg(array, 5>()); return vec4(_matrix * vec4(vec4(value)), 2.0); } diff --git a/tests/in/array-in-ctor.wgsl b/tests/in/array-in-ctor.wgsl index a7ca66be6..9607826fd 100644 --- a/tests/in/array-in-ctor.wgsl +++ b/tests/in/array-in-ctor.wgsl @@ -6,5 +6,5 @@ var ah: Ah; @compute @workgroup_size(1) fn cs_main() { - _ = ah; + let ah = ah; } diff --git a/tests/in/atomicOps.wgsl b/tests/in/atomicOps.wgsl index 111a9abbc..c1dd6b632 100644 --- a/tests/in/atomicOps.wgsl +++ b/tests/in/atomicOps.wgsl @@ -34,14 +34,14 @@ fn cs_main(@builtin(local_invocation_id) id: vec3) { workgroupBarrier(); - atomicLoad(&storage_atomic_scalar); - atomicLoad(&storage_atomic_arr[1]); - atomicLoad(&storage_struct.atomic_scalar); - atomicLoad(&storage_struct.atomic_arr[1]); - atomicLoad(&workgroup_atomic_scalar); - atomicLoad(&workgroup_atomic_arr[1]); - atomicLoad(&workgroup_struct.atomic_scalar); - atomicLoad(&workgroup_struct.atomic_arr[1]); + let l0 = atomicLoad(&storage_atomic_scalar); + let l1 = atomicLoad(&storage_atomic_arr[1]); + let l2 = atomicLoad(&storage_struct.atomic_scalar); + let l3 = atomicLoad(&storage_struct.atomic_arr[1]); + let l4 = atomicLoad(&workgroup_atomic_scalar); + let l5 = atomicLoad(&workgroup_atomic_arr[1]); + let l6 = atomicLoad(&workgroup_struct.atomic_scalar); + let l7 = atomicLoad(&workgroup_struct.atomic_arr[1]); workgroupBarrier(); diff --git a/tests/in/globals.wgsl b/tests/in/globals.wgsl index 8f687fd35..859ad369e 100644 --- a/tests/in/globals.wgsl +++ b/tests/in/globals.wgsl @@ -45,17 +45,17 @@ fn test_msl_packed_vec3() { let data = alignment; // loads - _ = data.v3; - _ = data.v3.zx; + let l0 = data.v3; + let l1 = data.v3.zx; test_msl_packed_vec3_as_arg(data.v3); // matrix vector multiplication - _ = data.v3 * mat3x3(); - _ = mat3x3() * data.v3; + let mvm0 = data.v3 * mat3x3(); + let mvm1 = mat3x3() * data.v3; // scalar vector multiplication - _ = data.v3 * 2.0; - _ = 2.0 * data.v3; + let svm0 = data.v3 * 2.0; + let svm1 = 2.0 * data.v3; } @compute @workgroup_size(1) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index eadafbdc1..365a03992 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -50,11 +50,11 @@ fn constructors() -> f32 { var foo: Foo; foo = Foo(vec4(1.0), 1); - let mat2comp = mat2x2( + let m0 = mat2x2( 1.0, 0.0, 0.0, 1.0, ); - let mat4comp = mat4x4( + let m1 = mat4x4( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, @@ -62,219 +62,221 @@ fn constructors() -> f32 { ); // zero value constructors - _ = bool(); - _ = i32(); - _ = u32(); - _ = f32(); - _ = vec2(); - _ = mat2x2(); - _ = array(); - _ = Foo(); + let zvc0 = bool(); + let zvc1 = i32(); + let zvc2 = u32(); + let zvc3 = f32(); + let zvc4 = vec2(); + let zvc5 = mat2x2(); + let zvc6 = array(); + let zvc7 = Foo(); // constructors that infer their type from their parameters - _ = vec2(0u); - _ = mat2x2(vec2(0.), vec2(0.)); - _ = array(0, 1, 2, 3); + let cit0 = vec2(0u); + let cit1 = mat2x2(vec2(0.), vec2(0.)); + let cit2 = array(0, 1, 2, 3); // identity constructors - _ = bool(bool()); - _ = i32(i32()); - _ = u32(u32()); - _ = f32(f32()); - _ = vec2(vec2()); - _ = mat2x3(mat2x3()); - _ = vec2(vec2()); - _ = mat2x3(mat2x3()); + let ic0 = bool(bool()); + let ic1 = i32(i32()); + let ic2 = u32(u32()); + let ic3 = f32(f32()); + let ic4 = vec2(vec2()); + let ic5 = mat2x3(mat2x3()); + let ic6 = vec2(vec2()); + let ic7 = mat2x3(mat2x3()); return foo.a.x; } fn logical() { // unary - _ = !true; - _ = !vec2(true); + let neg0 = !true; + let neg1 = !vec2(true); // binary - _ = true || false; - _ = true && false; - _ = true | false; - _ = vec3(true) | vec3(false); - _ = true & false; - _ = vec4(true) & vec4(false); + let or = true || false; + let and = true && false; + let bitwise_or0 = true | false; + let bitwise_or1 = vec3(true) | vec3(false); + let bitwise_and0 = true & false; + let bitwise_and1 = vec4(true) & vec4(false); } fn arithmetic() { // unary - _ = -1.0; - _ = -vec2(1); - _ = -vec2(1.0); + let neg0 = -1.0; + let neg1 = -vec2(1); + let neg2 = -vec2(1.0); // binary // Addition - _ = 2 + 1; - _ = 2u + 1u; - _ = 2.0 + 1.0; - _ = vec2(2) + vec2(1); - _ = vec3(2u) + vec3(1u); - _ = vec4(2.0) + vec4(1.0); + let add0 = 2 + 1; + let add1 = 2u + 1u; + let add2 = 2.0 + 1.0; + let add3 = vec2(2) + vec2(1); + let add4 = vec3(2u) + vec3(1u); + let add5 = vec4(2.0) + vec4(1.0); // Subtraction - _ = 2 - 1; - _ = 2u - 1u; - _ = 2.0 - 1.0; - _ = vec2(2) - vec2(1); - _ = vec3(2u) - vec3(1u); - _ = vec4(2.0) - vec4(1.0); + let sub0 = 2 - 1; + let sub1 = 2u - 1u; + let sub2 = 2.0 - 1.0; + let sub3 = vec2(2) - vec2(1); + let sub4 = vec3(2u) - vec3(1u); + let sub5 = vec4(2.0) - vec4(1.0); // Multiplication - _ = 2 * 1; - _ = 2u * 1u; - _ = 2.0 * 1.0; - _ = vec2(2) * vec2(1); - _ = vec3(2u) * vec3(1u); - _ = vec4(2.0) * vec4(1.0); + let mul0 = 2 * 1; + let mul1 = 2u * 1u; + let mul2 = 2.0 * 1.0; + let mul3 = vec2(2) * vec2(1); + let mul4 = vec3(2u) * vec3(1u); + let mul5 = vec4(2.0) * vec4(1.0); // Division - _ = 2 / 1; - _ = 2u / 1u; - _ = 2.0 / 1.0; - _ = vec2(2) / vec2(1); - _ = vec3(2u) / vec3(1u); - _ = vec4(2.0) / vec4(1.0); + let div0 = 2 / 1; + let div1 = 2u / 1u; + let div2 = 2.0 / 1.0; + let div3 = vec2(2) / vec2(1); + let div4 = vec3(2u) / vec3(1u); + let div5 = vec4(2.0) / vec4(1.0); // Remainder - _ = 2 % 1; - _ = 2u % 1u; - _ = 2.0 % 1.0; - _ = vec2(2) % vec2(1); - _ = vec3(2u) % vec3(1u); - _ = vec4(2.0) % vec4(1.0); + let rem0 = 2 % 1; + let rem1 = 2u % 1u; + let rem2 = 2.0 % 1.0; + let rem3 = vec2(2) % vec2(1); + let rem4 = vec3(2u) % vec3(1u); + let rem5 = vec4(2.0) % vec4(1.0); // Binary arithmetic expressions with mixed scalar and vector operands - _ = vec2(2) + 1; - _ = 2 + vec2(1); - _ = vec2(2u) + 1u; - _ = 2u + vec2(1u); - _ = vec2(2.0) + 1.0; - _ = 2.0 + vec2(1.0); + { + let add0 = vec2(2) + 1; + let add1 = 2 + vec2(1); + let add2 = vec2(2u) + 1u; + let add3 = 2u + vec2(1u); + let add4 = vec2(2.0) + 1.0; + let add5 = 2.0 + vec2(1.0); - _ = vec2(2) - 1; - _ = 2 - vec2(1); - _ = vec2(2u) - 1u; - _ = 2u - vec2(1u); - _ = vec2(2.0) - 1.0; - _ = 2.0 - vec2(1.0); + let sub0 = vec2(2) - 1; + let sub1 = 2 - vec2(1); + let sub2 = vec2(2u) - 1u; + let sub3 = 2u - vec2(1u); + let sub4 = vec2(2.0) - 1.0; + let sub5 = 2.0 - vec2(1.0); - _ = vec2(2) * 1; - _ = 2 * vec2(1); - _ = vec2(2u) * 1u; - _ = 2u * vec2(1u); - _ = vec2(2.0) * 1.0; - _ = 2.0 * vec2(1.0); + let mul0 = vec2(2) * 1; + let mul1 = 2 * vec2(1); + let mul2 = vec2(2u) * 1u; + let mul3 = 2u * vec2(1u); + let mul4 = vec2(2.0) * 1.0; + let mul5 = 2.0 * vec2(1.0); - _ = vec2(2) / 1; - _ = 2 / vec2(1); - _ = vec2(2u) / 1u; - _ = 2u / vec2(1u); - _ = vec2(2.0) / 1.0; - _ = 2.0 / vec2(1.0); + let div0 = vec2(2) / 1; + let div1 = 2 / vec2(1); + let div2 = vec2(2u) / 1u; + let div3 = 2u / vec2(1u); + let div4 = vec2(2.0) / 1.0; + let div5 = 2.0 / vec2(1.0); - _ = vec2(2) % 1; - _ = 2 % vec2(1); - _ = vec2(2u) % 1u; - _ = 2u % vec2(1u); - _ = vec2(2.0) % 1.0; - _ = 2.0 % vec2(1.0); + let rem0 = vec2(2) % 1; + let rem1 = 2 % vec2(1); + let rem2 = vec2(2u) % 1u; + let rem3 = 2u % vec2(1u); + let rem4 = vec2(2.0) % 1.0; + let rem5 = 2.0 % vec2(1.0); + } // Matrix arithmetic - _ = mat3x3() + mat3x3(); - _ = mat3x3() - mat3x3(); + let add = mat3x3() + mat3x3(); + let sub = mat3x3() - mat3x3(); - _ = mat3x3() * 1.0; - _ = 2.0 * mat3x3(); + let mul_scalar0 = mat3x3() * 1.0; + let mul_scalar1 = 2.0 * mat3x3(); - _ = mat4x3() * vec4(1.0); - _ = vec3f(2.0) * mat4x3f(); + let mul_vector0 = mat4x3() * vec4(1.0); + let mul_vector1 = vec3f(2.0) * mat4x3f(); - _ = mat4x3() * mat3x4(); + let mul = mat4x3() * mat3x4(); } fn bit() { // unary - _ = ~1; - _ = ~1u; - _ = ~vec2(1); - _ = ~vec3(1u); + let flip0 = ~1; + let flip1 = ~1u; + let flip2 = ~vec2(1); + let flip3 = ~vec3(1u); // binary - _ = 2 | 1; - _ = 2u | 1u; - _ = vec2(2) | vec2(1); - _ = vec3(2u) | vec3(1u); + let or0 = 2 | 1; + let or1 = 2u | 1u; + let or2 = vec2(2) | vec2(1); + let or3 = vec3(2u) | vec3(1u); - _ = 2 & 1; - _ = 2u & 1u; - _ = vec2(2) & vec2(1); - _ = vec3(2u) & vec3(1u); + let and0 = 2 & 1; + let and1 = 2u & 1u; + let and2 = vec2(2) & vec2(1); + let and3 = vec3(2u) & vec3(1u); - _ = 2 ^ 1; - _ = 2u ^ 1u; - _ = vec2(2) ^ vec2(1); - _ = vec3(2u) ^ vec3(1u); + let xor0 = 2 ^ 1; + let xor1 = 2u ^ 1u; + let xor2 = vec2(2) ^ vec2(1); + let xor3 = vec3(2u) ^ vec3(1u); - _ = 2 << 1u; - _ = 2u << 1u; - _ = vec2(2) << vec2(1u); - _ = vec3(2u) << vec3(1u); + let shl0 = 2 << 1u; + let shl1 = 2u << 1u; + let shl2 = vec2(2) << vec2(1u); + let shl3 = vec3(2u) << vec3(1u); - _ = 2 >> 1u; - _ = 2u >> 1u; - _ = vec2(2) >> vec2(1u); - _ = vec3(2u) >> vec3(1u); + let shr0 = 2 >> 1u; + let shr1 = 2u >> 1u; + let shr2 = vec2(2) >> vec2(1u); + let shr3 = vec3(2u) >> vec3(1u); } fn comparison() { - _ = 2 == 1; - _ = 2u == 1u; - _ = 2.0 == 1.0; - _ = vec2(2) == vec2(1); - _ = vec3(2u) == vec3(1u); - _ = vec4(2.0) == vec4(1.0); + let eq0 = 2 == 1; + let eq1 = 2u == 1u; + let eq2 = 2.0 == 1.0; + let eq3 = vec2(2) == vec2(1); + let eq4 = vec3(2u) == vec3(1u); + let eq5 = vec4(2.0) == vec4(1.0); - _ = 2 != 1; - _ = 2u != 1u; - _ = 2.0 != 1.0; - _ = vec2(2) != vec2(1); - _ = vec3(2u) != vec3(1u); - _ = vec4(2.0) != vec4(1.0); + let neq0 = 2 != 1; + let neq1 = 2u != 1u; + let neq2 = 2.0 != 1.0; + let neq3 = vec2(2) != vec2(1); + let neq4 = vec3(2u) != vec3(1u); + let neq5 = vec4(2.0) != vec4(1.0); - _ = 2 < 1; - _ = 2u < 1u; - _ = 2.0 < 1.0; - _ = vec2(2) < vec2(1); - _ = vec3(2u) < vec3(1u); - _ = vec4(2.0) < vec4(1.0); + let lt0 = 2 < 1; + let lt1 = 2u < 1u; + let lt2 = 2.0 < 1.0; + let lt3 = vec2(2) < vec2(1); + let lt4 = vec3(2u) < vec3(1u); + let lt5 = vec4(2.0) < vec4(1.0); - _ = 2 <= 1; - _ = 2u <= 1u; - _ = 2.0 <= 1.0; - _ = vec2(2) <= vec2(1); - _ = vec3(2u) <= vec3(1u); - _ = vec4(2.0) <= vec4(1.0); + let lte0 = 2 <= 1; + let lte1 = 2u <= 1u; + let lte2 = 2.0 <= 1.0; + let lte3 = vec2(2) <= vec2(1); + let lte4 = vec3(2u) <= vec3(1u); + let lte5 = vec4(2.0) <= vec4(1.0); - _ = 2 > 1; - _ = 2u > 1u; - _ = 2.0 > 1.0; - _ = vec2(2) > vec2(1); - _ = vec3(2u) > vec3(1u); - _ = vec4(2.0) > vec4(1.0); + let gt0 = 2 > 1; + let gt1 = 2u > 1u; + let gt2 = 2.0 > 1.0; + let gt3 = vec2(2) > vec2(1); + let gt4 = vec3(2u) > vec3(1u); + let gt5 = vec4(2.0) > vec4(1.0); - _ = 2 >= 1; - _ = 2u >= 1u; - _ = 2.0 >= 1.0; - _ = vec2(2) >= vec2(1); - _ = vec3(2u) >= vec3(1u); - _ = vec4(2.0) >= vec4(1.0); + let gte0 = 2 >= 1; + let gte1 = 2u >= 1u; + let gte2 = 2.0 >= 1.0; + let gte3 = vec2(2) >= vec2(1); + let gte4 = vec3(2u) >= vec3(1u); + let gte5 = vec4(2.0) >= vec4(1.0); } fn assignment() { @@ -301,10 +303,10 @@ fn assignment() { @compute @workgroup_size(1) fn main() { - _ = builtins(); - _ = splat(); - _ = bool_cast(v_f32_one.xyz); - _ = constructors(); + builtins(); + splat(); + bool_cast(v_f32_one.xyz); + constructors(); logical(); arithmetic(); @@ -314,12 +316,12 @@ fn main() { } fn negation_avoids_prefix_decrement() { - _ = -1; - _ = - -2; - _ = -(-3); - _ = -(- 4); - _ = - - -5; - _ = - - - - 6; - _ = - - -(- -7); - _ = (- - - - -8); + let p0 = -1; + let p1 = - -2; + let p2 = -(-3); + let p3 = -(- 4); + let p4 = - - -5; + let p5 = - - - - 6; + let p6 = - - -(- -7); + let p7 = (- - - - -8); } diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index f3754247b..2a5e03882 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -39,18 +39,18 @@ void test_matrix_within_struct_accesses() { idx = 1; int _e2 = idx; idx = (_e2 - 1); - mat3x2 unnamed = _group_0_binding_1_vs.m; - vec2 unnamed_1 = _group_0_binding_1_vs.m[0]; + mat3x2 l0_ = _group_0_binding_1_vs.m; + vec2 l1_ = _group_0_binding_1_vs.m[0]; int _e15 = idx; - vec2 unnamed_2 = _group_0_binding_1_vs.m[_e15]; - float unnamed_3 = _group_0_binding_1_vs.m[0][1]; + vec2 l2_ = _group_0_binding_1_vs.m[_e15]; + float l3_ = _group_0_binding_1_vs.m[0][1]; int _e29 = idx; - float unnamed_4 = _group_0_binding_1_vs.m[0][_e29]; + float l4_ = _group_0_binding_1_vs.m[0][_e29]; int _e34 = idx; - float unnamed_5 = _group_0_binding_1_vs.m[_e34][1]; + float l5_ = _group_0_binding_1_vs.m[_e34][1]; int _e41 = idx; int _e43 = idx; - float unnamed_6 = _group_0_binding_1_vs.m[_e41][_e43]; + float l6_ = _group_0_binding_1_vs.m[_e41][_e43]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); int _e55 = idx; idx = (_e55 + 1); @@ -75,19 +75,19 @@ void test_matrix_within_array_within_struct_accesses() { idx_1 = 1; int _e2 = idx_1; idx_1 = (_e2 - 1); - mat4x2 unnamed_7[2] = _group_0_binding_3_vs.am; - mat4x2 unnamed_8 = _group_0_binding_3_vs.am[0]; - vec2 unnamed_9 = _group_0_binding_3_vs.am[0][0]; + mat4x2 l0_1[2] = _group_0_binding_3_vs.am; + mat4x2 l1_1 = _group_0_binding_3_vs.am[0]; + vec2 l2_1 = _group_0_binding_3_vs.am[0][0]; int _e24 = idx_1; - vec2 unnamed_10 = _group_0_binding_3_vs.am[0][_e24]; - float unnamed_11 = _group_0_binding_3_vs.am[0][0][1]; + vec2 l3_1 = _group_0_binding_3_vs.am[0][_e24]; + float l4_1 = _group_0_binding_3_vs.am[0][0][1]; int _e42 = idx_1; - float unnamed_12 = _group_0_binding_3_vs.am[0][0][_e42]; + float l5_1 = _group_0_binding_3_vs.am[0][0][_e42]; int _e49 = idx_1; - float unnamed_13 = _group_0_binding_3_vs.am[0][_e49][1]; + float l6_1 = _group_0_binding_3_vs.am[0][_e49][1]; int _e58 = idx_1; int _e60 = idx_1; - float unnamed_14 = _group_0_binding_3_vs.am[0][_e58][_e60]; + float l7_ = _group_0_binding_3_vs.am[0][_e58][_e60]; t_1 = MatCx2InArray(mat4x2[2](mat4x2(0.0), mat4x2(0.0))); int _e66 = idx_1; idx_1 = (_e66 + 1); diff --git a/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl b/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl index e8245d55e..bd918087b 100644 --- a/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl +++ b/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl @@ -12,6 +12,6 @@ layout(std430) readonly buffer Ah_block_0Compute { Ah _group_0_binding_0_cs; }; void main() { - Ah unnamed = _group_0_binding_0_cs; + Ah ah_1 = _group_0_binding_0_cs; } diff --git a/tests/out/glsl/atomicOps.cs_main.Compute.glsl b/tests/out/glsl/atomicOps.cs_main.Compute.glsl index 30086fa8e..c40e85d30 100644 --- a/tests/out/glsl/atomicOps.cs_main.Compute.glsl +++ b/tests/out/glsl/atomicOps.cs_main.Compute.glsl @@ -41,14 +41,14 @@ void main() { workgroup_struct.atomic_arr[1] = 1; memoryBarrierShared(); barrier(); - uint unnamed = _group_0_binding_0_cs; - int unnamed_1 = _group_0_binding_1_cs[1]; - uint unnamed_2 = _group_0_binding_2_cs.atomic_scalar; - int unnamed_3 = _group_0_binding_2_cs.atomic_arr[1]; - uint unnamed_4 = workgroup_atomic_scalar; - int unnamed_5 = workgroup_atomic_arr[1]; - uint unnamed_6 = workgroup_struct.atomic_scalar; - int unnamed_7 = workgroup_struct.atomic_arr[1]; + uint l0_ = _group_0_binding_0_cs; + int l1_ = _group_0_binding_1_cs[1]; + uint l2_ = _group_0_binding_2_cs.atomic_scalar; + int l3_ = _group_0_binding_2_cs.atomic_arr[1]; + uint l4_ = workgroup_atomic_scalar; + int l5_ = workgroup_atomic_arr[1]; + uint l6_ = workgroup_struct.atomic_scalar; + int l7_ = workgroup_struct.atomic_arr[1]; memoryBarrierShared(); barrier(); uint _e59 = atomicAdd(_group_0_binding_0_cs, 1u); diff --git a/tests/out/glsl/break-if.main.Compute.glsl b/tests/out/glsl/break-if.main.Compute.glsl index 025156af7..b4554d5d3 100644 --- a/tests/out/glsl/break-if.main.Compute.glsl +++ b/tests/out/glsl/break-if.main.Compute.glsl @@ -29,8 +29,7 @@ void breakIfEmptyBody(bool a) { bool _e2 = b; c = (a != _e2); bool _e5 = c; - bool unnamed = (a == _e5); - if (unnamed) { + if ((a == _e5)) { break; } } @@ -46,8 +45,7 @@ void breakIf(bool a_1) { while(true) { if (!loop_init_2) { bool _e5 = e; - bool unnamed_1 = (a_1 == _e5); - if (unnamed_1) { + if ((a_1 == _e5)) { break; } } diff --git a/tests/out/glsl/do-while.main.Fragment.glsl b/tests/out/glsl/do-while.main.Fragment.glsl index 1d1ca4e8e..56a69123c 100644 --- a/tests/out/glsl/do-while.main.Fragment.glsl +++ b/tests/out/glsl/do-while.main.Fragment.glsl @@ -9,8 +9,7 @@ void fb1_(inout bool cond) { while(true) { if (!loop_init) { bool _e6 = cond; - bool unnamed = !(_e6); - if (unnamed) { + if (!(_e6)) { break; } } diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index cb695ac1d..5c194d532 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -41,13 +41,13 @@ void test_msl_packed_vec3_() { int _e17 = idx; _group_0_binding_1_cs.v3_[_e17] = 3.0; FooStruct data = _group_0_binding_1_cs; - vec3 unnamed = data.v3_; - vec2 unnamed_1 = data.v3_.zx; + vec3 l0_ = data.v3_; + vec2 l1_ = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); - vec3 unnamed_2 = (data.v3_ * mat3x3(0.0)); - vec3 unnamed_3 = (mat3x3(0.0) * data.v3_); - vec3 unnamed_4 = (data.v3_ * 2.0); - vec3 unnamed_5 = (2.0 * data.v3_); + vec3 mvm0_ = (data.v3_ * mat3x3(0.0)); + vec3 mvm1_ = (mat3x3(0.0) * data.v3_); + vec3 svm0_ = (data.v3_ * 2.0); + vec3 svm1_ = (2.0 * data.v3_); } void main() { diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 9754ae2bb..d3859ef63 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -49,170 +49,172 @@ vec3 bool_cast(vec3 x) { float constructors() { Foo foo = Foo(vec4(0.0), 0); foo = Foo(vec4(1.0), 1); - mat2x2 mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); - mat4x4 mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - uvec2 unnamed = uvec2(0u); - mat2x2 unnamed_1 = mat2x2(vec2(0.0), vec2(0.0)); - int unnamed_2[4] = int[4](0, 1, 2, 3); - bool unnamed_3 = bool(false); - int unnamed_4 = int(0); - uint unnamed_5 = uint(0u); - float unnamed_6 = float(0.0); - uvec2 unnamed_7 = uvec2(uvec2(0u)); - mat2x3 unnamed_8 = mat2x3(mat2x3(0.0)); - uvec2 unnamed_9 = uvec2(0u); - mat2x3 unnamed_10 = mat2x3(0.0); + mat2x2 m0_ = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); + mat4x4 m1_1 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + uvec2 cit0_ = uvec2(0u); + mat2x2 cit1_ = mat2x2(vec2(0.0), vec2(0.0)); + int cit2_[4] = int[4](0, 1, 2, 3); + bool ic0_ = bool(false); + int ic1_ = int(0); + uint ic2_ = uint(0u); + float ic3_ = float(0.0); + uvec2 ic4_ = uvec2(uvec2(0u)); + mat2x3 ic5_ = mat2x3(mat2x3(0.0)); + uvec2 ic6_ = uvec2(0u); + mat2x3 ic7_ = mat2x3(0.0); float _e71 = foo.a.x; return _e71; } void logical() { - bool unnamed_11 = !(true); - bvec2 unnamed_12 = not(bvec2(true)); - bool unnamed_13 = (true || false); - bool unnamed_14 = (true && false); - bool unnamed_15 = (true || false); - bvec3 unnamed_16 = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); - bool unnamed_17 = (true && false); - bvec4 unnamed_18 = bvec4(bvec4(true).x && bvec4(false).x, bvec4(true).y && bvec4(false).y, bvec4(true).z && bvec4(false).z, bvec4(true).w && bvec4(false).w); + bool neg0_ = !(true); + bvec2 neg1_ = not(bvec2(true)); + bool or = (true || false); + bool and = (true && false); + bool bitwise_or0_ = (true || false); + bvec3 bitwise_or1_ = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); + bool bitwise_and0_ = (true && false); + bvec4 bitwise_and1_ = bvec4(bvec4(true).x && bvec4(false).x, bvec4(true).y && bvec4(false).y, bvec4(true).z && bvec4(false).z, bvec4(true).w && bvec4(false).w); } void arithmetic() { - ivec2 unnamed_19 = -(ivec2(1)); - vec2 unnamed_20 = -(vec2(1.0)); - int unnamed_21 = (2 + 1); - uint unnamed_22 = (2u + 1u); - float unnamed_23 = (2.0 + 1.0); - ivec2 unnamed_24 = (ivec2(2) + ivec2(1)); - uvec3 unnamed_25 = (uvec3(2u) + uvec3(1u)); - vec4 unnamed_26 = (vec4(2.0) + vec4(1.0)); - int unnamed_27 = (2 - 1); - uint unnamed_28 = (2u - 1u); - float unnamed_29 = (2.0 - 1.0); - ivec2 unnamed_30 = (ivec2(2) - ivec2(1)); - uvec3 unnamed_31 = (uvec3(2u) - uvec3(1u)); - vec4 unnamed_32 = (vec4(2.0) - vec4(1.0)); - int unnamed_33 = (2 * 1); - uint unnamed_34 = (2u * 1u); - float unnamed_35 = (2.0 * 1.0); - ivec2 unnamed_36 = (ivec2(2) * ivec2(1)); - uvec3 unnamed_37 = (uvec3(2u) * uvec3(1u)); - vec4 unnamed_38 = (vec4(2.0) * vec4(1.0)); - int unnamed_39 = (2 / 1); - uint unnamed_40 = (2u / 1u); - float unnamed_41 = (2.0 / 1.0); - ivec2 unnamed_42 = (ivec2(2) / ivec2(1)); - uvec3 unnamed_43 = (uvec3(2u) / uvec3(1u)); - vec4 unnamed_44 = (vec4(2.0) / vec4(1.0)); - int unnamed_45 = (2 % 1); - uint unnamed_46 = (2u % 1u); - float unnamed_47 = (2.0 - 1.0 * trunc(2.0 / 1.0)); - ivec2 unnamed_48 = (ivec2(2) % ivec2(1)); - uvec3 unnamed_49 = (uvec3(2u) % uvec3(1u)); - vec4 unnamed_50 = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); - ivec2 unnamed_51 = (ivec2(2) + ivec2(1)); - ivec2 unnamed_52 = (ivec2(2) + ivec2(1)); - uvec2 unnamed_53 = (uvec2(2u) + uvec2(1u)); - uvec2 unnamed_54 = (uvec2(2u) + uvec2(1u)); - vec2 unnamed_55 = (vec2(2.0) + vec2(1.0)); - vec2 unnamed_56 = (vec2(2.0) + vec2(1.0)); - ivec2 unnamed_57 = (ivec2(2) - ivec2(1)); - ivec2 unnamed_58 = (ivec2(2) - ivec2(1)); - uvec2 unnamed_59 = (uvec2(2u) - uvec2(1u)); - uvec2 unnamed_60 = (uvec2(2u) - uvec2(1u)); - vec2 unnamed_61 = (vec2(2.0) - vec2(1.0)); - vec2 unnamed_62 = (vec2(2.0) - vec2(1.0)); - ivec2 unnamed_63 = (ivec2(2) * 1); - ivec2 unnamed_64 = (2 * ivec2(1)); - uvec2 unnamed_65 = (uvec2(2u) * 1u); - uvec2 unnamed_66 = (2u * uvec2(1u)); - vec2 unnamed_67 = (vec2(2.0) * 1.0); - vec2 unnamed_68 = (2.0 * vec2(1.0)); - ivec2 unnamed_69 = (ivec2(2) / ivec2(1)); - ivec2 unnamed_70 = (ivec2(2) / ivec2(1)); - uvec2 unnamed_71 = (uvec2(2u) / uvec2(1u)); - uvec2 unnamed_72 = (uvec2(2u) / uvec2(1u)); - vec2 unnamed_73 = (vec2(2.0) / vec2(1.0)); - vec2 unnamed_74 = (vec2(2.0) / vec2(1.0)); - ivec2 unnamed_75 = (ivec2(2) % ivec2(1)); - ivec2 unnamed_76 = (ivec2(2) % ivec2(1)); - uvec2 unnamed_77 = (uvec2(2u) % uvec2(1u)); - uvec2 unnamed_78 = (uvec2(2u) % uvec2(1u)); - vec2 unnamed_79 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); - vec2 unnamed_80 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); - mat3x3 unnamed_81 = (mat3x3(0.0) + mat3x3(0.0)); - mat3x3 unnamed_82 = (mat3x3(0.0) - mat3x3(0.0)); - mat3x3 unnamed_83 = (mat3x3(0.0) * 1.0); - mat3x3 unnamed_84 = (2.0 * mat3x3(0.0)); - vec3 unnamed_85 = (mat4x3(0.0) * vec4(1.0)); - vec4 unnamed_86 = (vec3(2.0) * mat4x3(0.0)); - mat3x3 unnamed_87 = (mat4x3(0.0) * mat3x4(0.0)); + ivec2 neg1_1 = -(ivec2(1)); + vec2 neg2_ = -(vec2(1.0)); + int add0_ = (2 + 1); + uint add1_ = (2u + 1u); + float add2_ = (2.0 + 1.0); + ivec2 add3_ = (ivec2(2) + ivec2(1)); + uvec3 add4_ = (uvec3(2u) + uvec3(1u)); + vec4 add5_ = (vec4(2.0) + vec4(1.0)); + int sub0_ = (2 - 1); + uint sub1_ = (2u - 1u); + float sub2_ = (2.0 - 1.0); + ivec2 sub3_ = (ivec2(2) - ivec2(1)); + uvec3 sub4_ = (uvec3(2u) - uvec3(1u)); + vec4 sub5_ = (vec4(2.0) - vec4(1.0)); + int mul0_ = (2 * 1); + uint mul1_ = (2u * 1u); + float mul2_ = (2.0 * 1.0); + ivec2 mul3_ = (ivec2(2) * ivec2(1)); + uvec3 mul4_ = (uvec3(2u) * uvec3(1u)); + vec4 mul5_ = (vec4(2.0) * vec4(1.0)); + int div0_ = (2 / 1); + uint div1_ = (2u / 1u); + float div2_ = (2.0 / 1.0); + ivec2 div3_ = (ivec2(2) / ivec2(1)); + uvec3 div4_ = (uvec3(2u) / uvec3(1u)); + vec4 div5_ = (vec4(2.0) / vec4(1.0)); + int rem0_ = (2 % 1); + uint rem1_ = (2u % 1u); + float rem2_ = (2.0 - 1.0 * trunc(2.0 / 1.0)); + ivec2 rem3_ = (ivec2(2) % ivec2(1)); + uvec3 rem4_ = (uvec3(2u) % uvec3(1u)); + vec4 rem5_ = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); + { + ivec2 add0_1 = (ivec2(2) + ivec2(1)); + ivec2 add1_1 = (ivec2(2) + ivec2(1)); + uvec2 add2_1 = (uvec2(2u) + uvec2(1u)); + uvec2 add3_1 = (uvec2(2u) + uvec2(1u)); + vec2 add4_1 = (vec2(2.0) + vec2(1.0)); + vec2 add5_1 = (vec2(2.0) + vec2(1.0)); + ivec2 sub0_1 = (ivec2(2) - ivec2(1)); + ivec2 sub1_1 = (ivec2(2) - ivec2(1)); + uvec2 sub2_1 = (uvec2(2u) - uvec2(1u)); + uvec2 sub3_1 = (uvec2(2u) - uvec2(1u)); + vec2 sub4_1 = (vec2(2.0) - vec2(1.0)); + vec2 sub5_1 = (vec2(2.0) - vec2(1.0)); + ivec2 mul0_1 = (ivec2(2) * 1); + ivec2 mul1_1 = (2 * ivec2(1)); + uvec2 mul2_1 = (uvec2(2u) * 1u); + uvec2 mul3_1 = (2u * uvec2(1u)); + vec2 mul4_1 = (vec2(2.0) * 1.0); + vec2 mul5_1 = (2.0 * vec2(1.0)); + ivec2 div0_1 = (ivec2(2) / ivec2(1)); + ivec2 div1_1 = (ivec2(2) / ivec2(1)); + uvec2 div2_1 = (uvec2(2u) / uvec2(1u)); + uvec2 div3_1 = (uvec2(2u) / uvec2(1u)); + vec2 div4_1 = (vec2(2.0) / vec2(1.0)); + vec2 div5_1 = (vec2(2.0) / vec2(1.0)); + ivec2 rem0_1 = (ivec2(2) % ivec2(1)); + ivec2 rem1_1 = (ivec2(2) % ivec2(1)); + uvec2 rem2_1 = (uvec2(2u) % uvec2(1u)); + uvec2 rem3_1 = (uvec2(2u) % uvec2(1u)); + vec2 rem4_1 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + vec2 rem5_1 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); + } + mat3x3 add = (mat3x3(0.0) + mat3x3(0.0)); + mat3x3 sub = (mat3x3(0.0) - mat3x3(0.0)); + mat3x3 mul_scalar0_ = (mat3x3(0.0) * 1.0); + mat3x3 mul_scalar1_ = (2.0 * mat3x3(0.0)); + vec3 mul_vector0_ = (mat4x3(0.0) * vec4(1.0)); + vec4 mul_vector1_ = (vec3(2.0) * mat4x3(0.0)); + mat3x3 mul = (mat4x3(0.0) * mat3x4(0.0)); } void bit() { - int unnamed_88 = ~(1); - uint unnamed_89 = ~(1u); - ivec2 unnamed_90 = ~(ivec2(1)); - uvec3 unnamed_91 = ~(uvec3(1u)); - int unnamed_92 = (2 | 1); - uint unnamed_93 = (2u | 1u); - ivec2 unnamed_94 = (ivec2(2) | ivec2(1)); - uvec3 unnamed_95 = (uvec3(2u) | uvec3(1u)); - int unnamed_96 = (2 & 1); - uint unnamed_97 = (2u & 1u); - ivec2 unnamed_98 = (ivec2(2) & ivec2(1)); - uvec3 unnamed_99 = (uvec3(2u) & uvec3(1u)); - int unnamed_100 = (2 ^ 1); - uint unnamed_101 = (2u ^ 1u); - ivec2 unnamed_102 = (ivec2(2) ^ ivec2(1)); - uvec3 unnamed_103 = (uvec3(2u) ^ uvec3(1u)); - int unnamed_104 = (2 << 1u); - uint unnamed_105 = (2u << 1u); - ivec2 unnamed_106 = (ivec2(2) << uvec2(1u)); - uvec3 unnamed_107 = (uvec3(2u) << uvec3(1u)); - int unnamed_108 = (2 >> 1u); - uint unnamed_109 = (2u >> 1u); - ivec2 unnamed_110 = (ivec2(2) >> uvec2(1u)); - uvec3 unnamed_111 = (uvec3(2u) >> uvec3(1u)); + int flip0_ = ~(1); + uint flip1_ = ~(1u); + ivec2 flip2_ = ~(ivec2(1)); + uvec3 flip3_ = ~(uvec3(1u)); + int or0_ = (2 | 1); + uint or1_ = (2u | 1u); + ivec2 or2_ = (ivec2(2) | ivec2(1)); + uvec3 or3_ = (uvec3(2u) | uvec3(1u)); + int and0_ = (2 & 1); + uint and1_ = (2u & 1u); + ivec2 and2_ = (ivec2(2) & ivec2(1)); + uvec3 and3_ = (uvec3(2u) & uvec3(1u)); + int xor0_ = (2 ^ 1); + uint xor1_ = (2u ^ 1u); + ivec2 xor2_ = (ivec2(2) ^ ivec2(1)); + uvec3 xor3_ = (uvec3(2u) ^ uvec3(1u)); + int shl0_ = (2 << 1u); + uint shl1_ = (2u << 1u); + ivec2 shl2_ = (ivec2(2) << uvec2(1u)); + uvec3 shl3_ = (uvec3(2u) << uvec3(1u)); + int shr0_ = (2 >> 1u); + uint shr1_ = (2u >> 1u); + ivec2 shr2_ = (ivec2(2) >> uvec2(1u)); + uvec3 shr3_ = (uvec3(2u) >> uvec3(1u)); } void comparison() { - bool unnamed_112 = (2 == 1); - bool unnamed_113 = (2u == 1u); - bool unnamed_114 = (2.0 == 1.0); - bvec2 unnamed_115 = equal(ivec2(2), ivec2(1)); - bvec3 unnamed_116 = equal(uvec3(2u), uvec3(1u)); - bvec4 unnamed_117 = equal(vec4(2.0), vec4(1.0)); - bool unnamed_118 = (2 != 1); - bool unnamed_119 = (2u != 1u); - bool unnamed_120 = (2.0 != 1.0); - bvec2 unnamed_121 = notEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_122 = notEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_123 = notEqual(vec4(2.0), vec4(1.0)); - bool unnamed_124 = (2 < 1); - bool unnamed_125 = (2u < 1u); - bool unnamed_126 = (2.0 < 1.0); - bvec2 unnamed_127 = lessThan(ivec2(2), ivec2(1)); - bvec3 unnamed_128 = lessThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_129 = lessThan(vec4(2.0), vec4(1.0)); - bool unnamed_130 = (2 <= 1); - bool unnamed_131 = (2u <= 1u); - bool unnamed_132 = (2.0 <= 1.0); - bvec2 unnamed_133 = lessThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_134 = lessThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_135 = lessThanEqual(vec4(2.0), vec4(1.0)); - bool unnamed_136 = (2 > 1); - bool unnamed_137 = (2u > 1u); - bool unnamed_138 = (2.0 > 1.0); - bvec2 unnamed_139 = greaterThan(ivec2(2), ivec2(1)); - bvec3 unnamed_140 = greaterThan(uvec3(2u), uvec3(1u)); - bvec4 unnamed_141 = greaterThan(vec4(2.0), vec4(1.0)); - bool unnamed_142 = (2 >= 1); - bool unnamed_143 = (2u >= 1u); - bool unnamed_144 = (2.0 >= 1.0); - bvec2 unnamed_145 = greaterThanEqual(ivec2(2), ivec2(1)); - bvec3 unnamed_146 = greaterThanEqual(uvec3(2u), uvec3(1u)); - bvec4 unnamed_147 = greaterThanEqual(vec4(2.0), vec4(1.0)); + bool eq0_ = (2 == 1); + bool eq1_ = (2u == 1u); + bool eq2_ = (2.0 == 1.0); + bvec2 eq3_ = equal(ivec2(2), ivec2(1)); + bvec3 eq4_ = equal(uvec3(2u), uvec3(1u)); + bvec4 eq5_ = equal(vec4(2.0), vec4(1.0)); + bool neq0_ = (2 != 1); + bool neq1_ = (2u != 1u); + bool neq2_ = (2.0 != 1.0); + bvec2 neq3_ = notEqual(ivec2(2), ivec2(1)); + bvec3 neq4_ = notEqual(uvec3(2u), uvec3(1u)); + bvec4 neq5_ = notEqual(vec4(2.0), vec4(1.0)); + bool lt0_ = (2 < 1); + bool lt1_ = (2u < 1u); + bool lt2_ = (2.0 < 1.0); + bvec2 lt3_ = lessThan(ivec2(2), ivec2(1)); + bvec3 lt4_ = lessThan(uvec3(2u), uvec3(1u)); + bvec4 lt5_ = lessThan(vec4(2.0), vec4(1.0)); + bool lte0_ = (2 <= 1); + bool lte1_ = (2u <= 1u); + bool lte2_ = (2.0 <= 1.0); + bvec2 lte3_ = lessThanEqual(ivec2(2), ivec2(1)); + bvec3 lte4_ = lessThanEqual(uvec3(2u), uvec3(1u)); + bvec4 lte5_ = lessThanEqual(vec4(2.0), vec4(1.0)); + bool gt0_ = (2 > 1); + bool gt1_ = (2u > 1u); + bool gt2_ = (2.0 > 1.0); + bvec2 gt3_ = greaterThan(ivec2(2), ivec2(1)); + bvec3 gt4_ = greaterThan(uvec3(2u), uvec3(1u)); + bvec4 gt5_ = greaterThan(vec4(2.0), vec4(1.0)); + bool gte0_ = (2 >= 1); + bool gte1_ = (2u >= 1u); + bool gte2_ = (2.0 >= 1.0); + bvec2 gte3_ = greaterThanEqual(ivec2(2), ivec2(1)); + bvec3 gte4_ = greaterThanEqual(uvec3(2u), uvec3(1u)); + bvec4 gte5_ = greaterThanEqual(vec4(2.0), vec4(1.0)); } void assignment() { @@ -254,13 +256,13 @@ void assignment() { } void negation_avoids_prefix_decrement() { - int unnamed_148 = -(-2); - int unnamed_149 = -(-3); - int unnamed_150 = -(-(4)); - int unnamed_151 = -(-(-5)); - int unnamed_152 = -(-(-(-(6)))); - int unnamed_153 = -(-(-(-(-7)))); - int unnamed_154 = -(-(-(-(-8)))); + int p1_ = -(-2); + int p2_ = -(-3); + int p3_ = -(-(4)); + int p4_ = -(-(-5)); + int p5_ = -(-(-(-(6)))); + int p6_ = -(-(-(-(-7)))); + int p7_ = -(-(-(-(-8)))); } void main() { diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 63814754e..2af083b72 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -126,18 +126,18 @@ void test_matrix_within_struct_accesses() idx = 1; int _expr2 = idx; idx = (_expr2 - 1); - float3x2 unnamed = GetMatmOnBaz(baz); - float2 unnamed_1 = GetMatmOnBaz(baz)[0]; + float3x2 l0_ = GetMatmOnBaz(baz); + float2 l1_ = GetMatmOnBaz(baz)[0]; int _expr15 = idx; - float2 unnamed_2 = GetMatmOnBaz(baz)[_expr15]; - float unnamed_3 = GetMatmOnBaz(baz)[0].y; + float2 l2_ = GetMatmOnBaz(baz)[_expr15]; + float l3_ = GetMatmOnBaz(baz)[0].y; int _expr29 = idx; - float unnamed_4 = GetMatmOnBaz(baz)[0][_expr29]; + float l4_ = GetMatmOnBaz(baz)[0][_expr29]; int _expr34 = idx; - float unnamed_5 = GetMatmOnBaz(baz)[_expr34].y; + float l5_ = GetMatmOnBaz(baz)[_expr34].y; int _expr41 = idx; int _expr43 = idx; - float unnamed_6 = GetMatmOnBaz(baz)[_expr41][_expr43]; + float l6_ = GetMatmOnBaz(baz)[_expr41][_expr43]; t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); int _expr55 = idx; idx = (_expr55 + 1); @@ -170,19 +170,19 @@ void test_matrix_within_array_within_struct_accesses() idx_1 = 1; int _expr2 = idx_1; idx_1 = (_expr2 - 1); - float4x2 unnamed_7[2] = ((float4x2[2])nested_mat_cx2_.am); - float4x2 unnamed_8 = ((float4x2)nested_mat_cx2_.am[0]); - float2 unnamed_9 = nested_mat_cx2_.am[0]._0; + float4x2 l0_1[2] = ((float4x2[2])nested_mat_cx2_.am); + float4x2 l1_1 = ((float4x2)nested_mat_cx2_.am[0]); + float2 l2_1 = nested_mat_cx2_.am[0]._0; int _expr24 = idx_1; - float2 unnamed_10 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr24); - float unnamed_11 = nested_mat_cx2_.am[0]._0.y; + float2 l3_1 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr24); + float l4_1 = nested_mat_cx2_.am[0]._0.y; int _expr42 = idx_1; - float unnamed_12 = nested_mat_cx2_.am[0]._0[_expr42]; + float l5_1 = nested_mat_cx2_.am[0]._0[_expr42]; int _expr49 = idx_1; - float unnamed_13 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr49).y; + float l6_1 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr49).y; int _expr58 = idx_1; int _expr60 = idx_1; - float unnamed_14 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr58)[_expr60]; + float l7_ = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr58)[_expr60]; t_1 = ConstructMatCx2InArray((float4x2[2])0); int _expr66 = idx_1; idx_1 = (_expr66 + 1); diff --git a/tests/out/hlsl/array-in-ctor.hlsl b/tests/out/hlsl/array-in-ctor.hlsl index edaa95473..e184339e9 100644 --- a/tests/out/hlsl/array-in-ctor.hlsl +++ b/tests/out/hlsl/array-in-ctor.hlsl @@ -20,5 +20,5 @@ Ah ConstructAh(float arg0[2]) { [numthreads(1, 1, 1)] void cs_main() { - Ah unnamed = ConstructAh(Constructarray2_float_(asfloat(ah.Load(0+0)), asfloat(ah.Load(0+4)))); + Ah ah_1 = ConstructAh(Constructarray2_float_(asfloat(ah.Load(0+0)), asfloat(ah.Load(0+4)))); } diff --git a/tests/out/hlsl/atomicOps.hlsl b/tests/out/hlsl/atomicOps.hlsl index f6322cd92..a45afb1a8 100644 --- a/tests/out/hlsl/atomicOps.hlsl +++ b/tests/out/hlsl/atomicOps.hlsl @@ -29,14 +29,14 @@ void cs_main(uint3 id : SV_GroupThreadID, uint3 __local_invocation_id : SV_Group workgroup_struct.atomic_scalar = 1u; workgroup_struct.atomic_arr[1] = 1; GroupMemoryBarrierWithGroupSync(); - uint unnamed = asuint(storage_atomic_scalar.Load(0)); - int unnamed_1 = asint(storage_atomic_arr.Load(4)); - uint unnamed_2 = asuint(storage_struct.Load(0)); - int unnamed_3 = asint(storage_struct.Load(4+4)); - uint unnamed_4 = workgroup_atomic_scalar; - int unnamed_5 = workgroup_atomic_arr[1]; - uint unnamed_6 = workgroup_struct.atomic_scalar; - int unnamed_7 = workgroup_struct.atomic_arr[1]; + uint l0_ = asuint(storage_atomic_scalar.Load(0)); + int l1_ = asint(storage_atomic_arr.Load(4)); + uint l2_ = asuint(storage_struct.Load(0)); + int l3_ = asint(storage_struct.Load(4+4)); + uint l4_ = workgroup_atomic_scalar; + int l5_ = workgroup_atomic_arr[1]; + uint l6_ = workgroup_struct.atomic_scalar; + int l7_ = workgroup_struct.atomic_arr[1]; GroupMemoryBarrierWithGroupSync(); uint _e59; storage_atomic_scalar.InterlockedAdd(0, 1u, _e59); int _e64; storage_atomic_arr.InterlockedAdd(4, 1, _e64); diff --git a/tests/out/hlsl/break-if.hlsl b/tests/out/hlsl/break-if.hlsl index fc91096a9..5a3a453e5 100644 --- a/tests/out/hlsl/break-if.hlsl +++ b/tests/out/hlsl/break-if.hlsl @@ -25,8 +25,7 @@ void breakIfEmptyBody(bool a) bool _expr2 = b; c = (a != _expr2); bool _expr5 = c; - bool unnamed = (a == _expr5); - if (unnamed) { + if ((a == _expr5)) { break; } } @@ -44,8 +43,7 @@ void breakIf(bool a_1) while(true) { if (!loop_init_2) { bool _expr5 = e; - bool unnamed_1 = (a_1 == _expr5); - if (unnamed_1) { + if ((a_1 == _expr5)) { break; } } diff --git a/tests/out/hlsl/do-while.hlsl b/tests/out/hlsl/do-while.hlsl index 17341a6cf..9f6a1854c 100644 --- a/tests/out/hlsl/do-while.hlsl +++ b/tests/out/hlsl/do-while.hlsl @@ -5,8 +5,7 @@ void fb1_(inout bool cond) while(true) { if (!loop_init) { bool _expr6 = cond; - bool unnamed = !(_expr6); - if (unnamed) { + if (!(_expr6)) { break; } } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index 9d7eb2e99..b0b92f206 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -89,13 +89,13 @@ void test_msl_packed_vec3_() int _expr17 = idx; alignment.Store(_expr17*4+0, asuint(3.0)); FooStruct data = ConstructFooStruct(asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))); - float3 unnamed = data.v3_; - float2 unnamed_1 = data.v3_.zx; + float3 l0_ = data.v3_; + float2 l1_ = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); - float3 unnamed_2 = mul((float3x3)0, data.v3_); - float3 unnamed_3 = mul(data.v3_, (float3x3)0); - float3 unnamed_4 = (data.v3_ * 2.0); - float3 unnamed_5 = (2.0 * data.v3_); + float3 mvm0_ = mul((float3x3)0, data.v3_); + float3 mvm1_ = mul(data.v3_, (float3x3)0); + float3 svm0_ = (data.v3_ * 2.0); + float3 svm1_ = (2.0 * data.v3_); } uint NagaBufferLength(ByteAddressBuffer buffer) diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index abfbec61e..c2a92a967 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -70,174 +70,176 @@ float constructors() Foo foo = (Foo)0; foo = ConstructFoo((1.0).xxxx, 1); - float2x2 mat2comp = float2x2(float2(1.0, 0.0), float2(0.0, 1.0)); - float4x4 mat4comp = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); - uint2 unnamed = (0u).xx; - float2x2 unnamed_1 = float2x2((0.0).xx, (0.0).xx); - int unnamed_2[4] = Constructarray4_int_(0, 1, 2, 3); - bool unnamed_3 = bool((bool)0); - int unnamed_4 = int((int)0); - uint unnamed_5 = uint((uint)0); - float unnamed_6 = float((float)0); - uint2 unnamed_7 = uint2((uint2)0); - float2x3 unnamed_8 = float2x3((float2x3)0); - uint2 unnamed_9 = asuint((uint2)0); - float2x3 unnamed_10 = asfloat((float2x3)0); + float2x2 m0_ = float2x2(float2(1.0, 0.0), float2(0.0, 1.0)); + float4x4 m1_1 = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); + uint2 cit0_ = (0u).xx; + float2x2 cit1_ = float2x2((0.0).xx, (0.0).xx); + int cit2_[4] = Constructarray4_int_(0, 1, 2, 3); + bool ic0_ = bool((bool)0); + int ic1_ = int((int)0); + uint ic2_ = uint((uint)0); + float ic3_ = float((float)0); + uint2 ic4_ = uint2((uint2)0); + float2x3 ic5_ = float2x3((float2x3)0); + uint2 ic6_ = asuint((uint2)0); + float2x3 ic7_ = asfloat((float2x3)0); float _expr71 = foo.a.x; return _expr71; } void logical() { - bool unnamed_11 = !(true); - bool2 unnamed_12 = !((true).xx); - bool unnamed_13 = (true || false); - bool unnamed_14 = (true && false); - bool unnamed_15 = (true | false); - bool3 unnamed_16 = ((true).xxx | (false).xxx); - bool unnamed_17 = (true & false); - bool4 unnamed_18 = ((true).xxxx & (false).xxxx); + bool neg0_ = !(true); + bool2 neg1_ = !((true).xx); + bool or_ = (true || false); + bool and_ = (true && false); + bool bitwise_or0_ = (true | false); + bool3 bitwise_or1_ = ((true).xxx | (false).xxx); + bool bitwise_and0_ = (true & false); + bool4 bitwise_and1_ = ((true).xxxx & (false).xxxx); } void arithmetic() { - int2 unnamed_19 = -((1).xx); - float2 unnamed_20 = -((1.0).xx); - int unnamed_21 = (2 + 1); - uint unnamed_22 = (2u + 1u); - float unnamed_23 = (2.0 + 1.0); - int2 unnamed_24 = ((2).xx + (1).xx); - uint3 unnamed_25 = ((2u).xxx + (1u).xxx); - float4 unnamed_26 = ((2.0).xxxx + (1.0).xxxx); - int unnamed_27 = (2 - 1); - uint unnamed_28 = (2u - 1u); - float unnamed_29 = (2.0 - 1.0); - int2 unnamed_30 = ((2).xx - (1).xx); - uint3 unnamed_31 = ((2u).xxx - (1u).xxx); - float4 unnamed_32 = ((2.0).xxxx - (1.0).xxxx); - int unnamed_33 = (2 * 1); - uint unnamed_34 = (2u * 1u); - float unnamed_35 = (2.0 * 1.0); - int2 unnamed_36 = ((2).xx * (1).xx); - uint3 unnamed_37 = ((2u).xxx * (1u).xxx); - float4 unnamed_38 = ((2.0).xxxx * (1.0).xxxx); - int unnamed_39 = (2 / 1); - uint unnamed_40 = (2u / 1u); - float unnamed_41 = (2.0 / 1.0); - int2 unnamed_42 = ((2).xx / (1).xx); - uint3 unnamed_43 = ((2u).xxx / (1u).xxx); - float4 unnamed_44 = ((2.0).xxxx / (1.0).xxxx); - int unnamed_45 = (2 % 1); - uint unnamed_46 = (2u % 1u); - float unnamed_47 = fmod(2.0, 1.0); - int2 unnamed_48 = ((2).xx % (1).xx); - uint3 unnamed_49 = ((2u).xxx % (1u).xxx); - float4 unnamed_50 = fmod((2.0).xxxx, (1.0).xxxx); - int2 unnamed_51 = ((2).xx + (1).xx); - int2 unnamed_52 = ((2).xx + (1).xx); - uint2 unnamed_53 = ((2u).xx + (1u).xx); - uint2 unnamed_54 = ((2u).xx + (1u).xx); - float2 unnamed_55 = ((2.0).xx + (1.0).xx); - float2 unnamed_56 = ((2.0).xx + (1.0).xx); - int2 unnamed_57 = ((2).xx - (1).xx); - int2 unnamed_58 = ((2).xx - (1).xx); - uint2 unnamed_59 = ((2u).xx - (1u).xx); - uint2 unnamed_60 = ((2u).xx - (1u).xx); - float2 unnamed_61 = ((2.0).xx - (1.0).xx); - float2 unnamed_62 = ((2.0).xx - (1.0).xx); - int2 unnamed_63 = ((2).xx * 1); - int2 unnamed_64 = (2 * (1).xx); - uint2 unnamed_65 = ((2u).xx * 1u); - uint2 unnamed_66 = (2u * (1u).xx); - float2 unnamed_67 = ((2.0).xx * 1.0); - float2 unnamed_68 = (2.0 * (1.0).xx); - int2 unnamed_69 = ((2).xx / (1).xx); - int2 unnamed_70 = ((2).xx / (1).xx); - uint2 unnamed_71 = ((2u).xx / (1u).xx); - uint2 unnamed_72 = ((2u).xx / (1u).xx); - float2 unnamed_73 = ((2.0).xx / (1.0).xx); - float2 unnamed_74 = ((2.0).xx / (1.0).xx); - int2 unnamed_75 = ((2).xx % (1).xx); - int2 unnamed_76 = ((2).xx % (1).xx); - uint2 unnamed_77 = ((2u).xx % (1u).xx); - uint2 unnamed_78 = ((2u).xx % (1u).xx); - float2 unnamed_79 = fmod((2.0).xx, (1.0).xx); - float2 unnamed_80 = fmod((2.0).xx, (1.0).xx); - float3x3 unnamed_81 = ((float3x3)0 + (float3x3)0); - float3x3 unnamed_82 = ((float3x3)0 - (float3x3)0); - float3x3 unnamed_83 = mul(1.0, (float3x3)0); - float3x3 unnamed_84 = mul((float3x3)0, 2.0); - float3 unnamed_85 = mul((1.0).xxxx, (float4x3)0); - float4 unnamed_86 = mul((float4x3)0, (2.0).xxx); - float3x3 unnamed_87 = mul((float3x4)0, (float4x3)0); + int2 neg1_1 = -((1).xx); + float2 neg2_ = -((1.0).xx); + int add0_ = (2 + 1); + uint add1_ = (2u + 1u); + float add2_ = (2.0 + 1.0); + int2 add3_ = ((2).xx + (1).xx); + uint3 add4_ = ((2u).xxx + (1u).xxx); + float4 add5_ = ((2.0).xxxx + (1.0).xxxx); + int sub0_ = (2 - 1); + uint sub1_ = (2u - 1u); + float sub2_ = (2.0 - 1.0); + int2 sub3_ = ((2).xx - (1).xx); + uint3 sub4_ = ((2u).xxx - (1u).xxx); + float4 sub5_ = ((2.0).xxxx - (1.0).xxxx); + int mul0_ = (2 * 1); + uint mul1_ = (2u * 1u); + float mul2_ = (2.0 * 1.0); + int2 mul3_ = ((2).xx * (1).xx); + uint3 mul4_ = ((2u).xxx * (1u).xxx); + float4 mul5_ = ((2.0).xxxx * (1.0).xxxx); + int div0_ = (2 / 1); + uint div1_ = (2u / 1u); + float div2_ = (2.0 / 1.0); + int2 div3_ = ((2).xx / (1).xx); + uint3 div4_ = ((2u).xxx / (1u).xxx); + float4 div5_ = ((2.0).xxxx / (1.0).xxxx); + int rem0_ = (2 % 1); + uint rem1_ = (2u % 1u); + float rem2_ = fmod(2.0, 1.0); + int2 rem3_ = ((2).xx % (1).xx); + uint3 rem4_ = ((2u).xxx % (1u).xxx); + float4 rem5_ = fmod((2.0).xxxx, (1.0).xxxx); + { + int2 add0_1 = ((2).xx + (1).xx); + int2 add1_1 = ((2).xx + (1).xx); + uint2 add2_1 = ((2u).xx + (1u).xx); + uint2 add3_1 = ((2u).xx + (1u).xx); + float2 add4_1 = ((2.0).xx + (1.0).xx); + float2 add5_1 = ((2.0).xx + (1.0).xx); + int2 sub0_1 = ((2).xx - (1).xx); + int2 sub1_1 = ((2).xx - (1).xx); + uint2 sub2_1 = ((2u).xx - (1u).xx); + uint2 sub3_1 = ((2u).xx - (1u).xx); + float2 sub4_1 = ((2.0).xx - (1.0).xx); + float2 sub5_1 = ((2.0).xx - (1.0).xx); + int2 mul0_1 = ((2).xx * 1); + int2 mul1_1 = (2 * (1).xx); + uint2 mul2_1 = ((2u).xx * 1u); + uint2 mul3_1 = (2u * (1u).xx); + float2 mul4_1 = ((2.0).xx * 1.0); + float2 mul5_1 = (2.0 * (1.0).xx); + int2 div0_1 = ((2).xx / (1).xx); + int2 div1_1 = ((2).xx / (1).xx); + uint2 div2_1 = ((2u).xx / (1u).xx); + uint2 div3_1 = ((2u).xx / (1u).xx); + float2 div4_1 = ((2.0).xx / (1.0).xx); + float2 div5_1 = ((2.0).xx / (1.0).xx); + int2 rem0_1 = ((2).xx % (1).xx); + int2 rem1_1 = ((2).xx % (1).xx); + uint2 rem2_1 = ((2u).xx % (1u).xx); + uint2 rem3_1 = ((2u).xx % (1u).xx); + float2 rem4_1 = fmod((2.0).xx, (1.0).xx); + float2 rem5_1 = fmod((2.0).xx, (1.0).xx); + } + float3x3 add = ((float3x3)0 + (float3x3)0); + float3x3 sub = ((float3x3)0 - (float3x3)0); + float3x3 mul_scalar0_ = mul(1.0, (float3x3)0); + float3x3 mul_scalar1_ = mul((float3x3)0, 2.0); + float3 mul_vector0_ = mul((1.0).xxxx, (float4x3)0); + float4 mul_vector1_ = mul((float4x3)0, (2.0).xxx); + float3x3 mul_ = mul((float3x4)0, (float4x3)0); } void bit() { - int unnamed_88 = ~(1); - uint unnamed_89 = ~(1u); - int2 unnamed_90 = ~((1).xx); - uint3 unnamed_91 = ~((1u).xxx); - int unnamed_92 = (2 | 1); - uint unnamed_93 = (2u | 1u); - int2 unnamed_94 = ((2).xx | (1).xx); - uint3 unnamed_95 = ((2u).xxx | (1u).xxx); - int unnamed_96 = (2 & 1); - uint unnamed_97 = (2u & 1u); - int2 unnamed_98 = ((2).xx & (1).xx); - uint3 unnamed_99 = ((2u).xxx & (1u).xxx); - int unnamed_100 = (2 ^ 1); - uint unnamed_101 = (2u ^ 1u); - int2 unnamed_102 = ((2).xx ^ (1).xx); - uint3 unnamed_103 = ((2u).xxx ^ (1u).xxx); - int unnamed_104 = (2 << 1u); - uint unnamed_105 = (2u << 1u); - int2 unnamed_106 = ((2).xx << (1u).xx); - uint3 unnamed_107 = ((2u).xxx << (1u).xxx); - int unnamed_108 = (2 >> 1u); - uint unnamed_109 = (2u >> 1u); - int2 unnamed_110 = ((2).xx >> (1u).xx); - uint3 unnamed_111 = ((2u).xxx >> (1u).xxx); + int flip0_ = ~(1); + uint flip1_ = ~(1u); + int2 flip2_ = ~((1).xx); + uint3 flip3_ = ~((1u).xxx); + int or0_ = (2 | 1); + uint or1_ = (2u | 1u); + int2 or2_ = ((2).xx | (1).xx); + uint3 or3_ = ((2u).xxx | (1u).xxx); + int and0_ = (2 & 1); + uint and1_ = (2u & 1u); + int2 and2_ = ((2).xx & (1).xx); + uint3 and3_ = ((2u).xxx & (1u).xxx); + int xor0_ = (2 ^ 1); + uint xor1_ = (2u ^ 1u); + int2 xor2_ = ((2).xx ^ (1).xx); + uint3 xor3_ = ((2u).xxx ^ (1u).xxx); + int shl0_ = (2 << 1u); + uint shl1_ = (2u << 1u); + int2 shl2_ = ((2).xx << (1u).xx); + uint3 shl3_ = ((2u).xxx << (1u).xxx); + int shr0_ = (2 >> 1u); + uint shr1_ = (2u >> 1u); + int2 shr2_ = ((2).xx >> (1u).xx); + uint3 shr3_ = ((2u).xxx >> (1u).xxx); } void comparison() { - bool unnamed_112 = (2 == 1); - bool unnamed_113 = (2u == 1u); - bool unnamed_114 = (2.0 == 1.0); - bool2 unnamed_115 = ((2).xx == (1).xx); - bool3 unnamed_116 = ((2u).xxx == (1u).xxx); - bool4 unnamed_117 = ((2.0).xxxx == (1.0).xxxx); - bool unnamed_118 = (2 != 1); - bool unnamed_119 = (2u != 1u); - bool unnamed_120 = (2.0 != 1.0); - bool2 unnamed_121 = ((2).xx != (1).xx); - bool3 unnamed_122 = ((2u).xxx != (1u).xxx); - bool4 unnamed_123 = ((2.0).xxxx != (1.0).xxxx); - bool unnamed_124 = (2 < 1); - bool unnamed_125 = (2u < 1u); - bool unnamed_126 = (2.0 < 1.0); - bool2 unnamed_127 = ((2).xx < (1).xx); - bool3 unnamed_128 = ((2u).xxx < (1u).xxx); - bool4 unnamed_129 = ((2.0).xxxx < (1.0).xxxx); - bool unnamed_130 = (2 <= 1); - bool unnamed_131 = (2u <= 1u); - bool unnamed_132 = (2.0 <= 1.0); - bool2 unnamed_133 = ((2).xx <= (1).xx); - bool3 unnamed_134 = ((2u).xxx <= (1u).xxx); - bool4 unnamed_135 = ((2.0).xxxx <= (1.0).xxxx); - bool unnamed_136 = (2 > 1); - bool unnamed_137 = (2u > 1u); - bool unnamed_138 = (2.0 > 1.0); - bool2 unnamed_139 = ((2).xx > (1).xx); - bool3 unnamed_140 = ((2u).xxx > (1u).xxx); - bool4 unnamed_141 = ((2.0).xxxx > (1.0).xxxx); - bool unnamed_142 = (2 >= 1); - bool unnamed_143 = (2u >= 1u); - bool unnamed_144 = (2.0 >= 1.0); - bool2 unnamed_145 = ((2).xx >= (1).xx); - bool3 unnamed_146 = ((2u).xxx >= (1u).xxx); - bool4 unnamed_147 = ((2.0).xxxx >= (1.0).xxxx); + bool eq0_ = (2 == 1); + bool eq1_ = (2u == 1u); + bool eq2_ = (2.0 == 1.0); + bool2 eq3_ = ((2).xx == (1).xx); + bool3 eq4_ = ((2u).xxx == (1u).xxx); + bool4 eq5_ = ((2.0).xxxx == (1.0).xxxx); + bool neq0_ = (2 != 1); + bool neq1_ = (2u != 1u); + bool neq2_ = (2.0 != 1.0); + bool2 neq3_ = ((2).xx != (1).xx); + bool3 neq4_ = ((2u).xxx != (1u).xxx); + bool4 neq5_ = ((2.0).xxxx != (1.0).xxxx); + bool lt0_ = (2 < 1); + bool lt1_ = (2u < 1u); + bool lt2_ = (2.0 < 1.0); + bool2 lt3_ = ((2).xx < (1).xx); + bool3 lt4_ = ((2u).xxx < (1u).xxx); + bool4 lt5_ = ((2.0).xxxx < (1.0).xxxx); + bool lte0_ = (2 <= 1); + bool lte1_ = (2u <= 1u); + bool lte2_ = (2.0 <= 1.0); + bool2 lte3_ = ((2).xx <= (1).xx); + bool3 lte4_ = ((2u).xxx <= (1u).xxx); + bool4 lte5_ = ((2.0).xxxx <= (1.0).xxxx); + bool gt0_ = (2 > 1); + bool gt1_ = (2u > 1u); + bool gt2_ = (2.0 > 1.0); + bool2 gt3_ = ((2).xx > (1).xx); + bool3 gt4_ = ((2u).xxx > (1u).xxx); + bool4 gt5_ = ((2.0).xxxx > (1.0).xxxx); + bool gte0_ = (2 >= 1); + bool gte1_ = (2u >= 1u); + bool gte2_ = (2.0 >= 1.0); + bool2 gte3_ = ((2).xx >= (1).xx); + bool3 gte4_ = ((2u).xxx >= (1u).xxx); + bool4 gte5_ = ((2.0).xxxx >= (1.0).xxxx); } void assignment() @@ -282,13 +284,13 @@ void assignment() void negation_avoids_prefix_decrement() { - int unnamed_148 = -(-2); - int unnamed_149 = -(-3); - int unnamed_150 = -(-(4)); - int unnamed_151 = -(-(-5)); - int unnamed_152 = -(-(-(-(6)))); - int unnamed_153 = -(-(-(-(-7)))); - int unnamed_154 = -(-(-(-(-8)))); + int p1_ = -(-2); + int p2_ = -(-3); + int p3_ = -(-(4)); + int p4_ = -(-(-5)); + int p5_ = -(-(-(-(6)))); + int p6_ = -(-(-(-(-7)))); + int p7_ = -(-(-(-(-8)))); } [numthreads(1, 1, 1)] diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index b314d9fe1..6dda26d0d 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -779,7 +779,15 @@ ), Literal(F32(40.0)), ], - named_expressions: {}, + named_expressions: { + 8: "l0", + 13: "l1", + 18: "l2", + 25: "l3", + 32: "l4", + 39: "l5", + 46: "l6", + }, body: [ Store( pointer: 2, @@ -1350,7 +1358,16 @@ ), Literal(F32(40.0)), ], - named_expressions: {}, + named_expressions: { + 8: "l0", + 13: "l1", + 20: "l2", + 27: "l3", + 36: "l4", + 45: "l5", + 54: "l6", + 63: "l7", + }, body: [ Store( pointer: 2, diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 2e9dc72f0..1e83ae7c3 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -68,18 +68,18 @@ void test_matrix_within_struct_accesses( idx = 1; int _e2 = idx; idx = _e2 - 1; - metal::float3x2 unnamed = baz.m; - metal::float2 unnamed_1 = baz.m[0]; + metal::float3x2 l0_ = baz.m; + metal::float2 l1_ = baz.m[0]; int _e15 = idx; - metal::float2 unnamed_2 = baz.m[_e15]; - float unnamed_3 = baz.m[0].y; + metal::float2 l2_ = baz.m[_e15]; + float l3_ = baz.m[0].y; int _e29 = idx; - float unnamed_4 = baz.m[0][_e29]; + float l4_ = baz.m[0][_e29]; int _e34 = idx; - float unnamed_5 = baz.m[_e34].y; + float l5_ = baz.m[_e34].y; int _e41 = idx; int _e43 = idx; - float unnamed_6 = baz.m[_e41][_e43]; + float l6_ = baz.m[_e41][_e43]; t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; int _e55 = idx; idx = _e55 + 1; @@ -106,19 +106,19 @@ void test_matrix_within_array_within_struct_accesses( idx_1 = 1; int _e2 = idx_1; idx_1 = _e2 - 1; - type_15 unnamed_7 = nested_mat_cx2_.am; - metal::float4x2 unnamed_8 = nested_mat_cx2_.am.inner[0]; - metal::float2 unnamed_9 = nested_mat_cx2_.am.inner[0][0]; + type_15 l0_1 = nested_mat_cx2_.am; + metal::float4x2 l1_1 = nested_mat_cx2_.am.inner[0]; + metal::float2 l2_1 = nested_mat_cx2_.am.inner[0][0]; int _e24 = idx_1; - metal::float2 unnamed_10 = nested_mat_cx2_.am.inner[0][_e24]; - float unnamed_11 = nested_mat_cx2_.am.inner[0][0].y; + metal::float2 l3_1 = nested_mat_cx2_.am.inner[0][_e24]; + float l4_1 = nested_mat_cx2_.am.inner[0][0].y; int _e42 = idx_1; - float unnamed_12 = nested_mat_cx2_.am.inner[0][0][_e42]; + float l5_1 = nested_mat_cx2_.am.inner[0][0][_e42]; int _e49 = idx_1; - float unnamed_13 = nested_mat_cx2_.am.inner[0][_e49].y; + float l6_1 = nested_mat_cx2_.am.inner[0][_e49].y; int _e58 = idx_1; int _e60 = idx_1; - float unnamed_14 = nested_mat_cx2_.am.inner[0][_e58][_e60]; + float l7_ = nested_mat_cx2_.am.inner[0][_e58][_e60]; t_1 = MatCx2InArray {type_15 {}}; int _e66 = idx_1; idx_1 = _e66 + 1; diff --git a/tests/out/msl/array-in-ctor.msl b/tests/out/msl/array-in-ctor.msl index eab190df7..9428cb1e7 100644 --- a/tests/out/msl/array-in-ctor.msl +++ b/tests/out/msl/array-in-ctor.msl @@ -14,5 +14,5 @@ struct Ah { kernel void cs_main( device Ah const& ah [[user(fake0)]] ) { - Ah unnamed = ah; + Ah ah_1 = ah; } diff --git a/tests/out/msl/atomicOps.msl b/tests/out/msl/atomicOps.msl index feed8fb74..b7264e883 100644 --- a/tests/out/msl/atomicOps.msl +++ b/tests/out/msl/atomicOps.msl @@ -43,14 +43,14 @@ kernel void cs_main( metal::atomic_store_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); metal::atomic_store_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - uint unnamed = metal::atomic_load_explicit(&storage_atomic_scalar, metal::memory_order_relaxed); - int unnamed_1 = metal::atomic_load_explicit(&storage_atomic_arr.inner[1], metal::memory_order_relaxed); - uint unnamed_2 = metal::atomic_load_explicit(&storage_struct.atomic_scalar, metal::memory_order_relaxed); - int unnamed_3 = metal::atomic_load_explicit(&storage_struct.atomic_arr.inner[1], metal::memory_order_relaxed); - uint unnamed_4 = metal::atomic_load_explicit(&workgroup_atomic_scalar, metal::memory_order_relaxed); - int unnamed_5 = metal::atomic_load_explicit(&workgroup_atomic_arr.inner[1], metal::memory_order_relaxed); - uint unnamed_6 = metal::atomic_load_explicit(&workgroup_struct.atomic_scalar, metal::memory_order_relaxed); - int unnamed_7 = metal::atomic_load_explicit(&workgroup_struct.atomic_arr.inner[1], metal::memory_order_relaxed); + uint l0_ = metal::atomic_load_explicit(&storage_atomic_scalar, metal::memory_order_relaxed); + int l1_ = metal::atomic_load_explicit(&storage_atomic_arr.inner[1], metal::memory_order_relaxed); + uint l2_ = metal::atomic_load_explicit(&storage_struct.atomic_scalar, metal::memory_order_relaxed); + int l3_ = metal::atomic_load_explicit(&storage_struct.atomic_arr.inner[1], metal::memory_order_relaxed); + uint l4_ = metal::atomic_load_explicit(&workgroup_atomic_scalar, metal::memory_order_relaxed); + int l5_ = metal::atomic_load_explicit(&workgroup_atomic_arr.inner[1], metal::memory_order_relaxed); + uint l6_ = metal::atomic_load_explicit(&workgroup_struct.atomic_scalar, metal::memory_order_relaxed); + int l7_ = metal::atomic_load_explicit(&workgroup_struct.atomic_arr.inner[1], metal::memory_order_relaxed); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); uint _e59 = metal::atomic_fetch_add_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); int _e64 = metal::atomic_fetch_add_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); diff --git a/tests/out/msl/break-if.msl b/tests/out/msl/break-if.msl index 600cca60d..3a6f2e9bf 100644 --- a/tests/out/msl/break-if.msl +++ b/tests/out/msl/break-if.msl @@ -31,7 +31,6 @@ void breakIfEmptyBody( bool _e2 = b; c = a != _e2; bool _e5 = c; - bool unnamed = a == _e5; if (a == c) { break; } @@ -50,7 +49,6 @@ void breakIf( while(true) { if (!loop_init_2) { bool _e5 = e; - bool unnamed_1 = a_1 == _e5; if (a_1 == e) { break; } diff --git a/tests/out/msl/do-while.msl b/tests/out/msl/do-while.msl index 035965cd2..ac2393bf7 100644 --- a/tests/out/msl/do-while.msl +++ b/tests/out/msl/do-while.msl @@ -12,7 +12,6 @@ void fb1_( while(true) { if (!loop_init) { bool _e6 = cond; - bool unnamed = !(_e6); if (!(cond)) { break; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 7ebf5c9be..786e03ea5 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -50,13 +50,13 @@ void test_msl_packed_vec3_( int _e17 = idx; alignment.v3_[_e17] = 3.0; FooStruct data = alignment; - metal::float3 unnamed = data.v3_; - metal::float2 unnamed_1 = metal::float3(data.v3_).zx; + metal::float3 l0_ = data.v3_; + metal::float2 l1_ = metal::float3(data.v3_).zx; test_msl_packed_vec3_as_arg(data.v3_); - metal::float3 unnamed_2 = metal::float3(data.v3_) * metal::float3x3 {}; - metal::float3 unnamed_3 = metal::float3x3 {} * metal::float3(data.v3_); - metal::float3 unnamed_4 = data.v3_ * 2.0; - metal::float3 unnamed_5 = 2.0 * data.v3_; + metal::float3 mvm0_ = metal::float3(data.v3_) * metal::float3x3 {}; + metal::float3 mvm1_ = metal::float3x3 {} * metal::float3(data.v3_); + metal::float3 svm0_ = data.v3_ * 2.0; + metal::float3 svm1_ = 2.0 * data.v3_; } kernel void main_( diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 18a3d256c..33f13e1cb 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -64,174 +64,176 @@ float constructors( ) { Foo foo = {}; foo = Foo {metal::float4(1.0), 1}; - metal::float2x2 mat2comp = metal::float2x2(metal::float2(1.0, 0.0), metal::float2(0.0, 1.0)); - metal::float4x4 mat4comp = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); - metal::uint2 unnamed = metal::uint2(0u); - metal::float2x2 unnamed_1 = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); - type_14 unnamed_2 = type_14 {0, 1, 2, 3}; - bool unnamed_3 = static_cast(bool {}); - int unnamed_4 = static_cast(int {}); - uint unnamed_5 = static_cast(uint {}); - float unnamed_6 = static_cast(float {}); - metal::uint2 unnamed_7 = static_cast(metal::uint2 {}); - metal::float2x3 unnamed_8 = metal::float2x3(metal::float2x3 {}); - metal::uint2 unnamed_9 = as_type(metal::uint2 {}); - metal::float2x3 unnamed_10 = metal::float2x3(metal::float2x3 {}); + metal::float2x2 m0_ = metal::float2x2(metal::float2(1.0, 0.0), metal::float2(0.0, 1.0)); + metal::float4x4 m1_1 = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); + metal::uint2 cit0_ = metal::uint2(0u); + metal::float2x2 cit1_ = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); + type_14 cit2_ = type_14 {0, 1, 2, 3}; + bool ic0_ = static_cast(bool {}); + int ic1_ = static_cast(int {}); + uint ic2_ = static_cast(uint {}); + float ic3_ = static_cast(float {}); + metal::uint2 ic4_ = static_cast(metal::uint2 {}); + metal::float2x3 ic5_ = metal::float2x3(metal::float2x3 {}); + metal::uint2 ic6_ = as_type(metal::uint2 {}); + metal::float2x3 ic7_ = metal::float2x3(metal::float2x3 {}); float _e71 = foo.a.x; return _e71; } void logical( ) { - bool unnamed_11 = !(true); - metal::bool2 unnamed_12 = !(metal::bool2(true)); - bool unnamed_13 = true || false; - bool unnamed_14 = true && false; - bool unnamed_15 = true | false; - metal::bool3 unnamed_16 = metal::bool3(true) | metal::bool3(false); - bool unnamed_17 = true & false; - metal::bool4 unnamed_18 = metal::bool4(true) & metal::bool4(false); + bool neg0_ = !(true); + metal::bool2 neg1_ = !(metal::bool2(true)); + bool or_ = true || false; + bool and_ = true && false; + bool bitwise_or0_ = true | false; + metal::bool3 bitwise_or1_ = metal::bool3(true) | metal::bool3(false); + bool bitwise_and0_ = true & false; + metal::bool4 bitwise_and1_ = metal::bool4(true) & metal::bool4(false); } void arithmetic( ) { - metal::int2 unnamed_19 = -(metal::int2(1)); - metal::float2 unnamed_20 = -(metal::float2(1.0)); - int unnamed_21 = 2 + 1; - uint unnamed_22 = 2u + 1u; - float unnamed_23 = 2.0 + 1.0; - metal::int2 unnamed_24 = metal::int2(2) + metal::int2(1); - metal::uint3 unnamed_25 = metal::uint3(2u) + metal::uint3(1u); - metal::float4 unnamed_26 = metal::float4(2.0) + metal::float4(1.0); - int unnamed_27 = 2 - 1; - uint unnamed_28 = 2u - 1u; - float unnamed_29 = 2.0 - 1.0; - metal::int2 unnamed_30 = metal::int2(2) - metal::int2(1); - metal::uint3 unnamed_31 = metal::uint3(2u) - metal::uint3(1u); - metal::float4 unnamed_32 = metal::float4(2.0) - metal::float4(1.0); - int unnamed_33 = 2 * 1; - uint unnamed_34 = 2u * 1u; - float unnamed_35 = 2.0 * 1.0; - metal::int2 unnamed_36 = metal::int2(2) * metal::int2(1); - metal::uint3 unnamed_37 = metal::uint3(2u) * metal::uint3(1u); - metal::float4 unnamed_38 = metal::float4(2.0) * metal::float4(1.0); - int unnamed_39 = 2 / 1; - uint unnamed_40 = 2u / 1u; - float unnamed_41 = 2.0 / 1.0; - metal::int2 unnamed_42 = metal::int2(2) / metal::int2(1); - metal::uint3 unnamed_43 = metal::uint3(2u) / metal::uint3(1u); - metal::float4 unnamed_44 = metal::float4(2.0) / metal::float4(1.0); - int unnamed_45 = 2 % 1; - uint unnamed_46 = 2u % 1u; - float unnamed_47 = metal::fmod(2.0, 1.0); - metal::int2 unnamed_48 = metal::int2(2) % metal::int2(1); - metal::uint3 unnamed_49 = metal::uint3(2u) % metal::uint3(1u); - metal::float4 unnamed_50 = metal::fmod(metal::float4(2.0), metal::float4(1.0)); - metal::int2 unnamed_51 = metal::int2(2) + metal::int2(1); - metal::int2 unnamed_52 = metal::int2(2) + metal::int2(1); - metal::uint2 unnamed_53 = metal::uint2(2u) + metal::uint2(1u); - metal::uint2 unnamed_54 = metal::uint2(2u) + metal::uint2(1u); - metal::float2 unnamed_55 = metal::float2(2.0) + metal::float2(1.0); - metal::float2 unnamed_56 = metal::float2(2.0) + metal::float2(1.0); - metal::int2 unnamed_57 = metal::int2(2) - metal::int2(1); - metal::int2 unnamed_58 = metal::int2(2) - metal::int2(1); - metal::uint2 unnamed_59 = metal::uint2(2u) - metal::uint2(1u); - metal::uint2 unnamed_60 = metal::uint2(2u) - metal::uint2(1u); - metal::float2 unnamed_61 = metal::float2(2.0) - metal::float2(1.0); - metal::float2 unnamed_62 = metal::float2(2.0) - metal::float2(1.0); - metal::int2 unnamed_63 = metal::int2(2) * 1; - metal::int2 unnamed_64 = 2 * metal::int2(1); - metal::uint2 unnamed_65 = metal::uint2(2u) * 1u; - metal::uint2 unnamed_66 = 2u * metal::uint2(1u); - metal::float2 unnamed_67 = metal::float2(2.0) * 1.0; - metal::float2 unnamed_68 = 2.0 * metal::float2(1.0); - metal::int2 unnamed_69 = metal::int2(2) / metal::int2(1); - metal::int2 unnamed_70 = metal::int2(2) / metal::int2(1); - metal::uint2 unnamed_71 = metal::uint2(2u) / metal::uint2(1u); - metal::uint2 unnamed_72 = metal::uint2(2u) / metal::uint2(1u); - metal::float2 unnamed_73 = metal::float2(2.0) / metal::float2(1.0); - metal::float2 unnamed_74 = metal::float2(2.0) / metal::float2(1.0); - metal::int2 unnamed_75 = metal::int2(2) % metal::int2(1); - metal::int2 unnamed_76 = metal::int2(2) % metal::int2(1); - metal::uint2 unnamed_77 = metal::uint2(2u) % metal::uint2(1u); - metal::uint2 unnamed_78 = metal::uint2(2u) % metal::uint2(1u); - metal::float2 unnamed_79 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float2 unnamed_80 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); - metal::float3x3 unnamed_81 = metal::float3x3 {} + metal::float3x3 {}; - metal::float3x3 unnamed_82 = metal::float3x3 {} - metal::float3x3 {}; - metal::float3x3 unnamed_83 = metal::float3x3 {} * 1.0; - metal::float3x3 unnamed_84 = 2.0 * metal::float3x3 {}; - metal::float3 unnamed_85 = metal::float4x3 {} * metal::float4(1.0); - metal::float4 unnamed_86 = metal::float3(2.0) * metal::float4x3 {}; - metal::float3x3 unnamed_87 = metal::float4x3 {} * metal::float3x4 {}; + metal::int2 neg1_1 = -(metal::int2(1)); + metal::float2 neg2_ = -(metal::float2(1.0)); + int add0_ = 2 + 1; + uint add1_ = 2u + 1u; + float add2_ = 2.0 + 1.0; + metal::int2 add3_ = metal::int2(2) + metal::int2(1); + metal::uint3 add4_ = metal::uint3(2u) + metal::uint3(1u); + metal::float4 add5_ = metal::float4(2.0) + metal::float4(1.0); + int sub0_ = 2 - 1; + uint sub1_ = 2u - 1u; + float sub2_ = 2.0 - 1.0; + metal::int2 sub3_ = metal::int2(2) - metal::int2(1); + metal::uint3 sub4_ = metal::uint3(2u) - metal::uint3(1u); + metal::float4 sub5_ = metal::float4(2.0) - metal::float4(1.0); + int mul0_ = 2 * 1; + uint mul1_ = 2u * 1u; + float mul2_ = 2.0 * 1.0; + metal::int2 mul3_ = metal::int2(2) * metal::int2(1); + metal::uint3 mul4_ = metal::uint3(2u) * metal::uint3(1u); + metal::float4 mul5_ = metal::float4(2.0) * metal::float4(1.0); + int div0_ = 2 / 1; + uint div1_ = 2u / 1u; + float div2_ = 2.0 / 1.0; + metal::int2 div3_ = metal::int2(2) / metal::int2(1); + metal::uint3 div4_ = metal::uint3(2u) / metal::uint3(1u); + metal::float4 div5_ = metal::float4(2.0) / metal::float4(1.0); + int rem0_ = 2 % 1; + uint rem1_ = 2u % 1u; + float rem2_ = metal::fmod(2.0, 1.0); + metal::int2 rem3_ = metal::int2(2) % metal::int2(1); + metal::uint3 rem4_ = metal::uint3(2u) % metal::uint3(1u); + metal::float4 rem5_ = metal::fmod(metal::float4(2.0), metal::float4(1.0)); + { + metal::int2 add0_1 = metal::int2(2) + metal::int2(1); + metal::int2 add1_1 = metal::int2(2) + metal::int2(1); + metal::uint2 add2_1 = metal::uint2(2u) + metal::uint2(1u); + metal::uint2 add3_1 = metal::uint2(2u) + metal::uint2(1u); + metal::float2 add4_1 = metal::float2(2.0) + metal::float2(1.0); + metal::float2 add5_1 = metal::float2(2.0) + metal::float2(1.0); + metal::int2 sub0_1 = metal::int2(2) - metal::int2(1); + metal::int2 sub1_1 = metal::int2(2) - metal::int2(1); + metal::uint2 sub2_1 = metal::uint2(2u) - metal::uint2(1u); + metal::uint2 sub3_1 = metal::uint2(2u) - metal::uint2(1u); + metal::float2 sub4_1 = metal::float2(2.0) - metal::float2(1.0); + metal::float2 sub5_1 = metal::float2(2.0) - metal::float2(1.0); + metal::int2 mul0_1 = metal::int2(2) * 1; + metal::int2 mul1_1 = 2 * metal::int2(1); + metal::uint2 mul2_1 = metal::uint2(2u) * 1u; + metal::uint2 mul3_1 = 2u * metal::uint2(1u); + metal::float2 mul4_1 = metal::float2(2.0) * 1.0; + metal::float2 mul5_1 = 2.0 * metal::float2(1.0); + metal::int2 div0_1 = metal::int2(2) / metal::int2(1); + metal::int2 div1_1 = metal::int2(2) / metal::int2(1); + metal::uint2 div2_1 = metal::uint2(2u) / metal::uint2(1u); + metal::uint2 div3_1 = metal::uint2(2u) / metal::uint2(1u); + metal::float2 div4_1 = metal::float2(2.0) / metal::float2(1.0); + metal::float2 div5_1 = metal::float2(2.0) / metal::float2(1.0); + metal::int2 rem0_1 = metal::int2(2) % metal::int2(1); + metal::int2 rem1_1 = metal::int2(2) % metal::int2(1); + metal::uint2 rem2_1 = metal::uint2(2u) % metal::uint2(1u); + metal::uint2 rem3_1 = metal::uint2(2u) % metal::uint2(1u); + metal::float2 rem4_1 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + metal::float2 rem5_1 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); + } + metal::float3x3 add = metal::float3x3 {} + metal::float3x3 {}; + metal::float3x3 sub = metal::float3x3 {} - metal::float3x3 {}; + metal::float3x3 mul_scalar0_ = metal::float3x3 {} * 1.0; + metal::float3x3 mul_scalar1_ = 2.0 * metal::float3x3 {}; + metal::float3 mul_vector0_ = metal::float4x3 {} * metal::float4(1.0); + metal::float4 mul_vector1_ = metal::float3(2.0) * metal::float4x3 {}; + metal::float3x3 mul = metal::float4x3 {} * metal::float3x4 {}; } void bit( ) { - int unnamed_88 = ~(1); - uint unnamed_89 = ~(1u); - metal::int2 unnamed_90 = ~(metal::int2(1)); - metal::uint3 unnamed_91 = ~(metal::uint3(1u)); - int unnamed_92 = 2 | 1; - uint unnamed_93 = 2u | 1u; - metal::int2 unnamed_94 = metal::int2(2) | metal::int2(1); - metal::uint3 unnamed_95 = metal::uint3(2u) | metal::uint3(1u); - int unnamed_96 = 2 & 1; - uint unnamed_97 = 2u & 1u; - metal::int2 unnamed_98 = metal::int2(2) & metal::int2(1); - metal::uint3 unnamed_99 = metal::uint3(2u) & metal::uint3(1u); - int unnamed_100 = 2 ^ 1; - uint unnamed_101 = 2u ^ 1u; - metal::int2 unnamed_102 = metal::int2(2) ^ metal::int2(1); - metal::uint3 unnamed_103 = metal::uint3(2u) ^ metal::uint3(1u); - int unnamed_104 = 2 << 1u; - uint unnamed_105 = 2u << 1u; - metal::int2 unnamed_106 = metal::int2(2) << metal::uint2(1u); - metal::uint3 unnamed_107 = metal::uint3(2u) << metal::uint3(1u); - int unnamed_108 = 2 >> 1u; - uint unnamed_109 = 2u >> 1u; - metal::int2 unnamed_110 = metal::int2(2) >> metal::uint2(1u); - metal::uint3 unnamed_111 = metal::uint3(2u) >> metal::uint3(1u); + int flip0_ = ~(1); + uint flip1_ = ~(1u); + metal::int2 flip2_ = ~(metal::int2(1)); + metal::uint3 flip3_ = ~(metal::uint3(1u)); + int or0_ = 2 | 1; + uint or1_ = 2u | 1u; + metal::int2 or2_ = metal::int2(2) | metal::int2(1); + metal::uint3 or3_ = metal::uint3(2u) | metal::uint3(1u); + int and0_ = 2 & 1; + uint and1_ = 2u & 1u; + metal::int2 and2_ = metal::int2(2) & metal::int2(1); + metal::uint3 and3_ = metal::uint3(2u) & metal::uint3(1u); + int xor0_ = 2 ^ 1; + uint xor1_ = 2u ^ 1u; + metal::int2 xor2_ = metal::int2(2) ^ metal::int2(1); + metal::uint3 xor3_ = metal::uint3(2u) ^ metal::uint3(1u); + int shl0_ = 2 << 1u; + uint shl1_ = 2u << 1u; + metal::int2 shl2_ = metal::int2(2) << metal::uint2(1u); + metal::uint3 shl3_ = metal::uint3(2u) << metal::uint3(1u); + int shr0_ = 2 >> 1u; + uint shr1_ = 2u >> 1u; + metal::int2 shr2_ = metal::int2(2) >> metal::uint2(1u); + metal::uint3 shr3_ = metal::uint3(2u) >> metal::uint3(1u); } void comparison( ) { - bool unnamed_112 = 2 == 1; - bool unnamed_113 = 2u == 1u; - bool unnamed_114 = 2.0 == 1.0; - metal::bool2 unnamed_115 = metal::int2(2) == metal::int2(1); - metal::bool3 unnamed_116 = metal::uint3(2u) == metal::uint3(1u); - metal::bool4 unnamed_117 = metal::float4(2.0) == metal::float4(1.0); - bool unnamed_118 = 2 != 1; - bool unnamed_119 = 2u != 1u; - bool unnamed_120 = 2.0 != 1.0; - metal::bool2 unnamed_121 = metal::int2(2) != metal::int2(1); - metal::bool3 unnamed_122 = metal::uint3(2u) != metal::uint3(1u); - metal::bool4 unnamed_123 = metal::float4(2.0) != metal::float4(1.0); - bool unnamed_124 = 2 < 1; - bool unnamed_125 = 2u < 1u; - bool unnamed_126 = 2.0 < 1.0; - metal::bool2 unnamed_127 = metal::int2(2) < metal::int2(1); - metal::bool3 unnamed_128 = metal::uint3(2u) < metal::uint3(1u); - metal::bool4 unnamed_129 = metal::float4(2.0) < metal::float4(1.0); - bool unnamed_130 = 2 <= 1; - bool unnamed_131 = 2u <= 1u; - bool unnamed_132 = 2.0 <= 1.0; - metal::bool2 unnamed_133 = metal::int2(2) <= metal::int2(1); - metal::bool3 unnamed_134 = metal::uint3(2u) <= metal::uint3(1u); - metal::bool4 unnamed_135 = metal::float4(2.0) <= metal::float4(1.0); - bool unnamed_136 = 2 > 1; - bool unnamed_137 = 2u > 1u; - bool unnamed_138 = 2.0 > 1.0; - metal::bool2 unnamed_139 = metal::int2(2) > metal::int2(1); - metal::bool3 unnamed_140 = metal::uint3(2u) > metal::uint3(1u); - metal::bool4 unnamed_141 = metal::float4(2.0) > metal::float4(1.0); - bool unnamed_142 = 2 >= 1; - bool unnamed_143 = 2u >= 1u; - bool unnamed_144 = 2.0 >= 1.0; - metal::bool2 unnamed_145 = metal::int2(2) >= metal::int2(1); - metal::bool3 unnamed_146 = metal::uint3(2u) >= metal::uint3(1u); - metal::bool4 unnamed_147 = metal::float4(2.0) >= metal::float4(1.0); + bool eq0_ = 2 == 1; + bool eq1_ = 2u == 1u; + bool eq2_ = 2.0 == 1.0; + metal::bool2 eq3_ = metal::int2(2) == metal::int2(1); + metal::bool3 eq4_ = metal::uint3(2u) == metal::uint3(1u); + metal::bool4 eq5_ = metal::float4(2.0) == metal::float4(1.0); + bool neq0_ = 2 != 1; + bool neq1_ = 2u != 1u; + bool neq2_ = 2.0 != 1.0; + metal::bool2 neq3_ = metal::int2(2) != metal::int2(1); + metal::bool3 neq4_ = metal::uint3(2u) != metal::uint3(1u); + metal::bool4 neq5_ = metal::float4(2.0) != metal::float4(1.0); + bool lt0_ = 2 < 1; + bool lt1_ = 2u < 1u; + bool lt2_ = 2.0 < 1.0; + metal::bool2 lt3_ = metal::int2(2) < metal::int2(1); + metal::bool3 lt4_ = metal::uint3(2u) < metal::uint3(1u); + metal::bool4 lt5_ = metal::float4(2.0) < metal::float4(1.0); + bool lte0_ = 2 <= 1; + bool lte1_ = 2u <= 1u; + bool lte2_ = 2.0 <= 1.0; + metal::bool2 lte3_ = metal::int2(2) <= metal::int2(1); + metal::bool3 lte4_ = metal::uint3(2u) <= metal::uint3(1u); + metal::bool4 lte5_ = metal::float4(2.0) <= metal::float4(1.0); + bool gt0_ = 2 > 1; + bool gt1_ = 2u > 1u; + bool gt2_ = 2.0 > 1.0; + metal::bool2 gt3_ = metal::int2(2) > metal::int2(1); + metal::bool3 gt4_ = metal::uint3(2u) > metal::uint3(1u); + metal::bool4 gt5_ = metal::float4(2.0) > metal::float4(1.0); + bool gte0_ = 2 >= 1; + bool gte1_ = 2u >= 1u; + bool gte2_ = 2.0 >= 1.0; + metal::bool2 gte3_ = metal::int2(2) >= metal::int2(1); + metal::bool3 gte4_ = metal::uint3(2u) >= metal::uint3(1u); + metal::bool4 gte5_ = metal::float4(2.0) >= metal::float4(1.0); } void assignment( @@ -275,13 +277,13 @@ void assignment( void negation_avoids_prefix_decrement( ) { - int unnamed_148 = -(-2); - int unnamed_149 = -(-3); - int unnamed_150 = -(-(4)); - int unnamed_151 = -(-(-5)); - int unnamed_152 = -(-(-(-(6)))); - int unnamed_153 = -(-(-(-(-7)))); - int unnamed_154 = -(-(-(-(-8)))); + int p1_ = -(-2); + int p2_ = -(-3); + int p3_ = -(-(4)); + int p4_ = -(-(-5)); + int p5_ = -(-(-(-(6)))); + int p6_ = -(-(-(-(-7)))); + int p7_ = -(-(-(-(-8)))); } kernel void main_( diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index e3a2b7564..92e3a2fbe 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 327 +; Bound: 326 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %241 "foo_vert" %236 %239 -OpEntryPoint Fragment %287 "foo_frag" %286 -OpEntryPoint GLCompute %307 "assign_through_ptr" %310 -OpExecutionMode %287 OriginUpperLeft -OpExecutionMode %307 LocalSize 1 1 1 +OpEntryPoint Vertex %239 "foo_vert" %234 %237 +OpEntryPoint Fragment %286 "foo_frag" %285 +OpEntryPoint GLCompute %306 "assign_through_ptr" %309 +OpExecutionMode %286 OriginUpperLeft +OpExecutionMode %306 LocalSize 1 1 1 OpSource GLSL 450 OpMemberName %12 0 "a" OpMemberName %12 1 "b" @@ -45,17 +45,17 @@ OpName %202 "foo" OpName %203 "read_from_private" OpName %208 "a" OpName %209 "test_arr_as_arg" -OpName %217 "p" -OpName %218 "assign_through_ptr_fn" -OpName %223 "foo" -OpName %224 "assign_array_through_ptr_fn" -OpName %230 "foo" -OpName %232 "c2" -OpName %236 "vi" -OpName %241 "foo_vert" -OpName %287 "foo_frag" -OpName %304 "arr" -OpName %307 "assign_through_ptr" +OpName %215 "p" +OpName %216 "assign_through_ptr_fn" +OpName %221 "foo" +OpName %222 "assign_array_through_ptr_fn" +OpName %228 "foo" +OpName %230 "c2" +OpName %234 "vi" +OpName %239 "foo_vert" +OpName %286 "foo_frag" +OpName %303 "arr" +OpName %306 "assign_through_ptr" OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpMemberDecorate %12 2 Offset 28 @@ -100,10 +100,10 @@ OpDecorate %56 DescriptorSet 0 OpDecorate %56 Binding 3 OpDecorate %57 Block OpMemberDecorate %57 0 Offset 0 -OpDecorate %236 BuiltIn VertexIndex -OpDecorate %239 BuiltIn Position -OpDecorate %286 Location 0 -OpDecorate %310 BuiltIn LocalInvocationId +OpDecorate %234 BuiltIn VertexIndex +OpDecorate %237 BuiltIn Position +OpDecorate %285 Location 0 +OpDecorate %309 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpConstant %4 0 @@ -201,41 +201,40 @@ OpDecorate %310 BuiltIn LocalInvocationId %181 = OpTypePointer Function %30 %204 = OpTypeFunction %16 %33 %210 = OpTypeFunction %16 %35 -%211 = OpConstant %6 4 -%212 = OpConstant %6 9 -%219 = OpTypeFunction %2 %41 -%220 = OpConstant %4 42 -%225 = OpTypeFunction %2 %43 -%231 = OpConstantNull %16 -%233 = OpTypePointer Function %39 -%234 = OpConstantNull %39 -%237 = OpTypePointer Input %4 -%236 = OpVariable %237 Input -%240 = OpTypePointer Output %37 -%239 = OpVariable %240 Output -%243 = OpTypePointer StorageBuffer %29 -%246 = OpConstant %16 0.0 -%247 = OpConstant %4 3 -%248 = OpConstant %6 3 -%249 = OpConstant %6 42 -%250 = OpConstantNull %35 -%255 = OpTypePointer StorageBuffer %14 -%258 = OpTypePointer StorageBuffer %24 -%259 = OpConstant %4 4 -%262 = OpTypePointer StorageBuffer %15 -%263 = OpTypePointer StorageBuffer %16 -%266 = OpTypePointer StorageBuffer %25 -%269 = OpTypePointer StorageBuffer %13 -%286 = OpVariable %240 Output -%289 = OpConstantNull %29 -%305 = OpConstantNull %42 -%309 = OpConstantNull %4 -%311 = OpTypePointer Input %11 -%310 = OpVariable %311 Input -%313 = OpConstantNull %11 -%315 = OpTypeBool -%314 = OpTypeVector %315 3 -%320 = OpConstant %4 264 +%217 = OpTypeFunction %2 %41 +%218 = OpConstant %4 42 +%223 = OpTypeFunction %2 %43 +%229 = OpConstantNull %16 +%231 = OpTypePointer Function %39 +%232 = OpConstantNull %39 +%235 = OpTypePointer Input %4 +%234 = OpVariable %235 Input +%238 = OpTypePointer Output %37 +%237 = OpVariable %238 Output +%241 = OpTypePointer StorageBuffer %29 +%244 = OpConstant %16 0.0 +%245 = OpConstant %4 3 +%246 = OpConstant %6 3 +%247 = OpConstant %6 4 +%248 = OpConstant %6 42 +%249 = OpConstantNull %35 +%254 = OpTypePointer StorageBuffer %14 +%257 = OpTypePointer StorageBuffer %24 +%258 = OpConstant %4 4 +%261 = OpTypePointer StorageBuffer %15 +%262 = OpTypePointer StorageBuffer %16 +%265 = OpTypePointer StorageBuffer %25 +%268 = OpTypePointer StorageBuffer %13 +%285 = OpVariable %238 Output +%288 = OpConstantNull %29 +%304 = OpConstantNull %42 +%308 = OpConstantNull %4 +%310 = OpTypePointer Input %11 +%309 = OpVariable %310 Input +%312 = OpConstantNull %11 +%314 = OpTypeBool +%313 = OpTypeVector %314 3 +%319 = OpConstant %4 264 %67 = OpFunction %2 None %68 %66 = OpLabel %60 = OpVariable %61 Function %62 @@ -380,122 +379,122 @@ OpFunctionEnd %209 = OpFunction %16 None %210 %208 = OpFunctionParameter %35 %207 = OpLabel -OpBranch %213 -%213 = OpLabel -%214 = OpCompositeExtract %34 %208 4 -%215 = OpCompositeExtract %16 %214 9 -OpReturnValue %215 +OpBranch %211 +%211 = OpLabel +%212 = OpCompositeExtract %34 %208 4 +%213 = OpCompositeExtract %16 %212 9 +OpReturnValue %213 OpFunctionEnd -%218 = OpFunction %2 None %219 -%217 = OpFunctionParameter %41 -%216 = OpLabel -OpBranch %221 -%221 = OpLabel -OpStore %217 %220 +%216 = OpFunction %2 None %217 +%215 = OpFunctionParameter %41 +%214 = OpLabel +OpBranch %219 +%219 = OpLabel +OpStore %215 %218 OpReturn OpFunctionEnd -%224 = OpFunction %2 None %225 -%223 = OpFunctionParameter %43 -%222 = OpLabel -OpBranch %226 -%226 = OpLabel -%227 = OpCompositeConstruct %37 %71 %71 %71 %71 -%228 = OpCompositeConstruct %37 %72 %72 %72 %72 -%229 = OpCompositeConstruct %42 %227 %228 -OpStore %223 %229 +%222 = OpFunction %2 None %223 +%221 = OpFunctionParameter %43 +%220 = OpLabel +OpBranch %224 +%224 = OpLabel +%225 = OpCompositeConstruct %37 %71 %71 %71 %71 +%226 = OpCompositeConstruct %37 %72 %72 %72 %72 +%227 = OpCompositeConstruct %42 %225 %226 +OpStore %221 %227 OpReturn OpFunctionEnd -%241 = OpFunction %2 None %68 -%235 = OpLabel -%230 = OpVariable %33 Function %231 -%232 = OpVariable %233 Function %234 -%238 = OpLoad %4 %236 -%242 = OpAccessChain %69 %50 %3 -%244 = OpAccessChain %243 %53 %3 -%245 = OpAccessChain %144 %56 %3 -OpBranch %251 -%251 = OpLabel -OpStore %230 %246 -%252 = OpLoad %16 %230 -OpStore %230 %71 -%253 = OpFunctionCall %2 %67 -%254 = OpFunctionCall %2 %143 -%256 = OpAccessChain %255 %48 %3 -%257 = OpLoad %14 %256 -%260 = OpAccessChain %258 %48 %259 -%261 = OpLoad %24 %260 -%264 = OpAccessChain %263 %48 %3 %247 %3 -%265 = OpLoad %16 %264 -%267 = OpArrayLength %4 %48 5 -%268 = OpISub %4 %267 %20 -%270 = OpAccessChain %38 %48 %36 %268 %3 -%271 = OpLoad %6 %270 -%272 = OpLoad %29 %244 -%273 = OpFunctionCall %16 %203 %230 -%274 = OpConvertFToS %6 %265 -%275 = OpCompositeConstruct %39 %271 %274 %248 %211 %10 -OpStore %232 %275 -%276 = OpIAdd %4 %238 %96 -%277 = OpAccessChain %61 %232 %276 -OpStore %277 %249 -%278 = OpAccessChain %61 %232 %238 -%279 = OpLoad %6 %278 -%280 = OpFunctionCall %16 %209 %250 -%281 = OpCompositeConstruct %40 %279 %279 %279 %279 -%282 = OpConvertSToF %37 %281 -%283 = OpMatrixTimesVector %15 %257 %282 -%284 = OpCompositeConstruct %37 %283 %72 -OpStore %239 %284 +%239 = OpFunction %2 None %68 +%233 = OpLabel +%228 = OpVariable %33 Function %229 +%230 = OpVariable %231 Function %232 +%236 = OpLoad %4 %234 +%240 = OpAccessChain %69 %50 %3 +%242 = OpAccessChain %241 %53 %3 +%243 = OpAccessChain %144 %56 %3 +OpBranch %250 +%250 = OpLabel +OpStore %228 %244 +%251 = OpLoad %16 %228 +OpStore %228 %71 +%252 = OpFunctionCall %2 %67 +%253 = OpFunctionCall %2 %143 +%255 = OpAccessChain %254 %48 %3 +%256 = OpLoad %14 %255 +%259 = OpAccessChain %257 %48 %258 +%260 = OpLoad %24 %259 +%263 = OpAccessChain %262 %48 %3 %245 %3 +%264 = OpLoad %16 %263 +%266 = OpArrayLength %4 %48 5 +%267 = OpISub %4 %266 %20 +%269 = OpAccessChain %38 %48 %36 %267 %3 +%270 = OpLoad %6 %269 +%271 = OpLoad %29 %242 +%272 = OpFunctionCall %16 %203 %228 +%273 = OpConvertFToS %6 %264 +%274 = OpCompositeConstruct %39 %270 %273 %246 %247 %10 +OpStore %230 %274 +%275 = OpIAdd %4 %236 %96 +%276 = OpAccessChain %61 %230 %275 +OpStore %276 %248 +%277 = OpAccessChain %61 %230 %236 +%278 = OpLoad %6 %277 +%279 = OpFunctionCall %16 %209 %249 +%280 = OpCompositeConstruct %40 %278 %278 %278 %278 +%281 = OpConvertSToF %37 %280 +%282 = OpMatrixTimesVector %15 %256 %281 +%283 = OpCompositeConstruct %37 %282 %72 +OpStore %237 %283 OpReturn OpFunctionEnd -%287 = OpFunction %2 None %68 -%285 = OpLabel -%288 = OpAccessChain %243 %53 %3 -OpBranch %290 -%290 = OpLabel -%291 = OpAccessChain %263 %48 %3 %96 %20 -OpStore %291 %71 -%292 = OpCompositeConstruct %15 %246 %246 %246 -%293 = OpCompositeConstruct %15 %71 %71 %71 -%294 = OpCompositeConstruct %15 %72 %72 %72 -%295 = OpCompositeConstruct %15 %73 %73 %73 -%296 = OpCompositeConstruct %14 %292 %293 %294 %295 -%297 = OpAccessChain %255 %48 %3 -OpStore %297 %296 -%298 = OpCompositeConstruct %23 %3 %3 -%299 = OpCompositeConstruct %23 %96 %96 -%300 = OpCompositeConstruct %24 %298 %299 -%301 = OpAccessChain %258 %48 %259 -OpStore %301 %300 -%302 = OpAccessChain %38 %48 %36 %96 %3 -OpStore %302 %9 -OpStore %288 %289 -%303 = OpCompositeConstruct %37 %246 %246 %246 %246 -OpStore %286 %303 +%286 = OpFunction %2 None %68 +%284 = OpLabel +%287 = OpAccessChain %241 %53 %3 +OpBranch %289 +%289 = OpLabel +%290 = OpAccessChain %262 %48 %3 %96 %20 +OpStore %290 %71 +%291 = OpCompositeConstruct %15 %244 %244 %244 +%292 = OpCompositeConstruct %15 %71 %71 %71 +%293 = OpCompositeConstruct %15 %72 %72 %72 +%294 = OpCompositeConstruct %15 %73 %73 %73 +%295 = OpCompositeConstruct %14 %291 %292 %293 %294 +%296 = OpAccessChain %254 %48 %3 +OpStore %296 %295 +%297 = OpCompositeConstruct %23 %3 %3 +%298 = OpCompositeConstruct %23 %96 %96 +%299 = OpCompositeConstruct %24 %297 %298 +%300 = OpAccessChain %257 %48 %258 +OpStore %300 %299 +%301 = OpAccessChain %38 %48 %36 %96 %3 +OpStore %301 %9 +OpStore %287 %288 +%302 = OpCompositeConstruct %37 %244 %244 %244 %244 +OpStore %285 %302 OpReturn OpFunctionEnd -%307 = OpFunction %2 None %68 -%306 = OpLabel -%304 = OpVariable %43 Function %305 -OpBranch %308 -%308 = OpLabel -%312 = OpLoad %11 %310 -%316 = OpIEqual %314 %312 %313 -%317 = OpAll %315 %316 -OpSelectionMerge %318 None -OpBranchConditional %317 %319 %318 -%319 = OpLabel -OpStore %59 %309 -OpBranch %318 +%306 = OpFunction %2 None %68 +%305 = OpLabel +%303 = OpVariable %43 Function %304 +OpBranch %307 +%307 = OpLabel +%311 = OpLoad %11 %309 +%315 = OpIEqual %313 %311 %312 +%316 = OpAll %314 %315 +OpSelectionMerge %317 None +OpBranchConditional %316 %318 %317 %318 = OpLabel -OpControlBarrier %20 %20 %320 -OpBranch %321 -%321 = OpLabel -%322 = OpCompositeConstruct %37 %74 %74 %74 %74 -%323 = OpCompositeConstruct %37 %149 %149 %149 %149 -%324 = OpCompositeConstruct %42 %322 %323 -OpStore %304 %324 -%325 = OpFunctionCall %2 %218 %59 -%326 = OpFunctionCall %2 %224 %304 +OpStore %59 %308 +OpBranch %317 +%317 = OpLabel +OpControlBarrier %20 %20 %319 +OpBranch %320 +%320 = OpLabel +%321 = OpCompositeConstruct %37 %74 %74 %74 %74 +%322 = OpCompositeConstruct %37 %149 %149 %149 %149 +%323 = OpCompositeConstruct %42 %321 %322 +OpStore %303 %323 +%324 = OpFunctionCall %2 %216 %59 +%325 = OpFunctionCall %2 %222 %303 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-buffer-arrays.spvasm b/tests/out/spv/binding-buffer-arrays.spvasm index cd20c1dd7..b09377b6b 100644 --- a/tests/out/spv/binding-buffer-arrays.spvasm +++ b/tests/out/spv/binding-buffer-arrays.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 66 +; Bound: 65 OpCapability Shader OpCapability ShaderNonUniform OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -24,7 +24,7 @@ OpMemberDecorate %16 0 Offset 0 OpDecorate %23 Location 0 OpDecorate %23 Flat OpDecorate %26 Location 0 -OpDecorate %57 NonUniform +OpDecorate %56 NonUniform %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpConstant %4 1 @@ -51,55 +51,54 @@ OpDecorate %57 NonUniform %30 = OpTypePointer Uniform %6 %31 = OpConstant %5 0 %33 = OpTypePointer StorageBuffer %8 -%34 = OpConstant %4 0 -%36 = OpTypePointer Uniform %5 -%40 = OpTypePointer StorageBuffer %7 -%41 = OpTypePointer StorageBuffer %5 -%47 = OpTypeBool -%49 = OpConstantNull %5 -%58 = OpConstantNull %5 +%35 = OpTypePointer Uniform %5 +%39 = OpTypePointer StorageBuffer %7 +%40 = OpTypePointer StorageBuffer %5 +%46 = OpTypeBool +%48 = OpConstantNull %5 +%57 = OpConstantNull %5 %28 = OpFunction %2 None %29 %21 = OpLabel %18 = OpVariable %19 Function %20 %25 = OpLoad %5 %23 %22 = OpCompositeConstruct %10 %25 %32 = OpAccessChain %30 %15 %31 -OpBranch %35 -%35 = OpLabel -%37 = OpAccessChain %36 %32 %31 -%38 = OpLoad %5 %37 -%39 = OpCompositeExtract %5 %22 0 +OpBranch %34 +%34 = OpLabel +%36 = OpAccessChain %35 %32 %31 +%37 = OpLoad %5 %36 +%38 = OpCompositeExtract %5 %22 0 OpStore %18 %31 -%42 = OpAccessChain %41 %11 %31 %31 -%43 = OpLoad %5 %42 -%44 = OpLoad %5 %18 -%45 = OpIAdd %5 %44 %43 -OpStore %18 %45 -%46 = OpULessThan %47 %38 %9 -OpSelectionMerge %50 None -OpBranchConditional %46 %51 %50 -%51 = OpLabel -%48 = OpAccessChain %41 %11 %38 %31 -%52 = OpLoad %5 %48 -OpBranch %50 +%41 = OpAccessChain %40 %11 %31 %31 +%42 = OpLoad %5 %41 +%43 = OpLoad %5 %18 +%44 = OpIAdd %5 %43 %42 +OpStore %18 %44 +%45 = OpULessThan %46 %37 %9 +OpSelectionMerge %49 None +OpBranchConditional %45 %50 %49 %50 = OpLabel -%53 = OpPhi %5 %49 %35 %52 %51 -%54 = OpLoad %5 %18 -%55 = OpIAdd %5 %54 %53 -OpStore %18 %55 -%56 = OpULessThan %47 %39 %9 -OpSelectionMerge %59 None -OpBranchConditional %56 %60 %59 -%60 = OpLabel -%57 = OpAccessChain %41 %11 %39 %31 -%61 = OpLoad %5 %57 -OpBranch %59 +%47 = OpAccessChain %40 %11 %37 %31 +%51 = OpLoad %5 %47 +OpBranch %49 +%49 = OpLabel +%52 = OpPhi %5 %48 %34 %51 %50 +%53 = OpLoad %5 %18 +%54 = OpIAdd %5 %53 %52 +OpStore %18 %54 +%55 = OpULessThan %46 %38 %9 +OpSelectionMerge %58 None +OpBranchConditional %55 %59 %58 %59 = OpLabel -%62 = OpPhi %5 %58 %50 %61 %60 -%63 = OpLoad %5 %18 -%64 = OpIAdd %5 %63 %62 -OpStore %18 %64 -%65 = OpLoad %5 %18 -OpStore %26 %65 +%56 = OpAccessChain %40 %11 %38 %31 +%60 = OpLoad %5 %56 +OpBranch %58 +%58 = OpLabel +%61 = OpPhi %5 %57 %49 %60 %59 +%62 = OpLoad %5 %18 +%63 = OpIAdd %5 %62 %61 +OpStore %18 %63 +%64 = OpLoad %5 %18 +OpStore %26 %64 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-restrict.spvasm b/tests/out/spv/bounds-check-restrict.spvasm index bc0a00135..f6ea5dcde 100644 --- a/tests/out/spv/bounds-check-restrict.spvasm +++ b/tests/out/spv/bounds-check-restrict.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 167 +; Bound: 164 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -49,13 +49,10 @@ OpDecorate %12 Block %71 = OpTypeFunction %5 %4 %4 %80 = OpConstant %5 100.0 %92 = OpTypeFunction %5 -%93 = OpConstant %4 9 -%94 = OpConstant %4 3 -%95 = OpConstant %4 2 -%109 = OpTypeFunction %2 %4 %5 -%133 = OpTypeFunction %2 %4 %9 -%142 = OpTypeFunction %2 %4 %4 %5 -%162 = OpTypeFunction %2 %5 +%106 = OpTypeFunction %2 %4 %5 +%130 = OpTypeFunction %2 %4 %9 +%139 = OpTypeFunction %2 %4 %4 %5 +%159 = OpTypeFunction %2 %5 %17 = OpFunction %5 None %18 %16 = OpFunctionParameter %4 %15 = OpLabel @@ -137,103 +134,103 @@ OpReturnValue %89 OpFunctionEnd %91 = OpFunction %5 None %92 %90 = OpLabel -OpBranch %96 -%96 = OpLabel -%97 = OpAccessChain %21 %13 %24 %22 -%98 = OpLoad %5 %97 -%99 = OpAccessChain %44 %13 %33 %36 +OpBranch %93 +%93 = OpLabel +%94 = OpAccessChain %21 %13 %24 %22 +%95 = OpLoad %5 %94 +%96 = OpAccessChain %44 %13 %33 %36 +%97 = OpLoad %5 %96 +%98 = OpFAdd %5 %95 %97 +%99 = OpAccessChain %44 %13 %63 %63 %36 %100 = OpLoad %5 %99 %101 = OpFAdd %5 %98 %100 -%102 = OpAccessChain %44 %13 %63 %63 %36 -%103 = OpLoad %5 %102 -%104 = OpFAdd %5 %101 %103 -OpReturnValue %104 +OpReturnValue %101 OpFunctionEnd -%108 = OpFunction %2 None %109 -%106 = OpFunctionParameter %4 -%107 = OpFunctionParameter %5 -%105 = OpLabel -OpBranch %110 +%105 = OpFunction %2 None %106 +%103 = OpFunctionParameter %4 +%104 = OpFunctionParameter %5 +%102 = OpLabel +OpBranch %107 +%107 = OpLabel +%108 = OpExtInst %8 %1 UMin %103 %22 +%109 = OpAccessChain %21 %13 %24 %108 +OpStore %109 %104 +OpReturn +OpFunctionEnd +%113 = OpFunction %2 None %106 +%111 = OpFunctionParameter %4 +%112 = OpFunctionParameter %5 %110 = OpLabel -%111 = OpExtInst %8 %1 UMin %106 %22 -%112 = OpAccessChain %21 %13 %24 %111 -OpStore %112 %107 +OpBranch %114 +%114 = OpLabel +%115 = OpArrayLength %8 %13 3 +%116 = OpISub %8 %115 %33 +%117 = OpExtInst %8 %1 UMin %111 %116 +%118 = OpAccessChain %21 %13 %36 %117 +OpStore %118 %112 OpReturn OpFunctionEnd -%116 = OpFunction %2 None %109 -%114 = OpFunctionParameter %4 -%115 = OpFunctionParameter %5 -%113 = OpLabel -OpBranch %117 -%117 = OpLabel -%118 = OpArrayLength %8 %13 3 -%119 = OpISub %8 %118 %33 -%120 = OpExtInst %8 %1 UMin %114 %119 -%121 = OpAccessChain %21 %13 %36 %120 -OpStore %121 %115 +%122 = OpFunction %2 None %106 +%120 = OpFunctionParameter %4 +%121 = OpFunctionParameter %5 +%119 = OpLabel +OpBranch %123 +%123 = OpLabel +%124 = OpExtInst %8 %1 UMin %120 %36 +%125 = OpAccessChain %44 %13 %33 %124 +OpStore %125 %121 OpReturn OpFunctionEnd -%125 = OpFunction %2 None %109 -%123 = OpFunctionParameter %4 -%124 = OpFunctionParameter %5 -%122 = OpLabel -OpBranch %126 +%129 = OpFunction %2 None %130 +%127 = OpFunctionParameter %4 +%128 = OpFunctionParameter %9 %126 = OpLabel -%127 = OpExtInst %8 %1 UMin %123 %36 -%128 = OpAccessChain %44 %13 %33 %127 -OpStore %128 %124 +OpBranch %131 +%131 = OpLabel +%132 = OpExtInst %8 %1 UMin %127 %63 +%133 = OpAccessChain %62 %13 %63 %132 +OpStore %133 %128 OpReturn OpFunctionEnd -%132 = OpFunction %2 None %133 -%130 = OpFunctionParameter %4 -%131 = OpFunctionParameter %9 -%129 = OpLabel -OpBranch %134 +%138 = OpFunction %2 None %139 +%135 = OpFunctionParameter %4 +%136 = OpFunctionParameter %4 +%137 = OpFunctionParameter %5 %134 = OpLabel -%135 = OpExtInst %8 %1 UMin %130 %63 -%136 = OpAccessChain %62 %13 %63 %135 -OpStore %136 %131 +OpBranch %140 +%140 = OpLabel +%141 = OpExtInst %8 %1 UMin %136 %36 +%142 = OpExtInst %8 %1 UMin %135 %63 +%143 = OpAccessChain %44 %13 %63 %142 %141 +OpStore %143 %137 OpReturn OpFunctionEnd -%141 = OpFunction %2 None %142 -%138 = OpFunctionParameter %4 -%139 = OpFunctionParameter %4 -%140 = OpFunctionParameter %5 -%137 = OpLabel -OpBranch %143 -%143 = OpLabel -%144 = OpExtInst %8 %1 UMin %139 %36 -%145 = OpExtInst %8 %1 UMin %138 %63 -%146 = OpAccessChain %44 %13 %63 %145 %144 -OpStore %146 %140 +%147 = OpFunction %2 None %106 +%145 = OpFunctionParameter %4 +%146 = OpFunctionParameter %5 +%144 = OpLabel +OpBranch %148 +%148 = OpLabel +%149 = OpConvertSToF %5 %145 +%150 = OpFDiv %5 %149 %80 +%151 = OpExtInst %5 %1 Sin %150 +%152 = OpFMul %5 %151 %80 +%153 = OpConvertFToS %4 %152 +%154 = OpExtInst %8 %1 UMin %153 %22 +%155 = OpAccessChain %21 %13 %24 %154 +OpStore %155 %146 OpReturn OpFunctionEnd -%150 = OpFunction %2 None %109 -%148 = OpFunctionParameter %4 -%149 = OpFunctionParameter %5 -%147 = OpLabel -OpBranch %151 -%151 = OpLabel -%152 = OpConvertSToF %5 %148 -%153 = OpFDiv %5 %152 %80 -%154 = OpExtInst %5 %1 Sin %153 -%155 = OpFMul %5 %154 %80 -%156 = OpConvertFToS %4 %155 -%157 = OpExtInst %8 %1 UMin %156 %22 -%158 = OpAccessChain %21 %13 %24 %157 -OpStore %158 %149 -OpReturn -OpFunctionEnd -%161 = OpFunction %2 None %162 -%160 = OpFunctionParameter %5 -%159 = OpLabel -OpBranch %163 -%163 = OpLabel -%164 = OpAccessChain %21 %13 %24 %22 -OpStore %164 %160 -%165 = OpAccessChain %44 %13 %33 %36 -OpStore %165 %160 -%166 = OpAccessChain %44 %13 %63 %63 %36 -OpStore %166 %160 +%158 = OpFunction %2 None %159 +%157 = OpFunctionParameter %5 +%156 = OpLabel +OpBranch %160 +%160 = OpLabel +%161 = OpAccessChain %21 %13 %24 %22 +OpStore %161 %157 +%162 = OpAccessChain %44 %13 %33 %36 +OpStore %162 %157 +%163 = OpAccessChain %44 %13 %63 %63 %36 +OpStore %163 %157 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index b2a82f673..c18b02063 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 209 +; Bound: 206 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -57,14 +57,11 @@ OpDecorate %12 Block %105 = OpConstant %5 100.0 %114 = OpConstantNull %5 %121 = OpTypeFunction %5 -%122 = OpConstant %4 9 -%123 = OpConstant %4 3 -%124 = OpConstant %4 2 -%126 = OpConstant %8 9 -%139 = OpTypeFunction %2 %4 %5 -%168 = OpTypeFunction %2 %4 %9 -%179 = OpTypeFunction %2 %4 %4 %5 -%204 = OpTypeFunction %2 %5 +%123 = OpConstant %8 9 +%136 = OpTypeFunction %2 %4 %5 +%165 = OpTypeFunction %2 %4 %9 +%176 = OpTypeFunction %2 %4 %4 %5 +%201 = OpTypeFunction %2 %5 %17 = OpFunction %5 None %18 %16 = OpFunctionParameter %4 %15 = OpLabel @@ -188,133 +185,133 @@ OpReturnValue %118 OpFunctionEnd %120 = OpFunction %5 None %121 %119 = OpLabel -OpBranch %125 -%125 = OpLabel -%127 = OpAccessChain %21 %13 %24 %126 -%128 = OpLoad %5 %127 -%129 = OpAccessChain %50 %13 %53 %38 +OpBranch %122 +%122 = OpLabel +%124 = OpAccessChain %21 %13 %24 %123 +%125 = OpLoad %5 %124 +%126 = OpAccessChain %50 %13 %53 %38 +%127 = OpLoad %5 %126 +%128 = OpFAdd %5 %125 %127 +%129 = OpAccessChain %50 %13 %80 %80 %38 %130 = OpLoad %5 %129 %131 = OpFAdd %5 %128 %130 -%132 = OpAccessChain %50 %13 %80 %80 %38 -%133 = OpLoad %5 %132 -%134 = OpFAdd %5 %131 %133 -OpReturnValue %134 +OpReturnValue %131 OpFunctionEnd -%138 = OpFunction %2 None %139 -%136 = OpFunctionParameter %4 -%137 = OpFunctionParameter %5 -%135 = OpLabel +%135 = OpFunction %2 None %136 +%133 = OpFunctionParameter %4 +%134 = OpFunctionParameter %5 +%132 = OpLabel +OpBranch %137 +%137 = OpLabel +%138 = OpULessThan %23 %133 %7 +OpSelectionMerge %140 None +OpBranchConditional %138 %141 %140 +%141 = OpLabel +%139 = OpAccessChain %21 %13 %24 %133 +OpStore %139 %134 OpBranch %140 %140 = OpLabel -%141 = OpULessThan %23 %136 %7 -OpSelectionMerge %143 None -OpBranchConditional %141 %144 %143 -%144 = OpLabel -%142 = OpAccessChain %21 %13 %24 %136 -OpStore %142 %137 -OpBranch %143 -%143 = OpLabel OpReturn OpFunctionEnd -%148 = OpFunction %2 None %139 -%146 = OpFunctionParameter %4 -%147 = OpFunctionParameter %5 -%145 = OpLabel -OpBranch %149 -%149 = OpLabel -%150 = OpArrayLength %8 %13 3 -%151 = OpULessThan %23 %146 %150 -OpSelectionMerge %153 None -OpBranchConditional %151 %154 %153 -%154 = OpLabel -%152 = OpAccessChain %21 %13 %38 %146 -OpStore %152 %147 -OpBranch %153 -%153 = OpLabel +%145 = OpFunction %2 None %136 +%143 = OpFunctionParameter %4 +%144 = OpFunctionParameter %5 +%142 = OpLabel +OpBranch %146 +%146 = OpLabel +%147 = OpArrayLength %8 %13 3 +%148 = OpULessThan %23 %143 %147 +OpSelectionMerge %150 None +OpBranchConditional %148 %151 %150 +%151 = OpLabel +%149 = OpAccessChain %21 %13 %38 %143 +OpStore %149 %144 +OpBranch %150 +%150 = OpLabel OpReturn OpFunctionEnd -%158 = OpFunction %2 None %139 -%156 = OpFunctionParameter %4 -%157 = OpFunctionParameter %5 -%155 = OpLabel +%155 = OpFunction %2 None %136 +%153 = OpFunctionParameter %4 +%154 = OpFunctionParameter %5 +%152 = OpLabel +OpBranch %156 +%156 = OpLabel +%157 = OpULessThan %23 %153 %51 +OpSelectionMerge %159 None +OpBranchConditional %157 %160 %159 +%160 = OpLabel +%158 = OpAccessChain %50 %13 %53 %153 +OpStore %158 %154 OpBranch %159 %159 = OpLabel -%160 = OpULessThan %23 %156 %51 -OpSelectionMerge %162 None -OpBranchConditional %160 %163 %162 -%163 = OpLabel -%161 = OpAccessChain %50 %13 %53 %156 -OpStore %161 %157 -OpBranch %162 -%162 = OpLabel OpReturn OpFunctionEnd -%167 = OpFunction %2 None %168 -%165 = OpFunctionParameter %4 -%166 = OpFunctionParameter %9 -%164 = OpLabel +%164 = OpFunction %2 None %165 +%162 = OpFunctionParameter %4 +%163 = OpFunctionParameter %9 +%161 = OpLabel +OpBranch %166 +%166 = OpLabel +%167 = OpULessThan %23 %162 %38 +OpSelectionMerge %169 None +OpBranchConditional %167 %170 %169 +%170 = OpLabel +%168 = OpAccessChain %78 %13 %80 %162 +OpStore %168 %163 OpBranch %169 %169 = OpLabel -%170 = OpULessThan %23 %165 %38 -OpSelectionMerge %172 None -OpBranchConditional %170 %173 %172 -%173 = OpLabel -%171 = OpAccessChain %78 %13 %80 %165 -OpStore %171 %166 -OpBranch %172 -%172 = OpLabel OpReturn OpFunctionEnd -%178 = OpFunction %2 None %179 -%175 = OpFunctionParameter %4 -%176 = OpFunctionParameter %4 -%177 = OpFunctionParameter %5 -%174 = OpLabel -OpBranch %180 -%180 = OpLabel -%181 = OpULessThan %23 %176 %51 -%182 = OpULessThan %23 %175 %38 -%183 = OpLogicalAnd %23 %181 %182 -OpSelectionMerge %185 None -OpBranchConditional %183 %186 %185 -%186 = OpLabel -%184 = OpAccessChain %50 %13 %80 %175 %176 -OpStore %184 %177 -OpBranch %185 -%185 = OpLabel +%175 = OpFunction %2 None %176 +%172 = OpFunctionParameter %4 +%173 = OpFunctionParameter %4 +%174 = OpFunctionParameter %5 +%171 = OpLabel +OpBranch %177 +%177 = OpLabel +%178 = OpULessThan %23 %173 %51 +%179 = OpULessThan %23 %172 %38 +%180 = OpLogicalAnd %23 %178 %179 +OpSelectionMerge %182 None +OpBranchConditional %180 %183 %182 +%183 = OpLabel +%181 = OpAccessChain %50 %13 %80 %172 %173 +OpStore %181 %174 +OpBranch %182 +%182 = OpLabel OpReturn OpFunctionEnd -%190 = OpFunction %2 None %139 -%188 = OpFunctionParameter %4 -%189 = OpFunctionParameter %5 -%187 = OpLabel -OpBranch %191 -%191 = OpLabel -%192 = OpConvertSToF %5 %188 -%193 = OpFDiv %5 %192 %105 -%194 = OpExtInst %5 %1 Sin %193 -%195 = OpFMul %5 %194 %105 -%196 = OpConvertFToS %4 %195 -%197 = OpULessThan %23 %196 %7 -OpSelectionMerge %199 None -OpBranchConditional %197 %200 %199 -%200 = OpLabel -%198 = OpAccessChain %21 %13 %24 %196 -OpStore %198 %189 -OpBranch %199 -%199 = OpLabel +%187 = OpFunction %2 None %136 +%185 = OpFunctionParameter %4 +%186 = OpFunctionParameter %5 +%184 = OpLabel +OpBranch %188 +%188 = OpLabel +%189 = OpConvertSToF %5 %185 +%190 = OpFDiv %5 %189 %105 +%191 = OpExtInst %5 %1 Sin %190 +%192 = OpFMul %5 %191 %105 +%193 = OpConvertFToS %4 %192 +%194 = OpULessThan %23 %193 %7 +OpSelectionMerge %196 None +OpBranchConditional %194 %197 %196 +%197 = OpLabel +%195 = OpAccessChain %21 %13 %24 %193 +OpStore %195 %186 +OpBranch %196 +%196 = OpLabel OpReturn OpFunctionEnd -%203 = OpFunction %2 None %204 -%202 = OpFunctionParameter %5 -%201 = OpLabel -OpBranch %205 -%205 = OpLabel -%206 = OpAccessChain %21 %13 %24 %126 -OpStore %206 %202 -%207 = OpAccessChain %50 %13 %53 %38 -OpStore %207 %202 -%208 = OpAccessChain %50 %13 %80 %80 %38 -OpStore %208 %202 +%200 = OpFunction %2 None %201 +%199 = OpFunctionParameter %5 +%198 = OpLabel +OpBranch %202 +%202 = OpLabel +%203 = OpAccessChain %21 %13 %24 %123 +OpStore %203 %199 +%204 = OpAccessChain %50 %13 %53 %38 +OpStore %204 %199 +%205 = OpAccessChain %50 %13 %80 %80 %38 +OpStore %205 %199 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 9f5c1d495..f50b80696 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 186 +; Bound: 180 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %104 "main" %129 -OpExecutionMode %104 LocalSize 1 1 1 +OpEntryPoint GLCompute %103 "main" %123 +OpExecutionMode %103 LocalSize 1 1 1 OpDecorate %11 ArrayStride 4 OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %13 1 Offset 12 @@ -48,7 +48,7 @@ OpDecorate %50 DescriptorSet 0 OpDecorate %50 Binding 7 OpDecorate %51 Block OpMemberDecorate %51 0 Offset 0 -OpDecorate %129 BuiltIn LocalInvocationId +OpDecorate %123 BuiltIn LocalInvocationId %2 = OpTypeVoid %4 = OpTypeBool %3 = OpConstantTrue %4 @@ -108,55 +108,49 @@ OpDecorate %129 BuiltIn LocalInvocationId %65 = OpConstant %6 0 %67 = OpConstant %10 1.0 %68 = OpConstant %8 1 -%69 = OpConstant %8 0 -%70 = OpConstant %10 2.0 -%71 = OpConstant %10 3.0 +%69 = OpConstant %10 2.0 +%70 = OpConstant %10 3.0 +%71 = OpConstantNull %27 %72 = OpConstantNull %27 -%73 = OpConstantNull %27 -%75 = OpTypePointer StorageBuffer %12 -%78 = OpTypePointer StorageBuffer %10 -%98 = OpTypePointer Function %10 -%99 = OpConstantNull %10 -%101 = OpTypePointer Function %4 -%102 = OpConstantNull %4 -%106 = OpTypePointer StorageBuffer %15 -%108 = OpTypePointer Uniform %17 -%110 = OpTypePointer Uniform %12 -%112 = OpTypePointer Uniform %19 -%114 = OpTypePointer Uniform %23 -%116 = OpTypePointer Uniform %26 -%118 = OpConstant %8 7 -%119 = OpConstant %8 6 -%120 = OpConstant %8 5 -%121 = OpConstant %8 4 -%122 = OpConstant %8 3 -%123 = OpConstant %10 4.0 -%124 = OpConstantTrue %4 -%126 = OpConstantNull %11 -%127 = OpConstantNull %6 -%128 = OpTypeVector %6 3 -%130 = OpTypePointer Input %128 -%129 = OpVariable %130 Input -%132 = OpConstantNull %128 -%133 = OpTypeVector %4 3 -%138 = OpConstant %6 264 -%141 = OpTypePointer Workgroup %10 -%142 = OpTypePointer Uniform %25 -%143 = OpTypePointer Uniform %24 -%146 = OpTypePointer Uniform %21 -%147 = OpTypePointer Uniform %20 -%148 = OpTypePointer Uniform %16 -%153 = OpConstant %6 7 -%159 = OpConstant %6 6 -%161 = OpTypePointer StorageBuffer %14 -%162 = OpConstant %6 1 -%165 = OpConstant %6 5 -%167 = OpTypePointer Uniform %16 -%168 = OpTypePointer Uniform %10 -%169 = OpConstant %6 3 -%172 = OpConstant %6 4 -%174 = OpTypePointer StorageBuffer %10 -%185 = OpConstant %6 256 +%74 = OpTypePointer StorageBuffer %12 +%77 = OpTypePointer StorageBuffer %10 +%97 = OpTypePointer Function %10 +%98 = OpConstantNull %10 +%100 = OpTypePointer Function %4 +%101 = OpConstantNull %4 +%105 = OpTypePointer StorageBuffer %15 +%107 = OpTypePointer Uniform %17 +%109 = OpTypePointer Uniform %12 +%111 = OpTypePointer Uniform %19 +%113 = OpTypePointer Uniform %23 +%115 = OpTypePointer Uniform %26 +%117 = OpConstant %10 4.0 +%118 = OpConstantTrue %4 +%120 = OpConstantNull %11 +%121 = OpConstantNull %6 +%122 = OpTypeVector %6 3 +%124 = OpTypePointer Input %122 +%123 = OpVariable %124 Input +%126 = OpConstantNull %122 +%127 = OpTypeVector %4 3 +%132 = OpConstant %6 264 +%135 = OpTypePointer Workgroup %10 +%136 = OpTypePointer Uniform %25 +%137 = OpTypePointer Uniform %24 +%140 = OpTypePointer Uniform %21 +%141 = OpTypePointer Uniform %20 +%142 = OpTypePointer Uniform %16 +%147 = OpConstant %6 7 +%153 = OpConstant %6 6 +%155 = OpTypePointer StorageBuffer %14 +%156 = OpConstant %6 1 +%159 = OpConstant %6 5 +%161 = OpTypePointer Uniform %16 +%162 = OpTypePointer Uniform %10 +%163 = OpConstant %6 3 +%166 = OpConstant %6 4 +%168 = OpTypePointer StorageBuffer %10 +%179 = OpConstant %6 256 %55 = OpFunction %2 None %56 %54 = OpFunctionParameter %12 %53 = OpLabel @@ -168,100 +162,100 @@ OpFunctionEnd %61 = OpLabel %58 = OpVariable %59 Function %60 %66 = OpAccessChain %64 %32 %65 -OpBranch %74 -%74 = OpLabel -%76 = OpCompositeConstruct %12 %67 %67 %67 -%77 = OpAccessChain %75 %66 %65 -OpStore %77 %76 +OpBranch %73 +%73 = OpLabel +%75 = OpCompositeConstruct %12 %67 %67 %67 +%76 = OpAccessChain %74 %66 %65 +OpStore %76 %75 OpStore %58 %68 -%79 = OpAccessChain %78 %66 %65 %65 -OpStore %79 %67 -%80 = OpAccessChain %78 %66 %65 %65 -OpStore %80 %70 -%81 = OpLoad %8 %58 -%82 = OpAccessChain %78 %66 %65 %81 -OpStore %82 %71 -%83 = OpLoad %13 %66 -%84 = OpCompositeExtract %12 %83 0 -%85 = OpCompositeExtract %12 %83 0 -%86 = OpVectorShuffle %14 %85 %85 2 0 -%87 = OpCompositeExtract %12 %83 0 -%88 = OpFunctionCall %2 %55 %87 -%89 = OpCompositeExtract %12 %83 0 -%90 = OpVectorTimesMatrix %12 %89 %72 -%91 = OpCompositeExtract %12 %83 0 -%92 = OpMatrixTimesVector %12 %73 %91 -%93 = OpCompositeExtract %12 %83 0 -%94 = OpVectorTimesScalar %12 %93 %70 -%95 = OpCompositeExtract %12 %83 0 -%96 = OpVectorTimesScalar %12 %95 %70 +%78 = OpAccessChain %77 %66 %65 %65 +OpStore %78 %67 +%79 = OpAccessChain %77 %66 %65 %65 +OpStore %79 %69 +%80 = OpLoad %8 %58 +%81 = OpAccessChain %77 %66 %65 %80 +OpStore %81 %70 +%82 = OpLoad %13 %66 +%83 = OpCompositeExtract %12 %82 0 +%84 = OpCompositeExtract %12 %82 0 +%85 = OpVectorShuffle %14 %84 %84 2 0 +%86 = OpCompositeExtract %12 %82 0 +%87 = OpFunctionCall %2 %55 %86 +%88 = OpCompositeExtract %12 %82 0 +%89 = OpVectorTimesMatrix %12 %88 %71 +%90 = OpCompositeExtract %12 %82 0 +%91 = OpMatrixTimesVector %12 %72 %90 +%92 = OpCompositeExtract %12 %82 0 +%93 = OpVectorTimesScalar %12 %92 %69 +%94 = OpCompositeExtract %12 %82 0 +%95 = OpVectorTimesScalar %12 %94 %69 OpReturn OpFunctionEnd -%104 = OpFunction %2 None %63 -%103 = OpLabel -%97 = OpVariable %98 Function %99 -%100 = OpVariable %101 Function %102 -%105 = OpAccessChain %64 %32 %65 -%107 = OpAccessChain %106 %35 %65 -%109 = OpAccessChain %108 %38 %65 -%111 = OpAccessChain %110 %41 %65 -%113 = OpAccessChain %112 %44 %65 -%115 = OpAccessChain %114 %47 %65 -%117 = OpAccessChain %116 %50 %65 -OpBranch %125 -%125 = OpLabel -%131 = OpLoad %128 %129 -%134 = OpIEqual %133 %131 %132 -%135 = OpAll %4 %134 -OpSelectionMerge %136 None -OpBranchConditional %135 %137 %136 -%137 = OpLabel -OpStore %28 %126 -OpStore %30 %127 -OpBranch %136 -%136 = OpLabel -OpControlBarrier %22 %22 %138 -OpBranch %139 -%139 = OpLabel -%140 = OpFunctionCall %2 %62 -%144 = OpAccessChain %143 %117 %65 %65 -%145 = OpLoad %24 %144 -%149 = OpAccessChain %148 %115 %65 %65 %65 -%150 = OpLoad %16 %149 -%151 = OpMatrixTimesVector %14 %145 %150 +%103 = OpFunction %2 None %63 +%102 = OpLabel +%96 = OpVariable %97 Function %98 +%99 = OpVariable %100 Function %101 +%104 = OpAccessChain %64 %32 %65 +%106 = OpAccessChain %105 %35 %65 +%108 = OpAccessChain %107 %38 %65 +%110 = OpAccessChain %109 %41 %65 +%112 = OpAccessChain %111 %44 %65 +%114 = OpAccessChain %113 %47 %65 +%116 = OpAccessChain %115 %50 %65 +OpBranch %119 +%119 = OpLabel +%125 = OpLoad %122 %123 +%128 = OpIEqual %127 %125 %126 +%129 = OpAll %4 %128 +OpSelectionMerge %130 None +OpBranchConditional %129 %131 %130 +%131 = OpLabel +OpStore %28 %120 +OpStore %30 %121 +OpBranch %130 +%130 = OpLabel +OpControlBarrier %22 %22 %132 +OpBranch %133 +%133 = OpLabel +%134 = OpFunctionCall %2 %62 +%138 = OpAccessChain %137 %116 %65 %65 +%139 = OpLoad %24 %138 +%143 = OpAccessChain %142 %114 %65 %65 %65 +%144 = OpLoad %16 %143 +%145 = OpMatrixTimesVector %14 %139 %144 +%146 = OpCompositeExtract %10 %145 0 +%148 = OpAccessChain %135 %28 %147 +OpStore %148 %146 +%149 = OpLoad %19 %112 +%150 = OpLoad %12 %110 +%151 = OpMatrixTimesVector %14 %149 %150 %152 = OpCompositeExtract %10 %151 0 -%154 = OpAccessChain %141 %28 %153 +%154 = OpAccessChain %135 %28 %153 OpStore %154 %152 -%155 = OpLoad %19 %113 -%156 = OpLoad %12 %111 -%157 = OpMatrixTimesVector %14 %155 %156 -%158 = OpCompositeExtract %10 %157 0 -%160 = OpAccessChain %141 %28 %159 +%157 = OpAccessChain %77 %106 %156 %156 +%158 = OpLoad %10 %157 +%160 = OpAccessChain %135 %28 %159 OpStore %160 %158 -%163 = OpAccessChain %78 %107 %162 %162 -%164 = OpLoad %10 %163 -%166 = OpAccessChain %141 %28 %165 -OpStore %166 %164 -%170 = OpAccessChain %168 %109 %65 %169 -%171 = OpLoad %10 %170 -%173 = OpAccessChain %141 %28 %172 -OpStore %173 %171 -%175 = OpAccessChain %174 %105 %162 -%176 = OpLoad %10 %175 -%177 = OpAccessChain %141 %28 %169 -OpStore %177 %176 -%178 = OpAccessChain %78 %105 %65 %65 -%179 = OpLoad %10 %178 -%180 = OpAccessChain %141 %28 %22 -OpStore %180 %179 -%181 = OpAccessChain %174 %105 %162 -OpStore %181 %123 -%182 = OpArrayLength %6 %35 0 -%183 = OpConvertUToF %10 %182 -%184 = OpAccessChain %141 %28 %162 -OpStore %184 %183 -OpAtomicStore %30 %9 %185 %22 -OpStore %97 %67 -OpStore %100 %124 +%164 = OpAccessChain %162 %108 %65 %163 +%165 = OpLoad %10 %164 +%167 = OpAccessChain %135 %28 %166 +OpStore %167 %165 +%169 = OpAccessChain %168 %104 %156 +%170 = OpLoad %10 %169 +%171 = OpAccessChain %135 %28 %163 +OpStore %171 %170 +%172 = OpAccessChain %77 %104 %65 %65 +%173 = OpLoad %10 %172 +%174 = OpAccessChain %135 %28 %22 +OpStore %174 %173 +%175 = OpAccessChain %168 %104 %156 +OpStore %175 %117 +%176 = OpArrayLength %6 %35 0 +%177 = OpConvertUToF %10 %176 +%178 = OpAccessChain %135 %28 %156 +OpStore %178 %177 +OpAtomicStore %30 %9 %179 %22 +OpStore %96 %67 +OpStore %99 %118 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index 3e2e2a348..533a3daa5 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 56 +; Bound: 55 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -44,14 +44,13 @@ OpDecorate %29 BuiltIn NumWorkgroups %27 = OpVariable %20 Input %29 = OpVariable %20 Input %32 = OpTypeFunction %2 -%33 = OpConstant %4 0 -%35 = OpConstantNull %11 -%36 = OpConstantNull %13 -%37 = OpTypeVector %10 3 -%42 = OpConstant %8 2 -%43 = OpConstant %8 264 -%45 = OpTypePointer Workgroup %8 -%54 = OpConstant %8 0 +%34 = OpConstantNull %11 +%35 = OpConstantNull %13 +%36 = OpTypeVector %10 3 +%41 = OpConstant %8 2 +%42 = OpConstant %8 264 +%44 = OpTypePointer Workgroup %8 +%53 = OpConstant %8 0 %31 = OpFunction %2 None %32 %18 = OpLabel %21 = OpLoad %13 %19 @@ -59,28 +58,28 @@ OpDecorate %29 BuiltIn NumWorkgroups %26 = OpLoad %8 %24 %28 = OpLoad %13 %27 %30 = OpLoad %13 %29 -OpBranch %34 -%34 = OpLabel -%38 = OpIEqual %37 %23 %36 -%39 = OpAll %10 %38 -OpSelectionMerge %40 None -OpBranchConditional %39 %41 %40 -%41 = OpLabel -OpStore %16 %35 -OpBranch %40 +OpBranch %33 +%33 = OpLabel +%37 = OpIEqual %36 %23 %35 +%38 = OpAll %10 %37 +OpSelectionMerge %39 None +OpBranchConditional %38 %40 %39 %40 = OpLabel -OpControlBarrier %42 %42 %43 -OpBranch %44 -%44 = OpLabel -%46 = OpCompositeExtract %8 %21 0 -%47 = OpCompositeExtract %8 %23 0 -%48 = OpIAdd %8 %46 %47 -%49 = OpIAdd %8 %48 %26 -%50 = OpCompositeExtract %8 %28 0 -%51 = OpIAdd %8 %49 %50 -%52 = OpCompositeExtract %8 %30 0 -%53 = OpIAdd %8 %51 %52 -%55 = OpAccessChain %45 %16 %54 -OpStore %55 %53 +OpStore %16 %34 +OpBranch %39 +%39 = OpLabel +OpControlBarrier %41 %41 %42 +OpBranch %43 +%43 = OpLabel +%45 = OpCompositeExtract %8 %21 0 +%46 = OpCompositeExtract %8 %23 0 +%47 = OpIAdd %8 %45 %46 +%48 = OpIAdd %8 %47 %26 +%49 = OpCompositeExtract %8 %28 0 +%50 = OpIAdd %8 %48 %49 +%51 = OpCompositeExtract %8 %30 0 +%52 = OpIAdd %8 %50 %51 +%54 = OpAccessChain %44 %16 %53 +OpStore %54 %52 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 945775292..783b789c2 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 589 +; Bound: 591 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %577 "main" -OpExecutionMode %577 LocalSize 1 1 1 +OpEntryPoint GLCompute %579 "main" +OpExecutionMode %579 LocalSize 1 1 1 OpMemberDecorate %17 0 Offset 0 OpMemberDecorate %17 1 Offset 16 OpDecorate %22 ArrayStride 32 @@ -99,20 +99,20 @@ OpDecorate %24 ArrayStride 4 %195 = OpConstantNull %29 %197 = OpTypeVector %8 2 %208 = OpTypeVector %20 3 -%503 = OpTypePointer Function %8 -%504 = OpConstantNull %8 -%506 = OpTypePointer Function %30 -%507 = OpConstantNull %30 -%510 = OpConstantNull %30 -%538 = OpTypePointer Function %8 -%549 = OpConstant %8 -1 -%550 = OpConstant %8 -2 -%551 = OpConstant %8 -3 -%552 = OpConstant %8 4 -%553 = OpConstant %8 -5 -%554 = OpConstant %8 6 -%555 = OpConstant %8 -7 -%556 = OpConstant %8 -8 +%505 = OpTypePointer Function %8 +%506 = OpConstantNull %8 +%508 = OpTypePointer Function %30 +%509 = OpConstantNull %30 +%512 = OpConstantNull %30 +%540 = OpTypePointer Function %8 +%551 = OpConstant %8 -1 +%552 = OpConstant %8 -2 +%553 = OpConstant %8 -3 +%554 = OpConstant %8 4 +%555 = OpConstant %8 -5 +%556 = OpConstant %8 6 +%557 = OpConstant %8 -7 +%558 = OpConstant %8 -8 %36 = OpFunction %10 None %37 %35 = OpLabel OpBranch %42 @@ -304,348 +304,352 @@ OpBranch %196 %260 = OpCompositeConstruct %10 %66 %66 %66 %66 %261 = OpCompositeConstruct %10 %3 %3 %3 %3 %262 = OpFRem %10 %260 %261 -%263 = OpCompositeConstruct %197 %70 %70 -%264 = OpCompositeConstruct %197 %7 %7 -%265 = OpIAdd %197 %263 %264 +OpBranch %263 +%263 = OpLabel +%265 = OpCompositeConstruct %197 %70 %70 %266 = OpCompositeConstruct %197 %7 %7 -%267 = OpCompositeConstruct %197 %70 %70 -%268 = OpIAdd %197 %267 %266 -%269 = OpCompositeConstruct %21 %184 %184 -%270 = OpCompositeConstruct %21 %185 %185 -%271 = OpIAdd %21 %269 %270 +%267 = OpIAdd %197 %265 %266 +%268 = OpCompositeConstruct %197 %7 %7 +%269 = OpCompositeConstruct %197 %70 %70 +%270 = OpIAdd %197 %269 %268 +%271 = OpCompositeConstruct %21 %184 %184 %272 = OpCompositeConstruct %21 %185 %185 -%273 = OpCompositeConstruct %21 %184 %184 -%274 = OpIAdd %21 %273 %272 -%275 = OpCompositeConstruct %14 %66 %66 -%276 = OpCompositeConstruct %14 %3 %3 -%277 = OpFAdd %14 %275 %276 +%273 = OpIAdd %21 %271 %272 +%274 = OpCompositeConstruct %21 %185 %185 +%275 = OpCompositeConstruct %21 %184 %184 +%276 = OpIAdd %21 %275 %274 +%277 = OpCompositeConstruct %14 %66 %66 %278 = OpCompositeConstruct %14 %3 %3 -%279 = OpCompositeConstruct %14 %66 %66 -%280 = OpFAdd %14 %279 %278 -%281 = OpCompositeConstruct %197 %70 %70 -%282 = OpCompositeConstruct %197 %7 %7 -%283 = OpISub %197 %281 %282 +%279 = OpFAdd %14 %277 %278 +%280 = OpCompositeConstruct %14 %3 %3 +%281 = OpCompositeConstruct %14 %66 %66 +%282 = OpFAdd %14 %281 %280 +%283 = OpCompositeConstruct %197 %70 %70 %284 = OpCompositeConstruct %197 %7 %7 -%285 = OpCompositeConstruct %197 %70 %70 -%286 = OpISub %197 %285 %284 -%287 = OpCompositeConstruct %21 %184 %184 -%288 = OpCompositeConstruct %21 %185 %185 -%289 = OpISub %21 %287 %288 +%285 = OpISub %197 %283 %284 +%286 = OpCompositeConstruct %197 %7 %7 +%287 = OpCompositeConstruct %197 %70 %70 +%288 = OpISub %197 %287 %286 +%289 = OpCompositeConstruct %21 %184 %184 %290 = OpCompositeConstruct %21 %185 %185 -%291 = OpCompositeConstruct %21 %184 %184 -%292 = OpISub %21 %291 %290 -%293 = OpCompositeConstruct %14 %66 %66 -%294 = OpCompositeConstruct %14 %3 %3 -%295 = OpFSub %14 %293 %294 +%291 = OpISub %21 %289 %290 +%292 = OpCompositeConstruct %21 %185 %185 +%293 = OpCompositeConstruct %21 %184 %184 +%294 = OpISub %21 %293 %292 +%295 = OpCompositeConstruct %14 %66 %66 %296 = OpCompositeConstruct %14 %3 %3 -%297 = OpCompositeConstruct %14 %66 %66 -%298 = OpFSub %14 %297 %296 -%299 = OpCompositeConstruct %197 %70 %70 -%301 = OpCompositeConstruct %197 %7 %7 -%300 = OpIMul %197 %299 %301 -%302 = OpCompositeConstruct %197 %7 %7 -%304 = OpCompositeConstruct %197 %70 %70 -%303 = OpIMul %197 %302 %304 -%305 = OpCompositeConstruct %21 %184 %184 -%307 = OpCompositeConstruct %21 %185 %185 -%306 = OpIMul %21 %305 %307 -%308 = OpCompositeConstruct %21 %185 %185 -%310 = OpCompositeConstruct %21 %184 %184 -%309 = OpIMul %21 %308 %310 -%311 = OpCompositeConstruct %14 %66 %66 -%312 = OpVectorTimesScalar %14 %311 %3 -%313 = OpCompositeConstruct %14 %3 %3 -%314 = OpVectorTimesScalar %14 %313 %66 -%315 = OpCompositeConstruct %197 %70 %70 -%316 = OpCompositeConstruct %197 %7 %7 -%317 = OpSDiv %197 %315 %316 +%297 = OpFSub %14 %295 %296 +%298 = OpCompositeConstruct %14 %3 %3 +%299 = OpCompositeConstruct %14 %66 %66 +%300 = OpFSub %14 %299 %298 +%301 = OpCompositeConstruct %197 %70 %70 +%303 = OpCompositeConstruct %197 %7 %7 +%302 = OpIMul %197 %301 %303 +%304 = OpCompositeConstruct %197 %7 %7 +%306 = OpCompositeConstruct %197 %70 %70 +%305 = OpIMul %197 %304 %306 +%307 = OpCompositeConstruct %21 %184 %184 +%309 = OpCompositeConstruct %21 %185 %185 +%308 = OpIMul %21 %307 %309 +%310 = OpCompositeConstruct %21 %185 %185 +%312 = OpCompositeConstruct %21 %184 %184 +%311 = OpIMul %21 %310 %312 +%313 = OpCompositeConstruct %14 %66 %66 +%314 = OpVectorTimesScalar %14 %313 %3 +%315 = OpCompositeConstruct %14 %3 %3 +%316 = OpVectorTimesScalar %14 %315 %66 +%317 = OpCompositeConstruct %197 %70 %70 %318 = OpCompositeConstruct %197 %7 %7 -%319 = OpCompositeConstruct %197 %70 %70 -%320 = OpSDiv %197 %319 %318 -%321 = OpCompositeConstruct %21 %184 %184 -%322 = OpCompositeConstruct %21 %185 %185 -%323 = OpUDiv %21 %321 %322 +%319 = OpSDiv %197 %317 %318 +%320 = OpCompositeConstruct %197 %7 %7 +%321 = OpCompositeConstruct %197 %70 %70 +%322 = OpSDiv %197 %321 %320 +%323 = OpCompositeConstruct %21 %184 %184 %324 = OpCompositeConstruct %21 %185 %185 -%325 = OpCompositeConstruct %21 %184 %184 -%326 = OpUDiv %21 %325 %324 -%327 = OpCompositeConstruct %14 %66 %66 -%328 = OpCompositeConstruct %14 %3 %3 -%329 = OpFDiv %14 %327 %328 +%325 = OpUDiv %21 %323 %324 +%326 = OpCompositeConstruct %21 %185 %185 +%327 = OpCompositeConstruct %21 %184 %184 +%328 = OpUDiv %21 %327 %326 +%329 = OpCompositeConstruct %14 %66 %66 %330 = OpCompositeConstruct %14 %3 %3 -%331 = OpCompositeConstruct %14 %66 %66 -%332 = OpFDiv %14 %331 %330 -%333 = OpCompositeConstruct %197 %70 %70 -%334 = OpCompositeConstruct %197 %7 %7 -%335 = OpSRem %197 %333 %334 +%331 = OpFDiv %14 %329 %330 +%332 = OpCompositeConstruct %14 %3 %3 +%333 = OpCompositeConstruct %14 %66 %66 +%334 = OpFDiv %14 %333 %332 +%335 = OpCompositeConstruct %197 %70 %70 %336 = OpCompositeConstruct %197 %7 %7 -%337 = OpCompositeConstruct %197 %70 %70 -%338 = OpSRem %197 %337 %336 -%339 = OpCompositeConstruct %21 %184 %184 -%340 = OpCompositeConstruct %21 %185 %185 -%341 = OpUMod %21 %339 %340 +%337 = OpSRem %197 %335 %336 +%338 = OpCompositeConstruct %197 %7 %7 +%339 = OpCompositeConstruct %197 %70 %70 +%340 = OpSRem %197 %339 %338 +%341 = OpCompositeConstruct %21 %184 %184 %342 = OpCompositeConstruct %21 %185 %185 -%343 = OpCompositeConstruct %21 %184 %184 -%344 = OpUMod %21 %343 %342 -%345 = OpCompositeConstruct %14 %66 %66 -%346 = OpCompositeConstruct %14 %3 %3 -%347 = OpFRem %14 %345 %346 +%343 = OpUMod %21 %341 %342 +%344 = OpCompositeConstruct %21 %185 %185 +%345 = OpCompositeConstruct %21 %184 %184 +%346 = OpUMod %21 %345 %344 +%347 = OpCompositeConstruct %14 %66 %66 %348 = OpCompositeConstruct %14 %3 %3 -%349 = OpCompositeConstruct %14 %66 %66 -%350 = OpFRem %14 %349 %348 -%352 = OpCompositeExtract %15 %186 0 -%353 = OpCompositeExtract %15 %187 0 -%354 = OpFAdd %15 %352 %353 -%355 = OpCompositeExtract %15 %186 1 -%356 = OpCompositeExtract %15 %187 1 -%357 = OpFAdd %15 %355 %356 -%358 = OpCompositeExtract %15 %186 2 -%359 = OpCompositeExtract %15 %187 2 -%360 = OpFAdd %15 %358 %359 -%351 = OpCompositeConstruct %27 %354 %357 %360 -%362 = OpCompositeExtract %15 %188 0 -%363 = OpCompositeExtract %15 %189 0 -%364 = OpFSub %15 %362 %363 -%365 = OpCompositeExtract %15 %188 1 -%366 = OpCompositeExtract %15 %189 1 -%367 = OpFSub %15 %365 %366 -%368 = OpCompositeExtract %15 %188 2 -%369 = OpCompositeExtract %15 %189 2 -%370 = OpFSub %15 %368 %369 -%361 = OpCompositeConstruct %27 %364 %367 %370 -%371 = OpMatrixTimesScalar %27 %190 %3 -%372 = OpMatrixTimesScalar %27 %191 %66 -%373 = OpCompositeConstruct %10 %3 %3 %3 %3 -%374 = OpMatrixTimesVector %15 %192 %373 -%375 = OpCompositeConstruct %15 %66 %66 %66 -%376 = OpVectorTimesMatrix %10 %375 %193 -%377 = OpMatrixTimesMatrix %27 %194 %195 +%349 = OpFRem %14 %347 %348 +%350 = OpCompositeConstruct %14 %3 %3 +%351 = OpCompositeConstruct %14 %66 %66 +%352 = OpFRem %14 %351 %350 +OpBranch %264 +%264 = OpLabel +%354 = OpCompositeExtract %15 %186 0 +%355 = OpCompositeExtract %15 %187 0 +%356 = OpFAdd %15 %354 %355 +%357 = OpCompositeExtract %15 %186 1 +%358 = OpCompositeExtract %15 %187 1 +%359 = OpFAdd %15 %357 %358 +%360 = OpCompositeExtract %15 %186 2 +%361 = OpCompositeExtract %15 %187 2 +%362 = OpFAdd %15 %360 %361 +%353 = OpCompositeConstruct %27 %356 %359 %362 +%364 = OpCompositeExtract %15 %188 0 +%365 = OpCompositeExtract %15 %189 0 +%366 = OpFSub %15 %364 %365 +%367 = OpCompositeExtract %15 %188 1 +%368 = OpCompositeExtract %15 %189 1 +%369 = OpFSub %15 %367 %368 +%370 = OpCompositeExtract %15 %188 2 +%371 = OpCompositeExtract %15 %189 2 +%372 = OpFSub %15 %370 %371 +%363 = OpCompositeConstruct %27 %366 %369 %372 +%373 = OpMatrixTimesScalar %27 %190 %3 +%374 = OpMatrixTimesScalar %27 %191 %66 +%375 = OpCompositeConstruct %10 %3 %3 %3 %3 +%376 = OpMatrixTimesVector %15 %192 %375 +%377 = OpCompositeConstruct %15 %66 %66 %66 +%378 = OpVectorTimesMatrix %10 %377 %193 +%379 = OpMatrixTimesMatrix %27 %194 %195 OpReturn OpFunctionEnd -%379 = OpFunction %2 None %165 -%378 = OpLabel -OpBranch %380 +%381 = OpFunction %2 None %165 %380 = OpLabel -%381 = OpNot %8 %7 -%382 = OpNot %20 %185 -%383 = OpCompositeConstruct %197 %7 %7 -%384 = OpNot %197 %383 -%385 = OpCompositeConstruct %208 %185 %185 %185 -%386 = OpNot %208 %385 -%387 = OpBitwiseOr %8 %70 %7 -%388 = OpBitwiseOr %20 %184 %185 -%389 = OpCompositeConstruct %197 %70 %70 -%390 = OpCompositeConstruct %197 %7 %7 -%391 = OpBitwiseOr %197 %389 %390 -%392 = OpCompositeConstruct %208 %184 %184 %184 -%393 = OpCompositeConstruct %208 %185 %185 %185 -%394 = OpBitwiseOr %208 %392 %393 -%395 = OpBitwiseAnd %8 %70 %7 -%396 = OpBitwiseAnd %20 %184 %185 -%397 = OpCompositeConstruct %197 %70 %70 -%398 = OpCompositeConstruct %197 %7 %7 -%399 = OpBitwiseAnd %197 %397 %398 -%400 = OpCompositeConstruct %208 %184 %184 %184 -%401 = OpCompositeConstruct %208 %185 %185 %185 -%402 = OpBitwiseAnd %208 %400 %401 -%403 = OpBitwiseXor %8 %70 %7 -%404 = OpBitwiseXor %20 %184 %185 -%405 = OpCompositeConstruct %197 %70 %70 -%406 = OpCompositeConstruct %197 %7 %7 -%407 = OpBitwiseXor %197 %405 %406 -%408 = OpCompositeConstruct %208 %184 %184 %184 -%409 = OpCompositeConstruct %208 %185 %185 %185 -%410 = OpBitwiseXor %208 %408 %409 -%411 = OpShiftLeftLogical %8 %70 %185 -%412 = OpShiftLeftLogical %20 %184 %185 -%413 = OpCompositeConstruct %197 %70 %70 -%414 = OpCompositeConstruct %21 %185 %185 -%415 = OpShiftLeftLogical %197 %413 %414 -%416 = OpCompositeConstruct %208 %184 %184 %184 -%417 = OpCompositeConstruct %208 %185 %185 %185 -%418 = OpShiftLeftLogical %208 %416 %417 -%419 = OpShiftRightArithmetic %8 %70 %185 -%420 = OpShiftRightLogical %20 %184 %185 -%421 = OpCompositeConstruct %197 %70 %70 -%422 = OpCompositeConstruct %21 %185 %185 -%423 = OpShiftRightArithmetic %197 %421 %422 -%424 = OpCompositeConstruct %208 %184 %184 %184 -%425 = OpCompositeConstruct %208 %185 %185 %185 -%426 = OpShiftRightLogical %208 %424 %425 +OpBranch %382 +%382 = OpLabel +%383 = OpNot %8 %7 +%384 = OpNot %20 %185 +%385 = OpCompositeConstruct %197 %7 %7 +%386 = OpNot %197 %385 +%387 = OpCompositeConstruct %208 %185 %185 %185 +%388 = OpNot %208 %387 +%389 = OpBitwiseOr %8 %70 %7 +%390 = OpBitwiseOr %20 %184 %185 +%391 = OpCompositeConstruct %197 %70 %70 +%392 = OpCompositeConstruct %197 %7 %7 +%393 = OpBitwiseOr %197 %391 %392 +%394 = OpCompositeConstruct %208 %184 %184 %184 +%395 = OpCompositeConstruct %208 %185 %185 %185 +%396 = OpBitwiseOr %208 %394 %395 +%397 = OpBitwiseAnd %8 %70 %7 +%398 = OpBitwiseAnd %20 %184 %185 +%399 = OpCompositeConstruct %197 %70 %70 +%400 = OpCompositeConstruct %197 %7 %7 +%401 = OpBitwiseAnd %197 %399 %400 +%402 = OpCompositeConstruct %208 %184 %184 %184 +%403 = OpCompositeConstruct %208 %185 %185 %185 +%404 = OpBitwiseAnd %208 %402 %403 +%405 = OpBitwiseXor %8 %70 %7 +%406 = OpBitwiseXor %20 %184 %185 +%407 = OpCompositeConstruct %197 %70 %70 +%408 = OpCompositeConstruct %197 %7 %7 +%409 = OpBitwiseXor %197 %407 %408 +%410 = OpCompositeConstruct %208 %184 %184 %184 +%411 = OpCompositeConstruct %208 %185 %185 %185 +%412 = OpBitwiseXor %208 %410 %411 +%413 = OpShiftLeftLogical %8 %70 %185 +%414 = OpShiftLeftLogical %20 %184 %185 +%415 = OpCompositeConstruct %197 %70 %70 +%416 = OpCompositeConstruct %21 %185 %185 +%417 = OpShiftLeftLogical %197 %415 %416 +%418 = OpCompositeConstruct %208 %184 %184 %184 +%419 = OpCompositeConstruct %208 %185 %185 %185 +%420 = OpShiftLeftLogical %208 %418 %419 +%421 = OpShiftRightArithmetic %8 %70 %185 +%422 = OpShiftRightLogical %20 %184 %185 +%423 = OpCompositeConstruct %197 %70 %70 +%424 = OpCompositeConstruct %21 %185 %185 +%425 = OpShiftRightArithmetic %197 %423 %424 +%426 = OpCompositeConstruct %208 %184 %184 %184 +%427 = OpCompositeConstruct %208 %185 %185 %185 +%428 = OpShiftRightLogical %208 %426 %427 OpReturn OpFunctionEnd -%428 = OpFunction %2 None %165 -%427 = OpLabel -OpBranch %429 +%430 = OpFunction %2 None %165 %429 = OpLabel -%430 = OpIEqual %13 %70 %7 -%431 = OpIEqual %13 %184 %185 -%432 = OpFOrdEqual %13 %66 %3 -%433 = OpCompositeConstruct %197 %70 %70 -%434 = OpCompositeConstruct %197 %7 %7 -%435 = OpIEqual %168 %433 %434 -%436 = OpCompositeConstruct %208 %184 %184 %184 -%437 = OpCompositeConstruct %208 %185 %185 %185 -%438 = OpIEqual %16 %436 %437 -%439 = OpCompositeConstruct %10 %66 %66 %66 %66 -%440 = OpCompositeConstruct %10 %3 %3 %3 %3 -%441 = OpFOrdEqual %12 %439 %440 -%442 = OpINotEqual %13 %70 %7 -%443 = OpINotEqual %13 %184 %185 -%444 = OpFOrdNotEqual %13 %66 %3 -%445 = OpCompositeConstruct %197 %70 %70 -%446 = OpCompositeConstruct %197 %7 %7 -%447 = OpINotEqual %168 %445 %446 -%448 = OpCompositeConstruct %208 %184 %184 %184 -%449 = OpCompositeConstruct %208 %185 %185 %185 -%450 = OpINotEqual %16 %448 %449 -%451 = OpCompositeConstruct %10 %66 %66 %66 %66 -%452 = OpCompositeConstruct %10 %3 %3 %3 %3 -%453 = OpFOrdNotEqual %12 %451 %452 -%454 = OpSLessThan %13 %70 %7 -%455 = OpULessThan %13 %184 %185 -%456 = OpFOrdLessThan %13 %66 %3 -%457 = OpCompositeConstruct %197 %70 %70 -%458 = OpCompositeConstruct %197 %7 %7 -%459 = OpSLessThan %168 %457 %458 -%460 = OpCompositeConstruct %208 %184 %184 %184 -%461 = OpCompositeConstruct %208 %185 %185 %185 -%462 = OpULessThan %16 %460 %461 -%463 = OpCompositeConstruct %10 %66 %66 %66 %66 -%464 = OpCompositeConstruct %10 %3 %3 %3 %3 -%465 = OpFOrdLessThan %12 %463 %464 -%466 = OpSLessThanEqual %13 %70 %7 -%467 = OpULessThanEqual %13 %184 %185 -%468 = OpFOrdLessThanEqual %13 %66 %3 -%469 = OpCompositeConstruct %197 %70 %70 -%470 = OpCompositeConstruct %197 %7 %7 -%471 = OpSLessThanEqual %168 %469 %470 -%472 = OpCompositeConstruct %208 %184 %184 %184 -%473 = OpCompositeConstruct %208 %185 %185 %185 -%474 = OpULessThanEqual %16 %472 %473 -%475 = OpCompositeConstruct %10 %66 %66 %66 %66 -%476 = OpCompositeConstruct %10 %3 %3 %3 %3 -%477 = OpFOrdLessThanEqual %12 %475 %476 -%478 = OpSGreaterThan %13 %70 %7 -%479 = OpUGreaterThan %13 %184 %185 -%480 = OpFOrdGreaterThan %13 %66 %3 -%481 = OpCompositeConstruct %197 %70 %70 -%482 = OpCompositeConstruct %197 %7 %7 -%483 = OpSGreaterThan %168 %481 %482 -%484 = OpCompositeConstruct %208 %184 %184 %184 -%485 = OpCompositeConstruct %208 %185 %185 %185 -%486 = OpUGreaterThan %16 %484 %485 -%487 = OpCompositeConstruct %10 %66 %66 %66 %66 -%488 = OpCompositeConstruct %10 %3 %3 %3 %3 -%489 = OpFOrdGreaterThan %12 %487 %488 -%490 = OpSGreaterThanEqual %13 %70 %7 -%491 = OpUGreaterThanEqual %13 %184 %185 -%492 = OpFOrdGreaterThanEqual %13 %66 %3 -%493 = OpCompositeConstruct %197 %70 %70 -%494 = OpCompositeConstruct %197 %7 %7 -%495 = OpSGreaterThanEqual %168 %493 %494 -%496 = OpCompositeConstruct %208 %184 %184 %184 -%497 = OpCompositeConstruct %208 %185 %185 %185 -%498 = OpUGreaterThanEqual %16 %496 %497 -%499 = OpCompositeConstruct %10 %66 %66 %66 %66 -%500 = OpCompositeConstruct %10 %3 %3 %3 %3 -%501 = OpFOrdGreaterThanEqual %12 %499 %500 +OpBranch %431 +%431 = OpLabel +%432 = OpIEqual %13 %70 %7 +%433 = OpIEqual %13 %184 %185 +%434 = OpFOrdEqual %13 %66 %3 +%435 = OpCompositeConstruct %197 %70 %70 +%436 = OpCompositeConstruct %197 %7 %7 +%437 = OpIEqual %168 %435 %436 +%438 = OpCompositeConstruct %208 %184 %184 %184 +%439 = OpCompositeConstruct %208 %185 %185 %185 +%440 = OpIEqual %16 %438 %439 +%441 = OpCompositeConstruct %10 %66 %66 %66 %66 +%442 = OpCompositeConstruct %10 %3 %3 %3 %3 +%443 = OpFOrdEqual %12 %441 %442 +%444 = OpINotEqual %13 %70 %7 +%445 = OpINotEqual %13 %184 %185 +%446 = OpFOrdNotEqual %13 %66 %3 +%447 = OpCompositeConstruct %197 %70 %70 +%448 = OpCompositeConstruct %197 %7 %7 +%449 = OpINotEqual %168 %447 %448 +%450 = OpCompositeConstruct %208 %184 %184 %184 +%451 = OpCompositeConstruct %208 %185 %185 %185 +%452 = OpINotEqual %16 %450 %451 +%453 = OpCompositeConstruct %10 %66 %66 %66 %66 +%454 = OpCompositeConstruct %10 %3 %3 %3 %3 +%455 = OpFOrdNotEqual %12 %453 %454 +%456 = OpSLessThan %13 %70 %7 +%457 = OpULessThan %13 %184 %185 +%458 = OpFOrdLessThan %13 %66 %3 +%459 = OpCompositeConstruct %197 %70 %70 +%460 = OpCompositeConstruct %197 %7 %7 +%461 = OpSLessThan %168 %459 %460 +%462 = OpCompositeConstruct %208 %184 %184 %184 +%463 = OpCompositeConstruct %208 %185 %185 %185 +%464 = OpULessThan %16 %462 %463 +%465 = OpCompositeConstruct %10 %66 %66 %66 %66 +%466 = OpCompositeConstruct %10 %3 %3 %3 %3 +%467 = OpFOrdLessThan %12 %465 %466 +%468 = OpSLessThanEqual %13 %70 %7 +%469 = OpULessThanEqual %13 %184 %185 +%470 = OpFOrdLessThanEqual %13 %66 %3 +%471 = OpCompositeConstruct %197 %70 %70 +%472 = OpCompositeConstruct %197 %7 %7 +%473 = OpSLessThanEqual %168 %471 %472 +%474 = OpCompositeConstruct %208 %184 %184 %184 +%475 = OpCompositeConstruct %208 %185 %185 %185 +%476 = OpULessThanEqual %16 %474 %475 +%477 = OpCompositeConstruct %10 %66 %66 %66 %66 +%478 = OpCompositeConstruct %10 %3 %3 %3 %3 +%479 = OpFOrdLessThanEqual %12 %477 %478 +%480 = OpSGreaterThan %13 %70 %7 +%481 = OpUGreaterThan %13 %184 %185 +%482 = OpFOrdGreaterThan %13 %66 %3 +%483 = OpCompositeConstruct %197 %70 %70 +%484 = OpCompositeConstruct %197 %7 %7 +%485 = OpSGreaterThan %168 %483 %484 +%486 = OpCompositeConstruct %208 %184 %184 %184 +%487 = OpCompositeConstruct %208 %185 %185 %185 +%488 = OpUGreaterThan %16 %486 %487 +%489 = OpCompositeConstruct %10 %66 %66 %66 %66 +%490 = OpCompositeConstruct %10 %3 %3 %3 %3 +%491 = OpFOrdGreaterThan %12 %489 %490 +%492 = OpSGreaterThanEqual %13 %70 %7 +%493 = OpUGreaterThanEqual %13 %184 %185 +%494 = OpFOrdGreaterThanEqual %13 %66 %3 +%495 = OpCompositeConstruct %197 %70 %70 +%496 = OpCompositeConstruct %197 %7 %7 +%497 = OpSGreaterThanEqual %168 %495 %496 +%498 = OpCompositeConstruct %208 %184 %184 %184 +%499 = OpCompositeConstruct %208 %185 %185 %185 +%500 = OpUGreaterThanEqual %16 %498 %499 +%501 = OpCompositeConstruct %10 %66 %66 %66 %66 +%502 = OpCompositeConstruct %10 %3 %3 %3 %3 +%503 = OpFOrdGreaterThanEqual %12 %501 %502 OpReturn OpFunctionEnd -%509 = OpFunction %2 None %165 -%508 = OpLabel -%502 = OpVariable %503 Function %504 -%505 = OpVariable %506 Function %507 -OpBranch %511 -%511 = OpLabel -OpStore %502 %7 -%512 = OpLoad %8 %502 -%513 = OpIAdd %8 %512 %7 -OpStore %502 %513 -%514 = OpLoad %8 %502 -%515 = OpISub %8 %514 %7 -OpStore %502 %515 -%516 = OpLoad %8 %502 -%517 = OpLoad %8 %502 -%518 = OpIMul %8 %517 %516 -OpStore %502 %518 -%519 = OpLoad %8 %502 -%520 = OpLoad %8 %502 -%521 = OpSDiv %8 %520 %519 -OpStore %502 %521 -%522 = OpLoad %8 %502 -%523 = OpSRem %8 %522 %7 -OpStore %502 %523 -%524 = OpLoad %8 %502 -%525 = OpBitwiseAnd %8 %524 %39 -OpStore %502 %525 -%526 = OpLoad %8 %502 -%527 = OpBitwiseOr %8 %526 %39 -OpStore %502 %527 -%528 = OpLoad %8 %502 -%529 = OpBitwiseXor %8 %528 %39 -OpStore %502 %529 -%530 = OpLoad %8 %502 -%531 = OpShiftLeftLogical %8 %530 %184 -OpStore %502 %531 -%532 = OpLoad %8 %502 -%533 = OpShiftRightArithmetic %8 %532 %185 -OpStore %502 %533 -%534 = OpLoad %8 %502 -%535 = OpIAdd %8 %534 %7 -OpStore %502 %535 -%536 = OpLoad %8 %502 -%537 = OpISub %8 %536 %7 -OpStore %502 %537 -OpStore %505 %510 -%539 = OpAccessChain %538 %505 %185 -%540 = OpLoad %8 %539 -%541 = OpIAdd %8 %540 %7 -%542 = OpAccessChain %538 %505 %185 -OpStore %542 %541 -%543 = OpAccessChain %538 %505 %185 -%544 = OpLoad %8 %543 -%545 = OpISub %8 %544 %7 -%546 = OpAccessChain %538 %505 %185 -OpStore %546 %545 +%511 = OpFunction %2 None %165 +%510 = OpLabel +%504 = OpVariable %505 Function %506 +%507 = OpVariable %508 Function %509 +OpBranch %513 +%513 = OpLabel +OpStore %504 %7 +%514 = OpLoad %8 %504 +%515 = OpIAdd %8 %514 %7 +OpStore %504 %515 +%516 = OpLoad %8 %504 +%517 = OpISub %8 %516 %7 +OpStore %504 %517 +%518 = OpLoad %8 %504 +%519 = OpLoad %8 %504 +%520 = OpIMul %8 %519 %518 +OpStore %504 %520 +%521 = OpLoad %8 %504 +%522 = OpLoad %8 %504 +%523 = OpSDiv %8 %522 %521 +OpStore %504 %523 +%524 = OpLoad %8 %504 +%525 = OpSRem %8 %524 %7 +OpStore %504 %525 +%526 = OpLoad %8 %504 +%527 = OpBitwiseAnd %8 %526 %39 +OpStore %504 %527 +%528 = OpLoad %8 %504 +%529 = OpBitwiseOr %8 %528 %39 +OpStore %504 %529 +%530 = OpLoad %8 %504 +%531 = OpBitwiseXor %8 %530 %39 +OpStore %504 %531 +%532 = OpLoad %8 %504 +%533 = OpShiftLeftLogical %8 %532 %184 +OpStore %504 %533 +%534 = OpLoad %8 %504 +%535 = OpShiftRightArithmetic %8 %534 %185 +OpStore %504 %535 +%536 = OpLoad %8 %504 +%537 = OpIAdd %8 %536 %7 +OpStore %504 %537 +%538 = OpLoad %8 %504 +%539 = OpISub %8 %538 %7 +OpStore %504 %539 +OpStore %507 %512 +%541 = OpAccessChain %540 %507 %185 +%542 = OpLoad %8 %541 +%543 = OpIAdd %8 %542 %7 +%544 = OpAccessChain %540 %507 %185 +OpStore %544 %543 +%545 = OpAccessChain %540 %507 %185 +%546 = OpLoad %8 %545 +%547 = OpISub %8 %546 %7 +%548 = OpAccessChain %540 %507 %185 +OpStore %548 %547 OpReturn OpFunctionEnd -%548 = OpFunction %2 None %165 -%547 = OpLabel -OpBranch %557 -%557 = OpLabel -%558 = OpSNegate %8 %550 -%559 = OpSNegate %8 %551 +%550 = OpFunction %2 None %165 +%549 = OpLabel +OpBranch %559 +%559 = OpLabel %560 = OpSNegate %8 %552 -%561 = OpSNegate %8 %560 -%562 = OpSNegate %8 %553 +%561 = OpSNegate %8 %553 +%562 = OpSNegate %8 %554 %563 = OpSNegate %8 %562 -%564 = OpSNegate %8 %554 +%564 = OpSNegate %8 %555 %565 = OpSNegate %8 %564 -%566 = OpSNegate %8 %565 +%566 = OpSNegate %8 %556 %567 = OpSNegate %8 %566 -%568 = OpSNegate %8 %555 +%568 = OpSNegate %8 %567 %569 = OpSNegate %8 %568 -%570 = OpSNegate %8 %569 +%570 = OpSNegate %8 %557 %571 = OpSNegate %8 %570 -%572 = OpSNegate %8 %556 +%572 = OpSNegate %8 %571 %573 = OpSNegate %8 %572 -%574 = OpSNegate %8 %573 +%574 = OpSNegate %8 %558 %575 = OpSNegate %8 %574 +%576 = OpSNegate %8 %575 +%577 = OpSNegate %8 %576 OpReturn OpFunctionEnd -%577 = OpFunction %2 None %165 -%576 = OpLabel -OpBranch %578 +%579 = OpFunction %2 None %165 %578 = OpLabel -%579 = OpFunctionCall %10 %36 -%580 = OpFunctionCall %10 %65 -%581 = OpVectorShuffle %15 %31 %31 0 1 2 -%582 = OpFunctionCall %15 %105 %581 -%583 = OpFunctionCall %4 %116 -%584 = OpFunctionCall %2 %164 -%585 = OpFunctionCall %2 %182 -%586 = OpFunctionCall %2 %379 -%587 = OpFunctionCall %2 %428 -%588 = OpFunctionCall %2 %509 +OpBranch %580 +%580 = OpLabel +%581 = OpFunctionCall %10 %36 +%582 = OpFunctionCall %10 %65 +%583 = OpVectorShuffle %15 %31 %31 0 1 2 +%584 = OpFunctionCall %15 %105 %583 +%585 = OpFunctionCall %4 %116 +%586 = OpFunctionCall %2 %164 +%587 = OpFunctionCall %2 %182 +%588 = OpFunctionCall %2 %381 +%589 = OpFunctionCall %2 %430 +%590 = OpFunctionCall %2 %511 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl index 63e83ddb9..365fa3470 100644 --- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl @@ -47,8 +47,6 @@ fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; - _ = (&global.ViewProj); - _ = (&global_1.Model); main_1(); let _e21 = v_Uv; let _e23 = gl_Position; diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl index 5447e712c..f7932979b 100644 --- a/tests/out/wgsl/210-bevy-shader-vert.wgsl +++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl @@ -48,7 +48,6 @@ fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec Vertex_Position_1 = Vertex_Position; Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; - _ = (&global.ViewProj); main_1(); let _e23 = v_Position; let _e25 = v_Normal; diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl index ffd05885e..e92cf8127 100644 --- a/tests/out/wgsl/246-collatz-comp.wgsl +++ b/tests/out/wgsl/246-collatz-comp.wgsl @@ -10,7 +10,6 @@ fn collatz_iterations(n: u32) -> u32 { var n_1: u32; var i: u32; - _ = (&global.indices); n_1 = n; i = u32(0); loop { @@ -19,7 +18,6 @@ fn collatz_iterations(n: u32) -> u32 { break; } { - _ = n_1; let _e14 = n_1; let _e15 = f32(_e14); let _e17 = f32(2); @@ -49,7 +47,6 @@ fn main_1() { index = _e3.x; let _e6 = index; let _e8 = index; - _ = global.indices[_e8]; let _e11 = index; let _e13 = global.indices[_e11]; let _e14 = collatz_iterations(_e13); diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl index fdb5462d4..d749d5a1f 100644 --- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl +++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl @@ -36,8 +36,6 @@ fn main_1() { fn main(@location(0) position: vec2, @location(1) color: vec4) -> VertexOutput { position_1 = position; color_1 = color; - _ = (&global.view_matrix); - _ = (&global_1.world_matrix); main_1(); let _e15 = frag_color; let _e17 = gl_Position; diff --git a/tests/out/wgsl/900-implicit-conversions-frag.wgsl b/tests/out/wgsl/900-implicit-conversions-frag.wgsl index 97ff5a4fe..923e38722 100644 --- a/tests/out/wgsl/900-implicit-conversions-frag.wgsl +++ b/tests/out/wgsl/900-implicit-conversions-frag.wgsl @@ -57,7 +57,6 @@ fn implicit_dims_3(v_6: vec4) { fn main_1() { exact_1(1); implicit(f32(1u)); - _ = vec3(1); implicit_dims_2(vec3(vec3(1))); return; } diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index d7358b267..c8b87516f 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -43,18 +43,18 @@ fn test_matrix_within_struct_accesses() { idx = 1; let _e2 = idx; idx = (_e2 - 1); - _ = baz.m; - _ = baz.m[0]; + let l0_ = baz.m; + let l1_ = baz.m[0]; let _e15 = idx; - _ = baz.m[_e15]; - _ = baz.m[0][1]; + let l2_ = baz.m[_e15]; + let l3_ = baz.m[0][1]; let _e29 = idx; - _ = baz.m[0][_e29]; + let l4_ = baz.m[0][_e29]; let _e34 = idx; - _ = baz.m[_e34][1]; + let l5_ = baz.m[_e34][1]; let _e41 = idx; let _e43 = idx; - _ = baz.m[_e41][_e43]; + let l6_ = baz.m[_e41][_e43]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); let _e55 = idx; idx = (_e55 + 1); @@ -80,19 +80,19 @@ fn test_matrix_within_array_within_struct_accesses() { idx_1 = 1; let _e2 = idx_1; idx_1 = (_e2 - 1); - _ = nested_mat_cx2_.am; - _ = nested_mat_cx2_.am[0]; - _ = nested_mat_cx2_.am[0][0]; + let l0_1 = nested_mat_cx2_.am; + let l1_1 = nested_mat_cx2_.am[0]; + let l2_1 = nested_mat_cx2_.am[0][0]; let _e24 = idx_1; - _ = nested_mat_cx2_.am[0][_e24]; - _ = nested_mat_cx2_.am[0][0][1]; + let l3_1 = nested_mat_cx2_.am[0][_e24]; + let l4_1 = nested_mat_cx2_.am[0][0][1]; let _e42 = idx_1; - _ = nested_mat_cx2_.am[0][0][_e42]; + let l5_1 = nested_mat_cx2_.am[0][0][_e42]; let _e49 = idx_1; - _ = nested_mat_cx2_.am[0][_e49][1]; + let l6_1 = nested_mat_cx2_.am[0][_e49][1]; let _e58 = idx_1; let _e60 = idx_1; - _ = nested_mat_cx2_.am[0][_e58][_e60]; + let l7_ = nested_mat_cx2_.am[0][_e58][_e60]; t_1 = MatCx2InArray(array, 2>()); let _e66 = idx_1; idx_1 = (_e66 + 1); diff --git a/tests/out/wgsl/array-in-ctor.wgsl b/tests/out/wgsl/array-in-ctor.wgsl index 290442d6f..8c17731f0 100644 --- a/tests/out/wgsl/array-in-ctor.wgsl +++ b/tests/out/wgsl/array-in-ctor.wgsl @@ -7,5 +7,5 @@ var ah: Ah; @compute @workgroup_size(1, 1, 1) fn cs_main() { - _ = ah; + let ah_1 = ah; } diff --git a/tests/out/wgsl/atomicOps.wgsl b/tests/out/wgsl/atomicOps.wgsl index 86f877666..934a7b795 100644 --- a/tests/out/wgsl/atomicOps.wgsl +++ b/tests/out/wgsl/atomicOps.wgsl @@ -24,14 +24,14 @@ fn cs_main(@builtin(local_invocation_id) id: vec3) { atomicStore((&workgroup_struct.atomic_scalar), 1u); atomicStore((&workgroup_struct.atomic_arr[1]), 1); workgroupBarrier(); - _ = atomicLoad((&storage_atomic_scalar)); - _ = atomicLoad((&storage_atomic_arr[1])); - _ = atomicLoad((&storage_struct.atomic_scalar)); - _ = atomicLoad((&storage_struct.atomic_arr[1])); - _ = atomicLoad((&workgroup_atomic_scalar)); - _ = atomicLoad((&workgroup_atomic_arr[1])); - _ = atomicLoad((&workgroup_struct.atomic_scalar)); - _ = atomicLoad((&workgroup_struct.atomic_arr[1])); + let l0_ = atomicLoad((&storage_atomic_scalar)); + let l1_ = atomicLoad((&storage_atomic_arr[1])); + let l2_ = atomicLoad((&storage_struct.atomic_scalar)); + let l3_ = atomicLoad((&storage_struct.atomic_arr[1])); + let l4_ = atomicLoad((&workgroup_atomic_scalar)); + let l5_ = atomicLoad((&workgroup_atomic_arr[1])); + let l6_ = atomicLoad((&workgroup_struct.atomic_scalar)); + let l7_ = atomicLoad((&workgroup_struct.atomic_arr[1])); workgroupBarrier(); let _e59 = atomicAdd((&storage_atomic_scalar), 1u); let _e64 = atomicAdd((&storage_atomic_arr[1]), 1); diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 9f55e5f16..41fc6e399 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -101,17 +101,6 @@ fn pow5_(x: f32) -> f32 { var x_1: f32; var x2_: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); x_1 = x; let _e42 = x_1; let _e43 = x_1; @@ -129,17 +118,6 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 var smoothFactor: f32; var attenuation: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); distanceSquare_1 = distanceSquare; inverseRangeSquared_1 = inverseRangeSquared; let _e44 = distanceSquare_1; @@ -147,7 +125,6 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 factor = (_e44 * _e45); let _e49 = factor; let _e50 = factor; - _ = (1.0 - (_e49 * _e50)); let _e56 = factor; let _e57 = factor; smoothFactor = clamp((1.0 - (_e56 * _e57)), 0.0, 1.0); @@ -155,7 +132,6 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 let _e65 = smoothFactor; attenuation = (_e64 * _e65); let _e68 = attenuation; - _ = distanceSquare_1; let _e73 = distanceSquare_1; return ((_e68 * 1.0) / max(_e73, 0.001)); } @@ -168,17 +144,6 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { var k: f32; var d: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); roughness_1 = roughness; NoH_1 = NoH; let _e46 = NoH_1; @@ -208,17 +173,6 @@ fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { var lambdaL: f32; var v: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); roughness_3 = roughness_2; NoV_1 = NoV; NoL_1 = NoL; @@ -231,7 +185,6 @@ fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { let _e53 = NoV_1; let _e56 = NoV_1; let _e58 = a2_; - _ = (((_e51 - (_e52 * _e53)) * _e56) + _e58); let _e60 = NoV_1; let _e61 = a2_; let _e62 = NoV_1; @@ -244,7 +197,6 @@ fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { let _e75 = NoL_1; let _e78 = NoL_1; let _e80 = a2_; - _ = (((_e73 - (_e74 * _e75)) * _e78) + _e80); let _e82 = NoL_1; let _e83 = a2_; let _e84 = NoL_1; @@ -262,22 +214,10 @@ fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { var f90_1: f32; var VoH_1: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); f90_1 = f90_; VoH_1 = VoH; let _e45 = f90_1; let _e49 = VoH_1; - _ = (1.0 - _e49); let _e52 = VoH_1; let _e54 = pow5_((1.0 - _e52)); return (f0_ + ((vec3(_e45) - f0_) * _e54)); @@ -288,17 +228,6 @@ fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 { var f90_3: f32; var VoH_3: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); f0_2 = f0_1; f90_3 = f90_2; VoH_3 = VoH_2; @@ -306,7 +235,6 @@ fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 { let _e47 = f90_3; let _e48 = f0_2; let _e51 = VoH_3; - _ = (1.0 - _e51); let _e54 = VoH_3; let _e56 = pow5_((1.0 - _e54)); return (_e46 + ((_e47 - _e48) * _e56)); @@ -317,30 +245,11 @@ fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { var LoH_1: f32; var f90_4: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); f0_4 = f0_3; LoH_1 = LoH; - _ = f0_4; - _ = vec3((50.0 * 0.33)); let _e49 = f0_4; - _ = dot(_e49, vec3((50.0 * 0.33))); - _ = f0_4; - _ = vec3((50.0 * 0.33)); let _e62 = f0_4; f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33))), 0.0, 1.0); - _ = f0_4; - _ = f90_4; - _ = LoH_1; let _e75 = f0_4; let _e76 = f90_4; let _e77 = LoH_1; @@ -360,17 +269,6 @@ fn specular(f0_5: vec3, roughness_4: f32, h_1: vec3, NoV_2: f32, NoL_2 var V: f32; var F: vec3; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); f0_6 = f0_5; roughness_5 = roughness_4; NoV_3 = NoV_2; @@ -378,22 +276,15 @@ fn specular(f0_5: vec3, roughness_4: f32, h_1: vec3, NoV_2: f32, NoL_2 NoH_3 = NoH_2; LoH_3 = LoH_2; specularIntensity_1 = specularIntensity; - _ = roughness_5; - _ = NoH_3; let _e57 = roughness_5; let _e58 = NoH_3; let _e59 = D_GGX(_e57, _e58, h_1); D = _e59; - _ = roughness_5; - _ = NoV_3; - _ = NoL_3; let _e64 = roughness_5; let _e65 = NoV_3; let _e66 = NoL_3; let _e67 = V_SmithGGXCorrelated(_e64, _e65, _e66); V = _e67; - _ = f0_6; - _ = LoH_3; let _e71 = f0_6; let _e72 = LoH_3; let _e73 = fresnel(_e71, _e72); @@ -414,17 +305,6 @@ fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { var lightScatter: f32; var viewScatter: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); roughness_7 = roughness_6; NoV_5 = NoV_4; NoL_5 = NoL_4; @@ -433,14 +313,10 @@ fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { let _e52 = LoH_5; let _e54 = LoH_5; f90_5 = (0.5 + (((2.0 * _e50) * _e52) * _e54)); - _ = f90_5; - _ = NoL_5; let _e62 = f90_5; let _e63 = NoL_5; let _e64 = F_Schlick_1(1.0, _e62, _e63); lightScatter = _e64; - _ = f90_5; - _ = NoV_5; let _e70 = f90_5; let _e71 = NoV_5; let _e72 = F_Schlick_1(1.0, _e70, _e71); @@ -460,17 +336,6 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 var a004_: f32; var AB: vec2; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); f0_8 = f0_7; perceptual_roughness_1 = perceptual_roughness; NoV_7 = NoV_6; @@ -482,15 +347,11 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 r = ((vec4(_e62) * _e64) + _e66); let _e69 = r; let _e71 = r; - _ = (_e69.x * _e71.x); let _e76 = NoV_7; - _ = (-(9.28) * _e76); let _e80 = NoV_7; - _ = exp2((-(9.28) * _e80)); let _e83 = r; let _e85 = r; let _e90 = NoV_7; - _ = (-(9.28) * _e90); let _e94 = NoV_7; let _e98 = r; let _e101 = r; @@ -508,19 +369,7 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { var perceptualRoughness_1: f32; var clampedPerceptualRoughness: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); perceptualRoughness_1 = perceptualRoughness; - _ = perceptualRoughness_1; let _e45 = perceptualRoughness_1; clampedPerceptualRoughness = clamp(_e45, 0.089, 1.0); let _e50 = clampedPerceptualRoughness; @@ -531,17 +380,6 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { fn reinhard(color: vec3) -> vec3 { var color_1: vec3; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); color_1 = color; let _e42 = color_1; let _e45 = color_1; @@ -553,17 +391,6 @@ fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { var max_white_1: f32; var numerator: vec3; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); color_3 = color_2; max_white_1 = max_white; let _e44 = color_3; @@ -579,20 +406,7 @@ fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { fn luminance(v_1: vec3) -> f32 { var v_2: vec3; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); v_2 = v_1; - _ = v_2; - _ = vec3(0.2126, 0.7152, 0.0722); let _e47 = v_2; return dot(_e47, vec3(0.2126, 0.7152, 0.0722)); } @@ -602,20 +416,8 @@ fn change_luminance(c_in: vec3, l_out: f32) -> vec3 { var l_out_1: f32; var l_in: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); c_in_1 = c_in; l_out_1 = l_out; - _ = c_in_1; let _e45 = c_in_1; let _e46 = luminance(_e45); l_in = _e46; @@ -630,27 +432,13 @@ fn reinhard_luminance(color_4: vec3) -> vec3 { var l_old: f32; var l_new: f32; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); color_5 = color_4; - _ = color_5; let _e43 = color_5; let _e44 = luminance(_e43); l_old = _e44; let _e46 = l_old; let _e48 = l_old; l_new = (_e46 / (1.0 + _e48)); - _ = color_5; - _ = l_new; let _e54 = color_5; let _e55 = l_new; let _e56 = change_luminance(_e54, _e55); @@ -664,20 +452,8 @@ fn reinhard_extended_luminance(color_6: vec3, max_white_l: f32) -> vec3, max_white_l: f32) -> vec3, V_ var specular_1: vec3; var diffuse: vec3; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); light_1 = light; roughness_9 = roughness_8; NdotV_1 = NdotV; @@ -746,14 +509,10 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ let _e56 = light_1; let _e59 = v_WorldPosition_1; light_to_frag = (_e56.pos.xyz - _e59.xyz); - _ = light_to_frag; - _ = light_to_frag; let _e65 = light_to_frag; let _e66 = light_to_frag; distance_square = dot(_e65, _e66); - _ = distance_square; let _e70 = light_1; - _ = _e70.lightParams.x; let _e73 = distance_square; let _e74 = light_1; let _e77 = getDistanceAttenuation(_e73, _e74.lightParams.x); @@ -762,8 +521,6 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ a_1 = _e79; let _e81 = light_1; radius = _e81.lightParams.y; - _ = light_to_frag; - _ = R_1; let _e87 = light_to_frag; let _e88 = R_1; let _e90 = R_1; @@ -772,34 +529,18 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ let _e95 = light_to_frag; let _e96 = centerToRay; let _e97 = radius; - _ = centerToRay; - _ = centerToRay; let _e100 = centerToRay; let _e101 = centerToRay; - _ = dot(_e100, _e101); - _ = centerToRay; - _ = centerToRay; let _e105 = centerToRay; let _e106 = centerToRay; - _ = (_e97 * inverseSqrt(dot(_e105, _e106))); let _e112 = radius; - _ = centerToRay; - _ = centerToRay; let _e115 = centerToRay; let _e116 = centerToRay; - _ = dot(_e115, _e116); - _ = centerToRay; - _ = centerToRay; let _e120 = centerToRay; let _e121 = centerToRay; closestPoint = (_e95 + (_e96 * clamp((_e112 * inverseSqrt(dot(_e120, _e121))), 0.0, 1.0))); - _ = closestPoint; - _ = closestPoint; let _e133 = closestPoint; let _e134 = closestPoint; - _ = dot(_e133, _e134); - _ = closestPoint; - _ = closestPoint; let _e138 = closestPoint; let _e139 = closestPoint; LspecLengthInverse = inverseSqrt(dot(_e138, _e139)); @@ -807,7 +548,6 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ let _e144 = a_1; let _e145 = radius; let _e148 = LspecLengthInverse; - _ = (_e144 + ((_e145 * 0.5) * _e148)); let _e153 = a_1; let _e154 = radius; let _e157 = LspecLengthInverse; @@ -820,48 +560,24 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ L = (_e169 * _e170); let _e173 = L; let _e174 = V_2; - _ = (_e173 + _e174); let _e176 = L; let _e177 = V_2; H = normalize((_e176 + _e177)); - _ = N_1; - _ = L; let _e183 = N_1; let _e184 = L; - _ = dot(_e183, _e184); - _ = N_1; - _ = L; let _e190 = N_1; let _e191 = L; NoL_6 = clamp(dot(_e190, _e191), 0.0, 1.0); - _ = N_1; - _ = H; let _e199 = N_1; let _e200 = H; - _ = dot(_e199, _e200); - _ = N_1; - _ = H; let _e206 = N_1; let _e207 = H; NoH_4 = clamp(dot(_e206, _e207), 0.0, 1.0); - _ = L; - _ = H; let _e215 = L; let _e216 = H; - _ = dot(_e215, _e216); - _ = L; - _ = H; let _e222 = L; let _e223 = H; LoH_6 = clamp(dot(_e222, _e223), 0.0, 1.0); - _ = F0_1; - _ = roughness_9; - _ = H; - _ = NdotV_1; - _ = NoL_6; - _ = NoH_4; - _ = LoH_6; - _ = specularIntensity_2; let _e237 = F0_1; let _e238 = roughness_9; let _e239 = H; @@ -872,50 +588,29 @@ fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3, V_ let _e244 = specularIntensity_2; let _e245 = specular(_e237, _e238, _e239, _e240, _e241, _e242, _e243, _e244); specular_1 = _e245; - _ = light_to_frag; let _e248 = light_to_frag; L = normalize(_e248); let _e250 = L; let _e251 = V_2; - _ = (_e250 + _e251); let _e253 = L; let _e254 = V_2; H = normalize((_e253 + _e254)); - _ = N_1; - _ = L; let _e259 = N_1; let _e260 = L; - _ = dot(_e259, _e260); - _ = N_1; - _ = L; let _e266 = N_1; let _e267 = L; NoL_6 = clamp(dot(_e266, _e267), 0.0, 1.0); - _ = N_1; - _ = H; let _e274 = N_1; let _e275 = H; - _ = dot(_e274, _e275); - _ = N_1; - _ = H; let _e281 = N_1; let _e282 = H; NoH_4 = clamp(dot(_e281, _e282), 0.0, 1.0); - _ = L; - _ = H; let _e289 = L; let _e290 = H; - _ = dot(_e289, _e290); - _ = L; - _ = H; let _e296 = L; let _e297 = H; LoH_6 = clamp(dot(_e296, _e297), 0.0, 1.0); let _e302 = diffuseColor_1; - _ = roughness_9; - _ = NdotV_1; - _ = NoL_6; - _ = LoH_6; let _e307 = roughness_9; let _e308 = NdotV_1; let _e309 = NoL_6; @@ -948,17 +643,6 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: var specularIntensity_3: f32; var specular_2: vec3; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); light_3 = light_2; roughness_11 = roughness_10; NdotV_3 = NdotV_2; @@ -971,45 +655,25 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: incident_light = _e56.direction.xyz; let _e60 = incident_light; let _e61 = view_1; - _ = (_e60 + _e61); let _e63 = incident_light; let _e64 = view_1; half_vector = normalize((_e63 + _e64)); - _ = normal_1; - _ = incident_light; let _e70 = normal_1; let _e71 = incident_light; - _ = dot(_e70, _e71); - _ = normal_1; - _ = incident_light; let _e77 = normal_1; let _e78 = incident_light; NoL_7 = clamp(dot(_e77, _e78), 0.0, 1.0); - _ = normal_1; - _ = half_vector; let _e86 = normal_1; let _e87 = half_vector; - _ = dot(_e86, _e87); - _ = normal_1; - _ = half_vector; let _e93 = normal_1; let _e94 = half_vector; NoH_5 = clamp(dot(_e93, _e94), 0.0, 1.0); - _ = incident_light; - _ = half_vector; let _e102 = incident_light; let _e103 = half_vector; - _ = dot(_e102, _e103); - _ = incident_light; - _ = half_vector; let _e109 = incident_light; let _e110 = half_vector; LoH_7 = clamp(dot(_e109, _e110), 0.0, 1.0); let _e116 = diffuseColor_3; - _ = roughness_11; - _ = NdotV_3; - _ = NoL_7; - _ = LoH_7; let _e121 = roughness_11; let _e122 = NdotV_3; let _e123 = NoL_7; @@ -1017,14 +681,6 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: let _e125 = Fd_Burley(_e121, _e122, _e123, _e124); diffuse_1 = (_e116 * _e125); specularIntensity_3 = 1.0; - _ = F0_3; - _ = roughness_11; - _ = half_vector; - _ = NdotV_3; - _ = NoL_7; - _ = NoH_5; - _ = LoH_7; - _ = specularIntensity_3; let _e138 = F0_3; let _e139 = roughness_11; let _e140 = half_vector; @@ -1068,15 +724,12 @@ fn main_1() { var diffuse_ambient: vec3; var specular_ambient: vec3; - _ = (&global.ViewProj); let _e40 = global_3.base_color; output_color = _e40; let _e42 = output_color; - _ = v_Uv_1; let _e44 = v_Uv_1; let _e45 = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, _e44); output_color = (_e42 * _e45); - _ = v_Uv_1; let _e48 = v_Uv_1; let _e49 = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, _e48); metallic_roughness = _e49; @@ -1086,19 +739,14 @@ fn main_1() { let _e56 = global_4.perceptual_roughness; let _e57 = metallic_roughness; perceptual_roughness_2 = (_e56 * _e57.y); - _ = perceptual_roughness_2; let _e62 = perceptual_roughness_2; let _e63 = perceptualRoughnessToRoughness(_e62); roughness_12 = _e63; - _ = v_WorldNormal_1; let _e66 = v_WorldNormal_1; N_2 = normalize(_e66); let _e69 = v_WorldTangent_1; - _ = _e69.xyz; let _e71 = v_WorldTangent_1; T = normalize(_e71.xyz); - _ = N_2; - _ = T; let _e77 = N_2; let _e78 = T; let _e80 = v_WorldTangent_1; @@ -1138,24 +786,18 @@ fn main_1() { let _e105 = N_2; TBN = mat3x3(vec3(_e103.x, _e103.y, _e103.z), vec3(_e104.x, _e104.y, _e104.z), vec3(_e105.x, _e105.y, _e105.z)); let _e120 = TBN; - _ = v_Uv_1; let _e122 = v_Uv_1; let _e123 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e122); - _ = ((_e123.xyz * 2.0) - vec3(1.0)); - _ = v_Uv_1; let _e131 = v_Uv_1; let _e132 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e131); N_2 = (_e120 * normalize(((_e132.xyz * 2.0) - vec3(1.0)))); - _ = v_Uv_1; let _e142 = v_Uv_1; let _e143 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e142); occlusion = _e143.x; let _e146 = global_7.emissive; emissive = _e146; let _e148 = emissive; - _ = _e148.xyz; let _e150 = emissive; - _ = v_Uv_1; let _e153 = v_Uv_1; let _e154 = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, _e153); let _e156 = (_e150.xyz * _e154.xyz); @@ -1164,17 +806,11 @@ fn main_1() { emissive.z = _e156.z; let _e163 = global_1.CameraPos; let _e165 = v_WorldPosition_1; - _ = (_e163.xyz - _e165.xyz); let _e168 = global_1.CameraPos; let _e170 = v_WorldPosition_1; V_3 = normalize((_e168.xyz - _e170.xyz)); - _ = N_2; - _ = V_3; let _e177 = N_2; let _e178 = V_3; - _ = dot(_e177, _e178); - _ = N_2; - _ = V_3; let _e183 = N_2; let _e184 = V_3; NdotV_4 = max(dot(_e183, _e184), 0.001); @@ -1188,8 +824,6 @@ fn main_1() { let _e209 = metallic; diffuseColor_4 = (_e206.xyz * vec3((1.0 - _e209))); let _e214 = V_3; - _ = -(_e214); - _ = N_2; let _e217 = V_3; let _e219 = N_2; R_4 = reflect(-(_e217), _e219); @@ -1205,14 +839,6 @@ fn main_1() { { let _e239 = light_accum; let _e240 = i; - _ = global_2.PointLights[_e240]; - _ = roughness_12; - _ = NdotV_4; - _ = N_2; - _ = V_3; - _ = R_4; - _ = F0_4; - _ = diffuseColor_4; let _e250 = i; let _e252 = global_2.PointLights[_e250]; let _e253 = roughness_12; @@ -1241,14 +867,6 @@ fn main_1() { { let _e276 = light_accum; let _e277 = i_1; - _ = global_2.DirectionalLights[_e277]; - _ = roughness_12; - _ = NdotV_4; - _ = N_2; - _ = V_3; - _ = R_4; - _ = F0_4; - _ = diffuseColor_4; let _e287 = i_1; let _e289 = global_2.DirectionalLights[_e287]; let _e290 = roughness_12; @@ -1266,28 +884,21 @@ fn main_1() { i_1 = (_e273 + 1); } } - _ = diffuseColor_4; - _ = NdotV_4; let _e302 = diffuseColor_4; let _e304 = NdotV_4; let _e305 = EnvBRDFApprox(_e302, 1.0, _e304); diffuse_ambient = _e305; - _ = F0_4; - _ = perceptual_roughness_2; - _ = NdotV_4; let _e310 = F0_4; let _e311 = perceptual_roughness_2; let _e312 = NdotV_4; let _e313 = EnvBRDFApprox(_e310, _e311, _e312); specular_ambient = _e313; let _e315 = output_color; - _ = _e315.xyz; let _e317 = light_accum; output_color.x = _e317.x; output_color.y = _e317.y; output_color.z = _e317.z; let _e324 = output_color; - _ = _e324.xyz; let _e326 = output_color; let _e328 = diffuse_ambient; let _e329 = specular_ambient; @@ -1298,7 +909,6 @@ fn main_1() { output_color.y = _e336.y; output_color.z = _e336.z; let _e343 = output_color; - _ = _e343.xyz; let _e345 = output_color; let _e347 = emissive; let _e349 = output_color; @@ -1307,9 +917,7 @@ fn main_1() { output_color.y = _e352.y; output_color.z = _e352.z; let _e359 = output_color; - _ = _e359.xyz; let _e361 = output_color; - _ = _e361.xyz; let _e363 = output_color; let _e365 = reinhard_luminance(_e363.xyz); output_color.x = _e365.x; @@ -1327,17 +935,6 @@ fn main(@location(0) v_WorldPosition: vec3, @location(1) v_WorldNormal: vec v_Uv_1 = v_Uv; v_WorldTangent_1 = v_WorldTangent; gl_FrontFacing = param; - _ = (&global.ViewProj); - _ = (&global_1.CameraPos); - _ = (&global_2.AmbientColor); - _ = (&global_2.NumLights); - _ = (&global_2.PointLights); - _ = (&global_2.DirectionalLights); - _ = (&global_3.base_color); - _ = (&global_4.perceptual_roughness); - _ = (&global_5.metallic); - _ = (&global_6.reflectance); - _ = (&global_7.emissive); main_1(); let _e72 = o_Target; return FragmentOutput(_e72); diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl index dd4c17496..ac13dcdfd 100644 --- a/tests/out/wgsl/bevy-pbr-vert.wgsl +++ b/tests/out/wgsl/bevy-pbr-vert.wgsl @@ -58,7 +58,6 @@ fn main(@location(0) Vertex_Position: vec3, @location(1) Vertex_Normal: vec Vertex_Normal_1 = Vertex_Normal; Vertex_Uv_1 = Vertex_Uv; Vertex_Tangent_1 = Vertex_Tangent; - _ = (&global.ViewProj); main_1(); let _e29 = v_WorldPosition; let _e31 = v_WorldNormal; diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index b68253a27..6e63fe662 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -20,154 +20,96 @@ fn main_1() { u4_ = vec4(u32(0)); f2_ = vec2(0.0); f4_ = vec4(0.0); - _ = f4_; let _e33 = f4_; u = pack4x8snorm(_e33); - _ = f4_; let _e36 = f4_; u = pack4x8unorm(_e36); - _ = f2_; let _e39 = f2_; u = pack2x16unorm(_e39); - _ = f2_; let _e42 = f2_; u = pack2x16snorm(_e42); - _ = f2_; let _e45 = f2_; u = pack2x16float(_e45); - _ = u; let _e48 = u; f4_ = unpack4x8snorm(_e48); - _ = u; let _e51 = u; f4_ = unpack4x8unorm(_e51); - _ = u; let _e54 = u; f2_ = unpack2x16snorm(_e54); - _ = u; let _e57 = u; f2_ = unpack2x16unorm(_e57); - _ = u; let _e60 = u; f2_ = unpack2x16float(_e60); - _ = i; - _ = i; let _e66 = i; let _e67 = i; - _ = u32(10); i = insertBits(_e66, _e67, u32(5), u32(10)); - _ = i2_; - _ = i2_; let _e77 = i2_; let _e78 = i2_; - _ = u32(10); i2_ = insertBits(_e77, _e78, u32(5), u32(10)); - _ = i3_; - _ = i3_; let _e88 = i3_; let _e89 = i3_; - _ = u32(10); i3_ = insertBits(_e88, _e89, u32(5), u32(10)); - _ = i4_; - _ = i4_; let _e99 = i4_; let _e100 = i4_; - _ = u32(10); i4_ = insertBits(_e99, _e100, u32(5), u32(10)); - _ = u; - _ = u; let _e110 = u; let _e111 = u; - _ = u32(10); u = insertBits(_e110, _e111, u32(5), u32(10)); - _ = u2_; - _ = u2_; let _e121 = u2_; let _e122 = u2_; - _ = u32(10); u2_ = insertBits(_e121, _e122, u32(5), u32(10)); - _ = u3_; - _ = u3_; let _e132 = u3_; let _e133 = u3_; - _ = u32(10); u3_ = insertBits(_e132, _e133, u32(5), u32(10)); - _ = u4_; - _ = u4_; let _e143 = u4_; let _e144 = u4_; - _ = u32(10); u4_ = insertBits(_e143, _e144, u32(5), u32(10)); - _ = i; let _e153 = i; i = extractBits(_e153, u32(5), u32(10)); - _ = i2_; let _e162 = i2_; i2_ = extractBits(_e162, u32(5), u32(10)); - _ = i3_; let _e171 = i3_; i3_ = extractBits(_e171, u32(5), u32(10)); - _ = i4_; let _e180 = i4_; i4_ = extractBits(_e180, u32(5), u32(10)); - _ = u; let _e189 = u; u = extractBits(_e189, u32(5), u32(10)); - _ = u2_; let _e198 = u2_; u2_ = extractBits(_e198, u32(5), u32(10)); - _ = u3_; let _e207 = u3_; u3_ = extractBits(_e207, u32(5), u32(10)); - _ = u4_; let _e216 = u4_; u4_ = extractBits(_e216, u32(5), u32(10)); - _ = i; let _e223 = i; i = firstTrailingBit(_e223); - _ = i2_; let _e226 = i2_; i2_ = firstTrailingBit(_e226); - _ = i3_; let _e229 = i3_; i3_ = firstTrailingBit(_e229); - _ = i4_; let _e232 = i4_; i4_ = firstTrailingBit(_e232); - _ = u; let _e235 = u; i = i32(firstTrailingBit(_e235)); - _ = u2_; let _e239 = u2_; i2_ = vec2(firstTrailingBit(_e239)); - _ = u3_; let _e243 = u3_; i3_ = vec3(firstTrailingBit(_e243)); - _ = u4_; let _e247 = u4_; i4_ = vec4(firstTrailingBit(_e247)); - _ = i; let _e251 = i; i = firstLeadingBit(_e251); - _ = i2_; let _e254 = i2_; i2_ = firstLeadingBit(_e254); - _ = i3_; let _e257 = i3_; i3_ = firstLeadingBit(_e257); - _ = i4_; let _e260 = i4_; i4_ = firstLeadingBit(_e260); - _ = u; let _e263 = u; i = i32(firstLeadingBit(_e263)); - _ = u2_; let _e267 = u2_; i2_ = vec2(firstLeadingBit(_e267)); - _ = u3_; let _e271 = u3_; i3_ = vec3(firstLeadingBit(_e271)); - _ = u4_; let _e275 = u4_; i4_ = vec4(firstLeadingBit(_e275)); return; diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index c34fc979d..4f0e218ee 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -21,8 +21,6 @@ fn TevPerCompGT_1(a_2: vec3, b_2: vec3) -> vec3 { a_3 = a_2; b_3 = b_2; - _ = a_3; - _ = b_3; let _e7 = a_3; let _e8 = b_3; return select(vec3(0.0), vec3(1.0), (_e7 > _e8)); @@ -30,9 +28,6 @@ fn TevPerCompGT_1(a_2: vec3, b_2: vec3) -> vec3 { fn main_1() { let _e1 = o_color; - _ = _e1.xyz; - _ = vec3(3.0); - _ = vec3(5.0); let _e11 = TevPerCompGT_1(vec3(3.0), vec3(5.0)); o_color.x = _e11.x; o_color.y = _e11.y; diff --git a/tests/out/wgsl/break-if.wgsl b/tests/out/wgsl/break-if.wgsl index 04b232905..6e65c5215 100644 --- a/tests/out/wgsl/break-if.wgsl +++ b/tests/out/wgsl/break-if.wgsl @@ -17,7 +17,6 @@ fn breakIfEmptyBody(a: bool) { let _e2 = b; c = (a != _e2); let _e5 = c; - _ = (a == _e5); break if (a == _e5); } } @@ -34,7 +33,6 @@ fn breakIf(a_1: bool) { e = (a_1 != _e2); continuing { let _e5 = e; - _ = (a_1 == _e5); break if (a_1 == _e5); } } diff --git a/tests/out/wgsl/buffer-frag.wgsl b/tests/out/wgsl/buffer-frag.wgsl index 3408a69d9..4f561b427 100644 --- a/tests/out/wgsl/buffer-frag.wgsl +++ b/tests/out/wgsl/buffer-frag.wgsl @@ -21,9 +21,6 @@ fn main_1() { var a: u32; var b: u32; - _ = (&testBuffer.data); - _ = (&testBufferWriteOnly.data); - _ = (&testBufferReadOnly.data); let _e12 = testBuffer.data[0]; a = _e12; testBuffer.data[1] = u32(2); @@ -35,8 +32,6 @@ fn main_1() { @fragment fn main() { - _ = (&testBuffer.data); - _ = (&testBufferWriteOnly.data); main_1(); return; } diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index 777b562b3..deeea02ef 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -6,7 +6,6 @@ var a_pos_1: vec2; var gl_Position: vec4; fn main_1() { - _ = a_pos_1; let _e5 = a_pos_1; let _e10 = clamp(_e5, vec2(0.0), vec2(1.0)); gl_Position = vec4(_e10.x, _e10.y, 0.0, 1.0); diff --git a/tests/out/wgsl/declarations-frag.wgsl b/tests/out/wgsl/declarations-frag.wgsl index a004823b6..bdcca29e0 100644 --- a/tests/out/wgsl/declarations-frag.wgsl +++ b/tests/out/wgsl/declarations-frag.wgsl @@ -34,10 +34,6 @@ fn main_1() { var a_1: f32; var b: f32; - _ = (&vert.position); - _ = (&vert.a); - _ = (&frag.position); - _ = (&frag.a); positions = array, 2>(vec3(-(1.0), 1.0, 0.0), vec3(-(1.0), -(1.0), 0.0)); strct = TestStruct(f32(1), f32(2)); let _e35 = in_array_2[1]; @@ -56,10 +52,6 @@ fn main(@location(0) position: vec2, @location(1) a: vec2, @location(2 vert.a = a; in_array_2[0] = in_array; in_array_2[1] = in_array_1; - _ = (&vert.position); - _ = (&vert.a); - _ = (&frag.position); - _ = (&frag.a); main_1(); let _e30 = frag.position; let _e32 = frag.a; diff --git a/tests/out/wgsl/do-while.wgsl b/tests/out/wgsl/do-while.wgsl index d444169e4..2940016da 100644 --- a/tests/out/wgsl/do-while.wgsl +++ b/tests/out/wgsl/do-while.wgsl @@ -3,7 +3,6 @@ fn fb1_(cond: ptr) { continue; continuing { let _e6 = (*cond); - _ = !(_e6); break if !(_e6); } } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index d32860d55..fc821ca8e 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -394,9 +394,7 @@ fn testConstantLength(a_24: array) { var a_25: array; var len_1: i32; - _ = (&global_1.a); a_25 = a_24; - _ = a_25; len_1 = i32(4u); return; } @@ -406,7 +404,6 @@ fn indexConstantNonConstantIndex(i: i32) { var local_5: TestStruct = TestStruct(array, 2>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); var a_26: vec4; - _ = (&global_1.a); i_1 = i; let _e6 = i_1; let _e10 = local_5.array_[_e6]; @@ -417,16 +414,12 @@ fn indexConstantNonConstantIndex(i: i32) { fn testSwizzleWrites(a_27: vec3) { var a_28: vec3; - _ = (&global_1.a); a_28 = a_27; let _e6 = a_28; - _ = _e6.zxy; - _ = _e6.zx; let _e11 = vec2(3.0, 4.0); a_28.z = _e11.x; a_28.x = _e11.y; let _e16 = a_28; - _ = _e16.xy; let _e18 = a_28; let _e21 = (_e18.xy * 5.0); a_28.x = _e21.x; @@ -441,15 +434,12 @@ fn testSwizzleWrites(a_27: vec3) { fn main_1() { var local_6: f32; - _ = (&global_1.a); - _ = global; let _e6 = global; local_6 = _e6; privatePointer((&local_6)); let _e8 = local_6; global = _e8; let _e9 = o_color; - _ = _e9.xyzw; let _e12 = vec4(1.0); o_color.x = _e12.x; o_color.y = _e12.y; @@ -460,8 +450,6 @@ fn main_1() { @fragment fn main() -> FragmentOutput { - _ = (&global_1.a); - _ = TestStruct(array, 2>(vec4(u32(0)), vec4(u32(1)))); main_1(); let _e17 = o_color; return FragmentOutput(_e17); diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index 08ec9ddd8..d7c74c224 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -33,7 +33,6 @@ fn Fma(d: ptr, m: Mat4x3_, s: f32) { fn main_1() { let _e1 = o_color; - _ = _e1.xyzw; let _e4 = vec4(1.0); o_color.x = _e4.x; o_color.y = _e4.y; diff --git a/tests/out/wgsl/functions_call-frag.wgsl b/tests/out/wgsl/functions_call-frag.wgsl index 25615db22..62aaeb203 100644 --- a/tests/out/wgsl/functions_call-frag.wgsl +++ b/tests/out/wgsl/functions_call-frag.wgsl @@ -8,7 +8,6 @@ fn swizzleCaller(a_1: vec3) { a_2 = a_1; let _e2 = a_2; - _ = _e2.xz; let _e4 = a_2; local = _e4.xz; swizzleCallee((&local)); @@ -28,8 +27,6 @@ fn outImplicitCastCaller(a_4: f32) { var local_1: u32; a_5 = a_4; - _ = a_5; - _ = a_5; outImplicitCastCallee((&local_1)); let _e5 = local_1; a_5 = f32(_e5); @@ -46,9 +43,7 @@ fn swizzleImplicitCastCaller(a_7: vec3) { a_8 = a_7; let _e2 = a_8; - _ = _e2.xz; let _e4 = a_8; - _ = _e4.xz; swizzleImplicitCastCallee((&local_2)); let _e11 = local_2.x; a_8.x = f32(_e11); diff --git a/tests/out/wgsl/global-constant-array-frag.wgsl b/tests/out/wgsl/global-constant-array-frag.wgsl index 85b871c2a..a82ad9483 100644 --- a/tests/out/wgsl/global-constant-array-frag.wgsl +++ b/tests/out/wgsl/global-constant-array-frag.wgsl @@ -9,7 +9,6 @@ fn main_1() { @fragment fn main() { - _ = array(1.0, 2.0); main_1(); return; } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 7acdbfec7..b83b43806 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -36,13 +36,13 @@ fn test_msl_packed_vec3_() { let _e17 = idx; alignment.v3_[_e17] = 3.0; let data = alignment; - _ = data.v3_; - _ = data.v3_.zx; + let l0_ = data.v3_; + let l1_ = data.v3_.zx; test_msl_packed_vec3_as_arg(data.v3_); - _ = (data.v3_ * mat3x3()); - _ = (mat3x3() * data.v3_); - _ = (data.v3_ * 2.0); - _ = (2.0 * data.v3_); + let mvm0_ = (data.v3_ * mat3x3()); + let mvm1_ = (mat3x3() * data.v3_); + let svm0_ = (data.v3_ * 2.0); + let svm1_ = (2.0 * data.v3_); } @compute @workgroup_size(1, 1, 1) diff --git a/tests/out/wgsl/images-frag.wgsl b/tests/out/wgsl/images-frag.wgsl index e5c68dccc..2a0f5e749 100644 --- a/tests/out/wgsl/images-frag.wgsl +++ b/tests/out/wgsl/images-frag.wgsl @@ -23,11 +23,8 @@ fn testImg1D(coord: i32) { coord_1 = coord; let _e10 = textureDimensions(img1D); size = i32(_e10); - _ = coord_1; - _ = vec4(f32(2)); let _e17 = coord_1; textureStore(img1D, _e17, vec4(f32(2))); - _ = coord_1; let _e22 = coord_1; let _e23 = textureLoad(img1D, _e22); c = _e23; @@ -43,12 +40,9 @@ fn testImg1DArray(coord_2: vec2) { let _e10 = textureDimensions(img1DArray); let _e11 = textureNumLayers(img1DArray); size_1 = vec2(vec2(vec2(_e10, _e11))); - _ = coord_3; let _e17 = coord_3; let _e20 = textureLoad(img1DArray, _e17.x, _e17.y); c_1 = _e20; - _ = coord_3; - _ = vec4(f32(2)); let _e26 = coord_3; textureStore(img1DArray, _e26.x, _e26.y, vec4(f32(2))); return; @@ -62,12 +56,9 @@ fn testImg2D(coord_4: vec2) { coord_5 = coord_4; let _e10 = textureDimensions(img2D); size_2 = vec2(vec2(_e10)); - _ = coord_5; let _e15 = coord_5; let _e16 = textureLoad(img2D, _e15); c_2 = _e16; - _ = coord_5; - _ = vec4(f32(2)); let _e22 = coord_5; textureStore(img2D, _e22, vec4(f32(2))); return; @@ -82,12 +73,9 @@ fn testImg2DArray(coord_6: vec3) { let _e10 = textureDimensions(img2DArray); let _e13 = textureNumLayers(img2DArray); size_3 = vec3(vec3(vec3(_e10.x, _e10.y, _e13))); - _ = coord_7; let _e19 = coord_7; let _e22 = textureLoad(img2DArray, _e19.xy, _e19.z); c_3 = _e22; - _ = coord_7; - _ = vec4(f32(2)); let _e28 = coord_7; textureStore(img2DArray, _e28.xy, _e28.z, vec4(f32(2))); return; @@ -101,12 +89,9 @@ fn testImg3D(coord_8: vec3) { coord_9 = coord_8; let _e10 = textureDimensions(img3D); size_4 = vec3(vec3(_e10)); - _ = coord_9; let _e15 = coord_9; let _e16 = textureLoad(img3D, _e15); c_4 = _e16; - _ = coord_9; - _ = vec4(f32(2)); let _e22 = coord_9; textureStore(img3D, _e22, vec4(f32(2))); return; @@ -120,7 +105,6 @@ fn testImgReadOnly(coord_10: vec2) { coord_11 = coord_10; let _e10 = textureDimensions(img2D); size_5 = vec2(vec2(_e10)); - _ = coord_11; let _e15 = coord_11; let _e16 = textureLoad(imgReadOnly, _e15); c_5 = _e16; @@ -134,8 +118,6 @@ fn testImgWriteOnly(coord_12: vec2) { coord_13 = coord_12; let _e10 = textureDimensions(img2D); size_6 = vec2(vec2(_e10)); - _ = coord_13; - _ = vec4(f32(2)); let _e18 = coord_13; textureStore(imgWriteOnly, _e18, vec4(f32(2))); return; diff --git a/tests/out/wgsl/math-functions-frag.wgsl b/tests/out/wgsl/math-functions-frag.wgsl index b9049ef23..0b5957038 100644 --- a/tests/out/wgsl/math-functions-frag.wgsl +++ b/tests/out/wgsl/math-functions-frag.wgsl @@ -56,165 +56,109 @@ fn main_1() { let _e9 = b; m = mat4x4(vec4(_e6.x, _e6.y, _e6.z, _e6.w), vec4(_e7.x, _e7.y, _e7.z, _e7.w), vec4(_e8.x, _e8.y, _e8.z, _e8.w), vec4(_e9.x, _e9.y, _e9.z, _e9.w)); i = 5; - _ = a; let _e35 = a; ceilOut = ceil(_e35); - _ = a; let _e39 = a; roundOut = round(_e39); - _ = a; let _e43 = a; floorOut = floor(_e43); - _ = a; let _e47 = a; fractOut = fract(_e47); - _ = a; let _e51 = a; truncOut = trunc(_e51); - _ = a; let _e55 = a; sinOut = sin(_e55); - _ = a; let _e59 = a; absOut = abs(_e59); - _ = a; let _e63 = a; sqrtOut = sqrt(_e63); - _ = a; let _e67 = a; inversesqrtOut = inverseSqrt(_e67); - _ = a; let _e71 = a; expOut = exp(_e71); - _ = a; let _e75 = a; exp2Out = exp2(_e75); - _ = a; let _e79 = a; signOut = sign(_e79); - _ = m; let _e83 = m; transposeOut = transpose(_e83); - _ = a; let _e87 = a; normalizeOut = normalize(_e87); - _ = a; let _e91 = a; sinhOut = sinh(_e91); - _ = a; let _e95 = a; cosOut = cos(_e95); - _ = a; let _e99 = a; coshOut = cosh(_e99); - _ = a; let _e103 = a; tanOut = tan(_e103); - _ = a; let _e107 = a; tanhOut = tanh(_e107); - _ = a; let _e111 = a; acosOut = acos(_e111); - _ = a; let _e115 = a; asinOut = asin(_e115); - _ = a; let _e119 = a; logOut = log(_e119); - _ = a; let _e123 = a; log2Out = log2(_e123); - _ = a; let _e127 = a; lengthOut = length(_e127); - _ = m; let _e131 = m; determinantOut = determinant(_e131); - _ = i; let _e135 = i; bitCountOut = countOneBits(_e135); - _ = i; let _e139 = i; bitfieldReverseOut = reverseBits(_e139); let _e142 = a; - _ = _e142.x; let _e144 = a; atanOut = atan(_e144.x); let _e148 = a; - _ = _e148.x; let _e150 = a; - _ = _e150.y; let _e152 = a; let _e154 = a; atan2Out = atan2(_e152.x, _e154.y); let _e158 = a; - _ = _e158.x; let _e160 = b; - _ = _e160.x; let _e162 = a; let _e164 = b; modOut = (_e162.x - (floor((_e162.x / _e164.x)) * _e164.x)); - _ = a; - _ = b; let _e173 = a; let _e174 = b; powOut = pow(_e173, _e174); - _ = a; - _ = b; let _e179 = a; let _e180 = b; dotOut = dot(_e179, _e180); - _ = a; - _ = b; let _e185 = a; let _e186 = b; maxOut = max(_e185, _e186); - _ = a; - _ = b; let _e191 = a; let _e192 = b; minOut = min(_e191, _e192); - _ = a; - _ = b; let _e197 = a; let _e198 = b; reflectOut = reflect(_e197, _e198); let _e201 = a; - _ = _e201.xyz; let _e203 = b; - _ = _e203.xyz; let _e205 = a; let _e207 = b; crossOut = cross(_e205.xyz, _e207.xyz); - _ = a; - _ = b; let _e213 = a; let _e214 = b; outerProductOut = outerProduct(_e213, _e214); - _ = a; - _ = b; let _e219 = a; let _e220 = b; distanceOut = distance(_e219, _e220); - _ = a; - _ = b; let _e225 = a; let _e226 = b; stepOut = step(_e225, _e226); - _ = a; let _e230 = a; rad = radians(_e230); let _e233 = a; - _ = _e233.x; let _e235 = a; deg = degrees(_e235.x); smoothStepScalar = smoothstep(0.0, 1.0, 0.5); - _ = vec4(0.0); - _ = vec4(1.0); - _ = vec4(0.5); smoothStepVector = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); - _ = vec4(0.5); smoothStepMixed = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); return; } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index a5aba2064..fc7204045 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -48,170 +48,172 @@ fn constructors() -> f32 { var foo: Foo; foo = Foo(vec4(1.0), 1); - let mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); - let mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - _ = vec2(0u); - _ = mat2x2(vec2(0.0), vec2(0.0)); - _ = array(0, 1, 2, 3); - _ = bool(bool()); - _ = i32(i32()); - _ = u32(u32()); - _ = f32(f32()); - _ = vec2(vec2()); - _ = mat2x3(mat2x3()); - _ = bitcast>(vec2()); - _ = mat2x3(mat2x3()); + let m0_ = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); + let m1_1 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + let cit0_ = vec2(0u); + let cit1_ = mat2x2(vec2(0.0), vec2(0.0)); + let cit2_ = array(0, 1, 2, 3); + let ic0_ = bool(bool()); + let ic1_ = i32(i32()); + let ic2_ = u32(u32()); + let ic3_ = f32(f32()); + let ic4_ = vec2(vec2()); + let ic5_ = mat2x3(mat2x3()); + let ic6_ = bitcast>(vec2()); + let ic7_ = mat2x3(mat2x3()); let _e71 = foo.a.x; return _e71; } fn logical() { - _ = !(true); - _ = !(vec2(true)); - _ = (true || false); - _ = (true && false); - _ = (true | false); - _ = (vec3(true) | vec3(false)); - _ = (true & false); - _ = (vec4(true) & vec4(false)); + let neg0_ = !(true); + let neg1_ = !(vec2(true)); + let or = (true || false); + let and = (true && false); + let bitwise_or0_ = (true | false); + let bitwise_or1_ = (vec3(true) | vec3(false)); + let bitwise_and0_ = (true & false); + let bitwise_and1_ = (vec4(true) & vec4(false)); } fn arithmetic() { - _ = -(vec2(1)); - _ = -(vec2(1.0)); - _ = (2 + 1); - _ = (2u + 1u); - _ = (2.0 + 1.0); - _ = (vec2(2) + vec2(1)); - _ = (vec3(2u) + vec3(1u)); - _ = (vec4(2.0) + vec4(1.0)); - _ = (2 - 1); - _ = (2u - 1u); - _ = (2.0 - 1.0); - _ = (vec2(2) - vec2(1)); - _ = (vec3(2u) - vec3(1u)); - _ = (vec4(2.0) - vec4(1.0)); - _ = (2 * 1); - _ = (2u * 1u); - _ = (2.0 * 1.0); - _ = (vec2(2) * vec2(1)); - _ = (vec3(2u) * vec3(1u)); - _ = (vec4(2.0) * vec4(1.0)); - _ = (2 / 1); - _ = (2u / 1u); - _ = (2.0 / 1.0); - _ = (vec2(2) / vec2(1)); - _ = (vec3(2u) / vec3(1u)); - _ = (vec4(2.0) / vec4(1.0)); - _ = (2 % 1); - _ = (2u % 1u); - _ = (2.0 % 1.0); - _ = (vec2(2) % vec2(1)); - _ = (vec3(2u) % vec3(1u)); - _ = (vec4(2.0) % vec4(1.0)); - _ = (vec2(2) + vec2(1)); - _ = (vec2(2) + vec2(1)); - _ = (vec2(2u) + vec2(1u)); - _ = (vec2(2u) + vec2(1u)); - _ = (vec2(2.0) + vec2(1.0)); - _ = (vec2(2.0) + vec2(1.0)); - _ = (vec2(2) - vec2(1)); - _ = (vec2(2) - vec2(1)); - _ = (vec2(2u) - vec2(1u)); - _ = (vec2(2u) - vec2(1u)); - _ = (vec2(2.0) - vec2(1.0)); - _ = (vec2(2.0) - vec2(1.0)); - _ = (vec2(2) * 1); - _ = (2 * vec2(1)); - _ = (vec2(2u) * 1u); - _ = (2u * vec2(1u)); - _ = (vec2(2.0) * 1.0); - _ = (2.0 * vec2(1.0)); - _ = (vec2(2) / vec2(1)); - _ = (vec2(2) / vec2(1)); - _ = (vec2(2u) / vec2(1u)); - _ = (vec2(2u) / vec2(1u)); - _ = (vec2(2.0) / vec2(1.0)); - _ = (vec2(2.0) / vec2(1.0)); - _ = (vec2(2) % vec2(1)); - _ = (vec2(2) % vec2(1)); - _ = (vec2(2u) % vec2(1u)); - _ = (vec2(2u) % vec2(1u)); - _ = (vec2(2.0) % vec2(1.0)); - _ = (vec2(2.0) % vec2(1.0)); - _ = (mat3x3() + mat3x3()); - _ = (mat3x3() - mat3x3()); - _ = (mat3x3() * 1.0); - _ = (2.0 * mat3x3()); - _ = (mat4x3() * vec4(1.0)); - _ = (vec3(2.0) * mat4x3()); - _ = (mat4x3() * mat3x4()); + let neg1_1 = -(vec2(1)); + let neg2_ = -(vec2(1.0)); + let add0_ = (2 + 1); + let add1_ = (2u + 1u); + let add2_ = (2.0 + 1.0); + let add3_ = (vec2(2) + vec2(1)); + let add4_ = (vec3(2u) + vec3(1u)); + let add5_ = (vec4(2.0) + vec4(1.0)); + let sub0_ = (2 - 1); + let sub1_ = (2u - 1u); + let sub2_ = (2.0 - 1.0); + let sub3_ = (vec2(2) - vec2(1)); + let sub4_ = (vec3(2u) - vec3(1u)); + let sub5_ = (vec4(2.0) - vec4(1.0)); + let mul0_ = (2 * 1); + let mul1_ = (2u * 1u); + let mul2_ = (2.0 * 1.0); + let mul3_ = (vec2(2) * vec2(1)); + let mul4_ = (vec3(2u) * vec3(1u)); + let mul5_ = (vec4(2.0) * vec4(1.0)); + let div0_ = (2 / 1); + let div1_ = (2u / 1u); + let div2_ = (2.0 / 1.0); + let div3_ = (vec2(2) / vec2(1)); + let div4_ = (vec3(2u) / vec3(1u)); + let div5_ = (vec4(2.0) / vec4(1.0)); + let rem0_ = (2 % 1); + let rem1_ = (2u % 1u); + let rem2_ = (2.0 % 1.0); + let rem3_ = (vec2(2) % vec2(1)); + let rem4_ = (vec3(2u) % vec3(1u)); + let rem5_ = (vec4(2.0) % vec4(1.0)); + { + let add0_1 = (vec2(2) + vec2(1)); + let add1_1 = (vec2(2) + vec2(1)); + let add2_1 = (vec2(2u) + vec2(1u)); + let add3_1 = (vec2(2u) + vec2(1u)); + let add4_1 = (vec2(2.0) + vec2(1.0)); + let add5_1 = (vec2(2.0) + vec2(1.0)); + let sub0_1 = (vec2(2) - vec2(1)); + let sub1_1 = (vec2(2) - vec2(1)); + let sub2_1 = (vec2(2u) - vec2(1u)); + let sub3_1 = (vec2(2u) - vec2(1u)); + let sub4_1 = (vec2(2.0) - vec2(1.0)); + let sub5_1 = (vec2(2.0) - vec2(1.0)); + let mul0_1 = (vec2(2) * 1); + let mul1_1 = (2 * vec2(1)); + let mul2_1 = (vec2(2u) * 1u); + let mul3_1 = (2u * vec2(1u)); + let mul4_1 = (vec2(2.0) * 1.0); + let mul5_1 = (2.0 * vec2(1.0)); + let div0_1 = (vec2(2) / vec2(1)); + let div1_1 = (vec2(2) / vec2(1)); + let div2_1 = (vec2(2u) / vec2(1u)); + let div3_1 = (vec2(2u) / vec2(1u)); + let div4_1 = (vec2(2.0) / vec2(1.0)); + let div5_1 = (vec2(2.0) / vec2(1.0)); + let rem0_1 = (vec2(2) % vec2(1)); + let rem1_1 = (vec2(2) % vec2(1)); + let rem2_1 = (vec2(2u) % vec2(1u)); + let rem3_1 = (vec2(2u) % vec2(1u)); + let rem4_1 = (vec2(2.0) % vec2(1.0)); + let rem5_1 = (vec2(2.0) % vec2(1.0)); + } + let add = (mat3x3() + mat3x3()); + let sub = (mat3x3() - mat3x3()); + let mul_scalar0_ = (mat3x3() * 1.0); + let mul_scalar1_ = (2.0 * mat3x3()); + let mul_vector0_ = (mat4x3() * vec4(1.0)); + let mul_vector1_ = (vec3(2.0) * mat4x3()); + let mul = (mat4x3() * mat3x4()); } fn bit() { - _ = ~(1); - _ = ~(1u); - _ = !(vec2(1)); - _ = !(vec3(1u)); - _ = (2 | 1); - _ = (2u | 1u); - _ = (vec2(2) | vec2(1)); - _ = (vec3(2u) | vec3(1u)); - _ = (2 & 1); - _ = (2u & 1u); - _ = (vec2(2) & vec2(1)); - _ = (vec3(2u) & vec3(1u)); - _ = (2 ^ 1); - _ = (2u ^ 1u); - _ = (vec2(2) ^ vec2(1)); - _ = (vec3(2u) ^ vec3(1u)); - _ = (2 << 1u); - _ = (2u << 1u); - _ = (vec2(2) << vec2(1u)); - _ = (vec3(2u) << vec3(1u)); - _ = (2 >> 1u); - _ = (2u >> 1u); - _ = (vec2(2) >> vec2(1u)); - _ = (vec3(2u) >> vec3(1u)); + let flip0_ = ~(1); + let flip1_ = ~(1u); + let flip2_ = !(vec2(1)); + let flip3_ = !(vec3(1u)); + let or0_ = (2 | 1); + let or1_ = (2u | 1u); + let or2_ = (vec2(2) | vec2(1)); + let or3_ = (vec3(2u) | vec3(1u)); + let and0_ = (2 & 1); + let and1_ = (2u & 1u); + let and2_ = (vec2(2) & vec2(1)); + let and3_ = (vec3(2u) & vec3(1u)); + let xor0_ = (2 ^ 1); + let xor1_ = (2u ^ 1u); + let xor2_ = (vec2(2) ^ vec2(1)); + let xor3_ = (vec3(2u) ^ vec3(1u)); + let shl0_ = (2 << 1u); + let shl1_ = (2u << 1u); + let shl2_ = (vec2(2) << vec2(1u)); + let shl3_ = (vec3(2u) << vec3(1u)); + let shr0_ = (2 >> 1u); + let shr1_ = (2u >> 1u); + let shr2_ = (vec2(2) >> vec2(1u)); + let shr3_ = (vec3(2u) >> vec3(1u)); } fn comparison() { - _ = (2 == 1); - _ = (2u == 1u); - _ = (2.0 == 1.0); - _ = (vec2(2) == vec2(1)); - _ = (vec3(2u) == vec3(1u)); - _ = (vec4(2.0) == vec4(1.0)); - _ = (2 != 1); - _ = (2u != 1u); - _ = (2.0 != 1.0); - _ = (vec2(2) != vec2(1)); - _ = (vec3(2u) != vec3(1u)); - _ = (vec4(2.0) != vec4(1.0)); - _ = (2 < 1); - _ = (2u < 1u); - _ = (2.0 < 1.0); - _ = (vec2(2) < vec2(1)); - _ = (vec3(2u) < vec3(1u)); - _ = (vec4(2.0) < vec4(1.0)); - _ = (2 <= 1); - _ = (2u <= 1u); - _ = (2.0 <= 1.0); - _ = (vec2(2) <= vec2(1)); - _ = (vec3(2u) <= vec3(1u)); - _ = (vec4(2.0) <= vec4(1.0)); - _ = (2 > 1); - _ = (2u > 1u); - _ = (2.0 > 1.0); - _ = (vec2(2) > vec2(1)); - _ = (vec3(2u) > vec3(1u)); - _ = (vec4(2.0) > vec4(1.0)); - _ = (2 >= 1); - _ = (2u >= 1u); - _ = (2.0 >= 1.0); - _ = (vec2(2) >= vec2(1)); - _ = (vec3(2u) >= vec3(1u)); - _ = (vec4(2.0) >= vec4(1.0)); + let eq0_ = (2 == 1); + let eq1_ = (2u == 1u); + let eq2_ = (2.0 == 1.0); + let eq3_ = (vec2(2) == vec2(1)); + let eq4_ = (vec3(2u) == vec3(1u)); + let eq5_ = (vec4(2.0) == vec4(1.0)); + let neq0_ = (2 != 1); + let neq1_ = (2u != 1u); + let neq2_ = (2.0 != 1.0); + let neq3_ = (vec2(2) != vec2(1)); + let neq4_ = (vec3(2u) != vec3(1u)); + let neq5_ = (vec4(2.0) != vec4(1.0)); + let lt0_ = (2 < 1); + let lt1_ = (2u < 1u); + let lt2_ = (2.0 < 1.0); + let lt3_ = (vec2(2) < vec2(1)); + let lt4_ = (vec3(2u) < vec3(1u)); + let lt5_ = (vec4(2.0) < vec4(1.0)); + let lte0_ = (2 <= 1); + let lte1_ = (2u <= 1u); + let lte2_ = (2.0 <= 1.0); + let lte3_ = (vec2(2) <= vec2(1)); + let lte4_ = (vec3(2u) <= vec3(1u)); + let lte5_ = (vec4(2.0) <= vec4(1.0)); + let gt0_ = (2 > 1); + let gt1_ = (2u > 1u); + let gt2_ = (2.0 > 1.0); + let gt3_ = (vec2(2) > vec2(1)); + let gt4_ = (vec3(2u) > vec3(1u)); + let gt5_ = (vec4(2.0) > vec4(1.0)); + let gte0_ = (2 >= 1); + let gte1_ = (2u >= 1u); + let gte2_ = (2.0 >= 1.0); + let gte3_ = (vec2(2) >= vec2(1)); + let gte4_ = (vec3(2u) >= vec3(1u)); + let gte5_ = (vec4(2.0) >= vec4(1.0)); } fn assignment() { @@ -254,13 +256,13 @@ fn assignment() { } fn negation_avoids_prefix_decrement() { - _ = -(-2); - _ = -(-3); - _ = -(-(4)); - _ = -(-(-5)); - _ = -(-(-(-(6)))); - _ = -(-(-(-(-7)))); - _ = -(-(-(-(-8)))); + let p1_ = -(-2); + let p2_ = -(-3); + let p3_ = -(-(4)); + let p4_ = -(-(-5)); + let p5_ = -(-(-(-(6)))); + let p6_ = -(-(-(-(-7)))); + let p7_ = -(-(-(-(-8)))); } @compute @workgroup_size(1, 1, 1) diff --git a/tests/out/wgsl/sampler-functions-frag.wgsl b/tests/out/wgsl/sampler-functions-frag.wgsl index 805dc8f7f..89a5c35dc 100644 --- a/tests/out/wgsl/sampler-functions-frag.wgsl +++ b/tests/out/wgsl/sampler-functions-frag.wgsl @@ -6,7 +6,6 @@ fn CalcShadowPCF1_(T_P_t_TextureDepth: texture_depth_2d, S_P_t_TextureDepth: sam t_Res = 0.0; let _e6 = t_Res; let _e7 = t_ProjCoord_1; - _ = _e7.xyz; let _e9 = t_ProjCoord_1; let _e10 = _e9.xyz; let _e13 = textureSampleCompare(T_P_t_TextureDepth, S_P_t_TextureDepth, _e10.xy, _e10.z); @@ -25,7 +24,6 @@ fn CalcShadowPCF(T_P_t_TextureDepth_1: texture_depth_2d, S_P_t_TextureDepth_1: s let _e9 = t_Bias_1; t_ProjCoord_3.z = (_e7.z + _e9); let _e11 = t_ProjCoord_3; - _ = _e11.xyz; let _e13 = t_ProjCoord_3; let _e15 = CalcShadowPCF1_(T_P_t_TextureDepth_1, S_P_t_TextureDepth_1, _e13.xyz); return _e15; diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index e9c111659..56d4489d8 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -39,141 +39,115 @@ fn testTex1D(coord: f32) { coord_1 = coord; let _e20 = textureDimensions(tex1D, 0); size1D = i32(_e20); - _ = coord_1; let _e25 = coord_1; let _e26 = textureSample(tex1D, samp, _e25); c = _e26; - _ = coord_1; let _e29 = coord_1; let _e31 = textureSampleBias(tex1D, samp, _e29, 2.0); c = _e31; - _ = coord_1; let _e35 = coord_1; let _e38 = textureSampleGrad(tex1D, samp, _e35, 4.0, 4.0); c = _e38; - _ = coord_1; let _e43 = coord_1; let _e47 = textureSampleGrad(tex1D, samp, _e43, 4.0, 4.0, 5); c = _e47; - _ = coord_1; let _e50 = coord_1; let _e52 = textureSampleLevel(tex1D, samp, _e50, 3.0); c = _e52; - _ = coord_1; let _e56 = coord_1; let _e59 = textureSampleLevel(tex1D, samp, _e56, 3.0, 5); c = _e59; - _ = coord_1; let _e62 = coord_1; let _e64 = textureSample(tex1D, samp, _e62, 5); c = _e64; - _ = coord_1; let _e68 = coord_1; let _e71 = textureSampleBias(tex1D, samp, _e68, 2.0, 5); c = _e71; let _e72 = coord_1; - _ = vec2(_e72, 6.0); let _e75 = coord_1; let _e77 = vec2(_e75, 6.0); let _e81 = textureSample(tex1D, samp, (_e77.x / _e77.y)); c = _e81; let _e82 = coord_1; - _ = vec4(_e82, 0.0, 0.0, 6.0); let _e87 = coord_1; let _e91 = vec4(_e87, 0.0, 0.0, 6.0); let _e97 = textureSample(tex1D, samp, (_e91.xyz / vec3(_e91.w)).x); c = _e97; let _e98 = coord_1; - _ = vec2(_e98, 6.0); let _e102 = coord_1; let _e104 = vec2(_e102, 6.0); let _e109 = textureSampleBias(tex1D, samp, (_e104.x / _e104.y), 2.0); c = _e109; let _e110 = coord_1; - _ = vec4(_e110, 0.0, 0.0, 6.0); let _e116 = coord_1; let _e120 = vec4(_e116, 0.0, 0.0, 6.0); let _e127 = textureSampleBias(tex1D, samp, (_e120.xyz / vec3(_e120.w)).x, 2.0); c = _e127; let _e128 = coord_1; - _ = vec2(_e128, 6.0); let _e133 = coord_1; let _e135 = vec2(_e133, 6.0); let _e141 = textureSampleGrad(tex1D, samp, (_e135.x / _e135.y), 4.0, 4.0); c = _e141; let _e142 = coord_1; - _ = vec4(_e142, 0.0, 0.0, 6.0); let _e149 = coord_1; let _e153 = vec4(_e149, 0.0, 0.0, 6.0); let _e161 = textureSampleGrad(tex1D, samp, (_e153.xyz / vec3(_e153.w)).x, 4.0, 4.0); c = _e161; let _e162 = coord_1; - _ = vec2(_e162, 6.0); let _e168 = coord_1; let _e170 = vec2(_e168, 6.0); let _e177 = textureSampleGrad(tex1D, samp, (_e170.x / _e170.y), 4.0, 4.0, 5); c = _e177; let _e178 = coord_1; - _ = vec4(_e178, 0.0, 0.0, 6.0); let _e186 = coord_1; let _e190 = vec4(_e186, 0.0, 0.0, 6.0); let _e199 = textureSampleGrad(tex1D, samp, (_e190.xyz / vec3(_e190.w)).x, 4.0, 4.0, 5); c = _e199; let _e200 = coord_1; - _ = vec2(_e200, 6.0); let _e204 = coord_1; let _e206 = vec2(_e204, 6.0); let _e211 = textureSampleLevel(tex1D, samp, (_e206.x / _e206.y), 3.0); c = _e211; let _e212 = coord_1; - _ = vec4(_e212, 0.0, 0.0, 6.0); let _e218 = coord_1; let _e222 = vec4(_e218, 0.0, 0.0, 6.0); let _e229 = textureSampleLevel(tex1D, samp, (_e222.xyz / vec3(_e222.w)).x, 3.0); c = _e229; let _e230 = coord_1; - _ = vec2(_e230, 6.0); let _e235 = coord_1; let _e237 = vec2(_e235, 6.0); let _e243 = textureSampleLevel(tex1D, samp, (_e237.x / _e237.y), 3.0, 5); c = _e243; let _e244 = coord_1; - _ = vec4(_e244, 0.0, 0.0, 6.0); let _e251 = coord_1; let _e255 = vec4(_e251, 0.0, 0.0, 6.0); let _e263 = textureSampleLevel(tex1D, samp, (_e255.xyz / vec3(_e255.w)).x, 3.0, 5); c = _e263; let _e264 = coord_1; - _ = vec2(_e264, 6.0); let _e268 = coord_1; let _e270 = vec2(_e268, 6.0); let _e275 = textureSample(tex1D, samp, (_e270.x / _e270.y), 5); c = _e275; let _e276 = coord_1; - _ = vec4(_e276, 0.0, 0.0, 6.0); let _e282 = coord_1; let _e286 = vec4(_e282, 0.0, 0.0, 6.0); let _e293 = textureSample(tex1D, samp, (_e286.xyz / vec3(_e286.w)).x, 5); c = _e293; let _e294 = coord_1; - _ = vec2(_e294, 6.0); let _e299 = coord_1; let _e301 = vec2(_e299, 6.0); let _e307 = textureSampleBias(tex1D, samp, (_e301.x / _e301.y), 2.0, 5); c = _e307; let _e308 = coord_1; - _ = vec4(_e308, 0.0, 0.0, 6.0); let _e315 = coord_1; let _e319 = vec4(_e315, 0.0, 0.0, 6.0); let _e327 = textureSampleBias(tex1D, samp, (_e319.xyz / vec3(_e319.w)).x, 2.0, 5); c = _e327; let _e328 = coord_1; - _ = i32(_e328); let _e331 = coord_1; let _e334 = textureLoad(tex1D, i32(_e331), 3); c = _e334; let _e335 = coord_1; - _ = i32(_e335); let _e339 = coord_1; let _e343 = textureLoad(tex1D, i32(_e339), 3); c = _e343; @@ -189,46 +163,36 @@ fn testTex1DArray(coord_2: vec2) { let _e20 = textureDimensions(tex1DArray, 0); let _e21 = textureNumLayers(tex1DArray); size1DArray = vec2(vec2(_e20, _e21)); - _ = coord_3; let _e27 = coord_3; let _e31 = textureSample(tex1DArray, samp, _e27.x, i32(_e27.y)); c_1 = _e31; - _ = coord_3; let _e34 = coord_3; let _e39 = textureSampleBias(tex1DArray, samp, _e34.x, i32(_e34.y), 2.0); c_1 = _e39; - _ = coord_3; let _e43 = coord_3; let _e49 = textureSampleGrad(tex1DArray, samp, _e43.x, i32(_e43.y), 4.0, 4.0); c_1 = _e49; - _ = coord_3; let _e54 = coord_3; let _e61 = textureSampleGrad(tex1DArray, samp, _e54.x, i32(_e54.y), 4.0, 4.0, 5); c_1 = _e61; - _ = coord_3; let _e64 = coord_3; let _e69 = textureSampleLevel(tex1DArray, samp, _e64.x, i32(_e64.y), 3.0); c_1 = _e69; - _ = coord_3; let _e73 = coord_3; let _e79 = textureSampleLevel(tex1DArray, samp, _e73.x, i32(_e73.y), 3.0, 5); c_1 = _e79; - _ = coord_3; let _e82 = coord_3; let _e87 = textureSample(tex1DArray, samp, _e82.x, i32(_e82.y), 5); c_1 = _e87; - _ = coord_3; let _e91 = coord_3; let _e97 = textureSampleBias(tex1DArray, samp, _e91.x, i32(_e91.y), 2.0, 5); c_1 = _e97; let _e98 = coord_3; - _ = vec2(_e98); let _e101 = coord_3; let _e102 = vec2(_e101); let _e106 = textureLoad(tex1DArray, _e102.x, _e102.y, 3); c_1 = _e106; let _e107 = coord_3; - _ = vec2(_e107); let _e111 = coord_3; let _e112 = vec2(_e111); let _e117 = textureLoad(tex1DArray, _e112.x, _e112.y, 3); @@ -244,180 +208,116 @@ fn testTex2D(coord_4: vec2) { coord_5 = coord_4; let _e20 = textureDimensions(tex2D, 0); size2D = vec2(_e20); - _ = coord_5; let _e25 = coord_5; let _e26 = textureSample(tex2D, samp, _e25); c_2 = _e26; - _ = coord_5; let _e29 = coord_5; let _e31 = textureSampleBias(tex2D, samp, _e29, 2.0); c_2 = _e31; - _ = coord_5; - _ = vec2(4.0); - _ = vec2(4.0); let _e37 = coord_5; let _e42 = textureSampleGrad(tex2D, samp, _e37, vec2(4.0), vec2(4.0)); c_2 = _e42; - _ = coord_5; - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e50 = coord_5; - _ = vec2(5); let _e57 = textureSampleGrad(tex2D, samp, _e50, vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e57; - _ = coord_5; let _e60 = coord_5; let _e62 = textureSampleLevel(tex2D, samp, _e60, 3.0); c_2 = _e62; - _ = coord_5; - _ = vec2(5); let _e67 = coord_5; - _ = vec2(5); let _e71 = textureSampleLevel(tex2D, samp, _e67, 3.0, vec2(5, 5)); c_2 = _e71; - _ = coord_5; - _ = vec2(5); let _e75 = coord_5; - _ = vec2(5); let _e78 = textureSample(tex2D, samp, _e75, vec2(5, 5)); c_2 = _e78; - _ = coord_5; - _ = vec2(5); let _e83 = coord_5; - _ = vec2(5); let _e87 = textureSampleBias(tex2D, samp, _e83, 2.0, vec2(5, 5)); c_2 = _e87; let _e88 = coord_5; - _ = vec3(_e88.x, _e88.y, 6.0); let _e93 = coord_5; let _e97 = vec3(_e93.x, _e93.y, 6.0); let _e102 = textureSample(tex2D, samp, (_e97.xy / vec2(_e97.z))); c_2 = _e102; let _e103 = coord_5; - _ = vec4(_e103.x, _e103.y, 0.0, 6.0); let _e109 = coord_5; let _e114 = vec4(_e109.x, _e109.y, 0.0, 6.0); let _e120 = textureSample(tex2D, samp, (_e114.xyz / vec3(_e114.w)).xy); c_2 = _e120; let _e121 = coord_5; - _ = vec3(_e121.x, _e121.y, 6.0); let _e127 = coord_5; let _e131 = vec3(_e127.x, _e127.y, 6.0); let _e137 = textureSampleBias(tex2D, samp, (_e131.xy / vec2(_e131.z)), 2.0); c_2 = _e137; let _e138 = coord_5; - _ = vec4(_e138.x, _e138.y, 0.0, 6.0); let _e145 = coord_5; let _e150 = vec4(_e145.x, _e145.y, 0.0, 6.0); let _e157 = textureSampleBias(tex2D, samp, (_e150.xyz / vec3(_e150.w)).xy, 2.0); c_2 = _e157; let _e158 = coord_5; - _ = vec3(_e158.x, _e158.y, 6.0); - _ = vec2(4.0); - _ = vec2(4.0); let _e167 = coord_5; let _e171 = vec3(_e167.x, _e167.y, 6.0); let _e180 = textureSampleGrad(tex2D, samp, (_e171.xy / vec2(_e171.z)), vec2(4.0), vec2(4.0)); c_2 = _e180; let _e181 = coord_5; - _ = vec4(_e181.x, _e181.y, 0.0, 6.0); - _ = vec2(4.0); - _ = vec2(4.0); let _e191 = coord_5; let _e196 = vec4(_e191.x, _e191.y, 0.0, 6.0); let _e206 = textureSampleGrad(tex2D, samp, (_e196.xyz / vec3(_e196.w)).xy, vec2(4.0), vec2(4.0)); c_2 = _e206; let _e207 = coord_5; - _ = vec3(_e207.x, _e207.y, 6.0); - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e218 = coord_5; let _e222 = vec3(_e218.x, _e218.y, 6.0); - _ = vec2(5); let _e233 = textureSampleGrad(tex2D, samp, (_e222.xy / vec2(_e222.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e233; let _e234 = coord_5; - _ = vec4(_e234.x, _e234.y, 0.0, 6.0); - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e246 = coord_5; let _e251 = vec4(_e246.x, _e246.y, 0.0, 6.0); - _ = vec2(5); let _e263 = textureSampleGrad(tex2D, samp, (_e251.xyz / vec3(_e251.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e263; let _e264 = coord_5; - _ = vec3(_e264.x, _e264.y, 6.0); let _e270 = coord_5; let _e274 = vec3(_e270.x, _e270.y, 6.0); let _e280 = textureSampleLevel(tex2D, samp, (_e274.xy / vec2(_e274.z)), 3.0); c_2 = _e280; let _e281 = coord_5; - _ = vec4(_e281.x, _e281.y, 0.0, 6.0); let _e288 = coord_5; let _e293 = vec4(_e288.x, _e288.y, 0.0, 6.0); let _e300 = textureSampleLevel(tex2D, samp, (_e293.xyz / vec3(_e293.w)).xy, 3.0); c_2 = _e300; let _e301 = coord_5; - _ = vec3(_e301.x, _e301.y, 6.0); - _ = vec2(5); let _e309 = coord_5; let _e313 = vec3(_e309.x, _e309.y, 6.0); - _ = vec2(5); let _e321 = textureSampleLevel(tex2D, samp, (_e313.xy / vec2(_e313.z)), 3.0, vec2(5, 5)); c_2 = _e321; let _e322 = coord_5; - _ = vec4(_e322.x, _e322.y, 0.0, 6.0); - _ = vec2(5); let _e331 = coord_5; let _e336 = vec4(_e331.x, _e331.y, 0.0, 6.0); - _ = vec2(5); let _e345 = textureSampleLevel(tex2D, samp, (_e336.xyz / vec3(_e336.w)).xy, 3.0, vec2(5, 5)); c_2 = _e345; let _e346 = coord_5; - _ = vec3(_e346.x, _e346.y, 6.0); - _ = vec2(5); let _e353 = coord_5; let _e357 = vec3(_e353.x, _e353.y, 6.0); - _ = vec2(5); let _e364 = textureSample(tex2D, samp, (_e357.xy / vec2(_e357.z)), vec2(5, 5)); c_2 = _e364; let _e365 = coord_5; - _ = vec4(_e365.x, _e365.y, 0.0, 6.0); - _ = vec2(5); let _e373 = coord_5; let _e378 = vec4(_e373.x, _e373.y, 0.0, 6.0); - _ = vec2(5); let _e386 = textureSample(tex2D, samp, (_e378.xyz / vec3(_e378.w)).xy, vec2(5, 5)); c_2 = _e386; let _e387 = coord_5; - _ = vec3(_e387.x, _e387.y, 6.0); - _ = vec2(5); let _e395 = coord_5; let _e399 = vec3(_e395.x, _e395.y, 6.0); - _ = vec2(5); let _e407 = textureSampleBias(tex2D, samp, (_e399.xy / vec2(_e399.z)), 2.0, vec2(5, 5)); c_2 = _e407; let _e408 = coord_5; - _ = vec4(_e408.x, _e408.y, 0.0, 6.0); - _ = vec2(5); let _e417 = coord_5; let _e422 = vec4(_e417.x, _e417.y, 0.0, 6.0); - _ = vec2(5); let _e431 = textureSampleBias(tex2D, samp, (_e422.xyz / vec3(_e422.w)).xy, 2.0, vec2(5, 5)); c_2 = _e431; let _e432 = coord_5; - _ = vec2(_e432); let _e435 = coord_5; let _e438 = textureLoad(tex2D, vec2(_e435), 3); c_2 = _e438; let _e439 = coord_5; - _ = vec2(_e439); - _ = vec2(5); let _e444 = coord_5; - _ = vec2(5); let _e449 = textureLoad(tex2D, vec2(_e444), 3); c_2 = _e449; return; @@ -432,108 +332,68 @@ fn testTex2DShadow(coord_6: vec2) { let _e20 = textureDimensions(tex2DShadow, 0); size2DShadow = vec2(_e20); let _e24 = coord_7; - _ = vec3(_e24.x, _e24.y, 1.0); let _e29 = coord_7; let _e33 = vec3(_e29.x, _e29.y, 1.0); let _e36 = textureSampleCompare(tex2DShadow, sampShadow, _e33.xy, _e33.z); d = _e36; let _e37 = coord_7; - _ = vec3(_e37.x, _e37.y, 1.0); - _ = vec2(4.0); - _ = vec2(4.0); let _e46 = coord_7; let _e50 = vec3(_e46.x, _e46.y, 1.0); - _ = vec2(4.0); - _ = vec2(4.0); let _e57 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e50.xy, _e50.z); d = _e57; let _e58 = coord_7; - _ = vec3(_e58.x, _e58.y, 1.0); - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e69 = coord_7; let _e73 = vec3(_e69.x, _e69.y, 1.0); - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e82 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e73.xy, _e73.z, vec2(5, 5)); d = _e82; let _e83 = coord_7; - _ = vec3(_e83.x, _e83.y, 1.0); let _e89 = coord_7; let _e93 = vec3(_e89.x, _e89.y, 1.0); let _e97 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e93.xy, _e93.z); d = _e97; let _e98 = coord_7; - _ = vec3(_e98.x, _e98.y, 1.0); - _ = vec2(5); let _e106 = coord_7; let _e110 = vec3(_e106.x, _e106.y, 1.0); - _ = vec2(5); let _e116 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e110.xy, _e110.z, vec2(5, 5)); d = _e116; let _e117 = coord_7; - _ = vec3(_e117.x, _e117.y, 1.0); - _ = vec2(5); let _e124 = coord_7; let _e128 = vec3(_e124.x, _e124.y, 1.0); - _ = vec2(5); let _e133 = textureSampleCompare(tex2DShadow, sampShadow, _e128.xy, _e128.z, vec2(5, 5)); d = _e133; let _e134 = coord_7; - _ = vec4(_e134.x, _e134.y, 1.0, 6.0); let _e140 = coord_7; let _e145 = vec4(_e140.x, _e140.y, 1.0, 6.0); let _e149 = (_e145.xyz / vec3(_e145.w)); let _e152 = textureSampleCompare(tex2DShadow, sampShadow, _e149.xy, _e149.z); d = _e152; let _e153 = coord_7; - _ = vec4(_e153.x, _e153.y, 1.0, 6.0); - _ = vec2(4.0); - _ = vec2(4.0); let _e163 = coord_7; let _e168 = vec4(_e163.x, _e163.y, 1.0, 6.0); - _ = vec2(4.0); - _ = vec2(4.0); let _e176 = (_e168.xyz / vec3(_e168.w)); let _e179 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e176.xy, _e176.z); d = _e179; let _e180 = coord_7; - _ = vec4(_e180.x, _e180.y, 1.0, 6.0); - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e192 = coord_7; let _e197 = vec4(_e192.x, _e192.y, 1.0, 6.0); - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e207 = (_e197.xyz / vec3(_e197.w)); let _e210 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e207.xy, _e207.z, vec2(5, 5)); d = _e210; let _e211 = coord_7; - _ = vec4(_e211.x, _e211.y, 1.0, 6.0); let _e218 = coord_7; let _e223 = vec4(_e218.x, _e218.y, 1.0, 6.0); let _e228 = (_e223.xyz / vec3(_e223.w)); let _e231 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e228.xy, _e228.z); d = _e231; let _e232 = coord_7; - _ = vec4(_e232.x, _e232.y, 1.0, 6.0); - _ = vec2(5); let _e241 = coord_7; let _e246 = vec4(_e241.x, _e241.y, 1.0, 6.0); - _ = vec2(5); let _e253 = (_e246.xyz / vec3(_e246.w)); let _e256 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e253.xy, _e253.z, vec2(5, 5)); d = _e256; let _e257 = coord_7; - _ = vec4(_e257.x, _e257.y, 1.0, 6.0); - _ = vec2(5); let _e265 = coord_7; let _e270 = vec4(_e265.x, _e265.y, 1.0, 6.0); - _ = vec2(5); let _e276 = (_e270.xyz / vec3(_e270.w)); let _e279 = textureSampleCompare(tex2DShadow, sampShadow, _e276.xy, _e276.z, vec2(5, 5)); d = _e279; @@ -549,62 +409,38 @@ fn testTex2DArray(coord_8: vec3) { let _e20 = textureDimensions(tex2DArray, 0); let _e23 = textureNumLayers(tex2DArray); size2DArray = vec3(vec3(_e20.x, _e20.y, _e23)); - _ = coord_9; let _e29 = coord_9; let _e33 = textureSample(tex2DArray, samp, _e29.xy, i32(_e29.z)); c_3 = _e33; - _ = coord_9; let _e36 = coord_9; let _e41 = textureSampleBias(tex2DArray, samp, _e36.xy, i32(_e36.z), 2.0); c_3 = _e41; - _ = coord_9; - _ = vec2(4.0); - _ = vec2(4.0); let _e47 = coord_9; let _e55 = textureSampleGrad(tex2DArray, samp, _e47.xy, i32(_e47.z), vec2(4.0), vec2(4.0)); c_3 = _e55; - _ = coord_9; - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e63 = coord_9; - _ = vec2(5); let _e73 = textureSampleGrad(tex2DArray, samp, _e63.xy, i32(_e63.z), vec2(4.0), vec2(4.0), vec2(5, 5)); c_3 = _e73; - _ = coord_9; let _e76 = coord_9; let _e81 = textureSampleLevel(tex2DArray, samp, _e76.xy, i32(_e76.z), 3.0); c_3 = _e81; - _ = coord_9; - _ = vec2(5); let _e86 = coord_9; - _ = vec2(5); let _e93 = textureSampleLevel(tex2DArray, samp, _e86.xy, i32(_e86.z), 3.0, vec2(5, 5)); c_3 = _e93; - _ = coord_9; - _ = vec2(5); let _e97 = coord_9; - _ = vec2(5); let _e103 = textureSample(tex2DArray, samp, _e97.xy, i32(_e97.z), vec2(5, 5)); c_3 = _e103; - _ = coord_9; - _ = vec2(5); let _e108 = coord_9; - _ = vec2(5); let _e115 = textureSampleBias(tex2DArray, samp, _e108.xy, i32(_e108.z), 2.0, vec2(5, 5)); c_3 = _e115; let _e116 = coord_9; - _ = vec3(_e116); let _e119 = coord_9; let _e120 = vec3(_e119); let _e124 = textureLoad(tex2DArray, _e120.xy, _e120.z, 3); c_3 = _e124; let _e125 = coord_9; - _ = vec3(_e125); - _ = vec2(5); let _e130 = coord_9; let _e131 = vec3(_e130); - _ = vec2(5); let _e137 = textureLoad(tex2DArray, _e131.xy, _e131.z, 3); c_3 = _e137; return; @@ -620,39 +456,23 @@ fn testTex2DArrayShadow(coord_10: vec3) { let _e23 = textureNumLayers(tex2DArrayShadow); size2DArrayShadow = vec3(vec3(_e20.x, _e20.y, _e23)); let _e28 = coord_11; - _ = vec4(_e28.x, _e28.y, _e28.z, 1.0); let _e34 = coord_11; let _e39 = vec4(_e34.x, _e34.y, _e34.z, 1.0); let _e44 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e39.xy, i32(_e39.z), _e39.w); d_1 = _e44; let _e45 = coord_11; - _ = vec4(_e45.x, _e45.y, _e45.z, 1.0); - _ = vec2(4.0); - _ = vec2(4.0); let _e55 = coord_11; let _e60 = vec4(_e55.x, _e55.y, _e55.z, 1.0); - _ = vec2(4.0); - _ = vec2(4.0); let _e69 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e60.xy, i32(_e60.z), _e60.w); d_1 = _e69; let _e70 = coord_11; - _ = vec4(_e70.x, _e70.y, _e70.z, 1.0); - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e82 = coord_11; let _e87 = vec4(_e82.x, _e82.y, _e82.z, 1.0); - _ = vec2(4.0); - _ = vec2(4.0); - _ = vec2(5); let _e98 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e87.xy, i32(_e87.z), _e87.w, vec2(5, 5)); d_1 = _e98; let _e99 = coord_11; - _ = vec4(_e99.x, _e99.y, _e99.z, 1.0); - _ = vec2(5); let _e107 = coord_11; let _e112 = vec4(_e107.x, _e107.y, _e107.z, 1.0); - _ = vec2(5); let _e119 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e112.xy, i32(_e112.z), _e112.w, vec2(5, 5)); d_1 = _e119; return; @@ -666,21 +486,15 @@ fn testTexCube(coord_12: vec3) { coord_13 = coord_12; let _e20 = textureDimensions(texCube, 0); sizeCube = vec2(_e20); - _ = coord_13; let _e25 = coord_13; let _e26 = textureSample(texCube, samp, _e25); c_4 = _e26; - _ = coord_13; let _e29 = coord_13; let _e31 = textureSampleBias(texCube, samp, _e29, 2.0); c_4 = _e31; - _ = coord_13; - _ = vec3(4.0); - _ = vec3(4.0); let _e37 = coord_13; let _e42 = textureSampleGrad(texCube, samp, _e37, vec3(4.0), vec3(4.0)); c_4 = _e42; - _ = coord_13; let _e45 = coord_13; let _e47 = textureSampleLevel(texCube, samp, _e45, 3.0); c_4 = _e47; @@ -696,19 +510,13 @@ fn testTexCubeShadow(coord_14: vec3) { let _e20 = textureDimensions(texCubeShadow, 0); sizeCubeShadow = vec2(_e20); let _e24 = coord_15; - _ = vec4(_e24.x, _e24.y, _e24.z, 1.0); let _e30 = coord_15; let _e35 = vec4(_e30.x, _e30.y, _e30.z, 1.0); let _e38 = textureSampleCompare(texCubeShadow, sampShadow, _e35.xyz, _e35.w); d_2 = _e38; let _e39 = coord_15; - _ = vec4(_e39.x, _e39.y, _e39.z, 1.0); - _ = vec3(4.0); - _ = vec3(4.0); let _e49 = coord_15; let _e54 = vec4(_e49.x, _e49.y, _e49.z, 1.0); - _ = vec3(4.0); - _ = vec3(4.0); let _e61 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e54.xyz, _e54.w); d_2 = _e61; return; @@ -723,21 +531,15 @@ fn testTexCubeArray(coord_16: vec4) { let _e20 = textureDimensions(texCubeArray, 0); let _e23 = textureNumLayers(texCubeArray); sizeCubeArray = vec3(vec3(_e20.x, _e20.y, _e23)); - _ = coord_17; let _e29 = coord_17; let _e33 = textureSample(texCubeArray, samp, _e29.xyz, i32(_e29.w)); c_5 = _e33; - _ = coord_17; let _e36 = coord_17; let _e41 = textureSampleBias(texCubeArray, samp, _e36.xyz, i32(_e36.w), 2.0); c_5 = _e41; - _ = coord_17; - _ = vec3(4.0); - _ = vec3(4.0); let _e47 = coord_17; let _e55 = textureSampleGrad(texCubeArray, samp, _e47.xyz, i32(_e47.w), vec3(4.0), vec3(4.0)); c_5 = _e55; - _ = coord_17; let _e58 = coord_17; let _e63 = textureSampleLevel(texCubeArray, samp, _e58.xyz, i32(_e58.w), 3.0); c_5 = _e63; @@ -753,7 +555,6 @@ fn testTexCubeArrayShadow(coord_18: vec4) { let _e20 = textureDimensions(texCubeArrayShadow, 0); let _e23 = textureNumLayers(texCubeArrayShadow); sizeCubeArrayShadow = vec3(vec3(_e20.x, _e20.y, _e23)); - _ = coord_19; let _e30 = coord_19; let _e35 = textureSampleCompare(texCubeArrayShadow, sampShadow, _e30.xyz, i32(_e30.w), 1.0); d_3 = _e35; @@ -768,120 +569,76 @@ fn testTex3D(coord_20: vec3) { coord_21 = coord_20; let _e20 = textureDimensions(tex3D, 0); size3D = vec3(_e20); - _ = coord_21; let _e25 = coord_21; let _e26 = textureSample(tex3D, samp, _e25); c_6 = _e26; - _ = coord_21; let _e29 = coord_21; let _e31 = textureSampleBias(tex3D, samp, _e29, 2.0); c_6 = _e31; let _e32 = coord_21; - _ = vec4(_e32.x, _e32.y, _e32.z, 6.0); let _e38 = coord_21; let _e43 = vec4(_e38.x, _e38.y, _e38.z, 6.0); let _e48 = textureSample(tex3D, samp, (_e43.xyz / vec3(_e43.w))); c_6 = _e48; let _e49 = coord_21; - _ = vec4(_e49.x, _e49.y, _e49.z, 6.0); let _e56 = coord_21; let _e61 = vec4(_e56.x, _e56.y, _e56.z, 6.0); let _e67 = textureSampleBias(tex3D, samp, (_e61.xyz / vec3(_e61.w)), 2.0); c_6 = _e67; let _e68 = coord_21; - _ = vec4(_e68.x, _e68.y, _e68.z, 6.0); - _ = vec3(5); let _e76 = coord_21; let _e81 = vec4(_e76.x, _e76.y, _e76.z, 6.0); - _ = vec3(5); let _e88 = textureSample(tex3D, samp, (_e81.xyz / vec3(_e81.w)), vec3(5, 5, 5)); c_6 = _e88; let _e89 = coord_21; - _ = vec4(_e89.x, _e89.y, _e89.z, 6.0); - _ = vec3(5); let _e98 = coord_21; let _e103 = vec4(_e98.x, _e98.y, _e98.z, 6.0); - _ = vec3(5); let _e111 = textureSampleBias(tex3D, samp, (_e103.xyz / vec3(_e103.w)), 2.0, vec3(5, 5, 5)); c_6 = _e111; let _e112 = coord_21; - _ = vec4(_e112.x, _e112.y, _e112.z, 6.0); let _e119 = coord_21; let _e124 = vec4(_e119.x, _e119.y, _e119.z, 6.0); let _e130 = textureSampleLevel(tex3D, samp, (_e124.xyz / vec3(_e124.w)), 3.0); c_6 = _e130; let _e131 = coord_21; - _ = vec4(_e131.x, _e131.y, _e131.z, 6.0); - _ = vec3(5); let _e140 = coord_21; let _e145 = vec4(_e140.x, _e140.y, _e140.z, 6.0); - _ = vec3(5); let _e153 = textureSampleLevel(tex3D, samp, (_e145.xyz / vec3(_e145.w)), 3.0, vec3(5, 5, 5)); c_6 = _e153; let _e154 = coord_21; - _ = vec4(_e154.x, _e154.y, _e154.z, 6.0); - _ = vec3(4.0); - _ = vec3(4.0); let _e164 = coord_21; let _e169 = vec4(_e164.x, _e164.y, _e164.z, 6.0); let _e178 = textureSampleGrad(tex3D, samp, (_e169.xyz / vec3(_e169.w)), vec3(4.0), vec3(4.0)); c_6 = _e178; let _e179 = coord_21; - _ = vec4(_e179.x, _e179.y, _e179.z, 6.0); - _ = vec3(4.0); - _ = vec3(4.0); - _ = vec3(5); let _e191 = coord_21; let _e196 = vec4(_e191.x, _e191.y, _e191.z, 6.0); - _ = vec3(5); let _e207 = textureSampleGrad(tex3D, samp, (_e196.xyz / vec3(_e196.w)), vec3(4.0), vec3(4.0), vec3(5, 5, 5)); c_6 = _e207; - _ = coord_21; - _ = vec3(4.0); - _ = vec3(4.0); let _e213 = coord_21; let _e218 = textureSampleGrad(tex3D, samp, _e213, vec3(4.0), vec3(4.0)); c_6 = _e218; - _ = coord_21; - _ = vec3(4.0); - _ = vec3(4.0); - _ = vec3(5); let _e226 = coord_21; - _ = vec3(5); let _e233 = textureSampleGrad(tex3D, samp, _e226, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); c_6 = _e233; - _ = coord_21; let _e236 = coord_21; let _e238 = textureSampleLevel(tex3D, samp, _e236, 3.0); c_6 = _e238; - _ = coord_21; - _ = vec3(5); let _e243 = coord_21; - _ = vec3(5); let _e247 = textureSampleLevel(tex3D, samp, _e243, 3.0, vec3(5, 5, 5)); c_6 = _e247; - _ = coord_21; - _ = vec3(5); let _e251 = coord_21; - _ = vec3(5); let _e254 = textureSample(tex3D, samp, _e251, vec3(5, 5, 5)); c_6 = _e254; - _ = coord_21; - _ = vec3(5); let _e259 = coord_21; - _ = vec3(5); let _e263 = textureSampleBias(tex3D, samp, _e259, 2.0, vec3(5, 5, 5)); c_6 = _e263; let _e264 = coord_21; - _ = vec3(_e264); let _e267 = coord_21; let _e270 = textureLoad(tex3D, vec3(_e267), 3); c_6 = _e270; let _e271 = coord_21; - _ = vec3(_e271); - _ = vec3(5); let _e276 = coord_21; - _ = vec3(5); let _e281 = textureLoad(tex3D, vec3(_e276), 3); c_6 = _e281; return; @@ -896,7 +653,6 @@ fn testTex2DMS(coord_22: vec2) { let _e18 = textureDimensions(tex2DMS); size2DMS = vec2(_e18); let _e22 = coord_23; - _ = vec2(_e22); let _e25 = coord_23; let _e28 = textureLoad(tex2DMS, vec2(_e25), 3); c_7 = _e28; @@ -913,7 +669,6 @@ fn testTex2DMSArray(coord_24: vec3) { let _e21 = textureNumLayers(tex2DMSArray); size2DMSArray = vec3(vec3(_e18.x, _e18.y, _e21)); let _e26 = coord_25; - _ = vec3(_e26); let _e29 = coord_25; let _e30 = vec3(_e29); let _e34 = textureLoad(tex2DMSArray, _e30.xy, _e30.z, 3); diff --git a/tests/out/wgsl/vector-functions-frag.wgsl b/tests/out/wgsl/vector-functions-frag.wgsl index f7dfdd15c..90b35f383 100644 --- a/tests/out/wgsl/vector-functions-frag.wgsl +++ b/tests/out/wgsl/vector-functions-frag.wgsl @@ -10,33 +10,21 @@ fn ftest(a: vec4, b: vec4) { a_1 = a; b_1 = b; - _ = a_1; - _ = b_1; let _e6 = a_1; let _e7 = b_1; c = (_e6 < _e7); - _ = a_1; - _ = b_1; let _e12 = a_1; let _e13 = b_1; d = (_e12 <= _e13); - _ = a_1; - _ = b_1; let _e18 = a_1; let _e19 = b_1; e = (_e18 > _e19); - _ = a_1; - _ = b_1; let _e24 = a_1; let _e25 = b_1; f = (_e24 >= _e25); - _ = a_1; - _ = b_1; let _e30 = a_1; let _e31 = b_1; g = (_e30 == _e31); - _ = a_1; - _ = b_1; let _e36 = a_1; let _e37 = b_1; h = (_e36 != _e37); @@ -55,33 +43,21 @@ fn dtest(a_2: vec4, b_2: vec4) { a_3 = a_2; b_3 = b_2; - _ = a_3; - _ = b_3; let _e6 = a_3; let _e7 = b_3; c_1 = (_e6 < _e7); - _ = a_3; - _ = b_3; let _e12 = a_3; let _e13 = b_3; d_1 = (_e12 <= _e13); - _ = a_3; - _ = b_3; let _e18 = a_3; let _e19 = b_3; e_1 = (_e18 > _e19); - _ = a_3; - _ = b_3; let _e24 = a_3; let _e25 = b_3; f_1 = (_e24 >= _e25); - _ = a_3; - _ = b_3; let _e30 = a_3; let _e31 = b_3; g_1 = (_e30 == _e31); - _ = a_3; - _ = b_3; let _e36 = a_3; let _e37 = b_3; h_1 = (_e36 != _e37); @@ -100,33 +76,21 @@ fn itest(a_4: vec4, b_4: vec4) { a_5 = a_4; b_5 = b_4; - _ = a_5; - _ = b_5; let _e6 = a_5; let _e7 = b_5; c_2 = (_e6 < _e7); - _ = a_5; - _ = b_5; let _e12 = a_5; let _e13 = b_5; d_2 = (_e12 <= _e13); - _ = a_5; - _ = b_5; let _e18 = a_5; let _e19 = b_5; e_2 = (_e18 > _e19); - _ = a_5; - _ = b_5; let _e24 = a_5; let _e25 = b_5; f_2 = (_e24 >= _e25); - _ = a_5; - _ = b_5; let _e30 = a_5; let _e31 = b_5; g_2 = (_e30 == _e31); - _ = a_5; - _ = b_5; let _e36 = a_5; let _e37 = b_5; h_2 = (_e36 != _e37); @@ -145,33 +109,21 @@ fn utest(a_6: vec4, b_6: vec4) { a_7 = a_6; b_7 = b_6; - _ = a_7; - _ = b_7; let _e6 = a_7; let _e7 = b_7; c_3 = (_e6 < _e7); - _ = a_7; - _ = b_7; let _e12 = a_7; let _e13 = b_7; d_3 = (_e12 <= _e13); - _ = a_7; - _ = b_7; let _e18 = a_7; let _e19 = b_7; e_3 = (_e18 > _e19); - _ = a_7; - _ = b_7; let _e24 = a_7; let _e25 = b_7; f_3 = (_e24 >= _e25); - _ = a_7; - _ = b_7; let _e30 = a_7; let _e31 = b_7; g_3 = (_e30 == _e31); - _ = a_7; - _ = b_7; let _e36 = a_7; let _e37 = b_7; h_3 = (_e36 != _e37); @@ -189,23 +141,16 @@ fn btest(a_8: vec4, b_8: vec4) { a_9 = a_8; b_9 = b_8; - _ = a_9; - _ = b_9; let _e6 = a_9; let _e7 = b_9; c_4 = (_e6 == _e7); - _ = a_9; - _ = b_9; let _e12 = a_9; let _e13 = b_9; d_4 = (_e12 != _e13); - _ = a_9; let _e17 = a_9; e_4 = any(_e17); - _ = a_9; let _e21 = a_9; f_4 = all(_e21); - _ = a_9; let _e25 = a_9; g_4 = !(_e25); return; From 76003dc0035d53a474d366dcdf49d2e4d12e921f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 13 Jun 2023 20:31:06 +0200 Subject: [PATCH 2020/2212] remove unnecessary macro parameters --- src/back/hlsl/keywords.rs | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/src/back/hlsl/keywords.rs b/src/back/hlsl/keywords.rs index eb358f31b..81b797bbf 100644 --- a/src/back/hlsl/keywords.rs +++ b/src/back/hlsl/keywords.rs @@ -825,50 +825,48 @@ pub const TYPES: &[&str] = &{ /// For each scalar type, it will additionally generate vector and matrix shorthands macro_rules! generate { - ($a:ident, $i:ident, [$($roots:literal),*], $x:tt) => { + ([$($roots:literal),*], $x:tt) => { $( - generate!(@inner push $a, $i, $roots); - generate!(@inner $a, $i, $roots, $x); + generate!(@inner push $roots); + generate!(@inner $roots, $x); )* }; - (@inner $a:ident, $i:ident, $root:literal, [$($x:literal),*]) => { - generate!(@inner vector $a, $i, $root, $($x)*); - generate!(@inner matrix $a, $i, $root, $($x)*); + (@inner $root:literal, [$($x:literal),*]) => { + generate!(@inner vector $root, $($x)*); + generate!(@inner matrix $root, $($x)*); }; - (@inner vector $a:ident, $i:ident, $root:literal, $($x:literal)*) => { + (@inner vector $root:literal, $($x:literal)*) => { $( - generate!(@inner push $a, $i, concat!($root, $x)); + generate!(@inner push concat!($root, $x)); )* }; - (@inner matrix $a:ident, $i:ident, $root:literal, $($x:literal)*) => { + (@inner matrix $root:literal, $($x:literal)*) => { // Duplicate the list - generate!(@inner matrix $a, $i, $root, $($x)*; $($x)*); + generate!(@inner matrix $root, $($x)*; $($x)*); }; // The head/tail recursion: pick the first element of the first list and recursively do it for the tail. - (@inner matrix $a:ident, $i:ident, $root:literal, $head:literal $($tail:literal)*; $($x:literal)*) => { + (@inner matrix $root:literal, $head:literal $($tail:literal)*; $($x:literal)*) => { $( - generate!(@inner push $a, $i, concat!($root, $head, "x", $x)); + generate!(@inner push concat!($root, $head, "x", $x)); )* - generate!(@inner matrix $a, $i, $root, $($tail)*; $($x)*); + generate!(@inner matrix $root, $($tail)*; $($x)*); }; // The end of iteration: we exhausted the list - (@inner matrix $a:ident, $i:ident, $root:literal, ; $($x:literal)*) => {}; + (@inner matrix $root:literal, ; $($x:literal)*) => {}; - (@inner push $a:ident, $i:ident, $v:expr) => { - $a[$i] = $v; - $i += 1; + (@inner push $v:expr) => { + res[c] = $v; + c += 1; }; } generate!( - res, - c, [ "bool", "int", From b7da0057a09ff9f1f45a7931e6dc0c8f9aed12d9 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 15 Jun 2023 05:40:13 -0700 Subject: [PATCH 2021/2212] Don't `use std::opsIndex`, used only when `"validate"` is on. (#2383) In `src/valid/expresion.rs`, use the full path `std::ops::Index` when implementing the trait on `ExpressionTypeResolver`. This implementation is `#[cfg(feature = "validate")]`, so the `use` directive becomes unnecessary when that feature is not enabled, triggering warnings. --- src/valid/expression.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 0cf40c232..071c1a499 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,5 +1,3 @@ -use std::ops::Index; - #[cfg(feature = "validate")] use super::{ compose::validate_compose, validate_atomic_compare_exchange_struct, FunctionInfo, ShaderStages, @@ -134,7 +132,7 @@ struct ExpressionTypeResolver<'a> { } #[cfg(feature = "validate")] -impl<'a> Index> for ExpressionTypeResolver<'a> { +impl<'a> std::ops::Index> for ExpressionTypeResolver<'a> { type Output = crate::TypeInner; #[allow(clippy::panic)] From 304ba5805c5d0ecf7e3be1a1549355282e9223f8 Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Tue, 13 Jun 2023 23:05:24 +0300 Subject: [PATCH 2022/2212] [glsl-out] Fix functions with array return type --- src/back/glsl/mod.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index d5fc89bca..b7384af73 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1390,6 +1390,9 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "void")?; } else if let Some(ref result) = func.result { self.write_type(result.ty)?; + if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner { + self.write_array_size(base, size)? + } } else { write!(self.out, "void")?; } @@ -2154,7 +2157,12 @@ impl<'a, W: Write> Writer<'a, W> { let name = format!("{}{}", back::BAKE_PREFIX, expr.index()); let result = self.module.functions[function].result.as_ref().unwrap(); self.write_type(result.ty)?; - write!(self.out, " {name} = ")?; + write!(self.out, " {name}")?; + if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner + { + self.write_array_size(base, size)? + } + write!(self.out, " = ")?; self.named_expressions.insert(expr, name); } write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?; From f31093fb3b0c8183069037fcac99a90d3adef2bd Mon Sep 17 00:00:00 2001 From: Igor Shaposhnik Date: Wed, 14 Jun 2023 22:41:43 +0300 Subject: [PATCH 2023/2212] Add array-in-function-return-type test --- .../array-in-function-return-type.param.ron | 2 + tests/in/array-in-function-return-type.wgsl | 9 ++++ ...in-function-return-type.main.Fragment.glsl | 17 +++++++ .../out/msl/array-in-function-return-type.msl | 23 ++++++++++ .../spv/array-in-function-return-type.spvasm | 44 +++++++++++++++++++ .../wgsl/array-in-function-return-type.wgsl | 9 ++++ tests/snapshots.rs | 5 +++ 7 files changed, 109 insertions(+) create mode 100644 tests/in/array-in-function-return-type.param.ron create mode 100644 tests/in/array-in-function-return-type.wgsl create mode 100644 tests/out/glsl/array-in-function-return-type.main.Fragment.glsl create mode 100644 tests/out/msl/array-in-function-return-type.msl create mode 100644 tests/out/spv/array-in-function-return-type.spvasm create mode 100644 tests/out/wgsl/array-in-function-return-type.wgsl diff --git a/tests/in/array-in-function-return-type.param.ron b/tests/in/array-in-function-return-type.param.ron new file mode 100644 index 000000000..72873dd66 --- /dev/null +++ b/tests/in/array-in-function-return-type.param.ron @@ -0,0 +1,2 @@ +( +) diff --git a/tests/in/array-in-function-return-type.wgsl b/tests/in/array-in-function-return-type.wgsl new file mode 100644 index 000000000..21e2012e7 --- /dev/null +++ b/tests/in/array-in-function-return-type.wgsl @@ -0,0 +1,9 @@ +fn ret_array() -> array { + return array(1.0, 2.0); +} + +@fragment +fn main() -> @location(0) vec4 { + let a = ret_array(); + return vec4(a[0], a[1], 0.0, 1.0); +} diff --git a/tests/out/glsl/array-in-function-return-type.main.Fragment.glsl b/tests/out/glsl/array-in-function-return-type.main.Fragment.glsl new file mode 100644 index 000000000..45fc31a62 --- /dev/null +++ b/tests/out/glsl/array-in-function-return-type.main.Fragment.glsl @@ -0,0 +1,17 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(location = 0) out vec4 _fs2p_location0; + +float[2] ret_array() { + return float[2](1.0, 2.0); +} + +void main() { + float _e0[2] = ret_array(); + _fs2p_location0 = vec4(_e0[0], _e0[1], 0.0, 1.0); + return; +} + diff --git a/tests/out/msl/array-in-function-return-type.msl b/tests/out/msl/array-in-function-return-type.msl new file mode 100644 index 000000000..c2c2379cc --- /dev/null +++ b/tests/out/msl/array-in-function-return-type.msl @@ -0,0 +1,23 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct type_1 { + float inner[2]; +}; + +type_1 ret_array( +) { + return type_1 {1.0, 2.0}; +} + +struct main_Output { + metal::float4 member [[color(0)]]; +}; +fragment main_Output main_( +) { + type_1 _e0 = ret_array(); + return main_Output { metal::float4(_e0.inner[0], _e0.inner[1], 0.0, 1.0) }; +} diff --git a/tests/out/spv/array-in-function-return-type.spvasm b/tests/out/spv/array-in-function-return-type.spvasm new file mode 100644 index 000000000..e70434025 --- /dev/null +++ b/tests/out/spv/array-in-function-return-type.spvasm @@ -0,0 +1,44 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 28 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %20 "main" %18 +OpExecutionMode %20 OriginUpperLeft +OpDecorate %6 ArrayStride 4 +OpDecorate %18 Location 0 +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpConstant %4 2 +%5 = OpTypeFloat 32 +%8 = OpTypeInt 32 0 +%7 = OpConstant %8 2 +%6 = OpTypeArray %5 %7 +%9 = OpTypeVector %5 4 +%12 = OpTypeFunction %6 +%13 = OpConstant %5 1.0 +%14 = OpConstant %5 2.0 +%19 = OpTypePointer Output %9 +%18 = OpVariable %19 Output +%21 = OpTypeFunction %2 +%22 = OpConstant %5 0.0 +%11 = OpFunction %6 None %12 +%10 = OpLabel +OpBranch %15 +%15 = OpLabel +%16 = OpCompositeConstruct %6 %13 %14 +OpReturnValue %16 +OpFunctionEnd +%20 = OpFunction %2 None %21 +%17 = OpLabel +OpBranch %23 +%23 = OpLabel +%24 = OpFunctionCall %6 %11 +%25 = OpCompositeExtract %5 %24 0 +%26 = OpCompositeExtract %5 %24 1 +%27 = OpCompositeConstruct %9 %25 %26 %22 %13 +OpStore %18 %27 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/array-in-function-return-type.wgsl b/tests/out/wgsl/array-in-function-return-type.wgsl new file mode 100644 index 000000000..2d5b1e84a --- /dev/null +++ b/tests/out/wgsl/array-in-function-return-type.wgsl @@ -0,0 +1,9 @@ +fn ret_array() -> array { + return array(1.0, 2.0); +} + +@fragment +fn main() -> @location(0) vec4 { + let _e0 = ret_array(); + return vec4(_e0[0], _e0[1], 0.0, 1.0); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1ea52b46c..2aab4f29f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -401,10 +401,15 @@ fn convert_wgsl() { let root = env!("CARGO_MANIFEST_DIR"); let inputs = [ + // TODO: merge array-in-ctor and array-in-function-return-type tests after fix HLSL issue https://github.com/gfx-rs/naga/issues/1930 ( "array-in-ctor", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ( + "array-in-function-return-type", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + ), ( "empty", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, From f915d39a87874862d8e31523e2057b292bf21d6d Mon Sep 17 00:00:00 2001 From: Eduard-Mihai Burtescu Date: Wed, 21 Jun 2023 23:14:00 +0300 Subject: [PATCH 2024/2212] [spv-out] Use `IndexSet` instead of `HashSet` for iterated sets (capabilities/extensions). --- src/back/spv/mod.rs | 4 ++-- src/back/spv/recyclable.rs | 7 +++++++ src/back/spv/writer.rs | 6 +++--- src/lib.rs | 5 +++++ tests/out/spv/bounds-check-image-restrict.spvasm | 4 ++-- tests/out/spv/bounds-check-image-rzsw.spvasm | 4 ++-- tests/out/spv/image.spvasm | 6 +++--- tests/out/spv/ray-query.spvasm | 2 +- tests/spirv-capabilities.rs | 6 +++--- 9 files changed, 28 insertions(+), 16 deletions(-) diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 1e10d2e9c..642c0c7d1 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -595,10 +595,10 @@ pub struct Writer { /// /// If `capabilities_available` is `Some`, then this is always a subset of /// that. - capabilities_used: crate::FastHashSet, + capabilities_used: crate::FastIndexSet, /// The set of spirv extensions used. - extensions_used: crate::FastHashSet<&'static str>, + extensions_used: crate::FastIndexSet<&'static str>, debugs: Vec, annotations: Vec, diff --git a/src/back/spv/recyclable.rs b/src/back/spv/recyclable.rs index 49f3a0274..cd1466e3c 100644 --- a/src/back/spv/recyclable.rs +++ b/src/back/spv/recyclable.rs @@ -52,6 +52,13 @@ impl Recyclable for std::collections::HashSet { } } +impl Recyclable for indexmap::IndexSet { + fn recycle(mut self) -> Self { + self.clear(); + self + } +} + impl Recyclable for std::collections::BTreeMap { fn recycle(mut self) -> Self { self.clear(); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 64e27fae1..4a1bc8ff2 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -47,7 +47,7 @@ impl Writer { } let raw_version = ((major as u32) << 16) | ((minor as u32) << 8); - let mut capabilities_used = crate::FastHashSet::default(); + let mut capabilities_used = crate::FastIndexSet::default(); capabilities_used.insert(spirv::Capability::Shader); let mut id_gen = IdGenerator::default(); @@ -60,7 +60,7 @@ impl Writer { id_gen, capabilities_available: options.capabilities.clone(), capabilities_used, - extensions_used: crate::FastHashSet::default(), + extensions_used: crate::FastIndexSet::default(), debugs: vec![], annotations: vec![], flags: options.flags, @@ -1936,7 +1936,7 @@ impl Writer { } /// Return the set of capabilities the last module written used. - pub const fn get_capabilities_used(&self) -> &crate::FastHashSet { + pub const fn get_capabilities_used(&self) -> &crate::FastIndexSet { &self.capabilities_used } diff --git a/src/lib.rs b/src/lib.rs index 7ac59be50..2d50e7434 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -254,6 +254,11 @@ pub type FastHashMap = rustc_hash::FxHashMap; /// Hash set that is faster but not resilient to DoS attacks. pub type FastHashSet = rustc_hash::FxHashSet; +/// Insertion-order-preserving hash set (`IndexSet`), but with the same +/// hasher as `FastHashSet` (faster but not resilient to DoS attacks). +pub type FastIndexSet = + indexmap::IndexSet>; + /// Map of expressions that have associated variable names pub(crate) type NamedExpressions = indexmap::IndexMap< Handle, diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index bfddef393..c88421004 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -2,10 +2,10 @@ ; Version: 1.1 ; Generator: rspirv ; Bound: 310 -OpCapability ImageQuery -OpCapability Image1D OpCapability Shader OpCapability Sampled1D +OpCapability Image1D +OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %269 "fragment_shader" %267 diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index 6228f45f9..e5e12fabd 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -2,10 +2,10 @@ ; Version: 1.1 ; Generator: rspirv ; Bound: 347 -OpCapability ImageQuery -OpCapability Image1D OpCapability Shader OpCapability Sampled1D +OpCapability Image1D +OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %306 "fragment_shader" %304 diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 7b9aa5ed6..6b94b3e27 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -2,11 +2,11 @@ ; Version: 1.1 ; Generator: rspirv ; Bound: 546 +OpCapability Shader +OpCapability Image1D +OpCapability Sampled1D OpCapability SampledCubeArray OpCapability ImageQuery -OpCapability Image1D -OpCapability Shader -OpCapability Sampled1D %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %82 "main" %79 diff --git a/tests/out/spv/ray-query.spvasm b/tests/out/spv/ray-query.spvasm index 03a43966e..2445b3169 100644 --- a/tests/out/spv/ray-query.spvasm +++ b/tests/out/spv/ray-query.spvasm @@ -2,8 +2,8 @@ ; Version: 1.4 ; Generator: rspirv ; Bound: 95 -OpCapability RayQueryKHR OpCapability Shader +OpCapability RayQueryKHR OpExtension "SPV_KHR_ray_query" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs index 254590928..f26918285 100644 --- a/tests/spirv-capabilities.rs +++ b/tests/spirv-capabilities.rs @@ -6,7 +6,7 @@ Test SPIR-V backend capability checks. use spirv::Capability as Ca; -fn capabilities_used(source: &str) -> naga::FastHashSet { +fn capabilities_used(source: &str) -> naga::FastIndexSet { use naga::back::spv; use naga::valid; @@ -36,7 +36,7 @@ fn require_and_forbid(required: &[Ca], forbidden: &[Ca], source: &str) { let missing_caps: Vec<_> = required .iter() - .filter(|cap| !caps_used.contains(cap)) + .filter(|&cap| !caps_used.contains(cap)) .cloned() .collect(); if !missing_caps.is_empty() { @@ -45,7 +45,7 @@ fn require_and_forbid(required: &[Ca], forbidden: &[Ca], source: &str) { let forbidden_caps: Vec<_> = forbidden .iter() - .filter(|cap| caps_used.contains(cap)) + .filter(|&cap| caps_used.contains(cap)) .cloned() .collect(); if !forbidden_caps.is_empty() { From ffe2308a6008eeb998b44a913e66ecff9a58b4d4 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Thu, 22 Jun 2023 15:36:54 +0200 Subject: [PATCH 2025/2212] rename `allow_point_size` to `allow_and_force_point_size` (#2280) --- src/back/msl/mod.rs | 9 ++++++--- src/back/msl/writer.rs | 8 ++++---- tests/in/interface.param.ron | 2 +- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 3174d4b75..78bcc2123 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -210,10 +210,13 @@ impl Default for Options { #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct PipelineOptions { - /// Allow `BuiltIn::PointSize` in the vertex shader. + /// Allow `BuiltIn::PointSize` and inject it if doesn't exist. /// - /// Metal doesn't like this for non-point primitive topologies. - pub allow_point_size: bool, + /// Metal doesn't like this for non-point primitive topologies and requires it for + /// point primitive topologies. + /// + /// Enable this for vertex shaders with point primitive topologies. + pub allow_and_force_point_size: bool, } impl Options { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 22a5f56b7..a9551dc71 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2321,7 +2321,7 @@ impl Writer { member.binding { has_point_size = true; - if !context.pipeline_options.allow_point_size { + if !context.pipeline_options.allow_and_force_point_size { continue; } } @@ -2358,7 +2358,7 @@ impl Writer { if let FunctionOrigin::EntryPoint(ep_index) = context.origin { let stage = context.module.entry_points[ep_index as usize].stage; - if context.pipeline_options.allow_point_size + if context.pipeline_options.allow_and_force_point_size && stage == crate::ShaderStage::Vertex && !has_point_size { @@ -3769,7 +3769,7 @@ impl Writer { if let crate::Binding::BuiltIn(crate::BuiltIn::PointSize) = *binding { has_point_size = true; - if !pipeline_options.allow_point_size { + if !pipeline_options.allow_and_force_point_size { continue; } } @@ -3790,7 +3790,7 @@ impl Writer { writeln!(self.out, ";")?; } - if pipeline_options.allow_point_size + if pipeline_options.allow_and_force_point_size && ep.stage == crate::ShaderStage::Vertex && !has_point_size { diff --git a/tests/in/interface.param.ron b/tests/in/interface.param.ron index 1c910d2b8..4d8566176 100644 --- a/tests/in/interface.param.ron +++ b/tests/in/interface.param.ron @@ -26,6 +26,6 @@ zero_initialize_workgroup_memory: true, ), msl_pipeline: ( - allow_point_size: true, + allow_and_force_point_size: true, ), ) From adf1cca68d936b3c5a2872579ea8b6c68690137e Mon Sep 17 00:00:00 2001 From: Elabajaba Date: Fri, 23 Jun 2023 09:52:22 -0400 Subject: [PATCH 2026/2212] Implement Pack/Unpack for HLSL (#2353) --- src/back/hlsl/writer.rs | 233 +++++++++++++++++++++++++++++++- src/proc/mod.rs | 11 ++ tests/out/hlsl/bits.hlsl | 131 ++++++++++++++++++ tests/out/hlsl/bits.hlsl.config | 3 + tests/out/hlsl/bits.ron | 12 ++ tests/snapshots.rs | 2 +- 6 files changed, 389 insertions(+), 3 deletions(-) create mode 100644 tests/out/hlsl/bits.hlsl create mode 100644 tests/out/hlsl/bits.hlsl.config create mode 100644 tests/out/hlsl/bits.ron diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 45c0a464a..ec99c9744 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -122,14 +122,41 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.need_bake_expressions.insert(fun_handle); } - if let Expression::Math { fun, arg, .. } = *expr { + if let Expression::Math { + fun, + arg, + arg1, + arg2, + arg3, + } = *expr + { match fun { crate::MathFunction::Asinh | crate::MathFunction::Acosh | crate::MathFunction::Atanh - | crate::MathFunction::Unpack2x16float => { + | crate::MathFunction::Unpack2x16float + | crate::MathFunction::Unpack2x16snorm + | crate::MathFunction::Unpack2x16unorm + | crate::MathFunction::Unpack4x8snorm + | crate::MathFunction::Unpack4x8unorm + | crate::MathFunction::Pack2x16float + | crate::MathFunction::Pack2x16snorm + | crate::MathFunction::Pack2x16unorm + | crate::MathFunction::Pack4x8snorm + | crate::MathFunction::Pack4x8unorm => { self.need_bake_expressions.insert(arg); } + crate::MathFunction::ExtractBits => { + self.need_bake_expressions.insert(arg); + self.need_bake_expressions.insert(arg1.unwrap()); + self.need_bake_expressions.insert(arg2.unwrap()); + } + crate::MathFunction::InsertBits => { + self.need_bake_expressions.insert(arg); + self.need_bake_expressions.insert(arg1.unwrap()); + self.need_bake_expressions.insert(arg2.unwrap()); + self.need_bake_expressions.insert(arg3.unwrap()); + } crate::MathFunction::CountLeadingZeros => { let inner = info[fun_handle].ty.inner_with(&module.types); if let Some(crate::ScalarKind::Sint) = inner.scalar_kind() { @@ -2589,7 +2616,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { enum Function { Asincosh { is_sin: bool }, Atanh, + ExtractBits, + InsertBits, + Pack2x16float, + Pack2x16snorm, + Pack2x16unorm, + Pack4x8snorm, + Pack4x8unorm, Unpack2x16float, + Unpack2x16snorm, + Unpack2x16unorm, + Unpack4x8snorm, + Unpack4x8unorm, Regular(&'static str), MissingIntOverload(&'static str), MissingIntReturnType(&'static str), @@ -2663,7 +2701,20 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::ReverseBits => Function::MissingIntOverload("reversebits"), Mf::FindLsb => Function::MissingIntReturnType("firstbitlow"), Mf::FindMsb => Function::MissingIntReturnType("firstbithigh"), + Mf::ExtractBits => Function::ExtractBits, + Mf::InsertBits => Function::InsertBits, + // Data Packing + Mf::Pack2x16float => Function::Pack2x16float, + Mf::Pack2x16snorm => Function::Pack2x16snorm, + Mf::Pack2x16unorm => Function::Pack2x16unorm, + Mf::Pack4x8snorm => Function::Pack4x8snorm, + Mf::Pack4x8unorm => Function::Pack4x8unorm, + // Data Unpacking Mf::Unpack2x16float => Function::Unpack2x16float, + Mf::Unpack2x16snorm => Function::Unpack2x16snorm, + Mf::Unpack2x16unorm => Function::Unpack2x16unorm, + Mf::Unpack4x8snorm => Function::Unpack4x8snorm, + Mf::Unpack4x8unorm => Function::Unpack4x8unorm, _ => return Err(Error::Unimplemented(format!("write_expr_math {fun:?}"))), }; @@ -2687,6 +2738,140 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, arg, func_ctx)?; write!(self.out, "))")?; } + Function::ExtractBits => { + // e: T, + // offset: u32, + // count: u32 + // T is u32 or i32 or vecN or vecN + if let (Some(offset), Some(count)) = (arg1, arg2) { + let scalar_width: u8 = 32; + // Works for signed and unsigned + // (count == 0 ? 0 : (e << (32 - count - offset)) >> (32 - count)) + write!(self.out, "(")?; + self.write_expr(module, count, func_ctx)?; + write!(self.out, " == 0 ? 0 : (")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " << ({scalar_width} - ")?; + self.write_expr(module, count, func_ctx)?; + write!(self.out, " - ")?; + self.write_expr(module, offset, func_ctx)?; + write!(self.out, ")) >> ({scalar_width} - ")?; + self.write_expr(module, count, func_ctx)?; + write!(self.out, "))")?; + } + } + Function::InsertBits => { + // e: T, + // newbits: T, + // offset: u32, + // count: u32 + // returns T + // T is i32, u32, vecN, or vecN + if let (Some(newbits), Some(offset), Some(count)) = (arg1, arg2, arg3) { + let scalar_width: u8 = 32; + let scalar_max: u32 = 0xFFFFFFFF; + // mask = ((0xFFFFFFFFu >> (32 - count)) << offset) + // (count == 0 ? e : ((e & ~mask) | ((newbits << offset) & mask))) + write!(self.out, "(")?; + self.write_expr(module, count, func_ctx)?; + write!(self.out, " == 0 ? ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " : ")?; + write!(self.out, "(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " & ~")?; + // mask + write!(self.out, "(({scalar_max}u >> ({scalar_width}u - ")?; + self.write_expr(module, count, func_ctx)?; + write!(self.out, ")) << ")?; + self.write_expr(module, offset, func_ctx)?; + write!(self.out, ")")?; + // end mask + write!(self.out, ") | ((")?; + self.write_expr(module, newbits, func_ctx)?; + write!(self.out, " << ")?; + self.write_expr(module, offset, func_ctx)?; + write!(self.out, ") & ")?; + // // mask + write!(self.out, "(({scalar_max}u >> ({scalar_width}u - ")?; + self.write_expr(module, count, func_ctx)?; + write!(self.out, ")) << ")?; + self.write_expr(module, offset, func_ctx)?; + write!(self.out, ")")?; + // // end mask + write!(self.out, "))")?; + } + } + Function::Pack2x16float => { + write!(self.out, "(f32tof16(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "[0]) | f32tof16(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "[1]) << 16)")?; + } + Function::Pack2x16snorm => { + let scale = 32767; + + write!(self.out, "uint((int(round(clamp(")?; + self.write_expr(module, arg, func_ctx)?; + write!( + self.out, + "[0], -1.0, 1.0) * {scale}.0)) & 0xFFFF) | ((int(round(clamp(" + )?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "[1], -1.0, 1.0) * {scale}.0)) & 0xFFFF) << 16))",)?; + } + Function::Pack2x16unorm => { + let scale = 65535; + + write!(self.out, "(uint(round(clamp(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "[0], 0.0, 1.0) * {scale}.0)) | uint(round(clamp(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "[1], 0.0, 1.0) * {scale}.0)) << 16)")?; + } + Function::Pack4x8snorm => { + let scale = 127; + + write!(self.out, "uint((int(round(clamp(")?; + self.write_expr(module, arg, func_ctx)?; + write!( + self.out, + "[0], -1.0, 1.0) * {scale}.0)) & 0xFF) | ((int(round(clamp(" + )?; + self.write_expr(module, arg, func_ctx)?; + write!( + self.out, + "[1], -1.0, 1.0) * {scale}.0)) & 0xFF) << 8) | ((int(round(clamp(" + )?; + self.write_expr(module, arg, func_ctx)?; + write!( + self.out, + "[2], -1.0, 1.0) * {scale}.0)) & 0xFF) << 16) | ((int(round(clamp(" + )?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "[3], -1.0, 1.0) * {scale}.0)) & 0xFF) << 24))",)?; + } + Function::Pack4x8unorm => { + let scale = 255; + + write!(self.out, "(uint(round(clamp(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "[0], 0.0, 1.0) * {scale}.0)) | uint(round(clamp(")?; + self.write_expr(module, arg, func_ctx)?; + write!( + self.out, + "[1], 0.0, 1.0) * {scale}.0)) << 8 | uint(round(clamp(" + )?; + self.write_expr(module, arg, func_ctx)?; + write!( + self.out, + "[2], 0.0, 1.0) * {scale}.0)) << 16 | uint(round(clamp(" + )?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, "[3], 0.0, 1.0) * {scale}.0)) << 24)")?; + } + Function::Unpack2x16float => { write!(self.out, "float2(f16tof32(")?; self.write_expr(module, arg, func_ctx)?; @@ -2694,6 +2879,50 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, arg, func_ctx)?; write!(self.out, ") >> 16))")?; } + Function::Unpack2x16snorm => { + let scale = 32767; + + write!(self.out, "(float2(int2(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " << 16, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ") >> 16) / {scale}.0)")?; + } + Function::Unpack2x16unorm => { + let scale = 65535; + + write!(self.out, "(float2(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " & 0xFFFF, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " >> 16) / {scale}.0)")?; + } + Function::Unpack4x8snorm => { + let scale = 127; + + write!(self.out, "(float4(int4(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " << 24, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " << 16, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " << 8, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ") >> 24) / {scale}.0)")?; + } + Function::Unpack4x8unorm => { + let scale = 255; + + write!(self.out, "(float4(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " & 0xFF, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " >> 8 & 0xFF, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " >> 16 & 0xFF, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " >> 24) / {scale}.0)")?; + } Function::Regular(fun_name) => { write!(self.out, "{fun_name}(")?; self.write_expr(module, arg, func_ctx)?; diff --git a/src/proc/mod.rs b/src/proc/mod.rs index ddcca263c..c61fbdd93 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -190,6 +190,17 @@ impl super::TypeInner { } } + pub const fn scalar_width(&self) -> Option { + // Multiply by 8 to get the bit width + match *self { + super::TypeInner::Scalar { width, .. } | super::TypeInner::Vector { width, .. } => { + Some(width * 8) + } + super::TypeInner::Matrix { width, .. } => Some(width * 8), + _ => None, + } + } + pub const fn pointer_space(&self) -> Option { match *self { Self::Pointer { space, .. } => Some(space), diff --git a/tests/out/hlsl/bits.hlsl b/tests/out/hlsl/bits.hlsl new file mode 100644 index 000000000..425738067 --- /dev/null +++ b/tests/out/hlsl/bits.hlsl @@ -0,0 +1,131 @@ + +[numthreads(1, 1, 1)] +void main() +{ + int i = (int)0; + int2 i2_ = (int2)0; + int3 i3_ = (int3)0; + int4 i4_ = (int4)0; + uint u = (uint)0; + uint2 u2_ = (uint2)0; + uint3 u3_ = (uint3)0; + uint4 u4_ = (uint4)0; + float2 f2_ = (float2)0; + float4 f4_ = (float4)0; + + i = 0; + i2_ = (0).xx; + i3_ = (0).xxx; + i4_ = (0).xxxx; + u = 0u; + u2_ = (0u).xx; + u3_ = (0u).xxx; + u4_ = (0u).xxxx; + f2_ = (0.0).xx; + f4_ = (0.0).xxxx; + float4 _expr28 = f4_; + u = uint((int(round(clamp(_expr28[0], -1.0, 1.0) * 127.0)) & 0xFF) | ((int(round(clamp(_expr28[1], -1.0, 1.0) * 127.0)) & 0xFF) << 8) | ((int(round(clamp(_expr28[2], -1.0, 1.0) * 127.0)) & 0xFF) << 16) | ((int(round(clamp(_expr28[3], -1.0, 1.0) * 127.0)) & 0xFF) << 24)); + float4 _expr30 = f4_; + u = (uint(round(clamp(_expr30[0], 0.0, 1.0) * 255.0)) | uint(round(clamp(_expr30[1], 0.0, 1.0) * 255.0)) << 8 | uint(round(clamp(_expr30[2], 0.0, 1.0) * 255.0)) << 16 | uint(round(clamp(_expr30[3], 0.0, 1.0) * 255.0)) << 24); + float2 _expr32 = f2_; + u = uint((int(round(clamp(_expr32[0], -1.0, 1.0) * 32767.0)) & 0xFFFF) | ((int(round(clamp(_expr32[1], -1.0, 1.0) * 32767.0)) & 0xFFFF) << 16)); + float2 _expr34 = f2_; + u = (uint(round(clamp(_expr34[0], 0.0, 1.0) * 65535.0)) | uint(round(clamp(_expr34[1], 0.0, 1.0) * 65535.0)) << 16); + float2 _expr36 = f2_; + u = (f32tof16(_expr36[0]) | f32tof16(_expr36[1]) << 16); + uint _expr38 = u; + f4_ = (float4(int4(_expr38 << 24, _expr38 << 16, _expr38 << 8, _expr38) >> 24) / 127.0); + uint _expr40 = u; + f4_ = (float4(_expr40 & 0xFF, _expr40 >> 8 & 0xFF, _expr40 >> 16 & 0xFF, _expr40 >> 24) / 255.0); + uint _expr42 = u; + f2_ = (float2(int2(_expr42 << 16, _expr42) >> 16) / 32767.0); + uint _expr44 = u; + f2_ = (float2(_expr44 & 0xFFFF, _expr44 >> 16) / 65535.0); + uint _expr46 = u; + f2_ = float2(f16tof32(_expr46), f16tof32((_expr46) >> 16)); + int _expr48 = i; + int _expr49 = i; + i = (10u == 0 ? _expr48 : (_expr48 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr49 << 5u) & ((4294967295u >> (32u - 10u)) << 5u))); + int2 _expr53 = i2_; + int2 _expr54 = i2_; + i2_ = (10u == 0 ? _expr53 : (_expr53 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr54 << 5u) & ((4294967295u >> (32u - 10u)) << 5u))); + int3 _expr58 = i3_; + int3 _expr59 = i3_; + i3_ = (10u == 0 ? _expr58 : (_expr58 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr59 << 5u) & ((4294967295u >> (32u - 10u)) << 5u))); + int4 _expr63 = i4_; + int4 _expr64 = i4_; + i4_ = (10u == 0 ? _expr63 : (_expr63 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr64 << 5u) & ((4294967295u >> (32u - 10u)) << 5u))); + uint _expr68 = u; + uint _expr69 = u; + u = (10u == 0 ? _expr68 : (_expr68 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr69 << 5u) & ((4294967295u >> (32u - 10u)) << 5u))); + uint2 _expr73 = u2_; + uint2 _expr74 = u2_; + u2_ = (10u == 0 ? _expr73 : (_expr73 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr74 << 5u) & ((4294967295u >> (32u - 10u)) << 5u))); + uint3 _expr78 = u3_; + uint3 _expr79 = u3_; + u3_ = (10u == 0 ? _expr78 : (_expr78 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr79 << 5u) & ((4294967295u >> (32u - 10u)) << 5u))); + uint4 _expr83 = u4_; + uint4 _expr84 = u4_; + u4_ = (10u == 0 ? _expr83 : (_expr83 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr84 << 5u) & ((4294967295u >> (32u - 10u)) << 5u))); + int _expr88 = i; + i = (10u == 0 ? 0 : (_expr88 << (32 - 10u - 5u)) >> (32 - 10u)); + int2 _expr92 = i2_; + i2_ = (10u == 0 ? 0 : (_expr92 << (32 - 10u - 5u)) >> (32 - 10u)); + int3 _expr96 = i3_; + i3_ = (10u == 0 ? 0 : (_expr96 << (32 - 10u - 5u)) >> (32 - 10u)); + int4 _expr100 = i4_; + i4_ = (10u == 0 ? 0 : (_expr100 << (32 - 10u - 5u)) >> (32 - 10u)); + uint _expr104 = u; + u = (10u == 0 ? 0 : (_expr104 << (32 - 10u - 5u)) >> (32 - 10u)); + uint2 _expr108 = u2_; + u2_ = (10u == 0 ? 0 : (_expr108 << (32 - 10u - 5u)) >> (32 - 10u)); + uint3 _expr112 = u3_; + u3_ = (10u == 0 ? 0 : (_expr112 << (32 - 10u - 5u)) >> (32 - 10u)); + uint4 _expr116 = u4_; + u4_ = (10u == 0 ? 0 : (_expr116 << (32 - 10u - 5u)) >> (32 - 10u)); + int _expr120 = i; + i = asint(firstbitlow(_expr120)); + uint2 _expr122 = u2_; + u2_ = firstbitlow(_expr122); + int3 _expr124 = i3_; + i3_ = asint(firstbithigh(_expr124)); + uint3 _expr126 = u3_; + u3_ = firstbithigh(_expr126); + int _expr128 = i; + i = asint(firstbithigh(_expr128)); + uint _expr130 = u; + u = firstbithigh(_expr130); + int _expr132 = i; + i = asint(countbits(asuint(_expr132))); + int2 _expr134 = i2_; + i2_ = asint(countbits(asuint(_expr134))); + int3 _expr136 = i3_; + i3_ = asint(countbits(asuint(_expr136))); + int4 _expr138 = i4_; + i4_ = asint(countbits(asuint(_expr138))); + uint _expr140 = u; + u = countbits(_expr140); + uint2 _expr142 = u2_; + u2_ = countbits(_expr142); + uint3 _expr144 = u3_; + u3_ = countbits(_expr144); + uint4 _expr146 = u4_; + u4_ = countbits(_expr146); + int _expr148 = i; + i = asint(reversebits(asuint(_expr148))); + int2 _expr150 = i2_; + i2_ = asint(reversebits(asuint(_expr150))); + int3 _expr152 = i3_; + i3_ = asint(reversebits(asuint(_expr152))); + int4 _expr154 = i4_; + i4_ = asint(reversebits(asuint(_expr154))); + uint _expr156 = u; + u = reversebits(_expr156); + uint2 _expr158 = u2_; + u2_ = reversebits(_expr158); + uint3 _expr160 = u3_; + u3_ = reversebits(_expr160); + uint4 _expr162 = u4_; + u4_ = reversebits(_expr162); + return; +} diff --git a/tests/out/hlsl/bits.hlsl.config b/tests/out/hlsl/bits.hlsl.config new file mode 100644 index 000000000..246c485cf --- /dev/null +++ b/tests/out/hlsl/bits.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/bits.ron b/tests/out/hlsl/bits.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/bits.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 2aab4f29f..eab1aaae6 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -425,7 +425,7 @@ fn convert_wgsl() { ), ( "bits", - Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL, + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ( "bitcast", From 614da63366f70117ca8c6d6f5ff9b52385082679 Mon Sep 17 00:00:00 2001 From: Joe O'Connor <48067162+Joeoc2001@users.noreply.github.com> Date: Tue, 27 Jun 2023 14:25:55 +0100 Subject: [PATCH 2027/2212] Expose early depth test field (#2393) --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 2d50e7434..1148379c0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -289,7 +289,7 @@ pub(crate) type NamedExpressions = indexmap::IndexMap< #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub struct EarlyDepthTest { - conservative: Option, + pub conservative: Option, } /// Enables adjusting depth without disabling early Z. /// From 25e4f17a691e22e157abe31df83724d6ea69ab18 Mon Sep 17 00:00:00 2001 From: wicast Date: Wed, 28 Jun 2023 20:30:25 +0800 Subject: [PATCH 2028/2212] add debug info for spv-out (#2379) --- benches/criterion.rs | 4 +- cli/src/bin/naga.rs | 23 +- src/back/spv/block.rs | 49 +- src/back/spv/instructions.rs | 31 +- src/back/spv/mod.rs | 27 +- src/back/spv/writer.rs | 40 +- tests/in/debug-symbol-simple.param.ron | 7 + tests/in/debug-symbol-simple.wgsl | 33 + tests/in/debug-symbol-terrain.param.ron | 7 + tests/in/debug-symbol-terrain.wgsl | 297 ++++ tests/out/spv/access.spvasm | 1 - tests/out/spv/boids.spvasm | 1 - .../spv/bounds-check-image-restrict.spvasm | 1 - tests/out/spv/bounds-check-image-rzsw.spvasm | 1 - tests/out/spv/collatz.spvasm | 1 - tests/out/spv/debug-symbol-simple.spvasm | 217 +++ tests/out/spv/debug-symbol-terrain.spvasm | 1470 +++++++++++++++++ tests/out/spv/image.spvasm | 1 - tests/out/spv/interpolate.spvasm | 1 - tests/out/spv/padding.spvasm | 1 - tests/out/spv/pointers.spvasm | 1 - tests/out/spv/policy-mix.spvasm | 1 - tests/out/spv/quad.spvasm | 1 - tests/out/spv/shadow.spvasm | 1 - tests/out/spv/texture-arg.spvasm | 1 - tests/out/spv/workgroup-var-init.spvasm | 1 - tests/snapshots.rs | 90 +- tests/spirv-capabilities.rs | 4 +- 28 files changed, 2258 insertions(+), 55 deletions(-) create mode 100644 tests/in/debug-symbol-simple.param.ron create mode 100644 tests/in/debug-symbol-simple.wgsl create mode 100644 tests/in/debug-symbol-terrain.param.ron create mode 100644 tests/in/debug-symbol-terrain.wgsl create mode 100644 tests/out/spv/debug-symbol-simple.spvasm create mode 100644 tests/out/spv/debug-symbol-terrain.spvasm diff --git a/benches/criterion.rs b/benches/criterion.rs index 624744555..9c0dc225f 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -181,7 +181,7 @@ fn backends(c: &mut Criterion) { let options = naga::back::spv::Options::default(); for &(ref module, ref info) in inputs.iter() { let mut writer = naga::back::spv::Writer::new(&options).unwrap(); - writer.write(module, info, None, &mut data).unwrap(); + writer.write(module, info, None, &None, &mut data).unwrap(); data.clear(); } }); @@ -199,7 +199,7 @@ fn backends(c: &mut Criterion) { entry_point: ep.name.clone(), }; writer - .write(module, info, Some(&pipeline_options), &mut data) + .write(module, info, Some(&pipeline_options), &None, &mut data) .unwrap(); data.clear(); } diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index b121dd52d..4904a78cf 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -68,6 +68,10 @@ struct Args { #[argh(option)] stdin_file_path: Option, + /// generate debug symbols, only works for spv-out for now + #[argh(option, short = 'g')] + generate_debug_symbols: Option, + /// show version #[argh(switch)] version: bool, @@ -144,13 +148,13 @@ impl FromStr for GlslProfileArg { } #[derive(Default)] -struct Parameters { +struct Parameters<'a> { validation_flags: naga::valid::ValidationFlags, bounds_check_policies: naga::proc::BoundsCheckPolicies, entry_point: Option, keep_coordinate_space: bool, spv_block_ctx_dump_prefix: Option, - spv: naga::back::spv::Options, + spv: naga::back::spv::Options<'a>, msl: naga::back::msl::Options, glsl: naga::back::glsl::Options, hlsl: naga::back::hlsl::Options, @@ -336,9 +340,9 @@ fn run() -> Result<(), Box> { { Ok(info) => Some(info), Err(error) => { - if let Some(input) = input_text { + if let Some(input) = &input_text { let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); - emit_annotated_error(&error, filename.unwrap_or("input"), &input); + emit_annotated_error(&error, filename.unwrap_or("input"), input); } print_err(&error); None @@ -415,6 +419,17 @@ fn run() -> Result<(), Box> { }; params.spv.bounds_check_policies = params.bounds_check_policies; + + //Insert Debug infos + let debug_info = args.generate_debug_symbols.and_then(|debug| { + params.spv.flags.set(spv::WriterFlags::DEBUG, debug); + Some(spv::DebugInfo { + source_code: input_text.as_ref()?, + file_name: input_path.file_name().and_then(std::ffi::OsStr::to_str)?, + }) + }); + params.spv.debug_info = debug_info; + params.spv.flags.set( spv::WriterFlags::ADJUST_COORDINATE_SPACE, !params.keep_coordinate_space, diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index fa9596655..84910e699 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -7,7 +7,7 @@ use super::{ Dimension, Error, Instruction, LocalType, LookupType, LoopContext, ResultMember, Writer, WriterFlags, }; -use crate::{arena::Handle, proc::TypeResolution}; +use crate::{arena::Handle, proc::TypeResolution, Statement}; use spirv::Word; fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { @@ -60,6 +60,12 @@ pub enum BlockExit { }, } +#[derive(Debug)] +pub(crate) struct DebugInfoInner<'a> { + pub source_code: &'a str, + pub source_file_id: Word, +} + impl Writer { // Flip Y coordinate to adjust for coordinate space difference // between SPIR-V and our IR. @@ -1699,13 +1705,32 @@ impl<'w> BlockContext<'w> { pub(super) fn write_block( &mut self, label_id: Word, - statements: &[crate::Statement], + naga_block: &crate::Block, exit: BlockExit, loop_context: LoopContext, + debug_info: Option<&DebugInfoInner>, ) -> Result<(), Error> { let mut block = Block::new(label_id); - - for statement in statements { + for (statement, span) in naga_block.span_iter() { + if let (Some(debug_info), false) = ( + debug_info, + matches!( + statement, + &(Statement::Block(..) + | Statement::Break + | Statement::Continue + | Statement::Kill + | Statement::Return { .. } + | Statement::Loop { .. }) + ), + ) { + let loc: crate::SourceLocation = span.location(debug_info.source_code); + block.body.push(Instruction::line( + debug_info.source_file_id, + loc.line_number, + loc.line_position, + )); + }; match *statement { crate::Statement::Emit(ref range) => { for handle in range.clone() { @@ -1722,6 +1747,7 @@ impl<'w> BlockContext<'w> { block_statements, BlockExit::Branch { target: merge_id }, loop_context, + debug_info, )?; block = Block::new(merge_id); @@ -1765,6 +1791,7 @@ impl<'w> BlockContext<'w> { accept, BlockExit::Branch { target: merge_id }, loop_context, + debug_info, )?; } if let Some(block_id) = reject_id { @@ -1773,6 +1800,7 @@ impl<'w> BlockContext<'w> { reject, BlockExit::Branch { target: merge_id }, loop_context, + debug_info, )?; } @@ -1852,6 +1880,7 @@ impl<'w> BlockContext<'w> { target: case_finish_id, }, inner_context, + debug_info, )?; } @@ -1873,6 +1902,16 @@ impl<'w> BlockContext<'w> { // SPIR-V requires the continuing to the `OpLoopMerge`, // so we have to start a new block with it. block = Block::new(preamble_id); + // HACK the loop statement is begin with branch instruction, + // so we need to put `OpLine` debug info before merge instruction + if let Some(debug_info) = debug_info { + let loc: crate::SourceLocation = span.location(debug_info.source_code); + block.body.push(Instruction::line( + debug_info.source_file_id, + loc.line_number, + loc.line_position, + )) + } block.body.push(Instruction::loop_merge( merge_id, continuing_id, @@ -1890,6 +1929,7 @@ impl<'w> BlockContext<'w> { continuing_id: Some(continuing_id), break_id: Some(merge_id), }, + debug_info, )?; let exit = match break_if { @@ -1910,6 +1950,7 @@ impl<'w> BlockContext<'w> { continuing_id: None, break_id: Some(merge_id), }, + debug_info, )?; block = Block::new(merge_id); diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 31ed6e231..11794fc73 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -1,4 +1,4 @@ -use super::helpers; +use super::{block::DebugInfoInner, helpers}; use spirv::{Op, Word}; pub(super) enum Signedness { @@ -21,10 +21,25 @@ impl super::Instruction { // Debug Instructions // - pub(super) fn source(source_language: spirv::SourceLanguage, version: u32) -> Self { + pub(super) fn string(name: &str, id: Word) -> Self { + let mut instruction = Self::new(Op::String); + instruction.set_result(id); + instruction.add_operands(helpers::string_to_words(name)); + instruction + } + + pub(super) fn source( + source_language: spirv::SourceLanguage, + version: u32, + source: &Option, + ) -> Self { let mut instruction = Self::new(Op::Source); instruction.add_operand(source_language as u32); instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes())); + if let Some(source) = source.as_ref() { + instruction.add_operand(source.source_file_id); + instruction.add_operands(helpers::string_to_words(source.source_code)); + } instruction } @@ -43,6 +58,18 @@ impl super::Instruction { instruction } + pub(super) fn line(file: Word, line: Word, column: Word) -> Self { + let mut instruction = Self::new(Op::Line); + instruction.add_operand(file); + instruction.add_operand(line); + instruction.add_operand(column); + instruction + } + + pub(super) const fn no_line() -> Self { + Self::new(Op::NoLine) + } + // // Annotation Instructions // diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 642c0c7d1..4e1ab5015 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -82,6 +82,12 @@ impl IdGenerator { } } +#[derive(Debug, Clone)] +pub struct DebugInfo<'a> { + pub source_code: &'a str, + pub file_name: &'a str, +} + /// A SPIR-V block to which we are still adding instructions. /// /// A `Block` represents a SPIR-V block that does not yet have a termination @@ -620,6 +626,7 @@ pub struct Writer { saved_cached: CachedExpressions, gl450_ext_inst_id: Word, + // Just a temporary list of SPIR-V ids temp_list: Vec, } @@ -664,7 +671,7 @@ pub enum ZeroInitializeWorkgroupMemoryMode { } #[derive(Debug, Clone)] -pub struct Options { +pub struct Options<'a> { /// (Major, Minor) target version of the SPIR-V. pub lang_version: (u8, u8), @@ -686,9 +693,11 @@ pub struct Options { /// Dictates the way workgroup variables should be zero initialized pub zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode, + + pub debug_info: Option>, } -impl Default for Options { +impl<'a> Default for Options<'a> { fn default() -> Self { let mut flags = WriterFlags::ADJUST_COORDINATE_SPACE | WriterFlags::LABEL_VARYINGS @@ -703,6 +712,7 @@ impl Default for Options { capabilities: None, bounds_check_policies: crate::proc::BoundsCheckPolicies::default(), zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode::Polyfill, + debug_info: None, } } } @@ -726,8 +736,17 @@ pub fn write_vec( options: &Options, pipeline_options: Option<&PipelineOptions>, ) -> Result, Error> { - let mut words = Vec::new(); + let mut words: Vec = Vec::new(); let mut w = Writer::new(options)?; - w.write(module, info, pipeline_options, &mut words)?; + + if options.flags.contains(WriterFlags::DEBUG) {} + + w.write( + module, + info, + pipeline_options, + &options.debug_info, + &mut words, + )?; Ok(words) } diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4a1bc8ff2..554db6d8a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,9 +1,10 @@ use super::{ + block::DebugInfoInner, helpers::{contains_builtin, global_needs_wrapper, map_storage_class}, - make_local, Block, BlockContext, CachedConstant, CachedExpressions, EntryPointContext, Error, - Function, FunctionArgument, GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable, - LogicalLayout, LookupFunctionType, LookupType, LoopContext, Options, PhysicalLayout, - PipelineOptions, ResultMember, Writer, WriterFlags, BITS_PER_BYTE, + make_local, Block, BlockContext, CachedConstant, CachedExpressions, DebugInfo, + EntryPointContext, Error, Function, FunctionArgument, GlobalVariable, IdGenerator, Instruction, + LocalType, LocalVariable, LogicalLayout, LookupFunctionType, LookupType, LoopContext, Options, + PhysicalLayout, PipelineOptions, ResultMember, Writer, WriterFlags, BITS_PER_BYTE, }; use crate::{ arena::{Handle, UniqueArena}, @@ -329,6 +330,7 @@ impl Writer { info: &FunctionInfo, ir_module: &crate::Module, mut interface: Option, + debug_info: &Option, ) -> Result { let mut function = Function::default(); @@ -693,6 +695,7 @@ impl Writer { &ir_function.body, super::block::BlockExit::Return, LoopContext::default(), + debug_info.as_ref(), )?; // Consume the `BlockContext`, ending its borrows and letting the @@ -726,6 +729,7 @@ impl Writer { entry_point: &crate::EntryPoint, info: &FunctionInfo, ir_module: &crate::Module, + debug_info: &Option, ) -> Result { let mut interface_ids = Vec::new(); let function_id = self.write_function( @@ -736,6 +740,7 @@ impl Writer { varying_ids: &mut interface_ids, stage: entry_point.stage, }), + debug_info, )?; let exec_model = match entry_point.stage { @@ -1724,6 +1729,7 @@ impl Writer { ir_module: &crate::Module, mod_info: &ModuleInfo, ep_index: Option, + debug_info: &Option, ) -> Result<(), Error> { fn has_view_index_check( ir_module: &crate::Module, @@ -1771,9 +1777,23 @@ impl Writer { Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450") .to_words(&mut self.logical_layout.ext_inst_imports); + let mut debug_info_inner = None; if self.flags.contains(WriterFlags::DEBUG) { - self.debugs - .push(Instruction::source(spirv::SourceLanguage::GLSL, 450)); + if let Some(debug_info) = debug_info.as_ref() { + let source_file_id = self.id_gen.next(); + self.debugs + .push(Instruction::string(debug_info.file_name, source_file_id)); + + debug_info_inner = Some(DebugInfoInner { + source_code: debug_info.source_code, + source_file_id, + }); + self.debugs.push(Instruction::source( + spirv::SourceLanguage::Unknown, + 0, + &debug_info_inner, + )); + } } self.constant_ids.resize(ir_module.constants.len(), 0); @@ -1858,7 +1878,7 @@ impl Writer { continue; } } - let id = self.write_function(ir_function, info, ir_module, None)?; + let id = self.write_function(ir_function, info, ir_module, None, &debug_info_inner)?; self.lookup_function.insert(handle, id); } @@ -1868,7 +1888,8 @@ impl Writer { continue; } let info = mod_info.get_entry_point(index); - let ep_instruction = self.write_entry_point(ir_ep, info, ir_module)?; + let ep_instruction = + self.write_entry_point(ir_ep, info, ir_module, &debug_info_inner)?; ep_instruction.to_words(&mut self.logical_layout.entry_points); } @@ -1910,6 +1931,7 @@ impl Writer { ir_module: &crate::Module, info: &ModuleInfo, pipeline_options: Option<&PipelineOptions>, + debug_info: &Option, words: &mut Vec, ) -> Result<(), Error> { self.reset(); @@ -1927,7 +1949,7 @@ impl Writer { None => None, }; - self.write_logical_layout(ir_module, info, ep_index)?; + self.write_logical_layout(ir_module, info, ep_index, debug_info)?; self.write_physical_layout(); self.physical_layout.in_words(words); diff --git a/tests/in/debug-symbol-simple.param.ron b/tests/in/debug-symbol-simple.param.ron new file mode 100644 index 000000000..2869084cd --- /dev/null +++ b/tests/in/debug-symbol-simple.param.ron @@ -0,0 +1,7 @@ +( + spv: ( + version: (1, 1), + debug: true, + adjust_coordinate_space: false, + ), +) \ No newline at end of file diff --git a/tests/in/debug-symbol-simple.wgsl b/tests/in/debug-symbol-simple.wgsl new file mode 100644 index 000000000..86505a159 --- /dev/null +++ b/tests/in/debug-symbol-simple.wgsl @@ -0,0 +1,33 @@ +struct VertexInput { + @location(0) position: vec3, + @location(1) color: vec3, +}; + +struct VertexOutput { + @builtin(position) clip_position: vec4, + @location(0) color: vec3, +}; + +@vertex +fn vs_main( + model: VertexInput, +) -> VertexOutput { + var out: VertexOutput; + out.color = model.color; + out.clip_position = vec4(model.position, 1.0); + return out; +} + +// Fragment shader + +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + var color = in.color; + for (var i = 0; i < 10; i += 1) { + var ii = f32(i); + color.x += ii*0.001; + color.y += ii*0.002; + } + + return vec4(color, 1.0); +} \ No newline at end of file diff --git a/tests/in/debug-symbol-terrain.param.ron b/tests/in/debug-symbol-terrain.param.ron new file mode 100644 index 000000000..2869084cd --- /dev/null +++ b/tests/in/debug-symbol-terrain.param.ron @@ -0,0 +1,7 @@ +( + spv: ( + version: (1, 1), + debug: true, + adjust_coordinate_space: false, + ), +) \ No newline at end of file diff --git a/tests/in/debug-symbol-terrain.wgsl b/tests/in/debug-symbol-terrain.wgsl new file mode 100644 index 000000000..3f3dd58dd --- /dev/null +++ b/tests/in/debug-symbol-terrain.wgsl @@ -0,0 +1,297 @@ +// Taken from https://github.com/sotrh/learn-wgpu/blob/11820796f5e1dbce42fb1119f04ddeb4b167d2a0/code/intermediate/tutorial13-terrain/src/terrain.wgsl +// ============================ +// Terrain Generation +// ============================ + +// https://gist.github.com/munrocket/236ed5ba7e409b8bdf1ff6eca5dcdc39 +// MIT License. © Ian McEwan, Stefan Gustavson, Munrocket +// - Less condensed glsl implementation with comments can be found at https://weber.itn.liu.se/~stegu/jgt2012/article.pdf + +fn permute3(x: vec3) -> vec3 { return (((x * 34.) + 1.) * x) % vec3(289.); } + +fn snoise2(v: vec2) -> f32 { + let C = vec4(0.211324865405187, 0.366025403784439, -0.577350269189626, 0.024390243902439); + var i: vec2 = floor(v + dot(v, C.yy)); + let x0 = v - i + dot(i, C.xx); + // I flipped the condition here from > to < as it fixed some artifacting I was observing + var i1: vec2 = select(vec2(1., 0.), vec2(0., 1.), (x0.x < x0.y)); + var x12: vec4 = x0.xyxy + C.xxzz - vec4(i1, 0., 0.); + i = i % vec2(289.); + let p = permute3(permute3(i.y + vec3(0., i1.y, 1.)) + i.x + vec3(0., i1.x, 1.)); + var m: vec3 = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), vec3(0.)); + m = m * m; + m = m * m; + let x = 2. * fract(p * C.www) - 1.; + let h = abs(x) - 0.5; + let ox = floor(x + 0.5); + let a0 = x - ox; + m = m * (1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h)); + let g = vec3(a0.x * x0.x + h.x * x0.y, a0.yz * x12.xz + h.yz * x12.yw); + return 130. * dot(m, g); +} + + +fn fbm(p: vec2) -> f32 { + let NUM_OCTAVES: u32 = 5u; + var x = p * 0.01; + var v = 0.0; + var a = 0.5; + let shift = vec2(100.0); + let cs = vec2(cos(0.5), sin(0.5)); + let rot = mat2x2(cs.x, cs.y, -cs.y, cs.x); + + for (var i = 0u; i < NUM_OCTAVES; i = i + 1u) { + v = v + a * snoise2(x); + x = rot * x * 2.0 + shift; + a = a * 0.5; + } + + return v; +} + +struct ChunkData { + chunk_size: vec2, + chunk_corner: vec2, + min_max_height: vec2, +} + +struct Vertex { + @location(0) position: vec3, + @location(1) normal: vec3, +} + +struct VertexBuffer { + data: array, // stride: 32 +} + +struct IndexBuffer { + data: array, +} + +@group(0) @binding(0) var chunk_data: ChunkData; +@group(0) @binding(1) var vertices: VertexBuffer; +@group(0) @binding(2) var indices: IndexBuffer; + +fn terrain_point(p: vec2, min_max_height: vec2) -> vec3 { + return vec3( + p.x, + mix(min_max_height.x, min_max_height.y, fbm(p)), + p.y, + ); +} + +fn terrain_vertex(p: vec2, min_max_height: vec2) -> Vertex { + let v = terrain_point(p, min_max_height); + + let tpx = terrain_point(p + vec2(0.1, 0.0), min_max_height) - v; + let tpz = terrain_point(p + vec2(0.0, 0.1), min_max_height) - v; + let tnx = terrain_point(p + vec2(-0.1, 0.0), min_max_height) - v; + let tnz = terrain_point(p + vec2(0.0, -0.1), min_max_height) - v; + + let pn = normalize(cross(tpz, tpx)); + let nn = normalize(cross(tnz, tnx)); + + let n = (pn + nn) * 0.5; + + return Vertex(v, n); +} + +fn index_to_p(vert_index: u32, chunk_size: vec2, chunk_corner: vec2) -> vec2 { + return vec2( + f32(vert_index) % f32(chunk_size.x + 1u), + f32(vert_index / (chunk_size.x + 1u)), + ) + vec2(chunk_corner); +} + +@compute @workgroup_size(64) +fn gen_terrain_compute( + @builtin(global_invocation_id) gid: vec3 +) { + // Create vert_component + let vert_index = gid.x; + + let p = index_to_p(vert_index, chunk_data.chunk_size, chunk_data.chunk_corner); + + vertices.data[vert_index] = terrain_vertex(p, chunk_data.min_max_height); + + // Create indices + let start_index = gid.x * 6u; // using TriangleList + + if (start_index >= (chunk_data.chunk_size.x * chunk_data.chunk_size.y * 6u)) { return; } + + let v00 = vert_index + gid.x / chunk_data.chunk_size.x; + let v10 = v00 + 1u; + let v01 = v00 + chunk_data.chunk_size.x + 1u; + let v11 = v01 + 1u; + + indices.data[start_index] = v00; + indices.data[start_index + 1u] = v01; + indices.data[start_index + 2u] = v11; + indices.data[start_index + 3u] = v00; + indices.data[start_index + 4u] = v11; + indices.data[start_index + 5u] = v10; +} + +// ============================ +// Terrain Gen (Fragment Shader) +// ============================ + +struct GenData { + chunk_size: vec2, + chunk_corner: vec2, + min_max_height: vec2, + texture_size: u32, + start_index: u32, +} +@group(0) +@binding(0) +var gen_data: GenData; + +struct GenVertexOutput { + @location(0) + index: u32, + @builtin(position) + position: vec4, + @location(1) + uv: vec2, +}; + +@vertex +fn gen_terrain_vertex(@builtin(vertex_index) vindex: u32) -> GenVertexOutput { + let u = f32(((vindex + 2u) / 3u) % 2u); + let v = f32(((vindex + 1u) / 3u) % 2u); + let uv = vec2(u, v); + + let position = vec4(-1.0 + uv * 2.0, 0.0, 1.0); + + // TODO: maybe replace this with u32(dot(uv, vec2(f32(gen_data.texture_dim.x)))) + let index = u32(uv.x * f32(gen_data.texture_size) + uv.y * f32(gen_data.texture_size)) + gen_data.start_index; + + return GenVertexOutput(index, position, uv); +} + + +struct GenFragmentOutput { + @location(0) vert_component: u32, + @location(1) index: u32, +} + +@fragment +fn gen_terrain_fragment(in: GenVertexOutput) -> GenFragmentOutput { + let i = u32(in.uv.x * f32(gen_data.texture_size) + in.uv.y * f32(gen_data.texture_size * gen_data.texture_size)) + gen_data.start_index; + let vert_index = u32(floor(f32(i) / 6.)); + let comp_index = i % 6u; + + let p = index_to_p(vert_index, gen_data.chunk_size, gen_data.chunk_corner); + let v = terrain_vertex(p, gen_data.min_max_height); + + var vert_component: f32 = 0.; + + switch comp_index { + case 0u: { vert_component = v.position.x; } + case 1u: { vert_component = v.position.y; } + case 2u: { vert_component = v.position.z; } + case 3u: { vert_component = v.normal.x; } + case 4u: { vert_component = v.normal.y; } + case 5u: { vert_component = v.normal.z; } + default: {} + } + + let v00 = vert_index + vert_index / gen_data.chunk_size.x; + let v10 = v00 + 1u; + let v01 = v00 + gen_data.chunk_size.x + 1u; + let v11 = v01 + 1u; + + var index = 0u; + switch comp_index { + case 0u, 3u: { index = v00; } + case 2u, 4u: { index = v11; } + case 1u: { index = v01; } + case 5u: { index = v10; } + default: {} + } + index = in.index; + // index = gen_data.start_index; + // indices.data[start_index] = v00; + // indices.data[start_index + 1u] = v01; + // indices.data[start_index + 2u] = v11; + // indices.data[start_index + 3u] = v00; + // indices.data[start_index + 4u] = v11; + // indices.data[start_index + 5u] = v10; + + let ivert_component = bitcast(vert_component); + return GenFragmentOutput(ivert_component, index); +} + +// ============================ +// Terrain Rendering +// ============================ + +struct Camera { + view_pos: vec4, + view_proj: mat4x4, +} +@group(0) @binding(0) +var camera: Camera; + +struct Light { + position: vec3, + color: vec3, +} +@group(1) @binding(0) +var light: Light; + +struct VertexOutput { + @builtin(position) clip_position: vec4, + @location(0) normal: vec3, + @location(1) world_pos: vec3, +} + +@vertex +fn vs_main( + vertex: Vertex, +) -> VertexOutput { + let clip_position = camera.view_proj * vec4(vertex.position, 1.); + let normal = vertex.normal; + return VertexOutput(clip_position, normal, vertex.position); +} + +@group(2) @binding(0) +var t_diffuse: texture_2d; +@group(2) @binding(1) +var s_diffuse: sampler; +@group(2) @binding(2) +var t_normal: texture_2d; +@group(2) @binding(3) +var s_normal: sampler; + +fn color23(p: vec2) -> vec3 { + return vec3( + snoise2(p) * 0.5 + 0.5, + snoise2(p + vec2(23., 32.)) * 0.5 + 0.5, + snoise2(p + vec2(-43., 3.)) * 0.5 + 0.5, + ); +} + +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + var color = smoothstep(vec3(0.0), vec3(0.1), fract(in.world_pos)); + color = mix(vec3(0.5, 0.1, 0.7), vec3(0.2, 0.2, 0.2), vec3(color.x * color.y * color.z)); + + let ambient_strength = 0.1; + let ambient_color = light.color * ambient_strength; + + let light_dir = normalize(light.position - in.world_pos); + let view_dir = normalize(camera.view_pos.xyz - in.world_pos); + let half_dir = normalize(view_dir + light_dir); + + let diffuse_strength = max(dot(in.normal, light_dir), 0.0); + let diffuse_color = diffuse_strength * light.color; + + let specular_strength = pow(max(dot(in.normal, half_dir), 0.0), 32.0); + let specular_color = specular_strength * light.color; + + let result = (ambient_color + diffuse_color + specular_color) * color; + + return vec4(result, 1.0); +} \ No newline at end of file diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 92e3a2fbe..12d2ceef2 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -11,7 +11,6 @@ OpEntryPoint Fragment %286 "foo_frag" %285 OpEntryPoint GLCompute %306 "assign_through_ptr" %309 OpExecutionMode %286 OriginUpperLeft OpExecutionMode %306 LocalSize 1 1 1 -OpSource GLSL 450 OpMemberName %12 0 "a" OpMemberName %12 1 "b" OpMemberName %12 2 "c" diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 002959167..4b19d9b4f 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -8,7 +8,6 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %46 "main" %43 OpExecutionMode %46 LocalSize 64 1 1 -OpSource GLSL 450 OpName %3 "NUM_PARTICLES" OpMemberName %7 0 "pos" OpMemberName %7 1 "vel" diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index c88421004..1a99215ef 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -10,7 +10,6 @@ OpCapability ImageQuery OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %269 "fragment_shader" %267 OpExecutionMode %269 OriginUpperLeft -OpSource GLSL 450 OpName %21 "image_1d" OpName %23 "image_2d" OpName %25 "image_2d_array" diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index e5e12fabd..53e27a796 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -10,7 +10,6 @@ OpCapability ImageQuery OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %306 "fragment_shader" %304 OpExecutionMode %306 OriginUpperLeft -OpSource GLSL 450 OpName %21 "image_1d" OpName %23 "image_2d" OpName %25 "image_2d_array" diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index a08b44670..a8ed9ab78 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -8,7 +8,6 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %52 "main" %49 OpExecutionMode %52 LocalSize 1 1 1 -OpSource GLSL 450 OpMemberName %5 0 "data" OpName %5 "PrimeIndices" OpName %7 "v_indices" diff --git a/tests/out/spv/debug-symbol-simple.spvasm b/tests/out/spv/debug-symbol-simple.spvasm new file mode 100644 index 000000000..67ad8beb2 --- /dev/null +++ b/tests/out/spv/debug-symbol-simple.spvasm @@ -0,0 +1,217 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 95 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %24 "vs_main" %15 %18 %20 %22 +OpEntryPoint Fragment %57 "fs_main" %51 %54 %56 +OpExecutionMode %57 OriginUpperLeft +%3 = OpString "debug-symbol-simple" +OpSource Unknown 0 %3 "struct VertexInput { + @location(0) position: vec3, + @location(1) color: vec3, +}; + +struct VertexOutput { + @builtin(position) clip_position: vec4, + @location(0) color: vec3, +}; + +@vertex +fn vs_main( + model: VertexInput, +) -> VertexOutput { + var out: VertexOutput; + out.color = model.color; + out.clip_position = vec4(model.position, 1.0); + return out; +} + +// Fragment shader + +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + var color = in.color; + for (var i = 0; i < 10; i += 1) { + var ii = f32(i); + color.x += ii*0.001; + color.y += ii*0.002; + } + + return vec4(color, 1.0); +}" +OpMemberName %6 0 "position" +OpMemberName %6 1 "color" +OpName %6 "VertexInput" +OpMemberName %8 0 "clip_position" +OpMemberName %8 1 "color" +OpName %8 "VertexOutput" +OpName %10 "out" +OpName %15 "position" +OpName %18 "color" +OpName %20 "clip_position" +OpName %22 "color" +OpName %24 "vs_main" +OpName %41 "color" +OpName %43 "i" +OpName %46 "ii" +OpName %51 "clip_position" +OpName %54 "color" +OpName %57 "fs_main" +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %6 1 Offset 16 +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %8 1 Offset 16 +OpDecorate %15 Location 0 +OpDecorate %18 Location 1 +OpDecorate %20 BuiltIn Position +OpDecorate %22 Location 0 +OpDecorate %51 BuiltIn FragCoord +OpDecorate %54 Location 0 +OpDecorate %56 Location 0 +%2 = OpTypeVoid +%5 = OpTypeFloat 32 +%4 = OpTypeVector %5 3 +%6 = OpTypeStruct %4 %4 +%7 = OpTypeVector %5 4 +%8 = OpTypeStruct %7 %4 +%9 = OpTypeInt 32 1 +%11 = OpTypePointer Function %8 +%12 = OpConstantNull %8 +%16 = OpTypePointer Input %4 +%15 = OpVariable %16 Input +%18 = OpVariable %16 Input +%21 = OpTypePointer Output %7 +%20 = OpVariable %21 Output +%23 = OpTypePointer Output %4 +%22 = OpVariable %23 Output +%25 = OpTypeFunction %2 +%26 = OpConstant %5 1.0 +%28 = OpTypePointer Function %4 +%31 = OpTypeInt 32 0 +%30 = OpConstant %31 1 +%33 = OpTypePointer Function %7 +%36 = OpConstant %31 0 +%42 = OpConstantNull %4 +%44 = OpTypePointer Function %9 +%45 = OpConstantNull %9 +%47 = OpTypePointer Function %5 +%48 = OpConstantNull %5 +%52 = OpTypePointer Input %7 +%51 = OpVariable %52 Input +%54 = OpVariable %16 Input +%56 = OpVariable %21 Output +%58 = OpConstant %9 0 +%59 = OpConstant %9 10 +%60 = OpConstant %5 0.001 +%61 = OpConstant %5 0.002 +%62 = OpConstant %9 1 +%70 = OpTypeBool +%78 = OpTypePointer Function %5 +%24 = OpFunction %2 None %25 +%13 = OpLabel +%10 = OpVariable %11 Function %12 +%17 = OpLoad %4 %15 +%19 = OpLoad %4 %18 +%14 = OpCompositeConstruct %6 %17 %19 +OpBranch %27 +%27 = OpLabel +OpLine %3 16 5 +%29 = OpCompositeExtract %4 %14 1 +OpLine %3 16 5 +%32 = OpAccessChain %28 %10 %30 +OpStore %32 %29 +OpLine %3 17 5 +%34 = OpCompositeExtract %4 %14 0 +OpLine %3 17 25 +%35 = OpCompositeConstruct %7 %34 %26 +OpLine %3 17 5 +%37 = OpAccessChain %33 %10 %36 +OpStore %37 %35 +OpLine %3 1 1 +%38 = OpLoad %8 %10 +%39 = OpCompositeExtract %7 %38 0 +OpStore %20 %39 +%40 = OpCompositeExtract %4 %38 1 +OpStore %22 %40 +OpReturn +OpFunctionEnd +%57 = OpFunction %2 None %25 +%49 = OpLabel +%41 = OpVariable %28 Function %42 +%43 = OpVariable %44 Function %45 +%46 = OpVariable %47 Function %48 +%53 = OpLoad %7 %51 +%55 = OpLoad %4 %54 +%50 = OpCompositeConstruct %8 %53 %55 +OpBranch %63 +%63 = OpLabel +OpLine %3 25 17 +%64 = OpCompositeExtract %4 %50 1 +OpLine %3 25 5 +OpStore %41 %64 +OpLine %3 26 10 +OpStore %43 %58 +OpBranch %65 +%65 = OpLabel +OpLine %3 26 5 +OpLoopMerge %66 %68 None +OpBranch %67 +%67 = OpLabel +OpLine %3 1 1 +%69 = OpLoad %9 %43 +OpLine %3 26 21 +%71 = OpSLessThan %70 %69 %59 +OpLine %3 26 20 +OpSelectionMerge %72 None +OpBranchConditional %71 %72 %73 +%73 = OpLabel +OpBranch %66 +%72 = OpLabel +OpBranch %74 +%74 = OpLabel +OpLine %3 27 18 +%76 = OpLoad %9 %43 +%77 = OpConvertSToF %5 %76 +OpLine %3 27 9 +OpStore %46 %77 +OpLine %3 28 9 +%79 = OpLoad %5 %46 +OpLine %3 28 9 +%80 = OpFMul %5 %79 %60 +%81 = OpAccessChain %78 %41 %36 +%82 = OpLoad %5 %81 +%83 = OpFAdd %5 %82 %80 +OpLine %3 28 9 +%84 = OpAccessChain %78 %41 %36 +OpStore %84 %83 +OpLine %3 29 9 +%85 = OpLoad %5 %46 +OpLine %3 29 9 +%86 = OpFMul %5 %85 %61 +%87 = OpAccessChain %78 %41 %30 +%88 = OpLoad %5 %87 +%89 = OpFAdd %5 %88 %86 +OpLine %3 29 9 +%90 = OpAccessChain %78 %41 %30 +OpStore %90 %89 +OpBranch %75 +%75 = OpLabel +OpBranch %68 +%68 = OpLabel +OpLine %3 26 29 +%91 = OpLoad %9 %43 +%92 = OpIAdd %9 %91 %62 +OpLine %3 26 29 +OpStore %43 %92 +OpBranch %65 +%66 = OpLabel +OpLine %3 1 1 +%93 = OpLoad %4 %41 +OpLine %3 32 12 +%94 = OpCompositeConstruct %7 %93 %26 +OpStore %56 %94 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/debug-symbol-terrain.spvasm b/tests/out/spv/debug-symbol-terrain.spvasm new file mode 100644 index 000000000..9fb3bbff9 --- /dev/null +++ b/tests/out/spv/debug-symbol-terrain.spvasm @@ -0,0 +1,1470 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 653 +OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %351 "gen_terrain_compute" %348 +OpEntryPoint Vertex %421 "gen_terrain_vertex" %412 %415 %417 %419 +OpEntryPoint Fragment %475 "gen_terrain_fragment" %465 %467 %470 %473 %474 +OpEntryPoint Vertex %566 "vs_main" %557 %560 %562 %563 %565 +OpEntryPoint Fragment %593 "fs_main" %586 %588 %590 %592 +OpExecutionMode %351 LocalSize 64 1 1 +OpExecutionMode %475 OriginUpperLeft +OpExecutionMode %593 OriginUpperLeft +%3 = OpString "debug-symbol-terrain" +OpSource Unknown 0 %3 "// Taken from https://github.com/sotrh/learn-wgpu/blob/11820796f5e1dbce42fb1119f04ddeb4b167d2a0/code/intermediate/tutorial13-terrain/src/terrain.wgsl +// ============================ +// Terrain Generation +// ============================ + +// https://gist.github.com/munrocket/236ed5ba7e409b8bdf1ff6eca5dcdc39 +// MIT License. © Ian McEwan, Stefan Gustavson, Munrocket +// - Less condensed glsl implementation with comments can be found at https://weber.itn.liu.se/~stegu/jgt2012/article.pdf + +fn permute3(x: vec3) -> vec3 { return (((x * 34.) + 1.) * x) % vec3(289.); } + +fn snoise2(v: vec2) -> f32 { + let C = vec4(0.211324865405187, 0.366025403784439, -0.577350269189626, 0.024390243902439); + var i: vec2 = floor(v + dot(v, C.yy)); + let x0 = v - i + dot(i, C.xx); + // I flipped the condition here from > to < as it fixed some artifacting I was observing + var i1: vec2 = select(vec2(1., 0.), vec2(0., 1.), (x0.x < x0.y)); + var x12: vec4 = x0.xyxy + C.xxzz - vec4(i1, 0., 0.); + i = i % vec2(289.); + let p = permute3(permute3(i.y + vec3(0., i1.y, 1.)) + i.x + vec3(0., i1.x, 1.)); + var m: vec3 = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), vec3(0.)); + m = m * m; + m = m * m; + let x = 2. * fract(p * C.www) - 1.; + let h = abs(x) - 0.5; + let ox = floor(x + 0.5); + let a0 = x - ox; + m = m * (1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h)); + let g = vec3(a0.x * x0.x + h.x * x0.y, a0.yz * x12.xz + h.yz * x12.yw); + return 130. * dot(m, g); +} + + +fn fbm(p: vec2) -> f32 { + let NUM_OCTAVES: u32 = 5u; + var x = p * 0.01; + var v = 0.0; + var a = 0.5; + let shift = vec2(100.0); + let cs = vec2(cos(0.5), sin(0.5)); + let rot = mat2x2(cs.x, cs.y, -cs.y, cs.x); + + for (var i = 0u; i < NUM_OCTAVES; i = i + 1u) { + v = v + a * snoise2(x); + x = rot * x * 2.0 + shift; + a = a * 0.5; + } + + return v; +} + +struct ChunkData { + chunk_size: vec2, + chunk_corner: vec2, + min_max_height: vec2, +} + +struct Vertex { + @location(0) position: vec3, + @location(1) normal: vec3, +} + +struct VertexBuffer { + data: array, // stride: 32 +} + +struct IndexBuffer { + data: array, +} + +@group(0) @binding(0) var chunk_data: ChunkData; +@group(0) @binding(1) var vertices: VertexBuffer; +@group(0) @binding(2) var indices: IndexBuffer; + +fn terrain_point(p: vec2, min_max_height: vec2) -> vec3 { + return vec3( + p.x, + mix(min_max_height.x, min_max_height.y, fbm(p)), + p.y, + ); +} + +fn terrain_vertex(p: vec2, min_max_height: vec2) -> Vertex { + let v = terrain_point(p, min_max_height); + + let tpx = terrain_point(p + vec2(0.1, 0.0), min_max_height) - v; + let tpz = terrain_point(p + vec2(0.0, 0.1), min_max_height) - v; + let tnx = terrain_point(p + vec2(-0.1, 0.0), min_max_height) - v; + let tnz = terrain_point(p + vec2(0.0, -0.1), min_max_height) - v; + + let pn = normalize(cross(tpz, tpx)); + let nn = normalize(cross(tnz, tnx)); + + let n = (pn + nn) * 0.5; + + return Vertex(v, n); +} + +fn index_to_p(vert_index: u32, chunk_size: vec2, chunk_corner: vec2) -> vec2 { + return vec2( + f32(vert_index) % f32(chunk_size.x + 1u), + f32(vert_index / (chunk_size.x + 1u)), + ) + vec2(chunk_corner); +} + +@compute @workgroup_size(64) +fn gen_terrain_compute( + @builtin(global_invocation_id) gid: vec3 +) { + // Create vert_component + let vert_index = gid.x; + + let p = index_to_p(vert_index, chunk_data.chunk_size, chunk_data.chunk_corner); + + vertices.data[vert_index] = terrain_vertex(p, chunk_data.min_max_height); + + // Create indices + let start_index = gid.x * 6u; // using TriangleList + + if (start_index >= (chunk_data.chunk_size.x * chunk_data.chunk_size.y * 6u)) { return; } + + let v00 = vert_index + gid.x / chunk_data.chunk_size.x; + let v10 = v00 + 1u; + let v01 = v00 + chunk_data.chunk_size.x + 1u; + let v11 = v01 + 1u; + + indices.data[start_index] = v00; + indices.data[start_index + 1u] = v01; + indices.data[start_index + 2u] = v11; + indices.data[start_index + 3u] = v00; + indices.data[start_index + 4u] = v11; + indices.data[start_index + 5u] = v10; +} + +// ============================ +// Terrain Gen (Fragment Shader) +// ============================ + +struct GenData { + chunk_size: vec2, + chunk_corner: vec2, + min_max_height: vec2, + texture_size: u32, + start_index: u32, +} +@group(0) +@binding(0) +var gen_data: GenData; + +struct GenVertexOutput { + @location(0) + index: u32, + @builtin(position) + position: vec4, + @location(1) + uv: vec2, +}; + +@vertex +fn gen_terrain_vertex(@builtin(vertex_index) vindex: u32) -> GenVertexOutput { + let u = f32(((vindex + 2u) / 3u) % 2u); + let v = f32(((vindex + 1u) / 3u) % 2u); + let uv = vec2(u, v); + + let position = vec4(-1.0 + uv * 2.0, 0.0, 1.0); + + // TODO: maybe replace this with u32(dot(uv, vec2(f32(gen_data.texture_dim.x)))) + let index = u32(uv.x * f32(gen_data.texture_size) + uv.y * f32(gen_data.texture_size)) + gen_data.start_index; + + return GenVertexOutput(index, position, uv); +} + + +struct GenFragmentOutput { + @location(0) vert_component: u32, + @location(1) index: u32, +} + +@fragment +fn gen_terrain_fragment(in: GenVertexOutput) -> GenFragmentOutput { + let i = u32(in.uv.x * f32(gen_data.texture_size) + in.uv.y * f32(gen_data.texture_size * gen_data.texture_size)) + gen_data.start_index; + let vert_index = u32(floor(f32(i) / 6.)); + let comp_index = i % 6u; + + let p = index_to_p(vert_index, gen_data.chunk_size, gen_data.chunk_corner); + let v = terrain_vertex(p, gen_data.min_max_height); + + var vert_component: f32 = 0.; + + switch comp_index { + case 0u: { vert_component = v.position.x; } + case 1u: { vert_component = v.position.y; } + case 2u: { vert_component = v.position.z; } + case 3u: { vert_component = v.normal.x; } + case 4u: { vert_component = v.normal.y; } + case 5u: { vert_component = v.normal.z; } + default: {} + } + + let v00 = vert_index + vert_index / gen_data.chunk_size.x; + let v10 = v00 + 1u; + let v01 = v00 + gen_data.chunk_size.x + 1u; + let v11 = v01 + 1u; + + var index = 0u; + switch comp_index { + case 0u, 3u: { index = v00; } + case 2u, 4u: { index = v11; } + case 1u: { index = v01; } + case 5u: { index = v10; } + default: {} + } + index = in.index; + // index = gen_data.start_index; + // indices.data[start_index] = v00; + // indices.data[start_index + 1u] = v01; + // indices.data[start_index + 2u] = v11; + // indices.data[start_index + 3u] = v00; + // indices.data[start_index + 4u] = v11; + // indices.data[start_index + 5u] = v10; + + let ivert_component = bitcast(vert_component); + return GenFragmentOutput(ivert_component, index); +} + +// ============================ +// Terrain Rendering +// ============================ + +struct Camera { + view_pos: vec4, + view_proj: mat4x4, +} +@group(0) @binding(0) +var camera: Camera; + +struct Light { + position: vec3, + color: vec3, +} +@group(1) @binding(0) +var light: Light; + +struct VertexOutput { + @builtin(position) clip_position: vec4, + @location(0) normal: vec3, + @location(1) world_pos: vec3, +} + +@vertex +fn vs_main( + vertex: Vertex, +) -> VertexOutput { + let clip_position = camera.view_proj * vec4(vertex.position, 1.); + let normal = vertex.normal; + return VertexOutput(clip_position, normal, vertex.position); +} + +@group(2) @binding(0) +var t_diffuse: texture_2d; +@group(2) @binding(1) +var s_diffuse: sampler; +@group(2) @binding(2) +var t_normal: texture_2d; +@group(2) @binding(3) +var s_normal: sampler; + +fn color23(p: vec2) -> vec3 { + return vec3( + snoise2(p) * 0.5 + 0.5, + snoise2(p + vec2(23., 32.)) * 0.5 + 0.5, + snoise2(p + vec2(-43., 3.)) * 0.5 + 0.5, + ); +} + +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + var color = smoothstep(vec3(0.0), vec3(0.1), fract(in.world_pos)); + color = mix(vec3(0.5, 0.1, 0.7), vec3(0.2, 0.2, 0.2), vec3(color.x * color.y * color.z)); + + let ambient_strength = 0.1; + let ambient_color = light.color * ambient_strength; + + let light_dir = normalize(light.position - in.world_pos); + let view_dir = normalize(camera.view_pos.xyz - in.world_pos); + let half_dir = normalize(view_dir + light_dir); + + let diffuse_strength = max(dot(in.normal, light_dir), 0.0); + let diffuse_color = diffuse_strength * light.color; + + let specular_strength = pow(max(dot(in.normal, half_dir), 0.0), 32.0); + let specular_color = specular_strength * light.color; + + let result = (ambient_color + diffuse_color + specular_color) * color; + + return vec4(result, 1.0); +}" +OpMemberName %13 0 "chunk_size" +OpMemberName %13 1 "chunk_corner" +OpMemberName %13 2 "min_max_height" +OpName %13 "ChunkData" +OpMemberName %14 0 "position" +OpMemberName %14 1 "normal" +OpName %14 "Vertex" +OpMemberName %16 0 "data" +OpName %16 "VertexBuffer" +OpMemberName %18 0 "data" +OpName %18 "IndexBuffer" +OpMemberName %20 0 "chunk_size" +OpMemberName %20 1 "chunk_corner" +OpMemberName %20 2 "min_max_height" +OpMemberName %20 3 "texture_size" +OpMemberName %20 4 "start_index" +OpName %20 "GenData" +OpMemberName %21 0 "index" +OpMemberName %21 1 "position" +OpMemberName %21 2 "uv" +OpName %21 "GenVertexOutput" +OpMemberName %22 0 "vert_component" +OpMemberName %22 1 "index" +OpName %22 "GenFragmentOutput" +OpMemberName %24 0 "view_pos" +OpMemberName %24 1 "view_proj" +OpName %24 "Camera" +OpMemberName %25 0 "position" +OpMemberName %25 1 "color" +OpName %25 "Light" +OpMemberName %26 0 "clip_position" +OpMemberName %26 1 "normal" +OpMemberName %26 2 "world_pos" +OpName %26 "VertexOutput" +OpName %29 "chunk_data" +OpName %32 "vertices" +OpName %34 "indices" +OpName %36 "gen_data" +OpName %39 "camera" +OpName %42 "light" +OpName %45 "t_diffuse" +OpName %47 "s_diffuse" +OpName %49 "t_normal" +OpName %50 "s_normal" +OpName %52 "x" +OpName %53 "permute3" +OpName %65 "i" +OpName %68 "i1" +OpName %70 "x12" +OpName %73 "m" +OpName %77 "v" +OpName %78 "snoise2" +OpName %205 "x" +OpName %207 "v" +OpName %210 "a" +OpName %212 "i" +OpName %216 "p" +OpName %217 "fbm" +OpName %261 "p" +OpName %262 "min_max_height" +OpName %263 "terrain_point" +OpName %274 "p" +OpName %275 "min_max_height" +OpName %276 "terrain_vertex" +OpName %306 "vert_index" +OpName %307 "chunk_size" +OpName %308 "chunk_corner" +OpName %309 "index_to_p" +OpName %325 "p" +OpName %326 "color23" +OpName %348 "gid" +OpName %351 "gen_terrain_compute" +OpName %412 "vindex" +OpName %415 "index" +OpName %417 "position" +OpName %419 "uv" +OpName %421 "gen_terrain_vertex" +OpName %459 "vert_component" +OpName %461 "index" +OpName %465 "index" +OpName %467 "position" +OpName %470 "uv" +OpName %473 "vert_component" +OpName %474 "index" +OpName %475 "gen_terrain_fragment" +OpName %557 "position" +OpName %560 "normal" +OpName %562 "clip_position" +OpName %563 "normal" +OpName %565 "world_pos" +OpName %566 "vs_main" +OpName %582 "color" +OpName %586 "clip_position" +OpName %588 "normal" +OpName %590 "world_pos" +OpName %593 "fs_main" +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 1 Offset 8 +OpMemberDecorate %13 2 Offset 16 +OpMemberDecorate %14 0 Offset 0 +OpMemberDecorate %14 1 Offset 16 +OpDecorate %15 ArrayStride 32 +OpMemberDecorate %16 0 Offset 0 +OpDecorate %17 ArrayStride 4 +OpMemberDecorate %18 0 Offset 0 +OpMemberDecorate %20 0 Offset 0 +OpMemberDecorate %20 1 Offset 8 +OpMemberDecorate %20 2 Offset 16 +OpMemberDecorate %20 3 Offset 24 +OpMemberDecorate %20 4 Offset 28 +OpMemberDecorate %21 0 Offset 0 +OpMemberDecorate %21 1 Offset 16 +OpMemberDecorate %21 2 Offset 32 +OpMemberDecorate %22 0 Offset 0 +OpMemberDecorate %22 1 Offset 4 +OpMemberDecorate %24 0 Offset 0 +OpMemberDecorate %24 1 Offset 16 +OpMemberDecorate %24 1 ColMajor +OpMemberDecorate %24 1 MatrixStride 16 +OpMemberDecorate %25 0 Offset 0 +OpMemberDecorate %25 1 Offset 16 +OpMemberDecorate %26 0 Offset 0 +OpMemberDecorate %26 1 Offset 16 +OpMemberDecorate %26 2 Offset 32 +OpDecorate %29 DescriptorSet 0 +OpDecorate %29 Binding 0 +OpDecorate %30 Block +OpMemberDecorate %30 0 Offset 0 +OpDecorate %32 DescriptorSet 0 +OpDecorate %32 Binding 1 +OpDecorate %16 Block +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 2 +OpDecorate %18 Block +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 0 +OpDecorate %37 Block +OpMemberDecorate %37 0 Offset 0 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 0 +OpDecorate %40 Block +OpMemberDecorate %40 0 Offset 0 +OpDecorate %42 DescriptorSet 1 +OpDecorate %42 Binding 0 +OpDecorate %43 Block +OpMemberDecorate %43 0 Offset 0 +OpDecorate %45 DescriptorSet 2 +OpDecorate %45 Binding 0 +OpDecorate %47 DescriptorSet 2 +OpDecorate %47 Binding 1 +OpDecorate %49 DescriptorSet 2 +OpDecorate %49 Binding 2 +OpDecorate %50 DescriptorSet 2 +OpDecorate %50 Binding 3 +OpDecorate %348 BuiltIn GlobalInvocationId +OpDecorate %412 BuiltIn VertexIndex +OpDecorate %415 Location 0 +OpDecorate %415 Flat +OpDecorate %417 BuiltIn Position +OpDecorate %419 Location 1 +OpDecorate %465 Location 0 +OpDecorate %465 Flat +OpDecorate %467 BuiltIn FragCoord +OpDecorate %470 Location 1 +OpDecorate %473 Location 0 +OpDecorate %474 Location 1 +OpDecorate %557 Location 0 +OpDecorate %560 Location 1 +OpDecorate %562 BuiltIn Position +OpDecorate %563 Location 0 +OpDecorate %565 Location 1 +OpDecorate %586 BuiltIn FragCoord +OpDecorate %588 Location 0 +OpDecorate %590 Location 1 +OpDecorate %592 Location 0 +%2 = OpTypeVoid +%5 = OpTypeFloat 32 +%4 = OpTypeVector %5 3 +%6 = OpTypeVector %5 2 +%7 = OpTypeVector %5 4 +%8 = OpTypeInt 32 0 +%9 = OpTypeMatrix %6 2 +%10 = OpTypeVector %8 2 +%12 = OpTypeInt 32 1 +%11 = OpTypeVector %12 2 +%13 = OpTypeStruct %10 %11 %6 +%14 = OpTypeStruct %4 %4 +%15 = OpTypeRuntimeArray %14 +%16 = OpTypeStruct %15 +%17 = OpTypeRuntimeArray %8 +%18 = OpTypeStruct %17 +%19 = OpTypeVector %8 3 +%20 = OpTypeStruct %10 %11 %6 %8 %8 +%21 = OpTypeStruct %8 %7 %6 +%22 = OpTypeStruct %8 %8 +%23 = OpTypeMatrix %7 4 +%24 = OpTypeStruct %7 %23 +%25 = OpTypeStruct %4 %4 +%26 = OpTypeStruct %7 %4 %4 +%27 = OpTypeImage %5 2D 0 0 0 1 Unknown +%28 = OpTypeSampler +%30 = OpTypeStruct %13 +%31 = OpTypePointer Uniform %30 +%29 = OpVariable %31 Uniform +%33 = OpTypePointer StorageBuffer %16 +%32 = OpVariable %33 StorageBuffer +%35 = OpTypePointer StorageBuffer %18 +%34 = OpVariable %35 StorageBuffer +%37 = OpTypeStruct %20 +%38 = OpTypePointer Uniform %37 +%36 = OpVariable %38 Uniform +%40 = OpTypeStruct %24 +%41 = OpTypePointer Uniform %40 +%39 = OpVariable %41 Uniform +%43 = OpTypeStruct %25 +%44 = OpTypePointer Uniform %43 +%42 = OpVariable %44 Uniform +%46 = OpTypePointer UniformConstant %27 +%45 = OpVariable %46 UniformConstant +%48 = OpTypePointer UniformConstant %28 +%47 = OpVariable %48 UniformConstant +%49 = OpVariable %46 UniformConstant +%50 = OpVariable %48 UniformConstant +%54 = OpTypeFunction %4 %4 +%55 = OpConstant %5 34.0 +%56 = OpConstant %5 1.0 +%57 = OpConstant %5 289.0 +%66 = OpTypePointer Function %6 +%67 = OpConstantNull %6 +%69 = OpConstantNull %6 +%71 = OpTypePointer Function %7 +%72 = OpConstantNull %7 +%74 = OpTypePointer Function %4 +%75 = OpConstantNull %4 +%79 = OpTypeFunction %5 %6 +%80 = OpConstant %5 0.21132487 +%81 = OpConstant %5 0.36602542 +%82 = OpConstant %5 -0.57735026 +%83 = OpConstant %5 0.024390243 +%84 = OpConstant %5 0.0 +%85 = OpConstant %5 0.5 +%86 = OpConstant %5 2.0 +%87 = OpConstant %5 1.7928429 +%88 = OpConstant %5 0.85373473 +%89 = OpConstant %5 130.0 +%108 = OpTypeBool +%111 = OpTypeVector %108 2 +%122 = OpTypePointer Function %5 +%123 = OpConstant %8 1 +%132 = OpConstant %8 0 +%206 = OpConstantNull %6 +%208 = OpTypePointer Function %5 +%209 = OpConstantNull %5 +%211 = OpConstantNull %5 +%213 = OpTypePointer Function %8 +%214 = OpConstantNull %8 +%218 = OpConstant %8 5 +%219 = OpConstant %5 0.01 +%220 = OpConstant %5 100.0 +%264 = OpTypeFunction %4 %6 %6 +%277 = OpTypeFunction %14 %6 %6 +%278 = OpConstant %5 0.1 +%279 = OpConstant %5 -0.1 +%310 = OpTypeFunction %6 %8 %10 %11 +%327 = OpTypeFunction %4 %6 +%328 = OpConstant %5 23.0 +%329 = OpConstant %5 32.0 +%330 = OpConstant %5 -43.0 +%331 = OpConstant %5 3.0 +%349 = OpTypePointer Input %19 +%348 = OpVariable %349 Input +%352 = OpTypeFunction %2 +%353 = OpTypePointer Uniform %13 +%355 = OpConstant %8 6 +%356 = OpConstant %8 2 +%357 = OpConstant %8 3 +%358 = OpConstant %8 4 +%361 = OpTypePointer Uniform %10 +%364 = OpTypePointer Uniform %11 +%368 = OpTypePointer StorageBuffer %15 +%369 = OpTypePointer StorageBuffer %14 +%370 = OpTypePointer Uniform %6 +%377 = OpTypePointer Uniform %8 +%398 = OpTypePointer StorageBuffer %17 +%399 = OpTypePointer StorageBuffer %8 +%413 = OpTypePointer Input %8 +%412 = OpVariable %413 Input +%416 = OpTypePointer Output %8 +%415 = OpVariable %416 Output +%418 = OpTypePointer Output %7 +%417 = OpVariable %418 Output +%420 = OpTypePointer Output %6 +%419 = OpVariable %420 Output +%422 = OpTypePointer Uniform %20 +%424 = OpConstant %5 -1.0 +%440 = OpTypePointer Uniform %8 +%460 = OpConstantNull %5 +%462 = OpConstantNull %8 +%465 = OpVariable %413 Input +%468 = OpTypePointer Input %7 +%467 = OpVariable %468 Input +%471 = OpTypePointer Input %6 +%470 = OpVariable %471 Input +%473 = OpVariable %416 Output +%474 = OpVariable %416 Output +%477 = OpConstant %5 6.0 +%558 = OpTypePointer Input %4 +%557 = OpVariable %558 Input +%560 = OpVariable %558 Input +%562 = OpVariable %418 Output +%564 = OpTypePointer Output %4 +%563 = OpVariable %564 Output +%565 = OpVariable %564 Output +%567 = OpTypePointer Uniform %24 +%570 = OpTypePointer Uniform %23 +%583 = OpConstantNull %4 +%586 = OpVariable %468 Input +%588 = OpVariable %558 Input +%590 = OpVariable %558 Input +%592 = OpVariable %418 Output +%595 = OpTypePointer Uniform %25 +%597 = OpConstant %5 0.7 +%598 = OpConstant %5 0.2 +%617 = OpTypePointer Uniform %4 +%626 = OpTypePointer Uniform %7 +%53 = OpFunction %4 None %54 +%52 = OpFunctionParameter %4 +%51 = OpLabel +OpBranch %58 +%58 = OpLabel +OpLine %3 10 52 +%59 = OpVectorTimesScalar %4 %52 %55 +OpLine %3 10 50 +%60 = OpCompositeConstruct %4 %56 %56 %56 +%61 = OpFAdd %4 %59 %60 +%62 = OpFMul %4 %61 %52 +OpLine %3 10 49 +%63 = OpCompositeConstruct %4 %57 %57 %57 +%64 = OpFRem %4 %62 %63 +OpReturnValue %64 +OpFunctionEnd +%78 = OpFunction %5 None %79 +%77 = OpFunctionParameter %6 +%76 = OpLabel +%68 = OpVariable %66 Function %69 +%73 = OpVariable %74 Function %75 +%65 = OpVariable %66 Function %67 +%70 = OpVariable %71 Function %72 +OpBranch %90 +%90 = OpLabel +OpLine %3 13 13 +%91 = OpCompositeConstruct %7 %80 %81 %82 %83 +OpLine %3 14 24 +%92 = OpVectorShuffle %6 %91 %91 1 1 +%93 = OpDot %5 %77 %92 +%94 = OpCompositeConstruct %6 %93 %93 +%95 = OpFAdd %6 %77 %94 +%96 = OpExtInst %6 %1 Floor %95 +OpLine %3 14 5 +OpStore %65 %96 +OpLine %3 15 14 +%97 = OpLoad %6 %65 +%98 = OpFSub %6 %77 %97 +%99 = OpLoad %6 %65 +%100 = OpVectorShuffle %6 %91 %91 0 0 +%101 = OpDot %5 %99 %100 +%102 = OpCompositeConstruct %6 %101 %101 +%103 = OpFAdd %6 %98 %102 +OpLine %3 17 32 +%104 = OpCompositeConstruct %6 %56 %84 +OpLine %3 17 25 +%105 = OpCompositeConstruct %6 %84 %56 +%106 = OpCompositeExtract %5 %103 0 +%107 = OpCompositeExtract %5 %103 1 +%109 = OpFOrdLessThan %108 %106 %107 +%112 = OpCompositeConstruct %111 %109 %109 +%110 = OpSelect %6 %112 %105 %104 +OpLine %3 17 5 +OpStore %68 %110 +OpLine %3 18 26 +%113 = OpVectorShuffle %7 %103 %103 0 1 0 1 +%114 = OpVectorShuffle %7 %91 %91 0 0 2 2 +%115 = OpFAdd %7 %113 %114 +%116 = OpLoad %6 %68 +OpLine %3 18 26 +%117 = OpCompositeConstruct %7 %116 %84 %84 +%118 = OpFSub %7 %115 %117 +OpLine %3 18 5 +OpStore %70 %118 +OpLine %3 1 1 +%119 = OpLoad %6 %65 +OpLine %3 19 9 +%120 = OpCompositeConstruct %6 %57 %57 +%121 = OpFRem %6 %119 %120 +OpLine %3 19 5 +OpStore %65 %121 +OpLine %3 20 31 +%124 = OpAccessChain %122 %65 %123 +%125 = OpLoad %5 %124 +OpLine %3 20 51 +%126 = OpAccessChain %122 %68 %123 +%127 = OpLoad %5 %126 +OpLine %3 20 31 +%128 = OpCompositeConstruct %4 %84 %127 %56 +%129 = OpCompositeConstruct %4 %125 %125 %125 +%130 = OpFAdd %4 %129 %128 +OpLine %3 20 22 +%131 = OpFunctionCall %4 %53 %130 +OpLine %3 20 22 +%133 = OpAccessChain %122 %65 %132 +%134 = OpLoad %5 %133 +%135 = OpCompositeConstruct %4 %134 %134 %134 +%136 = OpFAdd %4 %131 %135 +OpLine %3 20 84 +%137 = OpAccessChain %122 %68 %132 +%138 = OpLoad %5 %137 +OpLine %3 20 22 +%139 = OpCompositeConstruct %4 %84 %138 %56 +%140 = OpFAdd %4 %136 %139 +OpLine %3 20 13 +%141 = OpFunctionCall %4 %53 %140 +OpLine %3 21 28 +%142 = OpDot %5 %103 %103 +%143 = OpLoad %7 %70 +%144 = OpVectorShuffle %6 %143 %143 0 1 +%145 = OpLoad %7 %70 +%146 = OpVectorShuffle %6 %145 %145 0 1 +%147 = OpDot %5 %144 %146 +%148 = OpLoad %7 %70 +%149 = OpVectorShuffle %6 %148 %148 2 3 +%150 = OpLoad %7 %70 +%151 = OpVectorShuffle %6 %150 %150 2 3 +%152 = OpDot %5 %149 %151 +%153 = OpCompositeConstruct %4 %142 %147 %152 +%154 = OpCompositeConstruct %4 %85 %85 %85 +%155 = OpFSub %4 %154 %153 +OpLine %3 21 24 +%156 = OpCompositeConstruct %4 %84 %84 %84 +%157 = OpExtInst %4 %1 FMax %155 %156 +OpLine %3 21 5 +OpStore %73 %157 +OpLine %3 22 9 +%158 = OpLoad %4 %73 +%159 = OpLoad %4 %73 +%160 = OpFMul %4 %158 %159 +OpLine %3 22 5 +OpStore %73 %160 +OpLine %3 23 9 +%161 = OpLoad %4 %73 +%162 = OpLoad %4 %73 +%163 = OpFMul %4 %161 %162 +OpLine %3 23 5 +OpStore %73 %163 +OpLine %3 24 13 +%164 = OpVectorShuffle %4 %91 %91 3 3 3 +%165 = OpFMul %4 %141 %164 +%166 = OpExtInst %4 %1 Fract %165 +%167 = OpVectorTimesScalar %4 %166 %86 +OpLine %3 24 13 +%168 = OpCompositeConstruct %4 %56 %56 %56 +%169 = OpFSub %4 %167 %168 +OpLine %3 25 13 +%170 = OpExtInst %4 %1 FAbs %169 +OpLine %3 25 13 +%171 = OpCompositeConstruct %4 %85 %85 %85 +%172 = OpFSub %4 %170 %171 +OpLine %3 26 14 +%173 = OpCompositeConstruct %4 %85 %85 %85 +%174 = OpFAdd %4 %169 %173 +%175 = OpExtInst %4 %1 Floor %174 +OpLine %3 27 14 +%176 = OpFSub %4 %169 %175 +OpLine %3 1 1 +%177 = OpLoad %4 %73 +OpLine %3 28 9 +%178 = OpFMul %4 %176 %176 +%179 = OpFMul %4 %172 %172 +%180 = OpFAdd %4 %178 %179 +%181 = OpVectorTimesScalar %4 %180 %88 +%182 = OpCompositeConstruct %4 %87 %87 %87 +%183 = OpFSub %4 %182 %181 +%184 = OpFMul %4 %177 %183 +OpLine %3 28 5 +OpStore %73 %184 +OpLine %3 29 13 +%185 = OpCompositeExtract %5 %176 0 +%186 = OpCompositeExtract %5 %103 0 +%187 = OpFMul %5 %185 %186 +%188 = OpCompositeExtract %5 %172 0 +%189 = OpCompositeExtract %5 %103 1 +%190 = OpFMul %5 %188 %189 +%191 = OpFAdd %5 %187 %190 +%192 = OpVectorShuffle %6 %176 %176 1 2 +%193 = OpLoad %7 %70 +%194 = OpVectorShuffle %6 %193 %193 0 2 +%195 = OpFMul %6 %192 %194 +%196 = OpVectorShuffle %6 %172 %172 1 2 +%197 = OpLoad %7 %70 +%198 = OpVectorShuffle %6 %197 %197 1 3 +%199 = OpFMul %6 %196 %198 +%200 = OpFAdd %6 %195 %199 +%201 = OpCompositeConstruct %4 %191 %200 +OpLine %3 30 12 +%202 = OpLoad %4 %73 +%203 = OpDot %5 %202 %201 +%204 = OpFMul %5 %89 %203 +OpReturnValue %204 +OpFunctionEnd +%217 = OpFunction %5 None %79 +%216 = OpFunctionParameter %6 +%215 = OpLabel +%207 = OpVariable %208 Function %209 +%212 = OpVariable %213 Function %214 +%205 = OpVariable %66 Function %206 +%210 = OpVariable %208 Function %211 +OpBranch %221 +%221 = OpLabel +OpLine %3 36 13 +%222 = OpVectorTimesScalar %6 %216 %219 +OpLine %3 36 5 +OpStore %205 %222 +OpLine %3 37 5 +OpStore %207 %84 +OpLine %3 38 5 +OpStore %210 %85 +OpLine %3 39 17 +%223 = OpCompositeConstruct %6 %220 %220 +OpLine %3 40 24 +%224 = OpExtInst %5 %1 Cos %85 +OpLine %3 40 14 +%225 = OpExtInst %5 %1 Sin %85 +%226 = OpCompositeConstruct %6 %224 %225 +OpLine %3 41 15 +%227 = OpCompositeExtract %5 %226 0 +%228 = OpCompositeExtract %5 %226 1 +%229 = OpCompositeExtract %5 %226 1 +%230 = OpFNegate %5 %229 +%231 = OpCompositeExtract %5 %226 0 +%232 = OpCompositeConstruct %6 %227 %228 +%233 = OpCompositeConstruct %6 %230 %231 +%234 = OpCompositeConstruct %9 %232 %233 +OpLine %3 43 10 +OpStore %212 %132 +OpBranch %235 +%235 = OpLabel +OpLine %3 43 5 +OpLoopMerge %236 %238 None +OpBranch %237 +%237 = OpLabel +OpLine %3 43 22 +%239 = OpLoad %8 %212 +%240 = OpULessThan %108 %239 %218 +OpLine %3 43 21 +OpSelectionMerge %241 None +OpBranchConditional %240 %241 %242 +%242 = OpLabel +OpBranch %236 +%241 = OpLabel +OpBranch %243 +%243 = OpLabel +OpLine %3 1 1 +%245 = OpLoad %5 %207 +%246 = OpLoad %5 %210 +%247 = OpLoad %6 %205 +OpLine %3 44 21 +%248 = OpFunctionCall %5 %78 %247 +OpLine %3 44 13 +%249 = OpFMul %5 %246 %248 +%250 = OpFAdd %5 %245 %249 +OpLine %3 44 9 +OpStore %207 %250 +OpLine %3 45 13 +%251 = OpLoad %6 %205 +%252 = OpMatrixTimesVector %6 %234 %251 +OpLine %3 45 13 +%253 = OpVectorTimesScalar %6 %252 %86 +%254 = OpFAdd %6 %253 %223 +OpLine %3 45 9 +OpStore %205 %254 +OpLine %3 1 1 +%255 = OpLoad %5 %210 +OpLine %3 46 13 +%256 = OpFMul %5 %255 %85 +OpLine %3 46 9 +OpStore %210 %256 +OpBranch %244 +%244 = OpLabel +OpBranch %238 +%238 = OpLabel +OpLine %3 1 1 +%257 = OpLoad %8 %212 +OpLine %3 43 43 +%258 = OpIAdd %8 %257 %123 +OpLine %3 43 39 +OpStore %212 %258 +OpBranch %235 +%236 = OpLabel +OpLine %3 1 1 +%259 = OpLoad %5 %207 +OpReturnValue %259 +OpFunctionEnd +%263 = OpFunction %4 None %264 +%261 = OpFunctionParameter %6 +%262 = OpFunctionParameter %6 +%260 = OpLabel +OpBranch %265 +%265 = OpLabel +OpLine %3 77 9 +%266 = OpCompositeExtract %5 %261 0 +%267 = OpCompositeExtract %5 %262 0 +%268 = OpCompositeExtract %5 %262 1 +OpLine %3 78 49 +%269 = OpFunctionCall %5 %217 %261 +OpLine %3 76 12 +%270 = OpExtInst %5 %1 FMix %267 %268 %269 +%271 = OpCompositeExtract %5 %261 1 +%272 = OpCompositeConstruct %4 %266 %270 %271 +OpReturnValue %272 +OpFunctionEnd +%276 = OpFunction %14 None %277 +%274 = OpFunctionParameter %6 +%275 = OpFunctionParameter %6 +%273 = OpLabel +OpBranch %280 +%280 = OpLabel +OpLine %3 84 13 +%281 = OpFunctionCall %4 %263 %274 %275 +OpLine %3 86 29 +%282 = OpCompositeConstruct %6 %278 %84 +%283 = OpFAdd %6 %274 %282 +OpLine %3 86 15 +%284 = OpFunctionCall %4 %263 %283 %275 +OpLine %3 86 15 +%285 = OpFSub %4 %284 %281 +OpLine %3 87 29 +%286 = OpCompositeConstruct %6 %84 %278 +%287 = OpFAdd %6 %274 %286 +OpLine %3 87 15 +%288 = OpFunctionCall %4 %263 %287 %275 +OpLine %3 87 15 +%289 = OpFSub %4 %288 %281 +OpLine %3 88 29 +%290 = OpCompositeConstruct %6 %279 %84 +%291 = OpFAdd %6 %274 %290 +OpLine %3 88 15 +%292 = OpFunctionCall %4 %263 %291 %275 +OpLine %3 88 15 +%293 = OpFSub %4 %292 %281 +OpLine %3 89 29 +%294 = OpCompositeConstruct %6 %84 %279 +%295 = OpFAdd %6 %274 %294 +OpLine %3 89 15 +%296 = OpFunctionCall %4 %263 %295 %275 +OpLine %3 89 15 +%297 = OpFSub %4 %296 %281 +OpLine %3 91 14 +%298 = OpExtInst %4 %1 Cross %289 %285 +%299 = OpExtInst %4 %1 Normalize %298 +OpLine %3 92 14 +%300 = OpExtInst %4 %1 Cross %297 %293 +%301 = OpExtInst %4 %1 Normalize %300 +OpLine %3 94 14 +%302 = OpFAdd %4 %299 %301 +OpLine %3 94 13 +%303 = OpVectorTimesScalar %4 %302 %85 +OpLine %3 96 12 +%304 = OpCompositeConstruct %14 %281 %303 +OpReturnValue %304 +OpFunctionEnd +%309 = OpFunction %6 None %310 +%306 = OpFunctionParameter %8 +%307 = OpFunctionParameter %10 +%308 = OpFunctionParameter %11 +%305 = OpLabel +OpBranch %311 +%311 = OpLabel +OpLine %3 101 9 +%312 = OpConvertUToF %5 %306 +%313 = OpCompositeExtract %8 %307 0 +OpLine %3 101 9 +%314 = OpIAdd %8 %313 %123 +%315 = OpConvertUToF %5 %314 +%316 = OpFRem %5 %312 %315 +%317 = OpCompositeExtract %8 %307 0 +OpLine %3 100 12 +%318 = OpIAdd %8 %317 %123 +%319 = OpUDiv %8 %306 %318 +%320 = OpConvertUToF %5 %319 +%321 = OpCompositeConstruct %6 %316 %320 +%322 = OpConvertSToF %6 %308 +%323 = OpFAdd %6 %321 %322 +OpReturnValue %323 +OpFunctionEnd +%326 = OpFunction %4 None %327 +%325 = OpFunctionParameter %6 +%324 = OpLabel +OpBranch %332 +%332 = OpLabel +OpLine %3 270 9 +%333 = OpFunctionCall %5 %78 %325 +OpLine %3 270 9 +%334 = OpFMul %5 %333 %85 +OpLine %3 270 9 +%335 = OpFAdd %5 %334 %85 +OpLine %3 271 17 +%336 = OpCompositeConstruct %6 %328 %329 +%337 = OpFAdd %6 %325 %336 +OpLine %3 271 9 +%338 = OpFunctionCall %5 %78 %337 +OpLine %3 271 9 +%339 = OpFMul %5 %338 %85 +OpLine %3 271 9 +%340 = OpFAdd %5 %339 %85 +OpLine %3 272 17 +%341 = OpCompositeConstruct %6 %330 %331 +%342 = OpFAdd %6 %325 %341 +OpLine %3 272 9 +%343 = OpFunctionCall %5 %78 %342 +OpLine %3 272 9 +%344 = OpFMul %5 %343 %85 +OpLine %3 269 12 +%345 = OpFAdd %5 %344 %85 +%346 = OpCompositeConstruct %4 %335 %340 %345 +OpReturnValue %346 +OpFunctionEnd +%351 = OpFunction %2 None %352 +%347 = OpLabel +%350 = OpLoad %19 %348 +%354 = OpAccessChain %353 %29 %132 +OpBranch %359 +%359 = OpLabel +OpLine %3 111 22 +%360 = OpCompositeExtract %8 %350 0 +OpLine %3 113 36 +%362 = OpAccessChain %361 %354 %132 +%363 = OpLoad %10 %362 +OpLine %3 113 59 +%365 = OpAccessChain %364 %354 %123 +%366 = OpLoad %11 %365 +OpLine %3 113 13 +%367 = OpFunctionCall %6 %309 %360 %363 %366 +OpLine %3 115 5 +OpLine %3 115 51 +%371 = OpAccessChain %370 %354 %356 +%372 = OpLoad %6 %371 +OpLine %3 115 33 +%373 = OpFunctionCall %14 %276 %367 %372 +OpLine %3 115 5 +%374 = OpAccessChain %369 %32 %132 %360 +OpStore %374 %373 +OpLine %3 118 23 +%375 = OpCompositeExtract %8 %350 0 +OpLine %3 118 23 +%376 = OpIMul %8 %375 %355 +OpLine %3 120 25 +%378 = OpAccessChain %377 %354 %132 %132 +%379 = OpLoad %8 %378 +OpLine %3 120 25 +%380 = OpAccessChain %377 %354 %132 %123 +%381 = OpLoad %8 %380 +%382 = OpIMul %8 %379 %381 +OpLine %3 120 9 +%383 = OpIMul %8 %382 %355 +%384 = OpUGreaterThanEqual %108 %376 %383 +OpLine %3 120 5 +OpSelectionMerge %385 None +OpBranchConditional %384 %386 %385 +%386 = OpLabel +OpReturn +%385 = OpLabel +OpLine %3 122 28 +%387 = OpCompositeExtract %8 %350 0 +OpLine %3 122 15 +%388 = OpAccessChain %377 %354 %132 %132 +%389 = OpLoad %8 %388 +%390 = OpUDiv %8 %387 %389 +%391 = OpIAdd %8 %360 %390 +OpLine %3 123 15 +%392 = OpIAdd %8 %391 %123 +OpLine %3 124 15 +%393 = OpAccessChain %377 %354 %132 %132 +%394 = OpLoad %8 %393 +%395 = OpIAdd %8 %391 %394 +OpLine %3 124 15 +%396 = OpIAdd %8 %395 %123 +OpLine %3 125 15 +%397 = OpIAdd %8 %396 %123 +OpLine %3 127 5 +OpLine %3 127 5 +%400 = OpAccessChain %399 %34 %132 %376 +OpStore %400 %391 +OpLine %3 128 5 +OpLine %3 128 5 +%401 = OpIAdd %8 %376 %123 +OpLine %3 128 5 +%402 = OpAccessChain %399 %34 %132 %401 +OpStore %402 %396 +OpLine %3 129 5 +OpLine %3 129 5 +%403 = OpIAdd %8 %376 %356 +OpLine %3 129 5 +%404 = OpAccessChain %399 %34 %132 %403 +OpStore %404 %397 +OpLine %3 130 5 +OpLine %3 130 5 +%405 = OpIAdd %8 %376 %357 +OpLine %3 130 5 +%406 = OpAccessChain %399 %34 %132 %405 +OpStore %406 %391 +OpLine %3 131 5 +OpLine %3 131 5 +%407 = OpIAdd %8 %376 %358 +OpLine %3 131 5 +%408 = OpAccessChain %399 %34 %132 %407 +OpStore %408 %397 +OpLine %3 132 5 +OpLine %3 132 5 +%409 = OpIAdd %8 %376 %218 +OpLine %3 132 5 +%410 = OpAccessChain %399 %34 %132 %409 +OpStore %410 %392 +OpReturn +OpFunctionEnd +%421 = OpFunction %2 None %352 +%411 = OpLabel +%414 = OpLoad %8 %412 +%423 = OpAccessChain %422 %36 %132 +OpBranch %425 +%425 = OpLabel +OpLine %3 161 19 +%426 = OpIAdd %8 %414 %356 +OpLine %3 161 18 +%427 = OpUDiv %8 %426 %357 +OpLine %3 161 13 +%428 = OpUMod %8 %427 %356 +%429 = OpConvertUToF %5 %428 +OpLine %3 162 19 +%430 = OpIAdd %8 %414 %123 +OpLine %3 162 18 +%431 = OpUDiv %8 %430 %357 +OpLine %3 162 13 +%432 = OpUMod %8 %431 %356 +%433 = OpConvertUToF %5 %432 +OpLine %3 163 14 +%434 = OpCompositeConstruct %6 %429 %433 +OpLine %3 165 30 +%435 = OpVectorTimesScalar %6 %434 %86 +%436 = OpCompositeConstruct %6 %424 %424 +%437 = OpFAdd %6 %436 %435 +OpLine %3 165 20 +%438 = OpCompositeConstruct %7 %437 %84 %56 +OpLine %3 168 21 +%439 = OpCompositeExtract %5 %434 0 +OpLine %3 168 21 +%441 = OpAccessChain %440 %423 %357 +%442 = OpLoad %8 %441 +%443 = OpConvertUToF %5 %442 +%444 = OpFMul %5 %439 %443 +%445 = OpCompositeExtract %5 %434 1 +OpLine %3 168 17 +%446 = OpAccessChain %440 %423 %357 +%447 = OpLoad %8 %446 +%448 = OpConvertUToF %5 %447 +%449 = OpFMul %5 %445 %448 +%450 = OpFAdd %5 %444 %449 +%451 = OpConvertFToU %8 %450 +OpLine %3 168 17 +%452 = OpAccessChain %440 %423 %358 +%453 = OpLoad %8 %452 +%454 = OpIAdd %8 %451 %453 +OpLine %3 170 12 +%455 = OpCompositeConstruct %21 %454 %438 %434 +%456 = OpCompositeExtract %8 %455 0 +OpStore %415 %456 +%457 = OpCompositeExtract %7 %455 1 +OpStore %417 %457 +%458 = OpCompositeExtract %6 %455 2 +OpStore %419 %458 +OpReturn +OpFunctionEnd +%475 = OpFunction %2 None %352 +%463 = OpLabel +%459 = OpVariable %208 Function %460 +%461 = OpVariable %213 Function %462 +%466 = OpLoad %8 %465 +%469 = OpLoad %7 %467 +%472 = OpLoad %6 %470 +%464 = OpCompositeConstruct %21 %466 %469 %472 +%476 = OpAccessChain %422 %36 %132 +OpBranch %478 +%478 = OpLabel +OpLine %3 181 17 +%479 = OpCompositeExtract %6 %464 2 +%480 = OpCompositeExtract %5 %479 0 +OpLine %3 181 17 +%481 = OpAccessChain %440 %476 %357 +%482 = OpLoad %8 %481 +%483 = OpConvertUToF %5 %482 +%484 = OpFMul %5 %480 %483 +%485 = OpCompositeExtract %6 %464 2 +%486 = OpCompositeExtract %5 %485 1 +OpLine %3 181 70 +%487 = OpAccessChain %440 %476 %357 +%488 = OpLoad %8 %487 +OpLine %3 181 13 +%489 = OpAccessChain %440 %476 %357 +%490 = OpLoad %8 %489 +%491 = OpIMul %8 %488 %490 +%492 = OpConvertUToF %5 %491 +%493 = OpFMul %5 %486 %492 +%494 = OpFAdd %5 %484 %493 +%495 = OpConvertFToU %8 %494 +OpLine %3 181 13 +%496 = OpAccessChain %440 %476 %358 +%497 = OpLoad %8 %496 +%498 = OpIAdd %8 %495 %497 +OpLine %3 182 32 +%499 = OpConvertUToF %5 %498 +OpLine %3 182 22 +%500 = OpFDiv %5 %499 %477 +%501 = OpExtInst %5 %1 Floor %500 +%502 = OpConvertFToU %8 %501 +OpLine %3 183 22 +%503 = OpUMod %8 %498 %355 +OpLine %3 185 36 +%504 = OpAccessChain %361 %476 %132 +%505 = OpLoad %10 %504 +OpLine %3 185 57 +%506 = OpAccessChain %364 %476 %123 +%507 = OpLoad %11 %506 +OpLine %3 185 13 +%508 = OpFunctionCall %6 %309 %502 %505 %507 +OpLine %3 186 31 +%509 = OpAccessChain %370 %476 %356 +%510 = OpLoad %6 %509 +OpLine %3 186 13 +%511 = OpFunctionCall %14 %276 %508 %510 +OpLine %3 188 5 +OpStore %459 %84 +OpLine %3 190 5 +OpSelectionMerge %512 None +OpSwitch %503 %519 0 %513 1 %514 2 %515 3 %516 4 %517 5 %518 +%513 = OpLabel +OpLine %3 191 37 +%520 = OpCompositeExtract %4 %511 0 +%521 = OpCompositeExtract %5 %520 0 +OpLine %3 191 20 +OpStore %459 %521 +OpBranch %512 +%514 = OpLabel +OpLine %3 192 37 +%522 = OpCompositeExtract %4 %511 0 +%523 = OpCompositeExtract %5 %522 1 +OpLine %3 192 20 +OpStore %459 %523 +OpBranch %512 +%515 = OpLabel +OpLine %3 193 37 +%524 = OpCompositeExtract %4 %511 0 +%525 = OpCompositeExtract %5 %524 2 +OpLine %3 193 20 +OpStore %459 %525 +OpBranch %512 +%516 = OpLabel +OpLine %3 194 37 +%526 = OpCompositeExtract %4 %511 1 +%527 = OpCompositeExtract %5 %526 0 +OpLine %3 194 20 +OpStore %459 %527 +OpBranch %512 +%517 = OpLabel +OpLine %3 195 37 +%528 = OpCompositeExtract %4 %511 1 +%529 = OpCompositeExtract %5 %528 1 +OpLine %3 195 20 +OpStore %459 %529 +OpBranch %512 +%518 = OpLabel +OpLine %3 196 37 +%530 = OpCompositeExtract %4 %511 1 +%531 = OpCompositeExtract %5 %530 2 +OpLine %3 196 20 +OpStore %459 %531 +OpBranch %512 +%519 = OpLabel +OpBranch %512 +%512 = OpLabel +OpLine %3 200 15 +%532 = OpAccessChain %377 %476 %132 %132 +%533 = OpLoad %8 %532 +%534 = OpUDiv %8 %502 %533 +%535 = OpIAdd %8 %502 %534 +OpLine %3 201 15 +%536 = OpIAdd %8 %535 %123 +OpLine %3 202 15 +%537 = OpAccessChain %377 %476 %132 %132 +%538 = OpLoad %8 %537 +%539 = OpIAdd %8 %535 %538 +OpLine %3 202 15 +%540 = OpIAdd %8 %539 %123 +OpLine %3 203 15 +%541 = OpIAdd %8 %540 %123 +OpLine %3 205 5 +OpStore %461 %132 +OpLine %3 206 5 +OpSelectionMerge %542 None +OpSwitch %503 %547 0 %543 3 %543 2 %544 4 %544 1 %545 5 %546 +%543 = OpLabel +OpLine %3 207 24 +OpStore %461 %535 +OpBranch %542 +%544 = OpLabel +OpLine %3 208 24 +OpStore %461 %541 +OpBranch %542 +%545 = OpLabel +OpLine %3 209 20 +OpStore %461 %540 +OpBranch %542 +%546 = OpLabel +OpLine %3 210 20 +OpStore %461 %536 +OpBranch %542 +%547 = OpLabel +OpBranch %542 +%542 = OpLabel +OpLine %3 213 13 +%548 = OpCompositeExtract %8 %464 0 +OpLine %3 213 5 +OpStore %461 %548 +OpLine %3 222 27 +%549 = OpLoad %5 %459 +%550 = OpBitcast %8 %549 +OpLine %3 223 12 +%551 = OpLoad %8 %461 +%552 = OpCompositeConstruct %22 %550 %551 +%553 = OpCompositeExtract %8 %552 0 +OpStore %473 %553 +%554 = OpCompositeExtract %8 %552 1 +OpStore %474 %554 +OpReturn +OpFunctionEnd +%566 = OpFunction %2 None %352 +%555 = OpLabel +%559 = OpLoad %4 %557 +%561 = OpLoad %4 %560 +%556 = OpCompositeConstruct %14 %559 %561 +%568 = OpAccessChain %567 %39 %132 +OpBranch %569 +%569 = OpLabel +OpLine %3 254 25 +%571 = OpAccessChain %570 %568 %123 +%572 = OpLoad %23 %571 +%573 = OpCompositeExtract %4 %556 0 +OpLine %3 254 25 +%574 = OpCompositeConstruct %7 %573 %56 +%575 = OpMatrixTimesVector %7 %572 %574 +OpLine %3 255 18 +%576 = OpCompositeExtract %4 %556 1 +OpLine %3 256 12 +%577 = OpCompositeExtract %4 %556 0 +%578 = OpCompositeConstruct %26 %575 %576 %577 +%579 = OpCompositeExtract %7 %578 0 +OpStore %562 %579 +%580 = OpCompositeExtract %4 %578 1 +OpStore %563 %580 +%581 = OpCompositeExtract %4 %578 2 +OpStore %565 %581 +OpReturn +OpFunctionEnd +%593 = OpFunction %2 None %352 +%584 = OpLabel +%582 = OpVariable %74 Function %583 +%587 = OpLoad %7 %586 +%589 = OpLoad %4 %588 +%591 = OpLoad %4 %590 +%585 = OpCompositeConstruct %26 %587 %589 %591 +%594 = OpAccessChain %567 %39 %132 +%596 = OpAccessChain %595 %42 %132 +OpBranch %599 +%599 = OpLabel +OpLine %3 278 28 +%600 = OpCompositeConstruct %4 %84 %84 %84 +OpLine %3 278 17 +%601 = OpCompositeConstruct %4 %278 %278 %278 +%602 = OpCompositeExtract %4 %585 2 +%603 = OpExtInst %4 %1 Fract %602 +%604 = OpExtInst %4 %1 SmoothStep %600 %601 %603 +OpLine %3 278 5 +OpStore %582 %604 +OpLine %3 279 17 +%605 = OpCompositeConstruct %4 %85 %278 %597 +OpLine %3 279 13 +%606 = OpCompositeConstruct %4 %598 %598 %598 +%607 = OpAccessChain %122 %582 %132 +%608 = OpLoad %5 %607 +%609 = OpAccessChain %122 %582 %123 +%610 = OpLoad %5 %609 +%611 = OpFMul %5 %608 %610 +%612 = OpAccessChain %122 %582 %356 +%613 = OpLoad %5 %612 +%614 = OpFMul %5 %611 %613 +%615 = OpCompositeConstruct %4 %614 %614 %614 +%616 = OpExtInst %4 %1 FMix %605 %606 %615 +OpLine %3 279 5 +OpStore %582 %616 +OpLine %3 282 25 +%618 = OpAccessChain %617 %596 %123 +%619 = OpLoad %4 %618 +%620 = OpVectorTimesScalar %4 %619 %278 +OpLine %3 284 21 +%621 = OpAccessChain %617 %596 %132 +%622 = OpLoad %4 %621 +%623 = OpCompositeExtract %4 %585 2 +%624 = OpFSub %4 %622 %623 +%625 = OpExtInst %4 %1 Normalize %624 +OpLine %3 285 20 +%627 = OpAccessChain %626 %594 %132 +%628 = OpLoad %7 %627 +%629 = OpVectorShuffle %4 %628 %628 0 1 2 +%630 = OpCompositeExtract %4 %585 2 +%631 = OpFSub %4 %629 %630 +%632 = OpExtInst %4 %1 Normalize %631 +OpLine %3 286 20 +%633 = OpFAdd %4 %632 %625 +%634 = OpExtInst %4 %1 Normalize %633 +OpLine %3 288 32 +%635 = OpCompositeExtract %4 %585 1 +%636 = OpDot %5 %635 %625 +OpLine %3 288 28 +%637 = OpExtInst %5 %1 FMax %636 %84 +OpLine %3 289 25 +%638 = OpAccessChain %617 %596 %123 +%639 = OpLoad %4 %638 +%640 = OpVectorTimesScalar %4 %639 %637 +OpLine %3 291 37 +%641 = OpCompositeExtract %4 %585 1 +%642 = OpDot %5 %641 %634 +OpLine %3 291 33 +%643 = OpExtInst %5 %1 FMax %642 %84 +OpLine %3 291 29 +%644 = OpExtInst %5 %1 Pow %643 %329 +OpLine %3 292 26 +%645 = OpAccessChain %617 %596 %123 +%646 = OpLoad %4 %645 +%647 = OpVectorTimesScalar %4 %646 %644 +OpLine %3 294 18 +%648 = OpFAdd %4 %620 %640 +%649 = OpFAdd %4 %648 %647 +%650 = OpLoad %4 %582 +%651 = OpFMul %4 %649 %650 +OpLine %3 296 12 +%652 = OpCompositeConstruct %7 %651 %56 +OpStore %592 %652 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 6b94b3e27..4f9dd442e 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -23,7 +23,6 @@ OpExecutionMode %299 OriginUpperLeft OpExecutionMode %444 OriginUpperLeft OpExecutionMode %499 OriginUpperLeft OpExecutionMode %534 OriginUpperLeft -OpSource GLSL 450 OpName %35 "image_mipmapped_src" OpName %37 "image_multisampled_src" OpName %39 "image_depth_multisampled_src" diff --git a/tests/out/spv/interpolate.spvasm b/tests/out/spv/interpolate.spvasm index b9df1e059..bcfad15c1 100644 --- a/tests/out/spv/interpolate.spvasm +++ b/tests/out/spv/interpolate.spvasm @@ -9,7 +9,6 @@ OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %29 "vert_main" %13 %15 %17 %19 %21 %23 %24 %25 %26 OpEntryPoint Fragment %109 "frag_main" %88 %91 %94 %97 %100 %103 %105 %107 OpExecutionMode %109 OriginUpperLeft -OpSource GLSL 450 OpMemberName %8 0 "position" OpMemberName %8 1 "_flat" OpMemberName %8 2 "_linear" diff --git a/tests/out/spv/padding.spvasm b/tests/out/spv/padding.spvasm index 485ac9367..0efcef10e 100644 --- a/tests/out/spv/padding.spvasm +++ b/tests/out/spv/padding.spvasm @@ -6,7 +6,6 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %28 "vertex" %26 -OpSource GLSL 450 OpMemberName %7 0 "a" OpName %7 "S" OpMemberName %8 0 "a" diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index 71a680aa7..3debe27b1 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -7,7 +7,6 @@ OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpSource GLSL 450 OpMemberName %7 0 "arr" OpName %7 "DynamicArray" OpName %10 "dynamic_array" diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index d11747605..970da7d10 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -8,7 +8,6 @@ OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpSource GLSL 450 OpMemberName %14 0 "a" OpName %14 "InStorage" OpMemberName %17 0 "a" diff --git a/tests/out/spv/quad.spvasm b/tests/out/spv/quad.spvasm index 9d4ba0226..4c82c92b0 100644 --- a/tests/out/spv/quad.spvasm +++ b/tests/out/spv/quad.spvasm @@ -10,7 +10,6 @@ OpEntryPoint Fragment %44 "frag_main" %41 %43 OpEntryPoint Fragment %60 "fs_extra" %59 OpExecutionMode %44 OriginUpperLeft OpExecutionMode %60 OriginUpperLeft -OpSource GLSL 450 OpName %3 "c_scale" OpMemberName %7 0 "uv" OpMemberName %7 1 "position" diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index d087a25c9..26ee96559 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -11,7 +11,6 @@ OpEntryPoint Fragment %149 "fs_main" %140 %143 %146 %148 OpEntryPoint Fragment %218 "fs_main_without_storage" %211 %213 %215 %217 OpExecutionMode %149 OriginUpperLeft OpExecutionMode %218 OriginUpperLeft -OpSource GLSL 450 OpName %7 "c_max_lights" OpMemberName %13 0 "view_proj" OpMemberName %13 1 "num_lights" diff --git a/tests/out/spv/texture-arg.spvasm b/tests/out/spv/texture-arg.spvasm index f761edf70..485b2d7d9 100644 --- a/tests/out/spv/texture-arg.spvasm +++ b/tests/out/spv/texture-arg.spvasm @@ -7,7 +7,6 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %28 "main" %26 OpExecutionMode %28 OriginUpperLeft -OpSource GLSL 450 OpName %8 "Texture" OpName %10 "Sampler" OpName %13 "Passed_Texture" diff --git a/tests/out/spv/workgroup-var-init.spvasm b/tests/out/spv/workgroup-var-init.spvasm index 122a61283..e95a11aa9 100644 --- a/tests/out/spv/workgroup-var-init.spvasm +++ b/tests/out/spv/workgroup-var-init.spvasm @@ -8,7 +8,6 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %19 "main" %27 OpExecutionMode %19 LocalSize 1 1 1 -OpSource GLSL 450 OpMemberName %12 0 "arr" OpMemberName %12 1 "atom" OpMemberName %12 2 "atom_arr" diff --git a/tests/snapshots.rs b/tests/snapshots.rs index eab1aaae6..658e5fe7f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -89,7 +89,7 @@ struct Parameters { } #[allow(unused_variables)] -fn check_targets(module: &naga::Module, name: &str, targets: Targets) { +fn check_targets(module: &naga::Module, name: &str, targets: Targets, source_code: Option<&str>) { let root = env!("CARGO_MANIFEST_DIR"); let filepath = format!("{root}/{BASE_DIR_IN}/{name}.param.ron"); let params = match fs::read_to_string(&filepath) { @@ -131,12 +131,22 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets) { #[cfg(all(feature = "deserialize", feature = "spv-out"))] { + let debug_info = if cfg!(feature = "span") { + source_code.map(|code| naga::back::spv::DebugInfo { + source_code: code, + file_name: name, + }) + } else { + None + }; + if targets.contains(Targets::SPIRV) { write_output_spv( module, &info, &dest, name, + debug_info, ¶ms.spv, params.bounds_check_policies, ); @@ -204,6 +214,7 @@ fn write_output_spv( info: &naga::valid::ModuleInfo, destination: &Path, file_name: &str, + debug_info: Option, params: &SpirvOutParameters, bounds_check_policies: naga::proc::BoundsCheckPolicies, ) { @@ -232,6 +243,7 @@ fn write_output_spv( bounds_check_policies, binding_map: params.binding_map.clone(), zero_initialize_workgroup_memory: spv::ZeroInitializeWorkgroupMemoryMode::Polyfill, + debug_info, }; if params.separate_entry_points { @@ -240,22 +252,52 @@ fn write_output_spv( entry_point: ep.name.clone(), shader_stage: ep.stage, }; - let spv = spv::write_vec(module, info, &options, Some(&pipeline_options)).unwrap(); - let dis = rspirv::dr::load_words(spv) - .expect("Produced invalid SPIR-V") - .disassemble(); - let path = format!("spv/{}.{}.spvasm", file_name, ep.name); - fs::write(destination.join(path), dis).unwrap(); + write_output_spv_inner( + module, + info, + &options, + Some(&pipeline_options), + destination, + format!("spv/{}.{}.spvasm", file_name, ep.name), + ); } } else { - let spv = spv::write_vec(module, info, &options, None).unwrap(); - let dis = rspirv::dr::load_words(spv) - .expect("Produced invalid SPIR-V") - .disassemble(); - fs::write(destination.join(format!("spv/{file_name}.spvasm")), dis).unwrap(); + write_output_spv_inner( + module, + info, + &options, + None, + destination, + format!("spv/{file_name}.spvasm"), + ); } } +#[cfg(feature = "spv-out")] +fn write_output_spv_inner( + module: &naga::Module, + info: &naga::valid::ModuleInfo, + options: &naga::back::spv::Options<'_>, + pipeline_options: Option<&naga::back::spv::PipelineOptions>, + destination: &Path, + path: String, +) { + use naga::back::spv; + use rspirv::binary::Disassemble; + let spv = spv::write_vec(module, info, options, pipeline_options).unwrap(); + let dis = rspirv::dr::load_words(spv) + .expect("Produced invalid SPIR-V") + .disassemble(); + // HACK escape CR/LF if source code is in side. + let dis = if options.debug_info.is_some() { + let dis = dis.replace("\\r", "\r"); + dis.replace("\\n", "\n") + } else { + dis + }; + fs::write(destination.join(path), dis).unwrap(); +} + #[cfg(feature = "msl-out")] fn write_output_msl( module: &naga::Module, @@ -573,10 +615,28 @@ fn convert_wgsl() { let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/{name}.wgsl")) .expect("Couldn't find wgsl file"); match naga::front::wgsl::parse_str(&file) { - Ok(module) => check_targets(&module, name, targets), + Ok(module) => check_targets(&module, name, targets, None), Err(e) => panic!("{}", e.emit_to_string(&file)), } } + + #[cfg(feature = "span")] + { + let inputs = [ + ("debug-symbol-simple", Targets::SPIRV), + ("debug-symbol-terrain", Targets::SPIRV), + ]; + for &(name, targets) in inputs.iter() { + println!("Processing '{name}'"); + // WGSL shaders lives in root dir as a privileged. + let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/{name}.wgsl")) + .expect("Couldn't find wgsl file"); + match naga::front::wgsl::parse_str(&file) { + Ok(module) => check_targets(&module, name, targets, Some(&file)), + Err(e) => panic!("{}", e.emit_to_string(&file)), + } + } + } } #[cfg(feature = "spv-in")] @@ -594,7 +654,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { }, ) .unwrap(); - check_targets(&module, name, targets); + check_targets(&module, name, targets, None); naga::valid::Validator::new( naga::valid::ValidationFlags::all(), naga::valid::Capabilities::default(), @@ -648,7 +708,7 @@ fn convert_glsl_variations_check() { &file, ) .unwrap(); - check_targets(&module, "variations-glsl", Targets::GLSL); + check_targets(&module, "variations-glsl", Targets::GLSL, None); } #[cfg(feature = "glsl-in")] diff --git a/tests/spirv-capabilities.rs b/tests/spirv-capabilities.rs index f26918285..35f24b7d6 100644 --- a/tests/spirv-capabilities.rs +++ b/tests/spirv-capabilities.rs @@ -23,7 +23,9 @@ fn capabilities_used(source: &str) -> naga::FastIndexSet { let mut words = vec![]; let mut writer = spv::Writer::new(&spv::Options::default()).unwrap(); - writer.write(&module, &info, None, &mut words).unwrap(); + writer + .write(&module, &info, None, &None, &mut words) + .unwrap(); writer.get_capabilities_used().clone() } From 3ca8b4997d54711cd32890d4dbd1954b297b6f77 Mon Sep 17 00:00:00 2001 From: wicast Date: Thu, 29 Jun 2023 19:31:26 +0800 Subject: [PATCH 2029/2212] fix(spv-out-debug): fix debug options (#2394) --- cli/src/bin/naga.rs | 16 ++++++++++------ src/back/spv/mod.rs | 2 -- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index 4904a78cf..2081d1a1b 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -421,14 +421,18 @@ fn run() -> Result<(), Box> { params.spv.bounds_check_policies = params.bounds_check_policies; //Insert Debug infos - let debug_info = args.generate_debug_symbols.and_then(|debug| { + params.spv.debug_info = args.generate_debug_symbols.and_then(|debug| { params.spv.flags.set(spv::WriterFlags::DEBUG, debug); - Some(spv::DebugInfo { - source_code: input_text.as_ref()?, - file_name: input_path.file_name().and_then(std::ffi::OsStr::to_str)?, - }) + + if debug { + Some(spv::DebugInfo { + source_code: input_text.as_ref()?, + file_name: input_path.file_name().and_then(std::ffi::OsStr::to_str)?, + }) + } else { + None + } }); - params.spv.debug_info = debug_info; params.spv.flags.set( spv::WriterFlags::ADJUST_COORDINATE_SPACE, diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 4e1ab5015..8554c6226 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -739,8 +739,6 @@ pub fn write_vec( let mut words: Vec = Vec::new(); let mut w = Writer::new(options)?; - if options.flags.contains(WriterFlags::DEBUG) {} - w.write( module, info, From a550b0b4999cbf5f9e6a540380822d93b4ef5bb0 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Thu, 29 Jun 2023 16:59:37 +0200 Subject: [PATCH 2030/2212] Split image bounds check policy (#2265) --- cli/src/bin/naga.rs | 17 +++++++++--- src/back/glsl/features.rs | 2 +- src/back/glsl/mod.rs | 21 +++++++++++---- src/back/msl/writer.rs | 6 ++--- src/back/spv/image.rs | 4 +-- src/proc/index.rs | 27 ++++++++++++++----- tests/in/binding-arrays.param.ron | 3 ++- .../in/bounds-check-image-restrict.param.ron | 3 ++- tests/in/bounds-check-image-rzsw.param.ron | 3 ++- tests/in/pointers.param.ron | 3 ++- tests/in/policy-mix.param.ron | 3 ++- tests/in/resource-binding-map.param.ron | 3 ++- 12 files changed, 68 insertions(+), 27 deletions(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index 2081d1a1b..8f57984f5 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -30,12 +30,19 @@ struct Args { #[argh(option)] buffer_bounds_check_policy: Option, - /// what policy to use for texture bounds checking. + /// what policy to use for texture loads bounds checking. /// /// Possible values are the same as for `index-bounds-check-policy`. If /// omitted, defaults to the index bounds check policy. #[argh(option)] - image_bounds_check_policy: Option, + image_load_bounds_check_policy: Option, + + /// what policy to use for texture stores bounds checking. + /// + /// Possible values are the same as for `index-bounds-check-policy`. If + /// omitted, defaults to the index bounds check policy. + #[argh(option)] + image_store_bounds_check_policy: Option, /// directory to dump the SPIR-V block context dump to #[argh(option)] @@ -248,7 +255,11 @@ fn run() -> Result<(), Box> { Some(arg) => arg.0, None => params.bounds_check_policies.index, }; - params.bounds_check_policies.image = match args.image_bounds_check_policy { + params.bounds_check_policies.image_load = match args.image_load_bounds_check_policy { + Some(arg) => arg.0, + None => params.bounds_check_policies.index, + }; + params.bounds_check_policies.image_store = match args.image_store_bounds_check_policy { Some(arg) => arg.0, None => params.bounds_check_policies.index, }; diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index c175d9a23..8a5da1b6e 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -443,7 +443,7 @@ impl<'a, W> Writer<'a, W> { Expression::ImageLoad { sample, level, .. } => { - if policies.image != crate::proc::BoundsCheckPolicy::Unchecked { + if policies.image_load != crate::proc::BoundsCheckPolicy::Unchecked { if sample.is_some() { features.request(Features::TEXTURE_SAMPLES) } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index b7384af73..03e3338d1 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1824,7 +1824,7 @@ impl<'a, W: Write> Writer<'a, W> { .. } = *ctx.info[image].ty.inner_with(&self.module.types) { - if let proc::BoundsCheckPolicy::Restrict = self.policies.image { + if let proc::BoundsCheckPolicy::Restrict = self.policies.image_load { write!(self.out, "{level}")?; self.write_clamped_lod(ctx, handle, image, level_expr)? } @@ -3532,11 +3532,22 @@ impl<'a, W: Write> Writer<'a, W> { // and the policy to be used with it. let (fun_name, policy) = match class { // Sampled images inherit the policy from the user passed policies - crate::ImageClass::Sampled { .. } => ("texelFetch", self.policies.image), + crate::ImageClass::Sampled { .. } => ("texelFetch", self.policies.image_load), crate::ImageClass::Storage { .. } => { - // OpenGL 4.2 Core §3.9.20 defines that out of bounds texels in `imageLoad`s - // always return zero values so we don't need to generate bounds checks - ("imageLoad", proc::BoundsCheckPolicy::Unchecked) + // OpenGL ES 3.1 mentiones in Chapter "8.22 Texture Image Loads and Stores" that: + // "Invalid image loads will return a vector where the value of R, G, and B components + // is 0 and the value of the A component is undefined." + // + // OpenGL 4.2 Core mentiones in Chapter "3.9.20 Texture Image Loads and Stores" that: + // "Invalid image loads will return zero." + // + // So, we only inject bounds checks for ES + let policy = if self.options.version.is_es() { + self.policies.image_load + } else { + proc::BoundsCheckPolicy::Unchecked + }; + ("imageLoad", policy) } // TODO: Is there even a function for this? crate::ImageClass::Depth { multi: _ } => { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a9551dc71..1c9e87ff2 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -955,7 +955,7 @@ impl Writer { mut address: TexelAddress, context: &ExpressionContext, ) -> BackendResult { - match context.policies.image { + match context.policies.image_load { proc::BoundsCheckPolicy::Restrict => { // Use the cached restricted level of detail, if any. Omit the // level altogether for 1D textures. @@ -1024,7 +1024,7 @@ impl Writer { value: Handle, context: &StatementContext, ) -> BackendResult { - match context.expression.policies.image { + match context.expression.policies.image_store { proc::BoundsCheckPolicy::Restrict => { // We don't have a restricted level value, because we don't // support writes to mipmapped textures. @@ -2507,7 +2507,7 @@ impl Writer { None => return Ok(()), }; - if context.expression.policies.image != index::BoundsCheckPolicy::Restrict + if context.expression.policies.image_load != index::BoundsCheckPolicy::Restrict || !context.expression.image_needs_lod(image) { return Ok(()); diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index 81c9de375..b62a711ef 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -759,7 +759,7 @@ impl<'w> BlockContext<'w> { let sample_id = sample.map(|expr| self.cached[expr]); // Perform the access, according to the bounds check policy. - let access_id = match self.writer.bounds_check_policies.image { + let access_id = match self.writer.bounds_check_policies.image_load { crate::proc::BoundsCheckPolicy::Restrict => { let (coords, level_id, sample_id) = self.write_restricted_coordinates( image_id, @@ -1235,7 +1235,7 @@ impl<'w> BlockContext<'w> { let write = Store { image_id, value_id }; - match self.writer.bounds_check_policies.image { + match self.writer.bounds_check_policies.image_store { crate::proc::BoundsCheckPolicy::Restrict => { let (coords, _, _) = self.write_restricted_coordinates(image_id, coordinates, None, None, block)?; diff --git a/src/proc/index.rs b/src/proc/index.rs index 0ccdfdca5..62d75e0db 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -106,17 +106,27 @@ pub struct BoundsCheckPolicies { #[cfg_attr(feature = "deserialize", serde(default))] pub buffer: BoundsCheckPolicy, - /// How should the generated code handle image texel references that are out + /// How should the generated code handle image texel loads that are out /// of range? /// - /// This controls the behavior of [`ImageLoad`] expressions and - /// [`ImageStore`] statements when a coordinate, texture array index, level - /// of detail, or multisampled sample number is out of range. + /// This controls the behavior of [`ImageLoad`] expressions when a coordinate, + /// texture array index, level of detail, or multisampled sample number is out of range. /// /// [`ImageLoad`]: crate::Expression::ImageLoad + #[cfg_attr(feature = "deserialize", serde(default))] + pub image_load: BoundsCheckPolicy, + + /// How should the generated code handle image texel stores that are out + /// of range? + /// + /// This controls the behavior of [`ImageStore`] statements when a coordinate, + /// texture array index, level of detail, or multisampled sample number is out of range. + /// + /// This policy should't be needed since all backends should ignore OOB writes. + /// /// [`ImageStore`]: crate::Statement::ImageStore #[cfg_attr(feature = "deserialize", serde(default))] - pub image: BoundsCheckPolicy, + pub image_store: BoundsCheckPolicy, /// How should the generated code handle binding array indexes that are out of bounds. #[cfg_attr(feature = "deserialize", serde(default))] @@ -163,7 +173,10 @@ impl BoundsCheckPolicies { /// Return `true` if any of `self`'s policies are `policy`. pub fn contains(&self, policy: BoundsCheckPolicy) -> bool { - self.index == policy || self.buffer == policy || self.image == policy + self.index == policy + || self.buffer == policy + || self.image_load == policy + || self.image_store == policy } } @@ -261,7 +274,7 @@ pub fn find_checked_indexes( level, .. } => { - if policies.image == BoundsCheckPolicy::ReadZeroSkipWrite { + if policies.image_load == BoundsCheckPolicy::ReadZeroSkipWrite { guarded_indices.insert(coordinate.index()); if let Some(array_index) = array_index { guarded_indices.insert(array_index.index()); diff --git a/tests/in/binding-arrays.param.ron b/tests/in/binding-arrays.param.ron index 1f2ac686b..39d6c0366 100644 --- a/tests/in/binding-arrays.param.ron +++ b/tests/in/binding-arrays.param.ron @@ -41,6 +41,7 @@ bounds_check_policies: ( index: ReadZeroSkipWrite, buffer: ReadZeroSkipWrite, - image: ReadZeroSkipWrite, + image_load: ReadZeroSkipWrite, + image_store: ReadZeroSkipWrite, ) ) diff --git a/tests/in/bounds-check-image-restrict.param.ron b/tests/in/bounds-check-image-restrict.param.ron index 8d45e982e..448db8a5d 100644 --- a/tests/in/bounds-check-image-restrict.param.ron +++ b/tests/in/bounds-check-image-restrict.param.ron @@ -1,6 +1,7 @@ ( bounds_check_policies: ( - image: Restrict, + image_load: Restrict, + image_store: Restrict, ), spv: ( version: (1, 1), diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/tests/in/bounds-check-image-rzsw.param.ron index 88978a733..0a82f9584 100644 --- a/tests/in/bounds-check-image-rzsw.param.ron +++ b/tests/in/bounds-check-image-rzsw.param.ron @@ -1,6 +1,7 @@ ( bounds_check_policies: ( - image: ReadZeroSkipWrite, + image_load: ReadZeroSkipWrite, + image_store: ReadZeroSkipWrite, ), spv: ( version: (1, 1), diff --git a/tests/in/pointers.param.ron b/tests/in/pointers.param.ron index fee286e50..fc4027283 100644 --- a/tests/in/pointers.param.ron +++ b/tests/in/pointers.param.ron @@ -1,6 +1,7 @@ ( bounds_check_policies: ( - image: ReadZeroSkipWrite, + image_load: ReadZeroSkipWrite, + image_store: ReadZeroSkipWrite, ), spv: ( version: (1, 2), diff --git a/tests/in/policy-mix.param.ron b/tests/in/policy-mix.param.ron index 9136eed38..e5469157e 100644 --- a/tests/in/policy-mix.param.ron +++ b/tests/in/policy-mix.param.ron @@ -2,7 +2,8 @@ bounds_check_policies: ( index: Restrict, buffer: Unchecked, - image: ReadZeroSkipWrite, + image_load: ReadZeroSkipWrite, + image_store: ReadZeroSkipWrite, ), spv: ( version: (1, 1), diff --git a/tests/in/resource-binding-map.param.ron b/tests/in/resource-binding-map.param.ron index 6b0b43c2a..15a14b197 100644 --- a/tests/in/resource-binding-map.param.ron +++ b/tests/in/resource-binding-map.param.ron @@ -48,6 +48,7 @@ bounds_check_policies: ( index: ReadZeroSkipWrite, buffer: ReadZeroSkipWrite, - image: ReadZeroSkipWrite, + image_load: ReadZeroSkipWrite, + image_store: ReadZeroSkipWrite, ) ) From 7624d6c78e34bb9d111140f84c63d797bc575d67 Mon Sep 17 00:00:00 2001 From: Nicolas Silva Date: Tue, 4 Jul 2023 15:53:29 +0200 Subject: [PATCH 2031/2212] [glsl-out] textureSize level must be a signed integer. (#2397) --- src/back/glsl/mod.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 03e3338d1..af7cb522b 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2589,8 +2589,25 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "textureSize(")?; self.write_expr(image, ctx)?; if let Some(expr) = level { + let cast_to_int = matches!( + *ctx.info[expr].ty.inner_with(&self.module.types), + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } + ); + write!(self.out, ", ")?; + + if cast_to_int { + write!(self.out, "int(")?; + } + self.write_expr(expr, ctx)?; + + if cast_to_int { + write!(self.out, ")")?; + } } else if !multi { // All textureSize calls requires an lod argument // except for multisampled samplers From 981c1f919643d8a949bc4f1022ad07dd0123844a Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Sat, 8 Jul 2023 01:33:48 +0200 Subject: [PATCH 2032/2212] Fix installing naga-cli from git (#2398) Move hl-snapshots out from the xtask workspace, since it's also used as a dev dependency in the naga crate itself for a test. --- .github/workflows/validation-windows.yml | 1 + Cargo.toml | 2 +- {xtask/hlsl-snapshots => hlsl-snapshots}/Cargo.toml | 0 {xtask/hlsl-snapshots => hlsl-snapshots}/src/lib.rs | 0 xtask/Cargo.toml | 4 +--- 5 files changed, 3 insertions(+), 4 deletions(-) rename {xtask/hlsl-snapshots => hlsl-snapshots}/Cargo.toml (100%) rename {xtask/hlsl-snapshots => hlsl-snapshots}/src/lib.rs (100%) diff --git a/.github/workflows/validation-windows.yml b/.github/workflows/validation-windows.yml index d84b44f62..536b71d7b 100644 --- a/.github/workflows/validation-windows.yml +++ b/.github/workflows/validation-windows.yml @@ -6,6 +6,7 @@ on: - 'tests/out/hlsl/*.hlsl' - 'tests/out/hlsl/*.ron' - 'xtask/**' + - 'hlsl-snapshots/**' jobs: validate-windows-dxc: diff --git a/Cargo.toml b/Cargo.toml index c7ee98e27..2f44f8203 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ bincode = "1" criterion = { version = "0.3", features = [] } diff = "0.1" env_logger = "0.9" -hlsl-snapshots = { path = "./xtask/hlsl-snapshots"} +hlsl-snapshots = { path = "./hlsl-snapshots"} # Require at least version 0.7.1 of ron, this version changed how floating points are # serialized by forcing them to always have the decimal part, this makes it backwards # incompatible with our tests because we do a syntatic diff and not a semantic one. diff --git a/xtask/hlsl-snapshots/Cargo.toml b/hlsl-snapshots/Cargo.toml similarity index 100% rename from xtask/hlsl-snapshots/Cargo.toml rename to hlsl-snapshots/Cargo.toml diff --git a/xtask/hlsl-snapshots/src/lib.rs b/hlsl-snapshots/src/lib.rs similarity index 100% rename from xtask/hlsl-snapshots/src/lib.rs rename to hlsl-snapshots/src/lib.rs diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 4214df66f..579c521ea 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -8,12 +8,10 @@ publish = false anyhow = "1" env_logger = { version = "0.10.0", default-features = false } glob = "0.3.1" -hlsl-snapshots = { path = "./hlsl-snapshots"} +hlsl-snapshots = { path = "../hlsl-snapshots"} log = "0.4.17" pico-args = "0.5.0" shell-words = "1.1.0" which = "4.4.0" [workspace] - -members = [".", "./hlsl-snapshots"] From 04ef22f6dc8d9c4b958dc6575bbb3be9d7719ee0 Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Sat, 8 Jul 2023 12:37:41 +0200 Subject: [PATCH 2033/2212] Update README after the make -> xtask transition (#2401) --- README.md | 17 ++++++++--------- xtask/src/cli.rs | 1 + 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 0de0cd61b..c9f22e502 100644 --- a/README.md +++ b/README.md @@ -74,14 +74,13 @@ default = ["spv-out"] #TEMP! This allows IDE basic checks to report errors there, unless your IDE is sufficiently configurable already. Finally, when changes to the snapshots are made, we should verify that the produced shaders -are indeed valid for the target platforms they are compiled for. We automate this with `Makefile`: +are indeed valid for the target platforms they are compiled for: ```bash -make validate-spv # for Vulkan shaders, requires SPIRV-Tools installed -make validate-msl # for Metal shaders, requires XCode command-line tools installed -make validate-glsl # for OpenGL shaders, requires GLSLang installed -make validate-dot # for dot files, requires GraphViz installed -make validate-wgsl # for WGSL shaders -make validate-hlsl-dxc # for HLSL shaders via DXC -make validate-hlsl-fxc # for HLSL shaders via FXC -# Note: HLSL Make targets make use of the "sh" shell. This is not the default shell in Windows. +cargo xtask validate spv # for Vulkan shaders, requires SPIRV-Tools installed +cargo xtask validate msl # for Metal shaders, requires XCode command-line tools installed +cargo xtask validate glsl # for OpenGL shaders, requires GLSLang installed +cargo xtask validate dot # for dot files, requires GraphViz installed +cargo xtask validate wgsl # for WGSL shaders +cargo xtask validate hlsl dxc # for HLSL shaders via DXC +cargo xtask validate hlsl fxc # for HLSL shaders via FXC ``` diff --git a/xtask/src/cli.rs b/xtask/src/cli.rs index 01d60dfa1..3b5b1ed69 100644 --- a/xtask/src/cli.rs +++ b/xtask/src/cli.rs @@ -17,6 +17,7 @@ Commands: fxc msl spv + wgsl Options: -h, --help Print help From dfd88ee485304fdbadeda32f9e8ebbe95a2ec538 Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Mon, 17 Jul 2023 17:22:25 +0200 Subject: [PATCH 2034/2212] [glsl-in] Support commas in structure definitions (#2400) --- src/front/glsl/parser/declarations.rs | 57 +++++++++++++++------------ tests/in/glsl/declarations.frag | 5 +++ tests/out/wgsl/declarations-frag.wgsl | 10 +++++ 3 files changed, 47 insertions(+), 25 deletions(-) diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 79bf1bc8c..4e43e75c8 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -628,36 +628,43 @@ impl<'source> ParsingContext<'source> { loop { // TODO: type_qualifier - let (mut ty, mut meta) = self.parse_type_non_void(frontend)?; - let (name, end_meta) = self.expect_ident(frontend)?; + let (base_ty, mut meta) = self.parse_type_non_void(frontend)?; - meta.subsume(end_meta); + loop { + let (name, name_meta) = self.expect_ident(frontend)?; + let mut ty = base_ty; + self.parse_array_specifier(frontend, &mut meta, &mut ty)?; - self.parse_array_specifier(frontend, &mut meta, &mut ty)?; + meta.subsume(name_meta); + + let info = offset::calculate_offset( + ty, + meta, + layout, + &mut frontend.module.types, + &mut frontend.errors, + ); + + let member_alignment = info.align; + span = member_alignment.round_up(span); + align = member_alignment.max(align); + + members.push(StructMember { + name: Some(name), + ty: info.ty, + binding: None, + offset: span, + }); + + span += info.span; + + if self.bump_if(frontend, TokenValue::Comma).is_none() { + break; + } + } self.expect(frontend, TokenValue::Semicolon)?; - let info = offset::calculate_offset( - ty, - meta, - layout, - &mut frontend.module.types, - &mut frontend.errors, - ); - - let member_alignment = info.align; - span = member_alignment.round_up(span); - align = member_alignment.max(align); - - members.push(StructMember { - name: Some(name), - ty: info.ty, - binding: None, - offset: span, - }); - - span += info.span; - if let TokenValue::RightBrace = self.expect_peek(frontend)?.value { break; } diff --git a/tests/in/glsl/declarations.frag b/tests/in/glsl/declarations.frag index 75122bc46..7ef8b56a7 100644 --- a/tests/in/glsl/declarations.frag +++ b/tests/in/glsl/declarations.frag @@ -21,6 +21,11 @@ struct TestStruct { float array_2d[2][2]; float array_toomanyd[2][2][2][2][2][2][2]; +struct LightScatteringParams { + float BetaRay, BetaMie[3], HGg, DistanceMul[4], BlendCoeff; + vec3 SunDirection, SunColor; +}; + void main() { const vec3 positions[2] = vec3[2]( vec3(-1.0, 1.0, 0.0), diff --git a/tests/out/wgsl/declarations-frag.wgsl b/tests/out/wgsl/declarations-frag.wgsl index bdcca29e0..23c697a00 100644 --- a/tests/out/wgsl/declarations-frag.wgsl +++ b/tests/out/wgsl/declarations-frag.wgsl @@ -13,6 +13,16 @@ struct TestStruct { b: f32, } +struct LightScatteringParams { + BetaRay: f32, + BetaMie: array, + HGg: f32, + DistanceMul: array, + BlendCoeff: f32, + SunDirection: vec3, + SunColor: vec3, +} + struct FragmentOutput { @location(0) position: vec2, @location(1) a: vec2, From d348d843e1ebd55349ab1a4981416fdf40944af4 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 5 Apr 2023 17:38:03 +0200 Subject: [PATCH 2035/2212] implement const-expressions (phase 1) --- src/back/dot/mod.rs | 8 +- src/back/glsl/mod.rs | 249 ++-- src/back/hlsl/help.rs | 98 +- src/back/hlsl/writer.rs | 297 ++--- src/back/mod.rs | 8 + src/back/msl/writer.rs | 461 +++---- src/back/spv/block.rs | 43 +- src/back/spv/image.rs | 2 +- src/back/spv/index.rs | 76 +- src/back/spv/mod.rs | 1 + src/back/spv/writer.rs | 93 +- src/back/wgsl/writer.rs | 298 ++--- src/front/glsl/builtins.rs | 9 +- src/front/glsl/constants.rs | 1129 +++++++++-------- src/front/glsl/context.rs | 41 +- src/front/glsl/functions.rs | 109 +- src/front/glsl/parser.rs | 38 +- src/front/glsl/parser/declarations.rs | 6 +- src/front/glsl/parser/functions.rs | 23 +- src/front/glsl/parser_tests.rs | 56 +- src/front/glsl/types.rs | 7 +- src/front/glsl/variables.rs | 30 +- src/front/mod.rs | 10 - src/front/spv/function.rs | 2 + src/front/spv/image.rs | 4 + src/front/spv/mod.rs | 229 ++-- src/front/spv/null.rs | 175 +-- src/front/wgsl/error.rs | 20 +- src/front/wgsl/lower/construction.rs | 87 +- src/front/wgsl/lower/mod.rs | 710 ++++++----- src/front/wgsl/mod.rs | 2 + src/front/wgsl/parse/ast.rs | 6 +- src/lib.rs | 75 +- src/proc/index.rs | 20 +- src/proc/mod.rs | 180 +-- src/proc/namer.rs | 38 +- src/proc/typifier.rs | 26 +- src/valid/analyzer.rs | 30 +- src/valid/expression.rs | 107 +- src/valid/function.rs | 34 +- src/valid/handles.rs | 83 +- src/valid/interface.rs | 11 + src/valid/mod.rs | 119 +- tests/out/analysis/access.info.ron | 156 ++- tests/out/analysis/collatz.info.ron | 1 + tests/out/analysis/shadow.info.ron | 787 +++++------- tests/out/glsl/access.foo_vert.Vertex.glsl | 16 +- tests/out/glsl/boids.main.Compute.glsl | 6 +- tests/out/glsl/do-while.main.Fragment.glsl | 4 +- tests/out/glsl/globals.main.Compute.glsl | 2 + tests/out/glsl/operators.main.Compute.glsl | 37 +- tests/out/glsl/quad-vert.main.Vertex.glsl | 8 +- tests/out/glsl/quad.frag_main.Fragment.glsl | 2 + tests/out/glsl/quad.fs_extra.Fragment.glsl | 2 + tests/out/glsl/quad.vert_main.Vertex.glsl | 4 +- tests/out/glsl/shadow.fs_main.Fragment.glsl | 11 +- ...adow.fs_main_without_storage.Fragment.glsl | 11 +- tests/out/glsl/shadow.vs_main.Vertex.glsl | 3 + ...oad.test_workgroupUniformLoad.Compute.glsl | 2 + tests/out/hlsl/access.hlsl | 45 +- tests/out/hlsl/array-in-ctor.hlsl | 1 - tests/out/hlsl/atomicOps.hlsl | 1 - tests/out/hlsl/binding-arrays.hlsl | 219 ++-- tests/out/hlsl/bitcast.hlsl | 1 - tests/out/hlsl/bits.hlsl | 1 - tests/out/hlsl/boids.hlsl | 4 +- tests/out/hlsl/break-if.hlsl | 1 - tests/out/hlsl/collatz.hlsl | 1 - tests/out/hlsl/control-flow.hlsl | 1 - tests/out/hlsl/do-while.hlsl | 5 +- tests/out/hlsl/empty-global-name.hlsl | 5 +- tests/out/hlsl/empty.hlsl | 1 - tests/out/hlsl/fragment-output.hlsl | 1 - tests/out/hlsl/functions.hlsl | 1 - tests/out/hlsl/globals.hlsl | 4 +- tests/out/hlsl/hlsl-keyword.hlsl | 1 - tests/out/hlsl/image.hlsl | 1 - tests/out/hlsl/interpolate.hlsl | 1 - .../hlsl/inv-hyperbolic-trig-functions.hlsl | 11 +- tests/out/hlsl/math-functions.hlsl | 1 - tests/out/hlsl/operators.hlsl | 42 +- tests/out/hlsl/padding.hlsl | 1 - tests/out/hlsl/quad-vert.hlsl | 17 +- tests/out/hlsl/quad.hlsl | 4 +- tests/out/hlsl/shadow.hlsl | 18 +- tests/out/hlsl/standard.hlsl | 1 - tests/out/hlsl/texture-arg.hlsl | 1 - tests/out/hlsl/workgroup-uniform-load.hlsl | 2 +- tests/out/hlsl/workgroup-var-init.hlsl | 1 - tests/out/ir/access.ron | 163 +-- tests/out/ir/collatz.ron | 1 + tests/out/ir/shadow.ron | 875 ++++++------- tests/out/msl/access.msl | 18 +- tests/out/msl/binding-arrays.msl | 226 ++-- tests/out/msl/boids.msl | 2 +- tests/out/msl/do-while.msl | 2 +- tests/out/msl/empty-global-name.msl | 4 +- tests/out/msl/globals.msl | 2 +- tests/out/msl/image.msl | 23 +- tests/out/msl/operators.msl | 24 +- tests/out/msl/quad-vert.msl | 13 +- tests/out/msl/quad.msl | 2 +- tests/out/msl/shadow.msl | 12 +- tests/out/msl/workgroup-uniform-load.msl | 2 +- tests/out/spv/access.spvasm | 730 +++++------ tests/out/spv/array-in-ctor.spvasm | 26 +- .../spv/array-in-function-return-type.spvasm | 38 +- tests/out/spv/atomicCompareExchange.spvasm | 357 +++--- tests/out/spv/atomicOps.spvasm | 192 +-- tests/out/spv/binding-arrays.spvasm | 596 ++++----- tests/out/spv/binding-buffer-arrays.spvasm | 90 +- tests/out/spv/boids.spvasm | 318 ++--- tests/out/spv/bounds-check-restrict.spvasm | 228 ++-- tests/out/spv/bounds-check-zero.spvasm | 232 ++-- tests/out/spv/globals.spvasm | 325 +++-- tests/out/spv/image.spvasm | 878 ++++++------- tests/out/spv/interface.compute.spvasm | 88 +- tests/out/spv/interface.fragment.spvasm | 88 +- tests/out/spv/interface.vertex.spvasm | 70 +- .../spv/interface.vertex_two_structs.spvasm | 78 +- tests/out/spv/operators.spvasm | 850 ++++++------- tests/out/spv/padding.spvasm | 98 +- tests/out/spv/policy-mix.spvasm | 174 +-- tests/out/spv/quad.spvasm | 80 +- tests/out/spv/shadow.spvasm | 805 ++++++------ tests/out/spv/workgroup-uniform-load.spvasm | 111 +- tests/out/spv/workgroup-var-init.spvasm | 56 +- tests/out/wgsl/access.wgsl | 16 +- tests/out/wgsl/atomicCompareExchange.wgsl | 8 +- tests/out/wgsl/bevy-pbr-frag.wgsl | 4 +- tests/out/wgsl/binding-arrays.dynamic.wgsl | 4 +- tests/out/wgsl/binding-arrays.static.wgsl | 4 +- tests/out/wgsl/binding-arrays.wgsl | 236 ++-- tests/out/wgsl/do-while.wgsl | 4 +- tests/out/wgsl/empty-global-name.wgsl | 4 +- tests/out/wgsl/expressions-frag.wgsl | 3 +- .../out/wgsl/global-constant-array-frag.wgsl | 3 +- .../wgsl/inv-hyperbolic-trig-functions.wgsl | 10 +- tests/out/wgsl/lexical-scopes.wgsl | 4 +- tests/out/wgsl/operators.wgsl | 33 +- tests/out/wgsl/quad-vert.wgsl | 10 +- tests/out/wgsl/quad.wgsl | 2 +- tests/out/wgsl/quad_glsl-vert.wgsl | 2 +- tests/out/wgsl/shadow.wgsl | 14 +- tests/wgsl-errors.rs | 6 +- 145 files changed, 7055 insertions(+), 7685 deletions(-) diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index 85f382d26..d92fe39e4 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -405,6 +405,10 @@ fn write_function_expressions( E::Literal(_) => ("Literal".into(), 2), E::Constant(_) => ("Constant".into(), 2), E::ZeroValue(_) => ("ZeroValue".into(), 2), + E::Compose { ref components, .. } => { + payload = Some(Payload::Arguments(components)); + ("Compose".into(), 3) + } E::Access { base, index } => { edges.insert("base", base); edges.insert("index", index); @@ -426,10 +430,6 @@ fn write_function_expressions( edges.insert("vector", vector); (format!("Swizzle{:?}", &pattern[..size as usize]).into(), 3) } - E::Compose { ref components, .. } => { - payload = Some(Payload::Arguments(components)); - ("Compose".into(), 3) - } E::FunctionArgument(index) => (format!("Argument[{index}]").into(), 1), E::GlobalVariable(h) => { payload = Some(Payload::Global(h)); diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index af7cb522b..696598bdf 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -604,8 +604,6 @@ impl<'a, W: Write> Writer<'a, W> { } } - let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); - // Write struct types. // // This are always ordered because the IR is structured in a way that @@ -627,6 +625,23 @@ impl<'a, W: Write> Writer<'a, W> { } } + // Write all named constants + let mut constants = self + .module + .constants + .iter() + .filter(|&(_, c)| c.name.is_some()) + .peekable(); + while let Some((handle, _)) = constants.next() { + self.write_global_constant(handle)?; + // Add extra newline for readability on last iteration + if constants.peek().is_none() { + writeln!(self.out)?; + } + } + + let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); + // Write the globals // // Unless explicitly disabled with WriterFlags::INCLUDE_UNUSED_ITEMS, @@ -722,31 +737,6 @@ impl<'a, W: Write> Writer<'a, W> { } } - if include_unused { - // write named constants - for (handle, constant) in self.module.constants.iter() { - if let Some(name) = constant.name.as_ref() { - write!(self.out, "const ")?; - match constant.inner { - crate::ConstantInner::Scalar { width, value } => { - // create a TypeInner to write - let inner = TypeInner::Scalar { - width, - kind: value.scalar_kind(), - }; - self.write_value_type(&inner)?; - } - crate::ConstantInner::Composite { ty, .. } => { - self.write_type(ty)?; - } - }; - write!(self.out, " {name} = ")?; - self.write_constant(handle)?; - writeln!(self.out, ";")?; - } - } - } - for arg in self.entry_point.function.arguments.iter() { self.write_varying(arg.binding.as_ref(), arg.ty, false)?; } @@ -818,12 +808,6 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Adds no trailing or leading whitespace - /// - /// # Panics - /// - If type is either a image, a sampler, a pointer, or a struct - /// - If it's an Array with a [`ArraySize::Constant`](crate::ArraySize::Constant) with a - /// constant that isn't a [`Scalar`](crate::ConstantInner::Scalar) or if the - /// scalar value isn't an [`Sint`](crate::ScalarValue::Sint) or [`Uint`](crate::ScalarValue::Uint) fn write_value_type(&mut self, inner: &TypeInner) -> BackendResult { match *inner { // Scalars are simple we just get the full name from `glsl_scalar` @@ -865,11 +849,9 @@ impl<'a, W: Write> Writer<'a, W> { rows as u8 )?, // GLSL arrays are written as `type name[size]` - // Current code is written arrays only as `[size]` + // Here we only write the size of the array i.e. `[size]` // Base `type` and `name` should be written outside TypeInner::Array { base, size, .. } => self.write_array_size(base, size)?, - // Panic if either Image, Sampler, Pointer, or a Struct is being written - // // Write all variants instead of `_` so that if new variants are added a // no exhaustiveness error is thrown TypeInner::Pointer { .. } @@ -890,12 +872,6 @@ impl<'a, W: Write> Writer<'a, W> { /// /// # Notes /// Adds no trailing or leading whitespace - /// - /// # Panics - /// - If type is either a image or sampler - /// - If it's an Array with a [`ArraySize::Constant`](crate::ArraySize::Constant) with a - /// constant that isn't a [`Scalar`](crate::ConstantInner::Scalar) or if the - /// scalar value isn't an [`Sint`](crate::ScalarValue::Sint) or [`Uint`](crate::ScalarValue::Uint) fn write_type(&mut self, ty: Handle) -> BackendResult { match self.module.types[ty].inner { // glsl has no pointer types so just write types as normal and loads are skipped @@ -1050,7 +1026,7 @@ impl<'a, W: Write> Writer<'a, W> { if global.space.initializable() && is_value_init_supported(self.module, global.ty) { write!(self.out, " = ")?; if let Some(init) = global.init { - self.write_constant(init)?; + self.write_const_expr(init)?; } else { self.write_zero_init_value(global.ty)?; } @@ -1550,7 +1526,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the constant // `write_constant` adds no trailing or leading space/newline - self.write_constant(init)?; + self.write_const_expr(init)?; } else if is_value_init_supported(self.module, local.ty) { write!(self.out, " = ")?; self.write_zero_init_value(local.ty)?; @@ -1621,60 +1597,29 @@ impl<'a, W: Write> Writer<'a, W> { mut f: F, ) -> BackendResult { // Loop trough `data` invoking `f` for each element - for (i, item) in data.iter().enumerate() { - f(self, i as u32, item)?; - - // Only write a comma if isn't the last element - if i != data.len().saturating_sub(1) { - // The leading space is for readability only + for (index, item) in data.iter().enumerate() { + if index != 0 { write!(self.out, ", ")?; } + f(self, index as u32, item)?; } Ok(()) } - /// Helper method used to write constants - /// - /// # Notes - /// Adds no newlines or leading/trailing whitespace - fn write_constant(&mut self, handle: Handle) -> BackendResult { - use crate::ScalarValue as Sv; - - match self.module.constants[handle].inner { - crate::ConstantInner::Scalar { - width: _, - ref value, - } => match *value { - // Signed integers don't need anything special - Sv::Sint(int) => write!(self.out, "{int}")?, - // Unsigned integers need a `u` at the end - // - // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we - // always write it as the extra branch wouldn't have any benefit in readability - Sv::Uint(int) => write!(self.out, "{int}u")?, - // Floats are written using `Debug` instead of `Display` because it always appends the - // decimal part even it's zero which is needed for a valid glsl float constant - Sv::Float(float) => write!(self.out, "{float:?}")?, - // Booleans are either `true` or `false` so nothing special needs to be done - Sv::Bool(boolean) => write!(self.out, "{boolean}")?, - }, - // Composite constant are created using the same syntax as compose - // `type(components)` where `components` is a comma separated list of constants - crate::ConstantInner::Composite { ty, ref components } => { - self.write_type(ty)?; - if let TypeInner::Array { base, size, .. } = self.module.types[ty].inner { - self.write_array_size(base, size)?; - } - write!(self.out, "(")?; - - // Write the comma separated constants - self.write_slice(components, |this, _, arg| this.write_constant(*arg))?; - - write!(self.out, ")")? - } + /// Helper method used to write global constants + fn write_global_constant(&mut self, handle: Handle) -> BackendResult { + write!(self.out, "const ")?; + let constant = &self.module.constants[handle]; + self.write_type(constant.ty)?; + let name = &self.names[&NameKey::Constant(handle)]; + write!(self.out, " {name}")?; + if let TypeInner::Array { base, size, .. } = self.module.types[constant.ty].inner { + self.write_array_size(base, size)?; } - + write!(self.out, " = ")?; + self.write_const_expr(constant.init)?; + writeln!(self.out, ";")?; Ok(()) } @@ -2219,6 +2164,80 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper method used to write constant expressions + /// + /// # Notes + /// Adds no newlines or leading/trailing whitespace + fn write_const_expr(&mut self, expr: Handle) -> BackendResult { + self.write_possibly_const_expr(expr, &self.module.const_expressions, |writer, expr| { + writer.write_const_expr(expr) + }) + } + + /// Helper method used to write possibly constant expressions + /// + /// # Notes + /// Adds no newlines or leading/trailing whitespace + fn write_possibly_const_expr( + &mut self, + expr: Handle, + expressions: &crate::Arena, + write_expression: E, + ) -> BackendResult + where + E: Fn(&mut Self, Handle) -> BackendResult, + { + use crate::Expression; + + match expressions[expr] { + Expression::Literal(literal) => { + match literal { + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero which is needed for a valid glsl float constant + crate::Literal::F64(value) => write!(self.out, "{:?}LF", value)?, + crate::Literal::F32(value) => write!(self.out, "{:?}", value)?, + // Unsigned integers need a `u` at the end + // + // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we + // always write it as the extra branch wouldn't have any benefit in readability + crate::Literal::U32(value) => write!(self.out, "{}u", value)?, + crate::Literal::I32(value) => write!(self.out, "{}", value)?, + crate::Literal::Bool(value) => write!(self.out, "{}", value)?, + } + } + Expression::Constant(handle) => { + let constant = &self.module.constants[handle]; + if constant.name.is_some() { + write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?; + } else { + self.write_const_expr(constant.init)?; + } + } + Expression::ZeroValue(ty) => { + self.write_zero_init_value(ty)?; + } + Expression::Compose { ty, ref components } => { + self.write_type(ty)?; + + if let TypeInner::Array { base, size, .. } = self.module.types[ty].inner { + self.write_array_size(base, size)?; + } + + write!(self.out, "(")?; + for (index, component) in components.iter().enumerate() { + if index != 0 { + write!(self.out, ", ")?; + } + write_expression(self, *component)?; + } + write!(self.out, ")")? + } + _ => unreachable!(), + } + + Ok(()) + } + /// Helper method to write expressions /// /// # Notes @@ -2236,6 +2255,14 @@ impl<'a, W: Write> Writer<'a, W> { } match ctx.expressions[expr] { + Expression::Literal(_) + | Expression::Constant(_) + | Expression::ZeroValue(_) + | Expression::Compose { .. } => { + self.write_possibly_const_expr(expr, ctx.expressions, |writer, expr| { + writer.write_expr(expr, ctx) + })?; + } // `Access` is applied to arrays, vectors and matrices and is written as indexing Expression::Access { base, index } => { self.write_expr(base, ctx)?; @@ -2281,26 +2308,6 @@ impl<'a, W: Write> Writer<'a, W> { ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))), } } - // Constants are delegated to `write_constant` - Expression::Constant(constant) => self.write_constant(constant)?, - Expression::ZeroValue(ty) => { - self.write_zero_init_value(ty)?; - } - Expression::Literal(literal) => { - match literal { - // Floats are written using `Debug` instead of `Display` because it always appends the - // decimal part even it's zero which is needed for a valid glsl float constant - crate::Literal::F64(value) => write!(self.out, "{:?}LF", value)?, - crate::Literal::F32(value) => write!(self.out, "{:?}", value)?, - // Unsigned integers need a `u` at the end - // - // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we - // always write it as the extra branch wouldn't have any benefit in readability - crate::Literal::U32(value) => write!(self.out, "{}u", value)?, - crate::Literal::I32(value) => write!(self.out, "{}", value)?, - crate::Literal::Bool(value) => write!(self.out, "{}", value)?, - } - } // `Splat` needs to actually write down a vector, it's not always inferred in GLSL. Expression::Splat { size: _, value } => { let resolved = ctx.info[expr].ty.inner_with(&self.module.types); @@ -2321,20 +2328,6 @@ impl<'a, W: Write> Writer<'a, W> { self.out.write_char(back::COMPONENTS[sc as usize])?; } } - // `Compose` is pretty simple we just write `type(components)` where `components` is a - // comma separated list of expressions - Expression::Compose { ty, ref components } => { - self.write_type(ty)?; - - let resolved = ctx.info[expr].ty.inner_with(&self.module.types); - if let TypeInner::Array { base, size, .. } = *resolved { - self.write_array_size(base, size)?; - } - - write!(self.out, "(")?; - self.write_slice(components, |this, _, arg| this.write_expr(*arg, ctx))?; - write!(self.out, ")")? - } // Function arguments are written as the argument name Expression::FunctionArgument(pos) => { write!(self.out, "{}", &self.names[&ctx.argument_key(pos)])? @@ -2524,7 +2517,7 @@ impl<'a, W: Write> Writer<'a, W> { if tex_1d_hack { write!(self.out, "ivec2(")?; } - self.write_constant(constant)?; + self.write_const_expr(constant)?; if tex_1d_hack { write!(self.out, ", 0)")?; } @@ -3857,11 +3850,11 @@ impl<'a, W: Write> Writer<'a, W> { TypeInner::Struct { ref members, .. } => { let name = &self.names[&NameKey::Type(ty)]; write!(self.out, "{name}(")?; - for (i, member) in members.iter().enumerate() { - self.write_zero_init_value(member.ty)?; - if i != members.len().saturating_sub(1) { + for (index, member) in members.iter().enumerate() { + if index != 0 { write!(self.out, ", ")?; } + self.write_zero_init_value(member.ty)?; } write!(self.out, ")")?; } diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index c59816550..7ad463131 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -159,10 +159,7 @@ impl<'a, W: Write> super::Writer<'a, W> { /// pub(super) fn write_wrapped_array_length_function( &mut self, - module: &crate::Module, wal: WrappedArrayLength, - expr_handle: Handle, - func_ctx: &FunctionCtx, ) -> BackendResult { use crate::back::INDENT; @@ -170,9 +167,7 @@ impl<'a, W: Write> super::Writer<'a, W> { const RETURN_VARIABLE_NAME: &str = "ret"; // Write function return type and name - let ret_ty = func_ctx.info[expr_handle].ty.inner_with(&module.types); - self.write_value_type(module, ret_ty)?; - write!(self.out, " ")?; + write!(self.out, "uint ")?; self.write_wrapped_array_length_function_name(wal)?; // Write function parameters @@ -786,14 +781,36 @@ impl<'a, W: Write> super::Writer<'a, W> { Ok(()) } - /// Helper function that write wrapped function for `Expression::ImageQuery` and `Expression::ArrayLength` - /// - /// + /// Helper function that writes compose wrapped functions + pub(super) fn write_wrapped_compose_functions( + &mut self, + module: &crate::Module, + expressions: &crate::Arena, + ) -> BackendResult { + for (handle, _) in expressions.iter() { + if let crate::Expression::Compose { ty, .. } = expressions[handle] { + match module.types[ty].inner { + crate::TypeInner::Struct { .. } | crate::TypeInner::Array { .. } => { + let constructor = WrappedConstructor { ty }; + if self.wrapped.constructors.insert(constructor) { + self.write_wrapped_constructor_function(module, constructor)?; + } + } + _ => {} + }; + } + } + Ok(()) + } + + /// Helper function that writes various wrapped functions pub(super) fn write_wrapped_functions( &mut self, module: &crate::Module, func_ctx: &FunctionCtx, ) -> BackendResult { + self.write_wrapped_compose_functions(module, func_ctx.expressions)?; + for (handle, _) in func_ctx.expressions.iter() { match func_ctx.expressions[handle] { crate::Expression::ArrayLength(expr) => { @@ -816,9 +833,8 @@ impl<'a, W: Write> super::Writer<'a, W> { writable: storage_access.contains(crate::StorageAccess::STORE), }; - if !self.wrapped.array_lengths.contains(&wal) { - self.write_wrapped_array_length_function(module, wal, handle, func_ctx)?; - self.wrapped.array_lengths.insert(wal); + if self.wrapped.array_lengths.insert(wal) { + self.write_wrapped_array_length_function(wal)?; } } crate::Expression::ImageQuery { image, query } => { @@ -836,9 +852,8 @@ impl<'a, W: Write> super::Writer<'a, W> { _ => unreachable!("we only query images"), }; - if !self.wrapped.image_queries.contains(&wiq) { + if self.wrapped.image_queries.insert(wiq) { self.write_wrapped_image_query_function(module, wiq, handle, func_ctx)?; - self.wrapped.image_queries.insert(wiq); } } // Write `WrappedConstructor` for structs that are loaded from `AddressSpace::Storage` @@ -867,19 +882,18 @@ impl<'a, W: Write> super::Writer<'a, W> { } let constructor = WrappedConstructor { ty }; - if !writer.wrapped.constructors.contains(&constructor) { + if writer.wrapped.constructors.insert(constructor) { writer .write_wrapped_constructor_function(module, constructor)?; - writer.wrapped.constructors.insert(constructor); } } crate::TypeInner::Array { base, .. } => { write_wrapped_constructor(writer, base, module)?; + let constructor = WrappedConstructor { ty }; - if !writer.wrapped.constructors.contains(&constructor) { + if writer.wrapped.constructors.insert(constructor) { writer .write_wrapped_constructor_function(module, constructor)?; - writer.wrapped.constructors.insert(constructor); } } _ => {} @@ -888,18 +902,6 @@ impl<'a, W: Write> super::Writer<'a, W> { Ok(()) } } - crate::Expression::Compose { ty, components: _ } => { - let constructor = match module.types[ty].inner { - crate::TypeInner::Struct { .. } | crate::TypeInner::Array { .. } => { - WrappedConstructor { ty } - } - _ => continue, - }; - if !self.wrapped.constructors.contains(&constructor) { - self.write_wrapped_constructor_function(module, constructor)?; - self.wrapped.constructors.insert(constructor); - } - } // We treat matrices of the form `matCx2` as a sequence of C `vec2`s // (see top level module docs for details). // @@ -925,7 +927,7 @@ impl<'a, W: Write> super::Writer<'a, W> { let ty = base_ty_handle.unwrap(); let access = WrappedStructMatrixAccess { ty, index }; - if !self.wrapped.struct_matrix_access.contains(&access) { + if self.wrapped.struct_matrix_access.insert(access) { self.write_wrapped_struct_matrix_get_function(module, access)?; self.write_wrapped_struct_matrix_set_function(module, access)?; self.write_wrapped_struct_matrix_set_vec_function( @@ -934,7 +936,6 @@ impl<'a, W: Write> super::Writer<'a, W> { self.write_wrapped_struct_matrix_set_scalar_function( module, access, )?; - self.wrapped.struct_matrix_access.insert(access); } } _ => {} @@ -948,33 +949,6 @@ impl<'a, W: Write> super::Writer<'a, W> { Ok(()) } - pub(super) fn write_wrapped_constructor_function_for_constant( - &mut self, - module: &crate::Module, - constant: &crate::Constant, - ) -> BackendResult { - if let crate::ConstantInner::Composite { ty, ref components } = constant.inner { - match module.types[ty].inner { - crate::TypeInner::Struct { .. } | crate::TypeInner::Array { .. } => { - let constructor = WrappedConstructor { ty }; - if !self.wrapped.constructors.contains(&constructor) { - self.write_wrapped_constructor_function(module, constructor)?; - self.wrapped.constructors.insert(constructor); - } - } - _ => {} - } - for constant in components { - self.write_wrapped_constructor_function_for_constant( - module, - &module.constants[*constant], - )?; - } - } - - Ok(()) - } - pub(super) fn write_texture_coordinates( &mut self, kind: &str, @@ -1085,9 +1059,8 @@ impl<'a, W: Write> super::Writer<'a, W> { }) = super::writer::get_inner_matrix_data(module, global.ty) { let entry = WrappedMatCx2 { columns }; - if !self.wrapped.mat_cx2s.contains(&entry) { + if self.wrapped.mat_cx2s.insert(entry) { self.write_mat_cx2_typedef_and_functions(entry)?; - self.wrapped.mat_cx2s.insert(entry); } } } @@ -1104,9 +1077,8 @@ impl<'a, W: Write> super::Writer<'a, W> { }) = super::writer::get_inner_matrix_data(module, member.ty) { let entry = WrappedMatCx2 { columns }; - if !self.wrapped.mat_cx2s.contains(&entry) { + if self.wrapped.mat_cx2s.insert(entry) { self.write_mat_cx2_typedef_and_functions(entry)?; - self.wrapped.mat_cx2s.insert(entry); } } } diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index ec99c9744..4f1912638 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -199,31 +199,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ", space{}", bt.space)?; } writeln!(self.out, ");")?; - } - // Write all constants - // For example, input wgsl shader: - // ```wgsl - // let c_scale: f32 = 1.2; - // return VertexOutput(uv, vec4(c_scale * pos, 0.0, 1.0)); - // ``` - // - // Output shader: - // ```hlsl - // static const float c_scale = 1.2; - // const VertexOutput vertexoutput1 = { vertexinput.uv3, float4((c_scale * vertexinput.pos1), 0.0, 1.0) }; - // ``` - // - // If we remove `write_global_constant` `c_scale` will be inlined. - for (handle, constant) in module.constants.iter() { - if constant.name.is_some() { - self.write_global_constant(module, &constant.inner, handle)?; - } + // Extra newline for readability + writeln!(self.out)?; } - // Extra newline for readability - writeln!(self.out)?; - // Save all entry point output types let ep_results = module .entry_points @@ -264,9 +244,20 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - // Write wrapped constructor functions used in constants - for (_, constant) in module.constants.iter() { - self.write_wrapped_constructor_function_for_constant(module, constant)?; + self.write_wrapped_compose_functions(module, &module.const_expressions)?; + + // Write all named constants + let mut constants = module + .constants + .iter() + .filter(|&(_, c)| c.name.is_some()) + .peekable(); + while let Some((handle, _)) = constants.next() { + self.write_global_constant(module, handle)?; + // Add extra newline for readability on last iteration + if constants.peek().is_none() { + writeln!(self.out)?; + } } // Write all globals @@ -321,8 +312,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; let name = self.names[&NameKey::Function(handle)].clone(); - // Write wrapped function for `Expression::ImageQuery` and `Expressions::ArrayLength` - // before writing all statements and expressions. self.write_wrapped_functions(module, &ctx)?; self.write_function(module, name.as_str(), function, &ctx, info)?; @@ -362,8 +351,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { named_expressions: &ep.function.named_expressions, }; - // Write wrapped function for `Expression::ImageQuery` and `Expressions::ArrayLength` - // before writing all statements and expressions. self.write_wrapped_functions(module, &ctx)?; if ep.stage == ShaderStage::Compute { @@ -769,7 +756,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if global.space == crate::AddressSpace::Private { write!(self.out, " = ")?; if let Some(init) = global.init { - self.write_constant(module, init)?; + self.write_const_expression(module, init)?; } else { self.write_default_init(module, global.ty)?; } @@ -807,44 +794,19 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { fn write_global_constant( &mut self, module: &Module, - inner: &crate::ConstantInner, handle: Handle, ) -> BackendResult { write!(self.out, "static const ")?; - match *inner { - crate::ConstantInner::Scalar { - width: _, - ref value, - } => { - // Write type - let ty_str = match *value { - crate::ScalarValue::Sint(_) => "int", - crate::ScalarValue::Uint(_) => "uint", - crate::ScalarValue::Float(_) => "float", - crate::ScalarValue::Bool(_) => "bool", - }; - let name = &self.names[&NameKey::Constant(handle)]; - write!(self.out, "{ty_str} {name} = ")?; - - // Second match required to avoid heap allocation by `format!()` - match *value { - crate::ScalarValue::Sint(value) => write!(self.out, "{value}")?, - crate::ScalarValue::Uint(value) => write!(self.out, "{value}")?, - crate::ScalarValue::Float(value) => { - // Floats are written using `Debug` instead of `Display` because it always appends the - // decimal part even it's zero - write!(self.out, "{value:?}")? - } - crate::ScalarValue::Bool(value) => write!(self.out, "{value}")?, - }; - } - crate::ConstantInner::Composite { ty, ref components } => { - self.write_type(module, ty)?; - let name = &self.names[&NameKey::Constant(handle)]; - write!(self.out, " {name} = ")?; - self.write_composite_constant(module, ty, components)?; - } + let constant = &module.constants[handle]; + self.write_type(module, constant.ty)?; + let name = &self.names[&NameKey::Constant(handle)]; + write!(self.out, " {}", name)?; + // Write size for array type + if let TypeInner::Array { base, size, .. } = module.types[constant.ty].inner { + self.write_array_size(module, base, size)?; } + write!(self.out, " = ")?; + self.write_const_expression(module, constant.init)?; writeln!(self.out, ";")?; Ok(()) } @@ -1261,12 +1223,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, " = ")?; // Write the local initializer if needed if let Some(init) = local.init { - // Put the equal signal only if there's a initializer - // The leading and trailing spaces aren't needed but help with readability - - // Write the constant - // `write_constant` adds no trailing or leading space/newline - self.write_constant(module, init)?; + self.write_const_expression(module, init)?; } else { // Zero initialize local variables self.write_default_init(module, local.ty)?; @@ -1859,12 +1816,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let func_name = &self.names[&NameKey::Function(function)]; write!(self.out, "{func_name}(")?; for (index, argument) in arguments.iter().enumerate() { - self.write_expr(module, *argument, func_ctx)?; - // Only write a comma if isn't the last element - if index != arguments.len().saturating_sub(1) { - // The leading space is for readability only + if index != 0 { write!(self.out, ", ")?; } + self.write_expr(module, *argument, func_ctx)?; } writeln!(self.out, ");")? } @@ -2043,6 +1998,77 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } + fn write_const_expression( + &mut self, + module: &Module, + expr: Handle, + ) -> BackendResult { + self.write_possibly_const_expression( + module, + expr, + &module.const_expressions, + |writer, expr| writer.write_const_expression(module, expr), + ) + } + + fn write_possibly_const_expression( + &mut self, + module: &Module, + expr: Handle, + expressions: &crate::Arena, + write_expression: E, + ) -> BackendResult + where + E: Fn(&mut Self, Handle) -> BackendResult, + { + use crate::Expression; + + match expressions[expr] { + Expression::Literal(literal) => match literal { + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero + crate::Literal::F64(value) => write!(self.out, "{value:?}L")?, + crate::Literal::F32(value) => write!(self.out, "{value:?}")?, + crate::Literal::U32(value) => write!(self.out, "{}u", value)?, + crate::Literal::I32(value) => write!(self.out, "{}", value)?, + crate::Literal::Bool(value) => write!(self.out, "{}", value)?, + }, + Expression::Constant(handle) => { + let constant = &module.constants[handle]; + if constant.name.is_some() { + write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?; + } else { + self.write_const_expression(module, constant.init)?; + } + } + Expression::ZeroValue(ty) => self.write_default_init(module, ty)?, + Expression::Compose { ty, ref components } => { + match module.types[ty].inner { + TypeInner::Struct { .. } | TypeInner::Array { .. } => { + self.write_wrapped_constructor_function_name( + module, + WrappedConstructor { ty }, + )?; + } + _ => { + self.write_type(module, ty)?; + } + }; + write!(self.out, "(")?; + for (index, component) in components.iter().enumerate() { + if index != 0 { + write!(self.out, ", ")?; + } + write_expression(self, *component)?; + } + write!(self.out, ")")?; + } + _ => unreachable!(), + } + + Ok(()) + } + /// Helper method to write expressions /// /// # Notes @@ -2091,41 +2117,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let expression = &func_ctx.expressions[expr]; match *expression { - Expression::Constant(constant) => self.write_constant(module, constant)?, - Expression::ZeroValue(ty) => self.write_default_init(module, ty)?, - Expression::Literal(literal) => match literal { - // Floats are written using `Debug` instead of `Display` because it always appends the - // decimal part even it's zero - crate::Literal::F64(value) => write!(self.out, "{value:?}L")?, - crate::Literal::F32(value) => write!(self.out, "{value:?}")?, - crate::Literal::U32(value) => write!(self.out, "{}u", value)?, - crate::Literal::I32(value) => write!(self.out, "{}", value)?, - crate::Literal::Bool(value) => write!(self.out, "{}", value)?, - }, - Expression::Compose { ty, ref components } => { - match module.types[ty].inner { - TypeInner::Struct { .. } | TypeInner::Array { .. } => { - self.write_wrapped_constructor_function_name( - module, - WrappedConstructor { ty }, - )?; - } - _ => { - self.write_type(module, ty)?; - } - }; - - write!(self.out, "(")?; - - for (index, &component) in components.iter().enumerate() { - if index != 0 { - // The leading space is for readability only - write!(self.out, ", ")?; - } - self.write_expr(module, component, func_ctx)?; - } - - write!(self.out, ")")?; + Expression::Literal(_) + | Expression::Constant(_) + | Expression::ZeroValue(_) + | Expression::Compose { .. } => { + self.write_possibly_const_expression( + module, + expr, + func_ctx.expressions, + |writer, expr| writer.write_expr(module, expr, func_ctx), + )?; } // All of the multiplication can be expressed as `mul`, // except vector * vector, which needs to use the "*" operator. @@ -2412,7 +2413,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if let Some(offset) = offset { write!(self.out, ", ")?; - self.write_constant(module, offset)?; + self.write_const_expression(module, offset)?; } write!(self.out, ")")?; @@ -3184,82 +3185,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } - /// Helper method used to write constants - /// - /// # Notes - /// Doesn't add any newlines or leading/trailing spaces - fn write_constant( - &mut self, - module: &Module, - handle: Handle, - ) -> BackendResult { - let constant = &module.constants[handle]; - match constant.inner { - crate::ConstantInner::Scalar { - width: _, - ref value, - } => { - if constant.name.is_some() { - write!(self.out, "{}", &self.names[&NameKey::Constant(handle)])?; - } else { - self.write_scalar_value(*value)?; - } - } - crate::ConstantInner::Composite { ty, ref components } => { - self.write_composite_constant(module, ty, components)?; - } - } - - Ok(()) - } - - fn write_composite_constant( - &mut self, - module: &Module, - ty: Handle, - components: &[Handle], - ) -> BackendResult { - match module.types[ty].inner { - TypeInner::Struct { .. } | TypeInner::Array { .. } => { - self.write_wrapped_constructor_function_name(module, WrappedConstructor { ty })?; - } - _ => { - self.write_type(module, ty)?; - } - }; - write!(self.out, "(")?; - for (index, constant) in components.iter().enumerate() { - self.write_constant(module, *constant)?; - // Only write a comma if isn't the last element - if index != components.len().saturating_sub(1) { - // The leading space is for readability only - write!(self.out, ", ")?; - } - } - write!(self.out, ")")?; - - Ok(()) - } - - /// Helper method used to write [`ScalarValue`](crate::ScalarValue) - /// - /// # Notes - /// Adds no trailing or leading whitespace - fn write_scalar_value(&mut self, value: crate::ScalarValue) -> BackendResult { - use crate::ScalarValue as Sv; - - match value { - Sv::Sint(value) => write!(self.out, "{value}")?, - Sv::Uint(value) => write!(self.out, "{value}u")?, - // Floats are written using `Debug` instead of `Display` because it always appends the - // decimal part even it's zero - Sv::Float(value) => write!(self.out, "{value:?}")?, - Sv::Bool(value) => write!(self.out, "{value}")?, - } - - Ok(()) - } - fn write_named_expr( &mut self, module: &Module, diff --git a/src/back/mod.rs b/src/back/mod.rs index 76fbaf764..875b04d69 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -71,6 +71,14 @@ struct FunctionCtx<'a> { } impl FunctionCtx<'_> { + fn resolve_type<'a>( + &'a self, + handle: crate::Handle, + types: &'a crate::UniqueArena, + ) -> &'a crate::TypeInner { + self.info[handle].ty.inner_with(types) + } + /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function const fn name_key(&self, local: crate::Handle) -> crate::proc::NameKey { match self.ty { diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 1c9e87ff2..a8a103e6d 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -300,50 +300,6 @@ impl<'a> TypedGlobalVariable<'a> { } } -struct ConstantContext<'a> { - handle: Handle, - arena: &'a crate::Arena, - names: &'a FastHashMap, - first_time: bool, -} - -impl<'a> Display for ConstantContext<'a> { - fn fmt(&self, out: &mut Formatter<'_>) -> Result<(), FmtError> { - let con = &self.arena[self.handle]; - if con.needs_alias() && !self.first_time { - let name = &self.names[&NameKey::Constant(self.handle)]; - return write!(out, "{name}"); - } - - match con.inner { - crate::ConstantInner::Scalar { value, width: _ } => match value { - crate::ScalarValue::Sint(value) => { - write!(out, "{value}") - } - crate::ScalarValue::Uint(value) => { - write!(out, "{value}u") - } - crate::ScalarValue::Float(value) => { - if value.is_infinite() { - let sign = if value.is_sign_negative() { "-" } else { "" }; - write!(out, "{sign}INFINITY") - } else if value.is_nan() { - write!(out, "NAN") - } else { - let suffix = if value.fract() == 0.0 { ".0" } else { "" }; - - write!(out, "{value}{suffix}") - } - } - crate::ScalarValue::Bool(value) => { - write!(out, "{value}") - } - }, - crate::ConstantInner::Composite { .. } => unreachable!("should be aliased"), - } - } -} - pub struct Writer { out: W, names: FastHashMap, @@ -501,16 +457,6 @@ impl crate::Type { } } -impl crate::Constant { - // Returns `true` if we need to emit an alias for this constant. - const fn needs_alias(&self) -> bool { - match self.inner { - crate::ConstantInner::Scalar { .. } => self.name.is_some(), - crate::ConstantInner::Composite { .. } => true, - } - } -} - enum FunctionOrigin { Handle(Handle), EntryPoint(proc::EntryPointIndex), @@ -655,12 +601,25 @@ impl Writer { parameters: impl Iterator>, context: &ExpressionContext, ) -> BackendResult { + self.put_call_parameters_impl(parameters, |writer, expr| { + writer.put_expression(expr, context, true) + }) + } + + fn put_call_parameters_impl( + &mut self, + parameters: impl Iterator>, + put_expression: E, + ) -> BackendResult + where + E: Fn(&mut Self, Handle) -> BackendResult, + { write!(self.out, "(")?; for (i, handle) in parameters.enumerate() { if i != 0 { write!(self.out, ", ")?; } - self.put_expression(handle, context, true)?; + put_expression(self, handle)?; } write!(self.out, ")")?; Ok(()) @@ -1077,44 +1036,6 @@ impl Writer { Ok(()) } - fn put_compose( - &mut self, - ty: Handle, - components: &[Handle], - context: &ExpressionContext, - ) -> BackendResult { - match context.module.types[ty].inner { - crate::TypeInner::Scalar { width: 4, kind } if components.len() == 1 => { - write!(self.out, "{}", kind.to_msl_name())?; - self.put_call_parameters(components.iter().cloned(), context)?; - } - crate::TypeInner::Vector { size, kind, .. } => { - put_numeric_type(&mut self.out, kind, &[size])?; - self.put_call_parameters(components.iter().cloned(), context)?; - } - crate::TypeInner::Matrix { columns, rows, .. } => { - put_numeric_type(&mut self.out, crate::ScalarKind::Float, &[rows, columns])?; - self.put_call_parameters(components.iter().cloned(), context)?; - } - crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { - write!(self.out, "{} {{", &self.names[&NameKey::Type(ty)])?; - for (index, &component) in components.iter().enumerate() { - if index != 0 { - write!(self.out, ", ")?; - } - // insert padding initialization, if needed - if self.struct_member_pads.contains(&(ty, index as u32)) { - write!(self.out, "{{}}, ")?; - } - self.put_expression(component, context, true)?; - } - write!(self.out, "}}")?; - } - _ => return Err(Error::UnsupportedCompose(ty)), - } - Ok(()) - } - /// Write the maximum valid index of the dynamically sized array at the end of `handle`. /// /// The 'maximum valid index' is simply one less than the array's length. @@ -1260,6 +1181,113 @@ impl Writer { Ok(()) } + fn put_const_expression( + &mut self, + expr_handle: Handle, + module: &crate::Module, + ) -> BackendResult { + self.put_possibly_const_expression( + expr_handle, + &module.const_expressions, + module, + |writer, expr| writer.put_const_expression(expr, module), + ) + } + + fn put_possibly_const_expression( + &mut self, + expr_handle: Handle, + expressions: &crate::Arena, + module: &crate::Module, + put_expression: E, + ) -> BackendResult + where + E: Fn(&mut Self, Handle) -> BackendResult, + { + match expressions[expr_handle] { + crate::Expression::Literal(literal) => match literal { + crate::Literal::F64(_) => { + return Err(Error::CapabilityNotSupported(valid::Capabilities::FLOAT64)) + } + crate::Literal::F32(value) => { + if value.is_infinite() { + let sign = if value.is_sign_negative() { "-" } else { "" }; + write!(self.out, "{sign}INFINITY")?; + } else if value.is_nan() { + write!(self.out, "NAN")?; + } else { + let suffix = if value.fract() == 0.0 { ".0" } else { "" }; + write!(self.out, "{value}{suffix}")?; + } + } + crate::Literal::U32(value) => { + write!(self.out, "{value}u")?; + } + crate::Literal::I32(value) => { + write!(self.out, "{value}")?; + } + crate::Literal::Bool(value) => { + write!(self.out, "{value}")?; + } + }, + crate::Expression::Constant(handle) => { + let constant = &module.constants[handle]; + if constant.name.is_some() { + write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?; + } else { + self.put_const_expression(constant.init, module)?; + } + } + crate::Expression::ZeroValue(ty) => { + let ty_name = TypeContext { + handle: ty, + gctx: module.to_ctx(), + names: &self.names, + access: crate::StorageAccess::empty(), + binding: None, + first_time: false, + }; + write!(self.out, "{ty_name} {{}}")?; + } + crate::Expression::Compose { ty, ref components } => { + let ty_name = TypeContext { + handle: ty, + gctx: module.to_ctx(), + names: &self.names, + access: crate::StorageAccess::empty(), + binding: None, + first_time: false, + }; + write!(self.out, "{ty_name}")?; + match module.types[ty].inner { + crate::TypeInner::Scalar { .. } + | crate::TypeInner::Vector { .. } + | crate::TypeInner::Matrix { .. } => { + self.put_call_parameters_impl(components.iter().copied(), put_expression)?; + } + crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { + write!(self.out, " {{")?; + for (index, &component) in components.iter().enumerate() { + if index != 0 { + write!(self.out, ", ")?; + } + // insert padding initialization, if needed + if self.struct_member_pads.contains(&(ty, index as u32)) { + write!(self.out, "{{}}, ")?; + } + put_expression(self, component)?; + } + write!(self.out, "}}")?; + } + _ => return Err(Error::UnsupportedCompose(ty)), + } + } + _ => unreachable!(), + } + + Ok(()) + } + /// Emit code for the expression `expr_handle`. /// /// The `is_scoped` argument is true if the surrounding operators have the @@ -1291,6 +1319,17 @@ impl Writer { let expression = &context.function.expressions[expr_handle]; log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { + crate::Expression::Literal(_) + | crate::Expression::Constant(_) + | crate::Expression::ZeroValue(_) + | crate::Expression::Compose { .. } => { + self.put_possibly_const_expression( + expr_handle, + &context.function.expressions, + context.module, + |writer, expr| writer.put_expression(expr, context, true), + )?; + } crate::Expression::Access { base, .. } | crate::Expression::AccessIndex { base, .. } => { // This is an acceptable place to generate a `ReadZeroSkipWrite` check. @@ -1318,51 +1357,6 @@ impl Writer { self.put_access_chain(expr_handle, policy, context)?; } } - crate::Expression::Constant(handle) => { - let coco = ConstantContext { - handle, - arena: &context.module.constants, - names: &self.names, - first_time: false, - }; - write!(self.out, "{coco}")?; - } - crate::Expression::ZeroValue(ty) => { - let ty_name = TypeContext { - handle: ty, - gctx: context.module.to_ctx(), - names: &self.names, - access: crate::StorageAccess::empty(), - binding: None, - first_time: false, - }; - write!(self.out, "{ty_name} {{}}")?; - } - crate::Expression::Literal(literal) => match literal { - crate::Literal::F64(_) => { - return Err(Error::CapabilityNotSupported(valid::Capabilities::FLOAT64)) - } - crate::Literal::F32(value) => { - if value.is_infinite() { - let sign = if value.is_sign_negative() { "-" } else { "" }; - write!(self.out, "{sign}INFINITY")?; - } else if value.is_nan() { - write!(self.out, "NAN")?; - } else { - let suffix = if value.fract() == 0.0 { ".0" } else { "" }; - write!(self.out, "{value}{suffix}")?; - } - } - crate::Literal::U32(value) => { - write!(self.out, "{value}u")?; - } - crate::Literal::I32(value) => { - write!(self.out, "{value}")?; - } - crate::Literal::Bool(value) => { - write!(self.out, "{value}")?; - } - }, crate::Expression::Splat { size, value } => { let scalar_kind = match *context.resolve_type(value) { crate::TypeInner::Scalar { kind, .. } => kind, @@ -1384,9 +1378,6 @@ impl Writer { write!(self.out, "{}", back::COMPONENTS[sc as usize])?; } } - crate::Expression::Compose { ty, ref components } => { - self.put_compose(ty, components, context)?; - } crate::Expression::FunctionArgument(index) => { let name_key = match context.origin { FunctionOrigin::Handle(handle) => NameKey::FunctionArgument(handle, index), @@ -1448,15 +1439,11 @@ impl Writer { self.put_image_sample_level(image, level, context)?; - if let Some(constant) = offset { - let coco = ConstantContext { - handle: constant, - arena: &context.module.constants, - names: &self.names, - first_time: false, - }; - write!(self.out, ", {coco}")?; + if let Some(offset) = offset { + write!(self.out, ", ")?; + self.put_const_expression(offset, context.module)?; } + match gather { None | Some(crate::SwizzleComponent::X) => {} Some(component) => { @@ -2270,15 +2257,11 @@ impl Writer { policy: index::BoundsCheckPolicy, context: &ExpressionContext, ) -> BackendResult { - let is_atomic = match *context.resolve_type(pointer) { - crate::TypeInner::Pointer { base, .. } => match context.module.types[base].inner { - crate::TypeInner::Atomic { .. } => true, - _ => false, - }, - _ => false, - }; + let is_atomic_pointer = context + .resolve_type(pointer) + .is_atomic_pointer(&context.module.types); - if is_atomic { + if is_atomic_pointer { write!( self.out, "{NAMESPACE}::atomic_load_explicit({ATOMIC_REFERENCE}" @@ -2420,9 +2403,8 @@ impl Writer { // check what kind of product this is depending // on the resolve type of the Dot function itself - if let crate::TypeInner::Scalar { kind, .. } = - *context.resolve_type(expr_handle) - { + let inner = context.resolve_type(expr_handle); + if let crate::TypeInner::Scalar { kind, .. } = *inner { match kind { crate::ScalarKind::Sint | crate::ScalarKind::Uint => { self.need_bake_expressions.insert(arg); @@ -2991,18 +2973,12 @@ impl Writer { level: back::Level, context: &StatementContext, ) -> BackendResult { - let pointer_inner = context.expression.resolve_type(pointer); - let is_atomic = match *pointer_inner { - crate::TypeInner::Pointer { base, .. } => { - match context.expression.module.types[base].inner { - crate::TypeInner::Atomic { .. } => true, - _ => false, - } - } - _ => false, - }; + let is_atomic_pointer = context + .expression + .resolve_type(pointer) + .is_atomic_pointer(&context.expression.module.types); - if is_atomic { + if is_atomic_pointer { write!( self.out, "{level}{NAMESPACE}::atomic_store_explicit({ATOMIC_REFERENCE}" @@ -3107,9 +3083,8 @@ impl Writer { } }; - self.write_scalar_constants(module)?; self.write_type_defs(module)?; - self.write_composite_constants(module)?; + self.write_global_constants(module)?; self.write_functions(module, info, options, pipeline_options) } @@ -3264,78 +3239,25 @@ impl Writer { Ok(()) } - fn write_scalar_constants(&mut self, module: &crate::Module) -> BackendResult { - for (handle, constant) in module.constants.iter() { - match constant.inner { - crate::ConstantInner::Scalar { - width: _, - ref value, - } if constant.name.is_some() => { - debug_assert!(constant.needs_alias()); - write!(self.out, "constexpr constant ")?; - match *value { - crate::ScalarValue::Sint(_) => { - write!(self.out, "int")?; - } - crate::ScalarValue::Uint(_) => { - write!(self.out, "unsigned")?; - } - crate::ScalarValue::Float(_) => { - write!(self.out, "float")?; - } - crate::ScalarValue::Bool(_) => { - write!(self.out, "bool")?; - } - } - let name = &self.names[&NameKey::Constant(handle)]; - let coco = ConstantContext { - handle, - arena: &module.constants, - names: &self.names, - first_time: true, - }; - writeln!(self.out, " {name} = {coco};")?; - } - _ => {} - } - } - Ok(()) - } + /// Writes all named constants + fn write_global_constants(&mut self, module: &crate::Module) -> BackendResult { + let constants = module.constants.iter().filter(|&(_, c)| c.name.is_some()); - fn write_composite_constants(&mut self, module: &crate::Module) -> BackendResult { - for (handle, constant) in module.constants.iter() { - match constant.inner { - crate::ConstantInner::Scalar { .. } => {} - crate::ConstantInner::Composite { ty, ref components } => { - debug_assert!(constant.needs_alias()); - let name = &self.names[&NameKey::Constant(handle)]; - let ty_name = TypeContext { - handle: ty, - gctx: module.to_ctx(), - names: &self.names, - access: crate::StorageAccess::empty(), - binding: None, - first_time: false, - }; - write!(self.out, "constant {ty_name} {name} = {{",)?; - for (i, &sub_handle) in components.iter().enumerate() { - // insert padding initialization, if needed - if self.struct_member_pads.contains(&(ty, i as u32)) { - write!(self.out, ", {{}}")?; - } - let separator = if i != 0 { ", " } else { "" }; - let coco = ConstantContext { - handle: sub_handle, - arena: &module.constants, - names: &self.names, - first_time: false, - }; - write!(self.out, "{separator}{coco}")?; - } - writeln!(self.out, "}};")?; - } - } + for (handle, constant) in constants { + let ty_name = TypeContext { + handle: constant.ty, + gctx: module.to_ctx(), + names: &self.names, + access: crate::StorageAccess::empty(), + binding: None, + first_time: false, + }; + let name = &self.names[&NameKey::Constant(handle)]; + write!(self.out, "constant {ty_name} {name} = ")?; + self.put_const_expression(constant.init, module)?; + writeln!(self.out, ";")?; } + Ok(()) } @@ -3528,13 +3450,8 @@ impl Writer { write!(self.out, "{}{} {}", back::INDENT, ty_name, local_name)?; match local.init { Some(value) => { - let coco = ConstantContext { - handle: value, - arena: &module.constants, - names: &self.names, - first_time: false, - }; - write!(self.out, " = {coco}")?; + write!(self.out, " = ")?; + self.put_const_expression(value, module)?; } None => { write!(self.out, " = {{}}")?; @@ -3935,13 +3852,8 @@ impl Writer { resolved.try_fmt(&mut self.out)?; } if let Some(value) = var.init { - let coco = ConstantContext { - handle: value, - arena: &module.constants, - names: &self.names, - first_time: false, - }; - write!(self.out, " = {coco}")?; + write!(self.out, " = ")?; + self.put_const_expression(value, module)?; } writeln!(self.out)?; } @@ -3996,13 +3908,9 @@ impl Writer { tyvar.try_fmt(&mut self.out)?; match var.init { Some(value) => { - let coco = ConstantContext { - handle: value, - arena: &module.constants, - names: &self.names, - first_time: false, - }; - writeln!(self.out, " = {coco};")?; + write!(self.out, " = ")?; + self.put_const_expression(value, module)?; + writeln!(self.out, ";")?; } None => { writeln!(self.out, " = {{}};")?; @@ -4100,13 +4008,8 @@ impl Writer { write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; match local.init { Some(value) => { - let coco = ConstantContext { - handle: value, - arena: &module.constants, - names: &self.names, - first_time: false, - }; - write!(self.out, " = {coco}")?; + write!(self.out, " = ")?; + self.put_const_expression(value, module)?; } None => { write!(self.out, " = {{}}")?; @@ -4373,21 +4276,11 @@ fn test_stack_size() { use crate::valid::{Capabilities, ValidationFlags}; // create a module with at least one expression nested let mut module = crate::Module::default(); - let constant = module.constants.append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - value: crate::ScalarValue::Float(1.0), - width: 4, - }, - }, + let mut fun = crate::Function::default(); + let const_expr = fun.expressions.append( + crate::Expression::Literal(crate::Literal::F32(1.0)), Default::default(), ); - let mut fun = crate::Function::default(); - let const_expr = fun - .expressions - .append(crate::Expression::Constant(constant), Default::default()); let nested_expr = fun.expressions.append( crate::Expression::Unary { op: crate::UnaryOperator::Negate, diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 84910e699..ec3531ede 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -237,6 +237,29 @@ impl<'w> BlockContext<'w> { let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty); let id = match self.ir_function.expressions[expr_handle] { + crate::Expression::Literal(literal) => self.writer.get_constant_scalar(literal), + crate::Expression::Constant(handle) => { + let init = self.ir_module.constants[handle].init; + self.writer.constant_ids[init.index()] + } + crate::Expression::ZeroValue(_) => self.writer.write_constant_null(result_type_id), + crate::Expression::Compose { + ty: _, + ref components, + } => { + self.temp_list.clear(); + for &component in components { + self.temp_list.push(self.cached[component]); + } + + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + result_type_id, + id, + &self.temp_list, + )); + id + } crate::Expression::Access { base, index: _ } if self.is_intermediate(base) => { // See `is_intermediate`; we'll handle this later in // `write_expression_pointer`. @@ -372,9 +395,6 @@ impl<'w> BlockContext<'w> { crate::Expression::GlobalVariable(handle) => { self.writer.global_variables[handle.index()].access_id } - crate::Expression::Constant(handle) => self.writer.constant_ids[handle.index()], - crate::Expression::ZeroValue(_) => self.writer.write_constant_null(result_type_id), - crate::Expression::Literal(literal) => self.writer.get_constant_scalar(literal), crate::Expression::Splat { size, value } => { let value_id = self.cached[value]; let components = [value_id; 4]; @@ -406,23 +426,6 @@ impl<'w> BlockContext<'w> { )); id } - crate::Expression::Compose { - ty: _, - ref components, - } => { - self.temp_list.clear(); - for &component in components { - self.temp_list.push(self.cached[component]); - } - - let id = self.gen_id(); - block.body.push(Instruction::composite_construct( - result_type_id, - id, - &self.temp_list, - )); - id - } crate::Expression::Unary { op, expr } => { let id = self.gen_id(); let expr_id = self.cached[expr]; diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index b62a711ef..ac4b71d95 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -823,7 +823,7 @@ impl<'w> BlockContext<'w> { gather: Option, coordinate: Handle, array_index: Option>, - offset: Option>, + offset: Option>, level: crate::SampleLevel, depth_ref: Option>, block: &mut Block, diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index d2cbdf4d6..19cc4a896 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -176,17 +176,19 @@ impl<'w> BlockContext<'w> { // done the bounds check. let max_index_id = match self.write_sequence_max_index(sequence, block)? { MaybeKnown::Known(known_max_index) => { - if let crate::Expression::Constant(index_k) = self.ir_function.expressions[index] { - if let Some(known_index) = self.ir_module.constants[index_k].to_array_length() { - // Both the index and length are known at compile time. - // - // In strict WGSL compliance mode, out-of-bounds indices cannot be - // reported at shader translation time, and must be replaced with - // in-bounds indices at run time. So we cannot assume that - // validation ensured the index was in bounds. Restrict now. - let restricted = std::cmp::min(known_index, known_max_index); - return Ok(BoundsCheckResult::KnownInBounds(restricted)); - } + if let Ok(known_index) = self + .ir_module + .to_ctx() + .eval_expr_to_u32_from(index, &self.ir_function.expressions) + { + // Both the index and length are known at compile time. + // + // In strict WGSL compliance mode, out-of-bounds indices cannot be + // reported at shader translation time, and must be replaced with + // in-bounds indices at run time. So we cannot assume that + // validation ensured the index was in bounds. Restrict now. + let restricted = std::cmp::min(known_index, known_max_index); + return Ok(BoundsCheckResult::KnownInBounds(restricted)); } self.get_index_constant(known_max_index) @@ -236,31 +238,33 @@ impl<'w> BlockContext<'w> { // bounds check. let length_id = match self.write_sequence_length(sequence, block)? { MaybeKnown::Known(known_length) => { - if let crate::Expression::Constant(index_k) = self.ir_function.expressions[index] { - if let Some(known_index) = self.ir_module.constants[index_k].to_array_length() { - // Both the index and length are known at compile time. - // - // It would be nice to assume that, since we are using the - // `ReadZeroSkipWrite` policy, we are not in strict WGSL - // compliance mode, and thus we can count on the validator to have - // rejected any programs with known out-of-bounds indices, and - // thus just return `KnownInBounds` here without actually - // checking. - // - // But it's also reasonable to expect that bounds check policies - // and error reporting policies should be able to vary - // independently without introducing security holes. So, we should - // support the case where bad indices do not cause validation - // errors, and are handled via `ReadZeroSkipWrite`. - // - // In theory, when `known_index` is bad, we could return a new - // `KnownOutOfBounds` variant here. But it's simpler just to fall - // through and let the bounds check take place. The shader is - // broken anyway, so it doesn't make sense to invest in emitting - // the ideal code for it. - if known_index < known_length { - return Ok(BoundsCheckResult::KnownInBounds(known_index)); - } + if let Ok(known_index) = self + .ir_module + .to_ctx() + .eval_expr_to_u32_from(index, &self.ir_function.expressions) + { + // Both the index and length are known at compile time. + // + // It would be nice to assume that, since we are using the + // `ReadZeroSkipWrite` policy, we are not in strict WGSL + // compliance mode, and thus we can count on the validator to have + // rejected any programs with known out-of-bounds indices, and + // thus just return `KnownInBounds` here without actually + // checking. + // + // But it's also reasonable to expect that bounds check policies + // and error reporting policies should be able to vary + // independently without introducing security holes. So, we should + // support the case where bad indices do not cause validation + // errors, and are handled via `ReadZeroSkipWrite`. + // + // In theory, when `known_index` is bad, we could return a new + // `KnownOutOfBounds` variant here. But it's simpler just to fall + // through and let the bounds check take place. The shader is + // broken anyway, so it doesn't make sense to invest in emitting + // the ideal code for it. + if known_index < known_length { + return Ok(BoundsCheckResult::KnownInBounds(known_index)); } } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 8554c6226..2d395effa 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -616,6 +616,7 @@ pub struct Writer { lookup_type: crate::FastHashMap, lookup_function: crate::FastHashMap, Word>, lookup_function_type: crate::FastHashMap, + /// Indexed by const-expression handle indexes constant_ids: Vec, cached_constants: crate::FastHashMap, global_variables: Vec, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 554db6d8a..e402400b3 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1213,6 +1213,36 @@ impl Writer { null_id } + fn write_constant_expr( + &mut self, + handle: Handle, + ir_module: &crate::Module, + ) -> Result { + let id = match ir_module.const_expressions[handle] { + crate::Expression::Literal(literal) => self.get_constant_scalar(literal), + crate::Expression::Constant(constant) => { + let constant = &ir_module.constants[constant]; + self.constant_ids[constant.init.index()] + } + crate::Expression::ZeroValue(ty) => { + let type_id = self.get_type_id(LookupType::Handle(ty)); + self.write_constant_null(type_id) + } + crate::Expression::Compose { ty, ref components } => { + let component_ids: Vec<_> = components + .iter() + .map(|component| self.constant_ids[component.index()]) + .collect(); + self.get_constant_composite(LookupType::Handle(ty), component_ids.as_slice()) + } + _ => unreachable!(), + }; + + self.constant_ids[handle.index()] = id; + + Ok(id) + } + pub(super) fn write_barrier(&mut self, flags: crate::Barrier, block: &mut Block) { let memory_scope = if flags.contains(crate::Barrier::STORAGE) { spirv::Scope::Device @@ -1796,59 +1826,30 @@ impl Writer { } } - self.constant_ids.resize(ir_module.constants.len(), 0); - // first, output all the scalar constants - for (handle, constant) in ir_module.constants.iter() { - match constant.inner { - crate::ConstantInner::Composite { .. } => continue, - crate::ConstantInner::Scalar { width, ref value } => { - let literal = crate::Literal::from_scalar(*value, width).ok_or( - Error::Validation("Unexpected kind and/or width for Literal"), - )?; - self.constant_ids[handle.index()] = match constant.name { - Some(ref name) => { - let id = self.id_gen.next(); - self.write_constant_scalar(id, &literal, Some(name)); - id - } - None => self.get_constant_scalar(literal), - }; - } - } - } - - // then all types, some of them may rely on constants and struct type set + // write all types for (handle, _) in ir_module.types.iter() { self.write_type_declaration_arena(&ir_module.types, handle)?; } - // then all the composite constants, they rely on types - for (handle, constant) in ir_module.constants.iter() { - match constant.inner { - crate::ConstantInner::Scalar { .. } => continue, - crate::ConstantInner::Composite { ty, ref components } => { - let ty = LookupType::Handle(ty); + // write all const-expressions as constants + self.constant_ids + .resize(ir_module.const_expressions.len(), 0); + for (handle, _) in ir_module.const_expressions.iter() { + self.write_constant_expr(handle, ir_module)?; + } + debug_assert!(self.constant_ids.iter().all(|&id| id != 0)); - let mut constituent_ids = Vec::with_capacity(components.len()); - for constituent in components.iter() { - let constituent_id = self.constant_ids[constituent.index()]; - constituent_ids.push(constituent_id); - } - - self.constant_ids[handle.index()] = match constant.name { - Some(ref name) => { - let id = self.id_gen.next(); - self.write_constant_composite(id, ty, &constituent_ids, Some(name)); - id - } - None => self.get_constant_composite(ty, &constituent_ids), - }; + // write the name of constants on their respective const-expression initializer + if self.flags.contains(WriterFlags::DEBUG) { + for (_, constant) in ir_module.constants.iter() { + if let Some(ref name) = constant.name { + let id = self.constant_ids[constant.init.index()]; + self.debugs.push(Instruction::name(id, name)); } } } - debug_assert_eq!(self.constant_ids.iter().position(|&id| id == 0), None); - // now write all globals + // write all global variables for (handle, var) in ir_module.global_variables.iter() { // If a single entry point was specified, only write `OpVariable` instructions // for the globals it actually uses. Emit dummies for the others, @@ -1865,7 +1866,7 @@ impl Writer { self.global_variables.push(gvar); } - // all functions + // write all functions for (handle, ir_function) in ir_module.functions.iter() { let info = &mod_info[handle]; if let Some(index) = ep_index { @@ -1882,7 +1883,7 @@ impl Writer { self.lookup_function.insert(handle, id); } - // and entry points + // write all or one entry points for (index, ir_ep) in ir_module.entry_points.iter().enumerate() { if ep_index.is_some() && ep_index != Some(index) { continue; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 225df0b89..44dd2a97c 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -118,10 +118,17 @@ impl Writer { } } - // Write all constants - for (handle, constant) in module.constants.iter() { - if constant.name.is_some() { - self.write_global_constant(module, &constant.inner, handle)?; + // Write all named constants + let mut constants = module + .constants + .iter() + .filter(|&(_, c)| c.name.is_some()) + .peekable(); + while let Some((handle, _)) = constants.next() { + self.write_global_constant(module, handle)?; + // Add extra newline for readability on last iteration + if constants.peek().is_none() { + writeln!(self.out)?; } } @@ -182,25 +189,6 @@ impl Writer { Ok(()) } - /// Helper method used to write [`ScalarValue`](crate::ScalarValue) - /// - /// # Notes - /// Adds no trailing or leading whitespace - fn write_scalar_value(&mut self, value: crate::ScalarValue) -> BackendResult { - use crate::ScalarValue as Sv; - - match value { - Sv::Sint(value) => write!(self.out, "{value}")?, - Sv::Uint(value) => write!(self.out, "{value}u")?, - // Floats are written using `Debug` instead of `Display` because it always appends the - // decimal part even it's zero - Sv::Float(value) => write!(self.out, "{value:?}")?, - Sv::Bool(value) => write!(self.out, "{value}")?, - } - - Ok(()) - } - /// Helper method used to write struct name /// /// # Notes @@ -302,7 +290,7 @@ impl Writer { // Write the constant // `write_constant` adds no trailing or leading space/newline - self.write_constant(module, init)?; + self.write_const_expression(module, init)?; } // Finish the local with `;` and add a newline (only for readability) @@ -708,14 +696,11 @@ impl Writer { Statement::Store { pointer, value } => { write!(self.out, "{level}")?; - let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { - crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { - crate::TypeInner::Atomic { .. } => true, - _ => false, - }, - _ => false, - }; - if is_atomic { + let is_atomic_pointer = func_ctx + .resolve_type(pointer, &module.types) + .is_atomic_pointer(&module.types); + + if is_atomic_pointer { write!(self.out, "atomicStore(")?; self.write_expr(module, pointer, func_ctx)?; write!(self.out, ", ")?; @@ -747,12 +732,10 @@ impl Writer { let func_name = &self.names[&NameKey::Function(function)]; write!(self.out, "{func_name}(")?; for (index, &argument) in arguments.iter().enumerate() { - self.write_expr(module, argument, func_ctx)?; - // Only write a comma if isn't the last element - if index != arguments.len().saturating_sub(1) { - // The leading space is for readability only + if index != 0 { write!(self.out, ", ")?; } + self.write_expr(module, argument, func_ctx)?; } writeln!(self.out, ");")? } @@ -987,7 +970,7 @@ impl Writer { } } Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => { - let base_ty = func_ctx.info[base].ty.inner_with(&module.types); + let base_ty = func_ctx.resolve_type(base, &module.types); match *base_ty { crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { Indirection::Reference @@ -1077,6 +1060,74 @@ impl Writer { Ok(()) } + fn write_const_expression( + &mut self, + module: &Module, + expr: Handle, + ) -> BackendResult { + self.write_possibly_const_expression( + module, + expr, + &module.const_expressions, + |writer, expr| writer.write_const_expression(module, expr), + ) + } + + fn write_possibly_const_expression( + &mut self, + module: &Module, + expr: Handle, + expressions: &crate::Arena, + write_expression: E, + ) -> BackendResult + where + E: Fn(&mut Self, Handle) -> BackendResult, + { + use crate::Expression; + + match expressions[expr] { + Expression::Literal(literal) => { + match literal { + // Floats are written using `Debug` instead of `Display` because it always appends the + // decimal part even it's zero + crate::Literal::F64(_) => { + return Err(Error::Custom("unsupported f64 literal".to_string())); + } + crate::Literal::F32(value) => write!(self.out, "{:?}", value)?, + crate::Literal::U32(value) => write!(self.out, "{}u", value)?, + crate::Literal::I32(value) => write!(self.out, "{}", value)?, + crate::Literal::Bool(value) => write!(self.out, "{}", value)?, + } + } + Expression::Constant(handle) => { + let constant = &module.constants[handle]; + if constant.name.is_some() { + write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?; + } else { + self.write_const_expression(module, constant.init)?; + } + } + Expression::ZeroValue(ty) => { + self.write_type(module, ty)?; + write!(self.out, "()")?; + } + Expression::Compose { ty, ref components } => { + self.write_type(module, ty)?; + write!(self.out, "(")?; + for (index, component) in components.iter().enumerate() { + if index != 0 { + write!(self.out, ", ")?; + } + write_expression(self, *component)?; + } + write!(self.out, ")")? + } + _ => unreachable!(), + } + + Ok(()) + } + /// Write the 'plain form' of `expr`. /// /// An expression's 'plain form' is the most general rendition of that @@ -1109,36 +1160,16 @@ impl Writer { // `postfix_expression` forms for member/component access and // subscripting. match *expression { - Expression::Literal(literal) => { - match literal { - // Floats are written using `Debug` instead of `Display` because it always appends the - // decimal part even it's zero - crate::Literal::F64(_) => { - return Err(Error::Custom("unsupported f64 literal".to_string())); - } - crate::Literal::F32(value) => write!(self.out, "{:?}", value)?, - crate::Literal::U32(value) => write!(self.out, "{}u", value)?, - crate::Literal::I32(value) => write!(self.out, "{}", value)?, - crate::Literal::Bool(value) => write!(self.out, "{}", value)?, - } - } - Expression::Constant(constant) => self.write_constant(module, constant)?, - Expression::ZeroValue(ty) => { - self.write_type(module, ty)?; - write!(self.out, "()")?; - } - Expression::Compose { ty, ref components } => { - self.write_type(module, ty)?; - write!(self.out, "(")?; - for (index, component) in components.iter().enumerate() { - self.write_expr(module, *component, func_ctx)?; - // Only write a comma if isn't the last element - if index != components.len().saturating_sub(1) { - // The leading space is for readability only - write!(self.out, ", ")?; - } - } - write!(self.out, ")")? + Expression::Literal(_) + | Expression::Constant(_) + | Expression::ZeroValue(_) + | Expression::Compose { .. } => { + self.write_possibly_const_expression( + module, + expr, + func_ctx.expressions, + |writer, expr| writer.write_expr(module, expr, func_ctx), + )?; } Expression::FunctionArgument(pos) => { let name_key = func_ctx.argument_key(pos); @@ -1261,11 +1292,12 @@ impl Writer { if let Some(offset) = offset { write!(self.out, ", ")?; - self.write_constant(module, offset)?; + self.write_const_expression(module, offset)?; } write!(self.out, ")")?; } + Expression::ImageSample { image, sampler, @@ -1282,7 +1314,7 @@ impl Writer { }; write!(self.out, "textureGather{suffix_cmp}(")?; - match *func_ctx.info[image].ty.inner_with(&module.types) { + match *func_ctx.resolve_type(image, &module.types) { TypeInner::Image { class: crate::ImageClass::Depth { multi: _ }, .. @@ -1309,7 +1341,7 @@ impl Writer { if let Some(offset) = offset { write!(self.out, ", ")?; - self.write_constant(module, offset)?; + self.write_const_expression(module, offset)?; } write!(self.out, ")")?; @@ -1332,6 +1364,7 @@ impl Writer { }; write!(self.out, ")")?; } + Expression::ImageLoad { image, coordinate, @@ -1357,12 +1390,13 @@ impl Writer { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{name}")?; } + Expression::As { expr, kind, convert, } => { - let inner = func_ctx.info[expr].ty.inner_with(&module.types); + let inner = func_ctx.resolve_type(expr, &module.types); match *inner { TypeInner::Matrix { columns, @@ -1407,7 +1441,7 @@ impl Writer { write!(self.out, ")")?; } Expression::Splat { size, value } => { - let inner = func_ctx.info[value].ty.inner_with(&module.types); + let inner = func_ctx.resolve_type(value, &module.types); let (scalar_kind, scalar_width) = match *inner { crate::TypeInner::Scalar { kind, width } => (kind, width), _ => { @@ -1424,15 +1458,11 @@ impl Writer { write!(self.out, ")")?; } Expression::Load { pointer } => { - let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) { - crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { - crate::TypeInner::Atomic { .. } => true, - _ => false, - }, - _ => false, - }; + let is_atomic_pointer = func_ctx + .resolve_type(pointer, &module.types) + .is_atomic_pointer(&module.types); - if is_atomic { + if is_atomic_pointer { write!(self.out, "atomicLoad(")?; self.write_expr(module, pointer, func_ctx)?; write!(self.out, ")")?; @@ -1453,6 +1483,7 @@ impl Writer { self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")?; } + Expression::Math { fun, arg, @@ -1561,6 +1592,7 @@ impl Writer { } } } + Expression::Swizzle { size, vector, @@ -1576,7 +1608,7 @@ impl Writer { let unary = match op { crate::UnaryOperator::Negate => "-", crate::UnaryOperator::Not => { - match *func_ctx.info[expr].ty.inner_with(&module.types) { + match *func_ctx.resolve_type(expr, &module.types) { TypeInner::Scalar { kind: crate::ScalarKind::Bool, .. @@ -1592,6 +1624,7 @@ impl Writer { write!(self.out, ")")? } + Expression::Select { condition, accept, @@ -1688,7 +1721,7 @@ impl Writer { // Write initializer if let Some(init) = global.init { write!(self.out, " = ")?; - self.write_constant(module, init)?; + self.write_const_expression(module, init)?; } // End with semicolon @@ -1697,47 +1730,6 @@ impl Writer { Ok(()) } - /// Helper method used to write constants - /// - /// # Notes - /// Doesn't add any newlines or leading/trailing spaces - fn write_constant( - &mut self, - module: &Module, - handle: Handle, - ) -> BackendResult { - let constant = &module.constants[handle]; - match constant.inner { - crate::ConstantInner::Scalar { - width: _, - ref value, - } => { - if constant.name.is_some() { - write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?; - } else { - self.write_scalar_value(*value)?; - } - } - crate::ConstantInner::Composite { ty, ref components } => { - self.write_type(module, ty)?; - write!(self.out, "(")?; - - // Write the comma separated constants - for (index, constant) in components.iter().enumerate() { - self.write_constant(module, *constant)?; - // Only write a comma if isn't the last element - if index != components.len().saturating_sub(1) { - // The leading space is for readability only - write!(self.out, ", ")?; - } - } - write!(self.out, ")")? - } - } - - Ok(()) - } - /// Helper method used to write global constants /// /// # Notes @@ -1745,61 +1737,17 @@ impl Writer { fn write_global_constant( &mut self, module: &Module, - inner: &crate::ConstantInner, handle: Handle, ) -> BackendResult { - match *inner { - crate::ConstantInner::Scalar { - width: _, - ref value, - } => { - let name = &self.names[&NameKey::Constant(handle)]; - // First write only constant name - write!(self.out, "const {name}: ")?; - // Next write constant type and value - match *value { - crate::ScalarValue::Sint(value) => { - write!(self.out, "i32 = {value}")?; - } - crate::ScalarValue::Uint(value) => { - write!(self.out, "u32 = {value}u")?; - } - crate::ScalarValue::Float(value) => { - // Floats are written using `Debug` instead of `Display` because it always appends the - // decimal part even it's zero - write!(self.out, "f32 = {value:?}")?; - } - crate::ScalarValue::Bool(value) => { - write!(self.out, "bool = {value}")?; - } - }; - // End with semicolon - writeln!(self.out, ";")?; - } - crate::ConstantInner::Composite { ty, ref components } => { - let name = &self.names[&NameKey::Constant(handle)]; - // First write only constant name - write!(self.out, "const {name}: ")?; - // Next write constant type - self.write_type(module, ty)?; + let name = &self.names[&NameKey::Constant(handle)]; + // First write only constant name + write!(self.out, "const {name}: ")?; + self.write_type(module, module.constants[handle].ty)?; + write!(self.out, " = ")?; + let init = module.constants[handle].init; + self.write_const_expression(module, init)?; + writeln!(self.out, ";")?; - write!(self.out, " = ")?; - self.write_type(module, ty)?; - - write!(self.out, "(")?; - for (index, constant) in components.iter().enumerate() { - self.write_constant(module, *constant)?; - // Only write a comma if isn't the last element - if index != components.len().saturating_sub(1) { - // The leading space is for readability only - write!(self.out, ", ")?; - } - } - write!(self.out, ");")?; - } - } - // End with extra newline for readability - writeln!(self.out)?; Ok(()) } diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 14e223d6a..5a5acf432 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -7,10 +7,9 @@ use super::{ Error, ErrorKind, Frontend, Result, }; use crate::{ - BinaryOperator, Block, Constant, DerivativeAxis as Axis, DerivativeControl as Ctrl, Expression, - Handle, ImageClass, ImageDimension as Dim, ImageQuery, MathFunction, Module, - RelationalFunction, SampleLevel, ScalarKind as Sk, Span, Type, TypeInner, UnaryOperator, - VectorSize, + BinaryOperator, Block, DerivativeAxis as Axis, DerivativeControl as Ctrl, Expression, Handle, + ImageClass, ImageDimension as Dim, ImageQuery, MathFunction, Module, RelationalFunction, + SampleLevel, ScalarKind as Sk, Span, Type, TypeInner, UnaryOperator, VectorSize, }; impl crate::ScalarKind { @@ -2183,7 +2182,7 @@ fn texture_call( image: Handle, level: SampleLevel, comps: CoordComponents, - offset: Option>, + offset: Option>, body: &mut Block, meta: Span, ) -> Result> { diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs index 35569926c..81ec6f3a8 100644 --- a/src/front/glsl/constants.rs +++ b/src/front/glsl/constants.rs @@ -1,6 +1,6 @@ use crate::{ arena::{Arena, Handle, UniqueArena}, - BinaryOperator, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, TypeInner, + ArraySize, BinaryOperator, Constant, Expression, Literal, ScalarKind, Type, TypeInner, UnaryOperator, }; @@ -9,6 +9,7 @@ pub struct ConstantSolver<'a> { pub types: &'a mut UniqueArena, pub expressions: &'a Arena, pub constants: &'a mut Arena, + pub const_expressions: &'a mut Arena, } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -59,34 +60,84 @@ pub enum ConstantSolvingError { SplatScalarOnly, #[error("Can only swizzle vector constants")] SwizzleVectorOnly, + #[error("Type is not constructible")] + TypeNotConstructible, #[error("Not implemented as constant expression: {0}")] NotImplemented(String), } +#[derive(Clone, Copy)] +pub enum ExprType { + Regular, + Constant, +} + impl<'a> ConstantSolver<'a> { pub fn solve( &mut self, expr: Handle, - ) -> Result, ConstantSolvingError> { - let span = self.expressions.get_span(expr); - match self.expressions[expr] { - Expression::Constant(constant) => Ok(constant), - Expression::ZeroValue(ty) => self.register_zero_constant(ty, span), - Expression::Literal(literal) => Ok(self.register_literal(literal, span)), - Expression::AccessIndex { base, index } => self.access(base, index as usize), - Expression::Access { base, index } => { - let index = self.solve(index)?; + ) -> Result, ConstantSolvingError> { + self.solve_impl(expr, ExprType::Regular, true) + } - self.access(base, self.constant_index(index)?) + pub fn solve_impl( + &mut self, + expr: Handle, + expr_type: ExprType, + top_level: bool, + ) -> Result, ConstantSolvingError> { + let expressions = match expr_type { + ExprType::Regular => self.expressions, + ExprType::Constant => self.const_expressions, + }; + let span = expressions.get_span(expr); + match expressions[expr] { + ref expression @ (Expression::Literal(_) | Expression::ZeroValue(_)) => match expr_type + { + ExprType::Regular => Ok(self.register_constant(expression.clone(), span)), + ExprType::Constant => Ok(expr), + }, + Expression::Compose { ty, ref components } => match expr_type { + ExprType::Regular => { + let mut components = components.clone(); + for component in &mut components { + *component = self.solve_impl(*component, expr_type, false)?; + } + Ok(self.register_constant(Expression::Compose { ty, components }, span)) + } + ExprType::Constant => Ok(expr), + }, + Expression::Constant(constant) => { + if top_level { + match expr_type { + ExprType::Regular => { + Ok(self.register_constant(Expression::Constant(constant), span)) + } + ExprType::Constant => Ok(expr), + } + } else { + self.solve_impl(self.constants[constant].init, ExprType::Constant, false) + } + } + Expression::AccessIndex { base, index } => { + let base = self.solve_impl(base, expr_type, false)?; + self.access(base, index as usize, span) + } + Expression::Access { base, index } => { + let base = self.solve_impl(base, expr_type, false)?; + let index = self.solve_impl(index, expr_type, false)?; + + self.access(base, self.constant_index(index)?, span) } Expression::Splat { size, value: splat_value, } => { - let value_constant = self.solve(splat_value)?; - let ty = match self.constants[value_constant].inner { - ConstantInner::Scalar { ref value, width } => { - let kind = value.scalar_kind(); + let value_constant = self.solve_impl(splat_value, expr_type, false)?; + let ty = match self.const_expressions[value_constant] { + Expression::Literal(literal) => { + let kind = literal.scalar_kind(); + let width = literal.width(); self.types.insert( Type { name: None, @@ -95,76 +146,83 @@ impl<'a> ConstantSolver<'a> { span, ) } - ConstantInner::Composite { .. } => { + Expression::ZeroValue(ty) => { + let inner = match self.types[ty].inner { + TypeInner::Scalar { kind, width } => { + TypeInner::Vector { size, kind, width } + } + _ => return Err(ConstantSolvingError::SplatScalarOnly), + }; + let res_ty = self.types.insert(Type { name: None, inner }, span); + let expr = Expression::ZeroValue(res_ty); + return Ok(self.register_constant(expr, span)); + } + _ => { return Err(ConstantSolvingError::SplatScalarOnly); } }; - let inner = ConstantInner::Composite { + let expr = Expression::Compose { ty, components: vec![value_constant; size as usize], }; - Ok(self.register_constant(inner, span)) + Ok(self.register_constant(expr, span)) } Expression::Swizzle { size, vector: src_vector, pattern, } => { - let src_constant = self.solve(src_vector)?; - let (ty, src_components) = match self.constants[src_constant].inner { - ConstantInner::Scalar { .. } => { - return Err(ConstantSolvingError::SwizzleVectorOnly); - } - ConstantInner::Composite { - ty, - components: ref src_components, - } => match self.types[ty].inner { - crate::TypeInner::Vector { - size: _, - kind, - width, - } => { - let dst_ty = self.types.insert( - Type { - name: None, - inner: crate::TypeInner::Vector { size, kind, width }, - }, - span, - ); - (dst_ty, &src_components[..]) - } - _ => { - return Err(ConstantSolvingError::SwizzleVectorOnly); - } - }, + let src_constant = self.solve_impl(src_vector, expr_type, false)?; + + let mut get_dst_ty = |ty| match self.types[ty].inner { + crate::TypeInner::Vector { + size: _, + kind, + width, + } => Ok(self.types.insert( + Type { + name: None, + inner: crate::TypeInner::Vector { size, kind, width }, + }, + span, + )), + _ => Err(ConstantSolvingError::SwizzleVectorOnly), }; - let components = pattern - .iter() - .map(|&sc| src_components[sc as usize]) - .collect(); - let inner = ConstantInner::Composite { ty, components }; + match self.const_expressions[src_constant] { + Expression::ZeroValue(ty) => { + let dst_ty = get_dst_ty(ty)?; + let expr = Expression::ZeroValue(dst_ty); + Ok(self.register_constant(expr, span)) + } + Expression::Compose { + ty, + components: ref src_components, + } => { + let dst_ty = get_dst_ty(ty)?; - Ok(self.register_constant(inner, span)) - } - Expression::Compose { ty, ref components } => { - let components = components - .iter() - .map(|c| self.solve(*c)) - .collect::>()?; - let inner = ConstantInner::Composite { ty, components }; - - Ok(self.register_constant(inner, span)) + let components = pattern + .iter() + .map(|&sc| src_components[sc as usize]) + .collect(); + let expr = Expression::Compose { + ty: dst_ty, + components, + }; + Ok(self.register_constant(expr, span)) + } + _ => Err(ConstantSolvingError::SwizzleVectorOnly), + } } Expression::Unary { expr, op } => { - let expr_constant = self.solve(expr)?; + let expr_constant = self.solve_impl(expr, expr_type, false)?; self.unary_op(op, expr_constant, span) } Expression::Binary { left, right, op } => { - let left_constant = self.solve(left)?; - let right_constant = self.solve(right)?; + let left_constant = self.solve_impl(left, expr_type, false)?; + let right_constant = self.solve_impl(right, expr_type, false)?; self.binary_op(op, left_constant, right_constant, span) } @@ -173,76 +231,61 @@ impl<'a> ConstantSolver<'a> { arg, arg1, arg2, - .. + arg3, } => { - let arg = self.solve(arg)?; - let arg1 = arg1.map(|arg| self.solve(arg)).transpose()?; - let arg2 = arg2.map(|arg| self.solve(arg)).transpose()?; + let arg = self.solve_impl(arg, expr_type, false)?; + let arg1 = arg1 + .map(|arg| self.solve_impl(arg, expr_type, false)) + .transpose()?; + let arg2 = arg2 + .map(|arg| self.solve_impl(arg, expr_type, false)) + .transpose()?; + let arg3 = arg3 + .map(|arg| self.solve_impl(arg, expr_type, false)) + .transpose()?; - let const0 = &self.constants[arg].inner; - let const1 = arg1.map(|arg| &self.constants[arg].inner); - let const2 = arg2.map(|arg| &self.constants[arg].inner); + let const0 = &self.const_expressions[arg]; + let const1 = arg1.map(|arg| &self.const_expressions[arg]); + let const2 = arg2.map(|arg| &self.const_expressions[arg]); + let _const3 = arg3.map(|arg| &self.const_expressions[arg]); match fun { crate::MathFunction::Pow => { - let (value, width) = match (const0, const1.unwrap()) { - ( - &ConstantInner::Scalar { - width, - value: value0, - }, - &ConstantInner::Scalar { value: value1, .. }, - ) => ( + let literal = match (const0, const1.unwrap()) { + (&Expression::Literal(value0), &Expression::Literal(value1)) => { match (value0, value1) { - (ScalarValue::Sint(a), ScalarValue::Sint(b)) => { - ScalarValue::Sint(a.pow(b as u32)) - } - (ScalarValue::Uint(a), ScalarValue::Uint(b)) => { - ScalarValue::Uint(a.pow(b as u32)) - } - (ScalarValue::Float(a), ScalarValue::Float(b)) => { - ScalarValue::Float(a.powf(b)) + (Literal::I32(a), Literal::I32(b)) => { + Literal::I32(a.pow(b as u32)) } + (Literal::U32(a), Literal::U32(b)) => Literal::U32(a.pow(b)), + (Literal::F32(a), Literal::F32(b)) => Literal::F32(a.powf(b)), _ => return Err(ConstantSolvingError::InvalidMathArg), - }, - width, - ), + } + } _ => return Err(ConstantSolvingError::InvalidMathArg), }; - let inner = ConstantInner::Scalar { width, value }; - Ok(self.register_constant(inner, span)) + let expr = Expression::Literal(literal); + Ok(self.register_constant(expr, span)) } crate::MathFunction::Clamp => { - let (value, width) = match (const0, const1.unwrap(), const2.unwrap()) { + let literal = match (const0, const1.unwrap(), const2.unwrap()) { ( - &ConstantInner::Scalar { - width, - value: value0, - }, - &ConstantInner::Scalar { value: value1, .. }, - &ConstantInner::Scalar { value: value2, .. }, - ) => ( - match (value0, value1, value2) { - ( - ScalarValue::Sint(a), - ScalarValue::Sint(b), - ScalarValue::Sint(c), - ) => ScalarValue::Sint(a.clamp(b, c)), - ( - ScalarValue::Uint(a), - ScalarValue::Uint(b), - ScalarValue::Uint(c), - ) => ScalarValue::Uint(a.clamp(b, c)), - ( - ScalarValue::Float(a), - ScalarValue::Float(b), - ScalarValue::Float(c), - ) => ScalarValue::Float(glsl_float_clamp(a, b, c)), - _ => return Err(ConstantSolvingError::InvalidMathArg), - }, - width, - ), + &Expression::Literal(value0), + &Expression::Literal(value1), + &Expression::Literal(value2), + ) => match (value0, value1, value2) { + (Literal::I32(a), Literal::I32(b), Literal::I32(c)) => { + Literal::I32(a.clamp(b, c)) + } + (Literal::U32(a), Literal::U32(b), Literal::U32(c)) => { + Literal::U32(a.clamp(b, c)) + } + (Literal::F32(a), Literal::F32(b), Literal::F32(c)) => { + Literal::F32(glsl_float_clamp(a, b, c)) + } + _ => return Err(ConstantSolvingError::InvalidMathArg), + }, _ => { return Err(ConstantSolvingError::NotImplemented(format!( "{fun:?} applied to vector values" @@ -250,8 +293,8 @@ impl<'a> ConstantSolver<'a> { } }; - let inner = ConstantInner::Scalar { width, value }; - Ok(self.register_constant(inner, span)) + let expr = Expression::Literal(literal); + Ok(self.register_constant(expr, span)) } _ => Err(ConstantSolvingError::NotImplemented(format!("{fun:?}"))), } @@ -261,7 +304,7 @@ impl<'a> ConstantSolver<'a> { expr, kind, } => { - let expr_constant = self.solve(expr)?; + let expr_constant = self.solve_impl(expr, expr_type, false)?; match convert { Some(width) => self.cast(expr_constant, kind, width, span), @@ -269,27 +312,24 @@ impl<'a> ConstantSolver<'a> { } } Expression::ArrayLength(expr) => { - let array = self.solve(expr)?; + let array = self.solve_impl(expr, expr_type, false)?; - match self.constants[array].inner { - ConstantInner::Scalar { .. } => { - Err(ConstantSolvingError::InvalidArrayLengthArg) + match self.const_expressions[array] { + Expression::ZeroValue(ty) | Expression::Compose { ty, .. } => { + match self.types[ty].inner { + TypeInner::Array { size, .. } => match size { + crate::ArraySize::Constant(len) => { + let expr = Expression::Literal(Literal::U32(len.get())); + Ok(self.register_constant(expr, span)) + } + crate::ArraySize::Dynamic => { + Err(ConstantSolvingError::ArrayLengthDynamic) + } + }, + _ => Err(ConstantSolvingError::InvalidArrayLengthArg), + } } - ConstantInner::Composite { ty, .. } => match self.types[ty].inner { - TypeInner::Array { size, .. } => match size { - crate::ArraySize::Constant(size) => Ok(self.register_constant( - ConstantInner::Scalar { - width: 4, - value: ScalarValue::Uint(size.get() as u64), - }, - span, - )), - crate::ArraySize::Dynamic => { - Err(ConstantSolvingError::ArrayLengthDynamic) - } - }, - _ => Err(ConstantSolvingError::InvalidArrayLengthArg), - }, + _ => Err(ConstantSolvingError::InvalidArrayLengthArg), } } @@ -316,281 +356,97 @@ impl<'a> ConstantSolver<'a> { &mut self, base: Handle, index: usize, - ) -> Result, ConstantSolvingError> { - let base = self.solve(base)?; + span: crate::Span, + ) -> Result, ConstantSolvingError> { + match self.const_expressions[base] { + Expression::ZeroValue(ty) => { + let ty_inner = &self.types[ty].inner; + let components = ty_inner + .components() + .ok_or(ConstantSolvingError::InvalidAccessBase)?; - match self.constants[base].inner { - ConstantInner::Scalar { .. } => Err(ConstantSolvingError::InvalidAccessBase), - ConstantInner::Composite { ty, ref components } => { - match self.types[ty].inner { - TypeInner::Vector { .. } - | TypeInner::Matrix { .. } - | TypeInner::Array { .. } - | TypeInner::Struct { .. } => (), - _ => return Err(ConstantSolvingError::InvalidAccessBase), + if index >= components as usize { + Err(ConstantSolvingError::InvalidAccessBase) + } else { + let ty_res = ty_inner + .component_type(index) + .ok_or(ConstantSolvingError::InvalidAccessIndex)?; + let ty = match ty_res { + crate::proc::TypeResolution::Handle(ty) => ty, + crate::proc::TypeResolution::Value(inner) => { + self.types.insert(Type { name: None, inner }, span) + } + }; + Ok(self.register_constant(Expression::ZeroValue(ty), span)) } + } + Expression::Compose { ty, ref components } => { + let _ = self.types[ty] + .inner + .components() + .ok_or(ConstantSolvingError::InvalidAccessBase)?; components .get(index) .copied() .ok_or(ConstantSolvingError::InvalidAccessIndex) } + _ => Err(ConstantSolvingError::InvalidAccessBase), } } - fn constant_index(&self, constant: Handle) -> Result { - match self.constants[constant].inner { - ConstantInner::Scalar { - value: ScalarValue::Uint(index), - .. - } => Ok(index as usize), + fn constant_index(&self, expr: Handle) -> Result { + match self.const_expressions[expr] { + Expression::Literal(Literal::U32(index)) => Ok(index as usize), _ => Err(ConstantSolvingError::InvalidAccessIndexTy), } } - fn cast( + /// Transforms a `Expression::ZeroValue` into either `Expression::Literal` or `Expression::Compose` + fn eval_zero_value( &mut self, - constant: Handle, - kind: ScalarKind, - target_width: crate::Bytes, + expr: Handle, span: crate::Span, - ) -> Result, ConstantSolvingError> { - let mut inner = self.constants[constant].inner.clone(); - - match inner { - ConstantInner::Scalar { - ref mut value, - ref mut width, - } => { - *width = target_width; - *value = match kind { - ScalarKind::Sint => ScalarValue::Sint(match *value { - ScalarValue::Sint(v) => v, - ScalarValue::Uint(v) => v as i64, - ScalarValue::Float(v) => v as i64, - ScalarValue::Bool(v) => v as i64, - }), - ScalarKind::Uint => ScalarValue::Uint(match *value { - ScalarValue::Sint(v) => v as u64, - ScalarValue::Uint(v) => v, - ScalarValue::Float(v) => v as u64, - ScalarValue::Bool(v) => v as u64, - }), - ScalarKind::Float => ScalarValue::Float(match *value { - ScalarValue::Sint(v) => v as f64, - ScalarValue::Uint(v) => v as f64, - ScalarValue::Float(v) => v, - ScalarValue::Bool(v) => v as u64 as f64, - }), - ScalarKind::Bool => ScalarValue::Bool(match *value { - ScalarValue::Sint(v) => v != 0, - ScalarValue::Uint(v) => v != 0, - ScalarValue::Float(v) => v != 0.0, - ScalarValue::Bool(v) => v, - }), - } - } - ConstantInner::Composite { - ty, - ref mut components, - } => { - match self.types[ty].inner { - TypeInner::Vector { .. } | TypeInner::Matrix { .. } => (), - _ => return Err(ConstantSolvingError::InvalidCastArg), - } - - for component in components { - *component = self.cast(*component, kind, target_width, span)?; - } - } + ) -> Result, ConstantSolvingError> { + match self.const_expressions[expr] { + Expression::ZeroValue(ty) => self.eval_zero_value_impl(ty, span), + _ => Ok(expr), } - - Ok(self.register_constant(inner, span)) } - fn unary_op( - &mut self, - op: UnaryOperator, - constant: Handle, - span: crate::Span, - ) -> Result, ConstantSolvingError> { - let mut inner = self.constants[constant].inner.clone(); - - match inner { - ConstantInner::Scalar { ref mut value, .. } => match op { - UnaryOperator::Negate => match *value { - ScalarValue::Sint(ref mut v) => *v = -*v, - ScalarValue::Float(ref mut v) => *v = -*v, - _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), - }, - UnaryOperator::Not => match *value { - ScalarValue::Sint(ref mut v) => *v = !*v, - ScalarValue::Uint(ref mut v) => *v = !*v, - ScalarValue::Bool(ref mut v) => *v = !*v, - ScalarValue::Float(_) => return Err(ConstantSolvingError::InvalidUnaryOpArg), - }, - }, - ConstantInner::Composite { - ty, - ref mut components, - } => { - match self.types[ty].inner { - TypeInner::Vector { .. } | TypeInner::Matrix { .. } => (), - _ => return Err(ConstantSolvingError::InvalidCastArg), - } - - for component in components { - *component = self.unary_op(op, *component, span)? - } - } - } - - Ok(self.register_constant(inner, span)) - } - - fn binary_op( - &mut self, - op: BinaryOperator, - left: Handle, - right: Handle, - span: crate::Span, - ) -> Result, ConstantSolvingError> { - let left_inner = &self.constants[left].inner; - let right_inner = &self.constants[right].inner; - - let inner = match (left_inner, right_inner) { - ( - &ConstantInner::Scalar { - value: left_value, - width, - }, - &ConstantInner::Scalar { - value: right_value, - width: _, - }, - ) => { - let value = match op { - BinaryOperator::Equal => ScalarValue::Bool(left_value == right_value), - BinaryOperator::NotEqual => ScalarValue::Bool(left_value != right_value), - BinaryOperator::Less => ScalarValue::Bool(left_value < right_value), - BinaryOperator::LessEqual => ScalarValue::Bool(left_value <= right_value), - BinaryOperator::Greater => ScalarValue::Bool(left_value > right_value), - BinaryOperator::GreaterEqual => ScalarValue::Bool(left_value >= right_value), - - _ => match (left_value, right_value) { - (ScalarValue::Sint(a), ScalarValue::Sint(b)) => { - ScalarValue::Sint(match op { - BinaryOperator::Add => a.wrapping_add(b), - BinaryOperator::Subtract => a.wrapping_sub(b), - BinaryOperator::Multiply => a.wrapping_mul(b), - BinaryOperator::Divide => a.checked_div(b).unwrap_or(0), - BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0), - BinaryOperator::And => a & b, - BinaryOperator::ExclusiveOr => a ^ b, - BinaryOperator::InclusiveOr => a | b, - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), - }) - } - (ScalarValue::Sint(a), ScalarValue::Uint(b)) => { - ScalarValue::Sint(match op { - BinaryOperator::ShiftLeft => a.wrapping_shl(b as u32), - BinaryOperator::ShiftRight => a.wrapping_shr(b as u32), - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), - }) - } - (ScalarValue::Uint(a), ScalarValue::Uint(b)) => { - ScalarValue::Uint(match op { - BinaryOperator::Add => a.wrapping_add(b), - BinaryOperator::Subtract => a.wrapping_sub(b), - BinaryOperator::Multiply => a.wrapping_mul(b), - BinaryOperator::Divide => a.checked_div(b).unwrap_or(0), - BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0), - BinaryOperator::And => a & b, - BinaryOperator::ExclusiveOr => a ^ b, - BinaryOperator::InclusiveOr => a | b, - BinaryOperator::ShiftLeft => a.wrapping_shl(b as u32), - BinaryOperator::ShiftRight => a.wrapping_shr(b as u32), - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), - }) - } - (ScalarValue::Float(a), ScalarValue::Float(b)) => { - ScalarValue::Float(match op { - BinaryOperator::Add => a + b, - BinaryOperator::Subtract => a - b, - BinaryOperator::Multiply => a * b, - BinaryOperator::Divide => a / b, - BinaryOperator::Modulo => a - b * (a / b).floor(), - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), - }) - } - (ScalarValue::Bool(a), ScalarValue::Bool(b)) => { - ScalarValue::Bool(match op { - BinaryOperator::LogicalAnd => a && b, - BinaryOperator::LogicalOr => a || b, - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), - }) - } - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), - }, - }; - - ConstantInner::Scalar { value, width } - } - (&ConstantInner::Composite { ref components, ty }, &ConstantInner::Scalar { .. }) => { - let mut components = components.clone(); - for comp in components.iter_mut() { - *comp = self.binary_op(op, *comp, right, span)?; - } - ConstantInner::Composite { ty, components } - } - (&ConstantInner::Scalar { .. }, &ConstantInner::Composite { ref components, ty }) => { - let mut components = components.clone(); - for comp in components.iter_mut() { - *comp = self.binary_op(op, left, *comp, span)?; - } - ConstantInner::Composite { ty, components } - } - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), - }; - - Ok(self.register_constant(inner, span)) - } - - fn register_zero_constant( + fn eval_zero_value_impl( &mut self, ty: Handle, span: crate::Span, - ) -> Result, ConstantSolvingError> { - let inner = match self.types[ty].inner { + ) -> Result, ConstantSolvingError> { + match self.types[ty].inner { TypeInner::Scalar { kind, width } => { - let value = match kind { - ScalarKind::Sint => ScalarValue::Sint(0), - ScalarKind::Uint => ScalarValue::Uint(0), - ScalarKind::Float => ScalarValue::Float(1.0), - ScalarKind::Bool => ScalarValue::Bool(false), - }; - ConstantInner::Scalar { width, value } + let expr = Expression::Literal( + Literal::zero(kind, width).ok_or(ConstantSolvingError::TypeNotConstructible)?, + ); + Ok(self.register_constant(expr, span)) } TypeInner::Vector { size, kind, width } => { - let element_type = self.types.insert( + let scalar_ty = self.types.insert( Type { name: None, inner: TypeInner::Scalar { kind, width }, }, span, ); - let element = self.register_zero_constant(element_type, span)?; - let components = std::iter::repeat(element) - .take(size as u8 as usize) - .collect(); - ConstantInner::Composite { ty, components } + let el = self.eval_zero_value_impl(scalar_ty, span)?; + let expr = Expression::Compose { + ty, + components: vec![el; size as usize], + }; + Ok(self.register_constant(expr, span)) } TypeInner::Matrix { columns, rows, width, } => { - let column_type = self.types.insert( + let vec_ty = self.types.insert( Type { name: None, inner: TypeInner::Vector { @@ -601,65 +457,253 @@ impl<'a> ConstantSolver<'a> { }, span, ); - let column = self.register_zero_constant(column_type, span)?; - let components = std::iter::repeat(column) - .take(columns as u8 as usize) - .collect(); - ConstantInner::Composite { ty, components } - } - TypeInner::Array { base, size, .. } => { - let length = match size { - crate::ArraySize::Constant(size) => size.get(), - crate::ArraySize::Dynamic => { - return Err(ConstantSolvingError::ArrayLengthDynamic) - } + let el = self.eval_zero_value_impl(vec_ty, span)?; + let expr = Expression::Compose { + ty, + components: vec![el; columns as usize], }; - let element = self.register_zero_constant(base, span)?; - let components = std::iter::repeat(element).take(length as usize).collect(); - ConstantInner::Composite { ty, components } + Ok(self.register_constant(expr, span)) + } + TypeInner::Array { + base, + size: ArraySize::Constant(size), + .. + } => { + let el = self.eval_zero_value_impl(base, span)?; + let expr = Expression::Compose { + ty, + components: vec![el; size.get() as usize], + }; + Ok(self.register_constant(expr, span)) } TypeInner::Struct { ref members, .. } => { - // Make a copy of the member types, for the borrow checker. - let types: Vec> = members.iter().map(|member| member.ty).collect(); - let mut components = vec![]; - for member_ty in types { - let value = self.register_zero_constant(member_ty, span)?; - components.push(value); + let types: Vec<_> = members.iter().map(|m| m.ty).collect(); + let mut components = Vec::with_capacity(members.len()); + for ty in types { + components.push(self.eval_zero_value_impl(ty, span)?); } - ConstantInner::Composite { ty, components } + let expr = Expression::Compose { ty, components }; + Ok(self.register_constant(expr, span)) } - ref inner => { - return Err(ConstantSolvingError::NotImplemented(format!( - "zero-value construction for types: {:?}", - inner - ))); - } - }; - - Ok(self.register_constant(inner, span)) + _ => Err(ConstantSolvingError::TypeNotConstructible), + } } - fn register_literal(&mut self, literal: crate::Literal, span: crate::Span) -> Handle { - let (width, value) = match literal { - crate::Literal::F64(n) => (8, ScalarValue::Float(n)), - crate::Literal::F32(n) => (4, ScalarValue::Float(n as f64)), - crate::Literal::U32(n) => (4, ScalarValue::Uint(n as u64)), - crate::Literal::I32(n) => (4, ScalarValue::Sint(n as i64)), - crate::Literal::Bool(b) => (1, ScalarValue::Bool(b)), + fn cast( + &mut self, + expr: Handle, + kind: ScalarKind, + target_width: crate::Bytes, + span: crate::Span, + ) -> Result, ConstantSolvingError> { + let expr = self.eval_zero_value(expr, span)?; + + let expr = match self.const_expressions[expr] { + Expression::Literal(literal) => { + let literal = match (kind, target_width) { + (ScalarKind::Sint, 4) => Literal::I32(match literal { + Literal::I32(v) => v, + Literal::U32(v) => v as i32, + Literal::F32(v) => v as i32, + Literal::Bool(v) => v as i32, + Literal::F64(_) => return Err(ConstantSolvingError::InvalidCastArg), + }), + (ScalarKind::Uint, 4) => Literal::U32(match literal { + Literal::I32(v) => v as u32, + Literal::U32(v) => v, + Literal::F32(v) => v as u32, + Literal::Bool(v) => v as u32, + Literal::F64(_) => return Err(ConstantSolvingError::InvalidCastArg), + }), + (ScalarKind::Float, 4) => Literal::F32(match literal { + Literal::I32(v) => v as f32, + Literal::U32(v) => v as f32, + Literal::F32(v) => v, + Literal::Bool(v) => v as u32 as f32, + Literal::F64(_) => return Err(ConstantSolvingError::InvalidCastArg), + }), + (ScalarKind::Bool, crate::BOOL_WIDTH) => Literal::Bool(match literal { + Literal::I32(v) => v != 0, + Literal::U32(v) => v != 0, + Literal::F32(v) => v != 0.0, + Literal::Bool(v) => v, + Literal::F64(_) => return Err(ConstantSolvingError::InvalidCastArg), + }), + _ => return Err(ConstantSolvingError::InvalidCastArg), + }; + Expression::Literal(literal) + } + Expression::Compose { + ty, + components: ref src_components, + } => { + match self.types[ty].inner { + TypeInner::Vector { .. } | TypeInner::Matrix { .. } => (), + _ => return Err(ConstantSolvingError::InvalidCastArg), + } + + let mut components = src_components.clone(); + for component in &mut components { + *component = self.cast(*component, kind, target_width, span)?; + } + + Expression::Compose { ty, components } + } + _ => return Err(ConstantSolvingError::InvalidCastArg), }; - self.register_constant(ConstantInner::Scalar { width, value }, span) + Ok(self.register_constant(expr, span)) } - fn register_constant(&mut self, inner: ConstantInner, span: crate::Span) -> Handle { - self.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner, - }, - span, - ) + fn unary_op( + &mut self, + op: UnaryOperator, + expr: Handle, + span: crate::Span, + ) -> Result, ConstantSolvingError> { + let expr = self.eval_zero_value(expr, span)?; + + let expr = match self.const_expressions[expr] { + Expression::Literal(value) => Expression::Literal(match op { + UnaryOperator::Negate => match value { + Literal::I32(v) => Literal::I32(-v), + Literal::F32(v) => Literal::F32(-v), + _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + }, + UnaryOperator::Not => match value { + Literal::I32(v) => Literal::I32(!v), + Literal::U32(v) => Literal::U32(!v), + Literal::Bool(v) => Literal::Bool(!v), + _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + }, + }), + Expression::Compose { + ty, + components: ref src_components, + } => { + match self.types[ty].inner { + TypeInner::Vector { .. } | TypeInner::Matrix { .. } => (), + _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + } + + let mut components = src_components.clone(); + for component in &mut components { + *component = self.unary_op(op, *component, span)?; + } + + Expression::Compose { ty, components } + } + _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + }; + + Ok(self.register_constant(expr, span)) + } + + fn binary_op( + &mut self, + op: BinaryOperator, + left: Handle, + right: Handle, + span: crate::Span, + ) -> Result, ConstantSolvingError> { + let left = self.eval_zero_value(left, span)?; + let right = self.eval_zero_value(right, span)?; + + let expr = match ( + &self.const_expressions[left], + &self.const_expressions[right], + ) { + (&Expression::Literal(left_value), &Expression::Literal(right_value)) => { + let literal = match op { + BinaryOperator::Equal => Literal::Bool(left_value == right_value), + BinaryOperator::NotEqual => Literal::Bool(left_value != right_value), + BinaryOperator::Less => Literal::Bool(left_value < right_value), + BinaryOperator::LessEqual => Literal::Bool(left_value <= right_value), + BinaryOperator::Greater => Literal::Bool(left_value > right_value), + BinaryOperator::GreaterEqual => Literal::Bool(left_value >= right_value), + + _ => match (left_value, right_value) { + (Literal::I32(a), Literal::I32(b)) => Literal::I32(match op { + BinaryOperator::Add => a.wrapping_add(b), + BinaryOperator::Subtract => a.wrapping_sub(b), + BinaryOperator::Multiply => a.wrapping_mul(b), + BinaryOperator::Divide => a.checked_div(b).unwrap_or(0), + BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0), + BinaryOperator::And => a & b, + BinaryOperator::ExclusiveOr => a ^ b, + BinaryOperator::InclusiveOr => a | b, + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }), + (Literal::I32(a), Literal::U32(b)) => Literal::I32(match op { + BinaryOperator::ShiftLeft => a.wrapping_shl(b), + BinaryOperator::ShiftRight => a.wrapping_shr(b), + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }), + (Literal::U32(a), Literal::U32(b)) => Literal::U32(match op { + BinaryOperator::Add => a.wrapping_add(b), + BinaryOperator::Subtract => a.wrapping_sub(b), + BinaryOperator::Multiply => a.wrapping_mul(b), + BinaryOperator::Divide => a.checked_div(b).unwrap_or(0), + BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0), + BinaryOperator::And => a & b, + BinaryOperator::ExclusiveOr => a ^ b, + BinaryOperator::InclusiveOr => a | b, + BinaryOperator::ShiftLeft => a.wrapping_shl(b), + BinaryOperator::ShiftRight => a.wrapping_shr(b), + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }), + (Literal::F32(a), Literal::F32(b)) => Literal::F32(match op { + BinaryOperator::Add => a + b, + BinaryOperator::Subtract => a - b, + BinaryOperator::Multiply => a * b, + BinaryOperator::Divide => a / b, + BinaryOperator::Modulo => a - b * (a / b).floor(), + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }), + (Literal::Bool(a), Literal::Bool(b)) => Literal::Bool(match op { + BinaryOperator::LogicalAnd => a && b, + BinaryOperator::LogicalOr => a || b, + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }), + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }, + }; + Expression::Literal(literal) + } + ( + &Expression::Compose { + components: ref src_components, + ty, + }, + &Expression::Literal(_), + ) => { + let mut components = src_components.clone(); + for component in &mut components { + *component = self.binary_op(op, *component, right, span)?; + } + Expression::Compose { ty, components } + } + ( + &Expression::Literal(_), + &Expression::Compose { + components: ref src_components, + ty, + }, + ) => { + let mut components = src_components.clone(); + for component in &mut components { + *component = self.binary_op(op, left, *component, span)?; + } + Expression::Compose { ty, components } + } + _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + }; + + Ok(self.register_constant(expr, span)) + } + + fn register_constant(&mut self, expr: Expression, span: crate::Span) -> Handle { + self.const_expressions.append(expr, span) } } @@ -676,7 +720,7 @@ impl<'a> ConstantSolver<'a> { /// ``` /// /// Rust will return `1.0` while GLSL should return NaN. -fn glsl_float_max(x: f64, y: f64) -> f64 { +fn glsl_float_max(x: f32, y: f32) -> f32 { if x < y { y } else { @@ -697,7 +741,7 @@ fn glsl_float_max(x: f64, y: f64) -> f64 { /// ``` /// /// Rust will return `1.0` while GLSL should return NaN. -fn glsl_float_min(x: f64, y: f64) -> f64 { +fn glsl_float_min(x: f32, y: f32) -> f32 { if y < x { y } else { @@ -710,7 +754,7 @@ fn glsl_float_min(x: f64, y: f64) -> f64 { /// While Rust does provide a `f64::clamp` method, it panics if either /// `min` or `max` are `NaN`s which is not the behavior specified by /// the glsl specification. -fn glsl_float_clamp(value: f64, min: f64, max: f64) -> f64 { +fn glsl_float_clamp(value: f32, min: f32, max: f32) -> f32 { glsl_float_min(glsl_float_max(value, min), max) } @@ -719,23 +763,23 @@ mod tests { use std::vec; use crate::{ - Arena, Constant, ConstantInner, Expression, ScalarKind, ScalarValue, Type, TypeInner, - UnaryOperator, UniqueArena, VectorSize, + Arena, Constant, Expression, Literal, ScalarKind, Type, TypeInner, UnaryOperator, + UniqueArena, VectorSize, }; use super::ConstantSolver; #[test] fn nan_handling() { - assert!(super::glsl_float_max(f64::NAN, 2.0).is_nan()); - assert!(!super::glsl_float_max(2.0, f64::NAN).is_nan()); + assert!(super::glsl_float_max(f32::NAN, 2.0).is_nan()); + assert!(!super::glsl_float_max(2.0, f32::NAN).is_nan()); - assert!(super::glsl_float_min(f64::NAN, 2.0).is_nan()); - assert!(!super::glsl_float_min(2.0, f64::NAN).is_nan()); + assert!(super::glsl_float_min(f32::NAN, 2.0).is_nan()); + assert!(!super::glsl_float_min(2.0, f32::NAN).is_nan()); - assert!(super::glsl_float_clamp(f64::NAN, 1.0, 2.0).is_nan()); - assert!(!super::glsl_float_clamp(1.0, f64::NAN, 2.0).is_nan()); - assert!(!super::glsl_float_clamp(1.0, 2.0, f64::NAN).is_nan()); + assert!(super::glsl_float_clamp(f32::NAN, 1.0, 2.0).is_nan()); + assert!(!super::glsl_float_clamp(1.0, f32::NAN, 2.0).is_nan()); + assert!(!super::glsl_float_clamp(1.0, 2.0, f32::NAN).is_nan()); } #[test] @@ -743,6 +787,18 @@ mod tests { let mut types = UniqueArena::new(); let mut expressions = Arena::new(); let mut constants = Arena::new(); + let mut const_expressions = Arena::new(); + + let scalar_ty = types.insert( + Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + }, + Default::default(), + ); let vec_ty = types.insert( Type { @@ -759,11 +815,10 @@ mod tests { let h = constants.append( Constant { name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(4), - }, + r#override: crate::Override::None, + ty: scalar_ty, + init: const_expressions + .append(Expression::Literal(Literal::I32(4)), Default::default()), }, Default::default(), ); @@ -771,11 +826,10 @@ mod tests { let h1 = constants.append( Constant { name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(8), - }, + r#override: crate::Override::None, + ty: scalar_ty, + init: const_expressions + .append(Expression::Literal(Literal::I32(8)), Default::default()), }, Default::default(), ); @@ -783,11 +837,15 @@ mod tests { let vec_h = constants.append( Constant { name: None, - specialization: None, - inner: ConstantInner::Composite { - ty: vec_ty, - components: vec![h, h1], - }, + r#override: crate::Override::None, + ty: vec_ty, + init: const_expressions.append( + Expression::Compose { + ty: vec_ty, + components: vec![constants[h].init, constants[h1].init], + }, + Default::default(), + ), }, Default::default(), ); @@ -823,6 +881,7 @@ mod tests { types: &mut types, expressions: &expressions, constants: &mut constants, + const_expressions: &mut const_expressions, }; let res1 = solver.solve(root1).unwrap(); @@ -830,43 +889,31 @@ mod tests { let res3 = solver.solve(root3).unwrap(); assert_eq!( - constants[res1].inner, - ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(-4), - }, + const_expressions[res1], + Expression::Literal(Literal::I32(-4)) ); assert_eq!( - constants[res2].inner, - ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(!4), - }, + const_expressions[res2], + Expression::Literal(Literal::I32(!4)) ); - let res3_inner = &constants[res3].inner; + let res3_inner = &const_expressions[res3]; match *res3_inner { - ConstantInner::Composite { + Expression::Compose { ref ty, ref components, } => { assert_eq!(*ty, vec_ty); let mut components_iter = components.iter().copied(); assert_eq!( - constants[components_iter.next().unwrap()].inner, - ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(!4), - }, + const_expressions[components_iter.next().unwrap()], + Expression::Literal(Literal::I32(!4)) ); assert_eq!( - constants[components_iter.next().unwrap()].inner, - ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(!8), - }, + const_expressions[components_iter.next().unwrap()], + Expression::Literal(Literal::I32(!8)) ); assert!(components_iter.next().is_none()); } @@ -876,17 +923,29 @@ mod tests { #[test] fn cast() { + let mut types = UniqueArena::new(); let mut expressions = Arena::new(); let mut constants = Arena::new(); + let mut const_expressions = Arena::new(); + + let scalar_ty = types.insert( + Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + }, + Default::default(), + ); let h = constants.append( Constant { name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Sint(4), - }, + r#override: crate::Override::None, + ty: scalar_ty, + init: const_expressions + .append(Expression::Literal(Literal::I32(4)), Default::default()), }, Default::default(), ); @@ -903,19 +962,17 @@ mod tests { ); let mut solver = ConstantSolver { - types: &mut UniqueArena::new(), + types: &mut types, expressions: &expressions, constants: &mut constants, + const_expressions: &mut const_expressions, }; let res = solver.solve(root).unwrap(); assert_eq!( - constants[res].inner, - ConstantInner::Scalar { - width: crate::BOOL_WIDTH, - value: ScalarValue::Bool(true), - }, + const_expressions[res], + Expression::Literal(Literal::Bool(true)) ); } @@ -924,6 +981,7 @@ mod tests { let mut types = UniqueArena::new(); let mut expressions = Arena::new(); let mut constants = Arena::new(); + let mut const_expressions = Arena::new(); let matrix_ty = types.insert( Type { @@ -953,15 +1011,8 @@ mod tests { let mut vec2_components = Vec::with_capacity(3); for i in 0..3 { - let h = constants.append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(i as f64), - }, - }, + let h = const_expressions.append( + Expression::Literal(Literal::F32(i as f32)), Default::default(), ); @@ -969,15 +1020,8 @@ mod tests { } for i in 3..6 { - let h = constants.append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(i as f64), - }, - }, + let h = const_expressions.append( + Expression::Literal(Literal::F32(i as f32)), Default::default(), ); @@ -987,11 +1031,15 @@ mod tests { let vec1 = constants.append( Constant { name: None, - specialization: None, - inner: ConstantInner::Composite { - ty: vec_ty, - components: vec1_components, - }, + r#override: crate::Override::None, + ty: vec_ty, + init: const_expressions.append( + Expression::Compose { + ty: vec_ty, + components: vec1_components, + }, + Default::default(), + ), }, Default::default(), ); @@ -999,11 +1047,15 @@ mod tests { let vec2 = constants.append( Constant { name: None, - specialization: None, - inner: ConstantInner::Composite { - ty: vec_ty, - components: vec2_components, - }, + r#override: crate::Override::None, + ty: vec_ty, + init: const_expressions.append( + Expression::Compose { + ty: vec_ty, + components: vec2_components, + }, + Default::default(), + ), }, Default::default(), ); @@ -1011,11 +1063,15 @@ mod tests { let h = constants.append( Constant { name: None, - specialization: None, - inner: ConstantInner::Composite { - ty: matrix_ty, - components: vec![vec1, vec2], - }, + r#override: crate::Override::None, + ty: matrix_ty, + init: const_expressions.append( + Expression::Compose { + ty: matrix_ty, + components: vec![constants[vec1].init, constants[vec2].init], + }, + Default::default(), + ), }, Default::default(), ); @@ -1037,40 +1093,30 @@ mod tests { types: &mut types, expressions: &expressions, constants: &mut constants, + const_expressions: &mut const_expressions, }; let res1 = solver.solve(root1).unwrap(); let res2 = solver.solve(root2).unwrap(); - let res1_inner = &constants[res1].inner; - - match *res1_inner { - ConstantInner::Composite { + match const_expressions[res1] { + Expression::Compose { ref ty, ref components, } => { assert_eq!(*ty, vec_ty); let mut components_iter = components.iter().copied(); assert_eq!( - constants[components_iter.next().unwrap()].inner, - ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(3.), - }, + const_expressions[components_iter.next().unwrap()], + Expression::Literal(Literal::F32(3.)) ); assert_eq!( - constants[components_iter.next().unwrap()].inner, - ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(4.), - }, + const_expressions[components_iter.next().unwrap()], + Expression::Literal(Literal::F32(4.)) ); assert_eq!( - constants[components_iter.next().unwrap()].inner, - ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(5.), - }, + const_expressions[components_iter.next().unwrap()], + Expression::Literal(Literal::F32(5.)) ); assert!(components_iter.next().is_none()); } @@ -1078,11 +1124,8 @@ mod tests { } assert_eq!( - constants[res2].inner, - ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(5.), - }, + const_expressions[res2], + Expression::Literal(Literal::F32(5.)) ); } } diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 93b7e03b6..e16dc125e 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -10,10 +10,10 @@ use super::{ use crate::{ front::{Emitter, Typifier}, AddressSpace, Arena, BinaryOperator, Block, Expression, FastHashMap, FunctionArgument, Handle, - Literal, LocalVariable, RelationalFunction, ScalarKind, ScalarValue, Span, Statement, Type, - TypeInner, VectorSize, + Literal, LocalVariable, RelationalFunction, ScalarKind, Span, Statement, Type, TypeInner, + VectorSize, }; -use std::{convert::TryFrom, ops::Index}; +use std::ops::Index; /// The position at which an expression is, used while lowering #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -519,21 +519,12 @@ impl Context { .0; let pointer = maybe_constant_index - .and_then(|constant| { + .and_then(|const_expr| { Some(self.add_expression( Expression::AccessIndex { base, - index: match frontend.module.constants[constant].inner { - crate::ConstantInner::Scalar { - value: ScalarValue::Uint(i), - .. - } => u32::try_from(i).ok()?, - crate::ConstantInner::Scalar { - value: ScalarValue::Sint(i), - .. - } => u32::try_from(i).ok()?, - _ => return None, - }, + index: + frontend.module.to_ctx().eval_expr_to_u32(const_expr).ok()?, }, meta, body, @@ -1039,14 +1030,18 @@ impl Context { // pointer type which is required for dynamic indexing if !constant_index { if let Some((constant, ty)) = var.constant { - let local = self.locals.append( - LocalVariable { - name: None, - ty, - init: Some(constant), - }, - Span::default(), - ); + let local = + self.locals.append( + LocalVariable { + name: None, + ty, + init: Some(frontend.module.const_expressions.append( + Expression::Constant(constant), + Span::default(), + )), + }, + Span::default(), + ); self.add_expression( Expression::LocalVariable(local), diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index b7b4be8a6..f44827258 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -8,8 +8,8 @@ use super::{ }; use crate::{ front::glsl::types::type_power, proc::ensure_block_returns, AddressSpace, Arena, Block, - Constant, ConstantInner, EntryPoint, Expression, Function, FunctionArgument, FunctionResult, - Handle, LocalVariable, ScalarKind, ScalarValue, Span, Statement, StructMember, Type, TypeInner, + EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, Literal, + LocalVariable, ScalarKind, Span, Statement, StructMember, Type, TypeInner, }; use std::iter; @@ -24,29 +24,6 @@ struct ProxyWrite { } impl Frontend { - fn add_constant_value( - &mut self, - scalar_kind: ScalarKind, - value: u64, - meta: Span, - ) -> Handle { - let value = match scalar_kind { - ScalarKind::Uint => ScalarValue::Uint(value), - ScalarKind::Sint => ScalarValue::Sint(value as i64), - ScalarKind::Float => ScalarValue::Float(value as f64), - ScalarKind::Bool => unreachable!(), - }; - - self.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { width: 4, value }, - }, - meta, - ) - } - pub(crate) fn function_or_constructor_call( &mut self, ctx: &mut Context, @@ -97,10 +74,10 @@ impl Frontend { if expr_type.scalar_kind() == Some(ScalarKind::Bool) && result_scalar_kind != ScalarKind::Bool => { - let c0 = self.add_constant_value(result_scalar_kind, 0u64, meta); - let c1 = self.add_constant_value(result_scalar_kind, 1u64, meta); - let mut reject = ctx.add_expression(Expression::Constant(c0), expr_meta, body); - let mut accept = ctx.add_expression(Expression::Constant(c1), expr_meta, body); + let l0 = Literal::zero(result_scalar_kind, 4).unwrap(); + let l1 = Literal::one(result_scalar_kind, 4).unwrap(); + let mut reject = ctx.add_expression(Expression::Literal(l0), expr_meta, body); + let mut accept = ctx.add_expression(Expression::Literal(l1), expr_meta, body); ctx.implicit_splat(self, &mut reject, meta, vector_size)?; ctx.implicit_splat(self, &mut accept, meta, vector_size)?; @@ -282,18 +259,9 @@ impl Frontend { }, meta, ); - let zero_constant = self.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width, - value: ScalarValue::Float(0.0), - }, - }, - meta, - ); - let zero = ctx.add_expression(Expression::Constant(zero_constant), meta, body); + + let zero_literal = Literal::zero(ScalarKind::Float, width).unwrap(); + let zero = ctx.add_expression(Expression::Literal(zero_literal), meta, body); for i in 0..columns as u32 { components.push( @@ -323,30 +291,12 @@ impl Frontend { // (column i, row j) in the argument will be initialized from there. All // other components will be initialized to the identity matrix. - let zero_constant = self.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width, - value: ScalarValue::Float(0.0), - }, - }, - meta, - ); - let zero = ctx.add_expression(Expression::Constant(zero_constant), meta, body); - let one_constant = self.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Scalar { - width, - value: ScalarValue::Float(1.0), - }, - }, - meta, - ); - let one = ctx.add_expression(Expression::Constant(one_constant), meta, body); + let zero_literal = Literal::zero(ScalarKind::Float, width).unwrap(); + let one_literal = Literal::one(ScalarKind::Float, width).unwrap(); + + let zero = ctx.add_expression(Expression::Literal(zero_literal), meta, body); + let one = ctx.add_expression(Expression::Literal(one_literal), meta, body); + let vector_ty = self.module.types.insert( Type { name: None, @@ -406,24 +356,17 @@ impl Frontend { Ordering::Greater => ctx.vector_resize(rows, vector, meta, body), }) } else { - let vec_constant = self.module.constants.fetch_or_append( - Constant { - name: None, - specialization: None, - inner: ConstantInner::Composite { - ty: vector_ty, - components: (0..rows as u32) - .map(|r| match r == i { - true => one_constant, - false => zero_constant, - }) - .collect(), - }, - }, - meta, - ); - let vec = - ctx.add_expression(Expression::Constant(vec_constant), meta, body); + let compose_expr = Expression::Compose { + ty: vector_ty, + components: (0..rows as u32) + .map(|r| match r == i { + true => one, + false => zero, + }) + .collect(), + }; + + let vec = ctx.add_expression(compose_expr, meta, body); components.push(vec) } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index ed139e799..7db30ea80 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -9,8 +9,7 @@ use super::{ variables::{GlobalOrConstant, VarDeclaration}, Frontend, Result, }; -use crate::{arena::Handle, Block, Constant, ConstantInner, Expression, ScalarValue, Span, Type}; -use core::convert::TryFrom; +use crate::{arena::Handle, proc::U32EvalError, Block, Expression, Span, Type}; use pp_rs::token::{PreprocessorError, Token as PPToken, TokenValue as PPTokenValue}; use std::iter::Peekable; @@ -192,30 +191,21 @@ impl<'source> ParsingContext<'source> { } fn parse_uint_constant(&mut self, frontend: &mut Frontend) -> Result<(u32, Span)> { - let (value, meta) = self.parse_constant_expression(frontend)?; + let (const_expr, meta) = self.parse_constant_expression(frontend)?; - let int = match frontend.module.constants[value].inner { - ConstantInner::Scalar { - value: ScalarValue::Uint(int), - .. - } => u32::try_from(int).map_err(|_| Error { + let res = frontend.module.to_ctx().eval_expr_to_u32(const_expr); + + let int = match res { + Ok(value) => Ok(value), + Err(U32EvalError::Negative) => Err(Error { kind: ErrorKind::SemanticError("int constant overflows".into()), meta, - })?, - ConstantInner::Scalar { - value: ScalarValue::Sint(int), - .. - } => u32::try_from(int).map_err(|_| Error { - kind: ErrorKind::SemanticError("int constant overflows".into()), + }), + Err(U32EvalError::NonConst) => Err(Error { + kind: ErrorKind::SemanticError("Expected a uint constant".into()), meta, - })?, - _ => { - return Err(Error { - kind: ErrorKind::SemanticError("Expected a uint constant".into()), - meta, - }) - } - }; + }), + }?; Ok((int, meta)) } @@ -223,7 +213,7 @@ impl<'source> ParsingContext<'source> { fn parse_constant_expression( &mut self, frontend: &mut Frontend, - ) -> Result<(Handle, Span)> { + ) -> Result<(Handle, Span)> { let mut block = Block::new(); let mut ctx = Context::new(frontend, &mut block); @@ -412,7 +402,7 @@ impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { frontend: &mut Frontend, ty: Handle, name: String, - init: Option>, + init: Option>, meta: Span, ) -> Result> { let decl = VarDeclaration { diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 4e43e75c8..e99dda54f 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -244,7 +244,7 @@ impl<'source> ParsingContext<'source> { .transpose()?; let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; - let maybe_constant = if ctx.external { + let maybe_const_expr = if ctx.external { if let Some((root, meta)) = init { match frontend.solve_constant(ctx.ctx, root, meta) { Ok(res) => Some(res), @@ -260,9 +260,9 @@ impl<'source> ParsingContext<'source> { None }; - let pointer = ctx.add_var(frontend, ty, name, maybe_constant, meta)?; + let pointer = ctx.add_var(frontend, ty, name, maybe_const_expr, meta)?; - if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) { + if let Some((value, _)) = init.filter(|_| maybe_const_expr.is_none()) { ctx.flush_expressions(); ctx.body.push(Statement::Store { pointer, value }, meta); } diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 781f4cffe..c05d060ea 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -1,5 +1,6 @@ use crate::front::glsl::context::ExprPos; use crate::front::glsl::Span; +use crate::Literal; use crate::{ front::glsl::{ ast::ParameterQualifier, @@ -9,7 +10,7 @@ use crate::{ variables::VarDeclaration, Error, ErrorKind, Frontend, Result, }, - Block, ConstantInner, Expression, ScalarValue, Statement, SwitchCase, UnaryOperator, + Block, Expression, Statement, SwitchCase, UnaryOperator, }; impl<'source> ParsingContext<'source> { @@ -194,20 +195,16 @@ impl<'source> ParsingContext<'source> { let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; let (root, meta) = ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; - let constant = frontend.solve_constant(ctx, root, meta)?; + let const_expr = frontend.solve_constant(ctx, root, meta)?; - match frontend.module.constants[constant].inner { - ConstantInner::Scalar { - value: ScalarValue::Sint(int), - .. - } => match uint { - true => crate::SwitchValue::U32(int as u32), - false => crate::SwitchValue::I32(int as i32), + match frontend.module.const_expressions[const_expr] { + Expression::Literal(Literal::I32(value)) => match uint { + true => crate::SwitchValue::U32(value as u32), + false => crate::SwitchValue::I32(value), }, - ConstantInner::Scalar { - value: ScalarValue::Uint(int), - .. - } => crate::SwitchValue::U32(int as u32), + Expression::Literal(Literal::U32(value)) => { + crate::SwitchValue::U32(value) + } _ => { frontend.errors.push(Error { kind: ErrorKind::SemanticError( diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index ae529a6fb..dd5880068 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -509,7 +509,8 @@ fn functions() { #[test] fn constants() { - use crate::{Constant, ConstantInner, ScalarValue}; + use crate::{Constant, Expression, ScalarKind, Type, TypeInner}; + let mut frontend = Frontend::default(); let module = frontend @@ -526,28 +527,49 @@ fn constants() { ) .unwrap(); + let mut types = module.types.iter(); let mut constants = module.constants.iter(); + let mut const_expressions = module.const_expressions.iter(); + + let (ty_handle, ty) = types.next().unwrap(); + assert_eq!( + ty, + &Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Float, + width: 4 + } + } + ); + + let (init_a_handle, init_a) = const_expressions.next().unwrap(); + assert_eq!(init_a, &Expression::Literal(crate::Literal::F32(1.0))); + + let (constant_a_handle, constant_a) = constants.next().unwrap(); + assert_eq!( + constant_a, + &Constant { + name: Some("a".to_owned()), + r#override: crate::Override::None, + ty: ty_handle, + init: init_a_handle + } + ); + + // skip const expr that was inserted for `global` var + const_expressions.next().unwrap(); + + let (init_b_handle, init_b) = const_expressions.next().unwrap(); + assert_eq!(init_b, &Expression::Constant(constant_a_handle)); - assert_eq!( - constants.next().unwrap().1, - &Constant { - name: Some("a".to_owned()), - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(1.0) - } - } - ); assert_eq!( constants.next().unwrap().1, &Constant { name: Some("b".to_owned()), - specialization: None, - inner: ConstantInner::Scalar { - width: 4, - value: ScalarValue::Float(1.0) - } + r#override: crate::Override::None, + ty: ty_handle, + init: init_b_handle } ); diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index a7967848d..513bc2275 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -2,8 +2,8 @@ use super::{ constants::ConstantSolver, context::Context, Error, ErrorKind, Frontend, Result, Span, }; use crate::{ - proc::ResolveContext, Bytes, Constant, Expression, Handle, ImageClass, ImageDimension, - ScalarKind, Type, TypeInner, VectorSize, + proc::ResolveContext, Bytes, Expression, Handle, ImageClass, ImageDimension, ScalarKind, Type, + TypeInner, VectorSize, }; pub fn parse_type(type_name: &str) -> Option { @@ -320,11 +320,12 @@ impl Frontend { ctx: &Context, root: Handle, meta: Span, - ) -> Result> { + ) -> Result> { let mut solver = ConstantSolver { types: &mut self.module.types, expressions: &ctx.expressions, constants: &mut self.module.constants, + const_expressions: &mut self.module.const_expressions, }; solver.solve(root).map_err(|e| Error { diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 4c0e0a927..a9a403e40 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -14,7 +14,7 @@ pub struct VarDeclaration<'a, 'key> { pub qualifiers: &'a mut TypeQualifiers<'key>, pub ty: Handle, pub name: Option, - pub init: Option>, + pub init: Option>, pub meta: Span, } @@ -494,29 +494,21 @@ impl Frontend { meta, })?; + let constant = Constant { + name: name.clone(), + r#override: crate::Override::None, + ty, + init, + }; + let handle = self.module.constants.fetch_or_append(constant, meta); + let lookup = GlobalLookup { - kind: GlobalLookupKind::Constant(init, ty), + kind: GlobalLookupKind::Constant(handle, ty), entry_arg: None, mutable: false, }; - if let Some(name) = name.as_ref() { - let constant = self.module.constants.get_mut(init); - if constant.name.is_none() { - // set the name of the constant - constant.name = Some(name.clone()) - } else { - // add a copy of the constant with the new name - let new_const = Constant { - name: Some(name.clone()), - specialization: constant.specialization, - inner: constant.inner.clone(), - }; - self.module.constants.fetch_or_append(new_const, meta); - } - } - - (GlobalOrConstant::Constant(init), lookup) + (GlobalOrConstant::Constant(handle), lookup) } StorageQualifier::AddressSpace(mut space) => { match space { diff --git a/src/front/mod.rs b/src/front/mod.rs index d6f38671e..1f16ff637 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -55,16 +55,6 @@ impl Emitter { } } -#[allow(dead_code)] -impl super::ConstantInner { - const fn boolean(value: bool) -> Self { - Self::Scalar { - width: super::BOOL_WIDTH, - value: super::ScalarValue::Bool(value), - } - } -} - /// A table of types for an `Arena`. /// /// A front end can use a `Typifier` to get types for an arena's expressions diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 97a197497..7a874ae4e 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -128,6 +128,7 @@ impl> super::Frontend { expressions: &mut fun.expressions, local_arena: &mut fun.local_variables, const_arena: &mut module.constants, + const_expressions: &mut module.const_expressions, type_arena: &module.types, global_arena: &module.global_variables, arguments: &fun.arguments, @@ -572,6 +573,7 @@ impl<'function> BlockContext<'function> { crate::proc::GlobalCtx { types: self.type_arena, constants: self.const_arena, + const_expressions: self.const_expressions, } } diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index ddbc8c19b..ac0129059 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -503,6 +503,10 @@ impl> super::Frontend { spirv::ImageOperands::CONST_OFFSET => { let offset_constant = self.next()?; let offset_handle = self.lookup_constant.lookup(offset_constant)?.handle; + let offset_handle = ctx.const_expressions.append( + crate::Expression::Constant(offset_handle), + Default::default(), + ); offset = Some(offset_handle); words_left -= 1; } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a2124bfa8..6ddd1d70c 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -221,6 +221,11 @@ impl Decoration { } } + fn specialization(&self) -> crate::Override { + self.specialization + .map_or(crate::Override::None, crate::Override::ByNameOrId) + } + const fn resource_binding(&self) -> Option { match *self { Decoration { @@ -536,6 +541,7 @@ struct BlockContext<'function> { local_arena: &'function mut Arena, /// Constants arena of the module being processed const_arena: &'function mut Arena, + const_expressions: &'function mut Arena, /// Type arena of the module being processed type_arena: &'function UniqueArena, /// Global arena of the module being processed @@ -584,8 +590,6 @@ pub struct Frontend { // so that in the IR any called function is already known. function_call_graph: GraphMap, options: Options, - index_constants: Vec>, - index_constant_expressions: Vec>, /// Maps for a switch from a case target to the respective body and associated literals that /// use that target block id. @@ -636,8 +640,6 @@ impl> Frontend { dummy_functions: Arena::new(), function_call_graph: GraphMap::new(), options: options.clone(), - index_constants: Vec::new(), - index_constant_expressions: Vec::new(), switch_cases: indexmap::IndexMap::default(), gl_per_vertex_builtin_access: FastHashSet::default(), } @@ -1395,7 +1397,10 @@ impl> Frontend { inst.expect(5)?; let init_id = self.next()?; let lconst = self.lookup_constant.lookup(init_id)?; - Some(lconst.handle) + Some( + ctx.const_expressions + .append(crate::Expression::Constant(lconst.handle), span), + ) } else { None }; @@ -1531,11 +1536,15 @@ impl> Frontend { let index_expr_handle = get_expr_handle!(access_id, &index_expr); let index_expr_data = &ctx.expressions[index_expr.handle]; let index_maybe = match *index_expr_data { - crate::Expression::Constant(const_handle) => { - Some(ctx.const_arena[const_handle].to_array_length().ok_or( - Error::InvalidAccess(crate::Expression::Constant(const_handle)), - )?) - } + crate::Expression::Constant(const_handle) => Some( + ctx.gctx() + .eval_expr_to_u32(ctx.const_arena[const_handle].init) + .map_err(|_| { + Error::InvalidAccess(crate::Expression::Constant( + const_handle, + )) + })?, + ), _ => None, }; @@ -3731,13 +3740,6 @@ impl> Frontend { }, ); } - // register special constants - self.index_constant_expressions.clear(); - for &con_handle in self.index_constants.iter() { - let span = constants.get_span(con_handle); - let handle = expressions.append(crate::Expression::Constant(con_handle), span); - self.index_constant_expressions.push(handle); - } // register constants for (&id, con) in self.lookup_constant.iter() { let span = constants.get_span(con.handle); @@ -3902,23 +3904,6 @@ impl> Frontend { crate::Module::default() }; - // register indexing constants - self.index_constants.clear(); - for i in 0..4 { - let handle = module.constants.append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Sint(i), - }, - }, - Default::default(), - ); - self.index_constants.push(handle); - } - self.layouter.clear(); self.dummy_functions = Arena::new(); self.lookup_function.clear(); @@ -3965,9 +3950,7 @@ impl> Frontend { Op::TypeSampler => self.parse_type_sampler(inst, &mut module), Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), Op::ConstantComposite => self.parse_composite_constant(inst, &mut module), - Op::ConstantNull | Op::Undef => self - .parse_null_constant(inst, &module.types, &mut module.constants) - .map(|_| ()), + Op::ConstantNull | Op::Undef => self.parse_null_constant(inst, &mut module), Op::ConstantTrue => self.parse_bool_constant(inst, true, &mut module), Op::ConstantFalse => self.parse_bool_constant(inst, false, &mut module), Op::Variable => self.parse_global_variable(inst, &mut module), @@ -4892,21 +4875,15 @@ impl> Frontend { let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; - let inner = match module.types[ty].inner { + let literal = match module.types[ty].inner { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, width, } => { let low = self.next()?; - let high = if width > 4 { - inst.expect(5)?; - self.next()? - } else { - 0 - }; - crate::ConstantInner::Scalar { - width, - value: crate::ScalarValue::Uint((u64::from(high) << 32) | u64::from(low)), + match width { + 4 => crate::Literal::U32(low), + _ => return Err(Error::InvalidTypeWidth(width as u32)), } } crate::TypeInner::Scalar { @@ -4914,17 +4891,9 @@ impl> Frontend { width, } => { let low = self.next()?; - let high = if width > 4 { - inst.expect(5)?; - self.next()? - } else { - 0 - }; - crate::ConstantInner::Scalar { - width, - value: crate::ScalarValue::Sint( - (i64::from(high as i32) << 32) | ((i64::from(low as i32) << 32) >> 32), - ), + match width { + 4 => crate::Literal::I32(low as i32), + _ => return Err(Error::InvalidTypeWidth(width as u32)), } } crate::TypeInner::Scalar { @@ -4932,18 +4901,16 @@ impl> Frontend { width, } => { let low = self.next()?; - let extended = match width { - 4 => f64::from(f32::from_bits(low)), + match width { + 4 => crate::Literal::F32(f32::from_bits(low)), 8 => { inst.expect(5)?; let high = self.next()?; - f64::from_bits((u64::from(high) << 32) | u64::from(low)) + crate::Literal::F64(f64::from_bits( + (u64::from(high) << 32) | u64::from(low), + )) } _ => return Err(Error::InvalidTypeWidth(width as u32)), - }; - crate::ConstantInner::Scalar { - width, - value: crate::ScalarValue::Float(extended), } } _ => return Err(Error::UnsupportedType(type_lookup.handle)), @@ -4951,16 +4918,22 @@ impl> Frontend { let decor = self.future_decor.remove(&id).unwrap_or_default(); + let span = self.span_from_with_op(start); + + let init = module + .const_expressions + .append(crate::Expression::Literal(literal), span); self.lookup_constant.insert( id, LookupConstant { handle: module.constants.append( crate::Constant { - specialization: decor.specialization, + r#override: decor.specialization(), name: decor.name, - inner, + ty, + init, }, - self.span_from_with_op(start), + span, ), type_id, }, @@ -4977,27 +4950,41 @@ impl> Frontend { self.switch(ModuleState::Type, inst.op)?; inst.expect_at_least(3)?; let type_id = self.next()?; + let id = self.next()?; + let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; - let id = self.next()?; let mut components = Vec::with_capacity(inst.wc as usize - 3); for _ in 0..components.capacity() { + let start = self.data_offset; let component_id = self.next()?; + let span = self.span_from_with_op(start); let constant = self.lookup_constant.lookup(component_id)?; - components.push(constant.handle); + let expr = module + .const_expressions + .append(crate::Expression::Constant(constant.handle), span); + components.push(expr); } + let decor = self.future_decor.remove(&id).unwrap_or_default(); + + let span = self.span_from_with_op(start); + + let init = module + .const_expressions + .append(crate::Expression::Compose { ty, components }, span); self.lookup_constant.insert( id, LookupConstant { handle: module.constants.append( crate::Constant { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - specialization: None, - inner: crate::ConstantInner::Composite { ty, components }, + r#override: decor.specialization(), + name: decor.name, + ty, + init, }, - self.span_from_with_op(start), + span, ), type_id, }, @@ -5008,30 +4995,35 @@ impl> Frontend { fn parse_null_constant( &mut self, inst: Instruction, - types: &UniqueArena, - constants: &mut Arena, - ) -> Result<(u32, u32, Handle), Error> { + module: &mut crate::Module, + ) -> Result<(), Error> { let start = self.data_offset; self.switch(ModuleState::Type, inst.op)?; inst.expect(3)?; let type_id = self.next()?; let id = self.next()?; let span = self.span_from_with_op(start); + let type_lookup = self.lookup_type.lookup(type_id)?; let ty = type_lookup.handle; - let inner = null::generate_null_constant(ty, types, constants, span)?; - let handle = constants.append( + let decor = self.future_decor.remove(&id).unwrap_or_default(); + + let init = module + .const_expressions + .append(crate::Expression::ZeroValue(ty), span); + let handle = module.constants.append( crate::Constant { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - specialization: None, //TODO - inner, + r#override: decor.specialization(), + name: decor.name, + ty, + init, }, span, ); self.lookup_constant .insert(id, LookupConstant { handle, type_id }); - Ok((type_id, id, handle)) + Ok(()) } fn parse_bool_constant( @@ -5045,17 +5037,28 @@ impl> Frontend { inst.expect(3)?; let type_id = self.next()?; let id = self.next()?; + let span = self.span_from_with_op(start); + let type_lookup = self.lookup_type.lookup(type_id)?; + let ty = type_lookup.handle; + + let decor = self.future_decor.remove(&id).unwrap_or_default(); + + let init = module.const_expressions.append( + crate::Expression::Literal(crate::Literal::Bool(value)), + span, + ); self.lookup_constant.insert( id, LookupConstant { handle: module.constants.append( crate::Constant { - name: self.future_decor.remove(&id).and_then(|dec| dec.name), - specialization: None, //TODO - inner: crate::ConstantInner::boolean(value), + r#override: decor.specialization(), + name: decor.name, + ty, + init, }, - self.span_from_with_op(start), + span, ), type_id, }, @@ -5076,9 +5079,14 @@ impl> Frontend { let storage_class = self.next()?; let init = if inst.wc > 4 { inst.expect(5)?; + let start = self.data_offset; let init_id = self.next()?; + let span = self.span_from_with_op(start); let lconst = self.lookup_constant.lookup(init_id)?; - Some(lconst.handle) + let expr = module + .const_expressions + .append(crate::Expression::Constant(lconst.handle), span); + Some(expr) } else { None }; @@ -5211,8 +5219,7 @@ impl> Frontend { match null::generate_default_built_in( Some(built_in), ty, - &module.types, - &mut module.constants, + &mut module.const_expressions, span, ) { Ok(handle) => Some(handle), @@ -5225,37 +5232,25 @@ impl> Frontend { Some(crate::Binding::Location { .. }) => None, None => match module.types[ty].inner { crate::TypeInner::Struct { ref members, .. } => { - // A temporary to avoid borrowing `module.types` - let pairs = members - .iter() - .map(|member| { - let built_in = match member.binding { - Some(crate::Binding::BuiltIn(built_in)) => Some(built_in), - _ => None, - }; - (built_in, member.ty) - }) - .collect::>(); - let mut components = Vec::with_capacity(members.len()); - for (built_in, member_ty) in pairs { + for member in members.iter() { + let built_in = match member.binding { + Some(crate::Binding::BuiltIn(built_in)) => Some(built_in), + _ => None, + }; let handle = null::generate_default_built_in( built_in, - member_ty, - &module.types, - &mut module.constants, + member.ty, + &mut module.const_expressions, span, )?; components.push(handle); } - Some(module.constants.append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Composite { ty, components }, - }, - span, - )) + Some( + module + .const_expressions + .append(crate::Expression::Compose { ty, components }, span), + ) } _ => None, }, @@ -5322,7 +5317,11 @@ fn resolve_constant( gctx: crate::proc::GlobalCtx, constant: Handle, ) -> Option { - gctx.constants[constant].to_array_length() + match gctx.const_expressions[gctx.constants[constant].init] { + crate::Expression::Literal(crate::Literal::U32(id)) => Some(id), + crate::Expression::Literal(crate::Literal::I32(id)) => Some(id as u32), + _ => None, + } } pub fn parse_u8_slice(data: &[u8], options: &Options) -> Result { diff --git a/src/front/spv/null.rs b/src/front/spv/null.rs index eb0b418aa..42cccca80 100644 --- a/src/front/spv/null.rs +++ b/src/front/spv/null.rs @@ -1,172 +1,31 @@ use super::Error; -use crate::arena::{Arena, Handle, UniqueArena}; - -const fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { - crate::ConstantInner::Scalar { - width, - value: match kind { - crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), - crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), - crate::ScalarKind::Float => crate::ScalarValue::Float(0.0), - crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), - }, - } -} - -pub fn generate_null_constant( - ty: Handle, - type_arena: &UniqueArena, - constant_arena: &mut Arena, - span: crate::Span, -) -> Result { - let inner = match type_arena[ty].inner { - crate::TypeInner::Scalar { kind, width } => make_scalar_inner(kind, width), - crate::TypeInner::Vector { size, kind, width } => { - let mut components = Vec::with_capacity(size as usize); - for _ in 0..size as usize { - components.push(constant_arena.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: make_scalar_inner(kind, width), - }, - span, - )); - } - crate::ConstantInner::Composite { ty, components } - } - crate::TypeInner::Matrix { - columns, - rows, - width, - } => { - // If we successfully declared a matrix type, we have declared a vector type for it too. - let vector_ty = type_arena - .get(&crate::Type { - name: None, - inner: crate::TypeInner::Vector { - kind: crate::ScalarKind::Float, - size: rows, - width, - }, - }) - .unwrap(); - let vector_inner = generate_null_constant(vector_ty, type_arena, constant_arena, span)?; - let vector_handle = constant_arena.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: vector_inner, - }, - span, - ); - crate::ConstantInner::Composite { - ty, - components: vec![vector_handle; columns as usize], - } - } - crate::TypeInner::Struct { ref members, .. } => { - let mut components = Vec::with_capacity(members.len()); - // copy out the types to avoid borrowing `members` - let member_tys = members.iter().map(|member| member.ty).collect::>(); - for member_ty in member_tys { - let inner = generate_null_constant(member_ty, type_arena, constant_arena, span)?; - components.push(constant_arena.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - span, - )); - } - crate::ConstantInner::Composite { ty, components } - } - crate::TypeInner::Array { - base, - size: crate::ArraySize::Constant(size), - .. - } => { - let inner = generate_null_constant(base, type_arena, constant_arena, span)?; - let value = constant_arena.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - span, - ); - crate::ConstantInner::Composite { - ty, - components: vec![value; size.get() as usize], - } - } - ref other => { - log::warn!("null constant type {:?}", other); - return Err(Error::UnsupportedType(ty)); - } - }; - Ok(inner) -} +use crate::arena::{Arena, Handle}; /// Create a default value for an output built-in. pub fn generate_default_built_in( built_in: Option, ty: Handle, - type_arena: &UniqueArena, - constant_arena: &mut Arena, + const_expressions: &mut Arena, span: crate::Span, -) -> Result, Error> { - let inner = match built_in { +) -> Result, Error> { + let expr = match built_in { Some(crate::BuiltIn::Position { .. }) => { - let zero = constant_arena.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - value: crate::ScalarValue::Float(0.0), - width: 4, - }, - }, - span, - ); - let one = constant_arena.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - value: crate::ScalarValue::Float(1.0), - width: 4, - }, - }, - span, - ); - crate::ConstantInner::Composite { + let zero = const_expressions + .append(crate::Expression::Literal(crate::Literal::F32(0.0)), span); + let one = const_expressions + .append(crate::Expression::Literal(crate::Literal::F32(1.0)), span); + crate::Expression::Compose { ty, components: vec![zero, zero, zero, one], } } - Some(crate::BuiltIn::PointSize) => crate::ConstantInner::Scalar { - value: crate::ScalarValue::Float(1.0), - width: 4, - }, - Some(crate::BuiltIn::FragDepth) => crate::ConstantInner::Scalar { - value: crate::ScalarValue::Float(0.0), - width: 4, - }, - Some(crate::BuiltIn::SampleMask) => crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(u64::MAX), - width: 4, - }, - //Note: `crate::BuiltIn::ClipDistance` is intentionally left for the default path - _ => generate_null_constant(ty, type_arena, constant_arena, span)?, + Some(crate::BuiltIn::PointSize) => crate::Expression::Literal(crate::Literal::F32(1.0)), + Some(crate::BuiltIn::FragDepth) => crate::Expression::Literal(crate::Literal::F32(0.0)), + Some(crate::BuiltIn::SampleMask) => { + crate::Expression::Literal(crate::Literal::U32(u32::MAX)) + } + // Note: `crate::BuiltIn::ClipDistance` is intentionally left for the default path + _ => crate::Expression::ZeroValue(ty), }; - Ok(constant_arena.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - span, - )) + Ok(const_expressions.append(expr, span)) } diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index dc9a3b178..701eca992 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -100,8 +100,6 @@ pub enum ExpectedToken<'a> { Identifier, Number, Integer, - /// A compile-time constant expression. - Constant, /// Expected: constant, parenthesized expression, identifier PrimaryExpression, /// Expected: assignment, increment/decrement expression @@ -141,6 +139,7 @@ pub enum InvalidAssignmentType { pub enum Error<'a> { Unexpected(Span, ExpectedToken<'a>), UnexpectedComponents(Span), + UnexpectedOperationInConstContext(Span), BadNumber(Span, NumberError), /// A negative signed integer literal where both signed and unsigned, /// but only non-negative literals are allowed. @@ -227,7 +226,6 @@ pub enum Error<'a> { /// the same identifier as `ident`, above. path: Vec<(Span, Span)>, }, - ConstExprUnsupported(Span), InvalidSwitchValue { uint: bool, span: Span, @@ -273,7 +271,6 @@ impl<'a> Error<'a> { ExpectedToken::Identifier => "identifier".to_string(), ExpectedToken::Number => "32-bit signed integer literal".to_string(), ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), - ExpectedToken::Constant => "compile-time constant".to_string(), ExpectedToken::PrimaryExpression => "expression".to_string(), ExpectedToken::Assignment => "assignment or increment/decrement".to_string(), ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), @@ -297,6 +294,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span, "unexpected components".into())], notes: vec![], }, + Error::UnexpectedOperationInConstContext(span) => ParseError { + message: "this operation is not supported in a const context".to_string(), + labels: vec![(span, "operation not supported here".into())], + notes: vec![], + }, Error::BadNumber(bad_span, ref err) => ParseError { message: format!("{}: `{}`", err, &source[bad_span],), labels: vec![(bad_span, err.to_string().into())], @@ -625,14 +627,6 @@ impl<'a> Error<'a> { .collect(), notes: vec![], }, - Error::ConstExprUnsupported(span) => ParseError { - message: "this constant expression is not supported".to_string(), - labels: vec![(span, "expression is not supported".into())], - notes: vec![ - "this should be fixed in a future version of Naga".into(), - "https://github.com/gfx-rs/naga/issues/1829".into(), - ], - }, Error::InvalidSwitchValue { uint, span } => ParseError { message: "invalid switch value".to_string(), labels: vec![( @@ -701,7 +695,7 @@ impl<'a> Error<'a> { }, Error::NonPositiveArrayLength(span) => ParseError { message: "array element count must be greater than zero".to_string(), - labels: vec![(span, "must be positive".into())], + labels: vec![(span, "must be greater than zero".into())], notes: vec![], }, } diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 8d7a5cdc2..3b4830b05 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -4,7 +4,7 @@ use crate::front::wgsl::parse::ast; use crate::{Handle, Span}; use crate::front::wgsl::error::Error; -use crate::front::wgsl::lower::{ExpressionContext, Lowerer, OutputContext}; +use crate::front::wgsl::lower::{ExpressionContext, Lowerer}; use crate::proc::TypeResolution; enum ConcreteConstructorHandle { @@ -145,7 +145,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { components: &[Handle>], mut ctx: ExpressionContext<'source, '_, '_>, ) -> Result, Error<'source>> { - let constructor_h = self.constructor(constructor, ctx.as_output())?; + let constructor_h = self.constructor(constructor, ctx.reborrow())?; let components_h = match *components { [] => ComponentsHandle::None, @@ -153,7 +153,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let span = ctx.ast_expressions.get_span(component); let component = self.expression(component, ctx.reborrow())?; ctx.grow_types(component)?; - let ty = &ctx.typifier[component]; + let ty = &ctx.typifier()[component]; ComponentsHandle::One { component, @@ -179,7 +179,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .collect(); ctx.grow_types(component)?; - let ty = &ctx.typifier[component]; + let ty = &ctx.typifier()[component]; ComponentsHandle::Many { components, @@ -195,14 +195,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ); let expr = match (components, constructor) { // Empty constructor - (Components::None, dst_ty) => { - let ty = match dst_ty { - ConcreteConstructor::Type(ty, _) => ty, - _ => return Err(Error::TypeNotInferrable(ty_span)), - }; - - return Ok(ctx.interrupt_emitter(crate::Expression::ZeroValue(ty), span)); - } + (Components::None, dst_ty) => match dst_ty { + ConcreteConstructor::Type(ty, _) => { + return Ok(ctx.interrupt_emitter(crate::Expression::ZeroValue(ty), span)) + } + _ => return Err(Error::TypeNotInferrable(ty_span)), + }, // Scalar constructor & conversion (scalar -> scalar) ( @@ -402,7 +400,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let components = components .chunks(rows as usize) .map(|vec_components| { - ctx.naga_expressions.append( + ctx.append_expression( crate::Expression::Compose { ty: vec_ty, components: Vec::from(vec_components), @@ -525,55 +523,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { _ => return Err(Error::TypeNotConstructible(ty_span)), }; - let expr = ctx.naga_expressions.append(expr, span); + let expr = ctx.append_expression(expr, span); Ok(expr) } - /// Build a Naga IR [`ConstantInner`] given a WGSL construction expression. - /// - /// Given `constructor`, representing the head of a WGSL [`type constructor - /// expression`], and a slice of [`ast::Expression`] handles representing - /// the constructor's arguments, build a Naga [`ConstantInner`] value - /// representing the given value. - /// - /// If `constructor` is for a composite type, this may entail adding new - /// [`Type`]s and [`Constant`]s to [`ctx.module`], if it doesn't already - /// have what we need. - /// - /// If the arguments cannot be evaluated at compile time, return an error. - /// - /// [`ConstantInner`]: crate::ConstantInner - /// [`type constructor expression`]: https://gpuweb.github.io/gpuweb/wgsl/#type-constructor-expr - /// [`Function::expressions`]: ast::Function::expressions - /// [`TranslationUnit::global_expressions`]: ast::TranslationUnit::global_expressions - /// [`Type`]: crate::Type - /// [`Constant`]: crate::Constant - /// [`ctx.module`]: OutputContext::module - pub fn const_construct( - &mut self, - span: Span, - constructor: &ast::ConstructorType<'source>, - components: &[Handle>], - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result> { - // TODO: Support zero values, splatting and inference. - - let constructor = self.constructor(constructor, ctx.reborrow())?; - - let c = match constructor { - ConcreteConstructorHandle::Type(ty) => { - let components = components - .iter() - .map(|&expr| self.constant(expr, ctx.reborrow())) - .collect::>()?; - - crate::ConstantInner::Composite { ty, components } - } - _ => return Err(Error::ConstExprUnsupported(span)), - }; - Ok(c) - } - /// Build a Naga IR [`Type`] for `constructor` if there is enough /// information to do so. /// @@ -591,13 +544,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { /// array's length. /// /// [`Type`]: crate::Type - /// [`ctx.module`]: OutputContext::module + /// [`ctx.module`]: ExpressionContext::module /// [`Array`]: crate::TypeInner::Array /// [`Constant`]: crate::Constant fn constructor<'out>( &mut self, constructor: &ast::ConstructorType<'source>, - mut ctx: OutputContext<'source, '_, 'out>, + mut ctx: ExpressionContext<'source, '_, 'out>, ) -> Result> { let c = match *constructor { ast::ConstructorType::Scalar { width, kind } => { @@ -628,17 +581,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::ConstructorType::PartialArray => ConcreteConstructorHandle::PartialArray, ast::ConstructorType::Array { base, size } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; + let base = self.resolve_ast_type(base, ctx.as_global())?; let size = match size { ast::ArraySize::Constant(expr) => { - let span = ctx.ast_expressions.get_span(expr); - let constant = self.constant(expr, ctx.reborrow())?; - let size = ctx.module.constants[constant] - .to_array_length() - .ok_or(Error::ExpectedArraySize(span))?; - let size = - NonZeroU32::new(size).ok_or(Error::NonPositiveArrayLength(span))?; - crate::ArraySize::Constant(size) + let const_expr = self.expression(expr, ctx.as_const())?; + crate::ArraySize::Constant(ctx.array_length(const_expr)?) } ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, }; diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 0de078353..6fecc6c26 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -12,7 +12,7 @@ use indexmap::IndexMap; mod construction; /// State for constructing a `crate::Module`. -pub struct OutputContext<'source, 'temp, 'out> { +pub struct GlobalContext<'source, 'temp, 'out> { /// The `TranslationUnit`'s expressions arena. ast_expressions: &'temp Arena>, @@ -26,15 +26,29 @@ pub struct OutputContext<'source, 'temp, 'out> { /// The module we're constructing. module: &'out mut crate::Module, + + const_typifier: &'temp mut Typifier, } -impl<'source> OutputContext<'source, '_, '_> { - fn reborrow(&mut self) -> OutputContext<'source, '_, '_> { - OutputContext { +impl<'source> GlobalContext<'source, '_, '_> { + fn reborrow(&mut self) -> GlobalContext<'source, '_, '_> { + GlobalContext { ast_expressions: self.ast_expressions, globals: self.globals, types: self.types, module: self.module, + const_typifier: self.const_typifier, + } + } + + fn as_const(&mut self) -> ExpressionContext<'source, '_, '_> { + ExpressionContext { + ast_expressions: self.ast_expressions, + globals: self.globals, + types: self.types, + module: self.module, + const_typifier: self.const_typifier, + expr_type: ExpressionContextType::Constant, } } @@ -74,6 +88,7 @@ pub struct StatementContext<'source, 'temp, 'out> { /// [`FunctionArgument`]: crate::Expression::FunctionArgument local_table: &'temp mut FastHashMap, TypedExpression>, + const_typifier: &'temp mut Typifier, typifier: &'temp mut Typifier, variables: &'out mut Arena, naga_expressions: &'out mut Arena, @@ -91,6 +106,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { globals: self.globals, types: self.types, ast_expressions: self.ast_expressions, + const_typifier: self.const_typifier, typifier: self.typifier, variables: self.variables, naga_expressions: self.naga_expressions, @@ -109,26 +125,30 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { 'temp: 't, { ExpressionContext { - local_table: self.local_table, globals: self.globals, types: self.types, ast_expressions: self.ast_expressions, - typifier: self.typifier, - naga_expressions: self.naga_expressions, + const_typifier: self.const_typifier, module: self.module, - local_vars: self.variables, - arguments: self.arguments, - block, - emitter, + expr_type: ExpressionContextType::Runtime(RuntimeExpressionContext { + local_table: self.local_table, + naga_expressions: self.naga_expressions, + local_vars: self.variables, + arguments: self.arguments, + typifier: self.typifier, + block, + emitter, + }), } } - fn as_output(&mut self) -> OutputContext<'a, '_, '_> { - OutputContext { + fn as_global(&mut self) -> GlobalContext<'a, '_, '_> { + GlobalContext { ast_expressions: self.ast_expressions, globals: self.globals, types: self.types, module: self.module, + const_typifier: self.const_typifier, } } @@ -146,12 +166,41 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { } } +pub struct RuntimeExpressionContext<'temp, 'out> { + local_table: &'temp mut FastHashMap, TypedExpression>, + + naga_expressions: &'out mut Arena, + local_vars: &'out Arena, + arguments: &'out [crate::FunctionArgument], + block: &'temp mut crate::Block, + emitter: &'temp mut Emitter, + typifier: &'temp mut Typifier, +} + +impl RuntimeExpressionContext<'_, '_> { + fn reborrow(&mut self) -> RuntimeExpressionContext<'_, '_> { + RuntimeExpressionContext { + local_table: self.local_table, + naga_expressions: self.naga_expressions, + local_vars: self.local_vars, + arguments: self.arguments, + block: self.block, + emitter: self.emitter, + typifier: self.typifier, + } + } +} + +pub enum ExpressionContextType<'temp, 'out> { + Runtime(RuntimeExpressionContext<'temp, 'out>), + Constant, +} + /// State for lowering an `ast::Expression` to Naga IR. /// /// Not to be confused with `parser::ExpressionContext`. pub struct ExpressionContext<'source, 'temp, 'out> { // WGSL AST values. - local_table: &'temp mut FastHashMap, TypedExpression>, ast_expressions: &'temp Arena>, types: &'temp Arena>, @@ -160,38 +209,130 @@ pub struct ExpressionContext<'source, 'temp, 'out> { /// `Handle`s we have built for them, owned by `Lowerer::lower`. globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, - typifier: &'temp mut Typifier, - naga_expressions: &'out mut Arena, - local_vars: &'out Arena, - arguments: &'out [crate::FunctionArgument], + const_typifier: &'temp mut Typifier, module: &'out mut crate::Module, - block: &'temp mut crate::Block, - emitter: &'temp mut Emitter, + expr_type: ExpressionContextType<'temp, 'out>, } -impl<'a> ExpressionContext<'a, '_, '_> { - fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { +impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { + fn reborrow(&mut self) -> ExpressionContext<'source, '_, '_> { ExpressionContext { - local_table: self.local_table, globals: self.globals, types: self.types, ast_expressions: self.ast_expressions, - typifier: self.typifier, - naga_expressions: self.naga_expressions, + const_typifier: self.const_typifier, module: self.module, - local_vars: self.local_vars, - arguments: self.arguments, - block: self.block, - emitter: self.emitter, + expr_type: match self.expr_type { + ExpressionContextType::Runtime(ref mut c) => { + ExpressionContextType::Runtime(c.reborrow()) + } + ExpressionContextType::Constant => ExpressionContextType::Constant, + }, } } - fn as_output(&mut self) -> OutputContext<'a, '_, '_> { - OutputContext { + fn as_const(&mut self) -> ExpressionContext<'source, '_, '_> { + ExpressionContext { + globals: self.globals, + types: self.types, + ast_expressions: self.ast_expressions, + const_typifier: self.const_typifier, + module: self.module, + expr_type: ExpressionContextType::Constant, + } + } + + fn as_global(&mut self) -> GlobalContext<'source, '_, '_> { + GlobalContext { ast_expressions: self.ast_expressions, globals: self.globals, types: self.types, module: self.module, + const_typifier: self.const_typifier, + } + } + + fn append_expression( + &mut self, + expr: crate::Expression, + span: Span, + ) -> Handle { + match self.expr_type { + ExpressionContextType::Runtime(ref mut ctx) => ctx.naga_expressions.append(expr, span), + ExpressionContextType::Constant => self.module.const_expressions.append(expr, span), + } + } + + fn get_expression(&self, handle: Handle) -> &crate::Expression { + match self.expr_type { + ExpressionContextType::Runtime(ref ctx) => &ctx.naga_expressions[handle], + ExpressionContextType::Constant => &self.module.const_expressions[handle], + } + } + + fn get_expression_span(&self, handle: Handle) -> Span { + match self.expr_type { + ExpressionContextType::Runtime(ref ctx) => ctx.naga_expressions.get_span(handle), + ExpressionContextType::Constant => self.module.const_expressions.get_span(handle), + } + } + + fn typifier(&self) -> &Typifier { + match self.expr_type { + ExpressionContextType::Runtime(ref ctx) => ctx.typifier, + ExpressionContextType::Constant => self.const_typifier, + } + } + + fn runtime_expression_ctx( + &mut self, + span: Span, + ) -> Result, Error<'source>> { + match self.expr_type { + ExpressionContextType::Runtime(ref mut ctx) => Ok(ctx.reborrow()), + ExpressionContextType::Constant => Err(Error::UnexpectedOperationInConstContext(span)), + } + } + + fn array_length( + &self, + const_expr: Handle, + ) -> Result> { + let span = self.module.const_expressions.get_span(const_expr); + let len = self + .module + .to_ctx() + .eval_expr_to_u32(const_expr) + .map_err(|err| match err { + crate::proc::U32EvalError::NonConst => Error::ExpectedArraySize(span), + crate::proc::U32EvalError::Negative => Error::NonPositiveArrayLength(span), + })?; + NonZeroU32::new(len).ok_or(Error::NonPositiveArrayLength(span)) + } + + fn gather_component( + &self, + expr: Handle, + gather_span: Span, + ) -> Result> { + match self.expr_type { + ExpressionContextType::Runtime(ref ctx) => { + let expr_span = ctx.naga_expressions.get_span(expr); + let index = self + .module + .to_ctx() + .eval_expr_to_u32_from(expr, ctx.naga_expressions) + .map_err(|_| Error::InvalidGatherComponent(expr_span))?; + crate::SwizzleComponent::XYZW + .get(index as usize) + .copied() + .ok_or(Error::InvalidGatherComponent(expr_span)) + } + // This means a `gather` operation appeared in a constant expression. + // This error refers to the `gather` itself, not its "component" argument. + ExpressionContextType::Constant => { + Err(Error::UnexpectedOperationInConstContext(gather_span)) + } } } @@ -210,9 +351,13 @@ impl<'a> ExpressionContext<'a, '_, '_> { fn register_type( &mut self, handle: Handle, - ) -> Result, Error<'a>> { + ) -> Result, Error<'source>> { self.grow_types(handle)?; - Ok(self.typifier.register_type(handle, &mut self.module.types)) + let typifier = match self.expr_type { + ExpressionContextType::Runtime(ref ctx) => ctx.typifier, + ExpressionContextType::Constant => &*self.const_typifier, + }; + Ok(typifier.register_type(handle, &mut self.module.types)) } /// Resolve the types of all expressions up through `handle`. @@ -235,23 +380,43 @@ impl<'a> ExpressionContext<'a, '_, '_> { /// [`self.typifier`]: ExpressionContext::typifier /// [`self.resolved_inner(handle)`]: ExpressionContext::resolved_inner /// [`Typifier`]: Typifier - fn grow_types(&mut self, handle: Handle) -> Result<&mut Self, Error<'a>> { - let resolve_ctx = ResolveContext::with_locals(self.module, self.local_vars, self.arguments); - self.typifier - .grow(handle, self.naga_expressions, &resolve_ctx) + fn grow_types( + &mut self, + handle: Handle, + ) -> Result<&mut Self, Error<'source>> { + let empty_arena = Arena::new(); + let resolve_ctx = match self.expr_type { + ExpressionContextType::Runtime(ref ctx) => { + ResolveContext::with_locals(self.module, ctx.local_vars, ctx.arguments) + } + ExpressionContextType::Constant => { + ResolveContext::with_locals(self.module, &empty_arena, &[]) + } + }; + let (typifier, expressions) = match self.expr_type { + ExpressionContextType::Runtime(ref mut ctx) => { + (&mut *ctx.typifier, &*ctx.naga_expressions) + } + ExpressionContextType::Constant => { + (&mut *self.const_typifier, &self.module.const_expressions) + } + }; + typifier + .grow(handle, expressions, &resolve_ctx) .map_err(Error::InvalidResolve)?; + Ok(self) } fn resolved_inner(&self, handle: Handle) -> &crate::TypeInner { - self.typifier[handle].inner_with(&self.module.types) + self.typifier()[handle].inner_with(&self.module.types) } fn image_data( &mut self, image: Handle, span: Span, - ) -> Result<(crate::ImageClass, bool), Error<'a>> { + ) -> Result<(crate::ImageClass, bool), Error<'source>> { self.grow_types(image)?; match *self.resolved_inner(image) { crate::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), @@ -261,10 +426,10 @@ impl<'a> ExpressionContext<'a, '_, '_> { fn prepare_args<'b>( &mut self, - args: &'b [Handle>], + args: &'b [Handle>], min_args: u32, span: Span, - ) -> ArgumentContext<'b, 'a> { + ) -> ArgumentContext<'b, 'source> { ArgumentContext { args: args.iter(), min_args, @@ -280,7 +445,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { op: crate::BinaryOperator, left: &mut Handle, right: &mut Handle, - ) -> Result<(), Error<'a>> { + ) -> Result<(), Error<'source>> { if op != crate::BinaryOperator::Multiply { self.grow_types(*left)?.grow_types(*right)?; @@ -291,18 +456,18 @@ impl<'a> ExpressionContext<'a, '_, '_> { match (left_size, self.resolved_inner(*right)) { (Some(size), &crate::TypeInner::Scalar { .. }) => { - *right = self.naga_expressions.append( + *right = self.append_expression( crate::Expression::Splat { size, value: *right, }, - self.naga_expressions.get_span(*right), + self.get_expression_span(*right), ); } (None, &crate::TypeInner::Vector { size, .. }) => { - *left = self.naga_expressions.append( + *left = self.append_expression( crate::Expression::Splat { size, value: *left }, - self.naga_expressions.get_span(*left), + self.get_expression_span(*left), ); } _ => {} @@ -321,10 +486,20 @@ impl<'a> ExpressionContext<'a, '_, '_> { expression: crate::Expression, span: Span, ) -> Handle { - self.block - .extend(self.emitter.finish(self.naga_expressions)); - let result = self.naga_expressions.append(expression, span); - self.emitter.start(self.naga_expressions); + match self.expr_type { + ExpressionContextType::Runtime(ref mut rctx) => { + rctx.block + .extend(rctx.emitter.finish(rctx.naga_expressions)); + } + ExpressionContextType::Constant => {} + } + let result = self.append_expression(expression, span); + match self.expr_type { + ExpressionContextType::Runtime(ref mut rctx) => { + rctx.emitter.start(rctx.naga_expressions); + } + ExpressionContextType::Constant => {} + } result } @@ -337,8 +512,8 @@ impl<'a> ExpressionContext<'a, '_, '_> { let load = crate::Expression::Load { pointer: expr.handle, }; - let span = self.naga_expressions.get_span(expr.handle); - self.naga_expressions.append(load, span) + let span = self.get_expression_span(expr.handle); + self.append_expression(load, span) } else { expr.handle } @@ -364,7 +539,7 @@ impl<'a> ExpressionContext<'a, '_, '_> { } fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { - self.as_output().ensure_type_exists(inner) + self.as_global().ensure_type_exists(inner) } } @@ -485,11 +660,6 @@ enum LoweredGlobalDecl { EntryPoint, } -enum ConstantOrInner { - Constant(Handle), - Inner(crate::ConstantInner), -} - enum Texture { Gather, GatherCompare, @@ -555,11 +725,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ) -> Result> { let mut module = crate::Module::default(); - let mut ctx = OutputContext { + let mut ctx = GlobalContext { ast_expressions: &tu.expressions, globals: &mut FastHashMap::default(), types: &tu.types, module: &mut module, + const_typifier: &mut Typifier::new(), }; for decl_handle in self.index.visit_ordered() { @@ -576,7 +747,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let init = v .init - .map(|init| self.constant(init, ctx.reborrow())) + .map(|init| self.expression(init, ctx.as_const())) .transpose()?; let handle = ctx.module.global_variables.append( @@ -594,30 +765,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .insert(v.name.name, LoweredGlobalDecl::Var(handle)); } ast::GlobalDeclKind::Const(ref c) => { - let inner = self.constant_inner(c.init, ctx.reborrow())?; - let inner = match inner { - ConstantOrInner::Constant(c) => ctx.module.constants[c].inner.clone(), - ConstantOrInner::Inner(inner) => inner, - }; - - let inferred_type = match inner { - crate::ConstantInner::Scalar { width, value } => { - ctx.ensure_type_exists(crate::TypeInner::Scalar { - width, - kind: value.scalar_kind(), - }) - } - crate::ConstantInner::Composite { ty, .. } => ty, - }; - - let handle = ctx.module.constants.append( - crate::Constant { - name: Some(c.name.name.to_string()), - specialization: None, - inner, - }, - span, - ); + let mut ectx = ctx.as_const(); + let init = self.expression(c.init, ectx.reborrow())?; + let inferred_type = ectx.register_type(init)?; let explicit_ty = c.ty.map(|ty| self.resolve_ast_type(ty, ctx.reborrow())) @@ -645,6 +795,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } } + let handle = ctx.module.constants.append( + crate::Constant { + name: Some(c.name.name.to_string()), + r#override: crate::Override::None, + ty: inferred_type, + init, + }, + span, + ); + ctx.globals .insert(c.name.name, LoweredGlobalDecl::Const(handle)); } @@ -668,7 +828,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, f: &ast::Function<'source>, span: Span, - mut ctx: OutputContext<'source, '_, '_>, + mut ctx: GlobalContext<'source, '_, '_>, ) -> Result> { let mut local_table = FastHashMap::default(); let mut local_variables = Arena::new(); @@ -713,6 +873,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { local_table: &mut local_table, globals: ctx.globals, ast_expressions: ctx.ast_expressions, + const_typifier: ctx.const_typifier, typifier: &mut typifier, variables: &mut local_variables, naga_expressions: &mut expressions, @@ -785,7 +946,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let value = self.expression(l.init, ctx.as_expression(block, &mut emitter))?; let explicit_ty = - l.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) + l.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_global())) .transpose()?; if let Some(ty) = explicit_ty { @@ -827,7 +988,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let explicit_ty = - v.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) + v.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_global())) .transpose()?; let ty = match (explicit_ty, initializer) { @@ -1021,7 +1182,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut ctx = ctx.as_expression(block, &mut emitter); let mut left = ctx.apply_load_rule(expr); ctx.binary_op_splat(op, &mut left, &mut value)?; - ctx.naga_expressions.append( + ctx.append_expression( crate::Expression::Binary { op, left, @@ -1068,32 +1229,24 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }, _ => return Err(Error::BadIncrDecrReferenceType(value_span)), }; - let constant_inner = crate::ConstantInner::Scalar { - width, - value: match kind { - crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), - crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), - _ => return Err(Error::BadIncrDecrReferenceType(value_span)), - }, + let literal = match kind { + crate::ScalarKind::Sint | crate::ScalarKind::Uint => { + crate::Literal::one(kind, width) + .ok_or(Error::BadIncrDecrReferenceType(value_span))? + } + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), }; - let constant = ectx.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: constant_inner, - }, - Span::UNDEFINED, - ); - let left = ectx.naga_expressions.append( + let right = + ectx.interrupt_emitter(crate::Expression::Literal(literal), Span::UNDEFINED); + let rctx = ectx.runtime_expression_ctx(stmt.span)?; + let left = rctx.naga_expressions.append( crate::Expression::Load { pointer: reference.handle, }, value_span, ); - let right = - ectx.interrupt_emitter(crate::Expression::Constant(constant), Span::UNDEFINED); - let value = ectx + let value = rctx .naga_expressions .append(crate::Expression::Binary { op, left, right }, stmt.span); @@ -1150,7 +1303,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { return Ok(TypedExpression::non_reference(handle)); } ast::Expression::Ident(ast::IdentExpr::Local(local)) => { - return Ok(ctx.local_table[&local]) + let rctx = ctx.runtime_expression_ctx(span)?; + return Ok(rctx.local_table[&local]); } ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { return if let Some(global) = ctx.globals.get(name) { @@ -1248,54 +1402,31 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { )); } - match ctx.naga_expressions[index] { - crate::Expression::Constant(constant) => { - let span = ctx.naga_expressions.get_span(index); - let index = match ctx.module.constants[constant].inner { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Sint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), - _ => Err(Error::BadU32Constant(span)), - }?; + if let crate::Expression::Literal(lit) = *ctx.get_expression(index) { + let span = ctx.get_expression_span(index); + let index = match lit { + crate::Literal::U32(index) => Ok(index), + crate::Literal::I32(index) => { + u32::try_from(index).map_err(|_| Error::BadU32Constant(span)) + } + _ => Err(Error::BadU32Constant(span)), + }?; - ( - crate::Expression::AccessIndex { - base: expr.handle, - index, - }, - expr.is_reference, - ) - } - crate::Expression::Literal(literal) => { - let span = ctx.naga_expressions.get_span(index); - let index = match literal { - crate::Literal::U32(n) => n, - crate::Literal::I32(n) => { - u32::try_from(n).map_err(|_| Error::BadU32Constant(span))? - } - _ => return Err(Error::BadU32Constant(span)), - }; - - ( - crate::Expression::AccessIndex { - base: expr.handle, - index, - }, - expr.is_reference, - ) - } - _ => ( + ( + crate::Expression::AccessIndex { + base: expr.handle, + index, + }, + expr.is_reference, + ) + } else { + ( crate::Expression::Access { base: expr.handle, index, }, expr.is_reference, - ), + ) } } ast::Expression::Member { base, ref field } => { @@ -1387,13 +1518,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::Expression::Bitcast { expr, to, ty_span } => { let expr = self.expression(expr, ctx.reborrow())?; - let to_resolved = self.resolve_ast_type(to, ctx.as_output())?; + let to_resolved = self.resolve_ast_type(to, ctx.as_global())?; let kind = match ctx.module.types[to_resolved].inner { crate::TypeInner::Scalar { kind, .. } => kind, crate::TypeInner::Vector { kind, .. } => kind, _ => { - let ty = &ctx.typifier[expr]; + let ty = &ctx.typifier()[expr]; return Err(Error::BadTypeCast { from_type: ctx.format_type_resolution(ty), span: ty_span, @@ -1413,7 +1544,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; - let handle = ctx.naga_expressions.append(expr, span); + let handle = ctx.append_expression(expr, span); Ok(TypedExpression { handle, is_reference, @@ -1466,13 +1597,17 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .map(|&arg| self.expression(arg, ctx.reborrow())) .collect::, _>>()?; - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - let result = ctx.module.functions[function].result.is_some().then(|| { - ctx.naga_expressions + let has_result = ctx.module.functions[function].result.is_some(); + let rctx = ctx.runtime_expression_ctx(span)?; + // we need to always do this before a fn call since all arguments need to be emitted before the fn call + rctx.block + .extend(rctx.emitter.finish(rctx.naga_expressions)); + let result = has_result.then(|| { + rctx.naga_expressions .append(crate::Expression::CallResult(function), span) }); - ctx.emitter.start(ctx.naga_expressions); - ctx.block.push( + rctx.emitter.start(rctx.naga_expressions); + rctx.block.push( crate::Statement::Call { function, arguments, @@ -1566,9 +1701,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let value = self.expression(args.next()?, ctx.reborrow())?; args.finish()?; - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - ctx.emitter.start(ctx.naga_expressions); - ctx.block + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block + .extend(rctx.emitter.finish(rctx.naga_expressions)); + rctx.emitter.start(rctx.naga_expressions); + rctx.block .push(crate::Statement::Store { pointer, value }, span); return Ok(None); } @@ -1664,7 +1801,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let result = ctx.interrupt_emitter(expression, span); - ctx.block.push( + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block.push( crate::Statement::Atomic { pointer, fun: crate::AtomicFunction::Exchange { @@ -1680,14 +1818,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { "storageBarrier" => { ctx.prepare_args(arguments, 0, span).finish()?; - ctx.block + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block .push(crate::Statement::Barrier(crate::Barrier::STORAGE), span); return Ok(None); } "workgroupBarrier" => { ctx.prepare_args(arguments, 0, span).finish()?; - ctx.block + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block .push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP), span); return Ok(None); } @@ -1713,7 +1853,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { crate::Expression::WorkGroupUniformLoadResult { ty: result_ty }, span, ); - ctx.block.push( + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block.push( crate::Statement::WorkGroupUniformLoad { pointer, result }, span, ); @@ -1739,15 +1880,17 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args.finish()?; - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - ctx.emitter.start(ctx.naga_expressions); + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block + .extend(rctx.emitter.finish(rctx.naga_expressions)); + rctx.emitter.start(rctx.naga_expressions); let stmt = crate::Statement::ImageStore { image, coordinate, array_index, value, }; - ctx.block.push(stmt, span); + rctx.block.push(stmt, span); return Ok(None); } "textureLoad" => { @@ -1843,9 +1986,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { descriptor, }; - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - ctx.emitter.start(ctx.naga_expressions); - ctx.block + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block + .extend(rctx.emitter.finish(rctx.naga_expressions)); + rctx.emitter.start(rctx.naga_expressions); + rctx.block .push(crate::Statement::RayQuery { query, fun }, span); return Ok(None); } @@ -1854,14 +1999,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let query = self.ray_query_pointer(args.next()?, ctx.reborrow())?; args.finish()?; - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); let result = ctx - .naga_expressions - .append(crate::Expression::RayQueryProceedResult, span); + .interrupt_emitter(crate::Expression::RayQueryProceedResult, span); let fun = crate::RayQueryFunction::Proceed { result }; - - ctx.emitter.start(ctx.naga_expressions); - ctx.block + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block .push(crate::Statement::RayQuery { query, fun }, span); return Ok(Some(result)); } @@ -1892,7 +2034,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; - let expr = ctx.naga_expressions.append(expr, span); + let expr = ctx.append_expression(expr, span); Ok(Some(expr)) } } @@ -1946,7 +2088,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }, span, ); - ctx.block.push( + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block.push( crate::Statement::Atomic { pointer, fun, @@ -1967,31 +2110,58 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ) -> Result> { let mut args = ctx.prepare_args(args, fun.min_argument_count(), span); - let (image, gather) = match fun { + fn get_image_and_span<'source>( + lowerer: &mut Lowerer<'source, '_>, + args: &mut ArgumentContext<'_, 'source>, + ctx: &mut ExpressionContext<'source, '_, '_>, + ) -> Result<(Handle, Span), Error<'source>> { + let image = args.next()?; + let image_span = ctx.ast_expressions.get_span(image); + let image = lowerer.expression(image, ctx.reborrow())?; + Ok((image, image_span)) + } + + let (image, image_span, gather) = match fun { Texture::Gather => { let image_or_component = args.next()?; - match self.gather_component(image_or_component, ctx.reborrow())? { - Some(component) => { - let image = args.next()?; - (image, Some(component)) + // Gathers from depth textures don't take an initial `component` argument. + let lowered_image_or_component = + self.expression(image_or_component, ctx.reborrow())?; + + ctx.grow_types(lowered_image_or_component)?; + match *ctx.resolved_inner(lowered_image_or_component) { + crate::TypeInner::Image { + class: crate::ImageClass::Depth { .. }, + .. + } => { + let image_span = ctx.ast_expressions.get_span(image_or_component); + ( + lowered_image_or_component, + image_span, + Some(crate::SwizzleComponent::X), + ) + } + _ => { + let (image, image_span) = get_image_and_span(self, &mut args, &mut ctx)?; + ( + image, + image_span, + Some(ctx.gather_component(lowered_image_or_component, span)?), + ) } - None => (image_or_component, Some(crate::SwizzleComponent::X)), } } Texture::GatherCompare => { - let image = args.next()?; - (image, Some(crate::SwizzleComponent::X)) + let (image, image_span) = get_image_and_span(self, &mut args, &mut ctx)?; + (image, image_span, Some(crate::SwizzleComponent::X)) } _ => { - let image = args.next()?; - (image, None) + let (image, image_span) = get_image_and_span(self, &mut args, &mut ctx)?; + (image, image_span, None) } }; - let image_span = ctx.ast_expressions.get_span(image); - let image = self.expression(image, ctx.reborrow())?; - let sampler = self.expression(args.next()?, ctx.reborrow())?; let coordinate = self.expression(args.next()?, ctx.reborrow())?; @@ -2034,7 +2204,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let offset = args .next() - .map(|arg| self.constant(arg, ctx.as_output())) + .map(|arg| self.expression(arg, ctx.as_const())) .ok() .transpose()?; @@ -2052,45 +2222,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }) } - fn gather_component( - &mut self, - expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let span = ctx.ast_expressions.get_span(expr); - - let constant = match self.constant_inner(expr, ctx.as_output()).ok() { - Some(ConstantOrInner::Constant(c)) => ctx.module.constants[c].inner.clone(), - Some(ConstantOrInner::Inner(inner)) => inner, - None => return Ok(None), - }; - - let int = match constant { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Sint(i), - .. - } if i >= 0 => i as u64, - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(i), - .. - } => i, - _ => { - return Err(Error::InvalidGatherComponent(span)); - } - }; - - crate::SwizzleComponent::XYZW - .get(int as usize) - .copied() - .map(Some) - .ok_or(Error::InvalidGatherComponent(span)) - } - fn r#struct( &mut self, s: &ast::Struct<'source>, span: Span, - mut ctx: OutputContext<'source, '_, '_>, + mut ctx: GlobalContext<'source, '_, '_>, ) -> Result, Error<'source>> { let mut offset = 0; let mut struct_alignment = Alignment::ONE; @@ -2163,7 +2299,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn resolve_ast_type( &mut self, handle: Handle>, - mut ctx: OutputContext<'source, '_, '_>, + mut ctx: GlobalContext<'source, '_, '_>, ) -> Result, Error<'source>> { let inner = match ctx.types[handle] { ast::Type::Scalar { kind, width } => crate::TypeInner::Scalar { kind, width }, @@ -2192,14 +2328,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { base, size: match size { ast::ArraySize::Constant(constant) => { - let span = ctx.ast_expressions.get_span(constant); - let constant = self.constant(constant, ctx.reborrow())?; - let size = ctx.module.constants[constant] - .to_array_length() - .ok_or(Error::ExpectedArraySize(span))?; - let size = - NonZeroU32::new(size).ok_or(Error::NonPositiveArrayLength(span))?; - crate::ArraySize::Constant(size) + let const_expr = self.expression(constant, ctx.as_const())?; + crate::ArraySize::Constant(ctx.as_const().array_length(const_expr)?) } ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, }, @@ -2225,14 +2355,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { base, size: match size { ast::ArraySize::Constant(constant) => { - let span = ctx.ast_expressions.get_span(constant); - let constant = self.constant(constant, ctx.reborrow())?; - let size = ctx.module.constants[constant] - .to_array_length() - .ok_or(Error::ExpectedArraySize(span))?; - let size = - NonZeroU32::new(size).ok_or(Error::NonPositiveArrayLength(span))?; - crate::ArraySize::Constant(size) + let const_expr = self.expression(constant, ctx.as_const())?; + crate::ArraySize::Constant(ctx.as_const().array_length(const_expr)?) } ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, }, @@ -2256,105 +2380,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok(ctx.ensure_type_exists(inner)) } - /// Find or construct a Naga [`Constant`] whose value is `expr`. - /// - /// The `ctx` indicates the Naga [`Module`] to which we should add - /// new `Constant`s or [`Type`]s as needed. - /// - /// [`Module`]: crate::Module - /// [`Constant`]: crate::Constant - /// [`Type`]: crate::Type - fn constant( - &mut self, - expr: Handle>, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let inner = match self.constant_inner(expr, ctx.reborrow())? { - ConstantOrInner::Constant(c) => return Ok(c), - ConstantOrInner::Inner(inner) => inner, - }; - - let c = ctx.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Span::UNDEFINED, - ); - Ok(c) - } - - fn constant_inner( - &mut self, - expr: Handle>, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result> { - let span = ctx.ast_expressions.get_span(expr); - let inner = match ctx.ast_expressions[expr] { - ast::Expression::Literal(literal) => match literal { - ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Float(f as _), - }, - ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Sint(i as _), - }, - ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(u as _), - }, - ast::Literal::Number(_) => { - unreachable!("got abstract numeric type when not expected"); - } - ast::Literal::Bool(b) => crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(b), - }, - }, - ast::Expression::Ident(ast::IdentExpr::Local(_)) => { - return Err(Error::Unexpected(span, ExpectedToken::Constant)) - } - ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { - return if let Some(global) = ctx.globals.get(name) { - match *global { - LoweredGlobalDecl::Const(handle) => Ok(ConstantOrInner::Constant(handle)), - _ => Err(Error::Unexpected(span, ExpectedToken::Constant)), - } - } else { - Err(Error::UnknownIdent(span, name)) - } - } - ast::Expression::Construct { - ref ty, - ref components, - .. - } => self.const_construct(span, ty, components, ctx.reborrow())?, - ast::Expression::Call { - ref function, - ref arguments, - } => match ctx.globals.get(function.name) { - Some(&LoweredGlobalDecl::Type(ty)) => self.const_construct( - span, - &ast::ConstructorType::Type(ty), - arguments, - ctx.reborrow(), - )?, - Some(_) => return Err(Error::ConstExprUnsupported(span)), - None => return Err(Error::UnknownIdent(function.span, function.name)), - }, - _ => return Err(Error::ConstExprUnsupported(span)), - }; - - Ok(ConstantOrInner::Inner(inner)) - } - fn interpolate_default( &mut self, binding: &Option, ty: Handle, - ctx: OutputContext<'source, '_, '_>, + ctx: GlobalContext<'source, '_, '_>, ) -> Option { let mut binding = binding.clone(); if let Some(ref mut binding) = binding { diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index b60f6fe65..2b471a8a9 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -198,6 +198,7 @@ impl crate::TypeInner { } mod type_inner_tests { + #[test] fn to_wgsl() { use std::num::NonZeroU32; @@ -228,6 +229,7 @@ mod type_inner_tests { let gctx = crate::proc::GlobalCtx { types: &types, constants: &crate::Arena::new(), + const_expressions: &crate::Arena::new(), }; let array = crate::TypeInner::Array { base: mytype1, diff --git a/src/front/wgsl/parse/ast.rs b/src/front/wgsl/parse/ast.rs index 2a56ac6f8..9b7670e4a 100644 --- a/src/front/wgsl/parse/ast.rs +++ b/src/front/wgsl/parse/ast.rs @@ -107,7 +107,7 @@ pub struct EntryPoint { } #[cfg(doc)] -use crate::front::wgsl::lower::{ExpressionContext, StatementContext}; +use crate::front::wgsl::lower::{RuntimeExpressionContext, StatementContext}; #[derive(Debug)] pub struct Function<'a> { @@ -132,14 +132,14 @@ pub struct Function<'a> { /// During lowering, [`LocalDecl`] statements add entries to a per-function /// table that maps `Handle` values to their Naga representations, /// accessed via [`StatementContext::local_table`] and - /// [`ExpressionContext::local_table`]. This table is then consulted when + /// [`RuntimeExpressionContext::local_table`]. This table is then consulted when /// lowering subsequent [`Ident`] expressions. /// /// [`LocalDecl`]: StatementKind::LocalDecl /// [`arguments`]: Function::arguments /// [`Ident`]: Expression::Ident /// [`StatementContext::local_table`]: StatementContext::local_table - /// [`ExpressionContext::local_table`]: ExpressionContext::local_table + /// [`RuntimeExpressionContext::local_table`]: RuntimeExpressionContext::local_table pub locals: Arena, pub body: Block<'a>, diff --git a/src/lib.rs b/src/lib.rs index 1148379c0..9cff798ae 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -796,18 +796,6 @@ pub enum TypeInner { BindingArray { base: Handle, size: ArraySize }, } -/// Constant value. -#[derive(Debug, PartialEq)] -#[cfg_attr(feature = "clone", derive(Clone))] -#[cfg_attr(feature = "serialize", derive(Serialize))] -#[cfg_attr(feature = "deserialize", derive(Deserialize))] -#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] -pub struct Constant { - pub name: Option, - pub specialization: Option, - pub inner: ConstantInner, -} - #[derive(Debug, Clone, Copy, PartialOrd)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] @@ -820,32 +808,29 @@ pub enum Literal { Bool(bool), } -/// A literal scalar value, used in constants. -#[derive(Debug, Clone, Copy, PartialOrd)] +#[derive(Debug, PartialEq)] +#[cfg_attr(feature = "clone", derive(Clone))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] -pub enum ScalarValue { - Sint(i64), - Uint(u64), - Float(f64), - Bool(bool), +pub enum Override { + None, + ByName, + ByNameOrId(u32), } -/// Additional information, dependent on the kind of constant. -#[derive(Clone, Debug, PartialEq)] +/// Constant value. +#[derive(Debug, PartialEq)] +#[cfg_attr(feature = "clone", derive(Clone))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] -pub enum ConstantInner { - Scalar { - width: Bytes, - value: ScalarValue, - }, - Composite { - ty: Handle, - components: Vec>, - }, +pub struct Constant { + pub name: Option, + pub r#override: Override, + pub ty: Handle, + /// Expression handle lives in const_expressions + pub init: Handle, } /// Describes how an input/output variable is to be bound. @@ -907,7 +892,9 @@ pub struct GlobalVariable { /// The type of this variable. pub ty: Handle, /// Initial value for this variable. - pub init: Option>, + /// + /// Expression handle lives in const_expressions + pub init: Option>, } /// Variable defined at function level. @@ -921,7 +908,9 @@ pub struct LocalVariable { /// The type of this variable. pub ty: Handle, /// Initial value for this variable. - pub init: Option>, + /// + /// Expression handle lives in const_expressions + pub init: Option>, } /// Operation that can be applied on a single value. @@ -1224,6 +1213,11 @@ pub enum Expression { Constant(Handle), /// Zero value of a type. ZeroValue(Handle), + /// Composite expression. + Compose { + ty: Handle, + components: Vec>, + }, /// Array access with a computed index. /// @@ -1294,11 +1288,6 @@ pub enum Expression { vector: Handle, pattern: [SwizzleComponent; 4], }, - /// Composite expression. - Compose { - ty: Handle, - components: Vec>, - }, /// Reference a function parameter, by its index. /// @@ -1347,7 +1336,8 @@ pub enum Expression { gather: Option, coordinate: Handle, array_index: Option>, - offset: Option>, + /// Expression handle lives in const_expressions + offset: Option>, level: SampleLevel, depth_ref: Option>, }, @@ -1448,7 +1438,6 @@ pub enum Expression { Derivative { axis: DerivativeAxis, ctrl: DerivativeControl, - //modifier, expr: Handle, }, /// Call a relational function. @@ -1510,7 +1499,6 @@ pub enum Expression { pub use block::Block; /// The value of the switch case. -// Clone is used only for error reporting and is not intended for end users #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] @@ -1619,7 +1607,7 @@ pub enum Statement { /// [`body`]: SwitchCase::body /// [`Default`]: SwitchValue::Default Switch { - selector: Handle, //int + selector: Handle, cases: Vec, }, @@ -1939,6 +1927,11 @@ pub struct Module { pub constants: Arena, /// Arena for the global variables defined in this module. pub global_variables: Arena, + /// const/override-expressions used by this module. + /// + /// An `Expression` must occur before all other `Expression`s that use its + /// value. + pub const_expressions: Arena, /// Arena for the functions defined in this module. /// /// Each function must appear in this arena strictly before all its callers. diff --git a/src/proc/index.rs b/src/proc/index.rs index 62d75e0db..af3221c0f 100644 --- a/src/proc/index.rs +++ b/src/proc/index.rs @@ -340,22 +340,16 @@ pub fn access_needs_check( } impl GuardedIndex { - /// Make A `GuardedIndex::Known` from a `GuardedIndex::Expression` if possible. - /// - /// If the expression is a [`Constant`] whose value is a non-specialized, scalar - /// integer constant that can be converted to a `u32`, do so and return a - /// `GuardedIndex::Known`. Otherwise, return the `GuardedIndex::Expression` - /// unchanged. + /// Make a `GuardedIndex::Known` from a `GuardedIndex::Expression` if possible. /// /// Return values that are already `Known` unchanged. - /// - /// [`Constant`]: crate::Expression::Constant fn try_resolve_to_constant(&mut self, function: &crate::Function, module: &crate::Module) { if let GuardedIndex::Expression(expr) = *self { - if let crate::Expression::Constant(handle) = function.expressions[expr] { - if let Some(value) = module.constants[handle].to_array_length() { - *self = GuardedIndex::Known(value); - } + if let Ok(value) = module + .to_ctx() + .eval_expr_to_u32_from(expr, &function.expressions) + { + *self = GuardedIndex::Known(value); } } } @@ -366,7 +360,7 @@ pub enum IndexableLengthError { #[error("Type is not indexable, and has no length (validation error)")] TypeNotIndexable, #[error("Array length constant {0:?} is invalid")] - InvalidArrayLength(Handle), + InvalidArrayLength(Handle), } impl crate::TypeInner { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c61fbdd93..582c88703 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -8,8 +8,6 @@ mod namer; mod terminator; mod typifier; -use std::cmp::PartialEq; - pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength, IndexableLengthError}; pub use layouter::{Alignment, LayoutError, LayoutErrorInner, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; @@ -62,17 +60,6 @@ impl From for super::ScalarKind { } } -impl super::ScalarValue { - pub const fn scalar_kind(&self) -> super::ScalarKind { - match *self { - Self::Uint(_) => super::ScalarKind::Uint, - Self::Sint(_) => super::ScalarKind::Sint, - Self::Float(_) => super::ScalarKind::Float, - Self::Bool(_) => super::ScalarKind::Bool, - } - } -} - impl super::ScalarKind { pub const fn is_numeric(self) -> bool { match self { @@ -135,17 +122,6 @@ impl crate::Literal { } } - pub const fn from_scalar(scalar: crate::ScalarValue, width: crate::Bytes) -> Option { - match (scalar, width) { - (crate::ScalarValue::Sint(n), 4) => Some(Self::I32(n as _)), - (crate::ScalarValue::Uint(n), 4) => Some(Self::U32(n as _)), - (crate::ScalarValue::Float(n), 4) => Some(Self::F32(n as _)), - (crate::ScalarValue::Float(n), 8) => Some(Self::F64(n)), - (crate::ScalarValue::Bool(b), _) => Some(Self::Bool(b)), - _ => None, - } - } - pub const fn zero(kind: crate::ScalarKind, width: crate::Bytes) -> Option { Self::new(0, kind, width) } @@ -209,6 +185,16 @@ impl super::TypeInner { } } + pub fn is_atomic_pointer(&self, types: &crate::UniqueArena) -> bool { + match *self { + crate::TypeInner::Pointer { base, .. } => match types[base].inner { + crate::TypeInner::Atomic { .. } => true, + _ => false, + }, + _ => false, + } + } + /// Get the size of this type. pub fn size(&self, _gctx: GlobalCtx) -> u32 { match *self { @@ -308,6 +294,39 @@ impl super::TypeInner { _ => false, } } + + pub fn components(&self) -> Option { + Some(match *self { + Self::Vector { size, .. } => size as u32, + Self::Matrix { columns, .. } => columns as u32, + Self::Array { + size: crate::ArraySize::Constant(len), + .. + } => len.get(), + Self::Struct { ref members, .. } => members.len() as u32, + _ => return None, + }) + } + + pub fn component_type(&self, index: usize) -> Option { + Some(match *self { + Self::Vector { kind, width, .. } => { + TypeResolution::Value(crate::TypeInner::Scalar { kind, width }) + } + Self::Matrix { rows, width, .. } => TypeResolution::Value(crate::TypeInner::Vector { + size: rows, + kind: crate::ScalarKind::Float, + width, + }), + Self::Array { + base, + size: crate::ArraySize::Constant(_), + .. + } => TypeResolution::Handle(base), + Self::Struct { ref members, .. } => TypeResolution::Handle(members[index].ty), + _ => return None, + }) + } } impl super::AddressSpace { @@ -441,7 +460,7 @@ impl crate::Expression { pub fn is_dynamic_index(&self, module: &crate::Module) -> bool { if let Self::Constant(handle) = *self { let constant = &module.constants[handle]; - constant.specialization.is_some() + !matches!(constant.r#override, crate::Override::None) } else { true } @@ -484,36 +503,6 @@ impl crate::SampleLevel { } } -impl crate::Constant { - /// Interpret this constant as an array length, and return it as a `u32`. - /// - /// Ignore any specialization available for this constant; return its - /// unspecialized value. - /// - /// If the constant has an inappropriate kind (non-scalar or non-integer) or - /// value (negative, out of range for u32), return `None`. This usually - /// indicates an error, but only the caller has enough information to report - /// the error helpfully: in back ends, it's a validation error, but in front - /// ends, it may indicate ill-formed input (for example, a SPIR-V - /// `OpArrayType` referring to an inappropriate `OpConstant`). So we return - /// `Option` and let the caller sort things out. - pub(crate) fn to_array_length(&self) -> Option { - match self.inner { - crate::ConstantInner::Scalar { value, width: _ } => match value { - crate::ScalarValue::Uint(value) => value.try_into().ok(), - // Accept a signed integer size to avoid - // requiring an explicit uint - // literal. Type inference should make - // this unnecessary. - crate::ScalarValue::Sint(value) => value.try_into().ok(), - _ => None, - }, - // caught by type validation - crate::ConstantInner::Composite { .. } => None, - } - } -} - impl crate::Binding { pub const fn to_built_in(&self) -> Option { match *self { @@ -523,30 +512,6 @@ impl crate::Binding { } } -//TODO: should we use an existing crate for hashable floats? -impl PartialEq for crate::ScalarValue { - fn eq(&self, other: &Self) -> bool { - match (*self, *other) { - (Self::Uint(a), Self::Uint(b)) => a == b, - (Self::Sint(a), Self::Sint(b)) => a == b, - (Self::Float(a), Self::Float(b)) => a.to_bits() == b.to_bits(), - (Self::Bool(a), Self::Bool(b)) => a == b, - _ => false, - } - } -} -impl Eq for crate::ScalarValue {} -impl std::hash::Hash for crate::ScalarValue { - fn hash(&self, hasher: &mut H) { - match *self { - Self::Sint(v) => v.hash(hasher), - Self::Uint(v) => v.hash(hasher), - Self::Float(v) => v.to_bits().hash(hasher), - Self::Bool(v) => v.hash(hasher), - } - } -} - impl super::SwizzleComponent { pub const XYZW: [Self; 4] = [Self::X, Self::Y, Self::Z, Self::W]; @@ -589,14 +554,71 @@ impl crate::Module { GlobalCtx { types: &self.types, constants: &self.constants, + const_expressions: &self.const_expressions, } } } +#[derive(Debug)] +pub(super) enum U32EvalError { + NonConst, + Negative, +} + #[derive(Clone, Copy)] pub struct GlobalCtx<'a> { pub types: &'a crate::UniqueArena, pub constants: &'a crate::Arena, + pub const_expressions: &'a crate::Arena, +} + +impl GlobalCtx<'_> { + /// Try to evaluate the expression in `self.const_expressions` using its `handle` and return it as a `u32`. + #[allow(dead_code)] + pub(super) fn eval_expr_to_u32( + &self, + handle: crate::Handle, + ) -> Result { + self.eval_expr_to_u32_from(handle, self.const_expressions) + } + + /// Try to evaluate the expression in the `arena` using its `handle` and return it as a `u32`. + pub(super) fn eval_expr_to_u32_from( + &self, + handle: crate::Handle, + arena: &crate::Arena, + ) -> Result { + fn get( + gctx: GlobalCtx, + handle: crate::Handle, + arena: &crate::Arena, + ) -> Result { + match arena[handle] { + crate::Expression::Literal(crate::Literal::U32(value)) => Ok(value), + crate::Expression::Literal(crate::Literal::I32(value)) => { + value.try_into().map_err(|_| U32EvalError::Negative) + } + crate::Expression::ZeroValue(ty) + if matches!( + gctx.types[ty].inner, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint, + width: _ + } + ) => + { + Ok(0) + } + _ => Err(U32EvalError::NonConst), + } + } + match arena[handle] { + crate::Expression::Constant(c) => { + get(*self, self.constants[c].init, self.const_expressions) + } + _ => get(*self, handle, arena), + } + } } #[test] diff --git a/src/proc/namer.rs b/src/proc/namer.rs index de98f601c..2f262d7d5 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -225,43 +225,7 @@ impl Namer { use std::fmt::Write; // Try to be more descriptive about the constant values temp.clear(); - match constant.inner { - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Sint(v), - } => write!(temp, "const_{v}i"), - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Uint(v), - } => write!(temp, "const_{v}u"), - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Float(v), - } => { - let abs = v.abs(); - write!( - temp, - "const_{}{}", - if v < 0.0 { "n" } else { "" }, - abs.trunc(), - ) - .unwrap(); - let fract = abs.fract(); - if fract == 0.0 { - write!(temp, "f") - } else { - write!(temp, "_{:02}f", (fract * 100.0) as i8) - } - } - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Bool(v), - } => write!(temp, "const_{v}"), - crate::ConstantInner::Composite { ty, components: _ } => { - write!(temp, "const_{}", output[&NameKey::Type(ty)]) - } - } - .unwrap(); + write!(temp, "const_{}", output[&NameKey::Type(constant.ty)]).unwrap(); &temp } }; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index f0030f340..6b79e0ead 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -148,18 +148,6 @@ impl Clone for TypeResolution { } } -impl crate::ConstantInner { - pub const fn resolve_type(&self) -> TypeResolution { - match *self { - Self::Scalar { width, ref value } => TypeResolution::Value(crate::TypeInner::Scalar { - kind: value.scalar_kind(), - width, - }), - Self::Composite { ty, components: _ } => TypeResolution::Handle(ty), - } - } -} - #[derive(Clone, Debug, Error, PartialEq)] pub enum ResolveError { #[error("Index {index} is out of bounds for expression {expr:?}")] @@ -421,17 +409,6 @@ impl<'a> ResolveContext<'a> { } } } - crate::Expression::Literal(lit) => TypeResolution::Value(lit.ty_inner()), - crate::Expression::Constant(h) => match self.constants[h].inner { - crate::ConstantInner::Scalar { width, ref value } => { - TypeResolution::Value(Ti::Scalar { - kind: value.scalar_kind(), - width, - }) - } - crate::ConstantInner::Composite { ty, components: _ } => TypeResolution::Handle(ty), - }, - crate::Expression::ZeroValue(ty) => TypeResolution::Handle(ty), crate::Expression::Splat { size, value } => match *past(value)?.inner_with(types) { Ti::Scalar { kind, width } => { TypeResolution::Value(Ti::Vector { size, kind, width }) @@ -456,6 +433,9 @@ impl<'a> ResolveContext<'a> { return Err(ResolveError::InvalidVector(vector)); } }, + crate::Expression::Literal(lit) => TypeResolution::Value(lit.ty_inner()), + crate::Expression::Constant(h) => TypeResolution::Handle(self.constants[h].ty), + crate::Expression::ZeroValue(ty) => TypeResolution::Handle(ty), crate::Expression::Compose { ty, .. } => TypeResolution::Handle(ty), crate::Expression::FunctionArgument(index) => { let arg = self diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 8ce63eaf3..1e75c5af6 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -495,7 +495,6 @@ impl FunctionInfo { requirements: UniformityRequirements::empty(), }, // always uniform - E::Literal(_) | E::Constant(_) | E::ZeroValue(_) => Uniformity::new(), E::Splat { size: _, value } => Uniformity { non_uniform_result: self.add_ref(value), requirements: UniformityRequirements::empty(), @@ -504,6 +503,7 @@ impl FunctionInfo { non_uniform_result: self.add_ref(vector), requirements: UniformityRequirements::empty(), }, + E::Literal(_) | E::Constant(_) | E::ZeroValue(_) => Uniformity::new(), E::Compose { ref components, .. } => { let non_uniform_result = components .iter() @@ -969,6 +969,18 @@ impl FunctionInfo { } impl ModuleInfo { + /// Populates `self.const_expression_types` + pub(super) fn process_const_expression( + &mut self, + handle: Handle, + resolve_context: &ResolveContext, + gctx: crate::proc::GlobalCtx, + ) -> Result<(), super::ConstExpressionError> { + self.const_expression_types[handle.index()] = + resolve_context.resolve(&gctx.const_expressions[handle], |h| Ok(&self[h]))?; + Ok(()) + } + /// Builds the `FunctionInfo` based on the function, and validates the /// uniform control flow if required by the expressions of this function. pub(super) fn process_function( @@ -1022,18 +1034,6 @@ impl ModuleInfo { fn uniform_control_flow() { use crate::{Expression as E, Statement as S}; - let mut constant_arena = Arena::new(); - let constant = constant_arena.append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(0), - }, - }, - Default::default(), - ); let mut type_arena = crate::UniqueArena::new(); let ty = type_arena.insert( crate::Type { @@ -1070,7 +1070,7 @@ fn uniform_control_flow() { let mut expressions = Arena::new(); // checks the uniform control flow - let constant_expr = expressions.append(E::Constant(constant), Default::default()); + let constant_expr = expressions.append(E::Literal(crate::Literal::U32(0)), Default::default()); // checks the non-uniform control flow let derivative_expr = expressions.append( E::Derivative { @@ -1110,7 +1110,7 @@ fn uniform_control_flow() { sampling: crate::FastHashSet::default(), }; let resolve_context = ResolveContext { - constants: &constant_arena, + constants: &Arena::new(), types: &type_arena, special_types: &crate::SpecialTypes::default(), global_vars: &global_var_arena, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 071c1a499..1703d213e 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1,7 +1,7 @@ #[cfg(feature = "validate")] use super::{ - compose::validate_compose, validate_atomic_compare_exchange_struct, FunctionInfo, ShaderStages, - TypeFlags, + compose::validate_compose, validate_atomic_compare_exchange_struct, FunctionInfo, ModuleInfo, + ShaderStages, TypeFlags, }; #[cfg(feature = "validate")] use crate::arena::UniqueArena; @@ -22,8 +22,10 @@ pub enum ExpressionError { InvalidBaseType(Handle), #[error("Accessing with index {0:?} can't be done")] InvalidIndexType(Handle), - #[error("Accessing index {1:?} is out of {0:?} bounds")] - IndexOutOfBounds(Handle, crate::ScalarValue), + #[error("Accessing {0:?} via a negative index is invalid")] + NegativeIndex(Handle), + #[error("Accessing index {1} is out of {0:?} bounds")] + IndexOutOfBounds(Handle, u32), #[error("The expression {0:?} may only be indexed by a constant")] IndexMustBeConstant(Handle), #[error("Function argument {0:?} doesn't exist")] @@ -91,7 +93,7 @@ pub enum ExpressionError { has_ref: bool, }, #[error("Sample offset constant {1:?} doesn't match the image dimension {0:?}")] - InvalidSampleOffset(crate::ImageDimension, Handle), + InvalidSampleOffset(crate::ImageDimension, Handle), #[error("Depth reference {0:?} is not a scalar float")] InvalidDepthReference(Handle), #[error("Depth sample level can only be Auto or Zero")] @@ -151,6 +153,29 @@ impl<'a> std::ops::Index> for ExpressionTypeResolver<' #[cfg(feature = "validate")] impl super::Validator { + pub(super) fn validate_const_expression( + &self, + handle: Handle, + gctx: crate::proc::GlobalCtx, + mod_info: &mut ModuleInfo, + ) -> Result<(), super::ConstExpressionError> { + use crate::Expression as E; + + match gctx.const_expressions[handle] { + E::Literal(_) | E::Constant(_) | E::ZeroValue(_) => {} + E::Compose { ref components, ty } => { + validate_compose( + ty, + gctx, + components.iter().map(|&handle| mod_info[handle].clone()), + )?; + } + _ => return Err(super::ConstExpressionError::NonConst), + } + + Ok(()) + } + pub(super) fn validate_expression( &self, root: Handle, @@ -158,7 +183,7 @@ impl super::Validator { function: &crate::Function, module: &crate::Module, info: &FunctionInfo, - other_infos: &[FunctionInfo], + mod_info: &ModuleInfo, ) -> Result { use crate::{Expression as E, ScalarKind as Sk, TypeInner as Ti}; @@ -205,27 +230,19 @@ impl super::Validator { if let crate::proc::IndexableLength::Known(known_length) = base_type.indexable_length(module)? { - if let E::Constant(k) = function.expressions[index] { - if let crate::Constant { - // We must treat specializable constants as unknown. - specialization: None, - // Non-scalar indices should have been caught above. - inner: crate::ConstantInner::Scalar { value, .. }, - .. - } = module.constants[k] - { - match value { - crate::ScalarValue::Uint(u) if u >= known_length as u64 => { - return Err(ExpressionError::IndexOutOfBounds(base, value)); - } - crate::ScalarValue::Sint(s) - if s < 0 || s >= known_length as i64 => - { - return Err(ExpressionError::IndexOutOfBounds(base, value)); - } - _ => (), + match module + .to_ctx() + .eval_expr_to_u32_from(index, &function.expressions) + { + Ok(value) => { + if value >= known_length { + return Err(ExpressionError::IndexOutOfBounds(base, value)); } } + Err(crate::proc::U32EvalError::Negative) => { + return Err(ExpressionError::NegativeIndex(base)) + } + Err(crate::proc::U32EvalError::NonConst) => {} } } @@ -263,16 +280,10 @@ impl super::Validator { let limit = resolve_index_limit(module, base, &resolver[base], true)?; if index >= limit { - return Err(ExpressionError::IndexOutOfBounds( - base, - crate::ScalarValue::Uint(limit as _), - )); + return Err(ExpressionError::IndexOutOfBounds(base, limit)); } ShaderStages::all() } - E::Literal(_value) => ShaderStages::all(), - E::Constant(_handle) => ShaderStages::all(), - E::ZeroValue(_type) => ShaderStages::all(), E::Splat { size: _, value } => match resolver[value] { Ti::Scalar { .. } => ShaderStages::all(), ref other => { @@ -299,6 +310,7 @@ impl super::Validator { } ShaderStages::all() } + E::Literal(_) | E::Constant(_) | E::ZeroValue(_) => ShaderStages::all(), E::Compose { ref components, ty } => { validate_compose( ty, @@ -412,26 +424,17 @@ impl super::Validator { } // check constant offset - if let Some(const_handle) = offset { - let good = match module.constants[const_handle].inner { - crate::ConstantInner::Scalar { - width: _, - value: crate::ScalarValue::Sint(_), - } => num_components == 1, - crate::ConstantInner::Scalar { .. } => false, - crate::ConstantInner::Composite { ty, .. } => { - match module.types[ty].inner { - Ti::Vector { - size, - kind: Sk::Sint, - .. - } => size as u32 == num_components, - _ => false, - } + if let Some(const_expr) = offset { + match *mod_info[const_expr].inner_with(&module.types) { + Ti::Scalar { kind: Sk::Sint, .. } if num_components == 1 => {} + Ti::Vector { + size, + kind: Sk::Sint, + .. + } if size as u32 == num_components => {} + _ => { + return Err(ExpressionError::InvalidSampleOffset(dim, const_expr)); } - }; - if !good { - return Err(ExpressionError::InvalidSampleOffset(dim, const_handle)); } } @@ -1388,7 +1391,7 @@ impl super::Validator { } ShaderStages::all() } - E::CallResult(function) => other_infos[function.index()].available_stages, + E::CallResult(function) => mod_info.functions[function.index()].available_stages, E::AtomicResult { ty, comparison } => { let scalar_predicate = |ty: &crate::TypeInner| match ty { &crate::TypeInner::Scalar { diff --git a/src/valid/function.rs b/src/valid/function.rs index 41f31b565..06aa27c84 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -941,6 +941,7 @@ impl super::Validator { &self, var: &crate::LocalVariable, gctx: crate::proc::GlobalCtx, + mod_info: &ModuleInfo, ) -> Result<(), LocalVariableError> { log::debug!("var {:?}", var); let type_info = self @@ -954,24 +955,14 @@ impl super::Validator { return Err(LocalVariableError::InvalidType(var.ty)); } - if let Some(const_handle) = var.init { - match gctx.constants[const_handle].inner { - crate::ConstantInner::Scalar { width, ref value } => { - let ty_inner = crate::TypeInner::Scalar { - width, - kind: value.scalar_kind(), - }; - if gctx.types[var.ty].inner != ty_inner { - return Err(LocalVariableError::InitializerType); - } - } - crate::ConstantInner::Composite { ty, components: _ } => { - if ty != var.ty { - return Err(LocalVariableError::InitializerType); - } - } + if let Some(init) = var.init { + let decl_ty = &gctx.types[var.ty].inner; + let init_ty = mod_info[init].inner_with(gctx.types); + if !decl_ty.equivalent(init_ty, gctx.types) { + return Err(LocalVariableError::InitializerType); } } + Ok(()) } @@ -987,7 +978,7 @@ impl super::Validator { #[cfg(feature = "validate")] for (var_handle, var) in fun.local_variables.iter() { - self.validate_local_var(var, module.to_ctx()) + self.validate_local_var(var, module.to_ctx(), mod_info) .map_err(|source| { FunctionError::LocalVariable { handle: var_handle, @@ -1061,14 +1052,7 @@ impl super::Validator { } #[cfg(feature = "validate")] if self.flags.contains(super::ValidationFlags::EXPRESSIONS) { - match self.validate_expression( - handle, - expr, - fun, - module, - &info, - &mod_info.functions, - ) { + match self.validate_expression(handle, expr, fun, module, &info, mod_info) { Ok(stages) => info.available_stages &= stages, Err(source) => { return Err(FunctionError::Expression { handle, source } diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 2b0d10762..3ec062415 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -40,6 +40,7 @@ impl super::Validator { ref global_variables, ref types, ref special_types, + ref const_expressions, } = module; // NOTE: Types being first is important. All other forms of validation depend on this. @@ -70,24 +71,24 @@ impl super::Validator { } } - let validate_type = |handle| Self::validate_type_handle(handle, types); - - for (this_handle, constant) in constants.iter() { - let &crate::Constant { - name: _, - specialization: _, - ref inner, - } = constant; - match *inner { - crate::ConstantInner::Scalar { .. } => (), - crate::ConstantInner::Composite { ty, ref components } => { - validate_type(ty)?; - this_handle.check_dep_iter(components.iter().copied())?; - } - } + for handle_and_expr in const_expressions.iter() { + Self::validate_const_expression_handles(handle_and_expr, constants, types)?; } - let validate_constant = |handle| Self::validate_constant_handle(handle, constants); + let validate_type = |handle| Self::validate_type_handle(handle, types); + let validate_const_expr = + |handle| Self::validate_expression_handle(handle, const_expressions); + + for (_handle, constant) in constants.iter() { + let &crate::Constant { + name: _, + r#override: _, + ty, + init, + } = constant; + validate_type(ty)?; + validate_const_expr(init)?; + } for (_handle, global_variable) in global_variables.iter() { let &crate::GlobalVariable { @@ -99,7 +100,7 @@ impl super::Validator { } = global_variable; validate_type(ty)?; if let Some(init_expr) = init { - validate_constant(init_expr)?; + validate_const_expr(init_expr)?; } } @@ -131,7 +132,7 @@ impl super::Validator { let &crate::LocalVariable { name: _, ty, init } = local_variable; validate_type(ty)?; if let Some(init_constant) = init { - validate_constant(init_constant)?; + validate_const_expr(init_constant)?; } } @@ -143,6 +144,7 @@ impl super::Validator { Self::validate_expression_handles( handle_and_expr, constants, + const_expressions, types, local_variables, global_variables, @@ -202,9 +204,36 @@ impl super::Validator { handle.check_valid_for(functions).map(|_| ()) } + fn validate_const_expression_handles( + (handle, expression): (Handle, &crate::Expression), + constants: &Arena, + types: &UniqueArena, + ) -> Result<(), InvalidHandleError> { + let validate_constant = |handle| Self::validate_constant_handle(handle, constants); + let validate_type = |handle| Self::validate_type_handle(handle, types); + + match *expression { + crate::Expression::Literal(_) => {} + crate::Expression::Constant(constant) => { + validate_constant(constant)?; + } + crate::Expression::ZeroValue(ty) => { + validate_type(ty)?; + } + crate::Expression::Compose { ty, ref components } => { + validate_type(ty)?; + handle.check_dep_iter(components.iter().copied())?; + } + _ => {} + } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] fn validate_expression_handles( (handle, expression): (Handle, &crate::Expression), constants: &Arena, + const_expressions: &Arena, types: &UniqueArena, local_variables: &Arena, global_variables: &Arena, @@ -213,6 +242,8 @@ impl super::Validator { current_function: Option>, ) -> Result<(), InvalidHandleError> { let validate_constant = |handle| Self::validate_constant_handle(handle, constants); + let validate_const_expr = + |handle| Self::validate_expression_handle(handle, const_expressions); let validate_type = |handle| Self::validate_type_handle(handle, types); match *expression { @@ -222,19 +253,19 @@ impl super::Validator { crate::Expression::AccessIndex { base, .. } => { handle.check_dep(base)?; } - crate::Expression::Literal(_value) => {} - crate::Expression::Constant(constant) => { - validate_constant(constant)?; - } - crate::Expression::ZeroValue(ty) => { - validate_type(ty)?; - } crate::Expression::Splat { value, .. } => { handle.check_dep(value)?; } crate::Expression::Swizzle { vector, .. } => { handle.check_dep(vector)?; } + crate::Expression::Literal(_) => {} + crate::Expression::Constant(constant) => { + validate_constant(constant)?; + } + crate::Expression::ZeroValue(ty) => { + validate_type(ty)?; + } crate::Expression::Compose { ty, ref components } => { validate_type(ty)?; handle.check_dep_iter(components.iter().copied())?; @@ -260,7 +291,7 @@ impl super::Validator { depth_ref, } => { if let Some(offset) = offset { - validate_constant(offset)?; + validate_const_expr(offset)?; } handle diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 47e2f201c..f1f9548a7 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -31,6 +31,8 @@ pub enum GlobalVariableError { Handle, #[source] Disalignment, ), + #[error("Initializer doesn't match the variable type")] + InitializerType, } #[derive(Clone, Debug, thiserror::Error)] @@ -396,6 +398,7 @@ impl super::Validator { &self, var: &crate::GlobalVariable, gctx: crate::proc::GlobalCtx, + mod_info: &ModuleInfo, ) -> Result<(), GlobalVariableError> { use super::TypeFlags; @@ -509,6 +512,14 @@ impl super::Validator { } } + if let Some(init) = var.init { + let decl_ty = &gctx.types[var.ty].inner; + let init_ty = mod_info[init].inner_with(gctx.types); + if !decl_ty.equivalent(init_ty, gctx.types) { + return Err(GlobalVariableError::InitializerType); + } + } + Ok(()) } diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 2c83e1a8d..b04d69b5b 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -10,12 +10,9 @@ mod handles; mod interface; mod r#type; -#[cfg(feature = "validate")] -use crate::arena::UniqueArena; - use crate::{ arena::Handle, - proc::{LayoutError, Layouter}, + proc::{LayoutError, Layouter, TypeResolution}, FastHashSet, }; use bit_set::BitSet; @@ -143,6 +140,7 @@ pub struct ModuleInfo { type_flags: Vec, functions: Vec, entry_points: Vec, + const_expression_types: Box<[TypeResolution]>, } impl ops::Index> for ModuleInfo { @@ -159,6 +157,13 @@ impl ops::Index> for ModuleInfo { } } +impl ops::Index> for ModuleInfo { + type Output = TypeResolution; + fn index(&self, handle: Handle) -> &Self::Output { + &self.const_expression_types[handle.index()] + } +} + #[derive(Debug)] pub struct Validator { flags: ValidationFlags, @@ -173,12 +178,22 @@ pub struct Validator { valid_expression_set: BitSet, } +#[derive(Clone, Debug, thiserror::Error)] +pub enum ConstExpressionError { + #[error("The expression is not a constant expression")] + NonConst, + #[error(transparent)] + Compose(#[from] ComposeError), + #[error("Type resolution failed")] + Type(#[from] crate::proc::ResolveError), +} + #[derive(Clone, Debug, thiserror::Error)] pub enum ConstantError { #[error("The type doesn't match the constant")] InvalidType, - #[error(transparent)] - Compose(#[from] ComposeError), + #[error("The type is not constructible")] + NonConstructibleType, } #[derive(Clone, Debug, thiserror::Error)] @@ -193,6 +208,11 @@ pub enum ValidationError { name: String, source: TypeError, }, + #[error("Constant expression {handle:?} is invalid")] + ConstExpression { + handle: Handle, + source: ConstExpressionError, + }, #[error("Constant {handle:?} '{name}' is invalid")] Constant { handle: Handle, @@ -300,24 +320,21 @@ impl Validator { &self, handle: Handle, gctx: crate::proc::GlobalCtx, + mod_info: &ModuleInfo, ) -> Result<(), ConstantError> { let con = &gctx.constants[handle]; - match con.inner { - crate::ConstantInner::Scalar { width, ref value } => { - if self.check_width(value.scalar_kind(), width).is_err() { - return Err(ConstantError::InvalidType); - } - } - crate::ConstantInner::Composite { ty, ref components } => { - compose::validate_compose( - ty, - gctx, - components - .iter() - .map(|&component| gctx.constants[component].inner.resolve_type()), - )?; - } + + let type_info = &self.types[con.ty.index()]; + if !type_info.flags.contains(TypeFlags::CONSTRUCTIBLE) { + return Err(ConstantError::NonConstructibleType); } + + let decl_ty = &gctx.types[con.ty].inner; + let init_ty = mod_info[con.init].inner_with(gctx.types); + if !decl_ty.equivalent(init_ty, gctx.types) { + return Err(ConstantError::InvalidType); + } + Ok(()) } @@ -337,25 +354,17 @@ impl Validator { ValidationError::from(e).with_span_handle(handle, &module.types) })?; - #[cfg(feature = "validate")] - if self.flags.contains(ValidationFlags::CONSTANTS) { - for (handle, constant) in module.constants.iter() { - self.validate_constant(handle, module.to_ctx()) - .map_err(|source| { - ValidationError::Constant { - handle, - name: constant.name.clone().unwrap_or_default(), - source, - } - .with_span_handle(handle, &module.constants) - })? - } - } + let placeholder = TypeResolution::Value(crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: 0, + }); let mut mod_info = ModuleInfo { type_flags: Vec::with_capacity(module.types.len()), functions: Vec::with_capacity(module.functions.len()), entry_points: Vec::with_capacity(module.entry_points.len()), + const_expression_types: vec![placeholder; module.const_expressions.len()] + .into_boxed_slice(), }; for (handle, ty) in module.types.iter() { @@ -373,9 +382,45 @@ impl Validator { self.types[handle.index()] = ty_info; } + { + let t = crate::Arena::new(); + let resolve_context = crate::proc::ResolveContext::with_locals(module, &t, &[]); + for (handle, _) in module.const_expressions.iter() { + mod_info + .process_const_expression(handle, &resolve_context, module.to_ctx()) + .map_err(|source| { + ValidationError::ConstExpression { handle, source } + .with_span_handle(handle, &module.const_expressions) + })? + } + } + + #[cfg(feature = "validate")] + if self.flags.contains(ValidationFlags::CONSTANTS) { + for (handle, _) in module.const_expressions.iter() { + self.validate_const_expression(handle, module.to_ctx(), &mut mod_info) + .map_err(|source| { + ValidationError::ConstExpression { handle, source } + .with_span_handle(handle, &module.const_expressions) + })? + } + + for (handle, constant) in module.constants.iter() { + self.validate_constant(handle, module.to_ctx(), &mod_info) + .map_err(|source| { + ValidationError::Constant { + handle, + name: constant.name.clone().unwrap_or_default(), + source, + } + .with_span_handle(handle, &module.constants) + })? + } + } + #[cfg(feature = "validate")] for (var_handle, var) in module.global_variables.iter() { - self.validate_global_var(var, module.to_ctx()) + self.validate_global_var(var, module.to_ctx(), &mod_info) .map_err(|source| { ValidationError::GlobalVariable { handle: var_handle, @@ -434,7 +479,7 @@ impl Validator { #[cfg(feature = "validate")] fn validate_atomic_compare_exchange_struct( - types: &UniqueArena, + types: &crate::UniqueArena, members: &[crate::StructMember], scalar_predicate: impl FnOnce(&crate::TypeInner) -> bool, ) -> bool { diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron index 66b38e35a..62e898d3c 100644 --- a/tests/out/analysis/access.info.ron +++ b/tests/out/analysis/access.info.ron @@ -77,15 +77,6 @@ space: Function, )), ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), ( uniformity: ( non_uniform_result: None, @@ -107,6 +98,15 @@ assignable_global: None, ty: Handle(3), ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), ( uniformity: ( non_uniform_result: None, @@ -708,15 +708,6 @@ space: Function, )), ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), ( uniformity: ( non_uniform_result: None, @@ -738,6 +729,15 @@ assignable_global: None, ty: Handle(3), ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), ( uniformity: ( non_uniform_result: Some(55), @@ -1294,15 +1294,6 @@ space: Function, )), ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), ( uniformity: ( non_uniform_result: None, @@ -1324,6 +1315,15 @@ assignable_global: None, ty: Handle(3), ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), ( uniformity: ( non_uniform_result: None, @@ -2051,15 +2051,6 @@ space: Function, )), ), - ( - uniformity: ( - non_uniform_result: Some(2), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(3), - ), ( uniformity: ( non_uniform_result: None, @@ -2081,6 +2072,15 @@ assignable_global: None, ty: Handle(3), ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), ( uniformity: ( non_uniform_result: Some(66), @@ -4290,4 +4290,88 @@ sampling: [], ), ], + const_expression_types: [ + Value(Scalar( + kind: Uint, + width: 4, + )), + Value(Scalar( + kind: Uint, + width: 4, + )), + Value(Scalar( + kind: Uint, + width: 4, + )), + Value(Scalar( + kind: Uint, + width: 4, + )), + Handle(2), + Value(Scalar( + kind: Sint, + width: 4, + )), + Handle(4), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + ], ) \ No newline at end of file diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index f060e3b3f..c0c222ba4 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -428,4 +428,5 @@ sampling: [], ), ], + const_expression_types: [], ) \ No newline at end of file diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index fdafe5107..8af61bff5 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -143,58 +143,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -203,10 +152,7 @@ ), ref_count: 2, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -215,10 +161,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -227,10 +170,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -239,10 +179,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -251,10 +188,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -263,10 +197,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -275,10 +206,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -287,10 +215,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Uint, - width: 4, - )), + ty: Handle(3), ), ( uniformity: ( @@ -299,10 +224,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -311,10 +233,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -323,10 +242,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -335,10 +251,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -347,10 +260,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -359,10 +269,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -371,10 +278,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -383,10 +287,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -395,10 +296,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -407,10 +305,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -419,10 +314,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Uint, - width: 4, - )), + ty: Handle(3), ), ( uniformity: ( @@ -431,10 +323,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Uint, - width: 4, - )), + ty: Handle(3), ), ( uniformity: ( @@ -443,10 +332,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -455,10 +341,7 @@ ), ref_count: 3, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -467,10 +350,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -479,10 +359,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -491,10 +368,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -503,10 +377,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -515,10 +386,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -527,10 +395,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -539,10 +404,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -551,10 +413,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -563,10 +422,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -575,10 +431,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -596,14 +449,11 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( - non_uniform_result: Some(47), + non_uniform_result: Some(43), requirements: (""), ), ref_count: 1, @@ -612,7 +462,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 6, @@ -621,7 +471,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -633,7 +483,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -645,7 +495,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -657,7 +507,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -669,7 +519,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -687,7 +537,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -696,7 +546,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -708,19 +558,16 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -742,7 +589,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 2, @@ -751,7 +598,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -763,7 +610,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -775,7 +622,7 @@ ), ( uniformity: ( - non_uniform_result: Some(47), + non_uniform_result: Some(43), requirements: (""), ), ref_count: 1, @@ -787,7 +634,7 @@ ), ( uniformity: ( - non_uniform_result: Some(47), + non_uniform_result: Some(43), requirements: (""), ), ref_count: 1, @@ -799,7 +646,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 3, @@ -808,7 +655,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -820,7 +667,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -832,7 +679,25 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(1), + ), + ( + uniformity: ( + non_uniform_result: Some(44), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(1), + ), + ( + uniformity: ( + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -844,7 +709,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -856,31 +721,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(48), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -889,7 +730,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -901,7 +742,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1037,10 +878,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1049,58 +887,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -1109,10 +896,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1121,10 +905,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1133,10 +914,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1145,10 +923,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1157,10 +932,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1169,10 +941,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1181,10 +950,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Uint, - width: 4, - )), + ty: Handle(3), ), ( uniformity: ( @@ -1193,10 +959,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1205,10 +968,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -1217,10 +977,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1229,10 +986,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1241,10 +995,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -1253,10 +1004,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1265,10 +1013,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1277,10 +1022,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1289,10 +1031,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1301,10 +1040,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1313,10 +1049,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Uint, - width: 4, - )), + ty: Handle(3), ), ( uniformity: ( @@ -1325,10 +1058,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Uint, - width: 4, - )), + ty: Handle(3), ), ( uniformity: ( @@ -1337,10 +1067,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -1349,10 +1076,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -1361,10 +1085,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1373,10 +1094,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1385,10 +1103,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1397,10 +1112,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1409,10 +1121,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1421,10 +1130,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1433,10 +1139,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1445,10 +1148,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1457,10 +1157,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1469,10 +1166,7 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), + ty: Handle(9), ), ( uniformity: ( @@ -1490,14 +1184,11 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( - non_uniform_result: Some(47), + non_uniform_result: Some(43), requirements: (""), ), ref_count: 3, @@ -1509,7 +1200,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 11, @@ -1521,7 +1212,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1580,7 +1271,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1592,7 +1283,7 @@ ), ( uniformity: ( - non_uniform_result: Some(47), + non_uniform_result: Some(43), requirements: (""), ), ref_count: 1, @@ -1601,7 +1292,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1624,7 +1315,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1633,7 +1324,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1647,7 +1338,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1661,7 +1352,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1679,7 +1370,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1733,7 +1424,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1742,7 +1433,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1756,7 +1447,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1770,7 +1461,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1786,7 +1477,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1812,7 +1503,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1821,7 +1512,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1835,7 +1526,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1849,7 +1540,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1865,7 +1556,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1891,7 +1582,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1900,7 +1591,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1914,7 +1605,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1928,7 +1619,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1944,7 +1635,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -1956,7 +1647,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2052,7 +1743,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2061,7 +1752,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2087,10 +1778,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -2099,10 +1787,7 @@ ), ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), + ty: Handle(1), ), ( uniformity: ( @@ -2120,7 +1805,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2129,7 +1814,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2143,7 +1828,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2157,7 +1842,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2173,7 +1858,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2199,7 +1884,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2208,7 +1893,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2222,7 +1907,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2236,7 +1921,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2252,7 +1937,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2278,7 +1963,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2287,7 +1972,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2301,7 +1986,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2315,7 +2000,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2331,7 +2016,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2343,7 +2028,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2352,7 +2037,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2361,7 +2046,7 @@ ), ( uniformity: ( - non_uniform_result: Some(47), + non_uniform_result: Some(43), requirements: (""), ), ref_count: 1, @@ -2370,7 +2055,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2379,7 +2064,7 @@ ), ( uniformity: ( - non_uniform_result: Some(48), + non_uniform_result: Some(44), requirements: (""), ), ref_count: 1, @@ -2388,7 +2073,7 @@ ), ( uniformity: ( - non_uniform_result: Some(47), + non_uniform_result: Some(43), requirements: (""), ), ref_count: 1, @@ -2397,7 +2082,7 @@ ), ( uniformity: ( - non_uniform_result: Some(47), + non_uniform_result: Some(43), requirements: (""), ), ref_count: 1, @@ -2500,4 +2185,148 @@ sampling: [], ), ], + const_expression_types: [ + Value(Scalar( + kind: Float, + width: 4, + )), + Value(Scalar( + kind: Float, + width: 4, + )), + Value(Scalar( + kind: Float, + width: 4, + )), + Value(Scalar( + kind: Float, + width: 4, + )), + Value(Scalar( + kind: Float, + width: 4, + )), + Handle(1), + Handle(1), + Handle(1), + Handle(2), + Value(Scalar( + kind: Uint, + width: 4, + )), + Value(Scalar( + kind: Uint, + width: 4, + )), + Value(Scalar( + kind: Uint, + width: 4, + )), + Value(Scalar( + kind: Float, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Value(Scalar( + kind: Sint, + width: 4, + )), + Handle(2), + Handle(3), + ], ) \ No newline at end of file diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index 2a5e03882..a25eda03b 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -37,8 +37,8 @@ void test_matrix_within_struct_accesses() { int idx = 0; Baz t = Baz(mat3x2(0.0)); idx = 1; - int _e2 = idx; - idx = (_e2 - 1); + int _e3 = idx; + idx = (_e3 - 1); mat3x2 l0_ = _group_0_binding_1_vs.m; vec2 l1_ = _group_0_binding_1_vs.m[0]; int _e15 = idx; @@ -52,8 +52,8 @@ void test_matrix_within_struct_accesses() { int _e43 = idx; float l6_ = _group_0_binding_1_vs.m[_e41][_e43]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - int _e55 = idx; - idx = (_e55 + 1); + int _e56 = idx; + idx = (_e56 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); int _e72 = idx; @@ -73,8 +73,8 @@ void test_matrix_within_array_within_struct_accesses() { int idx_1 = 0; MatCx2InArray t_1 = MatCx2InArray(mat4x2[2](mat4x2(0.0), mat4x2(0.0))); idx_1 = 1; - int _e2 = idx_1; - idx_1 = (_e2 - 1); + int _e3 = idx_1; + idx_1 = (_e3 - 1); mat4x2 l0_1[2] = _group_0_binding_3_vs.am; mat4x2 l1_1 = _group_0_binding_3_vs.am[0]; vec2 l2_1 = _group_0_binding_3_vs.am[0][0]; @@ -89,8 +89,8 @@ void test_matrix_within_array_within_struct_accesses() { int _e60 = idx_1; float l7_ = _group_0_binding_3_vs.am[0][_e58][_e60]; t_1 = MatCx2InArray(mat4x2[2](mat4x2(0.0), mat4x2(0.0))); - int _e66 = idx_1; - idx_1 = (_e66 + 1); + int _e67 = idx_1; + idx_1 = (_e67 + 1); t_1.am = mat4x2[2](mat4x2(0.0), mat4x2(0.0)); t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); t_1.am[0][0] = vec2(9.0); diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 0f6485361..8d6067aee 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -18,6 +18,8 @@ struct SimParams { float rule2Scale; float rule3Scale; }; +const uint NUM_PARTICLES = 1500u; + uniform SimParams_block_0Compute { SimParams _group_0_binding_0_cs; }; layout(std430) readonly buffer Particles_block_1Compute { @@ -42,7 +44,7 @@ void main() { vec2 vel = vec2(0.0); uint i = 0u; uint index = global_invocation_id.x; - if ((index >= 1500u)) { + if ((index >= NUM_PARTICLES)) { return; } vec2 _e8 = _group_0_binding_1_cs.particles[index].pos; @@ -63,7 +65,7 @@ void main() { } loop_init = false; uint _e36 = i; - if ((_e36 >= 1500u)) { + if ((_e36 >= NUM_PARTICLES)) { break; } uint _e39 = i; diff --git a/tests/out/glsl/do-while.main.Fragment.glsl b/tests/out/glsl/do-while.main.Fragment.glsl index 56a69123c..50e9a4897 100644 --- a/tests/out/glsl/do-while.main.Fragment.glsl +++ b/tests/out/glsl/do-while.main.Fragment.glsl @@ -8,8 +8,8 @@ void fb1_(inout bool cond) { bool loop_init = true; while(true) { if (!loop_init) { - bool _e6 = cond; - if (!(_e6)) { + bool _e2 = cond; + if (!(_e2)) { break; } } diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index 5c194d532..d1b234734 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -9,6 +9,8 @@ struct FooStruct { vec3 v3_; float v1_; }; +const bool Foo_1 = true; + shared float wg[10]; shared uint at_1; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index d3859ef63..51dc36969 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -9,16 +9,21 @@ struct Foo { vec4 a; int b; }; +const vec4 v_f32_one = vec4(1.0, 1.0, 1.0, 1.0); +const vec4 v_f32_zero = vec4(0.0, 0.0, 0.0, 0.0); +const vec4 v_f32_half = vec4(0.5, 0.5, 0.5, 0.5); +const ivec4 v_i32_one = ivec4(1, 1, 1, 1); + vec4 builtins() { int s1_ = (true ? 1 : 0); - vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0)); - vec4 s3_ = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), bvec4(false, false, false, false)); - vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); - float b1_ = intBitsToFloat(ivec4(1, 1, 1, 1).x); - vec4 b2_ = intBitsToFloat(ivec4(1, 1, 1, 1)); - ivec4 v_i32_zero = ivec4(vec4(0.0, 0.0, 0.0, 0.0)); + vec4 s2_ = (true ? v_f32_one : v_f32_zero); + vec4 s3_ = mix(v_f32_one, v_f32_zero, bvec4(false, false, false, false)); + vec4 m1_ = mix(v_f32_zero, v_f32_one, v_f32_half); + vec4 m2_ = mix(v_f32_zero, v_f32_one, 0.1); + float b1_ = intBitsToFloat(v_i32_one.x); + vec4 b2_ = intBitsToFloat(v_i32_one); + ivec4 v_i32_zero = ivec4(v_f32_zero); return (((((vec4((ivec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } @@ -243,15 +248,15 @@ void assignment() { a_1 = (_e27 << 2u); int _e30 = a_1; a_1 = (_e30 >> 1u); - int _e32 = a_1; - a_1 = (_e32 + 1); - int _e35 = a_1; - a_1 = (_e35 - 1); + int _e33 = a_1; + a_1 = (_e33 + 1); + int _e36 = a_1; + a_1 = (_e36 - 1); vec0_ = ivec3(0); - int _e42 = vec0_.y; - vec0_.y = (_e42 + 1); - int _e47 = vec0_.y; - vec0_.y = (_e47 - 1); + int _e43 = vec0_.y; + vec0_.y = (_e43 + 1); + int _e48 = vec0_.y; + vec0_.y = (_e48 - 1); return; } @@ -268,7 +273,7 @@ void negation_avoids_prefix_decrement() { void main() { vec4 _e0 = builtins(); vec4 _e1 = splat(); - vec3 _e4 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + vec3 _e4 = bool_cast(v_f32_one.xyz); float _e5 = constructors(); logical(); arithmetic(); diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index 082196af5..eec208cdc 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -26,10 +26,10 @@ layout(location = 0) in vec2 _p2vs_location0; layout(location = 0) smooth out vec2 _vs2fs_location0; void main_1() { - vec2 _e12 = a_uv_1; - v_uv = _e12; - vec2 _e13 = a_pos_1; - perVertexStruct.gen_gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); + vec2 _e8 = a_uv_1; + v_uv = _e8; + vec2 _e9 = a_pos_1; + perVertexStruct.gen_gl_Position = vec4(_e9.x, _e9.y, 0.0, 1.0); return; } diff --git a/tests/out/glsl/quad.frag_main.Fragment.glsl b/tests/out/glsl/quad.frag_main.Fragment.glsl index e1902d9e3..c69b9eb5f 100644 --- a/tests/out/glsl/quad.frag_main.Fragment.glsl +++ b/tests/out/glsl/quad.frag_main.Fragment.glsl @@ -7,6 +7,8 @@ struct VertexOutput { vec2 uv; vec4 position; }; +const float c_scale = 1.2; + uniform highp sampler2D _group_0_binding_0_fs; smooth in vec2 _vs2fs_location0; diff --git a/tests/out/glsl/quad.fs_extra.Fragment.glsl b/tests/out/glsl/quad.fs_extra.Fragment.glsl index 932fa76ba..31674b12d 100644 --- a/tests/out/glsl/quad.fs_extra.Fragment.glsl +++ b/tests/out/glsl/quad.fs_extra.Fragment.glsl @@ -7,6 +7,8 @@ struct VertexOutput { vec2 uv; vec4 position; }; +const float c_scale = 1.2; + layout(location = 0) out vec4 _fs2p_location0; void main() { diff --git a/tests/out/glsl/quad.vert_main.Vertex.glsl b/tests/out/glsl/quad.vert_main.Vertex.glsl index 5a1f432b2..c5bca7f66 100644 --- a/tests/out/glsl/quad.vert_main.Vertex.glsl +++ b/tests/out/glsl/quad.vert_main.Vertex.glsl @@ -7,6 +7,8 @@ struct VertexOutput { vec2 uv; vec4 position; }; +const float c_scale = 1.2; + layout(location = 0) in vec2 _p2vs_location0; layout(location = 1) in vec2 _p2vs_location1; smooth out vec2 _vs2fs_location0; @@ -14,7 +16,7 @@ smooth out vec2 _vs2fs_location0; void main() { vec2 pos = _p2vs_location0; vec2 uv = _p2vs_location1; - VertexOutput _tmp_return = VertexOutput(uv, vec4((1.2000000476837158 * pos), 0.0, 1.0)); + VertexOutput _tmp_return = VertexOutput(uv, vec4((c_scale * pos), 0.0, 1.0)); _vs2fs_location0 = _tmp_return.uv; gl_Position = _tmp_return.position; return; diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index b34e39e5c..091085081 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -21,6 +21,9 @@ struct Light { vec4 pos; vec4 color; }; +const vec3 c_ambient = vec3(0.05, 0.05, 0.05); +const uint c_max_lights = 10u; + uniform Globals_block_0Fragment { Globals _group_0_binding_0_fs; }; uniform Entity_block_1Fragment { Entity _group_1_binding_0_fs; }; @@ -49,18 +52,18 @@ void main() { vec3 color = vec3(0.0); uint i = 0u; vec3 normal_1 = normalize(in_.world_normal); - color = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + color = c_ambient; i = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _e39 = i; - i = (_e39 + 1u); + uint _e40 = i; + i = (_e40 + 1u); } loop_init = false; uint _e7 = i; uint _e11 = _group_0_binding_0_fs.num_lights.x; - if ((_e7 < min(_e11, 10u))) { + if ((_e7 < min(_e11, c_max_lights))) { } else { break; } diff --git a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl index ae3dd1c86..c85a89eb9 100644 --- a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl @@ -21,6 +21,9 @@ struct Light { vec4 pos; vec4 color; }; +const vec3 c_ambient = vec3(0.05, 0.05, 0.05); +const uint c_max_lights = 10u; + uniform Globals_block_0Fragment { Globals _group_0_binding_0_fs; }; uniform Entity_block_1Fragment { Entity _group_1_binding_0_fs; }; @@ -49,18 +52,18 @@ void main() { vec3 color_1 = vec3(0.0); uint i_1 = 0u; vec3 normal_1 = normalize(in_1.world_normal); - color_1 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + color_1 = c_ambient; i_1 = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _e39 = i_1; - i_1 = (_e39 + 1u); + uint _e40 = i_1; + i_1 = (_e40 + 1u); } loop_init = false; uint _e7 = i_1; uint _e11 = _group_0_binding_0_fs.num_lights.x; - if ((_e7 < min(_e11, 10u))) { + if ((_e7 < min(_e11, c_max_lights))) { } else { break; } diff --git a/tests/out/glsl/shadow.vs_main.Vertex.glsl b/tests/out/glsl/shadow.vs_main.Vertex.glsl index eced93ae7..631c412f2 100644 --- a/tests/out/glsl/shadow.vs_main.Vertex.glsl +++ b/tests/out/glsl/shadow.vs_main.Vertex.glsl @@ -21,6 +21,9 @@ struct Light { vec4 pos; vec4 color; }; +const vec3 c_ambient = vec3(0.05, 0.05, 0.05); +const uint c_max_lights = 10u; + uniform Globals_block_0Vertex { Globals _group_0_binding_0_vs; }; uniform Entity_block_1Vertex { Entity _group_1_binding_0_vs; }; diff --git a/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl b/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl index 03857ec79..6315309c9 100644 --- a/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl +++ b/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl @@ -5,6 +5,8 @@ precision highp int; layout(local_size_x = 4, local_size_y = 1, local_size_z = 1) in; +const uint SIZE = 128u; + shared int arr_i32_[128]; diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 2af083b72..5fdd97fbc 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -1,4 +1,3 @@ - typedef struct { float2 _0; float2 _1; } __mat2x2; float2 __get_col_of_mat2x2(__mat2x2 mat, uint idx) { switch(idx) { @@ -84,6 +83,14 @@ RWByteAddressBuffer qux : register(u2); cbuffer nested_mat_cx2_ : register(b3) { MatCx2InArray nested_mat_cx2_; } groupshared uint val; +Baz ConstructBaz(float3x2 arg0) { + Baz ret = (Baz)0; + ret.m_0 = arg0[0]; + ret.m_1 = arg0[1]; + ret.m_2 = arg0[2]; + return ret; +} + float3x2 GetMatmOnBaz(Baz obj) { return float3x2(obj.m_0, obj.m_1, obj.m_2); } @@ -110,22 +117,14 @@ void SetMatScalarmOnBaz(Baz obj, float scalar, uint mat_idx, uint vec_idx) { } } -Baz ConstructBaz(float3x2 arg0) { - Baz ret = (Baz)0; - ret.m_0 = arg0[0]; - ret.m_1 = arg0[1]; - ret.m_2 = arg0[2]; - return ret; -} - void test_matrix_within_struct_accesses() { int idx = (int)0; Baz t = (Baz)0; idx = 1; - int _expr2 = idx; - idx = (_expr2 - 1); + int _expr3 = idx; + idx = (_expr3 - 1); float3x2 l0_ = GetMatmOnBaz(baz); float2 l1_ = GetMatmOnBaz(baz)[0]; int _expr15 = idx; @@ -139,8 +138,8 @@ void test_matrix_within_struct_accesses() int _expr43 = idx; float l6_ = GetMatmOnBaz(baz)[_expr41][_expr43]; t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); - int _expr55 = idx; - idx = (_expr55 + 1); + int _expr56 = idx; + idx = (_expr56 + 1); SetMatmOnBaz(t, float3x2((6.0).xx, (5.0).xx, (4.0).xx)); t.m_0 = (9.0).xx; int _expr72 = idx; @@ -168,8 +167,8 @@ void test_matrix_within_array_within_struct_accesses() MatCx2InArray t_1 = (MatCx2InArray)0; idx_1 = 1; - int _expr2 = idx_1; - idx_1 = (_expr2 - 1); + int _expr3 = idx_1; + idx_1 = (_expr3 - 1); float4x2 l0_1[2] = ((float4x2[2])nested_mat_cx2_.am); float4x2 l1_1 = ((float4x2)nested_mat_cx2_.am[0]); float2 l2_1 = nested_mat_cx2_.am[0]._0; @@ -184,8 +183,8 @@ void test_matrix_within_array_within_struct_accesses() int _expr60 = idx_1; float l7_ = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr58)[_expr60]; t_1 = ConstructMatCx2InArray((float4x2[2])0); - int _expr66 = idx_1; - idx_1 = (_expr66 + 1); + int _expr67 = idx_1; + idx_1 = (_expr67 + 1); t_1.am = (__mat4x2[2])(float4x2[2])0; t_1.am[0] = (__mat4x2)float4x2((8.0).xx, (7.0).xx, (6.0).xx, (5.0).xx); t_1.am[0]._0 = (9.0).xx; @@ -231,6 +230,12 @@ void assign_array_through_ptr_fn(inout float4 foo_2[2]) return; } +typedef int ret_Constructarray5_int_[5]; +ret_Constructarray5_int_ Constructarray5_int_(int arg0, int arg1, int arg2, int arg3, int arg4) { + int ret[5] = { arg0, arg1, arg2, arg3, arg4 }; + return ret; +} + typedef uint2 ret_Constructarray2_uint2_[2]; ret_Constructarray2_uint2_ Constructarray2_uint2_(uint2 arg0, uint2 arg1) { uint2 ret[2] = { arg0, arg1 }; @@ -244,12 +249,6 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer) return ret; } -typedef int ret_Constructarray5_int_[5]; -ret_Constructarray5_int_ Constructarray5_int_(int arg0, int arg1, int arg2, int arg3, int arg4) { - int ret[5] = { arg0, arg1, arg2, arg3, arg4 }; - return ret; -} - float4 foo_vert(uint vi : SV_VertexID) : SV_Position { float foo = (float)0; diff --git a/tests/out/hlsl/array-in-ctor.hlsl b/tests/out/hlsl/array-in-ctor.hlsl index e184339e9..1079262a0 100644 --- a/tests/out/hlsl/array-in-ctor.hlsl +++ b/tests/out/hlsl/array-in-ctor.hlsl @@ -1,4 +1,3 @@ - struct Ah { float inner[2]; }; diff --git a/tests/out/hlsl/atomicOps.hlsl b/tests/out/hlsl/atomicOps.hlsl index a45afb1a8..0363920b3 100644 --- a/tests/out/hlsl/atomicOps.hlsl +++ b/tests/out/hlsl/atomicOps.hlsl @@ -1,4 +1,3 @@ - struct Struct { uint atomic_scalar; int atomic_arr[2]; diff --git a/tests/out/hlsl/binding-arrays.hlsl b/tests/out/hlsl/binding-arrays.hlsl index 7784f2425..13d93c43c 100644 --- a/tests/out/hlsl/binding-arrays.hlsl +++ b/tests/out/hlsl/binding-arrays.hlsl @@ -1,4 +1,3 @@ - struct UniformIndex { uint index; }; @@ -71,115 +70,115 @@ float4 main(FragmentInput_main fragmentinput_main) : SV_Target0 u2_ = (_expr28 + NagaDimensions2D(texture_array_unbounded[uniform_index])); uint2 _expr33 = u2_; u2_ = (_expr33 + NagaDimensions2D(texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)])); - float4 _expr41 = texture_array_bounded[0].Gather(samp[0], uv); - float4 _expr42 = v4_; - v4_ = (_expr42 + _expr41); - float4 _expr48 = texture_array_bounded[uniform_index].Gather(samp[uniform_index], uv); - float4 _expr49 = v4_; - v4_ = (_expr49 + _expr48); - float4 _expr55 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Gather(samp[NonUniformResourceIndex(non_uniform_index)], uv); - float4 _expr56 = v4_; - v4_ = (_expr56 + _expr55); - float4 _expr65 = texture_array_depth[0].GatherCmp(samp_comp[0], uv, 0.0); - float4 _expr66 = v4_; - v4_ = (_expr66 + _expr65); - float4 _expr73 = texture_array_depth[uniform_index].GatherCmp(samp_comp[uniform_index], uv, 0.0); - float4 _expr74 = v4_; - v4_ = (_expr74 + _expr73); - float4 _expr81 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].GatherCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float4 _expr82 = v4_; - v4_ = (_expr82 + _expr81); - float4 _expr88 = texture_array_unbounded[0].Load(int3(pix, 0)); - float4 _expr89 = v4_; - v4_ = (_expr89 + _expr88); - float4 _expr94 = texture_array_unbounded[uniform_index].Load(int3(pix, 0)); - float4 _expr95 = v4_; - v4_ = (_expr95 + _expr94); - float4 _expr100 = texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)].Load(int3(pix, 0)); - float4 _expr101 = v4_; - v4_ = (_expr101 + _expr100); - uint _expr107 = u1_; - u1_ = (_expr107 + NagaNumLayers2DArray(texture_array_2darray[0])); - uint _expr112 = u1_; - u1_ = (_expr112 + NagaNumLayers2DArray(texture_array_2darray[uniform_index])); - uint _expr117 = u1_; - u1_ = (_expr117 + NagaNumLayers2DArray(texture_array_2darray[NonUniformResourceIndex(non_uniform_index)])); - uint _expr123 = u1_; - u1_ = (_expr123 + NagaNumLevels2D(texture_array_bounded[0])); - uint _expr128 = u1_; - u1_ = (_expr128 + NagaNumLevels2D(texture_array_bounded[uniform_index])); - uint _expr133 = u1_; - u1_ = (_expr133 + NagaNumLevels2D(texture_array_bounded[NonUniformResourceIndex(non_uniform_index)])); - uint _expr139 = u1_; - u1_ = (_expr139 + NagaMSNumSamples2D(texture_array_multisampled[0])); - uint _expr144 = u1_; - u1_ = (_expr144 + NagaMSNumSamples2D(texture_array_multisampled[uniform_index])); - uint _expr149 = u1_; - u1_ = (_expr149 + NagaMSNumSamples2D(texture_array_multisampled[NonUniformResourceIndex(non_uniform_index)])); - float4 _expr157 = texture_array_bounded[0].Sample(samp[0], uv); - float4 _expr158 = v4_; - v4_ = (_expr158 + _expr157); - float4 _expr164 = texture_array_bounded[uniform_index].Sample(samp[uniform_index], uv); - float4 _expr165 = v4_; - v4_ = (_expr165 + _expr164); - float4 _expr171 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Sample(samp[NonUniformResourceIndex(non_uniform_index)], uv); - float4 _expr172 = v4_; - v4_ = (_expr172 + _expr171); - float4 _expr181 = texture_array_bounded[0].SampleBias(samp[0], uv, 0.0); - float4 _expr182 = v4_; - v4_ = (_expr182 + _expr181); - float4 _expr189 = texture_array_bounded[uniform_index].SampleBias(samp[uniform_index], uv, 0.0); - float4 _expr190 = v4_; - v4_ = (_expr190 + _expr189); - float4 _expr197 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleBias(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float4 _expr198 = v4_; - v4_ = (_expr198 + _expr197); - float _expr207 = texture_array_depth[0].SampleCmp(samp_comp[0], uv, 0.0); - float _expr208 = v1_; - v1_ = (_expr208 + _expr207); - float _expr215 = texture_array_depth[uniform_index].SampleCmp(samp_comp[uniform_index], uv, 0.0); - float _expr216 = v1_; - v1_ = (_expr216 + _expr215); - float _expr223 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float _expr224 = v1_; - v1_ = (_expr224 + _expr223); - float _expr233 = texture_array_depth[0].SampleCmpLevelZero(samp_comp[0], uv, 0.0); - float _expr234 = v1_; - v1_ = (_expr234 + _expr233); - float _expr241 = texture_array_depth[uniform_index].SampleCmpLevelZero(samp_comp[uniform_index], uv, 0.0); - float _expr242 = v1_; - v1_ = (_expr242 + _expr241); - float _expr249 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmpLevelZero(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float _expr250 = v1_; - v1_ = (_expr250 + _expr249); - float4 _expr258 = texture_array_bounded[0].SampleGrad(samp[0], uv, uv, uv); - float4 _expr259 = v4_; - v4_ = (_expr259 + _expr258); - float4 _expr265 = texture_array_bounded[uniform_index].SampleGrad(samp[uniform_index], uv, uv, uv); - float4 _expr266 = v4_; - v4_ = (_expr266 + _expr265); - float4 _expr272 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleGrad(samp[NonUniformResourceIndex(non_uniform_index)], uv, uv, uv); - float4 _expr273 = v4_; - v4_ = (_expr273 + _expr272); - float4 _expr282 = texture_array_bounded[0].SampleLevel(samp[0], uv, 0.0); - float4 _expr283 = v4_; - v4_ = (_expr283 + _expr282); - float4 _expr290 = texture_array_bounded[uniform_index].SampleLevel(samp[uniform_index], uv, 0.0); - float4 _expr291 = v4_; - v4_ = (_expr291 + _expr290); - float4 _expr298 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleLevel(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float4 _expr299 = v4_; - v4_ = (_expr299 + _expr298); - float4 _expr304 = v4_; - texture_array_storage[0][pix] = _expr304; + float4 _expr42 = texture_array_bounded[0].Gather(samp[0], uv); + float4 _expr43 = v4_; + v4_ = (_expr43 + _expr42); + float4 _expr50 = texture_array_bounded[uniform_index].Gather(samp[uniform_index], uv); + float4 _expr51 = v4_; + v4_ = (_expr51 + _expr50); + float4 _expr58 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Gather(samp[NonUniformResourceIndex(non_uniform_index)], uv); + float4 _expr59 = v4_; + v4_ = (_expr59 + _expr58); + float4 _expr68 = texture_array_depth[0].GatherCmp(samp_comp[0], uv, 0.0); + float4 _expr69 = v4_; + v4_ = (_expr69 + _expr68); + float4 _expr76 = texture_array_depth[uniform_index].GatherCmp(samp_comp[uniform_index], uv, 0.0); + float4 _expr77 = v4_; + v4_ = (_expr77 + _expr76); + float4 _expr84 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].GatherCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float4 _expr85 = v4_; + v4_ = (_expr85 + _expr84); + float4 _expr91 = texture_array_unbounded[0].Load(int3(pix, 0)); + float4 _expr92 = v4_; + v4_ = (_expr92 + _expr91); + float4 _expr97 = texture_array_unbounded[uniform_index].Load(int3(pix, 0)); + float4 _expr98 = v4_; + v4_ = (_expr98 + _expr97); + float4 _expr103 = texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)].Load(int3(pix, 0)); + float4 _expr104 = v4_; + v4_ = (_expr104 + _expr103); + uint _expr110 = u1_; + u1_ = (_expr110 + NagaNumLayers2DArray(texture_array_2darray[0])); + uint _expr115 = u1_; + u1_ = (_expr115 + NagaNumLayers2DArray(texture_array_2darray[uniform_index])); + uint _expr120 = u1_; + u1_ = (_expr120 + NagaNumLayers2DArray(texture_array_2darray[NonUniformResourceIndex(non_uniform_index)])); + uint _expr126 = u1_; + u1_ = (_expr126 + NagaNumLevels2D(texture_array_bounded[0])); + uint _expr131 = u1_; + u1_ = (_expr131 + NagaNumLevels2D(texture_array_bounded[uniform_index])); + uint _expr136 = u1_; + u1_ = (_expr136 + NagaNumLevels2D(texture_array_bounded[NonUniformResourceIndex(non_uniform_index)])); + uint _expr142 = u1_; + u1_ = (_expr142 + NagaMSNumSamples2D(texture_array_multisampled[0])); + uint _expr147 = u1_; + u1_ = (_expr147 + NagaMSNumSamples2D(texture_array_multisampled[uniform_index])); + uint _expr152 = u1_; + u1_ = (_expr152 + NagaMSNumSamples2D(texture_array_multisampled[NonUniformResourceIndex(non_uniform_index)])); + float4 _expr160 = texture_array_bounded[0].Sample(samp[0], uv); + float4 _expr161 = v4_; + v4_ = (_expr161 + _expr160); + float4 _expr167 = texture_array_bounded[uniform_index].Sample(samp[uniform_index], uv); + float4 _expr168 = v4_; + v4_ = (_expr168 + _expr167); + float4 _expr174 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Sample(samp[NonUniformResourceIndex(non_uniform_index)], uv); + float4 _expr175 = v4_; + v4_ = (_expr175 + _expr174); + float4 _expr184 = texture_array_bounded[0].SampleBias(samp[0], uv, 0.0); + float4 _expr185 = v4_; + v4_ = (_expr185 + _expr184); + float4 _expr192 = texture_array_bounded[uniform_index].SampleBias(samp[uniform_index], uv, 0.0); + float4 _expr193 = v4_; + v4_ = (_expr193 + _expr192); + float4 _expr200 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleBias(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float4 _expr201 = v4_; + v4_ = (_expr201 + _expr200); + float _expr210 = texture_array_depth[0].SampleCmp(samp_comp[0], uv, 0.0); + float _expr211 = v1_; + v1_ = (_expr211 + _expr210); + float _expr218 = texture_array_depth[uniform_index].SampleCmp(samp_comp[uniform_index], uv, 0.0); + float _expr219 = v1_; + v1_ = (_expr219 + _expr218); + float _expr226 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float _expr227 = v1_; + v1_ = (_expr227 + _expr226); + float _expr236 = texture_array_depth[0].SampleCmpLevelZero(samp_comp[0], uv, 0.0); + float _expr237 = v1_; + v1_ = (_expr237 + _expr236); + float _expr244 = texture_array_depth[uniform_index].SampleCmpLevelZero(samp_comp[uniform_index], uv, 0.0); + float _expr245 = v1_; + v1_ = (_expr245 + _expr244); + float _expr252 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmpLevelZero(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float _expr253 = v1_; + v1_ = (_expr253 + _expr252); + float4 _expr261 = texture_array_bounded[0].SampleGrad(samp[0], uv, uv, uv); + float4 _expr262 = v4_; + v4_ = (_expr262 + _expr261); + float4 _expr268 = texture_array_bounded[uniform_index].SampleGrad(samp[uniform_index], uv, uv, uv); + float4 _expr269 = v4_; + v4_ = (_expr269 + _expr268); + float4 _expr275 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleGrad(samp[NonUniformResourceIndex(non_uniform_index)], uv, uv, uv); + float4 _expr276 = v4_; + v4_ = (_expr276 + _expr275); + float4 _expr285 = texture_array_bounded[0].SampleLevel(samp[0], uv, 0.0); + float4 _expr286 = v4_; + v4_ = (_expr286 + _expr285); + float4 _expr293 = texture_array_bounded[uniform_index].SampleLevel(samp[uniform_index], uv, 0.0); + float4 _expr294 = v4_; + v4_ = (_expr294 + _expr293); + float4 _expr301 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleLevel(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float4 _expr302 = v4_; + v4_ = (_expr302 + _expr301); float4 _expr307 = v4_; - texture_array_storage[uniform_index][pix] = _expr307; + texture_array_storage[0][pix] = _expr307; float4 _expr310 = v4_; - texture_array_storage[NonUniformResourceIndex(non_uniform_index)][pix] = _expr310; - uint2 _expr311 = u2_; - uint _expr312 = u1_; - float2 v2_ = float2((_expr311 + (_expr312).xx)); - float4 _expr316 = v4_; - float _expr323 = v1_; - return ((_expr316 + float4(v2_.x, v2_.y, v2_.x, v2_.y)) + (_expr323).xxxx); + texture_array_storage[uniform_index][pix] = _expr310; + float4 _expr313 = v4_; + texture_array_storage[NonUniformResourceIndex(non_uniform_index)][pix] = _expr313; + uint2 _expr314 = u2_; + uint _expr315 = u1_; + float2 v2_ = float2((_expr314 + (_expr315).xx)); + float4 _expr319 = v4_; + float _expr326 = v1_; + return ((_expr319 + float4(v2_.x, v2_.y, v2_.x, v2_.y)) + (_expr326).xxxx); } diff --git a/tests/out/hlsl/bitcast.hlsl b/tests/out/hlsl/bitcast.hlsl index eda86b0ab..00f4206a1 100644 --- a/tests/out/hlsl/bitcast.hlsl +++ b/tests/out/hlsl/bitcast.hlsl @@ -1,4 +1,3 @@ - [numthreads(1, 1, 1)] void main() { diff --git a/tests/out/hlsl/bits.hlsl b/tests/out/hlsl/bits.hlsl index 425738067..55e1afbd8 100644 --- a/tests/out/hlsl/bits.hlsl +++ b/tests/out/hlsl/bits.hlsl @@ -1,4 +1,3 @@ - [numthreads(1, 1, 1)] void main() { diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index d6bac1cb2..5400a5e3a 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -1,5 +1,3 @@ -static const uint NUM_PARTICLES = 1500; - struct Particle { float2 pos; float2 vel; @@ -15,6 +13,8 @@ struct SimParams { float rule3Scale; }; +static const uint NUM_PARTICLES = 1500u; + cbuffer params : register(b0) { SimParams params; } ByteAddressBuffer particlesSrc : register(t1); RWByteAddressBuffer particlesDst : register(u2); diff --git a/tests/out/hlsl/break-if.hlsl b/tests/out/hlsl/break-if.hlsl index 5a3a453e5..f1aaaac09 100644 --- a/tests/out/hlsl/break-if.hlsl +++ b/tests/out/hlsl/break-if.hlsl @@ -1,4 +1,3 @@ - void breakIfEmpty() { bool loop_init = true; diff --git a/tests/out/hlsl/collatz.hlsl b/tests/out/hlsl/collatz.hlsl index aa0412965..92539ee2f 100644 --- a/tests/out/hlsl/collatz.hlsl +++ b/tests/out/hlsl/collatz.hlsl @@ -1,4 +1,3 @@ - RWByteAddressBuffer v_indices : register(u0); uint collatz_iterations(uint n_base) diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl index 7f7a4b6e5..8d71388c4 100644 --- a/tests/out/hlsl/control-flow.hlsl +++ b/tests/out/hlsl/control-flow.hlsl @@ -1,4 +1,3 @@ - void switch_default_break(int i) { switch(i) { diff --git a/tests/out/hlsl/do-while.hlsl b/tests/out/hlsl/do-while.hlsl index 9f6a1854c..88a3d522e 100644 --- a/tests/out/hlsl/do-while.hlsl +++ b/tests/out/hlsl/do-while.hlsl @@ -1,11 +1,10 @@ - void fb1_(inout bool cond) { bool loop_init = true; while(true) { if (!loop_init) { - bool _expr6 = cond; - if (!(_expr6)) { + bool _expr2 = cond; + if (!(_expr2)) { break; } } diff --git a/tests/out/hlsl/empty-global-name.hlsl b/tests/out/hlsl/empty-global-name.hlsl index e958af7e9..2ad022d6b 100644 --- a/tests/out/hlsl/empty-global-name.hlsl +++ b/tests/out/hlsl/empty-global-name.hlsl @@ -1,4 +1,3 @@ - struct type_1 { int member; }; @@ -7,8 +6,8 @@ RWByteAddressBuffer unnamed : register(u0); void function() { - int _expr8 = asint(unnamed.Load(0)); - unnamed.Store(0, asuint((_expr8 + 1))); + int _expr4 = asint(unnamed.Load(0)); + unnamed.Store(0, asuint((_expr4 + 1))); return; } diff --git a/tests/out/hlsl/empty.hlsl b/tests/out/hlsl/empty.hlsl index 2b5243867..e79d36b9c 100644 --- a/tests/out/hlsl/empty.hlsl +++ b/tests/out/hlsl/empty.hlsl @@ -1,4 +1,3 @@ - [numthreads(1, 1, 1)] void main() { diff --git a/tests/out/hlsl/fragment-output.hlsl b/tests/out/hlsl/fragment-output.hlsl index a4ba428a6..be425a5ef 100644 --- a/tests/out/hlsl/fragment-output.hlsl +++ b/tests/out/hlsl/fragment-output.hlsl @@ -1,4 +1,3 @@ - struct FragmentOutputVec4Vec3_ { float4 vec4f : SV_Target0; nointerpolation int4 vec4i : SV_Target1; diff --git a/tests/out/hlsl/functions.hlsl b/tests/out/hlsl/functions.hlsl index 04a340415..6d7e21030 100644 --- a/tests/out/hlsl/functions.hlsl +++ b/tests/out/hlsl/functions.hlsl @@ -1,4 +1,3 @@ - float2 test_fma() { float2 a = float2(2.0, 2.0); diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index b0b92f206..f8cede1ac 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -1,5 +1,3 @@ -static const bool Foo_1 = true; - typedef struct { float2 _0; float2 _1; float2 _2; } __mat3x2; float2 __get_col_of_mat3x2(__mat3x2 mat, uint idx) { switch(idx) { @@ -56,6 +54,8 @@ struct FooStruct { float v1_; }; +static const bool Foo_1 = true; + groupshared float wg[10]; groupshared uint at_1; RWByteAddressBuffer alignment : register(u1); diff --git a/tests/out/hlsl/hlsl-keyword.hlsl b/tests/out/hlsl/hlsl-keyword.hlsl index efdeb9960..8602525e2 100644 --- a/tests/out/hlsl/hlsl-keyword.hlsl +++ b/tests/out/hlsl/hlsl-keyword.hlsl @@ -1,4 +1,3 @@ - float4 fs_main() : SV_Target0 { float4 Pass_ = (float4)0; diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 75672b9be..e284813a1 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -1,4 +1,3 @@ - Texture2D image_mipmapped_src : register(t0); Texture2DMS image_multisampled_src : register(t3); Texture2DMS image_depth_multisampled_src : register(t4); diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl index a9bd0c346..aa1986f5d 100644 --- a/tests/out/hlsl/interpolate.hlsl +++ b/tests/out/hlsl/interpolate.hlsl @@ -1,4 +1,3 @@ - struct FragmentInput { float4 position : SV_Position; nointerpolation uint _flat : LOC0; diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl index 23fdc45f4..d086bf14b 100644 --- a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl +++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl @@ -1,4 +1,3 @@ - static float a = (float)0; void main_1() @@ -7,12 +6,12 @@ void main_1() float c = (float)0; float d = (float)0; + float _expr4 = a; + b = log(_expr4 + sqrt(_expr4 * _expr4 + 1.0)); + float _expr6 = a; + c = log(_expr6 + sqrt(_expr6 * _expr6 - 1.0)); float _expr8 = a; - b = log(_expr8 + sqrt(_expr8 * _expr8 + 1.0)); - float _expr10 = a; - c = log(_expr10 + sqrt(_expr10 * _expr10 - 1.0)); - float _expr12 = a; - d = 0.5 * log((1.0 + _expr12) / (1.0 - _expr12)); + d = 0.5 * log((1.0 + _expr8) / (1.0 - _expr8)); return; } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index e3443604f..a1be81053 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -1,4 +1,3 @@ - void main() { float4 v = (0.0).xxxx; diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index c2a92a967..a54c90e6b 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -1,8 +1,3 @@ -static const float4 v_f32_one = float4(1.0, 1.0, 1.0, 1.0); -static const float4 v_f32_zero = float4(0.0, 0.0, 0.0, 0.0); -static const float4 v_f32_half = float4(0.5, 0.5, 0.5, 0.5); -static const int4 v_i32_one = int4(1, 1, 1, 1); - struct Foo { float4 a; int b; @@ -11,16 +6,21 @@ struct Foo { int _end_pad_2; }; +static const float4 v_f32_one = float4(1.0, 1.0, 1.0, 1.0); +static const float4 v_f32_zero = float4(0.0, 0.0, 0.0, 0.0); +static const float4 v_f32_half = float4(0.5, 0.5, 0.5, 0.5); +static const int4 v_i32_one = int4(1, 1, 1, 1); + float4 builtins() { int s1_ = (true ? 1 : 0); - float4 s2_ = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0)); - float4 s3_ = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0)); - float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5)); - float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.1); - float b1_ = asfloat(int4(1, 1, 1, 1).x); - float4 b2_ = asfloat(int4(1, 1, 1, 1)); - int4 v_i32_zero = int4(float4(0.0, 0.0, 0.0, 0.0)); + float4 s2_ = (true ? v_f32_one : v_f32_zero); + float4 s3_ = (bool4(false, false, false, false) ? v_f32_zero : v_f32_one); + float4 m1_ = lerp(v_f32_zero, v_f32_one, v_f32_half); + float4 m2_ = lerp(v_f32_zero, v_f32_one, 0.1); + float b1_ = asfloat(v_i32_one.x); + float4 b2_ = asfloat(v_i32_one); + int4 v_i32_zero = int4(v_f32_zero); return (((((float4(((s1_).xxxx + v_i32_zero)) + s2_) + m1_) + m2_) + (b1_).xxxx) + b2_); } @@ -270,15 +270,15 @@ void assignment() a_1 = (_expr27 << 2u); int _expr30 = a_1; a_1 = (_expr30 >> 1u); - int _expr32 = a_1; - a_1 = (_expr32 + 1); - int _expr35 = a_1; - a_1 = (_expr35 - 1); + int _expr33 = a_1; + a_1 = (_expr33 + 1); + int _expr36 = a_1; + a_1 = (_expr36 - 1); vec0_ = (int3)0; - int _expr42 = vec0_.y; - vec0_.y = (_expr42 + 1); - int _expr47 = vec0_.y; - vec0_.y = (_expr47 - 1); + int _expr43 = vec0_.y; + vec0_.y = (_expr43 + 1); + int _expr48 = vec0_.y; + vec0_.y = (_expr48 - 1); return; } @@ -298,7 +298,7 @@ void main() { const float4 _e0 = builtins(); const float4 _e1 = splat(); - const float3 _e4 = bool_cast(float4(1.0, 1.0, 1.0, 1.0).xyz); + const float3 _e4 = bool_cast(v_f32_one.xyz); const float _e5 = constructors(); logical(); arithmetic(); diff --git a/tests/out/hlsl/padding.hlsl b/tests/out/hlsl/padding.hlsl index 32e762cce..e3271e566 100644 --- a/tests/out/hlsl/padding.hlsl +++ b/tests/out/hlsl/padding.hlsl @@ -1,4 +1,3 @@ - struct S { float3 a; int _end_pad_0; diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index 1fdcc43f5..bed52d505 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -1,4 +1,3 @@ - struct gl_PerVertex { float4 gl_Position : SV_Position; float gl_PointSize; @@ -12,12 +11,6 @@ struct type_9 { float4 gl_Position : SV_Position; }; -typedef float ret_Constructarray1_float_[1]; -ret_Constructarray1_float_ Constructarray1_float_(float arg0) { - float ret[1] = { arg0 }; - return ret; -} - gl_PerVertex Constructgl_PerVertex(float4 arg0, float arg1, float arg2[1], float arg3[1]) { gl_PerVertex ret = (gl_PerVertex)0; ret.gl_Position = arg0; @@ -29,7 +22,7 @@ gl_PerVertex Constructgl_PerVertex(float4 arg0, float arg1, float arg2[1], float static float2 v_uv = (float2)0; static float2 a_uv_1 = (float2)0; -static gl_PerVertex perVertexStruct = Constructgl_PerVertex(float4(0.0, 0.0, 0.0, 1.0), 1.0, Constructarray1_float_(0.0), Constructarray1_float_(0.0)); +static gl_PerVertex perVertexStruct = Constructgl_PerVertex(float4(0.0, 0.0, 0.0, 1.0), 1.0, (float[1])0, (float[1])0); static float2 a_pos_1 = (float2)0; struct VertexOutput_main { @@ -39,10 +32,10 @@ struct VertexOutput_main { void main_1() { - float2 _expr12 = a_uv_1; - v_uv = _expr12; - float2 _expr13 = a_pos_1; - perVertexStruct.gl_Position = float4(_expr13.x, _expr13.y, 0.0, 1.0); + float2 _expr8 = a_uv_1; + v_uv = _expr8; + float2 _expr9 = a_pos_1; + perVertexStruct.gl_Position = float4(_expr9.x, _expr9.y, 0.0, 1.0); return; } diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl index 9a987af1c..5bd8530c6 100644 --- a/tests/out/hlsl/quad.hlsl +++ b/tests/out/hlsl/quad.hlsl @@ -1,10 +1,10 @@ -static const float c_scale = 1.2000000476837158; - struct VertexOutput { float2 uv : LOC0; float4 position : SV_Position; }; +static const float c_scale = 1.2; + Texture2D u_texture : register(t0); SamplerState u_sampler : register(s1); diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 5ea06f90c..7116e803e 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -1,6 +1,3 @@ -static const float3 c_ambient = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); -static const uint c_max_lights = 10; - struct Globals { row_major float4x4 view_proj; uint4 num_lights; @@ -23,6 +20,9 @@ struct Light { float4 color; }; +static const float3 c_ambient = float3(0.05, 0.05, 0.05); +static const uint c_max_lights = 10u; + cbuffer u_globals : register(b0) { Globals u_globals; } cbuffer u_entity : register(b0, space1) { Entity u_entity; } ByteAddressBuffer s_lights : register(t1); @@ -92,13 +92,13 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 uint i = (uint)0; float3 normal_1 = normalize(in_.world_normal); - color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + color = c_ambient; i = 0u; bool loop_init = true; while(true) { if (!loop_init) { - uint _expr39 = i; - i = (_expr39 + 1u); + uint _expr40 = i; + i = (_expr40 + 1u); } loop_init = false; uint _expr7 = i; @@ -130,13 +130,13 @@ float4 fs_main_without_storage(FragmentInput_fs_main_without_storage fragmentinp uint i_1 = (uint)0; float3 normal_2 = normalize(in_1.world_normal); - color_1 = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + color_1 = c_ambient; i_1 = 0u; bool loop_init_1 = true; while(true) { if (!loop_init_1) { - uint _expr39 = i_1; - i_1 = (_expr39 + 1u); + uint _expr40 = i_1; + i_1 = (_expr40 + 1u); } loop_init_1 = false; uint _expr7 = i_1; diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl index aacb25012..a2bcc70ec 100644 --- a/tests/out/hlsl/standard.hlsl +++ b/tests/out/hlsl/standard.hlsl @@ -1,4 +1,3 @@ - struct FragmentInput_derivatives { float4 foo_1 : SV_Position; }; diff --git a/tests/out/hlsl/texture-arg.hlsl b/tests/out/hlsl/texture-arg.hlsl index dd0ca1096..b3fac887f 100644 --- a/tests/out/hlsl/texture-arg.hlsl +++ b/tests/out/hlsl/texture-arg.hlsl @@ -1,4 +1,3 @@ - Texture2D Texture : register(t0); SamplerState Sampler : register(s1); diff --git a/tests/out/hlsl/workgroup-uniform-load.hlsl b/tests/out/hlsl/workgroup-uniform-load.hlsl index ad049461f..663fe3364 100644 --- a/tests/out/hlsl/workgroup-uniform-load.hlsl +++ b/tests/out/hlsl/workgroup-uniform-load.hlsl @@ -1,4 +1,4 @@ -static const uint SIZE = 128; +static const uint SIZE = 128u; groupshared int arr_i32_[128]; diff --git a/tests/out/hlsl/workgroup-var-init.hlsl b/tests/out/hlsl/workgroup-var-init.hlsl index 3e70d6e09..e0bd73f8f 100644 --- a/tests/out/hlsl/workgroup-var-init.hlsl +++ b/tests/out/hlsl/workgroup-var-init.hlsl @@ -1,4 +1,3 @@ - struct WStruct { uint arr[512]; int atom; diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 6dda26d0d..744724912 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -335,87 +335,14 @@ ray_desc: None, ray_intersection: None, ), - constants: [ - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(0), - ), - ), - ( - name: None, - specialization: None, - inner: Composite( - ty: 2, - components: [ - 1, - 1, - 1, - ], - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), - ), - ( - name: None, - specialization: None, - inner: Composite( - ty: 4, - components: [ - 1, - 2, - 3, - ], - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(2), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(10), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(1), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(5), - ), - ), - ], + constants: [], global_variables: [ ( name: Some("global_const"), space: Private, binding: None, ty: 4, - init: Some(4), + init: Some(7), ), ( name: Some("bar"), @@ -469,6 +396,44 @@ init: None, ), ], + const_expressions: [ + Literal(U32(0)), + Literal(U32(0)), + Literal(U32(0)), + Literal(U32(0)), + Compose( + ty: 2, + components: [ + 2, + 3, + 4, + ], + ), + Literal(I32(0)), + Compose( + ty: 4, + components: [ + 1, + 5, + 6, + ], + ), + Literal(I32(2)), + Literal(I32(10)), + Literal(I32(2)), + Literal(I32(2)), + Literal(I32(2)), + Literal(I32(2)), + Literal(I32(10)), + Literal(I32(5)), + Literal(I32(5)), + Literal(I32(10)), + Literal(I32(5)), + Literal(I32(2)), + Literal(I32(2)), + Literal(I32(2)), + Literal(I32(2)), + ], functions: [ ( name: Some("test_matrix_within_struct_accesses"), @@ -489,14 +454,14 @@ expressions: [ Literal(I32(1)), LocalVariable(1), + Literal(I32(1)), Load( pointer: 2, ), - Constant(7), Binary( op: Subtract, - left: 3, - right: 4, + left: 4, + right: 3, ), GlobalVariable(3), AccessIndex( @@ -644,14 +609,14 @@ ], ), LocalVariable(2), + Literal(I32(1)), Load( pointer: 2, ), - Constant(7), Binary( op: Add, - left: 56, - right: 57, + left: 57, + right: 56, ), AccessIndex( base: 55, @@ -794,11 +759,7 @@ value: 1, ), Emit(( - start: 2, - end: 3, - )), - Emit(( - start: 4, + start: 3, end: 5, )), Store( @@ -870,11 +831,7 @@ value: 54, ), Emit(( - start: 55, - end: 56, - )), - Emit(( - start: 57, + start: 56, end: 58, )), Store( @@ -1001,14 +958,14 @@ expressions: [ Literal(I32(1)), LocalVariable(1), + Literal(I32(1)), Load( pointer: 2, ), - Constant(7), Binary( op: Subtract, - left: 3, - right: 4, + left: 4, + right: 3, ), GlobalVariable(5), AccessIndex( @@ -1177,14 +1134,14 @@ ], ), LocalVariable(2), + Literal(I32(1)), Load( pointer: 2, ), - Constant(7), Binary( op: Add, - left: 67, - right: 68, + left: 68, + right: 67, ), AccessIndex( base: 66, @@ -1374,11 +1331,7 @@ value: 1, ), Emit(( - start: 2, - end: 3, - )), - Emit(( - start: 4, + start: 3, end: 5, )), Store( @@ -1474,11 +1427,7 @@ value: 65, ), Emit(( - start: 66, - end: 67, - )), - Emit(( - start: 68, + start: 67, end: 69, )), Store( diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 1d38cc34f..6451fc715 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -57,6 +57,7 @@ init: None, ), ], + const_expressions: [], functions: [ ( name: Some("collatz_iterations"), diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 103e69b5f..246657255 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -270,319 +270,213 @@ constants: [ ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 1, + init: 1, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(1), - ), + override: None, + ty: 1, + init: 2, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(2), - ), + override: None, + ty: 1, + init: 3, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(3), - ), + override: None, + ty: 1, + init: 4, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(0.0), - ), + override: None, + ty: 1, + init: 5, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(1.0), - ), + override: None, + ty: 2, + init: 9, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(0.5), - ), + override: None, + ty: 3, + init: 10, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(-0.5), - ), + override: None, + ty: 3, + init: 11, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(0.05000000074505806), - ), + override: None, + ty: 3, + init: 12, ), ( name: None, - specialization: None, - inner: Composite( - ty: 2, - components: [ - 9, - 9, - 9, - ], - ), + override: None, + ty: 1, + init: 13, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(10), - ), + override: None, + ty: 9, + init: 14, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(0), - ), + override: None, + ty: 9, + init: 15, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Uint(1), - ), + override: None, + ty: 9, + init: 16, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Float(0.0), - ), + override: None, + ty: 9, + init: 17, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 18, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 19, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 20, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 21, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 22, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(1), - ), + override: None, + ty: 9, + init: 23, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 24, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 25, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(1), - ), + override: None, + ty: 9, + init: 26, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(1), - ), + override: None, + ty: 9, + init: 27, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 28, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(1), - ), + override: None, + ty: 9, + init: 29, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(2), - ), + override: None, + ty: 9, + init: 30, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 31, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(1), - ), + override: None, + ty: 9, + init: 32, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(2), - ), + override: None, + ty: 9, + init: 33, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 34, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(2), - ), + override: None, + ty: 9, + init: 35, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 36, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), + override: None, + ty: 9, + init: 37, ), ( name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(2), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(1), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(0), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(2), - ), - ), - ( - name: None, - specialization: None, - inner: Scalar( - width: 4, - value: Sint(2), - ), + override: None, + ty: 9, + init: 38, ), ], global_variables: [ @@ -650,6 +544,55 @@ init: None, ), ], + const_expressions: [ + Literal(F32(0.0)), + Literal(F32(1.0)), + Literal(F32(0.5)), + Literal(F32(-0.5)), + Literal(F32(0.05)), + Constant(5), + Constant(5), + Constant(5), + Compose( + ty: 2, + components: [ + 6, + 7, + 8, + ], + ), + Literal(U32(10)), + Literal(U32(0)), + Literal(U32(1)), + Literal(F32(0.0)), + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(1)), + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(1)), + Literal(I32(1)), + Literal(I32(0)), + Literal(I32(1)), + Literal(I32(2)), + Literal(I32(0)), + Literal(I32(1)), + Literal(I32(2)), + Literal(I32(0)), + Literal(I32(2)), + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(2)), + Literal(I32(1)), + Literal(I32(0)), + Literal(I32(2)), + Literal(I32(2)), + Constant(6), + Constant(8), + ], functions: [ ( name: None, @@ -678,171 +621,167 @@ GlobalVariable(2), GlobalVariable(4), GlobalVariable(7), - Constant(1), - Constant(2), + Constant(16), Constant(3), - Constant(4), - Constant(20), - Constant(7), - Constant(33), - Constant(31), Constant(29), Constant(27), Constant(25), - Constant(15), - Constant(12), Constant(23), + Constant(21), + Constant(11), Constant(8), - Constant(36), - Constant(34), - Constant(14), + Constant(19), + Constant(4), Constant(32), Constant(30), - Constant(17), - Constant(26), - Constant(39), - Constant(13), - Constant(11), - Constant(9), - Constant(6), - Constant(21), - Constant(35), - Constant(19), - Constant(37), - Constant(18), - Constant(28), - Constant(16), - Constant(24), - Constant(38), - Constant(22), Constant(10), + Constant(28), + Constant(26), + Constant(13), + Constant(22), + Constant(35), + Constant(9), + Constant(7), Constant(5), + Constant(2), + Constant(17), + Constant(31), + Constant(15), + Constant(33), + Constant(14), + Constant(24), + Constant(12), + Constant(20), + Constant(34), + Constant(18), + Constant(6), + Constant(1), FunctionArgument(0), FunctionArgument(1), AccessIndex( - base: 48, + base: 44, index: 3, ), Binary( op: LessEqual, - left: 49, - right: 46, + left: 45, + right: 42, ), AccessIndex( - base: 48, + base: 44, index: 0, ), AccessIndex( - base: 48, + base: 44, index: 1, ), Compose( ty: 6, components: [ - 51, - 52, + 47, + 48, ], ), Compose( ty: 6, components: [ - 13, - 22, + 9, + 18, ], ), Binary( op: Multiply, - left: 53, - right: 54, + left: 49, + right: 50, ), AccessIndex( - base: 48, + base: 44, index: 3, ), Binary( op: Divide, - left: 34, - right: 56, + left: 30, + right: 52, ), Binary( op: Multiply, - left: 55, - right: 57, + left: 51, + right: 53, ), Splat( size: Bi, - value: 13, + value: 9, ), Binary( op: Add, - left: 58, - right: 59, + left: 54, + right: 55, ), AccessIndex( - base: 60, + base: 56, index: 0, ), AccessIndex( - base: 60, + base: 56, index: 1, ), As( - expr: 47, + expr: 43, kind: Sint, convert: None, ), As( - expr: 63, + expr: 59, kind: Float, convert: Some(4), ), Compose( ty: 2, components: [ - 61, - 62, - 64, + 57, + 58, + 60, ], ), AccessIndex( - base: 48, + base: 44, index: 2, ), AccessIndex( - base: 48, + base: 44, index: 3, ), Binary( op: Divide, - left: 34, - right: 67, + left: 30, + right: 63, ), Binary( op: Multiply, - left: 66, - right: 68, + left: 62, + right: 64, ), AccessIndex( - base: 65, + base: 61, index: 0, ), AccessIndex( - base: 65, + base: 61, index: 1, ), Compose( ty: 6, components: [ - 70, - 71, + 66, + 67, ], ), AccessIndex( - base: 65, + base: 61, index: 2, ), As( - expr: 73, + expr: 69, kind: Sint, convert: Some(4), ), @@ -850,34 +789,34 @@ image: 4, sampler: 5, gather: None, - coordinate: 72, - array_index: Some(74), + coordinate: 68, + array_index: Some(70), offset: None, level: Zero, - depth_ref: Some(69), + depth_ref: Some(65), ), ], named_expressions: {}, body: [ Emit(( - start: 48, - end: 50, + start: 44, + end: 46, )), If( - condition: 50, + condition: 46, accept: [ Return( - value: Some(34), + value: Some(30), ), ], reject: [], ), Emit(( - start: 50, - end: 75, + start: 46, + end: 71, )), Return( - value: Some(75), + value: Some(71), ), ], ), @@ -889,12 +828,12 @@ ( name: Some("color"), ty: 2, - init: Some(10), + init: Some(39), ), ( name: Some("i"), ty: 3, - init: Some(12), + init: Some(40), ), ], expressions: [ @@ -905,104 +844,100 @@ GlobalVariable(2), GlobalVariable(4), GlobalVariable(7), - Constant(1), - Constant(2), + Constant(16), Constant(3), - Constant(4), - Constant(20), - Constant(7), - Constant(33), - Constant(31), Constant(29), Constant(27), Constant(25), - Constant(15), - Constant(12), Constant(23), + Constant(21), + Constant(11), Constant(8), - Constant(36), - Constant(34), - Constant(14), + Constant(19), + Constant(4), Constant(32), Constant(30), - Constant(17), - Constant(26), - Constant(39), - Constant(13), - Constant(11), - Constant(9), - Constant(6), - Constant(21), - Constant(35), - Constant(19), - Constant(37), - Constant(18), - Constant(28), - Constant(16), - Constant(24), - Constant(38), - Constant(22), Constant(10), + Constant(28), + Constant(26), + Constant(13), + Constant(22), + Constant(35), + Constant(9), + Constant(7), Constant(5), + Constant(2), + Constant(17), + Constant(31), + Constant(15), + Constant(33), + Constant(14), + Constant(24), + Constant(12), + Constant(20), + Constant(34), + Constant(18), + Constant(6), + Constant(1), LocalVariable(1), LocalVariable(2), Load( - pointer: 48, + pointer: 44, ), AccessIndex( base: 1, index: 0, ), Access( - base: 50, - index: 41, + base: 46, + index: 37, ), Load( - pointer: 51, + pointer: 47, ), Math( fun: Min, - arg: 52, - arg1: Some(32), + arg: 48, + arg1: Some(28), arg2: None, arg3: None, ), Binary( op: GreaterEqual, - left: 49, - right: 53, + left: 45, + right: 49, ), Load( - pointer: 47, + pointer: 43, ), Load( - pointer: 48, + pointer: 44, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 48, + pointer: 44, ), Access( - base: 57, - index: 58, + base: 53, + index: 54, ), AccessIndex( - base: 59, + base: 55, index: 0, ), Load( - pointer: 60, + pointer: 56, ), Load( pointer: 3, ), Binary( op: Multiply, - left: 61, - right: 62, + left: 57, + right: 58, ), CallResult(1), Load( @@ -1010,7 +945,7 @@ ), Math( fun: Normalize, - arg: 65, + arg: 61, arg1: None, arg2: None, arg3: None, @@ -1020,235 +955,235 @@ index: 0, ), Load( - pointer: 48, + pointer: 44, ), Access( - base: 67, - index: 68, + base: 63, + index: 64, ), AccessIndex( + base: 65, + index: 1, + ), + Access( + base: 66, + index: 31, + ), + Load( + pointer: 67, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( base: 69, + index: 70, + ), + AccessIndex( + base: 71, index: 1, ), Access( - base: 70, - index: 35, + base: 72, + index: 38, ), Load( - pointer: 71, + pointer: 73, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 48, + pointer: 44, ), Access( - base: 73, - index: 74, - ), - AccessIndex( base: 75, + index: 76, + ), + AccessIndex( + base: 77, index: 1, ), Access( - base: 76, - index: 42, + base: 78, + index: 13, ), Load( - pointer: 77, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 48, - ), - Access( - base: 79, - index: 80, - ), - AccessIndex( - base: 81, - index: 1, - ), - Access( - base: 82, - index: 17, - ), - Load( - pointer: 83, + pointer: 79, ), Compose( ty: 2, components: [ - 72, - 78, - 84, + 68, + 74, + 80, ], ), Access( base: 3, - index: 40, + index: 36, + ), + Load( + pointer: 82, + ), + Access( + base: 3, + index: 12, + ), + Load( + pointer: 84, + ), + Access( + base: 3, + index: 23, ), Load( pointer: 86, ), - Access( - base: 3, - index: 16, - ), - Load( - pointer: 88, - ), - Access( - base: 3, - index: 27, - ), - Load( - pointer: 90, - ), Compose( ty: 2, components: [ + 83, + 85, 87, - 89, - 91, ], ), Binary( op: Subtract, - left: 85, - right: 92, + left: 81, + right: 88, ), Math( fun: Normalize, - arg: 93, + arg: 89, arg1: None, arg2: None, arg3: None, ), Math( fun: Dot, - arg: 66, - arg1: Some(94), + arg: 62, + arg1: Some(90), arg2: None, arg3: None, ), Math( fun: Max, - arg: 46, - arg1: Some(95), + arg: 42, + arg1: Some(91), arg2: None, arg3: None, ), Binary( op: Multiply, - left: 64, - right: 96, + left: 60, + right: 92, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 48, + pointer: 44, ), Access( - base: 98, - index: 99, + base: 94, + index: 95, ), AccessIndex( + base: 96, + index: 2, + ), + Access( + base: 97, + index: 10, + ), + Load( + pointer: 98, + ), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 44, + ), + Access( base: 100, + index: 101, + ), + AccessIndex( + base: 102, index: 2, ), Access( - base: 101, - index: 14, + base: 103, + index: 19, ), Load( - pointer: 102, + pointer: 104, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 48, + pointer: 44, ), Access( - base: 104, - index: 105, - ), - AccessIndex( base: 106, + index: 107, + ), + AccessIndex( + base: 108, index: 2, ), Access( - base: 107, - index: 23, + base: 109, + index: 26, ), Load( - pointer: 108, - ), - AccessIndex( - base: 6, - index: 0, - ), - Load( - pointer: 48, - ), - Access( - base: 110, - index: 111, - ), - AccessIndex( - base: 112, - index: 2, - ), - Access( - base: 113, - index: 30, - ), - Load( - pointer: 114, + pointer: 110, ), Compose( ty: 2, components: [ - 103, - 109, - 115, + 99, + 105, + 111, ], ), Binary( op: Multiply, - left: 116, - right: 97, + left: 112, + right: 93, ), Binary( op: Add, - left: 55, - right: 117, + left: 51, + right: 113, ), Load( - pointer: 48, + pointer: 44, ), Binary( op: Add, - left: 119, - right: 31, + left: 115, + right: 27, ), Load( - pointer: 47, + pointer: 43, ), Compose( ty: 4, components: [ - 121, - 34, + 117, + 30, ], ), ], @@ -1257,57 +1192,57 @@ Loop( body: [ Emit(( - start: 48, - end: 54, + start: 44, + end: 50, )), If( - condition: 54, + condition: 50, accept: [ Break, ], reject: [], ), Emit(( - start: 54, - end: 63, + start: 50, + end: 59, )), Call( function: 1, arguments: [ - 56, - 63, + 52, + 59, ], - result: Some(64), + result: Some(60), ), Emit(( - start: 64, - end: 118, + start: 60, + end: 114, )), Store( - pointer: 47, - value: 118, + pointer: 43, + value: 114, ), Continue, ], continuing: [ Emit(( - start: 118, - end: 120, + start: 114, + end: 116, )), Store( - pointer: 48, - value: 120, + pointer: 44, + value: 116, ), ], break_if: None, ), Emit(( - start: 120, - end: 122, + start: 116, + end: 118, )), Store( pointer: 7, - value: 122, + value: 118, ), Return( value: None, diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 1e83ae7c3..e5d875dd1 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -57,8 +57,6 @@ struct type_22 { struct type_26 { metal::float4 inner[2]; }; -constant metal::uint3 const_type_1_ = {0u, 0u, 0u}; -constant GlobalConst const_GlobalConst = {0u, {}, const_type_1_, 0}; void test_matrix_within_struct_accesses( constant Baz& baz @@ -66,8 +64,8 @@ void test_matrix_within_struct_accesses( int idx = {}; Baz t = {}; idx = 1; - int _e2 = idx; - idx = _e2 - 1; + int _e3 = idx; + idx = _e3 - 1; metal::float3x2 l0_ = baz.m; metal::float2 l1_ = baz.m[0]; int _e15 = idx; @@ -81,8 +79,8 @@ void test_matrix_within_struct_accesses( int _e43 = idx; float l6_ = baz.m[_e41][_e43]; t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; - int _e55 = idx; - idx = _e55 + 1; + int _e56 = idx; + idx = _e56 + 1; t.m = metal::float3x2(metal::float2(6.0), metal::float2(5.0), metal::float2(4.0)); t.m[0] = metal::float2(9.0); int _e72 = idx; @@ -104,8 +102,8 @@ void test_matrix_within_array_within_struct_accesses( int idx_1 = {}; MatCx2InArray t_1 = {}; idx_1 = 1; - int _e2 = idx_1; - idx_1 = _e2 - 1; + int _e3 = idx_1; + idx_1 = _e3 - 1; type_15 l0_1 = nested_mat_cx2_.am; metal::float4x2 l1_1 = nested_mat_cx2_.am.inner[0]; metal::float2 l2_1 = nested_mat_cx2_.am.inner[0][0]; @@ -120,8 +118,8 @@ void test_matrix_within_array_within_struct_accesses( int _e60 = idx_1; float l7_ = nested_mat_cx2_.am.inner[0][_e58][_e60]; t_1 = MatCx2InArray {type_15 {}}; - int _e66 = idx_1; - idx_1 = _e66 + 1; + int _e67 = idx_1; + idx_1 = _e67 + 1; t_1.am = type_15 {}; t_1.am.inner[0] = metal::float4x2(metal::float2(8.0), metal::float2(7.0), metal::float2(6.0), metal::float2(5.0)); t_1.am.inner[0][0] = metal::float2(9.0); diff --git a/tests/out/msl/binding-arrays.msl b/tests/out/msl/binding-arrays.msl index 694f79452..10a539791 100644 --- a/tests/out/msl/binding-arrays.msl +++ b/tests/out/msl/binding-arrays.msl @@ -54,121 +54,121 @@ fragment main_Output main_( u2_ = _e28 + metal::uint2(texture_array_unbounded[uniform_index].get_width(), texture_array_unbounded[uniform_index].get_height()); metal::uint2 _e33 = u2_; u2_ = _e33 + metal::uint2(texture_array_unbounded[non_uniform_index].get_width(), texture_array_unbounded[non_uniform_index].get_height()); - metal::float4 _e41 = texture_array_bounded[0].gather(samp[0], uv); - metal::float4 _e42 = v4_; - v4_ = _e42 + _e41; - metal::float4 _e48 = texture_array_bounded[uniform_index].gather(samp[uniform_index], uv); - metal::float4 _e49 = v4_; - v4_ = _e49 + _e48; - metal::float4 _e55 = texture_array_bounded[non_uniform_index].gather(samp[non_uniform_index], uv); - metal::float4 _e56 = v4_; - v4_ = _e56 + _e55; - metal::float4 _e65 = texture_array_depth[0].gather_compare(samp_comp[0], uv, 0.0); - metal::float4 _e66 = v4_; - v4_ = _e66 + _e65; - metal::float4 _e73 = texture_array_depth[uniform_index].gather_compare(samp_comp[uniform_index], uv, 0.0); - metal::float4 _e74 = v4_; - v4_ = _e74 + _e73; - metal::float4 _e81 = texture_array_depth[non_uniform_index].gather_compare(samp_comp[non_uniform_index], uv, 0.0); - metal::float4 _e82 = v4_; - v4_ = _e82 + _e81; - metal::float4 _e88 = (uint(0) < texture_array_unbounded[0].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[0].get_width(0), texture_array_unbounded[0].get_height(0))) ? texture_array_unbounded[0].read(metal::uint2(pix), 0): DefaultConstructible()); - metal::float4 _e89 = v4_; - v4_ = _e89 + _e88; - metal::float4 _e94 = (uint(0) < texture_array_unbounded[uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[uniform_index].get_width(0), texture_array_unbounded[uniform_index].get_height(0))) ? texture_array_unbounded[uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); - metal::float4 _e95 = v4_; - v4_ = _e95 + _e94; - metal::float4 _e100 = (uint(0) < texture_array_unbounded[non_uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[non_uniform_index].get_width(0), texture_array_unbounded[non_uniform_index].get_height(0))) ? texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); - metal::float4 _e101 = v4_; - v4_ = _e101 + _e100; - uint _e107 = u1_; - u1_ = _e107 + texture_array_2darray[0].get_array_size(); - uint _e112 = u1_; - u1_ = _e112 + texture_array_2darray[uniform_index].get_array_size(); - uint _e117 = u1_; - u1_ = _e117 + texture_array_2darray[non_uniform_index].get_array_size(); - uint _e123 = u1_; - u1_ = _e123 + texture_array_bounded[0].get_num_mip_levels(); - uint _e128 = u1_; - u1_ = _e128 + texture_array_bounded[uniform_index].get_num_mip_levels(); - uint _e133 = u1_; - u1_ = _e133 + texture_array_bounded[non_uniform_index].get_num_mip_levels(); - uint _e139 = u1_; - u1_ = _e139 + texture_array_multisampled[0].get_num_samples(); - uint _e144 = u1_; - u1_ = _e144 + texture_array_multisampled[uniform_index].get_num_samples(); - uint _e149 = u1_; - u1_ = _e149 + texture_array_multisampled[non_uniform_index].get_num_samples(); - metal::float4 _e157 = texture_array_bounded[0].sample(samp[0], uv); - metal::float4 _e158 = v4_; - v4_ = _e158 + _e157; - metal::float4 _e164 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv); - metal::float4 _e165 = v4_; - v4_ = _e165 + _e164; - metal::float4 _e171 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv); - metal::float4 _e172 = v4_; - v4_ = _e172 + _e171; - metal::float4 _e181 = texture_array_bounded[0].sample(samp[0], uv, metal::bias(0.0)); - metal::float4 _e182 = v4_; - v4_ = _e182 + _e181; - metal::float4 _e189 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::bias(0.0)); - metal::float4 _e190 = v4_; - v4_ = _e190 + _e189; - metal::float4 _e197 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::bias(0.0)); - metal::float4 _e198 = v4_; - v4_ = _e198 + _e197; - float _e207 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); - float _e208 = v1_; - v1_ = _e208 + _e207; - float _e215 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); - float _e216 = v1_; - v1_ = _e216 + _e215; - float _e223 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); - float _e224 = v1_; - v1_ = _e224 + _e223; - float _e233 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); - float _e234 = v1_; - v1_ = _e234 + _e233; - float _e241 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); - float _e242 = v1_; - v1_ = _e242 + _e241; - float _e249 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); - float _e250 = v1_; - v1_ = _e250 + _e249; - metal::float4 _e258 = texture_array_bounded[0].sample(samp[0], uv, metal::gradient2d(uv, uv)); - metal::float4 _e259 = v4_; - v4_ = _e259 + _e258; - metal::float4 _e265 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::gradient2d(uv, uv)); - metal::float4 _e266 = v4_; - v4_ = _e266 + _e265; - metal::float4 _e272 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::gradient2d(uv, uv)); - metal::float4 _e273 = v4_; - v4_ = _e273 + _e272; - metal::float4 _e282 = texture_array_bounded[0].sample(samp[0], uv, metal::level(0.0)); - metal::float4 _e283 = v4_; - v4_ = _e283 + _e282; - metal::float4 _e290 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::level(0.0)); - metal::float4 _e291 = v4_; - v4_ = _e291 + _e290; - metal::float4 _e298 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::level(0.0)); - metal::float4 _e299 = v4_; - v4_ = _e299 + _e298; - metal::float4 _e304 = v4_; - if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[0].get_width(), texture_array_storage[0].get_height()))) { - texture_array_storage[0].write(_e304, metal::uint2(pix)); - } + metal::float4 _e42 = texture_array_bounded[0].gather(samp[0], uv); + metal::float4 _e43 = v4_; + v4_ = _e43 + _e42; + metal::float4 _e50 = texture_array_bounded[uniform_index].gather(samp[uniform_index], uv); + metal::float4 _e51 = v4_; + v4_ = _e51 + _e50; + metal::float4 _e58 = texture_array_bounded[non_uniform_index].gather(samp[non_uniform_index], uv); + metal::float4 _e59 = v4_; + v4_ = _e59 + _e58; + metal::float4 _e68 = texture_array_depth[0].gather_compare(samp_comp[0], uv, 0.0); + metal::float4 _e69 = v4_; + v4_ = _e69 + _e68; + metal::float4 _e76 = texture_array_depth[uniform_index].gather_compare(samp_comp[uniform_index], uv, 0.0); + metal::float4 _e77 = v4_; + v4_ = _e77 + _e76; + metal::float4 _e84 = texture_array_depth[non_uniform_index].gather_compare(samp_comp[non_uniform_index], uv, 0.0); + metal::float4 _e85 = v4_; + v4_ = _e85 + _e84; + metal::float4 _e91 = (uint(0) < texture_array_unbounded[0].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[0].get_width(0), texture_array_unbounded[0].get_height(0))) ? texture_array_unbounded[0].read(metal::uint2(pix), 0): DefaultConstructible()); + metal::float4 _e92 = v4_; + v4_ = _e92 + _e91; + metal::float4 _e97 = (uint(0) < texture_array_unbounded[uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[uniform_index].get_width(0), texture_array_unbounded[uniform_index].get_height(0))) ? texture_array_unbounded[uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); + metal::float4 _e98 = v4_; + v4_ = _e98 + _e97; + metal::float4 _e103 = (uint(0) < texture_array_unbounded[non_uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[non_uniform_index].get_width(0), texture_array_unbounded[non_uniform_index].get_height(0))) ? texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); + metal::float4 _e104 = v4_; + v4_ = _e104 + _e103; + uint _e110 = u1_; + u1_ = _e110 + texture_array_2darray[0].get_array_size(); + uint _e115 = u1_; + u1_ = _e115 + texture_array_2darray[uniform_index].get_array_size(); + uint _e120 = u1_; + u1_ = _e120 + texture_array_2darray[non_uniform_index].get_array_size(); + uint _e126 = u1_; + u1_ = _e126 + texture_array_bounded[0].get_num_mip_levels(); + uint _e131 = u1_; + u1_ = _e131 + texture_array_bounded[uniform_index].get_num_mip_levels(); + uint _e136 = u1_; + u1_ = _e136 + texture_array_bounded[non_uniform_index].get_num_mip_levels(); + uint _e142 = u1_; + u1_ = _e142 + texture_array_multisampled[0].get_num_samples(); + uint _e147 = u1_; + u1_ = _e147 + texture_array_multisampled[uniform_index].get_num_samples(); + uint _e152 = u1_; + u1_ = _e152 + texture_array_multisampled[non_uniform_index].get_num_samples(); + metal::float4 _e160 = texture_array_bounded[0].sample(samp[0], uv); + metal::float4 _e161 = v4_; + v4_ = _e161 + _e160; + metal::float4 _e167 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv); + metal::float4 _e168 = v4_; + v4_ = _e168 + _e167; + metal::float4 _e174 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv); + metal::float4 _e175 = v4_; + v4_ = _e175 + _e174; + metal::float4 _e184 = texture_array_bounded[0].sample(samp[0], uv, metal::bias(0.0)); + metal::float4 _e185 = v4_; + v4_ = _e185 + _e184; + metal::float4 _e192 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::bias(0.0)); + metal::float4 _e193 = v4_; + v4_ = _e193 + _e192; + metal::float4 _e200 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::bias(0.0)); + metal::float4 _e201 = v4_; + v4_ = _e201 + _e200; + float _e210 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); + float _e211 = v1_; + v1_ = _e211 + _e210; + float _e218 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); + float _e219 = v1_; + v1_ = _e219 + _e218; + float _e226 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); + float _e227 = v1_; + v1_ = _e227 + _e226; + float _e236 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); + float _e237 = v1_; + v1_ = _e237 + _e236; + float _e244 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); + float _e245 = v1_; + v1_ = _e245 + _e244; + float _e252 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); + float _e253 = v1_; + v1_ = _e253 + _e252; + metal::float4 _e261 = texture_array_bounded[0].sample(samp[0], uv, metal::gradient2d(uv, uv)); + metal::float4 _e262 = v4_; + v4_ = _e262 + _e261; + metal::float4 _e268 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::gradient2d(uv, uv)); + metal::float4 _e269 = v4_; + v4_ = _e269 + _e268; + metal::float4 _e275 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::gradient2d(uv, uv)); + metal::float4 _e276 = v4_; + v4_ = _e276 + _e275; + metal::float4 _e285 = texture_array_bounded[0].sample(samp[0], uv, metal::level(0.0)); + metal::float4 _e286 = v4_; + v4_ = _e286 + _e285; + metal::float4 _e293 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::level(0.0)); + metal::float4 _e294 = v4_; + v4_ = _e294 + _e293; + metal::float4 _e301 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::level(0.0)); + metal::float4 _e302 = v4_; + v4_ = _e302 + _e301; metal::float4 _e307 = v4_; - if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[uniform_index].get_width(), texture_array_storage[uniform_index].get_height()))) { - texture_array_storage[uniform_index].write(_e307, metal::uint2(pix)); + if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[0].get_width(), texture_array_storage[0].get_height()))) { + texture_array_storage[0].write(_e307, metal::uint2(pix)); } metal::float4 _e310 = v4_; - if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[non_uniform_index].get_width(), texture_array_storage[non_uniform_index].get_height()))) { - texture_array_storage[non_uniform_index].write(_e310, metal::uint2(pix)); + if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[uniform_index].get_width(), texture_array_storage[uniform_index].get_height()))) { + texture_array_storage[uniform_index].write(_e310, metal::uint2(pix)); } - metal::uint2 _e311 = u2_; - uint _e312 = u1_; - metal::float2 v2_ = static_cast(_e311 + metal::uint2(_e312)); - metal::float4 _e316 = v4_; - float _e323 = v1_; - return main_Output { (_e316 + metal::float4(v2_.x, v2_.y, v2_.x, v2_.y)) + metal::float4(_e323) }; + metal::float4 _e313 = v4_; + if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[non_uniform_index].get_width(), texture_array_storage[non_uniform_index].get_height()))) { + texture_array_storage[non_uniform_index].write(_e313, metal::uint2(pix)); + } + metal::uint2 _e314 = u2_; + uint _e315 = u1_; + metal::float2 v2_ = static_cast(_e314 + metal::uint2(_e315)); + metal::float4 _e319 = v4_; + float _e326 = v1_; + return main_Output { (_e319 + metal::float4(v2_.x, v2_.y, v2_.x, v2_.y)) + metal::float4(_e326) }; } diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index 100a6dc1e..1a81aaf68 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -9,7 +9,6 @@ struct _mslBufferSizes { uint size2; }; -constexpr constant unsigned NUM_PARTICLES = 1500u; struct Particle { metal::float2 pos; metal::float2 vel; @@ -27,6 +26,7 @@ typedef Particle type_3[1]; struct Particles { type_3 particles; }; +constant uint NUM_PARTICLES = 1500u; struct main_Input { }; diff --git a/tests/out/msl/do-while.msl b/tests/out/msl/do-while.msl index ac2393bf7..4f928d1f3 100644 --- a/tests/out/msl/do-while.msl +++ b/tests/out/msl/do-while.msl @@ -11,7 +11,7 @@ void fb1_( bool loop_init = true; while(true) { if (!loop_init) { - bool _e6 = cond; + bool _e2 = cond; if (!(cond)) { break; } diff --git a/tests/out/msl/empty-global-name.msl b/tests/out/msl/empty-global-name.msl index 6001dba93..f456649bc 100644 --- a/tests/out/msl/empty-global-name.msl +++ b/tests/out/msl/empty-global-name.msl @@ -11,8 +11,8 @@ struct type_1 { void function( device type_1& unnamed ) { - int _e8 = unnamed.member; - unnamed.member = _e8 + 1; + int _e4 = unnamed.member; + unnamed.member = _e4 + 1; return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 786e03ea5..d9142c199 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -8,7 +8,6 @@ struct _mslBufferSizes { uint size3; }; -constexpr constant bool Foo_1 = true; struct type_2 { float inner[10]; }; @@ -32,6 +31,7 @@ struct type_14 { struct type_15 { type_14 inner[2]; }; +constant bool Foo_1 = true; void test_msl_packed_vec3_as_arg( metal::float3 arg diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 77c0a8679..e390c2e0f 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -4,7 +4,6 @@ using metal::uint; -constant metal::int2 const_type_9_ = {3, 1}; struct main_Input { }; @@ -126,46 +125,46 @@ fragment texture_sampleOutput texture_sample( metal::float4 _e14 = image_2d.sample(sampler_reg, tc); metal::float4 _e15 = a; a = _e15 + _e14; - metal::float4 _e19 = image_2d.sample(sampler_reg, tc, const_type_9_); + metal::float4 _e19 = image_2d.sample(sampler_reg, tc, metal::int2(3, 1)); metal::float4 _e20 = a; a = _e20 + _e19; metal::float4 _e24 = image_2d.sample(sampler_reg, tc, metal::level(2.3)); metal::float4 _e25 = a; a = _e25 + _e24; - metal::float4 _e29 = image_2d.sample(sampler_reg, tc, metal::level(2.3), const_type_9_); + metal::float4 _e29 = image_2d.sample(sampler_reg, tc, metal::level(2.3), metal::int2(3, 1)); metal::float4 _e30 = a; a = _e30 + _e29; - metal::float4 _e35 = image_2d.sample(sampler_reg, tc, metal::bias(2.0), const_type_9_); + metal::float4 _e35 = image_2d.sample(sampler_reg, tc, metal::bias(2.0), metal::int2(3, 1)); metal::float4 _e36 = a; a = _e36 + _e35; metal::float4 _e41 = image_2d_array.sample(sampler_reg, tc, 0u); metal::float4 _e42 = a; a = _e42 + _e41; - metal::float4 _e47 = image_2d_array.sample(sampler_reg, tc, 0u, const_type_9_); + metal::float4 _e47 = image_2d_array.sample(sampler_reg, tc, 0u, metal::int2(3, 1)); metal::float4 _e48 = a; a = _e48 + _e47; metal::float4 _e53 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3)); metal::float4 _e54 = a; a = _e54 + _e53; - metal::float4 _e59 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3), const_type_9_); + metal::float4 _e59 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3), metal::int2(3, 1)); metal::float4 _e60 = a; a = _e60 + _e59; - metal::float4 _e66 = image_2d_array.sample(sampler_reg, tc, 0u, metal::bias(2.0), const_type_9_); + metal::float4 _e66 = image_2d_array.sample(sampler_reg, tc, 0u, metal::bias(2.0), metal::int2(3, 1)); metal::float4 _e67 = a; a = _e67 + _e66; metal::float4 _e72 = image_2d_array.sample(sampler_reg, tc, 0); metal::float4 _e73 = a; a = _e73 + _e72; - metal::float4 _e78 = image_2d_array.sample(sampler_reg, tc, 0, const_type_9_); + metal::float4 _e78 = image_2d_array.sample(sampler_reg, tc, 0, metal::int2(3, 1)); metal::float4 _e79 = a; a = _e79 + _e78; metal::float4 _e84 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3)); metal::float4 _e85 = a; a = _e85 + _e84; - metal::float4 _e90 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3), const_type_9_); + metal::float4 _e90 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3), metal::int2(3, 1)); metal::float4 _e91 = a; a = _e91 + _e90; - metal::float4 _e97 = image_2d_array.sample(sampler_reg, tc, 0, metal::bias(2.0), const_type_9_); + metal::float4 _e97 = image_2d_array.sample(sampler_reg, tc, 0, metal::bias(2.0), metal::int2(3, 1)); metal::float4 _e98 = a; a = _e98 + _e97; metal::float4 _e103 = image_cube_array.sample(sampler_reg, tc3_, 0u); @@ -245,9 +244,9 @@ fragment gatherOutput gather( ) { metal::float2 tc_2 = metal::float2(0.5); metal::float4 s2d = image_2d.gather(sampler_reg, tc_2, metal::int2(0), metal::component::y); - metal::float4 s2d_offset = image_2d.gather(sampler_reg, tc_2, const_type_9_, metal::component::w); + metal::float4 s2d_offset = image_2d.gather(sampler_reg, tc_2, metal::int2(3, 1), metal::component::w); metal::float4 s2d_depth = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5); - metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, const_type_9_); + metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, metal::int2(3, 1)); metal::uint4 u = image_2d_u32_.gather(sampler_reg, tc_2); metal::int4 i = image_2d_i32_.gather(sampler_reg, tc_2); metal::float4 f = static_cast(u) + static_cast(i); diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 33f13e1cb..78614ffbd 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -14,10 +14,10 @@ struct type_13 { struct type_14 { int inner[4]; }; -constant metal::float4 v_f32_one = {1.0, 1.0, 1.0, 1.0}; -constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0}; -constant metal::float4 v_f32_half = {0.5, 0.5, 0.5, 0.5}; -constant metal::int4 v_i32_one = {1, 1, 1, 1}; +constant metal::float4 v_f32_one = metal::float4(1.0, 1.0, 1.0, 1.0); +constant metal::float4 v_f32_zero = metal::float4(0.0, 0.0, 0.0, 0.0); +constant metal::float4 v_f32_half = metal::float4(0.5, 0.5, 0.5, 0.5); +constant metal::int4 v_i32_one = metal::int4(1, 1, 1, 1); metal::float4 builtins( ) { @@ -263,15 +263,15 @@ void assignment( a_1 = _e27 << 2u; int _e30 = a_1; a_1 = _e30 >> 1u; - int _e32 = a_1; - a_1 = _e32 + 1; - int _e35 = a_1; - a_1 = _e35 - 1; + int _e33 = a_1; + a_1 = _e33 + 1; + int _e36 = a_1; + a_1 = _e36 - 1; vec0_ = metal::int3 {}; - int _e42 = vec0_.y; - vec0_.y = _e42 + 1; - int _e47 = vec0_.y; - vec0_.y = _e47 - 1; + int _e43 = vec0_.y; + vec0_.y = _e43 + 1; + int _e48 = vec0_.y; + vec0_.y = _e48 - 1; return; } diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index d5e62774e..d322cbcb9 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -17,9 +17,6 @@ struct type_9 { metal::float2 member; metal::float4 gl_Position; }; -constant metal::float4 const_type_3_ = {0.0, 0.0, 0.0, 1.0}; -constant type_5 const_type_5_ = {0.0}; -constant gl_PerVertex const_gl_PerVertex = {const_type_3_, 1.0, const_type_5_, const_type_5_}; void main_1( thread metal::float2& v_uv, @@ -27,10 +24,10 @@ void main_1( thread gl_PerVertex& perVertexStruct, thread metal::float2& a_pos_1 ) { - metal::float2 _e12 = a_uv_1; - v_uv = _e12; - metal::float2 _e13 = a_pos_1; - perVertexStruct.gl_Position = metal::float4(_e13.x, _e13.y, 0.0, 1.0); + metal::float2 _e8 = a_uv_1; + v_uv = _e8; + metal::float2 _e9 = a_pos_1; + perVertexStruct.gl_Position = metal::float4(_e9.x, _e9.y, 0.0, 1.0); return; } @@ -47,7 +44,7 @@ vertex main_Output main_( ) { metal::float2 v_uv = {}; metal::float2 a_uv_1 = {}; - gl_PerVertex perVertexStruct = const_gl_PerVertex; + gl_PerVertex perVertexStruct = gl_PerVertex {metal::float4(0.0, 0.0, 0.0, 1.0), 1.0, type_5 {}, type_5 {}}; metal::float2 a_pos_1 = {}; const auto a_uv = varyings.a_uv; const auto a_pos = varyings.a_pos; diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl index a6beb30b8..5fa5788aa 100644 --- a/tests/out/msl/quad.msl +++ b/tests/out/msl/quad.msl @@ -4,11 +4,11 @@ using metal::uint; -constexpr constant float c_scale = 1.2000000476837158; struct VertexOutput { metal::float2 uv; metal::float4 position; }; +constant float c_scale = 1.2; struct vert_mainInput { metal::float2 pos [[attribute(0)]]; diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index fa1b284c6..53f320344 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -8,7 +8,6 @@ struct _mslBufferSizes { uint size2; }; -constexpr constant unsigned c_max_lights = 10u; struct Globals { metal::float4x4 view_proj; metal::uint4 num_lights; @@ -31,7 +30,8 @@ typedef Light type_6[1]; struct type_7 { Light inner[10]; }; -constant metal::float3 c_ambient = {0.05000000074505806, 0.05000000074505806, 0.05000000074505806}; +constant metal::float3 c_ambient = metal::float3(0.05, 0.05, 0.05); +constant uint c_max_lights = 10u; float fetch_shadow( uint light_id, @@ -105,8 +105,8 @@ fragment fs_mainOutput fs_main( bool loop_init = true; while(true) { if (!loop_init) { - uint _e39 = i; - i = _e39 + 1u; + uint _e40 = i; + i = _e40 + 1u; } loop_init = false; uint _e7 = i; @@ -157,8 +157,8 @@ fragment fs_main_without_storageOutput fs_main_without_storage( bool loop_init_1 = true; while(true) { if (!loop_init_1) { - uint _e39 = i_1; - i_1 = _e39 + 1u; + uint _e40 = i_1; + i_1 = _e40 + 1u; } loop_init_1 = false; uint _e7 = i_1; diff --git a/tests/out/msl/workgroup-uniform-load.msl b/tests/out/msl/workgroup-uniform-load.msl index cd85811d9..37a878173 100644 --- a/tests/out/msl/workgroup-uniform-load.msl +++ b/tests/out/msl/workgroup-uniform-load.msl @@ -4,10 +4,10 @@ using metal::uint; -constexpr constant unsigned SIZE = 128u; struct type_2 { int inner[128]; }; +constant uint SIZE = 128u; struct test_workgroupUniformLoadInput { }; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 12d2ceef2..8687ddb6a 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -11,32 +11,32 @@ OpEntryPoint Fragment %286 "foo_frag" %285 OpEntryPoint GLCompute %306 "assign_through_ptr" %309 OpExecutionMode %286 OriginUpperLeft OpExecutionMode %306 LocalSize 1 1 1 -OpMemberName %12 0 "a" -OpMemberName %12 1 "b" -OpMemberName %12 2 "c" -OpName %12 "GlobalConst" -OpMemberName %13 0 "value" -OpName %13 "AlignedWrapper" -OpMemberName %26 0 "_matrix" -OpMemberName %26 1 "matrix_array" -OpMemberName %26 2 "atom" -OpMemberName %26 3 "atom_arr" -OpMemberName %26 4 "arr" -OpMemberName %26 5 "data" -OpName %26 "Bar" -OpMemberName %28 0 "m" -OpName %28 "Baz" -OpMemberName %32 0 "am" -OpName %32 "MatCx2InArray" -OpName %46 "global_const" -OpName %48 "bar" -OpName %50 "baz" -OpName %53 "qux" -OpName %56 "nested_mat_cx2" -OpName %59 "val" -OpName %60 "idx" -OpName %63 "t" -OpName %67 "test_matrix_within_struct_accesses" +OpMemberName %6 0 "a" +OpMemberName %6 1 "b" +OpMemberName %6 2 "c" +OpName %6 "GlobalConst" +OpMemberName %7 0 "value" +OpName %7 "AlignedWrapper" +OpMemberName %20 0 "_matrix" +OpMemberName %20 1 "matrix_array" +OpMemberName %20 2 "atom" +OpMemberName %20 3 "atom_arr" +OpMemberName %20 4 "arr" +OpMemberName %20 5 "data" +OpName %20 "Bar" +OpMemberName %22 0 "m" +OpName %22 "Baz" +OpMemberName %26 0 "am" +OpName %26 "MatCx2InArray" +OpName %45 "global_const" +OpName %47 "bar" +OpName %49 "baz" +OpName %52 "qux" +OpName %55 "nested_mat_cx2" +OpName %58 "val" +OpName %59 "idx" +OpName %62 "t" +OpName %66 "test_matrix_within_struct_accesses" OpName %137 "idx" OpName %139 "t" OpName %143 "test_matrix_within_array_within_struct_accesses" @@ -55,337 +55,337 @@ OpName %239 "foo_vert" OpName %286 "foo_frag" OpName %303 "arr" OpName %306 "assign_through_ptr" -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 16 -OpMemberDecorate %12 2 Offset 28 -OpMemberDecorate %13 0 Offset 0 -OpDecorate %19 ArrayStride 16 -OpDecorate %21 ArrayStride 4 -OpDecorate %24 ArrayStride 8 -OpDecorate %25 ArrayStride 8 +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %6 1 Offset 16 +OpMemberDecorate %6 2 Offset 28 +OpMemberDecorate %7 0 Offset 0 +OpDecorate %13 ArrayStride 16 +OpDecorate %15 ArrayStride 4 +OpDecorate %18 ArrayStride 8 +OpDecorate %19 ArrayStride 8 +OpMemberDecorate %20 0 Offset 0 +OpMemberDecorate %20 0 ColMajor +OpMemberDecorate %20 0 MatrixStride 16 +OpMemberDecorate %20 1 Offset 64 +OpMemberDecorate %20 1 ColMajor +OpMemberDecorate %20 1 MatrixStride 8 +OpMemberDecorate %20 2 Offset 96 +OpMemberDecorate %20 3 Offset 100 +OpMemberDecorate %20 4 Offset 144 +OpMemberDecorate %20 5 Offset 160 +OpMemberDecorate %22 0 Offset 0 +OpMemberDecorate %22 0 ColMajor +OpMemberDecorate %22 0 MatrixStride 8 +OpDecorate %25 ArrayStride 32 OpMemberDecorate %26 0 Offset 0 OpMemberDecorate %26 0 ColMajor -OpMemberDecorate %26 0 MatrixStride 16 -OpMemberDecorate %26 1 Offset 64 -OpMemberDecorate %26 1 ColMajor -OpMemberDecorate %26 1 MatrixStride 8 -OpMemberDecorate %26 2 Offset 96 -OpMemberDecorate %26 3 Offset 100 -OpMemberDecorate %26 4 Offset 144 -OpMemberDecorate %26 5 Offset 160 -OpMemberDecorate %28 0 Offset 0 -OpMemberDecorate %28 0 ColMajor -OpMemberDecorate %28 0 MatrixStride 8 -OpDecorate %31 ArrayStride 32 -OpMemberDecorate %32 0 Offset 0 -OpMemberDecorate %32 0 ColMajor -OpMemberDecorate %32 0 MatrixStride 8 -OpDecorate %34 ArrayStride 4 -OpDecorate %35 ArrayStride 40 -OpDecorate %39 ArrayStride 4 -OpDecorate %42 ArrayStride 16 -OpDecorate %48 DescriptorSet 0 -OpDecorate %48 Binding 0 -OpDecorate %26 Block -OpDecorate %50 DescriptorSet 0 -OpDecorate %50 Binding 1 -OpDecorate %51 Block -OpMemberDecorate %51 0 Offset 0 -OpDecorate %53 DescriptorSet 0 -OpDecorate %53 Binding 2 -OpDecorate %54 Block -OpMemberDecorate %54 0 Offset 0 -OpDecorate %56 DescriptorSet 0 -OpDecorate %56 Binding 3 -OpDecorate %57 Block -OpMemberDecorate %57 0 Offset 0 +OpMemberDecorate %26 0 MatrixStride 8 +OpDecorate %28 ArrayStride 4 +OpDecorate %29 ArrayStride 40 +OpDecorate %33 ArrayStride 4 +OpDecorate %36 ArrayStride 16 +OpDecorate %47 DescriptorSet 0 +OpDecorate %47 Binding 0 +OpDecorate %20 Block +OpDecorate %49 DescriptorSet 0 +OpDecorate %49 Binding 1 +OpDecorate %50 Block +OpMemberDecorate %50 0 Offset 0 +OpDecorate %52 DescriptorSet 0 +OpDecorate %52 Binding 2 +OpDecorate %53 Block +OpMemberDecorate %53 0 Offset 0 +OpDecorate %55 DescriptorSet 0 +OpDecorate %55 Binding 3 +OpDecorate %56 Block +OpMemberDecorate %56 0 Offset 0 OpDecorate %234 BuiltIn VertexIndex OpDecorate %237 BuiltIn Position OpDecorate %285 Location 0 OpDecorate %309 BuiltIn LocalInvocationId %2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpConstant %4 0 -%6 = OpTypeInt 32 1 -%5 = OpConstant %6 0 -%7 = OpConstant %6 2 -%8 = OpConstant %6 10 -%9 = OpConstant %6 1 -%10 = OpConstant %6 5 -%11 = OpTypeVector %4 3 -%12 = OpTypeStruct %4 %11 %6 -%13 = OpTypeStruct %6 -%16 = OpTypeFloat 32 -%15 = OpTypeVector %16 3 -%14 = OpTypeMatrix %15 4 -%18 = OpTypeVector %16 2 -%17 = OpTypeMatrix %18 2 -%20 = OpConstant %4 2 -%19 = OpTypeArray %17 %20 -%22 = OpConstant %4 10 -%21 = OpTypeArray %6 %22 -%23 = OpTypeVector %4 2 -%24 = OpTypeArray %23 %20 -%25 = OpTypeRuntimeArray %13 -%26 = OpTypeStruct %14 %19 %6 %21 %24 %25 -%27 = OpTypeMatrix %18 3 -%28 = OpTypeStruct %27 -%29 = OpTypeVector %6 2 -%30 = OpTypeMatrix %18 4 -%31 = OpTypeArray %30 %20 -%32 = OpTypeStruct %31 -%33 = OpTypePointer Function %16 -%34 = OpTypeArray %16 %22 -%36 = OpConstant %4 5 -%35 = OpTypeArray %34 %36 -%37 = OpTypeVector %16 4 -%38 = OpTypePointer StorageBuffer %6 -%39 = OpTypeArray %6 %36 -%40 = OpTypeVector %6 4 -%41 = OpTypePointer Workgroup %4 -%42 = OpTypeArray %37 %20 -%43 = OpTypePointer Function %42 -%44 = OpConstantComposite %11 %3 %3 %3 -%45 = OpConstantComposite %12 %3 %44 %5 -%47 = OpTypePointer Private %12 -%46 = OpVariable %47 Private %45 -%49 = OpTypePointer StorageBuffer %26 -%48 = OpVariable %49 StorageBuffer -%51 = OpTypeStruct %28 -%52 = OpTypePointer Uniform %51 -%50 = OpVariable %52 Uniform -%54 = OpTypeStruct %29 -%55 = OpTypePointer StorageBuffer %54 -%53 = OpVariable %55 StorageBuffer -%57 = OpTypeStruct %32 -%58 = OpTypePointer Uniform %57 -%56 = OpVariable %58 Uniform -%59 = OpVariable %41 Workgroup -%61 = OpTypePointer Function %6 -%62 = OpConstantNull %6 -%64 = OpTypePointer Function %28 -%65 = OpConstantNull %28 -%68 = OpTypeFunction %2 -%69 = OpTypePointer Uniform %28 -%71 = OpConstant %16 1.0 -%72 = OpConstant %16 2.0 -%73 = OpConstant %16 3.0 -%74 = OpConstant %16 6.0 -%75 = OpConstant %16 5.0 -%76 = OpConstant %16 4.0 -%77 = OpConstant %16 9.0 -%78 = OpConstant %16 90.0 -%79 = OpConstant %16 10.0 -%80 = OpConstant %16 20.0 -%81 = OpConstant %16 30.0 -%82 = OpConstant %16 40.0 -%86 = OpTypePointer Uniform %27 -%89 = OpTypePointer Uniform %18 -%95 = OpTypePointer Uniform %16 -%96 = OpConstant %4 1 -%116 = OpTypePointer Function %27 -%122 = OpTypePointer Function %18 -%128 = OpTypePointer Function %16 -%138 = OpConstantNull %6 -%140 = OpTypePointer Function %32 -%141 = OpConstantNull %32 -%144 = OpTypePointer Uniform %32 -%146 = OpConstantNull %31 -%147 = OpConstantNull %31 -%148 = OpConstant %16 8.0 -%149 = OpConstant %16 7.0 -%153 = OpTypePointer Uniform %31 -%156 = OpTypePointer Uniform %30 -%179 = OpTypePointer Function %31 -%181 = OpTypePointer Function %30 -%204 = OpTypeFunction %16 %33 -%210 = OpTypeFunction %16 %35 -%217 = OpTypeFunction %2 %41 -%218 = OpConstant %4 42 -%223 = OpTypeFunction %2 %43 -%229 = OpConstantNull %16 -%231 = OpTypePointer Function %39 -%232 = OpConstantNull %39 -%235 = OpTypePointer Input %4 +%3 = OpTypeInt 32 0 +%4 = OpTypeVector %3 3 +%5 = OpTypeInt 32 1 +%6 = OpTypeStruct %3 %4 %5 +%7 = OpTypeStruct %5 +%10 = OpTypeFloat 32 +%9 = OpTypeVector %10 3 +%8 = OpTypeMatrix %9 4 +%12 = OpTypeVector %10 2 +%11 = OpTypeMatrix %12 2 +%14 = OpConstant %3 2 +%13 = OpTypeArray %11 %14 +%16 = OpConstant %3 10 +%15 = OpTypeArray %5 %16 +%17 = OpTypeVector %3 2 +%18 = OpTypeArray %17 %14 +%19 = OpTypeRuntimeArray %7 +%20 = OpTypeStruct %8 %13 %5 %15 %18 %19 +%21 = OpTypeMatrix %12 3 +%22 = OpTypeStruct %21 +%23 = OpTypeVector %5 2 +%24 = OpTypeMatrix %12 4 +%25 = OpTypeArray %24 %14 +%26 = OpTypeStruct %25 +%27 = OpTypePointer Function %10 +%28 = OpTypeArray %10 %16 +%30 = OpConstant %3 5 +%29 = OpTypeArray %28 %30 +%31 = OpTypeVector %10 4 +%32 = OpTypePointer StorageBuffer %5 +%33 = OpTypeArray %5 %30 +%34 = OpTypeVector %5 4 +%35 = OpTypePointer Workgroup %3 +%36 = OpTypeArray %31 %14 +%37 = OpTypePointer Function %36 +%38 = OpConstant %3 0 +%39 = OpConstantComposite %4 %38 %38 %38 +%40 = OpConstant %5 0 +%41 = OpConstantComposite %6 %38 %39 %40 +%42 = OpConstant %5 2 +%43 = OpConstant %5 10 +%44 = OpConstant %5 5 +%46 = OpTypePointer Private %6 +%45 = OpVariable %46 Private %41 +%48 = OpTypePointer StorageBuffer %20 +%47 = OpVariable %48 StorageBuffer +%50 = OpTypeStruct %22 +%51 = OpTypePointer Uniform %50 +%49 = OpVariable %51 Uniform +%53 = OpTypeStruct %23 +%54 = OpTypePointer StorageBuffer %53 +%52 = OpVariable %54 StorageBuffer +%56 = OpTypeStruct %26 +%57 = OpTypePointer Uniform %56 +%55 = OpVariable %57 Uniform +%58 = OpVariable %35 Workgroup +%60 = OpTypePointer Function %5 +%61 = OpConstantNull %5 +%63 = OpTypePointer Function %22 +%64 = OpConstantNull %22 +%67 = OpTypeFunction %2 +%68 = OpTypePointer Uniform %22 +%70 = OpConstant %5 1 +%71 = OpConstant %10 1.0 +%72 = OpConstant %10 2.0 +%73 = OpConstant %10 3.0 +%74 = OpConstant %10 6.0 +%75 = OpConstant %10 5.0 +%76 = OpConstant %10 4.0 +%77 = OpConstant %10 9.0 +%78 = OpConstant %10 90.0 +%79 = OpConstant %10 10.0 +%80 = OpConstant %10 20.0 +%81 = OpConstant %10 30.0 +%82 = OpConstant %10 40.0 +%86 = OpTypePointer Uniform %21 +%89 = OpTypePointer Uniform %12 +%95 = OpTypePointer Uniform %10 +%96 = OpConstant %3 1 +%116 = OpTypePointer Function %21 +%122 = OpTypePointer Function %12 +%128 = OpTypePointer Function %10 +%138 = OpConstantNull %5 +%140 = OpTypePointer Function %26 +%141 = OpConstantNull %26 +%144 = OpTypePointer Uniform %26 +%146 = OpConstantNull %25 +%147 = OpConstantNull %25 +%148 = OpConstant %10 8.0 +%149 = OpConstant %10 7.0 +%153 = OpTypePointer Uniform %25 +%156 = OpTypePointer Uniform %24 +%179 = OpTypePointer Function %25 +%181 = OpTypePointer Function %24 +%204 = OpTypeFunction %10 %27 +%210 = OpTypeFunction %10 %29 +%217 = OpTypeFunction %2 %35 +%218 = OpConstant %3 42 +%223 = OpTypeFunction %2 %37 +%229 = OpConstantNull %10 +%231 = OpTypePointer Function %33 +%232 = OpConstantNull %33 +%235 = OpTypePointer Input %3 %234 = OpVariable %235 Input -%238 = OpTypePointer Output %37 +%238 = OpTypePointer Output %31 %237 = OpVariable %238 Output -%241 = OpTypePointer StorageBuffer %29 -%244 = OpConstant %16 0.0 -%245 = OpConstant %4 3 -%246 = OpConstant %6 3 -%247 = OpConstant %6 4 -%248 = OpConstant %6 42 -%249 = OpConstantNull %35 -%254 = OpTypePointer StorageBuffer %14 -%257 = OpTypePointer StorageBuffer %24 -%258 = OpConstant %4 4 -%261 = OpTypePointer StorageBuffer %15 -%262 = OpTypePointer StorageBuffer %16 -%265 = OpTypePointer StorageBuffer %25 -%268 = OpTypePointer StorageBuffer %13 +%241 = OpTypePointer StorageBuffer %23 +%244 = OpConstant %10 0.0 +%245 = OpConstant %3 3 +%246 = OpConstant %5 3 +%247 = OpConstant %5 4 +%248 = OpConstant %5 42 +%249 = OpConstantNull %29 +%254 = OpTypePointer StorageBuffer %8 +%257 = OpTypePointer StorageBuffer %18 +%258 = OpConstant %3 4 +%261 = OpTypePointer StorageBuffer %9 +%262 = OpTypePointer StorageBuffer %10 +%265 = OpTypePointer StorageBuffer %19 +%268 = OpTypePointer StorageBuffer %7 %285 = OpVariable %238 Output -%288 = OpConstantNull %29 -%304 = OpConstantNull %42 -%308 = OpConstantNull %4 -%310 = OpTypePointer Input %11 +%288 = OpConstantNull %23 +%304 = OpConstantNull %36 +%308 = OpConstantNull %3 +%310 = OpTypePointer Input %4 %309 = OpVariable %310 Input -%312 = OpConstantNull %11 +%312 = OpConstantNull %4 %314 = OpTypeBool %313 = OpTypeVector %314 3 -%319 = OpConstant %4 264 -%67 = OpFunction %2 None %68 -%66 = OpLabel -%60 = OpVariable %61 Function %62 -%63 = OpVariable %64 Function %65 -%70 = OpAccessChain %69 %50 %3 +%319 = OpConstant %3 264 +%66 = OpFunction %2 None %67 +%65 = OpLabel +%59 = OpVariable %60 Function %61 +%62 = OpVariable %63 Function %64 +%69 = OpAccessChain %68 %49 %38 OpBranch %83 %83 = OpLabel -OpStore %60 %9 -%84 = OpLoad %6 %60 -%85 = OpISub %6 %84 %9 -OpStore %60 %85 -%87 = OpAccessChain %86 %70 %3 -%88 = OpLoad %27 %87 -%90 = OpAccessChain %89 %70 %3 %3 -%91 = OpLoad %18 %90 -%92 = OpLoad %6 %60 -%93 = OpAccessChain %89 %70 %3 %92 -%94 = OpLoad %18 %93 -%97 = OpAccessChain %95 %70 %3 %3 %96 -%98 = OpLoad %16 %97 -%99 = OpLoad %6 %60 -%100 = OpAccessChain %95 %70 %3 %3 %99 -%101 = OpLoad %16 %100 -%102 = OpLoad %6 %60 -%103 = OpAccessChain %95 %70 %3 %102 %96 -%104 = OpLoad %16 %103 -%105 = OpLoad %6 %60 -%106 = OpLoad %6 %60 -%107 = OpAccessChain %95 %70 %3 %105 %106 -%108 = OpLoad %16 %107 -%109 = OpCompositeConstruct %18 %71 %71 -%110 = OpCompositeConstruct %18 %72 %72 -%111 = OpCompositeConstruct %18 %73 %73 -%112 = OpCompositeConstruct %27 %109 %110 %111 -%113 = OpCompositeConstruct %28 %112 -OpStore %63 %113 -%114 = OpLoad %6 %60 -%115 = OpIAdd %6 %114 %9 -OpStore %60 %115 -%117 = OpCompositeConstruct %18 %74 %74 -%118 = OpCompositeConstruct %18 %75 %75 -%119 = OpCompositeConstruct %18 %76 %76 -%120 = OpCompositeConstruct %27 %117 %118 %119 -%121 = OpAccessChain %116 %63 %3 +OpStore %59 %70 +%84 = OpLoad %5 %59 +%85 = OpISub %5 %84 %70 +OpStore %59 %85 +%87 = OpAccessChain %86 %69 %38 +%88 = OpLoad %21 %87 +%90 = OpAccessChain %89 %69 %38 %38 +%91 = OpLoad %12 %90 +%92 = OpLoad %5 %59 +%93 = OpAccessChain %89 %69 %38 %92 +%94 = OpLoad %12 %93 +%97 = OpAccessChain %95 %69 %38 %38 %96 +%98 = OpLoad %10 %97 +%99 = OpLoad %5 %59 +%100 = OpAccessChain %95 %69 %38 %38 %99 +%101 = OpLoad %10 %100 +%102 = OpLoad %5 %59 +%103 = OpAccessChain %95 %69 %38 %102 %96 +%104 = OpLoad %10 %103 +%105 = OpLoad %5 %59 +%106 = OpLoad %5 %59 +%107 = OpAccessChain %95 %69 %38 %105 %106 +%108 = OpLoad %10 %107 +%109 = OpCompositeConstruct %12 %71 %71 +%110 = OpCompositeConstruct %12 %72 %72 +%111 = OpCompositeConstruct %12 %73 %73 +%112 = OpCompositeConstruct %21 %109 %110 %111 +%113 = OpCompositeConstruct %22 %112 +OpStore %62 %113 +%114 = OpLoad %5 %59 +%115 = OpIAdd %5 %114 %70 +OpStore %59 %115 +%117 = OpCompositeConstruct %12 %74 %74 +%118 = OpCompositeConstruct %12 %75 %75 +%119 = OpCompositeConstruct %12 %76 %76 +%120 = OpCompositeConstruct %21 %117 %118 %119 +%121 = OpAccessChain %116 %62 %38 OpStore %121 %120 -%123 = OpCompositeConstruct %18 %77 %77 -%124 = OpAccessChain %122 %63 %3 %3 +%123 = OpCompositeConstruct %12 %77 %77 +%124 = OpAccessChain %122 %62 %38 %38 OpStore %124 %123 -%125 = OpLoad %6 %60 -%126 = OpCompositeConstruct %18 %78 %78 -%127 = OpAccessChain %122 %63 %3 %125 +%125 = OpLoad %5 %59 +%126 = OpCompositeConstruct %12 %78 %78 +%127 = OpAccessChain %122 %62 %38 %125 OpStore %127 %126 -%129 = OpAccessChain %128 %63 %3 %3 %96 +%129 = OpAccessChain %128 %62 %38 %38 %96 OpStore %129 %79 -%130 = OpLoad %6 %60 -%131 = OpAccessChain %128 %63 %3 %3 %130 +%130 = OpLoad %5 %59 +%131 = OpAccessChain %128 %62 %38 %38 %130 OpStore %131 %80 -%132 = OpLoad %6 %60 -%133 = OpAccessChain %128 %63 %3 %132 %96 +%132 = OpLoad %5 %59 +%133 = OpAccessChain %128 %62 %38 %132 %96 OpStore %133 %81 -%134 = OpLoad %6 %60 -%135 = OpLoad %6 %60 -%136 = OpAccessChain %128 %63 %3 %134 %135 +%134 = OpLoad %5 %59 +%135 = OpLoad %5 %59 +%136 = OpAccessChain %128 %62 %38 %134 %135 OpStore %136 %82 OpReturn OpFunctionEnd -%143 = OpFunction %2 None %68 +%143 = OpFunction %2 None %67 %142 = OpLabel -%137 = OpVariable %61 Function %138 +%137 = OpVariable %60 Function %138 %139 = OpVariable %140 Function %141 -%145 = OpAccessChain %144 %56 %3 +%145 = OpAccessChain %144 %55 %38 OpBranch %150 %150 = OpLabel -OpStore %137 %9 -%151 = OpLoad %6 %137 -%152 = OpISub %6 %151 %9 +OpStore %137 %70 +%151 = OpLoad %5 %137 +%152 = OpISub %5 %151 %70 OpStore %137 %152 -%154 = OpAccessChain %153 %145 %3 -%155 = OpLoad %31 %154 -%157 = OpAccessChain %156 %145 %3 %3 -%158 = OpLoad %30 %157 -%159 = OpAccessChain %89 %145 %3 %3 %3 -%160 = OpLoad %18 %159 -%161 = OpLoad %6 %137 -%162 = OpAccessChain %89 %145 %3 %3 %161 -%163 = OpLoad %18 %162 -%164 = OpAccessChain %95 %145 %3 %3 %3 %96 -%165 = OpLoad %16 %164 -%166 = OpLoad %6 %137 -%167 = OpAccessChain %95 %145 %3 %3 %3 %166 -%168 = OpLoad %16 %167 -%169 = OpLoad %6 %137 -%170 = OpAccessChain %95 %145 %3 %3 %169 %96 -%171 = OpLoad %16 %170 -%172 = OpLoad %6 %137 -%173 = OpLoad %6 %137 -%174 = OpAccessChain %95 %145 %3 %3 %172 %173 -%175 = OpLoad %16 %174 -%176 = OpCompositeConstruct %32 %146 +%154 = OpAccessChain %153 %145 %38 +%155 = OpLoad %25 %154 +%157 = OpAccessChain %156 %145 %38 %38 +%158 = OpLoad %24 %157 +%159 = OpAccessChain %89 %145 %38 %38 %38 +%160 = OpLoad %12 %159 +%161 = OpLoad %5 %137 +%162 = OpAccessChain %89 %145 %38 %38 %161 +%163 = OpLoad %12 %162 +%164 = OpAccessChain %95 %145 %38 %38 %38 %96 +%165 = OpLoad %10 %164 +%166 = OpLoad %5 %137 +%167 = OpAccessChain %95 %145 %38 %38 %38 %166 +%168 = OpLoad %10 %167 +%169 = OpLoad %5 %137 +%170 = OpAccessChain %95 %145 %38 %38 %169 %96 +%171 = OpLoad %10 %170 +%172 = OpLoad %5 %137 +%173 = OpLoad %5 %137 +%174 = OpAccessChain %95 %145 %38 %38 %172 %173 +%175 = OpLoad %10 %174 +%176 = OpCompositeConstruct %26 %146 OpStore %139 %176 -%177 = OpLoad %6 %137 -%178 = OpIAdd %6 %177 %9 +%177 = OpLoad %5 %137 +%178 = OpIAdd %5 %177 %70 OpStore %137 %178 -%180 = OpAccessChain %179 %139 %3 +%180 = OpAccessChain %179 %139 %38 OpStore %180 %147 -%182 = OpCompositeConstruct %18 %148 %148 -%183 = OpCompositeConstruct %18 %149 %149 -%184 = OpCompositeConstruct %18 %74 %74 -%185 = OpCompositeConstruct %18 %75 %75 -%186 = OpCompositeConstruct %30 %182 %183 %184 %185 -%187 = OpAccessChain %181 %139 %3 %3 +%182 = OpCompositeConstruct %12 %148 %148 +%183 = OpCompositeConstruct %12 %149 %149 +%184 = OpCompositeConstruct %12 %74 %74 +%185 = OpCompositeConstruct %12 %75 %75 +%186 = OpCompositeConstruct %24 %182 %183 %184 %185 +%187 = OpAccessChain %181 %139 %38 %38 OpStore %187 %186 -%188 = OpCompositeConstruct %18 %77 %77 -%189 = OpAccessChain %122 %139 %3 %3 %3 +%188 = OpCompositeConstruct %12 %77 %77 +%189 = OpAccessChain %122 %139 %38 %38 %38 OpStore %189 %188 -%190 = OpLoad %6 %137 -%191 = OpCompositeConstruct %18 %78 %78 -%192 = OpAccessChain %122 %139 %3 %3 %190 +%190 = OpLoad %5 %137 +%191 = OpCompositeConstruct %12 %78 %78 +%192 = OpAccessChain %122 %139 %38 %38 %190 OpStore %192 %191 -%193 = OpAccessChain %128 %139 %3 %3 %3 %96 +%193 = OpAccessChain %128 %139 %38 %38 %38 %96 OpStore %193 %79 -%194 = OpLoad %6 %137 -%195 = OpAccessChain %128 %139 %3 %3 %3 %194 +%194 = OpLoad %5 %137 +%195 = OpAccessChain %128 %139 %38 %38 %38 %194 OpStore %195 %80 -%196 = OpLoad %6 %137 -%197 = OpAccessChain %128 %139 %3 %3 %196 %96 +%196 = OpLoad %5 %137 +%197 = OpAccessChain %128 %139 %38 %38 %196 %96 OpStore %197 %81 -%198 = OpLoad %6 %137 -%199 = OpLoad %6 %137 -%200 = OpAccessChain %128 %139 %3 %3 %198 %199 +%198 = OpLoad %5 %137 +%199 = OpLoad %5 %137 +%200 = OpAccessChain %128 %139 %38 %38 %198 %199 OpStore %200 %82 OpReturn OpFunctionEnd -%203 = OpFunction %16 None %204 -%202 = OpFunctionParameter %33 +%203 = OpFunction %10 None %204 +%202 = OpFunctionParameter %27 %201 = OpLabel OpBranch %205 %205 = OpLabel -%206 = OpLoad %16 %202 +%206 = OpLoad %10 %202 OpReturnValue %206 OpFunctionEnd -%209 = OpFunction %16 None %210 -%208 = OpFunctionParameter %35 +%209 = OpFunction %10 None %210 +%208 = OpFunctionParameter %29 %207 = OpLabel OpBranch %211 %211 = OpLabel -%212 = OpCompositeExtract %34 %208 4 -%213 = OpCompositeExtract %16 %212 9 +%212 = OpCompositeExtract %28 %208 4 +%213 = OpCompositeExtract %10 %212 9 OpReturnValue %213 OpFunctionEnd %216 = OpFunction %2 None %217 -%215 = OpFunctionParameter %41 +%215 = OpFunctionParameter %35 %214 = OpLabel OpBranch %219 %219 = OpLabel @@ -393,107 +393,107 @@ OpStore %215 %218 OpReturn OpFunctionEnd %222 = OpFunction %2 None %223 -%221 = OpFunctionParameter %43 +%221 = OpFunctionParameter %37 %220 = OpLabel OpBranch %224 %224 = OpLabel -%225 = OpCompositeConstruct %37 %71 %71 %71 %71 -%226 = OpCompositeConstruct %37 %72 %72 %72 %72 -%227 = OpCompositeConstruct %42 %225 %226 +%225 = OpCompositeConstruct %31 %71 %71 %71 %71 +%226 = OpCompositeConstruct %31 %72 %72 %72 %72 +%227 = OpCompositeConstruct %36 %225 %226 OpStore %221 %227 OpReturn OpFunctionEnd -%239 = OpFunction %2 None %68 +%239 = OpFunction %2 None %67 %233 = OpLabel -%228 = OpVariable %33 Function %229 +%228 = OpVariable %27 Function %229 %230 = OpVariable %231 Function %232 -%236 = OpLoad %4 %234 -%240 = OpAccessChain %69 %50 %3 -%242 = OpAccessChain %241 %53 %3 -%243 = OpAccessChain %144 %56 %3 +%236 = OpLoad %3 %234 +%240 = OpAccessChain %68 %49 %38 +%242 = OpAccessChain %241 %52 %38 +%243 = OpAccessChain %144 %55 %38 OpBranch %250 %250 = OpLabel OpStore %228 %244 -%251 = OpLoad %16 %228 +%251 = OpLoad %10 %228 OpStore %228 %71 -%252 = OpFunctionCall %2 %67 +%252 = OpFunctionCall %2 %66 %253 = OpFunctionCall %2 %143 -%255 = OpAccessChain %254 %48 %3 -%256 = OpLoad %14 %255 -%259 = OpAccessChain %257 %48 %258 -%260 = OpLoad %24 %259 -%263 = OpAccessChain %262 %48 %3 %245 %3 -%264 = OpLoad %16 %263 -%266 = OpArrayLength %4 %48 5 -%267 = OpISub %4 %266 %20 -%269 = OpAccessChain %38 %48 %36 %267 %3 -%270 = OpLoad %6 %269 -%271 = OpLoad %29 %242 -%272 = OpFunctionCall %16 %203 %228 -%273 = OpConvertFToS %6 %264 -%274 = OpCompositeConstruct %39 %270 %273 %246 %247 %10 +%255 = OpAccessChain %254 %47 %38 +%256 = OpLoad %8 %255 +%259 = OpAccessChain %257 %47 %258 +%260 = OpLoad %18 %259 +%263 = OpAccessChain %262 %47 %38 %245 %38 +%264 = OpLoad %10 %263 +%266 = OpArrayLength %3 %47 5 +%267 = OpISub %3 %266 %14 +%269 = OpAccessChain %32 %47 %30 %267 %38 +%270 = OpLoad %5 %269 +%271 = OpLoad %23 %242 +%272 = OpFunctionCall %10 %203 %228 +%273 = OpConvertFToS %5 %264 +%274 = OpCompositeConstruct %33 %270 %273 %246 %247 %44 OpStore %230 %274 -%275 = OpIAdd %4 %236 %96 -%276 = OpAccessChain %61 %230 %275 +%275 = OpIAdd %3 %236 %96 +%276 = OpAccessChain %60 %230 %275 OpStore %276 %248 -%277 = OpAccessChain %61 %230 %236 -%278 = OpLoad %6 %277 -%279 = OpFunctionCall %16 %209 %249 -%280 = OpCompositeConstruct %40 %278 %278 %278 %278 -%281 = OpConvertSToF %37 %280 -%282 = OpMatrixTimesVector %15 %256 %281 -%283 = OpCompositeConstruct %37 %282 %72 +%277 = OpAccessChain %60 %230 %236 +%278 = OpLoad %5 %277 +%279 = OpFunctionCall %10 %209 %249 +%280 = OpCompositeConstruct %34 %278 %278 %278 %278 +%281 = OpConvertSToF %31 %280 +%282 = OpMatrixTimesVector %9 %256 %281 +%283 = OpCompositeConstruct %31 %282 %72 OpStore %237 %283 OpReturn OpFunctionEnd -%286 = OpFunction %2 None %68 +%286 = OpFunction %2 None %67 %284 = OpLabel -%287 = OpAccessChain %241 %53 %3 +%287 = OpAccessChain %241 %52 %38 OpBranch %289 %289 = OpLabel -%290 = OpAccessChain %262 %48 %3 %96 %20 +%290 = OpAccessChain %262 %47 %38 %96 %14 OpStore %290 %71 -%291 = OpCompositeConstruct %15 %244 %244 %244 -%292 = OpCompositeConstruct %15 %71 %71 %71 -%293 = OpCompositeConstruct %15 %72 %72 %72 -%294 = OpCompositeConstruct %15 %73 %73 %73 -%295 = OpCompositeConstruct %14 %291 %292 %293 %294 -%296 = OpAccessChain %254 %48 %3 +%291 = OpCompositeConstruct %9 %244 %244 %244 +%292 = OpCompositeConstruct %9 %71 %71 %71 +%293 = OpCompositeConstruct %9 %72 %72 %72 +%294 = OpCompositeConstruct %9 %73 %73 %73 +%295 = OpCompositeConstruct %8 %291 %292 %293 %294 +%296 = OpAccessChain %254 %47 %38 OpStore %296 %295 -%297 = OpCompositeConstruct %23 %3 %3 -%298 = OpCompositeConstruct %23 %96 %96 -%299 = OpCompositeConstruct %24 %297 %298 -%300 = OpAccessChain %257 %48 %258 +%297 = OpCompositeConstruct %17 %38 %38 +%298 = OpCompositeConstruct %17 %96 %96 +%299 = OpCompositeConstruct %18 %297 %298 +%300 = OpAccessChain %257 %47 %258 OpStore %300 %299 -%301 = OpAccessChain %38 %48 %36 %96 %3 -OpStore %301 %9 +%301 = OpAccessChain %32 %47 %30 %96 %38 +OpStore %301 %70 OpStore %287 %288 -%302 = OpCompositeConstruct %37 %244 %244 %244 %244 +%302 = OpCompositeConstruct %31 %244 %244 %244 %244 OpStore %285 %302 OpReturn OpFunctionEnd -%306 = OpFunction %2 None %68 +%306 = OpFunction %2 None %67 %305 = OpLabel -%303 = OpVariable %43 Function %304 +%303 = OpVariable %37 Function %304 OpBranch %307 %307 = OpLabel -%311 = OpLoad %11 %309 +%311 = OpLoad %4 %309 %315 = OpIEqual %313 %311 %312 %316 = OpAll %314 %315 OpSelectionMerge %317 None OpBranchConditional %316 %318 %317 %318 = OpLabel -OpStore %59 %308 +OpStore %58 %308 OpBranch %317 %317 = OpLabel -OpControlBarrier %20 %20 %319 +OpControlBarrier %14 %14 %319 OpBranch %320 %320 = OpLabel -%321 = OpCompositeConstruct %37 %74 %74 %74 %74 -%322 = OpCompositeConstruct %37 %149 %149 %149 %149 -%323 = OpCompositeConstruct %42 %321 %322 +%321 = OpCompositeConstruct %31 %74 %74 %74 %74 +%322 = OpCompositeConstruct %31 %149 %149 %149 %149 +%323 = OpCompositeConstruct %36 %321 %322 OpStore %303 %323 -%324 = OpFunctionCall %2 %216 %59 +%324 = OpFunctionCall %2 %216 %58 %325 = OpFunctionCall %2 %222 %303 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/array-in-ctor.spvasm b/tests/out/spv/array-in-ctor.spvasm index 5511954fc..61d1bd48d 100644 --- a/tests/out/spv/array-in-ctor.spvasm +++ b/tests/out/spv/array-in-ctor.spvasm @@ -8,32 +8,32 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %14 "cs_main" OpExecutionMode %14 LocalSize 1 1 1 -OpDecorate %6 ArrayStride 4 -OpMemberDecorate %9 0 Offset 0 +OpDecorate %4 ArrayStride 4 +OpMemberDecorate %7 0 Offset 0 OpDecorate %10 NonWritable OpDecorate %10 DescriptorSet 0 OpDecorate %10 Binding 0 OpDecorate %11 Block OpMemberDecorate %11 0 Offset 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 2 -%5 = OpTypeFloat 32 -%8 = OpTypeInt 32 0 -%7 = OpConstant %8 2 -%6 = OpTypeArray %5 %7 -%9 = OpTypeStruct %6 -%11 = OpTypeStruct %9 +%3 = OpTypeFloat 32 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 2 +%4 = OpTypeArray %3 %5 +%7 = OpTypeStruct %4 +%9 = OpTypeInt 32 1 +%8 = OpConstant %9 2 +%11 = OpTypeStruct %7 %12 = OpTypePointer StorageBuffer %11 %10 = OpVariable %12 StorageBuffer %15 = OpTypeFunction %2 -%16 = OpTypePointer StorageBuffer %9 -%17 = OpConstant %8 0 +%16 = OpTypePointer StorageBuffer %7 +%17 = OpConstant %6 0 %14 = OpFunction %2 None %15 %13 = OpLabel %18 = OpAccessChain %16 %10 %17 OpBranch %19 %19 = OpLabel -%20 = OpLoad %9 %18 +%20 = OpLoad %7 %18 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/array-in-function-return-type.spvasm b/tests/out/spv/array-in-function-return-type.spvasm index e70434025..71e1cd6f1 100644 --- a/tests/out/spv/array-in-function-return-type.spvasm +++ b/tests/out/spv/array-in-function-return-type.spvasm @@ -7,38 +7,38 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %20 "main" %18 OpExecutionMode %20 OriginUpperLeft -OpDecorate %6 ArrayStride 4 +OpDecorate %4 ArrayStride 4 OpDecorate %18 Location 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 2 -%5 = OpTypeFloat 32 -%8 = OpTypeInt 32 0 -%7 = OpConstant %8 2 -%6 = OpTypeArray %5 %7 -%9 = OpTypeVector %5 4 -%12 = OpTypeFunction %6 -%13 = OpConstant %5 1.0 -%14 = OpConstant %5 2.0 -%19 = OpTypePointer Output %9 +%3 = OpTypeFloat 32 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 2 +%4 = OpTypeArray %3 %5 +%7 = OpTypeVector %3 4 +%9 = OpTypeInt 32 1 +%8 = OpConstant %9 2 +%12 = OpTypeFunction %4 +%13 = OpConstant %3 1.0 +%14 = OpConstant %3 2.0 +%19 = OpTypePointer Output %7 %18 = OpVariable %19 Output %21 = OpTypeFunction %2 -%22 = OpConstant %5 0.0 -%11 = OpFunction %6 None %12 +%22 = OpConstant %3 0.0 +%11 = OpFunction %4 None %12 %10 = OpLabel OpBranch %15 %15 = OpLabel -%16 = OpCompositeConstruct %6 %13 %14 +%16 = OpCompositeConstruct %4 %13 %14 OpReturnValue %16 OpFunctionEnd %20 = OpFunction %2 None %21 %17 = OpLabel OpBranch %23 %23 = OpLabel -%24 = OpFunctionCall %6 %11 -%25 = OpCompositeExtract %5 %24 0 -%26 = OpCompositeExtract %5 %24 1 -%27 = OpCompositeConstruct %9 %25 %26 %22 %13 +%24 = OpFunctionCall %4 %11 +%25 = OpCompositeExtract %3 %24 0 +%26 = OpCompositeExtract %3 %24 1 +%27 = OpCompositeConstruct %7 %25 %26 %22 %13 OpStore %18 %27 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/tests/out/spv/atomicCompareExchange.spvasm index 1812f1a90..82ebc2f20 100644 --- a/tests/out/spv/atomicCompareExchange.spvasm +++ b/tests/out/spv/atomicCompareExchange.spvasm @@ -1,209 +1,208 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 127 +; Bound: 126 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %30 "test_atomic_compare_exchange_i32" -OpEntryPoint GLCompute %85 "test_atomic_compare_exchange_u32" -OpExecutionMode %30 LocalSize 1 1 1 -OpExecutionMode %85 LocalSize 1 1 1 +OpEntryPoint GLCompute %28 "test_atomic_compare_exchange_i32" +OpEntryPoint GLCompute %84 "test_atomic_compare_exchange_u32" +OpExecutionMode %28 LocalSize 1 1 1 +OpExecutionMode %84 LocalSize 1 1 1 +OpDecorate %5 ArrayStride 4 OpDecorate %7 ArrayStride 4 -OpDecorate %9 ArrayStride 4 -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 4 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 4 +OpMemberDecorate %11 0 Offset 0 +OpMemberDecorate %11 1 Offset 4 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 0 +OpDecorate %13 Block OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 4 -OpDecorate %14 DescriptorSet 0 -OpDecorate %14 Binding 0 -OpDecorate %15 Block -OpMemberDecorate %15 0 Offset 0 -OpDecorate %17 DescriptorSet 0 -OpDecorate %17 Binding 1 -OpDecorate %18 Block -OpMemberDecorate %18 0 Offset 0 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 1 +OpDecorate %16 Block +OpMemberDecorate %16 0 Offset 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpConstant %4 128 -%5 = OpConstant %4 1 -%6 = OpTypeInt 32 1 -%8 = OpConstant %4 128 -%7 = OpTypeArray %6 %8 -%9 = OpTypeArray %4 %8 -%10 = OpTypeBool -%11 = OpTypeFloat 32 -%12 = OpTypeStruct %6 %10 -%13 = OpTypeStruct %4 %10 -%15 = OpTypeStruct %7 -%16 = OpTypePointer StorageBuffer %15 -%14 = OpVariable %16 StorageBuffer -%18 = OpTypeStruct %9 -%19 = OpTypePointer StorageBuffer %18 -%17 = OpVariable %19 StorageBuffer -%21 = OpTypePointer Function %4 -%22 = OpConstantNull %4 -%24 = OpTypePointer Function %6 -%25 = OpConstantNull %6 -%27 = OpTypePointer Function %10 -%28 = OpConstantNull %10 -%31 = OpTypeFunction %2 -%32 = OpTypePointer StorageBuffer %7 -%33 = OpConstant %4 0 -%35 = OpConstantFalse %10 -%36 = OpConstant %11 1.0 -%49 = OpTypePointer StorageBuffer %6 -%52 = OpConstant %6 1 -%53 = OpConstant %4 64 -%79 = OpConstantNull %4 -%81 = OpConstantNull %4 -%83 = OpConstantNull %10 -%86 = OpTypePointer StorageBuffer %9 -%100 = OpTypePointer StorageBuffer %4 -%30 = OpFunction %2 None %31 -%29 = OpLabel -%20 = OpVariable %21 Function %22 -%23 = OpVariable %24 Function %25 -%26 = OpVariable %27 Function %28 -%34 = OpAccessChain %32 %14 %33 +%3 = OpTypeInt 32 0 +%4 = OpTypeInt 32 1 +%6 = OpConstant %3 128 +%5 = OpTypeArray %4 %6 +%7 = OpTypeArray %3 %6 +%8 = OpTypeBool +%9 = OpTypeFloat 32 +%10 = OpTypeStruct %4 %8 +%11 = OpTypeStruct %3 %8 +%13 = OpTypeStruct %5 +%14 = OpTypePointer StorageBuffer %13 +%12 = OpVariable %14 StorageBuffer +%16 = OpTypeStruct %7 +%17 = OpTypePointer StorageBuffer %16 +%15 = OpVariable %17 StorageBuffer +%19 = OpTypePointer Function %3 +%20 = OpConstantNull %3 +%22 = OpTypePointer Function %4 +%23 = OpConstantNull %4 +%25 = OpTypePointer Function %8 +%26 = OpConstantNull %8 +%29 = OpTypeFunction %2 +%30 = OpTypePointer StorageBuffer %5 +%31 = OpConstant %3 0 +%33 = OpConstantFalse %8 +%34 = OpConstant %9 1.0 +%35 = OpConstant %3 1 +%48 = OpTypePointer StorageBuffer %4 +%51 = OpConstant %4 1 +%52 = OpConstant %3 64 +%78 = OpConstantNull %3 +%80 = OpConstantNull %3 +%82 = OpConstantNull %8 +%85 = OpTypePointer StorageBuffer %7 +%99 = OpTypePointer StorageBuffer %3 +%28 = OpFunction %2 None %29 +%27 = OpLabel +%18 = OpVariable %19 Function %20 +%21 = OpVariable %22 Function %23 +%24 = OpVariable %25 Function %26 +%32 = OpAccessChain %30 %12 %31 +OpBranch %36 +%36 = OpLabel +OpStore %18 %31 OpBranch %37 %37 = OpLabel -OpStore %20 %33 -OpBranch %38 -%38 = OpLabel -OpLoopMerge %39 %41 None -OpBranch %40 -%40 = OpLabel -%42 = OpLoad %4 %20 -%43 = OpULessThan %10 %42 %3 -OpSelectionMerge %44 None -OpBranchConditional %43 %44 %45 -%45 = OpLabel +OpLoopMerge %38 %40 None OpBranch %39 +%39 = OpLabel +%41 = OpLoad %3 %18 +%42 = OpULessThan %8 %41 %6 +OpSelectionMerge %43 None +OpBranchConditional %42 %43 %44 %44 = OpLabel -OpBranch %46 -%46 = OpLabel -%48 = OpLoad %4 %20 -%50 = OpAccessChain %49 %34 %48 -%51 = OpAtomicLoad %6 %50 %52 %53 -OpStore %23 %51 -OpStore %26 %35 -OpBranch %54 -%54 = OpLabel -OpLoopMerge %55 %57 None -OpBranch %56 -%56 = OpLabel -%58 = OpLoad %10 %26 -%59 = OpLogicalNot %10 %58 -OpSelectionMerge %60 None -OpBranchConditional %59 %60 %61 -%61 = OpLabel +OpBranch %38 +%43 = OpLabel +OpBranch %45 +%45 = OpLabel +%47 = OpLoad %3 %18 +%49 = OpAccessChain %48 %32 %47 +%50 = OpAtomicLoad %4 %49 %51 %52 +OpStore %21 %50 +OpStore %24 %33 +OpBranch %53 +%53 = OpLabel +OpLoopMerge %54 %56 None OpBranch %55 +%55 = OpLabel +%57 = OpLoad %8 %24 +%58 = OpLogicalNot %8 %57 +OpSelectionMerge %59 None +OpBranchConditional %58 %59 %60 %60 = OpLabel +OpBranch %54 +%59 = OpLabel +OpBranch %61 +%61 = OpLabel +%63 = OpLoad %4 %21 +%64 = OpBitcast %9 %63 +%65 = OpFAdd %9 %64 %34 +%66 = OpBitcast %4 %65 +%67 = OpLoad %3 %18 +%68 = OpLoad %4 %21 +%70 = OpAccessChain %48 %32 %67 +%71 = OpAtomicCompareExchange %4 %70 %51 %52 %52 %66 %68 +%72 = OpIEqual %8 %71 %68 +%69 = OpCompositeConstruct %10 %71 %72 +%73 = OpCompositeExtract %4 %69 0 +OpStore %21 %73 +%74 = OpCompositeExtract %8 %69 1 +OpStore %24 %74 OpBranch %62 %62 = OpLabel -%64 = OpLoad %6 %23 -%65 = OpBitcast %11 %64 -%66 = OpFAdd %11 %65 %36 -%67 = OpBitcast %6 %66 -%68 = OpLoad %4 %20 -%69 = OpLoad %6 %23 -%71 = OpAccessChain %49 %34 %68 -%72 = OpAtomicCompareExchange %6 %71 %52 %53 %53 %67 %69 -%73 = OpIEqual %10 %72 %69 -%70 = OpCompositeConstruct %12 %72 %73 -%74 = OpCompositeExtract %6 %70 0 -OpStore %23 %74 -%75 = OpCompositeExtract %10 %70 1 -OpStore %26 %75 -OpBranch %63 -%63 = OpLabel -OpBranch %57 -%57 = OpLabel -OpBranch %54 -%55 = OpLabel -OpBranch %47 -%47 = OpLabel -OpBranch %41 -%41 = OpLabel -%76 = OpLoad %4 %20 -%77 = OpIAdd %4 %76 %5 -OpStore %20 %77 -OpBranch %38 -%39 = OpLabel +OpBranch %56 +%56 = OpLabel +OpBranch %53 +%54 = OpLabel +OpBranch %46 +%46 = OpLabel +OpBranch %40 +%40 = OpLabel +%75 = OpLoad %3 %18 +%76 = OpIAdd %3 %75 %35 +OpStore %18 %76 +OpBranch %37 +%38 = OpLabel OpReturn OpFunctionEnd -%85 = OpFunction %2 None %31 -%84 = OpLabel -%78 = OpVariable %21 Function %79 -%80 = OpVariable %21 Function %81 -%82 = OpVariable %27 Function %83 -%87 = OpAccessChain %86 %17 %33 +%84 = OpFunction %2 None %29 +%83 = OpLabel +%77 = OpVariable %19 Function %78 +%79 = OpVariable %19 Function %80 +%81 = OpVariable %25 Function %82 +%86 = OpAccessChain %85 %15 %31 +OpBranch %87 +%87 = OpLabel +OpStore %77 %31 OpBranch %88 %88 = OpLabel -OpStore %78 %33 -OpBranch %89 -%89 = OpLabel -OpLoopMerge %90 %92 None -OpBranch %91 -%91 = OpLabel -%93 = OpLoad %4 %78 -%94 = OpULessThan %10 %93 %3 -OpSelectionMerge %95 None -OpBranchConditional %94 %95 %96 -%96 = OpLabel +OpLoopMerge %89 %91 None OpBranch %90 +%90 = OpLabel +%92 = OpLoad %3 %77 +%93 = OpULessThan %8 %92 %6 +OpSelectionMerge %94 None +OpBranchConditional %93 %94 %95 %95 = OpLabel -OpBranch %97 -%97 = OpLabel -%99 = OpLoad %4 %78 -%101 = OpAccessChain %100 %87 %99 -%102 = OpAtomicLoad %4 %101 %52 %53 -OpStore %80 %102 -OpStore %82 %35 -OpBranch %103 -%103 = OpLabel -OpLoopMerge %104 %106 None -OpBranch %105 -%105 = OpLabel -%107 = OpLoad %10 %82 -%108 = OpLogicalNot %10 %107 -OpSelectionMerge %109 None -OpBranchConditional %108 %109 %110 -%110 = OpLabel +OpBranch %89 +%94 = OpLabel +OpBranch %96 +%96 = OpLabel +%98 = OpLoad %3 %77 +%100 = OpAccessChain %99 %86 %98 +%101 = OpAtomicLoad %3 %100 %51 %52 +OpStore %79 %101 +OpStore %81 %33 +OpBranch %102 +%102 = OpLabel +OpLoopMerge %103 %105 None OpBranch %104 +%104 = OpLabel +%106 = OpLoad %8 %81 +%107 = OpLogicalNot %8 %106 +OpSelectionMerge %108 None +OpBranchConditional %107 %108 %109 %109 = OpLabel +OpBranch %103 +%108 = OpLabel +OpBranch %110 +%110 = OpLabel +%112 = OpLoad %3 %79 +%113 = OpBitcast %9 %112 +%114 = OpFAdd %9 %113 %34 +%115 = OpBitcast %3 %114 +%116 = OpLoad %3 %77 +%117 = OpLoad %3 %79 +%119 = OpAccessChain %99 %86 %116 +%120 = OpAtomicCompareExchange %3 %119 %51 %52 %52 %115 %117 +%121 = OpIEqual %8 %120 %117 +%118 = OpCompositeConstruct %11 %120 %121 +%122 = OpCompositeExtract %3 %118 0 +OpStore %79 %122 +%123 = OpCompositeExtract %8 %118 1 +OpStore %81 %123 OpBranch %111 %111 = OpLabel -%113 = OpLoad %4 %80 -%114 = OpBitcast %11 %113 -%115 = OpFAdd %11 %114 %36 -%116 = OpBitcast %4 %115 -%117 = OpLoad %4 %78 -%118 = OpLoad %4 %80 -%120 = OpAccessChain %100 %87 %117 -%121 = OpAtomicCompareExchange %4 %120 %52 %53 %53 %116 %118 -%122 = OpIEqual %10 %121 %118 -%119 = OpCompositeConstruct %13 %121 %122 -%123 = OpCompositeExtract %4 %119 0 -OpStore %80 %123 -%124 = OpCompositeExtract %10 %119 1 -OpStore %82 %124 -OpBranch %112 -%112 = OpLabel -OpBranch %106 -%106 = OpLabel -OpBranch %103 -%104 = OpLabel -OpBranch %98 -%98 = OpLabel -OpBranch %92 -%92 = OpLabel -%125 = OpLoad %4 %78 -%126 = OpIAdd %4 %125 %5 -OpStore %78 %126 -OpBranch %89 -%90 = OpLabel +OpBranch %105 +%105 = OpLabel +OpBranch %102 +%103 = OpLabel +OpBranch %97 +%97 = OpLabel +OpBranch %91 +%91 = OpLabel +%124 = OpLoad %3 %77 +%125 = OpIAdd %3 %124 %35 +OpStore %77 %125 +OpBranch %88 +%89 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/atomicOps.spvasm b/tests/out/spv/atomicOps.spvasm index a30a92a30..65d078ad9 100644 --- a/tests/out/spv/atomicOps.spvasm +++ b/tests/out/spv/atomicOps.spvasm @@ -8,9 +8,9 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %29 "cs_main" %26 OpExecutionMode %29 LocalSize 2 1 1 -OpDecorate %6 ArrayStride 4 -OpMemberDecorate %8 0 Offset 0 -OpMemberDecorate %8 1 Offset 4 +OpDecorate %5 ArrayStride 4 +OpMemberDecorate %7 0 Offset 0 +OpMemberDecorate %7 1 Offset 4 OpDecorate %10 DescriptorSet 0 OpDecorate %10 Binding 0 OpDecorate %11 Block @@ -25,51 +25,51 @@ OpDecorate %17 Block OpMemberDecorate %17 0 Offset 0 OpDecorate %26 BuiltIn LocalInvocationId %2 = OpTypeVoid +%3 = OpTypeInt 32 0 %4 = OpTypeInt 32 1 -%3 = OpConstant %4 2 -%5 = OpTypeInt 32 0 -%7 = OpConstant %5 2 -%6 = OpTypeArray %4 %7 -%8 = OpTypeStruct %5 %6 -%9 = OpTypeVector %5 3 -%11 = OpTypeStruct %5 +%6 = OpConstant %3 2 +%5 = OpTypeArray %4 %6 +%7 = OpTypeStruct %3 %5 +%8 = OpTypeVector %3 3 +%9 = OpConstant %4 2 +%11 = OpTypeStruct %3 %12 = OpTypePointer StorageBuffer %11 %10 = OpVariable %12 StorageBuffer -%14 = OpTypeStruct %6 +%14 = OpTypeStruct %5 %15 = OpTypePointer StorageBuffer %14 %13 = OpVariable %15 StorageBuffer -%17 = OpTypeStruct %8 +%17 = OpTypeStruct %7 %18 = OpTypePointer StorageBuffer %17 %16 = OpVariable %18 StorageBuffer -%20 = OpTypePointer Workgroup %5 +%20 = OpTypePointer Workgroup %3 %19 = OpVariable %20 Workgroup -%22 = OpTypePointer Workgroup %6 +%22 = OpTypePointer Workgroup %5 %21 = OpVariable %22 Workgroup -%24 = OpTypePointer Workgroup %8 +%24 = OpTypePointer Workgroup %7 %23 = OpVariable %24 Workgroup -%27 = OpTypePointer Input %9 +%27 = OpTypePointer Input %8 %26 = OpVariable %27 Input %30 = OpTypeFunction %2 -%31 = OpTypePointer StorageBuffer %5 -%32 = OpConstant %5 0 -%34 = OpTypePointer StorageBuffer %6 -%36 = OpTypePointer StorageBuffer %8 -%38 = OpConstant %5 1 +%31 = OpTypePointer StorageBuffer %3 +%32 = OpConstant %3 0 +%34 = OpTypePointer StorageBuffer %5 +%36 = OpTypePointer StorageBuffer %7 +%38 = OpConstant %3 1 %39 = OpConstant %4 1 -%41 = OpConstantNull %5 -%42 = OpConstantNull %6 -%43 = OpConstantNull %8 -%44 = OpConstantNull %9 +%41 = OpConstantNull %3 +%42 = OpConstantNull %5 +%43 = OpConstantNull %7 +%44 = OpConstantNull %8 %46 = OpTypeBool %45 = OpTypeVector %46 3 -%51 = OpConstant %5 264 -%53 = OpConstant %5 64 +%51 = OpConstant %3 264 +%53 = OpConstant %3 64 %54 = OpTypePointer StorageBuffer %4 -%58 = OpConstant %5 256 +%58 = OpConstant %3 256 %59 = OpTypePointer Workgroup %4 %29 = OpFunction %2 None %30 %25 = OpLabel -%28 = OpLoad %9 %26 +%28 = OpLoad %8 %26 %33 = OpAccessChain %31 %10 %32 %35 = OpAccessChain %34 %13 %32 %37 = OpAccessChain %36 %16 %32 @@ -85,7 +85,7 @@ OpStore %21 %42 OpStore %23 %43 OpBranch %49 %49 = OpLabel -OpControlBarrier %7 %7 %51 +OpControlBarrier %6 %6 %51 OpBranch %52 %52 = OpLabel OpAtomicStore %33 %39 %53 %38 @@ -95,146 +95,146 @@ OpAtomicStore %55 %39 %53 %39 OpAtomicStore %56 %39 %53 %38 %57 = OpAccessChain %54 %37 %38 %38 OpAtomicStore %57 %39 %53 %39 -OpAtomicStore %19 %3 %58 %38 +OpAtomicStore %19 %9 %58 %38 %60 = OpAccessChain %59 %21 %38 -OpAtomicStore %60 %3 %58 %39 +OpAtomicStore %60 %9 %58 %39 %61 = OpAccessChain %20 %23 %32 -OpAtomicStore %61 %3 %58 %38 +OpAtomicStore %61 %9 %58 %38 %62 = OpAccessChain %59 %23 %38 %38 -OpAtomicStore %62 %3 %58 %39 -OpControlBarrier %7 %7 %51 -%63 = OpAtomicLoad %5 %33 %39 %53 +OpAtomicStore %62 %9 %58 %39 +OpControlBarrier %6 %6 %51 +%63 = OpAtomicLoad %3 %33 %39 %53 %64 = OpAccessChain %54 %35 %38 %65 = OpAtomicLoad %4 %64 %39 %53 %66 = OpAccessChain %31 %37 %32 -%67 = OpAtomicLoad %5 %66 %39 %53 +%67 = OpAtomicLoad %3 %66 %39 %53 %68 = OpAccessChain %54 %37 %38 %38 %69 = OpAtomicLoad %4 %68 %39 %53 -%70 = OpAtomicLoad %5 %19 %3 %58 +%70 = OpAtomicLoad %3 %19 %9 %58 %71 = OpAccessChain %59 %21 %38 -%72 = OpAtomicLoad %4 %71 %3 %58 +%72 = OpAtomicLoad %4 %71 %9 %58 %73 = OpAccessChain %20 %23 %32 -%74 = OpAtomicLoad %5 %73 %3 %58 +%74 = OpAtomicLoad %3 %73 %9 %58 %75 = OpAccessChain %59 %23 %38 %38 -%76 = OpAtomicLoad %4 %75 %3 %58 -OpControlBarrier %7 %7 %51 -%77 = OpAtomicIAdd %5 %33 %39 %53 %38 +%76 = OpAtomicLoad %4 %75 %9 %58 +OpControlBarrier %6 %6 %51 +%77 = OpAtomicIAdd %3 %33 %39 %53 %38 %79 = OpAccessChain %54 %35 %38 %78 = OpAtomicIAdd %4 %79 %39 %53 %39 %81 = OpAccessChain %31 %37 %32 -%80 = OpAtomicIAdd %5 %81 %39 %53 %38 +%80 = OpAtomicIAdd %3 %81 %39 %53 %38 %83 = OpAccessChain %54 %37 %38 %38 %82 = OpAtomicIAdd %4 %83 %39 %53 %39 -%84 = OpAtomicIAdd %5 %19 %3 %58 %38 +%84 = OpAtomicIAdd %3 %19 %9 %58 %38 %86 = OpAccessChain %59 %21 %38 -%85 = OpAtomicIAdd %4 %86 %3 %58 %39 +%85 = OpAtomicIAdd %4 %86 %9 %58 %39 %88 = OpAccessChain %20 %23 %32 -%87 = OpAtomicIAdd %5 %88 %3 %58 %38 +%87 = OpAtomicIAdd %3 %88 %9 %58 %38 %90 = OpAccessChain %59 %23 %38 %38 -%89 = OpAtomicIAdd %4 %90 %3 %58 %39 -OpControlBarrier %7 %7 %51 -%91 = OpAtomicISub %5 %33 %39 %53 %38 +%89 = OpAtomicIAdd %4 %90 %9 %58 %39 +OpControlBarrier %6 %6 %51 +%91 = OpAtomicISub %3 %33 %39 %53 %38 %93 = OpAccessChain %54 %35 %38 %92 = OpAtomicISub %4 %93 %39 %53 %39 %95 = OpAccessChain %31 %37 %32 -%94 = OpAtomicISub %5 %95 %39 %53 %38 +%94 = OpAtomicISub %3 %95 %39 %53 %38 %97 = OpAccessChain %54 %37 %38 %38 %96 = OpAtomicISub %4 %97 %39 %53 %39 -%98 = OpAtomicISub %5 %19 %3 %58 %38 +%98 = OpAtomicISub %3 %19 %9 %58 %38 %100 = OpAccessChain %59 %21 %38 -%99 = OpAtomicISub %4 %100 %3 %58 %39 +%99 = OpAtomicISub %4 %100 %9 %58 %39 %102 = OpAccessChain %20 %23 %32 -%101 = OpAtomicISub %5 %102 %3 %58 %38 +%101 = OpAtomicISub %3 %102 %9 %58 %38 %104 = OpAccessChain %59 %23 %38 %38 -%103 = OpAtomicISub %4 %104 %3 %58 %39 -OpControlBarrier %7 %7 %51 -%105 = OpAtomicUMax %5 %33 %39 %53 %38 +%103 = OpAtomicISub %4 %104 %9 %58 %39 +OpControlBarrier %6 %6 %51 +%105 = OpAtomicUMax %3 %33 %39 %53 %38 %107 = OpAccessChain %54 %35 %38 %106 = OpAtomicSMax %4 %107 %39 %53 %39 %109 = OpAccessChain %31 %37 %32 -%108 = OpAtomicUMax %5 %109 %39 %53 %38 +%108 = OpAtomicUMax %3 %109 %39 %53 %38 %111 = OpAccessChain %54 %37 %38 %38 %110 = OpAtomicSMax %4 %111 %39 %53 %39 -%112 = OpAtomicUMax %5 %19 %3 %58 %38 +%112 = OpAtomicUMax %3 %19 %9 %58 %38 %114 = OpAccessChain %59 %21 %38 -%113 = OpAtomicSMax %4 %114 %3 %58 %39 +%113 = OpAtomicSMax %4 %114 %9 %58 %39 %116 = OpAccessChain %20 %23 %32 -%115 = OpAtomicUMax %5 %116 %3 %58 %38 +%115 = OpAtomicUMax %3 %116 %9 %58 %38 %118 = OpAccessChain %59 %23 %38 %38 -%117 = OpAtomicSMax %4 %118 %3 %58 %39 -OpControlBarrier %7 %7 %51 -%119 = OpAtomicUMin %5 %33 %39 %53 %38 +%117 = OpAtomicSMax %4 %118 %9 %58 %39 +OpControlBarrier %6 %6 %51 +%119 = OpAtomicUMin %3 %33 %39 %53 %38 %121 = OpAccessChain %54 %35 %38 %120 = OpAtomicSMin %4 %121 %39 %53 %39 %123 = OpAccessChain %31 %37 %32 -%122 = OpAtomicUMin %5 %123 %39 %53 %38 +%122 = OpAtomicUMin %3 %123 %39 %53 %38 %125 = OpAccessChain %54 %37 %38 %38 %124 = OpAtomicSMin %4 %125 %39 %53 %39 -%126 = OpAtomicUMin %5 %19 %3 %58 %38 +%126 = OpAtomicUMin %3 %19 %9 %58 %38 %128 = OpAccessChain %59 %21 %38 -%127 = OpAtomicSMin %4 %128 %3 %58 %39 +%127 = OpAtomicSMin %4 %128 %9 %58 %39 %130 = OpAccessChain %20 %23 %32 -%129 = OpAtomicUMin %5 %130 %3 %58 %38 +%129 = OpAtomicUMin %3 %130 %9 %58 %38 %132 = OpAccessChain %59 %23 %38 %38 -%131 = OpAtomicSMin %4 %132 %3 %58 %39 -OpControlBarrier %7 %7 %51 -%133 = OpAtomicAnd %5 %33 %39 %53 %38 +%131 = OpAtomicSMin %4 %132 %9 %58 %39 +OpControlBarrier %6 %6 %51 +%133 = OpAtomicAnd %3 %33 %39 %53 %38 %135 = OpAccessChain %54 %35 %38 %134 = OpAtomicAnd %4 %135 %39 %53 %39 %137 = OpAccessChain %31 %37 %32 -%136 = OpAtomicAnd %5 %137 %39 %53 %38 +%136 = OpAtomicAnd %3 %137 %39 %53 %38 %139 = OpAccessChain %54 %37 %38 %38 %138 = OpAtomicAnd %4 %139 %39 %53 %39 -%140 = OpAtomicAnd %5 %19 %3 %58 %38 +%140 = OpAtomicAnd %3 %19 %9 %58 %38 %142 = OpAccessChain %59 %21 %38 -%141 = OpAtomicAnd %4 %142 %3 %58 %39 +%141 = OpAtomicAnd %4 %142 %9 %58 %39 %144 = OpAccessChain %20 %23 %32 -%143 = OpAtomicAnd %5 %144 %3 %58 %38 +%143 = OpAtomicAnd %3 %144 %9 %58 %38 %146 = OpAccessChain %59 %23 %38 %38 -%145 = OpAtomicAnd %4 %146 %3 %58 %39 -OpControlBarrier %7 %7 %51 -%147 = OpAtomicOr %5 %33 %39 %53 %38 +%145 = OpAtomicAnd %4 %146 %9 %58 %39 +OpControlBarrier %6 %6 %51 +%147 = OpAtomicOr %3 %33 %39 %53 %38 %149 = OpAccessChain %54 %35 %38 %148 = OpAtomicOr %4 %149 %39 %53 %39 %151 = OpAccessChain %31 %37 %32 -%150 = OpAtomicOr %5 %151 %39 %53 %38 +%150 = OpAtomicOr %3 %151 %39 %53 %38 %153 = OpAccessChain %54 %37 %38 %38 %152 = OpAtomicOr %4 %153 %39 %53 %39 -%154 = OpAtomicOr %5 %19 %3 %58 %38 +%154 = OpAtomicOr %3 %19 %9 %58 %38 %156 = OpAccessChain %59 %21 %38 -%155 = OpAtomicOr %4 %156 %3 %58 %39 +%155 = OpAtomicOr %4 %156 %9 %58 %39 %158 = OpAccessChain %20 %23 %32 -%157 = OpAtomicOr %5 %158 %3 %58 %38 +%157 = OpAtomicOr %3 %158 %9 %58 %38 %160 = OpAccessChain %59 %23 %38 %38 -%159 = OpAtomicOr %4 %160 %3 %58 %39 -OpControlBarrier %7 %7 %51 -%161 = OpAtomicXor %5 %33 %39 %53 %38 +%159 = OpAtomicOr %4 %160 %9 %58 %39 +OpControlBarrier %6 %6 %51 +%161 = OpAtomicXor %3 %33 %39 %53 %38 %163 = OpAccessChain %54 %35 %38 %162 = OpAtomicXor %4 %163 %39 %53 %39 %165 = OpAccessChain %31 %37 %32 -%164 = OpAtomicXor %5 %165 %39 %53 %38 +%164 = OpAtomicXor %3 %165 %39 %53 %38 %167 = OpAccessChain %54 %37 %38 %38 %166 = OpAtomicXor %4 %167 %39 %53 %39 -%168 = OpAtomicXor %5 %19 %3 %58 %38 +%168 = OpAtomicXor %3 %19 %9 %58 %38 %170 = OpAccessChain %59 %21 %38 -%169 = OpAtomicXor %4 %170 %3 %58 %39 +%169 = OpAtomicXor %4 %170 %9 %58 %39 %172 = OpAccessChain %20 %23 %32 -%171 = OpAtomicXor %5 %172 %3 %58 %38 +%171 = OpAtomicXor %3 %172 %9 %58 %38 %174 = OpAccessChain %59 %23 %38 %38 -%173 = OpAtomicXor %4 %174 %3 %58 %39 -%175 = OpAtomicExchange %5 %33 %39 %53 %38 +%173 = OpAtomicXor %4 %174 %9 %58 %39 +%175 = OpAtomicExchange %3 %33 %39 %53 %38 %177 = OpAccessChain %54 %35 %38 %176 = OpAtomicExchange %4 %177 %39 %53 %39 %179 = OpAccessChain %31 %37 %32 -%178 = OpAtomicExchange %5 %179 %39 %53 %38 +%178 = OpAtomicExchange %3 %179 %39 %53 %38 %181 = OpAccessChain %54 %37 %38 %38 %180 = OpAtomicExchange %4 %181 %39 %53 %39 -%182 = OpAtomicExchange %5 %19 %3 %58 %38 +%182 = OpAtomicExchange %3 %19 %9 %58 %38 %184 = OpAccessChain %59 %21 %38 -%183 = OpAtomicExchange %4 %184 %3 %58 %39 +%183 = OpAtomicExchange %4 %184 %9 %58 %39 %186 = OpAccessChain %20 %23 %32 -%185 = OpAtomicExchange %5 %186 %3 %58 %38 +%185 = OpAtomicExchange %3 %186 %9 %58 %38 %188 = OpAccessChain %59 %23 %38 %38 -%187 = OpAtomicExchange %4 %188 %3 %58 %39 +%187 = OpAtomicExchange %4 %188 %9 %58 %39 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 4574eb108..393df57bb 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -10,8 +10,8 @@ OpExtension "SPV_EXT_descriptor_indexing" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %68 "main" %63 %66 OpExecutionMode %68 OriginUpperLeft -OpMemberDecorate %6 0 Offset 0 -OpMemberDecorate %23 0 Offset 0 +OpMemberDecorate %4 0 Offset 0 +OpMemberDecorate %21 0 Offset 0 OpDecorate %28 DescriptorSet 0 OpDecorate %28 Binding 0 OpDecorate %32 DescriptorSet 0 @@ -58,471 +58,471 @@ OpDecorate %399 NonUniform OpDecorate %401 NonUniform OpDecorate %424 NonUniform %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 5 -%5 = OpTypeInt 32 0 -%6 = OpTypeStruct %5 -%8 = OpTypeFloat 32 -%7 = OpTypeImage %8 2D 0 0 0 1 Unknown -%9 = OpTypeRuntimeArray %7 -%11 = OpConstant %5 5 -%10 = OpTypeArray %7 %11 -%12 = OpTypeImage %8 2D 0 1 0 1 Unknown -%13 = OpTypeArray %12 %11 -%14 = OpTypeImage %8 2D 0 0 1 1 Unknown -%15 = OpTypeArray %14 %11 -%16 = OpTypeImage %8 2D 1 0 0 1 Unknown -%17 = OpTypeArray %16 %11 -%18 = OpTypeImage %8 2D 0 0 0 2 Rgba32f -%19 = OpTypeArray %18 %11 -%20 = OpTypeSampler -%21 = OpTypeArray %20 %11 -%22 = OpTypeArray %20 %11 -%23 = OpTypeStruct %5 -%24 = OpTypeVector %8 4 -%25 = OpTypeVector %5 2 -%26 = OpTypeVector %8 2 -%27 = OpTypeVector %4 2 -%31 = OpConstant %5 10 -%30 = OpTypeArray %7 %31 +%3 = OpTypeInt 32 0 +%4 = OpTypeStruct %3 +%6 = OpTypeFloat 32 +%5 = OpTypeImage %6 2D 0 0 0 1 Unknown +%7 = OpTypeRuntimeArray %5 +%9 = OpConstant %3 5 +%8 = OpTypeArray %5 %9 +%10 = OpTypeImage %6 2D 0 1 0 1 Unknown +%11 = OpTypeArray %10 %9 +%12 = OpTypeImage %6 2D 0 0 1 1 Unknown +%13 = OpTypeArray %12 %9 +%14 = OpTypeImage %6 2D 1 0 0 1 Unknown +%15 = OpTypeArray %14 %9 +%16 = OpTypeImage %6 2D 0 0 0 2 Rgba32f +%17 = OpTypeArray %16 %9 +%18 = OpTypeSampler +%19 = OpTypeArray %18 %9 +%20 = OpTypeArray %18 %9 +%21 = OpTypeStruct %3 +%22 = OpTypeVector %6 4 +%23 = OpTypeVector %3 2 +%24 = OpTypeVector %6 2 +%26 = OpTypeInt 32 1 +%25 = OpTypeVector %26 2 +%27 = OpConstant %26 5 +%31 = OpConstant %3 10 +%30 = OpTypeArray %5 %31 %29 = OpTypePointer UniformConstant %30 %28 = OpVariable %29 UniformConstant -%33 = OpTypePointer UniformConstant %10 +%33 = OpTypePointer UniformConstant %8 %32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %13 +%35 = OpTypePointer UniformConstant %11 %34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %15 +%37 = OpTypePointer UniformConstant %13 %36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %17 +%39 = OpTypePointer UniformConstant %15 %38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %19 +%41 = OpTypePointer UniformConstant %17 %40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %21 +%43 = OpTypePointer UniformConstant %19 %42 = OpVariable %43 UniformConstant -%45 = OpTypePointer UniformConstant %22 +%45 = OpTypePointer UniformConstant %20 %44 = OpVariable %45 UniformConstant -%47 = OpTypeStruct %6 +%47 = OpTypeStruct %4 %48 = OpTypePointer Uniform %47 %46 = OpVariable %48 Uniform -%50 = OpTypePointer Function %5 -%51 = OpConstantNull %5 -%53 = OpTypePointer Function %25 -%54 = OpConstantNull %25 -%56 = OpTypePointer Function %8 -%57 = OpConstantNull %8 -%59 = OpTypePointer Function %24 -%60 = OpConstantNull %24 -%64 = OpTypePointer Input %5 +%50 = OpTypePointer Function %3 +%51 = OpConstantNull %3 +%53 = OpTypePointer Function %23 +%54 = OpConstantNull %23 +%56 = OpTypePointer Function %6 +%57 = OpConstantNull %6 +%59 = OpTypePointer Function %22 +%60 = OpConstantNull %22 +%64 = OpTypePointer Input %3 %63 = OpVariable %64 Input -%67 = OpTypePointer Output %24 +%67 = OpTypePointer Output %22 %66 = OpVariable %67 Output %69 = OpTypeFunction %2 -%70 = OpTypePointer Uniform %6 -%71 = OpConstant %5 0 -%73 = OpConstant %8 0.0 -%74 = OpConstant %4 0 -%76 = OpTypePointer Uniform %5 -%84 = OpTypePointer UniformConstant %7 -%105 = OpTypePointer UniformConstant %20 -%108 = OpTypeSampledImage %7 -%129 = OpTypePointer UniformConstant %16 -%132 = OpTypePointer UniformConstant %20 -%135 = OpTypeSampledImage %16 +%70 = OpTypePointer Uniform %4 +%71 = OpConstant %3 0 +%73 = OpConstant %6 0.0 +%74 = OpConstant %26 0 +%76 = OpTypePointer Uniform %3 +%84 = OpTypePointer UniformConstant %5 +%105 = OpTypePointer UniformConstant %18 +%108 = OpTypeSampledImage %5 +%129 = OpTypePointer UniformConstant %14 +%132 = OpTypePointer UniformConstant %18 +%135 = OpTypeSampledImage %14 %158 = OpTypeBool -%159 = OpConstantNull %24 +%159 = OpConstantNull %22 %165 = OpTypeVector %158 2 -%175 = OpConstantNull %24 -%190 = OpConstantNull %24 -%203 = OpTypePointer UniformConstant %12 -%206 = OpTypeVector %4 3 -%244 = OpTypePointer UniformConstant %14 -%407 = OpTypePointer UniformConstant %18 +%175 = OpConstantNull %22 +%190 = OpConstantNull %22 +%203 = OpTypePointer UniformConstant %10 +%206 = OpTypeVector %26 3 +%244 = OpTypePointer UniformConstant %12 +%407 = OpTypePointer UniformConstant %16 %68 = OpFunction %2 None %69 %61 = OpLabel %52 = OpVariable %53 Function %54 %58 = OpVariable %59 Function %60 %49 = OpVariable %50 Function %51 %55 = OpVariable %56 Function %57 -%65 = OpLoad %5 %63 -%62 = OpCompositeConstruct %23 %65 +%65 = OpLoad %3 %63 +%62 = OpCompositeConstruct %21 %65 %72 = OpAccessChain %70 %46 %71 OpBranch %75 %75 = OpLabel %77 = OpAccessChain %76 %72 %71 -%78 = OpLoad %5 %77 -%79 = OpCompositeExtract %5 %62 0 +%78 = OpLoad %3 %77 +%79 = OpCompositeExtract %3 %62 0 OpStore %49 %71 -%80 = OpCompositeConstruct %25 %71 %71 +%80 = OpCompositeConstruct %23 %71 %71 OpStore %52 %80 OpStore %55 %73 -%81 = OpCompositeConstruct %24 %73 %73 %73 %73 +%81 = OpCompositeConstruct %22 %73 %73 %73 %73 OpStore %58 %81 -%82 = OpCompositeConstruct %26 %73 %73 -%83 = OpCompositeConstruct %27 %74 %74 +%82 = OpCompositeConstruct %24 %73 %73 +%83 = OpCompositeConstruct %25 %74 %74 %85 = OpAccessChain %84 %28 %71 -%86 = OpLoad %7 %85 -%87 = OpImageQuerySizeLod %27 %86 %71 -%88 = OpBitcast %25 %87 -%89 = OpLoad %25 %52 -%90 = OpIAdd %25 %89 %88 +%86 = OpLoad %5 %85 +%87 = OpImageQuerySizeLod %25 %86 %71 +%88 = OpBitcast %23 %87 +%89 = OpLoad %23 %52 +%90 = OpIAdd %23 %89 %88 OpStore %52 %90 %91 = OpAccessChain %84 %28 %78 -%92 = OpLoad %7 %91 -%93 = OpImageQuerySizeLod %27 %92 %71 -%94 = OpBitcast %25 %93 -%95 = OpLoad %25 %52 -%96 = OpIAdd %25 %95 %94 +%92 = OpLoad %5 %91 +%93 = OpImageQuerySizeLod %25 %92 %71 +%94 = OpBitcast %23 %93 +%95 = OpLoad %23 %52 +%96 = OpIAdd %23 %95 %94 OpStore %52 %96 %97 = OpAccessChain %84 %28 %79 -%98 = OpLoad %7 %97 -%99 = OpImageQuerySizeLod %27 %98 %71 -%100 = OpBitcast %25 %99 -%101 = OpLoad %25 %52 -%102 = OpIAdd %25 %101 %100 +%98 = OpLoad %5 %97 +%99 = OpImageQuerySizeLod %25 %98 %71 +%100 = OpBitcast %23 %99 +%101 = OpLoad %23 %52 +%102 = OpIAdd %23 %101 %100 OpStore %52 %102 %103 = OpAccessChain %84 %32 %71 -%104 = OpLoad %7 %103 +%104 = OpLoad %5 %103 %106 = OpAccessChain %105 %42 %71 -%107 = OpLoad %20 %106 +%107 = OpLoad %18 %106 %109 = OpSampledImage %108 %104 %107 -%110 = OpImageGather %24 %109 %82 %71 -%111 = OpLoad %24 %58 -%112 = OpFAdd %24 %111 %110 +%110 = OpImageGather %22 %109 %82 %71 +%111 = OpLoad %22 %58 +%112 = OpFAdd %22 %111 %110 OpStore %58 %112 %113 = OpAccessChain %84 %32 %78 -%114 = OpLoad %7 %113 +%114 = OpLoad %5 %113 %115 = OpAccessChain %105 %42 %78 -%116 = OpLoad %20 %115 +%116 = OpLoad %18 %115 %117 = OpSampledImage %108 %114 %116 -%118 = OpImageGather %24 %117 %82 %71 -%119 = OpLoad %24 %58 -%120 = OpFAdd %24 %119 %118 +%118 = OpImageGather %22 %117 %82 %71 +%119 = OpLoad %22 %58 +%120 = OpFAdd %22 %119 %118 OpStore %58 %120 %121 = OpAccessChain %84 %32 %79 -%122 = OpLoad %7 %121 +%122 = OpLoad %5 %121 %123 = OpAccessChain %105 %42 %79 -%124 = OpLoad %20 %123 +%124 = OpLoad %18 %123 %125 = OpSampledImage %108 %122 %124 -%126 = OpImageGather %24 %125 %82 %71 -%127 = OpLoad %24 %58 -%128 = OpFAdd %24 %127 %126 +%126 = OpImageGather %22 %125 %82 %71 +%127 = OpLoad %22 %58 +%128 = OpFAdd %22 %127 %126 OpStore %58 %128 %130 = OpAccessChain %129 %38 %71 -%131 = OpLoad %16 %130 +%131 = OpLoad %14 %130 %133 = OpAccessChain %132 %44 %71 -%134 = OpLoad %20 %133 +%134 = OpLoad %18 %133 %136 = OpSampledImage %135 %131 %134 -%137 = OpImageDrefGather %24 %136 %82 %73 -%138 = OpLoad %24 %58 -%139 = OpFAdd %24 %138 %137 +%137 = OpImageDrefGather %22 %136 %82 %73 +%138 = OpLoad %22 %58 +%139 = OpFAdd %22 %138 %137 OpStore %58 %139 %140 = OpAccessChain %129 %38 %78 -%141 = OpLoad %16 %140 +%141 = OpLoad %14 %140 %142 = OpAccessChain %132 %44 %78 -%143 = OpLoad %20 %142 +%143 = OpLoad %18 %142 %144 = OpSampledImage %135 %141 %143 -%145 = OpImageDrefGather %24 %144 %82 %73 -%146 = OpLoad %24 %58 -%147 = OpFAdd %24 %146 %145 +%145 = OpImageDrefGather %22 %144 %82 %73 +%146 = OpLoad %22 %58 +%147 = OpFAdd %22 %146 %145 OpStore %58 %147 %148 = OpAccessChain %129 %38 %79 -%149 = OpLoad %16 %148 +%149 = OpLoad %14 %148 %150 = OpAccessChain %132 %44 %79 -%151 = OpLoad %20 %150 +%151 = OpLoad %18 %150 %152 = OpSampledImage %135 %149 %151 -%153 = OpImageDrefGather %24 %152 %82 %73 -%154 = OpLoad %24 %58 -%155 = OpFAdd %24 %154 %153 +%153 = OpImageDrefGather %22 %152 %82 %73 +%154 = OpLoad %22 %58 +%155 = OpFAdd %22 %154 %153 OpStore %58 %155 %156 = OpAccessChain %84 %28 %71 -%157 = OpLoad %7 %156 -%160 = OpImageQueryLevels %4 %157 +%157 = OpLoad %5 %156 +%160 = OpImageQueryLevels %26 %157 %161 = OpULessThan %158 %74 %160 OpSelectionMerge %162 None OpBranchConditional %161 %163 %162 %163 = OpLabel -%164 = OpImageQuerySizeLod %27 %157 %74 +%164 = OpImageQuerySizeLod %25 %157 %74 %166 = OpULessThan %165 %83 %164 %167 = OpAll %158 %166 OpBranchConditional %167 %168 %162 %168 = OpLabel -%169 = OpImageFetch %24 %157 %83 Lod %74 +%169 = OpImageFetch %22 %157 %83 Lod %74 OpBranch %162 %162 = OpLabel -%170 = OpPhi %24 %159 %75 %159 %163 %169 %168 -%171 = OpLoad %24 %58 -%172 = OpFAdd %24 %171 %170 +%170 = OpPhi %22 %159 %75 %159 %163 %169 %168 +%171 = OpLoad %22 %58 +%172 = OpFAdd %22 %171 %170 OpStore %58 %172 %173 = OpAccessChain %84 %28 %78 -%174 = OpLoad %7 %173 -%176 = OpImageQueryLevels %4 %174 +%174 = OpLoad %5 %173 +%176 = OpImageQueryLevels %26 %174 %177 = OpULessThan %158 %74 %176 OpSelectionMerge %178 None OpBranchConditional %177 %179 %178 %179 = OpLabel -%180 = OpImageQuerySizeLod %27 %174 %74 +%180 = OpImageQuerySizeLod %25 %174 %74 %181 = OpULessThan %165 %83 %180 %182 = OpAll %158 %181 OpBranchConditional %182 %183 %178 %183 = OpLabel -%184 = OpImageFetch %24 %174 %83 Lod %74 +%184 = OpImageFetch %22 %174 %83 Lod %74 OpBranch %178 %178 = OpLabel -%185 = OpPhi %24 %175 %162 %175 %179 %184 %183 -%186 = OpLoad %24 %58 -%187 = OpFAdd %24 %186 %185 +%185 = OpPhi %22 %175 %162 %175 %179 %184 %183 +%186 = OpLoad %22 %58 +%187 = OpFAdd %22 %186 %185 OpStore %58 %187 %188 = OpAccessChain %84 %28 %79 -%189 = OpLoad %7 %188 -%191 = OpImageQueryLevels %4 %189 +%189 = OpLoad %5 %188 +%191 = OpImageQueryLevels %26 %189 %192 = OpULessThan %158 %74 %191 OpSelectionMerge %193 None OpBranchConditional %192 %194 %193 %194 = OpLabel -%195 = OpImageQuerySizeLod %27 %189 %74 +%195 = OpImageQuerySizeLod %25 %189 %74 %196 = OpULessThan %165 %83 %195 %197 = OpAll %158 %196 OpBranchConditional %197 %198 %193 %198 = OpLabel -%199 = OpImageFetch %24 %189 %83 Lod %74 +%199 = OpImageFetch %22 %189 %83 Lod %74 OpBranch %193 %193 = OpLabel -%200 = OpPhi %24 %190 %178 %190 %194 %199 %198 -%201 = OpLoad %24 %58 -%202 = OpFAdd %24 %201 %200 +%200 = OpPhi %22 %190 %178 %190 %194 %199 %198 +%201 = OpLoad %22 %58 +%202 = OpFAdd %22 %201 %200 OpStore %58 %202 %204 = OpAccessChain %203 %34 %71 -%205 = OpLoad %12 %204 +%205 = OpLoad %10 %204 %207 = OpImageQuerySizeLod %206 %205 %71 -%208 = OpCompositeExtract %4 %207 2 -%209 = OpBitcast %5 %208 -%210 = OpLoad %5 %49 -%211 = OpIAdd %5 %210 %209 +%208 = OpCompositeExtract %26 %207 2 +%209 = OpBitcast %3 %208 +%210 = OpLoad %3 %49 +%211 = OpIAdd %3 %210 %209 OpStore %49 %211 %212 = OpAccessChain %203 %34 %78 -%213 = OpLoad %12 %212 +%213 = OpLoad %10 %212 %214 = OpImageQuerySizeLod %206 %213 %71 -%215 = OpCompositeExtract %4 %214 2 -%216 = OpBitcast %5 %215 -%217 = OpLoad %5 %49 -%218 = OpIAdd %5 %217 %216 +%215 = OpCompositeExtract %26 %214 2 +%216 = OpBitcast %3 %215 +%217 = OpLoad %3 %49 +%218 = OpIAdd %3 %217 %216 OpStore %49 %218 %219 = OpAccessChain %203 %34 %79 -%220 = OpLoad %12 %219 +%220 = OpLoad %10 %219 %221 = OpImageQuerySizeLod %206 %220 %71 -%222 = OpCompositeExtract %4 %221 2 -%223 = OpBitcast %5 %222 -%224 = OpLoad %5 %49 -%225 = OpIAdd %5 %224 %223 +%222 = OpCompositeExtract %26 %221 2 +%223 = OpBitcast %3 %222 +%224 = OpLoad %3 %49 +%225 = OpIAdd %3 %224 %223 OpStore %49 %225 %226 = OpAccessChain %84 %32 %71 -%227 = OpLoad %7 %226 -%228 = OpImageQueryLevels %4 %227 -%229 = OpBitcast %5 %228 -%230 = OpLoad %5 %49 -%231 = OpIAdd %5 %230 %229 +%227 = OpLoad %5 %226 +%228 = OpImageQueryLevels %26 %227 +%229 = OpBitcast %3 %228 +%230 = OpLoad %3 %49 +%231 = OpIAdd %3 %230 %229 OpStore %49 %231 %232 = OpAccessChain %84 %32 %78 -%233 = OpLoad %7 %232 -%234 = OpImageQueryLevels %4 %233 -%235 = OpBitcast %5 %234 -%236 = OpLoad %5 %49 -%237 = OpIAdd %5 %236 %235 +%233 = OpLoad %5 %232 +%234 = OpImageQueryLevels %26 %233 +%235 = OpBitcast %3 %234 +%236 = OpLoad %3 %49 +%237 = OpIAdd %3 %236 %235 OpStore %49 %237 %238 = OpAccessChain %84 %32 %79 -%239 = OpLoad %7 %238 -%240 = OpImageQueryLevels %4 %239 -%241 = OpBitcast %5 %240 -%242 = OpLoad %5 %49 -%243 = OpIAdd %5 %242 %241 +%239 = OpLoad %5 %238 +%240 = OpImageQueryLevels %26 %239 +%241 = OpBitcast %3 %240 +%242 = OpLoad %3 %49 +%243 = OpIAdd %3 %242 %241 OpStore %49 %243 %245 = OpAccessChain %244 %36 %71 -%246 = OpLoad %14 %245 -%247 = OpImageQuerySamples %4 %246 -%248 = OpBitcast %5 %247 -%249 = OpLoad %5 %49 -%250 = OpIAdd %5 %249 %248 +%246 = OpLoad %12 %245 +%247 = OpImageQuerySamples %26 %246 +%248 = OpBitcast %3 %247 +%249 = OpLoad %3 %49 +%250 = OpIAdd %3 %249 %248 OpStore %49 %250 %251 = OpAccessChain %244 %36 %78 -%252 = OpLoad %14 %251 -%253 = OpImageQuerySamples %4 %252 -%254 = OpBitcast %5 %253 -%255 = OpLoad %5 %49 -%256 = OpIAdd %5 %255 %254 +%252 = OpLoad %12 %251 +%253 = OpImageQuerySamples %26 %252 +%254 = OpBitcast %3 %253 +%255 = OpLoad %3 %49 +%256 = OpIAdd %3 %255 %254 OpStore %49 %256 %257 = OpAccessChain %244 %36 %79 -%258 = OpLoad %14 %257 -%259 = OpImageQuerySamples %4 %258 -%260 = OpBitcast %5 %259 -%261 = OpLoad %5 %49 -%262 = OpIAdd %5 %261 %260 +%258 = OpLoad %12 %257 +%259 = OpImageQuerySamples %26 %258 +%260 = OpBitcast %3 %259 +%261 = OpLoad %3 %49 +%262 = OpIAdd %3 %261 %260 OpStore %49 %262 %263 = OpAccessChain %84 %32 %71 -%264 = OpLoad %7 %263 +%264 = OpLoad %5 %263 %265 = OpAccessChain %105 %42 %71 -%266 = OpLoad %20 %265 +%266 = OpLoad %18 %265 %267 = OpSampledImage %108 %264 %266 -%268 = OpImageSampleImplicitLod %24 %267 %82 -%269 = OpLoad %24 %58 -%270 = OpFAdd %24 %269 %268 +%268 = OpImageSampleImplicitLod %22 %267 %82 +%269 = OpLoad %22 %58 +%270 = OpFAdd %22 %269 %268 OpStore %58 %270 %271 = OpAccessChain %84 %32 %78 -%272 = OpLoad %7 %271 +%272 = OpLoad %5 %271 %273 = OpAccessChain %105 %42 %78 -%274 = OpLoad %20 %273 +%274 = OpLoad %18 %273 %275 = OpSampledImage %108 %272 %274 -%276 = OpImageSampleImplicitLod %24 %275 %82 -%277 = OpLoad %24 %58 -%278 = OpFAdd %24 %277 %276 +%276 = OpImageSampleImplicitLod %22 %275 %82 +%277 = OpLoad %22 %58 +%278 = OpFAdd %22 %277 %276 OpStore %58 %278 %279 = OpAccessChain %84 %32 %79 -%280 = OpLoad %7 %279 +%280 = OpLoad %5 %279 %281 = OpAccessChain %105 %42 %79 -%282 = OpLoad %20 %281 +%282 = OpLoad %18 %281 %283 = OpSampledImage %108 %280 %282 -%284 = OpImageSampleImplicitLod %24 %283 %82 -%285 = OpLoad %24 %58 -%286 = OpFAdd %24 %285 %284 +%284 = OpImageSampleImplicitLod %22 %283 %82 +%285 = OpLoad %22 %58 +%286 = OpFAdd %22 %285 %284 OpStore %58 %286 %287 = OpAccessChain %84 %32 %71 -%288 = OpLoad %7 %287 +%288 = OpLoad %5 %287 %289 = OpAccessChain %105 %42 %71 -%290 = OpLoad %20 %289 +%290 = OpLoad %18 %289 %291 = OpSampledImage %108 %288 %290 -%292 = OpImageSampleImplicitLod %24 %291 %82 Bias %73 -%293 = OpLoad %24 %58 -%294 = OpFAdd %24 %293 %292 +%292 = OpImageSampleImplicitLod %22 %291 %82 Bias %73 +%293 = OpLoad %22 %58 +%294 = OpFAdd %22 %293 %292 OpStore %58 %294 %295 = OpAccessChain %84 %32 %78 -%296 = OpLoad %7 %295 +%296 = OpLoad %5 %295 %297 = OpAccessChain %105 %42 %78 -%298 = OpLoad %20 %297 +%298 = OpLoad %18 %297 %299 = OpSampledImage %108 %296 %298 -%300 = OpImageSampleImplicitLod %24 %299 %82 Bias %73 -%301 = OpLoad %24 %58 -%302 = OpFAdd %24 %301 %300 +%300 = OpImageSampleImplicitLod %22 %299 %82 Bias %73 +%301 = OpLoad %22 %58 +%302 = OpFAdd %22 %301 %300 OpStore %58 %302 %303 = OpAccessChain %84 %32 %79 -%304 = OpLoad %7 %303 +%304 = OpLoad %5 %303 %305 = OpAccessChain %105 %42 %79 -%306 = OpLoad %20 %305 +%306 = OpLoad %18 %305 %307 = OpSampledImage %108 %304 %306 -%308 = OpImageSampleImplicitLod %24 %307 %82 Bias %73 -%309 = OpLoad %24 %58 -%310 = OpFAdd %24 %309 %308 +%308 = OpImageSampleImplicitLod %22 %307 %82 Bias %73 +%309 = OpLoad %22 %58 +%310 = OpFAdd %22 %309 %308 OpStore %58 %310 %311 = OpAccessChain %129 %38 %71 -%312 = OpLoad %16 %311 +%312 = OpLoad %14 %311 %313 = OpAccessChain %132 %44 %71 -%314 = OpLoad %20 %313 +%314 = OpLoad %18 %313 %315 = OpSampledImage %135 %312 %314 -%316 = OpImageSampleDrefImplicitLod %8 %315 %82 %73 -%317 = OpLoad %8 %55 -%318 = OpFAdd %8 %317 %316 +%316 = OpImageSampleDrefImplicitLod %6 %315 %82 %73 +%317 = OpLoad %6 %55 +%318 = OpFAdd %6 %317 %316 OpStore %55 %318 %319 = OpAccessChain %129 %38 %78 -%320 = OpLoad %16 %319 +%320 = OpLoad %14 %319 %321 = OpAccessChain %132 %44 %78 -%322 = OpLoad %20 %321 +%322 = OpLoad %18 %321 %323 = OpSampledImage %135 %320 %322 -%324 = OpImageSampleDrefImplicitLod %8 %323 %82 %73 -%325 = OpLoad %8 %55 -%326 = OpFAdd %8 %325 %324 +%324 = OpImageSampleDrefImplicitLod %6 %323 %82 %73 +%325 = OpLoad %6 %55 +%326 = OpFAdd %6 %325 %324 OpStore %55 %326 %327 = OpAccessChain %129 %38 %79 -%328 = OpLoad %16 %327 +%328 = OpLoad %14 %327 %329 = OpAccessChain %132 %44 %79 -%330 = OpLoad %20 %329 +%330 = OpLoad %18 %329 %331 = OpSampledImage %135 %328 %330 -%332 = OpImageSampleDrefImplicitLod %8 %331 %82 %73 -%333 = OpLoad %8 %55 -%334 = OpFAdd %8 %333 %332 +%332 = OpImageSampleDrefImplicitLod %6 %331 %82 %73 +%333 = OpLoad %6 %55 +%334 = OpFAdd %6 %333 %332 OpStore %55 %334 %335 = OpAccessChain %129 %38 %71 -%336 = OpLoad %16 %335 +%336 = OpLoad %14 %335 %337 = OpAccessChain %132 %44 %71 -%338 = OpLoad %20 %337 +%338 = OpLoad %18 %337 %339 = OpSampledImage %135 %336 %338 -%340 = OpImageSampleDrefExplicitLod %8 %339 %82 %73 Lod %73 -%341 = OpLoad %8 %55 -%342 = OpFAdd %8 %341 %340 +%340 = OpImageSampleDrefExplicitLod %6 %339 %82 %73 Lod %73 +%341 = OpLoad %6 %55 +%342 = OpFAdd %6 %341 %340 OpStore %55 %342 %343 = OpAccessChain %129 %38 %78 -%344 = OpLoad %16 %343 +%344 = OpLoad %14 %343 %345 = OpAccessChain %132 %44 %78 -%346 = OpLoad %20 %345 +%346 = OpLoad %18 %345 %347 = OpSampledImage %135 %344 %346 -%348 = OpImageSampleDrefExplicitLod %8 %347 %82 %73 Lod %73 -%349 = OpLoad %8 %55 -%350 = OpFAdd %8 %349 %348 +%348 = OpImageSampleDrefExplicitLod %6 %347 %82 %73 Lod %73 +%349 = OpLoad %6 %55 +%350 = OpFAdd %6 %349 %348 OpStore %55 %350 %351 = OpAccessChain %129 %38 %79 -%352 = OpLoad %16 %351 +%352 = OpLoad %14 %351 %353 = OpAccessChain %132 %44 %79 -%354 = OpLoad %20 %353 +%354 = OpLoad %18 %353 %355 = OpSampledImage %135 %352 %354 -%356 = OpImageSampleDrefExplicitLod %8 %355 %82 %73 Lod %73 -%357 = OpLoad %8 %55 -%358 = OpFAdd %8 %357 %356 +%356 = OpImageSampleDrefExplicitLod %6 %355 %82 %73 Lod %73 +%357 = OpLoad %6 %55 +%358 = OpFAdd %6 %357 %356 OpStore %55 %358 %359 = OpAccessChain %84 %32 %71 -%360 = OpLoad %7 %359 +%360 = OpLoad %5 %359 %361 = OpAccessChain %105 %42 %71 -%362 = OpLoad %20 %361 +%362 = OpLoad %18 %361 %363 = OpSampledImage %108 %360 %362 -%364 = OpImageSampleExplicitLod %24 %363 %82 Grad %82 %82 -%365 = OpLoad %24 %58 -%366 = OpFAdd %24 %365 %364 +%364 = OpImageSampleExplicitLod %22 %363 %82 Grad %82 %82 +%365 = OpLoad %22 %58 +%366 = OpFAdd %22 %365 %364 OpStore %58 %366 %367 = OpAccessChain %84 %32 %78 -%368 = OpLoad %7 %367 +%368 = OpLoad %5 %367 %369 = OpAccessChain %105 %42 %78 -%370 = OpLoad %20 %369 +%370 = OpLoad %18 %369 %371 = OpSampledImage %108 %368 %370 -%372 = OpImageSampleExplicitLod %24 %371 %82 Grad %82 %82 -%373 = OpLoad %24 %58 -%374 = OpFAdd %24 %373 %372 +%372 = OpImageSampleExplicitLod %22 %371 %82 Grad %82 %82 +%373 = OpLoad %22 %58 +%374 = OpFAdd %22 %373 %372 OpStore %58 %374 %375 = OpAccessChain %84 %32 %79 -%376 = OpLoad %7 %375 +%376 = OpLoad %5 %375 %377 = OpAccessChain %105 %42 %79 -%378 = OpLoad %20 %377 +%378 = OpLoad %18 %377 %379 = OpSampledImage %108 %376 %378 -%380 = OpImageSampleExplicitLod %24 %379 %82 Grad %82 %82 -%381 = OpLoad %24 %58 -%382 = OpFAdd %24 %381 %380 +%380 = OpImageSampleExplicitLod %22 %379 %82 Grad %82 %82 +%381 = OpLoad %22 %58 +%382 = OpFAdd %22 %381 %380 OpStore %58 %382 %383 = OpAccessChain %84 %32 %71 -%384 = OpLoad %7 %383 +%384 = OpLoad %5 %383 %385 = OpAccessChain %105 %42 %71 -%386 = OpLoad %20 %385 +%386 = OpLoad %18 %385 %387 = OpSampledImage %108 %384 %386 -%388 = OpImageSampleExplicitLod %24 %387 %82 Lod %73 -%389 = OpLoad %24 %58 -%390 = OpFAdd %24 %389 %388 +%388 = OpImageSampleExplicitLod %22 %387 %82 Lod %73 +%389 = OpLoad %22 %58 +%390 = OpFAdd %22 %389 %388 OpStore %58 %390 %391 = OpAccessChain %84 %32 %78 -%392 = OpLoad %7 %391 +%392 = OpLoad %5 %391 %393 = OpAccessChain %105 %42 %78 -%394 = OpLoad %20 %393 +%394 = OpLoad %18 %393 %395 = OpSampledImage %108 %392 %394 -%396 = OpImageSampleExplicitLod %24 %395 %82 Lod %73 -%397 = OpLoad %24 %58 -%398 = OpFAdd %24 %397 %396 +%396 = OpImageSampleExplicitLod %22 %395 %82 Lod %73 +%397 = OpLoad %22 %58 +%398 = OpFAdd %22 %397 %396 OpStore %58 %398 %399 = OpAccessChain %84 %32 %79 -%400 = OpLoad %7 %399 +%400 = OpLoad %5 %399 %401 = OpAccessChain %105 %42 %79 -%402 = OpLoad %20 %401 +%402 = OpLoad %18 %401 %403 = OpSampledImage %108 %400 %402 -%404 = OpImageSampleExplicitLod %24 %403 %82 Lod %73 -%405 = OpLoad %24 %58 -%406 = OpFAdd %24 %405 %404 +%404 = OpImageSampleExplicitLod %22 %403 %82 Lod %73 +%405 = OpLoad %22 %58 +%406 = OpFAdd %22 %405 %404 OpStore %58 %406 %408 = OpAccessChain %407 %40 %71 -%409 = OpLoad %18 %408 -%410 = OpLoad %24 %58 -%411 = OpImageQuerySize %27 %409 +%409 = OpLoad %16 %408 +%410 = OpLoad %22 %58 +%411 = OpImageQuerySize %25 %409 %412 = OpULessThan %165 %83 %411 %413 = OpAll %158 %412 OpSelectionMerge %414 None @@ -532,9 +532,9 @@ OpImageWrite %409 %83 %410 OpBranch %414 %414 = OpLabel %416 = OpAccessChain %407 %40 %78 -%417 = OpLoad %18 %416 -%418 = OpLoad %24 %58 -%419 = OpImageQuerySize %27 %417 +%417 = OpLoad %16 %416 +%418 = OpLoad %22 %58 +%419 = OpImageQuerySize %25 %417 %420 = OpULessThan %165 %83 %419 %421 = OpAll %158 %420 OpSelectionMerge %422 None @@ -544,9 +544,9 @@ OpImageWrite %417 %83 %418 OpBranch %422 %422 = OpLabel %424 = OpAccessChain %407 %40 %79 -%425 = OpLoad %18 %424 -%426 = OpLoad %24 %58 -%427 = OpImageQuerySize %27 %425 +%425 = OpLoad %16 %424 +%426 = OpLoad %22 %58 +%427 = OpImageQuerySize %25 %425 %428 = OpULessThan %165 %83 %427 %429 = OpAll %158 %428 OpSelectionMerge %430 None @@ -555,21 +555,21 @@ OpBranchConditional %429 %431 %430 OpImageWrite %425 %83 %426 OpBranch %430 %430 = OpLabel -%432 = OpLoad %25 %52 -%433 = OpLoad %5 %49 -%434 = OpCompositeConstruct %25 %433 %433 -%435 = OpIAdd %25 %432 %434 -%436 = OpConvertUToF %26 %435 -%437 = OpLoad %24 %58 -%438 = OpCompositeExtract %8 %436 0 -%439 = OpCompositeExtract %8 %436 1 -%440 = OpCompositeExtract %8 %436 0 -%441 = OpCompositeExtract %8 %436 1 -%442 = OpCompositeConstruct %24 %438 %439 %440 %441 -%443 = OpFAdd %24 %437 %442 -%444 = OpLoad %8 %55 -%445 = OpCompositeConstruct %24 %444 %444 %444 %444 -%446 = OpFAdd %24 %443 %445 +%432 = OpLoad %23 %52 +%433 = OpLoad %3 %49 +%434 = OpCompositeConstruct %23 %433 %433 +%435 = OpIAdd %23 %432 %434 +%436 = OpConvertUToF %24 %435 +%437 = OpLoad %22 %58 +%438 = OpCompositeExtract %6 %436 0 +%439 = OpCompositeExtract %6 %436 1 +%440 = OpCompositeExtract %6 %436 0 +%441 = OpCompositeExtract %6 %436 1 +%442 = OpCompositeConstruct %22 %438 %439 %440 %441 +%443 = OpFAdd %22 %437 %442 +%444 = OpLoad %6 %55 +%445 = OpCompositeConstruct %22 %444 %444 %444 %444 +%446 = OpFAdd %22 %443 %445 OpStore %66 %446 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-buffer-arrays.spvasm b/tests/out/spv/binding-buffer-arrays.spvasm index b09377b6b..83a676a9e 100644 --- a/tests/out/spv/binding-buffer-arrays.spvasm +++ b/tests/out/spv/binding-buffer-arrays.spvasm @@ -10,13 +10,13 @@ OpExtension "SPV_EXT_descriptor_indexing" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %28 "main" %23 %26 OpExecutionMode %28 OriginUpperLeft -OpMemberDecorate %6 0 Offset 0 -OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %4 0 Offset 0 +OpMemberDecorate %5 0 Offset 0 +OpMemberDecorate %8 0 Offset 0 OpDecorate %11 NonWritable OpDecorate %11 DescriptorSet 0 OpDecorate %11 Binding 0 -OpDecorate %7 Block +OpDecorate %5 Block OpDecorate %15 DescriptorSet 0 OpDecorate %15 Binding 10 OpDecorate %16 Block @@ -26,79 +26,79 @@ OpDecorate %23 Flat OpDecorate %26 Location 0 OpDecorate %56 NonUniform %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 1 -%5 = OpTypeInt 32 0 -%6 = OpTypeStruct %5 -%7 = OpTypeStruct %5 -%9 = OpConstant %5 1 -%8 = OpTypeArray %7 %9 -%10 = OpTypeStruct %5 -%14 = OpConstant %5 10 -%13 = OpTypeArray %7 %14 +%3 = OpTypeInt 32 0 +%4 = OpTypeStruct %3 +%5 = OpTypeStruct %3 +%7 = OpConstant %3 1 +%6 = OpTypeArray %5 %7 +%8 = OpTypeStruct %3 +%10 = OpTypeInt 32 1 +%9 = OpConstant %10 1 +%14 = OpConstant %3 10 +%13 = OpTypeArray %5 %14 %12 = OpTypePointer StorageBuffer %13 %11 = OpVariable %12 StorageBuffer -%16 = OpTypeStruct %6 +%16 = OpTypeStruct %4 %17 = OpTypePointer Uniform %16 %15 = OpVariable %17 Uniform -%19 = OpTypePointer Function %5 -%20 = OpConstantNull %5 -%24 = OpTypePointer Input %5 +%19 = OpTypePointer Function %3 +%20 = OpConstantNull %3 +%24 = OpTypePointer Input %3 %23 = OpVariable %24 Input -%27 = OpTypePointer Output %5 +%27 = OpTypePointer Output %3 %26 = OpVariable %27 Output %29 = OpTypeFunction %2 -%30 = OpTypePointer Uniform %6 -%31 = OpConstant %5 0 -%33 = OpTypePointer StorageBuffer %8 -%35 = OpTypePointer Uniform %5 -%39 = OpTypePointer StorageBuffer %7 -%40 = OpTypePointer StorageBuffer %5 +%30 = OpTypePointer Uniform %4 +%31 = OpConstant %3 0 +%33 = OpTypePointer StorageBuffer %6 +%35 = OpTypePointer Uniform %3 +%39 = OpTypePointer StorageBuffer %5 +%40 = OpTypePointer StorageBuffer %3 %46 = OpTypeBool -%48 = OpConstantNull %5 -%57 = OpConstantNull %5 +%48 = OpConstantNull %3 +%57 = OpConstantNull %3 %28 = OpFunction %2 None %29 %21 = OpLabel %18 = OpVariable %19 Function %20 -%25 = OpLoad %5 %23 -%22 = OpCompositeConstruct %10 %25 +%25 = OpLoad %3 %23 +%22 = OpCompositeConstruct %8 %25 %32 = OpAccessChain %30 %15 %31 OpBranch %34 %34 = OpLabel %36 = OpAccessChain %35 %32 %31 -%37 = OpLoad %5 %36 -%38 = OpCompositeExtract %5 %22 0 +%37 = OpLoad %3 %36 +%38 = OpCompositeExtract %3 %22 0 OpStore %18 %31 %41 = OpAccessChain %40 %11 %31 %31 -%42 = OpLoad %5 %41 -%43 = OpLoad %5 %18 -%44 = OpIAdd %5 %43 %42 +%42 = OpLoad %3 %41 +%43 = OpLoad %3 %18 +%44 = OpIAdd %3 %43 %42 OpStore %18 %44 -%45 = OpULessThan %46 %37 %9 +%45 = OpULessThan %46 %37 %7 OpSelectionMerge %49 None OpBranchConditional %45 %50 %49 %50 = OpLabel %47 = OpAccessChain %40 %11 %37 %31 -%51 = OpLoad %5 %47 +%51 = OpLoad %3 %47 OpBranch %49 %49 = OpLabel -%52 = OpPhi %5 %48 %34 %51 %50 -%53 = OpLoad %5 %18 -%54 = OpIAdd %5 %53 %52 +%52 = OpPhi %3 %48 %34 %51 %50 +%53 = OpLoad %3 %18 +%54 = OpIAdd %3 %53 %52 OpStore %18 %54 -%55 = OpULessThan %46 %38 %9 +%55 = OpULessThan %46 %38 %7 OpSelectionMerge %58 None OpBranchConditional %55 %59 %58 %59 = OpLabel %56 = OpAccessChain %40 %11 %38 %31 -%60 = OpLoad %5 %56 +%60 = OpLoad %3 %56 OpBranch %58 %58 = OpLabel -%61 = OpPhi %5 %57 %49 %60 %59 -%62 = OpLoad %5 %18 -%63 = OpIAdd %5 %62 %61 +%61 = OpPhi %3 %57 %49 %60 %59 +%62 = OpLoad %3 %18 +%63 = OpIAdd %3 %62 %61 OpStore %18 %63 -%64 = OpLoad %5 %18 +%64 = OpLoad %3 %18 OpStore %26 %64 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 4b19d9b4f..30e77fdcd 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -8,20 +8,20 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %46 "main" %43 OpExecutionMode %46 LocalSize 64 1 1 -OpName %3 "NUM_PARTICLES" -OpMemberName %7 0 "pos" -OpMemberName %7 1 "vel" -OpName %7 "Particle" -OpMemberName %8 0 "deltaT" -OpMemberName %8 1 "rule1Distance" -OpMemberName %8 2 "rule2Distance" -OpMemberName %8 3 "rule3Distance" -OpMemberName %8 4 "rule1Scale" -OpMemberName %8 5 "rule2Scale" -OpMemberName %8 6 "rule3Scale" -OpName %8 "SimParams" -OpMemberName %10 0 "particles" -OpName %10 "Particles" +OpMemberName %6 0 "pos" +OpMemberName %6 1 "vel" +OpName %6 "Particle" +OpMemberName %7 0 "deltaT" +OpMemberName %7 1 "rule1Distance" +OpMemberName %7 2 "rule2Distance" +OpMemberName %7 3 "rule3Distance" +OpMemberName %7 4 "rule1Scale" +OpMemberName %7 5 "rule2Scale" +OpMemberName %7 6 "rule3Scale" +OpName %7 "SimParams" +OpMemberName %9 0 "particles" +OpName %9 "Particles" +OpName %12 "NUM_PARTICLES" OpName %13 "params" OpName %16 "particlesSrc" OpName %18 "particlesDst" @@ -37,17 +37,17 @@ OpName %37 "vel" OpName %39 "i" OpName %43 "global_invocation_id" OpName %46 "main" +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %6 1 Offset 8 OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %7 1 Offset 8 -OpMemberDecorate %8 0 Offset 0 -OpMemberDecorate %8 1 Offset 4 -OpMemberDecorate %8 2 Offset 8 -OpMemberDecorate %8 3 Offset 12 -OpMemberDecorate %8 4 Offset 16 -OpMemberDecorate %8 5 Offset 20 -OpMemberDecorate %8 6 Offset 24 -OpDecorate %9 ArrayStride 16 -OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %7 1 Offset 4 +OpMemberDecorate %7 2 Offset 8 +OpMemberDecorate %7 3 Offset 12 +OpMemberDecorate %7 4 Offset 16 +OpMemberDecorate %7 5 Offset 20 +OpMemberDecorate %7 6 Offset 24 +OpDecorate %8 ArrayStride 16 +OpMemberDecorate %9 0 Offset 0 OpDecorate %13 DescriptorSet 0 OpDecorate %13 Binding 0 OpDecorate %14 Block @@ -55,64 +55,64 @@ OpMemberDecorate %14 0 Offset 0 OpDecorate %16 NonWritable OpDecorate %16 DescriptorSet 0 OpDecorate %16 Binding 1 -OpDecorate %10 Block +OpDecorate %9 Block OpDecorate %18 DescriptorSet 0 OpDecorate %18 Binding 2 -OpDecorate %10 Block +OpDecorate %9 Block OpDecorate %43 BuiltIn GlobalInvocationId %2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpConstant %4 1500 -%6 = OpTypeFloat 32 -%5 = OpTypeVector %6 2 -%7 = OpTypeStruct %5 %5 -%8 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6 -%9 = OpTypeRuntimeArray %7 -%10 = OpTypeStruct %9 -%11 = OpTypeVector %4 3 -%12 = OpTypeInt 32 1 -%14 = OpTypeStruct %8 +%3 = OpTypeInt 32 0 +%5 = OpTypeFloat 32 +%4 = OpTypeVector %5 2 +%6 = OpTypeStruct %4 %4 +%7 = OpTypeStruct %5 %5 %5 %5 %5 %5 %5 +%8 = OpTypeRuntimeArray %6 +%9 = OpTypeStruct %8 +%10 = OpTypeVector %3 3 +%11 = OpTypeInt 32 1 +%12 = OpConstant %3 1500 +%14 = OpTypeStruct %7 %15 = OpTypePointer Uniform %14 %13 = OpVariable %15 Uniform -%17 = OpTypePointer StorageBuffer %10 +%17 = OpTypePointer StorageBuffer %9 %16 = OpVariable %17 StorageBuffer %18 = OpVariable %17 StorageBuffer -%20 = OpTypePointer Function %5 -%21 = OpConstantNull %5 -%23 = OpConstantNull %5 -%25 = OpConstantNull %5 -%27 = OpConstantNull %5 -%29 = OpConstantNull %5 -%31 = OpTypePointer Function %12 -%32 = OpConstantNull %12 -%34 = OpConstantNull %12 -%36 = OpConstantNull %5 -%38 = OpConstantNull %5 -%40 = OpTypePointer Function %4 -%41 = OpConstantNull %4 -%44 = OpTypePointer Input %11 +%20 = OpTypePointer Function %4 +%21 = OpConstantNull %4 +%23 = OpConstantNull %4 +%25 = OpConstantNull %4 +%27 = OpConstantNull %4 +%29 = OpConstantNull %4 +%31 = OpTypePointer Function %11 +%32 = OpConstantNull %11 +%34 = OpConstantNull %11 +%36 = OpConstantNull %4 +%38 = OpConstantNull %4 +%40 = OpTypePointer Function %3 +%41 = OpConstantNull %3 +%44 = OpTypePointer Input %10 %43 = OpVariable %44 Input %47 = OpTypeFunction %2 -%48 = OpTypePointer Uniform %8 -%49 = OpConstant %4 0 -%51 = OpConstant %6 0.0 -%52 = OpConstant %12 0 -%53 = OpConstant %12 1 -%54 = OpConstant %4 1 -%55 = OpConstant %6 0.1 -%56 = OpConstant %6 -1.0 -%57 = OpConstant %6 1.0 +%48 = OpTypePointer Uniform %7 +%49 = OpConstant %3 0 +%51 = OpConstant %5 0.0 +%52 = OpConstant %11 0 +%53 = OpConstant %11 1 +%54 = OpConstant %3 1 +%55 = OpConstant %5 0.1 +%56 = OpConstant %5 -1.0 +%57 = OpConstant %5 1.0 %60 = OpTypeBool -%64 = OpTypePointer StorageBuffer %9 -%65 = OpTypePointer StorageBuffer %7 -%66 = OpTypePointer StorageBuffer %5 -%95 = OpTypePointer Uniform %6 -%109 = OpConstant %4 2 -%123 = OpConstant %4 3 -%158 = OpConstant %4 4 -%164 = OpConstant %4 5 -%170 = OpConstant %4 6 -%187 = OpTypePointer Function %6 +%64 = OpTypePointer StorageBuffer %8 +%65 = OpTypePointer StorageBuffer %6 +%66 = OpTypePointer StorageBuffer %4 +%95 = OpTypePointer Uniform %5 +%109 = OpConstant %3 2 +%123 = OpConstant %3 3 +%158 = OpConstant %3 4 +%164 = OpConstant %3 5 +%170 = OpConstant %3 6 +%187 = OpTypePointer Function %5 %46 = OpFunction %2 None %47 %42 = OpLabel %39 = OpVariable %40 Function %41 @@ -125,28 +125,28 @@ OpDecorate %43 BuiltIn GlobalInvocationId %37 = OpVariable %20 Function %38 %30 = OpVariable %31 Function %32 %24 = OpVariable %20 Function %25 -%45 = OpLoad %11 %43 +%45 = OpLoad %10 %43 %50 = OpAccessChain %48 %13 %49 OpBranch %58 %58 = OpLabel -%59 = OpCompositeExtract %4 %45 0 -%61 = OpUGreaterThanEqual %60 %59 %3 +%59 = OpCompositeExtract %3 %45 0 +%61 = OpUGreaterThanEqual %60 %59 %12 OpSelectionMerge %62 None OpBranchConditional %61 %63 %62 %63 = OpLabel OpReturn %62 = OpLabel %67 = OpAccessChain %66 %16 %49 %59 %49 -%68 = OpLoad %5 %67 +%68 = OpLoad %4 %67 OpStore %19 %68 %69 = OpAccessChain %66 %16 %49 %59 %54 -%70 = OpLoad %5 %69 +%70 = OpLoad %4 %69 OpStore %22 %70 -%71 = OpCompositeConstruct %5 %51 %51 +%71 = OpCompositeConstruct %4 %51 %51 OpStore %24 %71 -%72 = OpCompositeConstruct %5 %51 %51 +%72 = OpCompositeConstruct %4 %51 %51 OpStore %26 %72 -%73 = OpCompositeConstruct %5 %51 %51 +%73 = OpCompositeConstruct %4 %51 %51 OpStore %28 %73 OpStore %30 %52 OpStore %33 %52 @@ -156,149 +156,149 @@ OpBranch %74 OpLoopMerge %75 %77 None OpBranch %76 %76 = OpLabel -%78 = OpLoad %4 %39 -%79 = OpUGreaterThanEqual %60 %78 %3 +%78 = OpLoad %3 %39 +%79 = OpUGreaterThanEqual %60 %78 %12 OpSelectionMerge %80 None OpBranchConditional %79 %81 %80 %81 = OpLabel OpBranch %75 %80 = OpLabel -%82 = OpLoad %4 %39 +%82 = OpLoad %3 %39 %83 = OpIEqual %60 %82 %59 OpSelectionMerge %84 None OpBranchConditional %83 %85 %84 %85 = OpLabel OpBranch %77 %84 = OpLabel -%86 = OpLoad %4 %39 +%86 = OpLoad %3 %39 %87 = OpAccessChain %66 %16 %49 %86 %49 -%88 = OpLoad %5 %87 +%88 = OpLoad %4 %87 OpStore %35 %88 -%89 = OpLoad %4 %39 +%89 = OpLoad %3 %39 %90 = OpAccessChain %66 %16 %49 %89 %54 -%91 = OpLoad %5 %90 +%91 = OpLoad %4 %90 OpStore %37 %91 -%92 = OpLoad %5 %35 -%93 = OpLoad %5 %19 -%94 = OpExtInst %6 %1 Distance %92 %93 +%92 = OpLoad %4 %35 +%93 = OpLoad %4 %19 +%94 = OpExtInst %5 %1 Distance %92 %93 %96 = OpAccessChain %95 %50 %54 -%97 = OpLoad %6 %96 +%97 = OpLoad %5 %96 %98 = OpFOrdLessThan %60 %94 %97 OpSelectionMerge %99 None OpBranchConditional %98 %100 %99 %100 = OpLabel -%101 = OpLoad %5 %24 -%102 = OpLoad %5 %35 -%103 = OpFAdd %5 %101 %102 +%101 = OpLoad %4 %24 +%102 = OpLoad %4 %35 +%103 = OpFAdd %4 %101 %102 OpStore %24 %103 -%104 = OpLoad %12 %30 -%105 = OpIAdd %12 %104 %53 +%104 = OpLoad %11 %30 +%105 = OpIAdd %11 %104 %53 OpStore %30 %105 OpBranch %99 %99 = OpLabel -%106 = OpLoad %5 %35 -%107 = OpLoad %5 %19 -%108 = OpExtInst %6 %1 Distance %106 %107 +%106 = OpLoad %4 %35 +%107 = OpLoad %4 %19 +%108 = OpExtInst %5 %1 Distance %106 %107 %110 = OpAccessChain %95 %50 %109 -%111 = OpLoad %6 %110 +%111 = OpLoad %5 %110 %112 = OpFOrdLessThan %60 %108 %111 OpSelectionMerge %113 None OpBranchConditional %112 %114 %113 %114 = OpLabel -%115 = OpLoad %5 %28 -%116 = OpLoad %5 %35 -%117 = OpLoad %5 %19 -%118 = OpFSub %5 %116 %117 -%119 = OpFSub %5 %115 %118 +%115 = OpLoad %4 %28 +%116 = OpLoad %4 %35 +%117 = OpLoad %4 %19 +%118 = OpFSub %4 %116 %117 +%119 = OpFSub %4 %115 %118 OpStore %28 %119 OpBranch %113 %113 = OpLabel -%120 = OpLoad %5 %35 -%121 = OpLoad %5 %19 -%122 = OpExtInst %6 %1 Distance %120 %121 +%120 = OpLoad %4 %35 +%121 = OpLoad %4 %19 +%122 = OpExtInst %5 %1 Distance %120 %121 %124 = OpAccessChain %95 %50 %123 -%125 = OpLoad %6 %124 +%125 = OpLoad %5 %124 %126 = OpFOrdLessThan %60 %122 %125 OpSelectionMerge %127 None OpBranchConditional %126 %128 %127 %128 = OpLabel -%129 = OpLoad %5 %26 -%130 = OpLoad %5 %37 -%131 = OpFAdd %5 %129 %130 +%129 = OpLoad %4 %26 +%130 = OpLoad %4 %37 +%131 = OpFAdd %4 %129 %130 OpStore %26 %131 -%132 = OpLoad %12 %33 -%133 = OpIAdd %12 %132 %53 +%132 = OpLoad %11 %33 +%133 = OpIAdd %11 %132 %53 OpStore %33 %133 OpBranch %127 %127 = OpLabel OpBranch %77 %77 = OpLabel -%134 = OpLoad %4 %39 -%135 = OpIAdd %4 %134 %54 +%134 = OpLoad %3 %39 +%135 = OpIAdd %3 %134 %54 OpStore %39 %135 OpBranch %74 %75 = OpLabel -%136 = OpLoad %12 %30 +%136 = OpLoad %11 %30 %137 = OpSGreaterThan %60 %136 %52 OpSelectionMerge %138 None OpBranchConditional %137 %139 %138 %139 = OpLabel -%140 = OpLoad %5 %24 -%141 = OpLoad %12 %30 -%142 = OpConvertSToF %6 %141 -%143 = OpCompositeConstruct %5 %142 %142 -%144 = OpFDiv %5 %140 %143 -%145 = OpLoad %5 %19 -%146 = OpFSub %5 %144 %145 +%140 = OpLoad %4 %24 +%141 = OpLoad %11 %30 +%142 = OpConvertSToF %5 %141 +%143 = OpCompositeConstruct %4 %142 %142 +%144 = OpFDiv %4 %140 %143 +%145 = OpLoad %4 %19 +%146 = OpFSub %4 %144 %145 OpStore %24 %146 OpBranch %138 %138 = OpLabel -%147 = OpLoad %12 %33 +%147 = OpLoad %11 %33 %148 = OpSGreaterThan %60 %147 %52 OpSelectionMerge %149 None OpBranchConditional %148 %150 %149 %150 = OpLabel -%151 = OpLoad %5 %26 -%152 = OpLoad %12 %33 -%153 = OpConvertSToF %6 %152 -%154 = OpCompositeConstruct %5 %153 %153 -%155 = OpFDiv %5 %151 %154 +%151 = OpLoad %4 %26 +%152 = OpLoad %11 %33 +%153 = OpConvertSToF %5 %152 +%154 = OpCompositeConstruct %4 %153 %153 +%155 = OpFDiv %4 %151 %154 OpStore %26 %155 OpBranch %149 %149 = OpLabel -%156 = OpLoad %5 %22 -%157 = OpLoad %5 %24 +%156 = OpLoad %4 %22 +%157 = OpLoad %4 %24 %159 = OpAccessChain %95 %50 %158 -%160 = OpLoad %6 %159 -%161 = OpVectorTimesScalar %5 %157 %160 -%162 = OpFAdd %5 %156 %161 -%163 = OpLoad %5 %28 +%160 = OpLoad %5 %159 +%161 = OpVectorTimesScalar %4 %157 %160 +%162 = OpFAdd %4 %156 %161 +%163 = OpLoad %4 %28 %165 = OpAccessChain %95 %50 %164 -%166 = OpLoad %6 %165 -%167 = OpVectorTimesScalar %5 %163 %166 -%168 = OpFAdd %5 %162 %167 -%169 = OpLoad %5 %26 +%166 = OpLoad %5 %165 +%167 = OpVectorTimesScalar %4 %163 %166 +%168 = OpFAdd %4 %162 %167 +%169 = OpLoad %4 %26 %171 = OpAccessChain %95 %50 %170 -%172 = OpLoad %6 %171 -%173 = OpVectorTimesScalar %5 %169 %172 -%174 = OpFAdd %5 %168 %173 +%172 = OpLoad %5 %171 +%173 = OpVectorTimesScalar %4 %169 %172 +%174 = OpFAdd %4 %168 %173 OpStore %22 %174 -%175 = OpLoad %5 %22 -%176 = OpExtInst %5 %1 Normalize %175 -%177 = OpLoad %5 %22 -%178 = OpExtInst %6 %1 Length %177 -%179 = OpExtInst %6 %1 FClamp %178 %51 %55 -%180 = OpVectorTimesScalar %5 %176 %179 +%175 = OpLoad %4 %22 +%176 = OpExtInst %4 %1 Normalize %175 +%177 = OpLoad %4 %22 +%178 = OpExtInst %5 %1 Length %177 +%179 = OpExtInst %5 %1 FClamp %178 %51 %55 +%180 = OpVectorTimesScalar %4 %176 %179 OpStore %22 %180 -%181 = OpLoad %5 %19 -%182 = OpLoad %5 %22 +%181 = OpLoad %4 %19 +%182 = OpLoad %4 %22 %183 = OpAccessChain %95 %50 %49 -%184 = OpLoad %6 %183 -%185 = OpVectorTimesScalar %5 %182 %184 -%186 = OpFAdd %5 %181 %185 +%184 = OpLoad %5 %183 +%185 = OpVectorTimesScalar %4 %182 %184 +%186 = OpFAdd %4 %181 %185 OpStore %19 %186 %188 = OpAccessChain %187 %19 %49 -%189 = OpLoad %6 %188 +%189 = OpLoad %5 %188 %190 = OpFOrdLessThan %60 %189 %56 OpSelectionMerge %191 None OpBranchConditional %190 %192 %191 @@ -308,7 +308,7 @@ OpStore %193 %57 OpBranch %191 %191 = OpLabel %194 = OpAccessChain %187 %19 %49 -%195 = OpLoad %6 %194 +%195 = OpLoad %5 %194 %196 = OpFOrdGreaterThan %60 %195 %57 OpSelectionMerge %197 None OpBranchConditional %196 %198 %197 @@ -318,7 +318,7 @@ OpStore %199 %56 OpBranch %197 %197 = OpLabel %200 = OpAccessChain %187 %19 %54 -%201 = OpLoad %6 %200 +%201 = OpLoad %5 %200 %202 = OpFOrdLessThan %60 %201 %56 OpSelectionMerge %203 None OpBranchConditional %202 %204 %203 @@ -328,7 +328,7 @@ OpStore %205 %57 OpBranch %203 %203 = OpLabel %206 = OpAccessChain %187 %19 %54 -%207 = OpLoad %6 %206 +%207 = OpLoad %5 %206 %208 = OpFOrdGreaterThan %60 %207 %57 OpSelectionMerge %209 None OpBranchConditional %208 %210 %209 @@ -337,10 +337,10 @@ OpBranchConditional %208 %210 %209 OpStore %211 %56 OpBranch %209 %209 = OpLabel -%212 = OpLoad %5 %19 +%212 = OpLoad %4 %19 %213 = OpAccessChain %66 %18 %49 %59 %49 OpStore %213 %212 -%214 = OpLoad %5 %22 +%214 = OpLoad %4 %22 %215 = OpAccessChain %66 %18 %49 %59 %54 OpStore %215 %214 OpReturn diff --git a/tests/out/spv/bounds-check-restrict.spvasm b/tests/out/spv/bounds-check-restrict.spvasm index f6ea5dcde..8b13b4480 100644 --- a/tests/out/spv/bounds-check-restrict.spvasm +++ b/tests/out/spv/bounds-check-restrict.spvasm @@ -7,222 +7,222 @@ OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpDecorate %6 ArrayStride 4 -OpDecorate %11 ArrayStride 4 -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 48 -OpMemberDecorate %12 2 Offset 64 -OpMemberDecorate %12 2 ColMajor -OpMemberDecorate %12 2 MatrixStride 16 -OpMemberDecorate %12 3 Offset 112 +OpDecorate %4 ArrayStride 4 +OpDecorate %9 ArrayStride 4 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 48 +OpMemberDecorate %10 2 Offset 64 +OpMemberDecorate %10 2 ColMajor +OpMemberDecorate %10 2 MatrixStride 16 +OpMemberDecorate %10 3 Offset 112 OpDecorate %13 DescriptorSet 0 OpDecorate %13 Binding 0 -OpDecorate %12 Block +OpDecorate %10 Block %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 10 -%5 = OpTypeFloat 32 -%8 = OpTypeInt 32 0 -%7 = OpConstant %8 10 -%6 = OpTypeArray %5 %7 -%9 = OpTypeVector %5 4 -%10 = OpTypeMatrix %9 3 -%11 = OpTypeRuntimeArray %5 -%12 = OpTypeStruct %6 %9 %10 %11 -%14 = OpTypePointer StorageBuffer %12 +%3 = OpTypeFloat 32 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 10 +%4 = OpTypeArray %3 %5 +%7 = OpTypeVector %3 4 +%8 = OpTypeMatrix %7 3 +%9 = OpTypeRuntimeArray %3 +%10 = OpTypeStruct %4 %7 %8 %9 +%11 = OpTypeInt 32 1 +%12 = OpConstant %11 10 +%14 = OpTypePointer StorageBuffer %10 %13 = OpVariable %14 StorageBuffer -%18 = OpTypeFunction %5 %4 -%20 = OpTypePointer StorageBuffer %6 -%21 = OpTypePointer StorageBuffer %5 -%22 = OpConstant %8 9 -%24 = OpConstant %8 0 -%31 = OpTypePointer StorageBuffer %11 -%33 = OpConstant %8 1 -%36 = OpConstant %8 3 -%43 = OpTypePointer StorageBuffer %9 -%44 = OpTypePointer StorageBuffer %5 -%52 = OpTypeFunction %5 %9 %4 -%59 = OpTypeFunction %9 %4 -%61 = OpTypePointer StorageBuffer %10 -%62 = OpTypePointer StorageBuffer %9 -%63 = OpConstant %8 2 -%71 = OpTypeFunction %5 %4 %4 -%80 = OpConstant %5 100.0 -%92 = OpTypeFunction %5 -%106 = OpTypeFunction %2 %4 %5 -%130 = OpTypeFunction %2 %4 %9 -%139 = OpTypeFunction %2 %4 %4 %5 -%159 = OpTypeFunction %2 %5 -%17 = OpFunction %5 None %18 -%16 = OpFunctionParameter %4 +%18 = OpTypeFunction %3 %11 +%20 = OpTypePointer StorageBuffer %4 +%21 = OpTypePointer StorageBuffer %3 +%22 = OpConstant %6 9 +%24 = OpConstant %6 0 +%31 = OpTypePointer StorageBuffer %9 +%33 = OpConstant %6 1 +%36 = OpConstant %6 3 +%43 = OpTypePointer StorageBuffer %7 +%44 = OpTypePointer StorageBuffer %3 +%52 = OpTypeFunction %3 %7 %11 +%59 = OpTypeFunction %7 %11 +%61 = OpTypePointer StorageBuffer %8 +%62 = OpTypePointer StorageBuffer %7 +%63 = OpConstant %6 2 +%71 = OpTypeFunction %3 %11 %11 +%80 = OpConstant %3 100.0 +%92 = OpTypeFunction %3 +%106 = OpTypeFunction %2 %11 %3 +%130 = OpTypeFunction %2 %11 %7 +%139 = OpTypeFunction %2 %11 %11 %3 +%159 = OpTypeFunction %2 %3 +%17 = OpFunction %3 None %18 +%16 = OpFunctionParameter %11 %15 = OpLabel OpBranch %19 %19 = OpLabel -%23 = OpExtInst %8 %1 UMin %16 %22 +%23 = OpExtInst %6 %1 UMin %16 %22 %25 = OpAccessChain %21 %13 %24 %23 -%26 = OpLoad %5 %25 +%26 = OpLoad %3 %25 OpReturnValue %26 OpFunctionEnd -%29 = OpFunction %5 None %18 -%28 = OpFunctionParameter %4 +%29 = OpFunction %3 None %18 +%28 = OpFunctionParameter %11 %27 = OpLabel OpBranch %30 %30 = OpLabel -%32 = OpArrayLength %8 %13 3 -%34 = OpISub %8 %32 %33 -%35 = OpExtInst %8 %1 UMin %28 %34 +%32 = OpArrayLength %6 %13 3 +%34 = OpISub %6 %32 %33 +%35 = OpExtInst %6 %1 UMin %28 %34 %37 = OpAccessChain %21 %13 %36 %35 -%38 = OpLoad %5 %37 +%38 = OpLoad %3 %37 OpReturnValue %38 OpFunctionEnd -%41 = OpFunction %5 None %18 -%40 = OpFunctionParameter %4 +%41 = OpFunction %3 None %18 +%40 = OpFunctionParameter %11 %39 = OpLabel OpBranch %42 %42 = OpLabel -%45 = OpExtInst %8 %1 UMin %40 %36 +%45 = OpExtInst %6 %1 UMin %40 %36 %46 = OpAccessChain %44 %13 %33 %45 -%47 = OpLoad %5 %46 +%47 = OpLoad %3 %46 OpReturnValue %47 OpFunctionEnd -%51 = OpFunction %5 None %52 -%49 = OpFunctionParameter %9 -%50 = OpFunctionParameter %4 +%51 = OpFunction %3 None %52 +%49 = OpFunctionParameter %7 +%50 = OpFunctionParameter %11 %48 = OpLabel OpBranch %53 %53 = OpLabel -%54 = OpExtInst %8 %1 UMin %50 %36 -%55 = OpVectorExtractDynamic %5 %49 %54 +%54 = OpExtInst %6 %1 UMin %50 %36 +%55 = OpVectorExtractDynamic %3 %49 %54 OpReturnValue %55 OpFunctionEnd -%58 = OpFunction %9 None %59 -%57 = OpFunctionParameter %4 +%58 = OpFunction %7 None %59 +%57 = OpFunctionParameter %11 %56 = OpLabel OpBranch %60 %60 = OpLabel -%64 = OpExtInst %8 %1 UMin %57 %63 +%64 = OpExtInst %6 %1 UMin %57 %63 %65 = OpAccessChain %62 %13 %63 %64 -%66 = OpLoad %9 %65 +%66 = OpLoad %7 %65 OpReturnValue %66 OpFunctionEnd -%70 = OpFunction %5 None %71 -%68 = OpFunctionParameter %4 -%69 = OpFunctionParameter %4 +%70 = OpFunction %3 None %71 +%68 = OpFunctionParameter %11 +%69 = OpFunctionParameter %11 %67 = OpLabel OpBranch %72 %72 = OpLabel -%73 = OpExtInst %8 %1 UMin %69 %36 -%74 = OpExtInst %8 %1 UMin %68 %63 +%73 = OpExtInst %6 %1 UMin %69 %36 +%74 = OpExtInst %6 %1 UMin %68 %63 %75 = OpAccessChain %44 %13 %63 %74 %73 -%76 = OpLoad %5 %75 +%76 = OpLoad %3 %75 OpReturnValue %76 OpFunctionEnd -%79 = OpFunction %5 None %18 -%78 = OpFunctionParameter %4 +%79 = OpFunction %3 None %18 +%78 = OpFunctionParameter %11 %77 = OpLabel OpBranch %81 %81 = OpLabel -%82 = OpConvertSToF %5 %78 -%83 = OpFDiv %5 %82 %80 -%84 = OpExtInst %5 %1 Sin %83 -%85 = OpFMul %5 %84 %80 -%86 = OpConvertFToS %4 %85 -%87 = OpExtInst %8 %1 UMin %86 %22 +%82 = OpConvertSToF %3 %78 +%83 = OpFDiv %3 %82 %80 +%84 = OpExtInst %3 %1 Sin %83 +%85 = OpFMul %3 %84 %80 +%86 = OpConvertFToS %11 %85 +%87 = OpExtInst %6 %1 UMin %86 %22 %88 = OpAccessChain %21 %13 %24 %87 -%89 = OpLoad %5 %88 +%89 = OpLoad %3 %88 OpReturnValue %89 OpFunctionEnd -%91 = OpFunction %5 None %92 +%91 = OpFunction %3 None %92 %90 = OpLabel OpBranch %93 %93 = OpLabel %94 = OpAccessChain %21 %13 %24 %22 -%95 = OpLoad %5 %94 +%95 = OpLoad %3 %94 %96 = OpAccessChain %44 %13 %33 %36 -%97 = OpLoad %5 %96 -%98 = OpFAdd %5 %95 %97 +%97 = OpLoad %3 %96 +%98 = OpFAdd %3 %95 %97 %99 = OpAccessChain %44 %13 %63 %63 %36 -%100 = OpLoad %5 %99 -%101 = OpFAdd %5 %98 %100 +%100 = OpLoad %3 %99 +%101 = OpFAdd %3 %98 %100 OpReturnValue %101 OpFunctionEnd %105 = OpFunction %2 None %106 -%103 = OpFunctionParameter %4 -%104 = OpFunctionParameter %5 +%103 = OpFunctionParameter %11 +%104 = OpFunctionParameter %3 %102 = OpLabel OpBranch %107 %107 = OpLabel -%108 = OpExtInst %8 %1 UMin %103 %22 +%108 = OpExtInst %6 %1 UMin %103 %22 %109 = OpAccessChain %21 %13 %24 %108 OpStore %109 %104 OpReturn OpFunctionEnd %113 = OpFunction %2 None %106 -%111 = OpFunctionParameter %4 -%112 = OpFunctionParameter %5 +%111 = OpFunctionParameter %11 +%112 = OpFunctionParameter %3 %110 = OpLabel OpBranch %114 %114 = OpLabel -%115 = OpArrayLength %8 %13 3 -%116 = OpISub %8 %115 %33 -%117 = OpExtInst %8 %1 UMin %111 %116 +%115 = OpArrayLength %6 %13 3 +%116 = OpISub %6 %115 %33 +%117 = OpExtInst %6 %1 UMin %111 %116 %118 = OpAccessChain %21 %13 %36 %117 OpStore %118 %112 OpReturn OpFunctionEnd %122 = OpFunction %2 None %106 -%120 = OpFunctionParameter %4 -%121 = OpFunctionParameter %5 +%120 = OpFunctionParameter %11 +%121 = OpFunctionParameter %3 %119 = OpLabel OpBranch %123 %123 = OpLabel -%124 = OpExtInst %8 %1 UMin %120 %36 +%124 = OpExtInst %6 %1 UMin %120 %36 %125 = OpAccessChain %44 %13 %33 %124 OpStore %125 %121 OpReturn OpFunctionEnd %129 = OpFunction %2 None %130 -%127 = OpFunctionParameter %4 -%128 = OpFunctionParameter %9 +%127 = OpFunctionParameter %11 +%128 = OpFunctionParameter %7 %126 = OpLabel OpBranch %131 %131 = OpLabel -%132 = OpExtInst %8 %1 UMin %127 %63 +%132 = OpExtInst %6 %1 UMin %127 %63 %133 = OpAccessChain %62 %13 %63 %132 OpStore %133 %128 OpReturn OpFunctionEnd %138 = OpFunction %2 None %139 -%135 = OpFunctionParameter %4 -%136 = OpFunctionParameter %4 -%137 = OpFunctionParameter %5 +%135 = OpFunctionParameter %11 +%136 = OpFunctionParameter %11 +%137 = OpFunctionParameter %3 %134 = OpLabel OpBranch %140 %140 = OpLabel -%141 = OpExtInst %8 %1 UMin %136 %36 -%142 = OpExtInst %8 %1 UMin %135 %63 +%141 = OpExtInst %6 %1 UMin %136 %36 +%142 = OpExtInst %6 %1 UMin %135 %63 %143 = OpAccessChain %44 %13 %63 %142 %141 OpStore %143 %137 OpReturn OpFunctionEnd %147 = OpFunction %2 None %106 -%145 = OpFunctionParameter %4 -%146 = OpFunctionParameter %5 +%145 = OpFunctionParameter %11 +%146 = OpFunctionParameter %3 %144 = OpLabel OpBranch %148 %148 = OpLabel -%149 = OpConvertSToF %5 %145 -%150 = OpFDiv %5 %149 %80 -%151 = OpExtInst %5 %1 Sin %150 -%152 = OpFMul %5 %151 %80 -%153 = OpConvertFToS %4 %152 -%154 = OpExtInst %8 %1 UMin %153 %22 +%149 = OpConvertSToF %3 %145 +%150 = OpFDiv %3 %149 %80 +%151 = OpExtInst %3 %1 Sin %150 +%152 = OpFMul %3 %151 %80 +%153 = OpConvertFToS %11 %152 +%154 = OpExtInst %6 %1 UMin %153 %22 %155 = OpAccessChain %21 %13 %24 %154 OpStore %155 %146 OpReturn OpFunctionEnd %158 = OpFunction %2 None %159 -%157 = OpFunctionParameter %5 +%157 = OpFunctionParameter %3 %156 = OpLabel OpBranch %160 %160 = OpLabel diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index c18b02063..e5fcdce2f 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -7,96 +7,96 @@ OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpDecorate %6 ArrayStride 4 -OpDecorate %11 ArrayStride 4 -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 48 -OpMemberDecorate %12 2 Offset 64 -OpMemberDecorate %12 2 ColMajor -OpMemberDecorate %12 2 MatrixStride 16 -OpMemberDecorate %12 3 Offset 112 +OpDecorate %4 ArrayStride 4 +OpDecorate %9 ArrayStride 4 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 48 +OpMemberDecorate %10 2 Offset 64 +OpMemberDecorate %10 2 ColMajor +OpMemberDecorate %10 2 MatrixStride 16 +OpMemberDecorate %10 3 Offset 112 OpDecorate %13 DescriptorSet 0 OpDecorate %13 Binding 0 -OpDecorate %12 Block +OpDecorate %10 Block %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 10 -%5 = OpTypeFloat 32 -%8 = OpTypeInt 32 0 -%7 = OpConstant %8 10 -%6 = OpTypeArray %5 %7 -%9 = OpTypeVector %5 4 -%10 = OpTypeMatrix %9 3 -%11 = OpTypeRuntimeArray %5 -%12 = OpTypeStruct %6 %9 %10 %11 -%14 = OpTypePointer StorageBuffer %12 +%3 = OpTypeFloat 32 +%6 = OpTypeInt 32 0 +%5 = OpConstant %6 10 +%4 = OpTypeArray %3 %5 +%7 = OpTypeVector %3 4 +%8 = OpTypeMatrix %7 3 +%9 = OpTypeRuntimeArray %3 +%10 = OpTypeStruct %4 %7 %8 %9 +%11 = OpTypeInt 32 1 +%12 = OpConstant %11 10 +%14 = OpTypePointer StorageBuffer %10 %13 = OpVariable %14 StorageBuffer -%18 = OpTypeFunction %5 %4 -%20 = OpTypePointer StorageBuffer %6 -%21 = OpTypePointer StorageBuffer %5 +%18 = OpTypeFunction %3 %11 +%20 = OpTypePointer StorageBuffer %4 +%21 = OpTypePointer StorageBuffer %3 %23 = OpTypeBool -%24 = OpConstant %8 0 -%26 = OpConstantNull %5 -%35 = OpTypePointer StorageBuffer %11 -%38 = OpConstant %8 3 -%40 = OpConstantNull %5 -%49 = OpTypePointer StorageBuffer %9 -%50 = OpTypePointer StorageBuffer %5 -%51 = OpConstant %8 4 -%53 = OpConstant %8 1 -%55 = OpConstantNull %5 -%64 = OpTypeFunction %5 %9 %4 -%67 = OpConstantNull %5 -%75 = OpTypeFunction %9 %4 -%77 = OpTypePointer StorageBuffer %10 -%78 = OpTypePointer StorageBuffer %9 -%80 = OpConstant %8 2 -%82 = OpConstantNull %9 -%91 = OpTypeFunction %5 %4 %4 -%97 = OpConstantNull %5 -%105 = OpConstant %5 100.0 -%114 = OpConstantNull %5 -%121 = OpTypeFunction %5 -%123 = OpConstant %8 9 -%136 = OpTypeFunction %2 %4 %5 -%165 = OpTypeFunction %2 %4 %9 -%176 = OpTypeFunction %2 %4 %4 %5 -%201 = OpTypeFunction %2 %5 -%17 = OpFunction %5 None %18 -%16 = OpFunctionParameter %4 +%24 = OpConstant %6 0 +%26 = OpConstantNull %3 +%35 = OpTypePointer StorageBuffer %9 +%38 = OpConstant %6 3 +%40 = OpConstantNull %3 +%49 = OpTypePointer StorageBuffer %7 +%50 = OpTypePointer StorageBuffer %3 +%51 = OpConstant %6 4 +%53 = OpConstant %6 1 +%55 = OpConstantNull %3 +%64 = OpTypeFunction %3 %7 %11 +%67 = OpConstantNull %3 +%75 = OpTypeFunction %7 %11 +%77 = OpTypePointer StorageBuffer %8 +%78 = OpTypePointer StorageBuffer %7 +%80 = OpConstant %6 2 +%82 = OpConstantNull %7 +%91 = OpTypeFunction %3 %11 %11 +%97 = OpConstantNull %3 +%105 = OpConstant %3 100.0 +%114 = OpConstantNull %3 +%121 = OpTypeFunction %3 +%123 = OpConstant %6 9 +%136 = OpTypeFunction %2 %11 %3 +%165 = OpTypeFunction %2 %11 %7 +%176 = OpTypeFunction %2 %11 %11 %3 +%201 = OpTypeFunction %2 %3 +%17 = OpFunction %3 None %18 +%16 = OpFunctionParameter %11 %15 = OpLabel OpBranch %19 %19 = OpLabel -%22 = OpULessThan %23 %16 %7 +%22 = OpULessThan %23 %16 %5 OpSelectionMerge %27 None OpBranchConditional %22 %28 %27 %28 = OpLabel %25 = OpAccessChain %21 %13 %24 %16 -%29 = OpLoad %5 %25 +%29 = OpLoad %3 %25 OpBranch %27 %27 = OpLabel -%30 = OpPhi %5 %26 %19 %29 %28 +%30 = OpPhi %3 %26 %19 %29 %28 OpReturnValue %30 OpFunctionEnd -%33 = OpFunction %5 None %18 -%32 = OpFunctionParameter %4 +%33 = OpFunction %3 None %18 +%32 = OpFunctionParameter %11 %31 = OpLabel OpBranch %34 %34 = OpLabel -%36 = OpArrayLength %8 %13 3 +%36 = OpArrayLength %6 %13 3 %37 = OpULessThan %23 %32 %36 OpSelectionMerge %41 None OpBranchConditional %37 %42 %41 %42 = OpLabel %39 = OpAccessChain %21 %13 %38 %32 -%43 = OpLoad %5 %39 +%43 = OpLoad %3 %39 OpBranch %41 %41 = OpLabel -%44 = OpPhi %5 %40 %34 %43 %42 +%44 = OpPhi %3 %40 %34 %43 %42 OpReturnValue %44 OpFunctionEnd -%47 = OpFunction %5 None %18 -%46 = OpFunctionParameter %4 +%47 = OpFunction %3 None %18 +%46 = OpFunctionParameter %11 %45 = OpLabel OpBranch %48 %48 = OpLabel @@ -105,15 +105,15 @@ OpSelectionMerge %56 None OpBranchConditional %52 %57 %56 %57 = OpLabel %54 = OpAccessChain %50 %13 %53 %46 -%58 = OpLoad %5 %54 +%58 = OpLoad %3 %54 OpBranch %56 %56 = OpLabel -%59 = OpPhi %5 %55 %48 %58 %57 +%59 = OpPhi %3 %55 %48 %58 %57 OpReturnValue %59 OpFunctionEnd -%63 = OpFunction %5 None %64 -%61 = OpFunctionParameter %9 -%62 = OpFunctionParameter %4 +%63 = OpFunction %3 None %64 +%61 = OpFunctionParameter %7 +%62 = OpFunctionParameter %11 %60 = OpLabel OpBranch %65 %65 = OpLabel @@ -121,14 +121,14 @@ OpBranch %65 OpSelectionMerge %68 None OpBranchConditional %66 %69 %68 %69 = OpLabel -%70 = OpVectorExtractDynamic %5 %61 %62 +%70 = OpVectorExtractDynamic %3 %61 %62 OpBranch %68 %68 = OpLabel -%71 = OpPhi %5 %67 %65 %70 %69 +%71 = OpPhi %3 %67 %65 %70 %69 OpReturnValue %71 OpFunctionEnd -%74 = OpFunction %9 None %75 -%73 = OpFunctionParameter %4 +%74 = OpFunction %7 None %75 +%73 = OpFunctionParameter %11 %72 = OpLabel OpBranch %76 %76 = OpLabel @@ -137,15 +137,15 @@ OpSelectionMerge %83 None OpBranchConditional %79 %84 %83 %84 = OpLabel %81 = OpAccessChain %78 %13 %80 %73 -%85 = OpLoad %9 %81 +%85 = OpLoad %7 %81 OpBranch %83 %83 = OpLabel -%86 = OpPhi %9 %82 %76 %85 %84 +%86 = OpPhi %7 %82 %76 %85 %84 OpReturnValue %86 OpFunctionEnd -%90 = OpFunction %5 None %91 -%88 = OpFunctionParameter %4 -%89 = OpFunctionParameter %4 +%90 = OpFunction %3 None %91 +%88 = OpFunctionParameter %11 +%89 = OpFunctionParameter %11 %87 = OpLabel OpBranch %92 %92 = OpLabel @@ -156,54 +156,54 @@ OpSelectionMerge %98 None OpBranchConditional %95 %99 %98 %99 = OpLabel %96 = OpAccessChain %50 %13 %80 %88 %89 -%100 = OpLoad %5 %96 +%100 = OpLoad %3 %96 OpBranch %98 %98 = OpLabel -%101 = OpPhi %5 %97 %92 %100 %99 +%101 = OpPhi %3 %97 %92 %100 %99 OpReturnValue %101 OpFunctionEnd -%104 = OpFunction %5 None %18 -%103 = OpFunctionParameter %4 +%104 = OpFunction %3 None %18 +%103 = OpFunctionParameter %11 %102 = OpLabel OpBranch %106 %106 = OpLabel -%107 = OpConvertSToF %5 %103 -%108 = OpFDiv %5 %107 %105 -%109 = OpExtInst %5 %1 Sin %108 -%110 = OpFMul %5 %109 %105 -%111 = OpConvertFToS %4 %110 -%112 = OpULessThan %23 %111 %7 +%107 = OpConvertSToF %3 %103 +%108 = OpFDiv %3 %107 %105 +%109 = OpExtInst %3 %1 Sin %108 +%110 = OpFMul %3 %109 %105 +%111 = OpConvertFToS %11 %110 +%112 = OpULessThan %23 %111 %5 OpSelectionMerge %115 None OpBranchConditional %112 %116 %115 %116 = OpLabel %113 = OpAccessChain %21 %13 %24 %111 -%117 = OpLoad %5 %113 +%117 = OpLoad %3 %113 OpBranch %115 %115 = OpLabel -%118 = OpPhi %5 %114 %106 %117 %116 +%118 = OpPhi %3 %114 %106 %117 %116 OpReturnValue %118 OpFunctionEnd -%120 = OpFunction %5 None %121 +%120 = OpFunction %3 None %121 %119 = OpLabel OpBranch %122 %122 = OpLabel %124 = OpAccessChain %21 %13 %24 %123 -%125 = OpLoad %5 %124 +%125 = OpLoad %3 %124 %126 = OpAccessChain %50 %13 %53 %38 -%127 = OpLoad %5 %126 -%128 = OpFAdd %5 %125 %127 +%127 = OpLoad %3 %126 +%128 = OpFAdd %3 %125 %127 %129 = OpAccessChain %50 %13 %80 %80 %38 -%130 = OpLoad %5 %129 -%131 = OpFAdd %5 %128 %130 +%130 = OpLoad %3 %129 +%131 = OpFAdd %3 %128 %130 OpReturnValue %131 OpFunctionEnd %135 = OpFunction %2 None %136 -%133 = OpFunctionParameter %4 -%134 = OpFunctionParameter %5 +%133 = OpFunctionParameter %11 +%134 = OpFunctionParameter %3 %132 = OpLabel OpBranch %137 %137 = OpLabel -%138 = OpULessThan %23 %133 %7 +%138 = OpULessThan %23 %133 %5 OpSelectionMerge %140 None OpBranchConditional %138 %141 %140 %141 = OpLabel @@ -214,12 +214,12 @@ OpBranch %140 OpReturn OpFunctionEnd %145 = OpFunction %2 None %136 -%143 = OpFunctionParameter %4 -%144 = OpFunctionParameter %5 +%143 = OpFunctionParameter %11 +%144 = OpFunctionParameter %3 %142 = OpLabel OpBranch %146 %146 = OpLabel -%147 = OpArrayLength %8 %13 3 +%147 = OpArrayLength %6 %13 3 %148 = OpULessThan %23 %143 %147 OpSelectionMerge %150 None OpBranchConditional %148 %151 %150 @@ -231,8 +231,8 @@ OpBranch %150 OpReturn OpFunctionEnd %155 = OpFunction %2 None %136 -%153 = OpFunctionParameter %4 -%154 = OpFunctionParameter %5 +%153 = OpFunctionParameter %11 +%154 = OpFunctionParameter %3 %152 = OpLabel OpBranch %156 %156 = OpLabel @@ -247,8 +247,8 @@ OpBranch %159 OpReturn OpFunctionEnd %164 = OpFunction %2 None %165 -%162 = OpFunctionParameter %4 -%163 = OpFunctionParameter %9 +%162 = OpFunctionParameter %11 +%163 = OpFunctionParameter %7 %161 = OpLabel OpBranch %166 %166 = OpLabel @@ -263,9 +263,9 @@ OpBranch %169 OpReturn OpFunctionEnd %175 = OpFunction %2 None %176 -%172 = OpFunctionParameter %4 -%173 = OpFunctionParameter %4 -%174 = OpFunctionParameter %5 +%172 = OpFunctionParameter %11 +%173 = OpFunctionParameter %11 +%174 = OpFunctionParameter %3 %171 = OpLabel OpBranch %177 %177 = OpLabel @@ -282,17 +282,17 @@ OpBranch %182 OpReturn OpFunctionEnd %187 = OpFunction %2 None %136 -%185 = OpFunctionParameter %4 -%186 = OpFunctionParameter %5 +%185 = OpFunctionParameter %11 +%186 = OpFunctionParameter %3 %184 = OpLabel OpBranch %188 %188 = OpLabel -%189 = OpConvertSToF %5 %185 -%190 = OpFDiv %5 %189 %105 -%191 = OpExtInst %5 %1 Sin %190 -%192 = OpFMul %5 %191 %105 -%193 = OpConvertFToS %4 %192 -%194 = OpULessThan %23 %193 %7 +%189 = OpConvertSToF %3 %185 +%190 = OpFDiv %3 %189 %105 +%191 = OpExtInst %3 %1 Sin %190 +%192 = OpFMul %3 %191 %105 +%193 = OpConvertFToS %11 %192 +%194 = OpULessThan %23 %193 %5 OpSelectionMerge %196 None OpBranchConditional %194 %197 %196 %197 = OpLabel @@ -303,7 +303,7 @@ OpBranch %196 OpReturn OpFunctionEnd %200 = OpFunction %2 None %201 -%199 = OpFunctionParameter %5 +%199 = OpFunctionParameter %3 %198 = OpLabel OpBranch %202 %202 = OpLabel diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index f50b80696..6e7e2958c 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,22 +1,22 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 180 +; Bound: 179 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %103 "main" %123 +OpEntryPoint GLCompute %103 "main" %122 OpExecutionMode %103 LocalSize 1 1 1 -OpDecorate %11 ArrayStride 4 -OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 1 Offset 12 -OpDecorate %15 ArrayStride 8 -OpDecorate %17 ArrayStride 16 +OpDecorate %5 ArrayStride 4 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 12 +OpDecorate %11 ArrayStride 8 +OpDecorate %13 ArrayStride 16 +OpDecorate %17 ArrayStride 32 +OpDecorate %19 ArrayStride 64 OpDecorate %21 ArrayStride 32 -OpDecorate %23 ArrayStride 64 -OpDecorate %25 ArrayStride 32 -OpDecorate %26 ArrayStride 64 +OpDecorate %22 ArrayStride 64 OpDecorate %32 DescriptorSet 0 OpDecorate %32 Binding 1 OpDecorate %33 Block @@ -48,111 +48,110 @@ OpDecorate %50 DescriptorSet 0 OpDecorate %50 Binding 7 OpDecorate %51 Block OpMemberDecorate %51 0 Offset 0 -OpDecorate %123 BuiltIn LocalInvocationId +OpDecorate %122 BuiltIn LocalInvocationId %2 = OpTypeVoid -%4 = OpTypeBool -%3 = OpConstantTrue %4 -%6 = OpTypeInt 32 0 -%5 = OpConstant %6 10 -%8 = OpTypeInt 32 1 -%7 = OpConstant %8 20 -%9 = OpConstant %8 2 -%10 = OpTypeFloat 32 -%11 = OpTypeArray %10 %5 -%12 = OpTypeVector %10 3 -%13 = OpTypeStruct %12 %10 -%14 = OpTypeVector %10 2 -%15 = OpTypeRuntimeArray %14 -%16 = OpTypeVector %10 4 -%18 = OpConstant %6 20 +%3 = OpTypeBool +%4 = OpTypeFloat 32 +%7 = OpTypeInt 32 0 +%6 = OpConstant %7 10 +%5 = OpTypeArray %4 %6 +%8 = OpTypeVector %4 3 +%9 = OpTypeStruct %8 %4 +%10 = OpTypeVector %4 2 +%11 = OpTypeRuntimeArray %10 +%12 = OpTypeVector %4 4 +%14 = OpConstant %7 20 +%13 = OpTypeArray %12 %14 +%15 = OpTypeMatrix %10 3 +%16 = OpTypeMatrix %12 2 +%18 = OpConstant %7 2 %17 = OpTypeArray %16 %18 -%19 = OpTypeMatrix %14 3 -%20 = OpTypeMatrix %16 2 -%22 = OpConstant %6 2 -%21 = OpTypeArray %20 %22 -%23 = OpTypeArray %21 %22 -%24 = OpTypeMatrix %14 4 -%25 = OpTypeArray %24 %22 -%26 = OpTypeArray %25 %22 -%27 = OpTypeMatrix %12 3 -%29 = OpTypePointer Workgroup %11 +%19 = OpTypeArray %17 %18 +%20 = OpTypeMatrix %10 4 +%21 = OpTypeArray %20 %18 +%22 = OpTypeArray %21 %18 +%23 = OpTypeInt 32 1 +%24 = OpTypeMatrix %8 3 +%25 = OpConstantTrue %3 +%26 = OpConstant %23 20 +%27 = OpConstant %23 2 +%29 = OpTypePointer Workgroup %5 %28 = OpVariable %29 Workgroup -%31 = OpTypePointer Workgroup %6 +%31 = OpTypePointer Workgroup %7 %30 = OpVariable %31 Workgroup -%33 = OpTypeStruct %13 +%33 = OpTypeStruct %9 %34 = OpTypePointer StorageBuffer %33 %32 = OpVariable %34 StorageBuffer -%36 = OpTypeStruct %15 +%36 = OpTypeStruct %11 %37 = OpTypePointer StorageBuffer %36 %35 = OpVariable %37 StorageBuffer -%39 = OpTypeStruct %17 +%39 = OpTypeStruct %13 %40 = OpTypePointer Uniform %39 %38 = OpVariable %40 Uniform -%42 = OpTypeStruct %12 +%42 = OpTypeStruct %8 %43 = OpTypePointer Uniform %42 %41 = OpVariable %43 Uniform -%45 = OpTypeStruct %19 +%45 = OpTypeStruct %15 %46 = OpTypePointer Uniform %45 %44 = OpVariable %46 Uniform -%48 = OpTypeStruct %23 +%48 = OpTypeStruct %19 %49 = OpTypePointer Uniform %48 %47 = OpVariable %49 Uniform -%51 = OpTypeStruct %26 +%51 = OpTypeStruct %22 %52 = OpTypePointer Uniform %51 %50 = OpVariable %52 Uniform -%56 = OpTypeFunction %2 %12 -%59 = OpTypePointer Function %8 -%60 = OpConstantNull %8 +%56 = OpTypeFunction %2 %8 +%59 = OpTypePointer Function %23 +%60 = OpConstantNull %23 %63 = OpTypeFunction %2 -%64 = OpTypePointer StorageBuffer %13 -%65 = OpConstant %6 0 -%67 = OpConstant %10 1.0 -%68 = OpConstant %8 1 -%69 = OpConstant %10 2.0 -%70 = OpConstant %10 3.0 -%71 = OpConstantNull %27 -%72 = OpConstantNull %27 -%74 = OpTypePointer StorageBuffer %12 -%77 = OpTypePointer StorageBuffer %10 -%97 = OpTypePointer Function %10 -%98 = OpConstantNull %10 -%100 = OpTypePointer Function %4 -%101 = OpConstantNull %4 -%105 = OpTypePointer StorageBuffer %15 -%107 = OpTypePointer Uniform %17 -%109 = OpTypePointer Uniform %12 -%111 = OpTypePointer Uniform %19 -%113 = OpTypePointer Uniform %23 -%115 = OpTypePointer Uniform %26 -%117 = OpConstant %10 4.0 -%118 = OpConstantTrue %4 -%120 = OpConstantNull %11 -%121 = OpConstantNull %6 -%122 = OpTypeVector %6 3 -%124 = OpTypePointer Input %122 -%123 = OpVariable %124 Input -%126 = OpConstantNull %122 -%127 = OpTypeVector %4 3 -%132 = OpConstant %6 264 -%135 = OpTypePointer Workgroup %10 -%136 = OpTypePointer Uniform %25 -%137 = OpTypePointer Uniform %24 -%140 = OpTypePointer Uniform %21 -%141 = OpTypePointer Uniform %20 -%142 = OpTypePointer Uniform %16 -%147 = OpConstant %6 7 -%153 = OpConstant %6 6 -%155 = OpTypePointer StorageBuffer %14 -%156 = OpConstant %6 1 -%159 = OpConstant %6 5 -%161 = OpTypePointer Uniform %16 -%162 = OpTypePointer Uniform %10 -%163 = OpConstant %6 3 -%166 = OpConstant %6 4 -%168 = OpTypePointer StorageBuffer %10 -%179 = OpConstant %6 256 +%64 = OpTypePointer StorageBuffer %9 +%65 = OpConstant %7 0 +%67 = OpConstant %4 1.0 +%68 = OpConstant %23 1 +%69 = OpConstant %4 2.0 +%70 = OpConstant %4 3.0 +%71 = OpConstantNull %24 +%72 = OpConstantNull %24 +%74 = OpTypePointer StorageBuffer %8 +%77 = OpTypePointer StorageBuffer %4 +%97 = OpTypePointer Function %4 +%98 = OpConstantNull %4 +%100 = OpTypePointer Function %3 +%101 = OpConstantNull %3 +%105 = OpTypePointer StorageBuffer %11 +%107 = OpTypePointer Uniform %13 +%109 = OpTypePointer Uniform %8 +%111 = OpTypePointer Uniform %15 +%113 = OpTypePointer Uniform %19 +%115 = OpTypePointer Uniform %22 +%117 = OpConstant %4 4.0 +%119 = OpConstantNull %5 +%120 = OpConstantNull %7 +%121 = OpTypeVector %7 3 +%123 = OpTypePointer Input %121 +%122 = OpVariable %123 Input +%125 = OpConstantNull %121 +%126 = OpTypeVector %3 3 +%131 = OpConstant %7 264 +%134 = OpTypePointer Workgroup %4 +%135 = OpTypePointer Uniform %21 +%136 = OpTypePointer Uniform %20 +%139 = OpTypePointer Uniform %17 +%140 = OpTypePointer Uniform %16 +%141 = OpTypePointer Uniform %12 +%146 = OpConstant %7 7 +%152 = OpConstant %7 6 +%154 = OpTypePointer StorageBuffer %10 +%155 = OpConstant %7 1 +%158 = OpConstant %7 5 +%160 = OpTypePointer Uniform %12 +%161 = OpTypePointer Uniform %4 +%162 = OpConstant %7 3 +%165 = OpConstant %7 4 +%167 = OpTypePointer StorageBuffer %4 +%178 = OpConstant %7 256 %55 = OpFunction %2 None %56 -%54 = OpFunctionParameter %12 +%54 = OpFunctionParameter %8 %53 = OpLabel OpBranch %57 %57 = OpLabel @@ -164,7 +163,7 @@ OpFunctionEnd %66 = OpAccessChain %64 %32 %65 OpBranch %73 %73 = OpLabel -%75 = OpCompositeConstruct %12 %67 %67 %67 +%75 = OpCompositeConstruct %8 %67 %67 %67 %76 = OpAccessChain %74 %66 %65 OpStore %76 %75 OpStore %58 %68 @@ -172,23 +171,23 @@ OpStore %58 %68 OpStore %78 %67 %79 = OpAccessChain %77 %66 %65 %65 OpStore %79 %69 -%80 = OpLoad %8 %58 +%80 = OpLoad %23 %58 %81 = OpAccessChain %77 %66 %65 %80 OpStore %81 %70 -%82 = OpLoad %13 %66 -%83 = OpCompositeExtract %12 %82 0 -%84 = OpCompositeExtract %12 %82 0 -%85 = OpVectorShuffle %14 %84 %84 2 0 -%86 = OpCompositeExtract %12 %82 0 +%82 = OpLoad %9 %66 +%83 = OpCompositeExtract %8 %82 0 +%84 = OpCompositeExtract %8 %82 0 +%85 = OpVectorShuffle %10 %84 %84 2 0 +%86 = OpCompositeExtract %8 %82 0 %87 = OpFunctionCall %2 %55 %86 -%88 = OpCompositeExtract %12 %82 0 -%89 = OpVectorTimesMatrix %12 %88 %71 -%90 = OpCompositeExtract %12 %82 0 -%91 = OpMatrixTimesVector %12 %72 %90 -%92 = OpCompositeExtract %12 %82 0 -%93 = OpVectorTimesScalar %12 %92 %69 -%94 = OpCompositeExtract %12 %82 0 -%95 = OpVectorTimesScalar %12 %94 %69 +%88 = OpCompositeExtract %8 %82 0 +%89 = OpVectorTimesMatrix %8 %88 %71 +%90 = OpCompositeExtract %8 %82 0 +%91 = OpMatrixTimesVector %8 %72 %90 +%92 = OpCompositeExtract %8 %82 0 +%93 = OpVectorTimesScalar %8 %92 %69 +%94 = OpCompositeExtract %8 %82 0 +%95 = OpVectorTimesScalar %8 %94 %69 OpReturn OpFunctionEnd %103 = OpFunction %2 None %63 @@ -202,60 +201,60 @@ OpFunctionEnd %112 = OpAccessChain %111 %44 %65 %114 = OpAccessChain %113 %47 %65 %116 = OpAccessChain %115 %50 %65 -OpBranch %119 -%119 = OpLabel -%125 = OpLoad %122 %123 -%128 = OpIEqual %127 %125 %126 -%129 = OpAll %4 %128 -OpSelectionMerge %130 None -OpBranchConditional %129 %131 %130 -%131 = OpLabel -OpStore %28 %120 -OpStore %30 %121 -OpBranch %130 +OpBranch %118 +%118 = OpLabel +%124 = OpLoad %121 %122 +%127 = OpIEqual %126 %124 %125 +%128 = OpAll %3 %127 +OpSelectionMerge %129 None +OpBranchConditional %128 %130 %129 %130 = OpLabel -OpControlBarrier %22 %22 %132 -OpBranch %133 -%133 = OpLabel -%134 = OpFunctionCall %2 %62 -%138 = OpAccessChain %137 %116 %65 %65 -%139 = OpLoad %24 %138 -%143 = OpAccessChain %142 %114 %65 %65 %65 -%144 = OpLoad %16 %143 -%145 = OpMatrixTimesVector %14 %139 %144 -%146 = OpCompositeExtract %10 %145 0 -%148 = OpAccessChain %135 %28 %147 -OpStore %148 %146 -%149 = OpLoad %19 %112 -%150 = OpLoad %12 %110 -%151 = OpMatrixTimesVector %14 %149 %150 -%152 = OpCompositeExtract %10 %151 0 -%154 = OpAccessChain %135 %28 %153 -OpStore %154 %152 -%157 = OpAccessChain %77 %106 %156 %156 -%158 = OpLoad %10 %157 -%160 = OpAccessChain %135 %28 %159 -OpStore %160 %158 -%164 = OpAccessChain %162 %108 %65 %163 -%165 = OpLoad %10 %164 -%167 = OpAccessChain %135 %28 %166 -OpStore %167 %165 -%169 = OpAccessChain %168 %104 %156 -%170 = OpLoad %10 %169 -%171 = OpAccessChain %135 %28 %163 -OpStore %171 %170 -%172 = OpAccessChain %77 %104 %65 %65 -%173 = OpLoad %10 %172 -%174 = OpAccessChain %135 %28 %22 -OpStore %174 %173 -%175 = OpAccessChain %168 %104 %156 -OpStore %175 %117 -%176 = OpArrayLength %6 %35 0 -%177 = OpConvertUToF %10 %176 -%178 = OpAccessChain %135 %28 %156 -OpStore %178 %177 -OpAtomicStore %30 %9 %179 %22 +OpStore %28 %119 +OpStore %30 %120 +OpBranch %129 +%129 = OpLabel +OpControlBarrier %18 %18 %131 +OpBranch %132 +%132 = OpLabel +%133 = OpFunctionCall %2 %62 +%137 = OpAccessChain %136 %116 %65 %65 +%138 = OpLoad %20 %137 +%142 = OpAccessChain %141 %114 %65 %65 %65 +%143 = OpLoad %12 %142 +%144 = OpMatrixTimesVector %10 %138 %143 +%145 = OpCompositeExtract %4 %144 0 +%147 = OpAccessChain %134 %28 %146 +OpStore %147 %145 +%148 = OpLoad %15 %112 +%149 = OpLoad %8 %110 +%150 = OpMatrixTimesVector %10 %148 %149 +%151 = OpCompositeExtract %4 %150 0 +%153 = OpAccessChain %134 %28 %152 +OpStore %153 %151 +%156 = OpAccessChain %77 %106 %155 %155 +%157 = OpLoad %4 %156 +%159 = OpAccessChain %134 %28 %158 +OpStore %159 %157 +%163 = OpAccessChain %161 %108 %65 %162 +%164 = OpLoad %4 %163 +%166 = OpAccessChain %134 %28 %165 +OpStore %166 %164 +%168 = OpAccessChain %167 %104 %155 +%169 = OpLoad %4 %168 +%170 = OpAccessChain %134 %28 %162 +OpStore %170 %169 +%171 = OpAccessChain %77 %104 %65 %65 +%172 = OpLoad %4 %171 +%173 = OpAccessChain %134 %28 %18 +OpStore %173 %172 +%174 = OpAccessChain %167 %104 %155 +OpStore %174 %117 +%175 = OpArrayLength %7 %35 0 +%176 = OpConvertUToF %4 %175 +%177 = OpAccessChain %134 %28 %155 +OpStore %177 %176 +OpAtomicStore %30 %27 %178 %18 OpStore %96 %67 -OpStore %99 %118 +OpStore %99 %25 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 4f9dd442e..fc8261145 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -113,608 +113,608 @@ OpDecorate %442 Location 0 OpDecorate %498 Location 0 OpDecorate %533 Location 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 3 -%5 = OpConstant %4 1 -%7 = OpTypeInt 32 0 -%6 = OpTypeImage %7 2D 0 0 0 1 Unknown -%8 = OpTypeImage %7 2D 0 0 1 1 Unknown -%10 = OpTypeFloat 32 -%9 = OpTypeImage %10 2D 1 0 1 1 Unknown -%11 = OpTypeImage %7 2D 0 0 0 2 Rgba8ui -%12 = OpTypeImage %7 2D 0 1 0 1 Unknown -%13 = OpTypeImage %7 1D 0 0 0 2 R32ui -%14 = OpTypeImage %7 1D 0 0 0 1 Unknown -%15 = OpTypeVector %7 3 -%16 = OpTypeVector %4 2 -%17 = OpTypeVector %7 2 -%18 = OpTypeVector %7 4 -%19 = OpTypeImage %10 1D 0 0 0 1 Unknown -%20 = OpTypeImage %10 2D 0 0 0 1 Unknown -%21 = OpTypeImage %4 2D 0 0 0 1 Unknown -%22 = OpTypeImage %10 2D 0 1 0 1 Unknown -%23 = OpTypeImage %10 Cube 0 0 0 1 Unknown -%24 = OpTypeImage %10 Cube 0 1 0 1 Unknown -%25 = OpTypeImage %10 3D 0 0 0 1 Unknown -%26 = OpTypeImage %10 2D 0 0 1 1 Unknown -%27 = OpTypeVector %10 4 -%28 = OpTypeSampler -%29 = OpTypeVector %10 2 -%30 = OpTypeVector %10 3 -%31 = OpTypeImage %10 2D 1 0 0 1 Unknown -%32 = OpTypeImage %10 2D 1 1 0 1 Unknown -%33 = OpTypeImage %10 Cube 1 0 0 1 Unknown -%34 = OpConstantComposite %16 %3 %5 -%36 = OpTypePointer UniformConstant %6 +%4 = OpTypeInt 32 0 +%3 = OpTypeImage %4 2D 0 0 0 1 Unknown +%5 = OpTypeImage %4 2D 0 0 1 1 Unknown +%7 = OpTypeFloat 32 +%6 = OpTypeImage %7 2D 1 0 1 1 Unknown +%8 = OpTypeImage %4 2D 0 0 0 2 Rgba8ui +%9 = OpTypeImage %4 2D 0 1 0 1 Unknown +%10 = OpTypeImage %4 1D 0 0 0 2 R32ui +%11 = OpTypeImage %4 1D 0 0 0 1 Unknown +%12 = OpTypeVector %4 3 +%14 = OpTypeInt 32 1 +%13 = OpTypeVector %14 2 +%15 = OpTypeVector %4 2 +%16 = OpTypeVector %4 4 +%17 = OpTypeImage %7 1D 0 0 0 1 Unknown +%18 = OpTypeImage %7 2D 0 0 0 1 Unknown +%19 = OpTypeImage %14 2D 0 0 0 1 Unknown +%20 = OpTypeImage %7 2D 0 1 0 1 Unknown +%21 = OpTypeImage %7 Cube 0 0 0 1 Unknown +%22 = OpTypeImage %7 Cube 0 1 0 1 Unknown +%23 = OpTypeImage %7 3D 0 0 0 1 Unknown +%24 = OpTypeImage %7 2D 0 0 1 1 Unknown +%25 = OpTypeVector %7 4 +%26 = OpTypeSampler +%27 = OpTypeVector %7 2 +%28 = OpTypeVector %7 3 +%29 = OpTypeImage %7 2D 1 0 0 1 Unknown +%30 = OpTypeImage %7 2D 1 1 0 1 Unknown +%31 = OpTypeImage %7 Cube 1 0 0 1 Unknown +%32 = OpConstant %14 3 +%33 = OpConstant %14 1 +%34 = OpConstantComposite %13 %32 %33 +%36 = OpTypePointer UniformConstant %3 %35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %8 +%38 = OpTypePointer UniformConstant %5 %37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %9 +%40 = OpTypePointer UniformConstant %6 %39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %11 +%42 = OpTypePointer UniformConstant %8 %41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %12 +%44 = OpTypePointer UniformConstant %9 %43 = OpVariable %44 UniformConstant -%46 = OpTypePointer UniformConstant %13 +%46 = OpTypePointer UniformConstant %10 %45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %14 +%48 = OpTypePointer UniformConstant %11 %47 = OpVariable %48 UniformConstant -%50 = OpTypePointer UniformConstant %13 +%50 = OpTypePointer UniformConstant %10 %49 = OpVariable %50 UniformConstant -%52 = OpTypePointer UniformConstant %19 +%52 = OpTypePointer UniformConstant %17 %51 = OpVariable %52 UniformConstant -%54 = OpTypePointer UniformConstant %20 +%54 = OpTypePointer UniformConstant %18 %53 = OpVariable %54 UniformConstant %55 = OpVariable %36 UniformConstant -%57 = OpTypePointer UniformConstant %21 +%57 = OpTypePointer UniformConstant %19 %56 = OpVariable %57 UniformConstant -%59 = OpTypePointer UniformConstant %22 +%59 = OpTypePointer UniformConstant %20 %58 = OpVariable %59 UniformConstant -%61 = OpTypePointer UniformConstant %23 +%61 = OpTypePointer UniformConstant %21 %60 = OpVariable %61 UniformConstant -%63 = OpTypePointer UniformConstant %24 +%63 = OpTypePointer UniformConstant %22 %62 = OpVariable %63 UniformConstant -%65 = OpTypePointer UniformConstant %25 +%65 = OpTypePointer UniformConstant %23 %64 = OpVariable %65 UniformConstant -%67 = OpTypePointer UniformConstant %26 +%67 = OpTypePointer UniformConstant %24 %66 = OpVariable %67 UniformConstant -%69 = OpTypePointer UniformConstant %28 +%69 = OpTypePointer UniformConstant %26 %68 = OpVariable %69 UniformConstant -%71 = OpTypePointer UniformConstant %28 +%71 = OpTypePointer UniformConstant %26 %70 = OpVariable %71 UniformConstant -%73 = OpTypePointer UniformConstant %31 +%73 = OpTypePointer UniformConstant %29 %72 = OpVariable %73 UniformConstant -%75 = OpTypePointer UniformConstant %32 +%75 = OpTypePointer UniformConstant %30 %74 = OpVariable %75 UniformConstant -%77 = OpTypePointer UniformConstant %33 +%77 = OpTypePointer UniformConstant %31 %76 = OpVariable %77 UniformConstant -%80 = OpTypePointer Input %15 +%80 = OpTypePointer Input %12 %79 = OpVariable %80 Input %83 = OpTypeFunction %2 -%90 = OpConstant %4 10 -%91 = OpConstant %4 20 -%112 = OpTypeVector %4 3 +%90 = OpConstant %14 10 +%91 = OpConstant %14 20 +%112 = OpTypeVector %14 3 %170 = OpVariable %80 Input -%193 = OpTypePointer Output %27 +%193 = OpTypePointer Output %25 %192 = OpVariable %193 Output -%203 = OpConstant %7 0 +%203 = OpConstant %4 0 %258 = OpVariable %193 Output -%295 = OpTypePointer Function %27 -%296 = OpConstantNull %27 +%295 = OpTypePointer Function %25 +%296 = OpConstantNull %25 %298 = OpVariable %193 Output -%305 = OpConstant %10 0.5 -%306 = OpConstant %10 2.3 -%307 = OpConstant %10 2.0 -%308 = OpConstant %4 0 -%313 = OpTypeSampledImage %19 -%318 = OpTypeSampledImage %20 -%339 = OpTypeSampledImage %22 -%400 = OpTypeSampledImage %24 -%439 = OpTypePointer Function %10 -%440 = OpConstantNull %10 -%443 = OpTypePointer Output %10 +%305 = OpConstant %7 0.5 +%306 = OpConstant %7 2.3 +%307 = OpConstant %7 2.0 +%308 = OpConstant %14 0 +%313 = OpTypeSampledImage %17 +%318 = OpTypeSampledImage %18 +%339 = OpTypeSampledImage %20 +%400 = OpTypeSampledImage %22 +%439 = OpTypePointer Function %7 +%440 = OpConstantNull %7 +%443 = OpTypePointer Output %7 %442 = OpVariable %443 Output -%452 = OpTypeSampledImage %31 -%457 = OpTypeSampledImage %32 -%470 = OpTypeSampledImage %33 -%477 = OpConstant %10 0.0 +%452 = OpTypeSampledImage %29 +%457 = OpTypeSampledImage %30 +%470 = OpTypeSampledImage %31 +%477 = OpConstant %7 0.0 %498 = OpVariable %193 Output -%510 = OpConstant %7 1 -%513 = OpConstant %7 3 -%518 = OpTypeSampledImage %6 -%521 = OpTypeVector %4 4 -%522 = OpTypeSampledImage %21 +%510 = OpConstant %4 1 +%513 = OpConstant %4 3 +%518 = OpTypeSampledImage %3 +%521 = OpTypeVector %14 4 +%522 = OpTypeSampledImage %19 %533 = OpVariable %193 Output %82 = OpFunction %2 None %83 %78 = OpLabel -%81 = OpLoad %15 %79 -%84 = OpLoad %6 %35 -%85 = OpLoad %8 %37 -%86 = OpLoad %11 %41 -%87 = OpLoad %12 %43 -%88 = OpLoad %14 %47 -%89 = OpLoad %13 %49 +%81 = OpLoad %12 %79 +%84 = OpLoad %3 %35 +%85 = OpLoad %5 %37 +%86 = OpLoad %8 %41 +%87 = OpLoad %9 %43 +%88 = OpLoad %11 %47 +%89 = OpLoad %10 %49 OpBranch %92 %92 = OpLabel -%93 = OpImageQuerySize %16 %86 -%94 = OpBitcast %17 %93 -%95 = OpVectorShuffle %17 %81 %81 0 1 -%96 = OpIMul %17 %94 %95 -%97 = OpBitcast %16 %96 -%98 = OpCompositeConstruct %16 %90 %91 -%99 = OpSRem %16 %97 %98 -%100 = OpCompositeExtract %7 %81 2 -%101 = OpBitcast %4 %100 -%102 = OpImageFetch %18 %84 %99 Lod %101 -%103 = OpCompositeExtract %7 %81 2 -%104 = OpBitcast %4 %103 -%105 = OpImageFetch %18 %85 %99 Sample %104 -%106 = OpImageRead %18 %86 %99 -%107 = OpCompositeExtract %7 %81 2 -%108 = OpCompositeExtract %7 %81 2 -%109 = OpBitcast %4 %108 -%110 = OpIAdd %4 %109 %5 -%111 = OpBitcast %4 %107 +%93 = OpImageQuerySize %13 %86 +%94 = OpBitcast %15 %93 +%95 = OpVectorShuffle %15 %81 %81 0 1 +%96 = OpIMul %15 %94 %95 +%97 = OpBitcast %13 %96 +%98 = OpCompositeConstruct %13 %90 %91 +%99 = OpSRem %13 %97 %98 +%100 = OpCompositeExtract %4 %81 2 +%101 = OpBitcast %14 %100 +%102 = OpImageFetch %16 %84 %99 Lod %101 +%103 = OpCompositeExtract %4 %81 2 +%104 = OpBitcast %14 %103 +%105 = OpImageFetch %16 %85 %99 Sample %104 +%106 = OpImageRead %16 %86 %99 +%107 = OpCompositeExtract %4 %81 2 +%108 = OpCompositeExtract %4 %81 2 +%109 = OpBitcast %14 %108 +%110 = OpIAdd %14 %109 %33 +%111 = OpBitcast %14 %107 %113 = OpCompositeConstruct %112 %99 %111 -%114 = OpImageFetch %18 %87 %113 Lod %110 -%115 = OpCompositeExtract %7 %81 2 -%116 = OpBitcast %4 %115 -%117 = OpCompositeExtract %7 %81 2 -%118 = OpBitcast %4 %117 -%119 = OpIAdd %4 %118 %5 +%114 = OpImageFetch %16 %87 %113 Lod %110 +%115 = OpCompositeExtract %4 %81 2 +%116 = OpBitcast %14 %115 +%117 = OpCompositeExtract %4 %81 2 +%118 = OpBitcast %14 %117 +%119 = OpIAdd %14 %118 %33 %120 = OpCompositeConstruct %112 %99 %116 -%121 = OpImageFetch %18 %87 %120 Lod %119 -%122 = OpCompositeExtract %7 %81 0 -%123 = OpBitcast %4 %122 -%124 = OpCompositeExtract %7 %81 2 -%125 = OpBitcast %4 %124 -%126 = OpImageFetch %18 %88 %123 Lod %125 -%127 = OpBitcast %17 %99 -%128 = OpCompositeExtract %7 %81 2 -%129 = OpBitcast %4 %128 -%130 = OpImageFetch %18 %84 %127 Lod %129 -%131 = OpBitcast %17 %99 -%132 = OpCompositeExtract %7 %81 2 -%133 = OpBitcast %4 %132 -%134 = OpImageFetch %18 %85 %131 Sample %133 -%135 = OpBitcast %17 %99 -%136 = OpImageRead %18 %86 %135 -%137 = OpBitcast %17 %99 -%138 = OpCompositeExtract %7 %81 2 -%139 = OpCompositeExtract %7 %81 2 -%140 = OpBitcast %4 %139 -%141 = OpIAdd %4 %140 %5 -%142 = OpCompositeConstruct %15 %137 %138 -%143 = OpImageFetch %18 %87 %142 Lod %141 -%144 = OpBitcast %17 %99 -%145 = OpCompositeExtract %7 %81 2 -%146 = OpBitcast %4 %145 -%147 = OpCompositeExtract %7 %81 2 -%148 = OpBitcast %4 %147 -%149 = OpIAdd %4 %148 %5 -%150 = OpBitcast %7 %146 -%151 = OpCompositeConstruct %15 %144 %150 -%152 = OpImageFetch %18 %87 %151 Lod %149 -%153 = OpCompositeExtract %7 %81 0 -%155 = OpCompositeExtract %7 %81 2 -%156 = OpBitcast %4 %155 -%157 = OpImageFetch %18 %88 %153 Lod %156 -%158 = OpCompositeExtract %4 %99 0 -%159 = OpIAdd %18 %102 %105 -%160 = OpIAdd %18 %159 %106 -%161 = OpIAdd %18 %160 %114 -%162 = OpIAdd %18 %161 %121 +%121 = OpImageFetch %16 %87 %120 Lod %119 +%122 = OpCompositeExtract %4 %81 0 +%123 = OpBitcast %14 %122 +%124 = OpCompositeExtract %4 %81 2 +%125 = OpBitcast %14 %124 +%126 = OpImageFetch %16 %88 %123 Lod %125 +%127 = OpBitcast %15 %99 +%128 = OpCompositeExtract %4 %81 2 +%129 = OpBitcast %14 %128 +%130 = OpImageFetch %16 %84 %127 Lod %129 +%131 = OpBitcast %15 %99 +%132 = OpCompositeExtract %4 %81 2 +%133 = OpBitcast %14 %132 +%134 = OpImageFetch %16 %85 %131 Sample %133 +%135 = OpBitcast %15 %99 +%136 = OpImageRead %16 %86 %135 +%137 = OpBitcast %15 %99 +%138 = OpCompositeExtract %4 %81 2 +%139 = OpCompositeExtract %4 %81 2 +%140 = OpBitcast %14 %139 +%141 = OpIAdd %14 %140 %33 +%142 = OpCompositeConstruct %12 %137 %138 +%143 = OpImageFetch %16 %87 %142 Lod %141 +%144 = OpBitcast %15 %99 +%145 = OpCompositeExtract %4 %81 2 +%146 = OpBitcast %14 %145 +%147 = OpCompositeExtract %4 %81 2 +%148 = OpBitcast %14 %147 +%149 = OpIAdd %14 %148 %33 +%150 = OpBitcast %4 %146 +%151 = OpCompositeConstruct %12 %144 %150 +%152 = OpImageFetch %16 %87 %151 Lod %149 +%153 = OpCompositeExtract %4 %81 0 +%155 = OpCompositeExtract %4 %81 2 +%156 = OpBitcast %14 %155 +%157 = OpImageFetch %16 %88 %153 Lod %156 +%158 = OpCompositeExtract %14 %99 0 +%159 = OpIAdd %16 %102 %105 +%160 = OpIAdd %16 %159 %106 +%161 = OpIAdd %16 %160 %114 +%162 = OpIAdd %16 %161 %121 OpImageWrite %89 %158 %162 -%163 = OpCompositeExtract %4 %99 0 -%164 = OpBitcast %7 %163 -%165 = OpIAdd %18 %130 %134 -%166 = OpIAdd %18 %165 %136 -%167 = OpIAdd %18 %166 %143 -%168 = OpIAdd %18 %167 %152 +%163 = OpCompositeExtract %14 %99 0 +%164 = OpBitcast %4 %163 +%165 = OpIAdd %16 %130 %134 +%166 = OpIAdd %16 %165 %136 +%167 = OpIAdd %16 %166 %143 +%168 = OpIAdd %16 %167 %152 OpImageWrite %89 %164 %168 OpReturn OpFunctionEnd %172 = OpFunction %2 None %83 %169 = OpLabel -%171 = OpLoad %15 %170 -%173 = OpLoad %9 %39 -%174 = OpLoad %11 %41 -%175 = OpLoad %13 %49 +%171 = OpLoad %12 %170 +%173 = OpLoad %6 %39 +%174 = OpLoad %8 %41 +%175 = OpLoad %10 %49 OpBranch %176 %176 = OpLabel -%177 = OpImageQuerySize %16 %174 -%178 = OpBitcast %17 %177 -%179 = OpVectorShuffle %17 %171 %171 0 1 -%180 = OpIMul %17 %178 %179 -%181 = OpBitcast %16 %180 -%182 = OpCompositeConstruct %16 %90 %91 -%183 = OpSRem %16 %181 %182 -%184 = OpCompositeExtract %7 %171 2 -%185 = OpBitcast %4 %184 -%186 = OpImageFetch %27 %173 %183 Sample %185 -%187 = OpCompositeExtract %10 %186 0 -%188 = OpCompositeExtract %4 %183 0 -%189 = OpConvertFToU %7 %187 -%190 = OpCompositeConstruct %18 %189 %189 %189 %189 +%177 = OpImageQuerySize %13 %174 +%178 = OpBitcast %15 %177 +%179 = OpVectorShuffle %15 %171 %171 0 1 +%180 = OpIMul %15 %178 %179 +%181 = OpBitcast %13 %180 +%182 = OpCompositeConstruct %13 %90 %91 +%183 = OpSRem %13 %181 %182 +%184 = OpCompositeExtract %4 %171 2 +%185 = OpBitcast %14 %184 +%186 = OpImageFetch %25 %173 %183 Sample %185 +%187 = OpCompositeExtract %7 %186 0 +%188 = OpCompositeExtract %14 %183 0 +%189 = OpConvertFToU %4 %187 +%190 = OpCompositeConstruct %16 %189 %189 %189 %189 OpImageWrite %175 %188 %190 OpReturn OpFunctionEnd %194 = OpFunction %2 None %83 %191 = OpLabel -%195 = OpLoad %19 %51 -%196 = OpLoad %20 %53 -%197 = OpLoad %22 %58 -%198 = OpLoad %23 %60 -%199 = OpLoad %24 %62 -%200 = OpLoad %25 %64 -%201 = OpLoad %26 %66 +%195 = OpLoad %17 %51 +%196 = OpLoad %18 %53 +%197 = OpLoad %20 %58 +%198 = OpLoad %21 %60 +%199 = OpLoad %22 %62 +%200 = OpLoad %23 %64 +%201 = OpLoad %24 %66 OpBranch %202 %202 = OpLabel -%204 = OpImageQuerySizeLod %4 %195 %203 -%205 = OpBitcast %7 %204 -%206 = OpBitcast %4 %205 -%207 = OpImageQuerySizeLod %4 %195 %206 -%208 = OpBitcast %7 %207 -%209 = OpImageQuerySizeLod %16 %196 %203 -%210 = OpBitcast %17 %209 -%211 = OpImageQuerySizeLod %16 %196 %5 -%212 = OpBitcast %17 %211 +%204 = OpImageQuerySizeLod %14 %195 %203 +%205 = OpBitcast %4 %204 +%206 = OpBitcast %14 %205 +%207 = OpImageQuerySizeLod %14 %195 %206 +%208 = OpBitcast %4 %207 +%209 = OpImageQuerySizeLod %13 %196 %203 +%210 = OpBitcast %15 %209 +%211 = OpImageQuerySizeLod %13 %196 %33 +%212 = OpBitcast %15 %211 %213 = OpImageQuerySizeLod %112 %197 %203 -%214 = OpBitcast %15 %213 -%215 = OpVectorShuffle %17 %214 %214 0 1 -%216 = OpImageQuerySizeLod %112 %197 %5 -%217 = OpBitcast %15 %216 -%218 = OpVectorShuffle %17 %217 %217 0 1 -%219 = OpImageQuerySizeLod %16 %198 %203 -%220 = OpBitcast %17 %219 -%221 = OpImageQuerySizeLod %16 %198 %5 -%222 = OpBitcast %17 %221 +%214 = OpBitcast %12 %213 +%215 = OpVectorShuffle %15 %214 %214 0 1 +%216 = OpImageQuerySizeLod %112 %197 %33 +%217 = OpBitcast %12 %216 +%218 = OpVectorShuffle %15 %217 %217 0 1 +%219 = OpImageQuerySizeLod %13 %198 %203 +%220 = OpBitcast %15 %219 +%221 = OpImageQuerySizeLod %13 %198 %33 +%222 = OpBitcast %15 %221 %223 = OpImageQuerySizeLod %112 %199 %203 -%224 = OpBitcast %15 %223 -%225 = OpVectorShuffle %17 %224 %224 0 0 -%226 = OpImageQuerySizeLod %112 %199 %5 -%227 = OpBitcast %15 %226 -%228 = OpVectorShuffle %17 %227 %227 0 0 +%224 = OpBitcast %12 %223 +%225 = OpVectorShuffle %15 %224 %224 0 0 +%226 = OpImageQuerySizeLod %112 %199 %33 +%227 = OpBitcast %12 %226 +%228 = OpVectorShuffle %15 %227 %227 0 0 %229 = OpImageQuerySizeLod %112 %200 %203 -%230 = OpBitcast %15 %229 -%231 = OpImageQuerySizeLod %112 %200 %5 -%232 = OpBitcast %15 %231 -%233 = OpImageQuerySize %16 %201 -%234 = OpBitcast %17 %233 -%235 = OpCompositeExtract %7 %210 1 -%236 = OpIAdd %7 %205 %235 -%237 = OpCompositeExtract %7 %212 1 -%238 = OpIAdd %7 %236 %237 -%239 = OpCompositeExtract %7 %215 1 -%240 = OpIAdd %7 %238 %239 -%241 = OpCompositeExtract %7 %218 1 -%242 = OpIAdd %7 %240 %241 -%243 = OpCompositeExtract %7 %220 1 -%244 = OpIAdd %7 %242 %243 -%245 = OpCompositeExtract %7 %222 1 -%246 = OpIAdd %7 %244 %245 -%247 = OpCompositeExtract %7 %225 1 -%248 = OpIAdd %7 %246 %247 -%249 = OpCompositeExtract %7 %228 1 -%250 = OpIAdd %7 %248 %249 -%251 = OpCompositeExtract %7 %230 2 -%252 = OpIAdd %7 %250 %251 -%253 = OpCompositeExtract %7 %232 2 -%254 = OpIAdd %7 %252 %253 -%255 = OpConvertUToF %10 %254 -%256 = OpCompositeConstruct %27 %255 %255 %255 %255 +%230 = OpBitcast %12 %229 +%231 = OpImageQuerySizeLod %112 %200 %33 +%232 = OpBitcast %12 %231 +%233 = OpImageQuerySize %13 %201 +%234 = OpBitcast %15 %233 +%235 = OpCompositeExtract %4 %210 1 +%236 = OpIAdd %4 %205 %235 +%237 = OpCompositeExtract %4 %212 1 +%238 = OpIAdd %4 %236 %237 +%239 = OpCompositeExtract %4 %215 1 +%240 = OpIAdd %4 %238 %239 +%241 = OpCompositeExtract %4 %218 1 +%242 = OpIAdd %4 %240 %241 +%243 = OpCompositeExtract %4 %220 1 +%244 = OpIAdd %4 %242 %243 +%245 = OpCompositeExtract %4 %222 1 +%246 = OpIAdd %4 %244 %245 +%247 = OpCompositeExtract %4 %225 1 +%248 = OpIAdd %4 %246 %247 +%249 = OpCompositeExtract %4 %228 1 +%250 = OpIAdd %4 %248 %249 +%251 = OpCompositeExtract %4 %230 2 +%252 = OpIAdd %4 %250 %251 +%253 = OpCompositeExtract %4 %232 2 +%254 = OpIAdd %4 %252 %253 +%255 = OpConvertUToF %7 %254 +%256 = OpCompositeConstruct %25 %255 %255 %255 %255 OpStore %192 %256 OpReturn OpFunctionEnd %259 = OpFunction %2 None %83 %257 = OpLabel -%260 = OpLoad %20 %53 -%261 = OpLoad %22 %58 -%262 = OpLoad %23 %60 -%263 = OpLoad %24 %62 -%264 = OpLoad %25 %64 -%265 = OpLoad %26 %66 +%260 = OpLoad %18 %53 +%261 = OpLoad %20 %58 +%262 = OpLoad %21 %60 +%263 = OpLoad %22 %62 +%264 = OpLoad %23 %64 +%265 = OpLoad %24 %66 OpBranch %266 %266 = OpLabel -%267 = OpImageQueryLevels %4 %260 -%268 = OpBitcast %7 %267 -%269 = OpImageQueryLevels %4 %261 -%270 = OpBitcast %7 %269 +%267 = OpImageQueryLevels %14 %260 +%268 = OpBitcast %4 %267 +%269 = OpImageQueryLevels %14 %261 +%270 = OpBitcast %4 %269 %271 = OpImageQuerySizeLod %112 %261 %203 -%272 = OpCompositeExtract %4 %271 2 -%273 = OpBitcast %7 %272 -%274 = OpImageQueryLevels %4 %262 -%275 = OpBitcast %7 %274 -%276 = OpImageQueryLevels %4 %263 -%277 = OpBitcast %7 %276 +%272 = OpCompositeExtract %14 %271 2 +%273 = OpBitcast %4 %272 +%274 = OpImageQueryLevels %14 %262 +%275 = OpBitcast %4 %274 +%276 = OpImageQueryLevels %14 %263 +%277 = OpBitcast %4 %276 %278 = OpImageQuerySizeLod %112 %263 %203 -%279 = OpCompositeExtract %4 %278 2 -%280 = OpBitcast %7 %279 -%281 = OpImageQueryLevels %4 %264 -%282 = OpBitcast %7 %281 -%283 = OpImageQuerySamples %4 %265 -%284 = OpBitcast %7 %283 -%285 = OpIAdd %7 %273 %280 -%286 = OpIAdd %7 %285 %284 -%287 = OpIAdd %7 %286 %268 -%288 = OpIAdd %7 %287 %270 -%289 = OpIAdd %7 %288 %282 -%290 = OpIAdd %7 %289 %275 -%291 = OpIAdd %7 %290 %277 -%292 = OpConvertUToF %10 %291 -%293 = OpCompositeConstruct %27 %292 %292 %292 %292 +%279 = OpCompositeExtract %14 %278 2 +%280 = OpBitcast %4 %279 +%281 = OpImageQueryLevels %14 %264 +%282 = OpBitcast %4 %281 +%283 = OpImageQuerySamples %14 %265 +%284 = OpBitcast %4 %283 +%285 = OpIAdd %4 %273 %280 +%286 = OpIAdd %4 %285 %284 +%287 = OpIAdd %4 %286 %268 +%288 = OpIAdd %4 %287 %270 +%289 = OpIAdd %4 %288 %282 +%290 = OpIAdd %4 %289 %275 +%291 = OpIAdd %4 %290 %277 +%292 = OpConvertUToF %7 %291 +%293 = OpCompositeConstruct %25 %292 %292 %292 %292 OpStore %258 %293 OpReturn OpFunctionEnd %299 = OpFunction %2 None %83 %297 = OpLabel %294 = OpVariable %295 Function %296 -%300 = OpLoad %19 %51 -%301 = OpLoad %20 %53 -%302 = OpLoad %22 %58 -%303 = OpLoad %24 %62 -%304 = OpLoad %28 %68 +%300 = OpLoad %17 %51 +%301 = OpLoad %18 %53 +%302 = OpLoad %20 %58 +%303 = OpLoad %22 %62 +%304 = OpLoad %26 %68 OpBranch %309 %309 = OpLabel -%310 = OpCompositeConstruct %29 %305 %305 -%311 = OpCompositeConstruct %30 %305 %305 %305 -%312 = OpCompositeExtract %10 %310 0 +%310 = OpCompositeConstruct %27 %305 %305 +%311 = OpCompositeConstruct %28 %305 %305 %305 +%312 = OpCompositeExtract %7 %310 0 %314 = OpSampledImage %313 %300 %304 -%315 = OpImageSampleImplicitLod %27 %314 %312 -%316 = OpLoad %27 %294 -%317 = OpFAdd %27 %316 %315 +%315 = OpImageSampleImplicitLod %25 %314 %312 +%316 = OpLoad %25 %294 +%317 = OpFAdd %25 %316 %315 OpStore %294 %317 %319 = OpSampledImage %318 %301 %304 -%320 = OpImageSampleImplicitLod %27 %319 %310 -%321 = OpLoad %27 %294 -%322 = OpFAdd %27 %321 %320 +%320 = OpImageSampleImplicitLod %25 %319 %310 +%321 = OpLoad %25 %294 +%322 = OpFAdd %25 %321 %320 OpStore %294 %322 %323 = OpSampledImage %318 %301 %304 -%324 = OpImageSampleImplicitLod %27 %323 %310 ConstOffset %34 -%325 = OpLoad %27 %294 -%326 = OpFAdd %27 %325 %324 +%324 = OpImageSampleImplicitLod %25 %323 %310 ConstOffset %34 +%325 = OpLoad %25 %294 +%326 = OpFAdd %25 %325 %324 OpStore %294 %326 %327 = OpSampledImage %318 %301 %304 -%328 = OpImageSampleExplicitLod %27 %327 %310 Lod %306 -%329 = OpLoad %27 %294 -%330 = OpFAdd %27 %329 %328 +%328 = OpImageSampleExplicitLod %25 %327 %310 Lod %306 +%329 = OpLoad %25 %294 +%330 = OpFAdd %25 %329 %328 OpStore %294 %330 %331 = OpSampledImage %318 %301 %304 -%332 = OpImageSampleExplicitLod %27 %331 %310 Lod|ConstOffset %306 %34 -%333 = OpLoad %27 %294 -%334 = OpFAdd %27 %333 %332 +%332 = OpImageSampleExplicitLod %25 %331 %310 Lod|ConstOffset %306 %34 +%333 = OpLoad %25 %294 +%334 = OpFAdd %25 %333 %332 OpStore %294 %334 %335 = OpSampledImage %318 %301 %304 -%336 = OpImageSampleImplicitLod %27 %335 %310 Bias|ConstOffset %307 %34 -%337 = OpLoad %27 %294 -%338 = OpFAdd %27 %337 %336 +%336 = OpImageSampleImplicitLod %25 %335 %310 Bias|ConstOffset %307 %34 +%337 = OpLoad %25 %294 +%338 = OpFAdd %25 %337 %336 OpStore %294 %338 -%340 = OpConvertUToF %10 %203 -%341 = OpCompositeConstruct %30 %310 %340 +%340 = OpConvertUToF %7 %203 +%341 = OpCompositeConstruct %28 %310 %340 %342 = OpSampledImage %339 %302 %304 -%343 = OpImageSampleImplicitLod %27 %342 %341 -%344 = OpLoad %27 %294 -%345 = OpFAdd %27 %344 %343 +%343 = OpImageSampleImplicitLod %25 %342 %341 +%344 = OpLoad %25 %294 +%345 = OpFAdd %25 %344 %343 OpStore %294 %345 -%346 = OpConvertUToF %10 %203 -%347 = OpCompositeConstruct %30 %310 %346 +%346 = OpConvertUToF %7 %203 +%347 = OpCompositeConstruct %28 %310 %346 %348 = OpSampledImage %339 %302 %304 -%349 = OpImageSampleImplicitLod %27 %348 %347 ConstOffset %34 -%350 = OpLoad %27 %294 -%351 = OpFAdd %27 %350 %349 +%349 = OpImageSampleImplicitLod %25 %348 %347 ConstOffset %34 +%350 = OpLoad %25 %294 +%351 = OpFAdd %25 %350 %349 OpStore %294 %351 -%352 = OpConvertUToF %10 %203 -%353 = OpCompositeConstruct %30 %310 %352 +%352 = OpConvertUToF %7 %203 +%353 = OpCompositeConstruct %28 %310 %352 %354 = OpSampledImage %339 %302 %304 -%355 = OpImageSampleExplicitLod %27 %354 %353 Lod %306 -%356 = OpLoad %27 %294 -%357 = OpFAdd %27 %356 %355 +%355 = OpImageSampleExplicitLod %25 %354 %353 Lod %306 +%356 = OpLoad %25 %294 +%357 = OpFAdd %25 %356 %355 OpStore %294 %357 -%358 = OpConvertUToF %10 %203 -%359 = OpCompositeConstruct %30 %310 %358 +%358 = OpConvertUToF %7 %203 +%359 = OpCompositeConstruct %28 %310 %358 %360 = OpSampledImage %339 %302 %304 -%361 = OpImageSampleExplicitLod %27 %360 %359 Lod|ConstOffset %306 %34 -%362 = OpLoad %27 %294 -%363 = OpFAdd %27 %362 %361 +%361 = OpImageSampleExplicitLod %25 %360 %359 Lod|ConstOffset %306 %34 +%362 = OpLoad %25 %294 +%363 = OpFAdd %25 %362 %361 OpStore %294 %363 -%364 = OpConvertUToF %10 %203 -%365 = OpCompositeConstruct %30 %310 %364 +%364 = OpConvertUToF %7 %203 +%365 = OpCompositeConstruct %28 %310 %364 %366 = OpSampledImage %339 %302 %304 -%367 = OpImageSampleImplicitLod %27 %366 %365 Bias|ConstOffset %307 %34 -%368 = OpLoad %27 %294 -%369 = OpFAdd %27 %368 %367 +%367 = OpImageSampleImplicitLod %25 %366 %365 Bias|ConstOffset %307 %34 +%368 = OpLoad %25 %294 +%369 = OpFAdd %25 %368 %367 OpStore %294 %369 -%370 = OpConvertSToF %10 %308 -%371 = OpCompositeConstruct %30 %310 %370 +%370 = OpConvertSToF %7 %308 +%371 = OpCompositeConstruct %28 %310 %370 %372 = OpSampledImage %339 %302 %304 -%373 = OpImageSampleImplicitLod %27 %372 %371 -%374 = OpLoad %27 %294 -%375 = OpFAdd %27 %374 %373 +%373 = OpImageSampleImplicitLod %25 %372 %371 +%374 = OpLoad %25 %294 +%375 = OpFAdd %25 %374 %373 OpStore %294 %375 -%376 = OpConvertSToF %10 %308 -%377 = OpCompositeConstruct %30 %310 %376 +%376 = OpConvertSToF %7 %308 +%377 = OpCompositeConstruct %28 %310 %376 %378 = OpSampledImage %339 %302 %304 -%379 = OpImageSampleImplicitLod %27 %378 %377 ConstOffset %34 -%380 = OpLoad %27 %294 -%381 = OpFAdd %27 %380 %379 +%379 = OpImageSampleImplicitLod %25 %378 %377 ConstOffset %34 +%380 = OpLoad %25 %294 +%381 = OpFAdd %25 %380 %379 OpStore %294 %381 -%382 = OpConvertSToF %10 %308 -%383 = OpCompositeConstruct %30 %310 %382 +%382 = OpConvertSToF %7 %308 +%383 = OpCompositeConstruct %28 %310 %382 %384 = OpSampledImage %339 %302 %304 -%385 = OpImageSampleExplicitLod %27 %384 %383 Lod %306 -%386 = OpLoad %27 %294 -%387 = OpFAdd %27 %386 %385 +%385 = OpImageSampleExplicitLod %25 %384 %383 Lod %306 +%386 = OpLoad %25 %294 +%387 = OpFAdd %25 %386 %385 OpStore %294 %387 -%388 = OpConvertSToF %10 %308 -%389 = OpCompositeConstruct %30 %310 %388 +%388 = OpConvertSToF %7 %308 +%389 = OpCompositeConstruct %28 %310 %388 %390 = OpSampledImage %339 %302 %304 -%391 = OpImageSampleExplicitLod %27 %390 %389 Lod|ConstOffset %306 %34 -%392 = OpLoad %27 %294 -%393 = OpFAdd %27 %392 %391 +%391 = OpImageSampleExplicitLod %25 %390 %389 Lod|ConstOffset %306 %34 +%392 = OpLoad %25 %294 +%393 = OpFAdd %25 %392 %391 OpStore %294 %393 -%394 = OpConvertSToF %10 %308 -%395 = OpCompositeConstruct %30 %310 %394 +%394 = OpConvertSToF %7 %308 +%395 = OpCompositeConstruct %28 %310 %394 %396 = OpSampledImage %339 %302 %304 -%397 = OpImageSampleImplicitLod %27 %396 %395 Bias|ConstOffset %307 %34 -%398 = OpLoad %27 %294 -%399 = OpFAdd %27 %398 %397 +%397 = OpImageSampleImplicitLod %25 %396 %395 Bias|ConstOffset %307 %34 +%398 = OpLoad %25 %294 +%399 = OpFAdd %25 %398 %397 OpStore %294 %399 -%401 = OpConvertUToF %10 %203 -%402 = OpCompositeConstruct %27 %311 %401 +%401 = OpConvertUToF %7 %203 +%402 = OpCompositeConstruct %25 %311 %401 %403 = OpSampledImage %400 %303 %304 -%404 = OpImageSampleImplicitLod %27 %403 %402 -%405 = OpLoad %27 %294 -%406 = OpFAdd %27 %405 %404 +%404 = OpImageSampleImplicitLod %25 %403 %402 +%405 = OpLoad %25 %294 +%406 = OpFAdd %25 %405 %404 OpStore %294 %406 -%407 = OpConvertUToF %10 %203 -%408 = OpCompositeConstruct %27 %311 %407 +%407 = OpConvertUToF %7 %203 +%408 = OpCompositeConstruct %25 %311 %407 %409 = OpSampledImage %400 %303 %304 -%410 = OpImageSampleExplicitLod %27 %409 %408 Lod %306 -%411 = OpLoad %27 %294 -%412 = OpFAdd %27 %411 %410 +%410 = OpImageSampleExplicitLod %25 %409 %408 Lod %306 +%411 = OpLoad %25 %294 +%412 = OpFAdd %25 %411 %410 OpStore %294 %412 -%413 = OpConvertUToF %10 %203 -%414 = OpCompositeConstruct %27 %311 %413 +%413 = OpConvertUToF %7 %203 +%414 = OpCompositeConstruct %25 %311 %413 %415 = OpSampledImage %400 %303 %304 -%416 = OpImageSampleImplicitLod %27 %415 %414 Bias %307 -%417 = OpLoad %27 %294 -%418 = OpFAdd %27 %417 %416 +%416 = OpImageSampleImplicitLod %25 %415 %414 Bias %307 +%417 = OpLoad %25 %294 +%418 = OpFAdd %25 %417 %416 OpStore %294 %418 -%419 = OpConvertSToF %10 %308 -%420 = OpCompositeConstruct %27 %311 %419 +%419 = OpConvertSToF %7 %308 +%420 = OpCompositeConstruct %25 %311 %419 %421 = OpSampledImage %400 %303 %304 -%422 = OpImageSampleImplicitLod %27 %421 %420 -%423 = OpLoad %27 %294 -%424 = OpFAdd %27 %423 %422 +%422 = OpImageSampleImplicitLod %25 %421 %420 +%423 = OpLoad %25 %294 +%424 = OpFAdd %25 %423 %422 OpStore %294 %424 -%425 = OpConvertSToF %10 %308 -%426 = OpCompositeConstruct %27 %311 %425 +%425 = OpConvertSToF %7 %308 +%426 = OpCompositeConstruct %25 %311 %425 %427 = OpSampledImage %400 %303 %304 -%428 = OpImageSampleExplicitLod %27 %427 %426 Lod %306 -%429 = OpLoad %27 %294 -%430 = OpFAdd %27 %429 %428 +%428 = OpImageSampleExplicitLod %25 %427 %426 Lod %306 +%429 = OpLoad %25 %294 +%430 = OpFAdd %25 %429 %428 OpStore %294 %430 -%431 = OpConvertSToF %10 %308 -%432 = OpCompositeConstruct %27 %311 %431 +%431 = OpConvertSToF %7 %308 +%432 = OpCompositeConstruct %25 %311 %431 %433 = OpSampledImage %400 %303 %304 -%434 = OpImageSampleImplicitLod %27 %433 %432 Bias %307 -%435 = OpLoad %27 %294 -%436 = OpFAdd %27 %435 %434 +%434 = OpImageSampleImplicitLod %25 %433 %432 Bias %307 +%435 = OpLoad %25 %294 +%436 = OpFAdd %25 %435 %434 OpStore %294 %436 -%437 = OpLoad %27 %294 +%437 = OpLoad %25 %294 OpStore %298 %437 OpReturn OpFunctionEnd %444 = OpFunction %2 None %83 %441 = OpLabel %438 = OpVariable %439 Function %440 -%445 = OpLoad %28 %70 -%446 = OpLoad %31 %72 -%447 = OpLoad %32 %74 -%448 = OpLoad %33 %76 +%445 = OpLoad %26 %70 +%446 = OpLoad %29 %72 +%447 = OpLoad %30 %74 +%448 = OpLoad %31 %76 OpBranch %449 %449 = OpLabel -%450 = OpCompositeConstruct %29 %305 %305 -%451 = OpCompositeConstruct %30 %305 %305 %305 +%450 = OpCompositeConstruct %27 %305 %305 +%451 = OpCompositeConstruct %28 %305 %305 %305 %453 = OpSampledImage %452 %446 %445 -%454 = OpImageSampleDrefImplicitLod %10 %453 %450 %305 -%455 = OpLoad %10 %438 -%456 = OpFAdd %10 %455 %454 +%454 = OpImageSampleDrefImplicitLod %7 %453 %450 %305 +%455 = OpLoad %7 %438 +%456 = OpFAdd %7 %455 %454 OpStore %438 %456 -%458 = OpConvertUToF %10 %203 -%459 = OpCompositeConstruct %30 %450 %458 +%458 = OpConvertUToF %7 %203 +%459 = OpCompositeConstruct %28 %450 %458 %460 = OpSampledImage %457 %447 %445 -%461 = OpImageSampleDrefImplicitLod %10 %460 %459 %305 -%462 = OpLoad %10 %438 -%463 = OpFAdd %10 %462 %461 +%461 = OpImageSampleDrefImplicitLod %7 %460 %459 %305 +%462 = OpLoad %7 %438 +%463 = OpFAdd %7 %462 %461 OpStore %438 %463 -%464 = OpConvertSToF %10 %308 -%465 = OpCompositeConstruct %30 %450 %464 +%464 = OpConvertSToF %7 %308 +%465 = OpCompositeConstruct %28 %450 %464 %466 = OpSampledImage %457 %447 %445 -%467 = OpImageSampleDrefImplicitLod %10 %466 %465 %305 -%468 = OpLoad %10 %438 -%469 = OpFAdd %10 %468 %467 +%467 = OpImageSampleDrefImplicitLod %7 %466 %465 %305 +%468 = OpLoad %7 %438 +%469 = OpFAdd %7 %468 %467 OpStore %438 %469 %471 = OpSampledImage %470 %448 %445 -%472 = OpImageSampleDrefImplicitLod %10 %471 %451 %305 -%473 = OpLoad %10 %438 -%474 = OpFAdd %10 %473 %472 +%472 = OpImageSampleDrefImplicitLod %7 %471 %451 %305 +%473 = OpLoad %7 %438 +%474 = OpFAdd %7 %473 %472 OpStore %438 %474 %475 = OpSampledImage %452 %446 %445 -%476 = OpImageSampleDrefExplicitLod %10 %475 %450 %305 Lod %477 -%478 = OpLoad %10 %438 -%479 = OpFAdd %10 %478 %476 +%476 = OpImageSampleDrefExplicitLod %7 %475 %450 %305 Lod %477 +%478 = OpLoad %7 %438 +%479 = OpFAdd %7 %478 %476 OpStore %438 %479 -%480 = OpConvertUToF %10 %203 -%481 = OpCompositeConstruct %30 %450 %480 +%480 = OpConvertUToF %7 %203 +%481 = OpCompositeConstruct %28 %450 %480 %482 = OpSampledImage %457 %447 %445 -%483 = OpImageSampleDrefExplicitLod %10 %482 %481 %305 Lod %477 -%484 = OpLoad %10 %438 -%485 = OpFAdd %10 %484 %483 +%483 = OpImageSampleDrefExplicitLod %7 %482 %481 %305 Lod %477 +%484 = OpLoad %7 %438 +%485 = OpFAdd %7 %484 %483 OpStore %438 %485 -%486 = OpConvertSToF %10 %308 -%487 = OpCompositeConstruct %30 %450 %486 +%486 = OpConvertSToF %7 %308 +%487 = OpCompositeConstruct %28 %450 %486 %488 = OpSampledImage %457 %447 %445 -%489 = OpImageSampleDrefExplicitLod %10 %488 %487 %305 Lod %477 -%490 = OpLoad %10 %438 -%491 = OpFAdd %10 %490 %489 +%489 = OpImageSampleDrefExplicitLod %7 %488 %487 %305 Lod %477 +%490 = OpLoad %7 %438 +%491 = OpFAdd %7 %490 %489 OpStore %438 %491 %492 = OpSampledImage %470 %448 %445 -%493 = OpImageSampleDrefExplicitLod %10 %492 %451 %305 Lod %477 -%494 = OpLoad %10 %438 -%495 = OpFAdd %10 %494 %493 +%493 = OpImageSampleDrefExplicitLod %7 %492 %451 %305 Lod %477 +%494 = OpLoad %7 %438 +%495 = OpFAdd %7 %494 %493 OpStore %438 %495 -%496 = OpLoad %10 %438 +%496 = OpLoad %7 %438 OpStore %442 %496 OpReturn OpFunctionEnd %499 = OpFunction %2 None %83 %497 = OpLabel -%500 = OpLoad %20 %53 -%501 = OpLoad %6 %55 -%502 = OpLoad %21 %56 -%503 = OpLoad %28 %68 -%504 = OpLoad %28 %70 -%505 = OpLoad %31 %72 +%500 = OpLoad %18 %53 +%501 = OpLoad %3 %55 +%502 = OpLoad %19 %56 +%503 = OpLoad %26 %68 +%504 = OpLoad %26 %70 +%505 = OpLoad %29 %72 OpBranch %506 %506 = OpLabel -%507 = OpCompositeConstruct %29 %305 %305 +%507 = OpCompositeConstruct %27 %305 %305 %508 = OpSampledImage %318 %500 %503 -%509 = OpImageGather %27 %508 %507 %510 +%509 = OpImageGather %25 %508 %507 %510 %511 = OpSampledImage %318 %500 %503 -%512 = OpImageGather %27 %511 %507 %513 ConstOffset %34 +%512 = OpImageGather %25 %511 %507 %513 ConstOffset %34 %514 = OpSampledImage %452 %505 %504 -%515 = OpImageDrefGather %27 %514 %507 %305 +%515 = OpImageDrefGather %25 %514 %507 %305 %516 = OpSampledImage %452 %505 %504 -%517 = OpImageDrefGather %27 %516 %507 %305 ConstOffset %34 +%517 = OpImageDrefGather %25 %516 %507 %305 ConstOffset %34 %519 = OpSampledImage %518 %501 %503 -%520 = OpImageGather %18 %519 %507 %203 +%520 = OpImageGather %16 %519 %507 %203 %523 = OpSampledImage %522 %502 %503 %524 = OpImageGather %521 %523 %507 %203 -%525 = OpConvertUToF %27 %520 -%526 = OpConvertSToF %27 %524 -%527 = OpFAdd %27 %525 %526 -%528 = OpFAdd %27 %509 %512 -%529 = OpFAdd %27 %528 %515 -%530 = OpFAdd %27 %529 %517 -%531 = OpFAdd %27 %530 %527 +%525 = OpConvertUToF %25 %520 +%526 = OpConvertSToF %25 %524 +%527 = OpFAdd %25 %525 %526 +%528 = OpFAdd %25 %509 %512 +%529 = OpFAdd %25 %528 %515 +%530 = OpFAdd %25 %529 %517 +%531 = OpFAdd %25 %530 %527 OpStore %498 %531 OpReturn OpFunctionEnd %534 = OpFunction %2 None %83 %532 = OpLabel -%535 = OpLoad %28 %68 -%536 = OpLoad %31 %72 +%535 = OpLoad %26 %68 +%536 = OpLoad %29 %72 OpBranch %537 %537 = OpLabel -%538 = OpCompositeConstruct %29 %305 %305 +%538 = OpCompositeConstruct %27 %305 %305 %539 = OpSampledImage %452 %536 %535 -%540 = OpImageSampleImplicitLod %27 %539 %538 -%541 = OpCompositeExtract %10 %540 0 +%540 = OpImageSampleImplicitLod %25 %539 %538 +%541 = OpCompositeExtract %7 %540 0 %542 = OpSampledImage %452 %536 %535 -%543 = OpImageGather %27 %542 %538 %203 -%544 = OpCompositeConstruct %27 %541 %541 %541 %541 -%545 = OpFAdd %27 %544 %543 +%543 = OpImageGather %25 %542 %538 %203 +%544 = OpCompositeConstruct %25 %541 %541 %541 %541 +%545 = OpFAdd %25 %544 %543 OpStore %533 %545 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index 533a3daa5..df5e3edda 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -7,61 +7,61 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %31 "compute" %19 %22 %24 %27 %29 OpExecutionMode %31 LocalSize 1 1 1 +OpMemberDecorate %5 0 Offset 0 +OpMemberDecorate %5 1 Offset 16 OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %7 1 Offset 16 -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 4 -OpMemberDecorate %9 2 Offset 8 -OpDecorate %11 ArrayStride 4 -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %15 0 Offset 0 +OpMemberDecorate %7 1 Offset 4 +OpMemberDecorate %7 2 Offset 8 +OpDecorate %9 ArrayStride 4 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %13 0 Offset 0 OpDecorate %19 BuiltIn GlobalInvocationId OpDecorate %22 BuiltIn LocalInvocationId OpDecorate %24 BuiltIn LocalInvocationIndex OpDecorate %27 BuiltIn WorkgroupId OpDecorate %29 BuiltIn NumWorkgroups %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 1 -%6 = OpTypeFloat 32 -%5 = OpTypeVector %6 4 -%7 = OpTypeStruct %5 %6 -%8 = OpTypeInt 32 0 -%9 = OpTypeStruct %6 %8 %6 -%10 = OpTypeBool -%12 = OpConstant %8 1 -%11 = OpTypeArray %8 %12 -%13 = OpTypeVector %8 3 -%14 = OpTypeStruct %8 -%15 = OpTypeStruct %8 -%17 = OpTypePointer Workgroup %11 +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%5 = OpTypeStruct %3 %4 +%6 = OpTypeInt 32 0 +%7 = OpTypeStruct %4 %6 %4 +%8 = OpTypeBool +%10 = OpConstant %6 1 +%9 = OpTypeArray %6 %10 +%11 = OpTypeVector %6 3 +%12 = OpTypeStruct %6 +%13 = OpTypeStruct %6 +%15 = OpTypeInt 32 1 +%14 = OpConstant %15 1 +%17 = OpTypePointer Workgroup %9 %16 = OpVariable %17 Workgroup -%20 = OpTypePointer Input %13 +%20 = OpTypePointer Input %11 %19 = OpVariable %20 Input %22 = OpVariable %20 Input -%25 = OpTypePointer Input %8 +%25 = OpTypePointer Input %6 %24 = OpVariable %25 Input %27 = OpVariable %20 Input %29 = OpVariable %20 Input %32 = OpTypeFunction %2 -%34 = OpConstantNull %11 -%35 = OpConstantNull %13 -%36 = OpTypeVector %10 3 -%41 = OpConstant %8 2 -%42 = OpConstant %8 264 -%44 = OpTypePointer Workgroup %8 -%53 = OpConstant %8 0 +%34 = OpConstantNull %9 +%35 = OpConstantNull %11 +%36 = OpTypeVector %8 3 +%41 = OpConstant %6 2 +%42 = OpConstant %6 264 +%44 = OpTypePointer Workgroup %6 +%53 = OpConstant %6 0 %31 = OpFunction %2 None %32 %18 = OpLabel -%21 = OpLoad %13 %19 -%23 = OpLoad %13 %22 -%26 = OpLoad %8 %24 -%28 = OpLoad %13 %27 -%30 = OpLoad %13 %29 +%21 = OpLoad %11 %19 +%23 = OpLoad %11 %22 +%26 = OpLoad %6 %24 +%28 = OpLoad %11 %27 +%30 = OpLoad %11 %29 OpBranch %33 %33 = OpLabel %37 = OpIEqual %36 %23 %35 -%38 = OpAll %10 %37 +%38 = OpAll %8 %37 OpSelectionMerge %39 None OpBranchConditional %38 %40 %39 %40 = OpLabel @@ -71,14 +71,14 @@ OpBranch %39 OpControlBarrier %41 %41 %42 OpBranch %43 %43 = OpLabel -%45 = OpCompositeExtract %8 %21 0 -%46 = OpCompositeExtract %8 %23 0 -%47 = OpIAdd %8 %45 %46 -%48 = OpIAdd %8 %47 %26 -%49 = OpCompositeExtract %8 %28 0 -%50 = OpIAdd %8 %48 %49 -%51 = OpCompositeExtract %8 %30 0 -%52 = OpIAdd %8 %50 %51 +%45 = OpCompositeExtract %6 %21 0 +%46 = OpCompositeExtract %6 %23 0 +%47 = OpIAdd %6 %45 %46 +%48 = OpIAdd %6 %47 %26 +%49 = OpCompositeExtract %6 %28 0 +%50 = OpIAdd %6 %48 %49 +%51 = OpCompositeExtract %6 %30 0 +%52 = OpIAdd %6 %50 %51 %54 = OpAccessChain %44 %16 %53 OpStore %54 %52 OpReturn diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 795ed31d7..6acbab9d7 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -9,14 +9,14 @@ OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %37 "fragment" %18 %21 %24 %27 %30 %32 %34 %36 OpExecutionMode %37 OriginUpperLeft OpExecutionMode %37 DepthReplacing +OpMemberDecorate %5 0 Offset 0 +OpMemberDecorate %5 1 Offset 16 OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %7 1 Offset 16 -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 4 -OpMemberDecorate %9 2 Offset 8 -OpDecorate %11 ArrayStride 4 -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %15 0 Offset 0 +OpMemberDecorate %7 1 Offset 4 +OpMemberDecorate %7 2 Offset 8 +OpDecorate %9 ArrayStride 4 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %13 0 Offset 0 OpDecorate %18 Invariant OpDecorate %18 BuiltIn FragCoord OpDecorate %21 Location 1 @@ -30,59 +30,59 @@ OpDecorate %32 BuiltIn FragDepth OpDecorate %34 BuiltIn SampleMask OpDecorate %36 Location 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 1 -%6 = OpTypeFloat 32 -%5 = OpTypeVector %6 4 -%7 = OpTypeStruct %5 %6 -%8 = OpTypeInt 32 0 -%9 = OpTypeStruct %6 %8 %6 -%10 = OpTypeBool -%12 = OpConstant %8 1 -%11 = OpTypeArray %8 %12 -%13 = OpTypeVector %8 3 -%14 = OpTypeStruct %8 -%15 = OpTypeStruct %8 -%19 = OpTypePointer Input %5 +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%5 = OpTypeStruct %3 %4 +%6 = OpTypeInt 32 0 +%7 = OpTypeStruct %4 %6 %4 +%8 = OpTypeBool +%10 = OpConstant %6 1 +%9 = OpTypeArray %6 %10 +%11 = OpTypeVector %6 3 +%12 = OpTypeStruct %6 +%13 = OpTypeStruct %6 +%15 = OpTypeInt 32 1 +%14 = OpConstant %15 1 +%19 = OpTypePointer Input %3 %18 = OpVariable %19 Input -%22 = OpTypePointer Input %6 +%22 = OpTypePointer Input %4 %21 = OpVariable %22 Input -%25 = OpTypePointer Input %10 +%25 = OpTypePointer Input %8 %24 = OpVariable %25 Input -%28 = OpTypePointer Input %8 +%28 = OpTypePointer Input %6 %27 = OpVariable %28 Input %30 = OpVariable %28 Input -%33 = OpTypePointer Output %6 +%33 = OpTypePointer Output %4 %32 = OpVariable %33 Output -%35 = OpTypePointer Output %8 +%35 = OpTypePointer Output %6 %34 = OpVariable %35 Output %36 = OpVariable %33 Output %38 = OpTypeFunction %2 -%39 = OpConstant %6 0.0 -%40 = OpConstant %6 1.0 +%39 = OpConstant %4 0.0 +%40 = OpConstant %4 1.0 %37 = OpFunction %2 None %38 %16 = OpLabel -%20 = OpLoad %5 %18 -%23 = OpLoad %6 %21 -%17 = OpCompositeConstruct %7 %20 %23 -%26 = OpLoad %10 %24 -%29 = OpLoad %8 %27 -%31 = OpLoad %8 %30 +%20 = OpLoad %3 %18 +%23 = OpLoad %4 %21 +%17 = OpCompositeConstruct %5 %20 %23 +%26 = OpLoad %8 %24 +%29 = OpLoad %6 %27 +%31 = OpLoad %6 %30 OpBranch %41 %41 = OpLabel -%42 = OpShiftLeftLogical %8 %12 %29 -%43 = OpBitwiseAnd %8 %31 %42 -%44 = OpSelect %6 %26 %40 %39 -%45 = OpCompositeExtract %6 %17 1 -%46 = OpCompositeConstruct %9 %45 %43 %44 -%47 = OpCompositeExtract %6 %46 0 +%42 = OpShiftLeftLogical %6 %10 %29 +%43 = OpBitwiseAnd %6 %31 %42 +%44 = OpSelect %4 %26 %40 %39 +%45 = OpCompositeExtract %4 %17 1 +%46 = OpCompositeConstruct %7 %45 %43 %44 +%47 = OpCompositeExtract %4 %46 0 OpStore %32 %47 -%48 = OpLoad %6 %32 -%49 = OpExtInst %6 %1 FClamp %48 %39 %40 +%48 = OpLoad %4 %32 +%49 = OpExtInst %4 %1 FClamp %48 %39 %40 OpStore %32 %49 -%50 = OpCompositeExtract %8 %46 1 +%50 = OpCompositeExtract %6 %46 1 OpStore %34 %50 -%51 = OpCompositeExtract %6 %46 2 +%51 = OpCompositeExtract %4 %46 2 OpStore %36 %51 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index 28b842dbe..6e930aa01 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -6,14 +6,14 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %31 "vertex" %17 %20 %22 %24 %26 %28 +OpMemberDecorate %5 0 Offset 0 +OpMemberDecorate %5 1 Offset 16 OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %7 1 Offset 16 -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 4 -OpMemberDecorate %9 2 Offset 8 -OpDecorate %11 ArrayStride 4 -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %15 0 Offset 0 +OpMemberDecorate %7 1 Offset 4 +OpMemberDecorate %7 2 Offset 8 +OpDecorate %9 ArrayStride 4 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %13 0 Offset 0 OpDecorate %17 BuiltIn VertexIndex OpDecorate %20 BuiltIn InstanceIndex OpDecorate %22 Location 10 @@ -22,47 +22,47 @@ OpDecorate %24 BuiltIn Position OpDecorate %26 Location 1 OpDecorate %28 BuiltIn PointSize %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 1 -%6 = OpTypeFloat 32 -%5 = OpTypeVector %6 4 -%7 = OpTypeStruct %5 %6 -%8 = OpTypeInt 32 0 -%9 = OpTypeStruct %6 %8 %6 -%10 = OpTypeBool -%12 = OpConstant %8 1 -%11 = OpTypeArray %8 %12 -%13 = OpTypeVector %8 3 -%14 = OpTypeStruct %8 -%15 = OpTypeStruct %8 -%18 = OpTypePointer Input %8 +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%5 = OpTypeStruct %3 %4 +%6 = OpTypeInt 32 0 +%7 = OpTypeStruct %4 %6 %4 +%8 = OpTypeBool +%10 = OpConstant %6 1 +%9 = OpTypeArray %6 %10 +%11 = OpTypeVector %6 3 +%12 = OpTypeStruct %6 +%13 = OpTypeStruct %6 +%15 = OpTypeInt 32 1 +%14 = OpConstant %15 1 +%18 = OpTypePointer Input %6 %17 = OpVariable %18 Input %20 = OpVariable %18 Input %22 = OpVariable %18 Input -%25 = OpTypePointer Output %5 +%25 = OpTypePointer Output %3 %24 = OpVariable %25 Output -%27 = OpTypePointer Output %6 +%27 = OpTypePointer Output %4 %26 = OpVariable %27 Output -%29 = OpTypePointer Output %6 +%29 = OpTypePointer Output %4 %28 = OpVariable %29 Output -%30 = OpConstant %6 1.0 +%30 = OpConstant %4 1.0 %32 = OpTypeFunction %2 %31 = OpFunction %2 None %32 %16 = OpLabel -%19 = OpLoad %8 %17 -%21 = OpLoad %8 %20 -%23 = OpLoad %8 %22 +%19 = OpLoad %6 %17 +%21 = OpLoad %6 %20 +%23 = OpLoad %6 %22 OpStore %28 %30 OpBranch %33 %33 = OpLabel -%34 = OpIAdd %8 %19 %21 -%35 = OpIAdd %8 %34 %23 -%36 = OpCompositeConstruct %5 %30 %30 %30 %30 -%37 = OpConvertUToF %6 %35 -%38 = OpCompositeConstruct %7 %36 %37 -%39 = OpCompositeExtract %5 %38 0 +%34 = OpIAdd %6 %19 %21 +%35 = OpIAdd %6 %34 %23 +%36 = OpCompositeConstruct %3 %30 %30 %30 %30 +%37 = OpConvertUToF %4 %35 +%38 = OpCompositeConstruct %5 %36 %37 +%39 = OpCompositeExtract %3 %38 0 OpStore %24 %39 -%40 = OpCompositeExtract %6 %38 1 +%40 = OpCompositeExtract %4 %38 1 OpStore %26 %40 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index 5f555c019..db2bf9b99 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -6,64 +6,64 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %32 "vertex_two_structs" %21 %25 %27 %29 +OpMemberDecorate %5 0 Offset 0 +OpMemberDecorate %5 1 Offset 16 OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %7 1 Offset 16 -OpMemberDecorate %9 0 Offset 0 -OpMemberDecorate %9 1 Offset 4 -OpMemberDecorate %9 2 Offset 8 -OpDecorate %11 ArrayStride 4 -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %15 0 Offset 0 +OpMemberDecorate %7 1 Offset 4 +OpMemberDecorate %7 2 Offset 8 +OpDecorate %9 ArrayStride 4 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %13 0 Offset 0 OpDecorate %21 BuiltIn VertexIndex OpDecorate %25 BuiltIn InstanceIndex OpDecorate %27 Invariant OpDecorate %27 BuiltIn Position OpDecorate %29 BuiltIn PointSize %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 1 -%6 = OpTypeFloat 32 -%5 = OpTypeVector %6 4 -%7 = OpTypeStruct %5 %6 -%8 = OpTypeInt 32 0 -%9 = OpTypeStruct %6 %8 %6 -%10 = OpTypeBool -%12 = OpConstant %8 1 -%11 = OpTypeArray %8 %12 -%13 = OpTypeVector %8 3 -%14 = OpTypeStruct %8 -%15 = OpTypeStruct %8 -%17 = OpTypePointer Function %8 -%18 = OpConstantNull %8 -%22 = OpTypePointer Input %8 +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%5 = OpTypeStruct %3 %4 +%6 = OpTypeInt 32 0 +%7 = OpTypeStruct %4 %6 %4 +%8 = OpTypeBool +%10 = OpConstant %6 1 +%9 = OpTypeArray %6 %10 +%11 = OpTypeVector %6 3 +%12 = OpTypeStruct %6 +%13 = OpTypeStruct %6 +%15 = OpTypeInt 32 1 +%14 = OpConstant %15 1 +%17 = OpTypePointer Function %6 +%18 = OpConstantNull %6 +%22 = OpTypePointer Input %6 %21 = OpVariable %22 Input %25 = OpVariable %22 Input -%28 = OpTypePointer Output %5 +%28 = OpTypePointer Output %3 %27 = OpVariable %28 Output -%30 = OpTypePointer Output %6 +%30 = OpTypePointer Output %4 %29 = OpVariable %30 Output -%31 = OpConstant %6 1.0 +%31 = OpConstant %4 1.0 %33 = OpTypeFunction %2 -%34 = OpConstant %8 2 -%35 = OpConstant %6 0.0 +%34 = OpConstant %6 2 +%35 = OpConstant %4 0.0 %32 = OpFunction %2 None %33 %19 = OpLabel %16 = OpVariable %17 Function %18 -%23 = OpLoad %8 %21 -%20 = OpCompositeConstruct %14 %23 -%26 = OpLoad %8 %25 -%24 = OpCompositeConstruct %15 %26 +%23 = OpLoad %6 %21 +%20 = OpCompositeConstruct %12 %23 +%26 = OpLoad %6 %25 +%24 = OpCompositeConstruct %13 %26 OpStore %29 %31 OpBranch %36 %36 = OpLabel OpStore %16 %34 -%37 = OpCompositeExtract %8 %20 0 -%38 = OpConvertUToF %6 %37 -%39 = OpCompositeExtract %8 %24 0 -%40 = OpConvertUToF %6 %39 -%41 = OpLoad %8 %16 -%42 = OpConvertUToF %6 %41 -%43 = OpCompositeConstruct %5 %38 %40 %42 %35 +%37 = OpCompositeExtract %6 %20 0 +%38 = OpConvertUToF %4 %37 +%39 = OpCompositeExtract %6 %24 0 +%40 = OpConvertUToF %4 %39 +%41 = OpLoad %6 %16 +%42 = OpConvertUToF %4 %41 +%43 = OpCompositeConstruct %3 %38 %40 %42 %35 OpStore %27 %43 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 783b789c2..6e0a51467 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -7,187 +7,187 @@ OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %579 "main" OpExecutionMode %579 LocalSize 1 1 1 -OpMemberDecorate %17 0 Offset 0 -OpMemberDecorate %17 1 Offset 16 -OpDecorate %22 ArrayStride 32 -OpDecorate %24 ArrayStride 4 +OpMemberDecorate %12 0 Offset 0 +OpMemberDecorate %12 1 Offset 16 +OpDecorate %17 ArrayStride 32 +OpDecorate %19 ArrayStride 4 %2 = OpTypeVoid %4 = OpTypeFloat 32 -%3 = OpConstant %4 1.0 -%5 = OpConstant %4 0.0 -%6 = OpConstant %4 0.5 -%8 = OpTypeInt 32 1 -%7 = OpConstant %8 1 -%9 = OpConstant %8 3 -%10 = OpTypeVector %4 4 -%11 = OpTypeVector %8 4 -%13 = OpTypeBool -%12 = OpTypeVector %13 4 -%14 = OpTypeVector %4 2 -%15 = OpTypeVector %4 3 -%16 = OpTypeVector %13 3 -%17 = OpTypeStruct %10 %8 -%18 = OpTypeMatrix %14 2 -%19 = OpTypeMatrix %10 4 -%20 = OpTypeInt 32 0 -%21 = OpTypeVector %20 2 -%23 = OpConstant %20 3 -%22 = OpTypeArray %17 %23 -%25 = OpConstant %20 4 -%24 = OpTypeArray %8 %25 -%26 = OpTypeMatrix %15 2 -%27 = OpTypeMatrix %15 3 -%28 = OpTypeMatrix %15 4 -%29 = OpTypeMatrix %10 3 -%30 = OpTypeVector %8 3 -%31 = OpConstantComposite %10 %3 %3 %3 %3 -%32 = OpConstantComposite %10 %5 %5 %5 %5 -%33 = OpConstantComposite %10 %6 %6 %6 %6 -%34 = OpConstantComposite %11 %7 %7 %7 %7 -%37 = OpTypeFunction %10 -%38 = OpConstantTrue %13 -%39 = OpConstant %8 0 -%40 = OpConstantFalse %13 +%3 = OpTypeVector %4 4 +%6 = OpTypeInt 32 1 +%5 = OpTypeVector %6 4 +%8 = OpTypeBool +%7 = OpTypeVector %8 4 +%9 = OpTypeVector %4 2 +%10 = OpTypeVector %4 3 +%11 = OpTypeVector %8 3 +%12 = OpTypeStruct %3 %6 +%13 = OpTypeMatrix %9 2 +%14 = OpTypeMatrix %3 4 +%15 = OpTypeInt 32 0 +%16 = OpTypeVector %15 2 +%18 = OpConstant %15 3 +%17 = OpTypeArray %12 %18 +%20 = OpConstant %15 4 +%19 = OpTypeArray %6 %20 +%21 = OpTypeMatrix %10 2 +%22 = OpTypeMatrix %10 3 +%23 = OpTypeMatrix %10 4 +%24 = OpTypeMatrix %3 3 +%25 = OpTypeVector %6 3 +%26 = OpConstant %4 1.0 +%27 = OpConstantComposite %3 %26 %26 %26 %26 +%28 = OpConstant %4 0.0 +%29 = OpConstantComposite %3 %28 %28 %28 %28 +%30 = OpConstant %4 0.5 +%31 = OpConstantComposite %3 %30 %30 %30 %30 +%32 = OpConstant %6 1 +%33 = OpConstantComposite %5 %32 %32 %32 %32 +%34 = OpConstant %6 3 +%37 = OpTypeFunction %3 +%38 = OpConstantTrue %8 +%39 = OpConstant %6 0 +%40 = OpConstantFalse %8 %41 = OpConstant %4 0.1 %66 = OpConstant %4 2.0 %67 = OpConstant %4 3.0 %68 = OpConstant %4 4.0 -%69 = OpConstant %8 5 -%70 = OpConstant %8 2 -%86 = OpTypePointer Function %14 -%87 = OpConstantNull %14 -%90 = OpTypeFunction %14 -%106 = OpTypeFunction %15 %15 -%108 = OpConstantComposite %15 %5 %5 %5 -%110 = OpConstantComposite %15 %3 %3 %3 -%113 = OpTypePointer Function %17 -%114 = OpConstantNull %17 +%69 = OpConstant %6 5 +%70 = OpConstant %6 2 +%86 = OpTypePointer Function %9 +%87 = OpConstantNull %9 +%90 = OpTypeFunction %9 +%106 = OpTypeFunction %10 %10 +%108 = OpConstantComposite %10 %28 %28 %28 +%110 = OpConstantComposite %10 %26 %26 %26 +%113 = OpTypePointer Function %12 +%114 = OpConstantNull %12 %117 = OpTypeFunction %4 -%118 = OpConstantNull %13 -%119 = OpConstantNull %8 -%120 = OpConstantNull %20 +%118 = OpConstantNull %8 +%119 = OpConstantNull %6 +%120 = OpConstantNull %15 %121 = OpConstantNull %4 -%122 = OpConstantNull %21 -%123 = OpConstantNull %18 -%124 = OpConstantNull %22 -%125 = OpConstantNull %17 -%126 = OpConstant %20 0 -%127 = OpConstantNull %13 -%128 = OpConstantNull %8 -%129 = OpConstantNull %20 +%122 = OpConstantNull %16 +%123 = OpConstantNull %13 +%124 = OpConstantNull %17 +%125 = OpConstantNull %12 +%126 = OpConstant %15 0 +%127 = OpConstantNull %8 +%128 = OpConstantNull %6 +%129 = OpConstantNull %15 %130 = OpConstantNull %4 -%131 = OpConstantNull %21 -%132 = OpConstantNull %26 -%133 = OpConstantNull %21 -%134 = OpConstantNull %26 -%159 = OpTypePointer Function %10 +%131 = OpConstantNull %16 +%132 = OpConstantNull %21 +%133 = OpConstantNull %16 +%134 = OpConstantNull %21 +%159 = OpTypePointer Function %3 %160 = OpTypePointer Function %4 %165 = OpTypeFunction %2 -%168 = OpTypeVector %13 2 +%168 = OpTypeVector %8 2 %183 = OpConstant %4 -1.0 -%184 = OpConstant %20 2 -%185 = OpConstant %20 1 -%186 = OpConstantNull %27 -%187 = OpConstantNull %27 -%188 = OpConstantNull %27 -%189 = OpConstantNull %27 -%190 = OpConstantNull %27 -%191 = OpConstantNull %27 -%192 = OpConstantNull %28 -%193 = OpConstantNull %28 -%194 = OpConstantNull %28 -%195 = OpConstantNull %29 -%197 = OpTypeVector %8 2 -%208 = OpTypeVector %20 3 -%505 = OpTypePointer Function %8 -%506 = OpConstantNull %8 -%508 = OpTypePointer Function %30 -%509 = OpConstantNull %30 -%512 = OpConstantNull %30 -%540 = OpTypePointer Function %8 -%551 = OpConstant %8 -1 -%552 = OpConstant %8 -2 -%553 = OpConstant %8 -3 -%554 = OpConstant %8 4 -%555 = OpConstant %8 -5 -%556 = OpConstant %8 6 -%557 = OpConstant %8 -7 -%558 = OpConstant %8 -8 -%36 = OpFunction %10 None %37 +%184 = OpConstant %15 2 +%185 = OpConstant %15 1 +%186 = OpConstantNull %22 +%187 = OpConstantNull %22 +%188 = OpConstantNull %22 +%189 = OpConstantNull %22 +%190 = OpConstantNull %22 +%191 = OpConstantNull %22 +%192 = OpConstantNull %23 +%193 = OpConstantNull %23 +%194 = OpConstantNull %23 +%195 = OpConstantNull %24 +%197 = OpTypeVector %6 2 +%208 = OpTypeVector %15 3 +%505 = OpTypePointer Function %6 +%506 = OpConstantNull %6 +%508 = OpTypePointer Function %25 +%509 = OpConstantNull %25 +%512 = OpConstantNull %25 +%540 = OpTypePointer Function %6 +%551 = OpConstant %6 -1 +%552 = OpConstant %6 -2 +%553 = OpConstant %6 -3 +%554 = OpConstant %6 4 +%555 = OpConstant %6 -5 +%556 = OpConstant %6 6 +%557 = OpConstant %6 -7 +%558 = OpConstant %6 -8 +%36 = OpFunction %3 None %37 %35 = OpLabel OpBranch %42 %42 = OpLabel -%43 = OpSelect %8 %38 %7 %39 -%45 = OpCompositeConstruct %12 %38 %38 %38 %38 -%44 = OpSelect %10 %45 %31 %32 -%46 = OpCompositeConstruct %12 %40 %40 %40 %40 -%47 = OpSelect %10 %46 %32 %31 -%48 = OpExtInst %10 %1 FMix %32 %31 %33 -%50 = OpCompositeConstruct %10 %41 %41 %41 %41 -%49 = OpExtInst %10 %1 FMix %32 %31 %50 -%51 = OpCompositeExtract %8 %34 0 +%43 = OpSelect %6 %38 %32 %39 +%45 = OpCompositeConstruct %7 %38 %38 %38 %38 +%44 = OpSelect %3 %45 %27 %29 +%46 = OpCompositeConstruct %7 %40 %40 %40 %40 +%47 = OpSelect %3 %46 %29 %27 +%48 = OpExtInst %3 %1 FMix %29 %27 %31 +%50 = OpCompositeConstruct %3 %41 %41 %41 %41 +%49 = OpExtInst %3 %1 FMix %29 %27 %50 +%51 = OpCompositeExtract %6 %33 0 %52 = OpBitcast %4 %51 -%53 = OpBitcast %10 %34 -%54 = OpConvertFToS %11 %32 -%55 = OpCompositeConstruct %11 %43 %43 %43 %43 -%56 = OpIAdd %11 %55 %54 -%57 = OpConvertSToF %10 %56 -%58 = OpFAdd %10 %57 %44 -%59 = OpFAdd %10 %58 %48 -%60 = OpFAdd %10 %59 %49 -%61 = OpCompositeConstruct %10 %52 %52 %52 %52 -%62 = OpFAdd %10 %60 %61 -%63 = OpFAdd %10 %62 %53 +%53 = OpBitcast %3 %33 +%54 = OpConvertFToS %5 %29 +%55 = OpCompositeConstruct %5 %43 %43 %43 %43 +%56 = OpIAdd %5 %55 %54 +%57 = OpConvertSToF %3 %56 +%58 = OpFAdd %3 %57 %44 +%59 = OpFAdd %3 %58 %48 +%60 = OpFAdd %3 %59 %49 +%61 = OpCompositeConstruct %3 %52 %52 %52 %52 +%62 = OpFAdd %3 %60 %61 +%63 = OpFAdd %3 %62 %53 OpReturnValue %63 OpFunctionEnd -%65 = OpFunction %10 None %37 +%65 = OpFunction %3 None %37 %64 = OpLabel OpBranch %71 %71 = OpLabel -%72 = OpCompositeConstruct %14 %66 %66 -%73 = OpCompositeConstruct %14 %3 %3 -%74 = OpFAdd %14 %73 %72 -%75 = OpCompositeConstruct %14 %67 %67 -%76 = OpFSub %14 %74 %75 -%77 = OpCompositeConstruct %14 %68 %68 -%78 = OpFDiv %14 %76 %77 -%79 = OpCompositeConstruct %11 %69 %69 %69 %69 -%80 = OpCompositeConstruct %11 %70 %70 %70 %70 -%81 = OpSRem %11 %79 %80 -%82 = OpVectorShuffle %10 %78 %78 0 1 0 1 -%83 = OpConvertSToF %10 %81 -%84 = OpFAdd %10 %82 %83 +%72 = OpCompositeConstruct %9 %66 %66 +%73 = OpCompositeConstruct %9 %26 %26 +%74 = OpFAdd %9 %73 %72 +%75 = OpCompositeConstruct %9 %67 %67 +%76 = OpFSub %9 %74 %75 +%77 = OpCompositeConstruct %9 %68 %68 +%78 = OpFDiv %9 %76 %77 +%79 = OpCompositeConstruct %5 %69 %69 %69 %69 +%80 = OpCompositeConstruct %5 %70 %70 %70 %70 +%81 = OpSRem %5 %79 %80 +%82 = OpVectorShuffle %3 %78 %78 0 1 0 1 +%83 = OpConvertSToF %3 %81 +%84 = OpFAdd %3 %82 %83 OpReturnValue %84 OpFunctionEnd -%89 = OpFunction %14 None %90 +%89 = OpFunction %9 None %90 %88 = OpLabel %85 = OpVariable %86 Function %87 OpBranch %91 %91 = OpLabel -%92 = OpCompositeConstruct %14 %66 %66 +%92 = OpCompositeConstruct %9 %66 %66 OpStore %85 %92 -%93 = OpLoad %14 %85 -%94 = OpCompositeConstruct %14 %3 %3 -%95 = OpFAdd %14 %93 %94 +%93 = OpLoad %9 %85 +%94 = OpCompositeConstruct %9 %26 %26 +%95 = OpFAdd %9 %93 %94 OpStore %85 %95 -%96 = OpLoad %14 %85 -%97 = OpCompositeConstruct %14 %67 %67 -%98 = OpFSub %14 %96 %97 +%96 = OpLoad %9 %85 +%97 = OpCompositeConstruct %9 %67 %67 +%98 = OpFSub %9 %96 %97 OpStore %85 %98 -%99 = OpLoad %14 %85 -%100 = OpCompositeConstruct %14 %68 %68 -%101 = OpFDiv %14 %99 %100 +%99 = OpLoad %9 %85 +%100 = OpCompositeConstruct %9 %68 %68 +%101 = OpFDiv %9 %99 %100 OpStore %85 %101 -%102 = OpLoad %14 %85 +%102 = OpLoad %9 %85 OpReturnValue %102 OpFunctionEnd -%105 = OpFunction %15 None %106 -%104 = OpFunctionParameter %15 +%105 = OpFunction %10 None %106 +%104 = OpFunctionParameter %10 %103 = OpLabel OpBranch %107 %107 = OpLabel -%109 = OpFUnordNotEqual %16 %104 %108 -%111 = OpSelect %15 %109 %110 %108 +%109 = OpFUnordNotEqual %11 %104 %108 +%111 = OpSelect %10 %109 %110 %108 OpReturnValue %111 OpFunctionEnd %116 = OpFunction %4 None %117 @@ -195,24 +195,24 @@ OpFunctionEnd %112 = OpVariable %113 Function %114 OpBranch %135 %135 = OpLabel -%136 = OpCompositeConstruct %10 %3 %3 %3 %3 -%137 = OpCompositeConstruct %17 %136 %7 +%136 = OpCompositeConstruct %3 %26 %26 %26 %26 +%137 = OpCompositeConstruct %12 %136 %32 OpStore %112 %137 -%138 = OpCompositeConstruct %14 %3 %5 -%139 = OpCompositeConstruct %14 %5 %3 -%140 = OpCompositeConstruct %18 %138 %139 -%141 = OpCompositeConstruct %10 %3 %5 %5 %5 -%142 = OpCompositeConstruct %10 %5 %3 %5 %5 -%143 = OpCompositeConstruct %10 %5 %5 %3 %5 -%144 = OpCompositeConstruct %10 %5 %5 %5 %3 -%145 = OpCompositeConstruct %19 %141 %142 %143 %144 -%146 = OpCompositeConstruct %21 %126 %126 -%147 = OpCompositeConstruct %14 %5 %5 -%148 = OpCompositeConstruct %14 %5 %5 -%149 = OpCompositeConstruct %18 %147 %148 -%150 = OpCompositeConstruct %24 %39 %7 %70 %9 -%156 = OpCopyObject %26 %132 -%158 = OpCopyObject %26 %134 +%138 = OpCompositeConstruct %9 %26 %28 +%139 = OpCompositeConstruct %9 %28 %26 +%140 = OpCompositeConstruct %13 %138 %139 +%141 = OpCompositeConstruct %3 %26 %28 %28 %28 +%142 = OpCompositeConstruct %3 %28 %26 %28 %28 +%143 = OpCompositeConstruct %3 %28 %28 %26 %28 +%144 = OpCompositeConstruct %3 %28 %28 %28 %26 +%145 = OpCompositeConstruct %14 %141 %142 %143 %144 +%146 = OpCompositeConstruct %16 %126 %126 +%147 = OpCompositeConstruct %9 %28 %28 +%148 = OpCompositeConstruct %9 %28 %28 +%149 = OpCompositeConstruct %13 %147 %148 +%150 = OpCompositeConstruct %19 %39 %32 %70 %34 +%156 = OpCopyObject %21 %132 +%158 = OpCopyObject %21 %134 %161 = OpAccessChain %160 %112 %126 %126 %162 = OpLoad %4 %161 OpReturnValue %162 @@ -221,256 +221,256 @@ OpFunctionEnd %163 = OpLabel OpBranch %166 %166 = OpLabel -%167 = OpLogicalNot %13 %38 +%167 = OpLogicalNot %8 %38 %169 = OpCompositeConstruct %168 %38 %38 %170 = OpLogicalNot %168 %169 -%171 = OpLogicalOr %13 %38 %40 -%172 = OpLogicalAnd %13 %38 %40 -%173 = OpLogicalOr %13 %38 %40 -%174 = OpCompositeConstruct %16 %38 %38 %38 -%175 = OpCompositeConstruct %16 %40 %40 %40 -%176 = OpLogicalOr %16 %174 %175 -%177 = OpLogicalAnd %13 %38 %40 -%178 = OpCompositeConstruct %12 %38 %38 %38 %38 -%179 = OpCompositeConstruct %12 %40 %40 %40 %40 -%180 = OpLogicalAnd %12 %178 %179 +%171 = OpLogicalOr %8 %38 %40 +%172 = OpLogicalAnd %8 %38 %40 +%173 = OpLogicalOr %8 %38 %40 +%174 = OpCompositeConstruct %11 %38 %38 %38 +%175 = OpCompositeConstruct %11 %40 %40 %40 +%176 = OpLogicalOr %11 %174 %175 +%177 = OpLogicalAnd %8 %38 %40 +%178 = OpCompositeConstruct %7 %38 %38 %38 %38 +%179 = OpCompositeConstruct %7 %40 %40 %40 %40 +%180 = OpLogicalAnd %7 %178 %179 OpReturn OpFunctionEnd %182 = OpFunction %2 None %165 %181 = OpLabel OpBranch %196 %196 = OpLabel -%198 = OpCompositeConstruct %197 %7 %7 +%198 = OpCompositeConstruct %197 %32 %32 %199 = OpSNegate %197 %198 -%200 = OpCompositeConstruct %14 %3 %3 -%201 = OpFNegate %14 %200 -%202 = OpIAdd %8 %70 %7 -%203 = OpIAdd %20 %184 %185 -%204 = OpFAdd %4 %66 %3 +%200 = OpCompositeConstruct %9 %26 %26 +%201 = OpFNegate %9 %200 +%202 = OpIAdd %6 %70 %32 +%203 = OpIAdd %15 %184 %185 +%204 = OpFAdd %4 %66 %26 %205 = OpCompositeConstruct %197 %70 %70 -%206 = OpCompositeConstruct %197 %7 %7 +%206 = OpCompositeConstruct %197 %32 %32 %207 = OpIAdd %197 %205 %206 %209 = OpCompositeConstruct %208 %184 %184 %184 %210 = OpCompositeConstruct %208 %185 %185 %185 %211 = OpIAdd %208 %209 %210 -%212 = OpCompositeConstruct %10 %66 %66 %66 %66 -%213 = OpCompositeConstruct %10 %3 %3 %3 %3 -%214 = OpFAdd %10 %212 %213 -%215 = OpISub %8 %70 %7 -%216 = OpISub %20 %184 %185 -%217 = OpFSub %4 %66 %3 +%212 = OpCompositeConstruct %3 %66 %66 %66 %66 +%213 = OpCompositeConstruct %3 %26 %26 %26 %26 +%214 = OpFAdd %3 %212 %213 +%215 = OpISub %6 %70 %32 +%216 = OpISub %15 %184 %185 +%217 = OpFSub %4 %66 %26 %218 = OpCompositeConstruct %197 %70 %70 -%219 = OpCompositeConstruct %197 %7 %7 +%219 = OpCompositeConstruct %197 %32 %32 %220 = OpISub %197 %218 %219 %221 = OpCompositeConstruct %208 %184 %184 %184 %222 = OpCompositeConstruct %208 %185 %185 %185 %223 = OpISub %208 %221 %222 -%224 = OpCompositeConstruct %10 %66 %66 %66 %66 -%225 = OpCompositeConstruct %10 %3 %3 %3 %3 -%226 = OpFSub %10 %224 %225 -%227 = OpIMul %8 %70 %7 -%228 = OpIMul %20 %184 %185 -%229 = OpFMul %4 %66 %3 +%224 = OpCompositeConstruct %3 %66 %66 %66 %66 +%225 = OpCompositeConstruct %3 %26 %26 %26 %26 +%226 = OpFSub %3 %224 %225 +%227 = OpIMul %6 %70 %32 +%228 = OpIMul %15 %184 %185 +%229 = OpFMul %4 %66 %26 %230 = OpCompositeConstruct %197 %70 %70 -%231 = OpCompositeConstruct %197 %7 %7 +%231 = OpCompositeConstruct %197 %32 %32 %232 = OpIMul %197 %230 %231 %233 = OpCompositeConstruct %208 %184 %184 %184 %234 = OpCompositeConstruct %208 %185 %185 %185 %235 = OpIMul %208 %233 %234 -%236 = OpCompositeConstruct %10 %66 %66 %66 %66 -%237 = OpCompositeConstruct %10 %3 %3 %3 %3 -%238 = OpFMul %10 %236 %237 -%239 = OpSDiv %8 %70 %7 -%240 = OpUDiv %20 %184 %185 -%241 = OpFDiv %4 %66 %3 +%236 = OpCompositeConstruct %3 %66 %66 %66 %66 +%237 = OpCompositeConstruct %3 %26 %26 %26 %26 +%238 = OpFMul %3 %236 %237 +%239 = OpSDiv %6 %70 %32 +%240 = OpUDiv %15 %184 %185 +%241 = OpFDiv %4 %66 %26 %242 = OpCompositeConstruct %197 %70 %70 -%243 = OpCompositeConstruct %197 %7 %7 +%243 = OpCompositeConstruct %197 %32 %32 %244 = OpSDiv %197 %242 %243 %245 = OpCompositeConstruct %208 %184 %184 %184 %246 = OpCompositeConstruct %208 %185 %185 %185 %247 = OpUDiv %208 %245 %246 -%248 = OpCompositeConstruct %10 %66 %66 %66 %66 -%249 = OpCompositeConstruct %10 %3 %3 %3 %3 -%250 = OpFDiv %10 %248 %249 -%251 = OpSRem %8 %70 %7 -%252 = OpUMod %20 %184 %185 -%253 = OpFRem %4 %66 %3 +%248 = OpCompositeConstruct %3 %66 %66 %66 %66 +%249 = OpCompositeConstruct %3 %26 %26 %26 %26 +%250 = OpFDiv %3 %248 %249 +%251 = OpSRem %6 %70 %32 +%252 = OpUMod %15 %184 %185 +%253 = OpFRem %4 %66 %26 %254 = OpCompositeConstruct %197 %70 %70 -%255 = OpCompositeConstruct %197 %7 %7 +%255 = OpCompositeConstruct %197 %32 %32 %256 = OpSRem %197 %254 %255 %257 = OpCompositeConstruct %208 %184 %184 %184 %258 = OpCompositeConstruct %208 %185 %185 %185 %259 = OpUMod %208 %257 %258 -%260 = OpCompositeConstruct %10 %66 %66 %66 %66 -%261 = OpCompositeConstruct %10 %3 %3 %3 %3 -%262 = OpFRem %10 %260 %261 +%260 = OpCompositeConstruct %3 %66 %66 %66 %66 +%261 = OpCompositeConstruct %3 %26 %26 %26 %26 +%262 = OpFRem %3 %260 %261 OpBranch %263 %263 = OpLabel %265 = OpCompositeConstruct %197 %70 %70 -%266 = OpCompositeConstruct %197 %7 %7 +%266 = OpCompositeConstruct %197 %32 %32 %267 = OpIAdd %197 %265 %266 -%268 = OpCompositeConstruct %197 %7 %7 +%268 = OpCompositeConstruct %197 %32 %32 %269 = OpCompositeConstruct %197 %70 %70 %270 = OpIAdd %197 %269 %268 -%271 = OpCompositeConstruct %21 %184 %184 -%272 = OpCompositeConstruct %21 %185 %185 -%273 = OpIAdd %21 %271 %272 -%274 = OpCompositeConstruct %21 %185 %185 -%275 = OpCompositeConstruct %21 %184 %184 -%276 = OpIAdd %21 %275 %274 -%277 = OpCompositeConstruct %14 %66 %66 -%278 = OpCompositeConstruct %14 %3 %3 -%279 = OpFAdd %14 %277 %278 -%280 = OpCompositeConstruct %14 %3 %3 -%281 = OpCompositeConstruct %14 %66 %66 -%282 = OpFAdd %14 %281 %280 +%271 = OpCompositeConstruct %16 %184 %184 +%272 = OpCompositeConstruct %16 %185 %185 +%273 = OpIAdd %16 %271 %272 +%274 = OpCompositeConstruct %16 %185 %185 +%275 = OpCompositeConstruct %16 %184 %184 +%276 = OpIAdd %16 %275 %274 +%277 = OpCompositeConstruct %9 %66 %66 +%278 = OpCompositeConstruct %9 %26 %26 +%279 = OpFAdd %9 %277 %278 +%280 = OpCompositeConstruct %9 %26 %26 +%281 = OpCompositeConstruct %9 %66 %66 +%282 = OpFAdd %9 %281 %280 %283 = OpCompositeConstruct %197 %70 %70 -%284 = OpCompositeConstruct %197 %7 %7 +%284 = OpCompositeConstruct %197 %32 %32 %285 = OpISub %197 %283 %284 -%286 = OpCompositeConstruct %197 %7 %7 +%286 = OpCompositeConstruct %197 %32 %32 %287 = OpCompositeConstruct %197 %70 %70 %288 = OpISub %197 %287 %286 -%289 = OpCompositeConstruct %21 %184 %184 -%290 = OpCompositeConstruct %21 %185 %185 -%291 = OpISub %21 %289 %290 -%292 = OpCompositeConstruct %21 %185 %185 -%293 = OpCompositeConstruct %21 %184 %184 -%294 = OpISub %21 %293 %292 -%295 = OpCompositeConstruct %14 %66 %66 -%296 = OpCompositeConstruct %14 %3 %3 -%297 = OpFSub %14 %295 %296 -%298 = OpCompositeConstruct %14 %3 %3 -%299 = OpCompositeConstruct %14 %66 %66 -%300 = OpFSub %14 %299 %298 +%289 = OpCompositeConstruct %16 %184 %184 +%290 = OpCompositeConstruct %16 %185 %185 +%291 = OpISub %16 %289 %290 +%292 = OpCompositeConstruct %16 %185 %185 +%293 = OpCompositeConstruct %16 %184 %184 +%294 = OpISub %16 %293 %292 +%295 = OpCompositeConstruct %9 %66 %66 +%296 = OpCompositeConstruct %9 %26 %26 +%297 = OpFSub %9 %295 %296 +%298 = OpCompositeConstruct %9 %26 %26 +%299 = OpCompositeConstruct %9 %66 %66 +%300 = OpFSub %9 %299 %298 %301 = OpCompositeConstruct %197 %70 %70 -%303 = OpCompositeConstruct %197 %7 %7 +%303 = OpCompositeConstruct %197 %32 %32 %302 = OpIMul %197 %301 %303 -%304 = OpCompositeConstruct %197 %7 %7 +%304 = OpCompositeConstruct %197 %32 %32 %306 = OpCompositeConstruct %197 %70 %70 %305 = OpIMul %197 %304 %306 -%307 = OpCompositeConstruct %21 %184 %184 -%309 = OpCompositeConstruct %21 %185 %185 -%308 = OpIMul %21 %307 %309 -%310 = OpCompositeConstruct %21 %185 %185 -%312 = OpCompositeConstruct %21 %184 %184 -%311 = OpIMul %21 %310 %312 -%313 = OpCompositeConstruct %14 %66 %66 -%314 = OpVectorTimesScalar %14 %313 %3 -%315 = OpCompositeConstruct %14 %3 %3 -%316 = OpVectorTimesScalar %14 %315 %66 +%307 = OpCompositeConstruct %16 %184 %184 +%309 = OpCompositeConstruct %16 %185 %185 +%308 = OpIMul %16 %307 %309 +%310 = OpCompositeConstruct %16 %185 %185 +%312 = OpCompositeConstruct %16 %184 %184 +%311 = OpIMul %16 %310 %312 +%313 = OpCompositeConstruct %9 %66 %66 +%314 = OpVectorTimesScalar %9 %313 %26 +%315 = OpCompositeConstruct %9 %26 %26 +%316 = OpVectorTimesScalar %9 %315 %66 %317 = OpCompositeConstruct %197 %70 %70 -%318 = OpCompositeConstruct %197 %7 %7 +%318 = OpCompositeConstruct %197 %32 %32 %319 = OpSDiv %197 %317 %318 -%320 = OpCompositeConstruct %197 %7 %7 +%320 = OpCompositeConstruct %197 %32 %32 %321 = OpCompositeConstruct %197 %70 %70 %322 = OpSDiv %197 %321 %320 -%323 = OpCompositeConstruct %21 %184 %184 -%324 = OpCompositeConstruct %21 %185 %185 -%325 = OpUDiv %21 %323 %324 -%326 = OpCompositeConstruct %21 %185 %185 -%327 = OpCompositeConstruct %21 %184 %184 -%328 = OpUDiv %21 %327 %326 -%329 = OpCompositeConstruct %14 %66 %66 -%330 = OpCompositeConstruct %14 %3 %3 -%331 = OpFDiv %14 %329 %330 -%332 = OpCompositeConstruct %14 %3 %3 -%333 = OpCompositeConstruct %14 %66 %66 -%334 = OpFDiv %14 %333 %332 +%323 = OpCompositeConstruct %16 %184 %184 +%324 = OpCompositeConstruct %16 %185 %185 +%325 = OpUDiv %16 %323 %324 +%326 = OpCompositeConstruct %16 %185 %185 +%327 = OpCompositeConstruct %16 %184 %184 +%328 = OpUDiv %16 %327 %326 +%329 = OpCompositeConstruct %9 %66 %66 +%330 = OpCompositeConstruct %9 %26 %26 +%331 = OpFDiv %9 %329 %330 +%332 = OpCompositeConstruct %9 %26 %26 +%333 = OpCompositeConstruct %9 %66 %66 +%334 = OpFDiv %9 %333 %332 %335 = OpCompositeConstruct %197 %70 %70 -%336 = OpCompositeConstruct %197 %7 %7 +%336 = OpCompositeConstruct %197 %32 %32 %337 = OpSRem %197 %335 %336 -%338 = OpCompositeConstruct %197 %7 %7 +%338 = OpCompositeConstruct %197 %32 %32 %339 = OpCompositeConstruct %197 %70 %70 %340 = OpSRem %197 %339 %338 -%341 = OpCompositeConstruct %21 %184 %184 -%342 = OpCompositeConstruct %21 %185 %185 -%343 = OpUMod %21 %341 %342 -%344 = OpCompositeConstruct %21 %185 %185 -%345 = OpCompositeConstruct %21 %184 %184 -%346 = OpUMod %21 %345 %344 -%347 = OpCompositeConstruct %14 %66 %66 -%348 = OpCompositeConstruct %14 %3 %3 -%349 = OpFRem %14 %347 %348 -%350 = OpCompositeConstruct %14 %3 %3 -%351 = OpCompositeConstruct %14 %66 %66 -%352 = OpFRem %14 %351 %350 +%341 = OpCompositeConstruct %16 %184 %184 +%342 = OpCompositeConstruct %16 %185 %185 +%343 = OpUMod %16 %341 %342 +%344 = OpCompositeConstruct %16 %185 %185 +%345 = OpCompositeConstruct %16 %184 %184 +%346 = OpUMod %16 %345 %344 +%347 = OpCompositeConstruct %9 %66 %66 +%348 = OpCompositeConstruct %9 %26 %26 +%349 = OpFRem %9 %347 %348 +%350 = OpCompositeConstruct %9 %26 %26 +%351 = OpCompositeConstruct %9 %66 %66 +%352 = OpFRem %9 %351 %350 OpBranch %264 %264 = OpLabel -%354 = OpCompositeExtract %15 %186 0 -%355 = OpCompositeExtract %15 %187 0 -%356 = OpFAdd %15 %354 %355 -%357 = OpCompositeExtract %15 %186 1 -%358 = OpCompositeExtract %15 %187 1 -%359 = OpFAdd %15 %357 %358 -%360 = OpCompositeExtract %15 %186 2 -%361 = OpCompositeExtract %15 %187 2 -%362 = OpFAdd %15 %360 %361 -%353 = OpCompositeConstruct %27 %356 %359 %362 -%364 = OpCompositeExtract %15 %188 0 -%365 = OpCompositeExtract %15 %189 0 -%366 = OpFSub %15 %364 %365 -%367 = OpCompositeExtract %15 %188 1 -%368 = OpCompositeExtract %15 %189 1 -%369 = OpFSub %15 %367 %368 -%370 = OpCompositeExtract %15 %188 2 -%371 = OpCompositeExtract %15 %189 2 -%372 = OpFSub %15 %370 %371 -%363 = OpCompositeConstruct %27 %366 %369 %372 -%373 = OpMatrixTimesScalar %27 %190 %3 -%374 = OpMatrixTimesScalar %27 %191 %66 -%375 = OpCompositeConstruct %10 %3 %3 %3 %3 -%376 = OpMatrixTimesVector %15 %192 %375 -%377 = OpCompositeConstruct %15 %66 %66 %66 -%378 = OpVectorTimesMatrix %10 %377 %193 -%379 = OpMatrixTimesMatrix %27 %194 %195 +%354 = OpCompositeExtract %10 %186 0 +%355 = OpCompositeExtract %10 %187 0 +%356 = OpFAdd %10 %354 %355 +%357 = OpCompositeExtract %10 %186 1 +%358 = OpCompositeExtract %10 %187 1 +%359 = OpFAdd %10 %357 %358 +%360 = OpCompositeExtract %10 %186 2 +%361 = OpCompositeExtract %10 %187 2 +%362 = OpFAdd %10 %360 %361 +%353 = OpCompositeConstruct %22 %356 %359 %362 +%364 = OpCompositeExtract %10 %188 0 +%365 = OpCompositeExtract %10 %189 0 +%366 = OpFSub %10 %364 %365 +%367 = OpCompositeExtract %10 %188 1 +%368 = OpCompositeExtract %10 %189 1 +%369 = OpFSub %10 %367 %368 +%370 = OpCompositeExtract %10 %188 2 +%371 = OpCompositeExtract %10 %189 2 +%372 = OpFSub %10 %370 %371 +%363 = OpCompositeConstruct %22 %366 %369 %372 +%373 = OpMatrixTimesScalar %22 %190 %26 +%374 = OpMatrixTimesScalar %22 %191 %66 +%375 = OpCompositeConstruct %3 %26 %26 %26 %26 +%376 = OpMatrixTimesVector %10 %192 %375 +%377 = OpCompositeConstruct %10 %66 %66 %66 +%378 = OpVectorTimesMatrix %3 %377 %193 +%379 = OpMatrixTimesMatrix %22 %194 %195 OpReturn OpFunctionEnd %381 = OpFunction %2 None %165 %380 = OpLabel OpBranch %382 %382 = OpLabel -%383 = OpNot %8 %7 -%384 = OpNot %20 %185 -%385 = OpCompositeConstruct %197 %7 %7 +%383 = OpNot %6 %32 +%384 = OpNot %15 %185 +%385 = OpCompositeConstruct %197 %32 %32 %386 = OpNot %197 %385 %387 = OpCompositeConstruct %208 %185 %185 %185 %388 = OpNot %208 %387 -%389 = OpBitwiseOr %8 %70 %7 -%390 = OpBitwiseOr %20 %184 %185 +%389 = OpBitwiseOr %6 %70 %32 +%390 = OpBitwiseOr %15 %184 %185 %391 = OpCompositeConstruct %197 %70 %70 -%392 = OpCompositeConstruct %197 %7 %7 +%392 = OpCompositeConstruct %197 %32 %32 %393 = OpBitwiseOr %197 %391 %392 %394 = OpCompositeConstruct %208 %184 %184 %184 %395 = OpCompositeConstruct %208 %185 %185 %185 %396 = OpBitwiseOr %208 %394 %395 -%397 = OpBitwiseAnd %8 %70 %7 -%398 = OpBitwiseAnd %20 %184 %185 +%397 = OpBitwiseAnd %6 %70 %32 +%398 = OpBitwiseAnd %15 %184 %185 %399 = OpCompositeConstruct %197 %70 %70 -%400 = OpCompositeConstruct %197 %7 %7 +%400 = OpCompositeConstruct %197 %32 %32 %401 = OpBitwiseAnd %197 %399 %400 %402 = OpCompositeConstruct %208 %184 %184 %184 %403 = OpCompositeConstruct %208 %185 %185 %185 %404 = OpBitwiseAnd %208 %402 %403 -%405 = OpBitwiseXor %8 %70 %7 -%406 = OpBitwiseXor %20 %184 %185 +%405 = OpBitwiseXor %6 %70 %32 +%406 = OpBitwiseXor %15 %184 %185 %407 = OpCompositeConstruct %197 %70 %70 -%408 = OpCompositeConstruct %197 %7 %7 +%408 = OpCompositeConstruct %197 %32 %32 %409 = OpBitwiseXor %197 %407 %408 %410 = OpCompositeConstruct %208 %184 %184 %184 %411 = OpCompositeConstruct %208 %185 %185 %185 %412 = OpBitwiseXor %208 %410 %411 -%413 = OpShiftLeftLogical %8 %70 %185 -%414 = OpShiftLeftLogical %20 %184 %185 +%413 = OpShiftLeftLogical %6 %70 %185 +%414 = OpShiftLeftLogical %15 %184 %185 %415 = OpCompositeConstruct %197 %70 %70 -%416 = OpCompositeConstruct %21 %185 %185 +%416 = OpCompositeConstruct %16 %185 %185 %417 = OpShiftLeftLogical %197 %415 %416 %418 = OpCompositeConstruct %208 %184 %184 %184 %419 = OpCompositeConstruct %208 %185 %185 %185 %420 = OpShiftLeftLogical %208 %418 %419 -%421 = OpShiftRightArithmetic %8 %70 %185 -%422 = OpShiftRightLogical %20 %184 %185 +%421 = OpShiftRightArithmetic %6 %70 %185 +%422 = OpShiftRightLogical %15 %184 %185 %423 = OpCompositeConstruct %197 %70 %70 -%424 = OpCompositeConstruct %21 %185 %185 +%424 = OpCompositeConstruct %16 %185 %185 %425 = OpShiftRightArithmetic %197 %423 %424 %426 = OpCompositeConstruct %208 %184 %184 %184 %427 = OpCompositeConstruct %208 %185 %185 %185 @@ -481,78 +481,78 @@ OpFunctionEnd %429 = OpLabel OpBranch %431 %431 = OpLabel -%432 = OpIEqual %13 %70 %7 -%433 = OpIEqual %13 %184 %185 -%434 = OpFOrdEqual %13 %66 %3 +%432 = OpIEqual %8 %70 %32 +%433 = OpIEqual %8 %184 %185 +%434 = OpFOrdEqual %8 %66 %26 %435 = OpCompositeConstruct %197 %70 %70 -%436 = OpCompositeConstruct %197 %7 %7 +%436 = OpCompositeConstruct %197 %32 %32 %437 = OpIEqual %168 %435 %436 %438 = OpCompositeConstruct %208 %184 %184 %184 %439 = OpCompositeConstruct %208 %185 %185 %185 -%440 = OpIEqual %16 %438 %439 -%441 = OpCompositeConstruct %10 %66 %66 %66 %66 -%442 = OpCompositeConstruct %10 %3 %3 %3 %3 -%443 = OpFOrdEqual %12 %441 %442 -%444 = OpINotEqual %13 %70 %7 -%445 = OpINotEqual %13 %184 %185 -%446 = OpFOrdNotEqual %13 %66 %3 +%440 = OpIEqual %11 %438 %439 +%441 = OpCompositeConstruct %3 %66 %66 %66 %66 +%442 = OpCompositeConstruct %3 %26 %26 %26 %26 +%443 = OpFOrdEqual %7 %441 %442 +%444 = OpINotEqual %8 %70 %32 +%445 = OpINotEqual %8 %184 %185 +%446 = OpFOrdNotEqual %8 %66 %26 %447 = OpCompositeConstruct %197 %70 %70 -%448 = OpCompositeConstruct %197 %7 %7 +%448 = OpCompositeConstruct %197 %32 %32 %449 = OpINotEqual %168 %447 %448 %450 = OpCompositeConstruct %208 %184 %184 %184 %451 = OpCompositeConstruct %208 %185 %185 %185 -%452 = OpINotEqual %16 %450 %451 -%453 = OpCompositeConstruct %10 %66 %66 %66 %66 -%454 = OpCompositeConstruct %10 %3 %3 %3 %3 -%455 = OpFOrdNotEqual %12 %453 %454 -%456 = OpSLessThan %13 %70 %7 -%457 = OpULessThan %13 %184 %185 -%458 = OpFOrdLessThan %13 %66 %3 +%452 = OpINotEqual %11 %450 %451 +%453 = OpCompositeConstruct %3 %66 %66 %66 %66 +%454 = OpCompositeConstruct %3 %26 %26 %26 %26 +%455 = OpFOrdNotEqual %7 %453 %454 +%456 = OpSLessThan %8 %70 %32 +%457 = OpULessThan %8 %184 %185 +%458 = OpFOrdLessThan %8 %66 %26 %459 = OpCompositeConstruct %197 %70 %70 -%460 = OpCompositeConstruct %197 %7 %7 +%460 = OpCompositeConstruct %197 %32 %32 %461 = OpSLessThan %168 %459 %460 %462 = OpCompositeConstruct %208 %184 %184 %184 %463 = OpCompositeConstruct %208 %185 %185 %185 -%464 = OpULessThan %16 %462 %463 -%465 = OpCompositeConstruct %10 %66 %66 %66 %66 -%466 = OpCompositeConstruct %10 %3 %3 %3 %3 -%467 = OpFOrdLessThan %12 %465 %466 -%468 = OpSLessThanEqual %13 %70 %7 -%469 = OpULessThanEqual %13 %184 %185 -%470 = OpFOrdLessThanEqual %13 %66 %3 +%464 = OpULessThan %11 %462 %463 +%465 = OpCompositeConstruct %3 %66 %66 %66 %66 +%466 = OpCompositeConstruct %3 %26 %26 %26 %26 +%467 = OpFOrdLessThan %7 %465 %466 +%468 = OpSLessThanEqual %8 %70 %32 +%469 = OpULessThanEqual %8 %184 %185 +%470 = OpFOrdLessThanEqual %8 %66 %26 %471 = OpCompositeConstruct %197 %70 %70 -%472 = OpCompositeConstruct %197 %7 %7 +%472 = OpCompositeConstruct %197 %32 %32 %473 = OpSLessThanEqual %168 %471 %472 %474 = OpCompositeConstruct %208 %184 %184 %184 %475 = OpCompositeConstruct %208 %185 %185 %185 -%476 = OpULessThanEqual %16 %474 %475 -%477 = OpCompositeConstruct %10 %66 %66 %66 %66 -%478 = OpCompositeConstruct %10 %3 %3 %3 %3 -%479 = OpFOrdLessThanEqual %12 %477 %478 -%480 = OpSGreaterThan %13 %70 %7 -%481 = OpUGreaterThan %13 %184 %185 -%482 = OpFOrdGreaterThan %13 %66 %3 +%476 = OpULessThanEqual %11 %474 %475 +%477 = OpCompositeConstruct %3 %66 %66 %66 %66 +%478 = OpCompositeConstruct %3 %26 %26 %26 %26 +%479 = OpFOrdLessThanEqual %7 %477 %478 +%480 = OpSGreaterThan %8 %70 %32 +%481 = OpUGreaterThan %8 %184 %185 +%482 = OpFOrdGreaterThan %8 %66 %26 %483 = OpCompositeConstruct %197 %70 %70 -%484 = OpCompositeConstruct %197 %7 %7 +%484 = OpCompositeConstruct %197 %32 %32 %485 = OpSGreaterThan %168 %483 %484 %486 = OpCompositeConstruct %208 %184 %184 %184 %487 = OpCompositeConstruct %208 %185 %185 %185 -%488 = OpUGreaterThan %16 %486 %487 -%489 = OpCompositeConstruct %10 %66 %66 %66 %66 -%490 = OpCompositeConstruct %10 %3 %3 %3 %3 -%491 = OpFOrdGreaterThan %12 %489 %490 -%492 = OpSGreaterThanEqual %13 %70 %7 -%493 = OpUGreaterThanEqual %13 %184 %185 -%494 = OpFOrdGreaterThanEqual %13 %66 %3 +%488 = OpUGreaterThan %11 %486 %487 +%489 = OpCompositeConstruct %3 %66 %66 %66 %66 +%490 = OpCompositeConstruct %3 %26 %26 %26 %26 +%491 = OpFOrdGreaterThan %7 %489 %490 +%492 = OpSGreaterThanEqual %8 %70 %32 +%493 = OpUGreaterThanEqual %8 %184 %185 +%494 = OpFOrdGreaterThanEqual %8 %66 %26 %495 = OpCompositeConstruct %197 %70 %70 -%496 = OpCompositeConstruct %197 %7 %7 +%496 = OpCompositeConstruct %197 %32 %32 %497 = OpSGreaterThanEqual %168 %495 %496 %498 = OpCompositeConstruct %208 %184 %184 %184 %499 = OpCompositeConstruct %208 %185 %185 %185 -%500 = OpUGreaterThanEqual %16 %498 %499 -%501 = OpCompositeConstruct %10 %66 %66 %66 %66 -%502 = OpCompositeConstruct %10 %3 %3 %3 %3 -%503 = OpFOrdGreaterThanEqual %12 %501 %502 +%500 = OpUGreaterThanEqual %11 %498 %499 +%501 = OpCompositeConstruct %3 %66 %66 %66 %66 +%502 = OpCompositeConstruct %3 %26 %26 %26 %26 +%503 = OpFOrdGreaterThanEqual %7 %501 %502 OpReturn OpFunctionEnd %511 = OpFunction %2 None %165 @@ -561,54 +561,54 @@ OpFunctionEnd %507 = OpVariable %508 Function %509 OpBranch %513 %513 = OpLabel -OpStore %504 %7 -%514 = OpLoad %8 %504 -%515 = OpIAdd %8 %514 %7 +OpStore %504 %32 +%514 = OpLoad %6 %504 +%515 = OpIAdd %6 %514 %32 OpStore %504 %515 -%516 = OpLoad %8 %504 -%517 = OpISub %8 %516 %7 +%516 = OpLoad %6 %504 +%517 = OpISub %6 %516 %32 OpStore %504 %517 -%518 = OpLoad %8 %504 -%519 = OpLoad %8 %504 -%520 = OpIMul %8 %519 %518 +%518 = OpLoad %6 %504 +%519 = OpLoad %6 %504 +%520 = OpIMul %6 %519 %518 OpStore %504 %520 -%521 = OpLoad %8 %504 -%522 = OpLoad %8 %504 -%523 = OpSDiv %8 %522 %521 +%521 = OpLoad %6 %504 +%522 = OpLoad %6 %504 +%523 = OpSDiv %6 %522 %521 OpStore %504 %523 -%524 = OpLoad %8 %504 -%525 = OpSRem %8 %524 %7 +%524 = OpLoad %6 %504 +%525 = OpSRem %6 %524 %32 OpStore %504 %525 -%526 = OpLoad %8 %504 -%527 = OpBitwiseAnd %8 %526 %39 +%526 = OpLoad %6 %504 +%527 = OpBitwiseAnd %6 %526 %39 OpStore %504 %527 -%528 = OpLoad %8 %504 -%529 = OpBitwiseOr %8 %528 %39 +%528 = OpLoad %6 %504 +%529 = OpBitwiseOr %6 %528 %39 OpStore %504 %529 -%530 = OpLoad %8 %504 -%531 = OpBitwiseXor %8 %530 %39 +%530 = OpLoad %6 %504 +%531 = OpBitwiseXor %6 %530 %39 OpStore %504 %531 -%532 = OpLoad %8 %504 -%533 = OpShiftLeftLogical %8 %532 %184 +%532 = OpLoad %6 %504 +%533 = OpShiftLeftLogical %6 %532 %184 OpStore %504 %533 -%534 = OpLoad %8 %504 -%535 = OpShiftRightArithmetic %8 %534 %185 +%534 = OpLoad %6 %504 +%535 = OpShiftRightArithmetic %6 %534 %185 OpStore %504 %535 -%536 = OpLoad %8 %504 -%537 = OpIAdd %8 %536 %7 +%536 = OpLoad %6 %504 +%537 = OpIAdd %6 %536 %32 OpStore %504 %537 -%538 = OpLoad %8 %504 -%539 = OpISub %8 %538 %7 +%538 = OpLoad %6 %504 +%539 = OpISub %6 %538 %32 OpStore %504 %539 OpStore %507 %512 %541 = OpAccessChain %540 %507 %185 -%542 = OpLoad %8 %541 -%543 = OpIAdd %8 %542 %7 +%542 = OpLoad %6 %541 +%543 = OpIAdd %6 %542 %32 %544 = OpAccessChain %540 %507 %185 OpStore %544 %543 %545 = OpAccessChain %540 %507 %185 -%546 = OpLoad %8 %545 -%547 = OpISub %8 %546 %7 +%546 = OpLoad %6 %545 +%547 = OpISub %6 %546 %32 %548 = OpAccessChain %540 %507 %185 OpStore %548 %547 OpReturn @@ -617,34 +617,34 @@ OpFunctionEnd %549 = OpLabel OpBranch %559 %559 = OpLabel -%560 = OpSNegate %8 %552 -%561 = OpSNegate %8 %553 -%562 = OpSNegate %8 %554 -%563 = OpSNegate %8 %562 -%564 = OpSNegate %8 %555 -%565 = OpSNegate %8 %564 -%566 = OpSNegate %8 %556 -%567 = OpSNegate %8 %566 -%568 = OpSNegate %8 %567 -%569 = OpSNegate %8 %568 -%570 = OpSNegate %8 %557 -%571 = OpSNegate %8 %570 -%572 = OpSNegate %8 %571 -%573 = OpSNegate %8 %572 -%574 = OpSNegate %8 %558 -%575 = OpSNegate %8 %574 -%576 = OpSNegate %8 %575 -%577 = OpSNegate %8 %576 +%560 = OpSNegate %6 %552 +%561 = OpSNegate %6 %553 +%562 = OpSNegate %6 %554 +%563 = OpSNegate %6 %562 +%564 = OpSNegate %6 %555 +%565 = OpSNegate %6 %564 +%566 = OpSNegate %6 %556 +%567 = OpSNegate %6 %566 +%568 = OpSNegate %6 %567 +%569 = OpSNegate %6 %568 +%570 = OpSNegate %6 %557 +%571 = OpSNegate %6 %570 +%572 = OpSNegate %6 %571 +%573 = OpSNegate %6 %572 +%574 = OpSNegate %6 %558 +%575 = OpSNegate %6 %574 +%576 = OpSNegate %6 %575 +%577 = OpSNegate %6 %576 OpReturn OpFunctionEnd %579 = OpFunction %2 None %165 %578 = OpLabel OpBranch %580 %580 = OpLabel -%581 = OpFunctionCall %10 %36 -%582 = OpFunctionCall %10 %65 -%583 = OpVectorShuffle %15 %31 %31 0 1 2 -%584 = OpFunctionCall %15 %105 %583 +%581 = OpFunctionCall %3 %36 +%582 = OpFunctionCall %3 %65 +%583 = OpVectorShuffle %10 %27 %27 0 1 2 +%584 = OpFunctionCall %10 %105 %583 %585 = OpFunctionCall %4 %116 %586 = OpFunctionCall %2 %164 %587 = OpFunctionCall %2 %182 diff --git a/tests/out/spv/padding.spvasm b/tests/out/spv/padding.spvasm index 0efcef10e..93c4ce63c 100644 --- a/tests/out/spv/padding.spvasm +++ b/tests/out/spv/padding.spvasm @@ -6,31 +6,31 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %28 "vertex" %26 -OpMemberName %7 0 "a" -OpName %7 "S" -OpMemberName %8 0 "a" -OpMemberName %8 1 "b" -OpName %8 "Test" +OpMemberName %5 0 "a" +OpName %5 "S" +OpMemberName %6 0 "a" +OpMemberName %6 1 "b" +OpName %6 "Test" +OpMemberName %10 0 "a" +OpMemberName %10 1 "b" +OpName %10 "Test2" OpMemberName %12 0 "a" OpMemberName %12 1 "b" -OpName %12 "Test2" -OpMemberName %14 0 "a" -OpMemberName %14 1 "b" -OpName %14 "Test3" +OpName %12 "Test3" OpName %16 "input1" OpName %19 "input2" OpName %22 "input3" OpName %28 "vertex" -OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %8 0 Offset 0 -OpMemberDecorate %8 1 Offset 16 -OpDecorate %9 ArrayStride 16 +OpMemberDecorate %5 0 Offset 0 +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %6 1 Offset 16 +OpDecorate %7 ArrayStride 16 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 32 OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 32 -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 0 ColMajor -OpMemberDecorate %14 0 MatrixStride 16 -OpMemberDecorate %14 1 Offset 64 +OpMemberDecorate %12 0 ColMajor +OpMemberDecorate %12 0 MatrixStride 16 +OpMemberDecorate %12 1 Offset 64 OpDecorate %16 DescriptorSet 0 OpDecorate %16 Binding 0 OpDecorate %17 Block @@ -45,38 +45,38 @@ OpDecorate %23 Block OpMemberDecorate %23 0 Offset 0 OpDecorate %26 BuiltIn Position %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 2 -%6 = OpTypeFloat 32 -%5 = OpTypeVector %6 3 -%7 = OpTypeStruct %5 -%8 = OpTypeStruct %7 %6 -%11 = OpTypeInt 32 0 -%10 = OpConstant %11 2 -%9 = OpTypeArray %5 %10 -%12 = OpTypeStruct %9 %6 -%13 = OpTypeMatrix %5 4 -%14 = OpTypeStruct %13 %6 -%15 = OpTypeVector %6 4 -%17 = OpTypeStruct %8 +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 3 +%5 = OpTypeStruct %3 +%6 = OpTypeStruct %5 %4 +%9 = OpTypeInt 32 0 +%8 = OpConstant %9 2 +%7 = OpTypeArray %3 %8 +%10 = OpTypeStruct %7 %4 +%11 = OpTypeMatrix %3 4 +%12 = OpTypeStruct %11 %4 +%13 = OpTypeVector %4 4 +%15 = OpTypeInt 32 1 +%14 = OpConstant %15 2 +%17 = OpTypeStruct %6 %18 = OpTypePointer Uniform %17 %16 = OpVariable %18 Uniform -%20 = OpTypeStruct %12 +%20 = OpTypeStruct %10 %21 = OpTypePointer Uniform %20 %19 = OpVariable %21 Uniform -%23 = OpTypeStruct %14 +%23 = OpTypeStruct %12 %24 = OpTypePointer Uniform %23 %22 = OpVariable %24 Uniform -%27 = OpTypePointer Output %15 +%27 = OpTypePointer Output %13 %26 = OpVariable %27 Output %29 = OpTypeFunction %2 -%30 = OpTypePointer Uniform %8 -%31 = OpConstant %11 0 -%33 = OpTypePointer Uniform %12 -%35 = OpTypePointer Uniform %14 -%37 = OpConstant %6 1.0 -%40 = OpTypePointer Uniform %6 -%41 = OpConstant %11 1 +%30 = OpTypePointer Uniform %6 +%31 = OpConstant %9 0 +%33 = OpTypePointer Uniform %10 +%35 = OpTypePointer Uniform %12 +%37 = OpConstant %4 1.0 +%40 = OpTypePointer Uniform %4 +%41 = OpConstant %9 1 %28 = OpFunction %2 None %29 %25 = OpLabel %32 = OpAccessChain %30 %16 %31 @@ -84,16 +84,16 @@ OpDecorate %26 BuiltIn Position %36 = OpAccessChain %35 %22 %31 OpBranch %38 %38 = OpLabel -%39 = OpCompositeConstruct %15 %37 %37 %37 %37 +%39 = OpCompositeConstruct %13 %37 %37 %37 %37 %42 = OpAccessChain %40 %32 %41 -%43 = OpLoad %6 %42 -%44 = OpVectorTimesScalar %15 %39 %43 +%43 = OpLoad %4 %42 +%44 = OpVectorTimesScalar %13 %39 %43 %45 = OpAccessChain %40 %34 %41 -%46 = OpLoad %6 %45 -%47 = OpVectorTimesScalar %15 %44 %46 +%46 = OpLoad %4 %45 +%47 = OpVectorTimesScalar %13 %44 %46 %48 = OpAccessChain %40 %36 %41 -%49 = OpLoad %6 %48 -%50 = OpVectorTimesScalar %15 %47 %49 +%49 = OpLoad %4 %48 +%50 = OpVectorTimesScalar %13 %47 %49 OpStore %26 %50 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index 970da7d10..ea77b3bb4 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -8,10 +8,10 @@ OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpMemberName %14 0 "a" -OpName %14 "InStorage" -OpMemberName %17 0 "a" -OpName %17 "InUniform" +OpMemberName %8 0 "a" +OpName %8 "InStorage" +OpMemberName %11 0 "a" +OpName %11 "InUniform" OpName %26 "in_storage" OpName %29 "in_uniform" OpName %32 "image_2d_array" @@ -22,13 +22,13 @@ OpName %43 "c" OpName %44 "i" OpName %45 "l" OpName %46 "mock_function" -OpDecorate %11 ArrayStride 16 -OpMemberDecorate %14 0 Offset 0 -OpDecorate %15 ArrayStride 16 -OpMemberDecorate %17 0 Offset 0 -OpDecorate %19 ArrayStride 4 -OpDecorate %21 ArrayStride 4 -OpDecorate %24 ArrayStride 16 +OpDecorate %5 ArrayStride 16 +OpMemberDecorate %8 0 Offset 0 +OpDecorate %9 ArrayStride 16 +OpMemberDecorate %11 0 Offset 0 +OpDecorate %13 ArrayStride 4 +OpDecorate %15 ArrayStride 4 +OpDecorate %19 ArrayStride 16 OpDecorate %26 NonWritable OpDecorate %26 DescriptorSet 0 OpDecorate %26 Binding 0 @@ -41,87 +41,87 @@ OpMemberDecorate %30 0 Offset 0 OpDecorate %32 DescriptorSet 0 OpDecorate %32 Binding 2 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 10 -%5 = OpConstant %4 20 -%6 = OpConstant %4 30 -%7 = OpConstant %4 40 -%8 = OpConstant %4 2 -%10 = OpTypeFloat 32 -%9 = OpTypeVector %10 4 -%13 = OpTypeInt 32 0 -%12 = OpConstant %13 10 -%11 = OpTypeArray %9 %12 -%14 = OpTypeStruct %11 -%16 = OpConstant %13 20 -%15 = OpTypeArray %9 %16 -%17 = OpTypeStruct %15 -%18 = OpTypeImage %10 2D 0 1 0 1 Unknown -%20 = OpConstant %13 30 -%19 = OpTypeArray %10 %20 -%22 = OpConstant %13 40 -%21 = OpTypeArray %10 %22 -%23 = OpTypeVector %4 2 -%25 = OpConstant %13 2 -%24 = OpTypeArray %9 %25 -%27 = OpTypeStruct %14 +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%7 = OpTypeInt 32 0 +%6 = OpConstant %7 10 +%5 = OpTypeArray %3 %6 +%8 = OpTypeStruct %5 +%10 = OpConstant %7 20 +%9 = OpTypeArray %3 %10 +%11 = OpTypeStruct %9 +%12 = OpTypeImage %4 2D 0 1 0 1 Unknown +%14 = OpConstant %7 30 +%13 = OpTypeArray %4 %14 +%16 = OpConstant %7 40 +%15 = OpTypeArray %4 %16 +%18 = OpTypeInt 32 1 +%17 = OpTypeVector %18 2 +%20 = OpConstant %7 2 +%19 = OpTypeArray %3 %20 +%21 = OpConstant %18 10 +%22 = OpConstant %18 20 +%23 = OpConstant %18 30 +%24 = OpConstant %18 40 +%25 = OpConstant %18 2 +%27 = OpTypeStruct %8 %28 = OpTypePointer StorageBuffer %27 %26 = OpVariable %28 StorageBuffer -%30 = OpTypeStruct %17 +%30 = OpTypeStruct %11 %31 = OpTypePointer Uniform %30 %29 = OpVariable %31 Uniform -%33 = OpTypePointer UniformConstant %18 +%33 = OpTypePointer UniformConstant %12 %32 = OpVariable %33 UniformConstant -%35 = OpTypePointer Workgroup %19 +%35 = OpTypePointer Workgroup %13 %34 = OpVariable %35 Workgroup -%37 = OpTypePointer Private %21 -%38 = OpConstantNull %21 +%37 = OpTypePointer Private %15 +%38 = OpConstantNull %15 %36 = OpVariable %37 Private %38 -%40 = OpTypePointer Function %24 -%41 = OpConstantNull %24 -%47 = OpTypeFunction %9 %23 %4 %4 -%48 = OpTypePointer StorageBuffer %14 -%49 = OpConstant %13 0 -%51 = OpTypePointer Uniform %17 -%54 = OpConstant %10 0.707 -%55 = OpConstant %10 0.0 -%56 = OpConstant %10 1.0 -%61 = OpTypePointer StorageBuffer %11 -%62 = OpTypePointer StorageBuffer %9 -%65 = OpTypePointer Uniform %15 -%66 = OpTypePointer Uniform %9 -%70 = OpTypeVector %4 3 +%40 = OpTypePointer Function %19 +%41 = OpConstantNull %19 +%47 = OpTypeFunction %3 %17 %18 %18 +%48 = OpTypePointer StorageBuffer %8 +%49 = OpConstant %7 0 +%51 = OpTypePointer Uniform %11 +%54 = OpConstant %4 0.707 +%55 = OpConstant %4 0.0 +%56 = OpConstant %4 1.0 +%61 = OpTypePointer StorageBuffer %5 +%62 = OpTypePointer StorageBuffer %3 +%65 = OpTypePointer Uniform %9 +%66 = OpTypePointer Uniform %3 +%70 = OpTypeVector %18 3 %72 = OpTypeBool -%73 = OpConstantNull %9 +%73 = OpConstantNull %3 %79 = OpTypeVector %72 3 -%86 = OpTypePointer Workgroup %10 -%87 = OpConstant %13 29 -%93 = OpTypePointer Private %10 -%94 = OpConstant %13 39 -%100 = OpTypePointer Function %9 -%101 = OpConstant %13 1 -%46 = OpFunction %9 None %47 -%43 = OpFunctionParameter %23 -%44 = OpFunctionParameter %4 -%45 = OpFunctionParameter %4 +%86 = OpTypePointer Workgroup %4 +%87 = OpConstant %7 29 +%93 = OpTypePointer Private %4 +%94 = OpConstant %7 39 +%100 = OpTypePointer Function %3 +%101 = OpConstant %7 1 +%46 = OpFunction %3 None %47 +%43 = OpFunctionParameter %17 +%44 = OpFunctionParameter %18 +%45 = OpFunctionParameter %18 %42 = OpLabel %39 = OpVariable %40 Function %41 %50 = OpAccessChain %48 %26 %49 %52 = OpAccessChain %51 %29 %49 -%53 = OpLoad %18 %32 +%53 = OpLoad %12 %32 OpBranch %57 %57 = OpLabel -%58 = OpCompositeConstruct %9 %54 %55 %55 %56 -%59 = OpCompositeConstruct %9 %55 %54 %55 %56 -%60 = OpCompositeConstruct %24 %58 %59 +%58 = OpCompositeConstruct %3 %54 %55 %55 %56 +%59 = OpCompositeConstruct %3 %55 %54 %55 %56 +%60 = OpCompositeConstruct %19 %58 %59 OpStore %39 %60 %63 = OpAccessChain %62 %50 %49 %44 -%64 = OpLoad %9 %63 +%64 = OpLoad %3 %63 %67 = OpAccessChain %66 %52 %49 %44 -%68 = OpLoad %9 %67 -%69 = OpFAdd %9 %64 %68 +%68 = OpLoad %3 %67 +%69 = OpFAdd %3 %64 %68 %71 = OpCompositeConstruct %70 %43 %44 -%74 = OpImageQueryLevels %4 %53 +%74 = OpImageQueryLevels %18 %53 %75 = OpULessThan %72 %45 %74 OpSelectionMerge %76 None OpBranchConditional %75 %77 %76 @@ -131,24 +131,24 @@ OpBranchConditional %75 %77 %76 %81 = OpAll %72 %80 OpBranchConditional %81 %82 %76 %82 = OpLabel -%83 = OpImageFetch %9 %53 %71 Lod %45 +%83 = OpImageFetch %3 %53 %71 Lod %45 OpBranch %76 %76 = OpLabel -%84 = OpPhi %9 %73 %57 %73 %77 %83 %82 -%85 = OpFAdd %9 %69 %84 -%88 = OpExtInst %13 %1 UMin %44 %87 +%84 = OpPhi %3 %73 %57 %73 %77 %83 %82 +%85 = OpFAdd %3 %69 %84 +%88 = OpExtInst %7 %1 UMin %44 %87 %89 = OpAccessChain %86 %34 %88 -%90 = OpLoad %10 %89 -%91 = OpCompositeConstruct %9 %90 %90 %90 %90 -%92 = OpFAdd %9 %85 %91 -%95 = OpExtInst %13 %1 UMin %44 %94 +%90 = OpLoad %4 %89 +%91 = OpCompositeConstruct %3 %90 %90 %90 %90 +%92 = OpFAdd %3 %85 %91 +%95 = OpExtInst %7 %1 UMin %44 %94 %96 = OpAccessChain %93 %36 %95 -%97 = OpLoad %10 %96 -%98 = OpCompositeConstruct %9 %97 %97 %97 %97 -%99 = OpFAdd %9 %92 %98 -%102 = OpExtInst %13 %1 UMin %44 %101 +%97 = OpLoad %4 %96 +%98 = OpCompositeConstruct %3 %97 %97 %97 %97 +%99 = OpFAdd %3 %92 %98 +%102 = OpExtInst %7 %1 UMin %44 %101 %103 = OpAccessChain %100 %39 %102 -%104 = OpLoad %9 %103 -%105 = OpFAdd %9 %99 %104 +%104 = OpLoad %3 %103 +%105 = OpFAdd %3 %99 %104 OpReturnValue %105 OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/quad.spvasm b/tests/out/spv/quad.spvasm index 4c82c92b0..3de529f6b 100644 --- a/tests/out/spv/quad.spvasm +++ b/tests/out/spv/quad.spvasm @@ -10,10 +10,10 @@ OpEntryPoint Fragment %44 "frag_main" %41 %43 OpEntryPoint Fragment %60 "fs_extra" %59 OpExecutionMode %44 OriginUpperLeft OpExecutionMode %60 OriginUpperLeft -OpName %3 "c_scale" -OpMemberName %7 0 "uv" -OpMemberName %7 1 "position" -OpName %7 "VertexOutput" +OpMemberName %6 0 "uv" +OpMemberName %6 1 "position" +OpName %6 "VertexOutput" +OpName %9 "c_scale" OpName %10 "u_texture" OpName %12 "u_sampler" OpName %15 "pos" @@ -24,8 +24,8 @@ OpName %24 "vert_main" OpName %41 "uv" OpName %44 "frag_main" OpName %60 "fs_extra" -OpMemberDecorate %7 0 Offset 0 -OpMemberDecorate %7 1 Offset 16 +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %6 1 Offset 16 OpDecorate %10 DescriptorSet 0 OpDecorate %10 Binding 0 OpDecorate %12 DescriptorSet 0 @@ -38,73 +38,73 @@ OpDecorate %41 Location 0 OpDecorate %43 Location 0 OpDecorate %59 Location 0 %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpConstant %4 1.2 -%5 = OpTypeVector %4 2 -%6 = OpTypeVector %4 4 -%7 = OpTypeStruct %5 %6 -%8 = OpTypeImage %4 2D 0 0 0 1 Unknown -%9 = OpTypeSampler -%11 = OpTypePointer UniformConstant %8 +%3 = OpTypeFloat 32 +%4 = OpTypeVector %3 2 +%5 = OpTypeVector %3 4 +%6 = OpTypeStruct %4 %5 +%7 = OpTypeImage %3 2D 0 0 0 1 Unknown +%8 = OpTypeSampler +%9 = OpConstant %3 1.2 +%11 = OpTypePointer UniformConstant %7 %10 = OpVariable %11 UniformConstant -%13 = OpTypePointer UniformConstant %9 +%13 = OpTypePointer UniformConstant %8 %12 = OpVariable %13 UniformConstant -%16 = OpTypePointer Input %5 +%16 = OpTypePointer Input %4 %15 = OpVariable %16 Input %18 = OpVariable %16 Input -%21 = OpTypePointer Output %5 +%21 = OpTypePointer Output %4 %20 = OpVariable %21 Output -%23 = OpTypePointer Output %6 +%23 = OpTypePointer Output %5 %22 = OpVariable %23 Output %25 = OpTypeFunction %2 -%26 = OpConstant %4 0.0 -%27 = OpConstant %4 1.0 -%34 = OpTypePointer Output %4 +%26 = OpConstant %3 0.0 +%27 = OpConstant %3 1.0 +%34 = OpTypePointer Output %3 %36 = OpTypeInt 32 0 %35 = OpConstant %36 1 %41 = OpVariable %16 Input %43 = OpVariable %23 Output -%48 = OpTypeSampledImage %8 +%48 = OpTypeSampledImage %7 %52 = OpTypeBool %59 = OpVariable %23 Output -%61 = OpConstant %4 0.5 +%61 = OpConstant %3 0.5 %24 = OpFunction %2 None %25 %14 = OpLabel -%17 = OpLoad %5 %15 -%19 = OpLoad %5 %18 +%17 = OpLoad %4 %15 +%19 = OpLoad %4 %18 OpBranch %28 %28 = OpLabel -%29 = OpVectorTimesScalar %5 %17 %3 -%30 = OpCompositeConstruct %6 %29 %26 %27 -%31 = OpCompositeConstruct %7 %19 %30 -%32 = OpCompositeExtract %5 %31 0 +%29 = OpVectorTimesScalar %4 %17 %9 +%30 = OpCompositeConstruct %5 %29 %26 %27 +%31 = OpCompositeConstruct %6 %19 %30 +%32 = OpCompositeExtract %4 %31 0 OpStore %20 %32 -%33 = OpCompositeExtract %6 %31 1 +%33 = OpCompositeExtract %5 %31 1 OpStore %22 %33 %37 = OpAccessChain %34 %22 %35 -%38 = OpLoad %4 %37 -%39 = OpFNegate %4 %38 +%38 = OpLoad %3 %37 +%39 = OpFNegate %3 %38 OpStore %37 %39 OpReturn OpFunctionEnd %44 = OpFunction %2 None %25 %40 = OpLabel -%42 = OpLoad %5 %41 -%45 = OpLoad %8 %10 -%46 = OpLoad %9 %12 +%42 = OpLoad %4 %41 +%45 = OpLoad %7 %10 +%46 = OpLoad %8 %12 OpBranch %47 %47 = OpLabel %49 = OpSampledImage %48 %45 %46 -%50 = OpImageSampleImplicitLod %6 %49 %42 -%51 = OpCompositeExtract %4 %50 3 +%50 = OpImageSampleImplicitLod %5 %49 %42 +%51 = OpCompositeExtract %3 %50 3 %53 = OpFOrdEqual %52 %51 %26 OpSelectionMerge %54 None OpBranchConditional %53 %55 %54 %55 = OpLabel OpKill %54 = OpLabel -%56 = OpCompositeExtract %4 %50 3 -%57 = OpVectorTimesScalar %6 %50 %56 +%56 = OpCompositeExtract %3 %50 3 +%57 = OpVectorTimesScalar %5 %50 %56 OpStore %43 %57 OpReturn OpFunctionEnd @@ -112,7 +112,7 @@ OpFunctionEnd %58 = OpLabel OpBranch %62 %62 = OpLabel -%63 = OpCompositeConstruct %6 %26 %61 %26 %61 +%63 = OpCompositeConstruct %5 %26 %61 %26 %61 OpStore %59 %63 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index 26ee96559..20fd9ccbf 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,430 +1,429 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 271 +; Bound: 270 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %90 "vs_main" %80 %83 %85 %87 %89 -OpEntryPoint Fragment %149 "fs_main" %140 %143 %146 %148 -OpEntryPoint Fragment %218 "fs_main_without_storage" %211 %213 %215 %217 -OpExecutionMode %149 OriginUpperLeft -OpExecutionMode %218 OriginUpperLeft -OpName %7 "c_max_lights" -OpMemberName %13 0 "view_proj" -OpMemberName %13 1 "num_lights" -OpName %13 "Globals" -OpMemberName %14 0 "world" -OpMemberName %14 1 "color" -OpName %14 "Entity" -OpMemberName %16 0 "proj_position" -OpMemberName %16 1 "world_normal" -OpMemberName %16 2 "world_position" -OpName %16 "VertexOutput" -OpMemberName %19 0 "proj" -OpMemberName %19 1 "pos" -OpMemberName %19 2 "color" -OpName %19 "Light" -OpName %26 "c_ambient" -OpName %27 "u_globals" -OpName %30 "u_entity" -OpName %33 "s_lights" -OpName %36 "u_lights" -OpName %39 "t_shadow" -OpName %41 "sampler_shadow" -OpName %44 "light_id" -OpName %45 "homogeneous_coords" -OpName %46 "fetch_shadow" -OpName %76 "out" -OpName %80 "position" -OpName %83 "normal" -OpName %85 "proj_position" -OpName %87 "world_normal" -OpName %89 "world_position" -OpName %90 "vs_main" -OpName %133 "color" -OpName %135 "i" -OpName %140 "proj_position" -OpName %143 "world_normal" -OpName %146 "world_position" -OpName %149 "fs_main" -OpName %205 "color" -OpName %207 "i" -OpName %211 "proj_position" -OpName %213 "world_normal" -OpName %215 "world_position" -OpName %218 "fs_main_without_storage" -OpMemberDecorate %13 0 Offset 0 -OpMemberDecorate %13 0 ColMajor -OpMemberDecorate %13 0 MatrixStride 16 -OpMemberDecorate %13 1 Offset 64 -OpMemberDecorate %14 0 Offset 0 -OpMemberDecorate %14 0 ColMajor -OpMemberDecorate %14 0 MatrixStride 16 -OpMemberDecorate %14 1 Offset 64 -OpMemberDecorate %16 0 Offset 0 -OpMemberDecorate %16 1 Offset 16 -OpMemberDecorate %16 2 Offset 32 -OpMemberDecorate %19 0 Offset 0 -OpMemberDecorate %19 0 ColMajor -OpMemberDecorate %19 0 MatrixStride 16 -OpMemberDecorate %19 1 Offset 64 -OpMemberDecorate %19 2 Offset 80 -OpDecorate %20 ArrayStride 96 -OpDecorate %21 ArrayStride 96 -OpDecorate %27 DescriptorSet 0 -OpDecorate %27 Binding 0 -OpDecorate %28 Block -OpMemberDecorate %28 0 Offset 0 -OpDecorate %30 DescriptorSet 1 -OpDecorate %30 Binding 0 -OpDecorate %31 Block -OpMemberDecorate %31 0 Offset 0 -OpDecorate %33 NonWritable -OpDecorate %33 DescriptorSet 0 -OpDecorate %33 Binding 1 -OpDecorate %34 Block -OpMemberDecorate %34 0 Offset 0 -OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 1 -OpDecorate %37 Block -OpMemberDecorate %37 0 Offset 0 +OpEntryPoint Vertex %88 "vs_main" %78 %81 %83 %85 %87 +OpEntryPoint Fragment %148 "fs_main" %139 %142 %145 %147 +OpEntryPoint Fragment %217 "fs_main_without_storage" %210 %212 %214 %216 +OpExecutionMode %148 OriginUpperLeft +OpExecutionMode %217 OriginUpperLeft +OpMemberName %8 0 "view_proj" +OpMemberName %8 1 "num_lights" +OpName %8 "Globals" +OpMemberName %9 0 "world" +OpMemberName %9 1 "color" +OpName %9 "Entity" +OpMemberName %11 0 "proj_position" +OpMemberName %11 1 "world_normal" +OpMemberName %11 2 "world_position" +OpName %11 "VertexOutput" +OpMemberName %15 0 "proj" +OpMemberName %15 1 "pos" +OpMemberName %15 2 "color" +OpName %15 "Light" +OpName %24 "c_ambient" +OpName %18 "c_max_lights" +OpName %25 "u_globals" +OpName %28 "u_entity" +OpName %31 "s_lights" +OpName %34 "u_lights" +OpName %37 "t_shadow" +OpName %39 "sampler_shadow" +OpName %42 "light_id" +OpName %43 "homogeneous_coords" +OpName %44 "fetch_shadow" +OpName %74 "out" +OpName %78 "position" +OpName %81 "normal" +OpName %83 "proj_position" +OpName %85 "world_normal" +OpName %87 "world_position" +OpName %88 "vs_main" +OpName %132 "color" +OpName %134 "i" +OpName %139 "proj_position" +OpName %142 "world_normal" +OpName %145 "world_position" +OpName %148 "fs_main" +OpName %204 "color" +OpName %206 "i" +OpName %210 "proj_position" +OpName %212 "world_normal" +OpName %214 "world_position" +OpName %217 "fs_main_without_storage" +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %8 0 ColMajor +OpMemberDecorate %8 0 MatrixStride 16 +OpMemberDecorate %8 1 Offset 64 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 0 ColMajor +OpMemberDecorate %9 0 MatrixStride 16 +OpMemberDecorate %9 1 Offset 64 +OpMemberDecorate %11 0 Offset 0 +OpMemberDecorate %11 1 Offset 16 +OpMemberDecorate %11 2 Offset 32 +OpMemberDecorate %15 0 Offset 0 +OpMemberDecorate %15 0 ColMajor +OpMemberDecorate %15 0 MatrixStride 16 +OpMemberDecorate %15 1 Offset 64 +OpMemberDecorate %15 2 Offset 80 +OpDecorate %16 ArrayStride 96 +OpDecorate %17 ArrayStride 96 +OpDecorate %25 DescriptorSet 0 +OpDecorate %25 Binding 0 +OpDecorate %26 Block +OpMemberDecorate %26 0 Offset 0 +OpDecorate %28 DescriptorSet 1 +OpDecorate %28 Binding 0 +OpDecorate %29 Block +OpMemberDecorate %29 0 Offset 0 +OpDecorate %31 NonWritable +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 1 +OpDecorate %32 Block +OpMemberDecorate %32 0 Offset 0 +OpDecorate %34 DescriptorSet 0 +OpDecorate %34 Binding 1 +OpDecorate %35 Block +OpMemberDecorate %35 0 Offset 0 +OpDecorate %37 DescriptorSet 0 +OpDecorate %37 Binding 2 OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 2 -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 3 -OpDecorate %80 Location 0 -OpDecorate %83 Location 1 -OpDecorate %85 BuiltIn Position -OpDecorate %87 Location 0 -OpDecorate %89 Location 1 -OpDecorate %140 BuiltIn FragCoord -OpDecorate %143 Location 0 -OpDecorate %146 Location 1 -OpDecorate %148 Location 0 -OpDecorate %211 BuiltIn FragCoord -OpDecorate %213 Location 0 -OpDecorate %215 Location 1 -OpDecorate %217 Location 0 +OpDecorate %39 Binding 3 +OpDecorate %78 Location 0 +OpDecorate %81 Location 1 +OpDecorate %83 BuiltIn Position +OpDecorate %85 Location 0 +OpDecorate %87 Location 1 +OpDecorate %139 BuiltIn FragCoord +OpDecorate %142 Location 0 +OpDecorate %145 Location 1 +OpDecorate %147 Location 0 +OpDecorate %210 BuiltIn FragCoord +OpDecorate %212 Location 0 +OpDecorate %214 Location 1 +OpDecorate %216 Location 0 %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 10 -%6 = OpTypeFloat 32 -%5 = OpConstant %6 0.05 -%8 = OpTypeInt 32 0 -%7 = OpConstant %8 10 -%9 = OpConstant %8 1 -%11 = OpTypeVector %6 4 -%10 = OpTypeMatrix %11 4 -%12 = OpTypeVector %8 4 -%13 = OpTypeStruct %10 %12 -%14 = OpTypeStruct %10 %11 -%15 = OpTypeVector %6 3 -%16 = OpTypeStruct %11 %15 %11 -%17 = OpTypeVector %4 4 -%18 = OpTypeMatrix %15 3 -%19 = OpTypeStruct %10 %11 %11 -%20 = OpTypeRuntimeArray %19 -%22 = OpConstant %8 10 -%21 = OpTypeArray %19 %22 -%23 = OpTypeImage %6 2D 1 1 0 1 Unknown -%24 = OpTypeSampler -%25 = OpTypeVector %6 2 -%26 = OpConstantComposite %15 %5 %5 %5 -%28 = OpTypeStruct %13 -%29 = OpTypePointer Uniform %28 -%27 = OpVariable %29 Uniform -%31 = OpTypeStruct %14 -%32 = OpTypePointer Uniform %31 -%30 = OpVariable %32 Uniform -%34 = OpTypeStruct %20 -%35 = OpTypePointer StorageBuffer %34 -%33 = OpVariable %35 StorageBuffer -%37 = OpTypeStruct %21 -%38 = OpTypePointer Uniform %37 -%36 = OpVariable %38 Uniform -%40 = OpTypePointer UniformConstant %23 +%5 = OpTypeFloat 32 +%4 = OpTypeVector %5 4 +%3 = OpTypeMatrix %4 4 +%7 = OpTypeInt 32 0 +%6 = OpTypeVector %7 4 +%8 = OpTypeStruct %3 %6 +%9 = OpTypeStruct %3 %4 +%10 = OpTypeVector %5 3 +%11 = OpTypeStruct %4 %10 %4 +%13 = OpTypeInt 32 1 +%12 = OpTypeVector %13 4 +%14 = OpTypeMatrix %10 3 +%15 = OpTypeStruct %3 %4 %4 +%16 = OpTypeRuntimeArray %15 +%18 = OpConstant %7 10 +%17 = OpTypeArray %15 %18 +%19 = OpTypeImage %5 2D 1 1 0 1 Unknown +%20 = OpTypeSampler +%21 = OpTypeVector %5 2 +%22 = OpConstant %13 10 +%23 = OpConstant %5 0.05 +%24 = OpConstantComposite %10 %23 %23 %23 +%26 = OpTypeStruct %8 +%27 = OpTypePointer Uniform %26 +%25 = OpVariable %27 Uniform +%29 = OpTypeStruct %9 +%30 = OpTypePointer Uniform %29 +%28 = OpVariable %30 Uniform +%32 = OpTypeStruct %16 +%33 = OpTypePointer StorageBuffer %32 +%31 = OpVariable %33 StorageBuffer +%35 = OpTypeStruct %17 +%36 = OpTypePointer Uniform %35 +%34 = OpVariable %36 Uniform +%38 = OpTypePointer UniformConstant %19 +%37 = OpVariable %38 UniformConstant +%40 = OpTypePointer UniformConstant %20 %39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %24 -%41 = OpVariable %42 UniformConstant -%47 = OpTypeFunction %6 %8 %11 -%50 = OpConstant %6 0.0 -%51 = OpConstant %6 1.0 -%52 = OpConstant %6 0.5 -%53 = OpConstant %6 -0.5 -%56 = OpTypeBool -%71 = OpTypeSampledImage %23 -%77 = OpTypePointer Function %16 -%78 = OpConstantNull %16 -%81 = OpTypePointer Input %17 -%80 = OpVariable %81 Input -%83 = OpVariable %81 Input -%86 = OpTypePointer Output %11 +%45 = OpTypeFunction %5 %7 %4 +%48 = OpConstant %5 0.0 +%49 = OpConstant %5 1.0 +%50 = OpConstant %5 0.5 +%51 = OpConstant %5 -0.5 +%54 = OpTypeBool +%69 = OpTypeSampledImage %19 +%75 = OpTypePointer Function %11 +%76 = OpConstantNull %11 +%79 = OpTypePointer Input %12 +%78 = OpVariable %79 Input +%81 = OpVariable %79 Input +%84 = OpTypePointer Output %4 +%83 = OpVariable %84 Output +%86 = OpTypePointer Output %10 %85 = OpVariable %86 Output -%88 = OpTypePointer Output %15 -%87 = OpVariable %88 Output -%89 = OpVariable %86 Output -%91 = OpTypeFunction %2 -%92 = OpTypePointer Uniform %13 -%93 = OpConstant %8 0 -%95 = OpTypePointer Uniform %14 -%98 = OpTypePointer Uniform %10 -%105 = OpTypePointer Function %15 -%113 = OpTypeVector %4 3 -%118 = OpTypePointer Function %11 -%119 = OpConstant %8 2 -%127 = OpTypePointer Output %6 -%134 = OpConstantNull %15 -%136 = OpTypePointer Function %8 -%137 = OpConstantNull %8 -%141 = OpTypePointer Input %11 -%140 = OpVariable %141 Input -%144 = OpTypePointer Input %15 -%143 = OpVariable %144 Input -%146 = OpVariable %141 Input -%148 = OpVariable %86 Output -%152 = OpTypePointer StorageBuffer %20 -%164 = OpTypePointer Uniform %12 -%165 = OpTypePointer Uniform %8 -%175 = OpTypePointer StorageBuffer %19 -%201 = OpTypePointer Uniform %11 -%206 = OpConstantNull %15 -%208 = OpConstantNull %8 -%211 = OpVariable %141 Input -%213 = OpVariable %144 Input -%215 = OpVariable %141 Input -%217 = OpVariable %86 Output -%221 = OpTypePointer Uniform %21 -%242 = OpTypePointer Uniform %19 -%46 = OpFunction %6 None %47 -%44 = OpFunctionParameter %8 -%45 = OpFunctionParameter %11 -%43 = OpLabel -%48 = OpLoad %23 %39 -%49 = OpLoad %24 %41 -OpBranch %54 -%54 = OpLabel -%55 = OpCompositeExtract %6 %45 3 -%57 = OpFOrdLessThanEqual %56 %55 %50 -OpSelectionMerge %58 None -OpBranchConditional %57 %59 %58 -%59 = OpLabel -OpReturnValue %51 -%58 = OpLabel -%60 = OpCompositeConstruct %25 %52 %53 -%61 = OpCompositeExtract %6 %45 3 -%62 = OpFDiv %6 %51 %61 -%63 = OpVectorShuffle %25 %45 %45 0 1 -%64 = OpFMul %25 %63 %60 -%65 = OpVectorTimesScalar %25 %64 %62 -%66 = OpCompositeConstruct %25 %52 %52 -%67 = OpFAdd %25 %65 %66 -%68 = OpBitcast %4 %44 -%69 = OpCompositeExtract %6 %45 2 -%70 = OpFMul %6 %69 %62 -%72 = OpConvertSToF %6 %68 -%73 = OpCompositeConstruct %15 %67 %72 -%74 = OpSampledImage %71 %48 %49 -%75 = OpImageSampleDrefExplicitLod %6 %74 %73 %70 Lod %50 -OpReturnValue %75 +%87 = OpVariable %84 Output +%89 = OpTypeFunction %2 +%90 = OpTypePointer Uniform %8 +%91 = OpConstant %7 0 +%93 = OpTypePointer Uniform %9 +%96 = OpTypePointer Uniform %3 +%103 = OpTypePointer Function %10 +%111 = OpTypeVector %13 3 +%115 = OpConstant %7 1 +%117 = OpTypePointer Function %4 +%118 = OpConstant %7 2 +%126 = OpTypePointer Output %5 +%133 = OpConstantNull %10 +%135 = OpTypePointer Function %7 +%136 = OpConstantNull %7 +%140 = OpTypePointer Input %4 +%139 = OpVariable %140 Input +%143 = OpTypePointer Input %10 +%142 = OpVariable %143 Input +%145 = OpVariable %140 Input +%147 = OpVariable %84 Output +%151 = OpTypePointer StorageBuffer %16 +%163 = OpTypePointer Uniform %6 +%164 = OpTypePointer Uniform %7 +%174 = OpTypePointer StorageBuffer %15 +%200 = OpTypePointer Uniform %4 +%205 = OpConstantNull %10 +%207 = OpConstantNull %7 +%210 = OpVariable %140 Input +%212 = OpVariable %143 Input +%214 = OpVariable %140 Input +%216 = OpVariable %84 Output +%220 = OpTypePointer Uniform %17 +%241 = OpTypePointer Uniform %15 +%44 = OpFunction %5 None %45 +%42 = OpFunctionParameter %7 +%43 = OpFunctionParameter %4 +%41 = OpLabel +%46 = OpLoad %19 %37 +%47 = OpLoad %20 %39 +OpBranch %52 +%52 = OpLabel +%53 = OpCompositeExtract %5 %43 3 +%55 = OpFOrdLessThanEqual %54 %53 %48 +OpSelectionMerge %56 None +OpBranchConditional %55 %57 %56 +%57 = OpLabel +OpReturnValue %49 +%56 = OpLabel +%58 = OpCompositeConstruct %21 %50 %51 +%59 = OpCompositeExtract %5 %43 3 +%60 = OpFDiv %5 %49 %59 +%61 = OpVectorShuffle %21 %43 %43 0 1 +%62 = OpFMul %21 %61 %58 +%63 = OpVectorTimesScalar %21 %62 %60 +%64 = OpCompositeConstruct %21 %50 %50 +%65 = OpFAdd %21 %63 %64 +%66 = OpBitcast %13 %42 +%67 = OpCompositeExtract %5 %43 2 +%68 = OpFMul %5 %67 %60 +%70 = OpConvertSToF %5 %66 +%71 = OpCompositeConstruct %10 %65 %70 +%72 = OpSampledImage %69 %46 %47 +%73 = OpImageSampleDrefExplicitLod %5 %72 %71 %68 Lod %48 +OpReturnValue %73 OpFunctionEnd -%90 = OpFunction %2 None %91 -%79 = OpLabel -%76 = OpVariable %77 Function %78 -%82 = OpLoad %17 %80 -%84 = OpLoad %17 %83 -%94 = OpAccessChain %92 %27 %93 -%96 = OpAccessChain %95 %30 %93 -OpBranch %97 -%97 = OpLabel -%99 = OpAccessChain %98 %96 %93 -%100 = OpLoad %10 %99 -%101 = OpAccessChain %98 %96 %93 -%102 = OpLoad %10 %101 -%103 = OpConvertSToF %11 %82 -%104 = OpMatrixTimesVector %11 %102 %103 -%106 = OpCompositeExtract %11 %100 0 -%107 = OpVectorShuffle %15 %106 %106 0 1 2 -%108 = OpCompositeExtract %11 %100 1 -%109 = OpVectorShuffle %15 %108 %108 0 1 2 -%110 = OpCompositeExtract %11 %100 2 -%111 = OpVectorShuffle %15 %110 %110 0 1 2 -%112 = OpCompositeConstruct %18 %107 %109 %111 -%114 = OpVectorShuffle %113 %84 %84 0 1 2 -%115 = OpConvertSToF %15 %114 -%116 = OpMatrixTimesVector %15 %112 %115 -%117 = OpAccessChain %105 %76 %9 -OpStore %117 %116 -%120 = OpAccessChain %118 %76 %119 -OpStore %120 %104 -%121 = OpAccessChain %98 %94 %93 -%122 = OpLoad %10 %121 -%123 = OpMatrixTimesVector %11 %122 %104 -%124 = OpAccessChain %118 %76 %93 -OpStore %124 %123 -%125 = OpLoad %16 %76 -%126 = OpCompositeExtract %11 %125 0 -OpStore %85 %126 -%128 = OpAccessChain %127 %85 %9 -%129 = OpLoad %6 %128 -%130 = OpFNegate %6 %129 -OpStore %128 %130 -%131 = OpCompositeExtract %15 %125 1 +%88 = OpFunction %2 None %89 +%77 = OpLabel +%74 = OpVariable %75 Function %76 +%80 = OpLoad %12 %78 +%82 = OpLoad %12 %81 +%92 = OpAccessChain %90 %25 %91 +%94 = OpAccessChain %93 %28 %91 +OpBranch %95 +%95 = OpLabel +%97 = OpAccessChain %96 %94 %91 +%98 = OpLoad %3 %97 +%99 = OpAccessChain %96 %94 %91 +%100 = OpLoad %3 %99 +%101 = OpConvertSToF %4 %80 +%102 = OpMatrixTimesVector %4 %100 %101 +%104 = OpCompositeExtract %4 %98 0 +%105 = OpVectorShuffle %10 %104 %104 0 1 2 +%106 = OpCompositeExtract %4 %98 1 +%107 = OpVectorShuffle %10 %106 %106 0 1 2 +%108 = OpCompositeExtract %4 %98 2 +%109 = OpVectorShuffle %10 %108 %108 0 1 2 +%110 = OpCompositeConstruct %14 %105 %107 %109 +%112 = OpVectorShuffle %111 %82 %82 0 1 2 +%113 = OpConvertSToF %10 %112 +%114 = OpMatrixTimesVector %10 %110 %113 +%116 = OpAccessChain %103 %74 %115 +OpStore %116 %114 +%119 = OpAccessChain %117 %74 %118 +OpStore %119 %102 +%120 = OpAccessChain %96 %92 %91 +%121 = OpLoad %3 %120 +%122 = OpMatrixTimesVector %4 %121 %102 +%123 = OpAccessChain %117 %74 %91 +OpStore %123 %122 +%124 = OpLoad %11 %74 +%125 = OpCompositeExtract %4 %124 0 +OpStore %83 %125 +%127 = OpAccessChain %126 %83 %115 +%128 = OpLoad %5 %127 +%129 = OpFNegate %5 %128 +OpStore %127 %129 +%130 = OpCompositeExtract %10 %124 1 +OpStore %85 %130 +%131 = OpCompositeExtract %4 %124 2 OpStore %87 %131 -%132 = OpCompositeExtract %11 %125 2 -OpStore %89 %132 OpReturn OpFunctionEnd -%149 = OpFunction %2 None %91 -%138 = OpLabel -%133 = OpVariable %105 Function %134 -%135 = OpVariable %136 Function %137 -%142 = OpLoad %11 %140 -%145 = OpLoad %15 %143 -%147 = OpLoad %11 %146 -%139 = OpCompositeConstruct %16 %142 %145 %147 -%150 = OpAccessChain %92 %27 %93 -%151 = OpAccessChain %95 %30 %93 -%153 = OpAccessChain %152 %33 %93 -%154 = OpLoad %23 %39 -%155 = OpLoad %24 %41 -OpBranch %156 -%156 = OpLabel -%157 = OpCompositeExtract %15 %139 1 -%158 = OpExtInst %15 %1 Normalize %157 -OpStore %133 %26 -OpStore %135 %93 -OpBranch %159 -%159 = OpLabel -OpLoopMerge %160 %162 None -OpBranch %161 -%161 = OpLabel -%163 = OpLoad %8 %135 -%166 = OpAccessChain %165 %150 %9 %93 -%167 = OpLoad %8 %166 -%168 = OpExtInst %8 %1 UMin %167 %7 -%169 = OpULessThan %56 %163 %168 -OpSelectionMerge %170 None -OpBranchConditional %169 %170 %171 -%171 = OpLabel +%148 = OpFunction %2 None %89 +%137 = OpLabel +%132 = OpVariable %103 Function %133 +%134 = OpVariable %135 Function %136 +%141 = OpLoad %4 %139 +%144 = OpLoad %10 %142 +%146 = OpLoad %4 %145 +%138 = OpCompositeConstruct %11 %141 %144 %146 +%149 = OpAccessChain %90 %25 %91 +%150 = OpAccessChain %93 %28 %91 +%152 = OpAccessChain %151 %31 %91 +%153 = OpLoad %19 %37 +%154 = OpLoad %20 %39 +OpBranch %155 +%155 = OpLabel +%156 = OpCompositeExtract %10 %138 1 +%157 = OpExtInst %10 %1 Normalize %156 +OpStore %132 %24 +OpStore %134 %91 +OpBranch %158 +%158 = OpLabel +OpLoopMerge %159 %161 None OpBranch %160 +%160 = OpLabel +%162 = OpLoad %7 %134 +%165 = OpAccessChain %164 %149 %115 %91 +%166 = OpLoad %7 %165 +%167 = OpExtInst %7 %1 UMin %166 %18 +%168 = OpULessThan %54 %162 %167 +OpSelectionMerge %169 None +OpBranchConditional %168 %169 %170 %170 = OpLabel +OpBranch %159 +%169 = OpLabel +OpBranch %171 +%171 = OpLabel +%173 = OpLoad %7 %134 +%175 = OpAccessChain %174 %152 %173 +%176 = OpLoad %15 %175 +%177 = OpLoad %7 %134 +%178 = OpCompositeExtract %3 %176 0 +%179 = OpCompositeExtract %4 %138 2 +%180 = OpMatrixTimesVector %4 %178 %179 +%181 = OpFunctionCall %5 %44 %177 %180 +%182 = OpCompositeExtract %4 %176 1 +%183 = OpVectorShuffle %10 %182 %182 0 1 2 +%184 = OpCompositeExtract %4 %138 2 +%185 = OpVectorShuffle %10 %184 %184 0 1 2 +%186 = OpFSub %10 %183 %185 +%187 = OpExtInst %10 %1 Normalize %186 +%188 = OpDot %5 %157 %187 +%189 = OpExtInst %5 %1 FMax %48 %188 +%190 = OpFMul %5 %181 %189 +%191 = OpCompositeExtract %4 %176 2 +%192 = OpVectorShuffle %10 %191 %191 0 1 2 +%193 = OpVectorTimesScalar %10 %192 %190 +%194 = OpLoad %10 %132 +%195 = OpFAdd %10 %194 %193 +OpStore %132 %195 OpBranch %172 %172 = OpLabel -%174 = OpLoad %8 %135 -%176 = OpAccessChain %175 %153 %174 -%177 = OpLoad %19 %176 -%178 = OpLoad %8 %135 -%179 = OpCompositeExtract %10 %177 0 -%180 = OpCompositeExtract %11 %139 2 -%181 = OpMatrixTimesVector %11 %179 %180 -%182 = OpFunctionCall %6 %46 %178 %181 -%183 = OpCompositeExtract %11 %177 1 -%184 = OpVectorShuffle %15 %183 %183 0 1 2 -%185 = OpCompositeExtract %11 %139 2 -%186 = OpVectorShuffle %15 %185 %185 0 1 2 -%187 = OpFSub %15 %184 %186 -%188 = OpExtInst %15 %1 Normalize %187 -%189 = OpDot %6 %158 %188 -%190 = OpExtInst %6 %1 FMax %50 %189 -%191 = OpFMul %6 %182 %190 -%192 = OpCompositeExtract %11 %177 2 -%193 = OpVectorShuffle %15 %192 %192 0 1 2 -%194 = OpVectorTimesScalar %15 %193 %191 -%195 = OpLoad %15 %133 -%196 = OpFAdd %15 %195 %194 -OpStore %133 %196 -OpBranch %173 -%173 = OpLabel -OpBranch %162 -%162 = OpLabel -%197 = OpLoad %8 %135 -%198 = OpIAdd %8 %197 %9 -OpStore %135 %198 -OpBranch %159 -%160 = OpLabel -%199 = OpLoad %15 %133 -%200 = OpCompositeConstruct %11 %199 %51 -%202 = OpAccessChain %201 %151 %9 -%203 = OpLoad %11 %202 -%204 = OpFMul %11 %200 %203 -OpStore %148 %204 +OpBranch %161 +%161 = OpLabel +%196 = OpLoad %7 %134 +%197 = OpIAdd %7 %196 %115 +OpStore %134 %197 +OpBranch %158 +%159 = OpLabel +%198 = OpLoad %10 %132 +%199 = OpCompositeConstruct %4 %198 %49 +%201 = OpAccessChain %200 %150 %115 +%202 = OpLoad %4 %201 +%203 = OpFMul %4 %199 %202 +OpStore %147 %203 OpReturn OpFunctionEnd -%218 = OpFunction %2 None %91 -%209 = OpLabel -%205 = OpVariable %105 Function %206 -%207 = OpVariable %136 Function %208 -%212 = OpLoad %11 %211 -%214 = OpLoad %15 %213 -%216 = OpLoad %11 %215 -%210 = OpCompositeConstruct %16 %212 %214 %216 -%219 = OpAccessChain %92 %27 %93 -%220 = OpAccessChain %95 %30 %93 -%222 = OpAccessChain %221 %36 %93 -%223 = OpLoad %23 %39 -%224 = OpLoad %24 %41 -OpBranch %225 -%225 = OpLabel -%226 = OpCompositeExtract %15 %210 1 -%227 = OpExtInst %15 %1 Normalize %226 -OpStore %205 %26 -OpStore %207 %93 -OpBranch %228 -%228 = OpLabel -OpLoopMerge %229 %231 None -OpBranch %230 -%230 = OpLabel -%232 = OpLoad %8 %207 -%233 = OpAccessChain %165 %219 %9 %93 -%234 = OpLoad %8 %233 -%235 = OpExtInst %8 %1 UMin %234 %7 -%236 = OpULessThan %56 %232 %235 -OpSelectionMerge %237 None -OpBranchConditional %236 %237 %238 -%238 = OpLabel +%217 = OpFunction %2 None %89 +%208 = OpLabel +%204 = OpVariable %103 Function %205 +%206 = OpVariable %135 Function %207 +%211 = OpLoad %4 %210 +%213 = OpLoad %10 %212 +%215 = OpLoad %4 %214 +%209 = OpCompositeConstruct %11 %211 %213 %215 +%218 = OpAccessChain %90 %25 %91 +%219 = OpAccessChain %93 %28 %91 +%221 = OpAccessChain %220 %34 %91 +%222 = OpLoad %19 %37 +%223 = OpLoad %20 %39 +OpBranch %224 +%224 = OpLabel +%225 = OpCompositeExtract %10 %209 1 +%226 = OpExtInst %10 %1 Normalize %225 +OpStore %204 %24 +OpStore %206 %91 +OpBranch %227 +%227 = OpLabel +OpLoopMerge %228 %230 None OpBranch %229 +%229 = OpLabel +%231 = OpLoad %7 %206 +%232 = OpAccessChain %164 %218 %115 %91 +%233 = OpLoad %7 %232 +%234 = OpExtInst %7 %1 UMin %233 %18 +%235 = OpULessThan %54 %231 %234 +OpSelectionMerge %236 None +OpBranchConditional %235 %236 %237 %237 = OpLabel +OpBranch %228 +%236 = OpLabel +OpBranch %238 +%238 = OpLabel +%240 = OpLoad %7 %206 +%242 = OpAccessChain %241 %221 %240 +%243 = OpLoad %15 %242 +%244 = OpLoad %7 %206 +%245 = OpCompositeExtract %3 %243 0 +%246 = OpCompositeExtract %4 %209 2 +%247 = OpMatrixTimesVector %4 %245 %246 +%248 = OpFunctionCall %5 %44 %244 %247 +%249 = OpCompositeExtract %4 %243 1 +%250 = OpVectorShuffle %10 %249 %249 0 1 2 +%251 = OpCompositeExtract %4 %209 2 +%252 = OpVectorShuffle %10 %251 %251 0 1 2 +%253 = OpFSub %10 %250 %252 +%254 = OpExtInst %10 %1 Normalize %253 +%255 = OpDot %5 %226 %254 +%256 = OpExtInst %5 %1 FMax %48 %255 +%257 = OpFMul %5 %248 %256 +%258 = OpCompositeExtract %4 %243 2 +%259 = OpVectorShuffle %10 %258 %258 0 1 2 +%260 = OpVectorTimesScalar %10 %259 %257 +%261 = OpLoad %10 %204 +%262 = OpFAdd %10 %261 %260 +OpStore %204 %262 OpBranch %239 %239 = OpLabel -%241 = OpLoad %8 %207 -%243 = OpAccessChain %242 %222 %241 -%244 = OpLoad %19 %243 -%245 = OpLoad %8 %207 -%246 = OpCompositeExtract %10 %244 0 -%247 = OpCompositeExtract %11 %210 2 -%248 = OpMatrixTimesVector %11 %246 %247 -%249 = OpFunctionCall %6 %46 %245 %248 -%250 = OpCompositeExtract %11 %244 1 -%251 = OpVectorShuffle %15 %250 %250 0 1 2 -%252 = OpCompositeExtract %11 %210 2 -%253 = OpVectorShuffle %15 %252 %252 0 1 2 -%254 = OpFSub %15 %251 %253 -%255 = OpExtInst %15 %1 Normalize %254 -%256 = OpDot %6 %227 %255 -%257 = OpExtInst %6 %1 FMax %50 %256 -%258 = OpFMul %6 %249 %257 -%259 = OpCompositeExtract %11 %244 2 -%260 = OpVectorShuffle %15 %259 %259 0 1 2 -%261 = OpVectorTimesScalar %15 %260 %258 -%262 = OpLoad %15 %205 -%263 = OpFAdd %15 %262 %261 -OpStore %205 %263 -OpBranch %240 -%240 = OpLabel -OpBranch %231 -%231 = OpLabel -%264 = OpLoad %8 %207 -%265 = OpIAdd %8 %264 %9 -OpStore %207 %265 -OpBranch %228 -%229 = OpLabel -%266 = OpLoad %15 %205 -%267 = OpCompositeConstruct %11 %266 %51 -%268 = OpAccessChain %201 %220 %9 -%269 = OpLoad %11 %268 -%270 = OpFMul %11 %267 %269 -OpStore %217 %270 +OpBranch %230 +%230 = OpLabel +%263 = OpLoad %7 %206 +%264 = OpIAdd %7 %263 %115 +OpStore %206 %264 +OpBranch %227 +%228 = OpLabel +%265 = OpLoad %10 %204 +%266 = OpCompositeConstruct %4 %265 %49 +%267 = OpAccessChain %200 %219 %115 +%268 = OpLoad %4 %267 +%269 = OpFMul %4 %266 %268 +OpStore %216 %269 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/workgroup-uniform-load.spvasm b/tests/out/spv/workgroup-uniform-load.spvasm index c8ae47c2f..87f212a79 100644 --- a/tests/out/spv/workgroup-uniform-load.spvasm +++ b/tests/out/spv/workgroup-uniform-load.spvasm @@ -1,67 +1,66 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 41 +; Bound: 40 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %15 "test_workgroupUniformLoad" %12 %20 -OpExecutionMode %15 LocalSize 4 1 1 -OpDecorate %6 ArrayStride 4 -OpDecorate %12 BuiltIn WorkgroupId -OpDecorate %20 BuiltIn LocalInvocationId +OpEntryPoint GLCompute %14 "test_workgroupUniformLoad" %11 %19 +OpExecutionMode %14 LocalSize 4 1 1 +OpDecorate %5 ArrayStride 4 +OpDecorate %11 BuiltIn WorkgroupId +OpDecorate %19 BuiltIn LocalInvocationId %2 = OpTypeVoid -%4 = OpTypeInt 32 0 -%3 = OpConstant %4 128 -%5 = OpTypeInt 32 1 -%7 = OpConstant %4 128 -%6 = OpTypeArray %5 %7 -%8 = OpTypeVector %4 3 -%10 = OpTypePointer Workgroup %6 -%9 = OpVariable %10 Workgroup -%13 = OpTypePointer Input %8 -%12 = OpVariable %13 Input -%16 = OpTypeFunction %2 -%17 = OpConstant %5 10 -%19 = OpConstantNull %6 -%21 = OpTypePointer Input %8 -%20 = OpVariable %21 Input -%23 = OpConstantNull %8 -%25 = OpTypeBool -%24 = OpTypeVector %25 3 -%30 = OpConstant %4 2 -%31 = OpConstant %4 264 -%34 = OpTypePointer Workgroup %5 -%15 = OpFunction %2 None %16 -%11 = OpLabel -%14 = OpLoad %8 %12 -OpBranch %18 -%18 = OpLabel -%22 = OpLoad %8 %20 -%26 = OpIEqual %24 %22 %23 -%27 = OpAll %25 %26 -OpSelectionMerge %28 None -OpBranchConditional %27 %29 %28 -%29 = OpLabel -OpStore %9 %19 -OpBranch %28 +%3 = OpTypeInt 32 0 +%4 = OpTypeInt 32 1 +%6 = OpConstant %3 128 +%5 = OpTypeArray %4 %6 +%7 = OpTypeVector %3 3 +%9 = OpTypePointer Workgroup %5 +%8 = OpVariable %9 Workgroup +%12 = OpTypePointer Input %7 +%11 = OpVariable %12 Input +%15 = OpTypeFunction %2 +%16 = OpConstant %4 10 +%18 = OpConstantNull %5 +%20 = OpTypePointer Input %7 +%19 = OpVariable %20 Input +%22 = OpConstantNull %7 +%24 = OpTypeBool +%23 = OpTypeVector %24 3 +%29 = OpConstant %3 2 +%30 = OpConstant %3 264 +%33 = OpTypePointer Workgroup %4 +%14 = OpFunction %2 None %15 +%10 = OpLabel +%13 = OpLoad %7 %11 +OpBranch %17 +%17 = OpLabel +%21 = OpLoad %7 %19 +%25 = OpIEqual %23 %21 %22 +%26 = OpAll %24 %25 +OpSelectionMerge %27 None +OpBranchConditional %26 %28 %27 %28 = OpLabel -OpControlBarrier %30 %30 %31 -OpBranch %32 -%32 = OpLabel -%33 = OpCompositeExtract %4 %14 0 -OpControlBarrier %30 %30 %31 -%35 = OpAccessChain %34 %9 %33 -%36 = OpLoad %5 %35 -OpControlBarrier %30 %30 %31 -%37 = OpSGreaterThan %25 %36 %17 -OpSelectionMerge %38 None -OpBranchConditional %37 %39 %40 -%39 = OpLabel -OpControlBarrier %30 %30 %31 -OpReturn -%40 = OpLabel -OpReturn +OpStore %8 %18 +OpBranch %27 +%27 = OpLabel +OpControlBarrier %29 %29 %30 +OpBranch %31 +%31 = OpLabel +%32 = OpCompositeExtract %3 %13 0 +OpControlBarrier %29 %29 %30 +%34 = OpAccessChain %33 %8 %32 +%35 = OpLoad %4 %34 +OpControlBarrier %29 %29 %30 +%36 = OpSGreaterThan %24 %35 %16 +OpSelectionMerge %37 None +OpBranchConditional %36 %38 %39 %38 = OpLabel +OpControlBarrier %29 %29 %30 +OpReturn +%39 = OpLabel +OpReturn +%37 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/workgroup-var-init.spvasm b/tests/out/spv/workgroup-var-init.spvasm index e95a11aa9..905ed00bf 100644 --- a/tests/out/spv/workgroup-var-init.spvasm +++ b/tests/out/spv/workgroup-var-init.spvasm @@ -8,53 +8,53 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %19 "main" %27 OpExecutionMode %19 LocalSize 1 1 1 -OpMemberName %12 0 "arr" -OpMemberName %12 1 "atom" -OpMemberName %12 2 "atom_arr" -OpName %12 "WStruct" +OpMemberName %10 0 "arr" +OpMemberName %10 1 "atom" +OpMemberName %10 2 "atom_arr" +OpName %10 "WStruct" OpName %13 "w_mem" OpName %15 "output" OpName %19 "main" +OpDecorate %4 ArrayStride 4 OpDecorate %7 ArrayStride 4 -OpDecorate %9 ArrayStride 4 -OpDecorate %11 ArrayStride 32 -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 2048 -OpMemberDecorate %12 2 Offset 2052 +OpDecorate %9 ArrayStride 32 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 2048 +OpMemberDecorate %10 2 Offset 2052 OpDecorate %15 DescriptorSet 0 OpDecorate %15 Binding 0 OpDecorate %16 Block OpMemberDecorate %16 0 Offset 0 OpDecorate %27 BuiltIn LocalInvocationId %2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 512 -%5 = OpConstant %4 8 -%6 = OpTypeInt 32 0 -%8 = OpConstant %6 512 +%3 = OpTypeInt 32 0 +%5 = OpConstant %3 512 +%4 = OpTypeArray %3 %5 +%6 = OpTypeInt 32 1 +%8 = OpConstant %3 8 %7 = OpTypeArray %6 %8 -%10 = OpConstant %6 8 -%9 = OpTypeArray %4 %10 -%11 = OpTypeArray %9 %10 -%12 = OpTypeStruct %7 %4 %11 -%14 = OpTypePointer Workgroup %12 +%9 = OpTypeArray %7 %8 +%10 = OpTypeStruct %4 %6 %9 +%11 = OpConstant %6 512 +%12 = OpConstant %6 8 +%14 = OpTypePointer Workgroup %10 %13 = OpVariable %14 Workgroup -%16 = OpTypeStruct %7 +%16 = OpTypeStruct %4 %17 = OpTypePointer StorageBuffer %16 %15 = OpVariable %17 StorageBuffer %20 = OpTypeFunction %2 -%21 = OpTypePointer StorageBuffer %7 -%22 = OpConstant %6 0 -%25 = OpConstantNull %12 -%26 = OpTypeVector %6 3 +%21 = OpTypePointer StorageBuffer %4 +%22 = OpConstant %3 0 +%25 = OpConstantNull %10 +%26 = OpTypeVector %3 3 %28 = OpTypePointer Input %26 %27 = OpVariable %28 Input %30 = OpConstantNull %26 %32 = OpTypeBool %31 = OpTypeVector %32 3 -%37 = OpConstant %6 2 -%38 = OpConstant %6 264 -%40 = OpTypePointer Workgroup %7 +%37 = OpConstant %3 2 +%38 = OpConstant %3 264 +%40 = OpTypePointer Workgroup %4 %19 = OpFunction %2 None %20 %18 = OpLabel %23 = OpAccessChain %21 %15 %22 @@ -73,7 +73,7 @@ OpControlBarrier %37 %37 %38 OpBranch %39 %39 = OpLabel %41 = OpAccessChain %40 %13 %22 -%42 = OpLoad %7 %41 +%42 = OpLoad %4 %41 OpStore %23 %42 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index c8b87516f..77ebe1ee1 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -41,8 +41,8 @@ fn test_matrix_within_struct_accesses() { var t: Baz; idx = 1; - let _e2 = idx; - idx = (_e2 - 1); + let _e3 = idx; + idx = (_e3 - 1); let l0_ = baz.m; let l1_ = baz.m[0]; let _e15 = idx; @@ -56,8 +56,8 @@ fn test_matrix_within_struct_accesses() { let _e43 = idx; let l6_ = baz.m[_e41][_e43]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - let _e55 = idx; - idx = (_e55 + 1); + let _e56 = idx; + idx = (_e56 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); let _e72 = idx; @@ -78,8 +78,8 @@ fn test_matrix_within_array_within_struct_accesses() { var t_1: MatCx2InArray; idx_1 = 1; - let _e2 = idx_1; - idx_1 = (_e2 - 1); + let _e3 = idx_1; + idx_1 = (_e3 - 1); let l0_1 = nested_mat_cx2_.am; let l1_1 = nested_mat_cx2_.am[0]; let l2_1 = nested_mat_cx2_.am[0][0]; @@ -94,8 +94,8 @@ fn test_matrix_within_array_within_struct_accesses() { let _e60 = idx_1; let l7_ = nested_mat_cx2_.am[0][_e58][_e60]; t_1 = MatCx2InArray(array, 2>()); - let _e66 = idx_1; - idx_1 = (_e66 + 1); + let _e67 = idx_1; + idx_1 = (_e67 + 1); t_1.am = array, 2>(); t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); t_1.am[0][0] = vec2(9.0); diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/tests/out/wgsl/atomicCompareExchange.wgsl index d9f0c0add..2ff428bd7 100644 --- a/tests/out/wgsl/atomicCompareExchange.wgsl +++ b/tests/out/wgsl/atomicCompareExchange.wgsl @@ -51,8 +51,8 @@ fn test_atomic_compare_exchange_i32_() { } } continuing { - let _e26 = i; - i = (_e26 + 1u); + let _e27 = i; + i = (_e27 + 1u); } } return; @@ -94,8 +94,8 @@ fn test_atomic_compare_exchange_u32_() { } } continuing { - let _e26 = i_1; - i_1 = (_e26 + 1u); + let _e27 = i_1; + i_1 = (_e27 + 1u); } } return; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 41fc6e399..249298dcc 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -49,10 +49,8 @@ struct FragmentOutput { } const MAX_POINT_LIGHTS: i32 = 10; - const MAX_DIRECTIONAL_LIGHTS: i32 = 1; - -const PI: f32 = 3.1415927410125732; +const PI: f32 = 3.1415927; var v_WorldPosition_1: vec3; var v_WorldNormal_1: vec3; diff --git a/tests/out/wgsl/binding-arrays.dynamic.wgsl b/tests/out/wgsl/binding-arrays.dynamic.wgsl index 523b31127..bccabd060 100644 --- a/tests/out/wgsl/binding-arrays.dynamic.wgsl +++ b/tests/out/wgsl/binding-arrays.dynamic.wgsl @@ -5,8 +5,8 @@ var global_1: binding_array; var global_2: vec4; fn function() { - let _e13 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); - global_2 = _e13; + let _e9 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); + global_2 = _e9; return; } diff --git a/tests/out/wgsl/binding-arrays.static.wgsl b/tests/out/wgsl/binding-arrays.static.wgsl index 2c1fb2be7..e9dec5bf1 100644 --- a/tests/out/wgsl/binding-arrays.static.wgsl +++ b/tests/out/wgsl/binding-arrays.static.wgsl @@ -5,8 +5,8 @@ var global_1: binding_array; var global_2: vec4; fn function() { - let _e14 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); - global_2 = _e14; + let _e10 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); + global_2 = _e10; return; } diff --git a/tests/out/wgsl/binding-arrays.wgsl b/tests/out/wgsl/binding-arrays.wgsl index 97c992e4e..7f181413b 100644 --- a/tests/out/wgsl/binding-arrays.wgsl +++ b/tests/out/wgsl/binding-arrays.wgsl @@ -49,124 +49,124 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { let _e32 = textureDimensions(texture_array_unbounded[non_uniform_index]); let _e33 = u2_; u2_ = (_e33 + _e32); - let _e41 = textureGather(0, texture_array_bounded[0], samp[0], uv); - let _e42 = v4_; - v4_ = (_e42 + _e41); - let _e48 = textureGather(0, texture_array_bounded[uniform_index], samp[uniform_index], uv); - let _e49 = v4_; - v4_ = (_e49 + _e48); - let _e55 = textureGather(0, texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); - let _e56 = v4_; - v4_ = (_e56 + _e55); - let _e65 = textureGatherCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); - let _e66 = v4_; - v4_ = (_e66 + _e65); - let _e73 = textureGatherCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); - let _e74 = v4_; - v4_ = (_e74 + _e73); - let _e81 = textureGatherCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); - let _e82 = v4_; - v4_ = (_e82 + _e81); - let _e88 = textureLoad(texture_array_unbounded[0], pix, 0); - let _e89 = v4_; - v4_ = (_e89 + _e88); - let _e94 = textureLoad(texture_array_unbounded[uniform_index], pix, 0); - let _e95 = v4_; - v4_ = (_e95 + _e94); - let _e100 = textureLoad(texture_array_unbounded[non_uniform_index], pix, 0); - let _e101 = v4_; - v4_ = (_e101 + _e100); - let _e106 = textureNumLayers(texture_array_2darray[0]); - let _e107 = u1_; - u1_ = (_e107 + _e106); - let _e111 = textureNumLayers(texture_array_2darray[uniform_index]); - let _e112 = u1_; - u1_ = (_e112 + _e111); - let _e116 = textureNumLayers(texture_array_2darray[non_uniform_index]); - let _e117 = u1_; - u1_ = (_e117 + _e116); - let _e122 = textureNumLevels(texture_array_bounded[0]); - let _e123 = u1_; - u1_ = (_e123 + _e122); - let _e127 = textureNumLevels(texture_array_bounded[uniform_index]); - let _e128 = u1_; - u1_ = (_e128 + _e127); - let _e132 = textureNumLevels(texture_array_bounded[non_uniform_index]); - let _e133 = u1_; - u1_ = (_e133 + _e132); - let _e138 = textureNumSamples(texture_array_multisampled[0]); - let _e139 = u1_; - u1_ = (_e139 + _e138); - let _e143 = textureNumSamples(texture_array_multisampled[uniform_index]); - let _e144 = u1_; - u1_ = (_e144 + _e143); - let _e148 = textureNumSamples(texture_array_multisampled[non_uniform_index]); - let _e149 = u1_; - u1_ = (_e149 + _e148); - let _e157 = textureSample(texture_array_bounded[0], samp[0], uv); - let _e158 = v4_; - v4_ = (_e158 + _e157); - let _e164 = textureSample(texture_array_bounded[uniform_index], samp[uniform_index], uv); - let _e165 = v4_; - v4_ = (_e165 + _e164); - let _e171 = textureSample(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); - let _e172 = v4_; - v4_ = (_e172 + _e171); - let _e181 = textureSampleBias(texture_array_bounded[0], samp[0], uv, 0.0); - let _e182 = v4_; - v4_ = (_e182 + _e181); - let _e189 = textureSampleBias(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); - let _e190 = v4_; - v4_ = (_e190 + _e189); - let _e197 = textureSampleBias(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); - let _e198 = v4_; - v4_ = (_e198 + _e197); - let _e207 = textureSampleCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); - let _e208 = v1_; - v1_ = (_e208 + _e207); - let _e215 = textureSampleCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); - let _e216 = v1_; - v1_ = (_e216 + _e215); - let _e223 = textureSampleCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); - let _e224 = v1_; - v1_ = (_e224 + _e223); - let _e233 = textureSampleCompareLevel(texture_array_depth[0], samp_comp[0], uv, 0.0); - let _e234 = v1_; - v1_ = (_e234 + _e233); - let _e241 = textureSampleCompareLevel(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); - let _e242 = v1_; - v1_ = (_e242 + _e241); - let _e249 = textureSampleCompareLevel(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); - let _e250 = v1_; - v1_ = (_e250 + _e249); - let _e258 = textureSampleGrad(texture_array_bounded[0], samp[0], uv, uv, uv); - let _e259 = v4_; - v4_ = (_e259 + _e258); - let _e265 = textureSampleGrad(texture_array_bounded[uniform_index], samp[uniform_index], uv, uv, uv); - let _e266 = v4_; - v4_ = (_e266 + _e265); - let _e272 = textureSampleGrad(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, uv, uv); - let _e273 = v4_; - v4_ = (_e273 + _e272); - let _e282 = textureSampleLevel(texture_array_bounded[0], samp[0], uv, 0.0); - let _e283 = v4_; - v4_ = (_e283 + _e282); - let _e290 = textureSampleLevel(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); - let _e291 = v4_; - v4_ = (_e291 + _e290); - let _e298 = textureSampleLevel(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); - let _e299 = v4_; - v4_ = (_e299 + _e298); - let _e304 = v4_; - textureStore(texture_array_storage[0], pix, _e304); + let _e42 = textureGather(0, texture_array_bounded[0], samp[0], uv); + let _e43 = v4_; + v4_ = (_e43 + _e42); + let _e50 = textureGather(0, texture_array_bounded[uniform_index], samp[uniform_index], uv); + let _e51 = v4_; + v4_ = (_e51 + _e50); + let _e58 = textureGather(0, texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); + let _e59 = v4_; + v4_ = (_e59 + _e58); + let _e68 = textureGatherCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e69 = v4_; + v4_ = (_e69 + _e68); + let _e76 = textureGatherCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + let _e77 = v4_; + v4_ = (_e77 + _e76); + let _e84 = textureGatherCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + let _e85 = v4_; + v4_ = (_e85 + _e84); + let _e91 = textureLoad(texture_array_unbounded[0], pix, 0); + let _e92 = v4_; + v4_ = (_e92 + _e91); + let _e97 = textureLoad(texture_array_unbounded[uniform_index], pix, 0); + let _e98 = v4_; + v4_ = (_e98 + _e97); + let _e103 = textureLoad(texture_array_unbounded[non_uniform_index], pix, 0); + let _e104 = v4_; + v4_ = (_e104 + _e103); + let _e109 = textureNumLayers(texture_array_2darray[0]); + let _e110 = u1_; + u1_ = (_e110 + _e109); + let _e114 = textureNumLayers(texture_array_2darray[uniform_index]); + let _e115 = u1_; + u1_ = (_e115 + _e114); + let _e119 = textureNumLayers(texture_array_2darray[non_uniform_index]); + let _e120 = u1_; + u1_ = (_e120 + _e119); + let _e125 = textureNumLevels(texture_array_bounded[0]); + let _e126 = u1_; + u1_ = (_e126 + _e125); + let _e130 = textureNumLevels(texture_array_bounded[uniform_index]); + let _e131 = u1_; + u1_ = (_e131 + _e130); + let _e135 = textureNumLevels(texture_array_bounded[non_uniform_index]); + let _e136 = u1_; + u1_ = (_e136 + _e135); + let _e141 = textureNumSamples(texture_array_multisampled[0]); + let _e142 = u1_; + u1_ = (_e142 + _e141); + let _e146 = textureNumSamples(texture_array_multisampled[uniform_index]); + let _e147 = u1_; + u1_ = (_e147 + _e146); + let _e151 = textureNumSamples(texture_array_multisampled[non_uniform_index]); + let _e152 = u1_; + u1_ = (_e152 + _e151); + let _e160 = textureSample(texture_array_bounded[0], samp[0], uv); + let _e161 = v4_; + v4_ = (_e161 + _e160); + let _e167 = textureSample(texture_array_bounded[uniform_index], samp[uniform_index], uv); + let _e168 = v4_; + v4_ = (_e168 + _e167); + let _e174 = textureSample(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); + let _e175 = v4_; + v4_ = (_e175 + _e174); + let _e184 = textureSampleBias(texture_array_bounded[0], samp[0], uv, 0.0); + let _e185 = v4_; + v4_ = (_e185 + _e184); + let _e192 = textureSampleBias(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + let _e193 = v4_; + v4_ = (_e193 + _e192); + let _e200 = textureSampleBias(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); + let _e201 = v4_; + v4_ = (_e201 + _e200); + let _e210 = textureSampleCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e211 = v1_; + v1_ = (_e211 + _e210); + let _e218 = textureSampleCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + let _e219 = v1_; + v1_ = (_e219 + _e218); + let _e226 = textureSampleCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + let _e227 = v1_; + v1_ = (_e227 + _e226); + let _e236 = textureSampleCompareLevel(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e237 = v1_; + v1_ = (_e237 + _e236); + let _e244 = textureSampleCompareLevel(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + let _e245 = v1_; + v1_ = (_e245 + _e244); + let _e252 = textureSampleCompareLevel(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + let _e253 = v1_; + v1_ = (_e253 + _e252); + let _e261 = textureSampleGrad(texture_array_bounded[0], samp[0], uv, uv, uv); + let _e262 = v4_; + v4_ = (_e262 + _e261); + let _e268 = textureSampleGrad(texture_array_bounded[uniform_index], samp[uniform_index], uv, uv, uv); + let _e269 = v4_; + v4_ = (_e269 + _e268); + let _e275 = textureSampleGrad(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, uv, uv); + let _e276 = v4_; + v4_ = (_e276 + _e275); + let _e285 = textureSampleLevel(texture_array_bounded[0], samp[0], uv, 0.0); + let _e286 = v4_; + v4_ = (_e286 + _e285); + let _e293 = textureSampleLevel(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + let _e294 = v4_; + v4_ = (_e294 + _e293); + let _e301 = textureSampleLevel(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); + let _e302 = v4_; + v4_ = (_e302 + _e301); let _e307 = v4_; - textureStore(texture_array_storage[uniform_index], pix, _e307); + textureStore(texture_array_storage[0], pix, _e307); let _e310 = v4_; - textureStore(texture_array_storage[non_uniform_index], pix, _e310); - let _e311 = u2_; - let _e312 = u1_; - let v2_ = vec2((_e311 + vec2(_e312))); - let _e316 = v4_; - let _e323 = v1_; - return ((_e316 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e323)); + textureStore(texture_array_storage[uniform_index], pix, _e310); + let _e313 = v4_; + textureStore(texture_array_storage[non_uniform_index], pix, _e313); + let _e314 = u2_; + let _e315 = u1_; + let v2_ = vec2((_e314 + vec2(_e315))); + let _e319 = v4_; + let _e326 = v1_; + return ((_e319 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e326)); } diff --git a/tests/out/wgsl/do-while.wgsl b/tests/out/wgsl/do-while.wgsl index 2940016da..50ed369f4 100644 --- a/tests/out/wgsl/do-while.wgsl +++ b/tests/out/wgsl/do-while.wgsl @@ -2,8 +2,8 @@ fn fb1_(cond: ptr) { loop { continue; continuing { - let _e6 = (*cond); - break if !(_e6); + let _e2 = (*cond); + break if !(_e2); } } return; diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index c84e56ad8..11aa6b96e 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -6,8 +6,8 @@ struct type_1 { var unnamed: type_1; fn function() { - let _e8 = unnamed.member; - unnamed.member = (_e8 + 1); + let _e4 = unnamed.member; + unnamed.member = (_e4 + 1); return; } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index fc821ca8e..e8e1a9f98 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -15,6 +15,7 @@ struct FragmentOutput { } const strct: TestStruct = TestStruct(array, 2>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); + var global: f32; @group(0) @binding(0) var global_1: a_buf; @@ -401,7 +402,7 @@ fn testConstantLength(a_24: array) { fn indexConstantNonConstantIndex(i: i32) { var i_1: i32; - var local_5: TestStruct = TestStruct(array, 2>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); + var local_5: TestStruct = strct; var a_26: vec4; i_1 = i; diff --git a/tests/out/wgsl/global-constant-array-frag.wgsl b/tests/out/wgsl/global-constant-array-frag.wgsl index a82ad9483..d6d4bfb61 100644 --- a/tests/out/wgsl/global-constant-array-frag.wgsl +++ b/tests/out/wgsl/global-constant-array-frag.wgsl @@ -1,8 +1,9 @@ const array_: array = array(1.0, 2.0); + var i: u32; fn main_1() { - var local: array = array(1.0, 2.0); + var local: array = array_; let _e2 = i; } diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl index 10f5d2594..e68413c27 100644 --- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl +++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl @@ -5,12 +5,12 @@ fn main_1() { var c: f32; var d: f32; + let _e4 = a; + b = asinh(_e4); + let _e6 = a; + c = acosh(_e6); let _e8 = a; - b = asinh(_e8); - let _e10 = a; - c = acosh(_e10); - let _e12 = a; - d = atanh(_e12); + d = atanh(_e8); return; } diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/tests/out/wgsl/lexical-scopes.wgsl index d44f6679f..22e59030c 100644 --- a/tests/out/wgsl/lexical-scopes.wgsl +++ b/tests/out/wgsl/lexical-scopes.wgsl @@ -33,8 +33,8 @@ fn forLexicalScope(a_3: f32) { { } continuing { - let _e7 = a_4; - a_4 = (_e7 + 1); + let _e8 = a_4; + a_4 = (_e8 + 1); } } return; diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index fc7204045..41a9c821a 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -7,15 +7,16 @@ const v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); const v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); const v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); const v_i32_one: vec4 = vec4(1, 1, 1, 1); + fn builtins() -> vec4 { let s1_ = select(0, 1, true); - let s2_ = select(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), true); - let s3_ = select(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), vec4(false, false, false, false)); - let m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5)); - let m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.1); - let b1_ = bitcast(vec4(1, 1, 1, 1).x); - let b2_ = bitcast>(vec4(1, 1, 1, 1)); - let v_i32_zero = vec4(vec4(0.0, 0.0, 0.0, 0.0)); + let s2_ = select(v_f32_zero, v_f32_one, true); + let s3_ = select(v_f32_one, v_f32_zero, vec4(false, false, false, false)); + let m1_ = mix(v_f32_zero, v_f32_one, v_f32_half); + let m2_ = mix(v_f32_zero, v_f32_one, 0.1); + let b1_ = bitcast(v_i32_one.x); + let b2_ = bitcast>(v_i32_one); + let v_i32_zero = vec4(v_f32_zero); return (((((vec4((vec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } @@ -243,15 +244,15 @@ fn assignment() { a_1 = (_e27 << 2u); let _e30 = a_1; a_1 = (_e30 >> 1u); - let _e32 = a_1; - a_1 = (_e32 + 1); - let _e35 = a_1; - a_1 = (_e35 - 1); + let _e33 = a_1; + a_1 = (_e33 + 1); + let _e36 = a_1; + a_1 = (_e36 - 1); vec0_ = vec3(); - let _e42 = vec0_.y; - vec0_.y = (_e42 + 1); - let _e47 = vec0_.y; - vec0_.y = (_e47 - 1); + let _e43 = vec0_.y; + vec0_.y = (_e43 + 1); + let _e48 = vec0_.y; + vec0_.y = (_e48 - 1); return; } @@ -269,7 +270,7 @@ fn negation_avoids_prefix_decrement() { fn main() { let _e0 = builtins(); let _e1 = splat(); - let _e4 = bool_cast(vec4(1.0, 1.0, 1.0, 1.0).xyz); + let _e4 = bool_cast(v_f32_one.xyz); let _e5 = constructors(); logical(); arithmetic(); diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index 2c824e873..72da615cc 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -12,14 +12,14 @@ struct VertexOutput { var v_uv: vec2; var a_uv_1: vec2; -var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), 1.0, array(0.0), array(0.0)); +var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0.0, 1.0), 1.0, array(), array()); var a_pos_1: vec2; fn main_1() { - let _e12 = a_uv_1; - v_uv = _e12; - let _e13 = a_pos_1; - perVertexStruct.gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0); + let _e8 = a_uv_1; + v_uv = _e8; + let _e9 = a_pos_1; + perVertexStruct.gl_Position = vec4(_e9.x, _e9.y, 0.0, 1.0); return; } diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl index b4cf4dd28..3a92981d9 100644 --- a/tests/out/wgsl/quad.wgsl +++ b/tests/out/wgsl/quad.wgsl @@ -3,7 +3,7 @@ struct VertexOutput { @builtin(position) position: vec4, } -const c_scale: f32 = 1.2000000476837158; +const c_scale: f32 = 1.2; @group(0) @binding(0) var u_texture: texture_2d; diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl index 68661486c..b8d52e04c 100644 --- a/tests/out/wgsl/quad_glsl-vert.wgsl +++ b/tests/out/wgsl/quad_glsl-vert.wgsl @@ -3,7 +3,7 @@ struct VertexOutput { @builtin(position) member: vec4, } -const c_scale: f32 = 1.2000000476837158; +const c_scale: f32 = 1.2; var a_pos_1: vec2; var a_uv_1: vec2; diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index d93c716ba..8000e785f 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -20,7 +20,7 @@ struct Light { color: vec4, } -const c_ambient: vec3 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); +const c_ambient: vec3 = vec3(0.05, 0.05, 0.05); const c_max_lights: u32 = 10u; @group(0) @binding(0) @@ -68,7 +68,7 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { var i: u32; let normal_1 = normalize(in.world_normal); - color = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + color = c_ambient; i = 0u; loop { let _e7 = i; @@ -88,8 +88,8 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { color = (_e37 + ((_e23 * diffuse) * light.color.xyz)); } continuing { - let _e39 = i; - i = (_e39 + 1u); + let _e40 = i; + i = (_e40 + 1u); } } let _e42 = color; @@ -103,7 +103,7 @@ fn fs_main_without_storage(in_1: VertexOutput) -> @location(0) vec4 { var i_1: u32; let normal_2 = normalize(in_1.world_normal); - color_1 = vec3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806); + color_1 = c_ambient; i_1 = 0u; loop { let _e7 = i_1; @@ -123,8 +123,8 @@ fn fs_main_without_storage(in_1: VertexOutput) -> @location(0) vec4 { color_1 = (_e37 + ((_e23 * diffuse_1) * light_1.color.xyz)); } continuing { - let _e39 = i_1; - i_1 = (_e39 + 1u); + let _e40 = i_1; + i_1 = (_e40 + 1u); } } let _e42 = color_1; diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 9ae76837e..48318f280 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -952,18 +952,18 @@ fn invalid_arrays() { ┌─ wgsl:1:24 │ 1 │ alias Bad = array; - │ ^ must be positive + │ ^ must be greater than zero "###, ); check( "alias Bad = array;", - r###"error: array element count must resolve to an integer scalar (u32 or i32) + r###"error: array element count must be greater than zero ┌─ wgsl:1:24 │ 1 │ alias Bad = array; - │ ^^ must resolve to u32/i32 + │ ^^ must be greater than zero "###, ); From ee81f569df16d2fd0c14e4771ae4c7e1433bbb96 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 5 Apr 2023 17:38:46 +0200 Subject: [PATCH 2036/2212] add constructors test file --- tests/in/constructors.param.ron | 2 + tests/in/constructors.wgsl | 67 + tests/in/operators.wgsl | 50 - tests/out/glsl/constructors.main.Compute.glsl | 43 + tests/out/glsl/operators.main.Compute.glsl | 25 - tests/out/hlsl/constructors.hlsl | 60 + tests/out/hlsl/constructors.hlsl.config | 3 + tests/out/hlsl/constructors.ron | 12 + tests/out/hlsl/operators.hlsl | 44 - tests/out/msl/constructors.msl | 50 + tests/out/msl/operators.msl | 32 - tests/out/spv/constructors.spvasm | 100 ++ tests/out/spv/operators.spvasm | 1175 ++++++++--------- tests/out/wgsl/constructors.wgsl | 37 + tests/out/wgsl/operators.wgsl | 27 - tests/snapshots.rs | 4 + 16 files changed, 934 insertions(+), 797 deletions(-) create mode 100644 tests/in/constructors.param.ron create mode 100644 tests/in/constructors.wgsl create mode 100644 tests/out/glsl/constructors.main.Compute.glsl create mode 100644 tests/out/hlsl/constructors.hlsl create mode 100644 tests/out/hlsl/constructors.hlsl.config create mode 100644 tests/out/hlsl/constructors.ron create mode 100644 tests/out/msl/constructors.msl create mode 100644 tests/out/spv/constructors.spvasm create mode 100644 tests/out/wgsl/constructors.wgsl diff --git a/tests/in/constructors.param.ron b/tests/in/constructors.param.ron new file mode 100644 index 000000000..72873dd66 --- /dev/null +++ b/tests/in/constructors.param.ron @@ -0,0 +1,2 @@ +( +) diff --git a/tests/in/constructors.wgsl b/tests/in/constructors.wgsl new file mode 100644 index 000000000..d221dc80d --- /dev/null +++ b/tests/in/constructors.wgsl @@ -0,0 +1,67 @@ +struct Foo { + a: vec4, + b: i32, +} + +// const const1 = vec3(0.0); // TODO: this is now a splat and we need to const eval it +const const2 = vec3(0.0, 1.0, 2.0); +const const3 = mat2x2(0.0, 1.0, 2.0, 3.0); +const const4 = array, 1>(mat2x2(0.0, 1.0, 2.0, 3.0)); + +// zero value constructors +const cz0 = bool(); +const cz1 = i32(); +const cz2 = u32(); +const cz3 = f32(); +const cz4 = vec2(); +const cz5 = mat2x2(); +const cz6 = array(); +const cz7 = Foo(); + +// constructors that infer their type from their parameters +// TODO: these also contain splats +// const cp1 = vec2(0u); +// const cp2 = mat2x2(vec2(0.), vec2(0.)); +const cp3 = array(0, 1, 2, 3); + +@compute @workgroup_size(1) +fn main() { + var foo: Foo; + foo = Foo(vec4(1.0), 1); + + let m0 = mat2x2( + 1.0, 0.0, + 0.0, 1.0, + ); + let m1 = mat4x4( + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ); + + // zero value constructors + let zvc0 = bool(); + let zvc1 = i32(); + let zvc2 = u32(); + let zvc3 = f32(); + let zvc4 = vec2(); + let zvc5 = mat2x2(); + let zvc6 = array(); + let zvc7 = Foo(); + + // constructors that infer their type from their parameters + let cit0 = vec2(0u); + let cit1 = mat2x2(vec2(0.), vec2(0.)); + let cit2 = array(0, 1, 2, 3); + + // identity constructors + let ic0 = bool(bool()); + let ic1 = i32(i32()); + let ic2 = u32(u32()); + let ic3 = f32(f32()); + let ic4 = vec2(vec2()); + let ic5 = mat2x3(mat2x3()); + let ic6 = vec2(vec2()); + let ic7 = mat2x3(mat2x3()); +} diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index 365a03992..eaf16ab8f 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -1,4 +1,3 @@ -//TODO: support splatting constructors for globals? const v_f32_one = vec4(1.0, 1.0, 1.0, 1.0); const v_f32_zero = vec4(0.0, 0.0, 0.0, 0.0); const v_f32_half = vec4(0.5, 0.5, 0.5, 0.5); @@ -41,54 +40,6 @@ fn bool_cast(x: vec3) -> vec3 { return vec3(y); } -struct Foo { - a: vec4, - b: i32, -} - -fn constructors() -> f32 { - var foo: Foo; - foo = Foo(vec4(1.0), 1); - - let m0 = mat2x2( - 1.0, 0.0, - 0.0, 1.0, - ); - let m1 = mat4x4( - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ); - - // zero value constructors - let zvc0 = bool(); - let zvc1 = i32(); - let zvc2 = u32(); - let zvc3 = f32(); - let zvc4 = vec2(); - let zvc5 = mat2x2(); - let zvc6 = array(); - let zvc7 = Foo(); - - // constructors that infer their type from their parameters - let cit0 = vec2(0u); - let cit1 = mat2x2(vec2(0.), vec2(0.)); - let cit2 = array(0, 1, 2, 3); - - // identity constructors - let ic0 = bool(bool()); - let ic1 = i32(i32()); - let ic2 = u32(u32()); - let ic3 = f32(f32()); - let ic4 = vec2(vec2()); - let ic5 = mat2x3(mat2x3()); - let ic6 = vec2(vec2()); - let ic7 = mat2x3(mat2x3()); - - return foo.a.x; -} - fn logical() { // unary let neg0 = !true; @@ -306,7 +257,6 @@ fn main() { builtins(); splat(); bool_cast(v_f32_one.xyz); - constructors(); logical(); arithmetic(); diff --git a/tests/out/glsl/constructors.main.Compute.glsl b/tests/out/glsl/constructors.main.Compute.glsl new file mode 100644 index 000000000..112795eda --- /dev/null +++ b/tests/out/glsl/constructors.main.Compute.glsl @@ -0,0 +1,43 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +struct Foo { + vec4 a; + int b; +}; +const vec3 const2_ = vec3(0.0, 1.0, 2.0); +const mat2x2 const3_ = mat2x2(vec2(0.0, 1.0), vec2(2.0, 3.0)); +const mat2x2 const4_[1] = mat2x2[1](mat2x2(vec2(0.0, 1.0), vec2(2.0, 3.0))); +const bool cz0_ = false; +const int cz1_ = 0; +const uint cz2_ = 0u; +const float cz3_ = 0.0; +const uvec2 cz4_ = uvec2(0u); +const mat2x2 cz5_ = mat2x2(0.0); +const Foo cz6_[3] = Foo[3](Foo(vec4(0.0), 0), Foo(vec4(0.0), 0), Foo(vec4(0.0), 0)); +const Foo cz7_ = Foo(vec4(0.0), 0); +const int cp3_[4] = int[4](0, 1, 2, 3); + + +void main() { + Foo foo = Foo(vec4(0.0), 0); + foo = Foo(vec4(1.0), 1); + mat2x2 m0_ = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); + mat4x4 m1_ = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + uvec2 cit0_ = uvec2(0u); + mat2x2 cit1_ = mat2x2(vec2(0.0), vec2(0.0)); + int cit2_[4] = int[4](0, 1, 2, 3); + bool ic0_ = bool(false); + int ic1_ = int(0); + uint ic2_ = uint(0u); + float ic3_ = float(0.0); + uvec2 ic4_ = uvec2(uvec2(0u)); + mat2x3 ic5_ = mat2x3(mat2x3(0.0)); + uvec2 ic6_ = uvec2(0u); + mat2x3 ic7_ = mat2x3(0.0); +} + diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 51dc36969..5adfec2f8 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -5,10 +5,6 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; -struct Foo { - vec4 a; - int b; -}; const vec4 v_f32_one = vec4(1.0, 1.0, 1.0, 1.0); const vec4 v_f32_zero = vec4(0.0, 0.0, 0.0, 0.0); const vec4 v_f32_half = vec4(0.5, 0.5, 0.5, 0.5); @@ -51,26 +47,6 @@ vec3 bool_cast(vec3 x) { return vec3(y); } -float constructors() { - Foo foo = Foo(vec4(0.0), 0); - foo = Foo(vec4(1.0), 1); - mat2x2 m0_ = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); - mat4x4 m1_1 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - uvec2 cit0_ = uvec2(0u); - mat2x2 cit1_ = mat2x2(vec2(0.0), vec2(0.0)); - int cit2_[4] = int[4](0, 1, 2, 3); - bool ic0_ = bool(false); - int ic1_ = int(0); - uint ic2_ = uint(0u); - float ic3_ = float(0.0); - uvec2 ic4_ = uvec2(uvec2(0u)); - mat2x3 ic5_ = mat2x3(mat2x3(0.0)); - uvec2 ic6_ = uvec2(0u); - mat2x3 ic7_ = mat2x3(0.0); - float _e71 = foo.a.x; - return _e71; -} - void logical() { bool neg0_ = !(true); bvec2 neg1_ = not(bvec2(true)); @@ -274,7 +250,6 @@ void main() { vec4 _e0 = builtins(); vec4 _e1 = splat(); vec3 _e4 = bool_cast(v_f32_one.xyz); - float _e5 = constructors(); logical(); arithmetic(); bit(); diff --git a/tests/out/hlsl/constructors.hlsl b/tests/out/hlsl/constructors.hlsl new file mode 100644 index 000000000..3b9c06b0c --- /dev/null +++ b/tests/out/hlsl/constructors.hlsl @@ -0,0 +1,60 @@ +struct Foo { + float4 a; + int b; + int _end_pad_0; + int _end_pad_1; + int _end_pad_2; +}; + +typedef float2x2 ret_Constructarray1_float2x2_[1]; +ret_Constructarray1_float2x2_ Constructarray1_float2x2_(float2x2 arg0) { + float2x2 ret[1] = { arg0 }; + return ret; +} + +typedef int ret_Constructarray4_int_[4]; +ret_Constructarray4_int_ Constructarray4_int_(int arg0, int arg1, int arg2, int arg3) { + int ret[4] = { arg0, arg1, arg2, arg3 }; + return ret; +} + +static const float3 const2_ = float3(0.0, 1.0, 2.0); +static const float2x2 const3_ = float2x2(float2(0.0, 1.0), float2(2.0, 3.0)); +static const float2x2 const4_[1] = Constructarray1_float2x2_(float2x2(float2(0.0, 1.0), float2(2.0, 3.0))); +static const bool cz0_ = (bool)0; +static const int cz1_ = (int)0; +static const uint cz2_ = (uint)0; +static const float cz3_ = (float)0; +static const uint2 cz4_ = (uint2)0; +static const float2x2 cz5_ = (float2x2)0; +static const Foo cz6_[3] = (Foo[3])0; +static const Foo cz7_ = (Foo)0; +static const int cp3_[4] = Constructarray4_int_(0, 1, 2, 3); + +Foo ConstructFoo(float4 arg0, int arg1) { + Foo ret = (Foo)0; + ret.a = arg0; + ret.b = arg1; + return ret; +} + +[numthreads(1, 1, 1)] +void main() +{ + Foo foo = (Foo)0; + + foo = ConstructFoo((1.0).xxxx, 1); + float2x2 m0_ = float2x2(float2(1.0, 0.0), float2(0.0, 1.0)); + float4x4 m1_ = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); + uint2 cit0_ = (0u).xx; + float2x2 cit1_ = float2x2((0.0).xx, (0.0).xx); + int cit2_[4] = Constructarray4_int_(0, 1, 2, 3); + bool ic0_ = bool((bool)0); + int ic1_ = int((int)0); + uint ic2_ = uint((uint)0); + float ic3_ = float((float)0); + uint2 ic4_ = uint2((uint2)0); + float2x3 ic5_ = float2x3((float2x3)0); + uint2 ic6_ = asuint((uint2)0); + float2x3 ic7_ = asfloat((float2x3)0); +} diff --git a/tests/out/hlsl/constructors.hlsl.config b/tests/out/hlsl/constructors.hlsl.config new file mode 100644 index 000000000..246c485cf --- /dev/null +++ b/tests/out/hlsl/constructors.hlsl.config @@ -0,0 +1,3 @@ +vertex=() +fragment=() +compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/constructors.ron b/tests/out/hlsl/constructors.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/constructors.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index a54c90e6b..4c57f3134 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -1,11 +1,3 @@ -struct Foo { - float4 a; - int b; - int _end_pad_0; - int _end_pad_1; - int _end_pad_2; -}; - static const float4 v_f32_one = float4(1.0, 1.0, 1.0, 1.0); static const float4 v_f32_zero = float4(0.0, 0.0, 0.0, 0.0); static const float4 v_f32_half = float4(0.5, 0.5, 0.5, 0.5); @@ -52,41 +44,6 @@ float3 bool_cast(float3 x) return float3(y); } -Foo ConstructFoo(float4 arg0, int arg1) { - Foo ret = (Foo)0; - ret.a = arg0; - ret.b = arg1; - return ret; -} - -typedef int ret_Constructarray4_int_[4]; -ret_Constructarray4_int_ Constructarray4_int_(int arg0, int arg1, int arg2, int arg3) { - int ret[4] = { arg0, arg1, arg2, arg3 }; - return ret; -} - -float constructors() -{ - Foo foo = (Foo)0; - - foo = ConstructFoo((1.0).xxxx, 1); - float2x2 m0_ = float2x2(float2(1.0, 0.0), float2(0.0, 1.0)); - float4x4 m1_1 = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0)); - uint2 cit0_ = (0u).xx; - float2x2 cit1_ = float2x2((0.0).xx, (0.0).xx); - int cit2_[4] = Constructarray4_int_(0, 1, 2, 3); - bool ic0_ = bool((bool)0); - int ic1_ = int((int)0); - uint ic2_ = uint((uint)0); - float ic3_ = float((float)0); - uint2 ic4_ = uint2((uint2)0); - float2x3 ic5_ = float2x3((float2x3)0); - uint2 ic6_ = asuint((uint2)0); - float2x3 ic7_ = asfloat((float2x3)0); - float _expr71 = foo.a.x; - return _expr71; -} - void logical() { bool neg0_ = !(true); @@ -299,7 +256,6 @@ void main() const float4 _e0 = builtins(); const float4 _e1 = splat(); const float3 _e4 = bool_cast(v_f32_one.xyz); - const float _e5 = constructors(); logical(); arithmetic(); bit(); diff --git a/tests/out/msl/constructors.msl b/tests/out/msl/constructors.msl new file mode 100644 index 000000000..b3d3b9dd4 --- /dev/null +++ b/tests/out/msl/constructors.msl @@ -0,0 +1,50 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct Foo { + metal::float4 a; + int b; +}; +struct type_5 { + metal::float2x2 inner[1]; +}; +struct type_10 { + Foo inner[3]; +}; +struct type_11 { + int inner[4]; +}; +constant metal::float3 const2_ = metal::float3(0.0, 1.0, 2.0); +constant metal::float2x2 const3_ = metal::float2x2(metal::float2(0.0, 1.0), metal::float2(2.0, 3.0)); +constant type_5 const4_ = type_5 {metal::float2x2(metal::float2(0.0, 1.0), metal::float2(2.0, 3.0))}; +constant bool cz0_ = bool {}; +constant int cz1_ = int {}; +constant uint cz2_ = uint {}; +constant float cz3_ = float {}; +constant metal::uint2 cz4_ = metal::uint2 {}; +constant metal::float2x2 cz5_ = metal::float2x2 {}; +constant type_10 cz6_ = type_10 {}; +constant Foo cz7_ = Foo {}; +constant type_11 cp3_ = type_11 {0, 1, 2, 3}; + +kernel void main_( +) { + Foo foo = {}; + foo = Foo {metal::float4(1.0), 1}; + metal::float2x2 m0_ = metal::float2x2(metal::float2(1.0, 0.0), metal::float2(0.0, 1.0)); + metal::float4x4 m1_ = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); + metal::uint2 cit0_ = metal::uint2(0u); + metal::float2x2 cit1_ = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); + type_11 cit2_ = type_11 {0, 1, 2, 3}; + bool ic0_ = static_cast(bool {}); + int ic1_ = static_cast(int {}); + uint ic2_ = static_cast(uint {}); + float ic3_ = static_cast(float {}); + metal::uint2 ic4_ = static_cast(metal::uint2 {}); + metal::float2x3 ic5_ = metal::float2x3(metal::float2x3 {}); + metal::uint2 ic6_ = as_type(metal::uint2 {}); + metal::float2x3 ic7_ = metal::float2x3(metal::float2x3 {}); +} diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 78614ffbd..de3e990db 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -4,16 +4,6 @@ using metal::uint; -struct Foo { - metal::float4 a; - int b; -}; -struct type_13 { - Foo inner[3]; -}; -struct type_14 { - int inner[4]; -}; constant metal::float4 v_f32_one = metal::float4(1.0, 1.0, 1.0, 1.0); constant metal::float4 v_f32_zero = metal::float4(0.0, 0.0, 0.0, 0.0); constant metal::float4 v_f32_half = metal::float4(0.5, 0.5, 0.5, 0.5); @@ -60,27 +50,6 @@ metal::float3 bool_cast( return static_cast(y); } -float constructors( -) { - Foo foo = {}; - foo = Foo {metal::float4(1.0), 1}; - metal::float2x2 m0_ = metal::float2x2(metal::float2(1.0, 0.0), metal::float2(0.0, 1.0)); - metal::float4x4 m1_1 = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0)); - metal::uint2 cit0_ = metal::uint2(0u); - metal::float2x2 cit1_ = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); - type_14 cit2_ = type_14 {0, 1, 2, 3}; - bool ic0_ = static_cast(bool {}); - int ic1_ = static_cast(int {}); - uint ic2_ = static_cast(uint {}); - float ic3_ = static_cast(float {}); - metal::uint2 ic4_ = static_cast(metal::uint2 {}); - metal::float2x3 ic5_ = metal::float2x3(metal::float2x3 {}); - metal::uint2 ic6_ = as_type(metal::uint2 {}); - metal::float2x3 ic7_ = metal::float2x3(metal::float2x3 {}); - float _e71 = foo.a.x; - return _e71; -} - void logical( ) { bool neg0_ = !(true); @@ -291,7 +260,6 @@ kernel void main_( metal::float4 _e0 = builtins(); metal::float4 _e1 = splat(); metal::float3 _e4 = bool_cast(v_f32_one.xyz); - float _e5 = constructors(); logical(); arithmetic(); bit(); diff --git a/tests/out/spv/constructors.spvasm b/tests/out/spv/constructors.spvasm new file mode 100644 index 000000000..2a2b3ad0f --- /dev/null +++ b/tests/out/spv/constructors.spvasm @@ -0,0 +1,100 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 90 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %47 "main" +OpExecutionMode %47 LocalSize 1 1 1 +OpMemberDecorate %6 0 Offset 0 +OpMemberDecorate %6 1 Offset 16 +OpDecorate %10 ArrayStride 16 +OpDecorate %15 ArrayStride 32 +OpDecorate %17 ArrayStride 4 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%5 = OpTypeInt 32 1 +%6 = OpTypeStruct %3 %5 +%7 = OpTypeVector %4 3 +%9 = OpTypeVector %4 2 +%8 = OpTypeMatrix %9 2 +%12 = OpTypeInt 32 0 +%11 = OpConstant %12 1 +%10 = OpTypeArray %8 %11 +%13 = OpTypeBool +%14 = OpTypeVector %12 2 +%16 = OpConstant %12 3 +%15 = OpTypeArray %6 %16 +%18 = OpConstant %12 4 +%17 = OpTypeArray %5 %18 +%19 = OpTypeMatrix %3 4 +%20 = OpTypeMatrix %7 2 +%21 = OpConstant %4 0.0 +%22 = OpConstant %4 1.0 +%23 = OpConstant %4 2.0 +%24 = OpConstantComposite %7 %21 %22 %23 +%25 = OpConstant %4 3.0 +%26 = OpConstantComposite %9 %21 %22 +%27 = OpConstantComposite %9 %23 %25 +%28 = OpConstantComposite %8 %26 %27 +%29 = OpConstant %5 1 +%30 = OpConstantComposite %10 %28 +%31 = OpConstantNull %13 +%32 = OpConstantNull %5 +%33 = OpConstantNull %12 +%34 = OpConstantNull %4 +%35 = OpConstantNull %14 +%36 = OpConstantNull %8 +%37 = OpConstant %5 3 +%38 = OpConstantNull %15 +%39 = OpConstantNull %6 +%40 = OpConstant %5 0 +%41 = OpConstant %5 2 +%42 = OpConstantComposite %17 %40 %29 %41 %37 +%44 = OpTypePointer Function %6 +%45 = OpConstantNull %6 +%48 = OpTypeFunction %2 +%49 = OpConstantNull %13 +%50 = OpConstantNull %5 +%51 = OpConstantNull %12 +%52 = OpConstantNull %4 +%53 = OpConstantNull %14 +%54 = OpConstantNull %8 +%55 = OpConstantNull %15 +%56 = OpConstantNull %6 +%57 = OpConstant %12 0 +%58 = OpConstantNull %13 +%59 = OpConstantNull %5 +%60 = OpConstantNull %12 +%61 = OpConstantNull %4 +%62 = OpConstantNull %14 +%63 = OpConstantNull %20 +%64 = OpConstantNull %14 +%65 = OpConstantNull %20 +%47 = OpFunction %2 None %48 +%46 = OpLabel +%43 = OpVariable %44 Function %45 +OpBranch %66 +%66 = OpLabel +%67 = OpCompositeConstruct %3 %22 %22 %22 %22 +%68 = OpCompositeConstruct %6 %67 %29 +OpStore %43 %68 +%69 = OpCompositeConstruct %9 %22 %21 +%70 = OpCompositeConstruct %9 %21 %22 +%71 = OpCompositeConstruct %8 %69 %70 +%72 = OpCompositeConstruct %3 %22 %21 %21 %21 +%73 = OpCompositeConstruct %3 %21 %22 %21 %21 +%74 = OpCompositeConstruct %3 %21 %21 %22 %21 +%75 = OpCompositeConstruct %3 %21 %21 %21 %22 +%76 = OpCompositeConstruct %19 %72 %73 %74 %75 +%77 = OpCompositeConstruct %14 %57 %57 +%78 = OpCompositeConstruct %9 %21 %21 +%79 = OpCompositeConstruct %9 %21 %21 +%80 = OpCompositeConstruct %8 %78 %79 +%81 = OpCompositeConstruct %17 %40 %29 %41 %37 +%87 = OpCopyObject %20 %63 +%89 = OpCopyObject %20 %65 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 6e0a51467..22a67029c 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,16 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 591 +; Bound: 530 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %579 "main" -OpExecutionMode %579 LocalSize 1 1 1 -OpMemberDecorate %12 0 Offset 0 -OpMemberDecorate %12 1 Offset 16 -OpDecorate %17 ArrayStride 32 -OpDecorate %19 ArrayStride 4 +OpEntryPoint GLCompute %519 "main" +OpExecutionMode %519 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -21,635 +17,576 @@ OpDecorate %19 ArrayStride 4 %9 = OpTypeVector %4 2 %10 = OpTypeVector %4 3 %11 = OpTypeVector %8 3 -%12 = OpTypeStruct %3 %6 -%13 = OpTypeMatrix %9 2 -%14 = OpTypeMatrix %3 4 -%15 = OpTypeInt 32 0 -%16 = OpTypeVector %15 2 -%18 = OpConstant %15 3 -%17 = OpTypeArray %12 %18 -%20 = OpConstant %15 4 -%19 = OpTypeArray %6 %20 -%21 = OpTypeMatrix %10 2 -%22 = OpTypeMatrix %10 3 -%23 = OpTypeMatrix %10 4 -%24 = OpTypeMatrix %3 3 -%25 = OpTypeVector %6 3 -%26 = OpConstant %4 1.0 -%27 = OpConstantComposite %3 %26 %26 %26 %26 -%28 = OpConstant %4 0.0 -%29 = OpConstantComposite %3 %28 %28 %28 %28 -%30 = OpConstant %4 0.5 -%31 = OpConstantComposite %3 %30 %30 %30 %30 -%32 = OpConstant %6 1 -%33 = OpConstantComposite %5 %32 %32 %32 %32 -%34 = OpConstant %6 3 -%37 = OpTypeFunction %3 -%38 = OpConstantTrue %8 -%39 = OpConstant %6 0 -%40 = OpConstantFalse %8 -%41 = OpConstant %4 0.1 -%66 = OpConstant %4 2.0 -%67 = OpConstant %4 3.0 -%68 = OpConstant %4 4.0 -%69 = OpConstant %6 5 -%70 = OpConstant %6 2 -%86 = OpTypePointer Function %9 -%87 = OpConstantNull %9 -%90 = OpTypeFunction %9 -%106 = OpTypeFunction %10 %10 -%108 = OpConstantComposite %10 %28 %28 %28 -%110 = OpConstantComposite %10 %26 %26 %26 -%113 = OpTypePointer Function %12 -%114 = OpConstantNull %12 -%117 = OpTypeFunction %4 -%118 = OpConstantNull %8 -%119 = OpConstantNull %6 -%120 = OpConstantNull %15 -%121 = OpConstantNull %4 -%122 = OpConstantNull %16 -%123 = OpConstantNull %13 -%124 = OpConstantNull %17 +%12 = OpTypeMatrix %10 3 +%13 = OpTypeMatrix %10 4 +%14 = OpTypeMatrix %3 3 +%15 = OpTypeVector %6 3 +%16 = OpConstant %4 1.0 +%17 = OpConstantComposite %3 %16 %16 %16 %16 +%18 = OpConstant %4 0.0 +%19 = OpConstantComposite %3 %18 %18 %18 %18 +%20 = OpConstant %4 0.5 +%21 = OpConstantComposite %3 %20 %20 %20 %20 +%22 = OpConstant %6 1 +%23 = OpConstantComposite %5 %22 %22 %22 %22 +%26 = OpTypeFunction %3 +%27 = OpConstantTrue %8 +%28 = OpConstant %6 0 +%29 = OpConstantFalse %8 +%30 = OpConstant %4 0.1 +%55 = OpConstant %4 2.0 +%56 = OpConstant %4 3.0 +%57 = OpConstant %4 4.0 +%58 = OpConstant %6 5 +%59 = OpConstant %6 2 +%75 = OpTypePointer Function %9 +%76 = OpConstantNull %9 +%79 = OpTypeFunction %9 +%95 = OpTypeFunction %10 %10 +%97 = OpConstantComposite %10 %18 %18 %18 +%99 = OpConstantComposite %10 %16 %16 %16 +%103 = OpTypeFunction %2 +%106 = OpTypeVector %8 2 +%121 = OpConstant %4 -1.0 +%122 = OpTypeInt 32 0 +%123 = OpConstant %122 2 +%124 = OpConstant %122 1 %125 = OpConstantNull %12 -%126 = OpConstant %15 0 -%127 = OpConstantNull %8 -%128 = OpConstantNull %6 -%129 = OpConstantNull %15 -%130 = OpConstantNull %4 -%131 = OpConstantNull %16 -%132 = OpConstantNull %21 -%133 = OpConstantNull %16 -%134 = OpConstantNull %21 -%159 = OpTypePointer Function %3 -%160 = OpTypePointer Function %4 -%165 = OpTypeFunction %2 -%168 = OpTypeVector %8 2 -%183 = OpConstant %4 -1.0 -%184 = OpConstant %15 2 -%185 = OpConstant %15 1 -%186 = OpConstantNull %22 -%187 = OpConstantNull %22 -%188 = OpConstantNull %22 -%189 = OpConstantNull %22 -%190 = OpConstantNull %22 -%191 = OpConstantNull %22 -%192 = OpConstantNull %23 -%193 = OpConstantNull %23 -%194 = OpConstantNull %23 -%195 = OpConstantNull %24 -%197 = OpTypeVector %6 2 -%208 = OpTypeVector %15 3 -%505 = OpTypePointer Function %6 -%506 = OpConstantNull %6 -%508 = OpTypePointer Function %25 -%509 = OpConstantNull %25 -%512 = OpConstantNull %25 -%540 = OpTypePointer Function %6 -%551 = OpConstant %6 -1 -%552 = OpConstant %6 -2 -%553 = OpConstant %6 -3 -%554 = OpConstant %6 4 -%555 = OpConstant %6 -5 -%556 = OpConstant %6 6 -%557 = OpConstant %6 -7 -%558 = OpConstant %6 -8 -%36 = OpFunction %3 None %37 -%35 = OpLabel -OpBranch %42 -%42 = OpLabel -%43 = OpSelect %6 %38 %32 %39 -%45 = OpCompositeConstruct %7 %38 %38 %38 %38 -%44 = OpSelect %3 %45 %27 %29 -%46 = OpCompositeConstruct %7 %40 %40 %40 %40 -%47 = OpSelect %3 %46 %29 %27 -%48 = OpExtInst %3 %1 FMix %29 %27 %31 +%126 = OpConstantNull %12 +%127 = OpConstantNull %12 +%128 = OpConstantNull %12 +%129 = OpConstantNull %12 +%130 = OpConstantNull %12 +%131 = OpConstantNull %13 +%132 = OpConstantNull %13 +%133 = OpConstantNull %13 +%134 = OpConstantNull %14 +%136 = OpTypeVector %6 2 +%147 = OpTypeVector %122 3 +%210 = OpTypeVector %122 2 +%445 = OpTypePointer Function %6 +%446 = OpConstantNull %6 +%448 = OpTypePointer Function %15 +%449 = OpConstantNull %15 +%452 = OpConstantNull %15 +%480 = OpTypePointer Function %6 +%491 = OpConstant %6 -1 +%492 = OpConstant %6 -2 +%493 = OpConstant %6 -3 +%494 = OpConstant %6 4 +%495 = OpConstant %6 -5 +%496 = OpConstant %6 6 +%497 = OpConstant %6 -7 +%498 = OpConstant %6 -8 +%25 = OpFunction %3 None %26 +%24 = OpLabel +OpBranch %31 +%31 = OpLabel +%32 = OpSelect %6 %27 %22 %28 +%34 = OpCompositeConstruct %7 %27 %27 %27 %27 +%33 = OpSelect %3 %34 %17 %19 +%35 = OpCompositeConstruct %7 %29 %29 %29 %29 +%36 = OpSelect %3 %35 %19 %17 +%37 = OpExtInst %3 %1 FMix %19 %17 %21 +%39 = OpCompositeConstruct %3 %30 %30 %30 %30 +%38 = OpExtInst %3 %1 FMix %19 %17 %39 +%40 = OpCompositeExtract %6 %23 0 +%41 = OpBitcast %4 %40 +%42 = OpBitcast %3 %23 +%43 = OpConvertFToS %5 %19 +%44 = OpCompositeConstruct %5 %32 %32 %32 %32 +%45 = OpIAdd %5 %44 %43 +%46 = OpConvertSToF %3 %45 +%47 = OpFAdd %3 %46 %33 +%48 = OpFAdd %3 %47 %37 +%49 = OpFAdd %3 %48 %38 %50 = OpCompositeConstruct %3 %41 %41 %41 %41 -%49 = OpExtInst %3 %1 FMix %29 %27 %50 -%51 = OpCompositeExtract %6 %33 0 -%52 = OpBitcast %4 %51 -%53 = OpBitcast %3 %33 -%54 = OpConvertFToS %5 %29 -%55 = OpCompositeConstruct %5 %43 %43 %43 %43 -%56 = OpIAdd %5 %55 %54 -%57 = OpConvertSToF %3 %56 -%58 = OpFAdd %3 %57 %44 -%59 = OpFAdd %3 %58 %48 -%60 = OpFAdd %3 %59 %49 -%61 = OpCompositeConstruct %3 %52 %52 %52 %52 -%62 = OpFAdd %3 %60 %61 -%63 = OpFAdd %3 %62 %53 -OpReturnValue %63 +%51 = OpFAdd %3 %49 %50 +%52 = OpFAdd %3 %51 %42 +OpReturnValue %52 OpFunctionEnd -%65 = OpFunction %3 None %37 -%64 = OpLabel -OpBranch %71 -%71 = OpLabel -%72 = OpCompositeConstruct %9 %66 %66 -%73 = OpCompositeConstruct %9 %26 %26 -%74 = OpFAdd %9 %73 %72 -%75 = OpCompositeConstruct %9 %67 %67 -%76 = OpFSub %9 %74 %75 -%77 = OpCompositeConstruct %9 %68 %68 -%78 = OpFDiv %9 %76 %77 -%79 = OpCompositeConstruct %5 %69 %69 %69 %69 -%80 = OpCompositeConstruct %5 %70 %70 %70 %70 -%81 = OpSRem %5 %79 %80 -%82 = OpVectorShuffle %3 %78 %78 0 1 0 1 -%83 = OpConvertSToF %3 %81 -%84 = OpFAdd %3 %82 %83 -OpReturnValue %84 +%54 = OpFunction %3 None %26 +%53 = OpLabel +OpBranch %60 +%60 = OpLabel +%61 = OpCompositeConstruct %9 %55 %55 +%62 = OpCompositeConstruct %9 %16 %16 +%63 = OpFAdd %9 %62 %61 +%64 = OpCompositeConstruct %9 %56 %56 +%65 = OpFSub %9 %63 %64 +%66 = OpCompositeConstruct %9 %57 %57 +%67 = OpFDiv %9 %65 %66 +%68 = OpCompositeConstruct %5 %58 %58 %58 %58 +%69 = OpCompositeConstruct %5 %59 %59 %59 %59 +%70 = OpSRem %5 %68 %69 +%71 = OpVectorShuffle %3 %67 %67 0 1 0 1 +%72 = OpConvertSToF %3 %70 +%73 = OpFAdd %3 %71 %72 +OpReturnValue %73 OpFunctionEnd -%89 = OpFunction %9 None %90 -%88 = OpLabel -%85 = OpVariable %86 Function %87 -OpBranch %91 -%91 = OpLabel -%92 = OpCompositeConstruct %9 %66 %66 -OpStore %85 %92 -%93 = OpLoad %9 %85 -%94 = OpCompositeConstruct %9 %26 %26 -%95 = OpFAdd %9 %93 %94 -OpStore %85 %95 -%96 = OpLoad %9 %85 -%97 = OpCompositeConstruct %9 %67 %67 -%98 = OpFSub %9 %96 %97 -OpStore %85 %98 -%99 = OpLoad %9 %85 -%100 = OpCompositeConstruct %9 %68 %68 -%101 = OpFDiv %9 %99 %100 -OpStore %85 %101 -%102 = OpLoad %9 %85 -OpReturnValue %102 +%78 = OpFunction %9 None %79 +%77 = OpLabel +%74 = OpVariable %75 Function %76 +OpBranch %80 +%80 = OpLabel +%81 = OpCompositeConstruct %9 %55 %55 +OpStore %74 %81 +%82 = OpLoad %9 %74 +%83 = OpCompositeConstruct %9 %16 %16 +%84 = OpFAdd %9 %82 %83 +OpStore %74 %84 +%85 = OpLoad %9 %74 +%86 = OpCompositeConstruct %9 %56 %56 +%87 = OpFSub %9 %85 %86 +OpStore %74 %87 +%88 = OpLoad %9 %74 +%89 = OpCompositeConstruct %9 %57 %57 +%90 = OpFDiv %9 %88 %89 +OpStore %74 %90 +%91 = OpLoad %9 %74 +OpReturnValue %91 OpFunctionEnd -%105 = OpFunction %10 None %106 -%104 = OpFunctionParameter %10 -%103 = OpLabel -OpBranch %107 -%107 = OpLabel -%109 = OpFUnordNotEqual %11 %104 %108 -%111 = OpSelect %10 %109 %110 %108 -OpReturnValue %111 +%94 = OpFunction %10 None %95 +%93 = OpFunctionParameter %10 +%92 = OpLabel +OpBranch %96 +%96 = OpLabel +%98 = OpFUnordNotEqual %11 %93 %97 +%100 = OpSelect %10 %98 %99 %97 +OpReturnValue %100 OpFunctionEnd -%116 = OpFunction %4 None %117 -%115 = OpLabel -%112 = OpVariable %113 Function %114 +%102 = OpFunction %2 None %103 +%101 = OpLabel +OpBranch %104 +%104 = OpLabel +%105 = OpLogicalNot %8 %27 +%107 = OpCompositeConstruct %106 %27 %27 +%108 = OpLogicalNot %106 %107 +%109 = OpLogicalOr %8 %27 %29 +%110 = OpLogicalAnd %8 %27 %29 +%111 = OpLogicalOr %8 %27 %29 +%112 = OpCompositeConstruct %11 %27 %27 %27 +%113 = OpCompositeConstruct %11 %29 %29 %29 +%114 = OpLogicalOr %11 %112 %113 +%115 = OpLogicalAnd %8 %27 %29 +%116 = OpCompositeConstruct %7 %27 %27 %27 %27 +%117 = OpCompositeConstruct %7 %29 %29 %29 %29 +%118 = OpLogicalAnd %7 %116 %117 +OpReturn +OpFunctionEnd +%120 = OpFunction %2 None %103 +%119 = OpLabel OpBranch %135 %135 = OpLabel -%136 = OpCompositeConstruct %3 %26 %26 %26 %26 -%137 = OpCompositeConstruct %12 %136 %32 -OpStore %112 %137 -%138 = OpCompositeConstruct %9 %26 %28 -%139 = OpCompositeConstruct %9 %28 %26 -%140 = OpCompositeConstruct %13 %138 %139 -%141 = OpCompositeConstruct %3 %26 %28 %28 %28 -%142 = OpCompositeConstruct %3 %28 %26 %28 %28 -%143 = OpCompositeConstruct %3 %28 %28 %26 %28 -%144 = OpCompositeConstruct %3 %28 %28 %28 %26 -%145 = OpCompositeConstruct %14 %141 %142 %143 %144 -%146 = OpCompositeConstruct %16 %126 %126 -%147 = OpCompositeConstruct %9 %28 %28 -%148 = OpCompositeConstruct %9 %28 %28 -%149 = OpCompositeConstruct %13 %147 %148 -%150 = OpCompositeConstruct %19 %39 %32 %70 %34 -%156 = OpCopyObject %21 %132 -%158 = OpCopyObject %21 %134 -%161 = OpAccessChain %160 %112 %126 %126 -%162 = OpLoad %4 %161 -OpReturnValue %162 -OpFunctionEnd -%164 = OpFunction %2 None %165 -%163 = OpLabel -OpBranch %166 -%166 = OpLabel -%167 = OpLogicalNot %8 %38 -%169 = OpCompositeConstruct %168 %38 %38 -%170 = OpLogicalNot %168 %169 -%171 = OpLogicalOr %8 %38 %40 -%172 = OpLogicalAnd %8 %38 %40 -%173 = OpLogicalOr %8 %38 %40 -%174 = OpCompositeConstruct %11 %38 %38 %38 -%175 = OpCompositeConstruct %11 %40 %40 %40 -%176 = OpLogicalOr %11 %174 %175 -%177 = OpLogicalAnd %8 %38 %40 -%178 = OpCompositeConstruct %7 %38 %38 %38 %38 -%179 = OpCompositeConstruct %7 %40 %40 %40 %40 -%180 = OpLogicalAnd %7 %178 %179 +%137 = OpCompositeConstruct %136 %22 %22 +%138 = OpSNegate %136 %137 +%139 = OpCompositeConstruct %9 %16 %16 +%140 = OpFNegate %9 %139 +%141 = OpIAdd %6 %59 %22 +%142 = OpIAdd %122 %123 %124 +%143 = OpFAdd %4 %55 %16 +%144 = OpCompositeConstruct %136 %59 %59 +%145 = OpCompositeConstruct %136 %22 %22 +%146 = OpIAdd %136 %144 %145 +%148 = OpCompositeConstruct %147 %123 %123 %123 +%149 = OpCompositeConstruct %147 %124 %124 %124 +%150 = OpIAdd %147 %148 %149 +%151 = OpCompositeConstruct %3 %55 %55 %55 %55 +%152 = OpCompositeConstruct %3 %16 %16 %16 %16 +%153 = OpFAdd %3 %151 %152 +%154 = OpISub %6 %59 %22 +%155 = OpISub %122 %123 %124 +%156 = OpFSub %4 %55 %16 +%157 = OpCompositeConstruct %136 %59 %59 +%158 = OpCompositeConstruct %136 %22 %22 +%159 = OpISub %136 %157 %158 +%160 = OpCompositeConstruct %147 %123 %123 %123 +%161 = OpCompositeConstruct %147 %124 %124 %124 +%162 = OpISub %147 %160 %161 +%163 = OpCompositeConstruct %3 %55 %55 %55 %55 +%164 = OpCompositeConstruct %3 %16 %16 %16 %16 +%165 = OpFSub %3 %163 %164 +%166 = OpIMul %6 %59 %22 +%167 = OpIMul %122 %123 %124 +%168 = OpFMul %4 %55 %16 +%169 = OpCompositeConstruct %136 %59 %59 +%170 = OpCompositeConstruct %136 %22 %22 +%171 = OpIMul %136 %169 %170 +%172 = OpCompositeConstruct %147 %123 %123 %123 +%173 = OpCompositeConstruct %147 %124 %124 %124 +%174 = OpIMul %147 %172 %173 +%175 = OpCompositeConstruct %3 %55 %55 %55 %55 +%176 = OpCompositeConstruct %3 %16 %16 %16 %16 +%177 = OpFMul %3 %175 %176 +%178 = OpSDiv %6 %59 %22 +%179 = OpUDiv %122 %123 %124 +%180 = OpFDiv %4 %55 %16 +%181 = OpCompositeConstruct %136 %59 %59 +%182 = OpCompositeConstruct %136 %22 %22 +%183 = OpSDiv %136 %181 %182 +%184 = OpCompositeConstruct %147 %123 %123 %123 +%185 = OpCompositeConstruct %147 %124 %124 %124 +%186 = OpUDiv %147 %184 %185 +%187 = OpCompositeConstruct %3 %55 %55 %55 %55 +%188 = OpCompositeConstruct %3 %16 %16 %16 %16 +%189 = OpFDiv %3 %187 %188 +%190 = OpSRem %6 %59 %22 +%191 = OpUMod %122 %123 %124 +%192 = OpFRem %4 %55 %16 +%193 = OpCompositeConstruct %136 %59 %59 +%194 = OpCompositeConstruct %136 %22 %22 +%195 = OpSRem %136 %193 %194 +%196 = OpCompositeConstruct %147 %123 %123 %123 +%197 = OpCompositeConstruct %147 %124 %124 %124 +%198 = OpUMod %147 %196 %197 +%199 = OpCompositeConstruct %3 %55 %55 %55 %55 +%200 = OpCompositeConstruct %3 %16 %16 %16 %16 +%201 = OpFRem %3 %199 %200 +OpBranch %202 +%202 = OpLabel +%204 = OpCompositeConstruct %136 %59 %59 +%205 = OpCompositeConstruct %136 %22 %22 +%206 = OpIAdd %136 %204 %205 +%207 = OpCompositeConstruct %136 %22 %22 +%208 = OpCompositeConstruct %136 %59 %59 +%209 = OpIAdd %136 %208 %207 +%211 = OpCompositeConstruct %210 %123 %123 +%212 = OpCompositeConstruct %210 %124 %124 +%213 = OpIAdd %210 %211 %212 +%214 = OpCompositeConstruct %210 %124 %124 +%215 = OpCompositeConstruct %210 %123 %123 +%216 = OpIAdd %210 %215 %214 +%217 = OpCompositeConstruct %9 %55 %55 +%218 = OpCompositeConstruct %9 %16 %16 +%219 = OpFAdd %9 %217 %218 +%220 = OpCompositeConstruct %9 %16 %16 +%221 = OpCompositeConstruct %9 %55 %55 +%222 = OpFAdd %9 %221 %220 +%223 = OpCompositeConstruct %136 %59 %59 +%224 = OpCompositeConstruct %136 %22 %22 +%225 = OpISub %136 %223 %224 +%226 = OpCompositeConstruct %136 %22 %22 +%227 = OpCompositeConstruct %136 %59 %59 +%228 = OpISub %136 %227 %226 +%229 = OpCompositeConstruct %210 %123 %123 +%230 = OpCompositeConstruct %210 %124 %124 +%231 = OpISub %210 %229 %230 +%232 = OpCompositeConstruct %210 %124 %124 +%233 = OpCompositeConstruct %210 %123 %123 +%234 = OpISub %210 %233 %232 +%235 = OpCompositeConstruct %9 %55 %55 +%236 = OpCompositeConstruct %9 %16 %16 +%237 = OpFSub %9 %235 %236 +%238 = OpCompositeConstruct %9 %16 %16 +%239 = OpCompositeConstruct %9 %55 %55 +%240 = OpFSub %9 %239 %238 +%241 = OpCompositeConstruct %136 %59 %59 +%243 = OpCompositeConstruct %136 %22 %22 +%242 = OpIMul %136 %241 %243 +%244 = OpCompositeConstruct %136 %22 %22 +%246 = OpCompositeConstruct %136 %59 %59 +%245 = OpIMul %136 %244 %246 +%247 = OpCompositeConstruct %210 %123 %123 +%249 = OpCompositeConstruct %210 %124 %124 +%248 = OpIMul %210 %247 %249 +%250 = OpCompositeConstruct %210 %124 %124 +%252 = OpCompositeConstruct %210 %123 %123 +%251 = OpIMul %210 %250 %252 +%253 = OpCompositeConstruct %9 %55 %55 +%254 = OpVectorTimesScalar %9 %253 %16 +%255 = OpCompositeConstruct %9 %16 %16 +%256 = OpVectorTimesScalar %9 %255 %55 +%257 = OpCompositeConstruct %136 %59 %59 +%258 = OpCompositeConstruct %136 %22 %22 +%259 = OpSDiv %136 %257 %258 +%260 = OpCompositeConstruct %136 %22 %22 +%261 = OpCompositeConstruct %136 %59 %59 +%262 = OpSDiv %136 %261 %260 +%263 = OpCompositeConstruct %210 %123 %123 +%264 = OpCompositeConstruct %210 %124 %124 +%265 = OpUDiv %210 %263 %264 +%266 = OpCompositeConstruct %210 %124 %124 +%267 = OpCompositeConstruct %210 %123 %123 +%268 = OpUDiv %210 %267 %266 +%269 = OpCompositeConstruct %9 %55 %55 +%270 = OpCompositeConstruct %9 %16 %16 +%271 = OpFDiv %9 %269 %270 +%272 = OpCompositeConstruct %9 %16 %16 +%273 = OpCompositeConstruct %9 %55 %55 +%274 = OpFDiv %9 %273 %272 +%275 = OpCompositeConstruct %136 %59 %59 +%276 = OpCompositeConstruct %136 %22 %22 +%277 = OpSRem %136 %275 %276 +%278 = OpCompositeConstruct %136 %22 %22 +%279 = OpCompositeConstruct %136 %59 %59 +%280 = OpSRem %136 %279 %278 +%281 = OpCompositeConstruct %210 %123 %123 +%282 = OpCompositeConstruct %210 %124 %124 +%283 = OpUMod %210 %281 %282 +%284 = OpCompositeConstruct %210 %124 %124 +%285 = OpCompositeConstruct %210 %123 %123 +%286 = OpUMod %210 %285 %284 +%287 = OpCompositeConstruct %9 %55 %55 +%288 = OpCompositeConstruct %9 %16 %16 +%289 = OpFRem %9 %287 %288 +%290 = OpCompositeConstruct %9 %16 %16 +%291 = OpCompositeConstruct %9 %55 %55 +%292 = OpFRem %9 %291 %290 +OpBranch %203 +%203 = OpLabel +%294 = OpCompositeExtract %10 %125 0 +%295 = OpCompositeExtract %10 %126 0 +%296 = OpFAdd %10 %294 %295 +%297 = OpCompositeExtract %10 %125 1 +%298 = OpCompositeExtract %10 %126 1 +%299 = OpFAdd %10 %297 %298 +%300 = OpCompositeExtract %10 %125 2 +%301 = OpCompositeExtract %10 %126 2 +%302 = OpFAdd %10 %300 %301 +%293 = OpCompositeConstruct %12 %296 %299 %302 +%304 = OpCompositeExtract %10 %127 0 +%305 = OpCompositeExtract %10 %128 0 +%306 = OpFSub %10 %304 %305 +%307 = OpCompositeExtract %10 %127 1 +%308 = OpCompositeExtract %10 %128 1 +%309 = OpFSub %10 %307 %308 +%310 = OpCompositeExtract %10 %127 2 +%311 = OpCompositeExtract %10 %128 2 +%312 = OpFSub %10 %310 %311 +%303 = OpCompositeConstruct %12 %306 %309 %312 +%313 = OpMatrixTimesScalar %12 %129 %16 +%314 = OpMatrixTimesScalar %12 %130 %55 +%315 = OpCompositeConstruct %3 %16 %16 %16 %16 +%316 = OpMatrixTimesVector %10 %131 %315 +%317 = OpCompositeConstruct %10 %55 %55 %55 +%318 = OpVectorTimesMatrix %3 %317 %132 +%319 = OpMatrixTimesMatrix %12 %133 %134 OpReturn OpFunctionEnd -%182 = OpFunction %2 None %165 -%181 = OpLabel -OpBranch %196 -%196 = OpLabel -%198 = OpCompositeConstruct %197 %32 %32 -%199 = OpSNegate %197 %198 -%200 = OpCompositeConstruct %9 %26 %26 -%201 = OpFNegate %9 %200 -%202 = OpIAdd %6 %70 %32 -%203 = OpIAdd %15 %184 %185 -%204 = OpFAdd %4 %66 %26 -%205 = OpCompositeConstruct %197 %70 %70 -%206 = OpCompositeConstruct %197 %32 %32 -%207 = OpIAdd %197 %205 %206 -%209 = OpCompositeConstruct %208 %184 %184 %184 -%210 = OpCompositeConstruct %208 %185 %185 %185 -%211 = OpIAdd %208 %209 %210 -%212 = OpCompositeConstruct %3 %66 %66 %66 %66 -%213 = OpCompositeConstruct %3 %26 %26 %26 %26 -%214 = OpFAdd %3 %212 %213 -%215 = OpISub %6 %70 %32 -%216 = OpISub %15 %184 %185 -%217 = OpFSub %4 %66 %26 -%218 = OpCompositeConstruct %197 %70 %70 -%219 = OpCompositeConstruct %197 %32 %32 -%220 = OpISub %197 %218 %219 -%221 = OpCompositeConstruct %208 %184 %184 %184 -%222 = OpCompositeConstruct %208 %185 %185 %185 -%223 = OpISub %208 %221 %222 -%224 = OpCompositeConstruct %3 %66 %66 %66 %66 -%225 = OpCompositeConstruct %3 %26 %26 %26 %26 -%226 = OpFSub %3 %224 %225 -%227 = OpIMul %6 %70 %32 -%228 = OpIMul %15 %184 %185 -%229 = OpFMul %4 %66 %26 -%230 = OpCompositeConstruct %197 %70 %70 -%231 = OpCompositeConstruct %197 %32 %32 -%232 = OpIMul %197 %230 %231 -%233 = OpCompositeConstruct %208 %184 %184 %184 -%234 = OpCompositeConstruct %208 %185 %185 %185 -%235 = OpIMul %208 %233 %234 -%236 = OpCompositeConstruct %3 %66 %66 %66 %66 -%237 = OpCompositeConstruct %3 %26 %26 %26 %26 -%238 = OpFMul %3 %236 %237 -%239 = OpSDiv %6 %70 %32 -%240 = OpUDiv %15 %184 %185 -%241 = OpFDiv %4 %66 %26 -%242 = OpCompositeConstruct %197 %70 %70 -%243 = OpCompositeConstruct %197 %32 %32 -%244 = OpSDiv %197 %242 %243 -%245 = OpCompositeConstruct %208 %184 %184 %184 -%246 = OpCompositeConstruct %208 %185 %185 %185 -%247 = OpUDiv %208 %245 %246 -%248 = OpCompositeConstruct %3 %66 %66 %66 %66 -%249 = OpCompositeConstruct %3 %26 %26 %26 %26 -%250 = OpFDiv %3 %248 %249 -%251 = OpSRem %6 %70 %32 -%252 = OpUMod %15 %184 %185 -%253 = OpFRem %4 %66 %26 -%254 = OpCompositeConstruct %197 %70 %70 -%255 = OpCompositeConstruct %197 %32 %32 -%256 = OpSRem %197 %254 %255 -%257 = OpCompositeConstruct %208 %184 %184 %184 -%258 = OpCompositeConstruct %208 %185 %185 %185 -%259 = OpUMod %208 %257 %258 -%260 = OpCompositeConstruct %3 %66 %66 %66 %66 -%261 = OpCompositeConstruct %3 %26 %26 %26 %26 -%262 = OpFRem %3 %260 %261 -OpBranch %263 -%263 = OpLabel -%265 = OpCompositeConstruct %197 %70 %70 -%266 = OpCompositeConstruct %197 %32 %32 -%267 = OpIAdd %197 %265 %266 -%268 = OpCompositeConstruct %197 %32 %32 -%269 = OpCompositeConstruct %197 %70 %70 -%270 = OpIAdd %197 %269 %268 -%271 = OpCompositeConstruct %16 %184 %184 -%272 = OpCompositeConstruct %16 %185 %185 -%273 = OpIAdd %16 %271 %272 -%274 = OpCompositeConstruct %16 %185 %185 -%275 = OpCompositeConstruct %16 %184 %184 -%276 = OpIAdd %16 %275 %274 -%277 = OpCompositeConstruct %9 %66 %66 -%278 = OpCompositeConstruct %9 %26 %26 -%279 = OpFAdd %9 %277 %278 -%280 = OpCompositeConstruct %9 %26 %26 -%281 = OpCompositeConstruct %9 %66 %66 -%282 = OpFAdd %9 %281 %280 -%283 = OpCompositeConstruct %197 %70 %70 -%284 = OpCompositeConstruct %197 %32 %32 -%285 = OpISub %197 %283 %284 -%286 = OpCompositeConstruct %197 %32 %32 -%287 = OpCompositeConstruct %197 %70 %70 -%288 = OpISub %197 %287 %286 -%289 = OpCompositeConstruct %16 %184 %184 -%290 = OpCompositeConstruct %16 %185 %185 -%291 = OpISub %16 %289 %290 -%292 = OpCompositeConstruct %16 %185 %185 -%293 = OpCompositeConstruct %16 %184 %184 -%294 = OpISub %16 %293 %292 -%295 = OpCompositeConstruct %9 %66 %66 -%296 = OpCompositeConstruct %9 %26 %26 -%297 = OpFSub %9 %295 %296 -%298 = OpCompositeConstruct %9 %26 %26 -%299 = OpCompositeConstruct %9 %66 %66 -%300 = OpFSub %9 %299 %298 -%301 = OpCompositeConstruct %197 %70 %70 -%303 = OpCompositeConstruct %197 %32 %32 -%302 = OpIMul %197 %301 %303 -%304 = OpCompositeConstruct %197 %32 %32 -%306 = OpCompositeConstruct %197 %70 %70 -%305 = OpIMul %197 %304 %306 -%307 = OpCompositeConstruct %16 %184 %184 -%309 = OpCompositeConstruct %16 %185 %185 -%308 = OpIMul %16 %307 %309 -%310 = OpCompositeConstruct %16 %185 %185 -%312 = OpCompositeConstruct %16 %184 %184 -%311 = OpIMul %16 %310 %312 -%313 = OpCompositeConstruct %9 %66 %66 -%314 = OpVectorTimesScalar %9 %313 %26 -%315 = OpCompositeConstruct %9 %26 %26 -%316 = OpVectorTimesScalar %9 %315 %66 -%317 = OpCompositeConstruct %197 %70 %70 -%318 = OpCompositeConstruct %197 %32 %32 -%319 = OpSDiv %197 %317 %318 -%320 = OpCompositeConstruct %197 %32 %32 -%321 = OpCompositeConstruct %197 %70 %70 -%322 = OpSDiv %197 %321 %320 -%323 = OpCompositeConstruct %16 %184 %184 -%324 = OpCompositeConstruct %16 %185 %185 -%325 = OpUDiv %16 %323 %324 -%326 = OpCompositeConstruct %16 %185 %185 -%327 = OpCompositeConstruct %16 %184 %184 -%328 = OpUDiv %16 %327 %326 -%329 = OpCompositeConstruct %9 %66 %66 -%330 = OpCompositeConstruct %9 %26 %26 -%331 = OpFDiv %9 %329 %330 -%332 = OpCompositeConstruct %9 %26 %26 -%333 = OpCompositeConstruct %9 %66 %66 -%334 = OpFDiv %9 %333 %332 -%335 = OpCompositeConstruct %197 %70 %70 -%336 = OpCompositeConstruct %197 %32 %32 -%337 = OpSRem %197 %335 %336 -%338 = OpCompositeConstruct %197 %32 %32 -%339 = OpCompositeConstruct %197 %70 %70 -%340 = OpSRem %197 %339 %338 -%341 = OpCompositeConstruct %16 %184 %184 -%342 = OpCompositeConstruct %16 %185 %185 -%343 = OpUMod %16 %341 %342 -%344 = OpCompositeConstruct %16 %185 %185 -%345 = OpCompositeConstruct %16 %184 %184 -%346 = OpUMod %16 %345 %344 -%347 = OpCompositeConstruct %9 %66 %66 -%348 = OpCompositeConstruct %9 %26 %26 -%349 = OpFRem %9 %347 %348 -%350 = OpCompositeConstruct %9 %26 %26 -%351 = OpCompositeConstruct %9 %66 %66 -%352 = OpFRem %9 %351 %350 -OpBranch %264 -%264 = OpLabel -%354 = OpCompositeExtract %10 %186 0 -%355 = OpCompositeExtract %10 %187 0 -%356 = OpFAdd %10 %354 %355 -%357 = OpCompositeExtract %10 %186 1 -%358 = OpCompositeExtract %10 %187 1 -%359 = OpFAdd %10 %357 %358 -%360 = OpCompositeExtract %10 %186 2 -%361 = OpCompositeExtract %10 %187 2 -%362 = OpFAdd %10 %360 %361 -%353 = OpCompositeConstruct %22 %356 %359 %362 -%364 = OpCompositeExtract %10 %188 0 -%365 = OpCompositeExtract %10 %189 0 -%366 = OpFSub %10 %364 %365 -%367 = OpCompositeExtract %10 %188 1 -%368 = OpCompositeExtract %10 %189 1 -%369 = OpFSub %10 %367 %368 -%370 = OpCompositeExtract %10 %188 2 -%371 = OpCompositeExtract %10 %189 2 -%372 = OpFSub %10 %370 %371 -%363 = OpCompositeConstruct %22 %366 %369 %372 -%373 = OpMatrixTimesScalar %22 %190 %26 -%374 = OpMatrixTimesScalar %22 %191 %66 -%375 = OpCompositeConstruct %3 %26 %26 %26 %26 -%376 = OpMatrixTimesVector %10 %192 %375 -%377 = OpCompositeConstruct %10 %66 %66 %66 -%378 = OpVectorTimesMatrix %3 %377 %193 -%379 = OpMatrixTimesMatrix %22 %194 %195 +%321 = OpFunction %2 None %103 +%320 = OpLabel +OpBranch %322 +%322 = OpLabel +%323 = OpNot %6 %22 +%324 = OpNot %122 %124 +%325 = OpCompositeConstruct %136 %22 %22 +%326 = OpNot %136 %325 +%327 = OpCompositeConstruct %147 %124 %124 %124 +%328 = OpNot %147 %327 +%329 = OpBitwiseOr %6 %59 %22 +%330 = OpBitwiseOr %122 %123 %124 +%331 = OpCompositeConstruct %136 %59 %59 +%332 = OpCompositeConstruct %136 %22 %22 +%333 = OpBitwiseOr %136 %331 %332 +%334 = OpCompositeConstruct %147 %123 %123 %123 +%335 = OpCompositeConstruct %147 %124 %124 %124 +%336 = OpBitwiseOr %147 %334 %335 +%337 = OpBitwiseAnd %6 %59 %22 +%338 = OpBitwiseAnd %122 %123 %124 +%339 = OpCompositeConstruct %136 %59 %59 +%340 = OpCompositeConstruct %136 %22 %22 +%341 = OpBitwiseAnd %136 %339 %340 +%342 = OpCompositeConstruct %147 %123 %123 %123 +%343 = OpCompositeConstruct %147 %124 %124 %124 +%344 = OpBitwiseAnd %147 %342 %343 +%345 = OpBitwiseXor %6 %59 %22 +%346 = OpBitwiseXor %122 %123 %124 +%347 = OpCompositeConstruct %136 %59 %59 +%348 = OpCompositeConstruct %136 %22 %22 +%349 = OpBitwiseXor %136 %347 %348 +%350 = OpCompositeConstruct %147 %123 %123 %123 +%351 = OpCompositeConstruct %147 %124 %124 %124 +%352 = OpBitwiseXor %147 %350 %351 +%353 = OpShiftLeftLogical %6 %59 %124 +%354 = OpShiftLeftLogical %122 %123 %124 +%355 = OpCompositeConstruct %136 %59 %59 +%356 = OpCompositeConstruct %210 %124 %124 +%357 = OpShiftLeftLogical %136 %355 %356 +%358 = OpCompositeConstruct %147 %123 %123 %123 +%359 = OpCompositeConstruct %147 %124 %124 %124 +%360 = OpShiftLeftLogical %147 %358 %359 +%361 = OpShiftRightArithmetic %6 %59 %124 +%362 = OpShiftRightLogical %122 %123 %124 +%363 = OpCompositeConstruct %136 %59 %59 +%364 = OpCompositeConstruct %210 %124 %124 +%365 = OpShiftRightArithmetic %136 %363 %364 +%366 = OpCompositeConstruct %147 %123 %123 %123 +%367 = OpCompositeConstruct %147 %124 %124 %124 +%368 = OpShiftRightLogical %147 %366 %367 OpReturn OpFunctionEnd -%381 = OpFunction %2 None %165 -%380 = OpLabel -OpBranch %382 -%382 = OpLabel -%383 = OpNot %6 %32 -%384 = OpNot %15 %185 -%385 = OpCompositeConstruct %197 %32 %32 -%386 = OpNot %197 %385 -%387 = OpCompositeConstruct %208 %185 %185 %185 -%388 = OpNot %208 %387 -%389 = OpBitwiseOr %6 %70 %32 -%390 = OpBitwiseOr %15 %184 %185 -%391 = OpCompositeConstruct %197 %70 %70 -%392 = OpCompositeConstruct %197 %32 %32 -%393 = OpBitwiseOr %197 %391 %392 -%394 = OpCompositeConstruct %208 %184 %184 %184 -%395 = OpCompositeConstruct %208 %185 %185 %185 -%396 = OpBitwiseOr %208 %394 %395 -%397 = OpBitwiseAnd %6 %70 %32 -%398 = OpBitwiseAnd %15 %184 %185 -%399 = OpCompositeConstruct %197 %70 %70 -%400 = OpCompositeConstruct %197 %32 %32 -%401 = OpBitwiseAnd %197 %399 %400 -%402 = OpCompositeConstruct %208 %184 %184 %184 -%403 = OpCompositeConstruct %208 %185 %185 %185 -%404 = OpBitwiseAnd %208 %402 %403 -%405 = OpBitwiseXor %6 %70 %32 -%406 = OpBitwiseXor %15 %184 %185 -%407 = OpCompositeConstruct %197 %70 %70 -%408 = OpCompositeConstruct %197 %32 %32 -%409 = OpBitwiseXor %197 %407 %408 -%410 = OpCompositeConstruct %208 %184 %184 %184 -%411 = OpCompositeConstruct %208 %185 %185 %185 -%412 = OpBitwiseXor %208 %410 %411 -%413 = OpShiftLeftLogical %6 %70 %185 -%414 = OpShiftLeftLogical %15 %184 %185 -%415 = OpCompositeConstruct %197 %70 %70 -%416 = OpCompositeConstruct %16 %185 %185 -%417 = OpShiftLeftLogical %197 %415 %416 -%418 = OpCompositeConstruct %208 %184 %184 %184 -%419 = OpCompositeConstruct %208 %185 %185 %185 -%420 = OpShiftLeftLogical %208 %418 %419 -%421 = OpShiftRightArithmetic %6 %70 %185 -%422 = OpShiftRightLogical %15 %184 %185 -%423 = OpCompositeConstruct %197 %70 %70 -%424 = OpCompositeConstruct %16 %185 %185 -%425 = OpShiftRightArithmetic %197 %423 %424 -%426 = OpCompositeConstruct %208 %184 %184 %184 -%427 = OpCompositeConstruct %208 %185 %185 %185 -%428 = OpShiftRightLogical %208 %426 %427 +%370 = OpFunction %2 None %103 +%369 = OpLabel +OpBranch %371 +%371 = OpLabel +%372 = OpIEqual %8 %59 %22 +%373 = OpIEqual %8 %123 %124 +%374 = OpFOrdEqual %8 %55 %16 +%375 = OpCompositeConstruct %136 %59 %59 +%376 = OpCompositeConstruct %136 %22 %22 +%377 = OpIEqual %106 %375 %376 +%378 = OpCompositeConstruct %147 %123 %123 %123 +%379 = OpCompositeConstruct %147 %124 %124 %124 +%380 = OpIEqual %11 %378 %379 +%381 = OpCompositeConstruct %3 %55 %55 %55 %55 +%382 = OpCompositeConstruct %3 %16 %16 %16 %16 +%383 = OpFOrdEqual %7 %381 %382 +%384 = OpINotEqual %8 %59 %22 +%385 = OpINotEqual %8 %123 %124 +%386 = OpFOrdNotEqual %8 %55 %16 +%387 = OpCompositeConstruct %136 %59 %59 +%388 = OpCompositeConstruct %136 %22 %22 +%389 = OpINotEqual %106 %387 %388 +%390 = OpCompositeConstruct %147 %123 %123 %123 +%391 = OpCompositeConstruct %147 %124 %124 %124 +%392 = OpINotEqual %11 %390 %391 +%393 = OpCompositeConstruct %3 %55 %55 %55 %55 +%394 = OpCompositeConstruct %3 %16 %16 %16 %16 +%395 = OpFOrdNotEqual %7 %393 %394 +%396 = OpSLessThan %8 %59 %22 +%397 = OpULessThan %8 %123 %124 +%398 = OpFOrdLessThan %8 %55 %16 +%399 = OpCompositeConstruct %136 %59 %59 +%400 = OpCompositeConstruct %136 %22 %22 +%401 = OpSLessThan %106 %399 %400 +%402 = OpCompositeConstruct %147 %123 %123 %123 +%403 = OpCompositeConstruct %147 %124 %124 %124 +%404 = OpULessThan %11 %402 %403 +%405 = OpCompositeConstruct %3 %55 %55 %55 %55 +%406 = OpCompositeConstruct %3 %16 %16 %16 %16 +%407 = OpFOrdLessThan %7 %405 %406 +%408 = OpSLessThanEqual %8 %59 %22 +%409 = OpULessThanEqual %8 %123 %124 +%410 = OpFOrdLessThanEqual %8 %55 %16 +%411 = OpCompositeConstruct %136 %59 %59 +%412 = OpCompositeConstruct %136 %22 %22 +%413 = OpSLessThanEqual %106 %411 %412 +%414 = OpCompositeConstruct %147 %123 %123 %123 +%415 = OpCompositeConstruct %147 %124 %124 %124 +%416 = OpULessThanEqual %11 %414 %415 +%417 = OpCompositeConstruct %3 %55 %55 %55 %55 +%418 = OpCompositeConstruct %3 %16 %16 %16 %16 +%419 = OpFOrdLessThanEqual %7 %417 %418 +%420 = OpSGreaterThan %8 %59 %22 +%421 = OpUGreaterThan %8 %123 %124 +%422 = OpFOrdGreaterThan %8 %55 %16 +%423 = OpCompositeConstruct %136 %59 %59 +%424 = OpCompositeConstruct %136 %22 %22 +%425 = OpSGreaterThan %106 %423 %424 +%426 = OpCompositeConstruct %147 %123 %123 %123 +%427 = OpCompositeConstruct %147 %124 %124 %124 +%428 = OpUGreaterThan %11 %426 %427 +%429 = OpCompositeConstruct %3 %55 %55 %55 %55 +%430 = OpCompositeConstruct %3 %16 %16 %16 %16 +%431 = OpFOrdGreaterThan %7 %429 %430 +%432 = OpSGreaterThanEqual %8 %59 %22 +%433 = OpUGreaterThanEqual %8 %123 %124 +%434 = OpFOrdGreaterThanEqual %8 %55 %16 +%435 = OpCompositeConstruct %136 %59 %59 +%436 = OpCompositeConstruct %136 %22 %22 +%437 = OpSGreaterThanEqual %106 %435 %436 +%438 = OpCompositeConstruct %147 %123 %123 %123 +%439 = OpCompositeConstruct %147 %124 %124 %124 +%440 = OpUGreaterThanEqual %11 %438 %439 +%441 = OpCompositeConstruct %3 %55 %55 %55 %55 +%442 = OpCompositeConstruct %3 %16 %16 %16 %16 +%443 = OpFOrdGreaterThanEqual %7 %441 %442 OpReturn OpFunctionEnd -%430 = OpFunction %2 None %165 -%429 = OpLabel -OpBranch %431 -%431 = OpLabel -%432 = OpIEqual %8 %70 %32 -%433 = OpIEqual %8 %184 %185 -%434 = OpFOrdEqual %8 %66 %26 -%435 = OpCompositeConstruct %197 %70 %70 -%436 = OpCompositeConstruct %197 %32 %32 -%437 = OpIEqual %168 %435 %436 -%438 = OpCompositeConstruct %208 %184 %184 %184 -%439 = OpCompositeConstruct %208 %185 %185 %185 -%440 = OpIEqual %11 %438 %439 -%441 = OpCompositeConstruct %3 %66 %66 %66 %66 -%442 = OpCompositeConstruct %3 %26 %26 %26 %26 -%443 = OpFOrdEqual %7 %441 %442 -%444 = OpINotEqual %8 %70 %32 -%445 = OpINotEqual %8 %184 %185 -%446 = OpFOrdNotEqual %8 %66 %26 -%447 = OpCompositeConstruct %197 %70 %70 -%448 = OpCompositeConstruct %197 %32 %32 -%449 = OpINotEqual %168 %447 %448 -%450 = OpCompositeConstruct %208 %184 %184 %184 -%451 = OpCompositeConstruct %208 %185 %185 %185 -%452 = OpINotEqual %11 %450 %451 -%453 = OpCompositeConstruct %3 %66 %66 %66 %66 -%454 = OpCompositeConstruct %3 %26 %26 %26 %26 -%455 = OpFOrdNotEqual %7 %453 %454 -%456 = OpSLessThan %8 %70 %32 -%457 = OpULessThan %8 %184 %185 -%458 = OpFOrdLessThan %8 %66 %26 -%459 = OpCompositeConstruct %197 %70 %70 -%460 = OpCompositeConstruct %197 %32 %32 -%461 = OpSLessThan %168 %459 %460 -%462 = OpCompositeConstruct %208 %184 %184 %184 -%463 = OpCompositeConstruct %208 %185 %185 %185 -%464 = OpULessThan %11 %462 %463 -%465 = OpCompositeConstruct %3 %66 %66 %66 %66 -%466 = OpCompositeConstruct %3 %26 %26 %26 %26 -%467 = OpFOrdLessThan %7 %465 %466 -%468 = OpSLessThanEqual %8 %70 %32 -%469 = OpULessThanEqual %8 %184 %185 -%470 = OpFOrdLessThanEqual %8 %66 %26 -%471 = OpCompositeConstruct %197 %70 %70 -%472 = OpCompositeConstruct %197 %32 %32 -%473 = OpSLessThanEqual %168 %471 %472 -%474 = OpCompositeConstruct %208 %184 %184 %184 -%475 = OpCompositeConstruct %208 %185 %185 %185 -%476 = OpULessThanEqual %11 %474 %475 -%477 = OpCompositeConstruct %3 %66 %66 %66 %66 -%478 = OpCompositeConstruct %3 %26 %26 %26 %26 -%479 = OpFOrdLessThanEqual %7 %477 %478 -%480 = OpSGreaterThan %8 %70 %32 -%481 = OpUGreaterThan %8 %184 %185 -%482 = OpFOrdGreaterThan %8 %66 %26 -%483 = OpCompositeConstruct %197 %70 %70 -%484 = OpCompositeConstruct %197 %32 %32 -%485 = OpSGreaterThan %168 %483 %484 -%486 = OpCompositeConstruct %208 %184 %184 %184 -%487 = OpCompositeConstruct %208 %185 %185 %185 -%488 = OpUGreaterThan %11 %486 %487 -%489 = OpCompositeConstruct %3 %66 %66 %66 %66 -%490 = OpCompositeConstruct %3 %26 %26 %26 %26 -%491 = OpFOrdGreaterThan %7 %489 %490 -%492 = OpSGreaterThanEqual %8 %70 %32 -%493 = OpUGreaterThanEqual %8 %184 %185 -%494 = OpFOrdGreaterThanEqual %8 %66 %26 -%495 = OpCompositeConstruct %197 %70 %70 -%496 = OpCompositeConstruct %197 %32 %32 -%497 = OpSGreaterThanEqual %168 %495 %496 -%498 = OpCompositeConstruct %208 %184 %184 %184 -%499 = OpCompositeConstruct %208 %185 %185 %185 -%500 = OpUGreaterThanEqual %11 %498 %499 -%501 = OpCompositeConstruct %3 %66 %66 %66 %66 -%502 = OpCompositeConstruct %3 %26 %26 %26 %26 -%503 = OpFOrdGreaterThanEqual %7 %501 %502 +%451 = OpFunction %2 None %103 +%450 = OpLabel +%444 = OpVariable %445 Function %446 +%447 = OpVariable %448 Function %449 +OpBranch %453 +%453 = OpLabel +OpStore %444 %22 +%454 = OpLoad %6 %444 +%455 = OpIAdd %6 %454 %22 +OpStore %444 %455 +%456 = OpLoad %6 %444 +%457 = OpISub %6 %456 %22 +OpStore %444 %457 +%458 = OpLoad %6 %444 +%459 = OpLoad %6 %444 +%460 = OpIMul %6 %459 %458 +OpStore %444 %460 +%461 = OpLoad %6 %444 +%462 = OpLoad %6 %444 +%463 = OpSDiv %6 %462 %461 +OpStore %444 %463 +%464 = OpLoad %6 %444 +%465 = OpSRem %6 %464 %22 +OpStore %444 %465 +%466 = OpLoad %6 %444 +%467 = OpBitwiseAnd %6 %466 %28 +OpStore %444 %467 +%468 = OpLoad %6 %444 +%469 = OpBitwiseOr %6 %468 %28 +OpStore %444 %469 +%470 = OpLoad %6 %444 +%471 = OpBitwiseXor %6 %470 %28 +OpStore %444 %471 +%472 = OpLoad %6 %444 +%473 = OpShiftLeftLogical %6 %472 %123 +OpStore %444 %473 +%474 = OpLoad %6 %444 +%475 = OpShiftRightArithmetic %6 %474 %124 +OpStore %444 %475 +%476 = OpLoad %6 %444 +%477 = OpIAdd %6 %476 %22 +OpStore %444 %477 +%478 = OpLoad %6 %444 +%479 = OpISub %6 %478 %22 +OpStore %444 %479 +OpStore %447 %452 +%481 = OpAccessChain %480 %447 %124 +%482 = OpLoad %6 %481 +%483 = OpIAdd %6 %482 %22 +%484 = OpAccessChain %480 %447 %124 +OpStore %484 %483 +%485 = OpAccessChain %480 %447 %124 +%486 = OpLoad %6 %485 +%487 = OpISub %6 %486 %22 +%488 = OpAccessChain %480 %447 %124 +OpStore %488 %487 OpReturn OpFunctionEnd -%511 = OpFunction %2 None %165 -%510 = OpLabel -%504 = OpVariable %505 Function %506 -%507 = OpVariable %508 Function %509 -OpBranch %513 -%513 = OpLabel -OpStore %504 %32 -%514 = OpLoad %6 %504 -%515 = OpIAdd %6 %514 %32 -OpStore %504 %515 -%516 = OpLoad %6 %504 -%517 = OpISub %6 %516 %32 -OpStore %504 %517 -%518 = OpLoad %6 %504 -%519 = OpLoad %6 %504 -%520 = OpIMul %6 %519 %518 -OpStore %504 %520 -%521 = OpLoad %6 %504 -%522 = OpLoad %6 %504 -%523 = OpSDiv %6 %522 %521 -OpStore %504 %523 -%524 = OpLoad %6 %504 -%525 = OpSRem %6 %524 %32 -OpStore %504 %525 -%526 = OpLoad %6 %504 -%527 = OpBitwiseAnd %6 %526 %39 -OpStore %504 %527 -%528 = OpLoad %6 %504 -%529 = OpBitwiseOr %6 %528 %39 -OpStore %504 %529 -%530 = OpLoad %6 %504 -%531 = OpBitwiseXor %6 %530 %39 -OpStore %504 %531 -%532 = OpLoad %6 %504 -%533 = OpShiftLeftLogical %6 %532 %184 -OpStore %504 %533 -%534 = OpLoad %6 %504 -%535 = OpShiftRightArithmetic %6 %534 %185 -OpStore %504 %535 -%536 = OpLoad %6 %504 -%537 = OpIAdd %6 %536 %32 -OpStore %504 %537 -%538 = OpLoad %6 %504 -%539 = OpISub %6 %538 %32 -OpStore %504 %539 -OpStore %507 %512 -%541 = OpAccessChain %540 %507 %185 -%542 = OpLoad %6 %541 -%543 = OpIAdd %6 %542 %32 -%544 = OpAccessChain %540 %507 %185 -OpStore %544 %543 -%545 = OpAccessChain %540 %507 %185 -%546 = OpLoad %6 %545 -%547 = OpISub %6 %546 %32 -%548 = OpAccessChain %540 %507 %185 -OpStore %548 %547 +%490 = OpFunction %2 None %103 +%489 = OpLabel +OpBranch %499 +%499 = OpLabel +%500 = OpSNegate %6 %492 +%501 = OpSNegate %6 %493 +%502 = OpSNegate %6 %494 +%503 = OpSNegate %6 %502 +%504 = OpSNegate %6 %495 +%505 = OpSNegate %6 %504 +%506 = OpSNegate %6 %496 +%507 = OpSNegate %6 %506 +%508 = OpSNegate %6 %507 +%509 = OpSNegate %6 %508 +%510 = OpSNegate %6 %497 +%511 = OpSNegate %6 %510 +%512 = OpSNegate %6 %511 +%513 = OpSNegate %6 %512 +%514 = OpSNegate %6 %498 +%515 = OpSNegate %6 %514 +%516 = OpSNegate %6 %515 +%517 = OpSNegate %6 %516 OpReturn OpFunctionEnd -%550 = OpFunction %2 None %165 -%549 = OpLabel -OpBranch %559 -%559 = OpLabel -%560 = OpSNegate %6 %552 -%561 = OpSNegate %6 %553 -%562 = OpSNegate %6 %554 -%563 = OpSNegate %6 %562 -%564 = OpSNegate %6 %555 -%565 = OpSNegate %6 %564 -%566 = OpSNegate %6 %556 -%567 = OpSNegate %6 %566 -%568 = OpSNegate %6 %567 -%569 = OpSNegate %6 %568 -%570 = OpSNegate %6 %557 -%571 = OpSNegate %6 %570 -%572 = OpSNegate %6 %571 -%573 = OpSNegate %6 %572 -%574 = OpSNegate %6 %558 -%575 = OpSNegate %6 %574 -%576 = OpSNegate %6 %575 -%577 = OpSNegate %6 %576 -OpReturn -OpFunctionEnd -%579 = OpFunction %2 None %165 -%578 = OpLabel -OpBranch %580 -%580 = OpLabel -%581 = OpFunctionCall %3 %36 -%582 = OpFunctionCall %3 %65 -%583 = OpVectorShuffle %10 %27 %27 0 1 2 -%584 = OpFunctionCall %10 %105 %583 -%585 = OpFunctionCall %4 %116 -%586 = OpFunctionCall %2 %164 -%587 = OpFunctionCall %2 %182 -%588 = OpFunctionCall %2 %381 -%589 = OpFunctionCall %2 %430 -%590 = OpFunctionCall %2 %511 +%519 = OpFunction %2 None %103 +%518 = OpLabel +OpBranch %520 +%520 = OpLabel +%521 = OpFunctionCall %3 %25 +%522 = OpFunctionCall %3 %54 +%523 = OpVectorShuffle %10 %17 %17 0 1 2 +%524 = OpFunctionCall %10 %94 %523 +%525 = OpFunctionCall %2 %102 +%526 = OpFunctionCall %2 %120 +%527 = OpFunctionCall %2 %321 +%528 = OpFunctionCall %2 %370 +%529 = OpFunctionCall %2 %451 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/constructors.wgsl b/tests/out/wgsl/constructors.wgsl new file mode 100644 index 000000000..7818e4c39 --- /dev/null +++ b/tests/out/wgsl/constructors.wgsl @@ -0,0 +1,37 @@ +struct Foo { + a: vec4, + b: i32, +} + +const const2_: vec3 = vec3(0.0, 1.0, 2.0); +const const3_: mat2x2 = mat2x2(vec2(0.0, 1.0), vec2(2.0, 3.0)); +const const4_: array, 1> = array, 1>(mat2x2(vec2(0.0, 1.0), vec2(2.0, 3.0))); +const cz0_: bool = bool(); +const cz1_: i32 = i32(); +const cz2_: u32 = u32(); +const cz3_: f32 = f32(); +const cz4_: vec2 = vec2(); +const cz5_: mat2x2 = mat2x2(); +const cz6_: array = array(); +const cz7_: Foo = Foo(); +const cp3_: array = array(0, 1, 2, 3); + +@compute @workgroup_size(1, 1, 1) +fn main() { + var foo: Foo; + + foo = Foo(vec4(1.0), 1); + let m0_ = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); + let m1_ = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); + let cit0_ = vec2(0u); + let cit1_ = mat2x2(vec2(0.0), vec2(0.0)); + let cit2_ = array(0, 1, 2, 3); + let ic0_ = bool(bool()); + let ic1_ = i32(i32()); + let ic2_ = u32(u32()); + let ic3_ = f32(f32()); + let ic4_ = vec2(vec2()); + let ic5_ = mat2x3(mat2x3()); + let ic6_ = bitcast>(vec2()); + let ic7_ = mat2x3(mat2x3()); +} diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 41a9c821a..9550bf840 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -1,8 +1,3 @@ -struct Foo { - a: vec4, - b: i32, -} - const v_f32_one: vec4 = vec4(1.0, 1.0, 1.0, 1.0); const v_f32_zero: vec4 = vec4(0.0, 0.0, 0.0, 0.0); const v_f32_half: vec4 = vec4(0.5, 0.5, 0.5, 0.5); @@ -45,27 +40,6 @@ fn bool_cast(x: vec3) -> vec3 { return vec3(y); } -fn constructors() -> f32 { - var foo: Foo; - - foo = Foo(vec4(1.0), 1); - let m0_ = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); - let m1_1 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let cit0_ = vec2(0u); - let cit1_ = mat2x2(vec2(0.0), vec2(0.0)); - let cit2_ = array(0, 1, 2, 3); - let ic0_ = bool(bool()); - let ic1_ = i32(i32()); - let ic2_ = u32(u32()); - let ic3_ = f32(f32()); - let ic4_ = vec2(vec2()); - let ic5_ = mat2x3(mat2x3()); - let ic6_ = bitcast>(vec2()); - let ic7_ = mat2x3(mat2x3()); - let _e71 = foo.a.x; - return _e71; -} - fn logical() { let neg0_ = !(true); let neg1_ = !(vec2(true)); @@ -271,7 +245,6 @@ fn main() { let _e0 = builtins(); let _e1 = splat(); let _e4 = bool_cast(v_f32_one.xyz); - let _e5 = constructors(); logical(); arithmetic(); bit(); diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 658e5fe7f..e1e114413 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -607,6 +607,10 @@ fn convert_wgsl() { ("invariant", Targets::GLSL), ("ray-query", Targets::SPIRV | Targets::METAL), ("hlsl-keyword", Targets::HLSL), + ( + "constructors", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + ), ]; for &(name, targets) in inputs.iter() { From c7490b9832468ca7d1539978091c4769fe148a52 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 3 Apr 2023 21:39:56 -0700 Subject: [PATCH 2037/2212] Document constant and override expressions. --- src/lib.rs | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9cff798ae..a835fec32 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -170,6 +170,35 @@ nested `Block` is not available in the `Block`'s parents. Such a value would need to be stored in a local variable to be carried upwards in the statement tree. +## Constant expressions + +A Naga *constant expression* is one of the following [`Expression`] +variants, whose operands (if any) are also constant expressions: +- [`Literal`] +- [`Constant`], for [`Constant`s][const_type] whose [`override`] is [`None`] +- [`ZeroValue`], for fixed-size types +- [`Compose`] +- [`Access`] +- [`AccessIndex`] +- [`Splat`] +- [`Swizzle`] +- [`Unary`] +- [`Binary`] +- [`Select`] +- [`Relational`] +- [`Math`] +- [`As`] + +A constant expression can be evaluated at module translation time. + +## Override expressions + +A Naga *override expression* is the same as a [constant expression], +except that it is also allowed to refer to [`Constant`s][const_type] +whose [`override`] is something other than [`None`]. + +An override expression can be evaluated at pipeline creation time. + [`AtomicResult`]: Expression::AtomicResult [`RayQueryProceedResult`]: Expression::RayQueryProceedResult [`CallResult`]: Expression::CallResult @@ -194,6 +223,26 @@ tree. [`Validator::validate`]: valid::Validator::validate [`ModuleInfo`]: valid::ModuleInfo + +[`Literal`]: Expression::Literal +[`ZeroValue`]: Expression::ZeroValue +[`Compose`]: Expression::Compose +[`Access`]: Expression::Access +[`AccessIndex`]: Expression::AccessIndex +[`Splat`]: Expression::Splat +[`Swizzle`]: Expression::Swizzle +[`Unary`]: Expression::Unary +[`Binary`]: Expression::Binary +[`Select`]: Expression::Select +[`Relational`]: Expression::Relational +[`Math`]: Expression::Math +[`As`]: Expression::As + +[const_type]: Constant +[`override`]: Constant::override +[`None`]: Override::None + +[constant expression]: index.html#constant-expressions */ #![allow( @@ -829,7 +878,20 @@ pub struct Constant { pub name: Option, pub r#override: Override, pub ty: Handle, - /// Expression handle lives in const_expressions + + /// The value of the constant. + /// + /// This [`Handle`] refers to [`Module::const_expressions`], not + /// any [`Function::expressions`] arena. + /// + /// If [`override`] is [`None`], then this must be a Naga + /// [constant expression]. Otherwise, this may be a Naga + /// [override expression] or [constant expression]. + /// + /// [`override`]: Constant::override + /// [`None`]: Override::None + /// [constant expression]: index.html#constant-expressions + /// [override expression]: index.html#override-expressions pub init: Handle, } @@ -1927,10 +1989,13 @@ pub struct Module { pub constants: Arena, /// Arena for the global variables defined in this module. pub global_variables: Arena, - /// const/override-expressions used by this module. + /// [Constant expressions] and [override expressions] used by this module. /// - /// An `Expression` must occur before all other `Expression`s that use its - /// value. + /// Each `Expression` must occur in the arena before any + /// `Expression` that uses its value. + /// + /// [Constant expressions]: index.html#constant-expressions + /// [override expressions]: index.html#override-expressions pub const_expressions: Arena, /// Arena for the functions defined in this module. /// From a3dff6b840bf49a007e10b773121d96a1a9e9743 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 19 Apr 2023 07:11:18 -0700 Subject: [PATCH 2038/2212] Document `front::wgsl::lower::ExpressionContextType` and friends. --- src/front/wgsl/lower/mod.rs | 57 +++++++++++++++++++++++++++++++++++-- src/front/wgsl/parse/mod.rs | 5 +++- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 6fecc6c26..ee592f398 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -191,14 +191,52 @@ impl RuntimeExpressionContext<'_, '_> { } } +/// The type of Naga IR expression we are lowering an [`ast::Expression`] to. pub enum ExpressionContextType<'temp, 'out> { + /// We are lowering to an arbitrary runtime expression, to be + /// included in a function's body. + /// + /// The given [`RuntimeExpressionContext`] holds information about + /// local variables, arguments, and other definitions available to + /// runtime expressions, but not constant or override expressions. Runtime(RuntimeExpressionContext<'temp, 'out>), + + /// We are lowering to a constant expression. + /// + /// Everything constant expressions are allowed to refer to is + /// available in the [`ExpressionContext`], so this variant + /// carries no further information. Constant, } -/// State for lowering an `ast::Expression` to Naga IR. +/// State for lowering an [`ast::Expression`] to Naga IR. /// -/// Not to be confused with `parser::ExpressionContext`. +/// [`ExpressionContext`]s come in two kinds: +/// +/// depending on the `expr_type` is a value of this type, determining what sort +/// of IR expression the context builds. +/// +/// These are constructed in restricted ways: +/// +/// - To originate a [`Runtime`] [`ExpressionContext`], call +/// [`StatementContext::as_expression`]. +/// +/// - To originate a [`Constant`] [`ExpressionContext`], call +/// [`GlobalContext::as_const`]. +/// +/// - You can demote a [`Runtime`] [`ExpressionContext`] to a [`Constant`] +/// context by calling [`as_const`], but there's no way to go in the other +/// direction and get a runtime context from a constant one. +/// +/// - You can always call [`ExpressionContext::reborrow`] to get a fresh context +/// for a recursive call. The reborrowed context is identical to the original. +/// +/// Not to be confused with `wgsl::parse::ExpressionContext`, which is +/// for parsing the `ast::Expression` in the first place. +/// +/// [`Runtime`]: ExpressionContextType::Runtime +/// [`Constant`]: ExpressionContextType::Constant +/// [`as_const`]: ExpressionContext::as_const pub struct ExpressionContext<'source, 'temp, 'out> { // WGSL AST values. ast_expressions: &'temp Arena>, @@ -209,8 +247,18 @@ pub struct ExpressionContext<'source, 'temp, 'out> { /// `Handle`s we have built for them, owned by `Lowerer::lower`. globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, - const_typifier: &'temp mut Typifier, + /// The IR [`Module`] we're constructing. + /// + /// [`Module`]: crate::Module module: &'out mut crate::Module, + + /// Type judgments for [`module::const_expressions`]. + /// + /// [`module::const_expressions`]: crate::Module::const_expressions + const_typifier: &'temp mut Typifier, + + /// Whether we are lowering a constant expression or a general + /// runtime expression, and the data needed in each case. expr_type: ExpressionContextType<'temp, 'out>, } @@ -353,6 +401,9 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { handle: Handle, ) -> Result, Error<'source>> { self.grow_types(handle)?; + // This is equivalent to calling ExpressionContext::typifier(), + // except that this lets the borrow checker see that it's okay + // to also borrow self.module.types mutably below. let typifier = match self.expr_type { ExpressionContextType::Runtime(ref ctx) => ctx.typifier, ExpressionContextType::Constant => &*self.const_typifier, diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 8e7abed70..c13ee5277 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -11,7 +11,10 @@ pub mod number; /// State for constructing an AST expression. /// -/// Not to be confused with `lower::ExpressionContext`. +/// Not to be confused with [`lower::ExpressionContext`], which is for producing +/// Naga IR from the AST we produce here. +/// +/// [`lower::ExpressionContext`]: super::lower::ExpressionContext struct ExpressionContext<'input, 'temp, 'out> { /// The [`TranslationUnit::expressions`] arena to which we should contribute /// expressions. From 63bc66bc70f5ea63a9fc7603666cc225d329ef3c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 30 Jun 2023 16:31:12 -0700 Subject: [PATCH 2039/2212] Reject constant/initializer cycles in handle validation. --- src/valid/handles.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/valid/handles.rs b/src/valid/handles.rs index 3ec062415..da95f6084 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -216,6 +216,7 @@ impl super::Validator { crate::Expression::Literal(_) => {} crate::Expression::Constant(constant) => { validate_constant(constant)?; + handle.check_dep(constants[constant].init)?; } crate::Expression::ZeroValue(ty) => { validate_type(ty)?; @@ -661,3 +662,51 @@ impl crate::arena::Range { arena.check_contains_range(self) } } + +#[test] +#[cfg(feature = "validate")] +fn constant_deps() { + use crate::{Constant, Expression, Literal, Span, Type, TypeInner}; + + let nowhere = Span::default(); + + let mut types = UniqueArena::new(); + let mut const_exprs = Arena::new(); + let mut fun_exprs = Arena::new(); + let mut constants = Arena::new(); + + let i32_handle = types.insert( + Type { + name: None, + inner: TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width: 4, + }, + }, + nowhere, + ); + + // Construct a self-referential constant by misusing a handle to + // fun_exprs as a constant initializer. + let fun_expr = fun_exprs.append(Expression::Literal(Literal::I32(42)), nowhere); + let self_referential_const = constants.append( + Constant { + name: None, + r#override: crate::Override::None, + ty: i32_handle, + init: fun_expr, + }, + nowhere, + ); + let _self_referential_expr = + const_exprs.append(Expression::Constant(self_referential_const), nowhere); + + for handle_and_expr in const_exprs.iter() { + assert!(super::Validator::validate_const_expression_handles( + handle_and_expr, + &constants, + &types, + ) + .is_err()); + } +} From e7cd4ffbaa22444bc2057e3a5eaa04fa97406370 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 13 Jul 2023 15:46:12 -0700 Subject: [PATCH 2040/2212] [wgsl-in] Document ExpressionContextType, ExpressionContext. --- src/front/wgsl/lower/mod.rs | 41 ++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index ee592f398..cf52d6ce8 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -196,12 +196,13 @@ pub enum ExpressionContextType<'temp, 'out> { /// We are lowering to an arbitrary runtime expression, to be /// included in a function's body. /// - /// The given [`RuntimeExpressionContext`] holds information about - /// local variables, arguments, and other definitions available to - /// runtime expressions, but not constant or override expressions. + /// The given [`RuntimeExpressionContext`] holds information about local + /// variables, arguments, and other definitions available only to runtime + /// expressions, not constant or override expressions. Runtime(RuntimeExpressionContext<'temp, 'out>), - /// We are lowering to a constant expression. + /// We are lowering to a constant expression, to be included in the module's + /// constant expression arena. /// /// Everything constant expressions are allowed to refer to is /// available in the [`ExpressionContext`], so this variant @@ -211,32 +212,44 @@ pub enum ExpressionContextType<'temp, 'out> { /// State for lowering an [`ast::Expression`] to Naga IR. /// -/// [`ExpressionContext`]s come in two kinds: +/// [`ExpressionContext`]s come in two kinds, distinguished by +/// the value of the [`expr_type`] field: /// -/// depending on the `expr_type` is a value of this type, determining what sort -/// of IR expression the context builds. +/// - A [`Runtime`] context contributes [`naga::Expression`]s to a [`naga::Function`]'s +/// runtime expression arena. /// -/// These are constructed in restricted ways: +/// - A [`Constant`] context contributes [`naga::Expression`]s to a [`naga::Module`]'s +/// constant expression arena. /// -/// - To originate a [`Runtime`] [`ExpressionContext`], call +/// [`ExpressionContext`]s are constructed in restricted ways: +/// +/// - To get a [`Runtime`] [`ExpressionContext`], call /// [`StatementContext::as_expression`]. /// -/// - To originate a [`Constant`] [`ExpressionContext`], call +/// - To get a [`Constant`] [`ExpressionContext`], call /// [`GlobalContext::as_const`]. /// -/// - You can demote a [`Runtime`] [`ExpressionContext`] to a [`Constant`] -/// context by calling [`as_const`], but there's no way to go in the other -/// direction and get a runtime context from a constant one. +/// - You can demote a [`Runtime`] context to a [`Constant`] context +/// by calling [`as_const`], but there's no way to go in the other +/// direction, producing a runtime context from a constant one. This +/// is because runtime expressions can refer to constant +/// expressions, via [`Expression::Constant`], but constant +/// expressions can't refer to a function's expressions. /// /// - You can always call [`ExpressionContext::reborrow`] to get a fresh context -/// for a recursive call. The reborrowed context is identical to the original. +/// for a recursive call. The reborrowed context is equivalent to the original. /// /// Not to be confused with `wgsl::parse::ExpressionContext`, which is /// for parsing the `ast::Expression` in the first place. /// +/// [`expr_type`]: ExpressionContext::expr_type /// [`Runtime`]: ExpressionContextType::Runtime +/// [`naga::Expression`]: crate::Expression +/// [`naga::Function`]: crate::Function /// [`Constant`]: ExpressionContextType::Constant +/// [`naga::Module`]: crate::Module /// [`as_const`]: ExpressionContext::as_const +/// [`Expression::Constant`]: crate::Expression::Constant pub struct ExpressionContext<'source, 'temp, 'out> { // WGSL AST values. ast_expressions: &'temp Arena>, From 409239c0e2313bfd0dc4fd64f8c3021185ccef1b Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 13 Jul 2023 15:48:43 -0700 Subject: [PATCH 2041/2212] [glsl-out] Various doc fixes. --- src/back/glsl/mod.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 696598bdf..ef5dd0143 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1581,7 +1581,7 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } - /// Helper method that writes a list of comma separated `T` with a writer function `F` + /// Write a list of comma separated `T` values using a writer function `F`. /// /// The writer function `F` receives a mutable reference to `self` that if needed won't cause /// borrow checker issues (using for example a closure with `self` will cause issues), the @@ -1596,7 +1596,7 @@ impl<'a, W: Write> Writer<'a, W> { data: &[T], mut f: F, ) -> BackendResult { - // Loop trough `data` invoking `f` for each element + // Loop through `data` invoking `f` for each element for (index, item) in data.iter().enumerate() { if index != 0 { write!(self.out, ", ")?; @@ -2164,20 +2164,40 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } - /// Helper method used to write constant expressions + /// Write a const expression. + /// + /// Write `expr`, a handle to an [`Expression`] in the current [`Module`]'s + /// constant expression arena, as GLSL expression. /// /// # Notes /// Adds no newlines or leading/trailing whitespace + /// + /// [`Expression`]: crate::Expression + /// [`Module`]: crate::Module fn write_const_expr(&mut self, expr: Handle) -> BackendResult { self.write_possibly_const_expr(expr, &self.module.const_expressions, |writer, expr| { writer.write_const_expr(expr) }) } - /// Helper method used to write possibly constant expressions + /// Write [`Expression`] variants that can occur in both runtime and const expressions. + /// + /// Write `expr`, a handle to an [`Expression`] in the arena `expressions`, + /// as as GLSL expression. This must be one of the [`Expression`] variants + /// that is allowed to occur in constant expressions. + /// + /// Use `write_expression` to write subexpressions. + /// + /// This is the common code for `write_expr`, which handles arbitrary + /// runtime expressions, and `write_const_expr`, which only handles + /// const-expressions. Each of those callers passes itself (essentially) as + /// the `write_expression` callback, so that subexpressions are restricted + /// to the appropriate variants. /// /// # Notes /// Adds no newlines or leading/trailing whitespace + /// + /// [`Expression`]: crate::Expression fn write_possibly_const_expr( &mut self, expr: Handle, From c67fcc24bb978c418916a167c42b4e1df152d961 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Wed, 19 Jul 2023 20:44:33 -0400 Subject: [PATCH 2042/2212] Bump dependencies --- Cargo.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2f44f8203..0b90ee678 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,14 +66,14 @@ unicode-xid = { version = "0.2.3", optional = true } [dev-dependencies] bincode = "1" -criterion = { version = "0.3", features = [] } +criterion = { version = "0.5", features = [] } diff = "0.1" -env_logger = "0.9" +env_logger = "0.10" hlsl-snapshots = { path = "./hlsl-snapshots"} # Require at least version 0.7.1 of ron, this version changed how floating points are # serialized by forcing them to always have the decimal part, this makes it backwards # incompatible with our tests because we do a syntatic diff and not a semantic one. -ron = "~0.7.1" +ron = "0.8.0" rspirv = { version = "0.11", git = "https://github.com/gfx-rs/rspirv", rev = "b969f175d5663258b4891e44b76c1544da9661ab" } serde = { version = "1.0", features = ["derive"] } spirv = { version = "0.2", features = ["deserialize"] } From bac2d82a430fbfcf100ee22b7c3bc12f3d593079 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Thu, 20 Jul 2023 22:16:18 -0400 Subject: [PATCH 2043/2212] Bump naga versions --- Cargo.toml | 2 +- cli/Cargo.toml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0b90ee678..65b806720 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.12.0" +version = "0.13.0" authors = ["Naga Developers"] edition = "2021" description = "Shader translation infrastructure" diff --git a/cli/Cargo.toml b/cli/Cargo.toml index ef6f6aff4..a159b041f 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga-cli" -version = "0.12.0" +version = "0.13.0" authors = ["Naga Developers"] edition = "2021" description = "Shader translation command line tool" @@ -10,7 +10,7 @@ keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" [dependencies] -naga = { version = "0.12", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } +naga = { version = "0.13", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } bincode = "1" log = "0.4" codespan-reporting = "0.11" From 5f8e4f6dead465f43b9727f151fa773770d6b488 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Mon, 24 Jul 2023 15:25:45 -0400 Subject: [PATCH 2044/2212] [spv] Fix OpImageQueries to allow Uints (#2404) --- src/back/spv/image.rs | 89 +-- src/front/spv/image.rs | 42 +- src/front/spv/mod.rs | 12 +- tests/out/spv/binding-arrays.spvasm | 876 +++++++++++------------ tests/out/spv/image.spvasm | 1025 +++++++++++++-------------- 5 files changed, 978 insertions(+), 1066 deletions(-) diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index ac4b71d95..a80ef3cfd 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -1045,7 +1045,7 @@ impl<'w> BlockContext<'w> { }; let extended_size_type_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size, - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Uint, width: 4, pointer_space: None, })); @@ -1077,24 +1077,7 @@ impl<'w> BlockContext<'w> { } block.body.push(inst); - let bitcast_type_id = self.get_type_id( - LocalType::Value { - vector_size, - kind: crate::ScalarKind::Uint, - width: 4, - pointer_space: None, - } - .into(), - ); - let bitcast_id = self.gen_id(); - block.body.push(Instruction::unary( - spirv::Op::Bitcast, - bitcast_type_id, - bitcast_id, - id_extended, - )); - - if result_type_id != bitcast_type_id { + if result_type_id != extended_size_type_id { let id = self.gen_id(); let components = match dim { // always pick the first component, and duplicate it for all 3 dimensions @@ -1104,42 +1087,26 @@ impl<'w> BlockContext<'w> { block.body.push(Instruction::vector_shuffle( result_type_id, id, - bitcast_id, - bitcast_id, + id_extended, + id_extended, components, )); id } else { - bitcast_id + id_extended } } Iq::NumLevels => { let query_id = self.gen_id(); block.body.push(Instruction::image_query( spirv::Op::ImageQueryLevels, - self.get_type_id( - LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Sint, - width: 4, - pointer_space: None, - } - .into(), - ), + result_type_id, query_id, image_id, )); - let id = self.gen_id(); - block.body.push(Instruction::unary( - spirv::Op::Bitcast, - result_type_id, - id, - query_id, - )); - - id + query_id } Iq::NumLayers => { let vec_size = match dim { @@ -1149,7 +1116,7 @@ impl<'w> BlockContext<'w> { }; let extended_size_type_id = self.get_type_id(LookupType::Local(LocalType::Value { vector_size: Some(vec_size), - kind: crate::ScalarKind::Sint, + kind: crate::ScalarKind::Uint, width: 4, pointer_space: None, })); @@ -1165,56 +1132,24 @@ impl<'w> BlockContext<'w> { let extract_id = self.gen_id(); block.body.push(Instruction::composite_extract( - self.get_type_id( - LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Sint, - width: 4, - pointer_space: None, - } - .into(), - ), + result_type_id, extract_id, id_extended, &[vec_size as u32 - 1], )); - let id = self.gen_id(); - block.body.push(Instruction::unary( - spirv::Op::Bitcast, - result_type_id, - id, - extract_id, - )); - - id + extract_id } Iq::NumSamples => { let query_id = self.gen_id(); block.body.push(Instruction::image_query( spirv::Op::ImageQuerySamples, - self.get_type_id( - LocalType::Value { - vector_size: None, - kind: crate::ScalarKind::Sint, - width: 4, - pointer_space: None, - } - .into(), - ), + result_type_id, query_id, image_id, )); - let id = self.gen_id(); - block.body.push(Instruction::unary( - spirv::Op::Bitcast, - result_type_id, - id, - query_id, - )); - - id + query_id } }; diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index ac0129059..1cefeb4fc 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -1,4 +1,4 @@ -use crate::arena::{Arena, Handle, UniqueArena}; +use crate::arena::{Handle, UniqueArena}; use super::{Error, LookupExpression, LookupHelper as _}; @@ -689,11 +689,20 @@ impl> super::Frontend { image: image_lexp.handle, query: crate::ImageQuery::Size { level }, }; - let expr = crate::Expression::As { - expr: ctx.expressions.append(expr, self.span_from_with_op(start)), - kind: crate::ScalarKind::Sint, - convert: Some(4), + + let result_type_handle = self.lookup_type.lookup(result_type_id)?.handle; + let maybe_scalar_kind = ctx.type_arena[result_type_handle].inner.scalar_kind(); + + let expr = if maybe_scalar_kind == Some(crate::ScalarKind::Sint) { + crate::Expression::As { + expr: ctx.expressions.append(expr, self.span_from_with_op(start)), + kind: crate::ScalarKind::Sint, + convert: Some(4), + } + } else { + expr }; + self.lookup_expression.insert( result_id, LookupExpression { @@ -702,13 +711,14 @@ impl> super::Frontend { block_id, }, ); + Ok(()) } pub(super) fn parse_image_query_other( &mut self, query: crate::ImageQuery, - expressions: &mut Arena, + ctx: &mut super::BlockContext, block_id: spirv::Word, ) -> Result<(), Error> { let start = self.data_offset; @@ -724,19 +734,29 @@ impl> super::Frontend { image: image_lexp.handle, query, }; - let expr = crate::Expression::As { - expr: expressions.append(expr, self.span_from_with_op(start)), - kind: crate::ScalarKind::Sint, - convert: Some(4), + + let result_type_handle = self.lookup_type.lookup(result_type_id)?.handle; + let maybe_scalar_kind = ctx.type_arena[result_type_handle].inner.scalar_kind(); + + let expr = if maybe_scalar_kind == Some(crate::ScalarKind::Sint) { + crate::Expression::As { + expr: ctx.expressions.append(expr, self.span_from_with_op(start)), + kind: crate::ScalarKind::Sint, + convert: Some(4), + } + } else { + expr }; + self.lookup_expression.insert( result_id, LookupExpression { - handle: expressions.append(expr, self.span_from_with_op(start)), + handle: ctx.expressions.append(expr, self.span_from_with_op(start)), type_id: result_type_id, block_id, }, ); + Ok(()) } } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 6ddd1d70c..a210e8c42 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2695,19 +2695,11 @@ impl> Frontend { } Op::ImageQueryLevels => { inst.expect(4)?; - self.parse_image_query_other( - crate::ImageQuery::NumLevels, - ctx.expressions, - block_id, - )?; + self.parse_image_query_other(crate::ImageQuery::NumLevels, ctx, block_id)?; } Op::ImageQuerySamples => { inst.expect(4)?; - self.parse_image_query_other( - crate::ImageQuery::NumSamples, - ctx.expressions, - block_id, - )?; + self.parse_image_query_other(crate::ImageQuery::NumSamples, ctx, block_id)?; } // other ops Op::Select => { diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 393df57bb..630ae6fbc 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 447 +; Bound: 435 OpCapability Shader OpCapability ImageQuery OpCapability ShaderNonUniform @@ -35,28 +35,28 @@ OpMemberDecorate %47 0 Offset 0 OpDecorate %63 Location 0 OpDecorate %63 Flat OpDecorate %66 Location 0 -OpDecorate %97 NonUniform -OpDecorate %121 NonUniform -OpDecorate %123 NonUniform -OpDecorate %148 NonUniform -OpDecorate %150 NonUniform -OpDecorate %188 NonUniform -OpDecorate %219 NonUniform -OpDecorate %238 NonUniform -OpDecorate %257 NonUniform -OpDecorate %279 NonUniform -OpDecorate %281 NonUniform -OpDecorate %303 NonUniform -OpDecorate %305 NonUniform -OpDecorate %327 NonUniform -OpDecorate %329 NonUniform -OpDecorate %351 NonUniform -OpDecorate %353 NonUniform -OpDecorate %375 NonUniform -OpDecorate %377 NonUniform -OpDecorate %399 NonUniform -OpDecorate %401 NonUniform -OpDecorate %424 NonUniform +OpDecorate %95 NonUniform +OpDecorate %118 NonUniform +OpDecorate %120 NonUniform +OpDecorate %145 NonUniform +OpDecorate %147 NonUniform +OpDecorate %185 NonUniform +OpDecorate %214 NonUniform +OpDecorate %230 NonUniform +OpDecorate %246 NonUniform +OpDecorate %267 NonUniform +OpDecorate %269 NonUniform +OpDecorate %291 NonUniform +OpDecorate %293 NonUniform +OpDecorate %315 NonUniform +OpDecorate %317 NonUniform +OpDecorate %339 NonUniform +OpDecorate %341 NonUniform +OpDecorate %363 NonUniform +OpDecorate %365 NonUniform +OpDecorate %387 NonUniform +OpDecorate %389 NonUniform +OpDecorate %412 NonUniform %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeStruct %3 @@ -123,20 +123,20 @@ OpDecorate %424 NonUniform %74 = OpConstant %26 0 %76 = OpTypePointer Uniform %3 %84 = OpTypePointer UniformConstant %5 -%105 = OpTypePointer UniformConstant %18 -%108 = OpTypeSampledImage %5 -%129 = OpTypePointer UniformConstant %14 -%132 = OpTypePointer UniformConstant %18 -%135 = OpTypeSampledImage %14 -%158 = OpTypeBool -%159 = OpConstantNull %22 -%165 = OpTypeVector %158 2 -%175 = OpConstantNull %22 -%190 = OpConstantNull %22 -%203 = OpTypePointer UniformConstant %10 -%206 = OpTypeVector %26 3 -%244 = OpTypePointer UniformConstant %12 -%407 = OpTypePointer UniformConstant %16 +%102 = OpTypePointer UniformConstant %18 +%105 = OpTypeSampledImage %5 +%126 = OpTypePointer UniformConstant %14 +%129 = OpTypePointer UniformConstant %18 +%132 = OpTypeSampledImage %14 +%155 = OpTypeBool +%156 = OpConstantNull %22 +%162 = OpTypeVector %155 2 +%172 = OpConstantNull %22 +%187 = OpConstantNull %22 +%200 = OpTypePointer UniformConstant %10 +%203 = OpTypeVector %3 3 +%235 = OpTypePointer UniformConstant %12 +%395 = OpTypePointer UniformConstant %16 %68 = OpFunction %2 None %69 %61 = OpLabel %52 = OpVariable %53 Function %54 @@ -161,415 +161,403 @@ OpStore %58 %81 %83 = OpCompositeConstruct %25 %74 %74 %85 = OpAccessChain %84 %28 %71 %86 = OpLoad %5 %85 -%87 = OpImageQuerySizeLod %25 %86 %71 -%88 = OpBitcast %23 %87 -%89 = OpLoad %23 %52 -%90 = OpIAdd %23 %89 %88 -OpStore %52 %90 -%91 = OpAccessChain %84 %28 %78 -%92 = OpLoad %5 %91 -%93 = OpImageQuerySizeLod %25 %92 %71 -%94 = OpBitcast %23 %93 -%95 = OpLoad %23 %52 -%96 = OpIAdd %23 %95 %94 -OpStore %52 %96 -%97 = OpAccessChain %84 %28 %79 -%98 = OpLoad %5 %97 -%99 = OpImageQuerySizeLod %25 %98 %71 -%100 = OpBitcast %23 %99 -%101 = OpLoad %23 %52 -%102 = OpIAdd %23 %101 %100 -OpStore %52 %102 -%103 = OpAccessChain %84 %32 %71 -%104 = OpLoad %5 %103 -%106 = OpAccessChain %105 %42 %71 -%107 = OpLoad %18 %106 -%109 = OpSampledImage %108 %104 %107 -%110 = OpImageGather %22 %109 %82 %71 -%111 = OpLoad %22 %58 -%112 = OpFAdd %22 %111 %110 -OpStore %58 %112 -%113 = OpAccessChain %84 %32 %78 -%114 = OpLoad %5 %113 -%115 = OpAccessChain %105 %42 %78 -%116 = OpLoad %18 %115 -%117 = OpSampledImage %108 %114 %116 -%118 = OpImageGather %22 %117 %82 %71 -%119 = OpLoad %22 %58 -%120 = OpFAdd %22 %119 %118 -OpStore %58 %120 -%121 = OpAccessChain %84 %32 %79 -%122 = OpLoad %5 %121 -%123 = OpAccessChain %105 %42 %79 -%124 = OpLoad %18 %123 -%125 = OpSampledImage %108 %122 %124 -%126 = OpImageGather %22 %125 %82 %71 -%127 = OpLoad %22 %58 -%128 = OpFAdd %22 %127 %126 -OpStore %58 %128 -%130 = OpAccessChain %129 %38 %71 -%131 = OpLoad %14 %130 -%133 = OpAccessChain %132 %44 %71 -%134 = OpLoad %18 %133 -%136 = OpSampledImage %135 %131 %134 -%137 = OpImageDrefGather %22 %136 %82 %73 -%138 = OpLoad %22 %58 -%139 = OpFAdd %22 %138 %137 -OpStore %58 %139 -%140 = OpAccessChain %129 %38 %78 -%141 = OpLoad %14 %140 -%142 = OpAccessChain %132 %44 %78 -%143 = OpLoad %18 %142 -%144 = OpSampledImage %135 %141 %143 -%145 = OpImageDrefGather %22 %144 %82 %73 -%146 = OpLoad %22 %58 -%147 = OpFAdd %22 %146 %145 -OpStore %58 %147 -%148 = OpAccessChain %129 %38 %79 -%149 = OpLoad %14 %148 -%150 = OpAccessChain %132 %44 %79 -%151 = OpLoad %18 %150 -%152 = OpSampledImage %135 %149 %151 -%153 = OpImageDrefGather %22 %152 %82 %73 -%154 = OpLoad %22 %58 -%155 = OpFAdd %22 %154 %153 -OpStore %58 %155 -%156 = OpAccessChain %84 %28 %71 -%157 = OpLoad %5 %156 -%160 = OpImageQueryLevels %26 %157 -%161 = OpULessThan %158 %74 %160 -OpSelectionMerge %162 None -OpBranchConditional %161 %163 %162 -%163 = OpLabel -%164 = OpImageQuerySizeLod %25 %157 %74 -%166 = OpULessThan %165 %83 %164 -%167 = OpAll %158 %166 -OpBranchConditional %167 %168 %162 -%168 = OpLabel -%169 = OpImageFetch %22 %157 %83 Lod %74 -OpBranch %162 -%162 = OpLabel -%170 = OpPhi %22 %159 %75 %159 %163 %169 %168 -%171 = OpLoad %22 %58 -%172 = OpFAdd %22 %171 %170 -OpStore %58 %172 -%173 = OpAccessChain %84 %28 %78 -%174 = OpLoad %5 %173 -%176 = OpImageQueryLevels %26 %174 -%177 = OpULessThan %158 %74 %176 -OpSelectionMerge %178 None -OpBranchConditional %177 %179 %178 -%179 = OpLabel -%180 = OpImageQuerySizeLod %25 %174 %74 -%181 = OpULessThan %165 %83 %180 -%182 = OpAll %158 %181 -OpBranchConditional %182 %183 %178 -%183 = OpLabel -%184 = OpImageFetch %22 %174 %83 Lod %74 -OpBranch %178 -%178 = OpLabel -%185 = OpPhi %22 %175 %162 %175 %179 %184 %183 -%186 = OpLoad %22 %58 -%187 = OpFAdd %22 %186 %185 -OpStore %58 %187 -%188 = OpAccessChain %84 %28 %79 -%189 = OpLoad %5 %188 -%191 = OpImageQueryLevels %26 %189 -%192 = OpULessThan %158 %74 %191 -OpSelectionMerge %193 None -OpBranchConditional %192 %194 %193 -%194 = OpLabel -%195 = OpImageQuerySizeLod %25 %189 %74 -%196 = OpULessThan %165 %83 %195 -%197 = OpAll %158 %196 -OpBranchConditional %197 %198 %193 -%198 = OpLabel -%199 = OpImageFetch %22 %189 %83 Lod %74 -OpBranch %193 -%193 = OpLabel -%200 = OpPhi %22 %190 %178 %190 %194 %199 %198 -%201 = OpLoad %22 %58 -%202 = OpFAdd %22 %201 %200 -OpStore %58 %202 -%204 = OpAccessChain %203 %34 %71 -%205 = OpLoad %10 %204 -%207 = OpImageQuerySizeLod %206 %205 %71 -%208 = OpCompositeExtract %26 %207 2 -%209 = OpBitcast %3 %208 -%210 = OpLoad %3 %49 -%211 = OpIAdd %3 %210 %209 -OpStore %49 %211 -%212 = OpAccessChain %203 %34 %78 -%213 = OpLoad %10 %212 -%214 = OpImageQuerySizeLod %206 %213 %71 -%215 = OpCompositeExtract %26 %214 2 -%216 = OpBitcast %3 %215 -%217 = OpLoad %3 %49 -%218 = OpIAdd %3 %217 %216 -OpStore %49 %218 -%219 = OpAccessChain %203 %34 %79 -%220 = OpLoad %10 %219 -%221 = OpImageQuerySizeLod %206 %220 %71 -%222 = OpCompositeExtract %26 %221 2 -%223 = OpBitcast %3 %222 -%224 = OpLoad %3 %49 -%225 = OpIAdd %3 %224 %223 -OpStore %49 %225 -%226 = OpAccessChain %84 %32 %71 -%227 = OpLoad %5 %226 -%228 = OpImageQueryLevels %26 %227 -%229 = OpBitcast %3 %228 -%230 = OpLoad %3 %49 -%231 = OpIAdd %3 %230 %229 -OpStore %49 %231 -%232 = OpAccessChain %84 %32 %78 -%233 = OpLoad %5 %232 -%234 = OpImageQueryLevels %26 %233 -%235 = OpBitcast %3 %234 -%236 = OpLoad %3 %49 -%237 = OpIAdd %3 %236 %235 -OpStore %49 %237 -%238 = OpAccessChain %84 %32 %79 -%239 = OpLoad %5 %238 -%240 = OpImageQueryLevels %26 %239 -%241 = OpBitcast %3 %240 -%242 = OpLoad %3 %49 -%243 = OpIAdd %3 %242 %241 -OpStore %49 %243 -%245 = OpAccessChain %244 %36 %71 -%246 = OpLoad %12 %245 -%247 = OpImageQuerySamples %26 %246 -%248 = OpBitcast %3 %247 +%87 = OpImageQuerySizeLod %23 %86 %71 +%88 = OpLoad %23 %52 +%89 = OpIAdd %23 %88 %87 +OpStore %52 %89 +%90 = OpAccessChain %84 %28 %78 +%91 = OpLoad %5 %90 +%92 = OpImageQuerySizeLod %23 %91 %71 +%93 = OpLoad %23 %52 +%94 = OpIAdd %23 %93 %92 +OpStore %52 %94 +%95 = OpAccessChain %84 %28 %79 +%96 = OpLoad %5 %95 +%97 = OpImageQuerySizeLod %23 %96 %71 +%98 = OpLoad %23 %52 +%99 = OpIAdd %23 %98 %97 +OpStore %52 %99 +%100 = OpAccessChain %84 %32 %71 +%101 = OpLoad %5 %100 +%103 = OpAccessChain %102 %42 %71 +%104 = OpLoad %18 %103 +%106 = OpSampledImage %105 %101 %104 +%107 = OpImageGather %22 %106 %82 %71 +%108 = OpLoad %22 %58 +%109 = OpFAdd %22 %108 %107 +OpStore %58 %109 +%110 = OpAccessChain %84 %32 %78 +%111 = OpLoad %5 %110 +%112 = OpAccessChain %102 %42 %78 +%113 = OpLoad %18 %112 +%114 = OpSampledImage %105 %111 %113 +%115 = OpImageGather %22 %114 %82 %71 +%116 = OpLoad %22 %58 +%117 = OpFAdd %22 %116 %115 +OpStore %58 %117 +%118 = OpAccessChain %84 %32 %79 +%119 = OpLoad %5 %118 +%120 = OpAccessChain %102 %42 %79 +%121 = OpLoad %18 %120 +%122 = OpSampledImage %105 %119 %121 +%123 = OpImageGather %22 %122 %82 %71 +%124 = OpLoad %22 %58 +%125 = OpFAdd %22 %124 %123 +OpStore %58 %125 +%127 = OpAccessChain %126 %38 %71 +%128 = OpLoad %14 %127 +%130 = OpAccessChain %129 %44 %71 +%131 = OpLoad %18 %130 +%133 = OpSampledImage %132 %128 %131 +%134 = OpImageDrefGather %22 %133 %82 %73 +%135 = OpLoad %22 %58 +%136 = OpFAdd %22 %135 %134 +OpStore %58 %136 +%137 = OpAccessChain %126 %38 %78 +%138 = OpLoad %14 %137 +%139 = OpAccessChain %129 %44 %78 +%140 = OpLoad %18 %139 +%141 = OpSampledImage %132 %138 %140 +%142 = OpImageDrefGather %22 %141 %82 %73 +%143 = OpLoad %22 %58 +%144 = OpFAdd %22 %143 %142 +OpStore %58 %144 +%145 = OpAccessChain %126 %38 %79 +%146 = OpLoad %14 %145 +%147 = OpAccessChain %129 %44 %79 +%148 = OpLoad %18 %147 +%149 = OpSampledImage %132 %146 %148 +%150 = OpImageDrefGather %22 %149 %82 %73 +%151 = OpLoad %22 %58 +%152 = OpFAdd %22 %151 %150 +OpStore %58 %152 +%153 = OpAccessChain %84 %28 %71 +%154 = OpLoad %5 %153 +%157 = OpImageQueryLevels %26 %154 +%158 = OpULessThan %155 %74 %157 +OpSelectionMerge %159 None +OpBranchConditional %158 %160 %159 +%160 = OpLabel +%161 = OpImageQuerySizeLod %25 %154 %74 +%163 = OpULessThan %162 %83 %161 +%164 = OpAll %155 %163 +OpBranchConditional %164 %165 %159 +%165 = OpLabel +%166 = OpImageFetch %22 %154 %83 Lod %74 +OpBranch %159 +%159 = OpLabel +%167 = OpPhi %22 %156 %75 %156 %160 %166 %165 +%168 = OpLoad %22 %58 +%169 = OpFAdd %22 %168 %167 +OpStore %58 %169 +%170 = OpAccessChain %84 %28 %78 +%171 = OpLoad %5 %170 +%173 = OpImageQueryLevels %26 %171 +%174 = OpULessThan %155 %74 %173 +OpSelectionMerge %175 None +OpBranchConditional %174 %176 %175 +%176 = OpLabel +%177 = OpImageQuerySizeLod %25 %171 %74 +%178 = OpULessThan %162 %83 %177 +%179 = OpAll %155 %178 +OpBranchConditional %179 %180 %175 +%180 = OpLabel +%181 = OpImageFetch %22 %171 %83 Lod %74 +OpBranch %175 +%175 = OpLabel +%182 = OpPhi %22 %172 %159 %172 %176 %181 %180 +%183 = OpLoad %22 %58 +%184 = OpFAdd %22 %183 %182 +OpStore %58 %184 +%185 = OpAccessChain %84 %28 %79 +%186 = OpLoad %5 %185 +%188 = OpImageQueryLevels %26 %186 +%189 = OpULessThan %155 %74 %188 +OpSelectionMerge %190 None +OpBranchConditional %189 %191 %190 +%191 = OpLabel +%192 = OpImageQuerySizeLod %25 %186 %74 +%193 = OpULessThan %162 %83 %192 +%194 = OpAll %155 %193 +OpBranchConditional %194 %195 %190 +%195 = OpLabel +%196 = OpImageFetch %22 %186 %83 Lod %74 +OpBranch %190 +%190 = OpLabel +%197 = OpPhi %22 %187 %175 %187 %191 %196 %195 +%198 = OpLoad %22 %58 +%199 = OpFAdd %22 %198 %197 +OpStore %58 %199 +%201 = OpAccessChain %200 %34 %71 +%202 = OpLoad %10 %201 +%204 = OpImageQuerySizeLod %203 %202 %71 +%205 = OpCompositeExtract %3 %204 2 +%206 = OpLoad %3 %49 +%207 = OpIAdd %3 %206 %205 +OpStore %49 %207 +%208 = OpAccessChain %200 %34 %78 +%209 = OpLoad %10 %208 +%210 = OpImageQuerySizeLod %203 %209 %71 +%211 = OpCompositeExtract %3 %210 2 +%212 = OpLoad %3 %49 +%213 = OpIAdd %3 %212 %211 +OpStore %49 %213 +%214 = OpAccessChain %200 %34 %79 +%215 = OpLoad %10 %214 +%216 = OpImageQuerySizeLod %203 %215 %71 +%217 = OpCompositeExtract %3 %216 2 +%218 = OpLoad %3 %49 +%219 = OpIAdd %3 %218 %217 +OpStore %49 %219 +%220 = OpAccessChain %84 %32 %71 +%221 = OpLoad %5 %220 +%222 = OpImageQueryLevels %3 %221 +%223 = OpLoad %3 %49 +%224 = OpIAdd %3 %223 %222 +OpStore %49 %224 +%225 = OpAccessChain %84 %32 %78 +%226 = OpLoad %5 %225 +%227 = OpImageQueryLevels %3 %226 +%228 = OpLoad %3 %49 +%229 = OpIAdd %3 %228 %227 +OpStore %49 %229 +%230 = OpAccessChain %84 %32 %79 +%231 = OpLoad %5 %230 +%232 = OpImageQueryLevels %3 %231 +%233 = OpLoad %3 %49 +%234 = OpIAdd %3 %233 %232 +OpStore %49 %234 +%236 = OpAccessChain %235 %36 %71 +%237 = OpLoad %12 %236 +%238 = OpImageQuerySamples %3 %237 +%239 = OpLoad %3 %49 +%240 = OpIAdd %3 %239 %238 +OpStore %49 %240 +%241 = OpAccessChain %235 %36 %78 +%242 = OpLoad %12 %241 +%243 = OpImageQuerySamples %3 %242 +%244 = OpLoad %3 %49 +%245 = OpIAdd %3 %244 %243 +OpStore %49 %245 +%246 = OpAccessChain %235 %36 %79 +%247 = OpLoad %12 %246 +%248 = OpImageQuerySamples %3 %247 %249 = OpLoad %3 %49 %250 = OpIAdd %3 %249 %248 OpStore %49 %250 -%251 = OpAccessChain %244 %36 %78 -%252 = OpLoad %12 %251 -%253 = OpImageQuerySamples %26 %252 -%254 = OpBitcast %3 %253 -%255 = OpLoad %3 %49 -%256 = OpIAdd %3 %255 %254 -OpStore %49 %256 -%257 = OpAccessChain %244 %36 %79 -%258 = OpLoad %12 %257 -%259 = OpImageQuerySamples %26 %258 -%260 = OpBitcast %3 %259 -%261 = OpLoad %3 %49 -%262 = OpIAdd %3 %261 %260 -OpStore %49 %262 -%263 = OpAccessChain %84 %32 %71 -%264 = OpLoad %5 %263 -%265 = OpAccessChain %105 %42 %71 -%266 = OpLoad %18 %265 -%267 = OpSampledImage %108 %264 %266 -%268 = OpImageSampleImplicitLod %22 %267 %82 -%269 = OpLoad %22 %58 -%270 = OpFAdd %22 %269 %268 -OpStore %58 %270 -%271 = OpAccessChain %84 %32 %78 -%272 = OpLoad %5 %271 -%273 = OpAccessChain %105 %42 %78 -%274 = OpLoad %18 %273 -%275 = OpSampledImage %108 %272 %274 -%276 = OpImageSampleImplicitLod %22 %275 %82 -%277 = OpLoad %22 %58 -%278 = OpFAdd %22 %277 %276 -OpStore %58 %278 -%279 = OpAccessChain %84 %32 %79 -%280 = OpLoad %5 %279 -%281 = OpAccessChain %105 %42 %79 -%282 = OpLoad %18 %281 -%283 = OpSampledImage %108 %280 %282 -%284 = OpImageSampleImplicitLod %22 %283 %82 -%285 = OpLoad %22 %58 -%286 = OpFAdd %22 %285 %284 -OpStore %58 %286 -%287 = OpAccessChain %84 %32 %71 -%288 = OpLoad %5 %287 -%289 = OpAccessChain %105 %42 %71 -%290 = OpLoad %18 %289 -%291 = OpSampledImage %108 %288 %290 -%292 = OpImageSampleImplicitLod %22 %291 %82 Bias %73 -%293 = OpLoad %22 %58 -%294 = OpFAdd %22 %293 %292 -OpStore %58 %294 -%295 = OpAccessChain %84 %32 %78 -%296 = OpLoad %5 %295 -%297 = OpAccessChain %105 %42 %78 -%298 = OpLoad %18 %297 -%299 = OpSampledImage %108 %296 %298 -%300 = OpImageSampleImplicitLod %22 %299 %82 Bias %73 -%301 = OpLoad %22 %58 -%302 = OpFAdd %22 %301 %300 -OpStore %58 %302 -%303 = OpAccessChain %84 %32 %79 -%304 = OpLoad %5 %303 -%305 = OpAccessChain %105 %42 %79 -%306 = OpLoad %18 %305 -%307 = OpSampledImage %108 %304 %306 -%308 = OpImageSampleImplicitLod %22 %307 %82 Bias %73 -%309 = OpLoad %22 %58 -%310 = OpFAdd %22 %309 %308 -OpStore %58 %310 -%311 = OpAccessChain %129 %38 %71 -%312 = OpLoad %14 %311 -%313 = OpAccessChain %132 %44 %71 -%314 = OpLoad %18 %313 -%315 = OpSampledImage %135 %312 %314 -%316 = OpImageSampleDrefImplicitLod %6 %315 %82 %73 -%317 = OpLoad %6 %55 -%318 = OpFAdd %6 %317 %316 -OpStore %55 %318 -%319 = OpAccessChain %129 %38 %78 -%320 = OpLoad %14 %319 -%321 = OpAccessChain %132 %44 %78 -%322 = OpLoad %18 %321 -%323 = OpSampledImage %135 %320 %322 -%324 = OpImageSampleDrefImplicitLod %6 %323 %82 %73 -%325 = OpLoad %6 %55 -%326 = OpFAdd %6 %325 %324 -OpStore %55 %326 -%327 = OpAccessChain %129 %38 %79 -%328 = OpLoad %14 %327 -%329 = OpAccessChain %132 %44 %79 -%330 = OpLoad %18 %329 -%331 = OpSampledImage %135 %328 %330 -%332 = OpImageSampleDrefImplicitLod %6 %331 %82 %73 -%333 = OpLoad %6 %55 -%334 = OpFAdd %6 %333 %332 -OpStore %55 %334 -%335 = OpAccessChain %129 %38 %71 -%336 = OpLoad %14 %335 -%337 = OpAccessChain %132 %44 %71 -%338 = OpLoad %18 %337 -%339 = OpSampledImage %135 %336 %338 -%340 = OpImageSampleDrefExplicitLod %6 %339 %82 %73 Lod %73 -%341 = OpLoad %6 %55 -%342 = OpFAdd %6 %341 %340 -OpStore %55 %342 -%343 = OpAccessChain %129 %38 %78 -%344 = OpLoad %14 %343 -%345 = OpAccessChain %132 %44 %78 -%346 = OpLoad %18 %345 -%347 = OpSampledImage %135 %344 %346 -%348 = OpImageSampleDrefExplicitLod %6 %347 %82 %73 Lod %73 -%349 = OpLoad %6 %55 -%350 = OpFAdd %6 %349 %348 -OpStore %55 %350 -%351 = OpAccessChain %129 %38 %79 -%352 = OpLoad %14 %351 -%353 = OpAccessChain %132 %44 %79 -%354 = OpLoad %18 %353 -%355 = OpSampledImage %135 %352 %354 -%356 = OpImageSampleDrefExplicitLod %6 %355 %82 %73 Lod %73 -%357 = OpLoad %6 %55 -%358 = OpFAdd %6 %357 %356 -OpStore %55 %358 -%359 = OpAccessChain %84 %32 %71 -%360 = OpLoad %5 %359 -%361 = OpAccessChain %105 %42 %71 -%362 = OpLoad %18 %361 -%363 = OpSampledImage %108 %360 %362 -%364 = OpImageSampleExplicitLod %22 %363 %82 Grad %82 %82 -%365 = OpLoad %22 %58 -%366 = OpFAdd %22 %365 %364 -OpStore %58 %366 -%367 = OpAccessChain %84 %32 %78 -%368 = OpLoad %5 %367 -%369 = OpAccessChain %105 %42 %78 -%370 = OpLoad %18 %369 -%371 = OpSampledImage %108 %368 %370 -%372 = OpImageSampleExplicitLod %22 %371 %82 Grad %82 %82 -%373 = OpLoad %22 %58 -%374 = OpFAdd %22 %373 %372 -OpStore %58 %374 -%375 = OpAccessChain %84 %32 %79 -%376 = OpLoad %5 %375 -%377 = OpAccessChain %105 %42 %79 -%378 = OpLoad %18 %377 -%379 = OpSampledImage %108 %376 %378 -%380 = OpImageSampleExplicitLod %22 %379 %82 Grad %82 %82 -%381 = OpLoad %22 %58 -%382 = OpFAdd %22 %381 %380 -OpStore %58 %382 -%383 = OpAccessChain %84 %32 %71 -%384 = OpLoad %5 %383 -%385 = OpAccessChain %105 %42 %71 -%386 = OpLoad %18 %385 -%387 = OpSampledImage %108 %384 %386 -%388 = OpImageSampleExplicitLod %22 %387 %82 Lod %73 -%389 = OpLoad %22 %58 -%390 = OpFAdd %22 %389 %388 -OpStore %58 %390 -%391 = OpAccessChain %84 %32 %78 -%392 = OpLoad %5 %391 -%393 = OpAccessChain %105 %42 %78 -%394 = OpLoad %18 %393 -%395 = OpSampledImage %108 %392 %394 -%396 = OpImageSampleExplicitLod %22 %395 %82 Lod %73 -%397 = OpLoad %22 %58 -%398 = OpFAdd %22 %397 %396 -OpStore %58 %398 -%399 = OpAccessChain %84 %32 %79 -%400 = OpLoad %5 %399 -%401 = OpAccessChain %105 %42 %79 -%402 = OpLoad %18 %401 -%403 = OpSampledImage %108 %400 %402 -%404 = OpImageSampleExplicitLod %22 %403 %82 Lod %73 -%405 = OpLoad %22 %58 -%406 = OpFAdd %22 %405 %404 -OpStore %58 %406 -%408 = OpAccessChain %407 %40 %71 -%409 = OpLoad %16 %408 -%410 = OpLoad %22 %58 -%411 = OpImageQuerySize %25 %409 -%412 = OpULessThan %165 %83 %411 -%413 = OpAll %158 %412 -OpSelectionMerge %414 None -OpBranchConditional %413 %415 %414 -%415 = OpLabel -OpImageWrite %409 %83 %410 -OpBranch %414 -%414 = OpLabel -%416 = OpAccessChain %407 %40 %78 -%417 = OpLoad %16 %416 -%418 = OpLoad %22 %58 -%419 = OpImageQuerySize %25 %417 -%420 = OpULessThan %165 %83 %419 -%421 = OpAll %158 %420 -OpSelectionMerge %422 None -OpBranchConditional %421 %423 %422 -%423 = OpLabel -OpImageWrite %417 %83 %418 -OpBranch %422 -%422 = OpLabel -%424 = OpAccessChain %407 %40 %79 -%425 = OpLoad %16 %424 -%426 = OpLoad %22 %58 -%427 = OpImageQuerySize %25 %425 -%428 = OpULessThan %165 %83 %427 -%429 = OpAll %158 %428 -OpSelectionMerge %430 None -OpBranchConditional %429 %431 %430 -%431 = OpLabel -OpImageWrite %425 %83 %426 -OpBranch %430 -%430 = OpLabel -%432 = OpLoad %23 %52 -%433 = OpLoad %3 %49 -%434 = OpCompositeConstruct %23 %433 %433 -%435 = OpIAdd %23 %432 %434 -%436 = OpConvertUToF %24 %435 -%437 = OpLoad %22 %58 -%438 = OpCompositeExtract %6 %436 0 -%439 = OpCompositeExtract %6 %436 1 -%440 = OpCompositeExtract %6 %436 0 -%441 = OpCompositeExtract %6 %436 1 -%442 = OpCompositeConstruct %22 %438 %439 %440 %441 -%443 = OpFAdd %22 %437 %442 -%444 = OpLoad %6 %55 -%445 = OpCompositeConstruct %22 %444 %444 %444 %444 -%446 = OpFAdd %22 %443 %445 -OpStore %66 %446 +%251 = OpAccessChain %84 %32 %71 +%252 = OpLoad %5 %251 +%253 = OpAccessChain %102 %42 %71 +%254 = OpLoad %18 %253 +%255 = OpSampledImage %105 %252 %254 +%256 = OpImageSampleImplicitLod %22 %255 %82 +%257 = OpLoad %22 %58 +%258 = OpFAdd %22 %257 %256 +OpStore %58 %258 +%259 = OpAccessChain %84 %32 %78 +%260 = OpLoad %5 %259 +%261 = OpAccessChain %102 %42 %78 +%262 = OpLoad %18 %261 +%263 = OpSampledImage %105 %260 %262 +%264 = OpImageSampleImplicitLod %22 %263 %82 +%265 = OpLoad %22 %58 +%266 = OpFAdd %22 %265 %264 +OpStore %58 %266 +%267 = OpAccessChain %84 %32 %79 +%268 = OpLoad %5 %267 +%269 = OpAccessChain %102 %42 %79 +%270 = OpLoad %18 %269 +%271 = OpSampledImage %105 %268 %270 +%272 = OpImageSampleImplicitLod %22 %271 %82 +%273 = OpLoad %22 %58 +%274 = OpFAdd %22 %273 %272 +OpStore %58 %274 +%275 = OpAccessChain %84 %32 %71 +%276 = OpLoad %5 %275 +%277 = OpAccessChain %102 %42 %71 +%278 = OpLoad %18 %277 +%279 = OpSampledImage %105 %276 %278 +%280 = OpImageSampleImplicitLod %22 %279 %82 Bias %73 +%281 = OpLoad %22 %58 +%282 = OpFAdd %22 %281 %280 +OpStore %58 %282 +%283 = OpAccessChain %84 %32 %78 +%284 = OpLoad %5 %283 +%285 = OpAccessChain %102 %42 %78 +%286 = OpLoad %18 %285 +%287 = OpSampledImage %105 %284 %286 +%288 = OpImageSampleImplicitLod %22 %287 %82 Bias %73 +%289 = OpLoad %22 %58 +%290 = OpFAdd %22 %289 %288 +OpStore %58 %290 +%291 = OpAccessChain %84 %32 %79 +%292 = OpLoad %5 %291 +%293 = OpAccessChain %102 %42 %79 +%294 = OpLoad %18 %293 +%295 = OpSampledImage %105 %292 %294 +%296 = OpImageSampleImplicitLod %22 %295 %82 Bias %73 +%297 = OpLoad %22 %58 +%298 = OpFAdd %22 %297 %296 +OpStore %58 %298 +%299 = OpAccessChain %126 %38 %71 +%300 = OpLoad %14 %299 +%301 = OpAccessChain %129 %44 %71 +%302 = OpLoad %18 %301 +%303 = OpSampledImage %132 %300 %302 +%304 = OpImageSampleDrefImplicitLod %6 %303 %82 %73 +%305 = OpLoad %6 %55 +%306 = OpFAdd %6 %305 %304 +OpStore %55 %306 +%307 = OpAccessChain %126 %38 %78 +%308 = OpLoad %14 %307 +%309 = OpAccessChain %129 %44 %78 +%310 = OpLoad %18 %309 +%311 = OpSampledImage %132 %308 %310 +%312 = OpImageSampleDrefImplicitLod %6 %311 %82 %73 +%313 = OpLoad %6 %55 +%314 = OpFAdd %6 %313 %312 +OpStore %55 %314 +%315 = OpAccessChain %126 %38 %79 +%316 = OpLoad %14 %315 +%317 = OpAccessChain %129 %44 %79 +%318 = OpLoad %18 %317 +%319 = OpSampledImage %132 %316 %318 +%320 = OpImageSampleDrefImplicitLod %6 %319 %82 %73 +%321 = OpLoad %6 %55 +%322 = OpFAdd %6 %321 %320 +OpStore %55 %322 +%323 = OpAccessChain %126 %38 %71 +%324 = OpLoad %14 %323 +%325 = OpAccessChain %129 %44 %71 +%326 = OpLoad %18 %325 +%327 = OpSampledImage %132 %324 %326 +%328 = OpImageSampleDrefExplicitLod %6 %327 %82 %73 Lod %73 +%329 = OpLoad %6 %55 +%330 = OpFAdd %6 %329 %328 +OpStore %55 %330 +%331 = OpAccessChain %126 %38 %78 +%332 = OpLoad %14 %331 +%333 = OpAccessChain %129 %44 %78 +%334 = OpLoad %18 %333 +%335 = OpSampledImage %132 %332 %334 +%336 = OpImageSampleDrefExplicitLod %6 %335 %82 %73 Lod %73 +%337 = OpLoad %6 %55 +%338 = OpFAdd %6 %337 %336 +OpStore %55 %338 +%339 = OpAccessChain %126 %38 %79 +%340 = OpLoad %14 %339 +%341 = OpAccessChain %129 %44 %79 +%342 = OpLoad %18 %341 +%343 = OpSampledImage %132 %340 %342 +%344 = OpImageSampleDrefExplicitLod %6 %343 %82 %73 Lod %73 +%345 = OpLoad %6 %55 +%346 = OpFAdd %6 %345 %344 +OpStore %55 %346 +%347 = OpAccessChain %84 %32 %71 +%348 = OpLoad %5 %347 +%349 = OpAccessChain %102 %42 %71 +%350 = OpLoad %18 %349 +%351 = OpSampledImage %105 %348 %350 +%352 = OpImageSampleExplicitLod %22 %351 %82 Grad %82 %82 +%353 = OpLoad %22 %58 +%354 = OpFAdd %22 %353 %352 +OpStore %58 %354 +%355 = OpAccessChain %84 %32 %78 +%356 = OpLoad %5 %355 +%357 = OpAccessChain %102 %42 %78 +%358 = OpLoad %18 %357 +%359 = OpSampledImage %105 %356 %358 +%360 = OpImageSampleExplicitLod %22 %359 %82 Grad %82 %82 +%361 = OpLoad %22 %58 +%362 = OpFAdd %22 %361 %360 +OpStore %58 %362 +%363 = OpAccessChain %84 %32 %79 +%364 = OpLoad %5 %363 +%365 = OpAccessChain %102 %42 %79 +%366 = OpLoad %18 %365 +%367 = OpSampledImage %105 %364 %366 +%368 = OpImageSampleExplicitLod %22 %367 %82 Grad %82 %82 +%369 = OpLoad %22 %58 +%370 = OpFAdd %22 %369 %368 +OpStore %58 %370 +%371 = OpAccessChain %84 %32 %71 +%372 = OpLoad %5 %371 +%373 = OpAccessChain %102 %42 %71 +%374 = OpLoad %18 %373 +%375 = OpSampledImage %105 %372 %374 +%376 = OpImageSampleExplicitLod %22 %375 %82 Lod %73 +%377 = OpLoad %22 %58 +%378 = OpFAdd %22 %377 %376 +OpStore %58 %378 +%379 = OpAccessChain %84 %32 %78 +%380 = OpLoad %5 %379 +%381 = OpAccessChain %102 %42 %78 +%382 = OpLoad %18 %381 +%383 = OpSampledImage %105 %380 %382 +%384 = OpImageSampleExplicitLod %22 %383 %82 Lod %73 +%385 = OpLoad %22 %58 +%386 = OpFAdd %22 %385 %384 +OpStore %58 %386 +%387 = OpAccessChain %84 %32 %79 +%388 = OpLoad %5 %387 +%389 = OpAccessChain %102 %42 %79 +%390 = OpLoad %18 %389 +%391 = OpSampledImage %105 %388 %390 +%392 = OpImageSampleExplicitLod %22 %391 %82 Lod %73 +%393 = OpLoad %22 %58 +%394 = OpFAdd %22 %393 %392 +OpStore %58 %394 +%396 = OpAccessChain %395 %40 %71 +%397 = OpLoad %16 %396 +%398 = OpLoad %22 %58 +%399 = OpImageQuerySize %25 %397 +%400 = OpULessThan %162 %83 %399 +%401 = OpAll %155 %400 +OpSelectionMerge %402 None +OpBranchConditional %401 %403 %402 +%403 = OpLabel +OpImageWrite %397 %83 %398 +OpBranch %402 +%402 = OpLabel +%404 = OpAccessChain %395 %40 %78 +%405 = OpLoad %16 %404 +%406 = OpLoad %22 %58 +%407 = OpImageQuerySize %25 %405 +%408 = OpULessThan %162 %83 %407 +%409 = OpAll %155 %408 +OpSelectionMerge %410 None +OpBranchConditional %409 %411 %410 +%411 = OpLabel +OpImageWrite %405 %83 %406 +OpBranch %410 +%410 = OpLabel +%412 = OpAccessChain %395 %40 %79 +%413 = OpLoad %16 %412 +%414 = OpLoad %22 %58 +%415 = OpImageQuerySize %25 %413 +%416 = OpULessThan %162 %83 %415 +%417 = OpAll %155 %416 +OpSelectionMerge %418 None +OpBranchConditional %417 %419 %418 +%419 = OpLabel +OpImageWrite %413 %83 %414 +OpBranch %418 +%418 = OpLabel +%420 = OpLoad %23 %52 +%421 = OpLoad %3 %49 +%422 = OpCompositeConstruct %23 %421 %421 +%423 = OpIAdd %23 %420 %422 +%424 = OpConvertUToF %24 %423 +%425 = OpLoad %22 %58 +%426 = OpCompositeExtract %6 %424 0 +%427 = OpCompositeExtract %6 %424 1 +%428 = OpCompositeExtract %6 %424 0 +%429 = OpCompositeExtract %6 %424 1 +%430 = OpCompositeConstruct %22 %426 %427 %428 %429 +%431 = OpFAdd %22 %425 %430 +%432 = OpLoad %6 %55 +%433 = OpCompositeConstruct %22 %432 %432 %432 %432 +%434 = OpFAdd %22 %431 %433 +OpStore %66 %434 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index fc8261145..45eadbae7 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 546 +; Bound: 523 OpCapability Shader OpCapability Image1D OpCapability Sampled1D @@ -10,19 +10,19 @@ OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %82 "main" %79 -OpEntryPoint GLCompute %172 "depth_load" %170 -OpEntryPoint Vertex %194 "queries" %192 -OpEntryPoint Vertex %259 "levels_queries" %258 -OpEntryPoint Fragment %299 "texture_sample" %298 -OpEntryPoint Fragment %444 "texture_sample_comparison" %442 -OpEntryPoint Fragment %499 "gather" %498 -OpEntryPoint Fragment %534 "depth_no_comparison" %533 +OpEntryPoint GLCompute %171 "depth_load" %169 +OpEntryPoint Vertex %192 "queries" %190 +OpEntryPoint Vertex %244 "levels_queries" %243 +OpEntryPoint Fragment %276 "texture_sample" %275 +OpEntryPoint Fragment %421 "texture_sample_comparison" %419 +OpEntryPoint Fragment %476 "gather" %475 +OpEntryPoint Fragment %511 "depth_no_comparison" %510 OpExecutionMode %82 LocalSize 16 1 1 -OpExecutionMode %172 LocalSize 16 1 1 -OpExecutionMode %299 OriginUpperLeft -OpExecutionMode %444 OriginUpperLeft -OpExecutionMode %499 OriginUpperLeft -OpExecutionMode %534 OriginUpperLeft +OpExecutionMode %171 LocalSize 16 1 1 +OpExecutionMode %276 OriginUpperLeft +OpExecutionMode %421 OriginUpperLeft +OpExecutionMode %476 OriginUpperLeft +OpExecutionMode %511 OriginUpperLeft OpName %35 "image_mipmapped_src" OpName %37 "image_multisampled_src" OpName %39 "image_depth_multisampled_src" @@ -47,16 +47,16 @@ OpName %74 "image_2d_array_depth" OpName %76 "image_cube_depth" OpName %79 "local_id" OpName %82 "main" -OpName %170 "local_id" -OpName %172 "depth_load" -OpName %194 "queries" -OpName %259 "levels_queries" -OpName %294 "a" -OpName %299 "texture_sample" -OpName %438 "a" -OpName %444 "texture_sample_comparison" -OpName %499 "gather" -OpName %534 "depth_no_comparison" +OpName %169 "local_id" +OpName %171 "depth_load" +OpName %192 "queries" +OpName %244 "levels_queries" +OpName %271 "a" +OpName %276 "texture_sample" +OpName %415 "a" +OpName %421 "texture_sample_comparison" +OpName %476 "gather" +OpName %511 "depth_no_comparison" OpDecorate %35 DescriptorSet 0 OpDecorate %35 Binding 0 OpDecorate %37 DescriptorSet 0 @@ -105,13 +105,13 @@ OpDecorate %74 Binding 3 OpDecorate %76 DescriptorSet 1 OpDecorate %76 Binding 4 OpDecorate %79 BuiltIn LocalInvocationId -OpDecorate %170 BuiltIn LocalInvocationId -OpDecorate %192 BuiltIn Position -OpDecorate %258 BuiltIn Position -OpDecorate %298 Location 0 -OpDecorate %442 Location 0 -OpDecorate %498 Location 0 -OpDecorate %533 Location 0 +OpDecorate %169 BuiltIn LocalInvocationId +OpDecorate %190 BuiltIn Position +OpDecorate %243 BuiltIn Position +OpDecorate %275 Location 0 +OpDecorate %419 Location 0 +OpDecorate %475 Location 0 +OpDecorate %510 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpTypeImage %4 2D 0 0 0 1 Unknown @@ -193,38 +193,38 @@ OpDecorate %533 Location 0 %83 = OpTypeFunction %2 %90 = OpConstant %14 10 %91 = OpConstant %14 20 -%112 = OpTypeVector %14 3 -%170 = OpVariable %80 Input -%193 = OpTypePointer Output %25 -%192 = OpVariable %193 Output -%203 = OpConstant %4 0 -%258 = OpVariable %193 Output -%295 = OpTypePointer Function %25 -%296 = OpConstantNull %25 -%298 = OpVariable %193 Output -%305 = OpConstant %7 0.5 -%306 = OpConstant %7 2.3 -%307 = OpConstant %7 2.0 -%308 = OpConstant %14 0 -%313 = OpTypeSampledImage %17 -%318 = OpTypeSampledImage %18 -%339 = OpTypeSampledImage %20 -%400 = OpTypeSampledImage %22 -%439 = OpTypePointer Function %7 -%440 = OpConstantNull %7 -%443 = OpTypePointer Output %7 -%442 = OpVariable %443 Output -%452 = OpTypeSampledImage %29 -%457 = OpTypeSampledImage %30 -%470 = OpTypeSampledImage %31 -%477 = OpConstant %7 0.0 -%498 = OpVariable %193 Output -%510 = OpConstant %4 1 -%513 = OpConstant %4 3 -%518 = OpTypeSampledImage %3 -%521 = OpTypeVector %14 4 -%522 = OpTypeSampledImage %19 -%533 = OpVariable %193 Output +%111 = OpTypeVector %14 3 +%169 = OpVariable %80 Input +%191 = OpTypePointer Output %25 +%190 = OpVariable %191 Output +%201 = OpConstant %4 0 +%243 = OpVariable %191 Output +%272 = OpTypePointer Function %25 +%273 = OpConstantNull %25 +%275 = OpVariable %191 Output +%282 = OpConstant %7 0.5 +%283 = OpConstant %7 2.3 +%284 = OpConstant %7 2.0 +%285 = OpConstant %14 0 +%290 = OpTypeSampledImage %17 +%295 = OpTypeSampledImage %18 +%316 = OpTypeSampledImage %20 +%377 = OpTypeSampledImage %22 +%416 = OpTypePointer Function %7 +%417 = OpConstantNull %7 +%420 = OpTypePointer Output %7 +%419 = OpVariable %420 Output +%429 = OpTypeSampledImage %29 +%434 = OpTypeSampledImage %30 +%447 = OpTypeSampledImage %31 +%454 = OpConstant %7 0.0 +%475 = OpVariable %191 Output +%487 = OpConstant %4 1 +%490 = OpConstant %4 3 +%495 = OpTypeSampledImage %3 +%498 = OpTypeVector %14 4 +%499 = OpTypeSampledImage %19 +%510 = OpVariable %191 Output %82 = OpFunction %2 None %83 %78 = OpLabel %81 = OpLoad %12 %79 @@ -236,485 +236,462 @@ OpDecorate %533 Location 0 %89 = OpLoad %10 %49 OpBranch %92 %92 = OpLabel -%93 = OpImageQuerySize %13 %86 -%94 = OpBitcast %15 %93 -%95 = OpVectorShuffle %15 %81 %81 0 1 -%96 = OpIMul %15 %94 %95 -%97 = OpBitcast %13 %96 -%98 = OpCompositeConstruct %13 %90 %91 -%99 = OpSRem %13 %97 %98 -%100 = OpCompositeExtract %4 %81 2 -%101 = OpBitcast %14 %100 -%102 = OpImageFetch %16 %84 %99 Lod %101 -%103 = OpCompositeExtract %4 %81 2 -%104 = OpBitcast %14 %103 -%105 = OpImageFetch %16 %85 %99 Sample %104 -%106 = OpImageRead %16 %86 %99 +%93 = OpImageQuerySize %15 %86 +%94 = OpVectorShuffle %15 %81 %81 0 1 +%95 = OpIMul %15 %93 %94 +%96 = OpBitcast %13 %95 +%97 = OpCompositeConstruct %13 %90 %91 +%98 = OpSRem %13 %96 %97 +%99 = OpCompositeExtract %4 %81 2 +%100 = OpBitcast %14 %99 +%101 = OpImageFetch %16 %84 %98 Lod %100 +%102 = OpCompositeExtract %4 %81 2 +%103 = OpBitcast %14 %102 +%104 = OpImageFetch %16 %85 %98 Sample %103 +%105 = OpImageRead %16 %86 %98 +%106 = OpCompositeExtract %4 %81 2 %107 = OpCompositeExtract %4 %81 2 -%108 = OpCompositeExtract %4 %81 2 -%109 = OpBitcast %14 %108 -%110 = OpIAdd %14 %109 %33 -%111 = OpBitcast %14 %107 -%113 = OpCompositeConstruct %112 %99 %111 -%114 = OpImageFetch %16 %87 %113 Lod %110 -%115 = OpCompositeExtract %4 %81 2 -%116 = OpBitcast %14 %115 -%117 = OpCompositeExtract %4 %81 2 -%118 = OpBitcast %14 %117 -%119 = OpIAdd %14 %118 %33 -%120 = OpCompositeConstruct %112 %99 %116 -%121 = OpImageFetch %16 %87 %120 Lod %119 -%122 = OpCompositeExtract %4 %81 0 -%123 = OpBitcast %14 %122 -%124 = OpCompositeExtract %4 %81 2 -%125 = OpBitcast %14 %124 -%126 = OpImageFetch %16 %88 %123 Lod %125 -%127 = OpBitcast %15 %99 -%128 = OpCompositeExtract %4 %81 2 -%129 = OpBitcast %14 %128 -%130 = OpImageFetch %16 %84 %127 Lod %129 -%131 = OpBitcast %15 %99 -%132 = OpCompositeExtract %4 %81 2 -%133 = OpBitcast %14 %132 -%134 = OpImageFetch %16 %85 %131 Sample %133 -%135 = OpBitcast %15 %99 -%136 = OpImageRead %16 %86 %135 -%137 = OpBitcast %15 %99 +%108 = OpBitcast %14 %107 +%109 = OpIAdd %14 %108 %33 +%110 = OpBitcast %14 %106 +%112 = OpCompositeConstruct %111 %98 %110 +%113 = OpImageFetch %16 %87 %112 Lod %109 +%114 = OpCompositeExtract %4 %81 2 +%115 = OpBitcast %14 %114 +%116 = OpCompositeExtract %4 %81 2 +%117 = OpBitcast %14 %116 +%118 = OpIAdd %14 %117 %33 +%119 = OpCompositeConstruct %111 %98 %115 +%120 = OpImageFetch %16 %87 %119 Lod %118 +%121 = OpCompositeExtract %4 %81 0 +%122 = OpBitcast %14 %121 +%123 = OpCompositeExtract %4 %81 2 +%124 = OpBitcast %14 %123 +%125 = OpImageFetch %16 %88 %122 Lod %124 +%126 = OpBitcast %15 %98 +%127 = OpCompositeExtract %4 %81 2 +%128 = OpBitcast %14 %127 +%129 = OpImageFetch %16 %84 %126 Lod %128 +%130 = OpBitcast %15 %98 +%131 = OpCompositeExtract %4 %81 2 +%132 = OpBitcast %14 %131 +%133 = OpImageFetch %16 %85 %130 Sample %132 +%134 = OpBitcast %15 %98 +%135 = OpImageRead %16 %86 %134 +%136 = OpBitcast %15 %98 +%137 = OpCompositeExtract %4 %81 2 %138 = OpCompositeExtract %4 %81 2 -%139 = OpCompositeExtract %4 %81 2 -%140 = OpBitcast %14 %139 -%141 = OpIAdd %14 %140 %33 -%142 = OpCompositeConstruct %12 %137 %138 -%143 = OpImageFetch %16 %87 %142 Lod %141 -%144 = OpBitcast %15 %99 -%145 = OpCompositeExtract %4 %81 2 -%146 = OpBitcast %14 %145 -%147 = OpCompositeExtract %4 %81 2 -%148 = OpBitcast %14 %147 -%149 = OpIAdd %14 %148 %33 -%150 = OpBitcast %4 %146 -%151 = OpCompositeConstruct %12 %144 %150 -%152 = OpImageFetch %16 %87 %151 Lod %149 -%153 = OpCompositeExtract %4 %81 0 -%155 = OpCompositeExtract %4 %81 2 -%156 = OpBitcast %14 %155 -%157 = OpImageFetch %16 %88 %153 Lod %156 -%158 = OpCompositeExtract %14 %99 0 -%159 = OpIAdd %16 %102 %105 -%160 = OpIAdd %16 %159 %106 -%161 = OpIAdd %16 %160 %114 -%162 = OpIAdd %16 %161 %121 -OpImageWrite %89 %158 %162 -%163 = OpCompositeExtract %14 %99 0 -%164 = OpBitcast %4 %163 -%165 = OpIAdd %16 %130 %134 -%166 = OpIAdd %16 %165 %136 -%167 = OpIAdd %16 %166 %143 -%168 = OpIAdd %16 %167 %152 -OpImageWrite %89 %164 %168 +%139 = OpBitcast %14 %138 +%140 = OpIAdd %14 %139 %33 +%141 = OpCompositeConstruct %12 %136 %137 +%142 = OpImageFetch %16 %87 %141 Lod %140 +%143 = OpBitcast %15 %98 +%144 = OpCompositeExtract %4 %81 2 +%145 = OpBitcast %14 %144 +%146 = OpCompositeExtract %4 %81 2 +%147 = OpBitcast %14 %146 +%148 = OpIAdd %14 %147 %33 +%149 = OpBitcast %4 %145 +%150 = OpCompositeConstruct %12 %143 %149 +%151 = OpImageFetch %16 %87 %150 Lod %148 +%152 = OpCompositeExtract %4 %81 0 +%154 = OpCompositeExtract %4 %81 2 +%155 = OpBitcast %14 %154 +%156 = OpImageFetch %16 %88 %152 Lod %155 +%157 = OpCompositeExtract %14 %98 0 +%158 = OpIAdd %16 %101 %104 +%159 = OpIAdd %16 %158 %105 +%160 = OpIAdd %16 %159 %113 +%161 = OpIAdd %16 %160 %120 +OpImageWrite %89 %157 %161 +%162 = OpCompositeExtract %14 %98 0 +%163 = OpBitcast %4 %162 +%164 = OpIAdd %16 %129 %133 +%165 = OpIAdd %16 %164 %135 +%166 = OpIAdd %16 %165 %142 +%167 = OpIAdd %16 %166 %151 +OpImageWrite %89 %163 %167 OpReturn OpFunctionEnd -%172 = OpFunction %2 None %83 -%169 = OpLabel -%171 = OpLoad %12 %170 -%173 = OpLoad %6 %39 -%174 = OpLoad %8 %41 -%175 = OpLoad %10 %49 -OpBranch %176 -%176 = OpLabel -%177 = OpImageQuerySize %13 %174 -%178 = OpBitcast %15 %177 -%179 = OpVectorShuffle %15 %171 %171 0 1 -%180 = OpIMul %15 %178 %179 -%181 = OpBitcast %13 %180 -%182 = OpCompositeConstruct %13 %90 %91 -%183 = OpSRem %13 %181 %182 -%184 = OpCompositeExtract %4 %171 2 -%185 = OpBitcast %14 %184 -%186 = OpImageFetch %25 %173 %183 Sample %185 -%187 = OpCompositeExtract %7 %186 0 -%188 = OpCompositeExtract %14 %183 0 -%189 = OpConvertFToU %4 %187 -%190 = OpCompositeConstruct %16 %189 %189 %189 %189 -OpImageWrite %175 %188 %190 +%171 = OpFunction %2 None %83 +%168 = OpLabel +%170 = OpLoad %12 %169 +%172 = OpLoad %6 %39 +%173 = OpLoad %8 %41 +%174 = OpLoad %10 %49 +OpBranch %175 +%175 = OpLabel +%176 = OpImageQuerySize %15 %173 +%177 = OpVectorShuffle %15 %170 %170 0 1 +%178 = OpIMul %15 %176 %177 +%179 = OpBitcast %13 %178 +%180 = OpCompositeConstruct %13 %90 %91 +%181 = OpSRem %13 %179 %180 +%182 = OpCompositeExtract %4 %170 2 +%183 = OpBitcast %14 %182 +%184 = OpImageFetch %25 %172 %181 Sample %183 +%185 = OpCompositeExtract %7 %184 0 +%186 = OpCompositeExtract %14 %181 0 +%187 = OpConvertFToU %4 %185 +%188 = OpCompositeConstruct %16 %187 %187 %187 %187 +OpImageWrite %174 %186 %188 OpReturn OpFunctionEnd -%194 = OpFunction %2 None %83 -%191 = OpLabel -%195 = OpLoad %17 %51 -%196 = OpLoad %18 %53 -%197 = OpLoad %20 %58 -%198 = OpLoad %21 %60 -%199 = OpLoad %22 %62 -%200 = OpLoad %23 %64 -%201 = OpLoad %24 %66 -OpBranch %202 -%202 = OpLabel -%204 = OpImageQuerySizeLod %14 %195 %203 -%205 = OpBitcast %4 %204 -%206 = OpBitcast %14 %205 -%207 = OpImageQuerySizeLod %14 %195 %206 -%208 = OpBitcast %4 %207 -%209 = OpImageQuerySizeLod %13 %196 %203 -%210 = OpBitcast %15 %209 -%211 = OpImageQuerySizeLod %13 %196 %33 -%212 = OpBitcast %15 %211 -%213 = OpImageQuerySizeLod %112 %197 %203 -%214 = OpBitcast %12 %213 -%215 = OpVectorShuffle %15 %214 %214 0 1 -%216 = OpImageQuerySizeLod %112 %197 %33 -%217 = OpBitcast %12 %216 -%218 = OpVectorShuffle %15 %217 %217 0 1 -%219 = OpImageQuerySizeLod %13 %198 %203 -%220 = OpBitcast %15 %219 -%221 = OpImageQuerySizeLod %13 %198 %33 -%222 = OpBitcast %15 %221 -%223 = OpImageQuerySizeLod %112 %199 %203 -%224 = OpBitcast %12 %223 -%225 = OpVectorShuffle %15 %224 %224 0 0 -%226 = OpImageQuerySizeLod %112 %199 %33 -%227 = OpBitcast %12 %226 -%228 = OpVectorShuffle %15 %227 %227 0 0 -%229 = OpImageQuerySizeLod %112 %200 %203 -%230 = OpBitcast %12 %229 -%231 = OpImageQuerySizeLod %112 %200 %33 -%232 = OpBitcast %12 %231 -%233 = OpImageQuerySize %13 %201 -%234 = OpBitcast %15 %233 -%235 = OpCompositeExtract %4 %210 1 -%236 = OpIAdd %4 %205 %235 -%237 = OpCompositeExtract %4 %212 1 -%238 = OpIAdd %4 %236 %237 -%239 = OpCompositeExtract %4 %215 1 -%240 = OpIAdd %4 %238 %239 -%241 = OpCompositeExtract %4 %218 1 -%242 = OpIAdd %4 %240 %241 -%243 = OpCompositeExtract %4 %220 1 -%244 = OpIAdd %4 %242 %243 -%245 = OpCompositeExtract %4 %222 1 -%246 = OpIAdd %4 %244 %245 -%247 = OpCompositeExtract %4 %225 1 -%248 = OpIAdd %4 %246 %247 -%249 = OpCompositeExtract %4 %228 1 -%250 = OpIAdd %4 %248 %249 -%251 = OpCompositeExtract %4 %230 2 -%252 = OpIAdd %4 %250 %251 -%253 = OpCompositeExtract %4 %232 2 -%254 = OpIAdd %4 %252 %253 -%255 = OpConvertUToF %7 %254 -%256 = OpCompositeConstruct %25 %255 %255 %255 %255 -OpStore %192 %256 +%192 = OpFunction %2 None %83 +%189 = OpLabel +%193 = OpLoad %17 %51 +%194 = OpLoad %18 %53 +%195 = OpLoad %20 %58 +%196 = OpLoad %21 %60 +%197 = OpLoad %22 %62 +%198 = OpLoad %23 %64 +%199 = OpLoad %24 %66 +OpBranch %200 +%200 = OpLabel +%202 = OpImageQuerySizeLod %4 %193 %201 +%203 = OpBitcast %14 %202 +%204 = OpImageQuerySizeLod %4 %193 %203 +%205 = OpImageQuerySizeLod %15 %194 %201 +%206 = OpImageQuerySizeLod %15 %194 %33 +%207 = OpImageQuerySizeLod %12 %195 %201 +%208 = OpVectorShuffle %15 %207 %207 0 1 +%209 = OpImageQuerySizeLod %12 %195 %33 +%210 = OpVectorShuffle %15 %209 %209 0 1 +%211 = OpImageQuerySizeLod %15 %196 %201 +%212 = OpImageQuerySizeLod %15 %196 %33 +%213 = OpImageQuerySizeLod %12 %197 %201 +%214 = OpVectorShuffle %15 %213 %213 0 0 +%215 = OpImageQuerySizeLod %12 %197 %33 +%216 = OpVectorShuffle %15 %215 %215 0 0 +%217 = OpImageQuerySizeLod %12 %198 %201 +%218 = OpImageQuerySizeLod %12 %198 %33 +%219 = OpImageQuerySize %15 %199 +%220 = OpCompositeExtract %4 %205 1 +%221 = OpIAdd %4 %202 %220 +%222 = OpCompositeExtract %4 %206 1 +%223 = OpIAdd %4 %221 %222 +%224 = OpCompositeExtract %4 %208 1 +%225 = OpIAdd %4 %223 %224 +%226 = OpCompositeExtract %4 %210 1 +%227 = OpIAdd %4 %225 %226 +%228 = OpCompositeExtract %4 %211 1 +%229 = OpIAdd %4 %227 %228 +%230 = OpCompositeExtract %4 %212 1 +%231 = OpIAdd %4 %229 %230 +%232 = OpCompositeExtract %4 %214 1 +%233 = OpIAdd %4 %231 %232 +%234 = OpCompositeExtract %4 %216 1 +%235 = OpIAdd %4 %233 %234 +%236 = OpCompositeExtract %4 %217 2 +%237 = OpIAdd %4 %235 %236 +%238 = OpCompositeExtract %4 %218 2 +%239 = OpIAdd %4 %237 %238 +%240 = OpConvertUToF %7 %239 +%241 = OpCompositeConstruct %25 %240 %240 %240 %240 +OpStore %190 %241 OpReturn OpFunctionEnd -%259 = OpFunction %2 None %83 -%257 = OpLabel -%260 = OpLoad %18 %53 -%261 = OpLoad %20 %58 -%262 = OpLoad %21 %60 -%263 = OpLoad %22 %62 -%264 = OpLoad %23 %64 -%265 = OpLoad %24 %66 -OpBranch %266 -%266 = OpLabel -%267 = OpImageQueryLevels %14 %260 -%268 = OpBitcast %4 %267 -%269 = OpImageQueryLevels %14 %261 -%270 = OpBitcast %4 %269 -%271 = OpImageQuerySizeLod %112 %261 %203 -%272 = OpCompositeExtract %14 %271 2 -%273 = OpBitcast %4 %272 -%274 = OpImageQueryLevels %14 %262 -%275 = OpBitcast %4 %274 -%276 = OpImageQueryLevels %14 %263 -%277 = OpBitcast %4 %276 -%278 = OpImageQuerySizeLod %112 %263 %203 -%279 = OpCompositeExtract %14 %278 2 -%280 = OpBitcast %4 %279 -%281 = OpImageQueryLevels %14 %264 -%282 = OpBitcast %4 %281 -%283 = OpImageQuerySamples %14 %265 -%284 = OpBitcast %4 %283 -%285 = OpIAdd %4 %273 %280 -%286 = OpIAdd %4 %285 %284 -%287 = OpIAdd %4 %286 %268 -%288 = OpIAdd %4 %287 %270 -%289 = OpIAdd %4 %288 %282 -%290 = OpIAdd %4 %289 %275 -%291 = OpIAdd %4 %290 %277 -%292 = OpConvertUToF %7 %291 -%293 = OpCompositeConstruct %25 %292 %292 %292 %292 -OpStore %258 %293 +%244 = OpFunction %2 None %83 +%242 = OpLabel +%245 = OpLoad %18 %53 +%246 = OpLoad %20 %58 +%247 = OpLoad %21 %60 +%248 = OpLoad %22 %62 +%249 = OpLoad %23 %64 +%250 = OpLoad %24 %66 +OpBranch %251 +%251 = OpLabel +%252 = OpImageQueryLevels %4 %245 +%253 = OpImageQueryLevels %4 %246 +%254 = OpImageQuerySizeLod %12 %246 %201 +%255 = OpCompositeExtract %4 %254 2 +%256 = OpImageQueryLevels %4 %247 +%257 = OpImageQueryLevels %4 %248 +%258 = OpImageQuerySizeLod %12 %248 %201 +%259 = OpCompositeExtract %4 %258 2 +%260 = OpImageQueryLevels %4 %249 +%261 = OpImageQuerySamples %4 %250 +%262 = OpIAdd %4 %255 %259 +%263 = OpIAdd %4 %262 %261 +%264 = OpIAdd %4 %263 %252 +%265 = OpIAdd %4 %264 %253 +%266 = OpIAdd %4 %265 %260 +%267 = OpIAdd %4 %266 %256 +%268 = OpIAdd %4 %267 %257 +%269 = OpConvertUToF %7 %268 +%270 = OpCompositeConstruct %25 %269 %269 %269 %269 +OpStore %243 %270 OpReturn OpFunctionEnd -%299 = OpFunction %2 None %83 -%297 = OpLabel -%294 = OpVariable %295 Function %296 -%300 = OpLoad %17 %51 -%301 = OpLoad %18 %53 -%302 = OpLoad %20 %58 -%303 = OpLoad %22 %62 -%304 = OpLoad %26 %68 -OpBranch %309 -%309 = OpLabel -%310 = OpCompositeConstruct %27 %305 %305 -%311 = OpCompositeConstruct %28 %305 %305 %305 -%312 = OpCompositeExtract %7 %310 0 -%314 = OpSampledImage %313 %300 %304 -%315 = OpImageSampleImplicitLod %25 %314 %312 -%316 = OpLoad %25 %294 -%317 = OpFAdd %25 %316 %315 -OpStore %294 %317 -%319 = OpSampledImage %318 %301 %304 -%320 = OpImageSampleImplicitLod %25 %319 %310 -%321 = OpLoad %25 %294 +%276 = OpFunction %2 None %83 +%274 = OpLabel +%271 = OpVariable %272 Function %273 +%277 = OpLoad %17 %51 +%278 = OpLoad %18 %53 +%279 = OpLoad %20 %58 +%280 = OpLoad %22 %62 +%281 = OpLoad %26 %68 +OpBranch %286 +%286 = OpLabel +%287 = OpCompositeConstruct %27 %282 %282 +%288 = OpCompositeConstruct %28 %282 %282 %282 +%289 = OpCompositeExtract %7 %287 0 +%291 = OpSampledImage %290 %277 %281 +%292 = OpImageSampleImplicitLod %25 %291 %289 +%293 = OpLoad %25 %271 +%294 = OpFAdd %25 %293 %292 +OpStore %271 %294 +%296 = OpSampledImage %295 %278 %281 +%297 = OpImageSampleImplicitLod %25 %296 %287 +%298 = OpLoad %25 %271 +%299 = OpFAdd %25 %298 %297 +OpStore %271 %299 +%300 = OpSampledImage %295 %278 %281 +%301 = OpImageSampleImplicitLod %25 %300 %287 ConstOffset %34 +%302 = OpLoad %25 %271 +%303 = OpFAdd %25 %302 %301 +OpStore %271 %303 +%304 = OpSampledImage %295 %278 %281 +%305 = OpImageSampleExplicitLod %25 %304 %287 Lod %283 +%306 = OpLoad %25 %271 +%307 = OpFAdd %25 %306 %305 +OpStore %271 %307 +%308 = OpSampledImage %295 %278 %281 +%309 = OpImageSampleExplicitLod %25 %308 %287 Lod|ConstOffset %283 %34 +%310 = OpLoad %25 %271 +%311 = OpFAdd %25 %310 %309 +OpStore %271 %311 +%312 = OpSampledImage %295 %278 %281 +%313 = OpImageSampleImplicitLod %25 %312 %287 Bias|ConstOffset %284 %34 +%314 = OpLoad %25 %271 +%315 = OpFAdd %25 %314 %313 +OpStore %271 %315 +%317 = OpConvertUToF %7 %201 +%318 = OpCompositeConstruct %28 %287 %317 +%319 = OpSampledImage %316 %279 %281 +%320 = OpImageSampleImplicitLod %25 %319 %318 +%321 = OpLoad %25 %271 %322 = OpFAdd %25 %321 %320 -OpStore %294 %322 -%323 = OpSampledImage %318 %301 %304 -%324 = OpImageSampleImplicitLod %25 %323 %310 ConstOffset %34 -%325 = OpLoad %25 %294 -%326 = OpFAdd %25 %325 %324 -OpStore %294 %326 -%327 = OpSampledImage %318 %301 %304 -%328 = OpImageSampleExplicitLod %25 %327 %310 Lod %306 -%329 = OpLoad %25 %294 -%330 = OpFAdd %25 %329 %328 -OpStore %294 %330 -%331 = OpSampledImage %318 %301 %304 -%332 = OpImageSampleExplicitLod %25 %331 %310 Lod|ConstOffset %306 %34 -%333 = OpLoad %25 %294 +OpStore %271 %322 +%323 = OpConvertUToF %7 %201 +%324 = OpCompositeConstruct %28 %287 %323 +%325 = OpSampledImage %316 %279 %281 +%326 = OpImageSampleImplicitLod %25 %325 %324 ConstOffset %34 +%327 = OpLoad %25 %271 +%328 = OpFAdd %25 %327 %326 +OpStore %271 %328 +%329 = OpConvertUToF %7 %201 +%330 = OpCompositeConstruct %28 %287 %329 +%331 = OpSampledImage %316 %279 %281 +%332 = OpImageSampleExplicitLod %25 %331 %330 Lod %283 +%333 = OpLoad %25 %271 %334 = OpFAdd %25 %333 %332 -OpStore %294 %334 -%335 = OpSampledImage %318 %301 %304 -%336 = OpImageSampleImplicitLod %25 %335 %310 Bias|ConstOffset %307 %34 -%337 = OpLoad %25 %294 -%338 = OpFAdd %25 %337 %336 -OpStore %294 %338 -%340 = OpConvertUToF %7 %203 -%341 = OpCompositeConstruct %28 %310 %340 -%342 = OpSampledImage %339 %302 %304 -%343 = OpImageSampleImplicitLod %25 %342 %341 -%344 = OpLoad %25 %294 -%345 = OpFAdd %25 %344 %343 -OpStore %294 %345 -%346 = OpConvertUToF %7 %203 -%347 = OpCompositeConstruct %28 %310 %346 -%348 = OpSampledImage %339 %302 %304 -%349 = OpImageSampleImplicitLod %25 %348 %347 ConstOffset %34 -%350 = OpLoad %25 %294 -%351 = OpFAdd %25 %350 %349 -OpStore %294 %351 -%352 = OpConvertUToF %7 %203 -%353 = OpCompositeConstruct %28 %310 %352 -%354 = OpSampledImage %339 %302 %304 -%355 = OpImageSampleExplicitLod %25 %354 %353 Lod %306 -%356 = OpLoad %25 %294 -%357 = OpFAdd %25 %356 %355 -OpStore %294 %357 -%358 = OpConvertUToF %7 %203 -%359 = OpCompositeConstruct %28 %310 %358 -%360 = OpSampledImage %339 %302 %304 -%361 = OpImageSampleExplicitLod %25 %360 %359 Lod|ConstOffset %306 %34 -%362 = OpLoad %25 %294 -%363 = OpFAdd %25 %362 %361 -OpStore %294 %363 -%364 = OpConvertUToF %7 %203 -%365 = OpCompositeConstruct %28 %310 %364 -%366 = OpSampledImage %339 %302 %304 -%367 = OpImageSampleImplicitLod %25 %366 %365 Bias|ConstOffset %307 %34 -%368 = OpLoad %25 %294 -%369 = OpFAdd %25 %368 %367 -OpStore %294 %369 -%370 = OpConvertSToF %7 %308 -%371 = OpCompositeConstruct %28 %310 %370 -%372 = OpSampledImage %339 %302 %304 -%373 = OpImageSampleImplicitLod %25 %372 %371 -%374 = OpLoad %25 %294 -%375 = OpFAdd %25 %374 %373 -OpStore %294 %375 -%376 = OpConvertSToF %7 %308 -%377 = OpCompositeConstruct %28 %310 %376 -%378 = OpSampledImage %339 %302 %304 -%379 = OpImageSampleImplicitLod %25 %378 %377 ConstOffset %34 -%380 = OpLoad %25 %294 -%381 = OpFAdd %25 %380 %379 -OpStore %294 %381 -%382 = OpConvertSToF %7 %308 -%383 = OpCompositeConstruct %28 %310 %382 -%384 = OpSampledImage %339 %302 %304 -%385 = OpImageSampleExplicitLod %25 %384 %383 Lod %306 -%386 = OpLoad %25 %294 -%387 = OpFAdd %25 %386 %385 -OpStore %294 %387 -%388 = OpConvertSToF %7 %308 -%389 = OpCompositeConstruct %28 %310 %388 -%390 = OpSampledImage %339 %302 %304 -%391 = OpImageSampleExplicitLod %25 %390 %389 Lod|ConstOffset %306 %34 -%392 = OpLoad %25 %294 -%393 = OpFAdd %25 %392 %391 -OpStore %294 %393 -%394 = OpConvertSToF %7 %308 -%395 = OpCompositeConstruct %28 %310 %394 -%396 = OpSampledImage %339 %302 %304 -%397 = OpImageSampleImplicitLod %25 %396 %395 Bias|ConstOffset %307 %34 -%398 = OpLoad %25 %294 -%399 = OpFAdd %25 %398 %397 -OpStore %294 %399 -%401 = OpConvertUToF %7 %203 -%402 = OpCompositeConstruct %25 %311 %401 -%403 = OpSampledImage %400 %303 %304 -%404 = OpImageSampleImplicitLod %25 %403 %402 -%405 = OpLoad %25 %294 -%406 = OpFAdd %25 %405 %404 -OpStore %294 %406 -%407 = OpConvertUToF %7 %203 -%408 = OpCompositeConstruct %25 %311 %407 -%409 = OpSampledImage %400 %303 %304 -%410 = OpImageSampleExplicitLod %25 %409 %408 Lod %306 -%411 = OpLoad %25 %294 -%412 = OpFAdd %25 %411 %410 -OpStore %294 %412 -%413 = OpConvertUToF %7 %203 -%414 = OpCompositeConstruct %25 %311 %413 -%415 = OpSampledImage %400 %303 %304 -%416 = OpImageSampleImplicitLod %25 %415 %414 Bias %307 -%417 = OpLoad %25 %294 -%418 = OpFAdd %25 %417 %416 -OpStore %294 %418 -%419 = OpConvertSToF %7 %308 -%420 = OpCompositeConstruct %25 %311 %419 -%421 = OpSampledImage %400 %303 %304 -%422 = OpImageSampleImplicitLod %25 %421 %420 -%423 = OpLoad %25 %294 -%424 = OpFAdd %25 %423 %422 -OpStore %294 %424 -%425 = OpConvertSToF %7 %308 -%426 = OpCompositeConstruct %25 %311 %425 -%427 = OpSampledImage %400 %303 %304 -%428 = OpImageSampleExplicitLod %25 %427 %426 Lod %306 -%429 = OpLoad %25 %294 -%430 = OpFAdd %25 %429 %428 -OpStore %294 %430 -%431 = OpConvertSToF %7 %308 -%432 = OpCompositeConstruct %25 %311 %431 -%433 = OpSampledImage %400 %303 %304 -%434 = OpImageSampleImplicitLod %25 %433 %432 Bias %307 -%435 = OpLoad %25 %294 -%436 = OpFAdd %25 %435 %434 -OpStore %294 %436 -%437 = OpLoad %25 %294 -OpStore %298 %437 +OpStore %271 %334 +%335 = OpConvertUToF %7 %201 +%336 = OpCompositeConstruct %28 %287 %335 +%337 = OpSampledImage %316 %279 %281 +%338 = OpImageSampleExplicitLod %25 %337 %336 Lod|ConstOffset %283 %34 +%339 = OpLoad %25 %271 +%340 = OpFAdd %25 %339 %338 +OpStore %271 %340 +%341 = OpConvertUToF %7 %201 +%342 = OpCompositeConstruct %28 %287 %341 +%343 = OpSampledImage %316 %279 %281 +%344 = OpImageSampleImplicitLod %25 %343 %342 Bias|ConstOffset %284 %34 +%345 = OpLoad %25 %271 +%346 = OpFAdd %25 %345 %344 +OpStore %271 %346 +%347 = OpConvertSToF %7 %285 +%348 = OpCompositeConstruct %28 %287 %347 +%349 = OpSampledImage %316 %279 %281 +%350 = OpImageSampleImplicitLod %25 %349 %348 +%351 = OpLoad %25 %271 +%352 = OpFAdd %25 %351 %350 +OpStore %271 %352 +%353 = OpConvertSToF %7 %285 +%354 = OpCompositeConstruct %28 %287 %353 +%355 = OpSampledImage %316 %279 %281 +%356 = OpImageSampleImplicitLod %25 %355 %354 ConstOffset %34 +%357 = OpLoad %25 %271 +%358 = OpFAdd %25 %357 %356 +OpStore %271 %358 +%359 = OpConvertSToF %7 %285 +%360 = OpCompositeConstruct %28 %287 %359 +%361 = OpSampledImage %316 %279 %281 +%362 = OpImageSampleExplicitLod %25 %361 %360 Lod %283 +%363 = OpLoad %25 %271 +%364 = OpFAdd %25 %363 %362 +OpStore %271 %364 +%365 = OpConvertSToF %7 %285 +%366 = OpCompositeConstruct %28 %287 %365 +%367 = OpSampledImage %316 %279 %281 +%368 = OpImageSampleExplicitLod %25 %367 %366 Lod|ConstOffset %283 %34 +%369 = OpLoad %25 %271 +%370 = OpFAdd %25 %369 %368 +OpStore %271 %370 +%371 = OpConvertSToF %7 %285 +%372 = OpCompositeConstruct %28 %287 %371 +%373 = OpSampledImage %316 %279 %281 +%374 = OpImageSampleImplicitLod %25 %373 %372 Bias|ConstOffset %284 %34 +%375 = OpLoad %25 %271 +%376 = OpFAdd %25 %375 %374 +OpStore %271 %376 +%378 = OpConvertUToF %7 %201 +%379 = OpCompositeConstruct %25 %288 %378 +%380 = OpSampledImage %377 %280 %281 +%381 = OpImageSampleImplicitLod %25 %380 %379 +%382 = OpLoad %25 %271 +%383 = OpFAdd %25 %382 %381 +OpStore %271 %383 +%384 = OpConvertUToF %7 %201 +%385 = OpCompositeConstruct %25 %288 %384 +%386 = OpSampledImage %377 %280 %281 +%387 = OpImageSampleExplicitLod %25 %386 %385 Lod %283 +%388 = OpLoad %25 %271 +%389 = OpFAdd %25 %388 %387 +OpStore %271 %389 +%390 = OpConvertUToF %7 %201 +%391 = OpCompositeConstruct %25 %288 %390 +%392 = OpSampledImage %377 %280 %281 +%393 = OpImageSampleImplicitLod %25 %392 %391 Bias %284 +%394 = OpLoad %25 %271 +%395 = OpFAdd %25 %394 %393 +OpStore %271 %395 +%396 = OpConvertSToF %7 %285 +%397 = OpCompositeConstruct %25 %288 %396 +%398 = OpSampledImage %377 %280 %281 +%399 = OpImageSampleImplicitLod %25 %398 %397 +%400 = OpLoad %25 %271 +%401 = OpFAdd %25 %400 %399 +OpStore %271 %401 +%402 = OpConvertSToF %7 %285 +%403 = OpCompositeConstruct %25 %288 %402 +%404 = OpSampledImage %377 %280 %281 +%405 = OpImageSampleExplicitLod %25 %404 %403 Lod %283 +%406 = OpLoad %25 %271 +%407 = OpFAdd %25 %406 %405 +OpStore %271 %407 +%408 = OpConvertSToF %7 %285 +%409 = OpCompositeConstruct %25 %288 %408 +%410 = OpSampledImage %377 %280 %281 +%411 = OpImageSampleImplicitLod %25 %410 %409 Bias %284 +%412 = OpLoad %25 %271 +%413 = OpFAdd %25 %412 %411 +OpStore %271 %413 +%414 = OpLoad %25 %271 +OpStore %275 %414 OpReturn OpFunctionEnd -%444 = OpFunction %2 None %83 -%441 = OpLabel -%438 = OpVariable %439 Function %440 -%445 = OpLoad %26 %70 -%446 = OpLoad %29 %72 -%447 = OpLoad %30 %74 -%448 = OpLoad %31 %76 -OpBranch %449 -%449 = OpLabel -%450 = OpCompositeConstruct %27 %305 %305 -%451 = OpCompositeConstruct %28 %305 %305 %305 -%453 = OpSampledImage %452 %446 %445 -%454 = OpImageSampleDrefImplicitLod %7 %453 %450 %305 -%455 = OpLoad %7 %438 -%456 = OpFAdd %7 %455 %454 -OpStore %438 %456 -%458 = OpConvertUToF %7 %203 -%459 = OpCompositeConstruct %28 %450 %458 -%460 = OpSampledImage %457 %447 %445 -%461 = OpImageSampleDrefImplicitLod %7 %460 %459 %305 -%462 = OpLoad %7 %438 -%463 = OpFAdd %7 %462 %461 -OpStore %438 %463 -%464 = OpConvertSToF %7 %308 -%465 = OpCompositeConstruct %28 %450 %464 -%466 = OpSampledImage %457 %447 %445 -%467 = OpImageSampleDrefImplicitLod %7 %466 %465 %305 -%468 = OpLoad %7 %438 -%469 = OpFAdd %7 %468 %467 -OpStore %438 %469 -%471 = OpSampledImage %470 %448 %445 -%472 = OpImageSampleDrefImplicitLod %7 %471 %451 %305 -%473 = OpLoad %7 %438 -%474 = OpFAdd %7 %473 %472 -OpStore %438 %474 -%475 = OpSampledImage %452 %446 %445 -%476 = OpImageSampleDrefExplicitLod %7 %475 %450 %305 Lod %477 -%478 = OpLoad %7 %438 -%479 = OpFAdd %7 %478 %476 -OpStore %438 %479 -%480 = OpConvertUToF %7 %203 -%481 = OpCompositeConstruct %28 %450 %480 -%482 = OpSampledImage %457 %447 %445 -%483 = OpImageSampleDrefExplicitLod %7 %482 %481 %305 Lod %477 -%484 = OpLoad %7 %438 -%485 = OpFAdd %7 %484 %483 -OpStore %438 %485 -%486 = OpConvertSToF %7 %308 -%487 = OpCompositeConstruct %28 %450 %486 -%488 = OpSampledImage %457 %447 %445 -%489 = OpImageSampleDrefExplicitLod %7 %488 %487 %305 Lod %477 -%490 = OpLoad %7 %438 -%491 = OpFAdd %7 %490 %489 -OpStore %438 %491 -%492 = OpSampledImage %470 %448 %445 -%493 = OpImageSampleDrefExplicitLod %7 %492 %451 %305 Lod %477 -%494 = OpLoad %7 %438 -%495 = OpFAdd %7 %494 %493 -OpStore %438 %495 -%496 = OpLoad %7 %438 -OpStore %442 %496 +%421 = OpFunction %2 None %83 +%418 = OpLabel +%415 = OpVariable %416 Function %417 +%422 = OpLoad %26 %70 +%423 = OpLoad %29 %72 +%424 = OpLoad %30 %74 +%425 = OpLoad %31 %76 +OpBranch %426 +%426 = OpLabel +%427 = OpCompositeConstruct %27 %282 %282 +%428 = OpCompositeConstruct %28 %282 %282 %282 +%430 = OpSampledImage %429 %423 %422 +%431 = OpImageSampleDrefImplicitLod %7 %430 %427 %282 +%432 = OpLoad %7 %415 +%433 = OpFAdd %7 %432 %431 +OpStore %415 %433 +%435 = OpConvertUToF %7 %201 +%436 = OpCompositeConstruct %28 %427 %435 +%437 = OpSampledImage %434 %424 %422 +%438 = OpImageSampleDrefImplicitLod %7 %437 %436 %282 +%439 = OpLoad %7 %415 +%440 = OpFAdd %7 %439 %438 +OpStore %415 %440 +%441 = OpConvertSToF %7 %285 +%442 = OpCompositeConstruct %28 %427 %441 +%443 = OpSampledImage %434 %424 %422 +%444 = OpImageSampleDrefImplicitLod %7 %443 %442 %282 +%445 = OpLoad %7 %415 +%446 = OpFAdd %7 %445 %444 +OpStore %415 %446 +%448 = OpSampledImage %447 %425 %422 +%449 = OpImageSampleDrefImplicitLod %7 %448 %428 %282 +%450 = OpLoad %7 %415 +%451 = OpFAdd %7 %450 %449 +OpStore %415 %451 +%452 = OpSampledImage %429 %423 %422 +%453 = OpImageSampleDrefExplicitLod %7 %452 %427 %282 Lod %454 +%455 = OpLoad %7 %415 +%456 = OpFAdd %7 %455 %453 +OpStore %415 %456 +%457 = OpConvertUToF %7 %201 +%458 = OpCompositeConstruct %28 %427 %457 +%459 = OpSampledImage %434 %424 %422 +%460 = OpImageSampleDrefExplicitLod %7 %459 %458 %282 Lod %454 +%461 = OpLoad %7 %415 +%462 = OpFAdd %7 %461 %460 +OpStore %415 %462 +%463 = OpConvertSToF %7 %285 +%464 = OpCompositeConstruct %28 %427 %463 +%465 = OpSampledImage %434 %424 %422 +%466 = OpImageSampleDrefExplicitLod %7 %465 %464 %282 Lod %454 +%467 = OpLoad %7 %415 +%468 = OpFAdd %7 %467 %466 +OpStore %415 %468 +%469 = OpSampledImage %447 %425 %422 +%470 = OpImageSampleDrefExplicitLod %7 %469 %428 %282 Lod %454 +%471 = OpLoad %7 %415 +%472 = OpFAdd %7 %471 %470 +OpStore %415 %472 +%473 = OpLoad %7 %415 +OpStore %419 %473 OpReturn OpFunctionEnd -%499 = OpFunction %2 None %83 -%497 = OpLabel -%500 = OpLoad %18 %53 -%501 = OpLoad %3 %55 -%502 = OpLoad %19 %56 -%503 = OpLoad %26 %68 -%504 = OpLoad %26 %70 -%505 = OpLoad %29 %72 -OpBranch %506 -%506 = OpLabel -%507 = OpCompositeConstruct %27 %305 %305 -%508 = OpSampledImage %318 %500 %503 -%509 = OpImageGather %25 %508 %507 %510 -%511 = OpSampledImage %318 %500 %503 -%512 = OpImageGather %25 %511 %507 %513 ConstOffset %34 -%514 = OpSampledImage %452 %505 %504 -%515 = OpImageDrefGather %25 %514 %507 %305 -%516 = OpSampledImage %452 %505 %504 -%517 = OpImageDrefGather %25 %516 %507 %305 ConstOffset %34 -%519 = OpSampledImage %518 %501 %503 -%520 = OpImageGather %16 %519 %507 %203 -%523 = OpSampledImage %522 %502 %503 -%524 = OpImageGather %521 %523 %507 %203 -%525 = OpConvertUToF %25 %520 -%526 = OpConvertSToF %25 %524 -%527 = OpFAdd %25 %525 %526 -%528 = OpFAdd %25 %509 %512 -%529 = OpFAdd %25 %528 %515 -%530 = OpFAdd %25 %529 %517 -%531 = OpFAdd %25 %530 %527 -OpStore %498 %531 +%476 = OpFunction %2 None %83 +%474 = OpLabel +%477 = OpLoad %18 %53 +%478 = OpLoad %3 %55 +%479 = OpLoad %19 %56 +%480 = OpLoad %26 %68 +%481 = OpLoad %26 %70 +%482 = OpLoad %29 %72 +OpBranch %483 +%483 = OpLabel +%484 = OpCompositeConstruct %27 %282 %282 +%485 = OpSampledImage %295 %477 %480 +%486 = OpImageGather %25 %485 %484 %487 +%488 = OpSampledImage %295 %477 %480 +%489 = OpImageGather %25 %488 %484 %490 ConstOffset %34 +%491 = OpSampledImage %429 %482 %481 +%492 = OpImageDrefGather %25 %491 %484 %282 +%493 = OpSampledImage %429 %482 %481 +%494 = OpImageDrefGather %25 %493 %484 %282 ConstOffset %34 +%496 = OpSampledImage %495 %478 %480 +%497 = OpImageGather %16 %496 %484 %201 +%500 = OpSampledImage %499 %479 %480 +%501 = OpImageGather %498 %500 %484 %201 +%502 = OpConvertUToF %25 %497 +%503 = OpConvertSToF %25 %501 +%504 = OpFAdd %25 %502 %503 +%505 = OpFAdd %25 %486 %489 +%506 = OpFAdd %25 %505 %492 +%507 = OpFAdd %25 %506 %494 +%508 = OpFAdd %25 %507 %504 +OpStore %475 %508 OpReturn OpFunctionEnd -%534 = OpFunction %2 None %83 -%532 = OpLabel -%535 = OpLoad %26 %68 -%536 = OpLoad %29 %72 -OpBranch %537 -%537 = OpLabel -%538 = OpCompositeConstruct %27 %305 %305 -%539 = OpSampledImage %452 %536 %535 -%540 = OpImageSampleImplicitLod %25 %539 %538 -%541 = OpCompositeExtract %7 %540 0 -%542 = OpSampledImage %452 %536 %535 -%543 = OpImageGather %25 %542 %538 %203 -%544 = OpCompositeConstruct %25 %541 %541 %541 %541 -%545 = OpFAdd %25 %544 %543 -OpStore %533 %545 +%511 = OpFunction %2 None %83 +%509 = OpLabel +%512 = OpLoad %26 %68 +%513 = OpLoad %29 %72 +OpBranch %514 +%514 = OpLabel +%515 = OpCompositeConstruct %27 %282 %282 +%516 = OpSampledImage %429 %513 %512 +%517 = OpImageSampleImplicitLod %25 %516 %515 +%518 = OpCompositeExtract %7 %517 0 +%519 = OpSampledImage %429 %513 %512 +%520 = OpImageGather %25 %519 %515 %201 +%521 = OpCompositeConstruct %25 %518 %518 %518 %518 +%522 = OpFAdd %25 %521 %520 +OpStore %510 %522 OpReturn OpFunctionEnd \ No newline at end of file From dcce91960a82ce3a6d37ac799da012e6809345e3 Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Tue, 25 Jul 2023 16:47:32 +0200 Subject: [PATCH 2045/2212] [glsl-out] Add built-in functions to keywords (#2410) * [glsl-out] Add built-in functions to keywords Fixes #2276 and part of #2366. * add a few more keywords and document where they come from --------- Co-authored-by: teoxoy <28601907+teoxoy@users.noreply.github.com> --- src/back/glsl/keywords.rs | 420 +++++++++++++++++++++++++++++++------- 1 file changed, 348 insertions(+), 72 deletions(-) diff --git a/src/back/glsl/keywords.rs b/src/back/glsl/keywords.rs index 5a2836c18..9679020a0 100644 --- a/src/back/glsl/keywords.rs +++ b/src/back/glsl/keywords.rs @@ -1,10 +1,17 @@ pub const RESERVED_KEYWORDS: &[&str] = &[ - "attribute", + // + // GLSL 4.6 keywords, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L2004-L2322 + // GLSL ES 3.2 keywords, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/es/3.2/GLSL_ES_Specification_3.20.html#L2166-L2478 + // + // Note: The GLSL ES 3.2 keywords are the same as GLSL 4.6 keywords with some residing in the reserved section. + // The only exception are the missing Vulkan keywords which I think is an oversight (see https://github.com/KhronosGroup/OpenGL-Registry/issues/585). + // "const", "uniform", - "varying", "buffer", "shared", + "attribute", + "varying", "coherent", "volatile", "restrict", @@ -18,6 +25,8 @@ pub const RESERVED_KEYWORDS: &[&str] = &[ "noperspective", "patch", "sample", + "invariant", + "precise", "break", "continue", "do", @@ -32,41 +41,15 @@ pub const RESERVED_KEYWORDS: &[&str] = &[ "in", "out", "inout", - "float", - "double", "int", "void", "bool", "true", "false", - "invariant", - "precise", + "float", + "double", "discard", "return", - "mat2", - "mat3", - "mat4", - "dmat2", - "dmat3", - "dmat4", - "mat2x2", - "mat2x3", - "mat2x4", - "dmat2x2", - "dmat2x3", - "dmat2x4", - "mat3x2", - "mat3x3", - "mat3x4", - "dmat3x2", - "dmat3x3", - "dmat3x4", - "mat4x2", - "mat4x3", - "mat4x4", - "dmat4x2", - "dmat4x3", - "dmat4x4", "vec2", "vec3", "vec4", @@ -76,91 +59,158 @@ pub const RESERVED_KEYWORDS: &[&str] = &[ "bvec2", "bvec3", "bvec4", - "dvec2", - "dvec3", - "dvec4", "uint", "uvec2", "uvec3", "uvec4", + "dvec2", + "dvec3", + "dvec4", + "mat2", + "mat3", + "mat4", + "mat2x2", + "mat2x3", + "mat2x4", + "mat3x2", + "mat3x3", + "mat3x4", + "mat4x2", + "mat4x3", + "mat4x4", + "dmat2", + "dmat3", + "dmat4", + "dmat2x2", + "dmat2x3", + "dmat2x4", + "dmat3x2", + "dmat3x3", + "dmat3x4", + "dmat4x2", + "dmat4x3", + "dmat4x4", "lowp", "mediump", "highp", "precision", "sampler1D", - "sampler2D", - "sampler3D", - "samplerCube", "sampler1DShadow", - "sampler2DShadow", - "samplerCubeShadow", "sampler1DArray", - "sampler2DArray", "sampler1DArrayShadow", - "sampler2DArrayShadow", "isampler1D", - "isampler2D", - "isampler3D", - "isamplerCube", "isampler1DArray", - "isampler2DArray", "usampler1D", - "usampler2D", - "usampler3D", - "usamplerCube", "usampler1DArray", + "sampler2D", + "sampler2DShadow", + "sampler2DArray", + "sampler2DArrayShadow", + "isampler2D", + "isampler2DArray", + "usampler2D", "usampler2DArray", "sampler2DRect", "sampler2DRectShadow", - "isampler2D", - "Rect", + "isampler2DRect", "usampler2DRect", - "samplerBuffer", - "isamplerBuffer", - "usamplerBuffer", "sampler2DMS", "isampler2DMS", "usampler2DMS", "sampler2DMSArray", "isampler2DMSArray", "usampler2DMSArray", + "sampler3D", + "isampler3D", + "usampler3D", + "samplerCube", + "samplerCubeShadow", + "isamplerCube", + "usamplerCube", "samplerCubeArray", "samplerCubeArrayShadow", "isamplerCubeArray", "usamplerCubeArray", + "samplerBuffer", + "isamplerBuffer", + "usamplerBuffer", "image1D", "iimage1D", "uimage1D", - "image2D", - "iimage2D", - "uimage2D", - "image3D", - "iimage3D", - "uimage3D", - "image2DRect", - "iimage2DRect", - "uimage2DRect", - "imageCube", - "iimageCube", - "uimageCube", - "imageBuffer", - "iimageBuffer", - "uimageBuffer", "image1DArray", "iimage1DArray", "uimage1DArray", + "image2D", + "iimage2D", + "uimage2D", "image2DArray", "iimage2DArray", "uimage2DArray", - "imageCubeArray", - "iimageCubeArray", - "uimageCubeArray", + "image2DRect", + "iimage2DRect", + "uimage2DRect", "image2DMS", "iimage2DMS", "uimage2DMS", "image2DMSArray", "iimage2DMSArray", - "uimage2DMSArraystruct", + "uimage2DMSArray", + "image3D", + "iimage3D", + "uimage3D", + "imageCube", + "iimageCube", + "uimageCube", + "imageCubeArray", + "iimageCubeArray", + "uimageCubeArray", + "imageBuffer", + "iimageBuffer", + "uimageBuffer", + "struct", + // Vulkan keywords + "texture1D", + "texture1DArray", + "itexture1D", + "itexture1DArray", + "utexture1D", + "utexture1DArray", + "texture2D", + "texture2DArray", + "itexture2D", + "itexture2DArray", + "utexture2D", + "utexture2DArray", + "texture2DRect", + "itexture2DRect", + "utexture2DRect", + "texture2DMS", + "itexture2DMS", + "utexture2DMS", + "texture2DMSArray", + "itexture2DMSArray", + "utexture2DMSArray", + "texture3D", + "itexture3D", + "utexture3D", + "textureCube", + "itextureCube", + "utextureCube", + "textureCubeArray", + "itextureCubeArray", + "utextureCubeArray", + "textureBuffer", + "itextureBuffer", + "utextureBuffer", + "sampler", + "samplerShadow", + "subpassInput", + "isubpassInput", + "usubpassInput", + "subpassInputMS", + "isubpassInputMS", + "usubpassInputMS", + // Reserved keywords "common", "partition", "active", @@ -194,11 +244,237 @@ pub const RESERVED_KEYWORDS: &[&str] = &[ "fvec2", "fvec3", "fvec4", - "sampler3DRect", "filter", "sizeof", "cast", "namespace", "using", + "sampler3DRect", + // + // GLSL 4.6 Built-In Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13314 + // + // Angle and Trigonometry Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13469-L13561C5 + "radians", + "degrees", + "sin", + "cos", + "tan", + "asin", + "acos", + "atan", + "sinh", + "cosh", + "tanh", + "asinh", + "acosh", + "atanh", + // Exponential Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13569-L13620 + "pow", + "exp", + "log", + "exp2", + "log2", + "sqrt", + "inversesqrt", + // Common Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13628-L13908 + "abs", + "sign", + "floor", + "trunc", + "round", + "roundEven", + "ceil", + "fract", + "mod", + "modf", + "min", + "max", + "clamp", + "mix", + "step", + "smoothstep", + "isnan", + "isinf", + "floatBitsToInt", + "floatBitsToUint", + "intBitsToFloat", + "uintBitsToFloat", + "fma", + "frexp", + "ldexp", + // Floating-Point Pack and Unpack Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13916-L14007 + "packUnorm2x16", + "packSnorm2x16", + "packUnorm4x8", + "packSnorm4x8", + "unpackUnorm2x16", + "unpackSnorm2x16", + "unpackUnorm4x8", + "unpackSnorm4x8", + "packHalf2x16", + "unpackHalf2x16", + "packDouble2x32", + "unpackDouble2x32", + // Geometric Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14014-L14121 + "length", + "distance", + "dot", + "cross", + "normalize", + "ftransform", + "faceforward", + "reflect", + "refract", + // Matrix Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14151-L14215 + "matrixCompMult", + "outerProduct", + "transpose", + "determinant", + "inverse", + // Vector Relational Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14259-L14322 + "lessThan", + "lessThanEqual", + "greaterThan", + "greaterThanEqual", + "equal", + "notEqual", + "any", + "all", + "not", + // Integer Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14335-L14432 + "uaddCarry", + "usubBorrow", + "umulExtended", + "imulExtended", + "bitfieldExtract", + "bitfieldInsert", + "bitfieldReverse", + "bitCount", + "findLSB", + "findMSB", + // Texture Query Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14645-L14732 + "textureSize", + "textureQueryLod", + "textureQueryLevels", + "textureSamples", + // Texel Lookup Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14736-L14997 + "texture", + "textureProj", + "textureLod", + "textureOffset", + "texelFetch", + "texelFetchOffset", + "textureProjOffset", + "textureLodOffset", + "textureProjLod", + "textureProjLodOffset", + "textureGrad", + "textureGradOffset", + "textureProjGrad", + "textureProjGradOffset", + // Texture Gather Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15077-L15154 + "textureGather", + "textureGatherOffset", + "textureGatherOffsets", + // Compatibility Profile Texture Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15161-L15220 + "texture1D", + "texture1DProj", + "texture1DLod", + "texture1DProjLod", + "texture2D", + "texture2DProj", + "texture2DLod", + "texture2DProjLod", + "texture3D", + "texture3DProj", + "texture3DLod", + "texture3DProjLod", + "textureCube", + "textureCubeLod", + "shadow1D", + "shadow2D", + "shadow1DProj", + "shadow2DProj", + "shadow1DLod", + "shadow2DLod", + "shadow1DProjLod", + "shadow2DProjLod", + // Atomic Counter Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15241-L15531 + "atomicCounterIncrement", + "atomicCounterDecrement", + "atomicCounter", + "atomicCounterAdd", + "atomicCounterSubtract", + "atomicCounterMin", + "atomicCounterMax", + "atomicCounterAnd", + "atomicCounterOr", + "atomicCounterXor", + "atomicCounterExchange", + "atomicCounterCompSwap", + // Atomic Memory Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15563-L15624 + "atomicAdd", + "atomicMin", + "atomicMax", + "atomicAnd", + "atomicOr", + "atomicXor", + "atomicExchange", + "atomicCompSwap", + // Image Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15763-L15878 + "imageSize", + "imageSamples", + "imageLoad", + "imageStore", + "imageAtomicAdd", + "imageAtomicMin", + "imageAtomicMax", + "imageAtomicAnd", + "imageAtomicOr", + "imageAtomicXor", + "imageAtomicExchange", + "imageAtomicCompSwap", + // Geometry Shader Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15886-L15932 + "EmitStreamVertex", + "EndStreamPrimitive", + "EmitVertex", + "EndPrimitive", + // Fragment Processing Functions, Derivative Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16041-L16114 + "dFdx", + "dFdy", + "dFdxFine", + "dFdyFine", + "dFdxCoarse", + "dFdyCoarse", + "fwidth", + "fwidthFine", + "fwidthCoarse", + // Fragment Processing Functions, Interpolation Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16150-L16198 + "interpolateAtCentroid", + "interpolateAtSample", + "interpolateAtOffset", + // Noise Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16214-L16243 + "noise1", + "noise2", + "noise3", + "noise4", + // Shader Invocation Control Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16255-L16276 + "barrier", + // Shader Memory Control Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16336-L16382 + "memoryBarrier", + "memoryBarrierAtomicCounter", + "memoryBarrierBuffer", + "memoryBarrierShared", + "memoryBarrierImage", + "groupMemoryBarrier", + // Subpass-Input Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16451-L16470 + "subpassLoad", + // Shader Invocation Group Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16483-L16511 + "anyInvocation", + "allInvocations", + "allInvocationsEqual", + // + // entry point name (should not be shadowed) + // "main", ]; From 535701f6b2f38f7e0088701ee4cf6d8024f74a21 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 26 Jul 2023 01:10:15 +0200 Subject: [PATCH 2046/2212] Add v0.13 changelog + minor version bumps of previous versions (#2411) --- CHANGELOG.md | 102 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 376bbf898..fac0fd78e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,93 @@ # Change Log +## v0.13 (2023-07-21) + +#### GENERAL + +- Move from `make` to `cargo xtask` workflows. ([#2297](https://github.com/gfx-rs/naga/pull/2297)) **@ErichDonGubler** +- Omit non referenced expressions from output. ([#2378](https://github.com/gfx-rs/naga/pull/2378)) **@teoxoy** +- Bump `bitflags` to v2. ([#2358](https://github.com/gfx-rs/naga/pull/2358)) **@daxpedda** +- Implement `workgroupUniformLoad`. ([#2201](https://github.com/gfx-rs/naga/pull/2201)) **@DJMcNab** + +#### API + +- Expose early depth test field. ([#2393](https://github.com/gfx-rs/naga/pull/2393)) **@Joeoc2001** +- Split image bounds check policy. ([#2265](https://github.com/gfx-rs/naga/pull/2265)) **@teoxoy** +- Change type of constant sized arrays to `NonZeroU32`. ([#2337](https://github.com/gfx-rs/naga/pull/2337)) **@teoxoy** +- Introduce `GlobalCtx`. ([#2335](https://github.com/gfx-rs/naga/pull/2335)) **@teoxoy** +- Introduce `Expression::Literal`. ([#2333](https://github.com/gfx-rs/naga/pull/2333)) **@teoxoy** +- Introduce `Expression::ZeroValue`. ([#2332](https://github.com/gfx-rs/naga/pull/2332)) **@teoxoy** +- Add support for const-expressions (only at the API level, functionality is still WIP). ([#2266](https://github.com/gfx-rs/naga/pull/2266)) **@teoxoy**, **@jimblandy** + +#### DOCS + +- Document which expressions are in scope for a `break_if` expression. ([#2326](https://github.com/gfx-rs/naga/pull/2326)) **@jimblandy** + +#### VALIDATOR + +- Don't `use std::opsIndex`, used only when `"validate"` is on. ([#2383](https://github.com/gfx-rs/naga/pull/2383)) **@jimblandy** +- Remove unneeded `ConstantError::Unresolved{Component,Size}`. ([#2330](https://github.com/gfx-rs/naga/pull/2330)) **@ErichDonGubler** +- Remove `TypeError::UnresolvedBase`. ([#2308](https://github.com/gfx-rs/naga/pull/2308)) **@ErichDonGubler** + +#### WGSL-IN + +- Error on param redefinition. ([#2342](https://github.com/gfx-rs/naga/pull/2342)) **@SparkyPotato** + +#### SPV-IN + +- Improve documentation for SPIR-V control flow parsing. ([#2324](https://github.com/gfx-rs/naga/pull/2324)) **@jimblandy** +- Obey the `is_depth` field of `OpTypeImage`. ([#2341](https://github.com/gfx-rs/naga/pull/2341)) **@expenses** +- Convert conditional backedges to `break if`. ([#2290](https://github.com/gfx-rs/naga/pull/2290)) **@eddyb** + +#### GLSL-IN + +- Support commas in structure definitions. ([#2400](https://github.com/gfx-rs/naga/pull/2400)) **@fornwall** + +#### SPV-OUT + +- Add debug info. ([#2379](https://github.com/gfx-rs/naga/pull/2379)) **@wicast** +- Use `IndexSet` instead of `HashSet` for iterated sets (capabilities/extensions). ([#2389](https://github.com/gfx-rs/naga/pull/2389)) **@eddyb** +- Support array bindings of buffers. ([#2282](https://github.com/gfx-rs/naga/pull/2282)) **@kvark** + +#### MSL-OUT + +- Rename `allow_point_size` to `allow_and_force_point_size`. ([#2280](https://github.com/gfx-rs/naga/pull/2280)) **@teoxoy** +- Initialize arrays inline. ([#2331](https://github.com/gfx-rs/naga/pull/2331)) **@teoxoy** + +#### HLSL-OUT + +- Implement Pack/Unpack for HLSL. ([#2353](https://github.com/gfx-rs/naga/pull/2353)) **@Elabajaba** +- Complete HLSL reserved symbols. ([#2367](https://github.com/gfx-rs/naga/pull/2367)) **@teoxoy** +- Handle case insensitive FXC keywords. ([#2347](https://github.com/gfx-rs/naga/pull/2347)) **@PJB3005** +- Fix return type for firstbitlow/high. ([#2315](https://github.com/gfx-rs/naga/pull/2315)) **@evahop** + +#### GLSL-OUT + +- `textureSize` level must be a signed integer. ([#2397](https://github.com/gfx-rs/naga/pull/2397)) **@nical** +- Fix functions with array return type. ([#2382](https://github.com/gfx-rs/naga/pull/2382)) **@Gordon-F** + +#### WGSL-OUT + +- Output `@interpolate(flat)` attribute for integer locations. ([#2318](https://github.com/gfx-rs/naga/pull/2318)) **@expenses** + +## v0.12.3 (2023-07-09) + +#### WGSL-OUT + +- (Backport) Output `@interpolate(flat)` attribute for integer locations. ([#2318](https://github.com/gfx-rs/naga/pull/2318)) **@expenses** + +## v0.12.2 (2023-05-30) + +#### SPV-OUT + +- (Backport) Support array bindings of buffers. ([#2282](https://github.com/gfx-rs/naga/pull/2282)) **@kvark** + +## v0.12.1 (2023-05-18) + +#### SPV-IN + +- (Backport) Convert conditional backedges to `break if`. ([#2290](https://github.com/gfx-rs/naga/pull/2290)) **@eddyb** + ## v0.12 (2023-04-19) #### GENERAL @@ -71,6 +159,12 @@ - Skip `invariant` for `gl_FragCoord` on WebGL2. ([#2254](https://github.com/gfx-rs/naga/pull/2254)) **@grovesNL** - Inject default `gl_PointSize = 1.0` in vertex shaders if `FORCE_POINT_SIZE` option was set. ([#2223](https://github.com/gfx-rs/naga/pull/2223)) **@REASY** +## v0.11.1 (2023-05-18) + +#### SPV-IN + +- (Backport) Convert conditional backedges to `break if`. ([#2290](https://github.com/gfx-rs/naga/pull/2290)) **@eddyb** + ## v0.11 (2023-01-25) - Move to the Rust 2021 edition ([#2085](https://github.com/gfx-rs/naga/pull/2085)) **@ErichDonGubler** @@ -163,6 +257,14 @@ - Write correct scalar kind when `width != 4` ([#1514](https://github.com/gfx-rs/naga/pull/1514)) **@fintelia** +## v0.10.1 (2023-06-21) + +SPV-OUT +- Backport #2389 (Use `IndexSet` instead of `HashSet` for iterated sets (capabilities/extensions)) by @eddyb, @jimblandy in https://github.com/gfx-rs/naga/pull/2391 + +SPV-IN +- Backport #2290 (Convert conditional backedges to `break if`) by @eddyb in https://github.com/gfx-rs/naga/pull/2387 + ## v0.10 (2022-10-05) - Make termcolor dependency optional by @AldaronLau in https://github.com/gfx-rs/naga/pull/2014 From 46951a09c00540310f68c442a7a6fbf3ecf70d1d Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Mon, 31 Jul 2023 15:59:17 +0200 Subject: [PATCH 2047/2212] Validate storage buffer access (#2415) * validate storage buffer access * remove GLSL writeonly buffer test --- src/valid/interface.rs | 7 ++++++- tests/in/glsl/buffer.frag | 6 ------ tests/out/wgsl/buffer-frag.wgsl | 15 ++++----------- 3 files changed, 10 insertions(+), 18 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index f1f9548a7..58ae82ce6 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -33,6 +33,8 @@ pub enum GlobalVariableError { ), #[error("Initializer doesn't match the variable type")] InitializerType, + #[error("Storage address space doesn't support write-only access")] + StorageAddressSpaceWriteOnlyNotSupported, } #[derive(Clone, Debug, thiserror::Error)] @@ -416,7 +418,7 @@ impl super::Validator { crate::AddressSpace::Function => { return Err(GlobalVariableError::InvalidUsage(var.space)) } - crate::AddressSpace::Storage { .. } => { + crate::AddressSpace::Storage { access } => { if let Err((ty_handle, disalignment)) = type_info.storage_layout { if self.flags.contains(super::ValidationFlags::STRUCT_LAYOUTS) { return Err(GlobalVariableError::Alignment( @@ -426,6 +428,9 @@ impl super::Validator { )); } } + if access == crate::StorageAccess::STORE { + return Err(GlobalVariableError::StorageAddressSpaceWriteOnlyNotSupported); + } (TypeFlags::DATA | TypeFlags::HOST_SHAREABLE, true) } crate::AddressSpace::Uniform => { diff --git a/tests/in/glsl/buffer.frag b/tests/in/glsl/buffer.frag index dc50aae2e..e57380f46 100644 --- a/tests/in/glsl/buffer.frag +++ b/tests/in/glsl/buffer.frag @@ -4,10 +4,6 @@ layout(set = 0, binding = 0) buffer testBufferBlock { uint[] data; } testBuffer; -layout(set = 0, binding = 1) writeonly buffer testBufferWriteOnlyBlock { - uint[] data; -} testBufferWriteOnly; - layout(set = 0, binding = 2) readonly buffer testBufferReadOnlyBlock { uint[] data; } testBufferReadOnly; @@ -16,7 +12,5 @@ void main() { uint a = testBuffer.data[0]; testBuffer.data[1] = 2; - testBufferWriteOnly.data[1] = 2; - uint b = testBufferReadOnly.data[0]; } diff --git a/tests/out/wgsl/buffer-frag.wgsl b/tests/out/wgsl/buffer-frag.wgsl index 4f561b427..73e543ca7 100644 --- a/tests/out/wgsl/buffer-frag.wgsl +++ b/tests/out/wgsl/buffer-frag.wgsl @@ -2,18 +2,12 @@ struct testBufferBlock { data: array, } -struct testBufferWriteOnlyBlock { - data: array, -} - struct testBufferReadOnlyBlock { data: array, } @group(0) @binding(0) var testBuffer: testBufferBlock; -@group(0) @binding(1) -var testBufferWriteOnly: testBufferWriteOnlyBlock; @group(0) @binding(2) var testBufferReadOnly: testBufferReadOnlyBlock; @@ -21,12 +15,11 @@ fn main_1() { var a: u32; var b: u32; - let _e12 = testBuffer.data[0]; - a = _e12; + let _e9 = testBuffer.data[0]; + a = _e9; testBuffer.data[1] = u32(2); - testBufferWriteOnly.data[1] = u32(2); - let _e27 = testBufferReadOnly.data[0]; - b = _e27; + let _e19 = testBufferReadOnly.data[0]; + b = _e19; return; } From d0d3a2e714e7392b429b5f11d51611616affcbb4 Mon Sep 17 00:00:00 2001 From: robtfm <50659922+robtfm@users.noreply.github.com> Date: Wed, 2 Aug 2023 13:01:04 +0100 Subject: [PATCH 2048/2212] derive PartialEq on Expression (#2417) --- src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index a835fec32..a1f7ef165 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1263,8 +1263,7 @@ bitflags::bitflags! { /// An expression that can be evaluated to obtain a value. /// /// This is a Single Static Assignment (SSA) scheme similar to SPIR-V. -#[derive(Clone, Debug)] -#[cfg_attr(test, derive(PartialEq))] +#[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] From f7de1942c12b82958d6f1d74e215f47623275984 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Wed, 2 Aug 2023 12:05:16 -0400 Subject: [PATCH 2049/2212] [spv-out] Cache OpConstantNull (#2414) --- src/back/spv/block.rs | 6 +- src/back/spv/image.rs | 2 +- src/back/spv/index.rs | 2 +- src/back/spv/mod.rs | 1 + src/back/spv/writer.rs | 20 +- tests/out/spv/access.spvasm | 502 +++--- tests/out/spv/atomicCompareExchange.spvasm | 145 +- tests/out/spv/binding-arrays.spvasm | 699 ++++---- tests/out/spv/binding-buffer-arrays.spvasm | 52 +- tests/out/spv/boids.spvasm | 531 +++--- .../spv/bounds-check-image-restrict.spvasm | 51 +- tests/out/spv/bounds-check-image-rzsw.spvasm | 771 ++++----- tests/out/spv/bounds-check-zero.spvasm | 437 +++-- tests/out/spv/break-if.spvasm | 87 +- tests/out/spv/collatz.spvasm | 151 +- tests/out/spv/constructors.spvasm | 74 +- tests/out/spv/debug-symbol-terrain.spvasm | 1528 ++++++++--------- tests/out/spv/functions.spvasm | 53 +- tests/out/spv/globals.spvasm | 267 ++- tests/out/spv/math-functions.spvasm | 149 +- tests/out/spv/operators.spvasm | 842 +++++---- tests/out/spv/shadow.spvasm | 174 +- tests/out/spv/skybox.spvasm | 181 +- tests/out/spv/standard.spvasm | 84 +- 24 files changed, 3362 insertions(+), 3447 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index ec3531ede..74d8cdfef 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -242,7 +242,7 @@ impl<'w> BlockContext<'w> { let init = self.ir_module.constants[handle].init; self.writer.constant_ids[init.index()] } - crate::Expression::ZeroValue(_) => self.writer.write_constant_null(result_type_id), + crate::Expression::ZeroValue(_) => self.writer.get_constant_null(result_type_id), crate::Expression::Compose { ty: _, ref components, @@ -1658,7 +1658,7 @@ impl<'w> BlockContext<'w> { size: u32, block: &mut Block, ) { - let mut partial_sum = self.writer.write_constant_null(result_type_id); + let mut partial_sum = self.writer.get_constant_null(result_type_id); let last_component = size - 1; for index in 0..=last_component { // compute the product of the current components @@ -2315,7 +2315,7 @@ impl<'w> BlockContext<'w> { BlockExit::Return => match self.ir_function.result { Some(ref result) if self.function.entry_point_context.is_none() => { let type_id = self.get_type_id(LookupType::Handle(result.ty)); - let null_id = self.writer.write_constant_null(type_id); + let null_id = self.writer.get_constant_null(type_id); Instruction::return_value(null_id) } _ => Instruction::return_void(), diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index a80ef3cfd..bc7846922 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -189,7 +189,7 @@ impl Access for Load { } fn out_of_bounds_value(&self, ctx: &mut BlockContext<'_>) -> Word { - ctx.writer.write_constant_null(self.type_id) + ctx.writer.get_constant_null(self.type_id) } } diff --git a/src/back/spv/index.rs b/src/back/spv/index.rs index 19cc4a896..92e0f88d9 100644 --- a/src/back/spv/index.rs +++ b/src/back/spv/index.rs @@ -304,7 +304,7 @@ impl<'w> BlockContext<'w> { F: FnOnce(&mut IdGenerator, &mut Block) -> Word, { // For the out-of-bounds case, we produce a zero value. - let null_id = self.writer.write_constant_null(result_type); + let null_id = self.writer.get_constant_null(result_type); let mut selection = Selection::start(block, result_type); diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 2d395effa..52e304a23 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -466,6 +466,7 @@ enum CachedConstant { ty: LookupType, constituent_ids: Vec, }, + ZeroValue(Word), } #[derive(Clone)] diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e402400b3..e6db93602 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -356,7 +356,7 @@ impl Writer { crate::TypeInner::RayQuery => None, _ => { let type_id = self.get_type_id(LookupType::Handle(variable.ty)); - Some(self.write_constant_null(type_id)) + Some(self.get_constant_null(type_id)) } }), ); @@ -1206,6 +1206,16 @@ impl Writer { .to_words(&mut self.logical_layout.declarations); } + pub(super) fn get_constant_null(&mut self, type_id: Word) -> Word { + let null = CachedConstant::ZeroValue(type_id); + if let Some(&id) = self.cached_constants.get(&null) { + return id; + } + let id = self.write_constant_null(type_id); + self.cached_constants.insert(null, id); + id + } + pub(super) fn write_constant_null(&mut self, type_id: Word) -> Word { let null_id = self.id_gen.next(); Instruction::constant_null(type_id, null_id) @@ -1226,7 +1236,7 @@ impl Writer { } crate::Expression::ZeroValue(ty) => { let type_id = self.get_type_id(LookupType::Handle(ty)); - self.write_constant_null(type_id) + self.get_constant_null(type_id) } crate::Expression::Compose { ty, ref components } => { let component_ids: Vec<_> = components @@ -1289,7 +1299,7 @@ impl Writer { // get wrapped, and we're initializing `WorkGroup` variables. let var_id = self.global_variables[handle.index()].var_id; let var_type_id = self.get_type_id(LookupType::Handle(var.ty)); - let init_word = self.write_constant_null(var_type_id); + let init_word = self.get_constant_null(var_type_id); Instruction::store(var_id, init_word, None) }) .collect::>(); @@ -1327,7 +1337,7 @@ impl Writer { id }; - let zero_id = self.write_constant_null(uint3_type_id); + let zero_id = self.get_constant_null(uint3_type_id); let bool3_type_id = self.get_bool3_type_id(); let eq_id = self.id_gen.next(); @@ -1663,7 +1673,7 @@ impl Writer { let init_word = match (global_variable.space, self.zero_initialize_workgroup_memory) { (crate::AddressSpace::Private, _) | (crate::AddressSpace::WorkGroup, super::ZeroInitializeWorkgroupMemoryMode::Native) => { - init_word.or_else(|| Some(self.write_constant_null(inner_type_id))) + init_word.or_else(|| Some(self.get_constant_null(inner_type_id))) } _ => init_word, }; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 8687ddb6a..f7be2338c 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 326 +; Bound: 324 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %239 "foo_vert" %234 %237 -OpEntryPoint Fragment %286 "foo_frag" %285 -OpEntryPoint GLCompute %306 "assign_through_ptr" %309 -OpExecutionMode %286 OriginUpperLeft -OpExecutionMode %306 LocalSize 1 1 1 +OpEntryPoint Vertex %237 "foo_vert" %232 %235 +OpEntryPoint Fragment %284 "foo_frag" %283 +OpEntryPoint GLCompute %304 "assign_through_ptr" %307 +OpExecutionMode %284 OriginUpperLeft +OpExecutionMode %304 LocalSize 1 1 1 OpMemberName %6 0 "a" OpMemberName %6 1 "b" OpMemberName %6 2 "c" @@ -38,23 +38,23 @@ OpName %59 "idx" OpName %62 "t" OpName %66 "test_matrix_within_struct_accesses" OpName %137 "idx" -OpName %139 "t" -OpName %143 "test_matrix_within_array_within_struct_accesses" -OpName %202 "foo" -OpName %203 "read_from_private" -OpName %208 "a" -OpName %209 "test_arr_as_arg" -OpName %215 "p" -OpName %216 "assign_through_ptr_fn" -OpName %221 "foo" -OpName %222 "assign_array_through_ptr_fn" -OpName %228 "foo" -OpName %230 "c2" -OpName %234 "vi" -OpName %239 "foo_vert" -OpName %286 "foo_frag" -OpName %303 "arr" -OpName %306 "assign_through_ptr" +OpName %138 "t" +OpName %142 "test_matrix_within_array_within_struct_accesses" +OpName %200 "foo" +OpName %201 "read_from_private" +OpName %206 "a" +OpName %207 "test_arr_as_arg" +OpName %213 "p" +OpName %214 "assign_through_ptr_fn" +OpName %219 "foo" +OpName %220 "assign_array_through_ptr_fn" +OpName %226 "foo" +OpName %228 "c2" +OpName %232 "vi" +OpName %237 "foo_vert" +OpName %284 "foo_frag" +OpName %301 "arr" +OpName %304 "assign_through_ptr" OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpMemberDecorate %6 2 Offset 28 @@ -99,10 +99,10 @@ OpDecorate %55 DescriptorSet 0 OpDecorate %55 Binding 3 OpDecorate %56 Block OpMemberDecorate %56 0 Offset 0 -OpDecorate %234 BuiltIn VertexIndex -OpDecorate %237 BuiltIn Position -OpDecorate %285 Location 0 -OpDecorate %309 BuiltIn LocalInvocationId +OpDecorate %232 BuiltIn VertexIndex +OpDecorate %235 BuiltIn Position +OpDecorate %283 Location 0 +OpDecorate %307 BuiltIn LocalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeVector %3 3 @@ -186,54 +186,52 @@ OpDecorate %309 BuiltIn LocalInvocationId %116 = OpTypePointer Function %21 %122 = OpTypePointer Function %12 %128 = OpTypePointer Function %10 -%138 = OpConstantNull %5 -%140 = OpTypePointer Function %26 -%141 = OpConstantNull %26 -%144 = OpTypePointer Uniform %26 -%146 = OpConstantNull %25 -%147 = OpConstantNull %25 -%148 = OpConstant %10 8.0 -%149 = OpConstant %10 7.0 -%153 = OpTypePointer Uniform %25 -%156 = OpTypePointer Uniform %24 -%179 = OpTypePointer Function %25 -%181 = OpTypePointer Function %24 -%204 = OpTypeFunction %10 %27 -%210 = OpTypeFunction %10 %29 -%217 = OpTypeFunction %2 %35 -%218 = OpConstant %3 42 -%223 = OpTypeFunction %2 %37 -%229 = OpConstantNull %10 -%231 = OpTypePointer Function %33 -%232 = OpConstantNull %33 -%235 = OpTypePointer Input %3 -%234 = OpVariable %235 Input -%238 = OpTypePointer Output %31 -%237 = OpVariable %238 Output -%241 = OpTypePointer StorageBuffer %23 -%244 = OpConstant %10 0.0 -%245 = OpConstant %3 3 -%246 = OpConstant %5 3 -%247 = OpConstant %5 4 -%248 = OpConstant %5 42 -%249 = OpConstantNull %29 -%254 = OpTypePointer StorageBuffer %8 -%257 = OpTypePointer StorageBuffer %18 -%258 = OpConstant %3 4 -%261 = OpTypePointer StorageBuffer %9 -%262 = OpTypePointer StorageBuffer %10 -%265 = OpTypePointer StorageBuffer %19 -%268 = OpTypePointer StorageBuffer %7 -%285 = OpVariable %238 Output -%288 = OpConstantNull %23 -%304 = OpConstantNull %36 -%308 = OpConstantNull %3 -%310 = OpTypePointer Input %4 -%309 = OpVariable %310 Input -%312 = OpConstantNull %4 -%314 = OpTypeBool -%313 = OpTypeVector %314 3 -%319 = OpConstant %3 264 +%139 = OpTypePointer Function %26 +%140 = OpConstantNull %26 +%143 = OpTypePointer Uniform %26 +%145 = OpConstantNull %25 +%146 = OpConstant %10 8.0 +%147 = OpConstant %10 7.0 +%151 = OpTypePointer Uniform %25 +%154 = OpTypePointer Uniform %24 +%177 = OpTypePointer Function %25 +%179 = OpTypePointer Function %24 +%202 = OpTypeFunction %10 %27 +%208 = OpTypeFunction %10 %29 +%215 = OpTypeFunction %2 %35 +%216 = OpConstant %3 42 +%221 = OpTypeFunction %2 %37 +%227 = OpConstantNull %10 +%229 = OpTypePointer Function %33 +%230 = OpConstantNull %33 +%233 = OpTypePointer Input %3 +%232 = OpVariable %233 Input +%236 = OpTypePointer Output %31 +%235 = OpVariable %236 Output +%239 = OpTypePointer StorageBuffer %23 +%242 = OpConstant %10 0.0 +%243 = OpConstant %3 3 +%244 = OpConstant %5 3 +%245 = OpConstant %5 4 +%246 = OpConstant %5 42 +%247 = OpConstantNull %29 +%252 = OpTypePointer StorageBuffer %8 +%255 = OpTypePointer StorageBuffer %18 +%256 = OpConstant %3 4 +%259 = OpTypePointer StorageBuffer %9 +%260 = OpTypePointer StorageBuffer %10 +%263 = OpTypePointer StorageBuffer %19 +%266 = OpTypePointer StorageBuffer %7 +%283 = OpVariable %236 Output +%286 = OpConstantNull %23 +%302 = OpConstantNull %36 +%306 = OpConstantNull %3 +%308 = OpTypePointer Input %4 +%307 = OpVariable %308 Input +%310 = OpConstantNull %4 +%312 = OpTypeBool +%311 = OpTypeVector %312 3 +%317 = OpConstant %3 264 %66 = OpFunction %2 None %67 %65 = OpLabel %59 = OpVariable %60 Function %61 @@ -300,200 +298,200 @@ OpStore %133 %81 OpStore %136 %82 OpReturn OpFunctionEnd -%143 = OpFunction %2 None %67 -%142 = OpLabel -%137 = OpVariable %60 Function %138 -%139 = OpVariable %140 Function %141 -%145 = OpAccessChain %144 %55 %38 -OpBranch %150 -%150 = OpLabel +%142 = OpFunction %2 None %67 +%141 = OpLabel +%137 = OpVariable %60 Function %61 +%138 = OpVariable %139 Function %140 +%144 = OpAccessChain %143 %55 %38 +OpBranch %148 +%148 = OpLabel OpStore %137 %70 -%151 = OpLoad %5 %137 -%152 = OpISub %5 %151 %70 -OpStore %137 %152 -%154 = OpAccessChain %153 %145 %38 -%155 = OpLoad %25 %154 -%157 = OpAccessChain %156 %145 %38 %38 -%158 = OpLoad %24 %157 -%159 = OpAccessChain %89 %145 %38 %38 %38 -%160 = OpLoad %12 %159 -%161 = OpLoad %5 %137 -%162 = OpAccessChain %89 %145 %38 %38 %161 -%163 = OpLoad %12 %162 -%164 = OpAccessChain %95 %145 %38 %38 %38 %96 -%165 = OpLoad %10 %164 -%166 = OpLoad %5 %137 -%167 = OpAccessChain %95 %145 %38 %38 %38 %166 -%168 = OpLoad %10 %167 -%169 = OpLoad %5 %137 -%170 = OpAccessChain %95 %145 %38 %38 %169 %96 -%171 = OpLoad %10 %170 -%172 = OpLoad %5 %137 -%173 = OpLoad %5 %137 -%174 = OpAccessChain %95 %145 %38 %38 %172 %173 -%175 = OpLoad %10 %174 -%176 = OpCompositeConstruct %26 %146 -OpStore %139 %176 -%177 = OpLoad %5 %137 -%178 = OpIAdd %5 %177 %70 -OpStore %137 %178 -%180 = OpAccessChain %179 %139 %38 -OpStore %180 %147 -%182 = OpCompositeConstruct %12 %148 %148 -%183 = OpCompositeConstruct %12 %149 %149 -%184 = OpCompositeConstruct %12 %74 %74 -%185 = OpCompositeConstruct %12 %75 %75 -%186 = OpCompositeConstruct %24 %182 %183 %184 %185 -%187 = OpAccessChain %181 %139 %38 %38 +%149 = OpLoad %5 %137 +%150 = OpISub %5 %149 %70 +OpStore %137 %150 +%152 = OpAccessChain %151 %144 %38 +%153 = OpLoad %25 %152 +%155 = OpAccessChain %154 %144 %38 %38 +%156 = OpLoad %24 %155 +%157 = OpAccessChain %89 %144 %38 %38 %38 +%158 = OpLoad %12 %157 +%159 = OpLoad %5 %137 +%160 = OpAccessChain %89 %144 %38 %38 %159 +%161 = OpLoad %12 %160 +%162 = OpAccessChain %95 %144 %38 %38 %38 %96 +%163 = OpLoad %10 %162 +%164 = OpLoad %5 %137 +%165 = OpAccessChain %95 %144 %38 %38 %38 %164 +%166 = OpLoad %10 %165 +%167 = OpLoad %5 %137 +%168 = OpAccessChain %95 %144 %38 %38 %167 %96 +%169 = OpLoad %10 %168 +%170 = OpLoad %5 %137 +%171 = OpLoad %5 %137 +%172 = OpAccessChain %95 %144 %38 %38 %170 %171 +%173 = OpLoad %10 %172 +%174 = OpCompositeConstruct %26 %145 +OpStore %138 %174 +%175 = OpLoad %5 %137 +%176 = OpIAdd %5 %175 %70 +OpStore %137 %176 +%178 = OpAccessChain %177 %138 %38 +OpStore %178 %145 +%180 = OpCompositeConstruct %12 %146 %146 +%181 = OpCompositeConstruct %12 %147 %147 +%182 = OpCompositeConstruct %12 %74 %74 +%183 = OpCompositeConstruct %12 %75 %75 +%184 = OpCompositeConstruct %24 %180 %181 %182 %183 +%185 = OpAccessChain %179 %138 %38 %38 +OpStore %185 %184 +%186 = OpCompositeConstruct %12 %77 %77 +%187 = OpAccessChain %122 %138 %38 %38 %38 OpStore %187 %186 -%188 = OpCompositeConstruct %12 %77 %77 -%189 = OpAccessChain %122 %139 %38 %38 %38 -OpStore %189 %188 -%190 = OpLoad %5 %137 -%191 = OpCompositeConstruct %12 %78 %78 -%192 = OpAccessChain %122 %139 %38 %38 %190 -OpStore %192 %191 -%193 = OpAccessChain %128 %139 %38 %38 %38 %96 -OpStore %193 %79 +%188 = OpLoad %5 %137 +%189 = OpCompositeConstruct %12 %78 %78 +%190 = OpAccessChain %122 %138 %38 %38 %188 +OpStore %190 %189 +%191 = OpAccessChain %128 %138 %38 %38 %38 %96 +OpStore %191 %79 +%192 = OpLoad %5 %137 +%193 = OpAccessChain %128 %138 %38 %38 %38 %192 +OpStore %193 %80 %194 = OpLoad %5 %137 -%195 = OpAccessChain %128 %139 %38 %38 %38 %194 -OpStore %195 %80 +%195 = OpAccessChain %128 %138 %38 %38 %194 %96 +OpStore %195 %81 %196 = OpLoad %5 %137 -%197 = OpAccessChain %128 %139 %38 %38 %196 %96 -OpStore %197 %81 -%198 = OpLoad %5 %137 -%199 = OpLoad %5 %137 -%200 = OpAccessChain %128 %139 %38 %38 %198 %199 -OpStore %200 %82 +%197 = OpLoad %5 %137 +%198 = OpAccessChain %128 %138 %38 %38 %196 %197 +OpStore %198 %82 OpReturn OpFunctionEnd -%203 = OpFunction %10 None %204 -%202 = OpFunctionParameter %27 -%201 = OpLabel -OpBranch %205 +%201 = OpFunction %10 None %202 +%200 = OpFunctionParameter %27 +%199 = OpLabel +OpBranch %203 +%203 = OpLabel +%204 = OpLoad %10 %200 +OpReturnValue %204 +OpFunctionEnd +%207 = OpFunction %10 None %208 +%206 = OpFunctionParameter %29 %205 = OpLabel -%206 = OpLoad %10 %202 -OpReturnValue %206 +OpBranch %209 +%209 = OpLabel +%210 = OpCompositeExtract %28 %206 4 +%211 = OpCompositeExtract %10 %210 9 +OpReturnValue %211 OpFunctionEnd -%209 = OpFunction %10 None %210 -%208 = OpFunctionParameter %29 -%207 = OpLabel -OpBranch %211 -%211 = OpLabel -%212 = OpCompositeExtract %28 %208 4 -%213 = OpCompositeExtract %10 %212 9 -OpReturnValue %213 -OpFunctionEnd -%216 = OpFunction %2 None %217 -%215 = OpFunctionParameter %35 -%214 = OpLabel -OpBranch %219 -%219 = OpLabel -OpStore %215 %218 +%214 = OpFunction %2 None %215 +%213 = OpFunctionParameter %35 +%212 = OpLabel +OpBranch %217 +%217 = OpLabel +OpStore %213 %216 OpReturn OpFunctionEnd -%222 = OpFunction %2 None %223 -%221 = OpFunctionParameter %37 -%220 = OpLabel -OpBranch %224 -%224 = OpLabel -%225 = OpCompositeConstruct %31 %71 %71 %71 %71 -%226 = OpCompositeConstruct %31 %72 %72 %72 %72 -%227 = OpCompositeConstruct %36 %225 %226 -OpStore %221 %227 +%220 = OpFunction %2 None %221 +%219 = OpFunctionParameter %37 +%218 = OpLabel +OpBranch %222 +%222 = OpLabel +%223 = OpCompositeConstruct %31 %71 %71 %71 %71 +%224 = OpCompositeConstruct %31 %72 %72 %72 %72 +%225 = OpCompositeConstruct %36 %223 %224 +OpStore %219 %225 OpReturn OpFunctionEnd -%239 = OpFunction %2 None %67 -%233 = OpLabel -%228 = OpVariable %27 Function %229 -%230 = OpVariable %231 Function %232 -%236 = OpLoad %3 %234 -%240 = OpAccessChain %68 %49 %38 -%242 = OpAccessChain %241 %52 %38 -%243 = OpAccessChain %144 %55 %38 -OpBranch %250 -%250 = OpLabel -OpStore %228 %244 -%251 = OpLoad %10 %228 -OpStore %228 %71 -%252 = OpFunctionCall %2 %66 -%253 = OpFunctionCall %2 %143 -%255 = OpAccessChain %254 %47 %38 -%256 = OpLoad %8 %255 -%259 = OpAccessChain %257 %47 %258 -%260 = OpLoad %18 %259 -%263 = OpAccessChain %262 %47 %38 %245 %38 -%264 = OpLoad %10 %263 -%266 = OpArrayLength %3 %47 5 -%267 = OpISub %3 %266 %14 -%269 = OpAccessChain %32 %47 %30 %267 %38 -%270 = OpLoad %5 %269 -%271 = OpLoad %23 %242 -%272 = OpFunctionCall %10 %203 %228 -%273 = OpConvertFToS %5 %264 -%274 = OpCompositeConstruct %33 %270 %273 %246 %247 %44 -OpStore %230 %274 -%275 = OpIAdd %3 %236 %96 -%276 = OpAccessChain %60 %230 %275 -OpStore %276 %248 -%277 = OpAccessChain %60 %230 %236 -%278 = OpLoad %5 %277 -%279 = OpFunctionCall %10 %209 %249 -%280 = OpCompositeConstruct %34 %278 %278 %278 %278 -%281 = OpConvertSToF %31 %280 -%282 = OpMatrixTimesVector %9 %256 %281 -%283 = OpCompositeConstruct %31 %282 %72 -OpStore %237 %283 +%237 = OpFunction %2 None %67 +%231 = OpLabel +%226 = OpVariable %27 Function %227 +%228 = OpVariable %229 Function %230 +%234 = OpLoad %3 %232 +%238 = OpAccessChain %68 %49 %38 +%240 = OpAccessChain %239 %52 %38 +%241 = OpAccessChain %143 %55 %38 +OpBranch %248 +%248 = OpLabel +OpStore %226 %242 +%249 = OpLoad %10 %226 +OpStore %226 %71 +%250 = OpFunctionCall %2 %66 +%251 = OpFunctionCall %2 %142 +%253 = OpAccessChain %252 %47 %38 +%254 = OpLoad %8 %253 +%257 = OpAccessChain %255 %47 %256 +%258 = OpLoad %18 %257 +%261 = OpAccessChain %260 %47 %38 %243 %38 +%262 = OpLoad %10 %261 +%264 = OpArrayLength %3 %47 5 +%265 = OpISub %3 %264 %14 +%267 = OpAccessChain %32 %47 %30 %265 %38 +%268 = OpLoad %5 %267 +%269 = OpLoad %23 %240 +%270 = OpFunctionCall %10 %201 %226 +%271 = OpConvertFToS %5 %262 +%272 = OpCompositeConstruct %33 %268 %271 %244 %245 %44 +OpStore %228 %272 +%273 = OpIAdd %3 %234 %96 +%274 = OpAccessChain %60 %228 %273 +OpStore %274 %246 +%275 = OpAccessChain %60 %228 %234 +%276 = OpLoad %5 %275 +%277 = OpFunctionCall %10 %207 %247 +%278 = OpCompositeConstruct %34 %276 %276 %276 %276 +%279 = OpConvertSToF %31 %278 +%280 = OpMatrixTimesVector %9 %254 %279 +%281 = OpCompositeConstruct %31 %280 %72 +OpStore %235 %281 OpReturn OpFunctionEnd -%286 = OpFunction %2 None %67 -%284 = OpLabel -%287 = OpAccessChain %241 %52 %38 -OpBranch %289 -%289 = OpLabel -%290 = OpAccessChain %262 %47 %38 %96 %14 -OpStore %290 %71 -%291 = OpCompositeConstruct %9 %244 %244 %244 -%292 = OpCompositeConstruct %9 %71 %71 %71 -%293 = OpCompositeConstruct %9 %72 %72 %72 -%294 = OpCompositeConstruct %9 %73 %73 %73 -%295 = OpCompositeConstruct %8 %291 %292 %293 %294 -%296 = OpAccessChain %254 %47 %38 -OpStore %296 %295 -%297 = OpCompositeConstruct %17 %38 %38 -%298 = OpCompositeConstruct %17 %96 %96 -%299 = OpCompositeConstruct %18 %297 %298 -%300 = OpAccessChain %257 %47 %258 -OpStore %300 %299 -%301 = OpAccessChain %32 %47 %30 %96 %38 -OpStore %301 %70 -OpStore %287 %288 -%302 = OpCompositeConstruct %31 %244 %244 %244 %244 -OpStore %285 %302 +%284 = OpFunction %2 None %67 +%282 = OpLabel +%285 = OpAccessChain %239 %52 %38 +OpBranch %287 +%287 = OpLabel +%288 = OpAccessChain %260 %47 %38 %96 %14 +OpStore %288 %71 +%289 = OpCompositeConstruct %9 %242 %242 %242 +%290 = OpCompositeConstruct %9 %71 %71 %71 +%291 = OpCompositeConstruct %9 %72 %72 %72 +%292 = OpCompositeConstruct %9 %73 %73 %73 +%293 = OpCompositeConstruct %8 %289 %290 %291 %292 +%294 = OpAccessChain %252 %47 %38 +OpStore %294 %293 +%295 = OpCompositeConstruct %17 %38 %38 +%296 = OpCompositeConstruct %17 %96 %96 +%297 = OpCompositeConstruct %18 %295 %296 +%298 = OpAccessChain %255 %47 %256 +OpStore %298 %297 +%299 = OpAccessChain %32 %47 %30 %96 %38 +OpStore %299 %70 +OpStore %285 %286 +%300 = OpCompositeConstruct %31 %242 %242 %242 %242 +OpStore %283 %300 OpReturn OpFunctionEnd -%306 = OpFunction %2 None %67 +%304 = OpFunction %2 None %67 +%303 = OpLabel +%301 = OpVariable %37 Function %302 +OpBranch %305 %305 = OpLabel -%303 = OpVariable %37 Function %304 -OpBranch %307 -%307 = OpLabel -%311 = OpLoad %4 %309 -%315 = OpIEqual %313 %311 %312 -%316 = OpAll %314 %315 -OpSelectionMerge %317 None -OpBranchConditional %316 %318 %317 +%309 = OpLoad %4 %307 +%313 = OpIEqual %311 %309 %310 +%314 = OpAll %312 %313 +OpSelectionMerge %315 None +OpBranchConditional %314 %316 %315 +%316 = OpLabel +OpStore %58 %306 +OpBranch %315 +%315 = OpLabel +OpControlBarrier %14 %14 %317 +OpBranch %318 %318 = OpLabel -OpStore %58 %308 -OpBranch %317 -%317 = OpLabel -OpControlBarrier %14 %14 %319 -OpBranch %320 -%320 = OpLabel -%321 = OpCompositeConstruct %31 %74 %74 %74 %74 -%322 = OpCompositeConstruct %31 %149 %149 %149 %149 -%323 = OpCompositeConstruct %36 %321 %322 -OpStore %303 %323 -%324 = OpFunctionCall %2 %216 %58 -%325 = OpFunctionCall %2 %222 %303 +%319 = OpCompositeConstruct %31 %74 %74 %74 %74 +%320 = OpCompositeConstruct %31 %147 %147 %147 %147 +%321 = OpCompositeConstruct %36 %319 %320 +OpStore %301 %321 +%322 = OpFunctionCall %2 %214 %58 +%323 = OpFunctionCall %2 %220 %301 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/tests/out/spv/atomicCompareExchange.spvasm index 82ebc2f20..05472b750 100644 --- a/tests/out/spv/atomicCompareExchange.spvasm +++ b/tests/out/spv/atomicCompareExchange.spvasm @@ -1,15 +1,15 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 126 +; Bound: 123 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %28 "test_atomic_compare_exchange_i32" -OpEntryPoint GLCompute %84 "test_atomic_compare_exchange_u32" +OpEntryPoint GLCompute %81 "test_atomic_compare_exchange_u32" OpExecutionMode %28 LocalSize 1 1 1 -OpExecutionMode %84 LocalSize 1 1 1 +OpExecutionMode %81 LocalSize 1 1 1 OpDecorate %5 ArrayStride 4 OpDecorate %7 ArrayStride 4 OpMemberDecorate %10 0 Offset 0 @@ -55,11 +55,8 @@ OpMemberDecorate %16 0 Offset 0 %48 = OpTypePointer StorageBuffer %4 %51 = OpConstant %4 1 %52 = OpConstant %3 64 -%78 = OpConstantNull %3 -%80 = OpConstantNull %3 -%82 = OpConstantNull %8 -%85 = OpTypePointer StorageBuffer %7 -%99 = OpTypePointer StorageBuffer %3 +%82 = OpTypePointer StorageBuffer %7 +%96 = OpTypePointer StorageBuffer %3 %28 = OpFunction %2 None %29 %27 = OpLabel %18 = OpVariable %19 Function %20 @@ -133,76 +130,76 @@ OpBranch %37 %38 = OpLabel OpReturn OpFunctionEnd -%84 = OpFunction %2 None %29 -%83 = OpLabel -%77 = OpVariable %19 Function %78 -%79 = OpVariable %19 Function %80 -%81 = OpVariable %25 Function %82 -%86 = OpAccessChain %85 %15 %31 +%81 = OpFunction %2 None %29 +%80 = OpLabel +%77 = OpVariable %19 Function %20 +%78 = OpVariable %19 Function %20 +%79 = OpVariable %25 Function %26 +%83 = OpAccessChain %82 %15 %31 +OpBranch %84 +%84 = OpLabel +OpStore %77 %31 +OpBranch %85 +%85 = OpLabel +OpLoopMerge %86 %88 None OpBranch %87 %87 = OpLabel -OpStore %77 %31 -OpBranch %88 -%88 = OpLabel -OpLoopMerge %89 %91 None -OpBranch %90 -%90 = OpLabel -%92 = OpLoad %3 %77 -%93 = OpULessThan %8 %92 %6 -OpSelectionMerge %94 None -OpBranchConditional %93 %94 %95 -%95 = OpLabel -OpBranch %89 -%94 = OpLabel -OpBranch %96 -%96 = OpLabel -%98 = OpLoad %3 %77 -%100 = OpAccessChain %99 %86 %98 -%101 = OpAtomicLoad %3 %100 %51 %52 -OpStore %79 %101 -OpStore %81 %33 +%89 = OpLoad %3 %77 +%90 = OpULessThan %8 %89 %6 +OpSelectionMerge %91 None +OpBranchConditional %90 %91 %92 +%92 = OpLabel +OpBranch %86 +%91 = OpLabel +OpBranch %93 +%93 = OpLabel +%95 = OpLoad %3 %77 +%97 = OpAccessChain %96 %83 %95 +%98 = OpAtomicLoad %3 %97 %51 %52 +OpStore %78 %98 +OpStore %79 %33 +OpBranch %99 +%99 = OpLabel +OpLoopMerge %100 %102 None +OpBranch %101 +%101 = OpLabel +%103 = OpLoad %8 %79 +%104 = OpLogicalNot %8 %103 +OpSelectionMerge %105 None +OpBranchConditional %104 %105 %106 +%106 = OpLabel +OpBranch %100 +%105 = OpLabel +OpBranch %107 +%107 = OpLabel +%109 = OpLoad %3 %78 +%110 = OpBitcast %9 %109 +%111 = OpFAdd %9 %110 %34 +%112 = OpBitcast %3 %111 +%113 = OpLoad %3 %77 +%114 = OpLoad %3 %78 +%116 = OpAccessChain %96 %83 %113 +%117 = OpAtomicCompareExchange %3 %116 %51 %52 %52 %112 %114 +%118 = OpIEqual %8 %117 %114 +%115 = OpCompositeConstruct %11 %117 %118 +%119 = OpCompositeExtract %3 %115 0 +OpStore %78 %119 +%120 = OpCompositeExtract %8 %115 1 +OpStore %79 %120 +OpBranch %108 +%108 = OpLabel OpBranch %102 %102 = OpLabel -OpLoopMerge %103 %105 None -OpBranch %104 -%104 = OpLabel -%106 = OpLoad %8 %81 -%107 = OpLogicalNot %8 %106 -OpSelectionMerge %108 None -OpBranchConditional %107 %108 %109 -%109 = OpLabel -OpBranch %103 -%108 = OpLabel -OpBranch %110 -%110 = OpLabel -%112 = OpLoad %3 %79 -%113 = OpBitcast %9 %112 -%114 = OpFAdd %9 %113 %34 -%115 = OpBitcast %3 %114 -%116 = OpLoad %3 %77 -%117 = OpLoad %3 %79 -%119 = OpAccessChain %99 %86 %116 -%120 = OpAtomicCompareExchange %3 %119 %51 %52 %52 %115 %117 -%121 = OpIEqual %8 %120 %117 -%118 = OpCompositeConstruct %11 %120 %121 -%122 = OpCompositeExtract %3 %118 0 -OpStore %79 %122 -%123 = OpCompositeExtract %8 %118 1 -OpStore %81 %123 -OpBranch %111 -%111 = OpLabel -OpBranch %105 -%105 = OpLabel -OpBranch %102 -%103 = OpLabel -OpBranch %97 -%97 = OpLabel -OpBranch %91 -%91 = OpLabel -%124 = OpLoad %3 %77 -%125 = OpIAdd %3 %124 %35 -OpStore %77 %125 +OpBranch %99 +%100 = OpLabel +OpBranch %94 +%94 = OpLabel OpBranch %88 -%89 = OpLabel +%88 = OpLabel +%121 = OpLoad %3 %77 +%122 = OpIAdd %3 %121 %35 +OpStore %77 %122 +OpBranch %85 +%86 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 630ae6fbc..cd56fb496 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 435 +; Bound: 432 OpCapability Shader OpCapability ImageQuery OpCapability ShaderNonUniform @@ -40,23 +40,23 @@ OpDecorate %118 NonUniform OpDecorate %120 NonUniform OpDecorate %145 NonUniform OpDecorate %147 NonUniform -OpDecorate %185 NonUniform -OpDecorate %214 NonUniform -OpDecorate %230 NonUniform -OpDecorate %246 NonUniform -OpDecorate %267 NonUniform -OpDecorate %269 NonUniform -OpDecorate %291 NonUniform -OpDecorate %293 NonUniform -OpDecorate %315 NonUniform -OpDecorate %317 NonUniform -OpDecorate %339 NonUniform -OpDecorate %341 NonUniform -OpDecorate %363 NonUniform -OpDecorate %365 NonUniform -OpDecorate %387 NonUniform -OpDecorate %389 NonUniform -OpDecorate %412 NonUniform +OpDecorate %183 NonUniform +OpDecorate %211 NonUniform +OpDecorate %227 NonUniform +OpDecorate %243 NonUniform +OpDecorate %264 NonUniform +OpDecorate %266 NonUniform +OpDecorate %288 NonUniform +OpDecorate %290 NonUniform +OpDecorate %312 NonUniform +OpDecorate %314 NonUniform +OpDecorate %336 NonUniform +OpDecorate %338 NonUniform +OpDecorate %360 NonUniform +OpDecorate %362 NonUniform +OpDecorate %384 NonUniform +OpDecorate %386 NonUniform +OpDecorate %409 NonUniform %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeStruct %3 @@ -129,14 +129,11 @@ OpDecorate %412 NonUniform %129 = OpTypePointer UniformConstant %18 %132 = OpTypeSampledImage %14 %155 = OpTypeBool -%156 = OpConstantNull %22 -%162 = OpTypeVector %155 2 -%172 = OpConstantNull %22 -%187 = OpConstantNull %22 -%200 = OpTypePointer UniformConstant %10 -%203 = OpTypeVector %3 3 -%235 = OpTypePointer UniformConstant %12 -%395 = OpTypePointer UniformConstant %16 +%161 = OpTypeVector %155 2 +%197 = OpTypePointer UniformConstant %10 +%200 = OpTypeVector %3 3 +%232 = OpTypePointer UniformConstant %12 +%392 = OpTypePointer UniformConstant %16 %68 = OpFunction %2 None %69 %61 = OpLabel %52 = OpVariable %53 Function %54 @@ -233,331 +230,331 @@ OpStore %58 %144 OpStore %58 %152 %153 = OpAccessChain %84 %28 %71 %154 = OpLoad %5 %153 -%157 = OpImageQueryLevels %26 %154 -%158 = OpULessThan %155 %74 %157 -OpSelectionMerge %159 None -OpBranchConditional %158 %160 %159 -%160 = OpLabel -%161 = OpImageQuerySizeLod %25 %154 %74 -%163 = OpULessThan %162 %83 %161 -%164 = OpAll %155 %163 -OpBranchConditional %164 %165 %159 -%165 = OpLabel -%166 = OpImageFetch %22 %154 %83 Lod %74 -OpBranch %159 +%156 = OpImageQueryLevels %26 %154 +%157 = OpULessThan %155 %74 %156 +OpSelectionMerge %158 None +OpBranchConditional %157 %159 %158 %159 = OpLabel -%167 = OpPhi %22 %156 %75 %156 %160 %166 %165 -%168 = OpLoad %22 %58 -%169 = OpFAdd %22 %168 %167 -OpStore %58 %169 -%170 = OpAccessChain %84 %28 %78 -%171 = OpLoad %5 %170 -%173 = OpImageQueryLevels %26 %171 -%174 = OpULessThan %155 %74 %173 -OpSelectionMerge %175 None -OpBranchConditional %174 %176 %175 -%176 = OpLabel -%177 = OpImageQuerySizeLod %25 %171 %74 -%178 = OpULessThan %162 %83 %177 -%179 = OpAll %155 %178 -OpBranchConditional %179 %180 %175 -%180 = OpLabel -%181 = OpImageFetch %22 %171 %83 Lod %74 -OpBranch %175 -%175 = OpLabel -%182 = OpPhi %22 %172 %159 %172 %176 %181 %180 -%183 = OpLoad %22 %58 -%184 = OpFAdd %22 %183 %182 -OpStore %58 %184 -%185 = OpAccessChain %84 %28 %79 -%186 = OpLoad %5 %185 -%188 = OpImageQueryLevels %26 %186 -%189 = OpULessThan %155 %74 %188 -OpSelectionMerge %190 None -OpBranchConditional %189 %191 %190 -%191 = OpLabel -%192 = OpImageQuerySizeLod %25 %186 %74 -%193 = OpULessThan %162 %83 %192 -%194 = OpAll %155 %193 -OpBranchConditional %194 %195 %190 -%195 = OpLabel -%196 = OpImageFetch %22 %186 %83 Lod %74 -OpBranch %190 -%190 = OpLabel -%197 = OpPhi %22 %187 %175 %187 %191 %196 %195 -%198 = OpLoad %22 %58 -%199 = OpFAdd %22 %198 %197 -OpStore %58 %199 -%201 = OpAccessChain %200 %34 %71 -%202 = OpLoad %10 %201 -%204 = OpImageQuerySizeLod %203 %202 %71 -%205 = OpCompositeExtract %3 %204 2 -%206 = OpLoad %3 %49 -%207 = OpIAdd %3 %206 %205 -OpStore %49 %207 -%208 = OpAccessChain %200 %34 %78 -%209 = OpLoad %10 %208 -%210 = OpImageQuerySizeLod %203 %209 %71 -%211 = OpCompositeExtract %3 %210 2 -%212 = OpLoad %3 %49 -%213 = OpIAdd %3 %212 %211 -OpStore %49 %213 -%214 = OpAccessChain %200 %34 %79 -%215 = OpLoad %10 %214 -%216 = OpImageQuerySizeLod %203 %215 %71 -%217 = OpCompositeExtract %3 %216 2 -%218 = OpLoad %3 %49 -%219 = OpIAdd %3 %218 %217 -OpStore %49 %219 -%220 = OpAccessChain %84 %32 %71 -%221 = OpLoad %5 %220 -%222 = OpImageQueryLevels %3 %221 -%223 = OpLoad %3 %49 -%224 = OpIAdd %3 %223 %222 -OpStore %49 %224 -%225 = OpAccessChain %84 %32 %78 -%226 = OpLoad %5 %225 -%227 = OpImageQueryLevels %3 %226 -%228 = OpLoad %3 %49 -%229 = OpIAdd %3 %228 %227 -OpStore %49 %229 -%230 = OpAccessChain %84 %32 %79 -%231 = OpLoad %5 %230 -%232 = OpImageQueryLevels %3 %231 -%233 = OpLoad %3 %49 -%234 = OpIAdd %3 %233 %232 -OpStore %49 %234 -%236 = OpAccessChain %235 %36 %71 -%237 = OpLoad %12 %236 -%238 = OpImageQuerySamples %3 %237 -%239 = OpLoad %3 %49 -%240 = OpIAdd %3 %239 %238 -OpStore %49 %240 -%241 = OpAccessChain %235 %36 %78 -%242 = OpLoad %12 %241 -%243 = OpImageQuerySamples %3 %242 -%244 = OpLoad %3 %49 -%245 = OpIAdd %3 %244 %243 -OpStore %49 %245 -%246 = OpAccessChain %235 %36 %79 -%247 = OpLoad %12 %246 -%248 = OpImageQuerySamples %3 %247 -%249 = OpLoad %3 %49 -%250 = OpIAdd %3 %249 %248 -OpStore %49 %250 -%251 = OpAccessChain %84 %32 %71 -%252 = OpLoad %5 %251 -%253 = OpAccessChain %102 %42 %71 -%254 = OpLoad %18 %253 -%255 = OpSampledImage %105 %252 %254 -%256 = OpImageSampleImplicitLod %22 %255 %82 -%257 = OpLoad %22 %58 -%258 = OpFAdd %22 %257 %256 -OpStore %58 %258 -%259 = OpAccessChain %84 %32 %78 -%260 = OpLoad %5 %259 -%261 = OpAccessChain %102 %42 %78 -%262 = OpLoad %18 %261 -%263 = OpSampledImage %105 %260 %262 -%264 = OpImageSampleImplicitLod %22 %263 %82 -%265 = OpLoad %22 %58 -%266 = OpFAdd %22 %265 %264 -OpStore %58 %266 -%267 = OpAccessChain %84 %32 %79 -%268 = OpLoad %5 %267 -%269 = OpAccessChain %102 %42 %79 -%270 = OpLoad %18 %269 -%271 = OpSampledImage %105 %268 %270 -%272 = OpImageSampleImplicitLod %22 %271 %82 -%273 = OpLoad %22 %58 -%274 = OpFAdd %22 %273 %272 -OpStore %58 %274 -%275 = OpAccessChain %84 %32 %71 -%276 = OpLoad %5 %275 -%277 = OpAccessChain %102 %42 %71 -%278 = OpLoad %18 %277 -%279 = OpSampledImage %105 %276 %278 -%280 = OpImageSampleImplicitLod %22 %279 %82 Bias %73 -%281 = OpLoad %22 %58 -%282 = OpFAdd %22 %281 %280 -OpStore %58 %282 -%283 = OpAccessChain %84 %32 %78 -%284 = OpLoad %5 %283 -%285 = OpAccessChain %102 %42 %78 -%286 = OpLoad %18 %285 -%287 = OpSampledImage %105 %284 %286 -%288 = OpImageSampleImplicitLod %22 %287 %82 Bias %73 -%289 = OpLoad %22 %58 -%290 = OpFAdd %22 %289 %288 -OpStore %58 %290 -%291 = OpAccessChain %84 %32 %79 -%292 = OpLoad %5 %291 -%293 = OpAccessChain %102 %42 %79 -%294 = OpLoad %18 %293 -%295 = OpSampledImage %105 %292 %294 -%296 = OpImageSampleImplicitLod %22 %295 %82 Bias %73 -%297 = OpLoad %22 %58 -%298 = OpFAdd %22 %297 %296 -OpStore %58 %298 -%299 = OpAccessChain %126 %38 %71 -%300 = OpLoad %14 %299 -%301 = OpAccessChain %129 %44 %71 -%302 = OpLoad %18 %301 -%303 = OpSampledImage %132 %300 %302 -%304 = OpImageSampleDrefImplicitLod %6 %303 %82 %73 -%305 = OpLoad %6 %55 -%306 = OpFAdd %6 %305 %304 -OpStore %55 %306 -%307 = OpAccessChain %126 %38 %78 -%308 = OpLoad %14 %307 -%309 = OpAccessChain %129 %44 %78 -%310 = OpLoad %18 %309 -%311 = OpSampledImage %132 %308 %310 -%312 = OpImageSampleDrefImplicitLod %6 %311 %82 %73 -%313 = OpLoad %6 %55 -%314 = OpFAdd %6 %313 %312 -OpStore %55 %314 -%315 = OpAccessChain %126 %38 %79 -%316 = OpLoad %14 %315 -%317 = OpAccessChain %129 %44 %79 -%318 = OpLoad %18 %317 -%319 = OpSampledImage %132 %316 %318 -%320 = OpImageSampleDrefImplicitLod %6 %319 %82 %73 -%321 = OpLoad %6 %55 -%322 = OpFAdd %6 %321 %320 -OpStore %55 %322 -%323 = OpAccessChain %126 %38 %71 -%324 = OpLoad %14 %323 -%325 = OpAccessChain %129 %44 %71 -%326 = OpLoad %18 %325 -%327 = OpSampledImage %132 %324 %326 -%328 = OpImageSampleDrefExplicitLod %6 %327 %82 %73 Lod %73 -%329 = OpLoad %6 %55 -%330 = OpFAdd %6 %329 %328 -OpStore %55 %330 -%331 = OpAccessChain %126 %38 %78 -%332 = OpLoad %14 %331 -%333 = OpAccessChain %129 %44 %78 -%334 = OpLoad %18 %333 -%335 = OpSampledImage %132 %332 %334 -%336 = OpImageSampleDrefExplicitLod %6 %335 %82 %73 Lod %73 -%337 = OpLoad %6 %55 -%338 = OpFAdd %6 %337 %336 -OpStore %55 %338 -%339 = OpAccessChain %126 %38 %79 -%340 = OpLoad %14 %339 -%341 = OpAccessChain %129 %44 %79 -%342 = OpLoad %18 %341 -%343 = OpSampledImage %132 %340 %342 -%344 = OpImageSampleDrefExplicitLod %6 %343 %82 %73 Lod %73 -%345 = OpLoad %6 %55 -%346 = OpFAdd %6 %345 %344 -OpStore %55 %346 -%347 = OpAccessChain %84 %32 %71 -%348 = OpLoad %5 %347 -%349 = OpAccessChain %102 %42 %71 -%350 = OpLoad %18 %349 -%351 = OpSampledImage %105 %348 %350 -%352 = OpImageSampleExplicitLod %22 %351 %82 Grad %82 %82 -%353 = OpLoad %22 %58 -%354 = OpFAdd %22 %353 %352 -OpStore %58 %354 -%355 = OpAccessChain %84 %32 %78 -%356 = OpLoad %5 %355 -%357 = OpAccessChain %102 %42 %78 -%358 = OpLoad %18 %357 -%359 = OpSampledImage %105 %356 %358 -%360 = OpImageSampleExplicitLod %22 %359 %82 Grad %82 %82 -%361 = OpLoad %22 %58 -%362 = OpFAdd %22 %361 %360 -OpStore %58 %362 -%363 = OpAccessChain %84 %32 %79 -%364 = OpLoad %5 %363 -%365 = OpAccessChain %102 %42 %79 -%366 = OpLoad %18 %365 -%367 = OpSampledImage %105 %364 %366 -%368 = OpImageSampleExplicitLod %22 %367 %82 Grad %82 %82 -%369 = OpLoad %22 %58 -%370 = OpFAdd %22 %369 %368 -OpStore %58 %370 -%371 = OpAccessChain %84 %32 %71 -%372 = OpLoad %5 %371 -%373 = OpAccessChain %102 %42 %71 -%374 = OpLoad %18 %373 -%375 = OpSampledImage %105 %372 %374 -%376 = OpImageSampleExplicitLod %22 %375 %82 Lod %73 -%377 = OpLoad %22 %58 -%378 = OpFAdd %22 %377 %376 -OpStore %58 %378 -%379 = OpAccessChain %84 %32 %78 -%380 = OpLoad %5 %379 -%381 = OpAccessChain %102 %42 %78 -%382 = OpLoad %18 %381 -%383 = OpSampledImage %105 %380 %382 -%384 = OpImageSampleExplicitLod %22 %383 %82 Lod %73 -%385 = OpLoad %22 %58 -%386 = OpFAdd %22 %385 %384 -OpStore %58 %386 -%387 = OpAccessChain %84 %32 %79 -%388 = OpLoad %5 %387 -%389 = OpAccessChain %102 %42 %79 -%390 = OpLoad %18 %389 -%391 = OpSampledImage %105 %388 %390 -%392 = OpImageSampleExplicitLod %22 %391 %82 Lod %73 -%393 = OpLoad %22 %58 -%394 = OpFAdd %22 %393 %392 -OpStore %58 %394 -%396 = OpAccessChain %395 %40 %71 -%397 = OpLoad %16 %396 -%398 = OpLoad %22 %58 -%399 = OpImageQuerySize %25 %397 -%400 = OpULessThan %162 %83 %399 -%401 = OpAll %155 %400 -OpSelectionMerge %402 None -OpBranchConditional %401 %403 %402 -%403 = OpLabel -OpImageWrite %397 %83 %398 -OpBranch %402 -%402 = OpLabel -%404 = OpAccessChain %395 %40 %78 -%405 = OpLoad %16 %404 -%406 = OpLoad %22 %58 -%407 = OpImageQuerySize %25 %405 -%408 = OpULessThan %162 %83 %407 -%409 = OpAll %155 %408 -OpSelectionMerge %410 None -OpBranchConditional %409 %411 %410 -%411 = OpLabel -OpImageWrite %405 %83 %406 -OpBranch %410 -%410 = OpLabel -%412 = OpAccessChain %395 %40 %79 -%413 = OpLoad %16 %412 -%414 = OpLoad %22 %58 -%415 = OpImageQuerySize %25 %413 -%416 = OpULessThan %162 %83 %415 -%417 = OpAll %155 %416 -OpSelectionMerge %418 None -OpBranchConditional %417 %419 %418 -%419 = OpLabel -OpImageWrite %413 %83 %414 -OpBranch %418 -%418 = OpLabel -%420 = OpLoad %23 %52 -%421 = OpLoad %3 %49 -%422 = OpCompositeConstruct %23 %421 %421 -%423 = OpIAdd %23 %420 %422 -%424 = OpConvertUToF %24 %423 -%425 = OpLoad %22 %58 -%426 = OpCompositeExtract %6 %424 0 -%427 = OpCompositeExtract %6 %424 1 -%428 = OpCompositeExtract %6 %424 0 -%429 = OpCompositeExtract %6 %424 1 -%430 = OpCompositeConstruct %22 %426 %427 %428 %429 -%431 = OpFAdd %22 %425 %430 -%432 = OpLoad %6 %55 -%433 = OpCompositeConstruct %22 %432 %432 %432 %432 -%434 = OpFAdd %22 %431 %433 -OpStore %66 %434 +%160 = OpImageQuerySizeLod %25 %154 %74 +%162 = OpULessThan %161 %83 %160 +%163 = OpAll %155 %162 +OpBranchConditional %163 %164 %158 +%164 = OpLabel +%165 = OpImageFetch %22 %154 %83 Lod %74 +OpBranch %158 +%158 = OpLabel +%166 = OpPhi %22 %60 %75 %60 %159 %165 %164 +%167 = OpLoad %22 %58 +%168 = OpFAdd %22 %167 %166 +OpStore %58 %168 +%169 = OpAccessChain %84 %28 %78 +%170 = OpLoad %5 %169 +%171 = OpImageQueryLevels %26 %170 +%172 = OpULessThan %155 %74 %171 +OpSelectionMerge %173 None +OpBranchConditional %172 %174 %173 +%174 = OpLabel +%175 = OpImageQuerySizeLod %25 %170 %74 +%176 = OpULessThan %161 %83 %175 +%177 = OpAll %155 %176 +OpBranchConditional %177 %178 %173 +%178 = OpLabel +%179 = OpImageFetch %22 %170 %83 Lod %74 +OpBranch %173 +%173 = OpLabel +%180 = OpPhi %22 %60 %158 %60 %174 %179 %178 +%181 = OpLoad %22 %58 +%182 = OpFAdd %22 %181 %180 +OpStore %58 %182 +%183 = OpAccessChain %84 %28 %79 +%184 = OpLoad %5 %183 +%185 = OpImageQueryLevels %26 %184 +%186 = OpULessThan %155 %74 %185 +OpSelectionMerge %187 None +OpBranchConditional %186 %188 %187 +%188 = OpLabel +%189 = OpImageQuerySizeLod %25 %184 %74 +%190 = OpULessThan %161 %83 %189 +%191 = OpAll %155 %190 +OpBranchConditional %191 %192 %187 +%192 = OpLabel +%193 = OpImageFetch %22 %184 %83 Lod %74 +OpBranch %187 +%187 = OpLabel +%194 = OpPhi %22 %60 %173 %60 %188 %193 %192 +%195 = OpLoad %22 %58 +%196 = OpFAdd %22 %195 %194 +OpStore %58 %196 +%198 = OpAccessChain %197 %34 %71 +%199 = OpLoad %10 %198 +%201 = OpImageQuerySizeLod %200 %199 %71 +%202 = OpCompositeExtract %3 %201 2 +%203 = OpLoad %3 %49 +%204 = OpIAdd %3 %203 %202 +OpStore %49 %204 +%205 = OpAccessChain %197 %34 %78 +%206 = OpLoad %10 %205 +%207 = OpImageQuerySizeLod %200 %206 %71 +%208 = OpCompositeExtract %3 %207 2 +%209 = OpLoad %3 %49 +%210 = OpIAdd %3 %209 %208 +OpStore %49 %210 +%211 = OpAccessChain %197 %34 %79 +%212 = OpLoad %10 %211 +%213 = OpImageQuerySizeLod %200 %212 %71 +%214 = OpCompositeExtract %3 %213 2 +%215 = OpLoad %3 %49 +%216 = OpIAdd %3 %215 %214 +OpStore %49 %216 +%217 = OpAccessChain %84 %32 %71 +%218 = OpLoad %5 %217 +%219 = OpImageQueryLevels %3 %218 +%220 = OpLoad %3 %49 +%221 = OpIAdd %3 %220 %219 +OpStore %49 %221 +%222 = OpAccessChain %84 %32 %78 +%223 = OpLoad %5 %222 +%224 = OpImageQueryLevels %3 %223 +%225 = OpLoad %3 %49 +%226 = OpIAdd %3 %225 %224 +OpStore %49 %226 +%227 = OpAccessChain %84 %32 %79 +%228 = OpLoad %5 %227 +%229 = OpImageQueryLevels %3 %228 +%230 = OpLoad %3 %49 +%231 = OpIAdd %3 %230 %229 +OpStore %49 %231 +%233 = OpAccessChain %232 %36 %71 +%234 = OpLoad %12 %233 +%235 = OpImageQuerySamples %3 %234 +%236 = OpLoad %3 %49 +%237 = OpIAdd %3 %236 %235 +OpStore %49 %237 +%238 = OpAccessChain %232 %36 %78 +%239 = OpLoad %12 %238 +%240 = OpImageQuerySamples %3 %239 +%241 = OpLoad %3 %49 +%242 = OpIAdd %3 %241 %240 +OpStore %49 %242 +%243 = OpAccessChain %232 %36 %79 +%244 = OpLoad %12 %243 +%245 = OpImageQuerySamples %3 %244 +%246 = OpLoad %3 %49 +%247 = OpIAdd %3 %246 %245 +OpStore %49 %247 +%248 = OpAccessChain %84 %32 %71 +%249 = OpLoad %5 %248 +%250 = OpAccessChain %102 %42 %71 +%251 = OpLoad %18 %250 +%252 = OpSampledImage %105 %249 %251 +%253 = OpImageSampleImplicitLod %22 %252 %82 +%254 = OpLoad %22 %58 +%255 = OpFAdd %22 %254 %253 +OpStore %58 %255 +%256 = OpAccessChain %84 %32 %78 +%257 = OpLoad %5 %256 +%258 = OpAccessChain %102 %42 %78 +%259 = OpLoad %18 %258 +%260 = OpSampledImage %105 %257 %259 +%261 = OpImageSampleImplicitLod %22 %260 %82 +%262 = OpLoad %22 %58 +%263 = OpFAdd %22 %262 %261 +OpStore %58 %263 +%264 = OpAccessChain %84 %32 %79 +%265 = OpLoad %5 %264 +%266 = OpAccessChain %102 %42 %79 +%267 = OpLoad %18 %266 +%268 = OpSampledImage %105 %265 %267 +%269 = OpImageSampleImplicitLod %22 %268 %82 +%270 = OpLoad %22 %58 +%271 = OpFAdd %22 %270 %269 +OpStore %58 %271 +%272 = OpAccessChain %84 %32 %71 +%273 = OpLoad %5 %272 +%274 = OpAccessChain %102 %42 %71 +%275 = OpLoad %18 %274 +%276 = OpSampledImage %105 %273 %275 +%277 = OpImageSampleImplicitLod %22 %276 %82 Bias %73 +%278 = OpLoad %22 %58 +%279 = OpFAdd %22 %278 %277 +OpStore %58 %279 +%280 = OpAccessChain %84 %32 %78 +%281 = OpLoad %5 %280 +%282 = OpAccessChain %102 %42 %78 +%283 = OpLoad %18 %282 +%284 = OpSampledImage %105 %281 %283 +%285 = OpImageSampleImplicitLod %22 %284 %82 Bias %73 +%286 = OpLoad %22 %58 +%287 = OpFAdd %22 %286 %285 +OpStore %58 %287 +%288 = OpAccessChain %84 %32 %79 +%289 = OpLoad %5 %288 +%290 = OpAccessChain %102 %42 %79 +%291 = OpLoad %18 %290 +%292 = OpSampledImage %105 %289 %291 +%293 = OpImageSampleImplicitLod %22 %292 %82 Bias %73 +%294 = OpLoad %22 %58 +%295 = OpFAdd %22 %294 %293 +OpStore %58 %295 +%296 = OpAccessChain %126 %38 %71 +%297 = OpLoad %14 %296 +%298 = OpAccessChain %129 %44 %71 +%299 = OpLoad %18 %298 +%300 = OpSampledImage %132 %297 %299 +%301 = OpImageSampleDrefImplicitLod %6 %300 %82 %73 +%302 = OpLoad %6 %55 +%303 = OpFAdd %6 %302 %301 +OpStore %55 %303 +%304 = OpAccessChain %126 %38 %78 +%305 = OpLoad %14 %304 +%306 = OpAccessChain %129 %44 %78 +%307 = OpLoad %18 %306 +%308 = OpSampledImage %132 %305 %307 +%309 = OpImageSampleDrefImplicitLod %6 %308 %82 %73 +%310 = OpLoad %6 %55 +%311 = OpFAdd %6 %310 %309 +OpStore %55 %311 +%312 = OpAccessChain %126 %38 %79 +%313 = OpLoad %14 %312 +%314 = OpAccessChain %129 %44 %79 +%315 = OpLoad %18 %314 +%316 = OpSampledImage %132 %313 %315 +%317 = OpImageSampleDrefImplicitLod %6 %316 %82 %73 +%318 = OpLoad %6 %55 +%319 = OpFAdd %6 %318 %317 +OpStore %55 %319 +%320 = OpAccessChain %126 %38 %71 +%321 = OpLoad %14 %320 +%322 = OpAccessChain %129 %44 %71 +%323 = OpLoad %18 %322 +%324 = OpSampledImage %132 %321 %323 +%325 = OpImageSampleDrefExplicitLod %6 %324 %82 %73 Lod %73 +%326 = OpLoad %6 %55 +%327 = OpFAdd %6 %326 %325 +OpStore %55 %327 +%328 = OpAccessChain %126 %38 %78 +%329 = OpLoad %14 %328 +%330 = OpAccessChain %129 %44 %78 +%331 = OpLoad %18 %330 +%332 = OpSampledImage %132 %329 %331 +%333 = OpImageSampleDrefExplicitLod %6 %332 %82 %73 Lod %73 +%334 = OpLoad %6 %55 +%335 = OpFAdd %6 %334 %333 +OpStore %55 %335 +%336 = OpAccessChain %126 %38 %79 +%337 = OpLoad %14 %336 +%338 = OpAccessChain %129 %44 %79 +%339 = OpLoad %18 %338 +%340 = OpSampledImage %132 %337 %339 +%341 = OpImageSampleDrefExplicitLod %6 %340 %82 %73 Lod %73 +%342 = OpLoad %6 %55 +%343 = OpFAdd %6 %342 %341 +OpStore %55 %343 +%344 = OpAccessChain %84 %32 %71 +%345 = OpLoad %5 %344 +%346 = OpAccessChain %102 %42 %71 +%347 = OpLoad %18 %346 +%348 = OpSampledImage %105 %345 %347 +%349 = OpImageSampleExplicitLod %22 %348 %82 Grad %82 %82 +%350 = OpLoad %22 %58 +%351 = OpFAdd %22 %350 %349 +OpStore %58 %351 +%352 = OpAccessChain %84 %32 %78 +%353 = OpLoad %5 %352 +%354 = OpAccessChain %102 %42 %78 +%355 = OpLoad %18 %354 +%356 = OpSampledImage %105 %353 %355 +%357 = OpImageSampleExplicitLod %22 %356 %82 Grad %82 %82 +%358 = OpLoad %22 %58 +%359 = OpFAdd %22 %358 %357 +OpStore %58 %359 +%360 = OpAccessChain %84 %32 %79 +%361 = OpLoad %5 %360 +%362 = OpAccessChain %102 %42 %79 +%363 = OpLoad %18 %362 +%364 = OpSampledImage %105 %361 %363 +%365 = OpImageSampleExplicitLod %22 %364 %82 Grad %82 %82 +%366 = OpLoad %22 %58 +%367 = OpFAdd %22 %366 %365 +OpStore %58 %367 +%368 = OpAccessChain %84 %32 %71 +%369 = OpLoad %5 %368 +%370 = OpAccessChain %102 %42 %71 +%371 = OpLoad %18 %370 +%372 = OpSampledImage %105 %369 %371 +%373 = OpImageSampleExplicitLod %22 %372 %82 Lod %73 +%374 = OpLoad %22 %58 +%375 = OpFAdd %22 %374 %373 +OpStore %58 %375 +%376 = OpAccessChain %84 %32 %78 +%377 = OpLoad %5 %376 +%378 = OpAccessChain %102 %42 %78 +%379 = OpLoad %18 %378 +%380 = OpSampledImage %105 %377 %379 +%381 = OpImageSampleExplicitLod %22 %380 %82 Lod %73 +%382 = OpLoad %22 %58 +%383 = OpFAdd %22 %382 %381 +OpStore %58 %383 +%384 = OpAccessChain %84 %32 %79 +%385 = OpLoad %5 %384 +%386 = OpAccessChain %102 %42 %79 +%387 = OpLoad %18 %386 +%388 = OpSampledImage %105 %385 %387 +%389 = OpImageSampleExplicitLod %22 %388 %82 Lod %73 +%390 = OpLoad %22 %58 +%391 = OpFAdd %22 %390 %389 +OpStore %58 %391 +%393 = OpAccessChain %392 %40 %71 +%394 = OpLoad %16 %393 +%395 = OpLoad %22 %58 +%396 = OpImageQuerySize %25 %394 +%397 = OpULessThan %161 %83 %396 +%398 = OpAll %155 %397 +OpSelectionMerge %399 None +OpBranchConditional %398 %400 %399 +%400 = OpLabel +OpImageWrite %394 %83 %395 +OpBranch %399 +%399 = OpLabel +%401 = OpAccessChain %392 %40 %78 +%402 = OpLoad %16 %401 +%403 = OpLoad %22 %58 +%404 = OpImageQuerySize %25 %402 +%405 = OpULessThan %161 %83 %404 +%406 = OpAll %155 %405 +OpSelectionMerge %407 None +OpBranchConditional %406 %408 %407 +%408 = OpLabel +OpImageWrite %402 %83 %403 +OpBranch %407 +%407 = OpLabel +%409 = OpAccessChain %392 %40 %79 +%410 = OpLoad %16 %409 +%411 = OpLoad %22 %58 +%412 = OpImageQuerySize %25 %410 +%413 = OpULessThan %161 %83 %412 +%414 = OpAll %155 %413 +OpSelectionMerge %415 None +OpBranchConditional %414 %416 %415 +%416 = OpLabel +OpImageWrite %410 %83 %411 +OpBranch %415 +%415 = OpLabel +%417 = OpLoad %23 %52 +%418 = OpLoad %3 %49 +%419 = OpCompositeConstruct %23 %418 %418 +%420 = OpIAdd %23 %417 %419 +%421 = OpConvertUToF %24 %420 +%422 = OpLoad %22 %58 +%423 = OpCompositeExtract %6 %421 0 +%424 = OpCompositeExtract %6 %421 1 +%425 = OpCompositeExtract %6 %421 0 +%426 = OpCompositeExtract %6 %421 1 +%427 = OpCompositeConstruct %22 %423 %424 %425 %426 +%428 = OpFAdd %22 %422 %427 +%429 = OpLoad %6 %55 +%430 = OpCompositeConstruct %22 %429 %429 %429 %429 +%431 = OpFAdd %22 %428 %430 +OpStore %66 %431 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-buffer-arrays.spvasm b/tests/out/spv/binding-buffer-arrays.spvasm index 83a676a9e..00d5b0fcf 100644 --- a/tests/out/spv/binding-buffer-arrays.spvasm +++ b/tests/out/spv/binding-buffer-arrays.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 65 +; Bound: 63 OpCapability Shader OpCapability ShaderNonUniform OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -24,7 +24,7 @@ OpMemberDecorate %16 0 Offset 0 OpDecorate %23 Location 0 OpDecorate %23 Flat OpDecorate %26 Location 0 -OpDecorate %56 NonUniform +OpDecorate %55 NonUniform %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeStruct %3 @@ -55,8 +55,6 @@ OpDecorate %56 NonUniform %39 = OpTypePointer StorageBuffer %5 %40 = OpTypePointer StorageBuffer %3 %46 = OpTypeBool -%48 = OpConstantNull %3 -%57 = OpConstantNull %3 %28 = OpFunction %2 None %29 %21 = OpLabel %18 = OpVariable %19 Function %20 @@ -75,30 +73,30 @@ OpStore %18 %31 %44 = OpIAdd %3 %43 %42 OpStore %18 %44 %45 = OpULessThan %46 %37 %7 -OpSelectionMerge %49 None -OpBranchConditional %45 %50 %49 -%50 = OpLabel -%47 = OpAccessChain %40 %11 %37 %31 -%51 = OpLoad %3 %47 -OpBranch %49 +OpSelectionMerge %48 None +OpBranchConditional %45 %49 %48 %49 = OpLabel -%52 = OpPhi %3 %48 %34 %51 %50 -%53 = OpLoad %3 %18 -%54 = OpIAdd %3 %53 %52 -OpStore %18 %54 -%55 = OpULessThan %46 %38 %7 -OpSelectionMerge %58 None -OpBranchConditional %55 %59 %58 -%59 = OpLabel -%56 = OpAccessChain %40 %11 %38 %31 -%60 = OpLoad %3 %56 -OpBranch %58 -%58 = OpLabel -%61 = OpPhi %3 %57 %49 %60 %59 +%47 = OpAccessChain %40 %11 %37 %31 +%50 = OpLoad %3 %47 +OpBranch %48 +%48 = OpLabel +%51 = OpPhi %3 %20 %34 %50 %49 +%52 = OpLoad %3 %18 +%53 = OpIAdd %3 %52 %51 +OpStore %18 %53 +%54 = OpULessThan %46 %38 %7 +OpSelectionMerge %56 None +OpBranchConditional %54 %57 %56 +%57 = OpLabel +%55 = OpAccessChain %40 %11 %38 %31 +%58 = OpLoad %3 %55 +OpBranch %56 +%56 = OpLabel +%59 = OpPhi %3 %20 %48 %58 %57 +%60 = OpLoad %3 %18 +%61 = OpIAdd %3 %60 %59 +OpStore %18 %61 %62 = OpLoad %3 %18 -%63 = OpIAdd %3 %62 %61 -OpStore %18 %63 -%64 = OpLoad %3 %18 -OpStore %26 %64 +OpStore %26 %62 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 30e77fdcd..94ee9e8d9 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 216 +; Bound: 209 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %46 "main" %43 -OpExecutionMode %46 LocalSize 64 1 1 +OpEntryPoint GLCompute %39 "main" %36 +OpExecutionMode %39 LocalSize 64 1 1 OpMemberName %6 0 "pos" OpMemberName %6 1 "vel" OpName %6 "Particle" @@ -27,16 +27,16 @@ OpName %16 "particlesSrc" OpName %18 "particlesDst" OpName %19 "vPos" OpName %22 "vVel" -OpName %24 "cMass" -OpName %26 "cVel" -OpName %28 "colVel" -OpName %30 "cMassCount" -OpName %33 "cVelCount" -OpName %35 "pos" -OpName %37 "vel" -OpName %39 "i" -OpName %43 "global_invocation_id" -OpName %46 "main" +OpName %23 "cMass" +OpName %24 "cVel" +OpName %25 "colVel" +OpName %26 "cMassCount" +OpName %29 "cVelCount" +OpName %30 "pos" +OpName %31 "vel" +OpName %32 "i" +OpName %36 "global_invocation_id" +OpName %39 "main" OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 8 OpMemberDecorate %7 0 Offset 0 @@ -59,7 +59,7 @@ OpDecorate %9 Block OpDecorate %18 DescriptorSet 0 OpDecorate %18 Binding 2 OpDecorate %9 Block -OpDecorate %43 BuiltIn GlobalInvocationId +OpDecorate %36 BuiltIn GlobalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 %5 = OpTypeFloat 32 @@ -79,269 +79,262 @@ OpDecorate %43 BuiltIn GlobalInvocationId %18 = OpVariable %17 StorageBuffer %20 = OpTypePointer Function %4 %21 = OpConstantNull %4 -%23 = OpConstantNull %4 -%25 = OpConstantNull %4 -%27 = OpConstantNull %4 -%29 = OpConstantNull %4 -%31 = OpTypePointer Function %11 -%32 = OpConstantNull %11 -%34 = OpConstantNull %11 -%36 = OpConstantNull %4 -%38 = OpConstantNull %4 -%40 = OpTypePointer Function %3 -%41 = OpConstantNull %3 -%44 = OpTypePointer Input %10 -%43 = OpVariable %44 Input -%47 = OpTypeFunction %2 -%48 = OpTypePointer Uniform %7 -%49 = OpConstant %3 0 -%51 = OpConstant %5 0.0 -%52 = OpConstant %11 0 -%53 = OpConstant %11 1 -%54 = OpConstant %3 1 -%55 = OpConstant %5 0.1 -%56 = OpConstant %5 -1.0 -%57 = OpConstant %5 1.0 -%60 = OpTypeBool -%64 = OpTypePointer StorageBuffer %8 -%65 = OpTypePointer StorageBuffer %6 -%66 = OpTypePointer StorageBuffer %4 -%95 = OpTypePointer Uniform %5 -%109 = OpConstant %3 2 -%123 = OpConstant %3 3 -%158 = OpConstant %3 4 -%164 = OpConstant %3 5 -%170 = OpConstant %3 6 -%187 = OpTypePointer Function %5 -%46 = OpFunction %2 None %47 -%42 = OpLabel -%39 = OpVariable %40 Function %41 -%33 = OpVariable %31 Function %34 -%26 = OpVariable %20 Function %27 +%27 = OpTypePointer Function %11 +%28 = OpConstantNull %11 +%33 = OpTypePointer Function %3 +%34 = OpConstantNull %3 +%37 = OpTypePointer Input %10 +%36 = OpVariable %37 Input +%40 = OpTypeFunction %2 +%41 = OpTypePointer Uniform %7 +%42 = OpConstant %3 0 +%44 = OpConstant %5 0.0 +%45 = OpConstant %11 0 +%46 = OpConstant %11 1 +%47 = OpConstant %3 1 +%48 = OpConstant %5 0.1 +%49 = OpConstant %5 -1.0 +%50 = OpConstant %5 1.0 +%53 = OpTypeBool +%57 = OpTypePointer StorageBuffer %8 +%58 = OpTypePointer StorageBuffer %6 +%59 = OpTypePointer StorageBuffer %4 +%88 = OpTypePointer Uniform %5 +%102 = OpConstant %3 2 +%116 = OpConstant %3 3 +%151 = OpConstant %3 4 +%157 = OpConstant %3 5 +%163 = OpConstant %3 6 +%180 = OpTypePointer Function %5 +%39 = OpFunction %2 None %40 +%35 = OpLabel +%32 = OpVariable %33 Function %34 +%29 = OpVariable %27 Function %28 +%24 = OpVariable %20 Function %21 %19 = OpVariable %20 Function %21 -%35 = OpVariable %20 Function %36 -%28 = OpVariable %20 Function %29 -%22 = OpVariable %20 Function %23 -%37 = OpVariable %20 Function %38 -%30 = OpVariable %31 Function %32 -%24 = OpVariable %20 Function %25 -%45 = OpLoad %10 %43 -%50 = OpAccessChain %48 %13 %49 -OpBranch %58 -%58 = OpLabel -%59 = OpCompositeExtract %3 %45 0 -%61 = OpUGreaterThanEqual %60 %59 %12 -OpSelectionMerge %62 None -OpBranchConditional %61 %63 %62 -%63 = OpLabel +%30 = OpVariable %20 Function %21 +%25 = OpVariable %20 Function %21 +%22 = OpVariable %20 Function %21 +%31 = OpVariable %20 Function %21 +%26 = OpVariable %27 Function %28 +%23 = OpVariable %20 Function %21 +%38 = OpLoad %10 %36 +%43 = OpAccessChain %41 %13 %42 +OpBranch %51 +%51 = OpLabel +%52 = OpCompositeExtract %3 %38 0 +%54 = OpUGreaterThanEqual %53 %52 %12 +OpSelectionMerge %55 None +OpBranchConditional %54 %56 %55 +%56 = OpLabel OpReturn -%62 = OpLabel -%67 = OpAccessChain %66 %16 %49 %59 %49 -%68 = OpLoad %4 %67 -OpStore %19 %68 -%69 = OpAccessChain %66 %16 %49 %59 %54 -%70 = OpLoad %4 %69 -OpStore %22 %70 -%71 = OpCompositeConstruct %4 %51 %51 -OpStore %24 %71 -%72 = OpCompositeConstruct %4 %51 %51 -OpStore %26 %72 -%73 = OpCompositeConstruct %4 %51 %51 -OpStore %28 %73 -OpStore %30 %52 -OpStore %33 %52 -OpStore %39 %49 -OpBranch %74 +%55 = OpLabel +%60 = OpAccessChain %59 %16 %42 %52 %42 +%61 = OpLoad %4 %60 +OpStore %19 %61 +%62 = OpAccessChain %59 %16 %42 %52 %47 +%63 = OpLoad %4 %62 +OpStore %22 %63 +%64 = OpCompositeConstruct %4 %44 %44 +OpStore %23 %64 +%65 = OpCompositeConstruct %4 %44 %44 +OpStore %24 %65 +%66 = OpCompositeConstruct %4 %44 %44 +OpStore %25 %66 +OpStore %26 %45 +OpStore %29 %45 +OpStore %32 %42 +OpBranch %67 +%67 = OpLabel +OpLoopMerge %68 %70 None +OpBranch %69 +%69 = OpLabel +%71 = OpLoad %3 %32 +%72 = OpUGreaterThanEqual %53 %71 %12 +OpSelectionMerge %73 None +OpBranchConditional %72 %74 %73 %74 = OpLabel -OpLoopMerge %75 %77 None -OpBranch %76 -%76 = OpLabel -%78 = OpLoad %3 %39 -%79 = OpUGreaterThanEqual %60 %78 %12 -OpSelectionMerge %80 None -OpBranchConditional %79 %81 %80 -%81 = OpLabel -OpBranch %75 -%80 = OpLabel -%82 = OpLoad %3 %39 -%83 = OpIEqual %60 %82 %59 -OpSelectionMerge %84 None -OpBranchConditional %83 %85 %84 -%85 = OpLabel -OpBranch %77 -%84 = OpLabel -%86 = OpLoad %3 %39 -%87 = OpAccessChain %66 %16 %49 %86 %49 -%88 = OpLoad %4 %87 -OpStore %35 %88 -%89 = OpLoad %3 %39 -%90 = OpAccessChain %66 %16 %49 %89 %54 -%91 = OpLoad %4 %90 -OpStore %37 %91 -%92 = OpLoad %4 %35 -%93 = OpLoad %4 %19 -%94 = OpExtInst %5 %1 Distance %92 %93 -%96 = OpAccessChain %95 %50 %54 -%97 = OpLoad %5 %96 -%98 = OpFOrdLessThan %60 %94 %97 -OpSelectionMerge %99 None -OpBranchConditional %98 %100 %99 -%100 = OpLabel -%101 = OpLoad %4 %24 -%102 = OpLoad %4 %35 -%103 = OpFAdd %4 %101 %102 -OpStore %24 %103 -%104 = OpLoad %11 %30 -%105 = OpIAdd %11 %104 %53 -OpStore %30 %105 -OpBranch %99 -%99 = OpLabel -%106 = OpLoad %4 %35 -%107 = OpLoad %4 %19 -%108 = OpExtInst %5 %1 Distance %106 %107 -%110 = OpAccessChain %95 %50 %109 -%111 = OpLoad %5 %110 -%112 = OpFOrdLessThan %60 %108 %111 -OpSelectionMerge %113 None -OpBranchConditional %112 %114 %113 -%114 = OpLabel -%115 = OpLoad %4 %28 -%116 = OpLoad %4 %35 -%117 = OpLoad %4 %19 -%118 = OpFSub %4 %116 %117 -%119 = OpFSub %4 %115 %118 -OpStore %28 %119 -OpBranch %113 -%113 = OpLabel -%120 = OpLoad %4 %35 -%121 = OpLoad %4 %19 -%122 = OpExtInst %5 %1 Distance %120 %121 -%124 = OpAccessChain %95 %50 %123 -%125 = OpLoad %5 %124 -%126 = OpFOrdLessThan %60 %122 %125 -OpSelectionMerge %127 None -OpBranchConditional %126 %128 %127 -%128 = OpLabel -%129 = OpLoad %4 %26 -%130 = OpLoad %4 %37 -%131 = OpFAdd %4 %129 %130 -OpStore %26 %131 -%132 = OpLoad %11 %33 -%133 = OpIAdd %11 %132 %53 -OpStore %33 %133 -OpBranch %127 -%127 = OpLabel -OpBranch %77 +OpBranch %68 +%73 = OpLabel +%75 = OpLoad %3 %32 +%76 = OpIEqual %53 %75 %52 +OpSelectionMerge %77 None +OpBranchConditional %76 %78 %77 +%78 = OpLabel +OpBranch %70 %77 = OpLabel -%134 = OpLoad %3 %39 -%135 = OpIAdd %3 %134 %54 -OpStore %39 %135 -OpBranch %74 -%75 = OpLabel -%136 = OpLoad %11 %30 -%137 = OpSGreaterThan %60 %136 %52 -OpSelectionMerge %138 None -OpBranchConditional %137 %139 %138 -%139 = OpLabel -%140 = OpLoad %4 %24 -%141 = OpLoad %11 %30 -%142 = OpConvertSToF %5 %141 -%143 = OpCompositeConstruct %4 %142 %142 -%144 = OpFDiv %4 %140 %143 -%145 = OpLoad %4 %19 -%146 = OpFSub %4 %144 %145 -OpStore %24 %146 -OpBranch %138 -%138 = OpLabel -%147 = OpLoad %11 %33 -%148 = OpSGreaterThan %60 %147 %52 -OpSelectionMerge %149 None -OpBranchConditional %148 %150 %149 -%150 = OpLabel -%151 = OpLoad %4 %26 -%152 = OpLoad %11 %33 -%153 = OpConvertSToF %5 %152 -%154 = OpCompositeConstruct %4 %153 %153 -%155 = OpFDiv %4 %151 %154 -OpStore %26 %155 -OpBranch %149 -%149 = OpLabel -%156 = OpLoad %4 %22 -%157 = OpLoad %4 %24 -%159 = OpAccessChain %95 %50 %158 -%160 = OpLoad %5 %159 -%161 = OpVectorTimesScalar %4 %157 %160 -%162 = OpFAdd %4 %156 %161 -%163 = OpLoad %4 %28 -%165 = OpAccessChain %95 %50 %164 -%166 = OpLoad %5 %165 -%167 = OpVectorTimesScalar %4 %163 %166 -%168 = OpFAdd %4 %162 %167 -%169 = OpLoad %4 %26 -%171 = OpAccessChain %95 %50 %170 -%172 = OpLoad %5 %171 +%79 = OpLoad %3 %32 +%80 = OpAccessChain %59 %16 %42 %79 %42 +%81 = OpLoad %4 %80 +OpStore %30 %81 +%82 = OpLoad %3 %32 +%83 = OpAccessChain %59 %16 %42 %82 %47 +%84 = OpLoad %4 %83 +OpStore %31 %84 +%85 = OpLoad %4 %30 +%86 = OpLoad %4 %19 +%87 = OpExtInst %5 %1 Distance %85 %86 +%89 = OpAccessChain %88 %43 %47 +%90 = OpLoad %5 %89 +%91 = OpFOrdLessThan %53 %87 %90 +OpSelectionMerge %92 None +OpBranchConditional %91 %93 %92 +%93 = OpLabel +%94 = OpLoad %4 %23 +%95 = OpLoad %4 %30 +%96 = OpFAdd %4 %94 %95 +OpStore %23 %96 +%97 = OpLoad %11 %26 +%98 = OpIAdd %11 %97 %46 +OpStore %26 %98 +OpBranch %92 +%92 = OpLabel +%99 = OpLoad %4 %30 +%100 = OpLoad %4 %19 +%101 = OpExtInst %5 %1 Distance %99 %100 +%103 = OpAccessChain %88 %43 %102 +%104 = OpLoad %5 %103 +%105 = OpFOrdLessThan %53 %101 %104 +OpSelectionMerge %106 None +OpBranchConditional %105 %107 %106 +%107 = OpLabel +%108 = OpLoad %4 %25 +%109 = OpLoad %4 %30 +%110 = OpLoad %4 %19 +%111 = OpFSub %4 %109 %110 +%112 = OpFSub %4 %108 %111 +OpStore %25 %112 +OpBranch %106 +%106 = OpLabel +%113 = OpLoad %4 %30 +%114 = OpLoad %4 %19 +%115 = OpExtInst %5 %1 Distance %113 %114 +%117 = OpAccessChain %88 %43 %116 +%118 = OpLoad %5 %117 +%119 = OpFOrdLessThan %53 %115 %118 +OpSelectionMerge %120 None +OpBranchConditional %119 %121 %120 +%121 = OpLabel +%122 = OpLoad %4 %24 +%123 = OpLoad %4 %31 +%124 = OpFAdd %4 %122 %123 +OpStore %24 %124 +%125 = OpLoad %11 %29 +%126 = OpIAdd %11 %125 %46 +OpStore %29 %126 +OpBranch %120 +%120 = OpLabel +OpBranch %70 +%70 = OpLabel +%127 = OpLoad %3 %32 +%128 = OpIAdd %3 %127 %47 +OpStore %32 %128 +OpBranch %67 +%68 = OpLabel +%129 = OpLoad %11 %26 +%130 = OpSGreaterThan %53 %129 %45 +OpSelectionMerge %131 None +OpBranchConditional %130 %132 %131 +%132 = OpLabel +%133 = OpLoad %4 %23 +%134 = OpLoad %11 %26 +%135 = OpConvertSToF %5 %134 +%136 = OpCompositeConstruct %4 %135 %135 +%137 = OpFDiv %4 %133 %136 +%138 = OpLoad %4 %19 +%139 = OpFSub %4 %137 %138 +OpStore %23 %139 +OpBranch %131 +%131 = OpLabel +%140 = OpLoad %11 %29 +%141 = OpSGreaterThan %53 %140 %45 +OpSelectionMerge %142 None +OpBranchConditional %141 %143 %142 +%143 = OpLabel +%144 = OpLoad %4 %24 +%145 = OpLoad %11 %29 +%146 = OpConvertSToF %5 %145 +%147 = OpCompositeConstruct %4 %146 %146 +%148 = OpFDiv %4 %144 %147 +OpStore %24 %148 +OpBranch %142 +%142 = OpLabel +%149 = OpLoad %4 %22 +%150 = OpLoad %4 %23 +%152 = OpAccessChain %88 %43 %151 +%153 = OpLoad %5 %152 +%154 = OpVectorTimesScalar %4 %150 %153 +%155 = OpFAdd %4 %149 %154 +%156 = OpLoad %4 %25 +%158 = OpAccessChain %88 %43 %157 +%159 = OpLoad %5 %158 +%160 = OpVectorTimesScalar %4 %156 %159 +%161 = OpFAdd %4 %155 %160 +%162 = OpLoad %4 %24 +%164 = OpAccessChain %88 %43 %163 +%165 = OpLoad %5 %164 +%166 = OpVectorTimesScalar %4 %162 %165 +%167 = OpFAdd %4 %161 %166 +OpStore %22 %167 +%168 = OpLoad %4 %22 +%169 = OpExtInst %4 %1 Normalize %168 +%170 = OpLoad %4 %22 +%171 = OpExtInst %5 %1 Length %170 +%172 = OpExtInst %5 %1 FClamp %171 %44 %48 %173 = OpVectorTimesScalar %4 %169 %172 -%174 = OpFAdd %4 %168 %173 -OpStore %22 %174 +OpStore %22 %173 +%174 = OpLoad %4 %19 %175 = OpLoad %4 %22 -%176 = OpExtInst %4 %1 Normalize %175 -%177 = OpLoad %4 %22 -%178 = OpExtInst %5 %1 Length %177 -%179 = OpExtInst %5 %1 FClamp %178 %51 %55 -%180 = OpVectorTimesScalar %4 %176 %179 -OpStore %22 %180 -%181 = OpLoad %4 %19 -%182 = OpLoad %4 %22 -%183 = OpAccessChain %95 %50 %49 -%184 = OpLoad %5 %183 -%185 = OpVectorTimesScalar %4 %182 %184 -%186 = OpFAdd %4 %181 %185 -OpStore %19 %186 -%188 = OpAccessChain %187 %19 %49 -%189 = OpLoad %5 %188 -%190 = OpFOrdLessThan %60 %189 %56 -OpSelectionMerge %191 None -OpBranchConditional %190 %192 %191 -%192 = OpLabel -%193 = OpAccessChain %187 %19 %49 -OpStore %193 %57 -OpBranch %191 +%176 = OpAccessChain %88 %43 %42 +%177 = OpLoad %5 %176 +%178 = OpVectorTimesScalar %4 %175 %177 +%179 = OpFAdd %4 %174 %178 +OpStore %19 %179 +%181 = OpAccessChain %180 %19 %42 +%182 = OpLoad %5 %181 +%183 = OpFOrdLessThan %53 %182 %49 +OpSelectionMerge %184 None +OpBranchConditional %183 %185 %184 +%185 = OpLabel +%186 = OpAccessChain %180 %19 %42 +OpStore %186 %50 +OpBranch %184 +%184 = OpLabel +%187 = OpAccessChain %180 %19 %42 +%188 = OpLoad %5 %187 +%189 = OpFOrdGreaterThan %53 %188 %50 +OpSelectionMerge %190 None +OpBranchConditional %189 %191 %190 %191 = OpLabel -%194 = OpAccessChain %187 %19 %49 -%195 = OpLoad %5 %194 -%196 = OpFOrdGreaterThan %60 %195 %57 -OpSelectionMerge %197 None -OpBranchConditional %196 %198 %197 -%198 = OpLabel -%199 = OpAccessChain %187 %19 %49 -OpStore %199 %56 -OpBranch %197 +%192 = OpAccessChain %180 %19 %42 +OpStore %192 %49 +OpBranch %190 +%190 = OpLabel +%193 = OpAccessChain %180 %19 %47 +%194 = OpLoad %5 %193 +%195 = OpFOrdLessThan %53 %194 %49 +OpSelectionMerge %196 None +OpBranchConditional %195 %197 %196 %197 = OpLabel -%200 = OpAccessChain %187 %19 %54 -%201 = OpLoad %5 %200 -%202 = OpFOrdLessThan %60 %201 %56 -OpSelectionMerge %203 None -OpBranchConditional %202 %204 %203 -%204 = OpLabel -%205 = OpAccessChain %187 %19 %54 -OpStore %205 %57 -OpBranch %203 +%198 = OpAccessChain %180 %19 %47 +OpStore %198 %50 +OpBranch %196 +%196 = OpLabel +%199 = OpAccessChain %180 %19 %47 +%200 = OpLoad %5 %199 +%201 = OpFOrdGreaterThan %53 %200 %50 +OpSelectionMerge %202 None +OpBranchConditional %201 %203 %202 %203 = OpLabel -%206 = OpAccessChain %187 %19 %54 -%207 = OpLoad %5 %206 -%208 = OpFOrdGreaterThan %60 %207 %57 -OpSelectionMerge %209 None -OpBranchConditional %208 %210 %209 -%210 = OpLabel -%211 = OpAccessChain %187 %19 %54 -OpStore %211 %56 -OpBranch %209 -%209 = OpLabel -%212 = OpLoad %4 %19 -%213 = OpAccessChain %66 %18 %49 %59 %49 -OpStore %213 %212 -%214 = OpLoad %4 %22 -%215 = OpAccessChain %66 %18 %49 %59 %54 -OpStore %215 %214 +%204 = OpAccessChain %180 %19 %47 +OpStore %204 %49 +OpBranch %202 +%202 = OpLabel +%205 = OpLoad %4 %19 +%206 = OpAccessChain %59 %18 %42 %52 %42 +OpStore %206 %205 +%207 = OpLoad %4 %22 +%208 = OpAccessChain %59 %18 %42 %52 %47 +OpStore %208 %207 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index 1a99215ef..923aadecf 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 310 +; Bound: 299 OpCapability Shader OpCapability Sampled1D OpCapability Image1D @@ -178,21 +178,10 @@ OpDecorate %267 Location 0 %270 = OpTypeFunction %2 %280 = OpConstant %5 0 %281 = OpConstantNull %8 -%282 = OpConstantNull %8 -%283 = OpConstant %10 0 -%284 = OpConstantNull %8 -%285 = OpConstantNull %12 -%286 = OpConstantNull %8 -%287 = OpConstantNull %6 -%288 = OpConstantNull %8 -%289 = OpConstantNull %6 -%290 = OpConstantNull %8 -%291 = OpConstantNull %6 -%292 = OpConstantNull %8 -%293 = OpConstantNull %6 -%294 = OpConstantNull %12 -%295 = OpConstantNull %6 -%296 = OpConstant %4 0.0 +%282 = OpConstant %10 0 +%283 = OpConstantNull %12 +%284 = OpConstantNull %6 +%285 = OpConstant %4 0.0 %48 = OpFunction %6 None %49 %46 = OpFunctionParameter %5 %47 = OpFunctionParameter %5 @@ -448,20 +437,20 @@ OpFunctionEnd %277 = OpLoad %18 %39 %278 = OpLoad %19 %41 %279 = OpLoad %20 %43 -OpBranch %297 -%297 = OpLabel -%298 = OpFunctionCall %6 %48 %280 %280 -%299 = OpFunctionCall %6 %63 %281 %280 -%300 = OpFunctionCall %6 %79 %282 %283 %280 -%301 = OpFunctionCall %6 %97 %284 %280 %280 -%302 = OpFunctionCall %6 %113 %285 %280 -%303 = OpFunctionCall %6 %128 %286 %280 -%304 = OpFunctionCall %2 %210 %280 %287 -%305 = OpFunctionCall %2 %220 %288 %289 -%306 = OpFunctionCall %2 %232 %290 %283 %291 -%307 = OpFunctionCall %2 %246 %292 %280 %293 -%308 = OpFunctionCall %2 %258 %294 %295 -%309 = OpCompositeConstruct %6 %296 %296 %296 %296 -OpStore %267 %309 +OpBranch %286 +%286 = OpLabel +%287 = OpFunctionCall %6 %48 %280 %280 +%288 = OpFunctionCall %6 %63 %281 %280 +%289 = OpFunctionCall %6 %79 %281 %282 %280 +%290 = OpFunctionCall %6 %97 %281 %280 %280 +%291 = OpFunctionCall %6 %113 %283 %280 +%292 = OpFunctionCall %6 %128 %281 %280 +%293 = OpFunctionCall %2 %210 %280 %284 +%294 = OpFunctionCall %2 %220 %281 %284 +%295 = OpFunctionCall %2 %232 %281 %282 %284 +%296 = OpFunctionCall %2 %246 %281 %280 %284 +%297 = OpFunctionCall %2 %258 %283 %284 +%298 = OpCompositeConstruct %6 %285 %285 %285 %285 +OpStore %267 %298 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index 53e27a796..8a6cfc1b7 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -1,15 +1,15 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 347 +; Bound: 326 OpCapability Shader OpCapability Sampled1D OpCapability Image1D OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %306 "fragment_shader" %304 -OpExecutionMode %306 OriginUpperLeft +OpEntryPoint Fragment %297 "fragment_shader" %295 +OpExecutionMode %297 OriginUpperLeft OpName %21 "image_1d" OpName %23 "image_2d" OpName %25 "image_2d_array" @@ -28,52 +28,52 @@ OpName %48 "test_textureLoad_1d" OpName %64 "coords" OpName %65 "level" OpName %66 "test_textureLoad_2d" -OpName %83 "coords" -OpName %84 "index" -OpName %85 "level" -OpName %86 "test_textureLoad_2d_array_u" -OpName %105 "coords" -OpName %106 "index" -OpName %107 "level" -OpName %108 "test_textureLoad_2d_array_s" -OpName %125 "coords" -OpName %126 "level" -OpName %127 "test_textureLoad_3d" -OpName %143 "coords" -OpName %144 "_sample" -OpName %145 "test_textureLoad_multisampled_2d" -OpName %160 "coords" -OpName %161 "level" -OpName %162 "test_textureLoad_depth_2d" -OpName %179 "coords" -OpName %180 "index" -OpName %181 "level" -OpName %182 "test_textureLoad_depth_2d_array_u" -OpName %201 "coords" -OpName %202 "index" -OpName %203 "level" -OpName %204 "test_textureLoad_depth_2d_array_s" -OpName %222 "coords" -OpName %223 "_sample" -OpName %224 "test_textureLoad_depth_multisampled_2d" -OpName %240 "coords" -OpName %241 "value" -OpName %242 "test_textureStore_1d" -OpName %251 "coords" -OpName %252 "value" -OpName %253 "test_textureStore_2d" -OpName %263 "coords" -OpName %264 "array_index" -OpName %265 "value" -OpName %266 "test_textureStore_2d_array_u" -OpName %278 "coords" -OpName %279 "array_index" -OpName %280 "value" -OpName %281 "test_textureStore_2d_array_s" -OpName %292 "coords" -OpName %293 "value" -OpName %294 "test_textureStore_3d" -OpName %306 "fragment_shader" +OpName %82 "coords" +OpName %83 "index" +OpName %84 "level" +OpName %85 "test_textureLoad_2d_array_u" +OpName %103 "coords" +OpName %104 "index" +OpName %105 "level" +OpName %106 "test_textureLoad_2d_array_s" +OpName %122 "coords" +OpName %123 "level" +OpName %124 "test_textureLoad_3d" +OpName %139 "coords" +OpName %140 "_sample" +OpName %141 "test_textureLoad_multisampled_2d" +OpName %155 "coords" +OpName %156 "level" +OpName %157 "test_textureLoad_depth_2d" +OpName %173 "coords" +OpName %174 "index" +OpName %175 "level" +OpName %176 "test_textureLoad_depth_2d_array_u" +OpName %194 "coords" +OpName %195 "index" +OpName %196 "level" +OpName %197 "test_textureLoad_depth_2d_array_s" +OpName %214 "coords" +OpName %215 "_sample" +OpName %216 "test_textureLoad_depth_multisampled_2d" +OpName %231 "coords" +OpName %232 "value" +OpName %233 "test_textureStore_1d" +OpName %242 "coords" +OpName %243 "value" +OpName %244 "test_textureStore_2d" +OpName %254 "coords" +OpName %255 "array_index" +OpName %256 "value" +OpName %257 "test_textureStore_2d_array_u" +OpName %269 "coords" +OpName %270 "array_index" +OpName %271 "value" +OpName %272 "test_textureStore_2d_array_s" +OpName %283 "coords" +OpName %284 "value" +OpName %285 "test_textureStore_3d" +OpName %297 "fragment_shader" OpDecorate %21 DescriptorSet 0 OpDecorate %21 Binding 0 OpDecorate %23 DescriptorSet 0 @@ -102,7 +102,7 @@ OpDecorate %41 Binding 10 OpDecorate %43 NonReadable OpDecorate %43 DescriptorSet 0 OpDecorate %43 Binding 11 -OpDecorate %304 Location 0 +OpDecorate %295 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeImage %4 1D 0 0 0 1 Unknown @@ -150,48 +150,27 @@ OpDecorate %304 Location 0 %52 = OpTypeBool %53 = OpConstantNull %6 %67 = OpTypeFunction %6 %8 %5 -%70 = OpConstantNull %6 -%76 = OpTypeVector %52 2 -%87 = OpTypeFunction %6 %8 %10 %5 -%92 = OpConstantNull %6 -%98 = OpTypeVector %52 3 -%109 = OpTypeFunction %6 %8 %5 %5 -%113 = OpConstantNull %6 -%128 = OpTypeFunction %6 %12 %5 -%131 = OpConstantNull %6 -%148 = OpConstantNull %6 -%163 = OpTypeFunction %4 %8 %5 -%166 = OpConstantNull %6 -%183 = OpTypeFunction %4 %8 %10 %5 -%188 = OpConstantNull %6 -%205 = OpTypeFunction %4 %8 %5 %5 -%209 = OpConstantNull %6 -%227 = OpConstantNull %6 -%243 = OpTypeFunction %2 %5 %6 -%254 = OpTypeFunction %2 %8 %6 -%267 = OpTypeFunction %2 %8 %10 %6 -%282 = OpTypeFunction %2 %8 %5 %6 -%295 = OpTypeFunction %2 %12 %6 -%305 = OpTypePointer Output %6 -%304 = OpVariable %305 Output -%307 = OpTypeFunction %2 -%317 = OpConstant %5 0 -%318 = OpConstantNull %8 -%319 = OpConstantNull %8 -%320 = OpConstant %10 0 -%321 = OpConstantNull %8 -%322 = OpConstantNull %12 -%323 = OpConstantNull %8 -%324 = OpConstantNull %6 -%325 = OpConstantNull %8 -%326 = OpConstantNull %6 -%327 = OpConstantNull %8 -%328 = OpConstantNull %6 -%329 = OpConstantNull %8 -%330 = OpConstantNull %6 -%331 = OpConstantNull %12 -%332 = OpConstantNull %6 -%333 = OpConstant %4 0.0 +%75 = OpTypeVector %52 2 +%86 = OpTypeFunction %6 %8 %10 %5 +%96 = OpTypeVector %52 3 +%107 = OpTypeFunction %6 %8 %5 %5 +%125 = OpTypeFunction %6 %12 %5 +%158 = OpTypeFunction %4 %8 %5 +%177 = OpTypeFunction %4 %8 %10 %5 +%198 = OpTypeFunction %4 %8 %5 %5 +%234 = OpTypeFunction %2 %5 %6 +%245 = OpTypeFunction %2 %8 %6 +%258 = OpTypeFunction %2 %8 %10 %6 +%273 = OpTypeFunction %2 %8 %5 %6 +%286 = OpTypeFunction %2 %12 %6 +%296 = OpTypePointer Output %6 +%295 = OpVariable %296 Output +%298 = OpTypeFunction %2 +%308 = OpConstant %5 0 +%309 = OpConstantNull %8 +%310 = OpConstant %10 0 +%311 = OpConstantNull %12 +%312 = OpConstant %4 0.0 %48 = OpFunction %6 None %49 %46 = OpFunctionParameter %5 %47 = OpFunctionParameter %5 @@ -221,339 +200,339 @@ OpFunctionEnd %68 = OpLoad %7 %23 OpBranch %69 %69 = OpLabel -%71 = OpImageQueryLevels %5 %68 -%72 = OpULessThan %52 %65 %71 -OpSelectionMerge %73 None -OpBranchConditional %72 %74 %73 -%74 = OpLabel -%75 = OpImageQuerySizeLod %8 %68 %65 -%77 = OpULessThan %76 %64 %75 -%78 = OpAll %52 %77 -OpBranchConditional %78 %79 %73 -%79 = OpLabel -%80 = OpImageFetch %6 %68 %64 Lod %65 -OpBranch %73 +%70 = OpImageQueryLevels %5 %68 +%71 = OpULessThan %52 %65 %70 +OpSelectionMerge %72 None +OpBranchConditional %71 %73 %72 %73 = OpLabel -%81 = OpPhi %6 %70 %69 %70 %74 %80 %79 -OpReturnValue %81 +%74 = OpImageQuerySizeLod %8 %68 %65 +%76 = OpULessThan %75 %64 %74 +%77 = OpAll %52 %76 +OpBranchConditional %77 %78 %72 +%78 = OpLabel +%79 = OpImageFetch %6 %68 %64 Lod %65 +OpBranch %72 +%72 = OpLabel +%80 = OpPhi %6 %53 %69 %53 %73 %79 %78 +OpReturnValue %80 OpFunctionEnd -%86 = OpFunction %6 None %87 -%83 = OpFunctionParameter %8 -%84 = OpFunctionParameter %10 -%85 = OpFunctionParameter %5 -%82 = OpLabel -%88 = OpLoad %9 %25 -OpBranch %89 -%89 = OpLabel -%90 = OpBitcast %5 %84 -%91 = OpCompositeConstruct %12 %83 %90 -%93 = OpImageQueryLevels %5 %88 -%94 = OpULessThan %52 %85 %93 -OpSelectionMerge %95 None -OpBranchConditional %94 %96 %95 -%96 = OpLabel -%97 = OpImageQuerySizeLod %12 %88 %85 -%99 = OpULessThan %98 %91 %97 -%100 = OpAll %52 %99 -OpBranchConditional %100 %101 %95 -%101 = OpLabel -%102 = OpImageFetch %6 %88 %91 Lod %85 -OpBranch %95 -%95 = OpLabel -%103 = OpPhi %6 %92 %89 %92 %96 %102 %101 -OpReturnValue %103 +%85 = OpFunction %6 None %86 +%82 = OpFunctionParameter %8 +%83 = OpFunctionParameter %10 +%84 = OpFunctionParameter %5 +%81 = OpLabel +%87 = OpLoad %9 %25 +OpBranch %88 +%88 = OpLabel +%89 = OpBitcast %5 %83 +%90 = OpCompositeConstruct %12 %82 %89 +%91 = OpImageQueryLevels %5 %87 +%92 = OpULessThan %52 %84 %91 +OpSelectionMerge %93 None +OpBranchConditional %92 %94 %93 +%94 = OpLabel +%95 = OpImageQuerySizeLod %12 %87 %84 +%97 = OpULessThan %96 %90 %95 +%98 = OpAll %52 %97 +OpBranchConditional %98 %99 %93 +%99 = OpLabel +%100 = OpImageFetch %6 %87 %90 Lod %84 +OpBranch %93 +%93 = OpLabel +%101 = OpPhi %6 %53 %88 %53 %94 %100 %99 +OpReturnValue %101 OpFunctionEnd -%108 = OpFunction %6 None %109 -%105 = OpFunctionParameter %8 -%106 = OpFunctionParameter %5 -%107 = OpFunctionParameter %5 -%104 = OpLabel -%110 = OpLoad %9 %25 -OpBranch %111 -%111 = OpLabel -%112 = OpCompositeConstruct %12 %105 %106 -%114 = OpImageQueryLevels %5 %110 -%115 = OpULessThan %52 %107 %114 -OpSelectionMerge %116 None -OpBranchConditional %115 %117 %116 -%117 = OpLabel -%118 = OpImageQuerySizeLod %12 %110 %107 -%119 = OpULessThan %98 %112 %118 -%120 = OpAll %52 %119 -OpBranchConditional %120 %121 %116 +%106 = OpFunction %6 None %107 +%103 = OpFunctionParameter %8 +%104 = OpFunctionParameter %5 +%105 = OpFunctionParameter %5 +%102 = OpLabel +%108 = OpLoad %9 %25 +OpBranch %109 +%109 = OpLabel +%110 = OpCompositeConstruct %12 %103 %104 +%111 = OpImageQueryLevels %5 %108 +%112 = OpULessThan %52 %105 %111 +OpSelectionMerge %113 None +OpBranchConditional %112 %114 %113 +%114 = OpLabel +%115 = OpImageQuerySizeLod %12 %108 %105 +%116 = OpULessThan %96 %110 %115 +%117 = OpAll %52 %116 +OpBranchConditional %117 %118 %113 +%118 = OpLabel +%119 = OpImageFetch %6 %108 %110 Lod %105 +OpBranch %113 +%113 = OpLabel +%120 = OpPhi %6 %53 %109 %53 %114 %119 %118 +OpReturnValue %120 +OpFunctionEnd +%124 = OpFunction %6 None %125 +%122 = OpFunctionParameter %12 +%123 = OpFunctionParameter %5 %121 = OpLabel -%122 = OpImageFetch %6 %110 %112 Lod %107 -OpBranch %116 -%116 = OpLabel -%123 = OpPhi %6 %113 %111 %113 %117 %122 %121 -OpReturnValue %123 -OpFunctionEnd -%127 = OpFunction %6 None %128 -%125 = OpFunctionParameter %12 -%126 = OpFunctionParameter %5 -%124 = OpLabel -%129 = OpLoad %11 %27 +%126 = OpLoad %11 %27 +OpBranch %127 +%127 = OpLabel +%128 = OpImageQueryLevels %5 %126 +%129 = OpULessThan %52 %123 %128 +OpSelectionMerge %130 None +OpBranchConditional %129 %131 %130 +%131 = OpLabel +%132 = OpImageQuerySizeLod %12 %126 %123 +%133 = OpULessThan %96 %122 %132 +%134 = OpAll %52 %133 +OpBranchConditional %134 %135 %130 +%135 = OpLabel +%136 = OpImageFetch %6 %126 %122 Lod %123 OpBranch %130 %130 = OpLabel -%132 = OpImageQueryLevels %5 %129 -%133 = OpULessThan %52 %126 %132 -OpSelectionMerge %134 None -OpBranchConditional %133 %135 %134 -%135 = OpLabel -%136 = OpImageQuerySizeLod %12 %129 %126 -%137 = OpULessThan %98 %125 %136 -%138 = OpAll %52 %137 -OpBranchConditional %138 %139 %134 -%139 = OpLabel -%140 = OpImageFetch %6 %129 %125 Lod %126 -OpBranch %134 -%134 = OpLabel -%141 = OpPhi %6 %131 %130 %131 %135 %140 %139 -OpReturnValue %141 +%137 = OpPhi %6 %53 %127 %53 %131 %136 %135 +OpReturnValue %137 OpFunctionEnd -%145 = OpFunction %6 None %67 -%143 = OpFunctionParameter %8 -%144 = OpFunctionParameter %5 -%142 = OpLabel -%146 = OpLoad %13 %29 -OpBranch %147 +%141 = OpFunction %6 None %67 +%139 = OpFunctionParameter %8 +%140 = OpFunctionParameter %5 +%138 = OpLabel +%142 = OpLoad %13 %29 +OpBranch %143 +%143 = OpLabel +%144 = OpImageQuerySamples %5 %142 +%145 = OpULessThan %52 %140 %144 +OpSelectionMerge %146 None +OpBranchConditional %145 %147 %146 %147 = OpLabel -%149 = OpImageQuerySamples %5 %146 -%150 = OpULessThan %52 %144 %149 -OpSelectionMerge %151 None -OpBranchConditional %150 %152 %151 -%152 = OpLabel -%153 = OpImageQuerySize %8 %146 -%154 = OpULessThan %76 %143 %153 -%155 = OpAll %52 %154 -OpBranchConditional %155 %156 %151 -%156 = OpLabel -%157 = OpImageFetch %6 %146 %143 Sample %144 -OpBranch %151 +%148 = OpImageQuerySize %8 %142 +%149 = OpULessThan %75 %139 %148 +%150 = OpAll %52 %149 +OpBranchConditional %150 %151 %146 %151 = OpLabel -%158 = OpPhi %6 %148 %147 %148 %152 %157 %156 -OpReturnValue %158 +%152 = OpImageFetch %6 %142 %139 Sample %140 +OpBranch %146 +%146 = OpLabel +%153 = OpPhi %6 %53 %143 %53 %147 %152 %151 +OpReturnValue %153 OpFunctionEnd -%162 = OpFunction %4 None %163 -%160 = OpFunctionParameter %8 -%161 = OpFunctionParameter %5 -%159 = OpLabel -%164 = OpLoad %14 %31 -OpBranch %165 -%165 = OpLabel -%167 = OpImageQueryLevels %5 %164 -%168 = OpULessThan %52 %161 %167 -OpSelectionMerge %169 None -OpBranchConditional %168 %170 %169 -%170 = OpLabel -%171 = OpImageQuerySizeLod %8 %164 %161 -%172 = OpULessThan %76 %160 %171 -%173 = OpAll %52 %172 -OpBranchConditional %173 %174 %169 -%174 = OpLabel -%175 = OpImageFetch %6 %164 %160 Lod %161 -OpBranch %169 -%169 = OpLabel -%176 = OpPhi %6 %166 %165 %166 %170 %175 %174 -%177 = OpCompositeExtract %4 %176 0 -OpReturnValue %177 +%157 = OpFunction %4 None %158 +%155 = OpFunctionParameter %8 +%156 = OpFunctionParameter %5 +%154 = OpLabel +%159 = OpLoad %14 %31 +OpBranch %160 +%160 = OpLabel +%161 = OpImageQueryLevels %5 %159 +%162 = OpULessThan %52 %156 %161 +OpSelectionMerge %163 None +OpBranchConditional %162 %164 %163 +%164 = OpLabel +%165 = OpImageQuerySizeLod %8 %159 %156 +%166 = OpULessThan %75 %155 %165 +%167 = OpAll %52 %166 +OpBranchConditional %167 %168 %163 +%168 = OpLabel +%169 = OpImageFetch %6 %159 %155 Lod %156 +OpBranch %163 +%163 = OpLabel +%170 = OpPhi %6 %53 %160 %53 %164 %169 %168 +%171 = OpCompositeExtract %4 %170 0 +OpReturnValue %171 OpFunctionEnd -%182 = OpFunction %4 None %183 -%179 = OpFunctionParameter %8 -%180 = OpFunctionParameter %10 -%181 = OpFunctionParameter %5 -%178 = OpLabel -%184 = OpLoad %15 %33 -OpBranch %185 +%176 = OpFunction %4 None %177 +%173 = OpFunctionParameter %8 +%174 = OpFunctionParameter %10 +%175 = OpFunctionParameter %5 +%172 = OpLabel +%178 = OpLoad %15 %33 +OpBranch %179 +%179 = OpLabel +%180 = OpBitcast %5 %174 +%181 = OpCompositeConstruct %12 %173 %180 +%182 = OpImageQueryLevels %5 %178 +%183 = OpULessThan %52 %175 %182 +OpSelectionMerge %184 None +OpBranchConditional %183 %185 %184 %185 = OpLabel -%186 = OpBitcast %5 %180 -%187 = OpCompositeConstruct %12 %179 %186 -%189 = OpImageQueryLevels %5 %184 -%190 = OpULessThan %52 %181 %189 -OpSelectionMerge %191 None -OpBranchConditional %190 %192 %191 -%192 = OpLabel -%193 = OpImageQuerySizeLod %12 %184 %181 -%194 = OpULessThan %98 %187 %193 -%195 = OpAll %52 %194 -OpBranchConditional %195 %196 %191 -%196 = OpLabel -%197 = OpImageFetch %6 %184 %187 Lod %181 -OpBranch %191 -%191 = OpLabel -%198 = OpPhi %6 %188 %185 %188 %192 %197 %196 -%199 = OpCompositeExtract %4 %198 0 -OpReturnValue %199 +%186 = OpImageQuerySizeLod %12 %178 %175 +%187 = OpULessThan %96 %181 %186 +%188 = OpAll %52 %187 +OpBranchConditional %188 %189 %184 +%189 = OpLabel +%190 = OpImageFetch %6 %178 %181 Lod %175 +OpBranch %184 +%184 = OpLabel +%191 = OpPhi %6 %53 %179 %53 %185 %190 %189 +%192 = OpCompositeExtract %4 %191 0 +OpReturnValue %192 OpFunctionEnd -%204 = OpFunction %4 None %205 -%201 = OpFunctionParameter %8 -%202 = OpFunctionParameter %5 -%203 = OpFunctionParameter %5 +%197 = OpFunction %4 None %198 +%194 = OpFunctionParameter %8 +%195 = OpFunctionParameter %5 +%196 = OpFunctionParameter %5 +%193 = OpLabel +%199 = OpLoad %15 %33 +OpBranch %200 %200 = OpLabel -%206 = OpLoad %15 %33 -OpBranch %207 -%207 = OpLabel -%208 = OpCompositeConstruct %12 %201 %202 -%210 = OpImageQueryLevels %5 %206 -%211 = OpULessThan %52 %203 %210 -OpSelectionMerge %212 None -OpBranchConditional %211 %213 %212 +%201 = OpCompositeConstruct %12 %194 %195 +%202 = OpImageQueryLevels %5 %199 +%203 = OpULessThan %52 %196 %202 +OpSelectionMerge %204 None +OpBranchConditional %203 %205 %204 +%205 = OpLabel +%206 = OpImageQuerySizeLod %12 %199 %196 +%207 = OpULessThan %96 %201 %206 +%208 = OpAll %52 %207 +OpBranchConditional %208 %209 %204 +%209 = OpLabel +%210 = OpImageFetch %6 %199 %201 Lod %196 +OpBranch %204 +%204 = OpLabel +%211 = OpPhi %6 %53 %200 %53 %205 %210 %209 +%212 = OpCompositeExtract %4 %211 0 +OpReturnValue %212 +OpFunctionEnd +%216 = OpFunction %4 None %158 +%214 = OpFunctionParameter %8 +%215 = OpFunctionParameter %5 %213 = OpLabel -%214 = OpImageQuerySizeLod %12 %206 %203 -%215 = OpULessThan %98 %208 %214 -%216 = OpAll %52 %215 -OpBranchConditional %216 %217 %212 -%217 = OpLabel -%218 = OpImageFetch %6 %206 %208 Lod %203 -OpBranch %212 -%212 = OpLabel -%219 = OpPhi %6 %209 %207 %209 %213 %218 %217 -%220 = OpCompositeExtract %4 %219 0 -OpReturnValue %220 -OpFunctionEnd -%224 = OpFunction %4 None %163 -%222 = OpFunctionParameter %8 -%223 = OpFunctionParameter %5 -%221 = OpLabel -%225 = OpLoad %16 %35 -OpBranch %226 +%217 = OpLoad %16 %35 +OpBranch %218 +%218 = OpLabel +%219 = OpImageQuerySamples %5 %217 +%220 = OpULessThan %52 %215 %219 +OpSelectionMerge %221 None +OpBranchConditional %220 %222 %221 +%222 = OpLabel +%223 = OpImageQuerySize %8 %217 +%224 = OpULessThan %75 %214 %223 +%225 = OpAll %52 %224 +OpBranchConditional %225 %226 %221 %226 = OpLabel -%228 = OpImageQuerySamples %5 %225 -%229 = OpULessThan %52 %223 %228 -OpSelectionMerge %230 None -OpBranchConditional %229 %231 %230 -%231 = OpLabel -%232 = OpImageQuerySize %8 %225 -%233 = OpULessThan %76 %222 %232 -%234 = OpAll %52 %233 -OpBranchConditional %234 %235 %230 -%235 = OpLabel -%236 = OpImageFetch %6 %225 %222 Sample %223 -OpBranch %230 -%230 = OpLabel -%237 = OpPhi %6 %227 %226 %227 %231 %236 %235 -%238 = OpCompositeExtract %4 %237 0 -OpReturnValue %238 +%227 = OpImageFetch %6 %217 %214 Sample %215 +OpBranch %221 +%221 = OpLabel +%228 = OpPhi %6 %53 %218 %53 %222 %227 %226 +%229 = OpCompositeExtract %4 %228 0 +OpReturnValue %229 OpFunctionEnd -%242 = OpFunction %2 None %243 -%240 = OpFunctionParameter %5 -%241 = OpFunctionParameter %6 +%233 = OpFunction %2 None %234 +%231 = OpFunctionParameter %5 +%232 = OpFunctionParameter %6 +%230 = OpLabel +%235 = OpLoad %17 %37 +OpBranch %236 +%236 = OpLabel +%237 = OpImageQuerySize %5 %235 +%238 = OpULessThan %52 %231 %237 +OpSelectionMerge %239 None +OpBranchConditional %238 %240 %239 +%240 = OpLabel +OpImageWrite %235 %231 %232 +OpBranch %239 %239 = OpLabel -%244 = OpLoad %17 %37 -OpBranch %245 -%245 = OpLabel -%246 = OpImageQuerySize %5 %244 -%247 = OpULessThan %52 %240 %246 -OpSelectionMerge %248 None -OpBranchConditional %247 %249 %248 -%249 = OpLabel -OpImageWrite %244 %240 %241 -OpBranch %248 -%248 = OpLabel OpReturn OpFunctionEnd -%253 = OpFunction %2 None %254 -%251 = OpFunctionParameter %8 -%252 = OpFunctionParameter %6 -%250 = OpLabel -%255 = OpLoad %18 %39 -OpBranch %256 -%256 = OpLabel -%257 = OpImageQuerySize %8 %255 -%258 = OpULessThan %76 %251 %257 -%259 = OpAll %52 %258 -OpSelectionMerge %260 None -OpBranchConditional %259 %261 %260 -%261 = OpLabel -OpImageWrite %255 %251 %252 +%244 = OpFunction %2 None %245 +%242 = OpFunctionParameter %8 +%243 = OpFunctionParameter %6 +%241 = OpLabel +%246 = OpLoad %18 %39 +OpBranch %247 +%247 = OpLabel +%248 = OpImageQuerySize %8 %246 +%249 = OpULessThan %75 %242 %248 +%250 = OpAll %52 %249 +OpSelectionMerge %251 None +OpBranchConditional %250 %252 %251 +%252 = OpLabel +OpImageWrite %246 %242 %243 +OpBranch %251 +%251 = OpLabel +OpReturn +OpFunctionEnd +%257 = OpFunction %2 None %258 +%254 = OpFunctionParameter %8 +%255 = OpFunctionParameter %10 +%256 = OpFunctionParameter %6 +%253 = OpLabel +%259 = OpLoad %19 %41 OpBranch %260 %260 = OpLabel +%261 = OpBitcast %5 %255 +%262 = OpCompositeConstruct %12 %254 %261 +%263 = OpImageQuerySize %12 %259 +%264 = OpULessThan %96 %262 %263 +%265 = OpAll %52 %264 +OpSelectionMerge %266 None +OpBranchConditional %265 %267 %266 +%267 = OpLabel +OpImageWrite %259 %262 %256 +OpBranch %266 +%266 = OpLabel OpReturn OpFunctionEnd -%266 = OpFunction %2 None %267 -%263 = OpFunctionParameter %8 -%264 = OpFunctionParameter %10 -%265 = OpFunctionParameter %6 -%262 = OpLabel -%268 = OpLoad %19 %41 -OpBranch %269 -%269 = OpLabel -%270 = OpBitcast %5 %264 -%271 = OpCompositeConstruct %12 %263 %270 -%272 = OpImageQuerySize %12 %268 -%273 = OpULessThan %98 %271 %272 -%274 = OpAll %52 %273 -OpSelectionMerge %275 None -OpBranchConditional %274 %276 %275 -%276 = OpLabel -OpImageWrite %268 %271 %265 +%272 = OpFunction %2 None %273 +%269 = OpFunctionParameter %8 +%270 = OpFunctionParameter %5 +%271 = OpFunctionParameter %6 +%268 = OpLabel +%274 = OpLoad %19 %41 OpBranch %275 %275 = OpLabel +%276 = OpCompositeConstruct %12 %269 %270 +%277 = OpImageQuerySize %12 %274 +%278 = OpULessThan %96 %276 %277 +%279 = OpAll %52 %278 +OpSelectionMerge %280 None +OpBranchConditional %279 %281 %280 +%281 = OpLabel +OpImageWrite %274 %276 %271 +OpBranch %280 +%280 = OpLabel OpReturn OpFunctionEnd -%281 = OpFunction %2 None %282 -%278 = OpFunctionParameter %8 -%279 = OpFunctionParameter %5 -%280 = OpFunctionParameter %6 -%277 = OpLabel -%283 = OpLoad %19 %41 -OpBranch %284 -%284 = OpLabel -%285 = OpCompositeConstruct %12 %278 %279 -%286 = OpImageQuerySize %12 %283 -%287 = OpULessThan %98 %285 %286 -%288 = OpAll %52 %287 -OpSelectionMerge %289 None -OpBranchConditional %288 %290 %289 -%290 = OpLabel -OpImageWrite %283 %285 %280 -OpBranch %289 -%289 = OpLabel +%285 = OpFunction %2 None %286 +%283 = OpFunctionParameter %12 +%284 = OpFunctionParameter %6 +%282 = OpLabel +%287 = OpLoad %20 %43 +OpBranch %288 +%288 = OpLabel +%289 = OpImageQuerySize %12 %287 +%290 = OpULessThan %96 %283 %289 +%291 = OpAll %52 %290 +OpSelectionMerge %292 None +OpBranchConditional %291 %293 %292 +%293 = OpLabel +OpImageWrite %287 %283 %284 +OpBranch %292 +%292 = OpLabel OpReturn OpFunctionEnd -%294 = OpFunction %2 None %295 -%292 = OpFunctionParameter %12 -%293 = OpFunctionParameter %6 -%291 = OpLabel -%296 = OpLoad %20 %43 -OpBranch %297 -%297 = OpLabel -%298 = OpImageQuerySize %12 %296 -%299 = OpULessThan %98 %292 %298 -%300 = OpAll %52 %299 -OpSelectionMerge %301 None -OpBranchConditional %300 %302 %301 -%302 = OpLabel -OpImageWrite %296 %292 %293 -OpBranch %301 -%301 = OpLabel -OpReturn -OpFunctionEnd -%306 = OpFunction %2 None %307 -%303 = OpLabel -%308 = OpLoad %3 %21 -%309 = OpLoad %7 %23 -%310 = OpLoad %9 %25 -%311 = OpLoad %11 %27 -%312 = OpLoad %13 %29 -%313 = OpLoad %17 %37 -%314 = OpLoad %18 %39 -%315 = OpLoad %19 %41 -%316 = OpLoad %20 %43 -OpBranch %334 -%334 = OpLabel -%335 = OpFunctionCall %6 %48 %317 %317 -%336 = OpFunctionCall %6 %66 %318 %317 -%337 = OpFunctionCall %6 %86 %319 %320 %317 -%338 = OpFunctionCall %6 %108 %321 %317 %317 -%339 = OpFunctionCall %6 %127 %322 %317 -%340 = OpFunctionCall %6 %145 %323 %317 -%341 = OpFunctionCall %2 %242 %317 %324 -%342 = OpFunctionCall %2 %253 %325 %326 -%343 = OpFunctionCall %2 %266 %327 %320 %328 -%344 = OpFunctionCall %2 %281 %329 %317 %330 -%345 = OpFunctionCall %2 %294 %331 %332 -%346 = OpCompositeConstruct %6 %333 %333 %333 %333 -OpStore %304 %346 +%297 = OpFunction %2 None %298 +%294 = OpLabel +%299 = OpLoad %3 %21 +%300 = OpLoad %7 %23 +%301 = OpLoad %9 %25 +%302 = OpLoad %11 %27 +%303 = OpLoad %13 %29 +%304 = OpLoad %17 %37 +%305 = OpLoad %18 %39 +%306 = OpLoad %19 %41 +%307 = OpLoad %20 %43 +OpBranch %313 +%313 = OpLabel +%314 = OpFunctionCall %6 %48 %308 %308 +%315 = OpFunctionCall %6 %66 %309 %308 +%316 = OpFunctionCall %6 %85 %309 %310 %308 +%317 = OpFunctionCall %6 %106 %309 %308 %308 +%318 = OpFunctionCall %6 %124 %311 %308 +%319 = OpFunctionCall %6 %141 %309 %308 +%320 = OpFunctionCall %2 %233 %308 %53 +%321 = OpFunctionCall %2 %244 %309 %53 +%322 = OpFunctionCall %2 %257 %309 %310 %53 +%323 = OpFunctionCall %2 %272 %309 %308 %53 +%324 = OpFunctionCall %2 %285 %311 %53 +%325 = OpCompositeConstruct %6 %312 %312 %312 %312 +OpStore %295 %325 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index e5fcdce2f..b3c108d98 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 206 +; Bound: 201 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -39,29 +39,24 @@ OpDecorate %10 Block %26 = OpConstantNull %3 %35 = OpTypePointer StorageBuffer %9 %38 = OpConstant %6 3 -%40 = OpConstantNull %3 -%49 = OpTypePointer StorageBuffer %7 -%50 = OpTypePointer StorageBuffer %3 -%51 = OpConstant %6 4 -%53 = OpConstant %6 1 -%55 = OpConstantNull %3 -%64 = OpTypeFunction %3 %7 %11 -%67 = OpConstantNull %3 -%75 = OpTypeFunction %7 %11 -%77 = OpTypePointer StorageBuffer %8 -%78 = OpTypePointer StorageBuffer %7 -%80 = OpConstant %6 2 -%82 = OpConstantNull %7 -%91 = OpTypeFunction %3 %11 %11 -%97 = OpConstantNull %3 -%105 = OpConstant %3 100.0 -%114 = OpConstantNull %3 -%121 = OpTypeFunction %3 -%123 = OpConstant %6 9 -%136 = OpTypeFunction %2 %11 %3 -%165 = OpTypeFunction %2 %11 %7 -%176 = OpTypeFunction %2 %11 %11 %3 -%201 = OpTypeFunction %2 %3 +%48 = OpTypePointer StorageBuffer %7 +%49 = OpTypePointer StorageBuffer %3 +%50 = OpConstant %6 4 +%52 = OpConstant %6 1 +%62 = OpTypeFunction %3 %7 %11 +%72 = OpTypeFunction %7 %11 +%74 = OpTypePointer StorageBuffer %8 +%75 = OpTypePointer StorageBuffer %7 +%77 = OpConstant %6 2 +%79 = OpConstantNull %7 +%88 = OpTypeFunction %3 %11 %11 +%101 = OpConstant %3 100.0 +%116 = OpTypeFunction %3 +%118 = OpConstant %6 9 +%131 = OpTypeFunction %2 %11 %3 +%160 = OpTypeFunction %2 %11 %7 +%171 = OpTypeFunction %2 %11 %11 %3 +%196 = OpTypeFunction %2 %3 %17 = OpFunction %3 None %18 %16 = OpFunctionParameter %11 %15 = OpLabel @@ -85,233 +80,233 @@ OpBranch %34 %34 = OpLabel %36 = OpArrayLength %6 %13 3 %37 = OpULessThan %23 %32 %36 -OpSelectionMerge %41 None -OpBranchConditional %37 %42 %41 -%42 = OpLabel -%39 = OpAccessChain %21 %13 %38 %32 -%43 = OpLoad %3 %39 -OpBranch %41 +OpSelectionMerge %40 None +OpBranchConditional %37 %41 %40 %41 = OpLabel -%44 = OpPhi %3 %40 %34 %43 %42 -OpReturnValue %44 +%39 = OpAccessChain %21 %13 %38 %32 +%42 = OpLoad %3 %39 +OpBranch %40 +%40 = OpLabel +%43 = OpPhi %3 %26 %34 %42 %41 +OpReturnValue %43 OpFunctionEnd -%47 = OpFunction %3 None %18 -%46 = OpFunctionParameter %11 -%45 = OpLabel -OpBranch %48 -%48 = OpLabel -%52 = OpULessThan %23 %46 %51 -OpSelectionMerge %56 None -OpBranchConditional %52 %57 %56 -%57 = OpLabel -%54 = OpAccessChain %50 %13 %53 %46 -%58 = OpLoad %3 %54 -OpBranch %56 -%56 = OpLabel -%59 = OpPhi %3 %55 %48 %58 %57 -OpReturnValue %59 +%46 = OpFunction %3 None %18 +%45 = OpFunctionParameter %11 +%44 = OpLabel +OpBranch %47 +%47 = OpLabel +%51 = OpULessThan %23 %45 %50 +OpSelectionMerge %54 None +OpBranchConditional %51 %55 %54 +%55 = OpLabel +%53 = OpAccessChain %49 %13 %52 %45 +%56 = OpLoad %3 %53 +OpBranch %54 +%54 = OpLabel +%57 = OpPhi %3 %26 %47 %56 %55 +OpReturnValue %57 OpFunctionEnd -%63 = OpFunction %3 None %64 -%61 = OpFunctionParameter %7 -%62 = OpFunctionParameter %11 -%60 = OpLabel +%61 = OpFunction %3 None %62 +%59 = OpFunctionParameter %7 +%60 = OpFunctionParameter %11 +%58 = OpLabel +OpBranch %63 +%63 = OpLabel +%64 = OpULessThan %23 %60 %50 +OpSelectionMerge %65 None +OpBranchConditional %64 %66 %65 +%66 = OpLabel +%67 = OpVectorExtractDynamic %3 %59 %60 OpBranch %65 %65 = OpLabel -%66 = OpULessThan %23 %62 %51 -OpSelectionMerge %68 None -OpBranchConditional %66 %69 %68 +%68 = OpPhi %3 %26 %63 %67 %66 +OpReturnValue %68 +OpFunctionEnd +%71 = OpFunction %7 None %72 +%70 = OpFunctionParameter %11 %69 = OpLabel -%70 = OpVectorExtractDynamic %3 %61 %62 -OpBranch %68 -%68 = OpLabel -%71 = OpPhi %3 %67 %65 %70 %69 -OpReturnValue %71 +OpBranch %73 +%73 = OpLabel +%76 = OpULessThan %23 %70 %38 +OpSelectionMerge %80 None +OpBranchConditional %76 %81 %80 +%81 = OpLabel +%78 = OpAccessChain %75 %13 %77 %70 +%82 = OpLoad %7 %78 +OpBranch %80 +%80 = OpLabel +%83 = OpPhi %7 %79 %73 %82 %81 +OpReturnValue %83 OpFunctionEnd -%74 = OpFunction %7 None %75 -%73 = OpFunctionParameter %11 -%72 = OpLabel -OpBranch %76 -%76 = OpLabel -%79 = OpULessThan %23 %73 %38 -OpSelectionMerge %83 None -OpBranchConditional %79 %84 %83 +%87 = OpFunction %3 None %88 +%85 = OpFunctionParameter %11 +%86 = OpFunctionParameter %11 %84 = OpLabel -%81 = OpAccessChain %78 %13 %80 %73 -%85 = OpLoad %7 %81 -OpBranch %83 -%83 = OpLabel -%86 = OpPhi %7 %82 %76 %85 %84 -OpReturnValue %86 +OpBranch %89 +%89 = OpLabel +%90 = OpULessThan %23 %86 %50 +%91 = OpULessThan %23 %85 %38 +%92 = OpLogicalAnd %23 %90 %91 +OpSelectionMerge %94 None +OpBranchConditional %92 %95 %94 +%95 = OpLabel +%93 = OpAccessChain %49 %13 %77 %85 %86 +%96 = OpLoad %3 %93 +OpBranch %94 +%94 = OpLabel +%97 = OpPhi %3 %26 %89 %96 %95 +OpReturnValue %97 OpFunctionEnd -%90 = OpFunction %3 None %91 -%88 = OpFunctionParameter %11 -%89 = OpFunctionParameter %11 -%87 = OpLabel -OpBranch %92 -%92 = OpLabel -%93 = OpULessThan %23 %89 %51 -%94 = OpULessThan %23 %88 %38 -%95 = OpLogicalAnd %23 %93 %94 -OpSelectionMerge %98 None -OpBranchConditional %95 %99 %98 -%99 = OpLabel -%96 = OpAccessChain %50 %13 %80 %88 %89 -%100 = OpLoad %3 %96 -OpBranch %98 +%100 = OpFunction %3 None %18 +%99 = OpFunctionParameter %11 %98 = OpLabel -%101 = OpPhi %3 %97 %92 %100 %99 -OpReturnValue %101 -OpFunctionEnd -%104 = OpFunction %3 None %18 -%103 = OpFunctionParameter %11 +OpBranch %102 %102 = OpLabel -OpBranch %106 -%106 = OpLabel -%107 = OpConvertSToF %3 %103 -%108 = OpFDiv %3 %107 %105 -%109 = OpExtInst %3 %1 Sin %108 -%110 = OpFMul %3 %109 %105 -%111 = OpConvertFToS %11 %110 -%112 = OpULessThan %23 %111 %5 -OpSelectionMerge %115 None -OpBranchConditional %112 %116 %115 -%116 = OpLabel -%113 = OpAccessChain %21 %13 %24 %111 -%117 = OpLoad %3 %113 -OpBranch %115 -%115 = OpLabel -%118 = OpPhi %3 %114 %106 %117 %116 -OpReturnValue %118 +%103 = OpConvertSToF %3 %99 +%104 = OpFDiv %3 %103 %101 +%105 = OpExtInst %3 %1 Sin %104 +%106 = OpFMul %3 %105 %101 +%107 = OpConvertFToS %11 %106 +%108 = OpULessThan %23 %107 %5 +OpSelectionMerge %110 None +OpBranchConditional %108 %111 %110 +%111 = OpLabel +%109 = OpAccessChain %21 %13 %24 %107 +%112 = OpLoad %3 %109 +OpBranch %110 +%110 = OpLabel +%113 = OpPhi %3 %26 %102 %112 %111 +OpReturnValue %113 OpFunctionEnd -%120 = OpFunction %3 None %121 -%119 = OpLabel -OpBranch %122 -%122 = OpLabel -%124 = OpAccessChain %21 %13 %24 %123 +%115 = OpFunction %3 None %116 +%114 = OpLabel +OpBranch %117 +%117 = OpLabel +%119 = OpAccessChain %21 %13 %24 %118 +%120 = OpLoad %3 %119 +%121 = OpAccessChain %49 %13 %52 %38 +%122 = OpLoad %3 %121 +%123 = OpFAdd %3 %120 %122 +%124 = OpAccessChain %49 %13 %77 %77 %38 %125 = OpLoad %3 %124 -%126 = OpAccessChain %50 %13 %53 %38 -%127 = OpLoad %3 %126 -%128 = OpFAdd %3 %125 %127 -%129 = OpAccessChain %50 %13 %80 %80 %38 -%130 = OpLoad %3 %129 -%131 = OpFAdd %3 %128 %130 -OpReturnValue %131 +%126 = OpFAdd %3 %123 %125 +OpReturnValue %126 OpFunctionEnd -%135 = OpFunction %2 None %136 -%133 = OpFunctionParameter %11 -%134 = OpFunctionParameter %3 +%130 = OpFunction %2 None %131 +%128 = OpFunctionParameter %11 +%129 = OpFunctionParameter %3 +%127 = OpLabel +OpBranch %132 %132 = OpLabel -OpBranch %137 +%133 = OpULessThan %23 %128 %5 +OpSelectionMerge %135 None +OpBranchConditional %133 %136 %135 +%136 = OpLabel +%134 = OpAccessChain %21 %13 %24 %128 +OpStore %134 %129 +OpBranch %135 +%135 = OpLabel +OpReturn +OpFunctionEnd +%140 = OpFunction %2 None %131 +%138 = OpFunctionParameter %11 +%139 = OpFunctionParameter %3 %137 = OpLabel -%138 = OpULessThan %23 %133 %5 -OpSelectionMerge %140 None -OpBranchConditional %138 %141 %140 +OpBranch %141 %141 = OpLabel -%139 = OpAccessChain %21 %13 %24 %133 -OpStore %139 %134 -OpBranch %140 -%140 = OpLabel -OpReturn -OpFunctionEnd -%145 = OpFunction %2 None %136 -%143 = OpFunctionParameter %11 -%144 = OpFunctionParameter %3 -%142 = OpLabel -OpBranch %146 +%142 = OpArrayLength %6 %13 3 +%143 = OpULessThan %23 %138 %142 +OpSelectionMerge %145 None +OpBranchConditional %143 %146 %145 %146 = OpLabel -%147 = OpArrayLength %6 %13 3 -%148 = OpULessThan %23 %143 %147 -OpSelectionMerge %150 None -OpBranchConditional %148 %151 %150 +%144 = OpAccessChain %21 %13 %38 %138 +OpStore %144 %139 +OpBranch %145 +%145 = OpLabel +OpReturn +OpFunctionEnd +%150 = OpFunction %2 None %131 +%148 = OpFunctionParameter %11 +%149 = OpFunctionParameter %3 +%147 = OpLabel +OpBranch %151 %151 = OpLabel -%149 = OpAccessChain %21 %13 %38 %143 -OpStore %149 %144 -OpBranch %150 -%150 = OpLabel +%152 = OpULessThan %23 %148 %50 +OpSelectionMerge %154 None +OpBranchConditional %152 %155 %154 +%155 = OpLabel +%153 = OpAccessChain %49 %13 %52 %148 +OpStore %153 %149 +OpBranch %154 +%154 = OpLabel OpReturn OpFunctionEnd -%155 = OpFunction %2 None %136 -%153 = OpFunctionParameter %11 -%154 = OpFunctionParameter %3 -%152 = OpLabel -OpBranch %156 +%159 = OpFunction %2 None %160 +%157 = OpFunctionParameter %11 +%158 = OpFunctionParameter %7 %156 = OpLabel -%157 = OpULessThan %23 %153 %51 -OpSelectionMerge %159 None -OpBranchConditional %157 %160 %159 -%160 = OpLabel -%158 = OpAccessChain %50 %13 %53 %153 -OpStore %158 %154 -OpBranch %159 -%159 = OpLabel -OpReturn -OpFunctionEnd -%164 = OpFunction %2 None %165 -%162 = OpFunctionParameter %11 -%163 = OpFunctionParameter %7 +OpBranch %161 %161 = OpLabel -OpBranch %166 -%166 = OpLabel -%167 = OpULessThan %23 %162 %38 -OpSelectionMerge %169 None -OpBranchConditional %167 %170 %169 -%170 = OpLabel -%168 = OpAccessChain %78 %13 %80 %162 -OpStore %168 %163 -OpBranch %169 -%169 = OpLabel +%162 = OpULessThan %23 %157 %38 +OpSelectionMerge %164 None +OpBranchConditional %162 %165 %164 +%165 = OpLabel +%163 = OpAccessChain %75 %13 %77 %157 +OpStore %163 %158 +OpBranch %164 +%164 = OpLabel OpReturn OpFunctionEnd -%175 = OpFunction %2 None %176 -%172 = OpFunctionParameter %11 -%173 = OpFunctionParameter %11 -%174 = OpFunctionParameter %3 -%171 = OpLabel +%170 = OpFunction %2 None %171 +%167 = OpFunctionParameter %11 +%168 = OpFunctionParameter %11 +%169 = OpFunctionParameter %3 +%166 = OpLabel +OpBranch %172 +%172 = OpLabel +%173 = OpULessThan %23 %168 %50 +%174 = OpULessThan %23 %167 %38 +%175 = OpLogicalAnd %23 %173 %174 +OpSelectionMerge %177 None +OpBranchConditional %175 %178 %177 +%178 = OpLabel +%176 = OpAccessChain %49 %13 %77 %167 %168 +OpStore %176 %169 OpBranch %177 %177 = OpLabel -%178 = OpULessThan %23 %173 %51 -%179 = OpULessThan %23 %172 %38 -%180 = OpLogicalAnd %23 %178 %179 -OpSelectionMerge %182 None -OpBranchConditional %180 %183 %182 +OpReturn +OpFunctionEnd +%182 = OpFunction %2 None %131 +%180 = OpFunctionParameter %11 +%181 = OpFunctionParameter %3 +%179 = OpLabel +OpBranch %183 %183 = OpLabel -%181 = OpAccessChain %50 %13 %80 %172 %173 -OpStore %181 %174 -OpBranch %182 -%182 = OpLabel +%184 = OpConvertSToF %3 %180 +%185 = OpFDiv %3 %184 %101 +%186 = OpExtInst %3 %1 Sin %185 +%187 = OpFMul %3 %186 %101 +%188 = OpConvertFToS %11 %187 +%189 = OpULessThan %23 %188 %5 +OpSelectionMerge %191 None +OpBranchConditional %189 %192 %191 +%192 = OpLabel +%190 = OpAccessChain %21 %13 %24 %188 +OpStore %190 %181 +OpBranch %191 +%191 = OpLabel OpReturn OpFunctionEnd -%187 = OpFunction %2 None %136 -%185 = OpFunctionParameter %11 -%186 = OpFunctionParameter %3 -%184 = OpLabel -OpBranch %188 -%188 = OpLabel -%189 = OpConvertSToF %3 %185 -%190 = OpFDiv %3 %189 %105 -%191 = OpExtInst %3 %1 Sin %190 -%192 = OpFMul %3 %191 %105 -%193 = OpConvertFToS %11 %192 -%194 = OpULessThan %23 %193 %5 -OpSelectionMerge %196 None -OpBranchConditional %194 %197 %196 +%195 = OpFunction %2 None %196 +%194 = OpFunctionParameter %3 +%193 = OpLabel +OpBranch %197 %197 = OpLabel -%195 = OpAccessChain %21 %13 %24 %193 -OpStore %195 %186 -OpBranch %196 -%196 = OpLabel -OpReturn -OpFunctionEnd -%200 = OpFunction %2 None %201 -%199 = OpFunctionParameter %3 -%198 = OpLabel -OpBranch %202 -%202 = OpLabel -%203 = OpAccessChain %21 %13 %24 %123 -OpStore %203 %199 -%204 = OpAccessChain %50 %13 %53 %38 -OpStore %204 %199 -%205 = OpAccessChain %50 %13 %80 %80 %38 -OpStore %205 %199 +%198 = OpAccessChain %21 %13 %24 %118 +OpStore %198 %194 +%199 = OpAccessChain %49 %13 %52 %38 +OpStore %199 %194 +%200 = OpAccessChain %49 %13 %77 %77 %38 +OpStore %200 %194 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/break-if.spvasm b/tests/out/spv/break-if.spvasm index 081cd21cc..9b17efb86 100644 --- a/tests/out/spv/break-if.spvasm +++ b/tests/out/spv/break-if.spvasm @@ -1,22 +1,19 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 50 +; Bound: 47 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %48 "main" -OpExecutionMode %48 LocalSize 1 1 1 +OpEntryPoint GLCompute %45 "main" +OpExecutionMode %45 LocalSize 1 1 1 %2 = OpTypeVoid %3 = OpTypeBool %6 = OpTypeFunction %2 %7 = OpConstantTrue %3 %14 = OpTypePointer Function %3 %15 = OpConstantNull %3 -%17 = OpConstantNull %3 -%21 = OpTypeFunction %2 %3 -%32 = OpConstantNull %3 -%34 = OpConstantNull %3 +%20 = OpTypeFunction %2 %3 %5 = OpFunction %2 None %6 %4 = OpLabel OpBranch %8 @@ -32,57 +29,57 @@ OpBranchConditional %7 %10 %9 %10 = OpLabel OpReturn OpFunctionEnd -%20 = OpFunction %2 None %21 -%19 = OpFunctionParameter %3 -%18 = OpLabel +%19 = OpFunction %2 None %20 +%18 = OpFunctionParameter %3 +%17 = OpLabel %13 = OpVariable %14 Function %15 -%16 = OpVariable %14 Function %17 +%16 = OpVariable %14 Function %15 +OpBranch %21 +%21 = OpLabel OpBranch %22 %22 = OpLabel -OpBranch %23 -%23 = OpLabel -OpLoopMerge %24 %26 None +OpLoopMerge %23 %25 None +OpBranch %24 +%24 = OpLabel OpBranch %25 %25 = OpLabel -OpBranch %26 -%26 = OpLabel -OpStore %13 %19 -%27 = OpLoad %3 %13 -%28 = OpLogicalNotEqual %3 %19 %27 -OpStore %16 %28 -%29 = OpLoad %3 %16 -%30 = OpLogicalEqual %3 %19 %29 -OpBranchConditional %30 %24 %23 -%24 = OpLabel +OpStore %13 %18 +%26 = OpLoad %3 %13 +%27 = OpLogicalNotEqual %3 %18 %26 +OpStore %16 %27 +%28 = OpLoad %3 %16 +%29 = OpLogicalEqual %3 %18 %28 +OpBranchConditional %29 %23 %22 +%23 = OpLabel OpReturn OpFunctionEnd -%37 = OpFunction %2 None %21 -%36 = OpFunctionParameter %3 +%34 = OpFunction %2 None %20 +%33 = OpFunctionParameter %3 +%32 = OpLabel +%30 = OpVariable %14 Function %15 +%31 = OpVariable %14 Function %15 +OpBranch %35 %35 = OpLabel -%31 = OpVariable %14 Function %32 -%33 = OpVariable %14 Function %34 +OpBranch %36 +%36 = OpLabel +OpLoopMerge %37 %39 None OpBranch %38 %38 = OpLabel +OpStore %30 %33 +%40 = OpLoad %3 %30 +%41 = OpLogicalNotEqual %3 %33 %40 +OpStore %31 %41 OpBranch %39 %39 = OpLabel -OpLoopMerge %40 %42 None -OpBranch %41 -%41 = OpLabel -OpStore %31 %36 -%43 = OpLoad %3 %31 -%44 = OpLogicalNotEqual %3 %36 %43 -OpStore %33 %44 -OpBranch %42 -%42 = OpLabel -%45 = OpLoad %3 %33 -%46 = OpLogicalEqual %3 %36 %45 -OpBranchConditional %46 %40 %39 -%40 = OpLabel +%42 = OpLoad %3 %31 +%43 = OpLogicalEqual %3 %33 %42 +OpBranchConditional %43 %37 %36 +%37 = OpLabel OpReturn OpFunctionEnd -%48 = OpFunction %2 None %6 -%47 = OpLabel -OpBranch %49 -%49 = OpLabel +%45 = OpFunction %2 None %6 +%44 = OpLabel +OpBranch %46 +%46 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index a8ed9ab78..f8212185c 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -1,28 +1,28 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 63 +; Bound: 62 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %52 "main" %49 -OpExecutionMode %52 LocalSize 1 1 1 +OpEntryPoint GLCompute %51 "main" %48 +OpExecutionMode %51 LocalSize 1 1 1 OpMemberName %5 0 "data" OpName %5 "PrimeIndices" OpName %7 "v_indices" OpName %9 "n" OpName %12 "i" -OpName %15 "n_base" -OpName %16 "collatz_iterations" -OpName %49 "global_id" -OpName %52 "main" +OpName %14 "n_base" +OpName %15 "collatz_iterations" +OpName %48 "global_id" +OpName %51 "main" OpDecorate %4 ArrayStride 4 OpMemberDecorate %5 0 Offset 0 OpDecorate %7 DescriptorSet 0 OpDecorate %7 Binding 0 OpDecorate %5 Block -OpDecorate %49 BuiltIn GlobalInvocationId +OpDecorate %48 BuiltIn GlobalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeRuntimeArray %3 @@ -32,81 +32,80 @@ OpDecorate %49 BuiltIn GlobalInvocationId %7 = OpVariable %8 StorageBuffer %10 = OpTypePointer Function %3 %11 = OpConstantNull %3 -%13 = OpConstantNull %3 -%17 = OpTypeFunction %3 %3 -%18 = OpConstant %3 0 -%19 = OpConstant %3 1 -%20 = OpConstant %3 2 -%21 = OpConstant %3 3 -%28 = OpTypeBool -%50 = OpTypePointer Input %6 -%49 = OpVariable %50 Input -%53 = OpTypeFunction %2 -%55 = OpTypePointer StorageBuffer %4 -%57 = OpTypePointer StorageBuffer %3 -%16 = OpFunction %3 None %17 -%15 = OpFunctionParameter %3 -%14 = OpLabel +%16 = OpTypeFunction %3 %3 +%17 = OpConstant %3 0 +%18 = OpConstant %3 1 +%19 = OpConstant %3 2 +%20 = OpConstant %3 3 +%27 = OpTypeBool +%49 = OpTypePointer Input %6 +%48 = OpVariable %49 Input +%52 = OpTypeFunction %2 +%54 = OpTypePointer StorageBuffer %4 +%56 = OpTypePointer StorageBuffer %3 +%15 = OpFunction %3 None %16 +%14 = OpFunctionParameter %3 +%13 = OpLabel %9 = OpVariable %10 Function %11 -%12 = OpVariable %10 Function %13 +%12 = OpVariable %10 Function %11 +OpBranch %21 +%21 = OpLabel +OpStore %9 %14 +OpStore %12 %17 OpBranch %22 %22 = OpLabel -OpStore %9 %15 -OpStore %12 %18 -OpBranch %23 -%23 = OpLabel -OpLoopMerge %24 %26 None -OpBranch %25 -%25 = OpLabel -%27 = OpLoad %3 %9 -%29 = OpUGreaterThan %28 %27 %19 -OpSelectionMerge %30 None -OpBranchConditional %29 %30 %31 -%31 = OpLabel +OpLoopMerge %23 %25 None OpBranch %24 +%24 = OpLabel +%26 = OpLoad %3 %9 +%28 = OpUGreaterThan %27 %26 %18 +OpSelectionMerge %29 None +OpBranchConditional %28 %29 %30 %30 = OpLabel +OpBranch %23 +%29 = OpLabel +OpBranch %31 +%31 = OpLabel +%33 = OpLoad %3 %9 +%34 = OpUMod %3 %33 %19 +%35 = OpIEqual %27 %34 %17 +OpSelectionMerge %36 None +OpBranchConditional %35 %37 %38 +%37 = OpLabel +%39 = OpLoad %3 %9 +%40 = OpUDiv %3 %39 %19 +OpStore %9 %40 +OpBranch %36 +%38 = OpLabel +%41 = OpLoad %3 %9 +%42 = OpIMul %3 %20 %41 +%43 = OpIAdd %3 %42 %18 +OpStore %9 %43 +OpBranch %36 +%36 = OpLabel +%44 = OpLoad %3 %12 +%45 = OpIAdd %3 %44 %18 +OpStore %12 %45 OpBranch %32 %32 = OpLabel -%34 = OpLoad %3 %9 -%35 = OpUMod %3 %34 %20 -%36 = OpIEqual %28 %35 %18 -OpSelectionMerge %37 None -OpBranchConditional %36 %38 %39 -%38 = OpLabel -%40 = OpLoad %3 %9 -%41 = OpUDiv %3 %40 %20 -OpStore %9 %41 -OpBranch %37 -%39 = OpLabel -%42 = OpLoad %3 %9 -%43 = OpIMul %3 %21 %42 -%44 = OpIAdd %3 %43 %19 -OpStore %9 %44 -OpBranch %37 -%37 = OpLabel -%45 = OpLoad %3 %12 -%46 = OpIAdd %3 %45 %19 -OpStore %12 %46 -OpBranch %33 -%33 = OpLabel -OpBranch %26 -%26 = OpLabel -OpBranch %23 -%24 = OpLabel -%47 = OpLoad %3 %12 -OpReturnValue %47 +OpBranch %25 +%25 = OpLabel +OpBranch %22 +%23 = OpLabel +%46 = OpLoad %3 %12 +OpReturnValue %46 OpFunctionEnd -%52 = OpFunction %2 None %53 -%48 = OpLabel -%51 = OpLoad %6 %49 -OpBranch %54 -%54 = OpLabel -%56 = OpCompositeExtract %3 %51 0 -%58 = OpCompositeExtract %3 %51 0 -%59 = OpAccessChain %57 %7 %18 %58 -%60 = OpLoad %3 %59 -%61 = OpFunctionCall %3 %16 %60 -%62 = OpAccessChain %57 %7 %18 %56 -OpStore %62 %61 +%51 = OpFunction %2 None %52 +%47 = OpLabel +%50 = OpLoad %6 %48 +OpBranch %53 +%53 = OpLabel +%55 = OpCompositeExtract %3 %50 0 +%57 = OpCompositeExtract %3 %50 0 +%58 = OpAccessChain %56 %7 %17 %57 +%59 = OpLoad %3 %58 +%60 = OpFunctionCall %3 %15 %59 +%61 = OpAccessChain %56 %7 %17 %55 +OpStore %61 %60 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/constructors.spvasm b/tests/out/spv/constructors.spvasm index 2a2b3ad0f..f52bd338c 100644 --- a/tests/out/spv/constructors.spvasm +++ b/tests/out/spv/constructors.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 90 +; Bound: 74 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %47 "main" -OpExecutionMode %47 LocalSize 1 1 1 +OpEntryPoint GLCompute %46 "main" +OpExecutionMode %46 LocalSize 1 1 1 OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpDecorate %10 ArrayStride 16 @@ -54,47 +54,31 @@ OpDecorate %17 ArrayStride 4 %41 = OpConstant %5 2 %42 = OpConstantComposite %17 %40 %29 %41 %37 %44 = OpTypePointer Function %6 -%45 = OpConstantNull %6 -%48 = OpTypeFunction %2 -%49 = OpConstantNull %13 -%50 = OpConstantNull %5 -%51 = OpConstantNull %12 -%52 = OpConstantNull %4 -%53 = OpConstantNull %14 -%54 = OpConstantNull %8 -%55 = OpConstantNull %15 -%56 = OpConstantNull %6 -%57 = OpConstant %12 0 -%58 = OpConstantNull %13 -%59 = OpConstantNull %5 -%60 = OpConstantNull %12 -%61 = OpConstantNull %4 -%62 = OpConstantNull %14 -%63 = OpConstantNull %20 -%64 = OpConstantNull %14 -%65 = OpConstantNull %20 -%47 = OpFunction %2 None %48 -%46 = OpLabel -%43 = OpVariable %44 Function %45 -OpBranch %66 -%66 = OpLabel -%67 = OpCompositeConstruct %3 %22 %22 %22 %22 -%68 = OpCompositeConstruct %6 %67 %29 -OpStore %43 %68 -%69 = OpCompositeConstruct %9 %22 %21 -%70 = OpCompositeConstruct %9 %21 %22 -%71 = OpCompositeConstruct %8 %69 %70 -%72 = OpCompositeConstruct %3 %22 %21 %21 %21 -%73 = OpCompositeConstruct %3 %21 %22 %21 %21 -%74 = OpCompositeConstruct %3 %21 %21 %22 %21 -%75 = OpCompositeConstruct %3 %21 %21 %21 %22 -%76 = OpCompositeConstruct %19 %72 %73 %74 %75 -%77 = OpCompositeConstruct %14 %57 %57 -%78 = OpCompositeConstruct %9 %21 %21 -%79 = OpCompositeConstruct %9 %21 %21 -%80 = OpCompositeConstruct %8 %78 %79 -%81 = OpCompositeConstruct %17 %40 %29 %41 %37 -%87 = OpCopyObject %20 %63 -%89 = OpCopyObject %20 %65 +%47 = OpTypeFunction %2 +%48 = OpConstant %12 0 +%49 = OpConstantNull %20 +%46 = OpFunction %2 None %47 +%45 = OpLabel +%43 = OpVariable %44 Function %39 +OpBranch %50 +%50 = OpLabel +%51 = OpCompositeConstruct %3 %22 %22 %22 %22 +%52 = OpCompositeConstruct %6 %51 %29 +OpStore %43 %52 +%53 = OpCompositeConstruct %9 %22 %21 +%54 = OpCompositeConstruct %9 %21 %22 +%55 = OpCompositeConstruct %8 %53 %54 +%56 = OpCompositeConstruct %3 %22 %21 %21 %21 +%57 = OpCompositeConstruct %3 %21 %22 %21 %21 +%58 = OpCompositeConstruct %3 %21 %21 %22 %21 +%59 = OpCompositeConstruct %3 %21 %21 %21 %22 +%60 = OpCompositeConstruct %19 %56 %57 %58 %59 +%61 = OpCompositeConstruct %14 %48 %48 +%62 = OpCompositeConstruct %9 %21 %21 +%63 = OpCompositeConstruct %9 %21 %21 +%64 = OpCompositeConstruct %8 %62 %63 +%65 = OpCompositeConstruct %17 %40 %29 %41 %37 +%71 = OpCopyObject %20 %49 +%73 = OpCopyObject %20 %49 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/debug-symbol-terrain.spvasm b/tests/out/spv/debug-symbol-terrain.spvasm index 9fb3bbff9..fcc14e485 100644 --- a/tests/out/spv/debug-symbol-terrain.spvasm +++ b/tests/out/spv/debug-symbol-terrain.spvasm @@ -1,19 +1,19 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 653 +; Bound: 647 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %351 "gen_terrain_compute" %348 -OpEntryPoint Vertex %421 "gen_terrain_vertex" %412 %415 %417 %419 -OpEntryPoint Fragment %475 "gen_terrain_fragment" %465 %467 %470 %473 %474 -OpEntryPoint Vertex %566 "vs_main" %557 %560 %562 %563 %565 -OpEntryPoint Fragment %593 "fs_main" %586 %588 %590 %592 -OpExecutionMode %351 LocalSize 64 1 1 -OpExecutionMode %475 OriginUpperLeft -OpExecutionMode %593 OriginUpperLeft +OpEntryPoint GLCompute %348 "gen_terrain_compute" %345 +OpEntryPoint Vertex %418 "gen_terrain_vertex" %409 %412 %414 %416 +OpEntryPoint Fragment %470 "gen_terrain_fragment" %460 %462 %465 %468 %469 +OpEntryPoint Vertex %561 "vs_main" %552 %555 %557 %558 %560 +OpEntryPoint Fragment %587 "fs_main" %580 %582 %584 %586 +OpExecutionMode %348 LocalSize 64 1 1 +OpExecutionMode %470 OriginUpperLeft +OpExecutionMode %587 OriginUpperLeft %3 = OpString "debug-symbol-terrain" OpSource Unknown 0 %3 "// Taken from https://github.com/sotrh/learn-wgpu/blob/11820796f5e1dbce42fb1119f04ddeb4b167d2a0/code/intermediate/tutorial13-terrain/src/terrain.wgsl // ============================ @@ -360,54 +360,54 @@ OpName %52 "x" OpName %53 "permute3" OpName %65 "i" OpName %68 "i1" -OpName %70 "x12" -OpName %73 "m" -OpName %77 "v" -OpName %78 "snoise2" -OpName %205 "x" -OpName %207 "v" -OpName %210 "a" -OpName %212 "i" -OpName %216 "p" -OpName %217 "fbm" -OpName %261 "p" -OpName %262 "min_max_height" -OpName %263 "terrain_point" -OpName %274 "p" -OpName %275 "min_max_height" -OpName %276 "terrain_vertex" -OpName %306 "vert_index" -OpName %307 "chunk_size" -OpName %308 "chunk_corner" -OpName %309 "index_to_p" -OpName %325 "p" -OpName %326 "color23" -OpName %348 "gid" -OpName %351 "gen_terrain_compute" -OpName %412 "vindex" -OpName %415 "index" -OpName %417 "position" -OpName %419 "uv" -OpName %421 "gen_terrain_vertex" -OpName %459 "vert_component" -OpName %461 "index" -OpName %465 "index" -OpName %467 "position" -OpName %470 "uv" -OpName %473 "vert_component" -OpName %474 "index" -OpName %475 "gen_terrain_fragment" -OpName %557 "position" -OpName %560 "normal" -OpName %562 "clip_position" -OpName %563 "normal" -OpName %565 "world_pos" -OpName %566 "vs_main" -OpName %582 "color" -OpName %586 "clip_position" -OpName %588 "normal" -OpName %590 "world_pos" -OpName %593 "fs_main" +OpName %69 "x12" +OpName %72 "m" +OpName %76 "v" +OpName %77 "snoise2" +OpName %204 "x" +OpName %205 "v" +OpName %208 "a" +OpName %209 "i" +OpName %213 "p" +OpName %214 "fbm" +OpName %258 "p" +OpName %259 "min_max_height" +OpName %260 "terrain_point" +OpName %271 "p" +OpName %272 "min_max_height" +OpName %273 "terrain_vertex" +OpName %303 "vert_index" +OpName %304 "chunk_size" +OpName %305 "chunk_corner" +OpName %306 "index_to_p" +OpName %322 "p" +OpName %323 "color23" +OpName %345 "gid" +OpName %348 "gen_terrain_compute" +OpName %409 "vindex" +OpName %412 "index" +OpName %414 "position" +OpName %416 "uv" +OpName %418 "gen_terrain_vertex" +OpName %456 "vert_component" +OpName %457 "index" +OpName %460 "index" +OpName %462 "position" +OpName %465 "uv" +OpName %468 "vert_component" +OpName %469 "index" +OpName %470 "gen_terrain_fragment" +OpName %552 "position" +OpName %555 "normal" +OpName %557 "clip_position" +OpName %558 "normal" +OpName %560 "world_pos" +OpName %561 "vs_main" +OpName %577 "color" +OpName %580 "clip_position" +OpName %582 "normal" +OpName %584 "world_pos" +OpName %587 "fs_main" OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %13 1 Offset 8 OpMemberDecorate %13 2 Offset 16 @@ -466,27 +466,27 @@ OpDecorate %49 DescriptorSet 2 OpDecorate %49 Binding 2 OpDecorate %50 DescriptorSet 2 OpDecorate %50 Binding 3 -OpDecorate %348 BuiltIn GlobalInvocationId -OpDecorate %412 BuiltIn VertexIndex -OpDecorate %415 Location 0 -OpDecorate %415 Flat -OpDecorate %417 BuiltIn Position -OpDecorate %419 Location 1 -OpDecorate %465 Location 0 -OpDecorate %465 Flat -OpDecorate %467 BuiltIn FragCoord -OpDecorate %470 Location 1 -OpDecorate %473 Location 0 -OpDecorate %474 Location 1 -OpDecorate %557 Location 0 +OpDecorate %345 BuiltIn GlobalInvocationId +OpDecorate %409 BuiltIn VertexIndex +OpDecorate %412 Location 0 +OpDecorate %412 Flat +OpDecorate %414 BuiltIn Position +OpDecorate %416 Location 1 +OpDecorate %460 Location 0 +OpDecorate %460 Flat +OpDecorate %462 BuiltIn FragCoord +OpDecorate %465 Location 1 +OpDecorate %468 Location 0 +OpDecorate %469 Location 1 +OpDecorate %552 Location 0 +OpDecorate %555 Location 1 +OpDecorate %557 BuiltIn Position +OpDecorate %558 Location 0 OpDecorate %560 Location 1 -OpDecorate %562 BuiltIn Position -OpDecorate %563 Location 0 -OpDecorate %565 Location 1 -OpDecorate %586 BuiltIn FragCoord -OpDecorate %588 Location 0 -OpDecorate %590 Location 1 -OpDecorate %592 Location 0 +OpDecorate %580 BuiltIn FragCoord +OpDecorate %582 Location 0 +OpDecorate %584 Location 1 +OpDecorate %586 Location 0 %2 = OpTypeVoid %5 = OpTypeFloat 32 %4 = OpTypeVector %5 3 @@ -541,102 +541,96 @@ OpDecorate %592 Location 0 %57 = OpConstant %5 289.0 %66 = OpTypePointer Function %6 %67 = OpConstantNull %6 -%69 = OpConstantNull %6 -%71 = OpTypePointer Function %7 -%72 = OpConstantNull %7 -%74 = OpTypePointer Function %4 -%75 = OpConstantNull %4 -%79 = OpTypeFunction %5 %6 -%80 = OpConstant %5 0.21132487 -%81 = OpConstant %5 0.36602542 -%82 = OpConstant %5 -0.57735026 -%83 = OpConstant %5 0.024390243 -%84 = OpConstant %5 0.0 -%85 = OpConstant %5 0.5 -%86 = OpConstant %5 2.0 -%87 = OpConstant %5 1.7928429 -%88 = OpConstant %5 0.85373473 -%89 = OpConstant %5 130.0 -%108 = OpTypeBool -%111 = OpTypeVector %108 2 -%122 = OpTypePointer Function %5 -%123 = OpConstant %8 1 -%132 = OpConstant %8 0 -%206 = OpConstantNull %6 -%208 = OpTypePointer Function %5 -%209 = OpConstantNull %5 -%211 = OpConstantNull %5 -%213 = OpTypePointer Function %8 -%214 = OpConstantNull %8 -%218 = OpConstant %8 5 -%219 = OpConstant %5 0.01 -%220 = OpConstant %5 100.0 -%264 = OpTypeFunction %4 %6 %6 -%277 = OpTypeFunction %14 %6 %6 -%278 = OpConstant %5 0.1 -%279 = OpConstant %5 -0.1 -%310 = OpTypeFunction %6 %8 %10 %11 -%327 = OpTypeFunction %4 %6 -%328 = OpConstant %5 23.0 -%329 = OpConstant %5 32.0 -%330 = OpConstant %5 -43.0 -%331 = OpConstant %5 3.0 -%349 = OpTypePointer Input %19 -%348 = OpVariable %349 Input -%352 = OpTypeFunction %2 -%353 = OpTypePointer Uniform %13 -%355 = OpConstant %8 6 -%356 = OpConstant %8 2 -%357 = OpConstant %8 3 -%358 = OpConstant %8 4 -%361 = OpTypePointer Uniform %10 -%364 = OpTypePointer Uniform %11 -%368 = OpTypePointer StorageBuffer %15 -%369 = OpTypePointer StorageBuffer %14 -%370 = OpTypePointer Uniform %6 -%377 = OpTypePointer Uniform %8 -%398 = OpTypePointer StorageBuffer %17 -%399 = OpTypePointer StorageBuffer %8 -%413 = OpTypePointer Input %8 -%412 = OpVariable %413 Input -%416 = OpTypePointer Output %8 -%415 = OpVariable %416 Output -%418 = OpTypePointer Output %7 -%417 = OpVariable %418 Output -%420 = OpTypePointer Output %6 -%419 = OpVariable %420 Output -%422 = OpTypePointer Uniform %20 -%424 = OpConstant %5 -1.0 -%440 = OpTypePointer Uniform %8 -%460 = OpConstantNull %5 -%462 = OpConstantNull %8 -%465 = OpVariable %413 Input -%468 = OpTypePointer Input %7 -%467 = OpVariable %468 Input -%471 = OpTypePointer Input %6 -%470 = OpVariable %471 Input -%473 = OpVariable %416 Output -%474 = OpVariable %416 Output -%477 = OpConstant %5 6.0 -%558 = OpTypePointer Input %4 -%557 = OpVariable %558 Input -%560 = OpVariable %558 Input -%562 = OpVariable %418 Output -%564 = OpTypePointer Output %4 -%563 = OpVariable %564 Output -%565 = OpVariable %564 Output -%567 = OpTypePointer Uniform %24 -%570 = OpTypePointer Uniform %23 -%583 = OpConstantNull %4 -%586 = OpVariable %468 Input -%588 = OpVariable %558 Input -%590 = OpVariable %558 Input -%592 = OpVariable %418 Output -%595 = OpTypePointer Uniform %25 -%597 = OpConstant %5 0.7 -%598 = OpConstant %5 0.2 -%617 = OpTypePointer Uniform %4 -%626 = OpTypePointer Uniform %7 +%70 = OpTypePointer Function %7 +%71 = OpConstantNull %7 +%73 = OpTypePointer Function %4 +%74 = OpConstantNull %4 +%78 = OpTypeFunction %5 %6 +%79 = OpConstant %5 0.21132487 +%80 = OpConstant %5 0.36602542 +%81 = OpConstant %5 -0.57735026 +%82 = OpConstant %5 0.024390243 +%83 = OpConstant %5 0.0 +%84 = OpConstant %5 0.5 +%85 = OpConstant %5 2.0 +%86 = OpConstant %5 1.7928429 +%87 = OpConstant %5 0.85373473 +%88 = OpConstant %5 130.0 +%107 = OpTypeBool +%110 = OpTypeVector %107 2 +%121 = OpTypePointer Function %5 +%122 = OpConstant %8 1 +%131 = OpConstant %8 0 +%206 = OpTypePointer Function %5 +%207 = OpConstantNull %5 +%210 = OpTypePointer Function %8 +%211 = OpConstantNull %8 +%215 = OpConstant %8 5 +%216 = OpConstant %5 0.01 +%217 = OpConstant %5 100.0 +%261 = OpTypeFunction %4 %6 %6 +%274 = OpTypeFunction %14 %6 %6 +%275 = OpConstant %5 0.1 +%276 = OpConstant %5 -0.1 +%307 = OpTypeFunction %6 %8 %10 %11 +%324 = OpTypeFunction %4 %6 +%325 = OpConstant %5 23.0 +%326 = OpConstant %5 32.0 +%327 = OpConstant %5 -43.0 +%328 = OpConstant %5 3.0 +%346 = OpTypePointer Input %19 +%345 = OpVariable %346 Input +%349 = OpTypeFunction %2 +%350 = OpTypePointer Uniform %13 +%352 = OpConstant %8 6 +%353 = OpConstant %8 2 +%354 = OpConstant %8 3 +%355 = OpConstant %8 4 +%358 = OpTypePointer Uniform %10 +%361 = OpTypePointer Uniform %11 +%365 = OpTypePointer StorageBuffer %15 +%366 = OpTypePointer StorageBuffer %14 +%367 = OpTypePointer Uniform %6 +%374 = OpTypePointer Uniform %8 +%395 = OpTypePointer StorageBuffer %17 +%396 = OpTypePointer StorageBuffer %8 +%410 = OpTypePointer Input %8 +%409 = OpVariable %410 Input +%413 = OpTypePointer Output %8 +%412 = OpVariable %413 Output +%415 = OpTypePointer Output %7 +%414 = OpVariable %415 Output +%417 = OpTypePointer Output %6 +%416 = OpVariable %417 Output +%419 = OpTypePointer Uniform %20 +%421 = OpConstant %5 -1.0 +%437 = OpTypePointer Uniform %8 +%460 = OpVariable %410 Input +%463 = OpTypePointer Input %7 +%462 = OpVariable %463 Input +%466 = OpTypePointer Input %6 +%465 = OpVariable %466 Input +%468 = OpVariable %413 Output +%469 = OpVariable %413 Output +%472 = OpConstant %5 6.0 +%553 = OpTypePointer Input %4 +%552 = OpVariable %553 Input +%555 = OpVariable %553 Input +%557 = OpVariable %415 Output +%559 = OpTypePointer Output %4 +%558 = OpVariable %559 Output +%560 = OpVariable %559 Output +%562 = OpTypePointer Uniform %24 +%565 = OpTypePointer Uniform %23 +%580 = OpVariable %463 Input +%582 = OpVariable %553 Input +%584 = OpVariable %553 Input +%586 = OpVariable %415 Output +%589 = OpTypePointer Uniform %25 +%591 = OpConstant %5 0.7 +%592 = OpConstant %5 0.2 +%611 = OpTypePointer Uniform %4 +%620 = OpTypePointer Uniform %7 %53 = OpFunction %4 None %54 %52 = OpFunctionParameter %4 %51 = OpLabel @@ -653,818 +647,818 @@ OpLine %3 10 49 %64 = OpFRem %4 %62 %63 OpReturnValue %64 OpFunctionEnd -%78 = OpFunction %5 None %79 -%77 = OpFunctionParameter %6 -%76 = OpLabel -%68 = OpVariable %66 Function %69 -%73 = OpVariable %74 Function %75 +%77 = OpFunction %5 None %78 +%76 = OpFunctionParameter %6 +%75 = OpLabel +%68 = OpVariable %66 Function %67 +%72 = OpVariable %73 Function %74 %65 = OpVariable %66 Function %67 -%70 = OpVariable %71 Function %72 -OpBranch %90 -%90 = OpLabel +%69 = OpVariable %70 Function %71 +OpBranch %89 +%89 = OpLabel OpLine %3 13 13 -%91 = OpCompositeConstruct %7 %80 %81 %82 %83 +%90 = OpCompositeConstruct %7 %79 %80 %81 %82 OpLine %3 14 24 -%92 = OpVectorShuffle %6 %91 %91 1 1 -%93 = OpDot %5 %77 %92 -%94 = OpCompositeConstruct %6 %93 %93 -%95 = OpFAdd %6 %77 %94 -%96 = OpExtInst %6 %1 Floor %95 +%91 = OpVectorShuffle %6 %90 %90 1 1 +%92 = OpDot %5 %76 %91 +%93 = OpCompositeConstruct %6 %92 %92 +%94 = OpFAdd %6 %76 %93 +%95 = OpExtInst %6 %1 Floor %94 OpLine %3 14 5 -OpStore %65 %96 +OpStore %65 %95 OpLine %3 15 14 -%97 = OpLoad %6 %65 -%98 = OpFSub %6 %77 %97 -%99 = OpLoad %6 %65 -%100 = OpVectorShuffle %6 %91 %91 0 0 -%101 = OpDot %5 %99 %100 -%102 = OpCompositeConstruct %6 %101 %101 -%103 = OpFAdd %6 %98 %102 +%96 = OpLoad %6 %65 +%97 = OpFSub %6 %76 %96 +%98 = OpLoad %6 %65 +%99 = OpVectorShuffle %6 %90 %90 0 0 +%100 = OpDot %5 %98 %99 +%101 = OpCompositeConstruct %6 %100 %100 +%102 = OpFAdd %6 %97 %101 OpLine %3 17 32 -%104 = OpCompositeConstruct %6 %56 %84 +%103 = OpCompositeConstruct %6 %56 %83 OpLine %3 17 25 -%105 = OpCompositeConstruct %6 %84 %56 -%106 = OpCompositeExtract %5 %103 0 -%107 = OpCompositeExtract %5 %103 1 -%109 = OpFOrdLessThan %108 %106 %107 -%112 = OpCompositeConstruct %111 %109 %109 -%110 = OpSelect %6 %112 %105 %104 +%104 = OpCompositeConstruct %6 %83 %56 +%105 = OpCompositeExtract %5 %102 0 +%106 = OpCompositeExtract %5 %102 1 +%108 = OpFOrdLessThan %107 %105 %106 +%111 = OpCompositeConstruct %110 %108 %108 +%109 = OpSelect %6 %111 %104 %103 OpLine %3 17 5 -OpStore %68 %110 +OpStore %68 %109 OpLine %3 18 26 -%113 = OpVectorShuffle %7 %103 %103 0 1 0 1 -%114 = OpVectorShuffle %7 %91 %91 0 0 2 2 -%115 = OpFAdd %7 %113 %114 -%116 = OpLoad %6 %68 +%112 = OpVectorShuffle %7 %102 %102 0 1 0 1 +%113 = OpVectorShuffle %7 %90 %90 0 0 2 2 +%114 = OpFAdd %7 %112 %113 +%115 = OpLoad %6 %68 OpLine %3 18 26 -%117 = OpCompositeConstruct %7 %116 %84 %84 -%118 = OpFSub %7 %115 %117 +%116 = OpCompositeConstruct %7 %115 %83 %83 +%117 = OpFSub %7 %114 %116 OpLine %3 18 5 -OpStore %70 %118 +OpStore %69 %117 OpLine %3 1 1 -%119 = OpLoad %6 %65 +%118 = OpLoad %6 %65 OpLine %3 19 9 -%120 = OpCompositeConstruct %6 %57 %57 -%121 = OpFRem %6 %119 %120 +%119 = OpCompositeConstruct %6 %57 %57 +%120 = OpFRem %6 %118 %119 OpLine %3 19 5 -OpStore %65 %121 +OpStore %65 %120 OpLine %3 20 31 -%124 = OpAccessChain %122 %65 %123 -%125 = OpLoad %5 %124 +%123 = OpAccessChain %121 %65 %122 +%124 = OpLoad %5 %123 OpLine %3 20 51 -%126 = OpAccessChain %122 %68 %123 -%127 = OpLoad %5 %126 +%125 = OpAccessChain %121 %68 %122 +%126 = OpLoad %5 %125 OpLine %3 20 31 -%128 = OpCompositeConstruct %4 %84 %127 %56 -%129 = OpCompositeConstruct %4 %125 %125 %125 -%130 = OpFAdd %4 %129 %128 +%127 = OpCompositeConstruct %4 %83 %126 %56 +%128 = OpCompositeConstruct %4 %124 %124 %124 +%129 = OpFAdd %4 %128 %127 OpLine %3 20 22 -%131 = OpFunctionCall %4 %53 %130 +%130 = OpFunctionCall %4 %53 %129 OpLine %3 20 22 -%133 = OpAccessChain %122 %65 %132 -%134 = OpLoad %5 %133 -%135 = OpCompositeConstruct %4 %134 %134 %134 -%136 = OpFAdd %4 %131 %135 +%132 = OpAccessChain %121 %65 %131 +%133 = OpLoad %5 %132 +%134 = OpCompositeConstruct %4 %133 %133 %133 +%135 = OpFAdd %4 %130 %134 OpLine %3 20 84 -%137 = OpAccessChain %122 %68 %132 -%138 = OpLoad %5 %137 +%136 = OpAccessChain %121 %68 %131 +%137 = OpLoad %5 %136 OpLine %3 20 22 -%139 = OpCompositeConstruct %4 %84 %138 %56 -%140 = OpFAdd %4 %136 %139 +%138 = OpCompositeConstruct %4 %83 %137 %56 +%139 = OpFAdd %4 %135 %138 OpLine %3 20 13 -%141 = OpFunctionCall %4 %53 %140 +%140 = OpFunctionCall %4 %53 %139 OpLine %3 21 28 -%142 = OpDot %5 %103 %103 -%143 = OpLoad %7 %70 -%144 = OpVectorShuffle %6 %143 %143 0 1 -%145 = OpLoad %7 %70 -%146 = OpVectorShuffle %6 %145 %145 0 1 -%147 = OpDot %5 %144 %146 -%148 = OpLoad %7 %70 -%149 = OpVectorShuffle %6 %148 %148 2 3 -%150 = OpLoad %7 %70 -%151 = OpVectorShuffle %6 %150 %150 2 3 -%152 = OpDot %5 %149 %151 -%153 = OpCompositeConstruct %4 %142 %147 %152 -%154 = OpCompositeConstruct %4 %85 %85 %85 -%155 = OpFSub %4 %154 %153 +%141 = OpDot %5 %102 %102 +%142 = OpLoad %7 %69 +%143 = OpVectorShuffle %6 %142 %142 0 1 +%144 = OpLoad %7 %69 +%145 = OpVectorShuffle %6 %144 %144 0 1 +%146 = OpDot %5 %143 %145 +%147 = OpLoad %7 %69 +%148 = OpVectorShuffle %6 %147 %147 2 3 +%149 = OpLoad %7 %69 +%150 = OpVectorShuffle %6 %149 %149 2 3 +%151 = OpDot %5 %148 %150 +%152 = OpCompositeConstruct %4 %141 %146 %151 +%153 = OpCompositeConstruct %4 %84 %84 %84 +%154 = OpFSub %4 %153 %152 OpLine %3 21 24 -%156 = OpCompositeConstruct %4 %84 %84 %84 -%157 = OpExtInst %4 %1 FMax %155 %156 +%155 = OpCompositeConstruct %4 %83 %83 %83 +%156 = OpExtInst %4 %1 FMax %154 %155 OpLine %3 21 5 -OpStore %73 %157 +OpStore %72 %156 OpLine %3 22 9 -%158 = OpLoad %4 %73 -%159 = OpLoad %4 %73 -%160 = OpFMul %4 %158 %159 +%157 = OpLoad %4 %72 +%158 = OpLoad %4 %72 +%159 = OpFMul %4 %157 %158 OpLine %3 22 5 -OpStore %73 %160 +OpStore %72 %159 OpLine %3 23 9 -%161 = OpLoad %4 %73 -%162 = OpLoad %4 %73 -%163 = OpFMul %4 %161 %162 +%160 = OpLoad %4 %72 +%161 = OpLoad %4 %72 +%162 = OpFMul %4 %160 %161 OpLine %3 23 5 -OpStore %73 %163 +OpStore %72 %162 OpLine %3 24 13 -%164 = OpVectorShuffle %4 %91 %91 3 3 3 -%165 = OpFMul %4 %141 %164 -%166 = OpExtInst %4 %1 Fract %165 -%167 = OpVectorTimesScalar %4 %166 %86 +%163 = OpVectorShuffle %4 %90 %90 3 3 3 +%164 = OpFMul %4 %140 %163 +%165 = OpExtInst %4 %1 Fract %164 +%166 = OpVectorTimesScalar %4 %165 %85 OpLine %3 24 13 -%168 = OpCompositeConstruct %4 %56 %56 %56 -%169 = OpFSub %4 %167 %168 +%167 = OpCompositeConstruct %4 %56 %56 %56 +%168 = OpFSub %4 %166 %167 OpLine %3 25 13 -%170 = OpExtInst %4 %1 FAbs %169 +%169 = OpExtInst %4 %1 FAbs %168 OpLine %3 25 13 -%171 = OpCompositeConstruct %4 %85 %85 %85 -%172 = OpFSub %4 %170 %171 +%170 = OpCompositeConstruct %4 %84 %84 %84 +%171 = OpFSub %4 %169 %170 OpLine %3 26 14 -%173 = OpCompositeConstruct %4 %85 %85 %85 -%174 = OpFAdd %4 %169 %173 -%175 = OpExtInst %4 %1 Floor %174 +%172 = OpCompositeConstruct %4 %84 %84 %84 +%173 = OpFAdd %4 %168 %172 +%174 = OpExtInst %4 %1 Floor %173 OpLine %3 27 14 -%176 = OpFSub %4 %169 %175 +%175 = OpFSub %4 %168 %174 OpLine %3 1 1 -%177 = OpLoad %4 %73 +%176 = OpLoad %4 %72 OpLine %3 28 9 -%178 = OpFMul %4 %176 %176 -%179 = OpFMul %4 %172 %172 -%180 = OpFAdd %4 %178 %179 -%181 = OpVectorTimesScalar %4 %180 %88 -%182 = OpCompositeConstruct %4 %87 %87 %87 -%183 = OpFSub %4 %182 %181 -%184 = OpFMul %4 %177 %183 +%177 = OpFMul %4 %175 %175 +%178 = OpFMul %4 %171 %171 +%179 = OpFAdd %4 %177 %178 +%180 = OpVectorTimesScalar %4 %179 %87 +%181 = OpCompositeConstruct %4 %86 %86 %86 +%182 = OpFSub %4 %181 %180 +%183 = OpFMul %4 %176 %182 OpLine %3 28 5 -OpStore %73 %184 +OpStore %72 %183 OpLine %3 29 13 -%185 = OpCompositeExtract %5 %176 0 -%186 = OpCompositeExtract %5 %103 0 -%187 = OpFMul %5 %185 %186 -%188 = OpCompositeExtract %5 %172 0 -%189 = OpCompositeExtract %5 %103 1 -%190 = OpFMul %5 %188 %189 -%191 = OpFAdd %5 %187 %190 -%192 = OpVectorShuffle %6 %176 %176 1 2 -%193 = OpLoad %7 %70 -%194 = OpVectorShuffle %6 %193 %193 0 2 -%195 = OpFMul %6 %192 %194 -%196 = OpVectorShuffle %6 %172 %172 1 2 -%197 = OpLoad %7 %70 -%198 = OpVectorShuffle %6 %197 %197 1 3 -%199 = OpFMul %6 %196 %198 -%200 = OpFAdd %6 %195 %199 -%201 = OpCompositeConstruct %4 %191 %200 +%184 = OpCompositeExtract %5 %175 0 +%185 = OpCompositeExtract %5 %102 0 +%186 = OpFMul %5 %184 %185 +%187 = OpCompositeExtract %5 %171 0 +%188 = OpCompositeExtract %5 %102 1 +%189 = OpFMul %5 %187 %188 +%190 = OpFAdd %5 %186 %189 +%191 = OpVectorShuffle %6 %175 %175 1 2 +%192 = OpLoad %7 %69 +%193 = OpVectorShuffle %6 %192 %192 0 2 +%194 = OpFMul %6 %191 %193 +%195 = OpVectorShuffle %6 %171 %171 1 2 +%196 = OpLoad %7 %69 +%197 = OpVectorShuffle %6 %196 %196 1 3 +%198 = OpFMul %6 %195 %197 +%199 = OpFAdd %6 %194 %198 +%200 = OpCompositeConstruct %4 %190 %199 OpLine %3 30 12 -%202 = OpLoad %4 %73 -%203 = OpDot %5 %202 %201 -%204 = OpFMul %5 %89 %203 -OpReturnValue %204 +%201 = OpLoad %4 %72 +%202 = OpDot %5 %201 %200 +%203 = OpFMul %5 %88 %202 +OpReturnValue %203 OpFunctionEnd -%217 = OpFunction %5 None %79 -%216 = OpFunctionParameter %6 -%215 = OpLabel -%207 = OpVariable %208 Function %209 -%212 = OpVariable %213 Function %214 -%205 = OpVariable %66 Function %206 -%210 = OpVariable %208 Function %211 -OpBranch %221 -%221 = OpLabel +%214 = OpFunction %5 None %78 +%213 = OpFunctionParameter %6 +%212 = OpLabel +%205 = OpVariable %206 Function %207 +%209 = OpVariable %210 Function %211 +%204 = OpVariable %66 Function %67 +%208 = OpVariable %206 Function %207 +OpBranch %218 +%218 = OpLabel OpLine %3 36 13 -%222 = OpVectorTimesScalar %6 %216 %219 +%219 = OpVectorTimesScalar %6 %213 %216 OpLine %3 36 5 -OpStore %205 %222 +OpStore %204 %219 OpLine %3 37 5 -OpStore %207 %84 +OpStore %205 %83 OpLine %3 38 5 -OpStore %210 %85 +OpStore %208 %84 OpLine %3 39 17 -%223 = OpCompositeConstruct %6 %220 %220 +%220 = OpCompositeConstruct %6 %217 %217 OpLine %3 40 24 -%224 = OpExtInst %5 %1 Cos %85 +%221 = OpExtInst %5 %1 Cos %84 OpLine %3 40 14 -%225 = OpExtInst %5 %1 Sin %85 -%226 = OpCompositeConstruct %6 %224 %225 +%222 = OpExtInst %5 %1 Sin %84 +%223 = OpCompositeConstruct %6 %221 %222 OpLine %3 41 15 -%227 = OpCompositeExtract %5 %226 0 -%228 = OpCompositeExtract %5 %226 1 -%229 = OpCompositeExtract %5 %226 1 -%230 = OpFNegate %5 %229 -%231 = OpCompositeExtract %5 %226 0 -%232 = OpCompositeConstruct %6 %227 %228 -%233 = OpCompositeConstruct %6 %230 %231 -%234 = OpCompositeConstruct %9 %232 %233 +%224 = OpCompositeExtract %5 %223 0 +%225 = OpCompositeExtract %5 %223 1 +%226 = OpCompositeExtract %5 %223 1 +%227 = OpFNegate %5 %226 +%228 = OpCompositeExtract %5 %223 0 +%229 = OpCompositeConstruct %6 %224 %225 +%230 = OpCompositeConstruct %6 %227 %228 +%231 = OpCompositeConstruct %9 %229 %230 OpLine %3 43 10 -OpStore %212 %132 +OpStore %209 %131 +OpBranch %232 +%232 = OpLabel +OpLine %3 43 5 +OpLoopMerge %233 %235 None +OpBranch %234 +%234 = OpLabel +OpLine %3 43 22 +%236 = OpLoad %8 %209 +%237 = OpULessThan %107 %236 %215 +OpLine %3 43 21 +OpSelectionMerge %238 None +OpBranchConditional %237 %238 %239 +%239 = OpLabel +OpBranch %233 +%238 = OpLabel +OpBranch %240 +%240 = OpLabel +OpLine %3 1 1 +%242 = OpLoad %5 %205 +%243 = OpLoad %5 %208 +%244 = OpLoad %6 %204 +OpLine %3 44 21 +%245 = OpFunctionCall %5 %77 %244 +OpLine %3 44 13 +%246 = OpFMul %5 %243 %245 +%247 = OpFAdd %5 %242 %246 +OpLine %3 44 9 +OpStore %205 %247 +OpLine %3 45 13 +%248 = OpLoad %6 %204 +%249 = OpMatrixTimesVector %6 %231 %248 +OpLine %3 45 13 +%250 = OpVectorTimesScalar %6 %249 %85 +%251 = OpFAdd %6 %250 %220 +OpLine %3 45 9 +OpStore %204 %251 +OpLine %3 1 1 +%252 = OpLoad %5 %208 +OpLine %3 46 13 +%253 = OpFMul %5 %252 %84 +OpLine %3 46 9 +OpStore %208 %253 +OpBranch %241 +%241 = OpLabel OpBranch %235 %235 = OpLabel -OpLine %3 43 5 -OpLoopMerge %236 %238 None -OpBranch %237 -%237 = OpLabel -OpLine %3 43 22 -%239 = OpLoad %8 %212 -%240 = OpULessThan %108 %239 %218 -OpLine %3 43 21 -OpSelectionMerge %241 None -OpBranchConditional %240 %241 %242 -%242 = OpLabel -OpBranch %236 -%241 = OpLabel -OpBranch %243 -%243 = OpLabel OpLine %3 1 1 -%245 = OpLoad %5 %207 -%246 = OpLoad %5 %210 -%247 = OpLoad %6 %205 -OpLine %3 44 21 -%248 = OpFunctionCall %5 %78 %247 -OpLine %3 44 13 -%249 = OpFMul %5 %246 %248 -%250 = OpFAdd %5 %245 %249 -OpLine %3 44 9 -OpStore %207 %250 -OpLine %3 45 13 -%251 = OpLoad %6 %205 -%252 = OpMatrixTimesVector %6 %234 %251 -OpLine %3 45 13 -%253 = OpVectorTimesScalar %6 %252 %86 -%254 = OpFAdd %6 %253 %223 -OpLine %3 45 9 -OpStore %205 %254 -OpLine %3 1 1 -%255 = OpLoad %5 %210 -OpLine %3 46 13 -%256 = OpFMul %5 %255 %85 -OpLine %3 46 9 -OpStore %210 %256 -OpBranch %244 -%244 = OpLabel -OpBranch %238 -%238 = OpLabel -OpLine %3 1 1 -%257 = OpLoad %8 %212 +%254 = OpLoad %8 %209 OpLine %3 43 43 -%258 = OpIAdd %8 %257 %123 +%255 = OpIAdd %8 %254 %122 OpLine %3 43 39 -OpStore %212 %258 -OpBranch %235 -%236 = OpLabel +OpStore %209 %255 +OpBranch %232 +%233 = OpLabel OpLine %3 1 1 -%259 = OpLoad %5 %207 -OpReturnValue %259 +%256 = OpLoad %5 %205 +OpReturnValue %256 OpFunctionEnd -%263 = OpFunction %4 None %264 -%261 = OpFunctionParameter %6 -%262 = OpFunctionParameter %6 -%260 = OpLabel -OpBranch %265 -%265 = OpLabel +%260 = OpFunction %4 None %261 +%258 = OpFunctionParameter %6 +%259 = OpFunctionParameter %6 +%257 = OpLabel +OpBranch %262 +%262 = OpLabel OpLine %3 77 9 -%266 = OpCompositeExtract %5 %261 0 -%267 = OpCompositeExtract %5 %262 0 -%268 = OpCompositeExtract %5 %262 1 +%263 = OpCompositeExtract %5 %258 0 +%264 = OpCompositeExtract %5 %259 0 +%265 = OpCompositeExtract %5 %259 1 OpLine %3 78 49 -%269 = OpFunctionCall %5 %217 %261 +%266 = OpFunctionCall %5 %214 %258 OpLine %3 76 12 -%270 = OpExtInst %5 %1 FMix %267 %268 %269 -%271 = OpCompositeExtract %5 %261 1 -%272 = OpCompositeConstruct %4 %266 %270 %271 -OpReturnValue %272 +%267 = OpExtInst %5 %1 FMix %264 %265 %266 +%268 = OpCompositeExtract %5 %258 1 +%269 = OpCompositeConstruct %4 %263 %267 %268 +OpReturnValue %269 OpFunctionEnd -%276 = OpFunction %14 None %277 -%274 = OpFunctionParameter %6 -%275 = OpFunctionParameter %6 -%273 = OpLabel -OpBranch %280 -%280 = OpLabel +%273 = OpFunction %14 None %274 +%271 = OpFunctionParameter %6 +%272 = OpFunctionParameter %6 +%270 = OpLabel +OpBranch %277 +%277 = OpLabel OpLine %3 84 13 -%281 = OpFunctionCall %4 %263 %274 %275 +%278 = OpFunctionCall %4 %260 %271 %272 OpLine %3 86 29 -%282 = OpCompositeConstruct %6 %278 %84 -%283 = OpFAdd %6 %274 %282 +%279 = OpCompositeConstruct %6 %275 %83 +%280 = OpFAdd %6 %271 %279 OpLine %3 86 15 -%284 = OpFunctionCall %4 %263 %283 %275 +%281 = OpFunctionCall %4 %260 %280 %272 OpLine %3 86 15 -%285 = OpFSub %4 %284 %281 +%282 = OpFSub %4 %281 %278 OpLine %3 87 29 -%286 = OpCompositeConstruct %6 %84 %278 -%287 = OpFAdd %6 %274 %286 +%283 = OpCompositeConstruct %6 %83 %275 +%284 = OpFAdd %6 %271 %283 OpLine %3 87 15 -%288 = OpFunctionCall %4 %263 %287 %275 +%285 = OpFunctionCall %4 %260 %284 %272 OpLine %3 87 15 -%289 = OpFSub %4 %288 %281 +%286 = OpFSub %4 %285 %278 OpLine %3 88 29 -%290 = OpCompositeConstruct %6 %279 %84 -%291 = OpFAdd %6 %274 %290 +%287 = OpCompositeConstruct %6 %276 %83 +%288 = OpFAdd %6 %271 %287 OpLine %3 88 15 -%292 = OpFunctionCall %4 %263 %291 %275 +%289 = OpFunctionCall %4 %260 %288 %272 OpLine %3 88 15 -%293 = OpFSub %4 %292 %281 +%290 = OpFSub %4 %289 %278 OpLine %3 89 29 -%294 = OpCompositeConstruct %6 %84 %279 -%295 = OpFAdd %6 %274 %294 +%291 = OpCompositeConstruct %6 %83 %276 +%292 = OpFAdd %6 %271 %291 OpLine %3 89 15 -%296 = OpFunctionCall %4 %263 %295 %275 +%293 = OpFunctionCall %4 %260 %292 %272 OpLine %3 89 15 -%297 = OpFSub %4 %296 %281 +%294 = OpFSub %4 %293 %278 OpLine %3 91 14 -%298 = OpExtInst %4 %1 Cross %289 %285 -%299 = OpExtInst %4 %1 Normalize %298 +%295 = OpExtInst %4 %1 Cross %286 %282 +%296 = OpExtInst %4 %1 Normalize %295 OpLine %3 92 14 -%300 = OpExtInst %4 %1 Cross %297 %293 -%301 = OpExtInst %4 %1 Normalize %300 +%297 = OpExtInst %4 %1 Cross %294 %290 +%298 = OpExtInst %4 %1 Normalize %297 OpLine %3 94 14 -%302 = OpFAdd %4 %299 %301 +%299 = OpFAdd %4 %296 %298 OpLine %3 94 13 -%303 = OpVectorTimesScalar %4 %302 %85 +%300 = OpVectorTimesScalar %4 %299 %84 OpLine %3 96 12 -%304 = OpCompositeConstruct %14 %281 %303 -OpReturnValue %304 +%301 = OpCompositeConstruct %14 %278 %300 +OpReturnValue %301 OpFunctionEnd -%309 = OpFunction %6 None %310 -%306 = OpFunctionParameter %8 -%307 = OpFunctionParameter %10 -%308 = OpFunctionParameter %11 -%305 = OpLabel -OpBranch %311 -%311 = OpLabel +%306 = OpFunction %6 None %307 +%303 = OpFunctionParameter %8 +%304 = OpFunctionParameter %10 +%305 = OpFunctionParameter %11 +%302 = OpLabel +OpBranch %308 +%308 = OpLabel OpLine %3 101 9 -%312 = OpConvertUToF %5 %306 -%313 = OpCompositeExtract %8 %307 0 +%309 = OpConvertUToF %5 %303 +%310 = OpCompositeExtract %8 %304 0 OpLine %3 101 9 -%314 = OpIAdd %8 %313 %123 -%315 = OpConvertUToF %5 %314 -%316 = OpFRem %5 %312 %315 -%317 = OpCompositeExtract %8 %307 0 +%311 = OpIAdd %8 %310 %122 +%312 = OpConvertUToF %5 %311 +%313 = OpFRem %5 %309 %312 +%314 = OpCompositeExtract %8 %304 0 OpLine %3 100 12 -%318 = OpIAdd %8 %317 %123 -%319 = OpUDiv %8 %306 %318 -%320 = OpConvertUToF %5 %319 -%321 = OpCompositeConstruct %6 %316 %320 -%322 = OpConvertSToF %6 %308 -%323 = OpFAdd %6 %321 %322 -OpReturnValue %323 +%315 = OpIAdd %8 %314 %122 +%316 = OpUDiv %8 %303 %315 +%317 = OpConvertUToF %5 %316 +%318 = OpCompositeConstruct %6 %313 %317 +%319 = OpConvertSToF %6 %305 +%320 = OpFAdd %6 %318 %319 +OpReturnValue %320 OpFunctionEnd -%326 = OpFunction %4 None %327 -%325 = OpFunctionParameter %6 -%324 = OpLabel -OpBranch %332 -%332 = OpLabel +%323 = OpFunction %4 None %324 +%322 = OpFunctionParameter %6 +%321 = OpLabel +OpBranch %329 +%329 = OpLabel OpLine %3 270 9 -%333 = OpFunctionCall %5 %78 %325 +%330 = OpFunctionCall %5 %77 %322 OpLine %3 270 9 -%334 = OpFMul %5 %333 %85 +%331 = OpFMul %5 %330 %84 OpLine %3 270 9 -%335 = OpFAdd %5 %334 %85 +%332 = OpFAdd %5 %331 %84 OpLine %3 271 17 -%336 = OpCompositeConstruct %6 %328 %329 -%337 = OpFAdd %6 %325 %336 +%333 = OpCompositeConstruct %6 %325 %326 +%334 = OpFAdd %6 %322 %333 OpLine %3 271 9 -%338 = OpFunctionCall %5 %78 %337 +%335 = OpFunctionCall %5 %77 %334 OpLine %3 271 9 -%339 = OpFMul %5 %338 %85 +%336 = OpFMul %5 %335 %84 OpLine %3 271 9 -%340 = OpFAdd %5 %339 %85 +%337 = OpFAdd %5 %336 %84 OpLine %3 272 17 -%341 = OpCompositeConstruct %6 %330 %331 -%342 = OpFAdd %6 %325 %341 +%338 = OpCompositeConstruct %6 %327 %328 +%339 = OpFAdd %6 %322 %338 OpLine %3 272 9 -%343 = OpFunctionCall %5 %78 %342 +%340 = OpFunctionCall %5 %77 %339 OpLine %3 272 9 -%344 = OpFMul %5 %343 %85 +%341 = OpFMul %5 %340 %84 OpLine %3 269 12 -%345 = OpFAdd %5 %344 %85 -%346 = OpCompositeConstruct %4 %335 %340 %345 -OpReturnValue %346 +%342 = OpFAdd %5 %341 %84 +%343 = OpCompositeConstruct %4 %332 %337 %342 +OpReturnValue %343 OpFunctionEnd -%351 = OpFunction %2 None %352 -%347 = OpLabel -%350 = OpLoad %19 %348 -%354 = OpAccessChain %353 %29 %132 -OpBranch %359 -%359 = OpLabel +%348 = OpFunction %2 None %349 +%344 = OpLabel +%347 = OpLoad %19 %345 +%351 = OpAccessChain %350 %29 %131 +OpBranch %356 +%356 = OpLabel OpLine %3 111 22 -%360 = OpCompositeExtract %8 %350 0 +%357 = OpCompositeExtract %8 %347 0 OpLine %3 113 36 -%362 = OpAccessChain %361 %354 %132 -%363 = OpLoad %10 %362 +%359 = OpAccessChain %358 %351 %131 +%360 = OpLoad %10 %359 OpLine %3 113 59 -%365 = OpAccessChain %364 %354 %123 -%366 = OpLoad %11 %365 +%362 = OpAccessChain %361 %351 %122 +%363 = OpLoad %11 %362 OpLine %3 113 13 -%367 = OpFunctionCall %6 %309 %360 %363 %366 +%364 = OpFunctionCall %6 %306 %357 %360 %363 OpLine %3 115 5 OpLine %3 115 51 -%371 = OpAccessChain %370 %354 %356 -%372 = OpLoad %6 %371 +%368 = OpAccessChain %367 %351 %353 +%369 = OpLoad %6 %368 OpLine %3 115 33 -%373 = OpFunctionCall %14 %276 %367 %372 +%370 = OpFunctionCall %14 %273 %364 %369 OpLine %3 115 5 -%374 = OpAccessChain %369 %32 %132 %360 -OpStore %374 %373 +%371 = OpAccessChain %366 %32 %131 %357 +OpStore %371 %370 OpLine %3 118 23 -%375 = OpCompositeExtract %8 %350 0 +%372 = OpCompositeExtract %8 %347 0 OpLine %3 118 23 -%376 = OpIMul %8 %375 %355 +%373 = OpIMul %8 %372 %352 OpLine %3 120 25 -%378 = OpAccessChain %377 %354 %132 %132 -%379 = OpLoad %8 %378 +%375 = OpAccessChain %374 %351 %131 %131 +%376 = OpLoad %8 %375 OpLine %3 120 25 -%380 = OpAccessChain %377 %354 %132 %123 -%381 = OpLoad %8 %380 -%382 = OpIMul %8 %379 %381 +%377 = OpAccessChain %374 %351 %131 %122 +%378 = OpLoad %8 %377 +%379 = OpIMul %8 %376 %378 OpLine %3 120 9 -%383 = OpIMul %8 %382 %355 -%384 = OpUGreaterThanEqual %108 %376 %383 +%380 = OpIMul %8 %379 %352 +%381 = OpUGreaterThanEqual %107 %373 %380 OpLine %3 120 5 -OpSelectionMerge %385 None -OpBranchConditional %384 %386 %385 -%386 = OpLabel +OpSelectionMerge %382 None +OpBranchConditional %381 %383 %382 +%383 = OpLabel OpReturn -%385 = OpLabel +%382 = OpLabel OpLine %3 122 28 -%387 = OpCompositeExtract %8 %350 0 +%384 = OpCompositeExtract %8 %347 0 OpLine %3 122 15 -%388 = OpAccessChain %377 %354 %132 %132 -%389 = OpLoad %8 %388 -%390 = OpUDiv %8 %387 %389 -%391 = OpIAdd %8 %360 %390 +%385 = OpAccessChain %374 %351 %131 %131 +%386 = OpLoad %8 %385 +%387 = OpUDiv %8 %384 %386 +%388 = OpIAdd %8 %357 %387 OpLine %3 123 15 -%392 = OpIAdd %8 %391 %123 +%389 = OpIAdd %8 %388 %122 OpLine %3 124 15 -%393 = OpAccessChain %377 %354 %132 %132 -%394 = OpLoad %8 %393 -%395 = OpIAdd %8 %391 %394 +%390 = OpAccessChain %374 %351 %131 %131 +%391 = OpLoad %8 %390 +%392 = OpIAdd %8 %388 %391 OpLine %3 124 15 -%396 = OpIAdd %8 %395 %123 +%393 = OpIAdd %8 %392 %122 OpLine %3 125 15 -%397 = OpIAdd %8 %396 %123 +%394 = OpIAdd %8 %393 %122 OpLine %3 127 5 OpLine %3 127 5 -%400 = OpAccessChain %399 %34 %132 %376 -OpStore %400 %391 +%397 = OpAccessChain %396 %34 %131 %373 +OpStore %397 %388 OpLine %3 128 5 OpLine %3 128 5 -%401 = OpIAdd %8 %376 %123 +%398 = OpIAdd %8 %373 %122 OpLine %3 128 5 -%402 = OpAccessChain %399 %34 %132 %401 -OpStore %402 %396 +%399 = OpAccessChain %396 %34 %131 %398 +OpStore %399 %393 OpLine %3 129 5 OpLine %3 129 5 -%403 = OpIAdd %8 %376 %356 +%400 = OpIAdd %8 %373 %353 OpLine %3 129 5 -%404 = OpAccessChain %399 %34 %132 %403 -OpStore %404 %397 +%401 = OpAccessChain %396 %34 %131 %400 +OpStore %401 %394 OpLine %3 130 5 OpLine %3 130 5 -%405 = OpIAdd %8 %376 %357 +%402 = OpIAdd %8 %373 %354 OpLine %3 130 5 -%406 = OpAccessChain %399 %34 %132 %405 -OpStore %406 %391 +%403 = OpAccessChain %396 %34 %131 %402 +OpStore %403 %388 OpLine %3 131 5 OpLine %3 131 5 -%407 = OpIAdd %8 %376 %358 +%404 = OpIAdd %8 %373 %355 OpLine %3 131 5 -%408 = OpAccessChain %399 %34 %132 %407 -OpStore %408 %397 +%405 = OpAccessChain %396 %34 %131 %404 +OpStore %405 %394 OpLine %3 132 5 OpLine %3 132 5 -%409 = OpIAdd %8 %376 %218 +%406 = OpIAdd %8 %373 %215 OpLine %3 132 5 -%410 = OpAccessChain %399 %34 %132 %409 -OpStore %410 %392 +%407 = OpAccessChain %396 %34 %131 %406 +OpStore %407 %389 OpReturn OpFunctionEnd -%421 = OpFunction %2 None %352 -%411 = OpLabel -%414 = OpLoad %8 %412 -%423 = OpAccessChain %422 %36 %132 -OpBranch %425 -%425 = OpLabel +%418 = OpFunction %2 None %349 +%408 = OpLabel +%411 = OpLoad %8 %409 +%420 = OpAccessChain %419 %36 %131 +OpBranch %422 +%422 = OpLabel OpLine %3 161 19 -%426 = OpIAdd %8 %414 %356 +%423 = OpIAdd %8 %411 %353 OpLine %3 161 18 -%427 = OpUDiv %8 %426 %357 +%424 = OpUDiv %8 %423 %354 OpLine %3 161 13 -%428 = OpUMod %8 %427 %356 -%429 = OpConvertUToF %5 %428 +%425 = OpUMod %8 %424 %353 +%426 = OpConvertUToF %5 %425 OpLine %3 162 19 -%430 = OpIAdd %8 %414 %123 +%427 = OpIAdd %8 %411 %122 OpLine %3 162 18 -%431 = OpUDiv %8 %430 %357 +%428 = OpUDiv %8 %427 %354 OpLine %3 162 13 -%432 = OpUMod %8 %431 %356 -%433 = OpConvertUToF %5 %432 +%429 = OpUMod %8 %428 %353 +%430 = OpConvertUToF %5 %429 OpLine %3 163 14 -%434 = OpCompositeConstruct %6 %429 %433 +%431 = OpCompositeConstruct %6 %426 %430 OpLine %3 165 30 -%435 = OpVectorTimesScalar %6 %434 %86 -%436 = OpCompositeConstruct %6 %424 %424 -%437 = OpFAdd %6 %436 %435 +%432 = OpVectorTimesScalar %6 %431 %85 +%433 = OpCompositeConstruct %6 %421 %421 +%434 = OpFAdd %6 %433 %432 OpLine %3 165 20 -%438 = OpCompositeConstruct %7 %437 %84 %56 +%435 = OpCompositeConstruct %7 %434 %83 %56 OpLine %3 168 21 -%439 = OpCompositeExtract %5 %434 0 +%436 = OpCompositeExtract %5 %431 0 OpLine %3 168 21 -%441 = OpAccessChain %440 %423 %357 -%442 = OpLoad %8 %441 -%443 = OpConvertUToF %5 %442 -%444 = OpFMul %5 %439 %443 -%445 = OpCompositeExtract %5 %434 1 +%438 = OpAccessChain %437 %420 %354 +%439 = OpLoad %8 %438 +%440 = OpConvertUToF %5 %439 +%441 = OpFMul %5 %436 %440 +%442 = OpCompositeExtract %5 %431 1 OpLine %3 168 17 -%446 = OpAccessChain %440 %423 %357 -%447 = OpLoad %8 %446 -%448 = OpConvertUToF %5 %447 -%449 = OpFMul %5 %445 %448 -%450 = OpFAdd %5 %444 %449 -%451 = OpConvertFToU %8 %450 +%443 = OpAccessChain %437 %420 %354 +%444 = OpLoad %8 %443 +%445 = OpConvertUToF %5 %444 +%446 = OpFMul %5 %442 %445 +%447 = OpFAdd %5 %441 %446 +%448 = OpConvertFToU %8 %447 OpLine %3 168 17 -%452 = OpAccessChain %440 %423 %358 -%453 = OpLoad %8 %452 -%454 = OpIAdd %8 %451 %453 +%449 = OpAccessChain %437 %420 %355 +%450 = OpLoad %8 %449 +%451 = OpIAdd %8 %448 %450 OpLine %3 170 12 -%455 = OpCompositeConstruct %21 %454 %438 %434 -%456 = OpCompositeExtract %8 %455 0 -OpStore %415 %456 -%457 = OpCompositeExtract %7 %455 1 -OpStore %417 %457 -%458 = OpCompositeExtract %6 %455 2 -OpStore %419 %458 +%452 = OpCompositeConstruct %21 %451 %435 %431 +%453 = OpCompositeExtract %8 %452 0 +OpStore %412 %453 +%454 = OpCompositeExtract %7 %452 1 +OpStore %414 %454 +%455 = OpCompositeExtract %6 %452 2 +OpStore %416 %455 OpReturn OpFunctionEnd -%475 = OpFunction %2 None %352 -%463 = OpLabel -%459 = OpVariable %208 Function %460 -%461 = OpVariable %213 Function %462 -%466 = OpLoad %8 %465 -%469 = OpLoad %7 %467 -%472 = OpLoad %6 %470 -%464 = OpCompositeConstruct %21 %466 %469 %472 -%476 = OpAccessChain %422 %36 %132 -OpBranch %478 -%478 = OpLabel +%470 = OpFunction %2 None %349 +%458 = OpLabel +%456 = OpVariable %206 Function %207 +%457 = OpVariable %210 Function %211 +%461 = OpLoad %8 %460 +%464 = OpLoad %7 %462 +%467 = OpLoad %6 %465 +%459 = OpCompositeConstruct %21 %461 %464 %467 +%471 = OpAccessChain %419 %36 %131 +OpBranch %473 +%473 = OpLabel OpLine %3 181 17 -%479 = OpCompositeExtract %6 %464 2 -%480 = OpCompositeExtract %5 %479 0 +%474 = OpCompositeExtract %6 %459 2 +%475 = OpCompositeExtract %5 %474 0 OpLine %3 181 17 -%481 = OpAccessChain %440 %476 %357 -%482 = OpLoad %8 %481 -%483 = OpConvertUToF %5 %482 -%484 = OpFMul %5 %480 %483 -%485 = OpCompositeExtract %6 %464 2 -%486 = OpCompositeExtract %5 %485 1 +%476 = OpAccessChain %437 %471 %354 +%477 = OpLoad %8 %476 +%478 = OpConvertUToF %5 %477 +%479 = OpFMul %5 %475 %478 +%480 = OpCompositeExtract %6 %459 2 +%481 = OpCompositeExtract %5 %480 1 OpLine %3 181 70 -%487 = OpAccessChain %440 %476 %357 -%488 = OpLoad %8 %487 +%482 = OpAccessChain %437 %471 %354 +%483 = OpLoad %8 %482 OpLine %3 181 13 -%489 = OpAccessChain %440 %476 %357 -%490 = OpLoad %8 %489 -%491 = OpIMul %8 %488 %490 -%492 = OpConvertUToF %5 %491 -%493 = OpFMul %5 %486 %492 -%494 = OpFAdd %5 %484 %493 -%495 = OpConvertFToU %8 %494 +%484 = OpAccessChain %437 %471 %354 +%485 = OpLoad %8 %484 +%486 = OpIMul %8 %483 %485 +%487 = OpConvertUToF %5 %486 +%488 = OpFMul %5 %481 %487 +%489 = OpFAdd %5 %479 %488 +%490 = OpConvertFToU %8 %489 OpLine %3 181 13 -%496 = OpAccessChain %440 %476 %358 -%497 = OpLoad %8 %496 -%498 = OpIAdd %8 %495 %497 +%491 = OpAccessChain %437 %471 %355 +%492 = OpLoad %8 %491 +%493 = OpIAdd %8 %490 %492 OpLine %3 182 32 -%499 = OpConvertUToF %5 %498 +%494 = OpConvertUToF %5 %493 OpLine %3 182 22 -%500 = OpFDiv %5 %499 %477 -%501 = OpExtInst %5 %1 Floor %500 -%502 = OpConvertFToU %8 %501 +%495 = OpFDiv %5 %494 %472 +%496 = OpExtInst %5 %1 Floor %495 +%497 = OpConvertFToU %8 %496 OpLine %3 183 22 -%503 = OpUMod %8 %498 %355 +%498 = OpUMod %8 %493 %352 OpLine %3 185 36 -%504 = OpAccessChain %361 %476 %132 -%505 = OpLoad %10 %504 +%499 = OpAccessChain %358 %471 %131 +%500 = OpLoad %10 %499 OpLine %3 185 57 -%506 = OpAccessChain %364 %476 %123 -%507 = OpLoad %11 %506 +%501 = OpAccessChain %361 %471 %122 +%502 = OpLoad %11 %501 OpLine %3 185 13 -%508 = OpFunctionCall %6 %309 %502 %505 %507 +%503 = OpFunctionCall %6 %306 %497 %500 %502 OpLine %3 186 31 -%509 = OpAccessChain %370 %476 %356 -%510 = OpLoad %6 %509 +%504 = OpAccessChain %367 %471 %353 +%505 = OpLoad %6 %504 OpLine %3 186 13 -%511 = OpFunctionCall %14 %276 %508 %510 +%506 = OpFunctionCall %14 %273 %503 %505 OpLine %3 188 5 -OpStore %459 %84 +OpStore %456 %83 OpLine %3 190 5 -OpSelectionMerge %512 None -OpSwitch %503 %519 0 %513 1 %514 2 %515 3 %516 4 %517 5 %518 -%513 = OpLabel +OpSelectionMerge %507 None +OpSwitch %498 %514 0 %508 1 %509 2 %510 3 %511 4 %512 5 %513 +%508 = OpLabel OpLine %3 191 37 -%520 = OpCompositeExtract %4 %511 0 -%521 = OpCompositeExtract %5 %520 0 +%515 = OpCompositeExtract %4 %506 0 +%516 = OpCompositeExtract %5 %515 0 OpLine %3 191 20 -OpStore %459 %521 -OpBranch %512 -%514 = OpLabel +OpStore %456 %516 +OpBranch %507 +%509 = OpLabel OpLine %3 192 37 -%522 = OpCompositeExtract %4 %511 0 -%523 = OpCompositeExtract %5 %522 1 +%517 = OpCompositeExtract %4 %506 0 +%518 = OpCompositeExtract %5 %517 1 OpLine %3 192 20 -OpStore %459 %523 -OpBranch %512 -%515 = OpLabel +OpStore %456 %518 +OpBranch %507 +%510 = OpLabel OpLine %3 193 37 -%524 = OpCompositeExtract %4 %511 0 -%525 = OpCompositeExtract %5 %524 2 +%519 = OpCompositeExtract %4 %506 0 +%520 = OpCompositeExtract %5 %519 2 OpLine %3 193 20 -OpStore %459 %525 -OpBranch %512 -%516 = OpLabel +OpStore %456 %520 +OpBranch %507 +%511 = OpLabel OpLine %3 194 37 -%526 = OpCompositeExtract %4 %511 1 -%527 = OpCompositeExtract %5 %526 0 +%521 = OpCompositeExtract %4 %506 1 +%522 = OpCompositeExtract %5 %521 0 OpLine %3 194 20 -OpStore %459 %527 -OpBranch %512 -%517 = OpLabel -OpLine %3 195 37 -%528 = OpCompositeExtract %4 %511 1 -%529 = OpCompositeExtract %5 %528 1 -OpLine %3 195 20 -OpStore %459 %529 -OpBranch %512 -%518 = OpLabel -OpLine %3 196 37 -%530 = OpCompositeExtract %4 %511 1 -%531 = OpCompositeExtract %5 %530 2 -OpLine %3 196 20 -OpStore %459 %531 -OpBranch %512 -%519 = OpLabel -OpBranch %512 +OpStore %456 %522 +OpBranch %507 %512 = OpLabel +OpLine %3 195 37 +%523 = OpCompositeExtract %4 %506 1 +%524 = OpCompositeExtract %5 %523 1 +OpLine %3 195 20 +OpStore %456 %524 +OpBranch %507 +%513 = OpLabel +OpLine %3 196 37 +%525 = OpCompositeExtract %4 %506 1 +%526 = OpCompositeExtract %5 %525 2 +OpLine %3 196 20 +OpStore %456 %526 +OpBranch %507 +%514 = OpLabel +OpBranch %507 +%507 = OpLabel OpLine %3 200 15 -%532 = OpAccessChain %377 %476 %132 %132 -%533 = OpLoad %8 %532 -%534 = OpUDiv %8 %502 %533 -%535 = OpIAdd %8 %502 %534 +%527 = OpAccessChain %374 %471 %131 %131 +%528 = OpLoad %8 %527 +%529 = OpUDiv %8 %497 %528 +%530 = OpIAdd %8 %497 %529 OpLine %3 201 15 -%536 = OpIAdd %8 %535 %123 +%531 = OpIAdd %8 %530 %122 OpLine %3 202 15 -%537 = OpAccessChain %377 %476 %132 %132 -%538 = OpLoad %8 %537 -%539 = OpIAdd %8 %535 %538 +%532 = OpAccessChain %374 %471 %131 %131 +%533 = OpLoad %8 %532 +%534 = OpIAdd %8 %530 %533 OpLine %3 202 15 -%540 = OpIAdd %8 %539 %123 +%535 = OpIAdd %8 %534 %122 OpLine %3 203 15 -%541 = OpIAdd %8 %540 %123 +%536 = OpIAdd %8 %535 %122 OpLine %3 205 5 -OpStore %461 %132 +OpStore %457 %131 OpLine %3 206 5 -OpSelectionMerge %542 None -OpSwitch %503 %547 0 %543 3 %543 2 %544 4 %544 1 %545 5 %546 -%543 = OpLabel +OpSelectionMerge %537 None +OpSwitch %498 %542 0 %538 3 %538 2 %539 4 %539 1 %540 5 %541 +%538 = OpLabel OpLine %3 207 24 -OpStore %461 %535 -OpBranch %542 -%544 = OpLabel +OpStore %457 %530 +OpBranch %537 +%539 = OpLabel OpLine %3 208 24 -OpStore %461 %541 -OpBranch %542 -%545 = OpLabel +OpStore %457 %536 +OpBranch %537 +%540 = OpLabel OpLine %3 209 20 -OpStore %461 %540 -OpBranch %542 -%546 = OpLabel +OpStore %457 %535 +OpBranch %537 +%541 = OpLabel OpLine %3 210 20 -OpStore %461 %536 -OpBranch %542 -%547 = OpLabel -OpBranch %542 +OpStore %457 %531 +OpBranch %537 %542 = OpLabel +OpBranch %537 +%537 = OpLabel OpLine %3 213 13 -%548 = OpCompositeExtract %8 %464 0 +%543 = OpCompositeExtract %8 %459 0 OpLine %3 213 5 -OpStore %461 %548 +OpStore %457 %543 OpLine %3 222 27 -%549 = OpLoad %5 %459 -%550 = OpBitcast %8 %549 +%544 = OpLoad %5 %456 +%545 = OpBitcast %8 %544 OpLine %3 223 12 -%551 = OpLoad %8 %461 -%552 = OpCompositeConstruct %22 %550 %551 -%553 = OpCompositeExtract %8 %552 0 -OpStore %473 %553 -%554 = OpCompositeExtract %8 %552 1 -OpStore %474 %554 +%546 = OpLoad %8 %457 +%547 = OpCompositeConstruct %22 %545 %546 +%548 = OpCompositeExtract %8 %547 0 +OpStore %468 %548 +%549 = OpCompositeExtract %8 %547 1 +OpStore %469 %549 OpReturn OpFunctionEnd -%566 = OpFunction %2 None %352 -%555 = OpLabel -%559 = OpLoad %4 %557 -%561 = OpLoad %4 %560 -%556 = OpCompositeConstruct %14 %559 %561 -%568 = OpAccessChain %567 %39 %132 -OpBranch %569 -%569 = OpLabel +%561 = OpFunction %2 None %349 +%550 = OpLabel +%554 = OpLoad %4 %552 +%556 = OpLoad %4 %555 +%551 = OpCompositeConstruct %14 %554 %556 +%563 = OpAccessChain %562 %39 %131 +OpBranch %564 +%564 = OpLabel OpLine %3 254 25 -%571 = OpAccessChain %570 %568 %123 -%572 = OpLoad %23 %571 -%573 = OpCompositeExtract %4 %556 0 +%566 = OpAccessChain %565 %563 %122 +%567 = OpLoad %23 %566 +%568 = OpCompositeExtract %4 %551 0 OpLine %3 254 25 -%574 = OpCompositeConstruct %7 %573 %56 -%575 = OpMatrixTimesVector %7 %572 %574 +%569 = OpCompositeConstruct %7 %568 %56 +%570 = OpMatrixTimesVector %7 %567 %569 OpLine %3 255 18 -%576 = OpCompositeExtract %4 %556 1 +%571 = OpCompositeExtract %4 %551 1 OpLine %3 256 12 -%577 = OpCompositeExtract %4 %556 0 -%578 = OpCompositeConstruct %26 %575 %576 %577 -%579 = OpCompositeExtract %7 %578 0 -OpStore %562 %579 -%580 = OpCompositeExtract %4 %578 1 -OpStore %563 %580 -%581 = OpCompositeExtract %4 %578 2 -OpStore %565 %581 +%572 = OpCompositeExtract %4 %551 0 +%573 = OpCompositeConstruct %26 %570 %571 %572 +%574 = OpCompositeExtract %7 %573 0 +OpStore %557 %574 +%575 = OpCompositeExtract %4 %573 1 +OpStore %558 %575 +%576 = OpCompositeExtract %4 %573 2 +OpStore %560 %576 OpReturn OpFunctionEnd -%593 = OpFunction %2 None %352 -%584 = OpLabel -%582 = OpVariable %74 Function %583 -%587 = OpLoad %7 %586 -%589 = OpLoad %4 %588 -%591 = OpLoad %4 %590 -%585 = OpCompositeConstruct %26 %587 %589 %591 -%594 = OpAccessChain %567 %39 %132 -%596 = OpAccessChain %595 %42 %132 -OpBranch %599 -%599 = OpLabel +%587 = OpFunction %2 None %349 +%578 = OpLabel +%577 = OpVariable %73 Function %74 +%581 = OpLoad %7 %580 +%583 = OpLoad %4 %582 +%585 = OpLoad %4 %584 +%579 = OpCompositeConstruct %26 %581 %583 %585 +%588 = OpAccessChain %562 %39 %131 +%590 = OpAccessChain %589 %42 %131 +OpBranch %593 +%593 = OpLabel OpLine %3 278 28 -%600 = OpCompositeConstruct %4 %84 %84 %84 +%594 = OpCompositeConstruct %4 %83 %83 %83 OpLine %3 278 17 -%601 = OpCompositeConstruct %4 %278 %278 %278 -%602 = OpCompositeExtract %4 %585 2 -%603 = OpExtInst %4 %1 Fract %602 -%604 = OpExtInst %4 %1 SmoothStep %600 %601 %603 +%595 = OpCompositeConstruct %4 %275 %275 %275 +%596 = OpCompositeExtract %4 %579 2 +%597 = OpExtInst %4 %1 Fract %596 +%598 = OpExtInst %4 %1 SmoothStep %594 %595 %597 OpLine %3 278 5 -OpStore %582 %604 +OpStore %577 %598 OpLine %3 279 17 -%605 = OpCompositeConstruct %4 %85 %278 %597 +%599 = OpCompositeConstruct %4 %84 %275 %591 OpLine %3 279 13 -%606 = OpCompositeConstruct %4 %598 %598 %598 -%607 = OpAccessChain %122 %582 %132 -%608 = OpLoad %5 %607 -%609 = OpAccessChain %122 %582 %123 -%610 = OpLoad %5 %609 -%611 = OpFMul %5 %608 %610 -%612 = OpAccessChain %122 %582 %356 -%613 = OpLoad %5 %612 -%614 = OpFMul %5 %611 %613 -%615 = OpCompositeConstruct %4 %614 %614 %614 -%616 = OpExtInst %4 %1 FMix %605 %606 %615 +%600 = OpCompositeConstruct %4 %592 %592 %592 +%601 = OpAccessChain %121 %577 %131 +%602 = OpLoad %5 %601 +%603 = OpAccessChain %121 %577 %122 +%604 = OpLoad %5 %603 +%605 = OpFMul %5 %602 %604 +%606 = OpAccessChain %121 %577 %353 +%607 = OpLoad %5 %606 +%608 = OpFMul %5 %605 %607 +%609 = OpCompositeConstruct %4 %608 %608 %608 +%610 = OpExtInst %4 %1 FMix %599 %600 %609 OpLine %3 279 5 -OpStore %582 %616 +OpStore %577 %610 OpLine %3 282 25 -%618 = OpAccessChain %617 %596 %123 -%619 = OpLoad %4 %618 -%620 = OpVectorTimesScalar %4 %619 %278 +%612 = OpAccessChain %611 %590 %122 +%613 = OpLoad %4 %612 +%614 = OpVectorTimesScalar %4 %613 %275 OpLine %3 284 21 -%621 = OpAccessChain %617 %596 %132 -%622 = OpLoad %4 %621 -%623 = OpCompositeExtract %4 %585 2 -%624 = OpFSub %4 %622 %623 -%625 = OpExtInst %4 %1 Normalize %624 +%615 = OpAccessChain %611 %590 %131 +%616 = OpLoad %4 %615 +%617 = OpCompositeExtract %4 %579 2 +%618 = OpFSub %4 %616 %617 +%619 = OpExtInst %4 %1 Normalize %618 OpLine %3 285 20 -%627 = OpAccessChain %626 %594 %132 -%628 = OpLoad %7 %627 -%629 = OpVectorShuffle %4 %628 %628 0 1 2 -%630 = OpCompositeExtract %4 %585 2 -%631 = OpFSub %4 %629 %630 -%632 = OpExtInst %4 %1 Normalize %631 +%621 = OpAccessChain %620 %588 %131 +%622 = OpLoad %7 %621 +%623 = OpVectorShuffle %4 %622 %622 0 1 2 +%624 = OpCompositeExtract %4 %579 2 +%625 = OpFSub %4 %623 %624 +%626 = OpExtInst %4 %1 Normalize %625 OpLine %3 286 20 -%633 = OpFAdd %4 %632 %625 -%634 = OpExtInst %4 %1 Normalize %633 +%627 = OpFAdd %4 %626 %619 +%628 = OpExtInst %4 %1 Normalize %627 OpLine %3 288 32 -%635 = OpCompositeExtract %4 %585 1 -%636 = OpDot %5 %635 %625 +%629 = OpCompositeExtract %4 %579 1 +%630 = OpDot %5 %629 %619 OpLine %3 288 28 -%637 = OpExtInst %5 %1 FMax %636 %84 +%631 = OpExtInst %5 %1 FMax %630 %83 OpLine %3 289 25 -%638 = OpAccessChain %617 %596 %123 -%639 = OpLoad %4 %638 -%640 = OpVectorTimesScalar %4 %639 %637 +%632 = OpAccessChain %611 %590 %122 +%633 = OpLoad %4 %632 +%634 = OpVectorTimesScalar %4 %633 %631 OpLine %3 291 37 -%641 = OpCompositeExtract %4 %585 1 -%642 = OpDot %5 %641 %634 +%635 = OpCompositeExtract %4 %579 1 +%636 = OpDot %5 %635 %628 OpLine %3 291 33 -%643 = OpExtInst %5 %1 FMax %642 %84 +%637 = OpExtInst %5 %1 FMax %636 %83 OpLine %3 291 29 -%644 = OpExtInst %5 %1 Pow %643 %329 +%638 = OpExtInst %5 %1 Pow %637 %326 OpLine %3 292 26 -%645 = OpAccessChain %617 %596 %123 -%646 = OpLoad %4 %645 -%647 = OpVectorTimesScalar %4 %646 %644 +%639 = OpAccessChain %611 %590 %122 +%640 = OpLoad %4 %639 +%641 = OpVectorTimesScalar %4 %640 %638 OpLine %3 294 18 -%648 = OpFAdd %4 %620 %640 -%649 = OpFAdd %4 %648 %647 -%650 = OpLoad %4 %582 -%651 = OpFMul %4 %649 %650 +%642 = OpFAdd %4 %614 %634 +%643 = OpFAdd %4 %642 %641 +%644 = OpLoad %4 %577 +%645 = OpFMul %4 %643 %644 OpLine %3 296 12 -%652 = OpCompositeConstruct %7 %651 %56 -OpStore %592 %652 +%646 = OpCompositeConstruct %7 %645 %56 +OpStore %586 %646 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/functions.spvasm b/tests/out/spv/functions.spvasm index c3fd23891..f114e2970 100644 --- a/tests/out/spv/functions.spvasm +++ b/tests/out/spv/functions.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 79 +; Bound: 78 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %74 "main" -OpExecutionMode %74 LocalSize 1 1 1 +OpEntryPoint GLCompute %73 "main" +OpExecutionMode %73 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 2 @@ -25,8 +25,7 @@ OpExecutionMode %74 LocalSize 1 1 1 %26 = OpConstant %5 2 %31 = OpConstantNull %5 %42 = OpConstantNull %8 -%57 = OpConstantNull %5 -%75 = OpTypeFunction %2 +%74 = OpTypeFunction %2 %11 = OpFunction %3 None %12 %10 = OpLabel OpBranch %15 @@ -67,29 +66,29 @@ OpBranch %27 %41 = OpIAdd %8 %50 %53 %54 = OpCompositeConstruct %9 %25 %25 %25 %25 %55 = OpCompositeConstruct %9 %26 %26 %26 %26 -%58 = OpCompositeExtract %5 %54 0 -%59 = OpCompositeExtract %5 %55 0 -%60 = OpIMul %5 %58 %59 -%61 = OpIAdd %5 %57 %60 -%62 = OpCompositeExtract %5 %54 1 -%63 = OpCompositeExtract %5 %55 1 -%64 = OpIMul %5 %62 %63 -%65 = OpIAdd %5 %61 %64 -%66 = OpCompositeExtract %5 %54 2 -%67 = OpCompositeExtract %5 %55 2 -%68 = OpIMul %5 %66 %67 -%69 = OpIAdd %5 %65 %68 -%70 = OpCompositeExtract %5 %54 3 -%71 = OpCompositeExtract %5 %55 3 -%72 = OpIMul %5 %70 %71 -%56 = OpIAdd %5 %69 %72 +%57 = OpCompositeExtract %5 %54 0 +%58 = OpCompositeExtract %5 %55 0 +%59 = OpIMul %5 %57 %58 +%60 = OpIAdd %5 %31 %59 +%61 = OpCompositeExtract %5 %54 1 +%62 = OpCompositeExtract %5 %55 1 +%63 = OpIMul %5 %61 %62 +%64 = OpIAdd %5 %60 %63 +%65 = OpCompositeExtract %5 %54 2 +%66 = OpCompositeExtract %5 %55 2 +%67 = OpIMul %5 %65 %66 +%68 = OpIAdd %5 %64 %67 +%69 = OpCompositeExtract %5 %54 3 +%70 = OpCompositeExtract %5 %55 3 +%71 = OpIMul %5 %69 %70 +%56 = OpIAdd %5 %68 %71 OpReturnValue %56 OpFunctionEnd -%74 = OpFunction %2 None %75 -%73 = OpLabel -OpBranch %76 -%76 = OpLabel -%77 = OpFunctionCall %3 %11 -%78 = OpFunctionCall %5 %21 +%73 = OpFunction %2 None %74 +%72 = OpLabel +OpBranch %75 +%75 = OpLabel +%76 = OpFunctionCall %3 %11 +%77 = OpFunctionCall %5 %21 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 6e7e2958c..015195c73 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 179 +; Bound: 178 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %103 "main" %122 -OpExecutionMode %103 LocalSize 1 1 1 +OpEntryPoint GLCompute %102 "main" %121 +OpExecutionMode %102 LocalSize 1 1 1 OpDecorate %5 ArrayStride 4 OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 12 @@ -48,7 +48,7 @@ OpDecorate %50 DescriptorSet 0 OpDecorate %50 Binding 7 OpDecorate %51 Block OpMemberDecorate %51 0 Offset 0 -OpDecorate %122 BuiltIn LocalInvocationId +OpDecorate %121 BuiltIn LocalInvocationId %2 = OpTypeVoid %3 = OpTypeBool %4 = OpTypeFloat 32 @@ -111,45 +111,44 @@ OpDecorate %122 BuiltIn LocalInvocationId %69 = OpConstant %4 2.0 %70 = OpConstant %4 3.0 %71 = OpConstantNull %24 -%72 = OpConstantNull %24 -%74 = OpTypePointer StorageBuffer %8 -%77 = OpTypePointer StorageBuffer %4 -%97 = OpTypePointer Function %4 -%98 = OpConstantNull %4 -%100 = OpTypePointer Function %3 -%101 = OpConstantNull %3 -%105 = OpTypePointer StorageBuffer %11 -%107 = OpTypePointer Uniform %13 -%109 = OpTypePointer Uniform %8 -%111 = OpTypePointer Uniform %15 -%113 = OpTypePointer Uniform %19 -%115 = OpTypePointer Uniform %22 -%117 = OpConstant %4 4.0 -%119 = OpConstantNull %5 -%120 = OpConstantNull %7 -%121 = OpTypeVector %7 3 -%123 = OpTypePointer Input %121 -%122 = OpVariable %123 Input -%125 = OpConstantNull %121 -%126 = OpTypeVector %3 3 -%131 = OpConstant %7 264 -%134 = OpTypePointer Workgroup %4 -%135 = OpTypePointer Uniform %21 -%136 = OpTypePointer Uniform %20 -%139 = OpTypePointer Uniform %17 -%140 = OpTypePointer Uniform %16 -%141 = OpTypePointer Uniform %12 -%146 = OpConstant %7 7 -%152 = OpConstant %7 6 -%154 = OpTypePointer StorageBuffer %10 -%155 = OpConstant %7 1 -%158 = OpConstant %7 5 -%160 = OpTypePointer Uniform %12 -%161 = OpTypePointer Uniform %4 -%162 = OpConstant %7 3 -%165 = OpConstant %7 4 -%167 = OpTypePointer StorageBuffer %4 -%178 = OpConstant %7 256 +%73 = OpTypePointer StorageBuffer %8 +%76 = OpTypePointer StorageBuffer %4 +%96 = OpTypePointer Function %4 +%97 = OpConstantNull %4 +%99 = OpTypePointer Function %3 +%100 = OpConstantNull %3 +%104 = OpTypePointer StorageBuffer %11 +%106 = OpTypePointer Uniform %13 +%108 = OpTypePointer Uniform %8 +%110 = OpTypePointer Uniform %15 +%112 = OpTypePointer Uniform %19 +%114 = OpTypePointer Uniform %22 +%116 = OpConstant %4 4.0 +%118 = OpConstantNull %5 +%119 = OpConstantNull %7 +%120 = OpTypeVector %7 3 +%122 = OpTypePointer Input %120 +%121 = OpVariable %122 Input +%124 = OpConstantNull %120 +%125 = OpTypeVector %3 3 +%130 = OpConstant %7 264 +%133 = OpTypePointer Workgroup %4 +%134 = OpTypePointer Uniform %21 +%135 = OpTypePointer Uniform %20 +%138 = OpTypePointer Uniform %17 +%139 = OpTypePointer Uniform %16 +%140 = OpTypePointer Uniform %12 +%145 = OpConstant %7 7 +%151 = OpConstant %7 6 +%153 = OpTypePointer StorageBuffer %10 +%154 = OpConstant %7 1 +%157 = OpConstant %7 5 +%159 = OpTypePointer Uniform %12 +%160 = OpTypePointer Uniform %4 +%161 = OpConstant %7 3 +%164 = OpConstant %7 4 +%166 = OpTypePointer StorageBuffer %4 +%177 = OpConstant %7 256 %55 = OpFunction %2 None %56 %54 = OpFunctionParameter %8 %53 = OpLabel @@ -161,100 +160,100 @@ OpFunctionEnd %61 = OpLabel %58 = OpVariable %59 Function %60 %66 = OpAccessChain %64 %32 %65 -OpBranch %73 -%73 = OpLabel -%75 = OpCompositeConstruct %8 %67 %67 %67 -%76 = OpAccessChain %74 %66 %65 -OpStore %76 %75 +OpBranch %72 +%72 = OpLabel +%74 = OpCompositeConstruct %8 %67 %67 %67 +%75 = OpAccessChain %73 %66 %65 +OpStore %75 %74 OpStore %58 %68 -%78 = OpAccessChain %77 %66 %65 %65 -OpStore %78 %67 -%79 = OpAccessChain %77 %66 %65 %65 -OpStore %79 %69 -%80 = OpLoad %23 %58 -%81 = OpAccessChain %77 %66 %65 %80 -OpStore %81 %70 -%82 = OpLoad %9 %66 -%83 = OpCompositeExtract %8 %82 0 -%84 = OpCompositeExtract %8 %82 0 -%85 = OpVectorShuffle %10 %84 %84 2 0 -%86 = OpCompositeExtract %8 %82 0 -%87 = OpFunctionCall %2 %55 %86 -%88 = OpCompositeExtract %8 %82 0 -%89 = OpVectorTimesMatrix %8 %88 %71 -%90 = OpCompositeExtract %8 %82 0 -%91 = OpMatrixTimesVector %8 %72 %90 -%92 = OpCompositeExtract %8 %82 0 -%93 = OpVectorTimesScalar %8 %92 %69 -%94 = OpCompositeExtract %8 %82 0 -%95 = OpVectorTimesScalar %8 %94 %69 +%77 = OpAccessChain %76 %66 %65 %65 +OpStore %77 %67 +%78 = OpAccessChain %76 %66 %65 %65 +OpStore %78 %69 +%79 = OpLoad %23 %58 +%80 = OpAccessChain %76 %66 %65 %79 +OpStore %80 %70 +%81 = OpLoad %9 %66 +%82 = OpCompositeExtract %8 %81 0 +%83 = OpCompositeExtract %8 %81 0 +%84 = OpVectorShuffle %10 %83 %83 2 0 +%85 = OpCompositeExtract %8 %81 0 +%86 = OpFunctionCall %2 %55 %85 +%87 = OpCompositeExtract %8 %81 0 +%88 = OpVectorTimesMatrix %8 %87 %71 +%89 = OpCompositeExtract %8 %81 0 +%90 = OpMatrixTimesVector %8 %71 %89 +%91 = OpCompositeExtract %8 %81 0 +%92 = OpVectorTimesScalar %8 %91 %69 +%93 = OpCompositeExtract %8 %81 0 +%94 = OpVectorTimesScalar %8 %93 %69 OpReturn OpFunctionEnd -%103 = OpFunction %2 None %63 -%102 = OpLabel -%96 = OpVariable %97 Function %98 -%99 = OpVariable %100 Function %101 -%104 = OpAccessChain %64 %32 %65 -%106 = OpAccessChain %105 %35 %65 -%108 = OpAccessChain %107 %38 %65 -%110 = OpAccessChain %109 %41 %65 -%112 = OpAccessChain %111 %44 %65 -%114 = OpAccessChain %113 %47 %65 -%116 = OpAccessChain %115 %50 %65 -OpBranch %118 -%118 = OpLabel -%124 = OpLoad %121 %122 -%127 = OpIEqual %126 %124 %125 -%128 = OpAll %3 %127 -OpSelectionMerge %129 None -OpBranchConditional %128 %130 %129 -%130 = OpLabel -OpStore %28 %119 -OpStore %30 %120 -OpBranch %129 +%102 = OpFunction %2 None %63 +%101 = OpLabel +%95 = OpVariable %96 Function %97 +%98 = OpVariable %99 Function %100 +%103 = OpAccessChain %64 %32 %65 +%105 = OpAccessChain %104 %35 %65 +%107 = OpAccessChain %106 %38 %65 +%109 = OpAccessChain %108 %41 %65 +%111 = OpAccessChain %110 %44 %65 +%113 = OpAccessChain %112 %47 %65 +%115 = OpAccessChain %114 %50 %65 +OpBranch %117 +%117 = OpLabel +%123 = OpLoad %120 %121 +%126 = OpIEqual %125 %123 %124 +%127 = OpAll %3 %126 +OpSelectionMerge %128 None +OpBranchConditional %127 %129 %128 %129 = OpLabel -OpControlBarrier %18 %18 %131 -OpBranch %132 -%132 = OpLabel -%133 = OpFunctionCall %2 %62 -%137 = OpAccessChain %136 %116 %65 %65 -%138 = OpLoad %20 %137 -%142 = OpAccessChain %141 %114 %65 %65 %65 -%143 = OpLoad %12 %142 -%144 = OpMatrixTimesVector %10 %138 %143 -%145 = OpCompositeExtract %4 %144 0 -%147 = OpAccessChain %134 %28 %146 -OpStore %147 %145 -%148 = OpLoad %15 %112 -%149 = OpLoad %8 %110 -%150 = OpMatrixTimesVector %10 %148 %149 -%151 = OpCompositeExtract %4 %150 0 -%153 = OpAccessChain %134 %28 %152 -OpStore %153 %151 -%156 = OpAccessChain %77 %106 %155 %155 -%157 = OpLoad %4 %156 -%159 = OpAccessChain %134 %28 %158 -OpStore %159 %157 -%163 = OpAccessChain %161 %108 %65 %162 -%164 = OpLoad %4 %163 -%166 = OpAccessChain %134 %28 %165 -OpStore %166 %164 -%168 = OpAccessChain %167 %104 %155 -%169 = OpLoad %4 %168 -%170 = OpAccessChain %134 %28 %162 -OpStore %170 %169 -%171 = OpAccessChain %77 %104 %65 %65 -%172 = OpLoad %4 %171 -%173 = OpAccessChain %134 %28 %18 -OpStore %173 %172 -%174 = OpAccessChain %167 %104 %155 -OpStore %174 %117 -%175 = OpArrayLength %7 %35 0 -%176 = OpConvertUToF %4 %175 -%177 = OpAccessChain %134 %28 %155 -OpStore %177 %176 -OpAtomicStore %30 %27 %178 %18 -OpStore %96 %67 -OpStore %99 %25 +OpStore %28 %118 +OpStore %30 %119 +OpBranch %128 +%128 = OpLabel +OpControlBarrier %18 %18 %130 +OpBranch %131 +%131 = OpLabel +%132 = OpFunctionCall %2 %62 +%136 = OpAccessChain %135 %115 %65 %65 +%137 = OpLoad %20 %136 +%141 = OpAccessChain %140 %113 %65 %65 %65 +%142 = OpLoad %12 %141 +%143 = OpMatrixTimesVector %10 %137 %142 +%144 = OpCompositeExtract %4 %143 0 +%146 = OpAccessChain %133 %28 %145 +OpStore %146 %144 +%147 = OpLoad %15 %111 +%148 = OpLoad %8 %109 +%149 = OpMatrixTimesVector %10 %147 %148 +%150 = OpCompositeExtract %4 %149 0 +%152 = OpAccessChain %133 %28 %151 +OpStore %152 %150 +%155 = OpAccessChain %76 %105 %154 %154 +%156 = OpLoad %4 %155 +%158 = OpAccessChain %133 %28 %157 +OpStore %158 %156 +%162 = OpAccessChain %160 %107 %65 %161 +%163 = OpLoad %4 %162 +%165 = OpAccessChain %133 %28 %164 +OpStore %165 %163 +%167 = OpAccessChain %166 %103 %154 +%168 = OpLoad %4 %167 +%169 = OpAccessChain %133 %28 %161 +OpStore %169 %168 +%170 = OpAccessChain %76 %103 %65 %65 +%171 = OpLoad %4 %170 +%172 = OpAccessChain %133 %28 %18 +OpStore %172 %171 +%173 = OpAccessChain %166 %103 %154 +OpStore %173 %116 +%174 = OpArrayLength %7 %35 0 +%175 = OpConvertUToF %4 %174 +%176 = OpAccessChain %133 %28 %154 +OpStore %176 %175 +OpAtomicStore %30 %27 %177 %18 +OpStore %95 %67 +OpStore %98 %25 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 0fa6bf529..60bdd7ae0 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 88 +; Bound: 87 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -16,83 +16,82 @@ OpExecutionMode %8 OriginUpperLeft %10 = OpConstant %4 1.0 %11 = OpConstant %4 0.0 %12 = OpConstantNull %5 -%13 = OpConstantNull %5 -%14 = OpTypeInt 32 0 -%15 = OpConstant %14 0 -%16 = OpConstant %6 -1 -%17 = OpConstant %14 1 -%18 = OpConstant %6 0 -%19 = OpConstant %14 4294967295 -%20 = OpConstant %6 1 -%28 = OpConstantComposite %3 %11 %11 %11 %11 -%29 = OpConstantComposite %3 %10 %10 %10 %10 -%32 = OpConstantNull %6 -%45 = OpTypeVector %14 2 -%55 = OpConstant %14 32 -%65 = OpConstantComposite %45 %55 %55 -%77 = OpConstant %6 31 -%83 = OpConstantComposite %5 %77 %77 +%13 = OpTypeInt 32 0 +%14 = OpConstant %13 0 +%15 = OpConstant %6 -1 +%16 = OpConstant %13 1 +%17 = OpConstant %6 0 +%18 = OpConstant %13 4294967295 +%19 = OpConstant %6 1 +%27 = OpConstantComposite %3 %11 %11 %11 %11 +%28 = OpConstantComposite %3 %10 %10 %10 %10 +%31 = OpConstantNull %6 +%44 = OpTypeVector %13 2 +%54 = OpConstant %13 32 +%64 = OpConstantComposite %44 %54 %54 +%76 = OpConstant %6 31 +%82 = OpConstantComposite %5 %76 %76 %8 = OpFunction %2 None %9 %7 = OpLabel -OpBranch %21 -%21 = OpLabel -%22 = OpCompositeConstruct %3 %11 %11 %11 %11 -%23 = OpExtInst %4 %1 Degrees %10 -%24 = OpExtInst %4 %1 Radians %10 -%25 = OpExtInst %3 %1 Degrees %22 -%26 = OpExtInst %3 %1 Radians %22 -%27 = OpExtInst %3 %1 FClamp %22 %28 %29 -%30 = OpExtInst %3 %1 Refract %22 %22 %10 +OpBranch %20 +%20 = OpLabel +%21 = OpCompositeConstruct %3 %11 %11 %11 %11 +%22 = OpExtInst %4 %1 Degrees %10 +%23 = OpExtInst %4 %1 Radians %10 +%24 = OpExtInst %3 %1 Degrees %21 +%25 = OpExtInst %3 %1 Radians %21 +%26 = OpExtInst %3 %1 FClamp %21 %27 %28 +%29 = OpExtInst %3 %1 Refract %21 %21 %10 +%32 = OpCompositeExtract %6 %12 0 %33 = OpCompositeExtract %6 %12 0 -%34 = OpCompositeExtract %6 %13 0 -%35 = OpIMul %6 %33 %34 -%36 = OpIAdd %6 %32 %35 +%34 = OpIMul %6 %32 %33 +%35 = OpIAdd %6 %31 %34 +%36 = OpCompositeExtract %6 %12 1 %37 = OpCompositeExtract %6 %12 1 -%38 = OpCompositeExtract %6 %13 1 -%39 = OpIMul %6 %37 %38 -%31 = OpIAdd %6 %36 %39 -%40 = OpCopyObject %14 %15 -%41 = OpExtInst %14 %1 FindUMsb %40 -%42 = OpExtInst %6 %1 FindSMsb %16 -%43 = OpCompositeConstruct %5 %16 %16 -%44 = OpExtInst %5 %1 FindSMsb %43 -%46 = OpCompositeConstruct %45 %17 %17 -%47 = OpExtInst %45 %1 FindUMsb %46 -%48 = OpExtInst %6 %1 FindILsb %16 -%49 = OpExtInst %14 %1 FindILsb %17 -%50 = OpCompositeConstruct %5 %16 %16 -%51 = OpExtInst %5 %1 FindILsb %50 -%52 = OpCompositeConstruct %45 %17 %17 -%53 = OpExtInst %45 %1 FindILsb %52 -%56 = OpExtInst %14 %1 FindILsb %15 -%54 = OpExtInst %14 %1 UMin %55 %56 -%58 = OpExtInst %6 %1 FindILsb %18 -%57 = OpExtInst %6 %1 UMin %55 %58 -%60 = OpExtInst %14 %1 FindILsb %19 -%59 = OpExtInst %14 %1 UMin %55 %60 -%62 = OpExtInst %6 %1 FindILsb %16 -%61 = OpExtInst %6 %1 UMin %55 %62 -%63 = OpCompositeConstruct %45 %15 %15 -%66 = OpExtInst %45 %1 FindILsb %63 -%64 = OpExtInst %45 %1 UMin %65 %66 -%67 = OpCompositeConstruct %5 %18 %18 -%69 = OpExtInst %5 %1 FindILsb %67 -%68 = OpExtInst %5 %1 UMin %65 %69 -%70 = OpCompositeConstruct %45 %17 %17 -%72 = OpExtInst %45 %1 FindILsb %70 -%71 = OpExtInst %45 %1 UMin %65 %72 -%73 = OpCompositeConstruct %5 %20 %20 -%75 = OpExtInst %5 %1 FindILsb %73 -%74 = OpExtInst %5 %1 UMin %65 %75 -%78 = OpExtInst %6 %1 FindUMsb %16 -%76 = OpISub %6 %77 %78 -%80 = OpExtInst %6 %1 FindUMsb %17 -%79 = OpISub %14 %77 %80 -%81 = OpCompositeConstruct %5 %16 %16 -%84 = OpExtInst %5 %1 FindUMsb %81 -%82 = OpISub %5 %83 %84 -%85 = OpCompositeConstruct %45 %17 %17 -%87 = OpExtInst %5 %1 FindUMsb %85 -%86 = OpISub %45 %83 %87 +%38 = OpIMul %6 %36 %37 +%30 = OpIAdd %6 %35 %38 +%39 = OpCopyObject %13 %14 +%40 = OpExtInst %13 %1 FindUMsb %39 +%41 = OpExtInst %6 %1 FindSMsb %15 +%42 = OpCompositeConstruct %5 %15 %15 +%43 = OpExtInst %5 %1 FindSMsb %42 +%45 = OpCompositeConstruct %44 %16 %16 +%46 = OpExtInst %44 %1 FindUMsb %45 +%47 = OpExtInst %6 %1 FindILsb %15 +%48 = OpExtInst %13 %1 FindILsb %16 +%49 = OpCompositeConstruct %5 %15 %15 +%50 = OpExtInst %5 %1 FindILsb %49 +%51 = OpCompositeConstruct %44 %16 %16 +%52 = OpExtInst %44 %1 FindILsb %51 +%55 = OpExtInst %13 %1 FindILsb %14 +%53 = OpExtInst %13 %1 UMin %54 %55 +%57 = OpExtInst %6 %1 FindILsb %17 +%56 = OpExtInst %6 %1 UMin %54 %57 +%59 = OpExtInst %13 %1 FindILsb %18 +%58 = OpExtInst %13 %1 UMin %54 %59 +%61 = OpExtInst %6 %1 FindILsb %15 +%60 = OpExtInst %6 %1 UMin %54 %61 +%62 = OpCompositeConstruct %44 %14 %14 +%65 = OpExtInst %44 %1 FindILsb %62 +%63 = OpExtInst %44 %1 UMin %64 %65 +%66 = OpCompositeConstruct %5 %17 %17 +%68 = OpExtInst %5 %1 FindILsb %66 +%67 = OpExtInst %5 %1 UMin %64 %68 +%69 = OpCompositeConstruct %44 %16 %16 +%71 = OpExtInst %44 %1 FindILsb %69 +%70 = OpExtInst %44 %1 UMin %64 %71 +%72 = OpCompositeConstruct %5 %19 %19 +%74 = OpExtInst %5 %1 FindILsb %72 +%73 = OpExtInst %5 %1 UMin %64 %74 +%77 = OpExtInst %6 %1 FindUMsb %15 +%75 = OpISub %6 %76 %77 +%79 = OpExtInst %6 %1 FindUMsb %16 +%78 = OpISub %13 %76 %79 +%80 = OpCompositeConstruct %5 %15 %15 +%83 = OpExtInst %5 %1 FindUMsb %80 +%81 = OpISub %5 %82 %83 +%84 = OpCompositeConstruct %44 %16 %16 +%86 = OpExtInst %5 %1 FindUMsb %84 +%85 = OpISub %44 %82 %86 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 22a67029c..6544cfd40 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 530 +; Bound: 522 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %519 "main" -OpExecutionMode %519 LocalSize 1 1 1 +OpEntryPoint GLCompute %511 "main" +OpExecutionMode %511 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -52,32 +52,24 @@ OpExecutionMode %519 LocalSize 1 1 1 %123 = OpConstant %122 2 %124 = OpConstant %122 1 %125 = OpConstantNull %12 -%126 = OpConstantNull %12 -%127 = OpConstantNull %12 -%128 = OpConstantNull %12 -%129 = OpConstantNull %12 -%130 = OpConstantNull %12 -%131 = OpConstantNull %13 -%132 = OpConstantNull %13 -%133 = OpConstantNull %13 -%134 = OpConstantNull %14 -%136 = OpTypeVector %6 2 -%147 = OpTypeVector %122 3 -%210 = OpTypeVector %122 2 -%445 = OpTypePointer Function %6 -%446 = OpConstantNull %6 -%448 = OpTypePointer Function %15 -%449 = OpConstantNull %15 -%452 = OpConstantNull %15 -%480 = OpTypePointer Function %6 -%491 = OpConstant %6 -1 -%492 = OpConstant %6 -2 -%493 = OpConstant %6 -3 -%494 = OpConstant %6 4 -%495 = OpConstant %6 -5 -%496 = OpConstant %6 6 -%497 = OpConstant %6 -7 -%498 = OpConstant %6 -8 +%126 = OpConstantNull %13 +%127 = OpConstantNull %14 +%129 = OpTypeVector %6 2 +%140 = OpTypeVector %122 3 +%203 = OpTypeVector %122 2 +%438 = OpTypePointer Function %6 +%439 = OpConstantNull %6 +%441 = OpTypePointer Function %15 +%442 = OpConstantNull %15 +%472 = OpTypePointer Function %6 +%483 = OpConstant %6 -1 +%484 = OpConstant %6 -2 +%485 = OpConstant %6 -3 +%486 = OpConstant %6 4 +%487 = OpConstant %6 -5 +%488 = OpConstant %6 6 +%489 = OpConstant %6 -7 +%490 = OpConstant %6 -8 %25 = OpFunction %3 None %26 %24 = OpLabel OpBranch %31 @@ -176,417 +168,417 @@ OpReturn OpFunctionEnd %120 = OpFunction %2 None %103 %119 = OpLabel -OpBranch %135 -%135 = OpLabel -%137 = OpCompositeConstruct %136 %22 %22 -%138 = OpSNegate %136 %137 -%139 = OpCompositeConstruct %9 %16 %16 -%140 = OpFNegate %9 %139 -%141 = OpIAdd %6 %59 %22 -%142 = OpIAdd %122 %123 %124 -%143 = OpFAdd %4 %55 %16 -%144 = OpCompositeConstruct %136 %59 %59 -%145 = OpCompositeConstruct %136 %22 %22 -%146 = OpIAdd %136 %144 %145 -%148 = OpCompositeConstruct %147 %123 %123 %123 -%149 = OpCompositeConstruct %147 %124 %124 %124 -%150 = OpIAdd %147 %148 %149 -%151 = OpCompositeConstruct %3 %55 %55 %55 %55 -%152 = OpCompositeConstruct %3 %16 %16 %16 %16 -%153 = OpFAdd %3 %151 %152 -%154 = OpISub %6 %59 %22 -%155 = OpISub %122 %123 %124 -%156 = OpFSub %4 %55 %16 -%157 = OpCompositeConstruct %136 %59 %59 -%158 = OpCompositeConstruct %136 %22 %22 -%159 = OpISub %136 %157 %158 -%160 = OpCompositeConstruct %147 %123 %123 %123 -%161 = OpCompositeConstruct %147 %124 %124 %124 -%162 = OpISub %147 %160 %161 -%163 = OpCompositeConstruct %3 %55 %55 %55 %55 -%164 = OpCompositeConstruct %3 %16 %16 %16 %16 -%165 = OpFSub %3 %163 %164 -%166 = OpIMul %6 %59 %22 -%167 = OpIMul %122 %123 %124 -%168 = OpFMul %4 %55 %16 -%169 = OpCompositeConstruct %136 %59 %59 -%170 = OpCompositeConstruct %136 %22 %22 -%171 = OpIMul %136 %169 %170 -%172 = OpCompositeConstruct %147 %123 %123 %123 -%173 = OpCompositeConstruct %147 %124 %124 %124 -%174 = OpIMul %147 %172 %173 -%175 = OpCompositeConstruct %3 %55 %55 %55 %55 -%176 = OpCompositeConstruct %3 %16 %16 %16 %16 -%177 = OpFMul %3 %175 %176 -%178 = OpSDiv %6 %59 %22 -%179 = OpUDiv %122 %123 %124 -%180 = OpFDiv %4 %55 %16 -%181 = OpCompositeConstruct %136 %59 %59 -%182 = OpCompositeConstruct %136 %22 %22 -%183 = OpSDiv %136 %181 %182 -%184 = OpCompositeConstruct %147 %123 %123 %123 -%185 = OpCompositeConstruct %147 %124 %124 %124 -%186 = OpUDiv %147 %184 %185 -%187 = OpCompositeConstruct %3 %55 %55 %55 %55 -%188 = OpCompositeConstruct %3 %16 %16 %16 %16 -%189 = OpFDiv %3 %187 %188 -%190 = OpSRem %6 %59 %22 -%191 = OpUMod %122 %123 %124 -%192 = OpFRem %4 %55 %16 -%193 = OpCompositeConstruct %136 %59 %59 -%194 = OpCompositeConstruct %136 %22 %22 -%195 = OpSRem %136 %193 %194 -%196 = OpCompositeConstruct %147 %123 %123 %123 -%197 = OpCompositeConstruct %147 %124 %124 %124 -%198 = OpUMod %147 %196 %197 -%199 = OpCompositeConstruct %3 %55 %55 %55 %55 -%200 = OpCompositeConstruct %3 %16 %16 %16 %16 -%201 = OpFRem %3 %199 %200 -OpBranch %202 -%202 = OpLabel -%204 = OpCompositeConstruct %136 %59 %59 -%205 = OpCompositeConstruct %136 %22 %22 -%206 = OpIAdd %136 %204 %205 -%207 = OpCompositeConstruct %136 %22 %22 -%208 = OpCompositeConstruct %136 %59 %59 -%209 = OpIAdd %136 %208 %207 -%211 = OpCompositeConstruct %210 %123 %123 -%212 = OpCompositeConstruct %210 %124 %124 -%213 = OpIAdd %210 %211 %212 -%214 = OpCompositeConstruct %210 %124 %124 -%215 = OpCompositeConstruct %210 %123 %123 -%216 = OpIAdd %210 %215 %214 -%217 = OpCompositeConstruct %9 %55 %55 -%218 = OpCompositeConstruct %9 %16 %16 -%219 = OpFAdd %9 %217 %218 -%220 = OpCompositeConstruct %9 %16 %16 -%221 = OpCompositeConstruct %9 %55 %55 -%222 = OpFAdd %9 %221 %220 -%223 = OpCompositeConstruct %136 %59 %59 -%224 = OpCompositeConstruct %136 %22 %22 -%225 = OpISub %136 %223 %224 -%226 = OpCompositeConstruct %136 %22 %22 -%227 = OpCompositeConstruct %136 %59 %59 -%228 = OpISub %136 %227 %226 -%229 = OpCompositeConstruct %210 %123 %123 -%230 = OpCompositeConstruct %210 %124 %124 -%231 = OpISub %210 %229 %230 -%232 = OpCompositeConstruct %210 %124 %124 -%233 = OpCompositeConstruct %210 %123 %123 -%234 = OpISub %210 %233 %232 -%235 = OpCompositeConstruct %9 %55 %55 -%236 = OpCompositeConstruct %9 %16 %16 -%237 = OpFSub %9 %235 %236 -%238 = OpCompositeConstruct %9 %16 %16 -%239 = OpCompositeConstruct %9 %55 %55 -%240 = OpFSub %9 %239 %238 -%241 = OpCompositeConstruct %136 %59 %59 -%243 = OpCompositeConstruct %136 %22 %22 -%242 = OpIMul %136 %241 %243 -%244 = OpCompositeConstruct %136 %22 %22 -%246 = OpCompositeConstruct %136 %59 %59 -%245 = OpIMul %136 %244 %246 -%247 = OpCompositeConstruct %210 %123 %123 -%249 = OpCompositeConstruct %210 %124 %124 -%248 = OpIMul %210 %247 %249 -%250 = OpCompositeConstruct %210 %124 %124 -%252 = OpCompositeConstruct %210 %123 %123 -%251 = OpIMul %210 %250 %252 -%253 = OpCompositeConstruct %9 %55 %55 -%254 = OpVectorTimesScalar %9 %253 %16 -%255 = OpCompositeConstruct %9 %16 %16 -%256 = OpVectorTimesScalar %9 %255 %55 -%257 = OpCompositeConstruct %136 %59 %59 -%258 = OpCompositeConstruct %136 %22 %22 -%259 = OpSDiv %136 %257 %258 -%260 = OpCompositeConstruct %136 %22 %22 -%261 = OpCompositeConstruct %136 %59 %59 -%262 = OpSDiv %136 %261 %260 -%263 = OpCompositeConstruct %210 %123 %123 -%264 = OpCompositeConstruct %210 %124 %124 -%265 = OpUDiv %210 %263 %264 -%266 = OpCompositeConstruct %210 %124 %124 -%267 = OpCompositeConstruct %210 %123 %123 -%268 = OpUDiv %210 %267 %266 -%269 = OpCompositeConstruct %9 %55 %55 -%270 = OpCompositeConstruct %9 %16 %16 -%271 = OpFDiv %9 %269 %270 -%272 = OpCompositeConstruct %9 %16 %16 -%273 = OpCompositeConstruct %9 %55 %55 -%274 = OpFDiv %9 %273 %272 -%275 = OpCompositeConstruct %136 %59 %59 -%276 = OpCompositeConstruct %136 %22 %22 -%277 = OpSRem %136 %275 %276 -%278 = OpCompositeConstruct %136 %22 %22 -%279 = OpCompositeConstruct %136 %59 %59 -%280 = OpSRem %136 %279 %278 -%281 = OpCompositeConstruct %210 %123 %123 -%282 = OpCompositeConstruct %210 %124 %124 -%283 = OpUMod %210 %281 %282 -%284 = OpCompositeConstruct %210 %124 %124 -%285 = OpCompositeConstruct %210 %123 %123 -%286 = OpUMod %210 %285 %284 -%287 = OpCompositeConstruct %9 %55 %55 -%288 = OpCompositeConstruct %9 %16 %16 -%289 = OpFRem %9 %287 %288 -%290 = OpCompositeConstruct %9 %16 %16 -%291 = OpCompositeConstruct %9 %55 %55 -%292 = OpFRem %9 %291 %290 -OpBranch %203 -%203 = OpLabel -%294 = OpCompositeExtract %10 %125 0 -%295 = OpCompositeExtract %10 %126 0 -%296 = OpFAdd %10 %294 %295 -%297 = OpCompositeExtract %10 %125 1 -%298 = OpCompositeExtract %10 %126 1 -%299 = OpFAdd %10 %297 %298 -%300 = OpCompositeExtract %10 %125 2 -%301 = OpCompositeExtract %10 %126 2 -%302 = OpFAdd %10 %300 %301 -%293 = OpCompositeConstruct %12 %296 %299 %302 -%304 = OpCompositeExtract %10 %127 0 -%305 = OpCompositeExtract %10 %128 0 -%306 = OpFSub %10 %304 %305 -%307 = OpCompositeExtract %10 %127 1 -%308 = OpCompositeExtract %10 %128 1 -%309 = OpFSub %10 %307 %308 -%310 = OpCompositeExtract %10 %127 2 -%311 = OpCompositeExtract %10 %128 2 -%312 = OpFSub %10 %310 %311 -%303 = OpCompositeConstruct %12 %306 %309 %312 -%313 = OpMatrixTimesScalar %12 %129 %16 -%314 = OpMatrixTimesScalar %12 %130 %55 -%315 = OpCompositeConstruct %3 %16 %16 %16 %16 -%316 = OpMatrixTimesVector %10 %131 %315 -%317 = OpCompositeConstruct %10 %55 %55 %55 -%318 = OpVectorTimesMatrix %3 %317 %132 -%319 = OpMatrixTimesMatrix %12 %133 %134 +OpBranch %128 +%128 = OpLabel +%130 = OpCompositeConstruct %129 %22 %22 +%131 = OpSNegate %129 %130 +%132 = OpCompositeConstruct %9 %16 %16 +%133 = OpFNegate %9 %132 +%134 = OpIAdd %6 %59 %22 +%135 = OpIAdd %122 %123 %124 +%136 = OpFAdd %4 %55 %16 +%137 = OpCompositeConstruct %129 %59 %59 +%138 = OpCompositeConstruct %129 %22 %22 +%139 = OpIAdd %129 %137 %138 +%141 = OpCompositeConstruct %140 %123 %123 %123 +%142 = OpCompositeConstruct %140 %124 %124 %124 +%143 = OpIAdd %140 %141 %142 +%144 = OpCompositeConstruct %3 %55 %55 %55 %55 +%145 = OpCompositeConstruct %3 %16 %16 %16 %16 +%146 = OpFAdd %3 %144 %145 +%147 = OpISub %6 %59 %22 +%148 = OpISub %122 %123 %124 +%149 = OpFSub %4 %55 %16 +%150 = OpCompositeConstruct %129 %59 %59 +%151 = OpCompositeConstruct %129 %22 %22 +%152 = OpISub %129 %150 %151 +%153 = OpCompositeConstruct %140 %123 %123 %123 +%154 = OpCompositeConstruct %140 %124 %124 %124 +%155 = OpISub %140 %153 %154 +%156 = OpCompositeConstruct %3 %55 %55 %55 %55 +%157 = OpCompositeConstruct %3 %16 %16 %16 %16 +%158 = OpFSub %3 %156 %157 +%159 = OpIMul %6 %59 %22 +%160 = OpIMul %122 %123 %124 +%161 = OpFMul %4 %55 %16 +%162 = OpCompositeConstruct %129 %59 %59 +%163 = OpCompositeConstruct %129 %22 %22 +%164 = OpIMul %129 %162 %163 +%165 = OpCompositeConstruct %140 %123 %123 %123 +%166 = OpCompositeConstruct %140 %124 %124 %124 +%167 = OpIMul %140 %165 %166 +%168 = OpCompositeConstruct %3 %55 %55 %55 %55 +%169 = OpCompositeConstruct %3 %16 %16 %16 %16 +%170 = OpFMul %3 %168 %169 +%171 = OpSDiv %6 %59 %22 +%172 = OpUDiv %122 %123 %124 +%173 = OpFDiv %4 %55 %16 +%174 = OpCompositeConstruct %129 %59 %59 +%175 = OpCompositeConstruct %129 %22 %22 +%176 = OpSDiv %129 %174 %175 +%177 = OpCompositeConstruct %140 %123 %123 %123 +%178 = OpCompositeConstruct %140 %124 %124 %124 +%179 = OpUDiv %140 %177 %178 +%180 = OpCompositeConstruct %3 %55 %55 %55 %55 +%181 = OpCompositeConstruct %3 %16 %16 %16 %16 +%182 = OpFDiv %3 %180 %181 +%183 = OpSRem %6 %59 %22 +%184 = OpUMod %122 %123 %124 +%185 = OpFRem %4 %55 %16 +%186 = OpCompositeConstruct %129 %59 %59 +%187 = OpCompositeConstruct %129 %22 %22 +%188 = OpSRem %129 %186 %187 +%189 = OpCompositeConstruct %140 %123 %123 %123 +%190 = OpCompositeConstruct %140 %124 %124 %124 +%191 = OpUMod %140 %189 %190 +%192 = OpCompositeConstruct %3 %55 %55 %55 %55 +%193 = OpCompositeConstruct %3 %16 %16 %16 %16 +%194 = OpFRem %3 %192 %193 +OpBranch %195 +%195 = OpLabel +%197 = OpCompositeConstruct %129 %59 %59 +%198 = OpCompositeConstruct %129 %22 %22 +%199 = OpIAdd %129 %197 %198 +%200 = OpCompositeConstruct %129 %22 %22 +%201 = OpCompositeConstruct %129 %59 %59 +%202 = OpIAdd %129 %201 %200 +%204 = OpCompositeConstruct %203 %123 %123 +%205 = OpCompositeConstruct %203 %124 %124 +%206 = OpIAdd %203 %204 %205 +%207 = OpCompositeConstruct %203 %124 %124 +%208 = OpCompositeConstruct %203 %123 %123 +%209 = OpIAdd %203 %208 %207 +%210 = OpCompositeConstruct %9 %55 %55 +%211 = OpCompositeConstruct %9 %16 %16 +%212 = OpFAdd %9 %210 %211 +%213 = OpCompositeConstruct %9 %16 %16 +%214 = OpCompositeConstruct %9 %55 %55 +%215 = OpFAdd %9 %214 %213 +%216 = OpCompositeConstruct %129 %59 %59 +%217 = OpCompositeConstruct %129 %22 %22 +%218 = OpISub %129 %216 %217 +%219 = OpCompositeConstruct %129 %22 %22 +%220 = OpCompositeConstruct %129 %59 %59 +%221 = OpISub %129 %220 %219 +%222 = OpCompositeConstruct %203 %123 %123 +%223 = OpCompositeConstruct %203 %124 %124 +%224 = OpISub %203 %222 %223 +%225 = OpCompositeConstruct %203 %124 %124 +%226 = OpCompositeConstruct %203 %123 %123 +%227 = OpISub %203 %226 %225 +%228 = OpCompositeConstruct %9 %55 %55 +%229 = OpCompositeConstruct %9 %16 %16 +%230 = OpFSub %9 %228 %229 +%231 = OpCompositeConstruct %9 %16 %16 +%232 = OpCompositeConstruct %9 %55 %55 +%233 = OpFSub %9 %232 %231 +%234 = OpCompositeConstruct %129 %59 %59 +%236 = OpCompositeConstruct %129 %22 %22 +%235 = OpIMul %129 %234 %236 +%237 = OpCompositeConstruct %129 %22 %22 +%239 = OpCompositeConstruct %129 %59 %59 +%238 = OpIMul %129 %237 %239 +%240 = OpCompositeConstruct %203 %123 %123 +%242 = OpCompositeConstruct %203 %124 %124 +%241 = OpIMul %203 %240 %242 +%243 = OpCompositeConstruct %203 %124 %124 +%245 = OpCompositeConstruct %203 %123 %123 +%244 = OpIMul %203 %243 %245 +%246 = OpCompositeConstruct %9 %55 %55 +%247 = OpVectorTimesScalar %9 %246 %16 +%248 = OpCompositeConstruct %9 %16 %16 +%249 = OpVectorTimesScalar %9 %248 %55 +%250 = OpCompositeConstruct %129 %59 %59 +%251 = OpCompositeConstruct %129 %22 %22 +%252 = OpSDiv %129 %250 %251 +%253 = OpCompositeConstruct %129 %22 %22 +%254 = OpCompositeConstruct %129 %59 %59 +%255 = OpSDiv %129 %254 %253 +%256 = OpCompositeConstruct %203 %123 %123 +%257 = OpCompositeConstruct %203 %124 %124 +%258 = OpUDiv %203 %256 %257 +%259 = OpCompositeConstruct %203 %124 %124 +%260 = OpCompositeConstruct %203 %123 %123 +%261 = OpUDiv %203 %260 %259 +%262 = OpCompositeConstruct %9 %55 %55 +%263 = OpCompositeConstruct %9 %16 %16 +%264 = OpFDiv %9 %262 %263 +%265 = OpCompositeConstruct %9 %16 %16 +%266 = OpCompositeConstruct %9 %55 %55 +%267 = OpFDiv %9 %266 %265 +%268 = OpCompositeConstruct %129 %59 %59 +%269 = OpCompositeConstruct %129 %22 %22 +%270 = OpSRem %129 %268 %269 +%271 = OpCompositeConstruct %129 %22 %22 +%272 = OpCompositeConstruct %129 %59 %59 +%273 = OpSRem %129 %272 %271 +%274 = OpCompositeConstruct %203 %123 %123 +%275 = OpCompositeConstruct %203 %124 %124 +%276 = OpUMod %203 %274 %275 +%277 = OpCompositeConstruct %203 %124 %124 +%278 = OpCompositeConstruct %203 %123 %123 +%279 = OpUMod %203 %278 %277 +%280 = OpCompositeConstruct %9 %55 %55 +%281 = OpCompositeConstruct %9 %16 %16 +%282 = OpFRem %9 %280 %281 +%283 = OpCompositeConstruct %9 %16 %16 +%284 = OpCompositeConstruct %9 %55 %55 +%285 = OpFRem %9 %284 %283 +OpBranch %196 +%196 = OpLabel +%287 = OpCompositeExtract %10 %125 0 +%288 = OpCompositeExtract %10 %125 0 +%289 = OpFAdd %10 %287 %288 +%290 = OpCompositeExtract %10 %125 1 +%291 = OpCompositeExtract %10 %125 1 +%292 = OpFAdd %10 %290 %291 +%293 = OpCompositeExtract %10 %125 2 +%294 = OpCompositeExtract %10 %125 2 +%295 = OpFAdd %10 %293 %294 +%286 = OpCompositeConstruct %12 %289 %292 %295 +%297 = OpCompositeExtract %10 %125 0 +%298 = OpCompositeExtract %10 %125 0 +%299 = OpFSub %10 %297 %298 +%300 = OpCompositeExtract %10 %125 1 +%301 = OpCompositeExtract %10 %125 1 +%302 = OpFSub %10 %300 %301 +%303 = OpCompositeExtract %10 %125 2 +%304 = OpCompositeExtract %10 %125 2 +%305 = OpFSub %10 %303 %304 +%296 = OpCompositeConstruct %12 %299 %302 %305 +%306 = OpMatrixTimesScalar %12 %125 %16 +%307 = OpMatrixTimesScalar %12 %125 %55 +%308 = OpCompositeConstruct %3 %16 %16 %16 %16 +%309 = OpMatrixTimesVector %10 %126 %308 +%310 = OpCompositeConstruct %10 %55 %55 %55 +%311 = OpVectorTimesMatrix %3 %310 %126 +%312 = OpMatrixTimesMatrix %12 %126 %127 OpReturn OpFunctionEnd -%321 = OpFunction %2 None %103 -%320 = OpLabel -OpBranch %322 -%322 = OpLabel -%323 = OpNot %6 %22 -%324 = OpNot %122 %124 -%325 = OpCompositeConstruct %136 %22 %22 -%326 = OpNot %136 %325 -%327 = OpCompositeConstruct %147 %124 %124 %124 -%328 = OpNot %147 %327 -%329 = OpBitwiseOr %6 %59 %22 -%330 = OpBitwiseOr %122 %123 %124 -%331 = OpCompositeConstruct %136 %59 %59 -%332 = OpCompositeConstruct %136 %22 %22 -%333 = OpBitwiseOr %136 %331 %332 -%334 = OpCompositeConstruct %147 %123 %123 %123 -%335 = OpCompositeConstruct %147 %124 %124 %124 -%336 = OpBitwiseOr %147 %334 %335 -%337 = OpBitwiseAnd %6 %59 %22 -%338 = OpBitwiseAnd %122 %123 %124 -%339 = OpCompositeConstruct %136 %59 %59 -%340 = OpCompositeConstruct %136 %22 %22 -%341 = OpBitwiseAnd %136 %339 %340 -%342 = OpCompositeConstruct %147 %123 %123 %123 -%343 = OpCompositeConstruct %147 %124 %124 %124 -%344 = OpBitwiseAnd %147 %342 %343 -%345 = OpBitwiseXor %6 %59 %22 -%346 = OpBitwiseXor %122 %123 %124 -%347 = OpCompositeConstruct %136 %59 %59 -%348 = OpCompositeConstruct %136 %22 %22 -%349 = OpBitwiseXor %136 %347 %348 -%350 = OpCompositeConstruct %147 %123 %123 %123 -%351 = OpCompositeConstruct %147 %124 %124 %124 -%352 = OpBitwiseXor %147 %350 %351 -%353 = OpShiftLeftLogical %6 %59 %124 -%354 = OpShiftLeftLogical %122 %123 %124 -%355 = OpCompositeConstruct %136 %59 %59 -%356 = OpCompositeConstruct %210 %124 %124 -%357 = OpShiftLeftLogical %136 %355 %356 -%358 = OpCompositeConstruct %147 %123 %123 %123 -%359 = OpCompositeConstruct %147 %124 %124 %124 -%360 = OpShiftLeftLogical %147 %358 %359 -%361 = OpShiftRightArithmetic %6 %59 %124 -%362 = OpShiftRightLogical %122 %123 %124 -%363 = OpCompositeConstruct %136 %59 %59 -%364 = OpCompositeConstruct %210 %124 %124 -%365 = OpShiftRightArithmetic %136 %363 %364 -%366 = OpCompositeConstruct %147 %123 %123 %123 -%367 = OpCompositeConstruct %147 %124 %124 %124 -%368 = OpShiftRightLogical %147 %366 %367 +%314 = OpFunction %2 None %103 +%313 = OpLabel +OpBranch %315 +%315 = OpLabel +%316 = OpNot %6 %22 +%317 = OpNot %122 %124 +%318 = OpCompositeConstruct %129 %22 %22 +%319 = OpNot %129 %318 +%320 = OpCompositeConstruct %140 %124 %124 %124 +%321 = OpNot %140 %320 +%322 = OpBitwiseOr %6 %59 %22 +%323 = OpBitwiseOr %122 %123 %124 +%324 = OpCompositeConstruct %129 %59 %59 +%325 = OpCompositeConstruct %129 %22 %22 +%326 = OpBitwiseOr %129 %324 %325 +%327 = OpCompositeConstruct %140 %123 %123 %123 +%328 = OpCompositeConstruct %140 %124 %124 %124 +%329 = OpBitwiseOr %140 %327 %328 +%330 = OpBitwiseAnd %6 %59 %22 +%331 = OpBitwiseAnd %122 %123 %124 +%332 = OpCompositeConstruct %129 %59 %59 +%333 = OpCompositeConstruct %129 %22 %22 +%334 = OpBitwiseAnd %129 %332 %333 +%335 = OpCompositeConstruct %140 %123 %123 %123 +%336 = OpCompositeConstruct %140 %124 %124 %124 +%337 = OpBitwiseAnd %140 %335 %336 +%338 = OpBitwiseXor %6 %59 %22 +%339 = OpBitwiseXor %122 %123 %124 +%340 = OpCompositeConstruct %129 %59 %59 +%341 = OpCompositeConstruct %129 %22 %22 +%342 = OpBitwiseXor %129 %340 %341 +%343 = OpCompositeConstruct %140 %123 %123 %123 +%344 = OpCompositeConstruct %140 %124 %124 %124 +%345 = OpBitwiseXor %140 %343 %344 +%346 = OpShiftLeftLogical %6 %59 %124 +%347 = OpShiftLeftLogical %122 %123 %124 +%348 = OpCompositeConstruct %129 %59 %59 +%349 = OpCompositeConstruct %203 %124 %124 +%350 = OpShiftLeftLogical %129 %348 %349 +%351 = OpCompositeConstruct %140 %123 %123 %123 +%352 = OpCompositeConstruct %140 %124 %124 %124 +%353 = OpShiftLeftLogical %140 %351 %352 +%354 = OpShiftRightArithmetic %6 %59 %124 +%355 = OpShiftRightLogical %122 %123 %124 +%356 = OpCompositeConstruct %129 %59 %59 +%357 = OpCompositeConstruct %203 %124 %124 +%358 = OpShiftRightArithmetic %129 %356 %357 +%359 = OpCompositeConstruct %140 %123 %123 %123 +%360 = OpCompositeConstruct %140 %124 %124 %124 +%361 = OpShiftRightLogical %140 %359 %360 OpReturn OpFunctionEnd -%370 = OpFunction %2 None %103 -%369 = OpLabel -OpBranch %371 -%371 = OpLabel -%372 = OpIEqual %8 %59 %22 -%373 = OpIEqual %8 %123 %124 -%374 = OpFOrdEqual %8 %55 %16 -%375 = OpCompositeConstruct %136 %59 %59 -%376 = OpCompositeConstruct %136 %22 %22 -%377 = OpIEqual %106 %375 %376 -%378 = OpCompositeConstruct %147 %123 %123 %123 -%379 = OpCompositeConstruct %147 %124 %124 %124 -%380 = OpIEqual %11 %378 %379 -%381 = OpCompositeConstruct %3 %55 %55 %55 %55 -%382 = OpCompositeConstruct %3 %16 %16 %16 %16 -%383 = OpFOrdEqual %7 %381 %382 -%384 = OpINotEqual %8 %59 %22 -%385 = OpINotEqual %8 %123 %124 -%386 = OpFOrdNotEqual %8 %55 %16 -%387 = OpCompositeConstruct %136 %59 %59 -%388 = OpCompositeConstruct %136 %22 %22 -%389 = OpINotEqual %106 %387 %388 -%390 = OpCompositeConstruct %147 %123 %123 %123 -%391 = OpCompositeConstruct %147 %124 %124 %124 -%392 = OpINotEqual %11 %390 %391 -%393 = OpCompositeConstruct %3 %55 %55 %55 %55 -%394 = OpCompositeConstruct %3 %16 %16 %16 %16 -%395 = OpFOrdNotEqual %7 %393 %394 -%396 = OpSLessThan %8 %59 %22 -%397 = OpULessThan %8 %123 %124 -%398 = OpFOrdLessThan %8 %55 %16 -%399 = OpCompositeConstruct %136 %59 %59 -%400 = OpCompositeConstruct %136 %22 %22 -%401 = OpSLessThan %106 %399 %400 -%402 = OpCompositeConstruct %147 %123 %123 %123 -%403 = OpCompositeConstruct %147 %124 %124 %124 -%404 = OpULessThan %11 %402 %403 -%405 = OpCompositeConstruct %3 %55 %55 %55 %55 -%406 = OpCompositeConstruct %3 %16 %16 %16 %16 -%407 = OpFOrdLessThan %7 %405 %406 -%408 = OpSLessThanEqual %8 %59 %22 -%409 = OpULessThanEqual %8 %123 %124 -%410 = OpFOrdLessThanEqual %8 %55 %16 -%411 = OpCompositeConstruct %136 %59 %59 -%412 = OpCompositeConstruct %136 %22 %22 -%413 = OpSLessThanEqual %106 %411 %412 -%414 = OpCompositeConstruct %147 %123 %123 %123 -%415 = OpCompositeConstruct %147 %124 %124 %124 -%416 = OpULessThanEqual %11 %414 %415 -%417 = OpCompositeConstruct %3 %55 %55 %55 %55 -%418 = OpCompositeConstruct %3 %16 %16 %16 %16 -%419 = OpFOrdLessThanEqual %7 %417 %418 -%420 = OpSGreaterThan %8 %59 %22 -%421 = OpUGreaterThan %8 %123 %124 -%422 = OpFOrdGreaterThan %8 %55 %16 -%423 = OpCompositeConstruct %136 %59 %59 -%424 = OpCompositeConstruct %136 %22 %22 -%425 = OpSGreaterThan %106 %423 %424 -%426 = OpCompositeConstruct %147 %123 %123 %123 -%427 = OpCompositeConstruct %147 %124 %124 %124 -%428 = OpUGreaterThan %11 %426 %427 -%429 = OpCompositeConstruct %3 %55 %55 %55 %55 -%430 = OpCompositeConstruct %3 %16 %16 %16 %16 -%431 = OpFOrdGreaterThan %7 %429 %430 -%432 = OpSGreaterThanEqual %8 %59 %22 -%433 = OpUGreaterThanEqual %8 %123 %124 -%434 = OpFOrdGreaterThanEqual %8 %55 %16 -%435 = OpCompositeConstruct %136 %59 %59 -%436 = OpCompositeConstruct %136 %22 %22 -%437 = OpSGreaterThanEqual %106 %435 %436 -%438 = OpCompositeConstruct %147 %123 %123 %123 -%439 = OpCompositeConstruct %147 %124 %124 %124 -%440 = OpUGreaterThanEqual %11 %438 %439 -%441 = OpCompositeConstruct %3 %55 %55 %55 %55 -%442 = OpCompositeConstruct %3 %16 %16 %16 %16 -%443 = OpFOrdGreaterThanEqual %7 %441 %442 +%363 = OpFunction %2 None %103 +%362 = OpLabel +OpBranch %364 +%364 = OpLabel +%365 = OpIEqual %8 %59 %22 +%366 = OpIEqual %8 %123 %124 +%367 = OpFOrdEqual %8 %55 %16 +%368 = OpCompositeConstruct %129 %59 %59 +%369 = OpCompositeConstruct %129 %22 %22 +%370 = OpIEqual %106 %368 %369 +%371 = OpCompositeConstruct %140 %123 %123 %123 +%372 = OpCompositeConstruct %140 %124 %124 %124 +%373 = OpIEqual %11 %371 %372 +%374 = OpCompositeConstruct %3 %55 %55 %55 %55 +%375 = OpCompositeConstruct %3 %16 %16 %16 %16 +%376 = OpFOrdEqual %7 %374 %375 +%377 = OpINotEqual %8 %59 %22 +%378 = OpINotEqual %8 %123 %124 +%379 = OpFOrdNotEqual %8 %55 %16 +%380 = OpCompositeConstruct %129 %59 %59 +%381 = OpCompositeConstruct %129 %22 %22 +%382 = OpINotEqual %106 %380 %381 +%383 = OpCompositeConstruct %140 %123 %123 %123 +%384 = OpCompositeConstruct %140 %124 %124 %124 +%385 = OpINotEqual %11 %383 %384 +%386 = OpCompositeConstruct %3 %55 %55 %55 %55 +%387 = OpCompositeConstruct %3 %16 %16 %16 %16 +%388 = OpFOrdNotEqual %7 %386 %387 +%389 = OpSLessThan %8 %59 %22 +%390 = OpULessThan %8 %123 %124 +%391 = OpFOrdLessThan %8 %55 %16 +%392 = OpCompositeConstruct %129 %59 %59 +%393 = OpCompositeConstruct %129 %22 %22 +%394 = OpSLessThan %106 %392 %393 +%395 = OpCompositeConstruct %140 %123 %123 %123 +%396 = OpCompositeConstruct %140 %124 %124 %124 +%397 = OpULessThan %11 %395 %396 +%398 = OpCompositeConstruct %3 %55 %55 %55 %55 +%399 = OpCompositeConstruct %3 %16 %16 %16 %16 +%400 = OpFOrdLessThan %7 %398 %399 +%401 = OpSLessThanEqual %8 %59 %22 +%402 = OpULessThanEqual %8 %123 %124 +%403 = OpFOrdLessThanEqual %8 %55 %16 +%404 = OpCompositeConstruct %129 %59 %59 +%405 = OpCompositeConstruct %129 %22 %22 +%406 = OpSLessThanEqual %106 %404 %405 +%407 = OpCompositeConstruct %140 %123 %123 %123 +%408 = OpCompositeConstruct %140 %124 %124 %124 +%409 = OpULessThanEqual %11 %407 %408 +%410 = OpCompositeConstruct %3 %55 %55 %55 %55 +%411 = OpCompositeConstruct %3 %16 %16 %16 %16 +%412 = OpFOrdLessThanEqual %7 %410 %411 +%413 = OpSGreaterThan %8 %59 %22 +%414 = OpUGreaterThan %8 %123 %124 +%415 = OpFOrdGreaterThan %8 %55 %16 +%416 = OpCompositeConstruct %129 %59 %59 +%417 = OpCompositeConstruct %129 %22 %22 +%418 = OpSGreaterThan %106 %416 %417 +%419 = OpCompositeConstruct %140 %123 %123 %123 +%420 = OpCompositeConstruct %140 %124 %124 %124 +%421 = OpUGreaterThan %11 %419 %420 +%422 = OpCompositeConstruct %3 %55 %55 %55 %55 +%423 = OpCompositeConstruct %3 %16 %16 %16 %16 +%424 = OpFOrdGreaterThan %7 %422 %423 +%425 = OpSGreaterThanEqual %8 %59 %22 +%426 = OpUGreaterThanEqual %8 %123 %124 +%427 = OpFOrdGreaterThanEqual %8 %55 %16 +%428 = OpCompositeConstruct %129 %59 %59 +%429 = OpCompositeConstruct %129 %22 %22 +%430 = OpSGreaterThanEqual %106 %428 %429 +%431 = OpCompositeConstruct %140 %123 %123 %123 +%432 = OpCompositeConstruct %140 %124 %124 %124 +%433 = OpUGreaterThanEqual %11 %431 %432 +%434 = OpCompositeConstruct %3 %55 %55 %55 %55 +%435 = OpCompositeConstruct %3 %16 %16 %16 %16 +%436 = OpFOrdGreaterThanEqual %7 %434 %435 OpReturn OpFunctionEnd -%451 = OpFunction %2 None %103 -%450 = OpLabel -%444 = OpVariable %445 Function %446 -%447 = OpVariable %448 Function %449 -OpBranch %453 -%453 = OpLabel -OpStore %444 %22 -%454 = OpLoad %6 %444 -%455 = OpIAdd %6 %454 %22 -OpStore %444 %455 -%456 = OpLoad %6 %444 -%457 = OpISub %6 %456 %22 -OpStore %444 %457 -%458 = OpLoad %6 %444 -%459 = OpLoad %6 %444 -%460 = OpIMul %6 %459 %458 -OpStore %444 %460 -%461 = OpLoad %6 %444 -%462 = OpLoad %6 %444 -%463 = OpSDiv %6 %462 %461 -OpStore %444 %463 -%464 = OpLoad %6 %444 -%465 = OpSRem %6 %464 %22 -OpStore %444 %465 -%466 = OpLoad %6 %444 -%467 = OpBitwiseAnd %6 %466 %28 -OpStore %444 %467 -%468 = OpLoad %6 %444 -%469 = OpBitwiseOr %6 %468 %28 -OpStore %444 %469 -%470 = OpLoad %6 %444 -%471 = OpBitwiseXor %6 %470 %28 -OpStore %444 %471 -%472 = OpLoad %6 %444 -%473 = OpShiftLeftLogical %6 %472 %123 -OpStore %444 %473 -%474 = OpLoad %6 %444 -%475 = OpShiftRightArithmetic %6 %474 %124 -OpStore %444 %475 -%476 = OpLoad %6 %444 -%477 = OpIAdd %6 %476 %22 -OpStore %444 %477 -%478 = OpLoad %6 %444 +%444 = OpFunction %2 None %103 +%443 = OpLabel +%437 = OpVariable %438 Function %439 +%440 = OpVariable %441 Function %442 +OpBranch %445 +%445 = OpLabel +OpStore %437 %22 +%446 = OpLoad %6 %437 +%447 = OpIAdd %6 %446 %22 +OpStore %437 %447 +%448 = OpLoad %6 %437 +%449 = OpISub %6 %448 %22 +OpStore %437 %449 +%450 = OpLoad %6 %437 +%451 = OpLoad %6 %437 +%452 = OpIMul %6 %451 %450 +OpStore %437 %452 +%453 = OpLoad %6 %437 +%454 = OpLoad %6 %437 +%455 = OpSDiv %6 %454 %453 +OpStore %437 %455 +%456 = OpLoad %6 %437 +%457 = OpSRem %6 %456 %22 +OpStore %437 %457 +%458 = OpLoad %6 %437 +%459 = OpBitwiseAnd %6 %458 %28 +OpStore %437 %459 +%460 = OpLoad %6 %437 +%461 = OpBitwiseOr %6 %460 %28 +OpStore %437 %461 +%462 = OpLoad %6 %437 +%463 = OpBitwiseXor %6 %462 %28 +OpStore %437 %463 +%464 = OpLoad %6 %437 +%465 = OpShiftLeftLogical %6 %464 %123 +OpStore %437 %465 +%466 = OpLoad %6 %437 +%467 = OpShiftRightArithmetic %6 %466 %124 +OpStore %437 %467 +%468 = OpLoad %6 %437 +%469 = OpIAdd %6 %468 %22 +OpStore %437 %469 +%470 = OpLoad %6 %437 +%471 = OpISub %6 %470 %22 +OpStore %437 %471 +OpStore %440 %442 +%473 = OpAccessChain %472 %440 %124 +%474 = OpLoad %6 %473 +%475 = OpIAdd %6 %474 %22 +%476 = OpAccessChain %472 %440 %124 +OpStore %476 %475 +%477 = OpAccessChain %472 %440 %124 +%478 = OpLoad %6 %477 %479 = OpISub %6 %478 %22 -OpStore %444 %479 -OpStore %447 %452 -%481 = OpAccessChain %480 %447 %124 -%482 = OpLoad %6 %481 -%483 = OpIAdd %6 %482 %22 -%484 = OpAccessChain %480 %447 %124 -OpStore %484 %483 -%485 = OpAccessChain %480 %447 %124 -%486 = OpLoad %6 %485 -%487 = OpISub %6 %486 %22 -%488 = OpAccessChain %480 %447 %124 -OpStore %488 %487 +%480 = OpAccessChain %472 %440 %124 +OpStore %480 %479 OpReturn OpFunctionEnd -%490 = OpFunction %2 None %103 -%489 = OpLabel -OpBranch %499 -%499 = OpLabel -%500 = OpSNegate %6 %492 -%501 = OpSNegate %6 %493 -%502 = OpSNegate %6 %494 +%482 = OpFunction %2 None %103 +%481 = OpLabel +OpBranch %491 +%491 = OpLabel +%492 = OpSNegate %6 %484 +%493 = OpSNegate %6 %485 +%494 = OpSNegate %6 %486 +%495 = OpSNegate %6 %494 +%496 = OpSNegate %6 %487 +%497 = OpSNegate %6 %496 +%498 = OpSNegate %6 %488 +%499 = OpSNegate %6 %498 +%500 = OpSNegate %6 %499 +%501 = OpSNegate %6 %500 +%502 = OpSNegate %6 %489 %503 = OpSNegate %6 %502 -%504 = OpSNegate %6 %495 +%504 = OpSNegate %6 %503 %505 = OpSNegate %6 %504 -%506 = OpSNegate %6 %496 +%506 = OpSNegate %6 %490 %507 = OpSNegate %6 %506 %508 = OpSNegate %6 %507 %509 = OpSNegate %6 %508 -%510 = OpSNegate %6 %497 -%511 = OpSNegate %6 %510 -%512 = OpSNegate %6 %511 -%513 = OpSNegate %6 %512 -%514 = OpSNegate %6 %498 -%515 = OpSNegate %6 %514 -%516 = OpSNegate %6 %515 -%517 = OpSNegate %6 %516 OpReturn OpFunctionEnd -%519 = OpFunction %2 None %103 -%518 = OpLabel -OpBranch %520 -%520 = OpLabel -%521 = OpFunctionCall %3 %25 -%522 = OpFunctionCall %3 %54 -%523 = OpVectorShuffle %10 %17 %17 0 1 2 -%524 = OpFunctionCall %10 %94 %523 -%525 = OpFunctionCall %2 %102 -%526 = OpFunctionCall %2 %120 -%527 = OpFunctionCall %2 %321 -%528 = OpFunctionCall %2 %370 -%529 = OpFunctionCall %2 %451 +%511 = OpFunction %2 None %103 +%510 = OpLabel +OpBranch %512 +%512 = OpLabel +%513 = OpFunctionCall %3 %25 +%514 = OpFunctionCall %3 %54 +%515 = OpVectorShuffle %10 %17 %17 0 1 2 +%516 = OpFunctionCall %10 %94 %515 +%517 = OpFunctionCall %2 %102 +%518 = OpFunctionCall %2 %120 +%519 = OpFunctionCall %2 %314 +%520 = OpFunctionCall %2 %363 +%521 = OpFunctionCall %2 %444 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index 20fd9ccbf..c5b1c7c3e 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 270 +; Bound: 268 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %88 "vs_main" %78 %81 %83 %85 %87 OpEntryPoint Fragment %148 "fs_main" %139 %142 %145 %147 -OpEntryPoint Fragment %217 "fs_main_without_storage" %210 %212 %214 %216 +OpEntryPoint Fragment %215 "fs_main_without_storage" %208 %210 %212 %214 OpExecutionMode %148 OriginUpperLeft -OpExecutionMode %217 OriginUpperLeft +OpExecutionMode %215 OriginUpperLeft OpMemberName %8 0 "view_proj" OpMemberName %8 1 "num_lights" OpName %8 "Globals" @@ -50,11 +50,11 @@ OpName %142 "world_normal" OpName %145 "world_position" OpName %148 "fs_main" OpName %204 "color" -OpName %206 "i" -OpName %210 "proj_position" -OpName %212 "world_normal" -OpName %214 "world_position" -OpName %217 "fs_main_without_storage" +OpName %205 "i" +OpName %208 "proj_position" +OpName %210 "world_normal" +OpName %212 "world_position" +OpName %215 "fs_main_without_storage" OpMemberDecorate %8 0 Offset 0 OpMemberDecorate %8 0 ColMajor OpMemberDecorate %8 0 MatrixStride 16 @@ -103,10 +103,10 @@ OpDecorate %139 BuiltIn FragCoord OpDecorate %142 Location 0 OpDecorate %145 Location 1 OpDecorate %147 Location 0 -OpDecorate %210 BuiltIn FragCoord -OpDecorate %212 Location 0 -OpDecorate %214 Location 1 -OpDecorate %216 Location 0 +OpDecorate %208 BuiltIn FragCoord +OpDecorate %210 Location 0 +OpDecorate %212 Location 1 +OpDecorate %214 Location 0 %2 = OpTypeVoid %5 = OpTypeFloat 32 %4 = OpTypeVector %5 4 @@ -188,14 +188,12 @@ OpDecorate %216 Location 0 %164 = OpTypePointer Uniform %7 %174 = OpTypePointer StorageBuffer %15 %200 = OpTypePointer Uniform %4 -%205 = OpConstantNull %10 -%207 = OpConstantNull %7 -%210 = OpVariable %140 Input -%212 = OpVariable %143 Input -%214 = OpVariable %140 Input -%216 = OpVariable %84 Output -%220 = OpTypePointer Uniform %17 -%241 = OpTypePointer Uniform %15 +%208 = OpVariable %140 Input +%210 = OpVariable %143 Input +%212 = OpVariable %140 Input +%214 = OpVariable %84 Output +%218 = OpTypePointer Uniform %17 +%239 = OpTypePointer Uniform %15 %44 = OpFunction %5 None %45 %42 = OpFunctionParameter %7 %43 = OpFunctionParameter %4 @@ -351,79 +349,79 @@ OpBranch %158 OpStore %147 %203 OpReturn OpFunctionEnd -%217 = OpFunction %2 None %89 -%208 = OpLabel -%204 = OpVariable %103 Function %205 -%206 = OpVariable %135 Function %207 -%211 = OpLoad %4 %210 -%213 = OpLoad %10 %212 -%215 = OpLoad %4 %214 -%209 = OpCompositeConstruct %11 %211 %213 %215 -%218 = OpAccessChain %90 %25 %91 -%219 = OpAccessChain %93 %28 %91 -%221 = OpAccessChain %220 %34 %91 -%222 = OpLoad %19 %37 -%223 = OpLoad %20 %39 -OpBranch %224 -%224 = OpLabel -%225 = OpCompositeExtract %10 %209 1 -%226 = OpExtInst %10 %1 Normalize %225 +%215 = OpFunction %2 None %89 +%206 = OpLabel +%204 = OpVariable %103 Function %133 +%205 = OpVariable %135 Function %136 +%209 = OpLoad %4 %208 +%211 = OpLoad %10 %210 +%213 = OpLoad %4 %212 +%207 = OpCompositeConstruct %11 %209 %211 %213 +%216 = OpAccessChain %90 %25 %91 +%217 = OpAccessChain %93 %28 %91 +%219 = OpAccessChain %218 %34 %91 +%220 = OpLoad %19 %37 +%221 = OpLoad %20 %39 +OpBranch %222 +%222 = OpLabel +%223 = OpCompositeExtract %10 %207 1 +%224 = OpExtInst %10 %1 Normalize %223 OpStore %204 %24 -OpStore %206 %91 +OpStore %205 %91 +OpBranch %225 +%225 = OpLabel +OpLoopMerge %226 %228 None OpBranch %227 %227 = OpLabel -OpLoopMerge %228 %230 None -OpBranch %229 -%229 = OpLabel -%231 = OpLoad %7 %206 -%232 = OpAccessChain %164 %218 %115 %91 -%233 = OpLoad %7 %232 -%234 = OpExtInst %7 %1 UMin %233 %18 -%235 = OpULessThan %54 %231 %234 -OpSelectionMerge %236 None -OpBranchConditional %235 %236 %237 +%229 = OpLoad %7 %205 +%230 = OpAccessChain %164 %216 %115 %91 +%231 = OpLoad %7 %230 +%232 = OpExtInst %7 %1 UMin %231 %18 +%233 = OpULessThan %54 %229 %232 +OpSelectionMerge %234 None +OpBranchConditional %233 %234 %235 +%235 = OpLabel +OpBranch %226 +%234 = OpLabel +OpBranch %236 +%236 = OpLabel +%238 = OpLoad %7 %205 +%240 = OpAccessChain %239 %219 %238 +%241 = OpLoad %15 %240 +%242 = OpLoad %7 %205 +%243 = OpCompositeExtract %3 %241 0 +%244 = OpCompositeExtract %4 %207 2 +%245 = OpMatrixTimesVector %4 %243 %244 +%246 = OpFunctionCall %5 %44 %242 %245 +%247 = OpCompositeExtract %4 %241 1 +%248 = OpVectorShuffle %10 %247 %247 0 1 2 +%249 = OpCompositeExtract %4 %207 2 +%250 = OpVectorShuffle %10 %249 %249 0 1 2 +%251 = OpFSub %10 %248 %250 +%252 = OpExtInst %10 %1 Normalize %251 +%253 = OpDot %5 %224 %252 +%254 = OpExtInst %5 %1 FMax %48 %253 +%255 = OpFMul %5 %246 %254 +%256 = OpCompositeExtract %4 %241 2 +%257 = OpVectorShuffle %10 %256 %256 0 1 2 +%258 = OpVectorTimesScalar %10 %257 %255 +%259 = OpLoad %10 %204 +%260 = OpFAdd %10 %259 %258 +OpStore %204 %260 +OpBranch %237 %237 = OpLabel OpBranch %228 -%236 = OpLabel -OpBranch %238 -%238 = OpLabel -%240 = OpLoad %7 %206 -%242 = OpAccessChain %241 %221 %240 -%243 = OpLoad %15 %242 -%244 = OpLoad %7 %206 -%245 = OpCompositeExtract %3 %243 0 -%246 = OpCompositeExtract %4 %209 2 -%247 = OpMatrixTimesVector %4 %245 %246 -%248 = OpFunctionCall %5 %44 %244 %247 -%249 = OpCompositeExtract %4 %243 1 -%250 = OpVectorShuffle %10 %249 %249 0 1 2 -%251 = OpCompositeExtract %4 %209 2 -%252 = OpVectorShuffle %10 %251 %251 0 1 2 -%253 = OpFSub %10 %250 %252 -%254 = OpExtInst %10 %1 Normalize %253 -%255 = OpDot %5 %226 %254 -%256 = OpExtInst %5 %1 FMax %48 %255 -%257 = OpFMul %5 %248 %256 -%258 = OpCompositeExtract %4 %243 2 -%259 = OpVectorShuffle %10 %258 %258 0 1 2 -%260 = OpVectorTimesScalar %10 %259 %257 -%261 = OpLoad %10 %204 -%262 = OpFAdd %10 %261 %260 -OpStore %204 %262 -OpBranch %239 -%239 = OpLabel -OpBranch %230 -%230 = OpLabel -%263 = OpLoad %7 %206 -%264 = OpIAdd %7 %263 %115 -OpStore %206 %264 -OpBranch %227 %228 = OpLabel -%265 = OpLoad %10 %204 -%266 = OpCompositeConstruct %4 %265 %49 -%267 = OpAccessChain %200 %219 %115 -%268 = OpLoad %4 %267 -%269 = OpFMul %4 %266 %268 -OpStore %216 %269 +%261 = OpLoad %7 %205 +%262 = OpIAdd %7 %261 %115 +OpStore %205 %262 +OpBranch %225 +%226 = OpLabel +%263 = OpLoad %10 %204 +%264 = OpCompositeConstruct %4 %263 %49 +%265 = OpAccessChain %200 %217 %115 +%266 = OpLoad %4 %265 +%267 = OpFMul %4 %264 %266 +OpStore %214 %267 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/skybox.spvasm b/tests/out/spv/skybox.spvasm index 3c3ed8ba7..dda9382c6 100644 --- a/tests/out/spv/skybox.spvasm +++ b/tests/out/spv/skybox.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 98 +; Bound: 97 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %34 "vs_main" %27 %30 %32 -OpEntryPoint Fragment %90 "fs_main" %83 %86 %89 -OpExecutionMode %90 OriginUpperLeft +OpEntryPoint Vertex %33 "vs_main" %26 %29 %31 +OpEntryPoint Fragment %89 "fs_main" %82 %85 %88 +OpExecutionMode %89 OriginUpperLeft OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpMemberDecorate %8 0 Offset 0 @@ -24,12 +24,12 @@ OpDecorate %17 DescriptorSet 0 OpDecorate %17 Binding 1 OpDecorate %19 DescriptorSet 0 OpDecorate %19 Binding 2 -OpDecorate %27 BuiltIn VertexIndex -OpDecorate %30 BuiltIn Position -OpDecorate %32 Location 0 -OpDecorate %83 BuiltIn FragCoord -OpDecorate %86 Location 0 -OpDecorate %89 Location 0 +OpDecorate %26 BuiltIn VertexIndex +OpDecorate %29 BuiltIn Position +OpDecorate %31 Location 0 +OpDecorate %82 BuiltIn FragCoord +OpDecorate %85 Location 0 +OpDecorate %88 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -51,89 +51,88 @@ OpDecorate %89 Location 0 %19 = OpVariable %20 UniformConstant %22 = OpTypePointer Function %10 %23 = OpConstantNull %10 -%25 = OpConstantNull %10 -%28 = OpTypePointer Input %9 -%27 = OpVariable %28 Input -%31 = OpTypePointer Output %3 -%30 = OpVariable %31 Output -%33 = OpTypePointer Output %5 -%32 = OpVariable %33 Output -%35 = OpTypeFunction %2 -%36 = OpTypePointer Uniform %8 -%37 = OpConstant %9 0 -%39 = OpConstant %10 2 -%40 = OpConstant %10 1 -%41 = OpConstant %4 4.0 -%42 = OpConstant %4 1.0 -%43 = OpConstant %4 0.0 -%58 = OpTypePointer Uniform %7 -%59 = OpTypePointer Uniform %3 -%60 = OpConstant %9 1 -%67 = OpConstant %9 2 -%84 = OpTypePointer Input %3 -%83 = OpVariable %84 Input -%87 = OpTypePointer Input %5 -%86 = OpVariable %87 Input -%89 = OpVariable %31 Output -%95 = OpTypeSampledImage %12 -%34 = OpFunction %2 None %35 -%26 = OpLabel +%27 = OpTypePointer Input %9 +%26 = OpVariable %27 Input +%30 = OpTypePointer Output %3 +%29 = OpVariable %30 Output +%32 = OpTypePointer Output %5 +%31 = OpVariable %32 Output +%34 = OpTypeFunction %2 +%35 = OpTypePointer Uniform %8 +%36 = OpConstant %9 0 +%38 = OpConstant %10 2 +%39 = OpConstant %10 1 +%40 = OpConstant %4 4.0 +%41 = OpConstant %4 1.0 +%42 = OpConstant %4 0.0 +%57 = OpTypePointer Uniform %7 +%58 = OpTypePointer Uniform %3 +%59 = OpConstant %9 1 +%66 = OpConstant %9 2 +%83 = OpTypePointer Input %3 +%82 = OpVariable %83 Input +%86 = OpTypePointer Input %5 +%85 = OpVariable %86 Input +%88 = OpVariable %30 Output +%94 = OpTypeSampledImage %12 +%33 = OpFunction %2 None %34 +%25 = OpLabel %21 = OpVariable %22 Function %23 -%24 = OpVariable %22 Function %25 -%29 = OpLoad %9 %27 -%38 = OpAccessChain %36 %14 %37 -OpBranch %44 -%44 = OpLabel -%45 = OpBitcast %10 %29 -%46 = OpSDiv %10 %45 %39 -OpStore %21 %46 -%47 = OpBitcast %10 %29 -%48 = OpBitwiseAnd %10 %47 %40 -OpStore %24 %48 -%49 = OpLoad %10 %21 -%50 = OpConvertSToF %4 %49 -%51 = OpFMul %4 %50 %41 -%52 = OpFSub %4 %51 %42 -%53 = OpLoad %10 %24 -%54 = OpConvertSToF %4 %53 -%55 = OpFMul %4 %54 %41 -%56 = OpFSub %4 %55 %42 -%57 = OpCompositeConstruct %3 %52 %56 %43 %42 -%61 = OpAccessChain %59 %38 %60 %37 -%62 = OpLoad %3 %61 -%63 = OpVectorShuffle %5 %62 %62 0 1 2 -%64 = OpAccessChain %59 %38 %60 %60 -%65 = OpLoad %3 %64 -%66 = OpVectorShuffle %5 %65 %65 0 1 2 -%68 = OpAccessChain %59 %38 %60 %67 -%69 = OpLoad %3 %68 -%70 = OpVectorShuffle %5 %69 %69 0 1 2 -%71 = OpCompositeConstruct %11 %63 %66 %70 -%72 = OpTranspose %11 %71 -%73 = OpAccessChain %58 %38 %37 -%74 = OpLoad %7 %73 -%75 = OpMatrixTimesVector %3 %74 %57 -%76 = OpVectorShuffle %5 %75 %75 0 1 2 -%77 = OpMatrixTimesVector %5 %72 %76 -%78 = OpCompositeConstruct %6 %57 %77 -%79 = OpCompositeExtract %3 %78 0 -OpStore %30 %79 -%80 = OpCompositeExtract %5 %78 1 -OpStore %32 %80 +%24 = OpVariable %22 Function %23 +%28 = OpLoad %9 %26 +%37 = OpAccessChain %35 %14 %36 +OpBranch %43 +%43 = OpLabel +%44 = OpBitcast %10 %28 +%45 = OpSDiv %10 %44 %38 +OpStore %21 %45 +%46 = OpBitcast %10 %28 +%47 = OpBitwiseAnd %10 %46 %39 +OpStore %24 %47 +%48 = OpLoad %10 %21 +%49 = OpConvertSToF %4 %48 +%50 = OpFMul %4 %49 %40 +%51 = OpFSub %4 %50 %41 +%52 = OpLoad %10 %24 +%53 = OpConvertSToF %4 %52 +%54 = OpFMul %4 %53 %40 +%55 = OpFSub %4 %54 %41 +%56 = OpCompositeConstruct %3 %51 %55 %42 %41 +%60 = OpAccessChain %58 %37 %59 %36 +%61 = OpLoad %3 %60 +%62 = OpVectorShuffle %5 %61 %61 0 1 2 +%63 = OpAccessChain %58 %37 %59 %59 +%64 = OpLoad %3 %63 +%65 = OpVectorShuffle %5 %64 %64 0 1 2 +%67 = OpAccessChain %58 %37 %59 %66 +%68 = OpLoad %3 %67 +%69 = OpVectorShuffle %5 %68 %68 0 1 2 +%70 = OpCompositeConstruct %11 %62 %65 %69 +%71 = OpTranspose %11 %70 +%72 = OpAccessChain %57 %37 %36 +%73 = OpLoad %7 %72 +%74 = OpMatrixTimesVector %3 %73 %56 +%75 = OpVectorShuffle %5 %74 %74 0 1 2 +%76 = OpMatrixTimesVector %5 %71 %75 +%77 = OpCompositeConstruct %6 %56 %76 +%78 = OpCompositeExtract %3 %77 0 +OpStore %29 %78 +%79 = OpCompositeExtract %5 %77 1 +OpStore %31 %79 OpReturn OpFunctionEnd -%90 = OpFunction %2 None %35 -%81 = OpLabel -%85 = OpLoad %3 %83 -%88 = OpLoad %5 %86 -%82 = OpCompositeConstruct %6 %85 %88 -%91 = OpLoad %12 %17 -%92 = OpLoad %13 %19 -OpBranch %93 -%93 = OpLabel -%94 = OpCompositeExtract %5 %82 1 -%96 = OpSampledImage %95 %91 %92 -%97 = OpImageSampleImplicitLod %3 %96 %94 -OpStore %89 %97 +%89 = OpFunction %2 None %34 +%80 = OpLabel +%84 = OpLoad %3 %82 +%87 = OpLoad %5 %85 +%81 = OpCompositeConstruct %6 %84 %87 +%90 = OpLoad %12 %17 +%91 = OpLoad %13 %19 +OpBranch %92 +%92 = OpLabel +%93 = OpCompositeExtract %5 %81 1 +%95 = OpSampledImage %94 %90 %91 +%96 = OpImageSampleImplicitLod %3 %95 %93 +OpStore %88 %96 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/standard.spvasm b/tests/out/spv/standard.spvasm index 518be0a22..6d9445808 100644 --- a/tests/out/spv/standard.spvasm +++ b/tests/out/spv/standard.spvasm @@ -1,58 +1,56 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 35 +; Bound: 33 OpCapability Shader OpCapability DerivativeControl %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %18 "derivatives" %13 %16 -OpExecutionMode %18 OriginUpperLeft -OpDecorate %13 BuiltIn FragCoord -OpDecorate %16 Location 0 +OpEntryPoint Fragment %16 "derivatives" %11 %14 +OpExecutionMode %16 OriginUpperLeft +OpDecorate %11 BuiltIn FragCoord +OpDecorate %14 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 %6 = OpTypePointer Function %3 %7 = OpConstantNull %3 -%9 = OpConstantNull %3 -%11 = OpConstantNull %3 -%14 = OpTypePointer Input %3 -%13 = OpVariable %14 Input -%17 = OpTypePointer Output %3 -%16 = OpVariable %17 Output -%19 = OpTypeFunction %2 -%18 = OpFunction %2 None %19 -%12 = OpLabel +%12 = OpTypePointer Input %3 +%11 = OpVariable %12 Input +%15 = OpTypePointer Output %3 +%14 = OpVariable %15 Output +%17 = OpTypeFunction %2 +%16 = OpFunction %2 None %17 +%10 = OpLabel %5 = OpVariable %6 Function %7 -%8 = OpVariable %6 Function %9 -%10 = OpVariable %6 Function %11 -%15 = OpLoad %3 %13 -OpBranch %20 -%20 = OpLabel -%21 = OpDPdxCoarse %3 %15 -OpStore %5 %21 -%22 = OpDPdyCoarse %3 %15 -OpStore %8 %22 -%23 = OpFwidthCoarse %3 %15 -OpStore %10 %23 -%24 = OpDPdxFine %3 %15 -OpStore %5 %24 -%25 = OpDPdyFine %3 %15 -OpStore %8 %25 -%26 = OpFwidthFine %3 %15 -OpStore %10 %26 -%27 = OpDPdx %3 %15 -OpStore %5 %27 -%28 = OpDPdy %3 %15 -OpStore %8 %28 -%29 = OpFwidth %3 %15 -OpStore %10 %29 -%30 = OpLoad %3 %5 -%31 = OpLoad %3 %8 -%32 = OpFAdd %3 %30 %31 -%33 = OpLoad %3 %10 -%34 = OpFMul %3 %32 %33 -OpStore %16 %34 +%8 = OpVariable %6 Function %7 +%9 = OpVariable %6 Function %7 +%13 = OpLoad %3 %11 +OpBranch %18 +%18 = OpLabel +%19 = OpDPdxCoarse %3 %13 +OpStore %5 %19 +%20 = OpDPdyCoarse %3 %13 +OpStore %8 %20 +%21 = OpFwidthCoarse %3 %13 +OpStore %9 %21 +%22 = OpDPdxFine %3 %13 +OpStore %5 %22 +%23 = OpDPdyFine %3 %13 +OpStore %8 %23 +%24 = OpFwidthFine %3 %13 +OpStore %9 %24 +%25 = OpDPdx %3 %13 +OpStore %5 %25 +%26 = OpDPdy %3 %13 +OpStore %8 %26 +%27 = OpFwidth %3 %13 +OpStore %9 %27 +%28 = OpLoad %3 %5 +%29 = OpLoad %3 %8 +%30 = OpFAdd %3 %28 %29 +%31 = OpLoad %3 %9 +%32 = OpFMul %3 %30 %31 +OpStore %14 %32 OpReturn OpFunctionEnd \ No newline at end of file From 543cae17a3f52a7801bb2b285062f67b29592a06 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 1 Aug 2023 15:39:01 -0700 Subject: [PATCH 2050/2212] Bump MSRV to 1.65. --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 6 ++++++ Cargo.toml | 2 +- README.md | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ce951216b..ff1af783d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,7 +5,7 @@ env: CARGO_INCREMENTAL: false CARGO_TERM_COLOR: always RUST_BACKTRACE: full - MSRV: 1.63 + MSRV: 1.65 jobs: check-msrv: diff --git a/CHANGELOG.md b/CHANGELOG.md index fac0fd78e..c6dd01339 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Change Log +## Unreleased + +#### GENERAL + +- Bump MSRV to 1.65 ([#2420](https://github.com/gfx-rs/naga/pull/2420)) **@jimblandy** + ## v0.13 (2023-07-21) #### GENERAL diff --git a/Cargo.toml b/Cargo.toml index 65b806720..efaf0548d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] resolver = "2" -rust-version = "1.63" +rust-version = "1.65" [package.metadata.docs.rs] all-features = true diff --git a/README.md b/README.md index c9f22e502..04ed84ab5 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Crates.io](https://img.shields.io/crates/v/naga.svg?label=naga)](https://crates.io/crates/naga) [![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga) [![Build Status](https://github.com/gfx-rs/naga/workflows/pipeline/badge.svg)](https://github.com/gfx-rs/naga/actions) -![MSRV](https://img.shields.io/badge/rustc-1.63+-blue.svg) +![MSRV](https://img.shields.io/badge/rustc-1.65+-blue.svg) [![codecov.io](https://codecov.io/gh/gfx-rs/naga/branch/master/graph/badge.svg?token=9VOKYO8BM2)](https://codecov.io/gh/gfx-rs/naga) The shader translation library for the needs of [wgpu](https://github.com/gfx-rs/wgpu). From f92340cd0338a9e3c33aaea135957872c9df66b4 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 4 Aug 2023 14:13:53 +0200 Subject: [PATCH 2051/2212] validate binding_array variable address space --- src/valid/interface.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 58ae82ce6..2e54df247 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -409,7 +409,12 @@ impl super::Validator { // A binding array is (mostly) supposed to behave the same as a // series of individually bound resources, so we can (mostly) // validate a `binding_array` as if it were just a plain `T`. - crate::TypeInner::BindingArray { base, .. } => base, + crate::TypeInner::BindingArray { base, .. } => match var.space { + crate::AddressSpace::Storage { .. } + | crate::AddressSpace::Uniform + | crate::AddressSpace::Handle => base, + _ => return Err(GlobalVariableError::InvalidUsage(var.space)), + }, _ => var.ty, }; let type_info = &self.types[inner_ty.index()]; From e51b4afa1e5afc03af6e991f67f2ea503d29a4a4 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 4 Aug 2023 14:45:48 +0200 Subject: [PATCH 2052/2212] clarify binding array of handles comment --- src/back/spv/block.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 74d8cdfef..6c455bbff 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -271,6 +271,7 @@ impl<'w> BlockContext<'w> { crate::TypeInner::Vector { .. } => { self.write_vector_access(expr_handle, base, index, block)? } + // Only binding arrays in the Handle address space will take this path (due to `is_intermediate`) crate::TypeInner::BindingArray { base: binding_type, .. } => { @@ -347,6 +348,7 @@ impl<'w> BlockContext<'w> { )); id } + // Only binding arrays in the Handle address space will take this path (due to `is_intermediate`) crate::TypeInner::BindingArray { base: binding_type, .. } => { @@ -1426,8 +1428,8 @@ impl<'w> BlockContext<'w> { ) -> Result { let result_lookup_ty = match self.fun_info[expr_handle].ty { TypeResolution::Handle(ty_handle) => match return_type_override { - // We use the return type override as a special case for binding arrays as the OpAccessChain - // needs to return a pointer, but indexing into a binding array just gives you the type of + // We use the return type override as a special case for handle binding arrays as the OpAccessChain + // needs to return a pointer, but indexing into a handle binding array just gives you the type of // the binding in the IR. Some(ty) => ty, None => LookupType::Handle(ty_handle), From c3e35df576af8cdd345875b8af1ab541c43defd7 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 4 Aug 2023 15:26:14 +0200 Subject: [PATCH 2053/2212] [spv-out] decorate the result of the `OpLoad` with `NonUniform` (not the access chain) when loading images/samplers (resources in the Handle address space) --- src/back/spv/block.rs | 31 ++++++++++++++++---- tests/out/spv/binding-arrays.spvasm | 44 ++++++++++++++--------------- 2 files changed, 47 insertions(+), 28 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 6c455bbff..11841bc52 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -309,6 +309,14 @@ impl<'w> BlockContext<'w> { None, )); + // Subsequent image operations require the image/sampler to be decorated as NonUniform + // if the image/sampler binding array was accessed with a non-uniform index + // see VUID-RuntimeSpirv-NonUniform-06274 + if self.fun_info[index].uniformity.non_uniform_result.is_some() { + self.writer + .decorate_non_uniform_binding_array_access(load_id)?; + } + load_id } ref other => { @@ -1456,12 +1464,20 @@ impl<'w> BlockContext<'w> { if let crate::Expression::GlobalVariable(var_handle) = self.ir_function.expressions[base] { - let gvar = &self.ir_module.global_variables[var_handle]; - if let crate::TypeInner::BindingArray { .. } = - self.ir_module.types[gvar.ty].inner - { - is_non_uniform_binding_array |= - self.fun_info[index].uniformity.non_uniform_result.is_some(); + let gvar: &crate::GlobalVariable = + &self.ir_module.global_variables[var_handle]; + match gvar.space { + crate::AddressSpace::Storage { .. } | crate::AddressSpace::Uniform => { + if let crate::TypeInner::BindingArray { .. } = + self.ir_module.types[gvar.ty].inner + { + is_non_uniform_binding_array = self.fun_info[index] + .uniformity + .non_uniform_result + .is_some(); + } + } + _ => {} } } @@ -1545,6 +1561,9 @@ impl<'w> BlockContext<'w> { }; (pointer_id, expr_pointer) }; + // Subsequent load, store and atomic operations require the pointer to be decorated as NonUniform + // if the buffer binding array was accessed with a non-uniform index + // see VUID-RuntimeSpirv-NonUniform-06274 if is_non_uniform_binding_array { self.writer .decorate_non_uniform_binding_array_access(pointer_id)?; diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index cd56fb496..090173100 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -35,28 +35,28 @@ OpMemberDecorate %47 0 Offset 0 OpDecorate %63 Location 0 OpDecorate %63 Flat OpDecorate %66 Location 0 -OpDecorate %95 NonUniform -OpDecorate %118 NonUniform -OpDecorate %120 NonUniform -OpDecorate %145 NonUniform -OpDecorate %147 NonUniform -OpDecorate %183 NonUniform -OpDecorate %211 NonUniform -OpDecorate %227 NonUniform -OpDecorate %243 NonUniform -OpDecorate %264 NonUniform -OpDecorate %266 NonUniform -OpDecorate %288 NonUniform -OpDecorate %290 NonUniform -OpDecorate %312 NonUniform -OpDecorate %314 NonUniform -OpDecorate %336 NonUniform -OpDecorate %338 NonUniform -OpDecorate %360 NonUniform -OpDecorate %362 NonUniform -OpDecorate %384 NonUniform -OpDecorate %386 NonUniform -OpDecorate %409 NonUniform +OpDecorate %96 NonUniform +OpDecorate %119 NonUniform +OpDecorate %121 NonUniform +OpDecorate %146 NonUniform +OpDecorate %148 NonUniform +OpDecorate %184 NonUniform +OpDecorate %212 NonUniform +OpDecorate %228 NonUniform +OpDecorate %244 NonUniform +OpDecorate %265 NonUniform +OpDecorate %267 NonUniform +OpDecorate %289 NonUniform +OpDecorate %291 NonUniform +OpDecorate %313 NonUniform +OpDecorate %315 NonUniform +OpDecorate %337 NonUniform +OpDecorate %339 NonUniform +OpDecorate %361 NonUniform +OpDecorate %363 NonUniform +OpDecorate %385 NonUniform +OpDecorate %387 NonUniform +OpDecorate %410 NonUniform %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeStruct %3 From 061d499ddb4107e425a6e066a101e8c8a339c8fc Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 4 Aug 2023 15:29:15 +0200 Subject: [PATCH 2054/2212] [spv-out] rename `get_image_id` to `get_handle_id` --- src/back/spv/image.rs | 12 ++++++------ src/back/spv/ray.rs | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index bc7846922..b4d2fb9e1 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -379,7 +379,7 @@ impl<'w> BlockContext<'w> { }) } - pub(super) fn get_image_id(&mut self, expr_handle: Handle) -> Word { + pub(super) fn get_handle_id(&mut self, expr_handle: Handle) -> Word { let id = match self.ir_function.expressions[expr_handle] { crate::Expression::GlobalVariable(handle) => { self.writer.global_variables[handle.index()].handle_id @@ -745,7 +745,7 @@ impl<'w> BlockContext<'w> { sample: Option>, block: &mut Block, ) -> Result { - let image_id = self.get_image_id(image); + let image_id = self.get_handle_id(image); let image_type = self.fun_info[image].ty.inner_with(&self.ir_module.types); let image_class = match *image_type { crate::TypeInner::Image { class, .. } => class, @@ -830,7 +830,7 @@ impl<'w> BlockContext<'w> { ) -> Result { use super::instructions::SampleLod; // image - let image_id = self.get_image_id(image); + let image_id = self.get_handle_id(image); let image_type = self.fun_info[image].ty.handle().unwrap(); // SPIR-V doesn't know about our `Depth` class, and it returns // `vec4`, so we need to grab the first component out of it. @@ -857,7 +857,7 @@ impl<'w> BlockContext<'w> { let sampled_image_type_id = self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id })); - let sampler_id = self.get_image_id(sampler); + let sampler_id = self.get_handle_id(sampler); let coordinates_id = self .write_image_coordinates(coordinate, array_index, block)? .value_id; @@ -1013,7 +1013,7 @@ impl<'w> BlockContext<'w> { ) -> Result { use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq}; - let image_id = self.get_image_id(image); + let image_id = self.get_handle_id(image); let image_type = self.fun_info[image].ty.handle().unwrap(); let (dim, arrayed, class) = match self.ir_module.types[image_type].inner { crate::TypeInner::Image { @@ -1164,7 +1164,7 @@ impl<'w> BlockContext<'w> { value: Handle, block: &mut Block, ) -> Result<(), Error> { - let image_id = self.get_image_id(image); + let image_id = self.get_handle_id(image); let coordinates = self.write_image_coordinates(coordinate, array_index, block)?; let value_id = self.cached[value]; diff --git a/src/back/spv/ray.rs b/src/back/spv/ray.rs index 0b53b9cc5..ed61129f9 100644 --- a/src/back/spv/ray.rs +++ b/src/back/spv/ray.rs @@ -20,7 +20,7 @@ impl<'w> BlockContext<'w> { } => { //Note: composite extract indices and types must match `generate_ray_desc_type` let desc_id = self.cached[descriptor]; - let acc_struct_id = self.get_image_id(acceleration_structure); + let acc_struct_id = self.get_handle_id(acceleration_structure); let width = 4; let flag_type_id = self.get_type_id(LookupType::Local(LocalType::Value { From 24afaa5cfdf56c065af9db9845bfcf23ed192c34 Mon Sep 17 00:00:00 2001 From: daxpedda Date: Fri, 11 Aug 2023 15:32:49 +0200 Subject: [PATCH 2055/2212] Properly test `-Zminimal-versions` (#2429) * Properly test `-Zminimal-versions` * Fix minimal version requirement --- .github/workflows/ci.yml | 2 +- Cargo.toml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ff1af783d..ef2c49712 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: tool: cargo-hack # -Z avoid-dev-deps doesn't work - - run: cargo +nightly hack generate-lockfile --remove-dev-deps -Z minimal-versions --offline + - run: cargo +nightly hack generate-lockfile --remove-dev-deps -Z minimal-versions - name: Test all features run: cargo +$MSRV clippy --all-features --workspace -- -D warnings diff --git a/Cargo.toml b/Cargo.toml index efaf0548d..8dcda7d25 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,8 +44,8 @@ name = "criterion" harness = false [dependencies] -arbitrary = { version = "1.0.2", features = ["derive"], optional = true } -bitflags = "2" +arbitrary = { version = "1.3", features = ["derive"], optional = true } +bitflags = "2.2" bit-set = "0.5" termcolor = { version = "1.0.4", optional = true } # remove termcolor dep when updating to the next version of codespan-reporting From bd74b11b4c2616c6883266f5c46ef5981dc8b945 Mon Sep 17 00:00:00 2001 From: daxpedda Date: Fri, 11 Aug 2023 16:28:28 +0200 Subject: [PATCH 2056/2212] Bump `indexmap` to v2 (#2426) --- Cargo.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8dcda7d25..1929bda82 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,8 +28,8 @@ dot-out = [] glsl-in = ["pp-rs"] glsl-out = [] msl-out = [] -serialize = ["serde", "bitflags/serde", "indexmap/serde-1"] -deserialize = ["serde", "bitflags/serde", "indexmap/serde-1"] +serialize = ["serde", "bitflags/serde", "indexmap/serde"] +deserialize = ["serde", "bitflags/serde", "indexmap/serde"] arbitrary = ["dep:arbitrary", "bitflags/arbitrary", "indexmap/arbitrary"] spv-in = ["petgraph", "spirv"] spv-out = ["spirv"] @@ -53,7 +53,7 @@ termcolor = { version = "1.0.4", optional = true } # https://github.com/brendanzab/codespan/commit/e99c867339a877731437e7ee6a903a3d03b5439e codespan-reporting = { version = "0.11.0", optional = true } rustc-hash = "1.1.0" -indexmap = { version = "1.9.2", features = ["std"] } +indexmap = { version = "2", features = ["std"] } log = "0.4" num-traits = "0.2" spirv = { version = "0.2", optional = true } From 30afa5bd1f64e607c11421fbf2d3604df261561c Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Fri, 11 Aug 2023 16:35:41 +0200 Subject: [PATCH 2057/2212] [wgsl-in] Fix error message for invalid texture{Load,Store}() on 2d_array (#2432) Fixes https://github.com/gfx-rs/naga/issues/2431 --- src/front/wgsl/lower/mod.rs | 10 ++++++++-- src/front/wgsl/tests.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index cf52d6ce8..84c0d993e 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1937,7 +1937,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let (_, arrayed) = ctx.image_data(image, image_span)?; let array_index = arrayed - .then(|| self.expression(args.next()?, ctx.reborrow())) + .then(|| { + args.min_args += 1; + self.expression(args.next()?, ctx.reborrow()) + }) .transpose()?; let value = self.expression(args.next()?, ctx.reborrow())?; @@ -1968,7 +1971,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let (class, arrayed) = ctx.image_data(image, image_span)?; let array_index = arrayed - .then(|| self.expression(args.next()?, ctx.reborrow())) + .then(|| { + args.min_args += 1; + self.expression(args.next()?, ctx.reborrow()) + }) .transpose()?; let level = class diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 31b589070..3aec0acf2 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -481,3 +481,31 @@ fn parse_alias() { ) .unwrap(); } + +#[test] +fn parse_texture_load_store_expecting_four_args() { + for (func, texture) in [ + ( + "textureStore", + "texture_storage_2d_array", + ), + ("textureLoad", "texture_2d_array"), + ] { + let error = parse_str(&format!( + " + @group(0) @binding(0) var tex_los_res: {texture}; + @compute + @workgroup_size(1) + fn main(@builtin(global_invocation_id) id: vec3) {{ + var color = vec4(1, 1, 1, 1); + {func}(tex_los_res, id, color); + }} + " + )) + .unwrap_err(); + assert_eq!( + error.message(), + "wrong number of arguments: expected 4, found 3" + ); + } +} From 7a19f3af909202c7eafd36633b5584bfbb353ecb Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Sun, 13 Aug 2023 17:52:10 +0200 Subject: [PATCH 2058/2212] [wgsl-in] Fail on repeated attributes (#2428) * [wgsl-in] Fail on repeated attributes Fixes #2425. * [wgsl-in] Use ParsedAttribute to keep track of parsed attributes --- src/front/wgsl/error.rs | 6 ++ src/front/wgsl/parse/mod.rs | 109 ++++++++++++++++++++++-------------- src/front/wgsl/tests.rs | 39 +++++++++++++ 3 files changed, 113 insertions(+), 41 deletions(-) diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index 701eca992..a3355f861 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -168,6 +168,7 @@ pub enum Error<'a> { InvalidIdentifierUnderscore(Span), ReservedIdentifierPrefix(Span), UnknownAddressSpace(Span), + RepeatedAttribute(Span), UnknownAttribute(Span), UnknownBuiltin(Span), UnknownAccess(Span), @@ -430,6 +431,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span, "unknown address space".into())], notes: vec![], }, + Error::RepeatedAttribute(bad_span) => ParseError { + message: format!("repeated attribute: '{}'", &source[bad_span]), + labels: vec![(bad_span, "repated attribute".into())], + notes: vec![], + }, Error::UnknownAttribute(bad_span) => ParseError { message: format!("unknown attribute: '{}'", &source[bad_span]), labels: vec![(bad_span, "unknown attribute".into())], diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index c13ee5277..b6798027e 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -120,13 +120,33 @@ enum Rule { GeneralExpr, } +struct ParsedAttribute { + value: Option, +} + +impl Default for ParsedAttribute { + fn default() -> Self { + Self { value: None } + } +} + +impl ParsedAttribute { + fn set(&mut self, value: T, name_span: Span) -> Result<(), Error<'static>> { + if self.value.is_some() { + return Err(Error::RepeatedAttribute(name_span)); + } + self.value = Some(value); + Ok(()) + } +} + #[derive(Default)] struct BindingParser { - location: Option, - built_in: Option, - interpolation: Option, - sampling: Option, - invariant: bool, + location: ParsedAttribute, + built_in: ParsedAttribute, + interpolation: ParsedAttribute, + sampling: ParsedAttribute, + invariant: ParsedAttribute, } impl BindingParser { @@ -139,38 +159,44 @@ impl BindingParser { match name { "location" => { lexer.expect(Token::Paren('('))?; - self.location = Some(Parser::non_negative_i32_literal(lexer)?); + self.location + .set(Parser::non_negative_i32_literal(lexer)?, name_span)?; lexer.expect(Token::Paren(')'))?; } "builtin" => { lexer.expect(Token::Paren('('))?; let (raw, span) = lexer.next_ident_with_span()?; - self.built_in = Some(conv::map_built_in(raw, span)?); + self.built_in + .set(conv::map_built_in(raw, span)?, name_span)?; lexer.expect(Token::Paren(')'))?; } "interpolate" => { lexer.expect(Token::Paren('('))?; let (raw, span) = lexer.next_ident_with_span()?; - self.interpolation = Some(conv::map_interpolation(raw, span)?); + self.interpolation + .set(conv::map_interpolation(raw, span)?, name_span)?; if lexer.skip(Token::Separator(',')) { let (raw, span) = lexer.next_ident_with_span()?; - self.sampling = Some(conv::map_sampling(raw, span)?); + self.sampling + .set(conv::map_sampling(raw, span)?, name_span)?; } lexer.expect(Token::Paren(')'))?; } - "invariant" => self.invariant = true, + "invariant" => { + self.invariant.set(true, name_span)?; + } _ => return Err(Error::UnknownAttribute(name_span)), } Ok(()) } - const fn finish<'a>(self, span: Span) -> Result, Error<'a>> { + fn finish<'a>(self, span: Span) -> Result, Error<'a>> { match ( - self.location, - self.built_in, - self.interpolation, - self.sampling, - self.invariant, + self.location.value, + self.built_in.value, + self.interpolation.value, + self.sampling.value, + self.invariant.value.unwrap_or_default(), ) { (None, None, None, None, false) => Ok(None), (Some(location), None, interpolation, sampling, false) => { @@ -990,22 +1016,22 @@ impl Parser { ExpectedToken::Token(Token::Separator(',')), )); } - let (mut size, mut align) = (None, None); + let (mut size, mut align) = (ParsedAttribute::default(), ParsedAttribute::default()); self.push_rule_span(Rule::Attribute, lexer); let mut bind_parser = BindingParser::default(); while lexer.skip(Token::Attribute) { match lexer.next_ident_with_span()? { - ("size", _) => { + ("size", name_span) => { lexer.expect(Token::Paren('('))?; let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; lexer.expect(Token::Paren(')'))?; - size = Some((value, span)); + size.set((value, span), name_span)?; } - ("align", _) => { + ("align", name_span) => { lexer.expect(Token::Paren('('))?; let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; lexer.expect(Token::Paren(')'))?; - align = Some((value, span)); + align.set((value, span), name_span)?; } (word, word_span) => bind_parser.parse(lexer, word, word_span)?, } @@ -1023,8 +1049,8 @@ impl Parser { name, ty, binding, - size, - align, + size: size.value, + align: align.value, }); } @@ -2131,32 +2157,33 @@ impl Parser { ) -> Result<(), Error<'a>> { // read attributes let mut binding = None; - let mut stage = None; + let mut stage = ParsedAttribute::default(); let mut workgroup_size = [0u32; 3]; - let mut early_depth_test = None; - let (mut bind_index, mut bind_group) = (None, None); + let mut early_depth_test = ParsedAttribute::default(); + let (mut bind_index, mut bind_group) = + (ParsedAttribute::default(), ParsedAttribute::default()); self.push_rule_span(Rule::Attribute, lexer); while lexer.skip(Token::Attribute) { match lexer.next_ident_with_span()? { - ("binding", _) => { + ("binding", name_span) => { lexer.expect(Token::Paren('('))?; - bind_index = Some(Self::non_negative_i32_literal(lexer)?); + bind_index.set(Self::non_negative_i32_literal(lexer)?, name_span)?; lexer.expect(Token::Paren(')'))?; } - ("group", _) => { + ("group", name_span) => { lexer.expect(Token::Paren('('))?; - bind_group = Some(Self::non_negative_i32_literal(lexer)?); + bind_group.set(Self::non_negative_i32_literal(lexer)?, name_span)?; lexer.expect(Token::Paren(')'))?; } - ("vertex", _) => { - stage = Some(crate::ShaderStage::Vertex); + ("vertex", name_span) => { + stage.set(crate::ShaderStage::Vertex, name_span)?; } - ("fragment", _) => { - stage = Some(crate::ShaderStage::Fragment); + ("fragment", name_span) => { + stage.set(crate::ShaderStage::Fragment, name_span)?; } - ("compute", _) => { - stage = Some(crate::ShaderStage::Compute); + ("compute", name_span) => { + stage.set(crate::ShaderStage::Compute, name_span)?; } ("workgroup_size", _) => { lexer.expect(Token::Paren('('))?; @@ -2175,7 +2202,7 @@ impl Parser { } } } - ("early_depth_test", _) => { + ("early_depth_test", name_span) => { let conservative = if lexer.skip(Token::Paren('(')) { let (ident, ident_span) = lexer.next_ident_with_span()?; let value = conv::map_conservative_depth(ident, ident_span)?; @@ -2184,14 +2211,14 @@ impl Parser { } else { None }; - early_depth_test = Some(crate::EarlyDepthTest { conservative }); + early_depth_test.set(crate::EarlyDepthTest { conservative }, name_span)?; } (_, word_span) => return Err(Error::UnknownAttribute(word_span)), } } let attrib_span = self.pop_rule_span(lexer); - match (bind_group, bind_index) { + match (bind_group.value, bind_index.value) { (Some(group), Some(index)) => { binding = Some(crate::ResourceBinding { group, @@ -2254,9 +2281,9 @@ impl Parser { (Token::Word("fn"), _) => { let function = self.function_decl(lexer, out, &mut dependencies)?; Some(ast::GlobalDeclKind::Fn(ast::Function { - entry_point: stage.map(|stage| ast::EntryPoint { + entry_point: stage.value.map(|stage| ast::EntryPoint { stage, - early_depth_test, + early_depth_test: early_depth_test.value, workgroup_size, }), ..function diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 3aec0acf2..80ea26143 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -509,3 +509,42 @@ fn parse_texture_load_store_expecting_four_args() { ); } } + +#[test] +fn parse_repeated_attributes() { + use crate::{ + front::wgsl::{error::Error, Frontend}, + Span, + }; + + let template_vs = "@vertex fn vs() -> __REPLACE__ vec4 { return vec4(0.0); }"; + let template_struct = "struct A { __REPLACE__ data: vec3 }"; + let template_resource = "__REPLACE__ var tex_los_res: texture_2d_array;"; + let template_stage = "__REPLACE__ fn vs() -> vec4 { return vec4(0.0); }"; + for (attribute, template) in [ + ("align(16)", template_struct), + ("binding(0)", template_resource), + ("builtin(position)", template_vs), + ("compute", template_stage), + ("fragment", template_stage), + ("group(0)", template_resource), + ("interpolate(flat)", template_vs), + ("invariant", template_vs), + ("location(0)", template_vs), + ("size(16)", template_struct), + ("vertex", template_stage), + ("early_depth_test(less_equal)", template_resource), + ] { + let shader = template.replace("__REPLACE__", &format!("@{attribute} @{attribute}")); + let name_length = attribute.rfind('(').unwrap_or(attribute.len()) as u32; + let span_start = shader.rfind(attribute).unwrap() as u32; + let span_end = span_start + name_length; + let expected_span = Span::new(span_start, span_end); + + let result = Frontend::new().inner(&shader); + assert!(matches!( + result.unwrap_err(), + Error::RepeatedAttribute(span) if span == expected_span + )); + } +} From f6e99a4603270b668eed35ef7508522acd486043 Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Thu, 17 Aug 2023 13:20:10 +0200 Subject: [PATCH 2059/2212] [wgsl-in] Handle repeated or missing @workgroup_size (#2435) --- src/front/wgsl/error.rs | 11 ++++++++++- src/front/wgsl/lower/mod.rs | 2 +- src/front/wgsl/parse/ast.rs | 2 +- src/front/wgsl/parse/mod.rs | 30 ++++++++++++++++++++---------- src/front/wgsl/tests.rs | 16 ++++++++++++++++ 5 files changed, 48 insertions(+), 13 deletions(-) diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index a3355f861..7ce795fa0 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -242,6 +242,7 @@ pub enum Error<'a> { Other, ExpectedArraySize(Span), NonPositiveArrayLength(Span), + MissingWorkgroupSize(Span), } impl<'a> Error<'a> { @@ -433,7 +434,7 @@ impl<'a> Error<'a> { }, Error::RepeatedAttribute(bad_span) => ParseError { message: format!("repeated attribute: '{}'", &source[bad_span]), - labels: vec![(bad_span, "repated attribute".into())], + labels: vec![(bad_span, "repeated attribute".into())], notes: vec![], }, Error::UnknownAttribute(bad_span) => ParseError { @@ -704,6 +705,14 @@ impl<'a> Error<'a> { labels: vec![(span, "must be greater than zero".into())], notes: vec![], }, + Error::MissingWorkgroupSize(span) => ParseError { + message: "workgroup size is missing on compute shader entry point".to_string(), + labels: vec![( + span, + "must be paired with a @workgroup_size attribute".into(), + )], + notes: vec![], + }, } } } diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 84c0d993e..884c4100c 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -967,7 +967,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { name: f.name.name.to_string(), stage: entry.stage, early_depth_test: entry.early_depth_test, - workgroup_size: entry.workgroup_size, + workgroup_size: entry.workgroup_size.unwrap_or([0, 0, 0]), function, }); Ok(LoweredGlobalDecl::EntryPoint) diff --git a/src/front/wgsl/parse/ast.rs b/src/front/wgsl/parse/ast.rs index 9b7670e4a..34aeb21a1 100644 --- a/src/front/wgsl/parse/ast.rs +++ b/src/front/wgsl/parse/ast.rs @@ -103,7 +103,7 @@ pub struct FunctionResult<'a> { pub struct EntryPoint { pub stage: crate::ShaderStage, pub early_depth_test: Option, - pub workgroup_size: [u32; 3], + pub workgroup_size: Option<[u32; 3]>, } #[cfg(doc)] diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index b6798027e..4a9aafc5f 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -2,7 +2,7 @@ use crate::front::wgsl::error::{Error, ExpectedToken}; use crate::front::wgsl::parse::lexer::{Lexer, Token}; use crate::front::wgsl::parse::number::Number; use crate::front::SymbolTable; -use crate::{Arena, FastHashSet, Handle, Span}; +use crate::{Arena, FastHashSet, Handle, ShaderStage, Span}; pub mod ast; pub mod conv; @@ -2158,7 +2158,8 @@ impl Parser { // read attributes let mut binding = None; let mut stage = ParsedAttribute::default(); - let mut workgroup_size = [0u32; 3]; + let mut compute_span = Span::new(0, 0); + let mut workgroup_size = ParsedAttribute::default(); let mut early_depth_test = ParsedAttribute::default(); let (mut bind_index, mut bind_group) = (ParsedAttribute::default(), ParsedAttribute::default()); @@ -2184,11 +2185,12 @@ impl Parser { } ("compute", name_span) => { stage.set(crate::ShaderStage::Compute, name_span)?; + compute_span = name_span; } - ("workgroup_size", _) => { + ("workgroup_size", name_span) => { lexer.expect(Token::Paren('('))?; - workgroup_size = [1u32; 3]; - for (i, size) in workgroup_size.iter_mut().enumerate() { + let mut new_workgroup_size = [1u32; 3]; + for (i, size) in new_workgroup_size.iter_mut().enumerate() { *size = Self::generic_non_negative_int_literal(lexer)?; match lexer.next() { (Token::Paren(')'), _) => break, @@ -2201,6 +2203,7 @@ impl Parser { } } } + workgroup_size.set(new_workgroup_size, name_span)?; } ("early_depth_test", name_span) => { let conservative = if lexer.skip(Token::Paren('(')) { @@ -2281,11 +2284,18 @@ impl Parser { (Token::Word("fn"), _) => { let function = self.function_decl(lexer, out, &mut dependencies)?; Some(ast::GlobalDeclKind::Fn(ast::Function { - entry_point: stage.value.map(|stage| ast::EntryPoint { - stage, - early_depth_test: early_depth_test.value, - workgroup_size, - }), + entry_point: if let Some(stage) = stage.value { + if stage == ShaderStage::Compute && workgroup_size.value.is_none() { + return Err(Error::MissingWorkgroupSize(compute_span)); + } + Some(ast::EntryPoint { + stage, + early_depth_test: early_depth_test.value, + workgroup_size: workgroup_size.value, + }) + } else { + None + }, ..function })) } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 80ea26143..084655d66 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -534,6 +534,7 @@ fn parse_repeated_attributes() { ("size(16)", template_struct), ("vertex", template_stage), ("early_depth_test(less_equal)", template_resource), + ("workgroup_size(1)", template_stage), ] { let shader = template.replace("__REPLACE__", &format!("@{attribute} @{attribute}")); let name_length = attribute.rfind('(').unwrap_or(attribute.len()) as u32; @@ -548,3 +549,18 @@ fn parse_repeated_attributes() { )); } } + +#[test] +fn parse_missing_workgroup_size() { + use crate::{ + front::wgsl::{error::Error, Frontend}, + Span, + }; + + let shader = "@compute fn vs() -> vec4 { return vec4(0.0); }"; + let result = Frontend::new().inner(shader); + assert!(matches!( + result.unwrap_err(), + Error::MissingWorkgroupSize(span) if span == Span::new(1, 8) + )); +} From 3da935512535d6fa3fd1d8e037fff153f679befd Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Fri, 18 Aug 2023 13:07:24 +0200 Subject: [PATCH 2060/2212] [wgsl-in] Avoid splatting all binary operator expressions (#2440) * [wgsl-in] Avoid splatting all binary operator expressions Fixes #2439. * [wgsl-in] Expand binary_op_splat function comment --- src/front/wgsl/lower/mod.rs | 14 ++++++++++- src/front/wgsl/tests.rs | 48 +++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 884c4100c..f3a7b22dd 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -504,13 +504,25 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { } /// Insert splats, if needed by the non-'*' operations. + /// + /// See the "Binary arithmetic expressions with mixed scalar and vector operands" + /// table in the WebGPU Shading Language specification for relevant operators. + /// + /// Multiply is not handled here as backends are expected to handle vec*scalar + /// operations, so inserting splats into the IR increases size needlessly. fn binary_op_splat( &mut self, op: crate::BinaryOperator, left: &mut Handle, right: &mut Handle, ) -> Result<(), Error<'source>> { - if op != crate::BinaryOperator::Multiply { + if matches!( + op, + crate::BinaryOperator::Add + | crate::BinaryOperator::Subtract + | crate::BinaryOperator::Divide + | crate::BinaryOperator::Modulo + ) { self.grow_types(*left)?.grow_types(*right)?; let left_size = match *self.resolved_inner(*left) { diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 084655d66..02fc110ca 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -387,6 +387,54 @@ fn parse_expressions() { }").unwrap(); } +#[test] +fn binary_expression_mixed_scalar_and_vector_operands() { + for (operand, expect_splat) in [ + ('<', false), + ('>', false), + ('&', false), + ('|', false), + ('+', true), + ('-', true), + ('*', false), + ('/', true), + ('%', true), + ] { + let module = parse_str(&format!( + " + const some_vec = vec3(1.0, 1.0, 1.0); + @fragment + fn main() -> @location(0) vec4 {{ + if (all(1.0 {operand} some_vec)) {{ + return vec4(0.0); + }} + return vec4(1.0); + }} + " + )) + .unwrap(); + + let expressions = &&module.entry_points[0].function.expressions; + + let found_expressions = expressions + .iter() + .filter(|&(_, e)| { + if let crate::Expression::Binary { left, .. } = *e { + matches!( + (expect_splat, &expressions[left]), + (false, &crate::Expression::Literal(crate::Literal::F32(..))) + | (true, &crate::Expression::Splat { .. }) + ) + } else { + false + } + }) + .count(); + + assert_eq!(found_expressions, 1); + } +} + #[test] fn parse_pointers() { parse_str( From b00131394700c37ed465d3092d8254de1bbc34df Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Fri, 18 Aug 2023 15:16:44 +0200 Subject: [PATCH 2061/2212] [wgsl-in] Only splat 'scalar op vec', not '_ op vec' (#2444) Change binary_op_splat() from splatting: vec op scalar _ op vec to only splat: vec op scalar scalar op vec --- src/front/wgsl/lower/mod.rs | 11 +++-------- src/front/wgsl/tests.rs | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index f3a7b22dd..4c5acf0ad 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -525,13 +525,8 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { ) { self.grow_types(*left)?.grow_types(*right)?; - let left_size = match *self.resolved_inner(*left) { - crate::TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - - match (left_size, self.resolved_inner(*right)) { - (Some(size), &crate::TypeInner::Scalar { .. }) => { + match (self.resolved_inner(*left), self.resolved_inner(*right)) { + (&crate::TypeInner::Vector { size, .. }, &crate::TypeInner::Scalar { .. }) => { *right = self.append_expression( crate::Expression::Splat { size, @@ -540,7 +535,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { self.get_expression_span(*right), ); } - (None, &crate::TypeInner::Vector { size, .. }) => { + (&crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, .. }) => { *left = self.append_expression( crate::Expression::Splat { size, value: *left }, self.get_expression_span(*left), diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 02fc110ca..09a4356b0 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -433,6 +433,24 @@ fn binary_expression_mixed_scalar_and_vector_operands() { assert_eq!(found_expressions, 1); } + + let module = parse_str( + "@fragment + fn main(mat: mat3x3) { + let vec = vec3(1.0, 1.0, 1.0); + let result = mat / vec; + }", + ) + .unwrap(); + let expressions = &&module.entry_points[0].function.expressions; + let found_splat = expressions.iter().any(|(_, e)| { + if let crate::Expression::Binary { left, .. } = *e { + matches!(&expressions[left], &crate::Expression::Splat { .. }) + } else { + false + } + }); + assert!(!found_splat, "'mat / vec' should not be splatted"); } #[test] From 6aca2e2b5ec1ac634e3e06e9a7d6113290070234 Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Sat, 19 Aug 2023 17:35:22 +0200 Subject: [PATCH 2062/2212] Add vim .swp files to gitignore (#2448) --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index e0e95c107..08a609ce9 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ Cargo.lock .fuse_hidden* .idea .vscode +*.swp /*.dot /*.metal /*.metallib From 1192588486221fc1362971c8a1564eb6a9c3cf9f Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Tue, 29 Aug 2023 19:59:50 +0200 Subject: [PATCH 2063/2212] [ci] Specify -HV 2018 to dxc (#2447) This avoids breaking the build with the latest release of dxc, which made HLSL the default. --- xtask/src/main.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 17156db73..48e3f5276 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -255,7 +255,14 @@ fn run(args: Args) -> anyhow::Result<()> { bin, file, config_item, - &["-Wno-parentheses-equality", "-Zi", "-Qembed_debug", "-Od"], + &[ + "-Wno-parentheses-equality", + "-Zi", + "-Qembed_debug", + "-Od", + "-HV", + "2018", + ], ) }) } From 3bd2834b4f70c9d9a95567278cfb7f2c5512ad63 Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Tue, 29 Aug 2023 21:34:55 +0200 Subject: [PATCH 2064/2212] [wgsl-in] Handle all(bool) and any(bool) (#2445) Fixes #1911. --- src/front/wgsl/lower/mod.rs | 21 +++- tests/in/standard.wgsl | 8 ++ .../glsl/standard.derivatives.Fragment.glsl | 13 ++- tests/out/hlsl/standard.hlsl | 14 ++- tests/out/msl/standard.msl | 14 ++- tests/out/spv/standard.spvasm | 98 ++++++++++--------- tests/out/wgsl/standard.wgsl | 13 ++- 7 files changed, 120 insertions(+), 61 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 4c5acf0ad..23d328236 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1696,7 +1696,26 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let argument = self.expression(args.next()?, ctx.reborrow())?; args.finish()?; - crate::Expression::Relational { fun, argument } + // Check for no-op all(bool) and any(bool): + let argument_unmodified = matches!( + fun, + crate::RelationalFunction::All | crate::RelationalFunction::Any + ) && { + ctx.grow_types(argument)?; + matches!( + ctx.resolved_inner(argument), + &crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + .. + } + ) + }; + + if argument_unmodified { + return Ok(Some(argument)); + } else { + crate::Expression::Relational { fun, argument } + } } else if let Some((axis, ctrl)) = conv::map_derivative(function.name) { let mut args = ctx.prepare_args(arguments, 1, span); let expr = self.expression(args.next()?, ctx.reborrow())?; diff --git a/tests/in/standard.wgsl b/tests/in/standard.wgsl index 79f5632ce..9fdc344bc 100644 --- a/tests/in/standard.wgsl +++ b/tests/in/standard.wgsl @@ -1,5 +1,11 @@ // Standard functions. +fn test_any_and_all_for_bool() -> bool { + let a = any(true); + return all(a); +} + + @fragment fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { var x = dpdxCoarse(foo); @@ -14,5 +20,7 @@ fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { y = dpdy(foo); z = fwidth(foo); + let a = test_any_and_all_for_bool(); + return (x + y) * z; } diff --git a/tests/out/glsl/standard.derivatives.Fragment.glsl b/tests/out/glsl/standard.derivatives.Fragment.glsl index 331ffb5c0..18e150a3f 100644 --- a/tests/out/glsl/standard.derivatives.Fragment.glsl +++ b/tests/out/glsl/standard.derivatives.Fragment.glsl @@ -5,6 +5,10 @@ precision highp int; layout(location = 0) out vec4 _fs2p_location0; +bool test_any_and_all_for_bool() { + return true; +} + void main() { vec4 foo = gl_FragCoord; vec4 x = vec4(0.0); @@ -28,10 +32,11 @@ void main() { y = _e11; vec4 _e12 = fwidth(foo); z = _e12; - vec4 _e13 = x; - vec4 _e14 = y; - vec4 _e16 = z; - _fs2p_location0 = ((_e13 + _e14) * _e16); + bool _e13 = test_any_and_all_for_bool(); + vec4 _e14 = x; + vec4 _e15 = y; + vec4 _e17 = z; + _fs2p_location0 = ((_e14 + _e15) * _e17); return; } diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl index a2bcc70ec..d3fd537eb 100644 --- a/tests/out/hlsl/standard.hlsl +++ b/tests/out/hlsl/standard.hlsl @@ -2,6 +2,11 @@ struct FragmentInput_derivatives { float4 foo_1 : SV_Position; }; +bool test_any_and_all_for_bool() +{ + return true; +} + float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Target0 { float4 foo = fragmentinput_derivatives.foo_1; @@ -27,8 +32,9 @@ float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Tar y = _expr11; float4 _expr12 = fwidth(foo); z = _expr12; - float4 _expr13 = x; - float4 _expr14 = y; - float4 _expr16 = z; - return ((_expr13 + _expr14) * _expr16); + const bool _e13 = test_any_and_all_for_bool(); + float4 _expr14 = x; + float4 _expr15 = y; + float4 _expr17 = z; + return ((_expr14 + _expr15) * _expr17); } diff --git a/tests/out/msl/standard.msl b/tests/out/msl/standard.msl index bca5f0cb0..f02243eaa 100644 --- a/tests/out/msl/standard.msl +++ b/tests/out/msl/standard.msl @@ -5,6 +5,11 @@ using metal::uint; +bool test_any_and_all_for_bool( +) { + return true; +} + struct derivativesInput { }; struct derivativesOutput { @@ -34,8 +39,9 @@ fragment derivativesOutput derivatives( y = _e11; metal::float4 _e12 = metal::fwidth(foo); z = _e12; - metal::float4 _e13 = x; - metal::float4 _e14 = y; - metal::float4 _e16 = z; - return derivativesOutput { (_e13 + _e14) * _e16 }; + bool _e13 = test_any_and_all_for_bool(); + metal::float4 _e14 = x; + metal::float4 _e15 = y; + metal::float4 _e17 = z; + return derivativesOutput { (_e14 + _e15) * _e17 }; } diff --git a/tests/out/spv/standard.spvasm b/tests/out/spv/standard.spvasm index 6d9445808..07bb2a790 100644 --- a/tests/out/spv/standard.spvasm +++ b/tests/out/spv/standard.spvasm @@ -1,56 +1,66 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 33 +; Bound: 40 OpCapability Shader OpCapability DerivativeControl %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %16 "derivatives" %11 %14 -OpExecutionMode %16 OriginUpperLeft -OpDecorate %11 BuiltIn FragCoord -OpDecorate %14 Location 0 +OpEntryPoint Fragment %22 "derivatives" %17 %20 +OpExecutionMode %22 OriginUpperLeft +OpDecorate %17 BuiltIn FragCoord +OpDecorate %20 Location 0 %2 = OpTypeVoid -%4 = OpTypeFloat 32 -%3 = OpTypeVector %4 4 -%6 = OpTypePointer Function %3 -%7 = OpConstantNull %3 -%12 = OpTypePointer Input %3 -%11 = OpVariable %12 Input -%15 = OpTypePointer Output %3 -%14 = OpVariable %15 Output -%17 = OpTypeFunction %2 -%16 = OpFunction %2 None %17 +%3 = OpTypeBool +%5 = OpTypeFloat 32 +%4 = OpTypeVector %5 4 +%8 = OpTypeFunction %3 +%9 = OpConstantTrue %3 +%12 = OpTypePointer Function %4 +%13 = OpConstantNull %4 +%18 = OpTypePointer Input %4 +%17 = OpVariable %18 Input +%21 = OpTypePointer Output %4 +%20 = OpVariable %21 Output +%23 = OpTypeFunction %2 +%7 = OpFunction %3 None %8 +%6 = OpLabel +OpBranch %10 %10 = OpLabel -%5 = OpVariable %6 Function %7 -%8 = OpVariable %6 Function %7 -%9 = OpVariable %6 Function %7 -%13 = OpLoad %3 %11 -OpBranch %18 -%18 = OpLabel -%19 = OpDPdxCoarse %3 %13 -OpStore %5 %19 -%20 = OpDPdyCoarse %3 %13 -OpStore %8 %20 -%21 = OpFwidthCoarse %3 %13 -OpStore %9 %21 -%22 = OpDPdxFine %3 %13 -OpStore %5 %22 -%23 = OpDPdyFine %3 %13 -OpStore %8 %23 -%24 = OpFwidthFine %3 %13 -OpStore %9 %24 -%25 = OpDPdx %3 %13 -OpStore %5 %25 -%26 = OpDPdy %3 %13 -OpStore %8 %26 -%27 = OpFwidth %3 %13 -OpStore %9 %27 -%28 = OpLoad %3 %5 -%29 = OpLoad %3 %8 -%30 = OpFAdd %3 %28 %29 -%31 = OpLoad %3 %9 -%32 = OpFMul %3 %30 %31 +OpReturnValue %9 +OpFunctionEnd +%22 = OpFunction %2 None %23 +%16 = OpLabel +%11 = OpVariable %12 Function %13 +%14 = OpVariable %12 Function %13 +%15 = OpVariable %12 Function %13 +%19 = OpLoad %4 %17 +OpBranch %24 +%24 = OpLabel +%25 = OpDPdxCoarse %4 %19 +OpStore %11 %25 +%26 = OpDPdyCoarse %4 %19 +OpStore %14 %26 +%27 = OpFwidthCoarse %4 %19 +OpStore %15 %27 +%28 = OpDPdxFine %4 %19 +OpStore %11 %28 +%29 = OpDPdyFine %4 %19 +OpStore %14 %29 +%30 = OpFwidthFine %4 %19 +OpStore %15 %30 +%31 = OpDPdx %4 %19 +OpStore %11 %31 +%32 = OpDPdy %4 %19 OpStore %14 %32 +%33 = OpFwidth %4 %19 +OpStore %15 %33 +%34 = OpFunctionCall %3 %7 +%35 = OpLoad %4 %11 +%36 = OpLoad %4 %14 +%37 = OpFAdd %4 %35 %36 +%38 = OpLoad %4 %15 +%39 = OpFMul %4 %37 %38 +OpStore %20 %39 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/standard.wgsl b/tests/out/wgsl/standard.wgsl index 80e8f2498..886cf0919 100644 --- a/tests/out/wgsl/standard.wgsl +++ b/tests/out/wgsl/standard.wgsl @@ -1,3 +1,7 @@ +fn test_any_and_all_for_bool() -> bool { + return true; +} + @fragment fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { var x: vec4; @@ -22,8 +26,9 @@ fn derivatives(@builtin(position) foo: vec4) -> @location(0) vec4 { y = _e11; let _e12 = fwidth(foo); z = _e12; - let _e13 = x; - let _e14 = y; - let _e16 = z; - return ((_e13 + _e14) * _e16); + let _e13 = test_any_and_all_for_bool(); + let _e14 = x; + let _e15 = y; + let _e17 = z; + return ((_e14 + _e15) * _e17); } From 0491d39232bafc30962f6ea240ab6ed457282a62 Mon Sep 17 00:00:00 2001 From: Frederik Magnus Johansen Vestre Date: Wed, 30 Aug 2023 21:00:35 +0200 Subject: [PATCH 2065/2212] Support dual source blending (#2427) Co-authored-by: teoxoy <28601907+teoxoy@users.noreply.github.com> --- src/back/glsl/features.rs | 11 ++++ src/back/glsl/mod.rs | 18 +++++- src/back/hlsl/writer.rs | 12 +++- src/back/msl/mod.rs | 29 ++++++++- src/back/spv/writer.rs | 4 ++ src/back/wgsl/writer.rs | 13 ++++ src/front/glsl/functions.rs | 2 + src/front/glsl/variables.rs | 1 + src/front/interpolator.rs | 1 + src/front/spv/mod.rs | 1 + src/front/wgsl/parse/mod.rs | 5 ++ src/lib.rs | 2 + src/valid/analyzer.rs | 5 ++ src/valid/interface.rs | 65 +++++++++++++++++++- src/valid/mod.rs | 2 + tests/in/dualsource.param.ron | 13 ++++ tests/in/dualsource.wgsl | 11 ++++ tests/out/analysis/access.info.ron | 9 +++ tests/out/analysis/collatz.info.ron | 2 + tests/out/analysis/shadow.info.ron | 3 + tests/out/glsl/dualsource.main.Fragment.glsl | 27 ++++++++ tests/out/hlsl/dualsource.hlsl | 29 +++++++++ tests/out/hlsl/dualsource.ron | 12 ++++ tests/out/ir/access.ron | 1 + tests/out/ir/shadow.ron | 3 + tests/out/msl/dualsource.msl | 29 +++++++++ tests/out/spv/dualsource.spvasm | 55 +++++++++++++++++ tests/out/wgsl/dualsource.wgsl | 16 +++++ tests/snapshots.rs | 4 ++ 29 files changed, 376 insertions(+), 9 deletions(-) create mode 100644 tests/in/dualsource.param.ron create mode 100644 tests/in/dualsource.wgsl create mode 100644 tests/out/glsl/dualsource.main.Fragment.glsl create mode 100644 tests/out/hlsl/dualsource.hlsl create mode 100644 tests/out/hlsl/dualsource.ron create mode 100644 tests/out/msl/dualsource.msl create mode 100644 tests/out/spv/dualsource.spvasm create mode 100644 tests/out/wgsl/dualsource.wgsl diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 8a5da1b6e..6bb5b1888 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -41,6 +41,8 @@ bitflags::bitflags! { const TEXTURE_LEVELS = 1 << 19; /// Image size query const IMAGE_SIZE = 1 << 20; + /// Dual source blending + const DUAL_SOURCE_BLENDING = 1 << 21; } } @@ -104,6 +106,7 @@ impl FeaturesManager { check_feature!(CULL_DISTANCE, 450, 300 /* with extension */); check_feature!(SAMPLE_VARIABLES, 400, 300); check_feature!(DYNAMIC_ARRAY_SIZE, 430, 310); + check_feature!(DUAL_SOURCE_BLENDING, 330, 300 /* with extension */); match version { Version::Embedded { is_webgl: true, .. } => check_feature!(MULTI_VIEW, 140, 300), _ => check_feature!(MULTI_VIEW, 140, 310), @@ -233,6 +236,10 @@ impl FeaturesManager { // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_query_levels.txt writeln!(out, "#extension GL_ARB_texture_query_levels : require")?; } + if self.0.contains(Features::DUAL_SOURCE_BLENDING) && version.is_es() { + // https://registry.khronos.org/OpenGL/extensions/EXT/EXT_blend_func_extended.txt + writeln!(out, "#extension GL_EXT_blend_func_extended : require")?; + } Ok(()) } @@ -497,6 +504,7 @@ impl<'a, W> Writer<'a, W> { location: _, interpolation, sampling, + second_blend_source, } => { if interpolation == Some(Interpolation::Linear) { self.features.request(Features::NOPERSPECTIVE_QUALIFIER); @@ -504,6 +512,9 @@ impl<'a, W> Writer<'a, W> { if sampling == Some(Sampling::Sample) { self.features.request(Features::SAMPLE_QUALIFIER); } + if second_blend_source { + self.features.request(Features::DUAL_SOURCE_BLENDING); + } } } } diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ef5dd0143..4b732a603 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -333,6 +333,12 @@ struct VaryingName<'a> { impl fmt::Display for VaryingName<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self.binding { + crate::Binding::Location { + second_blend_source: true, + .. + } => { + write!(f, "_fs2p_location1",) + } crate::Binding::Location { location, .. } => { let prefix = match (self.stage, self.output) { (ShaderStage::Compute, _) => unreachable!(), @@ -1235,12 +1241,13 @@ impl<'a, W: Write> Writer<'a, W> { Some(binding) => binding, }; - let (location, interpolation, sampling) = match *binding { + let (location, interpolation, sampling, second_blend_source) = match *binding { crate::Binding::Location { location, interpolation, sampling, - } => (location, interpolation, sampling), + second_blend_source, + } => (location, interpolation, sampling, second_blend_source), crate::Binding::BuiltIn(built_in) => { if let crate::BuiltIn::Position { invariant: true } = built_in { match (self.options.version, self.entry_point.stage) { @@ -1281,7 +1288,11 @@ impl<'a, W: Write> Writer<'a, W> { // Write the I/O locations, if allowed if self.options.version.supports_explicit_locations() || !emit_interpolation_and_auxiliary { - write!(self.out, "layout(location = {location}) ")?; + if second_blend_source { + write!(self.out, "layout(location = {location}, index = 1) ")?; + } else { + write!(self.out, "layout(location = {location}) ")?; + } } // Write the interpolation qualifier. @@ -1318,6 +1329,7 @@ impl<'a, W: Write> Writer<'a, W> { location, interpolation: None, sampling: None, + second_blend_source, }, stage: self.entry_point.stage, output, diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 4f1912638..c37334b60 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -416,7 +416,17 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let builtin_str = builtin.to_hlsl_str()?; write!(self.out, " : {builtin_str}")?; } - crate::Binding::Location { location, .. } => { + crate::Binding::Location { + second_blend_source: true, + .. + } => { + write!(self.out, " : SV_Target1")?; + } + crate::Binding::Location { + location, + second_blend_source: false, + .. + } => { if stage == Some((crate::ShaderStage::Fragment, Io::Output)) { write!(self.out, " : SV_Target{location}")?; } else { diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 78bcc2123..819d48a8f 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -82,7 +82,10 @@ pub type EntryPointResourceMap = std::collections::BTreeMap match mode { LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(location)), - LocationMode::FragmentOutput => Ok(ResolvedBinding::Color(location)), + LocationMode::FragmentOutput => { + if second_blend_source && self.lang_version < (1, 2) { + return Err(Error::UnsupportedAttribute( + "second_blend_source".to_string(), + )); + } + Ok(ResolvedBinding::Color { + location, + second_blend_source, + }) + } LocationMode::VertexOutput | LocationMode::FragmentInput => { Ok(ResolvedBinding::User { prefix: if self.spirv_cross_compatibility { @@ -404,7 +418,16 @@ impl ResolvedBinding { write!(out, "{name}")?; } Self::Attribute(index) => write!(out, "attribute({index})")?, - Self::Color(index) => write!(out, "color({index})")?, + Self::Color { + location, + second_blend_source, + } => { + if second_blend_source { + write!(out, "color({location}) index(1)")? + } else { + write!(out, "color({location})")? + } + } Self::User { prefix, index, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index e6db93602..41a13cbc1 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1434,6 +1434,7 @@ impl Writer { location, interpolation, sampling, + second_blend_source, } => { self.decorate(id, Decoration::Location, &[location]); @@ -1473,6 +1474,9 @@ impl Writer { } } } + if second_blend_source { + self.decorate(id, Decoration::Index, &[1]); + } } crate::Binding::BuiltIn(built_in) => { use crate::BuiltIn as Bi; diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 44dd2a97c..43d094ec2 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -17,6 +17,7 @@ enum Attribute { Invariant, Interpolate(Option, Option), Location(u32), + SecondBlendSource, Stage(ShaderStage), WorkGroupSize([u32; 3]), } @@ -319,6 +320,7 @@ impl Writer { for attribute in attributes { match *attribute { Attribute::Location(id) => write!(self.out, "@location({id}) ")?, + Attribute::SecondBlendSource => write!(self.out, "@second_blend_source ")?, Attribute::BuiltIn(builtin_attrib) => { let builtin = builtin_str(builtin_attrib)?; write!(self.out, "@builtin({builtin}) ")?; @@ -1917,9 +1919,20 @@ fn map_binding_to_attribute(binding: &crate::Binding) -> Vec { location, interpolation, sampling, + second_blend_source: false, } => vec![ Attribute::Location(location), Attribute::Interpolate(interpolation, sampling), ], + crate::Binding::Location { + location, + interpolation, + sampling, + second_blend_source: true, + } => vec![ + Attribute::Location(location), + Attribute::SecondBlendSource, + Attribute::Interpolate(interpolation, sampling), + ], } } diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index f44827258..7dee02374 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1294,6 +1294,7 @@ impl Frontend { location, interpolation, sampling: None, + second_blend_source: false, }; location += 1; @@ -1336,6 +1337,7 @@ impl Frontend { location, interpolation, sampling: None, + second_blend_source: false, }; location += 1; binding diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index a9a403e40..ad0bd7cbd 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -475,6 +475,7 @@ impl Frontend { location, interpolation, sampling, + second_blend_source: false, }, handle, storage, diff --git a/src/front/interpolator.rs b/src/front/interpolator.rs index 96f5db6ff..0196a2254 100644 --- a/src/front/interpolator.rs +++ b/src/front/interpolator.rs @@ -43,6 +43,7 @@ impl crate::Binding { location: _, interpolation: ref mut interpolation @ None, ref mut sampling, + second_blend_source: _, } = *self { match ty.scalar_kind() { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index a210e8c42..36108fdd9 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -255,6 +255,7 @@ impl Decoration { location, interpolation, sampling, + second_blend_source: false, }), _ => Err(Error::MissingDecoration(spirv::Decoration::Location)), } diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 4a9aafc5f..86dd12799 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -143,6 +143,7 @@ impl ParsedAttribute { #[derive(Default)] struct BindingParser { location: ParsedAttribute, + second_blend_source: ParsedAttribute, built_in: ParsedAttribute, interpolation: ParsedAttribute, sampling: ParsedAttribute, @@ -182,6 +183,9 @@ impl BindingParser { } lexer.expect(Token::Paren(')'))?; } + "second_blend_source" => { + self.second_blend_source.set(true, name_span)?; + } "invariant" => { self.invariant.set(true, name_span)?; } @@ -208,6 +212,7 @@ impl BindingParser { location, interpolation, sampling, + second_blend_source: self.second_blend_source.value.unwrap_or(false), })) } (None, Some(crate::BuiltIn::Position { .. }), None, None, invariant) => { diff --git a/src/lib.rs b/src/lib.rs index a1f7ef165..fdea215e3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -922,6 +922,8 @@ pub enum Binding { /// [`Fragment`]: crate::ShaderStage::Fragment Location { location: u32, + /// Indicates the 2nd input to the blender when dual-source blending. + second_blend_source: bool, interpolation: Option, sampling: Option, }, diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 1e75c5af6..e4162e15f 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -256,6 +256,9 @@ pub struct FunctionInfo { /// /// [`GlobalVariable`]: crate::GlobalVariable sampling: crate::FastHashSet, + + /// Indicates that the function is using dual source blending. + pub dual_source_blending: bool, } impl FunctionInfo { @@ -999,6 +1002,7 @@ impl ModuleInfo { global_uses: vec![GlobalUse::empty(); module.global_variables.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::new(); fun.expressions.len()].into_boxed_slice(), sampling: crate::FastHashSet::default(), + dual_source_blending: false, }; let resolve_context = ResolveContext::with_locals(module, &fun.local_variables, &fun.arguments); @@ -1108,6 +1112,7 @@ fn uniform_control_flow() { global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(), expressions: vec![ExpressionInfo::new(); expressions.len()].into_boxed_slice(), sampling: crate::FastHashSet::default(), + dual_source_blending: false, }; let resolve_context = ResolveContext { constants: &Arena::new(), diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 2e54df247..d788a54a3 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -61,6 +61,17 @@ pub enum VaryingError { DuplicateBuiltIn(crate::BuiltIn), #[error("Capability {0:?} is not supported")] UnsupportedCapability(Capabilities), + #[error("The attribute {0:?} is only valid as an output for stage {1:?}")] + InvalidInputAttributeInStage(&'static str, crate::ShaderStage), + #[error("The attribute {0:?} is not valid for stage {1:?}")] + InvalidAttributeInStage(&'static str, crate::ShaderStage), + #[error( + "The location index {location} cannot be used together with the attribute {attribute:?}" + )] + InvalidLocationAttributeCombination { + location: u32, + attribute: &'static str, + }, } #[derive(Clone, Debug, thiserror::Error)] @@ -89,6 +100,10 @@ pub enum EntryPointError { InvalidIntegerInterpolation { location: u32 }, #[error(transparent)] Function(#[from] FunctionError), + #[error( + "Invalid locations {location_mask:?} are set while dual source blending. Only location 0 may be set." + )] + InvalidLocationsWhileDualSourceBlending { location_mask: BitSet }, } #[cfg(feature = "validate")] @@ -106,6 +121,7 @@ fn storage_usage(access: crate::StorageAccess) -> GlobalUse { struct VaryingContext<'a> { stage: crate::ShaderStage, output: bool, + second_blend_source: bool, types: &'a UniqueArena, type_info: &'a Vec, location_mask: &'a mut BitSet, @@ -293,6 +309,7 @@ impl VaryingContext<'_> { location, interpolation, sampling, + second_blend_source, } => { // Only IO-shareable types may be stored in locations. if !self.type_info[ty.index()] @@ -301,7 +318,37 @@ impl VaryingContext<'_> { { return Err(VaryingError::NotIOShareableType(ty)); } - if !self.location_mask.insert(location as usize) { + + if second_blend_source { + if !self + .capabilities + .contains(Capabilities::DUAL_SOURCE_BLENDING) + { + return Err(VaryingError::UnsupportedCapability( + Capabilities::DUAL_SOURCE_BLENDING, + )); + } + if self.stage != crate::ShaderStage::Fragment { + return Err(VaryingError::InvalidAttributeInStage( + "second_blend_source", + self.stage, + )); + } + if !self.output { + return Err(VaryingError::InvalidInputAttributeInStage( + "second_blend_source", + self.stage, + )); + } + if location != 0 { + return Err(VaryingError::InvalidLocationAttributeCombination { + location, + attribute: "second_blend_source", + }); + } + + self.second_blend_source = true; + } else if !self.location_mask.insert(location as usize) { #[cfg(feature = "validate")] if self.flags.contains(super::ValidationFlags::BINDINGS) { return Err(VaryingError::BindingCollision { location }); @@ -567,7 +614,7 @@ impl super::Validator { return Err(EntryPointError::UnexpectedWorkgroupSize.with_span()); } - let info = self + let mut info = self .validate_function(&ep.function, module, mod_info, true) .map_err(WithSpan::into_other)?; @@ -593,6 +640,7 @@ impl super::Validator { let mut ctx = VaryingContext { stage: ep.stage, output: false, + second_blend_source: false, types: &module.types, type_info: &self.types, location_mask: &mut self.location_mask, @@ -612,6 +660,7 @@ impl super::Validator { let mut ctx = VaryingContext { stage: ep.stage, output: true, + second_blend_source: false, types: &module.types, type_info: &self.types, location_mask: &mut self.location_mask, @@ -623,6 +672,18 @@ impl super::Validator { }; ctx.validate(fr.ty, fr.binding.as_ref()) .map_err_inner(|e| EntryPointError::Result(e).with_span())?; + #[cfg(feature = "validate")] + if ctx.second_blend_source { + // Only the first location may be used whhen dual source blending + if ctx.location_mask.len() == 1 && ctx.location_mask.contains(0) { + info.dual_source_blending = true; + } else { + return Err(EntryPointError::InvalidLocationsWhileDualSourceBlending { + location_mask: self.location_mask.clone(), + } + .with_span()); + } + } #[cfg(feature = "validate")] if ep.stage == crate::ShaderStage::Vertex diff --git a/src/valid/mod.rs b/src/valid/mod.rs index b04d69b5b..535128772 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -112,6 +112,8 @@ bitflags::bitflags! { const MULTISAMPLED_SHADING = 0x800; /// Support for ray queries and acceleration structures. const RAY_QUERY = 0x1000; + /// Support for generating two sources for blending from fragement shaders + const DUAL_SOURCE_BLENDING = 0x2000; } } diff --git a/tests/in/dualsource.param.ron b/tests/in/dualsource.param.ron new file mode 100644 index 000000000..1cf512c6c --- /dev/null +++ b/tests/in/dualsource.param.ron @@ -0,0 +1,13 @@ +( + god_mode: true, + vertex:[ + ], + fragment:[ + ( + entry_point:"main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/in/dualsource.wgsl b/tests/in/dualsource.wgsl new file mode 100644 index 000000000..e7b658ef7 --- /dev/null +++ b/tests/in/dualsource.wgsl @@ -0,0 +1,11 @@ +/* Simple test for multiple output sources from fragment shaders */ +struct FragmentOutput{ + @location(0) color: vec4, + @location(0) @second_blend_source mask: vec4, +} +@fragment +fn main(@builtin(position) position: vec4) -> FragmentOutput { + var color = vec4(0.4,0.3,0.2,0.1); + var mask = vec4(0.9,0.8,0.7,0.6); + return FragmentOutput(color, mask); +} diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron index 62e898d3c..03186d9f1 100644 --- a/tests/out/analysis/access.info.ron +++ b/tests/out/analysis/access.info.ron @@ -1251,6 +1251,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2808,6 +2809,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2847,6 +2849,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2919,6 +2922,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2961,6 +2965,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -3050,6 +3055,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ], entry_points: [ @@ -3727,6 +3733,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -4184,6 +4191,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -4288,6 +4296,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ], const_expression_types: [ diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index c0c222ba4..8241bf9a1 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -273,6 +273,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ], entry_points: [ @@ -426,6 +427,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ], const_expression_types: [], diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 8af61bff5..7459466e2 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -766,6 +766,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2091,6 +2092,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ], entry_points: [ @@ -2183,6 +2185,7 @@ ), ], sampling: [], + dual_source_blending: false, ), ], const_expression_types: [ diff --git a/tests/out/glsl/dualsource.main.Fragment.glsl b/tests/out/glsl/dualsource.main.Fragment.glsl new file mode 100644 index 000000000..9ac463c2b --- /dev/null +++ b/tests/out/glsl/dualsource.main.Fragment.glsl @@ -0,0 +1,27 @@ +#version 310 es +#extension GL_EXT_blend_func_extended : require + +precision highp float; +precision highp int; + +struct FragmentOutput { + vec4 color; + vec4 mask; +}; +layout(location = 0) out vec4 _fs2p_location0; +layout(location = 0, index = 1) out vec4 _fs2p_location1; + +void main() { + vec4 position = gl_FragCoord; + vec4 color = vec4(0.0); + vec4 mask = vec4(0.0); + color = vec4(0.4, 0.3, 0.2, 0.1); + mask = vec4(0.9, 0.8, 0.7, 0.6); + vec4 _e13 = color; + vec4 _e14 = mask; + FragmentOutput _tmp_return = FragmentOutput(_e13, _e14); + _fs2p_location0 = _tmp_return.color; + _fs2p_location1 = _tmp_return.mask; + return; +} + diff --git a/tests/out/hlsl/dualsource.hlsl b/tests/out/hlsl/dualsource.hlsl new file mode 100644 index 000000000..1d5b53d6f --- /dev/null +++ b/tests/out/hlsl/dualsource.hlsl @@ -0,0 +1,29 @@ +struct FragmentOutput { + float4 color : SV_Target0; + float4 mask : SV_Target1; +}; + +struct FragmentInput_main { + float4 position_1 : SV_Position; +}; + +FragmentOutput ConstructFragmentOutput(float4 arg0, float4 arg1) { + FragmentOutput ret = (FragmentOutput)0; + ret.color = arg0; + ret.mask = arg1; + return ret; +} + +FragmentOutput main(FragmentInput_main fragmentinput_main) +{ + float4 position = fragmentinput_main.position_1; + float4 color = (float4)0; + float4 mask = (float4)0; + + color = float4(0.4, 0.3, 0.2, 0.1); + mask = float4(0.9, 0.8, 0.7, 0.6); + float4 _expr13 = color; + float4 _expr14 = mask; + const FragmentOutput fragmentoutput = ConstructFragmentOutput(_expr13, _expr14); + return fragmentoutput; +} diff --git a/tests/out/hlsl/dualsource.ron b/tests/out/hlsl/dualsource.ron new file mode 100644 index 000000000..341a4c528 --- /dev/null +++ b/tests/out/hlsl/dualsource.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"main", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 744724912..5cda4104c 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -2052,6 +2052,7 @@ ty: 26, binding: Some(Location( location: 0, + second_blend_source: false, interpolation: Some(Perspective), sampling: Some(Center), )), diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 246657255..9ae5af000 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -1264,6 +1264,7 @@ ty: 2, binding: Some(Location( location: 0, + second_blend_source: false, interpolation: Some(Perspective), sampling: Some(Center), )), @@ -1273,6 +1274,7 @@ ty: 4, binding: Some(Location( location: 1, + second_blend_source: false, interpolation: Some(Perspective), sampling: Some(Center), )), @@ -1282,6 +1284,7 @@ ty: 4, binding: Some(Location( location: 0, + second_blend_source: false, interpolation: None, sampling: None, )), diff --git a/tests/out/msl/dualsource.msl b/tests/out/msl/dualsource.msl new file mode 100644 index 000000000..92b1909f8 --- /dev/null +++ b/tests/out/msl/dualsource.msl @@ -0,0 +1,29 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct FragmentOutput { + metal::float4 color; + metal::float4 mask; +}; + +struct main_Input { +}; +struct main_Output { + metal::float4 color [[color(0)]]; + metal::float4 mask [[color(0) index(1)]]; +}; +fragment main_Output main_( + metal::float4 position [[position]] +) { + metal::float4 color = {}; + metal::float4 mask = {}; + color = metal::float4(0.4, 0.3, 0.2, 0.1); + mask = metal::float4(0.9, 0.8, 0.7, 0.6); + metal::float4 _e13 = color; + metal::float4 _e14 = mask; + const auto _tmp = FragmentOutput {_e13, _e14}; + return main_Output { _tmp.color, _tmp.mask }; +} diff --git a/tests/out/spv/dualsource.spvasm b/tests/out/spv/dualsource.spvasm new file mode 100644 index 000000000..0fba6bb26 --- /dev/null +++ b/tests/out/spv/dualsource.spvasm @@ -0,0 +1,55 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 35 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %17 "main" %11 %14 %16 +OpExecutionMode %17 OriginUpperLeft +OpMemberDecorate %5 0 Offset 0 +OpMemberDecorate %5 1 Offset 16 +OpDecorate %11 BuiltIn FragCoord +OpDecorate %14 Location 0 +OpDecorate %16 Location 0 +OpDecorate %16 Index 1 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%5 = OpTypeStruct %3 %3 +%7 = OpTypePointer Function %3 +%8 = OpConstantNull %3 +%12 = OpTypePointer Input %3 +%11 = OpVariable %12 Input +%15 = OpTypePointer Output %3 +%14 = OpVariable %15 Output +%16 = OpVariable %15 Output +%18 = OpTypeFunction %2 +%19 = OpConstant %4 0.4 +%20 = OpConstant %4 0.3 +%21 = OpConstant %4 0.2 +%22 = OpConstant %4 0.1 +%23 = OpConstant %4 0.9 +%24 = OpConstant %4 0.8 +%25 = OpConstant %4 0.7 +%26 = OpConstant %4 0.6 +%17 = OpFunction %2 None %18 +%10 = OpLabel +%6 = OpVariable %7 Function %8 +%9 = OpVariable %7 Function %8 +%13 = OpLoad %3 %11 +OpBranch %27 +%27 = OpLabel +%28 = OpCompositeConstruct %3 %19 %20 %21 %22 +OpStore %6 %28 +%29 = OpCompositeConstruct %3 %23 %24 %25 %26 +OpStore %9 %29 +%30 = OpLoad %3 %6 +%31 = OpLoad %3 %9 +%32 = OpCompositeConstruct %5 %30 %31 +%33 = OpCompositeExtract %3 %32 0 +OpStore %14 %33 +%34 = OpCompositeExtract %3 %32 1 +OpStore %16 %34 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/dualsource.wgsl b/tests/out/wgsl/dualsource.wgsl new file mode 100644 index 000000000..d7cc4cbfd --- /dev/null +++ b/tests/out/wgsl/dualsource.wgsl @@ -0,0 +1,16 @@ +struct FragmentOutput { + @location(0) color: vec4, + @location(0) @second_blend_source mask: vec4, +} + +@fragment +fn main(@builtin(position) position: vec4) -> FragmentOutput { + var color: vec4; + var mask: vec4; + + color = vec4(0.4, 0.3, 0.2, 0.1); + mask = vec4(0.9, 0.8, 0.7, 0.6); + let _e13 = color; + let _e14 = mask; + return FragmentOutput(_e13, _e14); +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index e1e114413..a2e03679b 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -512,6 +512,10 @@ fn convert_wgsl() { "fragment-output", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ( + "dualsource", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + ), ("functions-webgl", Targets::GLSL), ( "interpolate", From f49314dbbdfb3beb8c91c4e48402ca7a0591edeb Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Fri, 1 Sep 2023 18:44:48 +0200 Subject: [PATCH 2066/2212] Fix validation and glsl parsing of ldexp (#2449) Fixes #1908. --- src/front/glsl/builtins.rs | 14 +- src/valid/expression.rs | 37 +++- tests/in/glsl/math-functions.frag | 2 +- tests/in/math-functions.wgsl | 2 + .../glsl/math-functions.main.Fragment.glsl | 2 + tests/out/hlsl/math-functions.hlsl | 2 + tests/out/msl/math-functions.msl | 2 + tests/out/spv/math-functions.spvasm | 177 +++++++++--------- tests/out/wgsl/math-functions-frag.wgsl | 15 +- tests/out/wgsl/math-functions.wgsl | 2 + 10 files changed, 160 insertions(+), 95 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 5a5acf432..fa5d5d9b9 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1280,14 +1280,14 @@ fn inject_common_builtin( 0b10 => Some(VectorSize::Tri), _ => Some(VectorSize::Quad), }; - let ty = || match size { + let ty = |kind| match size { Some(size) => TypeInner::Vector { size, - kind: Sk::Float, + kind, width: float_width, }, None => TypeInner::Scalar { - kind: Sk::Float, + kind, width: float_width, }, }; @@ -1300,9 +1300,15 @@ fn inject_common_builtin( _ => unreachable!(), }; + let second_kind = if fun == MacroCall::MathFunction(MathFunction::Ldexp) { + Sk::Sint + } else { + Sk::Float + }; + declaration .overloads - .push(module.add_builtin(vec![ty(), ty()], fun)) + .push(module.add_builtin(vec![ty(Sk::Float), ty(second_kind)], fun)) } } "transpose" => { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 1703d213e..f0131c1df 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1014,7 +1014,7 @@ impl super::Validator { )); } } - Mf::Modf | Mf::Frexp | Mf::Ldexp => { + Mf::Modf | Mf::Frexp => { let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { (Some(ty1), None, None) => ty1, _ => return Err(ExpressionError::WrongArgumentCount(fun)), @@ -1049,6 +1049,41 @@ impl super::Validator { )); } } + Mf::Ldexp => { + let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { + (Some(ty1), None, None) => ty1, + _ => return Err(ExpressionError::WrongArgumentCount(fun)), + }; + let size0 = match *arg_ty { + Ti::Scalar { + kind: Sk::Float, .. + } => None, + Ti::Vector { + kind: Sk::Float, + size, + .. + } => Some(size), + _ => { + return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)); + } + }; + let good = match *arg1_ty { + Ti::Scalar { kind: Sk::Sint, .. } if size0.is_none() => true, + Ti::Vector { + size, + kind: Sk::Sint, + .. + } if Some(size) == size0 => true, + _ => false, + }; + if !good { + return Err(ExpressionError::InvalidArgumentType( + fun, + 1, + arg1.unwrap(), + )); + } + } Mf::Dot => { let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { (Some(ty1), None, None) => ty1, diff --git a/tests/in/glsl/math-functions.frag b/tests/in/glsl/math-functions.frag index 104ca0eea..3c12d82d2 100644 --- a/tests/in/glsl/math-functions.frag +++ b/tests/in/glsl/math-functions.frag @@ -50,7 +50,7 @@ void main() { // TODO: support out params in wgsl output // vec4 modfOut = modf(a, b); // vec4 frexpOut = frexp(a, b); - // float ldexpOut = ldexp(a.x, i); + float ldexpOut = ldexp(a.x, i); vec4 rad = radians(a); float deg = degrees(a.x); float smoothStepScalar = smoothstep(0.0, 1.0, 0.5); diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index efeb988f5..afc90811c 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -29,4 +29,6 @@ fn main() { let clz_b = countLeadingZeros(1u); let clz_c = countLeadingZeros(vec2(-1)); let clz_d = countLeadingZeros(vec2(1u)); + let lde_a = ldexp(1.0, 2); + let lde_b = ldexp(vec2(1.0, 2.0), vec2(3, 4)); } diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl index 70ad0b199..02cafcea0 100644 --- a/tests/out/glsl/math-functions.main.Fragment.glsl +++ b/tests/out/glsl/math-functions.main.Fragment.glsl @@ -34,5 +34,7 @@ void main() { ivec2 _e58 = ivec2(-1); ivec2 clz_c = mix(ivec2(31) - findMSB(_e58), ivec2(0), lessThan(_e58, ivec2(0))); uvec2 clz_d = uvec2(ivec2(31) - findMSB(uvec2(1u))); + float lde_a = ldexp(1.0, 2); + vec2 lde_b = ldexp(vec2(1.0, 2.0), ivec2(3, 4)); } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index a1be81053..3061a3ac1 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -29,4 +29,6 @@ void main() int2 _expr58 = (-1).xx; int2 clz_c = (_expr58 < (0).xx ? (0).xx : (31).xx - asint(firstbithigh(_expr58))); uint2 clz_d = ((31u).xx - firstbithigh((1u).xx)); + float lde_a = ldexp(1.0, 2); + float2 lde_b = ldexp(float2(1.0, 2.0), int2(3, 4)); } diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 120d526d4..1f22ae81d 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -38,4 +38,6 @@ fragment void main_( uint clz_b = metal::clz(1u); metal::int2 clz_c = metal::clz(metal::int2(-1)); metal::uint2 clz_d = metal::clz(metal::uint2(1u)); + float lde_a = metal::ldexp(1.0, 2); + metal::float2 lde_b = metal::ldexp(metal::float2(1.0, 2.0), metal::int2(3, 4)); } diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 60bdd7ae0..b3a32bce3 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,97 +1,106 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 87 +; Bound: 96 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %8 "main" -OpExecutionMode %8 OriginUpperLeft +OpEntryPoint Fragment %9 "main" +OpExecutionMode %9 OriginUpperLeft %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 %6 = OpTypeInt 32 1 %5 = OpTypeVector %6 2 -%9 = OpTypeFunction %2 -%10 = OpConstant %4 1.0 -%11 = OpConstant %4 0.0 -%12 = OpConstantNull %5 -%13 = OpTypeInt 32 0 -%14 = OpConstant %13 0 -%15 = OpConstant %6 -1 -%16 = OpConstant %13 1 -%17 = OpConstant %6 0 -%18 = OpConstant %13 4294967295 -%19 = OpConstant %6 1 -%27 = OpConstantComposite %3 %11 %11 %11 %11 -%28 = OpConstantComposite %3 %10 %10 %10 %10 -%31 = OpConstantNull %6 -%44 = OpTypeVector %13 2 -%54 = OpConstant %13 32 -%64 = OpConstantComposite %44 %54 %54 -%76 = OpConstant %6 31 -%82 = OpConstantComposite %5 %76 %76 -%8 = OpFunction %2 None %9 -%7 = OpLabel -OpBranch %20 -%20 = OpLabel -%21 = OpCompositeConstruct %3 %11 %11 %11 %11 -%22 = OpExtInst %4 %1 Degrees %10 -%23 = OpExtInst %4 %1 Radians %10 -%24 = OpExtInst %3 %1 Degrees %21 -%25 = OpExtInst %3 %1 Radians %21 -%26 = OpExtInst %3 %1 FClamp %21 %27 %28 -%29 = OpExtInst %3 %1 Refract %21 %21 %10 -%32 = OpCompositeExtract %6 %12 0 -%33 = OpCompositeExtract %6 %12 0 -%34 = OpIMul %6 %32 %33 -%35 = OpIAdd %6 %31 %34 -%36 = OpCompositeExtract %6 %12 1 -%37 = OpCompositeExtract %6 %12 1 -%38 = OpIMul %6 %36 %37 -%30 = OpIAdd %6 %35 %38 -%39 = OpCopyObject %13 %14 -%40 = OpExtInst %13 %1 FindUMsb %39 -%41 = OpExtInst %6 %1 FindSMsb %15 -%42 = OpCompositeConstruct %5 %15 %15 -%43 = OpExtInst %5 %1 FindSMsb %42 -%45 = OpCompositeConstruct %44 %16 %16 -%46 = OpExtInst %44 %1 FindUMsb %45 -%47 = OpExtInst %6 %1 FindILsb %15 -%48 = OpExtInst %13 %1 FindILsb %16 -%49 = OpCompositeConstruct %5 %15 %15 -%50 = OpExtInst %5 %1 FindILsb %49 -%51 = OpCompositeConstruct %44 %16 %16 -%52 = OpExtInst %44 %1 FindILsb %51 -%55 = OpExtInst %13 %1 FindILsb %14 -%53 = OpExtInst %13 %1 UMin %54 %55 -%57 = OpExtInst %6 %1 FindILsb %17 -%56 = OpExtInst %6 %1 UMin %54 %57 -%59 = OpExtInst %13 %1 FindILsb %18 -%58 = OpExtInst %13 %1 UMin %54 %59 -%61 = OpExtInst %6 %1 FindILsb %15 -%60 = OpExtInst %6 %1 UMin %54 %61 -%62 = OpCompositeConstruct %44 %14 %14 -%65 = OpExtInst %44 %1 FindILsb %62 -%63 = OpExtInst %44 %1 UMin %64 %65 -%66 = OpCompositeConstruct %5 %17 %17 -%68 = OpExtInst %5 %1 FindILsb %66 -%67 = OpExtInst %5 %1 UMin %64 %68 -%69 = OpCompositeConstruct %44 %16 %16 -%71 = OpExtInst %44 %1 FindILsb %69 -%70 = OpExtInst %44 %1 UMin %64 %71 -%72 = OpCompositeConstruct %5 %19 %19 -%74 = OpExtInst %5 %1 FindILsb %72 -%73 = OpExtInst %5 %1 UMin %64 %74 -%77 = OpExtInst %6 %1 FindUMsb %15 -%75 = OpISub %6 %76 %77 -%79 = OpExtInst %6 %1 FindUMsb %16 -%78 = OpISub %13 %76 %79 -%80 = OpCompositeConstruct %5 %15 %15 -%83 = OpExtInst %5 %1 FindUMsb %80 -%81 = OpISub %5 %82 %83 -%84 = OpCompositeConstruct %44 %16 %16 -%86 = OpExtInst %5 %1 FindUMsb %84 -%85 = OpISub %44 %82 %86 +%7 = OpTypeVector %4 2 +%10 = OpTypeFunction %2 +%11 = OpConstant %4 1.0 +%12 = OpConstant %4 0.0 +%13 = OpConstantNull %5 +%14 = OpTypeInt 32 0 +%15 = OpConstant %14 0 +%16 = OpConstant %6 -1 +%17 = OpConstant %14 1 +%18 = OpConstant %6 0 +%19 = OpConstant %14 4294967295 +%20 = OpConstant %6 1 +%21 = OpConstant %6 2 +%22 = OpConstant %4 2.0 +%23 = OpConstant %6 3 +%24 = OpConstant %6 4 +%32 = OpConstantComposite %3 %12 %12 %12 %12 +%33 = OpConstantComposite %3 %11 %11 %11 %11 +%36 = OpConstantNull %6 +%49 = OpTypeVector %14 2 +%59 = OpConstant %14 32 +%69 = OpConstantComposite %49 %59 %59 +%81 = OpConstant %6 31 +%87 = OpConstantComposite %5 %81 %81 +%9 = OpFunction %2 None %10 +%8 = OpLabel +OpBranch %25 +%25 = OpLabel +%26 = OpCompositeConstruct %3 %12 %12 %12 %12 +%27 = OpExtInst %4 %1 Degrees %11 +%28 = OpExtInst %4 %1 Radians %11 +%29 = OpExtInst %3 %1 Degrees %26 +%30 = OpExtInst %3 %1 Radians %26 +%31 = OpExtInst %3 %1 FClamp %26 %32 %33 +%34 = OpExtInst %3 %1 Refract %26 %26 %11 +%37 = OpCompositeExtract %6 %13 0 +%38 = OpCompositeExtract %6 %13 0 +%39 = OpIMul %6 %37 %38 +%40 = OpIAdd %6 %36 %39 +%41 = OpCompositeExtract %6 %13 1 +%42 = OpCompositeExtract %6 %13 1 +%43 = OpIMul %6 %41 %42 +%35 = OpIAdd %6 %40 %43 +%44 = OpCopyObject %14 %15 +%45 = OpExtInst %14 %1 FindUMsb %44 +%46 = OpExtInst %6 %1 FindSMsb %16 +%47 = OpCompositeConstruct %5 %16 %16 +%48 = OpExtInst %5 %1 FindSMsb %47 +%50 = OpCompositeConstruct %49 %17 %17 +%51 = OpExtInst %49 %1 FindUMsb %50 +%52 = OpExtInst %6 %1 FindILsb %16 +%53 = OpExtInst %14 %1 FindILsb %17 +%54 = OpCompositeConstruct %5 %16 %16 +%55 = OpExtInst %5 %1 FindILsb %54 +%56 = OpCompositeConstruct %49 %17 %17 +%57 = OpExtInst %49 %1 FindILsb %56 +%60 = OpExtInst %14 %1 FindILsb %15 +%58 = OpExtInst %14 %1 UMin %59 %60 +%62 = OpExtInst %6 %1 FindILsb %18 +%61 = OpExtInst %6 %1 UMin %59 %62 +%64 = OpExtInst %14 %1 FindILsb %19 +%63 = OpExtInst %14 %1 UMin %59 %64 +%66 = OpExtInst %6 %1 FindILsb %16 +%65 = OpExtInst %6 %1 UMin %59 %66 +%67 = OpCompositeConstruct %49 %15 %15 +%70 = OpExtInst %49 %1 FindILsb %67 +%68 = OpExtInst %49 %1 UMin %69 %70 +%71 = OpCompositeConstruct %5 %18 %18 +%73 = OpExtInst %5 %1 FindILsb %71 +%72 = OpExtInst %5 %1 UMin %69 %73 +%74 = OpCompositeConstruct %49 %17 %17 +%76 = OpExtInst %49 %1 FindILsb %74 +%75 = OpExtInst %49 %1 UMin %69 %76 +%77 = OpCompositeConstruct %5 %20 %20 +%79 = OpExtInst %5 %1 FindILsb %77 +%78 = OpExtInst %5 %1 UMin %69 %79 +%82 = OpExtInst %6 %1 FindUMsb %16 +%80 = OpISub %6 %81 %82 +%84 = OpExtInst %6 %1 FindUMsb %17 +%83 = OpISub %14 %81 %84 +%85 = OpCompositeConstruct %5 %16 %16 +%88 = OpExtInst %5 %1 FindUMsb %85 +%86 = OpISub %5 %87 %88 +%89 = OpCompositeConstruct %49 %17 %17 +%91 = OpExtInst %5 %1 FindUMsb %89 +%90 = OpISub %49 %87 %91 +%92 = OpExtInst %4 %1 Ldexp %11 %21 +%93 = OpCompositeConstruct %7 %11 %22 +%94 = OpCompositeConstruct %5 %23 %24 +%95 = OpExtInst %7 %1 Ldexp %93 %94 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions-frag.wgsl b/tests/out/wgsl/math-functions-frag.wgsl index 0b5957038..138bdbf24 100644 --- a/tests/out/wgsl/math-functions-frag.wgsl +++ b/tests/out/wgsl/math-functions-frag.wgsl @@ -42,6 +42,7 @@ fn main_1() { var outerProductOut: mat4x4; var distanceOut: f32; var stepOut: vec4; + var ldexpOut: f32; var rad: vec4; var deg: f32; var smoothStepScalar: f32; @@ -152,11 +153,15 @@ fn main_1() { let _e225 = a; let _e226 = b; stepOut = step(_e225, _e226); - let _e230 = a; - rad = radians(_e230); - let _e233 = a; - let _e235 = a; - deg = degrees(_e235.x); + let _e229 = a; + let _e232 = a; + let _e234 = i; + ldexpOut = ldexp(_e232.x, _e234); + let _e238 = a; + rad = radians(_e238); + let _e241 = a; + let _e243 = a; + deg = degrees(_e243.x); smoothStepScalar = smoothstep(0.0, 1.0, 0.5); smoothStepVector = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); smoothStepMixed = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 5faccba7b..5cdab8cdb 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -28,4 +28,6 @@ fn main() { let clz_b = countLeadingZeros(1u); let clz_c = countLeadingZeros(vec2(-1)); let clz_d = countLeadingZeros(vec2(1u)); + let lde_a = ldexp(1.0, 2); + let lde_b = ldexp(vec2(1.0, 2.0), vec2(3, 4)); } From 5329aa2bd5e8b9df413dfb3a862bc2994021c5be Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Sat, 2 Sep 2023 08:55:35 +0200 Subject: [PATCH 2067/2212] [wgsl-in] Handle modf and frexp (#2454) --- src/back/glsl/keywords.rs | 3 + src/back/glsl/mod.rs | 54 +++- src/back/hlsl/help.rs | 53 ++++ src/back/hlsl/keywords.rs | 3 + src/back/hlsl/writer.rs | 9 +- src/back/msl/keywords.rs | 2 + src/back/msl/writer.rs | 61 ++++- src/back/spv/block.rs | 4 +- src/back/wgsl/writer.rs | 22 +- src/front/type_gen.rs | 248 ++++++++++++++---- src/front/wgsl/lower/mod.rs | 29 +- src/front/wgsl/tests.rs | 5 +- src/lib.rs | 31 +++ src/proc/mod.rs | 4 +- src/proc/typifier.rs | 27 +- src/valid/expression.rs | 40 +-- tests/in/math-functions.wgsl | 10 + .../glsl/math-functions.main.Fragment.glsl | 60 +++++ tests/out/hlsl/math-functions.hlsl | 75 ++++++ tests/out/ir/access.ron | 1 + tests/out/ir/collatz.ron | 1 + tests/out/ir/shadow.ron | 1 + tests/out/msl/math-functions.msl | 60 +++++ tests/out/spv/math-functions.spvasm | 225 +++++++++------- tests/out/wgsl/atomicCompareExchange.wgsl | 10 - tests/out/wgsl/math-functions.wgsl | 10 + 26 files changed, 843 insertions(+), 205 deletions(-) diff --git a/src/back/glsl/keywords.rs b/src/back/glsl/keywords.rs index 9679020a0..afadd6e7f 100644 --- a/src/back/glsl/keywords.rs +++ b/src/back/glsl/keywords.rs @@ -477,4 +477,7 @@ pub const RESERVED_KEYWORDS: &[&str] = &[ // entry point name (should not be shadowed) // "main", + // Naga utilities: + super::MODF_FUNCTION, + super::FREXP_FUNCTION, ]; diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 4b732a603..54d5f341a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -72,6 +72,9 @@ pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; /// of detail for bounds checking in `ImageLoad` const CLAMPED_LOD_SUFFIX: &str = "_clamped_lod"; +pub(crate) const MODF_FUNCTION: &str = "naga_modf"; +pub(crate) const FREXP_FUNCTION: &str = "naga_frexp"; + /// Mapping between resources and bindings. pub type BindingMap = std::collections::BTreeMap; @@ -631,6 +634,53 @@ impl<'a, W: Write> Writer<'a, W> { } } + // Write functions to create special types. + for (type_key, struct_ty) in self.module.special_types.predeclared_types.iter() { + match type_key { + &crate::PredeclaredType::ModfResult { size, width } + | &crate::PredeclaredType::FrexpResult { size, width } => { + let arg_type_name_owner; + let arg_type_name = if let Some(size) = size { + arg_type_name_owner = + format!("{}vec{}", if width == 8 { "d" } else { "" }, size as u8); + &arg_type_name_owner + } else if width == 8 { + "double" + } else { + "float" + }; + + let other_type_name_owner; + let (defined_func_name, called_func_name, other_type_name) = + if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) { + (MODF_FUNCTION, "modf", arg_type_name) + } else { + let other_type_name = if let Some(size) = size { + other_type_name_owner = format!("ivec{}", size as u8); + &other_type_name_owner + } else { + "int" + }; + (FREXP_FUNCTION, "frexp", other_type_name) + }; + + let struct_name = &self.names[&NameKey::Type(*struct_ty)]; + + writeln!(self.out)?; + writeln!( + self.out, + "{} {defined_func_name}({arg_type_name} arg) {{ + {other_type_name} other; + {arg_type_name} fract = {called_func_name}(arg, other); + return {}(fract, other); +}}", + struct_name, struct_name + )?; + } + &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {} + } + } + // Write all named constants let mut constants = self .module @@ -2997,8 +3047,8 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Round => "roundEven", Mf::Fract => "fract", Mf::Trunc => "trunc", - Mf::Modf => "modf", - Mf::Frexp => "frexp", + Mf::Modf => MODF_FUNCTION, + Mf::Frexp => FREXP_FUNCTION, Mf::Ldexp => "ldexp", // exponent Mf::Exp => "exp", diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 7ad463131..2d725514b 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -781,6 +781,59 @@ impl<'a, W: Write> super::Writer<'a, W> { Ok(()) } + /// Write functions to create special types. + pub(super) fn write_special_functions(&mut self, module: &crate::Module) -> BackendResult { + for (type_key, struct_ty) in module.special_types.predeclared_types.iter() { + match type_key { + &crate::PredeclaredType::ModfResult { size, width } + | &crate::PredeclaredType::FrexpResult { size, width } => { + let arg_type_name_owner; + let arg_type_name = if let Some(size) = size { + arg_type_name_owner = format!( + "{}{}", + if width == 8 { "double" } else { "float" }, + size as u8 + ); + &arg_type_name_owner + } else if width == 8 { + "double" + } else { + "float" + }; + + let (defined_func_name, called_func_name, second_field_name, sign_multiplier) = + if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) { + (super::writer::MODF_FUNCTION, "modf", "whole", "") + } else { + ( + super::writer::FREXP_FUNCTION, + "frexp", + "exp_", + "sign(arg) * ", + ) + }; + + let struct_name = &self.names[&NameKey::Type(*struct_ty)]; + + writeln!( + self.out, + "{struct_name} {defined_func_name}({arg_type_name} arg) {{ + {arg_type_name} other; + {struct_name} result; + result.fract = {sign_multiplier}{called_func_name}(arg, other); + result.{second_field_name} = other; + return result; +}}" + )?; + writeln!(self.out)?; + } + &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {} + } + } + + Ok(()) + } + /// Helper function that writes compose wrapped functions pub(super) fn write_wrapped_compose_functions( &mut self, diff --git a/src/back/hlsl/keywords.rs b/src/back/hlsl/keywords.rs index 81b797bbf..059e533ff 100644 --- a/src/back/hlsl/keywords.rs +++ b/src/back/hlsl/keywords.rs @@ -814,6 +814,9 @@ pub const RESERVED: &[&str] = &[ "TextureBuffer", "ConstantBuffer", "RayQuery", + // Naga utilities + super::writer::MODF_FUNCTION, + super::writer::FREXP_FUNCTION, ]; // DXC scalar types, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/tools/clang/lib/AST/ASTContextHLSL.cpp#L48-L254 diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index c37334b60..6da98502f 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -17,6 +17,9 @@ const SPECIAL_BASE_VERTEX: &str = "base_vertex"; const SPECIAL_BASE_INSTANCE: &str = "base_instance"; const SPECIAL_OTHER: &str = "other"; +pub(crate) const MODF_FUNCTION: &str = "naga_modf"; +pub(crate) const FREXP_FUNCTION: &str = "naga_frexp"; + struct EpStructMember { name: String, ty: Handle, @@ -244,6 +247,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } + self.write_special_functions(module)?; + self.write_wrapped_compose_functions(module, &module.const_expressions)?; // Write all named constants @@ -2675,8 +2680,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::Round => Function::Regular("round"), Mf::Fract => Function::Regular("frac"), Mf::Trunc => Function::Regular("trunc"), - Mf::Modf => Function::Regular("modf"), - Mf::Frexp => Function::Regular("frexp"), + Mf::Modf => Function::Regular(MODF_FUNCTION), + Mf::Frexp => Function::Regular(FREXP_FUNCTION), Mf::Ldexp => Function::Regular("ldexp"), // exponent Mf::Exp => Function::Regular("exp"), diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs index a3a9c52dc..f34b618db 100644 --- a/src/back/msl/keywords.rs +++ b/src/back/msl/keywords.rs @@ -214,4 +214,6 @@ pub const RESERVED: &[&str] = &[ // Naga utilities "DefaultConstructible", "clamped_lod_e", + super::writer::FREXP_FUNCTION, + super::writer::MODF_FUNCTION, ]; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index a8a103e6d..24c54ff8a 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -32,6 +32,9 @@ const RAY_QUERY_FIELD_INTERSECTION: &str = "intersection"; const RAY_QUERY_FIELD_READY: &str = "ready"; const RAY_QUERY_FUN_MAP_INTERSECTION: &str = "_map_intersection_type"; +pub(crate) const MODF_FUNCTION: &str = "naga_modf"; +pub(crate) const FREXP_FUNCTION: &str = "naga_frexp"; + /// Write the Metal name for a Naga numeric type: scalar, vector, or matrix. /// /// The `sizes` slice determines whether this function writes a @@ -1678,8 +1681,8 @@ impl Writer { Mf::Round => "rint", Mf::Fract => "fract", Mf::Trunc => "trunc", - Mf::Modf => "modf", - Mf::Frexp => "frexp", + Mf::Modf => MODF_FUNCTION, + Mf::Frexp => FREXP_FUNCTION, Mf::Ldexp => "ldexp", // exponent Mf::Exp => "exp", @@ -1813,6 +1816,9 @@ impl Writer { write!(self.out, "((")?; self.put_expression(arg, context, false)?; write!(self.out, ") * 57.295779513082322865)")?; + } else if fun == Mf::Modf || fun == Mf::Frexp { + write!(self.out, "{fun_name}")?; + self.put_call_parameters(iter::once(arg), context)?; } else { write!(self.out, "{NAMESPACE}::{fun_name}")?; self.put_call_parameters( @@ -3236,6 +3242,57 @@ impl Writer { } } } + + // Write functions to create special types. + for (type_key, struct_ty) in module.special_types.predeclared_types.iter() { + match type_key { + &crate::PredeclaredType::ModfResult { size, width } + | &crate::PredeclaredType::FrexpResult { size, width } => { + let arg_type_name_owner; + let arg_type_name = if let Some(size) = size { + arg_type_name_owner = format!( + "{NAMESPACE}::{}{}", + if width == 8 { "double" } else { "float" }, + size as u8 + ); + &arg_type_name_owner + } else if width == 8 { + "double" + } else { + "float" + }; + + let other_type_name_owner; + let (defined_func_name, called_func_name, other_type_name) = + if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) { + (MODF_FUNCTION, "modf", arg_type_name) + } else { + let other_type_name = if let Some(size) = size { + other_type_name_owner = format!("int{}", size as u8); + &other_type_name_owner + } else { + "int" + }; + (FREXP_FUNCTION, "frexp", other_type_name) + }; + + let struct_name = &self.names[&NameKey::Type(*struct_ty)]; + + writeln!(self.out)?; + writeln!( + self.out, + "{} {defined_func_name}({arg_type_name} arg) {{ + {other_type_name} other; + {arg_type_name} fract = {NAMESPACE}::{called_func_name}(arg, other); + return {}{{ fract, other }}; +}}", + struct_name, struct_name + )?; + } + &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {} + } + } + Ok(()) } diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 11841bc52..c5246ad19 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -787,8 +787,8 @@ impl<'w> BlockContext<'w> { Mf::Floor => MathOp::Ext(spirv::GLOp::Floor), Mf::Fract => MathOp::Ext(spirv::GLOp::Fract), Mf::Trunc => MathOp::Ext(spirv::GLOp::Trunc), - Mf::Modf => MathOp::Ext(spirv::GLOp::Modf), - Mf::Frexp => MathOp::Ext(spirv::GLOp::Frexp), + Mf::Modf => MathOp::Ext(spirv::GLOp::ModfStruct), + Mf::Frexp => MathOp::Ext(spirv::GLOp::FrexpStruct), Mf::Ldexp => MathOp::Ext(spirv::GLOp::Ldexp), // geometry Mf::Dot => match *self.fun_info[arg].ty.inner_with(&self.ir_module.types) { diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 43d094ec2..da39cd94f 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -97,6 +97,14 @@ impl Writer { self.ep_results.clear(); } + fn is_builtin_wgsl_struct(&self, module: &Module, handle: Handle) -> bool { + module + .special_types + .predeclared_types + .values() + .any(|t| *t == handle) + } + pub fn write(&mut self, module: &Module, info: &valid::ModuleInfo) -> BackendResult { self.reset(module); @@ -109,13 +117,13 @@ impl Writer { // Write all structs for (handle, ty) in module.types.iter() { - if let TypeInner::Struct { - ref members, - span: _, - } = ty.inner - { - self.write_struct(module, handle, members)?; - writeln!(self.out)?; + if let TypeInner::Struct { ref members, .. } = ty.inner { + { + if !self.is_builtin_wgsl_struct(module, handle) { + self.write_struct(module, handle, members)?; + writeln!(self.out)?; + } + } } } diff --git a/src/front/type_gen.rs b/src/front/type_gen.rs index 1ee454c44..0c608504c 100644 --- a/src/front/type_gen.rs +++ b/src/front/type_gen.rs @@ -5,55 +5,6 @@ Type generators. use crate::{arena::Handle, span::Span}; impl crate::Module { - pub fn generate_atomic_compare_exchange_result( - &mut self, - kind: crate::ScalarKind, - width: crate::Bytes, - ) -> Handle { - let bool_ty = self.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: crate::BOOL_WIDTH, - }, - }, - Span::UNDEFINED, - ); - let scalar_ty = self.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { kind, width }, - }, - Span::UNDEFINED, - ); - - self.types.insert( - crate::Type { - name: Some(format!( - "__atomic_compare_exchange_result<{kind:?},{width}>" - )), - inner: crate::TypeInner::Struct { - members: vec![ - crate::StructMember { - name: Some("old_value".to_string()), - ty: scalar_ty, - binding: None, - offset: 0, - }, - crate::StructMember { - name: Some("exchanged".to_string()), - ty: bool_ty, - binding: None, - offset: 4, - }, - ], - span: 8, - }, - }, - Span::UNDEFINED, - ) - } /// Populate this module's [`SpecialTypes::ray_desc`] type. /// /// [`SpecialTypes::ray_desc`] is the type of the [`descriptor`] operand of @@ -311,4 +262,203 @@ impl crate::Module { self.special_types.ray_intersection = Some(handle); handle } + + /// Populate this module's [`SpecialTypes::predeclared_types`] type and return the handle. + /// + /// [`SpecialTypes::predeclared_types`]: crate::SpecialTypes::predeclared_types + pub fn generate_predeclared_type( + &mut self, + special_type: crate::PredeclaredType, + ) -> Handle { + use std::fmt::Write; + + if let Some(value) = self.special_types.predeclared_types.get(&special_type) { + return *value; + } + + let ty = match special_type { + crate::PredeclaredType::AtomicCompareExchangeWeakResult { kind, width } => { + let bool_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }, + }, + Span::UNDEFINED, + ); + let scalar_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind, width }, + }, + Span::UNDEFINED, + ); + + crate::Type { + name: Some(format!( + "__atomic_compare_exchange_result<{kind:?},{width}>" + )), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("old_value".to_string()), + ty: scalar_ty, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("exchanged".to_string()), + ty: bool_ty, + binding: None, + offset: 4, + }, + ], + span: 8, + }, + } + } + crate::PredeclaredType::ModfResult { size, width } => { + let float_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width, + }, + }, + Span::UNDEFINED, + ); + + let (member_ty, second_offset) = if let Some(size) = size { + let vec_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + size, + kind: crate::ScalarKind::Float, + width, + }, + }, + Span::UNDEFINED, + ); + (vec_ty, size as u32 * width as u32) + } else { + (float_ty, width as u32) + }; + + let mut type_name = "__modf_result_".to_string(); + if let Some(size) = size { + let _ = write!(type_name, "vec{}_", size as u8); + } + let _ = write!(type_name, "f{}", width * 8); + + crate::Type { + name: Some(type_name), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("fract".to_string()), + ty: member_ty, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("whole".to_string()), + ty: member_ty, + binding: None, + offset: second_offset, + }, + ], + span: second_offset * 2, + }, + } + } + crate::PredeclaredType::FrexpResult { size, width } => { + let float_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Float, + width, + }, + }, + Span::UNDEFINED, + ); + + let int_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Sint, + width, + }, + }, + Span::UNDEFINED, + ); + + let (fract_member_ty, exp_member_ty, second_offset) = if let Some(size) = size { + let vec_float_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + size, + kind: crate::ScalarKind::Float, + width, + }, + }, + Span::UNDEFINED, + ); + let vec_int_ty = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + size, + kind: crate::ScalarKind::Sint, + width, + }, + }, + Span::UNDEFINED, + ); + (vec_float_ty, vec_int_ty, size as u32 * width as u32) + } else { + (float_ty, int_ty, width as u32) + }; + + let mut type_name = "__frexp_result_".to_string(); + if let Some(size) = size { + let _ = write!(type_name, "vec{}_", size as u8); + } + let _ = write!(type_name, "f{}", width * 8); + + crate::Type { + name: Some(type_name), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("fract".to_string()), + ty: fract_member_ty, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("exp".to_string()), + ty: exp_member_ty, + binding: None, + offset: second_offset, + }, + ], + span: second_offset * 2, + }, + } + } + }; + + let handle = self.types.insert(ty, Span::UNDEFINED); + self.special_types + .predeclared_types + .insert(special_type, handle); + handle + } } diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 23d328236..64ef43cb9 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1745,6 +1745,25 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args.finish()?; + if fun == crate::MathFunction::Modf || fun == crate::MathFunction::Frexp { + ctx.grow_types(arg)?; + if let Some((size, width)) = match *ctx.resolved_inner(arg) { + crate::TypeInner::Scalar { width, .. } => Some((None, width)), + crate::TypeInner::Vector { size, width, .. } => { + Some((Some(size), width)) + } + _ => None, + } { + ctx.module.generate_predeclared_type( + if fun == crate::MathFunction::Modf { + crate::PredeclaredType::ModfResult { size, width } + } else { + crate::PredeclaredType::FrexpResult { size, width } + }, + ); + } + } + crate::Expression::Math { fun, arg, @@ -1880,10 +1899,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let expression = match *ctx.resolved_inner(value) { crate::TypeInner::Scalar { kind, width } => { crate::Expression::AtomicResult { - //TODO: cache this to avoid generating duplicate types - ty: ctx - .module - .generate_atomic_compare_exchange_result(kind, width), + ty: ctx.module.generate_predeclared_type( + crate::PredeclaredType::AtomicCompareExchangeWeakResult { + kind, + width, + }, + ), comparison: true, } } diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 09a4356b0..828f1e3c7 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -456,10 +456,11 @@ fn binary_expression_mixed_scalar_and_vector_operands() { #[test] fn parse_pointers() { parse_str( - "fn foo() { + "fn foo(a: ptr) -> f32 { return *a; } + fn bar() { var x: f32 = 1.0; let px = &x; - let py = frexp(0.5, px); + let py = foo(px); }", ) .unwrap(); diff --git a/src/lib.rs b/src/lib.rs index fdea215e3..49fd9d4e5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1945,6 +1945,31 @@ pub struct EntryPoint { pub function: Function, } +/// Return types predeclared for the frexp, modf, and atomicCompareExchangeWeak built-in functions. +/// +/// These cannot be spelled in WGSL source. +/// +/// Stored in [`SpecialTypes::predeclared_types`] and created by [`Module::generate_predeclared_type`]. +#[derive(Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "clone", derive(Clone))] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +pub enum PredeclaredType { + AtomicCompareExchangeWeakResult { + kind: ScalarKind, + width: Bytes, + }, + ModfResult { + size: Option, + width: Bytes, + }, + FrexpResult { + size: Option, + width: Bytes, + }, +} + /// Set of special types that can be optionally generated by the frontends. #[derive(Debug, Default)] #[cfg_attr(feature = "clone", derive(Clone))] @@ -1963,6 +1988,12 @@ pub struct SpecialTypes { /// Call [`Module::generate_ray_intersection_type`] to populate /// this if needed and return the handle. pub ray_intersection: Option>, + + /// Types for predeclared wgsl types instantiated on demand. + /// + /// Call [`Module::generate_predeclared_type`] to populate this if + /// needed and return the handle. + pub predeclared_types: indexmap::IndexMap>, } /// Shader module. diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 582c88703..bfb2b0d7a 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -375,8 +375,8 @@ impl super::MathFunction { Self::Round => 1, Self::Fract => 1, Self::Trunc => 1, - Self::Modf => 2, - Self::Frexp => 2, + Self::Modf => 1, + Self::Frexp => 1, Self::Ldexp => 2, // exponent Self::Exp => 1, diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 6b79e0ead..a6130ad79 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -706,8 +706,6 @@ impl<'a> ResolveContext<'a> { Mf::Round | Mf::Fract | Mf::Trunc | - Mf::Modf | - Mf::Frexp | Mf::Ldexp | // exponent Mf::Exp | @@ -715,6 +713,31 @@ impl<'a> ResolveContext<'a> { Mf::Log | Mf::Log2 | Mf::Pow => res_arg.clone(), + Mf::Modf | Mf::Frexp => { + let (size, width) = match res_arg.inner_with(types) { + &Ti::Scalar { + kind: crate::ScalarKind::Float, + width, + } => (None, width), + &Ti::Vector { + kind: crate::ScalarKind::Float, + size, + width, + } => (Some(size), width), + ref other => + return Err(ResolveError::IncompatibleOperands(format!("{fun:?}({other:?}, _)"))) + }; + let result = self + .special_types + .predeclared_types + .get(&if fun == Mf::Modf { + crate::PredeclaredType::ModfResult { size, width } + } else { + crate::PredeclaredType::FrexpResult { size, width } + }) + .ok_or(ResolveError::MissingSpecialType)?; + TypeResolution::Handle(*result) + }, // geometry Mf::Dot => match *res_arg.inner_with(types) { Ti::Vector { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index f0131c1df..548b6c145 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1015,38 +1015,20 @@ impl super::Validator { } } Mf::Modf | Mf::Frexp => { - let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { - (Some(ty1), None, None) => ty1, - _ => return Err(ExpressionError::WrongArgumentCount(fun)), - }; - let (size0, width0) = match *arg_ty { + if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + if !matches!( + *arg_ty, Ti::Scalar { kind: Sk::Float, - width, - } => (None, width), - Ti::Vector { + .. + } | Ti::Vector { kind: Sk::Float, - size, - width, - } => (Some(size), width), - _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), - }; - let good = match *arg1_ty { - Ti::Pointer { base, space: _ } => module.types[base].inner == *arg_ty, - Ti::ValuePointer { - size, - kind: Sk::Float, - width, - space: _, - } => size == size0 && width == width0, - _ => false, - }; - if !good { - return Err(ExpressionError::InvalidArgumentType( - fun, - 1, - arg1.unwrap(), - )); + .. + }, + ) { + return Err(ExpressionError::InvalidArgumentType(fun, 1, arg)); } } Mf::Ldexp => { diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index afc90811c..408f8a74f 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -31,4 +31,14 @@ fn main() { let clz_d = countLeadingZeros(vec2(1u)); let lde_a = ldexp(1.0, 2); let lde_b = ldexp(vec2(1.0, 2.0), vec2(3, 4)); + let modf_a = modf(1.5); + let modf_b = modf(1.5).fract; + let modf_c = modf(1.5).whole; + let modf_d = modf(vec2(1.5, 1.5)); + let modf_e = modf(vec4(1.5, 1.5, 1.5, 1.5)).whole.x; + let modf_f: f32 = modf(vec2(1.5, 1.5)).fract.y; + let frexp_a = frexp(1.5); + let frexp_b = frexp(1.5).fract; + let frexp_c: i32 = frexp(1.5).exp; + let frexp_d: i32 = frexp(vec4(1.5, 1.5, 1.5, 1.5)).exp.x; } diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl index 02cafcea0..be81715ce 100644 --- a/tests/out/glsl/math-functions.main.Fragment.glsl +++ b/tests/out/glsl/math-functions.main.Fragment.glsl @@ -3,6 +3,56 @@ precision highp float; precision highp int; +struct __modf_result_f32_ { + float fract_; + float whole; +}; +struct __modf_result_vec2_f32_ { + vec2 fract_; + vec2 whole; +}; +struct __modf_result_vec4_f32_ { + vec4 fract_; + vec4 whole; +}; +struct __frexp_result_f32_ { + float fract_; + int exp_; +}; +struct __frexp_result_vec4_f32_ { + vec4 fract_; + ivec4 exp_; +}; + +__modf_result_f32_ naga_modf(float arg) { + float other; + float fract = modf(arg, other); + return __modf_result_f32_(fract, other); +} + +__modf_result_vec2_f32_ naga_modf(vec2 arg) { + vec2 other; + vec2 fract = modf(arg, other); + return __modf_result_vec2_f32_(fract, other); +} + +__modf_result_vec4_f32_ naga_modf(vec4 arg) { + vec4 other; + vec4 fract = modf(arg, other); + return __modf_result_vec4_f32_(fract, other); +} + +__frexp_result_f32_ naga_frexp(float arg) { + int other; + float fract = frexp(arg, other); + return __frexp_result_f32_(fract, other); +} + +__frexp_result_vec4_f32_ naga_frexp(vec4 arg) { + ivec4 other; + vec4 fract = frexp(arg, other); + return __frexp_result_vec4_f32_(fract, other); +} void main() { vec4 v = vec4(0.0); @@ -36,5 +86,15 @@ void main() { uvec2 clz_d = uvec2(ivec2(31) - findMSB(uvec2(1u))); float lde_a = ldexp(1.0, 2); vec2 lde_b = ldexp(vec2(1.0, 2.0), ivec2(3, 4)); + __modf_result_f32_ modf_a = naga_modf(1.5); + float modf_b = naga_modf(1.5).fract_; + float modf_c = naga_modf(1.5).whole; + __modf_result_vec2_f32_ modf_d = naga_modf(vec2(1.5, 1.5)); + float modf_e = naga_modf(vec4(1.5, 1.5, 1.5, 1.5)).whole.x; + float modf_f = naga_modf(vec2(1.5, 1.5)).fract_.y; + __frexp_result_f32_ frexp_a = naga_frexp(1.5); + float frexp_b = naga_frexp(1.5).fract_; + int frexp_c = naga_frexp(1.5).exp_; + int frexp_d = naga_frexp(vec4(1.5, 1.5, 1.5, 1.5)).exp_.x; } diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index 3061a3ac1..afdc6f467 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -1,3 +1,68 @@ +struct __modf_result_f32_ { + float fract; + float whole; +}; + +struct __modf_result_vec2_f32_ { + float2 fract; + float2 whole; +}; + +struct __modf_result_vec4_f32_ { + float4 fract; + float4 whole; +}; + +struct __frexp_result_f32_ { + float fract; + int exp_; +}; + +struct __frexp_result_vec4_f32_ { + float4 fract; + int4 exp_; +}; + +__modf_result_f32_ naga_modf(float arg) { + float other; + __modf_result_f32_ result; + result.fract = modf(arg, other); + result.whole = other; + return result; +} + +__modf_result_vec2_f32_ naga_modf(float2 arg) { + float2 other; + __modf_result_vec2_f32_ result; + result.fract = modf(arg, other); + result.whole = other; + return result; +} + +__modf_result_vec4_f32_ naga_modf(float4 arg) { + float4 other; + __modf_result_vec4_f32_ result; + result.fract = modf(arg, other); + result.whole = other; + return result; +} + +__frexp_result_f32_ naga_frexp(float arg) { + float other; + __frexp_result_f32_ result; + result.fract = sign(arg) * frexp(arg, other); + result.exp_ = other; + return result; +} + +__frexp_result_vec4_f32_ naga_frexp(float4 arg) { + float4 other; + __frexp_result_vec4_f32_ result; + result.fract = sign(arg) * frexp(arg, other); + result.exp_ = other; + return result; +} + void main() { float4 v = (0.0).xxxx; @@ -31,4 +96,14 @@ void main() uint2 clz_d = ((31u).xx - firstbithigh((1u).xx)); float lde_a = ldexp(1.0, 2); float2 lde_b = ldexp(float2(1.0, 2.0), int2(3, 4)); + __modf_result_f32_ modf_a = naga_modf(1.5); + float modf_b = naga_modf(1.5).fract; + float modf_c = naga_modf(1.5).whole; + __modf_result_vec2_f32_ modf_d = naga_modf(float2(1.5, 1.5)); + float modf_e = naga_modf(float4(1.5, 1.5, 1.5, 1.5)).whole.x; + float modf_f = naga_modf(float2(1.5, 1.5)).fract.y; + __frexp_result_f32_ frexp_a = naga_frexp(1.5); + float frexp_b = naga_frexp(1.5).fract; + int frexp_c = naga_frexp(1.5).exp_; + int frexp_d = naga_frexp(float4(1.5, 1.5, 1.5, 1.5)).exp_.x; } diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 5cda4104c..a200e75a9 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -334,6 +334,7 @@ special_types: ( ray_desc: None, ray_intersection: None, + predeclared_types: {}, ), constants: [], global_variables: [ diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 6451fc715..fb8ff825e 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -41,6 +41,7 @@ special_types: ( ray_desc: None, ray_intersection: None, + predeclared_types: {}, ), constants: [], global_variables: [ diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index 9ae5af000..bfde76d6a 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -266,6 +266,7 @@ special_types: ( ray_desc: None, ray_intersection: None, + predeclared_types: {}, ), constants: [ ( diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 1f22ae81d..14824ec30 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -4,6 +4,56 @@ using metal::uint; +struct __modf_result_f32_ { + float fract; + float whole; +}; +struct __modf_result_vec2_f32_ { + metal::float2 fract; + metal::float2 whole; +}; +struct __modf_result_vec4_f32_ { + metal::float4 fract; + metal::float4 whole; +}; +struct __frexp_result_f32_ { + float fract; + int exp; +}; +struct __frexp_result_vec4_f32_ { + metal::float4 fract; + metal::int4 exp; +}; + +__modf_result_f32_ naga_modf(float arg) { + float other; + float fract = metal::modf(arg, other); + return __modf_result_f32_{ fract, other }; +} + +__modf_result_vec2_f32_ naga_modf(metal::float2 arg) { + metal::float2 other; + metal::float2 fract = metal::modf(arg, other); + return __modf_result_vec2_f32_{ fract, other }; +} + +__modf_result_vec4_f32_ naga_modf(metal::float4 arg) { + metal::float4 other; + metal::float4 fract = metal::modf(arg, other); + return __modf_result_vec4_f32_{ fract, other }; +} + +__frexp_result_f32_ naga_frexp(float arg) { + int other; + float fract = metal::frexp(arg, other); + return __frexp_result_f32_{ fract, other }; +} + +__frexp_result_vec4_f32_ naga_frexp(metal::float4 arg) { + int4 other; + metal::float4 fract = metal::frexp(arg, other); + return __frexp_result_vec4_f32_{ fract, other }; +} fragment void main_( ) { @@ -40,4 +90,14 @@ fragment void main_( metal::uint2 clz_d = metal::clz(metal::uint2(1u)); float lde_a = metal::ldexp(1.0, 2); metal::float2 lde_b = metal::ldexp(metal::float2(1.0, 2.0), metal::int2(3, 4)); + __modf_result_f32_ modf_a = naga_modf(1.5); + float modf_b = naga_modf(1.5).fract; + float modf_c = naga_modf(1.5).whole; + __modf_result_vec2_f32_ modf_d = naga_modf(metal::float2(1.5, 1.5)); + float modf_e = naga_modf(metal::float4(1.5, 1.5, 1.5, 1.5)).whole.x; + float modf_f = naga_modf(metal::float2(1.5, 1.5)).fract.y; + __frexp_result_f32_ frexp_a = naga_frexp(1.5); + float frexp_b = naga_frexp(1.5).fract; + int frexp_c = naga_frexp(1.5).exp; + int frexp_d = naga_frexp(metal::float4(1.5, 1.5, 1.5, 1.5)).exp.x; } diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index b3a32bce3..260c3b4bd 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,106 +1,147 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 96 +; Bound: 127 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %9 "main" -OpExecutionMode %9 OriginUpperLeft +OpEntryPoint Fragment %15 "main" +OpExecutionMode %15 OriginUpperLeft +OpMemberDecorate %8 0 Offset 0 +OpMemberDecorate %8 1 Offset 4 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 8 +OpMemberDecorate %10 0 Offset 0 +OpMemberDecorate %10 1 Offset 16 +OpMemberDecorate %11 0 Offset 0 +OpMemberDecorate %11 1 Offset 4 +OpMemberDecorate %13 0 Offset 0 +OpMemberDecorate %13 1 Offset 16 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 %6 = OpTypeInt 32 1 %5 = OpTypeVector %6 2 %7 = OpTypeVector %4 2 -%10 = OpTypeFunction %2 -%11 = OpConstant %4 1.0 -%12 = OpConstant %4 0.0 -%13 = OpConstantNull %5 -%14 = OpTypeInt 32 0 -%15 = OpConstant %14 0 -%16 = OpConstant %6 -1 -%17 = OpConstant %14 1 -%18 = OpConstant %6 0 -%19 = OpConstant %14 4294967295 -%20 = OpConstant %6 1 -%21 = OpConstant %6 2 -%22 = OpConstant %4 2.0 -%23 = OpConstant %6 3 -%24 = OpConstant %6 4 -%32 = OpConstantComposite %3 %12 %12 %12 %12 -%33 = OpConstantComposite %3 %11 %11 %11 %11 -%36 = OpConstantNull %6 -%49 = OpTypeVector %14 2 -%59 = OpConstant %14 32 -%69 = OpConstantComposite %49 %59 %59 -%81 = OpConstant %6 31 -%87 = OpConstantComposite %5 %81 %81 -%9 = OpFunction %2 None %10 -%8 = OpLabel -OpBranch %25 -%25 = OpLabel -%26 = OpCompositeConstruct %3 %12 %12 %12 %12 -%27 = OpExtInst %4 %1 Degrees %11 -%28 = OpExtInst %4 %1 Radians %11 -%29 = OpExtInst %3 %1 Degrees %26 -%30 = OpExtInst %3 %1 Radians %26 -%31 = OpExtInst %3 %1 FClamp %26 %32 %33 -%34 = OpExtInst %3 %1 Refract %26 %26 %11 -%37 = OpCompositeExtract %6 %13 0 -%38 = OpCompositeExtract %6 %13 0 -%39 = OpIMul %6 %37 %38 -%40 = OpIAdd %6 %36 %39 -%41 = OpCompositeExtract %6 %13 1 -%42 = OpCompositeExtract %6 %13 1 -%43 = OpIMul %6 %41 %42 -%35 = OpIAdd %6 %40 %43 -%44 = OpCopyObject %14 %15 -%45 = OpExtInst %14 %1 FindUMsb %44 -%46 = OpExtInst %6 %1 FindSMsb %16 -%47 = OpCompositeConstruct %5 %16 %16 -%48 = OpExtInst %5 %1 FindSMsb %47 -%50 = OpCompositeConstruct %49 %17 %17 -%51 = OpExtInst %49 %1 FindUMsb %50 -%52 = OpExtInst %6 %1 FindILsb %16 -%53 = OpExtInst %14 %1 FindILsb %17 -%54 = OpCompositeConstruct %5 %16 %16 -%55 = OpExtInst %5 %1 FindILsb %54 -%56 = OpCompositeConstruct %49 %17 %17 -%57 = OpExtInst %49 %1 FindILsb %56 -%60 = OpExtInst %14 %1 FindILsb %15 -%58 = OpExtInst %14 %1 UMin %59 %60 -%62 = OpExtInst %6 %1 FindILsb %18 -%61 = OpExtInst %6 %1 UMin %59 %62 -%64 = OpExtInst %14 %1 FindILsb %19 -%63 = OpExtInst %14 %1 UMin %59 %64 -%66 = OpExtInst %6 %1 FindILsb %16 -%65 = OpExtInst %6 %1 UMin %59 %66 -%67 = OpCompositeConstruct %49 %15 %15 -%70 = OpExtInst %49 %1 FindILsb %67 -%68 = OpExtInst %49 %1 UMin %69 %70 -%71 = OpCompositeConstruct %5 %18 %18 -%73 = OpExtInst %5 %1 FindILsb %71 -%72 = OpExtInst %5 %1 UMin %69 %73 -%74 = OpCompositeConstruct %49 %17 %17 -%76 = OpExtInst %49 %1 FindILsb %74 -%75 = OpExtInst %49 %1 UMin %69 %76 -%77 = OpCompositeConstruct %5 %20 %20 -%79 = OpExtInst %5 %1 FindILsb %77 -%78 = OpExtInst %5 %1 UMin %69 %79 -%82 = OpExtInst %6 %1 FindUMsb %16 -%80 = OpISub %6 %81 %82 -%84 = OpExtInst %6 %1 FindUMsb %17 -%83 = OpISub %14 %81 %84 -%85 = OpCompositeConstruct %5 %16 %16 -%88 = OpExtInst %5 %1 FindUMsb %85 -%86 = OpISub %5 %87 %88 -%89 = OpCompositeConstruct %49 %17 %17 -%91 = OpExtInst %5 %1 FindUMsb %89 -%90 = OpISub %49 %87 %91 -%92 = OpExtInst %4 %1 Ldexp %11 %21 -%93 = OpCompositeConstruct %7 %11 %22 -%94 = OpCompositeConstruct %5 %23 %24 -%95 = OpExtInst %7 %1 Ldexp %93 %94 +%8 = OpTypeStruct %4 %4 +%9 = OpTypeStruct %7 %7 +%10 = OpTypeStruct %3 %3 +%11 = OpTypeStruct %4 %6 +%12 = OpTypeVector %6 4 +%13 = OpTypeStruct %3 %12 +%16 = OpTypeFunction %2 +%17 = OpConstant %4 1.0 +%18 = OpConstant %4 0.0 +%19 = OpConstantNull %5 +%20 = OpTypeInt 32 0 +%21 = OpConstant %20 0 +%22 = OpConstant %6 -1 +%23 = OpConstant %20 1 +%24 = OpConstant %6 0 +%25 = OpConstant %20 4294967295 +%26 = OpConstant %6 1 +%27 = OpConstant %6 2 +%28 = OpConstant %4 2.0 +%29 = OpConstant %6 3 +%30 = OpConstant %6 4 +%31 = OpConstant %4 1.5 +%39 = OpConstantComposite %3 %18 %18 %18 %18 +%40 = OpConstantComposite %3 %17 %17 %17 %17 +%43 = OpConstantNull %6 +%56 = OpTypeVector %20 2 +%66 = OpConstant %20 32 +%76 = OpConstantComposite %56 %66 %66 +%88 = OpConstant %6 31 +%94 = OpConstantComposite %5 %88 %88 +%15 = OpFunction %2 None %16 +%14 = OpLabel +OpBranch %32 +%32 = OpLabel +%33 = OpCompositeConstruct %3 %18 %18 %18 %18 +%34 = OpExtInst %4 %1 Degrees %17 +%35 = OpExtInst %4 %1 Radians %17 +%36 = OpExtInst %3 %1 Degrees %33 +%37 = OpExtInst %3 %1 Radians %33 +%38 = OpExtInst %3 %1 FClamp %33 %39 %40 +%41 = OpExtInst %3 %1 Refract %33 %33 %17 +%44 = OpCompositeExtract %6 %19 0 +%45 = OpCompositeExtract %6 %19 0 +%46 = OpIMul %6 %44 %45 +%47 = OpIAdd %6 %43 %46 +%48 = OpCompositeExtract %6 %19 1 +%49 = OpCompositeExtract %6 %19 1 +%50 = OpIMul %6 %48 %49 +%42 = OpIAdd %6 %47 %50 +%51 = OpCopyObject %20 %21 +%52 = OpExtInst %20 %1 FindUMsb %51 +%53 = OpExtInst %6 %1 FindSMsb %22 +%54 = OpCompositeConstruct %5 %22 %22 +%55 = OpExtInst %5 %1 FindSMsb %54 +%57 = OpCompositeConstruct %56 %23 %23 +%58 = OpExtInst %56 %1 FindUMsb %57 +%59 = OpExtInst %6 %1 FindILsb %22 +%60 = OpExtInst %20 %1 FindILsb %23 +%61 = OpCompositeConstruct %5 %22 %22 +%62 = OpExtInst %5 %1 FindILsb %61 +%63 = OpCompositeConstruct %56 %23 %23 +%64 = OpExtInst %56 %1 FindILsb %63 +%67 = OpExtInst %20 %1 FindILsb %21 +%65 = OpExtInst %20 %1 UMin %66 %67 +%69 = OpExtInst %6 %1 FindILsb %24 +%68 = OpExtInst %6 %1 UMin %66 %69 +%71 = OpExtInst %20 %1 FindILsb %25 +%70 = OpExtInst %20 %1 UMin %66 %71 +%73 = OpExtInst %6 %1 FindILsb %22 +%72 = OpExtInst %6 %1 UMin %66 %73 +%74 = OpCompositeConstruct %56 %21 %21 +%77 = OpExtInst %56 %1 FindILsb %74 +%75 = OpExtInst %56 %1 UMin %76 %77 +%78 = OpCompositeConstruct %5 %24 %24 +%80 = OpExtInst %5 %1 FindILsb %78 +%79 = OpExtInst %5 %1 UMin %76 %80 +%81 = OpCompositeConstruct %56 %23 %23 +%83 = OpExtInst %56 %1 FindILsb %81 +%82 = OpExtInst %56 %1 UMin %76 %83 +%84 = OpCompositeConstruct %5 %26 %26 +%86 = OpExtInst %5 %1 FindILsb %84 +%85 = OpExtInst %5 %1 UMin %76 %86 +%89 = OpExtInst %6 %1 FindUMsb %22 +%87 = OpISub %6 %88 %89 +%91 = OpExtInst %6 %1 FindUMsb %23 +%90 = OpISub %20 %88 %91 +%92 = OpCompositeConstruct %5 %22 %22 +%95 = OpExtInst %5 %1 FindUMsb %92 +%93 = OpISub %5 %94 %95 +%96 = OpCompositeConstruct %56 %23 %23 +%98 = OpExtInst %5 %1 FindUMsb %96 +%97 = OpISub %56 %94 %98 +%99 = OpExtInst %4 %1 Ldexp %17 %27 +%100 = OpCompositeConstruct %7 %17 %28 +%101 = OpCompositeConstruct %5 %29 %30 +%102 = OpExtInst %7 %1 Ldexp %100 %101 +%103 = OpExtInst %8 %1 ModfStruct %31 +%104 = OpExtInst %8 %1 ModfStruct %31 +%105 = OpCompositeExtract %4 %104 0 +%106 = OpExtInst %8 %1 ModfStruct %31 +%107 = OpCompositeExtract %4 %106 1 +%108 = OpCompositeConstruct %7 %31 %31 +%109 = OpExtInst %9 %1 ModfStruct %108 +%110 = OpCompositeConstruct %3 %31 %31 %31 %31 +%111 = OpExtInst %10 %1 ModfStruct %110 +%112 = OpCompositeExtract %3 %111 1 +%113 = OpCompositeExtract %4 %112 0 +%114 = OpCompositeConstruct %7 %31 %31 +%115 = OpExtInst %9 %1 ModfStruct %114 +%116 = OpCompositeExtract %7 %115 0 +%117 = OpCompositeExtract %4 %116 1 +%118 = OpExtInst %11 %1 FrexpStruct %31 +%119 = OpExtInst %11 %1 FrexpStruct %31 +%120 = OpCompositeExtract %4 %119 0 +%121 = OpExtInst %11 %1 FrexpStruct %31 +%122 = OpCompositeExtract %6 %121 1 +%123 = OpCompositeConstruct %3 %31 %31 %31 %31 +%124 = OpExtInst %13 %1 FrexpStruct %123 +%125 = OpCompositeExtract %12 %124 1 +%126 = OpCompositeExtract %6 %125 0 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/tests/out/wgsl/atomicCompareExchange.wgsl index 2ff428bd7..b659bed2b 100644 --- a/tests/out/wgsl/atomicCompareExchange.wgsl +++ b/tests/out/wgsl/atomicCompareExchange.wgsl @@ -1,13 +1,3 @@ -struct gen___atomic_compare_exchange_resultSint4_ { - old_value: i32, - exchanged: bool, -} - -struct gen___atomic_compare_exchange_resultUint4_ { - old_value: u32, - exchanged: bool, -} - const SIZE: u32 = 128u; @group(0) @binding(0) diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 5cdab8cdb..149ebff8e 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -30,4 +30,14 @@ fn main() { let clz_d = countLeadingZeros(vec2(1u)); let lde_a = ldexp(1.0, 2); let lde_b = ldexp(vec2(1.0, 2.0), vec2(3, 4)); + let modf_a = modf(1.5); + let modf_b = modf(1.5).fract; + let modf_c = modf(1.5).whole; + let modf_d = modf(vec2(1.5, 1.5)); + let modf_e = modf(vec4(1.5, 1.5, 1.5, 1.5)).whole.x; + let modf_f = modf(vec2(1.5, 1.5)).fract.y; + let frexp_a = frexp(1.5); + let frexp_b = frexp(1.5).fract; + let frexp_c = frexp(1.5).exp; + let frexp_d = frexp(vec4(1.5, 1.5, 1.5, 1.5)).exp.x; } From 843557a48b4619458b0a38359d4dcad08793d97a Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 19 Apr 2023 18:28:10 +0200 Subject: [PATCH 2068/2212] [glsl-in] refactor: use `Context::add_expression` in all places --- src/front/glsl/builtins.rs | 14 +-- src/front/glsl/context.rs | 132 ++++++++++++++------------ src/front/glsl/functions.rs | 24 ++--- src/front/glsl/parser/declarations.rs | 7 +- 4 files changed, 93 insertions(+), 84 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index fa5d5d9b9..55ff8fbc9 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -2057,7 +2057,7 @@ impl MacroCall { body, ), MacroCall::Mod(size) => { - ctx.implicit_splat(frontend, &mut args[1], meta, size)?; + ctx.implicit_splat(frontend, &mut args[1], meta, size, body)?; // x - y * floor(x / y) @@ -2101,7 +2101,7 @@ impl MacroCall { ) } MacroCall::Splatted(fun, size, i) => { - ctx.implicit_splat(frontend, &mut args[i], meta, size)?; + ctx.implicit_splat(frontend, &mut args[i], meta, size, body)?; ctx.add_expression( Expression::Math { @@ -2125,8 +2125,8 @@ impl MacroCall { body, ), MacroCall::Clamp(size) => { - ctx.implicit_splat(frontend, &mut args[1], meta, size)?; - ctx.implicit_splat(frontend, &mut args[2], meta, size)?; + ctx.implicit_splat(frontend, &mut args[1], meta, size, body)?; + ctx.implicit_splat(frontend, &mut args[2], meta, size, body)?; ctx.add_expression( Expression::Math { @@ -2164,8 +2164,8 @@ impl MacroCall { return Ok(None); } MacroCall::SmoothStep { splatted } => { - ctx.implicit_splat(frontend, &mut args[0], meta, splatted)?; - ctx.implicit_splat(frontend, &mut args[1], meta, splatted)?; + ctx.implicit_splat(frontend, &mut args[0], meta, splatted, body)?; + ctx.implicit_splat(frontend, &mut args[1], meta, splatted, body)?; ctx.add_expression( Expression::Math { @@ -2196,7 +2196,7 @@ fn texture_call( let mut array_index = comps.array_index; if let Some(ref mut array_index_expr) = array_index { - ctx.conversion(array_index_expr, meta, Sk::Sint, 4)?; + ctx.conversion(array_index_expr, meta, Sk::Sint, 4, body)?; } Ok(ctx.add_expression( diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index e16dc125e..755f2eba9 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -114,28 +114,19 @@ impl Context { }: GlobalLookup, body: &mut Block, ) { - self.emit_end(body); let (expr, load, constant) = match kind { GlobalLookupKind::Variable(v) => { let span = frontend.module.global_variables.get_span(v); - let res = ( - self.expressions.append(Expression::GlobalVariable(v), span), + ( + self.add_expression(Expression::GlobalVariable(v), span, body), frontend.module.global_variables[v].space != AddressSpace::Handle, None, - ); - self.emit_start(); - - res + ) } GlobalLookupKind::BlockSelect(handle, index) => { let span = frontend.module.global_variables.get_span(handle); - let base = self - .expressions - .append(Expression::GlobalVariable(handle), span); - self.emit_start(); - let expr = self - .expressions - .append(Expression::AccessIndex { base, index }, span); + let base = self.add_expression(Expression::GlobalVariable(handle), span, body); + let expr = self.add_expression(Expression::AccessIndex { base, index }, span, body); ( expr, @@ -162,13 +153,11 @@ impl Context { } GlobalLookupKind::Constant(v, ty) => { let span = frontend.module.constants.get_span(v); - let res = ( - self.expressions.append(Expression::Constant(v), span), + ( + self.add_expression(Expression::Constant(v), span, body), false, Some((v, ty)), - ); - self.emit_start(); - res + ) } }; @@ -568,9 +557,10 @@ impl Context { right_meta, ScalarKind::Uint, 4, + body, )?, _ => self.binary_implicit_conversion( - frontend, &mut left, left_meta, &mut right, right_meta, + frontend, &mut left, left_meta, &mut right, right_meta, body, )?, } @@ -632,20 +622,21 @@ impl Context { ); // Divide the vectors - let column = self.expressions.append( + let column = self.add_expression( Expression::Binary { op, left: left_vector, right: right_vector, }, meta, + body, ); components.push(column) } // Rebuild the matrix from the divided vectors - self.expressions.append( + self.add_expression( Expression::Compose { ty: frontend.module.types.insert( Type { @@ -661,6 +652,7 @@ impl Context { components, }, meta, + body, ) } BinaryOperator::Equal | BinaryOperator::NotEqual => { @@ -699,13 +691,14 @@ impl Context { body, ); - let argument = self.expressions.append( + let argument = self.add_expression( Expression::Binary { op, left: left_vector, right: right_vector, }, meta, + body, ); // The result of comparing two vectors is a boolean vector @@ -750,9 +743,11 @@ impl Context { false => (BinaryOperator::NotEqual, RelationalFunction::Any), }; - let argument = self - .expressions - .append(Expression::Binary { op, left, right }, meta); + let argument = self.add_expression( + Expression::Binary { op, left, right }, + meta, + body, + ); self.add_expression( Expression::Relational { fun, argument }, @@ -872,20 +867,21 @@ impl Context { // Apply the operation to the splatted vector and // the column vector - let column = self.expressions.append( + let column = self.add_expression( Expression::Binary { op, left: scalar_vector, right: matrix_column, }, meta, + body, ); components.push(column) } // Rebuild the matrix from the operation result vectors - self.expressions.append( + self.add_expression( Expression::Compose { ty: frontend.module.types.insert( Type { @@ -901,6 +897,7 @@ impl Context { components, }, meta, + body, ) } _ => self.add_expression( @@ -963,20 +960,21 @@ impl Context { // Apply the operation to the splatted vector and // the column vector - let column = self.expressions.append( + let column = self.add_expression( Expression::Binary { op, left: matrix_column, right: scalar_vector, }, meta, + body, ); components.push(column) } // Rebuild the matrix from the operation result vectors - self.expressions.append( + self.add_expression( Expression::Compose { ty: frontend.module.types.insert( Type { @@ -992,6 +990,7 @@ impl Context { components, }, meta, + body, ) } _ => self.add_expression( @@ -1137,27 +1136,31 @@ impl Context { ) { match accept_power.cmp(&reject_power) { std::cmp::Ordering::Less => { - self.conversion(&mut accept, accept_meta, reject_kind, reject_width)?; + self.conversion( + &mut accept, + accept_meta, + reject_kind, + reject_width, + &mut accept_body, + )?; // The expression belongs to the `true` branch so we need to flush to // the respective body - self.emit_end(&mut accept_body); + self.emit_restart(&mut accept_body); } - // Technically there's nothing to flush but later we will need to - // add some expressions that must not be emitted so instead - // of flushing, starting and flushing again, just make sure - // everything is flushed. - std::cmp::Ordering::Equal => self.emit_end(body), + std::cmp::Ordering::Equal => {} std::cmp::Ordering::Greater => { - self.conversion(&mut reject, reject_meta, accept_kind, accept_width)?; + self.conversion( + &mut reject, + reject_meta, + accept_kind, + accept_width, + &mut reject_body, + )?; // The expression belongs to the `false` branch so we need to flush to // the respective body - self.emit_end(&mut reject_body); + self.emit_restart(&mut reject_body); } } - } else { - // Technically there's nothing to flush but later we will need to - // add some expressions that must not be emitted. - self.emit_end(body) } // We need to get the type of the resulting expression to create the local, @@ -1175,11 +1178,7 @@ impl Context { meta, ); - // Note: `Expression::LocalVariable` must not be emited so it's important - // that at this point the emitter is flushed but not started. - let local_expr = self - .expressions - .append(Expression::LocalVariable(local), meta); + let local_expr = self.add_expression(Expression::LocalVariable(local), meta, body); // Add to each body the store to the result variable accept_body.push( @@ -1208,16 +1207,14 @@ impl Context { meta, ); - // Restart the emitter - self.emit_start(); - // Note: `Expression::Load` must be emited before it's used so make // sure the emitter is active here. - self.expressions.append( + self.add_expression( Expression::Load { pointer: local_expr, }, meta, + body, ) } HirExprKind::Assign { tgt, value } if ExprPos::Lhs != pos => { @@ -1232,7 +1229,7 @@ impl Context { }; if let Some((kind, width)) = scalar_components(ty) { - self.implicit_conversion(frontend, &mut value, value_meta, kind, width)?; + self.implicit_conversion(frontend, &mut value, value_meta, kind, width, body)?; } self.lower_store(pointer, value, meta, body); @@ -1365,6 +1362,7 @@ impl Context { meta, ScalarKind::Sint, 4, + body, )?; array_length } @@ -1375,7 +1373,13 @@ impl Context { meta, body, ); - self.conversion(&mut array_length, meta, ScalarKind::Sint, 4)?; + self.conversion( + &mut array_length, + meta, + ScalarKind::Sint, + 4, + body, + )?; array_length } } @@ -1439,14 +1443,16 @@ impl Context { meta: Span, kind: ScalarKind, width: crate::Bytes, + body: &mut Block, ) -> Result<()> { - *expr = self.expressions.append( + *expr = self.add_expression( Expression::As { expr: *expr, kind, convert: Some(width), }, meta, + body, ); Ok(()) @@ -1459,13 +1465,14 @@ impl Context { meta: Span, kind: ScalarKind, width: crate::Bytes, + body: &mut Block, ) -> Result<()> { if let (Some(tgt_power), Some(expr_power)) = ( type_power(kind, width), self.expr_power(frontend, *expr, meta)?, ) { if tgt_power > expr_power { - self.conversion(expr, meta, kind, width)?; + self.conversion(expr, meta, kind, width, body)?; } } @@ -1479,12 +1486,13 @@ impl Context { meta: Span, kind: ScalarKind, width: crate::Bytes, + body: &mut Block, ) -> Result<()> { if let Some((expr_scalar_kind, expr_width)) = self.expr_scalar_components(frontend, *expr, meta)? { if expr_scalar_kind != kind || expr_width != width { - self.conversion(expr, meta, kind, width)?; + self.conversion(expr, meta, kind, width, body)?; } } @@ -1498,6 +1506,7 @@ impl Context { left_meta: Span, right: &mut Handle, right_meta: Span, + body: &mut Block, ) -> Result<()> { let left_components = self.expr_scalar_components(frontend, *left, left_meta)?; let right_components = self.expr_scalar_components(frontend, *right, right_meta)?; @@ -1512,11 +1521,11 @@ impl Context { ) { match left_power.cmp(&right_power) { std::cmp::Ordering::Less => { - self.conversion(left, left_meta, right_kind, right_width)?; + self.conversion(left, left_meta, right_kind, right_width, body)?; } std::cmp::Ordering::Equal => {} std::cmp::Ordering::Greater => { - self.conversion(right, right_meta, left_kind, left_width)?; + self.conversion(right, right_meta, left_kind, left_width, body)?; } } } @@ -1530,13 +1539,12 @@ impl Context { expr: &mut Handle, meta: Span, vector_size: Option, + body: &mut Block, ) -> Result<()> { let expr_type = frontend.resolve_type(self, *expr, meta)?; if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { - *expr = self - .expressions - .append(Expression::Splat { size, value: *expr }, meta) + *expr = self.add_expression(Expression::Splat { size, value: *expr }, meta, body) } Ok(()) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 7dee02374..f85c76505 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -79,8 +79,8 @@ impl Frontend { let mut reject = ctx.add_expression(Expression::Literal(l0), expr_meta, body); let mut accept = ctx.add_expression(Expression::Literal(l1), expr_meta, body); - ctx.implicit_splat(self, &mut reject, meta, vector_size)?; - ctx.implicit_splat(self, &mut accept, meta, vector_size)?; + ctx.implicit_splat(self, &mut reject, meta, vector_size, body)?; + ctx.implicit_splat(self, &mut accept, meta, vector_size, body)?; let h = ctx.add_expression( Expression::Select { @@ -99,7 +99,7 @@ impl Frontend { Ok(match self.module.types[ty].inner { TypeInner::Vector { size, kind, width } if vector_size.is_none() => { - ctx.forced_conversion(self, &mut value, expr_meta, kind, width)?; + ctx.forced_conversion(self, &mut value, expr_meta, kind, width, body)?; if let TypeInner::Scalar { .. } = *self.resolve_type(ctx, value, expr_meta)? { ctx.add_expression(Expression::Splat { size, value }, meta, body) @@ -186,7 +186,7 @@ impl Frontend { .get(0) .and_then(|member| scalar_components(&self.module.types[member.ty].inner)); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut value, expr_meta, kind, width)?; + ctx.implicit_conversion(self, &mut value, expr_meta, kind, width, body)?; } ctx.add_expression( @@ -202,7 +202,7 @@ impl Frontend { TypeInner::Array { base, .. } => { let scalar_components = scalar_components(&self.module.types[base].inner); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut value, expr_meta, kind, width)?; + ctx.implicit_conversion(self, &mut value, expr_meta, kind, width, body)?; } ctx.add_expression( @@ -242,7 +242,7 @@ impl Frontend { // `Expression::As` doesn't support matrix width // casts so we need to do some extra work for casts - ctx.forced_conversion(self, &mut value, expr_meta, ScalarKind::Float, width)?; + ctx.forced_conversion(self, &mut value, expr_meta, ScalarKind::Float, width, body)?; match *self.resolve_type(ctx, value, expr_meta)? { TypeInner::Scalar { .. } => { // If a matrix is constructed with a single scalar value, then that @@ -395,7 +395,7 @@ impl Frontend { let mut components = Vec::with_capacity(size as usize); for (mut arg, expr_meta) in args.iter().copied() { - ctx.forced_conversion(self, &mut arg, expr_meta, kind, width)?; + ctx.forced_conversion(self, &mut arg, expr_meta, kind, width, body)?; if components.len() >= size as usize { break; @@ -461,7 +461,7 @@ impl Frontend { let mut flattened = Vec::with_capacity(columns as usize * rows as usize); for (mut arg, meta) in args.iter().copied() { - ctx.forced_conversion(self, &mut arg, meta, ScalarKind::Float, width)?; + ctx.forced_conversion(self, &mut arg, meta, ScalarKind::Float, width, body)?; match *self.resolve_type(ctx, arg, meta)? { TypeInner::Vector { size, .. } => { @@ -510,7 +510,7 @@ impl Frontend { for (mut arg, meta) in args.iter().copied() { let scalar_components = scalar_components(&self.module.types[base].inner); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; + ctx.implicit_conversion(self, &mut arg, meta, kind, width, body)?; } components.push(arg) @@ -520,7 +520,7 @@ impl Frontend { for ((mut arg, meta), member) in args.iter().copied().zip(members.iter()) { let scalar_components = scalar_components(&self.module.types[member.ty].inner); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut arg, meta, kind, width)?; + ctx.implicit_conversion(self, &mut arg, meta, kind, width, body)?; } components.push(arg) @@ -845,7 +845,7 @@ impl Frontend { // Apply implicit conversions as needed if let Some((kind, width)) = scalar_comps { - ctx.implicit_conversion(self, &mut handle, meta, kind, width)?; + ctx.implicit_conversion(self, &mut handle, meta, kind, width, body)?; } arguments.push(handle) @@ -883,7 +883,7 @@ impl Frontend { ); if let Some((kind, width)) = proxy_write.convert { - ctx.conversion(&mut value, meta, kind, width)?; + ctx.conversion(&mut value, meta, kind, width, body)?; } ctx.emit_restart(body); diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index e99dda54f..42b2abb5c 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -161,7 +161,7 @@ impl<'source> ParsingContext<'source> { let scalar_components = scalar_components(&frontend.module.types[ty].inner); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(frontend, &mut init, init_meta, kind, width)?; + ctx.implicit_conversion(frontend, &mut init, init_meta, kind, width, body)?; } Ok((init, init_meta)) @@ -233,8 +233,9 @@ impl<'source> ParsingContext<'source> { let scalar_components = scalar_components(&frontend.module.types[ty].inner); if let Some((kind, width)) = scalar_components { - ctx.ctx - .implicit_conversion(frontend, &mut expr, init_meta, kind, width)?; + ctx.ctx.implicit_conversion( + frontend, &mut expr, init_meta, kind, width, ctx.body, + )?; } meta.subsume(init_meta); From 7c3c6a9d471679ee7b79d8c6d9566c26dcf929eb Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 27 Apr 2023 15:52:07 +0200 Subject: [PATCH 2069/2212] [glsl-in] move module and active body to Context --- src/front/glsl/builtins.rs | 184 +++----- src/front/glsl/context.rs | 622 +++++++++++--------------- src/front/glsl/functions.rs | 474 +++++++++----------- src/front/glsl/mod.rs | 26 +- src/front/glsl/parser.rs | 60 ++- src/front/glsl/parser/declarations.rs | 80 ++-- src/front/glsl/parser/expressions.rs | 63 ++- src/front/glsl/parser/functions.rs | 435 +++++++++--------- src/front/glsl/parser/types.rs | 54 ++- src/front/glsl/types.rs | 49 +- src/front/glsl/variables.rs | 76 ++-- 11 files changed, 947 insertions(+), 1176 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 55ff8fbc9..811be65cc 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -7,7 +7,7 @@ use super::{ Error, ErrorKind, Frontend, Result, }; use crate::{ - BinaryOperator, Block, DerivativeAxis as Axis, DerivativeControl as Ctrl, Expression, Handle, + BinaryOperator, DerivativeAxis as Axis, DerivativeControl as Ctrl, Expression, Handle, ImageClass, ImageDimension as Dim, ImageQuery, MathFunction, Module, RelationalFunction, SampleLevel, ScalarKind as Sk, Span, Type, TypeInner, UnaryOperator, VectorSize, }; @@ -1684,7 +1684,6 @@ impl MacroCall { &self, frontend: &mut Frontend, ctx: &mut Context, - body: &mut Block, args: &mut [Handle], meta: Span, ) -> Result>> { @@ -1694,14 +1693,8 @@ impl MacroCall { args[0] } MacroCall::SamplerShadow => { - sampled_to_depth( - &mut frontend.module, - ctx, - args[0], - meta, - &mut frontend.errors, - ); - frontend.invalidate_expression(ctx, args[0], meta)?; + sampled_to_depth(ctx, args[0], meta, &mut frontend.errors); + ctx.invalidate_expression(args[0], meta)?; ctx.samplers.insert(args[0], args[1]); args[0] } @@ -1714,7 +1707,7 @@ impl MacroCall { let mut coords = args[1]; if proj { - let size = match *frontend.resolve_type(ctx, coords, meta)? { + let size = match *ctx.resolve_type(coords, meta)? { TypeInner::Vector { size, .. } => size, _ => unreachable!(), }; @@ -1724,8 +1717,7 @@ impl MacroCall { index: size as u32 - 1, }, Span::default(), - body, - ); + )?; let left = if let VectorSize::Bi = size { ctx.add_expression( Expression::AccessIndex { @@ -1733,8 +1725,7 @@ impl MacroCall { index: 0, }, Span::default(), - body, - ) + )? } else { let size = match size { VectorSize::Tri => VectorSize::Bi, @@ -1743,9 +1734,8 @@ impl MacroCall { right = ctx.add_expression( Expression::Splat { size, value: right }, Span::default(), - body, - ); - ctx.vector_resize(size, coords, Span::default(), body) + )?; + ctx.vector_resize(size, coords, Span::default())? }; coords = ctx.add_expression( Expression::Binary { @@ -1754,13 +1744,11 @@ impl MacroCall { right, }, Span::default(), - body, - ); + )?; } let extra = args.get(2).copied(); - let comps = - frontend.coordinate_components(ctx, args[0], coords, extra, meta, body)?; + let comps = frontend.coordinate_components(ctx, args[0], coords, extra, meta)?; let mut num_args = 2; @@ -1807,7 +1795,7 @@ impl MacroCall { true => { let offset_arg = args[num_args]; num_args += 1; - match frontend.solve_constant(ctx, offset_arg, meta) { + match ctx.solve_constant(offset_arg, meta) { Ok(v) => Some(v), Err(e) => { frontend.errors.push(e); @@ -1826,7 +1814,7 @@ impl MacroCall { .map_or(SampleLevel::Auto, SampleLevel::Bias); } - texture_call(ctx, args[0], level, comps, texture_offset, body, meta)? + texture_call(ctx, args[0], level, comps, texture_offset, meta)? } MacroCall::TextureSize { arrayed } => { @@ -1838,20 +1826,18 @@ impl MacroCall { }, }, Span::default(), - body, - ); + )?; if arrayed { let mut components = Vec::with_capacity(4); - let size = match *frontend.resolve_type(ctx, expr, meta)? { + let size = match *ctx.resolve_type(expr, meta)? { TypeInner::Vector { size: ori_size, .. } => { for index in 0..(ori_size as u32) { components.push(ctx.add_expression( Expression::AccessIndex { base: expr, index }, Span::default(), - body, - )) + )?) } match ori_size { @@ -1871,10 +1857,9 @@ impl MacroCall { query: ImageQuery::NumLayers, }, Span::default(), - body, - )); + )?); - let ty = frontend.module.types.insert( + let ty = ctx.module.types.insert( Type { name: None, inner: TypeInner::Vector { @@ -1886,7 +1871,7 @@ impl MacroCall { Span::default(), ); - expr = ctx.add_expression(Expression::Compose { components, ty }, meta, body) + expr = ctx.add_expression(Expression::Compose { components, ty }, meta)? } ctx.add_expression( @@ -1896,12 +1881,10 @@ impl MacroCall { convert: Some(4), }, Span::default(), - body, - ) + )? } MacroCall::ImageLoad { multi } => { - let comps = - frontend.coordinate_components(ctx, args[0], args[1], None, meta, body)?; + let comps = frontend.coordinate_components(ctx, args[0], args[1], None, meta)?; let (sample, level) = match (multi, args.get(2)) { (_, None) => (None, None), (true, Some(&arg)) => (Some(arg), None), @@ -1916,14 +1899,12 @@ impl MacroCall { level, }, Span::default(), - body, - ) + )? } MacroCall::ImageStore => { - let comps = - frontend.coordinate_components(ctx, args[0], args[1], None, meta, body)?; - ctx.emit_restart(body); - body.push( + let comps = frontend.coordinate_components(ctx, args[0], args[1], None, meta)?; + ctx.emit_restart(); + ctx.body.push( crate::Statement::ImageStore { image: args[0], coordinate: comps.coordinate, @@ -1943,8 +1924,7 @@ impl MacroCall { arg3: args.get(3).copied(), }, Span::default(), - body, - ), + )?, mc @ (MacroCall::FindLsbUint | MacroCall::FindMsbUint) => { let fun = match mc { MacroCall::FindLsbUint => MathFunction::FindLsb, @@ -1960,8 +1940,7 @@ impl MacroCall { arg3: None, }, Span::default(), - body, - ); + )?; ctx.add_expression( Expression::As { expr: res, @@ -1969,8 +1948,7 @@ impl MacroCall { convert: Some(4), }, Span::default(), - body, - ) + )? } MacroCall::BitfieldInsert => { let conv_arg_2 = ctx.add_expression( @@ -1980,8 +1958,7 @@ impl MacroCall { convert: Some(4), }, Span::default(), - body, - ); + )?; let conv_arg_3 = ctx.add_expression( Expression::As { expr: args[3], @@ -1989,8 +1966,7 @@ impl MacroCall { convert: Some(4), }, Span::default(), - body, - ); + )?; ctx.add_expression( Expression::Math { fun: MathFunction::InsertBits, @@ -2000,8 +1976,7 @@ impl MacroCall { arg3: Some(conv_arg_3), }, Span::default(), - body, - ) + )? } MacroCall::BitfieldExtract => { let conv_arg_1 = ctx.add_expression( @@ -2011,8 +1986,7 @@ impl MacroCall { convert: Some(4), }, Span::default(), - body, - ); + )?; let conv_arg_2 = ctx.add_expression( Expression::As { expr: args[2], @@ -2020,8 +1994,7 @@ impl MacroCall { convert: Some(4), }, Span::default(), - body, - ); + )?; ctx.add_expression( Expression::Math { fun: MathFunction::ExtractBits, @@ -2031,8 +2004,7 @@ impl MacroCall { arg3: None, }, Span::default(), - body, - ) + )? } MacroCall::Relational(fun) => ctx.add_expression( Expression::Relational { @@ -2040,13 +2012,10 @@ impl MacroCall { argument: args[0], }, Span::default(), - body, - ), - MacroCall::Unary(op) => ctx.add_expression( - Expression::Unary { op, expr: args[0] }, - Span::default(), - body, - ), + )?, + MacroCall::Unary(op) => { + ctx.add_expression(Expression::Unary { op, expr: args[0] }, Span::default())? + } MacroCall::Binary(op) => ctx.add_expression( Expression::Binary { op, @@ -2054,10 +2023,9 @@ impl MacroCall { right: args[1], }, Span::default(), - body, - ), + )?, MacroCall::Mod(size) => { - ctx.implicit_splat(frontend, &mut args[1], meta, size, body)?; + ctx.implicit_splat(&mut args[1], meta, size)?; // x - y * floor(x / y) @@ -2068,8 +2036,7 @@ impl MacroCall { right: args[1], }, Span::default(), - body, - ); + )?; let floor = ctx.add_expression( Expression::Math { fun: MathFunction::Floor, @@ -2079,8 +2046,7 @@ impl MacroCall { arg3: None, }, Span::default(), - body, - ); + )?; let mult = ctx.add_expression( Expression::Binary { op: BinaryOperator::Multiply, @@ -2088,8 +2054,7 @@ impl MacroCall { right: args[1], }, Span::default(), - body, - ); + )?; ctx.add_expression( Expression::Binary { op: BinaryOperator::Subtract, @@ -2097,11 +2062,10 @@ impl MacroCall { right: mult, }, Span::default(), - body, - ) + )? } MacroCall::Splatted(fun, size, i) => { - ctx.implicit_splat(frontend, &mut args[i], meta, size, body)?; + ctx.implicit_splat(&mut args[i], meta, size)?; ctx.add_expression( Expression::Math { @@ -2112,8 +2076,7 @@ impl MacroCall { arg3: args.get(3).copied(), }, Span::default(), - body, - ) + )? } MacroCall::MixBoolean => ctx.add_expression( Expression::Select { @@ -2122,11 +2085,10 @@ impl MacroCall { reject: args[0], }, Span::default(), - body, - ), + )?, MacroCall::Clamp(size) => { - ctx.implicit_splat(frontend, &mut args[1], meta, size, body)?; - ctx.implicit_splat(frontend, &mut args[2], meta, size, body)?; + ctx.implicit_splat(&mut args[1], meta, size)?; + ctx.implicit_splat(&mut args[2], meta, size)?; ctx.add_expression( Expression::Math { @@ -2137,8 +2099,7 @@ impl MacroCall { arg3: args.get(3).copied(), }, Span::default(), - body, - ) + )? } MacroCall::BitCast(kind) => ctx.add_expression( Expression::As { @@ -2147,8 +2108,7 @@ impl MacroCall { convert: None, }, Span::default(), - body, - ), + )?, MacroCall::Derivate(axis, ctrl) => ctx.add_expression( Expression::Derivative { axis, @@ -2156,16 +2116,16 @@ impl MacroCall { expr: args[0], }, Span::default(), - body, - ), + )?, MacroCall::Barrier => { - ctx.emit_restart(body); - body.push(crate::Statement::Barrier(crate::Barrier::all()), meta); + ctx.emit_restart(); + ctx.body + .push(crate::Statement::Barrier(crate::Barrier::all()), meta); return Ok(None); } MacroCall::SmoothStep { splatted } => { - ctx.implicit_splat(frontend, &mut args[0], meta, splatted, body)?; - ctx.implicit_splat(frontend, &mut args[1], meta, splatted, body)?; + ctx.implicit_splat(&mut args[0], meta, splatted)?; + ctx.implicit_splat(&mut args[1], meta, splatted)?; ctx.add_expression( Expression::Math { @@ -2176,8 +2136,7 @@ impl MacroCall { arg3: None, }, Span::default(), - body, - ) + )? } })) } @@ -2189,14 +2148,13 @@ fn texture_call( level: SampleLevel, comps: CoordComponents, offset: Option>, - body: &mut Block, meta: Span, ) -> Result> { if let Some(sampler) = ctx.samplers.get(&image).copied() { let mut array_index = comps.array_index; if let Some(ref mut array_index_expr) = array_index { - ctx.conversion(array_index_expr, meta, Sk::Sint, 4, body)?; + ctx.conversion(array_index_expr, meta, Sk::Sint, 4)?; } Ok(ctx.add_expression( @@ -2211,8 +2169,7 @@ fn texture_call( depth_ref: comps.depth_ref, }, meta, - body, - )) + )?) } else { Err(Error { kind: ErrorKind::SemanticError("Bad call".into()), @@ -2241,13 +2198,12 @@ impl Frontend { coord: Handle, extra: Option>, meta: Span, - body: &mut Block, ) -> Result { if let TypeInner::Image { dim, arrayed, class, - } = *self.resolve_type(ctx, image, meta)? + } = *ctx.resolve_type(image, meta)? { let image_size = match dim { Dim::D1 => None, @@ -2255,7 +2211,7 @@ impl Frontend { Dim::D3 => Some(VectorSize::Tri), Dim::Cube => Some(VectorSize::Tri), }; - let coord_size = match *self.resolve_type(ctx, coord, meta)? { + let coord_size = match *ctx.resolve_type(coord, meta)? { TypeInner::Vector { size, .. } => Some(size), _ => None, }; @@ -2267,7 +2223,7 @@ impl Frontend { let coordinate = match (image_size, coord_size) { (Some(size), Some(coord_s)) if size != coord_s => { - ctx.vector_resize(size, coord, Span::default(), body) + ctx.vector_resize(size, coord, Span::default())? } (None, Some(_)) => ctx.add_expression( Expression::AccessIndex { @@ -2275,8 +2231,7 @@ impl Frontend { index: 0, }, Span::default(), - body, - ), + )?, _ => coord, }; @@ -2289,8 +2244,7 @@ impl Frontend { Some(ctx.add_expression( Expression::AccessIndex { base: coord, index }, Span::default(), - body, - )) + )?) } else { None }; @@ -2306,8 +2260,7 @@ impl Frontend { Some(ctx.add_expression( Expression::AccessIndex { base: coord, index }, Span::default(), - body, - )) + )?) } } false => None, @@ -2338,7 +2291,6 @@ impl Frontend { /// Helper function to cast a expression holding a sampled image to a /// depth image. pub fn sampled_to_depth( - module: &mut Module, ctx: &mut Context, image: Handle, meta: Span, @@ -2346,7 +2298,7 @@ pub fn sampled_to_depth( ) { // Get the a mutable type handle of the underlying image storage let ty = match ctx[image] { - Expression::GlobalVariable(handle) => &mut module.global_variables.get_mut(handle).ty, + Expression::GlobalVariable(handle) => &mut ctx.module.global_variables.get_mut(handle).ty, Expression::FunctionArgument(i) => { // Mark the function argument as carrying a depth texture ctx.parameters_info[i as usize].depth = true; @@ -2362,7 +2314,7 @@ pub fn sampled_to_depth( } }; - match module.types[*ty].inner { + match ctx.module.types[*ty].inner { // Update the image class to depth in case it already isn't TypeInner::Image { class, @@ -2370,7 +2322,7 @@ pub fn sampled_to_depth( arrayed, } => match class { ImageClass::Sampled { multi, .. } => { - *ty = module.types.insert( + *ty = ctx.module.types.insert( Type { name: None, inner: TypeInner::Image { diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 755f2eba9..407619c3d 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -44,7 +44,7 @@ impl ExprPos { } #[derive(Debug)] -pub struct Context { +pub struct Context<'a> { pub expressions: Arena, pub locals: Arena, @@ -74,10 +74,12 @@ pub struct Context { pub typifier: Typifier, emitter: Emitter, stmt_ctx: Option, + pub body: Block, + pub module: &'a mut crate::Module, } -impl Context { - pub fn new(frontend: &Frontend, body: &mut Block) -> Self { +impl<'a> Context<'a> { + pub fn new(frontend: &Frontend, module: &'a mut crate::Module) -> Result { let mut this = Context { expressions: Arena::new(), locals: Arena::new(), @@ -92,53 +94,84 @@ impl Context { typifier: Typifier::new(), emitter: Emitter::default(), stmt_ctx: Some(StmtContext::new()), + body: Block::new(), + module, }; this.emit_start(); for &(ref name, lookup) in frontend.global_variables.iter() { - this.add_global(frontend, name, lookup, body) + this.add_global(name, lookup)? } - this + Ok(this) + } + + pub fn new_body(&mut self, cb: F) -> Result + where + F: FnOnce(&mut Self) -> Result<()>, + { + self.new_body_with_ret(cb).map(|(b, _)| b) + } + + pub fn new_body_with_ret(&mut self, cb: F) -> Result<(Block, R)> + where + F: FnOnce(&mut Self) -> Result, + { + self.emit_restart(); + let old_body = std::mem::replace(&mut self.body, Block::new()); + let res = cb(self); + self.emit_restart(); + let new_body = std::mem::replace(&mut self.body, old_body); + res.map(|r| (new_body, r)) + } + + pub fn with_body(&mut self, body: Block, cb: F) -> Result + where + F: FnOnce(&mut Self) -> Result<()>, + { + self.emit_restart(); + let old_body = std::mem::replace(&mut self.body, body); + let res = cb(self); + self.emit_restart(); + let body = std::mem::replace(&mut self.body, old_body); + res.map(|_| body) } pub fn add_global( &mut self, - frontend: &Frontend, name: &str, GlobalLookup { kind, entry_arg, mutable, }: GlobalLookup, - body: &mut Block, - ) { + ) -> Result<()> { let (expr, load, constant) = match kind { GlobalLookupKind::Variable(v) => { - let span = frontend.module.global_variables.get_span(v); + let span = self.module.global_variables.get_span(v); ( - self.add_expression(Expression::GlobalVariable(v), span, body), - frontend.module.global_variables[v].space != AddressSpace::Handle, + self.add_expression(Expression::GlobalVariable(v), span)?, + self.module.global_variables[v].space != AddressSpace::Handle, None, ) } GlobalLookupKind::BlockSelect(handle, index) => { - let span = frontend.module.global_variables.get_span(handle); - let base = self.add_expression(Expression::GlobalVariable(handle), span, body); - let expr = self.add_expression(Expression::AccessIndex { base, index }, span, body); + let span = self.module.global_variables.get_span(handle); + let base = self.add_expression(Expression::GlobalVariable(handle), span)?; + let expr = self.add_expression(Expression::AccessIndex { base, index }, span)?; ( expr, { - let ty = frontend.module.global_variables[handle].ty; + let ty = self.module.global_variables[handle].ty; - match frontend.module.types[ty].inner { + match self.module.types[ty].inner { TypeInner::Struct { ref members, .. } => { if let TypeInner::Array { size: crate::ArraySize::Dynamic, .. - } = frontend.module.types[members[index as usize].ty].inner + } = self.module.types[members[index as usize].ty].inner { false } else { @@ -152,9 +185,9 @@ impl Context { ) } GlobalLookupKind::Constant(v, ty) => { - let span = frontend.module.constants.get_span(v); + let span = self.module.constants.get_span(v); ( - self.add_expression(Expression::Constant(v), span, body), + self.add_expression(Expression::Constant(v), span)?, false, Some((v, ty)), ) @@ -170,6 +203,8 @@ impl Context { }; self.symbol_table.add(name.into(), var); + + Ok(()) } /// Starts the expression emitter @@ -182,7 +217,7 @@ impl Context { self.emitter.start(&self.expressions) } - /// Emits all the expressions captured by the emitter to the passed `body` + /// Emits all the expressions captured by the emitter to the current body /// /// # Panics /// @@ -190,36 +225,31 @@ impl Context { /// - If called twice in a row without calling [`emit_start`]. /// /// [`emit_start`]: Self::emit_start - pub fn emit_end(&mut self, body: &mut Block) { - body.extend(self.emitter.finish(&self.expressions)) + pub fn emit_end(&mut self) { + self.body.extend(self.emitter.finish(&self.expressions)) } - /// Emits all the expressions captured by the emitter to the passed `body` + /// Emits all the expressions captured by the emitter to the current body /// and starts the emitter again /// /// # Panics /// /// - If called before calling [`emit_start`][Self::emit_start]. - pub fn emit_restart(&mut self, body: &mut Block) { - self.emit_end(body); + pub fn emit_restart(&mut self) { + self.emit_end(); self.emit_start() } - pub fn add_expression( - &mut self, - expr: Expression, - meta: Span, - body: &mut Block, - ) -> Handle { + pub fn add_expression(&mut self, expr: Expression, meta: Span) -> Result> { let needs_pre_emit = expr.needs_pre_emit(); if needs_pre_emit { - self.emit_end(body); + self.emit_end(); } let handle = self.expressions.append(expr, meta); if needs_pre_emit { self.emit_start(); } - handle + Ok(handle) } /// Add variable to current scope @@ -246,12 +276,10 @@ impl Context { /// Add function argument to current scope pub fn add_function_arg( &mut self, - frontend: &mut Frontend, - body: &mut Block, name_meta: Option<(String, Span)>, ty: Handle, qualifier: ParameterQualifier, - ) { + ) -> Result<()> { let index = self.arguments.len(); let mut arg = FunctionArgument { name: name_meta.as_ref().map(|&(ref name, _)| name.clone()), @@ -260,14 +288,14 @@ impl Context { }; self.parameters.push(ty); - let opaque = match frontend.module.types[ty].inner { + let opaque = match self.module.types[ty].inner { TypeInner::Image { .. } | TypeInner::Sampler { .. } => true, _ => false, }; if qualifier.is_lhs() { - let span = frontend.module.types.get_span(arg.ty); - arg.ty = frontend.module.types.insert( + let span = self.module.types.get_span(arg.ty); + arg.ty = self.module.types.insert( Type { name: None, inner: TypeInner::Pointer { @@ -287,7 +315,7 @@ impl Context { }); if let Some((name, meta)) = name_meta { - let expr = self.add_expression(Expression::FunctionArgument(index as u32), meta, body); + let expr = self.add_expression(Expression::FunctionArgument(index as u32), meta)?; let mutable = qualifier != ParameterQualifier::Const && !opaque; let load = qualifier.is_lhs(); @@ -300,11 +328,11 @@ impl Context { }, meta, ); - let local_expr = self.add_expression(Expression::LocalVariable(handle), meta, body); + let local_expr = self.add_expression(Expression::LocalVariable(handle), meta)?; - self.emit_restart(body); + self.emit_restart(); - body.push( + self.body.push( Statement::Store { pointer: local_expr, value: expr, @@ -331,6 +359,8 @@ impl Context { self.symbol_table.add(name, var); } + + Ok(()) } /// Returns a [`StmtContext`](StmtContext) to be used in parsing and lowering @@ -353,9 +383,8 @@ impl Context { frontend: &mut Frontend, expr: Handle, pos: ExprPos, - body: &mut Block, ) -> Result<(Option>, Span)> { - let res = self.lower_inner(&stmt, frontend, expr, pos, body); + let res = self.lower_inner(&stmt, frontend, expr, pos); stmt.hir_exprs.clear(); self.stmt_ctx = Some(stmt); @@ -374,9 +403,8 @@ impl Context { frontend: &mut Frontend, expr: Handle, pos: ExprPos, - body: &mut Block, ) -> Result<(Handle, Span)> { - let res = self.lower_expect_inner(&stmt, frontend, expr, pos, body); + let res = self.lower_expect_inner(&stmt, frontend, expr, pos); stmt.hir_exprs.clear(); self.stmt_ctx = Some(stmt); @@ -395,9 +423,8 @@ impl Context { frontend: &mut Frontend, expr: Handle, pos: ExprPos, - body: &mut Block, ) -> Result<(Handle, Span)> { - let (maybe_expr, meta) = self.lower_inner(stmt, frontend, expr, pos, body)?; + let (maybe_expr, meta) = self.lower_inner(stmt, frontend, expr, pos)?; let expr = match maybe_expr { Some(e) => e, @@ -417,8 +444,7 @@ impl Context { pointer: Handle, value: Handle, meta: Span, - body: &mut Block, - ) { + ) -> Result<()> { if let Expression::Swizzle { size, mut vector, @@ -445,20 +471,18 @@ impl Context { index: pattern[index].index(), }, meta, - body, - ); + )?; let src = self.add_expression( Expression::AccessIndex { base: value, index: index as u32, }, meta, - body, - ); + )?; - self.emit_restart(body); + self.emit_restart(); - body.push( + self.body.push( Statement::Store { pointer: dst, value: src, @@ -467,10 +491,12 @@ impl Context { ); } } else { - self.emit_restart(body); + self.emit_restart(); - body.push(Statement::Store { pointer, value }, meta); + self.body.push(Statement::Store { pointer, value }, meta); } + + Ok(()) } /// Internal implementation of [`lower`](Self::lower) @@ -480,7 +506,6 @@ impl Context { frontend: &mut Frontend, expr: Handle, pos: ExprPos, - body: &mut Block, ) -> Result<(Option>, Span)> { let HirExpr { ref kind, meta } = stmt.hir_exprs[expr]; @@ -489,12 +514,12 @@ impl Context { let handle = match *kind { HirExprKind::Access { base, index } => { let (index, index_meta) = - self.lower_expect_inner(stmt, frontend, index, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, index, ExprPos::Rhs)?; let maybe_constant_index = match pos { // Don't try to generate `AccessIndex` if in a LHS position, since it // wouldn't produce a pointer. ExprPos::Lhs => None, - _ => frontend.solve_constant(self, index, index_meta).ok(), + _ => self.solve_constant(index, index_meta).ok(), }; let base = self @@ -503,7 +528,6 @@ impl Context { frontend, base, pos.maybe_access_base(maybe_constant_index.is_some()), - body, )? .0; @@ -512,22 +536,20 @@ impl Context { Some(self.add_expression( Expression::AccessIndex { base, - index: - frontend.module.to_ctx().eval_expr_to_u32(const_expr).ok()?, + index: self.module.to_ctx().eval_expr_to_u32(const_expr).ok()?, }, meta, - body, )) }) .unwrap_or_else(|| { - self.add_expression(Expression::Access { base, index }, meta, body) - }); + self.add_expression(Expression::Access { base, index }, meta) + })?; if ExprPos::Rhs == pos { - let resolved = frontend.resolve_type(self, pointer, meta)?; + let resolved = self.resolve_type(pointer, meta)?; if resolved.pointer_space().is_some() { return Ok(( - Some(self.add_expression(Expression::Load { pointer }, meta, body)), + Some(self.add_expression(Expression::Load { pointer }, meta)?), meta, )); } @@ -536,39 +558,32 @@ impl Context { pointer } HirExprKind::Select { base, ref field } => { - let base = self.lower_expect_inner(stmt, frontend, base, pos, body)?.0; + let base = self.lower_expect_inner(stmt, frontend, base, pos)?.0; - frontend.field_selection(self, pos, body, base, field, meta)? + frontend.field_selection(self, pos, base, field, meta)? } HirExprKind::Literal(literal) if pos != ExprPos::Lhs => { - self.add_expression(Expression::Literal(literal), meta, body) + self.add_expression(Expression::Literal(literal), meta)? } HirExprKind::Binary { left, op, right } if pos != ExprPos::Lhs => { let (mut left, left_meta) = - self.lower_expect_inner(stmt, frontend, left, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, left, ExprPos::Rhs)?; let (mut right, right_meta) = - self.lower_expect_inner(stmt, frontend, right, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, right, ExprPos::Rhs)?; match op { - BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self - .implicit_conversion( - frontend, - &mut right, - right_meta, - ScalarKind::Uint, - 4, - body, - )?, - _ => self.binary_implicit_conversion( - frontend, &mut left, left_meta, &mut right, right_meta, body, - )?, + BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => { + self.implicit_conversion(&mut right, right_meta, ScalarKind::Uint, 4)? + } + _ => self + .binary_implicit_conversion(&mut left, left_meta, &mut right, right_meta)?, } - frontend.typifier_grow(self, left, left_meta)?; - frontend.typifier_grow(self, right, right_meta)?; + self.typifier_grow(left, left_meta)?; + self.typifier_grow(right, right_meta)?; - let left_inner = self.typifier.get(left, &frontend.module.types); - let right_inner = self.typifier.get(right, &frontend.module.types); + let left_inner = self.typifier.get(left, &self.module.types); + let right_inner = self.typifier.get(right, &self.module.types); match (left_inner, right_inner) { ( @@ -613,13 +628,11 @@ impl Context { let left_vector = self.add_expression( Expression::AccessIndex { base: left, index }, meta, - body, - ); + )?; let right_vector = self.add_expression( Expression::AccessIndex { base: right, index }, meta, - body, - ); + )?; // Divide the vectors let column = self.add_expression( @@ -629,31 +642,25 @@ impl Context { right: right_vector, }, meta, - body, - ); + )?; components.push(column) } - // Rebuild the matrix from the divided vectors - self.add_expression( - Expression::Compose { - ty: frontend.module.types.insert( - Type { - name: None, - inner: TypeInner::Matrix { - columns: left_columns, - rows: left_rows, - width: left_width, - }, - }, - Span::default(), - ), - components, + let ty = self.module.types.insert( + Type { + name: None, + inner: TypeInner::Matrix { + columns: left_columns, + rows: left_rows, + width: left_width, + }, }, - meta, - body, - ) + Span::default(), + ); + + // Rebuild the matrix from the divided vectors + self.add_expression(Expression::Compose { ty, components }, meta)? } BinaryOperator::Equal | BinaryOperator::NotEqual => { // Naga IR doesn't support matrix comparisons so we need to @@ -683,13 +690,11 @@ impl Context { let left_vector = self.add_expression( Expression::AccessIndex { base: left, index }, meta, - body, - ); + )?; let right_vector = self.add_expression( Expression::AccessIndex { base: right, index }, meta, - body, - ); + )?; let argument = self.add_expression( Expression::Binary { @@ -698,8 +703,7 @@ impl Context { right: right_vector, }, meta, - body, - ); + )?; // The result of comparing two vectors is a boolean vector // so use a relational function like all to get a single @@ -707,8 +711,7 @@ impl Context { let compare = self.add_expression( Expression::Relational { fun, argument }, meta, - body, - ); + )?; // Fold the result root = Some(match root { @@ -719,19 +722,16 @@ impl Context { right, }, meta, - body, - ), + )?, None => compare, }); } root.unwrap() } - _ => self.add_expression( - Expression::Binary { left, op, right }, - meta, - body, - ), + _ => { + self.add_expression(Expression::Binary { left, op, right }, meta)? + } } } (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) => match op { @@ -743,21 +743,12 @@ impl Context { false => (BinaryOperator::NotEqual, RelationalFunction::Any), }; - let argument = self.add_expression( - Expression::Binary { op, left, right }, - meta, - body, - ); + let argument = + self.add_expression(Expression::Binary { op, left, right }, meta)?; - self.add_expression( - Expression::Relational { fun, argument }, - meta, - body, - ) - } - _ => { - self.add_expression(Expression::Binary { left, op, right }, meta, body) + self.add_expression(Expression::Relational { fun, argument }, meta)? } + _ => self.add_expression(Expression::Binary { left, op, right }, meta)?, }, (&TypeInner::Vector { size, .. }, &TypeInner::Scalar { .. }) => match op { BinaryOperator::Add @@ -768,11 +759,8 @@ impl Context { | BinaryOperator::InclusiveOr | BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => { - let scalar_vector = self.add_expression( - Expression::Splat { size, value: right }, - meta, - body, - ); + let scalar_vector = self + .add_expression(Expression::Splat { size, value: right }, meta)?; self.add_expression( Expression::Binary { @@ -781,12 +769,9 @@ impl Context { right: scalar_vector, }, meta, - body, - ) - } - _ => { - self.add_expression(Expression::Binary { left, op, right }, meta, body) + )? } + _ => self.add_expression(Expression::Binary { left, op, right }, meta)?, }, (&TypeInner::Scalar { .. }, &TypeInner::Vector { size, .. }) => match op { BinaryOperator::Add @@ -795,11 +780,8 @@ impl Context { | BinaryOperator::And | BinaryOperator::ExclusiveOr | BinaryOperator::InclusiveOr => { - let scalar_vector = self.add_expression( - Expression::Splat { size, value: left }, - meta, - body, - ); + let scalar_vector = + self.add_expression(Expression::Splat { size, value: left }, meta)?; self.add_expression( Expression::Binary { @@ -808,12 +790,9 @@ impl Context { right, }, meta, - body, - ) - } - _ => { - self.add_expression(Expression::Binary { left, op, right }, meta, body) + )? } + _ => self.add_expression(Expression::Binary { left, op, right }, meta)?, }, ( &TypeInner::Scalar { @@ -852,8 +831,7 @@ impl Context { value: left, }, meta, - body, - ); + )?; let mut components = Vec::with_capacity(columns as usize); @@ -862,8 +840,7 @@ impl Context { let matrix_column = self.add_expression( Expression::AccessIndex { base: right, index }, meta, - body, - ); + )?; // Apply the operation to the splatted vector and // the column vector @@ -874,37 +851,29 @@ impl Context { right: matrix_column, }, meta, - body, - ); + )?; components.push(column) } - // Rebuild the matrix from the operation result vectors - self.add_expression( - Expression::Compose { - ty: frontend.module.types.insert( - Type { - name: None, - inner: TypeInner::Matrix { - columns, - rows, - width: left_width, - }, - }, - Span::default(), - ), - components, + let ty = self.module.types.insert( + Type { + name: None, + inner: TypeInner::Matrix { + columns, + rows, + width: left_width, + }, }, - meta, - body, - ) + Span::default(), + ); + + // Rebuild the matrix from the operation result vectors + self.add_expression(Expression::Compose { ty, components }, meta)? + } + _ => { + self.add_expression(Expression::Binary { left, op, right }, meta)? } - _ => self.add_expression( - Expression::Binary { left, op, right }, - meta, - body, - ), } } ( @@ -945,8 +914,7 @@ impl Context { value: right, }, meta, - body, - ); + )?; let mut components = Vec::with_capacity(columns as usize); @@ -955,8 +923,7 @@ impl Context { let matrix_column = self.add_expression( Expression::AccessIndex { base: left, index }, meta, - body, - ); + )?; // Apply the operation to the splatted vector and // the column vector @@ -967,48 +934,40 @@ impl Context { right: scalar_vector, }, meta, - body, - ); + )?; components.push(column) } - // Rebuild the matrix from the operation result vectors - self.add_expression( - Expression::Compose { - ty: frontend.module.types.insert( - Type { - name: None, - inner: TypeInner::Matrix { - columns, - rows, - width: left_width, - }, - }, - Span::default(), - ), - components, + let ty = self.module.types.insert( + Type { + name: None, + inner: TypeInner::Matrix { + columns, + rows, + width: left_width, + }, }, - meta, - body, - ) + Span::default(), + ); + + // Rebuild the matrix from the operation result vectors + self.add_expression(Expression::Compose { ty, components }, meta)? + } + _ => { + self.add_expression(Expression::Binary { left, op, right }, meta)? } - _ => self.add_expression( - Expression::Binary { left, op, right }, - meta, - body, - ), } } - _ => self.add_expression(Expression::Binary { left, op, right }, meta, body), + _ => self.add_expression(Expression::Binary { left, op, right }, meta)?, } } HirExprKind::Unary { op, expr } if pos != ExprPos::Lhs => { let expr = self - .lower_expect_inner(stmt, frontend, expr, ExprPos::Rhs, body)? + .lower_expect_inner(stmt, frontend, expr, ExprPos::Rhs)? .0; - self.add_expression(Expression::Unary { op, expr }, meta, body) + self.add_expression(Expression::Unary { op, expr }, meta)? } HirExprKind::Variable(ref var) => match pos { ExprPos::Lhs => { @@ -1034,7 +993,7 @@ impl Context { LocalVariable { name: None, ty, - init: Some(frontend.module.const_expressions.append( + init: Some(self.module.const_expressions.append( Expression::Constant(constant), Span::default(), )), @@ -1042,11 +1001,7 @@ impl Context { Span::default(), ); - self.add_expression( - Expression::LocalVariable(local), - Span::default(), - body, - ) + self.add_expression(Expression::LocalVariable(local), Span::default())? } else { var.expr } @@ -1055,7 +1010,7 @@ impl Context { } } _ if var.load => { - self.add_expression(Expression::Load { pointer: var.expr }, meta, body) + self.add_expression(Expression::Load { pointer: var.expr }, meta)? } ExprPos::Rhs => var.expr, }, @@ -1063,7 +1018,6 @@ impl Context { let maybe_expr = frontend.function_or_constructor_call( self, stmt, - body, call.kind.clone(), &call.args, meta, @@ -1096,31 +1050,20 @@ impl Context { // Lower the condition first to the current bodyy let condition = self - .lower_expect_inner(stmt, frontend, condition, ExprPos::Rhs, body)? + .lower_expect_inner(stmt, frontend, condition, ExprPos::Rhs)? .0; - // Emit all expressions since we will be adding statements to - // other bodies next - self.emit_restart(body); + let (mut accept_body, (mut accept, accept_meta)) = + self.new_body_with_ret(|ctx| { + // Lower the `true` branch + ctx.lower_expect_inner(stmt, frontend, accept, pos) + })?; - // Create the bodies for the two cases - let mut accept_body = Block::new(); - let mut reject_body = Block::new(); - - // Lower the `true` branch - let (mut accept, accept_meta) = - self.lower_expect_inner(stmt, frontend, accept, pos, &mut accept_body)?; - - // Flush the body of the `true` branch, to start emitting on the - // `false` branch - self.emit_restart(&mut accept_body); - - // Lower the `false` branch - let (mut reject, reject_meta) = - self.lower_expect_inner(stmt, frontend, reject, pos, &mut reject_body)?; - - // Flush the body of the `false` branch - self.emit_restart(&mut reject_body); + let (mut reject_body, (mut reject, reject_meta)) = + self.new_body_with_ret(|ctx| { + // Lower the `false` branch + ctx.lower_expect_inner(stmt, frontend, reject, pos) + })?; // We need to do some custom implicit conversions since the two target expressions // are in different bodies @@ -1129,36 +1072,34 @@ impl Context { Some((reject_power, reject_width, reject_kind)), ) = ( // Get the components of both branches and calculate the type power - self.expr_scalar_components(frontend, accept, accept_meta)? + self.expr_scalar_components(accept, accept_meta)? .and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), - self.expr_scalar_components(frontend, reject, reject_meta)? + self.expr_scalar_components(reject, reject_meta)? .and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), ) { match accept_power.cmp(&reject_power) { std::cmp::Ordering::Less => { - self.conversion( - &mut accept, - accept_meta, - reject_kind, - reject_width, - &mut accept_body, - )?; - // The expression belongs to the `true` branch so we need to flush to - // the respective body - self.emit_restart(&mut accept_body); + accept_body = self.with_body(accept_body, |ctx| { + ctx.conversion( + &mut accept, + accept_meta, + reject_kind, + reject_width, + )?; + Ok(()) + })?; } std::cmp::Ordering::Equal => {} std::cmp::Ordering::Greater => { - self.conversion( - &mut reject, - reject_meta, - accept_kind, - accept_width, - &mut reject_body, - )?; - // The expression belongs to the `false` branch so we need to flush to - // the respective body - self.emit_restart(&mut reject_body); + reject_body = self.with_body(reject_body, |ctx| { + ctx.conversion( + &mut reject, + reject_meta, + accept_kind, + accept_width, + )?; + Ok(()) + })?; } } } @@ -1166,7 +1107,7 @@ impl Context { // We need to get the type of the resulting expression to create the local, // this must be done after implicit conversions to ensure both branches have // the same type. - let ty = frontend.resolve_type_handle(self, accept, accept_meta)?; + let ty = self.resolve_type_handle(accept, accept_meta)?; // Add the local that will hold the result of our conditional let local = self.locals.append( @@ -1178,9 +1119,9 @@ impl Context { meta, ); - let local_expr = self.add_expression(Expression::LocalVariable(local), meta, body); + let local_expr = self.add_expression(Expression::LocalVariable(local), meta)?; - // Add to each body the store to the result variable + // Add to each the store to the result variable accept_body.push( Statement::Store { pointer: local_expr, @@ -1198,7 +1139,7 @@ impl Context { // Finally add the `If` to the main body with the `condition` we lowered // earlier and the branches we prepared. - body.push( + self.body.push( Statement::If { condition, accept: accept_body, @@ -1214,38 +1155,36 @@ impl Context { pointer: local_expr, }, meta, - body, - ) + )? } HirExprKind::Assign { tgt, value } if ExprPos::Lhs != pos => { let (pointer, ptr_meta) = - self.lower_expect_inner(stmt, frontend, tgt, ExprPos::Lhs, body)?; + self.lower_expect_inner(stmt, frontend, tgt, ExprPos::Lhs)?; let (mut value, value_meta) = - self.lower_expect_inner(stmt, frontend, value, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, value, ExprPos::Rhs)?; - let ty = match *frontend.resolve_type(self, pointer, ptr_meta)? { - TypeInner::Pointer { base, .. } => &frontend.module.types[base].inner, + let ty = match *self.resolve_type(pointer, ptr_meta)? { + TypeInner::Pointer { base, .. } => &self.module.types[base].inner, ref ty => ty, }; if let Some((kind, width)) = scalar_components(ty) { - self.implicit_conversion(frontend, &mut value, value_meta, kind, width, body)?; + self.implicit_conversion(&mut value, value_meta, kind, width)?; } - self.lower_store(pointer, value, meta, body); + self.lower_store(pointer, value, meta)?; value } HirExprKind::PrePostfix { op, postfix, expr } if ExprPos::Lhs != pos => { - let (pointer, _) = - self.lower_expect_inner(stmt, frontend, expr, ExprPos::Lhs, body)?; + let (pointer, _) = self.lower_expect_inner(stmt, frontend, expr, ExprPos::Lhs)?; let left = if let Expression::Swizzle { .. } = self.expressions[pointer] { pointer } else { - self.add_expression(Expression::Load { pointer }, meta, body) + self.add_expression(Expression::Load { pointer }, meta)? }; - let res = match *frontend.resolve_type(self, left, meta)? { + let res = match *self.resolve_type(left, meta)? { TypeInner::Scalar { kind, width } => { let ty = TypeInner::Scalar { kind, width }; Literal::one(kind, width).map(|i| (ty, i, None, None)) @@ -1282,18 +1221,17 @@ impl Context { } }; - let mut right = self.add_expression(Expression::Literal(literal), meta, body); + let mut right = self.add_expression(Expression::Literal(literal), meta)?; // Glsl allows pre/postfixes operations on vectors and matrices, so if the // target is either of them change the right side of the addition to be splatted // to the same size as the target, furthermore if the target is a matrix // use a composed matrix using the splatted value. if let Some(size) = rows { - right = - self.add_expression(Expression::Splat { size, value: right }, meta, body); + right = self.add_expression(Expression::Splat { size, value: right }, meta)?; if let Some(cols) = columns { - let ty = frontend.module.types.insert( + let ty = self.module.types.insert( Type { name: None, inner: ty_inner, @@ -1307,14 +1245,13 @@ impl Context { components: std::iter::repeat(right).take(cols as usize).collect(), }, meta, - body, - ); + )?; } } - let value = self.add_expression(Expression::Binary { op, left, right }, meta, body); + let value = self.add_expression(Expression::Binary { op, left, right }, meta)?; - self.lower_store(pointer, value, meta, body); + self.lower_store(pointer, value, meta)?; if postfix { left @@ -1329,7 +1266,7 @@ impl Context { } if ExprPos::Lhs != pos => { let args = args .iter() - .map(|e| self.lower_expect_inner(stmt, frontend, *e, ExprPos::Rhs, body)) + .map(|e| self.lower_expect_inner(stmt, frontend, *e, ExprPos::Rhs)) .collect::>>()?; match name.as_ref() { "length" => { @@ -1341,10 +1278,8 @@ impl Context { meta, }); } - let lowered_array = self - .lower_expect_inner(stmt, frontend, object, pos, body)? - .0; - let array_type = frontend.resolve_type(self, lowered_array, meta)?; + let lowered_array = self.lower_expect_inner(stmt, frontend, object, pos)?.0; + let array_type = self.resolve_type(lowered_array, meta)?; match *array_type { TypeInner::Array { @@ -1354,32 +1289,20 @@ impl Context { let mut array_length = self.add_expression( Expression::Literal(Literal::U32(size.get())), meta, - body, - ); + )?; self.forced_conversion( - frontend, &mut array_length, meta, ScalarKind::Sint, 4, - body, )?; array_length } // let the error be handled in type checking if it's not a dynamic array _ => { - let mut array_length = self.add_expression( - Expression::ArrayLength(lowered_array), - meta, - body, - ); - self.conversion( - &mut array_length, - meta, - ScalarKind::Sint, - 4, - body, - )?; + let mut array_length = self + .add_expression(Expression::ArrayLength(lowered_array), meta)?; + self.conversion(&mut array_length, meta, ScalarKind::Sint, 4)?; array_length } } @@ -1418,22 +1341,16 @@ impl Context { pub fn expr_scalar_components( &mut self, - frontend: &Frontend, expr: Handle, meta: Span, ) -> Result> { - let ty = frontend.resolve_type(self, expr, meta)?; + let ty = self.resolve_type(expr, meta)?; Ok(scalar_components(ty)) } - pub fn expr_power( - &mut self, - frontend: &Frontend, - expr: Handle, - meta: Span, - ) -> Result> { + pub fn expr_power(&mut self, expr: Handle, meta: Span) -> Result> { Ok(self - .expr_scalar_components(frontend, expr, meta)? + .expr_scalar_components(expr, meta)? .and_then(|(kind, width)| type_power(kind, width))) } @@ -1443,7 +1360,6 @@ impl Context { meta: Span, kind: ScalarKind, width: crate::Bytes, - body: &mut Block, ) -> Result<()> { *expr = self.add_expression( Expression::As { @@ -1452,27 +1368,23 @@ impl Context { convert: Some(width), }, meta, - body, - ); + )?; Ok(()) } pub fn implicit_conversion( &mut self, - frontend: &Frontend, expr: &mut Handle, meta: Span, kind: ScalarKind, width: crate::Bytes, - body: &mut Block, ) -> Result<()> { - if let (Some(tgt_power), Some(expr_power)) = ( - type_power(kind, width), - self.expr_power(frontend, *expr, meta)?, - ) { + if let (Some(tgt_power), Some(expr_power)) = + (type_power(kind, width), self.expr_power(*expr, meta)?) + { if tgt_power > expr_power { - self.conversion(expr, meta, kind, width, body)?; + self.conversion(expr, meta, kind, width)?; } } @@ -1481,18 +1393,14 @@ impl Context { pub fn forced_conversion( &mut self, - frontend: &Frontend, expr: &mut Handle, meta: Span, kind: ScalarKind, width: crate::Bytes, - body: &mut Block, ) -> Result<()> { - if let Some((expr_scalar_kind, expr_width)) = - self.expr_scalar_components(frontend, *expr, meta)? - { + if let Some((expr_scalar_kind, expr_width)) = self.expr_scalar_components(*expr, meta)? { if expr_scalar_kind != kind || expr_width != width { - self.conversion(expr, meta, kind, width, body)?; + self.conversion(expr, meta, kind, width)?; } } @@ -1501,15 +1409,13 @@ impl Context { pub fn binary_implicit_conversion( &mut self, - frontend: &Frontend, left: &mut Handle, left_meta: Span, right: &mut Handle, right_meta: Span, - body: &mut Block, ) -> Result<()> { - let left_components = self.expr_scalar_components(frontend, *left, left_meta)?; - let right_components = self.expr_scalar_components(frontend, *right, right_meta)?; + let left_components = self.expr_scalar_components(*left, left_meta)?; + let right_components = self.expr_scalar_components(*right, right_meta)?; if let ( Some((left_power, left_width, left_kind)), @@ -1521,11 +1427,11 @@ impl Context { ) { match left_power.cmp(&right_power) { std::cmp::Ordering::Less => { - self.conversion(left, left_meta, right_kind, right_width, body)?; + self.conversion(left, left_meta, right_kind, right_width)?; } std::cmp::Ordering::Equal => {} std::cmp::Ordering::Greater => { - self.conversion(right, right_meta, left_kind, left_width, body)?; + self.conversion(right, right_meta, left_kind, left_width)?; } } } @@ -1535,16 +1441,14 @@ impl Context { pub fn implicit_splat( &mut self, - frontend: &Frontend, expr: &mut Handle, meta: Span, vector_size: Option, - body: &mut Block, ) -> Result<()> { - let expr_type = frontend.resolve_type(self, *expr, meta)?; + let expr_type = self.resolve_type(*expr, meta)?; if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { - *expr = self.add_expression(Expression::Splat { size, value: *expr }, meta, body) + *expr = self.add_expression(Expression::Splat { size, value: *expr }, meta)? } Ok(()) @@ -1555,8 +1459,7 @@ impl Context { size: VectorSize, vector: Handle, meta: Span, - body: &mut Block, - ) -> Handle { + ) -> Result> { self.add_expression( Expression::Swizzle { size, @@ -1564,12 +1467,11 @@ impl Context { pattern: crate::SwizzleComponent::XYZW, }, meta, - body, ) } } -impl Index> for Context { +impl Index> for Context<'_> { type Output = Expression; fn index(&self, index: Handle) -> &Self::Output { diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index f85c76505..061494387 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -7,9 +7,9 @@ use super::{ Frontend, Result, }; use crate::{ - front::glsl::types::type_power, proc::ensure_block_returns, AddressSpace, Arena, Block, - EntryPoint, Expression, Function, FunctionArgument, FunctionResult, Handle, Literal, - LocalVariable, ScalarKind, Span, Statement, StructMember, Type, TypeInner, + front::glsl::types::type_power, proc::ensure_block_returns, AddressSpace, Block, EntryPoint, + Expression, Function, FunctionArgument, FunctionResult, Handle, Literal, LocalVariable, + ScalarKind, Span, Statement, StructMember, Type, TypeInner, }; use std::iter; @@ -28,27 +28,25 @@ impl Frontend { &mut self, ctx: &mut Context, stmt: &StmtContext, - body: &mut Block, fc: FunctionCallKind, raw_args: &[Handle], meta: Span, ) -> Result>> { let args: Vec<_> = raw_args .iter() - .map(|e| ctx.lower_expect_inner(stmt, self, *e, ExprPos::Rhs, body)) + .map(|e| ctx.lower_expect_inner(stmt, self, *e, ExprPos::Rhs)) .collect::>()?; match fc { FunctionCallKind::TypeConstructor(ty) => { if args.len() == 1 { - self.constructor_single(ctx, body, ty, args[0], meta) - .map(Some) + self.constructor_single(ctx, ty, args[0], meta).map(Some) } else { - self.constructor_many(ctx, body, ty, args, meta).map(Some) + self.constructor_many(ctx, ty, args, meta).map(Some) } } FunctionCallKind::Function(name) => { - self.function_call(ctx, stmt, body, name, args, raw_args, meta) + self.function_call(ctx, stmt, name, args, raw_args, meta) } } } @@ -56,31 +54,29 @@ impl Frontend { fn constructor_single( &mut self, ctx: &mut Context, - body: &mut Block, ty: Handle, (mut value, expr_meta): (Handle, Span), meta: Span, ) -> Result> { - let expr_type = self.resolve_type(ctx, value, expr_meta)?; + let expr_type = ctx.resolve_type(value, expr_meta)?; let vector_size = match *expr_type { TypeInner::Vector { size, .. } => Some(size), _ => None, }; + let expr_is_bool = expr_type.scalar_kind() == Some(ScalarKind::Bool); + // Special case: if casting from a bool, we need to use Select and not As. - match self.module.types[ty].inner.scalar_kind() { - Some(result_scalar_kind) - if expr_type.scalar_kind() == Some(ScalarKind::Bool) - && result_scalar_kind != ScalarKind::Bool => - { + match ctx.module.types[ty].inner.scalar_kind() { + Some(result_scalar_kind) if expr_is_bool && result_scalar_kind != ScalarKind::Bool => { let l0 = Literal::zero(result_scalar_kind, 4).unwrap(); let l1 = Literal::one(result_scalar_kind, 4).unwrap(); - let mut reject = ctx.add_expression(Expression::Literal(l0), expr_meta, body); - let mut accept = ctx.add_expression(Expression::Literal(l1), expr_meta, body); + let mut reject = ctx.add_expression(Expression::Literal(l0), expr_meta)?; + let mut accept = ctx.add_expression(Expression::Literal(l1), expr_meta)?; - ctx.implicit_splat(self, &mut reject, meta, vector_size, body)?; - ctx.implicit_splat(self, &mut accept, meta, vector_size, body)?; + ctx.implicit_splat(&mut reject, meta, vector_size)?; + ctx.implicit_splat(&mut accept, meta, vector_size)?; let h = ctx.add_expression( Expression::Select { @@ -89,24 +85,22 @@ impl Frontend { condition: value, }, expr_meta, - body, - ); + )?; return Ok(h); } _ => {} } - Ok(match self.module.types[ty].inner { + Ok(match ctx.module.types[ty].inner { TypeInner::Vector { size, kind, width } if vector_size.is_none() => { - ctx.forced_conversion(self, &mut value, expr_meta, kind, width, body)?; + ctx.forced_conversion(&mut value, expr_meta, kind, width)?; - if let TypeInner::Scalar { .. } = *self.resolve_type(ctx, value, expr_meta)? { - ctx.add_expression(Expression::Splat { size, value }, meta, body) + if let TypeInner::Scalar { .. } = *ctx.resolve_type(value, expr_meta)? { + ctx.add_expression(Expression::Splat { size, value }, meta)? } else { self.vector_constructor( ctx, - body, ty, size, kind, @@ -119,7 +113,7 @@ impl Frontend { TypeInner::Scalar { kind, width } => { let mut expr = value; if let TypeInner::Vector { .. } | TypeInner::Matrix { .. } = - *self.resolve_type(ctx, value, expr_meta)? + *ctx.resolve_type(value, expr_meta)? { expr = ctx.add_expression( Expression::AccessIndex { @@ -127,19 +121,17 @@ impl Frontend { index: 0, }, meta, - body, - ); + )?; } - if let TypeInner::Matrix { .. } = *self.resolve_type(ctx, value, expr_meta)? { + if let TypeInner::Matrix { .. } = *ctx.resolve_type(value, expr_meta)? { expr = ctx.add_expression( Expression::AccessIndex { base: expr, index: 0, }, meta, - body, - ); + )?; } ctx.add_expression( @@ -149,12 +141,11 @@ impl Frontend { convert: Some(width), }, meta, - body, - ) + )? } TypeInner::Vector { size, kind, width } => { if vector_size.map_or(true, |s| s != size) { - value = ctx.vector_resize(size, value, expr_meta, body); + value = ctx.vector_resize(size, value, expr_meta)?; } ctx.add_expression( @@ -164,29 +155,19 @@ impl Frontend { convert: Some(width), }, meta, - body, - ) + )? } TypeInner::Matrix { columns, rows, width, - } => self.matrix_one_arg( - ctx, - body, - ty, - columns, - rows, - width, - (value, expr_meta), - meta, - )?, + } => self.matrix_one_arg(ctx, ty, columns, rows, width, (value, expr_meta), meta)?, TypeInner::Struct { ref members, .. } => { let scalar_components = members .get(0) - .and_then(|member| scalar_components(&self.module.types[member.ty].inner)); + .and_then(|member| scalar_components(&ctx.module.types[member.ty].inner)); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut value, expr_meta, kind, width, body)?; + ctx.implicit_conversion(&mut value, expr_meta, kind, width)?; } ctx.add_expression( @@ -195,14 +176,13 @@ impl Frontend { components: vec![value], }, meta, - body, - ) + )? } TypeInner::Array { base, .. } => { - let scalar_components = scalar_components(&self.module.types[base].inner); + let scalar_components = scalar_components(&ctx.module.types[base].inner); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut value, expr_meta, kind, width, body)?; + ctx.implicit_conversion(&mut value, expr_meta, kind, width)?; } ctx.add_expression( @@ -211,8 +191,7 @@ impl Frontend { components: vec![value], }, meta, - body, - ) + )? } _ => { self.errors.push(Error { @@ -229,7 +208,6 @@ impl Frontend { fn matrix_one_arg( &mut self, ctx: &mut Context, - body: &mut Block, ty: Handle, columns: crate::VectorSize, rows: crate::VectorSize, @@ -242,13 +220,13 @@ impl Frontend { // `Expression::As` doesn't support matrix width // casts so we need to do some extra work for casts - ctx.forced_conversion(self, &mut value, expr_meta, ScalarKind::Float, width, body)?; - match *self.resolve_type(ctx, value, expr_meta)? { + ctx.forced_conversion(&mut value, expr_meta, ScalarKind::Float, width)?; + match *ctx.resolve_type(value, expr_meta)? { TypeInner::Scalar { .. } => { // If a matrix is constructed with a single scalar value, then that // value is used to initialize all the values along the diagonal of // the matrix; the rest are given zeros. - let vector_ty = self.module.types.insert( + let vector_ty = ctx.module.types.insert( Type { name: None, inner: TypeInner::Vector { @@ -261,7 +239,7 @@ impl Frontend { ); let zero_literal = Literal::zero(ScalarKind::Float, width).unwrap(); - let zero = ctx.add_expression(Expression::Literal(zero_literal), meta, body); + let zero = ctx.add_expression(Expression::Literal(zero_literal), meta)?; for i in 0..columns as u32 { components.push( @@ -276,8 +254,7 @@ impl Frontend { .collect(), }, meta, - body, - ), + )?, ) } } @@ -294,10 +271,10 @@ impl Frontend { let zero_literal = Literal::zero(ScalarKind::Float, width).unwrap(); let one_literal = Literal::one(ScalarKind::Float, width).unwrap(); - let zero = ctx.add_expression(Expression::Literal(zero_literal), meta, body); - let one = ctx.add_expression(Expression::Literal(one_literal), meta, body); + let zero = ctx.add_expression(Expression::Literal(zero_literal), meta)?; + let one = ctx.add_expression(Expression::Literal(one_literal), meta)?; - let vector_ty = self.module.types.insert( + let vector_ty = ctx.module.types.insert( Type { name: None, inner: TypeInner::Vector { @@ -319,8 +296,7 @@ impl Frontend { index: i, }, meta, - body, - ); + )?; components.push(match ori_rows.cmp(&rows) { Ordering::Less => { @@ -333,15 +309,14 @@ impl Frontend { index: r, }, meta, - body, ) } else if r == i { - one + Ok(one) } else { - zero + Ok(zero) } }) - .collect(); + .collect::>()?; ctx.add_expression( Expression::Compose { @@ -349,11 +324,10 @@ impl Frontend { components, }, meta, - body, - ) + )? } Ordering::Equal => vector, - Ordering::Greater => ctx.vector_resize(rows, vector, meta, body), + Ordering::Greater => ctx.vector_resize(rows, vector, meta)?, }) } else { let compose_expr = Expression::Compose { @@ -366,7 +340,7 @@ impl Frontend { .collect(), }; - let vec = ctx.add_expression(compose_expr, meta, body); + let vec = ctx.add_expression(compose_expr, meta)?; components.push(vec) } @@ -377,14 +351,13 @@ impl Frontend { } } - Ok(ctx.add_expression(Expression::Compose { ty, components }, meta, body)) + ctx.add_expression(Expression::Compose { ty, components }, meta) } #[allow(clippy::too_many_arguments)] fn vector_constructor( &mut self, ctx: &mut Context, - body: &mut Block, ty: Handle, size: crate::VectorSize, kind: ScalarKind, @@ -395,13 +368,13 @@ impl Frontend { let mut components = Vec::with_capacity(size as usize); for (mut arg, expr_meta) in args.iter().copied() { - ctx.forced_conversion(self, &mut arg, expr_meta, kind, width, body)?; + ctx.forced_conversion(&mut arg, expr_meta, kind, width)?; if components.len() >= size as usize { break; } - match *self.resolve_type(ctx, arg, expr_meta)? { + match *ctx.resolve_type(arg, expr_meta)? { TypeInner::Scalar { .. } => components.push(arg), TypeInner::Matrix { rows, columns, .. } => { components.reserve(rows as usize * columns as usize); @@ -412,14 +385,12 @@ impl Frontend { index: c, }, expr_meta, - body, - ); + )?; for r in 0..(rows as u32) { components.push(ctx.add_expression( Expression::AccessIndex { base, index: r }, expr_meta, - body, - )) + )?) } } } @@ -429,8 +400,7 @@ impl Frontend { components.push(ctx.add_expression( Expression::AccessIndex { base: arg, index }, expr_meta, - body, - )) + )?) } } _ => components.push(arg), @@ -439,20 +409,19 @@ impl Frontend { components.truncate(size as usize); - Ok(ctx.add_expression(Expression::Compose { ty, components }, meta, body)) + ctx.add_expression(Expression::Compose { ty, components }, meta) } fn constructor_many( &mut self, ctx: &mut Context, - body: &mut Block, ty: Handle, args: Vec<(Handle, Span)>, meta: Span, ) -> Result> { let mut components = Vec::with_capacity(args.len()); - match self.module.types[ty].inner { + let struct_member_data = match ctx.module.types[ty].inner { TypeInner::Matrix { columns, rows, @@ -461,9 +430,9 @@ impl Frontend { let mut flattened = Vec::with_capacity(columns as usize * rows as usize); for (mut arg, meta) in args.iter().copied() { - ctx.forced_conversion(self, &mut arg, meta, ScalarKind::Float, width, body)?; + ctx.forced_conversion(&mut arg, meta, ScalarKind::Float, width)?; - match *self.resolve_type(ctx, arg, meta)? { + match *ctx.resolve_type(arg, meta)? { TypeInner::Vector { size, .. } => { for i in 0..(size as u32) { flattened.push(ctx.add_expression( @@ -472,15 +441,14 @@ impl Frontend { index: i, }, meta, - body, - )) + )?) } } _ => flattened.push(arg), } } - let ty = self.module.types.insert( + let ty = ctx.module.types.insert( Type { name: None, inner: TypeInner::Vector { @@ -499,42 +467,51 @@ impl Frontend { components: Vec::from(chunk), }, meta, - body, - )) + )?) } + None } TypeInner::Vector { size, kind, width } => { - return self.vector_constructor(ctx, body, ty, size, kind, width, &args, meta) + return self.vector_constructor(ctx, ty, size, kind, width, &args, meta) } TypeInner::Array { base, .. } => { for (mut arg, meta) in args.iter().copied() { - let scalar_components = scalar_components(&self.module.types[base].inner); + let scalar_components = scalar_components(&ctx.module.types[base].inner); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut arg, meta, kind, width, body)?; - } - - components.push(arg) - } - } - TypeInner::Struct { ref members, .. } => { - for ((mut arg, meta), member) in args.iter().copied().zip(members.iter()) { - let scalar_components = scalar_components(&self.module.types[member.ty].inner); - if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(self, &mut arg, meta, kind, width, body)?; + ctx.implicit_conversion(&mut arg, meta, kind, width)?; } components.push(arg) } + None } + TypeInner::Struct { ref members, .. } => Some( + members + .iter() + .map(|member| scalar_components(&ctx.module.types[member.ty].inner)) + .collect::>(), + ), _ => { return Err(Error { kind: ErrorKind::SemanticError("Constructor: Too many arguments".into()), meta, }) } + }; + + if let Some(struct_member_data) = struct_member_data { + for ((mut arg, meta), scalar_components) in + args.iter().copied().zip(struct_member_data.iter().copied()) + { + if let Some((kind, width)) = scalar_components { + ctx.implicit_conversion(&mut arg, meta, kind, width)?; + } + + components.push(arg) + } } - Ok(ctx.add_expression(Expression::Compose { ty, components }, meta, body)) + ctx.add_expression(Expression::Compose { ty, components }, meta) } #[allow(clippy::too_many_arguments)] @@ -542,7 +519,6 @@ impl Frontend { &mut self, ctx: &mut Context, stmt: &StmtContext, - body: &mut Block, name: String, args: Vec<(Handle, Span)>, raw_args: &[Handle], @@ -551,13 +527,13 @@ impl Frontend { // Grow the typifier to be able to index it later without needing // to hold the context mutably for &(expr, span) in args.iter() { - self.typifier_grow(ctx, expr, span)?; + ctx.typifier_grow(expr, span)?; } // Check if the passed arguments require any special variations let mut variations = builtin_required_variations( args.iter() - .map(|&(expr, _)| ctx.typifier.get(expr, &self.module.types)), + .map(|&(expr, _)| ctx.typifier.get(expr, &ctx.module.types)), ); // Initiate the declaration if it wasn't previously initialized and inject builtins @@ -565,7 +541,7 @@ impl Frontend { variations |= BuiltinVariations::STANDARD; Default::default() }); - inject_builtin(declaration, &mut self.module, &name, variations); + inject_builtin(declaration, ctx.module, &name, variations); // Borrow again but without mutability, at this point a declaration is guaranteed let declaration = self.lookup_function.get(&name).unwrap(); @@ -609,18 +585,14 @@ impl Frontend { // If the image is used in the overload as a depth texture convert it // before comparing, otherwise exact matches wouldn't be reported if parameter_info.depth { - sampled_to_depth( - &mut self.module, - ctx, - call_argument.0, - call_argument.1, - &mut self.errors, - ); - self.invalidate_expression(ctx, call_argument.0, call_argument.1)? + sampled_to_depth(ctx, call_argument.0, call_argument.1, &mut self.errors); + ctx.invalidate_expression(call_argument.0, call_argument.1)? } - let overload_param_ty = &self.module.types[*overload_parameter].inner; - let call_arg_ty = self.resolve_type(ctx, call_argument.0, call_argument.1)?; + ctx.typifier_grow(call_argument.0, call_argument.1)?; + + let overload_param_ty = &ctx.module.types[*overload_parameter].inner; + let call_arg_ty = ctx.typifier.get(call_argument.0, &ctx.module.types); log::trace!( "Testing parameter {}\n\tOverload = {:?}\n\tCall = {:?}", @@ -823,12 +795,11 @@ impl Frontend { .zip(¶meters) { let (mut handle, meta) = - ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.as_pos(), body)?; + ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.as_pos())?; if parameter_info.qualifier.is_lhs() { self.process_lhs_argument( ctx, - body, meta, *parameter, parameter_info, @@ -841,11 +812,11 @@ impl Frontend { continue; } - let scalar_comps = scalar_components(&self.module.types[*parameter].inner); + let scalar_comps = scalar_components(&ctx.module.types[*parameter].inner); // Apply implicit conversions as needed if let Some((kind, width)) = scalar_comps { - ctx.implicit_conversion(self, &mut handle, meta, kind, width, body)?; + ctx.implicit_conversion(&mut handle, meta, kind, width)?; } arguments.push(handle) @@ -853,15 +824,15 @@ impl Frontend { match kind { FunctionKind::Call(function) => { - ctx.emit_end(body); + ctx.emit_end(); let result = if !is_void { - Some(ctx.add_expression(Expression::CallResult(function), meta, body)) + Some(ctx.add_expression(Expression::CallResult(function), meta)?) } else { None }; - body.push( + ctx.body.push( crate::Statement::Call { function, arguments, @@ -879,16 +850,15 @@ impl Frontend { pointer: proxy_write.value, }, meta, - body, - ); + )?; if let Some((kind, width)) = proxy_write.convert { - ctx.conversion(&mut value, meta, kind, width, body)?; + ctx.conversion(&mut value, meta, kind, width)?; } - ctx.emit_restart(body); + ctx.emit_restart(); - body.push( + ctx.body.push( Statement::Store { pointer: proxy_write.target, value, @@ -899,9 +869,7 @@ impl Frontend { Ok(result) } - FunctionKind::Macro(builtin) => { - builtin.call(self, ctx, body, arguments.as_mut_slice(), meta) - } + FunctionKind::Macro(builtin) => builtin.call(self, ctx, arguments.as_mut_slice(), meta), } } @@ -911,7 +879,6 @@ impl Frontend { fn process_lhs_argument( &mut self, ctx: &mut Context, - body: &mut Block, meta: Span, parameter_ty: Handle, parameter_info: &ParameterInfo, @@ -920,7 +887,7 @@ impl Frontend { proxy_writes: &mut Vec, arguments: &mut Vec>, ) -> Result<()> { - let original_ty = self.resolve_type(ctx, original, meta)?; + let original_ty = ctx.resolve_type(original, meta)?; let original_pointer_space = original_ty.pointer_space(); // The type of a possible spill variable needed for a proxy write @@ -928,7 +895,7 @@ impl Frontend { // If the argument is to be passed as a pointer but the type of the // expression returns a vector it must mean that it was for example // swizzled and it must be spilled into a local before calling - TypeInner::Vector { size, kind, width } => Some(self.module.types.insert( + TypeInner::Vector { size, kind, width } => Some(ctx.module.types.insert( Type { name: None, inner: TypeInner::Vector { size, kind, width }, @@ -951,7 +918,7 @@ impl Frontend { }; Some( - self.module + ctx.module .types .insert(Type { name: None, inner }, Span::default()), ) @@ -962,17 +929,15 @@ impl Frontend { // Since the original expression might be a pointer and we want a value // for the proxy writes, we might need to load the pointer. let value = if original_pointer_space.is_some() { - ctx.add_expression( - Expression::Load { pointer: original }, - Span::default(), - body, - ) + ctx.add_expression(Expression::Load { pointer: original }, Span::default())? } else { original }; - let call_arg_ty = self.resolve_type(ctx, call_argument.0, call_argument.1)?; - let overload_param_ty = &self.module.types[parameter_ty].inner; + ctx.typifier_grow(call_argument.0, call_argument.1)?; + + let overload_param_ty = &ctx.module.types[parameter_ty].inner; + let call_arg_ty = ctx.typifier.get(call_argument.0, &ctx.module.types); let needs_conversion = call_arg_ty != overload_param_ty; let arg_scalar_comps = scalar_components(call_arg_ty); @@ -995,12 +960,12 @@ impl Frontend { Span::default(), ); let spill_expr = - ctx.add_expression(Expression::LocalVariable(spill_var), Span::default(), body); + ctx.add_expression(Expression::LocalVariable(spill_var), Span::default())?; // If the argument is also copied in we must store the value of the // original variable to the spill variable. if let ParameterQualifier::InOut = parameter_info.qualifier { - body.push( + ctx.body.push( Statement::Store { pointer: spill_expr, value, @@ -1037,8 +1002,7 @@ impl Frontend { index: *component as u32, }, Span::default(), - body, - ); + )?; let spill_component = ctx.add_expression( Expression::AccessIndex { @@ -1046,8 +1010,7 @@ impl Frontend { index: i as u32, }, Span::default(), - body, - ); + )?; proxy_writes.push(ProxyWrite { target: original, @@ -1071,32 +1034,28 @@ impl Frontend { pub(crate) fn add_function( &mut self, - ctx: Context, + mut ctx: Context, name: String, result: Option, - mut body: Block, meta: Span, ) { - ensure_block_returns(&mut body); + ensure_block_returns(&mut ctx.body); let void = result.is_none(); - let &mut Frontend { - ref mut lookup_function, - ref mut module, - .. - } = self; - // Check if the passed arguments require any special variations - let mut variations = - builtin_required_variations(ctx.parameters.iter().map(|&arg| &module.types[arg].inner)); + let mut variations = builtin_required_variations( + ctx.parameters + .iter() + .map(|&arg| &ctx.module.types[arg].inner), + ); // Initiate the declaration if it wasn't previously initialized and inject builtins - let declaration = lookup_function.entry(name.clone()).or_insert_with(|| { + let declaration = self.lookup_function.entry(name.clone()).or_insert_with(|| { variations |= BuiltinVariations::STANDARD; Default::default() }); - inject_builtin(declaration, module, &name, variations); + inject_builtin(declaration, ctx.module, &name, variations); let Context { expressions, @@ -1104,6 +1063,8 @@ impl Frontend { arguments, parameters, parameters_info, + body, + module, .. } = ctx; @@ -1141,7 +1102,7 @@ impl Frontend { decl.defined = true; decl.parameters_info = parameters_info; match decl.kind { - FunctionKind::Call(handle) => *self.module.functions.get_mut(handle) = function, + FunctionKind::Call(handle) => *module.functions.get_mut(handle) = function, FunctionKind::Macro(_) => { let handle = module.functions.append(function, meta); decl.kind = FunctionKind::Call(handle) @@ -1170,27 +1131,25 @@ impl Frontend { ) { let void = result.is_none(); - let &mut Frontend { - ref mut lookup_function, - ref mut module, - .. - } = self; - // Check if the passed arguments require any special variations - let mut variations = - builtin_required_variations(ctx.parameters.iter().map(|&arg| &module.types[arg].inner)); + let mut variations = builtin_required_variations( + ctx.parameters + .iter() + .map(|&arg| &ctx.module.types[arg].inner), + ); // Initiate the declaration if it wasn't previously initialized and inject builtins - let declaration = lookup_function.entry(name.clone()).or_insert_with(|| { + let declaration = self.lookup_function.entry(name.clone()).or_insert_with(|| { variations |= BuiltinVariations::STANDARD; Default::default() }); - inject_builtin(declaration, module, &name, variations); + inject_builtin(declaration, ctx.module, &name, variations); let Context { arguments, parameters, parameters_info, + module, .. } = ctx; @@ -1238,27 +1197,26 @@ impl Frontend { /// recursively /// /// The passed arguments to the callback are: + /// - The ctx /// - The name /// - The pointer expression to the global storage /// - The handle to the type of the entry point argument /// - The binding of the entry point argument - /// - The expression arena fn arg_type_walker( - &self, + ctx: &mut Context, name: Option, binding: crate::Binding, pointer: Handle, ty: Handle, - expressions: &mut Arena, f: &mut impl FnMut( + &mut Context, Option, Handle, Handle, crate::Binding, - &mut Arena, ), - ) { - match self.module.types[ty].inner { + ) -> Result<()> { + match ctx.module.types[ty].inner { // TODO: Better error reporting // right now we just don't walk the array if the size isn't known at // compile time and let validation catch it @@ -1269,11 +1227,11 @@ impl Frontend { } => { let mut location = match binding { crate::Binding::Location { location, .. } => location, - crate::Binding::BuiltIn(_) => return, + crate::Binding::BuiltIn(_) => return Ok(()), }; let interpolation = - self.module.types[base] + ctx.module.types[base] .inner .scalar_kind() .map(|kind| match kind { @@ -1282,13 +1240,13 @@ impl Frontend { }); for index in 0..size.get() { - let member_pointer = expressions.append( + let member_pointer = ctx.add_expression( Expression::AccessIndex { base: pointer, index, }, crate::Span::default(), - ); + )?; let binding = crate::Binding::Location { location, @@ -1298,35 +1256,28 @@ impl Frontend { }; location += 1; - self.arg_type_walker( - name.clone(), - binding, - member_pointer, - base, - expressions, - f, - ) + Self::arg_type_walker(ctx, name.clone(), binding, member_pointer, base, f)? } } TypeInner::Struct { ref members, .. } => { let mut location = match binding { crate::Binding::Location { location, .. } => location, - crate::Binding::BuiltIn(_) => return, + crate::Binding::BuiltIn(_) => return Ok(()), }; - for (i, member) in members.iter().enumerate() { - let member_pointer = expressions.append( + for (i, member) in members.clone().into_iter().enumerate() { + let member_pointer = ctx.add_expression( Expression::AccessIndex { base: pointer, index: i as u32, }, crate::Span::default(), - ); + )?; - let binding = match member.binding.clone() { + let binding = match member.binding { Some(binding) => binding, None => { - let interpolation = self.module.types[member.ty] + let interpolation = ctx.module.types[member.ty] .inner .scalar_kind() .map(|kind| match kind { @@ -1344,51 +1295,51 @@ impl Frontend { } }; - self.arg_type_walker( - member.name.clone(), - binding, - member_pointer, - member.ty, - expressions, - f, - ) + Self::arg_type_walker(ctx, member.name, binding, member_pointer, member.ty, f)? } } - _ => f(name, pointer, ty, binding, expressions), + _ => f(ctx, name, pointer, ty, binding), } + + Ok(()) } pub(crate) fn add_entry_point( &mut self, function: Handle, - global_init_body: Block, - mut expressions: Arena, - ) { + mut ctx: Context, + ) -> Result<()> { let mut arguments = Vec::new(); - let mut body = Block::with_capacity( + + let body = Block::with_capacity( // global init body - global_init_body.len() + - // prologue and epilogue - self.entry_args.len() * 2 - // Call, Emit for composing struct and return - + 3, + ctx.body.len() + + // prologue and epilogue + self.entry_args.len() * 2 + // Call, Emit for composing struct and return + + 3, ); + let global_init_body = std::mem::replace(&mut ctx.body, body); + for arg in self.entry_args.iter() { if arg.storage != StorageQualifier::Input { continue; } - let pointer = - expressions.append(Expression::GlobalVariable(arg.handle), Default::default()); + let pointer = ctx + .expressions + .append(Expression::GlobalVariable(arg.handle), Default::default()); - self.arg_type_walker( + let ty = ctx.module.global_variables[arg.handle].ty; + + Self::arg_type_walker( + &mut ctx, arg.name.clone(), arg.binding.clone(), pointer, - self.module.global_variables[arg.handle].ty, - &mut expressions, - &mut |name, pointer, ty, binding, expressions| { + ty, + &mut |ctx, name, pointer, ty, binding| { let idx = arguments.len() as u32; arguments.push(FunctionArgument { @@ -1397,16 +1348,18 @@ impl Frontend { binding: Some(binding), }); - let value = - expressions.append(Expression::FunctionArgument(idx), Default::default()); - body.push(Statement::Store { pointer, value }, Default::default()); + let value = ctx + .expressions + .append(Expression::FunctionArgument(idx), Default::default()); + ctx.body + .push(Statement::Store { pointer, value }, Default::default()); }, - ) + )? } - body.extend_block(global_init_body); + ctx.body.extend_block(global_init_body); - body.push( + ctx.body.push( Statement::Call { function, arguments: Vec::new(), @@ -1424,16 +1377,19 @@ impl Frontend { continue; } - let pointer = - expressions.append(Expression::GlobalVariable(arg.handle), Default::default()); + let pointer = ctx + .expressions + .append(Expression::GlobalVariable(arg.handle), Default::default()); - self.arg_type_walker( + let ty = ctx.module.global_variables[arg.handle].ty; + + Self::arg_type_walker( + &mut ctx, arg.name.clone(), arg.binding.clone(), pointer, - self.module.global_variables[arg.handle].ty, - &mut expressions, - &mut |name, pointer, ty, binding, expressions| { + ty, + &mut |ctx, name, pointer, ty, binding| { members.push(StructMember { name, ty, @@ -1441,21 +1397,23 @@ impl Frontend { offset: span, }); - span += self.module.types[ty].inner.size(self.module.to_ctx()); + span += ctx.module.types[ty].inner.size(ctx.module.to_ctx()); - let len = expressions.len(); - let load = expressions.append(Expression::Load { pointer }, Default::default()); - body.push( - Statement::Emit(expressions.range_from(len)), + let len = ctx.expressions.len(); + let load = ctx + .expressions + .append(Expression::Load { pointer }, Default::default()); + ctx.body.push( + Statement::Emit(ctx.expressions.range_from(len)), Default::default(), ); components.push(load) }, - ) + )? } let (ty, value) = if !components.is_empty() { - let ty = self.module.types.insert( + let ty = ctx.module.types.insert( Type { name: None, inner: TypeInner::Struct { members, span }, @@ -1463,11 +1421,12 @@ impl Frontend { Default::default(), ); - let len = expressions.len(); - let res = - expressions.append(Expression::Compose { ty, components }, Default::default()); - body.push( - Statement::Emit(expressions.range_from(len)), + let len = ctx.expressions.len(); + let res = ctx + .expressions + .append(Expression::Compose { ty, components }, Default::default()); + ctx.body.push( + Statement::Emit(ctx.expressions.range_from(len)), Default::default(), ); @@ -1476,9 +1435,14 @@ impl Frontend { (None, None) }; - body.push(Statement::Return { value }, Default::default()); + ctx.body + .push(Statement::Return { value }, Default::default()); - self.module.entry_points.push(EntryPoint { + let Context { + body, expressions, .. + } = ctx; + + ctx.module.entry_points.push(EntryPoint { name: "main".to_string(), stage: self.meta.stage, early_depth_test: Some(crate::EarlyDepthTest { conservative: None }) @@ -1492,6 +1456,8 @@ impl Frontend { ..Default::default() }, }); + + Ok(()) } } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index a1aa4622d..f8f554bf2 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -175,8 +175,6 @@ pub struct Frontend { layouter: Layouter, errors: Vec, - - module: Module, } impl Frontend { @@ -188,10 +186,6 @@ impl Frontend { self.global_variables.clear(); self.entry_args.clear(); self.layouter.clear(); - - // This is necessary because if the last parsing errored out, the module - // wouldn't have been taken - self.module = Module::default(); } /// Parses a shader either outputting a shader [`Module`](Module) or a list @@ -208,14 +202,18 @@ impl Frontend { let lexer = lex::Lexer::new(source, &options.defines); let mut ctx = ParsingContext::new(lexer); - if let Err(e) = ctx.parse(self) { - self.errors.push(e); - } - - if self.errors.is_empty() { - Ok(std::mem::take(&mut self.module)) - } else { - Err(std::mem::take(&mut self.errors)) + match ctx.parse(self) { + Ok(module) => { + if self.errors.is_empty() { + Ok(module) + } else { + Err(std::mem::take(&mut self.errors)) + } + } + Err(e) => { + self.errors.push(e); + Err(std::mem::take(&mut self.errors)) + } } } diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 7db30ea80..1a3b5a908 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -9,7 +9,7 @@ use super::{ variables::{GlobalOrConstant, VarDeclaration}, Frontend, Result, }; -use crate::{arena::Handle, proc::U32EvalError, Block, Expression, Span, Type}; +use crate::{arena::Handle, proc::U32EvalError, Expression, Module, Span, Type}; use pp_rs::token::{PreprocessorError, Token as PPToken, TokenValue as PPTokenValue}; use std::iter::Peekable; @@ -162,13 +162,14 @@ impl<'source> ParsingContext<'source> { }) } - pub fn parse(&mut self, frontend: &mut Frontend) -> Result<()> { + pub fn parse(&mut self, frontend: &mut Frontend) -> Result { + let mut module = Module::default(); + // Body and expression arena for global initialization - let mut body = Block::new(); - let mut ctx = Context::new(frontend, &mut body); + let mut ctx = Context::new(frontend, &mut module)?; while self.peek(frontend).is_some() { - self.parse_external_declaration(frontend, &mut ctx, &mut body)?; + self.parse_external_declaration(frontend, &mut ctx)?; } // Add an `EntryPoint` to `parser.module` for `main`, if a @@ -177,8 +178,8 @@ impl<'source> ParsingContext<'source> { for decl in declaration.overloads.iter() { if let FunctionKind::Call(handle) = decl.kind { if decl.defined && decl.parameters.is_empty() { - frontend.add_entry_point(handle, body, ctx.expressions); - return Ok(()); + frontend.add_entry_point(handle, ctx)?; + return Ok(module); } } } @@ -190,10 +191,14 @@ impl<'source> ParsingContext<'source> { }) } - fn parse_uint_constant(&mut self, frontend: &mut Frontend) -> Result<(u32, Span)> { - let (const_expr, meta) = self.parse_constant_expression(frontend)?; + fn parse_uint_constant( + &mut self, + frontend: &mut Frontend, + ctx: &mut Context, + ) -> Result<(u32, Span)> { + let (const_expr, meta) = self.parse_constant_expression(frontend, ctx.module)?; - let res = frontend.module.to_ctx().eval_expr_to_u32(const_expr); + let res = ctx.module.to_ctx().eval_expr_to_u32(const_expr); let int = match res { Ok(value) => Ok(value), @@ -213,16 +218,15 @@ impl<'source> ParsingContext<'source> { fn parse_constant_expression( &mut self, frontend: &mut Frontend, + module: &mut Module, ) -> Result<(Handle, Span)> { - let mut block = Block::new(); - - let mut ctx = Context::new(frontend, &mut block); + let mut ctx = Context::new(frontend, module)?; let mut stmt_ctx = ctx.stmt_ctx(); - let expr = self.parse_conditional(frontend, &mut ctx, &mut stmt_ctx, &mut block, None)?; - let (root, meta) = ctx.lower_expect(stmt_ctx, frontend, expr, ExprPos::Rhs, &mut block)?; + let expr = self.parse_conditional(frontend, &mut ctx, &mut stmt_ctx, None)?; + let (root, meta) = ctx.lower_expect(stmt_ctx, frontend, expr, ExprPos::Rhs)?; - Ok((frontend.solve_constant(&ctx, root, meta)?, meta)) + Ok((ctx.solve_constant(root, meta)?, meta)) } } @@ -387,16 +391,14 @@ impl Frontend { } } -pub struct DeclarationContext<'ctx, 'qualifiers> { +pub struct DeclarationContext<'ctx, 'qualifiers, 'a> { qualifiers: TypeQualifiers<'qualifiers>, /// Indicates a global declaration external: bool, - - ctx: &'ctx mut Context, - body: &'ctx mut Block, + ctx: &'ctx mut Context<'a>, } -impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { +impl<'ctx, 'qualifiers, 'a> DeclarationContext<'ctx, 'qualifiers, 'a> { fn add_var( &mut self, frontend: &mut Frontend, @@ -415,24 +417,14 @@ impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { match self.external { true => { - let global = frontend.add_global_var(self.ctx, self.body, decl)?; + let global = frontend.add_global_var(self.ctx, decl)?; let expr = match global { GlobalOrConstant::Global(handle) => Expression::GlobalVariable(handle), GlobalOrConstant::Constant(handle) => Expression::Constant(handle), }; - Ok(self.ctx.add_expression(expr, meta, self.body)) + Ok(self.ctx.add_expression(expr, meta)?) } - false => frontend.add_local_var(self.ctx, self.body, decl), + false => frontend.add_local_var(self.ctx, decl), } } - - /// Emits all the expressions captured by the emitter and starts the emitter again - /// - /// Alias to [`emit_restart`] with the declaration body - /// - /// [`emit_restart`]: Context::emit_restart - #[inline] - fn flush_expressions(&mut self) { - self.ctx.emit_restart(self.body); - } } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 42b2abb5c..2abd67672 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -13,8 +13,8 @@ use crate::{ Error, ErrorKind, Frontend, Span, }, proc::Alignment, - AddressSpace, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StructMember, - Type, TypeInner, + AddressSpace, Expression, FunctionResult, Handle, ScalarKind, Statement, StructMember, Type, + TypeInner, }; use super::{DeclarationContext, ParsingContext, Result}; @@ -73,10 +73,9 @@ impl<'source> ParsingContext<'source> { &mut self, frontend: &mut Frontend, global_ctx: &mut Context, - global_body: &mut Block, ) -> Result<()> { if self - .parse_declaration(frontend, global_ctx, global_body, true)? + .parse_declaration(frontend, global_ctx, true)? .is_none() { let token = self.bump(frontend)?; @@ -103,7 +102,6 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ty: Handle, ctx: &mut Context, - body: &mut Block, ) -> Result<(Handle, Span)> { // initializer: // assignment_expression @@ -118,10 +116,9 @@ impl<'source> ParsingContext<'source> { let mut components = Vec::new(); loop { // The type expected to be parsed inside the initializer list - let new_ty = - element_or_member_type(ty, components.len(), &mut frontend.module.types); + let new_ty = element_or_member_type(ty, components.len(), &mut ctx.module.types); - components.push(self.parse_initializer(frontend, new_ty, ctx, body)?.0); + components.push(self.parse_initializer(frontend, new_ty, ctx)?.0); let token = self.bump(frontend)?; match token.value { @@ -150,18 +147,17 @@ impl<'source> ParsingContext<'source> { } Ok(( - ctx.add_expression(Expression::Compose { ty, components }, meta, body), + ctx.add_expression(Expression::Compose { ty, components }, meta)?, meta, )) } else { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_assignment(frontend, ctx, &mut stmt, body)?; - let (mut init, init_meta) = - ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; + let expr = self.parse_assignment(frontend, ctx, &mut stmt)?; + let (mut init, init_meta) = ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?; - let scalar_components = scalar_components(&frontend.module.types[ty].inner); + let scalar_components = scalar_components(&ctx.module.types[ty].inner); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(frontend, &mut init, init_meta, kind, width, body)?; + ctx.implicit_conversion(&mut init, init_meta, kind, width)?; } Ok((init, init_meta)) @@ -223,19 +219,17 @@ impl<'source> ParsingContext<'source> { // parse an array specifier if it exists // NOTE: unlike other parse methods this one doesn't expect an array specifier and // returns Ok(None) rather than an error if there is not one - self.parse_array_specifier(frontend, &mut meta, &mut ty)?; + self.parse_array_specifier(frontend, ctx.ctx, &mut meta, &mut ty)?; let init = self .bump_if(frontend, TokenValue::Assign) .map::, _>(|_| { - let (mut expr, init_meta) = - self.parse_initializer(frontend, ty, ctx.ctx, ctx.body)?; + let (mut expr, init_meta) = self.parse_initializer(frontend, ty, ctx.ctx)?; - let scalar_components = scalar_components(&frontend.module.types[ty].inner); + let scalar_components = scalar_components(&ctx.ctx.module.types[ty].inner); if let Some((kind, width)) = scalar_components { - ctx.ctx.implicit_conversion( - frontend, &mut expr, init_meta, kind, width, ctx.body, - )?; + ctx.ctx + .implicit_conversion(&mut expr, init_meta, kind, width)?; } meta.subsume(init_meta); @@ -247,7 +241,7 @@ impl<'source> ParsingContext<'source> { let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; let maybe_const_expr = if ctx.external { if let Some((root, meta)) = init { - match frontend.solve_constant(ctx.ctx, root, meta) { + match ctx.ctx.solve_constant(root, meta) { Ok(res) => Some(res), // If the declaration is external (global scope) and is constant qualified // then the initializer must be a constant expression @@ -264,8 +258,8 @@ impl<'source> ParsingContext<'source> { let pointer = ctx.add_var(frontend, ty, name, maybe_const_expr, meta)?; if let Some((value, _)) = init.filter(|_| maybe_const_expr.is_none()) { - ctx.flush_expressions(); - ctx.body.push(Statement::Store { pointer, value }, meta); + ctx.ctx.emit_restart(); + ctx.ctx.body.push(Statement::Store { pointer, value }, meta); } let token = self.bump(frontend)?; @@ -292,7 +286,6 @@ impl<'source> ParsingContext<'source> { &mut self, frontend: &mut Frontend, ctx: &mut Context, - body: &mut Block, external: bool, ) -> Result> { //declaration: @@ -308,12 +301,12 @@ impl<'source> ParsingContext<'source> { // type_qualifier IDENTIFIER identifier_list SEMICOLON if self.peek_type_qualifier(frontend) || self.peek_type_name(frontend) { - let mut qualifiers = self.parse_type_qualifiers(frontend)?; + let mut qualifiers = self.parse_type_qualifiers(frontend, ctx)?; if self.peek_type_name(frontend) { // This branch handles variables and function prototypes and if // external is true also function definitions - let (ty, mut meta) = self.parse_type(frontend)?; + let (ty, mut meta) = self.parse_type(frontend, ctx)?; let token = self.bump(frontend)?; let token_fallthrough = match token.value { @@ -323,11 +316,10 @@ impl<'source> ParsingContext<'source> { self.bump(frontend)?; let result = ty.map(|ty| FunctionResult { ty, binding: None }); - let mut body = Block::new(); - let mut context = Context::new(frontend, &mut body); + let mut context = Context::new(frontend, ctx.module)?; - self.parse_function_args(frontend, &mut context, &mut body)?; + self.parse_function_args(frontend, &mut context)?; let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta; meta.subsume(end_meta); @@ -350,11 +342,10 @@ impl<'source> ParsingContext<'source> { token.meta, frontend, &mut context, - &mut body, &mut None, )?; - frontend.add_function(context, name, result, body, meta); + frontend.add_function(context, name, result, meta); Ok(Some(meta)) } @@ -395,7 +386,6 @@ impl<'source> ParsingContext<'source> { qualifiers, external, ctx, - body, }; self.backtrack(token_fallthrough)?; @@ -420,7 +410,6 @@ impl<'source> ParsingContext<'source> { self.parse_block_declaration( frontend, ctx, - body, &mut qualifiers, ty_name, token.meta, @@ -428,7 +417,7 @@ impl<'source> ParsingContext<'source> { .map(Some) } else { if qualifiers.invariant.take().is_some() { - frontend.make_variable_invariant(ctx, body, &ty_name, token.meta); + frontend.make_variable_invariant(ctx, &ty_name, token.meta)?; qualifiers.unused_errors(&mut frontend.errors); self.expect(frontend, TokenValue::Semicolon)?; @@ -501,9 +490,9 @@ impl<'source> ParsingContext<'source> { } }; - let (ty, meta) = self.parse_type_non_void(frontend)?; + let (ty, meta) = self.parse_type_non_void(frontend, ctx)?; - match frontend.module.types[ty].inner { + match ctx.module.types[ty].inner { TypeInner::Scalar { kind: ScalarKind::Float | ScalarKind::Sint, .. @@ -529,7 +518,6 @@ impl<'source> ParsingContext<'source> { &mut self, frontend: &mut Frontend, ctx: &mut Context, - body: &mut Block, qualifiers: &mut TypeQualifiers, ty_name: String, mut meta: Span, @@ -549,10 +537,10 @@ impl<'source> ParsingContext<'source> { }; let mut members = Vec::new(); - let span = self.parse_struct_declaration_list(frontend, &mut members, layout)?; + let span = self.parse_struct_declaration_list(frontend, ctx, &mut members, layout)?; self.expect(frontend, TokenValue::RightBrace)?; - let mut ty = frontend.module.types.insert( + let mut ty = ctx.module.types.insert( Type { name: Some(ty_name), inner: TypeInner::Struct { @@ -567,7 +555,7 @@ impl<'source> ParsingContext<'source> { let name = match token.value { TokenValue::Semicolon => None, TokenValue::Identifier(name) => { - self.parse_array_specifier(frontend, &mut meta, &mut ty)?; + self.parse_array_specifier(frontend, ctx, &mut meta, &mut ty)?; self.expect(frontend, TokenValue::Semicolon)?; @@ -586,7 +574,6 @@ impl<'source> ParsingContext<'source> { let global = frontend.add_global_var( ctx, - body, VarDeclaration { qualifiers, ty, @@ -608,7 +595,7 @@ impl<'source> ParsingContext<'source> { entry_arg: None, mutable: true, }; - ctx.add_global(frontend, &k, lookup, body); + ctx.add_global(&k, lookup)?; frontend.global_variables.push((k, lookup)); } @@ -620,6 +607,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_struct_declaration_list( &mut self, frontend: &mut Frontend, + ctx: &mut Context, members: &mut Vec, layout: StructLayout, ) -> Result { @@ -629,12 +617,12 @@ impl<'source> ParsingContext<'source> { loop { // TODO: type_qualifier - let (base_ty, mut meta) = self.parse_type_non_void(frontend)?; + let (base_ty, mut meta) = self.parse_type_non_void(frontend, ctx)?; loop { let (name, name_meta) = self.expect_ident(frontend)?; let mut ty = base_ty; - self.parse_array_specifier(frontend, &mut meta, &mut ty)?; + self.parse_array_specifier(frontend, ctx, &mut meta, &mut ty)?; meta.subsume(name_meta); @@ -642,7 +630,7 @@ impl<'source> ParsingContext<'source> { ty, meta, layout, - &mut frontend.module.types, + &mut ctx.module.types, &mut frontend.errors, ); diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 7e47b2eea..32e0959c2 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -9,7 +9,7 @@ use crate::{ token::{Token, TokenValue}, Error, Frontend, Result, Span, }, - ArraySize, BinaryOperator, Block, Handle, Literal, Type, TypeInner, UnaryOperator, + ArraySize, BinaryOperator, Handle, Literal, Type, TypeInner, UnaryOperator, }; impl<'source> ParsingContext<'source> { @@ -18,7 +18,6 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, - body: &mut Block, ) -> Result> { let mut token = self.bump(frontend)?; @@ -47,7 +46,7 @@ impl<'source> ParsingContext<'source> { } TokenValue::BoolConstant(value) => Literal::Bool(value), TokenValue::LeftParen => { - let expr = self.parse_expression(frontend, ctx, stmt, body)?; + let expr = self.parse_expression(frontend, ctx, stmt)?; let meta = self.expect(frontend, TokenValue::RightParen)?.meta; token.meta.subsume(meta); @@ -84,7 +83,6 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, - body: &mut Block, meta: &mut Span, ) -> Result>> { let mut args = Vec::new(); @@ -92,7 +90,7 @@ impl<'source> ParsingContext<'source> { meta.subsume(token.meta); } else { loop { - args.push(self.parse_assignment(frontend, ctx, stmt, body)?); + args.push(self.parse_assignment(frontend, ctx, stmt)?); let token = self.bump(frontend)?; match token.value { @@ -122,21 +120,20 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, - body: &mut Block, ) -> Result> { let mut base = if self.peek_type_name(frontend) { - let (mut handle, mut meta) = self.parse_type_non_void(frontend)?; + let (mut handle, mut meta) = self.parse_type_non_void(frontend, ctx)?; self.expect(frontend, TokenValue::LeftParen)?; - let args = self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?; + let args = self.parse_function_call_args(frontend, ctx, stmt, &mut meta)?; if let TypeInner::Array { size: ArraySize::Dynamic, stride, base, - } = frontend.module.types[handle].inner + } = ctx.module.types[handle].inner { - let span = frontend.module.types.get_span(handle); + let span = ctx.module.types.get_span(handle); let size = u32::try_from(args.len()) .ok() @@ -148,7 +145,7 @@ impl<'source> ParsingContext<'source> { meta, })?; - handle = frontend.module.types.insert( + handle = ctx.module.types.insert( Type { name: None, inner: TypeInner::Array { @@ -175,7 +172,7 @@ impl<'source> ParsingContext<'source> { let (name, mut meta) = self.expect_ident(frontend)?; let expr = if self.bump_if(frontend, TokenValue::LeftParen).is_some() { - let args = self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?; + let args = self.parse_function_call_args(frontend, ctx, stmt, &mut meta)?; let kind = match frontend.lookup_type.get(&name) { Some(ty) => FunctionCallKind::TypeConstructor(*ty), @@ -187,7 +184,7 @@ impl<'source> ParsingContext<'source> { meta, } } else { - let var = match frontend.lookup_variable(ctx, body, &name, meta) { + let var = match frontend.lookup_variable(ctx, &name, meta)? { Some(var) => var, None => { return Err(Error { @@ -205,7 +202,7 @@ impl<'source> ParsingContext<'source> { stmt.hir_exprs.append(expr, Default::default()) } else { - self.parse_primary(frontend, ctx, stmt, body)? + self.parse_primary(frontend, ctx, stmt)? }; while let TokenValue::LeftBracket @@ -217,7 +214,7 @@ impl<'source> ParsingContext<'source> { match value { TokenValue::LeftBracket => { - let index = self.parse_expression(frontend, ctx, stmt, body)?; + let index = self.parse_expression(frontend, ctx, stmt)?; let end_meta = self.expect(frontend, TokenValue::RightBracket)?.meta; meta.subsume(end_meta); @@ -233,8 +230,7 @@ impl<'source> ParsingContext<'source> { let (field, end_meta) = self.expect_ident(frontend)?; if self.bump_if(frontend, TokenValue::LeftParen).is_some() { - let args = - self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?; + let args = self.parse_function_call_args(frontend, ctx, stmt, &mut meta)?; base = stmt.hir_exprs.append( HirExpr { @@ -287,13 +283,12 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, - body: &mut Block, ) -> Result> { Ok(match self.expect_peek(frontend)?.value { TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { let Token { value, mut meta } = self.bump(frontend)?; - let expr = self.parse_unary(frontend, ctx, stmt, body)?; + let expr = self.parse_unary(frontend, ctx, stmt)?; let end_meta = stmt.hir_exprs[expr].meta; let kind = match value { @@ -315,7 +310,7 @@ impl<'source> ParsingContext<'source> { TokenValue::Increment | TokenValue::Decrement => { let Token { value, meta } = self.bump(frontend)?; - let expr = self.parse_unary(frontend, ctx, stmt, body)?; + let expr = self.parse_unary(frontend, ctx, stmt)?; stmt.hir_exprs.append( HirExpr { @@ -332,7 +327,7 @@ impl<'source> ParsingContext<'source> { Default::default(), ) } - _ => self.parse_postfix(frontend, ctx, stmt, body)?, + _ => self.parse_postfix(frontend, ctx, stmt)?, }) } @@ -341,13 +336,12 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, - body: &mut Block, passthrough: Option>, min_bp: u8, ) -> Result> { let mut left = passthrough .ok_or(ErrorKind::EndOfFile /* Dummy error */) - .or_else(|_| self.parse_unary(frontend, ctx, stmt, body))?; + .or_else(|_| self.parse_unary(frontend, ctx, stmt))?; let mut meta = stmt.hir_exprs[left].meta; while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(frontend)?.value) { @@ -357,7 +351,7 @@ impl<'source> ParsingContext<'source> { let Token { value, .. } = self.bump(frontend)?; - let right = self.parse_binary(frontend, ctx, stmt, body, None, r_bp)?; + let right = self.parse_binary(frontend, ctx, stmt, None, r_bp)?; let end_meta = stmt.hir_exprs[right].meta; meta.subsume(end_meta); @@ -403,16 +397,15 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, - body: &mut Block, passthrough: Option>, ) -> Result> { - let mut condition = self.parse_binary(frontend, ctx, stmt, body, passthrough, 0)?; + let mut condition = self.parse_binary(frontend, ctx, stmt, passthrough, 0)?; let mut meta = stmt.hir_exprs[condition].meta; if self.bump_if(frontend, TokenValue::Question).is_some() { - let accept = self.parse_expression(frontend, ctx, stmt, body)?; + let accept = self.parse_expression(frontend, ctx, stmt)?; self.expect(frontend, TokenValue::Colon)?; - let reject = self.parse_assignment(frontend, ctx, stmt, body)?; + let reject = self.parse_assignment(frontend, ctx, stmt)?; let end_meta = stmt.hir_exprs[reject].meta; meta.subsume(end_meta); @@ -437,15 +430,14 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, - body: &mut Block, ) -> Result> { - let tgt = self.parse_unary(frontend, ctx, stmt, body)?; + let tgt = self.parse_unary(frontend, ctx, stmt)?; let mut meta = stmt.hir_exprs[tgt].meta; Ok(match self.expect_peek(frontend)?.value { TokenValue::Assign => { self.bump(frontend)?; - let value = self.parse_assignment(frontend, ctx, stmt, body)?; + let value = self.parse_assignment(frontend, ctx, stmt)?; let end_meta = stmt.hir_exprs[value].meta; meta.subsume(end_meta); @@ -468,7 +460,7 @@ impl<'source> ParsingContext<'source> { | TokenValue::RightShiftAssign | TokenValue::XorAssign => { let token = self.bump(frontend)?; - let right = self.parse_assignment(frontend, ctx, stmt, body)?; + let right = self.parse_assignment(frontend, ctx, stmt)?; let end_meta = stmt.hir_exprs[right].meta; meta.subsume(end_meta); @@ -504,7 +496,7 @@ impl<'source> ParsingContext<'source> { Default::default(), ) } - _ => self.parse_conditional(frontend, ctx, stmt, body, Some(tgt))?, + _ => self.parse_conditional(frontend, ctx, stmt, Some(tgt))?, }) } @@ -513,13 +505,12 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, - body: &mut Block, ) -> Result> { - let mut expr = self.parse_assignment(frontend, ctx, stmt, body)?; + let mut expr = self.parse_assignment(frontend, ctx, stmt)?; while let TokenValue::Comma = self.expect_peek(frontend)?.value { self.bump(frontend)?; - expr = self.parse_assignment(frontend, ctx, stmt, body)?; + expr = self.parse_assignment(frontend, ctx, stmt)?; } Ok(expr) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index c05d060ea..358bc52e7 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -40,12 +40,11 @@ impl<'source> ParsingContext<'source> { &mut self, frontend: &mut Frontend, ctx: &mut Context, - body: &mut Block, terminator: &mut Option, ) -> Result> { // Type qualifiers always identify a declaration statement if self.peek_type_qualifier(frontend) { - return self.parse_declaration(frontend, ctx, body, false); + return self.parse_declaration(frontend, ctx, false); } // Type names can identify either declaration statements or type constructors @@ -61,7 +60,7 @@ impl<'source> ParsingContext<'source> { self.backtrack(token)?; if declaration { - return self.parse_declaration(frontend, ctx, body, false); + return self.parse_declaration(frontend, ctx, false); } } @@ -79,14 +78,14 @@ impl<'source> ParsingContext<'source> { let meta_rest = match *value { TokenValue::Continue => { let meta = self.bump(frontend)?.meta; - body.push(Statement::Continue, meta); - terminator.get_or_insert(body.len()); + ctx.body.push(Statement::Continue, meta); + terminator.get_or_insert(ctx.body.len()); self.expect(frontend, TokenValue::Semicolon)?.meta } TokenValue::Break => { let meta = self.bump(frontend)?.meta; - body.push(Statement::Break, meta); - terminator.get_or_insert(body.len()); + ctx.body.push(Statement::Break, meta); + terminator.get_or_insert(ctx.body.len()); self.expect(frontend, TokenValue::Semicolon)?.meta } TokenValue::Return => { @@ -96,25 +95,25 @@ impl<'source> ParsingContext<'source> { _ => { // TODO: Implicit conversions let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt)?; self.expect(frontend, TokenValue::Semicolon)?; let (handle, meta) = - ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?; (Some(handle), meta) } }; - ctx.emit_restart(body); + ctx.emit_restart(); - body.push(Statement::Return { value }, meta); - terminator.get_or_insert(body.len()); + ctx.body.push(Statement::Return { value }, meta); + terminator.get_or_insert(ctx.body.len()); meta } TokenValue::Discard => { let meta = self.bump(frontend)?.meta; - body.push(Statement::Kill, meta); - terminator.get_or_insert(body.len()); + ctx.body.push(Statement::Kill, meta); + terminator.get_or_insert(ctx.body.len()); self.expect(frontend, TokenValue::Semicolon)?.meta } @@ -124,33 +123,31 @@ impl<'source> ParsingContext<'source> { self.expect(frontend, TokenValue::LeftParen)?; let condition = { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt)?; let (handle, more_meta) = - ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?; meta.subsume(more_meta); handle }; self.expect(frontend, TokenValue::RightParen)?; - ctx.emit_restart(body); - - let mut accept = Block::new(); - if let Some(more_meta) = - self.parse_statement(frontend, ctx, &mut accept, &mut None)? - { - meta.subsume(more_meta) - } - - let mut reject = Block::new(); - if self.bump_if(frontend, TokenValue::Else).is_some() { - if let Some(more_meta) = - self.parse_statement(frontend, ctx, &mut reject, &mut None)? - { + let accept = ctx.new_body(|ctx| { + if let Some(more_meta) = self.parse_statement(frontend, ctx, &mut None)? { meta.subsume(more_meta); } - } + Ok(()) + })?; - body.push( + let reject = ctx.new_body(|ctx| { + if self.bump_if(frontend, TokenValue::Else).is_some() { + if let Some(more_meta) = self.parse_statement(frontend, ctx, &mut None)? { + meta.subsume(more_meta); + } + } + Ok(()) + })?; + + ctx.body.push( Statement::If { condition, accept, @@ -169,17 +166,16 @@ impl<'source> ParsingContext<'source> { let (selector, uint) = { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; - let (root, meta) = - ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; - let uint = frontend.resolve_type(ctx, root, meta)?.scalar_kind() + let expr = self.parse_expression(frontend, ctx, &mut stmt)?; + let (root, meta) = ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?; + let uint = ctx.resolve_type(root, meta)?.scalar_kind() == Some(crate::ScalarKind::Uint); (root, uint) }; self.expect(frontend, TokenValue::RightParen)?; - ctx.emit_restart(body); + ctx.emit_restart(); let mut cases = Vec::new(); // Track if any default case is present in the switch statement. @@ -192,12 +188,12 @@ impl<'source> ParsingContext<'source> { self.bump(frontend)?; let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt)?; let (root, meta) = - ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; - let const_expr = frontend.solve_constant(ctx, root, meta)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?; + let const_expr = ctx.solve_constant(root, meta)?; - match frontend.module.const_expressions[const_expr] { + match ctx.module.const_expressions[const_expr] { Expression::Literal(Literal::I32(value)) => match uint { true => crate::SwitchValue::U32(value as u32), false => crate::SwitchValue::I32(value), @@ -244,35 +240,32 @@ impl<'source> ParsingContext<'source> { self.expect(frontend, TokenValue::Colon)?; - let mut body = Block::new(); - - let mut case_terminator = None; - loop { - match self.expect_peek(frontend)?.value { - TokenValue::Case | TokenValue::Default | TokenValue::RightBrace => { - break - } - _ => { - self.parse_statement( - frontend, - ctx, - &mut body, - &mut case_terminator, - )?; - } - } - } - let mut fall_through = true; - if let Some(mut idx) = case_terminator { - if let Statement::Break = body[idx - 1] { - fall_through = false; - idx -= 1; + let body = ctx.new_body(|ctx| { + let mut case_terminator = None; + loop { + match self.expect_peek(frontend)?.value { + TokenValue::Case | TokenValue::Default | TokenValue::RightBrace => { + break + } + _ => { + self.parse_statement(frontend, ctx, &mut case_terminator)?; + } + } } - body.cull(idx..) - } + if let Some(mut idx) = case_terminator { + if let Statement::Break = ctx.body[idx - 1] { + fall_through = false; + idx -= 1; + } + + ctx.body.cull(idx..) + } + + Ok(()) + })?; cases.push(SwitchCase { value, @@ -317,51 +310,48 @@ impl<'source> ParsingContext<'source> { }) } - body.push(Statement::Switch { selector, cases }, meta); + ctx.body.push(Statement::Switch { selector, cases }, meta); meta } TokenValue::While => { let mut meta = self.bump(frontend)?.meta; - let mut loop_body = Block::new(); + let loop_body = ctx.new_body(|ctx| { + let mut stmt = ctx.stmt_ctx(); + self.expect(frontend, TokenValue::LeftParen)?; + let root = self.parse_expression(frontend, ctx, &mut stmt)?; + meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta); - let mut stmt = ctx.stmt_ctx(); - self.expect(frontend, TokenValue::LeftParen)?; - let root = self.parse_expression(frontend, ctx, &mut stmt, &mut loop_body)?; - meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta); + let (expr, expr_meta) = ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs)?; + let condition = ctx.add_expression( + Expression::Unary { + op: UnaryOperator::Not, + expr, + }, + expr_meta, + )?; - let (expr, expr_meta) = - ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut loop_body)?; - let condition = ctx.add_expression( - Expression::Unary { - op: UnaryOperator::Not, - expr, - }, - expr_meta, - &mut loop_body, - ); + ctx.emit_restart(); - ctx.emit_restart(&mut loop_body); + ctx.body.push( + Statement::If { + condition, + accept: new_break(), + reject: Block::new(), + }, + crate::Span::default(), + ); - loop_body.push( - Statement::If { - condition, - accept: new_break(), - reject: Block::new(), - }, - crate::Span::default(), - ); + meta.subsume(expr_meta); - meta.subsume(expr_meta); + if let Some(body_meta) = self.parse_statement(frontend, ctx, &mut None)? { + meta.subsume(body_meta); + } + Ok(()) + })?; - if let Some(body_meta) = - self.parse_statement(frontend, ctx, &mut loop_body, &mut None)? - { - meta.subsume(body_meta); - } - - body.push( + ctx.body.push( Statement::Loop { body: loop_body, continuing: Block::new(), @@ -375,47 +365,46 @@ impl<'source> ParsingContext<'source> { TokenValue::Do => { let mut meta = self.bump(frontend)?.meta; - let mut loop_body = Block::new(); + let loop_body = ctx.new_body(|ctx| { + let mut terminator = None; + self.parse_statement(frontend, ctx, &mut terminator)?; - let mut terminator = None; - self.parse_statement(frontend, ctx, &mut loop_body, &mut terminator)?; + let mut stmt = ctx.stmt_ctx(); - let mut stmt = ctx.stmt_ctx(); + self.expect(frontend, TokenValue::While)?; + self.expect(frontend, TokenValue::LeftParen)?; + let root = self.parse_expression(frontend, ctx, &mut stmt)?; + let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta; - self.expect(frontend, TokenValue::While)?; - self.expect(frontend, TokenValue::LeftParen)?; - let root = self.parse_expression(frontend, ctx, &mut stmt, &mut loop_body)?; - let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta; + meta.subsume(end_meta); - meta.subsume(end_meta); + let (expr, expr_meta) = ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs)?; + let condition = ctx.add_expression( + Expression::Unary { + op: UnaryOperator::Not, + expr, + }, + expr_meta, + )?; - let (expr, expr_meta) = - ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut loop_body)?; - let condition = ctx.add_expression( - Expression::Unary { - op: UnaryOperator::Not, - expr, - }, - expr_meta, - &mut loop_body, - ); + ctx.emit_restart(); - ctx.emit_restart(&mut loop_body); + ctx.body.push( + Statement::If { + condition, + accept: new_break(), + reject: Block::new(), + }, + crate::Span::default(), + ); - loop_body.push( - Statement::If { - condition, - accept: new_break(), - reject: Block::new(), - }, - crate::Span::default(), - ); + if let Some(idx) = terminator { + ctx.body.cull(idx..) + } + Ok(()) + })?; - if let Some(idx) = terminator { - loop_body.cull(idx..) - } - - body.push( + ctx.body.push( Statement::Loop { body: loop_body, continuing: Block::new(), @@ -434,96 +423,98 @@ impl<'source> ParsingContext<'source> { if self.bump_if(frontend, TokenValue::Semicolon).is_none() { if self.peek_type_name(frontend) || self.peek_type_qualifier(frontend) { - self.parse_declaration(frontend, ctx, body, false)?; + self.parse_declaration(frontend, ctx, false)?; } else { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; - ctx.lower(stmt, frontend, expr, ExprPos::Rhs, body)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt)?; + ctx.lower(stmt, frontend, expr, ExprPos::Rhs)?; self.expect(frontend, TokenValue::Semicolon)?; } } - let (mut block, mut continuing) = (Block::new(), Block::new()); + let loop_body = ctx.new_body(|ctx| { + if self.bump_if(frontend, TokenValue::Semicolon).is_none() { + let (expr, expr_meta) = if self.peek_type_name(frontend) + || self.peek_type_qualifier(frontend) + { + let mut qualifiers = self.parse_type_qualifiers(frontend, ctx)?; + let (ty, mut meta) = self.parse_type_non_void(frontend, ctx)?; + let name = self.expect_ident(frontend)?.0; - if self.bump_if(frontend, TokenValue::Semicolon).is_none() { - let (expr, expr_meta) = if self.peek_type_name(frontend) - || self.peek_type_qualifier(frontend) - { - let mut qualifiers = self.parse_type_qualifiers(frontend)?; - let (ty, mut meta) = self.parse_type_non_void(frontend)?; - let name = self.expect_ident(frontend)?.0; + self.expect(frontend, TokenValue::Assign)?; - self.expect(frontend, TokenValue::Assign)?; + let (value, end_meta) = self.parse_initializer(frontend, ty, ctx)?; + meta.subsume(end_meta); - let (value, end_meta) = - self.parse_initializer(frontend, ty, ctx, &mut block)?; - meta.subsume(end_meta); + let decl = VarDeclaration { + qualifiers: &mut qualifiers, + ty, + name: Some(name), + init: None, + meta, + }; - let decl = VarDeclaration { - qualifiers: &mut qualifiers, - ty, - name: Some(name), - init: None, - meta, + let pointer = frontend.add_local_var(ctx, decl)?; + + ctx.emit_restart(); + + ctx.body.push(Statement::Store { pointer, value }, meta); + + (value, end_meta) + } else { + let mut stmt = ctx.stmt_ctx(); + let root = self.parse_expression(frontend, ctx, &mut stmt)?; + ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs)? }; - let pointer = frontend.add_local_var(ctx, &mut block, decl)?; + let condition = ctx.add_expression( + Expression::Unary { + op: UnaryOperator::Not, + expr, + }, + expr_meta, + )?; - ctx.emit_restart(&mut block); + ctx.emit_restart(); - block.push(Statement::Store { pointer, value }, meta); + ctx.body.push( + Statement::If { + condition, + accept: new_break(), + reject: Block::new(), + }, + crate::Span::default(), + ); - (value, end_meta) - } else { - let mut stmt = ctx.stmt_ctx(); - let root = self.parse_expression(frontend, ctx, &mut stmt, &mut block)?; - ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut block)? - }; - - let condition = ctx.add_expression( - Expression::Unary { - op: UnaryOperator::Not, - expr, - }, - expr_meta, - &mut block, - ); - - ctx.emit_restart(&mut block); - - block.push( - Statement::If { - condition, - accept: new_break(), - reject: Block::new(), - }, - crate::Span::default(), - ); - - self.expect(frontend, TokenValue::Semicolon)?; - } - - match self.expect_peek(frontend)?.value { - TokenValue::RightParen => {} - _ => { - let mut stmt = ctx.stmt_ctx(); - let rest = - self.parse_expression(frontend, ctx, &mut stmt, &mut continuing)?; - ctx.lower(stmt, frontend, rest, ExprPos::Rhs, &mut continuing)?; + self.expect(frontend, TokenValue::Semicolon)?; } - } + Ok(()) + })?; + + let continuing = ctx.new_body(|ctx| { + match self.expect_peek(frontend)?.value { + TokenValue::RightParen => {} + _ => { + let mut stmt = ctx.stmt_ctx(); + let rest = self.parse_expression(frontend, ctx, &mut stmt)?; + ctx.lower(stmt, frontend, rest, ExprPos::Rhs)?; + } + } + Ok(()) + })?; meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta); - if let Some(stmt_meta) = - self.parse_statement(frontend, ctx, &mut block, &mut None)? - { - meta.subsume(stmt_meta); - } + let loop_body = ctx.with_body(loop_body, |ctx| { + if let Some(stmt_meta) = self.parse_statement(frontend, ctx, &mut None)? { + meta.subsume(stmt_meta); + } + Ok(()) + })?; - body.push( + ctx.body.push( Statement::Loop { - body: block, + body: loop_body, continuing, break_if: None, }, @@ -535,22 +526,20 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::LeftBrace => { - let meta = self.bump(frontend)?.meta; - - let mut block = Block::new(); + let mut meta = self.bump(frontend)?.meta; let mut block_terminator = None; - let meta = self.parse_compound_statement( - meta, - frontend, - ctx, - &mut block, - &mut block_terminator, - )?; - body.push(Statement::Block(block), meta); + let block = ctx.new_body(|ctx| { + let block_meta = + self.parse_compound_statement(meta, frontend, ctx, &mut block_terminator)?; + meta.subsume(block_meta); + Ok(()) + })?; + + ctx.body.push(Statement::Block(block), meta); if block_terminator.is_some() { - terminator.get_or_insert(body.len()); + terminator.get_or_insert(ctx.body.len()); } meta @@ -561,8 +550,8 @@ impl<'source> ParsingContext<'source> { // tokens. Unknown or invalid tokens will be caught there and // turned into an error. let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; - ctx.lower(stmt, frontend, expr, ExprPos::Rhs, body)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt)?; + ctx.lower(stmt, frontend, expr, ExprPos::Rhs)?; self.expect(frontend, TokenValue::Semicolon)?.meta } }; @@ -576,7 +565,6 @@ impl<'source> ParsingContext<'source> { mut meta: Span, frontend: &mut Frontend, ctx: &mut Context, - body: &mut Block, terminator: &mut Option, ) -> Result { ctx.symbol_table.push_scope(); @@ -590,7 +578,7 @@ impl<'source> ParsingContext<'source> { break; } - let stmt = self.parse_statement(frontend, ctx, body, terminator)?; + let stmt = self.parse_statement(frontend, ctx, terminator)?; if let Some(stmt_meta) = stmt { meta.subsume(stmt_meta); @@ -598,7 +586,7 @@ impl<'source> ParsingContext<'source> { } if let Some(idx) = *terminator { - body.cull(idx..) + ctx.body.cull(idx..) } ctx.symbol_table.pop_scope(); @@ -609,8 +597,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_function_args( &mut self, frontend: &mut Frontend, - context: &mut Context, - body: &mut Block, + ctx: &mut Context, ) -> Result<()> { if self.bump_if(frontend, TokenValue::Void).is_some() { return Ok(()); @@ -619,19 +606,19 @@ impl<'source> ParsingContext<'source> { loop { if self.peek_type_name(frontend) || self.peek_parameter_qualifier(frontend) { let qualifier = self.parse_parameter_qualifier(frontend); - let mut ty = self.parse_type_non_void(frontend)?.0; + let mut ty = self.parse_type_non_void(frontend, ctx)?.0; match self.expect_peek(frontend)?.value { TokenValue::Comma => { self.bump(frontend)?; - context.add_function_arg(frontend, body, None, ty, qualifier); + ctx.add_function_arg(None, ty, qualifier)?; continue; } TokenValue::Identifier(_) => { let mut name = self.expect_ident(frontend)?; - self.parse_array_specifier(frontend, &mut name.1, &mut ty)?; + self.parse_array_specifier(frontend, ctx, &mut name.1, &mut ty)?; - context.add_function_arg(frontend, body, Some(name), ty, qualifier); + ctx.add_function_arg(Some(name), ty, qualifier)?; if self.bump_if(frontend, TokenValue::Comma).is_some() { continue; diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 4761e8bc5..d2d24b5da 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -3,6 +3,7 @@ use std::num::NonZeroU32; use crate::{ front::glsl::{ ast::{QualifierKey, QualifierValue, StorageQualifier, StructLayout, TypeQualifiers}, + context::Context, error::ExpectedToken, parser::ParsingContext, token::{Token, TokenValue}, @@ -17,10 +18,11 @@ impl<'source> ParsingContext<'source> { pub fn parse_array_specifier( &mut self, frontend: &mut Frontend, + ctx: &mut Context, span: &mut Span, ty: &mut Handle, ) -> Result<()> { - while self.parse_array_specifier_single(frontend, span, ty)? {} + while self.parse_array_specifier_single(frontend, ctx, span, ty)? {} Ok(()) } @@ -28,6 +30,7 @@ impl<'source> ParsingContext<'source> { fn parse_array_specifier_single( &mut self, frontend: &mut Frontend, + ctx: &mut Context, span: &mut Span, ty: &mut Handle, ) -> Result { @@ -38,7 +41,7 @@ impl<'source> ParsingContext<'source> { span.subsume(meta); ArraySize::Dynamic } else { - let (value, constant_span) = self.parse_uint_constant(frontend)?; + let (value, constant_span) = self.parse_uint_constant(frontend, ctx)?; let size = NonZeroU32::new(value).ok_or(Error { kind: ErrorKind::SemanticError("Array size must be greater than zero".into()), meta: constant_span, @@ -48,9 +51,9 @@ impl<'source> ParsingContext<'source> { ArraySize::Constant(size) }; - frontend.layouter.update(frontend.module.to_ctx()).unwrap(); + frontend.layouter.update(ctx.module.to_ctx()).unwrap(); let stride = frontend.layouter[*ty].to_stride(); - *ty = frontend.module.types.insert( + *ty = ctx.module.types.insert( Type { name: None, inner: TypeInner::Array { @@ -68,11 +71,15 @@ impl<'source> ParsingContext<'source> { } } - pub fn parse_type(&mut self, frontend: &mut Frontend) -> Result<(Option>, Span)> { + pub fn parse_type( + &mut self, + frontend: &mut Frontend, + ctx: &mut Context, + ) -> Result<(Option>, Span)> { let token = self.bump(frontend)?; let mut handle = match token.value { TokenValue::Void => return Ok((None, token.meta)), - TokenValue::TypeName(ty) => frontend.module.types.insert(ty, token.meta), + TokenValue::TypeName(ty) => ctx.module.types.insert(ty, token.meta), TokenValue::Struct => { let mut meta = token.meta; let ty_name = self.expect_ident(frontend)?.0; @@ -80,12 +87,13 @@ impl<'source> ParsingContext<'source> { let mut members = Vec::new(); let span = self.parse_struct_declaration_list( frontend, + ctx, &mut members, StructLayout::Std140, )?; let end_meta = self.expect(frontend, TokenValue::RightBrace)?.meta; meta.subsume(end_meta); - let ty = frontend.module.types.insert( + let ty = ctx.module.types.insert( Type { name: Some(ty_name.clone()), inner: TypeInner::Struct { members, span }, @@ -120,12 +128,16 @@ impl<'source> ParsingContext<'source> { }; let mut span = token.meta; - self.parse_array_specifier(frontend, &mut span, &mut handle)?; + self.parse_array_specifier(frontend, ctx, &mut span, &mut handle)?; Ok((Some(handle), span)) } - pub fn parse_type_non_void(&mut self, frontend: &mut Frontend) -> Result<(Handle, Span)> { - let (maybe_ty, meta) = self.parse_type(frontend)?; + pub fn parse_type_non_void( + &mut self, + frontend: &mut Frontend, + ctx: &mut Context, + ) -> Result<(Handle, Span)> { + let (maybe_ty, meta) = self.parse_type(frontend, ctx)?; let ty = maybe_ty.ok_or_else(|| Error { kind: ErrorKind::SemanticError("Type can't be void".into()), meta, @@ -156,6 +168,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_type_qualifiers<'a>( &mut self, frontend: &mut Frontend, + ctx: &mut Context, ) -> Result> { let mut qualifiers = TypeQualifiers::default(); @@ -164,7 +177,7 @@ impl<'source> ParsingContext<'source> { // Handle layout qualifiers outside the match since this can push multiple values if token.value == TokenValue::Layout { - self.parse_layout_qualifier_id_list(frontend, &mut qualifiers)?; + self.parse_layout_qualifier_id_list(frontend, ctx, &mut qualifiers)?; continue; } @@ -287,11 +300,12 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id_list( &mut self, frontend: &mut Frontend, + ctx: &mut Context, qualifiers: &mut TypeQualifiers, ) -> Result<()> { self.expect(frontend, TokenValue::LeftParen)?; loop { - self.parse_layout_qualifier_id(frontend, &mut qualifiers.layout_qualifiers)?; + self.parse_layout_qualifier_id(frontend, ctx, &mut qualifiers.layout_qualifiers)?; if self.bump_if(frontend, TokenValue::Comma).is_some() { continue; @@ -308,6 +322,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id( &mut self, frontend: &mut Frontend, + ctx: &mut Context, qualifiers: &mut crate::FastHashMap, ) -> Result<()> { // layout_qualifier_id: @@ -332,13 +347,14 @@ impl<'source> ParsingContext<'source> { } else { let key = QualifierKey::String(name.into()); let value = if self.bump_if(frontend, TokenValue::Assign).is_some() { - let (value, end_meta) = match self.parse_uint_constant(frontend) { - Ok(v) => v, - Err(e) => { - frontend.errors.push(e); - (0, Span::default()) - } - }; + let (value, end_meta) = + match self.parse_uint_constant(frontend, ctx) { + Ok(v) => v, + Err(e) => { + frontend.errors.push(e); + (0, Span::default()) + } + }; token.meta.subsume(end_meta); QualifierValue::Uint(value) diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 513bc2275..a91a0a9f2 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,6 +1,4 @@ -use super::{ - constants::ConstantSolver, context::Context, Error, ErrorKind, Frontend, Result, Span, -}; +use super::{constants::ConstantSolver, context::Context, Error, ErrorKind, Result, Span}; use crate::{ proc::ResolveContext, Bytes, Expression, Handle, ImageClass, ImageDimension, ScalarKind, Type, TypeInner, VectorSize, @@ -226,7 +224,7 @@ pub const fn type_power(kind: ScalarKind, width: Bytes) -> Option { }) } -impl Frontend { +impl Context<'_> { /// Resolves the types of the expressions until `expr` (inclusive) /// /// This needs to be done before the [`typifier`] can be queried for @@ -240,16 +238,11 @@ impl Frontend { /// /// [`typifier`]: Context::typifier /// [`resolve_type`]: Self::resolve_type - pub(crate) fn typifier_grow( - &self, - ctx: &mut Context, - expr: Handle, - meta: Span, - ) -> Result<()> { - let resolve_ctx = ResolveContext::with_locals(&self.module, &ctx.locals, &ctx.arguments); + pub(crate) fn typifier_grow(&mut self, expr: Handle, meta: Span) -> Result<()> { + let resolve_ctx = ResolveContext::with_locals(self.module, &self.locals, &self.arguments); - ctx.typifier - .grow(expr, &ctx.expressions, &resolve_ctx) + self.typifier + .grow(expr, &self.expressions, &resolve_ctx) .map_err(|error| Error { kind: ErrorKind::SemanticError(format!("Can't resolve type: {error:?}").into()), meta, @@ -263,14 +256,13 @@ impl Frontend { /// /// [`typifier`]: Context::typifier /// [`typifier_grow`]: Self::typifier_grow - pub(crate) fn resolve_type<'b>( - &'b self, - ctx: &'b mut Context, + pub(crate) fn resolve_type( + &mut self, expr: Handle, meta: Span, - ) -> Result<&'b TypeInner> { - self.typifier_grow(ctx, expr, meta)?; - Ok(ctx.typifier.get(expr, &self.module.types)) + ) -> Result<&TypeInner> { + self.typifier_grow(expr, meta)?; + Ok(self.typifier.get(expr, &self.module.types)) } /// Gets the type handle for the result of the `expr` expression @@ -290,25 +282,23 @@ impl Frontend { /// [`resolve_type`]: Self::resolve_type pub(crate) fn resolve_type_handle( &mut self, - ctx: &mut Context, expr: Handle, meta: Span, ) -> Result> { - self.typifier_grow(ctx, expr, meta)?; - Ok(ctx.typifier.register_type(expr, &mut self.module.types)) + self.typifier_grow(expr, meta)?; + Ok(self.typifier.register_type(expr, &mut self.module.types)) } /// Invalidates the cached type resolution for `expr` forcing a recomputation - pub(crate) fn invalidate_expression<'b>( - &'b self, - ctx: &'b mut Context, + pub(crate) fn invalidate_expression( + &mut self, expr: Handle, meta: Span, ) -> Result<()> { - let resolve_ctx = ResolveContext::with_locals(&self.module, &ctx.locals, &ctx.arguments); + let resolve_ctx = ResolveContext::with_locals(self.module, &self.locals, &self.arguments); - ctx.typifier - .invalidate(expr, &ctx.expressions, &resolve_ctx) + self.typifier + .invalidate(expr, &self.expressions, &resolve_ctx) .map_err(|error| Error { kind: ErrorKind::SemanticError(format!("Can't resolve type: {error:?}").into()), meta, @@ -317,13 +307,12 @@ impl Frontend { pub(crate) fn solve_constant( &mut self, - ctx: &Context, root: Handle, meta: Span, ) -> Result> { let mut solver = ConstantSolver { types: &mut self.module.types, - expressions: &ctx.expressions, + expressions: &self.expressions, constants: &mut self.module.constants, const_expressions: &mut self.module.const_expressions, }; diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index ad0bd7cbd..58cc31461 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -5,9 +5,9 @@ use super::{ Frontend, Result, Span, }; use crate::{ - AddressSpace, Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, - Interpolation, LocalVariable, ResourceBinding, ScalarKind, ShaderStage, SwizzleComponent, Type, - TypeInner, VectorSize, + AddressSpace, Binding, BuiltIn, Constant, Expression, GlobalVariable, Handle, Interpolation, + LocalVariable, ResourceBinding, ScalarKind, ShaderStage, SwizzleComponent, Type, TypeInner, + VectorSize, }; pub struct VarDeclaration<'a, 'key> { @@ -40,12 +40,11 @@ impl Frontend { fn add_builtin( &mut self, ctx: &mut Context, - body: &mut Block, name: &str, data: BuiltInData, meta: Span, - ) -> Option { - let ty = self.module.types.insert( + ) -> Result> { + let ty = ctx.module.types.insert( Type { name: None, inner: data.inner, @@ -53,7 +52,7 @@ impl Frontend { meta, ); - let handle = self.module.global_variables.append( + let handle = ctx.module.global_variables.append( GlobalVariable { name: Some(name.into()), space: AddressSpace::Private, @@ -81,7 +80,7 @@ impl Frontend { }, )); - let expr = ctx.add_expression(Expression::GlobalVariable(handle), meta, body); + let expr = ctx.add_expression(Expression::GlobalVariable(handle), meta)?; let var = VariableReference { expr, @@ -93,18 +92,17 @@ impl Frontend { ctx.symbol_table.add_root(name.into(), var.clone()); - Some(var) + Ok(Some(var)) } pub(crate) fn lookup_variable( &mut self, ctx: &mut Context, - body: &mut Block, name: &str, meta: Span, - ) -> Option { + ) -> Result> { if let Some(var) = ctx.symbol_table.lookup(name).cloned() { - return Some(var); + return Ok(Some(var)); } let data = match name { @@ -182,7 +180,7 @@ impl Frontend { storage: StorageQualifier::Output, }, "gl_ClipDistance" | "gl_CullDistance" => { - let base = self.module.types.insert( + let base = ctx.module.types.insert( Type { name: None, inner: TypeInner::Scalar { @@ -217,7 +215,7 @@ impl Frontend { "gl_VertexIndex" => BuiltIn::VertexIndex, "gl_SampleID" => BuiltIn::SampleIndex, "gl_LocalInvocationIndex" => BuiltIn::LocalInvocationIndex, - _ => return None, + _ => return Ok(None), }; BuiltInData { @@ -232,17 +230,16 @@ impl Frontend { } }; - self.add_builtin(ctx, body, name, data, meta) + self.add_builtin(ctx, name, data, meta) } pub(crate) fn make_variable_invariant( &mut self, ctx: &mut Context, - body: &mut Block, name: &str, meta: Span, - ) { - if let Some(var) = self.lookup_variable(ctx, body, name, meta) { + ) -> Result<()> { + if let Some(var) = self.lookup_variable(ctx, name, meta)? { if let Some(index) = var.entry_arg { if let Binding::BuiltIn(BuiltIn::Position { ref mut invariant }) = self.entry_args[index].binding @@ -251,19 +248,19 @@ impl Frontend { } } } + Ok(()) } pub(crate) fn field_selection( &mut self, ctx: &mut Context, pos: ExprPos, - body: &mut Block, expression: Handle, name: &str, meta: Span, ) -> Result> { - let (ty, is_pointer) = match *self.resolve_type(ctx, expression, meta)? { - TypeInner::Pointer { base, .. } => (&self.module.types[base].inner, true), + let (ty, is_pointer) = match *ctx.resolve_type(expression, meta)? { + TypeInner::Pointer { base, .. } => (&ctx.module.types[base].inner, true), ref ty => (ty, false), }; match *ty { @@ -281,12 +278,11 @@ impl Frontend { index: index as u32, }, meta, - body, - ); + )?; Ok(match pos { ExprPos::Rhs if is_pointer => { - ctx.add_expression(Expression::Load { pointer }, meta, body) + ctx.add_expression(Expression::Load { pointer }, meta)? } _ => pointer, }) @@ -358,19 +354,17 @@ impl Frontend { pointer: expression, }, meta, - body, - ); + )?; } _ => {} }; - return Ok(ctx.add_expression( + return ctx.add_expression( Expression::AccessIndex { base: expression, index: pattern[0].index(), }, meta, - body, - )); + ); } 2 => VectorSize::Bi, 3 => VectorSize::Tri, @@ -396,8 +390,7 @@ impl Frontend { pointer: expression, }, meta, - body, - ); + )?; } Ok(ctx.add_expression( @@ -407,8 +400,7 @@ impl Frontend { pattern, }, meta, - body, - )) + )?) } else { Err(Error { kind: ErrorKind::SemanticError( @@ -430,7 +422,6 @@ impl Frontend { pub(crate) fn add_global_var( &mut self, ctx: &mut Context, - body: &mut Block, VarDeclaration { qualifiers, mut ty, @@ -449,7 +440,7 @@ impl Frontend { .uint_layout_qualifier("location", &mut self.errors) .unwrap_or(0); let interpolation = qualifiers.interpolation.take().map(|(i, _)| i).or_else(|| { - let kind = self.module.types[ty].inner.scalar_kind()?; + let kind = ctx.module.types[ty].inner.scalar_kind()?; Some(match kind { ScalarKind::Float => Interpolation::Perspective, _ => Interpolation::Flat, @@ -457,7 +448,7 @@ impl Frontend { }); let sampling = qualifiers.sampling.take().map(|(s, _)| s); - let handle = self.module.global_variables.append( + let handle = ctx.module.global_variables.append( GlobalVariable { name: name.clone(), space: AddressSpace::Private, @@ -501,7 +492,7 @@ impl Frontend { ty, init, }; - let handle = self.module.constants.fetch_or_append(constant, meta); + let handle = ctx.module.constants.fetch_or_append(constant, meta); let lookup = GlobalLookup { kind: GlobalLookupKind::Constant(handle, ty), @@ -518,7 +509,7 @@ impl Frontend { *access = allowed_access; } } - AddressSpace::Uniform => match self.module.types[ty].inner { + AddressSpace::Uniform => match ctx.module.types[ty].inner { TypeInner::Image { class, dim, @@ -547,7 +538,7 @@ impl Frontend { _ => unreachable!(), } - ty = self.module.types.insert( + ty = ctx.module.types.insert( Type { name: None, inner: TypeInner::Image { @@ -593,7 +584,7 @@ impl Frontend { _ => None, }; - let handle = self.module.global_variables.append( + let handle = ctx.module.global_variables.append( GlobalVariable { name: name.clone(), space, @@ -615,7 +606,7 @@ impl Frontend { }; if let Some(name) = name { - ctx.add_global(self, &name, lookup, body); + ctx.add_global(&name, lookup)?; self.global_variables.push((name, lookup)); } @@ -628,7 +619,6 @@ impl Frontend { pub(crate) fn add_local_var( &mut self, ctx: &mut Context, - body: &mut Block, decl: VarDeclaration, ) -> Result> { let storage = decl.qualifiers.storage; @@ -652,7 +642,7 @@ impl Frontend { }, decl.meta, ); - let expr = ctx.add_expression(Expression::LocalVariable(handle), decl.meta, body); + let expr = ctx.add_expression(Expression::LocalVariable(handle), decl.meta)?; if let Some(name) = decl.name { let maybe_var = ctx.add_local_var(name.clone(), expr, mutable); From 4daed6707523cd4c0ec9d6d3916135231aa709e0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 2 Aug 2023 11:59:09 -0700 Subject: [PATCH 2070/2212] [glsl-in] Document Frontend::add_entry_point. --- src/front/glsl/functions.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 061494387..c0a208394 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1304,6 +1304,36 @@ impl Frontend { Ok(()) } + /// Create a Naga [`EntryPoint`] that calls the GLSL `main` function. + /// + /// We compile the GLSL `main` function as an ordinary Naga [`Function`]. + /// This function synthesizes a Naga [`EntryPoint`] to call that. + /// + /// Each GLSL input and output variable (including builtins) becomes a Naga + /// [`GlobalVariable`]s in the [`Private`] address space, which `main` can + /// access in the usual way. + /// + /// The `EntryPoint` we synthesize here has an argument for each GLSL input + /// variable, and returns a struct with a member for each GLSL output + /// variable. The entry point contains code to: + /// + /// - copy its arguments into the Naga globals representing the GLSL input + /// variables, + /// + /// - call the Naga `Function` representing the GLSL `main` function, and then + /// + /// - build its return value from whatever values the GLSL `main` left in + /// the Naga globals representing GLSL `output` variables. + /// + /// Upon entry, [`ctx.body`] should contain code, accumulated by prior calls + /// to [`ParsingContext::parse_external_declaration`][pxd], to initialize + /// private global variables as needed. This code gets spliced into the + /// entry point before the call to `main`. + /// + /// [`GlobalVariable`]: crate::GlobalVariable + /// [`Private`]: crate::AddressSpace::Private + /// [`ctx.body`]: Context::body + /// [pxd]: super::ParsingContext::parse_external_declaration pub(crate) fn add_entry_point( &mut self, function: Handle, From 9bcb5691a5adf08269adfc9a11a3ce852ec1be96 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 1 Sep 2023 12:43:43 -0700 Subject: [PATCH 2071/2212] [glsl-in] Doc fix. --- src/front/glsl/parser/functions.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 358bc52e7..200afc78f 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -195,6 +195,11 @@ impl<'source> ParsingContext<'source> { match ctx.module.const_expressions[const_expr] { Expression::Literal(Literal::I32(value)) => match uint { + // This unchecked cast isn't good, but since + // we only reach this code when the selector + // is unsigned but the case label is signed, + // verification will reject the module + // anyway (which also matches GLSL's rules). true => crate::SwitchValue::U32(value as u32), false => crate::SwitchValue::I32(value), }, From 3bd3c6ffb2767c958303e397420c248731eb71cc Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 5 Sep 2023 13:18:40 -0700 Subject: [PATCH 2072/2212] [glsl-in] Move `arg_type_walker` method from Frontend to Context. --- src/front/glsl/functions.rs | 234 ++++++++++++++++++------------------ 1 file changed, 117 insertions(+), 117 deletions(-) diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index c0a208394..fe96d2c4e 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -1191,119 +1191,6 @@ impl Frontend { }); } - /// Helper function for building the input/output interface of the entry point - /// - /// Calls `f` with the data of the entry point argument, flattening composite types - /// recursively - /// - /// The passed arguments to the callback are: - /// - The ctx - /// - The name - /// - The pointer expression to the global storage - /// - The handle to the type of the entry point argument - /// - The binding of the entry point argument - fn arg_type_walker( - ctx: &mut Context, - name: Option, - binding: crate::Binding, - pointer: Handle, - ty: Handle, - f: &mut impl FnMut( - &mut Context, - Option, - Handle, - Handle, - crate::Binding, - ), - ) -> Result<()> { - match ctx.module.types[ty].inner { - // TODO: Better error reporting - // right now we just don't walk the array if the size isn't known at - // compile time and let validation catch it - TypeInner::Array { - base, - size: crate::ArraySize::Constant(size), - .. - } => { - let mut location = match binding { - crate::Binding::Location { location, .. } => location, - crate::Binding::BuiltIn(_) => return Ok(()), - }; - - let interpolation = - ctx.module.types[base] - .inner - .scalar_kind() - .map(|kind| match kind { - ScalarKind::Float => crate::Interpolation::Perspective, - _ => crate::Interpolation::Flat, - }); - - for index in 0..size.get() { - let member_pointer = ctx.add_expression( - Expression::AccessIndex { - base: pointer, - index, - }, - crate::Span::default(), - )?; - - let binding = crate::Binding::Location { - location, - interpolation, - sampling: None, - second_blend_source: false, - }; - location += 1; - - Self::arg_type_walker(ctx, name.clone(), binding, member_pointer, base, f)? - } - } - TypeInner::Struct { ref members, .. } => { - let mut location = match binding { - crate::Binding::Location { location, .. } => location, - crate::Binding::BuiltIn(_) => return Ok(()), - }; - - for (i, member) in members.clone().into_iter().enumerate() { - let member_pointer = ctx.add_expression( - Expression::AccessIndex { - base: pointer, - index: i as u32, - }, - crate::Span::default(), - )?; - - let binding = match member.binding { - Some(binding) => binding, - None => { - let interpolation = ctx.module.types[member.ty] - .inner - .scalar_kind() - .map(|kind| match kind { - ScalarKind::Float => crate::Interpolation::Perspective, - _ => crate::Interpolation::Flat, - }); - let binding = crate::Binding::Location { - location, - interpolation, - sampling: None, - second_blend_source: false, - }; - location += 1; - binding - } - }; - - Self::arg_type_walker(ctx, member.name, binding, member_pointer, member.ty, f)? - } - } - _ => f(ctx, name, pointer, ty, binding), - } - - Ok(()) - } - /// Create a Naga [`EntryPoint`] that calls the GLSL `main` function. /// /// We compile the GLSL `main` function as an ordinary Naga [`Function`]. @@ -1363,8 +1250,7 @@ impl Frontend { let ty = ctx.module.global_variables[arg.handle].ty; - Self::arg_type_walker( - &mut ctx, + ctx.arg_type_walker( arg.name.clone(), arg.binding.clone(), pointer, @@ -1413,8 +1299,7 @@ impl Frontend { let ty = ctx.module.global_variables[arg.handle].ty; - Self::arg_type_walker( - &mut ctx, + ctx.arg_type_walker( arg.name.clone(), arg.binding.clone(), pointer, @@ -1491,6 +1376,121 @@ impl Frontend { } } +impl Context<'_> { + /// Helper function for building the input/output interface of the entry point + /// + /// Calls `f` with the data of the entry point argument, flattening composite types + /// recursively + /// + /// The passed arguments to the callback are: + /// - The ctx + /// - The name + /// - The pointer expression to the global storage + /// - The handle to the type of the entry point argument + /// - The binding of the entry point argument + fn arg_type_walker( + &mut self, + name: Option, + binding: crate::Binding, + pointer: Handle, + ty: Handle, + f: &mut impl FnMut( + &mut Context, + Option, + Handle, + Handle, + crate::Binding, + ), + ) -> Result<()> { + match self.module.types[ty].inner { + // TODO: Better error reporting + // right now we just don't walk the array if the size isn't known at + // compile time and let validation catch it + TypeInner::Array { + base, + size: crate::ArraySize::Constant(size), + .. + } => { + let mut location = match binding { + crate::Binding::Location { location, .. } => location, + crate::Binding::BuiltIn(_) => return Ok(()), + }; + + let interpolation = + self.module.types[base] + .inner + .scalar_kind() + .map(|kind| match kind { + ScalarKind::Float => crate::Interpolation::Perspective, + _ => crate::Interpolation::Flat, + }); + + for index in 0..size.get() { + let member_pointer = self.add_expression( + Expression::AccessIndex { + base: pointer, + index, + }, + crate::Span::default(), + )?; + + let binding = crate::Binding::Location { + location, + interpolation, + sampling: None, + second_blend_source: false, + }; + location += 1; + + self.arg_type_walker(name.clone(), binding, member_pointer, base, f)? + } + } + TypeInner::Struct { ref members, .. } => { + let mut location = match binding { + crate::Binding::Location { location, .. } => location, + crate::Binding::BuiltIn(_) => return Ok(()), + }; + + for (i, member) in members.clone().into_iter().enumerate() { + let member_pointer = self.add_expression( + Expression::AccessIndex { + base: pointer, + index: i as u32, + }, + crate::Span::default(), + )?; + + let binding = match member.binding { + Some(binding) => binding, + None => { + let interpolation = self.module.types[member.ty] + .inner + .scalar_kind() + .map(|kind| match kind { + ScalarKind::Float => crate::Interpolation::Perspective, + _ => crate::Interpolation::Flat, + }); + let binding = crate::Binding::Location { + location, + interpolation, + sampling: None, + second_blend_source: false, + }; + location += 1; + binding + } + }; + + self.arg_type_walker(member.name, binding, member_pointer, member.ty, f)? + } + } + _ => f(self, name, pointer, ty, binding), + } + + Ok(()) + } +} + /// Helper enum containing the type of conversion need for a call #[derive(PartialEq, Eq, Clone, Copy, Debug)] enum Conversion { From 978e6df645c6169c076f6b80fdc1ed7771aee509 Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Tue, 5 Sep 2023 22:16:42 +0200 Subject: [PATCH 2073/2212] Use || instead of | --- src/valid/expression.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 548b6c145..7a8385dba 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -893,7 +893,7 @@ impl super::Validator { let arg3_ty = arg3.map(resolve); match fun { Mf::Abs => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } let good = match *arg_ty { @@ -979,7 +979,7 @@ impl super::Validator { | Mf::Sign | Mf::Sqrt | Mf::InverseSqrt => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -1015,7 +1015,7 @@ impl super::Validator { } } Mf::Modf | Mf::Frexp => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } if !matches!( @@ -1147,7 +1147,7 @@ impl super::Validator { } } Mf::Normalize => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -1227,7 +1227,7 @@ impl super::Validator { } } Mf::Inverse | Mf::Determinant => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } let good = match *arg_ty { @@ -1239,7 +1239,7 @@ impl super::Validator { } } Mf::Transpose => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -1253,7 +1253,7 @@ impl super::Validator { | Mf::ReverseBits | Mf::FindLsb | Mf::FindMsb => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -1350,7 +1350,7 @@ impl super::Validator { } } Mf::Pack2x16unorm | Mf::Pack2x16snorm | Mf::Pack2x16float => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -1363,7 +1363,7 @@ impl super::Validator { } } Mf::Pack4x8snorm | Mf::Pack4x8unorm => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { @@ -1380,7 +1380,7 @@ impl super::Validator { | Mf::Unpack2x16unorm | Mf::Unpack4x8snorm | Mf::Unpack4x8unorm => { - if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { return Err(ExpressionError::WrongArgumentCount(fun)); } match *arg_ty { From a0eb1f54629133a05f1bd0c82c28c15e0e3e61a2 Mon Sep 17 00:00:00 2001 From: Fredrik Fornwall Date: Wed, 6 Sep 2023 18:29:35 +0200 Subject: [PATCH 2074/2212] [wgsl-in] Allow sign() to take int argument (#2463) --- src/back/msl/writer.rs | 47 +++- src/valid/expression.rs | 17 +- tests/in/math-functions.wgsl | 4 + .../glsl/math-functions.main.Fragment.glsl | 8 +- tests/out/hlsl/math-functions.hlsl | 8 +- tests/out/msl/math-functions.msl | 17 +- tests/out/spv/math-functions.spvasm | 225 +++++++++--------- tests/out/wgsl/math-functions.wgsl | 4 + 8 files changed, 207 insertions(+), 123 deletions(-) diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 24c54ff8a..67ab88728 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1184,6 +1184,31 @@ impl Writer { Ok(()) } + /// Emit code for the sign(i32) expression. + /// + fn put_isign( + &mut self, + arg: Handle, + context: &ExpressionContext, + ) -> BackendResult { + write!(self.out, "{NAMESPACE}::select({NAMESPACE}::select(")?; + match context.resolve_type(arg) { + &crate::TypeInner::Vector { size, .. } => { + let size = back::vector_size_str(size); + write!(self.out, "int{size}(-1), int{size}(1)")?; + } + _ => { + write!(self.out, "-1, 1")?; + } + } + write!(self.out, ", (")?; + self.put_expression(arg, context, true)?; + write!(self.out, " > 0)), 0, (")?; + self.put_expression(arg, context, true)?; + write!(self.out, " == 0))")?; + Ok(()) + } + fn put_const_expression( &mut self, expr_handle: Handle, @@ -1647,8 +1672,9 @@ impl Writer { } => { use crate::MathFunction as Mf; - let scalar_argument = match *context.resolve_type(arg) { - crate::TypeInner::Scalar { .. } => true, + let arg_type = context.resolve_type(arg); + let scalar_argument = match arg_type { + &crate::TypeInner::Scalar { .. } => true, _ => false, }; @@ -1713,7 +1739,12 @@ impl Writer { Mf::Reflect => "reflect", Mf::Refract => "refract", // computational - Mf::Sign => "sign", + Mf::Sign => match arg_type.scalar_kind() { + Some(crate::ScalarKind::Sint) => { + return self.put_isign(arg, context); + } + _ => "sign", + }, Mf::Fma => "fma", Mf::Mix => "mix", Mf::Step => "step", @@ -2423,6 +2454,16 @@ impl Writer { crate::MathFunction::FindMsb => { self.need_bake_expressions.insert(arg); } + crate::MathFunction::Sign => { + // WGSL's `sign` function works also on signed ints, but Metal's only + // works on floating points, so we emit inline code for integer `sign` + // calls. But that code uses each argument 2 times (see `put_isign`), + // so to avoid duplicated evaluation, we must bake the argument. + let inner = context.resolve_type(expr_handle); + if inner.scalar_kind() == Some(crate::ScalarKind::Sint) { + self.need_bake_expressions.insert(arg); + } + } _ => {} } } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 7a8385dba..1d1d6c0b9 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -976,7 +976,6 @@ impl super::Validator { | Mf::Log | Mf::Log2 | Mf::Length - | Mf::Sign | Mf::Sqrt | Mf::InverseSqrt => { if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { @@ -992,6 +991,22 @@ impl super::Validator { _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), } } + Mf::Sign => { + if arg1_ty.is_some() || arg2_ty.is_some() || arg3_ty.is_some() { + return Err(ExpressionError::WrongArgumentCount(fun)); + } + match *arg_ty { + Ti::Scalar { + kind: Sk::Float | Sk::Sint, + .. + } + | Ti::Vector { + kind: Sk::Float | Sk::Sint, + .. + } => {} + _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)), + } + } Mf::Atan2 | Mf::Pow | Mf::Distance | Mf::Step => { let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) { (Some(ty1), None, None) => ty1, diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl index 408f8a74f..d08e76e4f 100644 --- a/tests/in/math-functions.wgsl +++ b/tests/in/math-functions.wgsl @@ -8,6 +8,10 @@ fn main() { let d = radians(v); let e = saturate(v); let g = refract(v, v, f); + let sign_a = sign(-1); + let sign_b = sign(vec4(-1)); + let sign_c = sign(-1.0); + let sign_d = sign(vec4(-1.0)); let const_dot = dot(vec2(), vec2()); let first_leading_bit_abs = firstLeadingBit(abs(0u)); let flb_a = firstLeadingBit(-1); diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl index be81715ce..37c072a6f 100644 --- a/tests/out/glsl/math-functions.main.Fragment.glsl +++ b/tests/out/glsl/math-functions.main.Fragment.glsl @@ -62,6 +62,10 @@ void main() { vec4 d = radians(v); vec4 e = clamp(v, vec4(0.0), vec4(1.0)); vec4 g = refract(v, v, 1.0); + int sign_a = sign(-1); + ivec4 sign_b = sign(ivec4(-1)); + float sign_c = sign(-1.0); + vec4 sign_d = sign(vec4(-1.0)); int const_dot = ( + ivec2(0).x * ivec2(0).x + ivec2(0).y * ivec2(0).y); uint first_leading_bit_abs = uint(findMSB(uint(abs(int(0u))))); int flb_a = findMSB(-1); @@ -81,8 +85,8 @@ void main() { ivec2 ctz_h = ivec2(min(uvec2(findLSB(ivec2(1))), uvec2(32u))); int clz_a = (-1 < 0 ? 0 : 31 - findMSB(-1)); uint clz_b = uint(31 - findMSB(1u)); - ivec2 _e58 = ivec2(-1); - ivec2 clz_c = mix(ivec2(31) - findMSB(_e58), ivec2(0), lessThan(_e58, ivec2(0))); + ivec2 _e68 = ivec2(-1); + ivec2 clz_c = mix(ivec2(31) - findMSB(_e68), ivec2(0), lessThan(_e68, ivec2(0))); uvec2 clz_d = uvec2(ivec2(31) - findMSB(uvec2(1u))); float lde_a = ldexp(1.0, 2); vec2 lde_b = ldexp(vec2(1.0, 2.0), ivec2(3, 4)); diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index afdc6f467..fc5cadb65 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -72,6 +72,10 @@ void main() float4 d = radians(v); float4 e = saturate(v); float4 g = refract(v, v, 1.0); + int sign_a = sign(-1); + int4 sign_b = sign((-1).xxxx); + float sign_c = sign(-1.0); + float4 sign_d = sign((-1.0).xxxx); int const_dot = dot((int2)0, (int2)0); uint first_leading_bit_abs = firstbithigh(abs(0u)); int flb_a = asint(firstbithigh(-1)); @@ -91,8 +95,8 @@ void main() int2 ctz_h = asint(min((32u).xx, firstbitlow((1).xx))); int clz_a = (-1 < 0 ? 0 : 31 - asint(firstbithigh(-1))); uint clz_b = (31u - firstbithigh(1u)); - int2 _expr58 = (-1).xx; - int2 clz_c = (_expr58 < (0).xx ? (0).xx : (31).xx - asint(firstbithigh(_expr58))); + int2 _expr68 = (-1).xx; + int2 clz_c = (_expr68 < (0).xx ? (0).xx : (31).xx - asint(firstbithigh(_expr68))); uint2 clz_d = ((31u).xx - firstbithigh((1u).xx)); float lde_a = ldexp(1.0, 2); float2 lde_b = ldexp(float2(1.0, 2.0), int2(3, 4)); diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index 14824ec30..dccb90ad6 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -64,14 +64,19 @@ fragment void main_( metal::float4 d = ((v) * 0.017453292519943295474); metal::float4 e = metal::saturate(v); metal::float4 g = metal::refract(v, v, 1.0); + int sign_a = metal::select(metal::select(-1, 1, (-1 > 0)), 0, (-1 == 0)); + metal::int4 _e12 = metal::int4(-1); + metal::int4 sign_b = metal::select(metal::select(int4(-1), int4(1), (_e12 > 0)), 0, (_e12 == 0)); + float sign_c = metal::sign(-1.0); + metal::float4 sign_d = metal::sign(metal::float4(-1.0)); int const_dot = ( + metal::int2 {}.x * metal::int2 {}.x + metal::int2 {}.y * metal::int2 {}.y); - uint _e13 = metal::abs(0u); - uint first_leading_bit_abs = metal::select(31 - metal::clz(_e13), uint(-1), _e13 == 0 || _e13 == -1); + uint _e23 = metal::abs(0u); + uint first_leading_bit_abs = metal::select(31 - metal::clz(_e23), uint(-1), _e23 == 0 || _e23 == -1); int flb_a = metal::select(31 - metal::clz(metal::select(-1, ~-1, -1 < 0)), int(-1), -1 == 0 || -1 == -1); - metal::int2 _e18 = metal::int2(-1); - metal::int2 flb_b = metal::select(31 - metal::clz(metal::select(_e18, ~_e18, _e18 < 0)), int2(-1), _e18 == 0 || _e18 == -1); - metal::uint2 _e21 = metal::uint2(1u); - metal::uint2 flb_c = metal::select(31 - metal::clz(_e21), uint2(-1), _e21 == 0 || _e21 == -1); + metal::int2 _e28 = metal::int2(-1); + metal::int2 flb_b = metal::select(31 - metal::clz(metal::select(_e28, ~_e28, _e28 < 0)), int2(-1), _e28 == 0 || _e28 == -1); + metal::uint2 _e31 = metal::uint2(1u); + metal::uint2 flb_c = metal::select(31 - metal::clz(_e31), uint2(-1), _e31 == 0 || _e31 == -1); int ftb_a = (((metal::ctz(-1) + 1) % 33) - 1); uint ftb_b = (((metal::ctz(1u) + 1) % 33) - 1); metal::int2 ftb_c = (((metal::ctz(metal::int2(-1)) + 1) % 33) - 1); diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 260c3b4bd..7edb0e26b 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 127 +; Bound: 134 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -32,116 +32,123 @@ OpMemberDecorate %13 1 Offset 16 %16 = OpTypeFunction %2 %17 = OpConstant %4 1.0 %18 = OpConstant %4 0.0 -%19 = OpConstantNull %5 -%20 = OpTypeInt 32 0 -%21 = OpConstant %20 0 -%22 = OpConstant %6 -1 -%23 = OpConstant %20 1 -%24 = OpConstant %6 0 -%25 = OpConstant %20 4294967295 -%26 = OpConstant %6 1 -%27 = OpConstant %6 2 -%28 = OpConstant %4 2.0 -%29 = OpConstant %6 3 -%30 = OpConstant %6 4 -%31 = OpConstant %4 1.5 -%39 = OpConstantComposite %3 %18 %18 %18 %18 -%40 = OpConstantComposite %3 %17 %17 %17 %17 -%43 = OpConstantNull %6 -%56 = OpTypeVector %20 2 -%66 = OpConstant %20 32 -%76 = OpConstantComposite %56 %66 %66 -%88 = OpConstant %6 31 -%94 = OpConstantComposite %5 %88 %88 +%19 = OpConstant %6 -1 +%20 = OpConstant %4 -1.0 +%21 = OpConstantNull %5 +%22 = OpTypeInt 32 0 +%23 = OpConstant %22 0 +%24 = OpConstant %22 1 +%25 = OpConstant %6 0 +%26 = OpConstant %22 4294967295 +%27 = OpConstant %6 1 +%28 = OpConstant %6 2 +%29 = OpConstant %4 2.0 +%30 = OpConstant %6 3 +%31 = OpConstant %6 4 +%32 = OpConstant %4 1.5 +%40 = OpConstantComposite %3 %18 %18 %18 %18 +%41 = OpConstantComposite %3 %17 %17 %17 %17 +%50 = OpConstantNull %6 +%63 = OpTypeVector %22 2 +%73 = OpConstant %22 32 +%83 = OpConstantComposite %63 %73 %73 +%95 = OpConstant %6 31 +%101 = OpConstantComposite %5 %95 %95 %15 = OpFunction %2 None %16 %14 = OpLabel -OpBranch %32 -%32 = OpLabel -%33 = OpCompositeConstruct %3 %18 %18 %18 %18 -%34 = OpExtInst %4 %1 Degrees %17 -%35 = OpExtInst %4 %1 Radians %17 -%36 = OpExtInst %3 %1 Degrees %33 -%37 = OpExtInst %3 %1 Radians %33 -%38 = OpExtInst %3 %1 FClamp %33 %39 %40 -%41 = OpExtInst %3 %1 Refract %33 %33 %17 -%44 = OpCompositeExtract %6 %19 0 -%45 = OpCompositeExtract %6 %19 0 -%46 = OpIMul %6 %44 %45 -%47 = OpIAdd %6 %43 %46 -%48 = OpCompositeExtract %6 %19 1 -%49 = OpCompositeExtract %6 %19 1 -%50 = OpIMul %6 %48 %49 -%42 = OpIAdd %6 %47 %50 -%51 = OpCopyObject %20 %21 -%52 = OpExtInst %20 %1 FindUMsb %51 -%53 = OpExtInst %6 %1 FindSMsb %22 -%54 = OpCompositeConstruct %5 %22 %22 -%55 = OpExtInst %5 %1 FindSMsb %54 -%57 = OpCompositeConstruct %56 %23 %23 -%58 = OpExtInst %56 %1 FindUMsb %57 -%59 = OpExtInst %6 %1 FindILsb %22 -%60 = OpExtInst %20 %1 FindILsb %23 -%61 = OpCompositeConstruct %5 %22 %22 -%62 = OpExtInst %5 %1 FindILsb %61 -%63 = OpCompositeConstruct %56 %23 %23 -%64 = OpExtInst %56 %1 FindILsb %63 -%67 = OpExtInst %20 %1 FindILsb %21 -%65 = OpExtInst %20 %1 UMin %66 %67 -%69 = OpExtInst %6 %1 FindILsb %24 -%68 = OpExtInst %6 %1 UMin %66 %69 -%71 = OpExtInst %20 %1 FindILsb %25 -%70 = OpExtInst %20 %1 UMin %66 %71 -%73 = OpExtInst %6 %1 FindILsb %22 -%72 = OpExtInst %6 %1 UMin %66 %73 -%74 = OpCompositeConstruct %56 %21 %21 -%77 = OpExtInst %56 %1 FindILsb %74 -%75 = OpExtInst %56 %1 UMin %76 %77 -%78 = OpCompositeConstruct %5 %24 %24 -%80 = OpExtInst %5 %1 FindILsb %78 -%79 = OpExtInst %5 %1 UMin %76 %80 -%81 = OpCompositeConstruct %56 %23 %23 -%83 = OpExtInst %56 %1 FindILsb %81 -%82 = OpExtInst %56 %1 UMin %76 %83 -%84 = OpCompositeConstruct %5 %26 %26 -%86 = OpExtInst %5 %1 FindILsb %84 -%85 = OpExtInst %5 %1 UMin %76 %86 -%89 = OpExtInst %6 %1 FindUMsb %22 -%87 = OpISub %6 %88 %89 -%91 = OpExtInst %6 %1 FindUMsb %23 -%90 = OpISub %20 %88 %91 -%92 = OpCompositeConstruct %5 %22 %22 -%95 = OpExtInst %5 %1 FindUMsb %92 -%93 = OpISub %5 %94 %95 -%96 = OpCompositeConstruct %56 %23 %23 -%98 = OpExtInst %5 %1 FindUMsb %96 -%97 = OpISub %56 %94 %98 -%99 = OpExtInst %4 %1 Ldexp %17 %27 -%100 = OpCompositeConstruct %7 %17 %28 -%101 = OpCompositeConstruct %5 %29 %30 -%102 = OpExtInst %7 %1 Ldexp %100 %101 -%103 = OpExtInst %8 %1 ModfStruct %31 -%104 = OpExtInst %8 %1 ModfStruct %31 -%105 = OpCompositeExtract %4 %104 0 -%106 = OpExtInst %8 %1 ModfStruct %31 -%107 = OpCompositeExtract %4 %106 1 -%108 = OpCompositeConstruct %7 %31 %31 -%109 = OpExtInst %9 %1 ModfStruct %108 -%110 = OpCompositeConstruct %3 %31 %31 %31 %31 -%111 = OpExtInst %10 %1 ModfStruct %110 -%112 = OpCompositeExtract %3 %111 1 -%113 = OpCompositeExtract %4 %112 0 -%114 = OpCompositeConstruct %7 %31 %31 -%115 = OpExtInst %9 %1 ModfStruct %114 -%116 = OpCompositeExtract %7 %115 0 -%117 = OpCompositeExtract %4 %116 1 -%118 = OpExtInst %11 %1 FrexpStruct %31 -%119 = OpExtInst %11 %1 FrexpStruct %31 +OpBranch %33 +%33 = OpLabel +%34 = OpCompositeConstruct %3 %18 %18 %18 %18 +%35 = OpExtInst %4 %1 Degrees %17 +%36 = OpExtInst %4 %1 Radians %17 +%37 = OpExtInst %3 %1 Degrees %34 +%38 = OpExtInst %3 %1 Radians %34 +%39 = OpExtInst %3 %1 FClamp %34 %40 %41 +%42 = OpExtInst %3 %1 Refract %34 %34 %17 +%43 = OpExtInst %6 %1 SSign %19 +%44 = OpCompositeConstruct %12 %19 %19 %19 %19 +%45 = OpExtInst %12 %1 SSign %44 +%46 = OpExtInst %4 %1 FSign %20 +%47 = OpCompositeConstruct %3 %20 %20 %20 %20 +%48 = OpExtInst %3 %1 FSign %47 +%51 = OpCompositeExtract %6 %21 0 +%52 = OpCompositeExtract %6 %21 0 +%53 = OpIMul %6 %51 %52 +%54 = OpIAdd %6 %50 %53 +%55 = OpCompositeExtract %6 %21 1 +%56 = OpCompositeExtract %6 %21 1 +%57 = OpIMul %6 %55 %56 +%49 = OpIAdd %6 %54 %57 +%58 = OpCopyObject %22 %23 +%59 = OpExtInst %22 %1 FindUMsb %58 +%60 = OpExtInst %6 %1 FindSMsb %19 +%61 = OpCompositeConstruct %5 %19 %19 +%62 = OpExtInst %5 %1 FindSMsb %61 +%64 = OpCompositeConstruct %63 %24 %24 +%65 = OpExtInst %63 %1 FindUMsb %64 +%66 = OpExtInst %6 %1 FindILsb %19 +%67 = OpExtInst %22 %1 FindILsb %24 +%68 = OpCompositeConstruct %5 %19 %19 +%69 = OpExtInst %5 %1 FindILsb %68 +%70 = OpCompositeConstruct %63 %24 %24 +%71 = OpExtInst %63 %1 FindILsb %70 +%74 = OpExtInst %22 %1 FindILsb %23 +%72 = OpExtInst %22 %1 UMin %73 %74 +%76 = OpExtInst %6 %1 FindILsb %25 +%75 = OpExtInst %6 %1 UMin %73 %76 +%78 = OpExtInst %22 %1 FindILsb %26 +%77 = OpExtInst %22 %1 UMin %73 %78 +%80 = OpExtInst %6 %1 FindILsb %19 +%79 = OpExtInst %6 %1 UMin %73 %80 +%81 = OpCompositeConstruct %63 %23 %23 +%84 = OpExtInst %63 %1 FindILsb %81 +%82 = OpExtInst %63 %1 UMin %83 %84 +%85 = OpCompositeConstruct %5 %25 %25 +%87 = OpExtInst %5 %1 FindILsb %85 +%86 = OpExtInst %5 %1 UMin %83 %87 +%88 = OpCompositeConstruct %63 %24 %24 +%90 = OpExtInst %63 %1 FindILsb %88 +%89 = OpExtInst %63 %1 UMin %83 %90 +%91 = OpCompositeConstruct %5 %27 %27 +%93 = OpExtInst %5 %1 FindILsb %91 +%92 = OpExtInst %5 %1 UMin %83 %93 +%96 = OpExtInst %6 %1 FindUMsb %19 +%94 = OpISub %6 %95 %96 +%98 = OpExtInst %6 %1 FindUMsb %24 +%97 = OpISub %22 %95 %98 +%99 = OpCompositeConstruct %5 %19 %19 +%102 = OpExtInst %5 %1 FindUMsb %99 +%100 = OpISub %5 %101 %102 +%103 = OpCompositeConstruct %63 %24 %24 +%105 = OpExtInst %5 %1 FindUMsb %103 +%104 = OpISub %63 %101 %105 +%106 = OpExtInst %4 %1 Ldexp %17 %28 +%107 = OpCompositeConstruct %7 %17 %29 +%108 = OpCompositeConstruct %5 %30 %31 +%109 = OpExtInst %7 %1 Ldexp %107 %108 +%110 = OpExtInst %8 %1 ModfStruct %32 +%111 = OpExtInst %8 %1 ModfStruct %32 +%112 = OpCompositeExtract %4 %111 0 +%113 = OpExtInst %8 %1 ModfStruct %32 +%114 = OpCompositeExtract %4 %113 1 +%115 = OpCompositeConstruct %7 %32 %32 +%116 = OpExtInst %9 %1 ModfStruct %115 +%117 = OpCompositeConstruct %3 %32 %32 %32 %32 +%118 = OpExtInst %10 %1 ModfStruct %117 +%119 = OpCompositeExtract %3 %118 1 %120 = OpCompositeExtract %4 %119 0 -%121 = OpExtInst %11 %1 FrexpStruct %31 -%122 = OpCompositeExtract %6 %121 1 -%123 = OpCompositeConstruct %3 %31 %31 %31 %31 -%124 = OpExtInst %13 %1 FrexpStruct %123 -%125 = OpCompositeExtract %12 %124 1 -%126 = OpCompositeExtract %6 %125 0 +%121 = OpCompositeConstruct %7 %32 %32 +%122 = OpExtInst %9 %1 ModfStruct %121 +%123 = OpCompositeExtract %7 %122 0 +%124 = OpCompositeExtract %4 %123 1 +%125 = OpExtInst %11 %1 FrexpStruct %32 +%126 = OpExtInst %11 %1 FrexpStruct %32 +%127 = OpCompositeExtract %4 %126 0 +%128 = OpExtInst %11 %1 FrexpStruct %32 +%129 = OpCompositeExtract %6 %128 1 +%130 = OpCompositeConstruct %3 %32 %32 %32 %32 +%131 = OpExtInst %13 %1 FrexpStruct %130 +%132 = OpCompositeExtract %12 %131 1 +%133 = OpCompositeExtract %6 %132 0 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 149ebff8e..0b20291f5 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -7,6 +7,10 @@ fn main() { let d = radians(v); let e = saturate(v); let g = refract(v, v, 1.0); + let sign_a = sign(-1); + let sign_b = sign(vec4(-1)); + let sign_c = sign(-1.0); + let sign_d = sign(vec4(-1.0)); let const_dot = dot(vec2(), vec2()); let first_leading_bit_abs = firstLeadingBit(abs(0u)); let flb_a = firstLeadingBit(-1); From cc87b8f9eb30bb55d0735b89d3df3e099e1a6e7c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 11 Sep 2023 02:59:14 -0700 Subject: [PATCH 2075/2212] Don't warn about unused mut in tests when "validate" feature is off. (#2466) --- src/valid/interface.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index d788a54a3..2416e8921 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -614,6 +614,7 @@ impl super::Validator { return Err(EntryPointError::UnexpectedWorkgroupSize.with_span()); } + #[cfg_attr(not(feature = "validate"), allow(unused_mut))] let mut info = self .validate_function(&ep.function, module, mod_info, true) .map_err(WithSpan::into_other)?; From b17eaf76a32377bfa5c4c0892efc250bcd1206d8 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 11 Sep 2023 09:32:56 -0700 Subject: [PATCH 2076/2212] snapshots::convert_spv: Print input name before processing. (#2467) When `convert_spv` fails, this makes it easier to tell which file it was trying to process. --- tests/snapshots.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index a2e03679b..1782e8b96 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -653,6 +653,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { let root = env!("CARGO_MANIFEST_DIR"); + println!("Processing '{name}'"); let module = naga::front::spv::parse_u8_slice( &fs::read(format!("{root}/{BASE_DIR_IN}/spv/{name}.spv")).expect("Couldn't find spv file"), &naga::front::spv::Options { From 0f36a745cff90902f7f3ce0de18b3b4268061f80 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Sep 2023 10:34:24 -0700 Subject: [PATCH 2077/2212] [wgsl-out] Don't include type parameter in splat expressions. (#2469) Generate `vec4(1.0)` instead of `vec4(1.0)`, since WGSL requires us to infer the type parameter anyway. --- src/back/wgsl/writer.rs | 26 +-- .../wgsl/900-implicit-conversions-frag.wgsl | 2 +- tests/out/wgsl/901-lhs-field-select-frag.wgsl | 2 +- tests/out/wgsl/access.wgsl | 26 +-- tests/out/wgsl/bevy-pbr-frag.wgsl | 24 +-- tests/out/wgsl/binding-arrays.wgsl | 12 +- tests/out/wgsl/bitcast.wgsl | 18 +- tests/out/wgsl/bits.wgsl | 16 +- tests/out/wgsl/bits_glsl-frag.wgsl | 16 +- tests/out/wgsl/boids.wgsl | 4 +- tests/out/wgsl/bool-select-frag.wgsl | 4 +- tests/out/wgsl/clamp-splat-vert.wgsl | 2 +- tests/out/wgsl/constant-array-size-frag.wgsl | 2 +- tests/out/wgsl/constructors.wgsl | 6 +- tests/out/wgsl/declarations-frag.wgsl | 2 +- tests/out/wgsl/expressions-frag.wgsl | 86 ++++----- tests/out/wgsl/extra.wgsl | 2 +- tests/out/wgsl/fma-frag.wgsl | 2 +- tests/out/wgsl/fragment-output.wgsl | 18 +- tests/out/wgsl/functions.wgsl | 10 +- tests/out/wgsl/globals.wgsl | 2 +- tests/out/wgsl/image.wgsl | 20 +- tests/out/wgsl/images-frag.wgsl | 12 +- tests/out/wgsl/interface.wgsl | 2 +- tests/out/wgsl/long-form-matrix-frag.wgsl | 24 +-- tests/out/wgsl/math-functions-frag.wgsl | 8 +- tests/out/wgsl/math-functions.wgsl | 26 +-- tests/out/wgsl/module-scope.wgsl | 2 +- tests/out/wgsl/operators.wgsl | 178 +++++++++--------- tests/out/wgsl/padding.wgsl | 2 +- tests/out/wgsl/prepostfix-frag.wgsl | 10 +- tests/out/wgsl/samplers-frag.wgsl | 92 ++++----- tests/out/wgsl/type-alias.wgsl | 6 +- 33 files changed, 327 insertions(+), 337 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index da39cd94f..3a0424e7b 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1132,6 +1132,12 @@ impl Writer { } write!(self.out, ")")? } + Expression::Splat { size, value } => { + let size = back::vector_size_str(size); + write!(self.out, "vec{size}(")?; + write_expression(self, value)?; + write!(self.out, ")")?; + } _ => unreachable!(), } @@ -1173,7 +1179,8 @@ impl Writer { Expression::Literal(_) | Expression::Constant(_) | Expression::ZeroValue(_) - | Expression::Compose { .. } => { + | Expression::Compose { .. } + | Expression::Splat { .. } => { self.write_possibly_const_expression( module, expr, @@ -1450,23 +1457,6 @@ impl Writer { self.write_expr(module, expr, func_ctx)?; write!(self.out, ")")?; } - Expression::Splat { size, value } => { - let inner = func_ctx.resolve_type(value, &module.types); - let (scalar_kind, scalar_width) = match *inner { - crate::TypeInner::Scalar { kind, width } => (kind, width), - _ => { - return Err(Error::Unimplemented(format!( - "write_expr expression::splat {inner:?}" - ))); - } - }; - let scalar = scalar_kind_str(scalar_kind, scalar_width); - let size = back::vector_size_str(size); - - write!(self.out, "vec{size}<{scalar}>(")?; - self.write_expr(module, value, func_ctx)?; - write!(self.out, ")")?; - } Expression::Load { pointer } => { let is_atomic_pointer = func_ctx .resolve_type(pointer, &module.types) diff --git a/tests/out/wgsl/900-implicit-conversions-frag.wgsl b/tests/out/wgsl/900-implicit-conversions-frag.wgsl index 923e38722..58ed87e1e 100644 --- a/tests/out/wgsl/900-implicit-conversions-frag.wgsl +++ b/tests/out/wgsl/900-implicit-conversions-frag.wgsl @@ -57,7 +57,7 @@ fn implicit_dims_3(v_6: vec4) { fn main_1() { exact_1(1); implicit(f32(1u)); - implicit_dims_2(vec3(vec3(1))); + implicit_dims_2(vec3(vec3(1))); return; } diff --git a/tests/out/wgsl/901-lhs-field-select-frag.wgsl b/tests/out/wgsl/901-lhs-field-select-frag.wgsl index 196f21d79..71b987051 100644 --- a/tests/out/wgsl/901-lhs-field-select-frag.wgsl +++ b/tests/out/wgsl/901-lhs-field-select-frag.wgsl @@ -1,7 +1,7 @@ fn main_1() { var a: vec4; - a = vec4(1.0); + a = vec4(1.0); a.x = 2.0; return; } diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index 77ebe1ee1..ea64e80db 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -55,13 +55,13 @@ fn test_matrix_within_struct_accesses() { let _e41 = idx; let _e43 = idx; let l6_ = baz.m[_e41][_e43]; - t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); + t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); let _e56 = idx; idx = (_e56 + 1); - t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); - t.m[0] = vec2(9.0); + t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); + t.m[0] = vec2(9.0); let _e72 = idx; - t.m[_e72] = vec2(90.0); + t.m[_e72] = vec2(90.0); t.m[0][1] = 10.0; let _e85 = idx; t.m[0][_e85] = 20.0; @@ -97,10 +97,10 @@ fn test_matrix_within_array_within_struct_accesses() { let _e67 = idx_1; idx_1 = (_e67 + 1); t_1.am = array, 2>(); - t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); - t_1.am[0][0] = vec2(9.0); + t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); + t_1.am[0][0] = vec2(9.0); let _e93 = idx_1; - t_1.am[0][_e93] = vec2(90.0); + t_1.am[0][_e93] = vec2(90.0); t_1.am[0][0][1] = 10.0; let _e110 = idx_1; t_1.am[0][0][_e110] = 20.0; @@ -127,7 +127,7 @@ fn assign_through_ptr_fn(p: ptr) { } fn assign_array_through_ptr_fn(foo_2: ptr, 2>>) { - (*foo_2) = array, 2>(vec4(1.0), vec4(2.0)); + (*foo_2) = array, 2>(vec4(1.0), vec4(2.0)); return; } @@ -152,24 +152,24 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { c2_[(vi + 1u)] = 42; let value = c2_[vi]; let _e48 = test_arr_as_arg(array, 5>()); - return vec4((_matrix * vec4(vec4(value))), 2.0); + return vec4((_matrix * vec4(vec4(value))), 2.0); } @fragment fn foo_frag() -> @location(0) vec4 { bar._matrix[1][2] = 1.0; - bar._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); - bar.arr = array, 2>(vec2(0u), vec2(1u)); + bar._matrix = mat4x3(vec3(0.0), vec3(1.0), vec3(2.0), vec3(3.0)); + bar.arr = array, 2>(vec2(0u), vec2(1u)); bar.data[1].value = 1; qux = vec2(); - return vec4(0.0); + return vec4(0.0); } @compute @workgroup_size(1, 1, 1) fn assign_through_ptr() { var arr: array, 2>; - arr = array, 2>(vec4(6.0), vec4(7.0)); + arr = array, 2>(vec4(6.0), vec4(7.0)); assign_through_ptr_fn((&val)); assign_array_through_ptr_fn((&arr)); return; diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl index 249298dcc..85bbafd04 100644 --- a/tests/out/wgsl/bevy-pbr-frag.wgsl +++ b/tests/out/wgsl/bevy-pbr-frag.wgsl @@ -218,7 +218,7 @@ fn F_Schlick(f0_: vec3, f90_: f32, VoH: f32) -> vec3 { let _e49 = VoH_1; let _e52 = VoH_1; let _e54 = pow5_((1.0 - _e52)); - return (f0_ + ((vec3(_e45) - f0_) * _e54)); + return (f0_ + ((vec3(_e45) - f0_) * _e54)); } fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 { @@ -247,7 +247,7 @@ fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { LoH_1 = LoH; let _e49 = f0_4; let _e62 = f0_4; - f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33))), 0.0, 1.0); + f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33))), 0.0, 1.0); let _e75 = f0_4; let _e76 = f90_4; let _e77 = LoH_1; @@ -342,7 +342,7 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 let _e62 = perceptual_roughness_1; let _e64 = c0_; let _e66 = c1_; - r = ((vec4(_e62) * _e64) + _e66); + r = ((vec4(_e62) * _e64) + _e66); let _e69 = r; let _e71 = r; let _e76 = NoV_7; @@ -356,11 +356,11 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 a004_ = ((min((_e83.x * _e85.x), exp2((-(9.28) * _e94))) * _e98.x) + _e101.y); let _e109 = a004_; let _e112 = r; - AB = ((vec2(-(1.04), 1.04) * vec2(_e109)) + _e112.zw); + AB = ((vec2(-(1.04), 1.04) * vec2(_e109)) + _e112.zw); let _e116 = f0_8; let _e117 = AB; let _e121 = AB; - return ((_e116 * vec3(_e117.x)) + vec3(_e121.y)); + return ((_e116 * vec3(_e117.x)) + vec3(_e121.y)); } fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 { @@ -381,7 +381,7 @@ fn reinhard(color: vec3) -> vec3 { color_1 = color; let _e42 = color_1; let _e45 = color_1; - return (_e42 / (vec3(1.0) + _e45)); + return (_e42 / (vec3(1.0) + _e45)); } fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { @@ -395,10 +395,10 @@ fn reinhard_extended(color_2: vec3, max_white: f32) -> vec3 { let _e47 = color_3; let _e48 = max_white_1; let _e49 = max_white_1; - numerator = (_e44 * (vec3(1.0) + (_e47 / vec3((_e48 * _e49))))); + numerator = (_e44 * (vec3(1.0) + (_e47 / vec3((_e48 * _e49))))); let _e56 = numerator; let _e59 = color_3; - return (_e56 / (vec3(1.0) + _e59)); + return (_e56 / (vec3(1.0) + _e59)); } fn luminance(v_1: vec3) -> f32 { @@ -788,7 +788,7 @@ fn main_1() { let _e123 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e122); let _e131 = v_Uv_1; let _e132 = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, _e131); - N_2 = (_e120 * normalize(((_e132.xyz * 2.0) - vec3(1.0)))); + N_2 = (_e120 * normalize(((_e132.xyz * 2.0) - vec3(1.0)))); let _e142 = v_Uv_1; let _e143 = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, _e142); occlusion = _e143.x; @@ -817,15 +817,15 @@ fn main_1() { let _e195 = metallic; let _e199 = output_color; let _e201 = metallic; - F0_4 = (vec3((((0.16 * _e190) * _e192) * (1.0 - _e195))) + (_e199.xyz * vec3(_e201))); + F0_4 = (vec3((((0.16 * _e190) * _e192) * (1.0 - _e195))) + (_e199.xyz * vec3(_e201))); let _e206 = output_color; let _e209 = metallic; - diffuseColor_4 = (_e206.xyz * vec3((1.0 - _e209))); + diffuseColor_4 = (_e206.xyz * vec3((1.0 - _e209))); let _e214 = V_3; let _e217 = V_3; let _e219 = N_2; R_4 = reflect(-(_e217), _e219); - light_accum = vec3(0.0); + light_accum = vec3(0.0); i = 0; loop { let _e227 = i; diff --git a/tests/out/wgsl/binding-arrays.wgsl b/tests/out/wgsl/binding-arrays.wgsl index 7f181413b..878fb2c91 100644 --- a/tests/out/wgsl/binding-arrays.wgsl +++ b/tests/out/wgsl/binding-arrays.wgsl @@ -35,11 +35,11 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { let uniform_index = uni.index; let non_uniform_index = fragment_in.index; u1_ = 0u; - u2_ = vec2(0u); + u2_ = vec2(0u); v1_ = 0.0; - v4_ = vec4(0.0); - let uv = vec2(0.0); - let pix = vec2(0); + v4_ = vec4(0.0); + let uv = vec2(0.0); + let pix = vec2(0); let _e22 = textureDimensions(texture_array_unbounded[0]); let _e23 = u2_; u2_ = (_e23 + _e22); @@ -165,8 +165,8 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { textureStore(texture_array_storage[non_uniform_index], pix, _e313); let _e314 = u2_; let _e315 = u1_; - let v2_ = vec2((_e314 + vec2(_e315))); + let v2_ = vec2((_e314 + vec2(_e315))); let _e319 = v4_; let _e326 = v1_; - return ((_e319 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e326)); + return ((_e319 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e326)); } diff --git a/tests/out/wgsl/bitcast.wgsl b/tests/out/wgsl/bitcast.wgsl index 298c5fc21..a8699e0a9 100644 --- a/tests/out/wgsl/bitcast.wgsl +++ b/tests/out/wgsl/bitcast.wgsl @@ -10,15 +10,15 @@ fn main() { var f3_: vec3; var f4_: vec4; - i2_ = vec2(0); - i3_ = vec3(0); - i4_ = vec4(0); - u2_ = vec2(0u); - u3_ = vec3(0u); - u4_ = vec4(0u); - f2_ = vec2(0.0); - f3_ = vec3(0.0); - f4_ = vec4(0.0); + i2_ = vec2(0); + i3_ = vec3(0); + i4_ = vec4(0); + u2_ = vec2(0u); + u3_ = vec3(0u); + u4_ = vec4(0u); + f2_ = vec2(0.0); + f3_ = vec3(0.0); + f4_ = vec4(0.0); let _e27 = i2_; u2_ = bitcast>(_e27); let _e29 = i3_; diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index c203ac94d..4458a0740 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -12,15 +12,15 @@ fn main() { var f4_: vec4; i = 0; - i2_ = vec2(0); - i3_ = vec3(0); - i4_ = vec4(0); + i2_ = vec2(0); + i3_ = vec3(0); + i4_ = vec4(0); u = 0u; - u2_ = vec2(0u); - u3_ = vec3(0u); - u4_ = vec4(0u); - f2_ = vec2(0.0); - f4_ = vec4(0.0); + u2_ = vec2(0u); + u3_ = vec3(0u); + u4_ = vec4(0u); + f2_ = vec2(0.0); + f4_ = vec4(0.0); let _e28 = f4_; u = pack4x8snorm(_e28); let _e30 = f4_; diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl index 6e63fe662..d81c3319d 100644 --- a/tests/out/wgsl/bits_glsl-frag.wgsl +++ b/tests/out/wgsl/bits_glsl-frag.wgsl @@ -11,15 +11,15 @@ fn main_1() { var f4_: vec4; i = 0; - i2_ = vec2(0); - i3_ = vec3(0); - i4_ = vec4(0); + i2_ = vec2(0); + i3_ = vec3(0); + i4_ = vec4(0); u = u32(0); - u2_ = vec2(u32(0)); - u3_ = vec3(u32(0)); - u4_ = vec4(u32(0)); - f2_ = vec2(0.0); - f4_ = vec4(0.0); + u2_ = vec2(u32(0)); + u3_ = vec3(u32(0)); + u4_ = vec4(u32(0)); + f2_ = vec2(0.0); + f4_ = vec4(0.0); let _e33 = f4_; u = pack4x8snorm(_e33); let _e36 = f4_; diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index 26502a9e6..af5d5247d 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -107,13 +107,13 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { let _e97 = cMass; let _e98 = cMassCount; let _e102 = vPos; - cMass = ((_e97 / vec2(f32(_e98))) - _e102); + cMass = ((_e97 / vec2(f32(_e98))) - _e102); } let _e104 = cVelCount; if (_e104 > 0) { let _e107 = cVel; let _e108 = cVelCount; - cVel = (_e107 / vec2(f32(_e108))); + cVel = (_e107 / vec2(f32(_e108))); } let _e112 = vVel; let _e113 = cMass; diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl index 4f0e218ee..f34c54243 100644 --- a/tests/out/wgsl/bool-select-frag.wgsl +++ b/tests/out/wgsl/bool-select-frag.wgsl @@ -23,12 +23,12 @@ fn TevPerCompGT_1(a_2: vec3, b_2: vec3) -> vec3 { b_3 = b_2; let _e7 = a_3; let _e8 = b_3; - return select(vec3(0.0), vec3(1.0), (_e7 > _e8)); + return select(vec3(0.0), vec3(1.0), (_e7 > _e8)); } fn main_1() { let _e1 = o_color; - let _e11 = TevPerCompGT_1(vec3(3.0), vec3(5.0)); + let _e11 = TevPerCompGT_1(vec3(3.0), vec3(5.0)); o_color.x = _e11.x; o_color.y = _e11.y; o_color.z = _e11.z; diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl index deeea02ef..6b5fe96de 100644 --- a/tests/out/wgsl/clamp-splat-vert.wgsl +++ b/tests/out/wgsl/clamp-splat-vert.wgsl @@ -7,7 +7,7 @@ var gl_Position: vec4; fn main_1() { let _e5 = a_pos_1; - let _e10 = clamp(_e5, vec2(0.0), vec2(1.0)); + let _e10 = clamp(_e5, vec2(0.0), vec2(1.0)); gl_Position = vec4(_e10.x, _e10.y, 0.0, 1.0); return; } diff --git a/tests/out/wgsl/constant-array-size-frag.wgsl b/tests/out/wgsl/constant-array-size-frag.wgsl index fb706acf2..1aff03c79 100644 --- a/tests/out/wgsl/constant-array-size-frag.wgsl +++ b/tests/out/wgsl/constant-array-size-frag.wgsl @@ -11,7 +11,7 @@ fn function() -> vec4 { var sum: vec4; var i: i32; - sum = vec4(f32(0)); + sum = vec4(f32(0)); i = 0; loop { let _e9 = i; diff --git a/tests/out/wgsl/constructors.wgsl b/tests/out/wgsl/constructors.wgsl index 7818e4c39..6ed0e5090 100644 --- a/tests/out/wgsl/constructors.wgsl +++ b/tests/out/wgsl/constructors.wgsl @@ -20,11 +20,11 @@ const cp3_: array = array(0, 1, 2, 3); fn main() { var foo: Foo; - foo = Foo(vec4(1.0), 1); + foo = Foo(vec4(1.0), 1); let m0_ = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); let m1_ = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - let cit0_ = vec2(0u); - let cit1_ = mat2x2(vec2(0.0), vec2(0.0)); + let cit0_ = vec2(0u); + let cit1_ = mat2x2(vec2(0.0), vec2(0.0)); let cit2_ = array(0, 1, 2, 3); let ic0_ = bool(bool()); let ic1_ = i32(i32()); diff --git a/tests/out/wgsl/declarations-frag.wgsl b/tests/out/wgsl/declarations-frag.wgsl index 23c697a00..172029689 100644 --- a/tests/out/wgsl/declarations-frag.wgsl +++ b/tests/out/wgsl/declarations-frag.wgsl @@ -52,7 +52,7 @@ fn main_1() { a_1 = _e41; let _e57 = array_toomanyd[0][0][0][0][0][0][0]; b = _e57; - out_array[0] = vec4(2.0); + out_array[0] = vec4(2.0); return; } diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl index e8e1a9f98..d947a0df7 100644 --- a/tests/out/wgsl/expressions-frag.wgsl +++ b/tests/out/wgsl/expressions-frag.wgsl @@ -31,11 +31,11 @@ fn testBinOpVecFloat(a: vec4, b: f32) { let _e5 = a_1; v = (_e5 * 2.0); let _e8 = a_1; - v = (_e8 / vec4(2.0)); + v = (_e8 / vec4(2.0)); let _e12 = a_1; - v = (_e12 + vec4(2.0)); + v = (_e12 + vec4(2.0)); let _e16 = a_1; - v = (_e16 - vec4(2.0)); + v = (_e16 - vec4(2.0)); return; } @@ -51,13 +51,13 @@ fn testBinOpFloatVec(a_2: vec4, b_2: f32) { v_1 = (_e5 * _e6); let _e8 = a_3; let _e9 = b_3; - v_1 = (_e8 / vec4(_e9)); + v_1 = (_e8 / vec4(_e9)); let _e12 = a_3; let _e13 = b_3; - v_1 = (_e12 + vec4(_e13)); + v_1 = (_e12 + vec4(_e13)); let _e16 = a_3; let _e17 = b_3; - v_1 = (_e16 - vec4(_e17)); + v_1 = (_e16 - vec4(_e17)); return; } @@ -73,28 +73,28 @@ fn testBinOpIVecInt(a_4: vec4, b_4: i32) { v_2 = (_e5 * _e6); let _e8 = a_5; let _e9 = b_5; - v_2 = (_e8 / vec4(_e9)); + v_2 = (_e8 / vec4(_e9)); let _e12 = a_5; let _e13 = b_5; - v_2 = (_e12 + vec4(_e13)); + v_2 = (_e12 + vec4(_e13)); let _e16 = a_5; let _e17 = b_5; - v_2 = (_e16 - vec4(_e17)); + v_2 = (_e16 - vec4(_e17)); let _e20 = a_5; let _e21 = b_5; - v_2 = (_e20 & vec4(_e21)); + v_2 = (_e20 & vec4(_e21)); let _e24 = a_5; let _e25 = b_5; - v_2 = (_e24 | vec4(_e25)); + v_2 = (_e24 | vec4(_e25)); let _e28 = a_5; let _e29 = b_5; - v_2 = (_e28 ^ vec4(_e29)); + v_2 = (_e28 ^ vec4(_e29)); let _e32 = a_5; let _e33 = b_5; - v_2 = (_e32 >> vec4(u32(_e33))); + v_2 = (_e32 >> vec4(u32(_e33))); let _e37 = a_5; let _e38 = b_5; - v_2 = (_e37 << vec4(u32(_e38))); + v_2 = (_e37 << vec4(u32(_e38))); return; } @@ -110,19 +110,19 @@ fn testBinOpIntIVec(a_6: i32, b_6: vec4) { v_3 = (_e5 * _e6); let _e8 = a_7; let _e9 = b_7; - v_3 = (vec4(_e8) + _e9); + v_3 = (vec4(_e8) + _e9); let _e12 = a_7; let _e13 = b_7; - v_3 = (vec4(_e12) - _e13); + v_3 = (vec4(_e12) - _e13); let _e16 = a_7; let _e17 = b_7; - v_3 = (vec4(_e16) & _e17); + v_3 = (vec4(_e16) & _e17); let _e20 = a_7; let _e21 = b_7; - v_3 = (vec4(_e20) | _e21); + v_3 = (vec4(_e20) | _e21); let _e24 = a_7; let _e25 = b_7; - v_3 = (vec4(_e24) ^ _e25); + v_3 = (vec4(_e24) ^ _e25); return; } @@ -138,28 +138,28 @@ fn testBinOpUVecUint(a_8: vec4, b_8: u32) { v_4 = (_e5 * _e6); let _e8 = a_9; let _e9 = b_9; - v_4 = (_e8 / vec4(_e9)); + v_4 = (_e8 / vec4(_e9)); let _e12 = a_9; let _e13 = b_9; - v_4 = (_e12 + vec4(_e13)); + v_4 = (_e12 + vec4(_e13)); let _e16 = a_9; let _e17 = b_9; - v_4 = (_e16 - vec4(_e17)); + v_4 = (_e16 - vec4(_e17)); let _e20 = a_9; let _e21 = b_9; - v_4 = (_e20 & vec4(_e21)); + v_4 = (_e20 & vec4(_e21)); let _e24 = a_9; let _e25 = b_9; - v_4 = (_e24 | vec4(_e25)); + v_4 = (_e24 | vec4(_e25)); let _e28 = a_9; let _e29 = b_9; - v_4 = (_e28 ^ vec4(_e29)); + v_4 = (_e28 ^ vec4(_e29)); let _e32 = a_9; let _e33 = b_9; - v_4 = (_e32 >> vec4(_e33)); + v_4 = (_e32 >> vec4(_e33)); let _e36 = a_9; let _e37 = b_9; - v_4 = (_e36 << vec4(_e37)); + v_4 = (_e36 << vec4(_e37)); return; } @@ -175,19 +175,19 @@ fn testBinOpUintUVec(a_10: u32, b_10: vec4) { v_5 = (_e5 * _e6); let _e8 = a_11; let _e9 = b_11; - v_5 = (vec4(_e8) + _e9); + v_5 = (vec4(_e8) + _e9); let _e12 = a_11; let _e13 = b_11; - v_5 = (vec4(_e12) - _e13); + v_5 = (vec4(_e12) - _e13); let _e16 = a_11; let _e17 = b_11; - v_5 = (vec4(_e16) & _e17); + v_5 = (vec4(_e16) & _e17); let _e20 = a_11; let _e21 = b_11; - v_5 = (vec4(_e20) | _e21); + v_5 = (vec4(_e20) | _e21); let _e24 = a_11; let _e25 = b_11; - v_5 = (vec4(_e24) ^ _e25); + v_5 = (vec4(_e24) ^ _e25); return; } @@ -229,33 +229,33 @@ fn testBinOpMatFloat(a_14: f32, b_14: mat3x3) { b_15 = b_14; let _e5 = a_15; let _e6 = b_15; - let _e7 = vec3(_e5); + let _e7 = vec3(_e5); v_7 = mat3x3((_e7 / _e6[0]), (_e7 / _e6[1]), (_e7 / _e6[2])); let _e15 = a_15; let _e16 = b_15; v_7 = (_e15 * _e16); let _e18 = a_15; let _e19 = b_15; - let _e20 = vec3(_e18); + let _e20 = vec3(_e18); v_7 = mat3x3((_e20 + _e19[0]), (_e20 + _e19[1]), (_e20 + _e19[2])); let _e28 = a_15; let _e29 = b_15; - let _e30 = vec3(_e28); + let _e30 = vec3(_e28); v_7 = mat3x3((_e30 - _e29[0]), (_e30 - _e29[1]), (_e30 - _e29[2])); let _e38 = b_15; let _e39 = a_15; - let _e40 = vec3(_e39); + let _e40 = vec3(_e39); v_7 = mat3x3((_e38[0] / _e40), (_e38[1] / _e40), (_e38[2] / _e40)); let _e48 = b_15; let _e49 = a_15; v_7 = (_e48 * _e49); let _e51 = b_15; let _e52 = a_15; - let _e53 = vec3(_e52); + let _e53 = vec3(_e52); v_7 = mat3x3((_e51[0] + _e53), (_e51[1] + _e53), (_e51[2] + _e53)); let _e61 = b_15; let _e62 = a_15; - let _e63 = vec3(_e62); + let _e63 = vec3(_e62); v_7 = mat3x3((_e61[0] - _e63), (_e61[1] - _e63), (_e61[2] - _e63)); return; } @@ -268,12 +268,12 @@ fn testUnaryOpMat(a_16: mat3x3) { let _e3 = a_17; v_8 = -(_e3); let _e5 = a_17; - let _e7 = vec3(1.0); + let _e7 = vec3(1.0); let _e9 = (_e5 - mat3x3(_e7, _e7, _e7)); a_17 = _e9; v_8 = _e9; let _e10 = a_17; - let _e12 = vec3(1.0); + let _e12 = vec3(1.0); a_17 = (_e10 - mat3x3(_e12, _e12, _e12)); v_8 = _e10; return; @@ -310,7 +310,7 @@ fn testNonImplicitCastVectorCast() { a_18 = u32(1); let _e3 = a_18; - b_16 = vec4(i32(_e3)); + b_16 = vec4(i32(_e3)); return; } @@ -426,7 +426,7 @@ fn testSwizzleWrites(a_27: vec3) { a_28.x = _e21.x; a_28.y = _e21.y; let _e26 = a_28; - let _e30 = (_e26.zy + vec2(1.0)); + let _e30 = (_e26.zy + vec2(1.0)); a_28.z = _e30.x; a_28.y = _e30.y; return; @@ -441,7 +441,7 @@ fn main_1() { let _e8 = local_6; global = _e8; let _e9 = o_color; - let _e12 = vec4(1.0); + let _e12 = vec4(1.0); o_color.x = _e12.x; o_color.y = _e12.y; o_color.z = _e12.z; diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl index 8fc91fa2d..b6cfaea7d 100644 --- a/tests/out/wgsl/extra.wgsl +++ b/tests/out/wgsl/extra.wgsl @@ -16,6 +16,6 @@ fn main(in: FragmentIn) -> @location(0) vec4 { if (in.primitive_index == _e4) { return in.color; } else { - return vec4((vec3(1.0) - in.color.xyz), in.color.w); + return vec4((vec3(1.0) - in.color.xyz), in.color.w); } } diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl index d7c74c224..56677056f 100644 --- a/tests/out/wgsl/fma-frag.wgsl +++ b/tests/out/wgsl/fma-frag.wgsl @@ -33,7 +33,7 @@ fn Fma(d: ptr, m: Mat4x3_, s: f32) { fn main_1() { let _e1 = o_color; - let _e4 = vec4(1.0); + let _e4 = vec4(1.0); o_color.x = _e4.x; o_color.y = _e4.y; o_color.z = _e4.z; diff --git a/tests/out/wgsl/fragment-output.wgsl b/tests/out/wgsl/fragment-output.wgsl index 45cfdc8e8..f478faa70 100644 --- a/tests/out/wgsl/fragment-output.wgsl +++ b/tests/out/wgsl/fragment-output.wgsl @@ -20,12 +20,12 @@ struct FragmentOutputVec2Scalar { fn main_vec4vec3_() -> FragmentOutputVec4Vec3_ { var output: FragmentOutputVec4Vec3_; - output.vec4f = vec4(0.0); - output.vec4i = vec4(0); - output.vec4u = vec4(0u); - output.vec3f = vec3(0.0); - output.vec3i = vec3(0); - output.vec3u = vec3(0u); + output.vec4f = vec4(0.0); + output.vec4i = vec4(0); + output.vec4u = vec4(0u); + output.vec3f = vec3(0.0); + output.vec3i = vec3(0); + output.vec3u = vec3(0u); let _e19 = output; return _e19; } @@ -34,9 +34,9 @@ fn main_vec4vec3_() -> FragmentOutputVec4Vec3_ { fn main_vec2scalar() -> FragmentOutputVec2Scalar { var output_1: FragmentOutputVec2Scalar; - output_1.vec2f = vec2(0.0); - output_1.vec2i = vec2(0); - output_1.vec2u = vec2(0u); + output_1.vec2f = vec2(0.0); + output_1.vec2i = vec2(0); + output_1.vec2u = vec2(0u); output_1.scalarf = 0.0; output_1.scalari = 0; output_1.scalaru = 0u; diff --git a/tests/out/wgsl/functions.wgsl b/tests/out/wgsl/functions.wgsl index 62faf0e06..f48a86446 100644 --- a/tests/out/wgsl/functions.wgsl +++ b/tests/out/wgsl/functions.wgsl @@ -6,13 +6,13 @@ fn test_fma() -> vec2 { } fn test_integer_dot_product() -> i32 { - let a_2_ = vec2(1); - let b_2_ = vec2(1); + let a_2_ = vec2(1); + let b_2_ = vec2(1); let c_2_ = dot(a_2_, b_2_); - let a_3_ = vec3(1u); - let b_3_ = vec3(1u); + let a_3_ = vec3(1u); + let b_3_ = vec3(1u); let c_3_ = dot(a_3_, b_3_); - let c_4_ = dot(vec4(4), vec4(2)); + let c_4_ = dot(vec4(4), vec4(2)); return c_4_; } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index b83b43806..3cd484487 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -29,7 +29,7 @@ fn test_msl_packed_vec3_as_arg(arg: vec3) { fn test_msl_packed_vec3_() { var idx: i32; - alignment.v3_ = vec3(1.0); + alignment.v3_ = vec3(1.0); idx = 1; alignment.v3_.x = 1.0; alignment.v3_.x = 2.0; diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index ddfd0b216..062d37713 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -69,7 +69,7 @@ fn depth_load(@builtin(local_invocation_id) local_id_1: vec3) { let dim_1 = textureDimensions(image_storage_src); let itc_1 = (vec2((dim_1 * local_id_1.xy)) % vec2(10, 20)); let val = textureLoad(image_depth_multisampled_src, itc_1, i32(local_id_1.z)); - textureStore(image_dst, itc_1.x, vec4(u32(val))); + textureStore(image_dst, itc_1.x, vec4(u32(val))); return; } @@ -89,7 +89,7 @@ fn queries() -> @builtin(position) vec4 { let dim_3d_lod = textureDimensions(image_3d, 1); let dim_2s_ms = textureDimensions(image_aa); let sum = ((((((((((dim_1d + dim_2d.y) + dim_2d_lod.y) + dim_2d_array.y) + dim_2d_array_lod.y) + dim_cube.y) + dim_cube_lod.y) + dim_cube_array.y) + dim_cube_array_lod.y) + dim_3d.z) + dim_3d_lod.z); - return vec4(f32(sum)); + return vec4(f32(sum)); } @vertex @@ -103,15 +103,15 @@ fn levels_queries() -> @builtin(position) vec4 { let num_levels_3d = textureNumLevels(image_3d); let num_samples_aa = textureNumSamples(image_aa); let sum_1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array); - return vec4(f32(sum_1)); + return vec4(f32(sum_1)); } @fragment fn texture_sample() -> @location(0) vec4 { var a: vec4; - let tc = vec2(0.5); - let tc3_ = vec3(0.5); + let tc = vec2(0.5); + let tc3_ = vec3(0.5); let _e9 = textureSample(image_1d, sampler_reg, tc.x); let _e10 = a; a = (_e10 + _e9); @@ -186,8 +186,8 @@ fn texture_sample() -> @location(0) vec4 { fn texture_sample_comparison() -> @location(0) f32 { var a_1: f32; - let tc_1 = vec2(0.5); - let tc3_1 = vec3(0.5); + let tc_1 = vec2(0.5); + let tc3_1 = vec3(0.5); let _e8 = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5); let _e9 = a_1; a_1 = (_e9 + _e8); @@ -218,7 +218,7 @@ fn texture_sample_comparison() -> @location(0) f32 { @fragment fn gather() -> @location(0) vec4 { - let tc_2 = vec2(0.5); + let tc_2 = vec2(0.5); let s2d = textureGather(1, image_2d, sampler_reg, tc_2); let s2d_offset = textureGather(3, image_2d, sampler_reg, tc_2, vec2(3, 1)); let s2d_depth = textureGatherCompare(image_2d_depth, sampler_cmp, tc_2, 0.5); @@ -231,8 +231,8 @@ fn gather() -> @location(0) vec4 { @fragment fn depth_no_comparison() -> @location(0) vec4 { - let tc_3 = vec2(0.5); + let tc_3 = vec2(0.5); let s2d_1 = textureSample(image_2d_depth, sampler_reg, tc_3); let s2d_gather = textureGather(image_2d_depth, sampler_reg, tc_3); - return (vec4(s2d_1) + s2d_gather); + return (vec4(s2d_1) + s2d_gather); } diff --git a/tests/out/wgsl/images-frag.wgsl b/tests/out/wgsl/images-frag.wgsl index 2a0f5e749..8b77c3e94 100644 --- a/tests/out/wgsl/images-frag.wgsl +++ b/tests/out/wgsl/images-frag.wgsl @@ -24,7 +24,7 @@ fn testImg1D(coord: i32) { let _e10 = textureDimensions(img1D); size = i32(_e10); let _e17 = coord_1; - textureStore(img1D, _e17, vec4(f32(2))); + textureStore(img1D, _e17, vec4(f32(2))); let _e22 = coord_1; let _e23 = textureLoad(img1D, _e22); c = _e23; @@ -44,7 +44,7 @@ fn testImg1DArray(coord_2: vec2) { let _e20 = textureLoad(img1DArray, _e17.x, _e17.y); c_1 = _e20; let _e26 = coord_3; - textureStore(img1DArray, _e26.x, _e26.y, vec4(f32(2))); + textureStore(img1DArray, _e26.x, _e26.y, vec4(f32(2))); return; } @@ -60,7 +60,7 @@ fn testImg2D(coord_4: vec2) { let _e16 = textureLoad(img2D, _e15); c_2 = _e16; let _e22 = coord_5; - textureStore(img2D, _e22, vec4(f32(2))); + textureStore(img2D, _e22, vec4(f32(2))); return; } @@ -77,7 +77,7 @@ fn testImg2DArray(coord_6: vec3) { let _e22 = textureLoad(img2DArray, _e19.xy, _e19.z); c_3 = _e22; let _e28 = coord_7; - textureStore(img2DArray, _e28.xy, _e28.z, vec4(f32(2))); + textureStore(img2DArray, _e28.xy, _e28.z, vec4(f32(2))); return; } @@ -93,7 +93,7 @@ fn testImg3D(coord_8: vec3) { let _e16 = textureLoad(img3D, _e15); c_4 = _e16; let _e22 = coord_9; - textureStore(img3D, _e22, vec4(f32(2))); + textureStore(img3D, _e22, vec4(f32(2))); return; } @@ -119,7 +119,7 @@ fn testImgWriteOnly(coord_12: vec2) { let _e10 = textureDimensions(img2D); size_6 = vec2(vec2(_e10)); let _e18 = coord_13; - textureStore(imgWriteOnly, _e18, vec4(f32(2))); + textureStore(imgWriteOnly, _e18, vec4(f32(2))); return; } diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index 68fe28cd4..8654c13d9 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -22,7 +22,7 @@ var output: array; @vertex fn vertex(@builtin(vertex_index) vertex_index: u32, @builtin(instance_index) instance_index: u32, @location(10) @interpolate(flat) color: u32) -> VertexOutput { let tmp: u32 = ((vertex_index + instance_index) + color); - return VertexOutput(vec4(1.0), f32(tmp)); + return VertexOutput(vec4(1.0), f32(tmp)); } @fragment diff --git a/tests/out/wgsl/long-form-matrix-frag.wgsl b/tests/out/wgsl/long-form-matrix-frag.wgsl index 4a173b63c..f335452e1 100644 --- a/tests/out/wgsl/long-form-matrix-frag.wgsl +++ b/tests/out/wgsl/long-form-matrix-frag.wgsl @@ -10,26 +10,26 @@ fn main_1() { let _e1 = f32(1); splat = mat2x2(vec2(_e1, 0.0), vec2(0.0, _e1)); - let _e9 = vec2(f32(1)); - let _e12 = vec2(f32(2)); + let _e9 = vec2(f32(1)); + let _e12 = vec2(f32(2)); normal = mat2x2(vec2(_e9.x, _e9.y), vec2(_e12.x, _e12.y)); let _e26 = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); from_matrix = mat2x4(vec4(_e26[0].x, _e26[0].y, _e26[0].z, 0.0), vec4(_e26[1].x, _e26[1].y, _e26[1].z, 0.0)); a = mat2x2(vec2(f32(1), f32(2)), vec2(f32(3), f32(4))); let _e58 = vec2(f32(2), f32(3)); b = mat2x2(vec2(f32(1), _e58.x), vec2(_e58.y, f32(4))); - let _e73 = vec3(f32(1)); - let _e76 = vec3(f32(1)); + let _e73 = vec3(f32(1)); + let _e76 = vec3(f32(1)); c = mat3x3(vec3(f32(1), f32(2), f32(3)), vec3(_e73.x, _e73.y, _e73.z), vec3(_e76.x, _e76.y, _e76.z)); - let _e93 = vec2(f32(2)); - let _e97 = vec3(f32(1)); - let _e100 = vec3(f32(1)); + let _e93 = vec2(f32(2)); + let _e97 = vec3(f32(1)); + let _e100 = vec3(f32(1)); d = mat3x3(vec3(_e93.x, _e93.y, f32(1)), vec3(_e97.x, _e97.y, _e97.z), vec3(_e100.x, _e100.y, _e100.z)); - let _e117 = vec2(f32(2)); - let _e120 = vec4(f32(1)); - let _e123 = vec2(f32(2)); - let _e126 = vec4(f32(1)); - let _e129 = vec4(f32(1)); + let _e117 = vec2(f32(2)); + let _e120 = vec4(f32(1)); + let _e123 = vec2(f32(2)); + let _e126 = vec4(f32(1)); + let _e129 = vec4(f32(1)); e = mat4x4(vec4(_e117.x, _e117.y, _e120.x, _e120.y), vec4(_e120.z, _e120.w, _e123.x, _e123.y), vec4(_e126.x, _e126.y, _e126.z, _e126.w), vec4(_e129.x, _e129.y, _e129.z, _e129.w)); return; } diff --git a/tests/out/wgsl/math-functions-frag.wgsl b/tests/out/wgsl/math-functions-frag.wgsl index 138bdbf24..37e42868a 100644 --- a/tests/out/wgsl/math-functions-frag.wgsl +++ b/tests/out/wgsl/math-functions-frag.wgsl @@ -49,8 +49,8 @@ fn main_1() { var smoothStepVector: vec4; var smoothStepMixed: vec4; - a = vec4(1.0); - b = vec4(2.0); + a = vec4(1.0); + b = vec4(2.0); let _e6 = a; let _e7 = b; let _e8 = a; @@ -163,8 +163,8 @@ fn main_1() { let _e243 = a; deg = degrees(_e243.x); smoothStepScalar = smoothstep(0.0, 1.0, 0.5); - smoothStepVector = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); - smoothStepMixed = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); + smoothStepVector = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); + smoothStepMixed = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); return; } diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl index 0b20291f5..e6742fd31 100644 --- a/tests/out/wgsl/math-functions.wgsl +++ b/tests/out/wgsl/math-functions.wgsl @@ -1,6 +1,6 @@ @fragment fn main() { - let v = vec4(0.0); + let v = vec4(0.0); let a = degrees(1.0); let b = radians(1.0); let c = degrees(v); @@ -8,30 +8,30 @@ fn main() { let e = saturate(v); let g = refract(v, v, 1.0); let sign_a = sign(-1); - let sign_b = sign(vec4(-1)); + let sign_b = sign(vec4(-1)); let sign_c = sign(-1.0); - let sign_d = sign(vec4(-1.0)); + let sign_d = sign(vec4(-1.0)); let const_dot = dot(vec2(), vec2()); let first_leading_bit_abs = firstLeadingBit(abs(0u)); let flb_a = firstLeadingBit(-1); - let flb_b = firstLeadingBit(vec2(-1)); - let flb_c = firstLeadingBit(vec2(1u)); + let flb_b = firstLeadingBit(vec2(-1)); + let flb_c = firstLeadingBit(vec2(1u)); let ftb_a = firstTrailingBit(-1); let ftb_b = firstTrailingBit(1u); - let ftb_c = firstTrailingBit(vec2(-1)); - let ftb_d = firstTrailingBit(vec2(1u)); + let ftb_c = firstTrailingBit(vec2(-1)); + let ftb_d = firstTrailingBit(vec2(1u)); let ctz_a = countTrailingZeros(0u); let ctz_b = countTrailingZeros(0); let ctz_c = countTrailingZeros(4294967295u); let ctz_d = countTrailingZeros(-1); - let ctz_e = countTrailingZeros(vec2(0u)); - let ctz_f = countTrailingZeros(vec2(0)); - let ctz_g = countTrailingZeros(vec2(1u)); - let ctz_h = countTrailingZeros(vec2(1)); + let ctz_e = countTrailingZeros(vec2(0u)); + let ctz_f = countTrailingZeros(vec2(0)); + let ctz_g = countTrailingZeros(vec2(1u)); + let ctz_h = countTrailingZeros(vec2(1)); let clz_a = countLeadingZeros(-1); let clz_b = countLeadingZeros(1u); - let clz_c = countLeadingZeros(vec2(-1)); - let clz_d = countLeadingZeros(vec2(1u)); + let clz_c = countLeadingZeros(vec2(-1)); + let clz_d = countLeadingZeros(vec2(1u)); let lde_a = ldexp(1.0, 2); let lde_b = ldexp(vec2(1.0, 2.0), vec2(3, 4)); let modf_a = modf(1.5); diff --git a/tests/out/wgsl/module-scope.wgsl b/tests/out/wgsl/module-scope.wgsl index 91a13718d..141c28b50 100644 --- a/tests/out/wgsl/module-scope.wgsl +++ b/tests/out/wgsl/module-scope.wgsl @@ -21,6 +21,6 @@ fn call() { statement(); let _e0 = returns(); let vf = f32(Value); - let s = textureSample(Texture, Sampler, vec2(vf)); + let s = textureSample(Texture, Sampler, vec2(vf)); } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 9550bf840..3fb0846bf 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -12,25 +12,25 @@ fn builtins() -> vec4 { let b1_ = bitcast(v_i32_one.x); let b2_ = bitcast>(v_i32_one); let v_i32_zero = vec4(v_f32_zero); - return (((((vec4((vec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); + return (((((vec4((vec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } fn splat() -> vec4 { - let a_2 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); - let b = (vec4(5) % vec4(2)); + let a_2 = (((vec2(1.0) + vec2(2.0)) - vec2(3.0)) / vec2(4.0)); + let b = (vec4(5) % vec4(2)); return (a_2.xyxy + vec4(b)); } fn splat_assignment() -> vec2 { var a: vec2; - a = vec2(2.0); + a = vec2(2.0); let _e4 = a; - a = (_e4 + vec2(1.0)); + a = (_e4 + vec2(1.0)); let _e8 = a; - a = (_e8 - vec2(3.0)); + a = (_e8 - vec2(3.0)); let _e12 = a; - a = (_e12 / vec2(4.0)); + a = (_e12 / vec2(4.0)); let _e15 = a; return _e15; } @@ -42,153 +42,153 @@ fn bool_cast(x: vec3) -> vec3 { fn logical() { let neg0_ = !(true); - let neg1_ = !(vec2(true)); + let neg1_ = !(vec2(true)); let or = (true || false); let and = (true && false); let bitwise_or0_ = (true | false); - let bitwise_or1_ = (vec3(true) | vec3(false)); + let bitwise_or1_ = (vec3(true) | vec3(false)); let bitwise_and0_ = (true & false); - let bitwise_and1_ = (vec4(true) & vec4(false)); + let bitwise_and1_ = (vec4(true) & vec4(false)); } fn arithmetic() { - let neg1_1 = -(vec2(1)); - let neg2_ = -(vec2(1.0)); + let neg1_1 = -(vec2(1)); + let neg2_ = -(vec2(1.0)); let add0_ = (2 + 1); let add1_ = (2u + 1u); let add2_ = (2.0 + 1.0); - let add3_ = (vec2(2) + vec2(1)); - let add4_ = (vec3(2u) + vec3(1u)); - let add5_ = (vec4(2.0) + vec4(1.0)); + let add3_ = (vec2(2) + vec2(1)); + let add4_ = (vec3(2u) + vec3(1u)); + let add5_ = (vec4(2.0) + vec4(1.0)); let sub0_ = (2 - 1); let sub1_ = (2u - 1u); let sub2_ = (2.0 - 1.0); - let sub3_ = (vec2(2) - vec2(1)); - let sub4_ = (vec3(2u) - vec3(1u)); - let sub5_ = (vec4(2.0) - vec4(1.0)); + let sub3_ = (vec2(2) - vec2(1)); + let sub4_ = (vec3(2u) - vec3(1u)); + let sub5_ = (vec4(2.0) - vec4(1.0)); let mul0_ = (2 * 1); let mul1_ = (2u * 1u); let mul2_ = (2.0 * 1.0); - let mul3_ = (vec2(2) * vec2(1)); - let mul4_ = (vec3(2u) * vec3(1u)); - let mul5_ = (vec4(2.0) * vec4(1.0)); + let mul3_ = (vec2(2) * vec2(1)); + let mul4_ = (vec3(2u) * vec3(1u)); + let mul5_ = (vec4(2.0) * vec4(1.0)); let div0_ = (2 / 1); let div1_ = (2u / 1u); let div2_ = (2.0 / 1.0); - let div3_ = (vec2(2) / vec2(1)); - let div4_ = (vec3(2u) / vec3(1u)); - let div5_ = (vec4(2.0) / vec4(1.0)); + let div3_ = (vec2(2) / vec2(1)); + let div4_ = (vec3(2u) / vec3(1u)); + let div5_ = (vec4(2.0) / vec4(1.0)); let rem0_ = (2 % 1); let rem1_ = (2u % 1u); let rem2_ = (2.0 % 1.0); - let rem3_ = (vec2(2) % vec2(1)); - let rem4_ = (vec3(2u) % vec3(1u)); - let rem5_ = (vec4(2.0) % vec4(1.0)); + let rem3_ = (vec2(2) % vec2(1)); + let rem4_ = (vec3(2u) % vec3(1u)); + let rem5_ = (vec4(2.0) % vec4(1.0)); { - let add0_1 = (vec2(2) + vec2(1)); - let add1_1 = (vec2(2) + vec2(1)); - let add2_1 = (vec2(2u) + vec2(1u)); - let add3_1 = (vec2(2u) + vec2(1u)); - let add4_1 = (vec2(2.0) + vec2(1.0)); - let add5_1 = (vec2(2.0) + vec2(1.0)); - let sub0_1 = (vec2(2) - vec2(1)); - let sub1_1 = (vec2(2) - vec2(1)); - let sub2_1 = (vec2(2u) - vec2(1u)); - let sub3_1 = (vec2(2u) - vec2(1u)); - let sub4_1 = (vec2(2.0) - vec2(1.0)); - let sub5_1 = (vec2(2.0) - vec2(1.0)); - let mul0_1 = (vec2(2) * 1); - let mul1_1 = (2 * vec2(1)); - let mul2_1 = (vec2(2u) * 1u); - let mul3_1 = (2u * vec2(1u)); - let mul4_1 = (vec2(2.0) * 1.0); - let mul5_1 = (2.0 * vec2(1.0)); - let div0_1 = (vec2(2) / vec2(1)); - let div1_1 = (vec2(2) / vec2(1)); - let div2_1 = (vec2(2u) / vec2(1u)); - let div3_1 = (vec2(2u) / vec2(1u)); - let div4_1 = (vec2(2.0) / vec2(1.0)); - let div5_1 = (vec2(2.0) / vec2(1.0)); - let rem0_1 = (vec2(2) % vec2(1)); - let rem1_1 = (vec2(2) % vec2(1)); - let rem2_1 = (vec2(2u) % vec2(1u)); - let rem3_1 = (vec2(2u) % vec2(1u)); - let rem4_1 = (vec2(2.0) % vec2(1.0)); - let rem5_1 = (vec2(2.0) % vec2(1.0)); + let add0_1 = (vec2(2) + vec2(1)); + let add1_1 = (vec2(2) + vec2(1)); + let add2_1 = (vec2(2u) + vec2(1u)); + let add3_1 = (vec2(2u) + vec2(1u)); + let add4_1 = (vec2(2.0) + vec2(1.0)); + let add5_1 = (vec2(2.0) + vec2(1.0)); + let sub0_1 = (vec2(2) - vec2(1)); + let sub1_1 = (vec2(2) - vec2(1)); + let sub2_1 = (vec2(2u) - vec2(1u)); + let sub3_1 = (vec2(2u) - vec2(1u)); + let sub4_1 = (vec2(2.0) - vec2(1.0)); + let sub5_1 = (vec2(2.0) - vec2(1.0)); + let mul0_1 = (vec2(2) * 1); + let mul1_1 = (2 * vec2(1)); + let mul2_1 = (vec2(2u) * 1u); + let mul3_1 = (2u * vec2(1u)); + let mul4_1 = (vec2(2.0) * 1.0); + let mul5_1 = (2.0 * vec2(1.0)); + let div0_1 = (vec2(2) / vec2(1)); + let div1_1 = (vec2(2) / vec2(1)); + let div2_1 = (vec2(2u) / vec2(1u)); + let div3_1 = (vec2(2u) / vec2(1u)); + let div4_1 = (vec2(2.0) / vec2(1.0)); + let div5_1 = (vec2(2.0) / vec2(1.0)); + let rem0_1 = (vec2(2) % vec2(1)); + let rem1_1 = (vec2(2) % vec2(1)); + let rem2_1 = (vec2(2u) % vec2(1u)); + let rem3_1 = (vec2(2u) % vec2(1u)); + let rem4_1 = (vec2(2.0) % vec2(1.0)); + let rem5_1 = (vec2(2.0) % vec2(1.0)); } let add = (mat3x3() + mat3x3()); let sub = (mat3x3() - mat3x3()); let mul_scalar0_ = (mat3x3() * 1.0); let mul_scalar1_ = (2.0 * mat3x3()); - let mul_vector0_ = (mat4x3() * vec4(1.0)); - let mul_vector1_ = (vec3(2.0) * mat4x3()); + let mul_vector0_ = (mat4x3() * vec4(1.0)); + let mul_vector1_ = (vec3(2.0) * mat4x3()); let mul = (mat4x3() * mat3x4()); } fn bit() { let flip0_ = ~(1); let flip1_ = ~(1u); - let flip2_ = !(vec2(1)); - let flip3_ = !(vec3(1u)); + let flip2_ = !(vec2(1)); + let flip3_ = !(vec3(1u)); let or0_ = (2 | 1); let or1_ = (2u | 1u); - let or2_ = (vec2(2) | vec2(1)); - let or3_ = (vec3(2u) | vec3(1u)); + let or2_ = (vec2(2) | vec2(1)); + let or3_ = (vec3(2u) | vec3(1u)); let and0_ = (2 & 1); let and1_ = (2u & 1u); - let and2_ = (vec2(2) & vec2(1)); - let and3_ = (vec3(2u) & vec3(1u)); + let and2_ = (vec2(2) & vec2(1)); + let and3_ = (vec3(2u) & vec3(1u)); let xor0_ = (2 ^ 1); let xor1_ = (2u ^ 1u); - let xor2_ = (vec2(2) ^ vec2(1)); - let xor3_ = (vec3(2u) ^ vec3(1u)); + let xor2_ = (vec2(2) ^ vec2(1)); + let xor3_ = (vec3(2u) ^ vec3(1u)); let shl0_ = (2 << 1u); let shl1_ = (2u << 1u); - let shl2_ = (vec2(2) << vec2(1u)); - let shl3_ = (vec3(2u) << vec3(1u)); + let shl2_ = (vec2(2) << vec2(1u)); + let shl3_ = (vec3(2u) << vec3(1u)); let shr0_ = (2 >> 1u); let shr1_ = (2u >> 1u); - let shr2_ = (vec2(2) >> vec2(1u)); - let shr3_ = (vec3(2u) >> vec3(1u)); + let shr2_ = (vec2(2) >> vec2(1u)); + let shr3_ = (vec3(2u) >> vec3(1u)); } fn comparison() { let eq0_ = (2 == 1); let eq1_ = (2u == 1u); let eq2_ = (2.0 == 1.0); - let eq3_ = (vec2(2) == vec2(1)); - let eq4_ = (vec3(2u) == vec3(1u)); - let eq5_ = (vec4(2.0) == vec4(1.0)); + let eq3_ = (vec2(2) == vec2(1)); + let eq4_ = (vec3(2u) == vec3(1u)); + let eq5_ = (vec4(2.0) == vec4(1.0)); let neq0_ = (2 != 1); let neq1_ = (2u != 1u); let neq2_ = (2.0 != 1.0); - let neq3_ = (vec2(2) != vec2(1)); - let neq4_ = (vec3(2u) != vec3(1u)); - let neq5_ = (vec4(2.0) != vec4(1.0)); + let neq3_ = (vec2(2) != vec2(1)); + let neq4_ = (vec3(2u) != vec3(1u)); + let neq5_ = (vec4(2.0) != vec4(1.0)); let lt0_ = (2 < 1); let lt1_ = (2u < 1u); let lt2_ = (2.0 < 1.0); - let lt3_ = (vec2(2) < vec2(1)); - let lt4_ = (vec3(2u) < vec3(1u)); - let lt5_ = (vec4(2.0) < vec4(1.0)); + let lt3_ = (vec2(2) < vec2(1)); + let lt4_ = (vec3(2u) < vec3(1u)); + let lt5_ = (vec4(2.0) < vec4(1.0)); let lte0_ = (2 <= 1); let lte1_ = (2u <= 1u); let lte2_ = (2.0 <= 1.0); - let lte3_ = (vec2(2) <= vec2(1)); - let lte4_ = (vec3(2u) <= vec3(1u)); - let lte5_ = (vec4(2.0) <= vec4(1.0)); + let lte3_ = (vec2(2) <= vec2(1)); + let lte4_ = (vec3(2u) <= vec3(1u)); + let lte5_ = (vec4(2.0) <= vec4(1.0)); let gt0_ = (2 > 1); let gt1_ = (2u > 1u); let gt2_ = (2.0 > 1.0); - let gt3_ = (vec2(2) > vec2(1)); - let gt4_ = (vec3(2u) > vec3(1u)); - let gt5_ = (vec4(2.0) > vec4(1.0)); + let gt3_ = (vec2(2) > vec2(1)); + let gt4_ = (vec3(2u) > vec3(1u)); + let gt5_ = (vec4(2.0) > vec4(1.0)); let gte0_ = (2 >= 1); let gte1_ = (2u >= 1u); let gte2_ = (2.0 >= 1.0); - let gte3_ = (vec2(2) >= vec2(1)); - let gte4_ = (vec3(2u) >= vec3(1u)); - let gte5_ = (vec4(2.0) >= vec4(1.0)); + let gte3_ = (vec2(2) >= vec2(1)); + let gte4_ = (vec3(2u) >= vec3(1u)); + let gte5_ = (vec4(2.0) >= vec4(1.0)); } fn assignment() { diff --git a/tests/out/wgsl/padding.wgsl b/tests/out/wgsl/padding.wgsl index 7f77c3531..9893747ca 100644 --- a/tests/out/wgsl/padding.wgsl +++ b/tests/out/wgsl/padding.wgsl @@ -29,5 +29,5 @@ fn vertex() -> @builtin(position) vec4 { let _e4 = input1_.b; let _e8 = input2_.b; let _e12 = input3_.b; - return (((vec4(1.0) * _e4) * _e8) * _e12); + return (((vec4(1.0) * _e4) * _e8) * _e12); } diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl index 5515f9827..296a8151e 100644 --- a/tests/out/wgsl/prepostfix-frag.wgsl +++ b/tests/out/wgsl/prepostfix-frag.wgsl @@ -14,22 +14,22 @@ fn main_1() { let _e8 = (_e6 - 1); scalar = _e8; scalar_target = _e8; - vec = vec2(u32(1)); + vec = vec2(u32(1)); let _e14 = vec; - vec = (_e14 - vec2(1u)); + vec = (_e14 - vec2(1u)); vec_target = _e14; let _e18 = vec; - let _e21 = (_e18 + vec2(1u)); + let _e21 = (_e18 + vec2(1u)); vec = _e21; vec_target = _e21; let _e24 = f32(1); mat = mat4x3(vec3(_e24, 0.0, 0.0), vec3(0.0, _e24, 0.0), vec3(0.0, 0.0, _e24), vec3(0.0, 0.0, 0.0)); let _e32 = mat; - let _e34 = vec3(1.0); + let _e34 = vec3(1.0); mat = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); mat_target = _e32; let _e37 = mat; - let _e39 = vec3(1.0); + let _e39 = vec3(1.0); let _e41 = (_e37 - mat4x3(_e39, _e39, _e39, _e39)); mat = _e41; mat_target = _e41; diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl index 56d4489d8..96b662652 100644 --- a/tests/out/wgsl/samplers-frag.wgsl +++ b/tests/out/wgsl/samplers-frag.wgsl @@ -71,7 +71,7 @@ fn testTex1D(coord: f32) { let _e82 = coord_1; let _e87 = coord_1; let _e91 = vec4(_e87, 0.0, 0.0, 6.0); - let _e97 = textureSample(tex1D, samp, (_e91.xyz / vec3(_e91.w)).x); + let _e97 = textureSample(tex1D, samp, (_e91.xyz / vec3(_e91.w)).x); c = _e97; let _e98 = coord_1; let _e102 = coord_1; @@ -81,7 +81,7 @@ fn testTex1D(coord: f32) { let _e110 = coord_1; let _e116 = coord_1; let _e120 = vec4(_e116, 0.0, 0.0, 6.0); - let _e127 = textureSampleBias(tex1D, samp, (_e120.xyz / vec3(_e120.w)).x, 2.0); + let _e127 = textureSampleBias(tex1D, samp, (_e120.xyz / vec3(_e120.w)).x, 2.0); c = _e127; let _e128 = coord_1; let _e133 = coord_1; @@ -91,7 +91,7 @@ fn testTex1D(coord: f32) { let _e142 = coord_1; let _e149 = coord_1; let _e153 = vec4(_e149, 0.0, 0.0, 6.0); - let _e161 = textureSampleGrad(tex1D, samp, (_e153.xyz / vec3(_e153.w)).x, 4.0, 4.0); + let _e161 = textureSampleGrad(tex1D, samp, (_e153.xyz / vec3(_e153.w)).x, 4.0, 4.0); c = _e161; let _e162 = coord_1; let _e168 = coord_1; @@ -101,7 +101,7 @@ fn testTex1D(coord: f32) { let _e178 = coord_1; let _e186 = coord_1; let _e190 = vec4(_e186, 0.0, 0.0, 6.0); - let _e199 = textureSampleGrad(tex1D, samp, (_e190.xyz / vec3(_e190.w)).x, 4.0, 4.0, 5); + let _e199 = textureSampleGrad(tex1D, samp, (_e190.xyz / vec3(_e190.w)).x, 4.0, 4.0, 5); c = _e199; let _e200 = coord_1; let _e204 = coord_1; @@ -111,7 +111,7 @@ fn testTex1D(coord: f32) { let _e212 = coord_1; let _e218 = coord_1; let _e222 = vec4(_e218, 0.0, 0.0, 6.0); - let _e229 = textureSampleLevel(tex1D, samp, (_e222.xyz / vec3(_e222.w)).x, 3.0); + let _e229 = textureSampleLevel(tex1D, samp, (_e222.xyz / vec3(_e222.w)).x, 3.0); c = _e229; let _e230 = coord_1; let _e235 = coord_1; @@ -121,7 +121,7 @@ fn testTex1D(coord: f32) { let _e244 = coord_1; let _e251 = coord_1; let _e255 = vec4(_e251, 0.0, 0.0, 6.0); - let _e263 = textureSampleLevel(tex1D, samp, (_e255.xyz / vec3(_e255.w)).x, 3.0, 5); + let _e263 = textureSampleLevel(tex1D, samp, (_e255.xyz / vec3(_e255.w)).x, 3.0, 5); c = _e263; let _e264 = coord_1; let _e268 = coord_1; @@ -131,7 +131,7 @@ fn testTex1D(coord: f32) { let _e276 = coord_1; let _e282 = coord_1; let _e286 = vec4(_e282, 0.0, 0.0, 6.0); - let _e293 = textureSample(tex1D, samp, (_e286.xyz / vec3(_e286.w)).x, 5); + let _e293 = textureSample(tex1D, samp, (_e286.xyz / vec3(_e286.w)).x, 5); c = _e293; let _e294 = coord_1; let _e299 = coord_1; @@ -141,7 +141,7 @@ fn testTex1D(coord: f32) { let _e308 = coord_1; let _e315 = coord_1; let _e319 = vec4(_e315, 0.0, 0.0, 6.0); - let _e327 = textureSampleBias(tex1D, samp, (_e319.xyz / vec3(_e319.w)).x, 2.0, 5); + let _e327 = textureSampleBias(tex1D, samp, (_e319.xyz / vec3(_e319.w)).x, 2.0, 5); c = _e327; let _e328 = coord_1; let _e331 = coord_1; @@ -215,10 +215,10 @@ fn testTex2D(coord_4: vec2) { let _e31 = textureSampleBias(tex2D, samp, _e29, 2.0); c_2 = _e31; let _e37 = coord_5; - let _e42 = textureSampleGrad(tex2D, samp, _e37, vec2(4.0), vec2(4.0)); + let _e42 = textureSampleGrad(tex2D, samp, _e37, vec2(4.0), vec2(4.0)); c_2 = _e42; let _e50 = coord_5; - let _e57 = textureSampleGrad(tex2D, samp, _e50, vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e57 = textureSampleGrad(tex2D, samp, _e50, vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e57; let _e60 = coord_5; let _e62 = textureSampleLevel(tex2D, samp, _e60, 3.0); @@ -235,82 +235,82 @@ fn testTex2D(coord_4: vec2) { let _e88 = coord_5; let _e93 = coord_5; let _e97 = vec3(_e93.x, _e93.y, 6.0); - let _e102 = textureSample(tex2D, samp, (_e97.xy / vec2(_e97.z))); + let _e102 = textureSample(tex2D, samp, (_e97.xy / vec2(_e97.z))); c_2 = _e102; let _e103 = coord_5; let _e109 = coord_5; let _e114 = vec4(_e109.x, _e109.y, 0.0, 6.0); - let _e120 = textureSample(tex2D, samp, (_e114.xyz / vec3(_e114.w)).xy); + let _e120 = textureSample(tex2D, samp, (_e114.xyz / vec3(_e114.w)).xy); c_2 = _e120; let _e121 = coord_5; let _e127 = coord_5; let _e131 = vec3(_e127.x, _e127.y, 6.0); - let _e137 = textureSampleBias(tex2D, samp, (_e131.xy / vec2(_e131.z)), 2.0); + let _e137 = textureSampleBias(tex2D, samp, (_e131.xy / vec2(_e131.z)), 2.0); c_2 = _e137; let _e138 = coord_5; let _e145 = coord_5; let _e150 = vec4(_e145.x, _e145.y, 0.0, 6.0); - let _e157 = textureSampleBias(tex2D, samp, (_e150.xyz / vec3(_e150.w)).xy, 2.0); + let _e157 = textureSampleBias(tex2D, samp, (_e150.xyz / vec3(_e150.w)).xy, 2.0); c_2 = _e157; let _e158 = coord_5; let _e167 = coord_5; let _e171 = vec3(_e167.x, _e167.y, 6.0); - let _e180 = textureSampleGrad(tex2D, samp, (_e171.xy / vec2(_e171.z)), vec2(4.0), vec2(4.0)); + let _e180 = textureSampleGrad(tex2D, samp, (_e171.xy / vec2(_e171.z)), vec2(4.0), vec2(4.0)); c_2 = _e180; let _e181 = coord_5; let _e191 = coord_5; let _e196 = vec4(_e191.x, _e191.y, 0.0, 6.0); - let _e206 = textureSampleGrad(tex2D, samp, (_e196.xyz / vec3(_e196.w)).xy, vec2(4.0), vec2(4.0)); + let _e206 = textureSampleGrad(tex2D, samp, (_e196.xyz / vec3(_e196.w)).xy, vec2(4.0), vec2(4.0)); c_2 = _e206; let _e207 = coord_5; let _e218 = coord_5; let _e222 = vec3(_e218.x, _e218.y, 6.0); - let _e233 = textureSampleGrad(tex2D, samp, (_e222.xy / vec2(_e222.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e233 = textureSampleGrad(tex2D, samp, (_e222.xy / vec2(_e222.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e233; let _e234 = coord_5; let _e246 = coord_5; let _e251 = vec4(_e246.x, _e246.y, 0.0, 6.0); - let _e263 = textureSampleGrad(tex2D, samp, (_e251.xyz / vec3(_e251.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e263 = textureSampleGrad(tex2D, samp, (_e251.xyz / vec3(_e251.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); c_2 = _e263; let _e264 = coord_5; let _e270 = coord_5; let _e274 = vec3(_e270.x, _e270.y, 6.0); - let _e280 = textureSampleLevel(tex2D, samp, (_e274.xy / vec2(_e274.z)), 3.0); + let _e280 = textureSampleLevel(tex2D, samp, (_e274.xy / vec2(_e274.z)), 3.0); c_2 = _e280; let _e281 = coord_5; let _e288 = coord_5; let _e293 = vec4(_e288.x, _e288.y, 0.0, 6.0); - let _e300 = textureSampleLevel(tex2D, samp, (_e293.xyz / vec3(_e293.w)).xy, 3.0); + let _e300 = textureSampleLevel(tex2D, samp, (_e293.xyz / vec3(_e293.w)).xy, 3.0); c_2 = _e300; let _e301 = coord_5; let _e309 = coord_5; let _e313 = vec3(_e309.x, _e309.y, 6.0); - let _e321 = textureSampleLevel(tex2D, samp, (_e313.xy / vec2(_e313.z)), 3.0, vec2(5, 5)); + let _e321 = textureSampleLevel(tex2D, samp, (_e313.xy / vec2(_e313.z)), 3.0, vec2(5, 5)); c_2 = _e321; let _e322 = coord_5; let _e331 = coord_5; let _e336 = vec4(_e331.x, _e331.y, 0.0, 6.0); - let _e345 = textureSampleLevel(tex2D, samp, (_e336.xyz / vec3(_e336.w)).xy, 3.0, vec2(5, 5)); + let _e345 = textureSampleLevel(tex2D, samp, (_e336.xyz / vec3(_e336.w)).xy, 3.0, vec2(5, 5)); c_2 = _e345; let _e346 = coord_5; let _e353 = coord_5; let _e357 = vec3(_e353.x, _e353.y, 6.0); - let _e364 = textureSample(tex2D, samp, (_e357.xy / vec2(_e357.z)), vec2(5, 5)); + let _e364 = textureSample(tex2D, samp, (_e357.xy / vec2(_e357.z)), vec2(5, 5)); c_2 = _e364; let _e365 = coord_5; let _e373 = coord_5; let _e378 = vec4(_e373.x, _e373.y, 0.0, 6.0); - let _e386 = textureSample(tex2D, samp, (_e378.xyz / vec3(_e378.w)).xy, vec2(5, 5)); + let _e386 = textureSample(tex2D, samp, (_e378.xyz / vec3(_e378.w)).xy, vec2(5, 5)); c_2 = _e386; let _e387 = coord_5; let _e395 = coord_5; let _e399 = vec3(_e395.x, _e395.y, 6.0); - let _e407 = textureSampleBias(tex2D, samp, (_e399.xy / vec2(_e399.z)), 2.0, vec2(5, 5)); + let _e407 = textureSampleBias(tex2D, samp, (_e399.xy / vec2(_e399.z)), 2.0, vec2(5, 5)); c_2 = _e407; let _e408 = coord_5; let _e417 = coord_5; let _e422 = vec4(_e417.x, _e417.y, 0.0, 6.0); - let _e431 = textureSampleBias(tex2D, samp, (_e422.xyz / vec3(_e422.w)).xy, 2.0, vec2(5, 5)); + let _e431 = textureSampleBias(tex2D, samp, (_e422.xyz / vec3(_e422.w)).xy, 2.0, vec2(5, 5)); c_2 = _e431; let _e432 = coord_5; let _e435 = coord_5; @@ -364,37 +364,37 @@ fn testTex2DShadow(coord_6: vec2) { let _e134 = coord_7; let _e140 = coord_7; let _e145 = vec4(_e140.x, _e140.y, 1.0, 6.0); - let _e149 = (_e145.xyz / vec3(_e145.w)); + let _e149 = (_e145.xyz / vec3(_e145.w)); let _e152 = textureSampleCompare(tex2DShadow, sampShadow, _e149.xy, _e149.z); d = _e152; let _e153 = coord_7; let _e163 = coord_7; let _e168 = vec4(_e163.x, _e163.y, 1.0, 6.0); - let _e176 = (_e168.xyz / vec3(_e168.w)); + let _e176 = (_e168.xyz / vec3(_e168.w)); let _e179 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e176.xy, _e176.z); d = _e179; let _e180 = coord_7; let _e192 = coord_7; let _e197 = vec4(_e192.x, _e192.y, 1.0, 6.0); - let _e207 = (_e197.xyz / vec3(_e197.w)); + let _e207 = (_e197.xyz / vec3(_e197.w)); let _e210 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e207.xy, _e207.z, vec2(5, 5)); d = _e210; let _e211 = coord_7; let _e218 = coord_7; let _e223 = vec4(_e218.x, _e218.y, 1.0, 6.0); - let _e228 = (_e223.xyz / vec3(_e223.w)); + let _e228 = (_e223.xyz / vec3(_e223.w)); let _e231 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e228.xy, _e228.z); d = _e231; let _e232 = coord_7; let _e241 = coord_7; let _e246 = vec4(_e241.x, _e241.y, 1.0, 6.0); - let _e253 = (_e246.xyz / vec3(_e246.w)); + let _e253 = (_e246.xyz / vec3(_e246.w)); let _e256 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e253.xy, _e253.z, vec2(5, 5)); d = _e256; let _e257 = coord_7; let _e265 = coord_7; let _e270 = vec4(_e265.x, _e265.y, 1.0, 6.0); - let _e276 = (_e270.xyz / vec3(_e270.w)); + let _e276 = (_e270.xyz / vec3(_e270.w)); let _e279 = textureSampleCompare(tex2DShadow, sampShadow, _e276.xy, _e276.z, vec2(5, 5)); d = _e279; return; @@ -416,10 +416,10 @@ fn testTex2DArray(coord_8: vec3) { let _e41 = textureSampleBias(tex2DArray, samp, _e36.xy, i32(_e36.z), 2.0); c_3 = _e41; let _e47 = coord_9; - let _e55 = textureSampleGrad(tex2DArray, samp, _e47.xy, i32(_e47.z), vec2(4.0), vec2(4.0)); + let _e55 = textureSampleGrad(tex2DArray, samp, _e47.xy, i32(_e47.z), vec2(4.0), vec2(4.0)); c_3 = _e55; let _e63 = coord_9; - let _e73 = textureSampleGrad(tex2DArray, samp, _e63.xy, i32(_e63.z), vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e73 = textureSampleGrad(tex2DArray, samp, _e63.xy, i32(_e63.z), vec2(4.0), vec2(4.0), vec2(5, 5)); c_3 = _e73; let _e76 = coord_9; let _e81 = textureSampleLevel(tex2DArray, samp, _e76.xy, i32(_e76.z), 3.0); @@ -493,7 +493,7 @@ fn testTexCube(coord_12: vec3) { let _e31 = textureSampleBias(texCube, samp, _e29, 2.0); c_4 = _e31; let _e37 = coord_13; - let _e42 = textureSampleGrad(texCube, samp, _e37, vec3(4.0), vec3(4.0)); + let _e42 = textureSampleGrad(texCube, samp, _e37, vec3(4.0), vec3(4.0)); c_4 = _e42; let _e45 = coord_13; let _e47 = textureSampleLevel(texCube, samp, _e45, 3.0); @@ -538,7 +538,7 @@ fn testTexCubeArray(coord_16: vec4) { let _e41 = textureSampleBias(texCubeArray, samp, _e36.xyz, i32(_e36.w), 2.0); c_5 = _e41; let _e47 = coord_17; - let _e55 = textureSampleGrad(texCubeArray, samp, _e47.xyz, i32(_e47.w), vec3(4.0), vec3(4.0)); + let _e55 = textureSampleGrad(texCubeArray, samp, _e47.xyz, i32(_e47.w), vec3(4.0), vec3(4.0)); c_5 = _e55; let _e58 = coord_17; let _e63 = textureSampleLevel(texCubeArray, samp, _e58.xyz, i32(_e58.w), 3.0); @@ -578,48 +578,48 @@ fn testTex3D(coord_20: vec3) { let _e32 = coord_21; let _e38 = coord_21; let _e43 = vec4(_e38.x, _e38.y, _e38.z, 6.0); - let _e48 = textureSample(tex3D, samp, (_e43.xyz / vec3(_e43.w))); + let _e48 = textureSample(tex3D, samp, (_e43.xyz / vec3(_e43.w))); c_6 = _e48; let _e49 = coord_21; let _e56 = coord_21; let _e61 = vec4(_e56.x, _e56.y, _e56.z, 6.0); - let _e67 = textureSampleBias(tex3D, samp, (_e61.xyz / vec3(_e61.w)), 2.0); + let _e67 = textureSampleBias(tex3D, samp, (_e61.xyz / vec3(_e61.w)), 2.0); c_6 = _e67; let _e68 = coord_21; let _e76 = coord_21; let _e81 = vec4(_e76.x, _e76.y, _e76.z, 6.0); - let _e88 = textureSample(tex3D, samp, (_e81.xyz / vec3(_e81.w)), vec3(5, 5, 5)); + let _e88 = textureSample(tex3D, samp, (_e81.xyz / vec3(_e81.w)), vec3(5, 5, 5)); c_6 = _e88; let _e89 = coord_21; let _e98 = coord_21; let _e103 = vec4(_e98.x, _e98.y, _e98.z, 6.0); - let _e111 = textureSampleBias(tex3D, samp, (_e103.xyz / vec3(_e103.w)), 2.0, vec3(5, 5, 5)); + let _e111 = textureSampleBias(tex3D, samp, (_e103.xyz / vec3(_e103.w)), 2.0, vec3(5, 5, 5)); c_6 = _e111; let _e112 = coord_21; let _e119 = coord_21; let _e124 = vec4(_e119.x, _e119.y, _e119.z, 6.0); - let _e130 = textureSampleLevel(tex3D, samp, (_e124.xyz / vec3(_e124.w)), 3.0); + let _e130 = textureSampleLevel(tex3D, samp, (_e124.xyz / vec3(_e124.w)), 3.0); c_6 = _e130; let _e131 = coord_21; let _e140 = coord_21; let _e145 = vec4(_e140.x, _e140.y, _e140.z, 6.0); - let _e153 = textureSampleLevel(tex3D, samp, (_e145.xyz / vec3(_e145.w)), 3.0, vec3(5, 5, 5)); + let _e153 = textureSampleLevel(tex3D, samp, (_e145.xyz / vec3(_e145.w)), 3.0, vec3(5, 5, 5)); c_6 = _e153; let _e154 = coord_21; let _e164 = coord_21; let _e169 = vec4(_e164.x, _e164.y, _e164.z, 6.0); - let _e178 = textureSampleGrad(tex3D, samp, (_e169.xyz / vec3(_e169.w)), vec3(4.0), vec3(4.0)); + let _e178 = textureSampleGrad(tex3D, samp, (_e169.xyz / vec3(_e169.w)), vec3(4.0), vec3(4.0)); c_6 = _e178; let _e179 = coord_21; let _e191 = coord_21; let _e196 = vec4(_e191.x, _e191.y, _e191.z, 6.0); - let _e207 = textureSampleGrad(tex3D, samp, (_e196.xyz / vec3(_e196.w)), vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + let _e207 = textureSampleGrad(tex3D, samp, (_e196.xyz / vec3(_e196.w)), vec3(4.0), vec3(4.0), vec3(5, 5, 5)); c_6 = _e207; let _e213 = coord_21; - let _e218 = textureSampleGrad(tex3D, samp, _e213, vec3(4.0), vec3(4.0)); + let _e218 = textureSampleGrad(tex3D, samp, _e213, vec3(4.0), vec3(4.0)); c_6 = _e218; let _e226 = coord_21; - let _e233 = textureSampleGrad(tex3D, samp, _e226, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + let _e233 = textureSampleGrad(tex3D, samp, _e226, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); c_6 = _e233; let _e236 = coord_21; let _e238 = textureSampleLevel(tex3D, samp, _e236, 3.0); diff --git a/tests/out/wgsl/type-alias.wgsl b/tests/out/wgsl/type-alias.wgsl index b298c2c93..fea2dec10 100644 --- a/tests/out/wgsl/type-alias.wgsl +++ b/tests/out/wgsl/type-alias.wgsl @@ -1,8 +1,8 @@ fn main() { let a = vec3(0.0, 0.0, 0.0); - let c = vec3(0.0); - let b = vec3(vec2(0.0), 0.0); - let d = vec3(vec2(0.0), 0.0); + let c = vec3(0.0); + let b = vec3(vec2(0.0), 0.0); + let d = vec3(vec2(0.0), 0.0); let e = vec3(d); let f = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); let g = mat3x3(a, a, a); From 1281c1156cd3a0bac28faa46125ef842b209d088 Mon Sep 17 00:00:00 2001 From: Theo <127643579+TheoDulka@users.noreply.github.com> Date: Tue, 12 Sep 2023 12:59:31 -0500 Subject: [PATCH 2078/2212] [spv-out] Always give structs with runtime arrays a Block decoration (#2455) --- src/back/spv/writer.rs | 28 +++++++++++++++---- tests/in/runtime-array-in-unused-struct.wgsl | 12 ++++++++ tests/out/spv/access.spvasm | 2 +- tests/out/spv/boids.spvasm | 3 +- tests/out/spv/bounds-check-restrict.spvasm | 2 +- tests/out/spv/bounds-check-zero.spvasm | 2 +- tests/out/spv/collatz.spvasm | 2 +- tests/out/spv/debug-symbol-terrain.spvasm | 4 +-- tests/out/spv/pointers.spvasm | 2 +- .../spv/runtime-array-in-unused-struct.spvasm | 24 ++++++++++++++++ tests/snapshots.rs | 1 + 11 files changed, 67 insertions(+), 15 deletions(-) create mode 100644 tests/in/runtime-array-in-unused-struct.wgsl create mode 100644 tests/out/spv/runtime-array-in-unused-struct.spvasm diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 41a13cbc1..ea10f002f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1016,12 +1016,27 @@ impl Writer { ref members, span: _, } => { + let mut has_runtime_array = false; let mut member_ids = Vec::with_capacity(members.len()); for (index, member) in members.iter().enumerate() { + let member_ty = &arena[member.ty]; + match member_ty.inner { + crate::TypeInner::Array { + base: _, + size: crate::ArraySize::Dynamic, + stride: _, + } => { + has_runtime_array = true; + } + _ => (), + } self.decorate_struct_member(id, index, member, arena)?; let member_id = self.get_type_id(LookupType::Handle(member.ty)); member_ids.push(member_id); } + if has_runtime_array { + self.decorate(id, Decoration::Block, &[]); + } Instruction::type_struct(id, member_ids.as_slice()) } @@ -1656,16 +1671,17 @@ impl Writer { } else { // This is a global variable in the Storage address space. The only // way it could have `global_needs_wrapper() == false` is if it has - // a runtime-sized array. In this case, we need to decorate it with - // Block. + // a runtime-sized or binding array. + // Runtime-sized arrays were decorated when iterating through struct content. + // Now binding arrays require Block decorating. if let crate::AddressSpace::Storage { .. } = global_variable.space { - let decorated_id = match ir_module.types[global_variable.ty].inner { + match ir_module.types[global_variable.ty].inner { crate::TypeInner::BindingArray { base, .. } => { - self.get_type_id(LookupType::Handle(base)) + let decorated_id = self.get_type_id(LookupType::Handle(base)); + self.decorate(decorated_id, Decoration::Block, &[]); } - _ => inner_type_id, + _ => (), }; - self.decorate(decorated_id, Decoration::Block, &[]); } if substitute_inner_type_lookup.is_some() { inner_type_id diff --git a/tests/in/runtime-array-in-unused-struct.wgsl b/tests/in/runtime-array-in-unused-struct.wgsl new file mode 100644 index 000000000..bcee56d9b --- /dev/null +++ b/tests/in/runtime-array-in-unused-struct.wgsl @@ -0,0 +1,12 @@ +struct DataStruct { + data: f32, + data_vec: vec4, +} + +struct Struct { + data: array, +}; + +struct PrimitiveStruct { + data: array, +}; diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index f7be2338c..cb0cdeda2 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -73,6 +73,7 @@ OpMemberDecorate %20 2 Offset 96 OpMemberDecorate %20 3 Offset 100 OpMemberDecorate %20 4 Offset 144 OpMemberDecorate %20 5 Offset 160 +OpDecorate %20 Block OpMemberDecorate %22 0 Offset 0 OpMemberDecorate %22 0 ColMajor OpMemberDecorate %22 0 MatrixStride 8 @@ -86,7 +87,6 @@ OpDecorate %33 ArrayStride 4 OpDecorate %36 ArrayStride 16 OpDecorate %47 DescriptorSet 0 OpDecorate %47 Binding 0 -OpDecorate %20 Block OpDecorate %49 DescriptorSet 0 OpDecorate %49 Binding 1 OpDecorate %50 Block diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index 94ee9e8d9..f57d99723 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -48,6 +48,7 @@ OpMemberDecorate %7 5 Offset 20 OpMemberDecorate %7 6 Offset 24 OpDecorate %8 ArrayStride 16 OpMemberDecorate %9 0 Offset 0 +OpDecorate %9 Block OpDecorate %13 DescriptorSet 0 OpDecorate %13 Binding 0 OpDecorate %14 Block @@ -55,10 +56,8 @@ OpMemberDecorate %14 0 Offset 0 OpDecorate %16 NonWritable OpDecorate %16 DescriptorSet 0 OpDecorate %16 Binding 1 -OpDecorate %9 Block OpDecorate %18 DescriptorSet 0 OpDecorate %18 Binding 2 -OpDecorate %9 Block OpDecorate %36 BuiltIn GlobalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 diff --git a/tests/out/spv/bounds-check-restrict.spvasm b/tests/out/spv/bounds-check-restrict.spvasm index 8b13b4480..69e612022 100644 --- a/tests/out/spv/bounds-check-restrict.spvasm +++ b/tests/out/spv/bounds-check-restrict.spvasm @@ -15,9 +15,9 @@ OpMemberDecorate %10 2 Offset 64 OpMemberDecorate %10 2 ColMajor OpMemberDecorate %10 2 MatrixStride 16 OpMemberDecorate %10 3 Offset 112 +OpDecorate %10 Block OpDecorate %13 DescriptorSet 0 OpDecorate %13 Binding 0 -OpDecorate %10 Block %2 = OpTypeVoid %3 = OpTypeFloat 32 %6 = OpTypeInt 32 0 diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index b3c108d98..f24ab2cc7 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -15,9 +15,9 @@ OpMemberDecorate %10 2 Offset 64 OpMemberDecorate %10 2 ColMajor OpMemberDecorate %10 2 MatrixStride 16 OpMemberDecorate %10 3 Offset 112 +OpDecorate %10 Block OpDecorate %13 DescriptorSet 0 OpDecorate %13 Binding 0 -OpDecorate %10 Block %2 = OpTypeVoid %3 = OpTypeFloat 32 %6 = OpTypeInt 32 0 diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index f8212185c..310bc5c1e 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -19,9 +19,9 @@ OpName %48 "global_id" OpName %51 "main" OpDecorate %4 ArrayStride 4 OpMemberDecorate %5 0 Offset 0 +OpDecorate %5 Block OpDecorate %7 DescriptorSet 0 OpDecorate %7 Binding 0 -OpDecorate %5 Block OpDecorate %48 BuiltIn GlobalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 diff --git a/tests/out/spv/debug-symbol-terrain.spvasm b/tests/out/spv/debug-symbol-terrain.spvasm index fcc14e485..ac83cc123 100644 --- a/tests/out/spv/debug-symbol-terrain.spvasm +++ b/tests/out/spv/debug-symbol-terrain.spvasm @@ -415,8 +415,10 @@ OpMemberDecorate %14 0 Offset 0 OpMemberDecorate %14 1 Offset 16 OpDecorate %15 ArrayStride 32 OpMemberDecorate %16 0 Offset 0 +OpDecorate %16 Block OpDecorate %17 ArrayStride 4 OpMemberDecorate %18 0 Offset 0 +OpDecorate %18 Block OpMemberDecorate %20 0 Offset 0 OpMemberDecorate %20 1 Offset 8 OpMemberDecorate %20 2 Offset 16 @@ -442,10 +444,8 @@ OpDecorate %30 Block OpMemberDecorate %30 0 Offset 0 OpDecorate %32 DescriptorSet 0 OpDecorate %32 Binding 1 -OpDecorate %16 Block OpDecorate %34 DescriptorSet 0 OpDecorate %34 Binding 2 -OpDecorate %18 Block OpDecorate %36 DescriptorSet 0 OpDecorate %36 Binding 0 OpDecorate %37 Block diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index 3debe27b1..332d265fa 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -20,9 +20,9 @@ OpName %35 "v" OpName %36 "index_dynamic_array" OpDecorate %6 ArrayStride 4 OpMemberDecorate %7 0 Offset 0 +OpDecorate %7 Block OpDecorate %10 DescriptorSet 0 OpDecorate %10 Binding 0 -OpDecorate %7 Block %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 2 diff --git a/tests/out/spv/runtime-array-in-unused-struct.spvasm b/tests/out/spv/runtime-array-in-unused-struct.spvasm new file mode 100644 index 000000000..ab3bd3d01 --- /dev/null +++ b/tests/out/spv/runtime-array-in-unused-struct.spvasm @@ -0,0 +1,24 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 10 +OpCapability Shader +OpCapability Linkage +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpMemberDecorate %5 0 Offset 0 +OpMemberDecorate %5 1 Offset 16 +OpDecorate %6 ArrayStride 32 +OpMemberDecorate %7 0 Offset 0 +OpDecorate %7 Block +OpDecorate %8 ArrayStride 4 +OpMemberDecorate %9 0 Offset 0 +OpDecorate %9 Block +%2 = OpTypeVoid +%3 = OpTypeFloat 32 +%4 = OpTypeVector %3 4 +%5 = OpTypeStruct %3 %4 +%6 = OpTypeRuntimeArray %5 +%7 = OpTypeStruct %6 +%8 = OpTypeRuntimeArray %3 +%9 = OpTypeStruct %8 \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1782e8b96..dce0a7edf 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -606,6 +606,7 @@ fn convert_wgsl() { "workgroup-uniform-load", Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL, ), + ("runtime-array-in-unused-struct", Targets::SPIRV), ("sprite", Targets::SPIRV), ("force_point_size_vertex_shader_webgl", Targets::GLSL), ("invariant", Targets::GLSL), From 0ae0446f3a3c184ba462122edd4c89dbd07431b0 Mon Sep 17 00:00:00 2001 From: Elie Michel Date: Wed, 13 Sep 2023 15:23:58 +0200 Subject: [PATCH 2079/2212] [cli] Add support for `.{vert,frag,comp}.glsl` files (#2462) --- cli/src/bin/naga.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index 8f57984f5..8bd73b87f 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -302,7 +302,7 @@ fn run() -> Result<(), Box> { } } } - ext @ ("vert" | "frag" | "comp") => { + ext @ ("vert" | "frag" | "comp" | "glsl") => { let input = String::from_utf8(input)?; let mut parser = naga::front::glsl::Frontend::default(); @@ -314,6 +314,20 @@ fn run() -> Result<(), Box> { "vert" => naga::ShaderStage::Vertex, "frag" => naga::ShaderStage::Fragment, "comp" => naga::ShaderStage::Compute, + "glsl" => { + let internal_name = input_path.to_string_lossy(); + match Path::new(&internal_name[..internal_name.len()-5]) + .extension() + .ok_or(CliError("Input filename ending with .glsl has no internal extension"))? + .to_str() + .ok_or(CliError("Input filename not valid unicode"))? + { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + _ => unreachable!(), + } + }, _ => unreachable!(), }, defines: Default::default(), From 79c5cb2d04cf0432ff87981878f2959eedd37983 Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Wed, 13 Sep 2023 20:44:02 +0700 Subject: [PATCH 2080/2212] spv-out: Remove empty else branch. (#2473) --- src/back/spv/writer.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index ea10f002f..fd39fe2e4 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1636,7 +1636,6 @@ impl Writer { space: global_variable.space, })) } - } else { } }; From d2c29f012ef16c1da8382ca3416f2ebb96bccc8b Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Wed, 13 Sep 2023 20:44:50 +0700 Subject: [PATCH 2081/2212] Remove useless calls to `into_iter()`. (#2474) The `splice()` call takes `IntoIterator`, so calling `into_iter()` is not needed. --- src/block.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/block.rs b/src/block.rs index ba4c95ab3..b375132ef 100644 --- a/src/block.rs +++ b/src/block.rs @@ -75,9 +75,8 @@ impl Block { pub fn splice + Clone>(&mut self, range: R, other: Self) { #[cfg(feature = "span")] - self.span_info - .splice(range.clone(), other.span_info.into_iter()); - self.body.splice(range, other.body.into_iter()); + self.span_info.splice(range.clone(), other.span_info); + self.body.splice(range, other.body); } pub fn span_iter(&self) -> impl Iterator { #[cfg(feature = "span")] From ae9c1f7847da44967241bd34fc501e2e2a1b08fc Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Wed, 13 Sep 2023 20:45:50 +0700 Subject: [PATCH 2082/2212] clippy: Remove extra Iterator bounds. (#2475) `Iterator` is a supertrait of `ExactSizeIterator`, so specifying `ExactSizeIterator` is enough. --- src/front/wgsl/error.rs | 2 +- src/span.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index 7ce795fa0..f7bed6cdf 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -17,7 +17,7 @@ pub struct ParseError { } impl ParseError { - pub fn labels(&self) -> impl Iterator + ExactSizeIterator + '_ { + pub fn labels(&self) -> impl ExactSizeIterator + '_ { self.labels .iter() .map(|&(span, ref msg)| (span, msg.as_ref())) diff --git a/src/span.rs b/src/span.rs index 90bf3d174..0bc97ff46 100644 --- a/src/span.rs +++ b/src/span.rs @@ -181,7 +181,7 @@ impl WithSpan { } /// Iterator over stored [`SpanContext`]s. - pub fn spans(&self) -> impl Iterator + ExactSizeIterator { + pub fn spans(&self) -> impl ExactSizeIterator { #[cfg(feature = "span")] return self.spans.iter(); #[cfg(not(feature = "span"))] From 266634e82222b92a11c403e56f3ed1b85cd1fe5e Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Wed, 13 Sep 2023 21:11:10 +0700 Subject: [PATCH 2083/2212] clippy: Fix unnecessary_mut_passed warning. (#2476) The `ModuleInfo` was not used mutably. --- src/valid/expression.rs | 2 +- src/valid/mod.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 1d1d6c0b9..f9b77b129 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -157,7 +157,7 @@ impl super::Validator { &self, handle: Handle, gctx: crate::proc::GlobalCtx, - mod_info: &mut ModuleInfo, + mod_info: &ModuleInfo, ) -> Result<(), super::ConstExpressionError> { use crate::Expression as E; diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 535128772..f99a2055c 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -400,7 +400,7 @@ impl Validator { #[cfg(feature = "validate")] if self.flags.contains(ValidationFlags::CONSTANTS) { for (handle, _) in module.const_expressions.iter() { - self.validate_const_expression(handle, module.to_ctx(), &mut mod_info) + self.validate_const_expression(handle, module.to_ctx(), &mod_info) .map_err(|source| { ValidationError::ConstExpression { handle, source } .with_span_handle(handle, &module.const_expressions) From df8107b78812cc2b1e3d5de35279cedc1f0da3fb Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 15 Sep 2023 09:10:25 -0700 Subject: [PATCH 2084/2212] Fix documentation comments for `proc::Layouter::update`. (#2478) --- src/proc/layouter.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs index 11b2250e9..4c52e5ec8 100644 --- a/src/proc/layouter.rs +++ b/src/proc/layouter.rs @@ -151,10 +151,10 @@ impl Layouter { self.layouts.clear(); } - /// Extend this `Layouter` with layouts for any new entries in `types`. + /// Extend this `Layouter` with layouts for any new entries in `gctx.types`. /// - /// Ensure that every type in `types` has a corresponding [TypeLayout] in - /// [`self.layouts`]. + /// Ensure that every type in `gctx.types` has a corresponding [TypeLayout] + /// in [`self.layouts`]. /// /// Some front ends need to be able to compute layouts for existing types /// while module construction is still in progress and new types are still From d8b7573b9e19633e6cc5f0dd25221797f56d0ece Mon Sep 17 00:00:00 2001 From: andriyDev Date: Tue, 19 Sep 2023 03:59:32 -0700 Subject: [PATCH 2085/2212] Prevent using multiple push constant variables in one entry point. (#2484) --- src/valid/interface.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 2416e8921..2444d29d9 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -90,6 +90,8 @@ pub enum EntryPointError { ForbiddenStageOperations, #[error("Global variable {0:?} is used incorrectly as {1:?}")] InvalidGlobalUsage(Handle, GlobalUse), + #[error("More than 1 push constant variable is used")] + MoreThanOnePushConstantUsed, #[error("Bindings for {0:?} conflict with other resource")] BindingCollision(Handle), #[error("Argument {0} varying error")] @@ -701,6 +703,23 @@ impl super::Validator { bg.clear(); } + #[cfg(feature = "validate")] + { + let used_push_constants = module + .global_variables + .iter() + .filter(|&(_, var)| var.space == crate::AddressSpace::PushConstant) + .map(|(handle, _)| handle) + .filter(|&handle| !info[handle].is_empty()); + // Check if there is more than one push constant, and error if so. + // Use a loop for when returning multiple errors is supported. + #[allow(clippy::never_loop)] + for handle in used_push_constants.skip(1) { + return Err(EntryPointError::MoreThanOnePushConstantUsed + .with_span_handle(handle, &module.global_variables)); + } + } + #[cfg(feature = "validate")] for (var_handle, var) in module.global_variables.iter() { let usage = info[var_handle]; From 54df410b949b36ef4fecc5a5e3949c77bb849b27 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 19 Sep 2023 22:12:48 -0700 Subject: [PATCH 2086/2212] [wgsl-in] make RuntimeExpressionContext::local_table a shared ref. (#2481) The `front::wgsl::lowerer::RuntimeExpressionContext::local_table` field does not need to be a mutable reference, as expressions never introduce new local bindings. --- src/front/wgsl/lower/mod.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 64ef43cb9..36366d013 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -79,10 +79,17 @@ pub struct StatementContext<'source, 'temp, 'out> { /// `Handle`s we have built for them, owned by `Lowerer::lower`. globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, - /// A map from `ast::Local` handles to the Naga expressions we've built for them. + /// A map from each `ast::Local` handle to the Naga expression + /// we've built for it: /// - /// The Naga expressions are either [`LocalVariable`] or - /// [`FunctionArgument`] expressions. + /// - WGSL function arguments become Naga [`FunctionArgument`] expressions. + /// + /// - WGSL `var` declarations become Naga [`LocalVariable`] expressions. + /// + /// - WGSL `let` declararations become arbitrary Naga expressions. + /// + /// This always borrows the `local_table` local variable in + /// [`Lowerer::function`]. /// /// [`LocalVariable`]: crate::Expression::LocalVariable /// [`FunctionArgument`]: crate::Expression::FunctionArgument @@ -167,7 +174,11 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { } pub struct RuntimeExpressionContext<'temp, 'out> { - local_table: &'temp mut FastHashMap, TypedExpression>, + /// A map from [`ast::Local`] handles to the Naga expressions we've built for them. + /// + /// This is always [`StatementContext::local_table`] for the + /// enclosing statement; see that documentation for details. + local_table: &'temp FastHashMap, TypedExpression>, naga_expressions: &'out mut Arena, local_vars: &'out Arena, From 2a47a15f03a56dafe6dfe44b8d8bf79cbd13214a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Sep 2023 13:04:47 -0700 Subject: [PATCH 2087/2212] cli: Populate dot backend options in Parameters early. This is a step towards having the output loop depend only on `params`, rather than both `params` and `args`. --- cli/src/bin/naga.rs | 11 ++++------- src/back/dot/mod.rs | 2 +- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index 8bd73b87f..3e3d85400 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -161,6 +161,7 @@ struct Parameters<'a> { entry_point: Option, keep_coordinate_space: bool, spv_block_ctx_dump_prefix: Option, + dot: naga::back::dot::Options, spv: naga::back::spv::Options<'a>, msl: naga::back::msl::Options, glsl: naga::back::glsl::Options, @@ -273,6 +274,8 @@ fn run() -> Result<(), Box> { } params.keep_coordinate_space = args.keep_coordinate_space; + params.dot.cfg_only = args.dot_cfg_only; + let (module, input_text) = match Path::new(&input_path) .extension() .ok_or(CliError("Input filename has no extension"))? @@ -519,13 +522,7 @@ fn run() -> Result<(), Box> { "dot" => { use naga::back::dot; - let output = dot::write( - &module, - info.as_ref(), - naga::back::dot::Options { - cfg_only: args.dot_cfg_only, - }, - )?; + let output = dot::write(&module, info.as_ref(), params.dot.clone())?; fs::write(output_path, output)?; } "hlsl" => { diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs index d92fe39e4..1556371df 100644 --- a/src/back/dot/mod.rs +++ b/src/back/dot/mod.rs @@ -18,7 +18,7 @@ use std::{ }; /// Configuration options for the dot backend -#[derive(Default)] +#[derive(Clone, Default)] pub struct Options { /// Only emit function bodies pub cfg_only: bool, From 23860c0e298e9da5ce3cc00bef034dd1644c2757 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Sep 2023 13:31:50 -0700 Subject: [PATCH 2088/2212] cli: Change --generate-debug-symbols from `option` to `switch`. Change `--generate-debug-symbols` from an option that requires a value, "true" or "false", to a switch, whose mere presence enables the feature. --- cli/src/bin/naga.rs | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index 3e3d85400..bfeb00a42 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -76,8 +76,8 @@ struct Args { stdin_file_path: Option, /// generate debug symbols, only works for spv-out for now - #[argh(option, short = 'g')] - generate_debug_symbols: Option, + #[argh(switch, short = 'g')] + generate_debug_symbols: bool, /// show version #[argh(switch)] @@ -448,19 +448,32 @@ fn run() -> Result<(), Box> { params.spv.bounds_check_policies = params.bounds_check_policies; - //Insert Debug infos - params.spv.debug_info = args.generate_debug_symbols.and_then(|debug| { - params.spv.flags.set(spv::WriterFlags::DEBUG, debug); + // Include debugging information if requested. + params.spv.debug_info = if args.generate_debug_symbols { + if let Some(ref input_text) = input_text { + params.spv.flags.set(spv::WriterFlags::DEBUG, true); - if debug { Some(spv::DebugInfo { - source_code: input_text.as_ref()?, - file_name: input_path.file_name().and_then(std::ffi::OsStr::to_str)?, + source_code: input_text, + file_name: input_path + .file_name() + .and_then(std::ffi::OsStr::to_str) + .ok_or(CliError( + "input path for couldn't be converted to string \ + for `--generate-debug-symbols", + ))?, }) } else { + eprintln!( + "warning: `--generate-debug-symbols` was passed, \ + but input is not human-readable: {}", + input_path.display() + ); None } - }); + } else { + None + }; params.spv.flags.set( spv::WriterFlags::ADJUST_COORDINATE_SPACE, From 187aed8e1158ce4df7b7beb60e48e0e5a94af78a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Sep 2023 13:43:06 -0700 Subject: [PATCH 2089/2212] cli: Put a full naga::front::spv::Options in Parameters. This lets us gather up the code that influences SPV input. --- cli/src/bin/naga.rs | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index bfeb00a42..7b799e0d1 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -160,7 +160,7 @@ struct Parameters<'a> { bounds_check_policies: naga::proc::BoundsCheckPolicies, entry_point: Option, keep_coordinate_space: bool, - spv_block_ctx_dump_prefix: Option, + spv_in: naga::front::spv::Options, dot: naga::back::dot::Options, spv: naga::back::spv::Options<'a>, msl: naga::back::msl::Options, @@ -264,7 +264,13 @@ fn run() -> Result<(), Box> { Some(arg) => arg.0, None => params.bounds_check_policies.index, }; - params.spv_block_ctx_dump_prefix = args.block_ctx_dir; + + params.spv_in = naga::front::spv::Options { + adjust_coordinate_space: !args.keep_coordinate_space, + strict_capabilities: false, + block_ctx_dump_prefix: args.block_ctx_dir.map(std::path::PathBuf::from), + }; + params.entry_point = args.entry_point; if let Some(version) = args.profile { params.glsl.version = version.0; @@ -283,16 +289,7 @@ fn run() -> Result<(), Box> { .ok_or(CliError("Input filename not valid unicode"))? { "bin" => (bincode::deserialize(&input)?, None), - "spv" => { - let options = naga::front::spv::Options { - adjust_coordinate_space: !params.keep_coordinate_space, - strict_capabilities: false, - block_ctx_dump_prefix: params - .spv_block_ctx_dump_prefix - .map(std::path::PathBuf::from), - }; - naga::front::spv::parse_u8_slice(&input, &options).map(|m| (m, None))? - } + "spv" => naga::front::spv::parse_u8_slice(&input, ¶ms.spv_in).map(|m| (m, None))?, "wgsl" => { let input = String::from_utf8(input)?; let result = naga::front::wgsl::parse_str(&input); From 55a2ee445c7553ef4fa3bb11fdc762704391a341 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Sep 2023 14:10:30 -0700 Subject: [PATCH 2090/2212] cli: Gather up SPIR-V output options settings. --- cli/src/bin/naga.rs | 70 ++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index 7b799e0d1..42fc97c35 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -161,8 +161,8 @@ struct Parameters<'a> { entry_point: Option, keep_coordinate_space: bool, spv_in: naga::front::spv::Options, + spv_out: naga::back::spv::Options<'a>, dot: naga::back::dot::Options, - spv: naga::back::spv::Options<'a>, msl: naga::back::msl::Options, glsl: naga::back::glsl::Options, hlsl: naga::back::hlsl::Options, @@ -282,6 +282,12 @@ fn run() -> Result<(), Box> { params.dot.cfg_only = args.dot_cfg_only; + params.spv_out.bounds_check_policies = params.bounds_check_policies; + params.spv_out.flags.set( + naga::back::spv::WriterFlags::ADJUST_COORDINATE_SPACE, + !params.keep_coordinate_space, + ); + let (module, input_text) = match Path::new(&input_path) .extension() .ok_or(CliError("Input filename has no extension"))? @@ -345,6 +351,32 @@ fn run() -> Result<(), Box> { _ => return Err(CliError("Unknown input file extension").into()), }; + // Include debugging information if requested. + if args.generate_debug_symbols { + if let Some(ref input_text) = input_text { + params + .spv_out + .flags + .set(naga::back::spv::WriterFlags::DEBUG, true); + params.spv_out.debug_info = Some(naga::back::spv::DebugInfo { + source_code: input_text, + file_name: input_path + .file_name() + .and_then(std::ffi::OsStr::to_str) + .ok_or(CliError( + "input path for couldn't be converted to string \ + for `--generate-debug-symbols", + ))?, + }) + } else { + eprintln!( + "warning: `--generate-debug-symbols` was passed, \ + but input is not human-readable: {}", + input_path.display() + ); + } + } + // Decide which capabilities our output formats can support. let validation_caps = output_paths @@ -443,47 +475,13 @@ fn run() -> Result<(), Box> { None => None, }; - params.spv.bounds_check_policies = params.bounds_check_policies; - - // Include debugging information if requested. - params.spv.debug_info = if args.generate_debug_symbols { - if let Some(ref input_text) = input_text { - params.spv.flags.set(spv::WriterFlags::DEBUG, true); - - Some(spv::DebugInfo { - source_code: input_text, - file_name: input_path - .file_name() - .and_then(std::ffi::OsStr::to_str) - .ok_or(CliError( - "input path for couldn't be converted to string \ - for `--generate-debug-symbols", - ))?, - }) - } else { - eprintln!( - "warning: `--generate-debug-symbols` was passed, \ - but input is not human-readable: {}", - input_path.display() - ); - None - } - } else { - None - }; - - params.spv.flags.set( - spv::WriterFlags::ADJUST_COORDINATE_SPACE, - !params.keep_coordinate_space, - ); - let spv = spv::write_vec( &module, info.as_ref().ok_or(CliError( "Generating SPIR-V output requires validation to \ succeed, and it failed in a previous step", ))?, - ¶ms.spv, + ¶ms.spv_out, pipeline_options, ) .unwrap_pretty(); From 0b7afb3943619a827f0fcf1bacd03b0042bf6afb Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 12 Sep 2023 14:15:24 -0700 Subject: [PATCH 2091/2212] cli: Move file output into its own function. --- cli/src/bin/naga.rs | 291 +++++++++++++++++++++++--------------------- 1 file changed, 151 insertions(+), 140 deletions(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index 42fc97c35..7008151bb 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -416,155 +416,166 @@ fn run() -> Result<(), Box> { } for output_path in output_paths { - match Path::new(&output_path) - .extension() - .ok_or(CliError("Output filename has no extension"))? - .to_str() - .ok_or(CliError("Output filename not valid unicode"))? - { - "txt" => { - use std::io::Write; + write_output(&module, &info, ¶ms, output_path)?; + } - let mut file = fs::File::create(output_path)?; - writeln!(file, "{module:#?}")?; - if let Some(ref info) = info { - writeln!(file)?; - writeln!(file, "{info:#?}")?; + Ok(()) +} + +fn write_output( + module: &naga::Module, + info: &Option, + params: &Parameters, + output_path: &str, +) -> Result<(), Box> { + match Path::new(&output_path) + .extension() + .ok_or(CliError("Output filename has no extension"))? + .to_str() + .ok_or(CliError("Output filename not valid unicode"))? + { + "txt" => { + use std::io::Write; + + let mut file = fs::File::create(output_path)?; + writeln!(file, "{module:#?}")?; + if let Some(ref info) = *info { + writeln!(file)?; + writeln!(file, "{info:#?}")?; + } + } + "bin" => { + let file = fs::File::create(output_path)?; + bincode::serialize_into(file, module)?; + } + "metal" => { + use naga::back::msl; + + let mut options = params.msl.clone(); + options.bounds_check_policies = params.bounds_check_policies; + + let pipeline_options = msl::PipelineOptions::default(); + let (msl, _) = msl::write_string( + module, + info.as_ref().ok_or(CliError( + "Generating metal output requires validation to \ + succeed, and it failed in a previous step", + ))?, + &options, + &pipeline_options, + ) + .unwrap_pretty(); + fs::write(output_path, msl)?; + } + "spv" => { + use naga::back::spv; + + let pipeline_options_owned; + let pipeline_options = match params.entry_point { + Some(ref name) => { + let ep_index = module + .entry_points + .iter() + .position(|ep| ep.name == *name) + .expect("Unable to find the entry point"); + pipeline_options_owned = spv::PipelineOptions { + entry_point: name.clone(), + shader_stage: module.entry_points[ep_index].stage, + }; + Some(&pipeline_options_owned) } - } - "bin" => { - let file = fs::File::create(output_path)?; - bincode::serialize_into(file, &module)?; - } - "metal" => { - use naga::back::msl; + None => None, + }; - let mut options = params.msl.clone(); - options.bounds_check_policies = params.bounds_check_policies; + let spv = spv::write_vec( + module, + info.as_ref().ok_or(CliError( + "Generating SPIR-V output requires validation to \ + succeed, and it failed in a previous step", + ))?, + ¶ms.spv_out, + pipeline_options, + ) + .unwrap_pretty(); + let bytes = spv + .iter() + .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { + v.extend_from_slice(&w.to_le_bytes()); + v + }); - let pipeline_options = msl::PipelineOptions::default(); - let (msl, _) = msl::write_string( - &module, + fs::write(output_path, bytes.as_slice())?; + } + stage @ ("vert" | "frag" | "comp") => { + use naga::back::glsl; + + let pipeline_options = glsl::PipelineOptions { + entry_point: match params.entry_point { + Some(ref name) => name.clone(), + None => "main".to_string(), + }, + shader_stage: match stage { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + _ => unreachable!(), + }, + multiview: None, + }; + + let mut buffer = String::new(); + let mut writer = glsl::Writer::new( + &mut buffer, + module, + info.as_ref().ok_or(CliError( + "Generating glsl output requires validation to \ + succeed, and it failed in a previous step", + ))?, + ¶ms.glsl, + &pipeline_options, + params.bounds_check_policies, + ) + .unwrap_pretty(); + writer.write()?; + fs::write(output_path, buffer)?; + } + "dot" => { + use naga::back::dot; + + let output = dot::write(module, info.as_ref(), params.dot.clone())?; + fs::write(output_path, output)?; + } + "hlsl" => { + use naga::back::hlsl; + let mut buffer = String::new(); + let mut writer = hlsl::Writer::new(&mut buffer, ¶ms.hlsl); + writer + .write( + module, info.as_ref().ok_or(CliError( - "Generating metal output requires validation to \ - succeed, and it failed in a previous step", + "Generating hlsl output requires validation to \ + succeed, and it failed in a previous step", ))?, - &options, - &pipeline_options, ) .unwrap_pretty(); - fs::write(output_path, msl)?; - } - "spv" => { - use naga::back::spv; + fs::write(output_path, buffer)?; + } + "wgsl" => { + use naga::back::wgsl; - let pipeline_options_owned; - let pipeline_options = match params.entry_point { - Some(ref name) => { - let ep_index = module - .entry_points - .iter() - .position(|ep| ep.name == *name) - .expect("Unable to find the entry point"); - pipeline_options_owned = spv::PipelineOptions { - entry_point: name.clone(), - shader_stage: module.entry_points[ep_index].stage, - }; - Some(&pipeline_options_owned) - } - None => None, - }; - - let spv = spv::write_vec( - &module, - info.as_ref().ok_or(CliError( - "Generating SPIR-V output requires validation to \ - succeed, and it failed in a previous step", - ))?, - ¶ms.spv_out, - pipeline_options, - ) - .unwrap_pretty(); - let bytes = spv - .iter() - .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { - v.extend_from_slice(&w.to_le_bytes()); - v - }); - - fs::write(output_path, bytes.as_slice())?; - } - stage @ ("vert" | "frag" | "comp") => { - use naga::back::glsl; - - let pipeline_options = glsl::PipelineOptions { - entry_point: match params.entry_point { - Some(ref name) => name.clone(), - None => "main".to_string(), - }, - shader_stage: match stage { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - _ => unreachable!(), - }, - multiview: None, - }; - - let mut buffer = String::new(); - let mut writer = glsl::Writer::new( - &mut buffer, - &module, - info.as_ref().ok_or(CliError( - "Generating glsl output requires validation to \ - succeed, and it failed in a previous step", - ))?, - ¶ms.glsl, - &pipeline_options, - params.bounds_check_policies, - ) - .unwrap_pretty(); - writer.write()?; - fs::write(output_path, buffer)?; - } - "dot" => { - use naga::back::dot; - - let output = dot::write(&module, info.as_ref(), params.dot.clone())?; - fs::write(output_path, output)?; - } - "hlsl" => { - use naga::back::hlsl; - let mut buffer = String::new(); - let mut writer = hlsl::Writer::new(&mut buffer, ¶ms.hlsl); - writer - .write( - &module, - info.as_ref().ok_or(CliError( - "Generating hlsl output requires validation to \ - succeed, and it failed in a previous step", - ))?, - ) - .unwrap_pretty(); - fs::write(output_path, buffer)?; - } - "wgsl" => { - use naga::back::wgsl; - - let wgsl = wgsl::write_string( - &module, - info.as_ref().ok_or(CliError( - "Generating wgsl output requires validation to \ - succeed, and it failed in a previous step", - ))?, - wgsl::WriterFlags::empty(), - ) - .unwrap_pretty(); - fs::write(output_path, wgsl)?; - } - other => { - println!("Unknown output extension: {other}"); - } + let wgsl = wgsl::write_string( + module, + info.as_ref().ok_or(CliError( + "Generating wgsl output requires validation to \ + succeed, and it failed in a previous step", + ))?, + wgsl::WriterFlags::empty(), + ) + .unwrap_pretty(); + fs::write(output_path, wgsl)?; + } + other => { + println!("Unknown output extension: {other}"); } } From 8b267218a498ea2f4873528a3798799bc3e011bd Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 7 Sep 2023 13:22:44 -0700 Subject: [PATCH 2092/2212] Implement module compaction. Add a new Naga feature, `"compact"`, which adds a new function `naga::compact::compact`, which removes unused expressions, types, and constants from a `Module`. --- Cargo.toml | 1 + cli/Cargo.toml | 21 +- cli/src/bin/naga.rs | 58 +- src/arena.rs | 70 + src/compact/expressions.rs | 395 +++ src/compact/functions.rs | 134 + src/compact/handle_set_map.rs | 125 + src/compact/mod.rs | 286 +++ src/compact/statements.rs | 302 +++ src/compact/types.rs | 93 + src/lib.rs | 2 + tests/out/analysis/access.info.ron | 1330 +++------- tests/out/analysis/shadow.info.ron | 946 ++----- tests/out/glsl/access.foo_vert.Vertex.glsl | 82 +- tests/out/glsl/atomicOps.cs_main.Compute.glsl | 128 +- tests/out/glsl/do-while.main.Fragment.glsl | 4 +- tests/out/glsl/globals.main.Compute.glsl | 32 +- tests/out/glsl/operators.main.Compute.glsl | 8 +- tests/out/glsl/quad-vert.main.Vertex.glsl | 12 +- tests/out/hlsl/access.hlsl | 82 +- tests/out/hlsl/atomicOps.hlsl | 128 +- tests/out/hlsl/binding-arrays.hlsl | 206 +- tests/out/hlsl/do-while.hlsl | 4 +- tests/out/hlsl/empty-global-name.hlsl | 4 +- tests/out/hlsl/globals.hlsl | 32 +- tests/out/hlsl/operators.hlsl | 8 +- tests/out/hlsl/quad-vert.hlsl | 20 +- tests/out/ir/access.compact.ron | 2222 +++++++++++++++++ tests/out/ir/collatz.compact.ron | 334 +++ tests/out/ir/shadow.compact.ron | 1036 ++++++++ tests/out/msl/access.msl | 116 +- tests/out/msl/atomicOps.msl | 128 +- tests/out/msl/binding-arrays.msl | 208 +- tests/out/msl/bounds-check-restrict.msl | 8 +- tests/out/msl/bounds-check-zero.msl | 8 +- tests/out/msl/do-while.msl | 2 +- tests/out/msl/empty-global-name.msl | 4 +- tests/out/msl/globals.msl | 32 +- tests/out/msl/operators.msl | 8 +- tests/out/msl/quad-vert.msl | 20 +- tests/out/spv/access.spvasm | 786 +++--- tests/out/spv/array-in-ctor.spvasm | 42 +- .../spv/array-in-function-return-type.spvasm | 54 +- tests/out/spv/atomicCompareExchange.spvasm | 132 +- tests/out/spv/atomicOps.spvasm | 434 ++-- tests/out/spv/binding-arrays.spvasm | 1011 ++++---- tests/out/spv/binding-buffer-arrays.spvasm | 158 +- tests/out/spv/bounds-check-restrict.spvasm | 369 ++- tests/out/spv/bounds-check-zero.spvasm | 495 ++-- tests/out/spv/constructors.spvasm | 34 +- tests/out/spv/extra.spvasm | 98 +- tests/out/spv/functions.spvasm | 112 +- tests/out/spv/globals.spvasm | 421 ++-- tests/out/spv/image.spvasm | 1036 ++++---- tests/out/spv/interface.compute.spvasm | 106 +- tests/out/spv/interface.fragment.spvasm | 114 +- tests/out/spv/interface.vertex.spvasm | 70 +- .../spv/interface.vertex_two_structs.spvasm | 74 +- tests/out/spv/operators.spvasm | 530 ++-- tests/out/spv/padding.spvasm | 114 +- tests/out/spv/pointers.spvasm | 74 +- tests/out/spv/policy-mix.spvasm | 221 +- .../spv/runtime-array-in-unused-struct.spvasm | 19 +- tests/out/spv/shadow.spvasm | 701 +++--- tests/out/spv/workgroup-var-init.spvasm | 100 +- tests/out/wgsl/access.wgsl | 82 +- tests/out/wgsl/atomicOps.wgsl | 128 +- tests/out/wgsl/binding-arrays.dynamic.wgsl | 4 +- tests/out/wgsl/binding-arrays.static.wgsl | 4 +- tests/out/wgsl/binding-arrays.wgsl | 224 +- tests/out/wgsl/binding-buffer-arrays.wgsl | 22 +- tests/out/wgsl/do-while.wgsl | 4 +- tests/out/wgsl/empty-global-name.wgsl | 4 +- tests/out/wgsl/globals.wgsl | 32 +- tests/out/wgsl/operators.wgsl | 8 +- tests/out/wgsl/quad-vert.wgsl | 8 +- tests/snapshots.rs | 40 +- 77 files changed, 10199 insertions(+), 6305 deletions(-) create mode 100644 src/compact/expressions.rs create mode 100644 src/compact/functions.rs create mode 100644 src/compact/handle_set_map.rs create mode 100644 src/compact/mod.rs create mode 100644 src/compact/statements.rs create mode 100644 src/compact/types.rs create mode 100644 tests/out/ir/access.compact.ron create mode 100644 tests/out/ir/collatz.compact.ron create mode 100644 tests/out/ir/shadow.compact.ron diff --git a/Cargo.toml b/Cargo.toml index 1929bda82..0efdd20d1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,7 @@ wgsl-out = [] hlsl-out = [] span = ["codespan-reporting", "termcolor"] validate = [] +compact = [] [[bench]] name = "criterion" diff --git a/cli/Cargo.toml b/cli/Cargo.toml index a159b041f..1a786ee03 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -10,9 +10,28 @@ keywords = ["shader", "SPIR-V", "GLSL", "MSL"] license = "MIT OR Apache-2.0" [dependencies] -naga = { version = "0.13", path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "serialize", "deserialize"] } bincode = "1" log = "0.4" codespan-reporting = "0.11" env_logger = "0.10" argh = "0.1.5" + +[dependencies.naga] +version = "0.13" +path = "../" +features = [ + "validate", + "compact", + "span", + "wgsl-in", + "wgsl-out", + "glsl-in", + "glsl-out", + "spv-in", + "spv-out", + "msl-out", + "hlsl-out", + "dot-out", + "serialize", + "deserialize" +] diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index 7008151bb..3ca7305e4 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -79,6 +79,20 @@ struct Args { #[argh(switch, short = 'g')] generate_debug_symbols: bool, + /// compact the module's IR and revalidate. + /// + /// Output files will reflect the compacted IR. If you want to see the IR as + /// it was before compaction, use the `--before-compaction` option. + #[argh(switch)] + compact: bool, + + /// write the module's IR before compaction to the given file. + /// + /// This implies `--compact`. Like any other output file, the filename + /// extension determines the form in which the module is written. + #[argh(option)] + before_compaction: Option, + /// show version #[argh(switch)] version: bool, @@ -288,7 +302,7 @@ fn run() -> Result<(), Box> { !params.keep_coordinate_space, ); - let (module, input_text) = match Path::new(&input_path) + let (mut module, input_text) = match Path::new(&input_path) .extension() .ok_or(CliError("Input filename has no extension"))? .to_str() @@ -391,12 +405,13 @@ fn run() -> Result<(), Box> { caps & !missing }); - // validate the IR + // Validate the IR before compaction. let info = match naga::valid::Validator::new(params.validation_flags, validation_caps) .validate(&module) { Ok(info) => Some(info), Err(error) => { + // Validation failure is not fatal. Just report the error. if let Some(input) = &input_text { let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); emit_annotated_error(&error, filename.unwrap_or("input"), input); @@ -406,6 +421,45 @@ fn run() -> Result<(), Box> { } }; + // Compact the module, if requested. + let info = if args.compact || args.before_compaction.is_some() { + // Compact only if validation succeeded. Otherwise, compaction may panic. + if info.is_some() { + // Write out the module state before compaction, if requested. + if let Some(ref before_compaction) = args.before_compaction { + write_output(&module, &info, ¶ms, before_compaction)?; + } + + naga::compact::compact(&mut module); + + // Re-validate the IR after compaction. + match naga::valid::Validator::new(params.validation_flags, validation_caps) + .validate(&module) + { + Ok(info) => Some(info), + Err(error) => { + // Validation failure is not fatal. Just report the error. + eprintln!("Error validating compacted module:"); + if let Some(input) = &input_text { + let filename = input_path.file_name().and_then(std::ffi::OsStr::to_str); + emit_annotated_error(&error, filename.unwrap_or("input"), input); + } + print_err(&error); + None + } + } + } else { + eprintln!("Skipping compaction due to validation failure."); + None + } + } else { + info + }; + + // If no output was requested, then report validation results and stop here. + // + // If the user asked for output, don't stop: some output formats (".txt", + // ".dot", ".bin") can be generated even without a `ModuleInfo`. if output_paths.is_empty() { if info.is_some() { println!("Validation successful"); diff --git a/src/arena.rs b/src/arena.rs index 5c2681c83..1499cf177 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -192,12 +192,31 @@ impl Iterator for Range { } impl Range { + /// Return a range enclosing handles `first` through `last`, inclusive. pub fn new_from_bounds(first: Handle, last: Handle) -> Self { Self { inner: (first.index() as u32)..(last.index() as u32 + 1), marker: Default::default(), } } + + /// Return the first and last handles included in `self`. + /// + /// If `self` is an empty range, there are no handles included, so + /// return `None`. + pub fn first_and_last(&self) -> Option<(Handle, Handle)> { + if self.inner.start < self.inner.end { + Some(( + // `Range::new_from_bounds` expects a 1-based, start- and + // end-inclusive range, but `self.inner` is a zero-based, + // end-exclusive range. + Handle::new(Index::new(self.inner.start + 1).unwrap()), + Handle::new(Index::new(self.inner.end).unwrap()), + )) + } else { + None + } + } } /// An arena holding some kind of component (e.g., type, constant, @@ -382,6 +401,19 @@ impl Arena { Ok(()) } } + + #[cfg(feature = "compact")] + pub(crate) fn retain_mut

(&mut self, mut predicate: P) + where + P: FnMut(Handle, &mut T) -> bool, + { + let mut index = 0; + self.data.retain_mut(|elt| { + index += 1; + let handle = Handle::new(Index::new(index).unwrap()); + predicate(handle, elt) + }) + } } #[cfg(feature = "deserialize")] @@ -544,6 +576,44 @@ impl UniqueArena { Span::default() } } + + #[cfg(feature = "compact")] + pub(crate) fn drain_all(&mut self) -> UniqueArenaDrain { + UniqueArenaDrain { + inner_elts: self.set.drain(..), + #[cfg(feature = "span")] + inner_spans: self.span_info.drain(..), + index: Index::new(1).unwrap(), + } + } +} + +#[cfg(feature = "compact")] +pub(crate) struct UniqueArenaDrain<'a, T> { + inner_elts: indexmap::set::Drain<'a, T>, + #[cfg(feature = "span")] + inner_spans: std::vec::Drain<'a, Span>, + index: Index, +} + +#[cfg(feature = "compact")] +impl<'a, T> Iterator for UniqueArenaDrain<'a, T> { + type Item = (Handle, T, Span); + + fn next(&mut self) -> Option { + match self.inner_elts.next() { + Some(elt) => { + let handle = Handle::new(self.index); + self.index = self.index.checked_add(1).unwrap(); + #[cfg(feature = "span")] + let span = self.inner_spans.next().unwrap(); + #[cfg(not(feature = "span"))] + let span = Span::default(); + Some((handle, elt, span)) + } + None => None, + } + } } impl UniqueArena { diff --git a/src/compact/expressions.rs b/src/compact/expressions.rs new file mode 100644 index 000000000..4ccf559c4 --- /dev/null +++ b/src/compact/expressions.rs @@ -0,0 +1,395 @@ +use super::{HandleMap, HandleSet, ModuleMap}; +use crate::arena::{Arena, Handle, UniqueArena}; + +pub struct ExpressionTracer<'tracer> { + pub types: &'tracer UniqueArena, + pub constants: &'tracer Arena, + + /// The arena in which we are currently tracing expressions. + pub expressions: &'tracer Arena, + + /// The used map for `types`. + pub types_used: &'tracer mut HandleSet, + + /// The used map for `constants`. + pub constants_used: &'tracer mut HandleSet, + + /// The used set for `arena`. + /// + /// This points to whatever arena holds the expressions we are + /// currently tracing: either a function's expression arena, or + /// the module's constant expression arena. + pub expressions_used: &'tracer mut HandleSet, + + /// The constant expression arena and its used map, if we haven't + /// switched to tracing constant expressions yet. + pub const_expressions: Option<( + &'tracer Arena, + &'tracer mut HandleSet, + )>, +} + +impl<'tracer> ExpressionTracer<'tracer> { + pub fn trace_expression(&mut self, expr: Handle) { + log::trace!( + "entering trace_expression of {}", + if self.const_expressions.is_some() { + "function expressions" + } else { + "const expressions" + } + ); + let mut work_list = vec![expr]; + while let Some(expr) = work_list.pop() { + // If we've already seen this expression, no need to trace further. + if !self.expressions_used.insert(expr) { + continue; + } + log::trace!("tracing new expression {:?}", expr); + + use crate::Expression as Ex; + match self.expressions[expr] { + // Expressions that do not contain handles that need to be traced. + Ex::Literal(_) + | Ex::FunctionArgument(_) + | Ex::GlobalVariable(_) + | Ex::LocalVariable(_) + | Ex::CallResult(_) + | Ex::RayQueryProceedResult => {} + + Ex::Constant(handle) => { + self.constants_used.insert(handle); + let constant = &self.constants[handle]; + self.trace_type(constant.ty); + self.trace_const_expression(constant.init); + } + Ex::ZeroValue(ty) => self.trace_type(ty), + Ex::Compose { ty, ref components } => { + self.trace_type(ty); + work_list.extend(components); + } + Ex::Access { base, index } => work_list.extend([base, index]), + Ex::AccessIndex { base, index: _ } => work_list.push(base), + Ex::Splat { size: _, value } => work_list.push(value), + Ex::Swizzle { + size: _, + vector, + pattern: _, + } => work_list.push(vector), + Ex::Load { pointer } => work_list.push(pointer), + Ex::ImageSample { + image, + sampler, + gather: _, + coordinate, + array_index, + offset, + ref level, + depth_ref, + } => { + work_list.push(image); + work_list.push(sampler); + work_list.push(coordinate); + work_list.extend(array_index); + if let Some(offset) = offset { + self.trace_const_expression(offset); + } + use crate::SampleLevel as Sl; + match *level { + Sl::Auto | Sl::Zero => {} + Sl::Exact(expr) | Sl::Bias(expr) => work_list.push(expr), + Sl::Gradient { x, y } => work_list.extend([x, y]), + } + work_list.extend(depth_ref); + } + Ex::ImageLoad { + image, + coordinate, + array_index, + sample, + level, + } => { + work_list.push(image); + work_list.push(coordinate); + work_list.extend(array_index); + work_list.extend(sample); + work_list.extend(level); + } + Ex::ImageQuery { image, ref query } => { + work_list.push(image); + use crate::ImageQuery as Iq; + match *query { + Iq::Size { level } => work_list.extend(level), + Iq::NumLevels | Iq::NumLayers | Iq::NumSamples => {} + } + } + Ex::Unary { op: _, expr } => work_list.push(expr), + Ex::Binary { op: _, left, right } => work_list.extend([left, right]), + Ex::Select { + condition, + accept, + reject, + } => work_list.extend([condition, accept, reject]), + Ex::Derivative { + axis: _, + ctrl: _, + expr, + } => work_list.push(expr), + Ex::Relational { fun: _, argument } => work_list.push(argument), + Ex::Math { + fun: _, + arg, + arg1, + arg2, + arg3, + } => { + work_list.push(arg); + work_list.extend(arg1); + work_list.extend(arg2); + work_list.extend(arg3); + } + Ex::As { + expr, + kind: _, + convert: _, + } => work_list.push(expr), + Ex::AtomicResult { ty, comparison: _ } => self.trace_type(ty), + Ex::WorkGroupUniformLoadResult { ty } => self.trace_type(ty), + Ex::ArrayLength(expr) => work_list.push(expr), + Ex::RayQueryGetIntersection { + query, + committed: _, + } => work_list.push(query), + } + } + } + + fn trace_type(&mut self, ty: Handle) { + let mut types_used = super::types::TypeTracer { + types: self.types, + types_used: self.types_used, + }; + types_used.trace_type(ty); + } + + pub fn as_const_expression(&mut self) -> ExpressionTracer { + match self.const_expressions { + Some((ref mut exprs, ref mut exprs_used)) => ExpressionTracer { + expressions: exprs, + expressions_used: exprs_used, + types: self.types, + constants: self.constants, + types_used: self.types_used, + constants_used: self.constants_used, + const_expressions: None, + }, + None => ExpressionTracer { + types: self.types, + constants: self.constants, + expressions: self.expressions, + types_used: self.types_used, + constants_used: self.constants_used, + expressions_used: self.expressions_used, + const_expressions: None, + }, + } + } + + fn trace_const_expression(&mut self, const_expr: Handle) { + self.as_const_expression().trace_expression(const_expr); + } +} + +impl ModuleMap { + /// Fix up all handles in `expr`. + /// + /// Use the expression handle remappings in `operand_map`, and all + /// other mappings from `self`. + pub fn adjust_expression( + &self, + expr: &mut crate::Expression, + operand_map: &HandleMap, + ) { + let adjust = |expr: &mut Handle| { + operand_map.adjust(expr); + }; + + use crate::Expression as Ex; + match *expr { + // Expressions that do not contain handles that need to be adjusted. + Ex::Literal(_) + | Ex::FunctionArgument(_) + | Ex::GlobalVariable(_) + | Ex::LocalVariable(_) + | Ex::CallResult(_) + | Ex::RayQueryProceedResult => {} + + // Expressions that contain handles that need to be adjusted. + Ex::Constant(ref mut constant) => self.constants.adjust(constant), + Ex::ZeroValue(ref mut ty) => self.types.adjust(ty), + Ex::Compose { + ref mut ty, + ref mut components, + } => { + self.types.adjust(ty); + for component in components { + adjust(component); + } + } + Ex::Access { + ref mut base, + ref mut index, + } => { + adjust(base); + adjust(index); + } + Ex::AccessIndex { + ref mut base, + index: _, + } => adjust(base), + Ex::Splat { + size: _, + ref mut value, + } => adjust(value), + Ex::Swizzle { + size: _, + ref mut vector, + pattern: _, + } => adjust(vector), + Ex::Load { ref mut pointer } => adjust(pointer), + Ex::ImageSample { + ref mut image, + ref mut sampler, + gather: _, + ref mut coordinate, + ref mut array_index, + ref mut offset, + ref mut level, + ref mut depth_ref, + } => { + adjust(image); + adjust(sampler); + adjust(coordinate); + operand_map.adjust_option(array_index); + // TEST: try adjusting this with plain operand_map + if let Some(ref mut offset) = *offset { + self.const_expressions.adjust(offset); + } + self.adjust_sample_level(level, operand_map); + operand_map.adjust_option(depth_ref); + } + Ex::ImageLoad { + ref mut image, + ref mut coordinate, + ref mut array_index, + ref mut sample, + ref mut level, + } => { + adjust(image); + adjust(coordinate); + operand_map.adjust_option(array_index); + operand_map.adjust_option(sample); + operand_map.adjust_option(level); + } + Ex::ImageQuery { + ref mut image, + ref mut query, + } => { + adjust(image); + self.adjust_image_query(query, operand_map); + } + Ex::Unary { + op: _, + ref mut expr, + } => adjust(expr), + Ex::Binary { + op: _, + ref mut left, + ref mut right, + } => { + adjust(left); + adjust(right); + } + Ex::Select { + ref mut condition, + ref mut accept, + ref mut reject, + } => { + adjust(condition); + adjust(accept); + adjust(reject); + } + Ex::Derivative { + axis: _, + ctrl: _, + ref mut expr, + } => adjust(expr), + Ex::Relational { + fun: _, + ref mut argument, + } => adjust(argument), + Ex::Math { + fun: _, + ref mut arg, + ref mut arg1, + ref mut arg2, + ref mut arg3, + } => { + adjust(arg); + operand_map.adjust_option(arg1); + operand_map.adjust_option(arg2); + operand_map.adjust_option(arg3); + } + Ex::As { + ref mut expr, + kind: _, + convert: _, + } => adjust(expr), + Ex::AtomicResult { + ref mut ty, + comparison: _, + } => self.types.adjust(ty), + Ex::WorkGroupUniformLoadResult { ref mut ty } => self.types.adjust(ty), + Ex::ArrayLength(ref mut expr) => adjust(expr), + Ex::RayQueryGetIntersection { + ref mut query, + committed: _, + } => adjust(query), + } + } + + fn adjust_sample_level( + &self, + level: &mut crate::SampleLevel, + operand_map: &HandleMap, + ) { + let adjust = |expr: &mut Handle| operand_map.adjust(expr); + + use crate::SampleLevel as Sl; + match *level { + Sl::Auto | Sl::Zero => {} + Sl::Exact(ref mut expr) => adjust(expr), + Sl::Bias(ref mut expr) => adjust(expr), + Sl::Gradient { + ref mut x, + ref mut y, + } => { + adjust(x); + adjust(y); + } + } + } + + fn adjust_image_query( + &self, + query: &mut crate::ImageQuery, + operand_map: &HandleMap, + ) { + use crate::ImageQuery as Iq; + + match *query { + Iq::Size { ref mut level } => operand_map.adjust_option(level), + Iq::NumLevels | Iq::NumLayers | Iq::NumSamples => {} + } + } +} diff --git a/src/compact/functions.rs b/src/compact/functions.rs new file mode 100644 index 000000000..08ca289a5 --- /dev/null +++ b/src/compact/functions.rs @@ -0,0 +1,134 @@ +use super::handle_set_map::HandleSet; +use super::{FunctionMap, ModuleMap}; +use crate::arena::Handle; + +pub(super) struct FunctionTracer<'a> { + pub(super) module: &'a crate::Module, + pub(super) function: &'a crate::Function, + + pub(super) types_used: &'a mut HandleSet, + pub(super) constants_used: &'a mut HandleSet, + pub(super) const_expressions_used: &'a mut HandleSet, + + /// Function-local expressions used. + pub(super) expressions_used: HandleSet, +} + +impl<'a> FunctionTracer<'a> { + pub fn trace(&mut self) { + for argument in self.function.arguments.iter() { + self.trace_type(argument.ty); + } + + if let Some(ref result) = self.function.result { + self.trace_type(result.ty); + } + + for (_, local) in self.function.local_variables.iter() { + self.trace_type(local.ty); + if let Some(init) = local.init { + // TEST: try changing this to trace_expression + self.trace_const_expression(init); + } + } + + // Treat named expressions as alive, for the sake of our test suite, + // which uses `let blah = expr;` to exercise lots of things. + for (value, _name) in &self.function.named_expressions { + self.trace_expression(*value); + } + + self.trace_block(&self.function.body); + } + + pub fn trace_type(&mut self, ty: Handle) { + self.as_type().trace_type(ty) + } + + pub fn trace_expression(&mut self, expr: Handle) { + self.as_expression().trace_expression(expr); + } + + pub fn trace_const_expression(&mut self, expr: Handle) { + self.as_expression() + .as_const_expression() + .trace_expression(expr); + } + + /* + pub fn trace_const_expression(&mut self, const_expr: Handle) { + self.as_expression().as_const_expression().trace_expression(const_expr); + } + */ + + fn as_type(&mut self) -> super::types::TypeTracer { + super::types::TypeTracer { + types: &self.module.types, + types_used: self.types_used, + } + } + + fn as_expression(&mut self) -> super::expressions::ExpressionTracer { + super::expressions::ExpressionTracer { + types: &self.module.types, + constants: &self.module.constants, + expressions: &self.function.expressions, + + types_used: self.types_used, + constants_used: self.constants_used, + expressions_used: &mut self.expressions_used, + const_expressions: Some(( + &self.module.const_expressions, + &mut self.const_expressions_used, + )), + } + } +} + +impl FunctionMap { + pub fn compact( + &self, + function: &mut crate::Function, + module_map: &ModuleMap, + reuse: &mut crate::NamedExpressions, + ) { + assert!(reuse.is_empty()); + + for argument in function.arguments.iter_mut() { + module_map.types.adjust(&mut argument.ty); + } + + if let Some(ref mut result) = function.result { + module_map.types.adjust(&mut result.ty); + } + + for (_, local) in function.local_variables.iter_mut() { + log::trace!("adjusting local variable {:?}", local.name); + module_map.types.adjust(&mut local.ty); + if let Some(ref mut init) = local.init { + module_map.const_expressions.adjust(init); + } + } + + // Drop unused expressions, reusing existing storage. + function.expressions.retain_mut(|handle, expr| { + if self.expressions.used(handle) { + module_map.adjust_expression(expr, &self.expressions); + true + } else { + false + } + }); + + // Adjust named expressions. + for (mut handle, name) in function.named_expressions.drain(..) { + self.expressions.adjust(&mut handle); + reuse.insert(handle, name); + } + std::mem::swap(&mut function.named_expressions, reuse); + assert!(reuse.is_empty()); + + // Adjust statements. + self.adjust_block(&mut function.body); + } +} diff --git a/src/compact/handle_set_map.rs b/src/compact/handle_set_map.rs new file mode 100644 index 000000000..3a7968a71 --- /dev/null +++ b/src/compact/handle_set_map.rs @@ -0,0 +1,125 @@ +use crate::arena::{Arena, Handle, UniqueArena}; + +type Index = std::num::NonZeroU32; + +/// A set of `Handle` values. +pub struct HandleSet { + /// Bound on zero-based indexes of handles stored in this set. + len: usize, + + /// `members[i]` is true if the handle with zero-based index `i` + /// is a member. + members: bit_set::BitSet, + + /// This type is indexed by values of type `T`. + as_keys: std::marker::PhantomData, +} + +impl HandleSet { + pub fn for_arena(arena: &impl ArenaType) -> Self { + let len = arena.len(); + Self { + len, + members: bit_set::BitSet::with_capacity(len), + as_keys: std::marker::PhantomData, + } + } + + /// Add `handle` to the set. + /// + /// Return `true` if the handle was not already in the set. In + /// other words, return true if it was newly inserted. + pub fn insert(&mut self, handle: Handle) -> bool { + // Note that, oddly, `Handle::index` does not return a 1-based + // `Index`, but rather a zero-based `usize`. + self.members.insert(handle.index()) + } +} + +pub trait ArenaType { + fn len(&self) -> usize; +} + +impl ArenaType for Arena { + fn len(&self) -> usize { + self.len() + } +} + +impl ArenaType for UniqueArena { + fn len(&self) -> usize { + self.len() + } +} + +/// A map from old handle indices to new, compressed handle indices. +pub struct HandleMap { + /// The indices assigned to handles in the compacted module. + /// + /// If `new_index[i]` is `Some(n)`, then `n` is the 1-based + /// `Index` of the compacted `Handle` corresponding to the + /// pre-compacted `Handle` whose zero-based index is `i`. ("Clear + /// as mud.") + new_index: Vec>, + + /// This type is indexed by values of type `T`. + as_keys: std::marker::PhantomData, +} + +impl HandleMap { + pub fn from_set(set: HandleSet) -> Self { + let mut next_index = Index::new(1).unwrap(); + Self { + new_index: (0..set.len) + .map(|zero_based_index| { + if set.members.contains(zero_based_index) { + // This handle will be retained in the compacted version, + // so assign it a new index. + let this = next_index; + next_index = next_index.checked_add(1).unwrap(); + Some(this) + } else { + // This handle will be omitted in the compacted version. + None + } + }) + .collect(), + as_keys: std::marker::PhantomData, + } + } + + /// Return true if `old` is used in the compacted module. + pub fn used(&self, old: Handle) -> bool { + self.new_index[old.index()].is_some() + } + + /// Return the counterpart to `old` in the compacted module. + /// + /// If we thought `old` wouldn't be used in the compacted module, return + /// `None`. + pub fn try_adjust(&self, old: Handle) -> Option> { + log::trace!( + "adjusting {} handle [{}] -> [{:?}]", + std::any::type_name::(), + old.index() + 1, + self.new_index[old.index()] + ); + // Note that `Handle::index` returns a zero-based index, + // but `Handle::new` accepts a 1-based `Index`. + self.new_index[old.index()].map(Handle::new) + } + + /// Return the counterpart to `old` in the compacted module. + /// + /// If we thought `old` wouldn't be used in the compacted module, panic. + pub fn adjust(&self, handle: &mut Handle) { + *handle = self.try_adjust(*handle).unwrap(); + } + + /// Like `adjust`, but for optional handles. + pub fn adjust_option(&self, handle: &mut Option>) { + if let Some(ref mut handle) = *handle { + self.adjust(handle); + } + } +} diff --git a/src/compact/mod.rs b/src/compact/mod.rs new file mode 100644 index 000000000..e0de1fe97 --- /dev/null +++ b/src/compact/mod.rs @@ -0,0 +1,286 @@ +mod expressions; +mod functions; +mod handle_set_map; +mod statements; +mod types; + +use crate::{arena, compact::functions::FunctionTracer}; +use handle_set_map::{HandleMap, HandleSet}; + +/// Remove unused types, expressions, and constants from `module`. +/// +/// Assuming that all globals, named constants, special types, +/// functions and entry points in `module` are used, determine which +/// types, constants, and expressions (both function-local and global +/// constant expressions) are actually used, and remove the rest, +/// adjusting all handles as necessary. The result should be a module +/// functionally identical to the original. +/// +/// This may be useful to apply to modules generated in the snapshot +/// tests. Our backends often generate temporary names based on handle +/// indices, which means that adding or removing unused arena entries +/// can affect the output even though they have no semantic effect. +/// Such meaningless changes add noise to snapshot diffs, making +/// accurate patch review difficult. Compacting the modules before +/// generating snapshots makes the output independent of unused arena +/// entries. +/// +/// # Panics +/// +/// If `module` has not passed validation, this may panic. +pub fn compact(module: &mut crate::Module) { + let mut module_tracer = ModuleTracer::new(module); + + // We treat all globals as used by definition. + log::trace!("tracing global variables"); + { + for (_, global) in module.global_variables.iter() { + log::trace!("tracing global {:?}", global.name); + module_tracer.as_type().trace_type(global.ty); + if let Some(init) = global.init { + module_tracer.as_const_expression().trace_expression(init); + } + } + } + + // We treat all special types as used by definition. + module_tracer.trace_special_types(&module.special_types); + + // We treat all named constants as used by definition. + for (handle, constant) in module.constants.iter() { + if constant.name.is_some() { + module_tracer.constants_used.insert(handle); + module_tracer.as_type().trace_type(constant.ty); + module_tracer + .as_const_expression() + .trace_expression(constant.init); + } + } + + // We assume that all functions are used. + // + // Observe which types, constant expressions, constants, and + // expressions each function uses, and produce maps from + // pre-compaction to post-compaction handles. + log::trace!("tracing functions"); + let function_maps: Vec = module + .functions + .iter() + .map(|(_, f)| { + log::trace!("tracing function {:?}", f.name); + let mut function_tracer = module_tracer.enter_function(f); + function_tracer.trace(); + FunctionMap::from(function_tracer) + }) + .collect(); + + // Similiarly, observe what each entry point actually uses. + log::trace!("tracing entry points"); + let entry_point_maps: Vec = module + .entry_points + .iter() + .map(|e| { + log::trace!("tracing entry point {:?}", e.function.name); + let mut used = module_tracer.enter_function(&e.function); + used.trace(); + FunctionMap::from(used) + }) + .collect(); + + // Now that we know what is used and what is never touched, + // produce maps from the `Handle`s that appear in `module` now to + // the corresponding `Handle`s that will refer to the same items + // in the compacted module. + let module_map = ModuleMap::from(module_tracer); + + // Drop unused types from the type arena. + // + // `IndexSet`s don't have an underlying Vec that we can steal, compact in + // place, and then rebuild the `IndexSet` from. So we have to rebuild the + // type arena from scratch. + log::trace!("compacting types"); + let mut new_types = arena::UniqueArena::new(); + for (old_handle, mut ty, span) in module.types.drain_all() { + if let Some(expected_new_handle) = module_map.types.try_adjust(old_handle) { + module_map.adjust_type(&mut ty); + let actual_new_handle = new_types.insert(ty, span); + assert_eq!(actual_new_handle, expected_new_handle); + } + } + module.types = new_types; + log::trace!("adjusting special types"); + module_map.adjust_special_types(&mut module.special_types); + + // Drop unused constant expressions, reusing existing storage. + log::trace!("adjusting constant expressions"); + module.const_expressions.retain_mut(|handle, expr| { + if module_map.const_expressions.used(handle) { + module_map.adjust_expression(expr, &module_map.const_expressions); + true + } else { + false + } + }); + + // Drop unused constants in place, reusing existing storage. + log::trace!("adjusting constants"); + module.constants.retain_mut(|handle, constant| { + if module_map.constants.used(handle) { + module_map.types.adjust(&mut constant.ty); + module_map.const_expressions.adjust(&mut constant.init); + true + } else { + false + } + }); + + // Adjust global variables' types and initializers. + log::trace!("adjusting global variables"); + for (_, global) in module.global_variables.iter_mut() { + log::trace!("adjusting global {:?}", global.name); + module_map.types.adjust(&mut global.ty); + if let Some(ref mut init) = global.init { + module_map.const_expressions.adjust(init); + } + } + + // Temporary storage to help us reuse allocations of existing + // named expression tables. + let mut reused_named_expressions = crate::NamedExpressions::default(); + + // Compact each function. + for ((_, function), map) in module.functions.iter_mut().zip(function_maps.iter()) { + log::trace!("compacting function {:?}", function.name); + map.compact(function, &module_map, &mut reused_named_expressions); + } + + // Compact each entry point. + for (entry, map) in module.entry_points.iter_mut().zip(entry_point_maps.iter()) { + log::trace!("compacting entry point {:?}", entry.function.name); + map.compact( + &mut entry.function, + &module_map, + &mut reused_named_expressions, + ); + } +} + +struct ModuleTracer<'module> { + module: &'module crate::Module, + types_used: HandleSet, + constants_used: HandleSet, + const_expressions_used: HandleSet, +} + +impl<'module> ModuleTracer<'module> { + fn new(module: &'module crate::Module) -> Self { + Self { + module, + types_used: HandleSet::for_arena(&module.types), + constants_used: HandleSet::for_arena(&module.constants), + const_expressions_used: HandleSet::for_arena(&module.const_expressions), + } + } + + fn trace_special_types(&mut self, special_types: &crate::SpecialTypes) { + let crate::SpecialTypes { + ref ray_desc, + ref ray_intersection, + ref predeclared_types, + } = *special_types; + + let mut type_tracer = self.as_type(); + if let Some(ray_desc) = *ray_desc { + type_tracer.trace_type(ray_desc); + } + if let Some(ray_intersection) = *ray_intersection { + type_tracer.trace_type(ray_intersection); + } + for (_, &handle) in predeclared_types { + type_tracer.trace_type(handle); + } + } + + fn as_type(&mut self) -> types::TypeTracer { + types::TypeTracer { + types: &self.module.types, + types_used: &mut self.types_used, + } + } + + fn as_const_expression(&mut self) -> expressions::ExpressionTracer { + expressions::ExpressionTracer { + types: &self.module.types, + constants: &self.module.constants, + expressions: &self.module.const_expressions, + types_used: &mut self.types_used, + constants_used: &mut self.constants_used, + expressions_used: &mut self.const_expressions_used, + const_expressions: None, + } + } + + pub fn enter_function<'tracer>( + &'tracer mut self, + function: &'tracer crate::Function, + ) -> FunctionTracer<'tracer> { + FunctionTracer { + module: self.module, + function, + + types_used: &mut self.types_used, + constants_used: &mut self.constants_used, + const_expressions_used: &mut self.const_expressions_used, + expressions_used: HandleSet::for_arena(&function.expressions), + } + } +} + +struct ModuleMap { + types: HandleMap, + constants: HandleMap, + const_expressions: HandleMap, +} + +impl From> for ModuleMap { + fn from(used: ModuleTracer) -> Self { + ModuleMap { + types: HandleMap::from_set(used.types_used), + constants: HandleMap::from_set(used.constants_used), + const_expressions: HandleMap::from_set(used.const_expressions_used), + } + } +} + +impl ModuleMap { + fn adjust_special_types(&self, special: &mut crate::SpecialTypes) { + let crate::SpecialTypes { + ref mut ray_desc, + ref mut ray_intersection, + ref mut predeclared_types, + } = *special; + + if let Some(ref mut ray_desc) = *ray_desc { + self.types.adjust(ray_desc); + } + if let Some(ref mut ray_intersection) = *ray_intersection { + self.types.adjust(ray_intersection); + } + + for handle in predeclared_types.values_mut() { + self.types.adjust(handle); + } + } +} + +struct FunctionMap { + expressions: HandleMap, +} + +impl From> for FunctionMap { + fn from(used: FunctionTracer) -> Self { + FunctionMap { + expressions: HandleMap::from_set(used.expressions_used), + } + } +} diff --git a/src/compact/statements.rs b/src/compact/statements.rs new file mode 100644 index 000000000..2c33df049 --- /dev/null +++ b/src/compact/statements.rs @@ -0,0 +1,302 @@ +use super::functions::FunctionTracer; +use super::FunctionMap; +use crate::arena::Handle; + +impl FunctionTracer<'_> { + pub fn trace_block(&mut self, block: &[crate::Statement]) { + let mut worklist: Vec<&[crate::Statement]> = vec![block]; + while let Some(last) = worklist.pop() { + for stmt in last { + use crate::Statement as St; + match *stmt { + St::Emit(ref range) => { + for expr in range.clone() { + log::trace!("trace emitted expression {:?}", expr); + self.trace_expression(expr); + } + } + St::Block(ref block) => worklist.push(block), + St::If { + condition, + ref accept, + ref reject, + } => { + self.trace_expression(condition); + worklist.push(accept); + worklist.push(reject); + } + St::Switch { + selector, + ref cases, + } => { + self.trace_expression(selector); + for case in cases { + worklist.push(&case.body); + } + } + St::Loop { + ref body, + ref continuing, + break_if, + } => { + if let Some(break_if) = break_if { + self.trace_expression(break_if); + } + worklist.push(body); + worklist.push(continuing); + } + St::Return { value: Some(value) } => self.trace_expression(value), + St::Store { pointer, value } => { + self.trace_expression(pointer); + self.trace_expression(value); + } + St::ImageStore { + image, + coordinate, + array_index, + value, + } => { + self.trace_expression(image); + self.trace_expression(coordinate); + if let Some(array_index) = array_index { + self.trace_expression(array_index); + } + self.trace_expression(value); + } + St::Atomic { + pointer, + ref fun, + value, + result, + } => { + self.trace_expression(pointer); + self.trace_atomic_function(fun); + self.trace_expression(value); + self.trace_expression(result); + } + St::WorkGroupUniformLoad { pointer, result } => { + self.trace_expression(pointer); + self.trace_expression(result); + } + St::Call { + function: _, + ref arguments, + result, + } => { + for expr in arguments { + self.trace_expression(*expr); + } + if let Some(result) = result { + self.trace_expression(result); + } + } + St::RayQuery { query, ref fun } => { + self.trace_expression(query); + self.trace_ray_query_function(fun); + } + + // Trivial statements. + St::Break + | St::Continue + | St::Kill + | St::Barrier(_) + | St::Return { value: None } => {} + } + } + } + } + + fn trace_atomic_function(&mut self, fun: &crate::AtomicFunction) { + use crate::AtomicFunction as Af; + match *fun { + Af::Exchange { + compare: Some(expr), + } => self.trace_expression(expr), + Af::Exchange { compare: None } + | Af::Add + | Af::Subtract + | Af::And + | Af::ExclusiveOr + | Af::InclusiveOr + | Af::Min + | Af::Max => {} + } + } + + fn trace_ray_query_function(&mut self, fun: &crate::RayQueryFunction) { + use crate::RayQueryFunction as Qf; + match *fun { + Qf::Initialize { + acceleration_structure, + descriptor, + } => { + self.trace_expression(acceleration_structure); + self.trace_expression(descriptor); + } + Qf::Proceed { result } => self.trace_expression(result), + Qf::Terminate => {} + } + } +} + +impl FunctionMap { + pub fn adjust_block(&self, block: &mut [crate::Statement]) { + let mut worklist: Vec<&mut [crate::Statement]> = vec![block]; + let adjust = |handle: &mut Handle| { + self.expressions.adjust(handle); + }; + while let Some(last) = worklist.pop() { + for stmt in last { + use crate::Statement as St; + match *stmt { + St::Emit(ref mut range) => { + // Fortunately, compaction doesn't arbitrarily scramble + // the expressions in the arena, but instead preserves + // the order of the elements while squeezing out unused + // ones. That means that a contiguous range in the + // pre-compacted arena always maps to a contiguous range + // in the post-compacted arena. So we just need to + // adjust the endpoints. + let (mut first, mut last) = range.first_and_last().unwrap(); + self.expressions.adjust(&mut first); + self.expressions.adjust(&mut last); + *range = crate::arena::Range::new_from_bounds(first, last); + } + St::Block(ref mut block) => worklist.push(block), + St::If { + ref mut condition, + ref mut accept, + ref mut reject, + } => { + adjust(condition); + worklist.push(accept); + worklist.push(reject); + } + St::Switch { + ref mut selector, + ref mut cases, + } => { + adjust(selector); + for case in cases { + worklist.push(&mut case.body); + } + } + St::Loop { + ref mut body, + ref mut continuing, + ref mut break_if, + } => { + if let Some(ref mut break_if) = *break_if { + adjust(break_if); + } + worklist.push(body); + worklist.push(continuing); + } + St::Return { + value: Some(ref mut value), + } => adjust(value), + St::Store { + ref mut pointer, + ref mut value, + } => { + adjust(pointer); + adjust(value); + } + St::ImageStore { + ref mut image, + ref mut coordinate, + ref mut array_index, + ref mut value, + } => { + adjust(image); + adjust(coordinate); + if let Some(ref mut array_index) = *array_index { + adjust(array_index); + } + adjust(value); + } + St::Atomic { + ref mut pointer, + ref mut fun, + ref mut value, + ref mut result, + } => { + adjust(pointer); + self.adjust_atomic_function(fun); + adjust(value); + adjust(result); + } + St::WorkGroupUniformLoad { + ref mut pointer, + ref mut result, + } => { + adjust(pointer); + adjust(result); + } + St::Call { + function: _, + ref mut arguments, + ref mut result, + } => { + for expr in arguments { + adjust(expr); + } + if let Some(ref mut result) = *result { + adjust(result); + } + } + St::RayQuery { + ref mut query, + ref mut fun, + } => { + adjust(query); + self.adjust_ray_query_function(fun); + } + + // Trivial statements. + St::Break + | St::Continue + | St::Kill + | St::Barrier(_) + | St::Return { value: None } => {} + } + } + } + } + + fn adjust_atomic_function(&self, fun: &mut crate::AtomicFunction) { + use crate::AtomicFunction as Af; + match *fun { + Af::Exchange { + compare: Some(ref mut expr), + } => { + self.expressions.adjust(expr); + } + Af::Exchange { compare: None } + | Af::Add + | Af::Subtract + | Af::And + | Af::ExclusiveOr + | Af::InclusiveOr + | Af::Min + | Af::Max => {} + } + } + + fn adjust_ray_query_function(&self, fun: &mut crate::RayQueryFunction) { + use crate::RayQueryFunction as Qf; + match *fun { + Qf::Initialize { + ref mut acceleration_structure, + ref mut descriptor, + } => { + self.expressions.adjust(acceleration_structure); + self.expressions.adjust(descriptor); + } + Qf::Proceed { ref mut result } => { + self.expressions.adjust(result); + } + Qf::Terminate => {} + } + } +} diff --git a/src/compact/types.rs b/src/compact/types.rs new file mode 100644 index 000000000..d11ab8a73 --- /dev/null +++ b/src/compact/types.rs @@ -0,0 +1,93 @@ +use super::{HandleSet, ModuleMap}; +use crate::{Handle, UniqueArena}; + +pub struct TypeTracer<'a> { + pub types: &'a UniqueArena, + pub types_used: &'a mut HandleSet, +} + +impl<'a> TypeTracer<'a> { + pub fn trace_type(&mut self, ty: Handle) { + let mut work_list = vec![ty]; + while let Some(ty) = work_list.pop() { + // If we've already seen this type, no need to traverse further. + if !self.types_used.insert(ty) { + continue; + } + + use crate::TypeInner as Ti; + match self.types[ty].inner { + // Types that do not contain handles. + Ti::Scalar { .. } + | Ti::Vector { .. } + | Ti::Matrix { .. } + | Ti::Atomic { .. } + | Ti::ValuePointer { .. } + | Ti::Image { .. } + | Ti::Sampler { .. } + | Ti::AccelerationStructure + | Ti::RayQuery => {} + + // Types that do contain handles. + Ti::Pointer { base, space: _ } => work_list.push(base), + Ti::Array { + base, + size: _, + stride: _, + } => work_list.push(base), + Ti::Struct { + ref members, + span: _, + } => { + work_list.extend(members.iter().map(|m| m.ty)); + } + Ti::BindingArray { base, size: _ } => work_list.push(base), + } + } + } +} + +impl ModuleMap { + pub fn adjust_type(&self, ty: &mut crate::Type) { + let adjust = |ty: &mut Handle| self.types.adjust(ty); + + use crate::TypeInner as Ti; + match ty.inner { + // Types that do not contain handles. + Ti::Scalar { .. } + | Ti::Vector { .. } + | Ti::Matrix { .. } + | Ti::Atomic { .. } + | Ti::ValuePointer { .. } + | Ti::Image { .. } + | Ti::Sampler { .. } + | Ti::AccelerationStructure + | Ti::RayQuery => {} + + // Types that do contain handles. + Ti::Pointer { + ref mut base, + space: _, + } => adjust(base), + Ti::Array { + ref mut base, + size: _, + stride: _, + } => adjust(base), + Ti::Struct { + ref mut members, + span: _, + } => { + for member in members { + self.types.adjust(&mut member.ty); + } + } + Ti::BindingArray { + ref mut base, + size: _, + } => { + adjust(base); + } + }; + } +} diff --git a/src/lib.rs b/src/lib.rs index 49fd9d4e5..92a0ba2ce 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -279,6 +279,8 @@ An override expression can be evaluated at pipeline creation time. mod arena; pub mod back; mod block; +#[cfg(feature = "compact")] +pub mod compact; pub mod front; pub mod keywords; pub mod proc; diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron index 03186d9f1..4a020e48c 100644 --- a/tests/out/analysis/access.info.ron +++ b/tests/out/analysis/access.info.ron @@ -17,7 +17,6 @@ ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), - ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), @@ -26,10 +25,7 @@ ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), - ("SIZED | COPY"), ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), - ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), - ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("SIZED | COPY | ARGUMENT"), ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("SIZED | COPY | ARGUMENT"), @@ -164,18 +160,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -287,18 +271,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -313,18 +285,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -375,18 +335,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -483,18 +431,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: Some(2), @@ -698,7 +634,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 8, @@ -740,7 +676,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -836,7 +772,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -848,19 +784,7 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -899,7 +823,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -920,7 +844,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -959,7 +883,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -971,19 +895,7 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -997,19 +909,7 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1035,7 +935,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1047,19 +947,7 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1082,7 +970,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1108,7 +996,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1129,7 +1017,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1143,19 +1031,7 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1181,7 +1057,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1202,7 +1078,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1225,7 +1101,7 @@ ), ( uniformity: ( - non_uniform_result: Some(55), + non_uniform_result: Some(50), requirements: (""), ), ref_count: 1, @@ -1325,18 +1201,6 @@ assignable_global: None, ty: Handle(3), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(5), - ty: Value(Pointer( - base: 21, - space: Uniform, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1349,51 +1213,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(20), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(5), - ty: Value(Pointer( - base: 21, - space: Uniform, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(5), - ty: Value(Pointer( - base: 20, - space: Uniform, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1415,18 +1234,6 @@ assignable_global: None, ty: Handle(19), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(5), - ty: Value(Pointer( - base: 21, - space: Uniform, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1439,18 +1246,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1463,6 +1258,18 @@ space: Uniform, )), ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 18, + space: Uniform, + )), + ), ( uniformity: ( non_uniform_result: None, @@ -1470,9 +1277,42 @@ ), ref_count: 0, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, + ty: Handle(18), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 20, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 19, + space: Uniform, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 18, + space: Uniform, )), ), ( @@ -1502,18 +1342,6 @@ width: 4, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(5), - ty: Value(Pointer( - base: 21, - space: Uniform, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1526,18 +1354,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1550,6 +1366,18 @@ space: Uniform, )), ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 18, + space: Uniform, + )), + ), ( uniformity: ( non_uniform_result: Some(2), @@ -1586,18 +1414,6 @@ width: 4, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(5), - ty: Value(Pointer( - base: 21, - space: Uniform, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1610,18 +1426,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1639,11 +1443,11 @@ non_uniform_result: None, requirements: (""), ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 18, + space: Uniform, )), ), ( @@ -1660,18 +1464,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1698,18 +1490,6 @@ width: 4, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(5), - ty: Value(Pointer( - base: 21, - space: Uniform, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1722,18 +1502,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1751,11 +1519,11 @@ non_uniform_result: None, requirements: (""), ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 18, + space: Uniform, )), ), ( @@ -1807,18 +1575,6 @@ width: 4, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(5), - ty: Value(Pointer( - base: 21, - space: Uniform, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1831,18 +1587,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1855,6 +1599,18 @@ space: Uniform, )), ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 18, + space: Uniform, + )), + ), ( uniformity: ( non_uniform_result: Some(2), @@ -1878,18 +1634,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: Some(2), @@ -1916,18 +1660,6 @@ width: 4, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(5), - ty: Value(Pointer( - base: 21, - space: Uniform, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1940,18 +1672,6 @@ space: Uniform, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -1964,6 +1684,18 @@ space: Uniform, )), ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: Some(5), + ty: Value(Pointer( + base: 18, + space: Uniform, + )), + ), ( uniformity: ( non_uniform_result: Some(2), @@ -2022,6 +1754,15 @@ width: 4, )), ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(19), + ), ( uniformity: ( non_uniform_result: None, @@ -2033,22 +1774,13 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(21), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 9, assignable_global: None, ty: Value(Pointer( - base: 21, + base: 20, space: Function, )), ), @@ -2084,52 +1816,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Pointer( - base: 20, - space: Function, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(20), - ), - ( - uniformity: ( - non_uniform_result: Some(66), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Pointer( - base: 20, - space: Function, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2139,106 +1826,6 @@ space: Function, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Vector( - size: Bi, - kind: Float, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Vector( - size: Bi, - kind: Float, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Vector( - size: Bi, - kind: Float, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Scalar( - kind: Float, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Vector( - size: Bi, - kind: Float, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: None, @@ -2250,31 +1837,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Pointer( - base: 20, - space: Function, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2284,21 +1847,154 @@ space: Function, )), ), + ( + uniformity: ( + non_uniform_result: Some(54), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 18, + space: Function, + )), + ), ( uniformity: ( non_uniform_result: None, requirements: (""), ), - ref_count: 0, + ref_count: 1, assignable_global: None, ty: Value(Scalar( - kind: Sint, + kind: Float, width: 4, )), ), ( uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Vector( + size: Bi, + kind: Float, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(18), + ), + ( + uniformity: ( + non_uniform_result: Some(54), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 19, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(54), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 18, + space: Function, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2337,31 +2033,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Pointer( - base: 20, - space: Function, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2371,6 +2043,18 @@ space: Function, )), ), + ( + uniformity: ( + non_uniform_result: Some(54), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 18, + space: Function, + )), + ), ( uniformity: ( non_uniform_result: Some(2), @@ -2382,7 +2066,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2421,31 +2105,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Pointer( - base: 20, - space: Function, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2457,19 +2117,19 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(54), requirements: (""), ), - ref_count: 0, + ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, + ty: Value(Pointer( + base: 18, + space: Function, )), ), ( uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2483,19 +2143,7 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2521,31 +2169,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Pointer( - base: 20, - space: Function, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2557,19 +2181,19 @@ ), ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(54), requirements: (""), ), - ref_count: 0, + ref_count: 1, assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, + ty: Value(Pointer( + base: 18, + space: Function, )), ), ( uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2592,7 +2216,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2618,31 +2242,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Pointer( - base: 20, - space: Function, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2652,6 +2252,18 @@ space: Function, )), ), + ( + uniformity: ( + non_uniform_result: Some(54), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 18, + space: Function, + )), + ), ( uniformity: ( non_uniform_result: Some(2), @@ -2663,7 +2275,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2677,19 +2289,7 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2715,31 +2315,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Value(Pointer( - base: 20, - space: Function, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2749,6 +2325,18 @@ space: Function, )), ), + ( + uniformity: ( + non_uniform_result: Some(54), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 18, + space: Function, + )), + ), ( uniformity: ( non_uniform_result: Some(2), @@ -2760,7 +2348,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2783,7 +2371,7 @@ ), ( uniformity: ( - non_uniform_result: Some(66), + non_uniform_result: Some(54), requirements: (""), ), ref_count: 1, @@ -2829,6 +2417,55 @@ (""), ], expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(22), + ), + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(21), + ), + ], + sampling: [], + dual_source_blending: false, + ), + ( + flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), + available_stages: ("VERTEX | FRAGMENT | COMPUTE"), + uniformity: ( + non_uniform_result: Some(1), + requirements: (""), + ), + may_kill: false, + sampling_set: [], + global_uses: [ + (""), + (""), + (""), + (""), + (""), + (""), + ], + expressions: [ + ( + uniformity: ( + non_uniform_result: Some(1), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(24), + ), ( uniformity: ( non_uniform_result: Some(1), @@ -2845,80 +2482,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(22), - ), - ], - sampling: [], - dual_source_blending: false, - ), - ( - flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), - available_stages: ("VERTEX | FRAGMENT | COMPUTE"), - uniformity: ( - non_uniform_result: Some(1), - requirements: (""), - ), - may_kill: false, - sampling_set: [], - global_uses: [ - (""), - (""), - (""), - (""), - (""), - (""), - ], - expressions: [ - ( - uniformity: ( - non_uniform_result: Some(1), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(25), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(1), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(24), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(1), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(22), + ty: Handle(21), ), ], sampling: [], @@ -2949,7 +2513,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(31), + ty: Handle(27), ), ( uniformity: ( @@ -2992,7 +2556,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(33), + ty: Handle(29), ), ( uniformity: ( @@ -3051,7 +2615,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(32), + ty: Handle(28), ), ], sampling: [], @@ -3106,7 +2670,7 @@ ref_count: 4, assignable_global: None, ty: Value(Pointer( - base: 22, + base: 21, space: Function, )), ), @@ -3117,7 +2681,7 @@ ), ref_count: 0, assignable_global: None, - ty: Handle(22), + ty: Handle(21), ), ( uniformity: ( @@ -3469,18 +3033,6 @@ ), )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: Some(30), @@ -3516,7 +3068,7 @@ ), ref_count: 0, assignable_global: None, - ty: Handle(22), + ty: Handle(21), ), ( uniformity: ( @@ -3573,17 +3125,17 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(28), + ty: Handle(26), ), ( uniformity: ( - non_uniform_result: Some(41), + non_uniform_result: Some(40), requirements: (""), ), ref_count: 3, assignable_global: None, ty: Value(Pointer( - base: 28, + base: 26, space: Function, )), ), @@ -3610,7 +3162,7 @@ ), ( uniformity: ( - non_uniform_result: Some(41), + non_uniform_result: Some(40), requirements: (""), ), ref_count: 1, @@ -3634,7 +3186,7 @@ ), ( uniformity: ( - non_uniform_result: Some(41), + non_uniform_result: Some(40), requirements: (""), ), ref_count: 1, @@ -3646,7 +3198,7 @@ ), ( uniformity: ( - non_uniform_result: Some(41), + non_uniform_result: Some(40), requirements: (""), ), ref_count: 1, @@ -3660,7 +3212,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(25), + ty: Handle(24), ), ( uniformity: ( @@ -3669,11 +3221,11 @@ ), ref_count: 0, assignable_global: None, - ty: Handle(22), + ty: Handle(21), ), ( uniformity: ( - non_uniform_result: Some(41), + non_uniform_result: Some(40), requirements: (""), ), ref_count: 1, @@ -3686,7 +3238,7 @@ ), ( uniformity: ( - non_uniform_result: Some(41), + non_uniform_result: Some(40), requirements: (""), ), ref_count: 1, @@ -3729,7 +3281,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(26), + ty: Handle(25), ), ], sampling: [], @@ -3781,18 +3333,6 @@ ), )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), ( uniformity: ( non_uniform_result: Some(1), @@ -3839,7 +3379,7 @@ ), ( uniformity: ( - non_uniform_result: Some(7), + non_uniform_result: Some(6), requirements: (""), ), ref_count: 1, @@ -3853,7 +3393,7 @@ ), ( uniformity: ( - non_uniform_result: Some(7), + non_uniform_result: Some(6), requirements: (""), ), ref_count: 1, @@ -3976,7 +3516,7 @@ ), ( uniformity: ( - non_uniform_result: Some(18), + non_uniform_result: Some(17), requirements: (""), ), ref_count: 1, @@ -3990,7 +3530,7 @@ ), ( uniformity: ( - non_uniform_result: Some(18), + non_uniform_result: Some(17), requirements: (""), ), ref_count: 1, @@ -4063,7 +3603,7 @@ ), ( uniformity: ( - non_uniform_result: Some(25), + non_uniform_result: Some(24), requirements: (""), ), ref_count: 1, @@ -4077,7 +3617,7 @@ ), ( uniformity: ( - non_uniform_result: Some(25), + non_uniform_result: Some(24), requirements: (""), ), ref_count: 1, @@ -4091,19 +3631,7 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Value(Scalar( - kind: Sint, - width: 4, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(25), + non_uniform_result: Some(24), requirements: (""), ), ref_count: 1, @@ -4117,7 +3645,7 @@ ), ( uniformity: ( - non_uniform_result: Some(25), + non_uniform_result: Some(24), requirements: (""), ), ref_count: 1, @@ -4143,7 +3671,7 @@ ), ( uniformity: ( - non_uniform_result: Some(31), + non_uniform_result: Some(29), requirements: (""), ), ref_count: 1, @@ -4268,7 +3796,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(32), + ty: Handle(28), ), ( uniformity: ( @@ -4278,7 +3806,7 @@ ref_count: 2, assignable_global: None, ty: Value(Pointer( - base: 32, + base: 28, space: Function, )), ), @@ -4322,65 +3850,5 @@ width: 4, )), Handle(4), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), ], ) \ No newline at end of file diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 7459466e2..15ec6e2b3 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -4,31 +4,15 @@ ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), - ("DATA | SIZED | COPY | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("ARGUMENT"), - ("ARGUMENT"), - ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), - ("SIZED | COPY | ARGUMENT"), - ("SIZED | COPY | ARGUMENT"), ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), - ("SIZED | COPY"), - ("SIZED | COPY"), - ("SIZED | COPY"), + ("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | SIZED | COPY | HOST_SHAREABLE | ARGUMENT | CONSTRUCTIBLE"), ("DATA | COPY | HOST_SHAREABLE"), ("DATA | COPY | HOST_SHAREABLE"), - ("SIZED | COPY"), - ("SIZED | COPY"), - ("SIZED | COPY"), - ("SIZED | COPY"), - ("SIZED | COPY | ARGUMENT"), - ("SIZED | COPY | ARGUMENT"), - ("SIZED | COPY"), - ("SIZED | COPY"), - ("SIZED | COPY | ARGUMENT"), ("ARGUMENT"), ], functions: [ @@ -36,7 +20,7 @@ flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(1), requirements: (""), ), may_kill: false, @@ -58,92 +42,21 @@ expressions: [ ( uniformity: ( - non_uniform_result: None, + non_uniform_result: Some(1), requirements: (""), ), - ref_count: 0, - assignable_global: Some(3), - ty: Value(Pointer( - base: 13, - space: Uniform, - )), + ref_count: 1, + assignable_global: Some(1), + ty: Handle(6), ), ( uniformity: ( non_uniform_result: Some(2), requirements: (""), ), - ref_count: 0, - assignable_global: Some(6), - ty: Value(Pointer( - base: 2, - space: Private, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(3), - requirements: (""), - ), - ref_count: 0, - assignable_global: Some(5), - ty: Value(Pointer( - base: 4, - space: Private, - )), - ), - ( - uniformity: ( - non_uniform_result: Some(4), - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(1), - ty: Handle(7), - ), - ( - uniformity: ( - non_uniform_result: Some(5), - requirements: (""), - ), ref_count: 1, assignable_global: Some(2), - ty: Handle(30), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: Some(4), - ty: Value(Pointer( - base: 20, - space: Storage( - access: ("LOAD"), - ), - )), - ), - ( - uniformity: ( - non_uniform_result: Some(7), - requirements: (""), - ), - ref_count: 0, - assignable_global: Some(7), - ty: Value(Pointer( - base: 4, - space: Private, - )), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), + ty: Handle(14), ), ( uniformity: ( @@ -154,78 +67,6 @@ assignable_global: None, ty: Handle(1), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), ( uniformity: ( non_uniform_result: None, @@ -235,105 +76,6 @@ assignable_global: None, ty: Handle(1), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(1), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(1), - ), ( uniformity: ( non_uniform_result: None, @@ -343,105 +85,6 @@ assignable_global: None, ty: Handle(1), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(2), - ), ( uniformity: ( non_uniform_result: None, @@ -453,7 +96,7 @@ ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(7), requirements: (""), ), ref_count: 1, @@ -462,7 +105,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 6, @@ -471,7 +114,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -483,7 +126,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -495,7 +138,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -507,7 +150,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -519,12 +162,12 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, assignable_global: None, - ty: Handle(6), + ty: Handle(5), ), ( uniformity: ( @@ -533,20 +176,20 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(6), + ty: Handle(5), ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, assignable_global: None, - ty: Handle(6), + ty: Handle(5), ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -558,7 +201,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -567,12 +210,12 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, assignable_global: None, - ty: Handle(6), + ty: Handle(5), ), ( uniformity: ( @@ -589,16 +232,16 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 2, assignable_global: None, - ty: Handle(6), + ty: Handle(5), ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -610,7 +253,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -622,7 +265,7 @@ ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(7), requirements: (""), ), ref_count: 1, @@ -634,7 +277,7 @@ ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(7), requirements: (""), ), ref_count: 1, @@ -646,7 +289,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 3, @@ -655,7 +298,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -667,7 +310,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -679,7 +322,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -688,7 +331,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -697,7 +340,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -709,7 +352,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -721,16 +364,16 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, assignable_global: None, - ty: Handle(6), + ty: Handle(5), ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -742,7 +385,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -754,7 +397,7 @@ ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(1), requirements: (""), ), ref_count: 1, @@ -772,7 +415,7 @@ flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(1), requirements: (""), ), may_kill: false, @@ -800,7 +443,7 @@ ref_count: 1, assignable_global: Some(3), ty: Value(Pointer( - base: 13, + base: 9, space: Uniform, )), ), @@ -828,24 +471,6 @@ space: Private, )), ), - ( - uniformity: ( - non_uniform_result: Some(4), - requirements: (""), - ), - ref_count: 0, - assignable_global: Some(1), - ty: Handle(7), - ), - ( - uniformity: ( - non_uniform_result: Some(5), - requirements: (""), - ), - ref_count: 0, - assignable_global: Some(2), - ty: Handle(30), - ), ( uniformity: ( non_uniform_result: None, @@ -854,7 +479,7 @@ ref_count: 7, assignable_global: Some(4), ty: Value(Pointer( - base: 20, + base: 13, space: Storage( access: ("LOAD"), ), @@ -862,7 +487,7 @@ ), ( uniformity: ( - non_uniform_result: Some(7), + non_uniform_result: Some(5), requirements: (""), ), ref_count: 1, @@ -877,18 +502,9 @@ non_uniform_result: None, requirements: (""), ), - ref_count: 0, + ref_count: 1, assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(1), + ty: Handle(7), ), ( uniformity: ( @@ -897,16 +513,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), + ty: Handle(7), ), ( uniformity: ( @@ -915,7 +522,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), + ty: Handle(7), ), ( uniformity: ( @@ -924,52 +531,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(1), + ty: Handle(7), ), ( uniformity: ( @@ -978,34 +540,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(1), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), + ty: Handle(7), ), ( uniformity: ( @@ -1014,34 +549,7 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(9), + ty: Handle(7), ), ( uniformity: ( @@ -1066,10 +574,46 @@ non_uniform_result: None, requirements: (""), ), - ref_count: 0, + ref_count: 1, assignable_global: None, ty: Handle(1), ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(7), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(7), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(7), + ), + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(7), + ), ( uniformity: ( non_uniform_result: None, @@ -1081,115 +625,7 @@ ), ( uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(9), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 0, - assignable_global: None, - ty: Handle(2), - ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: None, - ty: Handle(1), - ), - ( - uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(20), requirements: (""), ), ref_count: 3, @@ -1201,7 +637,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 11, @@ -1213,7 +649,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1228,7 +664,7 @@ ref_count: 1, assignable_global: Some(3), ty: Value(Pointer( - base: 12, + base: 8, space: Uniform, )), ), @@ -1272,7 +708,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1284,7 +720,7 @@ ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(20), requirements: (""), ), ref_count: 1, @@ -1293,7 +729,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1308,7 +744,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 12, space: Storage( access: ("LOAD"), ), @@ -1316,7 +752,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1325,13 +761,13 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 18, + base: 11, space: Storage( access: ("LOAD"), ), @@ -1339,13 +775,13 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 17, + base: 10, space: Storage( access: ("LOAD"), ), @@ -1353,12 +789,12 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, assignable_global: None, - ty: Handle(17), + ty: Handle(10), ), ( uniformity: ( @@ -1371,7 +807,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1384,7 +820,7 @@ ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(1), requirements: (""), ), ref_count: 1, @@ -1417,7 +853,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 12, space: Storage( access: ("LOAD"), ), @@ -1425,7 +861,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1434,13 +870,13 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 18, + base: 11, space: Storage( access: ("LOAD"), ), @@ -1448,7 +884,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1462,7 +898,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1478,7 +914,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1496,7 +932,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 12, space: Storage( access: ("LOAD"), ), @@ -1504,7 +940,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1513,13 +949,13 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 18, + base: 11, space: Storage( access: ("LOAD"), ), @@ -1527,7 +963,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1541,7 +977,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1557,7 +993,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1575,7 +1011,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 12, space: Storage( access: ("LOAD"), ), @@ -1583,7 +1019,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1592,13 +1028,13 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 18, + base: 11, space: Storage( access: ("LOAD"), ), @@ -1606,7 +1042,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1620,7 +1056,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1636,7 +1072,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1648,7 +1084,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1744,7 +1180,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1753,7 +1189,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1783,7 +1219,7 @@ ), ( uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(1), requirements: (""), ), ref_count: 1, @@ -1798,7 +1234,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 12, space: Storage( access: ("LOAD"), ), @@ -1806,7 +1242,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1815,13 +1251,13 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 18, + base: 11, space: Storage( access: ("LOAD"), ), @@ -1829,7 +1265,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1843,7 +1279,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1859,7 +1295,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1877,7 +1313,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 12, space: Storage( access: ("LOAD"), ), @@ -1885,7 +1321,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1894,13 +1330,13 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 18, + base: 11, space: Storage( access: ("LOAD"), ), @@ -1908,7 +1344,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1922,7 +1358,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1938,7 +1374,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1956,7 +1392,7 @@ ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 19, + base: 12, space: Storage( access: ("LOAD"), ), @@ -1964,7 +1400,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1973,13 +1409,13 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, assignable_global: Some(4), ty: Value(Pointer( - base: 18, + base: 11, space: Storage( access: ("LOAD"), ), @@ -1987,7 +1423,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -2001,7 +1437,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -2017,7 +1453,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -2029,7 +1465,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -2038,7 +1474,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -2047,7 +1483,7 @@ ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(20), requirements: (""), ), ref_count: 1, @@ -2056,7 +1492,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -2065,7 +1501,7 @@ ), ( uniformity: ( - non_uniform_result: Some(44), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -2074,7 +1510,7 @@ ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(20), requirements: (""), ), ref_count: 1, @@ -2083,7 +1519,7 @@ ), ( uniformity: ( - non_uniform_result: Some(43), + non_uniform_result: Some(20), requirements: (""), ), ref_count: 1, @@ -2100,7 +1536,7 @@ flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), available_stages: ("VERTEX | FRAGMENT | COMPUTE"), uniformity: ( - non_uniform_result: Some(4), + non_uniform_result: Some(1), requirements: (""), ), may_kill: false, @@ -2225,70 +1661,6 @@ kind: Uint, width: 4, )), - Value(Scalar( - kind: Float, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), - Value(Scalar( - kind: Sint, - width: 4, - )), Value(Scalar( kind: Sint, width: 4, diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index a25eda03b..a505ee19e 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -41,31 +41,31 @@ void test_matrix_within_struct_accesses() { idx = (_e3 - 1); mat3x2 l0_ = _group_0_binding_1_vs.m; vec2 l1_ = _group_0_binding_1_vs.m[0]; - int _e15 = idx; - vec2 l2_ = _group_0_binding_1_vs.m[_e15]; + int _e14 = idx; + vec2 l2_ = _group_0_binding_1_vs.m[_e14]; float l3_ = _group_0_binding_1_vs.m[0][1]; - int _e29 = idx; - float l4_ = _group_0_binding_1_vs.m[0][_e29]; - int _e34 = idx; - float l5_ = _group_0_binding_1_vs.m[_e34][1]; - int _e41 = idx; - int _e43 = idx; - float l6_ = _group_0_binding_1_vs.m[_e41][_e43]; + int _e25 = idx; + float l4_ = _group_0_binding_1_vs.m[0][_e25]; + int _e30 = idx; + float l5_ = _group_0_binding_1_vs.m[_e30][1]; + int _e36 = idx; + int _e38 = idx; + float l6_ = _group_0_binding_1_vs.m[_e36][_e38]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - int _e56 = idx; - idx = (_e56 + 1); + int _e51 = idx; + idx = (_e51 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - int _e72 = idx; - t.m[_e72] = vec2(90.0); + int _e66 = idx; + t.m[_e66] = vec2(90.0); t.m[0][1] = 10.0; + int _e76 = idx; + t.m[0][_e76] = 20.0; + int _e80 = idx; + t.m[_e80][1] = 30.0; int _e85 = idx; - t.m[0][_e85] = 20.0; - int _e89 = idx; - t.m[_e89][1] = 30.0; - int _e95 = idx; - int _e97 = idx; - t.m[_e95][_e97] = 40.0; + int _e87 = idx; + t.m[_e85][_e87] = 40.0; return; } @@ -78,32 +78,32 @@ void test_matrix_within_array_within_struct_accesses() { mat4x2 l0_1[2] = _group_0_binding_3_vs.am; mat4x2 l1_1 = _group_0_binding_3_vs.am[0]; vec2 l2_1 = _group_0_binding_3_vs.am[0][0]; - int _e24 = idx_1; - vec2 l3_1 = _group_0_binding_3_vs.am[0][_e24]; + int _e20 = idx_1; + vec2 l3_1 = _group_0_binding_3_vs.am[0][_e20]; float l4_1 = _group_0_binding_3_vs.am[0][0][1]; - int _e42 = idx_1; - float l5_1 = _group_0_binding_3_vs.am[0][0][_e42]; - int _e49 = idx_1; - float l6_1 = _group_0_binding_3_vs.am[0][_e49][1]; - int _e58 = idx_1; - int _e60 = idx_1; - float l7_ = _group_0_binding_3_vs.am[0][_e58][_e60]; + int _e33 = idx_1; + float l5_1 = _group_0_binding_3_vs.am[0][0][_e33]; + int _e39 = idx_1; + float l6_1 = _group_0_binding_3_vs.am[0][_e39][1]; + int _e46 = idx_1; + int _e48 = idx_1; + float l7_ = _group_0_binding_3_vs.am[0][_e46][_e48]; t_1 = MatCx2InArray(mat4x2[2](mat4x2(0.0), mat4x2(0.0))); - int _e67 = idx_1; - idx_1 = (_e67 + 1); + int _e55 = idx_1; + idx_1 = (_e55 + 1); t_1.am = mat4x2[2](mat4x2(0.0), mat4x2(0.0)); t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); t_1.am[0][0] = vec2(9.0); - int _e93 = idx_1; - t_1.am[0][_e93] = vec2(90.0); + int _e77 = idx_1; + t_1.am[0][_e77] = vec2(90.0); t_1.am[0][0][1] = 10.0; - int _e110 = idx_1; - t_1.am[0][0][_e110] = 20.0; - int _e116 = idx_1; - t_1.am[0][_e116][1] = 30.0; - int _e124 = idx_1; - int _e126 = idx_1; - t_1.am[0][_e124][_e126] = 40.0; + int _e89 = idx_1; + t_1.am[0][0][_e89] = 20.0; + int _e94 = idx_1; + t_1.am[0][_e94][1] = 30.0; + int _e100 = idx_1; + int _e102 = idx_1; + t_1.am[0][_e100][_e102] = 40.0; return; } @@ -140,11 +140,11 @@ void main() { float b = _group_0_binding_0_vs._matrix[3][0]; int a_1 = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; ivec2 c = _group_0_binding_2_vs; - float _e34 = read_from_private(foo); + float _e33 = read_from_private(foo); c2_ = int[5](a_1, int(b), 3, 4, 5); c2_[(vi + 1u)] = 42; int value = c2_[vi]; - float _e48 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); + float _e47 = test_arr_as_arg(float[5][10](float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), float[10](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))); gl_Position = vec4((_matrix * vec4(ivec4(value))), 2.0); gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); return; diff --git a/tests/out/glsl/atomicOps.cs_main.Compute.glsl b/tests/out/glsl/atomicOps.cs_main.Compute.glsl index c40e85d30..b69c5107c 100644 --- a/tests/out/glsl/atomicOps.cs_main.Compute.glsl +++ b/tests/out/glsl/atomicOps.cs_main.Compute.glsl @@ -51,82 +51,82 @@ void main() { int l7_ = workgroup_struct.atomic_arr[1]; memoryBarrierShared(); barrier(); - uint _e59 = atomicAdd(_group_0_binding_0_cs, 1u); - int _e64 = atomicAdd(_group_0_binding_1_cs[1], 1); - uint _e68 = atomicAdd(_group_0_binding_2_cs.atomic_scalar, 1u); - int _e74 = atomicAdd(_group_0_binding_2_cs.atomic_arr[1], 1); - uint _e77 = atomicAdd(workgroup_atomic_scalar, 1u); - int _e82 = atomicAdd(workgroup_atomic_arr[1], 1); - uint _e86 = atomicAdd(workgroup_struct.atomic_scalar, 1u); - int _e92 = atomicAdd(workgroup_struct.atomic_arr[1], 1); + uint _e51 = atomicAdd(_group_0_binding_0_cs, 1u); + int _e55 = atomicAdd(_group_0_binding_1_cs[1], 1); + uint _e59 = atomicAdd(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e64 = atomicAdd(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e67 = atomicAdd(workgroup_atomic_scalar, 1u); + int _e71 = atomicAdd(workgroup_atomic_arr[1], 1); + uint _e75 = atomicAdd(workgroup_struct.atomic_scalar, 1u); + int _e80 = atomicAdd(workgroup_struct.atomic_arr[1], 1); memoryBarrierShared(); barrier(); - uint _e95 = atomicAdd(_group_0_binding_0_cs, -1u); - int _e100 = atomicAdd(_group_0_binding_1_cs[1], -1); - uint _e104 = atomicAdd(_group_0_binding_2_cs.atomic_scalar, -1u); - int _e110 = atomicAdd(_group_0_binding_2_cs.atomic_arr[1], -1); - uint _e113 = atomicAdd(workgroup_atomic_scalar, -1u); - int _e118 = atomicAdd(workgroup_atomic_arr[1], -1); - uint _e122 = atomicAdd(workgroup_struct.atomic_scalar, -1u); - int _e128 = atomicAdd(workgroup_struct.atomic_arr[1], -1); + uint _e83 = atomicAdd(_group_0_binding_0_cs, -1u); + int _e87 = atomicAdd(_group_0_binding_1_cs[1], -1); + uint _e91 = atomicAdd(_group_0_binding_2_cs.atomic_scalar, -1u); + int _e96 = atomicAdd(_group_0_binding_2_cs.atomic_arr[1], -1); + uint _e99 = atomicAdd(workgroup_atomic_scalar, -1u); + int _e103 = atomicAdd(workgroup_atomic_arr[1], -1); + uint _e107 = atomicAdd(workgroup_struct.atomic_scalar, -1u); + int _e112 = atomicAdd(workgroup_struct.atomic_arr[1], -1); memoryBarrierShared(); barrier(); - uint _e131 = atomicMax(_group_0_binding_0_cs, 1u); - int _e136 = atomicMax(_group_0_binding_1_cs[1], 1); - uint _e140 = atomicMax(_group_0_binding_2_cs.atomic_scalar, 1u); - int _e146 = atomicMax(_group_0_binding_2_cs.atomic_arr[1], 1); - uint _e149 = atomicMax(workgroup_atomic_scalar, 1u); - int _e154 = atomicMax(workgroup_atomic_arr[1], 1); - uint _e158 = atomicMax(workgroup_struct.atomic_scalar, 1u); - int _e164 = atomicMax(workgroup_struct.atomic_arr[1], 1); + uint _e115 = atomicMax(_group_0_binding_0_cs, 1u); + int _e119 = atomicMax(_group_0_binding_1_cs[1], 1); + uint _e123 = atomicMax(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e128 = atomicMax(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e131 = atomicMax(workgroup_atomic_scalar, 1u); + int _e135 = atomicMax(workgroup_atomic_arr[1], 1); + uint _e139 = atomicMax(workgroup_struct.atomic_scalar, 1u); + int _e144 = atomicMax(workgroup_struct.atomic_arr[1], 1); memoryBarrierShared(); barrier(); - uint _e167 = atomicMin(_group_0_binding_0_cs, 1u); - int _e172 = atomicMin(_group_0_binding_1_cs[1], 1); - uint _e176 = atomicMin(_group_0_binding_2_cs.atomic_scalar, 1u); - int _e182 = atomicMin(_group_0_binding_2_cs.atomic_arr[1], 1); - uint _e185 = atomicMin(workgroup_atomic_scalar, 1u); - int _e190 = atomicMin(workgroup_atomic_arr[1], 1); - uint _e194 = atomicMin(workgroup_struct.atomic_scalar, 1u); - int _e200 = atomicMin(workgroup_struct.atomic_arr[1], 1); + uint _e147 = atomicMin(_group_0_binding_0_cs, 1u); + int _e151 = atomicMin(_group_0_binding_1_cs[1], 1); + uint _e155 = atomicMin(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e160 = atomicMin(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e163 = atomicMin(workgroup_atomic_scalar, 1u); + int _e167 = atomicMin(workgroup_atomic_arr[1], 1); + uint _e171 = atomicMin(workgroup_struct.atomic_scalar, 1u); + int _e176 = atomicMin(workgroup_struct.atomic_arr[1], 1); memoryBarrierShared(); barrier(); - uint _e203 = atomicAnd(_group_0_binding_0_cs, 1u); - int _e208 = atomicAnd(_group_0_binding_1_cs[1], 1); - uint _e212 = atomicAnd(_group_0_binding_2_cs.atomic_scalar, 1u); - int _e218 = atomicAnd(_group_0_binding_2_cs.atomic_arr[1], 1); - uint _e221 = atomicAnd(workgroup_atomic_scalar, 1u); - int _e226 = atomicAnd(workgroup_atomic_arr[1], 1); - uint _e230 = atomicAnd(workgroup_struct.atomic_scalar, 1u); - int _e236 = atomicAnd(workgroup_struct.atomic_arr[1], 1); + uint _e179 = atomicAnd(_group_0_binding_0_cs, 1u); + int _e183 = atomicAnd(_group_0_binding_1_cs[1], 1); + uint _e187 = atomicAnd(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e192 = atomicAnd(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e195 = atomicAnd(workgroup_atomic_scalar, 1u); + int _e199 = atomicAnd(workgroup_atomic_arr[1], 1); + uint _e203 = atomicAnd(workgroup_struct.atomic_scalar, 1u); + int _e208 = atomicAnd(workgroup_struct.atomic_arr[1], 1); memoryBarrierShared(); barrier(); - uint _e239 = atomicOr(_group_0_binding_0_cs, 1u); - int _e244 = atomicOr(_group_0_binding_1_cs[1], 1); - uint _e248 = atomicOr(_group_0_binding_2_cs.atomic_scalar, 1u); - int _e254 = atomicOr(_group_0_binding_2_cs.atomic_arr[1], 1); - uint _e257 = atomicOr(workgroup_atomic_scalar, 1u); - int _e262 = atomicOr(workgroup_atomic_arr[1], 1); - uint _e266 = atomicOr(workgroup_struct.atomic_scalar, 1u); - int _e272 = atomicOr(workgroup_struct.atomic_arr[1], 1); + uint _e211 = atomicOr(_group_0_binding_0_cs, 1u); + int _e215 = atomicOr(_group_0_binding_1_cs[1], 1); + uint _e219 = atomicOr(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e224 = atomicOr(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e227 = atomicOr(workgroup_atomic_scalar, 1u); + int _e231 = atomicOr(workgroup_atomic_arr[1], 1); + uint _e235 = atomicOr(workgroup_struct.atomic_scalar, 1u); + int _e240 = atomicOr(workgroup_struct.atomic_arr[1], 1); memoryBarrierShared(); barrier(); - uint _e275 = atomicXor(_group_0_binding_0_cs, 1u); - int _e280 = atomicXor(_group_0_binding_1_cs[1], 1); - uint _e284 = atomicXor(_group_0_binding_2_cs.atomic_scalar, 1u); - int _e290 = atomicXor(_group_0_binding_2_cs.atomic_arr[1], 1); - uint _e293 = atomicXor(workgroup_atomic_scalar, 1u); - int _e298 = atomicXor(workgroup_atomic_arr[1], 1); - uint _e302 = atomicXor(workgroup_struct.atomic_scalar, 1u); - int _e308 = atomicXor(workgroup_struct.atomic_arr[1], 1); - uint _e311 = atomicExchange(_group_0_binding_0_cs, 1u); - int _e316 = atomicExchange(_group_0_binding_1_cs[1], 1); - uint _e320 = atomicExchange(_group_0_binding_2_cs.atomic_scalar, 1u); - int _e326 = atomicExchange(_group_0_binding_2_cs.atomic_arr[1], 1); - uint _e329 = atomicExchange(workgroup_atomic_scalar, 1u); - int _e334 = atomicExchange(workgroup_atomic_arr[1], 1); - uint _e338 = atomicExchange(workgroup_struct.atomic_scalar, 1u); - int _e344 = atomicExchange(workgroup_struct.atomic_arr[1], 1); + uint _e243 = atomicXor(_group_0_binding_0_cs, 1u); + int _e247 = atomicXor(_group_0_binding_1_cs[1], 1); + uint _e251 = atomicXor(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e256 = atomicXor(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e259 = atomicXor(workgroup_atomic_scalar, 1u); + int _e263 = atomicXor(workgroup_atomic_arr[1], 1); + uint _e267 = atomicXor(workgroup_struct.atomic_scalar, 1u); + int _e272 = atomicXor(workgroup_struct.atomic_arr[1], 1); + uint _e275 = atomicExchange(_group_0_binding_0_cs, 1u); + int _e279 = atomicExchange(_group_0_binding_1_cs[1], 1); + uint _e283 = atomicExchange(_group_0_binding_2_cs.atomic_scalar, 1u); + int _e288 = atomicExchange(_group_0_binding_2_cs.atomic_arr[1], 1); + uint _e291 = atomicExchange(workgroup_atomic_scalar, 1u); + int _e295 = atomicExchange(workgroup_atomic_arr[1], 1); + uint _e299 = atomicExchange(workgroup_struct.atomic_scalar, 1u); + int _e304 = atomicExchange(workgroup_struct.atomic_arr[1], 1); return; } diff --git a/tests/out/glsl/do-while.main.Fragment.glsl b/tests/out/glsl/do-while.main.Fragment.glsl index 50e9a4897..fb8f6e1ef 100644 --- a/tests/out/glsl/do-while.main.Fragment.glsl +++ b/tests/out/glsl/do-while.main.Fragment.glsl @@ -8,8 +8,8 @@ void fb1_(inout bool cond) { bool loop_init = true; while(true) { if (!loop_init) { - bool _e2 = cond; - if (!(_e2)) { + bool _e1 = cond; + if (!(_e1)) { break; } } diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index d1b234734..b5e36f541 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -40,8 +40,8 @@ void test_msl_packed_vec3_() { idx = 1; _group_0_binding_1_cs.v3_.x = 1.0; _group_0_binding_1_cs.v3_.x = 2.0; - int _e17 = idx; - _group_0_binding_1_cs.v3_[_e17] = 3.0; + int _e16 = idx; + _group_0_binding_1_cs.v3_[_e16] = 3.0; FooStruct data = _group_0_binding_1_cs; vec3 l0_ = data.v3_; vec2 l1_ = data.v3_.zx; @@ -62,20 +62,20 @@ void main() { float Foo = 0.0; bool at = false; test_msl_packed_vec3_(); - mat4x2 _e8 = _group_0_binding_7_cs[0][0]; - vec4 _e16 = _group_0_binding_6_cs[0][0][0]; - wg[7] = (_e8 * _e16).x; - mat3x2 _e23 = _group_0_binding_5_cs; - vec3 _e25 = _group_0_binding_4_cs; - wg[6] = (_e23 * _e25).x; - float _e35 = _group_0_binding_2_cs[1].y; - wg[5] = _e35; - float _e43 = _group_0_binding_3_cs[0].w; - wg[4] = _e43; - float _e49 = _group_0_binding_1_cs.v1_; - wg[3] = _e49; - float _e56 = _group_0_binding_1_cs.v3_.x; - wg[2] = _e56; + mat4x2 _e5 = _group_0_binding_7_cs[0][0]; + vec4 _e10 = _group_0_binding_6_cs[0][0][0]; + wg[7] = (_e5 * _e10).x; + mat3x2 _e16 = _group_0_binding_5_cs; + vec3 _e18 = _group_0_binding_4_cs; + wg[6] = (_e16 * _e18).x; + float _e26 = _group_0_binding_2_cs[1].y; + wg[5] = _e26; + float _e32 = _group_0_binding_3_cs[0].w; + wg[4] = _e32; + float _e37 = _group_0_binding_1_cs.v1_; + wg[3] = _e37; + float _e43 = _group_0_binding_1_cs.v3_.x; + wg[2] = _e43; _group_0_binding_1_cs.v1_ = 4.0; wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 5adfec2f8..ba3734be1 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -229,10 +229,10 @@ void assignment() { int _e36 = a_1; a_1 = (_e36 - 1); vec0_ = ivec3(0); - int _e43 = vec0_.y; - vec0_.y = (_e43 + 1); - int _e48 = vec0_.y; - vec0_.y = (_e48 - 1); + int _e42 = vec0_.y; + vec0_.y = (_e42 + 1); + int _e46 = vec0_.y; + vec0_.y = (_e46 - 1); return; } diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl index eec208cdc..db5089c2d 100644 --- a/tests/out/glsl/quad-vert.main.Vertex.glsl +++ b/tests/out/glsl/quad-vert.main.Vertex.glsl @@ -9,7 +9,7 @@ struct gen_gl_PerVertex { float gen_gl_ClipDistance[1]; float gen_gl_CullDistance[1]; }; -struct type_9 { +struct type_4 { vec2 member; vec4 gen_gl_Position; }; @@ -26,10 +26,10 @@ layout(location = 0) in vec2 _p2vs_location0; layout(location = 0) smooth out vec2 _vs2fs_location0; void main_1() { - vec2 _e8 = a_uv_1; - v_uv = _e8; - vec2 _e9 = a_pos_1; - perVertexStruct.gen_gl_Position = vec4(_e9.x, _e9.y, 0.0, 1.0); + vec2 _e6 = a_uv_1; + v_uv = _e6; + vec2 _e7 = a_pos_1; + perVertexStruct.gen_gl_Position = vec4(_e7.x, _e7.y, 0.0, 1.0); return; } @@ -41,7 +41,7 @@ void main() { main_1(); vec2 _e7 = v_uv; vec4 _e8 = perVertexStruct.gen_gl_Position; - type_9 _tmp_return = type_9(_e7, _e8); + type_4 _tmp_return = type_4(_e7, _e8); _vs2fs_location0 = _tmp_return.member; gl_Position = _tmp_return.gen_gl_Position; gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w); diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 5fdd97fbc..465643bb4 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -127,31 +127,31 @@ void test_matrix_within_struct_accesses() idx = (_expr3 - 1); float3x2 l0_ = GetMatmOnBaz(baz); float2 l1_ = GetMatmOnBaz(baz)[0]; - int _expr15 = idx; - float2 l2_ = GetMatmOnBaz(baz)[_expr15]; + int _expr14 = idx; + float2 l2_ = GetMatmOnBaz(baz)[_expr14]; float l3_ = GetMatmOnBaz(baz)[0].y; - int _expr29 = idx; - float l4_ = GetMatmOnBaz(baz)[0][_expr29]; - int _expr34 = idx; - float l5_ = GetMatmOnBaz(baz)[_expr34].y; - int _expr41 = idx; - int _expr43 = idx; - float l6_ = GetMatmOnBaz(baz)[_expr41][_expr43]; + int _expr25 = idx; + float l4_ = GetMatmOnBaz(baz)[0][_expr25]; + int _expr30 = idx; + float l5_ = GetMatmOnBaz(baz)[_expr30].y; + int _expr36 = idx; + int _expr38 = idx; + float l6_ = GetMatmOnBaz(baz)[_expr36][_expr38]; t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); - int _expr56 = idx; - idx = (_expr56 + 1); + int _expr51 = idx; + idx = (_expr51 + 1); SetMatmOnBaz(t, float3x2((6.0).xx, (5.0).xx, (4.0).xx)); t.m_0 = (9.0).xx; - int _expr72 = idx; - SetMatVecmOnBaz(t, (90.0).xx, _expr72); + int _expr66 = idx; + SetMatVecmOnBaz(t, (90.0).xx, _expr66); t.m_0[1] = 10.0; + int _expr76 = idx; + t.m_0[_expr76] = 20.0; + int _expr80 = idx; + SetMatScalarmOnBaz(t, 30.0, _expr80, 1); int _expr85 = idx; - t.m_0[_expr85] = 20.0; - int _expr89 = idx; - SetMatScalarmOnBaz(t, 30.0, _expr89, 1); - int _expr95 = idx; - int _expr97 = idx; - SetMatScalarmOnBaz(t, 40.0, _expr95, _expr97); + int _expr87 = idx; + SetMatScalarmOnBaz(t, 40.0, _expr85, _expr87); return; } @@ -172,32 +172,32 @@ void test_matrix_within_array_within_struct_accesses() float4x2 l0_1[2] = ((float4x2[2])nested_mat_cx2_.am); float4x2 l1_1 = ((float4x2)nested_mat_cx2_.am[0]); float2 l2_1 = nested_mat_cx2_.am[0]._0; - int _expr24 = idx_1; - float2 l3_1 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr24); + int _expr20 = idx_1; + float2 l3_1 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr20); float l4_1 = nested_mat_cx2_.am[0]._0.y; - int _expr42 = idx_1; - float l5_1 = nested_mat_cx2_.am[0]._0[_expr42]; - int _expr49 = idx_1; - float l6_1 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr49).y; - int _expr58 = idx_1; - int _expr60 = idx_1; - float l7_ = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr58)[_expr60]; + int _expr33 = idx_1; + float l5_1 = nested_mat_cx2_.am[0]._0[_expr33]; + int _expr39 = idx_1; + float l6_1 = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr39).y; + int _expr46 = idx_1; + int _expr48 = idx_1; + float l7_ = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr46)[_expr48]; t_1 = ConstructMatCx2InArray((float4x2[2])0); - int _expr67 = idx_1; - idx_1 = (_expr67 + 1); + int _expr55 = idx_1; + idx_1 = (_expr55 + 1); t_1.am = (__mat4x2[2])(float4x2[2])0; t_1.am[0] = (__mat4x2)float4x2((8.0).xx, (7.0).xx, (6.0).xx, (5.0).xx); t_1.am[0]._0 = (9.0).xx; - int _expr93 = idx_1; - __set_col_of_mat4x2(t_1.am[0], _expr93, (90.0).xx); + int _expr77 = idx_1; + __set_col_of_mat4x2(t_1.am[0], _expr77, (90.0).xx); t_1.am[0]._0.y = 10.0; - int _expr110 = idx_1; - t_1.am[0]._0[_expr110] = 20.0; - int _expr116 = idx_1; - __set_el_of_mat4x2(t_1.am[0], _expr116, 1, 30.0); - int _expr124 = idx_1; - int _expr126 = idx_1; - __set_el_of_mat4x2(t_1.am[0], _expr124, _expr126, 40.0); + int _expr89 = idx_1; + t_1.am[0]._0[_expr89] = 20.0; + int _expr94 = idx_1; + __set_el_of_mat4x2(t_1.am[0], _expr94, 1, 30.0); + int _expr100 = idx_1; + int _expr102 = idx_1; + __set_el_of_mat4x2(t_1.am[0], _expr100, _expr102, 40.0); return; } @@ -264,11 +264,11 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position float b = asfloat(bar.Load(0+48+0)); int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 160) / 8) - 2u)*8+160)); int2 c = asint(qux.Load2(0)); - const float _e34 = read_from_private(foo); + const float _e33 = read_from_private(foo); c2_ = Constructarray5_int_(a_1, int(b), 3, 4, 5); c2_[(vi + 1u)] = 42; int value = c2_[vi]; - const float _e48 = test_arr_as_arg((float[5][10])0); + const float _e47 = test_arr_as_arg((float[5][10])0); return float4(mul(float4((value).xxxx), _matrix), 2.0); } diff --git a/tests/out/hlsl/atomicOps.hlsl b/tests/out/hlsl/atomicOps.hlsl index 0363920b3..640972a2f 100644 --- a/tests/out/hlsl/atomicOps.hlsl +++ b/tests/out/hlsl/atomicOps.hlsl @@ -37,75 +37,75 @@ void cs_main(uint3 id : SV_GroupThreadID, uint3 __local_invocation_id : SV_Group uint l6_ = workgroup_struct.atomic_scalar; int l7_ = workgroup_struct.atomic_arr[1]; GroupMemoryBarrierWithGroupSync(); - uint _e59; storage_atomic_scalar.InterlockedAdd(0, 1u, _e59); - int _e64; storage_atomic_arr.InterlockedAdd(4, 1, _e64); - uint _e68; storage_struct.InterlockedAdd(0, 1u, _e68); - int _e74; storage_struct.InterlockedAdd(4+4, 1, _e74); - uint _e77; InterlockedAdd(workgroup_atomic_scalar, 1u, _e77); - int _e82; InterlockedAdd(workgroup_atomic_arr[1], 1, _e82); - uint _e86; InterlockedAdd(workgroup_struct.atomic_scalar, 1u, _e86); - int _e92; InterlockedAdd(workgroup_struct.atomic_arr[1], 1, _e92); + uint _e51; storage_atomic_scalar.InterlockedAdd(0, 1u, _e51); + int _e55; storage_atomic_arr.InterlockedAdd(4, 1, _e55); + uint _e59; storage_struct.InterlockedAdd(0, 1u, _e59); + int _e64; storage_struct.InterlockedAdd(4+4, 1, _e64); + uint _e67; InterlockedAdd(workgroup_atomic_scalar, 1u, _e67); + int _e71; InterlockedAdd(workgroup_atomic_arr[1], 1, _e71); + uint _e75; InterlockedAdd(workgroup_struct.atomic_scalar, 1u, _e75); + int _e80; InterlockedAdd(workgroup_struct.atomic_arr[1], 1, _e80); GroupMemoryBarrierWithGroupSync(); - uint _e95; storage_atomic_scalar.InterlockedAdd(0, -1u, _e95); - int _e100; storage_atomic_arr.InterlockedAdd(4, -1, _e100); - uint _e104; storage_struct.InterlockedAdd(0, -1u, _e104); - int _e110; storage_struct.InterlockedAdd(4+4, -1, _e110); - uint _e113; InterlockedAdd(workgroup_atomic_scalar, -1u, _e113); - int _e118; InterlockedAdd(workgroup_atomic_arr[1], -1, _e118); - uint _e122; InterlockedAdd(workgroup_struct.atomic_scalar, -1u, _e122); - int _e128; InterlockedAdd(workgroup_struct.atomic_arr[1], -1, _e128); + uint _e83; storage_atomic_scalar.InterlockedAdd(0, -1u, _e83); + int _e87; storage_atomic_arr.InterlockedAdd(4, -1, _e87); + uint _e91; storage_struct.InterlockedAdd(0, -1u, _e91); + int _e96; storage_struct.InterlockedAdd(4+4, -1, _e96); + uint _e99; InterlockedAdd(workgroup_atomic_scalar, -1u, _e99); + int _e103; InterlockedAdd(workgroup_atomic_arr[1], -1, _e103); + uint _e107; InterlockedAdd(workgroup_struct.atomic_scalar, -1u, _e107); + int _e112; InterlockedAdd(workgroup_struct.atomic_arr[1], -1, _e112); GroupMemoryBarrierWithGroupSync(); - uint _e131; storage_atomic_scalar.InterlockedMax(0, 1u, _e131); - int _e136; storage_atomic_arr.InterlockedMax(4, 1, _e136); - uint _e140; storage_struct.InterlockedMax(0, 1u, _e140); - int _e146; storage_struct.InterlockedMax(4+4, 1, _e146); - uint _e149; InterlockedMax(workgroup_atomic_scalar, 1u, _e149); - int _e154; InterlockedMax(workgroup_atomic_arr[1], 1, _e154); - uint _e158; InterlockedMax(workgroup_struct.atomic_scalar, 1u, _e158); - int _e164; InterlockedMax(workgroup_struct.atomic_arr[1], 1, _e164); + uint _e115; storage_atomic_scalar.InterlockedMax(0, 1u, _e115); + int _e119; storage_atomic_arr.InterlockedMax(4, 1, _e119); + uint _e123; storage_struct.InterlockedMax(0, 1u, _e123); + int _e128; storage_struct.InterlockedMax(4+4, 1, _e128); + uint _e131; InterlockedMax(workgroup_atomic_scalar, 1u, _e131); + int _e135; InterlockedMax(workgroup_atomic_arr[1], 1, _e135); + uint _e139; InterlockedMax(workgroup_struct.atomic_scalar, 1u, _e139); + int _e144; InterlockedMax(workgroup_struct.atomic_arr[1], 1, _e144); GroupMemoryBarrierWithGroupSync(); - uint _e167; storage_atomic_scalar.InterlockedMin(0, 1u, _e167); - int _e172; storage_atomic_arr.InterlockedMin(4, 1, _e172); - uint _e176; storage_struct.InterlockedMin(0, 1u, _e176); - int _e182; storage_struct.InterlockedMin(4+4, 1, _e182); - uint _e185; InterlockedMin(workgroup_atomic_scalar, 1u, _e185); - int _e190; InterlockedMin(workgroup_atomic_arr[1], 1, _e190); - uint _e194; InterlockedMin(workgroup_struct.atomic_scalar, 1u, _e194); - int _e200; InterlockedMin(workgroup_struct.atomic_arr[1], 1, _e200); + uint _e147; storage_atomic_scalar.InterlockedMin(0, 1u, _e147); + int _e151; storage_atomic_arr.InterlockedMin(4, 1, _e151); + uint _e155; storage_struct.InterlockedMin(0, 1u, _e155); + int _e160; storage_struct.InterlockedMin(4+4, 1, _e160); + uint _e163; InterlockedMin(workgroup_atomic_scalar, 1u, _e163); + int _e167; InterlockedMin(workgroup_atomic_arr[1], 1, _e167); + uint _e171; InterlockedMin(workgroup_struct.atomic_scalar, 1u, _e171); + int _e176; InterlockedMin(workgroup_struct.atomic_arr[1], 1, _e176); GroupMemoryBarrierWithGroupSync(); - uint _e203; storage_atomic_scalar.InterlockedAnd(0, 1u, _e203); - int _e208; storage_atomic_arr.InterlockedAnd(4, 1, _e208); - uint _e212; storage_struct.InterlockedAnd(0, 1u, _e212); - int _e218; storage_struct.InterlockedAnd(4+4, 1, _e218); - uint _e221; InterlockedAnd(workgroup_atomic_scalar, 1u, _e221); - int _e226; InterlockedAnd(workgroup_atomic_arr[1], 1, _e226); - uint _e230; InterlockedAnd(workgroup_struct.atomic_scalar, 1u, _e230); - int _e236; InterlockedAnd(workgroup_struct.atomic_arr[1], 1, _e236); + uint _e179; storage_atomic_scalar.InterlockedAnd(0, 1u, _e179); + int _e183; storage_atomic_arr.InterlockedAnd(4, 1, _e183); + uint _e187; storage_struct.InterlockedAnd(0, 1u, _e187); + int _e192; storage_struct.InterlockedAnd(4+4, 1, _e192); + uint _e195; InterlockedAnd(workgroup_atomic_scalar, 1u, _e195); + int _e199; InterlockedAnd(workgroup_atomic_arr[1], 1, _e199); + uint _e203; InterlockedAnd(workgroup_struct.atomic_scalar, 1u, _e203); + int _e208; InterlockedAnd(workgroup_struct.atomic_arr[1], 1, _e208); GroupMemoryBarrierWithGroupSync(); - uint _e239; storage_atomic_scalar.InterlockedOr(0, 1u, _e239); - int _e244; storage_atomic_arr.InterlockedOr(4, 1, _e244); - uint _e248; storage_struct.InterlockedOr(0, 1u, _e248); - int _e254; storage_struct.InterlockedOr(4+4, 1, _e254); - uint _e257; InterlockedOr(workgroup_atomic_scalar, 1u, _e257); - int _e262; InterlockedOr(workgroup_atomic_arr[1], 1, _e262); - uint _e266; InterlockedOr(workgroup_struct.atomic_scalar, 1u, _e266); - int _e272; InterlockedOr(workgroup_struct.atomic_arr[1], 1, _e272); + uint _e211; storage_atomic_scalar.InterlockedOr(0, 1u, _e211); + int _e215; storage_atomic_arr.InterlockedOr(4, 1, _e215); + uint _e219; storage_struct.InterlockedOr(0, 1u, _e219); + int _e224; storage_struct.InterlockedOr(4+4, 1, _e224); + uint _e227; InterlockedOr(workgroup_atomic_scalar, 1u, _e227); + int _e231; InterlockedOr(workgroup_atomic_arr[1], 1, _e231); + uint _e235; InterlockedOr(workgroup_struct.atomic_scalar, 1u, _e235); + int _e240; InterlockedOr(workgroup_struct.atomic_arr[1], 1, _e240); GroupMemoryBarrierWithGroupSync(); - uint _e275; storage_atomic_scalar.InterlockedXor(0, 1u, _e275); - int _e280; storage_atomic_arr.InterlockedXor(4, 1, _e280); - uint _e284; storage_struct.InterlockedXor(0, 1u, _e284); - int _e290; storage_struct.InterlockedXor(4+4, 1, _e290); - uint _e293; InterlockedXor(workgroup_atomic_scalar, 1u, _e293); - int _e298; InterlockedXor(workgroup_atomic_arr[1], 1, _e298); - uint _e302; InterlockedXor(workgroup_struct.atomic_scalar, 1u, _e302); - int _e308; InterlockedXor(workgroup_struct.atomic_arr[1], 1, _e308); - uint _e311; storage_atomic_scalar.InterlockedExchange(0, 1u, _e311); - int _e316; storage_atomic_arr.InterlockedExchange(4, 1, _e316); - uint _e320; storage_struct.InterlockedExchange(0, 1u, _e320); - int _e326; storage_struct.InterlockedExchange(4+4, 1, _e326); - uint _e329; InterlockedExchange(workgroup_atomic_scalar, 1u, _e329); - int _e334; InterlockedExchange(workgroup_atomic_arr[1], 1, _e334); - uint _e338; InterlockedExchange(workgroup_struct.atomic_scalar, 1u, _e338); - int _e344; InterlockedExchange(workgroup_struct.atomic_arr[1], 1, _e344); + uint _e243; storage_atomic_scalar.InterlockedXor(0, 1u, _e243); + int _e247; storage_atomic_arr.InterlockedXor(4, 1, _e247); + uint _e251; storage_struct.InterlockedXor(0, 1u, _e251); + int _e256; storage_struct.InterlockedXor(4+4, 1, _e256); + uint _e259; InterlockedXor(workgroup_atomic_scalar, 1u, _e259); + int _e263; InterlockedXor(workgroup_atomic_arr[1], 1, _e263); + uint _e267; InterlockedXor(workgroup_struct.atomic_scalar, 1u, _e267); + int _e272; InterlockedXor(workgroup_struct.atomic_arr[1], 1, _e272); + uint _e275; storage_atomic_scalar.InterlockedExchange(0, 1u, _e275); + int _e279; storage_atomic_arr.InterlockedExchange(4, 1, _e279); + uint _e283; storage_struct.InterlockedExchange(0, 1u, _e283); + int _e288; storage_struct.InterlockedExchange(4+4, 1, _e288); + uint _e291; InterlockedExchange(workgroup_atomic_scalar, 1u, _e291); + int _e295; InterlockedExchange(workgroup_atomic_arr[1], 1, _e295); + uint _e299; InterlockedExchange(workgroup_struct.atomic_scalar, 1u, _e299); + int _e304; InterlockedExchange(workgroup_struct.atomic_arr[1], 1, _e304); return; } diff --git a/tests/out/hlsl/binding-arrays.hlsl b/tests/out/hlsl/binding-arrays.hlsl index 13d93c43c..4a22c2746 100644 --- a/tests/out/hlsl/binding-arrays.hlsl +++ b/tests/out/hlsl/binding-arrays.hlsl @@ -64,121 +64,121 @@ float4 main(FragmentInput_main fragmentinput_main) : SV_Target0 v4_ = (0.0).xxxx; float2 uv = (0.0).xx; int2 pix = (0).xx; - uint2 _expr23 = u2_; - u2_ = (_expr23 + NagaDimensions2D(texture_array_unbounded[0])); - uint2 _expr28 = u2_; - u2_ = (_expr28 + NagaDimensions2D(texture_array_unbounded[uniform_index])); - uint2 _expr33 = u2_; - u2_ = (_expr33 + NagaDimensions2D(texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)])); - float4 _expr42 = texture_array_bounded[0].Gather(samp[0], uv); - float4 _expr43 = v4_; - v4_ = (_expr43 + _expr42); - float4 _expr50 = texture_array_bounded[uniform_index].Gather(samp[uniform_index], uv); - float4 _expr51 = v4_; - v4_ = (_expr51 + _expr50); - float4 _expr58 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Gather(samp[NonUniformResourceIndex(non_uniform_index)], uv); - float4 _expr59 = v4_; - v4_ = (_expr59 + _expr58); - float4 _expr68 = texture_array_depth[0].GatherCmp(samp_comp[0], uv, 0.0); + uint2 _expr22 = u2_; + u2_ = (_expr22 + NagaDimensions2D(texture_array_unbounded[0])); + uint2 _expr27 = u2_; + u2_ = (_expr27 + NagaDimensions2D(texture_array_unbounded[uniform_index])); + uint2 _expr32 = u2_; + u2_ = (_expr32 + NagaDimensions2D(texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)])); + float4 _expr38 = texture_array_bounded[0].Gather(samp[0], uv); + float4 _expr39 = v4_; + v4_ = (_expr39 + _expr38); + float4 _expr45 = texture_array_bounded[uniform_index].Gather(samp[uniform_index], uv); + float4 _expr46 = v4_; + v4_ = (_expr46 + _expr45); + float4 _expr52 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Gather(samp[NonUniformResourceIndex(non_uniform_index)], uv); + float4 _expr53 = v4_; + v4_ = (_expr53 + _expr52); + float4 _expr60 = texture_array_depth[0].GatherCmp(samp_comp[0], uv, 0.0); + float4 _expr61 = v4_; + v4_ = (_expr61 + _expr60); + float4 _expr68 = texture_array_depth[uniform_index].GatherCmp(samp_comp[uniform_index], uv, 0.0); float4 _expr69 = v4_; v4_ = (_expr69 + _expr68); - float4 _expr76 = texture_array_depth[uniform_index].GatherCmp(samp_comp[uniform_index], uv, 0.0); + float4 _expr76 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].GatherCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); float4 _expr77 = v4_; v4_ = (_expr77 + _expr76); - float4 _expr84 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].GatherCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float4 _expr85 = v4_; - v4_ = (_expr85 + _expr84); - float4 _expr91 = texture_array_unbounded[0].Load(int3(pix, 0)); - float4 _expr92 = v4_; - v4_ = (_expr92 + _expr91); - float4 _expr97 = texture_array_unbounded[uniform_index].Load(int3(pix, 0)); - float4 _expr98 = v4_; - v4_ = (_expr98 + _expr97); - float4 _expr103 = texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)].Load(int3(pix, 0)); - float4 _expr104 = v4_; - v4_ = (_expr104 + _expr103); + float4 _expr82 = texture_array_unbounded[0].Load(int3(pix, 0)); + float4 _expr83 = v4_; + v4_ = (_expr83 + _expr82); + float4 _expr88 = texture_array_unbounded[uniform_index].Load(int3(pix, 0)); + float4 _expr89 = v4_; + v4_ = (_expr89 + _expr88); + float4 _expr94 = texture_array_unbounded[NonUniformResourceIndex(non_uniform_index)].Load(int3(pix, 0)); + float4 _expr95 = v4_; + v4_ = (_expr95 + _expr94); + uint _expr100 = u1_; + u1_ = (_expr100 + NagaNumLayers2DArray(texture_array_2darray[0])); + uint _expr105 = u1_; + u1_ = (_expr105 + NagaNumLayers2DArray(texture_array_2darray[uniform_index])); uint _expr110 = u1_; - u1_ = (_expr110 + NagaNumLayers2DArray(texture_array_2darray[0])); + u1_ = (_expr110 + NagaNumLayers2DArray(texture_array_2darray[NonUniformResourceIndex(non_uniform_index)])); uint _expr115 = u1_; - u1_ = (_expr115 + NagaNumLayers2DArray(texture_array_2darray[uniform_index])); + u1_ = (_expr115 + NagaNumLevels2D(texture_array_bounded[0])); uint _expr120 = u1_; - u1_ = (_expr120 + NagaNumLayers2DArray(texture_array_2darray[NonUniformResourceIndex(non_uniform_index)])); - uint _expr126 = u1_; - u1_ = (_expr126 + NagaNumLevels2D(texture_array_bounded[0])); - uint _expr131 = u1_; - u1_ = (_expr131 + NagaNumLevels2D(texture_array_bounded[uniform_index])); - uint _expr136 = u1_; - u1_ = (_expr136 + NagaNumLevels2D(texture_array_bounded[NonUniformResourceIndex(non_uniform_index)])); - uint _expr142 = u1_; - u1_ = (_expr142 + NagaMSNumSamples2D(texture_array_multisampled[0])); - uint _expr147 = u1_; - u1_ = (_expr147 + NagaMSNumSamples2D(texture_array_multisampled[uniform_index])); - uint _expr152 = u1_; - u1_ = (_expr152 + NagaMSNumSamples2D(texture_array_multisampled[NonUniformResourceIndex(non_uniform_index)])); - float4 _expr160 = texture_array_bounded[0].Sample(samp[0], uv); + u1_ = (_expr120 + NagaNumLevels2D(texture_array_bounded[uniform_index])); + uint _expr125 = u1_; + u1_ = (_expr125 + NagaNumLevels2D(texture_array_bounded[NonUniformResourceIndex(non_uniform_index)])); + uint _expr130 = u1_; + u1_ = (_expr130 + NagaMSNumSamples2D(texture_array_multisampled[0])); + uint _expr135 = u1_; + u1_ = (_expr135 + NagaMSNumSamples2D(texture_array_multisampled[uniform_index])); + uint _expr140 = u1_; + u1_ = (_expr140 + NagaMSNumSamples2D(texture_array_multisampled[NonUniformResourceIndex(non_uniform_index)])); + float4 _expr146 = texture_array_bounded[0].Sample(samp[0], uv); + float4 _expr147 = v4_; + v4_ = (_expr147 + _expr146); + float4 _expr153 = texture_array_bounded[uniform_index].Sample(samp[uniform_index], uv); + float4 _expr154 = v4_; + v4_ = (_expr154 + _expr153); + float4 _expr160 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Sample(samp[NonUniformResourceIndex(non_uniform_index)], uv); float4 _expr161 = v4_; v4_ = (_expr161 + _expr160); - float4 _expr167 = texture_array_bounded[uniform_index].Sample(samp[uniform_index], uv); - float4 _expr168 = v4_; - v4_ = (_expr168 + _expr167); - float4 _expr174 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].Sample(samp[NonUniformResourceIndex(non_uniform_index)], uv); - float4 _expr175 = v4_; - v4_ = (_expr175 + _expr174); - float4 _expr184 = texture_array_bounded[0].SampleBias(samp[0], uv, 0.0); + float4 _expr168 = texture_array_bounded[0].SampleBias(samp[0], uv, 0.0); + float4 _expr169 = v4_; + v4_ = (_expr169 + _expr168); + float4 _expr176 = texture_array_bounded[uniform_index].SampleBias(samp[uniform_index], uv, 0.0); + float4 _expr177 = v4_; + v4_ = (_expr177 + _expr176); + float4 _expr184 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleBias(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); float4 _expr185 = v4_; v4_ = (_expr185 + _expr184); - float4 _expr192 = texture_array_bounded[uniform_index].SampleBias(samp[uniform_index], uv, 0.0); - float4 _expr193 = v4_; - v4_ = (_expr193 + _expr192); - float4 _expr200 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleBias(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float4 _expr201 = v4_; - v4_ = (_expr201 + _expr200); - float _expr210 = texture_array_depth[0].SampleCmp(samp_comp[0], uv, 0.0); - float _expr211 = v1_; - v1_ = (_expr211 + _expr210); - float _expr218 = texture_array_depth[uniform_index].SampleCmp(samp_comp[uniform_index], uv, 0.0); - float _expr219 = v1_; - v1_ = (_expr219 + _expr218); - float _expr226 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float _expr227 = v1_; - v1_ = (_expr227 + _expr226); - float _expr236 = texture_array_depth[0].SampleCmpLevelZero(samp_comp[0], uv, 0.0); - float _expr237 = v1_; - v1_ = (_expr237 + _expr236); - float _expr244 = texture_array_depth[uniform_index].SampleCmpLevelZero(samp_comp[uniform_index], uv, 0.0); - float _expr245 = v1_; - v1_ = (_expr245 + _expr244); - float _expr252 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmpLevelZero(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float _expr253 = v1_; - v1_ = (_expr253 + _expr252); - float4 _expr261 = texture_array_bounded[0].SampleGrad(samp[0], uv, uv, uv); + float _expr192 = texture_array_depth[0].SampleCmp(samp_comp[0], uv, 0.0); + float _expr193 = v1_; + v1_ = (_expr193 + _expr192); + float _expr200 = texture_array_depth[uniform_index].SampleCmp(samp_comp[uniform_index], uv, 0.0); + float _expr201 = v1_; + v1_ = (_expr201 + _expr200); + float _expr208 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmp(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float _expr209 = v1_; + v1_ = (_expr209 + _expr208); + float _expr216 = texture_array_depth[0].SampleCmpLevelZero(samp_comp[0], uv, 0.0); + float _expr217 = v1_; + v1_ = (_expr217 + _expr216); + float _expr224 = texture_array_depth[uniform_index].SampleCmpLevelZero(samp_comp[uniform_index], uv, 0.0); + float _expr225 = v1_; + v1_ = (_expr225 + _expr224); + float _expr232 = texture_array_depth[NonUniformResourceIndex(non_uniform_index)].SampleCmpLevelZero(samp_comp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float _expr233 = v1_; + v1_ = (_expr233 + _expr232); + float4 _expr239 = texture_array_bounded[0].SampleGrad(samp[0], uv, uv, uv); + float4 _expr240 = v4_; + v4_ = (_expr240 + _expr239); + float4 _expr246 = texture_array_bounded[uniform_index].SampleGrad(samp[uniform_index], uv, uv, uv); + float4 _expr247 = v4_; + v4_ = (_expr247 + _expr246); + float4 _expr253 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleGrad(samp[NonUniformResourceIndex(non_uniform_index)], uv, uv, uv); + float4 _expr254 = v4_; + v4_ = (_expr254 + _expr253); + float4 _expr261 = texture_array_bounded[0].SampleLevel(samp[0], uv, 0.0); float4 _expr262 = v4_; v4_ = (_expr262 + _expr261); - float4 _expr268 = texture_array_bounded[uniform_index].SampleGrad(samp[uniform_index], uv, uv, uv); - float4 _expr269 = v4_; - v4_ = (_expr269 + _expr268); - float4 _expr275 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleGrad(samp[NonUniformResourceIndex(non_uniform_index)], uv, uv, uv); - float4 _expr276 = v4_; - v4_ = (_expr276 + _expr275); - float4 _expr285 = texture_array_bounded[0].SampleLevel(samp[0], uv, 0.0); - float4 _expr286 = v4_; - v4_ = (_expr286 + _expr285); - float4 _expr293 = texture_array_bounded[uniform_index].SampleLevel(samp[uniform_index], uv, 0.0); + float4 _expr269 = texture_array_bounded[uniform_index].SampleLevel(samp[uniform_index], uv, 0.0); + float4 _expr270 = v4_; + v4_ = (_expr270 + _expr269); + float4 _expr277 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleLevel(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); + float4 _expr278 = v4_; + v4_ = (_expr278 + _expr277); + float4 _expr282 = v4_; + texture_array_storage[0][pix] = _expr282; + float4 _expr285 = v4_; + texture_array_storage[uniform_index][pix] = _expr285; + float4 _expr288 = v4_; + texture_array_storage[NonUniformResourceIndex(non_uniform_index)][pix] = _expr288; + uint2 _expr289 = u2_; + uint _expr290 = u1_; + float2 v2_ = float2((_expr289 + (_expr290).xx)); float4 _expr294 = v4_; - v4_ = (_expr294 + _expr293); - float4 _expr301 = texture_array_bounded[NonUniformResourceIndex(non_uniform_index)].SampleLevel(samp[NonUniformResourceIndex(non_uniform_index)], uv, 0.0); - float4 _expr302 = v4_; - v4_ = (_expr302 + _expr301); - float4 _expr307 = v4_; - texture_array_storage[0][pix] = _expr307; - float4 _expr310 = v4_; - texture_array_storage[uniform_index][pix] = _expr310; - float4 _expr313 = v4_; - texture_array_storage[NonUniformResourceIndex(non_uniform_index)][pix] = _expr313; - uint2 _expr314 = u2_; - uint _expr315 = u1_; - float2 v2_ = float2((_expr314 + (_expr315).xx)); - float4 _expr319 = v4_; - float _expr326 = v1_; - return ((_expr319 + float4(v2_.x, v2_.y, v2_.x, v2_.y)) + (_expr326).xxxx); + float _expr301 = v1_; + return ((_expr294 + float4(v2_.x, v2_.y, v2_.x, v2_.y)) + (_expr301).xxxx); } diff --git a/tests/out/hlsl/do-while.hlsl b/tests/out/hlsl/do-while.hlsl index 88a3d522e..b09e62457 100644 --- a/tests/out/hlsl/do-while.hlsl +++ b/tests/out/hlsl/do-while.hlsl @@ -3,8 +3,8 @@ void fb1_(inout bool cond) bool loop_init = true; while(true) { if (!loop_init) { - bool _expr2 = cond; - if (!(_expr2)) { + bool _expr1 = cond; + if (!(_expr1)) { break; } } diff --git a/tests/out/hlsl/empty-global-name.hlsl b/tests/out/hlsl/empty-global-name.hlsl index 2ad022d6b..8bb32b364 100644 --- a/tests/out/hlsl/empty-global-name.hlsl +++ b/tests/out/hlsl/empty-global-name.hlsl @@ -6,8 +6,8 @@ RWByteAddressBuffer unnamed : register(u0); void function() { - int _expr4 = asint(unnamed.Load(0)); - unnamed.Store(0, asuint((_expr4 + 1))); + int _expr3 = asint(unnamed.Load(0)); + unnamed.Store(0, asuint((_expr3 + 1))); return; } diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index f8cede1ac..b4994837c 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -86,8 +86,8 @@ void test_msl_packed_vec3_() idx = 1; alignment.Store(0+0, asuint(1.0)); alignment.Store(0+0, asuint(2.0)); - int _expr17 = idx; - alignment.Store(_expr17*4+0, asuint(3.0)); + int _expr16 = idx; + alignment.Store(_expr16*4+0, asuint(3.0)); FooStruct data = ConstructFooStruct(asfloat(alignment.Load3(0)), asfloat(alignment.Load(12))); float3 l0_ = data.v3_; float2 l1_ = data.v3_.zx; @@ -117,20 +117,20 @@ void main(uint3 __local_invocation_id : SV_GroupThreadID) bool at = (bool)0; test_msl_packed_vec3_(); - float4x2 _expr8 = ((float4x2)global_nested_arrays_of_matrices_4x2_[0][0]); - float4 _expr16 = global_nested_arrays_of_matrices_2x4_[0][0][0]; - wg[7] = mul(_expr16, _expr8).x; - float3x2 _expr23 = ((float3x2)global_mat); - float3 _expr25 = global_vec; - wg[6] = mul(_expr25, _expr23).x; - float _expr35 = asfloat(dummy.Load(4+8)); - wg[5] = _expr35; - float _expr43 = float_vecs[0].w; - wg[4] = _expr43; - float _expr49 = asfloat(alignment.Load(12)); - wg[3] = _expr49; - float _expr56 = asfloat(alignment.Load(0+0)); - wg[2] = _expr56; + float4x2 _expr5 = ((float4x2)global_nested_arrays_of_matrices_4x2_[0][0]); + float4 _expr10 = global_nested_arrays_of_matrices_2x4_[0][0][0]; + wg[7] = mul(_expr10, _expr5).x; + float3x2 _expr16 = ((float3x2)global_mat); + float3 _expr18 = global_vec; + wg[6] = mul(_expr18, _expr16).x; + float _expr26 = asfloat(dummy.Load(4+8)); + wg[5] = _expr26; + float _expr32 = float_vecs[0].w; + wg[4] = _expr32; + float _expr37 = asfloat(alignment.Load(12)); + wg[3] = _expr37; + float _expr43 = asfloat(alignment.Load(0+0)); + wg[2] = _expr43; alignment.Store(12, asuint(4.0)); wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 4c57f3134..846f567f9 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -232,10 +232,10 @@ void assignment() int _expr36 = a_1; a_1 = (_expr36 - 1); vec0_ = (int3)0; - int _expr43 = vec0_.y; - vec0_.y = (_expr43 + 1); - int _expr48 = vec0_.y; - vec0_.y = (_expr48 - 1); + int _expr42 = vec0_.y; + vec0_.y = (_expr42 + 1); + int _expr46 = vec0_.y; + vec0_.y = (_expr46 - 1); return; } diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl index bed52d505..da2ff49da 100644 --- a/tests/out/hlsl/quad-vert.hlsl +++ b/tests/out/hlsl/quad-vert.hlsl @@ -6,7 +6,7 @@ struct gl_PerVertex { int _end_pad_0; }; -struct type_9 { +struct type_4 { float2 member : LOC0; float4 gl_Position : SV_Position; }; @@ -32,15 +32,15 @@ struct VertexOutput_main { void main_1() { - float2 _expr8 = a_uv_1; - v_uv = _expr8; - float2 _expr9 = a_pos_1; - perVertexStruct.gl_Position = float4(_expr9.x, _expr9.y, 0.0, 1.0); + float2 _expr6 = a_uv_1; + v_uv = _expr6; + float2 _expr7 = a_pos_1; + perVertexStruct.gl_Position = float4(_expr7.x, _expr7.y, 0.0, 1.0); return; } -type_9 Constructtype_9(float2 arg0, float4 arg1) { - type_9 ret = (type_9)0; +type_4 Constructtype_4(float2 arg0, float4 arg1) { + type_4 ret = (type_4)0; ret.member = arg0; ret.gl_Position = arg1; return ret; @@ -53,7 +53,7 @@ VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0) main_1(); float2 _expr7 = v_uv; float4 _expr8 = perVertexStruct.gl_Position; - const type_9 type_9_ = Constructtype_9(_expr7, _expr8); - const VertexOutput_main type_9_1 = { type_9_.member, type_9_.gl_Position }; - return type_9_1; + const type_4 type_4_ = Constructtype_4(_expr7, _expr8); + const VertexOutput_main type_4_1 = { type_4_.member, type_4_.gl_Position }; + return type_4_1; } diff --git a/tests/out/ir/access.compact.ron b/tests/out/ir/access.compact.ron new file mode 100644 index 000000000..b725765d4 --- /dev/null +++ b/tests/out/ir/access.compact.ron @@ -0,0 +1,2222 @@ +( + types: [ + ( + name: None, + inner: Scalar( + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Tri, + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Scalar( + kind: Sint, + width: 4, + ), + ), + ( + name: Some("GlobalConst"), + inner: Struct( + members: [ + ( + name: Some("a"), + ty: 1, + binding: None, + offset: 0, + ), + ( + name: Some("b"), + ty: 2, + binding: None, + offset: 16, + ), + ( + name: Some("c"), + ty: 3, + binding: None, + offset: 28, + ), + ], + span: 32, + ), + ), + ( + name: Some("AlignedWrapper"), + inner: Struct( + members: [ + ( + name: Some("value"), + ty: 3, + binding: None, + offset: 0, + ), + ], + span: 8, + ), + ), + ( + name: None, + inner: Matrix( + columns: Quad, + rows: Tri, + width: 4, + ), + ), + ( + name: None, + inner: Matrix( + columns: Bi, + rows: Bi, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 7, + size: Constant(2), + stride: 16, + ), + ), + ( + name: None, + inner: Atomic( + kind: Sint, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 9, + size: Constant(10), + stride: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Bi, + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 11, + size: Constant(2), + stride: 8, + ), + ), + ( + name: None, + inner: Array( + base: 5, + size: Dynamic, + stride: 8, + ), + ), + ( + name: Some("Bar"), + inner: Struct( + members: [ + ( + name: Some("_matrix"), + ty: 6, + binding: None, + offset: 0, + ), + ( + name: Some("matrix_array"), + ty: 8, + binding: None, + offset: 64, + ), + ( + name: Some("atom"), + ty: 9, + binding: None, + offset: 96, + ), + ( + name: Some("atom_arr"), + ty: 10, + binding: None, + offset: 100, + ), + ( + name: Some("arr"), + ty: 12, + binding: None, + offset: 144, + ), + ( + name: Some("data"), + ty: 13, + binding: None, + offset: 160, + ), + ], + span: 176, + ), + ), + ( + name: None, + inner: Matrix( + columns: Tri, + rows: Bi, + width: 4, + ), + ), + ( + name: Some("Baz"), + inner: Struct( + members: [ + ( + name: Some("m"), + ty: 15, + binding: None, + offset: 0, + ), + ], + span: 24, + ), + ), + ( + name: None, + inner: Vector( + size: Bi, + kind: Sint, + width: 4, + ), + ), + ( + name: None, + inner: Matrix( + columns: Quad, + rows: Bi, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 18, + size: Constant(2), + stride: 32, + ), + ), + ( + name: Some("MatCx2InArray"), + inner: Struct( + members: [ + ( + name: Some("am"), + ty: 19, + binding: None, + offset: 0, + ), + ], + span: 64, + ), + ), + ( + name: None, + inner: Scalar( + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Pointer( + base: 21, + space: Function, + ), + ), + ( + name: None, + inner: Array( + base: 21, + size: Constant(10), + stride: 4, + ), + ), + ( + name: None, + inner: Array( + base: 23, + size: Constant(5), + stride: 40, + ), + ), + ( + name: None, + inner: Vector( + size: Quad, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 3, + size: Constant(5), + stride: 4, + ), + ), + ( + name: None, + inner: Pointer( + base: 1, + space: WorkGroup, + ), + ), + ( + name: None, + inner: Array( + base: 25, + size: Constant(2), + stride: 16, + ), + ), + ( + name: None, + inner: Pointer( + base: 28, + space: Function, + ), + ), + ], + special_types: ( + ray_desc: None, + ray_intersection: None, + predeclared_types: {}, + ), + constants: [], + global_variables: [ + ( + name: Some("global_const"), + space: Private, + binding: None, + ty: 4, + init: Some(7), + ), + ( + name: Some("bar"), + space: Storage( + access: ("LOAD | STORE"), + ), + binding: Some(( + group: 0, + binding: 0, + )), + ty: 14, + init: None, + ), + ( + name: Some("baz"), + space: Uniform, + binding: Some(( + group: 0, + binding: 1, + )), + ty: 16, + init: None, + ), + ( + name: Some("qux"), + space: Storage( + access: ("LOAD | STORE"), + ), + binding: Some(( + group: 0, + binding: 2, + )), + ty: 17, + init: None, + ), + ( + name: Some("nested_mat_cx2"), + space: Uniform, + binding: Some(( + group: 0, + binding: 3, + )), + ty: 20, + init: None, + ), + ( + name: Some("val"), + space: WorkGroup, + binding: None, + ty: 1, + init: None, + ), + ], + const_expressions: [ + Literal(U32(0)), + Literal(U32(0)), + Literal(U32(0)), + Literal(U32(0)), + Compose( + ty: 2, + components: [ + 2, + 3, + 4, + ], + ), + Literal(I32(0)), + Compose( + ty: 4, + components: [ + 1, + 5, + 6, + ], + ), + ], + functions: [ + ( + name: Some("test_matrix_within_struct_accesses"), + arguments: [], + result: None, + local_variables: [ + ( + name: Some("idx"), + ty: 3, + init: None, + ), + ( + name: Some("t"), + ty: 16, + init: None, + ), + ], + expressions: [ + Literal(I32(1)), + LocalVariable(1), + Literal(I32(1)), + Load( + pointer: 2, + ), + Binary( + op: Subtract, + left: 4, + right: 3, + ), + GlobalVariable(3), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 7, + ), + GlobalVariable(3), + AccessIndex( + base: 9, + index: 0, + ), + AccessIndex( + base: 10, + index: 0, + ), + Load( + pointer: 11, + ), + GlobalVariable(3), + AccessIndex( + base: 13, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 14, + index: 15, + ), + Load( + pointer: 16, + ), + GlobalVariable(3), + AccessIndex( + base: 18, + index: 0, + ), + AccessIndex( + base: 19, + index: 0, + ), + AccessIndex( + base: 20, + index: 1, + ), + Load( + pointer: 21, + ), + GlobalVariable(3), + AccessIndex( + base: 23, + index: 0, + ), + AccessIndex( + base: 24, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 25, + index: 26, + ), + Load( + pointer: 27, + ), + GlobalVariable(3), + AccessIndex( + base: 29, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 30, + index: 31, + ), + AccessIndex( + base: 32, + index: 1, + ), + Load( + pointer: 33, + ), + GlobalVariable(3), + AccessIndex( + base: 35, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 36, + index: 37, + ), + Load( + pointer: 2, + ), + Access( + base: 38, + index: 39, + ), + Load( + pointer: 40, + ), + Literal(F32(1.0)), + Splat( + size: Bi, + value: 42, + ), + Literal(F32(2.0)), + Splat( + size: Bi, + value: 44, + ), + Literal(F32(3.0)), + Splat( + size: Bi, + value: 46, + ), + Compose( + ty: 15, + components: [ + 43, + 45, + 47, + ], + ), + Compose( + ty: 16, + components: [ + 48, + ], + ), + LocalVariable(2), + Literal(I32(1)), + Load( + pointer: 2, + ), + Binary( + op: Add, + left: 52, + right: 51, + ), + AccessIndex( + base: 50, + index: 0, + ), + Literal(F32(6.0)), + Splat( + size: Bi, + value: 55, + ), + Literal(F32(5.0)), + Splat( + size: Bi, + value: 57, + ), + Literal(F32(4.0)), + Splat( + size: Bi, + value: 59, + ), + Compose( + ty: 15, + components: [ + 56, + 58, + 60, + ], + ), + AccessIndex( + base: 50, + index: 0, + ), + AccessIndex( + base: 62, + index: 0, + ), + Literal(F32(9.0)), + Splat( + size: Bi, + value: 64, + ), + AccessIndex( + base: 50, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 66, + index: 67, + ), + Literal(F32(90.0)), + Splat( + size: Bi, + value: 69, + ), + AccessIndex( + base: 50, + index: 0, + ), + AccessIndex( + base: 71, + index: 0, + ), + AccessIndex( + base: 72, + index: 1, + ), + Literal(F32(10.0)), + AccessIndex( + base: 50, + index: 0, + ), + AccessIndex( + base: 75, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 76, + index: 77, + ), + Literal(F32(20.0)), + AccessIndex( + base: 50, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 80, + index: 81, + ), + AccessIndex( + base: 82, + index: 1, + ), + Literal(F32(30.0)), + AccessIndex( + base: 50, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 85, + index: 86, + ), + Load( + pointer: 2, + ), + Access( + base: 87, + index: 88, + ), + Literal(F32(40.0)), + ], + named_expressions: { + 8: "l0", + 12: "l1", + 17: "l2", + 22: "l3", + 28: "l4", + 34: "l5", + 41: "l6", + }, + body: [ + Store( + pointer: 2, + value: 1, + ), + Emit(( + start: 3, + end: 5, + )), + Store( + pointer: 2, + value: 5, + ), + Emit(( + start: 6, + end: 8, + )), + Emit(( + start: 9, + end: 10, + )), + Emit(( + start: 10, + end: 12, + )), + Emit(( + start: 13, + end: 17, + )), + Emit(( + start: 18, + end: 19, + )), + Emit(( + start: 19, + end: 20, + )), + Emit(( + start: 20, + end: 22, + )), + Emit(( + start: 23, + end: 24, + )), + Emit(( + start: 24, + end: 28, + )), + Emit(( + start: 29, + end: 32, + )), + Emit(( + start: 32, + end: 34, + )), + Emit(( + start: 35, + end: 41, + )), + Emit(( + start: 42, + end: 43, + )), + Emit(( + start: 44, + end: 45, + )), + Emit(( + start: 46, + end: 49, + )), + Store( + pointer: 50, + value: 49, + ), + Emit(( + start: 51, + end: 53, + )), + Store( + pointer: 2, + value: 53, + ), + Emit(( + start: 53, + end: 54, + )), + Emit(( + start: 55, + end: 56, + )), + Emit(( + start: 57, + end: 58, + )), + Emit(( + start: 59, + end: 61, + )), + Store( + pointer: 54, + value: 61, + ), + Emit(( + start: 61, + end: 62, + )), + Emit(( + start: 62, + end: 63, + )), + Emit(( + start: 64, + end: 65, + )), + Store( + pointer: 63, + value: 65, + ), + Emit(( + start: 65, + end: 68, + )), + Emit(( + start: 69, + end: 70, + )), + Store( + pointer: 68, + value: 70, + ), + Emit(( + start: 70, + end: 71, + )), + Emit(( + start: 71, + end: 72, + )), + Emit(( + start: 72, + end: 73, + )), + Store( + pointer: 73, + value: 74, + ), + Emit(( + start: 74, + end: 75, + )), + Emit(( + start: 75, + end: 78, + )), + Store( + pointer: 78, + value: 79, + ), + Emit(( + start: 79, + end: 82, + )), + Emit(( + start: 82, + end: 83, + )), + Store( + pointer: 83, + value: 84, + ), + Emit(( + start: 84, + end: 89, + )), + Store( + pointer: 89, + value: 90, + ), + Return( + value: None, + ), + ], + ), + ( + name: Some("test_matrix_within_array_within_struct_accesses"), + arguments: [], + result: None, + local_variables: [ + ( + name: Some("idx"), + ty: 3, + init: None, + ), + ( + name: Some("t"), + ty: 20, + init: None, + ), + ], + expressions: [ + Literal(I32(1)), + LocalVariable(1), + Literal(I32(1)), + Load( + pointer: 2, + ), + Binary( + op: Subtract, + left: 4, + right: 3, + ), + GlobalVariable(5), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 7, + ), + GlobalVariable(5), + AccessIndex( + base: 9, + index: 0, + ), + AccessIndex( + base: 10, + index: 0, + ), + Load( + pointer: 11, + ), + GlobalVariable(5), + AccessIndex( + base: 13, + index: 0, + ), + AccessIndex( + base: 14, + index: 0, + ), + AccessIndex( + base: 15, + index: 0, + ), + Load( + pointer: 16, + ), + GlobalVariable(5), + AccessIndex( + base: 18, + index: 0, + ), + AccessIndex( + base: 19, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 20, + index: 21, + ), + Load( + pointer: 22, + ), + GlobalVariable(5), + AccessIndex( + base: 24, + index: 0, + ), + AccessIndex( + base: 25, + index: 0, + ), + AccessIndex( + base: 26, + index: 0, + ), + AccessIndex( + base: 27, + index: 1, + ), + Load( + pointer: 28, + ), + GlobalVariable(5), + AccessIndex( + base: 30, + index: 0, + ), + AccessIndex( + base: 31, + index: 0, + ), + AccessIndex( + base: 32, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 33, + index: 34, + ), + Load( + pointer: 35, + ), + GlobalVariable(5), + AccessIndex( + base: 37, + index: 0, + ), + AccessIndex( + base: 38, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 39, + index: 40, + ), + AccessIndex( + base: 41, + index: 1, + ), + Load( + pointer: 42, + ), + GlobalVariable(5), + AccessIndex( + base: 44, + index: 0, + ), + AccessIndex( + base: 45, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 46, + index: 47, + ), + Load( + pointer: 2, + ), + Access( + base: 48, + index: 49, + ), + Load( + pointer: 50, + ), + ZeroValue(19), + Compose( + ty: 20, + components: [ + 52, + ], + ), + LocalVariable(2), + Literal(I32(1)), + Load( + pointer: 2, + ), + Binary( + op: Add, + left: 56, + right: 55, + ), + AccessIndex( + base: 54, + index: 0, + ), + ZeroValue(19), + AccessIndex( + base: 54, + index: 0, + ), + AccessIndex( + base: 60, + index: 0, + ), + Literal(F32(8.0)), + Splat( + size: Bi, + value: 62, + ), + Literal(F32(7.0)), + Splat( + size: Bi, + value: 64, + ), + Literal(F32(6.0)), + Splat( + size: Bi, + value: 66, + ), + Literal(F32(5.0)), + Splat( + size: Bi, + value: 68, + ), + Compose( + ty: 18, + components: [ + 63, + 65, + 67, + 69, + ], + ), + AccessIndex( + base: 54, + index: 0, + ), + AccessIndex( + base: 71, + index: 0, + ), + AccessIndex( + base: 72, + index: 0, + ), + Literal(F32(9.0)), + Splat( + size: Bi, + value: 74, + ), + AccessIndex( + base: 54, + index: 0, + ), + AccessIndex( + base: 76, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 77, + index: 78, + ), + Literal(F32(90.0)), + Splat( + size: Bi, + value: 80, + ), + AccessIndex( + base: 54, + index: 0, + ), + AccessIndex( + base: 82, + index: 0, + ), + AccessIndex( + base: 83, + index: 0, + ), + AccessIndex( + base: 84, + index: 1, + ), + Literal(F32(10.0)), + AccessIndex( + base: 54, + index: 0, + ), + AccessIndex( + base: 87, + index: 0, + ), + AccessIndex( + base: 88, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 89, + index: 90, + ), + Literal(F32(20.0)), + AccessIndex( + base: 54, + index: 0, + ), + AccessIndex( + base: 93, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 94, + index: 95, + ), + AccessIndex( + base: 96, + index: 1, + ), + Literal(F32(30.0)), + AccessIndex( + base: 54, + index: 0, + ), + AccessIndex( + base: 99, + index: 0, + ), + Load( + pointer: 2, + ), + Access( + base: 100, + index: 101, + ), + Load( + pointer: 2, + ), + Access( + base: 102, + index: 103, + ), + Literal(F32(40.0)), + ], + named_expressions: { + 8: "l0", + 12: "l1", + 17: "l2", + 23: "l3", + 29: "l4", + 36: "l5", + 43: "l6", + 51: "l7", + }, + body: [ + Store( + pointer: 2, + value: 1, + ), + Emit(( + start: 3, + end: 5, + )), + Store( + pointer: 2, + value: 5, + ), + Emit(( + start: 6, + end: 8, + )), + Emit(( + start: 9, + end: 10, + )), + Emit(( + start: 10, + end: 12, + )), + Emit(( + start: 13, + end: 14, + )), + Emit(( + start: 14, + end: 15, + )), + Emit(( + start: 15, + end: 17, + )), + Emit(( + start: 18, + end: 19, + )), + Emit(( + start: 19, + end: 23, + )), + Emit(( + start: 24, + end: 25, + )), + Emit(( + start: 25, + end: 26, + )), + Emit(( + start: 26, + end: 27, + )), + Emit(( + start: 27, + end: 29, + )), + Emit(( + start: 30, + end: 31, + )), + Emit(( + start: 31, + end: 32, + )), + Emit(( + start: 32, + end: 36, + )), + Emit(( + start: 37, + end: 38, + )), + Emit(( + start: 38, + end: 41, + )), + Emit(( + start: 41, + end: 43, + )), + Emit(( + start: 44, + end: 45, + )), + Emit(( + start: 45, + end: 51, + )), + Emit(( + start: 52, + end: 53, + )), + Store( + pointer: 54, + value: 53, + ), + Emit(( + start: 55, + end: 57, + )), + Store( + pointer: 2, + value: 57, + ), + Emit(( + start: 57, + end: 58, + )), + Store( + pointer: 58, + value: 59, + ), + Emit(( + start: 59, + end: 60, + )), + Emit(( + start: 60, + end: 61, + )), + Emit(( + start: 62, + end: 63, + )), + Emit(( + start: 64, + end: 65, + )), + Emit(( + start: 66, + end: 67, + )), + Emit(( + start: 68, + end: 70, + )), + Store( + pointer: 61, + value: 70, + ), + Emit(( + start: 70, + end: 71, + )), + Emit(( + start: 71, + end: 72, + )), + Emit(( + start: 72, + end: 73, + )), + Emit(( + start: 74, + end: 75, + )), + Store( + pointer: 73, + value: 75, + ), + Emit(( + start: 75, + end: 76, + )), + Emit(( + start: 76, + end: 79, + )), + Emit(( + start: 80, + end: 81, + )), + Store( + pointer: 79, + value: 81, + ), + Emit(( + start: 81, + end: 82, + )), + Emit(( + start: 82, + end: 83, + )), + Emit(( + start: 83, + end: 84, + )), + Emit(( + start: 84, + end: 85, + )), + Store( + pointer: 85, + value: 86, + ), + Emit(( + start: 86, + end: 87, + )), + Emit(( + start: 87, + end: 88, + )), + Emit(( + start: 88, + end: 91, + )), + Store( + pointer: 91, + value: 92, + ), + Emit(( + start: 92, + end: 93, + )), + Emit(( + start: 93, + end: 96, + )), + Emit(( + start: 96, + end: 97, + )), + Store( + pointer: 97, + value: 98, + ), + Emit(( + start: 98, + end: 99, + )), + Emit(( + start: 99, + end: 104, + )), + Store( + pointer: 104, + value: 105, + ), + Return( + value: None, + ), + ], + ), + ( + name: Some("read_from_private"), + arguments: [ + ( + name: Some("foo"), + ty: 22, + binding: None, + ), + ], + result: Some(( + ty: 21, + binding: None, + )), + local_variables: [], + expressions: [ + FunctionArgument(0), + Load( + pointer: 1, + ), + ], + named_expressions: { + 1: "foo", + }, + body: [ + Emit(( + start: 1, + end: 2, + )), + Return( + value: Some(2), + ), + ], + ), + ( + name: Some("test_arr_as_arg"), + arguments: [ + ( + name: Some("a"), + ty: 24, + binding: None, + ), + ], + result: Some(( + ty: 21, + binding: None, + )), + local_variables: [], + expressions: [ + FunctionArgument(0), + AccessIndex( + base: 1, + index: 4, + ), + AccessIndex( + base: 2, + index: 9, + ), + ], + named_expressions: { + 1: "a", + }, + body: [ + Emit(( + start: 1, + end: 2, + )), + Emit(( + start: 2, + end: 3, + )), + Return( + value: Some(3), + ), + ], + ), + ( + name: Some("assign_through_ptr_fn"), + arguments: [ + ( + name: Some("p"), + ty: 27, + binding: None, + ), + ], + result: None, + local_variables: [], + expressions: [ + FunctionArgument(0), + Literal(U32(42)), + ], + named_expressions: { + 1: "p", + }, + body: [ + Store( + pointer: 1, + value: 2, + ), + Return( + value: None, + ), + ], + ), + ( + name: Some("assign_array_through_ptr_fn"), + arguments: [ + ( + name: Some("foo"), + ty: 29, + binding: None, + ), + ], + result: None, + local_variables: [], + expressions: [ + FunctionArgument(0), + Literal(F32(1.0)), + Splat( + size: Quad, + value: 2, + ), + Literal(F32(2.0)), + Splat( + size: Quad, + value: 4, + ), + Compose( + ty: 28, + components: [ + 3, + 5, + ], + ), + ], + named_expressions: { + 1: "foo", + }, + body: [ + Emit(( + start: 2, + end: 3, + )), + Emit(( + start: 4, + end: 6, + )), + Store( + pointer: 1, + value: 6, + ), + Return( + value: None, + ), + ], + ), + ], + entry_points: [ + ( + name: "foo_vert", + stage: Vertex, + early_depth_test: None, + workgroup_size: (0, 0, 0), + function: ( + name: Some("foo_vert"), + arguments: [ + ( + name: Some("vi"), + ty: 1, + binding: Some(BuiltIn(VertexIndex)), + ), + ], + result: Some(( + ty: 25, + binding: Some(BuiltIn(Position( + invariant: false, + ))), + )), + local_variables: [ + ( + name: Some("foo"), + ty: 21, + init: None, + ), + ( + name: Some("c2"), + ty: 26, + init: None, + ), + ], + expressions: [ + FunctionArgument(0), + Literal(F32(0.0)), + LocalVariable(1), + Load( + pointer: 3, + ), + Literal(F32(1.0)), + GlobalVariable(2), + AccessIndex( + base: 6, + index: 0, + ), + Load( + pointer: 7, + ), + GlobalVariable(2), + AccessIndex( + base: 9, + index: 4, + ), + Load( + pointer: 10, + ), + Literal(U32(3)), + GlobalVariable(2), + AccessIndex( + base: 13, + index: 0, + ), + AccessIndex( + base: 14, + index: 3, + ), + AccessIndex( + base: 15, + index: 0, + ), + Load( + pointer: 16, + ), + GlobalVariable(2), + AccessIndex( + base: 18, + index: 5, + ), + GlobalVariable(2), + AccessIndex( + base: 20, + index: 5, + ), + ArrayLength(21), + Literal(U32(2)), + Binary( + op: Subtract, + left: 22, + right: 23, + ), + Access( + base: 19, + index: 24, + ), + AccessIndex( + base: 25, + index: 0, + ), + Load( + pointer: 26, + ), + GlobalVariable(4), + Load( + pointer: 28, + ), + GlobalVariable(2), + AccessIndex( + base: 30, + index: 5, + ), + AccessIndex( + base: 31, + index: 0, + ), + AccessIndex( + base: 32, + index: 0, + ), + CallResult(3), + As( + expr: 17, + kind: Sint, + convert: Some(4), + ), + Literal(I32(3)), + Literal(I32(4)), + Literal(I32(5)), + Compose( + ty: 26, + components: [ + 27, + 35, + 36, + 37, + 38, + ], + ), + LocalVariable(2), + Literal(U32(1)), + Binary( + op: Add, + left: 1, + right: 41, + ), + Access( + base: 40, + index: 42, + ), + Literal(I32(42)), + Access( + base: 40, + index: 1, + ), + Load( + pointer: 45, + ), + ZeroValue(24), + CallResult(4), + Splat( + size: Quad, + value: 46, + ), + As( + expr: 49, + kind: Float, + convert: Some(4), + ), + Binary( + op: Multiply, + left: 8, + right: 50, + ), + Literal(F32(2.0)), + Compose( + ty: 25, + components: [ + 51, + 52, + ], + ), + ], + named_expressions: { + 1: "vi", + 4: "baz", + 8: "_matrix", + 11: "arr", + 12: "index", + 17: "b", + 27: "a", + 29: "c", + 33: "data_pointer", + 34: "foo_value", + 46: "value", + }, + body: [ + Store( + pointer: 3, + value: 2, + ), + Emit(( + start: 3, + end: 4, + )), + Store( + pointer: 3, + value: 5, + ), + Call( + function: 1, + arguments: [], + result: None, + ), + Call( + function: 2, + arguments: [], + result: None, + ), + Emit(( + start: 6, + end: 8, + )), + Emit(( + start: 9, + end: 11, + )), + Emit(( + start: 13, + end: 17, + )), + Emit(( + start: 18, + end: 19, + )), + Emit(( + start: 20, + end: 22, + )), + Emit(( + start: 23, + end: 27, + )), + Emit(( + start: 28, + end: 29, + )), + Emit(( + start: 30, + end: 31, + )), + Emit(( + start: 31, + end: 33, + )), + Call( + function: 3, + arguments: [ + 3, + ], + result: Some(34), + ), + Emit(( + start: 34, + end: 35, + )), + Emit(( + start: 38, + end: 39, + )), + Store( + pointer: 40, + value: 39, + ), + Emit(( + start: 41, + end: 43, + )), + Store( + pointer: 43, + value: 44, + ), + Emit(( + start: 44, + end: 46, + )), + Call( + function: 4, + arguments: [ + 47, + ], + result: Some(48), + ), + Emit(( + start: 48, + end: 51, + )), + Emit(( + start: 52, + end: 53, + )), + Return( + value: Some(53), + ), + ], + ), + ), + ( + name: "foo_frag", + stage: Fragment, + early_depth_test: None, + workgroup_size: (0, 0, 0), + function: ( + name: Some("foo_frag"), + arguments: [], + result: Some(( + ty: 25, + binding: Some(Location( + location: 0, + second_blend_source: false, + interpolation: Some(Perspective), + sampling: Some(Center), + )), + )), + local_variables: [], + expressions: [ + GlobalVariable(2), + AccessIndex( + base: 1, + index: 0, + ), + AccessIndex( + base: 2, + index: 1, + ), + AccessIndex( + base: 3, + index: 2, + ), + Literal(F32(1.0)), + GlobalVariable(2), + AccessIndex( + base: 6, + index: 0, + ), + Literal(F32(0.0)), + Splat( + size: Tri, + value: 8, + ), + Literal(F32(1.0)), + Splat( + size: Tri, + value: 10, + ), + Literal(F32(2.0)), + Splat( + size: Tri, + value: 12, + ), + Literal(F32(3.0)), + Splat( + size: Tri, + value: 14, + ), + Compose( + ty: 6, + components: [ + 9, + 11, + 13, + 15, + ], + ), + GlobalVariable(2), + AccessIndex( + base: 17, + index: 4, + ), + Literal(U32(0)), + Splat( + size: Bi, + value: 19, + ), + Literal(U32(1)), + Splat( + size: Bi, + value: 21, + ), + Compose( + ty: 12, + components: [ + 20, + 22, + ], + ), + GlobalVariable(2), + AccessIndex( + base: 24, + index: 5, + ), + AccessIndex( + base: 25, + index: 1, + ), + AccessIndex( + base: 26, + index: 0, + ), + Literal(I32(1)), + GlobalVariable(4), + ZeroValue(17), + Literal(F32(0.0)), + Splat( + size: Quad, + value: 31, + ), + ], + named_expressions: {}, + body: [ + Emit(( + start: 1, + end: 2, + )), + Emit(( + start: 2, + end: 4, + )), + Store( + pointer: 4, + value: 5, + ), + Emit(( + start: 6, + end: 7, + )), + Emit(( + start: 8, + end: 9, + )), + Emit(( + start: 10, + end: 11, + )), + Emit(( + start: 12, + end: 13, + )), + Emit(( + start: 14, + end: 16, + )), + Store( + pointer: 7, + value: 16, + ), + Emit(( + start: 17, + end: 18, + )), + Emit(( + start: 19, + end: 20, + )), + Emit(( + start: 21, + end: 23, + )), + Store( + pointer: 18, + value: 23, + ), + Emit(( + start: 24, + end: 25, + )), + Emit(( + start: 25, + end: 27, + )), + Store( + pointer: 27, + value: 28, + ), + Store( + pointer: 29, + value: 30, + ), + Emit(( + start: 31, + end: 32, + )), + Return( + value: Some(32), + ), + ], + ), + ), + ( + name: "assign_through_ptr", + stage: Compute, + early_depth_test: None, + workgroup_size: (1, 1, 1), + function: ( + name: Some("assign_through_ptr"), + arguments: [], + result: None, + local_variables: [ + ( + name: Some("arr"), + ty: 28, + init: None, + ), + ], + expressions: [ + Literal(F32(6.0)), + Splat( + size: Quad, + value: 1, + ), + Literal(F32(7.0)), + Splat( + size: Quad, + value: 3, + ), + Compose( + ty: 28, + components: [ + 2, + 4, + ], + ), + LocalVariable(1), + GlobalVariable(6), + ], + named_expressions: {}, + body: [ + Emit(( + start: 1, + end: 2, + )), + Emit(( + start: 3, + end: 5, + )), + Store( + pointer: 6, + value: 5, + ), + Call( + function: 5, + arguments: [ + 7, + ], + result: None, + ), + Call( + function: 6, + arguments: [ + 6, + ], + result: None, + ), + Return( + value: None, + ), + ], + ), + ), + ], +) \ No newline at end of file diff --git a/tests/out/ir/collatz.compact.ron b/tests/out/ir/collatz.compact.ron new file mode 100644 index 000000000..fb8ff825e --- /dev/null +++ b/tests/out/ir/collatz.compact.ron @@ -0,0 +1,334 @@ +( + types: [ + ( + name: None, + inner: Scalar( + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Array( + base: 1, + size: Dynamic, + stride: 4, + ), + ), + ( + name: Some("PrimeIndices"), + inner: Struct( + members: [ + ( + name: Some("data"), + ty: 2, + binding: None, + offset: 0, + ), + ], + span: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Tri, + kind: Uint, + width: 4, + ), + ), + ], + special_types: ( + ray_desc: None, + ray_intersection: None, + predeclared_types: {}, + ), + constants: [], + global_variables: [ + ( + name: Some("v_indices"), + space: Storage( + access: ("LOAD | STORE"), + ), + binding: Some(( + group: 0, + binding: 0, + )), + ty: 3, + init: None, + ), + ], + const_expressions: [], + functions: [ + ( + name: Some("collatz_iterations"), + arguments: [ + ( + name: Some("n_base"), + ty: 1, + binding: None, + ), + ], + result: Some(( + ty: 1, + binding: None, + )), + local_variables: [ + ( + name: Some("n"), + ty: 1, + init: None, + ), + ( + name: Some("i"), + ty: 1, + init: None, + ), + ], + expressions: [ + FunctionArgument(0), + LocalVariable(1), + Literal(U32(0)), + LocalVariable(2), + Load( + pointer: 2, + ), + Literal(U32(1)), + Binary( + op: Greater, + left: 5, + right: 6, + ), + Load( + pointer: 2, + ), + Literal(U32(2)), + Binary( + op: Modulo, + left: 8, + right: 9, + ), + Literal(U32(0)), + Binary( + op: Equal, + left: 10, + right: 11, + ), + Load( + pointer: 2, + ), + Literal(U32(2)), + Binary( + op: Divide, + left: 13, + right: 14, + ), + Literal(U32(3)), + Load( + pointer: 2, + ), + Binary( + op: Multiply, + left: 16, + right: 17, + ), + Literal(U32(1)), + Binary( + op: Add, + left: 18, + right: 19, + ), + Load( + pointer: 4, + ), + Literal(U32(1)), + Binary( + op: Add, + left: 21, + right: 22, + ), + Load( + pointer: 4, + ), + ], + named_expressions: { + 1: "n_base", + }, + body: [ + Store( + pointer: 2, + value: 1, + ), + Store( + pointer: 4, + value: 3, + ), + Loop( + body: [ + Emit(( + start: 4, + end: 5, + )), + Emit(( + start: 6, + end: 7, + )), + If( + condition: 7, + accept: [], + reject: [ + Break, + ], + ), + Block([ + Emit(( + start: 7, + end: 8, + )), + Emit(( + start: 9, + end: 10, + )), + Emit(( + start: 11, + end: 12, + )), + If( + condition: 12, + accept: [ + Emit(( + start: 12, + end: 13, + )), + Emit(( + start: 14, + end: 15, + )), + Store( + pointer: 2, + value: 15, + ), + ], + reject: [ + Emit(( + start: 16, + end: 18, + )), + Emit(( + start: 19, + end: 20, + )), + Store( + pointer: 2, + value: 20, + ), + ], + ), + Emit(( + start: 20, + end: 21, + )), + Emit(( + start: 22, + end: 23, + )), + Store( + pointer: 4, + value: 23, + ), + ]), + ], + continuing: [], + break_if: None, + ), + Emit(( + start: 23, + end: 24, + )), + Return( + value: Some(24), + ), + ], + ), + ], + entry_points: [ + ( + name: "main", + stage: Compute, + early_depth_test: None, + workgroup_size: (1, 1, 1), + function: ( + name: Some("main"), + arguments: [ + ( + name: Some("global_id"), + ty: 4, + binding: Some(BuiltIn(GlobalInvocationId)), + ), + ], + result: None, + local_variables: [], + expressions: [ + FunctionArgument(0), + GlobalVariable(1), + AccessIndex( + base: 2, + index: 0, + ), + AccessIndex( + base: 1, + index: 0, + ), + Access( + base: 3, + index: 4, + ), + GlobalVariable(1), + AccessIndex( + base: 6, + index: 0, + ), + AccessIndex( + base: 1, + index: 0, + ), + Access( + base: 7, + index: 8, + ), + Load( + pointer: 9, + ), + CallResult(1), + ], + named_expressions: { + 1: "global_id", + }, + body: [ + Emit(( + start: 2, + end: 5, + )), + Emit(( + start: 6, + end: 10, + )), + Call( + function: 1, + arguments: [ + 10, + ], + result: Some(11), + ), + Store( + pointer: 5, + value: 11, + ), + Return( + value: None, + ), + ], + ), + ), + ], +) \ No newline at end of file diff --git a/tests/out/ir/shadow.compact.ron b/tests/out/ir/shadow.compact.ron new file mode 100644 index 000000000..313938997 --- /dev/null +++ b/tests/out/ir/shadow.compact.ron @@ -0,0 +1,1036 @@ +( + types: [ + ( + name: None, + inner: Scalar( + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Tri, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Scalar( + kind: Uint, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Quad, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Bi, + kind: Float, + width: 4, + ), + ), + ( + name: None, + inner: Image( + dim: D2, + arrayed: true, + class: Depth( + multi: false, + ), + ), + ), + ( + name: None, + inner: Scalar( + kind: Sint, + width: 4, + ), + ), + ( + name: None, + inner: Vector( + size: Quad, + kind: Uint, + width: 4, + ), + ), + ( + name: Some("Globals"), + inner: Struct( + members: [ + ( + name: Some("num_lights"), + ty: 8, + binding: None, + offset: 0, + ), + ], + span: 16, + ), + ), + ( + name: None, + inner: Matrix( + columns: Quad, + rows: Quad, + width: 4, + ), + ), + ( + name: Some("Light"), + inner: Struct( + members: [ + ( + name: Some("proj"), + ty: 10, + binding: None, + offset: 0, + ), + ( + name: Some("pos"), + ty: 4, + binding: None, + offset: 64, + ), + ( + name: Some("color"), + ty: 4, + binding: None, + offset: 80, + ), + ], + span: 96, + ), + ), + ( + name: None, + inner: Array( + base: 11, + size: Dynamic, + stride: 96, + ), + ), + ( + name: Some("Lights"), + inner: Struct( + members: [ + ( + name: Some("data"), + ty: 12, + binding: None, + offset: 0, + ), + ], + span: 96, + ), + ), + ( + name: None, + inner: Sampler( + comparison: true, + ), + ), + ], + special_types: ( + ray_desc: None, + ray_intersection: None, + predeclared_types: {}, + ), + constants: [ + ( + name: None, + override: None, + ty: 1, + init: 1, + ), + ( + name: None, + override: None, + ty: 1, + init: 2, + ), + ( + name: None, + override: None, + ty: 1, + init: 3, + ), + ( + name: None, + override: None, + ty: 1, + init: 4, + ), + ( + name: None, + override: None, + ty: 1, + init: 5, + ), + ( + name: None, + override: None, + ty: 2, + init: 9, + ), + ( + name: None, + override: None, + ty: 3, + init: 10, + ), + ( + name: None, + override: None, + ty: 3, + init: 11, + ), + ( + name: None, + override: None, + ty: 3, + init: 12, + ), + ( + name: None, + override: None, + ty: 7, + init: 13, + ), + ( + name: None, + override: None, + ty: 7, + init: 14, + ), + ( + name: None, + override: None, + ty: 7, + init: 15, + ), + ( + name: None, + override: None, + ty: 7, + init: 16, + ), + ( + name: None, + override: None, + ty: 7, + init: 17, + ), + ( + name: None, + override: None, + ty: 7, + init: 18, + ), + ( + name: None, + override: None, + ty: 7, + init: 19, + ), + ( + name: None, + override: None, + ty: 7, + init: 20, + ), + ( + name: None, + override: None, + ty: 7, + init: 21, + ), + ( + name: None, + override: None, + ty: 7, + init: 22, + ), + ], + global_variables: [ + ( + name: Some("t_shadow"), + space: Handle, + binding: Some(( + group: 0, + binding: 2, + )), + ty: 6, + init: None, + ), + ( + name: Some("sampler_shadow"), + space: Handle, + binding: Some(( + group: 0, + binding: 3, + )), + ty: 14, + init: None, + ), + ( + name: Some("u_globals"), + space: Uniform, + binding: Some(( + group: 0, + binding: 0, + )), + ty: 9, + init: None, + ), + ( + name: Some("s_lights"), + space: Storage( + access: ("LOAD"), + ), + binding: Some(( + group: 0, + binding: 1, + )), + ty: 13, + init: None, + ), + ( + name: Some("in_position_fs"), + space: Private, + binding: None, + ty: 4, + init: None, + ), + ( + name: Some("in_normal_fs"), + space: Private, + binding: None, + ty: 2, + init: None, + ), + ( + name: Some("out_color_fs"), + space: Private, + binding: None, + ty: 4, + init: None, + ), + ], + const_expressions: [ + Literal(F32(0.0)), + Literal(F32(1.0)), + Literal(F32(0.5)), + Literal(F32(-0.5)), + Literal(F32(0.05)), + Constant(5), + Constant(5), + Constant(5), + Compose( + ty: 2, + components: [ + 6, + 7, + 8, + ], + ), + Literal(U32(10)), + Literal(U32(0)), + Literal(U32(1)), + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(1)), + Literal(I32(2)), + Literal(I32(0)), + Literal(I32(1)), + Literal(I32(2)), + Literal(I32(0)), + Literal(I32(1)), + Literal(I32(2)), + Constant(6), + Constant(8), + ], + functions: [ + ( + name: None, + arguments: [ + ( + name: None, + ty: 3, + binding: None, + ), + ( + name: None, + ty: 4, + binding: None, + ), + ], + result: Some(( + ty: 1, + binding: None, + )), + local_variables: [], + expressions: [ + GlobalVariable(1), + GlobalVariable(2), + Constant(3), + Constant(4), + Constant(2), + Constant(1), + FunctionArgument(0), + FunctionArgument(1), + AccessIndex( + base: 8, + index: 3, + ), + Binary( + op: LessEqual, + left: 9, + right: 6, + ), + AccessIndex( + base: 8, + index: 0, + ), + AccessIndex( + base: 8, + index: 1, + ), + Compose( + ty: 5, + components: [ + 11, + 12, + ], + ), + Compose( + ty: 5, + components: [ + 3, + 4, + ], + ), + Binary( + op: Multiply, + left: 13, + right: 14, + ), + AccessIndex( + base: 8, + index: 3, + ), + Binary( + op: Divide, + left: 5, + right: 16, + ), + Binary( + op: Multiply, + left: 15, + right: 17, + ), + Splat( + size: Bi, + value: 3, + ), + Binary( + op: Add, + left: 18, + right: 19, + ), + AccessIndex( + base: 20, + index: 0, + ), + AccessIndex( + base: 20, + index: 1, + ), + As( + expr: 7, + kind: Sint, + convert: None, + ), + As( + expr: 23, + kind: Float, + convert: Some(4), + ), + Compose( + ty: 2, + components: [ + 21, + 22, + 24, + ], + ), + AccessIndex( + base: 8, + index: 2, + ), + AccessIndex( + base: 8, + index: 3, + ), + Binary( + op: Divide, + left: 5, + right: 27, + ), + Binary( + op: Multiply, + left: 26, + right: 28, + ), + AccessIndex( + base: 25, + index: 0, + ), + AccessIndex( + base: 25, + index: 1, + ), + Compose( + ty: 5, + components: [ + 30, + 31, + ], + ), + AccessIndex( + base: 25, + index: 2, + ), + As( + expr: 33, + kind: Sint, + convert: Some(4), + ), + ImageSample( + image: 1, + sampler: 2, + gather: None, + coordinate: 32, + array_index: Some(34), + offset: None, + level: Zero, + depth_ref: Some(29), + ), + ], + named_expressions: {}, + body: [ + Emit(( + start: 8, + end: 10, + )), + If( + condition: 10, + accept: [ + Return( + value: Some(5), + ), + ], + reject: [], + ), + Emit(( + start: 10, + end: 35, + )), + Return( + value: Some(35), + ), + ], + ), + ( + name: Some("fs_main"), + arguments: [], + result: None, + local_variables: [ + ( + name: Some("color"), + ty: 2, + init: Some(23), + ), + ( + name: Some("i"), + ty: 3, + init: Some(24), + ), + ], + expressions: [ + GlobalVariable(3), + GlobalVariable(6), + GlobalVariable(5), + GlobalVariable(4), + GlobalVariable(7), + Constant(17), + Constant(15), + Constant(13), + Constant(18), + Constant(16), + Constant(19), + Constant(9), + Constant(7), + Constant(2), + Constant(11), + Constant(14), + Constant(10), + Constant(12), + Constant(1), + LocalVariable(1), + LocalVariable(2), + Load( + pointer: 21, + ), + AccessIndex( + base: 1, + index: 0, + ), + Access( + base: 23, + index: 17, + ), + Load( + pointer: 24, + ), + Math( + fun: Min, + arg: 25, + arg1: Some(13), + arg2: None, + arg3: None, + ), + Binary( + op: GreaterEqual, + left: 22, + right: 26, + ), + Load( + pointer: 20, + ), + Load( + pointer: 21, + ), + AccessIndex( + base: 4, + index: 0, + ), + Load( + pointer: 21, + ), + Access( + base: 30, + index: 31, + ), + AccessIndex( + base: 32, + index: 0, + ), + Load( + pointer: 33, + ), + Load( + pointer: 3, + ), + Binary( + op: Multiply, + left: 34, + right: 35, + ), + CallResult(1), + Load( + pointer: 2, + ), + Math( + fun: Normalize, + arg: 38, + arg1: None, + arg2: None, + arg3: None, + ), + AccessIndex( + base: 4, + index: 0, + ), + Load( + pointer: 21, + ), + Access( + base: 40, + index: 41, + ), + AccessIndex( + base: 42, + index: 1, + ), + Access( + base: 43, + index: 15, + ), + Load( + pointer: 44, + ), + AccessIndex( + base: 4, + index: 0, + ), + Load( + pointer: 21, + ), + Access( + base: 46, + index: 47, + ), + AccessIndex( + base: 48, + index: 1, + ), + Access( + base: 49, + index: 18, + ), + Load( + pointer: 50, + ), + AccessIndex( + base: 4, + index: 0, + ), + Load( + pointer: 21, + ), + Access( + base: 52, + index: 53, + ), + AccessIndex( + base: 54, + index: 1, + ), + Access( + base: 55, + index: 8, + ), + Load( + pointer: 56, + ), + Compose( + ty: 2, + components: [ + 45, + 51, + 57, + ], + ), + Access( + base: 3, + index: 16, + ), + Load( + pointer: 59, + ), + Access( + base: 3, + index: 7, + ), + Load( + pointer: 61, + ), + Access( + base: 3, + index: 10, + ), + Load( + pointer: 63, + ), + Compose( + ty: 2, + components: [ + 60, + 62, + 64, + ], + ), + Binary( + op: Subtract, + left: 58, + right: 65, + ), + Math( + fun: Normalize, + arg: 66, + arg1: None, + arg2: None, + arg3: None, + ), + Math( + fun: Dot, + arg: 39, + arg1: Some(67), + arg2: None, + arg3: None, + ), + Math( + fun: Max, + arg: 19, + arg1: Some(68), + arg2: None, + arg3: None, + ), + Binary( + op: Multiply, + left: 37, + right: 69, + ), + AccessIndex( + base: 4, + index: 0, + ), + Load( + pointer: 21, + ), + Access( + base: 71, + index: 72, + ), + AccessIndex( + base: 73, + index: 2, + ), + Access( + base: 74, + index: 6, + ), + Load( + pointer: 75, + ), + AccessIndex( + base: 4, + index: 0, + ), + Load( + pointer: 21, + ), + Access( + base: 77, + index: 78, + ), + AccessIndex( + base: 79, + index: 2, + ), + Access( + base: 80, + index: 9, + ), + Load( + pointer: 81, + ), + AccessIndex( + base: 4, + index: 0, + ), + Load( + pointer: 21, + ), + Access( + base: 83, + index: 84, + ), + AccessIndex( + base: 85, + index: 2, + ), + Access( + base: 86, + index: 11, + ), + Load( + pointer: 87, + ), + Compose( + ty: 2, + components: [ + 76, + 82, + 88, + ], + ), + Binary( + op: Multiply, + left: 89, + right: 70, + ), + Binary( + op: Add, + left: 28, + right: 90, + ), + Load( + pointer: 21, + ), + Binary( + op: Add, + left: 92, + right: 12, + ), + Load( + pointer: 20, + ), + Compose( + ty: 4, + components: [ + 94, + 14, + ], + ), + ], + named_expressions: {}, + body: [ + Loop( + body: [ + Emit(( + start: 21, + end: 27, + )), + If( + condition: 27, + accept: [ + Break, + ], + reject: [], + ), + Emit(( + start: 27, + end: 36, + )), + Call( + function: 1, + arguments: [ + 29, + 36, + ], + result: Some(37), + ), + Emit(( + start: 37, + end: 91, + )), + Store( + pointer: 20, + value: 91, + ), + Continue, + ], + continuing: [ + Emit(( + start: 91, + end: 93, + )), + Store( + pointer: 21, + value: 93, + ), + ], + break_if: None, + ), + Emit(( + start: 93, + end: 95, + )), + Store( + pointer: 5, + value: 95, + ), + Return( + value: None, + ), + ], + ), + ], + entry_points: [ + ( + name: "fs_main", + stage: Fragment, + early_depth_test: None, + workgroup_size: (0, 0, 0), + function: ( + name: Some("fs_main_wrap"), + arguments: [ + ( + name: Some("in_normal_fs"), + ty: 2, + binding: Some(Location( + location: 0, + second_blend_source: false, + interpolation: Some(Perspective), + sampling: Some(Center), + )), + ), + ( + name: Some("in_position_fs"), + ty: 4, + binding: Some(Location( + location: 1, + second_blend_source: false, + interpolation: Some(Perspective), + sampling: Some(Center), + )), + ), + ], + result: Some(( + ty: 4, + binding: Some(Location( + location: 0, + second_blend_source: false, + interpolation: None, + sampling: None, + )), + )), + local_variables: [], + expressions: [ + FunctionArgument(0), + GlobalVariable(6), + FunctionArgument(1), + GlobalVariable(5), + GlobalVariable(7), + Load( + pointer: 5, + ), + ], + named_expressions: {}, + body: [ + Store( + pointer: 2, + value: 1, + ), + Store( + pointer: 4, + value: 3, + ), + Call( + function: 2, + arguments: [], + result: None, + ), + Emit(( + start: 5, + end: 6, + )), + Return( + value: Some(6), + ), + ], + ), + ), + ], +) \ No newline at end of file diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index e5d875dd1..c35139a8c 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -39,22 +39,22 @@ struct Bar { struct Baz { metal::float3x2 m; }; -struct type_15 { +struct type_14 { metal::float4x2 inner[2]; }; struct MatCx2InArray { - type_15 am; + type_14 am; }; -struct type_18 { +struct type_17 { float inner[10]; }; -struct type_19 { - type_18 inner[5]; +struct type_18 { + type_17 inner[5]; }; -struct type_22 { +struct type_20 { int inner[5]; }; -struct type_26 { +struct type_22 { metal::float4 inner[2]; }; @@ -68,31 +68,31 @@ void test_matrix_within_struct_accesses( idx = _e3 - 1; metal::float3x2 l0_ = baz.m; metal::float2 l1_ = baz.m[0]; - int _e15 = idx; - metal::float2 l2_ = baz.m[_e15]; + int _e14 = idx; + metal::float2 l2_ = baz.m[_e14]; float l3_ = baz.m[0].y; - int _e29 = idx; - float l4_ = baz.m[0][_e29]; - int _e34 = idx; - float l5_ = baz.m[_e34].y; - int _e41 = idx; - int _e43 = idx; - float l6_ = baz.m[_e41][_e43]; + int _e25 = idx; + float l4_ = baz.m[0][_e25]; + int _e30 = idx; + float l5_ = baz.m[_e30].y; + int _e36 = idx; + int _e38 = idx; + float l6_ = baz.m[_e36][_e38]; t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; - int _e56 = idx; - idx = _e56 + 1; + int _e51 = idx; + idx = _e51 + 1; t.m = metal::float3x2(metal::float2(6.0), metal::float2(5.0), metal::float2(4.0)); t.m[0] = metal::float2(9.0); - int _e72 = idx; - t.m[_e72] = metal::float2(90.0); + int _e66 = idx; + t.m[_e66] = metal::float2(90.0); t.m[0].y = 10.0; + int _e76 = idx; + t.m[0][_e76] = 20.0; + int _e80 = idx; + t.m[_e80].y = 30.0; int _e85 = idx; - t.m[0][_e85] = 20.0; - int _e89 = idx; - t.m[_e89].y = 30.0; - int _e95 = idx; - int _e97 = idx; - t.m[_e95][_e97] = 40.0; + int _e87 = idx; + t.m[_e85][_e87] = 40.0; return; } @@ -104,35 +104,35 @@ void test_matrix_within_array_within_struct_accesses( idx_1 = 1; int _e3 = idx_1; idx_1 = _e3 - 1; - type_15 l0_1 = nested_mat_cx2_.am; + type_14 l0_1 = nested_mat_cx2_.am; metal::float4x2 l1_1 = nested_mat_cx2_.am.inner[0]; metal::float2 l2_1 = nested_mat_cx2_.am.inner[0][0]; - int _e24 = idx_1; - metal::float2 l3_1 = nested_mat_cx2_.am.inner[0][_e24]; + int _e20 = idx_1; + metal::float2 l3_1 = nested_mat_cx2_.am.inner[0][_e20]; float l4_1 = nested_mat_cx2_.am.inner[0][0].y; - int _e42 = idx_1; - float l5_1 = nested_mat_cx2_.am.inner[0][0][_e42]; - int _e49 = idx_1; - float l6_1 = nested_mat_cx2_.am.inner[0][_e49].y; - int _e58 = idx_1; - int _e60 = idx_1; - float l7_ = nested_mat_cx2_.am.inner[0][_e58][_e60]; - t_1 = MatCx2InArray {type_15 {}}; - int _e67 = idx_1; - idx_1 = _e67 + 1; - t_1.am = type_15 {}; + int _e33 = idx_1; + float l5_1 = nested_mat_cx2_.am.inner[0][0][_e33]; + int _e39 = idx_1; + float l6_1 = nested_mat_cx2_.am.inner[0][_e39].y; + int _e46 = idx_1; + int _e48 = idx_1; + float l7_ = nested_mat_cx2_.am.inner[0][_e46][_e48]; + t_1 = MatCx2InArray {type_14 {}}; + int _e55 = idx_1; + idx_1 = _e55 + 1; + t_1.am = type_14 {}; t_1.am.inner[0] = metal::float4x2(metal::float2(8.0), metal::float2(7.0), metal::float2(6.0), metal::float2(5.0)); t_1.am.inner[0][0] = metal::float2(9.0); - int _e93 = idx_1; - t_1.am.inner[0][_e93] = metal::float2(90.0); + int _e77 = idx_1; + t_1.am.inner[0][_e77] = metal::float2(90.0); t_1.am.inner[0][0].y = 10.0; - int _e110 = idx_1; - t_1.am.inner[0][0][_e110] = 20.0; - int _e116 = idx_1; - t_1.am.inner[0][_e116].y = 30.0; - int _e124 = idx_1; - int _e126 = idx_1; - t_1.am.inner[0][_e124][_e126] = 40.0; + int _e89 = idx_1; + t_1.am.inner[0][0][_e89] = 20.0; + int _e94 = idx_1; + t_1.am.inner[0][_e94].y = 30.0; + int _e100 = idx_1; + int _e102 = idx_1; + t_1.am.inner[0][_e100][_e102] = 40.0; return; } @@ -144,7 +144,7 @@ float read_from_private( } float test_arr_as_arg( - type_19 a + type_18 a ) { return a.inner[4].inner[9]; } @@ -157,9 +157,9 @@ void assign_through_ptr_fn( } void assign_array_through_ptr_fn( - thread type_26& foo_2 + thread type_22& foo_2 ) { - foo_2 = type_26 {metal::float4(1.0), metal::float4(2.0)}; + foo_2 = type_22 {metal::float4(1.0), metal::float4(2.0)}; return; } @@ -177,7 +177,7 @@ vertex foo_vertOutput foo_vert( , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { float foo = {}; - type_22 c2_ = {}; + type_20 c2_ = {}; foo = 0.0; float baz_1 = foo; foo = 1.0; @@ -188,11 +188,11 @@ vertex foo_vertOutput foo_vert( float b = bar._matrix[3].x; int a_1 = bar.data[(1 + (_buffer_sizes.size1 - 160 - 8) / 8) - 2u].value; metal::int2 c = qux; - float _e34 = read_from_private(foo); - c2_ = type_22 {a_1, static_cast(b), 3, 4, 5}; + float _e33 = read_from_private(foo); + c2_ = type_20 {a_1, static_cast(b), 3, 4, 5}; c2_.inner[vi + 1u] = 42; int value = c2_.inner[vi]; - float _e48 = test_arr_as_arg(type_19 {}); + float _e47 = test_arr_as_arg(type_18 {}); return foo_vertOutput { metal::float4(_matrix * static_cast(metal::int4(value)), 2.0) }; } @@ -222,8 +222,8 @@ kernel void assign_through_ptr( val = {}; } metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - type_26 arr = {}; - arr = type_26 {metal::float4(6.0), metal::float4(7.0)}; + type_22 arr = {}; + arr = type_22 {metal::float4(6.0), metal::float4(7.0)}; assign_through_ptr_fn(val); assign_array_through_ptr_fn(arr); return; diff --git a/tests/out/msl/atomicOps.msl b/tests/out/msl/atomicOps.msl index b7264e883..3a34cc307 100644 --- a/tests/out/msl/atomicOps.msl +++ b/tests/out/msl/atomicOps.msl @@ -52,75 +52,75 @@ kernel void cs_main( uint l6_ = metal::atomic_load_explicit(&workgroup_struct.atomic_scalar, metal::memory_order_relaxed); int l7_ = metal::atomic_load_explicit(&workgroup_struct.atomic_arr.inner[1], metal::memory_order_relaxed); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - uint _e59 = metal::atomic_fetch_add_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e64 = metal::atomic_fetch_add_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e68 = metal::atomic_fetch_add_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e74 = metal::atomic_fetch_add_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e77 = metal::atomic_fetch_add_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e82 = metal::atomic_fetch_add_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e86 = metal::atomic_fetch_add_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e92 = metal::atomic_fetch_add_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e51 = metal::atomic_fetch_add_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e55 = metal::atomic_fetch_add_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e59 = metal::atomic_fetch_add_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e64 = metal::atomic_fetch_add_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e67 = metal::atomic_fetch_add_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e71 = metal::atomic_fetch_add_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e75 = metal::atomic_fetch_add_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e80 = metal::atomic_fetch_add_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - uint _e95 = metal::atomic_fetch_sub_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e100 = metal::atomic_fetch_sub_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e104 = metal::atomic_fetch_sub_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e110 = metal::atomic_fetch_sub_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e113 = metal::atomic_fetch_sub_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e118 = metal::atomic_fetch_sub_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e122 = metal::atomic_fetch_sub_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e128 = metal::atomic_fetch_sub_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e83 = metal::atomic_fetch_sub_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e87 = metal::atomic_fetch_sub_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e91 = metal::atomic_fetch_sub_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e96 = metal::atomic_fetch_sub_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e99 = metal::atomic_fetch_sub_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e103 = metal::atomic_fetch_sub_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e107 = metal::atomic_fetch_sub_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e112 = metal::atomic_fetch_sub_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - uint _e131 = metal::atomic_fetch_max_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e136 = metal::atomic_fetch_max_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e140 = metal::atomic_fetch_max_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e146 = metal::atomic_fetch_max_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e149 = metal::atomic_fetch_max_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e154 = metal::atomic_fetch_max_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e158 = metal::atomic_fetch_max_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e164 = metal::atomic_fetch_max_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e115 = metal::atomic_fetch_max_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e119 = metal::atomic_fetch_max_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e123 = metal::atomic_fetch_max_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e128 = metal::atomic_fetch_max_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e131 = metal::atomic_fetch_max_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e135 = metal::atomic_fetch_max_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e139 = metal::atomic_fetch_max_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e144 = metal::atomic_fetch_max_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - uint _e167 = metal::atomic_fetch_min_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e172 = metal::atomic_fetch_min_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e176 = metal::atomic_fetch_min_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e182 = metal::atomic_fetch_min_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e185 = metal::atomic_fetch_min_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e190 = metal::atomic_fetch_min_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e194 = metal::atomic_fetch_min_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e200 = metal::atomic_fetch_min_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e147 = metal::atomic_fetch_min_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e151 = metal::atomic_fetch_min_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e155 = metal::atomic_fetch_min_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e160 = metal::atomic_fetch_min_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e163 = metal::atomic_fetch_min_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e167 = metal::atomic_fetch_min_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e171 = metal::atomic_fetch_min_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e176 = metal::atomic_fetch_min_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - uint _e203 = metal::atomic_fetch_and_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e208 = metal::atomic_fetch_and_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e212 = metal::atomic_fetch_and_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e218 = metal::atomic_fetch_and_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e221 = metal::atomic_fetch_and_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e226 = metal::atomic_fetch_and_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e230 = metal::atomic_fetch_and_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e236 = metal::atomic_fetch_and_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e179 = metal::atomic_fetch_and_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e183 = metal::atomic_fetch_and_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e187 = metal::atomic_fetch_and_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e192 = metal::atomic_fetch_and_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e195 = metal::atomic_fetch_and_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e199 = metal::atomic_fetch_and_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e203 = metal::atomic_fetch_and_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e208 = metal::atomic_fetch_and_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - uint _e239 = metal::atomic_fetch_or_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e244 = metal::atomic_fetch_or_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e248 = metal::atomic_fetch_or_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e254 = metal::atomic_fetch_or_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e257 = metal::atomic_fetch_or_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e262 = metal::atomic_fetch_or_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e266 = metal::atomic_fetch_or_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e272 = metal::atomic_fetch_or_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e211 = metal::atomic_fetch_or_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e215 = metal::atomic_fetch_or_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e219 = metal::atomic_fetch_or_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e224 = metal::atomic_fetch_or_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e227 = metal::atomic_fetch_or_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e231 = metal::atomic_fetch_or_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e235 = metal::atomic_fetch_or_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e240 = metal::atomic_fetch_or_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - uint _e275 = metal::atomic_fetch_xor_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e280 = metal::atomic_fetch_xor_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e284 = metal::atomic_fetch_xor_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e290 = metal::atomic_fetch_xor_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e293 = metal::atomic_fetch_xor_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e298 = metal::atomic_fetch_xor_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e302 = metal::atomic_fetch_xor_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e308 = metal::atomic_fetch_xor_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e311 = metal::atomic_exchange_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e316 = metal::atomic_exchange_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e320 = metal::atomic_exchange_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e326 = metal::atomic_exchange_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e329 = metal::atomic_exchange_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); - int _e334 = metal::atomic_exchange_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); - uint _e338 = metal::atomic_exchange_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); - int _e344 = metal::atomic_exchange_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e243 = metal::atomic_fetch_xor_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e247 = metal::atomic_fetch_xor_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e251 = metal::atomic_fetch_xor_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e256 = metal::atomic_fetch_xor_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e259 = metal::atomic_fetch_xor_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e263 = metal::atomic_fetch_xor_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e267 = metal::atomic_fetch_xor_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e272 = metal::atomic_fetch_xor_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e275 = metal::atomic_exchange_explicit(&storage_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e279 = metal::atomic_exchange_explicit(&storage_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e283 = metal::atomic_exchange_explicit(&storage_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e288 = metal::atomic_exchange_explicit(&storage_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e291 = metal::atomic_exchange_explicit(&workgroup_atomic_scalar, 1u, metal::memory_order_relaxed); + int _e295 = metal::atomic_exchange_explicit(&workgroup_atomic_arr.inner[1], 1, metal::memory_order_relaxed); + uint _e299 = metal::atomic_exchange_explicit(&workgroup_struct.atomic_scalar, 1u, metal::memory_order_relaxed); + int _e304 = metal::atomic_exchange_explicit(&workgroup_struct.atomic_arr.inner[1], 1, metal::memory_order_relaxed); return; } diff --git a/tests/out/msl/binding-arrays.msl b/tests/out/msl/binding-arrays.msl index 10a539791..f7597b5c7 100644 --- a/tests/out/msl/binding-arrays.msl +++ b/tests/out/msl/binding-arrays.msl @@ -48,127 +48,127 @@ fragment main_Output main_( v4_ = metal::float4(0.0); metal::float2 uv = metal::float2(0.0); metal::int2 pix = metal::int2(0); - metal::uint2 _e23 = u2_; - u2_ = _e23 + metal::uint2(texture_array_unbounded[0].get_width(), texture_array_unbounded[0].get_height()); - metal::uint2 _e28 = u2_; - u2_ = _e28 + metal::uint2(texture_array_unbounded[uniform_index].get_width(), texture_array_unbounded[uniform_index].get_height()); - metal::uint2 _e33 = u2_; - u2_ = _e33 + metal::uint2(texture_array_unbounded[non_uniform_index].get_width(), texture_array_unbounded[non_uniform_index].get_height()); - metal::float4 _e42 = texture_array_bounded[0].gather(samp[0], uv); - metal::float4 _e43 = v4_; - v4_ = _e43 + _e42; - metal::float4 _e50 = texture_array_bounded[uniform_index].gather(samp[uniform_index], uv); - metal::float4 _e51 = v4_; - v4_ = _e51 + _e50; - metal::float4 _e58 = texture_array_bounded[non_uniform_index].gather(samp[non_uniform_index], uv); - metal::float4 _e59 = v4_; - v4_ = _e59 + _e58; - metal::float4 _e68 = texture_array_depth[0].gather_compare(samp_comp[0], uv, 0.0); + metal::uint2 _e22 = u2_; + u2_ = _e22 + metal::uint2(texture_array_unbounded[0].get_width(), texture_array_unbounded[0].get_height()); + metal::uint2 _e27 = u2_; + u2_ = _e27 + metal::uint2(texture_array_unbounded[uniform_index].get_width(), texture_array_unbounded[uniform_index].get_height()); + metal::uint2 _e32 = u2_; + u2_ = _e32 + metal::uint2(texture_array_unbounded[non_uniform_index].get_width(), texture_array_unbounded[non_uniform_index].get_height()); + metal::float4 _e38 = texture_array_bounded[0].gather(samp[0], uv); + metal::float4 _e39 = v4_; + v4_ = _e39 + _e38; + metal::float4 _e45 = texture_array_bounded[uniform_index].gather(samp[uniform_index], uv); + metal::float4 _e46 = v4_; + v4_ = _e46 + _e45; + metal::float4 _e52 = texture_array_bounded[non_uniform_index].gather(samp[non_uniform_index], uv); + metal::float4 _e53 = v4_; + v4_ = _e53 + _e52; + metal::float4 _e60 = texture_array_depth[0].gather_compare(samp_comp[0], uv, 0.0); + metal::float4 _e61 = v4_; + v4_ = _e61 + _e60; + metal::float4 _e68 = texture_array_depth[uniform_index].gather_compare(samp_comp[uniform_index], uv, 0.0); metal::float4 _e69 = v4_; v4_ = _e69 + _e68; - metal::float4 _e76 = texture_array_depth[uniform_index].gather_compare(samp_comp[uniform_index], uv, 0.0); + metal::float4 _e76 = texture_array_depth[non_uniform_index].gather_compare(samp_comp[non_uniform_index], uv, 0.0); metal::float4 _e77 = v4_; v4_ = _e77 + _e76; - metal::float4 _e84 = texture_array_depth[non_uniform_index].gather_compare(samp_comp[non_uniform_index], uv, 0.0); - metal::float4 _e85 = v4_; - v4_ = _e85 + _e84; - metal::float4 _e91 = (uint(0) < texture_array_unbounded[0].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[0].get_width(0), texture_array_unbounded[0].get_height(0))) ? texture_array_unbounded[0].read(metal::uint2(pix), 0): DefaultConstructible()); - metal::float4 _e92 = v4_; - v4_ = _e92 + _e91; - metal::float4 _e97 = (uint(0) < texture_array_unbounded[uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[uniform_index].get_width(0), texture_array_unbounded[uniform_index].get_height(0))) ? texture_array_unbounded[uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); - metal::float4 _e98 = v4_; - v4_ = _e98 + _e97; - metal::float4 _e103 = (uint(0) < texture_array_unbounded[non_uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[non_uniform_index].get_width(0), texture_array_unbounded[non_uniform_index].get_height(0))) ? texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); - metal::float4 _e104 = v4_; - v4_ = _e104 + _e103; + metal::float4 _e82 = (uint(0) < texture_array_unbounded[0].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[0].get_width(0), texture_array_unbounded[0].get_height(0))) ? texture_array_unbounded[0].read(metal::uint2(pix), 0): DefaultConstructible()); + metal::float4 _e83 = v4_; + v4_ = _e83 + _e82; + metal::float4 _e88 = (uint(0) < texture_array_unbounded[uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[uniform_index].get_width(0), texture_array_unbounded[uniform_index].get_height(0))) ? texture_array_unbounded[uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); + metal::float4 _e89 = v4_; + v4_ = _e89 + _e88; + metal::float4 _e94 = (uint(0) < texture_array_unbounded[non_uniform_index].get_num_mip_levels() && metal::all(metal::uint2(pix) < metal::uint2(texture_array_unbounded[non_uniform_index].get_width(0), texture_array_unbounded[non_uniform_index].get_height(0))) ? texture_array_unbounded[non_uniform_index].read(metal::uint2(pix), 0): DefaultConstructible()); + metal::float4 _e95 = v4_; + v4_ = _e95 + _e94; + uint _e100 = u1_; + u1_ = _e100 + texture_array_2darray[0].get_array_size(); + uint _e105 = u1_; + u1_ = _e105 + texture_array_2darray[uniform_index].get_array_size(); uint _e110 = u1_; - u1_ = _e110 + texture_array_2darray[0].get_array_size(); + u1_ = _e110 + texture_array_2darray[non_uniform_index].get_array_size(); uint _e115 = u1_; - u1_ = _e115 + texture_array_2darray[uniform_index].get_array_size(); + u1_ = _e115 + texture_array_bounded[0].get_num_mip_levels(); uint _e120 = u1_; - u1_ = _e120 + texture_array_2darray[non_uniform_index].get_array_size(); - uint _e126 = u1_; - u1_ = _e126 + texture_array_bounded[0].get_num_mip_levels(); - uint _e131 = u1_; - u1_ = _e131 + texture_array_bounded[uniform_index].get_num_mip_levels(); - uint _e136 = u1_; - u1_ = _e136 + texture_array_bounded[non_uniform_index].get_num_mip_levels(); - uint _e142 = u1_; - u1_ = _e142 + texture_array_multisampled[0].get_num_samples(); - uint _e147 = u1_; - u1_ = _e147 + texture_array_multisampled[uniform_index].get_num_samples(); - uint _e152 = u1_; - u1_ = _e152 + texture_array_multisampled[non_uniform_index].get_num_samples(); - metal::float4 _e160 = texture_array_bounded[0].sample(samp[0], uv); + u1_ = _e120 + texture_array_bounded[uniform_index].get_num_mip_levels(); + uint _e125 = u1_; + u1_ = _e125 + texture_array_bounded[non_uniform_index].get_num_mip_levels(); + uint _e130 = u1_; + u1_ = _e130 + texture_array_multisampled[0].get_num_samples(); + uint _e135 = u1_; + u1_ = _e135 + texture_array_multisampled[uniform_index].get_num_samples(); + uint _e140 = u1_; + u1_ = _e140 + texture_array_multisampled[non_uniform_index].get_num_samples(); + metal::float4 _e146 = texture_array_bounded[0].sample(samp[0], uv); + metal::float4 _e147 = v4_; + v4_ = _e147 + _e146; + metal::float4 _e153 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv); + metal::float4 _e154 = v4_; + v4_ = _e154 + _e153; + metal::float4 _e160 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv); metal::float4 _e161 = v4_; v4_ = _e161 + _e160; - metal::float4 _e167 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv); - metal::float4 _e168 = v4_; - v4_ = _e168 + _e167; - metal::float4 _e174 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv); - metal::float4 _e175 = v4_; - v4_ = _e175 + _e174; - metal::float4 _e184 = texture_array_bounded[0].sample(samp[0], uv, metal::bias(0.0)); + metal::float4 _e168 = texture_array_bounded[0].sample(samp[0], uv, metal::bias(0.0)); + metal::float4 _e169 = v4_; + v4_ = _e169 + _e168; + metal::float4 _e176 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::bias(0.0)); + metal::float4 _e177 = v4_; + v4_ = _e177 + _e176; + metal::float4 _e184 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::bias(0.0)); metal::float4 _e185 = v4_; v4_ = _e185 + _e184; - metal::float4 _e192 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::bias(0.0)); - metal::float4 _e193 = v4_; - v4_ = _e193 + _e192; - metal::float4 _e200 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::bias(0.0)); - metal::float4 _e201 = v4_; - v4_ = _e201 + _e200; - float _e210 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); - float _e211 = v1_; - v1_ = _e211 + _e210; - float _e218 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); - float _e219 = v1_; - v1_ = _e219 + _e218; - float _e226 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); - float _e227 = v1_; - v1_ = _e227 + _e226; - float _e236 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); - float _e237 = v1_; - v1_ = _e237 + _e236; - float _e244 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); - float _e245 = v1_; - v1_ = _e245 + _e244; - float _e252 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); - float _e253 = v1_; - v1_ = _e253 + _e252; - metal::float4 _e261 = texture_array_bounded[0].sample(samp[0], uv, metal::gradient2d(uv, uv)); + float _e192 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); + float _e193 = v1_; + v1_ = _e193 + _e192; + float _e200 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); + float _e201 = v1_; + v1_ = _e201 + _e200; + float _e208 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); + float _e209 = v1_; + v1_ = _e209 + _e208; + float _e216 = texture_array_depth[0].sample_compare(samp_comp[0], uv, 0.0); + float _e217 = v1_; + v1_ = _e217 + _e216; + float _e224 = texture_array_depth[uniform_index].sample_compare(samp_comp[uniform_index], uv, 0.0); + float _e225 = v1_; + v1_ = _e225 + _e224; + float _e232 = texture_array_depth[non_uniform_index].sample_compare(samp_comp[non_uniform_index], uv, 0.0); + float _e233 = v1_; + v1_ = _e233 + _e232; + metal::float4 _e239 = texture_array_bounded[0].sample(samp[0], uv, metal::gradient2d(uv, uv)); + metal::float4 _e240 = v4_; + v4_ = _e240 + _e239; + metal::float4 _e246 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::gradient2d(uv, uv)); + metal::float4 _e247 = v4_; + v4_ = _e247 + _e246; + metal::float4 _e253 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::gradient2d(uv, uv)); + metal::float4 _e254 = v4_; + v4_ = _e254 + _e253; + metal::float4 _e261 = texture_array_bounded[0].sample(samp[0], uv, metal::level(0.0)); metal::float4 _e262 = v4_; v4_ = _e262 + _e261; - metal::float4 _e268 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::gradient2d(uv, uv)); - metal::float4 _e269 = v4_; - v4_ = _e269 + _e268; - metal::float4 _e275 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::gradient2d(uv, uv)); - metal::float4 _e276 = v4_; - v4_ = _e276 + _e275; - metal::float4 _e285 = texture_array_bounded[0].sample(samp[0], uv, metal::level(0.0)); - metal::float4 _e286 = v4_; - v4_ = _e286 + _e285; - metal::float4 _e293 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::level(0.0)); - metal::float4 _e294 = v4_; - v4_ = _e294 + _e293; - metal::float4 _e301 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::level(0.0)); - metal::float4 _e302 = v4_; - v4_ = _e302 + _e301; - metal::float4 _e307 = v4_; + metal::float4 _e269 = texture_array_bounded[uniform_index].sample(samp[uniform_index], uv, metal::level(0.0)); + metal::float4 _e270 = v4_; + v4_ = _e270 + _e269; + metal::float4 _e277 = texture_array_bounded[non_uniform_index].sample(samp[non_uniform_index], uv, metal::level(0.0)); + metal::float4 _e278 = v4_; + v4_ = _e278 + _e277; + metal::float4 _e282 = v4_; if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[0].get_width(), texture_array_storage[0].get_height()))) { - texture_array_storage[0].write(_e307, metal::uint2(pix)); + texture_array_storage[0].write(_e282, metal::uint2(pix)); } - metal::float4 _e310 = v4_; + metal::float4 _e285 = v4_; if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[uniform_index].get_width(), texture_array_storage[uniform_index].get_height()))) { - texture_array_storage[uniform_index].write(_e310, metal::uint2(pix)); + texture_array_storage[uniform_index].write(_e285, metal::uint2(pix)); } - metal::float4 _e313 = v4_; + metal::float4 _e288 = v4_; if (metal::all(metal::uint2(pix) < metal::uint2(texture_array_storage[non_uniform_index].get_width(), texture_array_storage[non_uniform_index].get_height()))) { - texture_array_storage[non_uniform_index].write(_e313, metal::uint2(pix)); + texture_array_storage[non_uniform_index].write(_e288, metal::uint2(pix)); } - metal::uint2 _e314 = u2_; - uint _e315 = u1_; - metal::float2 v2_ = static_cast(_e314 + metal::uint2(_e315)); - metal::float4 _e319 = v4_; - float _e326 = v1_; - return main_Output { (_e319 + metal::float4(v2_.x, v2_.y, v2_.x, v2_.y)) + metal::float4(_e326) }; + metal::uint2 _e289 = u2_; + uint _e290 = u1_; + metal::float2 v2_ = static_cast(_e289 + metal::uint2(_e290)); + metal::float4 _e294 = v4_; + float _e301 = v1_; + return main_Output { (_e294 + metal::float4(v2_.x, v2_.y, v2_.x, v2_.y)) + metal::float4(_e301) }; } diff --git a/tests/out/msl/bounds-check-restrict.msl b/tests/out/msl/bounds-check-restrict.msl index 49a232e70..4191fd276 100644 --- a/tests/out/msl/bounds-check-restrict.msl +++ b/tests/out/msl/bounds-check-restrict.msl @@ -86,10 +86,10 @@ float index_in_bounds( device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e4 = globals.a.inner[9]; - float _e9 = globals.v.w; - float _e17 = globals.m[2].w; - return (_e4 + _e9) + _e17; + float _e3 = globals.a.inner[9]; + float _e7 = globals.v.w; + float _e13 = globals.m[2].w; + return (_e3 + _e7) + _e13; } void set_array( diff --git a/tests/out/msl/bounds-check-zero.msl b/tests/out/msl/bounds-check-zero.msl index 816983d98..c83f25b31 100644 --- a/tests/out/msl/bounds-check-zero.msl +++ b/tests/out/msl/bounds-check-zero.msl @@ -93,10 +93,10 @@ float index_in_bounds( device Globals const& globals, constant _mslBufferSizes& _buffer_sizes ) { - float _e4 = globals.a.inner[9]; - float _e9 = globals.v.w; - float _e17 = globals.m[2].w; - return (_e4 + _e9) + _e17; + float _e3 = globals.a.inner[9]; + float _e7 = globals.v.w; + float _e13 = globals.m[2].w; + return (_e3 + _e7) + _e13; } void set_array( diff --git a/tests/out/msl/do-while.msl b/tests/out/msl/do-while.msl index 4f928d1f3..6ddd59dab 100644 --- a/tests/out/msl/do-while.msl +++ b/tests/out/msl/do-while.msl @@ -11,7 +11,7 @@ void fb1_( bool loop_init = true; while(true) { if (!loop_init) { - bool _e2 = cond; + bool _e1 = cond; if (!(cond)) { break; } diff --git a/tests/out/msl/empty-global-name.msl b/tests/out/msl/empty-global-name.msl index f456649bc..1cbf9adf4 100644 --- a/tests/out/msl/empty-global-name.msl +++ b/tests/out/msl/empty-global-name.msl @@ -11,8 +11,8 @@ struct type_1 { void function( device type_1& unnamed ) { - int _e4 = unnamed.member; - unnamed.member = _e4 + 1; + int _e3 = unnamed.member; + unnamed.member = _e3 + 1; return; } diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index d9142c199..9e964d6c1 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -47,8 +47,8 @@ void test_msl_packed_vec3_( idx = 1; alignment.v3_[0] = 1.0; alignment.v3_[0] = 2.0; - int _e17 = idx; - alignment.v3_[_e17] = 3.0; + int _e16 = idx; + alignment.v3_[_e16] = 3.0; FooStruct data = alignment; metal::float3 l0_ = data.v3_; metal::float2 l1_ = metal::float3(data.v3_).zx; @@ -80,20 +80,20 @@ kernel void main_( float Foo = {}; bool at = {}; test_msl_packed_vec3_(alignment); - metal::float4x2 _e8 = global_nested_arrays_of_matrices_4x2_.inner[0].inner[0]; - metal::float4 _e16 = global_nested_arrays_of_matrices_2x4_.inner[0].inner[0][0]; - wg.inner[7] = (_e8 * _e16).x; - metal::float3x2 _e23 = global_mat; - metal::float3 _e25 = global_vec; - wg.inner[6] = (_e23 * _e25).x; - float _e35 = dummy[1].y; - wg.inner[5] = _e35; - float _e43 = float_vecs.inner[0].w; - wg.inner[4] = _e43; - float _e49 = alignment.v1_; - wg.inner[3] = _e49; - float _e56 = alignment.v3_[0]; - wg.inner[2] = _e56; + metal::float4x2 _e5 = global_nested_arrays_of_matrices_4x2_.inner[0].inner[0]; + metal::float4 _e10 = global_nested_arrays_of_matrices_2x4_.inner[0].inner[0][0]; + wg.inner[7] = (_e5 * _e10).x; + metal::float3x2 _e16 = global_mat; + metal::float3 _e18 = global_vec; + wg.inner[6] = (_e16 * _e18).x; + float _e26 = dummy[1].y; + wg.inner[5] = _e26; + float _e32 = float_vecs.inner[0].w; + wg.inner[4] = _e32; + float _e37 = alignment.v1_; + wg.inner[3] = _e37; + float _e43 = alignment.v3_[0]; + wg.inner[2] = _e43; alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index de3e990db..a80c71bef 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -237,10 +237,10 @@ void assignment( int _e36 = a_1; a_1 = _e36 - 1; vec0_ = metal::int3 {}; - int _e43 = vec0_.y; - vec0_.y = _e43 + 1; - int _e48 = vec0_.y; - vec0_.y = _e48 - 1; + int _e42 = vec0_.y; + vec0_.y = _e42 + 1; + int _e46 = vec0_.y; + vec0_.y = _e46 - 1; return; } diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index d322cbcb9..718d7aafa 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -4,16 +4,16 @@ using metal::uint; -struct type_5 { +struct type_3 { float inner[1]; }; struct gl_PerVertex { metal::float4 gl_Position; float gl_PointSize; - type_5 gl_ClipDistance; - type_5 gl_CullDistance; + type_3 gl_ClipDistance; + type_3 gl_CullDistance; }; -struct type_9 { +struct type_4 { metal::float2 member; metal::float4 gl_Position; }; @@ -24,10 +24,10 @@ void main_1( thread gl_PerVertex& perVertexStruct, thread metal::float2& a_pos_1 ) { - metal::float2 _e8 = a_uv_1; - v_uv = _e8; - metal::float2 _e9 = a_pos_1; - perVertexStruct.gl_Position = metal::float4(_e9.x, _e9.y, 0.0, 1.0); + metal::float2 _e6 = a_uv_1; + v_uv = _e6; + metal::float2 _e7 = a_pos_1; + perVertexStruct.gl_Position = metal::float4(_e7.x, _e7.y, 0.0, 1.0); return; } @@ -44,7 +44,7 @@ vertex main_Output main_( ) { metal::float2 v_uv = {}; metal::float2 a_uv_1 = {}; - gl_PerVertex perVertexStruct = gl_PerVertex {metal::float4(0.0, 0.0, 0.0, 1.0), 1.0, type_5 {}, type_5 {}}; + gl_PerVertex perVertexStruct = gl_PerVertex {metal::float4(0.0, 0.0, 0.0, 1.0), 1.0, type_3 {}, type_3 {}}; metal::float2 a_pos_1 = {}; const auto a_uv = varyings.a_uv; const auto a_pos = varyings.a_pos; @@ -53,6 +53,6 @@ vertex main_Output main_( main_1(v_uv, a_uv_1, perVertexStruct, a_pos_1); metal::float2 _e7 = v_uv; metal::float4 _e8 = perVertexStruct.gl_Position; - const auto _tmp = type_9 {_e7, _e8}; + const auto _tmp = type_4 {_e7, _e8}; return main_Output { _tmp.member, _tmp.gl_Position }; } diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index cb0cdeda2..d5b6524ee 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 324 +; Bound: 322 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %237 "foo_vert" %232 %235 -OpEntryPoint Fragment %284 "foo_frag" %283 -OpEntryPoint GLCompute %304 "assign_through_ptr" %307 -OpExecutionMode %284 OriginUpperLeft -OpExecutionMode %304 LocalSize 1 1 1 +OpEntryPoint Vertex %232 "foo_vert" %227 %230 +OpEntryPoint Fragment %282 "foo_frag" %281 +OpEntryPoint GLCompute %302 "assign_through_ptr" %305 +OpExecutionMode %282 OriginUpperLeft +OpExecutionMode %302 LocalSize 1 1 1 OpMemberName %6 0 "a" OpMemberName %6 1 "b" OpMemberName %6 2 "c" @@ -28,33 +28,33 @@ OpMemberName %22 0 "m" OpName %22 "Baz" OpMemberName %26 0 "am" OpName %26 "MatCx2InArray" -OpName %45 "global_const" -OpName %47 "bar" -OpName %49 "baz" -OpName %52 "qux" -OpName %55 "nested_mat_cx2" -OpName %58 "val" -OpName %59 "idx" -OpName %62 "t" -OpName %66 "test_matrix_within_struct_accesses" -OpName %137 "idx" -OpName %138 "t" -OpName %142 "test_matrix_within_array_within_struct_accesses" -OpName %200 "foo" -OpName %201 "read_from_private" -OpName %206 "a" -OpName %207 "test_arr_as_arg" -OpName %213 "p" -OpName %214 "assign_through_ptr_fn" -OpName %219 "foo" -OpName %220 "assign_array_through_ptr_fn" -OpName %226 "foo" -OpName %228 "c2" -OpName %232 "vi" -OpName %237 "foo_vert" -OpName %284 "foo_frag" -OpName %301 "arr" -OpName %304 "assign_through_ptr" +OpName %40 "global_const" +OpName %42 "bar" +OpName %44 "baz" +OpName %47 "qux" +OpName %50 "nested_mat_cx2" +OpName %53 "val" +OpName %54 "idx" +OpName %57 "t" +OpName %61 "test_matrix_within_struct_accesses" +OpName %132 "idx" +OpName %133 "t" +OpName %137 "test_matrix_within_array_within_struct_accesses" +OpName %195 "foo" +OpName %196 "read_from_private" +OpName %201 "a" +OpName %202 "test_arr_as_arg" +OpName %208 "p" +OpName %209 "assign_through_ptr_fn" +OpName %214 "foo" +OpName %215 "assign_array_through_ptr_fn" +OpName %221 "foo" +OpName %223 "c2" +OpName %227 "vi" +OpName %232 "foo_vert" +OpName %282 "foo_frag" +OpName %299 "arr" +OpName %302 "assign_through_ptr" OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpMemberDecorate %6 2 Offset 28 @@ -83,26 +83,26 @@ OpMemberDecorate %26 0 ColMajor OpMemberDecorate %26 0 MatrixStride 8 OpDecorate %28 ArrayStride 4 OpDecorate %29 ArrayStride 40 -OpDecorate %33 ArrayStride 4 -OpDecorate %36 ArrayStride 16 +OpDecorate %32 ArrayStride 4 +OpDecorate %34 ArrayStride 16 +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 0 +OpDecorate %44 DescriptorSet 0 +OpDecorate %44 Binding 1 +OpDecorate %45 Block +OpMemberDecorate %45 0 Offset 0 OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 0 -OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 1 -OpDecorate %50 Block -OpMemberDecorate %50 0 Offset 0 -OpDecorate %52 DescriptorSet 0 -OpDecorate %52 Binding 2 -OpDecorate %53 Block -OpMemberDecorate %53 0 Offset 0 -OpDecorate %55 DescriptorSet 0 -OpDecorate %55 Binding 3 -OpDecorate %56 Block -OpMemberDecorate %56 0 Offset 0 -OpDecorate %232 BuiltIn VertexIndex -OpDecorate %235 BuiltIn Position -OpDecorate %283 Location 0 -OpDecorate %307 BuiltIn LocalInvocationId +OpDecorate %47 Binding 2 +OpDecorate %48 Block +OpMemberDecorate %48 0 Offset 0 +OpDecorate %50 DescriptorSet 0 +OpDecorate %50 Binding 3 +OpDecorate %51 Block +OpMemberDecorate %51 0 Offset 0 +OpDecorate %227 BuiltIn VertexIndex +OpDecorate %230 BuiltIn Position +OpDecorate %281 Location 0 +OpDecorate %305 BuiltIn LocalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeVector %3 3 @@ -133,365 +133,363 @@ OpDecorate %307 BuiltIn LocalInvocationId %30 = OpConstant %3 5 %29 = OpTypeArray %28 %30 %31 = OpTypeVector %10 4 -%32 = OpTypePointer StorageBuffer %5 -%33 = OpTypeArray %5 %30 -%34 = OpTypeVector %5 4 -%35 = OpTypePointer Workgroup %3 -%36 = OpTypeArray %31 %14 -%37 = OpTypePointer Function %36 -%38 = OpConstant %3 0 -%39 = OpConstantComposite %4 %38 %38 %38 -%40 = OpConstant %5 0 -%41 = OpConstantComposite %6 %38 %39 %40 -%42 = OpConstant %5 2 -%43 = OpConstant %5 10 -%44 = OpConstant %5 5 -%46 = OpTypePointer Private %6 -%45 = OpVariable %46 Private %41 -%48 = OpTypePointer StorageBuffer %20 -%47 = OpVariable %48 StorageBuffer -%50 = OpTypeStruct %22 -%51 = OpTypePointer Uniform %50 -%49 = OpVariable %51 Uniform -%53 = OpTypeStruct %23 -%54 = OpTypePointer StorageBuffer %53 -%52 = OpVariable %54 StorageBuffer -%56 = OpTypeStruct %26 -%57 = OpTypePointer Uniform %56 -%55 = OpVariable %57 Uniform -%58 = OpVariable %35 Workgroup -%60 = OpTypePointer Function %5 -%61 = OpConstantNull %5 -%63 = OpTypePointer Function %22 -%64 = OpConstantNull %22 -%67 = OpTypeFunction %2 -%68 = OpTypePointer Uniform %22 -%70 = OpConstant %5 1 -%71 = OpConstant %10 1.0 -%72 = OpConstant %10 2.0 -%73 = OpConstant %10 3.0 -%74 = OpConstant %10 6.0 -%75 = OpConstant %10 5.0 -%76 = OpConstant %10 4.0 -%77 = OpConstant %10 9.0 -%78 = OpConstant %10 90.0 -%79 = OpConstant %10 10.0 -%80 = OpConstant %10 20.0 -%81 = OpConstant %10 30.0 -%82 = OpConstant %10 40.0 -%86 = OpTypePointer Uniform %21 -%89 = OpTypePointer Uniform %12 -%95 = OpTypePointer Uniform %10 -%96 = OpConstant %3 1 -%116 = OpTypePointer Function %21 -%122 = OpTypePointer Function %12 -%128 = OpTypePointer Function %10 -%139 = OpTypePointer Function %26 -%140 = OpConstantNull %26 -%143 = OpTypePointer Uniform %26 -%145 = OpConstantNull %25 -%146 = OpConstant %10 8.0 -%147 = OpConstant %10 7.0 -%151 = OpTypePointer Uniform %25 -%154 = OpTypePointer Uniform %24 -%177 = OpTypePointer Function %25 -%179 = OpTypePointer Function %24 -%202 = OpTypeFunction %10 %27 -%208 = OpTypeFunction %10 %29 -%215 = OpTypeFunction %2 %35 -%216 = OpConstant %3 42 -%221 = OpTypeFunction %2 %37 -%227 = OpConstantNull %10 -%229 = OpTypePointer Function %33 -%230 = OpConstantNull %33 -%233 = OpTypePointer Input %3 -%232 = OpVariable %233 Input -%236 = OpTypePointer Output %31 -%235 = OpVariable %236 Output -%239 = OpTypePointer StorageBuffer %23 -%242 = OpConstant %10 0.0 -%243 = OpConstant %3 3 -%244 = OpConstant %5 3 -%245 = OpConstant %5 4 -%246 = OpConstant %5 42 -%247 = OpConstantNull %29 -%252 = OpTypePointer StorageBuffer %8 -%255 = OpTypePointer StorageBuffer %18 -%256 = OpConstant %3 4 -%259 = OpTypePointer StorageBuffer %9 -%260 = OpTypePointer StorageBuffer %10 -%263 = OpTypePointer StorageBuffer %19 -%266 = OpTypePointer StorageBuffer %7 -%283 = OpVariable %236 Output -%286 = OpConstantNull %23 -%302 = OpConstantNull %36 -%306 = OpConstantNull %3 -%308 = OpTypePointer Input %4 -%307 = OpVariable %308 Input -%310 = OpConstantNull %4 -%312 = OpTypeBool -%311 = OpTypeVector %312 3 -%317 = OpConstant %3 264 -%66 = OpFunction %2 None %67 -%65 = OpLabel -%59 = OpVariable %60 Function %61 -%62 = OpVariable %63 Function %64 -%69 = OpAccessChain %68 %49 %38 -OpBranch %83 -%83 = OpLabel -OpStore %59 %70 -%84 = OpLoad %5 %59 -%85 = OpISub %5 %84 %70 -OpStore %59 %85 -%87 = OpAccessChain %86 %69 %38 -%88 = OpLoad %21 %87 -%90 = OpAccessChain %89 %69 %38 %38 -%91 = OpLoad %12 %90 -%92 = OpLoad %5 %59 -%93 = OpAccessChain %89 %69 %38 %92 -%94 = OpLoad %12 %93 -%97 = OpAccessChain %95 %69 %38 %38 %96 -%98 = OpLoad %10 %97 -%99 = OpLoad %5 %59 -%100 = OpAccessChain %95 %69 %38 %38 %99 -%101 = OpLoad %10 %100 -%102 = OpLoad %5 %59 -%103 = OpAccessChain %95 %69 %38 %102 %96 -%104 = OpLoad %10 %103 -%105 = OpLoad %5 %59 -%106 = OpLoad %5 %59 -%107 = OpAccessChain %95 %69 %38 %105 %106 -%108 = OpLoad %10 %107 -%109 = OpCompositeConstruct %12 %71 %71 -%110 = OpCompositeConstruct %12 %72 %72 -%111 = OpCompositeConstruct %12 %73 %73 -%112 = OpCompositeConstruct %21 %109 %110 %111 -%113 = OpCompositeConstruct %22 %112 -OpStore %62 %113 -%114 = OpLoad %5 %59 -%115 = OpIAdd %5 %114 %70 -OpStore %59 %115 -%117 = OpCompositeConstruct %12 %74 %74 -%118 = OpCompositeConstruct %12 %75 %75 -%119 = OpCompositeConstruct %12 %76 %76 -%120 = OpCompositeConstruct %21 %117 %118 %119 -%121 = OpAccessChain %116 %62 %38 -OpStore %121 %120 -%123 = OpCompositeConstruct %12 %77 %77 -%124 = OpAccessChain %122 %62 %38 %38 -OpStore %124 %123 -%125 = OpLoad %5 %59 -%126 = OpCompositeConstruct %12 %78 %78 -%127 = OpAccessChain %122 %62 %38 %125 -OpStore %127 %126 -%129 = OpAccessChain %128 %62 %38 %38 %96 -OpStore %129 %79 -%130 = OpLoad %5 %59 -%131 = OpAccessChain %128 %62 %38 %38 %130 -OpStore %131 %80 -%132 = OpLoad %5 %59 -%133 = OpAccessChain %128 %62 %38 %132 %96 -OpStore %133 %81 -%134 = OpLoad %5 %59 -%135 = OpLoad %5 %59 -%136 = OpAccessChain %128 %62 %38 %134 %135 -OpStore %136 %82 +%32 = OpTypeArray %5 %30 +%33 = OpTypePointer Workgroup %3 +%34 = OpTypeArray %31 %14 +%35 = OpTypePointer Function %34 +%36 = OpConstant %3 0 +%37 = OpConstantComposite %4 %36 %36 %36 +%38 = OpConstant %5 0 +%39 = OpConstantComposite %6 %36 %37 %38 +%41 = OpTypePointer Private %6 +%40 = OpVariable %41 Private %39 +%43 = OpTypePointer StorageBuffer %20 +%42 = OpVariable %43 StorageBuffer +%45 = OpTypeStruct %22 +%46 = OpTypePointer Uniform %45 +%44 = OpVariable %46 Uniform +%48 = OpTypeStruct %23 +%49 = OpTypePointer StorageBuffer %48 +%47 = OpVariable %49 StorageBuffer +%51 = OpTypeStruct %26 +%52 = OpTypePointer Uniform %51 +%50 = OpVariable %52 Uniform +%53 = OpVariable %33 Workgroup +%55 = OpTypePointer Function %5 +%56 = OpConstantNull %5 +%58 = OpTypePointer Function %22 +%59 = OpConstantNull %22 +%62 = OpTypeFunction %2 +%63 = OpTypePointer Uniform %22 +%65 = OpConstant %5 1 +%66 = OpConstant %10 1.0 +%67 = OpConstant %10 2.0 +%68 = OpConstant %10 3.0 +%69 = OpConstant %10 6.0 +%70 = OpConstant %10 5.0 +%71 = OpConstant %10 4.0 +%72 = OpConstant %10 9.0 +%73 = OpConstant %10 90.0 +%74 = OpConstant %10 10.0 +%75 = OpConstant %10 20.0 +%76 = OpConstant %10 30.0 +%77 = OpConstant %10 40.0 +%81 = OpTypePointer Uniform %21 +%84 = OpTypePointer Uniform %12 +%90 = OpTypePointer Uniform %10 +%91 = OpConstant %3 1 +%111 = OpTypePointer Function %21 +%117 = OpTypePointer Function %12 +%123 = OpTypePointer Function %10 +%134 = OpTypePointer Function %26 +%135 = OpConstantNull %26 +%138 = OpTypePointer Uniform %26 +%140 = OpConstantNull %25 +%141 = OpConstant %10 8.0 +%142 = OpConstant %10 7.0 +%146 = OpTypePointer Uniform %25 +%149 = OpTypePointer Uniform %24 +%172 = OpTypePointer Function %25 +%174 = OpTypePointer Function %24 +%197 = OpTypeFunction %10 %27 +%203 = OpTypeFunction %10 %29 +%210 = OpTypeFunction %2 %33 +%211 = OpConstant %3 42 +%216 = OpTypeFunction %2 %35 +%222 = OpConstantNull %10 +%224 = OpTypePointer Function %32 +%225 = OpConstantNull %32 +%228 = OpTypePointer Input %3 +%227 = OpVariable %228 Input +%231 = OpTypePointer Output %31 +%230 = OpVariable %231 Output +%234 = OpTypePointer StorageBuffer %23 +%237 = OpConstant %10 0.0 +%238 = OpConstant %3 3 +%239 = OpConstant %5 3 +%240 = OpConstant %5 4 +%241 = OpConstant %5 5 +%242 = OpConstant %5 42 +%243 = OpConstantNull %29 +%248 = OpTypePointer StorageBuffer %8 +%251 = OpTypePointer StorageBuffer %18 +%252 = OpConstant %3 4 +%255 = OpTypePointer StorageBuffer %9 +%256 = OpTypePointer StorageBuffer %10 +%259 = OpTypePointer StorageBuffer %19 +%262 = OpTypePointer StorageBuffer %7 +%263 = OpTypePointer StorageBuffer %5 +%275 = OpTypeVector %5 4 +%281 = OpVariable %231 Output +%284 = OpConstantNull %23 +%300 = OpConstantNull %34 +%304 = OpConstantNull %3 +%306 = OpTypePointer Input %4 +%305 = OpVariable %306 Input +%308 = OpConstantNull %4 +%310 = OpTypeBool +%309 = OpTypeVector %310 3 +%315 = OpConstant %3 264 +%61 = OpFunction %2 None %62 +%60 = OpLabel +%54 = OpVariable %55 Function %56 +%57 = OpVariable %58 Function %59 +%64 = OpAccessChain %63 %44 %36 +OpBranch %78 +%78 = OpLabel +OpStore %54 %65 +%79 = OpLoad %5 %54 +%80 = OpISub %5 %79 %65 +OpStore %54 %80 +%82 = OpAccessChain %81 %64 %36 +%83 = OpLoad %21 %82 +%85 = OpAccessChain %84 %64 %36 %36 +%86 = OpLoad %12 %85 +%87 = OpLoad %5 %54 +%88 = OpAccessChain %84 %64 %36 %87 +%89 = OpLoad %12 %88 +%92 = OpAccessChain %90 %64 %36 %36 %91 +%93 = OpLoad %10 %92 +%94 = OpLoad %5 %54 +%95 = OpAccessChain %90 %64 %36 %36 %94 +%96 = OpLoad %10 %95 +%97 = OpLoad %5 %54 +%98 = OpAccessChain %90 %64 %36 %97 %91 +%99 = OpLoad %10 %98 +%100 = OpLoad %5 %54 +%101 = OpLoad %5 %54 +%102 = OpAccessChain %90 %64 %36 %100 %101 +%103 = OpLoad %10 %102 +%104 = OpCompositeConstruct %12 %66 %66 +%105 = OpCompositeConstruct %12 %67 %67 +%106 = OpCompositeConstruct %12 %68 %68 +%107 = OpCompositeConstruct %21 %104 %105 %106 +%108 = OpCompositeConstruct %22 %107 +OpStore %57 %108 +%109 = OpLoad %5 %54 +%110 = OpIAdd %5 %109 %65 +OpStore %54 %110 +%112 = OpCompositeConstruct %12 %69 %69 +%113 = OpCompositeConstruct %12 %70 %70 +%114 = OpCompositeConstruct %12 %71 %71 +%115 = OpCompositeConstruct %21 %112 %113 %114 +%116 = OpAccessChain %111 %57 %36 +OpStore %116 %115 +%118 = OpCompositeConstruct %12 %72 %72 +%119 = OpAccessChain %117 %57 %36 %36 +OpStore %119 %118 +%120 = OpLoad %5 %54 +%121 = OpCompositeConstruct %12 %73 %73 +%122 = OpAccessChain %117 %57 %36 %120 +OpStore %122 %121 +%124 = OpAccessChain %123 %57 %36 %36 %91 +OpStore %124 %74 +%125 = OpLoad %5 %54 +%126 = OpAccessChain %123 %57 %36 %36 %125 +OpStore %126 %75 +%127 = OpLoad %5 %54 +%128 = OpAccessChain %123 %57 %36 %127 %91 +OpStore %128 %76 +%129 = OpLoad %5 %54 +%130 = OpLoad %5 %54 +%131 = OpAccessChain %123 %57 %36 %129 %130 +OpStore %131 %77 OpReturn OpFunctionEnd -%142 = OpFunction %2 None %67 -%141 = OpLabel -%137 = OpVariable %60 Function %61 -%138 = OpVariable %139 Function %140 -%144 = OpAccessChain %143 %55 %38 -OpBranch %148 -%148 = OpLabel -OpStore %137 %70 -%149 = OpLoad %5 %137 -%150 = OpISub %5 %149 %70 -OpStore %137 %150 -%152 = OpAccessChain %151 %144 %38 -%153 = OpLoad %25 %152 -%155 = OpAccessChain %154 %144 %38 %38 -%156 = OpLoad %24 %155 -%157 = OpAccessChain %89 %144 %38 %38 %38 -%158 = OpLoad %12 %157 -%159 = OpLoad %5 %137 -%160 = OpAccessChain %89 %144 %38 %38 %159 -%161 = OpLoad %12 %160 -%162 = OpAccessChain %95 %144 %38 %38 %38 %96 -%163 = OpLoad %10 %162 -%164 = OpLoad %5 %137 -%165 = OpAccessChain %95 %144 %38 %38 %38 %164 -%166 = OpLoad %10 %165 -%167 = OpLoad %5 %137 -%168 = OpAccessChain %95 %144 %38 %38 %167 %96 -%169 = OpLoad %10 %168 -%170 = OpLoad %5 %137 -%171 = OpLoad %5 %137 -%172 = OpAccessChain %95 %144 %38 %38 %170 %171 -%173 = OpLoad %10 %172 -%174 = OpCompositeConstruct %26 %145 -OpStore %138 %174 -%175 = OpLoad %5 %137 -%176 = OpIAdd %5 %175 %70 -OpStore %137 %176 -%178 = OpAccessChain %177 %138 %38 -OpStore %178 %145 -%180 = OpCompositeConstruct %12 %146 %146 -%181 = OpCompositeConstruct %12 %147 %147 -%182 = OpCompositeConstruct %12 %74 %74 -%183 = OpCompositeConstruct %12 %75 %75 -%184 = OpCompositeConstruct %24 %180 %181 %182 %183 -%185 = OpAccessChain %179 %138 %38 %38 +%137 = OpFunction %2 None %62 +%136 = OpLabel +%132 = OpVariable %55 Function %56 +%133 = OpVariable %134 Function %135 +%139 = OpAccessChain %138 %50 %36 +OpBranch %143 +%143 = OpLabel +OpStore %132 %65 +%144 = OpLoad %5 %132 +%145 = OpISub %5 %144 %65 +OpStore %132 %145 +%147 = OpAccessChain %146 %139 %36 +%148 = OpLoad %25 %147 +%150 = OpAccessChain %149 %139 %36 %36 +%151 = OpLoad %24 %150 +%152 = OpAccessChain %84 %139 %36 %36 %36 +%153 = OpLoad %12 %152 +%154 = OpLoad %5 %132 +%155 = OpAccessChain %84 %139 %36 %36 %154 +%156 = OpLoad %12 %155 +%157 = OpAccessChain %90 %139 %36 %36 %36 %91 +%158 = OpLoad %10 %157 +%159 = OpLoad %5 %132 +%160 = OpAccessChain %90 %139 %36 %36 %36 %159 +%161 = OpLoad %10 %160 +%162 = OpLoad %5 %132 +%163 = OpAccessChain %90 %139 %36 %36 %162 %91 +%164 = OpLoad %10 %163 +%165 = OpLoad %5 %132 +%166 = OpLoad %5 %132 +%167 = OpAccessChain %90 %139 %36 %36 %165 %166 +%168 = OpLoad %10 %167 +%169 = OpCompositeConstruct %26 %140 +OpStore %133 %169 +%170 = OpLoad %5 %132 +%171 = OpIAdd %5 %170 %65 +OpStore %132 %171 +%173 = OpAccessChain %172 %133 %36 +OpStore %173 %140 +%175 = OpCompositeConstruct %12 %141 %141 +%176 = OpCompositeConstruct %12 %142 %142 +%177 = OpCompositeConstruct %12 %69 %69 +%178 = OpCompositeConstruct %12 %70 %70 +%179 = OpCompositeConstruct %24 %175 %176 %177 %178 +%180 = OpAccessChain %174 %133 %36 %36 +OpStore %180 %179 +%181 = OpCompositeConstruct %12 %72 %72 +%182 = OpAccessChain %117 %133 %36 %36 %36 +OpStore %182 %181 +%183 = OpLoad %5 %132 +%184 = OpCompositeConstruct %12 %73 %73 +%185 = OpAccessChain %117 %133 %36 %36 %183 OpStore %185 %184 -%186 = OpCompositeConstruct %12 %77 %77 -%187 = OpAccessChain %122 %138 %38 %38 %38 -OpStore %187 %186 -%188 = OpLoad %5 %137 -%189 = OpCompositeConstruct %12 %78 %78 -%190 = OpAccessChain %122 %138 %38 %38 %188 -OpStore %190 %189 -%191 = OpAccessChain %128 %138 %38 %38 %38 %96 -OpStore %191 %79 -%192 = OpLoad %5 %137 -%193 = OpAccessChain %128 %138 %38 %38 %38 %192 -OpStore %193 %80 -%194 = OpLoad %5 %137 -%195 = OpAccessChain %128 %138 %38 %38 %194 %96 -OpStore %195 %81 -%196 = OpLoad %5 %137 -%197 = OpLoad %5 %137 -%198 = OpAccessChain %128 %138 %38 %38 %196 %197 -OpStore %198 %82 +%186 = OpAccessChain %123 %133 %36 %36 %36 %91 +OpStore %186 %74 +%187 = OpLoad %5 %132 +%188 = OpAccessChain %123 %133 %36 %36 %36 %187 +OpStore %188 %75 +%189 = OpLoad %5 %132 +%190 = OpAccessChain %123 %133 %36 %36 %189 %91 +OpStore %190 %76 +%191 = OpLoad %5 %132 +%192 = OpLoad %5 %132 +%193 = OpAccessChain %123 %133 %36 %36 %191 %192 +OpStore %193 %77 OpReturn OpFunctionEnd -%201 = OpFunction %10 None %202 -%200 = OpFunctionParameter %27 -%199 = OpLabel -OpBranch %203 -%203 = OpLabel -%204 = OpLoad %10 %200 -OpReturnValue %204 +%196 = OpFunction %10 None %197 +%195 = OpFunctionParameter %27 +%194 = OpLabel +OpBranch %198 +%198 = OpLabel +%199 = OpLoad %10 %195 +OpReturnValue %199 OpFunctionEnd -%207 = OpFunction %10 None %208 -%206 = OpFunctionParameter %29 -%205 = OpLabel -OpBranch %209 -%209 = OpLabel -%210 = OpCompositeExtract %28 %206 4 -%211 = OpCompositeExtract %10 %210 9 -OpReturnValue %211 +%202 = OpFunction %10 None %203 +%201 = OpFunctionParameter %29 +%200 = OpLabel +OpBranch %204 +%204 = OpLabel +%205 = OpCompositeExtract %28 %201 4 +%206 = OpCompositeExtract %10 %205 9 +OpReturnValue %206 OpFunctionEnd -%214 = OpFunction %2 None %215 -%213 = OpFunctionParameter %35 +%209 = OpFunction %2 None %210 +%208 = OpFunctionParameter %33 +%207 = OpLabel +OpBranch %212 %212 = OpLabel +OpStore %208 %211 +OpReturn +OpFunctionEnd +%215 = OpFunction %2 None %216 +%214 = OpFunctionParameter %35 +%213 = OpLabel OpBranch %217 %217 = OpLabel -OpStore %213 %216 +%218 = OpCompositeConstruct %31 %66 %66 %66 %66 +%219 = OpCompositeConstruct %31 %67 %67 %67 %67 +%220 = OpCompositeConstruct %34 %218 %219 +OpStore %214 %220 OpReturn OpFunctionEnd -%220 = OpFunction %2 None %221 -%219 = OpFunctionParameter %37 -%218 = OpLabel -OpBranch %222 -%222 = OpLabel -%223 = OpCompositeConstruct %31 %71 %71 %71 %71 -%224 = OpCompositeConstruct %31 %72 %72 %72 %72 -%225 = OpCompositeConstruct %36 %223 %224 -OpStore %219 %225 +%232 = OpFunction %2 None %62 +%226 = OpLabel +%221 = OpVariable %27 Function %222 +%223 = OpVariable %224 Function %225 +%229 = OpLoad %3 %227 +%233 = OpAccessChain %63 %44 %36 +%235 = OpAccessChain %234 %47 %36 +%236 = OpAccessChain %138 %50 %36 +OpBranch %244 +%244 = OpLabel +OpStore %221 %237 +%245 = OpLoad %10 %221 +OpStore %221 %66 +%246 = OpFunctionCall %2 %61 +%247 = OpFunctionCall %2 %137 +%249 = OpAccessChain %248 %42 %36 +%250 = OpLoad %8 %249 +%253 = OpAccessChain %251 %42 %252 +%254 = OpLoad %18 %253 +%257 = OpAccessChain %256 %42 %36 %238 %36 +%258 = OpLoad %10 %257 +%260 = OpArrayLength %3 %42 5 +%261 = OpISub %3 %260 %14 +%264 = OpAccessChain %263 %42 %30 %261 %36 +%265 = OpLoad %5 %264 +%266 = OpLoad %23 %235 +%267 = OpFunctionCall %10 %196 %221 +%268 = OpConvertFToS %5 %258 +%269 = OpCompositeConstruct %32 %265 %268 %239 %240 %241 +OpStore %223 %269 +%270 = OpIAdd %3 %229 %91 +%271 = OpAccessChain %55 %223 %270 +OpStore %271 %242 +%272 = OpAccessChain %55 %223 %229 +%273 = OpLoad %5 %272 +%274 = OpFunctionCall %10 %202 %243 +%276 = OpCompositeConstruct %275 %273 %273 %273 %273 +%277 = OpConvertSToF %31 %276 +%278 = OpMatrixTimesVector %9 %250 %277 +%279 = OpCompositeConstruct %31 %278 %67 +OpStore %230 %279 OpReturn OpFunctionEnd -%237 = OpFunction %2 None %67 -%231 = OpLabel -%226 = OpVariable %27 Function %227 -%228 = OpVariable %229 Function %230 -%234 = OpLoad %3 %232 -%238 = OpAccessChain %68 %49 %38 -%240 = OpAccessChain %239 %52 %38 -%241 = OpAccessChain %143 %55 %38 -OpBranch %248 -%248 = OpLabel -OpStore %226 %242 -%249 = OpLoad %10 %226 -OpStore %226 %71 -%250 = OpFunctionCall %2 %66 -%251 = OpFunctionCall %2 %142 -%253 = OpAccessChain %252 %47 %38 -%254 = OpLoad %8 %253 -%257 = OpAccessChain %255 %47 %256 -%258 = OpLoad %18 %257 -%261 = OpAccessChain %260 %47 %38 %243 %38 -%262 = OpLoad %10 %261 -%264 = OpArrayLength %3 %47 5 -%265 = OpISub %3 %264 %14 -%267 = OpAccessChain %32 %47 %30 %265 %38 -%268 = OpLoad %5 %267 -%269 = OpLoad %23 %240 -%270 = OpFunctionCall %10 %201 %226 -%271 = OpConvertFToS %5 %262 -%272 = OpCompositeConstruct %33 %268 %271 %244 %245 %44 -OpStore %228 %272 -%273 = OpIAdd %3 %234 %96 -%274 = OpAccessChain %60 %228 %273 -OpStore %274 %246 -%275 = OpAccessChain %60 %228 %234 -%276 = OpLoad %5 %275 -%277 = OpFunctionCall %10 %207 %247 -%278 = OpCompositeConstruct %34 %276 %276 %276 %276 -%279 = OpConvertSToF %31 %278 -%280 = OpMatrixTimesVector %9 %254 %279 -%281 = OpCompositeConstruct %31 %280 %72 -OpStore %235 %281 +%282 = OpFunction %2 None %62 +%280 = OpLabel +%283 = OpAccessChain %234 %47 %36 +OpBranch %285 +%285 = OpLabel +%286 = OpAccessChain %256 %42 %36 %91 %14 +OpStore %286 %66 +%287 = OpCompositeConstruct %9 %237 %237 %237 +%288 = OpCompositeConstruct %9 %66 %66 %66 +%289 = OpCompositeConstruct %9 %67 %67 %67 +%290 = OpCompositeConstruct %9 %68 %68 %68 +%291 = OpCompositeConstruct %8 %287 %288 %289 %290 +%292 = OpAccessChain %248 %42 %36 +OpStore %292 %291 +%293 = OpCompositeConstruct %17 %36 %36 +%294 = OpCompositeConstruct %17 %91 %91 +%295 = OpCompositeConstruct %18 %293 %294 +%296 = OpAccessChain %251 %42 %252 +OpStore %296 %295 +%297 = OpAccessChain %263 %42 %30 %91 %36 +OpStore %297 %65 +OpStore %283 %284 +%298 = OpCompositeConstruct %31 %237 %237 %237 %237 +OpStore %281 %298 OpReturn OpFunctionEnd -%284 = OpFunction %2 None %67 -%282 = OpLabel -%285 = OpAccessChain %239 %52 %38 -OpBranch %287 -%287 = OpLabel -%288 = OpAccessChain %260 %47 %38 %96 %14 -OpStore %288 %71 -%289 = OpCompositeConstruct %9 %242 %242 %242 -%290 = OpCompositeConstruct %9 %71 %71 %71 -%291 = OpCompositeConstruct %9 %72 %72 %72 -%292 = OpCompositeConstruct %9 %73 %73 %73 -%293 = OpCompositeConstruct %8 %289 %290 %291 %292 -%294 = OpAccessChain %252 %47 %38 -OpStore %294 %293 -%295 = OpCompositeConstruct %17 %38 %38 -%296 = OpCompositeConstruct %17 %96 %96 -%297 = OpCompositeConstruct %18 %295 %296 -%298 = OpAccessChain %255 %47 %256 -OpStore %298 %297 -%299 = OpAccessChain %32 %47 %30 %96 %38 -OpStore %299 %70 -OpStore %285 %286 -%300 = OpCompositeConstruct %31 %242 %242 %242 %242 -OpStore %283 %300 -OpReturn -OpFunctionEnd -%304 = OpFunction %2 None %67 +%302 = OpFunction %2 None %62 +%301 = OpLabel +%299 = OpVariable %35 Function %300 +OpBranch %303 %303 = OpLabel -%301 = OpVariable %37 Function %302 -OpBranch %305 -%305 = OpLabel -%309 = OpLoad %4 %307 -%313 = OpIEqual %311 %309 %310 -%314 = OpAll %312 %313 -OpSelectionMerge %315 None -OpBranchConditional %314 %316 %315 +%307 = OpLoad %4 %305 +%311 = OpIEqual %309 %307 %308 +%312 = OpAll %310 %311 +OpSelectionMerge %313 None +OpBranchConditional %312 %314 %313 +%314 = OpLabel +OpStore %53 %304 +OpBranch %313 +%313 = OpLabel +OpControlBarrier %14 %14 %315 +OpBranch %316 %316 = OpLabel -OpStore %58 %306 -OpBranch %315 -%315 = OpLabel -OpControlBarrier %14 %14 %317 -OpBranch %318 -%318 = OpLabel -%319 = OpCompositeConstruct %31 %74 %74 %74 %74 -%320 = OpCompositeConstruct %31 %147 %147 %147 %147 -%321 = OpCompositeConstruct %36 %319 %320 -OpStore %301 %321 -%322 = OpFunctionCall %2 %214 %58 -%323 = OpFunctionCall %2 %220 %301 +%317 = OpCompositeConstruct %31 %69 %69 %69 %69 +%318 = OpCompositeConstruct %31 %142 %142 %142 %142 +%319 = OpCompositeConstruct %34 %317 %318 +OpStore %299 %319 +%320 = OpFunctionCall %2 %209 %53 +%321 = OpFunctionCall %2 %215 %299 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/array-in-ctor.spvasm b/tests/out/spv/array-in-ctor.spvasm index 61d1bd48d..aca4ee682 100644 --- a/tests/out/spv/array-in-ctor.spvasm +++ b/tests/out/spv/array-in-ctor.spvasm @@ -1,39 +1,37 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 21 +; Bound: 19 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %14 "cs_main" -OpExecutionMode %14 LocalSize 1 1 1 +OpEntryPoint GLCompute %12 "cs_main" +OpExecutionMode %12 LocalSize 1 1 1 OpDecorate %4 ArrayStride 4 OpMemberDecorate %7 0 Offset 0 -OpDecorate %10 NonWritable -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 0 -OpDecorate %11 Block -OpMemberDecorate %11 0 Offset 0 +OpDecorate %8 NonWritable +OpDecorate %8 DescriptorSet 0 +OpDecorate %8 Binding 0 +OpDecorate %9 Block +OpMemberDecorate %9 0 Offset 0 %2 = OpTypeVoid %3 = OpTypeFloat 32 %6 = OpTypeInt 32 0 %5 = OpConstant %6 2 %4 = OpTypeArray %3 %5 %7 = OpTypeStruct %4 -%9 = OpTypeInt 32 1 -%8 = OpConstant %9 2 -%11 = OpTypeStruct %7 -%12 = OpTypePointer StorageBuffer %11 -%10 = OpVariable %12 StorageBuffer -%15 = OpTypeFunction %2 -%16 = OpTypePointer StorageBuffer %7 -%17 = OpConstant %6 0 -%14 = OpFunction %2 None %15 -%13 = OpLabel -%18 = OpAccessChain %16 %10 %17 -OpBranch %19 -%19 = OpLabel -%20 = OpLoad %7 %18 +%9 = OpTypeStruct %7 +%10 = OpTypePointer StorageBuffer %9 +%8 = OpVariable %10 StorageBuffer +%13 = OpTypeFunction %2 +%14 = OpTypePointer StorageBuffer %7 +%15 = OpConstant %6 0 +%12 = OpFunction %2 None %13 +%11 = OpLabel +%16 = OpAccessChain %14 %8 %15 +OpBranch %17 +%17 = OpLabel +%18 = OpLoad %7 %16 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/array-in-function-return-type.spvasm b/tests/out/spv/array-in-function-return-type.spvasm index 71e1cd6f1..e68f6ad83 100644 --- a/tests/out/spv/array-in-function-return-type.spvasm +++ b/tests/out/spv/array-in-function-return-type.spvasm @@ -1,44 +1,42 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 28 +; Bound: 26 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %20 "main" %18 -OpExecutionMode %20 OriginUpperLeft +OpEntryPoint Fragment %18 "main" %16 +OpExecutionMode %18 OriginUpperLeft OpDecorate %4 ArrayStride 4 -OpDecorate %18 Location 0 +OpDecorate %16 Location 0 %2 = OpTypeVoid %3 = OpTypeFloat 32 %6 = OpTypeInt 32 0 %5 = OpConstant %6 2 %4 = OpTypeArray %3 %5 %7 = OpTypeVector %3 4 -%9 = OpTypeInt 32 1 -%8 = OpConstant %9 2 -%12 = OpTypeFunction %4 -%13 = OpConstant %3 1.0 -%14 = OpConstant %3 2.0 -%19 = OpTypePointer Output %7 -%18 = OpVariable %19 Output -%21 = OpTypeFunction %2 -%22 = OpConstant %3 0.0 -%11 = OpFunction %4 None %12 -%10 = OpLabel -OpBranch %15 -%15 = OpLabel -%16 = OpCompositeConstruct %4 %13 %14 -OpReturnValue %16 +%10 = OpTypeFunction %4 +%11 = OpConstant %3 1.0 +%12 = OpConstant %3 2.0 +%17 = OpTypePointer Output %7 +%16 = OpVariable %17 Output +%19 = OpTypeFunction %2 +%20 = OpConstant %3 0.0 +%9 = OpFunction %4 None %10 +%8 = OpLabel +OpBranch %13 +%13 = OpLabel +%14 = OpCompositeConstruct %4 %11 %12 +OpReturnValue %14 OpFunctionEnd -%20 = OpFunction %2 None %21 -%17 = OpLabel -OpBranch %23 -%23 = OpLabel -%24 = OpFunctionCall %4 %11 -%25 = OpCompositeExtract %3 %24 0 -%26 = OpCompositeExtract %3 %24 1 -%27 = OpCompositeConstruct %7 %25 %26 %22 %13 -OpStore %18 %27 +%18 = OpFunction %2 None %19 +%15 = OpLabel +OpBranch %21 +%21 = OpLabel +%22 = OpFunctionCall %4 %9 +%23 = OpCompositeExtract %3 %22 0 +%24 = OpCompositeExtract %3 %22 1 +%25 = OpCompositeConstruct %7 %23 %24 %20 %11 +OpStore %16 %25 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/tests/out/spv/atomicCompareExchange.spvasm index 05472b750..c73c159ea 100644 --- a/tests/out/spv/atomicCompareExchange.spvasm +++ b/tests/out/spv/atomicCompareExchange.spvasm @@ -6,24 +6,24 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %28 "test_atomic_compare_exchange_i32" +OpEntryPoint GLCompute %27 "test_atomic_compare_exchange_i32" OpEntryPoint GLCompute %81 "test_atomic_compare_exchange_u32" -OpExecutionMode %28 LocalSize 1 1 1 +OpExecutionMode %27 LocalSize 1 1 1 OpExecutionMode %81 LocalSize 1 1 1 OpDecorate %5 ArrayStride 4 OpDecorate %7 ArrayStride 4 +OpMemberDecorate %9 0 Offset 0 +OpMemberDecorate %9 1 Offset 4 OpMemberDecorate %10 0 Offset 0 OpMemberDecorate %10 1 Offset 4 -OpMemberDecorate %11 0 Offset 0 -OpMemberDecorate %11 1 Offset 4 -OpDecorate %12 DescriptorSet 0 -OpDecorate %12 Binding 0 -OpDecorate %13 Block -OpMemberDecorate %13 0 Offset 0 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 1 -OpDecorate %16 Block -OpMemberDecorate %16 0 Offset 0 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 0 +OpDecorate %12 Block +OpMemberDecorate %12 0 Offset 0 +OpDecorate %14 DescriptorSet 0 +OpDecorate %14 Binding 1 +OpDecorate %15 Block +OpMemberDecorate %15 0 Offset 0 %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeInt 32 1 @@ -31,47 +31,47 @@ OpMemberDecorate %16 0 Offset 0 %5 = OpTypeArray %4 %6 %7 = OpTypeArray %3 %6 %8 = OpTypeBool -%9 = OpTypeFloat 32 -%10 = OpTypeStruct %4 %8 -%11 = OpTypeStruct %3 %8 -%13 = OpTypeStruct %5 -%14 = OpTypePointer StorageBuffer %13 -%12 = OpVariable %14 StorageBuffer -%16 = OpTypeStruct %7 -%17 = OpTypePointer StorageBuffer %16 -%15 = OpVariable %17 StorageBuffer -%19 = OpTypePointer Function %3 -%20 = OpConstantNull %3 -%22 = OpTypePointer Function %4 -%23 = OpConstantNull %4 -%25 = OpTypePointer Function %8 -%26 = OpConstantNull %8 -%29 = OpTypeFunction %2 -%30 = OpTypePointer StorageBuffer %5 -%31 = OpConstant %3 0 -%33 = OpConstantFalse %8 -%34 = OpConstant %9 1.0 +%9 = OpTypeStruct %4 %8 +%10 = OpTypeStruct %3 %8 +%12 = OpTypeStruct %5 +%13 = OpTypePointer StorageBuffer %12 +%11 = OpVariable %13 StorageBuffer +%15 = OpTypeStruct %7 +%16 = OpTypePointer StorageBuffer %15 +%14 = OpVariable %16 StorageBuffer +%18 = OpTypePointer Function %3 +%19 = OpConstantNull %3 +%21 = OpTypePointer Function %4 +%22 = OpConstantNull %4 +%24 = OpTypePointer Function %8 +%25 = OpConstantNull %8 +%28 = OpTypeFunction %2 +%29 = OpTypePointer StorageBuffer %5 +%30 = OpConstant %3 0 +%32 = OpConstantFalse %8 +%33 = OpTypeFloat 32 +%34 = OpConstant %33 1.0 %35 = OpConstant %3 1 %48 = OpTypePointer StorageBuffer %4 %51 = OpConstant %4 1 %52 = OpConstant %3 64 %82 = OpTypePointer StorageBuffer %7 %96 = OpTypePointer StorageBuffer %3 -%28 = OpFunction %2 None %29 -%27 = OpLabel -%18 = OpVariable %19 Function %20 -%21 = OpVariable %22 Function %23 -%24 = OpVariable %25 Function %26 -%32 = OpAccessChain %30 %12 %31 +%27 = OpFunction %2 None %28 +%26 = OpLabel +%17 = OpVariable %18 Function %19 +%20 = OpVariable %21 Function %22 +%23 = OpVariable %24 Function %25 +%31 = OpAccessChain %29 %11 %30 OpBranch %36 %36 = OpLabel -OpStore %18 %31 +OpStore %17 %30 OpBranch %37 %37 = OpLabel OpLoopMerge %38 %40 None OpBranch %39 %39 = OpLabel -%41 = OpLoad %3 %18 +%41 = OpLoad %3 %17 %42 = OpULessThan %8 %41 %6 OpSelectionMerge %43 None OpBranchConditional %42 %43 %44 @@ -80,17 +80,17 @@ OpBranch %38 %43 = OpLabel OpBranch %45 %45 = OpLabel -%47 = OpLoad %3 %18 -%49 = OpAccessChain %48 %32 %47 +%47 = OpLoad %3 %17 +%49 = OpAccessChain %48 %31 %47 %50 = OpAtomicLoad %4 %49 %51 %52 -OpStore %21 %50 -OpStore %24 %33 +OpStore %20 %50 +OpStore %23 %32 OpBranch %53 %53 = OpLabel OpLoopMerge %54 %56 None OpBranch %55 %55 = OpLabel -%57 = OpLoad %8 %24 +%57 = OpLoad %8 %23 %58 = OpLogicalNot %8 %57 OpSelectionMerge %59 None OpBranchConditional %58 %59 %60 @@ -99,20 +99,20 @@ OpBranch %54 %59 = OpLabel OpBranch %61 %61 = OpLabel -%63 = OpLoad %4 %21 -%64 = OpBitcast %9 %63 -%65 = OpFAdd %9 %64 %34 +%63 = OpLoad %4 %20 +%64 = OpBitcast %33 %63 +%65 = OpFAdd %33 %64 %34 %66 = OpBitcast %4 %65 -%67 = OpLoad %3 %18 -%68 = OpLoad %4 %21 -%70 = OpAccessChain %48 %32 %67 +%67 = OpLoad %3 %17 +%68 = OpLoad %4 %20 +%70 = OpAccessChain %48 %31 %67 %71 = OpAtomicCompareExchange %4 %70 %51 %52 %52 %66 %68 %72 = OpIEqual %8 %71 %68 -%69 = OpCompositeConstruct %10 %71 %72 +%69 = OpCompositeConstruct %9 %71 %72 %73 = OpCompositeExtract %4 %69 0 -OpStore %21 %73 +OpStore %20 %73 %74 = OpCompositeExtract %8 %69 1 -OpStore %24 %74 +OpStore %23 %74 OpBranch %62 %62 = OpLabel OpBranch %56 @@ -123,22 +123,22 @@ OpBranch %46 %46 = OpLabel OpBranch %40 %40 = OpLabel -%75 = OpLoad %3 %18 +%75 = OpLoad %3 %17 %76 = OpIAdd %3 %75 %35 -OpStore %18 %76 +OpStore %17 %76 OpBranch %37 %38 = OpLabel OpReturn OpFunctionEnd -%81 = OpFunction %2 None %29 +%81 = OpFunction %2 None %28 %80 = OpLabel -%77 = OpVariable %19 Function %20 -%78 = OpVariable %19 Function %20 -%79 = OpVariable %25 Function %26 -%83 = OpAccessChain %82 %15 %31 +%77 = OpVariable %18 Function %19 +%78 = OpVariable %18 Function %19 +%79 = OpVariable %24 Function %25 +%83 = OpAccessChain %82 %14 %30 OpBranch %84 %84 = OpLabel -OpStore %77 %31 +OpStore %77 %30 OpBranch %85 %85 = OpLabel OpLoopMerge %86 %88 None @@ -157,7 +157,7 @@ OpBranch %93 %97 = OpAccessChain %96 %83 %95 %98 = OpAtomicLoad %3 %97 %51 %52 OpStore %78 %98 -OpStore %79 %33 +OpStore %79 %32 OpBranch %99 %99 = OpLabel OpLoopMerge %100 %102 None @@ -173,15 +173,15 @@ OpBranch %100 OpBranch %107 %107 = OpLabel %109 = OpLoad %3 %78 -%110 = OpBitcast %9 %109 -%111 = OpFAdd %9 %110 %34 +%110 = OpBitcast %33 %109 +%111 = OpFAdd %33 %110 %34 %112 = OpBitcast %3 %111 %113 = OpLoad %3 %77 %114 = OpLoad %3 %78 %116 = OpAccessChain %96 %83 %113 %117 = OpAtomicCompareExchange %3 %116 %51 %52 %52 %112 %114 %118 = OpIEqual %8 %117 %114 -%115 = OpCompositeConstruct %11 %117 %118 +%115 = OpCompositeConstruct %10 %117 %118 %119 = OpCompositeExtract %3 %115 0 OpStore %78 %119 %120 = OpCompositeExtract %8 %115 1 diff --git a/tests/out/spv/atomicOps.spvasm b/tests/out/spv/atomicOps.spvasm index 65d078ad9..de4d68782 100644 --- a/tests/out/spv/atomicOps.spvasm +++ b/tests/out/spv/atomicOps.spvasm @@ -6,24 +6,24 @@ OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %29 "cs_main" %26 -OpExecutionMode %29 LocalSize 2 1 1 +OpEntryPoint GLCompute %28 "cs_main" %25 +OpExecutionMode %28 LocalSize 2 1 1 OpDecorate %5 ArrayStride 4 OpMemberDecorate %7 0 Offset 0 OpMemberDecorate %7 1 Offset 4 -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 0 -OpDecorate %11 Block -OpMemberDecorate %11 0 Offset 0 -OpDecorate %13 DescriptorSet 0 -OpDecorate %13 Binding 1 -OpDecorate %14 Block -OpMemberDecorate %14 0 Offset 0 -OpDecorate %16 DescriptorSet 0 -OpDecorate %16 Binding 2 -OpDecorate %17 Block -OpMemberDecorate %17 0 Offset 0 -OpDecorate %26 BuiltIn LocalInvocationId +OpDecorate %9 DescriptorSet 0 +OpDecorate %9 Binding 0 +OpDecorate %10 Block +OpMemberDecorate %10 0 Offset 0 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 1 +OpDecorate %13 Block +OpMemberDecorate %13 0 Offset 0 +OpDecorate %15 DescriptorSet 0 +OpDecorate %15 Binding 2 +OpDecorate %16 Block +OpMemberDecorate %16 0 Offset 0 +OpDecorate %25 BuiltIn LocalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeInt 32 1 @@ -31,210 +31,210 @@ OpDecorate %26 BuiltIn LocalInvocationId %5 = OpTypeArray %4 %6 %7 = OpTypeStruct %3 %5 %8 = OpTypeVector %3 3 -%9 = OpConstant %4 2 -%11 = OpTypeStruct %3 -%12 = OpTypePointer StorageBuffer %11 -%10 = OpVariable %12 StorageBuffer -%14 = OpTypeStruct %5 -%15 = OpTypePointer StorageBuffer %14 -%13 = OpVariable %15 StorageBuffer -%17 = OpTypeStruct %7 -%18 = OpTypePointer StorageBuffer %17 -%16 = OpVariable %18 StorageBuffer -%20 = OpTypePointer Workgroup %3 -%19 = OpVariable %20 Workgroup -%22 = OpTypePointer Workgroup %5 -%21 = OpVariable %22 Workgroup -%24 = OpTypePointer Workgroup %7 -%23 = OpVariable %24 Workgroup -%27 = OpTypePointer Input %8 -%26 = OpVariable %27 Input -%30 = OpTypeFunction %2 -%31 = OpTypePointer StorageBuffer %3 -%32 = OpConstant %3 0 -%34 = OpTypePointer StorageBuffer %5 -%36 = OpTypePointer StorageBuffer %7 -%38 = OpConstant %3 1 -%39 = OpConstant %4 1 -%41 = OpConstantNull %3 -%42 = OpConstantNull %5 -%43 = OpConstantNull %7 -%44 = OpConstantNull %8 -%46 = OpTypeBool -%45 = OpTypeVector %46 3 -%51 = OpConstant %3 264 -%53 = OpConstant %3 64 -%54 = OpTypePointer StorageBuffer %4 +%10 = OpTypeStruct %3 +%11 = OpTypePointer StorageBuffer %10 +%9 = OpVariable %11 StorageBuffer +%13 = OpTypeStruct %5 +%14 = OpTypePointer StorageBuffer %13 +%12 = OpVariable %14 StorageBuffer +%16 = OpTypeStruct %7 +%17 = OpTypePointer StorageBuffer %16 +%15 = OpVariable %17 StorageBuffer +%19 = OpTypePointer Workgroup %3 +%18 = OpVariable %19 Workgroup +%21 = OpTypePointer Workgroup %5 +%20 = OpVariable %21 Workgroup +%23 = OpTypePointer Workgroup %7 +%22 = OpVariable %23 Workgroup +%26 = OpTypePointer Input %8 +%25 = OpVariable %26 Input +%29 = OpTypeFunction %2 +%30 = OpTypePointer StorageBuffer %3 +%31 = OpConstant %3 0 +%33 = OpTypePointer StorageBuffer %5 +%35 = OpTypePointer StorageBuffer %7 +%37 = OpConstant %3 1 +%38 = OpConstant %4 1 +%40 = OpConstantNull %3 +%41 = OpConstantNull %5 +%42 = OpConstantNull %7 +%43 = OpConstantNull %8 +%45 = OpTypeBool +%44 = OpTypeVector %45 3 +%50 = OpConstant %3 264 +%52 = OpConstant %3 64 +%53 = OpTypePointer StorageBuffer %4 +%57 = OpConstant %4 2 %58 = OpConstant %3 256 %59 = OpTypePointer Workgroup %4 -%29 = OpFunction %2 None %30 -%25 = OpLabel -%28 = OpLoad %8 %26 -%33 = OpAccessChain %31 %10 %32 -%35 = OpAccessChain %34 %13 %32 -%37 = OpAccessChain %36 %16 %32 -OpBranch %40 -%40 = OpLabel -%47 = OpIEqual %45 %28 %44 -%48 = OpAll %46 %47 -OpSelectionMerge %49 None -OpBranchConditional %48 %50 %49 -%50 = OpLabel -OpStore %19 %41 -OpStore %21 %42 -OpStore %23 %43 -OpBranch %49 +%28 = OpFunction %2 None %29 +%24 = OpLabel +%27 = OpLoad %8 %25 +%32 = OpAccessChain %30 %9 %31 +%34 = OpAccessChain %33 %12 %31 +%36 = OpAccessChain %35 %15 %31 +OpBranch %39 +%39 = OpLabel +%46 = OpIEqual %44 %27 %43 +%47 = OpAll %45 %46 +OpSelectionMerge %48 None +OpBranchConditional %47 %49 %48 %49 = OpLabel -OpControlBarrier %6 %6 %51 -OpBranch %52 -%52 = OpLabel -OpAtomicStore %33 %39 %53 %38 -%55 = OpAccessChain %54 %35 %38 -OpAtomicStore %55 %39 %53 %39 -%56 = OpAccessChain %31 %37 %32 -OpAtomicStore %56 %39 %53 %38 -%57 = OpAccessChain %54 %37 %38 %38 -OpAtomicStore %57 %39 %53 %39 -OpAtomicStore %19 %9 %58 %38 -%60 = OpAccessChain %59 %21 %38 -OpAtomicStore %60 %9 %58 %39 -%61 = OpAccessChain %20 %23 %32 -OpAtomicStore %61 %9 %58 %38 -%62 = OpAccessChain %59 %23 %38 %38 -OpAtomicStore %62 %9 %58 %39 -OpControlBarrier %6 %6 %51 -%63 = OpAtomicLoad %3 %33 %39 %53 -%64 = OpAccessChain %54 %35 %38 -%65 = OpAtomicLoad %4 %64 %39 %53 -%66 = OpAccessChain %31 %37 %32 -%67 = OpAtomicLoad %3 %66 %39 %53 -%68 = OpAccessChain %54 %37 %38 %38 -%69 = OpAtomicLoad %4 %68 %39 %53 -%70 = OpAtomicLoad %3 %19 %9 %58 -%71 = OpAccessChain %59 %21 %38 -%72 = OpAtomicLoad %4 %71 %9 %58 -%73 = OpAccessChain %20 %23 %32 -%74 = OpAtomicLoad %3 %73 %9 %58 -%75 = OpAccessChain %59 %23 %38 %38 -%76 = OpAtomicLoad %4 %75 %9 %58 -OpControlBarrier %6 %6 %51 -%77 = OpAtomicIAdd %3 %33 %39 %53 %38 -%79 = OpAccessChain %54 %35 %38 -%78 = OpAtomicIAdd %4 %79 %39 %53 %39 -%81 = OpAccessChain %31 %37 %32 -%80 = OpAtomicIAdd %3 %81 %39 %53 %38 -%83 = OpAccessChain %54 %37 %38 %38 -%82 = OpAtomicIAdd %4 %83 %39 %53 %39 -%84 = OpAtomicIAdd %3 %19 %9 %58 %38 -%86 = OpAccessChain %59 %21 %38 -%85 = OpAtomicIAdd %4 %86 %9 %58 %39 -%88 = OpAccessChain %20 %23 %32 -%87 = OpAtomicIAdd %3 %88 %9 %58 %38 -%90 = OpAccessChain %59 %23 %38 %38 -%89 = OpAtomicIAdd %4 %90 %9 %58 %39 -OpControlBarrier %6 %6 %51 -%91 = OpAtomicISub %3 %33 %39 %53 %38 -%93 = OpAccessChain %54 %35 %38 -%92 = OpAtomicISub %4 %93 %39 %53 %39 -%95 = OpAccessChain %31 %37 %32 -%94 = OpAtomicISub %3 %95 %39 %53 %38 -%97 = OpAccessChain %54 %37 %38 %38 -%96 = OpAtomicISub %4 %97 %39 %53 %39 -%98 = OpAtomicISub %3 %19 %9 %58 %38 -%100 = OpAccessChain %59 %21 %38 -%99 = OpAtomicISub %4 %100 %9 %58 %39 -%102 = OpAccessChain %20 %23 %32 -%101 = OpAtomicISub %3 %102 %9 %58 %38 -%104 = OpAccessChain %59 %23 %38 %38 -%103 = OpAtomicISub %4 %104 %9 %58 %39 -OpControlBarrier %6 %6 %51 -%105 = OpAtomicUMax %3 %33 %39 %53 %38 -%107 = OpAccessChain %54 %35 %38 -%106 = OpAtomicSMax %4 %107 %39 %53 %39 -%109 = OpAccessChain %31 %37 %32 -%108 = OpAtomicUMax %3 %109 %39 %53 %38 -%111 = OpAccessChain %54 %37 %38 %38 -%110 = OpAtomicSMax %4 %111 %39 %53 %39 -%112 = OpAtomicUMax %3 %19 %9 %58 %38 -%114 = OpAccessChain %59 %21 %38 -%113 = OpAtomicSMax %4 %114 %9 %58 %39 -%116 = OpAccessChain %20 %23 %32 -%115 = OpAtomicUMax %3 %116 %9 %58 %38 -%118 = OpAccessChain %59 %23 %38 %38 -%117 = OpAtomicSMax %4 %118 %9 %58 %39 -OpControlBarrier %6 %6 %51 -%119 = OpAtomicUMin %3 %33 %39 %53 %38 -%121 = OpAccessChain %54 %35 %38 -%120 = OpAtomicSMin %4 %121 %39 %53 %39 -%123 = OpAccessChain %31 %37 %32 -%122 = OpAtomicUMin %3 %123 %39 %53 %38 -%125 = OpAccessChain %54 %37 %38 %38 -%124 = OpAtomicSMin %4 %125 %39 %53 %39 -%126 = OpAtomicUMin %3 %19 %9 %58 %38 -%128 = OpAccessChain %59 %21 %38 -%127 = OpAtomicSMin %4 %128 %9 %58 %39 -%130 = OpAccessChain %20 %23 %32 -%129 = OpAtomicUMin %3 %130 %9 %58 %38 -%132 = OpAccessChain %59 %23 %38 %38 -%131 = OpAtomicSMin %4 %132 %9 %58 %39 -OpControlBarrier %6 %6 %51 -%133 = OpAtomicAnd %3 %33 %39 %53 %38 -%135 = OpAccessChain %54 %35 %38 -%134 = OpAtomicAnd %4 %135 %39 %53 %39 -%137 = OpAccessChain %31 %37 %32 -%136 = OpAtomicAnd %3 %137 %39 %53 %38 -%139 = OpAccessChain %54 %37 %38 %38 -%138 = OpAtomicAnd %4 %139 %39 %53 %39 -%140 = OpAtomicAnd %3 %19 %9 %58 %38 -%142 = OpAccessChain %59 %21 %38 -%141 = OpAtomicAnd %4 %142 %9 %58 %39 -%144 = OpAccessChain %20 %23 %32 -%143 = OpAtomicAnd %3 %144 %9 %58 %38 -%146 = OpAccessChain %59 %23 %38 %38 -%145 = OpAtomicAnd %4 %146 %9 %58 %39 -OpControlBarrier %6 %6 %51 -%147 = OpAtomicOr %3 %33 %39 %53 %38 -%149 = OpAccessChain %54 %35 %38 -%148 = OpAtomicOr %4 %149 %39 %53 %39 -%151 = OpAccessChain %31 %37 %32 -%150 = OpAtomicOr %3 %151 %39 %53 %38 -%153 = OpAccessChain %54 %37 %38 %38 -%152 = OpAtomicOr %4 %153 %39 %53 %39 -%154 = OpAtomicOr %3 %19 %9 %58 %38 -%156 = OpAccessChain %59 %21 %38 -%155 = OpAtomicOr %4 %156 %9 %58 %39 -%158 = OpAccessChain %20 %23 %32 -%157 = OpAtomicOr %3 %158 %9 %58 %38 -%160 = OpAccessChain %59 %23 %38 %38 -%159 = OpAtomicOr %4 %160 %9 %58 %39 -OpControlBarrier %6 %6 %51 -%161 = OpAtomicXor %3 %33 %39 %53 %38 -%163 = OpAccessChain %54 %35 %38 -%162 = OpAtomicXor %4 %163 %39 %53 %39 -%165 = OpAccessChain %31 %37 %32 -%164 = OpAtomicXor %3 %165 %39 %53 %38 -%167 = OpAccessChain %54 %37 %38 %38 -%166 = OpAtomicXor %4 %167 %39 %53 %39 -%168 = OpAtomicXor %3 %19 %9 %58 %38 -%170 = OpAccessChain %59 %21 %38 -%169 = OpAtomicXor %4 %170 %9 %58 %39 -%172 = OpAccessChain %20 %23 %32 -%171 = OpAtomicXor %3 %172 %9 %58 %38 -%174 = OpAccessChain %59 %23 %38 %38 -%173 = OpAtomicXor %4 %174 %9 %58 %39 -%175 = OpAtomicExchange %3 %33 %39 %53 %38 -%177 = OpAccessChain %54 %35 %38 -%176 = OpAtomicExchange %4 %177 %39 %53 %39 -%179 = OpAccessChain %31 %37 %32 -%178 = OpAtomicExchange %3 %179 %39 %53 %38 -%181 = OpAccessChain %54 %37 %38 %38 -%180 = OpAtomicExchange %4 %181 %39 %53 %39 -%182 = OpAtomicExchange %3 %19 %9 %58 %38 -%184 = OpAccessChain %59 %21 %38 -%183 = OpAtomicExchange %4 %184 %9 %58 %39 -%186 = OpAccessChain %20 %23 %32 -%185 = OpAtomicExchange %3 %186 %9 %58 %38 -%188 = OpAccessChain %59 %23 %38 %38 -%187 = OpAtomicExchange %4 %188 %9 %58 %39 +OpStore %18 %40 +OpStore %20 %41 +OpStore %22 %42 +OpBranch %48 +%48 = OpLabel +OpControlBarrier %6 %6 %50 +OpBranch %51 +%51 = OpLabel +OpAtomicStore %32 %38 %52 %37 +%54 = OpAccessChain %53 %34 %37 +OpAtomicStore %54 %38 %52 %38 +%55 = OpAccessChain %30 %36 %31 +OpAtomicStore %55 %38 %52 %37 +%56 = OpAccessChain %53 %36 %37 %37 +OpAtomicStore %56 %38 %52 %38 +OpAtomicStore %18 %57 %58 %37 +%60 = OpAccessChain %59 %20 %37 +OpAtomicStore %60 %57 %58 %38 +%61 = OpAccessChain %19 %22 %31 +OpAtomicStore %61 %57 %58 %37 +%62 = OpAccessChain %59 %22 %37 %37 +OpAtomicStore %62 %57 %58 %38 +OpControlBarrier %6 %6 %50 +%63 = OpAtomicLoad %3 %32 %38 %52 +%64 = OpAccessChain %53 %34 %37 +%65 = OpAtomicLoad %4 %64 %38 %52 +%66 = OpAccessChain %30 %36 %31 +%67 = OpAtomicLoad %3 %66 %38 %52 +%68 = OpAccessChain %53 %36 %37 %37 +%69 = OpAtomicLoad %4 %68 %38 %52 +%70 = OpAtomicLoad %3 %18 %57 %58 +%71 = OpAccessChain %59 %20 %37 +%72 = OpAtomicLoad %4 %71 %57 %58 +%73 = OpAccessChain %19 %22 %31 +%74 = OpAtomicLoad %3 %73 %57 %58 +%75 = OpAccessChain %59 %22 %37 %37 +%76 = OpAtomicLoad %4 %75 %57 %58 +OpControlBarrier %6 %6 %50 +%77 = OpAtomicIAdd %3 %32 %38 %52 %37 +%79 = OpAccessChain %53 %34 %37 +%78 = OpAtomicIAdd %4 %79 %38 %52 %38 +%81 = OpAccessChain %30 %36 %31 +%80 = OpAtomicIAdd %3 %81 %38 %52 %37 +%83 = OpAccessChain %53 %36 %37 %37 +%82 = OpAtomicIAdd %4 %83 %38 %52 %38 +%84 = OpAtomicIAdd %3 %18 %57 %58 %37 +%86 = OpAccessChain %59 %20 %37 +%85 = OpAtomicIAdd %4 %86 %57 %58 %38 +%88 = OpAccessChain %19 %22 %31 +%87 = OpAtomicIAdd %3 %88 %57 %58 %37 +%90 = OpAccessChain %59 %22 %37 %37 +%89 = OpAtomicIAdd %4 %90 %57 %58 %38 +OpControlBarrier %6 %6 %50 +%91 = OpAtomicISub %3 %32 %38 %52 %37 +%93 = OpAccessChain %53 %34 %37 +%92 = OpAtomicISub %4 %93 %38 %52 %38 +%95 = OpAccessChain %30 %36 %31 +%94 = OpAtomicISub %3 %95 %38 %52 %37 +%97 = OpAccessChain %53 %36 %37 %37 +%96 = OpAtomicISub %4 %97 %38 %52 %38 +%98 = OpAtomicISub %3 %18 %57 %58 %37 +%100 = OpAccessChain %59 %20 %37 +%99 = OpAtomicISub %4 %100 %57 %58 %38 +%102 = OpAccessChain %19 %22 %31 +%101 = OpAtomicISub %3 %102 %57 %58 %37 +%104 = OpAccessChain %59 %22 %37 %37 +%103 = OpAtomicISub %4 %104 %57 %58 %38 +OpControlBarrier %6 %6 %50 +%105 = OpAtomicUMax %3 %32 %38 %52 %37 +%107 = OpAccessChain %53 %34 %37 +%106 = OpAtomicSMax %4 %107 %38 %52 %38 +%109 = OpAccessChain %30 %36 %31 +%108 = OpAtomicUMax %3 %109 %38 %52 %37 +%111 = OpAccessChain %53 %36 %37 %37 +%110 = OpAtomicSMax %4 %111 %38 %52 %38 +%112 = OpAtomicUMax %3 %18 %57 %58 %37 +%114 = OpAccessChain %59 %20 %37 +%113 = OpAtomicSMax %4 %114 %57 %58 %38 +%116 = OpAccessChain %19 %22 %31 +%115 = OpAtomicUMax %3 %116 %57 %58 %37 +%118 = OpAccessChain %59 %22 %37 %37 +%117 = OpAtomicSMax %4 %118 %57 %58 %38 +OpControlBarrier %6 %6 %50 +%119 = OpAtomicUMin %3 %32 %38 %52 %37 +%121 = OpAccessChain %53 %34 %37 +%120 = OpAtomicSMin %4 %121 %38 %52 %38 +%123 = OpAccessChain %30 %36 %31 +%122 = OpAtomicUMin %3 %123 %38 %52 %37 +%125 = OpAccessChain %53 %36 %37 %37 +%124 = OpAtomicSMin %4 %125 %38 %52 %38 +%126 = OpAtomicUMin %3 %18 %57 %58 %37 +%128 = OpAccessChain %59 %20 %37 +%127 = OpAtomicSMin %4 %128 %57 %58 %38 +%130 = OpAccessChain %19 %22 %31 +%129 = OpAtomicUMin %3 %130 %57 %58 %37 +%132 = OpAccessChain %59 %22 %37 %37 +%131 = OpAtomicSMin %4 %132 %57 %58 %38 +OpControlBarrier %6 %6 %50 +%133 = OpAtomicAnd %3 %32 %38 %52 %37 +%135 = OpAccessChain %53 %34 %37 +%134 = OpAtomicAnd %4 %135 %38 %52 %38 +%137 = OpAccessChain %30 %36 %31 +%136 = OpAtomicAnd %3 %137 %38 %52 %37 +%139 = OpAccessChain %53 %36 %37 %37 +%138 = OpAtomicAnd %4 %139 %38 %52 %38 +%140 = OpAtomicAnd %3 %18 %57 %58 %37 +%142 = OpAccessChain %59 %20 %37 +%141 = OpAtomicAnd %4 %142 %57 %58 %38 +%144 = OpAccessChain %19 %22 %31 +%143 = OpAtomicAnd %3 %144 %57 %58 %37 +%146 = OpAccessChain %59 %22 %37 %37 +%145 = OpAtomicAnd %4 %146 %57 %58 %38 +OpControlBarrier %6 %6 %50 +%147 = OpAtomicOr %3 %32 %38 %52 %37 +%149 = OpAccessChain %53 %34 %37 +%148 = OpAtomicOr %4 %149 %38 %52 %38 +%151 = OpAccessChain %30 %36 %31 +%150 = OpAtomicOr %3 %151 %38 %52 %37 +%153 = OpAccessChain %53 %36 %37 %37 +%152 = OpAtomicOr %4 %153 %38 %52 %38 +%154 = OpAtomicOr %3 %18 %57 %58 %37 +%156 = OpAccessChain %59 %20 %37 +%155 = OpAtomicOr %4 %156 %57 %58 %38 +%158 = OpAccessChain %19 %22 %31 +%157 = OpAtomicOr %3 %158 %57 %58 %37 +%160 = OpAccessChain %59 %22 %37 %37 +%159 = OpAtomicOr %4 %160 %57 %58 %38 +OpControlBarrier %6 %6 %50 +%161 = OpAtomicXor %3 %32 %38 %52 %37 +%163 = OpAccessChain %53 %34 %37 +%162 = OpAtomicXor %4 %163 %38 %52 %38 +%165 = OpAccessChain %30 %36 %31 +%164 = OpAtomicXor %3 %165 %38 %52 %37 +%167 = OpAccessChain %53 %36 %37 %37 +%166 = OpAtomicXor %4 %167 %38 %52 %38 +%168 = OpAtomicXor %3 %18 %57 %58 %37 +%170 = OpAccessChain %59 %20 %37 +%169 = OpAtomicXor %4 %170 %57 %58 %38 +%172 = OpAccessChain %19 %22 %31 +%171 = OpAtomicXor %3 %172 %57 %58 %37 +%174 = OpAccessChain %59 %22 %37 %37 +%173 = OpAtomicXor %4 %174 %57 %58 %38 +%175 = OpAtomicExchange %3 %32 %38 %52 %37 +%177 = OpAccessChain %53 %34 %37 +%176 = OpAtomicExchange %4 %177 %38 %52 %38 +%179 = OpAccessChain %30 %36 %31 +%178 = OpAtomicExchange %3 %179 %38 %52 %37 +%181 = OpAccessChain %53 %36 %37 %37 +%180 = OpAtomicExchange %4 %181 %38 %52 %38 +%182 = OpAtomicExchange %3 %18 %57 %58 %37 +%184 = OpAccessChain %59 %20 %37 +%183 = OpAtomicExchange %4 %184 %57 %58 %38 +%186 = OpAccessChain %19 %22 %31 +%185 = OpAtomicExchange %3 %186 %57 %58 %37 +%188 = OpAccessChain %59 %22 %37 %37 +%187 = OpAtomicExchange %4 %188 %57 %58 %38 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 090173100..57636775f 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -1,62 +1,62 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 432 +; Bound: 431 OpCapability Shader OpCapability ImageQuery OpCapability ShaderNonUniform OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %68 "main" %63 %66 -OpExecutionMode %68 OriginUpperLeft +OpEntryPoint Fragment %64 "main" %59 %62 +OpExecutionMode %64 OriginUpperLeft OpMemberDecorate %4 0 Offset 0 OpMemberDecorate %21 0 Offset 0 +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 0 OpDecorate %28 DescriptorSet 0 -OpDecorate %28 Binding 0 +OpDecorate %28 Binding 1 +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 2 OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 1 +OpDecorate %32 Binding 3 OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 2 +OpDecorate %34 Binding 4 OpDecorate %36 DescriptorSet 0 -OpDecorate %36 Binding 3 +OpDecorate %36 Binding 5 OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 4 +OpDecorate %38 Binding 6 OpDecorate %40 DescriptorSet 0 -OpDecorate %40 Binding 5 +OpDecorate %40 Binding 7 OpDecorate %42 DescriptorSet 0 -OpDecorate %42 Binding 6 -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 7 -OpDecorate %46 DescriptorSet 0 -OpDecorate %46 Binding 8 -OpDecorate %47 Block -OpMemberDecorate %47 0 Offset 0 -OpDecorate %63 Location 0 -OpDecorate %63 Flat -OpDecorate %66 Location 0 -OpDecorate %96 NonUniform -OpDecorate %119 NonUniform -OpDecorate %121 NonUniform -OpDecorate %146 NonUniform -OpDecorate %148 NonUniform -OpDecorate %184 NonUniform -OpDecorate %212 NonUniform -OpDecorate %228 NonUniform -OpDecorate %244 NonUniform -OpDecorate %265 NonUniform -OpDecorate %267 NonUniform -OpDecorate %289 NonUniform -OpDecorate %291 NonUniform -OpDecorate %313 NonUniform -OpDecorate %315 NonUniform -OpDecorate %337 NonUniform -OpDecorate %339 NonUniform -OpDecorate %361 NonUniform -OpDecorate %363 NonUniform -OpDecorate %385 NonUniform -OpDecorate %387 NonUniform -OpDecorate %410 NonUniform +OpDecorate %42 Binding 8 +OpDecorate %43 Block +OpMemberDecorate %43 0 Offset 0 +OpDecorate %59 Location 0 +OpDecorate %59 Flat +OpDecorate %62 Location 0 +OpDecorate %95 NonUniform +OpDecorate %118 NonUniform +OpDecorate %120 NonUniform +OpDecorate %145 NonUniform +OpDecorate %147 NonUniform +OpDecorate %183 NonUniform +OpDecorate %211 NonUniform +OpDecorate %227 NonUniform +OpDecorate %243 NonUniform +OpDecorate %264 NonUniform +OpDecorate %266 NonUniform +OpDecorate %288 NonUniform +OpDecorate %290 NonUniform +OpDecorate %312 NonUniform +OpDecorate %314 NonUniform +OpDecorate %336 NonUniform +OpDecorate %338 NonUniform +OpDecorate %360 NonUniform +OpDecorate %362 NonUniform +OpDecorate %384 NonUniform +OpDecorate %386 NonUniform +OpDecorate %409 NonUniform %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeStruct %3 @@ -79,482 +79,481 @@ OpDecorate %410 NonUniform %21 = OpTypeStruct %3 %22 = OpTypeVector %6 4 %23 = OpTypeVector %3 2 -%24 = OpTypeVector %6 2 -%26 = OpTypeInt 32 1 -%25 = OpTypeVector %26 2 -%27 = OpConstant %26 5 -%31 = OpConstant %3 10 -%30 = OpTypeArray %5 %31 -%29 = OpTypePointer UniformConstant %30 +%27 = OpConstant %3 10 +%26 = OpTypeArray %5 %27 +%25 = OpTypePointer UniformConstant %26 +%24 = OpVariable %25 UniformConstant +%29 = OpTypePointer UniformConstant %8 %28 = OpVariable %29 UniformConstant -%33 = OpTypePointer UniformConstant %8 +%31 = OpTypePointer UniformConstant %11 +%30 = OpVariable %31 UniformConstant +%33 = OpTypePointer UniformConstant %13 %32 = OpVariable %33 UniformConstant -%35 = OpTypePointer UniformConstant %11 +%35 = OpTypePointer UniformConstant %15 %34 = OpVariable %35 UniformConstant -%37 = OpTypePointer UniformConstant %13 +%37 = OpTypePointer UniformConstant %17 %36 = OpVariable %37 UniformConstant -%39 = OpTypePointer UniformConstant %15 +%39 = OpTypePointer UniformConstant %19 %38 = OpVariable %39 UniformConstant -%41 = OpTypePointer UniformConstant %17 +%41 = OpTypePointer UniformConstant %20 %40 = OpVariable %41 UniformConstant -%43 = OpTypePointer UniformConstant %19 -%42 = OpVariable %43 UniformConstant -%45 = OpTypePointer UniformConstant %20 -%44 = OpVariable %45 UniformConstant -%47 = OpTypeStruct %4 -%48 = OpTypePointer Uniform %47 -%46 = OpVariable %48 Uniform -%50 = OpTypePointer Function %3 -%51 = OpConstantNull %3 -%53 = OpTypePointer Function %23 -%54 = OpConstantNull %23 -%56 = OpTypePointer Function %6 -%57 = OpConstantNull %6 -%59 = OpTypePointer Function %22 -%60 = OpConstantNull %22 -%64 = OpTypePointer Input %3 -%63 = OpVariable %64 Input -%67 = OpTypePointer Output %22 -%66 = OpVariable %67 Output -%69 = OpTypeFunction %2 -%70 = OpTypePointer Uniform %4 -%71 = OpConstant %3 0 -%73 = OpConstant %6 0.0 -%74 = OpConstant %26 0 -%76 = OpTypePointer Uniform %3 -%84 = OpTypePointer UniformConstant %5 -%102 = OpTypePointer UniformConstant %18 -%105 = OpTypeSampledImage %5 -%126 = OpTypePointer UniformConstant %14 -%129 = OpTypePointer UniformConstant %18 -%132 = OpTypeSampledImage %14 -%155 = OpTypeBool -%161 = OpTypeVector %155 2 -%197 = OpTypePointer UniformConstant %10 -%200 = OpTypeVector %3 3 -%232 = OpTypePointer UniformConstant %12 -%392 = OpTypePointer UniformConstant %16 -%68 = OpFunction %2 None %69 -%61 = OpLabel -%52 = OpVariable %53 Function %54 -%58 = OpVariable %59 Function %60 -%49 = OpVariable %50 Function %51 -%55 = OpVariable %56 Function %57 -%65 = OpLoad %3 %63 -%62 = OpCompositeConstruct %21 %65 -%72 = OpAccessChain %70 %46 %71 -OpBranch %75 -%75 = OpLabel -%77 = OpAccessChain %76 %72 %71 -%78 = OpLoad %3 %77 -%79 = OpCompositeExtract %3 %62 0 -OpStore %49 %71 -%80 = OpCompositeConstruct %23 %71 %71 -OpStore %52 %80 -OpStore %55 %73 -%81 = OpCompositeConstruct %22 %73 %73 %73 %73 -OpStore %58 %81 -%82 = OpCompositeConstruct %24 %73 %73 -%83 = OpCompositeConstruct %25 %74 %74 -%85 = OpAccessChain %84 %28 %71 -%86 = OpLoad %5 %85 -%87 = OpImageQuerySizeLod %23 %86 %71 -%88 = OpLoad %23 %52 -%89 = OpIAdd %23 %88 %87 -OpStore %52 %89 -%90 = OpAccessChain %84 %28 %78 -%91 = OpLoad %5 %90 -%92 = OpImageQuerySizeLod %23 %91 %71 -%93 = OpLoad %23 %52 -%94 = OpIAdd %23 %93 %92 -OpStore %52 %94 -%95 = OpAccessChain %84 %28 %79 -%96 = OpLoad %5 %95 -%97 = OpImageQuerySizeLod %23 %96 %71 -%98 = OpLoad %23 %52 -%99 = OpIAdd %23 %98 %97 -OpStore %52 %99 -%100 = OpAccessChain %84 %32 %71 -%101 = OpLoad %5 %100 -%103 = OpAccessChain %102 %42 %71 -%104 = OpLoad %18 %103 -%106 = OpSampledImage %105 %101 %104 -%107 = OpImageGather %22 %106 %82 %71 -%108 = OpLoad %22 %58 -%109 = OpFAdd %22 %108 %107 -OpStore %58 %109 -%110 = OpAccessChain %84 %32 %78 -%111 = OpLoad %5 %110 -%112 = OpAccessChain %102 %42 %78 -%113 = OpLoad %18 %112 -%114 = OpSampledImage %105 %111 %113 -%115 = OpImageGather %22 %114 %82 %71 -%116 = OpLoad %22 %58 -%117 = OpFAdd %22 %116 %115 -OpStore %58 %117 -%118 = OpAccessChain %84 %32 %79 -%119 = OpLoad %5 %118 -%120 = OpAccessChain %102 %42 %79 -%121 = OpLoad %18 %120 -%122 = OpSampledImage %105 %119 %121 -%123 = OpImageGather %22 %122 %82 %71 -%124 = OpLoad %22 %58 -%125 = OpFAdd %22 %124 %123 -OpStore %58 %125 -%127 = OpAccessChain %126 %38 %71 -%128 = OpLoad %14 %127 -%130 = OpAccessChain %129 %44 %71 -%131 = OpLoad %18 %130 -%133 = OpSampledImage %132 %128 %131 -%134 = OpImageDrefGather %22 %133 %82 %73 -%135 = OpLoad %22 %58 -%136 = OpFAdd %22 %135 %134 -OpStore %58 %136 -%137 = OpAccessChain %126 %38 %78 -%138 = OpLoad %14 %137 -%139 = OpAccessChain %129 %44 %78 -%140 = OpLoad %18 %139 -%141 = OpSampledImage %132 %138 %140 -%142 = OpImageDrefGather %22 %141 %82 %73 -%143 = OpLoad %22 %58 -%144 = OpFAdd %22 %143 %142 -OpStore %58 %144 -%145 = OpAccessChain %126 %38 %79 -%146 = OpLoad %14 %145 -%147 = OpAccessChain %129 %44 %79 -%148 = OpLoad %18 %147 -%149 = OpSampledImage %132 %146 %148 -%150 = OpImageDrefGather %22 %149 %82 %73 -%151 = OpLoad %22 %58 -%152 = OpFAdd %22 %151 %150 -OpStore %58 %152 -%153 = OpAccessChain %84 %28 %71 -%154 = OpLoad %5 %153 -%156 = OpImageQueryLevels %26 %154 -%157 = OpULessThan %155 %74 %156 -OpSelectionMerge %158 None -OpBranchConditional %157 %159 %158 -%159 = OpLabel -%160 = OpImageQuerySizeLod %25 %154 %74 -%162 = OpULessThan %161 %83 %160 -%163 = OpAll %155 %162 -OpBranchConditional %163 %164 %158 -%164 = OpLabel -%165 = OpImageFetch %22 %154 %83 Lod %74 -OpBranch %158 +%43 = OpTypeStruct %4 +%44 = OpTypePointer Uniform %43 +%42 = OpVariable %44 Uniform +%46 = OpTypePointer Function %3 +%47 = OpConstantNull %3 +%49 = OpTypePointer Function %23 +%50 = OpConstantNull %23 +%52 = OpTypePointer Function %6 +%53 = OpConstantNull %6 +%55 = OpTypePointer Function %22 +%56 = OpConstantNull %22 +%60 = OpTypePointer Input %3 +%59 = OpVariable %60 Input +%63 = OpTypePointer Output %22 +%62 = OpVariable %63 Output +%65 = OpTypeFunction %2 +%66 = OpTypePointer Uniform %4 +%67 = OpConstant %3 0 +%69 = OpConstant %6 0.0 +%70 = OpTypeInt 32 1 +%71 = OpConstant %70 0 +%73 = OpTypePointer Uniform %3 +%79 = OpTypeVector %6 2 +%81 = OpTypeVector %70 2 +%83 = OpTypePointer UniformConstant %5 +%101 = OpTypePointer UniformConstant %18 +%104 = OpTypeSampledImage %5 +%125 = OpTypePointer UniformConstant %14 +%128 = OpTypePointer UniformConstant %18 +%131 = OpTypeSampledImage %14 +%154 = OpTypeBool +%160 = OpTypeVector %154 2 +%196 = OpTypePointer UniformConstant %10 +%199 = OpTypeVector %3 3 +%231 = OpTypePointer UniformConstant %12 +%391 = OpTypePointer UniformConstant %16 +%64 = OpFunction %2 None %65 +%57 = OpLabel +%48 = OpVariable %49 Function %50 +%54 = OpVariable %55 Function %56 +%45 = OpVariable %46 Function %47 +%51 = OpVariable %52 Function %53 +%61 = OpLoad %3 %59 +%58 = OpCompositeConstruct %21 %61 +%68 = OpAccessChain %66 %42 %67 +OpBranch %72 +%72 = OpLabel +%74 = OpAccessChain %73 %68 %67 +%75 = OpLoad %3 %74 +%76 = OpCompositeExtract %3 %58 0 +OpStore %45 %67 +%77 = OpCompositeConstruct %23 %67 %67 +OpStore %48 %77 +OpStore %51 %69 +%78 = OpCompositeConstruct %22 %69 %69 %69 %69 +OpStore %54 %78 +%80 = OpCompositeConstruct %79 %69 %69 +%82 = OpCompositeConstruct %81 %71 %71 +%84 = OpAccessChain %83 %24 %67 +%85 = OpLoad %5 %84 +%86 = OpImageQuerySizeLod %23 %85 %67 +%87 = OpLoad %23 %48 +%88 = OpIAdd %23 %87 %86 +OpStore %48 %88 +%89 = OpAccessChain %83 %24 %75 +%90 = OpLoad %5 %89 +%91 = OpImageQuerySizeLod %23 %90 %67 +%92 = OpLoad %23 %48 +%93 = OpIAdd %23 %92 %91 +OpStore %48 %93 +%94 = OpAccessChain %83 %24 %76 +%95 = OpLoad %5 %94 +%96 = OpImageQuerySizeLod %23 %95 %67 +%97 = OpLoad %23 %48 +%98 = OpIAdd %23 %97 %96 +OpStore %48 %98 +%99 = OpAccessChain %83 %28 %67 +%100 = OpLoad %5 %99 +%102 = OpAccessChain %101 %38 %67 +%103 = OpLoad %18 %102 +%105 = OpSampledImage %104 %100 %103 +%106 = OpImageGather %22 %105 %80 %67 +%107 = OpLoad %22 %54 +%108 = OpFAdd %22 %107 %106 +OpStore %54 %108 +%109 = OpAccessChain %83 %28 %75 +%110 = OpLoad %5 %109 +%111 = OpAccessChain %101 %38 %75 +%112 = OpLoad %18 %111 +%113 = OpSampledImage %104 %110 %112 +%114 = OpImageGather %22 %113 %80 %67 +%115 = OpLoad %22 %54 +%116 = OpFAdd %22 %115 %114 +OpStore %54 %116 +%117 = OpAccessChain %83 %28 %76 +%118 = OpLoad %5 %117 +%119 = OpAccessChain %101 %38 %76 +%120 = OpLoad %18 %119 +%121 = OpSampledImage %104 %118 %120 +%122 = OpImageGather %22 %121 %80 %67 +%123 = OpLoad %22 %54 +%124 = OpFAdd %22 %123 %122 +OpStore %54 %124 +%126 = OpAccessChain %125 %34 %67 +%127 = OpLoad %14 %126 +%129 = OpAccessChain %128 %40 %67 +%130 = OpLoad %18 %129 +%132 = OpSampledImage %131 %127 %130 +%133 = OpImageDrefGather %22 %132 %80 %69 +%134 = OpLoad %22 %54 +%135 = OpFAdd %22 %134 %133 +OpStore %54 %135 +%136 = OpAccessChain %125 %34 %75 +%137 = OpLoad %14 %136 +%138 = OpAccessChain %128 %40 %75 +%139 = OpLoad %18 %138 +%140 = OpSampledImage %131 %137 %139 +%141 = OpImageDrefGather %22 %140 %80 %69 +%142 = OpLoad %22 %54 +%143 = OpFAdd %22 %142 %141 +OpStore %54 %143 +%144 = OpAccessChain %125 %34 %76 +%145 = OpLoad %14 %144 +%146 = OpAccessChain %128 %40 %76 +%147 = OpLoad %18 %146 +%148 = OpSampledImage %131 %145 %147 +%149 = OpImageDrefGather %22 %148 %80 %69 +%150 = OpLoad %22 %54 +%151 = OpFAdd %22 %150 %149 +OpStore %54 %151 +%152 = OpAccessChain %83 %24 %67 +%153 = OpLoad %5 %152 +%155 = OpImageQueryLevels %70 %153 +%156 = OpULessThan %154 %71 %155 +OpSelectionMerge %157 None +OpBranchConditional %156 %158 %157 %158 = OpLabel -%166 = OpPhi %22 %60 %75 %60 %159 %165 %164 -%167 = OpLoad %22 %58 -%168 = OpFAdd %22 %167 %166 -OpStore %58 %168 -%169 = OpAccessChain %84 %28 %78 -%170 = OpLoad %5 %169 -%171 = OpImageQueryLevels %26 %170 -%172 = OpULessThan %155 %74 %171 -OpSelectionMerge %173 None -OpBranchConditional %172 %174 %173 -%174 = OpLabel -%175 = OpImageQuerySizeLod %25 %170 %74 -%176 = OpULessThan %161 %83 %175 -%177 = OpAll %155 %176 -OpBranchConditional %177 %178 %173 -%178 = OpLabel -%179 = OpImageFetch %22 %170 %83 Lod %74 -OpBranch %173 +%159 = OpImageQuerySizeLod %81 %153 %71 +%161 = OpULessThan %160 %82 %159 +%162 = OpAll %154 %161 +OpBranchConditional %162 %163 %157 +%163 = OpLabel +%164 = OpImageFetch %22 %153 %82 Lod %71 +OpBranch %157 +%157 = OpLabel +%165 = OpPhi %22 %56 %72 %56 %158 %164 %163 +%166 = OpLoad %22 %54 +%167 = OpFAdd %22 %166 %165 +OpStore %54 %167 +%168 = OpAccessChain %83 %24 %75 +%169 = OpLoad %5 %168 +%170 = OpImageQueryLevels %70 %169 +%171 = OpULessThan %154 %71 %170 +OpSelectionMerge %172 None +OpBranchConditional %171 %173 %172 %173 = OpLabel -%180 = OpPhi %22 %60 %158 %60 %174 %179 %178 -%181 = OpLoad %22 %58 -%182 = OpFAdd %22 %181 %180 -OpStore %58 %182 -%183 = OpAccessChain %84 %28 %79 -%184 = OpLoad %5 %183 -%185 = OpImageQueryLevels %26 %184 -%186 = OpULessThan %155 %74 %185 -OpSelectionMerge %187 None -OpBranchConditional %186 %188 %187 -%188 = OpLabel -%189 = OpImageQuerySizeLod %25 %184 %74 -%190 = OpULessThan %161 %83 %189 -%191 = OpAll %155 %190 -OpBranchConditional %191 %192 %187 -%192 = OpLabel -%193 = OpImageFetch %22 %184 %83 Lod %74 -OpBranch %187 +%174 = OpImageQuerySizeLod %81 %169 %71 +%175 = OpULessThan %160 %82 %174 +%176 = OpAll %154 %175 +OpBranchConditional %176 %177 %172 +%177 = OpLabel +%178 = OpImageFetch %22 %169 %82 Lod %71 +OpBranch %172 +%172 = OpLabel +%179 = OpPhi %22 %56 %157 %56 %173 %178 %177 +%180 = OpLoad %22 %54 +%181 = OpFAdd %22 %180 %179 +OpStore %54 %181 +%182 = OpAccessChain %83 %24 %76 +%183 = OpLoad %5 %182 +%184 = OpImageQueryLevels %70 %183 +%185 = OpULessThan %154 %71 %184 +OpSelectionMerge %186 None +OpBranchConditional %185 %187 %186 %187 = OpLabel -%194 = OpPhi %22 %60 %173 %60 %188 %193 %192 -%195 = OpLoad %22 %58 -%196 = OpFAdd %22 %195 %194 -OpStore %58 %196 -%198 = OpAccessChain %197 %34 %71 -%199 = OpLoad %10 %198 -%201 = OpImageQuerySizeLod %200 %199 %71 -%202 = OpCompositeExtract %3 %201 2 -%203 = OpLoad %3 %49 -%204 = OpIAdd %3 %203 %202 -OpStore %49 %204 -%205 = OpAccessChain %197 %34 %78 -%206 = OpLoad %10 %205 -%207 = OpImageQuerySizeLod %200 %206 %71 -%208 = OpCompositeExtract %3 %207 2 -%209 = OpLoad %3 %49 -%210 = OpIAdd %3 %209 %208 -OpStore %49 %210 -%211 = OpAccessChain %197 %34 %79 -%212 = OpLoad %10 %211 -%213 = OpImageQuerySizeLod %200 %212 %71 -%214 = OpCompositeExtract %3 %213 2 -%215 = OpLoad %3 %49 -%216 = OpIAdd %3 %215 %214 -OpStore %49 %216 -%217 = OpAccessChain %84 %32 %71 -%218 = OpLoad %5 %217 -%219 = OpImageQueryLevels %3 %218 -%220 = OpLoad %3 %49 -%221 = OpIAdd %3 %220 %219 -OpStore %49 %221 -%222 = OpAccessChain %84 %32 %78 -%223 = OpLoad %5 %222 -%224 = OpImageQueryLevels %3 %223 -%225 = OpLoad %3 %49 -%226 = OpIAdd %3 %225 %224 -OpStore %49 %226 -%227 = OpAccessChain %84 %32 %79 -%228 = OpLoad %5 %227 -%229 = OpImageQueryLevels %3 %228 -%230 = OpLoad %3 %49 -%231 = OpIAdd %3 %230 %229 -OpStore %49 %231 -%233 = OpAccessChain %232 %36 %71 -%234 = OpLoad %12 %233 -%235 = OpImageQuerySamples %3 %234 -%236 = OpLoad %3 %49 -%237 = OpIAdd %3 %236 %235 -OpStore %49 %237 -%238 = OpAccessChain %232 %36 %78 -%239 = OpLoad %12 %238 -%240 = OpImageQuerySamples %3 %239 -%241 = OpLoad %3 %49 -%242 = OpIAdd %3 %241 %240 -OpStore %49 %242 -%243 = OpAccessChain %232 %36 %79 -%244 = OpLoad %12 %243 -%245 = OpImageQuerySamples %3 %244 -%246 = OpLoad %3 %49 -%247 = OpIAdd %3 %246 %245 -OpStore %49 %247 -%248 = OpAccessChain %84 %32 %71 -%249 = OpLoad %5 %248 -%250 = OpAccessChain %102 %42 %71 -%251 = OpLoad %18 %250 -%252 = OpSampledImage %105 %249 %251 -%253 = OpImageSampleImplicitLod %22 %252 %82 -%254 = OpLoad %22 %58 -%255 = OpFAdd %22 %254 %253 -OpStore %58 %255 -%256 = OpAccessChain %84 %32 %78 -%257 = OpLoad %5 %256 -%258 = OpAccessChain %102 %42 %78 -%259 = OpLoad %18 %258 -%260 = OpSampledImage %105 %257 %259 -%261 = OpImageSampleImplicitLod %22 %260 %82 -%262 = OpLoad %22 %58 -%263 = OpFAdd %22 %262 %261 -OpStore %58 %263 -%264 = OpAccessChain %84 %32 %79 -%265 = OpLoad %5 %264 -%266 = OpAccessChain %102 %42 %79 -%267 = OpLoad %18 %266 -%268 = OpSampledImage %105 %265 %267 -%269 = OpImageSampleImplicitLod %22 %268 %82 -%270 = OpLoad %22 %58 -%271 = OpFAdd %22 %270 %269 -OpStore %58 %271 -%272 = OpAccessChain %84 %32 %71 -%273 = OpLoad %5 %272 -%274 = OpAccessChain %102 %42 %71 -%275 = OpLoad %18 %274 -%276 = OpSampledImage %105 %273 %275 -%277 = OpImageSampleImplicitLod %22 %276 %82 Bias %73 -%278 = OpLoad %22 %58 -%279 = OpFAdd %22 %278 %277 -OpStore %58 %279 -%280 = OpAccessChain %84 %32 %78 -%281 = OpLoad %5 %280 -%282 = OpAccessChain %102 %42 %78 -%283 = OpLoad %18 %282 -%284 = OpSampledImage %105 %281 %283 -%285 = OpImageSampleImplicitLod %22 %284 %82 Bias %73 -%286 = OpLoad %22 %58 -%287 = OpFAdd %22 %286 %285 -OpStore %58 %287 -%288 = OpAccessChain %84 %32 %79 -%289 = OpLoad %5 %288 -%290 = OpAccessChain %102 %42 %79 -%291 = OpLoad %18 %290 -%292 = OpSampledImage %105 %289 %291 -%293 = OpImageSampleImplicitLod %22 %292 %82 Bias %73 -%294 = OpLoad %22 %58 -%295 = OpFAdd %22 %294 %293 -OpStore %58 %295 -%296 = OpAccessChain %126 %38 %71 -%297 = OpLoad %14 %296 -%298 = OpAccessChain %129 %44 %71 -%299 = OpLoad %18 %298 -%300 = OpSampledImage %132 %297 %299 -%301 = OpImageSampleDrefImplicitLod %6 %300 %82 %73 -%302 = OpLoad %6 %55 -%303 = OpFAdd %6 %302 %301 -OpStore %55 %303 -%304 = OpAccessChain %126 %38 %78 -%305 = OpLoad %14 %304 -%306 = OpAccessChain %129 %44 %78 -%307 = OpLoad %18 %306 -%308 = OpSampledImage %132 %305 %307 -%309 = OpImageSampleDrefImplicitLod %6 %308 %82 %73 -%310 = OpLoad %6 %55 -%311 = OpFAdd %6 %310 %309 -OpStore %55 %311 -%312 = OpAccessChain %126 %38 %79 -%313 = OpLoad %14 %312 -%314 = OpAccessChain %129 %44 %79 -%315 = OpLoad %18 %314 -%316 = OpSampledImage %132 %313 %315 -%317 = OpImageSampleDrefImplicitLod %6 %316 %82 %73 -%318 = OpLoad %6 %55 -%319 = OpFAdd %6 %318 %317 -OpStore %55 %319 -%320 = OpAccessChain %126 %38 %71 -%321 = OpLoad %14 %320 -%322 = OpAccessChain %129 %44 %71 -%323 = OpLoad %18 %322 -%324 = OpSampledImage %132 %321 %323 -%325 = OpImageSampleDrefExplicitLod %6 %324 %82 %73 Lod %73 -%326 = OpLoad %6 %55 -%327 = OpFAdd %6 %326 %325 -OpStore %55 %327 -%328 = OpAccessChain %126 %38 %78 -%329 = OpLoad %14 %328 -%330 = OpAccessChain %129 %44 %78 -%331 = OpLoad %18 %330 -%332 = OpSampledImage %132 %329 %331 -%333 = OpImageSampleDrefExplicitLod %6 %332 %82 %73 Lod %73 -%334 = OpLoad %6 %55 -%335 = OpFAdd %6 %334 %333 -OpStore %55 %335 -%336 = OpAccessChain %126 %38 %79 -%337 = OpLoad %14 %336 -%338 = OpAccessChain %129 %44 %79 -%339 = OpLoad %18 %338 -%340 = OpSampledImage %132 %337 %339 -%341 = OpImageSampleDrefExplicitLod %6 %340 %82 %73 Lod %73 -%342 = OpLoad %6 %55 -%343 = OpFAdd %6 %342 %341 -OpStore %55 %343 -%344 = OpAccessChain %84 %32 %71 -%345 = OpLoad %5 %344 -%346 = OpAccessChain %102 %42 %71 -%347 = OpLoad %18 %346 -%348 = OpSampledImage %105 %345 %347 -%349 = OpImageSampleExplicitLod %22 %348 %82 Grad %82 %82 -%350 = OpLoad %22 %58 -%351 = OpFAdd %22 %350 %349 -OpStore %58 %351 -%352 = OpAccessChain %84 %32 %78 -%353 = OpLoad %5 %352 -%354 = OpAccessChain %102 %42 %78 -%355 = OpLoad %18 %354 -%356 = OpSampledImage %105 %353 %355 -%357 = OpImageSampleExplicitLod %22 %356 %82 Grad %82 %82 -%358 = OpLoad %22 %58 -%359 = OpFAdd %22 %358 %357 -OpStore %58 %359 -%360 = OpAccessChain %84 %32 %79 -%361 = OpLoad %5 %360 -%362 = OpAccessChain %102 %42 %79 -%363 = OpLoad %18 %362 -%364 = OpSampledImage %105 %361 %363 -%365 = OpImageSampleExplicitLod %22 %364 %82 Grad %82 %82 -%366 = OpLoad %22 %58 -%367 = OpFAdd %22 %366 %365 -OpStore %58 %367 -%368 = OpAccessChain %84 %32 %71 -%369 = OpLoad %5 %368 -%370 = OpAccessChain %102 %42 %71 -%371 = OpLoad %18 %370 -%372 = OpSampledImage %105 %369 %371 -%373 = OpImageSampleExplicitLod %22 %372 %82 Lod %73 -%374 = OpLoad %22 %58 -%375 = OpFAdd %22 %374 %373 -OpStore %58 %375 -%376 = OpAccessChain %84 %32 %78 -%377 = OpLoad %5 %376 -%378 = OpAccessChain %102 %42 %78 -%379 = OpLoad %18 %378 -%380 = OpSampledImage %105 %377 %379 -%381 = OpImageSampleExplicitLod %22 %380 %82 Lod %73 -%382 = OpLoad %22 %58 -%383 = OpFAdd %22 %382 %381 -OpStore %58 %383 -%384 = OpAccessChain %84 %32 %79 -%385 = OpLoad %5 %384 -%386 = OpAccessChain %102 %42 %79 -%387 = OpLoad %18 %386 -%388 = OpSampledImage %105 %385 %387 -%389 = OpImageSampleExplicitLod %22 %388 %82 Lod %73 -%390 = OpLoad %22 %58 -%391 = OpFAdd %22 %390 %389 -OpStore %58 %391 -%393 = OpAccessChain %392 %40 %71 -%394 = OpLoad %16 %393 -%395 = OpLoad %22 %58 -%396 = OpImageQuerySize %25 %394 -%397 = OpULessThan %161 %83 %396 -%398 = OpAll %155 %397 -OpSelectionMerge %399 None -OpBranchConditional %398 %400 %399 -%400 = OpLabel -OpImageWrite %394 %83 %395 -OpBranch %399 +%188 = OpImageQuerySizeLod %81 %183 %71 +%189 = OpULessThan %160 %82 %188 +%190 = OpAll %154 %189 +OpBranchConditional %190 %191 %186 +%191 = OpLabel +%192 = OpImageFetch %22 %183 %82 Lod %71 +OpBranch %186 +%186 = OpLabel +%193 = OpPhi %22 %56 %172 %56 %187 %192 %191 +%194 = OpLoad %22 %54 +%195 = OpFAdd %22 %194 %193 +OpStore %54 %195 +%197 = OpAccessChain %196 %30 %67 +%198 = OpLoad %10 %197 +%200 = OpImageQuerySizeLod %199 %198 %67 +%201 = OpCompositeExtract %3 %200 2 +%202 = OpLoad %3 %45 +%203 = OpIAdd %3 %202 %201 +OpStore %45 %203 +%204 = OpAccessChain %196 %30 %75 +%205 = OpLoad %10 %204 +%206 = OpImageQuerySizeLod %199 %205 %67 +%207 = OpCompositeExtract %3 %206 2 +%208 = OpLoad %3 %45 +%209 = OpIAdd %3 %208 %207 +OpStore %45 %209 +%210 = OpAccessChain %196 %30 %76 +%211 = OpLoad %10 %210 +%212 = OpImageQuerySizeLod %199 %211 %67 +%213 = OpCompositeExtract %3 %212 2 +%214 = OpLoad %3 %45 +%215 = OpIAdd %3 %214 %213 +OpStore %45 %215 +%216 = OpAccessChain %83 %28 %67 +%217 = OpLoad %5 %216 +%218 = OpImageQueryLevels %3 %217 +%219 = OpLoad %3 %45 +%220 = OpIAdd %3 %219 %218 +OpStore %45 %220 +%221 = OpAccessChain %83 %28 %75 +%222 = OpLoad %5 %221 +%223 = OpImageQueryLevels %3 %222 +%224 = OpLoad %3 %45 +%225 = OpIAdd %3 %224 %223 +OpStore %45 %225 +%226 = OpAccessChain %83 %28 %76 +%227 = OpLoad %5 %226 +%228 = OpImageQueryLevels %3 %227 +%229 = OpLoad %3 %45 +%230 = OpIAdd %3 %229 %228 +OpStore %45 %230 +%232 = OpAccessChain %231 %32 %67 +%233 = OpLoad %12 %232 +%234 = OpImageQuerySamples %3 %233 +%235 = OpLoad %3 %45 +%236 = OpIAdd %3 %235 %234 +OpStore %45 %236 +%237 = OpAccessChain %231 %32 %75 +%238 = OpLoad %12 %237 +%239 = OpImageQuerySamples %3 %238 +%240 = OpLoad %3 %45 +%241 = OpIAdd %3 %240 %239 +OpStore %45 %241 +%242 = OpAccessChain %231 %32 %76 +%243 = OpLoad %12 %242 +%244 = OpImageQuerySamples %3 %243 +%245 = OpLoad %3 %45 +%246 = OpIAdd %3 %245 %244 +OpStore %45 %246 +%247 = OpAccessChain %83 %28 %67 +%248 = OpLoad %5 %247 +%249 = OpAccessChain %101 %38 %67 +%250 = OpLoad %18 %249 +%251 = OpSampledImage %104 %248 %250 +%252 = OpImageSampleImplicitLod %22 %251 %80 +%253 = OpLoad %22 %54 +%254 = OpFAdd %22 %253 %252 +OpStore %54 %254 +%255 = OpAccessChain %83 %28 %75 +%256 = OpLoad %5 %255 +%257 = OpAccessChain %101 %38 %75 +%258 = OpLoad %18 %257 +%259 = OpSampledImage %104 %256 %258 +%260 = OpImageSampleImplicitLod %22 %259 %80 +%261 = OpLoad %22 %54 +%262 = OpFAdd %22 %261 %260 +OpStore %54 %262 +%263 = OpAccessChain %83 %28 %76 +%264 = OpLoad %5 %263 +%265 = OpAccessChain %101 %38 %76 +%266 = OpLoad %18 %265 +%267 = OpSampledImage %104 %264 %266 +%268 = OpImageSampleImplicitLod %22 %267 %80 +%269 = OpLoad %22 %54 +%270 = OpFAdd %22 %269 %268 +OpStore %54 %270 +%271 = OpAccessChain %83 %28 %67 +%272 = OpLoad %5 %271 +%273 = OpAccessChain %101 %38 %67 +%274 = OpLoad %18 %273 +%275 = OpSampledImage %104 %272 %274 +%276 = OpImageSampleImplicitLod %22 %275 %80 Bias %69 +%277 = OpLoad %22 %54 +%278 = OpFAdd %22 %277 %276 +OpStore %54 %278 +%279 = OpAccessChain %83 %28 %75 +%280 = OpLoad %5 %279 +%281 = OpAccessChain %101 %38 %75 +%282 = OpLoad %18 %281 +%283 = OpSampledImage %104 %280 %282 +%284 = OpImageSampleImplicitLod %22 %283 %80 Bias %69 +%285 = OpLoad %22 %54 +%286 = OpFAdd %22 %285 %284 +OpStore %54 %286 +%287 = OpAccessChain %83 %28 %76 +%288 = OpLoad %5 %287 +%289 = OpAccessChain %101 %38 %76 +%290 = OpLoad %18 %289 +%291 = OpSampledImage %104 %288 %290 +%292 = OpImageSampleImplicitLod %22 %291 %80 Bias %69 +%293 = OpLoad %22 %54 +%294 = OpFAdd %22 %293 %292 +OpStore %54 %294 +%295 = OpAccessChain %125 %34 %67 +%296 = OpLoad %14 %295 +%297 = OpAccessChain %128 %40 %67 +%298 = OpLoad %18 %297 +%299 = OpSampledImage %131 %296 %298 +%300 = OpImageSampleDrefImplicitLod %6 %299 %80 %69 +%301 = OpLoad %6 %51 +%302 = OpFAdd %6 %301 %300 +OpStore %51 %302 +%303 = OpAccessChain %125 %34 %75 +%304 = OpLoad %14 %303 +%305 = OpAccessChain %128 %40 %75 +%306 = OpLoad %18 %305 +%307 = OpSampledImage %131 %304 %306 +%308 = OpImageSampleDrefImplicitLod %6 %307 %80 %69 +%309 = OpLoad %6 %51 +%310 = OpFAdd %6 %309 %308 +OpStore %51 %310 +%311 = OpAccessChain %125 %34 %76 +%312 = OpLoad %14 %311 +%313 = OpAccessChain %128 %40 %76 +%314 = OpLoad %18 %313 +%315 = OpSampledImage %131 %312 %314 +%316 = OpImageSampleDrefImplicitLod %6 %315 %80 %69 +%317 = OpLoad %6 %51 +%318 = OpFAdd %6 %317 %316 +OpStore %51 %318 +%319 = OpAccessChain %125 %34 %67 +%320 = OpLoad %14 %319 +%321 = OpAccessChain %128 %40 %67 +%322 = OpLoad %18 %321 +%323 = OpSampledImage %131 %320 %322 +%324 = OpImageSampleDrefExplicitLod %6 %323 %80 %69 Lod %69 +%325 = OpLoad %6 %51 +%326 = OpFAdd %6 %325 %324 +OpStore %51 %326 +%327 = OpAccessChain %125 %34 %75 +%328 = OpLoad %14 %327 +%329 = OpAccessChain %128 %40 %75 +%330 = OpLoad %18 %329 +%331 = OpSampledImage %131 %328 %330 +%332 = OpImageSampleDrefExplicitLod %6 %331 %80 %69 Lod %69 +%333 = OpLoad %6 %51 +%334 = OpFAdd %6 %333 %332 +OpStore %51 %334 +%335 = OpAccessChain %125 %34 %76 +%336 = OpLoad %14 %335 +%337 = OpAccessChain %128 %40 %76 +%338 = OpLoad %18 %337 +%339 = OpSampledImage %131 %336 %338 +%340 = OpImageSampleDrefExplicitLod %6 %339 %80 %69 Lod %69 +%341 = OpLoad %6 %51 +%342 = OpFAdd %6 %341 %340 +OpStore %51 %342 +%343 = OpAccessChain %83 %28 %67 +%344 = OpLoad %5 %343 +%345 = OpAccessChain %101 %38 %67 +%346 = OpLoad %18 %345 +%347 = OpSampledImage %104 %344 %346 +%348 = OpImageSampleExplicitLod %22 %347 %80 Grad %80 %80 +%349 = OpLoad %22 %54 +%350 = OpFAdd %22 %349 %348 +OpStore %54 %350 +%351 = OpAccessChain %83 %28 %75 +%352 = OpLoad %5 %351 +%353 = OpAccessChain %101 %38 %75 +%354 = OpLoad %18 %353 +%355 = OpSampledImage %104 %352 %354 +%356 = OpImageSampleExplicitLod %22 %355 %80 Grad %80 %80 +%357 = OpLoad %22 %54 +%358 = OpFAdd %22 %357 %356 +OpStore %54 %358 +%359 = OpAccessChain %83 %28 %76 +%360 = OpLoad %5 %359 +%361 = OpAccessChain %101 %38 %76 +%362 = OpLoad %18 %361 +%363 = OpSampledImage %104 %360 %362 +%364 = OpImageSampleExplicitLod %22 %363 %80 Grad %80 %80 +%365 = OpLoad %22 %54 +%366 = OpFAdd %22 %365 %364 +OpStore %54 %366 +%367 = OpAccessChain %83 %28 %67 +%368 = OpLoad %5 %367 +%369 = OpAccessChain %101 %38 %67 +%370 = OpLoad %18 %369 +%371 = OpSampledImage %104 %368 %370 +%372 = OpImageSampleExplicitLod %22 %371 %80 Lod %69 +%373 = OpLoad %22 %54 +%374 = OpFAdd %22 %373 %372 +OpStore %54 %374 +%375 = OpAccessChain %83 %28 %75 +%376 = OpLoad %5 %375 +%377 = OpAccessChain %101 %38 %75 +%378 = OpLoad %18 %377 +%379 = OpSampledImage %104 %376 %378 +%380 = OpImageSampleExplicitLod %22 %379 %80 Lod %69 +%381 = OpLoad %22 %54 +%382 = OpFAdd %22 %381 %380 +OpStore %54 %382 +%383 = OpAccessChain %83 %28 %76 +%384 = OpLoad %5 %383 +%385 = OpAccessChain %101 %38 %76 +%386 = OpLoad %18 %385 +%387 = OpSampledImage %104 %384 %386 +%388 = OpImageSampleExplicitLod %22 %387 %80 Lod %69 +%389 = OpLoad %22 %54 +%390 = OpFAdd %22 %389 %388 +OpStore %54 %390 +%392 = OpAccessChain %391 %36 %67 +%393 = OpLoad %16 %392 +%394 = OpLoad %22 %54 +%395 = OpImageQuerySize %81 %393 +%396 = OpULessThan %160 %82 %395 +%397 = OpAll %154 %396 +OpSelectionMerge %398 None +OpBranchConditional %397 %399 %398 %399 = OpLabel -%401 = OpAccessChain %392 %40 %78 -%402 = OpLoad %16 %401 -%403 = OpLoad %22 %58 -%404 = OpImageQuerySize %25 %402 -%405 = OpULessThan %161 %83 %404 -%406 = OpAll %155 %405 -OpSelectionMerge %407 None -OpBranchConditional %406 %408 %407 -%408 = OpLabel -OpImageWrite %402 %83 %403 -OpBranch %407 +OpImageWrite %393 %82 %394 +OpBranch %398 +%398 = OpLabel +%400 = OpAccessChain %391 %36 %75 +%401 = OpLoad %16 %400 +%402 = OpLoad %22 %54 +%403 = OpImageQuerySize %81 %401 +%404 = OpULessThan %160 %82 %403 +%405 = OpAll %154 %404 +OpSelectionMerge %406 None +OpBranchConditional %405 %407 %406 %407 = OpLabel -%409 = OpAccessChain %392 %40 %79 -%410 = OpLoad %16 %409 -%411 = OpLoad %22 %58 -%412 = OpImageQuerySize %25 %410 -%413 = OpULessThan %161 %83 %412 -%414 = OpAll %155 %413 -OpSelectionMerge %415 None -OpBranchConditional %414 %416 %415 -%416 = OpLabel -OpImageWrite %410 %83 %411 -OpBranch %415 +OpImageWrite %401 %82 %402 +OpBranch %406 +%406 = OpLabel +%408 = OpAccessChain %391 %36 %76 +%409 = OpLoad %16 %408 +%410 = OpLoad %22 %54 +%411 = OpImageQuerySize %81 %409 +%412 = OpULessThan %160 %82 %411 +%413 = OpAll %154 %412 +OpSelectionMerge %414 None +OpBranchConditional %413 %415 %414 %415 = OpLabel -%417 = OpLoad %23 %52 -%418 = OpLoad %3 %49 -%419 = OpCompositeConstruct %23 %418 %418 -%420 = OpIAdd %23 %417 %419 -%421 = OpConvertUToF %24 %420 -%422 = OpLoad %22 %58 -%423 = OpCompositeExtract %6 %421 0 -%424 = OpCompositeExtract %6 %421 1 -%425 = OpCompositeExtract %6 %421 0 -%426 = OpCompositeExtract %6 %421 1 -%427 = OpCompositeConstruct %22 %423 %424 %425 %426 -%428 = OpFAdd %22 %422 %427 -%429 = OpLoad %6 %55 -%430 = OpCompositeConstruct %22 %429 %429 %429 %429 -%431 = OpFAdd %22 %428 %430 -OpStore %66 %431 +OpImageWrite %409 %82 %410 +OpBranch %414 +%414 = OpLabel +%416 = OpLoad %23 %48 +%417 = OpLoad %3 %45 +%418 = OpCompositeConstruct %23 %417 %417 +%419 = OpIAdd %23 %416 %418 +%420 = OpConvertUToF %79 %419 +%421 = OpLoad %22 %54 +%422 = OpCompositeExtract %6 %420 0 +%423 = OpCompositeExtract %6 %420 1 +%424 = OpCompositeExtract %6 %420 0 +%425 = OpCompositeExtract %6 %420 1 +%426 = OpCompositeConstruct %22 %422 %423 %424 %425 +%427 = OpFAdd %22 %421 %426 +%428 = OpLoad %6 %51 +%429 = OpCompositeConstruct %22 %428 %428 %428 %428 +%430 = OpFAdd %22 %427 %429 +OpStore %62 %430 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-buffer-arrays.spvasm b/tests/out/spv/binding-buffer-arrays.spvasm index 00d5b0fcf..bc89271fd 100644 --- a/tests/out/spv/binding-buffer-arrays.spvasm +++ b/tests/out/spv/binding-buffer-arrays.spvasm @@ -1,30 +1,30 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 63 +; Bound: 61 OpCapability Shader OpCapability ShaderNonUniform OpExtension "SPV_KHR_storage_buffer_storage_class" OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %28 "main" %23 %26 -OpExecutionMode %28 OriginUpperLeft +OpEntryPoint Fragment %26 "main" %21 %24 +OpExecutionMode %26 OriginUpperLeft OpMemberDecorate %4 0 Offset 0 OpMemberDecorate %5 0 Offset 0 OpMemberDecorate %8 0 Offset 0 -OpDecorate %11 NonWritable -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 0 +OpDecorate %9 NonWritable +OpDecorate %9 DescriptorSet 0 +OpDecorate %9 Binding 0 OpDecorate %5 Block -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 10 -OpDecorate %16 Block -OpMemberDecorate %16 0 Offset 0 -OpDecorate %23 Location 0 -OpDecorate %23 Flat -OpDecorate %26 Location 0 -OpDecorate %55 NonUniform +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 10 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpDecorate %21 Location 0 +OpDecorate %21 Flat +OpDecorate %24 Location 0 +OpDecorate %53 NonUniform %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeStruct %3 @@ -32,71 +32,69 @@ OpDecorate %55 NonUniform %7 = OpConstant %3 1 %6 = OpTypeArray %5 %7 %8 = OpTypeStruct %3 -%10 = OpTypeInt 32 1 -%9 = OpConstant %10 1 -%14 = OpConstant %3 10 -%13 = OpTypeArray %5 %14 -%12 = OpTypePointer StorageBuffer %13 -%11 = OpVariable %12 StorageBuffer -%16 = OpTypeStruct %4 -%17 = OpTypePointer Uniform %16 -%15 = OpVariable %17 Uniform -%19 = OpTypePointer Function %3 -%20 = OpConstantNull %3 -%24 = OpTypePointer Input %3 -%23 = OpVariable %24 Input -%27 = OpTypePointer Output %3 -%26 = OpVariable %27 Output -%29 = OpTypeFunction %2 -%30 = OpTypePointer Uniform %4 -%31 = OpConstant %3 0 -%33 = OpTypePointer StorageBuffer %6 -%35 = OpTypePointer Uniform %3 -%39 = OpTypePointer StorageBuffer %5 -%40 = OpTypePointer StorageBuffer %3 -%46 = OpTypeBool -%28 = OpFunction %2 None %29 -%21 = OpLabel -%18 = OpVariable %19 Function %20 -%25 = OpLoad %3 %23 -%22 = OpCompositeConstruct %8 %25 -%32 = OpAccessChain %30 %15 %31 -OpBranch %34 -%34 = OpLabel -%36 = OpAccessChain %35 %32 %31 -%37 = OpLoad %3 %36 -%38 = OpCompositeExtract %3 %22 0 -OpStore %18 %31 -%41 = OpAccessChain %40 %11 %31 %31 -%42 = OpLoad %3 %41 -%43 = OpLoad %3 %18 -%44 = OpIAdd %3 %43 %42 -OpStore %18 %44 -%45 = OpULessThan %46 %37 %7 -OpSelectionMerge %48 None -OpBranchConditional %45 %49 %48 -%49 = OpLabel -%47 = OpAccessChain %40 %11 %37 %31 -%50 = OpLoad %3 %47 -OpBranch %48 -%48 = OpLabel -%51 = OpPhi %3 %20 %34 %50 %49 -%52 = OpLoad %3 %18 -%53 = OpIAdd %3 %52 %51 -OpStore %18 %53 -%54 = OpULessThan %46 %38 %7 -OpSelectionMerge %56 None -OpBranchConditional %54 %57 %56 -%57 = OpLabel -%55 = OpAccessChain %40 %11 %38 %31 -%58 = OpLoad %3 %55 -OpBranch %56 -%56 = OpLabel -%59 = OpPhi %3 %20 %48 %58 %57 -%60 = OpLoad %3 %18 -%61 = OpIAdd %3 %60 %59 -OpStore %18 %61 -%62 = OpLoad %3 %18 -OpStore %26 %62 +%12 = OpConstant %3 10 +%11 = OpTypeArray %5 %12 +%10 = OpTypePointer StorageBuffer %11 +%9 = OpVariable %10 StorageBuffer +%14 = OpTypeStruct %4 +%15 = OpTypePointer Uniform %14 +%13 = OpVariable %15 Uniform +%17 = OpTypePointer Function %3 +%18 = OpConstantNull %3 +%22 = OpTypePointer Input %3 +%21 = OpVariable %22 Input +%25 = OpTypePointer Output %3 +%24 = OpVariable %25 Output +%27 = OpTypeFunction %2 +%28 = OpTypePointer Uniform %4 +%29 = OpConstant %3 0 +%31 = OpTypePointer StorageBuffer %6 +%33 = OpTypePointer Uniform %3 +%37 = OpTypePointer StorageBuffer %5 +%38 = OpTypePointer StorageBuffer %3 +%44 = OpTypeBool +%26 = OpFunction %2 None %27 +%19 = OpLabel +%16 = OpVariable %17 Function %18 +%23 = OpLoad %3 %21 +%20 = OpCompositeConstruct %8 %23 +%30 = OpAccessChain %28 %13 %29 +OpBranch %32 +%32 = OpLabel +%34 = OpAccessChain %33 %30 %29 +%35 = OpLoad %3 %34 +%36 = OpCompositeExtract %3 %20 0 +OpStore %16 %29 +%39 = OpAccessChain %38 %9 %29 %29 +%40 = OpLoad %3 %39 +%41 = OpLoad %3 %16 +%42 = OpIAdd %3 %41 %40 +OpStore %16 %42 +%43 = OpULessThan %44 %35 %7 +OpSelectionMerge %46 None +OpBranchConditional %43 %47 %46 +%47 = OpLabel +%45 = OpAccessChain %38 %9 %35 %29 +%48 = OpLoad %3 %45 +OpBranch %46 +%46 = OpLabel +%49 = OpPhi %3 %18 %32 %48 %47 +%50 = OpLoad %3 %16 +%51 = OpIAdd %3 %50 %49 +OpStore %16 %51 +%52 = OpULessThan %44 %36 %7 +OpSelectionMerge %54 None +OpBranchConditional %52 %55 %54 +%55 = OpLabel +%53 = OpAccessChain %38 %9 %36 %29 +%56 = OpLoad %3 %53 +OpBranch %54 +%54 = OpLabel +%57 = OpPhi %3 %18 %46 %56 %55 +%58 = OpLoad %3 %16 +%59 = OpIAdd %3 %58 %57 +OpStore %16 %59 +%60 = OpLoad %3 %16 +OpStore %24 %60 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-restrict.spvasm b/tests/out/spv/bounds-check-restrict.spvasm index 69e612022..c7cf675a1 100644 --- a/tests/out/spv/bounds-check-restrict.spvasm +++ b/tests/out/spv/bounds-check-restrict.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 164 +; Bound: 163 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -16,8 +16,8 @@ OpMemberDecorate %10 2 ColMajor OpMemberDecorate %10 2 MatrixStride 16 OpMemberDecorate %10 3 Offset 112 OpDecorate %10 Block -OpDecorate %13 DescriptorSet 0 -OpDecorate %13 Binding 0 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 0 %2 = OpTypeVoid %3 = OpTypeFloat 32 %6 = OpTypeInt 32 0 @@ -28,209 +28,208 @@ OpDecorate %13 Binding 0 %9 = OpTypeRuntimeArray %3 %10 = OpTypeStruct %4 %7 %8 %9 %11 = OpTypeInt 32 1 -%12 = OpConstant %11 10 -%14 = OpTypePointer StorageBuffer %10 -%13 = OpVariable %14 StorageBuffer -%18 = OpTypeFunction %3 %11 -%20 = OpTypePointer StorageBuffer %4 -%21 = OpTypePointer StorageBuffer %3 -%22 = OpConstant %6 9 -%24 = OpConstant %6 0 -%31 = OpTypePointer StorageBuffer %9 -%33 = OpConstant %6 1 -%36 = OpConstant %6 3 -%43 = OpTypePointer StorageBuffer %7 -%44 = OpTypePointer StorageBuffer %3 -%52 = OpTypeFunction %3 %7 %11 -%59 = OpTypeFunction %7 %11 -%61 = OpTypePointer StorageBuffer %8 -%62 = OpTypePointer StorageBuffer %7 -%63 = OpConstant %6 2 -%71 = OpTypeFunction %3 %11 %11 -%80 = OpConstant %3 100.0 -%92 = OpTypeFunction %3 -%106 = OpTypeFunction %2 %11 %3 -%130 = OpTypeFunction %2 %11 %7 -%139 = OpTypeFunction %2 %11 %11 %3 -%159 = OpTypeFunction %2 %3 -%17 = OpFunction %3 None %18 -%16 = OpFunctionParameter %11 -%15 = OpLabel -OpBranch %19 -%19 = OpLabel -%23 = OpExtInst %6 %1 UMin %16 %22 -%25 = OpAccessChain %21 %13 %24 %23 -%26 = OpLoad %3 %25 -OpReturnValue %26 +%13 = OpTypePointer StorageBuffer %10 +%12 = OpVariable %13 StorageBuffer +%17 = OpTypeFunction %3 %11 +%19 = OpTypePointer StorageBuffer %4 +%20 = OpTypePointer StorageBuffer %3 +%21 = OpConstant %6 9 +%23 = OpConstant %6 0 +%30 = OpTypePointer StorageBuffer %9 +%32 = OpConstant %6 1 +%35 = OpConstant %6 3 +%42 = OpTypePointer StorageBuffer %7 +%43 = OpTypePointer StorageBuffer %3 +%51 = OpTypeFunction %3 %7 %11 +%58 = OpTypeFunction %7 %11 +%60 = OpTypePointer StorageBuffer %8 +%61 = OpTypePointer StorageBuffer %7 +%62 = OpConstant %6 2 +%70 = OpTypeFunction %3 %11 %11 +%79 = OpConstant %3 100.0 +%91 = OpTypeFunction %3 +%105 = OpTypeFunction %2 %11 %3 +%129 = OpTypeFunction %2 %11 %7 +%138 = OpTypeFunction %2 %11 %11 %3 +%158 = OpTypeFunction %2 %3 +%16 = OpFunction %3 None %17 +%15 = OpFunctionParameter %11 +%14 = OpLabel +OpBranch %18 +%18 = OpLabel +%22 = OpExtInst %6 %1 UMin %15 %21 +%24 = OpAccessChain %20 %12 %23 %22 +%25 = OpLoad %3 %24 +OpReturnValue %25 OpFunctionEnd -%29 = OpFunction %3 None %18 -%28 = OpFunctionParameter %11 -%27 = OpLabel -OpBranch %30 -%30 = OpLabel -%32 = OpArrayLength %6 %13 3 -%34 = OpISub %6 %32 %33 -%35 = OpExtInst %6 %1 UMin %28 %34 -%37 = OpAccessChain %21 %13 %36 %35 -%38 = OpLoad %3 %37 -OpReturnValue %38 +%28 = OpFunction %3 None %17 +%27 = OpFunctionParameter %11 +%26 = OpLabel +OpBranch %29 +%29 = OpLabel +%31 = OpArrayLength %6 %12 3 +%33 = OpISub %6 %31 %32 +%34 = OpExtInst %6 %1 UMin %27 %33 +%36 = OpAccessChain %20 %12 %35 %34 +%37 = OpLoad %3 %36 +OpReturnValue %37 OpFunctionEnd -%41 = OpFunction %3 None %18 -%40 = OpFunctionParameter %11 -%39 = OpLabel -OpBranch %42 -%42 = OpLabel -%45 = OpExtInst %6 %1 UMin %40 %36 -%46 = OpAccessChain %44 %13 %33 %45 -%47 = OpLoad %3 %46 -OpReturnValue %47 +%40 = OpFunction %3 None %17 +%39 = OpFunctionParameter %11 +%38 = OpLabel +OpBranch %41 +%41 = OpLabel +%44 = OpExtInst %6 %1 UMin %39 %35 +%45 = OpAccessChain %43 %12 %32 %44 +%46 = OpLoad %3 %45 +OpReturnValue %46 OpFunctionEnd -%51 = OpFunction %3 None %52 -%49 = OpFunctionParameter %7 -%50 = OpFunctionParameter %11 -%48 = OpLabel -OpBranch %53 -%53 = OpLabel -%54 = OpExtInst %6 %1 UMin %50 %36 -%55 = OpVectorExtractDynamic %3 %49 %54 -OpReturnValue %55 +%50 = OpFunction %3 None %51 +%48 = OpFunctionParameter %7 +%49 = OpFunctionParameter %11 +%47 = OpLabel +OpBranch %52 +%52 = OpLabel +%53 = OpExtInst %6 %1 UMin %49 %35 +%54 = OpVectorExtractDynamic %3 %48 %53 +OpReturnValue %54 OpFunctionEnd -%58 = OpFunction %7 None %59 -%57 = OpFunctionParameter %11 -%56 = OpLabel -OpBranch %60 -%60 = OpLabel -%64 = OpExtInst %6 %1 UMin %57 %63 -%65 = OpAccessChain %62 %13 %63 %64 -%66 = OpLoad %7 %65 -OpReturnValue %66 +%57 = OpFunction %7 None %58 +%56 = OpFunctionParameter %11 +%55 = OpLabel +OpBranch %59 +%59 = OpLabel +%63 = OpExtInst %6 %1 UMin %56 %62 +%64 = OpAccessChain %61 %12 %62 %63 +%65 = OpLoad %7 %64 +OpReturnValue %65 OpFunctionEnd -%70 = OpFunction %3 None %71 +%69 = OpFunction %3 None %70 +%67 = OpFunctionParameter %11 %68 = OpFunctionParameter %11 -%69 = OpFunctionParameter %11 -%67 = OpLabel -OpBranch %72 -%72 = OpLabel -%73 = OpExtInst %6 %1 UMin %69 %36 -%74 = OpExtInst %6 %1 UMin %68 %63 -%75 = OpAccessChain %44 %13 %63 %74 %73 -%76 = OpLoad %3 %75 -OpReturnValue %76 +%66 = OpLabel +OpBranch %71 +%71 = OpLabel +%72 = OpExtInst %6 %1 UMin %68 %35 +%73 = OpExtInst %6 %1 UMin %67 %62 +%74 = OpAccessChain %43 %12 %62 %73 %72 +%75 = OpLoad %3 %74 +OpReturnValue %75 OpFunctionEnd -%79 = OpFunction %3 None %18 -%78 = OpFunctionParameter %11 -%77 = OpLabel -OpBranch %81 -%81 = OpLabel -%82 = OpConvertSToF %3 %78 -%83 = OpFDiv %3 %82 %80 -%84 = OpExtInst %3 %1 Sin %83 -%85 = OpFMul %3 %84 %80 -%86 = OpConvertFToS %11 %85 -%87 = OpExtInst %6 %1 UMin %86 %22 -%88 = OpAccessChain %21 %13 %24 %87 -%89 = OpLoad %3 %88 -OpReturnValue %89 +%78 = OpFunction %3 None %17 +%77 = OpFunctionParameter %11 +%76 = OpLabel +OpBranch %80 +%80 = OpLabel +%81 = OpConvertSToF %3 %77 +%82 = OpFDiv %3 %81 %79 +%83 = OpExtInst %3 %1 Sin %82 +%84 = OpFMul %3 %83 %79 +%85 = OpConvertFToS %11 %84 +%86 = OpExtInst %6 %1 UMin %85 %21 +%87 = OpAccessChain %20 %12 %23 %86 +%88 = OpLoad %3 %87 +OpReturnValue %88 OpFunctionEnd -%91 = OpFunction %3 None %92 -%90 = OpLabel -OpBranch %93 -%93 = OpLabel -%94 = OpAccessChain %21 %13 %24 %22 -%95 = OpLoad %3 %94 -%96 = OpAccessChain %44 %13 %33 %36 -%97 = OpLoad %3 %96 -%98 = OpFAdd %3 %95 %97 -%99 = OpAccessChain %44 %13 %63 %63 %36 -%100 = OpLoad %3 %99 -%101 = OpFAdd %3 %98 %100 -OpReturnValue %101 +%90 = OpFunction %3 None %91 +%89 = OpLabel +OpBranch %92 +%92 = OpLabel +%93 = OpAccessChain %20 %12 %23 %21 +%94 = OpLoad %3 %93 +%95 = OpAccessChain %43 %12 %32 %35 +%96 = OpLoad %3 %95 +%97 = OpFAdd %3 %94 %96 +%98 = OpAccessChain %43 %12 %62 %62 %35 +%99 = OpLoad %3 %98 +%100 = OpFAdd %3 %97 %99 +OpReturnValue %100 OpFunctionEnd -%105 = OpFunction %2 None %106 -%103 = OpFunctionParameter %11 -%104 = OpFunctionParameter %3 -%102 = OpLabel -OpBranch %107 -%107 = OpLabel -%108 = OpExtInst %6 %1 UMin %103 %22 -%109 = OpAccessChain %21 %13 %24 %108 -OpStore %109 %104 +%104 = OpFunction %2 None %105 +%102 = OpFunctionParameter %11 +%103 = OpFunctionParameter %3 +%101 = OpLabel +OpBranch %106 +%106 = OpLabel +%107 = OpExtInst %6 %1 UMin %102 %21 +%108 = OpAccessChain %20 %12 %23 %107 +OpStore %108 %103 OpReturn OpFunctionEnd -%113 = OpFunction %2 None %106 -%111 = OpFunctionParameter %11 -%112 = OpFunctionParameter %3 -%110 = OpLabel -OpBranch %114 -%114 = OpLabel -%115 = OpArrayLength %6 %13 3 -%116 = OpISub %6 %115 %33 -%117 = OpExtInst %6 %1 UMin %111 %116 -%118 = OpAccessChain %21 %13 %36 %117 -OpStore %118 %112 +%112 = OpFunction %2 None %105 +%110 = OpFunctionParameter %11 +%111 = OpFunctionParameter %3 +%109 = OpLabel +OpBranch %113 +%113 = OpLabel +%114 = OpArrayLength %6 %12 3 +%115 = OpISub %6 %114 %32 +%116 = OpExtInst %6 %1 UMin %110 %115 +%117 = OpAccessChain %20 %12 %35 %116 +OpStore %117 %111 OpReturn OpFunctionEnd -%122 = OpFunction %2 None %106 -%120 = OpFunctionParameter %11 -%121 = OpFunctionParameter %3 -%119 = OpLabel -OpBranch %123 -%123 = OpLabel -%124 = OpExtInst %6 %1 UMin %120 %36 -%125 = OpAccessChain %44 %13 %33 %124 -OpStore %125 %121 +%121 = OpFunction %2 None %105 +%119 = OpFunctionParameter %11 +%120 = OpFunctionParameter %3 +%118 = OpLabel +OpBranch %122 +%122 = OpLabel +%123 = OpExtInst %6 %1 UMin %119 %35 +%124 = OpAccessChain %43 %12 %32 %123 +OpStore %124 %120 OpReturn OpFunctionEnd -%129 = OpFunction %2 None %130 -%127 = OpFunctionParameter %11 -%128 = OpFunctionParameter %7 -%126 = OpLabel -OpBranch %131 -%131 = OpLabel -%132 = OpExtInst %6 %1 UMin %127 %63 -%133 = OpAccessChain %62 %13 %63 %132 -OpStore %133 %128 +%128 = OpFunction %2 None %129 +%126 = OpFunctionParameter %11 +%127 = OpFunctionParameter %7 +%125 = OpLabel +OpBranch %130 +%130 = OpLabel +%131 = OpExtInst %6 %1 UMin %126 %62 +%132 = OpAccessChain %61 %12 %62 %131 +OpStore %132 %127 OpReturn OpFunctionEnd -%138 = OpFunction %2 None %139 +%137 = OpFunction %2 None %138 +%134 = OpFunctionParameter %11 %135 = OpFunctionParameter %11 -%136 = OpFunctionParameter %11 -%137 = OpFunctionParameter %3 -%134 = OpLabel -OpBranch %140 -%140 = OpLabel -%141 = OpExtInst %6 %1 UMin %136 %36 -%142 = OpExtInst %6 %1 UMin %135 %63 -%143 = OpAccessChain %44 %13 %63 %142 %141 -OpStore %143 %137 +%136 = OpFunctionParameter %3 +%133 = OpLabel +OpBranch %139 +%139 = OpLabel +%140 = OpExtInst %6 %1 UMin %135 %35 +%141 = OpExtInst %6 %1 UMin %134 %62 +%142 = OpAccessChain %43 %12 %62 %141 %140 +OpStore %142 %136 OpReturn OpFunctionEnd -%147 = OpFunction %2 None %106 -%145 = OpFunctionParameter %11 -%146 = OpFunctionParameter %3 -%144 = OpLabel -OpBranch %148 -%148 = OpLabel -%149 = OpConvertSToF %3 %145 -%150 = OpFDiv %3 %149 %80 -%151 = OpExtInst %3 %1 Sin %150 -%152 = OpFMul %3 %151 %80 -%153 = OpConvertFToS %11 %152 -%154 = OpExtInst %6 %1 UMin %153 %22 -%155 = OpAccessChain %21 %13 %24 %154 -OpStore %155 %146 +%146 = OpFunction %2 None %105 +%144 = OpFunctionParameter %11 +%145 = OpFunctionParameter %3 +%143 = OpLabel +OpBranch %147 +%147 = OpLabel +%148 = OpConvertSToF %3 %144 +%149 = OpFDiv %3 %148 %79 +%150 = OpExtInst %3 %1 Sin %149 +%151 = OpFMul %3 %150 %79 +%152 = OpConvertFToS %11 %151 +%153 = OpExtInst %6 %1 UMin %152 %21 +%154 = OpAccessChain %20 %12 %23 %153 +OpStore %154 %145 OpReturn OpFunctionEnd -%158 = OpFunction %2 None %159 -%157 = OpFunctionParameter %3 -%156 = OpLabel -OpBranch %160 -%160 = OpLabel -%161 = OpAccessChain %21 %13 %24 %22 -OpStore %161 %157 -%162 = OpAccessChain %44 %13 %33 %36 -OpStore %162 %157 -%163 = OpAccessChain %44 %13 %63 %63 %36 -OpStore %163 %157 +%157 = OpFunction %2 None %158 +%156 = OpFunctionParameter %3 +%155 = OpLabel +OpBranch %159 +%159 = OpLabel +%160 = OpAccessChain %20 %12 %23 %21 +OpStore %160 %156 +%161 = OpAccessChain %43 %12 %32 %35 +OpStore %161 %156 +%162 = OpAccessChain %43 %12 %62 %62 %35 +OpStore %162 %156 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm index f24ab2cc7..2bb81261e 100644 --- a/tests/out/spv/bounds-check-zero.spvasm +++ b/tests/out/spv/bounds-check-zero.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 201 +; Bound: 200 OpCapability Shader OpCapability Linkage OpExtension "SPV_KHR_storage_buffer_storage_class" @@ -16,8 +16,8 @@ OpMemberDecorate %10 2 ColMajor OpMemberDecorate %10 2 MatrixStride 16 OpMemberDecorate %10 3 Offset 112 OpDecorate %10 Block -OpDecorate %13 DescriptorSet 0 -OpDecorate %13 Binding 0 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 0 %2 = OpTypeVoid %3 = OpTypeFloat 32 %6 = OpTypeInt 32 0 @@ -28,285 +28,284 @@ OpDecorate %13 Binding 0 %9 = OpTypeRuntimeArray %3 %10 = OpTypeStruct %4 %7 %8 %9 %11 = OpTypeInt 32 1 -%12 = OpConstant %11 10 -%14 = OpTypePointer StorageBuffer %10 -%13 = OpVariable %14 StorageBuffer -%18 = OpTypeFunction %3 %11 -%20 = OpTypePointer StorageBuffer %4 -%21 = OpTypePointer StorageBuffer %3 -%23 = OpTypeBool -%24 = OpConstant %6 0 -%26 = OpConstantNull %3 -%35 = OpTypePointer StorageBuffer %9 -%38 = OpConstant %6 3 -%48 = OpTypePointer StorageBuffer %7 -%49 = OpTypePointer StorageBuffer %3 -%50 = OpConstant %6 4 -%52 = OpConstant %6 1 -%62 = OpTypeFunction %3 %7 %11 -%72 = OpTypeFunction %7 %11 -%74 = OpTypePointer StorageBuffer %8 -%75 = OpTypePointer StorageBuffer %7 -%77 = OpConstant %6 2 -%79 = OpConstantNull %7 -%88 = OpTypeFunction %3 %11 %11 -%101 = OpConstant %3 100.0 -%116 = OpTypeFunction %3 -%118 = OpConstant %6 9 -%131 = OpTypeFunction %2 %11 %3 -%160 = OpTypeFunction %2 %11 %7 -%171 = OpTypeFunction %2 %11 %11 %3 -%196 = OpTypeFunction %2 %3 -%17 = OpFunction %3 None %18 -%16 = OpFunctionParameter %11 -%15 = OpLabel -OpBranch %19 -%19 = OpLabel -%22 = OpULessThan %23 %16 %5 -OpSelectionMerge %27 None -OpBranchConditional %22 %28 %27 -%28 = OpLabel -%25 = OpAccessChain %21 %13 %24 %16 -%29 = OpLoad %3 %25 -OpBranch %27 +%13 = OpTypePointer StorageBuffer %10 +%12 = OpVariable %13 StorageBuffer +%17 = OpTypeFunction %3 %11 +%19 = OpTypePointer StorageBuffer %4 +%20 = OpTypePointer StorageBuffer %3 +%22 = OpTypeBool +%23 = OpConstant %6 0 +%25 = OpConstantNull %3 +%34 = OpTypePointer StorageBuffer %9 +%37 = OpConstant %6 3 +%47 = OpTypePointer StorageBuffer %7 +%48 = OpTypePointer StorageBuffer %3 +%49 = OpConstant %6 4 +%51 = OpConstant %6 1 +%61 = OpTypeFunction %3 %7 %11 +%71 = OpTypeFunction %7 %11 +%73 = OpTypePointer StorageBuffer %8 +%74 = OpTypePointer StorageBuffer %7 +%76 = OpConstant %6 2 +%78 = OpConstantNull %7 +%87 = OpTypeFunction %3 %11 %11 +%100 = OpConstant %3 100.0 +%115 = OpTypeFunction %3 +%117 = OpConstant %6 9 +%130 = OpTypeFunction %2 %11 %3 +%159 = OpTypeFunction %2 %11 %7 +%170 = OpTypeFunction %2 %11 %11 %3 +%195 = OpTypeFunction %2 %3 +%16 = OpFunction %3 None %17 +%15 = OpFunctionParameter %11 +%14 = OpLabel +OpBranch %18 +%18 = OpLabel +%21 = OpULessThan %22 %15 %5 +OpSelectionMerge %26 None +OpBranchConditional %21 %27 %26 %27 = OpLabel -%30 = OpPhi %3 %26 %19 %29 %28 -OpReturnValue %30 +%24 = OpAccessChain %20 %12 %23 %15 +%28 = OpLoad %3 %24 +OpBranch %26 +%26 = OpLabel +%29 = OpPhi %3 %25 %18 %28 %27 +OpReturnValue %29 OpFunctionEnd -%33 = OpFunction %3 None %18 -%32 = OpFunctionParameter %11 -%31 = OpLabel -OpBranch %34 -%34 = OpLabel -%36 = OpArrayLength %6 %13 3 -%37 = OpULessThan %23 %32 %36 -OpSelectionMerge %40 None -OpBranchConditional %37 %41 %40 -%41 = OpLabel -%39 = OpAccessChain %21 %13 %38 %32 -%42 = OpLoad %3 %39 -OpBranch %40 +%32 = OpFunction %3 None %17 +%31 = OpFunctionParameter %11 +%30 = OpLabel +OpBranch %33 +%33 = OpLabel +%35 = OpArrayLength %6 %12 3 +%36 = OpULessThan %22 %31 %35 +OpSelectionMerge %39 None +OpBranchConditional %36 %40 %39 %40 = OpLabel -%43 = OpPhi %3 %26 %34 %42 %41 -OpReturnValue %43 +%38 = OpAccessChain %20 %12 %37 %31 +%41 = OpLoad %3 %38 +OpBranch %39 +%39 = OpLabel +%42 = OpPhi %3 %25 %33 %41 %40 +OpReturnValue %42 OpFunctionEnd -%46 = OpFunction %3 None %18 -%45 = OpFunctionParameter %11 -%44 = OpLabel -OpBranch %47 -%47 = OpLabel -%51 = OpULessThan %23 %45 %50 -OpSelectionMerge %54 None -OpBranchConditional %51 %55 %54 -%55 = OpLabel -%53 = OpAccessChain %49 %13 %52 %45 -%56 = OpLoad %3 %53 -OpBranch %54 +%45 = OpFunction %3 None %17 +%44 = OpFunctionParameter %11 +%43 = OpLabel +OpBranch %46 +%46 = OpLabel +%50 = OpULessThan %22 %44 %49 +OpSelectionMerge %53 None +OpBranchConditional %50 %54 %53 %54 = OpLabel -%57 = OpPhi %3 %26 %47 %56 %55 -OpReturnValue %57 +%52 = OpAccessChain %48 %12 %51 %44 +%55 = OpLoad %3 %52 +OpBranch %53 +%53 = OpLabel +%56 = OpPhi %3 %25 %46 %55 %54 +OpReturnValue %56 OpFunctionEnd -%61 = OpFunction %3 None %62 -%59 = OpFunctionParameter %7 -%60 = OpFunctionParameter %11 -%58 = OpLabel -OpBranch %63 -%63 = OpLabel -%64 = OpULessThan %23 %60 %50 -OpSelectionMerge %65 None -OpBranchConditional %64 %66 %65 -%66 = OpLabel -%67 = OpVectorExtractDynamic %3 %59 %60 -OpBranch %65 +%60 = OpFunction %3 None %61 +%58 = OpFunctionParameter %7 +%59 = OpFunctionParameter %11 +%57 = OpLabel +OpBranch %62 +%62 = OpLabel +%63 = OpULessThan %22 %59 %49 +OpSelectionMerge %64 None +OpBranchConditional %63 %65 %64 %65 = OpLabel -%68 = OpPhi %3 %26 %63 %67 %66 -OpReturnValue %68 +%66 = OpVectorExtractDynamic %3 %58 %59 +OpBranch %64 +%64 = OpLabel +%67 = OpPhi %3 %25 %62 %66 %65 +OpReturnValue %67 OpFunctionEnd -%71 = OpFunction %7 None %72 -%70 = OpFunctionParameter %11 -%69 = OpLabel -OpBranch %73 -%73 = OpLabel -%76 = OpULessThan %23 %70 %38 -OpSelectionMerge %80 None -OpBranchConditional %76 %81 %80 -%81 = OpLabel -%78 = OpAccessChain %75 %13 %77 %70 -%82 = OpLoad %7 %78 -OpBranch %80 +%70 = OpFunction %7 None %71 +%69 = OpFunctionParameter %11 +%68 = OpLabel +OpBranch %72 +%72 = OpLabel +%75 = OpULessThan %22 %69 %37 +OpSelectionMerge %79 None +OpBranchConditional %75 %80 %79 %80 = OpLabel -%83 = OpPhi %7 %79 %73 %82 %81 -OpReturnValue %83 +%77 = OpAccessChain %74 %12 %76 %69 +%81 = OpLoad %7 %77 +OpBranch %79 +%79 = OpLabel +%82 = OpPhi %7 %78 %72 %81 %80 +OpReturnValue %82 OpFunctionEnd -%87 = OpFunction %3 None %88 +%86 = OpFunction %3 None %87 +%84 = OpFunctionParameter %11 %85 = OpFunctionParameter %11 -%86 = OpFunctionParameter %11 -%84 = OpLabel -OpBranch %89 -%89 = OpLabel -%90 = OpULessThan %23 %86 %50 -%91 = OpULessThan %23 %85 %38 -%92 = OpLogicalAnd %23 %90 %91 -OpSelectionMerge %94 None -OpBranchConditional %92 %95 %94 -%95 = OpLabel -%93 = OpAccessChain %49 %13 %77 %85 %86 -%96 = OpLoad %3 %93 -OpBranch %94 +%83 = OpLabel +OpBranch %88 +%88 = OpLabel +%89 = OpULessThan %22 %85 %49 +%90 = OpULessThan %22 %84 %37 +%91 = OpLogicalAnd %22 %89 %90 +OpSelectionMerge %93 None +OpBranchConditional %91 %94 %93 %94 = OpLabel -%97 = OpPhi %3 %26 %89 %96 %95 -OpReturnValue %97 +%92 = OpAccessChain %48 %12 %76 %84 %85 +%95 = OpLoad %3 %92 +OpBranch %93 +%93 = OpLabel +%96 = OpPhi %3 %25 %88 %95 %94 +OpReturnValue %96 OpFunctionEnd -%100 = OpFunction %3 None %18 -%99 = OpFunctionParameter %11 -%98 = OpLabel -OpBranch %102 -%102 = OpLabel -%103 = OpConvertSToF %3 %99 -%104 = OpFDiv %3 %103 %101 -%105 = OpExtInst %3 %1 Sin %104 -%106 = OpFMul %3 %105 %101 -%107 = OpConvertFToS %11 %106 -%108 = OpULessThan %23 %107 %5 -OpSelectionMerge %110 None -OpBranchConditional %108 %111 %110 -%111 = OpLabel -%109 = OpAccessChain %21 %13 %24 %107 -%112 = OpLoad %3 %109 -OpBranch %110 +%99 = OpFunction %3 None %17 +%98 = OpFunctionParameter %11 +%97 = OpLabel +OpBranch %101 +%101 = OpLabel +%102 = OpConvertSToF %3 %98 +%103 = OpFDiv %3 %102 %100 +%104 = OpExtInst %3 %1 Sin %103 +%105 = OpFMul %3 %104 %100 +%106 = OpConvertFToS %11 %105 +%107 = OpULessThan %22 %106 %5 +OpSelectionMerge %109 None +OpBranchConditional %107 %110 %109 %110 = OpLabel -%113 = OpPhi %3 %26 %102 %112 %111 -OpReturnValue %113 +%108 = OpAccessChain %20 %12 %23 %106 +%111 = OpLoad %3 %108 +OpBranch %109 +%109 = OpLabel +%112 = OpPhi %3 %25 %101 %111 %110 +OpReturnValue %112 OpFunctionEnd -%115 = OpFunction %3 None %116 -%114 = OpLabel -OpBranch %117 -%117 = OpLabel -%119 = OpAccessChain %21 %13 %24 %118 -%120 = OpLoad %3 %119 -%121 = OpAccessChain %49 %13 %52 %38 -%122 = OpLoad %3 %121 -%123 = OpFAdd %3 %120 %122 -%124 = OpAccessChain %49 %13 %77 %77 %38 -%125 = OpLoad %3 %124 -%126 = OpFAdd %3 %123 %125 -OpReturnValue %126 +%114 = OpFunction %3 None %115 +%113 = OpLabel +OpBranch %116 +%116 = OpLabel +%118 = OpAccessChain %20 %12 %23 %117 +%119 = OpLoad %3 %118 +%120 = OpAccessChain %48 %12 %51 %37 +%121 = OpLoad %3 %120 +%122 = OpFAdd %3 %119 %121 +%123 = OpAccessChain %48 %12 %76 %76 %37 +%124 = OpLoad %3 %123 +%125 = OpFAdd %3 %122 %124 +OpReturnValue %125 OpFunctionEnd -%130 = OpFunction %2 None %131 -%128 = OpFunctionParameter %11 -%129 = OpFunctionParameter %3 -%127 = OpLabel -OpBranch %132 -%132 = OpLabel -%133 = OpULessThan %23 %128 %5 -OpSelectionMerge %135 None -OpBranchConditional %133 %136 %135 -%136 = OpLabel -%134 = OpAccessChain %21 %13 %24 %128 -OpStore %134 %129 -OpBranch %135 +%129 = OpFunction %2 None %130 +%127 = OpFunctionParameter %11 +%128 = OpFunctionParameter %3 +%126 = OpLabel +OpBranch %131 +%131 = OpLabel +%132 = OpULessThan %22 %127 %5 +OpSelectionMerge %134 None +OpBranchConditional %132 %135 %134 %135 = OpLabel +%133 = OpAccessChain %20 %12 %23 %127 +OpStore %133 %128 +OpBranch %134 +%134 = OpLabel OpReturn OpFunctionEnd -%140 = OpFunction %2 None %131 -%138 = OpFunctionParameter %11 -%139 = OpFunctionParameter %3 -%137 = OpLabel -OpBranch %141 -%141 = OpLabel -%142 = OpArrayLength %6 %13 3 -%143 = OpULessThan %23 %138 %142 -OpSelectionMerge %145 None -OpBranchConditional %143 %146 %145 -%146 = OpLabel -%144 = OpAccessChain %21 %13 %38 %138 -OpStore %144 %139 -OpBranch %145 +%139 = OpFunction %2 None %130 +%137 = OpFunctionParameter %11 +%138 = OpFunctionParameter %3 +%136 = OpLabel +OpBranch %140 +%140 = OpLabel +%141 = OpArrayLength %6 %12 3 +%142 = OpULessThan %22 %137 %141 +OpSelectionMerge %144 None +OpBranchConditional %142 %145 %144 %145 = OpLabel +%143 = OpAccessChain %20 %12 %37 %137 +OpStore %143 %138 +OpBranch %144 +%144 = OpLabel OpReturn OpFunctionEnd -%150 = OpFunction %2 None %131 -%148 = OpFunctionParameter %11 -%149 = OpFunctionParameter %3 -%147 = OpLabel -OpBranch %151 -%151 = OpLabel -%152 = OpULessThan %23 %148 %50 -OpSelectionMerge %154 None -OpBranchConditional %152 %155 %154 -%155 = OpLabel -%153 = OpAccessChain %49 %13 %52 %148 -OpStore %153 %149 -OpBranch %154 +%149 = OpFunction %2 None %130 +%147 = OpFunctionParameter %11 +%148 = OpFunctionParameter %3 +%146 = OpLabel +OpBranch %150 +%150 = OpLabel +%151 = OpULessThan %22 %147 %49 +OpSelectionMerge %153 None +OpBranchConditional %151 %154 %153 %154 = OpLabel +%152 = OpAccessChain %48 %12 %51 %147 +OpStore %152 %148 +OpBranch %153 +%153 = OpLabel OpReturn OpFunctionEnd -%159 = OpFunction %2 None %160 -%157 = OpFunctionParameter %11 -%158 = OpFunctionParameter %7 -%156 = OpLabel -OpBranch %161 -%161 = OpLabel -%162 = OpULessThan %23 %157 %38 -OpSelectionMerge %164 None -OpBranchConditional %162 %165 %164 -%165 = OpLabel -%163 = OpAccessChain %75 %13 %77 %157 -OpStore %163 %158 -OpBranch %164 +%158 = OpFunction %2 None %159 +%156 = OpFunctionParameter %11 +%157 = OpFunctionParameter %7 +%155 = OpLabel +OpBranch %160 +%160 = OpLabel +%161 = OpULessThan %22 %156 %37 +OpSelectionMerge %163 None +OpBranchConditional %161 %164 %163 %164 = OpLabel +%162 = OpAccessChain %74 %12 %76 %156 +OpStore %162 %157 +OpBranch %163 +%163 = OpLabel OpReturn OpFunctionEnd -%170 = OpFunction %2 None %171 +%169 = OpFunction %2 None %170 +%166 = OpFunctionParameter %11 %167 = OpFunctionParameter %11 -%168 = OpFunctionParameter %11 -%169 = OpFunctionParameter %3 -%166 = OpLabel -OpBranch %172 -%172 = OpLabel -%173 = OpULessThan %23 %168 %50 -%174 = OpULessThan %23 %167 %38 -%175 = OpLogicalAnd %23 %173 %174 -OpSelectionMerge %177 None -OpBranchConditional %175 %178 %177 -%178 = OpLabel -%176 = OpAccessChain %49 %13 %77 %167 %168 -OpStore %176 %169 -OpBranch %177 +%168 = OpFunctionParameter %3 +%165 = OpLabel +OpBranch %171 +%171 = OpLabel +%172 = OpULessThan %22 %167 %49 +%173 = OpULessThan %22 %166 %37 +%174 = OpLogicalAnd %22 %172 %173 +OpSelectionMerge %176 None +OpBranchConditional %174 %177 %176 %177 = OpLabel +%175 = OpAccessChain %48 %12 %76 %166 %167 +OpStore %175 %168 +OpBranch %176 +%176 = OpLabel OpReturn OpFunctionEnd -%182 = OpFunction %2 None %131 -%180 = OpFunctionParameter %11 -%181 = OpFunctionParameter %3 -%179 = OpLabel -OpBranch %183 -%183 = OpLabel -%184 = OpConvertSToF %3 %180 -%185 = OpFDiv %3 %184 %101 -%186 = OpExtInst %3 %1 Sin %185 -%187 = OpFMul %3 %186 %101 -%188 = OpConvertFToS %11 %187 -%189 = OpULessThan %23 %188 %5 -OpSelectionMerge %191 None -OpBranchConditional %189 %192 %191 -%192 = OpLabel -%190 = OpAccessChain %21 %13 %24 %188 -OpStore %190 %181 -OpBranch %191 +%181 = OpFunction %2 None %130 +%179 = OpFunctionParameter %11 +%180 = OpFunctionParameter %3 +%178 = OpLabel +OpBranch %182 +%182 = OpLabel +%183 = OpConvertSToF %3 %179 +%184 = OpFDiv %3 %183 %100 +%185 = OpExtInst %3 %1 Sin %184 +%186 = OpFMul %3 %185 %100 +%187 = OpConvertFToS %11 %186 +%188 = OpULessThan %22 %187 %5 +OpSelectionMerge %190 None +OpBranchConditional %188 %191 %190 %191 = OpLabel +%189 = OpAccessChain %20 %12 %23 %187 +OpStore %189 %180 +OpBranch %190 +%190 = OpLabel OpReturn OpFunctionEnd -%195 = OpFunction %2 None %196 -%194 = OpFunctionParameter %3 -%193 = OpLabel -OpBranch %197 -%197 = OpLabel -%198 = OpAccessChain %21 %13 %24 %118 -OpStore %198 %194 -%199 = OpAccessChain %49 %13 %52 %38 -OpStore %199 %194 -%200 = OpAccessChain %49 %13 %77 %77 %38 -OpStore %200 %194 +%194 = OpFunction %2 None %195 +%193 = OpFunctionParameter %3 +%192 = OpLabel +OpBranch %196 +%196 = OpLabel +%197 = OpAccessChain %20 %12 %23 %117 +OpStore %197 %193 +%198 = OpAccessChain %48 %12 %51 %37 +OpStore %198 %193 +%199 = OpAccessChain %48 %12 %76 %76 %37 +OpStore %199 %193 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/constructors.spvasm b/tests/out/spv/constructors.spvasm index f52bd338c..ec54d6d1b 100644 --- a/tests/out/spv/constructors.spvasm +++ b/tests/out/spv/constructors.spvasm @@ -39,31 +39,31 @@ OpDecorate %17 ArrayStride 4 %26 = OpConstantComposite %9 %21 %22 %27 = OpConstantComposite %9 %23 %25 %28 = OpConstantComposite %8 %26 %27 -%29 = OpConstant %5 1 -%30 = OpConstantComposite %10 %28 -%31 = OpConstantNull %13 -%32 = OpConstantNull %5 -%33 = OpConstantNull %12 -%34 = OpConstantNull %4 -%35 = OpConstantNull %14 -%36 = OpConstantNull %8 -%37 = OpConstant %5 3 -%38 = OpConstantNull %15 -%39 = OpConstantNull %6 -%40 = OpConstant %5 0 -%41 = OpConstant %5 2 -%42 = OpConstantComposite %17 %40 %29 %41 %37 +%29 = OpConstantComposite %10 %28 +%30 = OpConstantNull %13 +%31 = OpConstantNull %5 +%32 = OpConstantNull %12 +%33 = OpConstantNull %4 +%34 = OpConstantNull %14 +%35 = OpConstantNull %8 +%36 = OpConstantNull %15 +%37 = OpConstantNull %6 +%38 = OpConstant %5 0 +%39 = OpConstant %5 1 +%40 = OpConstant %5 2 +%41 = OpConstant %5 3 +%42 = OpConstantComposite %17 %38 %39 %40 %41 %44 = OpTypePointer Function %6 %47 = OpTypeFunction %2 %48 = OpConstant %12 0 %49 = OpConstantNull %20 %46 = OpFunction %2 None %47 %45 = OpLabel -%43 = OpVariable %44 Function %39 +%43 = OpVariable %44 Function %37 OpBranch %50 %50 = OpLabel %51 = OpCompositeConstruct %3 %22 %22 %22 %22 -%52 = OpCompositeConstruct %6 %51 %29 +%52 = OpCompositeConstruct %6 %51 %39 OpStore %43 %52 %53 = OpCompositeConstruct %9 %22 %21 %54 = OpCompositeConstruct %9 %21 %22 @@ -77,7 +77,7 @@ OpStore %43 %52 %62 = OpCompositeConstruct %9 %21 %21 %63 = OpCompositeConstruct %9 %21 %21 %64 = OpCompositeConstruct %8 %62 %63 -%65 = OpCompositeConstruct %17 %40 %29 %41 %37 +%65 = OpCompositeConstruct %17 %38 %39 %40 %41 %71 = OpCopyObject %20 %49 %73 = OpCopyObject %20 %49 OpReturn diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index 16b9b750c..93de9e8d9 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -7,18 +7,18 @@ OpCapability Float64 OpCapability Geometry %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %24 "main" %16 %19 %22 -OpExecutionMode %24 OriginUpperLeft +OpEntryPoint Fragment %23 "main" %15 %18 %21 +OpExecutionMode %23 OriginUpperLeft OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 16 -OpDecorate %12 Block -OpMemberDecorate %12 0 Offset 0 -OpDecorate %16 Location 0 -OpDecorate %19 BuiltIn PrimitiveId -OpDecorate %19 Flat -OpDecorate %22 Location 0 +OpDecorate %11 Block +OpMemberDecorate %11 0 Offset 0 +OpDecorate %15 Location 0 +OpDecorate %18 BuiltIn PrimitiveId +OpDecorate %18 Flat +OpDecorate %21 Location 0 %2 = OpTypeVoid %3 = OpTypeInt 32 0 %5 = OpTypeFloat 64 @@ -27,50 +27,50 @@ OpDecorate %22 Location 0 %8 = OpTypeFloat 32 %7 = OpTypeVector %8 4 %9 = OpTypeStruct %7 %3 -%10 = OpTypeVector %8 3 -%12 = OpTypeStruct %6 -%13 = OpTypePointer PushConstant %12 -%11 = OpVariable %13 PushConstant -%17 = OpTypePointer Input %7 -%16 = OpVariable %17 Input -%20 = OpTypePointer Input %3 -%19 = OpVariable %20 Input -%23 = OpTypePointer Output %7 -%22 = OpVariable %23 Output -%25 = OpTypeFunction %2 -%26 = OpTypePointer PushConstant %6 -%27 = OpConstant %3 0 -%29 = OpConstant %8 1.0 -%32 = OpTypePointer PushConstant %3 -%35 = OpTypeBool -%24 = OpFunction %2 None %25 -%14 = OpLabel -%18 = OpLoad %7 %16 -%21 = OpLoad %3 %19 -%15 = OpCompositeConstruct %9 %18 %21 -%28 = OpAccessChain %26 %11 %27 -OpBranch %30 -%30 = OpLabel -%31 = OpCompositeExtract %3 %15 1 -%33 = OpAccessChain %32 %28 %27 -%34 = OpLoad %3 %33 -%36 = OpIEqual %35 %31 %34 -OpSelectionMerge %37 None -OpBranchConditional %36 %38 %39 -%38 = OpLabel -%40 = OpCompositeExtract %7 %15 0 -OpStore %22 %40 +%11 = OpTypeStruct %6 +%12 = OpTypePointer PushConstant %11 +%10 = OpVariable %12 PushConstant +%16 = OpTypePointer Input %7 +%15 = OpVariable %16 Input +%19 = OpTypePointer Input %3 +%18 = OpVariable %19 Input +%22 = OpTypePointer Output %7 +%21 = OpVariable %22 Output +%24 = OpTypeFunction %2 +%25 = OpTypePointer PushConstant %6 +%26 = OpConstant %3 0 +%28 = OpConstant %8 1.0 +%31 = OpTypePointer PushConstant %3 +%34 = OpTypeBool +%40 = OpTypeVector %8 3 +%23 = OpFunction %2 None %24 +%13 = OpLabel +%17 = OpLoad %7 %15 +%20 = OpLoad %3 %18 +%14 = OpCompositeConstruct %9 %17 %20 +%27 = OpAccessChain %25 %10 %26 +OpBranch %29 +%29 = OpLabel +%30 = OpCompositeExtract %3 %14 1 +%32 = OpAccessChain %31 %27 %26 +%33 = OpLoad %3 %32 +%35 = OpIEqual %34 %30 %33 +OpSelectionMerge %36 None +OpBranchConditional %35 %37 %38 +%37 = OpLabel +%39 = OpCompositeExtract %7 %14 0 +OpStore %21 %39 OpReturn -%39 = OpLabel -%41 = OpCompositeConstruct %10 %29 %29 %29 -%42 = OpCompositeExtract %7 %15 0 -%43 = OpVectorShuffle %10 %42 %42 0 1 2 -%44 = OpFSub %10 %41 %43 -%45 = OpCompositeExtract %7 %15 0 +%38 = OpLabel +%41 = OpCompositeConstruct %40 %28 %28 %28 +%42 = OpCompositeExtract %7 %14 0 +%43 = OpVectorShuffle %40 %42 %42 0 1 2 +%44 = OpFSub %40 %41 %43 +%45 = OpCompositeExtract %7 %14 0 %46 = OpCompositeExtract %8 %45 3 %47 = OpCompositeConstruct %7 %44 %46 -OpStore %22 %47 +OpStore %21 %47 OpReturn -%37 = OpLabel +%36 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/functions.spvasm b/tests/out/spv/functions.spvasm index f114e2970..a7338a932 100644 --- a/tests/out/spv/functions.spvasm +++ b/tests/out/spv/functions.spvasm @@ -11,65 +11,65 @@ OpExecutionMode %73 LocalSize 1 1 1 %4 = OpTypeFloat 32 %3 = OpTypeVector %4 2 %5 = OpTypeInt 32 1 -%6 = OpTypeVector %5 2 -%8 = OpTypeInt 32 0 -%7 = OpTypeVector %8 3 -%9 = OpTypeVector %5 4 -%12 = OpTypeFunction %3 -%13 = OpConstant %4 2.0 -%14 = OpConstant %4 0.5 -%22 = OpTypeFunction %5 -%23 = OpConstant %5 1 -%24 = OpConstant %8 1 -%25 = OpConstant %5 4 -%26 = OpConstant %5 2 -%31 = OpConstantNull %5 -%42 = OpConstantNull %8 +%8 = OpTypeFunction %3 +%9 = OpConstant %4 2.0 +%10 = OpConstant %4 0.5 +%18 = OpTypeFunction %5 +%19 = OpConstant %5 1 +%20 = OpTypeInt 32 0 +%21 = OpConstant %20 1 +%22 = OpConstant %5 4 +%23 = OpConstant %5 2 +%25 = OpTypeVector %5 2 +%29 = OpConstantNull %5 +%37 = OpTypeVector %20 3 +%41 = OpConstantNull %20 +%53 = OpTypeVector %5 4 %74 = OpTypeFunction %2 -%11 = OpFunction %3 None %12 -%10 = OpLabel -OpBranch %15 -%15 = OpLabel -%16 = OpCompositeConstruct %3 %13 %13 -%17 = OpCompositeConstruct %3 %14 %14 -%18 = OpCompositeConstruct %3 %14 %14 -%19 = OpExtInst %3 %1 Fma %16 %17 %18 -OpReturnValue %19 +%7 = OpFunction %3 None %8 +%6 = OpLabel +OpBranch %11 +%11 = OpLabel +%12 = OpCompositeConstruct %3 %9 %9 +%13 = OpCompositeConstruct %3 %10 %10 +%14 = OpCompositeConstruct %3 %10 %10 +%15 = OpExtInst %3 %1 Fma %12 %13 %14 +OpReturnValue %15 OpFunctionEnd -%21 = OpFunction %5 None %22 -%20 = OpLabel -OpBranch %27 -%27 = OpLabel -%28 = OpCompositeConstruct %6 %23 %23 -%29 = OpCompositeConstruct %6 %23 %23 -%32 = OpCompositeExtract %5 %28 0 -%33 = OpCompositeExtract %5 %29 0 -%34 = OpIMul %5 %32 %33 -%35 = OpIAdd %5 %31 %34 -%36 = OpCompositeExtract %5 %28 1 -%37 = OpCompositeExtract %5 %29 1 -%38 = OpIMul %5 %36 %37 -%30 = OpIAdd %5 %35 %38 -%39 = OpCompositeConstruct %7 %24 %24 %24 -%40 = OpCompositeConstruct %7 %24 %24 %24 -%43 = OpCompositeExtract %8 %39 0 -%44 = OpCompositeExtract %8 %40 0 -%45 = OpIMul %8 %43 %44 -%46 = OpIAdd %8 %42 %45 -%47 = OpCompositeExtract %8 %39 1 -%48 = OpCompositeExtract %8 %40 1 -%49 = OpIMul %8 %47 %48 -%50 = OpIAdd %8 %46 %49 -%51 = OpCompositeExtract %8 %39 2 -%52 = OpCompositeExtract %8 %40 2 -%53 = OpIMul %8 %51 %52 -%41 = OpIAdd %8 %50 %53 -%54 = OpCompositeConstruct %9 %25 %25 %25 %25 -%55 = OpCompositeConstruct %9 %26 %26 %26 %26 +%17 = OpFunction %5 None %18 +%16 = OpLabel +OpBranch %24 +%24 = OpLabel +%26 = OpCompositeConstruct %25 %19 %19 +%27 = OpCompositeConstruct %25 %19 %19 +%30 = OpCompositeExtract %5 %26 0 +%31 = OpCompositeExtract %5 %27 0 +%32 = OpIMul %5 %30 %31 +%33 = OpIAdd %5 %29 %32 +%34 = OpCompositeExtract %5 %26 1 +%35 = OpCompositeExtract %5 %27 1 +%36 = OpIMul %5 %34 %35 +%28 = OpIAdd %5 %33 %36 +%38 = OpCompositeConstruct %37 %21 %21 %21 +%39 = OpCompositeConstruct %37 %21 %21 %21 +%42 = OpCompositeExtract %20 %38 0 +%43 = OpCompositeExtract %20 %39 0 +%44 = OpIMul %20 %42 %43 +%45 = OpIAdd %20 %41 %44 +%46 = OpCompositeExtract %20 %38 1 +%47 = OpCompositeExtract %20 %39 1 +%48 = OpIMul %20 %46 %47 +%49 = OpIAdd %20 %45 %48 +%50 = OpCompositeExtract %20 %38 2 +%51 = OpCompositeExtract %20 %39 2 +%52 = OpIMul %20 %50 %51 +%40 = OpIAdd %20 %49 %52 +%54 = OpCompositeConstruct %53 %22 %22 %22 %22 +%55 = OpCompositeConstruct %53 %23 %23 %23 %23 %57 = OpCompositeExtract %5 %54 0 %58 = OpCompositeExtract %5 %55 0 %59 = OpIMul %5 %57 %58 -%60 = OpIAdd %5 %31 %59 +%60 = OpIAdd %5 %29 %59 %61 = OpCompositeExtract %5 %54 1 %62 = OpCompositeExtract %5 %55 1 %63 = OpIMul %5 %61 %62 @@ -88,7 +88,7 @@ OpFunctionEnd %72 = OpLabel OpBranch %75 %75 = OpLabel -%76 = OpFunctionCall %3 %11 -%77 = OpFunctionCall %5 %21 +%76 = OpFunctionCall %3 %7 +%77 = OpFunctionCall %5 %17 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 015195c73..9050f944b 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 178 +; Bound: 177 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %102 "main" %121 -OpExecutionMode %102 LocalSize 1 1 1 +OpEntryPoint GLCompute %100 "main" %119 +OpExecutionMode %100 LocalSize 1 1 1 OpDecorate %5 ArrayStride 4 OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 12 @@ -17,38 +17,38 @@ OpDecorate %17 ArrayStride 32 OpDecorate %19 ArrayStride 64 OpDecorate %21 ArrayStride 32 OpDecorate %22 ArrayStride 64 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 1 -OpDecorate %33 Block -OpMemberDecorate %33 0 Offset 0 -OpDecorate %35 NonWritable -OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 2 -OpDecorate %36 Block -OpMemberDecorate %36 0 Offset 0 -OpDecorate %38 DescriptorSet 0 -OpDecorate %38 Binding 3 -OpDecorate %39 Block -OpMemberDecorate %39 0 Offset 0 -OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 4 -OpDecorate %42 Block -OpMemberDecorate %42 0 Offset 0 -OpDecorate %44 DescriptorSet 0 -OpDecorate %44 Binding 5 -OpDecorate %45 Block -OpMemberDecorate %45 0 Offset 0 -OpMemberDecorate %45 0 ColMajor -OpMemberDecorate %45 0 MatrixStride 8 -OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 6 -OpDecorate %48 Block -OpMemberDecorate %48 0 Offset 0 -OpDecorate %50 DescriptorSet 0 -OpDecorate %50 Binding 7 -OpDecorate %51 Block -OpMemberDecorate %51 0 Offset 0 -OpDecorate %121 BuiltIn LocalInvocationId +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 1 +OpDecorate %31 Block +OpMemberDecorate %31 0 Offset 0 +OpDecorate %33 NonWritable +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 2 +OpDecorate %34 Block +OpMemberDecorate %34 0 Offset 0 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 3 +OpDecorate %37 Block +OpMemberDecorate %37 0 Offset 0 +OpDecorate %39 DescriptorSet 0 +OpDecorate %39 Binding 4 +OpDecorate %40 Block +OpMemberDecorate %40 0 Offset 0 +OpDecorate %42 DescriptorSet 0 +OpDecorate %42 Binding 5 +OpDecorate %43 Block +OpMemberDecorate %43 0 Offset 0 +OpMemberDecorate %43 0 ColMajor +OpMemberDecorate %43 0 MatrixStride 8 +OpDecorate %45 DescriptorSet 0 +OpDecorate %45 Binding 6 +OpDecorate %46 Block +OpMemberDecorate %46 0 Offset 0 +OpDecorate %48 DescriptorSet 0 +OpDecorate %48 Binding 7 +OpDecorate %49 Block +OpMemberDecorate %49 0 Offset 0 +OpDecorate %119 BuiltIn LocalInvocationId %2 = OpTypeVoid %3 = OpTypeBool %4 = OpTypeFloat 32 @@ -73,187 +73,186 @@ OpDecorate %121 BuiltIn LocalInvocationId %23 = OpTypeInt 32 1 %24 = OpTypeMatrix %8 3 %25 = OpConstantTrue %3 -%26 = OpConstant %23 20 -%27 = OpConstant %23 2 -%29 = OpTypePointer Workgroup %5 +%27 = OpTypePointer Workgroup %5 +%26 = OpVariable %27 Workgroup +%29 = OpTypePointer Workgroup %7 %28 = OpVariable %29 Workgroup -%31 = OpTypePointer Workgroup %7 -%30 = OpVariable %31 Workgroup -%33 = OpTypeStruct %9 -%34 = OpTypePointer StorageBuffer %33 -%32 = OpVariable %34 StorageBuffer -%36 = OpTypeStruct %11 -%37 = OpTypePointer StorageBuffer %36 -%35 = OpVariable %37 StorageBuffer -%39 = OpTypeStruct %13 -%40 = OpTypePointer Uniform %39 -%38 = OpVariable %40 Uniform -%42 = OpTypeStruct %8 -%43 = OpTypePointer Uniform %42 -%41 = OpVariable %43 Uniform -%45 = OpTypeStruct %15 -%46 = OpTypePointer Uniform %45 -%44 = OpVariable %46 Uniform -%48 = OpTypeStruct %19 -%49 = OpTypePointer Uniform %48 -%47 = OpVariable %49 Uniform -%51 = OpTypeStruct %22 -%52 = OpTypePointer Uniform %51 -%50 = OpVariable %52 Uniform -%56 = OpTypeFunction %2 %8 -%59 = OpTypePointer Function %23 -%60 = OpConstantNull %23 -%63 = OpTypeFunction %2 -%64 = OpTypePointer StorageBuffer %9 -%65 = OpConstant %7 0 -%67 = OpConstant %4 1.0 -%68 = OpConstant %23 1 -%69 = OpConstant %4 2.0 -%70 = OpConstant %4 3.0 -%71 = OpConstantNull %24 -%73 = OpTypePointer StorageBuffer %8 -%76 = OpTypePointer StorageBuffer %4 -%96 = OpTypePointer Function %4 -%97 = OpConstantNull %4 -%99 = OpTypePointer Function %3 -%100 = OpConstantNull %3 -%104 = OpTypePointer StorageBuffer %11 -%106 = OpTypePointer Uniform %13 -%108 = OpTypePointer Uniform %8 -%110 = OpTypePointer Uniform %15 -%112 = OpTypePointer Uniform %19 -%114 = OpTypePointer Uniform %22 -%116 = OpConstant %4 4.0 -%118 = OpConstantNull %5 -%119 = OpConstantNull %7 -%120 = OpTypeVector %7 3 -%122 = OpTypePointer Input %120 -%121 = OpVariable %122 Input -%124 = OpConstantNull %120 -%125 = OpTypeVector %3 3 -%130 = OpConstant %7 264 -%133 = OpTypePointer Workgroup %4 -%134 = OpTypePointer Uniform %21 -%135 = OpTypePointer Uniform %20 -%138 = OpTypePointer Uniform %17 -%139 = OpTypePointer Uniform %16 -%140 = OpTypePointer Uniform %12 -%145 = OpConstant %7 7 -%151 = OpConstant %7 6 -%153 = OpTypePointer StorageBuffer %10 -%154 = OpConstant %7 1 -%157 = OpConstant %7 5 -%159 = OpTypePointer Uniform %12 -%160 = OpTypePointer Uniform %4 -%161 = OpConstant %7 3 -%164 = OpConstant %7 4 -%166 = OpTypePointer StorageBuffer %4 -%177 = OpConstant %7 256 -%55 = OpFunction %2 None %56 -%54 = OpFunctionParameter %8 -%53 = OpLabel -OpBranch %57 -%57 = OpLabel +%31 = OpTypeStruct %9 +%32 = OpTypePointer StorageBuffer %31 +%30 = OpVariable %32 StorageBuffer +%34 = OpTypeStruct %11 +%35 = OpTypePointer StorageBuffer %34 +%33 = OpVariable %35 StorageBuffer +%37 = OpTypeStruct %13 +%38 = OpTypePointer Uniform %37 +%36 = OpVariable %38 Uniform +%40 = OpTypeStruct %8 +%41 = OpTypePointer Uniform %40 +%39 = OpVariable %41 Uniform +%43 = OpTypeStruct %15 +%44 = OpTypePointer Uniform %43 +%42 = OpVariable %44 Uniform +%46 = OpTypeStruct %19 +%47 = OpTypePointer Uniform %46 +%45 = OpVariable %47 Uniform +%49 = OpTypeStruct %22 +%50 = OpTypePointer Uniform %49 +%48 = OpVariable %50 Uniform +%54 = OpTypeFunction %2 %8 +%57 = OpTypePointer Function %23 +%58 = OpConstantNull %23 +%61 = OpTypeFunction %2 +%62 = OpTypePointer StorageBuffer %9 +%63 = OpConstant %7 0 +%65 = OpConstant %4 1.0 +%66 = OpConstant %23 1 +%67 = OpConstant %4 2.0 +%68 = OpConstant %4 3.0 +%69 = OpConstantNull %24 +%71 = OpTypePointer StorageBuffer %8 +%74 = OpTypePointer StorageBuffer %4 +%94 = OpTypePointer Function %4 +%95 = OpConstantNull %4 +%97 = OpTypePointer Function %3 +%98 = OpConstantNull %3 +%102 = OpTypePointer StorageBuffer %11 +%104 = OpTypePointer Uniform %13 +%106 = OpTypePointer Uniform %8 +%108 = OpTypePointer Uniform %15 +%110 = OpTypePointer Uniform %19 +%112 = OpTypePointer Uniform %22 +%114 = OpConstant %4 4.0 +%116 = OpConstantNull %5 +%117 = OpConstantNull %7 +%118 = OpTypeVector %7 3 +%120 = OpTypePointer Input %118 +%119 = OpVariable %120 Input +%122 = OpConstantNull %118 +%123 = OpTypeVector %3 3 +%128 = OpConstant %7 264 +%131 = OpTypePointer Workgroup %4 +%132 = OpTypePointer Uniform %21 +%133 = OpTypePointer Uniform %20 +%136 = OpTypePointer Uniform %17 +%137 = OpTypePointer Uniform %16 +%138 = OpTypePointer Uniform %12 +%143 = OpConstant %7 7 +%149 = OpConstant %7 6 +%151 = OpTypePointer StorageBuffer %10 +%152 = OpConstant %7 1 +%155 = OpConstant %7 5 +%157 = OpTypePointer Uniform %12 +%158 = OpTypePointer Uniform %4 +%159 = OpConstant %7 3 +%162 = OpConstant %7 4 +%164 = OpTypePointer StorageBuffer %4 +%175 = OpConstant %23 2 +%176 = OpConstant %7 256 +%53 = OpFunction %2 None %54 +%52 = OpFunctionParameter %8 +%51 = OpLabel +OpBranch %55 +%55 = OpLabel OpReturn OpFunctionEnd -%62 = OpFunction %2 None %63 -%61 = OpLabel -%58 = OpVariable %59 Function %60 -%66 = OpAccessChain %64 %32 %65 -OpBranch %72 -%72 = OpLabel -%74 = OpCompositeConstruct %8 %67 %67 %67 -%75 = OpAccessChain %73 %66 %65 -OpStore %75 %74 -OpStore %58 %68 -%77 = OpAccessChain %76 %66 %65 %65 -OpStore %77 %67 -%78 = OpAccessChain %76 %66 %65 %65 -OpStore %78 %69 -%79 = OpLoad %23 %58 -%80 = OpAccessChain %76 %66 %65 %79 -OpStore %80 %70 -%81 = OpLoad %9 %66 -%82 = OpCompositeExtract %8 %81 0 -%83 = OpCompositeExtract %8 %81 0 -%84 = OpVectorShuffle %10 %83 %83 2 0 -%85 = OpCompositeExtract %8 %81 0 -%86 = OpFunctionCall %2 %55 %85 -%87 = OpCompositeExtract %8 %81 0 -%88 = OpVectorTimesMatrix %8 %87 %71 -%89 = OpCompositeExtract %8 %81 0 -%90 = OpMatrixTimesVector %8 %71 %89 -%91 = OpCompositeExtract %8 %81 0 -%92 = OpVectorTimesScalar %8 %91 %69 -%93 = OpCompositeExtract %8 %81 0 -%94 = OpVectorTimesScalar %8 %93 %69 +%60 = OpFunction %2 None %61 +%59 = OpLabel +%56 = OpVariable %57 Function %58 +%64 = OpAccessChain %62 %30 %63 +OpBranch %70 +%70 = OpLabel +%72 = OpCompositeConstruct %8 %65 %65 %65 +%73 = OpAccessChain %71 %64 %63 +OpStore %73 %72 +OpStore %56 %66 +%75 = OpAccessChain %74 %64 %63 %63 +OpStore %75 %65 +%76 = OpAccessChain %74 %64 %63 %63 +OpStore %76 %67 +%77 = OpLoad %23 %56 +%78 = OpAccessChain %74 %64 %63 %77 +OpStore %78 %68 +%79 = OpLoad %9 %64 +%80 = OpCompositeExtract %8 %79 0 +%81 = OpCompositeExtract %8 %79 0 +%82 = OpVectorShuffle %10 %81 %81 2 0 +%83 = OpCompositeExtract %8 %79 0 +%84 = OpFunctionCall %2 %53 %83 +%85 = OpCompositeExtract %8 %79 0 +%86 = OpVectorTimesMatrix %8 %85 %69 +%87 = OpCompositeExtract %8 %79 0 +%88 = OpMatrixTimesVector %8 %69 %87 +%89 = OpCompositeExtract %8 %79 0 +%90 = OpVectorTimesScalar %8 %89 %67 +%91 = OpCompositeExtract %8 %79 0 +%92 = OpVectorTimesScalar %8 %91 %67 OpReturn OpFunctionEnd -%102 = OpFunction %2 None %63 -%101 = OpLabel -%95 = OpVariable %96 Function %97 -%98 = OpVariable %99 Function %100 -%103 = OpAccessChain %64 %32 %65 -%105 = OpAccessChain %104 %35 %65 -%107 = OpAccessChain %106 %38 %65 -%109 = OpAccessChain %108 %41 %65 -%111 = OpAccessChain %110 %44 %65 -%113 = OpAccessChain %112 %47 %65 -%115 = OpAccessChain %114 %50 %65 -OpBranch %117 -%117 = OpLabel -%123 = OpLoad %120 %121 -%126 = OpIEqual %125 %123 %124 -%127 = OpAll %3 %126 -OpSelectionMerge %128 None -OpBranchConditional %127 %129 %128 +%100 = OpFunction %2 None %61 +%99 = OpLabel +%93 = OpVariable %94 Function %95 +%96 = OpVariable %97 Function %98 +%101 = OpAccessChain %62 %30 %63 +%103 = OpAccessChain %102 %33 %63 +%105 = OpAccessChain %104 %36 %63 +%107 = OpAccessChain %106 %39 %63 +%109 = OpAccessChain %108 %42 %63 +%111 = OpAccessChain %110 %45 %63 +%113 = OpAccessChain %112 %48 %63 +OpBranch %115 +%115 = OpLabel +%121 = OpLoad %118 %119 +%124 = OpIEqual %123 %121 %122 +%125 = OpAll %3 %124 +OpSelectionMerge %126 None +OpBranchConditional %125 %127 %126 +%127 = OpLabel +OpStore %26 %116 +OpStore %28 %117 +OpBranch %126 +%126 = OpLabel +OpControlBarrier %18 %18 %128 +OpBranch %129 %129 = OpLabel -OpStore %28 %118 -OpStore %30 %119 -OpBranch %128 -%128 = OpLabel -OpControlBarrier %18 %18 %130 -OpBranch %131 -%131 = OpLabel -%132 = OpFunctionCall %2 %62 -%136 = OpAccessChain %135 %115 %65 %65 -%137 = OpLoad %20 %136 -%141 = OpAccessChain %140 %113 %65 %65 %65 -%142 = OpLoad %12 %141 -%143 = OpMatrixTimesVector %10 %137 %142 -%144 = OpCompositeExtract %4 %143 0 -%146 = OpAccessChain %133 %28 %145 -OpStore %146 %144 -%147 = OpLoad %15 %111 -%148 = OpLoad %8 %109 -%149 = OpMatrixTimesVector %10 %147 %148 -%150 = OpCompositeExtract %4 %149 0 -%152 = OpAccessChain %133 %28 %151 -OpStore %152 %150 -%155 = OpAccessChain %76 %105 %154 %154 -%156 = OpLoad %4 %155 -%158 = OpAccessChain %133 %28 %157 -OpStore %158 %156 -%162 = OpAccessChain %160 %107 %65 %161 -%163 = OpLoad %4 %162 -%165 = OpAccessChain %133 %28 %164 -OpStore %165 %163 -%167 = OpAccessChain %166 %103 %154 -%168 = OpLoad %4 %167 -%169 = OpAccessChain %133 %28 %161 -OpStore %169 %168 -%170 = OpAccessChain %76 %103 %65 %65 -%171 = OpLoad %4 %170 -%172 = OpAccessChain %133 %28 %18 -OpStore %172 %171 -%173 = OpAccessChain %166 %103 %154 -OpStore %173 %116 -%174 = OpArrayLength %7 %35 0 -%175 = OpConvertUToF %4 %174 -%176 = OpAccessChain %133 %28 %154 -OpStore %176 %175 -OpAtomicStore %30 %27 %177 %18 -OpStore %95 %67 -OpStore %98 %25 +%130 = OpFunctionCall %2 %60 +%134 = OpAccessChain %133 %113 %63 %63 +%135 = OpLoad %20 %134 +%139 = OpAccessChain %138 %111 %63 %63 %63 +%140 = OpLoad %12 %139 +%141 = OpMatrixTimesVector %10 %135 %140 +%142 = OpCompositeExtract %4 %141 0 +%144 = OpAccessChain %131 %26 %143 +OpStore %144 %142 +%145 = OpLoad %15 %109 +%146 = OpLoad %8 %107 +%147 = OpMatrixTimesVector %10 %145 %146 +%148 = OpCompositeExtract %4 %147 0 +%150 = OpAccessChain %131 %26 %149 +OpStore %150 %148 +%153 = OpAccessChain %74 %103 %152 %152 +%154 = OpLoad %4 %153 +%156 = OpAccessChain %131 %26 %155 +OpStore %156 %154 +%160 = OpAccessChain %158 %105 %63 %159 +%161 = OpLoad %4 %160 +%163 = OpAccessChain %131 %26 %162 +OpStore %163 %161 +%165 = OpAccessChain %164 %101 %152 +%166 = OpLoad %4 %165 +%167 = OpAccessChain %131 %26 %159 +OpStore %167 %166 +%168 = OpAccessChain %74 %101 %63 %63 +%169 = OpLoad %4 %168 +%170 = OpAccessChain %131 %26 %18 +OpStore %170 %169 +%171 = OpAccessChain %164 %101 %152 +OpStore %171 %114 +%172 = OpArrayLength %7 %33 0 +%173 = OpConvertUToF %4 %172 +%174 = OpAccessChain %131 %26 %152 +OpStore %174 %173 +OpAtomicStore %28 %175 %176 %18 +OpStore %93 %65 +OpStore %96 %25 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 45eadbae7..1b6ef2887 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -9,106 +9,106 @@ OpCapability SampledCubeArray OpCapability ImageQuery %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %82 "main" %79 -OpEntryPoint GLCompute %171 "depth_load" %169 -OpEntryPoint Vertex %192 "queries" %190 -OpEntryPoint Vertex %244 "levels_queries" %243 -OpEntryPoint Fragment %276 "texture_sample" %275 +OpEntryPoint GLCompute %78 "main" %75 +OpEntryPoint GLCompute %169 "depth_load" %167 +OpEntryPoint Vertex %190 "queries" %188 +OpEntryPoint Vertex %242 "levels_queries" %241 +OpEntryPoint Fragment %274 "texture_sample" %273 OpEntryPoint Fragment %421 "texture_sample_comparison" %419 OpEntryPoint Fragment %476 "gather" %475 OpEntryPoint Fragment %511 "depth_no_comparison" %510 -OpExecutionMode %82 LocalSize 16 1 1 -OpExecutionMode %171 LocalSize 16 1 1 -OpExecutionMode %276 OriginUpperLeft +OpExecutionMode %78 LocalSize 16 1 1 +OpExecutionMode %169 LocalSize 16 1 1 +OpExecutionMode %274 OriginUpperLeft OpExecutionMode %421 OriginUpperLeft OpExecutionMode %476 OriginUpperLeft OpExecutionMode %511 OriginUpperLeft -OpName %35 "image_mipmapped_src" -OpName %37 "image_multisampled_src" -OpName %39 "image_depth_multisampled_src" -OpName %41 "image_storage_src" -OpName %43 "image_array_src" -OpName %45 "image_dup_src" -OpName %47 "image_1d_src" -OpName %49 "image_dst" -OpName %51 "image_1d" -OpName %53 "image_2d" -OpName %55 "image_2d_u32" -OpName %56 "image_2d_i32" -OpName %58 "image_2d_array" -OpName %60 "image_cube" -OpName %62 "image_cube_array" -OpName %64 "image_3d" -OpName %66 "image_aa" -OpName %68 "sampler_reg" -OpName %70 "sampler_cmp" -OpName %72 "image_2d_depth" -OpName %74 "image_2d_array_depth" -OpName %76 "image_cube_depth" -OpName %79 "local_id" -OpName %82 "main" -OpName %169 "local_id" -OpName %171 "depth_load" -OpName %192 "queries" -OpName %244 "levels_queries" -OpName %271 "a" -OpName %276 "texture_sample" +OpName %31 "image_mipmapped_src" +OpName %33 "image_multisampled_src" +OpName %35 "image_depth_multisampled_src" +OpName %37 "image_storage_src" +OpName %39 "image_array_src" +OpName %41 "image_dup_src" +OpName %43 "image_1d_src" +OpName %45 "image_dst" +OpName %47 "image_1d" +OpName %49 "image_2d" +OpName %51 "image_2d_u32" +OpName %52 "image_2d_i32" +OpName %54 "image_2d_array" +OpName %56 "image_cube" +OpName %58 "image_cube_array" +OpName %60 "image_3d" +OpName %62 "image_aa" +OpName %64 "sampler_reg" +OpName %66 "sampler_cmp" +OpName %68 "image_2d_depth" +OpName %70 "image_2d_array_depth" +OpName %72 "image_cube_depth" +OpName %75 "local_id" +OpName %78 "main" +OpName %167 "local_id" +OpName %169 "depth_load" +OpName %190 "queries" +OpName %242 "levels_queries" +OpName %269 "a" +OpName %274 "texture_sample" OpName %415 "a" OpName %421 "texture_sample_comparison" OpName %476 "gather" OpName %511 "depth_no_comparison" +OpDecorate %31 DescriptorSet 0 +OpDecorate %31 Binding 0 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 3 OpDecorate %35 DescriptorSet 0 -OpDecorate %35 Binding 0 +OpDecorate %35 Binding 4 +OpDecorate %37 NonWritable OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 3 +OpDecorate %37 Binding 1 OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 4 +OpDecorate %39 Binding 5 OpDecorate %41 NonWritable OpDecorate %41 DescriptorSet 0 -OpDecorate %41 Binding 1 +OpDecorate %41 Binding 6 OpDecorate %43 DescriptorSet 0 -OpDecorate %43 Binding 5 -OpDecorate %45 NonWritable +OpDecorate %43 Binding 7 +OpDecorate %45 NonReadable OpDecorate %45 DescriptorSet 0 -OpDecorate %45 Binding 6 +OpDecorate %45 Binding 2 OpDecorate %47 DescriptorSet 0 -OpDecorate %47 Binding 7 -OpDecorate %49 NonReadable +OpDecorate %47 Binding 0 OpDecorate %49 DescriptorSet 0 -OpDecorate %49 Binding 2 +OpDecorate %49 Binding 1 OpDecorate %51 DescriptorSet 0 -OpDecorate %51 Binding 0 -OpDecorate %53 DescriptorSet 0 -OpDecorate %53 Binding 1 -OpDecorate %55 DescriptorSet 0 -OpDecorate %55 Binding 2 +OpDecorate %51 Binding 2 +OpDecorate %52 DescriptorSet 0 +OpDecorate %52 Binding 3 +OpDecorate %54 DescriptorSet 0 +OpDecorate %54 Binding 4 OpDecorate %56 DescriptorSet 0 -OpDecorate %56 Binding 3 +OpDecorate %56 Binding 5 OpDecorate %58 DescriptorSet 0 -OpDecorate %58 Binding 4 +OpDecorate %58 Binding 6 OpDecorate %60 DescriptorSet 0 -OpDecorate %60 Binding 5 +OpDecorate %60 Binding 7 OpDecorate %62 DescriptorSet 0 -OpDecorate %62 Binding 6 -OpDecorate %64 DescriptorSet 0 -OpDecorate %64 Binding 7 -OpDecorate %66 DescriptorSet 0 -OpDecorate %66 Binding 8 +OpDecorate %62 Binding 8 +OpDecorate %64 DescriptorSet 1 +OpDecorate %64 Binding 0 +OpDecorate %66 DescriptorSet 1 +OpDecorate %66 Binding 1 OpDecorate %68 DescriptorSet 1 -OpDecorate %68 Binding 0 +OpDecorate %68 Binding 2 OpDecorate %70 DescriptorSet 1 -OpDecorate %70 Binding 1 +OpDecorate %70 Binding 3 OpDecorate %72 DescriptorSet 1 -OpDecorate %72 Binding 2 -OpDecorate %74 DescriptorSet 1 -OpDecorate %74 Binding 3 -OpDecorate %76 DescriptorSet 1 -OpDecorate %76 Binding 4 -OpDecorate %79 BuiltIn LocalInvocationId -OpDecorate %169 BuiltIn LocalInvocationId -OpDecorate %190 BuiltIn Position -OpDecorate %243 BuiltIn Position -OpDecorate %275 Location 0 +OpDecorate %72 Binding 4 +OpDecorate %75 BuiltIn LocalInvocationId +OpDecorate %167 BuiltIn LocalInvocationId +OpDecorate %188 BuiltIn Position +OpDecorate %241 BuiltIn Position +OpDecorate %273 Location 0 OpDecorate %419 Location 0 OpDecorate %475 Location 0 OpDecorate %510 Location 0 @@ -125,47 +125,47 @@ OpDecorate %510 Location 0 %12 = OpTypeVector %4 3 %14 = OpTypeInt 32 1 %13 = OpTypeVector %14 2 -%15 = OpTypeVector %4 2 -%16 = OpTypeVector %4 4 -%17 = OpTypeImage %7 1D 0 0 0 1 Unknown -%18 = OpTypeImage %7 2D 0 0 0 1 Unknown -%19 = OpTypeImage %14 2D 0 0 0 1 Unknown -%20 = OpTypeImage %7 2D 0 1 0 1 Unknown -%21 = OpTypeImage %7 Cube 0 0 0 1 Unknown -%22 = OpTypeImage %7 Cube 0 1 0 1 Unknown -%23 = OpTypeImage %7 3D 0 0 0 1 Unknown -%24 = OpTypeImage %7 2D 0 0 1 1 Unknown -%25 = OpTypeVector %7 4 -%26 = OpTypeSampler -%27 = OpTypeVector %7 2 -%28 = OpTypeVector %7 3 -%29 = OpTypeImage %7 2D 1 0 0 1 Unknown -%30 = OpTypeImage %7 2D 1 1 0 1 Unknown -%31 = OpTypeImage %7 Cube 1 0 0 1 Unknown -%32 = OpConstant %14 3 -%33 = OpConstant %14 1 -%34 = OpConstantComposite %13 %32 %33 -%36 = OpTypePointer UniformConstant %3 +%15 = OpTypeImage %7 1D 0 0 0 1 Unknown +%16 = OpTypeImage %7 2D 0 0 0 1 Unknown +%17 = OpTypeImage %14 2D 0 0 0 1 Unknown +%18 = OpTypeImage %7 2D 0 1 0 1 Unknown +%19 = OpTypeImage %7 Cube 0 0 0 1 Unknown +%20 = OpTypeImage %7 Cube 0 1 0 1 Unknown +%21 = OpTypeImage %7 3D 0 0 0 1 Unknown +%22 = OpTypeImage %7 2D 0 0 1 1 Unknown +%23 = OpTypeVector %7 4 +%24 = OpTypeSampler +%25 = OpTypeImage %7 2D 1 0 0 1 Unknown +%26 = OpTypeImage %7 2D 1 1 0 1 Unknown +%27 = OpTypeImage %7 Cube 1 0 0 1 Unknown +%28 = OpConstant %14 3 +%29 = OpConstant %14 1 +%30 = OpConstantComposite %13 %28 %29 +%32 = OpTypePointer UniformConstant %3 +%31 = OpVariable %32 UniformConstant +%34 = OpTypePointer UniformConstant %5 +%33 = OpVariable %34 UniformConstant +%36 = OpTypePointer UniformConstant %6 %35 = OpVariable %36 UniformConstant -%38 = OpTypePointer UniformConstant %5 +%38 = OpTypePointer UniformConstant %8 %37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %6 +%40 = OpTypePointer UniformConstant %9 %39 = OpVariable %40 UniformConstant -%42 = OpTypePointer UniformConstant %8 +%42 = OpTypePointer UniformConstant %10 %41 = OpVariable %42 UniformConstant -%44 = OpTypePointer UniformConstant %9 +%44 = OpTypePointer UniformConstant %11 %43 = OpVariable %44 UniformConstant %46 = OpTypePointer UniformConstant %10 %45 = OpVariable %46 UniformConstant -%48 = OpTypePointer UniformConstant %11 +%48 = OpTypePointer UniformConstant %15 %47 = OpVariable %48 UniformConstant -%50 = OpTypePointer UniformConstant %10 +%50 = OpTypePointer UniformConstant %16 %49 = OpVariable %50 UniformConstant -%52 = OpTypePointer UniformConstant %17 -%51 = OpVariable %52 UniformConstant -%54 = OpTypePointer UniformConstant %18 -%53 = OpVariable %54 UniformConstant -%55 = OpVariable %36 UniformConstant +%51 = OpVariable %32 UniformConstant +%53 = OpTypePointer UniformConstant %17 +%52 = OpVariable %53 UniformConstant +%55 = OpTypePointer UniformConstant %18 +%54 = OpVariable %55 UniformConstant %57 = OpTypePointer UniformConstant %19 %56 = OpVariable %57 UniformConstant %59 = OpTypePointer UniformConstant %20 @@ -174,470 +174,470 @@ OpDecorate %510 Location 0 %60 = OpVariable %61 UniformConstant %63 = OpTypePointer UniformConstant %22 %62 = OpVariable %63 UniformConstant -%65 = OpTypePointer UniformConstant %23 +%65 = OpTypePointer UniformConstant %24 %64 = OpVariable %65 UniformConstant %67 = OpTypePointer UniformConstant %24 %66 = OpVariable %67 UniformConstant -%69 = OpTypePointer UniformConstant %26 +%69 = OpTypePointer UniformConstant %25 %68 = OpVariable %69 UniformConstant %71 = OpTypePointer UniformConstant %26 %70 = OpVariable %71 UniformConstant -%73 = OpTypePointer UniformConstant %29 +%73 = OpTypePointer UniformConstant %27 %72 = OpVariable %73 UniformConstant -%75 = OpTypePointer UniformConstant %30 -%74 = OpVariable %75 UniformConstant -%77 = OpTypePointer UniformConstant %31 -%76 = OpVariable %77 UniformConstant -%80 = OpTypePointer Input %12 -%79 = OpVariable %80 Input -%83 = OpTypeFunction %2 -%90 = OpConstant %14 10 -%91 = OpConstant %14 20 -%111 = OpTypeVector %14 3 -%169 = OpVariable %80 Input -%191 = OpTypePointer Output %25 -%190 = OpVariable %191 Output -%201 = OpConstant %4 0 -%243 = OpVariable %191 Output -%272 = OpTypePointer Function %25 -%273 = OpConstantNull %25 -%275 = OpVariable %191 Output -%282 = OpConstant %7 0.5 -%283 = OpConstant %7 2.3 -%284 = OpConstant %7 2.0 -%285 = OpConstant %14 0 -%290 = OpTypeSampledImage %17 -%295 = OpTypeSampledImage %18 -%316 = OpTypeSampledImage %20 -%377 = OpTypeSampledImage %22 +%76 = OpTypePointer Input %12 +%75 = OpVariable %76 Input +%79 = OpTypeFunction %2 +%86 = OpConstant %14 10 +%87 = OpConstant %14 20 +%89 = OpTypeVector %4 2 +%98 = OpTypeVector %4 4 +%109 = OpTypeVector %14 3 +%167 = OpVariable %76 Input +%189 = OpTypePointer Output %23 +%188 = OpVariable %189 Output +%199 = OpConstant %4 0 +%241 = OpVariable %189 Output +%270 = OpTypePointer Function %23 +%271 = OpConstantNull %23 +%273 = OpVariable %189 Output +%280 = OpConstant %7 0.5 +%281 = OpConstant %7 2.3 +%282 = OpConstant %7 2.0 +%283 = OpConstant %14 0 +%285 = OpTypeVector %7 2 +%287 = OpTypeVector %7 3 +%290 = OpTypeSampledImage %15 +%295 = OpTypeSampledImage %16 +%316 = OpTypeSampledImage %18 +%377 = OpTypeSampledImage %20 %416 = OpTypePointer Function %7 %417 = OpConstantNull %7 %420 = OpTypePointer Output %7 %419 = OpVariable %420 Output -%429 = OpTypeSampledImage %29 -%434 = OpTypeSampledImage %30 -%447 = OpTypeSampledImage %31 +%429 = OpTypeSampledImage %25 +%434 = OpTypeSampledImage %26 +%447 = OpTypeSampledImage %27 %454 = OpConstant %7 0.0 -%475 = OpVariable %191 Output +%475 = OpVariable %189 Output %487 = OpConstant %4 1 %490 = OpConstant %4 3 %495 = OpTypeSampledImage %3 %498 = OpTypeVector %14 4 -%499 = OpTypeSampledImage %19 -%510 = OpVariable %191 Output -%82 = OpFunction %2 None %83 -%78 = OpLabel -%81 = OpLoad %12 %79 -%84 = OpLoad %3 %35 -%85 = OpLoad %5 %37 -%86 = OpLoad %8 %41 -%87 = OpLoad %9 %43 -%88 = OpLoad %11 %47 -%89 = OpLoad %10 %49 -OpBranch %92 -%92 = OpLabel -%93 = OpImageQuerySize %15 %86 -%94 = OpVectorShuffle %15 %81 %81 0 1 -%95 = OpIMul %15 %93 %94 -%96 = OpBitcast %13 %95 -%97 = OpCompositeConstruct %13 %90 %91 -%98 = OpSRem %13 %96 %97 -%99 = OpCompositeExtract %4 %81 2 -%100 = OpBitcast %14 %99 -%101 = OpImageFetch %16 %84 %98 Lod %100 -%102 = OpCompositeExtract %4 %81 2 -%103 = OpBitcast %14 %102 -%104 = OpImageFetch %16 %85 %98 Sample %103 -%105 = OpImageRead %16 %86 %98 -%106 = OpCompositeExtract %4 %81 2 -%107 = OpCompositeExtract %4 %81 2 -%108 = OpBitcast %14 %107 -%109 = OpIAdd %14 %108 %33 -%110 = OpBitcast %14 %106 -%112 = OpCompositeConstruct %111 %98 %110 -%113 = OpImageFetch %16 %87 %112 Lod %109 -%114 = OpCompositeExtract %4 %81 2 +%499 = OpTypeSampledImage %17 +%510 = OpVariable %189 Output +%78 = OpFunction %2 None %79 +%74 = OpLabel +%77 = OpLoad %12 %75 +%80 = OpLoad %3 %31 +%81 = OpLoad %5 %33 +%82 = OpLoad %8 %37 +%83 = OpLoad %9 %39 +%84 = OpLoad %11 %43 +%85 = OpLoad %10 %45 +OpBranch %88 +%88 = OpLabel +%90 = OpImageQuerySize %89 %82 +%91 = OpVectorShuffle %89 %77 %77 0 1 +%92 = OpIMul %89 %90 %91 +%93 = OpBitcast %13 %92 +%94 = OpCompositeConstruct %13 %86 %87 +%95 = OpSRem %13 %93 %94 +%96 = OpCompositeExtract %4 %77 2 +%97 = OpBitcast %14 %96 +%99 = OpImageFetch %98 %80 %95 Lod %97 +%100 = OpCompositeExtract %4 %77 2 +%101 = OpBitcast %14 %100 +%102 = OpImageFetch %98 %81 %95 Sample %101 +%103 = OpImageRead %98 %82 %95 +%104 = OpCompositeExtract %4 %77 2 +%105 = OpCompositeExtract %4 %77 2 +%106 = OpBitcast %14 %105 +%107 = OpIAdd %14 %106 %29 +%108 = OpBitcast %14 %104 +%110 = OpCompositeConstruct %109 %95 %108 +%111 = OpImageFetch %98 %83 %110 Lod %107 +%112 = OpCompositeExtract %4 %77 2 +%113 = OpBitcast %14 %112 +%114 = OpCompositeExtract %4 %77 2 %115 = OpBitcast %14 %114 -%116 = OpCompositeExtract %4 %81 2 -%117 = OpBitcast %14 %116 -%118 = OpIAdd %14 %117 %33 -%119 = OpCompositeConstruct %111 %98 %115 -%120 = OpImageFetch %16 %87 %119 Lod %118 -%121 = OpCompositeExtract %4 %81 0 +%116 = OpIAdd %14 %115 %29 +%117 = OpCompositeConstruct %109 %95 %113 +%118 = OpImageFetch %98 %83 %117 Lod %116 +%119 = OpCompositeExtract %4 %77 0 +%120 = OpBitcast %14 %119 +%121 = OpCompositeExtract %4 %77 2 %122 = OpBitcast %14 %121 -%123 = OpCompositeExtract %4 %81 2 -%124 = OpBitcast %14 %123 -%125 = OpImageFetch %16 %88 %122 Lod %124 -%126 = OpBitcast %15 %98 -%127 = OpCompositeExtract %4 %81 2 -%128 = OpBitcast %14 %127 -%129 = OpImageFetch %16 %84 %126 Lod %128 -%130 = OpBitcast %15 %98 -%131 = OpCompositeExtract %4 %81 2 -%132 = OpBitcast %14 %131 -%133 = OpImageFetch %16 %85 %130 Sample %132 -%134 = OpBitcast %15 %98 -%135 = OpImageRead %16 %86 %134 -%136 = OpBitcast %15 %98 -%137 = OpCompositeExtract %4 %81 2 -%138 = OpCompositeExtract %4 %81 2 -%139 = OpBitcast %14 %138 -%140 = OpIAdd %14 %139 %33 -%141 = OpCompositeConstruct %12 %136 %137 -%142 = OpImageFetch %16 %87 %141 Lod %140 -%143 = OpBitcast %15 %98 -%144 = OpCompositeExtract %4 %81 2 +%123 = OpImageFetch %98 %84 %120 Lod %122 +%124 = OpBitcast %89 %95 +%125 = OpCompositeExtract %4 %77 2 +%126 = OpBitcast %14 %125 +%127 = OpImageFetch %98 %80 %124 Lod %126 +%128 = OpBitcast %89 %95 +%129 = OpCompositeExtract %4 %77 2 +%130 = OpBitcast %14 %129 +%131 = OpImageFetch %98 %81 %128 Sample %130 +%132 = OpBitcast %89 %95 +%133 = OpImageRead %98 %82 %132 +%134 = OpBitcast %89 %95 +%135 = OpCompositeExtract %4 %77 2 +%136 = OpCompositeExtract %4 %77 2 +%137 = OpBitcast %14 %136 +%138 = OpIAdd %14 %137 %29 +%139 = OpCompositeConstruct %12 %134 %135 +%140 = OpImageFetch %98 %83 %139 Lod %138 +%141 = OpBitcast %89 %95 +%142 = OpCompositeExtract %4 %77 2 +%143 = OpBitcast %14 %142 +%144 = OpCompositeExtract %4 %77 2 %145 = OpBitcast %14 %144 -%146 = OpCompositeExtract %4 %81 2 -%147 = OpBitcast %14 %146 -%148 = OpIAdd %14 %147 %33 -%149 = OpBitcast %4 %145 -%150 = OpCompositeConstruct %12 %143 %149 -%151 = OpImageFetch %16 %87 %150 Lod %148 -%152 = OpCompositeExtract %4 %81 0 -%154 = OpCompositeExtract %4 %81 2 -%155 = OpBitcast %14 %154 -%156 = OpImageFetch %16 %88 %152 Lod %155 -%157 = OpCompositeExtract %14 %98 0 -%158 = OpIAdd %16 %101 %104 -%159 = OpIAdd %16 %158 %105 -%160 = OpIAdd %16 %159 %113 -%161 = OpIAdd %16 %160 %120 -OpImageWrite %89 %157 %161 -%162 = OpCompositeExtract %14 %98 0 -%163 = OpBitcast %4 %162 -%164 = OpIAdd %16 %129 %133 -%165 = OpIAdd %16 %164 %135 -%166 = OpIAdd %16 %165 %142 -%167 = OpIAdd %16 %166 %151 -OpImageWrite %89 %163 %167 +%146 = OpIAdd %14 %145 %29 +%147 = OpBitcast %4 %143 +%148 = OpCompositeConstruct %12 %141 %147 +%149 = OpImageFetch %98 %83 %148 Lod %146 +%150 = OpCompositeExtract %4 %77 0 +%152 = OpCompositeExtract %4 %77 2 +%153 = OpBitcast %14 %152 +%154 = OpImageFetch %98 %84 %150 Lod %153 +%155 = OpCompositeExtract %14 %95 0 +%156 = OpIAdd %98 %99 %102 +%157 = OpIAdd %98 %156 %103 +%158 = OpIAdd %98 %157 %111 +%159 = OpIAdd %98 %158 %118 +OpImageWrite %85 %155 %159 +%160 = OpCompositeExtract %14 %95 0 +%161 = OpBitcast %4 %160 +%162 = OpIAdd %98 %127 %131 +%163 = OpIAdd %98 %162 %133 +%164 = OpIAdd %98 %163 %140 +%165 = OpIAdd %98 %164 %149 +OpImageWrite %85 %161 %165 OpReturn OpFunctionEnd -%171 = OpFunction %2 None %83 -%168 = OpLabel -%170 = OpLoad %12 %169 -%172 = OpLoad %6 %39 -%173 = OpLoad %8 %41 -%174 = OpLoad %10 %49 -OpBranch %175 -%175 = OpLabel -%176 = OpImageQuerySize %15 %173 -%177 = OpVectorShuffle %15 %170 %170 0 1 -%178 = OpIMul %15 %176 %177 -%179 = OpBitcast %13 %178 -%180 = OpCompositeConstruct %13 %90 %91 -%181 = OpSRem %13 %179 %180 -%182 = OpCompositeExtract %4 %170 2 -%183 = OpBitcast %14 %182 -%184 = OpImageFetch %25 %172 %181 Sample %183 -%185 = OpCompositeExtract %7 %184 0 -%186 = OpCompositeExtract %14 %181 0 -%187 = OpConvertFToU %4 %185 -%188 = OpCompositeConstruct %16 %187 %187 %187 %187 -OpImageWrite %174 %186 %188 +%169 = OpFunction %2 None %79 +%166 = OpLabel +%168 = OpLoad %12 %167 +%170 = OpLoad %6 %35 +%171 = OpLoad %8 %37 +%172 = OpLoad %10 %45 +OpBranch %173 +%173 = OpLabel +%174 = OpImageQuerySize %89 %171 +%175 = OpVectorShuffle %89 %168 %168 0 1 +%176 = OpIMul %89 %174 %175 +%177 = OpBitcast %13 %176 +%178 = OpCompositeConstruct %13 %86 %87 +%179 = OpSRem %13 %177 %178 +%180 = OpCompositeExtract %4 %168 2 +%181 = OpBitcast %14 %180 +%182 = OpImageFetch %23 %170 %179 Sample %181 +%183 = OpCompositeExtract %7 %182 0 +%184 = OpCompositeExtract %14 %179 0 +%185 = OpConvertFToU %4 %183 +%186 = OpCompositeConstruct %98 %185 %185 %185 %185 +OpImageWrite %172 %184 %186 OpReturn OpFunctionEnd -%192 = OpFunction %2 None %83 -%189 = OpLabel -%193 = OpLoad %17 %51 -%194 = OpLoad %18 %53 +%190 = OpFunction %2 None %79 +%187 = OpLabel +%191 = OpLoad %15 %47 +%192 = OpLoad %16 %49 +%193 = OpLoad %18 %54 +%194 = OpLoad %19 %56 %195 = OpLoad %20 %58 %196 = OpLoad %21 %60 %197 = OpLoad %22 %62 -%198 = OpLoad %23 %64 -%199 = OpLoad %24 %66 -OpBranch %200 -%200 = OpLabel -%202 = OpImageQuerySizeLod %4 %193 %201 -%203 = OpBitcast %14 %202 -%204 = OpImageQuerySizeLod %4 %193 %203 -%205 = OpImageQuerySizeLod %15 %194 %201 -%206 = OpImageQuerySizeLod %15 %194 %33 -%207 = OpImageQuerySizeLod %12 %195 %201 -%208 = OpVectorShuffle %15 %207 %207 0 1 -%209 = OpImageQuerySizeLod %12 %195 %33 -%210 = OpVectorShuffle %15 %209 %209 0 1 -%211 = OpImageQuerySizeLod %15 %196 %201 -%212 = OpImageQuerySizeLod %15 %196 %33 -%213 = OpImageQuerySizeLod %12 %197 %201 -%214 = OpVectorShuffle %15 %213 %213 0 0 -%215 = OpImageQuerySizeLod %12 %197 %33 -%216 = OpVectorShuffle %15 %215 %215 0 0 -%217 = OpImageQuerySizeLod %12 %198 %201 -%218 = OpImageQuerySizeLod %12 %198 %33 -%219 = OpImageQuerySize %15 %199 -%220 = OpCompositeExtract %4 %205 1 -%221 = OpIAdd %4 %202 %220 +OpBranch %198 +%198 = OpLabel +%200 = OpImageQuerySizeLod %4 %191 %199 +%201 = OpBitcast %14 %200 +%202 = OpImageQuerySizeLod %4 %191 %201 +%203 = OpImageQuerySizeLod %89 %192 %199 +%204 = OpImageQuerySizeLod %89 %192 %29 +%205 = OpImageQuerySizeLod %12 %193 %199 +%206 = OpVectorShuffle %89 %205 %205 0 1 +%207 = OpImageQuerySizeLod %12 %193 %29 +%208 = OpVectorShuffle %89 %207 %207 0 1 +%209 = OpImageQuerySizeLod %89 %194 %199 +%210 = OpImageQuerySizeLod %89 %194 %29 +%211 = OpImageQuerySizeLod %12 %195 %199 +%212 = OpVectorShuffle %89 %211 %211 0 0 +%213 = OpImageQuerySizeLod %12 %195 %29 +%214 = OpVectorShuffle %89 %213 %213 0 0 +%215 = OpImageQuerySizeLod %12 %196 %199 +%216 = OpImageQuerySizeLod %12 %196 %29 +%217 = OpImageQuerySize %89 %197 +%218 = OpCompositeExtract %4 %203 1 +%219 = OpIAdd %4 %200 %218 +%220 = OpCompositeExtract %4 %204 1 +%221 = OpIAdd %4 %219 %220 %222 = OpCompositeExtract %4 %206 1 %223 = OpIAdd %4 %221 %222 %224 = OpCompositeExtract %4 %208 1 %225 = OpIAdd %4 %223 %224 -%226 = OpCompositeExtract %4 %210 1 +%226 = OpCompositeExtract %4 %209 1 %227 = OpIAdd %4 %225 %226 -%228 = OpCompositeExtract %4 %211 1 +%228 = OpCompositeExtract %4 %210 1 %229 = OpIAdd %4 %227 %228 %230 = OpCompositeExtract %4 %212 1 %231 = OpIAdd %4 %229 %230 %232 = OpCompositeExtract %4 %214 1 %233 = OpIAdd %4 %231 %232 -%234 = OpCompositeExtract %4 %216 1 +%234 = OpCompositeExtract %4 %215 2 %235 = OpIAdd %4 %233 %234 -%236 = OpCompositeExtract %4 %217 2 +%236 = OpCompositeExtract %4 %216 2 %237 = OpIAdd %4 %235 %236 -%238 = OpCompositeExtract %4 %218 2 -%239 = OpIAdd %4 %237 %238 -%240 = OpConvertUToF %7 %239 -%241 = OpCompositeConstruct %25 %240 %240 %240 %240 -OpStore %190 %241 +%238 = OpConvertUToF %7 %237 +%239 = OpCompositeConstruct %23 %238 %238 %238 %238 +OpStore %188 %239 OpReturn OpFunctionEnd -%244 = OpFunction %2 None %83 -%242 = OpLabel -%245 = OpLoad %18 %53 +%242 = OpFunction %2 None %79 +%240 = OpLabel +%243 = OpLoad %16 %49 +%244 = OpLoad %18 %54 +%245 = OpLoad %19 %56 %246 = OpLoad %20 %58 %247 = OpLoad %21 %60 %248 = OpLoad %22 %62 -%249 = OpLoad %23 %64 -%250 = OpLoad %24 %66 -OpBranch %251 -%251 = OpLabel -%252 = OpImageQueryLevels %4 %245 -%253 = OpImageQueryLevels %4 %246 -%254 = OpImageQuerySizeLod %12 %246 %201 -%255 = OpCompositeExtract %4 %254 2 -%256 = OpImageQueryLevels %4 %247 -%257 = OpImageQueryLevels %4 %248 -%258 = OpImageQuerySizeLod %12 %248 %201 -%259 = OpCompositeExtract %4 %258 2 -%260 = OpImageQueryLevels %4 %249 -%261 = OpImageQuerySamples %4 %250 -%262 = OpIAdd %4 %255 %259 -%263 = OpIAdd %4 %262 %261 -%264 = OpIAdd %4 %263 %252 -%265 = OpIAdd %4 %264 %253 -%266 = OpIAdd %4 %265 %260 -%267 = OpIAdd %4 %266 %256 -%268 = OpIAdd %4 %267 %257 -%269 = OpConvertUToF %7 %268 -%270 = OpCompositeConstruct %25 %269 %269 %269 %269 -OpStore %243 %270 +OpBranch %249 +%249 = OpLabel +%250 = OpImageQueryLevels %4 %243 +%251 = OpImageQueryLevels %4 %244 +%252 = OpImageQuerySizeLod %12 %244 %199 +%253 = OpCompositeExtract %4 %252 2 +%254 = OpImageQueryLevels %4 %245 +%255 = OpImageQueryLevels %4 %246 +%256 = OpImageQuerySizeLod %12 %246 %199 +%257 = OpCompositeExtract %4 %256 2 +%258 = OpImageQueryLevels %4 %247 +%259 = OpImageQuerySamples %4 %248 +%260 = OpIAdd %4 %253 %257 +%261 = OpIAdd %4 %260 %259 +%262 = OpIAdd %4 %261 %250 +%263 = OpIAdd %4 %262 %251 +%264 = OpIAdd %4 %263 %258 +%265 = OpIAdd %4 %264 %254 +%266 = OpIAdd %4 %265 %255 +%267 = OpConvertUToF %7 %266 +%268 = OpCompositeConstruct %23 %267 %267 %267 %267 +OpStore %241 %268 OpReturn OpFunctionEnd -%276 = OpFunction %2 None %83 -%274 = OpLabel -%271 = OpVariable %272 Function %273 -%277 = OpLoad %17 %51 -%278 = OpLoad %18 %53 -%279 = OpLoad %20 %58 -%280 = OpLoad %22 %62 -%281 = OpLoad %26 %68 -OpBranch %286 -%286 = OpLabel -%287 = OpCompositeConstruct %27 %282 %282 -%288 = OpCompositeConstruct %28 %282 %282 %282 -%289 = OpCompositeExtract %7 %287 0 -%291 = OpSampledImage %290 %277 %281 -%292 = OpImageSampleImplicitLod %25 %291 %289 -%293 = OpLoad %25 %271 -%294 = OpFAdd %25 %293 %292 -OpStore %271 %294 -%296 = OpSampledImage %295 %278 %281 -%297 = OpImageSampleImplicitLod %25 %296 %287 -%298 = OpLoad %25 %271 -%299 = OpFAdd %25 %298 %297 -OpStore %271 %299 -%300 = OpSampledImage %295 %278 %281 -%301 = OpImageSampleImplicitLod %25 %300 %287 ConstOffset %34 -%302 = OpLoad %25 %271 -%303 = OpFAdd %25 %302 %301 -OpStore %271 %303 -%304 = OpSampledImage %295 %278 %281 -%305 = OpImageSampleExplicitLod %25 %304 %287 Lod %283 -%306 = OpLoad %25 %271 -%307 = OpFAdd %25 %306 %305 -OpStore %271 %307 -%308 = OpSampledImage %295 %278 %281 -%309 = OpImageSampleExplicitLod %25 %308 %287 Lod|ConstOffset %283 %34 -%310 = OpLoad %25 %271 -%311 = OpFAdd %25 %310 %309 -OpStore %271 %311 -%312 = OpSampledImage %295 %278 %281 -%313 = OpImageSampleImplicitLod %25 %312 %287 Bias|ConstOffset %284 %34 -%314 = OpLoad %25 %271 -%315 = OpFAdd %25 %314 %313 -OpStore %271 %315 -%317 = OpConvertUToF %7 %201 -%318 = OpCompositeConstruct %28 %287 %317 -%319 = OpSampledImage %316 %279 %281 -%320 = OpImageSampleImplicitLod %25 %319 %318 -%321 = OpLoad %25 %271 -%322 = OpFAdd %25 %321 %320 -OpStore %271 %322 -%323 = OpConvertUToF %7 %201 -%324 = OpCompositeConstruct %28 %287 %323 -%325 = OpSampledImage %316 %279 %281 -%326 = OpImageSampleImplicitLod %25 %325 %324 ConstOffset %34 -%327 = OpLoad %25 %271 -%328 = OpFAdd %25 %327 %326 -OpStore %271 %328 -%329 = OpConvertUToF %7 %201 -%330 = OpCompositeConstruct %28 %287 %329 -%331 = OpSampledImage %316 %279 %281 -%332 = OpImageSampleExplicitLod %25 %331 %330 Lod %283 -%333 = OpLoad %25 %271 -%334 = OpFAdd %25 %333 %332 -OpStore %271 %334 -%335 = OpConvertUToF %7 %201 -%336 = OpCompositeConstruct %28 %287 %335 -%337 = OpSampledImage %316 %279 %281 -%338 = OpImageSampleExplicitLod %25 %337 %336 Lod|ConstOffset %283 %34 -%339 = OpLoad %25 %271 -%340 = OpFAdd %25 %339 %338 -OpStore %271 %340 -%341 = OpConvertUToF %7 %201 -%342 = OpCompositeConstruct %28 %287 %341 -%343 = OpSampledImage %316 %279 %281 -%344 = OpImageSampleImplicitLod %25 %343 %342 Bias|ConstOffset %284 %34 -%345 = OpLoad %25 %271 -%346 = OpFAdd %25 %345 %344 -OpStore %271 %346 -%347 = OpConvertSToF %7 %285 -%348 = OpCompositeConstruct %28 %287 %347 -%349 = OpSampledImage %316 %279 %281 -%350 = OpImageSampleImplicitLod %25 %349 %348 -%351 = OpLoad %25 %271 -%352 = OpFAdd %25 %351 %350 -OpStore %271 %352 -%353 = OpConvertSToF %7 %285 -%354 = OpCompositeConstruct %28 %287 %353 -%355 = OpSampledImage %316 %279 %281 -%356 = OpImageSampleImplicitLod %25 %355 %354 ConstOffset %34 -%357 = OpLoad %25 %271 -%358 = OpFAdd %25 %357 %356 -OpStore %271 %358 -%359 = OpConvertSToF %7 %285 -%360 = OpCompositeConstruct %28 %287 %359 -%361 = OpSampledImage %316 %279 %281 -%362 = OpImageSampleExplicitLod %25 %361 %360 Lod %283 -%363 = OpLoad %25 %271 -%364 = OpFAdd %25 %363 %362 -OpStore %271 %364 -%365 = OpConvertSToF %7 %285 -%366 = OpCompositeConstruct %28 %287 %365 -%367 = OpSampledImage %316 %279 %281 -%368 = OpImageSampleExplicitLod %25 %367 %366 Lod|ConstOffset %283 %34 -%369 = OpLoad %25 %271 -%370 = OpFAdd %25 %369 %368 -OpStore %271 %370 -%371 = OpConvertSToF %7 %285 -%372 = OpCompositeConstruct %28 %287 %371 -%373 = OpSampledImage %316 %279 %281 -%374 = OpImageSampleImplicitLod %25 %373 %372 Bias|ConstOffset %284 %34 -%375 = OpLoad %25 %271 -%376 = OpFAdd %25 %375 %374 -OpStore %271 %376 -%378 = OpConvertUToF %7 %201 -%379 = OpCompositeConstruct %25 %288 %378 -%380 = OpSampledImage %377 %280 %281 -%381 = OpImageSampleImplicitLod %25 %380 %379 -%382 = OpLoad %25 %271 -%383 = OpFAdd %25 %382 %381 -OpStore %271 %383 -%384 = OpConvertUToF %7 %201 -%385 = OpCompositeConstruct %25 %288 %384 -%386 = OpSampledImage %377 %280 %281 -%387 = OpImageSampleExplicitLod %25 %386 %385 Lod %283 -%388 = OpLoad %25 %271 -%389 = OpFAdd %25 %388 %387 -OpStore %271 %389 -%390 = OpConvertUToF %7 %201 -%391 = OpCompositeConstruct %25 %288 %390 -%392 = OpSampledImage %377 %280 %281 -%393 = OpImageSampleImplicitLod %25 %392 %391 Bias %284 -%394 = OpLoad %25 %271 -%395 = OpFAdd %25 %394 %393 -OpStore %271 %395 -%396 = OpConvertSToF %7 %285 -%397 = OpCompositeConstruct %25 %288 %396 -%398 = OpSampledImage %377 %280 %281 -%399 = OpImageSampleImplicitLod %25 %398 %397 -%400 = OpLoad %25 %271 -%401 = OpFAdd %25 %400 %399 -OpStore %271 %401 -%402 = OpConvertSToF %7 %285 -%403 = OpCompositeConstruct %25 %288 %402 -%404 = OpSampledImage %377 %280 %281 -%405 = OpImageSampleExplicitLod %25 %404 %403 Lod %283 -%406 = OpLoad %25 %271 -%407 = OpFAdd %25 %406 %405 -OpStore %271 %407 -%408 = OpConvertSToF %7 %285 -%409 = OpCompositeConstruct %25 %288 %408 -%410 = OpSampledImage %377 %280 %281 -%411 = OpImageSampleImplicitLod %25 %410 %409 Bias %284 -%412 = OpLoad %25 %271 -%413 = OpFAdd %25 %412 %411 -OpStore %271 %413 -%414 = OpLoad %25 %271 -OpStore %275 %414 +%274 = OpFunction %2 None %79 +%272 = OpLabel +%269 = OpVariable %270 Function %271 +%275 = OpLoad %15 %47 +%276 = OpLoad %16 %49 +%277 = OpLoad %18 %54 +%278 = OpLoad %20 %58 +%279 = OpLoad %24 %64 +OpBranch %284 +%284 = OpLabel +%286 = OpCompositeConstruct %285 %280 %280 +%288 = OpCompositeConstruct %287 %280 %280 %280 +%289 = OpCompositeExtract %7 %286 0 +%291 = OpSampledImage %290 %275 %279 +%292 = OpImageSampleImplicitLod %23 %291 %289 +%293 = OpLoad %23 %269 +%294 = OpFAdd %23 %293 %292 +OpStore %269 %294 +%296 = OpSampledImage %295 %276 %279 +%297 = OpImageSampleImplicitLod %23 %296 %286 +%298 = OpLoad %23 %269 +%299 = OpFAdd %23 %298 %297 +OpStore %269 %299 +%300 = OpSampledImage %295 %276 %279 +%301 = OpImageSampleImplicitLod %23 %300 %286 ConstOffset %30 +%302 = OpLoad %23 %269 +%303 = OpFAdd %23 %302 %301 +OpStore %269 %303 +%304 = OpSampledImage %295 %276 %279 +%305 = OpImageSampleExplicitLod %23 %304 %286 Lod %281 +%306 = OpLoad %23 %269 +%307 = OpFAdd %23 %306 %305 +OpStore %269 %307 +%308 = OpSampledImage %295 %276 %279 +%309 = OpImageSampleExplicitLod %23 %308 %286 Lod|ConstOffset %281 %30 +%310 = OpLoad %23 %269 +%311 = OpFAdd %23 %310 %309 +OpStore %269 %311 +%312 = OpSampledImage %295 %276 %279 +%313 = OpImageSampleImplicitLod %23 %312 %286 Bias|ConstOffset %282 %30 +%314 = OpLoad %23 %269 +%315 = OpFAdd %23 %314 %313 +OpStore %269 %315 +%317 = OpConvertUToF %7 %199 +%318 = OpCompositeConstruct %287 %286 %317 +%319 = OpSampledImage %316 %277 %279 +%320 = OpImageSampleImplicitLod %23 %319 %318 +%321 = OpLoad %23 %269 +%322 = OpFAdd %23 %321 %320 +OpStore %269 %322 +%323 = OpConvertUToF %7 %199 +%324 = OpCompositeConstruct %287 %286 %323 +%325 = OpSampledImage %316 %277 %279 +%326 = OpImageSampleImplicitLod %23 %325 %324 ConstOffset %30 +%327 = OpLoad %23 %269 +%328 = OpFAdd %23 %327 %326 +OpStore %269 %328 +%329 = OpConvertUToF %7 %199 +%330 = OpCompositeConstruct %287 %286 %329 +%331 = OpSampledImage %316 %277 %279 +%332 = OpImageSampleExplicitLod %23 %331 %330 Lod %281 +%333 = OpLoad %23 %269 +%334 = OpFAdd %23 %333 %332 +OpStore %269 %334 +%335 = OpConvertUToF %7 %199 +%336 = OpCompositeConstruct %287 %286 %335 +%337 = OpSampledImage %316 %277 %279 +%338 = OpImageSampleExplicitLod %23 %337 %336 Lod|ConstOffset %281 %30 +%339 = OpLoad %23 %269 +%340 = OpFAdd %23 %339 %338 +OpStore %269 %340 +%341 = OpConvertUToF %7 %199 +%342 = OpCompositeConstruct %287 %286 %341 +%343 = OpSampledImage %316 %277 %279 +%344 = OpImageSampleImplicitLod %23 %343 %342 Bias|ConstOffset %282 %30 +%345 = OpLoad %23 %269 +%346 = OpFAdd %23 %345 %344 +OpStore %269 %346 +%347 = OpConvertSToF %7 %283 +%348 = OpCompositeConstruct %287 %286 %347 +%349 = OpSampledImage %316 %277 %279 +%350 = OpImageSampleImplicitLod %23 %349 %348 +%351 = OpLoad %23 %269 +%352 = OpFAdd %23 %351 %350 +OpStore %269 %352 +%353 = OpConvertSToF %7 %283 +%354 = OpCompositeConstruct %287 %286 %353 +%355 = OpSampledImage %316 %277 %279 +%356 = OpImageSampleImplicitLod %23 %355 %354 ConstOffset %30 +%357 = OpLoad %23 %269 +%358 = OpFAdd %23 %357 %356 +OpStore %269 %358 +%359 = OpConvertSToF %7 %283 +%360 = OpCompositeConstruct %287 %286 %359 +%361 = OpSampledImage %316 %277 %279 +%362 = OpImageSampleExplicitLod %23 %361 %360 Lod %281 +%363 = OpLoad %23 %269 +%364 = OpFAdd %23 %363 %362 +OpStore %269 %364 +%365 = OpConvertSToF %7 %283 +%366 = OpCompositeConstruct %287 %286 %365 +%367 = OpSampledImage %316 %277 %279 +%368 = OpImageSampleExplicitLod %23 %367 %366 Lod|ConstOffset %281 %30 +%369 = OpLoad %23 %269 +%370 = OpFAdd %23 %369 %368 +OpStore %269 %370 +%371 = OpConvertSToF %7 %283 +%372 = OpCompositeConstruct %287 %286 %371 +%373 = OpSampledImage %316 %277 %279 +%374 = OpImageSampleImplicitLod %23 %373 %372 Bias|ConstOffset %282 %30 +%375 = OpLoad %23 %269 +%376 = OpFAdd %23 %375 %374 +OpStore %269 %376 +%378 = OpConvertUToF %7 %199 +%379 = OpCompositeConstruct %23 %288 %378 +%380 = OpSampledImage %377 %278 %279 +%381 = OpImageSampleImplicitLod %23 %380 %379 +%382 = OpLoad %23 %269 +%383 = OpFAdd %23 %382 %381 +OpStore %269 %383 +%384 = OpConvertUToF %7 %199 +%385 = OpCompositeConstruct %23 %288 %384 +%386 = OpSampledImage %377 %278 %279 +%387 = OpImageSampleExplicitLod %23 %386 %385 Lod %281 +%388 = OpLoad %23 %269 +%389 = OpFAdd %23 %388 %387 +OpStore %269 %389 +%390 = OpConvertUToF %7 %199 +%391 = OpCompositeConstruct %23 %288 %390 +%392 = OpSampledImage %377 %278 %279 +%393 = OpImageSampleImplicitLod %23 %392 %391 Bias %282 +%394 = OpLoad %23 %269 +%395 = OpFAdd %23 %394 %393 +OpStore %269 %395 +%396 = OpConvertSToF %7 %283 +%397 = OpCompositeConstruct %23 %288 %396 +%398 = OpSampledImage %377 %278 %279 +%399 = OpImageSampleImplicitLod %23 %398 %397 +%400 = OpLoad %23 %269 +%401 = OpFAdd %23 %400 %399 +OpStore %269 %401 +%402 = OpConvertSToF %7 %283 +%403 = OpCompositeConstruct %23 %288 %402 +%404 = OpSampledImage %377 %278 %279 +%405 = OpImageSampleExplicitLod %23 %404 %403 Lod %281 +%406 = OpLoad %23 %269 +%407 = OpFAdd %23 %406 %405 +OpStore %269 %407 +%408 = OpConvertSToF %7 %283 +%409 = OpCompositeConstruct %23 %288 %408 +%410 = OpSampledImage %377 %278 %279 +%411 = OpImageSampleImplicitLod %23 %410 %409 Bias %282 +%412 = OpLoad %23 %269 +%413 = OpFAdd %23 %412 %411 +OpStore %269 %413 +%414 = OpLoad %23 %269 +OpStore %273 %414 OpReturn OpFunctionEnd -%421 = OpFunction %2 None %83 +%421 = OpFunction %2 None %79 %418 = OpLabel %415 = OpVariable %416 Function %417 -%422 = OpLoad %26 %70 -%423 = OpLoad %29 %72 -%424 = OpLoad %30 %74 -%425 = OpLoad %31 %76 +%422 = OpLoad %24 %66 +%423 = OpLoad %25 %68 +%424 = OpLoad %26 %70 +%425 = OpLoad %27 %72 OpBranch %426 %426 = OpLabel -%427 = OpCompositeConstruct %27 %282 %282 -%428 = OpCompositeConstruct %28 %282 %282 %282 +%427 = OpCompositeConstruct %285 %280 %280 +%428 = OpCompositeConstruct %287 %280 %280 %280 %430 = OpSampledImage %429 %423 %422 -%431 = OpImageSampleDrefImplicitLod %7 %430 %427 %282 +%431 = OpImageSampleDrefImplicitLod %7 %430 %427 %280 %432 = OpLoad %7 %415 %433 = OpFAdd %7 %432 %431 OpStore %415 %433 -%435 = OpConvertUToF %7 %201 -%436 = OpCompositeConstruct %28 %427 %435 +%435 = OpConvertUToF %7 %199 +%436 = OpCompositeConstruct %287 %427 %435 %437 = OpSampledImage %434 %424 %422 -%438 = OpImageSampleDrefImplicitLod %7 %437 %436 %282 +%438 = OpImageSampleDrefImplicitLod %7 %437 %436 %280 %439 = OpLoad %7 %415 %440 = OpFAdd %7 %439 %438 OpStore %415 %440 -%441 = OpConvertSToF %7 %285 -%442 = OpCompositeConstruct %28 %427 %441 +%441 = OpConvertSToF %7 %283 +%442 = OpCompositeConstruct %287 %427 %441 %443 = OpSampledImage %434 %424 %422 -%444 = OpImageSampleDrefImplicitLod %7 %443 %442 %282 +%444 = OpImageSampleDrefImplicitLod %7 %443 %442 %280 %445 = OpLoad %7 %415 %446 = OpFAdd %7 %445 %444 OpStore %415 %446 %448 = OpSampledImage %447 %425 %422 -%449 = OpImageSampleDrefImplicitLod %7 %448 %428 %282 +%449 = OpImageSampleDrefImplicitLod %7 %448 %428 %280 %450 = OpLoad %7 %415 %451 = OpFAdd %7 %450 %449 OpStore %415 %451 %452 = OpSampledImage %429 %423 %422 -%453 = OpImageSampleDrefExplicitLod %7 %452 %427 %282 Lod %454 +%453 = OpImageSampleDrefExplicitLod %7 %452 %427 %280 Lod %454 %455 = OpLoad %7 %415 %456 = OpFAdd %7 %455 %453 OpStore %415 %456 -%457 = OpConvertUToF %7 %201 -%458 = OpCompositeConstruct %28 %427 %457 +%457 = OpConvertUToF %7 %199 +%458 = OpCompositeConstruct %287 %427 %457 %459 = OpSampledImage %434 %424 %422 -%460 = OpImageSampleDrefExplicitLod %7 %459 %458 %282 Lod %454 +%460 = OpImageSampleDrefExplicitLod %7 %459 %458 %280 Lod %454 %461 = OpLoad %7 %415 %462 = OpFAdd %7 %461 %460 OpStore %415 %462 -%463 = OpConvertSToF %7 %285 -%464 = OpCompositeConstruct %28 %427 %463 +%463 = OpConvertSToF %7 %283 +%464 = OpCompositeConstruct %287 %427 %463 %465 = OpSampledImage %434 %424 %422 -%466 = OpImageSampleDrefExplicitLod %7 %465 %464 %282 Lod %454 +%466 = OpImageSampleDrefExplicitLod %7 %465 %464 %280 Lod %454 %467 = OpLoad %7 %415 %468 = OpFAdd %7 %467 %466 OpStore %415 %468 %469 = OpSampledImage %447 %425 %422 -%470 = OpImageSampleDrefExplicitLod %7 %469 %428 %282 Lod %454 +%470 = OpImageSampleDrefExplicitLod %7 %469 %428 %280 Lod %454 %471 = OpLoad %7 %415 %472 = OpFAdd %7 %471 %470 OpStore %415 %472 @@ -645,53 +645,53 @@ OpStore %415 %472 OpStore %419 %473 OpReturn OpFunctionEnd -%476 = OpFunction %2 None %83 +%476 = OpFunction %2 None %79 %474 = OpLabel -%477 = OpLoad %18 %53 -%478 = OpLoad %3 %55 -%479 = OpLoad %19 %56 -%480 = OpLoad %26 %68 -%481 = OpLoad %26 %70 -%482 = OpLoad %29 %72 +%477 = OpLoad %16 %49 +%478 = OpLoad %3 %51 +%479 = OpLoad %17 %52 +%480 = OpLoad %24 %64 +%481 = OpLoad %24 %66 +%482 = OpLoad %25 %68 OpBranch %483 %483 = OpLabel -%484 = OpCompositeConstruct %27 %282 %282 +%484 = OpCompositeConstruct %285 %280 %280 %485 = OpSampledImage %295 %477 %480 -%486 = OpImageGather %25 %485 %484 %487 +%486 = OpImageGather %23 %485 %484 %487 %488 = OpSampledImage %295 %477 %480 -%489 = OpImageGather %25 %488 %484 %490 ConstOffset %34 +%489 = OpImageGather %23 %488 %484 %490 ConstOffset %30 %491 = OpSampledImage %429 %482 %481 -%492 = OpImageDrefGather %25 %491 %484 %282 +%492 = OpImageDrefGather %23 %491 %484 %280 %493 = OpSampledImage %429 %482 %481 -%494 = OpImageDrefGather %25 %493 %484 %282 ConstOffset %34 +%494 = OpImageDrefGather %23 %493 %484 %280 ConstOffset %30 %496 = OpSampledImage %495 %478 %480 -%497 = OpImageGather %16 %496 %484 %201 +%497 = OpImageGather %98 %496 %484 %199 %500 = OpSampledImage %499 %479 %480 -%501 = OpImageGather %498 %500 %484 %201 -%502 = OpConvertUToF %25 %497 -%503 = OpConvertSToF %25 %501 -%504 = OpFAdd %25 %502 %503 -%505 = OpFAdd %25 %486 %489 -%506 = OpFAdd %25 %505 %492 -%507 = OpFAdd %25 %506 %494 -%508 = OpFAdd %25 %507 %504 +%501 = OpImageGather %498 %500 %484 %199 +%502 = OpConvertUToF %23 %497 +%503 = OpConvertSToF %23 %501 +%504 = OpFAdd %23 %502 %503 +%505 = OpFAdd %23 %486 %489 +%506 = OpFAdd %23 %505 %492 +%507 = OpFAdd %23 %506 %494 +%508 = OpFAdd %23 %507 %504 OpStore %475 %508 OpReturn OpFunctionEnd -%511 = OpFunction %2 None %83 +%511 = OpFunction %2 None %79 %509 = OpLabel -%512 = OpLoad %26 %68 -%513 = OpLoad %29 %72 +%512 = OpLoad %24 %64 +%513 = OpLoad %25 %68 OpBranch %514 %514 = OpLabel -%515 = OpCompositeConstruct %27 %282 %282 +%515 = OpCompositeConstruct %285 %280 %280 %516 = OpSampledImage %429 %513 %512 -%517 = OpImageSampleImplicitLod %25 %516 %515 +%517 = OpImageSampleImplicitLod %23 %516 %515 %518 = OpCompositeExtract %7 %517 0 %519 = OpSampledImage %429 %513 %512 -%520 = OpImageGather %25 %519 %515 %201 -%521 = OpCompositeConstruct %25 %518 %518 %518 %518 -%522 = OpFAdd %25 %521 %520 +%520 = OpImageGather %23 %519 %515 %199 +%521 = OpCompositeConstruct %23 %518 %518 %518 %518 +%522 = OpFAdd %23 %521 %520 OpStore %510 %522 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.compute.spvasm b/tests/out/spv/interface.compute.spvasm index df5e3edda..73f6ecb2c 100644 --- a/tests/out/spv/interface.compute.spvasm +++ b/tests/out/spv/interface.compute.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 55 +; Bound: 53 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %31 "compute" %19 %22 %24 %27 %29 -OpExecutionMode %31 LocalSize 1 1 1 +OpEntryPoint GLCompute %29 "compute" %17 %20 %22 %25 %27 +OpExecutionMode %29 LocalSize 1 1 1 OpMemberDecorate %5 0 Offset 0 OpMemberDecorate %5 1 Offset 16 OpMemberDecorate %7 0 Offset 0 @@ -15,11 +15,11 @@ OpMemberDecorate %7 2 Offset 8 OpDecorate %9 ArrayStride 4 OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %13 0 Offset 0 -OpDecorate %19 BuiltIn GlobalInvocationId -OpDecorate %22 BuiltIn LocalInvocationId -OpDecorate %24 BuiltIn LocalInvocationIndex -OpDecorate %27 BuiltIn WorkgroupId -OpDecorate %29 BuiltIn NumWorkgroups +OpDecorate %17 BuiltIn GlobalInvocationId +OpDecorate %20 BuiltIn LocalInvocationId +OpDecorate %22 BuiltIn LocalInvocationIndex +OpDecorate %25 BuiltIn WorkgroupId +OpDecorate %27 BuiltIn NumWorkgroups %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -32,54 +32,52 @@ OpDecorate %29 BuiltIn NumWorkgroups %11 = OpTypeVector %6 3 %12 = OpTypeStruct %6 %13 = OpTypeStruct %6 -%15 = OpTypeInt 32 1 -%14 = OpConstant %15 1 -%17 = OpTypePointer Workgroup %9 -%16 = OpVariable %17 Workgroup -%20 = OpTypePointer Input %11 -%19 = OpVariable %20 Input -%22 = OpVariable %20 Input -%25 = OpTypePointer Input %6 -%24 = OpVariable %25 Input -%27 = OpVariable %20 Input -%29 = OpVariable %20 Input -%32 = OpTypeFunction %2 -%34 = OpConstantNull %9 -%35 = OpConstantNull %11 -%36 = OpTypeVector %8 3 -%41 = OpConstant %6 2 -%42 = OpConstant %6 264 -%44 = OpTypePointer Workgroup %6 -%53 = OpConstant %6 0 -%31 = OpFunction %2 None %32 -%18 = OpLabel -%21 = OpLoad %11 %19 -%23 = OpLoad %11 %22 -%26 = OpLoad %6 %24 +%15 = OpTypePointer Workgroup %9 +%14 = OpVariable %15 Workgroup +%18 = OpTypePointer Input %11 +%17 = OpVariable %18 Input +%20 = OpVariable %18 Input +%23 = OpTypePointer Input %6 +%22 = OpVariable %23 Input +%25 = OpVariable %18 Input +%27 = OpVariable %18 Input +%30 = OpTypeFunction %2 +%32 = OpConstantNull %9 +%33 = OpConstantNull %11 +%34 = OpTypeVector %8 3 +%39 = OpConstant %6 2 +%40 = OpConstant %6 264 +%42 = OpTypePointer Workgroup %6 +%51 = OpConstant %6 0 +%29 = OpFunction %2 None %30 +%16 = OpLabel +%19 = OpLoad %11 %17 +%21 = OpLoad %11 %20 +%24 = OpLoad %6 %22 +%26 = OpLoad %11 %25 %28 = OpLoad %11 %27 -%30 = OpLoad %11 %29 -OpBranch %33 -%33 = OpLabel -%37 = OpIEqual %36 %23 %35 -%38 = OpAll %8 %37 -OpSelectionMerge %39 None -OpBranchConditional %38 %40 %39 -%40 = OpLabel -OpStore %16 %34 -OpBranch %39 -%39 = OpLabel -OpControlBarrier %41 %41 %42 -OpBranch %43 -%43 = OpLabel -%45 = OpCompositeExtract %6 %21 0 -%46 = OpCompositeExtract %6 %23 0 -%47 = OpIAdd %6 %45 %46 -%48 = OpIAdd %6 %47 %26 +OpBranch %31 +%31 = OpLabel +%35 = OpIEqual %34 %21 %33 +%36 = OpAll %8 %35 +OpSelectionMerge %37 None +OpBranchConditional %36 %38 %37 +%38 = OpLabel +OpStore %14 %32 +OpBranch %37 +%37 = OpLabel +OpControlBarrier %39 %39 %40 +OpBranch %41 +%41 = OpLabel +%43 = OpCompositeExtract %6 %19 0 +%44 = OpCompositeExtract %6 %21 0 +%45 = OpIAdd %6 %43 %44 +%46 = OpIAdd %6 %45 %24 +%47 = OpCompositeExtract %6 %26 0 +%48 = OpIAdd %6 %46 %47 %49 = OpCompositeExtract %6 %28 0 %50 = OpIAdd %6 %48 %49 -%51 = OpCompositeExtract %6 %30 0 -%52 = OpIAdd %6 %50 %51 -%54 = OpAccessChain %44 %16 %53 -OpStore %54 %52 +%52 = OpAccessChain %42 %14 %51 +OpStore %52 %50 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.fragment.spvasm b/tests/out/spv/interface.fragment.spvasm index 6acbab9d7..bb42c678e 100644 --- a/tests/out/spv/interface.fragment.spvasm +++ b/tests/out/spv/interface.fragment.spvasm @@ -1,14 +1,14 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 52 +; Bound: 50 OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %37 "fragment" %18 %21 %24 %27 %30 %32 %34 %36 -OpExecutionMode %37 OriginUpperLeft -OpExecutionMode %37 DepthReplacing +OpEntryPoint Fragment %35 "fragment" %16 %19 %22 %25 %28 %30 %32 %34 +OpExecutionMode %35 OriginUpperLeft +OpExecutionMode %35 DepthReplacing OpMemberDecorate %5 0 Offset 0 OpMemberDecorate %5 1 Offset 16 OpMemberDecorate %7 0 Offset 0 @@ -17,18 +17,18 @@ OpMemberDecorate %7 2 Offset 8 OpDecorate %9 ArrayStride 4 OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %13 0 Offset 0 -OpDecorate %18 Invariant -OpDecorate %18 BuiltIn FragCoord -OpDecorate %21 Location 1 -OpDecorate %24 BuiltIn FrontFacing -OpDecorate %24 Flat -OpDecorate %27 BuiltIn SampleId -OpDecorate %27 Flat -OpDecorate %30 BuiltIn SampleMask -OpDecorate %30 Flat -OpDecorate %32 BuiltIn FragDepth -OpDecorate %34 BuiltIn SampleMask -OpDecorate %36 Location 0 +OpDecorate %16 Invariant +OpDecorate %16 BuiltIn FragCoord +OpDecorate %19 Location 1 +OpDecorate %22 BuiltIn FrontFacing +OpDecorate %22 Flat +OpDecorate %25 BuiltIn SampleId +OpDecorate %25 Flat +OpDecorate %28 BuiltIn SampleMask +OpDecorate %28 Flat +OpDecorate %30 BuiltIn FragDepth +OpDecorate %32 BuiltIn SampleMask +OpDecorate %34 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -41,48 +41,46 @@ OpDecorate %36 Location 0 %11 = OpTypeVector %6 3 %12 = OpTypeStruct %6 %13 = OpTypeStruct %6 -%15 = OpTypeInt 32 1 -%14 = OpConstant %15 1 -%19 = OpTypePointer Input %3 -%18 = OpVariable %19 Input -%22 = OpTypePointer Input %4 -%21 = OpVariable %22 Input -%25 = OpTypePointer Input %8 -%24 = OpVariable %25 Input -%28 = OpTypePointer Input %6 -%27 = OpVariable %28 Input -%30 = OpVariable %28 Input -%33 = OpTypePointer Output %4 +%17 = OpTypePointer Input %3 +%16 = OpVariable %17 Input +%20 = OpTypePointer Input %4 +%19 = OpVariable %20 Input +%23 = OpTypePointer Input %8 +%22 = OpVariable %23 Input +%26 = OpTypePointer Input %6 +%25 = OpVariable %26 Input +%28 = OpVariable %26 Input +%31 = OpTypePointer Output %4 +%30 = OpVariable %31 Output +%33 = OpTypePointer Output %6 %32 = OpVariable %33 Output -%35 = OpTypePointer Output %6 -%34 = OpVariable %35 Output -%36 = OpVariable %33 Output -%38 = OpTypeFunction %2 -%39 = OpConstant %4 0.0 -%40 = OpConstant %4 1.0 -%37 = OpFunction %2 None %38 -%16 = OpLabel -%20 = OpLoad %3 %18 -%23 = OpLoad %4 %21 -%17 = OpCompositeConstruct %5 %20 %23 -%26 = OpLoad %8 %24 -%29 = OpLoad %6 %27 -%31 = OpLoad %6 %30 -OpBranch %41 -%41 = OpLabel -%42 = OpShiftLeftLogical %6 %10 %29 -%43 = OpBitwiseAnd %6 %31 %42 -%44 = OpSelect %4 %26 %40 %39 -%45 = OpCompositeExtract %4 %17 1 -%46 = OpCompositeConstruct %7 %45 %43 %44 -%47 = OpCompositeExtract %4 %46 0 -OpStore %32 %47 -%48 = OpLoad %4 %32 -%49 = OpExtInst %4 %1 FClamp %48 %39 %40 -OpStore %32 %49 -%50 = OpCompositeExtract %6 %46 1 -OpStore %34 %50 -%51 = OpCompositeExtract %4 %46 2 -OpStore %36 %51 +%34 = OpVariable %31 Output +%36 = OpTypeFunction %2 +%37 = OpConstant %4 0.0 +%38 = OpConstant %4 1.0 +%35 = OpFunction %2 None %36 +%14 = OpLabel +%18 = OpLoad %3 %16 +%21 = OpLoad %4 %19 +%15 = OpCompositeConstruct %5 %18 %21 +%24 = OpLoad %8 %22 +%27 = OpLoad %6 %25 +%29 = OpLoad %6 %28 +OpBranch %39 +%39 = OpLabel +%40 = OpShiftLeftLogical %6 %10 %27 +%41 = OpBitwiseAnd %6 %29 %40 +%42 = OpSelect %4 %24 %38 %37 +%43 = OpCompositeExtract %4 %15 1 +%44 = OpCompositeConstruct %7 %43 %41 %42 +%45 = OpCompositeExtract %4 %44 0 +OpStore %30 %45 +%46 = OpLoad %4 %30 +%47 = OpExtInst %4 %1 FClamp %46 %37 %38 +OpStore %30 %47 +%48 = OpCompositeExtract %6 %44 1 +OpStore %32 %48 +%49 = OpCompositeExtract %4 %44 2 +OpStore %34 %49 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index 6e930aa01..d2c949296 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -1,11 +1,11 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 41 +; Bound: 39 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %31 "vertex" %17 %20 %22 %24 %26 %28 +OpEntryPoint Vertex %29 "vertex" %15 %18 %20 %22 %24 %26 OpMemberDecorate %5 0 Offset 0 OpMemberDecorate %5 1 Offset 16 OpMemberDecorate %7 0 Offset 0 @@ -14,13 +14,13 @@ OpMemberDecorate %7 2 Offset 8 OpDecorate %9 ArrayStride 4 OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %13 0 Offset 0 -OpDecorate %17 BuiltIn VertexIndex -OpDecorate %20 BuiltIn InstanceIndex -OpDecorate %22 Location 10 -OpDecorate %24 Invariant -OpDecorate %24 BuiltIn Position -OpDecorate %26 Location 1 -OpDecorate %28 BuiltIn PointSize +OpDecorate %15 BuiltIn VertexIndex +OpDecorate %18 BuiltIn InstanceIndex +OpDecorate %20 Location 10 +OpDecorate %22 Invariant +OpDecorate %22 BuiltIn Position +OpDecorate %24 Location 1 +OpDecorate %26 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -33,36 +33,34 @@ OpDecorate %28 BuiltIn PointSize %11 = OpTypeVector %6 3 %12 = OpTypeStruct %6 %13 = OpTypeStruct %6 -%15 = OpTypeInt 32 1 -%14 = OpConstant %15 1 -%18 = OpTypePointer Input %6 -%17 = OpVariable %18 Input -%20 = OpVariable %18 Input -%22 = OpVariable %18 Input -%25 = OpTypePointer Output %3 +%16 = OpTypePointer Input %6 +%15 = OpVariable %16 Input +%18 = OpVariable %16 Input +%20 = OpVariable %16 Input +%23 = OpTypePointer Output %3 +%22 = OpVariable %23 Output +%25 = OpTypePointer Output %4 %24 = OpVariable %25 Output %27 = OpTypePointer Output %4 %26 = OpVariable %27 Output -%29 = OpTypePointer Output %4 -%28 = OpVariable %29 Output -%30 = OpConstant %4 1.0 -%32 = OpTypeFunction %2 -%31 = OpFunction %2 None %32 -%16 = OpLabel -%19 = OpLoad %6 %17 +%28 = OpConstant %4 1.0 +%30 = OpTypeFunction %2 +%29 = OpFunction %2 None %30 +%14 = OpLabel +%17 = OpLoad %6 %15 +%19 = OpLoad %6 %18 %21 = OpLoad %6 %20 -%23 = OpLoad %6 %22 -OpStore %28 %30 -OpBranch %33 -%33 = OpLabel -%34 = OpIAdd %6 %19 %21 -%35 = OpIAdd %6 %34 %23 -%36 = OpCompositeConstruct %3 %30 %30 %30 %30 -%37 = OpConvertUToF %4 %35 -%38 = OpCompositeConstruct %5 %36 %37 -%39 = OpCompositeExtract %3 %38 0 -OpStore %24 %39 -%40 = OpCompositeExtract %4 %38 1 -OpStore %26 %40 +OpStore %26 %28 +OpBranch %31 +%31 = OpLabel +%32 = OpIAdd %6 %17 %19 +%33 = OpIAdd %6 %32 %21 +%34 = OpCompositeConstruct %3 %28 %28 %28 %28 +%35 = OpConvertUToF %4 %33 +%36 = OpCompositeConstruct %5 %34 %35 +%37 = OpCompositeExtract %3 %36 0 +OpStore %22 %37 +%38 = OpCompositeExtract %4 %36 1 +OpStore %24 %38 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index db2bf9b99..505c55843 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -1,11 +1,11 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 44 +; Bound: 42 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %32 "vertex_two_structs" %21 %25 %27 %29 +OpEntryPoint Vertex %30 "vertex_two_structs" %19 %23 %25 %27 OpMemberDecorate %5 0 Offset 0 OpMemberDecorate %5 1 Offset 16 OpMemberDecorate %7 0 Offset 0 @@ -14,11 +14,11 @@ OpMemberDecorate %7 2 Offset 8 OpDecorate %9 ArrayStride 4 OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %13 0 Offset 0 -OpDecorate %21 BuiltIn VertexIndex -OpDecorate %25 BuiltIn InstanceIndex -OpDecorate %27 Invariant -OpDecorate %27 BuiltIn Position -OpDecorate %29 BuiltIn PointSize +OpDecorate %19 BuiltIn VertexIndex +OpDecorate %23 BuiltIn InstanceIndex +OpDecorate %25 Invariant +OpDecorate %25 BuiltIn Position +OpDecorate %27 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -31,39 +31,37 @@ OpDecorate %29 BuiltIn PointSize %11 = OpTypeVector %6 3 %12 = OpTypeStruct %6 %13 = OpTypeStruct %6 -%15 = OpTypeInt 32 1 -%14 = OpConstant %15 1 -%17 = OpTypePointer Function %6 -%18 = OpConstantNull %6 -%22 = OpTypePointer Input %6 -%21 = OpVariable %22 Input -%25 = OpVariable %22 Input -%28 = OpTypePointer Output %3 +%15 = OpTypePointer Function %6 +%16 = OpConstantNull %6 +%20 = OpTypePointer Input %6 +%19 = OpVariable %20 Input +%23 = OpVariable %20 Input +%26 = OpTypePointer Output %3 +%25 = OpVariable %26 Output +%28 = OpTypePointer Output %4 %27 = OpVariable %28 Output -%30 = OpTypePointer Output %4 -%29 = OpVariable %30 Output -%31 = OpConstant %4 1.0 -%33 = OpTypeFunction %2 -%34 = OpConstant %6 2 -%35 = OpConstant %4 0.0 -%32 = OpFunction %2 None %33 -%19 = OpLabel -%16 = OpVariable %17 Function %18 -%23 = OpLoad %6 %21 -%20 = OpCompositeConstruct %12 %23 -%26 = OpLoad %6 %25 -%24 = OpCompositeConstruct %13 %26 -OpStore %29 %31 -OpBranch %36 -%36 = OpLabel -OpStore %16 %34 -%37 = OpCompositeExtract %6 %20 0 +%29 = OpConstant %4 1.0 +%31 = OpTypeFunction %2 +%32 = OpConstant %6 2 +%33 = OpConstant %4 0.0 +%30 = OpFunction %2 None %31 +%17 = OpLabel +%14 = OpVariable %15 Function %16 +%21 = OpLoad %6 %19 +%18 = OpCompositeConstruct %12 %21 +%24 = OpLoad %6 %23 +%22 = OpCompositeConstruct %13 %24 +OpStore %27 %29 +OpBranch %34 +%34 = OpLabel +OpStore %14 %32 +%35 = OpCompositeExtract %6 %18 0 +%36 = OpConvertUToF %4 %35 +%37 = OpCompositeExtract %6 %22 0 %38 = OpConvertUToF %4 %37 -%39 = OpCompositeExtract %6 %24 0 +%39 = OpLoad %6 %14 %40 = OpConvertUToF %4 %39 -%41 = OpLoad %6 %16 -%42 = OpConvertUToF %4 %41 -%43 = OpCompositeConstruct %3 %38 %40 %42 %35 -OpStore %27 %43 +%41 = OpCompositeConstruct %3 %36 %38 %40 %33 +OpStore %25 %41 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 6544cfd40..71bd913f7 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -16,51 +16,51 @@ OpExecutionMode %511 LocalSize 1 1 1 %7 = OpTypeVector %8 4 %9 = OpTypeVector %4 2 %10 = OpTypeVector %4 3 -%11 = OpTypeVector %8 3 -%12 = OpTypeMatrix %10 3 -%13 = OpTypeMatrix %10 4 -%14 = OpTypeMatrix %3 3 -%15 = OpTypeVector %6 3 -%16 = OpConstant %4 1.0 -%17 = OpConstantComposite %3 %16 %16 %16 %16 -%18 = OpConstant %4 0.0 -%19 = OpConstantComposite %3 %18 %18 %18 %18 -%20 = OpConstant %4 0.5 -%21 = OpConstantComposite %3 %20 %20 %20 %20 -%22 = OpConstant %6 1 -%23 = OpConstantComposite %5 %22 %22 %22 %22 -%26 = OpTypeFunction %3 -%27 = OpConstantTrue %8 -%28 = OpConstant %6 0 -%29 = OpConstantFalse %8 -%30 = OpConstant %4 0.1 -%55 = OpConstant %4 2.0 -%56 = OpConstant %4 3.0 -%57 = OpConstant %4 4.0 -%58 = OpConstant %6 5 -%59 = OpConstant %6 2 -%75 = OpTypePointer Function %9 -%76 = OpConstantNull %9 -%79 = OpTypeFunction %9 -%95 = OpTypeFunction %10 %10 -%97 = OpConstantComposite %10 %18 %18 %18 -%99 = OpConstantComposite %10 %16 %16 %16 +%11 = OpTypeMatrix %10 3 +%12 = OpTypeMatrix %10 4 +%13 = OpTypeMatrix %3 3 +%14 = OpTypeVector %6 3 +%15 = OpConstant %4 1.0 +%16 = OpConstantComposite %3 %15 %15 %15 %15 +%17 = OpConstant %4 0.0 +%18 = OpConstantComposite %3 %17 %17 %17 %17 +%19 = OpConstant %4 0.5 +%20 = OpConstantComposite %3 %19 %19 %19 %19 +%21 = OpConstant %6 1 +%22 = OpConstantComposite %5 %21 %21 %21 %21 +%25 = OpTypeFunction %3 +%26 = OpConstantTrue %8 +%27 = OpConstant %6 0 +%28 = OpConstantFalse %8 +%29 = OpConstant %4 0.1 +%54 = OpConstant %4 2.0 +%55 = OpConstant %4 3.0 +%56 = OpConstant %4 4.0 +%57 = OpConstant %6 5 +%58 = OpConstant %6 2 +%74 = OpTypePointer Function %9 +%75 = OpConstantNull %9 +%78 = OpTypeFunction %9 +%94 = OpTypeFunction %10 %10 +%96 = OpTypeVector %8 3 +%97 = OpConstantComposite %10 %17 %17 %17 +%99 = OpConstantComposite %10 %15 %15 %15 %103 = OpTypeFunction %2 %106 = OpTypeVector %8 2 %121 = OpConstant %4 -1.0 %122 = OpTypeInt 32 0 %123 = OpConstant %122 2 %124 = OpConstant %122 1 -%125 = OpConstantNull %12 -%126 = OpConstantNull %13 -%127 = OpConstantNull %14 +%125 = OpConstantNull %11 +%126 = OpConstantNull %12 +%127 = OpConstantNull %13 %129 = OpTypeVector %6 2 %140 = OpTypeVector %122 3 %203 = OpTypeVector %122 2 %438 = OpTypePointer Function %6 %439 = OpConstantNull %6 -%441 = OpTypePointer Function %15 -%442 = OpConstantNull %15 +%441 = OpTypePointer Function %14 +%442 = OpConstantNull %14 %472 = OpTypePointer Function %6 %483 = OpConstant %6 -1 %484 = OpConstant %6 -2 @@ -70,80 +70,80 @@ OpExecutionMode %511 LocalSize 1 1 1 %488 = OpConstant %6 6 %489 = OpConstant %6 -7 %490 = OpConstant %6 -8 -%25 = OpFunction %3 None %26 -%24 = OpLabel -OpBranch %31 -%31 = OpLabel -%32 = OpSelect %6 %27 %22 %28 -%34 = OpCompositeConstruct %7 %27 %27 %27 %27 -%33 = OpSelect %3 %34 %17 %19 -%35 = OpCompositeConstruct %7 %29 %29 %29 %29 -%36 = OpSelect %3 %35 %19 %17 -%37 = OpExtInst %3 %1 FMix %19 %17 %21 -%39 = OpCompositeConstruct %3 %30 %30 %30 %30 -%38 = OpExtInst %3 %1 FMix %19 %17 %39 -%40 = OpCompositeExtract %6 %23 0 -%41 = OpBitcast %4 %40 -%42 = OpBitcast %3 %23 -%43 = OpConvertFToS %5 %19 -%44 = OpCompositeConstruct %5 %32 %32 %32 %32 -%45 = OpIAdd %5 %44 %43 -%46 = OpConvertSToF %3 %45 -%47 = OpFAdd %3 %46 %33 +%24 = OpFunction %3 None %25 +%23 = OpLabel +OpBranch %30 +%30 = OpLabel +%31 = OpSelect %6 %26 %21 %27 +%33 = OpCompositeConstruct %7 %26 %26 %26 %26 +%32 = OpSelect %3 %33 %16 %18 +%34 = OpCompositeConstruct %7 %28 %28 %28 %28 +%35 = OpSelect %3 %34 %18 %16 +%36 = OpExtInst %3 %1 FMix %18 %16 %20 +%38 = OpCompositeConstruct %3 %29 %29 %29 %29 +%37 = OpExtInst %3 %1 FMix %18 %16 %38 +%39 = OpCompositeExtract %6 %22 0 +%40 = OpBitcast %4 %39 +%41 = OpBitcast %3 %22 +%42 = OpConvertFToS %5 %18 +%43 = OpCompositeConstruct %5 %31 %31 %31 %31 +%44 = OpIAdd %5 %43 %42 +%45 = OpConvertSToF %3 %44 +%46 = OpFAdd %3 %45 %32 +%47 = OpFAdd %3 %46 %36 %48 = OpFAdd %3 %47 %37 -%49 = OpFAdd %3 %48 %38 -%50 = OpCompositeConstruct %3 %41 %41 %41 %41 -%51 = OpFAdd %3 %49 %50 -%52 = OpFAdd %3 %51 %42 -OpReturnValue %52 +%49 = OpCompositeConstruct %3 %40 %40 %40 %40 +%50 = OpFAdd %3 %48 %49 +%51 = OpFAdd %3 %50 %41 +OpReturnValue %51 OpFunctionEnd -%54 = OpFunction %3 None %26 -%53 = OpLabel -OpBranch %60 -%60 = OpLabel -%61 = OpCompositeConstruct %9 %55 %55 -%62 = OpCompositeConstruct %9 %16 %16 -%63 = OpFAdd %9 %62 %61 -%64 = OpCompositeConstruct %9 %56 %56 -%65 = OpFSub %9 %63 %64 -%66 = OpCompositeConstruct %9 %57 %57 -%67 = OpFDiv %9 %65 %66 +%53 = OpFunction %3 None %25 +%52 = OpLabel +OpBranch %59 +%59 = OpLabel +%60 = OpCompositeConstruct %9 %54 %54 +%61 = OpCompositeConstruct %9 %15 %15 +%62 = OpFAdd %9 %61 %60 +%63 = OpCompositeConstruct %9 %55 %55 +%64 = OpFSub %9 %62 %63 +%65 = OpCompositeConstruct %9 %56 %56 +%66 = OpFDiv %9 %64 %65 +%67 = OpCompositeConstruct %5 %57 %57 %57 %57 %68 = OpCompositeConstruct %5 %58 %58 %58 %58 -%69 = OpCompositeConstruct %5 %59 %59 %59 %59 -%70 = OpSRem %5 %68 %69 -%71 = OpVectorShuffle %3 %67 %67 0 1 0 1 -%72 = OpConvertSToF %3 %70 -%73 = OpFAdd %3 %71 %72 -OpReturnValue %73 +%69 = OpSRem %5 %67 %68 +%70 = OpVectorShuffle %3 %66 %66 0 1 0 1 +%71 = OpConvertSToF %3 %69 +%72 = OpFAdd %3 %70 %71 +OpReturnValue %72 OpFunctionEnd -%78 = OpFunction %9 None %79 -%77 = OpLabel -%74 = OpVariable %75 Function %76 -OpBranch %80 -%80 = OpLabel -%81 = OpCompositeConstruct %9 %55 %55 -OpStore %74 %81 -%82 = OpLoad %9 %74 -%83 = OpCompositeConstruct %9 %16 %16 -%84 = OpFAdd %9 %82 %83 -OpStore %74 %84 -%85 = OpLoad %9 %74 -%86 = OpCompositeConstruct %9 %56 %56 -%87 = OpFSub %9 %85 %86 -OpStore %74 %87 -%88 = OpLoad %9 %74 -%89 = OpCompositeConstruct %9 %57 %57 -%90 = OpFDiv %9 %88 %89 -OpStore %74 %90 -%91 = OpLoad %9 %74 -OpReturnValue %91 +%77 = OpFunction %9 None %78 +%76 = OpLabel +%73 = OpVariable %74 Function %75 +OpBranch %79 +%79 = OpLabel +%80 = OpCompositeConstruct %9 %54 %54 +OpStore %73 %80 +%81 = OpLoad %9 %73 +%82 = OpCompositeConstruct %9 %15 %15 +%83 = OpFAdd %9 %81 %82 +OpStore %73 %83 +%84 = OpLoad %9 %73 +%85 = OpCompositeConstruct %9 %55 %55 +%86 = OpFSub %9 %84 %85 +OpStore %73 %86 +%87 = OpLoad %9 %73 +%88 = OpCompositeConstruct %9 %56 %56 +%89 = OpFDiv %9 %87 %88 +OpStore %73 %89 +%90 = OpLoad %9 %73 +OpReturnValue %90 OpFunctionEnd -%94 = OpFunction %10 None %95 -%93 = OpFunctionParameter %10 -%92 = OpLabel -OpBranch %96 -%96 = OpLabel -%98 = OpFUnordNotEqual %11 %93 %97 +%93 = OpFunction %10 None %94 +%92 = OpFunctionParameter %10 +%91 = OpLabel +OpBranch %95 +%95 = OpLabel +%98 = OpFUnordNotEqual %96 %92 %97 %100 = OpSelect %10 %98 %99 %97 OpReturnValue %100 OpFunctionEnd @@ -151,18 +151,18 @@ OpFunctionEnd %101 = OpLabel OpBranch %104 %104 = OpLabel -%105 = OpLogicalNot %8 %27 -%107 = OpCompositeConstruct %106 %27 %27 +%105 = OpLogicalNot %8 %26 +%107 = OpCompositeConstruct %106 %26 %26 %108 = OpLogicalNot %106 %107 -%109 = OpLogicalOr %8 %27 %29 -%110 = OpLogicalAnd %8 %27 %29 -%111 = OpLogicalOr %8 %27 %29 -%112 = OpCompositeConstruct %11 %27 %27 %27 -%113 = OpCompositeConstruct %11 %29 %29 %29 -%114 = OpLogicalOr %11 %112 %113 -%115 = OpLogicalAnd %8 %27 %29 -%116 = OpCompositeConstruct %7 %27 %27 %27 %27 -%117 = OpCompositeConstruct %7 %29 %29 %29 %29 +%109 = OpLogicalOr %8 %26 %28 +%110 = OpLogicalAnd %8 %26 %28 +%111 = OpLogicalOr %8 %26 %28 +%112 = OpCompositeConstruct %96 %26 %26 %26 +%113 = OpCompositeConstruct %96 %28 %28 %28 +%114 = OpLogicalOr %96 %112 %113 +%115 = OpLogicalAnd %8 %26 %28 +%116 = OpCompositeConstruct %7 %26 %26 %26 %26 +%117 = OpCompositeConstruct %7 %28 %28 %28 %28 %118 = OpLogicalAnd %7 %116 %117 OpReturn OpFunctionEnd @@ -170,77 +170,77 @@ OpFunctionEnd %119 = OpLabel OpBranch %128 %128 = OpLabel -%130 = OpCompositeConstruct %129 %22 %22 +%130 = OpCompositeConstruct %129 %21 %21 %131 = OpSNegate %129 %130 -%132 = OpCompositeConstruct %9 %16 %16 +%132 = OpCompositeConstruct %9 %15 %15 %133 = OpFNegate %9 %132 -%134 = OpIAdd %6 %59 %22 +%134 = OpIAdd %6 %58 %21 %135 = OpIAdd %122 %123 %124 -%136 = OpFAdd %4 %55 %16 -%137 = OpCompositeConstruct %129 %59 %59 -%138 = OpCompositeConstruct %129 %22 %22 +%136 = OpFAdd %4 %54 %15 +%137 = OpCompositeConstruct %129 %58 %58 +%138 = OpCompositeConstruct %129 %21 %21 %139 = OpIAdd %129 %137 %138 %141 = OpCompositeConstruct %140 %123 %123 %123 %142 = OpCompositeConstruct %140 %124 %124 %124 %143 = OpIAdd %140 %141 %142 -%144 = OpCompositeConstruct %3 %55 %55 %55 %55 -%145 = OpCompositeConstruct %3 %16 %16 %16 %16 +%144 = OpCompositeConstruct %3 %54 %54 %54 %54 +%145 = OpCompositeConstruct %3 %15 %15 %15 %15 %146 = OpFAdd %3 %144 %145 -%147 = OpISub %6 %59 %22 +%147 = OpISub %6 %58 %21 %148 = OpISub %122 %123 %124 -%149 = OpFSub %4 %55 %16 -%150 = OpCompositeConstruct %129 %59 %59 -%151 = OpCompositeConstruct %129 %22 %22 +%149 = OpFSub %4 %54 %15 +%150 = OpCompositeConstruct %129 %58 %58 +%151 = OpCompositeConstruct %129 %21 %21 %152 = OpISub %129 %150 %151 %153 = OpCompositeConstruct %140 %123 %123 %123 %154 = OpCompositeConstruct %140 %124 %124 %124 %155 = OpISub %140 %153 %154 -%156 = OpCompositeConstruct %3 %55 %55 %55 %55 -%157 = OpCompositeConstruct %3 %16 %16 %16 %16 +%156 = OpCompositeConstruct %3 %54 %54 %54 %54 +%157 = OpCompositeConstruct %3 %15 %15 %15 %15 %158 = OpFSub %3 %156 %157 -%159 = OpIMul %6 %59 %22 +%159 = OpIMul %6 %58 %21 %160 = OpIMul %122 %123 %124 -%161 = OpFMul %4 %55 %16 -%162 = OpCompositeConstruct %129 %59 %59 -%163 = OpCompositeConstruct %129 %22 %22 +%161 = OpFMul %4 %54 %15 +%162 = OpCompositeConstruct %129 %58 %58 +%163 = OpCompositeConstruct %129 %21 %21 %164 = OpIMul %129 %162 %163 %165 = OpCompositeConstruct %140 %123 %123 %123 %166 = OpCompositeConstruct %140 %124 %124 %124 %167 = OpIMul %140 %165 %166 -%168 = OpCompositeConstruct %3 %55 %55 %55 %55 -%169 = OpCompositeConstruct %3 %16 %16 %16 %16 +%168 = OpCompositeConstruct %3 %54 %54 %54 %54 +%169 = OpCompositeConstruct %3 %15 %15 %15 %15 %170 = OpFMul %3 %168 %169 -%171 = OpSDiv %6 %59 %22 +%171 = OpSDiv %6 %58 %21 %172 = OpUDiv %122 %123 %124 -%173 = OpFDiv %4 %55 %16 -%174 = OpCompositeConstruct %129 %59 %59 -%175 = OpCompositeConstruct %129 %22 %22 +%173 = OpFDiv %4 %54 %15 +%174 = OpCompositeConstruct %129 %58 %58 +%175 = OpCompositeConstruct %129 %21 %21 %176 = OpSDiv %129 %174 %175 %177 = OpCompositeConstruct %140 %123 %123 %123 %178 = OpCompositeConstruct %140 %124 %124 %124 %179 = OpUDiv %140 %177 %178 -%180 = OpCompositeConstruct %3 %55 %55 %55 %55 -%181 = OpCompositeConstruct %3 %16 %16 %16 %16 +%180 = OpCompositeConstruct %3 %54 %54 %54 %54 +%181 = OpCompositeConstruct %3 %15 %15 %15 %15 %182 = OpFDiv %3 %180 %181 -%183 = OpSRem %6 %59 %22 +%183 = OpSRem %6 %58 %21 %184 = OpUMod %122 %123 %124 -%185 = OpFRem %4 %55 %16 -%186 = OpCompositeConstruct %129 %59 %59 -%187 = OpCompositeConstruct %129 %22 %22 +%185 = OpFRem %4 %54 %15 +%186 = OpCompositeConstruct %129 %58 %58 +%187 = OpCompositeConstruct %129 %21 %21 %188 = OpSRem %129 %186 %187 %189 = OpCompositeConstruct %140 %123 %123 %123 %190 = OpCompositeConstruct %140 %124 %124 %124 %191 = OpUMod %140 %189 %190 -%192 = OpCompositeConstruct %3 %55 %55 %55 %55 -%193 = OpCompositeConstruct %3 %16 %16 %16 %16 +%192 = OpCompositeConstruct %3 %54 %54 %54 %54 +%193 = OpCompositeConstruct %3 %15 %15 %15 %15 %194 = OpFRem %3 %192 %193 OpBranch %195 %195 = OpLabel -%197 = OpCompositeConstruct %129 %59 %59 -%198 = OpCompositeConstruct %129 %22 %22 +%197 = OpCompositeConstruct %129 %58 %58 +%198 = OpCompositeConstruct %129 %21 %21 %199 = OpIAdd %129 %197 %198 -%200 = OpCompositeConstruct %129 %22 %22 -%201 = OpCompositeConstruct %129 %59 %59 +%200 = OpCompositeConstruct %129 %21 %21 +%201 = OpCompositeConstruct %129 %58 %58 %202 = OpIAdd %129 %201 %200 %204 = OpCompositeConstruct %203 %123 %123 %205 = OpCompositeConstruct %203 %124 %124 @@ -248,17 +248,17 @@ OpBranch %195 %207 = OpCompositeConstruct %203 %124 %124 %208 = OpCompositeConstruct %203 %123 %123 %209 = OpIAdd %203 %208 %207 -%210 = OpCompositeConstruct %9 %55 %55 -%211 = OpCompositeConstruct %9 %16 %16 +%210 = OpCompositeConstruct %9 %54 %54 +%211 = OpCompositeConstruct %9 %15 %15 %212 = OpFAdd %9 %210 %211 -%213 = OpCompositeConstruct %9 %16 %16 -%214 = OpCompositeConstruct %9 %55 %55 +%213 = OpCompositeConstruct %9 %15 %15 +%214 = OpCompositeConstruct %9 %54 %54 %215 = OpFAdd %9 %214 %213 -%216 = OpCompositeConstruct %129 %59 %59 -%217 = OpCompositeConstruct %129 %22 %22 +%216 = OpCompositeConstruct %129 %58 %58 +%217 = OpCompositeConstruct %129 %21 %21 %218 = OpISub %129 %216 %217 -%219 = OpCompositeConstruct %129 %22 %22 -%220 = OpCompositeConstruct %129 %59 %59 +%219 = OpCompositeConstruct %129 %21 %21 +%220 = OpCompositeConstruct %129 %58 %58 %221 = OpISub %129 %220 %219 %222 = OpCompositeConstruct %203 %123 %123 %223 = OpCompositeConstruct %203 %124 %124 @@ -266,17 +266,17 @@ OpBranch %195 %225 = OpCompositeConstruct %203 %124 %124 %226 = OpCompositeConstruct %203 %123 %123 %227 = OpISub %203 %226 %225 -%228 = OpCompositeConstruct %9 %55 %55 -%229 = OpCompositeConstruct %9 %16 %16 +%228 = OpCompositeConstruct %9 %54 %54 +%229 = OpCompositeConstruct %9 %15 %15 %230 = OpFSub %9 %228 %229 -%231 = OpCompositeConstruct %9 %16 %16 -%232 = OpCompositeConstruct %9 %55 %55 +%231 = OpCompositeConstruct %9 %15 %15 +%232 = OpCompositeConstruct %9 %54 %54 %233 = OpFSub %9 %232 %231 -%234 = OpCompositeConstruct %129 %59 %59 -%236 = OpCompositeConstruct %129 %22 %22 +%234 = OpCompositeConstruct %129 %58 %58 +%236 = OpCompositeConstruct %129 %21 %21 %235 = OpIMul %129 %234 %236 -%237 = OpCompositeConstruct %129 %22 %22 -%239 = OpCompositeConstruct %129 %59 %59 +%237 = OpCompositeConstruct %129 %21 %21 +%239 = OpCompositeConstruct %129 %58 %58 %238 = OpIMul %129 %237 %239 %240 = OpCompositeConstruct %203 %123 %123 %242 = OpCompositeConstruct %203 %124 %124 @@ -284,15 +284,15 @@ OpBranch %195 %243 = OpCompositeConstruct %203 %124 %124 %245 = OpCompositeConstruct %203 %123 %123 %244 = OpIMul %203 %243 %245 -%246 = OpCompositeConstruct %9 %55 %55 -%247 = OpVectorTimesScalar %9 %246 %16 -%248 = OpCompositeConstruct %9 %16 %16 -%249 = OpVectorTimesScalar %9 %248 %55 -%250 = OpCompositeConstruct %129 %59 %59 -%251 = OpCompositeConstruct %129 %22 %22 +%246 = OpCompositeConstruct %9 %54 %54 +%247 = OpVectorTimesScalar %9 %246 %15 +%248 = OpCompositeConstruct %9 %15 %15 +%249 = OpVectorTimesScalar %9 %248 %54 +%250 = OpCompositeConstruct %129 %58 %58 +%251 = OpCompositeConstruct %129 %21 %21 %252 = OpSDiv %129 %250 %251 -%253 = OpCompositeConstruct %129 %22 %22 -%254 = OpCompositeConstruct %129 %59 %59 +%253 = OpCompositeConstruct %129 %21 %21 +%254 = OpCompositeConstruct %129 %58 %58 %255 = OpSDiv %129 %254 %253 %256 = OpCompositeConstruct %203 %123 %123 %257 = OpCompositeConstruct %203 %124 %124 @@ -300,17 +300,17 @@ OpBranch %195 %259 = OpCompositeConstruct %203 %124 %124 %260 = OpCompositeConstruct %203 %123 %123 %261 = OpUDiv %203 %260 %259 -%262 = OpCompositeConstruct %9 %55 %55 -%263 = OpCompositeConstruct %9 %16 %16 +%262 = OpCompositeConstruct %9 %54 %54 +%263 = OpCompositeConstruct %9 %15 %15 %264 = OpFDiv %9 %262 %263 -%265 = OpCompositeConstruct %9 %16 %16 -%266 = OpCompositeConstruct %9 %55 %55 +%265 = OpCompositeConstruct %9 %15 %15 +%266 = OpCompositeConstruct %9 %54 %54 %267 = OpFDiv %9 %266 %265 -%268 = OpCompositeConstruct %129 %59 %59 -%269 = OpCompositeConstruct %129 %22 %22 +%268 = OpCompositeConstruct %129 %58 %58 +%269 = OpCompositeConstruct %129 %21 %21 %270 = OpSRem %129 %268 %269 -%271 = OpCompositeConstruct %129 %22 %22 -%272 = OpCompositeConstruct %129 %59 %59 +%271 = OpCompositeConstruct %129 %21 %21 +%272 = OpCompositeConstruct %129 %58 %58 %273 = OpSRem %129 %272 %271 %274 = OpCompositeConstruct %203 %123 %123 %275 = OpCompositeConstruct %203 %124 %124 @@ -318,11 +318,11 @@ OpBranch %195 %277 = OpCompositeConstruct %203 %124 %124 %278 = OpCompositeConstruct %203 %123 %123 %279 = OpUMod %203 %278 %277 -%280 = OpCompositeConstruct %9 %55 %55 -%281 = OpCompositeConstruct %9 %16 %16 +%280 = OpCompositeConstruct %9 %54 %54 +%281 = OpCompositeConstruct %9 %15 %15 %282 = OpFRem %9 %280 %281 -%283 = OpCompositeConstruct %9 %16 %16 -%284 = OpCompositeConstruct %9 %55 %55 +%283 = OpCompositeConstruct %9 %15 %15 +%284 = OpCompositeConstruct %9 %54 %54 %285 = OpFRem %9 %284 %283 OpBranch %196 %196 = OpLabel @@ -335,7 +335,7 @@ OpBranch %196 %293 = OpCompositeExtract %10 %125 2 %294 = OpCompositeExtract %10 %125 2 %295 = OpFAdd %10 %293 %294 -%286 = OpCompositeConstruct %12 %289 %292 %295 +%286 = OpCompositeConstruct %11 %289 %292 %295 %297 = OpCompositeExtract %10 %125 0 %298 = OpCompositeExtract %10 %125 0 %299 = OpFSub %10 %297 %298 @@ -345,61 +345,61 @@ OpBranch %196 %303 = OpCompositeExtract %10 %125 2 %304 = OpCompositeExtract %10 %125 2 %305 = OpFSub %10 %303 %304 -%296 = OpCompositeConstruct %12 %299 %302 %305 -%306 = OpMatrixTimesScalar %12 %125 %16 -%307 = OpMatrixTimesScalar %12 %125 %55 -%308 = OpCompositeConstruct %3 %16 %16 %16 %16 +%296 = OpCompositeConstruct %11 %299 %302 %305 +%306 = OpMatrixTimesScalar %11 %125 %15 +%307 = OpMatrixTimesScalar %11 %125 %54 +%308 = OpCompositeConstruct %3 %15 %15 %15 %15 %309 = OpMatrixTimesVector %10 %126 %308 -%310 = OpCompositeConstruct %10 %55 %55 %55 +%310 = OpCompositeConstruct %10 %54 %54 %54 %311 = OpVectorTimesMatrix %3 %310 %126 -%312 = OpMatrixTimesMatrix %12 %126 %127 +%312 = OpMatrixTimesMatrix %11 %126 %127 OpReturn OpFunctionEnd %314 = OpFunction %2 None %103 %313 = OpLabel OpBranch %315 %315 = OpLabel -%316 = OpNot %6 %22 +%316 = OpNot %6 %21 %317 = OpNot %122 %124 -%318 = OpCompositeConstruct %129 %22 %22 +%318 = OpCompositeConstruct %129 %21 %21 %319 = OpNot %129 %318 %320 = OpCompositeConstruct %140 %124 %124 %124 %321 = OpNot %140 %320 -%322 = OpBitwiseOr %6 %59 %22 +%322 = OpBitwiseOr %6 %58 %21 %323 = OpBitwiseOr %122 %123 %124 -%324 = OpCompositeConstruct %129 %59 %59 -%325 = OpCompositeConstruct %129 %22 %22 +%324 = OpCompositeConstruct %129 %58 %58 +%325 = OpCompositeConstruct %129 %21 %21 %326 = OpBitwiseOr %129 %324 %325 %327 = OpCompositeConstruct %140 %123 %123 %123 %328 = OpCompositeConstruct %140 %124 %124 %124 %329 = OpBitwiseOr %140 %327 %328 -%330 = OpBitwiseAnd %6 %59 %22 +%330 = OpBitwiseAnd %6 %58 %21 %331 = OpBitwiseAnd %122 %123 %124 -%332 = OpCompositeConstruct %129 %59 %59 -%333 = OpCompositeConstruct %129 %22 %22 +%332 = OpCompositeConstruct %129 %58 %58 +%333 = OpCompositeConstruct %129 %21 %21 %334 = OpBitwiseAnd %129 %332 %333 %335 = OpCompositeConstruct %140 %123 %123 %123 %336 = OpCompositeConstruct %140 %124 %124 %124 %337 = OpBitwiseAnd %140 %335 %336 -%338 = OpBitwiseXor %6 %59 %22 +%338 = OpBitwiseXor %6 %58 %21 %339 = OpBitwiseXor %122 %123 %124 -%340 = OpCompositeConstruct %129 %59 %59 -%341 = OpCompositeConstruct %129 %22 %22 +%340 = OpCompositeConstruct %129 %58 %58 +%341 = OpCompositeConstruct %129 %21 %21 %342 = OpBitwiseXor %129 %340 %341 %343 = OpCompositeConstruct %140 %123 %123 %123 %344 = OpCompositeConstruct %140 %124 %124 %124 %345 = OpBitwiseXor %140 %343 %344 -%346 = OpShiftLeftLogical %6 %59 %124 +%346 = OpShiftLeftLogical %6 %58 %124 %347 = OpShiftLeftLogical %122 %123 %124 -%348 = OpCompositeConstruct %129 %59 %59 +%348 = OpCompositeConstruct %129 %58 %58 %349 = OpCompositeConstruct %203 %124 %124 %350 = OpShiftLeftLogical %129 %348 %349 %351 = OpCompositeConstruct %140 %123 %123 %123 %352 = OpCompositeConstruct %140 %124 %124 %124 %353 = OpShiftLeftLogical %140 %351 %352 -%354 = OpShiftRightArithmetic %6 %59 %124 +%354 = OpShiftRightArithmetic %6 %58 %124 %355 = OpShiftRightLogical %122 %123 %124 -%356 = OpCompositeConstruct %129 %59 %59 +%356 = OpCompositeConstruct %129 %58 %58 %357 = OpCompositeConstruct %203 %124 %124 %358 = OpShiftRightArithmetic %129 %356 %357 %359 = OpCompositeConstruct %140 %123 %123 %123 @@ -411,77 +411,77 @@ OpFunctionEnd %362 = OpLabel OpBranch %364 %364 = OpLabel -%365 = OpIEqual %8 %59 %22 +%365 = OpIEqual %8 %58 %21 %366 = OpIEqual %8 %123 %124 -%367 = OpFOrdEqual %8 %55 %16 -%368 = OpCompositeConstruct %129 %59 %59 -%369 = OpCompositeConstruct %129 %22 %22 +%367 = OpFOrdEqual %8 %54 %15 +%368 = OpCompositeConstruct %129 %58 %58 +%369 = OpCompositeConstruct %129 %21 %21 %370 = OpIEqual %106 %368 %369 %371 = OpCompositeConstruct %140 %123 %123 %123 %372 = OpCompositeConstruct %140 %124 %124 %124 -%373 = OpIEqual %11 %371 %372 -%374 = OpCompositeConstruct %3 %55 %55 %55 %55 -%375 = OpCompositeConstruct %3 %16 %16 %16 %16 +%373 = OpIEqual %96 %371 %372 +%374 = OpCompositeConstruct %3 %54 %54 %54 %54 +%375 = OpCompositeConstruct %3 %15 %15 %15 %15 %376 = OpFOrdEqual %7 %374 %375 -%377 = OpINotEqual %8 %59 %22 +%377 = OpINotEqual %8 %58 %21 %378 = OpINotEqual %8 %123 %124 -%379 = OpFOrdNotEqual %8 %55 %16 -%380 = OpCompositeConstruct %129 %59 %59 -%381 = OpCompositeConstruct %129 %22 %22 +%379 = OpFOrdNotEqual %8 %54 %15 +%380 = OpCompositeConstruct %129 %58 %58 +%381 = OpCompositeConstruct %129 %21 %21 %382 = OpINotEqual %106 %380 %381 %383 = OpCompositeConstruct %140 %123 %123 %123 %384 = OpCompositeConstruct %140 %124 %124 %124 -%385 = OpINotEqual %11 %383 %384 -%386 = OpCompositeConstruct %3 %55 %55 %55 %55 -%387 = OpCompositeConstruct %3 %16 %16 %16 %16 +%385 = OpINotEqual %96 %383 %384 +%386 = OpCompositeConstruct %3 %54 %54 %54 %54 +%387 = OpCompositeConstruct %3 %15 %15 %15 %15 %388 = OpFOrdNotEqual %7 %386 %387 -%389 = OpSLessThan %8 %59 %22 +%389 = OpSLessThan %8 %58 %21 %390 = OpULessThan %8 %123 %124 -%391 = OpFOrdLessThan %8 %55 %16 -%392 = OpCompositeConstruct %129 %59 %59 -%393 = OpCompositeConstruct %129 %22 %22 +%391 = OpFOrdLessThan %8 %54 %15 +%392 = OpCompositeConstruct %129 %58 %58 +%393 = OpCompositeConstruct %129 %21 %21 %394 = OpSLessThan %106 %392 %393 %395 = OpCompositeConstruct %140 %123 %123 %123 %396 = OpCompositeConstruct %140 %124 %124 %124 -%397 = OpULessThan %11 %395 %396 -%398 = OpCompositeConstruct %3 %55 %55 %55 %55 -%399 = OpCompositeConstruct %3 %16 %16 %16 %16 +%397 = OpULessThan %96 %395 %396 +%398 = OpCompositeConstruct %3 %54 %54 %54 %54 +%399 = OpCompositeConstruct %3 %15 %15 %15 %15 %400 = OpFOrdLessThan %7 %398 %399 -%401 = OpSLessThanEqual %8 %59 %22 +%401 = OpSLessThanEqual %8 %58 %21 %402 = OpULessThanEqual %8 %123 %124 -%403 = OpFOrdLessThanEqual %8 %55 %16 -%404 = OpCompositeConstruct %129 %59 %59 -%405 = OpCompositeConstruct %129 %22 %22 +%403 = OpFOrdLessThanEqual %8 %54 %15 +%404 = OpCompositeConstruct %129 %58 %58 +%405 = OpCompositeConstruct %129 %21 %21 %406 = OpSLessThanEqual %106 %404 %405 %407 = OpCompositeConstruct %140 %123 %123 %123 %408 = OpCompositeConstruct %140 %124 %124 %124 -%409 = OpULessThanEqual %11 %407 %408 -%410 = OpCompositeConstruct %3 %55 %55 %55 %55 -%411 = OpCompositeConstruct %3 %16 %16 %16 %16 +%409 = OpULessThanEqual %96 %407 %408 +%410 = OpCompositeConstruct %3 %54 %54 %54 %54 +%411 = OpCompositeConstruct %3 %15 %15 %15 %15 %412 = OpFOrdLessThanEqual %7 %410 %411 -%413 = OpSGreaterThan %8 %59 %22 +%413 = OpSGreaterThan %8 %58 %21 %414 = OpUGreaterThan %8 %123 %124 -%415 = OpFOrdGreaterThan %8 %55 %16 -%416 = OpCompositeConstruct %129 %59 %59 -%417 = OpCompositeConstruct %129 %22 %22 +%415 = OpFOrdGreaterThan %8 %54 %15 +%416 = OpCompositeConstruct %129 %58 %58 +%417 = OpCompositeConstruct %129 %21 %21 %418 = OpSGreaterThan %106 %416 %417 %419 = OpCompositeConstruct %140 %123 %123 %123 %420 = OpCompositeConstruct %140 %124 %124 %124 -%421 = OpUGreaterThan %11 %419 %420 -%422 = OpCompositeConstruct %3 %55 %55 %55 %55 -%423 = OpCompositeConstruct %3 %16 %16 %16 %16 +%421 = OpUGreaterThan %96 %419 %420 +%422 = OpCompositeConstruct %3 %54 %54 %54 %54 +%423 = OpCompositeConstruct %3 %15 %15 %15 %15 %424 = OpFOrdGreaterThan %7 %422 %423 -%425 = OpSGreaterThanEqual %8 %59 %22 +%425 = OpSGreaterThanEqual %8 %58 %21 %426 = OpUGreaterThanEqual %8 %123 %124 -%427 = OpFOrdGreaterThanEqual %8 %55 %16 -%428 = OpCompositeConstruct %129 %59 %59 -%429 = OpCompositeConstruct %129 %22 %22 +%427 = OpFOrdGreaterThanEqual %8 %54 %15 +%428 = OpCompositeConstruct %129 %58 %58 +%429 = OpCompositeConstruct %129 %21 %21 %430 = OpSGreaterThanEqual %106 %428 %429 %431 = OpCompositeConstruct %140 %123 %123 %123 %432 = OpCompositeConstruct %140 %124 %124 %124 -%433 = OpUGreaterThanEqual %11 %431 %432 -%434 = OpCompositeConstruct %3 %55 %55 %55 %55 -%435 = OpCompositeConstruct %3 %16 %16 %16 %16 +%433 = OpUGreaterThanEqual %96 %431 %432 +%434 = OpCompositeConstruct %3 %54 %54 %54 %54 +%435 = OpCompositeConstruct %3 %15 %15 %15 %15 %436 = OpFOrdGreaterThanEqual %7 %434 %435 OpReturn OpFunctionEnd @@ -491,12 +491,12 @@ OpFunctionEnd %440 = OpVariable %441 Function %442 OpBranch %445 %445 = OpLabel -OpStore %437 %22 +OpStore %437 %21 %446 = OpLoad %6 %437 -%447 = OpIAdd %6 %446 %22 +%447 = OpIAdd %6 %446 %21 OpStore %437 %447 %448 = OpLoad %6 %437 -%449 = OpISub %6 %448 %22 +%449 = OpISub %6 %448 %21 OpStore %437 %449 %450 = OpLoad %6 %437 %451 = OpLoad %6 %437 @@ -507,16 +507,16 @@ OpStore %437 %452 %455 = OpSDiv %6 %454 %453 OpStore %437 %455 %456 = OpLoad %6 %437 -%457 = OpSRem %6 %456 %22 +%457 = OpSRem %6 %456 %21 OpStore %437 %457 %458 = OpLoad %6 %437 -%459 = OpBitwiseAnd %6 %458 %28 +%459 = OpBitwiseAnd %6 %458 %27 OpStore %437 %459 %460 = OpLoad %6 %437 -%461 = OpBitwiseOr %6 %460 %28 +%461 = OpBitwiseOr %6 %460 %27 OpStore %437 %461 %462 = OpLoad %6 %437 -%463 = OpBitwiseXor %6 %462 %28 +%463 = OpBitwiseXor %6 %462 %27 OpStore %437 %463 %464 = OpLoad %6 %437 %465 = OpShiftLeftLogical %6 %464 %123 @@ -525,20 +525,20 @@ OpStore %437 %465 %467 = OpShiftRightArithmetic %6 %466 %124 OpStore %437 %467 %468 = OpLoad %6 %437 -%469 = OpIAdd %6 %468 %22 +%469 = OpIAdd %6 %468 %21 OpStore %437 %469 %470 = OpLoad %6 %437 -%471 = OpISub %6 %470 %22 +%471 = OpISub %6 %470 %21 OpStore %437 %471 OpStore %440 %442 %473 = OpAccessChain %472 %440 %124 %474 = OpLoad %6 %473 -%475 = OpIAdd %6 %474 %22 +%475 = OpIAdd %6 %474 %21 %476 = OpAccessChain %472 %440 %124 OpStore %476 %475 %477 = OpAccessChain %472 %440 %124 %478 = OpLoad %6 %477 -%479 = OpISub %6 %478 %22 +%479 = OpISub %6 %478 %21 %480 = OpAccessChain %472 %440 %124 OpStore %480 %479 OpReturn @@ -571,10 +571,10 @@ OpFunctionEnd %510 = OpLabel OpBranch %512 %512 = OpLabel -%513 = OpFunctionCall %3 %25 -%514 = OpFunctionCall %3 %54 -%515 = OpVectorShuffle %10 %17 %17 0 1 2 -%516 = OpFunctionCall %10 %94 %515 +%513 = OpFunctionCall %3 %24 +%514 = OpFunctionCall %3 %53 +%515 = OpVectorShuffle %10 %16 %16 0 1 2 +%516 = OpFunctionCall %10 %93 %515 %517 = OpFunctionCall %2 %102 %518 = OpFunctionCall %2 %120 %519 = OpFunctionCall %2 %314 diff --git a/tests/out/spv/padding.spvasm b/tests/out/spv/padding.spvasm index 93c4ce63c..e0b4251ae 100644 --- a/tests/out/spv/padding.spvasm +++ b/tests/out/spv/padding.spvasm @@ -1,11 +1,11 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 51 +; Bound: 49 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %28 "vertex" %26 +OpEntryPoint Vertex %26 "vertex" %24 OpMemberName %5 0 "a" OpName %5 "S" OpMemberName %6 0 "a" @@ -17,10 +17,10 @@ OpName %10 "Test2" OpMemberName %12 0 "a" OpMemberName %12 1 "b" OpName %12 "Test3" -OpName %16 "input1" -OpName %19 "input2" -OpName %22 "input3" -OpName %28 "vertex" +OpName %14 "input1" +OpName %17 "input2" +OpName %20 "input3" +OpName %26 "vertex" OpMemberDecorate %5 0 Offset 0 OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 @@ -31,19 +31,19 @@ OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 0 ColMajor OpMemberDecorate %12 0 MatrixStride 16 OpMemberDecorate %12 1 Offset 64 -OpDecorate %16 DescriptorSet 0 -OpDecorate %16 Binding 0 -OpDecorate %17 Block -OpMemberDecorate %17 0 Offset 0 -OpDecorate %19 DescriptorSet 0 -OpDecorate %19 Binding 1 -OpDecorate %20 Block -OpMemberDecorate %20 0 Offset 0 -OpDecorate %22 DescriptorSet 0 -OpDecorate %22 Binding 2 -OpDecorate %23 Block -OpMemberDecorate %23 0 Offset 0 -OpDecorate %26 BuiltIn Position +OpDecorate %14 DescriptorSet 0 +OpDecorate %14 Binding 0 +OpDecorate %15 Block +OpMemberDecorate %15 0 Offset 0 +OpDecorate %17 DescriptorSet 0 +OpDecorate %17 Binding 1 +OpDecorate %18 Block +OpMemberDecorate %18 0 Offset 0 +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 2 +OpDecorate %21 Block +OpMemberDecorate %21 0 Offset 0 +OpDecorate %24 BuiltIn Position %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 3 @@ -56,44 +56,42 @@ OpDecorate %26 BuiltIn Position %11 = OpTypeMatrix %3 4 %12 = OpTypeStruct %11 %4 %13 = OpTypeVector %4 4 -%15 = OpTypeInt 32 1 -%14 = OpConstant %15 2 -%17 = OpTypeStruct %6 -%18 = OpTypePointer Uniform %17 -%16 = OpVariable %18 Uniform -%20 = OpTypeStruct %10 -%21 = OpTypePointer Uniform %20 -%19 = OpVariable %21 Uniform -%23 = OpTypeStruct %12 -%24 = OpTypePointer Uniform %23 -%22 = OpVariable %24 Uniform -%27 = OpTypePointer Output %13 -%26 = OpVariable %27 Output -%29 = OpTypeFunction %2 -%30 = OpTypePointer Uniform %6 -%31 = OpConstant %9 0 -%33 = OpTypePointer Uniform %10 -%35 = OpTypePointer Uniform %12 -%37 = OpConstant %4 1.0 -%40 = OpTypePointer Uniform %4 -%41 = OpConstant %9 1 -%28 = OpFunction %2 None %29 -%25 = OpLabel -%32 = OpAccessChain %30 %16 %31 -%34 = OpAccessChain %33 %19 %31 -%36 = OpAccessChain %35 %22 %31 -OpBranch %38 -%38 = OpLabel -%39 = OpCompositeConstruct %13 %37 %37 %37 %37 -%42 = OpAccessChain %40 %32 %41 -%43 = OpLoad %4 %42 -%44 = OpVectorTimesScalar %13 %39 %43 -%45 = OpAccessChain %40 %34 %41 -%46 = OpLoad %4 %45 -%47 = OpVectorTimesScalar %13 %44 %46 -%48 = OpAccessChain %40 %36 %41 -%49 = OpLoad %4 %48 -%50 = OpVectorTimesScalar %13 %47 %49 -OpStore %26 %50 +%15 = OpTypeStruct %6 +%16 = OpTypePointer Uniform %15 +%14 = OpVariable %16 Uniform +%18 = OpTypeStruct %10 +%19 = OpTypePointer Uniform %18 +%17 = OpVariable %19 Uniform +%21 = OpTypeStruct %12 +%22 = OpTypePointer Uniform %21 +%20 = OpVariable %22 Uniform +%25 = OpTypePointer Output %13 +%24 = OpVariable %25 Output +%27 = OpTypeFunction %2 +%28 = OpTypePointer Uniform %6 +%29 = OpConstant %9 0 +%31 = OpTypePointer Uniform %10 +%33 = OpTypePointer Uniform %12 +%35 = OpConstant %4 1.0 +%38 = OpTypePointer Uniform %4 +%39 = OpConstant %9 1 +%26 = OpFunction %2 None %27 +%23 = OpLabel +%30 = OpAccessChain %28 %14 %29 +%32 = OpAccessChain %31 %17 %29 +%34 = OpAccessChain %33 %20 %29 +OpBranch %36 +%36 = OpLabel +%37 = OpCompositeConstruct %13 %35 %35 %35 %35 +%40 = OpAccessChain %38 %30 %39 +%41 = OpLoad %4 %40 +%42 = OpVectorTimesScalar %13 %37 %41 +%43 = OpAccessChain %38 %32 %39 +%44 = OpLoad %4 %43 +%45 = OpVectorTimesScalar %13 %42 %44 +%46 = OpAccessChain %38 %34 %39 +%47 = OpLoad %4 %46 +%48 = OpVectorTimesScalar %13 %45 %47 +OpStore %24 %48 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index 332d265fa..2de4a4971 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -9,69 +9,69 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpMemoryModel Logical GLSL450 OpMemberName %7 0 "arr" OpName %7 "DynamicArray" -OpName %10 "dynamic_array" -OpName %11 "v" -OpName %15 "f" -OpName %23 "i" -OpName %24 "v" -OpName %25 "index_unsized" +OpName %8 "dynamic_array" +OpName %10 "v" +OpName %14 "f" +OpName %22 "i" +OpName %23 "v" +OpName %24 "index_unsized" OpName %34 "i" OpName %35 "v" OpName %36 "index_dynamic_array" OpDecorate %6 ArrayStride 4 OpMemberDecorate %7 0 Offset 0 OpDecorate %7 Block -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 0 +OpDecorate %8 DescriptorSet 0 +OpDecorate %8 Binding 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 2 %5 = OpTypeInt 32 0 %6 = OpTypeRuntimeArray %5 %7 = OpTypeStruct %6 -%8 = OpTypePointer StorageBuffer %7 -%9 = OpTypePointer StorageBuffer %6 -%10 = OpVariable %8 StorageBuffer -%12 = OpTypePointer Function %3 -%13 = OpConstantNull %3 -%16 = OpTypeFunction %2 -%17 = OpConstant %4 10 -%19 = OpTypePointer Function %4 -%20 = OpConstant %5 0 -%26 = OpTypeFunction %2 %4 %5 +%9 = OpTypePointer StorageBuffer %7 +%8 = OpVariable %9 StorageBuffer +%11 = OpTypePointer Function %3 +%12 = OpConstantNull %3 +%15 = OpTypeFunction %2 +%16 = OpConstant %4 10 +%18 = OpTypePointer Function %4 +%19 = OpConstant %5 0 +%25 = OpTypeFunction %2 %4 %5 +%27 = OpTypePointer StorageBuffer %6 %28 = OpTypePointer StorageBuffer %5 -%15 = OpFunction %2 None %16 -%14 = OpLabel -%11 = OpVariable %12 Function %13 -OpBranch %18 -%18 = OpLabel -%21 = OpAccessChain %19 %11 %20 -OpStore %21 %17 +%14 = OpFunction %2 None %15 +%13 = OpLabel +%10 = OpVariable %11 Function %12 +OpBranch %17 +%17 = OpLabel +%20 = OpAccessChain %18 %10 %19 +OpStore %20 %16 OpReturn OpFunctionEnd -%25 = OpFunction %2 None %26 -%23 = OpFunctionParameter %4 -%24 = OpFunctionParameter %5 -%22 = OpLabel -OpBranch %27 -%27 = OpLabel -%29 = OpAccessChain %28 %10 %20 %23 +%24 = OpFunction %2 None %25 +%22 = OpFunctionParameter %4 +%23 = OpFunctionParameter %5 +%21 = OpLabel +OpBranch %26 +%26 = OpLabel +%29 = OpAccessChain %28 %8 %19 %22 %30 = OpLoad %5 %29 -%31 = OpIAdd %5 %30 %24 -%32 = OpAccessChain %28 %10 %20 %23 +%31 = OpIAdd %5 %30 %23 +%32 = OpAccessChain %28 %8 %19 %22 OpStore %32 %31 OpReturn OpFunctionEnd -%36 = OpFunction %2 None %26 +%36 = OpFunction %2 None %25 %34 = OpFunctionParameter %4 %35 = OpFunctionParameter %5 %33 = OpLabel OpBranch %37 %37 = OpLabel -%38 = OpAccessChain %28 %10 %20 %34 +%38 = OpAccessChain %28 %8 %19 %34 %39 = OpLoad %5 %38 %40 = OpIAdd %5 %39 %35 -%41 = OpAccessChain %28 %10 %20 %34 +%41 = OpAccessChain %28 %8 %19 %34 OpStore %41 %40 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index ea77b3bb4..a23714d9d 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 106 +; Bound: 101 OpCapability Shader OpCapability ImageQuery OpCapability Linkage @@ -12,16 +12,16 @@ OpMemberName %8 0 "a" OpName %8 "InStorage" OpMemberName %11 0 "a" OpName %11 "InUniform" -OpName %26 "in_storage" -OpName %29 "in_uniform" -OpName %32 "image_2d_array" -OpName %34 "in_workgroup" -OpName %36 "in_private" -OpName %39 "in_function" -OpName %43 "c" -OpName %44 "i" -OpName %45 "l" -OpName %46 "mock_function" +OpName %21 "in_storage" +OpName %24 "in_uniform" +OpName %27 "image_2d_array" +OpName %29 "in_workgroup" +OpName %31 "in_private" +OpName %34 "in_function" +OpName %38 "c" +OpName %39 "i" +OpName %40 "l" +OpName %41 "mock_function" OpDecorate %5 ArrayStride 16 OpMemberDecorate %8 0 Offset 0 OpDecorate %9 ArrayStride 16 @@ -29,17 +29,17 @@ OpMemberDecorate %11 0 Offset 0 OpDecorate %13 ArrayStride 4 OpDecorate %15 ArrayStride 4 OpDecorate %19 ArrayStride 16 -OpDecorate %26 NonWritable -OpDecorate %26 DescriptorSet 0 -OpDecorate %26 Binding 0 -OpDecorate %27 Block -OpMemberDecorate %27 0 Offset 0 -OpDecorate %29 DescriptorSet 0 -OpDecorate %29 Binding 1 -OpDecorate %30 Block -OpMemberDecorate %30 0 Offset 0 -OpDecorate %32 DescriptorSet 0 -OpDecorate %32 Binding 2 +OpDecorate %21 NonWritable +OpDecorate %21 DescriptorSet 0 +OpDecorate %21 Binding 0 +OpDecorate %22 Block +OpMemberDecorate %22 0 Offset 0 +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 1 +OpDecorate %25 Block +OpMemberDecorate %25 0 Offset 0 +OpDecorate %27 DescriptorSet 0 +OpDecorate %27 Binding 2 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -59,96 +59,91 @@ OpDecorate %32 Binding 2 %17 = OpTypeVector %18 2 %20 = OpConstant %7 2 %19 = OpTypeArray %3 %20 -%21 = OpConstant %18 10 -%22 = OpConstant %18 20 -%23 = OpConstant %18 30 -%24 = OpConstant %18 40 -%25 = OpConstant %18 2 -%27 = OpTypeStruct %8 -%28 = OpTypePointer StorageBuffer %27 -%26 = OpVariable %28 StorageBuffer -%30 = OpTypeStruct %11 -%31 = OpTypePointer Uniform %30 -%29 = OpVariable %31 Uniform -%33 = OpTypePointer UniformConstant %12 -%32 = OpVariable %33 UniformConstant -%35 = OpTypePointer Workgroup %13 -%34 = OpVariable %35 Workgroup -%37 = OpTypePointer Private %15 -%38 = OpConstantNull %15 -%36 = OpVariable %37 Private %38 -%40 = OpTypePointer Function %19 -%41 = OpConstantNull %19 -%47 = OpTypeFunction %3 %17 %18 %18 -%48 = OpTypePointer StorageBuffer %8 -%49 = OpConstant %7 0 -%51 = OpTypePointer Uniform %11 -%54 = OpConstant %4 0.707 -%55 = OpConstant %4 0.0 -%56 = OpConstant %4 1.0 -%61 = OpTypePointer StorageBuffer %5 -%62 = OpTypePointer StorageBuffer %3 -%65 = OpTypePointer Uniform %9 -%66 = OpTypePointer Uniform %3 -%70 = OpTypeVector %18 3 -%72 = OpTypeBool -%73 = OpConstantNull %3 -%79 = OpTypeVector %72 3 -%86 = OpTypePointer Workgroup %4 -%87 = OpConstant %7 29 -%93 = OpTypePointer Private %4 -%94 = OpConstant %7 39 -%100 = OpTypePointer Function %3 -%101 = OpConstant %7 1 -%46 = OpFunction %3 None %47 -%43 = OpFunctionParameter %17 -%44 = OpFunctionParameter %18 -%45 = OpFunctionParameter %18 -%42 = OpLabel -%39 = OpVariable %40 Function %41 -%50 = OpAccessChain %48 %26 %49 -%52 = OpAccessChain %51 %29 %49 -%53 = OpLoad %12 %32 -OpBranch %57 -%57 = OpLabel -%58 = OpCompositeConstruct %3 %54 %55 %55 %56 -%59 = OpCompositeConstruct %3 %55 %54 %55 %56 -%60 = OpCompositeConstruct %19 %58 %59 -OpStore %39 %60 -%63 = OpAccessChain %62 %50 %49 %44 -%64 = OpLoad %3 %63 -%67 = OpAccessChain %66 %52 %49 %44 -%68 = OpLoad %3 %67 -%69 = OpFAdd %3 %64 %68 -%71 = OpCompositeConstruct %70 %43 %44 -%74 = OpImageQueryLevels %18 %53 -%75 = OpULessThan %72 %45 %74 -OpSelectionMerge %76 None -OpBranchConditional %75 %77 %76 +%22 = OpTypeStruct %8 +%23 = OpTypePointer StorageBuffer %22 +%21 = OpVariable %23 StorageBuffer +%25 = OpTypeStruct %11 +%26 = OpTypePointer Uniform %25 +%24 = OpVariable %26 Uniform +%28 = OpTypePointer UniformConstant %12 +%27 = OpVariable %28 UniformConstant +%30 = OpTypePointer Workgroup %13 +%29 = OpVariable %30 Workgroup +%32 = OpTypePointer Private %15 +%33 = OpConstantNull %15 +%31 = OpVariable %32 Private %33 +%35 = OpTypePointer Function %19 +%36 = OpConstantNull %19 +%42 = OpTypeFunction %3 %17 %18 %18 +%43 = OpTypePointer StorageBuffer %8 +%44 = OpConstant %7 0 +%46 = OpTypePointer Uniform %11 +%49 = OpConstant %4 0.707 +%50 = OpConstant %4 0.0 +%51 = OpConstant %4 1.0 +%56 = OpTypePointer StorageBuffer %5 +%57 = OpTypePointer StorageBuffer %3 +%60 = OpTypePointer Uniform %9 +%61 = OpTypePointer Uniform %3 +%65 = OpTypeVector %18 3 +%67 = OpTypeBool +%68 = OpConstantNull %3 +%74 = OpTypeVector %67 3 +%81 = OpTypePointer Workgroup %4 +%82 = OpConstant %7 29 +%88 = OpTypePointer Private %4 +%89 = OpConstant %7 39 +%95 = OpTypePointer Function %3 +%96 = OpConstant %7 1 +%41 = OpFunction %3 None %42 +%38 = OpFunctionParameter %17 +%39 = OpFunctionParameter %18 +%40 = OpFunctionParameter %18 +%37 = OpLabel +%34 = OpVariable %35 Function %36 +%45 = OpAccessChain %43 %21 %44 +%47 = OpAccessChain %46 %24 %44 +%48 = OpLoad %12 %27 +OpBranch %52 +%52 = OpLabel +%53 = OpCompositeConstruct %3 %49 %50 %50 %51 +%54 = OpCompositeConstruct %3 %50 %49 %50 %51 +%55 = OpCompositeConstruct %19 %53 %54 +OpStore %34 %55 +%58 = OpAccessChain %57 %45 %44 %39 +%59 = OpLoad %3 %58 +%62 = OpAccessChain %61 %47 %44 %39 +%63 = OpLoad %3 %62 +%64 = OpFAdd %3 %59 %63 +%66 = OpCompositeConstruct %65 %38 %39 +%69 = OpImageQueryLevels %18 %48 +%70 = OpULessThan %67 %40 %69 +OpSelectionMerge %71 None +OpBranchConditional %70 %72 %71 +%72 = OpLabel +%73 = OpImageQuerySizeLod %65 %48 %40 +%75 = OpULessThan %74 %66 %73 +%76 = OpAll %67 %75 +OpBranchConditional %76 %77 %71 %77 = OpLabel -%78 = OpImageQuerySizeLod %70 %53 %45 -%80 = OpULessThan %79 %71 %78 -%81 = OpAll %72 %80 -OpBranchConditional %81 %82 %76 -%82 = OpLabel -%83 = OpImageFetch %3 %53 %71 Lod %45 -OpBranch %76 -%76 = OpLabel -%84 = OpPhi %3 %73 %57 %73 %77 %83 %82 -%85 = OpFAdd %3 %69 %84 -%88 = OpExtInst %7 %1 UMin %44 %87 -%89 = OpAccessChain %86 %34 %88 -%90 = OpLoad %4 %89 -%91 = OpCompositeConstruct %3 %90 %90 %90 %90 -%92 = OpFAdd %3 %85 %91 -%95 = OpExtInst %7 %1 UMin %44 %94 -%96 = OpAccessChain %93 %36 %95 -%97 = OpLoad %4 %96 -%98 = OpCompositeConstruct %3 %97 %97 %97 %97 -%99 = OpFAdd %3 %92 %98 -%102 = OpExtInst %7 %1 UMin %44 %101 -%103 = OpAccessChain %100 %39 %102 -%104 = OpLoad %3 %103 -%105 = OpFAdd %3 %99 %104 -OpReturnValue %105 +%78 = OpImageFetch %3 %48 %66 Lod %40 +OpBranch %71 +%71 = OpLabel +%79 = OpPhi %3 %68 %52 %68 %72 %78 %77 +%80 = OpFAdd %3 %64 %79 +%83 = OpExtInst %7 %1 UMin %39 %82 +%84 = OpAccessChain %81 %29 %83 +%85 = OpLoad %4 %84 +%86 = OpCompositeConstruct %3 %85 %85 %85 %85 +%87 = OpFAdd %3 %80 %86 +%90 = OpExtInst %7 %1 UMin %39 %89 +%91 = OpAccessChain %88 %31 %90 +%92 = OpLoad %4 %91 +%93 = OpCompositeConstruct %3 %92 %92 %92 %92 +%94 = OpFAdd %3 %87 %93 +%97 = OpExtInst %7 %1 UMin %39 %96 +%98 = OpAccessChain %95 %34 %97 +%99 = OpLoad %3 %98 +%100 = OpFAdd %3 %94 %99 +OpReturnValue %100 OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/runtime-array-in-unused-struct.spvasm b/tests/out/spv/runtime-array-in-unused-struct.spvasm index ab3bd3d01..d88b35b0b 100644 --- a/tests/out/spv/runtime-array-in-unused-struct.spvasm +++ b/tests/out/spv/runtime-array-in-unused-struct.spvasm @@ -1,24 +1,9 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 10 +; Bound: 3 OpCapability Shader OpCapability Linkage %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpMemberDecorate %5 0 Offset 0 -OpMemberDecorate %5 1 Offset 16 -OpDecorate %6 ArrayStride 32 -OpMemberDecorate %7 0 Offset 0 -OpDecorate %7 Block -OpDecorate %8 ArrayStride 4 -OpMemberDecorate %9 0 Offset 0 -OpDecorate %9 Block -%2 = OpTypeVoid -%3 = OpTypeFloat 32 -%4 = OpTypeVector %3 4 -%5 = OpTypeStruct %3 %4 -%6 = OpTypeRuntimeArray %5 -%7 = OpTypeStruct %6 -%8 = OpTypeRuntimeArray %3 -%9 = OpTypeStruct %8 \ No newline at end of file +%2 = OpTypeVoid \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index c5b1c7c3e..d0e3309c2 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 268 +; Bound: 267 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %88 "vs_main" %78 %81 %83 %85 %87 -OpEntryPoint Fragment %148 "fs_main" %139 %142 %145 %147 -OpEntryPoint Fragment %215 "fs_main_without_storage" %208 %210 %212 %214 -OpExecutionMode %148 OriginUpperLeft -OpExecutionMode %215 OriginUpperLeft +OpEntryPoint Vertex %87 "vs_main" %77 %80 %82 %84 %86 +OpEntryPoint Fragment %147 "fs_main" %138 %141 %144 %146 +OpEntryPoint Fragment %214 "fs_main_without_storage" %207 %209 %211 %213 +OpExecutionMode %147 OriginUpperLeft +OpExecutionMode %214 OriginUpperLeft OpMemberName %8 0 "view_proj" OpMemberName %8 1 "num_lights" OpName %8 "Globals" @@ -25,36 +25,36 @@ OpMemberName %15 0 "proj" OpMemberName %15 1 "pos" OpMemberName %15 2 "color" OpName %15 "Light" -OpName %24 "c_ambient" +OpName %23 "c_ambient" OpName %18 "c_max_lights" -OpName %25 "u_globals" -OpName %28 "u_entity" -OpName %31 "s_lights" -OpName %34 "u_lights" -OpName %37 "t_shadow" -OpName %39 "sampler_shadow" -OpName %42 "light_id" -OpName %43 "homogeneous_coords" -OpName %44 "fetch_shadow" -OpName %74 "out" -OpName %78 "position" -OpName %81 "normal" -OpName %83 "proj_position" -OpName %85 "world_normal" -OpName %87 "world_position" -OpName %88 "vs_main" -OpName %132 "color" -OpName %134 "i" -OpName %139 "proj_position" -OpName %142 "world_normal" -OpName %145 "world_position" -OpName %148 "fs_main" -OpName %204 "color" -OpName %205 "i" -OpName %208 "proj_position" -OpName %210 "world_normal" -OpName %212 "world_position" -OpName %215 "fs_main_without_storage" +OpName %24 "u_globals" +OpName %27 "u_entity" +OpName %30 "s_lights" +OpName %33 "u_lights" +OpName %36 "t_shadow" +OpName %38 "sampler_shadow" +OpName %41 "light_id" +OpName %42 "homogeneous_coords" +OpName %43 "fetch_shadow" +OpName %73 "out" +OpName %77 "position" +OpName %80 "normal" +OpName %82 "proj_position" +OpName %84 "world_normal" +OpName %86 "world_position" +OpName %87 "vs_main" +OpName %131 "color" +OpName %133 "i" +OpName %138 "proj_position" +OpName %141 "world_normal" +OpName %144 "world_position" +OpName %147 "fs_main" +OpName %203 "color" +OpName %204 "i" +OpName %207 "proj_position" +OpName %209 "world_normal" +OpName %211 "world_position" +OpName %214 "fs_main_without_storage" OpMemberDecorate %8 0 Offset 0 OpMemberDecorate %8 0 ColMajor OpMemberDecorate %8 0 MatrixStride 16 @@ -73,40 +73,40 @@ OpMemberDecorate %15 1 Offset 64 OpMemberDecorate %15 2 Offset 80 OpDecorate %16 ArrayStride 96 OpDecorate %17 ArrayStride 96 -OpDecorate %25 DescriptorSet 0 -OpDecorate %25 Binding 0 -OpDecorate %26 Block -OpMemberDecorate %26 0 Offset 0 -OpDecorate %28 DescriptorSet 1 -OpDecorate %28 Binding 0 -OpDecorate %29 Block -OpMemberDecorate %29 0 Offset 0 -OpDecorate %31 NonWritable -OpDecorate %31 DescriptorSet 0 -OpDecorate %31 Binding 1 -OpDecorate %32 Block -OpMemberDecorate %32 0 Offset 0 -OpDecorate %34 DescriptorSet 0 -OpDecorate %34 Binding 1 -OpDecorate %35 Block -OpMemberDecorate %35 0 Offset 0 -OpDecorate %37 DescriptorSet 0 -OpDecorate %37 Binding 2 -OpDecorate %39 DescriptorSet 0 -OpDecorate %39 Binding 3 -OpDecorate %78 Location 0 -OpDecorate %81 Location 1 -OpDecorate %83 BuiltIn Position -OpDecorate %85 Location 0 -OpDecorate %87 Location 1 -OpDecorate %139 BuiltIn FragCoord -OpDecorate %142 Location 0 -OpDecorate %145 Location 1 -OpDecorate %147 Location 0 -OpDecorate %208 BuiltIn FragCoord -OpDecorate %210 Location 0 -OpDecorate %212 Location 1 -OpDecorate %214 Location 0 +OpDecorate %24 DescriptorSet 0 +OpDecorate %24 Binding 0 +OpDecorate %25 Block +OpMemberDecorate %25 0 Offset 0 +OpDecorate %27 DescriptorSet 1 +OpDecorate %27 Binding 0 +OpDecorate %28 Block +OpMemberDecorate %28 0 Offset 0 +OpDecorate %30 NonWritable +OpDecorate %30 DescriptorSet 0 +OpDecorate %30 Binding 1 +OpDecorate %31 Block +OpMemberDecorate %31 0 Offset 0 +OpDecorate %33 DescriptorSet 0 +OpDecorate %33 Binding 1 +OpDecorate %34 Block +OpMemberDecorate %34 0 Offset 0 +OpDecorate %36 DescriptorSet 0 +OpDecorate %36 Binding 2 +OpDecorate %38 DescriptorSet 0 +OpDecorate %38 Binding 3 +OpDecorate %77 Location 0 +OpDecorate %80 Location 1 +OpDecorate %82 BuiltIn Position +OpDecorate %84 Location 0 +OpDecorate %86 Location 1 +OpDecorate %138 BuiltIn FragCoord +OpDecorate %141 Location 0 +OpDecorate %144 Location 1 +OpDecorate %146 Location 0 +OpDecorate %207 BuiltIn FragCoord +OpDecorate %209 Location 0 +OpDecorate %211 Location 1 +OpDecorate %213 Location 0 %2 = OpTypeVoid %5 = OpTypeFloat 32 %4 = OpTypeVector %5 4 @@ -127,301 +127,300 @@ OpDecorate %214 Location 0 %19 = OpTypeImage %5 2D 1 1 0 1 Unknown %20 = OpTypeSampler %21 = OpTypeVector %5 2 -%22 = OpConstant %13 10 -%23 = OpConstant %5 0.05 -%24 = OpConstantComposite %10 %23 %23 %23 -%26 = OpTypeStruct %8 -%27 = OpTypePointer Uniform %26 -%25 = OpVariable %27 Uniform -%29 = OpTypeStruct %9 -%30 = OpTypePointer Uniform %29 -%28 = OpVariable %30 Uniform -%32 = OpTypeStruct %16 -%33 = OpTypePointer StorageBuffer %32 -%31 = OpVariable %33 StorageBuffer -%35 = OpTypeStruct %17 -%36 = OpTypePointer Uniform %35 -%34 = OpVariable %36 Uniform -%38 = OpTypePointer UniformConstant %19 -%37 = OpVariable %38 UniformConstant -%40 = OpTypePointer UniformConstant %20 -%39 = OpVariable %40 UniformConstant -%45 = OpTypeFunction %5 %7 %4 -%48 = OpConstant %5 0.0 -%49 = OpConstant %5 1.0 -%50 = OpConstant %5 0.5 -%51 = OpConstant %5 -0.5 -%54 = OpTypeBool -%69 = OpTypeSampledImage %19 -%75 = OpTypePointer Function %11 -%76 = OpConstantNull %11 -%79 = OpTypePointer Input %12 -%78 = OpVariable %79 Input -%81 = OpVariable %79 Input -%84 = OpTypePointer Output %4 -%83 = OpVariable %84 Output -%86 = OpTypePointer Output %10 -%85 = OpVariable %86 Output -%87 = OpVariable %84 Output -%89 = OpTypeFunction %2 -%90 = OpTypePointer Uniform %8 -%91 = OpConstant %7 0 -%93 = OpTypePointer Uniform %9 -%96 = OpTypePointer Uniform %3 -%103 = OpTypePointer Function %10 -%111 = OpTypeVector %13 3 -%115 = OpConstant %7 1 -%117 = OpTypePointer Function %4 -%118 = OpConstant %7 2 -%126 = OpTypePointer Output %5 -%133 = OpConstantNull %10 -%135 = OpTypePointer Function %7 -%136 = OpConstantNull %7 -%140 = OpTypePointer Input %4 -%139 = OpVariable %140 Input -%143 = OpTypePointer Input %10 -%142 = OpVariable %143 Input -%145 = OpVariable %140 Input -%147 = OpVariable %84 Output -%151 = OpTypePointer StorageBuffer %16 -%163 = OpTypePointer Uniform %6 -%164 = OpTypePointer Uniform %7 -%174 = OpTypePointer StorageBuffer %15 -%200 = OpTypePointer Uniform %4 -%208 = OpVariable %140 Input -%210 = OpVariable %143 Input -%212 = OpVariable %140 Input -%214 = OpVariable %84 Output -%218 = OpTypePointer Uniform %17 -%239 = OpTypePointer Uniform %15 -%44 = OpFunction %5 None %45 -%42 = OpFunctionParameter %7 -%43 = OpFunctionParameter %4 -%41 = OpLabel -%46 = OpLoad %19 %37 -%47 = OpLoad %20 %39 -OpBranch %52 -%52 = OpLabel -%53 = OpCompositeExtract %5 %43 3 -%55 = OpFOrdLessThanEqual %54 %53 %48 -OpSelectionMerge %56 None -OpBranchConditional %55 %57 %56 -%57 = OpLabel -OpReturnValue %49 +%22 = OpConstant %5 0.05 +%23 = OpConstantComposite %10 %22 %22 %22 +%25 = OpTypeStruct %8 +%26 = OpTypePointer Uniform %25 +%24 = OpVariable %26 Uniform +%28 = OpTypeStruct %9 +%29 = OpTypePointer Uniform %28 +%27 = OpVariable %29 Uniform +%31 = OpTypeStruct %16 +%32 = OpTypePointer StorageBuffer %31 +%30 = OpVariable %32 StorageBuffer +%34 = OpTypeStruct %17 +%35 = OpTypePointer Uniform %34 +%33 = OpVariable %35 Uniform +%37 = OpTypePointer UniformConstant %19 +%36 = OpVariable %37 UniformConstant +%39 = OpTypePointer UniformConstant %20 +%38 = OpVariable %39 UniformConstant +%44 = OpTypeFunction %5 %7 %4 +%47 = OpConstant %5 0.0 +%48 = OpConstant %5 1.0 +%49 = OpConstant %5 0.5 +%50 = OpConstant %5 -0.5 +%53 = OpTypeBool +%68 = OpTypeSampledImage %19 +%74 = OpTypePointer Function %11 +%75 = OpConstantNull %11 +%78 = OpTypePointer Input %12 +%77 = OpVariable %78 Input +%80 = OpVariable %78 Input +%83 = OpTypePointer Output %4 +%82 = OpVariable %83 Output +%85 = OpTypePointer Output %10 +%84 = OpVariable %85 Output +%86 = OpVariable %83 Output +%88 = OpTypeFunction %2 +%89 = OpTypePointer Uniform %8 +%90 = OpConstant %7 0 +%92 = OpTypePointer Uniform %9 +%95 = OpTypePointer Uniform %3 +%102 = OpTypePointer Function %10 +%110 = OpTypeVector %13 3 +%114 = OpConstant %7 1 +%116 = OpTypePointer Function %4 +%117 = OpConstant %7 2 +%125 = OpTypePointer Output %5 +%132 = OpConstantNull %10 +%134 = OpTypePointer Function %7 +%135 = OpConstantNull %7 +%139 = OpTypePointer Input %4 +%138 = OpVariable %139 Input +%142 = OpTypePointer Input %10 +%141 = OpVariable %142 Input +%144 = OpVariable %139 Input +%146 = OpVariable %83 Output +%150 = OpTypePointer StorageBuffer %16 +%162 = OpTypePointer Uniform %6 +%163 = OpTypePointer Uniform %7 +%173 = OpTypePointer StorageBuffer %15 +%199 = OpTypePointer Uniform %4 +%207 = OpVariable %139 Input +%209 = OpVariable %142 Input +%211 = OpVariable %139 Input +%213 = OpVariable %83 Output +%217 = OpTypePointer Uniform %17 +%238 = OpTypePointer Uniform %15 +%43 = OpFunction %5 None %44 +%41 = OpFunctionParameter %7 +%42 = OpFunctionParameter %4 +%40 = OpLabel +%45 = OpLoad %19 %36 +%46 = OpLoad %20 %38 +OpBranch %51 +%51 = OpLabel +%52 = OpCompositeExtract %5 %42 3 +%54 = OpFOrdLessThanEqual %53 %52 %47 +OpSelectionMerge %55 None +OpBranchConditional %54 %56 %55 %56 = OpLabel -%58 = OpCompositeConstruct %21 %50 %51 -%59 = OpCompositeExtract %5 %43 3 -%60 = OpFDiv %5 %49 %59 -%61 = OpVectorShuffle %21 %43 %43 0 1 -%62 = OpFMul %21 %61 %58 -%63 = OpVectorTimesScalar %21 %62 %60 -%64 = OpCompositeConstruct %21 %50 %50 -%65 = OpFAdd %21 %63 %64 -%66 = OpBitcast %13 %42 -%67 = OpCompositeExtract %5 %43 2 -%68 = OpFMul %5 %67 %60 -%70 = OpConvertSToF %5 %66 -%71 = OpCompositeConstruct %10 %65 %70 -%72 = OpSampledImage %69 %46 %47 -%73 = OpImageSampleDrefExplicitLod %5 %72 %71 %68 Lod %48 -OpReturnValue %73 +OpReturnValue %48 +%55 = OpLabel +%57 = OpCompositeConstruct %21 %49 %50 +%58 = OpCompositeExtract %5 %42 3 +%59 = OpFDiv %5 %48 %58 +%60 = OpVectorShuffle %21 %42 %42 0 1 +%61 = OpFMul %21 %60 %57 +%62 = OpVectorTimesScalar %21 %61 %59 +%63 = OpCompositeConstruct %21 %49 %49 +%64 = OpFAdd %21 %62 %63 +%65 = OpBitcast %13 %41 +%66 = OpCompositeExtract %5 %42 2 +%67 = OpFMul %5 %66 %59 +%69 = OpConvertSToF %5 %65 +%70 = OpCompositeConstruct %10 %64 %69 +%71 = OpSampledImage %68 %45 %46 +%72 = OpImageSampleDrefExplicitLod %5 %71 %70 %67 Lod %47 +OpReturnValue %72 OpFunctionEnd -%88 = OpFunction %2 None %89 -%77 = OpLabel -%74 = OpVariable %75 Function %76 -%80 = OpLoad %12 %78 -%82 = OpLoad %12 %81 -%92 = OpAccessChain %90 %25 %91 -%94 = OpAccessChain %93 %28 %91 -OpBranch %95 -%95 = OpLabel -%97 = OpAccessChain %96 %94 %91 -%98 = OpLoad %3 %97 -%99 = OpAccessChain %96 %94 %91 -%100 = OpLoad %3 %99 -%101 = OpConvertSToF %4 %80 -%102 = OpMatrixTimesVector %4 %100 %101 -%104 = OpCompositeExtract %4 %98 0 -%105 = OpVectorShuffle %10 %104 %104 0 1 2 -%106 = OpCompositeExtract %4 %98 1 -%107 = OpVectorShuffle %10 %106 %106 0 1 2 -%108 = OpCompositeExtract %4 %98 2 -%109 = OpVectorShuffle %10 %108 %108 0 1 2 -%110 = OpCompositeConstruct %14 %105 %107 %109 -%112 = OpVectorShuffle %111 %82 %82 0 1 2 -%113 = OpConvertSToF %10 %112 -%114 = OpMatrixTimesVector %10 %110 %113 -%116 = OpAccessChain %103 %74 %115 -OpStore %116 %114 -%119 = OpAccessChain %117 %74 %118 -OpStore %119 %102 -%120 = OpAccessChain %96 %92 %91 -%121 = OpLoad %3 %120 -%122 = OpMatrixTimesVector %4 %121 %102 -%123 = OpAccessChain %117 %74 %91 -OpStore %123 %122 -%124 = OpLoad %11 %74 -%125 = OpCompositeExtract %4 %124 0 -OpStore %83 %125 -%127 = OpAccessChain %126 %83 %115 -%128 = OpLoad %5 %127 -%129 = OpFNegate %5 %128 -OpStore %127 %129 -%130 = OpCompositeExtract %10 %124 1 -OpStore %85 %130 -%131 = OpCompositeExtract %4 %124 2 -OpStore %87 %131 +%87 = OpFunction %2 None %88 +%76 = OpLabel +%73 = OpVariable %74 Function %75 +%79 = OpLoad %12 %77 +%81 = OpLoad %12 %80 +%91 = OpAccessChain %89 %24 %90 +%93 = OpAccessChain %92 %27 %90 +OpBranch %94 +%94 = OpLabel +%96 = OpAccessChain %95 %93 %90 +%97 = OpLoad %3 %96 +%98 = OpAccessChain %95 %93 %90 +%99 = OpLoad %3 %98 +%100 = OpConvertSToF %4 %79 +%101 = OpMatrixTimesVector %4 %99 %100 +%103 = OpCompositeExtract %4 %97 0 +%104 = OpVectorShuffle %10 %103 %103 0 1 2 +%105 = OpCompositeExtract %4 %97 1 +%106 = OpVectorShuffle %10 %105 %105 0 1 2 +%107 = OpCompositeExtract %4 %97 2 +%108 = OpVectorShuffle %10 %107 %107 0 1 2 +%109 = OpCompositeConstruct %14 %104 %106 %108 +%111 = OpVectorShuffle %110 %81 %81 0 1 2 +%112 = OpConvertSToF %10 %111 +%113 = OpMatrixTimesVector %10 %109 %112 +%115 = OpAccessChain %102 %73 %114 +OpStore %115 %113 +%118 = OpAccessChain %116 %73 %117 +OpStore %118 %101 +%119 = OpAccessChain %95 %91 %90 +%120 = OpLoad %3 %119 +%121 = OpMatrixTimesVector %4 %120 %101 +%122 = OpAccessChain %116 %73 %90 +OpStore %122 %121 +%123 = OpLoad %11 %73 +%124 = OpCompositeExtract %4 %123 0 +OpStore %82 %124 +%126 = OpAccessChain %125 %82 %114 +%127 = OpLoad %5 %126 +%128 = OpFNegate %5 %127 +OpStore %126 %128 +%129 = OpCompositeExtract %10 %123 1 +OpStore %84 %129 +%130 = OpCompositeExtract %4 %123 2 +OpStore %86 %130 OpReturn OpFunctionEnd -%148 = OpFunction %2 None %89 -%137 = OpLabel -%132 = OpVariable %103 Function %133 -%134 = OpVariable %135 Function %136 -%141 = OpLoad %4 %139 -%144 = OpLoad %10 %142 -%146 = OpLoad %4 %145 -%138 = OpCompositeConstruct %11 %141 %144 %146 -%149 = OpAccessChain %90 %25 %91 -%150 = OpAccessChain %93 %28 %91 -%152 = OpAccessChain %151 %31 %91 -%153 = OpLoad %19 %37 -%154 = OpLoad %20 %39 -OpBranch %155 -%155 = OpLabel -%156 = OpCompositeExtract %10 %138 1 -%157 = OpExtInst %10 %1 Normalize %156 -OpStore %132 %24 -OpStore %134 %91 -OpBranch %158 -%158 = OpLabel -OpLoopMerge %159 %161 None -OpBranch %160 -%160 = OpLabel -%162 = OpLoad %7 %134 -%165 = OpAccessChain %164 %149 %115 %91 -%166 = OpLoad %7 %165 -%167 = OpExtInst %7 %1 UMin %166 %18 -%168 = OpULessThan %54 %162 %167 -OpSelectionMerge %169 None -OpBranchConditional %168 %169 %170 -%170 = OpLabel +%147 = OpFunction %2 None %88 +%136 = OpLabel +%131 = OpVariable %102 Function %132 +%133 = OpVariable %134 Function %135 +%140 = OpLoad %4 %138 +%143 = OpLoad %10 %141 +%145 = OpLoad %4 %144 +%137 = OpCompositeConstruct %11 %140 %143 %145 +%148 = OpAccessChain %89 %24 %90 +%149 = OpAccessChain %92 %27 %90 +%151 = OpAccessChain %150 %30 %90 +%152 = OpLoad %19 %36 +%153 = OpLoad %20 %38 +OpBranch %154 +%154 = OpLabel +%155 = OpCompositeExtract %10 %137 1 +%156 = OpExtInst %10 %1 Normalize %155 +OpStore %131 %23 +OpStore %133 %90 +OpBranch %157 +%157 = OpLabel +OpLoopMerge %158 %160 None OpBranch %159 +%159 = OpLabel +%161 = OpLoad %7 %133 +%164 = OpAccessChain %163 %148 %114 %90 +%165 = OpLoad %7 %164 +%166 = OpExtInst %7 %1 UMin %165 %18 +%167 = OpULessThan %53 %161 %166 +OpSelectionMerge %168 None +OpBranchConditional %167 %168 %169 %169 = OpLabel +OpBranch %158 +%168 = OpLabel +OpBranch %170 +%170 = OpLabel +%172 = OpLoad %7 %133 +%174 = OpAccessChain %173 %151 %172 +%175 = OpLoad %15 %174 +%176 = OpLoad %7 %133 +%177 = OpCompositeExtract %3 %175 0 +%178 = OpCompositeExtract %4 %137 2 +%179 = OpMatrixTimesVector %4 %177 %178 +%180 = OpFunctionCall %5 %43 %176 %179 +%181 = OpCompositeExtract %4 %175 1 +%182 = OpVectorShuffle %10 %181 %181 0 1 2 +%183 = OpCompositeExtract %4 %137 2 +%184 = OpVectorShuffle %10 %183 %183 0 1 2 +%185 = OpFSub %10 %182 %184 +%186 = OpExtInst %10 %1 Normalize %185 +%187 = OpDot %5 %156 %186 +%188 = OpExtInst %5 %1 FMax %47 %187 +%189 = OpFMul %5 %180 %188 +%190 = OpCompositeExtract %4 %175 2 +%191 = OpVectorShuffle %10 %190 %190 0 1 2 +%192 = OpVectorTimesScalar %10 %191 %189 +%193 = OpLoad %10 %131 +%194 = OpFAdd %10 %193 %192 +OpStore %131 %194 OpBranch %171 %171 = OpLabel -%173 = OpLoad %7 %134 -%175 = OpAccessChain %174 %152 %173 -%176 = OpLoad %15 %175 -%177 = OpLoad %7 %134 -%178 = OpCompositeExtract %3 %176 0 -%179 = OpCompositeExtract %4 %138 2 -%180 = OpMatrixTimesVector %4 %178 %179 -%181 = OpFunctionCall %5 %44 %177 %180 -%182 = OpCompositeExtract %4 %176 1 -%183 = OpVectorShuffle %10 %182 %182 0 1 2 -%184 = OpCompositeExtract %4 %138 2 -%185 = OpVectorShuffle %10 %184 %184 0 1 2 -%186 = OpFSub %10 %183 %185 -%187 = OpExtInst %10 %1 Normalize %186 -%188 = OpDot %5 %157 %187 -%189 = OpExtInst %5 %1 FMax %48 %188 -%190 = OpFMul %5 %181 %189 -%191 = OpCompositeExtract %4 %176 2 -%192 = OpVectorShuffle %10 %191 %191 0 1 2 -%193 = OpVectorTimesScalar %10 %192 %190 -%194 = OpLoad %10 %132 -%195 = OpFAdd %10 %194 %193 -OpStore %132 %195 -OpBranch %172 -%172 = OpLabel -OpBranch %161 -%161 = OpLabel -%196 = OpLoad %7 %134 -%197 = OpIAdd %7 %196 %115 -OpStore %134 %197 -OpBranch %158 -%159 = OpLabel -%198 = OpLoad %10 %132 -%199 = OpCompositeConstruct %4 %198 %49 -%201 = OpAccessChain %200 %150 %115 -%202 = OpLoad %4 %201 -%203 = OpFMul %4 %199 %202 -OpStore %147 %203 +OpBranch %160 +%160 = OpLabel +%195 = OpLoad %7 %133 +%196 = OpIAdd %7 %195 %114 +OpStore %133 %196 +OpBranch %157 +%158 = OpLabel +%197 = OpLoad %10 %131 +%198 = OpCompositeConstruct %4 %197 %48 +%200 = OpAccessChain %199 %149 %114 +%201 = OpLoad %4 %200 +%202 = OpFMul %4 %198 %201 +OpStore %146 %202 OpReturn OpFunctionEnd -%215 = OpFunction %2 None %89 -%206 = OpLabel -%204 = OpVariable %103 Function %133 -%205 = OpVariable %135 Function %136 -%209 = OpLoad %4 %208 -%211 = OpLoad %10 %210 -%213 = OpLoad %4 %212 -%207 = OpCompositeConstruct %11 %209 %211 %213 -%216 = OpAccessChain %90 %25 %91 -%217 = OpAccessChain %93 %28 %91 -%219 = OpAccessChain %218 %34 %91 -%220 = OpLoad %19 %37 -%221 = OpLoad %20 %39 -OpBranch %222 -%222 = OpLabel -%223 = OpCompositeExtract %10 %207 1 -%224 = OpExtInst %10 %1 Normalize %223 -OpStore %204 %24 -OpStore %205 %91 -OpBranch %225 -%225 = OpLabel -OpLoopMerge %226 %228 None -OpBranch %227 -%227 = OpLabel -%229 = OpLoad %7 %205 -%230 = OpAccessChain %164 %216 %115 %91 -%231 = OpLoad %7 %230 -%232 = OpExtInst %7 %1 UMin %231 %18 -%233 = OpULessThan %54 %229 %232 -OpSelectionMerge %234 None -OpBranchConditional %233 %234 %235 -%235 = OpLabel +%214 = OpFunction %2 None %88 +%205 = OpLabel +%203 = OpVariable %102 Function %132 +%204 = OpVariable %134 Function %135 +%208 = OpLoad %4 %207 +%210 = OpLoad %10 %209 +%212 = OpLoad %4 %211 +%206 = OpCompositeConstruct %11 %208 %210 %212 +%215 = OpAccessChain %89 %24 %90 +%216 = OpAccessChain %92 %27 %90 +%218 = OpAccessChain %217 %33 %90 +%219 = OpLoad %19 %36 +%220 = OpLoad %20 %38 +OpBranch %221 +%221 = OpLabel +%222 = OpCompositeExtract %10 %206 1 +%223 = OpExtInst %10 %1 Normalize %222 +OpStore %203 %23 +OpStore %204 %90 +OpBranch %224 +%224 = OpLabel +OpLoopMerge %225 %227 None OpBranch %226 +%226 = OpLabel +%228 = OpLoad %7 %204 +%229 = OpAccessChain %163 %215 %114 %90 +%230 = OpLoad %7 %229 +%231 = OpExtInst %7 %1 UMin %230 %18 +%232 = OpULessThan %53 %228 %231 +OpSelectionMerge %233 None +OpBranchConditional %232 %233 %234 %234 = OpLabel +OpBranch %225 +%233 = OpLabel +OpBranch %235 +%235 = OpLabel +%237 = OpLoad %7 %204 +%239 = OpAccessChain %238 %218 %237 +%240 = OpLoad %15 %239 +%241 = OpLoad %7 %204 +%242 = OpCompositeExtract %3 %240 0 +%243 = OpCompositeExtract %4 %206 2 +%244 = OpMatrixTimesVector %4 %242 %243 +%245 = OpFunctionCall %5 %43 %241 %244 +%246 = OpCompositeExtract %4 %240 1 +%247 = OpVectorShuffle %10 %246 %246 0 1 2 +%248 = OpCompositeExtract %4 %206 2 +%249 = OpVectorShuffle %10 %248 %248 0 1 2 +%250 = OpFSub %10 %247 %249 +%251 = OpExtInst %10 %1 Normalize %250 +%252 = OpDot %5 %223 %251 +%253 = OpExtInst %5 %1 FMax %47 %252 +%254 = OpFMul %5 %245 %253 +%255 = OpCompositeExtract %4 %240 2 +%256 = OpVectorShuffle %10 %255 %255 0 1 2 +%257 = OpVectorTimesScalar %10 %256 %254 +%258 = OpLoad %10 %203 +%259 = OpFAdd %10 %258 %257 +OpStore %203 %259 OpBranch %236 %236 = OpLabel -%238 = OpLoad %7 %205 -%240 = OpAccessChain %239 %219 %238 -%241 = OpLoad %15 %240 -%242 = OpLoad %7 %205 -%243 = OpCompositeExtract %3 %241 0 -%244 = OpCompositeExtract %4 %207 2 -%245 = OpMatrixTimesVector %4 %243 %244 -%246 = OpFunctionCall %5 %44 %242 %245 -%247 = OpCompositeExtract %4 %241 1 -%248 = OpVectorShuffle %10 %247 %247 0 1 2 -%249 = OpCompositeExtract %4 %207 2 -%250 = OpVectorShuffle %10 %249 %249 0 1 2 -%251 = OpFSub %10 %248 %250 -%252 = OpExtInst %10 %1 Normalize %251 -%253 = OpDot %5 %224 %252 -%254 = OpExtInst %5 %1 FMax %48 %253 -%255 = OpFMul %5 %246 %254 -%256 = OpCompositeExtract %4 %241 2 -%257 = OpVectorShuffle %10 %256 %256 0 1 2 -%258 = OpVectorTimesScalar %10 %257 %255 -%259 = OpLoad %10 %204 -%260 = OpFAdd %10 %259 %258 -OpStore %204 %260 -OpBranch %237 -%237 = OpLabel -OpBranch %228 -%228 = OpLabel -%261 = OpLoad %7 %205 -%262 = OpIAdd %7 %261 %115 -OpStore %205 %262 -OpBranch %225 -%226 = OpLabel -%263 = OpLoad %10 %204 -%264 = OpCompositeConstruct %4 %263 %49 -%265 = OpAccessChain %200 %217 %115 -%266 = OpLoad %4 %265 -%267 = OpFMul %4 %264 %266 -OpStore %214 %267 +OpBranch %227 +%227 = OpLabel +%260 = OpLoad %7 %204 +%261 = OpIAdd %7 %260 %114 +OpStore %204 %261 +OpBranch %224 +%225 = OpLabel +%262 = OpLoad %10 %203 +%263 = OpCompositeConstruct %4 %262 %48 +%264 = OpAccessChain %199 %216 %114 +%265 = OpLoad %4 %264 +%266 = OpFMul %4 %263 %265 +OpStore %213 %266 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/workgroup-var-init.spvasm b/tests/out/spv/workgroup-var-init.spvasm index 905ed00bf..399f63855 100644 --- a/tests/out/spv/workgroup-var-init.spvasm +++ b/tests/out/spv/workgroup-var-init.spvasm @@ -1,31 +1,31 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 43 +; Bound: 41 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %19 "main" %27 -OpExecutionMode %19 LocalSize 1 1 1 +OpEntryPoint GLCompute %17 "main" %25 +OpExecutionMode %17 LocalSize 1 1 1 OpMemberName %10 0 "arr" OpMemberName %10 1 "atom" OpMemberName %10 2 "atom_arr" OpName %10 "WStruct" -OpName %13 "w_mem" -OpName %15 "output" -OpName %19 "main" +OpName %11 "w_mem" +OpName %13 "output" +OpName %17 "main" OpDecorate %4 ArrayStride 4 OpDecorate %7 ArrayStride 4 OpDecorate %9 ArrayStride 32 OpMemberDecorate %10 0 Offset 0 OpMemberDecorate %10 1 Offset 2048 OpMemberDecorate %10 2 Offset 2052 -OpDecorate %15 DescriptorSet 0 -OpDecorate %15 Binding 0 -OpDecorate %16 Block -OpMemberDecorate %16 0 Offset 0 -OpDecorate %27 BuiltIn LocalInvocationId +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 0 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 +OpDecorate %25 BuiltIn LocalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 %5 = OpConstant %3 512 @@ -35,45 +35,43 @@ OpDecorate %27 BuiltIn LocalInvocationId %7 = OpTypeArray %6 %8 %9 = OpTypeArray %7 %8 %10 = OpTypeStruct %4 %6 %9 -%11 = OpConstant %6 512 -%12 = OpConstant %6 8 -%14 = OpTypePointer Workgroup %10 -%13 = OpVariable %14 Workgroup -%16 = OpTypeStruct %4 -%17 = OpTypePointer StorageBuffer %16 -%15 = OpVariable %17 StorageBuffer -%20 = OpTypeFunction %2 -%21 = OpTypePointer StorageBuffer %4 -%22 = OpConstant %3 0 -%25 = OpConstantNull %10 -%26 = OpTypeVector %3 3 -%28 = OpTypePointer Input %26 -%27 = OpVariable %28 Input -%30 = OpConstantNull %26 -%32 = OpTypeBool -%31 = OpTypeVector %32 3 -%37 = OpConstant %3 2 -%38 = OpConstant %3 264 -%40 = OpTypePointer Workgroup %4 -%19 = OpFunction %2 None %20 -%18 = OpLabel -%23 = OpAccessChain %21 %15 %22 -OpBranch %24 -%24 = OpLabel -%29 = OpLoad %26 %27 -%33 = OpIEqual %31 %29 %30 -%34 = OpAll %32 %33 -OpSelectionMerge %35 None -OpBranchConditional %34 %36 %35 -%36 = OpLabel -OpStore %13 %25 -OpBranch %35 -%35 = OpLabel -OpControlBarrier %37 %37 %38 -OpBranch %39 -%39 = OpLabel -%41 = OpAccessChain %40 %13 %22 -%42 = OpLoad %4 %41 -OpStore %23 %42 +%12 = OpTypePointer Workgroup %10 +%11 = OpVariable %12 Workgroup +%14 = OpTypeStruct %4 +%15 = OpTypePointer StorageBuffer %14 +%13 = OpVariable %15 StorageBuffer +%18 = OpTypeFunction %2 +%19 = OpTypePointer StorageBuffer %4 +%20 = OpConstant %3 0 +%23 = OpConstantNull %10 +%24 = OpTypeVector %3 3 +%26 = OpTypePointer Input %24 +%25 = OpVariable %26 Input +%28 = OpConstantNull %24 +%30 = OpTypeBool +%29 = OpTypeVector %30 3 +%35 = OpConstant %3 2 +%36 = OpConstant %3 264 +%38 = OpTypePointer Workgroup %4 +%17 = OpFunction %2 None %18 +%16 = OpLabel +%21 = OpAccessChain %19 %13 %20 +OpBranch %22 +%22 = OpLabel +%27 = OpLoad %24 %25 +%31 = OpIEqual %29 %27 %28 +%32 = OpAll %30 %31 +OpSelectionMerge %33 None +OpBranchConditional %32 %34 %33 +%34 = OpLabel +OpStore %11 %23 +OpBranch %33 +%33 = OpLabel +OpControlBarrier %35 %35 %36 +OpBranch %37 +%37 = OpLabel +%39 = OpAccessChain %38 %11 %20 +%40 = OpLoad %4 %39 +OpStore %21 %40 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index ea64e80db..c01c4247c 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -45,31 +45,31 @@ fn test_matrix_within_struct_accesses() { idx = (_e3 - 1); let l0_ = baz.m; let l1_ = baz.m[0]; - let _e15 = idx; - let l2_ = baz.m[_e15]; + let _e14 = idx; + let l2_ = baz.m[_e14]; let l3_ = baz.m[0][1]; - let _e29 = idx; - let l4_ = baz.m[0][_e29]; - let _e34 = idx; - let l5_ = baz.m[_e34][1]; - let _e41 = idx; - let _e43 = idx; - let l6_ = baz.m[_e41][_e43]; + let _e25 = idx; + let l4_ = baz.m[0][_e25]; + let _e30 = idx; + let l5_ = baz.m[_e30][1]; + let _e36 = idx; + let _e38 = idx; + let l6_ = baz.m[_e36][_e38]; t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - let _e56 = idx; - idx = (_e56 + 1); + let _e51 = idx; + idx = (_e51 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); t.m[0] = vec2(9.0); - let _e72 = idx; - t.m[_e72] = vec2(90.0); + let _e66 = idx; + t.m[_e66] = vec2(90.0); t.m[0][1] = 10.0; + let _e76 = idx; + t.m[0][_e76] = 20.0; + let _e80 = idx; + t.m[_e80][1] = 30.0; let _e85 = idx; - t.m[0][_e85] = 20.0; - let _e89 = idx; - t.m[_e89][1] = 30.0; - let _e95 = idx; - let _e97 = idx; - t.m[_e95][_e97] = 40.0; + let _e87 = idx; + t.m[_e85][_e87] = 40.0; return; } @@ -83,32 +83,32 @@ fn test_matrix_within_array_within_struct_accesses() { let l0_1 = nested_mat_cx2_.am; let l1_1 = nested_mat_cx2_.am[0]; let l2_1 = nested_mat_cx2_.am[0][0]; - let _e24 = idx_1; - let l3_1 = nested_mat_cx2_.am[0][_e24]; + let _e20 = idx_1; + let l3_1 = nested_mat_cx2_.am[0][_e20]; let l4_1 = nested_mat_cx2_.am[0][0][1]; - let _e42 = idx_1; - let l5_1 = nested_mat_cx2_.am[0][0][_e42]; - let _e49 = idx_1; - let l6_1 = nested_mat_cx2_.am[0][_e49][1]; - let _e58 = idx_1; - let _e60 = idx_1; - let l7_ = nested_mat_cx2_.am[0][_e58][_e60]; + let _e33 = idx_1; + let l5_1 = nested_mat_cx2_.am[0][0][_e33]; + let _e39 = idx_1; + let l6_1 = nested_mat_cx2_.am[0][_e39][1]; + let _e46 = idx_1; + let _e48 = idx_1; + let l7_ = nested_mat_cx2_.am[0][_e46][_e48]; t_1 = MatCx2InArray(array, 2>()); - let _e67 = idx_1; - idx_1 = (_e67 + 1); + let _e55 = idx_1; + idx_1 = (_e55 + 1); t_1.am = array, 2>(); t_1.am[0] = mat4x2(vec2(8.0), vec2(7.0), vec2(6.0), vec2(5.0)); t_1.am[0][0] = vec2(9.0); - let _e93 = idx_1; - t_1.am[0][_e93] = vec2(90.0); + let _e77 = idx_1; + t_1.am[0][_e77] = vec2(90.0); t_1.am[0][0][1] = 10.0; - let _e110 = idx_1; - t_1.am[0][0][_e110] = 20.0; - let _e116 = idx_1; - t_1.am[0][_e116][1] = 30.0; - let _e124 = idx_1; - let _e126 = idx_1; - t_1.am[0][_e124][_e126] = 40.0; + let _e89 = idx_1; + t_1.am[0][0][_e89] = 20.0; + let _e94 = idx_1; + t_1.am[0][_e94][1] = 30.0; + let _e100 = idx_1; + let _e102 = idx_1; + t_1.am[0][_e100][_e102] = 40.0; return; } @@ -147,11 +147,11 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { let a_1 = bar.data[(arrayLength((&bar.data)) - 2u)].value; let c = qux; let data_pointer = (&bar.data[0].value); - let _e34 = read_from_private((&foo)); + let _e33 = read_from_private((&foo)); c2_ = array(a_1, i32(b), 3, 4, 5); c2_[(vi + 1u)] = 42; let value = c2_[vi]; - let _e48 = test_arr_as_arg(array, 5>()); + let _e47 = test_arr_as_arg(array, 5>()); return vec4((_matrix * vec4(vec4(value))), 2.0); } diff --git a/tests/out/wgsl/atomicOps.wgsl b/tests/out/wgsl/atomicOps.wgsl index 934a7b795..dcffe38e1 100644 --- a/tests/out/wgsl/atomicOps.wgsl +++ b/tests/out/wgsl/atomicOps.wgsl @@ -33,75 +33,75 @@ fn cs_main(@builtin(local_invocation_id) id: vec3) { let l6_ = atomicLoad((&workgroup_struct.atomic_scalar)); let l7_ = atomicLoad((&workgroup_struct.atomic_arr[1])); workgroupBarrier(); - let _e59 = atomicAdd((&storage_atomic_scalar), 1u); - let _e64 = atomicAdd((&storage_atomic_arr[1]), 1); - let _e68 = atomicAdd((&storage_struct.atomic_scalar), 1u); - let _e74 = atomicAdd((&storage_struct.atomic_arr[1]), 1); - let _e77 = atomicAdd((&workgroup_atomic_scalar), 1u); - let _e82 = atomicAdd((&workgroup_atomic_arr[1]), 1); - let _e86 = atomicAdd((&workgroup_struct.atomic_scalar), 1u); - let _e92 = atomicAdd((&workgroup_struct.atomic_arr[1]), 1); + let _e51 = atomicAdd((&storage_atomic_scalar), 1u); + let _e55 = atomicAdd((&storage_atomic_arr[1]), 1); + let _e59 = atomicAdd((&storage_struct.atomic_scalar), 1u); + let _e64 = atomicAdd((&storage_struct.atomic_arr[1]), 1); + let _e67 = atomicAdd((&workgroup_atomic_scalar), 1u); + let _e71 = atomicAdd((&workgroup_atomic_arr[1]), 1); + let _e75 = atomicAdd((&workgroup_struct.atomic_scalar), 1u); + let _e80 = atomicAdd((&workgroup_struct.atomic_arr[1]), 1); workgroupBarrier(); - let _e95 = atomicSub((&storage_atomic_scalar), 1u); - let _e100 = atomicSub((&storage_atomic_arr[1]), 1); - let _e104 = atomicSub((&storage_struct.atomic_scalar), 1u); - let _e110 = atomicSub((&storage_struct.atomic_arr[1]), 1); - let _e113 = atomicSub((&workgroup_atomic_scalar), 1u); - let _e118 = atomicSub((&workgroup_atomic_arr[1]), 1); - let _e122 = atomicSub((&workgroup_struct.atomic_scalar), 1u); - let _e128 = atomicSub((&workgroup_struct.atomic_arr[1]), 1); + let _e83 = atomicSub((&storage_atomic_scalar), 1u); + let _e87 = atomicSub((&storage_atomic_arr[1]), 1); + let _e91 = atomicSub((&storage_struct.atomic_scalar), 1u); + let _e96 = atomicSub((&storage_struct.atomic_arr[1]), 1); + let _e99 = atomicSub((&workgroup_atomic_scalar), 1u); + let _e103 = atomicSub((&workgroup_atomic_arr[1]), 1); + let _e107 = atomicSub((&workgroup_struct.atomic_scalar), 1u); + let _e112 = atomicSub((&workgroup_struct.atomic_arr[1]), 1); workgroupBarrier(); - let _e131 = atomicMax((&storage_atomic_scalar), 1u); - let _e136 = atomicMax((&storage_atomic_arr[1]), 1); - let _e140 = atomicMax((&storage_struct.atomic_scalar), 1u); - let _e146 = atomicMax((&storage_struct.atomic_arr[1]), 1); - let _e149 = atomicMax((&workgroup_atomic_scalar), 1u); - let _e154 = atomicMax((&workgroup_atomic_arr[1]), 1); - let _e158 = atomicMax((&workgroup_struct.atomic_scalar), 1u); - let _e164 = atomicMax((&workgroup_struct.atomic_arr[1]), 1); + let _e115 = atomicMax((&storage_atomic_scalar), 1u); + let _e119 = atomicMax((&storage_atomic_arr[1]), 1); + let _e123 = atomicMax((&storage_struct.atomic_scalar), 1u); + let _e128 = atomicMax((&storage_struct.atomic_arr[1]), 1); + let _e131 = atomicMax((&workgroup_atomic_scalar), 1u); + let _e135 = atomicMax((&workgroup_atomic_arr[1]), 1); + let _e139 = atomicMax((&workgroup_struct.atomic_scalar), 1u); + let _e144 = atomicMax((&workgroup_struct.atomic_arr[1]), 1); workgroupBarrier(); - let _e167 = atomicMin((&storage_atomic_scalar), 1u); - let _e172 = atomicMin((&storage_atomic_arr[1]), 1); - let _e176 = atomicMin((&storage_struct.atomic_scalar), 1u); - let _e182 = atomicMin((&storage_struct.atomic_arr[1]), 1); - let _e185 = atomicMin((&workgroup_atomic_scalar), 1u); - let _e190 = atomicMin((&workgroup_atomic_arr[1]), 1); - let _e194 = atomicMin((&workgroup_struct.atomic_scalar), 1u); - let _e200 = atomicMin((&workgroup_struct.atomic_arr[1]), 1); + let _e147 = atomicMin((&storage_atomic_scalar), 1u); + let _e151 = atomicMin((&storage_atomic_arr[1]), 1); + let _e155 = atomicMin((&storage_struct.atomic_scalar), 1u); + let _e160 = atomicMin((&storage_struct.atomic_arr[1]), 1); + let _e163 = atomicMin((&workgroup_atomic_scalar), 1u); + let _e167 = atomicMin((&workgroup_atomic_arr[1]), 1); + let _e171 = atomicMin((&workgroup_struct.atomic_scalar), 1u); + let _e176 = atomicMin((&workgroup_struct.atomic_arr[1]), 1); workgroupBarrier(); - let _e203 = atomicAnd((&storage_atomic_scalar), 1u); - let _e208 = atomicAnd((&storage_atomic_arr[1]), 1); - let _e212 = atomicAnd((&storage_struct.atomic_scalar), 1u); - let _e218 = atomicAnd((&storage_struct.atomic_arr[1]), 1); - let _e221 = atomicAnd((&workgroup_atomic_scalar), 1u); - let _e226 = atomicAnd((&workgroup_atomic_arr[1]), 1); - let _e230 = atomicAnd((&workgroup_struct.atomic_scalar), 1u); - let _e236 = atomicAnd((&workgroup_struct.atomic_arr[1]), 1); + let _e179 = atomicAnd((&storage_atomic_scalar), 1u); + let _e183 = atomicAnd((&storage_atomic_arr[1]), 1); + let _e187 = atomicAnd((&storage_struct.atomic_scalar), 1u); + let _e192 = atomicAnd((&storage_struct.atomic_arr[1]), 1); + let _e195 = atomicAnd((&workgroup_atomic_scalar), 1u); + let _e199 = atomicAnd((&workgroup_atomic_arr[1]), 1); + let _e203 = atomicAnd((&workgroup_struct.atomic_scalar), 1u); + let _e208 = atomicAnd((&workgroup_struct.atomic_arr[1]), 1); workgroupBarrier(); - let _e239 = atomicOr((&storage_atomic_scalar), 1u); - let _e244 = atomicOr((&storage_atomic_arr[1]), 1); - let _e248 = atomicOr((&storage_struct.atomic_scalar), 1u); - let _e254 = atomicOr((&storage_struct.atomic_arr[1]), 1); - let _e257 = atomicOr((&workgroup_atomic_scalar), 1u); - let _e262 = atomicOr((&workgroup_atomic_arr[1]), 1); - let _e266 = atomicOr((&workgroup_struct.atomic_scalar), 1u); - let _e272 = atomicOr((&workgroup_struct.atomic_arr[1]), 1); + let _e211 = atomicOr((&storage_atomic_scalar), 1u); + let _e215 = atomicOr((&storage_atomic_arr[1]), 1); + let _e219 = atomicOr((&storage_struct.atomic_scalar), 1u); + let _e224 = atomicOr((&storage_struct.atomic_arr[1]), 1); + let _e227 = atomicOr((&workgroup_atomic_scalar), 1u); + let _e231 = atomicOr((&workgroup_atomic_arr[1]), 1); + let _e235 = atomicOr((&workgroup_struct.atomic_scalar), 1u); + let _e240 = atomicOr((&workgroup_struct.atomic_arr[1]), 1); workgroupBarrier(); - let _e275 = atomicXor((&storage_atomic_scalar), 1u); - let _e280 = atomicXor((&storage_atomic_arr[1]), 1); - let _e284 = atomicXor((&storage_struct.atomic_scalar), 1u); - let _e290 = atomicXor((&storage_struct.atomic_arr[1]), 1); - let _e293 = atomicXor((&workgroup_atomic_scalar), 1u); - let _e298 = atomicXor((&workgroup_atomic_arr[1]), 1); - let _e302 = atomicXor((&workgroup_struct.atomic_scalar), 1u); - let _e308 = atomicXor((&workgroup_struct.atomic_arr[1]), 1); - let _e311 = atomicExchange((&storage_atomic_scalar), 1u); - let _e316 = atomicExchange((&storage_atomic_arr[1]), 1); - let _e320 = atomicExchange((&storage_struct.atomic_scalar), 1u); - let _e326 = atomicExchange((&storage_struct.atomic_arr[1]), 1); - let _e329 = atomicExchange((&workgroup_atomic_scalar), 1u); - let _e334 = atomicExchange((&workgroup_atomic_arr[1]), 1); - let _e338 = atomicExchange((&workgroup_struct.atomic_scalar), 1u); - let _e344 = atomicExchange((&workgroup_struct.atomic_arr[1]), 1); + let _e243 = atomicXor((&storage_atomic_scalar), 1u); + let _e247 = atomicXor((&storage_atomic_arr[1]), 1); + let _e251 = atomicXor((&storage_struct.atomic_scalar), 1u); + let _e256 = atomicXor((&storage_struct.atomic_arr[1]), 1); + let _e259 = atomicXor((&workgroup_atomic_scalar), 1u); + let _e263 = atomicXor((&workgroup_atomic_arr[1]), 1); + let _e267 = atomicXor((&workgroup_struct.atomic_scalar), 1u); + let _e272 = atomicXor((&workgroup_struct.atomic_arr[1]), 1); + let _e275 = atomicExchange((&storage_atomic_scalar), 1u); + let _e279 = atomicExchange((&storage_atomic_arr[1]), 1); + let _e283 = atomicExchange((&storage_struct.atomic_scalar), 1u); + let _e288 = atomicExchange((&storage_struct.atomic_arr[1]), 1); + let _e291 = atomicExchange((&workgroup_atomic_scalar), 1u); + let _e295 = atomicExchange((&workgroup_atomic_arr[1]), 1); + let _e299 = atomicExchange((&workgroup_struct.atomic_scalar), 1u); + let _e304 = atomicExchange((&workgroup_struct.atomic_arr[1]), 1); return; } diff --git a/tests/out/wgsl/binding-arrays.dynamic.wgsl b/tests/out/wgsl/binding-arrays.dynamic.wgsl index bccabd060..3a3b11664 100644 --- a/tests/out/wgsl/binding-arrays.dynamic.wgsl +++ b/tests/out/wgsl/binding-arrays.dynamic.wgsl @@ -5,8 +5,8 @@ var global_1: binding_array; var global_2: vec4; fn function() { - let _e9 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); - global_2 = _e9; + let _e8 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); + global_2 = _e8; return; } diff --git a/tests/out/wgsl/binding-arrays.static.wgsl b/tests/out/wgsl/binding-arrays.static.wgsl index e9dec5bf1..ff969359f 100644 --- a/tests/out/wgsl/binding-arrays.static.wgsl +++ b/tests/out/wgsl/binding-arrays.static.wgsl @@ -5,8 +5,8 @@ var global_1: binding_array; var global_2: vec4; fn function() { - let _e10 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); - global_2 = _e10; + let _e8 = textureSampleLevel(global[1], global_1[1], vec2(0.5, 0.5), 0.0); + global_2 = _e8; return; } diff --git a/tests/out/wgsl/binding-arrays.wgsl b/tests/out/wgsl/binding-arrays.wgsl index 878fb2c91..e9513c725 100644 --- a/tests/out/wgsl/binding-arrays.wgsl +++ b/tests/out/wgsl/binding-arrays.wgsl @@ -40,133 +40,133 @@ fn main(fragment_in: FragmentIn) -> @location(0) vec4 { v4_ = vec4(0.0); let uv = vec2(0.0); let pix = vec2(0); - let _e22 = textureDimensions(texture_array_unbounded[0]); - let _e23 = u2_; - u2_ = (_e23 + _e22); - let _e27 = textureDimensions(texture_array_unbounded[uniform_index]); - let _e28 = u2_; - u2_ = (_e28 + _e27); - let _e32 = textureDimensions(texture_array_unbounded[non_uniform_index]); - let _e33 = u2_; - u2_ = (_e33 + _e32); - let _e42 = textureGather(0, texture_array_bounded[0], samp[0], uv); - let _e43 = v4_; - v4_ = (_e43 + _e42); - let _e50 = textureGather(0, texture_array_bounded[uniform_index], samp[uniform_index], uv); - let _e51 = v4_; - v4_ = (_e51 + _e50); - let _e58 = textureGather(0, texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); - let _e59 = v4_; - v4_ = (_e59 + _e58); - let _e68 = textureGatherCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e21 = textureDimensions(texture_array_unbounded[0]); + let _e22 = u2_; + u2_ = (_e22 + _e21); + let _e26 = textureDimensions(texture_array_unbounded[uniform_index]); + let _e27 = u2_; + u2_ = (_e27 + _e26); + let _e31 = textureDimensions(texture_array_unbounded[non_uniform_index]); + let _e32 = u2_; + u2_ = (_e32 + _e31); + let _e38 = textureGather(0, texture_array_bounded[0], samp[0], uv); + let _e39 = v4_; + v4_ = (_e39 + _e38); + let _e45 = textureGather(0, texture_array_bounded[uniform_index], samp[uniform_index], uv); + let _e46 = v4_; + v4_ = (_e46 + _e45); + let _e52 = textureGather(0, texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); + let _e53 = v4_; + v4_ = (_e53 + _e52); + let _e60 = textureGatherCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e61 = v4_; + v4_ = (_e61 + _e60); + let _e68 = textureGatherCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); let _e69 = v4_; v4_ = (_e69 + _e68); - let _e76 = textureGatherCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + let _e76 = textureGatherCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); let _e77 = v4_; v4_ = (_e77 + _e76); - let _e84 = textureGatherCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); - let _e85 = v4_; - v4_ = (_e85 + _e84); - let _e91 = textureLoad(texture_array_unbounded[0], pix, 0); - let _e92 = v4_; - v4_ = (_e92 + _e91); - let _e97 = textureLoad(texture_array_unbounded[uniform_index], pix, 0); - let _e98 = v4_; - v4_ = (_e98 + _e97); - let _e103 = textureLoad(texture_array_unbounded[non_uniform_index], pix, 0); - let _e104 = v4_; - v4_ = (_e104 + _e103); - let _e109 = textureNumLayers(texture_array_2darray[0]); + let _e82 = textureLoad(texture_array_unbounded[0], pix, 0); + let _e83 = v4_; + v4_ = (_e83 + _e82); + let _e88 = textureLoad(texture_array_unbounded[uniform_index], pix, 0); + let _e89 = v4_; + v4_ = (_e89 + _e88); + let _e94 = textureLoad(texture_array_unbounded[non_uniform_index], pix, 0); + let _e95 = v4_; + v4_ = (_e95 + _e94); + let _e99 = textureNumLayers(texture_array_2darray[0]); + let _e100 = u1_; + u1_ = (_e100 + _e99); + let _e104 = textureNumLayers(texture_array_2darray[uniform_index]); + let _e105 = u1_; + u1_ = (_e105 + _e104); + let _e109 = textureNumLayers(texture_array_2darray[non_uniform_index]); let _e110 = u1_; u1_ = (_e110 + _e109); - let _e114 = textureNumLayers(texture_array_2darray[uniform_index]); + let _e114 = textureNumLevels(texture_array_bounded[0]); let _e115 = u1_; u1_ = (_e115 + _e114); - let _e119 = textureNumLayers(texture_array_2darray[non_uniform_index]); + let _e119 = textureNumLevels(texture_array_bounded[uniform_index]); let _e120 = u1_; u1_ = (_e120 + _e119); - let _e125 = textureNumLevels(texture_array_bounded[0]); - let _e126 = u1_; - u1_ = (_e126 + _e125); - let _e130 = textureNumLevels(texture_array_bounded[uniform_index]); - let _e131 = u1_; - u1_ = (_e131 + _e130); - let _e135 = textureNumLevels(texture_array_bounded[non_uniform_index]); - let _e136 = u1_; - u1_ = (_e136 + _e135); - let _e141 = textureNumSamples(texture_array_multisampled[0]); - let _e142 = u1_; - u1_ = (_e142 + _e141); - let _e146 = textureNumSamples(texture_array_multisampled[uniform_index]); - let _e147 = u1_; - u1_ = (_e147 + _e146); - let _e151 = textureNumSamples(texture_array_multisampled[non_uniform_index]); - let _e152 = u1_; - u1_ = (_e152 + _e151); - let _e160 = textureSample(texture_array_bounded[0], samp[0], uv); + let _e124 = textureNumLevels(texture_array_bounded[non_uniform_index]); + let _e125 = u1_; + u1_ = (_e125 + _e124); + let _e129 = textureNumSamples(texture_array_multisampled[0]); + let _e130 = u1_; + u1_ = (_e130 + _e129); + let _e134 = textureNumSamples(texture_array_multisampled[uniform_index]); + let _e135 = u1_; + u1_ = (_e135 + _e134); + let _e139 = textureNumSamples(texture_array_multisampled[non_uniform_index]); + let _e140 = u1_; + u1_ = (_e140 + _e139); + let _e146 = textureSample(texture_array_bounded[0], samp[0], uv); + let _e147 = v4_; + v4_ = (_e147 + _e146); + let _e153 = textureSample(texture_array_bounded[uniform_index], samp[uniform_index], uv); + let _e154 = v4_; + v4_ = (_e154 + _e153); + let _e160 = textureSample(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); let _e161 = v4_; v4_ = (_e161 + _e160); - let _e167 = textureSample(texture_array_bounded[uniform_index], samp[uniform_index], uv); - let _e168 = v4_; - v4_ = (_e168 + _e167); - let _e174 = textureSample(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv); - let _e175 = v4_; - v4_ = (_e175 + _e174); - let _e184 = textureSampleBias(texture_array_bounded[0], samp[0], uv, 0.0); + let _e168 = textureSampleBias(texture_array_bounded[0], samp[0], uv, 0.0); + let _e169 = v4_; + v4_ = (_e169 + _e168); + let _e176 = textureSampleBias(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + let _e177 = v4_; + v4_ = (_e177 + _e176); + let _e184 = textureSampleBias(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); let _e185 = v4_; v4_ = (_e185 + _e184); - let _e192 = textureSampleBias(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); - let _e193 = v4_; - v4_ = (_e193 + _e192); - let _e200 = textureSampleBias(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); - let _e201 = v4_; - v4_ = (_e201 + _e200); - let _e210 = textureSampleCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); - let _e211 = v1_; - v1_ = (_e211 + _e210); - let _e218 = textureSampleCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); - let _e219 = v1_; - v1_ = (_e219 + _e218); - let _e226 = textureSampleCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); - let _e227 = v1_; - v1_ = (_e227 + _e226); - let _e236 = textureSampleCompareLevel(texture_array_depth[0], samp_comp[0], uv, 0.0); - let _e237 = v1_; - v1_ = (_e237 + _e236); - let _e244 = textureSampleCompareLevel(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); - let _e245 = v1_; - v1_ = (_e245 + _e244); - let _e252 = textureSampleCompareLevel(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); - let _e253 = v1_; - v1_ = (_e253 + _e252); - let _e261 = textureSampleGrad(texture_array_bounded[0], samp[0], uv, uv, uv); + let _e192 = textureSampleCompare(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e193 = v1_; + v1_ = (_e193 + _e192); + let _e200 = textureSampleCompare(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + let _e201 = v1_; + v1_ = (_e201 + _e200); + let _e208 = textureSampleCompare(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + let _e209 = v1_; + v1_ = (_e209 + _e208); + let _e216 = textureSampleCompareLevel(texture_array_depth[0], samp_comp[0], uv, 0.0); + let _e217 = v1_; + v1_ = (_e217 + _e216); + let _e224 = textureSampleCompareLevel(texture_array_depth[uniform_index], samp_comp[uniform_index], uv, 0.0); + let _e225 = v1_; + v1_ = (_e225 + _e224); + let _e232 = textureSampleCompareLevel(texture_array_depth[non_uniform_index], samp_comp[non_uniform_index], uv, 0.0); + let _e233 = v1_; + v1_ = (_e233 + _e232); + let _e239 = textureSampleGrad(texture_array_bounded[0], samp[0], uv, uv, uv); + let _e240 = v4_; + v4_ = (_e240 + _e239); + let _e246 = textureSampleGrad(texture_array_bounded[uniform_index], samp[uniform_index], uv, uv, uv); + let _e247 = v4_; + v4_ = (_e247 + _e246); + let _e253 = textureSampleGrad(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, uv, uv); + let _e254 = v4_; + v4_ = (_e254 + _e253); + let _e261 = textureSampleLevel(texture_array_bounded[0], samp[0], uv, 0.0); let _e262 = v4_; v4_ = (_e262 + _e261); - let _e268 = textureSampleGrad(texture_array_bounded[uniform_index], samp[uniform_index], uv, uv, uv); - let _e269 = v4_; - v4_ = (_e269 + _e268); - let _e275 = textureSampleGrad(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, uv, uv); - let _e276 = v4_; - v4_ = (_e276 + _e275); - let _e285 = textureSampleLevel(texture_array_bounded[0], samp[0], uv, 0.0); - let _e286 = v4_; - v4_ = (_e286 + _e285); - let _e293 = textureSampleLevel(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + let _e269 = textureSampleLevel(texture_array_bounded[uniform_index], samp[uniform_index], uv, 0.0); + let _e270 = v4_; + v4_ = (_e270 + _e269); + let _e277 = textureSampleLevel(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); + let _e278 = v4_; + v4_ = (_e278 + _e277); + let _e282 = v4_; + textureStore(texture_array_storage[0], pix, _e282); + let _e285 = v4_; + textureStore(texture_array_storage[uniform_index], pix, _e285); + let _e288 = v4_; + textureStore(texture_array_storage[non_uniform_index], pix, _e288); + let _e289 = u2_; + let _e290 = u1_; + let v2_ = vec2((_e289 + vec2(_e290))); let _e294 = v4_; - v4_ = (_e294 + _e293); - let _e301 = textureSampleLevel(texture_array_bounded[non_uniform_index], samp[non_uniform_index], uv, 0.0); - let _e302 = v4_; - v4_ = (_e302 + _e301); - let _e307 = v4_; - textureStore(texture_array_storage[0], pix, _e307); - let _e310 = v4_; - textureStore(texture_array_storage[uniform_index], pix, _e310); - let _e313 = v4_; - textureStore(texture_array_storage[non_uniform_index], pix, _e313); - let _e314 = u2_; - let _e315 = u1_; - let v2_ = vec2((_e314 + vec2(_e315))); - let _e319 = v4_; - let _e326 = v1_; - return ((_e319 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e326)); + let _e301 = v1_; + return ((_e294 + vec4(v2_.x, v2_.y, v2_.x, v2_.y)) + vec4(_e301)); } diff --git a/tests/out/wgsl/binding-buffer-arrays.wgsl b/tests/out/wgsl/binding-buffer-arrays.wgsl index 4a36faa39..d28237d75 100644 --- a/tests/out/wgsl/binding-buffer-arrays.wgsl +++ b/tests/out/wgsl/binding-buffer-arrays.wgsl @@ -22,15 +22,15 @@ fn main(fragment_in: FragmentIn) -> @location(0) @interpolate(flat) u32 { let uniform_index = uni.index; let non_uniform_index = fragment_in.index; u1_ = 0u; - let _e11 = storage_array[0].x; - let _e12 = u1_; - u1_ = (_e12 + _e11); - let _e17 = storage_array[uniform_index].x; - let _e18 = u1_; - u1_ = (_e18 + _e17); - let _e23 = storage_array[non_uniform_index].x; - let _e24 = u1_; - u1_ = (_e24 + _e23); - let _e26 = u1_; - return _e26; + let _e10 = storage_array[0].x; + let _e11 = u1_; + u1_ = (_e11 + _e10); + let _e16 = storage_array[uniform_index].x; + let _e17 = u1_; + u1_ = (_e17 + _e16); + let _e22 = storage_array[non_uniform_index].x; + let _e23 = u1_; + u1_ = (_e23 + _e22); + let _e25 = u1_; + return _e25; } diff --git a/tests/out/wgsl/do-while.wgsl b/tests/out/wgsl/do-while.wgsl index 50ed369f4..0b7e3afbc 100644 --- a/tests/out/wgsl/do-while.wgsl +++ b/tests/out/wgsl/do-while.wgsl @@ -2,8 +2,8 @@ fn fb1_(cond: ptr) { loop { continue; continuing { - let _e2 = (*cond); - break if !(_e2); + let _e1 = (*cond); + break if !(_e1); } } return; diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl index 11aa6b96e..5114003be 100644 --- a/tests/out/wgsl/empty-global-name.wgsl +++ b/tests/out/wgsl/empty-global-name.wgsl @@ -6,8 +6,8 @@ struct type_1 { var unnamed: type_1; fn function() { - let _e4 = unnamed.member; - unnamed.member = (_e4 + 1); + let _e3 = unnamed.member; + unnamed.member = (_e3 + 1); return; } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index 3cd484487..af72c0cb8 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -33,8 +33,8 @@ fn test_msl_packed_vec3_() { idx = 1; alignment.v3_.x = 1.0; alignment.v3_.x = 2.0; - let _e17 = idx; - alignment.v3_[_e17] = 3.0; + let _e16 = idx; + alignment.v3_[_e16] = 3.0; let data = alignment; let l0_ = data.v3_; let l1_ = data.v3_.zx; @@ -51,20 +51,20 @@ fn main() { var at: bool; test_msl_packed_vec3_(); - let _e8 = global_nested_arrays_of_matrices_4x2_[0][0]; - let _e16 = global_nested_arrays_of_matrices_2x4_[0][0][0]; - wg[7] = (_e8 * _e16).x; - let _e23 = global_mat; - let _e25 = global_vec; - wg[6] = (_e23 * _e25).x; - let _e35 = dummy[1].y; - wg[5] = _e35; - let _e43 = float_vecs[0].w; - wg[4] = _e43; - let _e49 = alignment.v1_; - wg[3] = _e49; - let _e56 = alignment.v3_.x; - wg[2] = _e56; + let _e5 = global_nested_arrays_of_matrices_4x2_[0][0]; + let _e10 = global_nested_arrays_of_matrices_2x4_[0][0][0]; + wg[7] = (_e5 * _e10).x; + let _e16 = global_mat; + let _e18 = global_vec; + wg[6] = (_e16 * _e18).x; + let _e26 = dummy[1].y; + wg[5] = _e26; + let _e32 = float_vecs[0].w; + wg[4] = _e32; + let _e37 = alignment.v1_; + wg[3] = _e37; + let _e43 = alignment.v3_.x; + wg[2] = _e43; alignment.v1_ = 4.0; wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 3fb0846bf..f444c6db0 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -223,10 +223,10 @@ fn assignment() { let _e36 = a_1; a_1 = (_e36 - 1); vec0_ = vec3(); - let _e43 = vec0_.y; - vec0_.y = (_e43 + 1); - let _e48 = vec0_.y; - vec0_.y = (_e48 - 1); + let _e42 = vec0_.y; + vec0_.y = (_e42 + 1); + let _e46 = vec0_.y; + vec0_.y = (_e46 - 1); return; } diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl index 72da615cc..df7c6d000 100644 --- a/tests/out/wgsl/quad-vert.wgsl +++ b/tests/out/wgsl/quad-vert.wgsl @@ -16,10 +16,10 @@ var perVertexStruct: gl_PerVertex = gl_PerVertex(vec4(0.0, 0.0, 0. var a_pos_1: vec2; fn main_1() { - let _e8 = a_uv_1; - v_uv = _e8; - let _e9 = a_pos_1; - perVertexStruct.gl_Position = vec4(_e9.x, _e9.y, 0.0, 1.0); + let _e6 = a_uv_1; + v_uv = _e6; + let _e7 = a_pos_1; + perVertexStruct.gl_Position = vec4(_e7.x, _e7.y, 0.0, 1.0); return; } diff --git a/tests/snapshots.rs b/tests/snapshots.rs index dce0a7edf..4dcf1dd4d 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -89,7 +89,12 @@ struct Parameters { } #[allow(unused_variables)] -fn check_targets(module: &naga::Module, name: &str, targets: Targets, source_code: Option<&str>) { +fn check_targets( + module: &mut naga::Module, + name: &str, + targets: Targets, + source_code: Option<&str>, +) { let root = env!("CARGO_MANIFEST_DIR"); let filepath = format!("{root}/{BASE_DIR_IN}/{name}.param.ron"); let params = match fs::read_to_string(&filepath) { @@ -120,6 +125,26 @@ fn check_targets(module: &naga::Module, name: &str, targets: Targets, source_cod .validate(module) .expect(&format!("Naga module validation failed on test '{name}'")); + #[cfg(feature = "compact")] + let info = { + naga::compact::compact(module); + + #[cfg(feature = "serialize")] + { + if targets.contains(Targets::IR) { + let config = ron::ser::PrettyConfig::default().new_line("\n".to_string()); + let string = ron::ser::to_string_pretty(module, config).unwrap(); + fs::write(dest.join(format!("ir/{name}.compact.ron")), string).unwrap(); + } + } + + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities) + .validate(module) + .expect(&format!( + "Post-compaction module validation failed on test '{name}'" + )) + }; + #[cfg(feature = "serialize")] { if targets.contains(Targets::ANALYSIS) { @@ -284,6 +309,7 @@ fn write_output_spv_inner( ) { use naga::back::spv; use rspirv::binary::Disassemble; + println!("Writing SPIR-V {}", path); let spv = spv::write_vec(module, info, options, pipeline_options).unwrap(); let dis = rspirv::dr::load_words(spv) .expect("Produced invalid SPIR-V") @@ -624,7 +650,7 @@ fn convert_wgsl() { let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/{name}.wgsl")) .expect("Couldn't find wgsl file"); match naga::front::wgsl::parse_str(&file) { - Ok(module) => check_targets(&module, name, targets, None), + Ok(mut module) => check_targets(&mut module, name, targets, None), Err(e) => panic!("{}", e.emit_to_string(&file)), } } @@ -641,7 +667,7 @@ fn convert_wgsl() { let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/{name}.wgsl")) .expect("Couldn't find wgsl file"); match naga::front::wgsl::parse_str(&file) { - Ok(module) => check_targets(&module, name, targets, Some(&file)), + Ok(mut module) => check_targets(&mut module, name, targets, Some(&file)), Err(e) => panic!("{}", e.emit_to_string(&file)), } } @@ -655,7 +681,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { let root = env!("CARGO_MANIFEST_DIR"); println!("Processing '{name}'"); - let module = naga::front::spv::parse_u8_slice( + let mut module = naga::front::spv::parse_u8_slice( &fs::read(format!("{root}/{BASE_DIR_IN}/spv/{name}.spv")).expect("Couldn't find spv file"), &naga::front::spv::Options { adjust_coordinate_space, @@ -664,7 +690,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { }, ) .unwrap(); - check_targets(&module, name, targets, None); + check_targets(&mut module, name, targets, None); naga::valid::Validator::new( naga::valid::ValidationFlags::all(), naga::valid::Capabilities::default(), @@ -709,7 +735,7 @@ fn convert_glsl_variations_check() { let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/variations.glsl")) .expect("Couldn't find glsl file"); let mut parser = naga::front::glsl::Frontend::default(); - let module = parser + let mut module = parser .parse( &naga::front::glsl::Options { stage: naga::ShaderStage::Fragment, @@ -718,7 +744,7 @@ fn convert_glsl_variations_check() { &file, ) .unwrap(); - check_targets(&module, "variations-glsl", Targets::GLSL, None); + check_targets(&mut module, "variations-glsl", Targets::GLSL, None); } #[cfg(feature = "glsl-in")] From b586631efebffbd56021094b61d24335a61a783f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 10:20:47 -0700 Subject: [PATCH 2093/2212] Small cleanups to backend naming. (#2491) Document `FunctionType` better. Use `FunctionCtx` name key methods where appropriate in the WGSL and HLSL backends. --- src/back/hlsl/writer.rs | 7 +------ src/back/mod.rs | 23 +++++++++++++++++++---- src/back/wgsl/writer.rs | 9 +-------- 3 files changed, 21 insertions(+), 18 deletions(-) diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 6da98502f..e9809bd2d 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2352,12 +2352,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Expression::FunctionArgument(pos) => { - let key = match func_ctx.ty { - back::FunctionType::Function(handle) => NameKey::FunctionArgument(handle, pos), - back::FunctionType::EntryPoint(index) => { - NameKey::EntryPointArgument(index, pos) - } - }; + let key = func_ctx.argument_key(pos); let name = &self.names[&key]; write!(self.out, "{name}")?; } diff --git a/src/back/mod.rs b/src/back/mod.rs index 875b04d69..1314e14d7 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -37,13 +37,28 @@ impl std::fmt::Display for Level { } } -/// Stores the current function type (either a regular function or an entry point) +/// Whether we're generating an entry point or a regular function. /// -/// Also stores data needed to identify it (handle for a regular function or index for an entry point) +/// Backend languages often require different code for a [`Function`] +/// depending on whether it represents an [`EntryPoint`] or not. +/// Backends can pass common code one of these values to select the +/// right behavior. +/// +/// These values also carry enough information to find the `Function` +/// in the [`Module`]: the `Handle` for a regular function, or the +/// index into [`Module::entry_points`] for an entry point. +/// +/// [`Function`]: crate::Function +/// [`EntryPoint`]: crate::EntryPoint +/// [`Module`]: crate::Module +/// [`Module::entry_points`]: crate::Module::entry_points enum FunctionType { - /// A regular function and it's handle + /// A regular function. Function(crate::Handle), - /// A entry point and it's index + /// An [`EntryPoint`], and its index in [`Module::entry_points`]. + /// + /// [`EntryPoint`]: crate::EntryPoint + /// [`Module::entry_points`]: crate::Module::entry_points EntryPoint(crate::proc::EntryPointIndex), } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 3a0424e7b..980d76878 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -247,14 +247,7 @@ impl Writer { self.write_attributes(&map_binding_to_attribute(binding))?; } // Write argument name - let argument_name = match func_ctx.ty { - back::FunctionType::Function(handle) => { - &self.names[&NameKey::FunctionArgument(handle, index as u32)] - } - back::FunctionType::EntryPoint(ep_index) => { - &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)] - } - }; + let argument_name = &self.names[&func_ctx.argument_key(index as u32)]; write!(self.out, "{argument_name}: ")?; // Write argument type From 9105036be7f60bb9fc35eecad5248a90b2827f2c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 15:25:47 -0700 Subject: [PATCH 2094/2212] Use `FastIndexSet` for `UniqueArena`. --- src/arena.rs | 11 +++++------ src/compact/mod.rs | 6 +++--- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 1499cf177..49b932801 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -5,8 +5,7 @@ use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32, ops}; /// the same size and representation as `Handle`. type Index = NonZeroU32; -use crate::Span; -use indexmap::set::IndexSet; +use crate::{FastIndexSet, Span}; #[derive(Clone, Copy, Debug, thiserror::Error, PartialEq)] #[error("Handle {index} of {kind} is either not present, or inaccessible yet")] @@ -516,11 +515,11 @@ mod tests { /// `UniqueArena` is `HashSet`-like. #[cfg_attr(feature = "clone", derive(Clone))] pub struct UniqueArena { - set: IndexSet, + set: FastIndexSet, /// Spans for the elements, indexed by handle. /// - /// The length of this vector is always equal to `set.len()`. `IndexSet` + /// The length of this vector is always equal to `set.len()`. `FastIndexSet` /// promises that its elements "are indexed in a compact range, without /// holes in the range 0..set.len()", so we can always use the indices /// returned by insertion as indices into this vector. @@ -532,7 +531,7 @@ impl UniqueArena { /// Create a new arena with no initial capacity allocated. pub fn new() -> Self { UniqueArena { - set: IndexSet::new(), + set: FastIndexSet::default(), #[cfg(feature = "span")] span_info: Vec::new(), } @@ -741,7 +740,7 @@ where where D: serde::Deserializer<'de>, { - let set = IndexSet::deserialize(deserializer)?; + let set = FastIndexSet::deserialize(deserializer)?; #[cfg(feature = "span")] let span_info = std::iter::repeat(Span::default()).take(set.len()).collect(); diff --git a/src/compact/mod.rs b/src/compact/mod.rs index e0de1fe97..137f3bbe3 100644 --- a/src/compact/mod.rs +++ b/src/compact/mod.rs @@ -95,9 +95,9 @@ pub fn compact(module: &mut crate::Module) { // Drop unused types from the type arena. // - // `IndexSet`s don't have an underlying Vec that we can steal, compact in - // place, and then rebuild the `IndexSet` from. So we have to rebuild the - // type arena from scratch. + // `FastIndexSet`s don't have an underlying Vec that we can + // steal, compact in place, and then rebuild the `FastIndexSet` + // from. So we have to rebuild the type arena from scratch. log::trace!("compacting types"); let mut new_types = arena::UniqueArena::new(); for (old_handle, mut ty, span) in module.types.drain_all() { From ae0423835d195f915b582ce7e5b25bca128142d0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 15:34:26 -0700 Subject: [PATCH 2095/2212] Introduce `FastIndexMap` type alias, and use it for NamedExpressions. --- src/lib.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 92a0ba2ce..b220872dd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -310,12 +310,13 @@ pub type FastHashSet = rustc_hash::FxHashSet; pub type FastIndexSet = indexmap::IndexSet>; +/// Insertion-order-preserving hash map (`IndexMap`), but with the same +/// hasher as `FastHashMap` (faster but not resilient to DoS attacks). +pub type FastIndexMap = + indexmap::IndexMap>; + /// Map of expressions that have associated variable names -pub(crate) type NamedExpressions = indexmap::IndexMap< - Handle, - String, - std::hash::BuildHasherDefault, ->; +pub(crate) type NamedExpressions = FastIndexMap, String>; /// Early fragment tests. /// From 6a254d904de670c8df481fcba71fff4eb035c349 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 15:36:03 -0700 Subject: [PATCH 2096/2212] [wgsl-in] Use FastIndexMap for temporary named expressions table. --- src/front/wgsl/lower/mod.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 36366d013..56d870970 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -6,8 +6,7 @@ use crate::front::wgsl::parse::number::Number; use crate::front::wgsl::parse::{ast, conv}; use crate::front::{Emitter, Typifier}; use crate::proc::{ensure_block_returns, Alignment, Layouter, ResolveContext, TypeResolution}; -use crate::{Arena, FastHashMap, Handle, Span}; -use indexmap::IndexMap; +use crate::{Arena, FastHashMap, FastIndexMap, Handle, Span}; mod construction; @@ -101,7 +100,7 @@ pub struct StatementContext<'source, 'temp, 'out> { naga_expressions: &'out mut Arena, /// Stores the names of expressions that are assigned in `let` statement /// Also stores the spans of the names, for use in errors. - named_expressions: &'out mut IndexMap, (String, Span)>, + named_expressions: &'out mut FastIndexMap, (String, Span)>, arguments: &'out [crate::FunctionArgument], module: &'out mut crate::Module, } @@ -915,7 +914,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut local_table = FastHashMap::default(); let mut local_variables = Arena::new(); let mut expressions = Arena::new(); - let mut named_expressions = IndexMap::default(); + let mut named_expressions = FastIndexMap::default(); let arguments = f .arguments From 89523aec0887bab4d751e2d3fd3c0dfa154fc734 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 15:38:46 -0700 Subject: [PATCH 2097/2212] Use `FastIndexMap` for `SpecialTypes::predeclared_types`. --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index b220872dd..935157289 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1996,7 +1996,7 @@ pub struct SpecialTypes { /// /// Call [`Module::generate_predeclared_type`] to populate this if /// needed and return the handle. - pub predeclared_types: indexmap::IndexMap>, + pub predeclared_types: FastIndexMap>, } /// Shader module. From 1b1ea37f156c4eab7c9b35b2ffeb599e9efeee8a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 15:40:28 -0700 Subject: [PATCH 2098/2212] [spv-out] Use `FastIndexMap` for `Frontend::switch_cases`. --- src/front/spv/mod.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 36108fdd9..5fd54b023 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -40,7 +40,7 @@ use function::*; use crate::{ arena::{Arena, Handle, UniqueArena}, proc::{Alignment, Layouter}, - FastHashMap, FastHashSet, + FastHashMap, FastHashSet, FastIndexMap, }; use num_traits::cast::FromPrimitive; @@ -596,11 +596,7 @@ pub struct Frontend { /// use that target block id. /// /// Used to preserve allocations between instruction parsing. - switch_cases: indexmap::IndexMap< - spirv::Word, - (BodyIndex, Vec), - std::hash::BuildHasherDefault, - >, + switch_cases: FastIndexMap)>, /// Tracks access to gl_PerVertex's builtins, it is used to cull unused builtins since initializing those can /// affect performance and the mere presence of some of these builtins might cause backends to error since they @@ -641,7 +637,7 @@ impl> Frontend { dummy_functions: Arena::new(), function_call_graph: GraphMap::new(), options: options.clone(), - switch_cases: indexmap::IndexMap::default(), + switch_cases: FastIndexMap::default(), gl_per_vertex_builtin_access: FastHashSet::default(), } } From 57bebbcd200aa3dbbabcc0a1d3fbefacb500395d Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 15:52:09 -0700 Subject: [PATCH 2099/2212] [wgsl-in] Use deterministic ordering for dependency ordering. Use `FastIndexSet`, rather than `FastHashSet`, for tracking global declarations' dependencies, so that the order in which functions are inserted into the `Module` is not dependent on the hash function. --- src/front/wgsl/parse/ast.rs | 4 ++-- src/front/wgsl/parse/mod.rs | 8 ++++---- tests/out/wgsl/module-scope.wgsl | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/front/wgsl/parse/ast.rs b/src/front/wgsl/parse/ast.rs index 34aeb21a1..fca7457f0 100644 --- a/src/front/wgsl/parse/ast.rs +++ b/src/front/wgsl/parse/ast.rs @@ -1,5 +1,5 @@ use crate::front::wgsl::parse::number::Number; -use crate::{Arena, FastHashSet, Handle, Span}; +use crate::{Arena, FastIndexSet, Handle, Span}; use std::hash::Hash; #[derive(Debug, Default)] @@ -73,7 +73,7 @@ pub struct GlobalDecl<'a> { /// Names of all module-scope or predeclared objects this /// declaration uses. - pub dependencies: FastHashSet>, + pub dependencies: FastIndexSet>, } #[derive(Debug)] diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 86dd12799..325a8e690 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -2,7 +2,7 @@ use crate::front::wgsl::error::{Error, ExpectedToken}; use crate::front::wgsl::parse::lexer::{Lexer, Token}; use crate::front::wgsl::parse::number::Number; use crate::front::SymbolTable; -use crate::{Arena, FastHashSet, Handle, ShaderStage, Span}; +use crate::{Arena, FastIndexSet, Handle, ShaderStage, Span}; pub mod ast; pub mod conv; @@ -51,7 +51,7 @@ struct ExpressionContext<'input, 'temp, 'out> { /// /// [`GlobalDecl`]: ast::GlobalDecl /// [`dependencies`]: ast::GlobalDecl::dependencies - unresolved: &'out mut FastHashSet>, + unresolved: &'out mut FastIndexSet>, } impl<'a> ExpressionContext<'a, '_, '_> { @@ -2076,7 +2076,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, out: &mut ast::TranslationUnit<'a>, - dependencies: &mut FastHashSet>, + dependencies: &mut FastIndexSet>, ) -> Result, Error<'a>> { self.push_rule_span(Rule::FunctionDecl, lexer); // read function name @@ -2238,7 +2238,7 @@ impl Parser { (None, None) => {} } - let mut dependencies = FastHashSet::default(); + let mut dependencies = FastIndexSet::default(); let mut ctx = ExpressionContext { expressions: &mut out.expressions, local_table: &mut SymbolTable::default(), diff --git a/tests/out/wgsl/module-scope.wgsl b/tests/out/wgsl/module-scope.wgsl index 141c28b50..3276a0a10 100644 --- a/tests/out/wgsl/module-scope.wgsl +++ b/tests/out/wgsl/module-scope.wgsl @@ -9,14 +9,14 @@ var Texture: texture_2d; @group(0) @binding(1) var Sampler: sampler; -fn returns() -> S { - return S(Value); -} - fn statement() { return; } +fn returns() -> S { + return S(Value); +} + fn call() { statement(); let _e0 = returns(); From 711aa1a834a3adfdc07595bcee7d60d54e483047 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 24 Sep 2023 16:34:43 -0700 Subject: [PATCH 2100/2212] snapshots: convert_spv: Don't validate the module twice. Remove the call to `Validator::validate` in `convert_spv`, since it directly follows the call to `check_targets`, which also called `Validator::validate`. The only difference between the two is whether `Parameters::god_mode` is respected, but this difference doesn't seem to have been deliberate: at the time the call to `check_targets` was added to `convert_spv` (5f21cf360, 2021-02-17), the two calls were exactly the same. --- tests/snapshots.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 4dcf1dd4d..80b083466 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -691,12 +691,6 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { ) .unwrap(); check_targets(&mut module, name, targets, None); - naga::valid::Validator::new( - naga::valid::ValidationFlags::all(), - naga::valid::Capabilities::default(), - ) - .validate(&module) - .unwrap(); } #[cfg(feature = "spv-in")] From dc3d2b1e78ba7c0c2066ea37379ea2626ef5943d Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins Date: Mon, 25 Sep 2023 06:19:52 -0400 Subject: [PATCH 2101/2212] [glsl-out] Polyfill frexp --- src/back/glsl/mod.rs | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 54d5f341a..8a8dea664 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -189,6 +189,10 @@ impl Version { *self >= Version::Desktop(400) || *self >= Version::new_gles(310) } + fn supports_frexp_function(&self) -> bool { + *self >= Version::Desktop(400) || *self >= Version::new_gles(310) + } + fn supports_derivative_control(&self) -> bool { *self >= Version::Desktop(450) } @@ -667,15 +671,27 @@ impl<'a, W: Write> Writer<'a, W> { let struct_name = &self.names[&NameKey::Type(*struct_ty)]; writeln!(self.out)?; - writeln!( - self.out, - "{} {defined_func_name}({arg_type_name} arg) {{ + if !self.options.version.supports_frexp_function() + && matches!(type_key, &crate::PredeclaredType::FrexpResult { .. }) + { + writeln!( + self.out, + "{struct_name} {defined_func_name}({arg_type_name} arg) {{ + {other_type_name} other = arg == {arg_type_name}(0) ? {other_type_name}(0) : {other_type_name}({arg_type_name}(1) + log2(arg)); + {arg_type_name} fract = arg * exp2({arg_type_name}(-other)); + return {struct_name}(fract, other); +}}", + )?; + } else { + writeln!( + self.out, + "{struct_name} {defined_func_name}({arg_type_name} arg) {{ {other_type_name} other; {arg_type_name} fract = {called_func_name}(arg, other); - return {}(fract, other); + return {struct_name}(fract, other); }}", - struct_name, struct_name - )?; + )?; + } } &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {} } From bc0fc97b26ad4b79c0379315bc5f37ba96bd8ac1 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 23 Sep 2023 15:32:16 -0700 Subject: [PATCH 2102/2212] Delete output files no longer generated by snapshot tests. --- tests/out/glsl/access.atomics.Compute.glsl | 73 ------------------- .../glsl/fragment-output.main.Fragment.glsl | 62 ---------------- .../glsl/invariant.frag_main.Fragment.glsl | 11 --- tests/out/glsl/quad.main.Fragment.glsl | 26 ------- tests/out/glsl/quad.main.Vertex.glsl | 23 ------ tests/out/hlsl/bits.hlsl.config | 3 - tests/out/hlsl/constructors.hlsl.config | 3 - tests/out/spv/pointer-access.spvasm | 55 -------------- 8 files changed, 256 deletions(-) delete mode 100644 tests/out/glsl/access.atomics.Compute.glsl delete mode 100644 tests/out/glsl/fragment-output.main.Fragment.glsl delete mode 100644 tests/out/glsl/invariant.frag_main.Fragment.glsl delete mode 100644 tests/out/glsl/quad.main.Fragment.glsl delete mode 100644 tests/out/glsl/quad.main.Vertex.glsl delete mode 100644 tests/out/hlsl/bits.hlsl.config delete mode 100644 tests/out/hlsl/constructors.hlsl.config delete mode 100644 tests/out/spv/pointer-access.spvasm diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl deleted file mode 100644 index 8ccefe422..000000000 --- a/tests/out/glsl/access.atomics.Compute.glsl +++ /dev/null @@ -1,73 +0,0 @@ -#version 310 es - -precision highp float; -precision highp int; - -layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; - -struct GlobalConst { - uint a; - uvec3 b; - int c; -}; -struct AlignedWrapper { - int value; -}; -struct Baz { - mat3x2 m; -}; -struct MatCx2InArray { - mat4x2 am[2]; -}; -layout(std430) buffer Bar_block_0Compute { - mat4x3 _matrix; - mat2x2 matrix_array[2]; - int atom; - int atom_arr[10]; - uvec2 arr[2]; - AlignedWrapper data[]; -} _group_0_binding_0_cs; - - -float read_from_private(inout float foo_1) { - float _e1 = foo_1; - return _e1; -} - -float test_arr_as_arg(float a[5][10]) { - return a[4][9]; -} - -void assign_through_ptr_fn(inout uint p) { - p = 42u; - return; -} - -void assign_array_through_ptr_fn(inout vec4 foo_2[2]) { - foo_2 = vec4[2](vec4(1.0), vec4(2.0)); - return; -} - -void main() { - int tmp = 0; - int value = _group_0_binding_0_cs.atom; - int _e7 = atomicAdd(_group_0_binding_0_cs.atom, 5); - tmp = _e7; - int _e11 = atomicAdd(_group_0_binding_0_cs.atom, -5); - tmp = _e11; - int _e15 = atomicAnd(_group_0_binding_0_cs.atom, 5); - tmp = _e15; - int _e19 = atomicOr(_group_0_binding_0_cs.atom, 5); - tmp = _e19; - int _e23 = atomicXor(_group_0_binding_0_cs.atom, 5); - tmp = _e23; - int _e27 = atomicMin(_group_0_binding_0_cs.atom, 5); - tmp = _e27; - int _e31 = atomicMax(_group_0_binding_0_cs.atom, 5); - tmp = _e31; - int _e35 = atomicExchange(_group_0_binding_0_cs.atom, 5); - tmp = _e35; - _group_0_binding_0_cs.atom = value; - return; -} - diff --git a/tests/out/glsl/fragment-output.main.Fragment.glsl b/tests/out/glsl/fragment-output.main.Fragment.glsl deleted file mode 100644 index f8299e2ba..000000000 --- a/tests/out/glsl/fragment-output.main.Fragment.glsl +++ /dev/null @@ -1,62 +0,0 @@ -#version 310 es - -precision highp float; -precision highp int; - -struct FragmentOutput { - vec4 vec4f; - ivec4 vec4i; - uvec4 vec4u; - vec3 vec3f; - ivec3 vec3i; - uvec3 vec3u; - vec2 vec2f; - ivec2 vec2i; - uvec2 vec2u; - float scalarf; - int scalari; - uint scalaru; -}; -layout(location = 0) out vec4 _fs2p_location0; -layout(location = 1) out ivec4 _fs2p_location1; -layout(location = 2) out uvec4 _fs2p_location2; -layout(location = 3) out vec3 _fs2p_location3; -layout(location = 4) out ivec3 _fs2p_location4; -layout(location = 5) out uvec3 _fs2p_location5; -layout(location = 6) out vec2 _fs2p_location6; -layout(location = 7) out ivec2 _fs2p_location7; -layout(location = 8) out uvec2 _fs2p_location8; -layout(location = 9) out float _fs2p_location9; -layout(location = 10) out int _fs2p_location10; -layout(location = 11) out uint _fs2p_location11; - -void main() { - FragmentOutput output_ = FragmentOutput(vec4(0.0), ivec4(0), uvec4(0u), vec3(0.0), ivec3(0), uvec3(0u), vec2(0.0), ivec2(0), uvec2(0u), 0.0, 0, 0u); - output_.vec4f = vec4(0.0); - output_.vec4i = ivec4(0); - output_.vec4u = uvec4(0u); - output_.vec3f = vec3(0.0); - output_.vec3i = ivec3(0); - output_.vec3u = uvec3(0u); - output_.vec2f = vec2(0.0); - output_.vec2i = ivec2(0); - output_.vec2u = uvec2(0u); - output_.scalarf = 0.0; - output_.scalari = 0; - output_.scalaru = 0u; - FragmentOutput _e34 = output_; - _fs2p_location0 = _e34.vec4f; - _fs2p_location1 = _e34.vec4i; - _fs2p_location2 = _e34.vec4u; - _fs2p_location3 = _e34.vec3f; - _fs2p_location4 = _e34.vec3i; - _fs2p_location5 = _e34.vec3u; - _fs2p_location6 = _e34.vec2f; - _fs2p_location7 = _e34.vec2i; - _fs2p_location8 = _e34.vec2u; - _fs2p_location9 = _e34.scalarf; - _fs2p_location10 = _e34.scalari; - _fs2p_location11 = _e34.scalaru; - return; -} - diff --git a/tests/out/glsl/invariant.frag_main.Fragment.glsl b/tests/out/glsl/invariant.frag_main.Fragment.glsl deleted file mode 100644 index 9936a28ad..000000000 --- a/tests/out/glsl/invariant.frag_main.Fragment.glsl +++ /dev/null @@ -1,11 +0,0 @@ -#version 300 es - -precision highp float; -precision highp int; - - -void main() { - vec4 position = gl_FragCoord; - return; -} - diff --git a/tests/out/glsl/quad.main.Fragment.glsl b/tests/out/glsl/quad.main.Fragment.glsl deleted file mode 100644 index b290ed5a0..000000000 --- a/tests/out/glsl/quad.main.Fragment.glsl +++ /dev/null @@ -1,26 +0,0 @@ -#version 300 es - -precision highp float; -precision highp int; - -struct VertexOutput { - vec2 uv; - vec4 position; -}; - -uniform highp sampler2D _group_0_binding_0; - -smooth in vec2 _vs2fs_location0; -layout(location = 0) out vec4 _fs2p_location0; - -void main() { - vec2 uv_1 = _vs2fs_location0; - vec4 color = texture(_group_0_binding_0, vec2(uv_1)); - if ((color.w == 0.0)) { - discard; - } - vec4 premultiplied = (color.w * color); - _fs2p_location0 = premultiplied; - return; -} - diff --git a/tests/out/glsl/quad.main.Vertex.glsl b/tests/out/glsl/quad.main.Vertex.glsl deleted file mode 100644 index cda43f508..000000000 --- a/tests/out/glsl/quad.main.Vertex.glsl +++ /dev/null @@ -1,23 +0,0 @@ -#version 300 es - -precision highp float; -precision highp int; - -struct VertexOutput { - vec2 uv; - vec4 position; -}; - -layout(location = 0) in vec2 _p2vs_location0; -layout(location = 1) in vec2 _p2vs_location1; -smooth out vec2 _vs2fs_location0; - -void main() { - vec2 pos = _p2vs_location0; - vec2 uv = _p2vs_location1; - VertexOutput _tmp_return = VertexOutput(uv, vec4((1.2000000476837158 * pos), 0.0, 1.0)); - _vs2fs_location0 = _tmp_return.uv; - gl_Position = _tmp_return.position; - return; -} - diff --git a/tests/out/hlsl/bits.hlsl.config b/tests/out/hlsl/bits.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/bits.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/hlsl/constructors.hlsl.config b/tests/out/hlsl/constructors.hlsl.config deleted file mode 100644 index 246c485cf..000000000 --- a/tests/out/hlsl/constructors.hlsl.config +++ /dev/null @@ -1,3 +0,0 @@ -vertex=() -fragment=() -compute=(main:cs_5_1 ) diff --git a/tests/out/spv/pointer-access.spvasm b/tests/out/spv/pointer-access.spvasm deleted file mode 100644 index ef4b7bbce..000000000 --- a/tests/out/spv/pointer-access.spvasm +++ /dev/null @@ -1,55 +0,0 @@ -; SPIR-V -; Version: 1.0 -; Generator: rspirv -; Bound: 35 -OpCapability Shader -OpCapability Linkage -OpExtension "SPV_KHR_storage_buffer_storage_class" -%1 = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpSource GLSL 450 -OpDecorate %12 ArrayStride 4 -OpDecorate %14 ArrayStride 4 -OpDecorate %15 Block -OpMemberDecorate %15 0 Offset 0 -OpDecorate %17 DescriptorSet 0 -OpDecorate %17 Binding 0 -%2 = OpTypeVoid -%4 = OpTypeInt 32 1 -%3 = OpConstant %4 0 -%5 = OpConstant %4 1 -%6 = OpConstant %4 2 -%7 = OpConstant %4 3 -%9 = OpTypeInt 32 0 -%8 = OpConstant %9 0 -%10 = OpConstant %9 7 -%11 = OpTypePointer StorageBuffer %9 -%12 = OpTypeArray %9 %10 -%13 = OpTypePointer StorageBuffer %12 -%14 = OpTypeRuntimeArray %9 -%15 = OpTypeStruct %14 -%16 = OpTypePointer StorageBuffer %15 -%17 = OpVariable %16 StorageBuffer -%22 = OpTypeFunction %9 %13 %9 -%30 = OpTypeFunction %9 %16 %9 -%32 = OpTypePointer StorageBuffer %14 -%21 = OpFunction %9 None %22 -%19 = OpFunctionParameter %13 -%20 = OpFunctionParameter %9 -%18 = OpLabel -OpBranch %23 -%23 = OpLabel -%24 = OpAccessChain %11 %19 %20 -%25 = OpLoad %9 %24 -OpReturnValue %25 -OpFunctionEnd -%29 = OpFunction %9 None %30 -%27 = OpFunctionParameter %16 -%28 = OpFunctionParameter %9 -%26 = OpLabel -OpBranch %31 -%31 = OpLabel -%33 = OpAccessChain %11 %27 %8 %28 -%34 = OpLoad %9 %33 -OpReturnValue %34 -OpFunctionEnd \ No newline at end of file From 7060246357e626b94dc197f243a29a2455d3898a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 23 Sep 2023 15:47:41 -0700 Subject: [PATCH 2103/2212] Give `convert_glsl_folder`'s output more consistent names. Don't replace dots with dashes in the output filenames for no reason. Instead, give them names consistent with those generated by `write_output_glsl`. --- ...10-bevy-2d-shader-frag.wgsl => 210-bevy-2d-shader.frag.wgsl} | 0 ...10-bevy-2d-shader-vert.wgsl => 210-bevy-2d-shader.vert.wgsl} | 0 .../{210-bevy-shader-vert.wgsl => 210-bevy-shader.vert.wgsl} | 0 tests/out/wgsl/{246-collatz-comp.wgsl => 246-collatz.comp.wgsl} | 0 tests/out/wgsl/{277-casting-frag.wgsl => 277-casting.frag.wgsl} | 0 .../{280-matrix-cast-frag.wgsl => 280-matrix-cast.frag.wgsl} | 0 ...-preprocessor-if-frag.wgsl => 484-preprocessor-if.frag.wgsl} | 0 ...bounds-panic-vert.wgsl => 800-out-of-bounds-panic.vert.wgsl} | 0 ...{896-push-constant-frag.wgsl => 896-push-constant.frag.wgsl} | 0 ...conversions-frag.wgsl => 900-implicit-conversions.frag.wgsl} | 0 ...hs-field-select-frag.wgsl => 901-lhs-field-select.frag.wgsl} | 0 ...stant-emitting-frag.wgsl => 931-constant-emitting.frag.wgsl} | 0 .../{932-for-loop-if-frag.wgsl => 932-for-loop-if.frag.wgsl} | 0 tests/out/wgsl/{bevy-pbr-frag.wgsl => bevy-pbr.frag.wgsl} | 0 tests/out/wgsl/{bevy-pbr-vert.wgsl => bevy-pbr.vert.wgsl} | 0 tests/out/wgsl/{bits_glsl-frag.wgsl => bits_glsl.frag.wgsl} | 0 tests/out/wgsl/{bool-select-frag.wgsl => bool-select.frag.wgsl} | 0 tests/out/wgsl/{buffer-frag.wgsl => buffer.frag.wgsl} | 0 tests/out/wgsl/{clamp-splat-vert.wgsl => clamp-splat.vert.wgsl} | 0 ...stant-array-size-frag.wgsl => constant-array-size.frag.wgsl} | 0 .../out/wgsl/{declarations-frag.wgsl => declarations.frag.wgsl} | 0 tests/out/wgsl/{expressions-frag.wgsl => expressions.frag.wgsl} | 0 tests/out/wgsl/{fma-frag.wgsl => fma.frag.wgsl} | 0 .../wgsl/{functions_call-frag.wgsl => functions_call.frag.wgsl} | 0 ...constant-array-frag.wgsl => global-constant-array.frag.wgsl} | 0 tests/out/wgsl/{images-frag.wgsl => images.frag.wgsl} | 0 .../{long-form-matrix-frag.wgsl => long-form-matrix.frag.wgsl} | 0 .../wgsl/{math-functions-frag.wgsl => math-functions.frag.wgsl} | 0 tests/out/wgsl/{prepostfix-frag.wgsl => prepostfix.frag.wgsl} | 0 tests/out/wgsl/{quad_glsl-frag.wgsl => quad_glsl.frag.wgsl} | 0 tests/out/wgsl/{quad_glsl-vert.wgsl => quad_glsl.vert.wgsl} | 0 ...{sampler-functions-frag.wgsl => sampler-functions.frag.wgsl} | 0 tests/out/wgsl/{samplers-frag.wgsl => samplers.frag.wgsl} | 0 tests/out/wgsl/{statements-frag.wgsl => statements.frag.wgsl} | 0 .../{vector-functions-frag.wgsl => vector-functions.frag.wgsl} | 0 tests/snapshots.rs | 2 +- 36 files changed, 1 insertion(+), 1 deletion(-) rename tests/out/wgsl/{210-bevy-2d-shader-frag.wgsl => 210-bevy-2d-shader.frag.wgsl} (100%) rename tests/out/wgsl/{210-bevy-2d-shader-vert.wgsl => 210-bevy-2d-shader.vert.wgsl} (100%) rename tests/out/wgsl/{210-bevy-shader-vert.wgsl => 210-bevy-shader.vert.wgsl} (100%) rename tests/out/wgsl/{246-collatz-comp.wgsl => 246-collatz.comp.wgsl} (100%) rename tests/out/wgsl/{277-casting-frag.wgsl => 277-casting.frag.wgsl} (100%) rename tests/out/wgsl/{280-matrix-cast-frag.wgsl => 280-matrix-cast.frag.wgsl} (100%) rename tests/out/wgsl/{484-preprocessor-if-frag.wgsl => 484-preprocessor-if.frag.wgsl} (100%) rename tests/out/wgsl/{800-out-of-bounds-panic-vert.wgsl => 800-out-of-bounds-panic.vert.wgsl} (100%) rename tests/out/wgsl/{896-push-constant-frag.wgsl => 896-push-constant.frag.wgsl} (100%) rename tests/out/wgsl/{900-implicit-conversions-frag.wgsl => 900-implicit-conversions.frag.wgsl} (100%) rename tests/out/wgsl/{901-lhs-field-select-frag.wgsl => 901-lhs-field-select.frag.wgsl} (100%) rename tests/out/wgsl/{931-constant-emitting-frag.wgsl => 931-constant-emitting.frag.wgsl} (100%) rename tests/out/wgsl/{932-for-loop-if-frag.wgsl => 932-for-loop-if.frag.wgsl} (100%) rename tests/out/wgsl/{bevy-pbr-frag.wgsl => bevy-pbr.frag.wgsl} (100%) rename tests/out/wgsl/{bevy-pbr-vert.wgsl => bevy-pbr.vert.wgsl} (100%) rename tests/out/wgsl/{bits_glsl-frag.wgsl => bits_glsl.frag.wgsl} (100%) rename tests/out/wgsl/{bool-select-frag.wgsl => bool-select.frag.wgsl} (100%) rename tests/out/wgsl/{buffer-frag.wgsl => buffer.frag.wgsl} (100%) rename tests/out/wgsl/{clamp-splat-vert.wgsl => clamp-splat.vert.wgsl} (100%) rename tests/out/wgsl/{constant-array-size-frag.wgsl => constant-array-size.frag.wgsl} (100%) rename tests/out/wgsl/{declarations-frag.wgsl => declarations.frag.wgsl} (100%) rename tests/out/wgsl/{expressions-frag.wgsl => expressions.frag.wgsl} (100%) rename tests/out/wgsl/{fma-frag.wgsl => fma.frag.wgsl} (100%) rename tests/out/wgsl/{functions_call-frag.wgsl => functions_call.frag.wgsl} (100%) rename tests/out/wgsl/{global-constant-array-frag.wgsl => global-constant-array.frag.wgsl} (100%) rename tests/out/wgsl/{images-frag.wgsl => images.frag.wgsl} (100%) rename tests/out/wgsl/{long-form-matrix-frag.wgsl => long-form-matrix.frag.wgsl} (100%) rename tests/out/wgsl/{math-functions-frag.wgsl => math-functions.frag.wgsl} (100%) rename tests/out/wgsl/{prepostfix-frag.wgsl => prepostfix.frag.wgsl} (100%) rename tests/out/wgsl/{quad_glsl-frag.wgsl => quad_glsl.frag.wgsl} (100%) rename tests/out/wgsl/{quad_glsl-vert.wgsl => quad_glsl.vert.wgsl} (100%) rename tests/out/wgsl/{sampler-functions-frag.wgsl => sampler-functions.frag.wgsl} (100%) rename tests/out/wgsl/{samplers-frag.wgsl => samplers.frag.wgsl} (100%) rename tests/out/wgsl/{statements-frag.wgsl => statements.frag.wgsl} (100%) rename tests/out/wgsl/{vector-functions-frag.wgsl => vector-functions.frag.wgsl} (100%) diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader.frag.wgsl similarity index 100% rename from tests/out/wgsl/210-bevy-2d-shader-frag.wgsl rename to tests/out/wgsl/210-bevy-2d-shader.frag.wgsl diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader.vert.wgsl similarity index 100% rename from tests/out/wgsl/210-bevy-2d-shader-vert.wgsl rename to tests/out/wgsl/210-bevy-2d-shader.vert.wgsl diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader.vert.wgsl similarity index 100% rename from tests/out/wgsl/210-bevy-shader-vert.wgsl rename to tests/out/wgsl/210-bevy-shader.vert.wgsl diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz.comp.wgsl similarity index 100% rename from tests/out/wgsl/246-collatz-comp.wgsl rename to tests/out/wgsl/246-collatz.comp.wgsl diff --git a/tests/out/wgsl/277-casting-frag.wgsl b/tests/out/wgsl/277-casting.frag.wgsl similarity index 100% rename from tests/out/wgsl/277-casting-frag.wgsl rename to tests/out/wgsl/277-casting.frag.wgsl diff --git a/tests/out/wgsl/280-matrix-cast-frag.wgsl b/tests/out/wgsl/280-matrix-cast.frag.wgsl similarity index 100% rename from tests/out/wgsl/280-matrix-cast-frag.wgsl rename to tests/out/wgsl/280-matrix-cast.frag.wgsl diff --git a/tests/out/wgsl/484-preprocessor-if-frag.wgsl b/tests/out/wgsl/484-preprocessor-if.frag.wgsl similarity index 100% rename from tests/out/wgsl/484-preprocessor-if-frag.wgsl rename to tests/out/wgsl/484-preprocessor-if.frag.wgsl diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic.vert.wgsl similarity index 100% rename from tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl rename to tests/out/wgsl/800-out-of-bounds-panic.vert.wgsl diff --git a/tests/out/wgsl/896-push-constant-frag.wgsl b/tests/out/wgsl/896-push-constant.frag.wgsl similarity index 100% rename from tests/out/wgsl/896-push-constant-frag.wgsl rename to tests/out/wgsl/896-push-constant.frag.wgsl diff --git a/tests/out/wgsl/900-implicit-conversions-frag.wgsl b/tests/out/wgsl/900-implicit-conversions.frag.wgsl similarity index 100% rename from tests/out/wgsl/900-implicit-conversions-frag.wgsl rename to tests/out/wgsl/900-implicit-conversions.frag.wgsl diff --git a/tests/out/wgsl/901-lhs-field-select-frag.wgsl b/tests/out/wgsl/901-lhs-field-select.frag.wgsl similarity index 100% rename from tests/out/wgsl/901-lhs-field-select-frag.wgsl rename to tests/out/wgsl/901-lhs-field-select.frag.wgsl diff --git a/tests/out/wgsl/931-constant-emitting-frag.wgsl b/tests/out/wgsl/931-constant-emitting.frag.wgsl similarity index 100% rename from tests/out/wgsl/931-constant-emitting-frag.wgsl rename to tests/out/wgsl/931-constant-emitting.frag.wgsl diff --git a/tests/out/wgsl/932-for-loop-if-frag.wgsl b/tests/out/wgsl/932-for-loop-if.frag.wgsl similarity index 100% rename from tests/out/wgsl/932-for-loop-if-frag.wgsl rename to tests/out/wgsl/932-for-loop-if.frag.wgsl diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr.frag.wgsl similarity index 100% rename from tests/out/wgsl/bevy-pbr-frag.wgsl rename to tests/out/wgsl/bevy-pbr.frag.wgsl diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr.vert.wgsl similarity index 100% rename from tests/out/wgsl/bevy-pbr-vert.wgsl rename to tests/out/wgsl/bevy-pbr.vert.wgsl diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl.frag.wgsl similarity index 100% rename from tests/out/wgsl/bits_glsl-frag.wgsl rename to tests/out/wgsl/bits_glsl.frag.wgsl diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select.frag.wgsl similarity index 100% rename from tests/out/wgsl/bool-select-frag.wgsl rename to tests/out/wgsl/bool-select.frag.wgsl diff --git a/tests/out/wgsl/buffer-frag.wgsl b/tests/out/wgsl/buffer.frag.wgsl similarity index 100% rename from tests/out/wgsl/buffer-frag.wgsl rename to tests/out/wgsl/buffer.frag.wgsl diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat.vert.wgsl similarity index 100% rename from tests/out/wgsl/clamp-splat-vert.wgsl rename to tests/out/wgsl/clamp-splat.vert.wgsl diff --git a/tests/out/wgsl/constant-array-size-frag.wgsl b/tests/out/wgsl/constant-array-size.frag.wgsl similarity index 100% rename from tests/out/wgsl/constant-array-size-frag.wgsl rename to tests/out/wgsl/constant-array-size.frag.wgsl diff --git a/tests/out/wgsl/declarations-frag.wgsl b/tests/out/wgsl/declarations.frag.wgsl similarity index 100% rename from tests/out/wgsl/declarations-frag.wgsl rename to tests/out/wgsl/declarations.frag.wgsl diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions.frag.wgsl similarity index 100% rename from tests/out/wgsl/expressions-frag.wgsl rename to tests/out/wgsl/expressions.frag.wgsl diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma.frag.wgsl similarity index 100% rename from tests/out/wgsl/fma-frag.wgsl rename to tests/out/wgsl/fma.frag.wgsl diff --git a/tests/out/wgsl/functions_call-frag.wgsl b/tests/out/wgsl/functions_call.frag.wgsl similarity index 100% rename from tests/out/wgsl/functions_call-frag.wgsl rename to tests/out/wgsl/functions_call.frag.wgsl diff --git a/tests/out/wgsl/global-constant-array-frag.wgsl b/tests/out/wgsl/global-constant-array.frag.wgsl similarity index 100% rename from tests/out/wgsl/global-constant-array-frag.wgsl rename to tests/out/wgsl/global-constant-array.frag.wgsl diff --git a/tests/out/wgsl/images-frag.wgsl b/tests/out/wgsl/images.frag.wgsl similarity index 100% rename from tests/out/wgsl/images-frag.wgsl rename to tests/out/wgsl/images.frag.wgsl diff --git a/tests/out/wgsl/long-form-matrix-frag.wgsl b/tests/out/wgsl/long-form-matrix.frag.wgsl similarity index 100% rename from tests/out/wgsl/long-form-matrix-frag.wgsl rename to tests/out/wgsl/long-form-matrix.frag.wgsl diff --git a/tests/out/wgsl/math-functions-frag.wgsl b/tests/out/wgsl/math-functions.frag.wgsl similarity index 100% rename from tests/out/wgsl/math-functions-frag.wgsl rename to tests/out/wgsl/math-functions.frag.wgsl diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix.frag.wgsl similarity index 100% rename from tests/out/wgsl/prepostfix-frag.wgsl rename to tests/out/wgsl/prepostfix.frag.wgsl diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl.frag.wgsl similarity index 100% rename from tests/out/wgsl/quad_glsl-frag.wgsl rename to tests/out/wgsl/quad_glsl.frag.wgsl diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl.vert.wgsl similarity index 100% rename from tests/out/wgsl/quad_glsl-vert.wgsl rename to tests/out/wgsl/quad_glsl.vert.wgsl diff --git a/tests/out/wgsl/sampler-functions-frag.wgsl b/tests/out/wgsl/sampler-functions.frag.wgsl similarity index 100% rename from tests/out/wgsl/sampler-functions-frag.wgsl rename to tests/out/wgsl/sampler-functions.frag.wgsl diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers.frag.wgsl similarity index 100% rename from tests/out/wgsl/samplers-frag.wgsl rename to tests/out/wgsl/samplers.frag.wgsl diff --git a/tests/out/wgsl/statements-frag.wgsl b/tests/out/wgsl/statements.frag.wgsl similarity index 100% rename from tests/out/wgsl/statements-frag.wgsl rename to tests/out/wgsl/statements.frag.wgsl diff --git a/tests/out/wgsl/vector-functions-frag.wgsl b/tests/out/wgsl/vector-functions.frag.wgsl similarity index 100% rename from tests/out/wgsl/vector-functions-frag.wgsl rename to tests/out/wgsl/vector-functions.frag.wgsl diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 80b083466..495051084 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -789,7 +789,7 @@ fn convert_glsl_folder() { &module, &info, &dest, - &file_name.replace('.', "-"), + &file_name, &WgslOutParameters::default(), ); } From 0c69735f59e6dd43f81afae9e5dd678aa30201c1 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 22 Sep 2023 16:29:09 -0700 Subject: [PATCH 2104/2212] Change `naga::back::spv::DebugInfo::file_name` to a `&Path`. This makes it a bit easier to use in the CLI and snapshot tests. --- cli/src/bin/naga.rs | 8 +------- src/back/spv/mod.rs | 2 +- src/back/spv/writer.rs | 6 ++++-- tests/snapshots.rs | 2 +- 4 files changed, 7 insertions(+), 11 deletions(-) diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index 3ca7305e4..3b0873a37 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -374,13 +374,7 @@ fn run() -> Result<(), Box> { .set(naga::back::spv::WriterFlags::DEBUG, true); params.spv_out.debug_info = Some(naga::back::spv::DebugInfo { source_code: input_text, - file_name: input_path - .file_name() - .and_then(std::ffi::OsStr::to_str) - .ok_or(CliError( - "input path for couldn't be converted to string \ - for `--generate-debug-symbols", - ))?, + file_name: input_path, }) } else { eprintln!( diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index 52e304a23..c52827908 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -85,7 +85,7 @@ impl IdGenerator { #[derive(Debug, Clone)] pub struct DebugInfo<'a> { pub source_code: &'a str, - pub file_name: &'a str, + pub file_name: &'a std::path::Path, } /// A SPIR-V block to which we are still adding instructions. diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index fd39fe2e4..56d018b6f 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1840,8 +1840,10 @@ impl Writer { if self.flags.contains(WriterFlags::DEBUG) { if let Some(debug_info) = debug_info.as_ref() { let source_file_id = self.id_gen.next(); - self.debugs - .push(Instruction::string(debug_info.file_name, source_file_id)); + self.debugs.push(Instruction::string( + &debug_info.file_name.display().to_string(), + source_file_id, + )); debug_info_inner = Some(DebugInfoInner { source_code: debug_info.source_code, diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 495051084..b7327cce7 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -159,7 +159,7 @@ fn check_targets( let debug_info = if cfg!(feature = "span") { source_code.map(|code| naga::back::spv::DebugInfo { source_code: code, - file_name: name, + file_name: name.as_ref(), }) } else { None From 4329a6a51b4d39a3eeacf1d3abdeee3f63f9cd03 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 23 Sep 2023 16:37:15 -0700 Subject: [PATCH 2105/2212] snapshots: Name convert_glsl_variations_check output consistently. Rather than adding a `-glsl` suffix to the name, just rely on `check_targets`' standard naming behavior, treating `tests/in/variations.glsl` like any other snapshot input. --- ...ns-glsl.main.Fragment.glsl => variations.main.Fragment.glsl} | 0 tests/snapshots.rs | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename tests/out/glsl/{variations-glsl.main.Fragment.glsl => variations.main.Fragment.glsl} (100%) diff --git a/tests/out/glsl/variations-glsl.main.Fragment.glsl b/tests/out/glsl/variations.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/variations-glsl.main.Fragment.glsl rename to tests/out/glsl/variations.main.Fragment.glsl diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b7327cce7..b4d47dfc8 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -738,7 +738,7 @@ fn convert_glsl_variations_check() { &file, ) .unwrap(); - check_targets(&mut module, "variations-glsl", Targets::GLSL, None); + check_targets(&mut module, "variations", Targets::GLSL, None); } #[cfg(feature = "glsl-in")] From 5af7ebc9556428bdacf4025ad46660850b1d2fcf Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 23 Sep 2023 16:33:46 -0700 Subject: [PATCH 2106/2212] snapshots: Consolidate path handling. Add a new type, `Input`, representing a particular Naga input file, with methods to generate related paths - output files with a particular extension, parameter files, and the input file itself. Use this throughout `snapshots.rs` to generate paths. Give `Input` utility methods for reading and writing files. --- tests/out/spv/debug-symbol-simple.spvasm | 2 +- tests/out/spv/debug-symbol-terrain.spvasm | 2 +- tests/snapshots.rs | 324 +++++++++++++++------- 3 files changed, 226 insertions(+), 102 deletions(-) diff --git a/tests/out/spv/debug-symbol-simple.spvasm b/tests/out/spv/debug-symbol-simple.spvasm index 67ad8beb2..8f64c324c 100644 --- a/tests/out/spv/debug-symbol-simple.spvasm +++ b/tests/out/spv/debug-symbol-simple.spvasm @@ -8,7 +8,7 @@ OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %24 "vs_main" %15 %18 %20 %22 OpEntryPoint Fragment %57 "fs_main" %51 %54 %56 OpExecutionMode %57 OriginUpperLeft -%3 = OpString "debug-symbol-simple" +%3 = OpString "debug-symbol-simple.wgsl" OpSource Unknown 0 %3 "struct VertexInput { @location(0) position: vec3, @location(1) color: vec3, diff --git a/tests/out/spv/debug-symbol-terrain.spvasm b/tests/out/spv/debug-symbol-terrain.spvasm index ac83cc123..8c27f3ab9 100644 --- a/tests/out/spv/debug-symbol-terrain.spvasm +++ b/tests/out/spv/debug-symbol-terrain.spvasm @@ -14,7 +14,7 @@ OpEntryPoint Fragment %587 "fs_main" %580 %582 %584 %586 OpExecutionMode %348 LocalSize 64 1 1 OpExecutionMode %470 OriginUpperLeft OpExecutionMode %587 OriginUpperLeft -%3 = OpString "debug-symbol-terrain" +%3 = OpString "debug-symbol-terrain.wgsl" OpSource Unknown 0 %3 "// Taken from https://github.com/sotrh/learn-wgpu/blob/11820796f5e1dbce42fb1119f04ddeb4b167d2a0/code/intermediate/tutorial13-terrain/src/terrain.wgsl // ============================ // Terrain Generation diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b4d47dfc8..bc5fea08f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -7,6 +7,7 @@ use std::{ path::{Path, PathBuf}, }; +const CRATE_ROOT: &str = env!("CARGO_MANIFEST_DIR"); const BASE_DIR_IN: &str = "tests/in"; const BASE_DIR_OUT: &str = "tests/out"; @@ -88,21 +89,176 @@ struct Parameters { glsl_multiview: Option, } +/// Information about a shader input file. +#[derive(Debug)] +struct Input { + /// The subdirectory of `tests/in` to which this input belongs, if any. + /// + /// If the subdirectory is omitted, we assume that the output goes + /// to "wgsl". + subdirectory: Option, + + /// The input filename name, without a directory. + file_name: PathBuf, + + /// True if output filenames should add the output extension on top of + /// `file_name`'s existing extension, rather than replacing it. + /// + /// This is used by `convert_glsl_folder`, which wants to take input files + /// like `210-bevy-2d-shader.frag` and just add `.wgsl` to it, producing + /// `210-bevy-2d-shader.frag.wgsl`. + keep_input_extension: bool, +} + +impl Input { + /// Read an input file and its corresponding parameters file. + /// + /// Given `input`, the relative path of a shader input file, return + /// a `Source` value containing its path, code, and parameters. + /// + /// The `input` path is interpreted relative to the `BASE_DIR_IN` + /// subdirectory of the directory given by the `CARGO_MANIFEST_DIR` + /// environment variable. + fn new(subdirectory: Option<&str>, name: &str, extension: &str) -> Input { + Input { + subdirectory: subdirectory.map(PathBuf::from), + // Don't wipe out any extensions on `name`, as + // `with_extension` would do. + file_name: PathBuf::from(format!("{name}.{extension}")), + keep_input_extension: false, + } + } + + /// Return an iterator that produces an `Input` for each entry in `subdirectory`. + fn files_in_dir(subdirectory: &str) -> impl Iterator + 'static { + let subdirectory = subdirectory.to_string(); + let mut input_directory = Path::new(env!("CARGO_MANIFEST_DIR")).join(BASE_DIR_IN); + input_directory.push(&subdirectory); + match std::fs::read_dir(&input_directory) { + Ok(entries) => entries.map(move |result| { + let entry = result.expect("error reading directory"); + let file_name = PathBuf::from(entry.file_name()); + let extension = file_name + .extension() + .expect("all files in snapshot input directory should have extensions"); + let input = Input::new( + Some(&subdirectory), + &file_name.file_stem().unwrap().to_str().unwrap(), + &extension.to_str().unwrap(), + ); + input + }), + Err(err) => { + panic!( + "Error opening directory '{}': {}", + input_directory.display(), + err + ); + } + } + } + + /// Return the path to the input directory. + fn input_directory(&self) -> PathBuf { + let mut dir = Path::new(CRATE_ROOT).join(BASE_DIR_IN); + if let Some(ref subdirectory) = self.subdirectory { + dir.push(subdirectory); + } + dir + } + + /// Return the path to the output directory. + fn output_directory(&self, subdirectory: &str) -> PathBuf { + let mut dir = Path::new(CRATE_ROOT).join(BASE_DIR_OUT); + dir.push(subdirectory); + dir + } + + /// Return the path to the input file. + fn input_path(&self) -> PathBuf { + let mut input = self.input_directory(); + input.push(&self.file_name); + input + } + + fn output_path(&self, subdirectory: &str, extension: &str) -> PathBuf { + let mut output = self.output_directory(subdirectory); + if self.keep_input_extension { + let mut file_name = self.file_name.as_os_str().to_owned(); + file_name.push("."); + file_name.push(extension); + output.push(&file_name); + } else { + output.push(&self.file_name); + output.set_extension(extension); + } + output + } + + /// Return the contents of the input file as a string. + fn read_source(&self) -> String { + println!("Processing '{}'", self.file_name.display()); + let input_path = self.input_path(); + match fs::read_to_string(&input_path) { + Ok(source) => source, + Err(err) => { + panic!( + "Couldn't read shader input file `{}`: {}", + input_path.display(), + err + ); + } + } + } + + /// Return the contents of the input file as a vector of bytes. + fn read_bytes(&self) -> Vec { + println!("Processing '{}'", self.file_name.display()); + let input_path = self.input_path(); + match fs::read(&input_path) { + Ok(bytes) => bytes, + Err(err) => { + panic!( + "Couldn't read shader input file `{}`: {}", + input_path.display(), + err + ); + } + } + } + + /// Return this input's parameter file, parsed. + fn read_parameters(&self) -> Parameters { + let mut param_path = self.input_path(); + param_path.set_extension("param.ron"); + match fs::read_to_string(¶m_path) { + Ok(string) => ron::de::from_str(&string).expect(&format!( + "Couldn't parse param file: {}", + param_path.display() + )), + Err(_) => Parameters::default(), + } + } + + /// Write `data` to a file corresponding to this input file in + /// `subdirectory`, with `extension`. + fn write_output_file(&self, subdirectory: &str, extension: &str, data: impl AsRef<[u8]>) { + let output_path = self.output_path(subdirectory, extension); + if let Err(err) = fs::write(&output_path, data) { + panic!("Error writing {}: {}", output_path.display(), err); + } + } +} + #[allow(unused_variables)] fn check_targets( + input: &Input, module: &mut naga::Module, - name: &str, targets: Targets, source_code: Option<&str>, ) { - let root = env!("CARGO_MANIFEST_DIR"); - let filepath = format!("{root}/{BASE_DIR_IN}/{name}.param.ron"); - let params = match fs::read_to_string(&filepath) { - Ok(string) => { - ron::de::from_str(&string).expect(&format!("Couldn't parse param file: {}", filepath)) - } - Err(_) => Parameters::default(), - }; + let params = input.read_parameters(); + let name = &input.file_name; let capabilities = if params.god_mode { naga::valid::Capabilities::all() @@ -110,20 +266,21 @@ fn check_targets( naga::valid::Capabilities::default() }; - let dest = PathBuf::from(root).join(BASE_DIR_OUT); - #[cfg(feature = "serialize")] { if targets.contains(Targets::IR) { let config = ron::ser::PrettyConfig::default().new_line("\n".to_string()); let string = ron::ser::to_string_pretty(module, config).unwrap(); - fs::write(dest.join(format!("ir/{name}.ron")), string).unwrap(); + input.write_output_file("ir", "ron", string); } } let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities) .validate(module) - .expect(&format!("Naga module validation failed on test '{name}'")); + .expect(&format!( + "Naga module validation failed on test '{}'", + name.display() + )); #[cfg(feature = "compact")] let info = { @@ -134,14 +291,15 @@ fn check_targets( if targets.contains(Targets::IR) { let config = ron::ser::PrettyConfig::default().new_line("\n".to_string()); let string = ron::ser::to_string_pretty(module, config).unwrap(); - fs::write(dest.join(format!("ir/{name}.compact.ron")), string).unwrap(); + input.write_output_file("ir", "compact.ron", string); } } naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities) .validate(module) .expect(&format!( - "Post-compaction module validation failed on test '{name}'" + "Post-compaction module validation failed on test '{}'", + name.display() )) }; @@ -150,7 +308,7 @@ fn check_targets( if targets.contains(Targets::ANALYSIS) { let config = ron::ser::PrettyConfig::default().new_line("\n".to_string()); let string = ron::ser::to_string_pretty(&info, config).unwrap(); - fs::write(dest.join(format!("analysis/{name}.info.ron")), string).unwrap(); + input.write_output_file("analysis", "info.ron", string); } } @@ -167,10 +325,9 @@ fn check_targets( if targets.contains(Targets::SPIRV) { write_output_spv( + input, module, &info, - &dest, - name, debug_info, ¶ms.spv, params.bounds_check_policies, @@ -181,10 +338,9 @@ fn check_targets( { if targets.contains(Targets::METAL) { write_output_msl( + input, module, &info, - &dest, - name, ¶ms.msl, ¶ms.msl_pipeline, params.bounds_check_policies, @@ -199,10 +355,9 @@ fn check_targets( continue; } write_output_glsl( + input, module, &info, - &dest, - name, ep.stage, &ep.name, ¶ms.glsl, @@ -216,29 +371,28 @@ fn check_targets( { if targets.contains(Targets::DOT) { let string = naga::back::dot::write(module, Some(&info), Default::default()).unwrap(); - fs::write(dest.join(format!("dot/{name}.dot")), string).unwrap(); + input.write_output_file("dot", "dot", string); } } #[cfg(all(feature = "deserialize", feature = "hlsl-out"))] { if targets.contains(Targets::HLSL) { - write_output_hlsl(module, &info, &dest, name, ¶ms.hlsl); + write_output_hlsl(input, module, &info, ¶ms.hlsl); } } #[cfg(all(feature = "deserialize", feature = "wgsl-out"))] { if targets.contains(Targets::WGSL) { - write_output_wgsl(module, &info, &dest, name, ¶ms.wgsl); + write_output_wgsl(input, module, &info, ¶ms.wgsl); } } } #[cfg(feature = "spv-out")] fn write_output_spv( + input: &Input, module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, - file_name: &str, debug_info: Option, params: &SpirvOutParameters, bounds_check_policies: naga::proc::BoundsCheckPolicies, @@ -278,38 +432,31 @@ fn write_output_spv( shader_stage: ep.stage, }; write_output_spv_inner( + input, module, info, &options, Some(&pipeline_options), - destination, - format!("spv/{}.{}.spvasm", file_name, ep.name), + &format!("{}.spvasm", ep.name), ); } } else { - write_output_spv_inner( - module, - info, - &options, - None, - destination, - format!("spv/{file_name}.spvasm"), - ); + write_output_spv_inner(input, module, info, &options, None, "spvasm"); } } #[cfg(feature = "spv-out")] fn write_output_spv_inner( + input: &Input, module: &naga::Module, info: &naga::valid::ModuleInfo, options: &naga::back::spv::Options<'_>, pipeline_options: Option<&naga::back::spv::PipelineOptions>, - destination: &Path, - path: String, + extension: &str, ) { use naga::back::spv; use rspirv::binary::Disassemble; - println!("Writing SPIR-V {}", path); + println!("Writing SPIR-V for {:?}", input.file_name); let spv = spv::write_vec(module, info, options, pipeline_options).unwrap(); let dis = rspirv::dr::load_words(spv) .expect("Produced invalid SPIR-V") @@ -321,15 +468,14 @@ fn write_output_spv_inner( } else { dis }; - fs::write(destination.join(path), dis).unwrap(); + input.write_output_file("spv", extension, dis); } #[cfg(feature = "msl-out")] fn write_output_msl( + input: &Input, module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, - file_name: &str, options: &naga::back::msl::Options, pipeline_options: &naga::back::msl::PipelineOptions, bounds_check_policies: naga::proc::BoundsCheckPolicies, @@ -349,16 +495,15 @@ fn write_output_msl( } } - fs::write(destination.join(format!("msl/{file_name}.msl")), string).unwrap(); + input.write_output_file("msl", "msl", string); } #[cfg(feature = "glsl-out")] #[allow(clippy::too_many_arguments)] fn write_output_glsl( + input: &Input, module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, - file_name: &str, stage: naga::ShaderStage, ep_name: &str, options: &naga::back::glsl::Options, @@ -387,19 +532,15 @@ fn write_output_glsl( .expect("GLSL init failed"); writer.write().expect("GLSL write failed"); - fs::write( - destination.join(format!("glsl/{file_name}.{ep_name}.{stage:?}.glsl")), - buffer, - ) - .unwrap(); + let extension = format!("{ep_name}.{stage:?}.glsl"); + input.write_output_file("glsl", &extension, buffer); } #[cfg(feature = "hlsl-out")] fn write_output_hlsl( + input: &Input, module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, - file_name: &str, options: &naga::back::hlsl::Options, ) { use naga::back::hlsl; @@ -411,7 +552,7 @@ fn write_output_hlsl( let mut writer = hlsl::Writer::new(&mut buffer, options); let reflection_info = writer.write(module, info).expect("HLSL write failed"); - fs::write(destination.join(format!("hlsl/{file_name}.hlsl")), buffer).unwrap(); + input.write_output_file("hlsl", "hlsl", buffer); // We need a config file for validation script // This file contains an info about profiles (shader stages) contains inside generated shader @@ -437,17 +578,14 @@ fn write_output_hlsl( }); } - config - .to_file(destination.join(format!("hlsl/{file_name}.ron"))) - .unwrap(); + config.to_file(&input.output_path("hlsl", "ron")).unwrap(); } #[cfg(feature = "wgsl-out")] fn write_output_wgsl( + input: &Input, module: &naga::Module, info: &naga::valid::ModuleInfo, - destination: &Path, - file_name: &str, params: &WgslOutParameters, ) { use naga::back::wgsl; @@ -459,7 +597,7 @@ fn write_output_wgsl( let string = wgsl::write_string(module, info, flags).expect("WGSL write failed"); - fs::write(destination.join(format!("wgsl/{file_name}.wgsl")), string).unwrap(); + input.write_output_file("wgsl", "wgsl", string); } #[cfg(feature = "wgsl-in")] @@ -467,7 +605,6 @@ fn write_output_wgsl( fn convert_wgsl() { let _ = env_logger::try_init(); - let root = env!("CARGO_MANIFEST_DIR"); let inputs = [ // TODO: merge array-in-ctor and array-in-function-return-type tests after fix HLSL issue https://github.com/gfx-rs/naga/issues/1930 ( @@ -645,13 +782,12 @@ fn convert_wgsl() { ]; for &(name, targets) in inputs.iter() { - println!("Processing '{name}'"); // WGSL shaders lives in root dir as a privileged. - let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/{name}.wgsl")) - .expect("Couldn't find wgsl file"); - match naga::front::wgsl::parse_str(&file) { - Ok(mut module) => check_targets(&mut module, name, targets, None), - Err(e) => panic!("{}", e.emit_to_string(&file)), + let input = Input::new(None, name, "wgsl"); + let source = input.read_source(); + match naga::front::wgsl::parse_str(&source) { + Ok(mut module) => check_targets(&input, &mut module, targets, None), + Err(e) => panic!("{}", e.emit_to_string(&source)), } } @@ -662,13 +798,12 @@ fn convert_wgsl() { ("debug-symbol-terrain", Targets::SPIRV), ]; for &(name, targets) in inputs.iter() { - println!("Processing '{name}'"); // WGSL shaders lives in root dir as a privileged. - let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/{name}.wgsl")) - .expect("Couldn't find wgsl file"); - match naga::front::wgsl::parse_str(&file) { - Ok(mut module) => check_targets(&mut module, name, targets, Some(&file)), - Err(e) => panic!("{}", e.emit_to_string(&file)), + let input = Input::new(None, name, "wgsl"); + let source = input.read_source(); + match naga::front::wgsl::parse_str(&source) { + Ok(mut module) => check_targets(&input, &mut module, targets, Some(&source)), + Err(e) => panic!("{}", e.emit_to_string(&source)), } } } @@ -678,11 +813,9 @@ fn convert_wgsl() { fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { let _ = env_logger::try_init(); - let root = env!("CARGO_MANIFEST_DIR"); - - println!("Processing '{name}'"); + let input = Input::new(Some("spv"), name, "spv"); let mut module = naga::front::spv::parse_u8_slice( - &fs::read(format!("{root}/{BASE_DIR_IN}/spv/{name}.spv")).expect("Couldn't find spv file"), + &input.read_bytes(), &naga::front::spv::Options { adjust_coordinate_space, strict_capabilities: false, @@ -690,7 +823,7 @@ fn convert_spv(name: &str, adjust_coordinate_space: bool, targets: Targets) { }, ) .unwrap(); - check_targets(&mut module, name, targets, None); + check_targets(&input, &mut module, targets, None); } #[cfg(feature = "spv-in")] @@ -725,9 +858,8 @@ fn convert_spv_all() { #[cfg(feature = "glsl-in")] #[test] fn convert_glsl_variations_check() { - let root = env!("CARGO_MANIFEST_DIR"); - let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/variations.glsl")) - .expect("Couldn't find glsl file"); + let input = Input::new(None, "variations", "glsl"); + let source = input.read_source(); let mut parser = naga::front::glsl::Frontend::default(); let mut module = parser .parse( @@ -735,10 +867,10 @@ fn convert_glsl_variations_check() { stage: naga::ShaderStage::Fragment, defines: Default::default(), }, - &file, + &source, ) .unwrap(); - check_targets(&mut module, "variations", Targets::GLSL, None); + check_targets(&input, &mut module, Targets::GLSL, None); } #[cfg(feature = "glsl-in")] @@ -747,23 +879,22 @@ fn convert_glsl_variations_check() { fn convert_glsl_folder() { let _ = env_logger::try_init(); - let root = env!("CARGO_MANIFEST_DIR"); - - for entry in std::fs::read_dir(format!("{root}/{BASE_DIR_IN}/glsl")).unwrap() { - let entry = entry.unwrap(); - let file_name = entry.file_name().into_string().unwrap(); - + for input in Input::files_in_dir("glsl") { + let input = Input { + keep_input_extension: true, + ..input + }; + let file_name = &input.file_name; if file_name.ends_with(".ron") { // No needed to validate ron files continue; } - println!("Processing {file_name}"); let mut parser = naga::front::glsl::Frontend::default(); let module = parser .parse( &naga::front::glsl::Options { - stage: match entry.path().extension().and_then(|s| s.to_str()).unwrap() { + stage: match file_name.extension().and_then(|s| s.to_str()).unwrap() { "vert" => naga::ShaderStage::Vertex, "frag" => naga::ShaderStage::Fragment, "comp" => naga::ShaderStage::Compute, @@ -771,7 +902,7 @@ fn convert_glsl_folder() { }, defines: Default::default(), }, - &fs::read_to_string(entry.path()).expect("Couldn't find glsl file"), + &input.read_source(), ) .unwrap(); @@ -784,14 +915,7 @@ fn convert_glsl_folder() { #[cfg(feature = "wgsl-out")] { - let dest = PathBuf::from(root).join(BASE_DIR_OUT); - write_output_wgsl( - &module, - &info, - &dest, - &file_name, - &WgslOutParameters::default(), - ); + write_output_wgsl(&input, &module, &info, &WgslOutParameters::default()); } } } From 3bcb114adbf144544cb46497b000adf3e7e71181 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 24 Sep 2023 16:00:55 -0700 Subject: [PATCH 2107/2212] snapshots: Change messages for generating output. Change printlns in the backend functions to say "generating" instead of "writing" before calling the Naga backends. "Writing" suggests writing output to a file; "generating" seems more accurate for calling a backend. --- tests/snapshots.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index bc5fea08f..b4394c415 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -400,8 +400,6 @@ fn write_output_spv( use naga::back::spv; use rspirv::binary::Disassemble; - println!("writing SPIR-V"); - let mut flags = spv::WriterFlags::LABEL_VARYINGS; flags.set(spv::WriterFlags::DEBUG, params.debug); flags.set( @@ -456,7 +454,7 @@ fn write_output_spv_inner( ) { use naga::back::spv; use rspirv::binary::Disassemble; - println!("Writing SPIR-V for {:?}", input.file_name); + println!("Generating SPIR-V for {:?}", input.file_name); let spv = spv::write_vec(module, info, options, pipeline_options).unwrap(); let dis = rspirv::dr::load_words(spv) .expect("Produced invalid SPIR-V") @@ -482,7 +480,7 @@ fn write_output_msl( ) { use naga::back::msl; - println!("writing MSL"); + println!("generating MSL"); let mut options = options.clone(); options.bounds_check_policies = bounds_check_policies; @@ -512,7 +510,7 @@ fn write_output_glsl( ) { use naga::back::glsl; - println!("writing GLSL"); + println!("generating GLSL"); let pipeline_options = glsl::PipelineOptions { shader_stage: stage, @@ -546,7 +544,7 @@ fn write_output_hlsl( use naga::back::hlsl; use std::fmt::Write as _; - println!("writing HLSL"); + println!("generating HLSL"); let mut buffer = String::new(); let mut writer = hlsl::Writer::new(&mut buffer, options); @@ -590,7 +588,7 @@ fn write_output_wgsl( ) { use naga::back::wgsl; - println!("writing WGSL"); + println!("generating WGSL"); let mut flags = wgsl::WriterFlags::empty(); flags.set(wgsl::WriterFlags::EXPLICIT_TYPES, params.explicit_types); From a898522e10ca85516ad96aacf8cb56053e533738 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Tue, 26 Sep 2023 10:46:02 -0400 Subject: [PATCH 2108/2212] Rename identifiers containing double underscores (#2510) --- src/back/glsl/mod.rs | 3 +- src/proc/namer.rs | 12 ++++++- .../glsl/math-functions.main.Fragment.glsl | 36 +++++++++---------- tests/out/glsl/padding.vertex.Vertex.glsl | 4 +-- tests/out/hlsl/math-functions.hlsl | 36 +++++++++---------- tests/out/msl/math-functions.msl | 36 +++++++++---------- 6 files changed, 69 insertions(+), 58 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 8a8dea664..eb2c2ed02 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1129,7 +1129,8 @@ impl<'a, W: Write> Writer<'a, W> { let ty_name = &self.names[&NameKey::Type(global.ty)]; let block_name = format!( "{}_block_{}{:?}", - ty_name, + // avoid double underscores as they are reserved in GLSL + ty_name.trim_end_matches('_'), self.block_id.generate(), self.entry_point.stage, ); diff --git a/src/proc/namer.rs b/src/proc/namer.rs index 2f262d7d5..8afacb593 100644 --- a/src/proc/namer.rs +++ b/src/proc/namer.rs @@ -36,6 +36,7 @@ impl Namer { /// - Drop leading digits. /// - Retain only alphanumeric and `_` characters. /// - Avoid prefixes in [`Namer::reserved_prefixes`]. + /// - Replace consecutive `_` characters with a single `_` character. /// /// The return value is a valid identifier prefix in all of Naga's output languages, /// and it never ends with a `SEPARATOR` character. @@ -46,6 +47,7 @@ impl Namer { .trim_end_matches(SEPARATOR); let base = if !string.is_empty() + && !string.contains("__") && string .chars() .all(|c: char| c.is_ascii_alphanumeric() || c == '_') @@ -55,7 +57,13 @@ impl Namer { let mut filtered = string .chars() .filter(|&c| c.is_ascii_alphanumeric() || c == '_') - .collect::(); + .fold(String::new(), |mut s, c| { + if s.ends_with('_') && c == '_' { + return s; + } + s.push(c); + s + }); let stripped_len = filtered.trim_end_matches(SEPARATOR).len(); filtered.truncate(stripped_len); if filtered.is_empty() { @@ -268,4 +276,6 @@ fn test() { assert_eq!(namer.call("x"), "x"); assert_eq!(namer.call("x"), "x_1"); assert_eq!(namer.call("x1"), "x1_"); + assert_eq!(namer.call("__x"), "_x"); + assert_eq!(namer.call("1___x"), "_x_1"); } diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl index 37c072a6f..ed81535ab 100644 --- a/tests/out/glsl/math-functions.main.Fragment.glsl +++ b/tests/out/glsl/math-functions.main.Fragment.glsl @@ -3,55 +3,55 @@ precision highp float; precision highp int; -struct __modf_result_f32_ { +struct _modf_result_f32_ { float fract_; float whole; }; -struct __modf_result_vec2_f32_ { +struct _modf_result_vec2_f32_ { vec2 fract_; vec2 whole; }; -struct __modf_result_vec4_f32_ { +struct _modf_result_vec4_f32_ { vec4 fract_; vec4 whole; }; -struct __frexp_result_f32_ { +struct _frexp_result_f32_ { float fract_; int exp_; }; -struct __frexp_result_vec4_f32_ { +struct _frexp_result_vec4_f32_ { vec4 fract_; ivec4 exp_; }; -__modf_result_f32_ naga_modf(float arg) { +_modf_result_f32_ naga_modf(float arg) { float other; float fract = modf(arg, other); - return __modf_result_f32_(fract, other); + return _modf_result_f32_(fract, other); } -__modf_result_vec2_f32_ naga_modf(vec2 arg) { +_modf_result_vec2_f32_ naga_modf(vec2 arg) { vec2 other; vec2 fract = modf(arg, other); - return __modf_result_vec2_f32_(fract, other); + return _modf_result_vec2_f32_(fract, other); } -__modf_result_vec4_f32_ naga_modf(vec4 arg) { +_modf_result_vec4_f32_ naga_modf(vec4 arg) { vec4 other; vec4 fract = modf(arg, other); - return __modf_result_vec4_f32_(fract, other); + return _modf_result_vec4_f32_(fract, other); } -__frexp_result_f32_ naga_frexp(float arg) { +_frexp_result_f32_ naga_frexp(float arg) { int other; float fract = frexp(arg, other); - return __frexp_result_f32_(fract, other); + return _frexp_result_f32_(fract, other); } -__frexp_result_vec4_f32_ naga_frexp(vec4 arg) { +_frexp_result_vec4_f32_ naga_frexp(vec4 arg) { ivec4 other; vec4 fract = frexp(arg, other); - return __frexp_result_vec4_f32_(fract, other); + return _frexp_result_vec4_f32_(fract, other); } void main() { @@ -90,13 +90,13 @@ void main() { uvec2 clz_d = uvec2(ivec2(31) - findMSB(uvec2(1u))); float lde_a = ldexp(1.0, 2); vec2 lde_b = ldexp(vec2(1.0, 2.0), ivec2(3, 4)); - __modf_result_f32_ modf_a = naga_modf(1.5); + _modf_result_f32_ modf_a = naga_modf(1.5); float modf_b = naga_modf(1.5).fract_; float modf_c = naga_modf(1.5).whole; - __modf_result_vec2_f32_ modf_d = naga_modf(vec2(1.5, 1.5)); + _modf_result_vec2_f32_ modf_d = naga_modf(vec2(1.5, 1.5)); float modf_e = naga_modf(vec4(1.5, 1.5, 1.5, 1.5)).whole.x; float modf_f = naga_modf(vec2(1.5, 1.5)).fract_.y; - __frexp_result_f32_ frexp_a = naga_frexp(1.5); + _frexp_result_f32_ frexp_a = naga_frexp(1.5); float frexp_b = naga_frexp(1.5).fract_; int frexp_c = naga_frexp(1.5).exp_; int frexp_d = naga_frexp(vec4(1.5, 1.5, 1.5, 1.5)).exp_.x; diff --git a/tests/out/glsl/padding.vertex.Vertex.glsl b/tests/out/glsl/padding.vertex.Vertex.glsl index 1810cffc6..82d8d31fa 100644 --- a/tests/out/glsl/padding.vertex.Vertex.glsl +++ b/tests/out/glsl/padding.vertex.Vertex.glsl @@ -20,9 +20,9 @@ struct Test3_ { }; uniform Test_block_0Vertex { Test _group_0_binding_0_vs; }; -uniform Test2__block_1Vertex { Test2_ _group_0_binding_1_vs; }; +uniform Test2_block_1Vertex { Test2_ _group_0_binding_1_vs; }; -uniform Test3__block_2Vertex { Test3_ _group_0_binding_2_vs; }; +uniform Test3_block_2Vertex { Test3_ _group_0_binding_2_vs; }; void main() { diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl index fc5cadb65..53d3acf0c 100644 --- a/tests/out/hlsl/math-functions.hlsl +++ b/tests/out/hlsl/math-functions.hlsl @@ -1,63 +1,63 @@ -struct __modf_result_f32_ { +struct _modf_result_f32_ { float fract; float whole; }; -struct __modf_result_vec2_f32_ { +struct _modf_result_vec2_f32_ { float2 fract; float2 whole; }; -struct __modf_result_vec4_f32_ { +struct _modf_result_vec4_f32_ { float4 fract; float4 whole; }; -struct __frexp_result_f32_ { +struct _frexp_result_f32_ { float fract; int exp_; }; -struct __frexp_result_vec4_f32_ { +struct _frexp_result_vec4_f32_ { float4 fract; int4 exp_; }; -__modf_result_f32_ naga_modf(float arg) { +_modf_result_f32_ naga_modf(float arg) { float other; - __modf_result_f32_ result; + _modf_result_f32_ result; result.fract = modf(arg, other); result.whole = other; return result; } -__modf_result_vec2_f32_ naga_modf(float2 arg) { +_modf_result_vec2_f32_ naga_modf(float2 arg) { float2 other; - __modf_result_vec2_f32_ result; + _modf_result_vec2_f32_ result; result.fract = modf(arg, other); result.whole = other; return result; } -__modf_result_vec4_f32_ naga_modf(float4 arg) { +_modf_result_vec4_f32_ naga_modf(float4 arg) { float4 other; - __modf_result_vec4_f32_ result; + _modf_result_vec4_f32_ result; result.fract = modf(arg, other); result.whole = other; return result; } -__frexp_result_f32_ naga_frexp(float arg) { +_frexp_result_f32_ naga_frexp(float arg) { float other; - __frexp_result_f32_ result; + _frexp_result_f32_ result; result.fract = sign(arg) * frexp(arg, other); result.exp_ = other; return result; } -__frexp_result_vec4_f32_ naga_frexp(float4 arg) { +_frexp_result_vec4_f32_ naga_frexp(float4 arg) { float4 other; - __frexp_result_vec4_f32_ result; + _frexp_result_vec4_f32_ result; result.fract = sign(arg) * frexp(arg, other); result.exp_ = other; return result; @@ -100,13 +100,13 @@ void main() uint2 clz_d = ((31u).xx - firstbithigh((1u).xx)); float lde_a = ldexp(1.0, 2); float2 lde_b = ldexp(float2(1.0, 2.0), int2(3, 4)); - __modf_result_f32_ modf_a = naga_modf(1.5); + _modf_result_f32_ modf_a = naga_modf(1.5); float modf_b = naga_modf(1.5).fract; float modf_c = naga_modf(1.5).whole; - __modf_result_vec2_f32_ modf_d = naga_modf(float2(1.5, 1.5)); + _modf_result_vec2_f32_ modf_d = naga_modf(float2(1.5, 1.5)); float modf_e = naga_modf(float4(1.5, 1.5, 1.5, 1.5)).whole.x; float modf_f = naga_modf(float2(1.5, 1.5)).fract.y; - __frexp_result_f32_ frexp_a = naga_frexp(1.5); + _frexp_result_f32_ frexp_a = naga_frexp(1.5); float frexp_b = naga_frexp(1.5).fract; int frexp_c = naga_frexp(1.5).exp_; int frexp_d = naga_frexp(float4(1.5, 1.5, 1.5, 1.5)).exp_.x; diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index dccb90ad6..d0ae8c504 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -4,55 +4,55 @@ using metal::uint; -struct __modf_result_f32_ { +struct _modf_result_f32_ { float fract; float whole; }; -struct __modf_result_vec2_f32_ { +struct _modf_result_vec2_f32_ { metal::float2 fract; metal::float2 whole; }; -struct __modf_result_vec4_f32_ { +struct _modf_result_vec4_f32_ { metal::float4 fract; metal::float4 whole; }; -struct __frexp_result_f32_ { +struct _frexp_result_f32_ { float fract; int exp; }; -struct __frexp_result_vec4_f32_ { +struct _frexp_result_vec4_f32_ { metal::float4 fract; metal::int4 exp; }; -__modf_result_f32_ naga_modf(float arg) { +_modf_result_f32_ naga_modf(float arg) { float other; float fract = metal::modf(arg, other); - return __modf_result_f32_{ fract, other }; + return _modf_result_f32_{ fract, other }; } -__modf_result_vec2_f32_ naga_modf(metal::float2 arg) { +_modf_result_vec2_f32_ naga_modf(metal::float2 arg) { metal::float2 other; metal::float2 fract = metal::modf(arg, other); - return __modf_result_vec2_f32_{ fract, other }; + return _modf_result_vec2_f32_{ fract, other }; } -__modf_result_vec4_f32_ naga_modf(metal::float4 arg) { +_modf_result_vec4_f32_ naga_modf(metal::float4 arg) { metal::float4 other; metal::float4 fract = metal::modf(arg, other); - return __modf_result_vec4_f32_{ fract, other }; + return _modf_result_vec4_f32_{ fract, other }; } -__frexp_result_f32_ naga_frexp(float arg) { +_frexp_result_f32_ naga_frexp(float arg) { int other; float fract = metal::frexp(arg, other); - return __frexp_result_f32_{ fract, other }; + return _frexp_result_f32_{ fract, other }; } -__frexp_result_vec4_f32_ naga_frexp(metal::float4 arg) { +_frexp_result_vec4_f32_ naga_frexp(metal::float4 arg) { int4 other; metal::float4 fract = metal::frexp(arg, other); - return __frexp_result_vec4_f32_{ fract, other }; + return _frexp_result_vec4_f32_{ fract, other }; } fragment void main_( @@ -95,13 +95,13 @@ fragment void main_( metal::uint2 clz_d = metal::clz(metal::uint2(1u)); float lde_a = metal::ldexp(1.0, 2); metal::float2 lde_b = metal::ldexp(metal::float2(1.0, 2.0), metal::int2(3, 4)); - __modf_result_f32_ modf_a = naga_modf(1.5); + _modf_result_f32_ modf_a = naga_modf(1.5); float modf_b = naga_modf(1.5).fract; float modf_c = naga_modf(1.5).whole; - __modf_result_vec2_f32_ modf_d = naga_modf(metal::float2(1.5, 1.5)); + _modf_result_vec2_f32_ modf_d = naga_modf(metal::float2(1.5, 1.5)); float modf_e = naga_modf(metal::float4(1.5, 1.5, 1.5, 1.5)).whole.x; float modf_f = naga_modf(metal::float2(1.5, 1.5)).fract.y; - __frexp_result_f32_ frexp_a = naga_frexp(1.5); + _frexp_result_f32_ frexp_a = naga_frexp(1.5); float frexp_b = naga_frexp(1.5).fract; int frexp_c = naga_frexp(1.5).exp; int frexp_d = naga_frexp(metal::float4(1.5, 1.5, 1.5, 1.5)).exp.x; From a17a93ef8f6a06ed8dfc3145276663786828df03 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 28 Sep 2023 00:09:57 -0700 Subject: [PATCH 2109/2212] snapshots: convert_wgsl: Remove redundant cubeArrayShadow entry. (#2514) The duplicate entry was introduced accidentally in #1845. --- tests/snapshots.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index b4394c415..1a6159e3a 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -740,7 +740,6 @@ fn convert_wgsl() { "math-functions", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), - ("cubeArrayShadow", Targets::GLSL), ( "binding-arrays", Targets::WGSL | Targets::HLSL | Targets::METAL | Targets::SPIRV, From f72489be00b64f831f6f7fba3b06dae3cc37f8eb Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Thu, 28 Sep 2023 20:32:46 +0200 Subject: [PATCH 2110/2212] validate variable initializer for address spaces (#2513) --- src/valid/interface.rs | 9 +++++++++ tests/wgsl-errors.rs | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 2444d29d9..ef88a46a8 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -33,6 +33,8 @@ pub enum GlobalVariableError { ), #[error("Initializer doesn't match the variable type")] InitializerType, + #[error("Initializer can't be used with address space {0:?}")] + InitializerNotAllowed(crate::AddressSpace), #[error("Storage address space doesn't support write-only access")] StorageAddressSpaceWriteOnlyNotSupported, } @@ -572,6 +574,13 @@ impl super::Validator { } if let Some(init) = var.init { + match var.space { + crate::AddressSpace::Private | crate::AddressSpace::Function => {} + _ => { + return Err(GlobalVariableError::InitializerNotAllowed(var.space)); + } + } + let decl_ty = &gctx.types[var.ty].inner; let init_ty = mod_info[init].inner_with(gctx.types); if !decl_ty.equivalent(init_ty, gctx.types) { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 48318f280..b164f6955 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1606,6 +1606,21 @@ fn host_shareable_types() { } } +#[test] +fn var_init() { + check_validation! { + " + var initialized: u32 = 0u; + ": + Err( + naga::valid::ValidationError::GlobalVariable { + source: naga::valid::GlobalVariableError::InitializerNotAllowed(naga::AddressSpace::WorkGroup), + .. + }, + ) + } +} + #[test] fn misplaced_break_if() { check( From ee236e6c9b6234309b0cf6f650ea3418220abdfc Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 26 Sep 2023 19:15:09 +0200 Subject: [PATCH 2111/2212] [valid] make sure `textureSampleBias` is only used in the fragment stage --- src/valid/expression.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index f9b77b129..3426bf008 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -492,7 +492,7 @@ impl super::Validator { } => {} _ => return Err(ExpressionError::InvalidSampleLevelBiasType(expr)), } - ShaderStages::all() + ShaderStages::FRAGMENT } crate::SampleLevel::Gradient { x, y } => { match resolver[x] { From e6a47ba262470eece43fda4c9c48129b51a16e34 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 26 Sep 2023 19:22:34 +0200 Subject: [PATCH 2112/2212] disable uniformity analysis for the fragment stage --- src/valid/analyzer.rs | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index e4162e15f..9b21b7f73 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -16,6 +16,10 @@ use std::ops; pub type NonUniformResult = Option>; +// Remove this once we update our uniformity analysis and +// add support for the `derivative_uniformity` diagnostic +const DISABLE_UNIFORMITY_REQ_FOR_FRAGMENT_STAGE: bool = true; + bitflags::bitflags! { /// Kinds of expressions that require uniform control flow. #[cfg_attr(feature = "serialize", derive(serde::Serialize))] @@ -23,8 +27,8 @@ bitflags::bitflags! { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct UniformityRequirements: u8 { const WORK_GROUP_BARRIER = 0x1; - const DERIVATIVE = 0x2; - const IMPLICIT_LEVEL = 0x4; + const DERIVATIVE = if DISABLE_UNIFORMITY_REQ_FOR_FRAGMENT_STAGE { 0 } else { 0x2 }; + const IMPLICIT_LEVEL = if DISABLE_UNIFORMITY_REQ_FOR_FRAGMENT_STAGE { 0 } else { 0x4 }; } } @@ -1185,21 +1189,28 @@ fn uniform_control_flow() { .into(), reject: crate::Block::new(), }; - assert_eq!( - info.process_block( + { + let block_info = info.process_block( &vec![stmt_emit2, stmt_if_non_uniform].into(), &[], None, - &expressions - ), - Err(FunctionError::NonUniformControlFlow( - UniformityRequirements::DERIVATIVE, - derivative_expr, - UniformityDisruptor::Expression(non_uniform_global_expr) - ) - .with_span()), - ); - assert_eq!(info[derivative_expr].ref_count, 1); + &expressions, + ); + if DISABLE_UNIFORMITY_REQ_FOR_FRAGMENT_STAGE { + assert_eq!(info[derivative_expr].ref_count, 2); + } else { + assert_eq!( + block_info, + Err(FunctionError::NonUniformControlFlow( + UniformityRequirements::DERIVATIVE, + derivative_expr, + UniformityDisruptor::Expression(non_uniform_global_expr) + ) + .with_span()), + ); + assert_eq!(info[derivative_expr].ref_count, 1); + } + } assert_eq!(info[non_uniform_global], GlobalUse::READ); let stmt_emit3 = S::Emit(emit_range_globals); From c927d3ec826fb0e23538635b1882db1e4e1ce75e Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 26 Sep 2023 13:08:23 +0200 Subject: [PATCH 2113/2212] remove duplicated code --- src/back/glsl/features.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 6bb5b1888..2a706fb1e 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -209,11 +209,6 @@ impl FeaturesManager { writeln!(out, "#extension GL_OES_sample_variables : require")?; } - if self.0.contains(Features::SAMPLE_VARIABLES) && version.is_es() { - // https://www.khronos.org/registry/OpenGL/extensions/OES/OES_sample_variables.txt - writeln!(out, "#extension GL_OES_sample_variables : require")?; - } - if self.0.contains(Features::MULTI_VIEW) { if let Version::Embedded { is_webgl: true, .. } = version { // https://www.khronos.org/registry/OpenGL/extensions/OVR/OVR_multiview2.txt From 9f3cdb61aae3dccffbfe9affc0db85305f765864 Mon Sep 17 00:00:00 2001 From: Evan Mark Hopkins <85699459+evahop@users.noreply.github.com> Date: Fri, 29 Sep 2023 06:26:23 -0400 Subject: [PATCH 2114/2212] [msl-out] Make varyings' struct members unique (#2521) --- src/back/msl/writer.rs | 51 +++++++++++++++++----------------- tests/in/msl-varyings.wgsl | 23 +++++++++++++++ tests/out/msl/msl-varyings.msl | 50 +++++++++++++++++++++++++++++++++ tests/snapshots.rs | 1 + 4 files changed, 99 insertions(+), 26 deletions(-) create mode 100644 tests/in/msl-varyings.wgsl create mode 100644 tests/out/msl/msl-varyings.msl diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 67ab88728..77231a286 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3689,6 +3689,15 @@ impl Writer { } }; + // Since `Namer.reset` wasn't expecting struct members to be + // suddenly injected into another namespace like this, + // `self.names` doesn't keep them distinct from other variables. + // Generate fresh names for these arguments, and remember the + // mapping. + let mut flattened_member_names = FastHashMap::default(); + // Varyings' members get their own namespace + let mut varyings_namer = crate::proc::Namer::default(); + // List all the Naga `EntryPoint`'s `Function`'s arguments, // flattening structs into their members. In Metal, we will pass // each of these values to the entry point as a separate argument— @@ -3704,6 +3713,14 @@ impl Writer { member.ty, member.binding.as_ref(), )); + let name_key = NameKey::StructMember(arg.ty, member_index); + let name = match member.binding { + Some(crate::Binding::Location { .. }) => { + varyings_namer.call(&self.names[&name_key]) + } + _ => self.namer.call(&self.names[&name_key]), + }; + flattened_member_names.insert(name_key, name); } } _ => flattened_arguments.push(( @@ -3727,7 +3744,10 @@ impl Writer { _ => continue, }; has_varyings = true; - let name = &self.names[name_key]; + let name = match *name_key { + NameKey::StructMember(..) => &flattened_member_names[name_key], + _ => &self.names[name_key], + }; let ty_name = TypeContext { handle: ty, gctx: module.to_ctx(), @@ -3840,27 +3860,14 @@ impl Writer { // Then pass the remaining arguments not included in the varyings // struct. - // - // Since `Namer.reset` wasn't expecting struct members to be - // suddenly injected into the normal namespace like this, - // `self.names` doesn't keep them distinct from other variables. - // Generate fresh names for these arguments, and remember the - // mapping. - let mut flattened_member_names = FastHashMap::default(); for &(ref name_key, ty, binding) in flattened_arguments.iter() { let binding = match binding { Some(binding @ &crate::Binding::BuiltIn { .. }) => binding, _ => continue, }; - let name = if let NameKey::StructMember(ty, index) = *name_key { - // We should always insert a fresh entry here, but use - // `or_insert` to get a reference to the `String` we just - // inserted. - flattened_member_names - .entry(NameKey::StructMember(ty, index)) - .or_insert_with(|| self.namer.call(&self.names[name_key])) - } else { - &self.names[name_key] + let name = match *name_key { + NameKey::StructMember(..) => &flattened_member_names[name_key], + _ => &self.names[name_key], }; if binding == &crate::Binding::BuiltIn(crate::BuiltIn::LocalInvocationId) { @@ -4057,15 +4064,7 @@ impl Writer { )?; for (member_index, member) in members.iter().enumerate() { let key = NameKey::StructMember(arg.ty, member_index as u32); - // If it's not in the varying struct, then we should - // have passed it as its own argument and assigned - // it a new name. - let name = match member.binding { - Some(crate::Binding::BuiltIn { .. }) => { - &flattened_member_names[&key] - } - _ => &self.names[&key], - }; + let name = &flattened_member_names[&key]; if member_index != 0 { write!(self.out, ", ")?; } diff --git a/tests/in/msl-varyings.wgsl b/tests/in/msl-varyings.wgsl new file mode 100644 index 000000000..21c6184bf --- /dev/null +++ b/tests/in/msl-varyings.wgsl @@ -0,0 +1,23 @@ +struct Vertex { + @location(0) position: vec2f +} + +struct NoteInstance { + @location(1) position: vec2f +} + +struct VertexOutput { + @builtin(position) position: vec4f +} + +@vertex +fn vs_main(vertex: Vertex, note: NoteInstance) -> VertexOutput { + var out: VertexOutput; + return out; +} + +@fragment +fn fs_main(in: VertexOutput, note: NoteInstance) -> @location(0) vec4f { + let position = vec3(1f); + return in.position; +} diff --git a/tests/out/msl/msl-varyings.msl b/tests/out/msl/msl-varyings.msl new file mode 100644 index 000000000..62d635249 --- /dev/null +++ b/tests/out/msl/msl-varyings.msl @@ -0,0 +1,50 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + +struct Vertex { + metal::float2 position; +}; +struct NoteInstance { + metal::float2 position; +}; +struct VertexOutput { + metal::float4 position; +}; + +struct vs_mainInput { + metal::float2 position [[attribute(0)]]; + metal::float2 position_1 [[attribute(1)]]; +}; +struct vs_mainOutput { + metal::float4 position [[position]]; +}; +vertex vs_mainOutput vs_main( + vs_mainInput varyings [[stage_in]] +) { + const Vertex vertex_ = { varyings.position }; + const NoteInstance note = { varyings.position_1 }; + VertexOutput out = {}; + VertexOutput _e3 = out; + const auto _tmp = _e3; + return vs_mainOutput { _tmp.position }; +} + + +struct fs_mainInput { + metal::float2 position [[user(loc1), center_perspective]]; +}; +struct fs_mainOutput { + metal::float4 member_1 [[color(0)]]; +}; +fragment fs_mainOutput fs_main( + fs_mainInput varyings_1 [[stage_in]] +, metal::float4 position [[position]] +) { + const VertexOutput in = { position }; + const NoteInstance note_1 = { varyings_1.position }; + metal::float3 position_1 = metal::float3(1.0); + return fs_mainOutput { in.position }; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 1a6159e3a..495bea959 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -776,6 +776,7 @@ fn convert_wgsl() { "constructors", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ("msl-varyings", Targets::METAL), ]; for &(name, targets) in inputs.iter() { From 613da72ac0c2f56a5e1a2c4becf7e373a2b82e77 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 3 Oct 2023 13:34:56 +0200 Subject: [PATCH 2115/2212] [spv-out] require ClipDistance & CullDistance capabilities if necessary (#2528) --- src/back/spv/writer.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 56d018b6f..8cad9c4d2 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1514,8 +1514,20 @@ impl Writer { // vertex Bi::BaseInstance => BuiltIn::BaseInstance, Bi::BaseVertex => BuiltIn::BaseVertex, - Bi::ClipDistance => BuiltIn::ClipDistance, - Bi::CullDistance => BuiltIn::CullDistance, + Bi::ClipDistance => { + self.require_any( + "`clip_distance` built-in", + &[spirv::Capability::ClipDistance], + )?; + BuiltIn::ClipDistance + } + Bi::CullDistance => { + self.require_any( + "`cull_distance` built-in", + &[spirv::Capability::CullDistance], + )?; + BuiltIn::CullDistance + } Bi::InstanceIndex => BuiltIn::InstanceIndex, Bi::PointSize => BuiltIn::PointSize, Bi::VertexIndex => BuiltIn::VertexIndex, From 6668d0694cc51ee66c71c2ca3a1ab1081956299b Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 3 Oct 2023 13:36:14 +0200 Subject: [PATCH 2116/2212] Add Rgb10a2Uint format (#2525) --- src/back/glsl/features.rs | 1 + src/back/glsl/mod.rs | 3 ++- src/back/hlsl/conv.rs | 3 ++- src/back/spv/instructions.rs | 3 ++- src/back/wgsl/writer.rs | 1 + src/front/glsl/parser/types.rs | 1 + src/front/spv/convert.rs | 3 ++- src/front/wgsl/mod.rs | 1 + src/front/wgsl/parse/conv.rs | 1 + src/lib.rs | 1 + src/proc/mod.rs | 1 + 11 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 2a706fb1e..4aac9b2e6 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -357,6 +357,7 @@ impl<'a, W> Writer<'a, W> { | StorageFormat::Rg16Uint | StorageFormat::Rg16Sint | StorageFormat::Rg16Float + | StorageFormat::Rgb10a2Uint | StorageFormat::Rgb10a2Unorm | StorageFormat::Rg11b10Float | StorageFormat::Rg32Uint diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index eb2c2ed02..ddef6a4c0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -4238,7 +4238,8 @@ const fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { Sf::Rgba8Snorm => "rgba8_snorm", Sf::Rgba8Uint => "rgba8ui", Sf::Rgba8Sint => "rgba8i", - Sf::Rgb10a2Unorm => "rgb10_a2ui", + Sf::Rgb10a2Uint => "rgb10_a2ui", + Sf::Rgb10a2Unorm => "rgb10_a2", Sf::Rg11b10Float => "r11f_g11f_b10f", Sf::Rg32Uint => "rg32ui", Sf::Rg32Sint => "rg32i", diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index aed2dc0ed..dcbda3d74 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -129,7 +129,8 @@ impl crate::StorageFormat { | Self::Rgba16Uint | Self::R32Uint | Self::Rg32Uint - | Self::Rgba32Uint => "uint4", + | Self::Rgba32Uint + | Self::Rgb10a2Uint => "uint4", Self::Rgba8Sint | Self::Rgba16Sint | Self::R32Sint diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 11794fc73..86b3fd865 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -1064,7 +1064,8 @@ impl From for spirv::ImageFormat { Sf::Rgba8Snorm => Self::Rgba8Snorm, Sf::Rgba8Uint => Self::Rgba8ui, Sf::Rgba8Sint => Self::Rgba8i, - Sf::Rgb10a2Unorm => Self::Rgb10a2ui, + Sf::Rgb10a2Uint => Self::Rgb10a2ui, + Sf::Rgb10a2Unorm => Self::Rgb10A2, Sf::Rg11b10Float => Self::R11fG11fB10f, Sf::Rg32Uint => Self::Rg32ui, Sf::Rg32Sint => Self::Rg32i, diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 980d76878..428a41337 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1830,6 +1830,7 @@ const fn storage_format_str(format: crate::StorageFormat) -> &'static str { Sf::Rgba8Snorm => "rgba8snorm", Sf::Rgba8Uint => "rgba8uint", Sf::Rgba8Sint => "rgba8sint", + Sf::Rgb10a2Uint => "rgb10a2uint", Sf::Rgb10a2Unorm => "rgb10a2unorm", Sf::Rg11b10Float => "rg11b10float", Sf::Rg32Uint => "rg32uint", diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index d2d24b5da..631667702 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -401,6 +401,7 @@ fn map_image_format(word: &str) -> Option { "r32f" => Sf::R32Float, "r16f" => Sf::R16Float, "rgba16" => Sf::Rgba16Unorm, + "rgb10_a2ui" => Sf::Rgb10a2Uint, "rgb10_a2" => Sf::Rgb10a2Unorm, "rgba8" => Sf::Rgba8Unorm, "rg16" => Sf::Rg16Unorm, diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 2967555d2..f547e806a 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -105,7 +105,8 @@ pub(super) fn map_image_format(word: spirv::Word) -> Result Ok(crate::StorageFormat::Rgba8Snorm), Some(spirv::ImageFormat::Rgba8ui) => Ok(crate::StorageFormat::Rgba8Uint), Some(spirv::ImageFormat::Rgba8i) => Ok(crate::StorageFormat::Rgba8Sint), - Some(spirv::ImageFormat::Rgb10a2ui) => Ok(crate::StorageFormat::Rgb10a2Unorm), + Some(spirv::ImageFormat::Rgb10a2ui) => Ok(crate::StorageFormat::Rgb10a2Uint), + Some(spirv::ImageFormat::Rgb10A2) => Ok(crate::StorageFormat::Rgb10a2Unorm), Some(spirv::ImageFormat::R11fG11fB10f) => Ok(crate::StorageFormat::Rg11b10Float), Some(spirv::ImageFormat::Rg32ui) => Ok(crate::StorageFormat::Rg32Uint), Some(spirv::ImageFormat::Rg32i) => Ok(crate::StorageFormat::Rg32Sint), diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 2b471a8a9..6982e850b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -71,6 +71,7 @@ impl crate::StorageFormat { Sf::Rgba8Snorm => "rgba8snorm", Sf::Rgba8Uint => "rgba8uint", Sf::Rgba8Sint => "rgba8sint", + Sf::Rgb10a2Uint => "rgb10a2uint", Sf::Rgb10a2Unorm => "rgb10a2unorm", Sf::Rg11b10Float => "rg11b10float", Sf::Rg32Uint => "rg32uint", diff --git a/src/front/wgsl/parse/conv.rs b/src/front/wgsl/parse/conv.rs index a69dbbe47..3b14d0aee 100644 --- a/src/front/wgsl/parse/conv.rs +++ b/src/front/wgsl/parse/conv.rs @@ -84,6 +84,7 @@ pub fn map_storage_format(word: &str, span: Span) -> Result Sf::Rgba8Snorm, "rgba8uint" => Sf::Rgba8Uint, "rgba8sint" => Sf::Rgba8Sint, + "rgb10a2uint" => Sf::Rgb10a2Uint, "rgb10a2unorm" => Sf::Rgb10a2Unorm, "rg11b10float" => Sf::Rg11b10Float, "rg32uint" => Sf::Rg32Uint, diff --git a/src/lib.rs b/src/lib.rs index 935157289..e7abe1e1c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -601,6 +601,7 @@ pub enum StorageFormat { Rgba8Sint, // Packed 32-bit formats + Rgb10a2Uint, Rgb10a2Unorm, Rg11b10Float, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index bfb2b0d7a..90fd9500a 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -39,6 +39,7 @@ impl From for super::ScalarKind { Sf::Rgba8Snorm => Sk::Float, Sf::Rgba8Uint => Sk::Uint, Sf::Rgba8Sint => Sk::Sint, + Sf::Rgb10a2Uint => Sk::Uint, Sf::Rgb10a2Unorm => Sk::Float, Sf::Rg11b10Float => Sk::Float, Sf::Rg32Uint => Sk::Uint, From f37db5affc6a5e84f3aa0f8e09eeb11e146e4032 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Oct 2023 19:14:52 +0200 Subject: [PATCH 2117/2212] [wgsl] remove `outerProduct` (#2535) --- src/back/wgsl/writer.rs | 3 +-- src/front/wgsl/parse/conv.rs | 1 - tests/in/glsl/math-functions.frag | 3 ++- tests/out/wgsl/math-functions.frag.wgsl | 24 ++++++++++-------------- 4 files changed, 13 insertions(+), 18 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 428a41337..8f6b4074a 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1529,7 +1529,6 @@ impl Writer { Mf::Pow => Function::Regular("pow"), // geometry Mf::Dot => Function::Regular("dot"), - Mf::Outer => Function::Regular("outerProduct"), Mf::Cross => Function::Regular("cross"), Mf::Distance => Function::Regular("distance"), Mf::Length => Function::Regular("length"), @@ -1568,7 +1567,7 @@ impl Writer { Mf::Unpack2x16snorm => Function::Regular("unpack2x16snorm"), Mf::Unpack2x16unorm => Function::Regular("unpack2x16unorm"), Mf::Unpack2x16float => Function::Regular("unpack2x16float"), - Mf::Inverse => { + Mf::Inverse | Mf::Outer => { return Err(Error::UnsupportedMathFunction(fun)); } }; diff --git a/src/front/wgsl/parse/conv.rs b/src/front/wgsl/parse/conv.rs index 3b14d0aee..fea60dc09 100644 --- a/src/front/wgsl/parse/conv.rs +++ b/src/front/wgsl/parse/conv.rs @@ -180,7 +180,6 @@ pub fn map_standard_fun(word: &str) -> Option { "pow" => Mf::Pow, // geometry "dot" => Mf::Dot, - "outerProduct" => Mf::Outer, "cross" => Mf::Cross, "distance" => Mf::Distance, "length" => Mf::Length, diff --git a/tests/in/glsl/math-functions.frag b/tests/in/glsl/math-functions.frag index 3c12d82d2..1006bda83 100644 --- a/tests/in/glsl/math-functions.frag +++ b/tests/in/glsl/math-functions.frag @@ -44,7 +44,8 @@ void main() { vec4 minOut = min(a, b); vec4 reflectOut = reflect(a, b); vec3 crossOut = cross(a.xyz, b.xyz); - mat4 outerProductOut = outerProduct(a, b); + // TODO: support outerProduct function in wgsl output + // mat4 outerProductOut = outerProduct(a, b); float distanceOut = distance(a, b); vec4 stepOut = step(a, b); // TODO: support out params in wgsl output diff --git a/tests/out/wgsl/math-functions.frag.wgsl b/tests/out/wgsl/math-functions.frag.wgsl index 37e42868a..0bcc5f533 100644 --- a/tests/out/wgsl/math-functions.frag.wgsl +++ b/tests/out/wgsl/math-functions.frag.wgsl @@ -39,7 +39,6 @@ fn main_1() { var minOut: vec4; var reflectOut: vec4; var crossOut: vec3; - var outerProductOut: mat4x4; var distanceOut: f32; var stepOut: vec4; var ldexpOut: f32; @@ -146,22 +145,19 @@ fn main_1() { crossOut = cross(_e205.xyz, _e207.xyz); let _e213 = a; let _e214 = b; - outerProductOut = outerProduct(_e213, _e214); + distanceOut = distance(_e213, _e214); let _e219 = a; let _e220 = b; - distanceOut = distance(_e219, _e220); - let _e225 = a; - let _e226 = b; - stepOut = step(_e225, _e226); - let _e229 = a; + stepOut = step(_e219, _e220); + let _e223 = a; + let _e226 = a; + let _e228 = i; + ldexpOut = ldexp(_e226.x, _e228); let _e232 = a; - let _e234 = i; - ldexpOut = ldexp(_e232.x, _e234); - let _e238 = a; - rad = radians(_e238); - let _e241 = a; - let _e243 = a; - deg = degrees(_e243.x); + rad = radians(_e232); + let _e235 = a; + let _e237 = a; + deg = degrees(_e237.x); smoothStepScalar = smoothstep(0.0, 1.0, 0.5); smoothStepVector = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); smoothStepMixed = smoothstep(vec4(0.0), vec4(1.0), vec4(0.5)); From 4d6e0005f41b97f4153772f5e78f25f67be27ab3 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Oct 2023 21:50:36 +0200 Subject: [PATCH 2118/2212] [valid] Disallow NaNs and infinities (#2508) * [valid] disallow NaNs and infinities * document literal float constraints --- src/lib.rs | 2 ++ src/valid/expression.rs | 58 ++++++++++++++++++++++++++++++++++++++--- src/valid/mod.rs | 12 +-------- 3 files changed, 58 insertions(+), 14 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e7abe1e1c..563325a7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -854,7 +854,9 @@ pub enum TypeInner { #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum Literal { + /// May not be NaN or infinity. F64(f64), + /// May not be NaN or infinity. F32(f32), U32(u32), I32(i32), diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 3426bf008..0b6125368 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -124,6 +124,29 @@ pub enum ExpressionError { InvalidWorkGroupUniformLoadResultType(Handle), #[error("Shader requires capability {0:?}")] MissingCapabilities(super::Capabilities), + #[error(transparent)] + Literal(#[from] LiteralError), +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum ConstExpressionError { + #[error("The expression is not a constant expression")] + NonConst, + #[error(transparent)] + Compose(#[from] super::ComposeError), + #[error("Type resolution failed")] + Type(#[from] ResolveError), + #[error(transparent)] + Literal(#[from] LiteralError), +} + +#[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] +pub enum LiteralError { + #[error("Float literal is NaN")] + NaN, + #[error("Float literal is infinite")] + Infinity, } #[cfg(feature = "validate")] @@ -158,11 +181,14 @@ impl super::Validator { handle: Handle, gctx: crate::proc::GlobalCtx, mod_info: &ModuleInfo, - ) -> Result<(), super::ConstExpressionError> { + ) -> Result<(), ConstExpressionError> { use crate::Expression as E; match gctx.const_expressions[handle] { - E::Literal(_) | E::Constant(_) | E::ZeroValue(_) => {} + E::Literal(literal) => { + validate_literal(literal)?; + } + E::Constant(_) | E::ZeroValue(_) => {} E::Compose { ref components, ty } => { validate_compose( ty, @@ -310,7 +336,11 @@ impl super::Validator { } ShaderStages::all() } - E::Literal(_) | E::Constant(_) | E::ZeroValue(_) => ShaderStages::all(), + E::Literal(literal) => { + validate_literal(literal)?; + ShaderStages::all() + } + E::Constant(_) | E::ZeroValue(_) => ShaderStages::all(), E::Compose { ref components, ty } => { validate_compose( ty, @@ -1529,3 +1559,25 @@ impl super::Validator { } } } + +fn validate_literal(literal: crate::Literal) -> Result<(), LiteralError> { + let is_nan = match literal { + crate::Literal::F64(v) => v.is_nan(), + crate::Literal::F32(v) => v.is_nan(), + _ => false, + }; + if is_nan { + return Err(LiteralError::NaN); + } + + let is_infinite = match literal { + crate::Literal::F64(v) => v.is_infinite(), + crate::Literal::F32(v) => v.is_infinite(), + _ => false, + }; + if is_infinite { + return Err(LiteralError::Infinity); + } + + Ok(()) +} diff --git a/src/valid/mod.rs b/src/valid/mod.rs index f99a2055c..6175aa094 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -24,7 +24,7 @@ use std::ops; use crate::span::{AddSpan as _, WithSpan}; pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements}; pub use compose::ComposeError; -pub use expression::ExpressionError; +pub use expression::{ConstExpressionError, ExpressionError}; pub use function::{CallError, FunctionError, LocalVariableError}; pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; pub use r#type::{Disalignment, TypeError, TypeFlags}; @@ -180,16 +180,6 @@ pub struct Validator { valid_expression_set: BitSet, } -#[derive(Clone, Debug, thiserror::Error)] -pub enum ConstExpressionError { - #[error("The expression is not a constant expression")] - NonConst, - #[error(transparent)] - Compose(#[from] ComposeError), - #[error("Type resolution failed")] - Type(#[from] crate::proc::ResolveError), -} - #[derive(Clone, Debug, thiserror::Error)] pub enum ConstantError { #[error("The type doesn't match the constant")] From 31f547580c535b0a496d0a97b42f6ef7d34e697c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 5 Oct 2023 17:30:29 -0700 Subject: [PATCH 2119/2212] Remove `expression` argument to `FunctionInfo::process_expression`. We're already passing the handle and the arena, so it's superfluous. --- src/valid/analyzer.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 9b21b7f73..72d898b63 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -427,7 +427,6 @@ impl FunctionInfo { fn process_expression( &mut self, handle: Handle, - expression: &crate::Expression, expression_arena: &Arena, other_functions: &[FunctionInfo], resolve_context: &ResolveContext, @@ -435,6 +434,7 @@ impl FunctionInfo { ) -> Result<(), ExpressionError> { use crate::{Expression as E, SampleLevel as Sl}; + let expression = &expression_arena[handle]; let mut assignable_global = None; let uniformity = match *expression { E::Access { base, index } => { @@ -1011,10 +1011,9 @@ impl ModuleInfo { let resolve_context = ResolveContext::with_locals(module, &fun.local_variables, &fun.arguments); - for (handle, expr) in fun.expressions.iter() { + for (handle, _) in fun.expressions.iter() { if let Err(source) = info.process_expression( handle, - expr, &fun.expressions, &self.functions, &resolve_context, @@ -1127,10 +1126,9 @@ fn uniform_control_flow() { functions: &Arena::new(), arguments: &[], }; - for (handle, expression) in expressions.iter() { + for (handle, _) in expressions.iter() { info.process_expression( handle, - expression, &expressions, &[], &resolve_context, From c6716033da62bf2038c0ba2460e893a8a928b6d3 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 5 Oct 2023 18:15:26 -0700 Subject: [PATCH 2120/2212] Improve docs for `FunctionInfo::process_expression`. --- src/valid/analyzer.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 72d898b63..0ed707c1e 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -421,8 +421,25 @@ impl FunctionInfo { }) } - /// Computes the expression info and stores it in `self.expressions`. - /// Also, bumps the reference counts on dependent expressions. + /// Compute the [`ExpressionInfo`] for `handle`. + /// + /// Replace the dummy entry in [`self.expressions`] for `handle` + /// with a real `ExpressionInfo` value describing that expression. + /// + /// This function is called as part of a forward sweep through the + /// arena, so we can assume that all earlier expressions in the + /// arena already have valid info. Since expressions only depend + /// on earlier expressions, this includes all our subexpressions. + /// + /// Adjust the reference counts on all expressions we use. + /// + /// Also populate the [`sampling_set`], [`sampling`] and + /// [`global_uses`] fields of `self`. + /// + /// [`self.expressions`]: FunctionInfo::expressions + /// [`sampling_set`]: FunctionInfo::sampling_set + /// [`sampling`]: FunctionInfo::sampling + /// [`global_uses`]: FunctionInfo::global_uses #[allow(clippy::or_fun_call)] fn process_expression( &mut self, From e820c33abf1f560297bdcdcff37952abb5eddc02 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 6 Oct 2023 09:15:33 -0700 Subject: [PATCH 2121/2212] compact: Minor cleanups. - Simplify visibility markings. - Remove some testing comments. (Tests carried out.) - Remove some commented-out code. --- src/compact/expressions.rs | 1 - src/compact/functions.rs | 21 +++++++-------------- 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/src/compact/expressions.rs b/src/compact/expressions.rs index 4ccf559c4..c1326e92b 100644 --- a/src/compact/expressions.rs +++ b/src/compact/expressions.rs @@ -271,7 +271,6 @@ impl ModuleMap { adjust(sampler); adjust(coordinate); operand_map.adjust_option(array_index); - // TEST: try adjusting this with plain operand_map if let Some(ref mut offset) = *offset { self.const_expressions.adjust(offset); } diff --git a/src/compact/functions.rs b/src/compact/functions.rs index 08ca289a5..35f4e7b34 100644 --- a/src/compact/functions.rs +++ b/src/compact/functions.rs @@ -2,16 +2,16 @@ use super::handle_set_map::HandleSet; use super::{FunctionMap, ModuleMap}; use crate::arena::Handle; -pub(super) struct FunctionTracer<'a> { - pub(super) module: &'a crate::Module, - pub(super) function: &'a crate::Function, +pub struct FunctionTracer<'a> { + pub module: &'a crate::Module, + pub function: &'a crate::Function, - pub(super) types_used: &'a mut HandleSet, - pub(super) constants_used: &'a mut HandleSet, - pub(super) const_expressions_used: &'a mut HandleSet, + pub types_used: &'a mut HandleSet, + pub constants_used: &'a mut HandleSet, + pub const_expressions_used: &'a mut HandleSet, /// Function-local expressions used. - pub(super) expressions_used: HandleSet, + pub expressions_used: HandleSet, } impl<'a> FunctionTracer<'a> { @@ -27,7 +27,6 @@ impl<'a> FunctionTracer<'a> { for (_, local) in self.function.local_variables.iter() { self.trace_type(local.ty); if let Some(init) = local.init { - // TEST: try changing this to trace_expression self.trace_const_expression(init); } } @@ -55,12 +54,6 @@ impl<'a> FunctionTracer<'a> { .trace_expression(expr); } - /* - pub fn trace_const_expression(&mut self, const_expr: Handle) { - self.as_expression().as_const_expression().trace_expression(const_expr); - } - */ - fn as_type(&mut self) -> super::types::TypeTracer { super::types::TypeTracer { types: &self.module.types, From fa0fed100eac261375659e3d459aece66d224480 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 7 Oct 2023 10:02:54 -0700 Subject: [PATCH 2122/2212] compact: Don't assume Emitted expressions are live. If an `Emit` statement covers an `Expression` that is not otherwise used by any `Statement`, remove it from the `Arena` anyway. An `Emit` statement controls when `Expression`s are evaluated, but it doesn't have any side effects, so unless an expression is used by some other statement, it's not necessary to the program. --- src/arena.rs | 50 ++++++++++++++++++++++++++--------- src/compact/functions.rs | 2 +- src/compact/handle_set_map.rs | 35 +++++++++++++++++++++++- src/compact/statements.rs | 26 +++++++----------- 4 files changed, 82 insertions(+), 31 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 49b932801..3f17c5729 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -199,7 +199,7 @@ impl Range { } } - /// Return the first and last handles included in `self`. + /// return the first and last handles included in `self`. /// /// If `self` is an empty range, there are no handles included, so /// return `None`. @@ -216,6 +216,24 @@ impl Range { None } } + + /// Return the zero-based index range covered by `self`. + pub fn zero_based_index_range(&self) -> ops::Range { + self.inner.clone() + } + + /// Construct a `Range` that covers the zero-based indices in `inner`. + pub fn from_zero_based_index_range(inner: ops::Range, arena: &Arena) -> Self { + // Since `inner` is a `Range`, we only need to check that + // the start and end are well-ordered, and that the end fits + // within `arena`. + assert!(inner.start <= inner.end); + assert!(inner.end as usize <= arena.len()); + Self { + inner, + marker: Default::default(), + } + } } /// An arena holding some kind of component (e.g., type, constant, @@ -387,18 +405,26 @@ impl Arena { /// Assert that `range` is valid for this arena. pub fn check_contains_range(&self, range: &Range) -> Result<(), BadRangeError> { - // Since `range.inner` is a `Range`, we only need to - // check that the start precedes the end, and that the end is - // in range. - if range.inner.start > range.inner.end - || self - .check_contains_handle(Handle::new(range.inner.end.try_into().unwrap())) - .is_err() - { - Err(BadRangeError::new(range.clone())) - } else { - Ok(()) + // Since `range.inner` is a `Range`, we only need to check that the + // start precedes the end, and that the end is in range. + if range.inner.start > range.inner.end { + return Err(BadRangeError::new(range.clone())); } + + // Empty ranges are tolerated: they can be produced by compaction. + if range.inner.start == range.inner.end { + return Ok(()); + } + + // `range.inner` is zero-based, but end-exclusive, so `range.inner.end` + // is actually the right one-based index for the last handle within the + // range. + let last_handle = Handle::new(range.inner.end.try_into().unwrap()); + if self.check_contains_handle(last_handle).is_err() { + return Err(BadRangeError::new(range.clone())); + } + + Ok(()) } #[cfg(feature = "compact")] diff --git a/src/compact/functions.rs b/src/compact/functions.rs index 35f4e7b34..176221f98 100644 --- a/src/compact/functions.rs +++ b/src/compact/functions.rs @@ -122,6 +122,6 @@ impl FunctionMap { assert!(reuse.is_empty()); // Adjust statements. - self.adjust_block(&mut function.body); + self.adjust_body(function); } } diff --git a/src/compact/handle_set_map.rs b/src/compact/handle_set_map.rs index 3a7968a71..bf74d3f0b 100644 --- a/src/compact/handle_set_map.rs +++ b/src/compact/handle_set_map.rs @@ -1,4 +1,4 @@ -use crate::arena::{Arena, Handle, UniqueArena}; +use crate::arena::{Arena, Handle, Range, UniqueArena}; type Index = std::num::NonZeroU32; @@ -122,4 +122,37 @@ impl HandleMap { self.adjust(handle); } } + + /// Shrink `range` to include only used handles. + /// + /// Fortunately, compaction doesn't arbitrarily scramble the expressions + /// in the arena, but instead preserves the order of the elements while + /// squeezing out unused ones. That means that a contiguous range in the + /// pre-compacted arena always maps to a contiguous range in the + /// post-compacted arena. So we just need to adjust the endpoints. + /// + /// Compaction may have eliminated the endpoints themselves. + /// + /// Use `compacted_arena` to bounds-check the result. + pub fn adjust_range(&self, range: &mut Range, compacted_arena: &Arena) { + let mut index_range = range.zero_based_index_range(); + let compacted; + // Remember that the indices we retrieve from `new_index` are 1-based + // compacted indices, but the index range we're computing is zero-based + // compacted indices. + if let Some(first1) = index_range.find_map(|i| self.new_index[i as usize]) { + // The first call to `find_map` mutated `index_range` to hold the + // remainder of original range, which is exactly the range we need + // to search for the new last handle. + if let Some(last1) = index_range.rev().find_map(|i| self.new_index[i as usize]) { + // Build a zero-based end-exclusive range, given one-based handle indices. + compacted = first1.get() - 1..last1.get(); + } else { + compacted = first1.get() - 1..first1.get(); + } + } else { + compacted = 0..0; + }; + *range = Range::from_zero_based_index_range(compacted, compacted_arena); + } } diff --git a/src/compact/statements.rs b/src/compact/statements.rs index 2c33df049..4c6277102 100644 --- a/src/compact/statements.rs +++ b/src/compact/statements.rs @@ -9,11 +9,12 @@ impl FunctionTracer<'_> { for stmt in last { use crate::Statement as St; match *stmt { - St::Emit(ref range) => { - for expr in range.clone() { - log::trace!("trace emitted expression {:?}", expr); - self.trace_expression(expr); - } + St::Emit(ref _range) => { + // If we come across a statement that actually uses an + // expression in this range, it'll get traced from + // there. But since evaluating expressions has no + // effect, we don't need to assume that everything + // emitted is live. } St::Block(ref block) => worklist.push(block), St::If { @@ -140,7 +141,8 @@ impl FunctionTracer<'_> { } impl FunctionMap { - pub fn adjust_block(&self, block: &mut [crate::Statement]) { + pub fn adjust_body(&self, function: &mut crate::Function) { + let block = &mut function.body; let mut worklist: Vec<&mut [crate::Statement]> = vec![block]; let adjust = |handle: &mut Handle| { self.expressions.adjust(handle); @@ -150,17 +152,7 @@ impl FunctionMap { use crate::Statement as St; match *stmt { St::Emit(ref mut range) => { - // Fortunately, compaction doesn't arbitrarily scramble - // the expressions in the arena, but instead preserves - // the order of the elements while squeezing out unused - // ones. That means that a contiguous range in the - // pre-compacted arena always maps to a contiguous range - // in the post-compacted arena. So we just need to - // adjust the endpoints. - let (mut first, mut last) = range.first_and_last().unwrap(); - self.expressions.adjust(&mut first); - self.expressions.adjust(&mut last); - *range = crate::arena::Range::new_from_bounds(first, last); + self.expressions.adjust_range(range, &function.expressions); } St::Block(ref mut block) => worklist.push(block), St::If { From fe484b3a1ba4c6a6bffebe4f12ed3168ed87bee0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 8 Oct 2023 13:53:05 -0700 Subject: [PATCH 2123/2212] Require that `Function` and `Private` variables be `CONSTRUCTIBLE`. Change the validator to enforce WGSL's requirement that all variables in the `function` and `private` address spaces must have constructible types. Mark the `RayQuery` type as `CONSTRUCTIBLE`, since it is intended to be used for local variables. Add a regression test. --- src/valid/function.rs | 5 +---- src/valid/interface.rs | 5 ++--- src/valid/type.rs | 5 ++++- tests/wgsl-errors.rs | 17 +++++++++++++++++ 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index 06aa27c84..998f873c0 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -948,10 +948,7 @@ impl super::Validator { .types .get(var.ty.index()) .ok_or(LocalVariableError::InvalidType(var.ty))?; - if !type_info - .flags - .contains(super::TypeFlags::DATA | super::TypeFlags::SIZED) - { + if !type_info.flags.contains(super::TypeFlags::CONSTRUCTIBLE) { return Err(LocalVariableError::InvalidType(var.ty)); } diff --git a/src/valid/interface.rs b/src/valid/interface.rs index ef88a46a8..7c6c5244e 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -541,9 +541,8 @@ impl super::Validator { (TypeFlags::empty(), true) } - crate::AddressSpace::Private | crate::AddressSpace::WorkGroup => { - (TypeFlags::DATA | TypeFlags::SIZED, false) - } + crate::AddressSpace::Private => (TypeFlags::CONSTRUCTIBLE, false), + crate::AddressSpace::WorkGroup => (TypeFlags::DATA | TypeFlags::SIZED, false), crate::AddressSpace::PushConstant => { if !self.capabilities.contains(Capabilities::PUSH_CONSTANT) { return Err(GlobalVariableError::UnsupportedCapability( diff --git a/src/valid/type.rs b/src/valid/type.rs index f8ceb463c..c0d8a1295 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -566,7 +566,10 @@ impl super::Validator { } Ti::RayQuery => { self.require_type_capability(Capabilities::RAY_QUERY)?; - TypeInfo::new(TypeFlags::DATA | TypeFlags::SIZED, Alignment::ONE) + TypeInfo::new( + TypeFlags::DATA | TypeFlags::CONSTRUCTIBLE | TypeFlags::SIZED, + Alignment::ONE, + ) } Ti::BindingArray { base, size } => { if base >= handle { diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index b164f6955..cbab66026 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1342,6 +1342,23 @@ fn invalid_local_vars() { }) if local_var_name == "not_okay" } + + check_validation! { + " + fn f() { + var x: atomic; + } + ": + Err(naga::valid::ValidationError::Function { + source: naga::valid::FunctionError::LocalVariable { + name: local_var_name, + source: naga::valid::LocalVariableError::InvalidType(_), + .. + }, + .. + }) + if local_var_name == "x" + } } #[test] From 3c7dbc4016b84a35c69b30305b12abaeefc21fd9 Mon Sep 17 00:00:00 2001 From: Nicolas Silva Date: Fri, 6 Oct 2023 10:00:31 +0200 Subject: [PATCH 2124/2212] Add StorageFormat::Bgra8Unorm --- src/back/glsl/mod.rs | 16 +++++++++++----- src/back/hlsl/conv.rs | 4 +++- src/back/spv/image.rs | 15 +++++++++++++++ src/back/spv/instructions.rs | 1 + src/back/wgsl/writer.rs | 1 + src/front/wgsl/mod.rs | 1 + src/lib.rs | 1 + src/proc/mod.rs | 1 + 8 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index ddef6a4c0..86b1aecd0 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -766,7 +766,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "binding = {binding}")?; } if let Some((format, _)) = storage_format_access { - let format_str = glsl_storage_format(format); + let format_str = glsl_storage_format(format)?; let separator = match layout_binding { Some(_) => ",", None => "", @@ -1491,7 +1491,7 @@ impl<'a, W: Write> Writer<'a, W> { .. } = this.module.types[arg.ty].inner { - write!(this.out, "layout({}) ", glsl_storage_format(format))?; + write!(this.out, "layout({}) ", glsl_storage_format(format)?)?; } // write the type @@ -4213,10 +4213,10 @@ const fn glsl_dimension(dim: crate::ImageDimension) -> &'static str { } /// Helper function that returns the glsl storage format string of [`StorageFormat`](crate::StorageFormat) -const fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { +fn glsl_storage_format(format: crate::StorageFormat) -> Result<&'static str, Error> { use crate::StorageFormat as Sf; - match format { + Ok(match format { Sf::R8Unorm => "r8", Sf::R8Snorm => "r8_snorm", Sf::R8Uint => "r8ui", @@ -4256,7 +4256,13 @@ const fn glsl_storage_format(format: crate::StorageFormat) -> &'static str { Sf::Rg16Snorm => "rg16_snorm", Sf::Rgba16Unorm => "rgba16", Sf::Rgba16Snorm => "rgba16_snorm", - } + + Sf::Bgra8Unorm => { + return Err(Error::Custom( + "Support format BGRA8 is not implemented".into(), + )) + } + }) } fn is_value_init_supported(module: &crate::Module, ty: Handle) -> bool { diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs index dcbda3d74..19bde6926 100644 --- a/src/back/hlsl/conv.rs +++ b/src/back/hlsl/conv.rs @@ -122,7 +122,9 @@ impl crate::StorageFormat { Self::Rg11b10Float => "float3", Self::Rgba16Float | Self::R32Float | Self::Rg32Float | Self::Rgba32Float => "float4", - Self::Rgba8Unorm | Self::Rgba16Unorm | Self::Rgb10a2Unorm => "unorm float4", + Self::Rgba8Unorm | Self::Bgra8Unorm | Self::Rgba16Unorm | Self::Rgb10a2Unorm => { + "unorm float4" + } Self::Rgba8Snorm | Self::Rgba16Snorm => "snorm float4", Self::Rgba8Uint diff --git a/src/back/spv/image.rs b/src/back/spv/image.rs index b4d2fb9e1..1630dc0dd 100644 --- a/src/back/spv/image.rs +++ b/src/back/spv/image.rs @@ -1170,6 +1170,21 @@ impl<'w> BlockContext<'w> { let write = Store { image_id, value_id }; + match *self.fun_info[image].ty.inner_with(&self.ir_module.types) { + crate::TypeInner::Image { + class: + crate::ImageClass::Storage { + format: crate::StorageFormat::Bgra8Unorm, + .. + }, + .. + } => self.writer.require_any( + "Bgra8Unorm storage write", + &[spirv::Capability::StorageImageWriteWithoutFormat], + )?, + _ => {} + } + match self.writer.bounds_check_policies.image_store { crate::proc::BoundsCheckPolicy::Restrict => { let (coords, _, _) = diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs index 86b3fd865..b963793ad 100644 --- a/src/back/spv/instructions.rs +++ b/src/back/spv/instructions.rs @@ -1064,6 +1064,7 @@ impl From for spirv::ImageFormat { Sf::Rgba8Snorm => Self::Rgba8Snorm, Sf::Rgba8Uint => Self::Rgba8ui, Sf::Rgba8Sint => Self::Rgba8i, + Sf::Bgra8Unorm => Self::Unknown, Sf::Rgb10a2Uint => Self::Rgb10a2ui, Sf::Rgb10a2Unorm => Self::Rgb10A2, Sf::Rg11b10Float => Self::R11fG11fB10f, diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 8f6b4074a..e41460061 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1829,6 +1829,7 @@ const fn storage_format_str(format: crate::StorageFormat) -> &'static str { Sf::Rgba8Snorm => "rgba8snorm", Sf::Rgba8Uint => "rgba8uint", Sf::Rgba8Sint => "rgba8sint", + Sf::Bgra8Unorm => "bgra8unorm", Sf::Rgb10a2Uint => "rgb10a2uint", Sf::Rgb10a2Unorm => "rgb10a2unorm", Sf::Rg11b10Float => "rg11b10float", diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 6982e850b..56834d5d9 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -71,6 +71,7 @@ impl crate::StorageFormat { Sf::Rgba8Snorm => "rgba8snorm", Sf::Rgba8Uint => "rgba8uint", Sf::Rgba8Sint => "rgba8sint", + Sf::Bgra8Unorm => "bgra8unorm", Sf::Rgb10a2Uint => "rgb10a2uint", Sf::Rgb10a2Unorm => "rgb10a2unorm", Sf::Rg11b10Float => "rg11b10float", diff --git a/src/lib.rs b/src/lib.rs index 563325a7d..93ecaa1ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -599,6 +599,7 @@ pub enum StorageFormat { Rgba8Snorm, Rgba8Uint, Rgba8Sint, + Bgra8Unorm, // Packed 32-bit formats Rgb10a2Uint, diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 90fd9500a..0d12126ac 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -39,6 +39,7 @@ impl From for super::ScalarKind { Sf::Rgba8Snorm => Sk::Float, Sf::Rgba8Uint => Sk::Uint, Sf::Rgba8Sint => Sk::Sint, + Sf::Bgra8Unorm => Sk::Float, Sf::Rgb10a2Uint => Sk::Uint, Sf::Rgb10a2Unorm => Sk::Float, Sf::Rg11b10Float => Sk::Float, From 33b75a27d93c6574b11b4dd4492b85b5783d6c52 Mon Sep 17 00:00:00 2001 From: Nicolas Silva Date: Tue, 10 Oct 2023 18:13:19 +0200 Subject: [PATCH 2125/2212] [wgsl-in] Parse the bgra8unorm storage format (#2550) --- src/front/wgsl/parse/conv.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/wgsl/parse/conv.rs b/src/front/wgsl/parse/conv.rs index fea60dc09..51977173d 100644 --- a/src/front/wgsl/parse/conv.rs +++ b/src/front/wgsl/parse/conv.rs @@ -98,6 +98,7 @@ pub fn map_storage_format(word: &str, span: Span) -> Result Sf::Rgba32Uint, "rgba32sint" => Sf::Rgba32Sint, "rgba32float" => Sf::Rgba32Float, + "bgra8unorm" => Sf::Bgra8Unorm, _ => return Err(Error::UnknownStorageFormat(span)), }) } From c5d884fca8b56ac957530c7184ee050cc5fd67ec Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Wed, 11 Oct 2023 13:54:15 -0400 Subject: [PATCH 2126/2212] Add codeowners file --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..312b7e1bf --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @gfx-rs/naga From a730236b68f0e73f3bafbba767134751e9ea830f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 19 Apr 2023 14:55:07 +0200 Subject: [PATCH 2127/2212] [wgsl-in] eagerly evaluate const-expressions [wgsl-in] support const-expressions in attributes allow `Splat` as an evaluated const-expression type --- src/back/glsl/mod.rs | 47 +- src/back/hlsl/writer.rs | 31 +- src/back/msl/writer.rs | 90 +- src/back/spv/writer.rs | 21 +- src/front/glsl/builtins.rs | 2 +- src/front/glsl/context.rs | 2 +- src/front/glsl/error.rs | 8 +- src/front/glsl/mod.rs | 1 - src/front/glsl/parser.rs | 2 +- src/front/glsl/parser/declarations.rs | 2 +- src/front/glsl/parser/functions.rs | 7 +- src/front/glsl/types.rs | 21 +- src/front/mod.rs | 3 + src/front/wgsl/error.rs | 55 +- src/front/wgsl/lower/construction.rs | 8 +- src/front/wgsl/lower/mod.rs | 302 +++-- src/front/wgsl/parse/ast.rs | 43 +- src/front/wgsl/parse/mod.rs | 127 +- src/front/wgsl/tests.rs | 10 +- .../constant_evaluator.rs} | 917 ++++++++----- src/proc/mod.rs | 47 +- src/valid/expression.rs | 6 + tests/out/glsl/constructors.main.Compute.glsl | 7 +- .../cubeArrayShadow.fragment.Fragment.glsl | 4 +- .../glsl/image.texture_sample.Fragment.glsl | 136 +- tests/out/glsl/operators.main.Compute.glsl | 112 +- tests/out/hlsl/constructors.hlsl | 7 +- tests/out/hlsl/image.hlsl | 140 +- tests/out/hlsl/operators.hlsl | 112 +- tests/out/ir/access.ron | 11 + tests/out/ir/collatz.ron | 6 +- tests/out/msl/constructors.msl | 7 +- tests/out/msl/image.msl | 136 +- tests/out/msl/operators.msl | 112 +- tests/out/spv/constructors.spvasm | 9 +- tests/out/spv/debug-symbol-terrain.spvasm | 1157 ++++++++--------- tests/out/spv/image.spvasm | 569 ++++---- tests/out/spv/operators.spvasm | 1026 +++++++-------- tests/out/wgsl/constructors.wgsl | 7 +- tests/out/wgsl/image.wgsl | 136 +- tests/out/wgsl/module-scope.wgsl | 3 +- tests/out/wgsl/operators.wgsl | 112 +- tests/out/wgsl/type-alias.wgsl | 2 +- tests/wgsl-errors.rs | 124 +- 44 files changed, 2917 insertions(+), 2770 deletions(-) rename src/{front/glsl/constants.rs => proc/constant_evaluator.rs} (52%) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 86b1aecd0..12d358bb8 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1709,7 +1709,7 @@ impl<'a, W: Write> Writer<'a, W> { arg: Handle, arg1: Handle, size: usize, - ctx: &back::FunctionCtx<'_>, + ctx: &back::FunctionCtx, ) -> BackendResult { // Write parantheses around the dot product expression to prevent operators // with different precedences from applying earlier. @@ -2254,9 +2254,12 @@ impl<'a, W: Write> Writer<'a, W> { /// [`Expression`]: crate::Expression /// [`Module`]: crate::Module fn write_const_expr(&mut self, expr: Handle) -> BackendResult { - self.write_possibly_const_expr(expr, &self.module.const_expressions, |writer, expr| { - writer.write_const_expr(expr) - }) + self.write_possibly_const_expr( + expr, + &self.module.const_expressions, + |expr| &self.info[expr], + |writer, expr| writer.write_const_expr(expr), + ) } /// Write [`Expression`] variants that can occur in both runtime and const expressions. @@ -2277,13 +2280,15 @@ impl<'a, W: Write> Writer<'a, W> { /// Adds no newlines or leading/trailing whitespace /// /// [`Expression`]: crate::Expression - fn write_possibly_const_expr( - &mut self, + fn write_possibly_const_expr<'w, I, E>( + &'w mut self, expr: Handle, expressions: &crate::Arena, + info: I, write_expression: E, ) -> BackendResult where + I: Fn(Handle) -> &'w proc::TypeResolution, E: Fn(&mut Self, Handle) -> BackendResult, { use crate::Expression; @@ -2331,6 +2336,14 @@ impl<'a, W: Write> Writer<'a, W> { } write!(self.out, ")")? } + // `Splat` needs to actually write down a vector, it's not always inferred in GLSL. + Expression::Splat { size: _, value } => { + let resolved = info(expr).inner_with(&self.module.types); + self.write_value_type(resolved)?; + write!(self.out, "(")?; + write_expression(self, value)?; + write!(self.out, ")")? + } _ => unreachable!(), } @@ -2344,7 +2357,7 @@ impl<'a, W: Write> Writer<'a, W> { fn write_expr( &mut self, expr: Handle, - ctx: &back::FunctionCtx<'_>, + ctx: &back::FunctionCtx, ) -> BackendResult { use crate::Expression; @@ -2357,10 +2370,14 @@ impl<'a, W: Write> Writer<'a, W> { Expression::Literal(_) | Expression::Constant(_) | Expression::ZeroValue(_) - | Expression::Compose { .. } => { - self.write_possibly_const_expr(expr, ctx.expressions, |writer, expr| { - writer.write_expr(expr, ctx) - })?; + | Expression::Compose { .. } + | Expression::Splat { .. } => { + self.write_possibly_const_expr( + expr, + ctx.expressions, + |expr| &ctx.info[expr].ty, + |writer, expr| writer.write_expr(expr, ctx), + )?; } // `Access` is applied to arrays, vectors and matrices and is written as indexing Expression::Access { base, index } => { @@ -2407,14 +2424,6 @@ impl<'a, W: Write> Writer<'a, W> { ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))), } } - // `Splat` needs to actually write down a vector, it's not always inferred in GLSL. - Expression::Splat { size: _, value } => { - let resolved = ctx.info[expr].ty.inner_with(&self.module.types); - self.write_value_type(resolved)?; - write!(self.out, "(")?; - self.write_expr(value, ctx)?; - write!(self.out, ")")? - } // `Swizzle` adds a few letters behind the dot. Expression::Swizzle { size, diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index e9809bd2d..a2e0d2fef 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2078,6 +2078,19 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } write!(self.out, ")")?; } + Expression::Splat { size, value } => { + // hlsl is not supported one value constructor + // if we write, for example, int4(0), dxc returns error: + // error: too few elements in vector initialization (expected 4 elements, have 1) + let number_of_components = match size { + crate::VectorSize::Bi => "xx", + crate::VectorSize::Tri => "xxx", + crate::VectorSize::Quad => "xxxx", + }; + write!(self.out, "(")?; + write_expression(self, value)?; + write!(self.out, ").{number_of_components}")? + } _ => unreachable!(), } @@ -2135,7 +2148,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Expression::Literal(_) | Expression::Constant(_) | Expression::ZeroValue(_) - | Expression::Compose { .. } => { + | Expression::Compose { .. } + | Expression::Splat { .. } => { self.write_possibly_const_expression( module, expr, @@ -2423,7 +2437,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if let Some(offset) = offset { write!(self.out, ", ")?; + write!(self.out, "int2(")?; // work around https://github.com/microsoft/DirectXShaderCompiler/issues/5082#issuecomment-1540147807 self.write_const_expression(module, offset)?; + write!(self.out, ")")?; } write!(self.out, ")")?; @@ -3154,19 +3170,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, argument, func_ctx)?; write!(self.out, ")")? } - Expression::Splat { size, value } => { - // hlsl is not supported one value constructor - // if we write, for example, int4(0), dxc returns error: - // error: too few elements in vector initialization (expected 4 elements, have 1) - let number_of_components = match size { - crate::VectorSize::Bi => "xx", - crate::VectorSize::Tri => "xxx", - crate::VectorSize::Quad => "xxxx", - }; - write!(self.out, "(")?; - self.write_expr(module, value, func_ctx)?; - write!(self.out, ").{number_of_components}")? - } Expression::Select { condition, accept, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 77231a286..fee917b03 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -501,6 +501,7 @@ struct ExpressionContext<'a> { origin: FunctionOrigin, info: &'a valid::FunctionInfo, module: &'a crate::Module, + mod_info: &'a valid::ModuleInfo, pipeline_options: &'a PipelineOptions, policies: index::BoundsCheckPolicies, @@ -571,7 +572,6 @@ impl<'a> ExpressionContext<'a> { struct StatementContext<'a> { expression: ExpressionContext<'a>, - mod_info: &'a valid::ModuleInfo, result_struct: Option<&'a str>, } @@ -604,25 +604,26 @@ impl Writer { parameters: impl Iterator>, context: &ExpressionContext, ) -> BackendResult { - self.put_call_parameters_impl(parameters, |writer, expr| { + self.put_call_parameters_impl(parameters, context, |writer, context, expr| { writer.put_expression(expr, context, true) }) } - fn put_call_parameters_impl( + fn put_call_parameters_impl( &mut self, parameters: impl Iterator>, + ctx: &C, put_expression: E, ) -> BackendResult where - E: Fn(&mut Self, Handle) -> BackendResult, + E: Fn(&mut Self, &C, Handle) -> BackendResult, { write!(self.out, "(")?; for (i, handle) in parameters.enumerate() { if i != 0 { write!(self.out, ", ")?; } - put_expression(self, handle)?; + put_expression(self, ctx, handle)?; } write!(self.out, ")")?; Ok(()) @@ -1213,24 +1214,33 @@ impl Writer { &mut self, expr_handle: Handle, module: &crate::Module, + mod_info: &valid::ModuleInfo, ) -> BackendResult { self.put_possibly_const_expression( expr_handle, &module.const_expressions, module, - |writer, expr| writer.put_const_expression(expr, module), + mod_info, + &(module, mod_info), + |&(_, mod_info), expr| &mod_info[expr], + |writer, &(module, _), expr| writer.put_const_expression(expr, module, mod_info), ) } - fn put_possibly_const_expression( + #[allow(clippy::too_many_arguments)] + fn put_possibly_const_expression( &mut self, expr_handle: Handle, expressions: &crate::Arena, module: &crate::Module, + mod_info: &valid::ModuleInfo, + ctx: &C, + get_expr_ty: I, put_expression: E, ) -> BackendResult where - E: Fn(&mut Self, Handle) -> BackendResult, + I: Fn(&C, Handle) -> &TypeResolution, + E: Fn(&mut Self, &C, Handle) -> BackendResult, { match expressions[expr_handle] { crate::Expression::Literal(literal) => match literal { @@ -1263,7 +1273,7 @@ impl Writer { if constant.name.is_some() { write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?; } else { - self.put_const_expression(constant.init, module)?; + self.put_const_expression(constant.init, module, mod_info)?; } } crate::Expression::ZeroValue(ty) => { @@ -1291,7 +1301,11 @@ impl Writer { crate::TypeInner::Scalar { .. } | crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { - self.put_call_parameters_impl(components.iter().copied(), put_expression)?; + self.put_call_parameters_impl( + components.iter().copied(), + ctx, + put_expression, + )?; } crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => { write!(self.out, " {{")?; @@ -1303,13 +1317,23 @@ impl Writer { if self.struct_member_pads.contains(&(ty, index as u32)) { write!(self.out, "{{}}, ")?; } - put_expression(self, component)?; + put_expression(self, ctx, component)?; } write!(self.out, "}}")?; } _ => return Err(Error::UnsupportedCompose(ty)), } } + crate::Expression::Splat { size, value } => { + let scalar_kind = match *get_expr_ty(ctx, value).inner_with(&module.types) { + crate::TypeInner::Scalar { kind, .. } => kind, + _ => return Err(Error::Validation), + }; + put_numeric_type(&mut self.out, scalar_kind, &[size])?; + write!(self.out, "(")?; + put_expression(self, ctx, value)?; + write!(self.out, ")")?; + } _ => unreachable!(), } @@ -1350,12 +1374,16 @@ impl Writer { crate::Expression::Literal(_) | crate::Expression::Constant(_) | crate::Expression::ZeroValue(_) - | crate::Expression::Compose { .. } => { + | crate::Expression::Compose { .. } + | crate::Expression::Splat { .. } => { self.put_possibly_const_expression( expr_handle, &context.function.expressions, context.module, - |writer, expr| writer.put_expression(expr, context, true), + context.mod_info, + context, + |context, expr: Handle| &context.info[expr].ty, + |writer, context, expr| writer.put_expression(expr, context, true), )?; } crate::Expression::Access { base, .. } @@ -1385,16 +1413,6 @@ impl Writer { self.put_access_chain(expr_handle, policy, context)?; } } - crate::Expression::Splat { size, value } => { - let scalar_kind = match *context.resolve_type(value) { - crate::TypeInner::Scalar { kind, .. } => kind, - _ => return Err(Error::Validation), - }; - put_numeric_type(&mut self.out, scalar_kind, &[size])?; - write!(self.out, "(")?; - self.put_expression(value, context, true)?; - write!(self.out, ")")?; - } crate::Expression::Swizzle { size, vector, @@ -1469,7 +1487,7 @@ impl Writer { if let Some(offset) = offset { write!(self.out, ", ")?; - self.put_const_expression(offset, context.module)?; + self.put_const_expression(offset, context.module, context.mod_info)?; } match gather { @@ -2792,7 +2810,7 @@ impl Writer { } // follow-up with any global resources used let mut separate = !arguments.is_empty(); - let fun_info = &context.mod_info[function]; + let fun_info = &context.expression.mod_info[function]; let mut supports_array_length = false; for (handle, var) in context.expression.module.global_variables.iter() { if fun_info[handle].is_empty() { @@ -3131,7 +3149,7 @@ impl Writer { }; self.write_type_defs(module)?; - self.write_global_constants(module)?; + self.write_global_constants(module, info)?; self.write_functions(module, info, options, pipeline_options) } @@ -3338,7 +3356,11 @@ impl Writer { } /// Writes all named constants - fn write_global_constants(&mut self, module: &crate::Module) -> BackendResult { + fn write_global_constants( + &mut self, + module: &crate::Module, + mod_info: &valid::ModuleInfo, + ) -> BackendResult { let constants = module.constants.iter().filter(|&(_, c)| c.name.is_some()); for (handle, constant) in constants { @@ -3352,7 +3374,7 @@ impl Writer { }; let name = &self.names[&NameKey::Constant(handle)]; write!(self.out, "constant {ty_name} {name} = ")?; - self.put_const_expression(constant.init, module)?; + self.put_const_expression(constant.init, module, mod_info)?; writeln!(self.out, ";")?; } @@ -3549,7 +3571,7 @@ impl Writer { match local.init { Some(value) => { write!(self.out, " = ")?; - self.put_const_expression(value, module)?; + self.put_const_expression(value, module, mod_info)?; } None => { write!(self.out, " = {{}}")?; @@ -3569,9 +3591,9 @@ impl Writer { policies: options.bounds_check_policies, guarded_indices, module, + mod_info, pipeline_options, }, - mod_info, result_struct: None, }; self.named_expressions.clear(); @@ -3958,7 +3980,7 @@ impl Writer { } if let Some(value) = var.init { write!(self.out, " = ")?; - self.put_const_expression(value, module)?; + self.put_const_expression(value, module, mod_info)?; } writeln!(self.out)?; } @@ -4014,7 +4036,7 @@ impl Writer { match var.init { Some(value) => { write!(self.out, " = ")?; - self.put_const_expression(value, module)?; + self.put_const_expression(value, module, mod_info)?; writeln!(self.out, ";")?; } None => { @@ -4106,7 +4128,7 @@ impl Writer { match local.init { Some(value) => { write!(self.out, " = ")?; - self.put_const_expression(value, module)?; + self.put_const_expression(value, module, mod_info)?; } None => { write!(self.out, " = {{}}")?; @@ -4126,9 +4148,9 @@ impl Writer { policies: options.bounds_check_policies, guarded_indices, module, + mod_info, pipeline_options, }, - mod_info, result_struct: Some(&stage_out_name), }; self.named_expressions.clear(); diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 8cad9c4d2..4be19cce6 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -198,11 +198,15 @@ impl Writer { } } - pub(super) fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Word { - let lookup_ty = match *tr { + pub(super) fn get_expression_lookup_type(&mut self, tr: &TypeResolution) -> LookupType { + match *tr { TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle), TypeResolution::Value(ref inner) => LookupType::Local(make_local(inner).unwrap()), - }; + } + } + + pub(super) fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Word { + let lookup_ty = self.get_expression_lookup_type(tr); self.get_type_id(lookup_ty) } @@ -1242,6 +1246,7 @@ impl Writer { &mut self, handle: Handle, ir_module: &crate::Module, + mod_info: &ModuleInfo, ) -> Result { let id = match ir_module.const_expressions[handle] { crate::Expression::Literal(literal) => self.get_constant_scalar(literal), @@ -1260,6 +1265,14 @@ impl Writer { .collect(); self.get_constant_composite(LookupType::Handle(ty), component_ids.as_slice()) } + crate::Expression::Splat { size, value } => { + let value_id = self.constant_ids[value.index()]; + let component_ids = &[value_id; 4][..size as usize]; + + let ty = self.get_expression_lookup_type(&mod_info[handle]); + + self.get_constant_composite(ty, component_ids) + } _ => unreachable!(), }; @@ -1878,7 +1891,7 @@ impl Writer { self.constant_ids .resize(ir_module.const_expressions.len(), 0); for (handle, _) in ir_module.const_expressions.iter() { - self.write_constant_expr(handle, ir_module)?; + self.write_constant_expr(handle, ir_module, mod_info)?; } debug_assert!(self.constant_ids.iter().all(|&id| id != 0)); diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 811be65cc..ff386e2e1 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1795,7 +1795,7 @@ impl MacroCall { true => { let offset_arg = args[num_args]; num_args += 1; - match ctx.solve_constant(offset_arg, meta) { + match ctx.eval_constant(offset_arg, meta) { Ok(v) => Some(v), Err(e) => { frontend.errors.push(e); diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 407619c3d..ffdc2bd97 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -519,7 +519,7 @@ impl<'a> Context<'a> { // Don't try to generate `AccessIndex` if in a LHS position, since it // wouldn't produce a pointer. ExprPos::Lhs => None, - _ => self.solve_constant(index, index_meta).ok(), + _ => self.eval_constant(index, index_meta).ok(), }; let base = self diff --git a/src/front/glsl/error.rs b/src/front/glsl/error.rs index 46b3aecd0..d6e358668 100644 --- a/src/front/glsl/error.rs +++ b/src/front/glsl/error.rs @@ -1,5 +1,5 @@ -use super::{constants::ConstantSolvingError, token::TokenValue}; -use crate::Span; +use super::token::TokenValue; +use crate::{proc::ConstantEvaluatorError, Span}; use pp_rs::token::PreprocessorError; use std::borrow::Cow; use thiserror::Error; @@ -116,8 +116,8 @@ pub enum ErrorKind { InternalError(&'static str), } -impl From for ErrorKind { - fn from(err: ConstantSolvingError) -> Self { +impl From for ErrorKind { + fn from(err: ConstantEvaluatorError) -> Self { ErrorKind::SemanticError(err.to_string().into()) } } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index f8f554bf2..4ce0dc478 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -22,7 +22,6 @@ use parser::ParsingContext; mod ast; mod builtins; -mod constants; mod context; mod error; mod functions; diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 1a3b5a908..075dce17e 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -226,7 +226,7 @@ impl<'source> ParsingContext<'source> { let expr = self.parse_conditional(frontend, &mut ctx, &mut stmt_ctx, None)?; let (root, meta) = ctx.lower_expect(stmt_ctx, frontend, expr, ExprPos::Rhs)?; - Ok((ctx.solve_constant(root, meta)?, meta)) + Ok((ctx.eval_constant(root, meta)?, meta)) } } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 2abd67672..75e18ea3b 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -241,7 +241,7 @@ impl<'source> ParsingContext<'source> { let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; let maybe_const_expr = if ctx.external { if let Some((root, meta)) = init { - match ctx.ctx.solve_constant(root, meta) { + match ctx.ctx.eval_constant(root, meta) { Ok(res) => Some(res), // If the declaration is external (global scope) and is constant qualified // then the initializer must be a constant expression diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 200afc78f..91b778787 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -187,11 +187,8 @@ impl<'source> ParsingContext<'source> { TokenValue::Case => { self.bump(frontend)?; - let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(frontend, ctx, &mut stmt)?; - let (root, meta) = - ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?; - let const_expr = ctx.solve_constant(root, meta)?; + let (const_expr, meta) = + self.parse_constant_expression(frontend, ctx.module)?; match ctx.module.const_expressions[const_expr] { Expression::Literal(Literal::I32(value)) => match uint { diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index a91a0a9f2..a8bb047e4 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,4 +1,4 @@ -use super::{constants::ConstantSolver, context::Context, Error, ErrorKind, Result, Span}; +use super::{context::Context, Error, ErrorKind, Result, Span}; use crate::{ proc::ResolveContext, Bytes, Expression, Handle, ImageClass, ImageDimension, ScalarKind, Type, TypeInner, VectorSize, @@ -305,19 +305,28 @@ impl Context<'_> { }) } - pub(crate) fn solve_constant( + pub(crate) fn eval_constant( &mut self, root: Handle, meta: Span, ) -> Result> { - let mut solver = ConstantSolver { + let mut solver = crate::proc::ConstantEvaluator { types: &mut self.module.types, - expressions: &self.expressions, + expressions: &mut self.module.const_expressions, constants: &mut self.module.constants, - const_expressions: &mut self.module.const_expressions, + const_expressions: Some(&self.expressions), + append: None::< + Box< + dyn FnMut( + &mut crate::Arena, + Expression, + Span, + ) -> Handle, + >, + >, }; - solver.solve(root).map_err(|e| Error { + solver.eval(root).map_err(|e| Error { kind: e.into(), meta, }) diff --git a/src/front/mod.rs b/src/front/mod.rs index 1f16ff637..faebde4e2 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -34,6 +34,9 @@ impl Emitter { } self.start_len = Some(arena.len()); } + const fn is_running(&self) -> bool { + self.start_len.is_some() + } #[must_use] fn finish( &mut self, diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index f7bed6cdf..93fff0490 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -1,5 +1,5 @@ use crate::front::wgsl::parse::lexer::Token; -use crate::proc::{Alignment, ResolveError}; +use crate::proc::{Alignment, ConstantEvaluatorError, ResolveError}; use crate::{SourceLocation, Span}; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::files::SimpleFile; @@ -98,8 +98,6 @@ impl std::error::Error for ParseError { pub enum ExpectedToken<'a> { Token(Token<'a>), Identifier, - Number, - Integer, /// Expected: constant, parenthesized expression, identifier PrimaryExpression, /// Expected: assignment, increment/decrement expression @@ -141,10 +139,6 @@ pub enum Error<'a> { UnexpectedComponents(Span), UnexpectedOperationInConstContext(Span), BadNumber(Span, NumberError), - /// A negative signed integer literal where both signed and unsigned, - /// but only non-negative literals are allowed. - NegativeInt(Span), - BadU32Constant(Span), BadMatrixScalarKind(Span, crate::ScalarKind, u8), BadAccessor(Span), BadTexture(Span), @@ -240,9 +234,11 @@ pub enum Error<'a> { FunctionReturnsVoid(Span), InvalidWorkGroupUniformLoad(Span), Other, - ExpectedArraySize(Span), - NonPositiveArrayLength(Span), + ExpectedConstExprConcreteIntegerScalar(Span), + ExpectedNonNegative(Span), + ExpectedPositiveArrayLength(Span), MissingWorkgroupSize(Span), + ConstantEvaluatorError(ConstantEvaluatorError, Span), } impl<'a> Error<'a> { @@ -271,8 +267,6 @@ impl<'a> Error<'a> { } } ExpectedToken::Identifier => "identifier".to_string(), - ExpectedToken::Number => "32-bit signed integer literal".to_string(), - ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), ExpectedToken::PrimaryExpression => "expression".to_string(), ExpectedToken::Assignment => "assignment or increment/decrement".to_string(), ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), @@ -306,22 +300,6 @@ impl<'a> Error<'a> { labels: vec![(bad_span, err.to_string().into())], notes: vec![], }, - Error::NegativeInt(bad_span) => ParseError { - message: format!( - "expected non-negative integer literal, found `{}`", - &source[bad_span], - ), - labels: vec![(bad_span, "expected non-negative integer".into())], - notes: vec![], - }, - Error::BadU32Constant(bad_span) => ParseError { - message: format!( - "expected unsigned integer constant expression, found `{}`", - &source[bad_span], - ), - labels: vec![(bad_span, "expected unsigned integer".into())], - notes: vec![], - }, Error::BadMatrixScalarKind(span, kind, width) => ParseError { message: format!( "matrix scalar type must be floating-point, but found `{}`", @@ -694,15 +672,24 @@ impl<'a> Error<'a> { labels: vec![], notes: vec![], }, - Error::ExpectedArraySize(span) => ParseError { - message: "array element count must resolve to an integer scalar (u32 or i32)" - .to_string(), - labels: vec![(span, "must resolve to u32/i32".into())], + Error::ExpectedConstExprConcreteIntegerScalar(span) => ParseError { + message: "must be a const-expression that resolves to a concrete integer scalar (u32 or i32)".to_string(), + labels: vec![(span, "must resolve to u32 or i32".into())], notes: vec![], }, - Error::NonPositiveArrayLength(span) => ParseError { - message: "array element count must be greater than zero".to_string(), - labels: vec![(span, "must be greater than zero".into())], + Error::ExpectedNonNegative(span) => ParseError { + message: "must be non-negative (>= 0)".to_string(), + labels: vec![(span, "must be non-negative".into())], + notes: vec![], + }, + Error::ExpectedPositiveArrayLength(span) => ParseError { + message: "array element count must be positive (> 0)".to_string(), + labels: vec![(span, "must be positive".into())], + notes: vec![], + }, + Error::ConstantEvaluatorError(ref e, span) => ParseError { + message: e.to_string(), + labels: vec![(span, "see msg".into())], notes: vec![], }, Error::MissingWorkgroupSize(span) => ParseError { diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 3b4830b05..970f63dca 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -197,7 +197,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // Empty constructor (Components::None, dst_ty) => match dst_ty { ConcreteConstructor::Type(ty, _) => { - return Ok(ctx.interrupt_emitter(crate::Expression::ZeroValue(ty), span)) + return ctx.append_expression(crate::Expression::ZeroValue(ty), span) } _ => return Err(Error::TypeNotInferrable(ty_span)), }, @@ -408,7 +408,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Default::default(), ) }) - .collect(); + .collect::, _>>()?; let ty = ctx.ensure_type_exists(crate::TypeInner::Matrix { columns, @@ -523,7 +523,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { _ => return Err(Error::TypeNotConstructible(ty_span)), }; - let expr = ctx.append_expression(expr, span); + let expr = ctx.append_expression(expr, span)?; Ok(expr) } @@ -585,7 +585,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let size = match size { ast::ArraySize::Constant(expr) => { let const_expr = self.expression(expr, ctx.as_const())?; - crate::ArraySize::Constant(ctx.array_length(const_expr)?) + crate::ArraySize::Constant(ctx.as_const().array_length(const_expr)?) } ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, }; diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 56d870970..3a78f0f2b 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -5,7 +5,9 @@ use crate::front::wgsl::index::Index; use crate::front::wgsl::parse::number::Number; use crate::front::wgsl::parse::{ast, conv}; use crate::front::{Emitter, Typifier}; -use crate::proc::{ensure_block_returns, Alignment, Layouter, ResolveContext, TypeResolution}; +use crate::proc::{ + ensure_block_returns, Alignment, ConstantEvaluator, Layouter, ResolveContext, TypeResolution, +}; use crate::{Arena, FastHashMap, FastIndexMap, Handle, Span}; mod construction; @@ -327,17 +329,66 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { &mut self, expr: crate::Expression, span: Span, - ) -> Handle { + ) -> Result, Error<'source>> { match self.expr_type { - ExpressionContextType::Runtime(ref mut ctx) => ctx.naga_expressions.append(expr, span), - ExpressionContextType::Constant => self.module.const_expressions.append(expr, span), + ExpressionContextType::Runtime(ref mut rctx) => { + let mut eval = ConstantEvaluator { + types: &mut self.module.types, + constants: &self.module.constants, + expressions: rctx.naga_expressions, + const_expressions: Some(&self.module.const_expressions), + append: Some( + |arena: &mut Arena, expr: crate::Expression, span| { + let is_running = rctx.emitter.is_running(); + let needs_pre_emit = expr.needs_pre_emit(); + if is_running && needs_pre_emit { + rctx.block.extend(rctx.emitter.finish(arena)); + } + let h = arena.append(expr, span); + if is_running && needs_pre_emit { + rctx.emitter.start(arena); + } + h + }, + ), + }; + + match eval.try_eval_and_append(&expr, span) { + Ok(expr) => Ok(expr), + Err(_) => Ok(rctx.naga_expressions.append(expr, span)), + } + } + ExpressionContextType::Constant => { + let mut eval = ConstantEvaluator { + types: &mut self.module.types, + constants: &self.module.constants, + expressions: &mut self.module.const_expressions, + const_expressions: None, + append: None::< + Box< + dyn FnMut( + &mut Arena, + crate::Expression, + Span, + ) -> Handle, + >, + >, + }; + + eval.try_eval_and_append(&expr, span) + .map_err(|e| Error::ConstantEvaluatorError(e, span)) + } } } - fn get_expression(&self, handle: Handle) -> &crate::Expression { + fn const_access(&self, handle: Handle) -> Option { match self.expr_type { - ExpressionContextType::Runtime(ref ctx) => &ctx.naga_expressions[handle], - ExpressionContextType::Constant => &self.module.const_expressions[handle], + ExpressionContextType::Runtime(ref ctx) => self + .module + .to_ctx() + .eval_expr_to_u32_from(handle, ctx.naga_expressions) + .ok(), + ExpressionContextType::Constant => self.module.to_ctx().eval_expr_to_u32(handle).ok(), } } @@ -366,34 +417,52 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { } fn array_length( - &self, + &mut self, const_expr: Handle, ) -> Result> { - let span = self.module.const_expressions.get_span(const_expr); - let len = self - .module - .to_ctx() - .eval_expr_to_u32(const_expr) - .map_err(|err| match err { - crate::proc::U32EvalError::NonConst => Error::ExpectedArraySize(span), - crate::proc::U32EvalError::Negative => Error::NonPositiveArrayLength(span), - })?; - NonZeroU32::new(len).ok_or(Error::NonPositiveArrayLength(span)) + match self.expr_type { + ExpressionContextType::Runtime(_) => { + unreachable!() + } + ExpressionContextType::Constant => { + let span = self.module.const_expressions.get_span(const_expr); + let len = + self.module + .to_ctx() + .eval_expr_to_u32(const_expr) + .map_err(|err| match err { + crate::proc::U32EvalError::NonConst => { + Error::ExpectedConstExprConcreteIntegerScalar(span) + } + crate::proc::U32EvalError::Negative => { + Error::ExpectedPositiveArrayLength(span) + } + })?; + NonZeroU32::new(len).ok_or(Error::ExpectedPositiveArrayLength(span)) + } + } } fn gather_component( - &self, + &mut self, expr: Handle, gather_span: Span, ) -> Result> { match self.expr_type { - ExpressionContextType::Runtime(ref ctx) => { - let expr_span = ctx.naga_expressions.get_span(expr); + ExpressionContextType::Runtime(ref rctx) => { + let expr_span = rctx.naga_expressions.get_span(expr); let index = self .module .to_ctx() - .eval_expr_to_u32_from(expr, ctx.naga_expressions) - .map_err(|_| Error::InvalidGatherComponent(expr_span))?; + .eval_expr_to_u32_from(expr, rctx.naga_expressions) + .map_err(|err| match err { + crate::proc::U32EvalError::NonConst => { + Error::ExpectedConstExprConcreteIntegerScalar(expr_span) + } + crate::proc::U32EvalError::Negative => { + Error::ExpectedNonNegative(expr_span) + } + })?; crate::SwizzleComponent::XYZW .get(index as usize) .copied() @@ -543,13 +612,13 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { value: *right, }, self.get_expression_span(*right), - ); + )?; } (&crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, .. }) => { *left = self.append_expression( crate::Expression::Splat { size, value: *left }, self.get_expression_span(*left), - ); + )?; } _ => {} } @@ -566,7 +635,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { &mut self, expression: crate::Expression, span: Span, - ) -> Handle { + ) -> Result, Error<'source>> { match self.expr_type { ExpressionContextType::Runtime(ref mut rctx) => { rctx.block @@ -588,7 +657,10 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { /// /// If `expr` is has type `ref`, perform a load to produce a value of type /// `T`. Otherwise, return `expr` unchanged. - fn apply_load_rule(&mut self, expr: TypedExpression) -> Handle { + fn apply_load_rule( + &mut self, + expr: TypedExpression, + ) -> Result, Error<'source>> { if expr.is_reference { let load = crate::Expression::Load { pointer: expr.handle, @@ -596,7 +668,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { let span = self.get_expression_span(expr.handle); self.append_expression(load, span) } else { - expr.handle + Ok(expr.handle) } } @@ -831,11 +903,20 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .map(|init| self.expression(init, ctx.as_const())) .transpose()?; + let binding = if let Some(ref binding) = v.binding { + Some(crate::ResourceBinding { + group: self.const_u32(binding.group, ctx.as_const())?.0, + binding: self.const_u32(binding.binding, ctx.as_const())?.0, + }) + } else { + None + }; + let handle = ctx.module.global_variables.append( crate::GlobalVariable { name: Some(v.name.name.to_string()), space: v.space, - binding: v.binding.clone(), + binding, ty, init, }, @@ -930,7 +1011,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok(crate::FunctionArgument { name: Some(arg.name.name.to_string()), ty, - binding: self.interpolate_default(&arg.binding, ty, ctx.reborrow()), + binding: self.binding(&arg.binding, ty, ctx.reborrow())?, }) }) .collect::, _>>()?; @@ -939,11 +1020,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .result .as_ref() .map(|res| { - self.resolve_ast_type(res.ty, ctx.reborrow()) - .map(|ty| crate::FunctionResult { - ty, - binding: self.interpolate_default(&res.binding, ty, ctx.reborrow()), - }) + let ty = self.resolve_ast_type(res.ty, ctx.reborrow())?; + Ok(crate::FunctionResult { + ty, + binding: self.binding(&res.binding, ty, ctx.reborrow())?, + }) }) .transpose()?; @@ -980,11 +1061,24 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; if let Some(ref entry) = f.entry_point { + let workgroup_size = if let Some(workgroup_size) = entry.workgroup_size { + // TODO: replace with try_map once stabilized + let mut workgroup_size_out = [1; 3]; + for (i, size) in workgroup_size.into_iter().enumerate() { + if let Some(size_expr) = size { + workgroup_size_out[i] = self.const_u32(size_expr, ctx.as_const())?.0; + } + } + workgroup_size_out + } else { + [0; 3] + }; + ctx.module.entry_points.push(crate::EntryPoint { name: f.name.name.to_string(), stage: entry.stage, early_depth_test: entry.early_depth_test, - workgroup_size: entry.workgroup_size.unwrap_or([0, 0, 0]), + workgroup_size, function, }); Ok(LoweredGlobalDecl::EntryPoint) @@ -1106,9 +1200,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { stmt.span, ); - let handle = ctx - .as_expression(block, &mut emitter) - .interrupt_emitter(crate::Expression::LocalVariable(var), Span::UNDEFINED); + let handle = ctx.as_expression(block, &mut emitter).interrupt_emitter( + crate::Expression::LocalVariable(var), + Span::UNDEFINED, + )?; block.extend(emitter.finish(ctx.naga_expressions)); ctx.local_table.insert( v.handle, @@ -1168,19 +1263,24 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .map(|case| { Ok(crate::SwitchCase { value: match case.value { - ast::SwitchValue::I32(value) if !uint => { - crate::SwitchValue::I32(value) - } - ast::SwitchValue::U32(value) if uint => { - crate::SwitchValue::U32(value) + ast::SwitchValue::Expr(expr) => { + let expr = self.expression(expr, ctx.as_global().as_const())?; + match ctx.module.to_ctx().eval_expr_to_literal(expr) { + Some(crate::Literal::I32(value)) if !uint => { + crate::SwitchValue::I32(value) + } + Some(crate::Literal::U32(value)) if uint => { + crate::SwitchValue::U32(value) + } + _ => { + return Err(Error::InvalidSwitchValue { + uint, + span: ctx.module.const_expressions.get_span(expr), + }); + } + } } ast::SwitchValue::Default => crate::SwitchValue::Default, - _ => { - return Err(Error::InvalidSwitchValue { - uint, - span: case.value_span, - }); - } }, body: self.block(&case.body, ctx.reborrow())?, fall_through: case.fall_through, @@ -1261,7 +1361,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let value = match op { Some(op) => { let mut ctx = ctx.as_expression(block, &mut emitter); - let mut left = ctx.apply_load_rule(expr); + let mut left = ctx.apply_load_rule(expr)?; ctx.binary_op_splat(op, &mut left, &mut value)?; ctx.append_expression( crate::Expression::Binary { @@ -1270,7 +1370,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { right: value, }, stmt.span, - ) + )? } None => value, }; @@ -1319,7 +1419,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let right = - ectx.interrupt_emitter(crate::Expression::Literal(literal), Span::UNDEFINED); + ectx.interrupt_emitter(crate::Expression::Literal(literal), Span::UNDEFINED)?; let rctx = ectx.runtime_expression_ctx(stmt.span)?; let left = rctx.naga_expressions.append( crate::Expression::Load { @@ -1358,7 +1458,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { mut ctx: ExpressionContext<'source, '_, '_>, ) -> Result, Error<'source>> { let expr = self.expression_for_reference(expr, ctx.reborrow())?; - Ok(ctx.apply_load_rule(expr)) + ctx.apply_load_rule(expr) } fn expression_for_reference( @@ -1380,7 +1480,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::Literal::Bool(b) => crate::Literal::Bool(b), }; - let handle = ctx.interrupt_emitter(crate::Expression::Literal(literal), span); + let handle = ctx.interrupt_emitter(crate::Expression::Literal(literal), span)?; return Ok(TypedExpression::non_reference(handle)); } ast::Expression::Ident(ast::IdentExpr::Local(local)) => { @@ -1403,7 +1503,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; - let handle = ctx.interrupt_emitter(expr, span); + let handle = ctx.interrupt_emitter(expr, span)?; Ok(TypedExpression { handle, is_reference, @@ -1483,16 +1583,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { )); } - if let crate::Expression::Literal(lit) = *ctx.get_expression(index) { - let span = ctx.get_expression_span(index); - let index = match lit { - crate::Literal::U32(index) => Ok(index), - crate::Literal::I32(index) => { - u32::try_from(index).map_err(|_| Error::BadU32Constant(span)) - } - _ => Err(Error::BadU32Constant(span)), - }?; - + if let Some(index) = ctx.const_access(index) { ( crate::Expression::AccessIndex { base: expr.handle, @@ -1572,7 +1663,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let vector = ctx.apply_load_rule(TypedExpression { handle, is_reference, - }); + })?; ( crate::Expression::Swizzle { @@ -1625,7 +1716,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; - let handle = ctx.append_expression(expr, span); + let handle = ctx.append_expression(expr, span)?; Ok(TypedExpression { handle, is_reference, @@ -1921,7 +2012,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { _ => return Err(Error::InvalidAtomicOperandType(value_span)), }; - let result = ctx.interrupt_emitter(expression, span); + let result = ctx.interrupt_emitter(expression, span)?; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block.push( crate::Statement::Atomic { @@ -1973,7 +2064,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let result = ctx.interrupt_emitter( crate::Expression::WorkGroupUniformLoadResult { ty: result_ty }, span, - ); + )?; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block.push( crate::Statement::WorkGroupUniformLoad { pointer, result }, @@ -2126,8 +2217,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let query = self.ray_query_pointer(args.next()?, ctx.reborrow())?; args.finish()?; - let result = ctx - .interrupt_emitter(crate::Expression::RayQueryProceedResult, span); + let result = ctx.interrupt_emitter( + crate::Expression::RayQueryProceedResult, + span, + )?; let fun = crate::RayQueryFunction::Proceed { result }; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block @@ -2161,7 +2254,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; - let expr = ctx.append_expression(expr, span); + let expr = ctx.append_expression(expr, span)?; Ok(Some(expr)) } } @@ -2214,7 +2307,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { comparison: false, }, span, - ); + )?; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block.push( crate::Statement::Atomic { @@ -2367,7 +2460,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let member_min_size = self.layouter[ty].size; let member_min_alignment = self.layouter[ty].alignment; - let member_size = if let Some((size, span)) = member.size { + let member_size = if let Some(size_expr) = member.size { + let (size, span) = self.const_u32(size_expr, ctx.as_const())?; if size < member_min_size { return Err(Error::SizeAttributeTooLow(span, member_min_size)); } else { @@ -2377,7 +2471,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { member_min_size }; - let member_alignment = if let Some((align, span)) = member.align { + let member_alignment = if let Some(align_expr) = member.align { + let (align, span) = self.const_u32(align_expr, ctx.as_const())?; if let Some(alignment) = Alignment::new(align) { if alignment < member_min_alignment { return Err(Error::AlignAttributeTooLow(span, member_min_alignment)); @@ -2391,7 +2486,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { member_min_alignment }; - let binding = self.interpolate_default(&member.binding, ty, ctx.reborrow()); + let binding = self.binding(&member.binding, ty, ctx.reborrow())?; offset = member_alignment.round_up(offset); struct_alignment = struct_alignment.max(member_alignment); @@ -2422,6 +2517,26 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok(handle) } + fn const_u32( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result<(u32, Span), Error<'source>> { + let expr = self.expression(expr, ctx.reborrow())?; + let span = ctx.module.const_expressions.get_span(expr); + let value = ctx + .module + .to_ctx() + .eval_expr_to_u32(expr) + .map_err(|err| match err { + crate::proc::U32EvalError::NonConst => { + Error::ExpectedConstExprConcreteIntegerScalar(span) + } + crate::proc::U32EvalError::Negative => Error::ExpectedNonNegative(span), + })?; + Ok((value, span)) + } + /// Return a Naga `Handle` representing the front-end type `handle`. fn resolve_ast_type( &mut self, @@ -2507,18 +2622,31 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok(ctx.ensure_type_exists(inner)) } - fn interpolate_default( + fn binding( &mut self, - binding: &Option, + binding: &Option>, ty: Handle, - ctx: GlobalContext<'source, '_, '_>, - ) -> Option { - let mut binding = binding.clone(); - if let Some(ref mut binding) = binding { - binding.apply_default_interpolation(&ctx.module.types[ty].inner); - } - - binding + mut ctx: GlobalContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + Ok(match *binding { + Some(ast::Binding::BuiltIn(b)) => Some(crate::Binding::BuiltIn(b)), + Some(ast::Binding::Location { + location, + second_blend_source, + interpolation, + sampling, + }) => { + let mut binding = crate::Binding::Location { + location: self.const_u32(location, ctx.as_const())?.0, + second_blend_source, + interpolation, + sampling, + }; + binding.apply_default_interpolation(&ctx.module.types[ty].inner); + Some(binding) + } + None => None, + }) } fn ray_query_pointer( diff --git a/src/front/wgsl/parse/ast.rs b/src/front/wgsl/parse/ast.rs index fca7457f0..f88e880a3 100644 --- a/src/front/wgsl/parse/ast.rs +++ b/src/front/wgsl/parse/ast.rs @@ -89,21 +89,21 @@ pub enum GlobalDeclKind<'a> { pub struct FunctionArgument<'a> { pub name: Ident<'a>, pub ty: Handle>, - pub binding: Option, + pub binding: Option>, pub handle: Handle, } #[derive(Debug)] pub struct FunctionResult<'a> { pub ty: Handle>, - pub binding: Option, + pub binding: Option>, } #[derive(Debug)] -pub struct EntryPoint { +pub struct EntryPoint<'a> { pub stage: crate::ShaderStage, pub early_depth_test: Option, - pub workgroup_size: Option<[u32; 3]>, + pub workgroup_size: Option<[Option>>; 3]>, } #[cfg(doc)] @@ -111,7 +111,7 @@ use crate::front::wgsl::lower::{RuntimeExpressionContext, StatementContext}; #[derive(Debug)] pub struct Function<'a> { - pub entry_point: Option, + pub entry_point: Option>, pub name: Ident<'a>, pub arguments: Vec>, pub result: Option>, @@ -145,11 +145,28 @@ pub struct Function<'a> { pub body: Block<'a>, } +#[derive(Debug)] +pub enum Binding<'a> { + BuiltIn(crate::BuiltIn), + Location { + location: Handle>, + second_blend_source: bool, + interpolation: Option, + sampling: Option, + }, +} + +#[derive(Debug)] +pub struct ResourceBinding<'a> { + pub group: Handle>, + pub binding: Handle>, +} + #[derive(Debug)] pub struct GlobalVariable<'a> { pub name: Ident<'a>, pub space: crate::AddressSpace, - pub binding: Option, + pub binding: Option>, pub ty: Handle>, pub init: Option>>, } @@ -158,9 +175,9 @@ pub struct GlobalVariable<'a> { pub struct StructMember<'a> { pub name: Ident<'a>, pub ty: Handle>, - pub binding: Option, - pub align: Option<(u32, Span)>, - pub size: Option<(u32, Span)>, + pub binding: Option>, + pub align: Option>>, + pub size: Option>>, } #[derive(Debug)] @@ -292,16 +309,14 @@ pub enum StatementKind<'a> { } #[derive(Debug)] -pub enum SwitchValue { - I32(i32), - U32(u32), +pub enum SwitchValue<'a> { + Expr(Handle>), Default, } #[derive(Debug)] pub struct SwitchCase<'a> { - pub value: SwitchValue, - pub value_span: Span, + pub value: SwitchValue<'a>, pub body: Block<'a>, pub fall_through: bool, } diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 325a8e690..74738ab23 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -141,8 +141,8 @@ impl ParsedAttribute { } #[derive(Default)] -struct BindingParser { - location: ParsedAttribute, +struct BindingParser<'a> { + location: ParsedAttribute>>, second_blend_source: ParsedAttribute, built_in: ParsedAttribute, interpolation: ParsedAttribute, @@ -150,18 +150,20 @@ struct BindingParser { invariant: ParsedAttribute, } -impl BindingParser { - fn parse<'a>( +impl<'a> BindingParser<'a> { + fn parse( &mut self, + parser: &mut Parser, lexer: &mut Lexer<'a>, name: &'a str, name_span: Span, + mut ctx: ExpressionContext<'a, '_, '_>, ) -> Result<(), Error<'a>> { match name { "location" => { lexer.expect(Token::Paren('('))?; self.location - .set(Parser::non_negative_i32_literal(lexer)?, name_span)?; + .set(parser.general_expression(lexer, ctx.reborrow())?, name_span)?; lexer.expect(Token::Paren(')'))?; } "builtin" => { @@ -194,7 +196,7 @@ impl BindingParser { Ok(()) } - fn finish<'a>(self, span: Span) -> Result, Error<'a>> { + fn finish(self, span: Span) -> Result>, Error<'a>> { match ( self.location.value, self.built_in.value, @@ -208,7 +210,7 @@ impl BindingParser { // `apply_default_interpolation` to ensure that the interpolation and // sampling have been explicitly specified on all vertex shader output and fragment // shader input user bindings, so leaving them potentially `None` here is fine. - Ok(Some(crate::Binding::Location { + Ok(Some(ast::Binding::Location { location, interpolation, sampling, @@ -216,13 +218,11 @@ impl BindingParser { })) } (None, Some(crate::BuiltIn::Position { .. }), None, None, invariant) => { - Ok(Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { + Ok(Some(ast::Binding::BuiltIn(crate::BuiltIn::Position { invariant, }))) } - (None, Some(built_in), None, None, false) => { - Ok(Some(crate::Binding::BuiltIn(built_in))) - } + (None, Some(built_in), None, None, false) => Ok(Some(ast::Binding::BuiltIn(built_in))), (_, _, _, _, _) => Err(Error::InconsistentBinding(span)), } } @@ -255,41 +255,18 @@ impl Parser { lexer.span_from(initial) } - fn switch_value<'a>(lexer: &mut Lexer<'a>) -> Result<(ast::SwitchValue, Span), Error<'a>> { - let token_span = lexer.next(); - match token_span.0 { - Token::Word("default") => Ok((ast::SwitchValue::Default, token_span.1)), - Token::Number(Ok(Number::U32(num))) => Ok((ast::SwitchValue::U32(num), token_span.1)), - Token::Number(Ok(Number::I32(num))) => Ok((ast::SwitchValue::I32(num), token_span.1)), - Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)), - _ => Err(Error::Unexpected(token_span.1, ExpectedToken::Integer)), + fn switch_value<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + if let Token::Word("default") = lexer.peek().0 { + let _ = lexer.next(); + return Ok(ast::SwitchValue::Default); } - } - /// Parse a non-negative signed integer literal. - /// This is for attributes like `size`, `location` and others. - fn non_negative_i32_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { - match lexer.next() { - (Token::Number(Ok(Number::I32(num))), span) => { - u32::try_from(num).map_err(|_| Error::NegativeInt(span)) - } - (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), - other => Err(Error::Unexpected(other.1, ExpectedToken::Number)), - } - } - - /// Parse a non-negative integer literal that may be either signed or unsigned. - /// This is for the `workgroup_size` attribute and array lengths. - /// Note: these values should be no larger than [`i32::MAX`], but this is not checked here. - fn generic_non_negative_int_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { - match lexer.next() { - (Token::Number(Ok(Number::I32(num))), span) => { - u32::try_from(num).map_err(|_| Error::NegativeInt(span)) - } - (Token::Number(Ok(Number::U32(num))), _) => Ok(num), - (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), - other => Err(Error::Unexpected(other.1, ExpectedToken::Number)), - } + let expr = self.general_expression(lexer, ctx.reborrow())?; + Ok(ast::SwitchValue::Expr(expr)) } /// Decide if we're looking at a construction expression, and return its @@ -1028,17 +1005,19 @@ impl Parser { match lexer.next_ident_with_span()? { ("size", name_span) => { lexer.expect(Token::Paren('('))?; - let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; + let expr = self.general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; - size.set((value, span), name_span)?; + size.set(expr, name_span)?; } ("align", name_span) => { lexer.expect(Token::Paren('('))?; - let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; + let expr = self.general_expression(lexer, ctx.reborrow())?; lexer.expect(Token::Paren(')'))?; - align.set((value, span), name_span)?; + align.set(expr, name_span)?; + } + (word, word_span) => { + bind_parser.parse(self, lexer, word, word_span, ctx.reborrow())? } - (word, word_span) => bind_parser.parse(lexer, word, word_span)?, } } @@ -1765,19 +1744,18 @@ impl Parser { match lexer.next() { (Token::Word("case"), _) => { // parse a list of values - let (value, value_span) = loop { - let (value, value_span) = Self::switch_value(lexer)?; + let value = loop { + let value = self.switch_value(lexer, ctx.reborrow())?; if lexer.skip(Token::Separator(',')) { if lexer.skip(Token::Separator(':')) { - break (value, value_span); + break value; } } else { lexer.skip(Token::Separator(':')); - break (value, value_span); + break value; } cases.push(ast::SwitchCase { value, - value_span, body: ast::Block::default(), fall_through: true, }); @@ -1787,17 +1765,15 @@ impl Parser { cases.push(ast::SwitchCase { value, - value_span, body, fall_through: false, }); } - (Token::Word("default"), value_span) => { + (Token::Word("default"), _) => { lexer.skip(Token::Separator(':')); let body = self.block(lexer, ctx.reborrow())?.0; cases.push(ast::SwitchCase { value: ast::SwitchValue::Default, - value_span, body, fall_through: false, }); @@ -2059,13 +2035,14 @@ impl Parser { fn varying_binding<'a>( &mut self, lexer: &mut Lexer<'a>, - ) -> Result, Error<'a>> { + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { let mut bind_parser = BindingParser::default(); self.push_rule_span(Rule::Attribute, lexer); while lexer.skip(Token::Attribute) { let (word, span) = lexer.next_ident_with_span()?; - bind_parser.parse(lexer, word, span)?; + bind_parser.parse(self, lexer, word, span, ctx.reborrow())?; } let span = self.pop_rule_span(lexer); @@ -2106,7 +2083,7 @@ impl Parser { ExpectedToken::Token(Token::Separator(',')), )); } - let binding = self.varying_binding(lexer)?; + let binding = self.varying_binding(lexer, ctx.reborrow())?; let param_name = lexer.next_ident()?; @@ -2124,7 +2101,7 @@ impl Parser { } // read return type let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { - let binding = self.varying_binding(lexer)?; + let binding = self.varying_binding(lexer, ctx.reborrow())?; let ty = self.type_decl(lexer, ctx.reborrow())?; Some(ast::FunctionResult { ty, binding }) } else { @@ -2169,17 +2146,26 @@ impl Parser { let (mut bind_index, mut bind_group) = (ParsedAttribute::default(), ParsedAttribute::default()); + let mut dependencies = FastIndexSet::default(); + let mut ctx = ExpressionContext { + expressions: &mut out.expressions, + local_table: &mut SymbolTable::default(), + locals: &mut Arena::new(), + types: &mut out.types, + unresolved: &mut dependencies, + }; + self.push_rule_span(Rule::Attribute, lexer); while lexer.skip(Token::Attribute) { match lexer.next_ident_with_span()? { ("binding", name_span) => { lexer.expect(Token::Paren('('))?; - bind_index.set(Self::non_negative_i32_literal(lexer)?, name_span)?; + bind_index.set(self.general_expression(lexer, ctx.reborrow())?, name_span)?; lexer.expect(Token::Paren(')'))?; } ("group", name_span) => { lexer.expect(Token::Paren('('))?; - bind_group.set(Self::non_negative_i32_literal(lexer)?, name_span)?; + bind_group.set(self.general_expression(lexer, ctx.reborrow())?, name_span)?; lexer.expect(Token::Paren(')'))?; } ("vertex", name_span) => { @@ -2194,9 +2180,9 @@ impl Parser { } ("workgroup_size", name_span) => { lexer.expect(Token::Paren('('))?; - let mut new_workgroup_size = [1u32; 3]; + let mut new_workgroup_size = [None; 3]; for (i, size) in new_workgroup_size.iter_mut().enumerate() { - *size = Self::generic_non_negative_int_literal(lexer)?; + *size = Some(self.general_expression(lexer, ctx.reborrow())?); match lexer.next() { (Token::Paren(')'), _) => break, (Token::Separator(','), _) if i != 2 => (), @@ -2228,7 +2214,7 @@ impl Parser { let attrib_span = self.pop_rule_span(lexer); match (bind_group.value, bind_index.value) { (Some(group), Some(index)) => { - binding = Some(crate::ResourceBinding { + binding = Some(ast::ResourceBinding { group, binding: index, }); @@ -2238,15 +2224,6 @@ impl Parser { (None, None) => {} } - let mut dependencies = FastIndexSet::default(); - let mut ctx = ExpressionContext { - expressions: &mut out.expressions, - local_table: &mut SymbolTable::default(), - locals: &mut Arena::new(), - types: &mut out.types, - unresolved: &mut dependencies, - }; - // read item let start = lexer.start_byte_offset(); let kind = match lexer.next() { diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs index 828f1e3c7..9e3ba2fab 100644 --- a/src/front/wgsl/tests.rs +++ b/src/front/wgsl/tests.rs @@ -402,9 +402,8 @@ fn binary_expression_mixed_scalar_and_vector_operands() { ] { let module = parse_str(&format!( " - const some_vec = vec3(1.0, 1.0, 1.0); @fragment - fn main() -> @location(0) vec4 {{ + fn main(@location(0) some_vec: vec3) -> @location(0) vec4 {{ if (all(1.0 {operand} some_vec)) {{ return vec4(0.0); }} @@ -431,7 +430,12 @@ fn binary_expression_mixed_scalar_and_vector_operands() { }) .count(); - assert_eq!(found_expressions, 1); + assert_eq!( + found_expressions, + 1, + "expected `{operand}` expression {} splat", + if expect_splat { "with" } else { "without" } + ); } let module = parse_str( diff --git a/src/front/glsl/constants.rs b/src/proc/constant_evaluator.rs similarity index 52% rename from src/front/glsl/constants.rs rename to src/proc/constant_evaluator.rs index 81ec6f3a8..cf00b13de 100644 --- a/src/front/glsl/constants.rs +++ b/src/proc/constant_evaluator.rs @@ -1,19 +1,23 @@ use crate::{ arena::{Arena, Handle, UniqueArena}, - ArraySize, BinaryOperator, Constant, Expression, Literal, ScalarKind, Type, TypeInner, + ArraySize, BinaryOperator, Constant, Expression, Literal, ScalarKind, Span, Type, TypeInner, UnaryOperator, }; #[derive(Debug)] -pub struct ConstantSolver<'a> { +pub struct ConstantEvaluator< + 'a, + F: FnMut(&mut Arena, Expression, Span) -> Handle, +> { pub types: &'a mut UniqueArena, - pub expressions: &'a Arena, - pub constants: &'a mut Arena, - pub const_expressions: &'a mut Arena, + pub constants: &'a Arena, + pub expressions: &'a mut Arena, + pub const_expressions: Option<&'a Arena>, + pub append: Option, } #[derive(Clone, Debug, PartialEq, thiserror::Error)] -pub enum ConstantSolvingError { +pub enum ConstantEvaluatorError { #[error("Constants cannot access function arguments")] FunctionArg, #[error("Constants cannot access global variables")] @@ -26,6 +30,8 @@ pub enum ConstantSolvingError { ArrayLengthDynamic, #[error("Constants cannot call functions")] Call, + #[error("Constants don't support workGroupUniformLoad")] + WorkGroupUniformLoadResult, #[error("Constants don't support atomic functions")] Atomic, #[error("Constants don't support relational functions")] @@ -62,6 +68,8 @@ pub enum ConstantSolvingError { SwizzleVectorOnly, #[error("Type is not constructible")] TypeNotConstructible, + #[error("Subexpression(s) are not constant")] + SubexpressionsAreNotConstant, #[error("Not implemented as constant expression: {0}")] NotImplemented(String), } @@ -72,38 +80,174 @@ pub enum ExprType { Constant, } -impl<'a> ConstantSolver<'a> { - pub fn solve( +// Access +// AccessIndex +// Splat +// Swizzle +// Unary +// Binary +// Select +// Relational +// Math +// As + +impl<'a, F: FnMut(&mut Arena, Expression, Span) -> Handle> + ConstantEvaluator<'a, F> +{ + fn check_and_get( &mut self, expr: Handle, - ) -> Result, ConstantSolvingError> { - self.solve_impl(expr, ExprType::Regular, true) + ) -> Result, ConstantEvaluatorError> { + match self.expressions[expr] { + Expression::Literal(_) + | Expression::ZeroValue(_) + | Expression::Compose { .. } + | Expression::Splat { .. } => Ok(expr), + Expression::Constant(c) => { + if let Some(const_expressions) = self.const_expressions { + self.copy_from(self.constants[c].init, const_expressions) + } else { + Ok(self.constants[c].init) + } + } + _ => Err(ConstantEvaluatorError::SubexpressionsAreNotConstant), + } } - pub fn solve_impl( + pub fn try_eval_and_append( + &mut self, + expr: &Expression, + span: Span, + ) -> Result, ConstantEvaluatorError> { + match *expr { + Expression::Literal(_) | Expression::ZeroValue(_) | Expression::Constant(_) => { + Ok(self.register_evaluated_expr(expr.clone(), span)) + } + Expression::Compose { ref components, .. } => { + for component in components { + self.check_and_get(*component)?; + } + Ok(self.register_evaluated_expr(expr.clone(), span)) + } + Expression::Splat { value, .. } => { + self.check_and_get(value)?; + Ok(self.register_evaluated_expr(expr.clone(), span)) + } + Expression::AccessIndex { base, index } => { + let base = self.check_and_get(base)?; + + self.access(base, index as usize, span) + } + Expression::Access { base, index } => { + let base = self.check_and_get(base)?; + let index = self.check_and_get(index)?; + + self.access(base, self.constant_index(index)?, span) + } + Expression::Swizzle { + size, + vector, + pattern, + } => { + let vector = self.check_and_get(vector)?; + + self.swizzle(size, span, vector, pattern) + } + Expression::Unary { expr, op } => { + let expr = self.check_and_get(expr)?; + + self.unary_op(op, expr, span) + } + Expression::Binary { left, right, op } => { + let left = self.check_and_get(left)?; + let right = self.check_and_get(right)?; + + self.binary_op(op, left, right, span) + } + Expression::Math { + fun, + arg, + arg1, + arg2, + arg3, + } => { + let arg = self.check_and_get(arg)?; + let arg1 = arg1.map(|arg| self.check_and_get(arg)).transpose()?; + let arg2 = arg2.map(|arg| self.check_and_get(arg)).transpose()?; + let arg3 = arg3.map(|arg| self.check_and_get(arg)).transpose()?; + + self.math(arg, arg1, arg2, arg3, fun, span) + } + Expression::As { + convert, + expr, + kind, + } => { + let expr = self.check_and_get(expr)?; + + match convert { + Some(width) => self.cast(expr, kind, width, span), + None => Err(ConstantEvaluatorError::Bitcast), + } + } + Expression::ArrayLength(expr) => { + let expr = self.check_and_get(expr)?; + + self.array_length(expr, span) + } + + Expression::Load { .. } => Err(ConstantEvaluatorError::Load), + Expression::Select { .. } => Err(ConstantEvaluatorError::Select), + Expression::LocalVariable(_) => Err(ConstantEvaluatorError::LocalVariable), + Expression::Derivative { .. } => Err(ConstantEvaluatorError::Derivative), + Expression::Relational { .. } => Err(ConstantEvaluatorError::Relational), + Expression::CallResult { .. } => Err(ConstantEvaluatorError::Call), + Expression::WorkGroupUniformLoadResult { .. } => { + Err(ConstantEvaluatorError::WorkGroupUniformLoadResult) + } + Expression::AtomicResult { .. } => Err(ConstantEvaluatorError::Atomic), + Expression::FunctionArgument(_) => Err(ConstantEvaluatorError::FunctionArg), + Expression::GlobalVariable(_) => Err(ConstantEvaluatorError::GlobalVariable), + Expression::ImageSample { .. } + | Expression::ImageLoad { .. } + | Expression::ImageQuery { .. } => Err(ConstantEvaluatorError::ImageExpression), + Expression::RayQueryProceedResult | Expression::RayQueryGetIntersection { .. } => { + Err(ConstantEvaluatorError::RayQueryExpression) + } + } + } + + pub fn eval( + &mut self, + expr: Handle, + ) -> Result, ConstantEvaluatorError> { + self.eval_impl(expr, ExprType::Regular, true) + } + + pub fn eval_impl( &mut self, expr: Handle, expr_type: ExprType, top_level: bool, - ) -> Result, ConstantSolvingError> { + ) -> Result, ConstantEvaluatorError> { let expressions = match expr_type { - ExprType::Regular => self.expressions, - ExprType::Constant => self.const_expressions, + ExprType::Regular => self.const_expressions.unwrap(), + ExprType::Constant => self.expressions, }; let span = expressions.get_span(expr); match expressions[expr] { ref expression @ (Expression::Literal(_) | Expression::ZeroValue(_)) => match expr_type { - ExprType::Regular => Ok(self.register_constant(expression.clone(), span)), + ExprType::Regular => Ok(self.register_evaluated_expr(expression.clone(), span)), ExprType::Constant => Ok(expr), }, Expression::Compose { ty, ref components } => match expr_type { ExprType::Regular => { let mut components = components.clone(); for component in &mut components { - *component = self.solve_impl(*component, expr_type, false)?; + *component = self.eval_impl(*component, expr_type, false)?; } - Ok(self.register_constant(Expression::Compose { ty, components }, span)) + Ok(self.register_evaluated_expr(Expression::Compose { ty, components }, span)) } ExprType::Constant => Ok(expr), }, @@ -111,118 +255,47 @@ impl<'a> ConstantSolver<'a> { if top_level { match expr_type { ExprType::Regular => { - Ok(self.register_constant(Expression::Constant(constant), span)) + Ok(self.register_evaluated_expr(Expression::Constant(constant), span)) } ExprType::Constant => Ok(expr), } } else { - self.solve_impl(self.constants[constant].init, ExprType::Constant, false) + self.eval_impl(self.constants[constant].init, ExprType::Constant, false) } } Expression::AccessIndex { base, index } => { - let base = self.solve_impl(base, expr_type, false)?; + let base = self.eval_impl(base, expr_type, false)?; + self.access(base, index as usize, span) } Expression::Access { base, index } => { - let base = self.solve_impl(base, expr_type, false)?; - let index = self.solve_impl(index, expr_type, false)?; + let base = self.eval_impl(base, expr_type, false)?; + let index = self.eval_impl(index, expr_type, false)?; self.access(base, self.constant_index(index)?, span) } - Expression::Splat { - size, - value: splat_value, - } => { - let value_constant = self.solve_impl(splat_value, expr_type, false)?; - let ty = match self.const_expressions[value_constant] { - Expression::Literal(literal) => { - let kind = literal.scalar_kind(); - let width = literal.width(); - self.types.insert( - Type { - name: None, - inner: TypeInner::Vector { size, kind, width }, - }, - span, - ) - } - Expression::ZeroValue(ty) => { - let inner = match self.types[ty].inner { - TypeInner::Scalar { kind, width } => { - TypeInner::Vector { size, kind, width } - } - _ => return Err(ConstantSolvingError::SplatScalarOnly), - }; - let res_ty = self.types.insert(Type { name: None, inner }, span); - let expr = Expression::ZeroValue(res_ty); - return Ok(self.register_constant(expr, span)); - } - _ => { - return Err(ConstantSolvingError::SplatScalarOnly); - } - }; + Expression::Splat { size, value } => { + let value = self.eval_impl(value, expr_type, false)?; - let expr = Expression::Compose { - ty, - components: vec![value_constant; size as usize], - }; - Ok(self.register_constant(expr, span)) + self.splat(value, size, span) } Expression::Swizzle { size, vector: src_vector, pattern, } => { - let src_constant = self.solve_impl(src_vector, expr_type, false)?; + let src_constant = self.eval_impl(src_vector, expr_type, false)?; - let mut get_dst_ty = |ty| match self.types[ty].inner { - crate::TypeInner::Vector { - size: _, - kind, - width, - } => Ok(self.types.insert( - Type { - name: None, - inner: crate::TypeInner::Vector { size, kind, width }, - }, - span, - )), - _ => Err(ConstantSolvingError::SwizzleVectorOnly), - }; - - match self.const_expressions[src_constant] { - Expression::ZeroValue(ty) => { - let dst_ty = get_dst_ty(ty)?; - let expr = Expression::ZeroValue(dst_ty); - Ok(self.register_constant(expr, span)) - } - Expression::Compose { - ty, - components: ref src_components, - } => { - let dst_ty = get_dst_ty(ty)?; - - let components = pattern - .iter() - .map(|&sc| src_components[sc as usize]) - .collect(); - let expr = Expression::Compose { - ty: dst_ty, - components, - }; - Ok(self.register_constant(expr, span)) - } - _ => Err(ConstantSolvingError::SwizzleVectorOnly), - } + self.swizzle(size, span, src_constant, pattern) } Expression::Unary { expr, op } => { - let expr_constant = self.solve_impl(expr, expr_type, false)?; + let expr_constant = self.eval_impl(expr, expr_type, false)?; self.unary_op(op, expr_constant, span) } Expression::Binary { left, right, op } => { - let left_constant = self.solve_impl(left, expr_type, false)?; - let right_constant = self.solve_impl(right, expr_type, false)?; + let left_constant = self.eval_impl(left, expr_type, false)?; + let right_constant = self.eval_impl(right, expr_type, false)?; self.binary_op(op, left_constant, right_constant, span) } @@ -233,183 +306,298 @@ impl<'a> ConstantSolver<'a> { arg2, arg3, } => { - let arg = self.solve_impl(arg, expr_type, false)?; + let arg = self.eval_impl(arg, expr_type, false)?; let arg1 = arg1 - .map(|arg| self.solve_impl(arg, expr_type, false)) + .map(|arg| self.eval_impl(arg, expr_type, false)) .transpose()?; let arg2 = arg2 - .map(|arg| self.solve_impl(arg, expr_type, false)) + .map(|arg| self.eval_impl(arg, expr_type, false)) .transpose()?; let arg3 = arg3 - .map(|arg| self.solve_impl(arg, expr_type, false)) + .map(|arg| self.eval_impl(arg, expr_type, false)) .transpose()?; - let const0 = &self.const_expressions[arg]; - let const1 = arg1.map(|arg| &self.const_expressions[arg]); - let const2 = arg2.map(|arg| &self.const_expressions[arg]); - let _const3 = arg3.map(|arg| &self.const_expressions[arg]); - - match fun { - crate::MathFunction::Pow => { - let literal = match (const0, const1.unwrap()) { - (&Expression::Literal(value0), &Expression::Literal(value1)) => { - match (value0, value1) { - (Literal::I32(a), Literal::I32(b)) => { - Literal::I32(a.pow(b as u32)) - } - (Literal::U32(a), Literal::U32(b)) => Literal::U32(a.pow(b)), - (Literal::F32(a), Literal::F32(b)) => Literal::F32(a.powf(b)), - _ => return Err(ConstantSolvingError::InvalidMathArg), - } - } - _ => return Err(ConstantSolvingError::InvalidMathArg), - }; - - let expr = Expression::Literal(literal); - Ok(self.register_constant(expr, span)) - } - crate::MathFunction::Clamp => { - let literal = match (const0, const1.unwrap(), const2.unwrap()) { - ( - &Expression::Literal(value0), - &Expression::Literal(value1), - &Expression::Literal(value2), - ) => match (value0, value1, value2) { - (Literal::I32(a), Literal::I32(b), Literal::I32(c)) => { - Literal::I32(a.clamp(b, c)) - } - (Literal::U32(a), Literal::U32(b), Literal::U32(c)) => { - Literal::U32(a.clamp(b, c)) - } - (Literal::F32(a), Literal::F32(b), Literal::F32(c)) => { - Literal::F32(glsl_float_clamp(a, b, c)) - } - _ => return Err(ConstantSolvingError::InvalidMathArg), - }, - _ => { - return Err(ConstantSolvingError::NotImplemented(format!( - "{fun:?} applied to vector values" - ))) - } - }; - - let expr = Expression::Literal(literal); - Ok(self.register_constant(expr, span)) - } - _ => Err(ConstantSolvingError::NotImplemented(format!("{fun:?}"))), - } + self.math(arg, arg1, arg2, arg3, fun, span) } Expression::As { convert, expr, kind, } => { - let expr_constant = self.solve_impl(expr, expr_type, false)?; + let expr_constant = self.eval_impl(expr, expr_type, false)?; match convert { Some(width) => self.cast(expr_constant, kind, width, span), - None => Err(ConstantSolvingError::Bitcast), + None => Err(ConstantEvaluatorError::Bitcast), } } Expression::ArrayLength(expr) => { - let array = self.solve_impl(expr, expr_type, false)?; + let array = self.eval_impl(expr, expr_type, false)?; - match self.const_expressions[array] { - Expression::ZeroValue(ty) | Expression::Compose { ty, .. } => { - match self.types[ty].inner { - TypeInner::Array { size, .. } => match size { - crate::ArraySize::Constant(len) => { - let expr = Expression::Literal(Literal::U32(len.get())); - Ok(self.register_constant(expr, span)) - } - crate::ArraySize::Dynamic => { - Err(ConstantSolvingError::ArrayLengthDynamic) - } - }, - _ => Err(ConstantSolvingError::InvalidArrayLengthArg), - } - } - _ => Err(ConstantSolvingError::InvalidArrayLengthArg), - } + self.array_length(array, span) } - Expression::Load { .. } => Err(ConstantSolvingError::Load), - Expression::Select { .. } => Err(ConstantSolvingError::Select), - Expression::LocalVariable(_) => Err(ConstantSolvingError::LocalVariable), - Expression::Derivative { .. } => Err(ConstantSolvingError::Derivative), - Expression::Relational { .. } => Err(ConstantSolvingError::Relational), - Expression::CallResult { .. } => Err(ConstantSolvingError::Call), + Expression::Load { .. } => Err(ConstantEvaluatorError::Load), + Expression::Select { .. } => Err(ConstantEvaluatorError::Select), + Expression::LocalVariable(_) => Err(ConstantEvaluatorError::LocalVariable), + Expression::Derivative { .. } => Err(ConstantEvaluatorError::Derivative), + Expression::Relational { .. } => Err(ConstantEvaluatorError::Relational), + Expression::CallResult { .. } => Err(ConstantEvaluatorError::Call), Expression::WorkGroupUniformLoadResult { .. } => unreachable!(), - Expression::AtomicResult { .. } => Err(ConstantSolvingError::Atomic), - Expression::FunctionArgument(_) => Err(ConstantSolvingError::FunctionArg), - Expression::GlobalVariable(_) => Err(ConstantSolvingError::GlobalVariable), + Expression::AtomicResult { .. } => Err(ConstantEvaluatorError::Atomic), + Expression::FunctionArgument(_) => Err(ConstantEvaluatorError::FunctionArg), + Expression::GlobalVariable(_) => Err(ConstantEvaluatorError::GlobalVariable), Expression::ImageSample { .. } | Expression::ImageLoad { .. } - | Expression::ImageQuery { .. } => Err(ConstantSolvingError::ImageExpression), + | Expression::ImageQuery { .. } => Err(ConstantEvaluatorError::ImageExpression), Expression::RayQueryProceedResult | Expression::RayQueryGetIntersection { .. } => { - Err(ConstantSolvingError::RayQueryExpression) + Err(ConstantEvaluatorError::RayQueryExpression) } } } + fn splat( + &mut self, + value: Handle, + size: crate::VectorSize, + span: Span, + ) -> Result, ConstantEvaluatorError> { + match self.expressions[value] { + Expression::Literal(literal) => { + let kind = literal.scalar_kind(); + let width = literal.width(); + let ty = self.types.insert( + Type { + name: None, + inner: TypeInner::Vector { size, kind, width }, + }, + span, + ); + let expr = Expression::Compose { + ty, + components: vec![value; size as usize], + }; + Ok(self.register_evaluated_expr(expr, span)) + } + Expression::ZeroValue(ty) => { + let inner = match self.types[ty].inner { + TypeInner::Scalar { kind, width } => TypeInner::Vector { size, kind, width }, + _ => return Err(ConstantEvaluatorError::SplatScalarOnly), + }; + let res_ty = self.types.insert(Type { name: None, inner }, span); + let expr = Expression::ZeroValue(res_ty); + Ok(self.register_evaluated_expr(expr, span)) + } + _ => Err(ConstantEvaluatorError::SplatScalarOnly), + } + } + + fn swizzle( + &mut self, + size: crate::VectorSize, + span: Span, + src_constant: Handle, + pattern: [crate::SwizzleComponent; 4], + ) -> Result, ConstantEvaluatorError> { + let mut get_dst_ty = |ty| match self.types[ty].inner { + crate::TypeInner::Vector { + size: _, + kind, + width, + } => Ok(self.types.insert( + Type { + name: None, + inner: crate::TypeInner::Vector { size, kind, width }, + }, + span, + )), + _ => Err(ConstantEvaluatorError::SwizzleVectorOnly), + }; + + match self.expressions[src_constant] { + Expression::ZeroValue(ty) => { + let dst_ty = get_dst_ty(ty)?; + let expr = Expression::ZeroValue(dst_ty); + Ok(self.register_evaluated_expr(expr, span)) + } + Expression::Splat { value, .. } => { + let expr = Expression::Splat { size, value }; + Ok(self.register_evaluated_expr(expr, span)) + } + Expression::Compose { + ty, + components: ref src_components, + } => { + let dst_ty = get_dst_ty(ty)?; + + let components = pattern + .iter() + .take(size as usize) + .map(|&sc| src_components[sc as usize]) + .collect(); + let expr = Expression::Compose { + ty: dst_ty, + components, + }; + Ok(self.register_evaluated_expr(expr, span)) + } + _ => Err(ConstantEvaluatorError::SwizzleVectorOnly), + } + } + + fn math( + &mut self, + arg: Handle, + arg1: Option>, + arg2: Option>, + arg3: Option>, + fun: crate::MathFunction, + span: Span, + ) -> Result, ConstantEvaluatorError> { + let const0 = &self.expressions[arg]; + let const1 = arg1.map(|arg| &self.expressions[arg]); + let const2 = arg2.map(|arg| &self.expressions[arg]); + let _const3 = arg3.map(|arg| &self.expressions[arg]); + + match fun { + crate::MathFunction::Pow => { + let literal = match (const0, const1.unwrap()) { + (&Expression::Literal(value0), &Expression::Literal(value1)) => { + match (value0, value1) { + (Literal::I32(a), Literal::I32(b)) => Literal::I32(a.pow(b as u32)), + (Literal::U32(a), Literal::U32(b)) => Literal::U32(a.pow(b)), + (Literal::F32(a), Literal::F32(b)) => Literal::F32(a.powf(b)), + _ => return Err(ConstantEvaluatorError::InvalidMathArg), + } + } + _ => return Err(ConstantEvaluatorError::InvalidMathArg), + }; + + let expr = Expression::Literal(literal); + Ok(self.register_evaluated_expr(expr, span)) + } + crate::MathFunction::Clamp => { + let literal = match (const0, const1.unwrap(), const2.unwrap()) { + ( + &Expression::Literal(value0), + &Expression::Literal(value1), + &Expression::Literal(value2), + ) => match (value0, value1, value2) { + (Literal::I32(a), Literal::I32(b), Literal::I32(c)) => { + Literal::I32(a.clamp(b, c)) + } + (Literal::U32(a), Literal::U32(b), Literal::U32(c)) => { + Literal::U32(a.clamp(b, c)) + } + (Literal::F32(a), Literal::F32(b), Literal::F32(c)) => { + Literal::F32(glsl_float_clamp(a, b, c)) + } + _ => return Err(ConstantEvaluatorError::InvalidMathArg), + }, + _ => { + return Err(ConstantEvaluatorError::NotImplemented(format!( + "{fun:?} applied to vector values" + ))) + } + }; + + let expr = Expression::Literal(literal); + Ok(self.register_evaluated_expr(expr, span)) + } + _ => Err(ConstantEvaluatorError::NotImplemented(format!("{fun:?}"))), + } + } + + fn array_length( + &mut self, + array: Handle, + span: Span, + ) -> Result, ConstantEvaluatorError> { + match self.expressions[array] { + Expression::ZeroValue(ty) | Expression::Compose { ty, .. } => { + match self.types[ty].inner { + TypeInner::Array { size, .. } => match size { + crate::ArraySize::Constant(len) => { + let expr = Expression::Literal(Literal::U32(len.get())); + Ok(self.register_evaluated_expr(expr, span)) + } + crate::ArraySize::Dynamic => { + Err(ConstantEvaluatorError::ArrayLengthDynamic) + } + }, + _ => Err(ConstantEvaluatorError::InvalidArrayLengthArg), + } + } + _ => Err(ConstantEvaluatorError::InvalidArrayLengthArg), + } + } + fn access( &mut self, base: Handle, index: usize, - span: crate::Span, - ) -> Result, ConstantSolvingError> { - match self.const_expressions[base] { + span: Span, + ) -> Result, ConstantEvaluatorError> { + match self.expressions[base] { Expression::ZeroValue(ty) => { let ty_inner = &self.types[ty].inner; let components = ty_inner .components() - .ok_or(ConstantSolvingError::InvalidAccessBase)?; + .ok_or(ConstantEvaluatorError::InvalidAccessBase)?; if index >= components as usize { - Err(ConstantSolvingError::InvalidAccessBase) + Err(ConstantEvaluatorError::InvalidAccessBase) } else { let ty_res = ty_inner .component_type(index) - .ok_or(ConstantSolvingError::InvalidAccessIndex)?; + .ok_or(ConstantEvaluatorError::InvalidAccessIndex)?; let ty = match ty_res { crate::proc::TypeResolution::Handle(ty) => ty, crate::proc::TypeResolution::Value(inner) => { self.types.insert(Type { name: None, inner }, span) } }; - Ok(self.register_constant(Expression::ZeroValue(ty), span)) + Ok(self.register_evaluated_expr(Expression::ZeroValue(ty), span)) + } + } + Expression::Splat { size, value } => { + if index >= size as usize { + Err(ConstantEvaluatorError::InvalidAccessBase) + } else { + Ok(value) } } Expression::Compose { ty, ref components } => { let _ = self.types[ty] .inner .components() - .ok_or(ConstantSolvingError::InvalidAccessBase)?; + .ok_or(ConstantEvaluatorError::InvalidAccessBase)?; components .get(index) .copied() - .ok_or(ConstantSolvingError::InvalidAccessIndex) + .ok_or(ConstantEvaluatorError::InvalidAccessIndex) } - _ => Err(ConstantSolvingError::InvalidAccessBase), + _ => Err(ConstantEvaluatorError::InvalidAccessBase), } } - fn constant_index(&self, expr: Handle) -> Result { - match self.const_expressions[expr] { + fn constant_index(&self, expr: Handle) -> Result { + match self.expressions[expr] { Expression::Literal(Literal::U32(index)) => Ok(index as usize), - _ => Err(ConstantSolvingError::InvalidAccessIndexTy), + _ => Err(ConstantEvaluatorError::InvalidAccessIndexTy), } } - /// Transforms a `Expression::ZeroValue` into either `Expression::Literal` or `Expression::Compose` - fn eval_zero_value( + /// Transforms `Expression::ZeroValue` and `Expression::Splat` into either `Expression::Literal` or `Expression::Compose` + fn eval_zero_value_and_splat( &mut self, expr: Handle, - span: crate::Span, - ) -> Result, ConstantSolvingError> { - match self.const_expressions[expr] { + span: Span, + ) -> Result, ConstantEvaluatorError> { + match self.expressions[expr] { Expression::ZeroValue(ty) => self.eval_zero_value_impl(ty, span), + Expression::Splat { size, value } => self.splat(value, size, span), _ => Ok(expr), } } @@ -417,14 +605,15 @@ impl<'a> ConstantSolver<'a> { fn eval_zero_value_impl( &mut self, ty: Handle, - span: crate::Span, - ) -> Result, ConstantSolvingError> { + span: Span, + ) -> Result, ConstantEvaluatorError> { match self.types[ty].inner { TypeInner::Scalar { kind, width } => { let expr = Expression::Literal( - Literal::zero(kind, width).ok_or(ConstantSolvingError::TypeNotConstructible)?, + Literal::zero(kind, width) + .ok_or(ConstantEvaluatorError::TypeNotConstructible)?, ); - Ok(self.register_constant(expr, span)) + Ok(self.register_evaluated_expr(expr, span)) } TypeInner::Vector { size, kind, width } => { let scalar_ty = self.types.insert( @@ -439,7 +628,7 @@ impl<'a> ConstantSolver<'a> { ty, components: vec![el; size as usize], }; - Ok(self.register_constant(expr, span)) + Ok(self.register_evaluated_expr(expr, span)) } TypeInner::Matrix { columns, @@ -462,7 +651,7 @@ impl<'a> ConstantSolver<'a> { ty, components: vec![el; columns as usize], }; - Ok(self.register_constant(expr, span)) + Ok(self.register_evaluated_expr(expr, span)) } TypeInner::Array { base, @@ -474,7 +663,7 @@ impl<'a> ConstantSolver<'a> { ty, components: vec![el; size.get() as usize], }; - Ok(self.register_constant(expr, span)) + Ok(self.register_evaluated_expr(expr, span)) } TypeInner::Struct { ref members, .. } => { let types: Vec<_> = members.iter().map(|m| m.ty).collect(); @@ -483,9 +672,9 @@ impl<'a> ConstantSolver<'a> { components.push(self.eval_zero_value_impl(ty, span)?); } let expr = Expression::Compose { ty, components }; - Ok(self.register_constant(expr, span)) + Ok(self.register_evaluated_expr(expr, span)) } - _ => Err(ConstantSolvingError::TypeNotConstructible), + _ => Err(ConstantEvaluatorError::TypeNotConstructible), } } @@ -494,11 +683,11 @@ impl<'a> ConstantSolver<'a> { expr: Handle, kind: ScalarKind, target_width: crate::Bytes, - span: crate::Span, - ) -> Result, ConstantSolvingError> { - let expr = self.eval_zero_value(expr, span)?; + span: Span, + ) -> Result, ConstantEvaluatorError> { + let expr = self.eval_zero_value_and_splat(expr, span)?; - let expr = match self.const_expressions[expr] { + let expr = match self.expressions[expr] { Expression::Literal(literal) => { let literal = match (kind, target_width) { (ScalarKind::Sint, 4) => Literal::I32(match literal { @@ -506,30 +695,30 @@ impl<'a> ConstantSolver<'a> { Literal::U32(v) => v as i32, Literal::F32(v) => v as i32, Literal::Bool(v) => v as i32, - Literal::F64(_) => return Err(ConstantSolvingError::InvalidCastArg), + Literal::F64(_) => return Err(ConstantEvaluatorError::InvalidCastArg), }), (ScalarKind::Uint, 4) => Literal::U32(match literal { Literal::I32(v) => v as u32, Literal::U32(v) => v, Literal::F32(v) => v as u32, Literal::Bool(v) => v as u32, - Literal::F64(_) => return Err(ConstantSolvingError::InvalidCastArg), + Literal::F64(_) => return Err(ConstantEvaluatorError::InvalidCastArg), }), (ScalarKind::Float, 4) => Literal::F32(match literal { Literal::I32(v) => v as f32, Literal::U32(v) => v as f32, Literal::F32(v) => v, Literal::Bool(v) => v as u32 as f32, - Literal::F64(_) => return Err(ConstantSolvingError::InvalidCastArg), + Literal::F64(_) => return Err(ConstantEvaluatorError::InvalidCastArg), }), (ScalarKind::Bool, crate::BOOL_WIDTH) => Literal::Bool(match literal { Literal::I32(v) => v != 0, Literal::U32(v) => v != 0, Literal::F32(v) => v != 0.0, Literal::Bool(v) => v, - Literal::F64(_) => return Err(ConstantSolvingError::InvalidCastArg), + Literal::F64(_) => return Err(ConstantEvaluatorError::InvalidCastArg), }), - _ => return Err(ConstantSolvingError::InvalidCastArg), + _ => return Err(ConstantEvaluatorError::InvalidCastArg), }; Expression::Literal(literal) } @@ -537,44 +726,61 @@ impl<'a> ConstantSolver<'a> { ty, components: ref src_components, } => { - match self.types[ty].inner { - TypeInner::Vector { .. } | TypeInner::Matrix { .. } => (), - _ => return Err(ConstantSolvingError::InvalidCastArg), - } + let ty_inner = match self.types[ty].inner { + TypeInner::Vector { size, .. } => TypeInner::Vector { + size, + kind, + width: target_width, + }, + TypeInner::Matrix { columns, rows, .. } => TypeInner::Matrix { + columns, + rows, + width: target_width, + }, + _ => return Err(ConstantEvaluatorError::InvalidCastArg), + }; let mut components = src_components.clone(); for component in &mut components { *component = self.cast(*component, kind, target_width, span)?; } + let ty = self.types.insert( + Type { + name: None, + inner: ty_inner, + }, + span, + ); + Expression::Compose { ty, components } } - _ => return Err(ConstantSolvingError::InvalidCastArg), + _ => return Err(ConstantEvaluatorError::InvalidCastArg), }; - Ok(self.register_constant(expr, span)) + Ok(self.register_evaluated_expr(expr, span)) } fn unary_op( &mut self, op: UnaryOperator, expr: Handle, - span: crate::Span, - ) -> Result, ConstantSolvingError> { - let expr = self.eval_zero_value(expr, span)?; + span: Span, + ) -> Result, ConstantEvaluatorError> { + let expr = self.eval_zero_value_and_splat(expr, span)?; - let expr = match self.const_expressions[expr] { + let expr = match self.expressions[expr] { Expression::Literal(value) => Expression::Literal(match op { UnaryOperator::Negate => match value { Literal::I32(v) => Literal::I32(-v), Literal::F32(v) => Literal::F32(-v), - _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + _ => return Err(ConstantEvaluatorError::InvalidUnaryOpArg), }, UnaryOperator::Not => match value { Literal::I32(v) => Literal::I32(!v), Literal::U32(v) => Literal::U32(!v), Literal::Bool(v) => Literal::Bool(!v), - _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + _ => return Err(ConstantEvaluatorError::InvalidUnaryOpArg), }, }), Expression::Compose { @@ -583,7 +789,7 @@ impl<'a> ConstantSolver<'a> { } => { match self.types[ty].inner { TypeInner::Vector { .. } | TypeInner::Matrix { .. } => (), - _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + _ => return Err(ConstantEvaluatorError::InvalidUnaryOpArg), } let mut components = src_components.clone(); @@ -593,10 +799,10 @@ impl<'a> ConstantSolver<'a> { Expression::Compose { ty, components } } - _ => return Err(ConstantSolvingError::InvalidUnaryOpArg), + _ => return Err(ConstantEvaluatorError::InvalidUnaryOpArg), }; - Ok(self.register_constant(expr, span)) + Ok(self.register_evaluated_expr(expr, span)) } fn binary_op( @@ -604,15 +810,12 @@ impl<'a> ConstantSolver<'a> { op: BinaryOperator, left: Handle, right: Handle, - span: crate::Span, - ) -> Result, ConstantSolvingError> { - let left = self.eval_zero_value(left, span)?; - let right = self.eval_zero_value(right, span)?; + span: Span, + ) -> Result, ConstantEvaluatorError> { + let left = self.eval_zero_value_and_splat(left, span)?; + let right = self.eval_zero_value_and_splat(right, span)?; - let expr = match ( - &self.const_expressions[left], - &self.const_expressions[right], - ) { + let expr = match (&self.expressions[left], &self.expressions[right]) { (&Expression::Literal(left_value), &Expression::Literal(right_value)) => { let literal = match op { BinaryOperator::Equal => Literal::Bool(left_value == right_value), @@ -632,12 +835,12 @@ impl<'a> ConstantSolver<'a> { BinaryOperator::And => a & b, BinaryOperator::ExclusiveOr => a ^ b, BinaryOperator::InclusiveOr => a | b, - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }), (Literal::I32(a), Literal::U32(b)) => Literal::I32(match op { BinaryOperator::ShiftLeft => a.wrapping_shl(b), BinaryOperator::ShiftRight => a.wrapping_shr(b), - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }), (Literal::U32(a), Literal::U32(b)) => Literal::U32(match op { BinaryOperator::Add => a.wrapping_add(b), @@ -650,7 +853,7 @@ impl<'a> ConstantSolver<'a> { BinaryOperator::InclusiveOr => a | b, BinaryOperator::ShiftLeft => a.wrapping_shl(b), BinaryOperator::ShiftRight => a.wrapping_shr(b), - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }), (Literal::F32(a), Literal::F32(b)) => Literal::F32(match op { BinaryOperator::Add => a + b, @@ -658,14 +861,14 @@ impl<'a> ConstantSolver<'a> { BinaryOperator::Multiply => a * b, BinaryOperator::Divide => a / b, BinaryOperator::Modulo => a - b * (a / b).floor(), - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }), (Literal::Bool(a), Literal::Bool(b)) => Literal::Bool(match op { BinaryOperator::LogicalAnd => a && b, BinaryOperator::LogicalOr => a || b, - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }), - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }, }; Expression::Literal(literal) @@ -696,14 +899,43 @@ impl<'a> ConstantSolver<'a> { } Expression::Compose { ty, components } } - _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs), + _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }; - Ok(self.register_constant(expr, span)) + Ok(self.register_evaluated_expr(expr, span)) } - fn register_constant(&mut self, expr: Expression, span: crate::Span) -> Handle { - self.const_expressions.append(expr, span) + fn copy_from( + &mut self, + handle: Handle, + expressions: &Arena, + ) -> Result, ConstantEvaluatorError> { + let span = expressions.get_span(handle); + match expressions[handle] { + ref expr @ (Expression::Literal(_) + | Expression::Constant(_) + | Expression::ZeroValue(_)) => Ok(self.register_evaluated_expr(expr.clone(), span)), + Expression::Compose { ty, ref components } => { + let mut components = components.clone(); + for component in &mut components { + *component = self.copy_from(*component, expressions)?; + } + Ok(self.register_evaluated_expr(Expression::Compose { ty, components }, span)) + } + Expression::Splat { size, value } => { + let value = self.copy_from(value, expressions)?; + Ok(self.register_evaluated_expr(Expression::Splat { size, value }, span)) + } + _ => Err(ConstantEvaluatorError::SubexpressionsAreNotConstant), + } + } + + fn register_evaluated_expr(&mut self, expr: Expression, span: Span) -> Handle { + if let Some(ref mut append) = self.append { + append(self.expressions, expr, span) + } else { + self.expressions.append(expr, span) + } } } @@ -767,7 +999,7 @@ mod tests { UniqueArena, VectorSize, }; - use super::ConstantSolver; + use super::ConstantEvaluator; #[test] fn nan_handling() { @@ -785,7 +1017,6 @@ mod tests { #[test] fn unary_op() { let mut types = UniqueArena::new(); - let mut expressions = Arena::new(); let mut constants = Arena::new(); let mut const_expressions = Arena::new(); @@ -850,43 +1081,49 @@ mod tests { Default::default(), ); - let expr = expressions.append(Expression::Constant(h), Default::default()); - let expr1 = expressions.append(Expression::Constant(vec_h), Default::default()); + let expr = const_expressions.append(Expression::Constant(h), Default::default()); + let expr1 = const_expressions.append(Expression::Constant(vec_h), Default::default()); - let root1 = expressions.append( - Expression::Unary { - op: UnaryOperator::Negate, - expr, - }, - Default::default(), - ); - - let root2 = expressions.append( - Expression::Unary { - op: UnaryOperator::Not, - expr, - }, - Default::default(), - ); - - let root3 = expressions.append( - Expression::Unary { - op: UnaryOperator::Not, - expr: expr1, - }, - Default::default(), - ); - - let mut solver = ConstantSolver { - types: &mut types, - expressions: &expressions, - constants: &mut constants, - const_expressions: &mut const_expressions, + let expr2 = Expression::Unary { + op: UnaryOperator::Negate, + expr, }; - let res1 = solver.solve(root1).unwrap(); - let res2 = solver.solve(root2).unwrap(); - let res3 = solver.solve(root3).unwrap(); + let expr3 = Expression::Unary { + op: UnaryOperator::Not, + expr, + }; + + let expr4 = Expression::Unary { + op: UnaryOperator::Not, + expr: expr1, + }; + + let mut solver = ConstantEvaluator { + types: &mut types, + constants: &constants, + expressions: &mut const_expressions, + const_expressions: None, + append: None::< + Box< + dyn FnMut( + &mut Arena, + Expression, + crate::Span, + ) -> crate::Handle, + >, + >, + }; + + let res1 = solver + .try_eval_and_append(&expr2, Default::default()) + .unwrap(); + let res2 = solver + .try_eval_and_append(&expr3, Default::default()) + .unwrap(); + let res3 = solver + .try_eval_and_append(&expr4, Default::default()) + .unwrap(); assert_eq!( const_expressions[res1], @@ -924,7 +1161,6 @@ mod tests { #[test] fn cast() { let mut types = UniqueArena::new(); - let mut expressions = Arena::new(); let mut constants = Arena::new(); let mut const_expressions = Arena::new(); @@ -950,25 +1186,33 @@ mod tests { Default::default(), ); - let expr = expressions.append(Expression::Constant(h), Default::default()); + let expr = const_expressions.append(Expression::Constant(h), Default::default()); - let root = expressions.append( - Expression::As { - expr, - kind: ScalarKind::Bool, - convert: Some(crate::BOOL_WIDTH), - }, - Default::default(), - ); - - let mut solver = ConstantSolver { - types: &mut types, - expressions: &expressions, - constants: &mut constants, - const_expressions: &mut const_expressions, + let root = Expression::As { + expr, + kind: ScalarKind::Bool, + convert: Some(crate::BOOL_WIDTH), }; - let res = solver.solve(root).unwrap(); + let mut solver = ConstantEvaluator { + types: &mut types, + constants: &constants, + expressions: &mut const_expressions, + const_expressions: None, + append: None::< + Box< + dyn FnMut( + &mut Arena, + Expression, + crate::Span, + ) -> crate::Handle, + >, + >, + }; + + let res = solver + .try_eval_and_append(&root, Default::default()) + .unwrap(); assert_eq!( const_expressions[res], @@ -979,7 +1223,6 @@ mod tests { #[test] fn access() { let mut types = UniqueArena::new(); - let mut expressions = Arena::new(); let mut constants = Arena::new(); let mut const_expressions = Arena::new(); @@ -1076,28 +1319,38 @@ mod tests { Default::default(), ); - let base = expressions.append(Expression::Constant(h), Default::default()); - let root1 = expressions.append( - Expression::AccessIndex { base, index: 1 }, - Default::default(), - ); - let root2 = expressions.append( - Expression::AccessIndex { - base: root1, - index: 2, - }, - Default::default(), - ); + let base = const_expressions.append(Expression::Constant(h), Default::default()); - let mut solver = ConstantSolver { + let mut solver = ConstantEvaluator { types: &mut types, - expressions: &expressions, - constants: &mut constants, - const_expressions: &mut const_expressions, + constants: &constants, + expressions: &mut const_expressions, + const_expressions: None, + append: None::< + Box< + dyn FnMut( + &mut Arena, + Expression, + crate::Span, + ) -> crate::Handle, + >, + >, }; - let res1 = solver.solve(root1).unwrap(); - let res2 = solver.solve(root2).unwrap(); + let root1 = Expression::AccessIndex { base, index: 1 }; + + let res1 = solver + .try_eval_and_append(&root1, Default::default()) + .unwrap(); + + let root2 = Expression::AccessIndex { + base: res1, + index: 2, + }; + + let res2 = solver + .try_eval_and_append(&root2, Default::default()) + .unwrap(); match const_expressions[res1] { Expression::Compose { diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 0d12126ac..c91e0cb3e 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -2,12 +2,14 @@ [`Module`](super::Module) processing functionality. */ +mod constant_evaluator; pub mod index; mod layouter; mod namer; mod terminator; mod typifier; +pub use constant_evaluator::{ConstantEvaluator, ConstantEvaluatorError}; pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength, IndexableLengthError}; pub use layouter::{Alignment, LayoutError, LayoutErrorInner, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; @@ -590,28 +592,39 @@ impl GlobalCtx<'_> { handle: crate::Handle, arena: &crate::Arena, ) -> Result { + match self.eval_expr_to_literal_from(handle, arena) { + Some(crate::Literal::U32(value)) => Ok(value), + Some(crate::Literal::I32(value)) => { + value.try_into().map_err(|_| U32EvalError::Negative) + } + _ => Err(U32EvalError::NonConst), + } + } + + pub(crate) fn eval_expr_to_literal( + &self, + handle: crate::Handle, + ) -> Option { + self.eval_expr_to_literal_from(handle, self.const_expressions) + } + + pub(crate) fn eval_expr_to_literal_from( + &self, + handle: crate::Handle, + arena: &crate::Arena, + ) -> Option { fn get( gctx: GlobalCtx, handle: crate::Handle, arena: &crate::Arena, - ) -> Result { + ) -> Option { match arena[handle] { - crate::Expression::Literal(crate::Literal::U32(value)) => Ok(value), - crate::Expression::Literal(crate::Literal::I32(value)) => { - value.try_into().map_err(|_| U32EvalError::Negative) - } - crate::Expression::ZeroValue(ty) - if matches!( - gctx.types[ty].inner, - crate::TypeInner::Scalar { - kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint, - width: _ - } - ) => - { - Ok(0) - } - _ => Err(U32EvalError::NonConst), + crate::Expression::Literal(literal) => Some(literal), + crate::Expression::ZeroValue(ty) => match gctx.types[ty].inner { + crate::TypeInner::Scalar { kind, width } => crate::Literal::zero(kind, width), + _ => None, + }, + _ => None, } } match arena[handle] { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 0b6125368..af4b774f1 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -134,6 +134,8 @@ pub enum ConstExpressionError { NonConst, #[error(transparent)] Compose(#[from] super::ComposeError), + #[error("Splatting {0:?} can't be done")] + InvalidSplatType(Handle), #[error("Type resolution failed")] Type(#[from] ResolveError), #[error(transparent)] @@ -196,6 +198,10 @@ impl super::Validator { components.iter().map(|&handle| mod_info[handle].clone()), )?; } + E::Splat { value, .. } => match *mod_info[value].inner_with(gctx.types) { + crate::TypeInner::Scalar { .. } => {} + _ => return Err(super::ConstExpressionError::InvalidSplatType(value)), + }, _ => return Err(super::ConstExpressionError::NonConst), } diff --git a/tests/out/glsl/constructors.main.Compute.glsl b/tests/out/glsl/constructors.main.Compute.glsl index 112795eda..8ef0a60ba 100644 --- a/tests/out/glsl/constructors.main.Compute.glsl +++ b/tests/out/glsl/constructors.main.Compute.glsl @@ -32,11 +32,8 @@ void main() { mat2x2 cit1_ = mat2x2(vec2(0.0), vec2(0.0)); int cit2_[4] = int[4](0, 1, 2, 3); bool ic0_ = bool(false); - int ic1_ = int(0); - uint ic2_ = uint(0u); - float ic3_ = float(0.0); - uvec2 ic4_ = uvec2(uvec2(0u)); - mat2x3 ic5_ = mat2x3(mat2x3(0.0)); + uvec2 ic4_ = uvec2(0u, 0u); + mat2x3 ic5_ = mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); uvec2 ic6_ = uvec2(0u); mat2x3 ic7_ = mat2x3(0.0); } diff --git a/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl b/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl index ac9bc6de4..933953283 100644 --- a/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl +++ b/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl @@ -9,8 +9,8 @@ uniform highp samplerCubeArrayShadow _group_0_binding_4_fs; layout(location = 0) out vec4 _fs2p_location0; void main() { - vec3 frag_ls = vec4(1.0, 1.0, 2.0, 1.0).xyz; - float a = texture(_group_0_binding_4_fs, vec4(frag_ls, int(1)), 1.0); + vec3 frag_ls = vec3(1.0, 1.0, 2.0); + float a = texture(_group_0_binding_4_fs, vec4(frag_ls, 1), 1.0); _fs2p_location0 = vec4(a, 1.0, 1.0, 1.0); return; } diff --git a/tests/out/glsl/image.texture_sample.Fragment.glsl b/tests/out/glsl/image.texture_sample.Fragment.glsl index 97be5a59d..dc17cedc2 100644 --- a/tests/out/glsl/image.texture_sample.Fragment.glsl +++ b/tests/out/glsl/image.texture_sample.Fragment.glsl @@ -18,74 +18,74 @@ void main() { vec4 a = vec4(0.0); vec2 tc = vec2(0.5); vec3 tc3_ = vec3(0.5); - vec4 _e9 = texture(_group_0_binding_0_fs, vec2(tc.x, 0.0)); - vec4 _e10 = a; - a = (_e10 + _e9); - vec4 _e14 = texture(_group_0_binding_1_fs, vec2(tc)); - vec4 _e15 = a; - a = (_e15 + _e14); - vec4 _e19 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1)); - vec4 _e20 = a; - a = (_e20 + _e19); - vec4 _e24 = textureLod(_group_0_binding_1_fs, vec2(tc), 2.3); - vec4 _e25 = a; - a = (_e25 + _e24); - vec4 _e29 = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.3, ivec2(3, 1)); - vec4 _e30 = a; - a = (_e30 + _e29); - vec4 _e35 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 2.0); - vec4 _e36 = a; - a = (_e36 + _e35); - vec4 _e41 = texture(_group_0_binding_4_fs, vec3(tc, 0u)); - vec4 _e42 = a; - a = (_e42 + _e41); - vec4 _e47 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1)); - vec4 _e48 = a; - a = (_e48 + _e47); - vec4 _e53 = textureLod(_group_0_binding_4_fs, vec3(tc, 0u), 2.3); - vec4 _e54 = a; - a = (_e54 + _e53); - vec4 _e59 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0u), 2.3, ivec2(3, 1)); - vec4 _e60 = a; - a = (_e60 + _e59); - vec4 _e66 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1), 2.0); - vec4 _e67 = a; - a = (_e67 + _e66); - vec4 _e72 = texture(_group_0_binding_4_fs, vec3(tc, 0)); - vec4 _e73 = a; - a = (_e73 + _e72); - vec4 _e78 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1)); - vec4 _e79 = a; - a = (_e79 + _e78); - vec4 _e84 = textureLod(_group_0_binding_4_fs, vec3(tc, 0), 2.3); - vec4 _e85 = a; - a = (_e85 + _e84); - vec4 _e90 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0), 2.3, ivec2(3, 1)); - vec4 _e91 = a; - a = (_e91 + _e90); - vec4 _e97 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1), 2.0); - vec4 _e98 = a; - a = (_e98 + _e97); - vec4 _e103 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u)); - vec4 _e104 = a; - a = (_e104 + _e103); - vec4 _e109 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.3); - vec4 _e110 = a; - a = (_e110 + _e109); - vec4 _e116 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.0); - vec4 _e117 = a; - a = (_e117 + _e116); - vec4 _e122 = texture(_group_0_binding_6_fs, vec4(tc3_, 0)); - vec4 _e123 = a; - a = (_e123 + _e122); - vec4 _e128 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0), 2.3); - vec4 _e129 = a; - a = (_e129 + _e128); - vec4 _e135 = texture(_group_0_binding_6_fs, vec4(tc3_, 0), 2.0); - vec4 _e136 = a; - a = (_e136 + _e135); - vec4 _e138 = a; - _fs2p_location0 = _e138; + vec4 _e8 = texture(_group_0_binding_0_fs, vec2(0.5, 0.0)); + vec4 _e9 = a; + a = (_e9 + _e8); + vec4 _e13 = texture(_group_0_binding_1_fs, vec2(tc)); + vec4 _e14 = a; + a = (_e14 + _e13); + vec4 _e18 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1)); + vec4 _e19 = a; + a = (_e19 + _e18); + vec4 _e23 = textureLod(_group_0_binding_1_fs, vec2(tc), 2.3); + vec4 _e24 = a; + a = (_e24 + _e23); + vec4 _e28 = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.3, ivec2(3, 1)); + vec4 _e29 = a; + a = (_e29 + _e28); + vec4 _e34 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 2.0); + vec4 _e35 = a; + a = (_e35 + _e34); + vec4 _e40 = texture(_group_0_binding_4_fs, vec3(tc, 0u)); + vec4 _e41 = a; + a = (_e41 + _e40); + vec4 _e46 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1)); + vec4 _e47 = a; + a = (_e47 + _e46); + vec4 _e52 = textureLod(_group_0_binding_4_fs, vec3(tc, 0u), 2.3); + vec4 _e53 = a; + a = (_e53 + _e52); + vec4 _e58 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0u), 2.3, ivec2(3, 1)); + vec4 _e59 = a; + a = (_e59 + _e58); + vec4 _e65 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1), 2.0); + vec4 _e66 = a; + a = (_e66 + _e65); + vec4 _e71 = texture(_group_0_binding_4_fs, vec3(tc, 0)); + vec4 _e72 = a; + a = (_e72 + _e71); + vec4 _e77 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1)); + vec4 _e78 = a; + a = (_e78 + _e77); + vec4 _e83 = textureLod(_group_0_binding_4_fs, vec3(tc, 0), 2.3); + vec4 _e84 = a; + a = (_e84 + _e83); + vec4 _e89 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0), 2.3, ivec2(3, 1)); + vec4 _e90 = a; + a = (_e90 + _e89); + vec4 _e96 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1), 2.0); + vec4 _e97 = a; + a = (_e97 + _e96); + vec4 _e102 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u)); + vec4 _e103 = a; + a = (_e103 + _e102); + vec4 _e108 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.3); + vec4 _e109 = a; + a = (_e109 + _e108); + vec4 _e115 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.0); + vec4 _e116 = a; + a = (_e116 + _e115); + vec4 _e121 = texture(_group_0_binding_6_fs, vec4(tc3_, 0)); + vec4 _e122 = a; + a = (_e122 + _e121); + vec4 _e127 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0), 2.3); + vec4 _e128 = a; + a = (_e128 + _e127); + vec4 _e134 = texture(_group_0_binding_6_fs, vec4(tc3_, 0), 2.0); + vec4 _e135 = a; + a = (_e135 + _e134); + vec4 _e137 = a; + _fs2p_location0 = _e137; return; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index ba3734be1..1ed88c102 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -17,9 +17,9 @@ vec4 builtins() { vec4 s3_ = mix(v_f32_one, v_f32_zero, bvec4(false, false, false, false)); vec4 m1_ = mix(v_f32_zero, v_f32_one, v_f32_half); vec4 m2_ = mix(v_f32_zero, v_f32_one, 0.1); - float b1_ = intBitsToFloat(v_i32_one.x); + float b1_ = intBitsToFloat(1); vec4 b2_ = intBitsToFloat(v_i32_one); - ivec4 v_i32_zero = ivec4(v_f32_zero); + ivec4 v_i32_zero = ivec4(0, 0, 0, 0); return (((((vec4((ivec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } @@ -48,10 +48,7 @@ vec3 bool_cast(vec3 x) { } void logical() { - bool neg0_ = !(true); - bvec2 neg1_ = not(bvec2(true)); - bool or = (true || false); - bool and = (true && false); + bvec2 neg1_ = bvec2(false, false); bool bitwise_or0_ = (true || false); bvec3 bitwise_or1_ = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); bool bitwise_and0_ = (true && false); @@ -59,140 +56,95 @@ void logical() { } void arithmetic() { - ivec2 neg1_1 = -(ivec2(1)); - vec2 neg2_ = -(vec2(1.0)); - int add0_ = (2 + 1); - uint add1_ = (2u + 1u); - float add2_ = (2.0 + 1.0); + ivec2 neg1_1 = ivec2(-1, -1); + vec2 neg2_ = vec2(-1.0, -1.0); ivec2 add3_ = (ivec2(2) + ivec2(1)); uvec3 add4_ = (uvec3(2u) + uvec3(1u)); vec4 add5_ = (vec4(2.0) + vec4(1.0)); - int sub0_ = (2 - 1); - uint sub1_ = (2u - 1u); - float sub2_ = (2.0 - 1.0); ivec2 sub3_ = (ivec2(2) - ivec2(1)); uvec3 sub4_ = (uvec3(2u) - uvec3(1u)); vec4 sub5_ = (vec4(2.0) - vec4(1.0)); - int mul0_ = (2 * 1); - uint mul1_ = (2u * 1u); - float mul2_ = (2.0 * 1.0); ivec2 mul3_ = (ivec2(2) * ivec2(1)); uvec3 mul4_ = (uvec3(2u) * uvec3(1u)); vec4 mul5_ = (vec4(2.0) * vec4(1.0)); - int div0_ = (2 / 1); - uint div1_ = (2u / 1u); - float div2_ = (2.0 / 1.0); ivec2 div3_ = (ivec2(2) / ivec2(1)); uvec3 div4_ = (uvec3(2u) / uvec3(1u)); vec4 div5_ = (vec4(2.0) / vec4(1.0)); - int rem0_ = (2 % 1); - uint rem1_ = (2u % 1u); - float rem2_ = (2.0 - 1.0 * trunc(2.0 / 1.0)); ivec2 rem3_ = (ivec2(2) % ivec2(1)); uvec3 rem4_ = (uvec3(2u) % uvec3(1u)); vec4 rem5_ = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); { - ivec2 add0_1 = (ivec2(2) + ivec2(1)); - ivec2 add1_1 = (ivec2(2) + ivec2(1)); - uvec2 add2_1 = (uvec2(2u) + uvec2(1u)); + ivec2 add0_ = (ivec2(2) + ivec2(1)); + ivec2 add1_ = (ivec2(2) + ivec2(1)); + uvec2 add2_ = (uvec2(2u) + uvec2(1u)); uvec2 add3_1 = (uvec2(2u) + uvec2(1u)); vec2 add4_1 = (vec2(2.0) + vec2(1.0)); vec2 add5_1 = (vec2(2.0) + vec2(1.0)); - ivec2 sub0_1 = (ivec2(2) - ivec2(1)); - ivec2 sub1_1 = (ivec2(2) - ivec2(1)); - uvec2 sub2_1 = (uvec2(2u) - uvec2(1u)); + ivec2 sub0_ = (ivec2(2) - ivec2(1)); + ivec2 sub1_ = (ivec2(2) - ivec2(1)); + uvec2 sub2_ = (uvec2(2u) - uvec2(1u)); uvec2 sub3_1 = (uvec2(2u) - uvec2(1u)); vec2 sub4_1 = (vec2(2.0) - vec2(1.0)); vec2 sub5_1 = (vec2(2.0) - vec2(1.0)); - ivec2 mul0_1 = (ivec2(2) * 1); - ivec2 mul1_1 = (2 * ivec2(1)); - uvec2 mul2_1 = (uvec2(2u) * 1u); - uvec2 mul3_1 = (2u * uvec2(1u)); - vec2 mul4_1 = (vec2(2.0) * 1.0); - vec2 mul5_1 = (2.0 * vec2(1.0)); - ivec2 div0_1 = (ivec2(2) / ivec2(1)); - ivec2 div1_1 = (ivec2(2) / ivec2(1)); - uvec2 div2_1 = (uvec2(2u) / uvec2(1u)); + ivec2 mul0_ = ivec2(2, 2); + ivec2 mul1_ = ivec2(2, 2); + uvec2 mul2_ = uvec2(2u, 2u); + uvec2 mul3_1 = uvec2(2u, 2u); + vec2 mul4_1 = vec2(2.0, 2.0); + vec2 mul5_1 = vec2(2.0, 2.0); + ivec2 div0_ = (ivec2(2) / ivec2(1)); + ivec2 div1_ = (ivec2(2) / ivec2(1)); + uvec2 div2_ = (uvec2(2u) / uvec2(1u)); uvec2 div3_1 = (uvec2(2u) / uvec2(1u)); vec2 div4_1 = (vec2(2.0) / vec2(1.0)); vec2 div5_1 = (vec2(2.0) / vec2(1.0)); - ivec2 rem0_1 = (ivec2(2) % ivec2(1)); - ivec2 rem1_1 = (ivec2(2) % ivec2(1)); - uvec2 rem2_1 = (uvec2(2u) % uvec2(1u)); + ivec2 rem0_ = (ivec2(2) % ivec2(1)); + ivec2 rem1_ = (ivec2(2) % ivec2(1)); + uvec2 rem2_ = (uvec2(2u) % uvec2(1u)); uvec2 rem3_1 = (uvec2(2u) % uvec2(1u)); vec2 rem4_1 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); vec2 rem5_1 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); } mat3x3 add = (mat3x3(0.0) + mat3x3(0.0)); mat3x3 sub = (mat3x3(0.0) - mat3x3(0.0)); - mat3x3 mul_scalar0_ = (mat3x3(0.0) * 1.0); - mat3x3 mul_scalar1_ = (2.0 * mat3x3(0.0)); + mat3x3 mul_scalar0_ = mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); + mat3x3 mul_scalar1_ = mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); vec3 mul_vector0_ = (mat4x3(0.0) * vec4(1.0)); vec4 mul_vector1_ = (vec3(2.0) * mat4x3(0.0)); mat3x3 mul = (mat4x3(0.0) * mat3x4(0.0)); } void bit() { - int flip0_ = ~(1); - uint flip1_ = ~(1u); - ivec2 flip2_ = ~(ivec2(1)); - uvec3 flip3_ = ~(uvec3(1u)); - int or0_ = (2 | 1); - uint or1_ = (2u | 1u); + ivec2 flip2_ = ivec2(-2, -2); + uvec3 flip3_ = uvec3(4294967294u, 4294967294u, 4294967294u); ivec2 or2_ = (ivec2(2) | ivec2(1)); uvec3 or3_ = (uvec3(2u) | uvec3(1u)); - int and0_ = (2 & 1); - uint and1_ = (2u & 1u); ivec2 and2_ = (ivec2(2) & ivec2(1)); uvec3 and3_ = (uvec3(2u) & uvec3(1u)); - int xor0_ = (2 ^ 1); - uint xor1_ = (2u ^ 1u); ivec2 xor2_ = (ivec2(2) ^ ivec2(1)); uvec3 xor3_ = (uvec3(2u) ^ uvec3(1u)); - int shl0_ = (2 << 1u); - uint shl1_ = (2u << 1u); ivec2 shl2_ = (ivec2(2) << uvec2(1u)); uvec3 shl3_ = (uvec3(2u) << uvec3(1u)); - int shr0_ = (2 >> 1u); - uint shr1_ = (2u >> 1u); ivec2 shr2_ = (ivec2(2) >> uvec2(1u)); uvec3 shr3_ = (uvec3(2u) >> uvec3(1u)); } void comparison() { - bool eq0_ = (2 == 1); - bool eq1_ = (2u == 1u); - bool eq2_ = (2.0 == 1.0); bvec2 eq3_ = equal(ivec2(2), ivec2(1)); bvec3 eq4_ = equal(uvec3(2u), uvec3(1u)); bvec4 eq5_ = equal(vec4(2.0), vec4(1.0)); - bool neq0_ = (2 != 1); - bool neq1_ = (2u != 1u); - bool neq2_ = (2.0 != 1.0); bvec2 neq3_ = notEqual(ivec2(2), ivec2(1)); bvec3 neq4_ = notEqual(uvec3(2u), uvec3(1u)); bvec4 neq5_ = notEqual(vec4(2.0), vec4(1.0)); - bool lt0_ = (2 < 1); - bool lt1_ = (2u < 1u); - bool lt2_ = (2.0 < 1.0); bvec2 lt3_ = lessThan(ivec2(2), ivec2(1)); bvec3 lt4_ = lessThan(uvec3(2u), uvec3(1u)); bvec4 lt5_ = lessThan(vec4(2.0), vec4(1.0)); - bool lte0_ = (2 <= 1); - bool lte1_ = (2u <= 1u); - bool lte2_ = (2.0 <= 1.0); bvec2 lte3_ = lessThanEqual(ivec2(2), ivec2(1)); bvec3 lte4_ = lessThanEqual(uvec3(2u), uvec3(1u)); bvec4 lte5_ = lessThanEqual(vec4(2.0), vec4(1.0)); - bool gt0_ = (2 > 1); - bool gt1_ = (2u > 1u); - bool gt2_ = (2.0 > 1.0); bvec2 gt3_ = greaterThan(ivec2(2), ivec2(1)); bvec3 gt4_ = greaterThan(uvec3(2u), uvec3(1u)); bvec4 gt5_ = greaterThan(vec4(2.0), vec4(1.0)); - bool gte0_ = (2 >= 1); - bool gte1_ = (2u >= 1u); - bool gte2_ = (2.0 >= 1.0); bvec2 gte3_ = greaterThanEqual(ivec2(2), ivec2(1)); bvec3 gte4_ = greaterThanEqual(uvec3(2u), uvec3(1u)); bvec4 gte5_ = greaterThanEqual(vec4(2.0), vec4(1.0)); @@ -237,19 +189,13 @@ void assignment() { } void negation_avoids_prefix_decrement() { - int p1_ = -(-2); - int p2_ = -(-3); - int p3_ = -(-(4)); - int p4_ = -(-(-5)); - int p5_ = -(-(-(-(6)))); - int p6_ = -(-(-(-(-7)))); - int p7_ = -(-(-(-(-8)))); + return; } void main() { vec4 _e0 = builtins(); vec4 _e1 = splat(); - vec3 _e4 = bool_cast(v_f32_one.xyz); + vec3 _e6 = bool_cast(vec3(1.0, 1.0, 1.0)); logical(); arithmetic(); bit(); diff --git a/tests/out/hlsl/constructors.hlsl b/tests/out/hlsl/constructors.hlsl index 3b9c06b0c..52de162f4 100644 --- a/tests/out/hlsl/constructors.hlsl +++ b/tests/out/hlsl/constructors.hlsl @@ -50,11 +50,8 @@ void main() float2x2 cit1_ = float2x2((0.0).xx, (0.0).xx); int cit2_[4] = Constructarray4_int_(0, 1, 2, 3); bool ic0_ = bool((bool)0); - int ic1_ = int((int)0); - uint ic2_ = uint((uint)0); - float ic3_ = float((float)0); - uint2 ic4_ = uint2((uint2)0); - float2x3 ic5_ = float2x3((float2x3)0); + uint2 ic4_ = uint2(0u, 0u); + float2x3 ic5_ = float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)); uint2 ic6_ = asuint((uint2)0); float2x3 ic7_ = asfloat((float2x3)0); } diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index e284813a1..05825e18c 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -246,74 +246,74 @@ float4 texture_sample() : SV_Target0 float2 tc = (0.5).xx; float3 tc3_ = (0.5).xxx; - float4 _expr9 = image_1d.Sample(sampler_reg, tc.x); - float4 _expr10 = a; - a = (_expr10 + _expr9); - float4 _expr14 = image_2d.Sample(sampler_reg, tc); - float4 _expr15 = a; - a = (_expr15 + _expr14); - float4 _expr19 = image_2d.Sample(sampler_reg, tc, int2(3, 1)); - float4 _expr20 = a; - a = (_expr20 + _expr19); - float4 _expr24 = image_2d.SampleLevel(sampler_reg, tc, 2.3); - float4 _expr25 = a; - a = (_expr25 + _expr24); - float4 _expr29 = image_2d.SampleLevel(sampler_reg, tc, 2.3, int2(3, 1)); - float4 _expr30 = a; - a = (_expr30 + _expr29); - float4 _expr35 = image_2d.SampleBias(sampler_reg, tc, 2.0, int2(3, 1)); - float4 _expr36 = a; - a = (_expr36 + _expr35); - float4 _expr41 = image_2d_array.Sample(sampler_reg, float3(tc, 0u)); - float4 _expr42 = a; - a = (_expr42 + _expr41); - float4 _expr47 = image_2d_array.Sample(sampler_reg, float3(tc, 0u), int2(3, 1)); - float4 _expr48 = a; - a = (_expr48 + _expr47); - float4 _expr53 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3); - float4 _expr54 = a; - a = (_expr54 + _expr53); - float4 _expr59 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3, int2(3, 1)); - float4 _expr60 = a; - a = (_expr60 + _expr59); - float4 _expr66 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0u), 2.0, int2(3, 1)); - float4 _expr67 = a; - a = (_expr67 + _expr66); - float4 _expr72 = image_2d_array.Sample(sampler_reg, float3(tc, 0)); - float4 _expr73 = a; - a = (_expr73 + _expr72); - float4 _expr78 = image_2d_array.Sample(sampler_reg, float3(tc, 0), int2(3, 1)); - float4 _expr79 = a; - a = (_expr79 + _expr78); - float4 _expr84 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3); - float4 _expr85 = a; - a = (_expr85 + _expr84); - float4 _expr90 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3, int2(3, 1)); - float4 _expr91 = a; - a = (_expr91 + _expr90); - float4 _expr97 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0), 2.0, int2(3, 1)); - float4 _expr98 = a; - a = (_expr98 + _expr97); - float4 _expr103 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0u)); - float4 _expr104 = a; - a = (_expr104 + _expr103); - float4 _expr109 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0u), 2.3); - float4 _expr110 = a; - a = (_expr110 + _expr109); - float4 _expr116 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0u), 2.0); - float4 _expr117 = a; - a = (_expr117 + _expr116); - float4 _expr122 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0)); - float4 _expr123 = a; - a = (_expr123 + _expr122); - float4 _expr128 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0), 2.3); - float4 _expr129 = a; - a = (_expr129 + _expr128); - float4 _expr135 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0), 2.0); - float4 _expr136 = a; - a = (_expr136 + _expr135); - float4 _expr138 = a; - return _expr138; + float4 _expr8 = image_1d.Sample(sampler_reg, 0.5); + float4 _expr9 = a; + a = (_expr9 + _expr8); + float4 _expr13 = image_2d.Sample(sampler_reg, tc); + float4 _expr14 = a; + a = (_expr14 + _expr13); + float4 _expr18 = image_2d.Sample(sampler_reg, tc, int2(int2(3, 1))); + float4 _expr19 = a; + a = (_expr19 + _expr18); + float4 _expr23 = image_2d.SampleLevel(sampler_reg, tc, 2.3); + float4 _expr24 = a; + a = (_expr24 + _expr23); + float4 _expr28 = image_2d.SampleLevel(sampler_reg, tc, 2.3, int2(int2(3, 1))); + float4 _expr29 = a; + a = (_expr29 + _expr28); + float4 _expr34 = image_2d.SampleBias(sampler_reg, tc, 2.0, int2(int2(3, 1))); + float4 _expr35 = a; + a = (_expr35 + _expr34); + float4 _expr40 = image_2d_array.Sample(sampler_reg, float3(tc, 0u)); + float4 _expr41 = a; + a = (_expr41 + _expr40); + float4 _expr46 = image_2d_array.Sample(sampler_reg, float3(tc, 0u), int2(int2(3, 1))); + float4 _expr47 = a; + a = (_expr47 + _expr46); + float4 _expr52 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3); + float4 _expr53 = a; + a = (_expr53 + _expr52); + float4 _expr58 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3, int2(int2(3, 1))); + float4 _expr59 = a; + a = (_expr59 + _expr58); + float4 _expr65 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0u), 2.0, int2(int2(3, 1))); + float4 _expr66 = a; + a = (_expr66 + _expr65); + float4 _expr71 = image_2d_array.Sample(sampler_reg, float3(tc, 0)); + float4 _expr72 = a; + a = (_expr72 + _expr71); + float4 _expr77 = image_2d_array.Sample(sampler_reg, float3(tc, 0), int2(int2(3, 1))); + float4 _expr78 = a; + a = (_expr78 + _expr77); + float4 _expr83 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3); + float4 _expr84 = a; + a = (_expr84 + _expr83); + float4 _expr89 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3, int2(int2(3, 1))); + float4 _expr90 = a; + a = (_expr90 + _expr89); + float4 _expr96 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0), 2.0, int2(int2(3, 1))); + float4 _expr97 = a; + a = (_expr97 + _expr96); + float4 _expr102 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0u)); + float4 _expr103 = a; + a = (_expr103 + _expr102); + float4 _expr108 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0u), 2.3); + float4 _expr109 = a; + a = (_expr109 + _expr108); + float4 _expr115 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0u), 2.0); + float4 _expr116 = a; + a = (_expr116 + _expr115); + float4 _expr121 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0)); + float4 _expr122 = a; + a = (_expr122 + _expr121); + float4 _expr127 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0), 2.3); + float4 _expr128 = a; + a = (_expr128 + _expr127); + float4 _expr134 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0), 2.0); + float4 _expr135 = a; + a = (_expr135 + _expr134); + float4 _expr137 = a; + return _expr137; } float texture_sample_comparison() : SV_Target0 @@ -354,9 +354,9 @@ float4 gather() : SV_Target0 { float2 tc_2 = (0.5).xx; float4 s2d = image_2d.GatherGreen(sampler_reg, tc_2); - float4 s2d_offset = image_2d.GatherAlpha(sampler_reg, tc_2, int2(3, 1)); + float4 s2d_offset = image_2d.GatherAlpha(sampler_reg, tc_2, int2(int2(3, 1))); float4 s2d_depth = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5); - float4 s2d_depth_offset = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5, int2(3, 1)); + float4 s2d_depth_offset = image_2d_depth.GatherCmp(sampler_cmp, tc_2, 0.5, int2(int2(3, 1))); uint4 u = image_2d_u32_.Gather(sampler_reg, tc_2); int4 i = image_2d_i32_.Gather(sampler_reg, tc_2); float4 f = (float4(u) + float4(i)); diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 846f567f9..90c6723e2 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -10,9 +10,9 @@ float4 builtins() float4 s3_ = (bool4(false, false, false, false) ? v_f32_zero : v_f32_one); float4 m1_ = lerp(v_f32_zero, v_f32_one, v_f32_half); float4 m2_ = lerp(v_f32_zero, v_f32_one, 0.1); - float b1_ = asfloat(v_i32_one.x); + float b1_ = asfloat(1); float4 b2_ = asfloat(v_i32_one); - int4 v_i32_zero = int4(v_f32_zero); + int4 v_i32_zero = int4(0, 0, 0, 0); return (((((float4(((s1_).xxxx + v_i32_zero)) + s2_) + m1_) + m2_) + (b1_).xxxx) + b2_); } @@ -46,10 +46,7 @@ float3 bool_cast(float3 x) void logical() { - bool neg0_ = !(true); - bool2 neg1_ = !((true).xx); - bool or_ = (true || false); - bool and_ = (true && false); + bool2 neg1_ = bool2(false, false); bool bitwise_or0_ = (true | false); bool3 bitwise_or1_ = ((true).xxx | (false).xxx); bool bitwise_and0_ = (true & false); @@ -58,74 +55,59 @@ void logical() void arithmetic() { - int2 neg1_1 = -((1).xx); - float2 neg2_ = -((1.0).xx); - int add0_ = (2 + 1); - uint add1_ = (2u + 1u); - float add2_ = (2.0 + 1.0); + int2 neg1_1 = int2(-1, -1); + float2 neg2_ = float2(-1.0, -1.0); int2 add3_ = ((2).xx + (1).xx); uint3 add4_ = ((2u).xxx + (1u).xxx); float4 add5_ = ((2.0).xxxx + (1.0).xxxx); - int sub0_ = (2 - 1); - uint sub1_ = (2u - 1u); - float sub2_ = (2.0 - 1.0); int2 sub3_ = ((2).xx - (1).xx); uint3 sub4_ = ((2u).xxx - (1u).xxx); float4 sub5_ = ((2.0).xxxx - (1.0).xxxx); - int mul0_ = (2 * 1); - uint mul1_ = (2u * 1u); - float mul2_ = (2.0 * 1.0); int2 mul3_ = ((2).xx * (1).xx); uint3 mul4_ = ((2u).xxx * (1u).xxx); float4 mul5_ = ((2.0).xxxx * (1.0).xxxx); - int div0_ = (2 / 1); - uint div1_ = (2u / 1u); - float div2_ = (2.0 / 1.0); int2 div3_ = ((2).xx / (1).xx); uint3 div4_ = ((2u).xxx / (1u).xxx); float4 div5_ = ((2.0).xxxx / (1.0).xxxx); - int rem0_ = (2 % 1); - uint rem1_ = (2u % 1u); - float rem2_ = fmod(2.0, 1.0); int2 rem3_ = ((2).xx % (1).xx); uint3 rem4_ = ((2u).xxx % (1u).xxx); float4 rem5_ = fmod((2.0).xxxx, (1.0).xxxx); { - int2 add0_1 = ((2).xx + (1).xx); - int2 add1_1 = ((2).xx + (1).xx); - uint2 add2_1 = ((2u).xx + (1u).xx); + int2 add0_ = ((2).xx + (1).xx); + int2 add1_ = ((2).xx + (1).xx); + uint2 add2_ = ((2u).xx + (1u).xx); uint2 add3_1 = ((2u).xx + (1u).xx); float2 add4_1 = ((2.0).xx + (1.0).xx); float2 add5_1 = ((2.0).xx + (1.0).xx); - int2 sub0_1 = ((2).xx - (1).xx); - int2 sub1_1 = ((2).xx - (1).xx); - uint2 sub2_1 = ((2u).xx - (1u).xx); + int2 sub0_ = ((2).xx - (1).xx); + int2 sub1_ = ((2).xx - (1).xx); + uint2 sub2_ = ((2u).xx - (1u).xx); uint2 sub3_1 = ((2u).xx - (1u).xx); float2 sub4_1 = ((2.0).xx - (1.0).xx); float2 sub5_1 = ((2.0).xx - (1.0).xx); - int2 mul0_1 = ((2).xx * 1); - int2 mul1_1 = (2 * (1).xx); - uint2 mul2_1 = ((2u).xx * 1u); - uint2 mul3_1 = (2u * (1u).xx); - float2 mul4_1 = ((2.0).xx * 1.0); - float2 mul5_1 = (2.0 * (1.0).xx); - int2 div0_1 = ((2).xx / (1).xx); - int2 div1_1 = ((2).xx / (1).xx); - uint2 div2_1 = ((2u).xx / (1u).xx); + int2 mul0_ = int2(2, 2); + int2 mul1_ = int2(2, 2); + uint2 mul2_ = uint2(2u, 2u); + uint2 mul3_1 = uint2(2u, 2u); + float2 mul4_1 = float2(2.0, 2.0); + float2 mul5_1 = float2(2.0, 2.0); + int2 div0_ = ((2).xx / (1).xx); + int2 div1_ = ((2).xx / (1).xx); + uint2 div2_ = ((2u).xx / (1u).xx); uint2 div3_1 = ((2u).xx / (1u).xx); float2 div4_1 = ((2.0).xx / (1.0).xx); float2 div5_1 = ((2.0).xx / (1.0).xx); - int2 rem0_1 = ((2).xx % (1).xx); - int2 rem1_1 = ((2).xx % (1).xx); - uint2 rem2_1 = ((2u).xx % (1u).xx); + int2 rem0_ = ((2).xx % (1).xx); + int2 rem1_ = ((2).xx % (1).xx); + uint2 rem2_ = ((2u).xx % (1u).xx); uint2 rem3_1 = ((2u).xx % (1u).xx); float2 rem4_1 = fmod((2.0).xx, (1.0).xx); float2 rem5_1 = fmod((2.0).xx, (1.0).xx); } float3x3 add = ((float3x3)0 + (float3x3)0); float3x3 sub = ((float3x3)0 - (float3x3)0); - float3x3 mul_scalar0_ = mul(1.0, (float3x3)0); - float3x3 mul_scalar1_ = mul((float3x3)0, 2.0); + float3x3 mul_scalar0_ = float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)); + float3x3 mul_scalar1_ = float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)); float3 mul_vector0_ = mul((1.0).xxxx, (float4x3)0); float4 mul_vector1_ = mul((float4x3)0, (2.0).xxx); float3x3 mul_ = mul((float3x4)0, (float4x3)0); @@ -133,67 +115,37 @@ void arithmetic() void bit() { - int flip0_ = ~(1); - uint flip1_ = ~(1u); - int2 flip2_ = ~((1).xx); - uint3 flip3_ = ~((1u).xxx); - int or0_ = (2 | 1); - uint or1_ = (2u | 1u); + int2 flip2_ = int2(-2, -2); + uint3 flip3_ = uint3(4294967294u, 4294967294u, 4294967294u); int2 or2_ = ((2).xx | (1).xx); uint3 or3_ = ((2u).xxx | (1u).xxx); - int and0_ = (2 & 1); - uint and1_ = (2u & 1u); int2 and2_ = ((2).xx & (1).xx); uint3 and3_ = ((2u).xxx & (1u).xxx); - int xor0_ = (2 ^ 1); - uint xor1_ = (2u ^ 1u); int2 xor2_ = ((2).xx ^ (1).xx); uint3 xor3_ = ((2u).xxx ^ (1u).xxx); - int shl0_ = (2 << 1u); - uint shl1_ = (2u << 1u); int2 shl2_ = ((2).xx << (1u).xx); uint3 shl3_ = ((2u).xxx << (1u).xxx); - int shr0_ = (2 >> 1u); - uint shr1_ = (2u >> 1u); int2 shr2_ = ((2).xx >> (1u).xx); uint3 shr3_ = ((2u).xxx >> (1u).xxx); } void comparison() { - bool eq0_ = (2 == 1); - bool eq1_ = (2u == 1u); - bool eq2_ = (2.0 == 1.0); bool2 eq3_ = ((2).xx == (1).xx); bool3 eq4_ = ((2u).xxx == (1u).xxx); bool4 eq5_ = ((2.0).xxxx == (1.0).xxxx); - bool neq0_ = (2 != 1); - bool neq1_ = (2u != 1u); - bool neq2_ = (2.0 != 1.0); bool2 neq3_ = ((2).xx != (1).xx); bool3 neq4_ = ((2u).xxx != (1u).xxx); bool4 neq5_ = ((2.0).xxxx != (1.0).xxxx); - bool lt0_ = (2 < 1); - bool lt1_ = (2u < 1u); - bool lt2_ = (2.0 < 1.0); bool2 lt3_ = ((2).xx < (1).xx); bool3 lt4_ = ((2u).xxx < (1u).xxx); bool4 lt5_ = ((2.0).xxxx < (1.0).xxxx); - bool lte0_ = (2 <= 1); - bool lte1_ = (2u <= 1u); - bool lte2_ = (2.0 <= 1.0); bool2 lte3_ = ((2).xx <= (1).xx); bool3 lte4_ = ((2u).xxx <= (1u).xxx); bool4 lte5_ = ((2.0).xxxx <= (1.0).xxxx); - bool gt0_ = (2 > 1); - bool gt1_ = (2u > 1u); - bool gt2_ = (2.0 > 1.0); bool2 gt3_ = ((2).xx > (1).xx); bool3 gt4_ = ((2u).xxx > (1u).xxx); bool4 gt5_ = ((2.0).xxxx > (1.0).xxxx); - bool gte0_ = (2 >= 1); - bool gte1_ = (2u >= 1u); - bool gte2_ = (2.0 >= 1.0); bool2 gte3_ = ((2).xx >= (1).xx); bool3 gte4_ = ((2u).xxx >= (1u).xxx); bool4 gte5_ = ((2.0).xxxx >= (1.0).xxxx); @@ -241,13 +193,7 @@ void assignment() void negation_avoids_prefix_decrement() { - int p1_ = -(-2); - int p2_ = -(-3); - int p3_ = -(-(4)); - int p4_ = -(-(-5)); - int p5_ = -(-(-(-(6)))); - int p6_ = -(-(-(-(-7)))); - int p7_ = -(-(-(-(-8)))); + return; } [numthreads(1, 1, 1)] @@ -255,7 +201,7 @@ void main() { const float4 _e0 = builtins(); const float4 _e1 = splat(); - const float3 _e4 = bool_cast(v_f32_one.xyz); + const float3 _e6 = bool_cast(float3(1.0, 1.0, 1.0)); logical(); arithmetic(); bit(); diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index a200e75a9..e2a7aa946 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -419,21 +419,32 @@ 6, ], ), + Literal(I32(8)), Literal(I32(2)), Literal(I32(10)), Literal(I32(2)), + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(1)), + Literal(I32(0)), Literal(I32(2)), Literal(I32(2)), + Literal(I32(0)), + Literal(I32(3)), + Literal(I32(2)), Literal(I32(2)), Literal(I32(10)), Literal(I32(5)), Literal(I32(5)), Literal(I32(10)), Literal(I32(5)), + Literal(I32(0)), Literal(I32(2)), Literal(I32(2)), Literal(I32(2)), Literal(I32(2)), + Literal(I32(1)), ], functions: [ ( diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index fb8ff825e..615c63850 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -58,7 +58,11 @@ init: None, ), ], - const_expressions: [], + const_expressions: [ + Literal(I32(0)), + Literal(I32(0)), + Literal(I32(1)), + ], functions: [ ( name: Some("collatz_iterations"), diff --git a/tests/out/msl/constructors.msl b/tests/out/msl/constructors.msl index b3d3b9dd4..100d6994e 100644 --- a/tests/out/msl/constructors.msl +++ b/tests/out/msl/constructors.msl @@ -40,11 +40,8 @@ kernel void main_( metal::float2x2 cit1_ = metal::float2x2(metal::float2(0.0), metal::float2(0.0)); type_11 cit2_ = type_11 {0, 1, 2, 3}; bool ic0_ = static_cast(bool {}); - int ic1_ = static_cast(int {}); - uint ic2_ = static_cast(uint {}); - float ic3_ = static_cast(float {}); - metal::uint2 ic4_ = static_cast(metal::uint2 {}); - metal::float2x3 ic5_ = metal::float2x3(metal::float2x3 {}); + metal::uint2 ic4_ = metal::uint2(0u, 0u); + metal::float2x3 ic5_ = metal::float2x3(metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0)); metal::uint2 ic6_ = as_type(metal::uint2 {}); metal::float2x3 ic7_ = metal::float2x3(metal::float2x3 {}); } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index e390c2e0f..1612314ec 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -119,74 +119,74 @@ fragment texture_sampleOutput texture_sample( metal::float4 a = {}; metal::float2 tc = metal::float2(0.5); metal::float3 tc3_ = metal::float3(0.5); - metal::float4 _e9 = image_1d.sample(sampler_reg, tc.x); - metal::float4 _e10 = a; - a = _e10 + _e9; - metal::float4 _e14 = image_2d.sample(sampler_reg, tc); - metal::float4 _e15 = a; - a = _e15 + _e14; - metal::float4 _e19 = image_2d.sample(sampler_reg, tc, metal::int2(3, 1)); - metal::float4 _e20 = a; - a = _e20 + _e19; - metal::float4 _e24 = image_2d.sample(sampler_reg, tc, metal::level(2.3)); - metal::float4 _e25 = a; - a = _e25 + _e24; - metal::float4 _e29 = image_2d.sample(sampler_reg, tc, metal::level(2.3), metal::int2(3, 1)); - metal::float4 _e30 = a; - a = _e30 + _e29; - metal::float4 _e35 = image_2d.sample(sampler_reg, tc, metal::bias(2.0), metal::int2(3, 1)); - metal::float4 _e36 = a; - a = _e36 + _e35; - metal::float4 _e41 = image_2d_array.sample(sampler_reg, tc, 0u); - metal::float4 _e42 = a; - a = _e42 + _e41; - metal::float4 _e47 = image_2d_array.sample(sampler_reg, tc, 0u, metal::int2(3, 1)); - metal::float4 _e48 = a; - a = _e48 + _e47; - metal::float4 _e53 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3)); - metal::float4 _e54 = a; - a = _e54 + _e53; - metal::float4 _e59 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3), metal::int2(3, 1)); - metal::float4 _e60 = a; - a = _e60 + _e59; - metal::float4 _e66 = image_2d_array.sample(sampler_reg, tc, 0u, metal::bias(2.0), metal::int2(3, 1)); - metal::float4 _e67 = a; - a = _e67 + _e66; - metal::float4 _e72 = image_2d_array.sample(sampler_reg, tc, 0); - metal::float4 _e73 = a; - a = _e73 + _e72; - metal::float4 _e78 = image_2d_array.sample(sampler_reg, tc, 0, metal::int2(3, 1)); - metal::float4 _e79 = a; - a = _e79 + _e78; - metal::float4 _e84 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3)); - metal::float4 _e85 = a; - a = _e85 + _e84; - metal::float4 _e90 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3), metal::int2(3, 1)); - metal::float4 _e91 = a; - a = _e91 + _e90; - metal::float4 _e97 = image_2d_array.sample(sampler_reg, tc, 0, metal::bias(2.0), metal::int2(3, 1)); - metal::float4 _e98 = a; - a = _e98 + _e97; - metal::float4 _e103 = image_cube_array.sample(sampler_reg, tc3_, 0u); - metal::float4 _e104 = a; - a = _e104 + _e103; - metal::float4 _e109 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::level(2.3)); - metal::float4 _e110 = a; - a = _e110 + _e109; - metal::float4 _e116 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::bias(2.0)); - metal::float4 _e117 = a; - a = _e117 + _e116; - metal::float4 _e122 = image_cube_array.sample(sampler_reg, tc3_, 0); - metal::float4 _e123 = a; - a = _e123 + _e122; - metal::float4 _e128 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::level(2.3)); - metal::float4 _e129 = a; - a = _e129 + _e128; - metal::float4 _e135 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::bias(2.0)); - metal::float4 _e136 = a; - a = _e136 + _e135; - metal::float4 _e138 = a; - return texture_sampleOutput { _e138 }; + metal::float4 _e8 = image_1d.sample(sampler_reg, 0.5); + metal::float4 _e9 = a; + a = _e9 + _e8; + metal::float4 _e13 = image_2d.sample(sampler_reg, tc); + metal::float4 _e14 = a; + a = _e14 + _e13; + metal::float4 _e18 = image_2d.sample(sampler_reg, tc, metal::int2(3, 1)); + metal::float4 _e19 = a; + a = _e19 + _e18; + metal::float4 _e23 = image_2d.sample(sampler_reg, tc, metal::level(2.3)); + metal::float4 _e24 = a; + a = _e24 + _e23; + metal::float4 _e28 = image_2d.sample(sampler_reg, tc, metal::level(2.3), metal::int2(3, 1)); + metal::float4 _e29 = a; + a = _e29 + _e28; + metal::float4 _e34 = image_2d.sample(sampler_reg, tc, metal::bias(2.0), metal::int2(3, 1)); + metal::float4 _e35 = a; + a = _e35 + _e34; + metal::float4 _e40 = image_2d_array.sample(sampler_reg, tc, 0u); + metal::float4 _e41 = a; + a = _e41 + _e40; + metal::float4 _e46 = image_2d_array.sample(sampler_reg, tc, 0u, metal::int2(3, 1)); + metal::float4 _e47 = a; + a = _e47 + _e46; + metal::float4 _e52 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3)); + metal::float4 _e53 = a; + a = _e53 + _e52; + metal::float4 _e58 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3), metal::int2(3, 1)); + metal::float4 _e59 = a; + a = _e59 + _e58; + metal::float4 _e65 = image_2d_array.sample(sampler_reg, tc, 0u, metal::bias(2.0), metal::int2(3, 1)); + metal::float4 _e66 = a; + a = _e66 + _e65; + metal::float4 _e71 = image_2d_array.sample(sampler_reg, tc, 0); + metal::float4 _e72 = a; + a = _e72 + _e71; + metal::float4 _e77 = image_2d_array.sample(sampler_reg, tc, 0, metal::int2(3, 1)); + metal::float4 _e78 = a; + a = _e78 + _e77; + metal::float4 _e83 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3)); + metal::float4 _e84 = a; + a = _e84 + _e83; + metal::float4 _e89 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3), metal::int2(3, 1)); + metal::float4 _e90 = a; + a = _e90 + _e89; + metal::float4 _e96 = image_2d_array.sample(sampler_reg, tc, 0, metal::bias(2.0), metal::int2(3, 1)); + metal::float4 _e97 = a; + a = _e97 + _e96; + metal::float4 _e102 = image_cube_array.sample(sampler_reg, tc3_, 0u); + metal::float4 _e103 = a; + a = _e103 + _e102; + metal::float4 _e108 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::level(2.3)); + metal::float4 _e109 = a; + a = _e109 + _e108; + metal::float4 _e115 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::bias(2.0)); + metal::float4 _e116 = a; + a = _e116 + _e115; + metal::float4 _e121 = image_cube_array.sample(sampler_reg, tc3_, 0); + metal::float4 _e122 = a; + a = _e122 + _e121; + metal::float4 _e127 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::level(2.3)); + metal::float4 _e128 = a; + a = _e128 + _e127; + metal::float4 _e134 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::bias(2.0)); + metal::float4 _e135 = a; + a = _e135 + _e134; + metal::float4 _e137 = a; + return texture_sampleOutput { _e137 }; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index a80c71bef..869f08673 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -16,9 +16,9 @@ metal::float4 builtins( metal::float4 s3_ = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false)); metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half); metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.1); - float b1_ = as_type(v_i32_one.x); + float b1_ = as_type(1); metal::float4 b2_ = as_type(v_i32_one); - metal::int4 v_i32_zero = static_cast(v_f32_zero); + metal::int4 v_i32_zero = metal::int4(0, 0, 0, 0); return ((((static_cast(metal::int4(s1_) + v_i32_zero) + s2_) + m1_) + m2_) + metal::float4(b1_)) + b2_; } @@ -52,10 +52,7 @@ metal::float3 bool_cast( void logical( ) { - bool neg0_ = !(true); - metal::bool2 neg1_ = !(metal::bool2(true)); - bool or_ = true || false; - bool and_ = true && false; + metal::bool2 neg1_ = metal::bool2(false, false); bool bitwise_or0_ = true | false; metal::bool3 bitwise_or1_ = metal::bool3(true) | metal::bool3(false); bool bitwise_and0_ = true & false; @@ -64,74 +61,59 @@ void logical( void arithmetic( ) { - metal::int2 neg1_1 = -(metal::int2(1)); - metal::float2 neg2_ = -(metal::float2(1.0)); - int add0_ = 2 + 1; - uint add1_ = 2u + 1u; - float add2_ = 2.0 + 1.0; + metal::int2 neg1_1 = metal::int2(-1, -1); + metal::float2 neg2_ = metal::float2(-1.0, -1.0); metal::int2 add3_ = metal::int2(2) + metal::int2(1); metal::uint3 add4_ = metal::uint3(2u) + metal::uint3(1u); metal::float4 add5_ = metal::float4(2.0) + metal::float4(1.0); - int sub0_ = 2 - 1; - uint sub1_ = 2u - 1u; - float sub2_ = 2.0 - 1.0; metal::int2 sub3_ = metal::int2(2) - metal::int2(1); metal::uint3 sub4_ = metal::uint3(2u) - metal::uint3(1u); metal::float4 sub5_ = metal::float4(2.0) - metal::float4(1.0); - int mul0_ = 2 * 1; - uint mul1_ = 2u * 1u; - float mul2_ = 2.0 * 1.0; metal::int2 mul3_ = metal::int2(2) * metal::int2(1); metal::uint3 mul4_ = metal::uint3(2u) * metal::uint3(1u); metal::float4 mul5_ = metal::float4(2.0) * metal::float4(1.0); - int div0_ = 2 / 1; - uint div1_ = 2u / 1u; - float div2_ = 2.0 / 1.0; metal::int2 div3_ = metal::int2(2) / metal::int2(1); metal::uint3 div4_ = metal::uint3(2u) / metal::uint3(1u); metal::float4 div5_ = metal::float4(2.0) / metal::float4(1.0); - int rem0_ = 2 % 1; - uint rem1_ = 2u % 1u; - float rem2_ = metal::fmod(2.0, 1.0); metal::int2 rem3_ = metal::int2(2) % metal::int2(1); metal::uint3 rem4_ = metal::uint3(2u) % metal::uint3(1u); metal::float4 rem5_ = metal::fmod(metal::float4(2.0), metal::float4(1.0)); { - metal::int2 add0_1 = metal::int2(2) + metal::int2(1); - metal::int2 add1_1 = metal::int2(2) + metal::int2(1); - metal::uint2 add2_1 = metal::uint2(2u) + metal::uint2(1u); + metal::int2 add0_ = metal::int2(2) + metal::int2(1); + metal::int2 add1_ = metal::int2(2) + metal::int2(1); + metal::uint2 add2_ = metal::uint2(2u) + metal::uint2(1u); metal::uint2 add3_1 = metal::uint2(2u) + metal::uint2(1u); metal::float2 add4_1 = metal::float2(2.0) + metal::float2(1.0); metal::float2 add5_1 = metal::float2(2.0) + metal::float2(1.0); - metal::int2 sub0_1 = metal::int2(2) - metal::int2(1); - metal::int2 sub1_1 = metal::int2(2) - metal::int2(1); - metal::uint2 sub2_1 = metal::uint2(2u) - metal::uint2(1u); + metal::int2 sub0_ = metal::int2(2) - metal::int2(1); + metal::int2 sub1_ = metal::int2(2) - metal::int2(1); + metal::uint2 sub2_ = metal::uint2(2u) - metal::uint2(1u); metal::uint2 sub3_1 = metal::uint2(2u) - metal::uint2(1u); metal::float2 sub4_1 = metal::float2(2.0) - metal::float2(1.0); metal::float2 sub5_1 = metal::float2(2.0) - metal::float2(1.0); - metal::int2 mul0_1 = metal::int2(2) * 1; - metal::int2 mul1_1 = 2 * metal::int2(1); - metal::uint2 mul2_1 = metal::uint2(2u) * 1u; - metal::uint2 mul3_1 = 2u * metal::uint2(1u); - metal::float2 mul4_1 = metal::float2(2.0) * 1.0; - metal::float2 mul5_1 = 2.0 * metal::float2(1.0); - metal::int2 div0_1 = metal::int2(2) / metal::int2(1); - metal::int2 div1_1 = metal::int2(2) / metal::int2(1); - metal::uint2 div2_1 = metal::uint2(2u) / metal::uint2(1u); + metal::int2 mul0_ = metal::int2(2, 2); + metal::int2 mul1_ = metal::int2(2, 2); + metal::uint2 mul2_ = metal::uint2(2u, 2u); + metal::uint2 mul3_1 = metal::uint2(2u, 2u); + metal::float2 mul4_1 = metal::float2(2.0, 2.0); + metal::float2 mul5_1 = metal::float2(2.0, 2.0); + metal::int2 div0_ = metal::int2(2) / metal::int2(1); + metal::int2 div1_ = metal::int2(2) / metal::int2(1); + metal::uint2 div2_ = metal::uint2(2u) / metal::uint2(1u); metal::uint2 div3_1 = metal::uint2(2u) / metal::uint2(1u); metal::float2 div4_1 = metal::float2(2.0) / metal::float2(1.0); metal::float2 div5_1 = metal::float2(2.0) / metal::float2(1.0); - metal::int2 rem0_1 = metal::int2(2) % metal::int2(1); - metal::int2 rem1_1 = metal::int2(2) % metal::int2(1); - metal::uint2 rem2_1 = metal::uint2(2u) % metal::uint2(1u); + metal::int2 rem0_ = metal::int2(2) % metal::int2(1); + metal::int2 rem1_ = metal::int2(2) % metal::int2(1); + metal::uint2 rem2_ = metal::uint2(2u) % metal::uint2(1u); metal::uint2 rem3_1 = metal::uint2(2u) % metal::uint2(1u); metal::float2 rem4_1 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); metal::float2 rem5_1 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); } metal::float3x3 add = metal::float3x3 {} + metal::float3x3 {}; metal::float3x3 sub = metal::float3x3 {} - metal::float3x3 {}; - metal::float3x3 mul_scalar0_ = metal::float3x3 {} * 1.0; - metal::float3x3 mul_scalar1_ = 2.0 * metal::float3x3 {}; + metal::float3x3 mul_scalar0_ = metal::float3x3(metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0)); + metal::float3x3 mul_scalar1_ = metal::float3x3(metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0)); metal::float3 mul_vector0_ = metal::float4x3 {} * metal::float4(1.0); metal::float4 mul_vector1_ = metal::float3(2.0) * metal::float4x3 {}; metal::float3x3 mul = metal::float4x3 {} * metal::float3x4 {}; @@ -139,67 +121,37 @@ void arithmetic( void bit( ) { - int flip0_ = ~(1); - uint flip1_ = ~(1u); - metal::int2 flip2_ = ~(metal::int2(1)); - metal::uint3 flip3_ = ~(metal::uint3(1u)); - int or0_ = 2 | 1; - uint or1_ = 2u | 1u; + metal::int2 flip2_ = metal::int2(-2, -2); + metal::uint3 flip3_ = metal::uint3(4294967294u, 4294967294u, 4294967294u); metal::int2 or2_ = metal::int2(2) | metal::int2(1); metal::uint3 or3_ = metal::uint3(2u) | metal::uint3(1u); - int and0_ = 2 & 1; - uint and1_ = 2u & 1u; metal::int2 and2_ = metal::int2(2) & metal::int2(1); metal::uint3 and3_ = metal::uint3(2u) & metal::uint3(1u); - int xor0_ = 2 ^ 1; - uint xor1_ = 2u ^ 1u; metal::int2 xor2_ = metal::int2(2) ^ metal::int2(1); metal::uint3 xor3_ = metal::uint3(2u) ^ metal::uint3(1u); - int shl0_ = 2 << 1u; - uint shl1_ = 2u << 1u; metal::int2 shl2_ = metal::int2(2) << metal::uint2(1u); metal::uint3 shl3_ = metal::uint3(2u) << metal::uint3(1u); - int shr0_ = 2 >> 1u; - uint shr1_ = 2u >> 1u; metal::int2 shr2_ = metal::int2(2) >> metal::uint2(1u); metal::uint3 shr3_ = metal::uint3(2u) >> metal::uint3(1u); } void comparison( ) { - bool eq0_ = 2 == 1; - bool eq1_ = 2u == 1u; - bool eq2_ = 2.0 == 1.0; metal::bool2 eq3_ = metal::int2(2) == metal::int2(1); metal::bool3 eq4_ = metal::uint3(2u) == metal::uint3(1u); metal::bool4 eq5_ = metal::float4(2.0) == metal::float4(1.0); - bool neq0_ = 2 != 1; - bool neq1_ = 2u != 1u; - bool neq2_ = 2.0 != 1.0; metal::bool2 neq3_ = metal::int2(2) != metal::int2(1); metal::bool3 neq4_ = metal::uint3(2u) != metal::uint3(1u); metal::bool4 neq5_ = metal::float4(2.0) != metal::float4(1.0); - bool lt0_ = 2 < 1; - bool lt1_ = 2u < 1u; - bool lt2_ = 2.0 < 1.0; metal::bool2 lt3_ = metal::int2(2) < metal::int2(1); metal::bool3 lt4_ = metal::uint3(2u) < metal::uint3(1u); metal::bool4 lt5_ = metal::float4(2.0) < metal::float4(1.0); - bool lte0_ = 2 <= 1; - bool lte1_ = 2u <= 1u; - bool lte2_ = 2.0 <= 1.0; metal::bool2 lte3_ = metal::int2(2) <= metal::int2(1); metal::bool3 lte4_ = metal::uint3(2u) <= metal::uint3(1u); metal::bool4 lte5_ = metal::float4(2.0) <= metal::float4(1.0); - bool gt0_ = 2 > 1; - bool gt1_ = 2u > 1u; - bool gt2_ = 2.0 > 1.0; metal::bool2 gt3_ = metal::int2(2) > metal::int2(1); metal::bool3 gt4_ = metal::uint3(2u) > metal::uint3(1u); metal::bool4 gt5_ = metal::float4(2.0) > metal::float4(1.0); - bool gte0_ = 2 >= 1; - bool gte1_ = 2u >= 1u; - bool gte2_ = 2.0 >= 1.0; metal::bool2 gte3_ = metal::int2(2) >= metal::int2(1); metal::bool3 gte4_ = metal::uint3(2u) >= metal::uint3(1u); metal::bool4 gte5_ = metal::float4(2.0) >= metal::float4(1.0); @@ -246,20 +198,14 @@ void assignment( void negation_avoids_prefix_decrement( ) { - int p1_ = -(-2); - int p2_ = -(-3); - int p3_ = -(-(4)); - int p4_ = -(-(-5)); - int p5_ = -(-(-(-(6)))); - int p6_ = -(-(-(-(-7)))); - int p7_ = -(-(-(-(-8)))); + return; } kernel void main_( ) { metal::float4 _e0 = builtins(); metal::float4 _e1 = splat(); - metal::float3 _e4 = bool_cast(v_f32_one.xyz); + metal::float3 _e6 = bool_cast(metal::float3(1.0, 1.0, 1.0)); logical(); arithmetic(); bit(); diff --git a/tests/out/spv/constructors.spvasm b/tests/out/spv/constructors.spvasm index ec54d6d1b..4670ab39d 100644 --- a/tests/out/spv/constructors.spvasm +++ b/tests/out/spv/constructors.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 74 +; Bound: 73 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -78,7 +78,10 @@ OpStore %43 %52 %63 = OpCompositeConstruct %9 %21 %21 %64 = OpCompositeConstruct %8 %62 %63 %65 = OpCompositeConstruct %17 %38 %39 %40 %41 -%71 = OpCopyObject %20 %49 -%73 = OpCopyObject %20 %49 +%67 = OpCompositeConstruct %14 %48 %48 +%68 = OpCompositeConstruct %7 %21 %21 %21 +%69 = OpCompositeConstruct %7 %21 %21 %21 +%70 = OpCompositeConstruct %20 %68 %69 +%72 = OpCopyObject %20 %49 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/debug-symbol-terrain.spvasm b/tests/out/spv/debug-symbol-terrain.spvasm index 8c27f3ab9..044f1f169 100644 --- a/tests/out/spv/debug-symbol-terrain.spvasm +++ b/tests/out/spv/debug-symbol-terrain.spvasm @@ -1,19 +1,19 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 647 +; Bound: 641 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %348 "gen_terrain_compute" %345 -OpEntryPoint Vertex %418 "gen_terrain_vertex" %409 %412 %414 %416 -OpEntryPoint Fragment %470 "gen_terrain_fragment" %460 %462 %465 %468 %469 -OpEntryPoint Vertex %561 "vs_main" %552 %555 %557 %558 %560 -OpEntryPoint Fragment %587 "fs_main" %580 %582 %584 %586 -OpExecutionMode %348 LocalSize 64 1 1 -OpExecutionMode %470 OriginUpperLeft -OpExecutionMode %587 OriginUpperLeft +OpEntryPoint GLCompute %344 "gen_terrain_compute" %341 +OpEntryPoint Vertex %414 "gen_terrain_vertex" %405 %408 %410 %412 +OpEntryPoint Fragment %464 "gen_terrain_fragment" %454 %456 %459 %462 %463 +OpEntryPoint Vertex %555 "vs_main" %546 %549 %551 %552 %554 +OpEntryPoint Fragment %581 "fs_main" %574 %576 %578 %580 +OpExecutionMode %344 LocalSize 64 1 1 +OpExecutionMode %464 OriginUpperLeft +OpExecutionMode %581 OriginUpperLeft %3 = OpString "debug-symbol-terrain.wgsl" OpSource Unknown 0 %3 "// Taken from https://github.com/sotrh/learn-wgpu/blob/11820796f5e1dbce42fb1119f04ddeb4b167d2a0/code/intermediate/tutorial13-terrain/src/terrain.wgsl // ============================ @@ -370,44 +370,44 @@ OpName %208 "a" OpName %209 "i" OpName %213 "p" OpName %214 "fbm" -OpName %258 "p" -OpName %259 "min_max_height" -OpName %260 "terrain_point" -OpName %271 "p" -OpName %272 "min_max_height" -OpName %273 "terrain_vertex" -OpName %303 "vert_index" -OpName %304 "chunk_size" -OpName %305 "chunk_corner" -OpName %306 "index_to_p" -OpName %322 "p" -OpName %323 "color23" -OpName %345 "gid" -OpName %348 "gen_terrain_compute" -OpName %409 "vindex" -OpName %412 "index" -OpName %414 "position" -OpName %416 "uv" -OpName %418 "gen_terrain_vertex" -OpName %456 "vert_component" -OpName %457 "index" -OpName %460 "index" -OpName %462 "position" -OpName %465 "uv" -OpName %468 "vert_component" -OpName %469 "index" -OpName %470 "gen_terrain_fragment" -OpName %552 "position" -OpName %555 "normal" -OpName %557 "clip_position" -OpName %558 "normal" -OpName %560 "world_pos" -OpName %561 "vs_main" -OpName %577 "color" -OpName %580 "clip_position" -OpName %582 "normal" -OpName %584 "world_pos" -OpName %587 "fs_main" +OpName %254 "p" +OpName %255 "min_max_height" +OpName %256 "terrain_point" +OpName %267 "p" +OpName %268 "min_max_height" +OpName %269 "terrain_vertex" +OpName %299 "vert_index" +OpName %300 "chunk_size" +OpName %301 "chunk_corner" +OpName %302 "index_to_p" +OpName %318 "p" +OpName %319 "color23" +OpName %341 "gid" +OpName %344 "gen_terrain_compute" +OpName %405 "vindex" +OpName %408 "index" +OpName %410 "position" +OpName %412 "uv" +OpName %414 "gen_terrain_vertex" +OpName %450 "vert_component" +OpName %451 "index" +OpName %454 "index" +OpName %456 "position" +OpName %459 "uv" +OpName %462 "vert_component" +OpName %463 "index" +OpName %464 "gen_terrain_fragment" +OpName %546 "position" +OpName %549 "normal" +OpName %551 "clip_position" +OpName %552 "normal" +OpName %554 "world_pos" +OpName %555 "vs_main" +OpName %571 "color" +OpName %574 "clip_position" +OpName %576 "normal" +OpName %578 "world_pos" +OpName %581 "fs_main" OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %13 1 Offset 8 OpMemberDecorate %13 2 Offset 16 @@ -466,27 +466,27 @@ OpDecorate %49 DescriptorSet 2 OpDecorate %49 Binding 2 OpDecorate %50 DescriptorSet 2 OpDecorate %50 Binding 3 -OpDecorate %345 BuiltIn GlobalInvocationId -OpDecorate %409 BuiltIn VertexIndex -OpDecorate %412 Location 0 -OpDecorate %412 Flat -OpDecorate %414 BuiltIn Position -OpDecorate %416 Location 1 -OpDecorate %460 Location 0 -OpDecorate %460 Flat -OpDecorate %462 BuiltIn FragCoord -OpDecorate %465 Location 1 -OpDecorate %468 Location 0 -OpDecorate %469 Location 1 +OpDecorate %341 BuiltIn GlobalInvocationId +OpDecorate %405 BuiltIn VertexIndex +OpDecorate %408 Location 0 +OpDecorate %408 Flat +OpDecorate %410 BuiltIn Position +OpDecorate %412 Location 1 +OpDecorate %454 Location 0 +OpDecorate %454 Flat +OpDecorate %456 BuiltIn FragCoord +OpDecorate %459 Location 1 +OpDecorate %462 Location 0 +OpDecorate %463 Location 1 +OpDecorate %546 Location 0 +OpDecorate %549 Location 1 +OpDecorate %551 BuiltIn Position OpDecorate %552 Location 0 -OpDecorate %555 Location 1 -OpDecorate %557 BuiltIn Position -OpDecorate %558 Location 0 -OpDecorate %560 Location 1 -OpDecorate %580 BuiltIn FragCoord -OpDecorate %582 Location 0 -OpDecorate %584 Location 1 -OpDecorate %586 Location 0 +OpDecorate %554 Location 1 +OpDecorate %574 BuiltIn FragCoord +OpDecorate %576 Location 0 +OpDecorate %578 Location 1 +OpDecorate %580 Location 0 %2 = OpTypeVoid %5 = OpTypeFloat 32 %4 = OpTypeVector %5 3 @@ -568,69 +568,69 @@ OpDecorate %586 Location 0 %215 = OpConstant %8 5 %216 = OpConstant %5 0.01 %217 = OpConstant %5 100.0 -%261 = OpTypeFunction %4 %6 %6 -%274 = OpTypeFunction %14 %6 %6 -%275 = OpConstant %5 0.1 -%276 = OpConstant %5 -0.1 -%307 = OpTypeFunction %6 %8 %10 %11 -%324 = OpTypeFunction %4 %6 -%325 = OpConstant %5 23.0 -%326 = OpConstant %5 32.0 -%327 = OpConstant %5 -43.0 -%328 = OpConstant %5 3.0 -%346 = OpTypePointer Input %19 -%345 = OpVariable %346 Input -%349 = OpTypeFunction %2 -%350 = OpTypePointer Uniform %13 -%352 = OpConstant %8 6 -%353 = OpConstant %8 2 -%354 = OpConstant %8 3 -%355 = OpConstant %8 4 -%358 = OpTypePointer Uniform %10 -%361 = OpTypePointer Uniform %11 -%365 = OpTypePointer StorageBuffer %15 -%366 = OpTypePointer StorageBuffer %14 -%367 = OpTypePointer Uniform %6 -%374 = OpTypePointer Uniform %8 -%395 = OpTypePointer StorageBuffer %17 -%396 = OpTypePointer StorageBuffer %8 -%410 = OpTypePointer Input %8 -%409 = OpVariable %410 Input -%413 = OpTypePointer Output %8 +%257 = OpTypeFunction %4 %6 %6 +%270 = OpTypeFunction %14 %6 %6 +%271 = OpConstant %5 0.1 +%272 = OpConstant %5 -0.1 +%303 = OpTypeFunction %6 %8 %10 %11 +%320 = OpTypeFunction %4 %6 +%321 = OpConstant %5 23.0 +%322 = OpConstant %5 32.0 +%323 = OpConstant %5 -43.0 +%324 = OpConstant %5 3.0 +%342 = OpTypePointer Input %19 +%341 = OpVariable %342 Input +%345 = OpTypeFunction %2 +%346 = OpTypePointer Uniform %13 +%348 = OpConstant %8 6 +%349 = OpConstant %8 2 +%350 = OpConstant %8 3 +%351 = OpConstant %8 4 +%354 = OpTypePointer Uniform %10 +%357 = OpTypePointer Uniform %11 +%361 = OpTypePointer StorageBuffer %15 +%362 = OpTypePointer StorageBuffer %14 +%363 = OpTypePointer Uniform %6 +%370 = OpTypePointer Uniform %8 +%391 = OpTypePointer StorageBuffer %17 +%392 = OpTypePointer StorageBuffer %8 +%406 = OpTypePointer Input %8 +%405 = OpVariable %406 Input +%409 = OpTypePointer Output %8 +%408 = OpVariable %409 Output +%411 = OpTypePointer Output %7 +%410 = OpVariable %411 Output +%413 = OpTypePointer Output %6 %412 = OpVariable %413 Output -%415 = OpTypePointer Output %7 -%414 = OpVariable %415 Output -%417 = OpTypePointer Output %6 -%416 = OpVariable %417 Output -%419 = OpTypePointer Uniform %20 -%421 = OpConstant %5 -1.0 -%437 = OpTypePointer Uniform %8 -%460 = OpVariable %410 Input -%463 = OpTypePointer Input %7 -%462 = OpVariable %463 Input -%466 = OpTypePointer Input %6 -%465 = OpVariable %466 Input -%468 = OpVariable %413 Output -%469 = OpVariable %413 Output -%472 = OpConstant %5 6.0 -%553 = OpTypePointer Input %4 -%552 = OpVariable %553 Input -%555 = OpVariable %553 Input -%557 = OpVariable %415 Output -%559 = OpTypePointer Output %4 -%558 = OpVariable %559 Output -%560 = OpVariable %559 Output -%562 = OpTypePointer Uniform %24 -%565 = OpTypePointer Uniform %23 -%580 = OpVariable %463 Input -%582 = OpVariable %553 Input -%584 = OpVariable %553 Input -%586 = OpVariable %415 Output -%589 = OpTypePointer Uniform %25 -%591 = OpConstant %5 0.7 -%592 = OpConstant %5 0.2 -%611 = OpTypePointer Uniform %4 -%620 = OpTypePointer Uniform %7 +%415 = OpTypePointer Uniform %20 +%417 = OpConstant %5 -1.0 +%432 = OpTypePointer Uniform %8 +%454 = OpVariable %406 Input +%457 = OpTypePointer Input %7 +%456 = OpVariable %457 Input +%460 = OpTypePointer Input %6 +%459 = OpVariable %460 Input +%462 = OpVariable %409 Output +%463 = OpVariable %409 Output +%466 = OpConstant %5 6.0 +%547 = OpTypePointer Input %4 +%546 = OpVariable %547 Input +%549 = OpVariable %547 Input +%551 = OpVariable %411 Output +%553 = OpTypePointer Output %4 +%552 = OpVariable %553 Output +%554 = OpVariable %553 Output +%556 = OpTypePointer Uniform %24 +%559 = OpTypePointer Uniform %23 +%574 = OpVariable %457 Input +%576 = OpVariable %547 Input +%578 = OpVariable %547 Input +%580 = OpVariable %411 Output +%583 = OpTypePointer Uniform %25 +%585 = OpConstant %5 0.7 +%586 = OpConstant %5 0.2 +%605 = OpTypePointer Uniform %4 +%614 = OpTypePointer Uniform %7 %53 = OpFunction %4 None %54 %52 = OpFunctionParameter %4 %51 = OpLabel @@ -659,7 +659,7 @@ OpBranch %89 OpLine %3 13 13 %90 = OpCompositeConstruct %7 %79 %80 %81 %82 OpLine %3 14 24 -%91 = OpVectorShuffle %6 %90 %90 1 1 +%91 = OpCompositeConstruct %6 %80 %80 %92 = OpDot %5 %76 %91 %93 = OpCompositeConstruct %6 %92 %92 %94 = OpFAdd %6 %76 %93 @@ -670,7 +670,7 @@ OpLine %3 15 14 %96 = OpLoad %6 %65 %97 = OpFSub %6 %76 %96 %98 = OpLoad %6 %65 -%99 = OpVectorShuffle %6 %90 %90 0 0 +%99 = OpCompositeConstruct %6 %79 %79 %100 = OpDot %5 %98 %99 %101 = OpCompositeConstruct %6 %100 %100 %102 = OpFAdd %6 %97 %101 @@ -687,7 +687,7 @@ OpLine %3 17 5 OpStore %68 %109 OpLine %3 18 26 %112 = OpVectorShuffle %7 %102 %102 0 1 0 1 -%113 = OpVectorShuffle %7 %90 %90 0 0 2 2 +%113 = OpCompositeConstruct %7 %79 %79 %81 %81 %114 = OpFAdd %7 %112 %113 %115 = OpLoad %6 %68 OpLine %3 18 26 @@ -760,7 +760,7 @@ OpLine %3 23 9 OpLine %3 23 5 OpStore %72 %162 OpLine %3 24 13 -%163 = OpVectorShuffle %4 %90 %90 3 3 3 +%163 = OpCompositeConstruct %4 %82 %82 %82 %164 = OpFMul %4 %140 %163 %165 = OpExtInst %4 %1 Fract %164 %166 = OpVectorTimesScalar %4 %165 %85 @@ -839,626 +839,619 @@ OpLine %3 40 14 %222 = OpExtInst %5 %1 Sin %84 %223 = OpCompositeConstruct %6 %221 %222 OpLine %3 41 15 -%224 = OpCompositeExtract %5 %223 0 -%225 = OpCompositeExtract %5 %223 1 -%226 = OpCompositeExtract %5 %223 1 -%227 = OpFNegate %5 %226 -%228 = OpCompositeExtract %5 %223 0 -%229 = OpCompositeConstruct %6 %224 %225 -%230 = OpCompositeConstruct %6 %227 %228 -%231 = OpCompositeConstruct %9 %229 %230 +%224 = OpFNegate %5 %222 +%225 = OpCompositeConstruct %6 %221 %222 +%226 = OpCompositeConstruct %6 %224 %221 +%227 = OpCompositeConstruct %9 %225 %226 OpLine %3 43 10 OpStore %209 %131 -OpBranch %232 -%232 = OpLabel +OpBranch %228 +%228 = OpLabel OpLine %3 43 5 -OpLoopMerge %233 %235 None -OpBranch %234 -%234 = OpLabel +OpLoopMerge %229 %231 None +OpBranch %230 +%230 = OpLabel OpLine %3 43 22 -%236 = OpLoad %8 %209 -%237 = OpULessThan %107 %236 %215 +%232 = OpLoad %8 %209 +%233 = OpULessThan %107 %232 %215 OpLine %3 43 21 -OpSelectionMerge %238 None -OpBranchConditional %237 %238 %239 -%239 = OpLabel -OpBranch %233 -%238 = OpLabel -OpBranch %240 -%240 = OpLabel -OpLine %3 1 1 -%242 = OpLoad %5 %205 -%243 = OpLoad %5 %208 -%244 = OpLoad %6 %204 -OpLine %3 44 21 -%245 = OpFunctionCall %5 %77 %244 -OpLine %3 44 13 -%246 = OpFMul %5 %243 %245 -%247 = OpFAdd %5 %242 %246 -OpLine %3 44 9 -OpStore %205 %247 -OpLine %3 45 13 -%248 = OpLoad %6 %204 -%249 = OpMatrixTimesVector %6 %231 %248 -OpLine %3 45 13 -%250 = OpVectorTimesScalar %6 %249 %85 -%251 = OpFAdd %6 %250 %220 -OpLine %3 45 9 -OpStore %204 %251 -OpLine %3 1 1 -%252 = OpLoad %5 %208 -OpLine %3 46 13 -%253 = OpFMul %5 %252 %84 -OpLine %3 46 9 -OpStore %208 %253 -OpBranch %241 -%241 = OpLabel -OpBranch %235 +OpSelectionMerge %234 None +OpBranchConditional %233 %234 %235 %235 = OpLabel +OpBranch %229 +%234 = OpLabel +OpBranch %236 +%236 = OpLabel OpLine %3 1 1 -%254 = OpLoad %8 %209 +%238 = OpLoad %5 %205 +%239 = OpLoad %5 %208 +%240 = OpLoad %6 %204 +OpLine %3 44 21 +%241 = OpFunctionCall %5 %77 %240 +OpLine %3 44 13 +%242 = OpFMul %5 %239 %241 +%243 = OpFAdd %5 %238 %242 +OpLine %3 44 9 +OpStore %205 %243 +OpLine %3 45 13 +%244 = OpLoad %6 %204 +%245 = OpMatrixTimesVector %6 %227 %244 +OpLine %3 45 13 +%246 = OpVectorTimesScalar %6 %245 %85 +%247 = OpFAdd %6 %246 %220 +OpLine %3 45 9 +OpStore %204 %247 +OpLine %3 1 1 +%248 = OpLoad %5 %208 +OpLine %3 46 13 +%249 = OpFMul %5 %248 %84 +OpLine %3 46 9 +OpStore %208 %249 +OpBranch %237 +%237 = OpLabel +OpBranch %231 +%231 = OpLabel +OpLine %3 1 1 +%250 = OpLoad %8 %209 OpLine %3 43 43 -%255 = OpIAdd %8 %254 %122 +%251 = OpIAdd %8 %250 %122 OpLine %3 43 39 -OpStore %209 %255 -OpBranch %232 -%233 = OpLabel +OpStore %209 %251 +OpBranch %228 +%229 = OpLabel OpLine %3 1 1 -%256 = OpLoad %5 %205 -OpReturnValue %256 +%252 = OpLoad %5 %205 +OpReturnValue %252 OpFunctionEnd -%260 = OpFunction %4 None %261 -%258 = OpFunctionParameter %6 -%259 = OpFunctionParameter %6 -%257 = OpLabel -OpBranch %262 -%262 = OpLabel +%256 = OpFunction %4 None %257 +%254 = OpFunctionParameter %6 +%255 = OpFunctionParameter %6 +%253 = OpLabel +OpBranch %258 +%258 = OpLabel OpLine %3 77 9 -%263 = OpCompositeExtract %5 %258 0 -%264 = OpCompositeExtract %5 %259 0 -%265 = OpCompositeExtract %5 %259 1 +%259 = OpCompositeExtract %5 %254 0 +%260 = OpCompositeExtract %5 %255 0 +%261 = OpCompositeExtract %5 %255 1 OpLine %3 78 49 -%266 = OpFunctionCall %5 %214 %258 +%262 = OpFunctionCall %5 %214 %254 OpLine %3 76 12 -%267 = OpExtInst %5 %1 FMix %264 %265 %266 -%268 = OpCompositeExtract %5 %258 1 -%269 = OpCompositeConstruct %4 %263 %267 %268 -OpReturnValue %269 +%263 = OpExtInst %5 %1 FMix %260 %261 %262 +%264 = OpCompositeExtract %5 %254 1 +%265 = OpCompositeConstruct %4 %259 %263 %264 +OpReturnValue %265 OpFunctionEnd -%273 = OpFunction %14 None %274 -%271 = OpFunctionParameter %6 -%272 = OpFunctionParameter %6 -%270 = OpLabel -OpBranch %277 -%277 = OpLabel +%269 = OpFunction %14 None %270 +%267 = OpFunctionParameter %6 +%268 = OpFunctionParameter %6 +%266 = OpLabel +OpBranch %273 +%273 = OpLabel OpLine %3 84 13 -%278 = OpFunctionCall %4 %260 %271 %272 +%274 = OpFunctionCall %4 %256 %267 %268 OpLine %3 86 29 -%279 = OpCompositeConstruct %6 %275 %83 -%280 = OpFAdd %6 %271 %279 +%275 = OpCompositeConstruct %6 %271 %83 +%276 = OpFAdd %6 %267 %275 OpLine %3 86 15 -%281 = OpFunctionCall %4 %260 %280 %272 +%277 = OpFunctionCall %4 %256 %276 %268 OpLine %3 86 15 -%282 = OpFSub %4 %281 %278 +%278 = OpFSub %4 %277 %274 OpLine %3 87 29 -%283 = OpCompositeConstruct %6 %83 %275 -%284 = OpFAdd %6 %271 %283 +%279 = OpCompositeConstruct %6 %83 %271 +%280 = OpFAdd %6 %267 %279 OpLine %3 87 15 -%285 = OpFunctionCall %4 %260 %284 %272 +%281 = OpFunctionCall %4 %256 %280 %268 OpLine %3 87 15 -%286 = OpFSub %4 %285 %278 +%282 = OpFSub %4 %281 %274 OpLine %3 88 29 -%287 = OpCompositeConstruct %6 %276 %83 -%288 = OpFAdd %6 %271 %287 +%283 = OpCompositeConstruct %6 %272 %83 +%284 = OpFAdd %6 %267 %283 OpLine %3 88 15 -%289 = OpFunctionCall %4 %260 %288 %272 +%285 = OpFunctionCall %4 %256 %284 %268 OpLine %3 88 15 -%290 = OpFSub %4 %289 %278 +%286 = OpFSub %4 %285 %274 OpLine %3 89 29 -%291 = OpCompositeConstruct %6 %83 %276 -%292 = OpFAdd %6 %271 %291 +%287 = OpCompositeConstruct %6 %83 %272 +%288 = OpFAdd %6 %267 %287 OpLine %3 89 15 -%293 = OpFunctionCall %4 %260 %292 %272 +%289 = OpFunctionCall %4 %256 %288 %268 OpLine %3 89 15 -%294 = OpFSub %4 %293 %278 +%290 = OpFSub %4 %289 %274 OpLine %3 91 14 -%295 = OpExtInst %4 %1 Cross %286 %282 -%296 = OpExtInst %4 %1 Normalize %295 +%291 = OpExtInst %4 %1 Cross %282 %278 +%292 = OpExtInst %4 %1 Normalize %291 OpLine %3 92 14 -%297 = OpExtInst %4 %1 Cross %294 %290 -%298 = OpExtInst %4 %1 Normalize %297 +%293 = OpExtInst %4 %1 Cross %290 %286 +%294 = OpExtInst %4 %1 Normalize %293 OpLine %3 94 14 -%299 = OpFAdd %4 %296 %298 +%295 = OpFAdd %4 %292 %294 OpLine %3 94 13 -%300 = OpVectorTimesScalar %4 %299 %84 +%296 = OpVectorTimesScalar %4 %295 %84 OpLine %3 96 12 -%301 = OpCompositeConstruct %14 %278 %300 -OpReturnValue %301 +%297 = OpCompositeConstruct %14 %274 %296 +OpReturnValue %297 OpFunctionEnd -%306 = OpFunction %6 None %307 -%303 = OpFunctionParameter %8 -%304 = OpFunctionParameter %10 -%305 = OpFunctionParameter %11 -%302 = OpLabel -OpBranch %308 -%308 = OpLabel +%302 = OpFunction %6 None %303 +%299 = OpFunctionParameter %8 +%300 = OpFunctionParameter %10 +%301 = OpFunctionParameter %11 +%298 = OpLabel +OpBranch %304 +%304 = OpLabel OpLine %3 101 9 -%309 = OpConvertUToF %5 %303 -%310 = OpCompositeExtract %8 %304 0 +%305 = OpConvertUToF %5 %299 +%306 = OpCompositeExtract %8 %300 0 OpLine %3 101 9 -%311 = OpIAdd %8 %310 %122 -%312 = OpConvertUToF %5 %311 -%313 = OpFRem %5 %309 %312 -%314 = OpCompositeExtract %8 %304 0 +%307 = OpIAdd %8 %306 %122 +%308 = OpConvertUToF %5 %307 +%309 = OpFRem %5 %305 %308 +%310 = OpCompositeExtract %8 %300 0 OpLine %3 100 12 -%315 = OpIAdd %8 %314 %122 -%316 = OpUDiv %8 %303 %315 -%317 = OpConvertUToF %5 %316 -%318 = OpCompositeConstruct %6 %313 %317 -%319 = OpConvertSToF %6 %305 -%320 = OpFAdd %6 %318 %319 -OpReturnValue %320 +%311 = OpIAdd %8 %310 %122 +%312 = OpUDiv %8 %299 %311 +%313 = OpConvertUToF %5 %312 +%314 = OpCompositeConstruct %6 %309 %313 +%315 = OpConvertSToF %6 %301 +%316 = OpFAdd %6 %314 %315 +OpReturnValue %316 OpFunctionEnd -%323 = OpFunction %4 None %324 -%322 = OpFunctionParameter %6 -%321 = OpLabel -OpBranch %329 -%329 = OpLabel +%319 = OpFunction %4 None %320 +%318 = OpFunctionParameter %6 +%317 = OpLabel +OpBranch %325 +%325 = OpLabel OpLine %3 270 9 -%330 = OpFunctionCall %5 %77 %322 +%326 = OpFunctionCall %5 %77 %318 OpLine %3 270 9 -%331 = OpFMul %5 %330 %84 +%327 = OpFMul %5 %326 %84 OpLine %3 270 9 -%332 = OpFAdd %5 %331 %84 +%328 = OpFAdd %5 %327 %84 OpLine %3 271 17 -%333 = OpCompositeConstruct %6 %325 %326 -%334 = OpFAdd %6 %322 %333 +%329 = OpCompositeConstruct %6 %321 %322 +%330 = OpFAdd %6 %318 %329 OpLine %3 271 9 -%335 = OpFunctionCall %5 %77 %334 +%331 = OpFunctionCall %5 %77 %330 OpLine %3 271 9 -%336 = OpFMul %5 %335 %84 +%332 = OpFMul %5 %331 %84 OpLine %3 271 9 -%337 = OpFAdd %5 %336 %84 +%333 = OpFAdd %5 %332 %84 OpLine %3 272 17 -%338 = OpCompositeConstruct %6 %327 %328 -%339 = OpFAdd %6 %322 %338 +%334 = OpCompositeConstruct %6 %323 %324 +%335 = OpFAdd %6 %318 %334 OpLine %3 272 9 -%340 = OpFunctionCall %5 %77 %339 +%336 = OpFunctionCall %5 %77 %335 OpLine %3 272 9 -%341 = OpFMul %5 %340 %84 +%337 = OpFMul %5 %336 %84 OpLine %3 269 12 -%342 = OpFAdd %5 %341 %84 -%343 = OpCompositeConstruct %4 %332 %337 %342 -OpReturnValue %343 +%338 = OpFAdd %5 %337 %84 +%339 = OpCompositeConstruct %4 %328 %333 %338 +OpReturnValue %339 OpFunctionEnd -%348 = OpFunction %2 None %349 -%344 = OpLabel -%347 = OpLoad %19 %345 -%351 = OpAccessChain %350 %29 %131 -OpBranch %356 -%356 = OpLabel +%344 = OpFunction %2 None %345 +%340 = OpLabel +%343 = OpLoad %19 %341 +%347 = OpAccessChain %346 %29 %131 +OpBranch %352 +%352 = OpLabel OpLine %3 111 22 -%357 = OpCompositeExtract %8 %347 0 +%353 = OpCompositeExtract %8 %343 0 OpLine %3 113 36 -%359 = OpAccessChain %358 %351 %131 -%360 = OpLoad %10 %359 +%355 = OpAccessChain %354 %347 %131 +%356 = OpLoad %10 %355 OpLine %3 113 59 -%362 = OpAccessChain %361 %351 %122 -%363 = OpLoad %11 %362 +%358 = OpAccessChain %357 %347 %122 +%359 = OpLoad %11 %358 OpLine %3 113 13 -%364 = OpFunctionCall %6 %306 %357 %360 %363 +%360 = OpFunctionCall %6 %302 %353 %356 %359 OpLine %3 115 5 OpLine %3 115 51 -%368 = OpAccessChain %367 %351 %353 -%369 = OpLoad %6 %368 +%364 = OpAccessChain %363 %347 %349 +%365 = OpLoad %6 %364 OpLine %3 115 33 -%370 = OpFunctionCall %14 %273 %364 %369 +%366 = OpFunctionCall %14 %269 %360 %365 OpLine %3 115 5 -%371 = OpAccessChain %366 %32 %131 %357 -OpStore %371 %370 +%367 = OpAccessChain %362 %32 %131 %353 +OpStore %367 %366 OpLine %3 118 23 -%372 = OpCompositeExtract %8 %347 0 +%368 = OpCompositeExtract %8 %343 0 OpLine %3 118 23 -%373 = OpIMul %8 %372 %352 +%369 = OpIMul %8 %368 %348 OpLine %3 120 25 -%375 = OpAccessChain %374 %351 %131 %131 -%376 = OpLoad %8 %375 +%371 = OpAccessChain %370 %347 %131 %131 +%372 = OpLoad %8 %371 OpLine %3 120 25 -%377 = OpAccessChain %374 %351 %131 %122 -%378 = OpLoad %8 %377 -%379 = OpIMul %8 %376 %378 +%373 = OpAccessChain %370 %347 %131 %122 +%374 = OpLoad %8 %373 +%375 = OpIMul %8 %372 %374 OpLine %3 120 9 -%380 = OpIMul %8 %379 %352 -%381 = OpUGreaterThanEqual %107 %373 %380 +%376 = OpIMul %8 %375 %348 +%377 = OpUGreaterThanEqual %107 %369 %376 OpLine %3 120 5 -OpSelectionMerge %382 None -OpBranchConditional %381 %383 %382 -%383 = OpLabel +OpSelectionMerge %378 None +OpBranchConditional %377 %379 %378 +%379 = OpLabel OpReturn -%382 = OpLabel +%378 = OpLabel OpLine %3 122 28 -%384 = OpCompositeExtract %8 %347 0 +%380 = OpCompositeExtract %8 %343 0 OpLine %3 122 15 -%385 = OpAccessChain %374 %351 %131 %131 -%386 = OpLoad %8 %385 -%387 = OpUDiv %8 %384 %386 -%388 = OpIAdd %8 %357 %387 +%381 = OpAccessChain %370 %347 %131 %131 +%382 = OpLoad %8 %381 +%383 = OpUDiv %8 %380 %382 +%384 = OpIAdd %8 %353 %383 OpLine %3 123 15 +%385 = OpIAdd %8 %384 %122 +OpLine %3 124 15 +%386 = OpAccessChain %370 %347 %131 %131 +%387 = OpLoad %8 %386 +%388 = OpIAdd %8 %384 %387 +OpLine %3 124 15 %389 = OpIAdd %8 %388 %122 -OpLine %3 124 15 -%390 = OpAccessChain %374 %351 %131 %131 -%391 = OpLoad %8 %390 -%392 = OpIAdd %8 %388 %391 -OpLine %3 124 15 -%393 = OpIAdd %8 %392 %122 OpLine %3 125 15 -%394 = OpIAdd %8 %393 %122 +%390 = OpIAdd %8 %389 %122 OpLine %3 127 5 OpLine %3 127 5 -%397 = OpAccessChain %396 %34 %131 %373 -OpStore %397 %388 +%393 = OpAccessChain %392 %34 %131 %369 +OpStore %393 %384 OpLine %3 128 5 OpLine %3 128 5 -%398 = OpIAdd %8 %373 %122 +%394 = OpIAdd %8 %369 %122 OpLine %3 128 5 -%399 = OpAccessChain %396 %34 %131 %398 -OpStore %399 %393 +%395 = OpAccessChain %392 %34 %131 %394 +OpStore %395 %389 OpLine %3 129 5 OpLine %3 129 5 -%400 = OpIAdd %8 %373 %353 +%396 = OpIAdd %8 %369 %349 OpLine %3 129 5 -%401 = OpAccessChain %396 %34 %131 %400 -OpStore %401 %394 +%397 = OpAccessChain %392 %34 %131 %396 +OpStore %397 %390 OpLine %3 130 5 OpLine %3 130 5 -%402 = OpIAdd %8 %373 %354 +%398 = OpIAdd %8 %369 %350 OpLine %3 130 5 -%403 = OpAccessChain %396 %34 %131 %402 -OpStore %403 %388 +%399 = OpAccessChain %392 %34 %131 %398 +OpStore %399 %384 OpLine %3 131 5 OpLine %3 131 5 -%404 = OpIAdd %8 %373 %355 +%400 = OpIAdd %8 %369 %351 OpLine %3 131 5 -%405 = OpAccessChain %396 %34 %131 %404 -OpStore %405 %394 +%401 = OpAccessChain %392 %34 %131 %400 +OpStore %401 %390 OpLine %3 132 5 OpLine %3 132 5 -%406 = OpIAdd %8 %373 %215 +%402 = OpIAdd %8 %369 %215 OpLine %3 132 5 -%407 = OpAccessChain %396 %34 %131 %406 -OpStore %407 %389 +%403 = OpAccessChain %392 %34 %131 %402 +OpStore %403 %385 OpReturn OpFunctionEnd -%418 = OpFunction %2 None %349 -%408 = OpLabel -%411 = OpLoad %8 %409 -%420 = OpAccessChain %419 %36 %131 -OpBranch %422 -%422 = OpLabel +%414 = OpFunction %2 None %345 +%404 = OpLabel +%407 = OpLoad %8 %405 +%416 = OpAccessChain %415 %36 %131 +OpBranch %418 +%418 = OpLabel OpLine %3 161 19 -%423 = OpIAdd %8 %411 %353 +%419 = OpIAdd %8 %407 %349 OpLine %3 161 18 -%424 = OpUDiv %8 %423 %354 +%420 = OpUDiv %8 %419 %350 OpLine %3 161 13 -%425 = OpUMod %8 %424 %353 -%426 = OpConvertUToF %5 %425 +%421 = OpUMod %8 %420 %349 +%422 = OpConvertUToF %5 %421 OpLine %3 162 19 -%427 = OpIAdd %8 %411 %122 +%423 = OpIAdd %8 %407 %122 OpLine %3 162 18 -%428 = OpUDiv %8 %427 %354 +%424 = OpUDiv %8 %423 %350 OpLine %3 162 13 -%429 = OpUMod %8 %428 %353 -%430 = OpConvertUToF %5 %429 +%425 = OpUMod %8 %424 %349 +%426 = OpConvertUToF %5 %425 OpLine %3 163 14 -%431 = OpCompositeConstruct %6 %426 %430 +%427 = OpCompositeConstruct %6 %422 %426 OpLine %3 165 30 -%432 = OpVectorTimesScalar %6 %431 %85 -%433 = OpCompositeConstruct %6 %421 %421 -%434 = OpFAdd %6 %433 %432 +%428 = OpVectorTimesScalar %6 %427 %85 +%429 = OpCompositeConstruct %6 %417 %417 +%430 = OpFAdd %6 %429 %428 OpLine %3 165 20 -%435 = OpCompositeConstruct %7 %434 %83 %56 +%431 = OpCompositeConstruct %7 %430 %83 %56 OpLine %3 168 21 -%436 = OpCompositeExtract %5 %431 0 -OpLine %3 168 21 -%438 = OpAccessChain %437 %420 %354 -%439 = OpLoad %8 %438 -%440 = OpConvertUToF %5 %439 -%441 = OpFMul %5 %436 %440 -%442 = OpCompositeExtract %5 %431 1 +%433 = OpAccessChain %432 %416 %350 +%434 = OpLoad %8 %433 +%435 = OpConvertUToF %5 %434 +%436 = OpFMul %5 %422 %435 OpLine %3 168 17 -%443 = OpAccessChain %437 %420 %354 +%437 = OpAccessChain %432 %416 %350 +%438 = OpLoad %8 %437 +%439 = OpConvertUToF %5 %438 +%440 = OpFMul %5 %426 %439 +%441 = OpFAdd %5 %436 %440 +%442 = OpConvertFToU %8 %441 +OpLine %3 168 17 +%443 = OpAccessChain %432 %416 %351 %444 = OpLoad %8 %443 -%445 = OpConvertUToF %5 %444 -%446 = OpFMul %5 %442 %445 -%447 = OpFAdd %5 %441 %446 -%448 = OpConvertFToU %8 %447 -OpLine %3 168 17 -%449 = OpAccessChain %437 %420 %355 -%450 = OpLoad %8 %449 -%451 = OpIAdd %8 %448 %450 +%445 = OpIAdd %8 %442 %444 OpLine %3 170 12 -%452 = OpCompositeConstruct %21 %451 %435 %431 -%453 = OpCompositeExtract %8 %452 0 -OpStore %412 %453 -%454 = OpCompositeExtract %7 %452 1 -OpStore %414 %454 -%455 = OpCompositeExtract %6 %452 2 -OpStore %416 %455 +%446 = OpCompositeConstruct %21 %445 %431 %427 +%447 = OpCompositeExtract %8 %446 0 +OpStore %408 %447 +%448 = OpCompositeExtract %7 %446 1 +OpStore %410 %448 +%449 = OpCompositeExtract %6 %446 2 +OpStore %412 %449 OpReturn OpFunctionEnd -%470 = OpFunction %2 None %349 -%458 = OpLabel -%456 = OpVariable %206 Function %207 -%457 = OpVariable %210 Function %211 -%461 = OpLoad %8 %460 -%464 = OpLoad %7 %462 -%467 = OpLoad %6 %465 -%459 = OpCompositeConstruct %21 %461 %464 %467 -%471 = OpAccessChain %419 %36 %131 -OpBranch %473 -%473 = OpLabel +%464 = OpFunction %2 None %345 +%452 = OpLabel +%450 = OpVariable %206 Function %207 +%451 = OpVariable %210 Function %211 +%455 = OpLoad %8 %454 +%458 = OpLoad %7 %456 +%461 = OpLoad %6 %459 +%453 = OpCompositeConstruct %21 %455 %458 %461 +%465 = OpAccessChain %415 %36 %131 +OpBranch %467 +%467 = OpLabel OpLine %3 181 17 -%474 = OpCompositeExtract %6 %459 2 -%475 = OpCompositeExtract %5 %474 0 +%468 = OpCompositeExtract %6 %453 2 +%469 = OpCompositeExtract %5 %468 0 OpLine %3 181 17 -%476 = OpAccessChain %437 %471 %354 -%477 = OpLoad %8 %476 -%478 = OpConvertUToF %5 %477 -%479 = OpFMul %5 %475 %478 -%480 = OpCompositeExtract %6 %459 2 -%481 = OpCompositeExtract %5 %480 1 +%470 = OpAccessChain %432 %465 %350 +%471 = OpLoad %8 %470 +%472 = OpConvertUToF %5 %471 +%473 = OpFMul %5 %469 %472 +%474 = OpCompositeExtract %6 %453 2 +%475 = OpCompositeExtract %5 %474 1 OpLine %3 181 70 -%482 = OpAccessChain %437 %471 %354 -%483 = OpLoad %8 %482 +%476 = OpAccessChain %432 %465 %350 +%477 = OpLoad %8 %476 OpLine %3 181 13 -%484 = OpAccessChain %437 %471 %354 -%485 = OpLoad %8 %484 -%486 = OpIMul %8 %483 %485 -%487 = OpConvertUToF %5 %486 -%488 = OpFMul %5 %481 %487 -%489 = OpFAdd %5 %479 %488 -%490 = OpConvertFToU %8 %489 +%478 = OpAccessChain %432 %465 %350 +%479 = OpLoad %8 %478 +%480 = OpIMul %8 %477 %479 +%481 = OpConvertUToF %5 %480 +%482 = OpFMul %5 %475 %481 +%483 = OpFAdd %5 %473 %482 +%484 = OpConvertFToU %8 %483 OpLine %3 181 13 -%491 = OpAccessChain %437 %471 %355 -%492 = OpLoad %8 %491 -%493 = OpIAdd %8 %490 %492 +%485 = OpAccessChain %432 %465 %351 +%486 = OpLoad %8 %485 +%487 = OpIAdd %8 %484 %486 OpLine %3 182 32 -%494 = OpConvertUToF %5 %493 +%488 = OpConvertUToF %5 %487 OpLine %3 182 22 -%495 = OpFDiv %5 %494 %472 -%496 = OpExtInst %5 %1 Floor %495 -%497 = OpConvertFToU %8 %496 +%489 = OpFDiv %5 %488 %466 +%490 = OpExtInst %5 %1 Floor %489 +%491 = OpConvertFToU %8 %490 OpLine %3 183 22 -%498 = OpUMod %8 %493 %352 +%492 = OpUMod %8 %487 %348 OpLine %3 185 36 -%499 = OpAccessChain %358 %471 %131 -%500 = OpLoad %10 %499 +%493 = OpAccessChain %354 %465 %131 +%494 = OpLoad %10 %493 OpLine %3 185 57 -%501 = OpAccessChain %361 %471 %122 -%502 = OpLoad %11 %501 +%495 = OpAccessChain %357 %465 %122 +%496 = OpLoad %11 %495 OpLine %3 185 13 -%503 = OpFunctionCall %6 %306 %497 %500 %502 +%497 = OpFunctionCall %6 %302 %491 %494 %496 OpLine %3 186 31 -%504 = OpAccessChain %367 %471 %353 -%505 = OpLoad %6 %504 +%498 = OpAccessChain %363 %465 %349 +%499 = OpLoad %6 %498 OpLine %3 186 13 -%506 = OpFunctionCall %14 %273 %503 %505 +%500 = OpFunctionCall %14 %269 %497 %499 OpLine %3 188 5 -OpStore %456 %83 +OpStore %450 %83 OpLine %3 190 5 -OpSelectionMerge %507 None -OpSwitch %498 %514 0 %508 1 %509 2 %510 3 %511 4 %512 5 %513 -%508 = OpLabel +OpSelectionMerge %501 None +OpSwitch %492 %508 0 %502 1 %503 2 %504 3 %505 4 %506 5 %507 +%502 = OpLabel OpLine %3 191 37 -%515 = OpCompositeExtract %4 %506 0 -%516 = OpCompositeExtract %5 %515 0 +%509 = OpCompositeExtract %4 %500 0 +%510 = OpCompositeExtract %5 %509 0 OpLine %3 191 20 -OpStore %456 %516 -OpBranch %507 -%509 = OpLabel +OpStore %450 %510 +OpBranch %501 +%503 = OpLabel OpLine %3 192 37 -%517 = OpCompositeExtract %4 %506 0 -%518 = OpCompositeExtract %5 %517 1 +%511 = OpCompositeExtract %4 %500 0 +%512 = OpCompositeExtract %5 %511 1 OpLine %3 192 20 -OpStore %456 %518 -OpBranch %507 -%510 = OpLabel +OpStore %450 %512 +OpBranch %501 +%504 = OpLabel OpLine %3 193 37 -%519 = OpCompositeExtract %4 %506 0 -%520 = OpCompositeExtract %5 %519 2 +%513 = OpCompositeExtract %4 %500 0 +%514 = OpCompositeExtract %5 %513 2 OpLine %3 193 20 -OpStore %456 %520 -OpBranch %507 -%511 = OpLabel +OpStore %450 %514 +OpBranch %501 +%505 = OpLabel OpLine %3 194 37 -%521 = OpCompositeExtract %4 %506 1 -%522 = OpCompositeExtract %5 %521 0 +%515 = OpCompositeExtract %4 %500 1 +%516 = OpCompositeExtract %5 %515 0 OpLine %3 194 20 -OpStore %456 %522 -OpBranch %507 -%512 = OpLabel +OpStore %450 %516 +OpBranch %501 +%506 = OpLabel OpLine %3 195 37 -%523 = OpCompositeExtract %4 %506 1 -%524 = OpCompositeExtract %5 %523 1 +%517 = OpCompositeExtract %4 %500 1 +%518 = OpCompositeExtract %5 %517 1 OpLine %3 195 20 -OpStore %456 %524 -OpBranch %507 -%513 = OpLabel -OpLine %3 196 37 -%525 = OpCompositeExtract %4 %506 1 -%526 = OpCompositeExtract %5 %525 2 -OpLine %3 196 20 -OpStore %456 %526 -OpBranch %507 -%514 = OpLabel -OpBranch %507 +OpStore %450 %518 +OpBranch %501 %507 = OpLabel +OpLine %3 196 37 +%519 = OpCompositeExtract %4 %500 1 +%520 = OpCompositeExtract %5 %519 2 +OpLine %3 196 20 +OpStore %450 %520 +OpBranch %501 +%508 = OpLabel +OpBranch %501 +%501 = OpLabel OpLine %3 200 15 -%527 = OpAccessChain %374 %471 %131 %131 -%528 = OpLoad %8 %527 -%529 = OpUDiv %8 %497 %528 -%530 = OpIAdd %8 %497 %529 +%521 = OpAccessChain %370 %465 %131 %131 +%522 = OpLoad %8 %521 +%523 = OpUDiv %8 %491 %522 +%524 = OpIAdd %8 %491 %523 OpLine %3 201 15 -%531 = OpIAdd %8 %530 %122 +%525 = OpIAdd %8 %524 %122 OpLine %3 202 15 -%532 = OpAccessChain %374 %471 %131 %131 -%533 = OpLoad %8 %532 -%534 = OpIAdd %8 %530 %533 +%526 = OpAccessChain %370 %465 %131 %131 +%527 = OpLoad %8 %526 +%528 = OpIAdd %8 %524 %527 OpLine %3 202 15 -%535 = OpIAdd %8 %534 %122 +%529 = OpIAdd %8 %528 %122 OpLine %3 203 15 -%536 = OpIAdd %8 %535 %122 +%530 = OpIAdd %8 %529 %122 OpLine %3 205 5 -OpStore %457 %131 +OpStore %451 %131 OpLine %3 206 5 -OpSelectionMerge %537 None -OpSwitch %498 %542 0 %538 3 %538 2 %539 4 %539 1 %540 5 %541 -%538 = OpLabel +OpSelectionMerge %531 None +OpSwitch %492 %536 0 %532 3 %532 2 %533 4 %533 1 %534 5 %535 +%532 = OpLabel OpLine %3 207 24 -OpStore %457 %530 -OpBranch %537 -%539 = OpLabel +OpStore %451 %524 +OpBranch %531 +%533 = OpLabel OpLine %3 208 24 -OpStore %457 %536 -OpBranch %537 -%540 = OpLabel +OpStore %451 %530 +OpBranch %531 +%534 = OpLabel OpLine %3 209 20 -OpStore %457 %535 -OpBranch %537 -%541 = OpLabel +OpStore %451 %529 +OpBranch %531 +%535 = OpLabel OpLine %3 210 20 -OpStore %457 %531 -OpBranch %537 -%542 = OpLabel -OpBranch %537 -%537 = OpLabel +OpStore %451 %525 +OpBranch %531 +%536 = OpLabel +OpBranch %531 +%531 = OpLabel OpLine %3 213 13 -%543 = OpCompositeExtract %8 %459 0 +%537 = OpCompositeExtract %8 %453 0 OpLine %3 213 5 -OpStore %457 %543 +OpStore %451 %537 OpLine %3 222 27 -%544 = OpLoad %5 %456 -%545 = OpBitcast %8 %544 +%538 = OpLoad %5 %450 +%539 = OpBitcast %8 %538 OpLine %3 223 12 -%546 = OpLoad %8 %457 -%547 = OpCompositeConstruct %22 %545 %546 -%548 = OpCompositeExtract %8 %547 0 -OpStore %468 %548 -%549 = OpCompositeExtract %8 %547 1 -OpStore %469 %549 +%540 = OpLoad %8 %451 +%541 = OpCompositeConstruct %22 %539 %540 +%542 = OpCompositeExtract %8 %541 0 +OpStore %462 %542 +%543 = OpCompositeExtract %8 %541 1 +OpStore %463 %543 OpReturn OpFunctionEnd -%561 = OpFunction %2 None %349 -%550 = OpLabel -%554 = OpLoad %4 %552 -%556 = OpLoad %4 %555 -%551 = OpCompositeConstruct %14 %554 %556 -%563 = OpAccessChain %562 %39 %131 -OpBranch %564 -%564 = OpLabel +%555 = OpFunction %2 None %345 +%544 = OpLabel +%548 = OpLoad %4 %546 +%550 = OpLoad %4 %549 +%545 = OpCompositeConstruct %14 %548 %550 +%557 = OpAccessChain %556 %39 %131 +OpBranch %558 +%558 = OpLabel OpLine %3 254 25 -%566 = OpAccessChain %565 %563 %122 -%567 = OpLoad %23 %566 -%568 = OpCompositeExtract %4 %551 0 +%560 = OpAccessChain %559 %557 %122 +%561 = OpLoad %23 %560 +%562 = OpCompositeExtract %4 %545 0 OpLine %3 254 25 -%569 = OpCompositeConstruct %7 %568 %56 -%570 = OpMatrixTimesVector %7 %567 %569 +%563 = OpCompositeConstruct %7 %562 %56 +%564 = OpMatrixTimesVector %7 %561 %563 OpLine %3 255 18 -%571 = OpCompositeExtract %4 %551 1 +%565 = OpCompositeExtract %4 %545 1 OpLine %3 256 12 -%572 = OpCompositeExtract %4 %551 0 -%573 = OpCompositeConstruct %26 %570 %571 %572 -%574 = OpCompositeExtract %7 %573 0 -OpStore %557 %574 -%575 = OpCompositeExtract %4 %573 1 -OpStore %558 %575 -%576 = OpCompositeExtract %4 %573 2 -OpStore %560 %576 +%566 = OpCompositeExtract %4 %545 0 +%567 = OpCompositeConstruct %26 %564 %565 %566 +%568 = OpCompositeExtract %7 %567 0 +OpStore %551 %568 +%569 = OpCompositeExtract %4 %567 1 +OpStore %552 %569 +%570 = OpCompositeExtract %4 %567 2 +OpStore %554 %570 OpReturn OpFunctionEnd -%587 = OpFunction %2 None %349 -%578 = OpLabel -%577 = OpVariable %73 Function %74 -%581 = OpLoad %7 %580 -%583 = OpLoad %4 %582 -%585 = OpLoad %4 %584 -%579 = OpCompositeConstruct %26 %581 %583 %585 -%588 = OpAccessChain %562 %39 %131 -%590 = OpAccessChain %589 %42 %131 -OpBranch %593 -%593 = OpLabel +%581 = OpFunction %2 None %345 +%572 = OpLabel +%571 = OpVariable %73 Function %74 +%575 = OpLoad %7 %574 +%577 = OpLoad %4 %576 +%579 = OpLoad %4 %578 +%573 = OpCompositeConstruct %26 %575 %577 %579 +%582 = OpAccessChain %556 %39 %131 +%584 = OpAccessChain %583 %42 %131 +OpBranch %587 +%587 = OpLabel OpLine %3 278 28 -%594 = OpCompositeConstruct %4 %83 %83 %83 +%588 = OpCompositeConstruct %4 %83 %83 %83 OpLine %3 278 17 -%595 = OpCompositeConstruct %4 %275 %275 %275 -%596 = OpCompositeExtract %4 %579 2 -%597 = OpExtInst %4 %1 Fract %596 -%598 = OpExtInst %4 %1 SmoothStep %594 %595 %597 +%589 = OpCompositeConstruct %4 %271 %271 %271 +%590 = OpCompositeExtract %4 %573 2 +%591 = OpExtInst %4 %1 Fract %590 +%592 = OpExtInst %4 %1 SmoothStep %588 %589 %591 OpLine %3 278 5 -OpStore %577 %598 +OpStore %571 %592 OpLine %3 279 17 -%599 = OpCompositeConstruct %4 %84 %275 %591 +%593 = OpCompositeConstruct %4 %84 %271 %585 OpLine %3 279 13 -%600 = OpCompositeConstruct %4 %592 %592 %592 -%601 = OpAccessChain %121 %577 %131 -%602 = OpLoad %5 %601 -%603 = OpAccessChain %121 %577 %122 -%604 = OpLoad %5 %603 -%605 = OpFMul %5 %602 %604 -%606 = OpAccessChain %121 %577 %353 -%607 = OpLoad %5 %606 -%608 = OpFMul %5 %605 %607 -%609 = OpCompositeConstruct %4 %608 %608 %608 -%610 = OpExtInst %4 %1 FMix %599 %600 %609 +%594 = OpCompositeConstruct %4 %586 %586 %586 +%595 = OpAccessChain %121 %571 %131 +%596 = OpLoad %5 %595 +%597 = OpAccessChain %121 %571 %122 +%598 = OpLoad %5 %597 +%599 = OpFMul %5 %596 %598 +%600 = OpAccessChain %121 %571 %349 +%601 = OpLoad %5 %600 +%602 = OpFMul %5 %599 %601 +%603 = OpCompositeConstruct %4 %602 %602 %602 +%604 = OpExtInst %4 %1 FMix %593 %594 %603 OpLine %3 279 5 -OpStore %577 %610 +OpStore %571 %604 OpLine %3 282 25 -%612 = OpAccessChain %611 %590 %122 -%613 = OpLoad %4 %612 -%614 = OpVectorTimesScalar %4 %613 %275 +%606 = OpAccessChain %605 %584 %122 +%607 = OpLoad %4 %606 +%608 = OpVectorTimesScalar %4 %607 %271 OpLine %3 284 21 -%615 = OpAccessChain %611 %590 %131 -%616 = OpLoad %4 %615 -%617 = OpCompositeExtract %4 %579 2 -%618 = OpFSub %4 %616 %617 -%619 = OpExtInst %4 %1 Normalize %618 +%609 = OpAccessChain %605 %584 %131 +%610 = OpLoad %4 %609 +%611 = OpCompositeExtract %4 %573 2 +%612 = OpFSub %4 %610 %611 +%613 = OpExtInst %4 %1 Normalize %612 OpLine %3 285 20 -%621 = OpAccessChain %620 %588 %131 -%622 = OpLoad %7 %621 -%623 = OpVectorShuffle %4 %622 %622 0 1 2 -%624 = OpCompositeExtract %4 %579 2 -%625 = OpFSub %4 %623 %624 -%626 = OpExtInst %4 %1 Normalize %625 +%615 = OpAccessChain %614 %582 %131 +%616 = OpLoad %7 %615 +%617 = OpVectorShuffle %4 %616 %616 0 1 2 +%618 = OpCompositeExtract %4 %573 2 +%619 = OpFSub %4 %617 %618 +%620 = OpExtInst %4 %1 Normalize %619 OpLine %3 286 20 -%627 = OpFAdd %4 %626 %619 -%628 = OpExtInst %4 %1 Normalize %627 +%621 = OpFAdd %4 %620 %613 +%622 = OpExtInst %4 %1 Normalize %621 OpLine %3 288 32 -%629 = OpCompositeExtract %4 %579 1 -%630 = OpDot %5 %629 %619 +%623 = OpCompositeExtract %4 %573 1 +%624 = OpDot %5 %623 %613 OpLine %3 288 28 -%631 = OpExtInst %5 %1 FMax %630 %83 +%625 = OpExtInst %5 %1 FMax %624 %83 OpLine %3 289 25 -%632 = OpAccessChain %611 %590 %122 -%633 = OpLoad %4 %632 -%634 = OpVectorTimesScalar %4 %633 %631 +%626 = OpAccessChain %605 %584 %122 +%627 = OpLoad %4 %626 +%628 = OpVectorTimesScalar %4 %627 %625 OpLine %3 291 37 -%635 = OpCompositeExtract %4 %579 1 -%636 = OpDot %5 %635 %628 +%629 = OpCompositeExtract %4 %573 1 +%630 = OpDot %5 %629 %622 OpLine %3 291 33 -%637 = OpExtInst %5 %1 FMax %636 %83 +%631 = OpExtInst %5 %1 FMax %630 %83 OpLine %3 291 29 -%638 = OpExtInst %5 %1 Pow %637 %326 +%632 = OpExtInst %5 %1 Pow %631 %322 OpLine %3 292 26 -%639 = OpAccessChain %611 %590 %122 -%640 = OpLoad %4 %639 -%641 = OpVectorTimesScalar %4 %640 %638 +%633 = OpAccessChain %605 %584 %122 +%634 = OpLoad %4 %633 +%635 = OpVectorTimesScalar %4 %634 %632 OpLine %3 294 18 -%642 = OpFAdd %4 %614 %634 -%643 = OpFAdd %4 %642 %641 -%644 = OpLoad %4 %577 -%645 = OpFMul %4 %643 %644 +%636 = OpFAdd %4 %608 %628 +%637 = OpFAdd %4 %636 %635 +%638 = OpLoad %4 %571 +%639 = OpFMul %4 %637 %638 OpLine %3 296 12 -%646 = OpCompositeConstruct %7 %645 %56 -OpStore %586 %646 +%640 = OpCompositeConstruct %7 %639 %56 +OpStore %580 %640 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 1b6ef2887..06aa36bcb 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 523 +; Bound: 522 OpCapability Shader OpCapability Image1D OpCapability Sampled1D @@ -14,15 +14,15 @@ OpEntryPoint GLCompute %169 "depth_load" %167 OpEntryPoint Vertex %190 "queries" %188 OpEntryPoint Vertex %242 "levels_queries" %241 OpEntryPoint Fragment %274 "texture_sample" %273 -OpEntryPoint Fragment %421 "texture_sample_comparison" %419 -OpEntryPoint Fragment %476 "gather" %475 -OpEntryPoint Fragment %511 "depth_no_comparison" %510 +OpEntryPoint Fragment %420 "texture_sample_comparison" %418 +OpEntryPoint Fragment %475 "gather" %474 +OpEntryPoint Fragment %510 "depth_no_comparison" %509 OpExecutionMode %78 LocalSize 16 1 1 OpExecutionMode %169 LocalSize 16 1 1 OpExecutionMode %274 OriginUpperLeft -OpExecutionMode %421 OriginUpperLeft -OpExecutionMode %476 OriginUpperLeft -OpExecutionMode %511 OriginUpperLeft +OpExecutionMode %420 OriginUpperLeft +OpExecutionMode %475 OriginUpperLeft +OpExecutionMode %510 OriginUpperLeft OpName %31 "image_mipmapped_src" OpName %33 "image_multisampled_src" OpName %35 "image_depth_multisampled_src" @@ -53,10 +53,10 @@ OpName %190 "queries" OpName %242 "levels_queries" OpName %269 "a" OpName %274 "texture_sample" -OpName %415 "a" -OpName %421 "texture_sample_comparison" -OpName %476 "gather" -OpName %511 "depth_no_comparison" +OpName %414 "a" +OpName %420 "texture_sample_comparison" +OpName %475 "gather" +OpName %510 "depth_no_comparison" OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 0 OpDecorate %33 DescriptorSet 0 @@ -109,9 +109,9 @@ OpDecorate %167 BuiltIn LocalInvocationId OpDecorate %188 BuiltIn Position OpDecorate %241 BuiltIn Position OpDecorate %273 Location 0 -OpDecorate %419 Location 0 -OpDecorate %475 Location 0 -OpDecorate %510 Location 0 +OpDecorate %418 Location 0 +OpDecorate %474 Location 0 +OpDecorate %509 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpTypeImage %4 2D 0 0 0 1 Unknown @@ -206,25 +206,25 @@ OpDecorate %510 Location 0 %283 = OpConstant %14 0 %285 = OpTypeVector %7 2 %287 = OpTypeVector %7 3 -%290 = OpTypeSampledImage %15 -%295 = OpTypeSampledImage %16 -%316 = OpTypeSampledImage %18 -%377 = OpTypeSampledImage %20 -%416 = OpTypePointer Function %7 -%417 = OpConstantNull %7 -%420 = OpTypePointer Output %7 -%419 = OpVariable %420 Output -%429 = OpTypeSampledImage %25 -%434 = OpTypeSampledImage %26 -%447 = OpTypeSampledImage %27 -%454 = OpConstant %7 0.0 -%475 = OpVariable %189 Output -%487 = OpConstant %4 1 -%490 = OpConstant %4 3 -%495 = OpTypeSampledImage %3 -%498 = OpTypeVector %14 4 -%499 = OpTypeSampledImage %17 -%510 = OpVariable %189 Output +%289 = OpTypeSampledImage %15 +%294 = OpTypeSampledImage %16 +%315 = OpTypeSampledImage %18 +%376 = OpTypeSampledImage %20 +%415 = OpTypePointer Function %7 +%416 = OpConstantNull %7 +%419 = OpTypePointer Output %7 +%418 = OpVariable %419 Output +%428 = OpTypeSampledImage %25 +%433 = OpTypeSampledImage %26 +%446 = OpTypeSampledImage %27 +%453 = OpConstant %7 0.0 +%474 = OpVariable %189 Output +%486 = OpConstant %4 1 +%489 = OpConstant %4 3 +%494 = OpTypeSampledImage %3 +%497 = OpTypeVector %14 4 +%498 = OpTypeSampledImage %17 +%509 = OpVariable %189 Output %78 = OpFunction %2 None %79 %74 = OpLabel %77 = OpLoad %12 %75 @@ -435,263 +435,262 @@ OpBranch %284 %284 = OpLabel %286 = OpCompositeConstruct %285 %280 %280 %288 = OpCompositeConstruct %287 %280 %280 %280 -%289 = OpCompositeExtract %7 %286 0 -%291 = OpSampledImage %290 %275 %279 -%292 = OpImageSampleImplicitLod %23 %291 %289 -%293 = OpLoad %23 %269 -%294 = OpFAdd %23 %293 %292 -OpStore %269 %294 -%296 = OpSampledImage %295 %276 %279 -%297 = OpImageSampleImplicitLod %23 %296 %286 -%298 = OpLoad %23 %269 -%299 = OpFAdd %23 %298 %297 -OpStore %269 %299 -%300 = OpSampledImage %295 %276 %279 -%301 = OpImageSampleImplicitLod %23 %300 %286 ConstOffset %30 -%302 = OpLoad %23 %269 -%303 = OpFAdd %23 %302 %301 -OpStore %269 %303 -%304 = OpSampledImage %295 %276 %279 -%305 = OpImageSampleExplicitLod %23 %304 %286 Lod %281 -%306 = OpLoad %23 %269 -%307 = OpFAdd %23 %306 %305 -OpStore %269 %307 -%308 = OpSampledImage %295 %276 %279 -%309 = OpImageSampleExplicitLod %23 %308 %286 Lod|ConstOffset %281 %30 -%310 = OpLoad %23 %269 -%311 = OpFAdd %23 %310 %309 -OpStore %269 %311 -%312 = OpSampledImage %295 %276 %279 -%313 = OpImageSampleImplicitLod %23 %312 %286 Bias|ConstOffset %282 %30 -%314 = OpLoad %23 %269 -%315 = OpFAdd %23 %314 %313 -OpStore %269 %315 -%317 = OpConvertUToF %7 %199 -%318 = OpCompositeConstruct %287 %286 %317 -%319 = OpSampledImage %316 %277 %279 -%320 = OpImageSampleImplicitLod %23 %319 %318 -%321 = OpLoad %23 %269 -%322 = OpFAdd %23 %321 %320 -OpStore %269 %322 -%323 = OpConvertUToF %7 %199 -%324 = OpCompositeConstruct %287 %286 %323 -%325 = OpSampledImage %316 %277 %279 -%326 = OpImageSampleImplicitLod %23 %325 %324 ConstOffset %30 -%327 = OpLoad %23 %269 -%328 = OpFAdd %23 %327 %326 -OpStore %269 %328 -%329 = OpConvertUToF %7 %199 -%330 = OpCompositeConstruct %287 %286 %329 -%331 = OpSampledImage %316 %277 %279 -%332 = OpImageSampleExplicitLod %23 %331 %330 Lod %281 -%333 = OpLoad %23 %269 -%334 = OpFAdd %23 %333 %332 -OpStore %269 %334 -%335 = OpConvertUToF %7 %199 -%336 = OpCompositeConstruct %287 %286 %335 -%337 = OpSampledImage %316 %277 %279 -%338 = OpImageSampleExplicitLod %23 %337 %336 Lod|ConstOffset %281 %30 -%339 = OpLoad %23 %269 -%340 = OpFAdd %23 %339 %338 -OpStore %269 %340 -%341 = OpConvertUToF %7 %199 -%342 = OpCompositeConstruct %287 %286 %341 -%343 = OpSampledImage %316 %277 %279 -%344 = OpImageSampleImplicitLod %23 %343 %342 Bias|ConstOffset %282 %30 -%345 = OpLoad %23 %269 -%346 = OpFAdd %23 %345 %344 -OpStore %269 %346 -%347 = OpConvertSToF %7 %283 -%348 = OpCompositeConstruct %287 %286 %347 -%349 = OpSampledImage %316 %277 %279 -%350 = OpImageSampleImplicitLod %23 %349 %348 -%351 = OpLoad %23 %269 -%352 = OpFAdd %23 %351 %350 -OpStore %269 %352 -%353 = OpConvertSToF %7 %283 -%354 = OpCompositeConstruct %287 %286 %353 -%355 = OpSampledImage %316 %277 %279 -%356 = OpImageSampleImplicitLod %23 %355 %354 ConstOffset %30 -%357 = OpLoad %23 %269 -%358 = OpFAdd %23 %357 %356 -OpStore %269 %358 -%359 = OpConvertSToF %7 %283 -%360 = OpCompositeConstruct %287 %286 %359 -%361 = OpSampledImage %316 %277 %279 -%362 = OpImageSampleExplicitLod %23 %361 %360 Lod %281 -%363 = OpLoad %23 %269 -%364 = OpFAdd %23 %363 %362 -OpStore %269 %364 -%365 = OpConvertSToF %7 %283 -%366 = OpCompositeConstruct %287 %286 %365 -%367 = OpSampledImage %316 %277 %279 -%368 = OpImageSampleExplicitLod %23 %367 %366 Lod|ConstOffset %281 %30 -%369 = OpLoad %23 %269 -%370 = OpFAdd %23 %369 %368 -OpStore %269 %370 -%371 = OpConvertSToF %7 %283 -%372 = OpCompositeConstruct %287 %286 %371 -%373 = OpSampledImage %316 %277 %279 -%374 = OpImageSampleImplicitLod %23 %373 %372 Bias|ConstOffset %282 %30 -%375 = OpLoad %23 %269 -%376 = OpFAdd %23 %375 %374 -OpStore %269 %376 -%378 = OpConvertUToF %7 %199 -%379 = OpCompositeConstruct %23 %288 %378 -%380 = OpSampledImage %377 %278 %279 -%381 = OpImageSampleImplicitLod %23 %380 %379 -%382 = OpLoad %23 %269 -%383 = OpFAdd %23 %382 %381 -OpStore %269 %383 -%384 = OpConvertUToF %7 %199 -%385 = OpCompositeConstruct %23 %288 %384 -%386 = OpSampledImage %377 %278 %279 -%387 = OpImageSampleExplicitLod %23 %386 %385 Lod %281 -%388 = OpLoad %23 %269 -%389 = OpFAdd %23 %388 %387 -OpStore %269 %389 -%390 = OpConvertUToF %7 %199 -%391 = OpCompositeConstruct %23 %288 %390 -%392 = OpSampledImage %377 %278 %279 -%393 = OpImageSampleImplicitLod %23 %392 %391 Bias %282 -%394 = OpLoad %23 %269 -%395 = OpFAdd %23 %394 %393 -OpStore %269 %395 -%396 = OpConvertSToF %7 %283 -%397 = OpCompositeConstruct %23 %288 %396 -%398 = OpSampledImage %377 %278 %279 -%399 = OpImageSampleImplicitLod %23 %398 %397 -%400 = OpLoad %23 %269 -%401 = OpFAdd %23 %400 %399 -OpStore %269 %401 -%402 = OpConvertSToF %7 %283 -%403 = OpCompositeConstruct %23 %288 %402 -%404 = OpSampledImage %377 %278 %279 -%405 = OpImageSampleExplicitLod %23 %404 %403 Lod %281 -%406 = OpLoad %23 %269 -%407 = OpFAdd %23 %406 %405 -OpStore %269 %407 -%408 = OpConvertSToF %7 %283 -%409 = OpCompositeConstruct %23 %288 %408 -%410 = OpSampledImage %377 %278 %279 -%411 = OpImageSampleImplicitLod %23 %410 %409 Bias %282 -%412 = OpLoad %23 %269 -%413 = OpFAdd %23 %412 %411 -OpStore %269 %413 -%414 = OpLoad %23 %269 -OpStore %273 %414 +%290 = OpSampledImage %289 %275 %279 +%291 = OpImageSampleImplicitLod %23 %290 %280 +%292 = OpLoad %23 %269 +%293 = OpFAdd %23 %292 %291 +OpStore %269 %293 +%295 = OpSampledImage %294 %276 %279 +%296 = OpImageSampleImplicitLod %23 %295 %286 +%297 = OpLoad %23 %269 +%298 = OpFAdd %23 %297 %296 +OpStore %269 %298 +%299 = OpSampledImage %294 %276 %279 +%300 = OpImageSampleImplicitLod %23 %299 %286 ConstOffset %30 +%301 = OpLoad %23 %269 +%302 = OpFAdd %23 %301 %300 +OpStore %269 %302 +%303 = OpSampledImage %294 %276 %279 +%304 = OpImageSampleExplicitLod %23 %303 %286 Lod %281 +%305 = OpLoad %23 %269 +%306 = OpFAdd %23 %305 %304 +OpStore %269 %306 +%307 = OpSampledImage %294 %276 %279 +%308 = OpImageSampleExplicitLod %23 %307 %286 Lod|ConstOffset %281 %30 +%309 = OpLoad %23 %269 +%310 = OpFAdd %23 %309 %308 +OpStore %269 %310 +%311 = OpSampledImage %294 %276 %279 +%312 = OpImageSampleImplicitLod %23 %311 %286 Bias|ConstOffset %282 %30 +%313 = OpLoad %23 %269 +%314 = OpFAdd %23 %313 %312 +OpStore %269 %314 +%316 = OpConvertUToF %7 %199 +%317 = OpCompositeConstruct %287 %286 %316 +%318 = OpSampledImage %315 %277 %279 +%319 = OpImageSampleImplicitLod %23 %318 %317 +%320 = OpLoad %23 %269 +%321 = OpFAdd %23 %320 %319 +OpStore %269 %321 +%322 = OpConvertUToF %7 %199 +%323 = OpCompositeConstruct %287 %286 %322 +%324 = OpSampledImage %315 %277 %279 +%325 = OpImageSampleImplicitLod %23 %324 %323 ConstOffset %30 +%326 = OpLoad %23 %269 +%327 = OpFAdd %23 %326 %325 +OpStore %269 %327 +%328 = OpConvertUToF %7 %199 +%329 = OpCompositeConstruct %287 %286 %328 +%330 = OpSampledImage %315 %277 %279 +%331 = OpImageSampleExplicitLod %23 %330 %329 Lod %281 +%332 = OpLoad %23 %269 +%333 = OpFAdd %23 %332 %331 +OpStore %269 %333 +%334 = OpConvertUToF %7 %199 +%335 = OpCompositeConstruct %287 %286 %334 +%336 = OpSampledImage %315 %277 %279 +%337 = OpImageSampleExplicitLod %23 %336 %335 Lod|ConstOffset %281 %30 +%338 = OpLoad %23 %269 +%339 = OpFAdd %23 %338 %337 +OpStore %269 %339 +%340 = OpConvertUToF %7 %199 +%341 = OpCompositeConstruct %287 %286 %340 +%342 = OpSampledImage %315 %277 %279 +%343 = OpImageSampleImplicitLod %23 %342 %341 Bias|ConstOffset %282 %30 +%344 = OpLoad %23 %269 +%345 = OpFAdd %23 %344 %343 +OpStore %269 %345 +%346 = OpConvertSToF %7 %283 +%347 = OpCompositeConstruct %287 %286 %346 +%348 = OpSampledImage %315 %277 %279 +%349 = OpImageSampleImplicitLod %23 %348 %347 +%350 = OpLoad %23 %269 +%351 = OpFAdd %23 %350 %349 +OpStore %269 %351 +%352 = OpConvertSToF %7 %283 +%353 = OpCompositeConstruct %287 %286 %352 +%354 = OpSampledImage %315 %277 %279 +%355 = OpImageSampleImplicitLod %23 %354 %353 ConstOffset %30 +%356 = OpLoad %23 %269 +%357 = OpFAdd %23 %356 %355 +OpStore %269 %357 +%358 = OpConvertSToF %7 %283 +%359 = OpCompositeConstruct %287 %286 %358 +%360 = OpSampledImage %315 %277 %279 +%361 = OpImageSampleExplicitLod %23 %360 %359 Lod %281 +%362 = OpLoad %23 %269 +%363 = OpFAdd %23 %362 %361 +OpStore %269 %363 +%364 = OpConvertSToF %7 %283 +%365 = OpCompositeConstruct %287 %286 %364 +%366 = OpSampledImage %315 %277 %279 +%367 = OpImageSampleExplicitLod %23 %366 %365 Lod|ConstOffset %281 %30 +%368 = OpLoad %23 %269 +%369 = OpFAdd %23 %368 %367 +OpStore %269 %369 +%370 = OpConvertSToF %7 %283 +%371 = OpCompositeConstruct %287 %286 %370 +%372 = OpSampledImage %315 %277 %279 +%373 = OpImageSampleImplicitLod %23 %372 %371 Bias|ConstOffset %282 %30 +%374 = OpLoad %23 %269 +%375 = OpFAdd %23 %374 %373 +OpStore %269 %375 +%377 = OpConvertUToF %7 %199 +%378 = OpCompositeConstruct %23 %288 %377 +%379 = OpSampledImage %376 %278 %279 +%380 = OpImageSampleImplicitLod %23 %379 %378 +%381 = OpLoad %23 %269 +%382 = OpFAdd %23 %381 %380 +OpStore %269 %382 +%383 = OpConvertUToF %7 %199 +%384 = OpCompositeConstruct %23 %288 %383 +%385 = OpSampledImage %376 %278 %279 +%386 = OpImageSampleExplicitLod %23 %385 %384 Lod %281 +%387 = OpLoad %23 %269 +%388 = OpFAdd %23 %387 %386 +OpStore %269 %388 +%389 = OpConvertUToF %7 %199 +%390 = OpCompositeConstruct %23 %288 %389 +%391 = OpSampledImage %376 %278 %279 +%392 = OpImageSampleImplicitLod %23 %391 %390 Bias %282 +%393 = OpLoad %23 %269 +%394 = OpFAdd %23 %393 %392 +OpStore %269 %394 +%395 = OpConvertSToF %7 %283 +%396 = OpCompositeConstruct %23 %288 %395 +%397 = OpSampledImage %376 %278 %279 +%398 = OpImageSampleImplicitLod %23 %397 %396 +%399 = OpLoad %23 %269 +%400 = OpFAdd %23 %399 %398 +OpStore %269 %400 +%401 = OpConvertSToF %7 %283 +%402 = OpCompositeConstruct %23 %288 %401 +%403 = OpSampledImage %376 %278 %279 +%404 = OpImageSampleExplicitLod %23 %403 %402 Lod %281 +%405 = OpLoad %23 %269 +%406 = OpFAdd %23 %405 %404 +OpStore %269 %406 +%407 = OpConvertSToF %7 %283 +%408 = OpCompositeConstruct %23 %288 %407 +%409 = OpSampledImage %376 %278 %279 +%410 = OpImageSampleImplicitLod %23 %409 %408 Bias %282 +%411 = OpLoad %23 %269 +%412 = OpFAdd %23 %411 %410 +OpStore %269 %412 +%413 = OpLoad %23 %269 +OpStore %273 %413 OpReturn OpFunctionEnd -%421 = OpFunction %2 None %79 -%418 = OpLabel -%415 = OpVariable %416 Function %417 -%422 = OpLoad %24 %66 -%423 = OpLoad %25 %68 -%424 = OpLoad %26 %70 -%425 = OpLoad %27 %72 -OpBranch %426 -%426 = OpLabel -%427 = OpCompositeConstruct %285 %280 %280 -%428 = OpCompositeConstruct %287 %280 %280 %280 -%430 = OpSampledImage %429 %423 %422 -%431 = OpImageSampleDrefImplicitLod %7 %430 %427 %280 -%432 = OpLoad %7 %415 -%433 = OpFAdd %7 %432 %431 -OpStore %415 %433 -%435 = OpConvertUToF %7 %199 -%436 = OpCompositeConstruct %287 %427 %435 -%437 = OpSampledImage %434 %424 %422 -%438 = OpImageSampleDrefImplicitLod %7 %437 %436 %280 -%439 = OpLoad %7 %415 -%440 = OpFAdd %7 %439 %438 -OpStore %415 %440 -%441 = OpConvertSToF %7 %283 -%442 = OpCompositeConstruct %287 %427 %441 -%443 = OpSampledImage %434 %424 %422 -%444 = OpImageSampleDrefImplicitLod %7 %443 %442 %280 -%445 = OpLoad %7 %415 -%446 = OpFAdd %7 %445 %444 -OpStore %415 %446 -%448 = OpSampledImage %447 %425 %422 -%449 = OpImageSampleDrefImplicitLod %7 %448 %428 %280 -%450 = OpLoad %7 %415 -%451 = OpFAdd %7 %450 %449 -OpStore %415 %451 -%452 = OpSampledImage %429 %423 %422 -%453 = OpImageSampleDrefExplicitLod %7 %452 %427 %280 Lod %454 -%455 = OpLoad %7 %415 -%456 = OpFAdd %7 %455 %453 -OpStore %415 %456 -%457 = OpConvertUToF %7 %199 -%458 = OpCompositeConstruct %287 %427 %457 -%459 = OpSampledImage %434 %424 %422 -%460 = OpImageSampleDrefExplicitLod %7 %459 %458 %280 Lod %454 -%461 = OpLoad %7 %415 -%462 = OpFAdd %7 %461 %460 -OpStore %415 %462 -%463 = OpConvertSToF %7 %283 -%464 = OpCompositeConstruct %287 %427 %463 -%465 = OpSampledImage %434 %424 %422 -%466 = OpImageSampleDrefExplicitLod %7 %465 %464 %280 Lod %454 -%467 = OpLoad %7 %415 -%468 = OpFAdd %7 %467 %466 -OpStore %415 %468 -%469 = OpSampledImage %447 %425 %422 -%470 = OpImageSampleDrefExplicitLod %7 %469 %428 %280 Lod %454 -%471 = OpLoad %7 %415 -%472 = OpFAdd %7 %471 %470 -OpStore %415 %472 -%473 = OpLoad %7 %415 -OpStore %419 %473 +%420 = OpFunction %2 None %79 +%417 = OpLabel +%414 = OpVariable %415 Function %416 +%421 = OpLoad %24 %66 +%422 = OpLoad %25 %68 +%423 = OpLoad %26 %70 +%424 = OpLoad %27 %72 +OpBranch %425 +%425 = OpLabel +%426 = OpCompositeConstruct %285 %280 %280 +%427 = OpCompositeConstruct %287 %280 %280 %280 +%429 = OpSampledImage %428 %422 %421 +%430 = OpImageSampleDrefImplicitLod %7 %429 %426 %280 +%431 = OpLoad %7 %414 +%432 = OpFAdd %7 %431 %430 +OpStore %414 %432 +%434 = OpConvertUToF %7 %199 +%435 = OpCompositeConstruct %287 %426 %434 +%436 = OpSampledImage %433 %423 %421 +%437 = OpImageSampleDrefImplicitLod %7 %436 %435 %280 +%438 = OpLoad %7 %414 +%439 = OpFAdd %7 %438 %437 +OpStore %414 %439 +%440 = OpConvertSToF %7 %283 +%441 = OpCompositeConstruct %287 %426 %440 +%442 = OpSampledImage %433 %423 %421 +%443 = OpImageSampleDrefImplicitLod %7 %442 %441 %280 +%444 = OpLoad %7 %414 +%445 = OpFAdd %7 %444 %443 +OpStore %414 %445 +%447 = OpSampledImage %446 %424 %421 +%448 = OpImageSampleDrefImplicitLod %7 %447 %427 %280 +%449 = OpLoad %7 %414 +%450 = OpFAdd %7 %449 %448 +OpStore %414 %450 +%451 = OpSampledImage %428 %422 %421 +%452 = OpImageSampleDrefExplicitLod %7 %451 %426 %280 Lod %453 +%454 = OpLoad %7 %414 +%455 = OpFAdd %7 %454 %452 +OpStore %414 %455 +%456 = OpConvertUToF %7 %199 +%457 = OpCompositeConstruct %287 %426 %456 +%458 = OpSampledImage %433 %423 %421 +%459 = OpImageSampleDrefExplicitLod %7 %458 %457 %280 Lod %453 +%460 = OpLoad %7 %414 +%461 = OpFAdd %7 %460 %459 +OpStore %414 %461 +%462 = OpConvertSToF %7 %283 +%463 = OpCompositeConstruct %287 %426 %462 +%464 = OpSampledImage %433 %423 %421 +%465 = OpImageSampleDrefExplicitLod %7 %464 %463 %280 Lod %453 +%466 = OpLoad %7 %414 +%467 = OpFAdd %7 %466 %465 +OpStore %414 %467 +%468 = OpSampledImage %446 %424 %421 +%469 = OpImageSampleDrefExplicitLod %7 %468 %427 %280 Lod %453 +%470 = OpLoad %7 %414 +%471 = OpFAdd %7 %470 %469 +OpStore %414 %471 +%472 = OpLoad %7 %414 +OpStore %418 %472 OpReturn OpFunctionEnd -%476 = OpFunction %2 None %79 -%474 = OpLabel -%477 = OpLoad %16 %49 -%478 = OpLoad %3 %51 -%479 = OpLoad %17 %52 -%480 = OpLoad %24 %64 -%481 = OpLoad %24 %66 -%482 = OpLoad %25 %68 -OpBranch %483 -%483 = OpLabel -%484 = OpCompositeConstruct %285 %280 %280 -%485 = OpSampledImage %295 %477 %480 -%486 = OpImageGather %23 %485 %484 %487 -%488 = OpSampledImage %295 %477 %480 -%489 = OpImageGather %23 %488 %484 %490 ConstOffset %30 -%491 = OpSampledImage %429 %482 %481 -%492 = OpImageDrefGather %23 %491 %484 %280 -%493 = OpSampledImage %429 %482 %481 -%494 = OpImageDrefGather %23 %493 %484 %280 ConstOffset %30 -%496 = OpSampledImage %495 %478 %480 -%497 = OpImageGather %98 %496 %484 %199 -%500 = OpSampledImage %499 %479 %480 -%501 = OpImageGather %498 %500 %484 %199 -%502 = OpConvertUToF %23 %497 -%503 = OpConvertSToF %23 %501 -%504 = OpFAdd %23 %502 %503 -%505 = OpFAdd %23 %486 %489 -%506 = OpFAdd %23 %505 %492 -%507 = OpFAdd %23 %506 %494 -%508 = OpFAdd %23 %507 %504 -OpStore %475 %508 +%475 = OpFunction %2 None %79 +%473 = OpLabel +%476 = OpLoad %16 %49 +%477 = OpLoad %3 %51 +%478 = OpLoad %17 %52 +%479 = OpLoad %24 %64 +%480 = OpLoad %24 %66 +%481 = OpLoad %25 %68 +OpBranch %482 +%482 = OpLabel +%483 = OpCompositeConstruct %285 %280 %280 +%484 = OpSampledImage %294 %476 %479 +%485 = OpImageGather %23 %484 %483 %486 +%487 = OpSampledImage %294 %476 %479 +%488 = OpImageGather %23 %487 %483 %489 ConstOffset %30 +%490 = OpSampledImage %428 %481 %480 +%491 = OpImageDrefGather %23 %490 %483 %280 +%492 = OpSampledImage %428 %481 %480 +%493 = OpImageDrefGather %23 %492 %483 %280 ConstOffset %30 +%495 = OpSampledImage %494 %477 %479 +%496 = OpImageGather %98 %495 %483 %199 +%499 = OpSampledImage %498 %478 %479 +%500 = OpImageGather %497 %499 %483 %199 +%501 = OpConvertUToF %23 %496 +%502 = OpConvertSToF %23 %500 +%503 = OpFAdd %23 %501 %502 +%504 = OpFAdd %23 %485 %488 +%505 = OpFAdd %23 %504 %491 +%506 = OpFAdd %23 %505 %493 +%507 = OpFAdd %23 %506 %503 +OpStore %474 %507 OpReturn OpFunctionEnd -%511 = OpFunction %2 None %79 -%509 = OpLabel -%512 = OpLoad %24 %64 -%513 = OpLoad %25 %68 -OpBranch %514 -%514 = OpLabel -%515 = OpCompositeConstruct %285 %280 %280 -%516 = OpSampledImage %429 %513 %512 -%517 = OpImageSampleImplicitLod %23 %516 %515 -%518 = OpCompositeExtract %7 %517 0 -%519 = OpSampledImage %429 %513 %512 -%520 = OpImageGather %23 %519 %515 %199 -%521 = OpCompositeConstruct %23 %518 %518 %518 %518 -%522 = OpFAdd %23 %521 %520 -OpStore %510 %522 +%510 = OpFunction %2 None %79 +%508 = OpLabel +%511 = OpLoad %24 %64 +%512 = OpLoad %25 %68 +OpBranch %513 +%513 = OpLabel +%514 = OpCompositeConstruct %285 %280 %280 +%515 = OpSampledImage %428 %512 %511 +%516 = OpImageSampleImplicitLod %23 %515 %514 +%517 = OpCompositeExtract %7 %516 0 +%518 = OpSampledImage %428 %512 %511 +%519 = OpImageGather %23 %518 %514 %199 +%520 = OpCompositeConstruct %23 %517 %517 %517 %517 +%521 = OpFAdd %23 %520 %519 +OpStore %509 %521 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 71bd913f7..5e2125b72 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 522 +; Bound: 450 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %511 "main" -OpExecutionMode %511 LocalSize 1 1 1 +OpEntryPoint GLCompute %439 "main" +OpExecutionMode %439 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -16,569 +16,497 @@ OpExecutionMode %511 LocalSize 1 1 1 %7 = OpTypeVector %8 4 %9 = OpTypeVector %4 2 %10 = OpTypeVector %4 3 -%11 = OpTypeMatrix %10 3 -%12 = OpTypeMatrix %10 4 -%13 = OpTypeMatrix %3 3 -%14 = OpTypeVector %6 3 -%15 = OpConstant %4 1.0 -%16 = OpConstantComposite %3 %15 %15 %15 %15 -%17 = OpConstant %4 0.0 -%18 = OpConstantComposite %3 %17 %17 %17 %17 -%19 = OpConstant %4 0.5 -%20 = OpConstantComposite %3 %19 %19 %19 %19 -%21 = OpConstant %6 1 -%22 = OpConstantComposite %5 %21 %21 %21 %21 -%25 = OpTypeFunction %3 -%26 = OpConstantTrue %8 -%27 = OpConstant %6 0 -%28 = OpConstantFalse %8 -%29 = OpConstant %4 0.1 -%54 = OpConstant %4 2.0 -%55 = OpConstant %4 3.0 -%56 = OpConstant %4 4.0 -%57 = OpConstant %6 5 -%58 = OpConstant %6 2 -%74 = OpTypePointer Function %9 -%75 = OpConstantNull %9 -%78 = OpTypeFunction %9 -%94 = OpTypeFunction %10 %10 -%96 = OpTypeVector %8 3 -%97 = OpConstantComposite %10 %17 %17 %17 -%99 = OpConstantComposite %10 %15 %15 %15 -%103 = OpTypeFunction %2 -%106 = OpTypeVector %8 2 -%121 = OpConstant %4 -1.0 -%122 = OpTypeInt 32 0 -%123 = OpConstant %122 2 -%124 = OpConstant %122 1 -%125 = OpConstantNull %11 -%126 = OpConstantNull %12 -%127 = OpConstantNull %13 -%129 = OpTypeVector %6 2 -%140 = OpTypeVector %122 3 -%203 = OpTypeVector %122 2 -%438 = OpTypePointer Function %6 -%439 = OpConstantNull %6 -%441 = OpTypePointer Function %14 -%442 = OpConstantNull %14 -%472 = OpTypePointer Function %6 -%483 = OpConstant %6 -1 -%484 = OpConstant %6 -2 -%485 = OpConstant %6 -3 -%486 = OpConstant %6 4 -%487 = OpConstant %6 -5 -%488 = OpConstant %6 6 -%489 = OpConstant %6 -7 -%490 = OpConstant %6 -8 -%24 = OpFunction %3 None %25 -%23 = OpLabel -OpBranch %30 -%30 = OpLabel -%31 = OpSelect %6 %26 %21 %27 -%33 = OpCompositeConstruct %7 %26 %26 %26 %26 -%32 = OpSelect %3 %33 %16 %18 -%34 = OpCompositeConstruct %7 %28 %28 %28 %28 -%35 = OpSelect %3 %34 %18 %16 -%36 = OpExtInst %3 %1 FMix %18 %16 %20 -%38 = OpCompositeConstruct %3 %29 %29 %29 %29 -%37 = OpExtInst %3 %1 FMix %18 %16 %38 -%39 = OpCompositeExtract %6 %22 0 -%40 = OpBitcast %4 %39 -%41 = OpBitcast %3 %22 -%42 = OpConvertFToS %5 %18 -%43 = OpCompositeConstruct %5 %31 %31 %31 %31 -%44 = OpIAdd %5 %43 %42 -%45 = OpConvertSToF %3 %44 -%46 = OpFAdd %3 %45 %32 -%47 = OpFAdd %3 %46 %36 -%48 = OpFAdd %3 %47 %37 -%49 = OpCompositeConstruct %3 %40 %40 %40 %40 -%50 = OpFAdd %3 %48 %49 +%11 = OpTypeVector %8 2 +%12 = OpTypeVector %6 2 +%14 = OpTypeInt 32 0 +%13 = OpTypeVector %14 3 +%15 = OpTypeVector %14 2 +%16 = OpTypeMatrix %10 3 +%17 = OpTypeMatrix %10 4 +%18 = OpTypeMatrix %3 3 +%19 = OpTypeVector %6 3 +%20 = OpConstant %4 1.0 +%21 = OpConstantComposite %3 %20 %20 %20 %20 +%22 = OpConstant %4 0.0 +%23 = OpConstantComposite %3 %22 %22 %22 %22 +%24 = OpConstant %4 0.5 +%25 = OpConstantComposite %3 %24 %24 %24 %24 +%26 = OpConstant %6 1 +%27 = OpConstantComposite %5 %26 %26 %26 %26 +%30 = OpTypeFunction %3 +%31 = OpConstantTrue %8 +%32 = OpConstant %6 0 +%33 = OpConstantFalse %8 +%34 = OpConstant %4 0.1 +%58 = OpConstant %4 2.0 +%59 = OpConstant %4 3.0 +%60 = OpConstant %4 4.0 +%61 = OpConstant %6 5 +%62 = OpConstant %6 2 +%78 = OpTypePointer Function %9 +%79 = OpConstantNull %9 +%82 = OpTypeFunction %9 +%98 = OpTypeFunction %10 %10 +%100 = OpTypeVector %8 3 +%101 = OpConstantComposite %10 %22 %22 %22 +%103 = OpConstantComposite %10 %20 %20 %20 +%107 = OpTypeFunction %2 +%120 = OpConstant %4 -1.0 +%121 = OpConstant %6 -1 +%122 = OpConstant %6 3 +%123 = OpConstant %14 3 +%124 = OpConstant %14 2 +%125 = OpConstant %14 1 +%126 = OpConstant %14 0 +%127 = OpConstantNull %16 +%128 = OpConstantNull %17 +%129 = OpConstantNull %18 +%293 = OpConstant %6 -2 +%294 = OpConstant %14 4294967294 +%295 = OpConstant %6 4 +%296 = OpConstant %14 4 +%388 = OpTypePointer Function %6 +%389 = OpConstantNull %6 +%391 = OpTypePointer Function %19 +%392 = OpConstantNull %19 +%422 = OpTypePointer Function %6 +%433 = OpConstant %6 -5 +%434 = OpConstant %6 6 +%435 = OpConstant %6 -7 +%436 = OpConstant %6 -8 +%29 = OpFunction %3 None %30 +%28 = OpLabel +OpBranch %35 +%35 = OpLabel +%36 = OpSelect %6 %31 %26 %32 +%38 = OpCompositeConstruct %7 %31 %31 %31 %31 +%37 = OpSelect %3 %38 %21 %23 +%39 = OpCompositeConstruct %7 %33 %33 %33 %33 +%40 = OpSelect %3 %39 %23 %21 +%41 = OpExtInst %3 %1 FMix %23 %21 %25 +%43 = OpCompositeConstruct %3 %34 %34 %34 %34 +%42 = OpExtInst %3 %1 FMix %23 %21 %43 +%44 = OpBitcast %4 %26 +%45 = OpBitcast %3 %27 +%46 = OpCompositeConstruct %5 %32 %32 %32 %32 +%47 = OpCompositeConstruct %5 %36 %36 %36 %36 +%48 = OpIAdd %5 %47 %46 +%49 = OpConvertSToF %3 %48 +%50 = OpFAdd %3 %49 %37 %51 = OpFAdd %3 %50 %41 -OpReturnValue %51 +%52 = OpFAdd %3 %51 %42 +%53 = OpCompositeConstruct %3 %44 %44 %44 %44 +%54 = OpFAdd %3 %52 %53 +%55 = OpFAdd %3 %54 %45 +OpReturnValue %55 OpFunctionEnd -%53 = OpFunction %3 None %25 -%52 = OpLabel -OpBranch %59 -%59 = OpLabel -%60 = OpCompositeConstruct %9 %54 %54 -%61 = OpCompositeConstruct %9 %15 %15 -%62 = OpFAdd %9 %61 %60 -%63 = OpCompositeConstruct %9 %55 %55 -%64 = OpFSub %9 %62 %63 -%65 = OpCompositeConstruct %9 %56 %56 -%66 = OpFDiv %9 %64 %65 -%67 = OpCompositeConstruct %5 %57 %57 %57 %57 -%68 = OpCompositeConstruct %5 %58 %58 %58 %58 -%69 = OpSRem %5 %67 %68 -%70 = OpVectorShuffle %3 %66 %66 0 1 0 1 -%71 = OpConvertSToF %3 %69 -%72 = OpFAdd %3 %70 %71 -OpReturnValue %72 +%57 = OpFunction %3 None %30 +%56 = OpLabel +OpBranch %63 +%63 = OpLabel +%64 = OpCompositeConstruct %9 %58 %58 +%65 = OpCompositeConstruct %9 %20 %20 +%66 = OpFAdd %9 %65 %64 +%67 = OpCompositeConstruct %9 %59 %59 +%68 = OpFSub %9 %66 %67 +%69 = OpCompositeConstruct %9 %60 %60 +%70 = OpFDiv %9 %68 %69 +%71 = OpCompositeConstruct %5 %61 %61 %61 %61 +%72 = OpCompositeConstruct %5 %62 %62 %62 %62 +%73 = OpSRem %5 %71 %72 +%74 = OpVectorShuffle %3 %70 %70 0 1 0 1 +%75 = OpConvertSToF %3 %73 +%76 = OpFAdd %3 %74 %75 +OpReturnValue %76 OpFunctionEnd -%77 = OpFunction %9 None %78 -%76 = OpLabel -%73 = OpVariable %74 Function %75 -OpBranch %79 -%79 = OpLabel -%80 = OpCompositeConstruct %9 %54 %54 -OpStore %73 %80 -%81 = OpLoad %9 %73 -%82 = OpCompositeConstruct %9 %15 %15 -%83 = OpFAdd %9 %81 %82 -OpStore %73 %83 -%84 = OpLoad %9 %73 -%85 = OpCompositeConstruct %9 %55 %55 -%86 = OpFSub %9 %84 %85 -OpStore %73 %86 -%87 = OpLoad %9 %73 -%88 = OpCompositeConstruct %9 %56 %56 -%89 = OpFDiv %9 %87 %88 -OpStore %73 %89 -%90 = OpLoad %9 %73 -OpReturnValue %90 +%81 = OpFunction %9 None %82 +%80 = OpLabel +%77 = OpVariable %78 Function %79 +OpBranch %83 +%83 = OpLabel +%84 = OpCompositeConstruct %9 %58 %58 +OpStore %77 %84 +%85 = OpLoad %9 %77 +%86 = OpCompositeConstruct %9 %20 %20 +%87 = OpFAdd %9 %85 %86 +OpStore %77 %87 +%88 = OpLoad %9 %77 +%89 = OpCompositeConstruct %9 %59 %59 +%90 = OpFSub %9 %88 %89 +OpStore %77 %90 +%91 = OpLoad %9 %77 +%92 = OpCompositeConstruct %9 %60 %60 +%93 = OpFDiv %9 %91 %92 +OpStore %77 %93 +%94 = OpLoad %9 %77 +OpReturnValue %94 OpFunctionEnd -%93 = OpFunction %10 None %94 -%92 = OpFunctionParameter %10 -%91 = OpLabel -OpBranch %95 +%97 = OpFunction %10 None %98 +%96 = OpFunctionParameter %10 %95 = OpLabel -%98 = OpFUnordNotEqual %96 %92 %97 -%100 = OpSelect %10 %98 %99 %97 -OpReturnValue %100 +OpBranch %99 +%99 = OpLabel +%102 = OpFUnordNotEqual %100 %96 %101 +%104 = OpSelect %10 %102 %103 %101 +OpReturnValue %104 OpFunctionEnd -%102 = OpFunction %2 None %103 -%101 = OpLabel -OpBranch %104 -%104 = OpLabel -%105 = OpLogicalNot %8 %26 -%107 = OpCompositeConstruct %106 %26 %26 -%108 = OpLogicalNot %106 %107 -%109 = OpLogicalOr %8 %26 %28 -%110 = OpLogicalAnd %8 %26 %28 -%111 = OpLogicalOr %8 %26 %28 -%112 = OpCompositeConstruct %96 %26 %26 %26 -%113 = OpCompositeConstruct %96 %28 %28 %28 -%114 = OpLogicalOr %96 %112 %113 -%115 = OpLogicalAnd %8 %26 %28 -%116 = OpCompositeConstruct %7 %26 %26 %26 %26 -%117 = OpCompositeConstruct %7 %28 %28 %28 %28 -%118 = OpLogicalAnd %7 %116 %117 +%106 = OpFunction %2 None %107 +%105 = OpLabel +OpBranch %108 +%108 = OpLabel +%109 = OpCompositeConstruct %11 %33 %33 +%110 = OpLogicalOr %8 %31 %33 +%111 = OpCompositeConstruct %100 %31 %31 %31 +%112 = OpCompositeConstruct %100 %33 %33 %33 +%113 = OpLogicalOr %100 %111 %112 +%114 = OpLogicalAnd %8 %31 %33 +%115 = OpCompositeConstruct %7 %31 %31 %31 %31 +%116 = OpCompositeConstruct %7 %33 %33 %33 %33 +%117 = OpLogicalAnd %7 %115 %116 OpReturn OpFunctionEnd -%120 = OpFunction %2 None %103 -%119 = OpLabel -OpBranch %128 -%128 = OpLabel -%130 = OpCompositeConstruct %129 %21 %21 -%131 = OpSNegate %129 %130 -%132 = OpCompositeConstruct %9 %15 %15 -%133 = OpFNegate %9 %132 -%134 = OpIAdd %6 %58 %21 -%135 = OpIAdd %122 %123 %124 -%136 = OpFAdd %4 %54 %15 -%137 = OpCompositeConstruct %129 %58 %58 -%138 = OpCompositeConstruct %129 %21 %21 -%139 = OpIAdd %129 %137 %138 -%141 = OpCompositeConstruct %140 %123 %123 %123 -%142 = OpCompositeConstruct %140 %124 %124 %124 -%143 = OpIAdd %140 %141 %142 -%144 = OpCompositeConstruct %3 %54 %54 %54 %54 -%145 = OpCompositeConstruct %3 %15 %15 %15 %15 -%146 = OpFAdd %3 %144 %145 -%147 = OpISub %6 %58 %21 -%148 = OpISub %122 %123 %124 -%149 = OpFSub %4 %54 %15 -%150 = OpCompositeConstruct %129 %58 %58 -%151 = OpCompositeConstruct %129 %21 %21 -%152 = OpISub %129 %150 %151 -%153 = OpCompositeConstruct %140 %123 %123 %123 -%154 = OpCompositeConstruct %140 %124 %124 %124 -%155 = OpISub %140 %153 %154 -%156 = OpCompositeConstruct %3 %54 %54 %54 %54 -%157 = OpCompositeConstruct %3 %15 %15 %15 %15 -%158 = OpFSub %3 %156 %157 -%159 = OpIMul %6 %58 %21 -%160 = OpIMul %122 %123 %124 -%161 = OpFMul %4 %54 %15 -%162 = OpCompositeConstruct %129 %58 %58 -%163 = OpCompositeConstruct %129 %21 %21 -%164 = OpIMul %129 %162 %163 -%165 = OpCompositeConstruct %140 %123 %123 %123 -%166 = OpCompositeConstruct %140 %124 %124 %124 -%167 = OpIMul %140 %165 %166 -%168 = OpCompositeConstruct %3 %54 %54 %54 %54 -%169 = OpCompositeConstruct %3 %15 %15 %15 %15 -%170 = OpFMul %3 %168 %169 -%171 = OpSDiv %6 %58 %21 -%172 = OpUDiv %122 %123 %124 -%173 = OpFDiv %4 %54 %15 -%174 = OpCompositeConstruct %129 %58 %58 -%175 = OpCompositeConstruct %129 %21 %21 -%176 = OpSDiv %129 %174 %175 -%177 = OpCompositeConstruct %140 %123 %123 %123 -%178 = OpCompositeConstruct %140 %124 %124 %124 -%179 = OpUDiv %140 %177 %178 -%180 = OpCompositeConstruct %3 %54 %54 %54 %54 -%181 = OpCompositeConstruct %3 %15 %15 %15 %15 -%182 = OpFDiv %3 %180 %181 -%183 = OpSRem %6 %58 %21 -%184 = OpUMod %122 %123 %124 -%185 = OpFRem %4 %54 %15 -%186 = OpCompositeConstruct %129 %58 %58 -%187 = OpCompositeConstruct %129 %21 %21 -%188 = OpSRem %129 %186 %187 -%189 = OpCompositeConstruct %140 %123 %123 %123 -%190 = OpCompositeConstruct %140 %124 %124 %124 -%191 = OpUMod %140 %189 %190 -%192 = OpCompositeConstruct %3 %54 %54 %54 %54 -%193 = OpCompositeConstruct %3 %15 %15 %15 %15 -%194 = OpFRem %3 %192 %193 -OpBranch %195 -%195 = OpLabel -%197 = OpCompositeConstruct %129 %58 %58 -%198 = OpCompositeConstruct %129 %21 %21 -%199 = OpIAdd %129 %197 %198 -%200 = OpCompositeConstruct %129 %21 %21 -%201 = OpCompositeConstruct %129 %58 %58 -%202 = OpIAdd %129 %201 %200 -%204 = OpCompositeConstruct %203 %123 %123 -%205 = OpCompositeConstruct %203 %124 %124 -%206 = OpIAdd %203 %204 %205 -%207 = OpCompositeConstruct %203 %124 %124 -%208 = OpCompositeConstruct %203 %123 %123 -%209 = OpIAdd %203 %208 %207 -%210 = OpCompositeConstruct %9 %54 %54 -%211 = OpCompositeConstruct %9 %15 %15 -%212 = OpFAdd %9 %210 %211 -%213 = OpCompositeConstruct %9 %15 %15 -%214 = OpCompositeConstruct %9 %54 %54 -%215 = OpFAdd %9 %214 %213 -%216 = OpCompositeConstruct %129 %58 %58 -%217 = OpCompositeConstruct %129 %21 %21 -%218 = OpISub %129 %216 %217 -%219 = OpCompositeConstruct %129 %21 %21 -%220 = OpCompositeConstruct %129 %58 %58 -%221 = OpISub %129 %220 %219 -%222 = OpCompositeConstruct %203 %123 %123 -%223 = OpCompositeConstruct %203 %124 %124 -%224 = OpISub %203 %222 %223 -%225 = OpCompositeConstruct %203 %124 %124 -%226 = OpCompositeConstruct %203 %123 %123 -%227 = OpISub %203 %226 %225 -%228 = OpCompositeConstruct %9 %54 %54 -%229 = OpCompositeConstruct %9 %15 %15 -%230 = OpFSub %9 %228 %229 -%231 = OpCompositeConstruct %9 %15 %15 -%232 = OpCompositeConstruct %9 %54 %54 -%233 = OpFSub %9 %232 %231 -%234 = OpCompositeConstruct %129 %58 %58 -%236 = OpCompositeConstruct %129 %21 %21 -%235 = OpIMul %129 %234 %236 -%237 = OpCompositeConstruct %129 %21 %21 -%239 = OpCompositeConstruct %129 %58 %58 -%238 = OpIMul %129 %237 %239 -%240 = OpCompositeConstruct %203 %123 %123 -%242 = OpCompositeConstruct %203 %124 %124 -%241 = OpIMul %203 %240 %242 -%243 = OpCompositeConstruct %203 %124 %124 -%245 = OpCompositeConstruct %203 %123 %123 -%244 = OpIMul %203 %243 %245 -%246 = OpCompositeConstruct %9 %54 %54 -%247 = OpVectorTimesScalar %9 %246 %15 -%248 = OpCompositeConstruct %9 %15 %15 -%249 = OpVectorTimesScalar %9 %248 %54 -%250 = OpCompositeConstruct %129 %58 %58 -%251 = OpCompositeConstruct %129 %21 %21 -%252 = OpSDiv %129 %250 %251 -%253 = OpCompositeConstruct %129 %21 %21 -%254 = OpCompositeConstruct %129 %58 %58 -%255 = OpSDiv %129 %254 %253 -%256 = OpCompositeConstruct %203 %123 %123 -%257 = OpCompositeConstruct %203 %124 %124 -%258 = OpUDiv %203 %256 %257 -%259 = OpCompositeConstruct %203 %124 %124 -%260 = OpCompositeConstruct %203 %123 %123 -%261 = OpUDiv %203 %260 %259 -%262 = OpCompositeConstruct %9 %54 %54 -%263 = OpCompositeConstruct %9 %15 %15 -%264 = OpFDiv %9 %262 %263 -%265 = OpCompositeConstruct %9 %15 %15 -%266 = OpCompositeConstruct %9 %54 %54 -%267 = OpFDiv %9 %266 %265 -%268 = OpCompositeConstruct %129 %58 %58 -%269 = OpCompositeConstruct %129 %21 %21 -%270 = OpSRem %129 %268 %269 -%271 = OpCompositeConstruct %129 %21 %21 -%272 = OpCompositeConstruct %129 %58 %58 -%273 = OpSRem %129 %272 %271 -%274 = OpCompositeConstruct %203 %123 %123 -%275 = OpCompositeConstruct %203 %124 %124 -%276 = OpUMod %203 %274 %275 -%277 = OpCompositeConstruct %203 %124 %124 -%278 = OpCompositeConstruct %203 %123 %123 -%279 = OpUMod %203 %278 %277 -%280 = OpCompositeConstruct %9 %54 %54 -%281 = OpCompositeConstruct %9 %15 %15 -%282 = OpFRem %9 %280 %281 -%283 = OpCompositeConstruct %9 %15 %15 -%284 = OpCompositeConstruct %9 %54 %54 -%285 = OpFRem %9 %284 %283 -OpBranch %196 -%196 = OpLabel -%287 = OpCompositeExtract %10 %125 0 -%288 = OpCompositeExtract %10 %125 0 -%289 = OpFAdd %10 %287 %288 -%290 = OpCompositeExtract %10 %125 1 -%291 = OpCompositeExtract %10 %125 1 -%292 = OpFAdd %10 %290 %291 -%293 = OpCompositeExtract %10 %125 2 -%294 = OpCompositeExtract %10 %125 2 -%295 = OpFAdd %10 %293 %294 -%286 = OpCompositeConstruct %11 %289 %292 %295 -%297 = OpCompositeExtract %10 %125 0 -%298 = OpCompositeExtract %10 %125 0 -%299 = OpFSub %10 %297 %298 -%300 = OpCompositeExtract %10 %125 1 -%301 = OpCompositeExtract %10 %125 1 -%302 = OpFSub %10 %300 %301 -%303 = OpCompositeExtract %10 %125 2 -%304 = OpCompositeExtract %10 %125 2 -%305 = OpFSub %10 %303 %304 -%296 = OpCompositeConstruct %11 %299 %302 %305 -%306 = OpMatrixTimesScalar %11 %125 %15 -%307 = OpMatrixTimesScalar %11 %125 %54 -%308 = OpCompositeConstruct %3 %15 %15 %15 %15 -%309 = OpMatrixTimesVector %10 %126 %308 -%310 = OpCompositeConstruct %10 %54 %54 %54 -%311 = OpVectorTimesMatrix %3 %310 %126 -%312 = OpMatrixTimesMatrix %11 %126 %127 +%119 = OpFunction %2 None %107 +%118 = OpLabel +OpBranch %130 +%130 = OpLabel +%131 = OpCompositeConstruct %12 %121 %121 +%132 = OpCompositeConstruct %9 %120 %120 +%133 = OpCompositeConstruct %12 %62 %62 +%134 = OpCompositeConstruct %12 %26 %26 +%135 = OpIAdd %12 %133 %134 +%136 = OpCompositeConstruct %13 %124 %124 %124 +%137 = OpCompositeConstruct %13 %125 %125 %125 +%138 = OpIAdd %13 %136 %137 +%139 = OpCompositeConstruct %3 %58 %58 %58 %58 +%140 = OpCompositeConstruct %3 %20 %20 %20 %20 +%141 = OpFAdd %3 %139 %140 +%142 = OpCompositeConstruct %12 %62 %62 +%143 = OpCompositeConstruct %12 %26 %26 +%144 = OpISub %12 %142 %143 +%145 = OpCompositeConstruct %13 %124 %124 %124 +%146 = OpCompositeConstruct %13 %125 %125 %125 +%147 = OpISub %13 %145 %146 +%148 = OpCompositeConstruct %3 %58 %58 %58 %58 +%149 = OpCompositeConstruct %3 %20 %20 %20 %20 +%150 = OpFSub %3 %148 %149 +%151 = OpCompositeConstruct %12 %62 %62 +%152 = OpCompositeConstruct %12 %26 %26 +%153 = OpIMul %12 %151 %152 +%154 = OpCompositeConstruct %13 %124 %124 %124 +%155 = OpCompositeConstruct %13 %125 %125 %125 +%156 = OpIMul %13 %154 %155 +%157 = OpCompositeConstruct %3 %58 %58 %58 %58 +%158 = OpCompositeConstruct %3 %20 %20 %20 %20 +%159 = OpFMul %3 %157 %158 +%160 = OpCompositeConstruct %12 %62 %62 +%161 = OpCompositeConstruct %12 %26 %26 +%162 = OpSDiv %12 %160 %161 +%163 = OpCompositeConstruct %13 %124 %124 %124 +%164 = OpCompositeConstruct %13 %125 %125 %125 +%165 = OpUDiv %13 %163 %164 +%166 = OpCompositeConstruct %3 %58 %58 %58 %58 +%167 = OpCompositeConstruct %3 %20 %20 %20 %20 +%168 = OpFDiv %3 %166 %167 +%169 = OpCompositeConstruct %12 %62 %62 +%170 = OpCompositeConstruct %12 %26 %26 +%171 = OpSRem %12 %169 %170 +%172 = OpCompositeConstruct %13 %124 %124 %124 +%173 = OpCompositeConstruct %13 %125 %125 %125 +%174 = OpUMod %13 %172 %173 +%175 = OpCompositeConstruct %3 %58 %58 %58 %58 +%176 = OpCompositeConstruct %3 %20 %20 %20 %20 +%177 = OpFRem %3 %175 %176 +OpBranch %178 +%178 = OpLabel +%180 = OpCompositeConstruct %12 %62 %62 +%181 = OpCompositeConstruct %12 %26 %26 +%182 = OpIAdd %12 %180 %181 +%183 = OpCompositeConstruct %12 %26 %26 +%184 = OpCompositeConstruct %12 %62 %62 +%185 = OpIAdd %12 %184 %183 +%186 = OpCompositeConstruct %15 %124 %124 +%187 = OpCompositeConstruct %15 %125 %125 +%188 = OpIAdd %15 %186 %187 +%189 = OpCompositeConstruct %15 %125 %125 +%190 = OpCompositeConstruct %15 %124 %124 +%191 = OpIAdd %15 %190 %189 +%192 = OpCompositeConstruct %9 %58 %58 +%193 = OpCompositeConstruct %9 %20 %20 +%194 = OpFAdd %9 %192 %193 +%195 = OpCompositeConstruct %9 %20 %20 +%196 = OpCompositeConstruct %9 %58 %58 +%197 = OpFAdd %9 %196 %195 +%198 = OpCompositeConstruct %12 %62 %62 +%199 = OpCompositeConstruct %12 %26 %26 +%200 = OpISub %12 %198 %199 +%201 = OpCompositeConstruct %12 %26 %26 +%202 = OpCompositeConstruct %12 %62 %62 +%203 = OpISub %12 %202 %201 +%204 = OpCompositeConstruct %15 %124 %124 +%205 = OpCompositeConstruct %15 %125 %125 +%206 = OpISub %15 %204 %205 +%207 = OpCompositeConstruct %15 %125 %125 +%208 = OpCompositeConstruct %15 %124 %124 +%209 = OpISub %15 %208 %207 +%210 = OpCompositeConstruct %9 %58 %58 +%211 = OpCompositeConstruct %9 %20 %20 +%212 = OpFSub %9 %210 %211 +%213 = OpCompositeConstruct %9 %20 %20 +%214 = OpCompositeConstruct %9 %58 %58 +%215 = OpFSub %9 %214 %213 +%216 = OpCompositeConstruct %12 %62 %62 +%217 = OpCompositeConstruct %12 %62 %62 +%218 = OpCompositeConstruct %15 %124 %124 +%219 = OpCompositeConstruct %15 %124 %124 +%220 = OpCompositeConstruct %9 %58 %58 +%221 = OpCompositeConstruct %9 %58 %58 +%222 = OpCompositeConstruct %12 %62 %62 +%223 = OpCompositeConstruct %12 %26 %26 +%224 = OpSDiv %12 %222 %223 +%225 = OpCompositeConstruct %12 %26 %26 +%226 = OpCompositeConstruct %12 %62 %62 +%227 = OpSDiv %12 %226 %225 +%228 = OpCompositeConstruct %15 %124 %124 +%229 = OpCompositeConstruct %15 %125 %125 +%230 = OpUDiv %15 %228 %229 +%231 = OpCompositeConstruct %15 %125 %125 +%232 = OpCompositeConstruct %15 %124 %124 +%233 = OpUDiv %15 %232 %231 +%234 = OpCompositeConstruct %9 %58 %58 +%235 = OpCompositeConstruct %9 %20 %20 +%236 = OpFDiv %9 %234 %235 +%237 = OpCompositeConstruct %9 %20 %20 +%238 = OpCompositeConstruct %9 %58 %58 +%239 = OpFDiv %9 %238 %237 +%240 = OpCompositeConstruct %12 %62 %62 +%241 = OpCompositeConstruct %12 %26 %26 +%242 = OpSRem %12 %240 %241 +%243 = OpCompositeConstruct %12 %26 %26 +%244 = OpCompositeConstruct %12 %62 %62 +%245 = OpSRem %12 %244 %243 +%246 = OpCompositeConstruct %15 %124 %124 +%247 = OpCompositeConstruct %15 %125 %125 +%248 = OpUMod %15 %246 %247 +%249 = OpCompositeConstruct %15 %125 %125 +%250 = OpCompositeConstruct %15 %124 %124 +%251 = OpUMod %15 %250 %249 +%252 = OpCompositeConstruct %9 %58 %58 +%253 = OpCompositeConstruct %9 %20 %20 +%254 = OpFRem %9 %252 %253 +%255 = OpCompositeConstruct %9 %20 %20 +%256 = OpCompositeConstruct %9 %58 %58 +%257 = OpFRem %9 %256 %255 +OpBranch %179 +%179 = OpLabel +%259 = OpCompositeExtract %10 %127 0 +%260 = OpCompositeExtract %10 %127 0 +%261 = OpFAdd %10 %259 %260 +%262 = OpCompositeExtract %10 %127 1 +%263 = OpCompositeExtract %10 %127 1 +%264 = OpFAdd %10 %262 %263 +%265 = OpCompositeExtract %10 %127 2 +%266 = OpCompositeExtract %10 %127 2 +%267 = OpFAdd %10 %265 %266 +%258 = OpCompositeConstruct %16 %261 %264 %267 +%269 = OpCompositeExtract %10 %127 0 +%270 = OpCompositeExtract %10 %127 0 +%271 = OpFSub %10 %269 %270 +%272 = OpCompositeExtract %10 %127 1 +%273 = OpCompositeExtract %10 %127 1 +%274 = OpFSub %10 %272 %273 +%275 = OpCompositeExtract %10 %127 2 +%276 = OpCompositeExtract %10 %127 2 +%277 = OpFSub %10 %275 %276 +%268 = OpCompositeConstruct %16 %271 %274 %277 +%278 = OpCompositeConstruct %10 %22 %22 %22 +%279 = OpCompositeConstruct %10 %22 %22 %22 +%280 = OpCompositeConstruct %10 %22 %22 %22 +%281 = OpCompositeConstruct %16 %278 %279 %280 +%282 = OpCompositeConstruct %10 %22 %22 %22 +%283 = OpCompositeConstruct %10 %22 %22 %22 +%284 = OpCompositeConstruct %10 %22 %22 %22 +%285 = OpCompositeConstruct %16 %282 %283 %284 +%286 = OpCompositeConstruct %3 %20 %20 %20 %20 +%287 = OpMatrixTimesVector %10 %128 %286 +%288 = OpCompositeConstruct %10 %58 %58 %58 +%289 = OpVectorTimesMatrix %3 %288 %128 +%290 = OpMatrixTimesMatrix %16 %128 %129 OpReturn OpFunctionEnd -%314 = OpFunction %2 None %103 -%313 = OpLabel -OpBranch %315 -%315 = OpLabel -%316 = OpNot %6 %21 -%317 = OpNot %122 %124 -%318 = OpCompositeConstruct %129 %21 %21 -%319 = OpNot %129 %318 -%320 = OpCompositeConstruct %140 %124 %124 %124 -%321 = OpNot %140 %320 -%322 = OpBitwiseOr %6 %58 %21 -%323 = OpBitwiseOr %122 %123 %124 -%324 = OpCompositeConstruct %129 %58 %58 -%325 = OpCompositeConstruct %129 %21 %21 -%326 = OpBitwiseOr %129 %324 %325 -%327 = OpCompositeConstruct %140 %123 %123 %123 -%328 = OpCompositeConstruct %140 %124 %124 %124 -%329 = OpBitwiseOr %140 %327 %328 -%330 = OpBitwiseAnd %6 %58 %21 -%331 = OpBitwiseAnd %122 %123 %124 -%332 = OpCompositeConstruct %129 %58 %58 -%333 = OpCompositeConstruct %129 %21 %21 -%334 = OpBitwiseAnd %129 %332 %333 -%335 = OpCompositeConstruct %140 %123 %123 %123 -%336 = OpCompositeConstruct %140 %124 %124 %124 -%337 = OpBitwiseAnd %140 %335 %336 -%338 = OpBitwiseXor %6 %58 %21 -%339 = OpBitwiseXor %122 %123 %124 -%340 = OpCompositeConstruct %129 %58 %58 -%341 = OpCompositeConstruct %129 %21 %21 -%342 = OpBitwiseXor %129 %340 %341 -%343 = OpCompositeConstruct %140 %123 %123 %123 -%344 = OpCompositeConstruct %140 %124 %124 %124 -%345 = OpBitwiseXor %140 %343 %344 -%346 = OpShiftLeftLogical %6 %58 %124 -%347 = OpShiftLeftLogical %122 %123 %124 -%348 = OpCompositeConstruct %129 %58 %58 -%349 = OpCompositeConstruct %203 %124 %124 -%350 = OpShiftLeftLogical %129 %348 %349 -%351 = OpCompositeConstruct %140 %123 %123 %123 -%352 = OpCompositeConstruct %140 %124 %124 %124 -%353 = OpShiftLeftLogical %140 %351 %352 -%354 = OpShiftRightArithmetic %6 %58 %124 -%355 = OpShiftRightLogical %122 %123 %124 -%356 = OpCompositeConstruct %129 %58 %58 -%357 = OpCompositeConstruct %203 %124 %124 -%358 = OpShiftRightArithmetic %129 %356 %357 -%359 = OpCompositeConstruct %140 %123 %123 %123 -%360 = OpCompositeConstruct %140 %124 %124 %124 -%361 = OpShiftRightLogical %140 %359 %360 +%292 = OpFunction %2 None %107 +%291 = OpLabel +OpBranch %297 +%297 = OpLabel +%298 = OpCompositeConstruct %12 %293 %293 +%299 = OpCompositeConstruct %13 %294 %294 %294 +%300 = OpCompositeConstruct %12 %62 %62 +%301 = OpCompositeConstruct %12 %26 %26 +%302 = OpBitwiseOr %12 %300 %301 +%303 = OpCompositeConstruct %13 %124 %124 %124 +%304 = OpCompositeConstruct %13 %125 %125 %125 +%305 = OpBitwiseOr %13 %303 %304 +%306 = OpCompositeConstruct %12 %62 %62 +%307 = OpCompositeConstruct %12 %26 %26 +%308 = OpBitwiseAnd %12 %306 %307 +%309 = OpCompositeConstruct %13 %124 %124 %124 +%310 = OpCompositeConstruct %13 %125 %125 %125 +%311 = OpBitwiseAnd %13 %309 %310 +%312 = OpCompositeConstruct %12 %62 %62 +%313 = OpCompositeConstruct %12 %26 %26 +%314 = OpBitwiseXor %12 %312 %313 +%315 = OpCompositeConstruct %13 %124 %124 %124 +%316 = OpCompositeConstruct %13 %125 %125 %125 +%317 = OpBitwiseXor %13 %315 %316 +%318 = OpCompositeConstruct %12 %62 %62 +%319 = OpCompositeConstruct %15 %125 %125 +%320 = OpShiftLeftLogical %12 %318 %319 +%321 = OpCompositeConstruct %13 %124 %124 %124 +%322 = OpCompositeConstruct %13 %125 %125 %125 +%323 = OpShiftLeftLogical %13 %321 %322 +%324 = OpCompositeConstruct %12 %62 %62 +%325 = OpCompositeConstruct %15 %125 %125 +%326 = OpShiftRightArithmetic %12 %324 %325 +%327 = OpCompositeConstruct %13 %124 %124 %124 +%328 = OpCompositeConstruct %13 %125 %125 %125 +%329 = OpShiftRightLogical %13 %327 %328 OpReturn OpFunctionEnd -%363 = OpFunction %2 None %103 -%362 = OpLabel -OpBranch %364 -%364 = OpLabel -%365 = OpIEqual %8 %58 %21 -%366 = OpIEqual %8 %123 %124 -%367 = OpFOrdEqual %8 %54 %15 -%368 = OpCompositeConstruct %129 %58 %58 -%369 = OpCompositeConstruct %129 %21 %21 -%370 = OpIEqual %106 %368 %369 -%371 = OpCompositeConstruct %140 %123 %123 %123 -%372 = OpCompositeConstruct %140 %124 %124 %124 -%373 = OpIEqual %96 %371 %372 -%374 = OpCompositeConstruct %3 %54 %54 %54 %54 -%375 = OpCompositeConstruct %3 %15 %15 %15 %15 -%376 = OpFOrdEqual %7 %374 %375 -%377 = OpINotEqual %8 %58 %21 -%378 = OpINotEqual %8 %123 %124 -%379 = OpFOrdNotEqual %8 %54 %15 -%380 = OpCompositeConstruct %129 %58 %58 -%381 = OpCompositeConstruct %129 %21 %21 -%382 = OpINotEqual %106 %380 %381 -%383 = OpCompositeConstruct %140 %123 %123 %123 -%384 = OpCompositeConstruct %140 %124 %124 %124 -%385 = OpINotEqual %96 %383 %384 -%386 = OpCompositeConstruct %3 %54 %54 %54 %54 -%387 = OpCompositeConstruct %3 %15 %15 %15 %15 -%388 = OpFOrdNotEqual %7 %386 %387 -%389 = OpSLessThan %8 %58 %21 -%390 = OpULessThan %8 %123 %124 -%391 = OpFOrdLessThan %8 %54 %15 -%392 = OpCompositeConstruct %129 %58 %58 -%393 = OpCompositeConstruct %129 %21 %21 -%394 = OpSLessThan %106 %392 %393 -%395 = OpCompositeConstruct %140 %123 %123 %123 -%396 = OpCompositeConstruct %140 %124 %124 %124 -%397 = OpULessThan %96 %395 %396 -%398 = OpCompositeConstruct %3 %54 %54 %54 %54 -%399 = OpCompositeConstruct %3 %15 %15 %15 %15 -%400 = OpFOrdLessThan %7 %398 %399 -%401 = OpSLessThanEqual %8 %58 %21 -%402 = OpULessThanEqual %8 %123 %124 -%403 = OpFOrdLessThanEqual %8 %54 %15 -%404 = OpCompositeConstruct %129 %58 %58 -%405 = OpCompositeConstruct %129 %21 %21 -%406 = OpSLessThanEqual %106 %404 %405 -%407 = OpCompositeConstruct %140 %123 %123 %123 -%408 = OpCompositeConstruct %140 %124 %124 %124 -%409 = OpULessThanEqual %96 %407 %408 -%410 = OpCompositeConstruct %3 %54 %54 %54 %54 -%411 = OpCompositeConstruct %3 %15 %15 %15 %15 -%412 = OpFOrdLessThanEqual %7 %410 %411 -%413 = OpSGreaterThan %8 %58 %21 -%414 = OpUGreaterThan %8 %123 %124 -%415 = OpFOrdGreaterThan %8 %54 %15 -%416 = OpCompositeConstruct %129 %58 %58 -%417 = OpCompositeConstruct %129 %21 %21 -%418 = OpSGreaterThan %106 %416 %417 -%419 = OpCompositeConstruct %140 %123 %123 %123 -%420 = OpCompositeConstruct %140 %124 %124 %124 -%421 = OpUGreaterThan %96 %419 %420 -%422 = OpCompositeConstruct %3 %54 %54 %54 %54 -%423 = OpCompositeConstruct %3 %15 %15 %15 %15 -%424 = OpFOrdGreaterThan %7 %422 %423 -%425 = OpSGreaterThanEqual %8 %58 %21 -%426 = OpUGreaterThanEqual %8 %123 %124 -%427 = OpFOrdGreaterThanEqual %8 %54 %15 -%428 = OpCompositeConstruct %129 %58 %58 -%429 = OpCompositeConstruct %129 %21 %21 -%430 = OpSGreaterThanEqual %106 %428 %429 -%431 = OpCompositeConstruct %140 %123 %123 %123 -%432 = OpCompositeConstruct %140 %124 %124 %124 -%433 = OpUGreaterThanEqual %96 %431 %432 -%434 = OpCompositeConstruct %3 %54 %54 %54 %54 -%435 = OpCompositeConstruct %3 %15 %15 %15 %15 -%436 = OpFOrdGreaterThanEqual %7 %434 %435 +%331 = OpFunction %2 None %107 +%330 = OpLabel +OpBranch %332 +%332 = OpLabel +%333 = OpCompositeConstruct %12 %62 %62 +%334 = OpCompositeConstruct %12 %26 %26 +%335 = OpIEqual %11 %333 %334 +%336 = OpCompositeConstruct %13 %124 %124 %124 +%337 = OpCompositeConstruct %13 %125 %125 %125 +%338 = OpIEqual %100 %336 %337 +%339 = OpCompositeConstruct %3 %58 %58 %58 %58 +%340 = OpCompositeConstruct %3 %20 %20 %20 %20 +%341 = OpFOrdEqual %7 %339 %340 +%342 = OpCompositeConstruct %12 %62 %62 +%343 = OpCompositeConstruct %12 %26 %26 +%344 = OpINotEqual %11 %342 %343 +%345 = OpCompositeConstruct %13 %124 %124 %124 +%346 = OpCompositeConstruct %13 %125 %125 %125 +%347 = OpINotEqual %100 %345 %346 +%348 = OpCompositeConstruct %3 %58 %58 %58 %58 +%349 = OpCompositeConstruct %3 %20 %20 %20 %20 +%350 = OpFOrdNotEqual %7 %348 %349 +%351 = OpCompositeConstruct %12 %62 %62 +%352 = OpCompositeConstruct %12 %26 %26 +%353 = OpSLessThan %11 %351 %352 +%354 = OpCompositeConstruct %13 %124 %124 %124 +%355 = OpCompositeConstruct %13 %125 %125 %125 +%356 = OpULessThan %100 %354 %355 +%357 = OpCompositeConstruct %3 %58 %58 %58 %58 +%358 = OpCompositeConstruct %3 %20 %20 %20 %20 +%359 = OpFOrdLessThan %7 %357 %358 +%360 = OpCompositeConstruct %12 %62 %62 +%361 = OpCompositeConstruct %12 %26 %26 +%362 = OpSLessThanEqual %11 %360 %361 +%363 = OpCompositeConstruct %13 %124 %124 %124 +%364 = OpCompositeConstruct %13 %125 %125 %125 +%365 = OpULessThanEqual %100 %363 %364 +%366 = OpCompositeConstruct %3 %58 %58 %58 %58 +%367 = OpCompositeConstruct %3 %20 %20 %20 %20 +%368 = OpFOrdLessThanEqual %7 %366 %367 +%369 = OpCompositeConstruct %12 %62 %62 +%370 = OpCompositeConstruct %12 %26 %26 +%371 = OpSGreaterThan %11 %369 %370 +%372 = OpCompositeConstruct %13 %124 %124 %124 +%373 = OpCompositeConstruct %13 %125 %125 %125 +%374 = OpUGreaterThan %100 %372 %373 +%375 = OpCompositeConstruct %3 %58 %58 %58 %58 +%376 = OpCompositeConstruct %3 %20 %20 %20 %20 +%377 = OpFOrdGreaterThan %7 %375 %376 +%378 = OpCompositeConstruct %12 %62 %62 +%379 = OpCompositeConstruct %12 %26 %26 +%380 = OpSGreaterThanEqual %11 %378 %379 +%381 = OpCompositeConstruct %13 %124 %124 %124 +%382 = OpCompositeConstruct %13 %125 %125 %125 +%383 = OpUGreaterThanEqual %100 %381 %382 +%384 = OpCompositeConstruct %3 %58 %58 %58 %58 +%385 = OpCompositeConstruct %3 %20 %20 %20 %20 +%386 = OpFOrdGreaterThanEqual %7 %384 %385 OpReturn OpFunctionEnd -%444 = OpFunction %2 None %103 -%443 = OpLabel -%437 = OpVariable %438 Function %439 -%440 = OpVariable %441 Function %442 -OpBranch %445 -%445 = OpLabel -OpStore %437 %21 -%446 = OpLoad %6 %437 -%447 = OpIAdd %6 %446 %21 -OpStore %437 %447 -%448 = OpLoad %6 %437 -%449 = OpISub %6 %448 %21 -OpStore %437 %449 -%450 = OpLoad %6 %437 -%451 = OpLoad %6 %437 -%452 = OpIMul %6 %451 %450 -OpStore %437 %452 -%453 = OpLoad %6 %437 -%454 = OpLoad %6 %437 -%455 = OpSDiv %6 %454 %453 -OpStore %437 %455 -%456 = OpLoad %6 %437 -%457 = OpSRem %6 %456 %21 -OpStore %437 %457 -%458 = OpLoad %6 %437 -%459 = OpBitwiseAnd %6 %458 %27 -OpStore %437 %459 -%460 = OpLoad %6 %437 -%461 = OpBitwiseOr %6 %460 %27 -OpStore %437 %461 -%462 = OpLoad %6 %437 -%463 = OpBitwiseXor %6 %462 %27 -OpStore %437 %463 -%464 = OpLoad %6 %437 -%465 = OpShiftLeftLogical %6 %464 %123 -OpStore %437 %465 -%466 = OpLoad %6 %437 -%467 = OpShiftRightArithmetic %6 %466 %124 -OpStore %437 %467 -%468 = OpLoad %6 %437 -%469 = OpIAdd %6 %468 %21 -OpStore %437 %469 -%470 = OpLoad %6 %437 -%471 = OpISub %6 %470 %21 -OpStore %437 %471 -OpStore %440 %442 -%473 = OpAccessChain %472 %440 %124 -%474 = OpLoad %6 %473 -%475 = OpIAdd %6 %474 %21 -%476 = OpAccessChain %472 %440 %124 -OpStore %476 %475 -%477 = OpAccessChain %472 %440 %124 -%478 = OpLoad %6 %477 -%479 = OpISub %6 %478 %21 -%480 = OpAccessChain %472 %440 %124 -OpStore %480 %479 +%394 = OpFunction %2 None %107 +%393 = OpLabel +%387 = OpVariable %388 Function %389 +%390 = OpVariable %391 Function %392 +OpBranch %395 +%395 = OpLabel +OpStore %387 %26 +%396 = OpLoad %6 %387 +%397 = OpIAdd %6 %396 %26 +OpStore %387 %397 +%398 = OpLoad %6 %387 +%399 = OpISub %6 %398 %26 +OpStore %387 %399 +%400 = OpLoad %6 %387 +%401 = OpLoad %6 %387 +%402 = OpIMul %6 %401 %400 +OpStore %387 %402 +%403 = OpLoad %6 %387 +%404 = OpLoad %6 %387 +%405 = OpSDiv %6 %404 %403 +OpStore %387 %405 +%406 = OpLoad %6 %387 +%407 = OpSRem %6 %406 %26 +OpStore %387 %407 +%408 = OpLoad %6 %387 +%409 = OpBitwiseAnd %6 %408 %32 +OpStore %387 %409 +%410 = OpLoad %6 %387 +%411 = OpBitwiseOr %6 %410 %32 +OpStore %387 %411 +%412 = OpLoad %6 %387 +%413 = OpBitwiseXor %6 %412 %32 +OpStore %387 %413 +%414 = OpLoad %6 %387 +%415 = OpShiftLeftLogical %6 %414 %124 +OpStore %387 %415 +%416 = OpLoad %6 %387 +%417 = OpShiftRightArithmetic %6 %416 %125 +OpStore %387 %417 +%418 = OpLoad %6 %387 +%419 = OpIAdd %6 %418 %26 +OpStore %387 %419 +%420 = OpLoad %6 %387 +%421 = OpISub %6 %420 %26 +OpStore %387 %421 +OpStore %390 %392 +%423 = OpAccessChain %422 %390 %125 +%424 = OpLoad %6 %423 +%425 = OpIAdd %6 %424 %26 +%426 = OpAccessChain %422 %390 %125 +OpStore %426 %425 +%427 = OpAccessChain %422 %390 %125 +%428 = OpLoad %6 %427 +%429 = OpISub %6 %428 %26 +%430 = OpAccessChain %422 %390 %125 +OpStore %430 %429 OpReturn OpFunctionEnd -%482 = OpFunction %2 None %103 -%481 = OpLabel -OpBranch %491 -%491 = OpLabel -%492 = OpSNegate %6 %484 -%493 = OpSNegate %6 %485 -%494 = OpSNegate %6 %486 -%495 = OpSNegate %6 %494 -%496 = OpSNegate %6 %487 -%497 = OpSNegate %6 %496 -%498 = OpSNegate %6 %488 -%499 = OpSNegate %6 %498 -%500 = OpSNegate %6 %499 -%501 = OpSNegate %6 %500 -%502 = OpSNegate %6 %489 -%503 = OpSNegate %6 %502 -%504 = OpSNegate %6 %503 -%505 = OpSNegate %6 %504 -%506 = OpSNegate %6 %490 -%507 = OpSNegate %6 %506 -%508 = OpSNegate %6 %507 -%509 = OpSNegate %6 %508 +%432 = OpFunction %2 None %107 +%431 = OpLabel +OpBranch %437 +%437 = OpLabel OpReturn OpFunctionEnd -%511 = OpFunction %2 None %103 -%510 = OpLabel -OpBranch %512 -%512 = OpLabel -%513 = OpFunctionCall %3 %24 -%514 = OpFunctionCall %3 %53 -%515 = OpVectorShuffle %10 %16 %16 0 1 2 -%516 = OpFunctionCall %10 %93 %515 -%517 = OpFunctionCall %2 %102 -%518 = OpFunctionCall %2 %120 -%519 = OpFunctionCall %2 %314 -%520 = OpFunctionCall %2 %363 -%521 = OpFunctionCall %2 %444 +%439 = OpFunction %2 None %107 +%438 = OpLabel +OpBranch %440 +%440 = OpLabel +%441 = OpFunctionCall %3 %29 +%442 = OpFunctionCall %3 %57 +%443 = OpCompositeConstruct %10 %20 %20 %20 +%444 = OpFunctionCall %10 %97 %443 +%445 = OpFunctionCall %2 %106 +%446 = OpFunctionCall %2 %119 +%447 = OpFunctionCall %2 %292 +%448 = OpFunctionCall %2 %331 +%449 = OpFunctionCall %2 %394 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/constructors.wgsl b/tests/out/wgsl/constructors.wgsl index 6ed0e5090..f15bcb6c8 100644 --- a/tests/out/wgsl/constructors.wgsl +++ b/tests/out/wgsl/constructors.wgsl @@ -27,11 +27,8 @@ fn main() { let cit1_ = mat2x2(vec2(0.0), vec2(0.0)); let cit2_ = array(0, 1, 2, 3); let ic0_ = bool(bool()); - let ic1_ = i32(i32()); - let ic2_ = u32(u32()); - let ic3_ = f32(f32()); - let ic4_ = vec2(vec2()); - let ic5_ = mat2x3(mat2x3()); + let ic4_ = vec2(0u, 0u); + let ic5_ = mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); let ic6_ = bitcast>(vec2()); let ic7_ = mat2x3(mat2x3()); } diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 062d37713..6dfa0dbac 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -112,74 +112,74 @@ fn texture_sample() -> @location(0) vec4 { let tc = vec2(0.5); let tc3_ = vec3(0.5); - let _e9 = textureSample(image_1d, sampler_reg, tc.x); - let _e10 = a; - a = (_e10 + _e9); - let _e14 = textureSample(image_2d, sampler_reg, tc); - let _e15 = a; - a = (_e15 + _e14); - let _e19 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); - let _e20 = a; - a = (_e20 + _e19); - let _e24 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3); - let _e25 = a; - a = (_e25 + _e24); - let _e29 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3, vec2(3, 1)); - let _e30 = a; - a = (_e30 + _e29); - let _e35 = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); - let _e36 = a; - a = (_e36 + _e35); - let _e41 = textureSample(image_2d_array, sampler_reg, tc, 0u); - let _e42 = a; - a = (_e42 + _e41); - let _e47 = textureSample(image_2d_array, sampler_reg, tc, 0u, vec2(3, 1)); - let _e48 = a; - a = (_e48 + _e47); - let _e53 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3); - let _e54 = a; - a = (_e54 + _e53); - let _e59 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3, vec2(3, 1)); - let _e60 = a; - a = (_e60 + _e59); - let _e66 = textureSampleBias(image_2d_array, sampler_reg, tc, 0u, 2.0, vec2(3, 1)); - let _e67 = a; - a = (_e67 + _e66); - let _e72 = textureSample(image_2d_array, sampler_reg, tc, 0); - let _e73 = a; - a = (_e73 + _e72); - let _e78 = textureSample(image_2d_array, sampler_reg, tc, 0, vec2(3, 1)); - let _e79 = a; - a = (_e79 + _e78); - let _e84 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3); - let _e85 = a; - a = (_e85 + _e84); - let _e90 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3, vec2(3, 1)); - let _e91 = a; - a = (_e91 + _e90); - let _e97 = textureSampleBias(image_2d_array, sampler_reg, tc, 0, 2.0, vec2(3, 1)); - let _e98 = a; - a = (_e98 + _e97); - let _e103 = textureSample(image_cube_array, sampler_reg, tc3_, 0u); - let _e104 = a; - a = (_e104 + _e103); - let _e109 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0u, 2.3); - let _e110 = a; - a = (_e110 + _e109); - let _e116 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0u, 2.0); - let _e117 = a; - a = (_e117 + _e116); - let _e122 = textureSample(image_cube_array, sampler_reg, tc3_, 0); - let _e123 = a; - a = (_e123 + _e122); - let _e128 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0, 2.3); - let _e129 = a; - a = (_e129 + _e128); - let _e135 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0, 2.0); - let _e136 = a; - a = (_e136 + _e135); - let _e138 = a; - return _e138; + let _e8 = textureSample(image_1d, sampler_reg, 0.5); + let _e9 = a; + a = (_e9 + _e8); + let _e13 = textureSample(image_2d, sampler_reg, tc); + let _e14 = a; + a = (_e14 + _e13); + let _e18 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); + let _e19 = a; + a = (_e19 + _e18); + let _e23 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3); + let _e24 = a; + a = (_e24 + _e23); + let _e28 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3, vec2(3, 1)); + let _e29 = a; + a = (_e29 + _e28); + let _e34 = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); + let _e35 = a; + a = (_e35 + _e34); + let _e40 = textureSample(image_2d_array, sampler_reg, tc, 0u); + let _e41 = a; + a = (_e41 + _e40); + let _e46 = textureSample(image_2d_array, sampler_reg, tc, 0u, vec2(3, 1)); + let _e47 = a; + a = (_e47 + _e46); + let _e52 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3); + let _e53 = a; + a = (_e53 + _e52); + let _e58 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3, vec2(3, 1)); + let _e59 = a; + a = (_e59 + _e58); + let _e65 = textureSampleBias(image_2d_array, sampler_reg, tc, 0u, 2.0, vec2(3, 1)); + let _e66 = a; + a = (_e66 + _e65); + let _e71 = textureSample(image_2d_array, sampler_reg, tc, 0); + let _e72 = a; + a = (_e72 + _e71); + let _e77 = textureSample(image_2d_array, sampler_reg, tc, 0, vec2(3, 1)); + let _e78 = a; + a = (_e78 + _e77); + let _e83 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3); + let _e84 = a; + a = (_e84 + _e83); + let _e89 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3, vec2(3, 1)); + let _e90 = a; + a = (_e90 + _e89); + let _e96 = textureSampleBias(image_2d_array, sampler_reg, tc, 0, 2.0, vec2(3, 1)); + let _e97 = a; + a = (_e97 + _e96); + let _e102 = textureSample(image_cube_array, sampler_reg, tc3_, 0u); + let _e103 = a; + a = (_e103 + _e102); + let _e108 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0u, 2.3); + let _e109 = a; + a = (_e109 + _e108); + let _e115 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0u, 2.0); + let _e116 = a; + a = (_e116 + _e115); + let _e121 = textureSample(image_cube_array, sampler_reg, tc3_, 0); + let _e122 = a; + a = (_e122 + _e121); + let _e127 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0, 2.3); + let _e128 = a; + a = (_e128 + _e127); + let _e134 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0, 2.0); + let _e135 = a; + a = (_e135 + _e134); + let _e137 = a; + return _e137; } @fragment diff --git a/tests/out/wgsl/module-scope.wgsl b/tests/out/wgsl/module-scope.wgsl index 3276a0a10..c30052dd1 100644 --- a/tests/out/wgsl/module-scope.wgsl +++ b/tests/out/wgsl/module-scope.wgsl @@ -20,7 +20,6 @@ fn returns() -> S { fn call() { statement(); let _e0 = returns(); - let vf = f32(Value); - let s = textureSample(Texture, Sampler, vec2(vf)); + let s = textureSample(Texture, Sampler, vec2(1.0)); } diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index f444c6db0..caedce204 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -9,9 +9,9 @@ fn builtins() -> vec4 { let s3_ = select(v_f32_one, v_f32_zero, vec4(false, false, false, false)); let m1_ = mix(v_f32_zero, v_f32_one, v_f32_half); let m2_ = mix(v_f32_zero, v_f32_one, 0.1); - let b1_ = bitcast(v_i32_one.x); + let b1_ = bitcast(1); let b2_ = bitcast>(v_i32_one); - let v_i32_zero = vec4(v_f32_zero); + let v_i32_zero = vec4(0, 0, 0, 0); return (((((vec4((vec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_); } @@ -41,10 +41,7 @@ fn bool_cast(x: vec3) -> vec3 { } fn logical() { - let neg0_ = !(true); - let neg1_ = !(vec2(true)); - let or = (true || false); - let and = (true && false); + let neg1_ = vec2(false, false); let bitwise_or0_ = (true | false); let bitwise_or1_ = (vec3(true) | vec3(false)); let bitwise_and0_ = (true & false); @@ -52,140 +49,95 @@ fn logical() { } fn arithmetic() { - let neg1_1 = -(vec2(1)); - let neg2_ = -(vec2(1.0)); - let add0_ = (2 + 1); - let add1_ = (2u + 1u); - let add2_ = (2.0 + 1.0); + let neg1_1 = vec2(-1, -1); + let neg2_ = vec2(-1.0, -1.0); let add3_ = (vec2(2) + vec2(1)); let add4_ = (vec3(2u) + vec3(1u)); let add5_ = (vec4(2.0) + vec4(1.0)); - let sub0_ = (2 - 1); - let sub1_ = (2u - 1u); - let sub2_ = (2.0 - 1.0); let sub3_ = (vec2(2) - vec2(1)); let sub4_ = (vec3(2u) - vec3(1u)); let sub5_ = (vec4(2.0) - vec4(1.0)); - let mul0_ = (2 * 1); - let mul1_ = (2u * 1u); - let mul2_ = (2.0 * 1.0); let mul3_ = (vec2(2) * vec2(1)); let mul4_ = (vec3(2u) * vec3(1u)); let mul5_ = (vec4(2.0) * vec4(1.0)); - let div0_ = (2 / 1); - let div1_ = (2u / 1u); - let div2_ = (2.0 / 1.0); let div3_ = (vec2(2) / vec2(1)); let div4_ = (vec3(2u) / vec3(1u)); let div5_ = (vec4(2.0) / vec4(1.0)); - let rem0_ = (2 % 1); - let rem1_ = (2u % 1u); - let rem2_ = (2.0 % 1.0); let rem3_ = (vec2(2) % vec2(1)); let rem4_ = (vec3(2u) % vec3(1u)); let rem5_ = (vec4(2.0) % vec4(1.0)); { - let add0_1 = (vec2(2) + vec2(1)); - let add1_1 = (vec2(2) + vec2(1)); - let add2_1 = (vec2(2u) + vec2(1u)); + let add0_ = (vec2(2) + vec2(1)); + let add1_ = (vec2(2) + vec2(1)); + let add2_ = (vec2(2u) + vec2(1u)); let add3_1 = (vec2(2u) + vec2(1u)); let add4_1 = (vec2(2.0) + vec2(1.0)); let add5_1 = (vec2(2.0) + vec2(1.0)); - let sub0_1 = (vec2(2) - vec2(1)); - let sub1_1 = (vec2(2) - vec2(1)); - let sub2_1 = (vec2(2u) - vec2(1u)); + let sub0_ = (vec2(2) - vec2(1)); + let sub1_ = (vec2(2) - vec2(1)); + let sub2_ = (vec2(2u) - vec2(1u)); let sub3_1 = (vec2(2u) - vec2(1u)); let sub4_1 = (vec2(2.0) - vec2(1.0)); let sub5_1 = (vec2(2.0) - vec2(1.0)); - let mul0_1 = (vec2(2) * 1); - let mul1_1 = (2 * vec2(1)); - let mul2_1 = (vec2(2u) * 1u); - let mul3_1 = (2u * vec2(1u)); - let mul4_1 = (vec2(2.0) * 1.0); - let mul5_1 = (2.0 * vec2(1.0)); - let div0_1 = (vec2(2) / vec2(1)); - let div1_1 = (vec2(2) / vec2(1)); - let div2_1 = (vec2(2u) / vec2(1u)); + let mul0_ = vec2(2, 2); + let mul1_ = vec2(2, 2); + let mul2_ = vec2(2u, 2u); + let mul3_1 = vec2(2u, 2u); + let mul4_1 = vec2(2.0, 2.0); + let mul5_1 = vec2(2.0, 2.0); + let div0_ = (vec2(2) / vec2(1)); + let div1_ = (vec2(2) / vec2(1)); + let div2_ = (vec2(2u) / vec2(1u)); let div3_1 = (vec2(2u) / vec2(1u)); let div4_1 = (vec2(2.0) / vec2(1.0)); let div5_1 = (vec2(2.0) / vec2(1.0)); - let rem0_1 = (vec2(2) % vec2(1)); - let rem1_1 = (vec2(2) % vec2(1)); - let rem2_1 = (vec2(2u) % vec2(1u)); + let rem0_ = (vec2(2) % vec2(1)); + let rem1_ = (vec2(2) % vec2(1)); + let rem2_ = (vec2(2u) % vec2(1u)); let rem3_1 = (vec2(2u) % vec2(1u)); let rem4_1 = (vec2(2.0) % vec2(1.0)); let rem5_1 = (vec2(2.0) % vec2(1.0)); } let add = (mat3x3() + mat3x3()); let sub = (mat3x3() - mat3x3()); - let mul_scalar0_ = (mat3x3() * 1.0); - let mul_scalar1_ = (2.0 * mat3x3()); + let mul_scalar0_ = mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); + let mul_scalar1_ = mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); let mul_vector0_ = (mat4x3() * vec4(1.0)); let mul_vector1_ = (vec3(2.0) * mat4x3()); let mul = (mat4x3() * mat3x4()); } fn bit() { - let flip0_ = ~(1); - let flip1_ = ~(1u); - let flip2_ = !(vec2(1)); - let flip3_ = !(vec3(1u)); - let or0_ = (2 | 1); - let or1_ = (2u | 1u); + let flip2_ = vec2(-2, -2); + let flip3_ = vec3(4294967294u, 4294967294u, 4294967294u); let or2_ = (vec2(2) | vec2(1)); let or3_ = (vec3(2u) | vec3(1u)); - let and0_ = (2 & 1); - let and1_ = (2u & 1u); let and2_ = (vec2(2) & vec2(1)); let and3_ = (vec3(2u) & vec3(1u)); - let xor0_ = (2 ^ 1); - let xor1_ = (2u ^ 1u); let xor2_ = (vec2(2) ^ vec2(1)); let xor3_ = (vec3(2u) ^ vec3(1u)); - let shl0_ = (2 << 1u); - let shl1_ = (2u << 1u); let shl2_ = (vec2(2) << vec2(1u)); let shl3_ = (vec3(2u) << vec3(1u)); - let shr0_ = (2 >> 1u); - let shr1_ = (2u >> 1u); let shr2_ = (vec2(2) >> vec2(1u)); let shr3_ = (vec3(2u) >> vec3(1u)); } fn comparison() { - let eq0_ = (2 == 1); - let eq1_ = (2u == 1u); - let eq2_ = (2.0 == 1.0); let eq3_ = (vec2(2) == vec2(1)); let eq4_ = (vec3(2u) == vec3(1u)); let eq5_ = (vec4(2.0) == vec4(1.0)); - let neq0_ = (2 != 1); - let neq1_ = (2u != 1u); - let neq2_ = (2.0 != 1.0); let neq3_ = (vec2(2) != vec2(1)); let neq4_ = (vec3(2u) != vec3(1u)); let neq5_ = (vec4(2.0) != vec4(1.0)); - let lt0_ = (2 < 1); - let lt1_ = (2u < 1u); - let lt2_ = (2.0 < 1.0); let lt3_ = (vec2(2) < vec2(1)); let lt4_ = (vec3(2u) < vec3(1u)); let lt5_ = (vec4(2.0) < vec4(1.0)); - let lte0_ = (2 <= 1); - let lte1_ = (2u <= 1u); - let lte2_ = (2.0 <= 1.0); let lte3_ = (vec2(2) <= vec2(1)); let lte4_ = (vec3(2u) <= vec3(1u)); let lte5_ = (vec4(2.0) <= vec4(1.0)); - let gt0_ = (2 > 1); - let gt1_ = (2u > 1u); - let gt2_ = (2.0 > 1.0); let gt3_ = (vec2(2) > vec2(1)); let gt4_ = (vec3(2u) > vec3(1u)); let gt5_ = (vec4(2.0) > vec4(1.0)); - let gte0_ = (2 >= 1); - let gte1_ = (2u >= 1u); - let gte2_ = (2.0 >= 1.0); let gte3_ = (vec2(2) >= vec2(1)); let gte4_ = (vec3(2u) >= vec3(1u)); let gte5_ = (vec4(2.0) >= vec4(1.0)); @@ -231,20 +183,14 @@ fn assignment() { } fn negation_avoids_prefix_decrement() { - let p1_ = -(-2); - let p2_ = -(-3); - let p3_ = -(-(4)); - let p4_ = -(-(-5)); - let p5_ = -(-(-(-(6)))); - let p6_ = -(-(-(-(-7)))); - let p7_ = -(-(-(-(-8)))); + return; } @compute @workgroup_size(1, 1, 1) fn main() { let _e0 = builtins(); let _e1 = splat(); - let _e4 = bool_cast(v_f32_one.xyz); + let _e6 = bool_cast(vec3(1.0, 1.0, 1.0)); logical(); arithmetic(); bit(); diff --git a/tests/out/wgsl/type-alias.wgsl b/tests/out/wgsl/type-alias.wgsl index fea2dec10..a4a9438eb 100644 --- a/tests/out/wgsl/type-alias.wgsl +++ b/tests/out/wgsl/type-alias.wgsl @@ -3,7 +3,7 @@ fn main() { let c = vec3(0.0); let b = vec3(vec2(0.0), 0.0); let d = vec3(vec2(0.0), 0.0); - let e = vec3(d); + let e = vec3(vec2(0, 0), 0); let f = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); let g = mat3x3(a, a, a); } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index cbab66026..637b5372f 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -107,24 +107,24 @@ fn unknown_identifier() { ); } -#[test] -fn negative_index() { - check( - r#" - fn main() -> f32 { - let a = array(0., 1., 2.); - return a[-1]; - } - "#, - r#"error: expected unsigned integer constant expression, found `-1` - ┌─ wgsl:4:26 - │ -4 │ return a[-1]; - │ ^^ expected unsigned integer +// #[test] +// fn negative_index() { +// check( +// r#" +// fn main() -> f32 { +// let a = array(0., 1., 2.); +// return a[-1]; +// } +// "#, +// r#"error: expected unsigned integer constant expression, found `-1` +// ┌─ wgsl:4:26 +// │ +// 4 │ return a[-1]; +// │ ^^ expected unsigned integer -"#, - ); -} +// "#, +// ); +// } #[test] fn bad_texture() { @@ -923,11 +923,11 @@ fn invalid_arrays() { check( "alias Bad = array;", - r###"error: array element count must resolve to an integer scalar (u32 or i32) + r###"error: must be a const-expression that resolves to a concrete integer scalar (u32 or i32) ┌─ wgsl:1:24 │ 1 │ alias Bad = array; - │ ^^^^ must resolve to u32/i32 + │ ^^^^ must resolve to u32 or i32 "###, ); @@ -937,33 +937,33 @@ fn invalid_arrays() { const length: f32 = 2.718; alias Bad = array; "#, - r###"error: array element count must resolve to an integer scalar (u32 or i32) + r###"error: must be a const-expression that resolves to a concrete integer scalar (u32 or i32) ┌─ wgsl:3:36 │ 3 │ alias Bad = array; - │ ^^^^^^ must resolve to u32/i32 + │ ^^^^^^ must resolve to u32 or i32 "###, ); check( "alias Bad = array;", - r###"error: array element count must be greater than zero + r###"error: array element count must be positive (> 0) ┌─ wgsl:1:24 │ 1 │ alias Bad = array; - │ ^ must be greater than zero + │ ^ must be positive "###, ); check( "alias Bad = array;", - r###"error: array element count must be greater than zero + r###"error: array element count must be positive (> 0) ┌─ wgsl:1:24 │ 1 │ alias Bad = array; - │ ^^ must be greater than zero + │ ^^ must be positive "###, ); @@ -1759,47 +1759,47 @@ fn assign_to_let() { "###, ); - check( - " - fn f() { - let a = array(1, 2); - a[0] = 1; - } - ", - r###"error: invalid left-hand side of assignment - ┌─ wgsl:3:17 - │ -3 │ let a = array(1, 2); - │ ^ this is an immutable binding -4 │ a[0] = 1; - │ ^^^^ cannot assign to this expression - │ - = note: consider declaring 'a' with `var` instead of `let` + // check( + // " + // fn f() { + // let a = array(1, 2); + // a[0] = 1; + // } + // ", + // r###"error: invalid left-hand side of assignment + // ┌─ wgsl:3:17 + // │ + // 3 │ let a = array(1, 2); + // │ ^ this is an immutable binding + // 4 │ a[0] = 1; + // │ ^^^^ cannot assign to this expression + // │ + // = note: consider declaring 'a' with `var` instead of `let` -"###, - ); + // "###, + // ); - check( - " - struct S { a: i32 } + // check( + // " + // struct S { a: i32 } - fn f() { - let a = S(10); - a.a = 20; - } - ", - r###"error: invalid left-hand side of assignment - ┌─ wgsl:5:17 - │ -5 │ let a = S(10); - │ ^ this is an immutable binding -6 │ a.a = 20; - │ ^^^ cannot assign to this expression - │ - = note: consider declaring 'a' with `var` instead of `let` + // fn f() { + // let a = S(10); + // a.a = 20; + // } + // ", + // r###"error: invalid left-hand side of assignment + // ┌─ wgsl:5:17 + // │ + // 5 │ let a = S(10); + // │ ^ this is an immutable binding + // 6 │ a.a = 20; + // │ ^^^ cannot assign to this expression + // │ + // = note: consider declaring 'a' with `var` instead of `let` -"###, - ); + // "###, + // ); } #[test] From 3fb4c333a73cc24376ecee37f86e3875ac333232 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 19 Apr 2023 15:16:46 +0200 Subject: [PATCH 2128/2212] use LocalVariable init --- src/back/glsl/mod.rs | 2 +- src/back/hlsl/writer.rs | 2 +- src/back/msl/writer.rs | 98 +- src/back/spv/block.rs | 55 +- src/back/spv/writer.rs | 74 +- src/back/wgsl/writer.rs | 2 +- src/compact/functions.rs | 10 +- src/front/glsl/context.rs | 22 +- src/front/spv/mod.rs | 2 +- src/front/wgsl/lower/mod.rs | 29 +- src/lib.rs | 4 +- src/proc/constant_evaluator.rs | 14 + src/valid/analyzer.rs | 6 + src/valid/function.rs | 6 +- src/valid/handles.rs | 4 +- tests/out/analysis/access.info.ron | 12 +- tests/out/analysis/collatz.info.ron | 2 +- tests/out/analysis/shadow.info.ron | 136 +- .../access.assign_through_ptr.Compute.glsl | 3 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 11 +- tests/out/glsl/bitcast.main.Compute.glsl | 9 - tests/out/glsl/bits.main.Compute.glsl | 10 - tests/out/glsl/boids.main.Compute.glsl | 12 +- tests/out/glsl/dualsource.main.Fragment.glsl | 6 +- tests/out/glsl/globals.main.Compute.glsl | 9 +- tests/out/glsl/operators.main.Compute.glsl | 7 +- tests/out/glsl/shadow.fs_main.Fragment.glsl | 4 +- ...adow.fs_main_without_storage.Fragment.glsl | 4 +- tests/out/hlsl/access.hlsl | 18 +- tests/out/hlsl/binding-arrays.hlsl | 12 +- tests/out/hlsl/bitcast.hlsl | 27 +- tests/out/hlsl/bits.hlsl | 30 +- tests/out/hlsl/boids.hlsl | 18 +- tests/out/hlsl/collatz.hlsl | 3 +- tests/out/hlsl/dualsource.hlsl | 6 +- tests/out/hlsl/globals.hlsl | 9 +- tests/out/hlsl/hlsl-keyword.hlsl | 3 +- tests/out/hlsl/interface.hlsl | 3 +- tests/out/hlsl/operators.hlsl | 7 +- tests/out/hlsl/shadow.hlsl | 12 +- tests/out/ir/access.compact.ron | 36 +- tests/out/ir/access.ron | 36 +- tests/out/ir/collatz.compact.ron | 6 +- tests/out/ir/collatz.ron | 6 +- tests/out/ir/shadow.compact.ron | 222 +-- tests/out/ir/shadow.ron | 222 +-- tests/out/msl/access.msl | 18 +- tests/out/msl/binding-arrays.msl | 12 +- tests/out/msl/bitcast.msl | 27 +- tests/out/msl/bits.msl | 30 +- tests/out/msl/boids.msl | 18 +- tests/out/msl/collatz.msl | 3 +- tests/out/msl/dualsource.msl | 6 +- tests/out/msl/globals.msl | 9 +- tests/out/msl/interface.msl | 3 +- tests/out/msl/operators.msl | 9 +- tests/out/msl/policy-mix.msl | 3 +- tests/out/msl/shadow.msl | 12 +- tests/out/spv/access.spvasm | 675 ++++---- .../spv/array-in-function-return-type.spvasm | 8 +- tests/out/spv/atomicCompareExchange.spvasm | 293 ++-- tests/out/spv/binding-arrays.spvasm | 959 +++++------ tests/out/spv/binding-buffer-arrays.spvasm | 97 +- tests/out/spv/bitcast.spvasm | 144 +- tests/out/spv/bits.spvasm | 406 +++-- tests/out/spv/boids.spvasm | 521 +++--- .../spv/bounds-check-image-restrict.spvasm | 30 +- tests/out/spv/bounds-check-image-rzsw.spvasm | 30 +- tests/out/spv/break-if.spvasm | 95 +- tests/out/spv/collatz.spvasm | 73 +- tests/out/spv/constructors.spvasm | 63 +- tests/out/spv/control-flow.spvasm | 60 +- tests/out/spv/debug-symbol-simple.spvasm | 261 ++- tests/out/spv/debug-symbol-terrain.spvasm | 1533 ++++++++--------- tests/out/spv/dualsource.spvasm | 79 +- tests/out/spv/extra.spvasm | 38 +- tests/out/spv/fragment-output.spvasm | 236 +-- tests/out/spv/functions.spvasm | 147 +- tests/out/spv/globals.spvasm | 278 ++- tests/out/spv/image.spvasm | 837 +++++---- tests/out/spv/interface.vertex.spvasm | 14 +- .../spv/interface.vertex_two_structs.spvasm | 76 +- tests/out/spv/interpolate.spvasm | 214 +-- tests/out/spv/math-functions.spvasm | 220 ++- tests/out/spv/operators.spvasm | 743 ++++---- tests/out/spv/padding.spvasm | 8 +- tests/out/spv/pointers.spvasm | 22 +- tests/out/spv/policy-mix.spvasm | 156 +- tests/out/spv/quad.spvasm | 8 +- tests/out/spv/ray-query.spvasm | 88 +- tests/out/spv/shadow.spvasm | 484 +++--- tests/out/spv/skybox.spvasm | 187 +- tests/out/spv/standard.spvasm | 92 +- tests/out/spv/texture-arg.spvasm | 8 +- tests/out/wgsl/access.wgsl | 18 +- tests/out/wgsl/atomicCompareExchange.wgsl | 10 +- tests/out/wgsl/binding-arrays.wgsl | 12 +- tests/out/wgsl/binding-buffer-arrays.wgsl | 3 +- tests/out/wgsl/bitcast.wgsl | 27 +- tests/out/wgsl/bits.wgsl | 30 +- tests/out/wgsl/boids.wgsl | 18 +- tests/out/wgsl/collatz.wgsl | 3 +- tests/out/wgsl/dualsource.wgsl | 6 +- tests/out/wgsl/expressions.frag.wgsl | 4 +- tests/out/wgsl/globals.wgsl | 9 +- tests/out/wgsl/interface.wgsl | 3 +- tests/out/wgsl/lexical-scopes.wgsl | 3 +- tests/out/wgsl/operators.wgsl | 9 +- tests/out/wgsl/shadow.wgsl | 12 +- 109 files changed, 5141 insertions(+), 5590 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 12d358bb8..77e206d3c 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1605,7 +1605,7 @@ impl<'a, W: Write> Writer<'a, W> { // Write the constant // `write_constant` adds no trailing or leading space/newline - self.write_const_expr(init)?; + self.write_expr(init, &ctx)?; } else if is_value_init_supported(self.module, local.ty) { write!(self.out, " = ")?; self.write_zero_init_value(local.ty)?; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index a2e0d2fef..590850fc4 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1238,7 +1238,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, " = ")?; // Write the local initializer if needed if let Some(init) = local.init { - self.write_const_expression(module, init)?; + self.write_expr(module, init, func_ctx)?; } else { // Zero initialize local variables self.write_default_init(module, local.ty)?; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index fee917b03..d0f541313 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3557,29 +3557,6 @@ impl Writer { writeln!(self.out, ") {{")?; - for (local_handle, local) in fun.local_variables.iter() { - let ty_name = TypeContext { - handle: local.ty, - gctx: module.to_ctx(), - names: &self.names, - access: crate::StorageAccess::empty(), - binding: None, - first_time: false, - }; - let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; - write!(self.out, "{}{} {}", back::INDENT, ty_name, local_name)?; - match local.init { - Some(value) => { - write!(self.out, " = ")?; - self.put_const_expression(value, module, mod_info)?; - } - None => { - write!(self.out, " = {{}}")?; - } - }; - writeln!(self.out, ";")?; - } - let guarded_indices = index::find_checked_indexes(module, fun, fun_info, options.bounds_check_policies); @@ -3596,6 +3573,30 @@ impl Writer { }, result_struct: None, }; + + for (local_handle, local) in fun.local_variables.iter() { + let ty_name = TypeContext { + handle: local.ty, + gctx: module.to_ctx(), + names: &self.names, + access: crate::StorageAccess::empty(), + binding: None, + first_time: false, + }; + let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; + write!(self.out, "{}{} {}", back::INDENT, ty_name, local_name)?; + match local.init { + Some(value) => { + write!(self.out, " = ")?; + self.put_expression(value, &context.expression, true)?; + } + None => { + write!(self.out, " = {{}}")?; + } + }; + writeln!(self.out, ";")?; + } + self.named_expressions.clear(); self.update_expressions_to_bake(fun, fun_info, &context.expression); self.put_block(back::Level(1), &fun.body, &context)?; @@ -4112,31 +4113,6 @@ impl Writer { } } - // Finally, declare all the local variables that we need - //TODO: we can postpone this till the relevant expressions are emitted - for (local_handle, local) in fun.local_variables.iter() { - let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; - let ty_name = TypeContext { - handle: local.ty, - gctx: module.to_ctx(), - names: &self.names, - access: crate::StorageAccess::empty(), - binding: None, - first_time: false, - }; - write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; - match local.init { - Some(value) => { - write!(self.out, " = ")?; - self.put_const_expression(value, module, mod_info)?; - } - None => { - write!(self.out, " = {{}}")?; - } - }; - writeln!(self.out, ";")?; - } - let guarded_indices = index::find_checked_indexes(module, fun, fun_info, options.bounds_check_policies); @@ -4153,6 +4129,32 @@ impl Writer { }, result_struct: Some(&stage_out_name), }; + + // Finally, declare all the local variables that we need + //TODO: we can postpone this till the relevant expressions are emitted + for (local_handle, local) in fun.local_variables.iter() { + let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; + let ty_name = TypeContext { + handle: local.ty, + gctx: module.to_ctx(), + names: &self.names, + access: crate::StorageAccess::empty(), + binding: None, + first_time: false, + }; + write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; + match local.init { + Some(value) => { + write!(self.out, " = ")?; + self.put_expression(value, &context.expression, true)?; + } + None => { + write!(self.out, " = {{}}")?; + } + }; + writeln!(self.out, ";")?; + } + self.named_expressions.clear(); self.update_expressions_to_bake(fun, fun_info, &context.expression); self.put_block(back::Level(1), &fun.body, &context)?; diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index c5246ad19..d698931f6 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -252,13 +252,39 @@ impl<'w> BlockContext<'w> { self.temp_list.push(self.cached[component]); } - let id = self.gen_id(); - block.body.push(Instruction::composite_construct( - result_type_id, - id, - &self.temp_list, - )); - id + if self.ir_function.expressions.is_const(expr_handle) { + let ty = self + .writer + .get_expression_lookup_type(&self.fun_info[expr_handle].ty); + self.writer.get_constant_composite(ty, &self.temp_list) + } else { + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + result_type_id, + id, + &self.temp_list, + )); + id + } + } + crate::Expression::Splat { size, value } => { + let value_id = self.cached[value]; + let components = &[value_id; 4][..size as usize]; + + if self.ir_function.expressions.is_const(expr_handle) { + let ty = self + .writer + .get_expression_lookup_type(&self.fun_info[expr_handle].ty); + self.writer.get_constant_composite(ty, components) + } else { + let id = self.gen_id(); + block.body.push(Instruction::composite_construct( + result_type_id, + id, + components, + )); + id + } } crate::Expression::Access { base, index: _ } if self.is_intermediate(base) => { // See `is_intermediate`; we'll handle this later in @@ -405,17 +431,6 @@ impl<'w> BlockContext<'w> { crate::Expression::GlobalVariable(handle) => { self.writer.global_variables[handle.index()].access_id } - crate::Expression::Splat { size, value } => { - let value_id = self.cached[value]; - let components = [value_id; 4]; - let id = self.gen_id(); - block.body.push(Instruction::composite_construct( - result_type_id, - id, - &components[..size as usize], - )); - id - } crate::Expression::Swizzle { size, vector, @@ -1758,7 +1773,9 @@ impl<'w> BlockContext<'w> { match *statement { crate::Statement::Emit(ref range) => { for handle in range.clone() { - self.cache_expression_value(handle, &mut block)?; + if !self.ir_function.expressions.is_const(handle) { + self.cache_expression_value(handle, &mut block)?; + } } } crate::Statement::Block(ref block_statements) => { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 4be19cce6..7d7937778 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -338,37 +338,6 @@ impl Writer { ) -> Result { let mut function = Function::default(); - for (handle, variable) in ir_function.local_variables.iter() { - let id = self.id_gen.next(); - - if self.flags.contains(WriterFlags::DEBUG) { - if let Some(ref name) = variable.name { - self.debugs.push(Instruction::name(id, name)); - } - } - - let init_word = variable - .init - .map(|constant| self.constant_ids[constant.index()]); - let pointer_type_id = - self.get_pointer_id(&ir_module.types, variable.ty, spirv::StorageClass::Function)?; - let instruction = Instruction::variable( - pointer_type_id, - id, - spirv::StorageClass::Function, - init_word.or_else(|| match ir_module.types[variable.ty].inner { - crate::TypeInner::RayQuery => None, - _ => { - let type_id = self.get_type_id(LookupType::Handle(variable.ty)); - Some(self.get_constant_null(type_id)) - } - }), - ); - function - .variables - .insert(handle, LocalVariable { id, instruction }); - } - let prelude_id = self.id_gen.next(); let mut prelude = Block::new(prelude_id); let mut ep_context = EntryPointContext { @@ -656,7 +625,48 @@ impl Writer { // fill up the pre-emitted expressions context.cached.reset(ir_function.expressions.len()); for (handle, expr) in ir_function.expressions.iter() { - if expr.needs_pre_emit() { + if (expr.needs_pre_emit() && !matches!(*expr, crate::Expression::LocalVariable(_))) + || ir_function.expressions.is_const(handle) + { + context.cache_expression_value(handle, &mut prelude)?; + } + } + + for (handle, variable) in ir_function.local_variables.iter() { + let id = context.gen_id(); + + if context.writer.flags.contains(WriterFlags::DEBUG) { + if let Some(ref name) = variable.name { + context.writer.debugs.push(Instruction::name(id, name)); + } + } + + let init_word = variable.init.map(|constant| context.cached[constant]); + let pointer_type_id = context.writer.get_pointer_id( + &ir_module.types, + variable.ty, + spirv::StorageClass::Function, + )?; + let instruction = Instruction::variable( + pointer_type_id, + id, + spirv::StorageClass::Function, + init_word.or_else(|| match ir_module.types[variable.ty].inner { + crate::TypeInner::RayQuery => None, + _ => { + let type_id = context.get_type_id(LookupType::Handle(variable.ty)); + Some(context.writer.write_constant_null(type_id)) + } + }), + ); + context + .function + .variables + .insert(handle, LocalVariable { id, instruction }); + } + + for (handle, expr) in ir_function.expressions.iter() { + if expr.needs_pre_emit() && matches!(*expr, crate::Expression::LocalVariable(_)) { context.cache_expression_value(handle, &mut prelude)?; } } diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index e41460061..0655fcde8 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -292,7 +292,7 @@ impl Writer { // Write the constant // `write_constant` adds no trailing or leading space/newline - self.write_const_expression(module, init)?; + self.write_expr(module, init, func_ctx)?; } // Finish the local with `;` and add a newline (only for readability) diff --git a/src/compact/functions.rs b/src/compact/functions.rs index 176221f98..752c3eb7f 100644 --- a/src/compact/functions.rs +++ b/src/compact/functions.rs @@ -27,7 +27,7 @@ impl<'a> FunctionTracer<'a> { for (_, local) in self.function.local_variables.iter() { self.trace_type(local.ty); if let Some(init) = local.init { - self.trace_const_expression(init); + self.trace_expression(init); } } @@ -48,12 +48,6 @@ impl<'a> FunctionTracer<'a> { self.as_expression().trace_expression(expr); } - pub fn trace_const_expression(&mut self, expr: Handle) { - self.as_expression() - .as_const_expression() - .trace_expression(expr); - } - fn as_type(&mut self) -> super::types::TypeTracer { super::types::TypeTracer { types: &self.module.types, @@ -99,7 +93,7 @@ impl FunctionMap { log::trace!("adjusting local variable {:?}", local.name); module_map.types.adjust(&mut local.ty); if let Some(ref mut init) = local.init { - module_map.const_expressions.adjust(init); + self.expressions.adjust(init); } } diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index ffdc2bd97..a13e6ac5b 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -988,18 +988,16 @@ impl<'a> Context<'a> { // pointer type which is required for dynamic indexing if !constant_index { if let Some((constant, ty)) = var.constant { - let local = - self.locals.append( - LocalVariable { - name: None, - ty, - init: Some(self.module.const_expressions.append( - Expression::Constant(constant), - Span::default(), - )), - }, - Span::default(), - ); + let init = self + .add_expression(Expression::Constant(constant), Span::default())?; + let local = self.locals.append( + LocalVariable { + name: None, + ty, + init: Some(init), + }, + Span::default(), + ); self.add_expression(Expression::LocalVariable(local), Span::default())? } else { diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 5fd54b023..1609868ef 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -1395,7 +1395,7 @@ impl> Frontend { let init_id = self.next()?; let lconst = self.lookup_constant.lookup(init_id)?; Some( - ctx.const_expressions + ctx.expressions .append(crate::Expression::Constant(lconst.handle), span), ) } else { diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 3a78f0f2b..edb4f6d49 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1031,6 +1031,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut typifier = Typifier::default(); let mut body = self.block( &f.body, + false, StatementContext { local_table: &mut local_table, globals: ctx.globals, @@ -1091,12 +1092,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn block( &mut self, b: &ast::Block<'source>, + is_inside_loop: bool, mut ctx: StatementContext<'source, '_, '_>, ) -> Result> { let mut block = crate::Block::default(); for stmt in b.stmts.iter() { - self.statement(stmt, &mut block, ctx.reborrow())?; + self.statement(stmt, &mut block, is_inside_loop, ctx.reborrow())?; } Ok(block) @@ -1106,11 +1108,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, stmt: &ast::Statement<'source>, block: &mut crate::Block, + is_inside_loop: bool, mut ctx: StatementContext<'source, '_, '_>, ) -> Result<(), Error<'source>> { let out = match stmt.kind { ast::StatementKind::Block(ref block) => { - let block = self.block(block, ctx.reborrow())?; + let block = self.block(block, is_inside_loop, ctx.reborrow())?; crate::Statement::Block(block) } ast::StatementKind::LocalDecl(ref decl) => match *decl { @@ -1191,11 +1194,21 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; + let (const_initializer, initializer) = { + match initializer { + Some(init) if ctx.naga_expressions.is_const(init) => { + (Some(init), is_inside_loop.then_some(init)) + } + Some(init) => (None, Some(init)), + None => (None, None), + } + }; + let var = ctx.variables.append( crate::LocalVariable { name: Some(v.name.name.to_string()), ty, - init: None, + init: const_initializer, }, stmt.span, ); @@ -1234,8 +1247,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { self.expression(condition, ctx.as_expression(block, &mut emitter))?; block.extend(emitter.finish(ctx.naga_expressions)); - let accept = self.block(accept, ctx.reborrow())?; - let reject = self.block(reject, ctx.reborrow())?; + let accept = self.block(accept, is_inside_loop, ctx.reborrow())?; + let reject = self.block(reject, is_inside_loop, ctx.reborrow())?; crate::Statement::If { condition, @@ -1282,7 +1295,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::SwitchValue::Default => crate::SwitchValue::Default, }, - body: self.block(&case.body, ctx.reborrow())?, + body: self.block(&case.body, is_inside_loop, ctx.reborrow())?, fall_through: case.fall_through, }) }) @@ -1295,8 +1308,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ref continuing, break_if, } => { - let body = self.block(body, ctx.reborrow())?; - let mut continuing = self.block(continuing, ctx.reborrow())?; + let body = self.block(body, true, ctx.reborrow())?; + let mut continuing = self.block(continuing, true, ctx.reborrow())?; let mut emitter = Emitter::default(); emitter.start(ctx.naga_expressions); diff --git a/src/lib.rs b/src/lib.rs index 93ecaa1ab..80461e16f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -978,9 +978,7 @@ pub struct LocalVariable { pub name: Option, /// The type of this variable. pub ty: Handle, - /// Initial value for this variable. - /// - /// Expression handle lives in const_expressions + /// Initial value for this variable. Must be a const-expression. pub init: Option>, } diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index cf00b13de..6778a0bf9 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -91,6 +91,20 @@ pub enum ExprType { // Math // As +// TODO(teoxoy): consider accumulating this metadata instead of recursing through subexpressions +impl Arena { + pub fn is_const(&self, handle: Handle) -> bool { + match self[handle] { + Expression::Literal(_) | Expression::ZeroValue(_) | Expression::Constant(_) => true, + Expression::Compose { ref components, .. } => { + components.iter().all(|h| self.is_const(*h)) + } + Expression::Splat { ref value, .. } => self.is_const(*value), + _ => false, + } + } +} + impl<'a, F: FnMut(&mut Arena, Expression, Span) -> Handle> ConstantEvaluator<'a, F> { diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs index 0ed707c1e..ff1db071c 100644 --- a/src/valid/analyzer.rs +++ b/src/valid/analyzer.rs @@ -1041,6 +1041,12 @@ impl ModuleInfo { } } + for (_, expr) in fun.local_variables.iter() { + if let Some(init) = expr.init { + let _ = info.add_ref(init); + } + } + let uniformity = info.process_block(&fun.body, &self.functions, None, &fun.expressions)?; info.uniformity = uniformity.result; info.may_kill = uniformity.exit.contains(ExitFlags::MAY_KILL); diff --git a/src/valid/function.rs b/src/valid/function.rs index 998f873c0..a056a1d1f 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -941,7 +941,7 @@ impl super::Validator { &self, var: &crate::LocalVariable, gctx: crate::proc::GlobalCtx, - mod_info: &ModuleInfo, + fun_info: &FunctionInfo, ) -> Result<(), LocalVariableError> { log::debug!("var {:?}", var); let type_info = self @@ -954,7 +954,7 @@ impl super::Validator { if let Some(init) = var.init { let decl_ty = &gctx.types[var.ty].inner; - let init_ty = mod_info[init].inner_with(gctx.types); + let init_ty = fun_info[init].ty.inner_with(gctx.types); if !decl_ty.equivalent(init_ty, gctx.types) { return Err(LocalVariableError::InitializerType); } @@ -975,7 +975,7 @@ impl super::Validator { #[cfg(feature = "validate")] for (var_handle, var) in fun.local_variables.iter() { - self.validate_local_var(var, module.to_ctx(), mod_info) + self.validate_local_var(var, module.to_ctx(), &info) .map_err(|source| { FunctionError::LocalVariable { handle: var_handle, diff --git a/src/valid/handles.rs b/src/valid/handles.rs index da95f6084..c68ded074 100644 --- a/src/valid/handles.rs +++ b/src/valid/handles.rs @@ -131,8 +131,8 @@ impl super::Validator { for (_handle, local_variable) in local_variables.iter() { let &crate::LocalVariable { name: _, ty, init } = local_variable; validate_type(ty)?; - if let Some(init_constant) = init { - validate_const_expr(init_constant)?; + if let Some(init) = init { + Self::validate_expression_handle(init, expressions)?; } } diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron index 4a020e48c..f66a79285 100644 --- a/tests/out/analysis/access.info.ron +++ b/tests/out/analysis/access.info.ron @@ -66,7 +66,7 @@ non_uniform_result: Some(2), requirements: (""), ), - ref_count: 15, + ref_count: 14, assignable_global: None, ty: Value(Pointer( base: 3, @@ -637,7 +637,7 @@ non_uniform_result: Some(50), requirements: (""), ), - ref_count: 8, + ref_count: 7, assignable_global: None, ty: Value(Pointer( base: 16, @@ -1164,7 +1164,7 @@ non_uniform_result: Some(2), requirements: (""), ), - ref_count: 15, + ref_count: 14, assignable_global: None, ty: Value(Pointer( base: 3, @@ -1777,7 +1777,7 @@ non_uniform_result: Some(54), requirements: (""), ), - ref_count: 9, + ref_count: 8, assignable_global: None, ty: Value(Pointer( base: 20, @@ -2667,7 +2667,7 @@ non_uniform_result: Some(3), requirements: (""), ), - ref_count: 4, + ref_count: 3, assignable_global: None, ty: Value(Pointer( base: 21, @@ -3803,7 +3803,7 @@ non_uniform_result: Some(6), requirements: (""), ), - ref_count: 2, + ref_count: 1, assignable_global: None, ty: Value(Pointer( base: 28, diff --git a/tests/out/analysis/collatz.info.ron b/tests/out/analysis/collatz.info.ron index 8241bf9a1..5b32bf44a 100644 --- a/tests/out/analysis/collatz.info.ron +++ b/tests/out/analysis/collatz.info.ron @@ -57,7 +57,7 @@ non_uniform_result: Some(4), requirements: (""), ), - ref_count: 4, + ref_count: 3, assignable_global: None, ty: Value(Pointer( base: 1, diff --git a/tests/out/analysis/shadow.info.ron b/tests/out/analysis/shadow.info.ron index 15ec6e2b3..3553f9030 100644 --- a/tests/out/analysis/shadow.info.ron +++ b/tests/out/analysis/shadow.info.ron @@ -625,7 +625,16 @@ ), ( uniformity: ( - non_uniform_result: Some(20), + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(2), + ), + ( + uniformity: ( + non_uniform_result: Some(21), requirements: (""), ), ref_count: 3, @@ -637,7 +646,16 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(3), + ), + ( + uniformity: ( + non_uniform_result: Some(23), requirements: (""), ), ref_count: 11, @@ -649,7 +667,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -708,7 +726,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -720,7 +738,7 @@ ), ( uniformity: ( - non_uniform_result: Some(20), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -729,7 +747,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -752,7 +770,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -761,7 +779,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -775,7 +793,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -789,7 +807,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -807,7 +825,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -861,7 +879,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -870,7 +888,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -884,7 +902,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -898,7 +916,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -914,7 +932,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -940,7 +958,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -949,7 +967,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -963,7 +981,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -977,7 +995,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -993,7 +1011,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1019,7 +1037,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1028,7 +1046,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1042,7 +1060,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1056,7 +1074,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1072,7 +1090,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1084,7 +1102,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1180,7 +1198,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1189,7 +1207,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1242,7 +1260,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1251,7 +1269,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1265,7 +1283,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1279,7 +1297,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1295,7 +1313,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1321,7 +1339,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1330,7 +1348,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1344,7 +1362,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1358,7 +1376,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1374,7 +1392,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1400,7 +1418,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1409,7 +1427,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1423,7 +1441,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1437,7 +1455,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1453,7 +1471,7 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1465,7 +1483,16 @@ ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Handle(2), + ), + ( + uniformity: ( + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1483,16 +1510,16 @@ ), ( uniformity: ( - non_uniform_result: Some(20), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, assignable_global: None, - ty: Handle(2), + ty: Handle(3), ), ( uniformity: ( - non_uniform_result: Some(21), + non_uniform_result: Some(23), requirements: (""), ), ref_count: 1, @@ -1506,20 +1533,11 @@ ), ref_count: 1, assignable_global: None, - ty: Handle(3), - ), - ( - uniformity: ( - non_uniform_result: Some(20), - requirements: (""), - ), - ref_count: 1, - assignable_global: None, ty: Handle(2), ), ( uniformity: ( - non_uniform_result: Some(20), + non_uniform_result: Some(21), requirements: (""), ), ref_count: 1, @@ -1701,7 +1719,5 @@ kind: Sint, width: 4, )), - Handle(2), - Handle(3), ], ) \ No newline at end of file diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/tests/out/glsl/access.assign_through_ptr.Compute.glsl index ab5bd9a3f..a75b0f4d9 100644 --- a/tests/out/glsl/access.assign_through_ptr.Compute.glsl +++ b/tests/out/glsl/access.assign_through_ptr.Compute.glsl @@ -47,8 +47,7 @@ void main() { } memoryBarrierShared(); barrier(); - vec4 arr[2] = vec4[2](vec4(0.0), vec4(0.0)); - arr = vec4[2](vec4(6.0), vec4(7.0)); + vec4 arr[2] = vec4[2](vec4(6.0), vec4(7.0)); assign_through_ptr_fn(val); assign_array_through_ptr_fn(arr); return; diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index a505ee19e..a79ff3039 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -34,9 +34,8 @@ uniform MatCx2InArray_block_3Vertex { MatCx2InArray _group_0_binding_3_vs; }; void test_matrix_within_struct_accesses() { - int idx = 0; - Baz t = Baz(mat3x2(0.0)); - idx = 1; + int idx = 1; + Baz t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); int _e3 = idx; idx = (_e3 - 1); mat3x2 l0_ = _group_0_binding_1_vs.m; @@ -51,7 +50,6 @@ void test_matrix_within_struct_accesses() { int _e36 = idx; int _e38 = idx; float l6_ = _group_0_binding_1_vs.m[_e36][_e38]; - t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); int _e51 = idx; idx = (_e51 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); @@ -70,9 +68,8 @@ void test_matrix_within_struct_accesses() { } void test_matrix_within_array_within_struct_accesses() { - int idx_1 = 0; + int idx_1 = 1; MatCx2InArray t_1 = MatCx2InArray(mat4x2[2](mat4x2(0.0), mat4x2(0.0))); - idx_1 = 1; int _e3 = idx_1; idx_1 = (_e3 - 1); mat4x2 l0_1[2] = _group_0_binding_3_vs.am; @@ -88,7 +85,6 @@ void test_matrix_within_array_within_struct_accesses() { int _e46 = idx_1; int _e48 = idx_1; float l7_ = _group_0_binding_3_vs.am[0][_e46][_e48]; - t_1 = MatCx2InArray(mat4x2[2](mat4x2(0.0), mat4x2(0.0))); int _e55 = idx_1; idx_1 = (_e55 + 1); t_1.am = mat4x2[2](mat4x2(0.0), mat4x2(0.0)); @@ -130,7 +126,6 @@ void main() { uint vi = uint(gl_VertexID); float foo = 0.0; int c2_[5] = int[5](0, 0, 0, 0, 0); - foo = 0.0; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); diff --git a/tests/out/glsl/bitcast.main.Compute.glsl b/tests/out/glsl/bitcast.main.Compute.glsl index 215aef8a5..57e7e221b 100644 --- a/tests/out/glsl/bitcast.main.Compute.glsl +++ b/tests/out/glsl/bitcast.main.Compute.glsl @@ -16,15 +16,6 @@ void main() { vec2 f2_ = vec2(0.0); vec3 f3_ = vec3(0.0); vec4 f4_ = vec4(0.0); - i2_ = ivec2(0); - i3_ = ivec3(0); - i4_ = ivec4(0); - u2_ = uvec2(0u); - u3_ = uvec3(0u); - u4_ = uvec4(0u); - f2_ = vec2(0.0); - f3_ = vec3(0.0); - f4_ = vec4(0.0); ivec2 _e27 = i2_; u2_ = uvec2(_e27); ivec3 _e29 = i3_; diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl index 1c17638fa..f991f532a 100644 --- a/tests/out/glsl/bits.main.Compute.glsl +++ b/tests/out/glsl/bits.main.Compute.glsl @@ -17,16 +17,6 @@ void main() { uvec4 u4_ = uvec4(0u); vec2 f2_ = vec2(0.0); vec4 f4_ = vec4(0.0); - i = 0; - i2_ = ivec2(0); - i3_ = ivec3(0); - i4_ = ivec4(0); - u = 0u; - u2_ = uvec2(0u); - u3_ = uvec3(0u); - u4_ = uvec4(0u); - f2_ = vec2(0.0); - f4_ = vec4(0.0); vec4 _e28 = f4_; u = packSnorm4x8(_e28); vec4 _e30 = f4_; diff --git a/tests/out/glsl/boids.main.Compute.glsl b/tests/out/glsl/boids.main.Compute.glsl index 8d6067aee..c42358bfe 100644 --- a/tests/out/glsl/boids.main.Compute.glsl +++ b/tests/out/glsl/boids.main.Compute.glsl @@ -35,9 +35,9 @@ void main() { uvec3 global_invocation_id = gl_GlobalInvocationID; vec2 vPos = vec2(0.0); vec2 vVel = vec2(0.0); - vec2 cMass = vec2(0.0); - vec2 cVel = vec2(0.0); - vec2 colVel = vec2(0.0); + vec2 cMass = vec2(0.0, 0.0); + vec2 cVel = vec2(0.0, 0.0); + vec2 colVel = vec2(0.0, 0.0); int cMassCount = 0; int cVelCount = 0; vec2 pos = vec2(0.0); @@ -51,12 +51,6 @@ void main() { vPos = _e8; vec2 _e14 = _group_0_binding_1_cs.particles[index].vel; vVel = _e14; - cMass = vec2(0.0, 0.0); - cVel = vec2(0.0, 0.0); - colVel = vec2(0.0, 0.0); - cMassCount = 0; - cVelCount = 0; - i = 0u; bool loop_init = true; while(true) { if (!loop_init) { diff --git a/tests/out/glsl/dualsource.main.Fragment.glsl b/tests/out/glsl/dualsource.main.Fragment.glsl index 9ac463c2b..ef5792279 100644 --- a/tests/out/glsl/dualsource.main.Fragment.glsl +++ b/tests/out/glsl/dualsource.main.Fragment.glsl @@ -13,10 +13,8 @@ layout(location = 0, index = 1) out vec4 _fs2p_location1; void main() { vec4 position = gl_FragCoord; - vec4 color = vec4(0.0); - vec4 mask = vec4(0.0); - color = vec4(0.4, 0.3, 0.2, 0.1); - mask = vec4(0.9, 0.8, 0.7, 0.6); + vec4 color = vec4(0.4, 0.3, 0.2, 0.1); + vec4 mask = vec4(0.9, 0.8, 0.7, 0.6); vec4 _e13 = color; vec4 _e14 = mask; FragmentOutput _tmp_return = FragmentOutput(_e13, _e14); diff --git a/tests/out/glsl/globals.main.Compute.glsl b/tests/out/glsl/globals.main.Compute.glsl index b5e36f541..b7ef8bd29 100644 --- a/tests/out/glsl/globals.main.Compute.glsl +++ b/tests/out/glsl/globals.main.Compute.glsl @@ -35,9 +35,8 @@ void test_msl_packed_vec3_as_arg(vec3 arg) { } void test_msl_packed_vec3_() { - int idx = 0; + int idx = 1; _group_0_binding_1_cs.v3_ = vec3(1.0); - idx = 1; _group_0_binding_1_cs.v3_.x = 1.0; _group_0_binding_1_cs.v3_.x = 2.0; int _e16 = idx; @@ -59,8 +58,8 @@ void main() { } memoryBarrierShared(); barrier(); - float Foo = 0.0; - bool at = false; + float Foo = 1.0; + bool at = true; test_msl_packed_vec3_(); mat4x2 _e5 = _group_0_binding_7_cs[0][0]; vec4 _e10 = _group_0_binding_6_cs[0][0][0]; @@ -79,8 +78,6 @@ void main() { _group_0_binding_1_cs.v1_ = 4.0; wg[1] = float(uint(_group_0_binding_2_cs.length())); at_1 = 2u; - Foo = 1.0; - at = true; return; } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index 1ed88c102..a1a7131e9 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -30,8 +30,7 @@ vec4 splat() { } vec2 splat_assignment() { - vec2 a = vec2(0.0); - a = vec2(2.0); + vec2 a = vec2(2.0); vec2 _e4 = a; a = (_e4 + vec2(1.0)); vec2 _e8 = a; @@ -151,9 +150,8 @@ void comparison() { } void assignment() { - int a_1 = 0; + int a_1 = 1; ivec3 vec0_ = ivec3(0); - a_1 = 1; int _e3 = a_1; a_1 = (_e3 + 1); int _e6 = a_1; @@ -180,7 +178,6 @@ void assignment() { a_1 = (_e33 + 1); int _e36 = a_1; a_1 = (_e36 - 1); - vec0_ = ivec3(0); int _e42 = vec0_.y; vec0_.y = (_e42 + 1); int _e46 = vec0_.y; diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/tests/out/glsl/shadow.fs_main.Fragment.glsl index 091085081..61c14561d 100644 --- a/tests/out/glsl/shadow.fs_main.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main.Fragment.glsl @@ -49,11 +49,9 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { void main() { VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); - vec3 color = vec3(0.0); + vec3 color = c_ambient; uint i = 0u; vec3 normal_1 = normalize(in_.world_normal); - color = c_ambient; - i = 0u; bool loop_init = true; while(true) { if (!loop_init) { diff --git a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl index c85a89eb9..57677c91a 100644 --- a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl +++ b/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl @@ -49,11 +49,9 @@ float fetch_shadow(uint light_id, vec4 homogeneous_coords) { void main() { VertexOutput in_1 = VertexOutput(gl_FragCoord, _vs2fs_location0, _vs2fs_location1); - vec3 color_1 = vec3(0.0); + vec3 color_1 = c_ambient; uint i_1 = 0u; vec3 normal_1 = normalize(in_1.world_normal); - color_1 = c_ambient; - i_1 = 0u; bool loop_init = true; while(true) { if (!loop_init) { diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 465643bb4..6f44bdb07 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -119,10 +119,9 @@ void SetMatScalarmOnBaz(Baz obj, float scalar, uint mat_idx, uint vec_idx) { void test_matrix_within_struct_accesses() { - int idx = (int)0; - Baz t = (Baz)0; + int idx = 1; + Baz t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); - idx = 1; int _expr3 = idx; idx = (_expr3 - 1); float3x2 l0_ = GetMatmOnBaz(baz); @@ -137,7 +136,6 @@ void test_matrix_within_struct_accesses() int _expr36 = idx; int _expr38 = idx; float l6_ = GetMatmOnBaz(baz)[_expr36][_expr38]; - t = ConstructBaz(float3x2((1.0).xx, (2.0).xx, (3.0).xx)); int _expr51 = idx; idx = (_expr51 + 1); SetMatmOnBaz(t, float3x2((6.0).xx, (5.0).xx, (4.0).xx)); @@ -163,10 +161,9 @@ MatCx2InArray ConstructMatCx2InArray(float4x2 arg0[2]) { void test_matrix_within_array_within_struct_accesses() { - int idx_1 = (int)0; - MatCx2InArray t_1 = (MatCx2InArray)0; + int idx_1 = 1; + MatCx2InArray t_1 = ConstructMatCx2InArray((float4x2[2])0); - idx_1 = 1; int _expr3 = idx_1; idx_1 = (_expr3 - 1); float4x2 l0_1[2] = ((float4x2[2])nested_mat_cx2_.am); @@ -182,7 +179,6 @@ void test_matrix_within_array_within_struct_accesses() int _expr46 = idx_1; int _expr48 = idx_1; float l7_ = __get_col_of_mat4x2(nested_mat_cx2_.am[0], _expr46)[_expr48]; - t_1 = ConstructMatCx2InArray((float4x2[2])0); int _expr55 = idx_1; idx_1 = (_expr55 + 1); t_1.am = (__mat4x2[2])(float4x2[2])0; @@ -251,10 +247,9 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer) float4 foo_vert(uint vi : SV_VertexID) : SV_Position { - float foo = (float)0; + float foo = 0.0; int c2_[5] = (int[5])0; - foo = 0.0; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); @@ -299,9 +294,8 @@ void assign_through_ptr(uint3 __local_invocation_id : SV_GroupThreadID) val = (uint)0; } GroupMemoryBarrierWithGroupSync(); - float4 arr[2] = (float4[2])0; + float4 arr[2] = Constructarray2_float4_((6.0).xxxx, (7.0).xxxx); - arr = Constructarray2_float4_((6.0).xxxx, (7.0).xxxx); assign_through_ptr_fn(val); assign_array_through_ptr_fn(arr); return; diff --git a/tests/out/hlsl/binding-arrays.hlsl b/tests/out/hlsl/binding-arrays.hlsl index 4a22c2746..aa631b322 100644 --- a/tests/out/hlsl/binding-arrays.hlsl +++ b/tests/out/hlsl/binding-arrays.hlsl @@ -51,17 +51,13 @@ uint NagaMSNumSamples2D(Texture2DMS tex) float4 main(FragmentInput_main fragmentinput_main) : SV_Target0 { FragmentIn fragment_in = { fragmentinput_main.index }; - uint u1_ = (uint)0; - uint2 u2_ = (uint2)0; - float v1_ = (float)0; - float4 v4_ = (float4)0; + uint u1_ = 0u; + uint2 u2_ = (0u).xx; + float v1_ = 0.0; + float4 v4_ = (0.0).xxxx; uint uniform_index = uni.index; uint non_uniform_index = fragment_in.index; - u1_ = 0u; - u2_ = (0u).xx; - v1_ = 0.0; - v4_ = (0.0).xxxx; float2 uv = (0.0).xx; int2 pix = (0).xx; uint2 _expr22 = u2_; diff --git a/tests/out/hlsl/bitcast.hlsl b/tests/out/hlsl/bitcast.hlsl index 00f4206a1..520807400 100644 --- a/tests/out/hlsl/bitcast.hlsl +++ b/tests/out/hlsl/bitcast.hlsl @@ -1,25 +1,16 @@ [numthreads(1, 1, 1)] void main() { - int2 i2_ = (int2)0; - int3 i3_ = (int3)0; - int4 i4_ = (int4)0; - uint2 u2_ = (uint2)0; - uint3 u3_ = (uint3)0; - uint4 u4_ = (uint4)0; - float2 f2_ = (float2)0; - float3 f3_ = (float3)0; - float4 f4_ = (float4)0; + int2 i2_ = (0).xx; + int3 i3_ = (0).xxx; + int4 i4_ = (0).xxxx; + uint2 u2_ = (0u).xx; + uint3 u3_ = (0u).xxx; + uint4 u4_ = (0u).xxxx; + float2 f2_ = (0.0).xx; + float3 f3_ = (0.0).xxx; + float4 f4_ = (0.0).xxxx; - i2_ = (0).xx; - i3_ = (0).xxx; - i4_ = (0).xxxx; - u2_ = (0u).xx; - u3_ = (0u).xxx; - u4_ = (0u).xxxx; - f2_ = (0.0).xx; - f3_ = (0.0).xxx; - f4_ = (0.0).xxxx; int2 _expr27 = i2_; u2_ = asuint(_expr27); int3 _expr29 = i3_; diff --git a/tests/out/hlsl/bits.hlsl b/tests/out/hlsl/bits.hlsl index 55e1afbd8..8ae2f7e1f 100644 --- a/tests/out/hlsl/bits.hlsl +++ b/tests/out/hlsl/bits.hlsl @@ -1,27 +1,17 @@ [numthreads(1, 1, 1)] void main() { - int i = (int)0; - int2 i2_ = (int2)0; - int3 i3_ = (int3)0; - int4 i4_ = (int4)0; - uint u = (uint)0; - uint2 u2_ = (uint2)0; - uint3 u3_ = (uint3)0; - uint4 u4_ = (uint4)0; - float2 f2_ = (float2)0; - float4 f4_ = (float4)0; + int i = 0; + int2 i2_ = (0).xx; + int3 i3_ = (0).xxx; + int4 i4_ = (0).xxxx; + uint u = 0u; + uint2 u2_ = (0u).xx; + uint3 u3_ = (0u).xxx; + uint4 u4_ = (0u).xxxx; + float2 f2_ = (0.0).xx; + float4 f4_ = (0.0).xxxx; - i = 0; - i2_ = (0).xx; - i3_ = (0).xxx; - i4_ = (0).xxxx; - u = 0u; - u2_ = (0u).xx; - u3_ = (0u).xxx; - u4_ = (0u).xxxx; - f2_ = (0.0).xx; - f4_ = (0.0).xxxx; float4 _expr28 = f4_; u = uint((int(round(clamp(_expr28[0], -1.0, 1.0) * 127.0)) & 0xFF) | ((int(round(clamp(_expr28[1], -1.0, 1.0) * 127.0)) & 0xFF) << 8) | ((int(round(clamp(_expr28[2], -1.0, 1.0) * 127.0)) & 0xFF) << 16) | ((int(round(clamp(_expr28[3], -1.0, 1.0) * 127.0)) & 0xFF) << 24)); float4 _expr30 = f4_; diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl index 5400a5e3a..bb6f6f9d1 100644 --- a/tests/out/hlsl/boids.hlsl +++ b/tests/out/hlsl/boids.hlsl @@ -24,14 +24,14 @@ void main(uint3 global_invocation_id : SV_DispatchThreadID) { float2 vPos = (float2)0; float2 vVel = (float2)0; - float2 cMass = (float2)0; - float2 cVel = (float2)0; - float2 colVel = (float2)0; - int cMassCount = (int)0; - int cVelCount = (int)0; + float2 cMass = float2(0.0, 0.0); + float2 cVel = float2(0.0, 0.0); + float2 colVel = float2(0.0, 0.0); + int cMassCount = 0; + int cVelCount = 0; float2 pos = (float2)0; float2 vel = (float2)0; - uint i = (uint)0; + uint i = 0u; uint index = global_invocation_id.x; if ((index >= NUM_PARTICLES)) { @@ -41,12 +41,6 @@ void main(uint3 global_invocation_id : SV_DispatchThreadID) vPos = _expr8; float2 _expr14 = asfloat(particlesSrc.Load2(8+index*16+0)); vVel = _expr14; - cMass = float2(0.0, 0.0); - cVel = float2(0.0, 0.0); - colVel = float2(0.0, 0.0); - cMassCount = 0; - cVelCount = 0; - i = 0u; bool loop_init = true; while(true) { if (!loop_init) { diff --git a/tests/out/hlsl/collatz.hlsl b/tests/out/hlsl/collatz.hlsl index 92539ee2f..a8a5a776e 100644 --- a/tests/out/hlsl/collatz.hlsl +++ b/tests/out/hlsl/collatz.hlsl @@ -3,10 +3,9 @@ RWByteAddressBuffer v_indices : register(u0); uint collatz_iterations(uint n_base) { uint n = (uint)0; - uint i = (uint)0; + uint i = 0u; n = n_base; - i = 0u; while(true) { uint _expr4 = n; if ((_expr4 > 1u)) { diff --git a/tests/out/hlsl/dualsource.hlsl b/tests/out/hlsl/dualsource.hlsl index 1d5b53d6f..36784b13d 100644 --- a/tests/out/hlsl/dualsource.hlsl +++ b/tests/out/hlsl/dualsource.hlsl @@ -17,11 +17,9 @@ FragmentOutput ConstructFragmentOutput(float4 arg0, float4 arg1) { FragmentOutput main(FragmentInput_main fragmentinput_main) { float4 position = fragmentinput_main.position_1; - float4 color = (float4)0; - float4 mask = (float4)0; + float4 color = float4(0.4, 0.3, 0.2, 0.1); + float4 mask = float4(0.9, 0.8, 0.7, 0.6); - color = float4(0.4, 0.3, 0.2, 0.1); - mask = float4(0.9, 0.8, 0.7, 0.6); float4 _expr13 = color; float4 _expr14 = mask; const FragmentOutput fragmentoutput = ConstructFragmentOutput(_expr13, _expr14); diff --git a/tests/out/hlsl/globals.hlsl b/tests/out/hlsl/globals.hlsl index b4994837c..55faf060d 100644 --- a/tests/out/hlsl/globals.hlsl +++ b/tests/out/hlsl/globals.hlsl @@ -80,10 +80,9 @@ FooStruct ConstructFooStruct(float3 arg0, float arg1) { void test_msl_packed_vec3_() { - int idx = (int)0; + int idx = 1; alignment.Store3(0, asuint((1.0).xxx)); - idx = 1; alignment.Store(0+0, asuint(1.0)); alignment.Store(0+0, asuint(2.0)); int _expr16 = idx; @@ -113,8 +112,8 @@ void main(uint3 __local_invocation_id : SV_GroupThreadID) at_1 = (uint)0; } GroupMemoryBarrierWithGroupSync(); - float Foo = (float)0; - bool at = (bool)0; + float Foo = 1.0; + bool at = true; test_msl_packed_vec3_(); float4x2 _expr5 = ((float4x2)global_nested_arrays_of_matrices_4x2_[0][0]); @@ -134,7 +133,5 @@ void main(uint3 __local_invocation_id : SV_GroupThreadID) alignment.Store(12, asuint(4.0)); wg[1] = float(((NagaBufferLength(dummy) - 0) / 8)); at_1 = 2u; - Foo = 1.0; - at = true; return; } diff --git a/tests/out/hlsl/hlsl-keyword.hlsl b/tests/out/hlsl/hlsl-keyword.hlsl index 8602525e2..9259549ab 100644 --- a/tests/out/hlsl/hlsl-keyword.hlsl +++ b/tests/out/hlsl/hlsl-keyword.hlsl @@ -1,8 +1,7 @@ float4 fs_main() : SV_Target0 { - float4 Pass_ = (float4)0; + float4 Pass_ = float4(1.0, 1.0, 1.0, 1.0); - Pass_ = float4(1.0, 1.0, 1.0, 1.0); float4 _expr6 = Pass_; return _expr6; } diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl index 9251396c7..3784864ed 100644 --- a/tests/out/hlsl/interface.hlsl +++ b/tests/out/hlsl/interface.hlsl @@ -87,9 +87,8 @@ void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThr precise float4 vertex_two_structs(Input1_ in1_, Input2_ in2_) : SV_Position { - uint index = (uint)0; + uint index = 2u; - index = 2u; uint _expr8 = index; return float4(float((_NagaConstants.base_vertex + in1_.index)), float((_NagaConstants.base_instance + in2_.index)), float(_expr8), 0.0); } diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 90c6723e2..7074d1d56 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -25,9 +25,8 @@ float4 splat() float2 splat_assignment() { - float2 a = (float2)0; + float2 a = (2.0).xx; - a = (2.0).xx; float2 _expr4 = a; a = (_expr4 + (1.0).xx); float2 _expr8 = a; @@ -153,10 +152,9 @@ void comparison() void assignment() { - int a_1 = (int)0; + int a_1 = 1; int3 vec0_ = (int3)0; - a_1 = 1; int _expr3 = a_1; a_1 = (_expr3 + 1); int _expr6 = a_1; @@ -183,7 +181,6 @@ void assignment() a_1 = (_expr33 + 1); int _expr36 = a_1; a_1 = (_expr36 - 1); - vec0_ = (int3)0; int _expr42 = vec0_.y; vec0_.y = (_expr42 + 1); int _expr46 = vec0_.y; diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl index 7116e803e..91a918283 100644 --- a/tests/out/hlsl/shadow.hlsl +++ b/tests/out/hlsl/shadow.hlsl @@ -88,12 +88,10 @@ Light ConstructLight(float4x4 arg0, float4 arg1, float4 arg2) { float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 { VertexOutput in_ = { fragmentinput_fs_main.proj_position_1, fragmentinput_fs_main.world_normal_1, fragmentinput_fs_main.world_position_1 }; - float3 color = (float3)0; - uint i = (uint)0; + float3 color = c_ambient; + uint i = 0u; float3 normal_1 = normalize(in_.world_normal); - color = c_ambient; - i = 0u; bool loop_init = true; while(true) { if (!loop_init) { @@ -126,12 +124,10 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 float4 fs_main_without_storage(FragmentInput_fs_main_without_storage fragmentinput_fs_main_without_storage) : SV_Target0 { VertexOutput in_1 = { fragmentinput_fs_main_without_storage.proj_position_2, fragmentinput_fs_main_without_storage.world_normal_2, fragmentinput_fs_main_without_storage.world_position_2 }; - float3 color_1 = (float3)0; - uint i_1 = (uint)0; + float3 color_1 = c_ambient; + uint i_1 = 0u; float3 normal_2 = normalize(in_1.world_normal); - color_1 = c_ambient; - i_1 = 0u; bool loop_init_1 = true; while(true) { if (!loop_init_1) { diff --git a/tests/out/ir/access.compact.ron b/tests/out/ir/access.compact.ron index b725765d4..1c0220141 100644 --- a/tests/out/ir/access.compact.ron +++ b/tests/out/ir/access.compact.ron @@ -396,12 +396,12 @@ ( name: Some("idx"), ty: 3, - init: None, + init: Some(1), ), ( name: Some("t"), ty: 16, - init: None, + init: Some(49), ), ], expressions: [ @@ -697,10 +697,6 @@ 41: "l6", }, body: [ - Store( - pointer: 2, - value: 1, - ), Emit(( start: 3, end: 5, @@ -769,10 +765,6 @@ start: 46, end: 49, )), - Store( - pointer: 50, - value: 49, - ), Emit(( start: 51, end: 53, @@ -890,12 +882,12 @@ ( name: Some("idx"), ty: 3, - init: None, + init: Some(1), ), ( name: Some("t"), ty: 20, - init: None, + init: Some(53), ), ], expressions: [ @@ -1245,10 +1237,6 @@ 51: "l7", }, body: [ - Store( - pointer: 2, - value: 1, - ), Emit(( start: 3, end: 5, @@ -1341,10 +1329,6 @@ start: 52, end: 53, )), - Store( - pointer: 54, - value: 53, - ), Emit(( start: 55, end: 57, @@ -1675,7 +1659,7 @@ ( name: Some("foo"), ty: 21, - init: None, + init: Some(2), ), ( name: Some("c2"), @@ -1846,10 +1830,6 @@ 46: "value", }, body: [ - Store( - pointer: 3, - value: 2, - ), Emit(( start: 3, end: 4, @@ -2160,7 +2140,7 @@ ( name: Some("arr"), ty: 28, - init: None, + init: Some(5), ), ], expressions: [ @@ -2194,10 +2174,6 @@ start: 3, end: 5, )), - Store( - pointer: 6, - value: 5, - ), Call( function: 5, arguments: [ diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index e2a7aa946..fcdd3b8b7 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -455,12 +455,12 @@ ( name: Some("idx"), ty: 3, - init: None, + init: Some(1), ), ( name: Some("t"), ty: 16, - init: None, + init: Some(54), ), ], expressions: [ @@ -766,10 +766,6 @@ 46: "l6", }, body: [ - Store( - pointer: 2, - value: 1, - ), Emit(( start: 3, end: 5, @@ -838,10 +834,6 @@ start: 51, end: 54, )), - Store( - pointer: 55, - value: 54, - ), Emit(( start: 56, end: 58, @@ -959,12 +951,12 @@ ( name: Some("idx"), ty: 3, - init: None, + init: Some(1), ), ( name: Some("t"), ty: 21, - init: None, + init: Some(65), ), ], expressions: [ @@ -1338,10 +1330,6 @@ 63: "l7", }, body: [ - Store( - pointer: 2, - value: 1, - ), Emit(( start: 3, end: 5, @@ -1434,10 +1422,6 @@ start: 64, end: 65, )), - Store( - pointer: 66, - value: 65, - ), Emit(( start: 67, end: 69, @@ -1770,7 +1754,7 @@ ( name: Some("foo"), ty: 22, - init: None, + init: Some(2), ), ( name: Some("c2"), @@ -1942,10 +1926,6 @@ 47: "value", }, body: [ - Store( - pointer: 3, - value: 2, - ), Emit(( start: 3, end: 4, @@ -2258,7 +2238,7 @@ ( name: Some("arr"), ty: 32, - init: None, + init: Some(5), ), ], expressions: [ @@ -2292,10 +2272,6 @@ start: 3, end: 5, )), - Store( - pointer: 6, - value: 5, - ), Call( function: 5, arguments: [ diff --git a/tests/out/ir/collatz.compact.ron b/tests/out/ir/collatz.compact.ron index fb8ff825e..7cad54b71 100644 --- a/tests/out/ir/collatz.compact.ron +++ b/tests/out/ir/collatz.compact.ron @@ -82,7 +82,7 @@ ( name: Some("i"), ty: 1, - init: None, + init: Some(3), ), ], expressions: [ @@ -159,10 +159,6 @@ pointer: 2, value: 1, ), - Store( - pointer: 4, - value: 3, - ), Loop( body: [ Emit(( diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron index 615c63850..8146909c1 100644 --- a/tests/out/ir/collatz.ron +++ b/tests/out/ir/collatz.ron @@ -86,7 +86,7 @@ ( name: Some("i"), ty: 1, - init: None, + init: Some(3), ), ], expressions: [ @@ -163,10 +163,6 @@ pointer: 2, value: 1, ), - Store( - pointer: 4, - value: 3, - ), Loop( body: [ Emit(( diff --git a/tests/out/ir/shadow.compact.ron b/tests/out/ir/shadow.compact.ron index 313938997..9ca6799c2 100644 --- a/tests/out/ir/shadow.compact.ron +++ b/tests/out/ir/shadow.compact.ron @@ -356,8 +356,6 @@ Literal(I32(0)), Literal(I32(1)), Literal(I32(2)), - Constant(6), - Constant(8), ], functions: [ ( @@ -558,12 +556,12 @@ ( name: Some("color"), ty: 2, - init: Some(23), + init: Some(20), ), ( name: Some("i"), ty: 3, - init: Some(24), + init: Some(22), ), ], expressions: [ @@ -586,65 +584,67 @@ Constant(10), Constant(12), Constant(1), + Constant(6), LocalVariable(1), + Constant(8), LocalVariable(2), Load( - pointer: 21, + pointer: 23, ), AccessIndex( base: 1, index: 0, ), Access( - base: 23, + base: 25, index: 17, ), Load( - pointer: 24, + pointer: 26, ), Math( fun: Min, - arg: 25, + arg: 27, arg1: Some(13), arg2: None, arg3: None, ), Binary( op: GreaterEqual, - left: 22, - right: 26, - ), - Load( - pointer: 20, + left: 24, + right: 28, ), Load( pointer: 21, ), + Load( + pointer: 23, + ), AccessIndex( base: 4, index: 0, ), Load( - pointer: 21, + pointer: 23, ), Access( - base: 30, - index: 31, + base: 32, + index: 33, ), AccessIndex( - base: 32, + base: 34, index: 0, ), Load( - pointer: 33, + pointer: 35, ), Load( pointer: 3, ), Binary( op: Multiply, - left: 34, - right: 35, + left: 36, + right: 37, ), CallResult(1), Load( @@ -652,7 +652,7 @@ ), Math( fun: Normalize, - arg: 38, + arg: 40, arg1: None, arg2: None, arg3: None, @@ -662,73 +662,73 @@ index: 0, ), Load( - pointer: 21, + pointer: 23, ), Access( - base: 40, - index: 41, + base: 42, + index: 43, ), AccessIndex( - base: 42, + base: 44, index: 1, ), Access( - base: 43, + base: 45, index: 15, ), Load( - pointer: 44, + pointer: 46, ), AccessIndex( base: 4, index: 0, ), Load( - pointer: 21, + pointer: 23, ), Access( - base: 46, - index: 47, + base: 48, + index: 49, ), AccessIndex( - base: 48, + base: 50, index: 1, ), Access( - base: 49, + base: 51, index: 18, ), Load( - pointer: 50, + pointer: 52, ), AccessIndex( base: 4, index: 0, ), Load( - pointer: 21, + pointer: 23, ), Access( - base: 52, - index: 53, + base: 54, + index: 55, ), AccessIndex( - base: 54, + base: 56, index: 1, ), Access( - base: 55, + base: 57, index: 8, ), Load( - pointer: 56, + pointer: 58, ), Compose( ty: 2, components: [ - 45, - 51, - 57, + 47, + 53, + 59, ], ), Access( @@ -736,160 +736,160 @@ index: 16, ), Load( - pointer: 59, + pointer: 61, ), Access( base: 3, index: 7, ), Load( - pointer: 61, + pointer: 63, ), Access( base: 3, index: 10, ), Load( - pointer: 63, + pointer: 65, ), Compose( ty: 2, components: [ - 60, 62, 64, + 66, ], ), Binary( op: Subtract, - left: 58, - right: 65, + left: 60, + right: 67, ), Math( fun: Normalize, - arg: 66, + arg: 68, arg1: None, arg2: None, arg3: None, ), Math( fun: Dot, - arg: 39, - arg1: Some(67), + arg: 41, + arg1: Some(69), arg2: None, arg3: None, ), Math( fun: Max, arg: 19, - arg1: Some(68), + arg1: Some(70), arg2: None, arg3: None, ), Binary( op: Multiply, - left: 37, - right: 69, + left: 39, + right: 71, ), AccessIndex( base: 4, index: 0, ), Load( - pointer: 21, + pointer: 23, ), Access( - base: 71, - index: 72, + base: 73, + index: 74, ), AccessIndex( - base: 73, + base: 75, index: 2, ), Access( - base: 74, + base: 76, index: 6, ), Load( - pointer: 75, + pointer: 77, ), AccessIndex( base: 4, index: 0, ), Load( - pointer: 21, + pointer: 23, ), Access( - base: 77, - index: 78, + base: 79, + index: 80, ), AccessIndex( - base: 79, + base: 81, index: 2, ), Access( - base: 80, + base: 82, index: 9, ), Load( - pointer: 81, + pointer: 83, ), AccessIndex( base: 4, index: 0, ), Load( - pointer: 21, + pointer: 23, ), Access( - base: 83, - index: 84, + base: 85, + index: 86, ), AccessIndex( - base: 85, + base: 87, index: 2, ), Access( - base: 86, + base: 88, index: 11, ), Load( - pointer: 87, + pointer: 89, ), Compose( ty: 2, components: [ - 76, - 82, - 88, + 78, + 84, + 90, ], ), Binary( op: Multiply, - left: 89, - right: 70, + left: 91, + right: 72, ), Binary( op: Add, - left: 28, - right: 90, + left: 30, + right: 92, + ), + Load( + pointer: 23, + ), + Binary( + op: Add, + left: 94, + right: 12, ), Load( pointer: 21, ), - Binary( - op: Add, - left: 92, - right: 12, - ), - Load( - pointer: 20, - ), Compose( ty: 4, components: [ - 94, + 96, 14, ], ), @@ -899,57 +899,57 @@ Loop( body: [ Emit(( - start: 21, - end: 27, + start: 23, + end: 29, )), If( - condition: 27, + condition: 29, accept: [ Break, ], reject: [], ), Emit(( - start: 27, - end: 36, + start: 29, + end: 38, )), Call( function: 1, arguments: [ - 29, - 36, + 31, + 38, ], - result: Some(37), + result: Some(39), ), Emit(( - start: 37, - end: 91, - )), - Store( - pointer: 20, - value: 91, - ), - Continue, - ], - continuing: [ - Emit(( - start: 91, + start: 39, end: 93, )), Store( pointer: 21, value: 93, ), + Continue, + ], + continuing: [ + Emit(( + start: 93, + end: 95, + )), + Store( + pointer: 23, + value: 95, + ), ], break_if: None, ), Emit(( - start: 93, - end: 95, + start: 95, + end: 97, )), Store( pointer: 5, - value: 95, + value: 97, ), Return( value: None, diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron index bfde76d6a..07bf66fcc 100644 --- a/tests/out/ir/shadow.ron +++ b/tests/out/ir/shadow.ron @@ -591,8 +591,6 @@ Literal(I32(0)), Literal(I32(2)), Literal(I32(2)), - Constant(6), - Constant(8), ], functions: [ ( @@ -829,12 +827,12 @@ ( name: Some("color"), ty: 2, - init: Some(39), + init: Some(43), ), ( name: Some("i"), ty: 3, - init: Some(40), + init: Some(45), ), ], expressions: [ @@ -880,65 +878,67 @@ Constant(18), Constant(6), Constant(1), + Constant(6), LocalVariable(1), + Constant(8), LocalVariable(2), Load( - pointer: 44, + pointer: 46, ), AccessIndex( base: 1, index: 0, ), Access( - base: 46, + base: 48, index: 37, ), Load( - pointer: 47, + pointer: 49, ), Math( fun: Min, - arg: 48, + arg: 50, arg1: Some(28), arg2: None, arg3: None, ), Binary( op: GreaterEqual, - left: 45, - right: 49, - ), - Load( - pointer: 43, + left: 47, + right: 51, ), Load( pointer: 44, ), + Load( + pointer: 46, + ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 46, ), Access( - base: 53, - index: 54, + base: 55, + index: 56, ), AccessIndex( - base: 55, + base: 57, index: 0, ), Load( - pointer: 56, + pointer: 58, ), Load( pointer: 3, ), Binary( op: Multiply, - left: 57, - right: 58, + left: 59, + right: 60, ), CallResult(1), Load( @@ -946,7 +946,7 @@ ), Math( fun: Normalize, - arg: 61, + arg: 63, arg1: None, arg2: None, arg3: None, @@ -956,73 +956,73 @@ index: 0, ), Load( - pointer: 44, + pointer: 46, ), Access( - base: 63, - index: 64, + base: 65, + index: 66, ), AccessIndex( - base: 65, + base: 67, index: 1, ), Access( - base: 66, + base: 68, index: 31, ), Load( - pointer: 67, + pointer: 69, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 46, ), Access( - base: 69, - index: 70, + base: 71, + index: 72, ), AccessIndex( - base: 71, + base: 73, index: 1, ), Access( - base: 72, + base: 74, index: 38, ), Load( - pointer: 73, + pointer: 75, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 46, ), Access( - base: 75, - index: 76, + base: 77, + index: 78, ), AccessIndex( - base: 77, + base: 79, index: 1, ), Access( - base: 78, + base: 80, index: 13, ), Load( - pointer: 79, + pointer: 81, ), Compose( ty: 2, components: [ - 68, - 74, - 80, + 70, + 76, + 82, ], ), Access( @@ -1030,160 +1030,160 @@ index: 36, ), Load( - pointer: 82, + pointer: 84, ), Access( base: 3, index: 12, ), Load( - pointer: 84, + pointer: 86, ), Access( base: 3, index: 23, ), Load( - pointer: 86, + pointer: 88, ), Compose( ty: 2, components: [ - 83, 85, 87, + 89, ], ), Binary( op: Subtract, - left: 81, - right: 88, + left: 83, + right: 90, ), Math( fun: Normalize, - arg: 89, + arg: 91, arg1: None, arg2: None, arg3: None, ), Math( fun: Dot, - arg: 62, - arg1: Some(90), + arg: 64, + arg1: Some(92), arg2: None, arg3: None, ), Math( fun: Max, arg: 42, - arg1: Some(91), + arg1: Some(93), arg2: None, arg3: None, ), Binary( op: Multiply, - left: 60, - right: 92, + left: 62, + right: 94, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 46, ), Access( - base: 94, - index: 95, + base: 96, + index: 97, ), AccessIndex( - base: 96, + base: 98, index: 2, ), Access( - base: 97, + base: 99, index: 10, ), Load( - pointer: 98, + pointer: 100, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 46, ), Access( - base: 100, - index: 101, + base: 102, + index: 103, ), AccessIndex( - base: 102, + base: 104, index: 2, ), Access( - base: 103, + base: 105, index: 19, ), Load( - pointer: 104, + pointer: 106, ), AccessIndex( base: 6, index: 0, ), Load( - pointer: 44, + pointer: 46, ), Access( - base: 106, - index: 107, + base: 108, + index: 109, ), AccessIndex( - base: 108, + base: 110, index: 2, ), Access( - base: 109, + base: 111, index: 26, ), Load( - pointer: 110, + pointer: 112, ), Compose( ty: 2, components: [ - 99, - 105, - 111, + 101, + 107, + 113, ], ), Binary( op: Multiply, - left: 112, - right: 93, + left: 114, + right: 95, ), Binary( op: Add, - left: 51, - right: 113, + left: 53, + right: 115, + ), + Load( + pointer: 46, + ), + Binary( + op: Add, + left: 117, + right: 27, ), Load( pointer: 44, ), - Binary( - op: Add, - left: 115, - right: 27, - ), - Load( - pointer: 43, - ), Compose( ty: 4, components: [ - 117, + 119, 30, ], ), @@ -1193,57 +1193,57 @@ Loop( body: [ Emit(( - start: 44, - end: 50, + start: 46, + end: 52, )), If( - condition: 50, + condition: 52, accept: [ Break, ], reject: [], ), Emit(( - start: 50, - end: 59, + start: 52, + end: 61, )), Call( function: 1, arguments: [ - 52, - 59, + 54, + 61, ], - result: Some(60), + result: Some(62), ), Emit(( - start: 60, - end: 114, - )), - Store( - pointer: 43, - value: 114, - ), - Continue, - ], - continuing: [ - Emit(( - start: 114, + start: 62, end: 116, )), Store( pointer: 44, value: 116, ), + Continue, + ], + continuing: [ + Emit(( + start: 116, + end: 118, + )), + Store( + pointer: 46, + value: 118, + ), ], break_if: None, ), Emit(( - start: 116, - end: 118, + start: 118, + end: 120, )), Store( pointer: 7, - value: 118, + value: 120, ), Return( value: None, diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index c35139a8c..3d57ebd7c 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -61,9 +61,8 @@ struct type_22 { void test_matrix_within_struct_accesses( constant Baz& baz ) { - int idx = {}; - Baz t = {}; - idx = 1; + int idx = 1; + Baz t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; int _e3 = idx; idx = _e3 - 1; metal::float3x2 l0_ = baz.m; @@ -78,7 +77,6 @@ void test_matrix_within_struct_accesses( int _e36 = idx; int _e38 = idx; float l6_ = baz.m[_e36][_e38]; - t = Baz {metal::float3x2(metal::float2(1.0), metal::float2(2.0), metal::float2(3.0))}; int _e51 = idx; idx = _e51 + 1; t.m = metal::float3x2(metal::float2(6.0), metal::float2(5.0), metal::float2(4.0)); @@ -99,9 +97,8 @@ void test_matrix_within_struct_accesses( void test_matrix_within_array_within_struct_accesses( constant MatCx2InArray& nested_mat_cx2_ ) { - int idx_1 = {}; - MatCx2InArray t_1 = {}; - idx_1 = 1; + int idx_1 = 1; + MatCx2InArray t_1 = MatCx2InArray {type_14 {}}; int _e3 = idx_1; idx_1 = _e3 - 1; type_14 l0_1 = nested_mat_cx2_.am; @@ -117,7 +114,6 @@ void test_matrix_within_array_within_struct_accesses( int _e46 = idx_1; int _e48 = idx_1; float l7_ = nested_mat_cx2_.am.inner[0][_e46][_e48]; - t_1 = MatCx2InArray {type_14 {}}; int _e55 = idx_1; idx_1 = _e55 + 1; t_1.am = type_14 {}; @@ -176,9 +172,8 @@ vertex foo_vertOutput foo_vert( , constant MatCx2InArray& nested_mat_cx2_ [[buffer(3)]] , constant _mslBufferSizes& _buffer_sizes [[buffer(24)]] ) { - float foo = {}; + float foo = 0.0; type_20 c2_ = {}; - foo = 0.0; float baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(baz); @@ -222,8 +217,7 @@ kernel void assign_through_ptr( val = {}; } metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - type_22 arr = {}; - arr = type_22 {metal::float4(6.0), metal::float4(7.0)}; + type_22 arr = type_22 {metal::float4(6.0), metal::float4(7.0)}; assign_through_ptr_fn(val); assign_array_through_ptr_fn(arr); return; diff --git a/tests/out/msl/binding-arrays.msl b/tests/out/msl/binding-arrays.msl index f7597b5c7..f3548c9e7 100644 --- a/tests/out/msl/binding-arrays.msl +++ b/tests/out/msl/binding-arrays.msl @@ -36,16 +36,12 @@ fragment main_Output main_( , constant UniformIndex& uni [[user(fake0)]] ) { const FragmentIn fragment_in = { varyings.index }; - uint u1_ = {}; - metal::uint2 u2_ = {}; - float v1_ = {}; - metal::float4 v4_ = {}; + uint u1_ = 0u; + metal::uint2 u2_ = metal::uint2(0u); + float v1_ = 0.0; + metal::float4 v4_ = metal::float4(0.0); uint uniform_index = uni.index; uint non_uniform_index = fragment_in.index; - u1_ = 0u; - u2_ = metal::uint2(0u); - v1_ = 0.0; - v4_ = metal::float4(0.0); metal::float2 uv = metal::float2(0.0); metal::int2 pix = metal::int2(0); metal::uint2 _e22 = u2_; diff --git a/tests/out/msl/bitcast.msl b/tests/out/msl/bitcast.msl index a0cf093b7..ca8bc329b 100644 --- a/tests/out/msl/bitcast.msl +++ b/tests/out/msl/bitcast.msl @@ -7,24 +7,15 @@ using metal::uint; kernel void main_( ) { - metal::int2 i2_ = {}; - metal::int3 i3_ = {}; - metal::int4 i4_ = {}; - metal::uint2 u2_ = {}; - metal::uint3 u3_ = {}; - metal::uint4 u4_ = {}; - metal::float2 f2_ = {}; - metal::float3 f3_ = {}; - metal::float4 f4_ = {}; - i2_ = metal::int2(0); - i3_ = metal::int3(0); - i4_ = metal::int4(0); - u2_ = metal::uint2(0u); - u3_ = metal::uint3(0u); - u4_ = metal::uint4(0u); - f2_ = metal::float2(0.0); - f3_ = metal::float3(0.0); - f4_ = metal::float4(0.0); + metal::int2 i2_ = metal::int2(0); + metal::int3 i3_ = metal::int3(0); + metal::int4 i4_ = metal::int4(0); + metal::uint2 u2_ = metal::uint2(0u); + metal::uint3 u3_ = metal::uint3(0u); + metal::uint4 u4_ = metal::uint4(0u); + metal::float2 f2_ = metal::float2(0.0); + metal::float3 f3_ = metal::float3(0.0); + metal::float4 f4_ = metal::float4(0.0); metal::int2 _e27 = i2_; u2_ = as_type(_e27); metal::int3 _e29 = i3_; diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl index 2a00b6b84..7d73568b7 100644 --- a/tests/out/msl/bits.msl +++ b/tests/out/msl/bits.msl @@ -7,26 +7,16 @@ using metal::uint; kernel void main_( ) { - int i = {}; - metal::int2 i2_ = {}; - metal::int3 i3_ = {}; - metal::int4 i4_ = {}; - uint u = {}; - metal::uint2 u2_ = {}; - metal::uint3 u3_ = {}; - metal::uint4 u4_ = {}; - metal::float2 f2_ = {}; - metal::float4 f4_ = {}; - i = 0; - i2_ = metal::int2(0); - i3_ = metal::int3(0); - i4_ = metal::int4(0); - u = 0u; - u2_ = metal::uint2(0u); - u3_ = metal::uint3(0u); - u4_ = metal::uint4(0u); - f2_ = metal::float2(0.0); - f4_ = metal::float4(0.0); + int i = 0; + metal::int2 i2_ = metal::int2(0); + metal::int3 i3_ = metal::int3(0); + metal::int4 i4_ = metal::int4(0); + uint u = 0u; + metal::uint2 u2_ = metal::uint2(0u); + metal::uint3 u3_ = metal::uint3(0u); + metal::uint4 u4_ = metal::uint4(0u); + metal::float2 f2_ = metal::float2(0.0); + metal::float4 f4_ = metal::float4(0.0); metal::float4 _e28 = f4_; u = metal::pack_float_to_snorm4x8(_e28); metal::float4 _e30 = f4_; diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index 1a81aaf68..de9d7186a 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -39,14 +39,14 @@ kernel void main_( ) { metal::float2 vPos = {}; metal::float2 vVel = {}; - metal::float2 cMass = {}; - metal::float2 cVel = {}; - metal::float2 colVel = {}; - int cMassCount = {}; - int cVelCount = {}; + metal::float2 cMass = metal::float2(0.0, 0.0); + metal::float2 cVel = metal::float2(0.0, 0.0); + metal::float2 colVel = metal::float2(0.0, 0.0); + int cMassCount = 0; + int cVelCount = 0; metal::float2 pos = {}; metal::float2 vel = {}; - uint i = {}; + uint i = 0u; uint index = global_invocation_id.x; if (index >= NUM_PARTICLES) { return; @@ -55,12 +55,6 @@ kernel void main_( vPos = _e8; metal::float2 _e14 = particlesSrc.particles[index].vel; vVel = _e14; - cMass = metal::float2(0.0, 0.0); - cVel = metal::float2(0.0, 0.0); - colVel = metal::float2(0.0, 0.0); - cMassCount = 0; - cVelCount = 0; - i = 0u; bool loop_init = true; while(true) { if (!loop_init) { diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index 88f9521a2..3c8bcf172 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -17,9 +17,8 @@ uint collatz_iterations( uint n_base ) { uint n = {}; - uint i = {}; + uint i = 0u; n = n_base; - i = 0u; while(true) { uint _e4 = n; if (_e4 > 1u) { diff --git a/tests/out/msl/dualsource.msl b/tests/out/msl/dualsource.msl index 92b1909f8..871957c81 100644 --- a/tests/out/msl/dualsource.msl +++ b/tests/out/msl/dualsource.msl @@ -18,10 +18,8 @@ struct main_Output { fragment main_Output main_( metal::float4 position [[position]] ) { - metal::float4 color = {}; - metal::float4 mask = {}; - color = metal::float4(0.4, 0.3, 0.2, 0.1); - mask = metal::float4(0.9, 0.8, 0.7, 0.6); + metal::float4 color = metal::float4(0.4, 0.3, 0.2, 0.1); + metal::float4 mask = metal::float4(0.9, 0.8, 0.7, 0.6); metal::float4 _e13 = color; metal::float4 _e14 = mask; const auto _tmp = FragmentOutput {_e13, _e14}; diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 9e964d6c1..9d09db805 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -42,9 +42,8 @@ void test_msl_packed_vec3_as_arg( void test_msl_packed_vec3_( device FooStruct& alignment ) { - int idx = {}; + int idx = 1; alignment.v3_ = metal::float3(1.0); - idx = 1; alignment.v3_[0] = 1.0; alignment.v3_[0] = 2.0; int _e16 = idx; @@ -77,8 +76,8 @@ kernel void main_( metal::atomic_store_explicit(&at_1, 0, metal::memory_order_relaxed); } metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); - float Foo = {}; - bool at = {}; + float Foo = 1.0; + bool at = true; test_msl_packed_vec3_(alignment); metal::float4x2 _e5 = global_nested_arrays_of_matrices_4x2_.inner[0].inner[0]; metal::float4 _e10 = global_nested_arrays_of_matrices_2x4_.inner[0].inner[0][0]; @@ -97,7 +96,5 @@ kernel void main_( alignment.v1_ = 4.0; wg.inner[1] = static_cast(1 + (_buffer_sizes.size3 - 0 - 8) / 8); metal::atomic_store_explicit(&at_1, 2u, metal::memory_order_relaxed); - Foo = 1.0; - at = true; return; } diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl index c9b93d86a..d03912fab 100644 --- a/tests/out/msl/interface.msl +++ b/tests/out/msl/interface.msl @@ -97,8 +97,7 @@ vertex vertex_two_structsOutput vertex_two_structs( ) { const Input1_ in1_ = { index_1 }; const Input2_ in2_ = { index_2 }; - uint index = {}; - index = 2u; + uint index = 2u; uint _e8 = index; return vertex_two_structsOutput { metal::float4(static_cast(in1_.index), static_cast(in2_.index), static_cast(_e8), 0.0), 1.0 }; } diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 869f08673..2a7463646 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -31,8 +31,7 @@ metal::float4 splat( metal::float2 splat_assignment( ) { - metal::float2 a = {}; - a = metal::float2(2.0); + metal::float2 a = metal::float2(2.0); metal::float2 _e4 = a; a = _e4 + metal::float2(1.0); metal::float2 _e8 = a; @@ -159,9 +158,8 @@ void comparison( void assignment( ) { - int a_1 = {}; - metal::int3 vec0_ = {}; - a_1 = 1; + int a_1 = 1; + metal::int3 vec0_ = metal::int3 {}; int _e3 = a_1; a_1 = _e3 + 1; int _e6 = a_1; @@ -188,7 +186,6 @@ void assignment( a_1 = _e33 + 1; int _e36 = a_1; a_1 = _e36 - 1; - vec0_ = metal::int3 {}; int _e42 = vec0_.y; vec0_.y = _e42 + 1; int _e46 = vec0_.y; diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index f6a4fe5d6..bb7c12671 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -42,8 +42,7 @@ metal::float4 mock_function( threadgroup type_5& in_workgroup, thread type_6& in_private ) { - type_9 in_function = {}; - in_function = type_9 {metal::float4(0.707, 0.0, 0.0, 1.0), metal::float4(0.0, 0.707, 0.0, 1.0)}; + type_9 in_function = type_9 {metal::float4(0.707, 0.0, 0.0, 1.0), metal::float4(0.0, 0.707, 0.0, 1.0)}; metal::float4 _e18 = in_storage.a.inner[i]; metal::float4 _e22 = in_uniform.a.inner[i]; metal::float4 _e25 = (uint(l) < image_2d_array.get_num_mip_levels() && uint(i) < image_2d_array.get_array_size() && metal::all(metal::uint2(c) < metal::uint2(image_2d_array.get_width(l), image_2d_array.get_height(l))) ? image_2d_array.read(metal::uint2(c), i, l): DefaultConstructible()); diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 53f320344..15dd042b8 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -97,11 +97,9 @@ fragment fs_mainOutput fs_main( , constant _mslBufferSizes& _buffer_sizes [[user(fake0)]] ) { const VertexOutput in = { proj_position, varyings_1.world_normal, varyings_1.world_position }; - metal::float3 color = {}; - uint i = {}; + metal::float3 color = c_ambient; + uint i = 0u; metal::float3 normal_1 = metal::normalize(in.world_normal); - color = c_ambient; - i = 0u; bool loop_init = true; while(true) { if (!loop_init) { @@ -149,11 +147,9 @@ fragment fs_main_without_storageOutput fs_main_without_storage( , metal::sampler sampler_shadow [[user(fake0)]] ) { const VertexOutput in_1 = { proj_position_1, varyings_2.world_normal, varyings_2.world_position }; - metal::float3 color_1 = {}; - uint i_1 = {}; + metal::float3 color_1 = c_ambient; + uint i_1 = 0u; metal::float3 normal_2 = metal::normalize(in_1.world_normal); - color_1 = c_ambient; - i_1 = 0u; bool loop_init_1 = true; while(true) { if (!loop_init_1) { diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index d5b6524ee..40476395c 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 322 +; Bound: 313 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %232 "foo_vert" %227 %230 -OpEntryPoint Fragment %282 "foo_frag" %281 -OpEntryPoint GLCompute %302 "assign_through_ptr" %305 -OpExecutionMode %282 OriginUpperLeft -OpExecutionMode %302 LocalSize 1 1 1 +OpEntryPoint Vertex %220 "foo_vert" %215 %218 +OpEntryPoint Fragment %274 "foo_frag" %273 +OpEntryPoint GLCompute %292 "assign_through_ptr" %299 +OpExecutionMode %274 OriginUpperLeft +OpExecutionMode %292 LocalSize 1 1 1 OpMemberName %6 0 "a" OpMemberName %6 1 "b" OpMemberName %6 2 "c" @@ -34,27 +34,27 @@ OpName %44 "baz" OpName %47 "qux" OpName %50 "nested_mat_cx2" OpName %53 "val" -OpName %54 "idx" -OpName %57 "t" -OpName %61 "test_matrix_within_struct_accesses" -OpName %132 "idx" -OpName %133 "t" -OpName %137 "test_matrix_within_array_within_struct_accesses" -OpName %195 "foo" -OpName %196 "read_from_private" -OpName %201 "a" -OpName %202 "test_arr_as_arg" -OpName %208 "p" -OpName %209 "assign_through_ptr_fn" -OpName %214 "foo" -OpName %215 "assign_array_through_ptr_fn" -OpName %221 "foo" -OpName %223 "c2" -OpName %227 "vi" -OpName %232 "foo_vert" -OpName %282 "foo_frag" -OpName %299 "arr" -OpName %302 "assign_through_ptr" +OpName %55 "test_matrix_within_struct_accesses" +OpName %83 "idx" +OpName %85 "t" +OpName %131 "test_matrix_within_array_within_struct_accesses" +OpName %141 "idx" +OpName %142 "t" +OpName %188 "foo" +OpName %189 "read_from_private" +OpName %194 "a" +OpName %195 "test_arr_as_arg" +OpName %201 "p" +OpName %202 "assign_through_ptr_fn" +OpName %207 "foo" +OpName %208 "assign_array_through_ptr_fn" +OpName %215 "vi" +OpName %220 "foo_vert" +OpName %232 "foo" +OpName %233 "c2" +OpName %274 "foo_frag" +OpName %292 "assign_through_ptr" +OpName %296 "arr" OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpMemberDecorate %6 2 Offset 28 @@ -99,10 +99,10 @@ OpDecorate %50 DescriptorSet 0 OpDecorate %50 Binding 3 OpDecorate %51 Block OpMemberDecorate %51 0 Offset 0 -OpDecorate %227 BuiltIn VertexIndex -OpDecorate %230 BuiltIn Position -OpDecorate %281 Location 0 -OpDecorate %305 BuiltIn LocalInvocationId +OpDecorate %215 BuiltIn VertexIndex +OpDecorate %218 BuiltIn Position +OpDecorate %273 Location 0 +OpDecorate %299 BuiltIn LocalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeVector %3 3 @@ -155,341 +155,326 @@ OpDecorate %305 BuiltIn LocalInvocationId %52 = OpTypePointer Uniform %51 %50 = OpVariable %52 Uniform %53 = OpVariable %33 Workgroup -%55 = OpTypePointer Function %5 -%56 = OpConstantNull %5 -%58 = OpTypePointer Function %22 -%59 = OpConstantNull %22 -%62 = OpTypeFunction %2 -%63 = OpTypePointer Uniform %22 -%65 = OpConstant %5 1 -%66 = OpConstant %10 1.0 -%67 = OpConstant %10 2.0 -%68 = OpConstant %10 3.0 -%69 = OpConstant %10 6.0 +%56 = OpTypeFunction %2 +%57 = OpTypePointer Uniform %22 +%59 = OpConstant %5 1 +%60 = OpConstant %10 1.0 +%61 = OpConstantComposite %12 %60 %60 +%62 = OpConstant %10 2.0 +%63 = OpConstantComposite %12 %62 %62 +%64 = OpConstant %10 3.0 +%65 = OpConstantComposite %12 %64 %64 +%66 = OpConstantComposite %21 %61 %63 %65 +%67 = OpConstantComposite %22 %66 +%68 = OpConstant %10 6.0 +%69 = OpConstantComposite %12 %68 %68 %70 = OpConstant %10 5.0 -%71 = OpConstant %10 4.0 -%72 = OpConstant %10 9.0 -%73 = OpConstant %10 90.0 -%74 = OpConstant %10 10.0 -%75 = OpConstant %10 20.0 -%76 = OpConstant %10 30.0 -%77 = OpConstant %10 40.0 -%81 = OpTypePointer Uniform %21 -%84 = OpTypePointer Uniform %12 -%90 = OpTypePointer Uniform %10 -%91 = OpConstant %3 1 -%111 = OpTypePointer Function %21 +%71 = OpConstantComposite %12 %70 %70 +%72 = OpConstant %10 4.0 +%73 = OpConstantComposite %12 %72 %72 +%74 = OpConstantComposite %21 %69 %71 %73 +%75 = OpConstant %10 9.0 +%76 = OpConstantComposite %12 %75 %75 +%77 = OpConstant %10 90.0 +%78 = OpConstantComposite %12 %77 %77 +%79 = OpConstant %10 10.0 +%80 = OpConstant %10 20.0 +%81 = OpConstant %10 30.0 +%82 = OpConstant %10 40.0 +%84 = OpTypePointer Function %5 +%86 = OpTypePointer Function %22 +%90 = OpTypePointer Uniform %21 +%93 = OpTypePointer Uniform %12 +%99 = OpTypePointer Uniform %10 +%100 = OpConstant %3 1 +%115 = OpTypePointer Function %21 %117 = OpTypePointer Function %12 -%123 = OpTypePointer Function %10 -%134 = OpTypePointer Function %26 -%135 = OpConstantNull %26 -%138 = OpTypePointer Uniform %26 -%140 = OpConstantNull %25 -%141 = OpConstant %10 8.0 -%142 = OpConstant %10 7.0 -%146 = OpTypePointer Uniform %25 -%149 = OpTypePointer Uniform %24 +%121 = OpTypePointer Function %10 +%132 = OpTypePointer Uniform %26 +%134 = OpConstantNull %25 +%135 = OpConstantComposite %26 %134 +%136 = OpConstant %10 8.0 +%137 = OpConstantComposite %12 %136 %136 +%138 = OpConstant %10 7.0 +%139 = OpConstantComposite %12 %138 %138 +%140 = OpConstantComposite %24 %137 %139 %69 %71 +%143 = OpTypePointer Function %26 +%147 = OpTypePointer Uniform %25 +%150 = OpTypePointer Uniform %24 %172 = OpTypePointer Function %25 %174 = OpTypePointer Function %24 -%197 = OpTypeFunction %10 %27 -%203 = OpTypeFunction %10 %29 -%210 = OpTypeFunction %2 %33 -%211 = OpConstant %3 42 -%216 = OpTypeFunction %2 %35 -%222 = OpConstantNull %10 -%224 = OpTypePointer Function %32 -%225 = OpConstantNull %32 -%228 = OpTypePointer Input %3 -%227 = OpVariable %228 Input -%231 = OpTypePointer Output %31 -%230 = OpVariable %231 Output -%234 = OpTypePointer StorageBuffer %23 -%237 = OpConstant %10 0.0 -%238 = OpConstant %3 3 -%239 = OpConstant %5 3 -%240 = OpConstant %5 4 -%241 = OpConstant %5 5 -%242 = OpConstant %5 42 -%243 = OpConstantNull %29 -%248 = OpTypePointer StorageBuffer %8 -%251 = OpTypePointer StorageBuffer %18 -%252 = OpConstant %3 4 -%255 = OpTypePointer StorageBuffer %9 -%256 = OpTypePointer StorageBuffer %10 -%259 = OpTypePointer StorageBuffer %19 -%262 = OpTypePointer StorageBuffer %7 -%263 = OpTypePointer StorageBuffer %5 -%275 = OpTypeVector %5 4 -%281 = OpVariable %231 Output +%190 = OpTypeFunction %10 %27 +%196 = OpTypeFunction %10 %29 +%203 = OpTypeFunction %2 %33 +%204 = OpConstant %3 42 +%209 = OpTypeFunction %2 %35 +%210 = OpConstantComposite %31 %60 %60 %60 %60 +%211 = OpConstantComposite %31 %62 %62 %62 %62 +%212 = OpConstantComposite %34 %210 %211 +%216 = OpTypePointer Input %3 +%215 = OpVariable %216 Input +%219 = OpTypePointer Output %31 +%218 = OpVariable %219 Output +%222 = OpTypePointer StorageBuffer %23 +%225 = OpConstant %10 0.0 +%226 = OpConstant %3 3 +%227 = OpConstant %5 3 +%228 = OpConstant %5 4 +%229 = OpConstant %5 5 +%230 = OpConstant %5 42 +%231 = OpConstantNull %29 +%234 = OpTypePointer Function %32 +%235 = OpConstantNull %32 +%240 = OpTypePointer StorageBuffer %8 +%243 = OpTypePointer StorageBuffer %18 +%244 = OpConstant %3 4 +%247 = OpTypePointer StorageBuffer %9 +%248 = OpTypePointer StorageBuffer %10 +%251 = OpTypePointer StorageBuffer %19 +%254 = OpTypePointer StorageBuffer %7 +%255 = OpTypePointer StorageBuffer %5 +%267 = OpTypeVector %5 4 +%273 = OpVariable %219 Output +%276 = OpConstantComposite %9 %225 %225 %225 +%277 = OpConstantComposite %9 %60 %60 %60 +%278 = OpConstantComposite %9 %62 %62 %62 +%279 = OpConstantComposite %9 %64 %64 %64 +%280 = OpConstantComposite %8 %276 %277 %278 %279 +%281 = OpConstantComposite %17 %36 %36 +%282 = OpConstantComposite %17 %100 %100 +%283 = OpConstantComposite %18 %281 %282 %284 = OpConstantNull %23 -%300 = OpConstantNull %34 -%304 = OpConstantNull %3 -%306 = OpTypePointer Input %4 -%305 = OpVariable %306 Input -%308 = OpConstantNull %4 -%310 = OpTypeBool -%309 = OpTypeVector %310 3 -%315 = OpConstant %3 264 -%61 = OpFunction %2 None %62 -%60 = OpLabel -%54 = OpVariable %55 Function %56 -%57 = OpVariable %58 Function %59 -%64 = OpAccessChain %63 %44 %36 -OpBranch %78 -%78 = OpLabel -OpStore %54 %65 -%79 = OpLoad %5 %54 -%80 = OpISub %5 %79 %65 -OpStore %54 %80 -%82 = OpAccessChain %81 %64 %36 -%83 = OpLoad %21 %82 -%85 = OpAccessChain %84 %64 %36 %36 -%86 = OpLoad %12 %85 -%87 = OpLoad %5 %54 -%88 = OpAccessChain %84 %64 %36 %87 -%89 = OpLoad %12 %88 -%92 = OpAccessChain %90 %64 %36 %36 %91 -%93 = OpLoad %10 %92 -%94 = OpLoad %5 %54 -%95 = OpAccessChain %90 %64 %36 %36 %94 -%96 = OpLoad %10 %95 -%97 = OpLoad %5 %54 -%98 = OpAccessChain %90 %64 %36 %97 %91 -%99 = OpLoad %10 %98 -%100 = OpLoad %5 %54 -%101 = OpLoad %5 %54 -%102 = OpAccessChain %90 %64 %36 %100 %101 -%103 = OpLoad %10 %102 -%104 = OpCompositeConstruct %12 %66 %66 -%105 = OpCompositeConstruct %12 %67 %67 -%106 = OpCompositeConstruct %12 %68 %68 -%107 = OpCompositeConstruct %21 %104 %105 %106 -%108 = OpCompositeConstruct %22 %107 -OpStore %57 %108 -%109 = OpLoad %5 %54 -%110 = OpIAdd %5 %109 %65 -OpStore %54 %110 -%112 = OpCompositeConstruct %12 %69 %69 -%113 = OpCompositeConstruct %12 %70 %70 -%114 = OpCompositeConstruct %12 %71 %71 -%115 = OpCompositeConstruct %21 %112 %113 %114 -%116 = OpAccessChain %111 %57 %36 -OpStore %116 %115 -%118 = OpCompositeConstruct %12 %72 %72 -%119 = OpAccessChain %117 %57 %36 %36 -OpStore %119 %118 -%120 = OpLoad %5 %54 -%121 = OpCompositeConstruct %12 %73 %73 -%122 = OpAccessChain %117 %57 %36 %120 -OpStore %122 %121 -%124 = OpAccessChain %123 %57 %36 %36 %91 -OpStore %124 %74 -%125 = OpLoad %5 %54 -%126 = OpAccessChain %123 %57 %36 %36 %125 -OpStore %126 %75 -%127 = OpLoad %5 %54 -%128 = OpAccessChain %123 %57 %36 %127 %91 -OpStore %128 %76 -%129 = OpLoad %5 %54 -%130 = OpLoad %5 %54 -%131 = OpAccessChain %123 %57 %36 %129 %130 -OpStore %131 %77 +%285 = OpConstantComposite %31 %225 %225 %225 %225 +%293 = OpConstantComposite %31 %68 %68 %68 %68 +%294 = OpConstantComposite %31 %138 %138 %138 %138 +%295 = OpConstantComposite %34 %293 %294 +%298 = OpConstantNull %3 +%300 = OpTypePointer Input %4 +%299 = OpVariable %300 Input +%302 = OpConstantNull %4 +%304 = OpTypeBool +%303 = OpTypeVector %304 3 +%309 = OpConstant %3 264 +%55 = OpFunction %2 None %56 +%54 = OpLabel +%83 = OpVariable %84 Function %59 +%85 = OpVariable %86 Function %67 +%58 = OpAccessChain %57 %44 %36 +OpBranch %87 +%87 = OpLabel +%88 = OpLoad %5 %83 +%89 = OpISub %5 %88 %59 +OpStore %83 %89 +%91 = OpAccessChain %90 %58 %36 +%92 = OpLoad %21 %91 +%94 = OpAccessChain %93 %58 %36 %36 +%95 = OpLoad %12 %94 +%96 = OpLoad %5 %83 +%97 = OpAccessChain %93 %58 %36 %96 +%98 = OpLoad %12 %97 +%101 = OpAccessChain %99 %58 %36 %36 %100 +%102 = OpLoad %10 %101 +%103 = OpLoad %5 %83 +%104 = OpAccessChain %99 %58 %36 %36 %103 +%105 = OpLoad %10 %104 +%106 = OpLoad %5 %83 +%107 = OpAccessChain %99 %58 %36 %106 %100 +%108 = OpLoad %10 %107 +%109 = OpLoad %5 %83 +%110 = OpLoad %5 %83 +%111 = OpAccessChain %99 %58 %36 %109 %110 +%112 = OpLoad %10 %111 +%113 = OpLoad %5 %83 +%114 = OpIAdd %5 %113 %59 +OpStore %83 %114 +%116 = OpAccessChain %115 %85 %36 +OpStore %116 %74 +%118 = OpAccessChain %117 %85 %36 %36 +OpStore %118 %76 +%119 = OpLoad %5 %83 +%120 = OpAccessChain %117 %85 %36 %119 +OpStore %120 %78 +%122 = OpAccessChain %121 %85 %36 %36 %100 +OpStore %122 %79 +%123 = OpLoad %5 %83 +%124 = OpAccessChain %121 %85 %36 %36 %123 +OpStore %124 %80 +%125 = OpLoad %5 %83 +%126 = OpAccessChain %121 %85 %36 %125 %100 +OpStore %126 %81 +%127 = OpLoad %5 %83 +%128 = OpLoad %5 %83 +%129 = OpAccessChain %121 %85 %36 %127 %128 +OpStore %129 %82 OpReturn OpFunctionEnd -%137 = OpFunction %2 None %62 -%136 = OpLabel -%132 = OpVariable %55 Function %56 -%133 = OpVariable %134 Function %135 -%139 = OpAccessChain %138 %50 %36 -OpBranch %143 -%143 = OpLabel -OpStore %132 %65 -%144 = OpLoad %5 %132 -%145 = OpISub %5 %144 %65 -OpStore %132 %145 -%147 = OpAccessChain %146 %139 %36 -%148 = OpLoad %25 %147 -%150 = OpAccessChain %149 %139 %36 %36 -%151 = OpLoad %24 %150 -%152 = OpAccessChain %84 %139 %36 %36 %36 -%153 = OpLoad %12 %152 -%154 = OpLoad %5 %132 -%155 = OpAccessChain %84 %139 %36 %36 %154 -%156 = OpLoad %12 %155 -%157 = OpAccessChain %90 %139 %36 %36 %36 %91 -%158 = OpLoad %10 %157 -%159 = OpLoad %5 %132 -%160 = OpAccessChain %90 %139 %36 %36 %36 %159 -%161 = OpLoad %10 %160 -%162 = OpLoad %5 %132 -%163 = OpAccessChain %90 %139 %36 %36 %162 %91 -%164 = OpLoad %10 %163 -%165 = OpLoad %5 %132 -%166 = OpLoad %5 %132 -%167 = OpAccessChain %90 %139 %36 %36 %165 %166 -%168 = OpLoad %10 %167 -%169 = OpCompositeConstruct %26 %140 -OpStore %133 %169 -%170 = OpLoad %5 %132 -%171 = OpIAdd %5 %170 %65 -OpStore %132 %171 -%173 = OpAccessChain %172 %133 %36 -OpStore %173 %140 -%175 = OpCompositeConstruct %12 %141 %141 -%176 = OpCompositeConstruct %12 %142 %142 -%177 = OpCompositeConstruct %12 %69 %69 -%178 = OpCompositeConstruct %12 %70 %70 -%179 = OpCompositeConstruct %24 %175 %176 %177 %178 -%180 = OpAccessChain %174 %133 %36 %36 -OpStore %180 %179 -%181 = OpCompositeConstruct %12 %72 %72 -%182 = OpAccessChain %117 %133 %36 %36 %36 -OpStore %182 %181 -%183 = OpLoad %5 %132 -%184 = OpCompositeConstruct %12 %73 %73 -%185 = OpAccessChain %117 %133 %36 %36 %183 -OpStore %185 %184 -%186 = OpAccessChain %123 %133 %36 %36 %36 %91 -OpStore %186 %74 -%187 = OpLoad %5 %132 -%188 = OpAccessChain %123 %133 %36 %36 %36 %187 -OpStore %188 %75 -%189 = OpLoad %5 %132 -%190 = OpAccessChain %123 %133 %36 %36 %189 %91 -OpStore %190 %76 -%191 = OpLoad %5 %132 -%192 = OpLoad %5 %132 -%193 = OpAccessChain %123 %133 %36 %36 %191 %192 -OpStore %193 %77 +%131 = OpFunction %2 None %56 +%130 = OpLabel +%141 = OpVariable %84 Function %59 +%142 = OpVariable %143 Function %135 +%133 = OpAccessChain %132 %50 %36 +OpBranch %144 +%144 = OpLabel +%145 = OpLoad %5 %141 +%146 = OpISub %5 %145 %59 +OpStore %141 %146 +%148 = OpAccessChain %147 %133 %36 +%149 = OpLoad %25 %148 +%151 = OpAccessChain %150 %133 %36 %36 +%152 = OpLoad %24 %151 +%153 = OpAccessChain %93 %133 %36 %36 %36 +%154 = OpLoad %12 %153 +%155 = OpLoad %5 %141 +%156 = OpAccessChain %93 %133 %36 %36 %155 +%157 = OpLoad %12 %156 +%158 = OpAccessChain %99 %133 %36 %36 %36 %100 +%159 = OpLoad %10 %158 +%160 = OpLoad %5 %141 +%161 = OpAccessChain %99 %133 %36 %36 %36 %160 +%162 = OpLoad %10 %161 +%163 = OpLoad %5 %141 +%164 = OpAccessChain %99 %133 %36 %36 %163 %100 +%165 = OpLoad %10 %164 +%166 = OpLoad %5 %141 +%167 = OpLoad %5 %141 +%168 = OpAccessChain %99 %133 %36 %36 %166 %167 +%169 = OpLoad %10 %168 +%170 = OpLoad %5 %141 +%171 = OpIAdd %5 %170 %59 +OpStore %141 %171 +%173 = OpAccessChain %172 %142 %36 +OpStore %173 %134 +%175 = OpAccessChain %174 %142 %36 %36 +OpStore %175 %140 +%176 = OpAccessChain %117 %142 %36 %36 %36 +OpStore %176 %76 +%177 = OpLoad %5 %141 +%178 = OpAccessChain %117 %142 %36 %36 %177 +OpStore %178 %78 +%179 = OpAccessChain %121 %142 %36 %36 %36 %100 +OpStore %179 %79 +%180 = OpLoad %5 %141 +%181 = OpAccessChain %121 %142 %36 %36 %36 %180 +OpStore %181 %80 +%182 = OpLoad %5 %141 +%183 = OpAccessChain %121 %142 %36 %36 %182 %100 +OpStore %183 %81 +%184 = OpLoad %5 %141 +%185 = OpLoad %5 %141 +%186 = OpAccessChain %121 %142 %36 %36 %184 %185 +OpStore %186 %82 OpReturn OpFunctionEnd -%196 = OpFunction %10 None %197 -%195 = OpFunctionParameter %27 -%194 = OpLabel -OpBranch %198 -%198 = OpLabel -%199 = OpLoad %10 %195 +%189 = OpFunction %10 None %190 +%188 = OpFunctionParameter %27 +%187 = OpLabel +OpBranch %191 +%191 = OpLabel +%192 = OpLoad %10 %188 +OpReturnValue %192 +OpFunctionEnd +%195 = OpFunction %10 None %196 +%194 = OpFunctionParameter %29 +%193 = OpLabel +OpBranch %197 +%197 = OpLabel +%198 = OpCompositeExtract %28 %194 4 +%199 = OpCompositeExtract %10 %198 9 OpReturnValue %199 OpFunctionEnd -%202 = OpFunction %10 None %203 -%201 = OpFunctionParameter %29 +%202 = OpFunction %2 None %203 +%201 = OpFunctionParameter %33 %200 = OpLabel -OpBranch %204 -%204 = OpLabel -%205 = OpCompositeExtract %28 %201 4 -%206 = OpCompositeExtract %10 %205 9 -OpReturnValue %206 -OpFunctionEnd -%209 = OpFunction %2 None %210 -%208 = OpFunctionParameter %33 -%207 = OpLabel -OpBranch %212 -%212 = OpLabel -OpStore %208 %211 +OpBranch %205 +%205 = OpLabel +OpStore %201 %204 OpReturn OpFunctionEnd -%215 = OpFunction %2 None %216 -%214 = OpFunctionParameter %35 +%208 = OpFunction %2 None %209 +%207 = OpFunctionParameter %35 +%206 = OpLabel +OpBranch %213 %213 = OpLabel -OpBranch %217 -%217 = OpLabel -%218 = OpCompositeConstruct %31 %66 %66 %66 %66 -%219 = OpCompositeConstruct %31 %67 %67 %67 %67 -%220 = OpCompositeConstruct %34 %218 %219 -OpStore %214 %220 +OpStore %207 %212 OpReturn OpFunctionEnd -%232 = OpFunction %2 None %62 -%226 = OpLabel -%221 = OpVariable %27 Function %222 -%223 = OpVariable %224 Function %225 -%229 = OpLoad %3 %227 -%233 = OpAccessChain %63 %44 %36 -%235 = OpAccessChain %234 %47 %36 -%236 = OpAccessChain %138 %50 %36 -OpBranch %244 -%244 = OpLabel -OpStore %221 %237 -%245 = OpLoad %10 %221 -OpStore %221 %66 -%246 = OpFunctionCall %2 %61 -%247 = OpFunctionCall %2 %137 -%249 = OpAccessChain %248 %42 %36 -%250 = OpLoad %8 %249 -%253 = OpAccessChain %251 %42 %252 -%254 = OpLoad %18 %253 -%257 = OpAccessChain %256 %42 %36 %238 %36 -%258 = OpLoad %10 %257 -%260 = OpArrayLength %3 %42 5 -%261 = OpISub %3 %260 %14 -%264 = OpAccessChain %263 %42 %30 %261 %36 +%220 = OpFunction %2 None %56 +%214 = OpLabel +%232 = OpVariable %27 Function %225 +%233 = OpVariable %234 Function %235 +%217 = OpLoad %3 %215 +%221 = OpAccessChain %57 %44 %36 +%223 = OpAccessChain %222 %47 %36 +%224 = OpAccessChain %132 %50 %36 +OpBranch %236 +%236 = OpLabel +%237 = OpLoad %10 %232 +OpStore %232 %60 +%238 = OpFunctionCall %2 %55 +%239 = OpFunctionCall %2 %131 +%241 = OpAccessChain %240 %42 %36 +%242 = OpLoad %8 %241 +%245 = OpAccessChain %243 %42 %244 +%246 = OpLoad %18 %245 +%249 = OpAccessChain %248 %42 %36 %226 %36 +%250 = OpLoad %10 %249 +%252 = OpArrayLength %3 %42 5 +%253 = OpISub %3 %252 %14 +%256 = OpAccessChain %255 %42 %30 %253 %36 +%257 = OpLoad %5 %256 +%258 = OpLoad %23 %223 +%259 = OpFunctionCall %10 %189 %232 +%260 = OpConvertFToS %5 %250 +%261 = OpCompositeConstruct %32 %257 %260 %227 %228 %229 +OpStore %233 %261 +%262 = OpIAdd %3 %217 %100 +%263 = OpAccessChain %84 %233 %262 +OpStore %263 %230 +%264 = OpAccessChain %84 %233 %217 %265 = OpLoad %5 %264 -%266 = OpLoad %23 %235 -%267 = OpFunctionCall %10 %196 %221 -%268 = OpConvertFToS %5 %258 -%269 = OpCompositeConstruct %32 %265 %268 %239 %240 %241 -OpStore %223 %269 -%270 = OpIAdd %3 %229 %91 -%271 = OpAccessChain %55 %223 %270 -OpStore %271 %242 -%272 = OpAccessChain %55 %223 %229 -%273 = OpLoad %5 %272 -%274 = OpFunctionCall %10 %202 %243 -%276 = OpCompositeConstruct %275 %273 %273 %273 %273 -%277 = OpConvertSToF %31 %276 -%278 = OpMatrixTimesVector %9 %250 %277 -%279 = OpCompositeConstruct %31 %278 %67 -OpStore %230 %279 +%266 = OpFunctionCall %10 %195 %231 +%268 = OpCompositeConstruct %267 %265 %265 %265 %265 +%269 = OpConvertSToF %31 %268 +%270 = OpMatrixTimesVector %9 %242 %269 +%271 = OpCompositeConstruct %31 %270 %62 +OpStore %218 %271 OpReturn OpFunctionEnd -%282 = OpFunction %2 None %62 -%280 = OpLabel -%283 = OpAccessChain %234 %47 %36 -OpBranch %285 -%285 = OpLabel -%286 = OpAccessChain %256 %42 %36 %91 %14 -OpStore %286 %66 -%287 = OpCompositeConstruct %9 %237 %237 %237 -%288 = OpCompositeConstruct %9 %66 %66 %66 -%289 = OpCompositeConstruct %9 %67 %67 %67 -%290 = OpCompositeConstruct %9 %68 %68 %68 -%291 = OpCompositeConstruct %8 %287 %288 %289 %290 -%292 = OpAccessChain %248 %42 %36 -OpStore %292 %291 -%293 = OpCompositeConstruct %17 %36 %36 -%294 = OpCompositeConstruct %17 %91 %91 -%295 = OpCompositeConstruct %18 %293 %294 -%296 = OpAccessChain %251 %42 %252 -OpStore %296 %295 -%297 = OpAccessChain %263 %42 %30 %91 %36 -OpStore %297 %65 -OpStore %283 %284 -%298 = OpCompositeConstruct %31 %237 %237 %237 %237 -OpStore %281 %298 +%274 = OpFunction %2 None %56 +%272 = OpLabel +%275 = OpAccessChain %222 %47 %36 +OpBranch %286 +%286 = OpLabel +%287 = OpAccessChain %248 %42 %36 %100 %14 +OpStore %287 %60 +%288 = OpAccessChain %240 %42 %36 +OpStore %288 %280 +%289 = OpAccessChain %243 %42 %244 +OpStore %289 %283 +%290 = OpAccessChain %255 %42 %30 %100 %36 +OpStore %290 %59 +OpStore %275 %284 +OpStore %273 %285 OpReturn OpFunctionEnd -%302 = OpFunction %2 None %62 -%301 = OpLabel -%299 = OpVariable %35 Function %300 -OpBranch %303 -%303 = OpLabel -%307 = OpLoad %4 %305 -%311 = OpIEqual %309 %307 %308 -%312 = OpAll %310 %311 -OpSelectionMerge %313 None -OpBranchConditional %312 %314 %313 -%314 = OpLabel -OpStore %53 %304 -OpBranch %313 -%313 = OpLabel -OpControlBarrier %14 %14 %315 -OpBranch %316 -%316 = OpLabel -%317 = OpCompositeConstruct %31 %69 %69 %69 %69 -%318 = OpCompositeConstruct %31 %142 %142 %142 %142 -%319 = OpCompositeConstruct %34 %317 %318 -OpStore %299 %319 -%320 = OpFunctionCall %2 %209 %53 -%321 = OpFunctionCall %2 %215 %299 +%292 = OpFunction %2 None %56 +%291 = OpLabel +%296 = OpVariable %35 Function %295 +OpBranch %297 +%297 = OpLabel +%301 = OpLoad %4 %299 +%305 = OpIEqual %303 %301 %302 +%306 = OpAll %304 %305 +OpSelectionMerge %307 None +OpBranchConditional %306 %308 %307 +%308 = OpLabel +OpStore %53 %298 +OpBranch %307 +%307 = OpLabel +OpControlBarrier %14 %14 %309 +OpBranch %310 +%310 = OpLabel +%311 = OpFunctionCall %2 %202 %53 +%312 = OpFunctionCall %2 %208 %296 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/array-in-function-return-type.spvasm b/tests/out/spv/array-in-function-return-type.spvasm index e68f6ad83..79e94fba8 100644 --- a/tests/out/spv/array-in-function-return-type.spvasm +++ b/tests/out/spv/array-in-function-return-type.spvasm @@ -18,16 +18,16 @@ OpDecorate %16 Location 0 %10 = OpTypeFunction %4 %11 = OpConstant %3 1.0 %12 = OpConstant %3 2.0 +%13 = OpConstantComposite %4 %11 %12 %17 = OpTypePointer Output %7 %16 = OpVariable %17 Output %19 = OpTypeFunction %2 %20 = OpConstant %3 0.0 %9 = OpFunction %4 None %10 %8 = OpLabel -OpBranch %13 -%13 = OpLabel -%14 = OpCompositeConstruct %4 %11 %12 -OpReturnValue %14 +OpBranch %14 +%14 = OpLabel +OpReturnValue %13 OpFunctionEnd %18 = OpFunction %2 None %19 %15 = OpLabel diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/tests/out/spv/atomicCompareExchange.spvasm index c73c159ea..d08e3656f 100644 --- a/tests/out/spv/atomicCompareExchange.spvasm +++ b/tests/out/spv/atomicCompareExchange.spvasm @@ -1,15 +1,15 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 123 +; Bound: 122 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %27 "test_atomic_compare_exchange_i32" -OpEntryPoint GLCompute %81 "test_atomic_compare_exchange_u32" -OpExecutionMode %27 LocalSize 1 1 1 -OpExecutionMode %81 LocalSize 1 1 1 +OpEntryPoint GLCompute %18 "test_atomic_compare_exchange_i32" +OpEntryPoint GLCompute %76 "test_atomic_compare_exchange_u32" +OpExecutionMode %18 LocalSize 1 1 1 +OpExecutionMode %76 LocalSize 1 1 1 OpDecorate %5 ArrayStride 4 OpDecorate %7 ArrayStride 4 OpMemberDecorate %9 0 Offset 0 @@ -39,167 +39,164 @@ OpMemberDecorate %15 0 Offset 0 %15 = OpTypeStruct %7 %16 = OpTypePointer StorageBuffer %15 %14 = OpVariable %16 StorageBuffer -%18 = OpTypePointer Function %3 -%19 = OpConstantNull %3 -%21 = OpTypePointer Function %4 -%22 = OpConstantNull %4 -%24 = OpTypePointer Function %8 -%25 = OpConstantNull %8 -%28 = OpTypeFunction %2 -%29 = OpTypePointer StorageBuffer %5 -%30 = OpConstant %3 0 -%32 = OpConstantFalse %8 -%33 = OpTypeFloat 32 -%34 = OpConstant %33 1.0 -%35 = OpConstant %3 1 -%48 = OpTypePointer StorageBuffer %4 -%51 = OpConstant %4 1 -%52 = OpConstant %3 64 -%82 = OpTypePointer StorageBuffer %7 -%96 = OpTypePointer StorageBuffer %3 -%27 = OpFunction %2 None %28 -%26 = OpLabel -%17 = OpVariable %18 Function %19 -%20 = OpVariable %21 Function %22 -%23 = OpVariable %24 Function %25 -%31 = OpAccessChain %29 %11 %30 -OpBranch %36 -%36 = OpLabel -OpStore %17 %30 +%19 = OpTypeFunction %2 +%20 = OpTypePointer StorageBuffer %5 +%21 = OpConstant %3 0 +%23 = OpConstantFalse %8 +%24 = OpTypeFloat 32 +%25 = OpConstant %24 1.0 +%26 = OpConstant %3 1 +%28 = OpTypePointer Function %3 +%30 = OpTypePointer Function %4 +%31 = OpConstantNull %4 +%33 = OpTypePointer Function %8 +%46 = OpTypePointer StorageBuffer %4 +%49 = OpConstant %4 1 +%50 = OpConstant %3 64 +%77 = OpTypePointer StorageBuffer %7 +%81 = OpConstantNull %3 +%95 = OpTypePointer StorageBuffer %3 +%18 = OpFunction %2 None %19 +%17 = OpLabel +%27 = OpVariable %28 Function %21 +%29 = OpVariable %30 Function %31 +%32 = OpVariable %33 Function %23 +%22 = OpAccessChain %20 %11 %21 +OpBranch %34 +%34 = OpLabel +OpBranch %35 +%35 = OpLabel +OpLoopMerge %36 %38 None OpBranch %37 %37 = OpLabel -OpLoopMerge %38 %40 None -OpBranch %39 -%39 = OpLabel -%41 = OpLoad %3 %17 -%42 = OpULessThan %8 %41 %6 -OpSelectionMerge %43 None -OpBranchConditional %42 %43 %44 -%44 = OpLabel -OpBranch %38 +%39 = OpLoad %3 %27 +%40 = OpULessThan %8 %39 %6 +OpSelectionMerge %41 None +OpBranchConditional %40 %41 %42 +%42 = OpLabel +OpBranch %36 +%41 = OpLabel +OpBranch %43 %43 = OpLabel -OpBranch %45 -%45 = OpLabel -%47 = OpLoad %3 %17 -%49 = OpAccessChain %48 %31 %47 -%50 = OpAtomicLoad %4 %49 %51 %52 -OpStore %20 %50 -OpStore %23 %32 +%45 = OpLoad %3 %27 +%47 = OpAccessChain %46 %22 %45 +%48 = OpAtomicLoad %4 %47 %49 %50 +OpStore %29 %48 +OpStore %32 %23 +OpBranch %51 +%51 = OpLabel +OpLoopMerge %52 %54 None OpBranch %53 %53 = OpLabel -OpLoopMerge %54 %56 None -OpBranch %55 -%55 = OpLabel -%57 = OpLoad %8 %23 -%58 = OpLogicalNot %8 %57 -OpSelectionMerge %59 None -OpBranchConditional %58 %59 %60 +%55 = OpLoad %8 %32 +%56 = OpLogicalNot %8 %55 +OpSelectionMerge %57 None +OpBranchConditional %56 %57 %58 +%58 = OpLabel +OpBranch %52 +%57 = OpLabel +OpBranch %59 +%59 = OpLabel +%61 = OpLoad %4 %29 +%62 = OpBitcast %24 %61 +%63 = OpFAdd %24 %62 %25 +%64 = OpBitcast %4 %63 +%65 = OpLoad %3 %27 +%66 = OpLoad %4 %29 +%68 = OpAccessChain %46 %22 %65 +%69 = OpAtomicCompareExchange %4 %68 %49 %50 %50 %64 %66 +%70 = OpIEqual %8 %69 %66 +%67 = OpCompositeConstruct %9 %69 %70 +%71 = OpCompositeExtract %4 %67 0 +OpStore %29 %71 +%72 = OpCompositeExtract %8 %67 1 +OpStore %32 %72 +OpBranch %60 %60 = OpLabel OpBranch %54 -%59 = OpLabel -OpBranch %61 -%61 = OpLabel -%63 = OpLoad %4 %20 -%64 = OpBitcast %33 %63 -%65 = OpFAdd %33 %64 %34 -%66 = OpBitcast %4 %65 -%67 = OpLoad %3 %17 -%68 = OpLoad %4 %20 -%70 = OpAccessChain %48 %31 %67 -%71 = OpAtomicCompareExchange %4 %70 %51 %52 %52 %66 %68 -%72 = OpIEqual %8 %71 %68 -%69 = OpCompositeConstruct %9 %71 %72 -%73 = OpCompositeExtract %4 %69 0 -OpStore %20 %73 -%74 = OpCompositeExtract %8 %69 1 -OpStore %23 %74 -OpBranch %62 -%62 = OpLabel -OpBranch %56 -%56 = OpLabel -OpBranch %53 %54 = OpLabel -OpBranch %46 -%46 = OpLabel -OpBranch %40 -%40 = OpLabel -%75 = OpLoad %3 %17 -%76 = OpIAdd %3 %75 %35 -OpStore %17 %76 -OpBranch %37 +OpBranch %51 +%52 = OpLabel +OpBranch %44 +%44 = OpLabel +OpBranch %38 %38 = OpLabel +%73 = OpLoad %3 %27 +%74 = OpIAdd %3 %73 %26 +OpStore %27 %74 +OpBranch %35 +%36 = OpLabel OpReturn OpFunctionEnd -%81 = OpFunction %2 None %28 -%80 = OpLabel -%77 = OpVariable %18 Function %19 -%78 = OpVariable %18 Function %19 -%79 = OpVariable %24 Function %25 -%83 = OpAccessChain %82 %14 %30 +%76 = OpFunction %2 None %19 +%75 = OpLabel +%79 = OpVariable %28 Function %21 +%80 = OpVariable %28 Function %81 +%82 = OpVariable %33 Function %23 +%78 = OpAccessChain %77 %14 %21 +OpBranch %83 +%83 = OpLabel OpBranch %84 %84 = OpLabel -OpStore %77 %30 -OpBranch %85 -%85 = OpLabel -OpLoopMerge %86 %88 None -OpBranch %87 -%87 = OpLabel -%89 = OpLoad %3 %77 -%90 = OpULessThan %8 %89 %6 -OpSelectionMerge %91 None -OpBranchConditional %90 %91 %92 -%92 = OpLabel +OpLoopMerge %85 %87 None OpBranch %86 +%86 = OpLabel +%88 = OpLoad %3 %79 +%89 = OpULessThan %8 %88 %6 +OpSelectionMerge %90 None +OpBranchConditional %89 %90 %91 %91 = OpLabel -OpBranch %93 -%93 = OpLabel -%95 = OpLoad %3 %77 -%97 = OpAccessChain %96 %83 %95 -%98 = OpAtomicLoad %3 %97 %51 %52 -OpStore %78 %98 -OpStore %79 %32 -OpBranch %99 -%99 = OpLabel -OpLoopMerge %100 %102 None -OpBranch %101 -%101 = OpLabel -%103 = OpLoad %8 %79 -%104 = OpLogicalNot %8 %103 -OpSelectionMerge %105 None -OpBranchConditional %104 %105 %106 -%106 = OpLabel +OpBranch %85 +%90 = OpLabel +OpBranch %92 +%92 = OpLabel +%94 = OpLoad %3 %79 +%96 = OpAccessChain %95 %78 %94 +%97 = OpAtomicLoad %3 %96 %49 %50 +OpStore %80 %97 +OpStore %82 %23 +OpBranch %98 +%98 = OpLabel +OpLoopMerge %99 %101 None OpBranch %100 +%100 = OpLabel +%102 = OpLoad %8 %82 +%103 = OpLogicalNot %8 %102 +OpSelectionMerge %104 None +OpBranchConditional %103 %104 %105 %105 = OpLabel +OpBranch %99 +%104 = OpLabel +OpBranch %106 +%106 = OpLabel +%108 = OpLoad %3 %80 +%109 = OpBitcast %24 %108 +%110 = OpFAdd %24 %109 %25 +%111 = OpBitcast %3 %110 +%112 = OpLoad %3 %79 +%113 = OpLoad %3 %80 +%115 = OpAccessChain %95 %78 %112 +%116 = OpAtomicCompareExchange %3 %115 %49 %50 %50 %111 %113 +%117 = OpIEqual %8 %116 %113 +%114 = OpCompositeConstruct %10 %116 %117 +%118 = OpCompositeExtract %3 %114 0 +OpStore %80 %118 +%119 = OpCompositeExtract %8 %114 1 +OpStore %82 %119 OpBranch %107 %107 = OpLabel -%109 = OpLoad %3 %78 -%110 = OpBitcast %33 %109 -%111 = OpFAdd %33 %110 %34 -%112 = OpBitcast %3 %111 -%113 = OpLoad %3 %77 -%114 = OpLoad %3 %78 -%116 = OpAccessChain %96 %83 %113 -%117 = OpAtomicCompareExchange %3 %116 %51 %52 %52 %112 %114 -%118 = OpIEqual %8 %117 %114 -%115 = OpCompositeConstruct %10 %117 %118 -%119 = OpCompositeExtract %3 %115 0 -OpStore %78 %119 -%120 = OpCompositeExtract %8 %115 1 -OpStore %79 %120 -OpBranch %108 -%108 = OpLabel -OpBranch %102 -%102 = OpLabel -OpBranch %99 -%100 = OpLabel -OpBranch %94 -%94 = OpLabel -OpBranch %88 -%88 = OpLabel -%121 = OpLoad %3 %77 -%122 = OpIAdd %3 %121 %35 -OpStore %77 %122 -OpBranch %85 -%86 = OpLabel +OpBranch %101 +%101 = OpLabel +OpBranch %98 +%99 = OpLabel +OpBranch %93 +%93 = OpLabel +OpBranch %87 +%87 = OpLabel +%120 = OpLoad %3 %79 +%121 = OpIAdd %3 %120 %26 +OpStore %79 %121 +OpBranch %84 +%85 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-arrays.spvasm b/tests/out/spv/binding-arrays.spvasm index 57636775f..3d3b9f8e5 100644 --- a/tests/out/spv/binding-arrays.spvasm +++ b/tests/out/spv/binding-arrays.spvasm @@ -1,15 +1,15 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 431 +; Bound: 428 OpCapability Shader OpCapability ImageQuery OpCapability ShaderNonUniform OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %64 "main" %59 %62 -OpExecutionMode %64 OriginUpperLeft +OpEntryPoint Fragment %52 "main" %47 %50 +OpExecutionMode %52 OriginUpperLeft OpMemberDecorate %4 0 Offset 0 OpMemberDecorate %21 0 Offset 0 OpDecorate %24 DescriptorSet 0 @@ -32,31 +32,31 @@ OpDecorate %42 DescriptorSet 0 OpDecorate %42 Binding 8 OpDecorate %43 Block OpMemberDecorate %43 0 Offset 0 -OpDecorate %59 Location 0 -OpDecorate %59 Flat -OpDecorate %62 Location 0 -OpDecorate %95 NonUniform -OpDecorate %118 NonUniform -OpDecorate %120 NonUniform -OpDecorate %145 NonUniform -OpDecorate %147 NonUniform -OpDecorate %183 NonUniform -OpDecorate %211 NonUniform -OpDecorate %227 NonUniform -OpDecorate %243 NonUniform -OpDecorate %264 NonUniform -OpDecorate %266 NonUniform -OpDecorate %288 NonUniform -OpDecorate %290 NonUniform -OpDecorate %312 NonUniform -OpDecorate %314 NonUniform -OpDecorate %336 NonUniform -OpDecorate %338 NonUniform -OpDecorate %360 NonUniform -OpDecorate %362 NonUniform -OpDecorate %384 NonUniform -OpDecorate %386 NonUniform -OpDecorate %409 NonUniform +OpDecorate %47 Location 0 +OpDecorate %47 Flat +OpDecorate %50 Location 0 +OpDecorate %91 NonUniform +OpDecorate %114 NonUniform +OpDecorate %116 NonUniform +OpDecorate %141 NonUniform +OpDecorate %143 NonUniform +OpDecorate %180 NonUniform +OpDecorate %208 NonUniform +OpDecorate %224 NonUniform +OpDecorate %240 NonUniform +OpDecorate %261 NonUniform +OpDecorate %263 NonUniform +OpDecorate %285 NonUniform +OpDecorate %287 NonUniform +OpDecorate %309 NonUniform +OpDecorate %311 NonUniform +OpDecorate %333 NonUniform +OpDecorate %335 NonUniform +OpDecorate %357 NonUniform +OpDecorate %359 NonUniform +OpDecorate %381 NonUniform +OpDecorate %383 NonUniform +OpDecorate %406 NonUniform %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeStruct %3 @@ -100,460 +100,453 @@ OpDecorate %409 NonUniform %43 = OpTypeStruct %4 %44 = OpTypePointer Uniform %43 %42 = OpVariable %44 Uniform -%46 = OpTypePointer Function %3 -%47 = OpConstantNull %3 -%49 = OpTypePointer Function %23 -%50 = OpConstantNull %23 -%52 = OpTypePointer Function %6 -%53 = OpConstantNull %6 -%55 = OpTypePointer Function %22 -%56 = OpConstantNull %22 -%60 = OpTypePointer Input %3 -%59 = OpVariable %60 Input -%63 = OpTypePointer Output %22 -%62 = OpVariable %63 Output -%65 = OpTypeFunction %2 -%66 = OpTypePointer Uniform %4 -%67 = OpConstant %3 0 -%69 = OpConstant %6 0.0 -%70 = OpTypeInt 32 1 -%71 = OpConstant %70 0 -%73 = OpTypePointer Uniform %3 -%79 = OpTypeVector %6 2 -%81 = OpTypeVector %70 2 -%83 = OpTypePointer UniformConstant %5 -%101 = OpTypePointer UniformConstant %18 -%104 = OpTypeSampledImage %5 -%125 = OpTypePointer UniformConstant %14 -%128 = OpTypePointer UniformConstant %18 -%131 = OpTypeSampledImage %14 -%154 = OpTypeBool -%160 = OpTypeVector %154 2 -%196 = OpTypePointer UniformConstant %10 -%199 = OpTypeVector %3 3 -%231 = OpTypePointer UniformConstant %12 -%391 = OpTypePointer UniformConstant %16 -%64 = OpFunction %2 None %65 -%57 = OpLabel -%48 = OpVariable %49 Function %50 -%54 = OpVariable %55 Function %56 -%45 = OpVariable %46 Function %47 -%51 = OpVariable %52 Function %53 -%61 = OpLoad %3 %59 -%58 = OpCompositeConstruct %21 %61 -%68 = OpAccessChain %66 %42 %67 -OpBranch %72 -%72 = OpLabel -%74 = OpAccessChain %73 %68 %67 -%75 = OpLoad %3 %74 -%76 = OpCompositeExtract %3 %58 0 -OpStore %45 %67 -%77 = OpCompositeConstruct %23 %67 %67 -OpStore %48 %77 -OpStore %51 %69 -%78 = OpCompositeConstruct %22 %69 %69 %69 %69 -OpStore %54 %78 -%80 = OpCompositeConstruct %79 %69 %69 -%82 = OpCompositeConstruct %81 %71 %71 -%84 = OpAccessChain %83 %24 %67 -%85 = OpLoad %5 %84 -%86 = OpImageQuerySizeLod %23 %85 %67 -%87 = OpLoad %23 %48 -%88 = OpIAdd %23 %87 %86 -OpStore %48 %88 -%89 = OpAccessChain %83 %24 %75 -%90 = OpLoad %5 %89 -%91 = OpImageQuerySizeLod %23 %90 %67 -%92 = OpLoad %23 %48 -%93 = OpIAdd %23 %92 %91 -OpStore %48 %93 -%94 = OpAccessChain %83 %24 %76 -%95 = OpLoad %5 %94 -%96 = OpImageQuerySizeLod %23 %95 %67 -%97 = OpLoad %23 %48 -%98 = OpIAdd %23 %97 %96 -OpStore %48 %98 -%99 = OpAccessChain %83 %28 %67 -%100 = OpLoad %5 %99 -%102 = OpAccessChain %101 %38 %67 -%103 = OpLoad %18 %102 -%105 = OpSampledImage %104 %100 %103 -%106 = OpImageGather %22 %105 %80 %67 -%107 = OpLoad %22 %54 -%108 = OpFAdd %22 %107 %106 -OpStore %54 %108 -%109 = OpAccessChain %83 %28 %75 -%110 = OpLoad %5 %109 -%111 = OpAccessChain %101 %38 %75 -%112 = OpLoad %18 %111 -%113 = OpSampledImage %104 %110 %112 -%114 = OpImageGather %22 %113 %80 %67 -%115 = OpLoad %22 %54 -%116 = OpFAdd %22 %115 %114 -OpStore %54 %116 -%117 = OpAccessChain %83 %28 %76 -%118 = OpLoad %5 %117 -%119 = OpAccessChain %101 %38 %76 -%120 = OpLoad %18 %119 -%121 = OpSampledImage %104 %118 %120 -%122 = OpImageGather %22 %121 %80 %67 -%123 = OpLoad %22 %54 -%124 = OpFAdd %22 %123 %122 -OpStore %54 %124 -%126 = OpAccessChain %125 %34 %67 -%127 = OpLoad %14 %126 -%129 = OpAccessChain %128 %40 %67 -%130 = OpLoad %18 %129 -%132 = OpSampledImage %131 %127 %130 -%133 = OpImageDrefGather %22 %132 %80 %69 -%134 = OpLoad %22 %54 -%135 = OpFAdd %22 %134 %133 -OpStore %54 %135 -%136 = OpAccessChain %125 %34 %75 -%137 = OpLoad %14 %136 -%138 = OpAccessChain %128 %40 %75 -%139 = OpLoad %18 %138 -%140 = OpSampledImage %131 %137 %139 -%141 = OpImageDrefGather %22 %140 %80 %69 -%142 = OpLoad %22 %54 -%143 = OpFAdd %22 %142 %141 -OpStore %54 %143 -%144 = OpAccessChain %125 %34 %76 -%145 = OpLoad %14 %144 -%146 = OpAccessChain %128 %40 %76 -%147 = OpLoad %18 %146 -%148 = OpSampledImage %131 %145 %147 -%149 = OpImageDrefGather %22 %148 %80 %69 -%150 = OpLoad %22 %54 -%151 = OpFAdd %22 %150 %149 -OpStore %54 %151 -%152 = OpAccessChain %83 %24 %67 -%153 = OpLoad %5 %152 -%155 = OpImageQueryLevels %70 %153 -%156 = OpULessThan %154 %71 %155 -OpSelectionMerge %157 None -OpBranchConditional %156 %158 %157 -%158 = OpLabel -%159 = OpImageQuerySizeLod %81 %153 %71 -%161 = OpULessThan %160 %82 %159 -%162 = OpAll %154 %161 -OpBranchConditional %162 %163 %157 -%163 = OpLabel -%164 = OpImageFetch %22 %153 %82 Lod %71 -OpBranch %157 -%157 = OpLabel -%165 = OpPhi %22 %56 %72 %56 %158 %164 %163 -%166 = OpLoad %22 %54 -%167 = OpFAdd %22 %166 %165 -OpStore %54 %167 -%168 = OpAccessChain %83 %24 %75 -%169 = OpLoad %5 %168 -%170 = OpImageQueryLevels %70 %169 -%171 = OpULessThan %154 %71 %170 -OpSelectionMerge %172 None -OpBranchConditional %171 %173 %172 -%173 = OpLabel -%174 = OpImageQuerySizeLod %81 %169 %71 -%175 = OpULessThan %160 %82 %174 -%176 = OpAll %154 %175 -OpBranchConditional %176 %177 %172 -%177 = OpLabel -%178 = OpImageFetch %22 %169 %82 Lod %71 -OpBranch %172 -%172 = OpLabel -%179 = OpPhi %22 %56 %157 %56 %173 %178 %177 -%180 = OpLoad %22 %54 -%181 = OpFAdd %22 %180 %179 -OpStore %54 %181 -%182 = OpAccessChain %83 %24 %76 -%183 = OpLoad %5 %182 -%184 = OpImageQueryLevels %70 %183 -%185 = OpULessThan %154 %71 %184 -OpSelectionMerge %186 None -OpBranchConditional %185 %187 %186 -%187 = OpLabel -%188 = OpImageQuerySizeLod %81 %183 %71 -%189 = OpULessThan %160 %82 %188 -%190 = OpAll %154 %189 -OpBranchConditional %190 %191 %186 -%191 = OpLabel -%192 = OpImageFetch %22 %183 %82 Lod %71 -OpBranch %186 -%186 = OpLabel -%193 = OpPhi %22 %56 %172 %56 %187 %192 %191 -%194 = OpLoad %22 %54 -%195 = OpFAdd %22 %194 %193 -OpStore %54 %195 -%197 = OpAccessChain %196 %30 %67 -%198 = OpLoad %10 %197 -%200 = OpImageQuerySizeLod %199 %198 %67 -%201 = OpCompositeExtract %3 %200 2 -%202 = OpLoad %3 %45 -%203 = OpIAdd %3 %202 %201 -OpStore %45 %203 -%204 = OpAccessChain %196 %30 %75 -%205 = OpLoad %10 %204 -%206 = OpImageQuerySizeLod %199 %205 %67 -%207 = OpCompositeExtract %3 %206 2 -%208 = OpLoad %3 %45 -%209 = OpIAdd %3 %208 %207 -OpStore %45 %209 -%210 = OpAccessChain %196 %30 %76 -%211 = OpLoad %10 %210 -%212 = OpImageQuerySizeLod %199 %211 %67 -%213 = OpCompositeExtract %3 %212 2 -%214 = OpLoad %3 %45 -%215 = OpIAdd %3 %214 %213 -OpStore %45 %215 -%216 = OpAccessChain %83 %28 %67 -%217 = OpLoad %5 %216 -%218 = OpImageQueryLevels %3 %217 -%219 = OpLoad %3 %45 -%220 = OpIAdd %3 %219 %218 -OpStore %45 %220 -%221 = OpAccessChain %83 %28 %75 -%222 = OpLoad %5 %221 -%223 = OpImageQueryLevels %3 %222 -%224 = OpLoad %3 %45 -%225 = OpIAdd %3 %224 %223 -OpStore %45 %225 -%226 = OpAccessChain %83 %28 %76 -%227 = OpLoad %5 %226 -%228 = OpImageQueryLevels %3 %227 -%229 = OpLoad %3 %45 -%230 = OpIAdd %3 %229 %228 -OpStore %45 %230 -%232 = OpAccessChain %231 %32 %67 -%233 = OpLoad %12 %232 -%234 = OpImageQuerySamples %3 %233 -%235 = OpLoad %3 %45 -%236 = OpIAdd %3 %235 %234 -OpStore %45 %236 -%237 = OpAccessChain %231 %32 %75 -%238 = OpLoad %12 %237 -%239 = OpImageQuerySamples %3 %238 -%240 = OpLoad %3 %45 -%241 = OpIAdd %3 %240 %239 -OpStore %45 %241 -%242 = OpAccessChain %231 %32 %76 -%243 = OpLoad %12 %242 -%244 = OpImageQuerySamples %3 %243 -%245 = OpLoad %3 %45 -%246 = OpIAdd %3 %245 %244 -OpStore %45 %246 -%247 = OpAccessChain %83 %28 %67 -%248 = OpLoad %5 %247 -%249 = OpAccessChain %101 %38 %67 -%250 = OpLoad %18 %249 -%251 = OpSampledImage %104 %248 %250 -%252 = OpImageSampleImplicitLod %22 %251 %80 -%253 = OpLoad %22 %54 -%254 = OpFAdd %22 %253 %252 -OpStore %54 %254 -%255 = OpAccessChain %83 %28 %75 -%256 = OpLoad %5 %255 -%257 = OpAccessChain %101 %38 %75 -%258 = OpLoad %18 %257 -%259 = OpSampledImage %104 %256 %258 -%260 = OpImageSampleImplicitLod %22 %259 %80 -%261 = OpLoad %22 %54 -%262 = OpFAdd %22 %261 %260 -OpStore %54 %262 -%263 = OpAccessChain %83 %28 %76 -%264 = OpLoad %5 %263 -%265 = OpAccessChain %101 %38 %76 -%266 = OpLoad %18 %265 -%267 = OpSampledImage %104 %264 %266 -%268 = OpImageSampleImplicitLod %22 %267 %80 -%269 = OpLoad %22 %54 -%270 = OpFAdd %22 %269 %268 -OpStore %54 %270 -%271 = OpAccessChain %83 %28 %67 -%272 = OpLoad %5 %271 -%273 = OpAccessChain %101 %38 %67 -%274 = OpLoad %18 %273 -%275 = OpSampledImage %104 %272 %274 -%276 = OpImageSampleImplicitLod %22 %275 %80 Bias %69 -%277 = OpLoad %22 %54 -%278 = OpFAdd %22 %277 %276 -OpStore %54 %278 -%279 = OpAccessChain %83 %28 %75 -%280 = OpLoad %5 %279 -%281 = OpAccessChain %101 %38 %75 -%282 = OpLoad %18 %281 -%283 = OpSampledImage %104 %280 %282 -%284 = OpImageSampleImplicitLod %22 %283 %80 Bias %69 -%285 = OpLoad %22 %54 -%286 = OpFAdd %22 %285 %284 -OpStore %54 %286 -%287 = OpAccessChain %83 %28 %76 -%288 = OpLoad %5 %287 -%289 = OpAccessChain %101 %38 %76 -%290 = OpLoad %18 %289 -%291 = OpSampledImage %104 %288 %290 -%292 = OpImageSampleImplicitLod %22 %291 %80 Bias %69 -%293 = OpLoad %22 %54 -%294 = OpFAdd %22 %293 %292 -OpStore %54 %294 -%295 = OpAccessChain %125 %34 %67 -%296 = OpLoad %14 %295 -%297 = OpAccessChain %128 %40 %67 -%298 = OpLoad %18 %297 -%299 = OpSampledImage %131 %296 %298 -%300 = OpImageSampleDrefImplicitLod %6 %299 %80 %69 -%301 = OpLoad %6 %51 -%302 = OpFAdd %6 %301 %300 -OpStore %51 %302 -%303 = OpAccessChain %125 %34 %75 -%304 = OpLoad %14 %303 -%305 = OpAccessChain %128 %40 %75 -%306 = OpLoad %18 %305 -%307 = OpSampledImage %131 %304 %306 -%308 = OpImageSampleDrefImplicitLod %6 %307 %80 %69 -%309 = OpLoad %6 %51 -%310 = OpFAdd %6 %309 %308 -OpStore %51 %310 -%311 = OpAccessChain %125 %34 %76 -%312 = OpLoad %14 %311 -%313 = OpAccessChain %128 %40 %76 -%314 = OpLoad %18 %313 -%315 = OpSampledImage %131 %312 %314 -%316 = OpImageSampleDrefImplicitLod %6 %315 %80 %69 -%317 = OpLoad %6 %51 -%318 = OpFAdd %6 %317 %316 -OpStore %51 %318 -%319 = OpAccessChain %125 %34 %67 -%320 = OpLoad %14 %319 -%321 = OpAccessChain %128 %40 %67 -%322 = OpLoad %18 %321 -%323 = OpSampledImage %131 %320 %322 -%324 = OpImageSampleDrefExplicitLod %6 %323 %80 %69 Lod %69 -%325 = OpLoad %6 %51 -%326 = OpFAdd %6 %325 %324 -OpStore %51 %326 -%327 = OpAccessChain %125 %34 %75 -%328 = OpLoad %14 %327 -%329 = OpAccessChain %128 %40 %75 -%330 = OpLoad %18 %329 -%331 = OpSampledImage %131 %328 %330 -%332 = OpImageSampleDrefExplicitLod %6 %331 %80 %69 Lod %69 -%333 = OpLoad %6 %51 -%334 = OpFAdd %6 %333 %332 -OpStore %51 %334 -%335 = OpAccessChain %125 %34 %76 -%336 = OpLoad %14 %335 -%337 = OpAccessChain %128 %40 %76 -%338 = OpLoad %18 %337 -%339 = OpSampledImage %131 %336 %338 -%340 = OpImageSampleDrefExplicitLod %6 %339 %80 %69 Lod %69 -%341 = OpLoad %6 %51 -%342 = OpFAdd %6 %341 %340 -OpStore %51 %342 -%343 = OpAccessChain %83 %28 %67 -%344 = OpLoad %5 %343 -%345 = OpAccessChain %101 %38 %67 -%346 = OpLoad %18 %345 -%347 = OpSampledImage %104 %344 %346 -%348 = OpImageSampleExplicitLod %22 %347 %80 Grad %80 %80 -%349 = OpLoad %22 %54 -%350 = OpFAdd %22 %349 %348 -OpStore %54 %350 -%351 = OpAccessChain %83 %28 %75 -%352 = OpLoad %5 %351 -%353 = OpAccessChain %101 %38 %75 -%354 = OpLoad %18 %353 -%355 = OpSampledImage %104 %352 %354 -%356 = OpImageSampleExplicitLod %22 %355 %80 Grad %80 %80 -%357 = OpLoad %22 %54 -%358 = OpFAdd %22 %357 %356 -OpStore %54 %358 -%359 = OpAccessChain %83 %28 %76 -%360 = OpLoad %5 %359 -%361 = OpAccessChain %101 %38 %76 -%362 = OpLoad %18 %361 -%363 = OpSampledImage %104 %360 %362 -%364 = OpImageSampleExplicitLod %22 %363 %80 Grad %80 %80 -%365 = OpLoad %22 %54 -%366 = OpFAdd %22 %365 %364 -OpStore %54 %366 -%367 = OpAccessChain %83 %28 %67 -%368 = OpLoad %5 %367 -%369 = OpAccessChain %101 %38 %67 -%370 = OpLoad %18 %369 -%371 = OpSampledImage %104 %368 %370 -%372 = OpImageSampleExplicitLod %22 %371 %80 Lod %69 -%373 = OpLoad %22 %54 -%374 = OpFAdd %22 %373 %372 -OpStore %54 %374 -%375 = OpAccessChain %83 %28 %75 -%376 = OpLoad %5 %375 -%377 = OpAccessChain %101 %38 %75 -%378 = OpLoad %18 %377 -%379 = OpSampledImage %104 %376 %378 -%380 = OpImageSampleExplicitLod %22 %379 %80 Lod %69 -%381 = OpLoad %22 %54 -%382 = OpFAdd %22 %381 %380 -OpStore %54 %382 -%383 = OpAccessChain %83 %28 %76 -%384 = OpLoad %5 %383 -%385 = OpAccessChain %101 %38 %76 -%386 = OpLoad %18 %385 -%387 = OpSampledImage %104 %384 %386 -%388 = OpImageSampleExplicitLod %22 %387 %80 Lod %69 -%389 = OpLoad %22 %54 -%390 = OpFAdd %22 %389 %388 -OpStore %54 %390 -%392 = OpAccessChain %391 %36 %67 -%393 = OpLoad %16 %392 -%394 = OpLoad %22 %54 -%395 = OpImageQuerySize %81 %393 -%396 = OpULessThan %160 %82 %395 -%397 = OpAll %154 %396 -OpSelectionMerge %398 None -OpBranchConditional %397 %399 %398 -%399 = OpLabel -OpImageWrite %393 %82 %394 -OpBranch %398 -%398 = OpLabel -%400 = OpAccessChain %391 %36 %75 -%401 = OpLoad %16 %400 -%402 = OpLoad %22 %54 -%403 = OpImageQuerySize %81 %401 -%404 = OpULessThan %160 %82 %403 -%405 = OpAll %154 %404 -OpSelectionMerge %406 None -OpBranchConditional %405 %407 %406 -%407 = OpLabel -OpImageWrite %401 %82 %402 -OpBranch %406 -%406 = OpLabel -%408 = OpAccessChain %391 %36 %76 -%409 = OpLoad %16 %408 -%410 = OpLoad %22 %54 -%411 = OpImageQuerySize %81 %409 -%412 = OpULessThan %160 %82 %411 -%413 = OpAll %154 %412 -OpSelectionMerge %414 None -OpBranchConditional %413 %415 %414 -%415 = OpLabel -OpImageWrite %409 %82 %410 -OpBranch %414 -%414 = OpLabel -%416 = OpLoad %23 %48 -%417 = OpLoad %3 %45 -%418 = OpCompositeConstruct %23 %417 %417 -%419 = OpIAdd %23 %416 %418 -%420 = OpConvertUToF %79 %419 -%421 = OpLoad %22 %54 -%422 = OpCompositeExtract %6 %420 0 -%423 = OpCompositeExtract %6 %420 1 -%424 = OpCompositeExtract %6 %420 0 -%425 = OpCompositeExtract %6 %420 1 -%426 = OpCompositeConstruct %22 %422 %423 %424 %425 -%427 = OpFAdd %22 %421 %426 -%428 = OpLoad %6 %51 -%429 = OpCompositeConstruct %22 %428 %428 %428 %428 -%430 = OpFAdd %22 %427 %429 -OpStore %62 %430 +%48 = OpTypePointer Input %3 +%47 = OpVariable %48 Input +%51 = OpTypePointer Output %22 +%50 = OpVariable %51 Output +%53 = OpTypeFunction %2 +%54 = OpTypePointer Uniform %4 +%55 = OpConstant %3 0 +%57 = OpConstantComposite %23 %55 %55 +%58 = OpConstant %6 0.0 +%59 = OpConstantComposite %22 %58 %58 %58 %58 +%60 = OpTypeVector %6 2 +%61 = OpConstantComposite %60 %58 %58 +%62 = OpTypeInt 32 1 +%63 = OpConstant %62 0 +%64 = OpTypeVector %62 2 +%65 = OpConstantComposite %64 %63 %63 +%67 = OpTypePointer Function %3 +%69 = OpTypePointer Function %23 +%71 = OpTypePointer Function %6 +%73 = OpTypePointer Function %22 +%75 = OpTypePointer Uniform %3 +%79 = OpTypePointer UniformConstant %5 +%97 = OpTypePointer UniformConstant %18 +%100 = OpTypeSampledImage %5 +%121 = OpTypePointer UniformConstant %14 +%124 = OpTypePointer UniformConstant %18 +%127 = OpTypeSampledImage %14 +%150 = OpTypeBool +%151 = OpConstantNull %22 +%157 = OpTypeVector %150 2 +%193 = OpTypePointer UniformConstant %10 +%196 = OpTypeVector %3 3 +%228 = OpTypePointer UniformConstant %12 +%388 = OpTypePointer UniformConstant %16 +%52 = OpFunction %2 None %53 +%45 = OpLabel +%68 = OpVariable %69 Function %57 +%72 = OpVariable %73 Function %59 +%66 = OpVariable %67 Function %55 +%70 = OpVariable %71 Function %58 +%49 = OpLoad %3 %47 +%46 = OpCompositeConstruct %21 %49 +%56 = OpAccessChain %54 %42 %55 +OpBranch %74 +%74 = OpLabel +%76 = OpAccessChain %75 %56 %55 +%77 = OpLoad %3 %76 +%78 = OpCompositeExtract %3 %46 0 +%80 = OpAccessChain %79 %24 %55 +%81 = OpLoad %5 %80 +%82 = OpImageQuerySizeLod %23 %81 %55 +%83 = OpLoad %23 %68 +%84 = OpIAdd %23 %83 %82 +OpStore %68 %84 +%85 = OpAccessChain %79 %24 %77 +%86 = OpLoad %5 %85 +%87 = OpImageQuerySizeLod %23 %86 %55 +%88 = OpLoad %23 %68 +%89 = OpIAdd %23 %88 %87 +OpStore %68 %89 +%90 = OpAccessChain %79 %24 %78 +%91 = OpLoad %5 %90 +%92 = OpImageQuerySizeLod %23 %91 %55 +%93 = OpLoad %23 %68 +%94 = OpIAdd %23 %93 %92 +OpStore %68 %94 +%95 = OpAccessChain %79 %28 %55 +%96 = OpLoad %5 %95 +%98 = OpAccessChain %97 %38 %55 +%99 = OpLoad %18 %98 +%101 = OpSampledImage %100 %96 %99 +%102 = OpImageGather %22 %101 %61 %55 +%103 = OpLoad %22 %72 +%104 = OpFAdd %22 %103 %102 +OpStore %72 %104 +%105 = OpAccessChain %79 %28 %77 +%106 = OpLoad %5 %105 +%107 = OpAccessChain %97 %38 %77 +%108 = OpLoad %18 %107 +%109 = OpSampledImage %100 %106 %108 +%110 = OpImageGather %22 %109 %61 %55 +%111 = OpLoad %22 %72 +%112 = OpFAdd %22 %111 %110 +OpStore %72 %112 +%113 = OpAccessChain %79 %28 %78 +%114 = OpLoad %5 %113 +%115 = OpAccessChain %97 %38 %78 +%116 = OpLoad %18 %115 +%117 = OpSampledImage %100 %114 %116 +%118 = OpImageGather %22 %117 %61 %55 +%119 = OpLoad %22 %72 +%120 = OpFAdd %22 %119 %118 +OpStore %72 %120 +%122 = OpAccessChain %121 %34 %55 +%123 = OpLoad %14 %122 +%125 = OpAccessChain %124 %40 %55 +%126 = OpLoad %18 %125 +%128 = OpSampledImage %127 %123 %126 +%129 = OpImageDrefGather %22 %128 %61 %58 +%130 = OpLoad %22 %72 +%131 = OpFAdd %22 %130 %129 +OpStore %72 %131 +%132 = OpAccessChain %121 %34 %77 +%133 = OpLoad %14 %132 +%134 = OpAccessChain %124 %40 %77 +%135 = OpLoad %18 %134 +%136 = OpSampledImage %127 %133 %135 +%137 = OpImageDrefGather %22 %136 %61 %58 +%138 = OpLoad %22 %72 +%139 = OpFAdd %22 %138 %137 +OpStore %72 %139 +%140 = OpAccessChain %121 %34 %78 +%141 = OpLoad %14 %140 +%142 = OpAccessChain %124 %40 %78 +%143 = OpLoad %18 %142 +%144 = OpSampledImage %127 %141 %143 +%145 = OpImageDrefGather %22 %144 %61 %58 +%146 = OpLoad %22 %72 +%147 = OpFAdd %22 %146 %145 +OpStore %72 %147 +%148 = OpAccessChain %79 %24 %55 +%149 = OpLoad %5 %148 +%152 = OpImageQueryLevels %62 %149 +%153 = OpULessThan %150 %63 %152 +OpSelectionMerge %154 None +OpBranchConditional %153 %155 %154 +%155 = OpLabel +%156 = OpImageQuerySizeLod %64 %149 %63 +%158 = OpULessThan %157 %65 %156 +%159 = OpAll %150 %158 +OpBranchConditional %159 %160 %154 +%160 = OpLabel +%161 = OpImageFetch %22 %149 %65 Lod %63 +OpBranch %154 +%154 = OpLabel +%162 = OpPhi %22 %151 %74 %151 %155 %161 %160 +%163 = OpLoad %22 %72 +%164 = OpFAdd %22 %163 %162 +OpStore %72 %164 +%165 = OpAccessChain %79 %24 %77 +%166 = OpLoad %5 %165 +%167 = OpImageQueryLevels %62 %166 +%168 = OpULessThan %150 %63 %167 +OpSelectionMerge %169 None +OpBranchConditional %168 %170 %169 +%170 = OpLabel +%171 = OpImageQuerySizeLod %64 %166 %63 +%172 = OpULessThan %157 %65 %171 +%173 = OpAll %150 %172 +OpBranchConditional %173 %174 %169 +%174 = OpLabel +%175 = OpImageFetch %22 %166 %65 Lod %63 +OpBranch %169 +%169 = OpLabel +%176 = OpPhi %22 %151 %154 %151 %170 %175 %174 +%177 = OpLoad %22 %72 +%178 = OpFAdd %22 %177 %176 +OpStore %72 %178 +%179 = OpAccessChain %79 %24 %78 +%180 = OpLoad %5 %179 +%181 = OpImageQueryLevels %62 %180 +%182 = OpULessThan %150 %63 %181 +OpSelectionMerge %183 None +OpBranchConditional %182 %184 %183 +%184 = OpLabel +%185 = OpImageQuerySizeLod %64 %180 %63 +%186 = OpULessThan %157 %65 %185 +%187 = OpAll %150 %186 +OpBranchConditional %187 %188 %183 +%188 = OpLabel +%189 = OpImageFetch %22 %180 %65 Lod %63 +OpBranch %183 +%183 = OpLabel +%190 = OpPhi %22 %151 %169 %151 %184 %189 %188 +%191 = OpLoad %22 %72 +%192 = OpFAdd %22 %191 %190 +OpStore %72 %192 +%194 = OpAccessChain %193 %30 %55 +%195 = OpLoad %10 %194 +%197 = OpImageQuerySizeLod %196 %195 %55 +%198 = OpCompositeExtract %3 %197 2 +%199 = OpLoad %3 %66 +%200 = OpIAdd %3 %199 %198 +OpStore %66 %200 +%201 = OpAccessChain %193 %30 %77 +%202 = OpLoad %10 %201 +%203 = OpImageQuerySizeLod %196 %202 %55 +%204 = OpCompositeExtract %3 %203 2 +%205 = OpLoad %3 %66 +%206 = OpIAdd %3 %205 %204 +OpStore %66 %206 +%207 = OpAccessChain %193 %30 %78 +%208 = OpLoad %10 %207 +%209 = OpImageQuerySizeLod %196 %208 %55 +%210 = OpCompositeExtract %3 %209 2 +%211 = OpLoad %3 %66 +%212 = OpIAdd %3 %211 %210 +OpStore %66 %212 +%213 = OpAccessChain %79 %28 %55 +%214 = OpLoad %5 %213 +%215 = OpImageQueryLevels %3 %214 +%216 = OpLoad %3 %66 +%217 = OpIAdd %3 %216 %215 +OpStore %66 %217 +%218 = OpAccessChain %79 %28 %77 +%219 = OpLoad %5 %218 +%220 = OpImageQueryLevels %3 %219 +%221 = OpLoad %3 %66 +%222 = OpIAdd %3 %221 %220 +OpStore %66 %222 +%223 = OpAccessChain %79 %28 %78 +%224 = OpLoad %5 %223 +%225 = OpImageQueryLevels %3 %224 +%226 = OpLoad %3 %66 +%227 = OpIAdd %3 %226 %225 +OpStore %66 %227 +%229 = OpAccessChain %228 %32 %55 +%230 = OpLoad %12 %229 +%231 = OpImageQuerySamples %3 %230 +%232 = OpLoad %3 %66 +%233 = OpIAdd %3 %232 %231 +OpStore %66 %233 +%234 = OpAccessChain %228 %32 %77 +%235 = OpLoad %12 %234 +%236 = OpImageQuerySamples %3 %235 +%237 = OpLoad %3 %66 +%238 = OpIAdd %3 %237 %236 +OpStore %66 %238 +%239 = OpAccessChain %228 %32 %78 +%240 = OpLoad %12 %239 +%241 = OpImageQuerySamples %3 %240 +%242 = OpLoad %3 %66 +%243 = OpIAdd %3 %242 %241 +OpStore %66 %243 +%244 = OpAccessChain %79 %28 %55 +%245 = OpLoad %5 %244 +%246 = OpAccessChain %97 %38 %55 +%247 = OpLoad %18 %246 +%248 = OpSampledImage %100 %245 %247 +%249 = OpImageSampleImplicitLod %22 %248 %61 +%250 = OpLoad %22 %72 +%251 = OpFAdd %22 %250 %249 +OpStore %72 %251 +%252 = OpAccessChain %79 %28 %77 +%253 = OpLoad %5 %252 +%254 = OpAccessChain %97 %38 %77 +%255 = OpLoad %18 %254 +%256 = OpSampledImage %100 %253 %255 +%257 = OpImageSampleImplicitLod %22 %256 %61 +%258 = OpLoad %22 %72 +%259 = OpFAdd %22 %258 %257 +OpStore %72 %259 +%260 = OpAccessChain %79 %28 %78 +%261 = OpLoad %5 %260 +%262 = OpAccessChain %97 %38 %78 +%263 = OpLoad %18 %262 +%264 = OpSampledImage %100 %261 %263 +%265 = OpImageSampleImplicitLod %22 %264 %61 +%266 = OpLoad %22 %72 +%267 = OpFAdd %22 %266 %265 +OpStore %72 %267 +%268 = OpAccessChain %79 %28 %55 +%269 = OpLoad %5 %268 +%270 = OpAccessChain %97 %38 %55 +%271 = OpLoad %18 %270 +%272 = OpSampledImage %100 %269 %271 +%273 = OpImageSampleImplicitLod %22 %272 %61 Bias %58 +%274 = OpLoad %22 %72 +%275 = OpFAdd %22 %274 %273 +OpStore %72 %275 +%276 = OpAccessChain %79 %28 %77 +%277 = OpLoad %5 %276 +%278 = OpAccessChain %97 %38 %77 +%279 = OpLoad %18 %278 +%280 = OpSampledImage %100 %277 %279 +%281 = OpImageSampleImplicitLod %22 %280 %61 Bias %58 +%282 = OpLoad %22 %72 +%283 = OpFAdd %22 %282 %281 +OpStore %72 %283 +%284 = OpAccessChain %79 %28 %78 +%285 = OpLoad %5 %284 +%286 = OpAccessChain %97 %38 %78 +%287 = OpLoad %18 %286 +%288 = OpSampledImage %100 %285 %287 +%289 = OpImageSampleImplicitLod %22 %288 %61 Bias %58 +%290 = OpLoad %22 %72 +%291 = OpFAdd %22 %290 %289 +OpStore %72 %291 +%292 = OpAccessChain %121 %34 %55 +%293 = OpLoad %14 %292 +%294 = OpAccessChain %124 %40 %55 +%295 = OpLoad %18 %294 +%296 = OpSampledImage %127 %293 %295 +%297 = OpImageSampleDrefImplicitLod %6 %296 %61 %58 +%298 = OpLoad %6 %70 +%299 = OpFAdd %6 %298 %297 +OpStore %70 %299 +%300 = OpAccessChain %121 %34 %77 +%301 = OpLoad %14 %300 +%302 = OpAccessChain %124 %40 %77 +%303 = OpLoad %18 %302 +%304 = OpSampledImage %127 %301 %303 +%305 = OpImageSampleDrefImplicitLod %6 %304 %61 %58 +%306 = OpLoad %6 %70 +%307 = OpFAdd %6 %306 %305 +OpStore %70 %307 +%308 = OpAccessChain %121 %34 %78 +%309 = OpLoad %14 %308 +%310 = OpAccessChain %124 %40 %78 +%311 = OpLoad %18 %310 +%312 = OpSampledImage %127 %309 %311 +%313 = OpImageSampleDrefImplicitLod %6 %312 %61 %58 +%314 = OpLoad %6 %70 +%315 = OpFAdd %6 %314 %313 +OpStore %70 %315 +%316 = OpAccessChain %121 %34 %55 +%317 = OpLoad %14 %316 +%318 = OpAccessChain %124 %40 %55 +%319 = OpLoad %18 %318 +%320 = OpSampledImage %127 %317 %319 +%321 = OpImageSampleDrefExplicitLod %6 %320 %61 %58 Lod %58 +%322 = OpLoad %6 %70 +%323 = OpFAdd %6 %322 %321 +OpStore %70 %323 +%324 = OpAccessChain %121 %34 %77 +%325 = OpLoad %14 %324 +%326 = OpAccessChain %124 %40 %77 +%327 = OpLoad %18 %326 +%328 = OpSampledImage %127 %325 %327 +%329 = OpImageSampleDrefExplicitLod %6 %328 %61 %58 Lod %58 +%330 = OpLoad %6 %70 +%331 = OpFAdd %6 %330 %329 +OpStore %70 %331 +%332 = OpAccessChain %121 %34 %78 +%333 = OpLoad %14 %332 +%334 = OpAccessChain %124 %40 %78 +%335 = OpLoad %18 %334 +%336 = OpSampledImage %127 %333 %335 +%337 = OpImageSampleDrefExplicitLod %6 %336 %61 %58 Lod %58 +%338 = OpLoad %6 %70 +%339 = OpFAdd %6 %338 %337 +OpStore %70 %339 +%340 = OpAccessChain %79 %28 %55 +%341 = OpLoad %5 %340 +%342 = OpAccessChain %97 %38 %55 +%343 = OpLoad %18 %342 +%344 = OpSampledImage %100 %341 %343 +%345 = OpImageSampleExplicitLod %22 %344 %61 Grad %61 %61 +%346 = OpLoad %22 %72 +%347 = OpFAdd %22 %346 %345 +OpStore %72 %347 +%348 = OpAccessChain %79 %28 %77 +%349 = OpLoad %5 %348 +%350 = OpAccessChain %97 %38 %77 +%351 = OpLoad %18 %350 +%352 = OpSampledImage %100 %349 %351 +%353 = OpImageSampleExplicitLod %22 %352 %61 Grad %61 %61 +%354 = OpLoad %22 %72 +%355 = OpFAdd %22 %354 %353 +OpStore %72 %355 +%356 = OpAccessChain %79 %28 %78 +%357 = OpLoad %5 %356 +%358 = OpAccessChain %97 %38 %78 +%359 = OpLoad %18 %358 +%360 = OpSampledImage %100 %357 %359 +%361 = OpImageSampleExplicitLod %22 %360 %61 Grad %61 %61 +%362 = OpLoad %22 %72 +%363 = OpFAdd %22 %362 %361 +OpStore %72 %363 +%364 = OpAccessChain %79 %28 %55 +%365 = OpLoad %5 %364 +%366 = OpAccessChain %97 %38 %55 +%367 = OpLoad %18 %366 +%368 = OpSampledImage %100 %365 %367 +%369 = OpImageSampleExplicitLod %22 %368 %61 Lod %58 +%370 = OpLoad %22 %72 +%371 = OpFAdd %22 %370 %369 +OpStore %72 %371 +%372 = OpAccessChain %79 %28 %77 +%373 = OpLoad %5 %372 +%374 = OpAccessChain %97 %38 %77 +%375 = OpLoad %18 %374 +%376 = OpSampledImage %100 %373 %375 +%377 = OpImageSampleExplicitLod %22 %376 %61 Lod %58 +%378 = OpLoad %22 %72 +%379 = OpFAdd %22 %378 %377 +OpStore %72 %379 +%380 = OpAccessChain %79 %28 %78 +%381 = OpLoad %5 %380 +%382 = OpAccessChain %97 %38 %78 +%383 = OpLoad %18 %382 +%384 = OpSampledImage %100 %381 %383 +%385 = OpImageSampleExplicitLod %22 %384 %61 Lod %58 +%386 = OpLoad %22 %72 +%387 = OpFAdd %22 %386 %385 +OpStore %72 %387 +%389 = OpAccessChain %388 %36 %55 +%390 = OpLoad %16 %389 +%391 = OpLoad %22 %72 +%392 = OpImageQuerySize %64 %390 +%393 = OpULessThan %157 %65 %392 +%394 = OpAll %150 %393 +OpSelectionMerge %395 None +OpBranchConditional %394 %396 %395 +%396 = OpLabel +OpImageWrite %390 %65 %391 +OpBranch %395 +%395 = OpLabel +%397 = OpAccessChain %388 %36 %77 +%398 = OpLoad %16 %397 +%399 = OpLoad %22 %72 +%400 = OpImageQuerySize %64 %398 +%401 = OpULessThan %157 %65 %400 +%402 = OpAll %150 %401 +OpSelectionMerge %403 None +OpBranchConditional %402 %404 %403 +%404 = OpLabel +OpImageWrite %398 %65 %399 +OpBranch %403 +%403 = OpLabel +%405 = OpAccessChain %388 %36 %78 +%406 = OpLoad %16 %405 +%407 = OpLoad %22 %72 +%408 = OpImageQuerySize %64 %406 +%409 = OpULessThan %157 %65 %408 +%410 = OpAll %150 %409 +OpSelectionMerge %411 None +OpBranchConditional %410 %412 %411 +%412 = OpLabel +OpImageWrite %406 %65 %407 +OpBranch %411 +%411 = OpLabel +%413 = OpLoad %23 %68 +%414 = OpLoad %3 %66 +%415 = OpCompositeConstruct %23 %414 %414 +%416 = OpIAdd %23 %413 %415 +%417 = OpConvertUToF %60 %416 +%418 = OpLoad %22 %72 +%419 = OpCompositeExtract %6 %417 0 +%420 = OpCompositeExtract %6 %417 1 +%421 = OpCompositeExtract %6 %417 0 +%422 = OpCompositeExtract %6 %417 1 +%423 = OpCompositeConstruct %22 %419 %420 %421 %422 +%424 = OpFAdd %22 %418 %423 +%425 = OpLoad %6 %70 +%426 = OpCompositeConstruct %22 %425 %425 %425 %425 +%427 = OpFAdd %22 %424 %426 +OpStore %50 %427 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/binding-buffer-arrays.spvasm b/tests/out/spv/binding-buffer-arrays.spvasm index bc89271fd..050372036 100644 --- a/tests/out/spv/binding-buffer-arrays.spvasm +++ b/tests/out/spv/binding-buffer-arrays.spvasm @@ -8,8 +8,8 @@ OpExtension "SPV_KHR_storage_buffer_storage_class" OpExtension "SPV_EXT_descriptor_indexing" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %26 "main" %21 %24 -OpExecutionMode %26 OriginUpperLeft +OpEntryPoint Fragment %23 "main" %18 %21 +OpExecutionMode %23 OriginUpperLeft OpMemberDecorate %4 0 Offset 0 OpMemberDecorate %5 0 Offset 0 OpMemberDecorate %8 0 Offset 0 @@ -21,9 +21,9 @@ OpDecorate %13 DescriptorSet 0 OpDecorate %13 Binding 10 OpDecorate %14 Block OpMemberDecorate %14 0 Offset 0 +OpDecorate %18 Location 0 +OpDecorate %18 Flat OpDecorate %21 Location 0 -OpDecorate %21 Flat -OpDecorate %24 Location 0 OpDecorate %53 NonUniform %2 = OpTypeVoid %3 = OpTypeInt 32 0 @@ -39,62 +39,61 @@ OpDecorate %53 NonUniform %14 = OpTypeStruct %4 %15 = OpTypePointer Uniform %14 %13 = OpVariable %15 Uniform -%17 = OpTypePointer Function %3 -%18 = OpConstantNull %3 -%22 = OpTypePointer Input %3 -%21 = OpVariable %22 Input -%25 = OpTypePointer Output %3 -%24 = OpVariable %25 Output -%27 = OpTypeFunction %2 -%28 = OpTypePointer Uniform %4 -%29 = OpConstant %3 0 -%31 = OpTypePointer StorageBuffer %6 -%33 = OpTypePointer Uniform %3 -%37 = OpTypePointer StorageBuffer %5 -%38 = OpTypePointer StorageBuffer %3 -%44 = OpTypeBool -%26 = OpFunction %2 None %27 -%19 = OpLabel -%16 = OpVariable %17 Function %18 -%23 = OpLoad %3 %21 -%20 = OpCompositeConstruct %8 %23 -%30 = OpAccessChain %28 %13 %29 -OpBranch %32 -%32 = OpLabel -%34 = OpAccessChain %33 %30 %29 -%35 = OpLoad %3 %34 -%36 = OpCompositeExtract %3 %20 0 -OpStore %16 %29 -%39 = OpAccessChain %38 %9 %29 %29 -%40 = OpLoad %3 %39 -%41 = OpLoad %3 %16 -%42 = OpIAdd %3 %41 %40 -OpStore %16 %42 -%43 = OpULessThan %44 %35 %7 +%19 = OpTypePointer Input %3 +%18 = OpVariable %19 Input +%22 = OpTypePointer Output %3 +%21 = OpVariable %22 Output +%24 = OpTypeFunction %2 +%25 = OpTypePointer Uniform %4 +%26 = OpConstant %3 0 +%28 = OpTypePointer StorageBuffer %6 +%30 = OpTypePointer Function %3 +%32 = OpTypePointer Uniform %3 +%36 = OpTypePointer StorageBuffer %5 +%37 = OpTypePointer StorageBuffer %3 +%43 = OpTypeBool +%45 = OpConstantNull %3 +%23 = OpFunction %2 None %24 +%16 = OpLabel +%29 = OpVariable %30 Function %26 +%20 = OpLoad %3 %18 +%17 = OpCompositeConstruct %8 %20 +%27 = OpAccessChain %25 %13 %26 +OpBranch %31 +%31 = OpLabel +%33 = OpAccessChain %32 %27 %26 +%34 = OpLoad %3 %33 +%35 = OpCompositeExtract %3 %17 0 +%38 = OpAccessChain %37 %9 %26 %26 +%39 = OpLoad %3 %38 +%40 = OpLoad %3 %29 +%41 = OpIAdd %3 %40 %39 +OpStore %29 %41 +%42 = OpULessThan %43 %34 %7 OpSelectionMerge %46 None -OpBranchConditional %43 %47 %46 +OpBranchConditional %42 %47 %46 %47 = OpLabel -%45 = OpAccessChain %38 %9 %35 %29 -%48 = OpLoad %3 %45 +%44 = OpAccessChain %37 %9 %34 %26 +%48 = OpLoad %3 %44 OpBranch %46 %46 = OpLabel -%49 = OpPhi %3 %18 %32 %48 %47 -%50 = OpLoad %3 %16 +%49 = OpPhi %3 %45 %31 %48 %47 +%50 = OpLoad %3 %29 %51 = OpIAdd %3 %50 %49 -OpStore %16 %51 -%52 = OpULessThan %44 %36 %7 +OpStore %29 %51 +%52 = OpULessThan %43 %35 %7 OpSelectionMerge %54 None OpBranchConditional %52 %55 %54 %55 = OpLabel -%53 = OpAccessChain %38 %9 %36 %29 +%53 = OpAccessChain %37 %9 %35 %26 %56 = OpLoad %3 %53 OpBranch %54 %54 = OpLabel -%57 = OpPhi %3 %18 %46 %56 %55 -%58 = OpLoad %3 %16 +%57 = OpPhi %3 %45 %46 %56 %55 +%58 = OpLoad %3 %29 %59 = OpIAdd %3 %58 %57 -OpStore %16 %59 -%60 = OpLoad %3 %16 -OpStore %24 %60 +OpStore %29 %59 +%60 = OpLoad %3 %29 +OpStore %21 %60 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bitcast.spvasm b/tests/out/spv/bitcast.spvasm index f8b0c9327..43dfa8df3 100644 --- a/tests/out/spv/bitcast.spvasm +++ b/tests/out/spv/bitcast.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 76 +; Bound: 67 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %43 "main" -OpExecutionMode %43 LocalSize 1 1 1 +OpEntryPoint GLCompute %16 "main" +OpExecutionMode %16 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 2 @@ -20,85 +20,67 @@ OpExecutionMode %43 LocalSize 1 1 1 %11 = OpTypeVector %12 2 %13 = OpTypeVector %12 3 %14 = OpTypeVector %12 4 -%16 = OpTypePointer Function %3 -%17 = OpConstantNull %3 -%19 = OpTypePointer Function %5 -%20 = OpConstantNull %5 -%22 = OpTypePointer Function %6 -%23 = OpConstantNull %6 -%25 = OpTypePointer Function %7 -%26 = OpConstantNull %7 -%28 = OpTypePointer Function %9 -%29 = OpConstantNull %9 -%31 = OpTypePointer Function %10 -%32 = OpConstantNull %10 -%34 = OpTypePointer Function %11 -%35 = OpConstantNull %11 -%37 = OpTypePointer Function %13 -%38 = OpConstantNull %13 -%40 = OpTypePointer Function %14 -%41 = OpConstantNull %14 -%44 = OpTypeFunction %2 -%45 = OpConstant %4 0 -%46 = OpConstant %8 0 -%47 = OpConstant %12 0.0 -%43 = OpFunction %2 None %44 -%42 = OpLabel -%33 = OpVariable %34 Function %35 -%24 = OpVariable %25 Function %26 -%15 = OpVariable %16 Function %17 -%36 = OpVariable %37 Function %38 -%27 = OpVariable %28 Function %29 -%18 = OpVariable %19 Function %20 -%39 = OpVariable %40 Function %41 -%30 = OpVariable %31 Function %32 -%21 = OpVariable %22 Function %23 +%17 = OpTypeFunction %2 +%18 = OpConstant %4 0 +%19 = OpConstantComposite %3 %18 %18 +%20 = OpConstantComposite %5 %18 %18 %18 +%21 = OpConstantComposite %6 %18 %18 %18 %18 +%22 = OpConstant %8 0 +%23 = OpConstantComposite %7 %22 %22 +%24 = OpConstantComposite %9 %22 %22 %22 +%25 = OpConstantComposite %10 %22 %22 %22 %22 +%26 = OpConstant %12 0.0 +%27 = OpConstantComposite %11 %26 %26 +%28 = OpConstantComposite %13 %26 %26 %26 +%29 = OpConstantComposite %14 %26 %26 %26 %26 +%31 = OpTypePointer Function %3 +%33 = OpTypePointer Function %5 +%35 = OpTypePointer Function %6 +%37 = OpTypePointer Function %7 +%39 = OpTypePointer Function %9 +%41 = OpTypePointer Function %10 +%43 = OpTypePointer Function %11 +%45 = OpTypePointer Function %13 +%47 = OpTypePointer Function %14 +%16 = OpFunction %2 None %17 +%15 = OpLabel +%42 = OpVariable %43 Function %27 +%36 = OpVariable %37 Function %23 +%30 = OpVariable %31 Function %19 +%44 = OpVariable %45 Function %28 +%38 = OpVariable %39 Function %24 +%32 = OpVariable %33 Function %20 +%46 = OpVariable %47 Function %29 +%40 = OpVariable %41 Function %25 +%34 = OpVariable %35 Function %21 OpBranch %48 %48 = OpLabel -%49 = OpCompositeConstruct %3 %45 %45 -OpStore %15 %49 -%50 = OpCompositeConstruct %5 %45 %45 %45 -OpStore %18 %50 -%51 = OpCompositeConstruct %6 %45 %45 %45 %45 -OpStore %21 %51 -%52 = OpCompositeConstruct %7 %46 %46 -OpStore %24 %52 -%53 = OpCompositeConstruct %9 %46 %46 %46 -OpStore %27 %53 -%54 = OpCompositeConstruct %10 %46 %46 %46 %46 -OpStore %30 %54 -%55 = OpCompositeConstruct %11 %47 %47 -OpStore %33 %55 -%56 = OpCompositeConstruct %13 %47 %47 %47 -OpStore %36 %56 -%57 = OpCompositeConstruct %14 %47 %47 %47 %47 -OpStore %39 %57 -%58 = OpLoad %3 %15 -%59 = OpBitcast %7 %58 -OpStore %24 %59 -%60 = OpLoad %5 %18 -%61 = OpBitcast %9 %60 -OpStore %27 %61 -%62 = OpLoad %6 %21 -%63 = OpBitcast %10 %62 -OpStore %30 %63 -%64 = OpLoad %7 %24 -%65 = OpBitcast %3 %64 -OpStore %15 %65 -%66 = OpLoad %9 %27 -%67 = OpBitcast %5 %66 -OpStore %18 %67 -%68 = OpLoad %10 %30 -%69 = OpBitcast %6 %68 -OpStore %21 %69 -%70 = OpLoad %3 %15 -%71 = OpBitcast %11 %70 -OpStore %33 %71 -%72 = OpLoad %5 %18 -%73 = OpBitcast %13 %72 -OpStore %36 %73 -%74 = OpLoad %6 %21 -%75 = OpBitcast %14 %74 -OpStore %39 %75 +%49 = OpLoad %3 %30 +%50 = OpBitcast %7 %49 +OpStore %36 %50 +%51 = OpLoad %5 %32 +%52 = OpBitcast %9 %51 +OpStore %38 %52 +%53 = OpLoad %6 %34 +%54 = OpBitcast %10 %53 +OpStore %40 %54 +%55 = OpLoad %7 %36 +%56 = OpBitcast %3 %55 +OpStore %30 %56 +%57 = OpLoad %9 %38 +%58 = OpBitcast %5 %57 +OpStore %32 %58 +%59 = OpLoad %10 %40 +%60 = OpBitcast %6 %59 +OpStore %34 %60 +%61 = OpLoad %3 %30 +%62 = OpBitcast %11 %61 +OpStore %42 %62 +%63 = OpLoad %5 %32 +%64 = OpBitcast %13 %63 +OpStore %44 %64 +%65 = OpLoad %6 %34 +%66 = OpBitcast %14 %65 +OpStore %46 %66 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bits.spvasm b/tests/out/spv/bits.spvasm index 674167359..a77c4470a 100644 --- a/tests/out/spv/bits.spvasm +++ b/tests/out/spv/bits.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 165 +; Bound: 155 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %45 "main" -OpExecutionMode %45 LocalSize 1 1 1 +OpEntryPoint GLCompute %15 "main" +OpExecutionMode %15 LocalSize 1 1 1 %2 = OpTypeVoid %3 = OpTypeInt 32 1 %4 = OpTypeVector %3 2 @@ -19,215 +19,195 @@ OpExecutionMode %45 LocalSize 1 1 1 %12 = OpTypeFloat 32 %11 = OpTypeVector %12 2 %13 = OpTypeVector %12 4 -%15 = OpTypePointer Function %3 -%16 = OpConstantNull %3 -%18 = OpTypePointer Function %4 -%19 = OpConstantNull %4 -%21 = OpTypePointer Function %5 -%22 = OpConstantNull %5 -%24 = OpTypePointer Function %6 -%25 = OpConstantNull %6 -%27 = OpTypePointer Function %7 -%28 = OpConstantNull %7 -%30 = OpTypePointer Function %8 -%31 = OpConstantNull %8 -%33 = OpTypePointer Function %9 -%34 = OpConstantNull %9 -%36 = OpTypePointer Function %10 -%37 = OpConstantNull %10 -%39 = OpTypePointer Function %11 -%40 = OpConstantNull %11 -%42 = OpTypePointer Function %13 -%43 = OpConstantNull %13 -%46 = OpTypeFunction %2 -%47 = OpConstant %3 0 -%48 = OpConstant %7 0 -%49 = OpConstant %12 0.0 -%50 = OpConstant %7 5 -%51 = OpConstant %7 10 -%45 = OpFunction %2 None %46 -%44 = OpLabel -%41 = OpVariable %42 Function %43 -%32 = OpVariable %33 Function %34 -%23 = OpVariable %24 Function %25 -%14 = OpVariable %15 Function %16 -%35 = OpVariable %36 Function %37 -%26 = OpVariable %27 Function %28 -%17 = OpVariable %18 Function %19 -%38 = OpVariable %39 Function %40 -%29 = OpVariable %30 Function %31 -%20 = OpVariable %21 Function %22 -OpBranch %52 -%52 = OpLabel -OpStore %14 %47 -%53 = OpCompositeConstruct %4 %47 %47 -OpStore %17 %53 -%54 = OpCompositeConstruct %5 %47 %47 %47 -OpStore %20 %54 -%55 = OpCompositeConstruct %6 %47 %47 %47 %47 -OpStore %23 %55 -OpStore %26 %48 -%56 = OpCompositeConstruct %8 %48 %48 -OpStore %29 %56 -%57 = OpCompositeConstruct %9 %48 %48 %48 -OpStore %32 %57 -%58 = OpCompositeConstruct %10 %48 %48 %48 %48 -OpStore %35 %58 -%59 = OpCompositeConstruct %11 %49 %49 -OpStore %38 %59 -%60 = OpCompositeConstruct %13 %49 %49 %49 %49 -OpStore %41 %60 -%61 = OpLoad %13 %41 -%62 = OpExtInst %7 %1 PackSnorm4x8 %61 -OpStore %26 %62 -%63 = OpLoad %13 %41 -%64 = OpExtInst %7 %1 PackUnorm4x8 %63 -OpStore %26 %64 -%65 = OpLoad %11 %38 -%66 = OpExtInst %7 %1 PackSnorm2x16 %65 -OpStore %26 %66 -%67 = OpLoad %11 %38 -%68 = OpExtInst %7 %1 PackUnorm2x16 %67 -OpStore %26 %68 -%69 = OpLoad %11 %38 -%70 = OpExtInst %7 %1 PackHalf2x16 %69 -OpStore %26 %70 -%71 = OpLoad %7 %26 -%72 = OpExtInst %13 %1 UnpackSnorm4x8 %71 -OpStore %41 %72 -%73 = OpLoad %7 %26 -%74 = OpExtInst %13 %1 UnpackUnorm4x8 %73 -OpStore %41 %74 -%75 = OpLoad %7 %26 -%76 = OpExtInst %11 %1 UnpackSnorm2x16 %75 -OpStore %38 %76 -%77 = OpLoad %7 %26 -%78 = OpExtInst %11 %1 UnpackUnorm2x16 %77 -OpStore %38 %78 -%79 = OpLoad %7 %26 -%80 = OpExtInst %11 %1 UnpackHalf2x16 %79 -OpStore %38 %80 -%81 = OpLoad %3 %14 -%82 = OpLoad %3 %14 -%83 = OpBitFieldInsert %3 %81 %82 %50 %51 -OpStore %14 %83 -%84 = OpLoad %4 %17 -%85 = OpLoad %4 %17 -%86 = OpBitFieldInsert %4 %84 %85 %50 %51 -OpStore %17 %86 -%87 = OpLoad %5 %20 -%88 = OpLoad %5 %20 -%89 = OpBitFieldInsert %5 %87 %88 %50 %51 -OpStore %20 %89 -%90 = OpLoad %6 %23 -%91 = OpLoad %6 %23 -%92 = OpBitFieldInsert %6 %90 %91 %50 %51 -OpStore %23 %92 -%93 = OpLoad %7 %26 -%94 = OpLoad %7 %26 -%95 = OpBitFieldInsert %7 %93 %94 %50 %51 -OpStore %26 %95 -%96 = OpLoad %8 %29 -%97 = OpLoad %8 %29 -%98 = OpBitFieldInsert %8 %96 %97 %50 %51 -OpStore %29 %98 -%99 = OpLoad %9 %32 -%100 = OpLoad %9 %32 -%101 = OpBitFieldInsert %9 %99 %100 %50 %51 -OpStore %32 %101 -%102 = OpLoad %10 %35 -%103 = OpLoad %10 %35 -%104 = OpBitFieldInsert %10 %102 %103 %50 %51 -OpStore %35 %104 -%105 = OpLoad %3 %14 -%106 = OpBitFieldSExtract %3 %105 %50 %51 -OpStore %14 %106 -%107 = OpLoad %4 %17 -%108 = OpBitFieldSExtract %4 %107 %50 %51 -OpStore %17 %108 -%109 = OpLoad %5 %20 -%110 = OpBitFieldSExtract %5 %109 %50 %51 -OpStore %20 %110 -%111 = OpLoad %6 %23 -%112 = OpBitFieldSExtract %6 %111 %50 %51 -OpStore %23 %112 -%113 = OpLoad %7 %26 -%114 = OpBitFieldUExtract %7 %113 %50 %51 -OpStore %26 %114 -%115 = OpLoad %8 %29 -%116 = OpBitFieldUExtract %8 %115 %50 %51 -OpStore %29 %116 -%117 = OpLoad %9 %32 -%118 = OpBitFieldUExtract %9 %117 %50 %51 -OpStore %32 %118 -%119 = OpLoad %10 %35 -%120 = OpBitFieldUExtract %10 %119 %50 %51 -OpStore %35 %120 -%121 = OpLoad %3 %14 -%122 = OpExtInst %3 %1 FindILsb %121 -OpStore %14 %122 -%123 = OpLoad %8 %29 -%124 = OpExtInst %8 %1 FindILsb %123 -OpStore %29 %124 -%125 = OpLoad %5 %20 -%126 = OpExtInst %5 %1 FindSMsb %125 -OpStore %20 %126 -%127 = OpLoad %9 %32 -%128 = OpExtInst %9 %1 FindUMsb %127 -OpStore %32 %128 -%129 = OpLoad %3 %14 -%130 = OpExtInst %3 %1 FindSMsb %129 -OpStore %14 %130 -%131 = OpLoad %7 %26 -%132 = OpExtInst %7 %1 FindUMsb %131 -OpStore %26 %132 -%133 = OpLoad %3 %14 -%134 = OpBitCount %3 %133 -OpStore %14 %134 -%135 = OpLoad %4 %17 -%136 = OpBitCount %4 %135 -OpStore %17 %136 -%137 = OpLoad %5 %20 -%138 = OpBitCount %5 %137 -OpStore %20 %138 -%139 = OpLoad %6 %23 -%140 = OpBitCount %6 %139 -OpStore %23 %140 -%141 = OpLoad %7 %26 -%142 = OpBitCount %7 %141 -OpStore %26 %142 -%143 = OpLoad %8 %29 -%144 = OpBitCount %8 %143 -OpStore %29 %144 -%145 = OpLoad %9 %32 -%146 = OpBitCount %9 %145 -OpStore %32 %146 -%147 = OpLoad %10 %35 -%148 = OpBitCount %10 %147 -OpStore %35 %148 -%149 = OpLoad %3 %14 -%150 = OpBitReverse %3 %149 -OpStore %14 %150 -%151 = OpLoad %4 %17 -%152 = OpBitReverse %4 %151 -OpStore %17 %152 -%153 = OpLoad %5 %20 -%154 = OpBitReverse %5 %153 -OpStore %20 %154 -%155 = OpLoad %6 %23 -%156 = OpBitReverse %6 %155 -OpStore %23 %156 -%157 = OpLoad %7 %26 -%158 = OpBitReverse %7 %157 -OpStore %26 %158 -%159 = OpLoad %8 %29 -%160 = OpBitReverse %8 %159 -OpStore %29 %160 -%161 = OpLoad %9 %32 -%162 = OpBitReverse %9 %161 -OpStore %32 %162 -%163 = OpLoad %10 %35 -%164 = OpBitReverse %10 %163 -OpStore %35 %164 +%16 = OpTypeFunction %2 +%17 = OpConstant %3 0 +%18 = OpConstantComposite %4 %17 %17 +%19 = OpConstantComposite %5 %17 %17 %17 +%20 = OpConstantComposite %6 %17 %17 %17 %17 +%21 = OpConstant %7 0 +%22 = OpConstantComposite %8 %21 %21 +%23 = OpConstantComposite %9 %21 %21 %21 +%24 = OpConstantComposite %10 %21 %21 %21 %21 +%25 = OpConstant %12 0.0 +%26 = OpConstantComposite %11 %25 %25 +%27 = OpConstantComposite %13 %25 %25 %25 %25 +%28 = OpConstant %7 5 +%29 = OpConstant %7 10 +%31 = OpTypePointer Function %3 +%33 = OpTypePointer Function %4 +%35 = OpTypePointer Function %5 +%37 = OpTypePointer Function %6 +%39 = OpTypePointer Function %7 +%41 = OpTypePointer Function %8 +%43 = OpTypePointer Function %9 +%45 = OpTypePointer Function %10 +%47 = OpTypePointer Function %11 +%49 = OpTypePointer Function %13 +%15 = OpFunction %2 None %16 +%14 = OpLabel +%48 = OpVariable %49 Function %27 +%42 = OpVariable %43 Function %23 +%36 = OpVariable %37 Function %20 +%30 = OpVariable %31 Function %17 +%44 = OpVariable %45 Function %24 +%38 = OpVariable %39 Function %21 +%32 = OpVariable %33 Function %18 +%46 = OpVariable %47 Function %26 +%40 = OpVariable %41 Function %22 +%34 = OpVariable %35 Function %19 +OpBranch %50 +%50 = OpLabel +%51 = OpLoad %13 %48 +%52 = OpExtInst %7 %1 PackSnorm4x8 %51 +OpStore %38 %52 +%53 = OpLoad %13 %48 +%54 = OpExtInst %7 %1 PackUnorm4x8 %53 +OpStore %38 %54 +%55 = OpLoad %11 %46 +%56 = OpExtInst %7 %1 PackSnorm2x16 %55 +OpStore %38 %56 +%57 = OpLoad %11 %46 +%58 = OpExtInst %7 %1 PackUnorm2x16 %57 +OpStore %38 %58 +%59 = OpLoad %11 %46 +%60 = OpExtInst %7 %1 PackHalf2x16 %59 +OpStore %38 %60 +%61 = OpLoad %7 %38 +%62 = OpExtInst %13 %1 UnpackSnorm4x8 %61 +OpStore %48 %62 +%63 = OpLoad %7 %38 +%64 = OpExtInst %13 %1 UnpackUnorm4x8 %63 +OpStore %48 %64 +%65 = OpLoad %7 %38 +%66 = OpExtInst %11 %1 UnpackSnorm2x16 %65 +OpStore %46 %66 +%67 = OpLoad %7 %38 +%68 = OpExtInst %11 %1 UnpackUnorm2x16 %67 +OpStore %46 %68 +%69 = OpLoad %7 %38 +%70 = OpExtInst %11 %1 UnpackHalf2x16 %69 +OpStore %46 %70 +%71 = OpLoad %3 %30 +%72 = OpLoad %3 %30 +%73 = OpBitFieldInsert %3 %71 %72 %28 %29 +OpStore %30 %73 +%74 = OpLoad %4 %32 +%75 = OpLoad %4 %32 +%76 = OpBitFieldInsert %4 %74 %75 %28 %29 +OpStore %32 %76 +%77 = OpLoad %5 %34 +%78 = OpLoad %5 %34 +%79 = OpBitFieldInsert %5 %77 %78 %28 %29 +OpStore %34 %79 +%80 = OpLoad %6 %36 +%81 = OpLoad %6 %36 +%82 = OpBitFieldInsert %6 %80 %81 %28 %29 +OpStore %36 %82 +%83 = OpLoad %7 %38 +%84 = OpLoad %7 %38 +%85 = OpBitFieldInsert %7 %83 %84 %28 %29 +OpStore %38 %85 +%86 = OpLoad %8 %40 +%87 = OpLoad %8 %40 +%88 = OpBitFieldInsert %8 %86 %87 %28 %29 +OpStore %40 %88 +%89 = OpLoad %9 %42 +%90 = OpLoad %9 %42 +%91 = OpBitFieldInsert %9 %89 %90 %28 %29 +OpStore %42 %91 +%92 = OpLoad %10 %44 +%93 = OpLoad %10 %44 +%94 = OpBitFieldInsert %10 %92 %93 %28 %29 +OpStore %44 %94 +%95 = OpLoad %3 %30 +%96 = OpBitFieldSExtract %3 %95 %28 %29 +OpStore %30 %96 +%97 = OpLoad %4 %32 +%98 = OpBitFieldSExtract %4 %97 %28 %29 +OpStore %32 %98 +%99 = OpLoad %5 %34 +%100 = OpBitFieldSExtract %5 %99 %28 %29 +OpStore %34 %100 +%101 = OpLoad %6 %36 +%102 = OpBitFieldSExtract %6 %101 %28 %29 +OpStore %36 %102 +%103 = OpLoad %7 %38 +%104 = OpBitFieldUExtract %7 %103 %28 %29 +OpStore %38 %104 +%105 = OpLoad %8 %40 +%106 = OpBitFieldUExtract %8 %105 %28 %29 +OpStore %40 %106 +%107 = OpLoad %9 %42 +%108 = OpBitFieldUExtract %9 %107 %28 %29 +OpStore %42 %108 +%109 = OpLoad %10 %44 +%110 = OpBitFieldUExtract %10 %109 %28 %29 +OpStore %44 %110 +%111 = OpLoad %3 %30 +%112 = OpExtInst %3 %1 FindILsb %111 +OpStore %30 %112 +%113 = OpLoad %8 %40 +%114 = OpExtInst %8 %1 FindILsb %113 +OpStore %40 %114 +%115 = OpLoad %5 %34 +%116 = OpExtInst %5 %1 FindSMsb %115 +OpStore %34 %116 +%117 = OpLoad %9 %42 +%118 = OpExtInst %9 %1 FindUMsb %117 +OpStore %42 %118 +%119 = OpLoad %3 %30 +%120 = OpExtInst %3 %1 FindSMsb %119 +OpStore %30 %120 +%121 = OpLoad %7 %38 +%122 = OpExtInst %7 %1 FindUMsb %121 +OpStore %38 %122 +%123 = OpLoad %3 %30 +%124 = OpBitCount %3 %123 +OpStore %30 %124 +%125 = OpLoad %4 %32 +%126 = OpBitCount %4 %125 +OpStore %32 %126 +%127 = OpLoad %5 %34 +%128 = OpBitCount %5 %127 +OpStore %34 %128 +%129 = OpLoad %6 %36 +%130 = OpBitCount %6 %129 +OpStore %36 %130 +%131 = OpLoad %7 %38 +%132 = OpBitCount %7 %131 +OpStore %38 %132 +%133 = OpLoad %8 %40 +%134 = OpBitCount %8 %133 +OpStore %40 %134 +%135 = OpLoad %9 %42 +%136 = OpBitCount %9 %135 +OpStore %42 %136 +%137 = OpLoad %10 %44 +%138 = OpBitCount %10 %137 +OpStore %44 %138 +%139 = OpLoad %3 %30 +%140 = OpBitReverse %3 %139 +OpStore %30 %140 +%141 = OpLoad %4 %32 +%142 = OpBitReverse %4 %141 +OpStore %32 %142 +%143 = OpLoad %5 %34 +%144 = OpBitReverse %5 %143 +OpStore %34 %144 +%145 = OpLoad %6 %36 +%146 = OpBitReverse %6 %145 +OpStore %36 %146 +%147 = OpLoad %7 %38 +%148 = OpBitReverse %7 %147 +OpStore %38 %148 +%149 = OpLoad %8 %40 +%150 = OpBitReverse %8 %149 +OpStore %40 %150 +%151 = OpLoad %9 %42 +%152 = OpBitReverse %9 %151 +OpStore %42 %152 +%153 = OpLoad %10 %44 +%154 = OpBitReverse %10 %153 +OpStore %44 %154 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/boids.spvasm b/tests/out/spv/boids.spvasm index f57d99723..0e48e0f55 100644 --- a/tests/out/spv/boids.spvasm +++ b/tests/out/spv/boids.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 209 +; Bound: 208 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %39 "main" %36 -OpExecutionMode %39 LocalSize 64 1 1 +OpEntryPoint GLCompute %23 "main" %20 +OpExecutionMode %23 LocalSize 64 1 1 OpMemberName %6 0 "pos" OpMemberName %6 1 "vel" OpName %6 "Particle" @@ -25,18 +25,18 @@ OpName %12 "NUM_PARTICLES" OpName %13 "params" OpName %16 "particlesSrc" OpName %18 "particlesDst" -OpName %19 "vPos" -OpName %22 "vVel" -OpName %23 "cMass" -OpName %24 "cVel" -OpName %25 "colVel" -OpName %26 "cMassCount" -OpName %29 "cVelCount" -OpName %30 "pos" -OpName %31 "vel" -OpName %32 "i" -OpName %36 "global_invocation_id" -OpName %39 "main" +OpName %20 "global_invocation_id" +OpName %23 "main" +OpName %36 "vPos" +OpName %39 "vVel" +OpName %41 "cMass" +OpName %42 "cVel" +OpName %43 "colVel" +OpName %44 "cMassCount" +OpName %46 "cVelCount" +OpName %47 "pos" +OpName %49 "vel" +OpName %51 "i" OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 8 OpMemberDecorate %7 0 Offset 0 @@ -58,7 +58,7 @@ OpDecorate %16 DescriptorSet 0 OpDecorate %16 Binding 1 OpDecorate %18 DescriptorSet 0 OpDecorate %18 Binding 2 -OpDecorate %36 BuiltIn GlobalInvocationId +OpDecorate %20 BuiltIn GlobalInvocationId %2 = OpTypeVoid %3 = OpTypeInt 32 0 %5 = OpTypeFloat 32 @@ -76,264 +76,257 @@ OpDecorate %36 BuiltIn GlobalInvocationId %17 = OpTypePointer StorageBuffer %9 %16 = OpVariable %17 StorageBuffer %18 = OpVariable %17 StorageBuffer -%20 = OpTypePointer Function %4 -%21 = OpConstantNull %4 -%27 = OpTypePointer Function %11 -%28 = OpConstantNull %11 -%33 = OpTypePointer Function %3 -%34 = OpConstantNull %3 -%37 = OpTypePointer Input %10 -%36 = OpVariable %37 Input -%40 = OpTypeFunction %2 -%41 = OpTypePointer Uniform %7 -%42 = OpConstant %3 0 -%44 = OpConstant %5 0.0 -%45 = OpConstant %11 0 -%46 = OpConstant %11 1 -%47 = OpConstant %3 1 -%48 = OpConstant %5 0.1 -%49 = OpConstant %5 -1.0 -%50 = OpConstant %5 1.0 -%53 = OpTypeBool -%57 = OpTypePointer StorageBuffer %8 -%58 = OpTypePointer StorageBuffer %6 -%59 = OpTypePointer StorageBuffer %4 -%88 = OpTypePointer Uniform %5 -%102 = OpConstant %3 2 -%116 = OpConstant %3 3 -%151 = OpConstant %3 4 -%157 = OpConstant %3 5 -%163 = OpConstant %3 6 -%180 = OpTypePointer Function %5 -%39 = OpFunction %2 None %40 -%35 = OpLabel -%32 = OpVariable %33 Function %34 -%29 = OpVariable %27 Function %28 -%24 = OpVariable %20 Function %21 -%19 = OpVariable %20 Function %21 -%30 = OpVariable %20 Function %21 -%25 = OpVariable %20 Function %21 -%22 = OpVariable %20 Function %21 -%31 = OpVariable %20 Function %21 -%26 = OpVariable %27 Function %28 -%23 = OpVariable %20 Function %21 -%38 = OpLoad %10 %36 -%43 = OpAccessChain %41 %13 %42 -OpBranch %51 -%51 = OpLabel -%52 = OpCompositeExtract %3 %38 0 -%54 = OpUGreaterThanEqual %53 %52 %12 -OpSelectionMerge %55 None -OpBranchConditional %54 %56 %55 -%56 = OpLabel +%21 = OpTypePointer Input %10 +%20 = OpVariable %21 Input +%24 = OpTypeFunction %2 +%25 = OpTypePointer Uniform %7 +%26 = OpConstant %3 0 +%28 = OpConstant %5 0.0 +%29 = OpConstantComposite %4 %28 %28 +%30 = OpConstant %11 0 +%31 = OpConstant %11 1 +%32 = OpConstant %3 1 +%33 = OpConstant %5 0.1 +%34 = OpConstant %5 -1.0 +%35 = OpConstant %5 1.0 +%37 = OpTypePointer Function %4 +%38 = OpConstantNull %4 +%40 = OpConstantNull %4 +%45 = OpTypePointer Function %11 +%48 = OpConstantNull %4 +%50 = OpConstantNull %4 +%52 = OpTypePointer Function %3 +%55 = OpTypeBool +%59 = OpTypePointer StorageBuffer %8 +%60 = OpTypePointer StorageBuffer %6 +%61 = OpTypePointer StorageBuffer %4 +%87 = OpTypePointer Uniform %5 +%101 = OpConstant %3 2 +%115 = OpConstant %3 3 +%150 = OpConstant %3 4 +%156 = OpConstant %3 5 +%162 = OpConstant %3 6 +%179 = OpTypePointer Function %5 +%23 = OpFunction %2 None %24 +%19 = OpLabel +%51 = OpVariable %52 Function %26 +%46 = OpVariable %45 Function %30 +%42 = OpVariable %37 Function %29 +%36 = OpVariable %37 Function %38 +%47 = OpVariable %37 Function %48 +%43 = OpVariable %37 Function %29 +%39 = OpVariable %37 Function %40 +%49 = OpVariable %37 Function %50 +%44 = OpVariable %45 Function %30 +%41 = OpVariable %37 Function %29 +%22 = OpLoad %10 %20 +%27 = OpAccessChain %25 %13 %26 +OpBranch %53 +%53 = OpLabel +%54 = OpCompositeExtract %3 %22 0 +%56 = OpUGreaterThanEqual %55 %54 %12 +OpSelectionMerge %57 None +OpBranchConditional %56 %58 %57 +%58 = OpLabel OpReturn -%55 = OpLabel -%60 = OpAccessChain %59 %16 %42 %52 %42 -%61 = OpLoad %4 %60 -OpStore %19 %61 -%62 = OpAccessChain %59 %16 %42 %52 %47 +%57 = OpLabel +%62 = OpAccessChain %61 %16 %26 %54 %26 %63 = OpLoad %4 %62 -OpStore %22 %63 -%64 = OpCompositeConstruct %4 %44 %44 -OpStore %23 %64 -%65 = OpCompositeConstruct %4 %44 %44 -OpStore %24 %65 -%66 = OpCompositeConstruct %4 %44 %44 -OpStore %25 %66 -OpStore %26 %45 -OpStore %29 %45 -OpStore %32 %42 +OpStore %36 %63 +%64 = OpAccessChain %61 %16 %26 %54 %32 +%65 = OpLoad %4 %64 +OpStore %39 %65 +OpBranch %66 +%66 = OpLabel +OpLoopMerge %67 %69 None +OpBranch %68 +%68 = OpLabel +%70 = OpLoad %3 %51 +%71 = OpUGreaterThanEqual %55 %70 %12 +OpSelectionMerge %72 None +OpBranchConditional %71 %73 %72 +%73 = OpLabel OpBranch %67 -%67 = OpLabel -OpLoopMerge %68 %70 None +%72 = OpLabel +%74 = OpLoad %3 %51 +%75 = OpIEqual %55 %74 %54 +OpSelectionMerge %76 None +OpBranchConditional %75 %77 %76 +%77 = OpLabel +OpBranch %69 +%76 = OpLabel +%78 = OpLoad %3 %51 +%79 = OpAccessChain %61 %16 %26 %78 %26 +%80 = OpLoad %4 %79 +OpStore %47 %80 +%81 = OpLoad %3 %51 +%82 = OpAccessChain %61 %16 %26 %81 %32 +%83 = OpLoad %4 %82 +OpStore %49 %83 +%84 = OpLoad %4 %47 +%85 = OpLoad %4 %36 +%86 = OpExtInst %5 %1 Distance %84 %85 +%88 = OpAccessChain %87 %27 %32 +%89 = OpLoad %5 %88 +%90 = OpFOrdLessThan %55 %86 %89 +OpSelectionMerge %91 None +OpBranchConditional %90 %92 %91 +%92 = OpLabel +%93 = OpLoad %4 %41 +%94 = OpLoad %4 %47 +%95 = OpFAdd %4 %93 %94 +OpStore %41 %95 +%96 = OpLoad %11 %44 +%97 = OpIAdd %11 %96 %31 +OpStore %44 %97 +OpBranch %91 +%91 = OpLabel +%98 = OpLoad %4 %47 +%99 = OpLoad %4 %36 +%100 = OpExtInst %5 %1 Distance %98 %99 +%102 = OpAccessChain %87 %27 %101 +%103 = OpLoad %5 %102 +%104 = OpFOrdLessThan %55 %100 %103 +OpSelectionMerge %105 None +OpBranchConditional %104 %106 %105 +%106 = OpLabel +%107 = OpLoad %4 %43 +%108 = OpLoad %4 %47 +%109 = OpLoad %4 %36 +%110 = OpFSub %4 %108 %109 +%111 = OpFSub %4 %107 %110 +OpStore %43 %111 +OpBranch %105 +%105 = OpLabel +%112 = OpLoad %4 %47 +%113 = OpLoad %4 %36 +%114 = OpExtInst %5 %1 Distance %112 %113 +%116 = OpAccessChain %87 %27 %115 +%117 = OpLoad %5 %116 +%118 = OpFOrdLessThan %55 %114 %117 +OpSelectionMerge %119 None +OpBranchConditional %118 %120 %119 +%120 = OpLabel +%121 = OpLoad %4 %42 +%122 = OpLoad %4 %49 +%123 = OpFAdd %4 %121 %122 +OpStore %42 %123 +%124 = OpLoad %11 %46 +%125 = OpIAdd %11 %124 %31 +OpStore %46 %125 +OpBranch %119 +%119 = OpLabel OpBranch %69 %69 = OpLabel -%71 = OpLoad %3 %32 -%72 = OpUGreaterThanEqual %53 %71 %12 -OpSelectionMerge %73 None -OpBranchConditional %72 %74 %73 -%74 = OpLabel -OpBranch %68 -%73 = OpLabel -%75 = OpLoad %3 %32 -%76 = OpIEqual %53 %75 %52 -OpSelectionMerge %77 None -OpBranchConditional %76 %78 %77 -%78 = OpLabel -OpBranch %70 -%77 = OpLabel -%79 = OpLoad %3 %32 -%80 = OpAccessChain %59 %16 %42 %79 %42 -%81 = OpLoad %4 %80 -OpStore %30 %81 -%82 = OpLoad %3 %32 -%83 = OpAccessChain %59 %16 %42 %82 %47 -%84 = OpLoad %4 %83 -OpStore %31 %84 -%85 = OpLoad %4 %30 -%86 = OpLoad %4 %19 -%87 = OpExtInst %5 %1 Distance %85 %86 -%89 = OpAccessChain %88 %43 %47 -%90 = OpLoad %5 %89 -%91 = OpFOrdLessThan %53 %87 %90 -OpSelectionMerge %92 None -OpBranchConditional %91 %93 %92 -%93 = OpLabel -%94 = OpLoad %4 %23 -%95 = OpLoad %4 %30 -%96 = OpFAdd %4 %94 %95 -OpStore %23 %96 -%97 = OpLoad %11 %26 -%98 = OpIAdd %11 %97 %46 -OpStore %26 %98 -OpBranch %92 -%92 = OpLabel -%99 = OpLoad %4 %30 -%100 = OpLoad %4 %19 -%101 = OpExtInst %5 %1 Distance %99 %100 -%103 = OpAccessChain %88 %43 %102 -%104 = OpLoad %5 %103 -%105 = OpFOrdLessThan %53 %101 %104 -OpSelectionMerge %106 None -OpBranchConditional %105 %107 %106 -%107 = OpLabel -%108 = OpLoad %4 %25 -%109 = OpLoad %4 %30 -%110 = OpLoad %4 %19 -%111 = OpFSub %4 %109 %110 -%112 = OpFSub %4 %108 %111 -OpStore %25 %112 -OpBranch %106 -%106 = OpLabel -%113 = OpLoad %4 %30 -%114 = OpLoad %4 %19 -%115 = OpExtInst %5 %1 Distance %113 %114 -%117 = OpAccessChain %88 %43 %116 -%118 = OpLoad %5 %117 -%119 = OpFOrdLessThan %53 %115 %118 -OpSelectionMerge %120 None -OpBranchConditional %119 %121 %120 -%121 = OpLabel -%122 = OpLoad %4 %24 -%123 = OpLoad %4 %31 -%124 = OpFAdd %4 %122 %123 -OpStore %24 %124 -%125 = OpLoad %11 %29 -%126 = OpIAdd %11 %125 %46 -OpStore %29 %126 -OpBranch %120 -%120 = OpLabel -OpBranch %70 -%70 = OpLabel -%127 = OpLoad %3 %32 -%128 = OpIAdd %3 %127 %47 -OpStore %32 %128 -OpBranch %67 -%68 = OpLabel -%129 = OpLoad %11 %26 -%130 = OpSGreaterThan %53 %129 %45 -OpSelectionMerge %131 None -OpBranchConditional %130 %132 %131 -%132 = OpLabel -%133 = OpLoad %4 %23 -%134 = OpLoad %11 %26 -%135 = OpConvertSToF %5 %134 -%136 = OpCompositeConstruct %4 %135 %135 -%137 = OpFDiv %4 %133 %136 -%138 = OpLoad %4 %19 -%139 = OpFSub %4 %137 %138 -OpStore %23 %139 -OpBranch %131 +%126 = OpLoad %3 %51 +%127 = OpIAdd %3 %126 %32 +OpStore %51 %127 +OpBranch %66 +%67 = OpLabel +%128 = OpLoad %11 %44 +%129 = OpSGreaterThan %55 %128 %30 +OpSelectionMerge %130 None +OpBranchConditional %129 %131 %130 %131 = OpLabel -%140 = OpLoad %11 %29 -%141 = OpSGreaterThan %53 %140 %45 -OpSelectionMerge %142 None -OpBranchConditional %141 %143 %142 -%143 = OpLabel -%144 = OpLoad %4 %24 -%145 = OpLoad %11 %29 -%146 = OpConvertSToF %5 %145 -%147 = OpCompositeConstruct %4 %146 %146 -%148 = OpFDiv %4 %144 %147 -OpStore %24 %148 -OpBranch %142 +%132 = OpLoad %4 %41 +%133 = OpLoad %11 %44 +%134 = OpConvertSToF %5 %133 +%135 = OpCompositeConstruct %4 %134 %134 +%136 = OpFDiv %4 %132 %135 +%137 = OpLoad %4 %36 +%138 = OpFSub %4 %136 %137 +OpStore %41 %138 +OpBranch %130 +%130 = OpLabel +%139 = OpLoad %11 %46 +%140 = OpSGreaterThan %55 %139 %30 +OpSelectionMerge %141 None +OpBranchConditional %140 %142 %141 %142 = OpLabel -%149 = OpLoad %4 %22 -%150 = OpLoad %4 %23 -%152 = OpAccessChain %88 %43 %151 -%153 = OpLoad %5 %152 -%154 = OpVectorTimesScalar %4 %150 %153 -%155 = OpFAdd %4 %149 %154 -%156 = OpLoad %4 %25 -%158 = OpAccessChain %88 %43 %157 -%159 = OpLoad %5 %158 -%160 = OpVectorTimesScalar %4 %156 %159 -%161 = OpFAdd %4 %155 %160 -%162 = OpLoad %4 %24 -%164 = OpAccessChain %88 %43 %163 -%165 = OpLoad %5 %164 -%166 = OpVectorTimesScalar %4 %162 %165 -%167 = OpFAdd %4 %161 %166 -OpStore %22 %167 -%168 = OpLoad %4 %22 -%169 = OpExtInst %4 %1 Normalize %168 -%170 = OpLoad %4 %22 -%171 = OpExtInst %5 %1 Length %170 -%172 = OpExtInst %5 %1 FClamp %171 %44 %48 -%173 = OpVectorTimesScalar %4 %169 %172 -OpStore %22 %173 -%174 = OpLoad %4 %19 -%175 = OpLoad %4 %22 -%176 = OpAccessChain %88 %43 %42 -%177 = OpLoad %5 %176 -%178 = OpVectorTimesScalar %4 %175 %177 -%179 = OpFAdd %4 %174 %178 -OpStore %19 %179 -%181 = OpAccessChain %180 %19 %42 -%182 = OpLoad %5 %181 -%183 = OpFOrdLessThan %53 %182 %49 -OpSelectionMerge %184 None -OpBranchConditional %183 %185 %184 -%185 = OpLabel -%186 = OpAccessChain %180 %19 %42 -OpStore %186 %50 -OpBranch %184 +%143 = OpLoad %4 %42 +%144 = OpLoad %11 %46 +%145 = OpConvertSToF %5 %144 +%146 = OpCompositeConstruct %4 %145 %145 +%147 = OpFDiv %4 %143 %146 +OpStore %42 %147 +OpBranch %141 +%141 = OpLabel +%148 = OpLoad %4 %39 +%149 = OpLoad %4 %41 +%151 = OpAccessChain %87 %27 %150 +%152 = OpLoad %5 %151 +%153 = OpVectorTimesScalar %4 %149 %152 +%154 = OpFAdd %4 %148 %153 +%155 = OpLoad %4 %43 +%157 = OpAccessChain %87 %27 %156 +%158 = OpLoad %5 %157 +%159 = OpVectorTimesScalar %4 %155 %158 +%160 = OpFAdd %4 %154 %159 +%161 = OpLoad %4 %42 +%163 = OpAccessChain %87 %27 %162 +%164 = OpLoad %5 %163 +%165 = OpVectorTimesScalar %4 %161 %164 +%166 = OpFAdd %4 %160 %165 +OpStore %39 %166 +%167 = OpLoad %4 %39 +%168 = OpExtInst %4 %1 Normalize %167 +%169 = OpLoad %4 %39 +%170 = OpExtInst %5 %1 Length %169 +%171 = OpExtInst %5 %1 FClamp %170 %28 %33 +%172 = OpVectorTimesScalar %4 %168 %171 +OpStore %39 %172 +%173 = OpLoad %4 %36 +%174 = OpLoad %4 %39 +%175 = OpAccessChain %87 %27 %26 +%176 = OpLoad %5 %175 +%177 = OpVectorTimesScalar %4 %174 %176 +%178 = OpFAdd %4 %173 %177 +OpStore %36 %178 +%180 = OpAccessChain %179 %36 %26 +%181 = OpLoad %5 %180 +%182 = OpFOrdLessThan %55 %181 %34 +OpSelectionMerge %183 None +OpBranchConditional %182 %184 %183 %184 = OpLabel -%187 = OpAccessChain %180 %19 %42 -%188 = OpLoad %5 %187 -%189 = OpFOrdGreaterThan %53 %188 %50 -OpSelectionMerge %190 None -OpBranchConditional %189 %191 %190 -%191 = OpLabel -%192 = OpAccessChain %180 %19 %42 -OpStore %192 %49 -OpBranch %190 +%185 = OpAccessChain %179 %36 %26 +OpStore %185 %35 +OpBranch %183 +%183 = OpLabel +%186 = OpAccessChain %179 %36 %26 +%187 = OpLoad %5 %186 +%188 = OpFOrdGreaterThan %55 %187 %35 +OpSelectionMerge %189 None +OpBranchConditional %188 %190 %189 %190 = OpLabel -%193 = OpAccessChain %180 %19 %47 -%194 = OpLoad %5 %193 -%195 = OpFOrdLessThan %53 %194 %49 -OpSelectionMerge %196 None -OpBranchConditional %195 %197 %196 -%197 = OpLabel -%198 = OpAccessChain %180 %19 %47 -OpStore %198 %50 -OpBranch %196 +%191 = OpAccessChain %179 %36 %26 +OpStore %191 %34 +OpBranch %189 +%189 = OpLabel +%192 = OpAccessChain %179 %36 %32 +%193 = OpLoad %5 %192 +%194 = OpFOrdLessThan %55 %193 %34 +OpSelectionMerge %195 None +OpBranchConditional %194 %196 %195 %196 = OpLabel -%199 = OpAccessChain %180 %19 %47 -%200 = OpLoad %5 %199 -%201 = OpFOrdGreaterThan %53 %200 %50 -OpSelectionMerge %202 None -OpBranchConditional %201 %203 %202 -%203 = OpLabel -%204 = OpAccessChain %180 %19 %47 -OpStore %204 %49 -OpBranch %202 +%197 = OpAccessChain %179 %36 %32 +OpStore %197 %35 +OpBranch %195 +%195 = OpLabel +%198 = OpAccessChain %179 %36 %32 +%199 = OpLoad %5 %198 +%200 = OpFOrdGreaterThan %55 %199 %35 +OpSelectionMerge %201 None +OpBranchConditional %200 %202 %201 %202 = OpLabel -%205 = OpLoad %4 %19 -%206 = OpAccessChain %59 %18 %42 %52 %42 -OpStore %206 %205 -%207 = OpLoad %4 %22 -%208 = OpAccessChain %59 %18 %42 %52 %47 -OpStore %208 %207 +%203 = OpAccessChain %179 %36 %32 +OpStore %203 %34 +OpBranch %201 +%201 = OpLabel +%204 = OpLoad %4 %36 +%205 = OpAccessChain %61 %18 %26 %54 %26 +OpStore %205 %204 +%206 = OpLoad %4 %39 +%207 = OpAccessChain %61 %18 %26 %54 %32 +OpStore %207 %206 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/tests/out/spv/bounds-check-image-restrict.spvasm index 923aadecf..038685a55 100644 --- a/tests/out/spv/bounds-check-image-restrict.spvasm +++ b/tests/out/spv/bounds-check-image-restrict.spvasm @@ -182,6 +182,7 @@ OpDecorate %267 Location 0 %283 = OpConstantNull %12 %284 = OpConstantNull %6 %285 = OpConstant %4 0.0 +%286 = OpConstantComposite %6 %285 %285 %285 %285 %48 = OpFunction %6 None %49 %46 = OpFunctionParameter %5 %47 = OpFunctionParameter %5 @@ -437,20 +438,19 @@ OpFunctionEnd %277 = OpLoad %18 %39 %278 = OpLoad %19 %41 %279 = OpLoad %20 %43 -OpBranch %286 -%286 = OpLabel -%287 = OpFunctionCall %6 %48 %280 %280 -%288 = OpFunctionCall %6 %63 %281 %280 -%289 = OpFunctionCall %6 %79 %281 %282 %280 -%290 = OpFunctionCall %6 %97 %281 %280 %280 -%291 = OpFunctionCall %6 %113 %283 %280 -%292 = OpFunctionCall %6 %128 %281 %280 -%293 = OpFunctionCall %2 %210 %280 %284 -%294 = OpFunctionCall %2 %220 %281 %284 -%295 = OpFunctionCall %2 %232 %281 %282 %284 -%296 = OpFunctionCall %2 %246 %281 %280 %284 -%297 = OpFunctionCall %2 %258 %283 %284 -%298 = OpCompositeConstruct %6 %285 %285 %285 %285 -OpStore %267 %298 +OpBranch %287 +%287 = OpLabel +%288 = OpFunctionCall %6 %48 %280 %280 +%289 = OpFunctionCall %6 %63 %281 %280 +%290 = OpFunctionCall %6 %79 %281 %282 %280 +%291 = OpFunctionCall %6 %97 %281 %280 %280 +%292 = OpFunctionCall %6 %113 %283 %280 +%293 = OpFunctionCall %6 %128 %281 %280 +%294 = OpFunctionCall %2 %210 %280 %284 +%295 = OpFunctionCall %2 %220 %281 %284 +%296 = OpFunctionCall %2 %232 %281 %282 %284 +%297 = OpFunctionCall %2 %246 %281 %280 %284 +%298 = OpFunctionCall %2 %258 %283 %284 +OpStore %267 %286 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/tests/out/spv/bounds-check-image-rzsw.spvasm index 8a6cfc1b7..a9eeb4204 100644 --- a/tests/out/spv/bounds-check-image-rzsw.spvasm +++ b/tests/out/spv/bounds-check-image-rzsw.spvasm @@ -171,6 +171,7 @@ OpDecorate %295 Location 0 %310 = OpConstant %10 0 %311 = OpConstantNull %12 %312 = OpConstant %4 0.0 +%313 = OpConstantComposite %6 %312 %312 %312 %312 %48 = OpFunction %6 None %49 %46 = OpFunctionParameter %5 %47 = OpFunctionParameter %5 @@ -519,20 +520,19 @@ OpFunctionEnd %305 = OpLoad %18 %39 %306 = OpLoad %19 %41 %307 = OpLoad %20 %43 -OpBranch %313 -%313 = OpLabel -%314 = OpFunctionCall %6 %48 %308 %308 -%315 = OpFunctionCall %6 %66 %309 %308 -%316 = OpFunctionCall %6 %85 %309 %310 %308 -%317 = OpFunctionCall %6 %106 %309 %308 %308 -%318 = OpFunctionCall %6 %124 %311 %308 -%319 = OpFunctionCall %6 %141 %309 %308 -%320 = OpFunctionCall %2 %233 %308 %53 -%321 = OpFunctionCall %2 %244 %309 %53 -%322 = OpFunctionCall %2 %257 %309 %310 %53 -%323 = OpFunctionCall %2 %272 %309 %308 %53 -%324 = OpFunctionCall %2 %285 %311 %53 -%325 = OpCompositeConstruct %6 %312 %312 %312 %312 -OpStore %295 %325 +OpBranch %314 +%314 = OpLabel +%315 = OpFunctionCall %6 %48 %308 %308 +%316 = OpFunctionCall %6 %66 %309 %308 +%317 = OpFunctionCall %6 %85 %309 %310 %308 +%318 = OpFunctionCall %6 %106 %309 %308 %308 +%319 = OpFunctionCall %6 %124 %311 %308 +%320 = OpFunctionCall %6 %141 %309 %308 +%321 = OpFunctionCall %2 %233 %308 %53 +%322 = OpFunctionCall %2 %244 %309 %53 +%323 = OpFunctionCall %2 %257 %309 %310 %53 +%324 = OpFunctionCall %2 %272 %309 %308 %53 +%325 = OpFunctionCall %2 %285 %311 %53 +OpStore %295 %313 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/break-if.spvasm b/tests/out/spv/break-if.spvasm index 9b17efb86..ea944130e 100644 --- a/tests/out/spv/break-if.spvasm +++ b/tests/out/spv/break-if.spvasm @@ -1,19 +1,22 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 47 +; Bound: 50 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %45 "main" -OpExecutionMode %45 LocalSize 1 1 1 +OpEntryPoint GLCompute %48 "main" +OpExecutionMode %48 LocalSize 1 1 1 %2 = OpTypeVoid %3 = OpTypeBool %6 = OpTypeFunction %2 %7 = OpConstantTrue %3 -%14 = OpTypePointer Function %3 -%15 = OpConstantNull %3 -%20 = OpTypeFunction %2 %3 +%16 = OpTypeFunction %2 %3 +%18 = OpTypePointer Function %3 +%19 = OpConstantNull %3 +%21 = OpConstantNull %3 +%35 = OpConstantNull %3 +%37 = OpConstantNull %3 %5 = OpFunction %2 None %6 %4 = OpLabel OpBranch %8 @@ -29,57 +32,57 @@ OpBranchConditional %7 %10 %9 %10 = OpLabel OpReturn OpFunctionEnd -%19 = OpFunction %2 None %20 -%18 = OpFunctionParameter %3 -%17 = OpLabel -%13 = OpVariable %14 Function %15 -%16 = OpVariable %14 Function %15 -OpBranch %21 -%21 = OpLabel +%15 = OpFunction %2 None %16 +%14 = OpFunctionParameter %3 +%13 = OpLabel +%17 = OpVariable %18 Function %19 +%20 = OpVariable %18 Function %21 OpBranch %22 %22 = OpLabel -OpLoopMerge %23 %25 None -OpBranch %24 -%24 = OpLabel +OpBranch %23 +%23 = OpLabel +OpLoopMerge %24 %26 None OpBranch %25 %25 = OpLabel -OpStore %13 %18 -%26 = OpLoad %3 %13 -%27 = OpLogicalNotEqual %3 %18 %26 -OpStore %16 %27 -%28 = OpLoad %3 %16 -%29 = OpLogicalEqual %3 %18 %28 -OpBranchConditional %29 %23 %22 -%23 = OpLabel +OpBranch %26 +%26 = OpLabel +OpStore %17 %14 +%27 = OpLoad %3 %17 +%28 = OpLogicalNotEqual %3 %14 %27 +OpStore %20 %28 +%29 = OpLoad %3 %20 +%30 = OpLogicalEqual %3 %14 %29 +OpBranchConditional %30 %24 %23 +%24 = OpLabel OpReturn OpFunctionEnd -%34 = OpFunction %2 None %20 -%33 = OpFunctionParameter %3 -%32 = OpLabel -%30 = OpVariable %14 Function %15 -%31 = OpVariable %14 Function %15 -OpBranch %35 -%35 = OpLabel -OpBranch %36 -%36 = OpLabel -OpLoopMerge %37 %39 None +%33 = OpFunction %2 None %16 +%32 = OpFunctionParameter %3 +%31 = OpLabel +%34 = OpVariable %18 Function %35 +%36 = OpVariable %18 Function %37 OpBranch %38 %38 = OpLabel -OpStore %30 %33 -%40 = OpLoad %3 %30 -%41 = OpLogicalNotEqual %3 %33 %40 -OpStore %31 %41 OpBranch %39 %39 = OpLabel -%42 = OpLoad %3 %31 -%43 = OpLogicalEqual %3 %33 %42 -OpBranchConditional %43 %37 %36 -%37 = OpLabel +OpLoopMerge %40 %42 None +OpBranch %41 +%41 = OpLabel +OpStore %34 %32 +%43 = OpLoad %3 %34 +%44 = OpLogicalNotEqual %3 %32 %43 +OpStore %36 %44 +OpBranch %42 +%42 = OpLabel +%45 = OpLoad %3 %36 +%46 = OpLogicalEqual %3 %32 %45 +OpBranchConditional %46 %40 %39 +%40 = OpLabel OpReturn OpFunctionEnd -%45 = OpFunction %2 None %6 -%44 = OpLabel -OpBranch %46 -%46 = OpLabel +%48 = OpFunction %2 None %6 +%47 = OpLabel +OpBranch %49 +%49 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm index 310bc5c1e..5c77a5226 100644 --- a/tests/out/spv/collatz.spvasm +++ b/tests/out/spv/collatz.spvasm @@ -11,10 +11,10 @@ OpExecutionMode %51 LocalSize 1 1 1 OpMemberName %5 0 "data" OpName %5 "PrimeIndices" OpName %7 "v_indices" -OpName %9 "n" -OpName %12 "i" -OpName %14 "n_base" -OpName %15 "collatz_iterations" +OpName %10 "n_base" +OpName %11 "collatz_iterations" +OpName %17 "n" +OpName %20 "i" OpName %48 "global_id" OpName %51 "main" OpDecorate %4 ArrayStride 4 @@ -30,35 +30,34 @@ OpDecorate %48 BuiltIn GlobalInvocationId %6 = OpTypeVector %3 3 %8 = OpTypePointer StorageBuffer %5 %7 = OpVariable %8 StorageBuffer -%10 = OpTypePointer Function %3 -%11 = OpConstantNull %3 -%16 = OpTypeFunction %3 %3 -%17 = OpConstant %3 0 -%18 = OpConstant %3 1 -%19 = OpConstant %3 2 -%20 = OpConstant %3 3 +%12 = OpTypeFunction %3 %3 +%13 = OpConstant %3 0 +%14 = OpConstant %3 1 +%15 = OpConstant %3 2 +%16 = OpConstant %3 3 +%18 = OpTypePointer Function %3 +%19 = OpConstantNull %3 %27 = OpTypeBool %49 = OpTypePointer Input %6 %48 = OpVariable %49 Input %52 = OpTypeFunction %2 %54 = OpTypePointer StorageBuffer %4 %56 = OpTypePointer StorageBuffer %3 -%15 = OpFunction %3 None %16 -%14 = OpFunctionParameter %3 -%13 = OpLabel -%9 = OpVariable %10 Function %11 -%12 = OpVariable %10 Function %11 +%11 = OpFunction %3 None %12 +%10 = OpFunctionParameter %3 +%9 = OpLabel +%17 = OpVariable %18 Function %19 +%20 = OpVariable %18 Function %13 OpBranch %21 %21 = OpLabel -OpStore %9 %14 -OpStore %12 %17 +OpStore %17 %10 OpBranch %22 %22 = OpLabel OpLoopMerge %23 %25 None OpBranch %24 %24 = OpLabel -%26 = OpLoad %3 %9 -%28 = OpUGreaterThan %27 %26 %18 +%26 = OpLoad %3 %17 +%28 = OpUGreaterThan %27 %26 %14 OpSelectionMerge %29 None OpBranchConditional %28 %29 %30 %30 = OpLabel @@ -66,33 +65,33 @@ OpBranch %23 %29 = OpLabel OpBranch %31 %31 = OpLabel -%33 = OpLoad %3 %9 -%34 = OpUMod %3 %33 %19 -%35 = OpIEqual %27 %34 %17 +%33 = OpLoad %3 %17 +%34 = OpUMod %3 %33 %15 +%35 = OpIEqual %27 %34 %13 OpSelectionMerge %36 None OpBranchConditional %35 %37 %38 %37 = OpLabel -%39 = OpLoad %3 %9 -%40 = OpUDiv %3 %39 %19 -OpStore %9 %40 +%39 = OpLoad %3 %17 +%40 = OpUDiv %3 %39 %15 +OpStore %17 %40 OpBranch %36 %38 = OpLabel -%41 = OpLoad %3 %9 -%42 = OpIMul %3 %20 %41 -%43 = OpIAdd %3 %42 %18 -OpStore %9 %43 +%41 = OpLoad %3 %17 +%42 = OpIMul %3 %16 %41 +%43 = OpIAdd %3 %42 %14 +OpStore %17 %43 OpBranch %36 %36 = OpLabel -%44 = OpLoad %3 %12 -%45 = OpIAdd %3 %44 %18 -OpStore %12 %45 +%44 = OpLoad %3 %20 +%45 = OpIAdd %3 %44 %14 +OpStore %20 %45 OpBranch %32 %32 = OpLabel OpBranch %25 %25 = OpLabel OpBranch %22 %23 = OpLabel -%46 = OpLoad %3 %12 +%46 = OpLoad %3 %20 OpReturnValue %46 OpFunctionEnd %51 = OpFunction %2 None %52 @@ -102,10 +101,10 @@ OpBranch %53 %53 = OpLabel %55 = OpCompositeExtract %3 %50 0 %57 = OpCompositeExtract %3 %50 0 -%58 = OpAccessChain %56 %7 %17 %57 +%58 = OpAccessChain %56 %7 %13 %57 %59 = OpLoad %3 %58 -%60 = OpFunctionCall %3 %15 %59 -%61 = OpAccessChain %56 %7 %17 %55 +%60 = OpFunctionCall %3 %11 %59 +%61 = OpAccessChain %56 %7 %13 %55 OpStore %61 %60 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/constructors.spvasm b/tests/out/spv/constructors.spvasm index 4670ab39d..e8e2e2595 100644 --- a/tests/out/spv/constructors.spvasm +++ b/tests/out/spv/constructors.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 73 +; Bound: 70 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %46 "main" -OpExecutionMode %46 LocalSize 1 1 1 +OpEntryPoint GLCompute %44 "main" +OpExecutionMode %44 LocalSize 1 1 1 OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpDecorate %10 ArrayStride 16 @@ -53,35 +53,32 @@ OpDecorate %17 ArrayStride 4 %40 = OpConstant %5 2 %41 = OpConstant %5 3 %42 = OpConstantComposite %17 %38 %39 %40 %41 -%44 = OpTypePointer Function %6 -%47 = OpTypeFunction %2 -%48 = OpConstant %12 0 -%49 = OpConstantNull %20 -%46 = OpFunction %2 None %47 -%45 = OpLabel -%43 = OpVariable %44 Function %37 -OpBranch %50 -%50 = OpLabel -%51 = OpCompositeConstruct %3 %22 %22 %22 %22 -%52 = OpCompositeConstruct %6 %51 %39 -OpStore %43 %52 -%53 = OpCompositeConstruct %9 %22 %21 -%54 = OpCompositeConstruct %9 %21 %22 -%55 = OpCompositeConstruct %8 %53 %54 -%56 = OpCompositeConstruct %3 %22 %21 %21 %21 -%57 = OpCompositeConstruct %3 %21 %22 %21 %21 -%58 = OpCompositeConstruct %3 %21 %21 %22 %21 -%59 = OpCompositeConstruct %3 %21 %21 %21 %22 -%60 = OpCompositeConstruct %19 %56 %57 %58 %59 -%61 = OpCompositeConstruct %14 %48 %48 -%62 = OpCompositeConstruct %9 %21 %21 -%63 = OpCompositeConstruct %9 %21 %21 -%64 = OpCompositeConstruct %8 %62 %63 -%65 = OpCompositeConstruct %17 %38 %39 %40 %41 -%67 = OpCompositeConstruct %14 %48 %48 -%68 = OpCompositeConstruct %7 %21 %21 %21 -%69 = OpCompositeConstruct %7 %21 %21 %21 -%70 = OpCompositeConstruct %20 %68 %69 -%72 = OpCopyObject %20 %49 +%45 = OpTypeFunction %2 +%46 = OpConstantComposite %3 %22 %22 %22 %22 +%47 = OpConstantComposite %6 %46 %39 +%48 = OpConstantComposite %9 %22 %21 +%49 = OpConstantComposite %8 %48 %26 +%50 = OpConstantComposite %3 %22 %21 %21 %21 +%51 = OpConstantComposite %3 %21 %22 %21 %21 +%52 = OpConstantComposite %3 %21 %21 %22 %21 +%53 = OpConstantComposite %3 %21 %21 %21 %22 +%54 = OpConstantComposite %19 %50 %51 %52 %53 +%55 = OpConstant %12 0 +%56 = OpConstantComposite %14 %55 %55 +%57 = OpConstantComposite %9 %21 %21 +%58 = OpConstantComposite %8 %57 %57 +%59 = OpConstantComposite %14 %55 %55 +%60 = OpConstantComposite %7 %21 %21 %21 +%61 = OpConstantComposite %20 %60 %60 +%62 = OpConstantNull %20 +%64 = OpTypePointer Function %6 +%65 = OpConstantNull %6 +%44 = OpFunction %2 None %45 +%43 = OpLabel +%63 = OpVariable %64 Function %65 +OpBranch %66 +%66 = OpLabel +OpStore %63 %47 +%69 = OpCopyObject %20 %62 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm index eb2f3b62e..2fc9337cf 100644 --- a/tests/out/spv/control-flow.spvasm +++ b/tests/out/spv/control-flow.spvasm @@ -5,9 +5,9 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %39 "main" %36 -OpExecutionMode %39 LocalSize 1 1 1 -OpDecorate %36 BuiltIn GlobalInvocationId +OpEntryPoint GLCompute %36 "main" %33 +OpExecutionMode %36 LocalSize 1 1 1 +OpDecorate %33 BuiltIn GlobalInvocationId %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpTypeVector %4 3 @@ -15,15 +15,15 @@ OpDecorate %36 BuiltIn GlobalInvocationId %9 = OpTypeFunction %2 %5 %15 = OpTypeFunction %2 %16 = OpConstant %5 0 -%33 = OpTypePointer Function %5 -%34 = OpConstantNull %5 -%37 = OpTypePointer Input %3 -%36 = OpVariable %37 Input -%40 = OpConstant %5 1 -%41 = OpConstant %5 2 -%42 = OpConstant %5 3 -%43 = OpConstant %5 4 -%44 = OpConstant %4 0 +%34 = OpTypePointer Input %3 +%33 = OpVariable %34 Input +%37 = OpConstant %5 1 +%38 = OpConstant %5 2 +%39 = OpConstant %5 3 +%40 = OpConstant %5 4 +%41 = OpConstant %4 0 +%43 = OpTypePointer Function %5 +%44 = OpConstantNull %5 %46 = OpConstant %4 2 %47 = OpConstant %4 1 %48 = OpConstant %4 72 @@ -76,62 +76,62 @@ OpBranch %25 %26 = OpLabel OpReturn OpFunctionEnd -%39 = OpFunction %2 None %15 -%35 = OpLabel -%32 = OpVariable %33 Function %34 -%38 = OpLoad %3 %36 +%36 = OpFunction %2 None %15 +%32 = OpLabel +%42 = OpVariable %43 Function %44 +%35 = OpLoad %3 %33 OpBranch %45 %45 = OpLabel OpControlBarrier %46 %47 %48 OpControlBarrier %46 %46 %49 OpSelectionMerge %50 None -OpSwitch %40 %51 +OpSwitch %37 %51 %51 = OpLabel -OpStore %32 %40 +OpStore %42 %37 OpBranch %50 %50 = OpLabel -%52 = OpLoad %5 %32 +%52 = OpLoad %5 %42 OpSelectionMerge %53 None OpSwitch %52 %58 1 %54 2 %55 3 %56 4 %56 5 %57 6 %58 %54 = OpLabel -OpStore %32 %16 +OpStore %42 %16 OpBranch %53 %55 = OpLabel -OpStore %32 %40 +OpStore %42 %37 OpBranch %53 %56 = OpLabel -OpStore %32 %41 +OpStore %42 %38 OpBranch %53 %57 = OpLabel -OpStore %32 %42 +OpStore %42 %39 OpBranch %53 %58 = OpLabel -OpStore %32 %43 +OpStore %42 %40 OpBranch %53 %53 = OpLabel OpSelectionMerge %59 None -OpSwitch %44 %61 0 %60 +OpSwitch %41 %61 0 %60 %60 = OpLabel OpBranch %59 %61 = OpLabel OpBranch %59 %59 = OpLabel -%62 = OpLoad %5 %32 +%62 = OpLoad %5 %42 OpSelectionMerge %63 None OpSwitch %62 %68 1 %64 2 %65 3 %66 4 %67 %64 = OpLabel -OpStore %32 %16 +OpStore %42 %16 OpBranch %63 %65 = OpLabel -OpStore %32 %40 +OpStore %42 %37 OpReturn %66 = OpLabel -OpStore %32 %41 +OpStore %42 %38 OpReturn %67 = OpLabel OpReturn %68 = OpLabel -OpStore %32 %42 +OpStore %42 %39 OpReturn %63 = OpLabel OpReturn diff --git a/tests/out/spv/debug-symbol-simple.spvasm b/tests/out/spv/debug-symbol-simple.spvasm index 8f64c324c..b2fd1f260 100644 --- a/tests/out/spv/debug-symbol-simple.spvasm +++ b/tests/out/spv/debug-symbol-simple.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 95 +; Bound: 94 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %24 "vs_main" %15 %18 %20 %22 -OpEntryPoint Fragment %57 "fs_main" %51 %54 %56 -OpExecutionMode %57 OriginUpperLeft +OpEntryPoint Vertex %21 "vs_main" %12 %15 %17 %19 +OpEntryPoint Fragment %49 "fs_main" %43 %46 %48 +OpExecutionMode %49 OriginUpperLeft %3 = OpString "debug-symbol-simple.wgsl" OpSource Unknown 0 %3 "struct VertexInput { @location(0) position: vec3, @@ -48,29 +48,29 @@ OpName %6 "VertexInput" OpMemberName %8 0 "clip_position" OpMemberName %8 1 "color" OpName %8 "VertexOutput" -OpName %10 "out" -OpName %15 "position" -OpName %18 "color" -OpName %20 "clip_position" -OpName %22 "color" -OpName %24 "vs_main" -OpName %41 "color" -OpName %43 "i" -OpName %46 "ii" -OpName %51 "clip_position" -OpName %54 "color" -OpName %57 "fs_main" +OpName %12 "position" +OpName %15 "color" +OpName %17 "clip_position" +OpName %19 "color" +OpName %21 "vs_main" +OpName %24 "out" +OpName %43 "clip_position" +OpName %46 "color" +OpName %49 "fs_main" +OpName %55 "color" +OpName %57 "i" +OpName %59 "ii" OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpMemberDecorate %8 0 Offset 0 OpMemberDecorate %8 1 Offset 16 -OpDecorate %15 Location 0 -OpDecorate %18 Location 1 -OpDecorate %20 BuiltIn Position -OpDecorate %22 Location 0 -OpDecorate %51 BuiltIn FragCoord -OpDecorate %54 Location 0 -OpDecorate %56 Location 0 +OpDecorate %12 Location 0 +OpDecorate %15 Location 1 +OpDecorate %17 BuiltIn Position +OpDecorate %19 Location 0 +OpDecorate %43 BuiltIn FragCoord +OpDecorate %46 Location 0 +OpDecorate %48 Location 0 %2 = OpTypeVoid %5 = OpTypeFloat 32 %4 = OpTypeVector %5 3 @@ -78,140 +78,137 @@ OpDecorate %56 Location 0 %7 = OpTypeVector %5 4 %8 = OpTypeStruct %7 %4 %9 = OpTypeInt 32 1 -%11 = OpTypePointer Function %8 -%12 = OpConstantNull %8 -%16 = OpTypePointer Input %4 -%15 = OpVariable %16 Input -%18 = OpVariable %16 Input -%21 = OpTypePointer Output %7 -%20 = OpVariable %21 Output -%23 = OpTypePointer Output %4 -%22 = OpVariable %23 Output -%25 = OpTypeFunction %2 -%26 = OpConstant %5 1.0 +%13 = OpTypePointer Input %4 +%12 = OpVariable %13 Input +%15 = OpVariable %13 Input +%18 = OpTypePointer Output %7 +%17 = OpVariable %18 Output +%20 = OpTypePointer Output %4 +%19 = OpVariable %20 Output +%22 = OpTypeFunction %2 +%23 = OpConstant %5 1.0 +%25 = OpTypePointer Function %8 +%26 = OpConstantNull %8 %28 = OpTypePointer Function %4 %31 = OpTypeInt 32 0 %30 = OpConstant %31 1 %33 = OpTypePointer Function %7 %36 = OpConstant %31 0 -%42 = OpConstantNull %4 -%44 = OpTypePointer Function %9 -%45 = OpConstantNull %9 -%47 = OpTypePointer Function %5 -%48 = OpConstantNull %5 -%52 = OpTypePointer Input %7 -%51 = OpVariable %52 Input -%54 = OpVariable %16 Input -%56 = OpVariable %21 Output -%58 = OpConstant %9 0 -%59 = OpConstant %9 10 -%60 = OpConstant %5 0.001 -%61 = OpConstant %5 0.002 -%62 = OpConstant %9 1 -%70 = OpTypeBool -%78 = OpTypePointer Function %5 -%24 = OpFunction %2 None %25 -%13 = OpLabel -%10 = OpVariable %11 Function %12 -%17 = OpLoad %4 %15 -%19 = OpLoad %4 %18 -%14 = OpCompositeConstruct %6 %17 %19 +%44 = OpTypePointer Input %7 +%43 = OpVariable %44 Input +%46 = OpVariable %13 Input +%48 = OpVariable %18 Output +%50 = OpConstant %9 0 +%51 = OpConstant %9 10 +%52 = OpConstant %5 0.001 +%53 = OpConstant %5 0.002 +%54 = OpConstant %9 1 +%56 = OpConstantNull %4 +%58 = OpTypePointer Function %9 +%60 = OpTypePointer Function %5 +%61 = OpConstantNull %5 +%69 = OpTypeBool +%77 = OpTypePointer Function %5 +%21 = OpFunction %2 None %22 +%10 = OpLabel +%24 = OpVariable %25 Function %26 +%14 = OpLoad %4 %12 +%16 = OpLoad %4 %15 +%11 = OpCompositeConstruct %6 %14 %16 OpBranch %27 %27 = OpLabel OpLine %3 16 5 -%29 = OpCompositeExtract %4 %14 1 +%29 = OpCompositeExtract %4 %11 1 OpLine %3 16 5 -%32 = OpAccessChain %28 %10 %30 +%32 = OpAccessChain %28 %24 %30 OpStore %32 %29 OpLine %3 17 5 -%34 = OpCompositeExtract %4 %14 0 +%34 = OpCompositeExtract %4 %11 0 OpLine %3 17 25 -%35 = OpCompositeConstruct %7 %34 %26 +%35 = OpCompositeConstruct %7 %34 %23 OpLine %3 17 5 -%37 = OpAccessChain %33 %10 %36 +%37 = OpAccessChain %33 %24 %36 OpStore %37 %35 OpLine %3 1 1 -%38 = OpLoad %8 %10 +%38 = OpLoad %8 %24 %39 = OpCompositeExtract %7 %38 0 -OpStore %20 %39 +OpStore %17 %39 %40 = OpCompositeExtract %4 %38 1 -OpStore %22 %40 +OpStore %19 %40 OpReturn OpFunctionEnd -%57 = OpFunction %2 None %25 -%49 = OpLabel -%41 = OpVariable %28 Function %42 -%43 = OpVariable %44 Function %45 -%46 = OpVariable %47 Function %48 -%53 = OpLoad %7 %51 -%55 = OpLoad %4 %54 -%50 = OpCompositeConstruct %8 %53 %55 -OpBranch %63 -%63 = OpLabel +%49 = OpFunction %2 None %22 +%41 = OpLabel +%55 = OpVariable %28 Function %56 +%57 = OpVariable %58 Function %50 +%59 = OpVariable %60 Function %61 +%45 = OpLoad %7 %43 +%47 = OpLoad %4 %46 +%42 = OpCompositeConstruct %8 %45 %47 +OpBranch %62 +%62 = OpLabel OpLine %3 25 17 -%64 = OpCompositeExtract %4 %50 1 +%63 = OpCompositeExtract %4 %42 1 OpLine %3 25 5 -OpStore %41 %64 -OpLine %3 26 10 -OpStore %43 %58 -OpBranch %65 -%65 = OpLabel +OpStore %55 %63 +OpBranch %64 +%64 = OpLabel OpLine %3 26 5 -OpLoopMerge %66 %68 None -OpBranch %67 -%67 = OpLabel -OpLine %3 1 1 -%69 = OpLoad %9 %43 -OpLine %3 26 21 -%71 = OpSLessThan %70 %69 %59 -OpLine %3 26 20 -OpSelectionMerge %72 None -OpBranchConditional %71 %72 %73 -%73 = OpLabel +OpLoopMerge %65 %67 None OpBranch %66 -%72 = OpLabel -OpBranch %74 -%74 = OpLabel -OpLine %3 27 18 -%76 = OpLoad %9 %43 -%77 = OpConvertSToF %5 %76 -OpLine %3 27 9 -OpStore %46 %77 -OpLine %3 28 9 -%79 = OpLoad %5 %46 -OpLine %3 28 9 -%80 = OpFMul %5 %79 %60 -%81 = OpAccessChain %78 %41 %36 -%82 = OpLoad %5 %81 -%83 = OpFAdd %5 %82 %80 -OpLine %3 28 9 -%84 = OpAccessChain %78 %41 %36 -OpStore %84 %83 -OpLine %3 29 9 -%85 = OpLoad %5 %46 -OpLine %3 29 9 -%86 = OpFMul %5 %85 %61 -%87 = OpAccessChain %78 %41 %30 -%88 = OpLoad %5 %87 -%89 = OpFAdd %5 %88 %86 -OpLine %3 29 9 -%90 = OpAccessChain %78 %41 %30 -OpStore %90 %89 -OpBranch %75 -%75 = OpLabel -OpBranch %68 -%68 = OpLabel -OpLine %3 26 29 -%91 = OpLoad %9 %43 -%92 = OpIAdd %9 %91 %62 -OpLine %3 26 29 -OpStore %43 %92 -OpBranch %65 %66 = OpLabel OpLine %3 1 1 -%93 = OpLoad %4 %41 +%68 = OpLoad %9 %57 +OpLine %3 26 21 +%70 = OpSLessThan %69 %68 %51 +OpLine %3 26 20 +OpSelectionMerge %71 None +OpBranchConditional %70 %71 %72 +%72 = OpLabel +OpBranch %65 +%71 = OpLabel +OpBranch %73 +%73 = OpLabel +OpLine %3 27 18 +%75 = OpLoad %9 %57 +%76 = OpConvertSToF %5 %75 +OpLine %3 27 9 +OpStore %59 %76 +OpLine %3 28 9 +%78 = OpLoad %5 %59 +OpLine %3 28 9 +%79 = OpFMul %5 %78 %52 +%80 = OpAccessChain %77 %55 %36 +%81 = OpLoad %5 %80 +%82 = OpFAdd %5 %81 %79 +OpLine %3 28 9 +%83 = OpAccessChain %77 %55 %36 +OpStore %83 %82 +OpLine %3 29 9 +%84 = OpLoad %5 %59 +OpLine %3 29 9 +%85 = OpFMul %5 %84 %53 +%86 = OpAccessChain %77 %55 %30 +%87 = OpLoad %5 %86 +%88 = OpFAdd %5 %87 %85 +OpLine %3 29 9 +%89 = OpAccessChain %77 %55 %30 +OpStore %89 %88 +OpBranch %74 +%74 = OpLabel +OpBranch %67 +%67 = OpLabel +OpLine %3 26 29 +%90 = OpLoad %9 %57 +%91 = OpIAdd %9 %90 %54 +OpLine %3 26 29 +OpStore %57 %91 +OpBranch %64 +%65 = OpLabel +OpLine %3 1 1 +%92 = OpLoad %4 %55 OpLine %3 32 12 -%94 = OpCompositeConstruct %7 %93 %26 -OpStore %56 %94 +%93 = OpCompositeConstruct %7 %92 %23 +OpStore %48 %93 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/debug-symbol-terrain.spvasm b/tests/out/spv/debug-symbol-terrain.spvasm index 044f1f169..3f53036ad 100644 --- a/tests/out/spv/debug-symbol-terrain.spvasm +++ b/tests/out/spv/debug-symbol-terrain.spvasm @@ -1,19 +1,19 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 641 +; Bound: 638 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %344 "gen_terrain_compute" %341 -OpEntryPoint Vertex %414 "gen_terrain_vertex" %405 %408 %410 %412 -OpEntryPoint Fragment %464 "gen_terrain_fragment" %454 %456 %459 %462 %463 -OpEntryPoint Vertex %555 "vs_main" %546 %549 %551 %552 %554 -OpEntryPoint Fragment %581 "fs_main" %574 %576 %578 %580 -OpExecutionMode %344 LocalSize 64 1 1 -OpExecutionMode %464 OriginUpperLeft -OpExecutionMode %581 OriginUpperLeft +OpEntryPoint GLCompute %341 "gen_terrain_compute" %338 +OpEntryPoint Vertex %411 "gen_terrain_vertex" %402 %405 %407 %409 +OpEntryPoint Fragment %459 "gen_terrain_fragment" %449 %451 %454 %457 %458 +OpEntryPoint Vertex %552 "vs_main" %543 %546 %548 %549 %551 +OpEntryPoint Fragment %577 "fs_main" %570 %572 %574 %576 +OpExecutionMode %341 LocalSize 64 1 1 +OpExecutionMode %459 OriginUpperLeft +OpExecutionMode %577 OriginUpperLeft %3 = OpString "debug-symbol-terrain.wgsl" OpSource Unknown 0 %3 "// Taken from https://github.com/sotrh/learn-wgpu/blob/11820796f5e1dbce42fb1119f04ddeb4b167d2a0/code/intermediate/tutorial13-terrain/src/terrain.wgsl // ============================ @@ -358,56 +358,56 @@ OpName %49 "t_normal" OpName %50 "s_normal" OpName %52 "x" OpName %53 "permute3" -OpName %65 "i" -OpName %68 "i1" -OpName %69 "x12" -OpName %72 "m" -OpName %76 "v" -OpName %77 "snoise2" -OpName %204 "x" -OpName %205 "v" -OpName %208 "a" -OpName %209 "i" -OpName %213 "p" -OpName %214 "fbm" -OpName %254 "p" -OpName %255 "min_max_height" -OpName %256 "terrain_point" -OpName %267 "p" -OpName %268 "min_max_height" -OpName %269 "terrain_vertex" -OpName %299 "vert_index" -OpName %300 "chunk_size" -OpName %301 "chunk_corner" -OpName %302 "index_to_p" -OpName %318 "p" -OpName %319 "color23" -OpName %341 "gid" -OpName %344 "gen_terrain_compute" -OpName %405 "vindex" -OpName %408 "index" -OpName %410 "position" -OpName %412 "uv" -OpName %414 "gen_terrain_vertex" -OpName %450 "vert_component" -OpName %451 "index" -OpName %454 "index" -OpName %456 "position" -OpName %459 "uv" +OpName %66 "v" +OpName %67 "snoise2" +OpName %90 "i" +OpName %93 "i1" +OpName %95 "x12" +OpName %98 "m" +OpName %203 "p" +OpName %204 "fbm" +OpName %209 "x" +OpName %211 "v" +OpName %213 "a" +OpName %214 "i" +OpName %251 "p" +OpName %252 "min_max_height" +OpName %253 "terrain_point" +OpName %264 "p" +OpName %265 "min_max_height" +OpName %266 "terrain_vertex" +OpName %296 "vert_index" +OpName %297 "chunk_size" +OpName %298 "chunk_corner" +OpName %299 "index_to_p" +OpName %315 "p" +OpName %316 "color23" +OpName %338 "gid" +OpName %341 "gen_terrain_compute" +OpName %402 "vindex" +OpName %405 "index" +OpName %407 "position" +OpName %409 "uv" +OpName %411 "gen_terrain_vertex" +OpName %449 "index" +OpName %451 "position" +OpName %454 "uv" +OpName %457 "vert_component" +OpName %458 "index" +OpName %459 "gen_terrain_fragment" OpName %462 "vert_component" OpName %463 "index" -OpName %464 "gen_terrain_fragment" -OpName %546 "position" +OpName %543 "position" +OpName %546 "normal" +OpName %548 "clip_position" OpName %549 "normal" -OpName %551 "clip_position" -OpName %552 "normal" -OpName %554 "world_pos" -OpName %555 "vs_main" -OpName %571 "color" -OpName %574 "clip_position" -OpName %576 "normal" -OpName %578 "world_pos" -OpName %581 "fs_main" +OpName %551 "world_pos" +OpName %552 "vs_main" +OpName %570 "clip_position" +OpName %572 "normal" +OpName %574 "world_pos" +OpName %577 "fs_main" +OpName %586 "color" OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %13 1 Offset 8 OpMemberDecorate %13 2 Offset 16 @@ -466,27 +466,27 @@ OpDecorate %49 DescriptorSet 2 OpDecorate %49 Binding 2 OpDecorate %50 DescriptorSet 2 OpDecorate %50 Binding 3 -OpDecorate %341 BuiltIn GlobalInvocationId -OpDecorate %405 BuiltIn VertexIndex -OpDecorate %408 Location 0 -OpDecorate %408 Flat -OpDecorate %410 BuiltIn Position -OpDecorate %412 Location 1 -OpDecorate %454 Location 0 -OpDecorate %454 Flat -OpDecorate %456 BuiltIn FragCoord -OpDecorate %459 Location 1 -OpDecorate %462 Location 0 -OpDecorate %463 Location 1 -OpDecorate %546 Location 0 -OpDecorate %549 Location 1 -OpDecorate %551 BuiltIn Position -OpDecorate %552 Location 0 -OpDecorate %554 Location 1 -OpDecorate %574 BuiltIn FragCoord +OpDecorate %338 BuiltIn GlobalInvocationId +OpDecorate %402 BuiltIn VertexIndex +OpDecorate %405 Location 0 +OpDecorate %405 Flat +OpDecorate %407 BuiltIn Position +OpDecorate %409 Location 1 +OpDecorate %449 Location 0 +OpDecorate %449 Flat +OpDecorate %451 BuiltIn FragCoord +OpDecorate %454 Location 1 +OpDecorate %457 Location 0 +OpDecorate %458 Location 1 +OpDecorate %543 Location 0 +OpDecorate %546 Location 1 +OpDecorate %548 BuiltIn Position +OpDecorate %549 Location 0 +OpDecorate %551 Location 1 +OpDecorate %570 BuiltIn FragCoord +OpDecorate %572 Location 0 +OpDecorate %574 Location 1 OpDecorate %576 Location 0 -OpDecorate %578 Location 1 -OpDecorate %580 Location 0 %2 = OpTypeVoid %5 = OpTypeFloat 32 %4 = OpTypeVector %5 3 @@ -538,920 +538,907 @@ OpDecorate %580 Location 0 %54 = OpTypeFunction %4 %4 %55 = OpConstant %5 34.0 %56 = OpConstant %5 1.0 -%57 = OpConstant %5 289.0 -%66 = OpTypePointer Function %6 -%67 = OpConstantNull %6 -%70 = OpTypePointer Function %7 -%71 = OpConstantNull %7 -%73 = OpTypePointer Function %4 -%74 = OpConstantNull %4 -%78 = OpTypeFunction %5 %6 -%79 = OpConstant %5 0.21132487 -%80 = OpConstant %5 0.36602542 -%81 = OpConstant %5 -0.57735026 -%82 = OpConstant %5 0.024390243 -%83 = OpConstant %5 0.0 -%84 = OpConstant %5 0.5 -%85 = OpConstant %5 2.0 +%57 = OpConstantComposite %4 %56 %56 %56 +%58 = OpConstant %5 289.0 +%59 = OpConstantComposite %4 %58 %58 %58 +%68 = OpTypeFunction %5 %6 +%69 = OpConstant %5 0.21132487 +%70 = OpConstant %5 0.36602542 +%71 = OpConstant %5 -0.57735026 +%72 = OpConstant %5 0.024390243 +%73 = OpConstantComposite %7 %69 %70 %71 %72 +%74 = OpConstantComposite %6 %70 %70 +%75 = OpConstantComposite %6 %69 %69 +%76 = OpConstant %5 0.0 +%77 = OpConstantComposite %6 %56 %76 +%78 = OpConstantComposite %6 %76 %56 +%79 = OpConstantComposite %7 %69 %69 %71 %71 +%80 = OpConstantComposite %6 %58 %58 +%81 = OpConstant %5 0.5 +%82 = OpConstantComposite %4 %81 %81 %81 +%83 = OpConstantComposite %4 %76 %76 %76 +%84 = OpConstant %5 2.0 +%85 = OpConstantComposite %4 %72 %72 %72 %86 = OpConstant %5 1.7928429 %87 = OpConstant %5 0.85373473 -%88 = OpConstant %5 130.0 -%107 = OpTypeBool -%110 = OpTypeVector %107 2 -%121 = OpTypePointer Function %5 -%122 = OpConstant %8 1 -%131 = OpConstant %8 0 -%206 = OpTypePointer Function %5 -%207 = OpConstantNull %5 -%210 = OpTypePointer Function %8 -%211 = OpConstantNull %8 -%215 = OpConstant %8 5 -%216 = OpConstant %5 0.01 -%217 = OpConstant %5 100.0 -%257 = OpTypeFunction %4 %6 %6 -%270 = OpTypeFunction %14 %6 %6 -%271 = OpConstant %5 0.1 -%272 = OpConstant %5 -0.1 -%303 = OpTypeFunction %6 %8 %10 %11 -%320 = OpTypeFunction %4 %6 -%321 = OpConstant %5 23.0 -%322 = OpConstant %5 32.0 -%323 = OpConstant %5 -43.0 -%324 = OpConstant %5 3.0 -%342 = OpTypePointer Input %19 -%341 = OpVariable %342 Input -%345 = OpTypeFunction %2 -%346 = OpTypePointer Uniform %13 -%348 = OpConstant %8 6 -%349 = OpConstant %8 2 -%350 = OpConstant %8 3 -%351 = OpConstant %8 4 -%354 = OpTypePointer Uniform %10 -%357 = OpTypePointer Uniform %11 -%361 = OpTypePointer StorageBuffer %15 -%362 = OpTypePointer StorageBuffer %14 -%363 = OpTypePointer Uniform %6 -%370 = OpTypePointer Uniform %8 -%391 = OpTypePointer StorageBuffer %17 -%392 = OpTypePointer StorageBuffer %8 -%406 = OpTypePointer Input %8 -%405 = OpVariable %406 Input -%409 = OpTypePointer Output %8 -%408 = OpVariable %409 Output -%411 = OpTypePointer Output %7 -%410 = OpVariable %411 Output -%413 = OpTypePointer Output %6 -%412 = OpVariable %413 Output -%415 = OpTypePointer Uniform %20 -%417 = OpConstant %5 -1.0 -%432 = OpTypePointer Uniform %8 -%454 = OpVariable %406 Input -%457 = OpTypePointer Input %7 -%456 = OpVariable %457 Input -%460 = OpTypePointer Input %6 -%459 = OpVariable %460 Input -%462 = OpVariable %409 Output -%463 = OpVariable %409 Output -%466 = OpConstant %5 6.0 -%547 = OpTypePointer Input %4 -%546 = OpVariable %547 Input -%549 = OpVariable %547 Input -%551 = OpVariable %411 Output -%553 = OpTypePointer Output %4 -%552 = OpVariable %553 Output -%554 = OpVariable %553 Output -%556 = OpTypePointer Uniform %24 -%559 = OpTypePointer Uniform %23 -%574 = OpVariable %457 Input -%576 = OpVariable %547 Input -%578 = OpVariable %547 Input -%580 = OpVariable %411 Output -%583 = OpTypePointer Uniform %25 -%585 = OpConstant %5 0.7 -%586 = OpConstant %5 0.2 -%605 = OpTypePointer Uniform %4 -%614 = OpTypePointer Uniform %7 +%88 = OpConstantComposite %4 %86 %86 %86 +%89 = OpConstant %5 130.0 +%91 = OpTypePointer Function %6 +%92 = OpConstantNull %6 +%94 = OpConstantNull %6 +%96 = OpTypePointer Function %7 +%97 = OpConstantNull %7 +%99 = OpTypePointer Function %4 +%100 = OpConstantNull %4 +%114 = OpTypeBool +%117 = OpTypeVector %114 2 +%126 = OpTypePointer Function %5 +%127 = OpConstant %8 1 +%136 = OpConstant %8 0 +%205 = OpConstant %8 5 +%206 = OpConstant %5 0.01 +%207 = OpConstant %5 100.0 +%208 = OpConstantComposite %6 %207 %207 +%210 = OpConstantNull %6 +%212 = OpTypePointer Function %5 +%215 = OpTypePointer Function %8 +%254 = OpTypeFunction %4 %6 %6 +%267 = OpTypeFunction %14 %6 %6 +%268 = OpConstant %5 0.1 +%269 = OpConstantComposite %6 %268 %76 +%270 = OpConstantComposite %6 %76 %268 +%271 = OpConstant %5 -0.1 +%272 = OpConstantComposite %6 %271 %76 +%273 = OpConstantComposite %6 %76 %271 +%300 = OpTypeFunction %6 %8 %10 %11 +%317 = OpTypeFunction %4 %6 +%318 = OpConstant %5 23.0 +%319 = OpConstant %5 32.0 +%320 = OpConstantComposite %6 %318 %319 +%321 = OpConstant %5 -43.0 +%322 = OpConstant %5 3.0 +%323 = OpConstantComposite %6 %321 %322 +%339 = OpTypePointer Input %19 +%338 = OpVariable %339 Input +%342 = OpTypeFunction %2 +%343 = OpTypePointer Uniform %13 +%345 = OpConstant %8 6 +%346 = OpConstant %8 2 +%347 = OpConstant %8 3 +%348 = OpConstant %8 4 +%351 = OpTypePointer Uniform %10 +%354 = OpTypePointer Uniform %11 +%358 = OpTypePointer StorageBuffer %15 +%359 = OpTypePointer StorageBuffer %14 +%360 = OpTypePointer Uniform %6 +%367 = OpTypePointer Uniform %8 +%388 = OpTypePointer StorageBuffer %17 +%389 = OpTypePointer StorageBuffer %8 +%403 = OpTypePointer Input %8 +%402 = OpVariable %403 Input +%406 = OpTypePointer Output %8 +%405 = OpVariable %406 Output +%408 = OpTypePointer Output %7 +%407 = OpVariable %408 Output +%410 = OpTypePointer Output %6 +%409 = OpVariable %410 Output +%412 = OpTypePointer Uniform %20 +%414 = OpConstant %5 -1.0 +%415 = OpConstantComposite %6 %414 %414 +%429 = OpTypePointer Uniform %8 +%449 = OpVariable %403 Input +%452 = OpTypePointer Input %7 +%451 = OpVariable %452 Input +%455 = OpTypePointer Input %6 +%454 = OpVariable %455 Input +%457 = OpVariable %406 Output +%458 = OpVariable %406 Output +%461 = OpConstant %5 6.0 +%544 = OpTypePointer Input %4 +%543 = OpVariable %544 Input +%546 = OpVariable %544 Input +%548 = OpVariable %408 Output +%550 = OpTypePointer Output %4 +%549 = OpVariable %550 Output +%551 = OpVariable %550 Output +%553 = OpTypePointer Uniform %24 +%556 = OpTypePointer Uniform %23 +%570 = OpVariable %452 Input +%572 = OpVariable %544 Input +%574 = OpVariable %544 Input +%576 = OpVariable %408 Output +%579 = OpTypePointer Uniform %25 +%581 = OpConstantComposite %4 %268 %268 %268 +%582 = OpConstant %5 0.7 +%583 = OpConstantComposite %4 %81 %268 %582 +%584 = OpConstant %5 0.2 +%585 = OpConstantComposite %4 %584 %584 %584 +%587 = OpConstantNull %4 +%602 = OpTypePointer Uniform %4 +%611 = OpTypePointer Uniform %7 %53 = OpFunction %4 None %54 %52 = OpFunctionParameter %4 %51 = OpLabel -OpBranch %58 -%58 = OpLabel +OpBranch %60 +%60 = OpLabel OpLine %3 10 52 -%59 = OpVectorTimesScalar %4 %52 %55 +%61 = OpVectorTimesScalar %4 %52 %55 OpLine %3 10 50 -%60 = OpCompositeConstruct %4 %56 %56 %56 -%61 = OpFAdd %4 %59 %60 -%62 = OpFMul %4 %61 %52 +%62 = OpFAdd %4 %61 %57 +%63 = OpFMul %4 %62 %52 OpLine %3 10 49 -%63 = OpCompositeConstruct %4 %57 %57 %57 -%64 = OpFRem %4 %62 %63 +%64 = OpFRem %4 %63 %59 OpReturnValue %64 OpFunctionEnd -%77 = OpFunction %5 None %78 -%76 = OpFunctionParameter %6 -%75 = OpLabel -%68 = OpVariable %66 Function %67 -%72 = OpVariable %73 Function %74 -%65 = OpVariable %66 Function %67 -%69 = OpVariable %70 Function %71 -OpBranch %89 -%89 = OpLabel +%67 = OpFunction %5 None %68 +%66 = OpFunctionParameter %6 +%65 = OpLabel +%93 = OpVariable %91 Function %94 +%98 = OpVariable %99 Function %100 +%90 = OpVariable %91 Function %92 +%95 = OpVariable %96 Function %97 +OpBranch %101 +%101 = OpLabel OpLine %3 13 13 -%90 = OpCompositeConstruct %7 %79 %80 %81 %82 OpLine %3 14 24 -%91 = OpCompositeConstruct %6 %80 %80 -%92 = OpDot %5 %76 %91 -%93 = OpCompositeConstruct %6 %92 %92 -%94 = OpFAdd %6 %76 %93 -%95 = OpExtInst %6 %1 Floor %94 +%102 = OpDot %5 %66 %74 +%103 = OpCompositeConstruct %6 %102 %102 +%104 = OpFAdd %6 %66 %103 +%105 = OpExtInst %6 %1 Floor %104 OpLine %3 14 5 -OpStore %65 %95 +OpStore %90 %105 OpLine %3 15 14 -%96 = OpLoad %6 %65 -%97 = OpFSub %6 %76 %96 -%98 = OpLoad %6 %65 -%99 = OpCompositeConstruct %6 %79 %79 -%100 = OpDot %5 %98 %99 -%101 = OpCompositeConstruct %6 %100 %100 -%102 = OpFAdd %6 %97 %101 +%106 = OpLoad %6 %90 +%107 = OpFSub %6 %66 %106 +%108 = OpLoad %6 %90 +%109 = OpDot %5 %108 %75 +%110 = OpCompositeConstruct %6 %109 %109 +%111 = OpFAdd %6 %107 %110 OpLine %3 17 32 -%103 = OpCompositeConstruct %6 %56 %83 OpLine %3 17 25 -%104 = OpCompositeConstruct %6 %83 %56 -%105 = OpCompositeExtract %5 %102 0 -%106 = OpCompositeExtract %5 %102 1 -%108 = OpFOrdLessThan %107 %105 %106 -%111 = OpCompositeConstruct %110 %108 %108 -%109 = OpSelect %6 %111 %104 %103 +%112 = OpCompositeExtract %5 %111 0 +%113 = OpCompositeExtract %5 %111 1 +%115 = OpFOrdLessThan %114 %112 %113 +%118 = OpCompositeConstruct %117 %115 %115 +%116 = OpSelect %6 %118 %78 %77 OpLine %3 17 5 -OpStore %68 %109 +OpStore %93 %116 OpLine %3 18 26 -%112 = OpVectorShuffle %7 %102 %102 0 1 0 1 -%113 = OpCompositeConstruct %7 %79 %79 %81 %81 -%114 = OpFAdd %7 %112 %113 -%115 = OpLoad %6 %68 +%119 = OpVectorShuffle %7 %111 %111 0 1 0 1 +%120 = OpFAdd %7 %119 %79 +%121 = OpLoad %6 %93 OpLine %3 18 26 -%116 = OpCompositeConstruct %7 %115 %83 %83 -%117 = OpFSub %7 %114 %116 +%122 = OpCompositeConstruct %7 %121 %76 %76 +%123 = OpFSub %7 %120 %122 OpLine %3 18 5 -OpStore %69 %117 +OpStore %95 %123 OpLine %3 1 1 -%118 = OpLoad %6 %65 +%124 = OpLoad %6 %90 OpLine %3 19 9 -%119 = OpCompositeConstruct %6 %57 %57 -%120 = OpFRem %6 %118 %119 +%125 = OpFRem %6 %124 %80 OpLine %3 19 5 -OpStore %65 %120 +OpStore %90 %125 OpLine %3 20 31 -%123 = OpAccessChain %121 %65 %122 -%124 = OpLoad %5 %123 +%128 = OpAccessChain %126 %90 %127 +%129 = OpLoad %5 %128 OpLine %3 20 51 -%125 = OpAccessChain %121 %68 %122 -%126 = OpLoad %5 %125 +%130 = OpAccessChain %126 %93 %127 +%131 = OpLoad %5 %130 OpLine %3 20 31 -%127 = OpCompositeConstruct %4 %83 %126 %56 -%128 = OpCompositeConstruct %4 %124 %124 %124 -%129 = OpFAdd %4 %128 %127 +%132 = OpCompositeConstruct %4 %76 %131 %56 +%133 = OpCompositeConstruct %4 %129 %129 %129 +%134 = OpFAdd %4 %133 %132 OpLine %3 20 22 -%130 = OpFunctionCall %4 %53 %129 +%135 = OpFunctionCall %4 %53 %134 OpLine %3 20 22 -%132 = OpAccessChain %121 %65 %131 -%133 = OpLoad %5 %132 -%134 = OpCompositeConstruct %4 %133 %133 %133 -%135 = OpFAdd %4 %130 %134 +%137 = OpAccessChain %126 %90 %136 +%138 = OpLoad %5 %137 +%139 = OpCompositeConstruct %4 %138 %138 %138 +%140 = OpFAdd %4 %135 %139 OpLine %3 20 84 -%136 = OpAccessChain %121 %68 %131 -%137 = OpLoad %5 %136 +%141 = OpAccessChain %126 %93 %136 +%142 = OpLoad %5 %141 OpLine %3 20 22 -%138 = OpCompositeConstruct %4 %83 %137 %56 -%139 = OpFAdd %4 %135 %138 +%143 = OpCompositeConstruct %4 %76 %142 %56 +%144 = OpFAdd %4 %140 %143 OpLine %3 20 13 -%140 = OpFunctionCall %4 %53 %139 +%145 = OpFunctionCall %4 %53 %144 OpLine %3 21 28 -%141 = OpDot %5 %102 %102 -%142 = OpLoad %7 %69 -%143 = OpVectorShuffle %6 %142 %142 0 1 -%144 = OpLoad %7 %69 -%145 = OpVectorShuffle %6 %144 %144 0 1 -%146 = OpDot %5 %143 %145 -%147 = OpLoad %7 %69 -%148 = OpVectorShuffle %6 %147 %147 2 3 -%149 = OpLoad %7 %69 -%150 = OpVectorShuffle %6 %149 %149 2 3 +%146 = OpDot %5 %111 %111 +%147 = OpLoad %7 %95 +%148 = OpVectorShuffle %6 %147 %147 0 1 +%149 = OpLoad %7 %95 +%150 = OpVectorShuffle %6 %149 %149 0 1 %151 = OpDot %5 %148 %150 -%152 = OpCompositeConstruct %4 %141 %146 %151 -%153 = OpCompositeConstruct %4 %84 %84 %84 -%154 = OpFSub %4 %153 %152 +%152 = OpLoad %7 %95 +%153 = OpVectorShuffle %6 %152 %152 2 3 +%154 = OpLoad %7 %95 +%155 = OpVectorShuffle %6 %154 %154 2 3 +%156 = OpDot %5 %153 %155 +%157 = OpCompositeConstruct %4 %146 %151 %156 +%158 = OpFSub %4 %82 %157 OpLine %3 21 24 -%155 = OpCompositeConstruct %4 %83 %83 %83 -%156 = OpExtInst %4 %1 FMax %154 %155 +%159 = OpExtInst %4 %1 FMax %158 %83 OpLine %3 21 5 -OpStore %72 %156 +OpStore %98 %159 OpLine %3 22 9 -%157 = OpLoad %4 %72 -%158 = OpLoad %4 %72 -%159 = OpFMul %4 %157 %158 -OpLine %3 22 5 -OpStore %72 %159 -OpLine %3 23 9 -%160 = OpLoad %4 %72 -%161 = OpLoad %4 %72 +%160 = OpLoad %4 %98 +%161 = OpLoad %4 %98 %162 = OpFMul %4 %160 %161 +OpLine %3 22 5 +OpStore %98 %162 +OpLine %3 23 9 +%163 = OpLoad %4 %98 +%164 = OpLoad %4 %98 +%165 = OpFMul %4 %163 %164 OpLine %3 23 5 -OpStore %72 %162 +OpStore %98 %165 OpLine %3 24 13 -%163 = OpCompositeConstruct %4 %82 %82 %82 -%164 = OpFMul %4 %140 %163 -%165 = OpExtInst %4 %1 Fract %164 -%166 = OpVectorTimesScalar %4 %165 %85 +%166 = OpFMul %4 %145 %85 +%167 = OpExtInst %4 %1 Fract %166 +%168 = OpVectorTimesScalar %4 %167 %84 OpLine %3 24 13 -%167 = OpCompositeConstruct %4 %56 %56 %56 -%168 = OpFSub %4 %166 %167 +%169 = OpFSub %4 %168 %57 OpLine %3 25 13 -%169 = OpExtInst %4 %1 FAbs %168 +%170 = OpExtInst %4 %1 FAbs %169 OpLine %3 25 13 -%170 = OpCompositeConstruct %4 %84 %84 %84 -%171 = OpFSub %4 %169 %170 +%171 = OpFSub %4 %170 %82 OpLine %3 26 14 -%172 = OpCompositeConstruct %4 %84 %84 %84 -%173 = OpFAdd %4 %168 %172 -%174 = OpExtInst %4 %1 Floor %173 +%172 = OpFAdd %4 %169 %82 +%173 = OpExtInst %4 %1 Floor %172 OpLine %3 27 14 -%175 = OpFSub %4 %168 %174 +%174 = OpFSub %4 %169 %173 OpLine %3 1 1 -%176 = OpLoad %4 %72 +%175 = OpLoad %4 %98 OpLine %3 28 9 -%177 = OpFMul %4 %175 %175 -%178 = OpFMul %4 %171 %171 -%179 = OpFAdd %4 %177 %178 -%180 = OpVectorTimesScalar %4 %179 %87 -%181 = OpCompositeConstruct %4 %86 %86 %86 -%182 = OpFSub %4 %181 %180 -%183 = OpFMul %4 %176 %182 +%176 = OpFMul %4 %174 %174 +%177 = OpFMul %4 %171 %171 +%178 = OpFAdd %4 %176 %177 +%179 = OpVectorTimesScalar %4 %178 %87 +%180 = OpFSub %4 %88 %179 +%181 = OpFMul %4 %175 %180 OpLine %3 28 5 -OpStore %72 %183 +OpStore %98 %181 OpLine %3 29 13 -%184 = OpCompositeExtract %5 %175 0 -%185 = OpCompositeExtract %5 %102 0 -%186 = OpFMul %5 %184 %185 -%187 = OpCompositeExtract %5 %171 0 -%188 = OpCompositeExtract %5 %102 1 -%189 = OpFMul %5 %187 %188 -%190 = OpFAdd %5 %186 %189 -%191 = OpVectorShuffle %6 %175 %175 1 2 -%192 = OpLoad %7 %69 -%193 = OpVectorShuffle %6 %192 %192 0 2 -%194 = OpFMul %6 %191 %193 -%195 = OpVectorShuffle %6 %171 %171 1 2 -%196 = OpLoad %7 %69 -%197 = OpVectorShuffle %6 %196 %196 1 3 -%198 = OpFMul %6 %195 %197 -%199 = OpFAdd %6 %194 %198 -%200 = OpCompositeConstruct %4 %190 %199 +%182 = OpCompositeExtract %5 %174 0 +%183 = OpCompositeExtract %5 %111 0 +%184 = OpFMul %5 %182 %183 +%185 = OpCompositeExtract %5 %171 0 +%186 = OpCompositeExtract %5 %111 1 +%187 = OpFMul %5 %185 %186 +%188 = OpFAdd %5 %184 %187 +%189 = OpVectorShuffle %6 %174 %174 1 2 +%190 = OpLoad %7 %95 +%191 = OpVectorShuffle %6 %190 %190 0 2 +%192 = OpFMul %6 %189 %191 +%193 = OpVectorShuffle %6 %171 %171 1 2 +%194 = OpLoad %7 %95 +%195 = OpVectorShuffle %6 %194 %194 1 3 +%196 = OpFMul %6 %193 %195 +%197 = OpFAdd %6 %192 %196 +%198 = OpCompositeConstruct %4 %188 %197 OpLine %3 30 12 -%201 = OpLoad %4 %72 -%202 = OpDot %5 %201 %200 -%203 = OpFMul %5 %88 %202 -OpReturnValue %203 +%199 = OpLoad %4 %98 +%200 = OpDot %5 %199 %198 +%201 = OpFMul %5 %89 %200 +OpReturnValue %201 OpFunctionEnd -%214 = OpFunction %5 None %78 -%213 = OpFunctionParameter %6 -%212 = OpLabel -%205 = OpVariable %206 Function %207 -%209 = OpVariable %210 Function %211 -%204 = OpVariable %66 Function %67 -%208 = OpVariable %206 Function %207 -OpBranch %218 -%218 = OpLabel +%204 = OpFunction %5 None %68 +%203 = OpFunctionParameter %6 +%202 = OpLabel +%211 = OpVariable %212 Function %76 +%214 = OpVariable %215 Function %136 +%209 = OpVariable %91 Function %210 +%213 = OpVariable %212 Function %81 +OpBranch %216 +%216 = OpLabel OpLine %3 36 13 -%219 = OpVectorTimesScalar %6 %213 %216 +%217 = OpVectorTimesScalar %6 %203 %206 OpLine %3 36 5 -OpStore %204 %219 -OpLine %3 37 5 -OpStore %205 %83 -OpLine %3 38 5 -OpStore %208 %84 +OpStore %209 %217 OpLine %3 39 17 -%220 = OpCompositeConstruct %6 %217 %217 OpLine %3 40 24 -%221 = OpExtInst %5 %1 Cos %84 +%218 = OpExtInst %5 %1 Cos %81 OpLine %3 40 14 -%222 = OpExtInst %5 %1 Sin %84 -%223 = OpCompositeConstruct %6 %221 %222 +%219 = OpExtInst %5 %1 Sin %81 +%220 = OpCompositeConstruct %6 %218 %219 OpLine %3 41 15 -%224 = OpFNegate %5 %222 -%225 = OpCompositeConstruct %6 %221 %222 -%226 = OpCompositeConstruct %6 %224 %221 -%227 = OpCompositeConstruct %9 %225 %226 -OpLine %3 43 10 -OpStore %209 %131 +%221 = OpFNegate %5 %219 +%222 = OpCompositeConstruct %6 %218 %219 +%223 = OpCompositeConstruct %6 %221 %218 +%224 = OpCompositeConstruct %9 %222 %223 +OpBranch %225 +%225 = OpLabel +OpLine %3 43 5 +OpLoopMerge %226 %228 None +OpBranch %227 +%227 = OpLabel +OpLine %3 43 22 +%229 = OpLoad %8 %214 +%230 = OpULessThan %114 %229 %205 +OpLine %3 43 21 +OpSelectionMerge %231 None +OpBranchConditional %230 %231 %232 +%232 = OpLabel +OpBranch %226 +%231 = OpLabel +OpBranch %233 +%233 = OpLabel +OpLine %3 1 1 +%235 = OpLoad %5 %211 +%236 = OpLoad %5 %213 +%237 = OpLoad %6 %209 +OpLine %3 44 21 +%238 = OpFunctionCall %5 %67 %237 +OpLine %3 44 13 +%239 = OpFMul %5 %236 %238 +%240 = OpFAdd %5 %235 %239 +OpLine %3 44 9 +OpStore %211 %240 +OpLine %3 45 13 +%241 = OpLoad %6 %209 +%242 = OpMatrixTimesVector %6 %224 %241 +OpLine %3 45 13 +%243 = OpVectorTimesScalar %6 %242 %84 +%244 = OpFAdd %6 %243 %208 +OpLine %3 45 9 +OpStore %209 %244 +OpLine %3 1 1 +%245 = OpLoad %5 %213 +OpLine %3 46 13 +%246 = OpFMul %5 %245 %81 +OpLine %3 46 9 +OpStore %213 %246 +OpBranch %234 +%234 = OpLabel OpBranch %228 %228 = OpLabel -OpLine %3 43 5 -OpLoopMerge %229 %231 None -OpBranch %230 -%230 = OpLabel -OpLine %3 43 22 -%232 = OpLoad %8 %209 -%233 = OpULessThan %107 %232 %215 -OpLine %3 43 21 -OpSelectionMerge %234 None -OpBranchConditional %233 %234 %235 -%235 = OpLabel -OpBranch %229 -%234 = OpLabel -OpBranch %236 -%236 = OpLabel OpLine %3 1 1 -%238 = OpLoad %5 %205 -%239 = OpLoad %5 %208 -%240 = OpLoad %6 %204 -OpLine %3 44 21 -%241 = OpFunctionCall %5 %77 %240 -OpLine %3 44 13 -%242 = OpFMul %5 %239 %241 -%243 = OpFAdd %5 %238 %242 -OpLine %3 44 9 -OpStore %205 %243 -OpLine %3 45 13 -%244 = OpLoad %6 %204 -%245 = OpMatrixTimesVector %6 %227 %244 -OpLine %3 45 13 -%246 = OpVectorTimesScalar %6 %245 %85 -%247 = OpFAdd %6 %246 %220 -OpLine %3 45 9 -OpStore %204 %247 -OpLine %3 1 1 -%248 = OpLoad %5 %208 -OpLine %3 46 13 -%249 = OpFMul %5 %248 %84 -OpLine %3 46 9 -OpStore %208 %249 -OpBranch %237 -%237 = OpLabel -OpBranch %231 -%231 = OpLabel -OpLine %3 1 1 -%250 = OpLoad %8 %209 +%247 = OpLoad %8 %214 OpLine %3 43 43 -%251 = OpIAdd %8 %250 %122 +%248 = OpIAdd %8 %247 %127 OpLine %3 43 39 -OpStore %209 %251 -OpBranch %228 -%229 = OpLabel +OpStore %214 %248 +OpBranch %225 +%226 = OpLabel OpLine %3 1 1 -%252 = OpLoad %5 %205 -OpReturnValue %252 +%249 = OpLoad %5 %211 +OpReturnValue %249 OpFunctionEnd -%256 = OpFunction %4 None %257 -%254 = OpFunctionParameter %6 -%255 = OpFunctionParameter %6 -%253 = OpLabel -OpBranch %258 -%258 = OpLabel +%253 = OpFunction %4 None %254 +%251 = OpFunctionParameter %6 +%252 = OpFunctionParameter %6 +%250 = OpLabel +OpBranch %255 +%255 = OpLabel OpLine %3 77 9 -%259 = OpCompositeExtract %5 %254 0 -%260 = OpCompositeExtract %5 %255 0 -%261 = OpCompositeExtract %5 %255 1 +%256 = OpCompositeExtract %5 %251 0 +%257 = OpCompositeExtract %5 %252 0 +%258 = OpCompositeExtract %5 %252 1 OpLine %3 78 49 -%262 = OpFunctionCall %5 %214 %254 +%259 = OpFunctionCall %5 %204 %251 OpLine %3 76 12 -%263 = OpExtInst %5 %1 FMix %260 %261 %262 -%264 = OpCompositeExtract %5 %254 1 -%265 = OpCompositeConstruct %4 %259 %263 %264 -OpReturnValue %265 +%260 = OpExtInst %5 %1 FMix %257 %258 %259 +%261 = OpCompositeExtract %5 %251 1 +%262 = OpCompositeConstruct %4 %256 %260 %261 +OpReturnValue %262 OpFunctionEnd -%269 = OpFunction %14 None %270 -%267 = OpFunctionParameter %6 -%268 = OpFunctionParameter %6 -%266 = OpLabel -OpBranch %273 -%273 = OpLabel +%266 = OpFunction %14 None %267 +%264 = OpFunctionParameter %6 +%265 = OpFunctionParameter %6 +%263 = OpLabel +OpBranch %274 +%274 = OpLabel OpLine %3 84 13 -%274 = OpFunctionCall %4 %256 %267 %268 +%275 = OpFunctionCall %4 %253 %264 %265 OpLine %3 86 29 -%275 = OpCompositeConstruct %6 %271 %83 -%276 = OpFAdd %6 %267 %275 +%276 = OpFAdd %6 %264 %269 OpLine %3 86 15 -%277 = OpFunctionCall %4 %256 %276 %268 +%277 = OpFunctionCall %4 %253 %276 %265 OpLine %3 86 15 -%278 = OpFSub %4 %277 %274 +%278 = OpFSub %4 %277 %275 OpLine %3 87 29 -%279 = OpCompositeConstruct %6 %83 %271 -%280 = OpFAdd %6 %267 %279 +%279 = OpFAdd %6 %264 %270 OpLine %3 87 15 -%281 = OpFunctionCall %4 %256 %280 %268 +%280 = OpFunctionCall %4 %253 %279 %265 OpLine %3 87 15 -%282 = OpFSub %4 %281 %274 +%281 = OpFSub %4 %280 %275 OpLine %3 88 29 -%283 = OpCompositeConstruct %6 %272 %83 -%284 = OpFAdd %6 %267 %283 +%282 = OpFAdd %6 %264 %272 OpLine %3 88 15 -%285 = OpFunctionCall %4 %256 %284 %268 +%283 = OpFunctionCall %4 %253 %282 %265 OpLine %3 88 15 -%286 = OpFSub %4 %285 %274 +%284 = OpFSub %4 %283 %275 OpLine %3 89 29 -%287 = OpCompositeConstruct %6 %83 %272 -%288 = OpFAdd %6 %267 %287 +%285 = OpFAdd %6 %264 %273 OpLine %3 89 15 -%289 = OpFunctionCall %4 %256 %288 %268 +%286 = OpFunctionCall %4 %253 %285 %265 OpLine %3 89 15 -%290 = OpFSub %4 %289 %274 +%287 = OpFSub %4 %286 %275 OpLine %3 91 14 -%291 = OpExtInst %4 %1 Cross %282 %278 -%292 = OpExtInst %4 %1 Normalize %291 +%288 = OpExtInst %4 %1 Cross %281 %278 +%289 = OpExtInst %4 %1 Normalize %288 OpLine %3 92 14 -%293 = OpExtInst %4 %1 Cross %290 %286 -%294 = OpExtInst %4 %1 Normalize %293 +%290 = OpExtInst %4 %1 Cross %287 %284 +%291 = OpExtInst %4 %1 Normalize %290 OpLine %3 94 14 -%295 = OpFAdd %4 %292 %294 +%292 = OpFAdd %4 %289 %291 OpLine %3 94 13 -%296 = OpVectorTimesScalar %4 %295 %84 +%293 = OpVectorTimesScalar %4 %292 %81 OpLine %3 96 12 -%297 = OpCompositeConstruct %14 %274 %296 -OpReturnValue %297 +%294 = OpCompositeConstruct %14 %275 %293 +OpReturnValue %294 OpFunctionEnd -%302 = OpFunction %6 None %303 -%299 = OpFunctionParameter %8 -%300 = OpFunctionParameter %10 -%301 = OpFunctionParameter %11 -%298 = OpLabel -OpBranch %304 -%304 = OpLabel +%299 = OpFunction %6 None %300 +%296 = OpFunctionParameter %8 +%297 = OpFunctionParameter %10 +%298 = OpFunctionParameter %11 +%295 = OpLabel +OpBranch %301 +%301 = OpLabel OpLine %3 101 9 -%305 = OpConvertUToF %5 %299 -%306 = OpCompositeExtract %8 %300 0 +%302 = OpConvertUToF %5 %296 +%303 = OpCompositeExtract %8 %297 0 OpLine %3 101 9 -%307 = OpIAdd %8 %306 %122 -%308 = OpConvertUToF %5 %307 -%309 = OpFRem %5 %305 %308 -%310 = OpCompositeExtract %8 %300 0 +%304 = OpIAdd %8 %303 %127 +%305 = OpConvertUToF %5 %304 +%306 = OpFRem %5 %302 %305 +%307 = OpCompositeExtract %8 %297 0 OpLine %3 100 12 -%311 = OpIAdd %8 %310 %122 -%312 = OpUDiv %8 %299 %311 -%313 = OpConvertUToF %5 %312 -%314 = OpCompositeConstruct %6 %309 %313 -%315 = OpConvertSToF %6 %301 -%316 = OpFAdd %6 %314 %315 -OpReturnValue %316 +%308 = OpIAdd %8 %307 %127 +%309 = OpUDiv %8 %296 %308 +%310 = OpConvertUToF %5 %309 +%311 = OpCompositeConstruct %6 %306 %310 +%312 = OpConvertSToF %6 %298 +%313 = OpFAdd %6 %311 %312 +OpReturnValue %313 OpFunctionEnd -%319 = OpFunction %4 None %320 -%318 = OpFunctionParameter %6 -%317 = OpLabel -OpBranch %325 -%325 = OpLabel +%316 = OpFunction %4 None %317 +%315 = OpFunctionParameter %6 +%314 = OpLabel +OpBranch %324 +%324 = OpLabel OpLine %3 270 9 -%326 = OpFunctionCall %5 %77 %318 +%325 = OpFunctionCall %5 %67 %315 OpLine %3 270 9 -%327 = OpFMul %5 %326 %84 +%326 = OpFMul %5 %325 %81 OpLine %3 270 9 -%328 = OpFAdd %5 %327 %84 +%327 = OpFAdd %5 %326 %81 OpLine %3 271 17 -%329 = OpCompositeConstruct %6 %321 %322 -%330 = OpFAdd %6 %318 %329 +%328 = OpFAdd %6 %315 %320 OpLine %3 271 9 -%331 = OpFunctionCall %5 %77 %330 +%329 = OpFunctionCall %5 %67 %328 OpLine %3 271 9 -%332 = OpFMul %5 %331 %84 +%330 = OpFMul %5 %329 %81 OpLine %3 271 9 -%333 = OpFAdd %5 %332 %84 +%331 = OpFAdd %5 %330 %81 OpLine %3 272 17 -%334 = OpCompositeConstruct %6 %323 %324 -%335 = OpFAdd %6 %318 %334 +%332 = OpFAdd %6 %315 %323 OpLine %3 272 9 -%336 = OpFunctionCall %5 %77 %335 +%333 = OpFunctionCall %5 %67 %332 OpLine %3 272 9 -%337 = OpFMul %5 %336 %84 +%334 = OpFMul %5 %333 %81 OpLine %3 269 12 -%338 = OpFAdd %5 %337 %84 -%339 = OpCompositeConstruct %4 %328 %333 %338 -OpReturnValue %339 +%335 = OpFAdd %5 %334 %81 +%336 = OpCompositeConstruct %4 %327 %331 %335 +OpReturnValue %336 OpFunctionEnd -%344 = OpFunction %2 None %345 -%340 = OpLabel -%343 = OpLoad %19 %341 -%347 = OpAccessChain %346 %29 %131 -OpBranch %352 -%352 = OpLabel +%341 = OpFunction %2 None %342 +%337 = OpLabel +%340 = OpLoad %19 %338 +%344 = OpAccessChain %343 %29 %136 +OpBranch %349 +%349 = OpLabel OpLine %3 111 22 -%353 = OpCompositeExtract %8 %343 0 +%350 = OpCompositeExtract %8 %340 0 OpLine %3 113 36 -%355 = OpAccessChain %354 %347 %131 -%356 = OpLoad %10 %355 +%352 = OpAccessChain %351 %344 %136 +%353 = OpLoad %10 %352 OpLine %3 113 59 -%358 = OpAccessChain %357 %347 %122 -%359 = OpLoad %11 %358 +%355 = OpAccessChain %354 %344 %127 +%356 = OpLoad %11 %355 OpLine %3 113 13 -%360 = OpFunctionCall %6 %302 %353 %356 %359 +%357 = OpFunctionCall %6 %299 %350 %353 %356 OpLine %3 115 5 OpLine %3 115 51 -%364 = OpAccessChain %363 %347 %349 -%365 = OpLoad %6 %364 +%361 = OpAccessChain %360 %344 %346 +%362 = OpLoad %6 %361 OpLine %3 115 33 -%366 = OpFunctionCall %14 %269 %360 %365 +%363 = OpFunctionCall %14 %266 %357 %362 OpLine %3 115 5 -%367 = OpAccessChain %362 %32 %131 %353 -OpStore %367 %366 +%364 = OpAccessChain %359 %32 %136 %350 +OpStore %364 %363 OpLine %3 118 23 -%368 = OpCompositeExtract %8 %343 0 +%365 = OpCompositeExtract %8 %340 0 OpLine %3 118 23 -%369 = OpIMul %8 %368 %348 +%366 = OpIMul %8 %365 %345 OpLine %3 120 25 -%371 = OpAccessChain %370 %347 %131 %131 -%372 = OpLoad %8 %371 +%368 = OpAccessChain %367 %344 %136 %136 +%369 = OpLoad %8 %368 OpLine %3 120 25 -%373 = OpAccessChain %370 %347 %131 %122 -%374 = OpLoad %8 %373 -%375 = OpIMul %8 %372 %374 +%370 = OpAccessChain %367 %344 %136 %127 +%371 = OpLoad %8 %370 +%372 = OpIMul %8 %369 %371 OpLine %3 120 9 -%376 = OpIMul %8 %375 %348 -%377 = OpUGreaterThanEqual %107 %369 %376 +%373 = OpIMul %8 %372 %345 +%374 = OpUGreaterThanEqual %114 %366 %373 OpLine %3 120 5 -OpSelectionMerge %378 None -OpBranchConditional %377 %379 %378 -%379 = OpLabel +OpSelectionMerge %375 None +OpBranchConditional %374 %376 %375 +%376 = OpLabel OpReturn -%378 = OpLabel +%375 = OpLabel OpLine %3 122 28 -%380 = OpCompositeExtract %8 %343 0 +%377 = OpCompositeExtract %8 %340 0 OpLine %3 122 15 -%381 = OpAccessChain %370 %347 %131 %131 -%382 = OpLoad %8 %381 -%383 = OpUDiv %8 %380 %382 -%384 = OpIAdd %8 %353 %383 +%378 = OpAccessChain %367 %344 %136 %136 +%379 = OpLoad %8 %378 +%380 = OpUDiv %8 %377 %379 +%381 = OpIAdd %8 %350 %380 OpLine %3 123 15 -%385 = OpIAdd %8 %384 %122 +%382 = OpIAdd %8 %381 %127 OpLine %3 124 15 -%386 = OpAccessChain %370 %347 %131 %131 -%387 = OpLoad %8 %386 -%388 = OpIAdd %8 %384 %387 +%383 = OpAccessChain %367 %344 %136 %136 +%384 = OpLoad %8 %383 +%385 = OpIAdd %8 %381 %384 OpLine %3 124 15 -%389 = OpIAdd %8 %388 %122 +%386 = OpIAdd %8 %385 %127 OpLine %3 125 15 -%390 = OpIAdd %8 %389 %122 +%387 = OpIAdd %8 %386 %127 OpLine %3 127 5 OpLine %3 127 5 -%393 = OpAccessChain %392 %34 %131 %369 -OpStore %393 %384 +%390 = OpAccessChain %389 %34 %136 %366 +OpStore %390 %381 OpLine %3 128 5 OpLine %3 128 5 -%394 = OpIAdd %8 %369 %122 +%391 = OpIAdd %8 %366 %127 OpLine %3 128 5 -%395 = OpAccessChain %392 %34 %131 %394 -OpStore %395 %389 +%392 = OpAccessChain %389 %34 %136 %391 +OpStore %392 %386 OpLine %3 129 5 OpLine %3 129 5 -%396 = OpIAdd %8 %369 %349 +%393 = OpIAdd %8 %366 %346 OpLine %3 129 5 -%397 = OpAccessChain %392 %34 %131 %396 -OpStore %397 %390 +%394 = OpAccessChain %389 %34 %136 %393 +OpStore %394 %387 OpLine %3 130 5 OpLine %3 130 5 -%398 = OpIAdd %8 %369 %350 +%395 = OpIAdd %8 %366 %347 OpLine %3 130 5 -%399 = OpAccessChain %392 %34 %131 %398 -OpStore %399 %384 +%396 = OpAccessChain %389 %34 %136 %395 +OpStore %396 %381 OpLine %3 131 5 OpLine %3 131 5 -%400 = OpIAdd %8 %369 %351 +%397 = OpIAdd %8 %366 %348 OpLine %3 131 5 -%401 = OpAccessChain %392 %34 %131 %400 -OpStore %401 %390 +%398 = OpAccessChain %389 %34 %136 %397 +OpStore %398 %387 OpLine %3 132 5 OpLine %3 132 5 -%402 = OpIAdd %8 %369 %215 +%399 = OpIAdd %8 %366 %205 OpLine %3 132 5 -%403 = OpAccessChain %392 %34 %131 %402 -OpStore %403 %385 +%400 = OpAccessChain %389 %34 %136 %399 +OpStore %400 %382 OpReturn OpFunctionEnd -%414 = OpFunction %2 None %345 -%404 = OpLabel -%407 = OpLoad %8 %405 -%416 = OpAccessChain %415 %36 %131 -OpBranch %418 -%418 = OpLabel +%411 = OpFunction %2 None %342 +%401 = OpLabel +%404 = OpLoad %8 %402 +%413 = OpAccessChain %412 %36 %136 +OpBranch %416 +%416 = OpLabel OpLine %3 161 19 -%419 = OpIAdd %8 %407 %349 +%417 = OpIAdd %8 %404 %346 OpLine %3 161 18 -%420 = OpUDiv %8 %419 %350 +%418 = OpUDiv %8 %417 %347 OpLine %3 161 13 -%421 = OpUMod %8 %420 %349 -%422 = OpConvertUToF %5 %421 +%419 = OpUMod %8 %418 %346 +%420 = OpConvertUToF %5 %419 OpLine %3 162 19 -%423 = OpIAdd %8 %407 %122 +%421 = OpIAdd %8 %404 %127 OpLine %3 162 18 -%424 = OpUDiv %8 %423 %350 +%422 = OpUDiv %8 %421 %347 OpLine %3 162 13 -%425 = OpUMod %8 %424 %349 -%426 = OpConvertUToF %5 %425 +%423 = OpUMod %8 %422 %346 +%424 = OpConvertUToF %5 %423 OpLine %3 163 14 -%427 = OpCompositeConstruct %6 %422 %426 +%425 = OpCompositeConstruct %6 %420 %424 OpLine %3 165 30 -%428 = OpVectorTimesScalar %6 %427 %85 -%429 = OpCompositeConstruct %6 %417 %417 -%430 = OpFAdd %6 %429 %428 +%426 = OpVectorTimesScalar %6 %425 %84 +%427 = OpFAdd %6 %415 %426 OpLine %3 165 20 -%431 = OpCompositeConstruct %7 %430 %83 %56 +%428 = OpCompositeConstruct %7 %427 %76 %56 OpLine %3 168 21 -%433 = OpAccessChain %432 %416 %350 -%434 = OpLoad %8 %433 -%435 = OpConvertUToF %5 %434 -%436 = OpFMul %5 %422 %435 +%430 = OpAccessChain %429 %413 %347 +%431 = OpLoad %8 %430 +%432 = OpConvertUToF %5 %431 +%433 = OpFMul %5 %420 %432 OpLine %3 168 17 -%437 = OpAccessChain %432 %416 %350 -%438 = OpLoad %8 %437 -%439 = OpConvertUToF %5 %438 -%440 = OpFMul %5 %426 %439 -%441 = OpFAdd %5 %436 %440 -%442 = OpConvertFToU %8 %441 +%434 = OpAccessChain %429 %413 %347 +%435 = OpLoad %8 %434 +%436 = OpConvertUToF %5 %435 +%437 = OpFMul %5 %424 %436 +%438 = OpFAdd %5 %433 %437 +%439 = OpConvertFToU %8 %438 OpLine %3 168 17 -%443 = OpAccessChain %432 %416 %351 -%444 = OpLoad %8 %443 -%445 = OpIAdd %8 %442 %444 +%440 = OpAccessChain %429 %413 %348 +%441 = OpLoad %8 %440 +%442 = OpIAdd %8 %439 %441 OpLine %3 170 12 -%446 = OpCompositeConstruct %21 %445 %431 %427 -%447 = OpCompositeExtract %8 %446 0 -OpStore %408 %447 -%448 = OpCompositeExtract %7 %446 1 -OpStore %410 %448 -%449 = OpCompositeExtract %6 %446 2 -OpStore %412 %449 +%443 = OpCompositeConstruct %21 %442 %428 %425 +%444 = OpCompositeExtract %8 %443 0 +OpStore %405 %444 +%445 = OpCompositeExtract %7 %443 1 +OpStore %407 %445 +%446 = OpCompositeExtract %6 %443 2 +OpStore %409 %446 OpReturn OpFunctionEnd -%464 = OpFunction %2 None %345 -%452 = OpLabel -%450 = OpVariable %206 Function %207 -%451 = OpVariable %210 Function %211 -%455 = OpLoad %8 %454 -%458 = OpLoad %7 %456 -%461 = OpLoad %6 %459 -%453 = OpCompositeConstruct %21 %455 %458 %461 -%465 = OpAccessChain %415 %36 %131 -OpBranch %467 -%467 = OpLabel +%459 = OpFunction %2 None %342 +%447 = OpLabel +%462 = OpVariable %212 Function %76 +%463 = OpVariable %215 Function %136 +%450 = OpLoad %8 %449 +%453 = OpLoad %7 %451 +%456 = OpLoad %6 %454 +%448 = OpCompositeConstruct %21 %450 %453 %456 +%460 = OpAccessChain %412 %36 %136 +OpBranch %464 +%464 = OpLabel OpLine %3 181 17 -%468 = OpCompositeExtract %6 %453 2 -%469 = OpCompositeExtract %5 %468 0 +%465 = OpCompositeExtract %6 %448 2 +%466 = OpCompositeExtract %5 %465 0 OpLine %3 181 17 -%470 = OpAccessChain %432 %465 %350 -%471 = OpLoad %8 %470 -%472 = OpConvertUToF %5 %471 -%473 = OpFMul %5 %469 %472 -%474 = OpCompositeExtract %6 %453 2 -%475 = OpCompositeExtract %5 %474 1 +%467 = OpAccessChain %429 %460 %347 +%468 = OpLoad %8 %467 +%469 = OpConvertUToF %5 %468 +%470 = OpFMul %5 %466 %469 +%471 = OpCompositeExtract %6 %448 2 +%472 = OpCompositeExtract %5 %471 1 OpLine %3 181 70 -%476 = OpAccessChain %432 %465 %350 -%477 = OpLoad %8 %476 +%473 = OpAccessChain %429 %460 %347 +%474 = OpLoad %8 %473 OpLine %3 181 13 -%478 = OpAccessChain %432 %465 %350 -%479 = OpLoad %8 %478 -%480 = OpIMul %8 %477 %479 -%481 = OpConvertUToF %5 %480 -%482 = OpFMul %5 %475 %481 -%483 = OpFAdd %5 %473 %482 -%484 = OpConvertFToU %8 %483 +%475 = OpAccessChain %429 %460 %347 +%476 = OpLoad %8 %475 +%477 = OpIMul %8 %474 %476 +%478 = OpConvertUToF %5 %477 +%479 = OpFMul %5 %472 %478 +%480 = OpFAdd %5 %470 %479 +%481 = OpConvertFToU %8 %480 OpLine %3 181 13 -%485 = OpAccessChain %432 %465 %351 -%486 = OpLoad %8 %485 -%487 = OpIAdd %8 %484 %486 +%482 = OpAccessChain %429 %460 %348 +%483 = OpLoad %8 %482 +%484 = OpIAdd %8 %481 %483 OpLine %3 182 32 -%488 = OpConvertUToF %5 %487 +%485 = OpConvertUToF %5 %484 OpLine %3 182 22 -%489 = OpFDiv %5 %488 %466 -%490 = OpExtInst %5 %1 Floor %489 -%491 = OpConvertFToU %8 %490 +%486 = OpFDiv %5 %485 %461 +%487 = OpExtInst %5 %1 Floor %486 +%488 = OpConvertFToU %8 %487 OpLine %3 183 22 -%492 = OpUMod %8 %487 %348 +%489 = OpUMod %8 %484 %345 OpLine %3 185 36 -%493 = OpAccessChain %354 %465 %131 -%494 = OpLoad %10 %493 +%490 = OpAccessChain %351 %460 %136 +%491 = OpLoad %10 %490 OpLine %3 185 57 -%495 = OpAccessChain %357 %465 %122 -%496 = OpLoad %11 %495 +%492 = OpAccessChain %354 %460 %127 +%493 = OpLoad %11 %492 OpLine %3 185 13 -%497 = OpFunctionCall %6 %302 %491 %494 %496 +%494 = OpFunctionCall %6 %299 %488 %491 %493 OpLine %3 186 31 -%498 = OpAccessChain %363 %465 %349 -%499 = OpLoad %6 %498 +%495 = OpAccessChain %360 %460 %346 +%496 = OpLoad %6 %495 OpLine %3 186 13 -%500 = OpFunctionCall %14 %269 %497 %499 -OpLine %3 188 5 -OpStore %450 %83 +%497 = OpFunctionCall %14 %266 %494 %496 OpLine %3 190 5 -OpSelectionMerge %501 None -OpSwitch %492 %508 0 %502 1 %503 2 %504 3 %505 4 %506 5 %507 -%502 = OpLabel +OpSelectionMerge %498 None +OpSwitch %489 %505 0 %499 1 %500 2 %501 3 %502 4 %503 5 %504 +%499 = OpLabel OpLine %3 191 37 -%509 = OpCompositeExtract %4 %500 0 -%510 = OpCompositeExtract %5 %509 0 +%506 = OpCompositeExtract %4 %497 0 +%507 = OpCompositeExtract %5 %506 0 OpLine %3 191 20 -OpStore %450 %510 -OpBranch %501 -%503 = OpLabel +OpStore %462 %507 +OpBranch %498 +%500 = OpLabel OpLine %3 192 37 -%511 = OpCompositeExtract %4 %500 0 -%512 = OpCompositeExtract %5 %511 1 +%508 = OpCompositeExtract %4 %497 0 +%509 = OpCompositeExtract %5 %508 1 OpLine %3 192 20 -OpStore %450 %512 -OpBranch %501 -%504 = OpLabel -OpLine %3 193 37 -%513 = OpCompositeExtract %4 %500 0 -%514 = OpCompositeExtract %5 %513 2 -OpLine %3 193 20 -OpStore %450 %514 -OpBranch %501 -%505 = OpLabel -OpLine %3 194 37 -%515 = OpCompositeExtract %4 %500 1 -%516 = OpCompositeExtract %5 %515 0 -OpLine %3 194 20 -OpStore %450 %516 -OpBranch %501 -%506 = OpLabel -OpLine %3 195 37 -%517 = OpCompositeExtract %4 %500 1 -%518 = OpCompositeExtract %5 %517 1 -OpLine %3 195 20 -OpStore %450 %518 -OpBranch %501 -%507 = OpLabel -OpLine %3 196 37 -%519 = OpCompositeExtract %4 %500 1 -%520 = OpCompositeExtract %5 %519 2 -OpLine %3 196 20 -OpStore %450 %520 -OpBranch %501 -%508 = OpLabel -OpBranch %501 +OpStore %462 %509 +OpBranch %498 %501 = OpLabel +OpLine %3 193 37 +%510 = OpCompositeExtract %4 %497 0 +%511 = OpCompositeExtract %5 %510 2 +OpLine %3 193 20 +OpStore %462 %511 +OpBranch %498 +%502 = OpLabel +OpLine %3 194 37 +%512 = OpCompositeExtract %4 %497 1 +%513 = OpCompositeExtract %5 %512 0 +OpLine %3 194 20 +OpStore %462 %513 +OpBranch %498 +%503 = OpLabel +OpLine %3 195 37 +%514 = OpCompositeExtract %4 %497 1 +%515 = OpCompositeExtract %5 %514 1 +OpLine %3 195 20 +OpStore %462 %515 +OpBranch %498 +%504 = OpLabel +OpLine %3 196 37 +%516 = OpCompositeExtract %4 %497 1 +%517 = OpCompositeExtract %5 %516 2 +OpLine %3 196 20 +OpStore %462 %517 +OpBranch %498 +%505 = OpLabel +OpBranch %498 +%498 = OpLabel OpLine %3 200 15 -%521 = OpAccessChain %370 %465 %131 %131 -%522 = OpLoad %8 %521 -%523 = OpUDiv %8 %491 %522 -%524 = OpIAdd %8 %491 %523 +%518 = OpAccessChain %367 %460 %136 %136 +%519 = OpLoad %8 %518 +%520 = OpUDiv %8 %488 %519 +%521 = OpIAdd %8 %488 %520 OpLine %3 201 15 -%525 = OpIAdd %8 %524 %122 +%522 = OpIAdd %8 %521 %127 OpLine %3 202 15 -%526 = OpAccessChain %370 %465 %131 %131 -%527 = OpLoad %8 %526 -%528 = OpIAdd %8 %524 %527 +%523 = OpAccessChain %367 %460 %136 %136 +%524 = OpLoad %8 %523 +%525 = OpIAdd %8 %521 %524 OpLine %3 202 15 -%529 = OpIAdd %8 %528 %122 +%526 = OpIAdd %8 %525 %127 OpLine %3 203 15 -%530 = OpIAdd %8 %529 %122 -OpLine %3 205 5 -OpStore %451 %131 +%527 = OpIAdd %8 %526 %127 OpLine %3 206 5 -OpSelectionMerge %531 None -OpSwitch %492 %536 0 %532 3 %532 2 %533 4 %533 1 %534 5 %535 -%532 = OpLabel +OpSelectionMerge %528 None +OpSwitch %489 %533 0 %529 3 %529 2 %530 4 %530 1 %531 5 %532 +%529 = OpLabel OpLine %3 207 24 -OpStore %451 %524 -OpBranch %531 -%533 = OpLabel +OpStore %463 %521 +OpBranch %528 +%530 = OpLabel OpLine %3 208 24 -OpStore %451 %530 -OpBranch %531 -%534 = OpLabel -OpLine %3 209 20 -OpStore %451 %529 -OpBranch %531 -%535 = OpLabel -OpLine %3 210 20 -OpStore %451 %525 -OpBranch %531 -%536 = OpLabel -OpBranch %531 +OpStore %463 %527 +OpBranch %528 %531 = OpLabel +OpLine %3 209 20 +OpStore %463 %526 +OpBranch %528 +%532 = OpLabel +OpLine %3 210 20 +OpStore %463 %522 +OpBranch %528 +%533 = OpLabel +OpBranch %528 +%528 = OpLabel OpLine %3 213 13 -%537 = OpCompositeExtract %8 %453 0 +%534 = OpCompositeExtract %8 %448 0 OpLine %3 213 5 -OpStore %451 %537 +OpStore %463 %534 OpLine %3 222 27 -%538 = OpLoad %5 %450 -%539 = OpBitcast %8 %538 +%535 = OpLoad %5 %462 +%536 = OpBitcast %8 %535 OpLine %3 223 12 -%540 = OpLoad %8 %451 -%541 = OpCompositeConstruct %22 %539 %540 -%542 = OpCompositeExtract %8 %541 0 -OpStore %462 %542 -%543 = OpCompositeExtract %8 %541 1 -OpStore %463 %543 +%537 = OpLoad %8 %463 +%538 = OpCompositeConstruct %22 %536 %537 +%539 = OpCompositeExtract %8 %538 0 +OpStore %457 %539 +%540 = OpCompositeExtract %8 %538 1 +OpStore %458 %540 OpReturn OpFunctionEnd -%555 = OpFunction %2 None %345 -%544 = OpLabel -%548 = OpLoad %4 %546 -%550 = OpLoad %4 %549 -%545 = OpCompositeConstruct %14 %548 %550 -%557 = OpAccessChain %556 %39 %131 -OpBranch %558 -%558 = OpLabel +%552 = OpFunction %2 None %342 +%541 = OpLabel +%545 = OpLoad %4 %543 +%547 = OpLoad %4 %546 +%542 = OpCompositeConstruct %14 %545 %547 +%554 = OpAccessChain %553 %39 %136 +OpBranch %555 +%555 = OpLabel OpLine %3 254 25 -%560 = OpAccessChain %559 %557 %122 -%561 = OpLoad %23 %560 -%562 = OpCompositeExtract %4 %545 0 +%557 = OpAccessChain %556 %554 %127 +%558 = OpLoad %23 %557 +%559 = OpCompositeExtract %4 %542 0 OpLine %3 254 25 -%563 = OpCompositeConstruct %7 %562 %56 -%564 = OpMatrixTimesVector %7 %561 %563 +%560 = OpCompositeConstruct %7 %559 %56 +%561 = OpMatrixTimesVector %7 %558 %560 OpLine %3 255 18 -%565 = OpCompositeExtract %4 %545 1 +%562 = OpCompositeExtract %4 %542 1 OpLine %3 256 12 -%566 = OpCompositeExtract %4 %545 0 -%567 = OpCompositeConstruct %26 %564 %565 %566 -%568 = OpCompositeExtract %7 %567 0 -OpStore %551 %568 -%569 = OpCompositeExtract %4 %567 1 -OpStore %552 %569 -%570 = OpCompositeExtract %4 %567 2 -OpStore %554 %570 +%563 = OpCompositeExtract %4 %542 0 +%564 = OpCompositeConstruct %26 %561 %562 %563 +%565 = OpCompositeExtract %7 %564 0 +OpStore %548 %565 +%566 = OpCompositeExtract %4 %564 1 +OpStore %549 %566 +%567 = OpCompositeExtract %4 %564 2 +OpStore %551 %567 OpReturn OpFunctionEnd -%581 = OpFunction %2 None %345 -%572 = OpLabel -%571 = OpVariable %73 Function %74 -%575 = OpLoad %7 %574 -%577 = OpLoad %4 %576 -%579 = OpLoad %4 %578 -%573 = OpCompositeConstruct %26 %575 %577 %579 -%582 = OpAccessChain %556 %39 %131 -%584 = OpAccessChain %583 %42 %131 -OpBranch %587 -%587 = OpLabel +%577 = OpFunction %2 None %342 +%568 = OpLabel +%586 = OpVariable %99 Function %587 +%571 = OpLoad %7 %570 +%573 = OpLoad %4 %572 +%575 = OpLoad %4 %574 +%569 = OpCompositeConstruct %26 %571 %573 %575 +%578 = OpAccessChain %553 %39 %136 +%580 = OpAccessChain %579 %42 %136 +OpBranch %588 +%588 = OpLabel OpLine %3 278 28 -%588 = OpCompositeConstruct %4 %83 %83 %83 OpLine %3 278 17 -%589 = OpCompositeConstruct %4 %271 %271 %271 -%590 = OpCompositeExtract %4 %573 2 -%591 = OpExtInst %4 %1 Fract %590 -%592 = OpExtInst %4 %1 SmoothStep %588 %589 %591 +%589 = OpCompositeExtract %4 %569 2 +%590 = OpExtInst %4 %1 Fract %589 +%591 = OpExtInst %4 %1 SmoothStep %83 %581 %590 OpLine %3 278 5 -OpStore %571 %592 +OpStore %586 %591 OpLine %3 279 17 -%593 = OpCompositeConstruct %4 %84 %271 %585 OpLine %3 279 13 -%594 = OpCompositeConstruct %4 %586 %586 %586 -%595 = OpAccessChain %121 %571 %131 -%596 = OpLoad %5 %595 -%597 = OpAccessChain %121 %571 %122 +%592 = OpAccessChain %126 %586 %136 +%593 = OpLoad %5 %592 +%594 = OpAccessChain %126 %586 %127 +%595 = OpLoad %5 %594 +%596 = OpFMul %5 %593 %595 +%597 = OpAccessChain %126 %586 %346 %598 = OpLoad %5 %597 %599 = OpFMul %5 %596 %598 -%600 = OpAccessChain %121 %571 %349 -%601 = OpLoad %5 %600 -%602 = OpFMul %5 %599 %601 -%603 = OpCompositeConstruct %4 %602 %602 %602 -%604 = OpExtInst %4 %1 FMix %593 %594 %603 +%600 = OpCompositeConstruct %4 %599 %599 %599 +%601 = OpExtInst %4 %1 FMix %583 %585 %600 OpLine %3 279 5 -OpStore %571 %604 +OpStore %586 %601 OpLine %3 282 25 -%606 = OpAccessChain %605 %584 %122 -%607 = OpLoad %4 %606 -%608 = OpVectorTimesScalar %4 %607 %271 +%603 = OpAccessChain %602 %580 %127 +%604 = OpLoad %4 %603 +%605 = OpVectorTimesScalar %4 %604 %268 OpLine %3 284 21 -%609 = OpAccessChain %605 %584 %131 -%610 = OpLoad %4 %609 -%611 = OpCompositeExtract %4 %573 2 -%612 = OpFSub %4 %610 %611 -%613 = OpExtInst %4 %1 Normalize %612 +%606 = OpAccessChain %602 %580 %136 +%607 = OpLoad %4 %606 +%608 = OpCompositeExtract %4 %569 2 +%609 = OpFSub %4 %607 %608 +%610 = OpExtInst %4 %1 Normalize %609 OpLine %3 285 20 -%615 = OpAccessChain %614 %582 %131 -%616 = OpLoad %7 %615 -%617 = OpVectorShuffle %4 %616 %616 0 1 2 -%618 = OpCompositeExtract %4 %573 2 -%619 = OpFSub %4 %617 %618 -%620 = OpExtInst %4 %1 Normalize %619 +%612 = OpAccessChain %611 %578 %136 +%613 = OpLoad %7 %612 +%614 = OpVectorShuffle %4 %613 %613 0 1 2 +%615 = OpCompositeExtract %4 %569 2 +%616 = OpFSub %4 %614 %615 +%617 = OpExtInst %4 %1 Normalize %616 OpLine %3 286 20 -%621 = OpFAdd %4 %620 %613 -%622 = OpExtInst %4 %1 Normalize %621 +%618 = OpFAdd %4 %617 %610 +%619 = OpExtInst %4 %1 Normalize %618 OpLine %3 288 32 -%623 = OpCompositeExtract %4 %573 1 -%624 = OpDot %5 %623 %613 +%620 = OpCompositeExtract %4 %569 1 +%621 = OpDot %5 %620 %610 OpLine %3 288 28 -%625 = OpExtInst %5 %1 FMax %624 %83 +%622 = OpExtInst %5 %1 FMax %621 %76 OpLine %3 289 25 -%626 = OpAccessChain %605 %584 %122 -%627 = OpLoad %4 %626 -%628 = OpVectorTimesScalar %4 %627 %625 +%623 = OpAccessChain %602 %580 %127 +%624 = OpLoad %4 %623 +%625 = OpVectorTimesScalar %4 %624 %622 OpLine %3 291 37 -%629 = OpCompositeExtract %4 %573 1 -%630 = OpDot %5 %629 %622 +%626 = OpCompositeExtract %4 %569 1 +%627 = OpDot %5 %626 %619 OpLine %3 291 33 -%631 = OpExtInst %5 %1 FMax %630 %83 +%628 = OpExtInst %5 %1 FMax %627 %76 OpLine %3 291 29 -%632 = OpExtInst %5 %1 Pow %631 %322 +%629 = OpExtInst %5 %1 Pow %628 %319 OpLine %3 292 26 -%633 = OpAccessChain %605 %584 %122 -%634 = OpLoad %4 %633 -%635 = OpVectorTimesScalar %4 %634 %632 +%630 = OpAccessChain %602 %580 %127 +%631 = OpLoad %4 %630 +%632 = OpVectorTimesScalar %4 %631 %629 OpLine %3 294 18 -%636 = OpFAdd %4 %608 %628 -%637 = OpFAdd %4 %636 %635 -%638 = OpLoad %4 %571 -%639 = OpFMul %4 %637 %638 +%633 = OpFAdd %4 %605 %625 +%634 = OpFAdd %4 %633 %632 +%635 = OpLoad %4 %586 +%636 = OpFMul %4 %634 %635 OpLine %3 296 12 -%640 = OpCompositeConstruct %7 %639 %56 -OpStore %580 %640 +%637 = OpCompositeConstruct %7 %636 %56 +OpStore %576 %637 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/dualsource.spvasm b/tests/out/spv/dualsource.spvasm index 0fba6bb26..a5c692b4c 100644 --- a/tests/out/spv/dualsource.spvasm +++ b/tests/out/spv/dualsource.spvasm @@ -1,55 +1,52 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 35 +; Bound: 34 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %17 "main" %11 %14 %16 -OpExecutionMode %17 OriginUpperLeft +OpEntryPoint Fragment %13 "main" %7 %10 %12 +OpExecutionMode %13 OriginUpperLeft OpMemberDecorate %5 0 Offset 0 OpMemberDecorate %5 1 Offset 16 -OpDecorate %11 BuiltIn FragCoord -OpDecorate %14 Location 0 -OpDecorate %16 Location 0 -OpDecorate %16 Index 1 +OpDecorate %7 BuiltIn FragCoord +OpDecorate %10 Location 0 +OpDecorate %12 Location 0 +OpDecorate %12 Index 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 %5 = OpTypeStruct %3 %3 -%7 = OpTypePointer Function %3 -%8 = OpConstantNull %3 -%12 = OpTypePointer Input %3 -%11 = OpVariable %12 Input -%15 = OpTypePointer Output %3 -%14 = OpVariable %15 Output -%16 = OpVariable %15 Output -%18 = OpTypeFunction %2 -%19 = OpConstant %4 0.4 -%20 = OpConstant %4 0.3 -%21 = OpConstant %4 0.2 -%22 = OpConstant %4 0.1 -%23 = OpConstant %4 0.9 -%24 = OpConstant %4 0.8 -%25 = OpConstant %4 0.7 -%26 = OpConstant %4 0.6 -%17 = OpFunction %2 None %18 -%10 = OpLabel -%6 = OpVariable %7 Function %8 -%9 = OpVariable %7 Function %8 -%13 = OpLoad %3 %11 -OpBranch %27 -%27 = OpLabel -%28 = OpCompositeConstruct %3 %19 %20 %21 %22 -OpStore %6 %28 -%29 = OpCompositeConstruct %3 %23 %24 %25 %26 -OpStore %9 %29 -%30 = OpLoad %3 %6 -%31 = OpLoad %3 %9 -%32 = OpCompositeConstruct %5 %30 %31 -%33 = OpCompositeExtract %3 %32 0 -OpStore %14 %33 -%34 = OpCompositeExtract %3 %32 1 -OpStore %16 %34 +%8 = OpTypePointer Input %3 +%7 = OpVariable %8 Input +%11 = OpTypePointer Output %3 +%10 = OpVariable %11 Output +%12 = OpVariable %11 Output +%14 = OpTypeFunction %2 +%15 = OpConstant %4 0.4 +%16 = OpConstant %4 0.3 +%17 = OpConstant %4 0.2 +%18 = OpConstant %4 0.1 +%19 = OpConstantComposite %3 %15 %16 %17 %18 +%20 = OpConstant %4 0.9 +%21 = OpConstant %4 0.8 +%22 = OpConstant %4 0.7 +%23 = OpConstant %4 0.6 +%24 = OpConstantComposite %3 %20 %21 %22 %23 +%26 = OpTypePointer Function %3 +%13 = OpFunction %2 None %14 +%6 = OpLabel +%25 = OpVariable %26 Function %19 +%27 = OpVariable %26 Function %24 +%9 = OpLoad %3 %7 +OpBranch %28 +%28 = OpLabel +%29 = OpLoad %3 %25 +%30 = OpLoad %3 %27 +%31 = OpCompositeConstruct %5 %29 %30 +%32 = OpCompositeExtract %3 %31 0 +OpStore %10 %32 +%33 = OpCompositeExtract %3 %31 1 +OpStore %12 %33 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/extra.spvasm b/tests/out/spv/extra.spvasm index 93de9e8d9..9c434a8ce 100644 --- a/tests/out/spv/extra.spvasm +++ b/tests/out/spv/extra.spvasm @@ -40,37 +40,37 @@ OpDecorate %21 Location 0 %25 = OpTypePointer PushConstant %6 %26 = OpConstant %3 0 %28 = OpConstant %8 1.0 -%31 = OpTypePointer PushConstant %3 -%34 = OpTypeBool -%40 = OpTypeVector %8 3 +%29 = OpTypeVector %8 3 +%30 = OpConstantComposite %29 %28 %28 %28 +%33 = OpTypePointer PushConstant %3 +%36 = OpTypeBool %23 = OpFunction %2 None %24 %13 = OpLabel %17 = OpLoad %7 %15 %20 = OpLoad %3 %18 %14 = OpCompositeConstruct %9 %17 %20 %27 = OpAccessChain %25 %10 %26 -OpBranch %29 -%29 = OpLabel -%30 = OpCompositeExtract %3 %14 1 -%32 = OpAccessChain %31 %27 %26 -%33 = OpLoad %3 %32 -%35 = OpIEqual %34 %30 %33 -OpSelectionMerge %36 None -OpBranchConditional %35 %37 %38 -%37 = OpLabel -%39 = OpCompositeExtract %7 %14 0 -OpStore %21 %39 +OpBranch %31 +%31 = OpLabel +%32 = OpCompositeExtract %3 %14 1 +%34 = OpAccessChain %33 %27 %26 +%35 = OpLoad %3 %34 +%37 = OpIEqual %36 %32 %35 +OpSelectionMerge %38 None +OpBranchConditional %37 %39 %40 +%39 = OpLabel +%41 = OpCompositeExtract %7 %14 0 +OpStore %21 %41 OpReturn -%38 = OpLabel -%41 = OpCompositeConstruct %40 %28 %28 %28 +%40 = OpLabel %42 = OpCompositeExtract %7 %14 0 -%43 = OpVectorShuffle %40 %42 %42 0 1 2 -%44 = OpFSub %40 %41 %43 +%43 = OpVectorShuffle %29 %42 %42 0 1 2 +%44 = OpFSub %29 %30 %43 %45 = OpCompositeExtract %7 %14 0 %46 = OpCompositeExtract %8 %45 3 %47 = OpCompositeConstruct %7 %44 %46 OpStore %21 %47 OpReturn -%36 = OpLabel +%38 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/fragment-output.spvasm b/tests/out/spv/fragment-output.spvasm index 0a6541799..c61ffb825 100644 --- a/tests/out/spv/fragment-output.spvasm +++ b/tests/out/spv/fragment-output.spvasm @@ -5,10 +5,10 @@ OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %33 "main_vec4vec3" %21 %23 %25 %27 %29 %31 -OpEntryPoint Fragment %85 "main_vec2scalar" %73 %75 %77 %79 %81 %83 -OpExecutionMode %33 OriginUpperLeft -OpExecutionMode %85 OriginUpperLeft +OpEntryPoint Fragment %30 "main_vec4vec3" %18 %20 %22 %24 %26 %28 +OpEntryPoint Fragment %82 "main_vec2scalar" %70 %72 %74 %76 %78 %80 +OpExecutionMode %30 OriginUpperLeft +OpExecutionMode %82 OriginUpperLeft OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %12 1 Offset 16 OpMemberDecorate %12 2 Offset 32 @@ -21,18 +21,18 @@ OpMemberDecorate %16 2 Offset 16 OpMemberDecorate %16 3 Offset 24 OpMemberDecorate %16 4 Offset 28 OpMemberDecorate %16 5 Offset 32 -OpDecorate %21 Location 0 -OpDecorate %23 Location 1 -OpDecorate %25 Location 2 -OpDecorate %27 Location 3 -OpDecorate %29 Location 4 -OpDecorate %31 Location 5 -OpDecorate %73 Location 0 -OpDecorate %75 Location 1 -OpDecorate %77 Location 2 -OpDecorate %79 Location 3 -OpDecorate %81 Location 4 -OpDecorate %83 Location 5 +OpDecorate %18 Location 0 +OpDecorate %20 Location 1 +OpDecorate %22 Location 2 +OpDecorate %24 Location 3 +OpDecorate %26 Location 4 +OpDecorate %28 Location 5 +OpDecorate %70 Location 0 +OpDecorate %72 Location 1 +OpDecorate %74 Location 2 +OpDecorate %76 Location 3 +OpDecorate %78 Location 4 +OpDecorate %80 Location 5 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -48,125 +48,125 @@ OpDecorate %83 Location 5 %14 = OpTypeVector %6 2 %15 = OpTypeVector %8 2 %16 = OpTypeStruct %13 %14 %15 %4 %6 %8 -%18 = OpTypePointer Function %12 -%19 = OpConstantNull %12 -%22 = OpTypePointer Output %3 -%21 = OpVariable %22 Output -%24 = OpTypePointer Output %5 -%23 = OpVariable %24 Output -%26 = OpTypePointer Output %7 -%25 = OpVariable %26 Output -%28 = OpTypePointer Output %9 -%27 = OpVariable %28 Output -%30 = OpTypePointer Output %10 -%29 = OpVariable %30 Output -%32 = OpTypePointer Output %11 -%31 = OpVariable %32 Output -%34 = OpTypeFunction %2 -%35 = OpConstant %4 0.0 -%36 = OpConstant %6 0 -%37 = OpConstant %8 0 -%39 = OpTypePointer Function %3 -%42 = OpTypePointer Function %5 -%44 = OpConstant %8 1 -%46 = OpTypePointer Function %7 -%48 = OpConstant %8 2 -%50 = OpTypePointer Function %9 -%52 = OpConstant %8 3 -%54 = OpTypePointer Function %10 -%56 = OpConstant %8 4 -%58 = OpTypePointer Function %11 +%19 = OpTypePointer Output %3 +%18 = OpVariable %19 Output +%21 = OpTypePointer Output %5 +%20 = OpVariable %21 Output +%23 = OpTypePointer Output %7 +%22 = OpVariable %23 Output +%25 = OpTypePointer Output %9 +%24 = OpVariable %25 Output +%27 = OpTypePointer Output %10 +%26 = OpVariable %27 Output +%29 = OpTypePointer Output %11 +%28 = OpVariable %29 Output +%31 = OpTypeFunction %2 +%32 = OpConstant %4 0.0 +%33 = OpConstantComposite %3 %32 %32 %32 %32 +%34 = OpConstant %6 0 +%35 = OpConstantComposite %5 %34 %34 %34 %34 +%36 = OpConstant %8 0 +%37 = OpConstantComposite %7 %36 %36 %36 %36 +%38 = OpConstantComposite %9 %32 %32 %32 +%39 = OpConstantComposite %10 %34 %34 %34 +%40 = OpConstantComposite %11 %36 %36 %36 +%42 = OpTypePointer Function %12 +%43 = OpConstantNull %12 +%45 = OpTypePointer Function %3 +%47 = OpTypePointer Function %5 +%48 = OpConstant %8 1 +%50 = OpTypePointer Function %7 +%51 = OpConstant %8 2 +%53 = OpTypePointer Function %9 +%54 = OpConstant %8 3 +%56 = OpTypePointer Function %10 +%57 = OpConstant %8 4 +%59 = OpTypePointer Function %11 %60 = OpConstant %8 5 -%70 = OpTypePointer Function %16 -%71 = OpConstantNull %16 -%74 = OpTypePointer Output %13 -%73 = OpVariable %74 Output -%76 = OpTypePointer Output %14 -%75 = OpVariable %76 Output -%78 = OpTypePointer Output %15 -%77 = OpVariable %78 Output -%80 = OpTypePointer Output %4 -%79 = OpVariable %80 Output -%82 = OpTypePointer Output %6 -%81 = OpVariable %82 Output -%84 = OpTypePointer Output %8 -%83 = OpVariable %84 Output -%87 = OpTypePointer Function %13 -%90 = OpTypePointer Function %14 -%93 = OpTypePointer Function %15 +%71 = OpTypePointer Output %13 +%70 = OpVariable %71 Output +%73 = OpTypePointer Output %14 +%72 = OpVariable %73 Output +%75 = OpTypePointer Output %15 +%74 = OpVariable %75 Output +%77 = OpTypePointer Output %4 +%76 = OpVariable %77 Output +%79 = OpTypePointer Output %6 +%78 = OpVariable %79 Output +%81 = OpTypePointer Output %8 +%80 = OpVariable %81 Output +%83 = OpConstantComposite %13 %32 %32 +%84 = OpConstantComposite %14 %34 %34 +%85 = OpConstantComposite %15 %36 %36 +%87 = OpTypePointer Function %16 +%88 = OpConstantNull %16 +%90 = OpTypePointer Function %13 +%92 = OpTypePointer Function %14 +%94 = OpTypePointer Function %15 %96 = OpTypePointer Function %4 %98 = OpTypePointer Function %6 %100 = OpTypePointer Function %8 -%33 = OpFunction %2 None %34 -%20 = OpLabel -%17 = OpVariable %18 Function %19 -OpBranch %38 -%38 = OpLabel -%40 = OpCompositeConstruct %3 %35 %35 %35 %35 -%41 = OpAccessChain %39 %17 %37 -OpStore %41 %40 -%43 = OpCompositeConstruct %5 %36 %36 %36 %36 -%45 = OpAccessChain %42 %17 %44 -OpStore %45 %43 -%47 = OpCompositeConstruct %7 %37 %37 %37 %37 -%49 = OpAccessChain %46 %17 %48 -OpStore %49 %47 -%51 = OpCompositeConstruct %9 %35 %35 %35 -%53 = OpAccessChain %50 %17 %52 -OpStore %53 %51 -%55 = OpCompositeConstruct %10 %36 %36 %36 -%57 = OpAccessChain %54 %17 %56 -OpStore %57 %55 -%59 = OpCompositeConstruct %11 %37 %37 %37 -%61 = OpAccessChain %58 %17 %60 -OpStore %61 %59 -%62 = OpLoad %12 %17 +%30 = OpFunction %2 None %31 +%17 = OpLabel +%41 = OpVariable %42 Function %43 +OpBranch %44 +%44 = OpLabel +%46 = OpAccessChain %45 %41 %36 +OpStore %46 %33 +%49 = OpAccessChain %47 %41 %48 +OpStore %49 %35 +%52 = OpAccessChain %50 %41 %51 +OpStore %52 %37 +%55 = OpAccessChain %53 %41 %54 +OpStore %55 %38 +%58 = OpAccessChain %56 %41 %57 +OpStore %58 %39 +%61 = OpAccessChain %59 %41 %60 +OpStore %61 %40 +%62 = OpLoad %12 %41 %63 = OpCompositeExtract %3 %62 0 -OpStore %21 %63 +OpStore %18 %63 %64 = OpCompositeExtract %5 %62 1 -OpStore %23 %64 +OpStore %20 %64 %65 = OpCompositeExtract %7 %62 2 -OpStore %25 %65 +OpStore %22 %65 %66 = OpCompositeExtract %9 %62 3 -OpStore %27 %66 +OpStore %24 %66 %67 = OpCompositeExtract %10 %62 4 -OpStore %29 %67 +OpStore %26 %67 %68 = OpCompositeExtract %11 %62 5 -OpStore %31 %68 +OpStore %28 %68 OpReturn OpFunctionEnd -%85 = OpFunction %2 None %34 -%72 = OpLabel -%69 = OpVariable %70 Function %71 -OpBranch %86 -%86 = OpLabel -%88 = OpCompositeConstruct %13 %35 %35 -%89 = OpAccessChain %87 %69 %37 -OpStore %89 %88 -%91 = OpCompositeConstruct %14 %36 %36 -%92 = OpAccessChain %90 %69 %44 -OpStore %92 %91 -%94 = OpCompositeConstruct %15 %37 %37 -%95 = OpAccessChain %93 %69 %48 -OpStore %95 %94 -%97 = OpAccessChain %96 %69 %52 -OpStore %97 %35 -%99 = OpAccessChain %98 %69 %56 -OpStore %99 %36 -%101 = OpAccessChain %100 %69 %60 -OpStore %101 %37 -%102 = OpLoad %16 %69 +%82 = OpFunction %2 None %31 +%69 = OpLabel +%86 = OpVariable %87 Function %88 +OpBranch %89 +%89 = OpLabel +%91 = OpAccessChain %90 %86 %36 +OpStore %91 %83 +%93 = OpAccessChain %92 %86 %48 +OpStore %93 %84 +%95 = OpAccessChain %94 %86 %51 +OpStore %95 %85 +%97 = OpAccessChain %96 %86 %54 +OpStore %97 %32 +%99 = OpAccessChain %98 %86 %57 +OpStore %99 %34 +%101 = OpAccessChain %100 %86 %60 +OpStore %101 %36 +%102 = OpLoad %16 %86 %103 = OpCompositeExtract %13 %102 0 -OpStore %73 %103 +OpStore %70 %103 %104 = OpCompositeExtract %14 %102 1 -OpStore %75 %104 +OpStore %72 %104 %105 = OpCompositeExtract %15 %102 2 -OpStore %77 %105 +OpStore %74 %105 %106 = OpCompositeExtract %4 %102 3 -OpStore %79 %106 +OpStore %76 %106 %107 = OpCompositeExtract %6 %102 4 -OpStore %81 %107 +OpStore %78 %107 %108 = OpCompositeExtract %8 %102 5 -OpStore %83 %108 +OpStore %80 %108 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/functions.spvasm b/tests/out/spv/functions.spvasm index a7338a932..463f7da0b 100644 --- a/tests/out/spv/functions.spvasm +++ b/tests/out/spv/functions.spvasm @@ -1,94 +1,91 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 78 +; Bound: 75 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %73 "main" -OpExecutionMode %73 LocalSize 1 1 1 +OpEntryPoint GLCompute %70 "main" +OpExecutionMode %70 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 2 %5 = OpTypeInt 32 1 %8 = OpTypeFunction %3 %9 = OpConstant %4 2.0 -%10 = OpConstant %4 0.5 -%18 = OpTypeFunction %5 -%19 = OpConstant %5 1 -%20 = OpTypeInt 32 0 -%21 = OpConstant %20 1 -%22 = OpConstant %5 4 -%23 = OpConstant %5 2 -%25 = OpTypeVector %5 2 -%29 = OpConstantNull %5 -%37 = OpTypeVector %20 3 -%41 = OpConstantNull %20 -%53 = OpTypeVector %5 4 -%74 = OpTypeFunction %2 +%10 = OpConstantComposite %3 %9 %9 +%11 = OpConstant %4 0.5 +%12 = OpConstantComposite %3 %11 %11 +%17 = OpTypeFunction %5 +%18 = OpConstant %5 1 +%19 = OpTypeVector %5 2 +%20 = OpConstantComposite %19 %18 %18 +%21 = OpTypeInt 32 0 +%22 = OpConstant %21 1 +%23 = OpTypeVector %21 3 +%24 = OpConstantComposite %23 %22 %22 %22 +%25 = OpConstant %5 4 +%26 = OpTypeVector %5 4 +%27 = OpConstantComposite %26 %25 %25 %25 %25 +%28 = OpConstant %5 2 +%29 = OpConstantComposite %26 %28 %28 %28 %28 +%32 = OpConstantNull %5 +%41 = OpConstantNull %21 +%71 = OpTypeFunction %2 %7 = OpFunction %3 None %8 %6 = OpLabel -OpBranch %11 -%11 = OpLabel -%12 = OpCompositeConstruct %3 %9 %9 -%13 = OpCompositeConstruct %3 %10 %10 -%14 = OpCompositeConstruct %3 %10 %10 -%15 = OpExtInst %3 %1 Fma %12 %13 %14 -OpReturnValue %15 +OpBranch %13 +%13 = OpLabel +%14 = OpExtInst %3 %1 Fma %10 %12 %12 +OpReturnValue %14 OpFunctionEnd -%17 = OpFunction %5 None %18 -%16 = OpLabel -OpBranch %24 -%24 = OpLabel -%26 = OpCompositeConstruct %25 %19 %19 -%27 = OpCompositeConstruct %25 %19 %19 -%30 = OpCompositeExtract %5 %26 0 -%31 = OpCompositeExtract %5 %27 0 -%32 = OpIMul %5 %30 %31 -%33 = OpIAdd %5 %29 %32 -%34 = OpCompositeExtract %5 %26 1 -%35 = OpCompositeExtract %5 %27 1 -%36 = OpIMul %5 %34 %35 -%28 = OpIAdd %5 %33 %36 -%38 = OpCompositeConstruct %37 %21 %21 %21 -%39 = OpCompositeConstruct %37 %21 %21 %21 -%42 = OpCompositeExtract %20 %38 0 -%43 = OpCompositeExtract %20 %39 0 -%44 = OpIMul %20 %42 %43 -%45 = OpIAdd %20 %41 %44 -%46 = OpCompositeExtract %20 %38 1 -%47 = OpCompositeExtract %20 %39 1 -%48 = OpIMul %20 %46 %47 -%49 = OpIAdd %20 %45 %48 -%50 = OpCompositeExtract %20 %38 2 -%51 = OpCompositeExtract %20 %39 2 -%52 = OpIMul %20 %50 %51 -%40 = OpIAdd %20 %49 %52 -%54 = OpCompositeConstruct %53 %22 %22 %22 %22 -%55 = OpCompositeConstruct %53 %23 %23 %23 %23 -%57 = OpCompositeExtract %5 %54 0 -%58 = OpCompositeExtract %5 %55 0 -%59 = OpIMul %5 %57 %58 -%60 = OpIAdd %5 %29 %59 -%61 = OpCompositeExtract %5 %54 1 -%62 = OpCompositeExtract %5 %55 1 -%63 = OpIMul %5 %61 %62 -%64 = OpIAdd %5 %60 %63 -%65 = OpCompositeExtract %5 %54 2 -%66 = OpCompositeExtract %5 %55 2 -%67 = OpIMul %5 %65 %66 -%68 = OpIAdd %5 %64 %67 -%69 = OpCompositeExtract %5 %54 3 -%70 = OpCompositeExtract %5 %55 3 -%71 = OpIMul %5 %69 %70 -%56 = OpIAdd %5 %68 %71 -OpReturnValue %56 +%16 = OpFunction %5 None %17 +%15 = OpLabel +OpBranch %30 +%30 = OpLabel +%33 = OpCompositeExtract %5 %20 0 +%34 = OpCompositeExtract %5 %20 0 +%35 = OpIMul %5 %33 %34 +%36 = OpIAdd %5 %32 %35 +%37 = OpCompositeExtract %5 %20 1 +%38 = OpCompositeExtract %5 %20 1 +%39 = OpIMul %5 %37 %38 +%31 = OpIAdd %5 %36 %39 +%42 = OpCompositeExtract %21 %24 0 +%43 = OpCompositeExtract %21 %24 0 +%44 = OpIMul %21 %42 %43 +%45 = OpIAdd %21 %41 %44 +%46 = OpCompositeExtract %21 %24 1 +%47 = OpCompositeExtract %21 %24 1 +%48 = OpIMul %21 %46 %47 +%49 = OpIAdd %21 %45 %48 +%50 = OpCompositeExtract %21 %24 2 +%51 = OpCompositeExtract %21 %24 2 +%52 = OpIMul %21 %50 %51 +%40 = OpIAdd %21 %49 %52 +%54 = OpCompositeExtract %5 %27 0 +%55 = OpCompositeExtract %5 %29 0 +%56 = OpIMul %5 %54 %55 +%57 = OpIAdd %5 %32 %56 +%58 = OpCompositeExtract %5 %27 1 +%59 = OpCompositeExtract %5 %29 1 +%60 = OpIMul %5 %58 %59 +%61 = OpIAdd %5 %57 %60 +%62 = OpCompositeExtract %5 %27 2 +%63 = OpCompositeExtract %5 %29 2 +%64 = OpIMul %5 %62 %63 +%65 = OpIAdd %5 %61 %64 +%66 = OpCompositeExtract %5 %27 3 +%67 = OpCompositeExtract %5 %29 3 +%68 = OpIMul %5 %66 %67 +%53 = OpIAdd %5 %65 %68 +OpReturnValue %53 OpFunctionEnd -%73 = OpFunction %2 None %74 +%70 = OpFunction %2 None %71 +%69 = OpLabel +OpBranch %72 %72 = OpLabel -OpBranch %75 -%75 = OpLabel -%76 = OpFunctionCall %3 %7 -%77 = OpFunctionCall %5 %17 +%73 = OpFunctionCall %3 %7 +%74 = OpFunctionCall %5 %16 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/globals.spvasm b/tests/out/spv/globals.spvasm index 9050f944b..4aa6a10ad 100644 --- a/tests/out/spv/globals.spvasm +++ b/tests/out/spv/globals.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 177 +; Bound: 174 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %100 "main" %119 -OpExecutionMode %100 LocalSize 1 1 1 +OpEntryPoint GLCompute %93 "main" %116 +OpExecutionMode %93 LocalSize 1 1 1 OpDecorate %5 ArrayStride 4 OpMemberDecorate %9 0 Offset 0 OpMemberDecorate %9 1 Offset 12 @@ -48,7 +48,7 @@ OpDecorate %48 DescriptorSet 0 OpDecorate %48 Binding 7 OpDecorate %49 Block OpMemberDecorate %49 0 Offset 0 -OpDecorate %119 BuiltIn LocalInvocationId +OpDecorate %116 BuiltIn LocalInvocationId %2 = OpTypeVoid %3 = OpTypeBool %4 = OpTypeFloat 32 @@ -99,55 +99,53 @@ OpDecorate %119 BuiltIn LocalInvocationId %50 = OpTypePointer Uniform %49 %48 = OpVariable %50 Uniform %54 = OpTypeFunction %2 %8 -%57 = OpTypePointer Function %23 -%58 = OpConstantNull %23 -%61 = OpTypeFunction %2 -%62 = OpTypePointer StorageBuffer %9 -%63 = OpConstant %7 0 -%65 = OpConstant %4 1.0 -%66 = OpConstant %23 1 -%67 = OpConstant %4 2.0 -%68 = OpConstant %4 3.0 -%69 = OpConstantNull %24 +%58 = OpTypeFunction %2 +%59 = OpTypePointer StorageBuffer %9 +%60 = OpConstant %7 0 +%62 = OpConstant %4 1.0 +%63 = OpConstantComposite %8 %62 %62 %62 +%64 = OpConstant %23 1 +%65 = OpConstant %4 2.0 +%66 = OpConstant %4 3.0 +%67 = OpConstantNull %24 +%69 = OpTypePointer Function %23 %71 = OpTypePointer StorageBuffer %8 -%74 = OpTypePointer StorageBuffer %4 -%94 = OpTypePointer Function %4 -%95 = OpConstantNull %4 -%97 = OpTypePointer Function %3 -%98 = OpConstantNull %3 -%102 = OpTypePointer StorageBuffer %11 -%104 = OpTypePointer Uniform %13 -%106 = OpTypePointer Uniform %8 -%108 = OpTypePointer Uniform %15 -%110 = OpTypePointer Uniform %19 -%112 = OpTypePointer Uniform %22 -%114 = OpConstant %4 4.0 -%116 = OpConstantNull %5 -%117 = OpConstantNull %7 -%118 = OpTypeVector %7 3 -%120 = OpTypePointer Input %118 -%119 = OpVariable %120 Input -%122 = OpConstantNull %118 -%123 = OpTypeVector %3 3 -%128 = OpConstant %7 264 -%131 = OpTypePointer Workgroup %4 -%132 = OpTypePointer Uniform %21 -%133 = OpTypePointer Uniform %20 -%136 = OpTypePointer Uniform %17 -%137 = OpTypePointer Uniform %16 -%138 = OpTypePointer Uniform %12 -%143 = OpConstant %7 7 -%149 = OpConstant %7 6 -%151 = OpTypePointer StorageBuffer %10 -%152 = OpConstant %7 1 -%155 = OpConstant %7 5 -%157 = OpTypePointer Uniform %12 -%158 = OpTypePointer Uniform %4 -%159 = OpConstant %7 3 -%162 = OpConstant %7 4 -%164 = OpTypePointer StorageBuffer %4 -%175 = OpConstant %23 2 -%176 = OpConstant %7 256 +%73 = OpTypePointer StorageBuffer %4 +%95 = OpTypePointer StorageBuffer %11 +%97 = OpTypePointer Uniform %13 +%99 = OpTypePointer Uniform %8 +%101 = OpTypePointer Uniform %15 +%103 = OpTypePointer Uniform %19 +%105 = OpTypePointer Uniform %22 +%107 = OpConstant %4 4.0 +%109 = OpTypePointer Function %4 +%111 = OpTypePointer Function %3 +%113 = OpConstantNull %5 +%114 = OpConstantNull %7 +%115 = OpTypeVector %7 3 +%117 = OpTypePointer Input %115 +%116 = OpVariable %117 Input +%119 = OpConstantNull %115 +%120 = OpTypeVector %3 3 +%125 = OpConstant %7 264 +%128 = OpTypePointer Workgroup %4 +%129 = OpTypePointer Uniform %21 +%130 = OpTypePointer Uniform %20 +%133 = OpTypePointer Uniform %17 +%134 = OpTypePointer Uniform %16 +%135 = OpTypePointer Uniform %12 +%140 = OpConstant %7 7 +%146 = OpConstant %7 6 +%148 = OpTypePointer StorageBuffer %10 +%149 = OpConstant %7 1 +%152 = OpConstant %7 5 +%154 = OpTypePointer Uniform %12 +%155 = OpTypePointer Uniform %4 +%156 = OpConstant %7 3 +%159 = OpConstant %7 4 +%161 = OpTypePointer StorageBuffer %4 +%172 = OpConstant %23 2 +%173 = OpConstant %7 256 %53 = OpFunction %2 None %54 %52 = OpFunctionParameter %8 %51 = OpLabel @@ -155,104 +153,100 @@ OpBranch %55 %55 = OpLabel OpReturn OpFunctionEnd -%60 = OpFunction %2 None %61 -%59 = OpLabel -%56 = OpVariable %57 Function %58 -%64 = OpAccessChain %62 %30 %63 +%57 = OpFunction %2 None %58 +%56 = OpLabel +%68 = OpVariable %69 Function %64 +%61 = OpAccessChain %59 %30 %60 OpBranch %70 %70 = OpLabel -%72 = OpCompositeConstruct %8 %65 %65 %65 -%73 = OpAccessChain %71 %64 %63 -OpStore %73 %72 -OpStore %56 %66 -%75 = OpAccessChain %74 %64 %63 %63 +%72 = OpAccessChain %71 %61 %60 +OpStore %72 %63 +%74 = OpAccessChain %73 %61 %60 %60 +OpStore %74 %62 +%75 = OpAccessChain %73 %61 %60 %60 OpStore %75 %65 -%76 = OpAccessChain %74 %64 %63 %63 -OpStore %76 %67 -%77 = OpLoad %23 %56 -%78 = OpAccessChain %74 %64 %63 %77 -OpStore %78 %68 -%79 = OpLoad %9 %64 -%80 = OpCompositeExtract %8 %79 0 -%81 = OpCompositeExtract %8 %79 0 -%82 = OpVectorShuffle %10 %81 %81 2 0 -%83 = OpCompositeExtract %8 %79 0 -%84 = OpFunctionCall %2 %53 %83 -%85 = OpCompositeExtract %8 %79 0 -%86 = OpVectorTimesMatrix %8 %85 %69 -%87 = OpCompositeExtract %8 %79 0 -%88 = OpMatrixTimesVector %8 %69 %87 -%89 = OpCompositeExtract %8 %79 0 -%90 = OpVectorTimesScalar %8 %89 %67 -%91 = OpCompositeExtract %8 %79 0 -%92 = OpVectorTimesScalar %8 %91 %67 +%76 = OpLoad %23 %68 +%77 = OpAccessChain %73 %61 %60 %76 +OpStore %77 %66 +%78 = OpLoad %9 %61 +%79 = OpCompositeExtract %8 %78 0 +%80 = OpCompositeExtract %8 %78 0 +%81 = OpVectorShuffle %10 %80 %80 2 0 +%82 = OpCompositeExtract %8 %78 0 +%83 = OpFunctionCall %2 %53 %82 +%84 = OpCompositeExtract %8 %78 0 +%85 = OpVectorTimesMatrix %8 %84 %67 +%86 = OpCompositeExtract %8 %78 0 +%87 = OpMatrixTimesVector %8 %67 %86 +%88 = OpCompositeExtract %8 %78 0 +%89 = OpVectorTimesScalar %8 %88 %65 +%90 = OpCompositeExtract %8 %78 0 +%91 = OpVectorTimesScalar %8 %90 %65 OpReturn OpFunctionEnd -%100 = OpFunction %2 None %61 -%99 = OpLabel -%93 = OpVariable %94 Function %95 -%96 = OpVariable %97 Function %98 -%101 = OpAccessChain %62 %30 %63 -%103 = OpAccessChain %102 %33 %63 -%105 = OpAccessChain %104 %36 %63 -%107 = OpAccessChain %106 %39 %63 -%109 = OpAccessChain %108 %42 %63 -%111 = OpAccessChain %110 %45 %63 -%113 = OpAccessChain %112 %48 %63 -OpBranch %115 -%115 = OpLabel -%121 = OpLoad %118 %119 -%124 = OpIEqual %123 %121 %122 -%125 = OpAll %3 %124 -OpSelectionMerge %126 None -OpBranchConditional %125 %127 %126 -%127 = OpLabel -OpStore %26 %116 -OpStore %28 %117 +%93 = OpFunction %2 None %58 +%92 = OpLabel +%108 = OpVariable %109 Function %62 +%110 = OpVariable %111 Function %25 +%94 = OpAccessChain %59 %30 %60 +%96 = OpAccessChain %95 %33 %60 +%98 = OpAccessChain %97 %36 %60 +%100 = OpAccessChain %99 %39 %60 +%102 = OpAccessChain %101 %42 %60 +%104 = OpAccessChain %103 %45 %60 +%106 = OpAccessChain %105 %48 %60 +OpBranch %112 +%112 = OpLabel +%118 = OpLoad %115 %116 +%121 = OpIEqual %120 %118 %119 +%122 = OpAll %3 %121 +OpSelectionMerge %123 None +OpBranchConditional %122 %124 %123 +%124 = OpLabel +OpStore %26 %113 +OpStore %28 %114 +OpBranch %123 +%123 = OpLabel +OpControlBarrier %18 %18 %125 OpBranch %126 %126 = OpLabel -OpControlBarrier %18 %18 %128 -OpBranch %129 -%129 = OpLabel -%130 = OpFunctionCall %2 %60 -%134 = OpAccessChain %133 %113 %63 %63 -%135 = OpLoad %20 %134 -%139 = OpAccessChain %138 %111 %63 %63 %63 -%140 = OpLoad %12 %139 -%141 = OpMatrixTimesVector %10 %135 %140 -%142 = OpCompositeExtract %4 %141 0 -%144 = OpAccessChain %131 %26 %143 -OpStore %144 %142 -%145 = OpLoad %15 %109 -%146 = OpLoad %8 %107 -%147 = OpMatrixTimesVector %10 %145 %146 -%148 = OpCompositeExtract %4 %147 0 -%150 = OpAccessChain %131 %26 %149 -OpStore %150 %148 -%153 = OpAccessChain %74 %103 %152 %152 -%154 = OpLoad %4 %153 -%156 = OpAccessChain %131 %26 %155 -OpStore %156 %154 -%160 = OpAccessChain %158 %105 %63 %159 -%161 = OpLoad %4 %160 -%163 = OpAccessChain %131 %26 %162 -OpStore %163 %161 -%165 = OpAccessChain %164 %101 %152 +%127 = OpFunctionCall %2 %57 +%131 = OpAccessChain %130 %106 %60 %60 +%132 = OpLoad %20 %131 +%136 = OpAccessChain %135 %104 %60 %60 %60 +%137 = OpLoad %12 %136 +%138 = OpMatrixTimesVector %10 %132 %137 +%139 = OpCompositeExtract %4 %138 0 +%141 = OpAccessChain %128 %26 %140 +OpStore %141 %139 +%142 = OpLoad %15 %102 +%143 = OpLoad %8 %100 +%144 = OpMatrixTimesVector %10 %142 %143 +%145 = OpCompositeExtract %4 %144 0 +%147 = OpAccessChain %128 %26 %146 +OpStore %147 %145 +%150 = OpAccessChain %73 %96 %149 %149 +%151 = OpLoad %4 %150 +%153 = OpAccessChain %128 %26 %152 +OpStore %153 %151 +%157 = OpAccessChain %155 %98 %60 %156 +%158 = OpLoad %4 %157 +%160 = OpAccessChain %128 %26 %159 +OpStore %160 %158 +%162 = OpAccessChain %161 %94 %149 +%163 = OpLoad %4 %162 +%164 = OpAccessChain %128 %26 %156 +OpStore %164 %163 +%165 = OpAccessChain %73 %94 %60 %60 %166 = OpLoad %4 %165 -%167 = OpAccessChain %131 %26 %159 +%167 = OpAccessChain %128 %26 %18 OpStore %167 %166 -%168 = OpAccessChain %74 %101 %63 %63 -%169 = OpLoad %4 %168 -%170 = OpAccessChain %131 %26 %18 -OpStore %170 %169 -%171 = OpAccessChain %164 %101 %152 -OpStore %171 %114 -%172 = OpArrayLength %7 %33 0 -%173 = OpConvertUToF %4 %172 -%174 = OpAccessChain %131 %26 %152 -OpStore %174 %173 -OpAtomicStore %28 %175 %176 %18 -OpStore %93 %65 -OpStore %96 %25 +%168 = OpAccessChain %161 %94 %149 +OpStore %168 %107 +%169 = OpArrayLength %7 %33 0 +%170 = OpConvertUToF %4 %169 +%171 = OpAccessChain %128 %26 %149 +OpStore %171 %170 +OpAtomicStore %28 %172 %173 %18 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index 06aa36bcb..ec35372f8 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 522 +; Bound: 517 OpCapability Shader OpCapability Image1D OpCapability Sampled1D @@ -11,18 +11,18 @@ OpCapability ImageQuery OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %78 "main" %75 OpEntryPoint GLCompute %169 "depth_load" %167 -OpEntryPoint Vertex %190 "queries" %188 -OpEntryPoint Vertex %242 "levels_queries" %241 -OpEntryPoint Fragment %274 "texture_sample" %273 -OpEntryPoint Fragment %420 "texture_sample_comparison" %418 -OpEntryPoint Fragment %475 "gather" %474 -OpEntryPoint Fragment %510 "depth_no_comparison" %509 +OpEntryPoint Vertex %189 "queries" %187 +OpEntryPoint Vertex %241 "levels_queries" %240 +OpEntryPoint Fragment %270 "texture_sample" %269 +OpEntryPoint Fragment %416 "texture_sample_comparison" %414 +OpEntryPoint Fragment %472 "gather" %471 +OpEntryPoint Fragment %506 "depth_no_comparison" %505 OpExecutionMode %78 LocalSize 16 1 1 OpExecutionMode %169 LocalSize 16 1 1 -OpExecutionMode %274 OriginUpperLeft -OpExecutionMode %420 OriginUpperLeft -OpExecutionMode %475 OriginUpperLeft -OpExecutionMode %510 OriginUpperLeft +OpExecutionMode %270 OriginUpperLeft +OpExecutionMode %416 OriginUpperLeft +OpExecutionMode %472 OriginUpperLeft +OpExecutionMode %506 OriginUpperLeft OpName %31 "image_mipmapped_src" OpName %33 "image_multisampled_src" OpName %35 "image_depth_multisampled_src" @@ -49,14 +49,14 @@ OpName %75 "local_id" OpName %78 "main" OpName %167 "local_id" OpName %169 "depth_load" -OpName %190 "queries" -OpName %242 "levels_queries" -OpName %269 "a" -OpName %274 "texture_sample" -OpName %414 "a" -OpName %420 "texture_sample_comparison" -OpName %475 "gather" -OpName %510 "depth_no_comparison" +OpName %189 "queries" +OpName %241 "levels_queries" +OpName %270 "texture_sample" +OpName %284 "a" +OpName %416 "texture_sample_comparison" +OpName %421 "a" +OpName %472 "gather" +OpName %506 "depth_no_comparison" OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 0 OpDecorate %33 DescriptorSet 0 @@ -106,12 +106,12 @@ OpDecorate %72 DescriptorSet 1 OpDecorate %72 Binding 4 OpDecorate %75 BuiltIn LocalInvocationId OpDecorate %167 BuiltIn LocalInvocationId -OpDecorate %188 BuiltIn Position -OpDecorate %241 BuiltIn Position -OpDecorate %273 Location 0 -OpDecorate %418 Location 0 -OpDecorate %474 Location 0 -OpDecorate %509 Location 0 +OpDecorate %187 BuiltIn Position +OpDecorate %240 BuiltIn Position +OpDecorate %269 Location 0 +OpDecorate %414 Location 0 +OpDecorate %471 Location 0 +OpDecorate %505 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpTypeImage %4 2D 0 0 0 1 Unknown @@ -189,42 +189,45 @@ OpDecorate %509 Location 0 %79 = OpTypeFunction %2 %86 = OpConstant %14 10 %87 = OpConstant %14 20 -%89 = OpTypeVector %4 2 +%88 = OpConstantComposite %13 %86 %87 +%90 = OpTypeVector %4 2 %98 = OpTypeVector %4 4 %109 = OpTypeVector %14 3 %167 = OpVariable %76 Input -%189 = OpTypePointer Output %23 -%188 = OpVariable %189 Output -%199 = OpConstant %4 0 -%241 = OpVariable %189 Output -%270 = OpTypePointer Function %23 -%271 = OpConstantNull %23 -%273 = OpVariable %189 Output -%280 = OpConstant %7 0.5 +%188 = OpTypePointer Output %23 +%187 = OpVariable %188 Output +%198 = OpConstant %4 0 +%240 = OpVariable %188 Output +%269 = OpVariable %188 Output +%276 = OpConstant %7 0.5 +%277 = OpTypeVector %7 2 +%278 = OpConstantComposite %277 %276 %276 +%279 = OpTypeVector %7 3 +%280 = OpConstantComposite %279 %276 %276 %276 %281 = OpConstant %7 2.3 %282 = OpConstant %7 2.0 %283 = OpConstant %14 0 -%285 = OpTypeVector %7 2 -%287 = OpTypeVector %7 3 -%289 = OpTypeSampledImage %15 -%294 = OpTypeSampledImage %16 -%315 = OpTypeSampledImage %18 -%376 = OpTypeSampledImage %20 -%415 = OpTypePointer Function %7 -%416 = OpConstantNull %7 -%419 = OpTypePointer Output %7 -%418 = OpVariable %419 Output -%428 = OpTypeSampledImage %25 -%433 = OpTypeSampledImage %26 -%446 = OpTypeSampledImage %27 -%453 = OpConstant %7 0.0 -%474 = OpVariable %189 Output -%486 = OpConstant %4 1 -%489 = OpConstant %4 3 -%494 = OpTypeSampledImage %3 -%497 = OpTypeVector %14 4 -%498 = OpTypeSampledImage %17 -%509 = OpVariable %189 Output +%285 = OpTypePointer Function %23 +%286 = OpConstantNull %23 +%288 = OpTypeSampledImage %15 +%293 = OpTypeSampledImage %16 +%314 = OpTypeSampledImage %18 +%375 = OpTypeSampledImage %20 +%415 = OpTypePointer Output %7 +%414 = OpVariable %415 Output +%422 = OpTypePointer Function %7 +%423 = OpConstantNull %7 +%425 = OpTypeSampledImage %25 +%430 = OpTypeSampledImage %26 +%443 = OpTypeSampledImage %27 +%450 = OpConstant %7 0.0 +%471 = OpVariable %188 Output +%482 = OpConstant %4 1 +%485 = OpConstant %4 3 +%490 = OpTypeSampledImage %3 +%493 = OpTypeVector %14 4 +%494 = OpTypeSampledImage %17 +%505 = OpVariable %188 Output %78 = OpFunction %2 None %79 %74 = OpLabel %77 = OpLoad %12 %75 @@ -234,14 +237,13 @@ OpDecorate %509 Location 0 %83 = OpLoad %9 %39 %84 = OpLoad %11 %43 %85 = OpLoad %10 %45 -OpBranch %88 -%88 = OpLabel -%90 = OpImageQuerySize %89 %82 -%91 = OpVectorShuffle %89 %77 %77 0 1 -%92 = OpIMul %89 %90 %91 -%93 = OpBitcast %13 %92 -%94 = OpCompositeConstruct %13 %86 %87 -%95 = OpSRem %13 %93 %94 +OpBranch %89 +%89 = OpLabel +%91 = OpImageQuerySize %90 %82 +%92 = OpVectorShuffle %90 %77 %77 0 1 +%93 = OpIMul %90 %91 %92 +%94 = OpBitcast %13 %93 +%95 = OpSRem %13 %94 %88 %96 = OpCompositeExtract %4 %77 2 %97 = OpBitcast %14 %96 %99 = OpImageFetch %98 %80 %95 Lod %97 @@ -268,24 +270,24 @@ OpBranch %88 %121 = OpCompositeExtract %4 %77 2 %122 = OpBitcast %14 %121 %123 = OpImageFetch %98 %84 %120 Lod %122 -%124 = OpBitcast %89 %95 +%124 = OpBitcast %90 %95 %125 = OpCompositeExtract %4 %77 2 %126 = OpBitcast %14 %125 %127 = OpImageFetch %98 %80 %124 Lod %126 -%128 = OpBitcast %89 %95 +%128 = OpBitcast %90 %95 %129 = OpCompositeExtract %4 %77 2 %130 = OpBitcast %14 %129 %131 = OpImageFetch %98 %81 %128 Sample %130 -%132 = OpBitcast %89 %95 +%132 = OpBitcast %90 %95 %133 = OpImageRead %98 %82 %132 -%134 = OpBitcast %89 %95 +%134 = OpBitcast %90 %95 %135 = OpCompositeExtract %4 %77 2 %136 = OpCompositeExtract %4 %77 2 %137 = OpBitcast %14 %136 %138 = OpIAdd %14 %137 %29 %139 = OpCompositeConstruct %12 %134 %135 %140 = OpImageFetch %98 %83 %139 Lod %138 -%141 = OpBitcast %89 %95 +%141 = OpBitcast %90 %95 %142 = OpCompositeExtract %4 %77 2 %143 = OpBitcast %14 %142 %144 = OpCompositeExtract %4 %77 2 @@ -321,376 +323,369 @@ OpFunctionEnd %172 = OpLoad %10 %45 OpBranch %173 %173 = OpLabel -%174 = OpImageQuerySize %89 %171 -%175 = OpVectorShuffle %89 %168 %168 0 1 -%176 = OpIMul %89 %174 %175 +%174 = OpImageQuerySize %90 %171 +%175 = OpVectorShuffle %90 %168 %168 0 1 +%176 = OpIMul %90 %174 %175 %177 = OpBitcast %13 %176 -%178 = OpCompositeConstruct %13 %86 %87 -%179 = OpSRem %13 %177 %178 -%180 = OpCompositeExtract %4 %168 2 -%181 = OpBitcast %14 %180 -%182 = OpImageFetch %23 %170 %179 Sample %181 -%183 = OpCompositeExtract %7 %182 0 -%184 = OpCompositeExtract %14 %179 0 -%185 = OpConvertFToU %4 %183 -%186 = OpCompositeConstruct %98 %185 %185 %185 %185 -OpImageWrite %172 %184 %186 +%178 = OpSRem %13 %177 %88 +%179 = OpCompositeExtract %4 %168 2 +%180 = OpBitcast %14 %179 +%181 = OpImageFetch %23 %170 %178 Sample %180 +%182 = OpCompositeExtract %7 %181 0 +%183 = OpCompositeExtract %14 %178 0 +%184 = OpConvertFToU %4 %182 +%185 = OpCompositeConstruct %98 %184 %184 %184 %184 +OpImageWrite %172 %183 %185 OpReturn OpFunctionEnd -%190 = OpFunction %2 None %79 -%187 = OpLabel -%191 = OpLoad %15 %47 -%192 = OpLoad %16 %49 -%193 = OpLoad %18 %54 -%194 = OpLoad %19 %56 -%195 = OpLoad %20 %58 -%196 = OpLoad %21 %60 -%197 = OpLoad %22 %62 -OpBranch %198 -%198 = OpLabel -%200 = OpImageQuerySizeLod %4 %191 %199 -%201 = OpBitcast %14 %200 -%202 = OpImageQuerySizeLod %4 %191 %201 -%203 = OpImageQuerySizeLod %89 %192 %199 -%204 = OpImageQuerySizeLod %89 %192 %29 -%205 = OpImageQuerySizeLod %12 %193 %199 -%206 = OpVectorShuffle %89 %205 %205 0 1 -%207 = OpImageQuerySizeLod %12 %193 %29 -%208 = OpVectorShuffle %89 %207 %207 0 1 -%209 = OpImageQuerySizeLod %89 %194 %199 -%210 = OpImageQuerySizeLod %89 %194 %29 -%211 = OpImageQuerySizeLod %12 %195 %199 -%212 = OpVectorShuffle %89 %211 %211 0 0 -%213 = OpImageQuerySizeLod %12 %195 %29 -%214 = OpVectorShuffle %89 %213 %213 0 0 -%215 = OpImageQuerySizeLod %12 %196 %199 -%216 = OpImageQuerySizeLod %12 %196 %29 -%217 = OpImageQuerySize %89 %197 -%218 = OpCompositeExtract %4 %203 1 -%219 = OpIAdd %4 %200 %218 -%220 = OpCompositeExtract %4 %204 1 -%221 = OpIAdd %4 %219 %220 -%222 = OpCompositeExtract %4 %206 1 -%223 = OpIAdd %4 %221 %222 -%224 = OpCompositeExtract %4 %208 1 -%225 = OpIAdd %4 %223 %224 -%226 = OpCompositeExtract %4 %209 1 -%227 = OpIAdd %4 %225 %226 -%228 = OpCompositeExtract %4 %210 1 -%229 = OpIAdd %4 %227 %228 -%230 = OpCompositeExtract %4 %212 1 -%231 = OpIAdd %4 %229 %230 -%232 = OpCompositeExtract %4 %214 1 -%233 = OpIAdd %4 %231 %232 -%234 = OpCompositeExtract %4 %215 2 -%235 = OpIAdd %4 %233 %234 -%236 = OpCompositeExtract %4 %216 2 -%237 = OpIAdd %4 %235 %236 -%238 = OpConvertUToF %7 %237 -%239 = OpCompositeConstruct %23 %238 %238 %238 %238 -OpStore %188 %239 +%189 = OpFunction %2 None %79 +%186 = OpLabel +%190 = OpLoad %15 %47 +%191 = OpLoad %16 %49 +%192 = OpLoad %18 %54 +%193 = OpLoad %19 %56 +%194 = OpLoad %20 %58 +%195 = OpLoad %21 %60 +%196 = OpLoad %22 %62 +OpBranch %197 +%197 = OpLabel +%199 = OpImageQuerySizeLod %4 %190 %198 +%200 = OpBitcast %14 %199 +%201 = OpImageQuerySizeLod %4 %190 %200 +%202 = OpImageQuerySizeLod %90 %191 %198 +%203 = OpImageQuerySizeLod %90 %191 %29 +%204 = OpImageQuerySizeLod %12 %192 %198 +%205 = OpVectorShuffle %90 %204 %204 0 1 +%206 = OpImageQuerySizeLod %12 %192 %29 +%207 = OpVectorShuffle %90 %206 %206 0 1 +%208 = OpImageQuerySizeLod %90 %193 %198 +%209 = OpImageQuerySizeLod %90 %193 %29 +%210 = OpImageQuerySizeLod %12 %194 %198 +%211 = OpVectorShuffle %90 %210 %210 0 0 +%212 = OpImageQuerySizeLod %12 %194 %29 +%213 = OpVectorShuffle %90 %212 %212 0 0 +%214 = OpImageQuerySizeLod %12 %195 %198 +%215 = OpImageQuerySizeLod %12 %195 %29 +%216 = OpImageQuerySize %90 %196 +%217 = OpCompositeExtract %4 %202 1 +%218 = OpIAdd %4 %199 %217 +%219 = OpCompositeExtract %4 %203 1 +%220 = OpIAdd %4 %218 %219 +%221 = OpCompositeExtract %4 %205 1 +%222 = OpIAdd %4 %220 %221 +%223 = OpCompositeExtract %4 %207 1 +%224 = OpIAdd %4 %222 %223 +%225 = OpCompositeExtract %4 %208 1 +%226 = OpIAdd %4 %224 %225 +%227 = OpCompositeExtract %4 %209 1 +%228 = OpIAdd %4 %226 %227 +%229 = OpCompositeExtract %4 %211 1 +%230 = OpIAdd %4 %228 %229 +%231 = OpCompositeExtract %4 %213 1 +%232 = OpIAdd %4 %230 %231 +%233 = OpCompositeExtract %4 %214 2 +%234 = OpIAdd %4 %232 %233 +%235 = OpCompositeExtract %4 %215 2 +%236 = OpIAdd %4 %234 %235 +%237 = OpConvertUToF %7 %236 +%238 = OpCompositeConstruct %23 %237 %237 %237 %237 +OpStore %187 %238 OpReturn OpFunctionEnd -%242 = OpFunction %2 None %79 -%240 = OpLabel -%243 = OpLoad %16 %49 -%244 = OpLoad %18 %54 -%245 = OpLoad %19 %56 -%246 = OpLoad %20 %58 -%247 = OpLoad %21 %60 -%248 = OpLoad %22 %62 -OpBranch %249 -%249 = OpLabel +%241 = OpFunction %2 None %79 +%239 = OpLabel +%242 = OpLoad %16 %49 +%243 = OpLoad %18 %54 +%244 = OpLoad %19 %56 +%245 = OpLoad %20 %58 +%246 = OpLoad %21 %60 +%247 = OpLoad %22 %62 +OpBranch %248 +%248 = OpLabel +%249 = OpImageQueryLevels %4 %242 %250 = OpImageQueryLevels %4 %243 -%251 = OpImageQueryLevels %4 %244 -%252 = OpImageQuerySizeLod %12 %244 %199 -%253 = OpCompositeExtract %4 %252 2 +%251 = OpImageQuerySizeLod %12 %243 %198 +%252 = OpCompositeExtract %4 %251 2 +%253 = OpImageQueryLevels %4 %244 %254 = OpImageQueryLevels %4 %245 -%255 = OpImageQueryLevels %4 %246 -%256 = OpImageQuerySizeLod %12 %246 %199 -%257 = OpCompositeExtract %4 %256 2 -%258 = OpImageQueryLevels %4 %247 -%259 = OpImageQuerySamples %4 %248 -%260 = OpIAdd %4 %253 %257 -%261 = OpIAdd %4 %260 %259 +%255 = OpImageQuerySizeLod %12 %245 %198 +%256 = OpCompositeExtract %4 %255 2 +%257 = OpImageQueryLevels %4 %246 +%258 = OpImageQuerySamples %4 %247 +%259 = OpIAdd %4 %252 %256 +%260 = OpIAdd %4 %259 %258 +%261 = OpIAdd %4 %260 %249 %262 = OpIAdd %4 %261 %250 -%263 = OpIAdd %4 %262 %251 -%264 = OpIAdd %4 %263 %258 +%263 = OpIAdd %4 %262 %257 +%264 = OpIAdd %4 %263 %253 %265 = OpIAdd %4 %264 %254 -%266 = OpIAdd %4 %265 %255 -%267 = OpConvertUToF %7 %266 -%268 = OpCompositeConstruct %23 %267 %267 %267 %267 -OpStore %241 %268 +%266 = OpConvertUToF %7 %265 +%267 = OpCompositeConstruct %23 %266 %266 %266 %266 +OpStore %240 %267 OpReturn OpFunctionEnd -%274 = OpFunction %2 None %79 -%272 = OpLabel -%269 = OpVariable %270 Function %271 -%275 = OpLoad %15 %47 -%276 = OpLoad %16 %49 -%277 = OpLoad %18 %54 -%278 = OpLoad %20 %58 -%279 = OpLoad %24 %64 -OpBranch %284 -%284 = OpLabel -%286 = OpCompositeConstruct %285 %280 %280 -%288 = OpCompositeConstruct %287 %280 %280 %280 -%290 = OpSampledImage %289 %275 %279 -%291 = OpImageSampleImplicitLod %23 %290 %280 -%292 = OpLoad %23 %269 -%293 = OpFAdd %23 %292 %291 -OpStore %269 %293 -%295 = OpSampledImage %294 %276 %279 -%296 = OpImageSampleImplicitLod %23 %295 %286 -%297 = OpLoad %23 %269 -%298 = OpFAdd %23 %297 %296 -OpStore %269 %298 -%299 = OpSampledImage %294 %276 %279 -%300 = OpImageSampleImplicitLod %23 %299 %286 ConstOffset %30 -%301 = OpLoad %23 %269 -%302 = OpFAdd %23 %301 %300 -OpStore %269 %302 -%303 = OpSampledImage %294 %276 %279 -%304 = OpImageSampleExplicitLod %23 %303 %286 Lod %281 -%305 = OpLoad %23 %269 -%306 = OpFAdd %23 %305 %304 -OpStore %269 %306 -%307 = OpSampledImage %294 %276 %279 -%308 = OpImageSampleExplicitLod %23 %307 %286 Lod|ConstOffset %281 %30 -%309 = OpLoad %23 %269 -%310 = OpFAdd %23 %309 %308 -OpStore %269 %310 -%311 = OpSampledImage %294 %276 %279 -%312 = OpImageSampleImplicitLod %23 %311 %286 Bias|ConstOffset %282 %30 -%313 = OpLoad %23 %269 -%314 = OpFAdd %23 %313 %312 -OpStore %269 %314 -%316 = OpConvertUToF %7 %199 -%317 = OpCompositeConstruct %287 %286 %316 -%318 = OpSampledImage %315 %277 %279 -%319 = OpImageSampleImplicitLod %23 %318 %317 -%320 = OpLoad %23 %269 -%321 = OpFAdd %23 %320 %319 -OpStore %269 %321 -%322 = OpConvertUToF %7 %199 -%323 = OpCompositeConstruct %287 %286 %322 -%324 = OpSampledImage %315 %277 %279 -%325 = OpImageSampleImplicitLod %23 %324 %323 ConstOffset %30 -%326 = OpLoad %23 %269 -%327 = OpFAdd %23 %326 %325 -OpStore %269 %327 -%328 = OpConvertUToF %7 %199 -%329 = OpCompositeConstruct %287 %286 %328 -%330 = OpSampledImage %315 %277 %279 -%331 = OpImageSampleExplicitLod %23 %330 %329 Lod %281 -%332 = OpLoad %23 %269 -%333 = OpFAdd %23 %332 %331 -OpStore %269 %333 -%334 = OpConvertUToF %7 %199 -%335 = OpCompositeConstruct %287 %286 %334 -%336 = OpSampledImage %315 %277 %279 -%337 = OpImageSampleExplicitLod %23 %336 %335 Lod|ConstOffset %281 %30 -%338 = OpLoad %23 %269 -%339 = OpFAdd %23 %338 %337 -OpStore %269 %339 -%340 = OpConvertUToF %7 %199 -%341 = OpCompositeConstruct %287 %286 %340 -%342 = OpSampledImage %315 %277 %279 -%343 = OpImageSampleImplicitLod %23 %342 %341 Bias|ConstOffset %282 %30 -%344 = OpLoad %23 %269 -%345 = OpFAdd %23 %344 %343 -OpStore %269 %345 -%346 = OpConvertSToF %7 %283 -%347 = OpCompositeConstruct %287 %286 %346 -%348 = OpSampledImage %315 %277 %279 -%349 = OpImageSampleImplicitLod %23 %348 %347 -%350 = OpLoad %23 %269 -%351 = OpFAdd %23 %350 %349 -OpStore %269 %351 -%352 = OpConvertSToF %7 %283 -%353 = OpCompositeConstruct %287 %286 %352 -%354 = OpSampledImage %315 %277 %279 -%355 = OpImageSampleImplicitLod %23 %354 %353 ConstOffset %30 -%356 = OpLoad %23 %269 -%357 = OpFAdd %23 %356 %355 -OpStore %269 %357 -%358 = OpConvertSToF %7 %283 -%359 = OpCompositeConstruct %287 %286 %358 -%360 = OpSampledImage %315 %277 %279 -%361 = OpImageSampleExplicitLod %23 %360 %359 Lod %281 -%362 = OpLoad %23 %269 -%363 = OpFAdd %23 %362 %361 -OpStore %269 %363 -%364 = OpConvertSToF %7 %283 -%365 = OpCompositeConstruct %287 %286 %364 -%366 = OpSampledImage %315 %277 %279 -%367 = OpImageSampleExplicitLod %23 %366 %365 Lod|ConstOffset %281 %30 -%368 = OpLoad %23 %269 -%369 = OpFAdd %23 %368 %367 -OpStore %269 %369 -%370 = OpConvertSToF %7 %283 -%371 = OpCompositeConstruct %287 %286 %370 -%372 = OpSampledImage %315 %277 %279 -%373 = OpImageSampleImplicitLod %23 %372 %371 Bias|ConstOffset %282 %30 -%374 = OpLoad %23 %269 -%375 = OpFAdd %23 %374 %373 -OpStore %269 %375 -%377 = OpConvertUToF %7 %199 -%378 = OpCompositeConstruct %23 %288 %377 -%379 = OpSampledImage %376 %278 %279 -%380 = OpImageSampleImplicitLod %23 %379 %378 -%381 = OpLoad %23 %269 -%382 = OpFAdd %23 %381 %380 -OpStore %269 %382 -%383 = OpConvertUToF %7 %199 -%384 = OpCompositeConstruct %23 %288 %383 -%385 = OpSampledImage %376 %278 %279 -%386 = OpImageSampleExplicitLod %23 %385 %384 Lod %281 -%387 = OpLoad %23 %269 -%388 = OpFAdd %23 %387 %386 -OpStore %269 %388 -%389 = OpConvertUToF %7 %199 -%390 = OpCompositeConstruct %23 %288 %389 -%391 = OpSampledImage %376 %278 %279 -%392 = OpImageSampleImplicitLod %23 %391 %390 Bias %282 -%393 = OpLoad %23 %269 -%394 = OpFAdd %23 %393 %392 -OpStore %269 %394 -%395 = OpConvertSToF %7 %283 -%396 = OpCompositeConstruct %23 %288 %395 -%397 = OpSampledImage %376 %278 %279 -%398 = OpImageSampleImplicitLod %23 %397 %396 -%399 = OpLoad %23 %269 -%400 = OpFAdd %23 %399 %398 -OpStore %269 %400 -%401 = OpConvertSToF %7 %283 -%402 = OpCompositeConstruct %23 %288 %401 -%403 = OpSampledImage %376 %278 %279 -%404 = OpImageSampleExplicitLod %23 %403 %402 Lod %281 -%405 = OpLoad %23 %269 -%406 = OpFAdd %23 %405 %404 -OpStore %269 %406 -%407 = OpConvertSToF %7 %283 -%408 = OpCompositeConstruct %23 %288 %407 -%409 = OpSampledImage %376 %278 %279 -%410 = OpImageSampleImplicitLod %23 %409 %408 Bias %282 -%411 = OpLoad %23 %269 -%412 = OpFAdd %23 %411 %410 +%270 = OpFunction %2 None %79 +%268 = OpLabel +%284 = OpVariable %285 Function %286 +%271 = OpLoad %15 %47 +%272 = OpLoad %16 %49 +%273 = OpLoad %18 %54 +%274 = OpLoad %20 %58 +%275 = OpLoad %24 %64 +OpBranch %287 +%287 = OpLabel +%289 = OpSampledImage %288 %271 %275 +%290 = OpImageSampleImplicitLod %23 %289 %276 +%291 = OpLoad %23 %284 +%292 = OpFAdd %23 %291 %290 +OpStore %284 %292 +%294 = OpSampledImage %293 %272 %275 +%295 = OpImageSampleImplicitLod %23 %294 %278 +%296 = OpLoad %23 %284 +%297 = OpFAdd %23 %296 %295 +OpStore %284 %297 +%298 = OpSampledImage %293 %272 %275 +%299 = OpImageSampleImplicitLod %23 %298 %278 ConstOffset %30 +%300 = OpLoad %23 %284 +%301 = OpFAdd %23 %300 %299 +OpStore %284 %301 +%302 = OpSampledImage %293 %272 %275 +%303 = OpImageSampleExplicitLod %23 %302 %278 Lod %281 +%304 = OpLoad %23 %284 +%305 = OpFAdd %23 %304 %303 +OpStore %284 %305 +%306 = OpSampledImage %293 %272 %275 +%307 = OpImageSampleExplicitLod %23 %306 %278 Lod|ConstOffset %281 %30 +%308 = OpLoad %23 %284 +%309 = OpFAdd %23 %308 %307 +OpStore %284 %309 +%310 = OpSampledImage %293 %272 %275 +%311 = OpImageSampleImplicitLod %23 %310 %278 Bias|ConstOffset %282 %30 +%312 = OpLoad %23 %284 +%313 = OpFAdd %23 %312 %311 +OpStore %284 %313 +%315 = OpConvertUToF %7 %198 +%316 = OpCompositeConstruct %279 %278 %315 +%317 = OpSampledImage %314 %273 %275 +%318 = OpImageSampleImplicitLod %23 %317 %316 +%319 = OpLoad %23 %284 +%320 = OpFAdd %23 %319 %318 +OpStore %284 %320 +%321 = OpConvertUToF %7 %198 +%322 = OpCompositeConstruct %279 %278 %321 +%323 = OpSampledImage %314 %273 %275 +%324 = OpImageSampleImplicitLod %23 %323 %322 ConstOffset %30 +%325 = OpLoad %23 %284 +%326 = OpFAdd %23 %325 %324 +OpStore %284 %326 +%327 = OpConvertUToF %7 %198 +%328 = OpCompositeConstruct %279 %278 %327 +%329 = OpSampledImage %314 %273 %275 +%330 = OpImageSampleExplicitLod %23 %329 %328 Lod %281 +%331 = OpLoad %23 %284 +%332 = OpFAdd %23 %331 %330 +OpStore %284 %332 +%333 = OpConvertUToF %7 %198 +%334 = OpCompositeConstruct %279 %278 %333 +%335 = OpSampledImage %314 %273 %275 +%336 = OpImageSampleExplicitLod %23 %335 %334 Lod|ConstOffset %281 %30 +%337 = OpLoad %23 %284 +%338 = OpFAdd %23 %337 %336 +OpStore %284 %338 +%339 = OpConvertUToF %7 %198 +%340 = OpCompositeConstruct %279 %278 %339 +%341 = OpSampledImage %314 %273 %275 +%342 = OpImageSampleImplicitLod %23 %341 %340 Bias|ConstOffset %282 %30 +%343 = OpLoad %23 %284 +%344 = OpFAdd %23 %343 %342 +OpStore %284 %344 +%345 = OpConvertSToF %7 %283 +%346 = OpCompositeConstruct %279 %278 %345 +%347 = OpSampledImage %314 %273 %275 +%348 = OpImageSampleImplicitLod %23 %347 %346 +%349 = OpLoad %23 %284 +%350 = OpFAdd %23 %349 %348 +OpStore %284 %350 +%351 = OpConvertSToF %7 %283 +%352 = OpCompositeConstruct %279 %278 %351 +%353 = OpSampledImage %314 %273 %275 +%354 = OpImageSampleImplicitLod %23 %353 %352 ConstOffset %30 +%355 = OpLoad %23 %284 +%356 = OpFAdd %23 %355 %354 +OpStore %284 %356 +%357 = OpConvertSToF %7 %283 +%358 = OpCompositeConstruct %279 %278 %357 +%359 = OpSampledImage %314 %273 %275 +%360 = OpImageSampleExplicitLod %23 %359 %358 Lod %281 +%361 = OpLoad %23 %284 +%362 = OpFAdd %23 %361 %360 +OpStore %284 %362 +%363 = OpConvertSToF %7 %283 +%364 = OpCompositeConstruct %279 %278 %363 +%365 = OpSampledImage %314 %273 %275 +%366 = OpImageSampleExplicitLod %23 %365 %364 Lod|ConstOffset %281 %30 +%367 = OpLoad %23 %284 +%368 = OpFAdd %23 %367 %366 +OpStore %284 %368 +%369 = OpConvertSToF %7 %283 +%370 = OpCompositeConstruct %279 %278 %369 +%371 = OpSampledImage %314 %273 %275 +%372 = OpImageSampleImplicitLod %23 %371 %370 Bias|ConstOffset %282 %30 +%373 = OpLoad %23 %284 +%374 = OpFAdd %23 %373 %372 +OpStore %284 %374 +%376 = OpConvertUToF %7 %198 +%377 = OpCompositeConstruct %23 %280 %376 +%378 = OpSampledImage %375 %274 %275 +%379 = OpImageSampleImplicitLod %23 %378 %377 +%380 = OpLoad %23 %284 +%381 = OpFAdd %23 %380 %379 +OpStore %284 %381 +%382 = OpConvertUToF %7 %198 +%383 = OpCompositeConstruct %23 %280 %382 +%384 = OpSampledImage %375 %274 %275 +%385 = OpImageSampleExplicitLod %23 %384 %383 Lod %281 +%386 = OpLoad %23 %284 +%387 = OpFAdd %23 %386 %385 +OpStore %284 %387 +%388 = OpConvertUToF %7 %198 +%389 = OpCompositeConstruct %23 %280 %388 +%390 = OpSampledImage %375 %274 %275 +%391 = OpImageSampleImplicitLod %23 %390 %389 Bias %282 +%392 = OpLoad %23 %284 +%393 = OpFAdd %23 %392 %391 +OpStore %284 %393 +%394 = OpConvertSToF %7 %283 +%395 = OpCompositeConstruct %23 %280 %394 +%396 = OpSampledImage %375 %274 %275 +%397 = OpImageSampleImplicitLod %23 %396 %395 +%398 = OpLoad %23 %284 +%399 = OpFAdd %23 %398 %397 +OpStore %284 %399 +%400 = OpConvertSToF %7 %283 +%401 = OpCompositeConstruct %23 %280 %400 +%402 = OpSampledImage %375 %274 %275 +%403 = OpImageSampleExplicitLod %23 %402 %401 Lod %281 +%404 = OpLoad %23 %284 +%405 = OpFAdd %23 %404 %403 +OpStore %284 %405 +%406 = OpConvertSToF %7 %283 +%407 = OpCompositeConstruct %23 %280 %406 +%408 = OpSampledImage %375 %274 %275 +%409 = OpImageSampleImplicitLod %23 %408 %407 Bias %282 +%410 = OpLoad %23 %284 +%411 = OpFAdd %23 %410 %409 +OpStore %284 %411 +%412 = OpLoad %23 %284 OpStore %269 %412 -%413 = OpLoad %23 %269 -OpStore %273 %413 OpReturn OpFunctionEnd -%420 = OpFunction %2 None %79 -%417 = OpLabel -%414 = OpVariable %415 Function %416 -%421 = OpLoad %24 %66 -%422 = OpLoad %25 %68 -%423 = OpLoad %26 %70 -%424 = OpLoad %27 %72 -OpBranch %425 -%425 = OpLabel -%426 = OpCompositeConstruct %285 %280 %280 -%427 = OpCompositeConstruct %287 %280 %280 %280 -%429 = OpSampledImage %428 %422 %421 -%430 = OpImageSampleDrefImplicitLod %7 %429 %426 %280 -%431 = OpLoad %7 %414 -%432 = OpFAdd %7 %431 %430 -OpStore %414 %432 -%434 = OpConvertUToF %7 %199 -%435 = OpCompositeConstruct %287 %426 %434 -%436 = OpSampledImage %433 %423 %421 -%437 = OpImageSampleDrefImplicitLod %7 %436 %435 %280 -%438 = OpLoad %7 %414 -%439 = OpFAdd %7 %438 %437 -OpStore %414 %439 -%440 = OpConvertSToF %7 %283 -%441 = OpCompositeConstruct %287 %426 %440 -%442 = OpSampledImage %433 %423 %421 -%443 = OpImageSampleDrefImplicitLod %7 %442 %441 %280 -%444 = OpLoad %7 %414 -%445 = OpFAdd %7 %444 %443 -OpStore %414 %445 -%447 = OpSampledImage %446 %424 %421 -%448 = OpImageSampleDrefImplicitLod %7 %447 %427 %280 -%449 = OpLoad %7 %414 -%450 = OpFAdd %7 %449 %448 -OpStore %414 %450 -%451 = OpSampledImage %428 %422 %421 -%452 = OpImageSampleDrefExplicitLod %7 %451 %426 %280 Lod %453 -%454 = OpLoad %7 %414 -%455 = OpFAdd %7 %454 %452 -OpStore %414 %455 -%456 = OpConvertUToF %7 %199 -%457 = OpCompositeConstruct %287 %426 %456 -%458 = OpSampledImage %433 %423 %421 -%459 = OpImageSampleDrefExplicitLod %7 %458 %457 %280 Lod %453 -%460 = OpLoad %7 %414 -%461 = OpFAdd %7 %460 %459 -OpStore %414 %461 -%462 = OpConvertSToF %7 %283 -%463 = OpCompositeConstruct %287 %426 %462 -%464 = OpSampledImage %433 %423 %421 -%465 = OpImageSampleDrefExplicitLod %7 %464 %463 %280 Lod %453 -%466 = OpLoad %7 %414 -%467 = OpFAdd %7 %466 %465 -OpStore %414 %467 -%468 = OpSampledImage %446 %424 %421 -%469 = OpImageSampleDrefExplicitLod %7 %468 %427 %280 Lod %453 -%470 = OpLoad %7 %414 -%471 = OpFAdd %7 %470 %469 -OpStore %414 %471 -%472 = OpLoad %7 %414 -OpStore %418 %472 +%416 = OpFunction %2 None %79 +%413 = OpLabel +%421 = OpVariable %422 Function %423 +%417 = OpLoad %24 %66 +%418 = OpLoad %25 %68 +%419 = OpLoad %26 %70 +%420 = OpLoad %27 %72 +OpBranch %424 +%424 = OpLabel +%426 = OpSampledImage %425 %418 %417 +%427 = OpImageSampleDrefImplicitLod %7 %426 %278 %276 +%428 = OpLoad %7 %421 +%429 = OpFAdd %7 %428 %427 +OpStore %421 %429 +%431 = OpConvertUToF %7 %198 +%432 = OpCompositeConstruct %279 %278 %431 +%433 = OpSampledImage %430 %419 %417 +%434 = OpImageSampleDrefImplicitLod %7 %433 %432 %276 +%435 = OpLoad %7 %421 +%436 = OpFAdd %7 %435 %434 +OpStore %421 %436 +%437 = OpConvertSToF %7 %283 +%438 = OpCompositeConstruct %279 %278 %437 +%439 = OpSampledImage %430 %419 %417 +%440 = OpImageSampleDrefImplicitLod %7 %439 %438 %276 +%441 = OpLoad %7 %421 +%442 = OpFAdd %7 %441 %440 +OpStore %421 %442 +%444 = OpSampledImage %443 %420 %417 +%445 = OpImageSampleDrefImplicitLod %7 %444 %280 %276 +%446 = OpLoad %7 %421 +%447 = OpFAdd %7 %446 %445 +OpStore %421 %447 +%448 = OpSampledImage %425 %418 %417 +%449 = OpImageSampleDrefExplicitLod %7 %448 %278 %276 Lod %450 +%451 = OpLoad %7 %421 +%452 = OpFAdd %7 %451 %449 +OpStore %421 %452 +%453 = OpConvertUToF %7 %198 +%454 = OpCompositeConstruct %279 %278 %453 +%455 = OpSampledImage %430 %419 %417 +%456 = OpImageSampleDrefExplicitLod %7 %455 %454 %276 Lod %450 +%457 = OpLoad %7 %421 +%458 = OpFAdd %7 %457 %456 +OpStore %421 %458 +%459 = OpConvertSToF %7 %283 +%460 = OpCompositeConstruct %279 %278 %459 +%461 = OpSampledImage %430 %419 %417 +%462 = OpImageSampleDrefExplicitLod %7 %461 %460 %276 Lod %450 +%463 = OpLoad %7 %421 +%464 = OpFAdd %7 %463 %462 +OpStore %421 %464 +%465 = OpSampledImage %443 %420 %417 +%466 = OpImageSampleDrefExplicitLod %7 %465 %280 %276 Lod %450 +%467 = OpLoad %7 %421 +%468 = OpFAdd %7 %467 %466 +OpStore %421 %468 +%469 = OpLoad %7 %421 +OpStore %414 %469 OpReturn OpFunctionEnd -%475 = OpFunction %2 None %79 -%473 = OpLabel -%476 = OpLoad %16 %49 -%477 = OpLoad %3 %51 -%478 = OpLoad %17 %52 -%479 = OpLoad %24 %64 -%480 = OpLoad %24 %66 -%481 = OpLoad %25 %68 -OpBranch %482 -%482 = OpLabel -%483 = OpCompositeConstruct %285 %280 %280 -%484 = OpSampledImage %294 %476 %479 -%485 = OpImageGather %23 %484 %483 %486 -%487 = OpSampledImage %294 %476 %479 -%488 = OpImageGather %23 %487 %483 %489 ConstOffset %30 -%490 = OpSampledImage %428 %481 %480 -%491 = OpImageDrefGather %23 %490 %483 %280 -%492 = OpSampledImage %428 %481 %480 -%493 = OpImageDrefGather %23 %492 %483 %280 ConstOffset %30 -%495 = OpSampledImage %494 %477 %479 -%496 = OpImageGather %98 %495 %483 %199 -%499 = OpSampledImage %498 %478 %479 -%500 = OpImageGather %497 %499 %483 %199 -%501 = OpConvertUToF %23 %496 -%502 = OpConvertSToF %23 %500 -%503 = OpFAdd %23 %501 %502 -%504 = OpFAdd %23 %485 %488 -%505 = OpFAdd %23 %504 %491 -%506 = OpFAdd %23 %505 %493 -%507 = OpFAdd %23 %506 %503 -OpStore %474 %507 +%472 = OpFunction %2 None %79 +%470 = OpLabel +%473 = OpLoad %16 %49 +%474 = OpLoad %3 %51 +%475 = OpLoad %17 %52 +%476 = OpLoad %24 %64 +%477 = OpLoad %24 %66 +%478 = OpLoad %25 %68 +OpBranch %479 +%479 = OpLabel +%480 = OpSampledImage %293 %473 %476 +%481 = OpImageGather %23 %480 %278 %482 +%483 = OpSampledImage %293 %473 %476 +%484 = OpImageGather %23 %483 %278 %485 ConstOffset %30 +%486 = OpSampledImage %425 %478 %477 +%487 = OpImageDrefGather %23 %486 %278 %276 +%488 = OpSampledImage %425 %478 %477 +%489 = OpImageDrefGather %23 %488 %278 %276 ConstOffset %30 +%491 = OpSampledImage %490 %474 %476 +%492 = OpImageGather %98 %491 %278 %198 +%495 = OpSampledImage %494 %475 %476 +%496 = OpImageGather %493 %495 %278 %198 +%497 = OpConvertUToF %23 %492 +%498 = OpConvertSToF %23 %496 +%499 = OpFAdd %23 %497 %498 +%500 = OpFAdd %23 %481 %484 +%501 = OpFAdd %23 %500 %487 +%502 = OpFAdd %23 %501 %489 +%503 = OpFAdd %23 %502 %499 +OpStore %471 %503 OpReturn OpFunctionEnd -%510 = OpFunction %2 None %79 -%508 = OpLabel -%511 = OpLoad %24 %64 -%512 = OpLoad %25 %68 -OpBranch %513 -%513 = OpLabel -%514 = OpCompositeConstruct %285 %280 %280 -%515 = OpSampledImage %428 %512 %511 -%516 = OpImageSampleImplicitLod %23 %515 %514 -%517 = OpCompositeExtract %7 %516 0 -%518 = OpSampledImage %428 %512 %511 -%519 = OpImageGather %23 %518 %514 %199 -%520 = OpCompositeConstruct %23 %517 %517 %517 %517 -%521 = OpFAdd %23 %520 %519 -OpStore %509 %521 +%506 = OpFunction %2 None %79 +%504 = OpLabel +%507 = OpLoad %24 %64 +%508 = OpLoad %25 %68 +OpBranch %509 +%509 = OpLabel +%510 = OpSampledImage %425 %508 %507 +%511 = OpImageSampleImplicitLod %23 %510 %278 +%512 = OpCompositeExtract %7 %511 0 +%513 = OpSampledImage %425 %508 %507 +%514 = OpImageGather %23 %513 %278 %198 +%515 = OpCompositeConstruct %23 %512 %512 %512 %512 +%516 = OpFAdd %23 %515 %514 +OpStore %505 %516 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interface.vertex.spvasm b/tests/out/spv/interface.vertex.spvasm index d2c949296..eaa947f5b 100644 --- a/tests/out/spv/interface.vertex.spvasm +++ b/tests/out/spv/interface.vertex.spvasm @@ -45,19 +45,19 @@ OpDecorate %26 BuiltIn PointSize %26 = OpVariable %27 Output %28 = OpConstant %4 1.0 %30 = OpTypeFunction %2 +%31 = OpConstantComposite %3 %28 %28 %28 %28 %29 = OpFunction %2 None %30 %14 = OpLabel %17 = OpLoad %6 %15 %19 = OpLoad %6 %18 %21 = OpLoad %6 %20 OpStore %26 %28 -OpBranch %31 -%31 = OpLabel -%32 = OpIAdd %6 %17 %19 -%33 = OpIAdd %6 %32 %21 -%34 = OpCompositeConstruct %3 %28 %28 %28 %28 -%35 = OpConvertUToF %4 %33 -%36 = OpCompositeConstruct %5 %34 %35 +OpBranch %32 +%32 = OpLabel +%33 = OpIAdd %6 %17 %19 +%34 = OpIAdd %6 %33 %21 +%35 = OpConvertUToF %4 %34 +%36 = OpCompositeConstruct %5 %31 %35 %37 = OpCompositeExtract %3 %36 0 OpStore %22 %37 %38 = OpCompositeExtract %4 %36 1 diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/tests/out/spv/interface.vertex_two_structs.spvasm index 505c55843..bcc4aab4e 100644 --- a/tests/out/spv/interface.vertex_two_structs.spvasm +++ b/tests/out/spv/interface.vertex_two_structs.spvasm @@ -1,11 +1,11 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 42 +; Bound: 41 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %30 "vertex_two_structs" %19 %23 %25 %27 +OpEntryPoint Vertex %27 "vertex_two_structs" %16 %20 %22 %24 OpMemberDecorate %5 0 Offset 0 OpMemberDecorate %5 1 Offset 16 OpMemberDecorate %7 0 Offset 0 @@ -14,11 +14,11 @@ OpMemberDecorate %7 2 Offset 8 OpDecorate %9 ArrayStride 4 OpMemberDecorate %12 0 Offset 0 OpMemberDecorate %13 0 Offset 0 -OpDecorate %19 BuiltIn VertexIndex -OpDecorate %23 BuiltIn InstanceIndex -OpDecorate %25 Invariant -OpDecorate %25 BuiltIn Position -OpDecorate %27 BuiltIn PointSize +OpDecorate %16 BuiltIn VertexIndex +OpDecorate %20 BuiltIn InstanceIndex +OpDecorate %22 Invariant +OpDecorate %22 BuiltIn Position +OpDecorate %24 BuiltIn PointSize %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -31,37 +31,35 @@ OpDecorate %27 BuiltIn PointSize %11 = OpTypeVector %6 3 %12 = OpTypeStruct %6 %13 = OpTypeStruct %6 -%15 = OpTypePointer Function %6 -%16 = OpConstantNull %6 -%20 = OpTypePointer Input %6 -%19 = OpVariable %20 Input -%23 = OpVariable %20 Input -%26 = OpTypePointer Output %3 -%25 = OpVariable %26 Output -%28 = OpTypePointer Output %4 -%27 = OpVariable %28 Output -%29 = OpConstant %4 1.0 -%31 = OpTypeFunction %2 -%32 = OpConstant %6 2 -%33 = OpConstant %4 0.0 -%30 = OpFunction %2 None %31 -%17 = OpLabel -%14 = OpVariable %15 Function %16 -%21 = OpLoad %6 %19 -%18 = OpCompositeConstruct %12 %21 -%24 = OpLoad %6 %23 -%22 = OpCompositeConstruct %13 %24 -OpStore %27 %29 -OpBranch %34 -%34 = OpLabel -OpStore %14 %32 -%35 = OpCompositeExtract %6 %18 0 -%36 = OpConvertUToF %4 %35 -%37 = OpCompositeExtract %6 %22 0 -%38 = OpConvertUToF %4 %37 -%39 = OpLoad %6 %14 -%40 = OpConvertUToF %4 %39 -%41 = OpCompositeConstruct %3 %36 %38 %40 %33 -OpStore %25 %41 +%17 = OpTypePointer Input %6 +%16 = OpVariable %17 Input +%20 = OpVariable %17 Input +%23 = OpTypePointer Output %3 +%22 = OpVariable %23 Output +%25 = OpTypePointer Output %4 +%24 = OpVariable %25 Output +%26 = OpConstant %4 1.0 +%28 = OpTypeFunction %2 +%29 = OpConstant %6 2 +%30 = OpConstant %4 0.0 +%32 = OpTypePointer Function %6 +%27 = OpFunction %2 None %28 +%14 = OpLabel +%31 = OpVariable %32 Function %29 +%18 = OpLoad %6 %16 +%15 = OpCompositeConstruct %12 %18 +%21 = OpLoad %6 %20 +%19 = OpCompositeConstruct %13 %21 +OpStore %24 %26 +OpBranch %33 +%33 = OpLabel +%34 = OpCompositeExtract %6 %15 0 +%35 = OpConvertUToF %4 %34 +%36 = OpCompositeExtract %6 %19 0 +%37 = OpConvertUToF %4 %36 +%38 = OpLoad %6 %31 +%39 = OpConvertUToF %4 %38 +%40 = OpCompositeConstruct %3 %35 %37 %39 %30 +OpStore %22 %40 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/interpolate.spvasm b/tests/out/spv/interpolate.spvasm index bcfad15c1..d2a67a9fd 100644 --- a/tests/out/spv/interpolate.spvasm +++ b/tests/out/spv/interpolate.spvasm @@ -6,7 +6,7 @@ OpCapability Shader OpCapability SampleRateShading %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %29 "vert_main" %13 %15 %17 %19 %21 %23 %24 %25 %26 +OpEntryPoint Vertex %26 "vert_main" %10 %12 %14 %16 %18 %20 %21 %22 %23 OpEntryPoint Fragment %109 "frag_main" %88 %91 %94 %97 %100 %103 %105 %107 OpExecutionMode %109 OriginUpperLeft OpMemberName %8 0 "position" @@ -18,16 +18,16 @@ OpMemberName %8 5 "perspective" OpMemberName %8 6 "perspective_centroid" OpMemberName %8 7 "perspective_sample" OpName %8 "FragmentInput" -OpName %9 "out" -OpName %13 "position" -OpName %15 "_flat" -OpName %17 "_linear" -OpName %19 "linear_centroid" -OpName %21 "linear_sample" -OpName %23 "perspective" -OpName %24 "perspective_centroid" -OpName %25 "perspective_sample" -OpName %29 "vert_main" +OpName %10 "position" +OpName %12 "_flat" +OpName %14 "_linear" +OpName %16 "linear_centroid" +OpName %18 "linear_sample" +OpName %20 "perspective" +OpName %21 "perspective_centroid" +OpName %22 "perspective_sample" +OpName %26 "vert_main" +OpName %49 "out" OpName %88 "position" OpName %91 "_flat" OpName %94 "_linear" @@ -45,23 +45,23 @@ OpMemberDecorate %8 4 Offset 32 OpMemberDecorate %8 5 Offset 48 OpMemberDecorate %8 6 Offset 64 OpMemberDecorate %8 7 Offset 68 -OpDecorate %13 BuiltIn Position -OpDecorate %15 Location 0 -OpDecorate %15 Flat -OpDecorate %17 Location 1 -OpDecorate %17 NoPerspective -OpDecorate %19 Location 2 -OpDecorate %19 NoPerspective -OpDecorate %19 Centroid -OpDecorate %21 Location 3 -OpDecorate %21 NoPerspective -OpDecorate %21 Sample -OpDecorate %23 Location 4 -OpDecorate %24 Location 5 -OpDecorate %24 Centroid -OpDecorate %25 Location 6 -OpDecorate %25 Sample -OpDecorate %26 BuiltIn PointSize +OpDecorate %10 BuiltIn Position +OpDecorate %12 Location 0 +OpDecorate %12 Flat +OpDecorate %14 Location 1 +OpDecorate %14 NoPerspective +OpDecorate %16 Location 2 +OpDecorate %16 NoPerspective +OpDecorate %16 Centroid +OpDecorate %18 Location 3 +OpDecorate %18 NoPerspective +OpDecorate %18 Sample +OpDecorate %20 Location 4 +OpDecorate %21 Location 5 +OpDecorate %21 Centroid +OpDecorate %22 Location 6 +OpDecorate %22 Sample +OpDecorate %23 BuiltIn PointSize OpDecorate %88 BuiltIn FragCoord OpDecorate %91 Location 0 OpDecorate %91 Flat @@ -85,52 +85,56 @@ OpDecorate %107 Sample %6 = OpTypeVector %4 2 %7 = OpTypeVector %4 3 %8 = OpTypeStruct %3 %5 %4 %6 %7 %3 %4 %4 -%10 = OpTypePointer Function %8 -%11 = OpConstantNull %8 -%14 = OpTypePointer Output %3 -%13 = OpVariable %14 Output -%16 = OpTypePointer Output %5 -%15 = OpVariable %16 Output -%18 = OpTypePointer Output %4 -%17 = OpVariable %18 Output -%20 = OpTypePointer Output %6 -%19 = OpVariable %20 Output -%22 = OpTypePointer Output %7 -%21 = OpVariable %22 Output -%23 = OpVariable %14 Output -%24 = OpVariable %18 Output -%25 = OpVariable %18 Output -%27 = OpTypePointer Output %4 -%26 = OpVariable %27 Output -%28 = OpConstant %4 1.0 -%30 = OpTypeFunction %2 -%31 = OpConstant %4 2.0 -%32 = OpConstant %4 4.0 -%33 = OpConstant %4 5.0 -%34 = OpConstant %4 6.0 -%35 = OpConstant %5 8 -%36 = OpConstant %4 27.0 -%37 = OpConstant %4 64.0 -%38 = OpConstant %4 125.0 -%39 = OpConstant %4 216.0 -%40 = OpConstant %4 343.0 -%41 = OpConstant %4 512.0 +%11 = OpTypePointer Output %3 +%10 = OpVariable %11 Output +%13 = OpTypePointer Output %5 +%12 = OpVariable %13 Output +%15 = OpTypePointer Output %4 +%14 = OpVariable %15 Output +%17 = OpTypePointer Output %6 +%16 = OpVariable %17 Output +%19 = OpTypePointer Output %7 +%18 = OpVariable %19 Output +%20 = OpVariable %11 Output +%21 = OpVariable %15 Output +%22 = OpVariable %15 Output +%24 = OpTypePointer Output %4 +%23 = OpVariable %24 Output +%25 = OpConstant %4 1.0 +%27 = OpTypeFunction %2 +%28 = OpConstant %4 2.0 +%29 = OpConstant %4 4.0 +%30 = OpConstant %4 5.0 +%31 = OpConstant %4 6.0 +%32 = OpConstantComposite %3 %28 %29 %30 %31 +%33 = OpConstant %5 8 +%34 = OpConstant %4 27.0 +%35 = OpConstant %4 64.0 +%36 = OpConstant %4 125.0 +%37 = OpConstantComposite %6 %35 %36 +%38 = OpConstant %4 216.0 +%39 = OpConstant %4 343.0 +%40 = OpConstant %4 512.0 +%41 = OpConstantComposite %7 %38 %39 %40 %42 = OpConstant %4 729.0 %43 = OpConstant %4 1000.0 %44 = OpConstant %4 1331.0 %45 = OpConstant %4 1728.0 -%46 = OpConstant %4 2197.0 -%47 = OpConstant %4 2744.0 -%49 = OpTypePointer Function %3 -%51 = OpConstant %5 0 -%53 = OpTypePointer Function %5 -%54 = OpConstant %5 1 -%56 = OpTypePointer Function %4 -%57 = OpConstant %5 2 -%59 = OpTypePointer Function %6 -%61 = OpConstant %5 3 -%63 = OpTypePointer Function %7 -%65 = OpConstant %5 4 +%46 = OpConstantComposite %3 %42 %43 %44 %45 +%47 = OpConstant %4 2197.0 +%48 = OpConstant %4 2744.0 +%50 = OpTypePointer Function %8 +%51 = OpConstantNull %8 +%53 = OpTypePointer Function %3 +%54 = OpConstant %5 0 +%56 = OpTypePointer Function %5 +%57 = OpConstant %5 1 +%59 = OpTypePointer Function %4 +%60 = OpConstant %5 2 +%62 = OpTypePointer Function %6 +%63 = OpConstant %5 3 +%65 = OpTypePointer Function %7 +%66 = OpConstant %5 4 %68 = OpConstant %5 5 %70 = OpConstant %5 6 %72 = OpConstant %5 7 @@ -147,56 +151,52 @@ OpDecorate %107 Sample %103 = OpVariable %89 Input %105 = OpVariable %95 Input %107 = OpVariable %95 Input -%29 = OpFunction %2 None %30 -%12 = OpLabel -%9 = OpVariable %10 Function %11 -OpStore %26 %28 -OpBranch %48 -%48 = OpLabel -%50 = OpCompositeConstruct %3 %31 %32 %33 %34 -%52 = OpAccessChain %49 %9 %51 -OpStore %52 %50 -%55 = OpAccessChain %53 %9 %54 -OpStore %55 %35 -%58 = OpAccessChain %56 %9 %57 -OpStore %58 %36 -%60 = OpCompositeConstruct %6 %37 %38 -%62 = OpAccessChain %59 %9 %61 -OpStore %62 %60 -%64 = OpCompositeConstruct %7 %39 %40 %41 -%66 = OpAccessChain %63 %9 %65 -OpStore %66 %64 -%67 = OpCompositeConstruct %3 %42 %43 %44 %45 -%69 = OpAccessChain %49 %9 %68 -OpStore %69 %67 -%71 = OpAccessChain %56 %9 %70 -OpStore %71 %46 -%73 = OpAccessChain %56 %9 %72 -OpStore %73 %47 -%74 = OpLoad %8 %9 +%26 = OpFunction %2 None %27 +%9 = OpLabel +%49 = OpVariable %50 Function %51 +OpStore %23 %25 +OpBranch %52 +%52 = OpLabel +%55 = OpAccessChain %53 %49 %54 +OpStore %55 %32 +%58 = OpAccessChain %56 %49 %57 +OpStore %58 %33 +%61 = OpAccessChain %59 %49 %60 +OpStore %61 %34 +%64 = OpAccessChain %62 %49 %63 +OpStore %64 %37 +%67 = OpAccessChain %65 %49 %66 +OpStore %67 %41 +%69 = OpAccessChain %53 %49 %68 +OpStore %69 %46 +%71 = OpAccessChain %59 %49 %70 +OpStore %71 %47 +%73 = OpAccessChain %59 %49 %72 +OpStore %73 %48 +%74 = OpLoad %8 %49 %75 = OpCompositeExtract %3 %74 0 -OpStore %13 %75 -%76 = OpAccessChain %27 %13 %54 +OpStore %10 %75 +%76 = OpAccessChain %24 %10 %57 %77 = OpLoad %4 %76 %78 = OpFNegate %4 %77 OpStore %76 %78 %79 = OpCompositeExtract %5 %74 1 -OpStore %15 %79 +OpStore %12 %79 %80 = OpCompositeExtract %4 %74 2 -OpStore %17 %80 +OpStore %14 %80 %81 = OpCompositeExtract %6 %74 3 -OpStore %19 %81 +OpStore %16 %81 %82 = OpCompositeExtract %7 %74 4 -OpStore %21 %82 +OpStore %18 %82 %83 = OpCompositeExtract %3 %74 5 -OpStore %23 %83 +OpStore %20 %83 %84 = OpCompositeExtract %4 %74 6 -OpStore %24 %84 +OpStore %21 %84 %85 = OpCompositeExtract %4 %74 7 -OpStore %25 %85 +OpStore %22 %85 OpReturn OpFunctionEnd -%109 = OpFunction %2 None %30 +%109 = OpFunction %2 None %27 %86 = OpLabel %90 = OpLoad %3 %88 %93 = OpLoad %5 %91 diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm index 7edb0e26b..ba3e7cffb 100644 --- a/tests/out/spv/math-functions.spvasm +++ b/tests/out/spv/math-functions.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 134 +; Bound: 126 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -32,123 +32,115 @@ OpMemberDecorate %13 1 Offset 16 %16 = OpTypeFunction %2 %17 = OpConstant %4 1.0 %18 = OpConstant %4 0.0 -%19 = OpConstant %6 -1 -%20 = OpConstant %4 -1.0 -%21 = OpConstantNull %5 -%22 = OpTypeInt 32 0 -%23 = OpConstant %22 0 -%24 = OpConstant %22 1 -%25 = OpConstant %6 0 -%26 = OpConstant %22 4294967295 -%27 = OpConstant %6 1 -%28 = OpConstant %6 2 -%29 = OpConstant %4 2.0 -%30 = OpConstant %6 3 -%31 = OpConstant %6 4 -%32 = OpConstant %4 1.5 -%40 = OpConstantComposite %3 %18 %18 %18 %18 -%41 = OpConstantComposite %3 %17 %17 %17 %17 -%50 = OpConstantNull %6 -%63 = OpTypeVector %22 2 -%73 = OpConstant %22 32 -%83 = OpConstantComposite %63 %73 %73 +%19 = OpConstantComposite %3 %18 %18 %18 %18 +%20 = OpConstant %6 -1 +%21 = OpConstantComposite %12 %20 %20 %20 %20 +%22 = OpConstant %4 -1.0 +%23 = OpConstantComposite %3 %22 %22 %22 %22 +%24 = OpConstantNull %5 +%25 = OpTypeInt 32 0 +%26 = OpConstant %25 0 +%27 = OpConstantComposite %5 %20 %20 +%28 = OpConstant %25 1 +%29 = OpTypeVector %25 2 +%30 = OpConstantComposite %29 %28 %28 +%31 = OpConstant %6 0 +%32 = OpConstant %25 4294967295 +%33 = OpConstantComposite %29 %26 %26 +%34 = OpConstantComposite %5 %31 %31 +%35 = OpConstant %6 1 +%36 = OpConstantComposite %5 %35 %35 +%37 = OpConstant %6 2 +%38 = OpConstant %4 2.0 +%39 = OpConstantComposite %7 %17 %38 +%40 = OpConstant %6 3 +%41 = OpConstant %6 4 +%42 = OpConstantComposite %5 %40 %41 +%43 = OpConstant %4 1.5 +%44 = OpConstantComposite %7 %43 %43 +%45 = OpConstantComposite %3 %43 %43 %43 %43 +%52 = OpConstantComposite %3 %17 %17 %17 %17 +%59 = OpConstantNull %6 +%77 = OpConstant %25 32 +%86 = OpConstantComposite %29 %77 %77 %95 = OpConstant %6 31 -%101 = OpConstantComposite %5 %95 %95 +%100 = OpConstantComposite %5 %95 %95 %15 = OpFunction %2 None %16 %14 = OpLabel -OpBranch %33 -%33 = OpLabel -%34 = OpCompositeConstruct %3 %18 %18 %18 %18 -%35 = OpExtInst %4 %1 Degrees %17 -%36 = OpExtInst %4 %1 Radians %17 -%37 = OpExtInst %3 %1 Degrees %34 -%38 = OpExtInst %3 %1 Radians %34 -%39 = OpExtInst %3 %1 FClamp %34 %40 %41 -%42 = OpExtInst %3 %1 Refract %34 %34 %17 -%43 = OpExtInst %6 %1 SSign %19 -%44 = OpCompositeConstruct %12 %19 %19 %19 %19 -%45 = OpExtInst %12 %1 SSign %44 -%46 = OpExtInst %4 %1 FSign %20 -%47 = OpCompositeConstruct %3 %20 %20 %20 %20 -%48 = OpExtInst %3 %1 FSign %47 -%51 = OpCompositeExtract %6 %21 0 -%52 = OpCompositeExtract %6 %21 0 -%53 = OpIMul %6 %51 %52 -%54 = OpIAdd %6 %50 %53 -%55 = OpCompositeExtract %6 %21 1 -%56 = OpCompositeExtract %6 %21 1 -%57 = OpIMul %6 %55 %56 -%49 = OpIAdd %6 %54 %57 -%58 = OpCopyObject %22 %23 -%59 = OpExtInst %22 %1 FindUMsb %58 -%60 = OpExtInst %6 %1 FindSMsb %19 -%61 = OpCompositeConstruct %5 %19 %19 -%62 = OpExtInst %5 %1 FindSMsb %61 -%64 = OpCompositeConstruct %63 %24 %24 -%65 = OpExtInst %63 %1 FindUMsb %64 -%66 = OpExtInst %6 %1 FindILsb %19 -%67 = OpExtInst %22 %1 FindILsb %24 -%68 = OpCompositeConstruct %5 %19 %19 -%69 = OpExtInst %5 %1 FindILsb %68 -%70 = OpCompositeConstruct %63 %24 %24 -%71 = OpExtInst %63 %1 FindILsb %70 -%74 = OpExtInst %22 %1 FindILsb %23 -%72 = OpExtInst %22 %1 UMin %73 %74 -%76 = OpExtInst %6 %1 FindILsb %25 -%75 = OpExtInst %6 %1 UMin %73 %76 -%78 = OpExtInst %22 %1 FindILsb %26 -%77 = OpExtInst %22 %1 UMin %73 %78 -%80 = OpExtInst %6 %1 FindILsb %19 -%79 = OpExtInst %6 %1 UMin %73 %80 -%81 = OpCompositeConstruct %63 %23 %23 -%84 = OpExtInst %63 %1 FindILsb %81 -%82 = OpExtInst %63 %1 UMin %83 %84 -%85 = OpCompositeConstruct %5 %25 %25 -%87 = OpExtInst %5 %1 FindILsb %85 -%86 = OpExtInst %5 %1 UMin %83 %87 -%88 = OpCompositeConstruct %63 %24 %24 -%90 = OpExtInst %63 %1 FindILsb %88 -%89 = OpExtInst %63 %1 UMin %83 %90 -%91 = OpCompositeConstruct %5 %27 %27 -%93 = OpExtInst %5 %1 FindILsb %91 -%92 = OpExtInst %5 %1 UMin %83 %93 -%96 = OpExtInst %6 %1 FindUMsb %19 +OpBranch %46 +%46 = OpLabel +%47 = OpExtInst %4 %1 Degrees %17 +%48 = OpExtInst %4 %1 Radians %17 +%49 = OpExtInst %3 %1 Degrees %19 +%50 = OpExtInst %3 %1 Radians %19 +%51 = OpExtInst %3 %1 FClamp %19 %19 %52 +%53 = OpExtInst %3 %1 Refract %19 %19 %17 +%54 = OpExtInst %6 %1 SSign %20 +%55 = OpExtInst %12 %1 SSign %21 +%56 = OpExtInst %4 %1 FSign %22 +%57 = OpExtInst %3 %1 FSign %23 +%60 = OpCompositeExtract %6 %24 0 +%61 = OpCompositeExtract %6 %24 0 +%62 = OpIMul %6 %60 %61 +%63 = OpIAdd %6 %59 %62 +%64 = OpCompositeExtract %6 %24 1 +%65 = OpCompositeExtract %6 %24 1 +%66 = OpIMul %6 %64 %65 +%58 = OpIAdd %6 %63 %66 +%67 = OpCopyObject %25 %26 +%68 = OpExtInst %25 %1 FindUMsb %67 +%69 = OpExtInst %6 %1 FindSMsb %20 +%70 = OpExtInst %5 %1 FindSMsb %27 +%71 = OpExtInst %29 %1 FindUMsb %30 +%72 = OpExtInst %6 %1 FindILsb %20 +%73 = OpExtInst %25 %1 FindILsb %28 +%74 = OpExtInst %5 %1 FindILsb %27 +%75 = OpExtInst %29 %1 FindILsb %30 +%78 = OpExtInst %25 %1 FindILsb %26 +%76 = OpExtInst %25 %1 UMin %77 %78 +%80 = OpExtInst %6 %1 FindILsb %31 +%79 = OpExtInst %6 %1 UMin %77 %80 +%82 = OpExtInst %25 %1 FindILsb %32 +%81 = OpExtInst %25 %1 UMin %77 %82 +%84 = OpExtInst %6 %1 FindILsb %20 +%83 = OpExtInst %6 %1 UMin %77 %84 +%87 = OpExtInst %29 %1 FindILsb %33 +%85 = OpExtInst %29 %1 UMin %86 %87 +%89 = OpExtInst %5 %1 FindILsb %34 +%88 = OpExtInst %5 %1 UMin %86 %89 +%91 = OpExtInst %29 %1 FindILsb %30 +%90 = OpExtInst %29 %1 UMin %86 %91 +%93 = OpExtInst %5 %1 FindILsb %36 +%92 = OpExtInst %5 %1 UMin %86 %93 +%96 = OpExtInst %6 %1 FindUMsb %20 %94 = OpISub %6 %95 %96 -%98 = OpExtInst %6 %1 FindUMsb %24 -%97 = OpISub %22 %95 %98 -%99 = OpCompositeConstruct %5 %19 %19 -%102 = OpExtInst %5 %1 FindUMsb %99 -%100 = OpISub %5 %101 %102 -%103 = OpCompositeConstruct %63 %24 %24 -%105 = OpExtInst %5 %1 FindUMsb %103 -%104 = OpISub %63 %101 %105 -%106 = OpExtInst %4 %1 Ldexp %17 %28 -%107 = OpCompositeConstruct %7 %17 %29 -%108 = OpCompositeConstruct %5 %30 %31 -%109 = OpExtInst %7 %1 Ldexp %107 %108 -%110 = OpExtInst %8 %1 ModfStruct %32 -%111 = OpExtInst %8 %1 ModfStruct %32 -%112 = OpCompositeExtract %4 %111 0 -%113 = OpExtInst %8 %1 ModfStruct %32 -%114 = OpCompositeExtract %4 %113 1 -%115 = OpCompositeConstruct %7 %32 %32 -%116 = OpExtInst %9 %1 ModfStruct %115 -%117 = OpCompositeConstruct %3 %32 %32 %32 %32 -%118 = OpExtInst %10 %1 ModfStruct %117 -%119 = OpCompositeExtract %3 %118 1 +%98 = OpExtInst %6 %1 FindUMsb %28 +%97 = OpISub %25 %95 %98 +%101 = OpExtInst %5 %1 FindUMsb %27 +%99 = OpISub %5 %100 %101 +%103 = OpExtInst %5 %1 FindUMsb %30 +%102 = OpISub %29 %100 %103 +%104 = OpExtInst %4 %1 Ldexp %17 %37 +%105 = OpExtInst %7 %1 Ldexp %39 %42 +%106 = OpExtInst %8 %1 ModfStruct %43 +%107 = OpExtInst %8 %1 ModfStruct %43 +%108 = OpCompositeExtract %4 %107 0 +%109 = OpExtInst %8 %1 ModfStruct %43 +%110 = OpCompositeExtract %4 %109 1 +%111 = OpExtInst %9 %1 ModfStruct %44 +%112 = OpExtInst %10 %1 ModfStruct %45 +%113 = OpCompositeExtract %3 %112 1 +%114 = OpCompositeExtract %4 %113 0 +%115 = OpExtInst %9 %1 ModfStruct %44 +%116 = OpCompositeExtract %7 %115 0 +%117 = OpCompositeExtract %4 %116 1 +%118 = OpExtInst %11 %1 FrexpStruct %43 +%119 = OpExtInst %11 %1 FrexpStruct %43 %120 = OpCompositeExtract %4 %119 0 -%121 = OpCompositeConstruct %7 %32 %32 -%122 = OpExtInst %9 %1 ModfStruct %121 -%123 = OpCompositeExtract %7 %122 0 -%124 = OpCompositeExtract %4 %123 1 -%125 = OpExtInst %11 %1 FrexpStruct %32 -%126 = OpExtInst %11 %1 FrexpStruct %32 -%127 = OpCompositeExtract %4 %126 0 -%128 = OpExtInst %11 %1 FrexpStruct %32 -%129 = OpCompositeExtract %6 %128 1 -%130 = OpCompositeConstruct %3 %32 %32 %32 %32 -%131 = OpExtInst %13 %1 FrexpStruct %130 -%132 = OpCompositeExtract %12 %131 1 -%133 = OpCompositeExtract %6 %132 0 +%121 = OpExtInst %11 %1 FrexpStruct %43 +%122 = OpCompositeExtract %6 %121 1 +%123 = OpExtInst %13 %1 FrexpStruct %45 +%124 = OpCompositeExtract %12 %123 1 +%125 = OpCompositeExtract %6 %124 0 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 5e2125b72..538c080e3 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 450 +; Bound: 308 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %439 "main" -OpExecutionMode %439 LocalSize 1 1 1 +OpEntryPoint GLCompute %297 "main" +OpExecutionMode %297 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -37,476 +37,331 @@ OpExecutionMode %439 LocalSize 1 1 1 %31 = OpConstantTrue %8 %32 = OpConstant %6 0 %33 = OpConstantFalse %8 -%34 = OpConstant %4 0.1 +%34 = OpConstantComposite %7 %33 %33 %33 %33 +%35 = OpConstant %4 0.1 +%36 = OpConstantComposite %5 %32 %32 %32 %32 %58 = OpConstant %4 2.0 -%59 = OpConstant %4 3.0 -%60 = OpConstant %4 4.0 -%61 = OpConstant %6 5 -%62 = OpConstant %6 2 -%78 = OpTypePointer Function %9 -%79 = OpConstantNull %9 -%82 = OpTypeFunction %9 -%98 = OpTypeFunction %10 %10 -%100 = OpTypeVector %8 3 -%101 = OpConstantComposite %10 %22 %22 %22 -%103 = OpConstantComposite %10 %20 %20 %20 -%107 = OpTypeFunction %2 -%120 = OpConstant %4 -1.0 -%121 = OpConstant %6 -1 -%122 = OpConstant %6 3 -%123 = OpConstant %14 3 -%124 = OpConstant %14 2 +%59 = OpConstantComposite %9 %58 %58 +%60 = OpConstantComposite %9 %20 %20 +%61 = OpConstant %4 3.0 +%62 = OpConstantComposite %9 %61 %61 +%63 = OpConstant %4 4.0 +%64 = OpConstantComposite %9 %63 %63 +%65 = OpConstant %6 5 +%66 = OpConstantComposite %5 %65 %65 %65 %65 +%67 = OpConstant %6 2 +%68 = OpConstantComposite %5 %67 %67 %67 %67 +%79 = OpTypeFunction %9 +%81 = OpTypePointer Function %9 +%93 = OpTypeFunction %10 %10 +%95 = OpTypeVector %8 3 +%96 = OpConstantComposite %10 %22 %22 %22 +%98 = OpConstantComposite %10 %20 %20 %20 +%102 = OpTypeFunction %2 +%103 = OpConstantComposite %11 %33 %33 +%104 = OpConstantComposite %95 %31 %31 %31 +%105 = OpConstantComposite %95 %33 %33 %33 +%106 = OpConstantComposite %7 %31 %31 %31 %31 +%107 = OpConstantComposite %7 %33 %33 %33 %33 +%115 = OpConstant %4 -1.0 +%116 = OpConstant %6 -1 +%117 = OpConstantComposite %12 %116 %116 +%118 = OpConstantComposite %9 %115 %115 +%119 = OpConstant %6 3 +%120 = OpConstant %14 3 +%121 = OpConstantComposite %12 %67 %67 +%122 = OpConstantComposite %12 %26 %26 +%123 = OpConstant %14 2 +%124 = OpConstantComposite %13 %123 %123 %123 %125 = OpConstant %14 1 -%126 = OpConstant %14 0 -%127 = OpConstantNull %16 -%128 = OpConstantNull %17 -%129 = OpConstantNull %18 -%293 = OpConstant %6 -2 -%294 = OpConstant %14 4294967294 -%295 = OpConstant %6 4 -%296 = OpConstant %14 4 -%388 = OpTypePointer Function %6 -%389 = OpConstantNull %6 -%391 = OpTypePointer Function %19 -%392 = OpConstantNull %19 -%422 = OpTypePointer Function %6 -%433 = OpConstant %6 -5 -%434 = OpConstant %6 6 -%435 = OpConstant %6 -7 -%436 = OpConstant %6 -8 +%126 = OpConstantComposite %13 %125 %125 %125 +%127 = OpConstantComposite %3 %58 %58 %58 %58 +%128 = OpConstantComposite %3 %20 %20 %20 %20 +%129 = OpConstant %14 0 +%130 = OpConstantComposite %15 %123 %123 +%131 = OpConstantComposite %15 %125 %125 +%132 = OpConstantComposite %12 %67 %67 +%133 = OpConstantComposite %15 %123 %123 +%134 = OpConstantComposite %9 %58 %58 +%135 = OpConstantNull %16 +%136 = OpConstantComposite %10 %22 %22 %22 +%137 = OpConstantComposite %16 %136 %136 %136 +%138 = OpConstantNull %17 +%139 = OpConstantComposite %10 %58 %58 %58 +%140 = OpConstantNull %18 +%208 = OpConstant %6 -2 +%209 = OpConstant %14 4294967294 +%210 = OpConstantComposite %12 %208 %208 +%211 = OpConstantComposite %13 %209 %209 %209 +%212 = OpConstant %6 4 +%213 = OpConstant %14 4 +%248 = OpConstantNull %19 +%250 = OpTypePointer Function %6 +%252 = OpTypePointer Function %19 +%280 = OpTypePointer Function %6 +%291 = OpConstant %6 -5 +%292 = OpConstant %6 6 +%293 = OpConstant %6 -7 +%294 = OpConstant %6 -8 +%298 = OpConstantComposite %10 %20 %20 %20 %29 = OpFunction %3 None %30 %28 = OpLabel -OpBranch %35 -%35 = OpLabel -%36 = OpSelect %6 %31 %26 %32 -%38 = OpCompositeConstruct %7 %31 %31 %31 %31 -%37 = OpSelect %3 %38 %21 %23 -%39 = OpCompositeConstruct %7 %33 %33 %33 %33 -%40 = OpSelect %3 %39 %23 %21 -%41 = OpExtInst %3 %1 FMix %23 %21 %25 -%43 = OpCompositeConstruct %3 %34 %34 %34 %34 -%42 = OpExtInst %3 %1 FMix %23 %21 %43 -%44 = OpBitcast %4 %26 -%45 = OpBitcast %3 %27 -%46 = OpCompositeConstruct %5 %32 %32 %32 %32 -%47 = OpCompositeConstruct %5 %36 %36 %36 %36 -%48 = OpIAdd %5 %47 %46 +OpBranch %37 +%37 = OpLabel +%38 = OpSelect %6 %31 %26 %32 +%40 = OpCompositeConstruct %7 %31 %31 %31 %31 +%39 = OpSelect %3 %40 %21 %23 +%41 = OpSelect %3 %34 %23 %21 +%42 = OpExtInst %3 %1 FMix %23 %21 %25 +%44 = OpCompositeConstruct %3 %35 %35 %35 %35 +%43 = OpExtInst %3 %1 FMix %23 %21 %44 +%45 = OpBitcast %4 %26 +%46 = OpBitcast %3 %27 +%47 = OpCompositeConstruct %5 %38 %38 %38 %38 +%48 = OpIAdd %5 %47 %36 %49 = OpConvertSToF %3 %48 -%50 = OpFAdd %3 %49 %37 -%51 = OpFAdd %3 %50 %41 -%52 = OpFAdd %3 %51 %42 -%53 = OpCompositeConstruct %3 %44 %44 %44 %44 +%50 = OpFAdd %3 %49 %39 +%51 = OpFAdd %3 %50 %42 +%52 = OpFAdd %3 %51 %43 +%53 = OpCompositeConstruct %3 %45 %45 %45 %45 %54 = OpFAdd %3 %52 %53 -%55 = OpFAdd %3 %54 %45 +%55 = OpFAdd %3 %54 %46 OpReturnValue %55 OpFunctionEnd %57 = OpFunction %3 None %30 %56 = OpLabel -OpBranch %63 -%63 = OpLabel -%64 = OpCompositeConstruct %9 %58 %58 -%65 = OpCompositeConstruct %9 %20 %20 -%66 = OpFAdd %9 %65 %64 -%67 = OpCompositeConstruct %9 %59 %59 -%68 = OpFSub %9 %66 %67 -%69 = OpCompositeConstruct %9 %60 %60 -%70 = OpFDiv %9 %68 %69 -%71 = OpCompositeConstruct %5 %61 %61 %61 %61 -%72 = OpCompositeConstruct %5 %62 %62 %62 %62 -%73 = OpSRem %5 %71 %72 -%74 = OpVectorShuffle %3 %70 %70 0 1 0 1 +OpBranch %69 +%69 = OpLabel +%70 = OpFAdd %9 %60 %59 +%71 = OpFSub %9 %70 %62 +%72 = OpFDiv %9 %71 %64 +%73 = OpSRem %5 %66 %68 +%74 = OpVectorShuffle %3 %72 %72 0 1 0 1 %75 = OpConvertSToF %3 %73 %76 = OpFAdd %3 %74 %75 OpReturnValue %76 OpFunctionEnd -%81 = OpFunction %9 None %82 -%80 = OpLabel -%77 = OpVariable %78 Function %79 -OpBranch %83 -%83 = OpLabel -%84 = OpCompositeConstruct %9 %58 %58 -OpStore %77 %84 -%85 = OpLoad %9 %77 -%86 = OpCompositeConstruct %9 %20 %20 -%87 = OpFAdd %9 %85 %86 -OpStore %77 %87 -%88 = OpLoad %9 %77 -%89 = OpCompositeConstruct %9 %59 %59 -%90 = OpFSub %9 %88 %89 -OpStore %77 %90 -%91 = OpLoad %9 %77 -%92 = OpCompositeConstruct %9 %60 %60 -%93 = OpFDiv %9 %91 %92 -OpStore %77 %93 -%94 = OpLoad %9 %77 -OpReturnValue %94 +%78 = OpFunction %9 None %79 +%77 = OpLabel +%80 = OpVariable %81 Function %59 +OpBranch %82 +%82 = OpLabel +%83 = OpLoad %9 %80 +%84 = OpFAdd %9 %83 %60 +OpStore %80 %84 +%85 = OpLoad %9 %80 +%86 = OpFSub %9 %85 %62 +OpStore %80 %86 +%87 = OpLoad %9 %80 +%88 = OpFDiv %9 %87 %64 +OpStore %80 %88 +%89 = OpLoad %9 %80 +OpReturnValue %89 OpFunctionEnd -%97 = OpFunction %10 None %98 -%96 = OpFunctionParameter %10 -%95 = OpLabel -OpBranch %99 -%99 = OpLabel -%102 = OpFUnordNotEqual %100 %96 %101 -%104 = OpSelect %10 %102 %103 %101 -OpReturnValue %104 +%92 = OpFunction %10 None %93 +%91 = OpFunctionParameter %10 +%90 = OpLabel +OpBranch %94 +%94 = OpLabel +%97 = OpFUnordNotEqual %95 %91 %96 +%99 = OpSelect %10 %97 %98 %96 +OpReturnValue %99 OpFunctionEnd -%106 = OpFunction %2 None %107 -%105 = OpLabel +%101 = OpFunction %2 None %102 +%100 = OpLabel OpBranch %108 %108 = OpLabel -%109 = OpCompositeConstruct %11 %33 %33 -%110 = OpLogicalOr %8 %31 %33 -%111 = OpCompositeConstruct %100 %31 %31 %31 -%112 = OpCompositeConstruct %100 %33 %33 %33 -%113 = OpLogicalOr %100 %111 %112 -%114 = OpLogicalAnd %8 %31 %33 -%115 = OpCompositeConstruct %7 %31 %31 %31 %31 -%116 = OpCompositeConstruct %7 %33 %33 %33 %33 -%117 = OpLogicalAnd %7 %115 %116 +%109 = OpLogicalOr %8 %31 %33 +%110 = OpLogicalOr %95 %104 %105 +%111 = OpLogicalAnd %8 %31 %33 +%112 = OpLogicalAnd %7 %106 %107 OpReturn OpFunctionEnd -%119 = OpFunction %2 None %107 -%118 = OpLabel -OpBranch %130 -%130 = OpLabel -%131 = OpCompositeConstruct %12 %121 %121 -%132 = OpCompositeConstruct %9 %120 %120 -%133 = OpCompositeConstruct %12 %62 %62 -%134 = OpCompositeConstruct %12 %26 %26 -%135 = OpIAdd %12 %133 %134 -%136 = OpCompositeConstruct %13 %124 %124 %124 -%137 = OpCompositeConstruct %13 %125 %125 %125 -%138 = OpIAdd %13 %136 %137 -%139 = OpCompositeConstruct %3 %58 %58 %58 %58 -%140 = OpCompositeConstruct %3 %20 %20 %20 %20 -%141 = OpFAdd %3 %139 %140 -%142 = OpCompositeConstruct %12 %62 %62 -%143 = OpCompositeConstruct %12 %26 %26 -%144 = OpISub %12 %142 %143 -%145 = OpCompositeConstruct %13 %124 %124 %124 -%146 = OpCompositeConstruct %13 %125 %125 %125 -%147 = OpISub %13 %145 %146 -%148 = OpCompositeConstruct %3 %58 %58 %58 %58 -%149 = OpCompositeConstruct %3 %20 %20 %20 %20 -%150 = OpFSub %3 %148 %149 -%151 = OpCompositeConstruct %12 %62 %62 -%152 = OpCompositeConstruct %12 %26 %26 -%153 = OpIMul %12 %151 %152 -%154 = OpCompositeConstruct %13 %124 %124 %124 -%155 = OpCompositeConstruct %13 %125 %125 %125 -%156 = OpIMul %13 %154 %155 -%157 = OpCompositeConstruct %3 %58 %58 %58 %58 -%158 = OpCompositeConstruct %3 %20 %20 %20 %20 -%159 = OpFMul %3 %157 %158 -%160 = OpCompositeConstruct %12 %62 %62 -%161 = OpCompositeConstruct %12 %26 %26 -%162 = OpSDiv %12 %160 %161 -%163 = OpCompositeConstruct %13 %124 %124 %124 -%164 = OpCompositeConstruct %13 %125 %125 %125 -%165 = OpUDiv %13 %163 %164 -%166 = OpCompositeConstruct %3 %58 %58 %58 %58 -%167 = OpCompositeConstruct %3 %20 %20 %20 %20 -%168 = OpFDiv %3 %166 %167 -%169 = OpCompositeConstruct %12 %62 %62 -%170 = OpCompositeConstruct %12 %26 %26 -%171 = OpSRem %12 %169 %170 -%172 = OpCompositeConstruct %13 %124 %124 %124 -%173 = OpCompositeConstruct %13 %125 %125 %125 -%174 = OpUMod %13 %172 %173 -%175 = OpCompositeConstruct %3 %58 %58 %58 %58 -%176 = OpCompositeConstruct %3 %20 %20 %20 %20 -%177 = OpFRem %3 %175 %176 -OpBranch %178 -%178 = OpLabel -%180 = OpCompositeConstruct %12 %62 %62 -%181 = OpCompositeConstruct %12 %26 %26 -%182 = OpIAdd %12 %180 %181 -%183 = OpCompositeConstruct %12 %26 %26 -%184 = OpCompositeConstruct %12 %62 %62 -%185 = OpIAdd %12 %184 %183 -%186 = OpCompositeConstruct %15 %124 %124 -%187 = OpCompositeConstruct %15 %125 %125 -%188 = OpIAdd %15 %186 %187 -%189 = OpCompositeConstruct %15 %125 %125 -%190 = OpCompositeConstruct %15 %124 %124 -%191 = OpIAdd %15 %190 %189 -%192 = OpCompositeConstruct %9 %58 %58 -%193 = OpCompositeConstruct %9 %20 %20 -%194 = OpFAdd %9 %192 %193 -%195 = OpCompositeConstruct %9 %20 %20 -%196 = OpCompositeConstruct %9 %58 %58 -%197 = OpFAdd %9 %196 %195 -%198 = OpCompositeConstruct %12 %62 %62 -%199 = OpCompositeConstruct %12 %26 %26 -%200 = OpISub %12 %198 %199 -%201 = OpCompositeConstruct %12 %26 %26 -%202 = OpCompositeConstruct %12 %62 %62 -%203 = OpISub %12 %202 %201 -%204 = OpCompositeConstruct %15 %124 %124 -%205 = OpCompositeConstruct %15 %125 %125 -%206 = OpISub %15 %204 %205 -%207 = OpCompositeConstruct %15 %125 %125 -%208 = OpCompositeConstruct %15 %124 %124 -%209 = OpISub %15 %208 %207 -%210 = OpCompositeConstruct %9 %58 %58 -%211 = OpCompositeConstruct %9 %20 %20 -%212 = OpFSub %9 %210 %211 -%213 = OpCompositeConstruct %9 %20 %20 -%214 = OpCompositeConstruct %9 %58 %58 -%215 = OpFSub %9 %214 %213 -%216 = OpCompositeConstruct %12 %62 %62 -%217 = OpCompositeConstruct %12 %62 %62 -%218 = OpCompositeConstruct %15 %124 %124 -%219 = OpCompositeConstruct %15 %124 %124 -%220 = OpCompositeConstruct %9 %58 %58 -%221 = OpCompositeConstruct %9 %58 %58 -%222 = OpCompositeConstruct %12 %62 %62 -%223 = OpCompositeConstruct %12 %26 %26 -%224 = OpSDiv %12 %222 %223 -%225 = OpCompositeConstruct %12 %26 %26 -%226 = OpCompositeConstruct %12 %62 %62 -%227 = OpSDiv %12 %226 %225 -%228 = OpCompositeConstruct %15 %124 %124 -%229 = OpCompositeConstruct %15 %125 %125 -%230 = OpUDiv %15 %228 %229 -%231 = OpCompositeConstruct %15 %125 %125 -%232 = OpCompositeConstruct %15 %124 %124 -%233 = OpUDiv %15 %232 %231 -%234 = OpCompositeConstruct %9 %58 %58 -%235 = OpCompositeConstruct %9 %20 %20 -%236 = OpFDiv %9 %234 %235 -%237 = OpCompositeConstruct %9 %20 %20 -%238 = OpCompositeConstruct %9 %58 %58 -%239 = OpFDiv %9 %238 %237 -%240 = OpCompositeConstruct %12 %62 %62 -%241 = OpCompositeConstruct %12 %26 %26 -%242 = OpSRem %12 %240 %241 -%243 = OpCompositeConstruct %12 %26 %26 -%244 = OpCompositeConstruct %12 %62 %62 -%245 = OpSRem %12 %244 %243 -%246 = OpCompositeConstruct %15 %124 %124 -%247 = OpCompositeConstruct %15 %125 %125 -%248 = OpUMod %15 %246 %247 -%249 = OpCompositeConstruct %15 %125 %125 -%250 = OpCompositeConstruct %15 %124 %124 -%251 = OpUMod %15 %250 %249 -%252 = OpCompositeConstruct %9 %58 %58 -%253 = OpCompositeConstruct %9 %20 %20 -%254 = OpFRem %9 %252 %253 -%255 = OpCompositeConstruct %9 %20 %20 -%256 = OpCompositeConstruct %9 %58 %58 -%257 = OpFRem %9 %256 %255 -OpBranch %179 -%179 = OpLabel -%259 = OpCompositeExtract %10 %127 0 -%260 = OpCompositeExtract %10 %127 0 -%261 = OpFAdd %10 %259 %260 -%262 = OpCompositeExtract %10 %127 1 -%263 = OpCompositeExtract %10 %127 1 -%264 = OpFAdd %10 %262 %263 -%265 = OpCompositeExtract %10 %127 2 -%266 = OpCompositeExtract %10 %127 2 -%267 = OpFAdd %10 %265 %266 -%258 = OpCompositeConstruct %16 %261 %264 %267 -%269 = OpCompositeExtract %10 %127 0 -%270 = OpCompositeExtract %10 %127 0 -%271 = OpFSub %10 %269 %270 -%272 = OpCompositeExtract %10 %127 1 -%273 = OpCompositeExtract %10 %127 1 -%274 = OpFSub %10 %272 %273 -%275 = OpCompositeExtract %10 %127 2 -%276 = OpCompositeExtract %10 %127 2 -%277 = OpFSub %10 %275 %276 -%268 = OpCompositeConstruct %16 %271 %274 %277 -%278 = OpCompositeConstruct %10 %22 %22 %22 -%279 = OpCompositeConstruct %10 %22 %22 %22 -%280 = OpCompositeConstruct %10 %22 %22 %22 -%281 = OpCompositeConstruct %16 %278 %279 %280 -%282 = OpCompositeConstruct %10 %22 %22 %22 -%283 = OpCompositeConstruct %10 %22 %22 %22 -%284 = OpCompositeConstruct %10 %22 %22 %22 -%285 = OpCompositeConstruct %16 %282 %283 %284 -%286 = OpCompositeConstruct %3 %20 %20 %20 %20 -%287 = OpMatrixTimesVector %10 %128 %286 -%288 = OpCompositeConstruct %10 %58 %58 %58 -%289 = OpVectorTimesMatrix %3 %288 %128 -%290 = OpMatrixTimesMatrix %16 %128 %129 +%114 = OpFunction %2 None %102 +%113 = OpLabel +OpBranch %141 +%141 = OpLabel +%142 = OpIAdd %12 %121 %122 +%143 = OpIAdd %13 %124 %126 +%144 = OpFAdd %3 %127 %128 +%145 = OpISub %12 %121 %122 +%146 = OpISub %13 %124 %126 +%147 = OpFSub %3 %127 %128 +%148 = OpIMul %12 %121 %122 +%149 = OpIMul %13 %124 %126 +%150 = OpFMul %3 %127 %128 +%151 = OpSDiv %12 %121 %122 +%152 = OpUDiv %13 %124 %126 +%153 = OpFDiv %3 %127 %128 +%154 = OpSRem %12 %121 %122 +%155 = OpUMod %13 %124 %126 +%156 = OpFRem %3 %127 %128 +OpBranch %157 +%157 = OpLabel +%159 = OpIAdd %12 %121 %122 +%160 = OpIAdd %12 %121 %122 +%161 = OpIAdd %15 %130 %131 +%162 = OpIAdd %15 %130 %131 +%163 = OpFAdd %9 %59 %60 +%164 = OpFAdd %9 %59 %60 +%165 = OpISub %12 %121 %122 +%166 = OpISub %12 %121 %122 +%167 = OpISub %15 %130 %131 +%168 = OpISub %15 %130 %131 +%169 = OpFSub %9 %59 %60 +%170 = OpFSub %9 %59 %60 +%171 = OpSDiv %12 %121 %122 +%172 = OpSDiv %12 %121 %122 +%173 = OpUDiv %15 %130 %131 +%174 = OpUDiv %15 %130 %131 +%175 = OpFDiv %9 %59 %60 +%176 = OpFDiv %9 %59 %60 +%177 = OpSRem %12 %121 %122 +%178 = OpSRem %12 %121 %122 +%179 = OpUMod %15 %130 %131 +%180 = OpUMod %15 %130 %131 +%181 = OpFRem %9 %59 %60 +%182 = OpFRem %9 %59 %60 +OpBranch %158 +%158 = OpLabel +%184 = OpCompositeExtract %10 %135 0 +%185 = OpCompositeExtract %10 %135 0 +%186 = OpFAdd %10 %184 %185 +%187 = OpCompositeExtract %10 %135 1 +%188 = OpCompositeExtract %10 %135 1 +%189 = OpFAdd %10 %187 %188 +%190 = OpCompositeExtract %10 %135 2 +%191 = OpCompositeExtract %10 %135 2 +%192 = OpFAdd %10 %190 %191 +%183 = OpCompositeConstruct %16 %186 %189 %192 +%194 = OpCompositeExtract %10 %135 0 +%195 = OpCompositeExtract %10 %135 0 +%196 = OpFSub %10 %194 %195 +%197 = OpCompositeExtract %10 %135 1 +%198 = OpCompositeExtract %10 %135 1 +%199 = OpFSub %10 %197 %198 +%200 = OpCompositeExtract %10 %135 2 +%201 = OpCompositeExtract %10 %135 2 +%202 = OpFSub %10 %200 %201 +%193 = OpCompositeConstruct %16 %196 %199 %202 +%203 = OpMatrixTimesVector %10 %138 %128 +%204 = OpVectorTimesMatrix %3 %139 %138 +%205 = OpMatrixTimesMatrix %16 %138 %140 OpReturn OpFunctionEnd -%292 = OpFunction %2 None %107 -%291 = OpLabel -OpBranch %297 -%297 = OpLabel -%298 = OpCompositeConstruct %12 %293 %293 -%299 = OpCompositeConstruct %13 %294 %294 %294 -%300 = OpCompositeConstruct %12 %62 %62 -%301 = OpCompositeConstruct %12 %26 %26 -%302 = OpBitwiseOr %12 %300 %301 -%303 = OpCompositeConstruct %13 %124 %124 %124 -%304 = OpCompositeConstruct %13 %125 %125 %125 -%305 = OpBitwiseOr %13 %303 %304 -%306 = OpCompositeConstruct %12 %62 %62 -%307 = OpCompositeConstruct %12 %26 %26 -%308 = OpBitwiseAnd %12 %306 %307 -%309 = OpCompositeConstruct %13 %124 %124 %124 -%310 = OpCompositeConstruct %13 %125 %125 %125 -%311 = OpBitwiseAnd %13 %309 %310 -%312 = OpCompositeConstruct %12 %62 %62 -%313 = OpCompositeConstruct %12 %26 %26 -%314 = OpBitwiseXor %12 %312 %313 -%315 = OpCompositeConstruct %13 %124 %124 %124 -%316 = OpCompositeConstruct %13 %125 %125 %125 -%317 = OpBitwiseXor %13 %315 %316 -%318 = OpCompositeConstruct %12 %62 %62 -%319 = OpCompositeConstruct %15 %125 %125 -%320 = OpShiftLeftLogical %12 %318 %319 -%321 = OpCompositeConstruct %13 %124 %124 %124 -%322 = OpCompositeConstruct %13 %125 %125 %125 -%323 = OpShiftLeftLogical %13 %321 %322 -%324 = OpCompositeConstruct %12 %62 %62 -%325 = OpCompositeConstruct %15 %125 %125 -%326 = OpShiftRightArithmetic %12 %324 %325 -%327 = OpCompositeConstruct %13 %124 %124 %124 -%328 = OpCompositeConstruct %13 %125 %125 %125 -%329 = OpShiftRightLogical %13 %327 %328 +%207 = OpFunction %2 None %102 +%206 = OpLabel +OpBranch %214 +%214 = OpLabel +%215 = OpBitwiseOr %12 %121 %122 +%216 = OpBitwiseOr %13 %124 %126 +%217 = OpBitwiseAnd %12 %121 %122 +%218 = OpBitwiseAnd %13 %124 %126 +%219 = OpBitwiseXor %12 %121 %122 +%220 = OpBitwiseXor %13 %124 %126 +%221 = OpShiftLeftLogical %12 %121 %131 +%222 = OpShiftLeftLogical %13 %124 %126 +%223 = OpShiftRightArithmetic %12 %121 %131 +%224 = OpShiftRightLogical %13 %124 %126 OpReturn OpFunctionEnd -%331 = OpFunction %2 None %107 -%330 = OpLabel -OpBranch %332 -%332 = OpLabel -%333 = OpCompositeConstruct %12 %62 %62 -%334 = OpCompositeConstruct %12 %26 %26 -%335 = OpIEqual %11 %333 %334 -%336 = OpCompositeConstruct %13 %124 %124 %124 -%337 = OpCompositeConstruct %13 %125 %125 %125 -%338 = OpIEqual %100 %336 %337 -%339 = OpCompositeConstruct %3 %58 %58 %58 %58 -%340 = OpCompositeConstruct %3 %20 %20 %20 %20 -%341 = OpFOrdEqual %7 %339 %340 -%342 = OpCompositeConstruct %12 %62 %62 -%343 = OpCompositeConstruct %12 %26 %26 -%344 = OpINotEqual %11 %342 %343 -%345 = OpCompositeConstruct %13 %124 %124 %124 -%346 = OpCompositeConstruct %13 %125 %125 %125 -%347 = OpINotEqual %100 %345 %346 -%348 = OpCompositeConstruct %3 %58 %58 %58 %58 -%349 = OpCompositeConstruct %3 %20 %20 %20 %20 -%350 = OpFOrdNotEqual %7 %348 %349 -%351 = OpCompositeConstruct %12 %62 %62 -%352 = OpCompositeConstruct %12 %26 %26 -%353 = OpSLessThan %11 %351 %352 -%354 = OpCompositeConstruct %13 %124 %124 %124 -%355 = OpCompositeConstruct %13 %125 %125 %125 -%356 = OpULessThan %100 %354 %355 -%357 = OpCompositeConstruct %3 %58 %58 %58 %58 -%358 = OpCompositeConstruct %3 %20 %20 %20 %20 -%359 = OpFOrdLessThan %7 %357 %358 -%360 = OpCompositeConstruct %12 %62 %62 -%361 = OpCompositeConstruct %12 %26 %26 -%362 = OpSLessThanEqual %11 %360 %361 -%363 = OpCompositeConstruct %13 %124 %124 %124 -%364 = OpCompositeConstruct %13 %125 %125 %125 -%365 = OpULessThanEqual %100 %363 %364 -%366 = OpCompositeConstruct %3 %58 %58 %58 %58 -%367 = OpCompositeConstruct %3 %20 %20 %20 %20 -%368 = OpFOrdLessThanEqual %7 %366 %367 -%369 = OpCompositeConstruct %12 %62 %62 -%370 = OpCompositeConstruct %12 %26 %26 -%371 = OpSGreaterThan %11 %369 %370 -%372 = OpCompositeConstruct %13 %124 %124 %124 -%373 = OpCompositeConstruct %13 %125 %125 %125 -%374 = OpUGreaterThan %100 %372 %373 -%375 = OpCompositeConstruct %3 %58 %58 %58 %58 -%376 = OpCompositeConstruct %3 %20 %20 %20 %20 -%377 = OpFOrdGreaterThan %7 %375 %376 -%378 = OpCompositeConstruct %12 %62 %62 -%379 = OpCompositeConstruct %12 %26 %26 -%380 = OpSGreaterThanEqual %11 %378 %379 -%381 = OpCompositeConstruct %13 %124 %124 %124 -%382 = OpCompositeConstruct %13 %125 %125 %125 -%383 = OpUGreaterThanEqual %100 %381 %382 -%384 = OpCompositeConstruct %3 %58 %58 %58 %58 -%385 = OpCompositeConstruct %3 %20 %20 %20 %20 -%386 = OpFOrdGreaterThanEqual %7 %384 %385 +%226 = OpFunction %2 None %102 +%225 = OpLabel +OpBranch %227 +%227 = OpLabel +%228 = OpIEqual %11 %121 %122 +%229 = OpIEqual %95 %124 %126 +%230 = OpFOrdEqual %7 %127 %128 +%231 = OpINotEqual %11 %121 %122 +%232 = OpINotEqual %95 %124 %126 +%233 = OpFOrdNotEqual %7 %127 %128 +%234 = OpSLessThan %11 %121 %122 +%235 = OpULessThan %95 %124 %126 +%236 = OpFOrdLessThan %7 %127 %128 +%237 = OpSLessThanEqual %11 %121 %122 +%238 = OpULessThanEqual %95 %124 %126 +%239 = OpFOrdLessThanEqual %7 %127 %128 +%240 = OpSGreaterThan %11 %121 %122 +%241 = OpUGreaterThan %95 %124 %126 +%242 = OpFOrdGreaterThan %7 %127 %128 +%243 = OpSGreaterThanEqual %11 %121 %122 +%244 = OpUGreaterThanEqual %95 %124 %126 +%245 = OpFOrdGreaterThanEqual %7 %127 %128 OpReturn OpFunctionEnd -%394 = OpFunction %2 None %107 -%393 = OpLabel -%387 = OpVariable %388 Function %389 -%390 = OpVariable %391 Function %392 -OpBranch %395 -%395 = OpLabel -OpStore %387 %26 -%396 = OpLoad %6 %387 -%397 = OpIAdd %6 %396 %26 -OpStore %387 %397 -%398 = OpLoad %6 %387 -%399 = OpISub %6 %398 %26 -OpStore %387 %399 -%400 = OpLoad %6 %387 -%401 = OpLoad %6 %387 -%402 = OpIMul %6 %401 %400 -OpStore %387 %402 -%403 = OpLoad %6 %387 -%404 = OpLoad %6 %387 -%405 = OpSDiv %6 %404 %403 -OpStore %387 %405 -%406 = OpLoad %6 %387 -%407 = OpSRem %6 %406 %26 -OpStore %387 %407 -%408 = OpLoad %6 %387 -%409 = OpBitwiseAnd %6 %408 %32 -OpStore %387 %409 -%410 = OpLoad %6 %387 -%411 = OpBitwiseOr %6 %410 %32 -OpStore %387 %411 -%412 = OpLoad %6 %387 -%413 = OpBitwiseXor %6 %412 %32 -OpStore %387 %413 -%414 = OpLoad %6 %387 -%415 = OpShiftLeftLogical %6 %414 %124 -OpStore %387 %415 -%416 = OpLoad %6 %387 -%417 = OpShiftRightArithmetic %6 %416 %125 -OpStore %387 %417 -%418 = OpLoad %6 %387 -%419 = OpIAdd %6 %418 %26 -OpStore %387 %419 -%420 = OpLoad %6 %387 -%421 = OpISub %6 %420 %26 -OpStore %387 %421 -OpStore %390 %392 -%423 = OpAccessChain %422 %390 %125 -%424 = OpLoad %6 %423 -%425 = OpIAdd %6 %424 %26 -%426 = OpAccessChain %422 %390 %125 -OpStore %426 %425 -%427 = OpAccessChain %422 %390 %125 -%428 = OpLoad %6 %427 -%429 = OpISub %6 %428 %26 -%430 = OpAccessChain %422 %390 %125 -OpStore %430 %429 +%247 = OpFunction %2 None %102 +%246 = OpLabel +%249 = OpVariable %250 Function %26 +%251 = OpVariable %252 Function %248 +OpBranch %253 +%253 = OpLabel +%254 = OpLoad %6 %249 +%255 = OpIAdd %6 %254 %26 +OpStore %249 %255 +%256 = OpLoad %6 %249 +%257 = OpISub %6 %256 %26 +OpStore %249 %257 +%258 = OpLoad %6 %249 +%259 = OpLoad %6 %249 +%260 = OpIMul %6 %259 %258 +OpStore %249 %260 +%261 = OpLoad %6 %249 +%262 = OpLoad %6 %249 +%263 = OpSDiv %6 %262 %261 +OpStore %249 %263 +%264 = OpLoad %6 %249 +%265 = OpSRem %6 %264 %26 +OpStore %249 %265 +%266 = OpLoad %6 %249 +%267 = OpBitwiseAnd %6 %266 %32 +OpStore %249 %267 +%268 = OpLoad %6 %249 +%269 = OpBitwiseOr %6 %268 %32 +OpStore %249 %269 +%270 = OpLoad %6 %249 +%271 = OpBitwiseXor %6 %270 %32 +OpStore %249 %271 +%272 = OpLoad %6 %249 +%273 = OpShiftLeftLogical %6 %272 %123 +OpStore %249 %273 +%274 = OpLoad %6 %249 +%275 = OpShiftRightArithmetic %6 %274 %125 +OpStore %249 %275 +%276 = OpLoad %6 %249 +%277 = OpIAdd %6 %276 %26 +OpStore %249 %277 +%278 = OpLoad %6 %249 +%279 = OpISub %6 %278 %26 +OpStore %249 %279 +%281 = OpAccessChain %280 %251 %125 +%282 = OpLoad %6 %281 +%283 = OpIAdd %6 %282 %26 +%284 = OpAccessChain %280 %251 %125 +OpStore %284 %283 +%285 = OpAccessChain %280 %251 %125 +%286 = OpLoad %6 %285 +%287 = OpISub %6 %286 %26 +%288 = OpAccessChain %280 %251 %125 +OpStore %288 %287 OpReturn OpFunctionEnd -%432 = OpFunction %2 None %107 -%431 = OpLabel -OpBranch %437 -%437 = OpLabel +%290 = OpFunction %2 None %102 +%289 = OpLabel +OpBranch %295 +%295 = OpLabel OpReturn OpFunctionEnd -%439 = OpFunction %2 None %107 -%438 = OpLabel -OpBranch %440 -%440 = OpLabel -%441 = OpFunctionCall %3 %29 -%442 = OpFunctionCall %3 %57 -%443 = OpCompositeConstruct %10 %20 %20 %20 -%444 = OpFunctionCall %10 %97 %443 -%445 = OpFunctionCall %2 %106 -%446 = OpFunctionCall %2 %119 -%447 = OpFunctionCall %2 %292 -%448 = OpFunctionCall %2 %331 -%449 = OpFunctionCall %2 %394 +%297 = OpFunction %2 None %102 +%296 = OpLabel +OpBranch %299 +%299 = OpLabel +%300 = OpFunctionCall %3 %29 +%301 = OpFunctionCall %3 %57 +%302 = OpFunctionCall %10 %92 %298 +%303 = OpFunctionCall %2 %101 +%304 = OpFunctionCall %2 %114 +%305 = OpFunctionCall %2 %207 +%306 = OpFunctionCall %2 %226 +%307 = OpFunctionCall %2 %247 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/padding.spvasm b/tests/out/spv/padding.spvasm index e0b4251ae..aae9f2cb7 100644 --- a/tests/out/spv/padding.spvasm +++ b/tests/out/spv/padding.spvasm @@ -73,6 +73,7 @@ OpDecorate %24 BuiltIn Position %31 = OpTypePointer Uniform %10 %33 = OpTypePointer Uniform %12 %35 = OpConstant %4 1.0 +%36 = OpConstantComposite %13 %35 %35 %35 %35 %38 = OpTypePointer Uniform %4 %39 = OpConstant %9 1 %26 = OpFunction %2 None %27 @@ -80,12 +81,11 @@ OpDecorate %24 BuiltIn Position %30 = OpAccessChain %28 %14 %29 %32 = OpAccessChain %31 %17 %29 %34 = OpAccessChain %33 %20 %29 -OpBranch %36 -%36 = OpLabel -%37 = OpCompositeConstruct %13 %35 %35 %35 %35 +OpBranch %37 +%37 = OpLabel %40 = OpAccessChain %38 %30 %39 %41 = OpLoad %4 %40 -%42 = OpVectorTimesScalar %13 %37 %41 +%42 = OpVectorTimesScalar %13 %36 %41 %43 = OpAccessChain %38 %32 %39 %44 = OpLoad %4 %43 %45 = OpVectorTimesScalar %13 %42 %44 diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm index 2de4a4971..ae42aed2e 100644 --- a/tests/out/spv/pointers.spvasm +++ b/tests/out/spv/pointers.spvasm @@ -10,8 +10,8 @@ OpMemoryModel Logical GLSL450 OpMemberName %7 0 "arr" OpName %7 "DynamicArray" OpName %8 "dynamic_array" -OpName %10 "v" -OpName %14 "f" +OpName %11 "f" +OpName %14 "v" OpName %22 "i" OpName %23 "v" OpName %24 "index_unsized" @@ -31,22 +31,22 @@ OpDecorate %8 Binding 0 %7 = OpTypeStruct %6 %9 = OpTypePointer StorageBuffer %7 %8 = OpVariable %9 StorageBuffer -%11 = OpTypePointer Function %3 -%12 = OpConstantNull %3 -%15 = OpTypeFunction %2 -%16 = OpConstant %4 10 +%12 = OpTypeFunction %2 +%13 = OpConstant %4 10 +%15 = OpTypePointer Function %3 +%16 = OpConstantNull %3 %18 = OpTypePointer Function %4 %19 = OpConstant %5 0 %25 = OpTypeFunction %2 %4 %5 %27 = OpTypePointer StorageBuffer %6 %28 = OpTypePointer StorageBuffer %5 -%14 = OpFunction %2 None %15 -%13 = OpLabel -%10 = OpVariable %11 Function %12 +%11 = OpFunction %2 None %12 +%10 = OpLabel +%14 = OpVariable %15 Function %16 OpBranch %17 %17 = OpLabel -%20 = OpAccessChain %18 %10 %19 -OpStore %20 %16 +%20 = OpAccessChain %18 %14 %19 +OpStore %20 %13 OpReturn OpFunctionEnd %24 = OpFunction %2 None %25 diff --git a/tests/out/spv/policy-mix.spvasm b/tests/out/spv/policy-mix.spvasm index a23714d9d..a10ff1121 100644 --- a/tests/out/spv/policy-mix.spvasm +++ b/tests/out/spv/policy-mix.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 101 +; Bound: 100 OpCapability Shader OpCapability ImageQuery OpCapability Linkage @@ -17,11 +17,11 @@ OpName %24 "in_uniform" OpName %27 "image_2d_array" OpName %29 "in_workgroup" OpName %31 "in_private" -OpName %34 "in_function" -OpName %38 "c" -OpName %39 "i" -OpName %40 "l" -OpName %41 "mock_function" +OpName %35 "c" +OpName %36 "i" +OpName %37 "l" +OpName %38 "mock_function" +OpName %52 "in_function" OpDecorate %5 ArrayStride 16 OpMemberDecorate %8 0 Offset 0 OpDecorate %9 ArrayStride 16 @@ -72,78 +72,76 @@ OpDecorate %27 Binding 2 %32 = OpTypePointer Private %15 %33 = OpConstantNull %15 %31 = OpVariable %32 Private %33 -%35 = OpTypePointer Function %19 -%36 = OpConstantNull %19 -%42 = OpTypeFunction %3 %17 %18 %18 -%43 = OpTypePointer StorageBuffer %8 -%44 = OpConstant %7 0 -%46 = OpTypePointer Uniform %11 -%49 = OpConstant %4 0.707 -%50 = OpConstant %4 0.0 -%51 = OpConstant %4 1.0 -%56 = OpTypePointer StorageBuffer %5 -%57 = OpTypePointer StorageBuffer %3 -%60 = OpTypePointer Uniform %9 -%61 = OpTypePointer Uniform %3 -%65 = OpTypeVector %18 3 -%67 = OpTypeBool -%68 = OpConstantNull %3 -%74 = OpTypeVector %67 3 -%81 = OpTypePointer Workgroup %4 -%82 = OpConstant %7 29 -%88 = OpTypePointer Private %4 -%89 = OpConstant %7 39 -%95 = OpTypePointer Function %3 -%96 = OpConstant %7 1 -%41 = OpFunction %3 None %42 -%38 = OpFunctionParameter %17 -%39 = OpFunctionParameter %18 -%40 = OpFunctionParameter %18 -%37 = OpLabel -%34 = OpVariable %35 Function %36 -%45 = OpAccessChain %43 %21 %44 -%47 = OpAccessChain %46 %24 %44 -%48 = OpLoad %12 %27 -OpBranch %52 -%52 = OpLabel -%53 = OpCompositeConstruct %3 %49 %50 %50 %51 -%54 = OpCompositeConstruct %3 %50 %49 %50 %51 -%55 = OpCompositeConstruct %19 %53 %54 -OpStore %34 %55 -%58 = OpAccessChain %57 %45 %44 %39 -%59 = OpLoad %3 %58 -%62 = OpAccessChain %61 %47 %44 %39 -%63 = OpLoad %3 %62 -%64 = OpFAdd %3 %59 %63 -%66 = OpCompositeConstruct %65 %38 %39 -%69 = OpImageQueryLevels %18 %48 -%70 = OpULessThan %67 %40 %69 -OpSelectionMerge %71 None -OpBranchConditional %70 %72 %71 -%72 = OpLabel -%73 = OpImageQuerySizeLod %65 %48 %40 -%75 = OpULessThan %74 %66 %73 -%76 = OpAll %67 %75 -OpBranchConditional %76 %77 %71 -%77 = OpLabel -%78 = OpImageFetch %3 %48 %66 Lod %40 -OpBranch %71 +%39 = OpTypeFunction %3 %17 %18 %18 +%40 = OpTypePointer StorageBuffer %8 +%41 = OpConstant %7 0 +%43 = OpTypePointer Uniform %11 +%46 = OpConstant %4 0.707 +%47 = OpConstant %4 0.0 +%48 = OpConstant %4 1.0 +%49 = OpConstantComposite %3 %46 %47 %47 %48 +%50 = OpConstantComposite %3 %47 %46 %47 %48 +%51 = OpConstantComposite %19 %49 %50 +%53 = OpTypePointer Function %19 +%55 = OpTypePointer StorageBuffer %5 +%56 = OpTypePointer StorageBuffer %3 +%59 = OpTypePointer Uniform %9 +%60 = OpTypePointer Uniform %3 +%64 = OpTypeVector %18 3 +%66 = OpTypeBool +%67 = OpConstantNull %3 +%73 = OpTypeVector %66 3 +%80 = OpTypePointer Workgroup %4 +%81 = OpConstant %7 29 +%87 = OpTypePointer Private %4 +%88 = OpConstant %7 39 +%94 = OpTypePointer Function %3 +%95 = OpConstant %7 1 +%38 = OpFunction %3 None %39 +%35 = OpFunctionParameter %17 +%36 = OpFunctionParameter %18 +%37 = OpFunctionParameter %18 +%34 = OpLabel +%52 = OpVariable %53 Function %51 +%42 = OpAccessChain %40 %21 %41 +%44 = OpAccessChain %43 %24 %41 +%45 = OpLoad %12 %27 +OpBranch %54 +%54 = OpLabel +%57 = OpAccessChain %56 %42 %41 %36 +%58 = OpLoad %3 %57 +%61 = OpAccessChain %60 %44 %41 %36 +%62 = OpLoad %3 %61 +%63 = OpFAdd %3 %58 %62 +%65 = OpCompositeConstruct %64 %35 %36 +%68 = OpImageQueryLevels %18 %45 +%69 = OpULessThan %66 %37 %68 +OpSelectionMerge %70 None +OpBranchConditional %69 %71 %70 %71 = OpLabel -%79 = OpPhi %3 %68 %52 %68 %72 %78 %77 -%80 = OpFAdd %3 %64 %79 -%83 = OpExtInst %7 %1 UMin %39 %82 -%84 = OpAccessChain %81 %29 %83 -%85 = OpLoad %4 %84 -%86 = OpCompositeConstruct %3 %85 %85 %85 %85 -%87 = OpFAdd %3 %80 %86 -%90 = OpExtInst %7 %1 UMin %39 %89 -%91 = OpAccessChain %88 %31 %90 -%92 = OpLoad %4 %91 -%93 = OpCompositeConstruct %3 %92 %92 %92 %92 -%94 = OpFAdd %3 %87 %93 -%97 = OpExtInst %7 %1 UMin %39 %96 -%98 = OpAccessChain %95 %34 %97 -%99 = OpLoad %3 %98 -%100 = OpFAdd %3 %94 %99 -OpReturnValue %100 +%72 = OpImageQuerySizeLod %64 %45 %37 +%74 = OpULessThan %73 %65 %72 +%75 = OpAll %66 %74 +OpBranchConditional %75 %76 %70 +%76 = OpLabel +%77 = OpImageFetch %3 %45 %65 Lod %37 +OpBranch %70 +%70 = OpLabel +%78 = OpPhi %3 %67 %54 %67 %71 %77 %76 +%79 = OpFAdd %3 %63 %78 +%82 = OpExtInst %7 %1 UMin %36 %81 +%83 = OpAccessChain %80 %29 %82 +%84 = OpLoad %4 %83 +%85 = OpCompositeConstruct %3 %84 %84 %84 %84 +%86 = OpFAdd %3 %79 %85 +%89 = OpExtInst %7 %1 UMin %36 %88 +%90 = OpAccessChain %87 %31 %89 +%91 = OpLoad %4 %90 +%92 = OpCompositeConstruct %3 %91 %91 %91 %91 +%93 = OpFAdd %3 %86 %92 +%96 = OpExtInst %7 %1 UMin %36 %95 +%97 = OpAccessChain %94 %52 %96 +%98 = OpLoad %3 %97 +%99 = OpFAdd %3 %93 %98 +OpReturnValue %99 OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/quad.spvasm b/tests/out/spv/quad.spvasm index 3de529f6b..b77ed65e0 100644 --- a/tests/out/spv/quad.spvasm +++ b/tests/out/spv/quad.spvasm @@ -68,6 +68,7 @@ OpDecorate %59 Location 0 %52 = OpTypeBool %59 = OpVariable %23 Output %61 = OpConstant %3 0.5 +%62 = OpConstantComposite %5 %26 %61 %26 %61 %24 = OpFunction %2 None %25 %14 = OpLabel %17 = OpLoad %4 %15 @@ -110,9 +111,8 @@ OpReturn OpFunctionEnd %60 = OpFunction %2 None %25 %58 = OpLabel -OpBranch %62 -%62 = OpLabel -%63 = OpCompositeConstruct %5 %26 %61 %26 %61 -OpStore %59 %63 +OpBranch %63 +%63 = OpLabel +OpStore %59 %62 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/ray-query.spvasm b/tests/out/spv/ray-query.spvasm index 2445b3169..d96dbb315 100644 --- a/tests/out/spv/ray-query.spvasm +++ b/tests/out/spv/ray-query.spvasm @@ -7,8 +7,8 @@ OpCapability RayQueryKHR OpExtension "SPV_KHR_ray_query" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %43 "main" %15 %17 -OpExecutionMode %43 LocalSize 1 1 1 +OpEntryPoint GLCompute %41 "main" %15 %17 +OpExecutionMode %41 LocalSize 1 1 1 OpMemberDecorate %7 0 Offset 0 OpMemberDecorate %7 1 Offset 16 OpMemberDecorate %11 0 Offset 0 @@ -60,14 +60,17 @@ OpMemberDecorate %18 0 Offset 0 %25 = OpConstant %6 1.0 %26 = OpConstant %6 2.4 %27 = OpConstant %6 0.0 -%41 = OpTypePointer Function %13 -%44 = OpTypeFunction %2 -%46 = OpTypePointer StorageBuffer %7 -%47 = OpConstant %4 0 -%49 = OpConstant %4 4 -%50 = OpConstant %4 255 -%51 = OpConstant %6 0.1 -%52 = OpConstant %6 100.0 +%42 = OpTypeFunction %2 +%44 = OpTypePointer StorageBuffer %7 +%45 = OpConstant %4 0 +%47 = OpConstantComposite %5 %27 %25 %27 +%48 = OpConstant %4 4 +%49 = OpConstant %4 255 +%50 = OpConstant %6 0.1 +%51 = OpConstant %6 100.0 +%52 = OpConstantComposite %5 %27 %27 %27 +%53 = OpConstantComposite %14 %48 %49 %50 %51 %52 %47 +%55 = OpTypePointer Function %13 %72 = OpConstant %4 1 %85 = OpTypePointer StorageBuffer %4 %90 = OpTypePointer StorageBuffer %5 @@ -90,29 +93,26 @@ OpBranch %28 %39 = OpExtInst %5 %1 Normalize %38 OpReturnValue %39 OpFunctionEnd -%43 = OpFunction %2 None %44 -%42 = OpLabel -%40 = OpVariable %41 Function -%45 = OpLoad %3 %15 -%48 = OpAccessChain %46 %17 %47 -OpBranch %53 -%53 = OpLabel -%54 = OpCompositeConstruct %5 %27 %25 %27 -%55 = OpCompositeConstruct %5 %27 %27 %27 -%56 = OpCompositeConstruct %14 %49 %50 %51 %52 %55 %54 -%57 = OpCompositeExtract %4 %56 0 -%58 = OpCompositeExtract %4 %56 1 -%59 = OpCompositeExtract %6 %56 2 -%60 = OpCompositeExtract %6 %56 3 -%61 = OpCompositeExtract %5 %56 4 -%62 = OpCompositeExtract %5 %56 5 -OpRayQueryInitializeKHR %40 %45 %57 %58 %61 %59 %62 %60 +%41 = OpFunction %2 None %42 +%40 = OpLabel +%54 = OpVariable %55 Function +%43 = OpLoad %3 %15 +%46 = OpAccessChain %44 %17 %45 +OpBranch %56 +%56 = OpLabel +%57 = OpCompositeExtract %4 %53 0 +%58 = OpCompositeExtract %4 %53 1 +%59 = OpCompositeExtract %6 %53 2 +%60 = OpCompositeExtract %6 %53 3 +%61 = OpCompositeExtract %5 %53 4 +%62 = OpCompositeExtract %5 %53 5 +OpRayQueryInitializeKHR %54 %43 %57 %58 %61 %59 %62 %60 OpBranch %63 %63 = OpLabel OpLoopMerge %64 %66 None OpBranch %65 %65 = OpLabel -%67 = OpRayQueryProceedKHR %9 %40 +%67 = OpRayQueryProceedKHR %9 %54 OpSelectionMerge %68 None OpBranchConditional %67 %68 %69 %69 = OpLabel @@ -126,27 +126,27 @@ OpBranch %66 %66 = OpLabel OpBranch %63 %64 = OpLabel -%73 = OpRayQueryGetIntersectionTypeKHR %4 %40 %72 -%74 = OpRayQueryGetIntersectionInstanceCustomIndexKHR %4 %40 %72 -%75 = OpRayQueryGetIntersectionInstanceIdKHR %4 %40 %72 -%76 = OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR %4 %40 %72 -%77 = OpRayQueryGetIntersectionGeometryIndexKHR %4 %40 %72 -%78 = OpRayQueryGetIntersectionPrimitiveIndexKHR %4 %40 %72 -%79 = OpRayQueryGetIntersectionTKHR %6 %40 %72 -%80 = OpRayQueryGetIntersectionBarycentricsKHR %8 %40 %72 -%81 = OpRayQueryGetIntersectionFrontFaceKHR %9 %40 %72 -%82 = OpRayQueryGetIntersectionObjectToWorldKHR %10 %40 %72 -%83 = OpRayQueryGetIntersectionWorldToObjectKHR %10 %40 %72 +%73 = OpRayQueryGetIntersectionTypeKHR %4 %54 %72 +%74 = OpRayQueryGetIntersectionInstanceCustomIndexKHR %4 %54 %72 +%75 = OpRayQueryGetIntersectionInstanceIdKHR %4 %54 %72 +%76 = OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR %4 %54 %72 +%77 = OpRayQueryGetIntersectionGeometryIndexKHR %4 %54 %72 +%78 = OpRayQueryGetIntersectionPrimitiveIndexKHR %4 %54 %72 +%79 = OpRayQueryGetIntersectionTKHR %6 %54 %72 +%80 = OpRayQueryGetIntersectionBarycentricsKHR %8 %54 %72 +%81 = OpRayQueryGetIntersectionFrontFaceKHR %9 %54 %72 +%82 = OpRayQueryGetIntersectionObjectToWorldKHR %10 %54 %72 +%83 = OpRayQueryGetIntersectionWorldToObjectKHR %10 %54 %72 %84 = OpCompositeConstruct %11 %73 %79 %74 %75 %76 %77 %78 %80 %81 %82 %83 %86 = OpCompositeExtract %4 %84 0 -%87 = OpIEqual %9 %86 %47 -%88 = OpSelect %4 %87 %72 %47 -%89 = OpAccessChain %85 %48 %47 +%87 = OpIEqual %9 %86 %45 +%88 = OpSelect %4 %87 %72 %45 +%89 = OpAccessChain %85 %46 %45 OpStore %89 %88 %91 = OpCompositeExtract %6 %84 1 -%92 = OpVectorTimesScalar %5 %54 %91 +%92 = OpVectorTimesScalar %5 %47 %91 %93 = OpFunctionCall %5 %23 %92 %84 -%94 = OpAccessChain %90 %48 %72 +%94 = OpAccessChain %90 %46 %72 OpStore %94 %93 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/shadow.spvasm b/tests/out/spv/shadow.spvasm index d0e3309c2..55bfa4fec 100644 --- a/tests/out/spv/shadow.spvasm +++ b/tests/out/spv/shadow.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.2 ; Generator: rspirv -; Bound: 267 +; Bound: 265 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %87 "vs_main" %77 %80 %82 %84 %86 -OpEntryPoint Fragment %147 "fs_main" %138 %141 %144 %146 -OpEntryPoint Fragment %214 "fs_main_without_storage" %207 %209 %211 %213 -OpExecutionMode %147 OriginUpperLeft -OpExecutionMode %214 OriginUpperLeft +OpEntryPoint Vertex %84 "vs_main" %74 %77 %79 %81 %83 +OpEntryPoint Fragment %142 "fs_main" %133 %136 %139 %141 +OpEntryPoint Fragment %210 "fs_main_without_storage" %203 %205 %207 %209 +OpExecutionMode %142 OriginUpperLeft +OpExecutionMode %210 OriginUpperLeft OpMemberName %8 0 "view_proj" OpMemberName %8 1 "num_lights" OpName %8 "Globals" @@ -36,25 +36,25 @@ OpName %38 "sampler_shadow" OpName %41 "light_id" OpName %42 "homogeneous_coords" OpName %43 "fetch_shadow" -OpName %73 "out" -OpName %77 "position" -OpName %80 "normal" -OpName %82 "proj_position" -OpName %84 "world_normal" -OpName %86 "world_position" -OpName %87 "vs_main" -OpName %131 "color" -OpName %133 "i" -OpName %138 "proj_position" -OpName %141 "world_normal" -OpName %144 "world_position" -OpName %147 "fs_main" -OpName %203 "color" -OpName %204 "i" -OpName %207 "proj_position" -OpName %209 "world_normal" -OpName %211 "world_position" -OpName %214 "fs_main_without_storage" +OpName %74 "position" +OpName %77 "normal" +OpName %79 "proj_position" +OpName %81 "world_normal" +OpName %83 "world_position" +OpName %84 "vs_main" +OpName %91 "out" +OpName %133 "proj_position" +OpName %136 "world_normal" +OpName %139 "world_position" +OpName %142 "fs_main" +OpName %149 "color" +OpName %150 "i" +OpName %203 "proj_position" +OpName %205 "world_normal" +OpName %207 "world_position" +OpName %210 "fs_main_without_storage" +OpName %217 "color" +OpName %218 "i" OpMemberDecorate %8 0 Offset 0 OpMemberDecorate %8 0 ColMajor OpMemberDecorate %8 0 MatrixStride 16 @@ -94,19 +94,19 @@ OpDecorate %36 DescriptorSet 0 OpDecorate %36 Binding 2 OpDecorate %38 DescriptorSet 0 OpDecorate %38 Binding 3 -OpDecorate %77 Location 0 -OpDecorate %80 Location 1 -OpDecorate %82 BuiltIn Position -OpDecorate %84 Location 0 -OpDecorate %86 Location 1 -OpDecorate %138 BuiltIn FragCoord +OpDecorate %74 Location 0 +OpDecorate %77 Location 1 +OpDecorate %79 BuiltIn Position +OpDecorate %81 Location 0 +OpDecorate %83 Location 1 +OpDecorate %133 BuiltIn FragCoord +OpDecorate %136 Location 0 +OpDecorate %139 Location 1 OpDecorate %141 Location 0 -OpDecorate %144 Location 1 -OpDecorate %146 Location 0 -OpDecorate %207 BuiltIn FragCoord +OpDecorate %203 BuiltIn FragCoord +OpDecorate %205 Location 0 +OpDecorate %207 Location 1 OpDecorate %209 Location 0 -OpDecorate %211 Location 1 -OpDecorate %213 Location 0 %2 = OpTypeVoid %5 = OpTypeFloat 32 %4 = OpTypeVector %5 4 @@ -150,22 +150,24 @@ OpDecorate %213 Location 0 %48 = OpConstant %5 1.0 %49 = OpConstant %5 0.5 %50 = OpConstant %5 -0.5 -%53 = OpTypeBool +%51 = OpConstantComposite %21 %49 %50 +%52 = OpConstantComposite %21 %49 %49 +%55 = OpTypeBool %68 = OpTypeSampledImage %19 -%74 = OpTypePointer Function %11 -%75 = OpConstantNull %11 -%78 = OpTypePointer Input %12 -%77 = OpVariable %78 Input -%80 = OpVariable %78 Input -%83 = OpTypePointer Output %4 -%82 = OpVariable %83 Output -%85 = OpTypePointer Output %10 -%84 = OpVariable %85 Output -%86 = OpVariable %83 Output -%88 = OpTypeFunction %2 -%89 = OpTypePointer Uniform %8 -%90 = OpConstant %7 0 -%92 = OpTypePointer Uniform %9 +%75 = OpTypePointer Input %12 +%74 = OpVariable %75 Input +%77 = OpVariable %75 Input +%80 = OpTypePointer Output %4 +%79 = OpVariable %80 Output +%82 = OpTypePointer Output %10 +%81 = OpVariable %82 Output +%83 = OpVariable %80 Output +%85 = OpTypeFunction %2 +%86 = OpTypePointer Uniform %8 +%87 = OpConstant %7 0 +%89 = OpTypePointer Uniform %9 +%92 = OpTypePointer Function %11 +%93 = OpConstantNull %11 %95 = OpTypePointer Uniform %3 %102 = OpTypePointer Function %10 %110 = OpTypeVector %13 3 @@ -173,72 +175,68 @@ OpDecorate %213 Location 0 %116 = OpTypePointer Function %4 %117 = OpConstant %7 2 %125 = OpTypePointer Output %5 -%132 = OpConstantNull %10 -%134 = OpTypePointer Function %7 -%135 = OpConstantNull %7 -%139 = OpTypePointer Input %4 -%138 = OpVariable %139 Input -%142 = OpTypePointer Input %10 -%141 = OpVariable %142 Input -%144 = OpVariable %139 Input -%146 = OpVariable %83 Output -%150 = OpTypePointer StorageBuffer %16 -%162 = OpTypePointer Uniform %6 -%163 = OpTypePointer Uniform %7 -%173 = OpTypePointer StorageBuffer %15 -%199 = OpTypePointer Uniform %4 -%207 = OpVariable %139 Input -%209 = OpVariable %142 Input -%211 = OpVariable %139 Input -%213 = OpVariable %83 Output -%217 = OpTypePointer Uniform %17 -%238 = OpTypePointer Uniform %15 +%134 = OpTypePointer Input %4 +%133 = OpVariable %134 Input +%137 = OpTypePointer Input %10 +%136 = OpVariable %137 Input +%139 = OpVariable %134 Input +%141 = OpVariable %80 Output +%145 = OpTypePointer StorageBuffer %16 +%151 = OpTypePointer Function %7 +%160 = OpTypePointer Uniform %6 +%161 = OpTypePointer Uniform %7 +%171 = OpTypePointer StorageBuffer %15 +%197 = OpTypePointer Uniform %4 +%203 = OpVariable %134 Input +%205 = OpVariable %137 Input +%207 = OpVariable %134 Input +%209 = OpVariable %80 Output +%213 = OpTypePointer Uniform %17 +%236 = OpTypePointer Uniform %15 %43 = OpFunction %5 None %44 %41 = OpFunctionParameter %7 %42 = OpFunctionParameter %4 %40 = OpLabel %45 = OpLoad %19 %36 %46 = OpLoad %20 %38 -OpBranch %51 -%51 = OpLabel -%52 = OpCompositeExtract %5 %42 3 -%54 = OpFOrdLessThanEqual %53 %52 %47 -OpSelectionMerge %55 None -OpBranchConditional %54 %56 %55 -%56 = OpLabel +OpBranch %53 +%53 = OpLabel +%54 = OpCompositeExtract %5 %42 3 +%56 = OpFOrdLessThanEqual %55 %54 %47 +OpSelectionMerge %57 None +OpBranchConditional %56 %58 %57 +%58 = OpLabel OpReturnValue %48 -%55 = OpLabel -%57 = OpCompositeConstruct %21 %49 %50 -%58 = OpCompositeExtract %5 %42 3 -%59 = OpFDiv %5 %48 %58 -%60 = OpVectorShuffle %21 %42 %42 0 1 -%61 = OpFMul %21 %60 %57 -%62 = OpVectorTimesScalar %21 %61 %59 -%63 = OpCompositeConstruct %21 %49 %49 -%64 = OpFAdd %21 %62 %63 +%57 = OpLabel +%59 = OpCompositeExtract %5 %42 3 +%60 = OpFDiv %5 %48 %59 +%61 = OpVectorShuffle %21 %42 %42 0 1 +%62 = OpFMul %21 %61 %51 +%63 = OpVectorTimesScalar %21 %62 %60 +%64 = OpFAdd %21 %63 %52 %65 = OpBitcast %13 %41 %66 = OpCompositeExtract %5 %42 2 -%67 = OpFMul %5 %66 %59 +%67 = OpFMul %5 %66 %60 %69 = OpConvertSToF %5 %65 %70 = OpCompositeConstruct %10 %64 %69 %71 = OpSampledImage %68 %45 %46 %72 = OpImageSampleDrefExplicitLod %5 %71 %70 %67 Lod %47 OpReturnValue %72 OpFunctionEnd -%87 = OpFunction %2 None %88 -%76 = OpLabel -%73 = OpVariable %74 Function %75 -%79 = OpLoad %12 %77 -%81 = OpLoad %12 %80 -%91 = OpAccessChain %89 %24 %90 -%93 = OpAccessChain %92 %27 %90 +%84 = OpFunction %2 None %85 +%73 = OpLabel +%91 = OpVariable %92 Function %93 +%76 = OpLoad %12 %74 +%78 = OpLoad %12 %77 +%88 = OpAccessChain %86 %24 %87 +%90 = OpAccessChain %89 %27 %87 OpBranch %94 %94 = OpLabel -%96 = OpAccessChain %95 %93 %90 +%96 = OpAccessChain %95 %90 %87 %97 = OpLoad %3 %96 -%98 = OpAccessChain %95 %93 %90 +%98 = OpAccessChain %95 %90 %87 %99 = OpLoad %3 %98 -%100 = OpConvertSToF %4 %79 +%100 = OpConvertSToF %4 %76 %101 = OpMatrixTimesVector %4 %99 %100 %103 = OpCompositeExtract %4 %97 0 %104 = OpVectorShuffle %10 %103 %103 0 1 2 @@ -247,180 +245,176 @@ OpBranch %94 %107 = OpCompositeExtract %4 %97 2 %108 = OpVectorShuffle %10 %107 %107 0 1 2 %109 = OpCompositeConstruct %14 %104 %106 %108 -%111 = OpVectorShuffle %110 %81 %81 0 1 2 +%111 = OpVectorShuffle %110 %78 %78 0 1 2 %112 = OpConvertSToF %10 %111 %113 = OpMatrixTimesVector %10 %109 %112 -%115 = OpAccessChain %102 %73 %114 +%115 = OpAccessChain %102 %91 %114 OpStore %115 %113 -%118 = OpAccessChain %116 %73 %117 +%118 = OpAccessChain %116 %91 %117 OpStore %118 %101 -%119 = OpAccessChain %95 %91 %90 +%119 = OpAccessChain %95 %88 %87 %120 = OpLoad %3 %119 %121 = OpMatrixTimesVector %4 %120 %101 -%122 = OpAccessChain %116 %73 %90 +%122 = OpAccessChain %116 %91 %87 OpStore %122 %121 -%123 = OpLoad %11 %73 +%123 = OpLoad %11 %91 %124 = OpCompositeExtract %4 %123 0 -OpStore %82 %124 -%126 = OpAccessChain %125 %82 %114 +OpStore %79 %124 +%126 = OpAccessChain %125 %79 %114 %127 = OpLoad %5 %126 %128 = OpFNegate %5 %127 OpStore %126 %128 %129 = OpCompositeExtract %10 %123 1 -OpStore %84 %129 +OpStore %81 %129 %130 = OpCompositeExtract %4 %123 2 -OpStore %86 %130 +OpStore %83 %130 OpReturn OpFunctionEnd -%147 = OpFunction %2 None %88 -%136 = OpLabel -%131 = OpVariable %102 Function %132 -%133 = OpVariable %134 Function %135 -%140 = OpLoad %4 %138 -%143 = OpLoad %10 %141 -%145 = OpLoad %4 %144 -%137 = OpCompositeConstruct %11 %140 %143 %145 -%148 = OpAccessChain %89 %24 %90 -%149 = OpAccessChain %92 %27 %90 -%151 = OpAccessChain %150 %30 %90 -%152 = OpLoad %19 %36 -%153 = OpLoad %20 %38 -OpBranch %154 -%154 = OpLabel -%155 = OpCompositeExtract %10 %137 1 -%156 = OpExtInst %10 %1 Normalize %155 -OpStore %131 %23 -OpStore %133 %90 +%142 = OpFunction %2 None %85 +%131 = OpLabel +%149 = OpVariable %102 Function %23 +%150 = OpVariable %151 Function %87 +%135 = OpLoad %4 %133 +%138 = OpLoad %10 %136 +%140 = OpLoad %4 %139 +%132 = OpCompositeConstruct %11 %135 %138 %140 +%143 = OpAccessChain %86 %24 %87 +%144 = OpAccessChain %89 %27 %87 +%146 = OpAccessChain %145 %30 %87 +%147 = OpLoad %19 %36 +%148 = OpLoad %20 %38 +OpBranch %152 +%152 = OpLabel +%153 = OpCompositeExtract %10 %132 1 +%154 = OpExtInst %10 %1 Normalize %153 +OpBranch %155 +%155 = OpLabel +OpLoopMerge %156 %158 None OpBranch %157 %157 = OpLabel -OpLoopMerge %158 %160 None -OpBranch %159 -%159 = OpLabel -%161 = OpLoad %7 %133 -%164 = OpAccessChain %163 %148 %114 %90 -%165 = OpLoad %7 %164 -%166 = OpExtInst %7 %1 UMin %165 %18 -%167 = OpULessThan %53 %161 %166 -OpSelectionMerge %168 None -OpBranchConditional %167 %168 %169 +%159 = OpLoad %7 %150 +%162 = OpAccessChain %161 %143 %114 %87 +%163 = OpLoad %7 %162 +%164 = OpExtInst %7 %1 UMin %163 %18 +%165 = OpULessThan %55 %159 %164 +OpSelectionMerge %166 None +OpBranchConditional %165 %166 %167 +%167 = OpLabel +OpBranch %156 +%166 = OpLabel +OpBranch %168 +%168 = OpLabel +%170 = OpLoad %7 %150 +%172 = OpAccessChain %171 %146 %170 +%173 = OpLoad %15 %172 +%174 = OpLoad %7 %150 +%175 = OpCompositeExtract %3 %173 0 +%176 = OpCompositeExtract %4 %132 2 +%177 = OpMatrixTimesVector %4 %175 %176 +%178 = OpFunctionCall %5 %43 %174 %177 +%179 = OpCompositeExtract %4 %173 1 +%180 = OpVectorShuffle %10 %179 %179 0 1 2 +%181 = OpCompositeExtract %4 %132 2 +%182 = OpVectorShuffle %10 %181 %181 0 1 2 +%183 = OpFSub %10 %180 %182 +%184 = OpExtInst %10 %1 Normalize %183 +%185 = OpDot %5 %154 %184 +%186 = OpExtInst %5 %1 FMax %47 %185 +%187 = OpFMul %5 %178 %186 +%188 = OpCompositeExtract %4 %173 2 +%189 = OpVectorShuffle %10 %188 %188 0 1 2 +%190 = OpVectorTimesScalar %10 %189 %187 +%191 = OpLoad %10 %149 +%192 = OpFAdd %10 %191 %190 +OpStore %149 %192 +OpBranch %169 %169 = OpLabel OpBranch %158 -%168 = OpLabel -OpBranch %170 -%170 = OpLabel -%172 = OpLoad %7 %133 -%174 = OpAccessChain %173 %151 %172 -%175 = OpLoad %15 %174 -%176 = OpLoad %7 %133 -%177 = OpCompositeExtract %3 %175 0 -%178 = OpCompositeExtract %4 %137 2 -%179 = OpMatrixTimesVector %4 %177 %178 -%180 = OpFunctionCall %5 %43 %176 %179 -%181 = OpCompositeExtract %4 %175 1 -%182 = OpVectorShuffle %10 %181 %181 0 1 2 -%183 = OpCompositeExtract %4 %137 2 -%184 = OpVectorShuffle %10 %183 %183 0 1 2 -%185 = OpFSub %10 %182 %184 -%186 = OpExtInst %10 %1 Normalize %185 -%187 = OpDot %5 %156 %186 -%188 = OpExtInst %5 %1 FMax %47 %187 -%189 = OpFMul %5 %180 %188 -%190 = OpCompositeExtract %4 %175 2 -%191 = OpVectorShuffle %10 %190 %190 0 1 2 -%192 = OpVectorTimesScalar %10 %191 %189 -%193 = OpLoad %10 %131 -%194 = OpFAdd %10 %193 %192 -OpStore %131 %194 -OpBranch %171 -%171 = OpLabel -OpBranch %160 -%160 = OpLabel -%195 = OpLoad %7 %133 -%196 = OpIAdd %7 %195 %114 -OpStore %133 %196 -OpBranch %157 %158 = OpLabel -%197 = OpLoad %10 %131 -%198 = OpCompositeConstruct %4 %197 %48 -%200 = OpAccessChain %199 %149 %114 -%201 = OpLoad %4 %200 -%202 = OpFMul %4 %198 %201 -OpStore %146 %202 +%193 = OpLoad %7 %150 +%194 = OpIAdd %7 %193 %114 +OpStore %150 %194 +OpBranch %155 +%156 = OpLabel +%195 = OpLoad %10 %149 +%196 = OpCompositeConstruct %4 %195 %48 +%198 = OpAccessChain %197 %144 %114 +%199 = OpLoad %4 %198 +%200 = OpFMul %4 %196 %199 +OpStore %141 %200 OpReturn OpFunctionEnd -%214 = OpFunction %2 None %88 -%205 = OpLabel -%203 = OpVariable %102 Function %132 -%204 = OpVariable %134 Function %135 +%210 = OpFunction %2 None %85 +%201 = OpLabel +%217 = OpVariable %102 Function %23 +%218 = OpVariable %151 Function %87 +%204 = OpLoad %4 %203 +%206 = OpLoad %10 %205 %208 = OpLoad %4 %207 -%210 = OpLoad %10 %209 -%212 = OpLoad %4 %211 -%206 = OpCompositeConstruct %11 %208 %210 %212 -%215 = OpAccessChain %89 %24 %90 -%216 = OpAccessChain %92 %27 %90 -%218 = OpAccessChain %217 %33 %90 -%219 = OpLoad %19 %36 -%220 = OpLoad %20 %38 -OpBranch %221 -%221 = OpLabel -%222 = OpCompositeExtract %10 %206 1 -%223 = OpExtInst %10 %1 Normalize %222 -OpStore %203 %23 -OpStore %204 %90 +%202 = OpCompositeConstruct %11 %204 %206 %208 +%211 = OpAccessChain %86 %24 %87 +%212 = OpAccessChain %89 %27 %87 +%214 = OpAccessChain %213 %33 %87 +%215 = OpLoad %19 %36 +%216 = OpLoad %20 %38 +OpBranch %219 +%219 = OpLabel +%220 = OpCompositeExtract %10 %202 1 +%221 = OpExtInst %10 %1 Normalize %220 +OpBranch %222 +%222 = OpLabel +OpLoopMerge %223 %225 None OpBranch %224 %224 = OpLabel -OpLoopMerge %225 %227 None -OpBranch %226 -%226 = OpLabel -%228 = OpLoad %7 %204 -%229 = OpAccessChain %163 %215 %114 %90 -%230 = OpLoad %7 %229 -%231 = OpExtInst %7 %1 UMin %230 %18 -%232 = OpULessThan %53 %228 %231 -OpSelectionMerge %233 None -OpBranchConditional %232 %233 %234 +%226 = OpLoad %7 %218 +%227 = OpAccessChain %161 %211 %114 %87 +%228 = OpLoad %7 %227 +%229 = OpExtInst %7 %1 UMin %228 %18 +%230 = OpULessThan %55 %226 %229 +OpSelectionMerge %231 None +OpBranchConditional %230 %231 %232 +%232 = OpLabel +OpBranch %223 +%231 = OpLabel +OpBranch %233 +%233 = OpLabel +%235 = OpLoad %7 %218 +%237 = OpAccessChain %236 %214 %235 +%238 = OpLoad %15 %237 +%239 = OpLoad %7 %218 +%240 = OpCompositeExtract %3 %238 0 +%241 = OpCompositeExtract %4 %202 2 +%242 = OpMatrixTimesVector %4 %240 %241 +%243 = OpFunctionCall %5 %43 %239 %242 +%244 = OpCompositeExtract %4 %238 1 +%245 = OpVectorShuffle %10 %244 %244 0 1 2 +%246 = OpCompositeExtract %4 %202 2 +%247 = OpVectorShuffle %10 %246 %246 0 1 2 +%248 = OpFSub %10 %245 %247 +%249 = OpExtInst %10 %1 Normalize %248 +%250 = OpDot %5 %221 %249 +%251 = OpExtInst %5 %1 FMax %47 %250 +%252 = OpFMul %5 %243 %251 +%253 = OpCompositeExtract %4 %238 2 +%254 = OpVectorShuffle %10 %253 %253 0 1 2 +%255 = OpVectorTimesScalar %10 %254 %252 +%256 = OpLoad %10 %217 +%257 = OpFAdd %10 %256 %255 +OpStore %217 %257 +OpBranch %234 %234 = OpLabel OpBranch %225 -%233 = OpLabel -OpBranch %235 -%235 = OpLabel -%237 = OpLoad %7 %204 -%239 = OpAccessChain %238 %218 %237 -%240 = OpLoad %15 %239 -%241 = OpLoad %7 %204 -%242 = OpCompositeExtract %3 %240 0 -%243 = OpCompositeExtract %4 %206 2 -%244 = OpMatrixTimesVector %4 %242 %243 -%245 = OpFunctionCall %5 %43 %241 %244 -%246 = OpCompositeExtract %4 %240 1 -%247 = OpVectorShuffle %10 %246 %246 0 1 2 -%248 = OpCompositeExtract %4 %206 2 -%249 = OpVectorShuffle %10 %248 %248 0 1 2 -%250 = OpFSub %10 %247 %249 -%251 = OpExtInst %10 %1 Normalize %250 -%252 = OpDot %5 %223 %251 -%253 = OpExtInst %5 %1 FMax %47 %252 -%254 = OpFMul %5 %245 %253 -%255 = OpCompositeExtract %4 %240 2 -%256 = OpVectorShuffle %10 %255 %255 0 1 2 -%257 = OpVectorTimesScalar %10 %256 %254 -%258 = OpLoad %10 %203 -%259 = OpFAdd %10 %258 %257 -OpStore %203 %259 -OpBranch %236 -%236 = OpLabel -OpBranch %227 -%227 = OpLabel -%260 = OpLoad %7 %204 -%261 = OpIAdd %7 %260 %114 -OpStore %204 %261 -OpBranch %224 %225 = OpLabel -%262 = OpLoad %10 %203 -%263 = OpCompositeConstruct %4 %262 %48 -%264 = OpAccessChain %199 %216 %114 -%265 = OpLoad %4 %264 -%266 = OpFMul %4 %263 %265 -OpStore %213 %266 +%258 = OpLoad %7 %218 +%259 = OpIAdd %7 %258 %114 +OpStore %218 %259 +OpBranch %222 +%223 = OpLabel +%260 = OpLoad %10 %217 +%261 = OpCompositeConstruct %4 %260 %48 +%262 = OpAccessChain %197 %212 %114 +%263 = OpLoad %4 %262 +%264 = OpFMul %4 %261 %263 +OpStore %209 %264 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/skybox.spvasm b/tests/out/spv/skybox.spvasm index dda9382c6..4d541321a 100644 --- a/tests/out/spv/skybox.spvasm +++ b/tests/out/spv/skybox.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.0 ; Generator: rspirv -; Bound: 97 +; Bound: 98 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %33 "vs_main" %26 %29 %31 -OpEntryPoint Fragment %89 "fs_main" %82 %85 %88 -OpExecutionMode %89 OriginUpperLeft +OpEntryPoint Vertex %29 "vs_main" %22 %25 %27 +OpEntryPoint Fragment %90 "fs_main" %83 %86 %89 +OpExecutionMode %90 OriginUpperLeft OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpMemberDecorate %8 0 Offset 0 @@ -24,12 +24,12 @@ OpDecorate %17 DescriptorSet 0 OpDecorate %17 Binding 1 OpDecorate %19 DescriptorSet 0 OpDecorate %19 Binding 2 -OpDecorate %26 BuiltIn VertexIndex -OpDecorate %29 BuiltIn Position -OpDecorate %31 Location 0 -OpDecorate %82 BuiltIn FragCoord -OpDecorate %85 Location 0 -OpDecorate %88 Location 0 +OpDecorate %22 BuiltIn VertexIndex +OpDecorate %25 BuiltIn Position +OpDecorate %27 Location 0 +OpDecorate %83 BuiltIn FragCoord +OpDecorate %86 Location 0 +OpDecorate %89 Location 0 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -49,90 +49,91 @@ OpDecorate %88 Location 0 %17 = OpVariable %18 UniformConstant %20 = OpTypePointer UniformConstant %13 %19 = OpVariable %20 UniformConstant -%22 = OpTypePointer Function %10 -%23 = OpConstantNull %10 -%27 = OpTypePointer Input %9 -%26 = OpVariable %27 Input -%30 = OpTypePointer Output %3 -%29 = OpVariable %30 Output -%32 = OpTypePointer Output %5 -%31 = OpVariable %32 Output -%34 = OpTypeFunction %2 -%35 = OpTypePointer Uniform %8 -%36 = OpConstant %9 0 -%38 = OpConstant %10 2 -%39 = OpConstant %10 1 -%40 = OpConstant %4 4.0 -%41 = OpConstant %4 1.0 -%42 = OpConstant %4 0.0 -%57 = OpTypePointer Uniform %7 -%58 = OpTypePointer Uniform %3 -%59 = OpConstant %9 1 -%66 = OpConstant %9 2 -%83 = OpTypePointer Input %3 -%82 = OpVariable %83 Input -%86 = OpTypePointer Input %5 -%85 = OpVariable %86 Input -%88 = OpVariable %30 Output -%94 = OpTypeSampledImage %12 -%33 = OpFunction %2 None %34 -%25 = OpLabel -%21 = OpVariable %22 Function %23 -%24 = OpVariable %22 Function %23 -%28 = OpLoad %9 %26 -%37 = OpAccessChain %35 %14 %36 -OpBranch %43 -%43 = OpLabel -%44 = OpBitcast %10 %28 -%45 = OpSDiv %10 %44 %38 -OpStore %21 %45 -%46 = OpBitcast %10 %28 -%47 = OpBitwiseAnd %10 %46 %39 -OpStore %24 %47 -%48 = OpLoad %10 %21 -%49 = OpConvertSToF %4 %48 -%50 = OpFMul %4 %49 %40 -%51 = OpFSub %4 %50 %41 -%52 = OpLoad %10 %24 -%53 = OpConvertSToF %4 %52 -%54 = OpFMul %4 %53 %40 -%55 = OpFSub %4 %54 %41 -%56 = OpCompositeConstruct %3 %51 %55 %42 %41 -%60 = OpAccessChain %58 %37 %59 %36 -%61 = OpLoad %3 %60 -%62 = OpVectorShuffle %5 %61 %61 0 1 2 -%63 = OpAccessChain %58 %37 %59 %59 -%64 = OpLoad %3 %63 -%65 = OpVectorShuffle %5 %64 %64 0 1 2 -%67 = OpAccessChain %58 %37 %59 %66 -%68 = OpLoad %3 %67 -%69 = OpVectorShuffle %5 %68 %68 0 1 2 -%70 = OpCompositeConstruct %11 %62 %65 %69 -%71 = OpTranspose %11 %70 -%72 = OpAccessChain %57 %37 %36 -%73 = OpLoad %7 %72 -%74 = OpMatrixTimesVector %3 %73 %56 -%75 = OpVectorShuffle %5 %74 %74 0 1 2 -%76 = OpMatrixTimesVector %5 %71 %75 -%77 = OpCompositeConstruct %6 %56 %76 -%78 = OpCompositeExtract %3 %77 0 -OpStore %29 %78 -%79 = OpCompositeExtract %5 %77 1 -OpStore %31 %79 +%23 = OpTypePointer Input %9 +%22 = OpVariable %23 Input +%26 = OpTypePointer Output %3 +%25 = OpVariable %26 Output +%28 = OpTypePointer Output %5 +%27 = OpVariable %28 Output +%30 = OpTypeFunction %2 +%31 = OpTypePointer Uniform %8 +%32 = OpConstant %9 0 +%34 = OpConstant %10 2 +%35 = OpConstant %10 1 +%36 = OpConstant %4 4.0 +%37 = OpConstant %4 1.0 +%38 = OpConstant %4 0.0 +%40 = OpTypePointer Function %10 +%41 = OpConstantNull %10 +%43 = OpConstantNull %10 +%58 = OpTypePointer Uniform %7 +%59 = OpTypePointer Uniform %3 +%60 = OpConstant %9 1 +%67 = OpConstant %9 2 +%84 = OpTypePointer Input %3 +%83 = OpVariable %84 Input +%87 = OpTypePointer Input %5 +%86 = OpVariable %87 Input +%89 = OpVariable %26 Output +%95 = OpTypeSampledImage %12 +%29 = OpFunction %2 None %30 +%21 = OpLabel +%39 = OpVariable %40 Function %41 +%42 = OpVariable %40 Function %43 +%24 = OpLoad %9 %22 +%33 = OpAccessChain %31 %14 %32 +OpBranch %44 +%44 = OpLabel +%45 = OpBitcast %10 %24 +%46 = OpSDiv %10 %45 %34 +OpStore %39 %46 +%47 = OpBitcast %10 %24 +%48 = OpBitwiseAnd %10 %47 %35 +OpStore %42 %48 +%49 = OpLoad %10 %39 +%50 = OpConvertSToF %4 %49 +%51 = OpFMul %4 %50 %36 +%52 = OpFSub %4 %51 %37 +%53 = OpLoad %10 %42 +%54 = OpConvertSToF %4 %53 +%55 = OpFMul %4 %54 %36 +%56 = OpFSub %4 %55 %37 +%57 = OpCompositeConstruct %3 %52 %56 %38 %37 +%61 = OpAccessChain %59 %33 %60 %32 +%62 = OpLoad %3 %61 +%63 = OpVectorShuffle %5 %62 %62 0 1 2 +%64 = OpAccessChain %59 %33 %60 %60 +%65 = OpLoad %3 %64 +%66 = OpVectorShuffle %5 %65 %65 0 1 2 +%68 = OpAccessChain %59 %33 %60 %67 +%69 = OpLoad %3 %68 +%70 = OpVectorShuffle %5 %69 %69 0 1 2 +%71 = OpCompositeConstruct %11 %63 %66 %70 +%72 = OpTranspose %11 %71 +%73 = OpAccessChain %58 %33 %32 +%74 = OpLoad %7 %73 +%75 = OpMatrixTimesVector %3 %74 %57 +%76 = OpVectorShuffle %5 %75 %75 0 1 2 +%77 = OpMatrixTimesVector %5 %72 %76 +%78 = OpCompositeConstruct %6 %57 %77 +%79 = OpCompositeExtract %3 %78 0 +OpStore %25 %79 +%80 = OpCompositeExtract %5 %78 1 +OpStore %27 %80 OpReturn OpFunctionEnd -%89 = OpFunction %2 None %34 -%80 = OpLabel -%84 = OpLoad %3 %82 -%87 = OpLoad %5 %85 -%81 = OpCompositeConstruct %6 %84 %87 -%90 = OpLoad %12 %17 -%91 = OpLoad %13 %19 -OpBranch %92 -%92 = OpLabel -%93 = OpCompositeExtract %5 %81 1 -%95 = OpSampledImage %94 %90 %91 -%96 = OpImageSampleImplicitLod %3 %95 %93 -OpStore %88 %96 +%90 = OpFunction %2 None %30 +%81 = OpLabel +%85 = OpLoad %3 %83 +%88 = OpLoad %5 %86 +%82 = OpCompositeConstruct %6 %85 %88 +%91 = OpLoad %12 %17 +%92 = OpLoad %13 %19 +OpBranch %93 +%93 = OpLabel +%94 = OpCompositeExtract %5 %82 1 +%96 = OpSampledImage %95 %91 %92 +%97 = OpImageSampleImplicitLod %3 %96 %94 +OpStore %89 %97 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/standard.spvasm b/tests/out/spv/standard.spvasm index 07bb2a790..50026e6dc 100644 --- a/tests/out/spv/standard.spvasm +++ b/tests/out/spv/standard.spvasm @@ -1,66 +1,68 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 40 +; Bound: 42 OpCapability Shader OpCapability DerivativeControl %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %22 "derivatives" %17 %20 -OpExecutionMode %22 OriginUpperLeft -OpDecorate %17 BuiltIn FragCoord -OpDecorate %20 Location 0 +OpEntryPoint Fragment %17 "derivatives" %12 %15 +OpExecutionMode %17 OriginUpperLeft +OpDecorate %12 BuiltIn FragCoord +OpDecorate %15 Location 0 %2 = OpTypeVoid %3 = OpTypeBool %5 = OpTypeFloat 32 %4 = OpTypeVector %5 4 %8 = OpTypeFunction %3 %9 = OpConstantTrue %3 -%12 = OpTypePointer Function %4 -%13 = OpConstantNull %4 -%18 = OpTypePointer Input %4 -%17 = OpVariable %18 Input -%21 = OpTypePointer Output %4 -%20 = OpVariable %21 Output -%23 = OpTypeFunction %2 +%13 = OpTypePointer Input %4 +%12 = OpVariable %13 Input +%16 = OpTypePointer Output %4 +%15 = OpVariable %16 Output +%18 = OpTypeFunction %2 +%20 = OpTypePointer Function %4 +%21 = OpConstantNull %4 +%23 = OpConstantNull %4 +%25 = OpConstantNull %4 %7 = OpFunction %3 None %8 %6 = OpLabel OpBranch %10 %10 = OpLabel OpReturnValue %9 OpFunctionEnd -%22 = OpFunction %2 None %23 -%16 = OpLabel -%11 = OpVariable %12 Function %13 -%14 = OpVariable %12 Function %13 -%15 = OpVariable %12 Function %13 -%19 = OpLoad %4 %17 -OpBranch %24 -%24 = OpLabel -%25 = OpDPdxCoarse %4 %19 -OpStore %11 %25 -%26 = OpDPdyCoarse %4 %19 -OpStore %14 %26 -%27 = OpFwidthCoarse %4 %19 -OpStore %15 %27 -%28 = OpDPdxFine %4 %19 -OpStore %11 %28 -%29 = OpDPdyFine %4 %19 -OpStore %14 %29 -%30 = OpFwidthFine %4 %19 -OpStore %15 %30 -%31 = OpDPdx %4 %19 -OpStore %11 %31 -%32 = OpDPdy %4 %19 -OpStore %14 %32 -%33 = OpFwidth %4 %19 -OpStore %15 %33 -%34 = OpFunctionCall %3 %7 -%35 = OpLoad %4 %11 -%36 = OpLoad %4 %14 -%37 = OpFAdd %4 %35 %36 -%38 = OpLoad %4 %15 -%39 = OpFMul %4 %37 %38 -OpStore %20 %39 +%17 = OpFunction %2 None %18 +%11 = OpLabel +%19 = OpVariable %20 Function %21 +%22 = OpVariable %20 Function %23 +%24 = OpVariable %20 Function %25 +%14 = OpLoad %4 %12 +OpBranch %26 +%26 = OpLabel +%27 = OpDPdxCoarse %4 %14 +OpStore %19 %27 +%28 = OpDPdyCoarse %4 %14 +OpStore %22 %28 +%29 = OpFwidthCoarse %4 %14 +OpStore %24 %29 +%30 = OpDPdxFine %4 %14 +OpStore %19 %30 +%31 = OpDPdyFine %4 %14 +OpStore %22 %31 +%32 = OpFwidthFine %4 %14 +OpStore %24 %32 +%33 = OpDPdx %4 %14 +OpStore %19 %33 +%34 = OpDPdy %4 %14 +OpStore %22 %34 +%35 = OpFwidth %4 %14 +OpStore %24 %35 +%36 = OpFunctionCall %3 %7 +%37 = OpLoad %4 %19 +%38 = OpLoad %4 %22 +%39 = OpFAdd %4 %37 %38 +%40 = OpLoad %4 %24 +%41 = OpFMul %4 %39 %40 +OpStore %15 %41 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/texture-arg.spvasm b/tests/out/spv/texture-arg.spvasm index 485b2d7d9..88832eb19 100644 --- a/tests/out/spv/texture-arg.spvasm +++ b/tests/out/spv/texture-arg.spvasm @@ -30,6 +30,7 @@ OpDecorate %26 Location 0 %10 = OpVariable %11 UniformConstant %18 = OpTypeFunction %6 %9 %11 %19 = OpConstant %4 0.0 +%20 = OpConstantComposite %7 %19 %19 %22 = OpTypeSampledImage %3 %27 = OpTypePointer Output %6 %26 = OpVariable %27 Output @@ -40,11 +41,10 @@ OpDecorate %26 Location 0 %12 = OpLabel %14 = OpLoad %3 %13 %16 = OpLoad %5 %15 -OpBranch %20 -%20 = OpLabel -%21 = OpCompositeConstruct %7 %19 %19 +OpBranch %21 +%21 = OpLabel %23 = OpSampledImage %22 %14 %16 -%24 = OpImageSampleImplicitLod %6 %23 %21 +%24 = OpImageSampleImplicitLod %6 %23 %20 OpReturnValue %24 OpFunctionEnd %28 = OpFunction %2 None %29 diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index c01c4247c..ba268dca9 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -37,10 +37,9 @@ var nested_mat_cx2_: MatCx2InArray; var val: u32; fn test_matrix_within_struct_accesses() { - var idx: i32; - var t: Baz; + var idx: i32 = 1; + var t: Baz = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); - idx = 1; let _e3 = idx; idx = (_e3 - 1); let l0_ = baz.m; @@ -55,7 +54,6 @@ fn test_matrix_within_struct_accesses() { let _e36 = idx; let _e38 = idx; let l6_ = baz.m[_e36][_e38]; - t = Baz(mat3x2(vec2(1.0), vec2(2.0), vec2(3.0))); let _e51 = idx; idx = (_e51 + 1); t.m = mat3x2(vec2(6.0), vec2(5.0), vec2(4.0)); @@ -74,10 +72,9 @@ fn test_matrix_within_struct_accesses() { } fn test_matrix_within_array_within_struct_accesses() { - var idx_1: i32; - var t_1: MatCx2InArray; + var idx_1: i32 = 1; + var t_1: MatCx2InArray = MatCx2InArray(array, 2>()); - idx_1 = 1; let _e3 = idx_1; idx_1 = (_e3 - 1); let l0_1 = nested_mat_cx2_.am; @@ -93,7 +90,6 @@ fn test_matrix_within_array_within_struct_accesses() { let _e46 = idx_1; let _e48 = idx_1; let l7_ = nested_mat_cx2_.am[0][_e46][_e48]; - t_1 = MatCx2InArray(array, 2>()); let _e55 = idx_1; idx_1 = (_e55 + 1); t_1.am = array, 2>(); @@ -133,10 +129,9 @@ fn assign_array_through_ptr_fn(foo_2: ptr, 2>>) { @vertex fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { - var foo: f32; + var foo: f32 = 0.0; var c2_: array; - foo = 0.0; let baz_1 = foo; foo = 1.0; test_matrix_within_struct_accesses(); @@ -167,9 +162,8 @@ fn foo_frag() -> @location(0) vec4 { @compute @workgroup_size(1, 1, 1) fn assign_through_ptr() { - var arr: array, 2>; + var arr: array, 2> = array, 2>(vec4(6.0), vec4(7.0)); - arr = array, 2>(vec4(6.0), vec4(7.0)); assign_through_ptr_fn((&val)); assign_array_through_ptr_fn((&arr)); return; diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/tests/out/wgsl/atomicCompareExchange.wgsl index b659bed2b..f68017028 100644 --- a/tests/out/wgsl/atomicCompareExchange.wgsl +++ b/tests/out/wgsl/atomicCompareExchange.wgsl @@ -7,11 +7,10 @@ var arr_u32_: array, 128>; @compute @workgroup_size(1, 1, 1) fn test_atomic_compare_exchange_i32_() { - var i: u32; + var i: u32 = 0u; var old: i32; - var exchanged: bool; + var exchanged: bool = false; - i = 0u; loop { let _e2 = i; if (_e2 < SIZE) { @@ -50,11 +49,10 @@ fn test_atomic_compare_exchange_i32_() { @compute @workgroup_size(1, 1, 1) fn test_atomic_compare_exchange_u32_() { - var i_1: u32; + var i_1: u32 = 0u; var old_1: u32; - var exchanged_1: bool; + var exchanged_1: bool = false; - i_1 = 0u; loop { let _e2 = i_1; if (_e2 < SIZE) { diff --git a/tests/out/wgsl/binding-arrays.wgsl b/tests/out/wgsl/binding-arrays.wgsl index e9513c725..c7a01fc5c 100644 --- a/tests/out/wgsl/binding-arrays.wgsl +++ b/tests/out/wgsl/binding-arrays.wgsl @@ -27,17 +27,13 @@ var uni: UniformIndex; @fragment fn main(fragment_in: FragmentIn) -> @location(0) vec4 { - var u1_: u32; - var u2_: vec2; - var v1_: f32; - var v4_: vec4; + var u1_: u32 = 0u; + var u2_: vec2 = vec2(0u); + var v1_: f32 = 0.0; + var v4_: vec4 = vec4(0.0); let uniform_index = uni.index; let non_uniform_index = fragment_in.index; - u1_ = 0u; - u2_ = vec2(0u); - v1_ = 0.0; - v4_ = vec4(0.0); let uv = vec2(0.0); let pix = vec2(0); let _e21 = textureDimensions(texture_array_unbounded[0]); diff --git a/tests/out/wgsl/binding-buffer-arrays.wgsl b/tests/out/wgsl/binding-buffer-arrays.wgsl index d28237d75..317a38623 100644 --- a/tests/out/wgsl/binding-buffer-arrays.wgsl +++ b/tests/out/wgsl/binding-buffer-arrays.wgsl @@ -17,11 +17,10 @@ var uni: UniformIndex; @fragment fn main(fragment_in: FragmentIn) -> @location(0) @interpolate(flat) u32 { - var u1_: u32; + var u1_: u32 = 0u; let uniform_index = uni.index; let non_uniform_index = fragment_in.index; - u1_ = 0u; let _e10 = storage_array[0].x; let _e11 = u1_; u1_ = (_e11 + _e10); diff --git a/tests/out/wgsl/bitcast.wgsl b/tests/out/wgsl/bitcast.wgsl index a8699e0a9..a426c26ca 100644 --- a/tests/out/wgsl/bitcast.wgsl +++ b/tests/out/wgsl/bitcast.wgsl @@ -1,24 +1,15 @@ @compute @workgroup_size(1, 1, 1) fn main() { - var i2_: vec2; - var i3_: vec3; - var i4_: vec4; - var u2_: vec2; - var u3_: vec3; - var u4_: vec4; - var f2_: vec2; - var f3_: vec3; - var f4_: vec4; + var i2_: vec2 = vec2(0); + var i3_: vec3 = vec3(0); + var i4_: vec4 = vec4(0); + var u2_: vec2 = vec2(0u); + var u3_: vec3 = vec3(0u); + var u4_: vec4 = vec4(0u); + var f2_: vec2 = vec2(0.0); + var f3_: vec3 = vec3(0.0); + var f4_: vec4 = vec4(0.0); - i2_ = vec2(0); - i3_ = vec3(0); - i4_ = vec4(0); - u2_ = vec2(0u); - u3_ = vec3(0u); - u4_ = vec4(0u); - f2_ = vec2(0.0); - f3_ = vec3(0.0); - f4_ = vec4(0.0); let _e27 = i2_; u2_ = bitcast>(_e27); let _e29 = i3_; diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl index 4458a0740..fb4f396a5 100644 --- a/tests/out/wgsl/bits.wgsl +++ b/tests/out/wgsl/bits.wgsl @@ -1,26 +1,16 @@ @compute @workgroup_size(1, 1, 1) fn main() { - var i: i32; - var i2_: vec2; - var i3_: vec3; - var i4_: vec4; - var u: u32; - var u2_: vec2; - var u3_: vec3; - var u4_: vec4; - var f2_: vec2; - var f4_: vec4; + var i: i32 = 0; + var i2_: vec2 = vec2(0); + var i3_: vec3 = vec3(0); + var i4_: vec4 = vec4(0); + var u: u32 = 0u; + var u2_: vec2 = vec2(0u); + var u3_: vec3 = vec3(0u); + var u4_: vec4 = vec4(0u); + var f2_: vec2 = vec2(0.0); + var f4_: vec4 = vec4(0.0); - i = 0; - i2_ = vec2(0); - i3_ = vec3(0); - i4_ = vec4(0); - u = 0u; - u2_ = vec2(0u); - u3_ = vec3(0u); - u4_ = vec4(0u); - f2_ = vec2(0.0); - f4_ = vec4(0.0); let _e28 = f4_; u = pack4x8snorm(_e28); let _e30 = f4_; diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl index af5d5247d..b87d3ed91 100644 --- a/tests/out/wgsl/boids.wgsl +++ b/tests/out/wgsl/boids.wgsl @@ -30,14 +30,14 @@ var particlesDst: Particles; fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { var vPos: vec2; var vVel: vec2; - var cMass: vec2; - var cVel: vec2; - var colVel: vec2; - var cMassCount: i32; - var cVelCount: i32; + var cMass: vec2 = vec2(0.0, 0.0); + var cVel: vec2 = vec2(0.0, 0.0); + var colVel: vec2 = vec2(0.0, 0.0); + var cMassCount: i32 = 0; + var cVelCount: i32 = 0; var pos: vec2; var vel: vec2; - var i: u32; + var i: u32 = 0u; let index = global_invocation_id.x; if (index >= NUM_PARTICLES) { @@ -47,12 +47,6 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { vPos = _e8; let _e14 = particlesSrc.particles[index].vel; vVel = _e14; - cMass = vec2(0.0, 0.0); - cVel = vec2(0.0, 0.0); - colVel = vec2(0.0, 0.0); - cMassCount = 0; - cVelCount = 0; - i = 0u; loop { let _e36 = i; if (_e36 >= NUM_PARTICLES) { diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl index a25f79536..477317594 100644 --- a/tests/out/wgsl/collatz.wgsl +++ b/tests/out/wgsl/collatz.wgsl @@ -7,10 +7,9 @@ var v_indices: PrimeIndices; fn collatz_iterations(n_base: u32) -> u32 { var n: u32; - var i: u32; + var i: u32 = 0u; n = n_base; - i = 0u; loop { let _e4 = n; if (_e4 > 1u) { diff --git a/tests/out/wgsl/dualsource.wgsl b/tests/out/wgsl/dualsource.wgsl index d7cc4cbfd..8d03f244a 100644 --- a/tests/out/wgsl/dualsource.wgsl +++ b/tests/out/wgsl/dualsource.wgsl @@ -5,11 +5,9 @@ struct FragmentOutput { @fragment fn main(@builtin(position) position: vec4) -> FragmentOutput { - var color: vec4; - var mask: vec4; + var color: vec4 = vec4(0.4, 0.3, 0.2, 0.1); + var mask: vec4 = vec4(0.9, 0.8, 0.7, 0.6); - color = vec4(0.4, 0.3, 0.2, 0.1); - mask = vec4(0.9, 0.8, 0.7, 0.6); let _e13 = color; let _e14 = mask; return FragmentOutput(_e13, _e14); diff --git a/tests/out/wgsl/expressions.frag.wgsl b/tests/out/wgsl/expressions.frag.wgsl index d947a0df7..1a1a6fd3b 100644 --- a/tests/out/wgsl/expressions.frag.wgsl +++ b/tests/out/wgsl/expressions.frag.wgsl @@ -407,8 +407,8 @@ fn indexConstantNonConstantIndex(i: i32) { i_1 = i; let _e6 = i_1; - let _e10 = local_5.array_[_e6]; - a_26 = _e10; + let _e11 = local_5.array_[_e6]; + a_26 = _e11; return; } diff --git a/tests/out/wgsl/globals.wgsl b/tests/out/wgsl/globals.wgsl index af72c0cb8..562533156 100644 --- a/tests/out/wgsl/globals.wgsl +++ b/tests/out/wgsl/globals.wgsl @@ -27,10 +27,9 @@ fn test_msl_packed_vec3_as_arg(arg: vec3) { } fn test_msl_packed_vec3_() { - var idx: i32; + var idx: i32 = 1; alignment.v3_ = vec3(1.0); - idx = 1; alignment.v3_.x = 1.0; alignment.v3_.x = 2.0; let _e16 = idx; @@ -47,8 +46,8 @@ fn test_msl_packed_vec3_() { @compute @workgroup_size(1, 1, 1) fn main() { - var Foo: f32; - var at: bool; + var Foo: f32 = 1.0; + var at: bool = true; test_msl_packed_vec3_(); let _e5 = global_nested_arrays_of_matrices_4x2_[0][0]; @@ -68,7 +67,5 @@ fn main() { alignment.v1_ = 4.0; wg[1] = f32(arrayLength((&dummy))); atomicStore((&at_1), 2u); - Foo = 1.0; - at = true; return; } diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl index 8654c13d9..96713aae9 100644 --- a/tests/out/wgsl/interface.wgsl +++ b/tests/out/wgsl/interface.wgsl @@ -40,9 +40,8 @@ fn compute(@builtin(global_invocation_id) global_id: vec3, @builtin(local_i @vertex fn vertex_two_structs(in1_: Input1_, in2_: Input2_) -> @builtin(position) @invariant vec4 { - var index: u32; + var index: u32 = 2u; - index = 2u; let _e8: u32 = index; return vec4(f32(in1_.index), f32(in2_.index), f32(_e8), 0.0); } diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/tests/out/wgsl/lexical-scopes.wgsl index 22e59030c..f3756b61b 100644 --- a/tests/out/wgsl/lexical-scopes.wgsl +++ b/tests/out/wgsl/lexical-scopes.wgsl @@ -21,9 +21,8 @@ fn loopLexicalScope(a_2: bool) { } fn forLexicalScope(a_3: f32) { - var a_4: i32; + var a_4: i32 = 0; - a_4 = 0; loop { let _e3 = a_4; if (_e3 < 1) { diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index caedce204..9c07526d3 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -22,9 +22,8 @@ fn splat() -> vec4 { } fn splat_assignment() -> vec2 { - var a: vec2; + var a: vec2 = vec2(2.0); - a = vec2(2.0); let _e4 = a; a = (_e4 + vec2(1.0)); let _e8 = a; @@ -144,10 +143,9 @@ fn comparison() { } fn assignment() { - var a_1: i32; - var vec0_: vec3; + var a_1: i32 = 1; + var vec0_: vec3 = vec3(); - a_1 = 1; let _e3 = a_1; a_1 = (_e3 + 1); let _e6 = a_1; @@ -174,7 +172,6 @@ fn assignment() { a_1 = (_e33 + 1); let _e36 = a_1; a_1 = (_e36 - 1); - vec0_ = vec3(); let _e42 = vec0_.y; vec0_.y = (_e42 + 1); let _e46 = vec0_.y; diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl index 8000e785f..b768fab2f 100644 --- a/tests/out/wgsl/shadow.wgsl +++ b/tests/out/wgsl/shadow.wgsl @@ -64,12 +64,10 @@ fn vs_main(@location(0) @interpolate(flat) position: vec4, @location(1) @in @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4 { - var color: vec3; - var i: u32; + var color: vec3 = c_ambient; + var i: u32 = 0u; let normal_1 = normalize(in.world_normal); - color = c_ambient; - i = 0u; loop { let _e7 = i; let _e11 = u_globals.num_lights.x; @@ -99,12 +97,10 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { @fragment fn fs_main_without_storage(in_1: VertexOutput) -> @location(0) vec4 { - var color_1: vec3; - var i_1: u32; + var color_1: vec3 = c_ambient; + var i_1: u32 = 0u; let normal_2 = normalize(in_1.world_normal); - color_1 = c_ambient; - i_1 = 0u; loop { let _e7 = i_1; let _e11 = u_globals.num_lights.x; From fe7bc01d279c43c366f3ee442685413479947c2c Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 3 May 2023 16:53:17 +0200 Subject: [PATCH 2129/2212] [glsl-in] const eval as soon as possible --- src/front/glsl/builtins.rs | 2 +- src/front/glsl/context.rs | 82 ++-- src/front/glsl/functions.rs | 10 +- src/front/glsl/parser.rs | 6 +- src/front/glsl/parser/declarations.rs | 32 +- src/front/glsl/types.rs | 95 +++-- src/front/glsl/variables.rs | 2 +- src/proc/constant_evaluator.rs | 145 ------- tests/out/wgsl/246-collatz.comp.wgsl | 11 +- tests/out/wgsl/277-casting.frag.wgsl | 2 +- tests/out/wgsl/280-matrix-cast.frag.wgsl | 3 +- .../wgsl/900-implicit-conversions.frag.wgsl | 4 +- tests/out/wgsl/bevy-pbr.frag.wgsl | 22 +- tests/out/wgsl/bits_glsl.frag.wgsl | 40 +- tests/out/wgsl/buffer.frag.wgsl | 2 +- tests/out/wgsl/constant-array-size.frag.wgsl | 2 +- tests/out/wgsl/declarations.frag.wgsl | 4 +- tests/out/wgsl/expressions.frag.wgsl | 50 ++- tests/out/wgsl/fma.frag.wgsl | 9 +- tests/out/wgsl/images.frag.wgsl | 12 +- tests/out/wgsl/long-form-matrix.frag.wgsl | 31 +- tests/out/wgsl/prepostfix.frag.wgsl | 5 +- tests/out/wgsl/quad_glsl.vert.wgsl | 10 +- tests/out/wgsl/sampler-functions.frag.wgsl | 2 +- tests/out/wgsl/samplers.frag.wgsl | 400 ++++++++---------- 25 files changed, 416 insertions(+), 567 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index ff386e2e1..8d57b66da 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1795,7 +1795,7 @@ impl MacroCall { true => { let offset_arg = args[num_args]; num_args += 1; - match ctx.eval_constant(offset_arg, meta) { + match ctx.lift_up_const_expression(offset_arg) { Ok(v) => Some(v), Err(e) => { frontend.errors.push(e); diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index a13e6ac5b..d767f9358 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -71,15 +71,17 @@ pub struct Context<'a> { pub symbol_table: crate::front::SymbolTable, pub samplers: FastHashMap, Handle>, + pub const_typifier: Typifier, pub typifier: Typifier, emitter: Emitter, stmt_ctx: Option, pub body: Block, pub module: &'a mut crate::Module, + pub is_const: bool, } impl<'a> Context<'a> { - pub fn new(frontend: &Frontend, module: &'a mut crate::Module) -> Result { + pub fn new(frontend: &Frontend, module: &'a mut crate::Module, is_const: bool) -> Result { let mut this = Context { expressions: Arena::new(), locals: Arena::new(), @@ -91,11 +93,13 @@ impl<'a> Context<'a> { symbol_table: crate::front::SymbolTable::default(), samplers: FastHashMap::default(), + const_typifier: Typifier::new(), typifier: Typifier::new(), emitter: Emitter::default(), stmt_ctx: Some(StmtContext::new()), body: Block::new(), module, + is_const: false, }; this.emit_start(); @@ -103,6 +107,7 @@ impl<'a> Context<'a> { for &(ref name, lookup) in frontend.global_variables.iter() { this.add_global(name, lookup)? } + this.is_const = is_const; Ok(this) } @@ -241,15 +246,43 @@ impl<'a> Context<'a> { } pub fn add_expression(&mut self, expr: Expression, meta: Span) -> Result> { - let needs_pre_emit = expr.needs_pre_emit(); - if needs_pre_emit { - self.emit_end(); + let mut append = |arena: &mut Arena, expr: Expression, span| { + let is_running = self.emitter.is_running(); + let needs_pre_emit = expr.needs_pre_emit(); + if is_running && needs_pre_emit { + self.body.extend(self.emitter.finish(arena)); + } + let h = arena.append(expr, span); + if is_running && needs_pre_emit { + self.emitter.start(arena); + } + h + }; + + let (expressions, const_expressions) = if self.is_const { + (&mut self.module.const_expressions, None) + } else { + (&mut self.expressions, Some(&self.module.const_expressions)) + }; + + let mut eval = crate::proc::ConstantEvaluator { + types: &mut self.module.types, + constants: &self.module.constants, + expressions, + const_expressions, + append: (!self.is_const).then_some(&mut append), + }; + + let res = eval.try_eval_and_append(&expr, meta).map_err(|e| Error { + kind: e.into(), + meta, + }); + + match res { + Ok(expr) => Ok(expr), + Err(e) if self.is_const => Err(e), + Err(_) => Ok(append(&mut self.expressions, expr, meta)), } - let handle = self.expressions.append(expr, meta); - if needs_pre_emit { - self.emit_start(); - } - Ok(handle) } /// Add variable to current scope @@ -513,13 +546,16 @@ impl<'a> Context<'a> { let handle = match *kind { HirExprKind::Access { base, index } => { - let (index, index_meta) = - self.lower_expect_inner(stmt, frontend, index, ExprPos::Rhs)?; + let (index, _) = self.lower_expect_inner(stmt, frontend, index, ExprPos::Rhs)?; let maybe_constant_index = match pos { // Don't try to generate `AccessIndex` if in a LHS position, since it // wouldn't produce a pointer. ExprPos::Lhs => None, - _ => self.eval_constant(index, index_meta).ok(), + _ => self + .module + .to_ctx() + .eval_expr_to_u32_from(index, &self.expressions) + .ok(), }; let base = self @@ -532,15 +568,7 @@ impl<'a> Context<'a> { .0; let pointer = maybe_constant_index - .and_then(|const_expr| { - Some(self.add_expression( - Expression::AccessIndex { - base, - index: self.module.to_ctx().eval_expr_to_u32(const_expr).ok()?, - }, - meta, - )) - }) + .map(|index| self.add_expression(Expression::AccessIndex { base, index }, meta)) .unwrap_or_else(|| { self.add_expression(Expression::Access { base, index }, meta) })?; @@ -582,8 +610,8 @@ impl<'a> Context<'a> { self.typifier_grow(left, left_meta)?; self.typifier_grow(right, right_meta)?; - let left_inner = self.typifier.get(left, &self.module.types); - let right_inner = self.typifier.get(right, &self.module.types); + let left_inner = self.get_type(left); + let right_inner = self.get_type(right); match (left_inner, right_inner) { ( @@ -1010,7 +1038,13 @@ impl<'a> Context<'a> { _ if var.load => { self.add_expression(Expression::Load { pointer: var.expr }, meta)? } - ExprPos::Rhs => var.expr, + ExprPos::Rhs => { + if let Some((constant, _)) = self.is_const.then_some(var.constant).flatten() { + self.add_expression(Expression::Constant(constant), meta)? + } else { + var.expr + } + } }, HirExprKind::Call(ref call) if pos != ExprPos::Lhs => { let maybe_expr = frontend.function_or_constructor_call( diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index fe96d2c4e..8bbef9162 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -531,10 +531,8 @@ impl Frontend { } // Check if the passed arguments require any special variations - let mut variations = builtin_required_variations( - args.iter() - .map(|&(expr, _)| ctx.typifier.get(expr, &ctx.module.types)), - ); + let mut variations = + builtin_required_variations(args.iter().map(|&(expr, _)| ctx.get_type(expr))); // Initiate the declaration if it wasn't previously initialized and inject builtins let declaration = self.lookup_function.entry(name.clone()).or_insert_with(|| { @@ -592,7 +590,7 @@ impl Frontend { ctx.typifier_grow(call_argument.0, call_argument.1)?; let overload_param_ty = &ctx.module.types[*overload_parameter].inner; - let call_arg_ty = ctx.typifier.get(call_argument.0, &ctx.module.types); + let call_arg_ty = ctx.get_type(call_argument.0); log::trace!( "Testing parameter {}\n\tOverload = {:?}\n\tCall = {:?}", @@ -937,7 +935,7 @@ impl Frontend { ctx.typifier_grow(call_argument.0, call_argument.1)?; let overload_param_ty = &ctx.module.types[parameter_ty].inner; - let call_arg_ty = ctx.typifier.get(call_argument.0, &ctx.module.types); + let call_arg_ty = ctx.get_type(call_argument.0); let needs_conversion = call_arg_ty != overload_param_ty; let arg_scalar_comps = scalar_components(call_arg_ty); diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 075dce17e..391357668 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -166,7 +166,7 @@ impl<'source> ParsingContext<'source> { let mut module = Module::default(); // Body and expression arena for global initialization - let mut ctx = Context::new(frontend, &mut module)?; + let mut ctx = Context::new(frontend, &mut module, false)?; while self.peek(frontend).is_some() { self.parse_external_declaration(frontend, &mut ctx)?; @@ -220,13 +220,13 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, module: &mut Module, ) -> Result<(Handle, Span)> { - let mut ctx = Context::new(frontend, module)?; + let mut ctx = Context::new(frontend, module, true)?; let mut stmt_ctx = ctx.stmt_ctx(); let expr = self.parse_conditional(frontend, &mut ctx, &mut stmt_ctx, None)?; let (root, meta) = ctx.lower_expect(stmt_ctx, frontend, expr, ExprPos::Rhs)?; - Ok((ctx.eval_constant(root, meta)?, meta)) + Ok((root, meta)) } } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index 75e18ea3b..da75b0ba6 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -221,9 +221,15 @@ impl<'source> ParsingContext<'source> { // returns Ok(None) rather than an error if there is not one self.parse_array_specifier(frontend, ctx.ctx, &mut meta, &mut ty)?; + let is_global_const = + ctx.qualifiers.storage.0 == StorageQualifier::Const && ctx.external; + let init = self .bump_if(frontend, TokenValue::Assign) .map::, _>(|_| { + let prev_const = ctx.ctx.is_const; + ctx.ctx.is_const = is_global_const; + let (mut expr, init_meta) = self.parse_initializer(frontend, ty, ctx.ctx)?; let scalar_components = scalar_components(&ctx.ctx.module.types[ty].inner); @@ -232,32 +238,26 @@ impl<'source> ParsingContext<'source> { .implicit_conversion(&mut expr, init_meta, kind, width)?; } + ctx.ctx.is_const = prev_const; + meta.subsume(init_meta); - Ok((expr, init_meta)) + Ok(expr) }) .transpose()?; - let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; - let maybe_const_expr = if ctx.external { - if let Some((root, meta)) = init { - match ctx.ctx.eval_constant(root, meta) { - Ok(res) => Some(res), - // If the declaration is external (global scope) and is constant qualified - // then the initializer must be a constant expression - Err(err) if is_const => return Err(err), - _ => None, - } - } else { - None - } + let maybe_const_expr = if is_global_const { + init + } else if ctx.external { + init.and_then(|expr| ctx.ctx.lift_up_const_expression(expr).ok()) } else { None + // init.filter(|expr| ctx.ctx.expressions.is_const(*expr)) }; let pointer = ctx.add_var(frontend, ty, name, maybe_const_expr, meta)?; - if let Some((value, _)) = init.filter(|_| maybe_const_expr.is_none()) { + if let Some(value) = init.filter(|_| maybe_const_expr.is_none()) { ctx.ctx.emit_restart(); ctx.ctx.body.push(Statement::Store { pointer, value }, meta); } @@ -317,7 +317,7 @@ impl<'source> ParsingContext<'source> { let result = ty.map(|ty| FunctionResult { ty, binding: None }); - let mut context = Context::new(frontend, ctx.module)?; + let mut context = Context::new(frontend, ctx.module, false)?; self.parse_function_args(frontend, &mut context)?; diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index a8bb047e4..ffa879506 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -241,14 +241,36 @@ impl Context<'_> { pub(crate) fn typifier_grow(&mut self, expr: Handle, meta: Span) -> Result<()> { let resolve_ctx = ResolveContext::with_locals(self.module, &self.locals, &self.arguments); - self.typifier - .grow(expr, &self.expressions, &resolve_ctx) + let typifier = if self.is_const { + &mut self.const_typifier + } else { + &mut self.typifier + }; + + let expressions = if self.is_const { + &self.module.const_expressions + } else { + &self.expressions + }; + + typifier + .grow(expr, expressions, &resolve_ctx) .map_err(|error| Error { kind: ErrorKind::SemanticError(format!("Can't resolve type: {error:?}").into()), meta, }) } + pub(crate) fn get_type(&self, expr: Handle) -> &TypeInner { + let typifier = if self.is_const { + &self.const_typifier + } else { + &self.typifier + }; + + typifier.get(expr, &self.module.types) + } + /// Gets the type for the result of the `expr` expression /// /// Automatically grows the [`typifier`] to `expr` so calling @@ -262,7 +284,7 @@ impl Context<'_> { meta: Span, ) -> Result<&TypeInner> { self.typifier_grow(expr, meta)?; - Ok(self.typifier.get(expr, &self.module.types)) + Ok(self.get_type(expr)) } /// Gets the type handle for the result of the `expr` expression @@ -286,7 +308,14 @@ impl Context<'_> { meta: Span, ) -> Result> { self.typifier_grow(expr, meta)?; - Ok(self.typifier.register_type(expr, &mut self.module.types)) + + let typifier = if self.is_const { + &mut self.const_typifier + } else { + &mut self.typifier + }; + + Ok(typifier.register_type(expr, &mut self.module.types)) } /// Invalidates the cached type resolution for `expr` forcing a recomputation @@ -297,7 +326,13 @@ impl Context<'_> { ) -> Result<()> { let resolve_ctx = ResolveContext::with_locals(self.module, &self.locals, &self.arguments); - self.typifier + let typifier = if self.is_const { + &mut self.const_typifier + } else { + &mut self.typifier + }; + + typifier .invalidate(expr, &self.expressions, &resolve_ctx) .map_err(|error| Error { kind: ErrorKind::SemanticError(format!("Can't resolve type: {error:?}").into()), @@ -305,30 +340,36 @@ impl Context<'_> { }) } - pub(crate) fn eval_constant( + pub(crate) fn lift_up_const_expression( &mut self, - root: Handle, - meta: Span, + expr: Handle, ) -> Result> { - let mut solver = crate::proc::ConstantEvaluator { - types: &mut self.module.types, - expressions: &mut self.module.const_expressions, - constants: &mut self.module.constants, - const_expressions: Some(&self.expressions), - append: None::< - Box< - dyn FnMut( - &mut crate::Arena, - Expression, - Span, - ) -> Handle, - >, - >, - }; - - solver.eval(root).map_err(|e| Error { - kind: e.into(), - meta, + let meta = self.expressions.get_span(expr); + Ok(match self.expressions[expr] { + ref expr @ (Expression::Literal(_) + | Expression::Constant(_) + | Expression::ZeroValue(_)) => self.module.const_expressions.append(expr.clone(), meta), + Expression::Compose { ty, ref components } => { + let mut components = components.clone(); + for component in &mut components { + *component = self.lift_up_const_expression(*component)?; + } + self.module + .const_expressions + .append(Expression::Compose { ty, components }, meta) + } + Expression::Splat { size, value } => { + let value = self.lift_up_const_expression(value)?; + self.module + .const_expressions + .append(Expression::Splat { size, value }, meta) + } + _ => { + return Err(Error { + kind: ErrorKind::SemanticError("Expression is not const-expression".into()), + meta, + }) + } }) } } diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index 58cc31461..794f181b5 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -638,7 +638,7 @@ impl Frontend { LocalVariable { name: decl.name.clone(), ty: decl.ty, - init: None, + init: decl.init, }, decl.meta, ); diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 6778a0bf9..218252e1f 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -74,12 +74,6 @@ pub enum ConstantEvaluatorError { NotImplemented(String), } -#[derive(Clone, Copy)] -pub enum ExprType { - Regular, - Constant, -} - // Access // AccessIndex // Splat @@ -231,145 +225,6 @@ impl<'a, F: FnMut(&mut Arena, Expression, Span) -> Handle, - ) -> Result, ConstantEvaluatorError> { - self.eval_impl(expr, ExprType::Regular, true) - } - - pub fn eval_impl( - &mut self, - expr: Handle, - expr_type: ExprType, - top_level: bool, - ) -> Result, ConstantEvaluatorError> { - let expressions = match expr_type { - ExprType::Regular => self.const_expressions.unwrap(), - ExprType::Constant => self.expressions, - }; - let span = expressions.get_span(expr); - match expressions[expr] { - ref expression @ (Expression::Literal(_) | Expression::ZeroValue(_)) => match expr_type - { - ExprType::Regular => Ok(self.register_evaluated_expr(expression.clone(), span)), - ExprType::Constant => Ok(expr), - }, - Expression::Compose { ty, ref components } => match expr_type { - ExprType::Regular => { - let mut components = components.clone(); - for component in &mut components { - *component = self.eval_impl(*component, expr_type, false)?; - } - Ok(self.register_evaluated_expr(Expression::Compose { ty, components }, span)) - } - ExprType::Constant => Ok(expr), - }, - Expression::Constant(constant) => { - if top_level { - match expr_type { - ExprType::Regular => { - Ok(self.register_evaluated_expr(Expression::Constant(constant), span)) - } - ExprType::Constant => Ok(expr), - } - } else { - self.eval_impl(self.constants[constant].init, ExprType::Constant, false) - } - } - Expression::AccessIndex { base, index } => { - let base = self.eval_impl(base, expr_type, false)?; - - self.access(base, index as usize, span) - } - Expression::Access { base, index } => { - let base = self.eval_impl(base, expr_type, false)?; - let index = self.eval_impl(index, expr_type, false)?; - - self.access(base, self.constant_index(index)?, span) - } - Expression::Splat { size, value } => { - let value = self.eval_impl(value, expr_type, false)?; - - self.splat(value, size, span) - } - Expression::Swizzle { - size, - vector: src_vector, - pattern, - } => { - let src_constant = self.eval_impl(src_vector, expr_type, false)?; - - self.swizzle(size, span, src_constant, pattern) - } - Expression::Unary { expr, op } => { - let expr_constant = self.eval_impl(expr, expr_type, false)?; - - self.unary_op(op, expr_constant, span) - } - Expression::Binary { left, right, op } => { - let left_constant = self.eval_impl(left, expr_type, false)?; - let right_constant = self.eval_impl(right, expr_type, false)?; - - self.binary_op(op, left_constant, right_constant, span) - } - Expression::Math { - fun, - arg, - arg1, - arg2, - arg3, - } => { - let arg = self.eval_impl(arg, expr_type, false)?; - let arg1 = arg1 - .map(|arg| self.eval_impl(arg, expr_type, false)) - .transpose()?; - let arg2 = arg2 - .map(|arg| self.eval_impl(arg, expr_type, false)) - .transpose()?; - let arg3 = arg3 - .map(|arg| self.eval_impl(arg, expr_type, false)) - .transpose()?; - - self.math(arg, arg1, arg2, arg3, fun, span) - } - Expression::As { - convert, - expr, - kind, - } => { - let expr_constant = self.eval_impl(expr, expr_type, false)?; - - match convert { - Some(width) => self.cast(expr_constant, kind, width, span), - None => Err(ConstantEvaluatorError::Bitcast), - } - } - Expression::ArrayLength(expr) => { - let array = self.eval_impl(expr, expr_type, false)?; - - self.array_length(array, span) - } - - Expression::Load { .. } => Err(ConstantEvaluatorError::Load), - Expression::Select { .. } => Err(ConstantEvaluatorError::Select), - Expression::LocalVariable(_) => Err(ConstantEvaluatorError::LocalVariable), - Expression::Derivative { .. } => Err(ConstantEvaluatorError::Derivative), - Expression::Relational { .. } => Err(ConstantEvaluatorError::Relational), - Expression::CallResult { .. } => Err(ConstantEvaluatorError::Call), - Expression::WorkGroupUniformLoadResult { .. } => unreachable!(), - Expression::AtomicResult { .. } => Err(ConstantEvaluatorError::Atomic), - Expression::FunctionArgument(_) => Err(ConstantEvaluatorError::FunctionArg), - Expression::GlobalVariable(_) => Err(ConstantEvaluatorError::GlobalVariable), - Expression::ImageSample { .. } - | Expression::ImageLoad { .. } - | Expression::ImageQuery { .. } => Err(ConstantEvaluatorError::ImageExpression), - Expression::RayQueryProceedResult | Expression::RayQueryGetIntersection { .. } => { - Err(ConstantEvaluatorError::RayQueryExpression) - } - } - } - fn splat( &mut self, value: Handle, diff --git a/tests/out/wgsl/246-collatz.comp.wgsl b/tests/out/wgsl/246-collatz.comp.wgsl index e92cf8127..e79d61964 100644 --- a/tests/out/wgsl/246-collatz.comp.wgsl +++ b/tests/out/wgsl/246-collatz.comp.wgsl @@ -11,25 +11,24 @@ fn collatz_iterations(n: u32) -> u32 { var i: u32; n_1 = n; - i = u32(0); + i = 0u; loop { let _e7 = n_1; - if !((_e7 != u32(1))) { + if !((_e7 != 1u)) { break; } { let _e14 = n_1; let _e15 = f32(_e14); - let _e17 = f32(2); - if ((_e15 - (floor((_e15 / _e17)) * _e17)) == f32(0)) { + if ((_e15 - (floor((_e15 / 2.0)) * 2.0)) == 0.0) { { let _e25 = n_1; - n_1 = (_e25 / u32(2)); + n_1 = (_e25 / 2u); } } else { { let _e30 = n_1; - n_1 = ((u32(3) * _e30) + u32(1)); + n_1 = ((3u * _e30) + 1u); } } let _e36 = i; diff --git a/tests/out/wgsl/277-casting.frag.wgsl b/tests/out/wgsl/277-casting.frag.wgsl index 26a3db792..84c50ddd4 100644 --- a/tests/out/wgsl/277-casting.frag.wgsl +++ b/tests/out/wgsl/277-casting.frag.wgsl @@ -1,7 +1,7 @@ fn main_1() { var a: f32; - a = f32(1); + a = 1.0; return; } diff --git a/tests/out/wgsl/280-matrix-cast.frag.wgsl b/tests/out/wgsl/280-matrix-cast.frag.wgsl index 316d93651..ad9f85b74 100644 --- a/tests/out/wgsl/280-matrix-cast.frag.wgsl +++ b/tests/out/wgsl/280-matrix-cast.frag.wgsl @@ -1,8 +1,7 @@ fn main_1() { var a: mat4x4; - let _e1 = f32(1); - a = mat4x4(vec4(_e1, 0.0, 0.0, 0.0), vec4(0.0, _e1, 0.0, 0.0), vec4(0.0, 0.0, _e1, 0.0), vec4(0.0, 0.0, 0.0, _e1)); + a = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); return; } diff --git a/tests/out/wgsl/900-implicit-conversions.frag.wgsl b/tests/out/wgsl/900-implicit-conversions.frag.wgsl index 58ed87e1e..dc4855efa 100644 --- a/tests/out/wgsl/900-implicit-conversions.frag.wgsl +++ b/tests/out/wgsl/900-implicit-conversions.frag.wgsl @@ -56,8 +56,8 @@ fn implicit_dims_3(v_6: vec4) { fn main_1() { exact_1(1); - implicit(f32(1u)); - implicit_dims_2(vec3(vec3(1))); + implicit(1.0); + implicit_dims_2(vec3(1.0, 1.0, 1.0)); return; } diff --git a/tests/out/wgsl/bevy-pbr.frag.wgsl b/tests/out/wgsl/bevy-pbr.frag.wgsl index 85bbafd04..73501b99f 100644 --- a/tests/out/wgsl/bevy-pbr.frag.wgsl +++ b/tests/out/wgsl/bevy-pbr.frag.wgsl @@ -157,9 +157,9 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3) -> f32 { k = (_e55 / (_e56 + (_e57 * _e58))); let _e63 = k; let _e64 = k; - d = ((_e63 * _e64) * (1.0 / PI)); - let _e70 = d; - return _e70; + d = ((_e63 * _e64) * 0.31830987); + let _e71 = d; + return _e71; } fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 { @@ -247,7 +247,7 @@ fn fresnel(f0_3: vec3, LoH: f32) -> vec3 { LoH_1 = LoH; let _e49 = f0_4; let _e62 = f0_4; - f90_4 = clamp(dot(_e62, vec3((50.0 * 0.33))), 0.0, 1.0); + f90_4 = clamp(dot(_e62, vec3(16.5)), 0.0, 1.0); let _e75 = f0_4; let _e76 = f90_4; let _e77 = LoH_1; @@ -321,7 +321,7 @@ fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 { viewScatter = _e72; let _e74 = lightScatter; let _e75 = viewScatter; - return ((_e74 * _e75) * (1.0 / PI)); + return ((_e74 * _e75) * 0.31830987); } fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 { @@ -337,8 +337,8 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 f0_8 = f0_7; perceptual_roughness_1 = perceptual_roughness; NoV_7 = NoV_6; - c0_ = vec4(-(1.0), -(0.0275), -(0.572), 0.022); - c1_ = vec4(1.0, 0.0425, 1.04, -(0.04)); + c0_ = vec4(-1.0, -0.0275, -0.572, 0.022); + c1_ = vec4(1.0, 0.0425, 1.04, -0.04); let _e62 = perceptual_roughness_1; let _e64 = c0_; let _e66 = c1_; @@ -353,10 +353,10 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 let _e94 = NoV_7; let _e98 = r; let _e101 = r; - a004_ = ((min((_e83.x * _e85.x), exp2((-(9.28) * _e94))) * _e98.x) + _e101.y); + a004_ = ((min((_e83.x * _e85.x), exp2((-9.28 * _e94))) * _e98.x) + _e101.y); let _e109 = a004_; let _e112 = r; - AB = ((vec2(-(1.04), 1.04) * vec2(_e109)) + _e112.zw); + AB = ((vec2(-1.04, 1.04) * vec2(_e109)) + _e112.zw); let _e116 = f0_8; let _e117 = AB; let _e121 = AB; @@ -934,6 +934,6 @@ fn main(@location(0) v_WorldPosition: vec3, @location(1) v_WorldNormal: vec v_WorldTangent_1 = v_WorldTangent; gl_FrontFacing = param; main_1(); - let _e72 = o_Target; - return FragmentOutput(_e72); + let _e69 = o_Target; + return FragmentOutput(_e69); } diff --git a/tests/out/wgsl/bits_glsl.frag.wgsl b/tests/out/wgsl/bits_glsl.frag.wgsl index d81c3319d..13f2a9925 100644 --- a/tests/out/wgsl/bits_glsl.frag.wgsl +++ b/tests/out/wgsl/bits_glsl.frag.wgsl @@ -14,10 +14,10 @@ fn main_1() { i2_ = vec2(0); i3_ = vec3(0); i4_ = vec4(0); - u = u32(0); - u2_ = vec2(u32(0)); - u3_ = vec3(u32(0)); - u4_ = vec4(u32(0)); + u = 0u; + u2_ = vec2(0u); + u3_ = vec3(0u); + u4_ = vec4(0u); f2_ = vec2(0.0); f4_ = vec4(0.0); let _e33 = f4_; @@ -42,44 +42,44 @@ fn main_1() { f2_ = unpack2x16float(_e60); let _e66 = i; let _e67 = i; - i = insertBits(_e66, _e67, u32(5), u32(10)); + i = insertBits(_e66, _e67, 5u, 10u); let _e77 = i2_; let _e78 = i2_; - i2_ = insertBits(_e77, _e78, u32(5), u32(10)); + i2_ = insertBits(_e77, _e78, 5u, 10u); let _e88 = i3_; let _e89 = i3_; - i3_ = insertBits(_e88, _e89, u32(5), u32(10)); + i3_ = insertBits(_e88, _e89, 5u, 10u); let _e99 = i4_; let _e100 = i4_; - i4_ = insertBits(_e99, _e100, u32(5), u32(10)); + i4_ = insertBits(_e99, _e100, 5u, 10u); let _e110 = u; let _e111 = u; - u = insertBits(_e110, _e111, u32(5), u32(10)); + u = insertBits(_e110, _e111, 5u, 10u); let _e121 = u2_; let _e122 = u2_; - u2_ = insertBits(_e121, _e122, u32(5), u32(10)); + u2_ = insertBits(_e121, _e122, 5u, 10u); let _e132 = u3_; let _e133 = u3_; - u3_ = insertBits(_e132, _e133, u32(5), u32(10)); + u3_ = insertBits(_e132, _e133, 5u, 10u); let _e143 = u4_; let _e144 = u4_; - u4_ = insertBits(_e143, _e144, u32(5), u32(10)); + u4_ = insertBits(_e143, _e144, 5u, 10u); let _e153 = i; - i = extractBits(_e153, u32(5), u32(10)); + i = extractBits(_e153, 5u, 10u); let _e162 = i2_; - i2_ = extractBits(_e162, u32(5), u32(10)); + i2_ = extractBits(_e162, 5u, 10u); let _e171 = i3_; - i3_ = extractBits(_e171, u32(5), u32(10)); + i3_ = extractBits(_e171, 5u, 10u); let _e180 = i4_; - i4_ = extractBits(_e180, u32(5), u32(10)); + i4_ = extractBits(_e180, 5u, 10u); let _e189 = u; - u = extractBits(_e189, u32(5), u32(10)); + u = extractBits(_e189, 5u, 10u); let _e198 = u2_; - u2_ = extractBits(_e198, u32(5), u32(10)); + u2_ = extractBits(_e198, 5u, 10u); let _e207 = u3_; - u3_ = extractBits(_e207, u32(5), u32(10)); + u3_ = extractBits(_e207, 5u, 10u); let _e216 = u4_; - u4_ = extractBits(_e216, u32(5), u32(10)); + u4_ = extractBits(_e216, 5u, 10u); let _e223 = i; i = firstTrailingBit(_e223); let _e226 = i2_; diff --git a/tests/out/wgsl/buffer.frag.wgsl b/tests/out/wgsl/buffer.frag.wgsl index 73e543ca7..43bcceb0d 100644 --- a/tests/out/wgsl/buffer.frag.wgsl +++ b/tests/out/wgsl/buffer.frag.wgsl @@ -17,7 +17,7 @@ fn main_1() { let _e9 = testBuffer.data[0]; a = _e9; - testBuffer.data[1] = u32(2); + testBuffer.data[1] = 2u; let _e19 = testBufferReadOnly.data[0]; b = _e19; return; diff --git a/tests/out/wgsl/constant-array-size.frag.wgsl b/tests/out/wgsl/constant-array-size.frag.wgsl index 1aff03c79..18da4f7cd 100644 --- a/tests/out/wgsl/constant-array-size.frag.wgsl +++ b/tests/out/wgsl/constant-array-size.frag.wgsl @@ -11,7 +11,7 @@ fn function() -> vec4 { var sum: vec4; var i: i32; - sum = vec4(f32(0)); + sum = vec4(0.0); i = 0; loop { let _e9 = i; diff --git a/tests/out/wgsl/declarations.frag.wgsl b/tests/out/wgsl/declarations.frag.wgsl index 172029689..6b2d133f7 100644 --- a/tests/out/wgsl/declarations.frag.wgsl +++ b/tests/out/wgsl/declarations.frag.wgsl @@ -44,8 +44,8 @@ fn main_1() { var a_1: f32; var b: f32; - positions = array, 2>(vec3(-(1.0), 1.0, 0.0), vec3(-(1.0), -(1.0), 0.0)); - strct = TestStruct(f32(1), f32(2)); + positions = array, 2>(vec3(-1.0, 1.0, 0.0), vec3(-1.0, -1.0, 0.0)); + strct = TestStruct(1.0, 2.0); let _e35 = in_array_2[1]; from_input_array = _e35; let _e41 = array_2d[0][0]; diff --git a/tests/out/wgsl/expressions.frag.wgsl b/tests/out/wgsl/expressions.frag.wgsl index 1a1a6fd3b..8a9776947 100644 --- a/tests/out/wgsl/expressions.frag.wgsl +++ b/tests/out/wgsl/expressions.frag.wgsl @@ -14,7 +14,7 @@ struct FragmentOutput { @location(0) o_color: vec4, } -const strct: TestStruct = TestStruct(array, 2>(vec4(0u, 0u, 0u, 0u), vec4(1u, 1u, 1u, 1u))); +const strct: TestStruct = TestStruct(array, 2>(vec4(0u), vec4(1u))); var global: f32; @group(0) @binding(0) @@ -289,7 +289,7 @@ fn testStructConstructor() { fn testNonScalarToScalarConstructor() { var f: f32; - f = f32(mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0))[0].x); + f = 1.0; return; } @@ -308,7 +308,7 @@ fn testNonImplicitCastVectorCast() { var a_18: u32; var b_16: vec4; - a_18 = u32(1); + a_18 = 1u; let _e3 = a_18; b_16 = vec4(i32(_e3)); return; @@ -332,7 +332,7 @@ fn ternary(a_20: bool) { a_21 = a_20; let _e3 = a_21; if _e3 { - local = u32(0); + local = 0u; } else { local = 1u; } @@ -342,7 +342,7 @@ fn ternary(a_20: bool) { if _e10 { local_1 = 0u; } else { - local_1 = u32(1); + local_1 = 1u; } let _e15 = local_1; c_1 = _e15; @@ -354,7 +354,7 @@ fn ternary(a_20: bool) { if _e19 { local_2 = 2u; } else { - local_2 = u32(3); + local_2 = 3u; } let _e24 = local_2; local_3 = _e24; @@ -364,7 +364,7 @@ fn ternary(a_20: bool) { let _e27 = local_3; local_4 = _e27; } else { - local_4 = u32(5); + local_4 = 5u; } let _e31 = local_4; nested = _e31; @@ -396,7 +396,7 @@ fn testConstantLength(a_24: array) { var len_1: i32; a_25 = a_24; - len_1 = i32(4u); + len_1 = 4; return; } @@ -417,18 +417,17 @@ fn testSwizzleWrites(a_27: vec3) { a_28 = a_27; let _e6 = a_28; - let _e11 = vec2(3.0, 4.0); - a_28.z = _e11.x; - a_28.x = _e11.y; + a_28.z = 3.0; + a_28.x = 4.0; + let _e14 = a_28; let _e16 = a_28; - let _e18 = a_28; - let _e21 = (_e18.xy * 5.0); - a_28.x = _e21.x; - a_28.y = _e21.y; - let _e26 = a_28; - let _e30 = (_e26.zy + vec2(1.0)); - a_28.z = _e30.x; - a_28.y = _e30.y; + let _e19 = (_e16.xy * 5.0); + a_28.x = _e19.x; + a_28.y = _e19.y; + let _e24 = a_28; + let _e28 = (_e24.zy + vec2(1.0)); + a_28.z = _e28.x; + a_28.y = _e28.y; return; } @@ -441,17 +440,16 @@ fn main_1() { let _e8 = local_6; global = _e8; let _e9 = o_color; - let _e12 = vec4(1.0); - o_color.x = _e12.x; - o_color.y = _e12.y; - o_color.z = _e12.z; - o_color.w = _e12.w; + o_color.x = 1.0; + o_color.y = 1.0; + o_color.z = 1.0; + o_color.w = 1.0; return; } @fragment fn main() -> FragmentOutput { main_1(); - let _e17 = o_color; - return FragmentOutput(_e17); + let _e9 = o_color; + return FragmentOutput(_e9); } diff --git a/tests/out/wgsl/fma.frag.wgsl b/tests/out/wgsl/fma.frag.wgsl index 56677056f..870853978 100644 --- a/tests/out/wgsl/fma.frag.wgsl +++ b/tests/out/wgsl/fma.frag.wgsl @@ -33,11 +33,10 @@ fn Fma(d: ptr, m: Mat4x3_, s: f32) { fn main_1() { let _e1 = o_color; - let _e4 = vec4(1.0); - o_color.x = _e4.x; - o_color.y = _e4.y; - o_color.z = _e4.z; - o_color.w = _e4.w; + o_color.x = 1.0; + o_color.y = 1.0; + o_color.z = 1.0; + o_color.w = 1.0; return; } diff --git a/tests/out/wgsl/images.frag.wgsl b/tests/out/wgsl/images.frag.wgsl index 8b77c3e94..2edcb9c0e 100644 --- a/tests/out/wgsl/images.frag.wgsl +++ b/tests/out/wgsl/images.frag.wgsl @@ -24,7 +24,7 @@ fn testImg1D(coord: i32) { let _e10 = textureDimensions(img1D); size = i32(_e10); let _e17 = coord_1; - textureStore(img1D, _e17, vec4(f32(2))); + textureStore(img1D, _e17, vec4(2.0)); let _e22 = coord_1; let _e23 = textureLoad(img1D, _e22); c = _e23; @@ -44,7 +44,7 @@ fn testImg1DArray(coord_2: vec2) { let _e20 = textureLoad(img1DArray, _e17.x, _e17.y); c_1 = _e20; let _e26 = coord_3; - textureStore(img1DArray, _e26.x, _e26.y, vec4(f32(2))); + textureStore(img1DArray, _e26.x, _e26.y, vec4(2.0)); return; } @@ -60,7 +60,7 @@ fn testImg2D(coord_4: vec2) { let _e16 = textureLoad(img2D, _e15); c_2 = _e16; let _e22 = coord_5; - textureStore(img2D, _e22, vec4(f32(2))); + textureStore(img2D, _e22, vec4(2.0)); return; } @@ -77,7 +77,7 @@ fn testImg2DArray(coord_6: vec3) { let _e22 = textureLoad(img2DArray, _e19.xy, _e19.z); c_3 = _e22; let _e28 = coord_7; - textureStore(img2DArray, _e28.xy, _e28.z, vec4(f32(2))); + textureStore(img2DArray, _e28.xy, _e28.z, vec4(2.0)); return; } @@ -93,7 +93,7 @@ fn testImg3D(coord_8: vec3) { let _e16 = textureLoad(img3D, _e15); c_4 = _e16; let _e22 = coord_9; - textureStore(img3D, _e22, vec4(f32(2))); + textureStore(img3D, _e22, vec4(2.0)); return; } @@ -119,7 +119,7 @@ fn testImgWriteOnly(coord_12: vec2) { let _e10 = textureDimensions(img2D); size_6 = vec2(vec2(_e10)); let _e18 = coord_13; - textureStore(imgWriteOnly, _e18, vec4(f32(2))); + textureStore(imgWriteOnly, _e18, vec4(2.0)); return; } diff --git a/tests/out/wgsl/long-form-matrix.frag.wgsl b/tests/out/wgsl/long-form-matrix.frag.wgsl index f335452e1..7cc26f1ff 100644 --- a/tests/out/wgsl/long-form-matrix.frag.wgsl +++ b/tests/out/wgsl/long-form-matrix.frag.wgsl @@ -8,29 +8,14 @@ fn main_1() { var d: mat3x3; var e: mat4x4; - let _e1 = f32(1); - splat = mat2x2(vec2(_e1, 0.0), vec2(0.0, _e1)); - let _e9 = vec2(f32(1)); - let _e12 = vec2(f32(2)); - normal = mat2x2(vec2(_e9.x, _e9.y), vec2(_e12.x, _e12.y)); - let _e26 = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); - from_matrix = mat2x4(vec4(_e26[0].x, _e26[0].y, _e26[0].z, 0.0), vec4(_e26[1].x, _e26[1].y, _e26[1].z, 0.0)); - a = mat2x2(vec2(f32(1), f32(2)), vec2(f32(3), f32(4))); - let _e58 = vec2(f32(2), f32(3)); - b = mat2x2(vec2(f32(1), _e58.x), vec2(_e58.y, f32(4))); - let _e73 = vec3(f32(1)); - let _e76 = vec3(f32(1)); - c = mat3x3(vec3(f32(1), f32(2), f32(3)), vec3(_e73.x, _e73.y, _e73.z), vec3(_e76.x, _e76.y, _e76.z)); - let _e93 = vec2(f32(2)); - let _e97 = vec3(f32(1)); - let _e100 = vec3(f32(1)); - d = mat3x3(vec3(_e93.x, _e93.y, f32(1)), vec3(_e97.x, _e97.y, _e97.z), vec3(_e100.x, _e100.y, _e100.z)); - let _e117 = vec2(f32(2)); - let _e120 = vec4(f32(1)); - let _e123 = vec2(f32(2)); - let _e126 = vec4(f32(1)); - let _e129 = vec4(f32(1)); - e = mat4x4(vec4(_e117.x, _e117.y, _e120.x, _e120.y), vec4(_e120.z, _e120.w, _e123.x, _e123.y), vec4(_e126.x, _e126.y, _e126.z, _e126.w), vec4(_e129.x, _e129.y, _e129.z, _e129.w)); + splat = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); + normal = mat2x2(vec2(1.0, 1.0), vec2(2.0, 2.0)); + from_matrix = mat2x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0)); + a = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); + b = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); + c = mat3x3(vec3(1.0, 2.0, 3.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); + d = mat3x3(vec3(2.0, 2.0, 1.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); + e = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); return; } diff --git a/tests/out/wgsl/prepostfix.frag.wgsl b/tests/out/wgsl/prepostfix.frag.wgsl index 296a8151e..5b8f1bfb6 100644 --- a/tests/out/wgsl/prepostfix.frag.wgsl +++ b/tests/out/wgsl/prepostfix.frag.wgsl @@ -14,7 +14,7 @@ fn main_1() { let _e8 = (_e6 - 1); scalar = _e8; scalar_target = _e8; - vec = vec2(u32(1)); + vec = vec2(1u); let _e14 = vec; vec = (_e14 - vec2(1u)); vec_target = _e14; @@ -22,8 +22,7 @@ fn main_1() { let _e21 = (_e18 + vec2(1u)); vec = _e21; vec_target = _e21; - let _e24 = f32(1); - mat = mat4x3(vec3(_e24, 0.0, 0.0), vec3(0.0, _e24, 0.0), vec3(0.0, 0.0, _e24), vec3(0.0, 0.0, 0.0)); + mat = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); let _e32 = mat; let _e34 = vec3(1.0); mat = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); diff --git a/tests/out/wgsl/quad_glsl.vert.wgsl b/tests/out/wgsl/quad_glsl.vert.wgsl index b8d52e04c..1cec36afa 100644 --- a/tests/out/wgsl/quad_glsl.vert.wgsl +++ b/tests/out/wgsl/quad_glsl.vert.wgsl @@ -14,8 +14,8 @@ fn main_1() { let _e4 = a_uv_1; v_uv = _e4; let _e6 = a_pos_1; - let _e7 = (c_scale * _e6); - gl_Position = vec4(_e7.x, _e7.y, 0.0, 1.0); + let _e8 = (c_scale * _e6); + gl_Position = vec4(_e8.x, _e8.y, 0.0, 1.0); return; } @@ -24,7 +24,7 @@ fn main(@location(0) a_pos: vec2, @location(1) a_uv: vec2) -> VertexOu a_pos_1 = a_pos; a_uv_1 = a_uv; main_1(); - let _e14 = v_uv; - let _e16 = gl_Position; - return VertexOutput(_e14, _e16); + let _e13 = v_uv; + let _e15 = gl_Position; + return VertexOutput(_e13, _e15); } diff --git a/tests/out/wgsl/sampler-functions.frag.wgsl b/tests/out/wgsl/sampler-functions.frag.wgsl index 89a5c35dc..7b2b01772 100644 --- a/tests/out/wgsl/sampler-functions.frag.wgsl +++ b/tests/out/wgsl/sampler-functions.frag.wgsl @@ -9,7 +9,7 @@ fn CalcShadowPCF1_(T_P_t_TextureDepth: texture_depth_2d, S_P_t_TextureDepth: sam let _e9 = t_ProjCoord_1; let _e10 = _e9.xyz; let _e13 = textureSampleCompare(T_P_t_TextureDepth, S_P_t_TextureDepth, _e10.xy, _e10.z); - t_Res = (_e6 + (_e13 * (1.0 / 5.0))); + t_Res = (_e6 + (_e13 * 0.2)); let _e19 = t_Res; return _e19; } diff --git a/tests/out/wgsl/samplers.frag.wgsl b/tests/out/wgsl/samplers.frag.wgsl index 96b662652..1009fd5cd 100644 --- a/tests/out/wgsl/samplers.frag.wgsl +++ b/tests/out/wgsl/samplers.frag.wgsl @@ -65,92 +65,76 @@ fn testTex1D(coord: f32) { c = _e71; let _e72 = coord_1; let _e75 = coord_1; - let _e77 = vec2(_e75, 6.0); - let _e81 = textureSample(tex1D, samp, (_e77.x / _e77.y)); - c = _e81; - let _e82 = coord_1; - let _e87 = coord_1; - let _e91 = vec4(_e87, 0.0, 0.0, 6.0); - let _e97 = textureSample(tex1D, samp, (_e91.xyz / vec3(_e91.w)).x); - c = _e97; - let _e98 = coord_1; - let _e102 = coord_1; - let _e104 = vec2(_e102, 6.0); - let _e109 = textureSampleBias(tex1D, samp, (_e104.x / _e104.y), 2.0); - c = _e109; - let _e110 = coord_1; - let _e116 = coord_1; - let _e120 = vec4(_e116, 0.0, 0.0, 6.0); - let _e127 = textureSampleBias(tex1D, samp, (_e120.xyz / vec3(_e120.w)).x, 2.0); - c = _e127; - let _e128 = coord_1; - let _e133 = coord_1; - let _e135 = vec2(_e133, 6.0); - let _e141 = textureSampleGrad(tex1D, samp, (_e135.x / _e135.y), 4.0, 4.0); - c = _e141; - let _e142 = coord_1; - let _e149 = coord_1; - let _e153 = vec4(_e149, 0.0, 0.0, 6.0); - let _e161 = textureSampleGrad(tex1D, samp, (_e153.xyz / vec3(_e153.w)).x, 4.0, 4.0); - c = _e161; + let _e79 = textureSample(tex1D, samp, (_e75 / 6.0)); + c = _e79; + let _e80 = coord_1; + let _e85 = coord_1; + let _e95 = textureSample(tex1D, samp, (vec3(_e85, 0.0, 0.0) / vec3(6.0)).x); + c = _e95; + let _e96 = coord_1; + let _e100 = coord_1; + let _e105 = textureSampleBias(tex1D, samp, (_e100 / 6.0), 2.0); + c = _e105; + let _e106 = coord_1; + let _e112 = coord_1; + let _e123 = textureSampleBias(tex1D, samp, (vec3(_e112, 0.0, 0.0) / vec3(6.0)).x, 2.0); + c = _e123; + let _e124 = coord_1; + let _e129 = coord_1; + let _e135 = textureSampleGrad(tex1D, samp, (_e129 / 6.0), 4.0, 4.0); + c = _e135; + let _e136 = coord_1; + let _e143 = coord_1; + let _e155 = textureSampleGrad(tex1D, samp, (vec3(_e143, 0.0, 0.0) / vec3(6.0)).x, 4.0, 4.0); + c = _e155; + let _e156 = coord_1; let _e162 = coord_1; - let _e168 = coord_1; - let _e170 = vec2(_e168, 6.0); - let _e177 = textureSampleGrad(tex1D, samp, (_e170.x / _e170.y), 4.0, 4.0, 5); - c = _e177; + let _e169 = textureSampleGrad(tex1D, samp, (_e162 / 6.0), 4.0, 4.0, 5); + c = _e169; + let _e170 = coord_1; let _e178 = coord_1; - let _e186 = coord_1; - let _e190 = vec4(_e186, 0.0, 0.0, 6.0); - let _e199 = textureSampleGrad(tex1D, samp, (_e190.xyz / vec3(_e190.w)).x, 4.0, 4.0, 5); - c = _e199; - let _e200 = coord_1; - let _e204 = coord_1; - let _e206 = vec2(_e204, 6.0); - let _e211 = textureSampleLevel(tex1D, samp, (_e206.x / _e206.y), 3.0); - c = _e211; - let _e212 = coord_1; - let _e218 = coord_1; - let _e222 = vec4(_e218, 0.0, 0.0, 6.0); - let _e229 = textureSampleLevel(tex1D, samp, (_e222.xyz / vec3(_e222.w)).x, 3.0); - c = _e229; - let _e230 = coord_1; - let _e235 = coord_1; - let _e237 = vec2(_e235, 6.0); - let _e243 = textureSampleLevel(tex1D, samp, (_e237.x / _e237.y), 3.0, 5); - c = _e243; - let _e244 = coord_1; - let _e251 = coord_1; - let _e255 = vec4(_e251, 0.0, 0.0, 6.0); - let _e263 = textureSampleLevel(tex1D, samp, (_e255.xyz / vec3(_e255.w)).x, 3.0, 5); - c = _e263; - let _e264 = coord_1; + let _e191 = textureSampleGrad(tex1D, samp, (vec3(_e178, 0.0, 0.0) / vec3(6.0)).x, 4.0, 4.0, 5); + c = _e191; + let _e192 = coord_1; + let _e196 = coord_1; + let _e201 = textureSampleLevel(tex1D, samp, (_e196 / 6.0), 3.0); + c = _e201; + let _e202 = coord_1; + let _e208 = coord_1; + let _e219 = textureSampleLevel(tex1D, samp, (vec3(_e208, 0.0, 0.0) / vec3(6.0)).x, 3.0); + c = _e219; + let _e220 = coord_1; + let _e225 = coord_1; + let _e231 = textureSampleLevel(tex1D, samp, (_e225 / 6.0), 3.0, 5); + c = _e231; + let _e232 = coord_1; + let _e239 = coord_1; + let _e251 = textureSampleLevel(tex1D, samp, (vec3(_e239, 0.0, 0.0) / vec3(6.0)).x, 3.0, 5); + c = _e251; + let _e252 = coord_1; + let _e256 = coord_1; + let _e261 = textureSample(tex1D, samp, (_e256 / 6.0), 5); + c = _e261; + let _e262 = coord_1; let _e268 = coord_1; - let _e270 = vec2(_e268, 6.0); - let _e275 = textureSample(tex1D, samp, (_e270.x / _e270.y), 5); - c = _e275; - let _e276 = coord_1; - let _e282 = coord_1; - let _e286 = vec4(_e282, 0.0, 0.0, 6.0); - let _e293 = textureSample(tex1D, samp, (_e286.xyz / vec3(_e286.w)).x, 5); - c = _e293; - let _e294 = coord_1; + let _e279 = textureSample(tex1D, samp, (vec3(_e268, 0.0, 0.0) / vec3(6.0)).x, 5); + c = _e279; + let _e280 = coord_1; + let _e285 = coord_1; + let _e291 = textureSampleBias(tex1D, samp, (_e285 / 6.0), 2.0, 5); + c = _e291; + let _e292 = coord_1; let _e299 = coord_1; - let _e301 = vec2(_e299, 6.0); - let _e307 = textureSampleBias(tex1D, samp, (_e301.x / _e301.y), 2.0, 5); - c = _e307; - let _e308 = coord_1; + let _e311 = textureSampleBias(tex1D, samp, (vec3(_e299, 0.0, 0.0) / vec3(6.0)).x, 2.0, 5); + c = _e311; + let _e312 = coord_1; let _e315 = coord_1; - let _e319 = vec4(_e315, 0.0, 0.0, 6.0); - let _e327 = textureSampleBias(tex1D, samp, (_e319.xyz / vec3(_e319.w)).x, 2.0, 5); + let _e318 = textureLoad(tex1D, i32(_e315), 3); + c = _e318; + let _e319 = coord_1; + let _e323 = coord_1; + let _e327 = textureLoad(tex1D, i32(_e323), 3); c = _e327; - let _e328 = coord_1; - let _e331 = coord_1; - let _e334 = textureLoad(tex1D, i32(_e331), 3); - c = _e334; - let _e335 = coord_1; - let _e339 = coord_1; - let _e343 = textureLoad(tex1D, i32(_e339), 3); - c = _e343; return; } @@ -218,99 +202,83 @@ fn testTex2D(coord_4: vec2) { let _e42 = textureSampleGrad(tex2D, samp, _e37, vec2(4.0), vec2(4.0)); c_2 = _e42; let _e50 = coord_5; - let _e57 = textureSampleGrad(tex2D, samp, _e50, vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e57 = textureSampleGrad(tex2D, samp, _e50, vec2(4.0), vec2(4.0), vec2(5)); c_2 = _e57; let _e60 = coord_5; let _e62 = textureSampleLevel(tex2D, samp, _e60, 3.0); c_2 = _e62; let _e67 = coord_5; - let _e71 = textureSampleLevel(tex2D, samp, _e67, 3.0, vec2(5, 5)); + let _e71 = textureSampleLevel(tex2D, samp, _e67, 3.0, vec2(5)); c_2 = _e71; let _e75 = coord_5; - let _e78 = textureSample(tex2D, samp, _e75, vec2(5, 5)); + let _e78 = textureSample(tex2D, samp, _e75, vec2(5)); c_2 = _e78; let _e83 = coord_5; - let _e87 = textureSampleBias(tex2D, samp, _e83, 2.0, vec2(5, 5)); + let _e87 = textureSampleBias(tex2D, samp, _e83, 2.0, vec2(5)); c_2 = _e87; let _e88 = coord_5; let _e93 = coord_5; - let _e97 = vec3(_e93.x, _e93.y, 6.0); - let _e102 = textureSample(tex2D, samp, (_e97.xy / vec2(_e97.z))); + let _e102 = textureSample(tex2D, samp, (vec2(_e93.x, _e93.y) / vec2(6.0))); c_2 = _e102; let _e103 = coord_5; let _e109 = coord_5; - let _e114 = vec4(_e109.x, _e109.y, 0.0, 6.0); - let _e120 = textureSample(tex2D, samp, (_e114.xyz / vec3(_e114.w)).xy); + let _e120 = textureSample(tex2D, samp, (vec3(_e109.x, _e109.y, 0.0) / vec3(6.0)).xy); c_2 = _e120; let _e121 = coord_5; let _e127 = coord_5; - let _e131 = vec3(_e127.x, _e127.y, 6.0); - let _e137 = textureSampleBias(tex2D, samp, (_e131.xy / vec2(_e131.z)), 2.0); + let _e137 = textureSampleBias(tex2D, samp, (vec2(_e127.x, _e127.y) / vec2(6.0)), 2.0); c_2 = _e137; let _e138 = coord_5; let _e145 = coord_5; - let _e150 = vec4(_e145.x, _e145.y, 0.0, 6.0); - let _e157 = textureSampleBias(tex2D, samp, (_e150.xyz / vec3(_e150.w)).xy, 2.0); + let _e157 = textureSampleBias(tex2D, samp, (vec3(_e145.x, _e145.y, 0.0) / vec3(6.0)).xy, 2.0); c_2 = _e157; let _e158 = coord_5; let _e167 = coord_5; - let _e171 = vec3(_e167.x, _e167.y, 6.0); - let _e180 = textureSampleGrad(tex2D, samp, (_e171.xy / vec2(_e171.z)), vec2(4.0), vec2(4.0)); + let _e180 = textureSampleGrad(tex2D, samp, (vec2(_e167.x, _e167.y) / vec2(6.0)), vec2(4.0), vec2(4.0)); c_2 = _e180; let _e181 = coord_5; let _e191 = coord_5; - let _e196 = vec4(_e191.x, _e191.y, 0.0, 6.0); - let _e206 = textureSampleGrad(tex2D, samp, (_e196.xyz / vec3(_e196.w)).xy, vec2(4.0), vec2(4.0)); + let _e206 = textureSampleGrad(tex2D, samp, (vec3(_e191.x, _e191.y, 0.0) / vec3(6.0)).xy, vec2(4.0), vec2(4.0)); c_2 = _e206; let _e207 = coord_5; let _e218 = coord_5; - let _e222 = vec3(_e218.x, _e218.y, 6.0); - let _e233 = textureSampleGrad(tex2D, samp, (_e222.xy / vec2(_e222.z)), vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e233 = textureSampleGrad(tex2D, samp, (vec2(_e218.x, _e218.y) / vec2(6.0)), vec2(4.0), vec2(4.0), vec2(5)); c_2 = _e233; let _e234 = coord_5; let _e246 = coord_5; - let _e251 = vec4(_e246.x, _e246.y, 0.0, 6.0); - let _e263 = textureSampleGrad(tex2D, samp, (_e251.xyz / vec3(_e251.w)).xy, vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e263 = textureSampleGrad(tex2D, samp, (vec3(_e246.x, _e246.y, 0.0) / vec3(6.0)).xy, vec2(4.0), vec2(4.0), vec2(5)); c_2 = _e263; let _e264 = coord_5; let _e270 = coord_5; - let _e274 = vec3(_e270.x, _e270.y, 6.0); - let _e280 = textureSampleLevel(tex2D, samp, (_e274.xy / vec2(_e274.z)), 3.0); + let _e280 = textureSampleLevel(tex2D, samp, (vec2(_e270.x, _e270.y) / vec2(6.0)), 3.0); c_2 = _e280; let _e281 = coord_5; let _e288 = coord_5; - let _e293 = vec4(_e288.x, _e288.y, 0.0, 6.0); - let _e300 = textureSampleLevel(tex2D, samp, (_e293.xyz / vec3(_e293.w)).xy, 3.0); + let _e300 = textureSampleLevel(tex2D, samp, (vec3(_e288.x, _e288.y, 0.0) / vec3(6.0)).xy, 3.0); c_2 = _e300; let _e301 = coord_5; let _e309 = coord_5; - let _e313 = vec3(_e309.x, _e309.y, 6.0); - let _e321 = textureSampleLevel(tex2D, samp, (_e313.xy / vec2(_e313.z)), 3.0, vec2(5, 5)); + let _e321 = textureSampleLevel(tex2D, samp, (vec2(_e309.x, _e309.y) / vec2(6.0)), 3.0, vec2(5)); c_2 = _e321; let _e322 = coord_5; let _e331 = coord_5; - let _e336 = vec4(_e331.x, _e331.y, 0.0, 6.0); - let _e345 = textureSampleLevel(tex2D, samp, (_e336.xyz / vec3(_e336.w)).xy, 3.0, vec2(5, 5)); + let _e345 = textureSampleLevel(tex2D, samp, (vec3(_e331.x, _e331.y, 0.0) / vec3(6.0)).xy, 3.0, vec2(5)); c_2 = _e345; let _e346 = coord_5; let _e353 = coord_5; - let _e357 = vec3(_e353.x, _e353.y, 6.0); - let _e364 = textureSample(tex2D, samp, (_e357.xy / vec2(_e357.z)), vec2(5, 5)); + let _e364 = textureSample(tex2D, samp, (vec2(_e353.x, _e353.y) / vec2(6.0)), vec2(5)); c_2 = _e364; let _e365 = coord_5; let _e373 = coord_5; - let _e378 = vec4(_e373.x, _e373.y, 0.0, 6.0); - let _e386 = textureSample(tex2D, samp, (_e378.xyz / vec3(_e378.w)).xy, vec2(5, 5)); + let _e386 = textureSample(tex2D, samp, (vec3(_e373.x, _e373.y, 0.0) / vec3(6.0)).xy, vec2(5)); c_2 = _e386; let _e387 = coord_5; let _e395 = coord_5; - let _e399 = vec3(_e395.x, _e395.y, 6.0); - let _e407 = textureSampleBias(tex2D, samp, (_e399.xy / vec2(_e399.z)), 2.0, vec2(5, 5)); + let _e407 = textureSampleBias(tex2D, samp, (vec2(_e395.x, _e395.y) / vec2(6.0)), 2.0, vec2(5)); c_2 = _e407; let _e408 = coord_5; let _e417 = coord_5; - let _e422 = vec4(_e417.x, _e417.y, 0.0, 6.0); - let _e431 = textureSampleBias(tex2D, samp, (_e422.xyz / vec3(_e422.w)).xy, 2.0, vec2(5, 5)); + let _e431 = textureSampleBias(tex2D, samp, (vec3(_e417.x, _e417.y, 0.0) / vec3(6.0)).xy, 2.0, vec2(5)); c_2 = _e431; let _e432 = coord_5; let _e435 = coord_5; @@ -333,70 +301,58 @@ fn testTex2DShadow(coord_6: vec2) { size2DShadow = vec2(_e20); let _e24 = coord_7; let _e29 = coord_7; - let _e33 = vec3(_e29.x, _e29.y, 1.0); - let _e36 = textureSampleCompare(tex2DShadow, sampShadow, _e33.xy, _e33.z); - d = _e36; - let _e37 = coord_7; - let _e46 = coord_7; - let _e50 = vec3(_e46.x, _e46.y, 1.0); - let _e57 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e50.xy, _e50.z); - d = _e57; - let _e58 = coord_7; - let _e69 = coord_7; - let _e73 = vec3(_e69.x, _e69.y, 1.0); - let _e82 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e73.xy, _e73.z, vec2(5, 5)); - d = _e82; - let _e83 = coord_7; - let _e89 = coord_7; - let _e93 = vec3(_e89.x, _e89.y, 1.0); - let _e97 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e93.xy, _e93.z); - d = _e97; - let _e98 = coord_7; - let _e106 = coord_7; - let _e110 = vec3(_e106.x, _e106.y, 1.0); - let _e116 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e110.xy, _e110.z, vec2(5, 5)); - d = _e116; - let _e117 = coord_7; - let _e124 = coord_7; - let _e128 = vec3(_e124.x, _e124.y, 1.0); - let _e133 = textureSampleCompare(tex2DShadow, sampShadow, _e128.xy, _e128.z, vec2(5, 5)); - d = _e133; + let _e35 = textureSampleCompare(tex2DShadow, sampShadow, vec2(_e29.x, _e29.y), 1.0); + d = _e35; + let _e36 = coord_7; + let _e45 = coord_7; + let _e55 = textureSampleCompareLevel(tex2DShadow, sampShadow, vec2(_e45.x, _e45.y), 1.0); + d = _e55; + let _e56 = coord_7; + let _e67 = coord_7; + let _e79 = textureSampleCompareLevel(tex2DShadow, sampShadow, vec2(_e67.x, _e67.y), 1.0, vec2(5)); + d = _e79; + let _e80 = coord_7; + let _e86 = coord_7; + let _e93 = textureSampleCompareLevel(tex2DShadow, sampShadow, vec2(_e86.x, _e86.y), 1.0); + d = _e93; + let _e94 = coord_7; + let _e102 = coord_7; + let _e111 = textureSampleCompareLevel(tex2DShadow, sampShadow, vec2(_e102.x, _e102.y), 1.0, vec2(5)); + d = _e111; + let _e112 = coord_7; + let _e119 = coord_7; + let _e127 = textureSampleCompare(tex2DShadow, sampShadow, vec2(_e119.x, _e119.y), 1.0, vec2(5)); + d = _e127; + let _e128 = coord_7; let _e134 = coord_7; - let _e140 = coord_7; - let _e145 = vec4(_e140.x, _e140.y, 1.0, 6.0); - let _e149 = (_e145.xyz / vec3(_e145.w)); - let _e152 = textureSampleCompare(tex2DShadow, sampShadow, _e149.xy, _e149.z); - d = _e152; - let _e153 = coord_7; - let _e163 = coord_7; - let _e168 = vec4(_e163.x, _e163.y, 1.0, 6.0); - let _e176 = (_e168.xyz / vec3(_e168.w)); - let _e179 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e176.xy, _e176.z); - d = _e179; - let _e180 = coord_7; - let _e192 = coord_7; - let _e197 = vec4(_e192.x, _e192.y, 1.0, 6.0); - let _e207 = (_e197.xyz / vec3(_e197.w)); - let _e210 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e207.xy, _e207.z, vec2(5, 5)); - d = _e210; - let _e211 = coord_7; - let _e218 = coord_7; - let _e223 = vec4(_e218.x, _e218.y, 1.0, 6.0); - let _e228 = (_e223.xyz / vec3(_e223.w)); - let _e231 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e228.xy, _e228.z); - d = _e231; - let _e232 = coord_7; - let _e241 = coord_7; - let _e246 = vec4(_e241.x, _e241.y, 1.0, 6.0); - let _e253 = (_e246.xyz / vec3(_e246.w)); - let _e256 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e253.xy, _e253.z, vec2(5, 5)); - d = _e256; - let _e257 = coord_7; - let _e265 = coord_7; - let _e270 = vec4(_e265.x, _e265.y, 1.0, 6.0); - let _e276 = (_e270.xyz / vec3(_e270.w)); - let _e279 = textureSampleCompare(tex2DShadow, sampShadow, _e276.xy, _e276.z, vec2(5, 5)); - d = _e279; + let _e143 = (vec3(_e134.x, _e134.y, 1.0) / vec3(6.0)); + let _e146 = textureSampleCompare(tex2DShadow, sampShadow, _e143.xy, _e143.z); + d = _e146; + let _e147 = coord_7; + let _e157 = coord_7; + let _e170 = (vec3(_e157.x, _e157.y, 1.0) / vec3(6.0)); + let _e173 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e170.xy, _e170.z); + d = _e173; + let _e174 = coord_7; + let _e186 = coord_7; + let _e201 = (vec3(_e186.x, _e186.y, 1.0) / vec3(6.0)); + let _e204 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e201.xy, _e201.z, vec2(5)); + d = _e204; + let _e205 = coord_7; + let _e212 = coord_7; + let _e222 = (vec3(_e212.x, _e212.y, 1.0) / vec3(6.0)); + let _e225 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e222.xy, _e222.z); + d = _e225; + let _e226 = coord_7; + let _e235 = coord_7; + let _e247 = (vec3(_e235.x, _e235.y, 1.0) / vec3(6.0)); + let _e250 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e247.xy, _e247.z, vec2(5)); + d = _e250; + let _e251 = coord_7; + let _e259 = coord_7; + let _e270 = (vec3(_e259.x, _e259.y, 1.0) / vec3(6.0)); + let _e273 = textureSampleCompare(tex2DShadow, sampShadow, _e270.xy, _e270.z, vec2(5)); + d = _e273; return; } @@ -419,19 +375,19 @@ fn testTex2DArray(coord_8: vec3) { let _e55 = textureSampleGrad(tex2DArray, samp, _e47.xy, i32(_e47.z), vec2(4.0), vec2(4.0)); c_3 = _e55; let _e63 = coord_9; - let _e73 = textureSampleGrad(tex2DArray, samp, _e63.xy, i32(_e63.z), vec2(4.0), vec2(4.0), vec2(5, 5)); + let _e73 = textureSampleGrad(tex2DArray, samp, _e63.xy, i32(_e63.z), vec2(4.0), vec2(4.0), vec2(5)); c_3 = _e73; let _e76 = coord_9; let _e81 = textureSampleLevel(tex2DArray, samp, _e76.xy, i32(_e76.z), 3.0); c_3 = _e81; let _e86 = coord_9; - let _e93 = textureSampleLevel(tex2DArray, samp, _e86.xy, i32(_e86.z), 3.0, vec2(5, 5)); + let _e93 = textureSampleLevel(tex2DArray, samp, _e86.xy, i32(_e86.z), 3.0, vec2(5)); c_3 = _e93; let _e97 = coord_9; - let _e103 = textureSample(tex2DArray, samp, _e97.xy, i32(_e97.z), vec2(5, 5)); + let _e103 = textureSample(tex2DArray, samp, _e97.xy, i32(_e97.z), vec2(5)); c_3 = _e103; let _e108 = coord_9; - let _e115 = textureSampleBias(tex2DArray, samp, _e108.xy, i32(_e108.z), 2.0, vec2(5, 5)); + let _e115 = textureSampleBias(tex2DArray, samp, _e108.xy, i32(_e108.z), 2.0, vec2(5)); c_3 = _e115; let _e116 = coord_9; let _e119 = coord_9; @@ -457,24 +413,20 @@ fn testTex2DArrayShadow(coord_10: vec3) { size2DArrayShadow = vec3(vec3(_e20.x, _e20.y, _e23)); let _e28 = coord_11; let _e34 = coord_11; - let _e39 = vec4(_e34.x, _e34.y, _e34.z, 1.0); - let _e44 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e39.xy, i32(_e39.z), _e39.w); - d_1 = _e44; - let _e45 = coord_11; - let _e55 = coord_11; - let _e60 = vec4(_e55.x, _e55.y, _e55.z, 1.0); - let _e69 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e60.xy, i32(_e60.z), _e60.w); - d_1 = _e69; - let _e70 = coord_11; - let _e82 = coord_11; - let _e87 = vec4(_e82.x, _e82.y, _e82.z, 1.0); - let _e98 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e87.xy, i32(_e87.z), _e87.w, vec2(5, 5)); - d_1 = _e98; - let _e99 = coord_11; - let _e107 = coord_11; - let _e112 = vec4(_e107.x, _e107.y, _e107.z, 1.0); - let _e119 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e112.xy, i32(_e112.z), _e112.w, vec2(5, 5)); - d_1 = _e119; + let _e42 = textureSampleCompare(tex2DArrayShadow, sampShadow, vec2(_e34.x, _e34.y), i32(_e34.z), 1.0); + d_1 = _e42; + let _e43 = coord_11; + let _e53 = coord_11; + let _e65 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, vec2(_e53.x, _e53.y), i32(_e53.z), 1.0); + d_1 = _e65; + let _e66 = coord_11; + let _e78 = coord_11; + let _e92 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, vec2(_e78.x, _e78.y), i32(_e78.z), 1.0, vec2(5)); + d_1 = _e92; + let _e93 = coord_11; + let _e101 = coord_11; + let _e111 = textureSampleCompare(tex2DArrayShadow, sampShadow, vec2(_e101.x, _e101.y), i32(_e101.z), 1.0, vec2(5)); + d_1 = _e111; return; } @@ -511,14 +463,12 @@ fn testTexCubeShadow(coord_14: vec3) { sizeCubeShadow = vec2(_e20); let _e24 = coord_15; let _e30 = coord_15; - let _e35 = vec4(_e30.x, _e30.y, _e30.z, 1.0); - let _e38 = textureSampleCompare(texCubeShadow, sampShadow, _e35.xyz, _e35.w); - d_2 = _e38; - let _e39 = coord_15; - let _e49 = coord_15; - let _e54 = vec4(_e49.x, _e49.y, _e49.z, 1.0); - let _e61 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e54.xyz, _e54.w); - d_2 = _e61; + let _e37 = textureSampleCompare(texCubeShadow, sampShadow, vec3(_e30.x, _e30.y, _e30.z), 1.0); + d_2 = _e37; + let _e38 = coord_15; + let _e48 = coord_15; + let _e59 = textureSampleCompareLevel(texCubeShadow, sampShadow, vec3(_e48.x, _e48.y, _e48.z), 1.0); + d_2 = _e59; return; } @@ -577,61 +527,53 @@ fn testTex3D(coord_20: vec3) { c_6 = _e31; let _e32 = coord_21; let _e38 = coord_21; - let _e43 = vec4(_e38.x, _e38.y, _e38.z, 6.0); - let _e48 = textureSample(tex3D, samp, (_e43.xyz / vec3(_e43.w))); + let _e48 = textureSample(tex3D, samp, (vec3(_e38.x, _e38.y, _e38.z) / vec3(6.0))); c_6 = _e48; let _e49 = coord_21; let _e56 = coord_21; - let _e61 = vec4(_e56.x, _e56.y, _e56.z, 6.0); - let _e67 = textureSampleBias(tex3D, samp, (_e61.xyz / vec3(_e61.w)), 2.0); + let _e67 = textureSampleBias(tex3D, samp, (vec3(_e56.x, _e56.y, _e56.z) / vec3(6.0)), 2.0); c_6 = _e67; let _e68 = coord_21; let _e76 = coord_21; - let _e81 = vec4(_e76.x, _e76.y, _e76.z, 6.0); - let _e88 = textureSample(tex3D, samp, (_e81.xyz / vec3(_e81.w)), vec3(5, 5, 5)); + let _e88 = textureSample(tex3D, samp, (vec3(_e76.x, _e76.y, _e76.z) / vec3(6.0)), vec3(5)); c_6 = _e88; let _e89 = coord_21; let _e98 = coord_21; - let _e103 = vec4(_e98.x, _e98.y, _e98.z, 6.0); - let _e111 = textureSampleBias(tex3D, samp, (_e103.xyz / vec3(_e103.w)), 2.0, vec3(5, 5, 5)); + let _e111 = textureSampleBias(tex3D, samp, (vec3(_e98.x, _e98.y, _e98.z) / vec3(6.0)), 2.0, vec3(5)); c_6 = _e111; let _e112 = coord_21; let _e119 = coord_21; - let _e124 = vec4(_e119.x, _e119.y, _e119.z, 6.0); - let _e130 = textureSampleLevel(tex3D, samp, (_e124.xyz / vec3(_e124.w)), 3.0); + let _e130 = textureSampleLevel(tex3D, samp, (vec3(_e119.x, _e119.y, _e119.z) / vec3(6.0)), 3.0); c_6 = _e130; let _e131 = coord_21; let _e140 = coord_21; - let _e145 = vec4(_e140.x, _e140.y, _e140.z, 6.0); - let _e153 = textureSampleLevel(tex3D, samp, (_e145.xyz / vec3(_e145.w)), 3.0, vec3(5, 5, 5)); + let _e153 = textureSampleLevel(tex3D, samp, (vec3(_e140.x, _e140.y, _e140.z) / vec3(6.0)), 3.0, vec3(5)); c_6 = _e153; let _e154 = coord_21; let _e164 = coord_21; - let _e169 = vec4(_e164.x, _e164.y, _e164.z, 6.0); - let _e178 = textureSampleGrad(tex3D, samp, (_e169.xyz / vec3(_e169.w)), vec3(4.0), vec3(4.0)); + let _e178 = textureSampleGrad(tex3D, samp, (vec3(_e164.x, _e164.y, _e164.z) / vec3(6.0)), vec3(4.0), vec3(4.0)); c_6 = _e178; let _e179 = coord_21; let _e191 = coord_21; - let _e196 = vec4(_e191.x, _e191.y, _e191.z, 6.0); - let _e207 = textureSampleGrad(tex3D, samp, (_e196.xyz / vec3(_e196.w)), vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + let _e207 = textureSampleGrad(tex3D, samp, (vec3(_e191.x, _e191.y, _e191.z) / vec3(6.0)), vec3(4.0), vec3(4.0), vec3(5)); c_6 = _e207; let _e213 = coord_21; let _e218 = textureSampleGrad(tex3D, samp, _e213, vec3(4.0), vec3(4.0)); c_6 = _e218; let _e226 = coord_21; - let _e233 = textureSampleGrad(tex3D, samp, _e226, vec3(4.0), vec3(4.0), vec3(5, 5, 5)); + let _e233 = textureSampleGrad(tex3D, samp, _e226, vec3(4.0), vec3(4.0), vec3(5)); c_6 = _e233; let _e236 = coord_21; let _e238 = textureSampleLevel(tex3D, samp, _e236, 3.0); c_6 = _e238; let _e243 = coord_21; - let _e247 = textureSampleLevel(tex3D, samp, _e243, 3.0, vec3(5, 5, 5)); + let _e247 = textureSampleLevel(tex3D, samp, _e243, 3.0, vec3(5)); c_6 = _e247; let _e251 = coord_21; - let _e254 = textureSample(tex3D, samp, _e251, vec3(5, 5, 5)); + let _e254 = textureSample(tex3D, samp, _e251, vec3(5)); c_6 = _e254; let _e259 = coord_21; - let _e263 = textureSampleBias(tex3D, samp, _e259, 2.0, vec3(5, 5, 5)); + let _e263 = textureSampleBias(tex3D, samp, _e259, 2.0, vec3(5)); c_6 = _e263; let _e264 = coord_21; let _e267 = coord_21; From 0e4ac2a98c10336a363597fb769d126e4418de5c Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 3 May 2023 16:55:27 +0200 Subject: [PATCH 2130/2212] [glsl-in] set initializer of local variables --- src/front/glsl/parser.rs | 1 + src/front/glsl/parser/declarations.rs | 24 +++++++---- src/front/glsl/parser/functions.rs | 40 +++++++++++++------ tests/in/glsl/local-var-init-in-loop.comp | 7 ++++ tests/out/wgsl/246-collatz.comp.wgsl | 3 +- tests/out/wgsl/277-casting.frag.wgsl | 3 +- tests/out/wgsl/280-matrix-cast.frag.wgsl | 4 +- tests/out/wgsl/901-lhs-field-select.frag.wgsl | 3 +- tests/out/wgsl/932-for-loop-if.frag.wgsl | 3 +- tests/out/wgsl/bevy-pbr.frag.wgsl | 18 +++------ tests/out/wgsl/bits_glsl.frag.wgsl | 30 +++++--------- tests/out/wgsl/constant-array-size.frag.wgsl | 6 +-- tests/out/wgsl/declarations.frag.wgsl | 6 +-- tests/out/wgsl/expressions.frag.wgsl | 19 +++------ .../out/wgsl/local-var-init-in-loop.comp.wgsl | 30 ++++++++++++++ tests/out/wgsl/long-form-matrix.frag.wgsl | 25 ++++-------- tests/out/wgsl/math-functions.frag.wgsl | 9 ++--- tests/out/wgsl/prepostfix.frag.wgsl | 9 ++--- tests/out/wgsl/sampler-functions.frag.wgsl | 3 +- 19 files changed, 127 insertions(+), 116 deletions(-) create mode 100644 tests/in/glsl/local-var-init-in-loop.comp create mode 100644 tests/out/wgsl/local-var-init-in-loop.comp.wgsl diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 391357668..851d2e1d7 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -395,6 +395,7 @@ pub struct DeclarationContext<'ctx, 'qualifiers, 'a> { qualifiers: TypeQualifiers<'qualifiers>, /// Indicates a global declaration external: bool, + is_inside_loop: bool, ctx: &'ctx mut Context<'a>, } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index da75b0ba6..d21366961 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -75,7 +75,7 @@ impl<'source> ParsingContext<'source> { global_ctx: &mut Context, ) -> Result<()> { if self - .parse_declaration(frontend, global_ctx, true)? + .parse_declaration(frontend, global_ctx, true, false)? .is_none() { let token = self.bump(frontend)?; @@ -246,18 +246,23 @@ impl<'source> ParsingContext<'source> { }) .transpose()?; - let maybe_const_expr = if is_global_const { - init + let (decl_initializer, late_initializer) = if is_global_const { + (init, None) } else if ctx.external { - init.and_then(|expr| ctx.ctx.lift_up_const_expression(expr).ok()) + let decl_initializer = + init.and_then(|expr| ctx.ctx.lift_up_const_expression(expr).ok()); + (decl_initializer, None) } else { - None - // init.filter(|expr| ctx.ctx.expressions.is_const(*expr)) + let decl_initializer = init.filter(|expr| ctx.ctx.expressions.is_const(*expr)); + let late_initializer = (decl_initializer.is_none() || ctx.is_inside_loop) + .then_some(init) + .flatten(); + (decl_initializer, late_initializer) }; - let pointer = ctx.add_var(frontend, ty, name, maybe_const_expr, meta)?; + let pointer = ctx.add_var(frontend, ty, name, decl_initializer, meta)?; - if let Some(value) = init.filter(|_| maybe_const_expr.is_none()) { + if let Some(value) = late_initializer { ctx.ctx.emit_restart(); ctx.ctx.body.push(Statement::Store { pointer, value }, meta); } @@ -287,6 +292,7 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, external: bool, + is_inside_loop: bool, ) -> Result> { //declaration: // function_prototype SEMICOLON @@ -343,6 +349,7 @@ impl<'source> ParsingContext<'source> { frontend, &mut context, &mut None, + false, )?; frontend.add_function(context, name, result, meta); @@ -385,6 +392,7 @@ impl<'source> ParsingContext<'source> { let mut ctx = DeclarationContext { qualifiers, external, + is_inside_loop, ctx, }; diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 91b778787..eebaec269 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -41,10 +41,11 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, terminator: &mut Option, + is_inside_loop: bool, ) -> Result> { // Type qualifiers always identify a declaration statement if self.peek_type_qualifier(frontend) { - return self.parse_declaration(frontend, ctx, false); + return self.parse_declaration(frontend, ctx, false, is_inside_loop); } // Type names can identify either declaration statements or type constructors @@ -60,7 +61,7 @@ impl<'source> ParsingContext<'source> { self.backtrack(token)?; if declaration { - return self.parse_declaration(frontend, ctx, false); + return self.parse_declaration(frontend, ctx, false, is_inside_loop); } } @@ -132,7 +133,9 @@ impl<'source> ParsingContext<'source> { self.expect(frontend, TokenValue::RightParen)?; let accept = ctx.new_body(|ctx| { - if let Some(more_meta) = self.parse_statement(frontend, ctx, &mut None)? { + if let Some(more_meta) = + self.parse_statement(frontend, ctx, &mut None, is_inside_loop)? + { meta.subsume(more_meta); } Ok(()) @@ -140,7 +143,9 @@ impl<'source> ParsingContext<'source> { let reject = ctx.new_body(|ctx| { if self.bump_if(frontend, TokenValue::Else).is_some() { - if let Some(more_meta) = self.parse_statement(frontend, ctx, &mut None)? { + if let Some(more_meta) = + self.parse_statement(frontend, ctx, &mut None, is_inside_loop)? + { meta.subsume(more_meta); } } @@ -252,7 +257,12 @@ impl<'source> ParsingContext<'source> { break } _ => { - self.parse_statement(frontend, ctx, &mut case_terminator)?; + self.parse_statement( + frontend, + ctx, + &mut case_terminator, + is_inside_loop, + )?; } } } @@ -347,7 +357,7 @@ impl<'source> ParsingContext<'source> { meta.subsume(expr_meta); - if let Some(body_meta) = self.parse_statement(frontend, ctx, &mut None)? { + if let Some(body_meta) = self.parse_statement(frontend, ctx, &mut None, true)? { meta.subsume(body_meta); } Ok(()) @@ -369,7 +379,7 @@ impl<'source> ParsingContext<'source> { let loop_body = ctx.new_body(|ctx| { let mut terminator = None; - self.parse_statement(frontend, ctx, &mut terminator)?; + self.parse_statement(frontend, ctx, &mut terminator, true)?; let mut stmt = ctx.stmt_ctx(); @@ -425,7 +435,7 @@ impl<'source> ParsingContext<'source> { if self.bump_if(frontend, TokenValue::Semicolon).is_none() { if self.peek_type_name(frontend) || self.peek_type_qualifier(frontend) { - self.parse_declaration(frontend, ctx, false)?; + self.parse_declaration(frontend, ctx, false, false)?; } else { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_expression(frontend, ctx, &mut stmt)?; @@ -508,7 +518,7 @@ impl<'source> ParsingContext<'source> { meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta); let loop_body = ctx.with_body(loop_body, |ctx| { - if let Some(stmt_meta) = self.parse_statement(frontend, ctx, &mut None)? { + if let Some(stmt_meta) = self.parse_statement(frontend, ctx, &mut None, true)? { meta.subsume(stmt_meta); } Ok(()) @@ -533,8 +543,13 @@ impl<'source> ParsingContext<'source> { let mut block_terminator = None; let block = ctx.new_body(|ctx| { - let block_meta = - self.parse_compound_statement(meta, frontend, ctx, &mut block_terminator)?; + let block_meta = self.parse_compound_statement( + meta, + frontend, + ctx, + &mut block_terminator, + is_inside_loop, + )?; meta.subsume(block_meta); Ok(()) })?; @@ -568,6 +583,7 @@ impl<'source> ParsingContext<'source> { frontend: &mut Frontend, ctx: &mut Context, terminator: &mut Option, + is_inside_loop: bool, ) -> Result { ctx.symbol_table.push_scope(); @@ -580,7 +596,7 @@ impl<'source> ParsingContext<'source> { break; } - let stmt = self.parse_statement(frontend, ctx, terminator)?; + let stmt = self.parse_statement(frontend, ctx, terminator, is_inside_loop)?; if let Some(stmt_meta) = stmt { meta.subsume(stmt_meta); diff --git a/tests/in/glsl/local-var-init-in-loop.comp b/tests/in/glsl/local-var-init-in-loop.comp new file mode 100644 index 000000000..e8b83ec40 --- /dev/null +++ b/tests/in/glsl/local-var-init-in-loop.comp @@ -0,0 +1,7 @@ +void main() { + vec4 sum = vec4(0); + for (int i = 0; i < 4; i++) { + vec4 a = vec4(1); + sum += a; + } +} \ No newline at end of file diff --git a/tests/out/wgsl/246-collatz.comp.wgsl b/tests/out/wgsl/246-collatz.comp.wgsl index e79d61964..5d1ea6483 100644 --- a/tests/out/wgsl/246-collatz.comp.wgsl +++ b/tests/out/wgsl/246-collatz.comp.wgsl @@ -8,10 +8,9 @@ var gl_GlobalInvocationID: vec3; fn collatz_iterations(n: u32) -> u32 { var n_1: u32; - var i: u32; + var i: u32 = 0u; n_1 = n; - i = 0u; loop { let _e7 = n_1; if !((_e7 != 1u)) { diff --git a/tests/out/wgsl/277-casting.frag.wgsl b/tests/out/wgsl/277-casting.frag.wgsl index 84c50ddd4..87761aff4 100644 --- a/tests/out/wgsl/277-casting.frag.wgsl +++ b/tests/out/wgsl/277-casting.frag.wgsl @@ -1,7 +1,6 @@ fn main_1() { - var a: f32; + var a: f32 = 1.0; - a = 1.0; return; } diff --git a/tests/out/wgsl/280-matrix-cast.frag.wgsl b/tests/out/wgsl/280-matrix-cast.frag.wgsl index ad9f85b74..7d432ee49 100644 --- a/tests/out/wgsl/280-matrix-cast.frag.wgsl +++ b/tests/out/wgsl/280-matrix-cast.frag.wgsl @@ -1,8 +1,6 @@ fn main_1() { - var a: mat4x4; + var a: mat4x4 = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - a = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); - return; } @fragment diff --git a/tests/out/wgsl/901-lhs-field-select.frag.wgsl b/tests/out/wgsl/901-lhs-field-select.frag.wgsl index 71b987051..341ef150e 100644 --- a/tests/out/wgsl/901-lhs-field-select.frag.wgsl +++ b/tests/out/wgsl/901-lhs-field-select.frag.wgsl @@ -1,7 +1,6 @@ fn main_1() { - var a: vec4; + var a: vec4 = vec4(1.0); - a = vec4(1.0); a.x = 2.0; return; } diff --git a/tests/out/wgsl/932-for-loop-if.frag.wgsl b/tests/out/wgsl/932-for-loop-if.frag.wgsl index f9a29ae87..ad1fdd34e 100644 --- a/tests/out/wgsl/932-for-loop-if.frag.wgsl +++ b/tests/out/wgsl/932-for-loop-if.frag.wgsl @@ -1,7 +1,6 @@ fn main_1() { - var i: i32; + var i: i32 = 0; - i = 0; loop { let _e2 = i; if !((_e2 < 1)) { diff --git a/tests/out/wgsl/bevy-pbr.frag.wgsl b/tests/out/wgsl/bevy-pbr.frag.wgsl index 73501b99f..c40b6dd73 100644 --- a/tests/out/wgsl/bevy-pbr.frag.wgsl +++ b/tests/out/wgsl/bevy-pbr.frag.wgsl @@ -328,8 +328,8 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 var f0_8: vec3; var perceptual_roughness_1: f32; var NoV_7: f32; - var c0_: vec4; - var c1_: vec4; + var c0_: vec4 = vec4(-1.0, -0.0275, -0.572, 0.022); + var c1_: vec4 = vec4(1.0, 0.0425, 1.04, -0.04); var r: vec4; var a004_: f32; var AB: vec2; @@ -337,8 +337,6 @@ fn EnvBRDFApprox(f0_7: vec3, perceptual_roughness: f32, NoV_6: f32) -> vec3 f0_8 = f0_7; perceptual_roughness_1 = perceptual_roughness; NoV_7 = NoV_6; - c0_ = vec4(-1.0, -0.0275, -0.572, 0.022); - c1_ = vec4(1.0, 0.0425, 1.04, -0.04); let _e62 = perceptual_roughness_1; let _e64 = c0_; let _e66 = c1_; @@ -638,7 +636,7 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: var NoH_5: f32; var LoH_7: f32; var diffuse_1: vec3; - var specularIntensity_3: f32; + var specularIntensity_3: f32 = 1.0; var specular_2: vec3; light_3 = light_2; @@ -678,7 +676,6 @@ fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: let _e124 = LoH_7; let _e125 = Fd_Burley(_e121, _e122, _e123, _e124); diffuse_1 = (_e116 * _e125); - specularIntensity_3 = 1.0; let _e138 = F0_3; let _e139 = roughness_11; let _e140 = half_vector; @@ -716,9 +713,9 @@ fn main_1() { var F0_4: vec3; var diffuseColor_4: vec3; var R_4: vec3; - var light_accum: vec3; - var i: i32; - var i_1: i32; + var light_accum: vec3 = vec3(0.0); + var i: i32 = 0; + var i_1: i32 = 0; var diffuse_ambient: vec3; var specular_ambient: vec3; @@ -825,8 +822,6 @@ fn main_1() { let _e217 = V_3; let _e219 = N_2; R_4 = reflect(-(_e217), _e219); - light_accum = vec3(0.0); - i = 0; loop { let _e227 = i; let _e228 = global_2.NumLights; @@ -854,7 +849,6 @@ fn main_1() { i = (_e236 + 1); } } - i_1 = 0; loop { let _e264 = i_1; let _e265 = global_2.NumLights; diff --git a/tests/out/wgsl/bits_glsl.frag.wgsl b/tests/out/wgsl/bits_glsl.frag.wgsl index 13f2a9925..597d5aa1c 100644 --- a/tests/out/wgsl/bits_glsl.frag.wgsl +++ b/tests/out/wgsl/bits_glsl.frag.wgsl @@ -1,25 +1,15 @@ fn main_1() { - var i: i32; - var i2_: vec2; - var i3_: vec3; - var i4_: vec4; - var u: u32; - var u2_: vec2; - var u3_: vec3; - var u4_: vec4; - var f2_: vec2; - var f4_: vec4; + var i: i32 = 0; + var i2_: vec2 = vec2(0); + var i3_: vec3 = vec3(0); + var i4_: vec4 = vec4(0); + var u: u32 = 0u; + var u2_: vec2 = vec2(0u); + var u3_: vec3 = vec3(0u); + var u4_: vec4 = vec4(0u); + var f2_: vec2 = vec2(0.0); + var f4_: vec4 = vec4(0.0); - i = 0; - i2_ = vec2(0); - i3_ = vec3(0); - i4_ = vec4(0); - u = 0u; - u2_ = vec2(0u); - u3_ = vec3(0u); - u4_ = vec4(0u); - f2_ = vec2(0.0); - f4_ = vec4(0.0); let _e33 = f4_; u = pack4x8snorm(_e33); let _e36 = f4_; diff --git a/tests/out/wgsl/constant-array-size.frag.wgsl b/tests/out/wgsl/constant-array-size.frag.wgsl index 18da4f7cd..f4baa8c12 100644 --- a/tests/out/wgsl/constant-array-size.frag.wgsl +++ b/tests/out/wgsl/constant-array-size.frag.wgsl @@ -8,11 +8,9 @@ const NUM_VECS: i32 = 42; var global: Data; fn function() -> vec4 { - var sum: vec4; - var i: i32; + var sum: vec4 = vec4(0.0); + var i: i32 = 0; - sum = vec4(0.0); - i = 0; loop { let _e9 = i; if !((_e9 < NUM_VECS)) { diff --git a/tests/out/wgsl/declarations.frag.wgsl b/tests/out/wgsl/declarations.frag.wgsl index 6b2d133f7..bfe6da8e2 100644 --- a/tests/out/wgsl/declarations.frag.wgsl +++ b/tests/out/wgsl/declarations.frag.wgsl @@ -38,14 +38,12 @@ var array_2d: array, 2>; var array_toomanyd: array, 2>, 2>, 2>, 2>, 2>, 2>; fn main_1() { - var positions: array, 2>; - var strct: TestStruct; + var positions: array, 2> = array, 2>(vec3(-1.0, 1.0, 0.0), vec3(-1.0, -1.0, 0.0)); + var strct: TestStruct = TestStruct(1.0, 2.0); var from_input_array: vec4; var a_1: f32; var b: f32; - positions = array, 2>(vec3(-1.0, 1.0, 0.0), vec3(-1.0, -1.0, 0.0)); - strct = TestStruct(1.0, 2.0); let _e35 = in_array_2[1]; from_input_array = _e35; let _e41 = array_2d[0][0]; diff --git a/tests/out/wgsl/expressions.frag.wgsl b/tests/out/wgsl/expressions.frag.wgsl index 8a9776947..c3817d8d7 100644 --- a/tests/out/wgsl/expressions.frag.wgsl +++ b/tests/out/wgsl/expressions.frag.wgsl @@ -280,24 +280,18 @@ fn testUnaryOpMat(a_16: mat3x3) { } fn testStructConstructor() { - var tree: BST; + var tree: BST = BST(1); - tree = BST(1); - return; } fn testNonScalarToScalarConstructor() { - var f: f32; + var f: f32 = 1.0; - f = 1.0; - return; } fn testArrayConstructor() { - var tree_1: array; + var tree_1: array = array(0.0); - tree_1 = array(0.0); - return; } fn testFreestandingConstructor() { @@ -305,10 +299,9 @@ fn testFreestandingConstructor() { } fn testNonImplicitCastVectorCast() { - var a_18: u32; + var a_18: u32 = 1u; var b_16: vec4; - a_18 = 1u; let _e3 = a_18; b_16 = vec4(i32(_e3)); return; @@ -393,11 +386,9 @@ fn testLength() { fn testConstantLength(a_24: array) { var a_25: array; - var len_1: i32; + var len_1: i32 = 4; a_25 = a_24; - len_1 = 4; - return; } fn indexConstantNonConstantIndex(i: i32) { diff --git a/tests/out/wgsl/local-var-init-in-loop.comp.wgsl b/tests/out/wgsl/local-var-init-in-loop.comp.wgsl new file mode 100644 index 000000000..750e32e6d --- /dev/null +++ b/tests/out/wgsl/local-var-init-in-loop.comp.wgsl @@ -0,0 +1,30 @@ +fn main_1() { + var sum: vec4 = vec4(0.0); + var i: i32 = 0; + var a: vec4 = vec4(1.0); + + loop { + let _e6 = i; + if !((_e6 < 4)) { + break; + } + { + let _e15 = vec4(1.0); + a = _e15; + let _e17 = sum; + let _e18 = a; + sum = (_e17 + _e18); + } + continuing { + let _e10 = i; + i = (_e10 + 1); + } + } + return; +} + +@compute @workgroup_size(1, 1, 1) +fn main() { + main_1(); + return; +} diff --git a/tests/out/wgsl/long-form-matrix.frag.wgsl b/tests/out/wgsl/long-form-matrix.frag.wgsl index 7cc26f1ff..cadfe936c 100644 --- a/tests/out/wgsl/long-form-matrix.frag.wgsl +++ b/tests/out/wgsl/long-form-matrix.frag.wgsl @@ -1,22 +1,13 @@ fn main_1() { - var splat: mat2x2; - var normal: mat2x2; - var from_matrix: mat2x4; - var a: mat2x2; - var b: mat2x2; - var c: mat3x3; - var d: mat3x3; - var e: mat4x4; + var splat: mat2x2 = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); + var normal: mat2x2 = mat2x2(vec2(1.0, 1.0), vec2(2.0, 2.0)); + var from_matrix: mat2x4 = mat2x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0)); + var a: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); + var b: mat2x2 = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); + var c: mat3x3 = mat3x3(vec3(1.0, 2.0, 3.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); + var d: mat3x3 = mat3x3(vec3(2.0, 2.0, 1.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); + var e: mat4x4 = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); - splat = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0)); - normal = mat2x2(vec2(1.0, 1.0), vec2(2.0, 2.0)); - from_matrix = mat2x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0)); - a = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); - b = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); - c = mat3x3(vec3(1.0, 2.0, 3.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); - d = mat3x3(vec3(2.0, 2.0, 1.0), vec3(1.0, 1.0, 1.0), vec3(1.0, 1.0, 1.0)); - e = mat4x4(vec4(2.0, 2.0, 1.0, 1.0), vec4(1.0, 1.0, 2.0, 2.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); - return; } @fragment diff --git a/tests/out/wgsl/math-functions.frag.wgsl b/tests/out/wgsl/math-functions.frag.wgsl index 0bcc5f533..0e3b5c384 100644 --- a/tests/out/wgsl/math-functions.frag.wgsl +++ b/tests/out/wgsl/math-functions.frag.wgsl @@ -1,8 +1,8 @@ fn main_1() { - var a: vec4; - var b: vec4; + var a: vec4 = vec4(1.0); + var b: vec4 = vec4(2.0); var m: mat4x4; - var i: i32; + var i: i32 = 5; var ceilOut: vec4; var roundOut: vec4; var floorOut: vec4; @@ -48,14 +48,11 @@ fn main_1() { var smoothStepVector: vec4; var smoothStepMixed: vec4; - a = vec4(1.0); - b = vec4(2.0); let _e6 = a; let _e7 = b; let _e8 = a; let _e9 = b; m = mat4x4(vec4(_e6.x, _e6.y, _e6.z, _e6.w), vec4(_e7.x, _e7.y, _e7.z, _e7.w), vec4(_e8.x, _e8.y, _e8.z, _e8.w), vec4(_e9.x, _e9.y, _e9.z, _e9.w)); - i = 5; let _e35 = a; ceilOut = ceil(_e35); let _e39 = a; diff --git a/tests/out/wgsl/prepostfix.frag.wgsl b/tests/out/wgsl/prepostfix.frag.wgsl index 5b8f1bfb6..3a98925a9 100644 --- a/tests/out/wgsl/prepostfix.frag.wgsl +++ b/tests/out/wgsl/prepostfix.frag.wgsl @@ -1,12 +1,11 @@ fn main_1() { var scalar_target: i32; - var scalar: i32; + var scalar: i32 = 1; var vec_target: vec2; - var vec: vec2; + var vec: vec2 = vec2(1u); var mat_target: mat4x3; - var mat: mat4x3; + var mat: mat4x3 = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); - scalar = 1; let _e3 = scalar; scalar = (_e3 + 1); scalar_target = _e3; @@ -14,7 +13,6 @@ fn main_1() { let _e8 = (_e6 - 1); scalar = _e8; scalar_target = _e8; - vec = vec2(1u); let _e14 = vec; vec = (_e14 - vec2(1u)); vec_target = _e14; @@ -22,7 +20,6 @@ fn main_1() { let _e21 = (_e18 + vec2(1u)); vec = _e21; vec_target = _e21; - mat = mat4x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 0.0)); let _e32 = mat; let _e34 = vec3(1.0); mat = (_e32 + mat4x3(_e34, _e34, _e34, _e34)); diff --git a/tests/out/wgsl/sampler-functions.frag.wgsl b/tests/out/wgsl/sampler-functions.frag.wgsl index 7b2b01772..39e51e93d 100644 --- a/tests/out/wgsl/sampler-functions.frag.wgsl +++ b/tests/out/wgsl/sampler-functions.frag.wgsl @@ -1,9 +1,8 @@ fn CalcShadowPCF1_(T_P_t_TextureDepth: texture_depth_2d, S_P_t_TextureDepth: sampler_comparison, t_ProjCoord: vec3) -> f32 { var t_ProjCoord_1: vec3; - var t_Res: f32; + var t_Res: f32 = 0.0; t_ProjCoord_1 = t_ProjCoord; - t_Res = 0.0; let _e6 = t_Res; let _e7 = t_ProjCoord_1; let _e9 = t_ProjCoord_1; From 77851ebfb69999eaca5f9578ab4534b30e0073d4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 13 Sep 2023 15:56:59 -0700 Subject: [PATCH 2131/2212] Move `front::Emitter` to `proc`. With the addition of the constant evaluator to the `proc` module, it is now concerned with constructing expressions. Any code that constructs expressions will generally also need to deal with `Emit` statements, which are handled by the `Emitter` type. However, `Emitter` is private to the `front` module. This patch moves it to `proc` and makes it accessible to both the constant evaluator and the front ends. --- src/front/glsl/context.rs | 7 +++---- src/front/mod.rs | 39 ------------------------------------ src/front/spv/function.rs | 2 +- src/front/spv/image.rs | 8 ++++---- src/front/spv/mod.rs | 20 +++++++++---------- src/front/wgsl/lower/mod.rs | 5 +++-- src/proc/emitter.rs | 40 +++++++++++++++++++++++++++++++++++++ src/proc/mod.rs | 2 ++ 8 files changed, 63 insertions(+), 60 deletions(-) create mode 100644 src/proc/emitter.rs diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index d767f9358..0f836def6 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -8,10 +8,9 @@ use super::{ Frontend, Result, }; use crate::{ - front::{Emitter, Typifier}, - AddressSpace, Arena, BinaryOperator, Block, Expression, FastHashMap, FunctionArgument, Handle, - Literal, LocalVariable, RelationalFunction, ScalarKind, Span, Statement, Type, TypeInner, - VectorSize, + front::Typifier, proc::Emitter, AddressSpace, Arena, BinaryOperator, Block, Expression, + FastHashMap, FunctionArgument, Handle, Literal, LocalVariable, RelationalFunction, ScalarKind, + Span, Statement, Type, TypeInner, VectorSize, }; use std::ops::Index; diff --git a/src/front/mod.rs b/src/front/mod.rs index faebde4e2..634c809fb 100644 --- a/src/front/mod.rs +++ b/src/front/mod.rs @@ -19,45 +19,6 @@ use crate::{ }; use std::ops; -/// Helper class to emit expressions -#[allow(dead_code)] -#[derive(Default, Debug)] -struct Emitter { - start_len: Option, -} - -#[allow(dead_code)] -impl Emitter { - fn start(&mut self, arena: &Arena) { - if self.start_len.is_some() { - unreachable!("Emitting has already started!"); - } - self.start_len = Some(arena.len()); - } - const fn is_running(&self) -> bool { - self.start_len.is_some() - } - #[must_use] - fn finish( - &mut self, - arena: &Arena, - ) -> Option<(crate::Statement, crate::span::Span)> { - let start_len = self.start_len.take().unwrap(); - if start_len != arena.len() { - #[allow(unused_mut)] - let mut span = crate::span::Span::default(); - let range = arena.range_from(start_len); - #[cfg(feature = "span")] - for handle in range.clone() { - span.subsume(arena.get_span(handle)) - } - Some((crate::Statement::Emit(range), span)) - } else { - None - } - } -} - /// A table of types for an `Arena`. /// /// A front end can use a `Typifier` to get types for an arena's expressions diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 7a874ae4e..198d9c52d 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -4,7 +4,7 @@ use crate::{ }; use super::{Error, Instruction, LookupExpression, LookupHelper as _}; -use crate::front::Emitter; +use crate::proc::Emitter; pub type BlockId = u32; diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 1cefeb4fc..ee58c7ba1 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -256,7 +256,7 @@ impl> super::Frontend { &mut self, words_left: u16, ctx: &mut super::BlockContext, - emitter: &mut crate::front::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, body_idx: usize, ) -> Result { @@ -315,7 +315,7 @@ impl> super::Frontend { &mut self, mut words_left: u16, ctx: &mut super::BlockContext, - emitter: &mut crate::front::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, @@ -415,7 +415,7 @@ impl> super::Frontend { mut words_left: u16, options: SamplingOptions, ctx: &mut super::BlockContext, - emitter: &mut crate::front::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, @@ -663,7 +663,7 @@ impl> super::Frontend { &mut self, at_level: bool, ctx: &mut super::BlockContext, - emitter: &mut crate::front::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 1609868ef..4bb696a63 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -789,7 +789,7 @@ impl> Frontend { id: spirv::Word, lookup: &LookupExpression, ctx: &mut BlockContext, - emitter: &mut super::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, body_idx: BodyIndex, ) -> Handle { @@ -851,7 +851,7 @@ impl> Frontend { fn parse_expr_unary_op( &mut self, ctx: &mut BlockContext, - emitter: &mut super::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, @@ -880,7 +880,7 @@ impl> Frontend { fn parse_expr_binary_op( &mut self, ctx: &mut BlockContext, - emitter: &mut super::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, @@ -914,7 +914,7 @@ impl> Frontend { fn parse_expr_unary_op_sign_adjusted( &mut self, ctx: &mut BlockContext, - emitter: &mut super::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, @@ -969,7 +969,7 @@ impl> Frontend { fn parse_expr_binary_op_sign_adjusted( &mut self, ctx: &mut BlockContext, - emitter: &mut super::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, @@ -1047,7 +1047,7 @@ impl> Frontend { fn parse_expr_int_comparison( &mut self, ctx: &mut BlockContext, - emitter: &mut super::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, @@ -1118,7 +1118,7 @@ impl> Frontend { fn parse_expr_shift_op( &mut self, ctx: &mut BlockContext, - emitter: &mut super::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, @@ -1161,7 +1161,7 @@ impl> Frontend { fn parse_expr_derivative( &mut self, ctx: &mut BlockContext, - emitter: &mut super::Emitter, + emitter: &mut crate::proc::Emitter, block: &mut crate::Block, block_id: spirv::Word, body_idx: usize, @@ -1292,7 +1292,7 @@ impl> Frontend { }) } - let mut emitter = super::Emitter::default(); + let mut emitter = crate::proc::Emitter::default(); emitter.start(ctx.expressions); // Find the `Body` to which this block contributes. @@ -5282,7 +5282,7 @@ fn make_index_literal( ctx: &mut BlockContext, index: u32, block: &mut crate::Block, - emitter: &mut super::Emitter, + emitter: &mut crate::proc::Emitter, index_type: Handle, index_type_id: spirv::Word, span: crate::Span, diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index edb4f6d49..905eb55ea 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -4,9 +4,10 @@ use crate::front::wgsl::error::{Error, ExpectedToken, InvalidAssignmentType}; use crate::front::wgsl::index::Index; use crate::front::wgsl::parse::number::Number; use crate::front::wgsl::parse::{ast, conv}; -use crate::front::{Emitter, Typifier}; +use crate::front::Typifier; use crate::proc::{ - ensure_block_returns, Alignment, ConstantEvaluator, Layouter, ResolveContext, TypeResolution, + ensure_block_returns, Alignment, ConstantEvaluator, Emitter, Layouter, ResolveContext, + TypeResolution, }; use crate::{Arena, FastHashMap, FastIndexMap, Handle, Span}; diff --git a/src/proc/emitter.rs b/src/proc/emitter.rs new file mode 100644 index 000000000..281a55e2a --- /dev/null +++ b/src/proc/emitter.rs @@ -0,0 +1,40 @@ +use crate::arena::Arena; + +/// Helper class to emit expressions +#[allow(dead_code)] +#[derive(Default, Debug)] +pub struct Emitter { + start_len: Option, +} + +#[allow(dead_code)] +impl Emitter { + pub fn start(&mut self, arena: &Arena) { + if self.start_len.is_some() { + unreachable!("Emitting has already started!"); + } + self.start_len = Some(arena.len()); + } + pub const fn is_running(&self) -> bool { + self.start_len.is_some() + } + #[must_use] + pub fn finish( + &mut self, + arena: &Arena, + ) -> Option<(crate::Statement, crate::span::Span)> { + let start_len = self.start_len.take().unwrap(); + if start_len != arena.len() { + #[allow(unused_mut)] + let mut span = crate::span::Span::default(); + let range = arena.range_from(start_len); + #[cfg(feature = "span")] + for handle in range.clone() { + span.subsume(arena.get_span(handle)) + } + Some((crate::Statement::Emit(range), span)) + } else { + None + } + } +} diff --git a/src/proc/mod.rs b/src/proc/mod.rs index c91e0cb3e..bbdd75eb3 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -3,6 +3,7 @@ */ mod constant_evaluator; +mod emitter; pub mod index; mod layouter; mod namer; @@ -10,6 +11,7 @@ mod terminator; mod typifier; pub use constant_evaluator::{ConstantEvaluator, ConstantEvaluatorError}; +pub use emitter::Emitter; pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength, IndexableLengthError}; pub use layouter::{Alignment, LayoutError, LayoutErrorInner, Layouter, TypeLayout}; pub use namer::{EntryPointIndex, NameKey, Namer}; From aa041aafbd285a7962218d646ebf14766482b657 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 13 Sep 2023 16:24:03 -0700 Subject: [PATCH 2132/2212] Replace `ConstantEvaluator`'s closure with optional emitter data. Instead of letting the user supply an arbitrary closure for appending expressions, instead give `ConstantEvaluator` an `Option` that holds an `Emitter` to interrupt, and a `block` to add any new `Emit` statements to. --- src/front/glsl/context.rs | 30 +++++++-------- src/front/wgsl/lower/mod.rs | 32 ++++------------ src/proc/constant_evaluator.rs | 68 +++++++++++++++------------------- src/proc/mod.rs | 2 +- 4 files changed, 52 insertions(+), 80 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 0f836def6..0fe0f734a 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -245,19 +245,6 @@ impl<'a> Context<'a> { } pub fn add_expression(&mut self, expr: Expression, meta: Span) -> Result> { - let mut append = |arena: &mut Arena, expr: Expression, span| { - let is_running = self.emitter.is_running(); - let needs_pre_emit = expr.needs_pre_emit(); - if is_running && needs_pre_emit { - self.body.extend(self.emitter.finish(arena)); - } - let h = arena.append(expr, span); - if is_running && needs_pre_emit { - self.emitter.start(arena); - } - h - }; - let (expressions, const_expressions) = if self.is_const { (&mut self.module.const_expressions, None) } else { @@ -269,7 +256,10 @@ impl<'a> Context<'a> { constants: &self.module.constants, expressions, const_expressions, - append: (!self.is_const).then_some(&mut append), + emitter: (!self.is_const).then_some(crate::proc::ConstantEvaluatorEmitter { + emitter: &mut self.emitter, + block: &mut self.body, + }), }; let res = eval.try_eval_and_append(&expr, meta).map_err(|e| Error { @@ -280,7 +270,17 @@ impl<'a> Context<'a> { match res { Ok(expr) => Ok(expr), Err(e) if self.is_const => Err(e), - Err(_) => Ok(append(&mut self.expressions, expr, meta)), + Err(_) => { + let needs_pre_emit = expr.needs_pre_emit(); + if needs_pre_emit { + self.body.extend(self.emitter.finish(expressions)); + } + let h = expressions.append(expr, meta); + if needs_pre_emit { + self.emitter.start(expressions); + } + Ok(h) + } } } diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 905eb55ea..f36840d3f 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -6,8 +6,8 @@ use crate::front::wgsl::parse::number::Number; use crate::front::wgsl::parse::{ast, conv}; use crate::front::Typifier; use crate::proc::{ - ensure_block_returns, Alignment, ConstantEvaluator, Emitter, Layouter, ResolveContext, - TypeResolution, + ensure_block_returns, Alignment, ConstantEvaluator, ConstantEvaluatorEmitter, Emitter, + Layouter, ResolveContext, TypeResolution, }; use crate::{Arena, FastHashMap, FastIndexMap, Handle, Span}; @@ -338,20 +338,10 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { constants: &self.module.constants, expressions: rctx.naga_expressions, const_expressions: Some(&self.module.const_expressions), - append: Some( - |arena: &mut Arena, expr: crate::Expression, span| { - let is_running = rctx.emitter.is_running(); - let needs_pre_emit = expr.needs_pre_emit(); - if is_running && needs_pre_emit { - rctx.block.extend(rctx.emitter.finish(arena)); - } - let h = arena.append(expr, span); - if is_running && needs_pre_emit { - rctx.emitter.start(arena); - } - h - }, - ), + emitter: Some(ConstantEvaluatorEmitter { + emitter: rctx.emitter, + block: rctx.block, + }), }; match eval.try_eval_and_append(&expr, span) { @@ -365,15 +355,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { constants: &self.module.constants, expressions: &mut self.module.const_expressions, const_expressions: None, - append: None::< - Box< - dyn FnMut( - &mut Arena, - crate::Expression, - Span, - ) -> Handle, - >, - >, + emitter: None, }; eval.try_eval_and_append(&expr, span) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 218252e1f..2580cadf2 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -5,15 +5,22 @@ use crate::{ }; #[derive(Debug)] -pub struct ConstantEvaluator< - 'a, - F: FnMut(&mut Arena, Expression, Span) -> Handle, -> { +pub struct ConstantEvaluator<'a> { pub types: &'a mut UniqueArena, pub constants: &'a Arena, pub expressions: &'a mut Arena, pub const_expressions: Option<&'a Arena>, - pub append: Option, + + /// When `expressions` refers to a function's local expression + /// arena, this is the emitter we should interrupt when inserting + /// new things into it. + pub emitter: Option>, +} + +#[derive(Debug)] +pub struct ConstantEvaluatorEmitter<'a> { + pub emitter: &'a mut super::Emitter, + pub block: &'a mut crate::Block, } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -99,9 +106,7 @@ impl Arena { } } -impl<'a, F: FnMut(&mut Arena, Expression, Span) -> Handle> - ConstantEvaluator<'a, F> -{ +impl ConstantEvaluator<'_> { fn check_and_get( &mut self, expr: Handle, @@ -800,11 +805,20 @@ impl<'a, F: FnMut(&mut Arena, Expression, Span) -> Handle Handle { - if let Some(ref mut append) = self.append { - append(self.expressions, expr, span) - } else { - self.expressions.append(expr, span) + if let Some(ref mut emitter) = self.emitter { + let is_running = emitter.emitter.is_running(); + let needs_pre_emit = expr.needs_pre_emit(); + if is_running && needs_pre_emit { + emitter + .block + .extend(emitter.emitter.finish(self.expressions)); + let h = self.expressions.append(expr, span); + emitter.emitter.start(self.expressions); + return h; + } } + + self.expressions.append(expr, span) } } @@ -973,15 +987,7 @@ mod tests { constants: &constants, expressions: &mut const_expressions, const_expressions: None, - append: None::< - Box< - dyn FnMut( - &mut Arena, - Expression, - crate::Span, - ) -> crate::Handle, - >, - >, + emitter: None, }; let res1 = solver @@ -1068,15 +1074,7 @@ mod tests { constants: &constants, expressions: &mut const_expressions, const_expressions: None, - append: None::< - Box< - dyn FnMut( - &mut Arena, - Expression, - crate::Span, - ) -> crate::Handle, - >, - >, + emitter: None, }; let res = solver @@ -1195,15 +1193,7 @@ mod tests { constants: &constants, expressions: &mut const_expressions, const_expressions: None, - append: None::< - Box< - dyn FnMut( - &mut Arena, - Expression, - crate::Span, - ) -> crate::Handle, - >, - >, + emitter: None, }; let root1 = Expression::AccessIndex { base, index: 1 }; diff --git a/src/proc/mod.rs b/src/proc/mod.rs index bbdd75eb3..2282520a3 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -10,7 +10,7 @@ mod namer; mod terminator; mod typifier; -pub use constant_evaluator::{ConstantEvaluator, ConstantEvaluatorError}; +pub use constant_evaluator::{ConstantEvaluator, ConstantEvaluatorEmitter, ConstantEvaluatorError}; pub use emitter::Emitter; pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength, IndexableLengthError}; pub use layouter::{Alignment, LayoutError, LayoutErrorInner, Layouter, TypeLayout}; From ca69a6b372f1a8cb33766aef83c87d8a61278604 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 19 Sep 2023 06:36:50 -0700 Subject: [PATCH 2133/2212] Add a bit of logging to `ConstantEvaluator`. (#2488) --- src/proc/constant_evaluator.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 2580cadf2..249b365c5 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -123,7 +123,10 @@ impl ConstantEvaluator<'_> { Ok(self.constants[c].init) } } - _ => Err(ConstantEvaluatorError::SubexpressionsAreNotConstant), + _ => { + log::debug!("check_and_get: SubexpressionsAreNotConstant"); + Err(ConstantEvaluatorError::SubexpressionsAreNotConstant) + } } } @@ -132,6 +135,7 @@ impl ConstantEvaluator<'_> { expr: &Expression, span: Span, ) -> Result, ConstantEvaluatorError> { + log::trace!("try_eval_and_append: {:?}", expr); match *expr { Expression::Literal(_) | Expression::ZeroValue(_) | Expression::Constant(_) => { Ok(self.register_evaluated_expr(expr.clone(), span)) @@ -800,7 +804,10 @@ impl ConstantEvaluator<'_> { let value = self.copy_from(value, expressions)?; Ok(self.register_evaluated_expr(Expression::Splat { size, value }, span)) } - _ => Err(ConstantEvaluatorError::SubexpressionsAreNotConstant), + _ => { + log::debug!("copy_from: SubexpressionsAreNotConstant"); + Err(ConstantEvaluatorError::SubexpressionsAreNotConstant) + } } } From 44ca6ac5b3aac57754e5d78bd35931e05b6b6d4d Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 19 Sep 2023 06:38:29 -0700 Subject: [PATCH 2134/2212] Document some parts of `ConstantEvaluator`. (#2489) --- src/proc/constant_evaluator.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 249b365c5..88c03bf57 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -117,9 +117,13 @@ impl ConstantEvaluator<'_> { | Expression::Compose { .. } | Expression::Splat { .. } => Ok(expr), Expression::Constant(c) => { + // Are we working in a function's expression arena, or the + // module's constant expression arena? if let Some(const_expressions) = self.const_expressions { + // Deep-copy the constant's value into our arena. self.copy_from(self.constants[c].init, const_expressions) } else { + // "See through" the constant and use its initializer. Ok(self.constants[c].init) } } @@ -783,6 +787,13 @@ impl ConstantEvaluator<'_> { Ok(self.register_evaluated_expr(expr, span)) } + /// Deep copy `expr` from `expressions` into `self.expressions`. + /// + /// Return the root of the new copy. + /// + /// This is used when we're evaluating expressions in a function's + /// expression arena that refer to a constant: we need to copy the + /// constant's value into the function's arena so we can operate on it. fn copy_from( &mut self, handle: Handle, From f0ac8380197700960f86870bb75bc7a77f183333 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 19 Sep 2023 06:38:37 -0700 Subject: [PATCH 2135/2212] ConstantEvaluator::copy_from: Rename argument `handle` to `expr`. (#2490) --- src/proc/constant_evaluator.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 88c03bf57..6b917c4d6 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -796,11 +796,11 @@ impl ConstantEvaluator<'_> { /// constant's value into the function's arena so we can operate on it. fn copy_from( &mut self, - handle: Handle, + expr: Handle, expressions: &Arena, ) -> Result, ConstantEvaluatorError> { - let span = expressions.get_span(handle); - match expressions[handle] { + let span = expressions.get_span(expr); + match expressions[expr] { ref expr @ (Expression::Literal(_) | Expression::Constant(_) | Expression::ZeroValue(_)) => Ok(self.register_evaluated_expr(expr.clone(), span)), From 1a4b526d9a263eb30fa1fdd048bf14b125adde5b Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 07:45:30 -0700 Subject: [PATCH 2136/2212] ConstantEvaluator::swizzle: Handle vector concatenation and indexing (#2485) * ConstantEvaluator::swizzle: Handle vector concatenation, indexing. * Handle vector Compose expressions nested two deep. * Move `flatten_compose` to `proc`, and make it a free function. * [spv-out] Ensure that we flatten Compose for OpConstantCompose. --- src/back/spv/block.rs | 27 +++++---- src/back/spv/writer.rs | 12 ++-- src/proc/constant_evaluator.rs | 36 ++++++++---- src/proc/mod.rs | 55 ++++++++++++++++++ tests/in/const-exprs.wgsl | 14 +++++ tests/out/glsl/const-exprs.main.Compute.glsl | 23 ++++++++ tests/out/hlsl/const-exprs.hlsl | 14 +++++ tests/out/hlsl/const-exprs.ron | 12 ++++ tests/out/msl/const-exprs.msl | 19 +++++++ tests/out/spv/const-exprs.spvasm | 60 ++++++++++++++++++++ tests/out/wgsl/const-exprs.wgsl | 16 ++++++ tests/snapshots.rs | 4 ++ 12 files changed, 264 insertions(+), 28 deletions(-) create mode 100644 tests/in/const-exprs.wgsl create mode 100644 tests/out/glsl/const-exprs.main.Compute.glsl create mode 100644 tests/out/hlsl/const-exprs.hlsl create mode 100644 tests/out/hlsl/const-exprs.ron create mode 100644 tests/out/msl/const-exprs.msl create mode 100644 tests/out/spv/const-exprs.spvasm create mode 100644 tests/out/wgsl/const-exprs.wgsl diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index d698931f6..342a3805f 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -243,21 +243,24 @@ impl<'w> BlockContext<'w> { self.writer.constant_ids[init.index()] } crate::Expression::ZeroValue(_) => self.writer.get_constant_null(result_type_id), - crate::Expression::Compose { - ty: _, - ref components, - } => { + crate::Expression::Compose { ty, ref components } => { self.temp_list.clear(); - for &component in components { - self.temp_list.push(self.cached[component]); - } - if self.ir_function.expressions.is_const(expr_handle) { - let ty = self - .writer - .get_expression_lookup_type(&self.fun_info[expr_handle].ty); - self.writer.get_constant_composite(ty, &self.temp_list) + self.temp_list.extend( + crate::proc::flatten_compose( + ty, + components, + &self.ir_function.expressions, + &self.ir_module.types, + ) + .map(|component| self.cached[component]), + ); + self.writer + .get_constant_composite(LookupType::Handle(ty), &self.temp_list) } else { + self.temp_list + .extend(components.iter().map(|&component| self.cached[component])); + let id = self.gen_id(); block.body.push(Instruction::composite_construct( result_type_id, diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 7d7937778..0f4809565 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1269,10 +1269,14 @@ impl Writer { self.get_constant_null(type_id) } crate::Expression::Compose { ty, ref components } => { - let component_ids: Vec<_> = components - .iter() - .map(|component| self.constant_ids[component.index()]) - .collect(); + let component_ids: Vec<_> = crate::proc::flatten_compose( + ty, + components, + &ir_module.const_expressions, + &ir_module.types, + ) + .map(|component| self.constant_ids[component.index()]) + .collect(); self.get_constant_composite(LookupType::Handle(ty), component_ids.as_slice()) } crate::Expression::Splat { size, value } => { diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 6b917c4d6..9d2055ff6 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -73,6 +73,8 @@ pub enum ConstantEvaluatorError { SplatScalarOnly, #[error("Can only swizzle vector constants")] SwizzleVectorOnly, + #[error("swizzle component not present in source expression")] + SwizzleOutOfBounds, #[error("Type is not constructible")] TypeNotConstructible, #[error("Subexpression(s) are not constant")] @@ -306,20 +308,31 @@ impl ConstantEvaluator<'_> { let expr = Expression::Splat { size, value }; Ok(self.register_evaluated_expr(expr, span)) } - Expression::Compose { - ty, - components: ref src_components, - } => { + Expression::Compose { ty, ref components } => { let dst_ty = get_dst_ty(ty)?; - let components = pattern + let mut flattened = [src_constant; 4]; // dummy value + let len = + crate::proc::flatten_compose(ty, components, self.expressions, self.types) + .zip(flattened.iter_mut()) + .map(|(component, elt)| *elt = component) + .count(); + let flattened = &flattened[..len]; + + let swizzled_components = pattern[..size as usize] .iter() - .take(size as usize) - .map(|&sc| src_components[sc as usize]) - .collect(); + .map(|&sc| { + let sc = sc as usize; + if let Some(elt) = flattened.get(sc) { + Ok(*elt) + } else { + Err(ConstantEvaluatorError::SwizzleOutOfBounds) + } + }) + .collect::>, _>>()?; let expr = Expression::Compose { ty: dst_ty, - components, + components: swizzled_components, }; Ok(self.register_evaluated_expr(expr, span)) } @@ -455,9 +468,8 @@ impl ConstantEvaluator<'_> { .components() .ok_or(ConstantEvaluatorError::InvalidAccessBase)?; - components - .get(index) - .copied() + crate::proc::flatten_compose(ty, components, self.expressions, self.types) + .nth(index) .ok_or(ConstantEvaluatorError::InvalidAccessIndex) } _ => Err(ConstantEvaluatorError::InvalidAccessBase), diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 2282520a3..2121da01b 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -638,6 +638,61 @@ impl GlobalCtx<'_> { } } +/// Return an iterator over the individual components assembled by a +/// `Compose` expression. +/// +/// Given `ty` and `components` from an `Expression::Compose`, return an +/// iterator over the components of the resulting value. +/// +/// Normally, this would just be an iterator over `components`. However, +/// `Compose` expressions can concatenate vectors, in which case the i'th +/// value being composed is not generally the i'th element of `components`. +/// This function consults `ty` to decide if this concatenation is occuring, +/// and returns an iterator that produces the components of the result of +/// the `Compose` expression in either case. +pub fn flatten_compose<'arenas>( + ty: crate::Handle, + components: &'arenas [crate::Handle], + expressions: &'arenas crate::Arena, + types: &'arenas crate::UniqueArena, +) -> impl Iterator> + 'arenas { + // Returning `impl Iterator` is a bit tricky. We may or may not want to + // flatten the components, but we have to settle on a single concrete + // type to return. The below is a single iterator chain that handles + // both the flattening and non-flattening cases. + let (size, is_vector) = if let crate::TypeInner::Vector { size, .. } = types[ty].inner { + (size as usize, true) + } else { + (components.len(), false) + }; + + fn flattener<'c>( + component: &'c crate::Handle, + is_vector: bool, + expressions: &'c crate::Arena, + ) -> &'c [crate::Handle] { + if is_vector { + if let crate::Expression::Compose { + ty: _, + components: ref subcomponents, + } = expressions[*component] + { + return subcomponents; + } + } + std::slice::from_ref(component) + } + + // Expressions like `vec4(vec3(vec2(6, 7), 8), 9)` require us to flatten + // two levels. + components + .iter() + .flat_map(move |component| flattener(component, is_vector, expressions)) + .flat_map(move |component| flattener(component, is_vector, expressions)) + .take(size) + .cloned() +} + #[test] fn test_matrix_size() { let module = crate::Module::default(); diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl new file mode 100644 index 000000000..c89e61d49 --- /dev/null +++ b/tests/in/const-exprs.wgsl @@ -0,0 +1,14 @@ +@group(0) @binding(0) var out: vec4; +@group(0) @binding(1) var out2: i32; +@group(0) @binding(2) var out3: i32; + +@compute @workgroup_size(1) +fn main() { + let a = vec2(1, 2); + let b = vec2(3, 4); + out = vec4(a, b).wzyx; + + out2 = vec4(a, b)[1]; + + out3 = vec4(vec3(vec2(6, 7), 8), 9)[0]; +} diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl new file mode 100644 index 000000000..ff634004c --- /dev/null +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -0,0 +1,23 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +layout(std430) buffer type_block_0Compute { ivec4 _group_0_binding_0_cs; }; + +layout(std430) buffer type_1_block_1Compute { int _group_0_binding_1_cs; }; + +layout(std430) buffer type_1_block_2Compute { int _group_0_binding_2_cs; }; + + +void main() { + ivec2 a = ivec2(1, 2); + ivec2 b = ivec2(3, 4); + _group_0_binding_0_cs = ivec4(4, 3, 2, 1); + _group_0_binding_1_cs = 2; + _group_0_binding_2_cs = 6; + return; +} + diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl new file mode 100644 index 000000000..f6faee1d4 --- /dev/null +++ b/tests/out/hlsl/const-exprs.hlsl @@ -0,0 +1,14 @@ +RWByteAddressBuffer out_ : register(u0); +RWByteAddressBuffer out2_ : register(u1); +RWByteAddressBuffer out3_ : register(u2); + +[numthreads(1, 1, 1)] +void main() +{ + int2 a = int2(1, 2); + int2 b = int2(3, 4); + out_.Store4(0, asuint(int4(4, 3, 2, 1))); + out2_.Store(0, asuint(2)); + out3_.Store(0, asuint(6)); + return; +} diff --git a/tests/out/hlsl/const-exprs.ron b/tests/out/hlsl/const-exprs.ron new file mode 100644 index 000000000..a07b03300 --- /dev/null +++ b/tests/out/hlsl/const-exprs.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ], + compute:[ + ( + entry_point:"main", + target_profile:"cs_5_1", + ), + ], +) diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl new file mode 100644 index 000000000..19b9b727f --- /dev/null +++ b/tests/out/msl/const-exprs.msl @@ -0,0 +1,19 @@ +// language: metal2.0 +#include +#include + +using metal::uint; + + +kernel void main_( + device metal::int4& out [[user(fake0)]] +, device int& out2_ [[user(fake0)]] +, device int& out3_ [[user(fake0)]] +) { + metal::int2 a = metal::int2(1, 2); + metal::int2 b = metal::int2(3, 4); + out = metal::int4(4, 3, 2, 1); + out2_ = 2; + out3_ = 6; + return; +} diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm new file mode 100644 index 000000000..23f7d242e --- /dev/null +++ b/tests/out/spv/const-exprs.spvasm @@ -0,0 +1,60 @@ +; SPIR-V +; Version: 1.1 +; Generator: rspirv +; Bound: 34 +OpCapability Shader +OpExtension "SPV_KHR_storage_buffer_storage_class" +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %16 "main" +OpExecutionMode %16 LocalSize 1 1 1 +OpDecorate %6 DescriptorSet 0 +OpDecorate %6 Binding 0 +OpDecorate %7 Block +OpMemberDecorate %7 0 Offset 0 +OpDecorate %9 DescriptorSet 0 +OpDecorate %9 Binding 1 +OpDecorate %10 Block +OpMemberDecorate %10 0 Offset 0 +OpDecorate %12 DescriptorSet 0 +OpDecorate %12 Binding 2 +OpDecorate %13 Block +OpMemberDecorate %13 0 Offset 0 +%2 = OpTypeVoid +%4 = OpTypeInt 32 1 +%3 = OpTypeVector %4 4 +%5 = OpTypeVector %4 2 +%7 = OpTypeStruct %3 +%8 = OpTypePointer StorageBuffer %7 +%6 = OpVariable %8 StorageBuffer +%10 = OpTypeStruct %4 +%11 = OpTypePointer StorageBuffer %10 +%9 = OpVariable %11 StorageBuffer +%13 = OpTypeStruct %4 +%14 = OpTypePointer StorageBuffer %13 +%12 = OpVariable %14 StorageBuffer +%17 = OpTypeFunction %2 +%18 = OpTypePointer StorageBuffer %3 +%20 = OpTypeInt 32 0 +%19 = OpConstant %20 0 +%22 = OpTypePointer StorageBuffer %4 +%25 = OpConstant %4 1 +%26 = OpConstant %4 2 +%27 = OpConstantComposite %5 %25 %26 +%28 = OpConstant %4 3 +%29 = OpConstant %4 4 +%30 = OpConstantComposite %5 %28 %29 +%31 = OpConstantComposite %3 %29 %28 %26 %25 +%32 = OpConstant %4 6 +%16 = OpFunction %2 None %17 +%15 = OpLabel +%21 = OpAccessChain %18 %6 %19 +%23 = OpAccessChain %22 %9 %19 +%24 = OpAccessChain %22 %12 %19 +OpBranch %33 +%33 = OpLabel +OpStore %21 %31 +OpStore %23 %26 +OpStore %24 %32 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl new file mode 100644 index 000000000..201535836 --- /dev/null +++ b/tests/out/wgsl/const-exprs.wgsl @@ -0,0 +1,16 @@ +@group(0) @binding(0) +var out: vec4; +@group(0) @binding(1) +var out2_: i32; +@group(0) @binding(2) +var out3_: i32; + +@compute @workgroup_size(1, 1, 1) +fn main() { + let a = vec2(1, 2); + let b = vec2(3, 4); + out = vec4(4, 3, 2, 1); + out2_ = 2; + out3_ = 6; + return; +} diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 495bea959..2bc7f4544 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -777,6 +777,10 @@ fn convert_wgsl() { Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), ("msl-varyings", Targets::METAL), + ( + "const-exprs", + Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, + ), ]; for &(name, targets) in inputs.iter() { From bdcb9f6f64becc7ee2a91ee143227335b0b231a0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 16:01:00 -0700 Subject: [PATCH 2137/2212] Split `const-exprs.rs` test into separate functions. Also, just use a single out variable for each type. rather than introducing a new output variable for every test we add. --- tests/in/const-exprs.wgsl | 22 ++++- tests/out/glsl/const-exprs.main.Compute.glsl | 27 ++++-- tests/out/hlsl/const-exprs.hlsl | 31 +++++-- tests/out/msl/const-exprs.msl | 36 ++++++-- tests/out/spv/const-exprs.spvasm | 86 ++++++++++++-------- tests/out/wgsl/const-exprs.wgsl | 29 +++++-- 6 files changed, 172 insertions(+), 59 deletions(-) diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl index c89e61d49..d2b084c38 100644 --- a/tests/in/const-exprs.wgsl +++ b/tests/in/const-exprs.wgsl @@ -1,14 +1,28 @@ @group(0) @binding(0) var out: vec4; @group(0) @binding(1) var out2: i32; -@group(0) @binding(2) var out3: i32; @compute @workgroup_size(1) fn main() { + swizzle_of_compose(); + index_of_compose(); + compose_three_deep(); +} + +// Swizzle the value of nested Compose expressions. +fn swizzle_of_compose() { let a = vec2(1, 2); let b = vec2(3, 4); - out = vec4(a, b).wzyx; + out = vec4(a, b).wzyx; // should assign vec4(4, 3, 2, 1); +} - out2 = vec4(a, b)[1]; +// Index the value of nested Compose expressions. +fn index_of_compose() { + let a = vec2(1, 2); + let b = vec2(3, 4); + out2 += vec4(a, b)[1]; // should assign 2 +} - out3 = vec4(vec3(vec2(6, 7), 8), 9)[0]; +// Index the value of Compose expressions nested three deep +fn compose_three_deep() { + out2 += vec4(vec3(vec2(6, 7), 8), 9)[0]; // should assign 6 } diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index ff634004c..9b676196d 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -9,15 +9,32 @@ layout(std430) buffer type_block_0Compute { ivec4 _group_0_binding_0_cs; }; layout(std430) buffer type_1_block_1Compute { int _group_0_binding_1_cs; }; -layout(std430) buffer type_1_block_2Compute { int _group_0_binding_2_cs; }; - -void main() { +void swizzle_of_compose() { ivec2 a = ivec2(1, 2); ivec2 b = ivec2(3, 4); _group_0_binding_0_cs = ivec4(4, 3, 2, 1); - _group_0_binding_1_cs = 2; - _group_0_binding_2_cs = 6; + return; +} + +void index_of_compose() { + ivec2 a_1 = ivec2(1, 2); + ivec2 b_1 = ivec2(3, 4); + int _e7 = _group_0_binding_1_cs; + _group_0_binding_1_cs = (_e7 + 2); + return; +} + +void compose_three_deep() { + int _e2 = _group_0_binding_1_cs; + _group_0_binding_1_cs = (_e2 + 6); + return; +} + +void main() { + swizzle_of_compose(); + index_of_compose(); + compose_three_deep(); return; } diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index f6faee1d4..4275b5236 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -1,14 +1,35 @@ RWByteAddressBuffer out_ : register(u0); RWByteAddressBuffer out2_ : register(u1); -RWByteAddressBuffer out3_ : register(u2); -[numthreads(1, 1, 1)] -void main() +void swizzle_of_compose() { int2 a = int2(1, 2); int2 b = int2(3, 4); out_.Store4(0, asuint(int4(4, 3, 2, 1))); - out2_.Store(0, asuint(2)); - out3_.Store(0, asuint(6)); + return; +} + +void index_of_compose() +{ + int2 a_1 = int2(1, 2); + int2 b_1 = int2(3, 4); + int _expr7 = asint(out2_.Load(0)); + out2_.Store(0, asuint((_expr7 + 2))); + return; +} + +void compose_three_deep() +{ + int _expr2 = asint(out2_.Load(0)); + out2_.Store(0, asuint((_expr2 + 6))); + return; +} + +[numthreads(1, 1, 1)] +void main() +{ + swizzle_of_compose(); + index_of_compose(); + compose_three_deep(); return; } diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 19b9b727f..4c55afb43 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -5,15 +5,39 @@ using metal::uint; -kernel void main_( - device metal::int4& out [[user(fake0)]] -, device int& out2_ [[user(fake0)]] -, device int& out3_ [[user(fake0)]] +void swizzle_of_compose( + device metal::int4& out ) { metal::int2 a = metal::int2(1, 2); metal::int2 b = metal::int2(3, 4); out = metal::int4(4, 3, 2, 1); - out2_ = 2; - out3_ = 6; + return; +} + +void index_of_compose( + device int& out2_ +) { + metal::int2 a_1 = metal::int2(1, 2); + metal::int2 b_1 = metal::int2(3, 4); + int _e7 = out2_; + out2_ = _e7 + 2; + return; +} + +void compose_three_deep( + device int& out2_ +) { + int _e2 = out2_; + out2_ = _e2 + 6; + return; +} + +kernel void main_( + device metal::int4& out [[user(fake0)]] +, device int& out2_ [[user(fake0)]] +) { + swizzle_of_compose(out); + index_of_compose(out2_); + compose_three_deep(out2_); return; } diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index 23f7d242e..091ad78d1 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 34 +; Bound: 49 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %16 "main" -OpExecutionMode %16 LocalSize 1 1 1 +OpEntryPoint GLCompute %42 "main" +OpExecutionMode %42 LocalSize 1 1 1 OpDecorate %6 DescriptorSet 0 OpDecorate %6 Binding 0 OpDecorate %7 Block @@ -16,10 +16,6 @@ OpDecorate %9 DescriptorSet 0 OpDecorate %9 Binding 1 OpDecorate %10 Block OpMemberDecorate %10 0 Offset 0 -OpDecorate %12 DescriptorSet 0 -OpDecorate %12 Binding 2 -OpDecorate %13 Block -OpMemberDecorate %13 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 4 @@ -30,31 +26,55 @@ OpMemberDecorate %13 0 Offset 0 %10 = OpTypeStruct %4 %11 = OpTypePointer StorageBuffer %10 %9 = OpVariable %11 StorageBuffer -%13 = OpTypeStruct %4 -%14 = OpTypePointer StorageBuffer %13 -%12 = OpVariable %14 StorageBuffer -%17 = OpTypeFunction %2 -%18 = OpTypePointer StorageBuffer %3 -%20 = OpTypeInt 32 0 -%19 = OpConstant %20 0 -%22 = OpTypePointer StorageBuffer %4 -%25 = OpConstant %4 1 -%26 = OpConstant %4 2 -%27 = OpConstantComposite %5 %25 %26 -%28 = OpConstant %4 3 -%29 = OpConstant %4 4 -%30 = OpConstantComposite %5 %28 %29 -%31 = OpConstantComposite %3 %29 %28 %26 %25 -%32 = OpConstant %4 6 -%16 = OpFunction %2 None %17 -%15 = OpLabel -%21 = OpAccessChain %18 %6 %19 -%23 = OpAccessChain %22 %9 %19 -%24 = OpAccessChain %22 %12 %19 -OpBranch %33 -%33 = OpLabel -OpStore %21 %31 -OpStore %23 %26 -OpStore %24 %32 +%14 = OpTypeFunction %2 +%15 = OpTypePointer StorageBuffer %3 +%17 = OpTypeInt 32 0 +%16 = OpConstant %17 0 +%19 = OpConstant %4 1 +%20 = OpConstant %4 2 +%21 = OpConstantComposite %5 %19 %20 +%22 = OpConstant %4 3 +%23 = OpConstant %4 4 +%24 = OpConstantComposite %5 %22 %23 +%25 = OpConstantComposite %3 %23 %22 %20 %19 +%29 = OpTypePointer StorageBuffer %4 +%37 = OpConstant %4 6 +%13 = OpFunction %2 None %14 +%12 = OpLabel +%18 = OpAccessChain %15 %6 %16 +OpBranch %26 +%26 = OpLabel +OpStore %18 %25 +OpReturn +OpFunctionEnd +%28 = OpFunction %2 None %14 +%27 = OpLabel +%30 = OpAccessChain %29 %9 %16 +OpBranch %31 +%31 = OpLabel +%32 = OpLoad %4 %30 +%33 = OpIAdd %4 %32 %20 +OpStore %30 %33 +OpReturn +OpFunctionEnd +%35 = OpFunction %2 None %14 +%34 = OpLabel +%36 = OpAccessChain %29 %9 %16 +OpBranch %38 +%38 = OpLabel +%39 = OpLoad %4 %36 +%40 = OpIAdd %4 %39 %37 +OpStore %36 %40 +OpReturn +OpFunctionEnd +%42 = OpFunction %2 None %14 +%41 = OpLabel +%43 = OpAccessChain %15 %6 %16 +%44 = OpAccessChain %29 %9 %16 +OpBranch %45 +%45 = OpLabel +%46 = OpFunctionCall %2 %13 +%47 = OpFunctionCall %2 %28 +%48 = OpFunctionCall %2 %35 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index 201535836..d93369f76 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -2,15 +2,32 @@ var out: vec4; @group(0) @binding(1) var out2_: i32; -@group(0) @binding(2) -var out3_: i32; -@compute @workgroup_size(1, 1, 1) -fn main() { +fn swizzle_of_compose() { let a = vec2(1, 2); let b = vec2(3, 4); out = vec4(4, 3, 2, 1); - out2_ = 2; - out3_ = 6; + return; +} + +fn index_of_compose() { + let a_1 = vec2(1, 2); + let b_1 = vec2(3, 4); + let _e7 = out2_; + out2_ = (_e7 + 2); + return; +} + +fn compose_three_deep() { + let _e2 = out2_; + out2_ = (_e2 + 6); + return; +} + +@compute @workgroup_size(1, 1, 1) +fn main() { + swizzle_of_compose(); + index_of_compose(); + compose_three_deep(); return; } From ab177af3ba56ef00348deb1c55894f37b012911a Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 20 Sep 2023 16:01:00 -0700 Subject: [PATCH 2138/2212] Test that only constant expressions are hoisted to initializers. --- tests/in/const-exprs.wgsl | 20 +++++++++ tests/out/glsl/const-exprs.main.Compute.glsl | 19 ++++++++ tests/out/hlsl/const-exprs.hlsl | 21 +++++++++ tests/out/msl/const-exprs.msl | 21 +++++++++ tests/out/spv/const-exprs.spvasm | 47 ++++++++++++++++---- tests/out/wgsl/const-exprs.wgsl | 20 +++++++++ 6 files changed, 139 insertions(+), 9 deletions(-) diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl index d2b084c38..fd1b9c31b 100644 --- a/tests/in/const-exprs.wgsl +++ b/tests/in/const-exprs.wgsl @@ -6,6 +6,7 @@ fn main() { swizzle_of_compose(); index_of_compose(); compose_three_deep(); + non_constant_initializers(); } // Swizzle the value of nested Compose expressions. @@ -26,3 +27,22 @@ fn index_of_compose() { fn compose_three_deep() { out2 += vec4(vec3(vec2(6, 7), 8), 9)[0]; // should assign 6 } + +// While WGSL allows local variables to be declared anywhere in the function, +// Naga treats them all as appearing at the top of the function. To ensure that +// WGSL initializer expressions are evaluated at the right time, in the general +// case they need to be turned into Naga `Store` statements executed at the +// point of the WGSL declaration. +// +// When a variable's initializer is a constant expression, however, it can be +// evaluated at any time. The WGSL front end thus renders locals with +// initializers that are constants as Naga locals with initializers. This test +// checks that Naga local variable initializers are only used when safe. +fn non_constant_initializers() { + var w = 10 + 20; + var x = w; + var y = x; + var z = 30 + 40; + + out += vec4(w, x, y, z); +} diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index 9b676196d..df029bdaa 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -31,10 +31,29 @@ void compose_three_deep() { return; } +void non_constant_initializers() { + int w = 30; + int x = 0; + int y = 0; + int z = 70; + int _e2 = w; + x = _e2; + int _e4 = x; + y = _e4; + int _e9 = w; + int _e10 = x; + int _e11 = y; + int _e12 = z; + ivec4 _e14 = _group_0_binding_0_cs; + _group_0_binding_0_cs = (_e14 + ivec4(_e9, _e10, _e11, _e12)); + return; +} + void main() { swizzle_of_compose(); index_of_compose(); compose_three_deep(); + non_constant_initializers(); return; } diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index 4275b5236..a43f27b02 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -25,11 +25,32 @@ void compose_three_deep() return; } +void non_constant_initializers() +{ + int w = 30; + int x = (int)0; + int y = (int)0; + int z = 70; + + int _expr2 = w; + x = _expr2; + int _expr4 = x; + y = _expr4; + int _expr9 = w; + int _expr10 = x; + int _expr11 = y; + int _expr12 = z; + int4 _expr14 = asint(out_.Load4(0)); + out_.Store4(0, asuint((_expr14 + int4(_expr9, _expr10, _expr11, _expr12)))); + return; +} + [numthreads(1, 1, 1)] void main() { swizzle_of_compose(); index_of_compose(); compose_three_deep(); + non_constant_initializers(); return; } diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 4c55afb43..a9aa55999 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -32,6 +32,26 @@ void compose_three_deep( return; } +void non_constant_initializers( + device metal::int4& out +) { + int w = 30; + int x = {}; + int y = {}; + int z = 70; + int _e2 = w; + x = _e2; + int _e4 = x; + y = _e4; + int _e9 = w; + int _e10 = x; + int _e11 = y; + int _e12 = z; + metal::int4 _e14 = out; + out = _e14 + metal::int4(_e9, _e10, _e11, _e12); + return; +} + kernel void main_( device metal::int4& out [[user(fake0)]] , device int& out2_ [[user(fake0)]] @@ -39,5 +59,6 @@ kernel void main_( swizzle_of_compose(out); index_of_compose(out2_); compose_three_deep(out2_); + non_constant_initializers(out); return; } diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index 091ad78d1..50b0373a4 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 49 +; Bound: 72 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %42 "main" -OpExecutionMode %42 LocalSize 1 1 1 +OpEntryPoint GLCompute %64 "main" +OpExecutionMode %64 LocalSize 1 1 1 OpDecorate %6 DescriptorSet 0 OpDecorate %6 Binding 0 OpDecorate %7 Block @@ -39,6 +39,11 @@ OpMemberDecorate %10 0 Offset 0 %25 = OpConstantComposite %3 %23 %22 %20 %19 %29 = OpTypePointer StorageBuffer %4 %37 = OpConstant %4 6 +%44 = OpConstant %4 30 +%45 = OpConstant %4 70 +%47 = OpTypePointer Function %4 +%49 = OpConstantNull %4 +%51 = OpConstantNull %4 %13 = OpFunction %2 None %14 %12 = OpLabel %18 = OpAccessChain %15 %6 %16 @@ -69,12 +74,36 @@ OpReturn OpFunctionEnd %42 = OpFunction %2 None %14 %41 = OpLabel +%48 = OpVariable %47 Function %49 +%52 = OpVariable %47 Function %45 +%46 = OpVariable %47 Function %44 +%50 = OpVariable %47 Function %51 %43 = OpAccessChain %15 %6 %16 -%44 = OpAccessChain %29 %9 %16 -OpBranch %45 -%45 = OpLabel -%46 = OpFunctionCall %2 %13 -%47 = OpFunctionCall %2 %28 -%48 = OpFunctionCall %2 %35 +OpBranch %53 +%53 = OpLabel +%54 = OpLoad %4 %46 +OpStore %48 %54 +%55 = OpLoad %4 %48 +OpStore %50 %55 +%56 = OpLoad %4 %46 +%57 = OpLoad %4 %48 +%58 = OpLoad %4 %50 +%59 = OpLoad %4 %52 +%60 = OpCompositeConstruct %3 %56 %57 %58 %59 +%61 = OpLoad %3 %43 +%62 = OpIAdd %3 %61 %60 +OpStore %43 %62 +OpReturn +OpFunctionEnd +%64 = OpFunction %2 None %14 +%63 = OpLabel +%65 = OpAccessChain %15 %6 %16 +%66 = OpAccessChain %29 %9 %16 +OpBranch %67 +%67 = OpLabel +%68 = OpFunctionCall %2 %13 +%69 = OpFunctionCall %2 %28 +%70 = OpFunctionCall %2 %35 +%71 = OpFunctionCall %2 %42 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index d93369f76..dcef1812b 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -24,10 +24,30 @@ fn compose_three_deep() { return; } +fn non_constant_initializers() { + var w: i32 = 30; + var x: i32; + var y: i32; + var z: i32 = 70; + + let _e2 = w; + x = _e2; + let _e4 = x; + y = _e4; + let _e9 = w; + let _e10 = x; + let _e11 = y; + let _e12 = z; + let _e14 = out; + out = (_e14 + vec4(_e9, _e10, _e11, _e12)); + return; +} + @compute @workgroup_size(1, 1, 1) fn main() { swizzle_of_compose(); index_of_compose(); compose_three_deep(); + non_constant_initializers(); return; } From c33d7ee40dd1b384c01a74a8d9fc7a91ba4ddb20 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 22 Sep 2023 18:49:05 +0200 Subject: [PATCH 2139/2212] add an expression constness tracker --- src/back/spv/block.rs | 7 +- src/back/spv/mod.rs | 3 + src/back/spv/writer.rs | 10 +- src/front/glsl/context.rs | 49 +- src/front/glsl/parser/declarations.rs | 26 +- src/front/wgsl/lower/mod.rs | 40 +- src/proc/constant_evaluator.rs | 169 ++- src/proc/mod.rs | 4 +- tests/out/spv/debug-symbol-terrain.spvasm | 1171 +++++++++-------- .../out/wgsl/local-var-init-in-loop.comp.wgsl | 5 +- tests/out/wgsl/samplers.frag.wgsl | 376 +++--- 11 files changed, 1007 insertions(+), 853 deletions(-) diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 342a3805f..4dba7ea0c 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -245,7 +245,7 @@ impl<'w> BlockContext<'w> { crate::Expression::ZeroValue(_) => self.writer.get_constant_null(result_type_id), crate::Expression::Compose { ty, ref components } => { self.temp_list.clear(); - if self.ir_function.expressions.is_const(expr_handle) { + if self.expression_constness.is_const(expr_handle) { self.temp_list.extend( crate::proc::flatten_compose( ty, @@ -274,7 +274,7 @@ impl<'w> BlockContext<'w> { let value_id = self.cached[value]; let components = &[value_id; 4][..size as usize]; - if self.ir_function.expressions.is_const(expr_handle) { + if self.expression_constness.is_const(expr_handle) { let ty = self .writer .get_expression_lookup_type(&self.fun_info[expr_handle].ty); @@ -1776,7 +1776,8 @@ impl<'w> BlockContext<'w> { match *statement { crate::Statement::Emit(ref range) => { for handle in range.clone() { - if !self.ir_function.expressions.is_const(handle) { + // omit const expressions as we've already cached those + if !self.expression_constness.is_const(handle) { self.cache_expression_value(handle, &mut block)?; } } diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs index c52827908..ac7281fc6 100644 --- a/src/back/spv/mod.rs +++ b/src/back/spv/mod.rs @@ -557,6 +557,9 @@ struct BlockContext<'w> { /// The `Writer`'s temporary vector, for convenience. temp_list: Vec, + + /// Tracks the constness of `Expression`s residing in `self.ir_function.expressions` + expression_constness: crate::proc::ExpressionConstnessTracker, } impl BlockContext<'_> { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 0f4809565..2e133985a 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -620,13 +620,16 @@ impl Writer { // Steal the Writer's temp list for a bit. temp_list: std::mem::take(&mut self.temp_list), writer: self, + expression_constness: crate::proc::ExpressionConstnessTracker::from_arena( + &ir_function.expressions, + ), }; - // fill up the pre-emitted expressions + // fill up the pre-emitted and const expressions context.cached.reset(ir_function.expressions.len()); for (handle, expr) in ir_function.expressions.iter() { if (expr.needs_pre_emit() && !matches!(*expr, crate::Expression::LocalVariable(_))) - || ir_function.expressions.is_const(handle) + || context.expression_constness.is_const(handle) { context.cache_expression_value(handle, &mut prelude)?; } @@ -665,8 +668,9 @@ impl Writer { .insert(handle, LocalVariable { id, instruction }); } + // cache local variable expressions for (handle, expr) in ir_function.expressions.iter() { - if expr.needs_pre_emit() && matches!(*expr, crate::Expression::LocalVariable(_)) { + if matches!(*expr, crate::Expression::LocalVariable(_)) { context.cache_expression_value(handle, &mut prelude)?; } } diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 0fe0f734a..871d110c7 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -77,6 +77,8 @@ pub struct Context<'a> { pub body: Block, pub module: &'a mut crate::Module, pub is_const: bool, + /// Tracks the constness of `Expression`s residing in `self.expressions` + pub expression_constness: crate::proc::ExpressionConstnessTracker, } impl<'a> Context<'a> { @@ -99,6 +101,7 @@ impl<'a> Context<'a> { body: Block::new(), module, is_const: false, + expression_constness: crate::proc::ExpressionConstnessTracker::new(), }; this.emit_start(); @@ -245,21 +248,16 @@ impl<'a> Context<'a> { } pub fn add_expression(&mut self, expr: Expression, meta: Span) -> Result> { - let (expressions, const_expressions) = if self.is_const { - (&mut self.module.const_expressions, None) + let mut eval = if self.is_const { + crate::proc::ConstantEvaluator::for_module(self.module) } else { - (&mut self.expressions, Some(&self.module.const_expressions)) - }; - - let mut eval = crate::proc::ConstantEvaluator { - types: &mut self.module.types, - constants: &self.module.constants, - expressions, - const_expressions, - emitter: (!self.is_const).then_some(crate::proc::ConstantEvaluatorEmitter { - emitter: &mut self.emitter, - block: &mut self.body, - }), + crate::proc::ConstantEvaluator::for_function( + self.module, + &mut self.expressions, + &mut self.expression_constness, + &mut self.emitter, + &mut self.body, + ) }; let res = eval.try_eval_and_append(&expr, meta).map_err(|e| Error { @@ -269,17 +267,20 @@ impl<'a> Context<'a> { match res { Ok(expr) => Ok(expr), - Err(e) if self.is_const => Err(e), - Err(_) => { - let needs_pre_emit = expr.needs_pre_emit(); - if needs_pre_emit { - self.body.extend(self.emitter.finish(expressions)); + Err(e) => { + if self.is_const { + Err(e) + } else { + let needs_pre_emit = expr.needs_pre_emit(); + if needs_pre_emit { + self.body.extend(self.emitter.finish(&self.expressions)); + } + let h = self.expressions.append(expr, meta); + if needs_pre_emit { + self.emitter.start(&self.expressions); + } + Ok(h) } - let h = expressions.append(expr, meta); - if needs_pre_emit { - self.emitter.start(expressions); - } - Ok(h) } } } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index d21366961..02ee2bede 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -246,18 +246,26 @@ impl<'source> ParsingContext<'source> { }) .transpose()?; - let (decl_initializer, late_initializer) = if is_global_const { - (init, None) + let decl_initializer; + let late_initializer; + if is_global_const { + decl_initializer = init; + late_initializer = None; } else if ctx.external { - let decl_initializer = + decl_initializer = init.and_then(|expr| ctx.ctx.lift_up_const_expression(expr).ok()); - (decl_initializer, None) + late_initializer = None; + } else if let Some(init) = init { + if ctx.is_inside_loop || !ctx.ctx.expression_constness.is_const(init) { + decl_initializer = None; + late_initializer = Some(init); + } else { + decl_initializer = Some(init); + late_initializer = None; + } } else { - let decl_initializer = init.filter(|expr| ctx.ctx.expressions.is_const(*expr)); - let late_initializer = (decl_initializer.is_none() || ctx.is_inside_loop) - .then_some(init) - .flatten(); - (decl_initializer, late_initializer) + decl_initializer = None; + late_initializer = None; }; let pointer = ctx.add_var(frontend, ty, name, decl_initializer, meta)?; diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index f36840d3f..d419f2911 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -6,8 +6,8 @@ use crate::front::wgsl::parse::number::Number; use crate::front::wgsl::parse::{ast, conv}; use crate::front::Typifier; use crate::proc::{ - ensure_block_returns, Alignment, ConstantEvaluator, ConstantEvaluatorEmitter, Emitter, - Layouter, ResolveContext, TypeResolution, + ensure_block_returns, Alignment, ConstantEvaluator, Emitter, Layouter, ResolveContext, + TypeResolution, }; use crate::{Arena, FastHashMap, FastIndexMap, Handle, Span}; @@ -106,6 +106,8 @@ pub struct StatementContext<'source, 'temp, 'out> { named_expressions: &'out mut FastIndexMap, (String, Span)>, arguments: &'out [crate::FunctionArgument], module: &'out mut crate::Module, + /// Tracks the constness of `Expression`s residing in `self.naga_expressions` + expression_constness: &'temp mut crate::proc::ExpressionConstnessTracker, } impl<'a, 'temp> StatementContext<'a, 'temp, '_> { @@ -122,6 +124,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { named_expressions: self.named_expressions, arguments: self.arguments, module: self.module, + expression_constness: self.expression_constness, } } @@ -147,6 +150,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { typifier: self.typifier, block, emitter, + expression_constness: self.expression_constness, }), } } @@ -188,6 +192,8 @@ pub struct RuntimeExpressionContext<'temp, 'out> { block: &'temp mut crate::Block, emitter: &'temp mut Emitter, typifier: &'temp mut Typifier, + /// Tracks the constness of `Expression`s residing in `self.naga_expressions` + expression_constness: &'temp mut crate::proc::ExpressionConstnessTracker, } impl RuntimeExpressionContext<'_, '_> { @@ -200,6 +206,7 @@ impl RuntimeExpressionContext<'_, '_> { block: self.block, emitter: self.emitter, typifier: self.typifier, + expression_constness: self.expression_constness, } } } @@ -333,16 +340,13 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { ) -> Result, Error<'source>> { match self.expr_type { ExpressionContextType::Runtime(ref mut rctx) => { - let mut eval = ConstantEvaluator { - types: &mut self.module.types, - constants: &self.module.constants, - expressions: rctx.naga_expressions, - const_expressions: Some(&self.module.const_expressions), - emitter: Some(ConstantEvaluatorEmitter { - emitter: rctx.emitter, - block: rctx.block, - }), - }; + let mut eval = ConstantEvaluator::for_function( + self.module, + rctx.naga_expressions, + rctx.expression_constness, + rctx.emitter, + rctx.block, + ); match eval.try_eval_and_append(&expr, span) { Ok(expr) => Ok(expr), @@ -350,14 +354,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { } } ExpressionContextType::Constant => { - let mut eval = ConstantEvaluator { - types: &mut self.module.types, - constants: &self.module.constants, - expressions: &mut self.module.const_expressions, - const_expressions: None, - emitter: None, - }; - + let mut eval = ConstantEvaluator::for_module(self.module); eval.try_eval_and_append(&expr, span) .map_err(|e| Error::ConstantEvaluatorError(e, span)) } @@ -1027,6 +1024,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { types: ctx.types, module: ctx.module, arguments: &arguments, + expression_constness: &mut crate::proc::ExpressionConstnessTracker::new(), }, )?; ensure_block_returns(&mut body); @@ -1179,7 +1177,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let (const_initializer, initializer) = { match initializer { - Some(init) if ctx.naga_expressions.is_const(init) => { + Some(init) if ctx.expression_constness.is_const(init) => { (Some(init), is_inside_loop.then_some(init)) } Some(init) => (None, Some(init)), diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 9d2055ff6..9dc021275 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -6,21 +6,64 @@ use crate::{ #[derive(Debug)] pub struct ConstantEvaluator<'a> { - pub types: &'a mut UniqueArena, - pub constants: &'a Arena, - pub expressions: &'a mut Arena, - pub const_expressions: Option<&'a Arena>, + types: &'a mut UniqueArena, + constants: &'a Arena, + expressions: &'a mut Arena, - /// When `expressions` refers to a function's local expression - /// arena, this is the emitter we should interrupt when inserting - /// new things into it. - pub emitter: Option>, + /// When `self.expressions` refers to a function's local expression + /// arena, this needs to be populated + function_local_data: Option>, } #[derive(Debug)] -pub struct ConstantEvaluatorEmitter<'a> { - pub emitter: &'a mut super::Emitter, - pub block: &'a mut crate::Block, +struct FunctionLocalData<'a> { + /// Global constant expressions + const_expressions: &'a Arena, + /// Tracks the constness of expressions residing in `ConstantEvaluator.expressions` + expression_constness: &'a mut ExpressionConstnessTracker, + emitter: &'a mut super::Emitter, + block: &'a mut crate::Block, +} + +#[derive(Debug)] +pub struct ExpressionConstnessTracker { + inner: bit_set::BitSet, +} + +impl ExpressionConstnessTracker { + pub fn new() -> Self { + Self { + inner: bit_set::BitSet::new(), + } + } + + fn insert(&mut self, value: Handle) { + self.inner.insert(value.index()); + } + + pub fn is_const(&self, value: Handle) -> bool { + self.inner.contains(value.index()) + } + + pub fn from_arena(arena: &Arena) -> Self { + let mut tracker = Self::new(); + for (handle, expr) in arena.iter() { + let insert = match *expr { + crate::Expression::Literal(_) + | crate::Expression::ZeroValue(_) + | crate::Expression::Constant(_) => true, + crate::Expression::Compose { ref components, .. } => { + components.iter().all(|h| tracker.is_const(*h)) + } + crate::Expression::Splat { value, .. } => tracker.is_const(value), + _ => false, + }; + if insert { + tracker.insert(handle); + } + } + tracker + } } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -94,44 +137,68 @@ pub enum ConstantEvaluatorError { // Math // As -// TODO(teoxoy): consider accumulating this metadata instead of recursing through subexpressions -impl Arena { - pub fn is_const(&self, handle: Handle) -> bool { - match self[handle] { - Expression::Literal(_) | Expression::ZeroValue(_) | Expression::Constant(_) => true, - Expression::Compose { ref components, .. } => { - components.iter().all(|h| self.is_const(*h)) - } - Expression::Splat { ref value, .. } => self.is_const(*value), - _ => false, +impl<'a> ConstantEvaluator<'a> { + pub fn for_module(module: &'a mut crate::Module) -> Self { + Self { + types: &mut module.types, + constants: &module.constants, + expressions: &mut module.const_expressions, + function_local_data: None, } } -} -impl ConstantEvaluator<'_> { + pub fn for_function( + module: &'a mut crate::Module, + expressions: &'a mut Arena, + expression_constness: &'a mut ExpressionConstnessTracker, + emitter: &'a mut super::Emitter, + block: &'a mut crate::Block, + ) -> Self { + Self { + types: &mut module.types, + constants: &module.constants, + expressions, + function_local_data: Some(FunctionLocalData { + const_expressions: &module.const_expressions, + expression_constness, + emitter, + block, + }), + } + } + + fn check(&self, expr: Handle) -> Result<(), ConstantEvaluatorError> { + if let Some(ref function_local_data) = self.function_local_data { + if !function_local_data.expression_constness.is_const(expr) { + log::debug!("check: SubexpressionsAreNotConstant"); + return Err(ConstantEvaluatorError::SubexpressionsAreNotConstant); + } + } + Ok(()) + } + fn check_and_get( &mut self, expr: Handle, ) -> Result, ConstantEvaluatorError> { match self.expressions[expr] { - Expression::Literal(_) - | Expression::ZeroValue(_) - | Expression::Compose { .. } - | Expression::Splat { .. } => Ok(expr), Expression::Constant(c) => { // Are we working in a function's expression arena, or the // module's constant expression arena? - if let Some(const_expressions) = self.const_expressions { + if let Some(ref function_local_data) = self.function_local_data { // Deep-copy the constant's value into our arena. - self.copy_from(self.constants[c].init, const_expressions) + self.copy_from( + self.constants[c].init, + function_local_data.const_expressions, + ) } else { // "See through" the constant and use its initializer. Ok(self.constants[c].init) } } _ => { - log::debug!("check_and_get: SubexpressionsAreNotConstant"); - Err(ConstantEvaluatorError::SubexpressionsAreNotConstant) + self.check(expr)?; + Ok(expr) } } } @@ -148,12 +215,12 @@ impl ConstantEvaluator<'_> { } Expression::Compose { ref components, .. } => { for component in components { - self.check_and_get(*component)?; + self.check(*component)?; } Ok(self.register_evaluated_expr(expr.clone(), span)) } Expression::Splat { value, .. } => { - self.check_and_get(value)?; + self.check(value)?; Ok(self.register_evaluated_expr(expr.clone(), span)) } Expression::AccessIndex { base, index } => { @@ -835,20 +902,29 @@ impl ConstantEvaluator<'_> { } fn register_evaluated_expr(&mut self, expr: Expression, span: Span) -> Handle { - if let Some(ref mut emitter) = self.emitter { - let is_running = emitter.emitter.is_running(); + if let Some(FunctionLocalData { + ref mut emitter, + ref mut block, + ref mut expression_constness, + .. + }) = self.function_local_data + { + let is_running = emitter.is_running(); let needs_pre_emit = expr.needs_pre_emit(); if is_running && needs_pre_emit { - emitter - .block - .extend(emitter.emitter.finish(self.expressions)); + block.extend(emitter.finish(self.expressions)); let h = self.expressions.append(expr, span); - emitter.emitter.start(self.expressions); - return h; + emitter.start(self.expressions); + expression_constness.insert(h); + h + } else { + let h = self.expressions.append(expr, span); + expression_constness.insert(h); + h } + } else { + self.expressions.append(expr, span) } - - self.expressions.append(expr, span) } } @@ -1016,8 +1092,7 @@ mod tests { types: &mut types, constants: &constants, expressions: &mut const_expressions, - const_expressions: None, - emitter: None, + function_local_data: None, }; let res1 = solver @@ -1103,8 +1178,7 @@ mod tests { types: &mut types, constants: &constants, expressions: &mut const_expressions, - const_expressions: None, - emitter: None, + function_local_data: None, }; let res = solver @@ -1222,8 +1296,7 @@ mod tests { types: &mut types, constants: &constants, expressions: &mut const_expressions, - const_expressions: None, - emitter: None, + function_local_data: None, }; let root1 = Expression::AccessIndex { base, index: 1 }; diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 2121da01b..bfa0d160c 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -10,7 +10,9 @@ mod namer; mod terminator; mod typifier; -pub use constant_evaluator::{ConstantEvaluator, ConstantEvaluatorEmitter, ConstantEvaluatorError}; +pub use constant_evaluator::{ + ConstantEvaluator, ConstantEvaluatorError, ExpressionConstnessTracker, +}; pub use emitter::Emitter; pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength, IndexableLengthError}; pub use layouter::{Alignment, LayoutError, LayoutErrorInner, Layouter, TypeLayout}; diff --git a/tests/out/spv/debug-symbol-terrain.spvasm b/tests/out/spv/debug-symbol-terrain.spvasm index 3f53036ad..30ecd2f8f 100644 --- a/tests/out/spv/debug-symbol-terrain.spvasm +++ b/tests/out/spv/debug-symbol-terrain.spvasm @@ -1,19 +1,19 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 638 +; Bound: 644 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %341 "gen_terrain_compute" %338 -OpEntryPoint Vertex %411 "gen_terrain_vertex" %402 %405 %407 %409 -OpEntryPoint Fragment %459 "gen_terrain_fragment" %449 %451 %454 %457 %458 -OpEntryPoint Vertex %552 "vs_main" %543 %546 %548 %549 %551 -OpEntryPoint Fragment %577 "fs_main" %570 %572 %574 %576 -OpExecutionMode %341 LocalSize 64 1 1 -OpExecutionMode %459 OriginUpperLeft -OpExecutionMode %577 OriginUpperLeft +OpEntryPoint GLCompute %345 "gen_terrain_compute" %342 +OpEntryPoint Vertex %415 "gen_terrain_vertex" %406 %409 %411 %413 +OpEntryPoint Fragment %465 "gen_terrain_fragment" %455 %457 %460 %463 %464 +OpEntryPoint Vertex %558 "vs_main" %549 %552 %554 %555 %557 +OpEntryPoint Fragment %583 "fs_main" %576 %578 %580 %582 +OpExecutionMode %345 LocalSize 64 1 1 +OpExecutionMode %465 OriginUpperLeft +OpExecutionMode %583 OriginUpperLeft %3 = OpString "debug-symbol-terrain.wgsl" OpSource Unknown 0 %3 "// Taken from https://github.com/sotrh/learn-wgpu/blob/11820796f5e1dbce42fb1119f04ddeb4b167d2a0/code/intermediate/tutorial13-terrain/src/terrain.wgsl // ============================ @@ -370,44 +370,44 @@ OpName %209 "x" OpName %211 "v" OpName %213 "a" OpName %214 "i" -OpName %251 "p" -OpName %252 "min_max_height" -OpName %253 "terrain_point" -OpName %264 "p" -OpName %265 "min_max_height" -OpName %266 "terrain_vertex" -OpName %296 "vert_index" -OpName %297 "chunk_size" -OpName %298 "chunk_corner" -OpName %299 "index_to_p" -OpName %315 "p" -OpName %316 "color23" -OpName %338 "gid" -OpName %341 "gen_terrain_compute" -OpName %402 "vindex" -OpName %405 "index" -OpName %407 "position" -OpName %409 "uv" -OpName %411 "gen_terrain_vertex" -OpName %449 "index" -OpName %451 "position" -OpName %454 "uv" -OpName %457 "vert_component" -OpName %458 "index" -OpName %459 "gen_terrain_fragment" -OpName %462 "vert_component" -OpName %463 "index" -OpName %543 "position" -OpName %546 "normal" -OpName %548 "clip_position" -OpName %549 "normal" -OpName %551 "world_pos" -OpName %552 "vs_main" -OpName %570 "clip_position" -OpName %572 "normal" -OpName %574 "world_pos" -OpName %577 "fs_main" -OpName %586 "color" +OpName %255 "p" +OpName %256 "min_max_height" +OpName %257 "terrain_point" +OpName %268 "p" +OpName %269 "min_max_height" +OpName %270 "terrain_vertex" +OpName %300 "vert_index" +OpName %301 "chunk_size" +OpName %302 "chunk_corner" +OpName %303 "index_to_p" +OpName %319 "p" +OpName %320 "color23" +OpName %342 "gid" +OpName %345 "gen_terrain_compute" +OpName %406 "vindex" +OpName %409 "index" +OpName %411 "position" +OpName %413 "uv" +OpName %415 "gen_terrain_vertex" +OpName %455 "index" +OpName %457 "position" +OpName %460 "uv" +OpName %463 "vert_component" +OpName %464 "index" +OpName %465 "gen_terrain_fragment" +OpName %468 "vert_component" +OpName %469 "index" +OpName %549 "position" +OpName %552 "normal" +OpName %554 "clip_position" +OpName %555 "normal" +OpName %557 "world_pos" +OpName %558 "vs_main" +OpName %576 "clip_position" +OpName %578 "normal" +OpName %580 "world_pos" +OpName %583 "fs_main" +OpName %592 "color" OpMemberDecorate %13 0 Offset 0 OpMemberDecorate %13 1 Offset 8 OpMemberDecorate %13 2 Offset 16 @@ -466,27 +466,27 @@ OpDecorate %49 DescriptorSet 2 OpDecorate %49 Binding 2 OpDecorate %50 DescriptorSet 2 OpDecorate %50 Binding 3 -OpDecorate %338 BuiltIn GlobalInvocationId -OpDecorate %402 BuiltIn VertexIndex -OpDecorate %405 Location 0 -OpDecorate %405 Flat -OpDecorate %407 BuiltIn Position -OpDecorate %409 Location 1 -OpDecorate %449 Location 0 -OpDecorate %449 Flat -OpDecorate %451 BuiltIn FragCoord -OpDecorate %454 Location 1 -OpDecorate %457 Location 0 -OpDecorate %458 Location 1 -OpDecorate %543 Location 0 -OpDecorate %546 Location 1 -OpDecorate %548 BuiltIn Position +OpDecorate %342 BuiltIn GlobalInvocationId +OpDecorate %406 BuiltIn VertexIndex +OpDecorate %409 Location 0 +OpDecorate %409 Flat +OpDecorate %411 BuiltIn Position +OpDecorate %413 Location 1 +OpDecorate %455 Location 0 +OpDecorate %455 Flat +OpDecorate %457 BuiltIn FragCoord +OpDecorate %460 Location 1 +OpDecorate %463 Location 0 +OpDecorate %464 Location 1 OpDecorate %549 Location 0 -OpDecorate %551 Location 1 -OpDecorate %570 BuiltIn FragCoord -OpDecorate %572 Location 0 -OpDecorate %574 Location 1 -OpDecorate %576 Location 0 +OpDecorate %552 Location 1 +OpDecorate %554 BuiltIn Position +OpDecorate %555 Location 0 +OpDecorate %557 Location 1 +OpDecorate %576 BuiltIn FragCoord +OpDecorate %578 Location 0 +OpDecorate %580 Location 1 +OpDecorate %582 Location 0 %2 = OpTypeVoid %5 = OpTypeFloat 32 %4 = OpTypeVector %5 3 @@ -582,80 +582,80 @@ OpDecorate %576 Location 0 %210 = OpConstantNull %6 %212 = OpTypePointer Function %5 %215 = OpTypePointer Function %8 -%254 = OpTypeFunction %4 %6 %6 -%267 = OpTypeFunction %14 %6 %6 -%268 = OpConstant %5 0.1 -%269 = OpConstantComposite %6 %268 %76 -%270 = OpConstantComposite %6 %76 %268 -%271 = OpConstant %5 -0.1 -%272 = OpConstantComposite %6 %271 %76 -%273 = OpConstantComposite %6 %76 %271 -%300 = OpTypeFunction %6 %8 %10 %11 -%317 = OpTypeFunction %4 %6 -%318 = OpConstant %5 23.0 -%319 = OpConstant %5 32.0 -%320 = OpConstantComposite %6 %318 %319 -%321 = OpConstant %5 -43.0 -%322 = OpConstant %5 3.0 -%323 = OpConstantComposite %6 %321 %322 -%339 = OpTypePointer Input %19 -%338 = OpVariable %339 Input -%342 = OpTypeFunction %2 -%343 = OpTypePointer Uniform %13 -%345 = OpConstant %8 6 -%346 = OpConstant %8 2 -%347 = OpConstant %8 3 -%348 = OpConstant %8 4 -%351 = OpTypePointer Uniform %10 -%354 = OpTypePointer Uniform %11 -%358 = OpTypePointer StorageBuffer %15 -%359 = OpTypePointer StorageBuffer %14 -%360 = OpTypePointer Uniform %6 -%367 = OpTypePointer Uniform %8 -%388 = OpTypePointer StorageBuffer %17 -%389 = OpTypePointer StorageBuffer %8 -%403 = OpTypePointer Input %8 -%402 = OpVariable %403 Input -%406 = OpTypePointer Output %8 -%405 = OpVariable %406 Output -%408 = OpTypePointer Output %7 -%407 = OpVariable %408 Output -%410 = OpTypePointer Output %6 +%258 = OpTypeFunction %4 %6 %6 +%271 = OpTypeFunction %14 %6 %6 +%272 = OpConstant %5 0.1 +%273 = OpConstantComposite %6 %272 %76 +%274 = OpConstantComposite %6 %76 %272 +%275 = OpConstant %5 -0.1 +%276 = OpConstantComposite %6 %275 %76 +%277 = OpConstantComposite %6 %76 %275 +%304 = OpTypeFunction %6 %8 %10 %11 +%321 = OpTypeFunction %4 %6 +%322 = OpConstant %5 23.0 +%323 = OpConstant %5 32.0 +%324 = OpConstantComposite %6 %322 %323 +%325 = OpConstant %5 -43.0 +%326 = OpConstant %5 3.0 +%327 = OpConstantComposite %6 %325 %326 +%343 = OpTypePointer Input %19 +%342 = OpVariable %343 Input +%346 = OpTypeFunction %2 +%347 = OpTypePointer Uniform %13 +%349 = OpConstant %8 6 +%350 = OpConstant %8 2 +%351 = OpConstant %8 3 +%352 = OpConstant %8 4 +%355 = OpTypePointer Uniform %10 +%358 = OpTypePointer Uniform %11 +%362 = OpTypePointer StorageBuffer %15 +%363 = OpTypePointer StorageBuffer %14 +%364 = OpTypePointer Uniform %6 +%371 = OpTypePointer Uniform %8 +%392 = OpTypePointer StorageBuffer %17 +%393 = OpTypePointer StorageBuffer %8 +%407 = OpTypePointer Input %8 +%406 = OpVariable %407 Input +%410 = OpTypePointer Output %8 %409 = OpVariable %410 Output -%412 = OpTypePointer Uniform %20 -%414 = OpConstant %5 -1.0 -%415 = OpConstantComposite %6 %414 %414 -%429 = OpTypePointer Uniform %8 -%449 = OpVariable %403 Input -%452 = OpTypePointer Input %7 -%451 = OpVariable %452 Input -%455 = OpTypePointer Input %6 -%454 = OpVariable %455 Input -%457 = OpVariable %406 Output -%458 = OpVariable %406 Output -%461 = OpConstant %5 6.0 -%544 = OpTypePointer Input %4 -%543 = OpVariable %544 Input -%546 = OpVariable %544 Input -%548 = OpVariable %408 Output -%550 = OpTypePointer Output %4 -%549 = OpVariable %550 Output -%551 = OpVariable %550 Output -%553 = OpTypePointer Uniform %24 -%556 = OpTypePointer Uniform %23 -%570 = OpVariable %452 Input -%572 = OpVariable %544 Input -%574 = OpVariable %544 Input -%576 = OpVariable %408 Output -%579 = OpTypePointer Uniform %25 -%581 = OpConstantComposite %4 %268 %268 %268 -%582 = OpConstant %5 0.7 -%583 = OpConstantComposite %4 %81 %268 %582 -%584 = OpConstant %5 0.2 -%585 = OpConstantComposite %4 %584 %584 %584 -%587 = OpConstantNull %4 -%602 = OpTypePointer Uniform %4 -%611 = OpTypePointer Uniform %7 +%412 = OpTypePointer Output %7 +%411 = OpVariable %412 Output +%414 = OpTypePointer Output %6 +%413 = OpVariable %414 Output +%416 = OpTypePointer Uniform %20 +%418 = OpConstant %5 -1.0 +%419 = OpConstantComposite %6 %418 %418 +%434 = OpTypePointer Uniform %8 +%455 = OpVariable %407 Input +%458 = OpTypePointer Input %7 +%457 = OpVariable %458 Input +%461 = OpTypePointer Input %6 +%460 = OpVariable %461 Input +%463 = OpVariable %410 Output +%464 = OpVariable %410 Output +%467 = OpConstant %5 6.0 +%550 = OpTypePointer Input %4 +%549 = OpVariable %550 Input +%552 = OpVariable %550 Input +%554 = OpVariable %412 Output +%556 = OpTypePointer Output %4 +%555 = OpVariable %556 Output +%557 = OpVariable %556 Output +%559 = OpTypePointer Uniform %24 +%562 = OpTypePointer Uniform %23 +%576 = OpVariable %458 Input +%578 = OpVariable %550 Input +%580 = OpVariable %550 Input +%582 = OpVariable %412 Output +%585 = OpTypePointer Uniform %25 +%587 = OpConstantComposite %4 %272 %272 %272 +%588 = OpConstant %5 0.7 +%589 = OpConstantComposite %4 %81 %272 %588 +%590 = OpConstant %5 0.2 +%591 = OpConstantComposite %4 %590 %590 %590 +%593 = OpConstantNull %4 +%608 = OpTypePointer Uniform %4 +%617 = OpTypePointer Uniform %7 %53 = OpFunction %4 None %54 %52 = OpFunctionParameter %4 %51 = OpLabel @@ -843,602 +843,609 @@ OpLine %3 40 14 %219 = OpExtInst %5 %1 Sin %81 %220 = OpCompositeConstruct %6 %218 %219 OpLine %3 41 15 -%221 = OpFNegate %5 %219 -%222 = OpCompositeConstruct %6 %218 %219 -%223 = OpCompositeConstruct %6 %221 %218 -%224 = OpCompositeConstruct %9 %222 %223 -OpBranch %225 -%225 = OpLabel +%221 = OpCompositeExtract %5 %220 0 +%222 = OpCompositeExtract %5 %220 1 +%223 = OpCompositeExtract %5 %220 1 +%224 = OpFNegate %5 %223 +%225 = OpCompositeExtract %5 %220 0 +%226 = OpCompositeConstruct %6 %221 %222 +%227 = OpCompositeConstruct %6 %224 %225 +%228 = OpCompositeConstruct %9 %226 %227 +OpBranch %229 +%229 = OpLabel OpLine %3 43 5 -OpLoopMerge %226 %228 None -OpBranch %227 -%227 = OpLabel -OpLine %3 43 22 -%229 = OpLoad %8 %214 -%230 = OpULessThan %114 %229 %205 -OpLine %3 43 21 -OpSelectionMerge %231 None -OpBranchConditional %230 %231 %232 -%232 = OpLabel -OpBranch %226 +OpLoopMerge %230 %232 None +OpBranch %231 %231 = OpLabel -OpBranch %233 -%233 = OpLabel +OpLine %3 43 22 +%233 = OpLoad %8 %214 +%234 = OpULessThan %114 %233 %205 +OpLine %3 43 21 +OpSelectionMerge %235 None +OpBranchConditional %234 %235 %236 +%236 = OpLabel +OpBranch %230 +%235 = OpLabel +OpBranch %237 +%237 = OpLabel OpLine %3 1 1 -%235 = OpLoad %5 %211 -%236 = OpLoad %5 %213 -%237 = OpLoad %6 %209 -OpLine %3 44 21 -%238 = OpFunctionCall %5 %67 %237 -OpLine %3 44 13 -%239 = OpFMul %5 %236 %238 -%240 = OpFAdd %5 %235 %239 -OpLine %3 44 9 -OpStore %211 %240 -OpLine %3 45 13 +%239 = OpLoad %5 %211 +%240 = OpLoad %5 %213 %241 = OpLoad %6 %209 -%242 = OpMatrixTimesVector %6 %224 %241 +OpLine %3 44 21 +%242 = OpFunctionCall %5 %67 %241 +OpLine %3 44 13 +%243 = OpFMul %5 %240 %242 +%244 = OpFAdd %5 %239 %243 +OpLine %3 44 9 +OpStore %211 %244 OpLine %3 45 13 -%243 = OpVectorTimesScalar %6 %242 %84 -%244 = OpFAdd %6 %243 %208 +%245 = OpLoad %6 %209 +%246 = OpMatrixTimesVector %6 %228 %245 +OpLine %3 45 13 +%247 = OpVectorTimesScalar %6 %246 %84 +%248 = OpFAdd %6 %247 %208 OpLine %3 45 9 -OpStore %209 %244 +OpStore %209 %248 OpLine %3 1 1 -%245 = OpLoad %5 %213 +%249 = OpLoad %5 %213 OpLine %3 46 13 -%246 = OpFMul %5 %245 %81 +%250 = OpFMul %5 %249 %81 OpLine %3 46 9 -OpStore %213 %246 -OpBranch %234 -%234 = OpLabel -OpBranch %228 -%228 = OpLabel +OpStore %213 %250 +OpBranch %238 +%238 = OpLabel +OpBranch %232 +%232 = OpLabel OpLine %3 1 1 -%247 = OpLoad %8 %214 +%251 = OpLoad %8 %214 OpLine %3 43 43 -%248 = OpIAdd %8 %247 %127 +%252 = OpIAdd %8 %251 %127 OpLine %3 43 39 -OpStore %214 %248 -OpBranch %225 -%226 = OpLabel +OpStore %214 %252 +OpBranch %229 +%230 = OpLabel OpLine %3 1 1 -%249 = OpLoad %5 %211 -OpReturnValue %249 +%253 = OpLoad %5 %211 +OpReturnValue %253 OpFunctionEnd -%253 = OpFunction %4 None %254 -%251 = OpFunctionParameter %6 -%252 = OpFunctionParameter %6 -%250 = OpLabel -OpBranch %255 -%255 = OpLabel +%257 = OpFunction %4 None %258 +%255 = OpFunctionParameter %6 +%256 = OpFunctionParameter %6 +%254 = OpLabel +OpBranch %259 +%259 = OpLabel OpLine %3 77 9 -%256 = OpCompositeExtract %5 %251 0 -%257 = OpCompositeExtract %5 %252 0 -%258 = OpCompositeExtract %5 %252 1 +%260 = OpCompositeExtract %5 %255 0 +%261 = OpCompositeExtract %5 %256 0 +%262 = OpCompositeExtract %5 %256 1 OpLine %3 78 49 -%259 = OpFunctionCall %5 %204 %251 +%263 = OpFunctionCall %5 %204 %255 OpLine %3 76 12 -%260 = OpExtInst %5 %1 FMix %257 %258 %259 -%261 = OpCompositeExtract %5 %251 1 -%262 = OpCompositeConstruct %4 %256 %260 %261 -OpReturnValue %262 +%264 = OpExtInst %5 %1 FMix %261 %262 %263 +%265 = OpCompositeExtract %5 %255 1 +%266 = OpCompositeConstruct %4 %260 %264 %265 +OpReturnValue %266 OpFunctionEnd -%266 = OpFunction %14 None %267 -%264 = OpFunctionParameter %6 -%265 = OpFunctionParameter %6 -%263 = OpLabel -OpBranch %274 -%274 = OpLabel +%270 = OpFunction %14 None %271 +%268 = OpFunctionParameter %6 +%269 = OpFunctionParameter %6 +%267 = OpLabel +OpBranch %278 +%278 = OpLabel OpLine %3 84 13 -%275 = OpFunctionCall %4 %253 %264 %265 +%279 = OpFunctionCall %4 %257 %268 %269 OpLine %3 86 29 -%276 = OpFAdd %6 %264 %269 +%280 = OpFAdd %6 %268 %273 OpLine %3 86 15 -%277 = OpFunctionCall %4 %253 %276 %265 +%281 = OpFunctionCall %4 %257 %280 %269 OpLine %3 86 15 -%278 = OpFSub %4 %277 %275 +%282 = OpFSub %4 %281 %279 OpLine %3 87 29 -%279 = OpFAdd %6 %264 %270 +%283 = OpFAdd %6 %268 %274 OpLine %3 87 15 -%280 = OpFunctionCall %4 %253 %279 %265 +%284 = OpFunctionCall %4 %257 %283 %269 OpLine %3 87 15 -%281 = OpFSub %4 %280 %275 +%285 = OpFSub %4 %284 %279 OpLine %3 88 29 -%282 = OpFAdd %6 %264 %272 +%286 = OpFAdd %6 %268 %276 OpLine %3 88 15 -%283 = OpFunctionCall %4 %253 %282 %265 +%287 = OpFunctionCall %4 %257 %286 %269 OpLine %3 88 15 -%284 = OpFSub %4 %283 %275 +%288 = OpFSub %4 %287 %279 OpLine %3 89 29 -%285 = OpFAdd %6 %264 %273 +%289 = OpFAdd %6 %268 %277 OpLine %3 89 15 -%286 = OpFunctionCall %4 %253 %285 %265 +%290 = OpFunctionCall %4 %257 %289 %269 OpLine %3 89 15 -%287 = OpFSub %4 %286 %275 +%291 = OpFSub %4 %290 %279 OpLine %3 91 14 -%288 = OpExtInst %4 %1 Cross %281 %278 -%289 = OpExtInst %4 %1 Normalize %288 +%292 = OpExtInst %4 %1 Cross %285 %282 +%293 = OpExtInst %4 %1 Normalize %292 OpLine %3 92 14 -%290 = OpExtInst %4 %1 Cross %287 %284 -%291 = OpExtInst %4 %1 Normalize %290 +%294 = OpExtInst %4 %1 Cross %291 %288 +%295 = OpExtInst %4 %1 Normalize %294 OpLine %3 94 14 -%292 = OpFAdd %4 %289 %291 +%296 = OpFAdd %4 %293 %295 OpLine %3 94 13 -%293 = OpVectorTimesScalar %4 %292 %81 +%297 = OpVectorTimesScalar %4 %296 %81 OpLine %3 96 12 -%294 = OpCompositeConstruct %14 %275 %293 -OpReturnValue %294 +%298 = OpCompositeConstruct %14 %279 %297 +OpReturnValue %298 OpFunctionEnd -%299 = OpFunction %6 None %300 -%296 = OpFunctionParameter %8 -%297 = OpFunctionParameter %10 -%298 = OpFunctionParameter %11 -%295 = OpLabel -OpBranch %301 -%301 = OpLabel +%303 = OpFunction %6 None %304 +%300 = OpFunctionParameter %8 +%301 = OpFunctionParameter %10 +%302 = OpFunctionParameter %11 +%299 = OpLabel +OpBranch %305 +%305 = OpLabel OpLine %3 101 9 -%302 = OpConvertUToF %5 %296 -%303 = OpCompositeExtract %8 %297 0 +%306 = OpConvertUToF %5 %300 +%307 = OpCompositeExtract %8 %301 0 OpLine %3 101 9 -%304 = OpIAdd %8 %303 %127 -%305 = OpConvertUToF %5 %304 -%306 = OpFRem %5 %302 %305 -%307 = OpCompositeExtract %8 %297 0 -OpLine %3 100 12 %308 = OpIAdd %8 %307 %127 -%309 = OpUDiv %8 %296 %308 -%310 = OpConvertUToF %5 %309 -%311 = OpCompositeConstruct %6 %306 %310 -%312 = OpConvertSToF %6 %298 -%313 = OpFAdd %6 %311 %312 -OpReturnValue %313 +%309 = OpConvertUToF %5 %308 +%310 = OpFRem %5 %306 %309 +%311 = OpCompositeExtract %8 %301 0 +OpLine %3 100 12 +%312 = OpIAdd %8 %311 %127 +%313 = OpUDiv %8 %300 %312 +%314 = OpConvertUToF %5 %313 +%315 = OpCompositeConstruct %6 %310 %314 +%316 = OpConvertSToF %6 %302 +%317 = OpFAdd %6 %315 %316 +OpReturnValue %317 OpFunctionEnd -%316 = OpFunction %4 None %317 -%315 = OpFunctionParameter %6 -%314 = OpLabel -OpBranch %324 -%324 = OpLabel +%320 = OpFunction %4 None %321 +%319 = OpFunctionParameter %6 +%318 = OpLabel +OpBranch %328 +%328 = OpLabel OpLine %3 270 9 -%325 = OpFunctionCall %5 %67 %315 +%329 = OpFunctionCall %5 %67 %319 OpLine %3 270 9 -%326 = OpFMul %5 %325 %81 -OpLine %3 270 9 -%327 = OpFAdd %5 %326 %81 -OpLine %3 271 17 -%328 = OpFAdd %6 %315 %320 -OpLine %3 271 9 -%329 = OpFunctionCall %5 %67 %328 -OpLine %3 271 9 %330 = OpFMul %5 %329 %81 -OpLine %3 271 9 +OpLine %3 270 9 %331 = OpFAdd %5 %330 %81 -OpLine %3 272 17 -%332 = OpFAdd %6 %315 %323 -OpLine %3 272 9 +OpLine %3 271 17 +%332 = OpFAdd %6 %319 %324 +OpLine %3 271 9 %333 = OpFunctionCall %5 %67 %332 -OpLine %3 272 9 +OpLine %3 271 9 %334 = OpFMul %5 %333 %81 -OpLine %3 269 12 +OpLine %3 271 9 %335 = OpFAdd %5 %334 %81 -%336 = OpCompositeConstruct %4 %327 %331 %335 -OpReturnValue %336 +OpLine %3 272 17 +%336 = OpFAdd %6 %319 %327 +OpLine %3 272 9 +%337 = OpFunctionCall %5 %67 %336 +OpLine %3 272 9 +%338 = OpFMul %5 %337 %81 +OpLine %3 269 12 +%339 = OpFAdd %5 %338 %81 +%340 = OpCompositeConstruct %4 %331 %335 %339 +OpReturnValue %340 OpFunctionEnd -%341 = OpFunction %2 None %342 -%337 = OpLabel -%340 = OpLoad %19 %338 -%344 = OpAccessChain %343 %29 %136 -OpBranch %349 -%349 = OpLabel +%345 = OpFunction %2 None %346 +%341 = OpLabel +%344 = OpLoad %19 %342 +%348 = OpAccessChain %347 %29 %136 +OpBranch %353 +%353 = OpLabel OpLine %3 111 22 -%350 = OpCompositeExtract %8 %340 0 +%354 = OpCompositeExtract %8 %344 0 OpLine %3 113 36 -%352 = OpAccessChain %351 %344 %136 -%353 = OpLoad %10 %352 +%356 = OpAccessChain %355 %348 %136 +%357 = OpLoad %10 %356 OpLine %3 113 59 -%355 = OpAccessChain %354 %344 %127 -%356 = OpLoad %11 %355 +%359 = OpAccessChain %358 %348 %127 +%360 = OpLoad %11 %359 OpLine %3 113 13 -%357 = OpFunctionCall %6 %299 %350 %353 %356 +%361 = OpFunctionCall %6 %303 %354 %357 %360 OpLine %3 115 5 OpLine %3 115 51 -%361 = OpAccessChain %360 %344 %346 -%362 = OpLoad %6 %361 +%365 = OpAccessChain %364 %348 %350 +%366 = OpLoad %6 %365 OpLine %3 115 33 -%363 = OpFunctionCall %14 %266 %357 %362 +%367 = OpFunctionCall %14 %270 %361 %366 OpLine %3 115 5 -%364 = OpAccessChain %359 %32 %136 %350 -OpStore %364 %363 +%368 = OpAccessChain %363 %32 %136 %354 +OpStore %368 %367 OpLine %3 118 23 -%365 = OpCompositeExtract %8 %340 0 +%369 = OpCompositeExtract %8 %344 0 OpLine %3 118 23 -%366 = OpIMul %8 %365 %345 +%370 = OpIMul %8 %369 %349 OpLine %3 120 25 -%368 = OpAccessChain %367 %344 %136 %136 -%369 = OpLoad %8 %368 +%372 = OpAccessChain %371 %348 %136 %136 +%373 = OpLoad %8 %372 OpLine %3 120 25 -%370 = OpAccessChain %367 %344 %136 %127 -%371 = OpLoad %8 %370 -%372 = OpIMul %8 %369 %371 +%374 = OpAccessChain %371 %348 %136 %127 +%375 = OpLoad %8 %374 +%376 = OpIMul %8 %373 %375 OpLine %3 120 9 -%373 = OpIMul %8 %372 %345 -%374 = OpUGreaterThanEqual %114 %366 %373 +%377 = OpIMul %8 %376 %349 +%378 = OpUGreaterThanEqual %114 %370 %377 OpLine %3 120 5 -OpSelectionMerge %375 None -OpBranchConditional %374 %376 %375 -%376 = OpLabel +OpSelectionMerge %379 None +OpBranchConditional %378 %380 %379 +%380 = OpLabel OpReturn -%375 = OpLabel +%379 = OpLabel OpLine %3 122 28 -%377 = OpCompositeExtract %8 %340 0 +%381 = OpCompositeExtract %8 %344 0 OpLine %3 122 15 -%378 = OpAccessChain %367 %344 %136 %136 -%379 = OpLoad %8 %378 -%380 = OpUDiv %8 %377 %379 -%381 = OpIAdd %8 %350 %380 +%382 = OpAccessChain %371 %348 %136 %136 +%383 = OpLoad %8 %382 +%384 = OpUDiv %8 %381 %383 +%385 = OpIAdd %8 %354 %384 OpLine %3 123 15 -%382 = OpIAdd %8 %381 %127 -OpLine %3 124 15 -%383 = OpAccessChain %367 %344 %136 %136 -%384 = OpLoad %8 %383 -%385 = OpIAdd %8 %381 %384 -OpLine %3 124 15 %386 = OpIAdd %8 %385 %127 +OpLine %3 124 15 +%387 = OpAccessChain %371 %348 %136 %136 +%388 = OpLoad %8 %387 +%389 = OpIAdd %8 %385 %388 +OpLine %3 124 15 +%390 = OpIAdd %8 %389 %127 OpLine %3 125 15 -%387 = OpIAdd %8 %386 %127 +%391 = OpIAdd %8 %390 %127 OpLine %3 127 5 OpLine %3 127 5 -%390 = OpAccessChain %389 %34 %136 %366 -OpStore %390 %381 +%394 = OpAccessChain %393 %34 %136 %370 +OpStore %394 %385 OpLine %3 128 5 OpLine %3 128 5 -%391 = OpIAdd %8 %366 %127 +%395 = OpIAdd %8 %370 %127 OpLine %3 128 5 -%392 = OpAccessChain %389 %34 %136 %391 -OpStore %392 %386 +%396 = OpAccessChain %393 %34 %136 %395 +OpStore %396 %390 OpLine %3 129 5 OpLine %3 129 5 -%393 = OpIAdd %8 %366 %346 +%397 = OpIAdd %8 %370 %350 OpLine %3 129 5 -%394 = OpAccessChain %389 %34 %136 %393 -OpStore %394 %387 +%398 = OpAccessChain %393 %34 %136 %397 +OpStore %398 %391 OpLine %3 130 5 OpLine %3 130 5 -%395 = OpIAdd %8 %366 %347 +%399 = OpIAdd %8 %370 %351 OpLine %3 130 5 -%396 = OpAccessChain %389 %34 %136 %395 -OpStore %396 %381 +%400 = OpAccessChain %393 %34 %136 %399 +OpStore %400 %385 OpLine %3 131 5 OpLine %3 131 5 -%397 = OpIAdd %8 %366 %348 +%401 = OpIAdd %8 %370 %352 OpLine %3 131 5 -%398 = OpAccessChain %389 %34 %136 %397 -OpStore %398 %387 +%402 = OpAccessChain %393 %34 %136 %401 +OpStore %402 %391 OpLine %3 132 5 OpLine %3 132 5 -%399 = OpIAdd %8 %366 %205 +%403 = OpIAdd %8 %370 %205 OpLine %3 132 5 -%400 = OpAccessChain %389 %34 %136 %399 -OpStore %400 %382 +%404 = OpAccessChain %393 %34 %136 %403 +OpStore %404 %386 OpReturn OpFunctionEnd -%411 = OpFunction %2 None %342 -%401 = OpLabel -%404 = OpLoad %8 %402 -%413 = OpAccessChain %412 %36 %136 -OpBranch %416 -%416 = OpLabel +%415 = OpFunction %2 None %346 +%405 = OpLabel +%408 = OpLoad %8 %406 +%417 = OpAccessChain %416 %36 %136 +OpBranch %420 +%420 = OpLabel OpLine %3 161 19 -%417 = OpIAdd %8 %404 %346 +%421 = OpIAdd %8 %408 %350 OpLine %3 161 18 -%418 = OpUDiv %8 %417 %347 +%422 = OpUDiv %8 %421 %351 OpLine %3 161 13 -%419 = OpUMod %8 %418 %346 -%420 = OpConvertUToF %5 %419 -OpLine %3 162 19 -%421 = OpIAdd %8 %404 %127 -OpLine %3 162 18 -%422 = OpUDiv %8 %421 %347 -OpLine %3 162 13 -%423 = OpUMod %8 %422 %346 +%423 = OpUMod %8 %422 %350 %424 = OpConvertUToF %5 %423 +OpLine %3 162 19 +%425 = OpIAdd %8 %408 %127 +OpLine %3 162 18 +%426 = OpUDiv %8 %425 %351 +OpLine %3 162 13 +%427 = OpUMod %8 %426 %350 +%428 = OpConvertUToF %5 %427 OpLine %3 163 14 -%425 = OpCompositeConstruct %6 %420 %424 +%429 = OpCompositeConstruct %6 %424 %428 OpLine %3 165 30 -%426 = OpVectorTimesScalar %6 %425 %84 -%427 = OpFAdd %6 %415 %426 +%430 = OpVectorTimesScalar %6 %429 %84 +%431 = OpFAdd %6 %419 %430 OpLine %3 165 20 -%428 = OpCompositeConstruct %7 %427 %76 %56 +%432 = OpCompositeConstruct %7 %431 %76 %56 OpLine %3 168 21 -%430 = OpAccessChain %429 %413 %347 -%431 = OpLoad %8 %430 -%432 = OpConvertUToF %5 %431 -%433 = OpFMul %5 %420 %432 +%433 = OpCompositeExtract %5 %429 0 +OpLine %3 168 21 +%435 = OpAccessChain %434 %417 %351 +%436 = OpLoad %8 %435 +%437 = OpConvertUToF %5 %436 +%438 = OpFMul %5 %433 %437 +%439 = OpCompositeExtract %5 %429 1 OpLine %3 168 17 -%434 = OpAccessChain %429 %413 %347 -%435 = OpLoad %8 %434 -%436 = OpConvertUToF %5 %435 -%437 = OpFMul %5 %424 %436 -%438 = OpFAdd %5 %433 %437 -%439 = OpConvertFToU %8 %438 -OpLine %3 168 17 -%440 = OpAccessChain %429 %413 %348 +%440 = OpAccessChain %434 %417 %351 %441 = OpLoad %8 %440 -%442 = OpIAdd %8 %439 %441 +%442 = OpConvertUToF %5 %441 +%443 = OpFMul %5 %439 %442 +%444 = OpFAdd %5 %438 %443 +%445 = OpConvertFToU %8 %444 +OpLine %3 168 17 +%446 = OpAccessChain %434 %417 %352 +%447 = OpLoad %8 %446 +%448 = OpIAdd %8 %445 %447 OpLine %3 170 12 -%443 = OpCompositeConstruct %21 %442 %428 %425 -%444 = OpCompositeExtract %8 %443 0 -OpStore %405 %444 -%445 = OpCompositeExtract %7 %443 1 -OpStore %407 %445 -%446 = OpCompositeExtract %6 %443 2 -OpStore %409 %446 +%449 = OpCompositeConstruct %21 %448 %432 %429 +%450 = OpCompositeExtract %8 %449 0 +OpStore %409 %450 +%451 = OpCompositeExtract %7 %449 1 +OpStore %411 %451 +%452 = OpCompositeExtract %6 %449 2 +OpStore %413 %452 OpReturn OpFunctionEnd -%459 = OpFunction %2 None %342 -%447 = OpLabel -%462 = OpVariable %212 Function %76 -%463 = OpVariable %215 Function %136 -%450 = OpLoad %8 %449 -%453 = OpLoad %7 %451 -%456 = OpLoad %6 %454 -%448 = OpCompositeConstruct %21 %450 %453 %456 -%460 = OpAccessChain %412 %36 %136 -OpBranch %464 -%464 = OpLabel +%465 = OpFunction %2 None %346 +%453 = OpLabel +%468 = OpVariable %212 Function %76 +%469 = OpVariable %215 Function %136 +%456 = OpLoad %8 %455 +%459 = OpLoad %7 %457 +%462 = OpLoad %6 %460 +%454 = OpCompositeConstruct %21 %456 %459 %462 +%466 = OpAccessChain %416 %36 %136 +OpBranch %470 +%470 = OpLabel OpLine %3 181 17 -%465 = OpCompositeExtract %6 %448 2 -%466 = OpCompositeExtract %5 %465 0 +%471 = OpCompositeExtract %6 %454 2 +%472 = OpCompositeExtract %5 %471 0 OpLine %3 181 17 -%467 = OpAccessChain %429 %460 %347 -%468 = OpLoad %8 %467 -%469 = OpConvertUToF %5 %468 -%470 = OpFMul %5 %466 %469 -%471 = OpCompositeExtract %6 %448 2 -%472 = OpCompositeExtract %5 %471 1 -OpLine %3 181 70 -%473 = OpAccessChain %429 %460 %347 +%473 = OpAccessChain %434 %466 %351 %474 = OpLoad %8 %473 +%475 = OpConvertUToF %5 %474 +%476 = OpFMul %5 %472 %475 +%477 = OpCompositeExtract %6 %454 2 +%478 = OpCompositeExtract %5 %477 1 +OpLine %3 181 70 +%479 = OpAccessChain %434 %466 %351 +%480 = OpLoad %8 %479 OpLine %3 181 13 -%475 = OpAccessChain %429 %460 %347 -%476 = OpLoad %8 %475 -%477 = OpIMul %8 %474 %476 -%478 = OpConvertUToF %5 %477 -%479 = OpFMul %5 %472 %478 -%480 = OpFAdd %5 %470 %479 -%481 = OpConvertFToU %8 %480 +%481 = OpAccessChain %434 %466 %351 +%482 = OpLoad %8 %481 +%483 = OpIMul %8 %480 %482 +%484 = OpConvertUToF %5 %483 +%485 = OpFMul %5 %478 %484 +%486 = OpFAdd %5 %476 %485 +%487 = OpConvertFToU %8 %486 OpLine %3 181 13 -%482 = OpAccessChain %429 %460 %348 -%483 = OpLoad %8 %482 -%484 = OpIAdd %8 %481 %483 +%488 = OpAccessChain %434 %466 %352 +%489 = OpLoad %8 %488 +%490 = OpIAdd %8 %487 %489 OpLine %3 182 32 -%485 = OpConvertUToF %5 %484 +%491 = OpConvertUToF %5 %490 OpLine %3 182 22 -%486 = OpFDiv %5 %485 %461 -%487 = OpExtInst %5 %1 Floor %486 -%488 = OpConvertFToU %8 %487 +%492 = OpFDiv %5 %491 %467 +%493 = OpExtInst %5 %1 Floor %492 +%494 = OpConvertFToU %8 %493 OpLine %3 183 22 -%489 = OpUMod %8 %484 %345 +%495 = OpUMod %8 %490 %349 OpLine %3 185 36 -%490 = OpAccessChain %351 %460 %136 -%491 = OpLoad %10 %490 +%496 = OpAccessChain %355 %466 %136 +%497 = OpLoad %10 %496 OpLine %3 185 57 -%492 = OpAccessChain %354 %460 %127 -%493 = OpLoad %11 %492 +%498 = OpAccessChain %358 %466 %127 +%499 = OpLoad %11 %498 OpLine %3 185 13 -%494 = OpFunctionCall %6 %299 %488 %491 %493 +%500 = OpFunctionCall %6 %303 %494 %497 %499 OpLine %3 186 31 -%495 = OpAccessChain %360 %460 %346 -%496 = OpLoad %6 %495 +%501 = OpAccessChain %364 %466 %350 +%502 = OpLoad %6 %501 OpLine %3 186 13 -%497 = OpFunctionCall %14 %266 %494 %496 +%503 = OpFunctionCall %14 %270 %500 %502 OpLine %3 190 5 -OpSelectionMerge %498 None -OpSwitch %489 %505 0 %499 1 %500 2 %501 3 %502 4 %503 5 %504 -%499 = OpLabel -OpLine %3 191 37 -%506 = OpCompositeExtract %4 %497 0 -%507 = OpCompositeExtract %5 %506 0 -OpLine %3 191 20 -OpStore %462 %507 -OpBranch %498 -%500 = OpLabel -OpLine %3 192 37 -%508 = OpCompositeExtract %4 %497 0 -%509 = OpCompositeExtract %5 %508 1 -OpLine %3 192 20 -OpStore %462 %509 -OpBranch %498 -%501 = OpLabel -OpLine %3 193 37 -%510 = OpCompositeExtract %4 %497 0 -%511 = OpCompositeExtract %5 %510 2 -OpLine %3 193 20 -OpStore %462 %511 -OpBranch %498 -%502 = OpLabel -OpLine %3 194 37 -%512 = OpCompositeExtract %4 %497 1 -%513 = OpCompositeExtract %5 %512 0 -OpLine %3 194 20 -OpStore %462 %513 -OpBranch %498 -%503 = OpLabel -OpLine %3 195 37 -%514 = OpCompositeExtract %4 %497 1 -%515 = OpCompositeExtract %5 %514 1 -OpLine %3 195 20 -OpStore %462 %515 -OpBranch %498 -%504 = OpLabel -OpLine %3 196 37 -%516 = OpCompositeExtract %4 %497 1 -%517 = OpCompositeExtract %5 %516 2 -OpLine %3 196 20 -OpStore %462 %517 -OpBranch %498 +OpSelectionMerge %504 None +OpSwitch %495 %511 0 %505 1 %506 2 %507 3 %508 4 %509 5 %510 %505 = OpLabel -OpBranch %498 -%498 = OpLabel +OpLine %3 191 37 +%512 = OpCompositeExtract %4 %503 0 +%513 = OpCompositeExtract %5 %512 0 +OpLine %3 191 20 +OpStore %468 %513 +OpBranch %504 +%506 = OpLabel +OpLine %3 192 37 +%514 = OpCompositeExtract %4 %503 0 +%515 = OpCompositeExtract %5 %514 1 +OpLine %3 192 20 +OpStore %468 %515 +OpBranch %504 +%507 = OpLabel +OpLine %3 193 37 +%516 = OpCompositeExtract %4 %503 0 +%517 = OpCompositeExtract %5 %516 2 +OpLine %3 193 20 +OpStore %468 %517 +OpBranch %504 +%508 = OpLabel +OpLine %3 194 37 +%518 = OpCompositeExtract %4 %503 1 +%519 = OpCompositeExtract %5 %518 0 +OpLine %3 194 20 +OpStore %468 %519 +OpBranch %504 +%509 = OpLabel +OpLine %3 195 37 +%520 = OpCompositeExtract %4 %503 1 +%521 = OpCompositeExtract %5 %520 1 +OpLine %3 195 20 +OpStore %468 %521 +OpBranch %504 +%510 = OpLabel +OpLine %3 196 37 +%522 = OpCompositeExtract %4 %503 1 +%523 = OpCompositeExtract %5 %522 2 +OpLine %3 196 20 +OpStore %468 %523 +OpBranch %504 +%511 = OpLabel +OpBranch %504 +%504 = OpLabel OpLine %3 200 15 -%518 = OpAccessChain %367 %460 %136 %136 -%519 = OpLoad %8 %518 -%520 = OpUDiv %8 %488 %519 -%521 = OpIAdd %8 %488 %520 +%524 = OpAccessChain %371 %466 %136 %136 +%525 = OpLoad %8 %524 +%526 = OpUDiv %8 %494 %525 +%527 = OpIAdd %8 %494 %526 OpLine %3 201 15 -%522 = OpIAdd %8 %521 %127 +%528 = OpIAdd %8 %527 %127 OpLine %3 202 15 -%523 = OpAccessChain %367 %460 %136 %136 -%524 = OpLoad %8 %523 -%525 = OpIAdd %8 %521 %524 +%529 = OpAccessChain %371 %466 %136 %136 +%530 = OpLoad %8 %529 +%531 = OpIAdd %8 %527 %530 OpLine %3 202 15 -%526 = OpIAdd %8 %525 %127 +%532 = OpIAdd %8 %531 %127 OpLine %3 203 15 -%527 = OpIAdd %8 %526 %127 +%533 = OpIAdd %8 %532 %127 OpLine %3 206 5 -OpSelectionMerge %528 None -OpSwitch %489 %533 0 %529 3 %529 2 %530 4 %530 1 %531 5 %532 -%529 = OpLabel +OpSelectionMerge %534 None +OpSwitch %495 %539 0 %535 3 %535 2 %536 4 %536 1 %537 5 %538 +%535 = OpLabel OpLine %3 207 24 -OpStore %463 %521 -OpBranch %528 -%530 = OpLabel +OpStore %469 %527 +OpBranch %534 +%536 = OpLabel OpLine %3 208 24 -OpStore %463 %527 -OpBranch %528 -%531 = OpLabel +OpStore %469 %533 +OpBranch %534 +%537 = OpLabel OpLine %3 209 20 -OpStore %463 %526 -OpBranch %528 -%532 = OpLabel +OpStore %469 %532 +OpBranch %534 +%538 = OpLabel OpLine %3 210 20 -OpStore %463 %522 -OpBranch %528 -%533 = OpLabel -OpBranch %528 -%528 = OpLabel +OpStore %469 %528 +OpBranch %534 +%539 = OpLabel +OpBranch %534 +%534 = OpLabel OpLine %3 213 13 -%534 = OpCompositeExtract %8 %448 0 +%540 = OpCompositeExtract %8 %454 0 OpLine %3 213 5 -OpStore %463 %534 +OpStore %469 %540 OpLine %3 222 27 -%535 = OpLoad %5 %462 -%536 = OpBitcast %8 %535 +%541 = OpLoad %5 %468 +%542 = OpBitcast %8 %541 OpLine %3 223 12 -%537 = OpLoad %8 %463 -%538 = OpCompositeConstruct %22 %536 %537 -%539 = OpCompositeExtract %8 %538 0 -OpStore %457 %539 -%540 = OpCompositeExtract %8 %538 1 -OpStore %458 %540 +%543 = OpLoad %8 %469 +%544 = OpCompositeConstruct %22 %542 %543 +%545 = OpCompositeExtract %8 %544 0 +OpStore %463 %545 +%546 = OpCompositeExtract %8 %544 1 +OpStore %464 %546 OpReturn OpFunctionEnd -%552 = OpFunction %2 None %342 -%541 = OpLabel -%545 = OpLoad %4 %543 -%547 = OpLoad %4 %546 -%542 = OpCompositeConstruct %14 %545 %547 -%554 = OpAccessChain %553 %39 %136 -OpBranch %555 -%555 = OpLabel +%558 = OpFunction %2 None %346 +%547 = OpLabel +%551 = OpLoad %4 %549 +%553 = OpLoad %4 %552 +%548 = OpCompositeConstruct %14 %551 %553 +%560 = OpAccessChain %559 %39 %136 +OpBranch %561 +%561 = OpLabel OpLine %3 254 25 -%557 = OpAccessChain %556 %554 %127 -%558 = OpLoad %23 %557 -%559 = OpCompositeExtract %4 %542 0 +%563 = OpAccessChain %562 %560 %127 +%564 = OpLoad %23 %563 +%565 = OpCompositeExtract %4 %548 0 OpLine %3 254 25 -%560 = OpCompositeConstruct %7 %559 %56 -%561 = OpMatrixTimesVector %7 %558 %560 +%566 = OpCompositeConstruct %7 %565 %56 +%567 = OpMatrixTimesVector %7 %564 %566 OpLine %3 255 18 -%562 = OpCompositeExtract %4 %542 1 +%568 = OpCompositeExtract %4 %548 1 OpLine %3 256 12 -%563 = OpCompositeExtract %4 %542 0 -%564 = OpCompositeConstruct %26 %561 %562 %563 -%565 = OpCompositeExtract %7 %564 0 -OpStore %548 %565 -%566 = OpCompositeExtract %4 %564 1 -OpStore %549 %566 -%567 = OpCompositeExtract %4 %564 2 -OpStore %551 %567 +%569 = OpCompositeExtract %4 %548 0 +%570 = OpCompositeConstruct %26 %567 %568 %569 +%571 = OpCompositeExtract %7 %570 0 +OpStore %554 %571 +%572 = OpCompositeExtract %4 %570 1 +OpStore %555 %572 +%573 = OpCompositeExtract %4 %570 2 +OpStore %557 %573 OpReturn OpFunctionEnd -%577 = OpFunction %2 None %342 -%568 = OpLabel -%586 = OpVariable %99 Function %587 -%571 = OpLoad %7 %570 -%573 = OpLoad %4 %572 -%575 = OpLoad %4 %574 -%569 = OpCompositeConstruct %26 %571 %573 %575 -%578 = OpAccessChain %553 %39 %136 -%580 = OpAccessChain %579 %42 %136 -OpBranch %588 -%588 = OpLabel +%583 = OpFunction %2 None %346 +%574 = OpLabel +%592 = OpVariable %99 Function %593 +%577 = OpLoad %7 %576 +%579 = OpLoad %4 %578 +%581 = OpLoad %4 %580 +%575 = OpCompositeConstruct %26 %577 %579 %581 +%584 = OpAccessChain %559 %39 %136 +%586 = OpAccessChain %585 %42 %136 +OpBranch %594 +%594 = OpLabel OpLine %3 278 28 OpLine %3 278 17 -%589 = OpCompositeExtract %4 %569 2 -%590 = OpExtInst %4 %1 Fract %589 -%591 = OpExtInst %4 %1 SmoothStep %83 %581 %590 +%595 = OpCompositeExtract %4 %575 2 +%596 = OpExtInst %4 %1 Fract %595 +%597 = OpExtInst %4 %1 SmoothStep %83 %587 %596 OpLine %3 278 5 -OpStore %586 %591 +OpStore %592 %597 OpLine %3 279 17 OpLine %3 279 13 -%592 = OpAccessChain %126 %586 %136 -%593 = OpLoad %5 %592 -%594 = OpAccessChain %126 %586 %127 -%595 = OpLoad %5 %594 -%596 = OpFMul %5 %593 %595 -%597 = OpAccessChain %126 %586 %346 -%598 = OpLoad %5 %597 -%599 = OpFMul %5 %596 %598 -%600 = OpCompositeConstruct %4 %599 %599 %599 -%601 = OpExtInst %4 %1 FMix %583 %585 %600 +%598 = OpAccessChain %126 %592 %136 +%599 = OpLoad %5 %598 +%600 = OpAccessChain %126 %592 %127 +%601 = OpLoad %5 %600 +%602 = OpFMul %5 %599 %601 +%603 = OpAccessChain %126 %592 %350 +%604 = OpLoad %5 %603 +%605 = OpFMul %5 %602 %604 +%606 = OpCompositeConstruct %4 %605 %605 %605 +%607 = OpExtInst %4 %1 FMix %589 %591 %606 OpLine %3 279 5 -OpStore %586 %601 +OpStore %592 %607 OpLine %3 282 25 -%603 = OpAccessChain %602 %580 %127 -%604 = OpLoad %4 %603 -%605 = OpVectorTimesScalar %4 %604 %268 +%609 = OpAccessChain %608 %586 %127 +%610 = OpLoad %4 %609 +%611 = OpVectorTimesScalar %4 %610 %272 OpLine %3 284 21 -%606 = OpAccessChain %602 %580 %136 -%607 = OpLoad %4 %606 -%608 = OpCompositeExtract %4 %569 2 -%609 = OpFSub %4 %607 %608 -%610 = OpExtInst %4 %1 Normalize %609 +%612 = OpAccessChain %608 %586 %136 +%613 = OpLoad %4 %612 +%614 = OpCompositeExtract %4 %575 2 +%615 = OpFSub %4 %613 %614 +%616 = OpExtInst %4 %1 Normalize %615 OpLine %3 285 20 -%612 = OpAccessChain %611 %578 %136 -%613 = OpLoad %7 %612 -%614 = OpVectorShuffle %4 %613 %613 0 1 2 -%615 = OpCompositeExtract %4 %569 2 -%616 = OpFSub %4 %614 %615 -%617 = OpExtInst %4 %1 Normalize %616 +%618 = OpAccessChain %617 %584 %136 +%619 = OpLoad %7 %618 +%620 = OpVectorShuffle %4 %619 %619 0 1 2 +%621 = OpCompositeExtract %4 %575 2 +%622 = OpFSub %4 %620 %621 +%623 = OpExtInst %4 %1 Normalize %622 OpLine %3 286 20 -%618 = OpFAdd %4 %617 %610 -%619 = OpExtInst %4 %1 Normalize %618 +%624 = OpFAdd %4 %623 %616 +%625 = OpExtInst %4 %1 Normalize %624 OpLine %3 288 32 -%620 = OpCompositeExtract %4 %569 1 -%621 = OpDot %5 %620 %610 +%626 = OpCompositeExtract %4 %575 1 +%627 = OpDot %5 %626 %616 OpLine %3 288 28 -%622 = OpExtInst %5 %1 FMax %621 %76 -OpLine %3 289 25 -%623 = OpAccessChain %602 %580 %127 -%624 = OpLoad %4 %623 -%625 = OpVectorTimesScalar %4 %624 %622 -OpLine %3 291 37 -%626 = OpCompositeExtract %4 %569 1 -%627 = OpDot %5 %626 %619 -OpLine %3 291 33 %628 = OpExtInst %5 %1 FMax %627 %76 +OpLine %3 289 25 +%629 = OpAccessChain %608 %586 %127 +%630 = OpLoad %4 %629 +%631 = OpVectorTimesScalar %4 %630 %628 +OpLine %3 291 37 +%632 = OpCompositeExtract %4 %575 1 +%633 = OpDot %5 %632 %625 +OpLine %3 291 33 +%634 = OpExtInst %5 %1 FMax %633 %76 OpLine %3 291 29 -%629 = OpExtInst %5 %1 Pow %628 %319 +%635 = OpExtInst %5 %1 Pow %634 %323 OpLine %3 292 26 -%630 = OpAccessChain %602 %580 %127 -%631 = OpLoad %4 %630 -%632 = OpVectorTimesScalar %4 %631 %629 +%636 = OpAccessChain %608 %586 %127 +%637 = OpLoad %4 %636 +%638 = OpVectorTimesScalar %4 %637 %635 OpLine %3 294 18 -%633 = OpFAdd %4 %605 %625 -%634 = OpFAdd %4 %633 %632 -%635 = OpLoad %4 %586 -%636 = OpFMul %4 %634 %635 +%639 = OpFAdd %4 %611 %631 +%640 = OpFAdd %4 %639 %638 +%641 = OpLoad %4 %592 +%642 = OpFMul %4 %640 %641 OpLine %3 296 12 -%637 = OpCompositeConstruct %7 %636 %56 -OpStore %576 %637 +%643 = OpCompositeConstruct %7 %642 %56 +OpStore %582 %643 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/local-var-init-in-loop.comp.wgsl b/tests/out/wgsl/local-var-init-in-loop.comp.wgsl index 750e32e6d..7675a54ce 100644 --- a/tests/out/wgsl/local-var-init-in-loop.comp.wgsl +++ b/tests/out/wgsl/local-var-init-in-loop.comp.wgsl @@ -1,7 +1,7 @@ fn main_1() { var sum: vec4 = vec4(0.0); var i: i32 = 0; - var a: vec4 = vec4(1.0); + var a: vec4; loop { let _e6 = i; @@ -9,8 +9,7 @@ fn main_1() { break; } { - let _e15 = vec4(1.0); - a = _e15; + a = vec4(1.0); let _e17 = sum; let _e18 = a; sum = (_e17 + _e18); diff --git a/tests/out/wgsl/samplers.frag.wgsl b/tests/out/wgsl/samplers.frag.wgsl index 1009fd5cd..11565d1f5 100644 --- a/tests/out/wgsl/samplers.frag.wgsl +++ b/tests/out/wgsl/samplers.frag.wgsl @@ -65,76 +65,92 @@ fn testTex1D(coord: f32) { c = _e71; let _e72 = coord_1; let _e75 = coord_1; - let _e79 = textureSample(tex1D, samp, (_e75 / 6.0)); - c = _e79; - let _e80 = coord_1; - let _e85 = coord_1; - let _e95 = textureSample(tex1D, samp, (vec3(_e85, 0.0, 0.0) / vec3(6.0)).x); - c = _e95; - let _e96 = coord_1; - let _e100 = coord_1; - let _e105 = textureSampleBias(tex1D, samp, (_e100 / 6.0), 2.0); - c = _e105; - let _e106 = coord_1; - let _e112 = coord_1; - let _e123 = textureSampleBias(tex1D, samp, (vec3(_e112, 0.0, 0.0) / vec3(6.0)).x, 2.0); - c = _e123; - let _e124 = coord_1; - let _e129 = coord_1; - let _e135 = textureSampleGrad(tex1D, samp, (_e129 / 6.0), 4.0, 4.0); - c = _e135; - let _e136 = coord_1; - let _e143 = coord_1; - let _e155 = textureSampleGrad(tex1D, samp, (vec3(_e143, 0.0, 0.0) / vec3(6.0)).x, 4.0, 4.0); - c = _e155; - let _e156 = coord_1; + let _e77 = vec2(_e75, 6.0); + let _e81 = textureSample(tex1D, samp, (_e77.x / _e77.y)); + c = _e81; + let _e82 = coord_1; + let _e87 = coord_1; + let _e91 = vec4(_e87, 0.0, 0.0, 6.0); + let _e97 = textureSample(tex1D, samp, (_e91.xyz / vec3(_e91.w)).x); + c = _e97; + let _e98 = coord_1; + let _e102 = coord_1; + let _e104 = vec2(_e102, 6.0); + let _e109 = textureSampleBias(tex1D, samp, (_e104.x / _e104.y), 2.0); + c = _e109; + let _e110 = coord_1; + let _e116 = coord_1; + let _e120 = vec4(_e116, 0.0, 0.0, 6.0); + let _e127 = textureSampleBias(tex1D, samp, (_e120.xyz / vec3(_e120.w)).x, 2.0); + c = _e127; + let _e128 = coord_1; + let _e133 = coord_1; + let _e135 = vec2(_e133, 6.0); + let _e141 = textureSampleGrad(tex1D, samp, (_e135.x / _e135.y), 4.0, 4.0); + c = _e141; + let _e142 = coord_1; + let _e149 = coord_1; + let _e153 = vec4(_e149, 0.0, 0.0, 6.0); + let _e161 = textureSampleGrad(tex1D, samp, (_e153.xyz / vec3(_e153.w)).x, 4.0, 4.0); + c = _e161; let _e162 = coord_1; - let _e169 = textureSampleGrad(tex1D, samp, (_e162 / 6.0), 4.0, 4.0, 5); - c = _e169; - let _e170 = coord_1; + let _e168 = coord_1; + let _e170 = vec2(_e168, 6.0); + let _e177 = textureSampleGrad(tex1D, samp, (_e170.x / _e170.y), 4.0, 4.0, 5); + c = _e177; let _e178 = coord_1; - let _e191 = textureSampleGrad(tex1D, samp, (vec3(_e178, 0.0, 0.0) / vec3(6.0)).x, 4.0, 4.0, 5); - c = _e191; - let _e192 = coord_1; - let _e196 = coord_1; - let _e201 = textureSampleLevel(tex1D, samp, (_e196 / 6.0), 3.0); - c = _e201; - let _e202 = coord_1; - let _e208 = coord_1; - let _e219 = textureSampleLevel(tex1D, samp, (vec3(_e208, 0.0, 0.0) / vec3(6.0)).x, 3.0); - c = _e219; - let _e220 = coord_1; - let _e225 = coord_1; - let _e231 = textureSampleLevel(tex1D, samp, (_e225 / 6.0), 3.0, 5); - c = _e231; - let _e232 = coord_1; - let _e239 = coord_1; - let _e251 = textureSampleLevel(tex1D, samp, (vec3(_e239, 0.0, 0.0) / vec3(6.0)).x, 3.0, 5); - c = _e251; - let _e252 = coord_1; - let _e256 = coord_1; - let _e261 = textureSample(tex1D, samp, (_e256 / 6.0), 5); - c = _e261; - let _e262 = coord_1; + let _e186 = coord_1; + let _e190 = vec4(_e186, 0.0, 0.0, 6.0); + let _e199 = textureSampleGrad(tex1D, samp, (_e190.xyz / vec3(_e190.w)).x, 4.0, 4.0, 5); + c = _e199; + let _e200 = coord_1; + let _e204 = coord_1; + let _e206 = vec2(_e204, 6.0); + let _e211 = textureSampleLevel(tex1D, samp, (_e206.x / _e206.y), 3.0); + c = _e211; + let _e212 = coord_1; + let _e218 = coord_1; + let _e222 = vec4(_e218, 0.0, 0.0, 6.0); + let _e229 = textureSampleLevel(tex1D, samp, (_e222.xyz / vec3(_e222.w)).x, 3.0); + c = _e229; + let _e230 = coord_1; + let _e235 = coord_1; + let _e237 = vec2(_e235, 6.0); + let _e243 = textureSampleLevel(tex1D, samp, (_e237.x / _e237.y), 3.0, 5); + c = _e243; + let _e244 = coord_1; + let _e251 = coord_1; + let _e255 = vec4(_e251, 0.0, 0.0, 6.0); + let _e263 = textureSampleLevel(tex1D, samp, (_e255.xyz / vec3(_e255.w)).x, 3.0, 5); + c = _e263; + let _e264 = coord_1; let _e268 = coord_1; - let _e279 = textureSample(tex1D, samp, (vec3(_e268, 0.0, 0.0) / vec3(6.0)).x, 5); - c = _e279; - let _e280 = coord_1; - let _e285 = coord_1; - let _e291 = textureSampleBias(tex1D, samp, (_e285 / 6.0), 2.0, 5); - c = _e291; - let _e292 = coord_1; + let _e270 = vec2(_e268, 6.0); + let _e275 = textureSample(tex1D, samp, (_e270.x / _e270.y), 5); + c = _e275; + let _e276 = coord_1; + let _e282 = coord_1; + let _e286 = vec4(_e282, 0.0, 0.0, 6.0); + let _e293 = textureSample(tex1D, samp, (_e286.xyz / vec3(_e286.w)).x, 5); + c = _e293; + let _e294 = coord_1; let _e299 = coord_1; - let _e311 = textureSampleBias(tex1D, samp, (vec3(_e299, 0.0, 0.0) / vec3(6.0)).x, 2.0, 5); - c = _e311; - let _e312 = coord_1; + let _e301 = vec2(_e299, 6.0); + let _e307 = textureSampleBias(tex1D, samp, (_e301.x / _e301.y), 2.0, 5); + c = _e307; + let _e308 = coord_1; let _e315 = coord_1; - let _e318 = textureLoad(tex1D, i32(_e315), 3); - c = _e318; - let _e319 = coord_1; - let _e323 = coord_1; - let _e327 = textureLoad(tex1D, i32(_e323), 3); + let _e319 = vec4(_e315, 0.0, 0.0, 6.0); + let _e327 = textureSampleBias(tex1D, samp, (_e319.xyz / vec3(_e319.w)).x, 2.0, 5); c = _e327; + let _e328 = coord_1; + let _e331 = coord_1; + let _e334 = textureLoad(tex1D, i32(_e331), 3); + c = _e334; + let _e335 = coord_1; + let _e339 = coord_1; + let _e343 = textureLoad(tex1D, i32(_e339), 3); + c = _e343; return; } @@ -218,67 +234,83 @@ fn testTex2D(coord_4: vec2) { c_2 = _e87; let _e88 = coord_5; let _e93 = coord_5; - let _e102 = textureSample(tex2D, samp, (vec2(_e93.x, _e93.y) / vec2(6.0))); + let _e97 = vec3(_e93.x, _e93.y, 6.0); + let _e102 = textureSample(tex2D, samp, (_e97.xy / vec2(_e97.z))); c_2 = _e102; let _e103 = coord_5; let _e109 = coord_5; - let _e120 = textureSample(tex2D, samp, (vec3(_e109.x, _e109.y, 0.0) / vec3(6.0)).xy); + let _e114 = vec4(_e109.x, _e109.y, 0.0, 6.0); + let _e120 = textureSample(tex2D, samp, (_e114.xyz / vec3(_e114.w)).xy); c_2 = _e120; let _e121 = coord_5; let _e127 = coord_5; - let _e137 = textureSampleBias(tex2D, samp, (vec2(_e127.x, _e127.y) / vec2(6.0)), 2.0); + let _e131 = vec3(_e127.x, _e127.y, 6.0); + let _e137 = textureSampleBias(tex2D, samp, (_e131.xy / vec2(_e131.z)), 2.0); c_2 = _e137; let _e138 = coord_5; let _e145 = coord_5; - let _e157 = textureSampleBias(tex2D, samp, (vec3(_e145.x, _e145.y, 0.0) / vec3(6.0)).xy, 2.0); + let _e150 = vec4(_e145.x, _e145.y, 0.0, 6.0); + let _e157 = textureSampleBias(tex2D, samp, (_e150.xyz / vec3(_e150.w)).xy, 2.0); c_2 = _e157; let _e158 = coord_5; let _e167 = coord_5; - let _e180 = textureSampleGrad(tex2D, samp, (vec2(_e167.x, _e167.y) / vec2(6.0)), vec2(4.0), vec2(4.0)); + let _e171 = vec3(_e167.x, _e167.y, 6.0); + let _e180 = textureSampleGrad(tex2D, samp, (_e171.xy / vec2(_e171.z)), vec2(4.0), vec2(4.0)); c_2 = _e180; let _e181 = coord_5; let _e191 = coord_5; - let _e206 = textureSampleGrad(tex2D, samp, (vec3(_e191.x, _e191.y, 0.0) / vec3(6.0)).xy, vec2(4.0), vec2(4.0)); + let _e196 = vec4(_e191.x, _e191.y, 0.0, 6.0); + let _e206 = textureSampleGrad(tex2D, samp, (_e196.xyz / vec3(_e196.w)).xy, vec2(4.0), vec2(4.0)); c_2 = _e206; let _e207 = coord_5; let _e218 = coord_5; - let _e233 = textureSampleGrad(tex2D, samp, (vec2(_e218.x, _e218.y) / vec2(6.0)), vec2(4.0), vec2(4.0), vec2(5)); + let _e222 = vec3(_e218.x, _e218.y, 6.0); + let _e233 = textureSampleGrad(tex2D, samp, (_e222.xy / vec2(_e222.z)), vec2(4.0), vec2(4.0), vec2(5)); c_2 = _e233; let _e234 = coord_5; let _e246 = coord_5; - let _e263 = textureSampleGrad(tex2D, samp, (vec3(_e246.x, _e246.y, 0.0) / vec3(6.0)).xy, vec2(4.0), vec2(4.0), vec2(5)); + let _e251 = vec4(_e246.x, _e246.y, 0.0, 6.0); + let _e263 = textureSampleGrad(tex2D, samp, (_e251.xyz / vec3(_e251.w)).xy, vec2(4.0), vec2(4.0), vec2(5)); c_2 = _e263; let _e264 = coord_5; let _e270 = coord_5; - let _e280 = textureSampleLevel(tex2D, samp, (vec2(_e270.x, _e270.y) / vec2(6.0)), 3.0); + let _e274 = vec3(_e270.x, _e270.y, 6.0); + let _e280 = textureSampleLevel(tex2D, samp, (_e274.xy / vec2(_e274.z)), 3.0); c_2 = _e280; let _e281 = coord_5; let _e288 = coord_5; - let _e300 = textureSampleLevel(tex2D, samp, (vec3(_e288.x, _e288.y, 0.0) / vec3(6.0)).xy, 3.0); + let _e293 = vec4(_e288.x, _e288.y, 0.0, 6.0); + let _e300 = textureSampleLevel(tex2D, samp, (_e293.xyz / vec3(_e293.w)).xy, 3.0); c_2 = _e300; let _e301 = coord_5; let _e309 = coord_5; - let _e321 = textureSampleLevel(tex2D, samp, (vec2(_e309.x, _e309.y) / vec2(6.0)), 3.0, vec2(5)); + let _e313 = vec3(_e309.x, _e309.y, 6.0); + let _e321 = textureSampleLevel(tex2D, samp, (_e313.xy / vec2(_e313.z)), 3.0, vec2(5)); c_2 = _e321; let _e322 = coord_5; let _e331 = coord_5; - let _e345 = textureSampleLevel(tex2D, samp, (vec3(_e331.x, _e331.y, 0.0) / vec3(6.0)).xy, 3.0, vec2(5)); + let _e336 = vec4(_e331.x, _e331.y, 0.0, 6.0); + let _e345 = textureSampleLevel(tex2D, samp, (_e336.xyz / vec3(_e336.w)).xy, 3.0, vec2(5)); c_2 = _e345; let _e346 = coord_5; let _e353 = coord_5; - let _e364 = textureSample(tex2D, samp, (vec2(_e353.x, _e353.y) / vec2(6.0)), vec2(5)); + let _e357 = vec3(_e353.x, _e353.y, 6.0); + let _e364 = textureSample(tex2D, samp, (_e357.xy / vec2(_e357.z)), vec2(5)); c_2 = _e364; let _e365 = coord_5; let _e373 = coord_5; - let _e386 = textureSample(tex2D, samp, (vec3(_e373.x, _e373.y, 0.0) / vec3(6.0)).xy, vec2(5)); + let _e378 = vec4(_e373.x, _e373.y, 0.0, 6.0); + let _e386 = textureSample(tex2D, samp, (_e378.xyz / vec3(_e378.w)).xy, vec2(5)); c_2 = _e386; let _e387 = coord_5; let _e395 = coord_5; - let _e407 = textureSampleBias(tex2D, samp, (vec2(_e395.x, _e395.y) / vec2(6.0)), 2.0, vec2(5)); + let _e399 = vec3(_e395.x, _e395.y, 6.0); + let _e407 = textureSampleBias(tex2D, samp, (_e399.xy / vec2(_e399.z)), 2.0, vec2(5)); c_2 = _e407; let _e408 = coord_5; let _e417 = coord_5; - let _e431 = textureSampleBias(tex2D, samp, (vec3(_e417.x, _e417.y, 0.0) / vec3(6.0)).xy, 2.0, vec2(5)); + let _e422 = vec4(_e417.x, _e417.y, 0.0, 6.0); + let _e431 = textureSampleBias(tex2D, samp, (_e422.xyz / vec3(_e422.w)).xy, 2.0, vec2(5)); c_2 = _e431; let _e432 = coord_5; let _e435 = coord_5; @@ -301,58 +333,70 @@ fn testTex2DShadow(coord_6: vec2) { size2DShadow = vec2(_e20); let _e24 = coord_7; let _e29 = coord_7; - let _e35 = textureSampleCompare(tex2DShadow, sampShadow, vec2(_e29.x, _e29.y), 1.0); - d = _e35; - let _e36 = coord_7; - let _e45 = coord_7; - let _e55 = textureSampleCompareLevel(tex2DShadow, sampShadow, vec2(_e45.x, _e45.y), 1.0); - d = _e55; - let _e56 = coord_7; - let _e67 = coord_7; - let _e79 = textureSampleCompareLevel(tex2DShadow, sampShadow, vec2(_e67.x, _e67.y), 1.0, vec2(5)); - d = _e79; - let _e80 = coord_7; - let _e86 = coord_7; - let _e93 = textureSampleCompareLevel(tex2DShadow, sampShadow, vec2(_e86.x, _e86.y), 1.0); - d = _e93; - let _e94 = coord_7; - let _e102 = coord_7; - let _e111 = textureSampleCompareLevel(tex2DShadow, sampShadow, vec2(_e102.x, _e102.y), 1.0, vec2(5)); - d = _e111; - let _e112 = coord_7; - let _e119 = coord_7; - let _e127 = textureSampleCompare(tex2DShadow, sampShadow, vec2(_e119.x, _e119.y), 1.0, vec2(5)); - d = _e127; - let _e128 = coord_7; + let _e33 = vec3(_e29.x, _e29.y, 1.0); + let _e36 = textureSampleCompare(tex2DShadow, sampShadow, _e33.xy, _e33.z); + d = _e36; + let _e37 = coord_7; + let _e46 = coord_7; + let _e50 = vec3(_e46.x, _e46.y, 1.0); + let _e57 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e50.xy, _e50.z); + d = _e57; + let _e58 = coord_7; + let _e69 = coord_7; + let _e73 = vec3(_e69.x, _e69.y, 1.0); + let _e82 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e73.xy, _e73.z, vec2(5)); + d = _e82; + let _e83 = coord_7; + let _e89 = coord_7; + let _e93 = vec3(_e89.x, _e89.y, 1.0); + let _e97 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e93.xy, _e93.z); + d = _e97; + let _e98 = coord_7; + let _e106 = coord_7; + let _e110 = vec3(_e106.x, _e106.y, 1.0); + let _e116 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e110.xy, _e110.z, vec2(5)); + d = _e116; + let _e117 = coord_7; + let _e124 = coord_7; + let _e128 = vec3(_e124.x, _e124.y, 1.0); + let _e133 = textureSampleCompare(tex2DShadow, sampShadow, _e128.xy, _e128.z, vec2(5)); + d = _e133; let _e134 = coord_7; - let _e143 = (vec3(_e134.x, _e134.y, 1.0) / vec3(6.0)); - let _e146 = textureSampleCompare(tex2DShadow, sampShadow, _e143.xy, _e143.z); - d = _e146; - let _e147 = coord_7; - let _e157 = coord_7; - let _e170 = (vec3(_e157.x, _e157.y, 1.0) / vec3(6.0)); - let _e173 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e170.xy, _e170.z); - d = _e173; - let _e174 = coord_7; - let _e186 = coord_7; - let _e201 = (vec3(_e186.x, _e186.y, 1.0) / vec3(6.0)); - let _e204 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e201.xy, _e201.z, vec2(5)); - d = _e204; - let _e205 = coord_7; - let _e212 = coord_7; - let _e222 = (vec3(_e212.x, _e212.y, 1.0) / vec3(6.0)); - let _e225 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e222.xy, _e222.z); - d = _e225; - let _e226 = coord_7; - let _e235 = coord_7; - let _e247 = (vec3(_e235.x, _e235.y, 1.0) / vec3(6.0)); - let _e250 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e247.xy, _e247.z, vec2(5)); - d = _e250; - let _e251 = coord_7; - let _e259 = coord_7; - let _e270 = (vec3(_e259.x, _e259.y, 1.0) / vec3(6.0)); - let _e273 = textureSampleCompare(tex2DShadow, sampShadow, _e270.xy, _e270.z, vec2(5)); - d = _e273; + let _e140 = coord_7; + let _e145 = vec4(_e140.x, _e140.y, 1.0, 6.0); + let _e149 = (_e145.xyz / vec3(_e145.w)); + let _e152 = textureSampleCompare(tex2DShadow, sampShadow, _e149.xy, _e149.z); + d = _e152; + let _e153 = coord_7; + let _e163 = coord_7; + let _e168 = vec4(_e163.x, _e163.y, 1.0, 6.0); + let _e176 = (_e168.xyz / vec3(_e168.w)); + let _e179 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e176.xy, _e176.z); + d = _e179; + let _e180 = coord_7; + let _e192 = coord_7; + let _e197 = vec4(_e192.x, _e192.y, 1.0, 6.0); + let _e207 = (_e197.xyz / vec3(_e197.w)); + let _e210 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e207.xy, _e207.z, vec2(5)); + d = _e210; + let _e211 = coord_7; + let _e218 = coord_7; + let _e223 = vec4(_e218.x, _e218.y, 1.0, 6.0); + let _e228 = (_e223.xyz / vec3(_e223.w)); + let _e231 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e228.xy, _e228.z); + d = _e231; + let _e232 = coord_7; + let _e241 = coord_7; + let _e246 = vec4(_e241.x, _e241.y, 1.0, 6.0); + let _e253 = (_e246.xyz / vec3(_e246.w)); + let _e256 = textureSampleCompareLevel(tex2DShadow, sampShadow, _e253.xy, _e253.z, vec2(5)); + d = _e256; + let _e257 = coord_7; + let _e265 = coord_7; + let _e270 = vec4(_e265.x, _e265.y, 1.0, 6.0); + let _e276 = (_e270.xyz / vec3(_e270.w)); + let _e279 = textureSampleCompare(tex2DShadow, sampShadow, _e276.xy, _e276.z, vec2(5)); + d = _e279; return; } @@ -413,20 +457,24 @@ fn testTex2DArrayShadow(coord_10: vec3) { size2DArrayShadow = vec3(vec3(_e20.x, _e20.y, _e23)); let _e28 = coord_11; let _e34 = coord_11; - let _e42 = textureSampleCompare(tex2DArrayShadow, sampShadow, vec2(_e34.x, _e34.y), i32(_e34.z), 1.0); - d_1 = _e42; - let _e43 = coord_11; - let _e53 = coord_11; - let _e65 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, vec2(_e53.x, _e53.y), i32(_e53.z), 1.0); - d_1 = _e65; - let _e66 = coord_11; - let _e78 = coord_11; - let _e92 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, vec2(_e78.x, _e78.y), i32(_e78.z), 1.0, vec2(5)); - d_1 = _e92; - let _e93 = coord_11; - let _e101 = coord_11; - let _e111 = textureSampleCompare(tex2DArrayShadow, sampShadow, vec2(_e101.x, _e101.y), i32(_e101.z), 1.0, vec2(5)); - d_1 = _e111; + let _e39 = vec4(_e34.x, _e34.y, _e34.z, 1.0); + let _e44 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e39.xy, i32(_e39.z), _e39.w); + d_1 = _e44; + let _e45 = coord_11; + let _e55 = coord_11; + let _e60 = vec4(_e55.x, _e55.y, _e55.z, 1.0); + let _e69 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e60.xy, i32(_e60.z), _e60.w); + d_1 = _e69; + let _e70 = coord_11; + let _e82 = coord_11; + let _e87 = vec4(_e82.x, _e82.y, _e82.z, 1.0); + let _e98 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, _e87.xy, i32(_e87.z), _e87.w, vec2(5)); + d_1 = _e98; + let _e99 = coord_11; + let _e107 = coord_11; + let _e112 = vec4(_e107.x, _e107.y, _e107.z, 1.0); + let _e119 = textureSampleCompare(tex2DArrayShadow, sampShadow, _e112.xy, i32(_e112.z), _e112.w, vec2(5)); + d_1 = _e119; return; } @@ -463,12 +511,14 @@ fn testTexCubeShadow(coord_14: vec3) { sizeCubeShadow = vec2(_e20); let _e24 = coord_15; let _e30 = coord_15; - let _e37 = textureSampleCompare(texCubeShadow, sampShadow, vec3(_e30.x, _e30.y, _e30.z), 1.0); - d_2 = _e37; - let _e38 = coord_15; - let _e48 = coord_15; - let _e59 = textureSampleCompareLevel(texCubeShadow, sampShadow, vec3(_e48.x, _e48.y, _e48.z), 1.0); - d_2 = _e59; + let _e35 = vec4(_e30.x, _e30.y, _e30.z, 1.0); + let _e38 = textureSampleCompare(texCubeShadow, sampShadow, _e35.xyz, _e35.w); + d_2 = _e38; + let _e39 = coord_15; + let _e49 = coord_15; + let _e54 = vec4(_e49.x, _e49.y, _e49.z, 1.0); + let _e61 = textureSampleCompareLevel(texCubeShadow, sampShadow, _e54.xyz, _e54.w); + d_2 = _e61; return; } @@ -527,35 +577,43 @@ fn testTex3D(coord_20: vec3) { c_6 = _e31; let _e32 = coord_21; let _e38 = coord_21; - let _e48 = textureSample(tex3D, samp, (vec3(_e38.x, _e38.y, _e38.z) / vec3(6.0))); + let _e43 = vec4(_e38.x, _e38.y, _e38.z, 6.0); + let _e48 = textureSample(tex3D, samp, (_e43.xyz / vec3(_e43.w))); c_6 = _e48; let _e49 = coord_21; let _e56 = coord_21; - let _e67 = textureSampleBias(tex3D, samp, (vec3(_e56.x, _e56.y, _e56.z) / vec3(6.0)), 2.0); + let _e61 = vec4(_e56.x, _e56.y, _e56.z, 6.0); + let _e67 = textureSampleBias(tex3D, samp, (_e61.xyz / vec3(_e61.w)), 2.0); c_6 = _e67; let _e68 = coord_21; let _e76 = coord_21; - let _e88 = textureSample(tex3D, samp, (vec3(_e76.x, _e76.y, _e76.z) / vec3(6.0)), vec3(5)); + let _e81 = vec4(_e76.x, _e76.y, _e76.z, 6.0); + let _e88 = textureSample(tex3D, samp, (_e81.xyz / vec3(_e81.w)), vec3(5)); c_6 = _e88; let _e89 = coord_21; let _e98 = coord_21; - let _e111 = textureSampleBias(tex3D, samp, (vec3(_e98.x, _e98.y, _e98.z) / vec3(6.0)), 2.0, vec3(5)); + let _e103 = vec4(_e98.x, _e98.y, _e98.z, 6.0); + let _e111 = textureSampleBias(tex3D, samp, (_e103.xyz / vec3(_e103.w)), 2.0, vec3(5)); c_6 = _e111; let _e112 = coord_21; let _e119 = coord_21; - let _e130 = textureSampleLevel(tex3D, samp, (vec3(_e119.x, _e119.y, _e119.z) / vec3(6.0)), 3.0); + let _e124 = vec4(_e119.x, _e119.y, _e119.z, 6.0); + let _e130 = textureSampleLevel(tex3D, samp, (_e124.xyz / vec3(_e124.w)), 3.0); c_6 = _e130; let _e131 = coord_21; let _e140 = coord_21; - let _e153 = textureSampleLevel(tex3D, samp, (vec3(_e140.x, _e140.y, _e140.z) / vec3(6.0)), 3.0, vec3(5)); + let _e145 = vec4(_e140.x, _e140.y, _e140.z, 6.0); + let _e153 = textureSampleLevel(tex3D, samp, (_e145.xyz / vec3(_e145.w)), 3.0, vec3(5)); c_6 = _e153; let _e154 = coord_21; let _e164 = coord_21; - let _e178 = textureSampleGrad(tex3D, samp, (vec3(_e164.x, _e164.y, _e164.z) / vec3(6.0)), vec3(4.0), vec3(4.0)); + let _e169 = vec4(_e164.x, _e164.y, _e164.z, 6.0); + let _e178 = textureSampleGrad(tex3D, samp, (_e169.xyz / vec3(_e169.w)), vec3(4.0), vec3(4.0)); c_6 = _e178; let _e179 = coord_21; let _e191 = coord_21; - let _e207 = textureSampleGrad(tex3D, samp, (vec3(_e191.x, _e191.y, _e191.z) / vec3(6.0)), vec3(4.0), vec3(4.0), vec3(5)); + let _e196 = vec4(_e191.x, _e191.y, _e191.z, 6.0); + let _e207 = textureSampleGrad(tex3D, samp, (_e196.xyz / vec3(_e196.w)), vec3(4.0), vec3(4.0), vec3(5)); c_6 = _e207; let _e213 = coord_21; let _e218 = textureSampleGrad(tex3D, samp, _e213, vec3(4.0), vec3(4.0)); From 6bd15e4492364d175d3ce981654ea03486a3582b Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 28 Sep 2023 16:31:59 -0700 Subject: [PATCH 2140/2212] Add snapshot tests for constant evaluation of splats and composes. --- tests/in/const-exprs.wgsl | 14 +++ tests/out/glsl/const-exprs.main.Compute.glsl | 14 +++ tests/out/hlsl/const-exprs.hlsl | 16 +++ tests/out/msl/const-exprs.msl | 17 +++ tests/out/spv/const-exprs.spvasm | 114 +++++++++++-------- tests/out/wgsl/const-exprs.wgsl | 14 +++ 6 files changed, 143 insertions(+), 46 deletions(-) diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl index fd1b9c31b..73d5b4af2 100644 --- a/tests/in/const-exprs.wgsl +++ b/tests/in/const-exprs.wgsl @@ -7,6 +7,8 @@ fn main() { index_of_compose(); compose_three_deep(); non_constant_initializers(); + splat_of_constant(); + compose_of_constant(); } // Swizzle the value of nested Compose expressions. @@ -46,3 +48,15 @@ fn non_constant_initializers() { out += vec4(w, x, y, z); } + +// Constant evaluation should be able to see through constants to +// their values. +const FOUR: i32 = 4; + +fn splat_of_constant() { + out = -vec4(FOUR); +} + +fn compose_of_constant() { + out = -vec4(FOUR, FOUR, FOUR, FOUR); +} diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index df029bdaa..fde4c9615 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -5,6 +5,8 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +const int FOUR = 4; + layout(std430) buffer type_block_0Compute { ivec4 _group_0_binding_0_cs; }; layout(std430) buffer type_1_block_1Compute { int _group_0_binding_1_cs; }; @@ -49,11 +51,23 @@ void non_constant_initializers() { return; } +void splat_of_constant() { + _group_0_binding_0_cs = -(ivec4(FOUR)); + return; +} + +void compose_of_constant() { + _group_0_binding_0_cs = -(ivec4(FOUR, FOUR, FOUR, FOUR)); + return; +} + void main() { swizzle_of_compose(); index_of_compose(); compose_three_deep(); non_constant_initializers(); + splat_of_constant(); + compose_of_constant(); return; } diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index a43f27b02..6e325a9bf 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -1,3 +1,5 @@ +static const int FOUR = 4; + RWByteAddressBuffer out_ : register(u0); RWByteAddressBuffer out2_ : register(u1); @@ -45,6 +47,18 @@ void non_constant_initializers() return; } +void splat_of_constant() +{ + out_.Store4(0, asuint(-((FOUR).xxxx))); + return; +} + +void compose_of_constant() +{ + out_.Store4(0, asuint(-(int4(FOUR, FOUR, FOUR, FOUR)))); + return; +} + [numthreads(1, 1, 1)] void main() { @@ -52,5 +66,7 @@ void main() index_of_compose(); compose_three_deep(); non_constant_initializers(); + splat_of_constant(); + compose_of_constant(); return; } diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index a9aa55999..1d9c8e9ca 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -4,6 +4,7 @@ using metal::uint; +constant int FOUR = 4; void swizzle_of_compose( device metal::int4& out @@ -52,6 +53,20 @@ void non_constant_initializers( return; } +void splat_of_constant( + device metal::int4& out +) { + out = -(metal::int4(FOUR)); + return; +} + +void compose_of_constant( + device metal::int4& out +) { + out = -(metal::int4(FOUR, FOUR, FOUR, FOUR)); + return; +} + kernel void main_( device metal::int4& out [[user(fake0)]] , device int& out2_ [[user(fake0)]] @@ -60,5 +75,7 @@ kernel void main_( index_of_compose(out2_); compose_three_deep(out2_); non_constant_initializers(out); + splat_of_constant(out); + compose_of_constant(out); return; } diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index 50b0373a4..9e0d6c14c 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,42 +1,42 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 72 +; Bound: 86 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %64 "main" -OpExecutionMode %64 LocalSize 1 1 1 -OpDecorate %6 DescriptorSet 0 -OpDecorate %6 Binding 0 -OpDecorate %7 Block -OpMemberDecorate %7 0 Offset 0 -OpDecorate %9 DescriptorSet 0 -OpDecorate %9 Binding 1 -OpDecorate %10 Block -OpMemberDecorate %10 0 Offset 0 +OpEntryPoint GLCompute %76 "main" +OpExecutionMode %76 LocalSize 1 1 1 +OpDecorate %7 DescriptorSet 0 +OpDecorate %7 Binding 0 +OpDecorate %8 Block +OpMemberDecorate %8 0 Offset 0 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 1 +OpDecorate %11 Block +OpMemberDecorate %11 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 4 %5 = OpTypeVector %4 2 -%7 = OpTypeStruct %3 -%8 = OpTypePointer StorageBuffer %7 -%6 = OpVariable %8 StorageBuffer -%10 = OpTypeStruct %4 -%11 = OpTypePointer StorageBuffer %10 -%9 = OpVariable %11 StorageBuffer -%14 = OpTypeFunction %2 -%15 = OpTypePointer StorageBuffer %3 -%17 = OpTypeInt 32 0 -%16 = OpConstant %17 0 -%19 = OpConstant %4 1 -%20 = OpConstant %4 2 -%21 = OpConstantComposite %5 %19 %20 -%22 = OpConstant %4 3 -%23 = OpConstant %4 4 -%24 = OpConstantComposite %5 %22 %23 -%25 = OpConstantComposite %3 %23 %22 %20 %19 +%6 = OpConstant %4 4 +%8 = OpTypeStruct %3 +%9 = OpTypePointer StorageBuffer %8 +%7 = OpVariable %9 StorageBuffer +%11 = OpTypeStruct %4 +%12 = OpTypePointer StorageBuffer %11 +%10 = OpVariable %12 StorageBuffer +%15 = OpTypeFunction %2 +%16 = OpTypePointer StorageBuffer %3 +%18 = OpTypeInt 32 0 +%17 = OpConstant %18 0 +%20 = OpConstant %4 1 +%21 = OpConstant %4 2 +%22 = OpConstantComposite %5 %20 %21 +%23 = OpConstant %4 3 +%24 = OpConstantComposite %5 %23 %6 +%25 = OpConstantComposite %3 %6 %23 %21 %20 %29 = OpTypePointer StorageBuffer %4 %37 = OpConstant %4 6 %44 = OpConstant %4 30 @@ -44,27 +44,29 @@ OpMemberDecorate %10 0 Offset 0 %47 = OpTypePointer Function %4 %49 = OpConstantNull %4 %51 = OpConstantNull %4 -%13 = OpFunction %2 None %14 -%12 = OpLabel -%18 = OpAccessChain %15 %6 %16 +%66 = OpConstantComposite %3 %6 %6 %6 %6 +%72 = OpConstantComposite %3 %6 %6 %6 %6 +%14 = OpFunction %2 None %15 +%13 = OpLabel +%19 = OpAccessChain %16 %7 %17 OpBranch %26 %26 = OpLabel -OpStore %18 %25 +OpStore %19 %25 OpReturn OpFunctionEnd -%28 = OpFunction %2 None %14 +%28 = OpFunction %2 None %15 %27 = OpLabel -%30 = OpAccessChain %29 %9 %16 +%30 = OpAccessChain %29 %10 %17 OpBranch %31 %31 = OpLabel %32 = OpLoad %4 %30 -%33 = OpIAdd %4 %32 %20 +%33 = OpIAdd %4 %32 %21 OpStore %30 %33 OpReturn OpFunctionEnd -%35 = OpFunction %2 None %14 +%35 = OpFunction %2 None %15 %34 = OpLabel -%36 = OpAccessChain %29 %9 %16 +%36 = OpAccessChain %29 %10 %17 OpBranch %38 %38 = OpLabel %39 = OpLoad %4 %36 @@ -72,13 +74,13 @@ OpBranch %38 OpStore %36 %40 OpReturn OpFunctionEnd -%42 = OpFunction %2 None %14 +%42 = OpFunction %2 None %15 %41 = OpLabel %48 = OpVariable %47 Function %49 %52 = OpVariable %47 Function %45 %46 = OpVariable %47 Function %44 %50 = OpVariable %47 Function %51 -%43 = OpAccessChain %15 %6 %16 +%43 = OpAccessChain %16 %7 %17 OpBranch %53 %53 = OpLabel %54 = OpLoad %4 %46 @@ -95,15 +97,35 @@ OpStore %50 %55 OpStore %43 %62 OpReturn OpFunctionEnd -%64 = OpFunction %2 None %14 +%64 = OpFunction %2 None %15 %63 = OpLabel -%65 = OpAccessChain %15 %6 %16 -%66 = OpAccessChain %29 %9 %16 +%65 = OpAccessChain %16 %7 %17 OpBranch %67 %67 = OpLabel -%68 = OpFunctionCall %2 %13 -%69 = OpFunctionCall %2 %28 -%70 = OpFunctionCall %2 %35 -%71 = OpFunctionCall %2 %42 +%68 = OpSNegate %3 %66 +OpStore %65 %68 +OpReturn +OpFunctionEnd +%70 = OpFunction %2 None %15 +%69 = OpLabel +%71 = OpAccessChain %16 %7 %17 +OpBranch %73 +%73 = OpLabel +%74 = OpSNegate %3 %72 +OpStore %71 %74 +OpReturn +OpFunctionEnd +%76 = OpFunction %2 None %15 +%75 = OpLabel +%77 = OpAccessChain %16 %7 %17 +%78 = OpAccessChain %29 %10 %17 +OpBranch %79 +%79 = OpLabel +%80 = OpFunctionCall %2 %14 +%81 = OpFunctionCall %2 %28 +%82 = OpFunctionCall %2 %35 +%83 = OpFunctionCall %2 %42 +%84 = OpFunctionCall %2 %64 +%85 = OpFunctionCall %2 %70 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index dcef1812b..47744ede0 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -1,3 +1,5 @@ +const FOUR: i32 = 4; + @group(0) @binding(0) var out: vec4; @group(0) @binding(1) @@ -43,11 +45,23 @@ fn non_constant_initializers() { return; } +fn splat_of_constant() { + out = -(vec4(FOUR)); + return; +} + +fn compose_of_constant() { + out = -(vec4(FOUR, FOUR, FOUR, FOUR)); + return; +} + @compute @workgroup_size(1, 1, 1) fn main() { swizzle_of_compose(); index_of_compose(); compose_three_deep(); non_constant_initializers(); + splat_of_constant(); + compose_of_constant(); return; } From 3e4d565576d4fa14076b4871db9b3cb92e2c3513 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 28 Sep 2023 16:18:41 -0700 Subject: [PATCH 2141/2212] Let ConstantEvaluator see through Constant exprs in Compose exprs. --- src/proc/constant_evaluator.rs | 94 ++++++++++++++++++-- tests/out/glsl/const-exprs.main.Compute.glsl | 2 +- tests/out/hlsl/const-exprs.hlsl | 2 +- tests/out/msl/const-exprs.msl | 2 +- tests/out/spv/const-exprs.spvasm | 10 +-- tests/out/wgsl/const-exprs.wgsl | 2 +- tests/out/wgsl/module-scope.wgsl | 2 +- 7 files changed, 99 insertions(+), 15 deletions(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 9dc021275..75b5d0c0a 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -213,11 +213,12 @@ impl<'a> ConstantEvaluator<'a> { Expression::Literal(_) | Expression::ZeroValue(_) | Expression::Constant(_) => { Ok(self.register_evaluated_expr(expr.clone(), span)) } - Expression::Compose { ref components, .. } => { - for component in components { - self.check(*component)?; - } - Ok(self.register_evaluated_expr(expr.clone(), span)) + Expression::Compose { ty, ref components } => { + let components = components + .iter() + .map(|component| self.check_and_get(*component)) + .collect::, _>>()?; + Ok(self.register_evaluated_expr(Expression::Compose { ty, components }, span)) } Expression::Splat { value, .. } => { self.check(value)?; @@ -1343,4 +1344,87 @@ mod tests { Expression::Literal(Literal::F32(5.)) ); } + + #[test] + fn compose_of_constants() { + let mut types = UniqueArena::new(); + let mut constants = Arena::new(); + let mut const_expressions = Arena::new(); + + let i32_ty = types.insert( + Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + }, + Default::default(), + ); + + let vec2_i32_ty = types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Sint, + width: 4, + }, + }, + Default::default(), + ); + + let h = constants.append( + Constant { + name: None, + r#override: crate::Override::None, + ty: i32_ty, + init: const_expressions + .append(Expression::Literal(Literal::I32(4)), Default::default()), + }, + Default::default(), + ); + + let h_expr = const_expressions.append(Expression::Constant(h), Default::default()); + + let mut solver = ConstantEvaluator { + types: &mut types, + constants: &constants, + expressions: &mut const_expressions, + function_local_data: None, + }; + + let solved_compose = solver + .try_eval_and_append( + &Expression::Compose { + ty: vec2_i32_ty, + components: vec![h_expr, h_expr], + }, + Default::default(), + ) + .unwrap(); + let solved_negate = solver + .try_eval_and_append( + &Expression::Unary { + op: UnaryOperator::Negate, + expr: solved_compose, + }, + Default::default(), + ) + .unwrap(); + + let pass = match const_expressions[solved_negate] { + Expression::Compose { ty, ref components } => { + ty == vec2_i32_ty + && components.iter().all(|&component| { + let component = &const_expressions[component]; + matches!(*component, Expression::Literal(Literal::I32(-4))) + }) + } + _ => false, + }; + if !pass { + panic!("unexpected evaluation result") + } + } } diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index fde4c9615..2d60807e9 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -57,7 +57,7 @@ void splat_of_constant() { } void compose_of_constant() { - _group_0_binding_0_cs = -(ivec4(FOUR, FOUR, FOUR, FOUR)); + _group_0_binding_0_cs = ivec4(-4, -4, -4, -4); return; } diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index 6e325a9bf..572e95e81 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -55,7 +55,7 @@ void splat_of_constant() void compose_of_constant() { - out_.Store4(0, asuint(-(int4(FOUR, FOUR, FOUR, FOUR)))); + out_.Store4(0, asuint(int4(-4, -4, -4, -4))); return; } diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 1d9c8e9ca..e9db1d0fb 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -63,7 +63,7 @@ void splat_of_constant( void compose_of_constant( device metal::int4& out ) { - out = -(metal::int4(FOUR, FOUR, FOUR, FOUR)); + out = metal::int4(-4, -4, -4, -4); return; } diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index 9e0d6c14c..357ecf919 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -45,7 +45,8 @@ OpMemberDecorate %11 0 Offset 0 %49 = OpConstantNull %4 %51 = OpConstantNull %4 %66 = OpConstantComposite %3 %6 %6 %6 %6 -%72 = OpConstantComposite %3 %6 %6 %6 %6 +%72 = OpConstant %4 -4 +%73 = OpConstantComposite %3 %72 %72 %72 %72 %14 = OpFunction %2 None %15 %13 = OpLabel %19 = OpAccessChain %16 %7 %17 @@ -109,10 +110,9 @@ OpFunctionEnd %70 = OpFunction %2 None %15 %69 = OpLabel %71 = OpAccessChain %16 %7 %17 -OpBranch %73 -%73 = OpLabel -%74 = OpSNegate %3 %72 -OpStore %71 %74 +OpBranch %74 +%74 = OpLabel +OpStore %71 %73 OpReturn OpFunctionEnd %76 = OpFunction %2 None %15 diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index 47744ede0..77d24bbdf 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -51,7 +51,7 @@ fn splat_of_constant() { } fn compose_of_constant() { - out = -(vec4(FOUR, FOUR, FOUR, FOUR)); + out = vec4(-4, -4, -4, -4); return; } diff --git a/tests/out/wgsl/module-scope.wgsl b/tests/out/wgsl/module-scope.wgsl index c30052dd1..b746ff37c 100644 --- a/tests/out/wgsl/module-scope.wgsl +++ b/tests/out/wgsl/module-scope.wgsl @@ -14,7 +14,7 @@ fn statement() { } fn returns() -> S { - return S(Value); + return S(1); } fn call() { From c16a298cac5741bc811d50fbfe9ada239aa4eeae Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 28 Sep 2023 16:19:25 -0700 Subject: [PATCH 2142/2212] Let ConstantEvaluator see through Constant exprs in Splat exprs. --- src/proc/constant_evaluator.rs | 89 +++++++++++++++++++- tests/out/glsl/const-exprs.main.Compute.glsl | 2 +- tests/out/hlsl/const-exprs.hlsl | 2 +- tests/out/msl/const-exprs.msl | 2 +- tests/out/spv/const-exprs.spvasm | 48 +++++------ tests/out/wgsl/const-exprs.wgsl | 2 +- 6 files changed, 113 insertions(+), 32 deletions(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 75b5d0c0a..e22b1275e 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -220,9 +220,9 @@ impl<'a> ConstantEvaluator<'a> { .collect::, _>>()?; Ok(self.register_evaluated_expr(Expression::Compose { ty, components }, span)) } - Expression::Splat { value, .. } => { - self.check(value)?; - Ok(self.register_evaluated_expr(expr.clone(), span)) + Expression::Splat { size, value } => { + let value = self.check_and_get(value)?; + Ok(self.register_evaluated_expr(Expression::Splat { size, value }, span)) } Expression::AccessIndex { base, index } => { let base = self.check_and_get(base)?; @@ -1427,4 +1427,87 @@ mod tests { panic!("unexpected evaluation result") } } + + #[test] + fn splat_of_constant() { + let mut types = UniqueArena::new(); + let mut constants = Arena::new(); + let mut const_expressions = Arena::new(); + + let i32_ty = types.insert( + Type { + name: None, + inner: TypeInner::Scalar { + kind: ScalarKind::Sint, + width: 4, + }, + }, + Default::default(), + ); + + let vec2_i32_ty = types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size: VectorSize::Bi, + kind: ScalarKind::Sint, + width: 4, + }, + }, + Default::default(), + ); + + let h = constants.append( + Constant { + name: None, + r#override: crate::Override::None, + ty: i32_ty, + init: const_expressions + .append(Expression::Literal(Literal::I32(4)), Default::default()), + }, + Default::default(), + ); + + let h_expr = const_expressions.append(Expression::Constant(h), Default::default()); + + let mut solver = ConstantEvaluator { + types: &mut types, + constants: &constants, + expressions: &mut const_expressions, + function_local_data: None, + }; + + let solved_compose = solver + .try_eval_and_append( + &Expression::Splat { + size: VectorSize::Bi, + value: h_expr, + }, + Default::default(), + ) + .unwrap(); + let solved_negate = solver + .try_eval_and_append( + &Expression::Unary { + op: UnaryOperator::Negate, + expr: solved_compose, + }, + Default::default(), + ) + .unwrap(); + + let pass = match const_expressions[solved_negate] { + Expression::Compose { ty, ref components } => { + ty == vec2_i32_ty + && components.iter().all(|&component| { + let component = &const_expressions[component]; + matches!(*component, Expression::Literal(Literal::I32(-4))) + }) + } + _ => false, + }; + if !pass { + panic!("unexpected evaluation result") + } + } } diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index 2d60807e9..86263b45c 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -52,7 +52,7 @@ void non_constant_initializers() { } void splat_of_constant() { - _group_0_binding_0_cs = -(ivec4(FOUR)); + _group_0_binding_0_cs = ivec4(-4, -4, -4, -4); return; } diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index 572e95e81..87b2a48d7 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -49,7 +49,7 @@ void non_constant_initializers() void splat_of_constant() { - out_.Store4(0, asuint(-((FOUR).xxxx))); + out_.Store4(0, asuint(int4(-4, -4, -4, -4))); return; } diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index e9db1d0fb..8cf66d617 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -56,7 +56,7 @@ void non_constant_initializers( void splat_of_constant( device metal::int4& out ) { - out = -(metal::int4(FOUR)); + out = metal::int4(-4, -4, -4, -4); return; } diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index 357ecf919..86cb57a91 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,13 +1,13 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 86 +; Bound: 84 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %76 "main" -OpExecutionMode %76 LocalSize 1 1 1 +OpEntryPoint GLCompute %74 "main" +OpExecutionMode %74 LocalSize 1 1 1 OpDecorate %7 DescriptorSet 0 OpDecorate %7 Binding 0 OpDecorate %8 Block @@ -44,9 +44,8 @@ OpMemberDecorate %11 0 Offset 0 %47 = OpTypePointer Function %4 %49 = OpConstantNull %4 %51 = OpConstantNull %4 -%66 = OpConstantComposite %3 %6 %6 %6 %6 -%72 = OpConstant %4 -4 -%73 = OpConstantComposite %3 %72 %72 %72 %72 +%66 = OpConstant %4 -4 +%67 = OpConstantComposite %3 %66 %66 %66 %66 %14 = OpFunction %2 None %15 %13 = OpLabel %19 = OpAccessChain %16 %7 %17 @@ -101,31 +100,30 @@ OpFunctionEnd %64 = OpFunction %2 None %15 %63 = OpLabel %65 = OpAccessChain %16 %7 %17 -OpBranch %67 -%67 = OpLabel -%68 = OpSNegate %3 %66 -OpStore %65 %68 +OpBranch %68 +%68 = OpLabel +OpStore %65 %67 OpReturn OpFunctionEnd %70 = OpFunction %2 None %15 %69 = OpLabel %71 = OpAccessChain %16 %7 %17 -OpBranch %74 -%74 = OpLabel -OpStore %71 %73 +OpBranch %72 +%72 = OpLabel +OpStore %71 %67 OpReturn OpFunctionEnd -%76 = OpFunction %2 None %15 -%75 = OpLabel -%77 = OpAccessChain %16 %7 %17 -%78 = OpAccessChain %29 %10 %17 -OpBranch %79 -%79 = OpLabel -%80 = OpFunctionCall %2 %14 -%81 = OpFunctionCall %2 %28 -%82 = OpFunctionCall %2 %35 -%83 = OpFunctionCall %2 %42 -%84 = OpFunctionCall %2 %64 -%85 = OpFunctionCall %2 %70 +%74 = OpFunction %2 None %15 +%73 = OpLabel +%75 = OpAccessChain %16 %7 %17 +%76 = OpAccessChain %29 %10 %17 +OpBranch %77 +%77 = OpLabel +%78 = OpFunctionCall %2 %14 +%79 = OpFunctionCall %2 %28 +%80 = OpFunctionCall %2 %35 +%81 = OpFunctionCall %2 %42 +%82 = OpFunctionCall %2 %64 +%83 = OpFunctionCall %2 %70 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index 77d24bbdf..ded8e5042 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -46,7 +46,7 @@ fn non_constant_initializers() { } fn splat_of_constant() { - out = -(vec4(FOUR)); + out = vec4(-4, -4, -4, -4); return; } From 648540999e8e97ac74d7189882c50767dccef452 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 29 Sep 2023 15:55:58 +0200 Subject: [PATCH 2143/2212] [wgsl-in] use ast spans for errors since they are more accurate --- src/front/wgsl/lower/construction.rs | 16 +--- src/front/wgsl/lower/mod.rs | 121 ++++++++++++--------------- 2 files changed, 57 insertions(+), 80 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 970f63dca..59d7b1743 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -582,20 +582,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ast::ConstructorType::PartialArray => ConcreteConstructorHandle::PartialArray, ast::ConstructorType::Array { base, size } => { let base = self.resolve_ast_type(base, ctx.as_global())?; - let size = match size { - ast::ArraySize::Constant(expr) => { - let const_expr = self.expression(expr, ctx.as_const())?; - crate::ArraySize::Constant(ctx.as_const().array_length(const_expr)?) - } - ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, - }; + let size = self.array_size(size, ctx.as_global())?; self.layouter.update(ctx.module.to_ctx()).unwrap(); - let ty = ctx.ensure_type_exists(crate::TypeInner::Array { - base, - size, - stride: self.layouter[base].to_stride(), - }); + let stride = self.layouter[base].to_stride(); + + let ty = ctx.ensure_type_exists(crate::TypeInner::Array { base, size, stride }); ConcreteConstructorHandle::Type(ty) } ast::ConstructorType::Type(ty) => ConcreteConstructorHandle::Type(ty), diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index d419f2911..6f06a3232 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -396,57 +396,30 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { } } - fn array_length( - &mut self, - const_expr: Handle, - ) -> Result> { - match self.expr_type { - ExpressionContextType::Runtime(_) => { - unreachable!() - } - ExpressionContextType::Constant => { - let span = self.module.const_expressions.get_span(const_expr); - let len = - self.module - .to_ctx() - .eval_expr_to_u32(const_expr) - .map_err(|err| match err { - crate::proc::U32EvalError::NonConst => { - Error::ExpectedConstExprConcreteIntegerScalar(span) - } - crate::proc::U32EvalError::Negative => { - Error::ExpectedPositiveArrayLength(span) - } - })?; - NonZeroU32::new(len).ok_or(Error::ExpectedPositiveArrayLength(span)) - } - } - } - fn gather_component( &mut self, expr: Handle, + component_span: Span, gather_span: Span, ) -> Result> { match self.expr_type { ExpressionContextType::Runtime(ref rctx) => { - let expr_span = rctx.naga_expressions.get_span(expr); let index = self .module .to_ctx() .eval_expr_to_u32_from(expr, rctx.naga_expressions) .map_err(|err| match err { crate::proc::U32EvalError::NonConst => { - Error::ExpectedConstExprConcreteIntegerScalar(expr_span) + Error::ExpectedConstExprConcreteIntegerScalar(component_span) } crate::proc::U32EvalError::Negative => { - Error::ExpectedNonNegative(expr_span) + Error::ExpectedNonNegative(component_span) } })?; crate::SwizzleComponent::XYZW .get(index as usize) .copied() - .ok_or(Error::InvalidGatherComponent(expr_span)) + .ok_or(Error::InvalidGatherComponent(component_span)) } // This means a `gather` operation appeared in a constant expression. // This error refers to the `gather` itself, not its "component" argument. @@ -1258,6 +1231,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok(crate::SwitchCase { value: match case.value { ast::SwitchValue::Expr(expr) => { + let span = ctx.ast_expressions.get_span(expr); let expr = self.expression(expr, ctx.as_global().as_const())?; match ctx.module.to_ctx().eval_expr_to_literal(expr) { Some(crate::Literal::I32(value)) if !uint => { @@ -1267,10 +1241,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { crate::SwitchValue::U32(value) } _ => { - return Err(Error::InvalidSwitchValue { - uint, - span: ctx.module.const_expressions.get_span(expr), - }); + return Err(Error::InvalidSwitchValue { uint, span }); } } } @@ -2338,6 +2309,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let (image, image_span, gather) = match fun { Texture::Gather => { let image_or_component = args.next()?; + let image_or_component_span = ctx.ast_expressions.get_span(image_or_component); // Gathers from depth textures don't take an initial `component` argument. let lowered_image_or_component = self.expression(image_or_component, ctx.reborrow())?; @@ -2347,20 +2319,21 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { crate::TypeInner::Image { class: crate::ImageClass::Depth { .. }, .. - } => { - let image_span = ctx.ast_expressions.get_span(image_or_component); - ( - lowered_image_or_component, - image_span, - Some(crate::SwizzleComponent::X), - ) - } + } => ( + lowered_image_or_component, + image_or_component_span, + Some(crate::SwizzleComponent::X), + ), _ => { let (image, image_span) = get_image_and_span(self, &mut args, &mut ctx)?; ( image, image_span, - Some(ctx.gather_component(lowered_image_or_component, span)?), + Some(ctx.gather_component( + lowered_image_or_component, + image_or_component_span, + span, + )?), ) } } @@ -2516,8 +2489,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { expr: Handle>, mut ctx: ExpressionContext<'source, '_, '_>, ) -> Result<(u32, Span), Error<'source>> { + let span = ctx.ast_expressions.get_span(expr); let expr = self.expression(expr, ctx.reborrow())?; - let span = ctx.module.const_expressions.get_span(expr); let value = ctx .module .to_ctx() @@ -2531,6 +2504,34 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok((value, span)) } + fn array_size( + &mut self, + size: ast::ArraySize<'source>, + mut ctx: GlobalContext<'source, '_, '_>, + ) -> Result> { + Ok(match size { + ast::ArraySize::Constant(expr) => { + let span = ctx.ast_expressions.get_span(expr); + let const_expr = self.expression(expr, ctx.as_const())?; + let len = + ctx.module + .to_ctx() + .eval_expr_to_u32(const_expr) + .map_err(|err| match err { + crate::proc::U32EvalError::NonConst => { + Error::ExpectedConstExprConcreteIntegerScalar(span) + } + crate::proc::U32EvalError::Negative => { + Error::ExpectedPositiveArrayLength(span) + } + })?; + let size = NonZeroU32::new(len).ok_or(Error::ExpectedPositiveArrayLength(span))?; + crate::ArraySize::Constant(size) + } + ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, + }) + } + /// Return a Naga `Handle` representing the front-end type `handle`. fn resolve_ast_type( &mut self, @@ -2558,19 +2559,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::Type::Array { base, size } => { let base = self.resolve_ast_type(base, ctx.reborrow())?; - self.layouter.update(ctx.module.to_ctx()).unwrap(); + let size = self.array_size(size, ctx.reborrow())?; - crate::TypeInner::Array { - base, - size: match size { - ast::ArraySize::Constant(constant) => { - let const_expr = self.expression(constant, ctx.as_const())?; - crate::ArraySize::Constant(ctx.as_const().array_length(const_expr)?) - } - ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, - }, - stride: self.layouter[base].to_stride(), - } + self.layouter.update(ctx.module.to_ctx()).unwrap(); + let stride = self.layouter[base].to_stride(); + + crate::TypeInner::Array { base, size, stride } } ast::Type::Image { dim, @@ -2586,17 +2580,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ast::Type::RayQuery => crate::TypeInner::RayQuery, ast::Type::BindingArray { base, size } => { let base = self.resolve_ast_type(base, ctx.reborrow())?; - - crate::TypeInner::BindingArray { - base, - size: match size { - ast::ArraySize::Constant(constant) => { - let const_expr = self.expression(constant, ctx.as_const())?; - crate::ArraySize::Constant(ctx.as_const().array_length(const_expr)?) - } - ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, - }, - } + let size = self.array_size(size, ctx.reborrow())?; + crate::TypeInner::BindingArray { base, size } } ast::Type::RayDesc => { return Ok(ctx.module.generate_ray_desc_type()); From 3d346977e59ba41d653fcc6ddd457569bb2fec74 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 29 Sep 2023 16:08:04 +0200 Subject: [PATCH 2144/2212] avoid having constants pointing to other constants --- src/front/glsl/parser_tests.rs | 17 +- src/proc/constant_evaluator.rs | 5 + tests/in/const-exprs.wgsl | 5 + tests/out/glsl/const-exprs.main.Compute.glsl | 3 + tests/out/hlsl/const-exprs.hlsl | 3 + tests/out/msl/const-exprs.msl | 3 + tests/out/spv/const-exprs.spvasm | 205 ++++++++++--------- tests/out/wgsl/const-exprs.wgsl | 3 + 8 files changed, 130 insertions(+), 114 deletions(-) diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index dd5880068..1813a4ce4 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -543,33 +543,26 @@ fn constants() { } ); - let (init_a_handle, init_a) = const_expressions.next().unwrap(); - assert_eq!(init_a, &Expression::Literal(crate::Literal::F32(1.0))); + let (init_handle, init) = const_expressions.next().unwrap(); + assert_eq!(init, &Expression::Literal(crate::Literal::F32(1.0))); - let (constant_a_handle, constant_a) = constants.next().unwrap(); assert_eq!( - constant_a, + constants.next().unwrap().1, &Constant { name: Some("a".to_owned()), r#override: crate::Override::None, ty: ty_handle, - init: init_a_handle + init: init_handle } ); - // skip const expr that was inserted for `global` var - const_expressions.next().unwrap(); - - let (init_b_handle, init_b) = const_expressions.next().unwrap(); - assert_eq!(init_b, &Expression::Constant(constant_a_handle)); - assert_eq!( constants.next().unwrap().1, &Constant { name: Some("b".to_owned()), r#override: crate::Override::None, ty: ty_handle, - init: init_b_handle + init: init_handle } ); diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index e22b1275e..a95684e78 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -210,6 +210,11 @@ impl<'a> ConstantEvaluator<'a> { ) -> Result, ConstantEvaluatorError> { log::trace!("try_eval_and_append: {:?}", expr); match *expr { + Expression::Constant(c) if self.function_local_data.is_none() => { + // "See through" the constant and use its initializer. + // This is mainly done to avoid having constants pointing to other constants. + Ok(self.constants[c].init) + } Expression::Literal(_) | Expression::ZeroValue(_) | Expression::Constant(_) => { Ok(self.register_evaluated_expr(expr.clone(), span)) } diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl index 73d5b4af2..89d8976f5 100644 --- a/tests/in/const-exprs.wgsl +++ b/tests/in/const-exprs.wgsl @@ -53,6 +53,11 @@ fn non_constant_initializers() { // their values. const FOUR: i32 = 4; +const FOUR_ALIAS: i32 = FOUR; + +const TEST_CONSTANT_ADDITION: i32 = FOUR + FOUR; +const TEST_CONSTANT_ALIAS_ADDITION: i32 = FOUR_ALIAS + FOUR_ALIAS; + fn splat_of_constant() { out = -vec4(FOUR); } diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index 86263b45c..00714b34f 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -6,6 +6,9 @@ precision highp int; layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; const int FOUR = 4; +const int FOUR_ALIAS = 4; +const int TEST_CONSTANT_ADDITION = 8; +const int TEST_CONSTANT_ALIAS_ADDITION = 8; layout(std430) buffer type_block_0Compute { ivec4 _group_0_binding_0_cs; }; diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index 87b2a48d7..46961977e 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -1,4 +1,7 @@ static const int FOUR = 4; +static const int FOUR_ALIAS = 4; +static const int TEST_CONSTANT_ADDITION = 8; +static const int TEST_CONSTANT_ALIAS_ADDITION = 8; RWByteAddressBuffer out_ : register(u0); RWByteAddressBuffer out2_ : register(u1); diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 8cf66d617..135b4ec10 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -5,6 +5,9 @@ using metal::uint; constant int FOUR = 4; +constant int FOUR_ALIAS = 4; +constant int TEST_CONSTANT_ADDITION = 8; +constant int TEST_CONSTANT_ALIAS_ADDITION = 8; void swizzle_of_compose( device metal::int4& out diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index 86cb57a91..0b5c91317 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,129 +1,130 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 84 +; Bound: 85 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %74 "main" -OpExecutionMode %74 LocalSize 1 1 1 -OpDecorate %7 DescriptorSet 0 -OpDecorate %7 Binding 0 -OpDecorate %8 Block -OpMemberDecorate %8 0 Offset 0 -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 1 -OpDecorate %11 Block -OpMemberDecorate %11 0 Offset 0 +OpEntryPoint GLCompute %75 "main" +OpExecutionMode %75 LocalSize 1 1 1 +OpDecorate %8 DescriptorSet 0 +OpDecorate %8 Binding 0 +OpDecorate %9 Block +OpMemberDecorate %9 0 Offset 0 +OpDecorate %11 DescriptorSet 0 +OpDecorate %11 Binding 1 +OpDecorate %12 Block +OpMemberDecorate %12 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 4 %5 = OpTypeVector %4 2 %6 = OpConstant %4 4 -%8 = OpTypeStruct %3 -%9 = OpTypePointer StorageBuffer %8 -%7 = OpVariable %9 StorageBuffer -%11 = OpTypeStruct %4 -%12 = OpTypePointer StorageBuffer %11 -%10 = OpVariable %12 StorageBuffer -%15 = OpTypeFunction %2 -%16 = OpTypePointer StorageBuffer %3 -%18 = OpTypeInt 32 0 -%17 = OpConstant %18 0 -%20 = OpConstant %4 1 -%21 = OpConstant %4 2 -%22 = OpConstantComposite %5 %20 %21 -%23 = OpConstant %4 3 -%24 = OpConstantComposite %5 %23 %6 -%25 = OpConstantComposite %3 %6 %23 %21 %20 -%29 = OpTypePointer StorageBuffer %4 -%37 = OpConstant %4 6 -%44 = OpConstant %4 30 -%45 = OpConstant %4 70 -%47 = OpTypePointer Function %4 -%49 = OpConstantNull %4 -%51 = OpConstantNull %4 -%66 = OpConstant %4 -4 -%67 = OpConstantComposite %3 %66 %66 %66 %66 -%14 = OpFunction %2 None %15 -%13 = OpLabel -%19 = OpAccessChain %16 %7 %17 -OpBranch %26 -%26 = OpLabel -OpStore %19 %25 -OpReturn -OpFunctionEnd -%28 = OpFunction %2 None %15 +%7 = OpConstant %4 8 +%9 = OpTypeStruct %3 +%10 = OpTypePointer StorageBuffer %9 +%8 = OpVariable %10 StorageBuffer +%12 = OpTypeStruct %4 +%13 = OpTypePointer StorageBuffer %12 +%11 = OpVariable %13 StorageBuffer +%16 = OpTypeFunction %2 +%17 = OpTypePointer StorageBuffer %3 +%19 = OpTypeInt 32 0 +%18 = OpConstant %19 0 +%21 = OpConstant %4 1 +%22 = OpConstant %4 2 +%23 = OpConstantComposite %5 %21 %22 +%24 = OpConstant %4 3 +%25 = OpConstantComposite %5 %24 %6 +%26 = OpConstantComposite %3 %6 %24 %22 %21 +%30 = OpTypePointer StorageBuffer %4 +%38 = OpConstant %4 6 +%45 = OpConstant %4 30 +%46 = OpConstant %4 70 +%48 = OpTypePointer Function %4 +%50 = OpConstantNull %4 +%52 = OpConstantNull %4 +%67 = OpConstant %4 -4 +%68 = OpConstantComposite %3 %67 %67 %67 %67 +%15 = OpFunction %2 None %16 +%14 = OpLabel +%20 = OpAccessChain %17 %8 %18 +OpBranch %27 %27 = OpLabel -%30 = OpAccessChain %29 %10 %17 -OpBranch %31 -%31 = OpLabel -%32 = OpLoad %4 %30 -%33 = OpIAdd %4 %32 %21 -OpStore %30 %33 +OpStore %20 %26 OpReturn OpFunctionEnd -%35 = OpFunction %2 None %15 -%34 = OpLabel -%36 = OpAccessChain %29 %10 %17 -OpBranch %38 -%38 = OpLabel -%39 = OpLoad %4 %36 -%40 = OpIAdd %4 %39 %37 -OpStore %36 %40 +%29 = OpFunction %2 None %16 +%28 = OpLabel +%31 = OpAccessChain %30 %11 %18 +OpBranch %32 +%32 = OpLabel +%33 = OpLoad %4 %31 +%34 = OpIAdd %4 %33 %22 +OpStore %31 %34 OpReturn OpFunctionEnd -%42 = OpFunction %2 None %15 -%41 = OpLabel -%48 = OpVariable %47 Function %49 -%52 = OpVariable %47 Function %45 -%46 = OpVariable %47 Function %44 -%50 = OpVariable %47 Function %51 -%43 = OpAccessChain %16 %7 %17 -OpBranch %53 -%53 = OpLabel -%54 = OpLoad %4 %46 -OpStore %48 %54 -%55 = OpLoad %4 %48 -OpStore %50 %55 -%56 = OpLoad %4 %46 -%57 = OpLoad %4 %48 -%58 = OpLoad %4 %50 -%59 = OpLoad %4 %52 -%60 = OpCompositeConstruct %3 %56 %57 %58 %59 -%61 = OpLoad %3 %43 -%62 = OpIAdd %3 %61 %60 -OpStore %43 %62 +%36 = OpFunction %2 None %16 +%35 = OpLabel +%37 = OpAccessChain %30 %11 %18 +OpBranch %39 +%39 = OpLabel +%40 = OpLoad %4 %37 +%41 = OpIAdd %4 %40 %38 +OpStore %37 %41 OpReturn OpFunctionEnd -%64 = OpFunction %2 None %15 -%63 = OpLabel -%65 = OpAccessChain %16 %7 %17 -OpBranch %68 -%68 = OpLabel -OpStore %65 %67 +%43 = OpFunction %2 None %16 +%42 = OpLabel +%49 = OpVariable %48 Function %50 +%53 = OpVariable %48 Function %46 +%47 = OpVariable %48 Function %45 +%51 = OpVariable %48 Function %52 +%44 = OpAccessChain %17 %8 %18 +OpBranch %54 +%54 = OpLabel +%55 = OpLoad %4 %47 +OpStore %49 %55 +%56 = OpLoad %4 %49 +OpStore %51 %56 +%57 = OpLoad %4 %47 +%58 = OpLoad %4 %49 +%59 = OpLoad %4 %51 +%60 = OpLoad %4 %53 +%61 = OpCompositeConstruct %3 %57 %58 %59 %60 +%62 = OpLoad %3 %44 +%63 = OpIAdd %3 %62 %61 +OpStore %44 %63 OpReturn OpFunctionEnd -%70 = OpFunction %2 None %15 +%65 = OpFunction %2 None %16 +%64 = OpLabel +%66 = OpAccessChain %17 %8 %18 +OpBranch %69 %69 = OpLabel -%71 = OpAccessChain %16 %7 %17 -OpBranch %72 -%72 = OpLabel -OpStore %71 %67 +OpStore %66 %68 OpReturn OpFunctionEnd -%74 = OpFunction %2 None %15 +%71 = OpFunction %2 None %16 +%70 = OpLabel +%72 = OpAccessChain %17 %8 %18 +OpBranch %73 %73 = OpLabel -%75 = OpAccessChain %16 %7 %17 -%76 = OpAccessChain %29 %10 %17 -OpBranch %77 -%77 = OpLabel -%78 = OpFunctionCall %2 %14 -%79 = OpFunctionCall %2 %28 -%80 = OpFunctionCall %2 %35 -%81 = OpFunctionCall %2 %42 -%82 = OpFunctionCall %2 %64 -%83 = OpFunctionCall %2 %70 +OpStore %72 %68 +OpReturn +OpFunctionEnd +%75 = OpFunction %2 None %16 +%74 = OpLabel +%76 = OpAccessChain %17 %8 %18 +%77 = OpAccessChain %30 %11 %18 +OpBranch %78 +%78 = OpLabel +%79 = OpFunctionCall %2 %15 +%80 = OpFunctionCall %2 %29 +%81 = OpFunctionCall %2 %36 +%82 = OpFunctionCall %2 %43 +%83 = OpFunctionCall %2 %65 +%84 = OpFunctionCall %2 %71 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index ded8e5042..57f3ba6a4 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -1,4 +1,7 @@ const FOUR: i32 = 4; +const FOUR_ALIAS: i32 = 4; +const TEST_CONSTANT_ADDITION: i32 = 8; +const TEST_CONSTANT_ALIAS_ADDITION: i32 = 8; @group(0) @binding(0) var out: vec4; From 55dd0e1fbcdec2cbc7345f4f6caaf63733c550ec Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 29 Sep 2023 19:20:50 +0200 Subject: [PATCH 2145/2212] [wgsl-in] don't treat `let` declarations as `const` declarations --- src/front/wgsl/lower/mod.rs | 22 +- src/proc/constant_evaluator.rs | 5 + src/proc/mod.rs | 2 +- tests/in/const-exprs.wgsl | 8 +- tests/out/analysis/access.info.ron | 2 +- tests/out/glsl/access.foo_vert.Vertex.glsl | 2 +- tests/out/glsl/const-exprs.main.Compute.glsl | 8 +- .../glsl/image.texture_sample.Fragment.glsl | 136 ++--- tests/out/hlsl/access.hlsl | 2 +- tests/out/hlsl/const-exprs.hlsl | 8 +- tests/out/hlsl/image.hlsl | 136 ++--- tests/out/ir/access.compact.ron | 4 +- tests/out/ir/access.ron | 4 +- tests/out/msl/access.msl | 2 +- tests/out/msl/const-exprs.msl | 8 +- tests/out/msl/image.msl | 136 ++--- tests/out/spv/const-exprs.spvasm | 207 ++++--- tests/out/spv/debug-symbol-terrain.spvasm | 382 ++++++------ tests/out/spv/image.spvasm | 561 +++++++++--------- tests/out/wgsl/access.wgsl | 2 +- tests/out/wgsl/const-exprs.wgsl | 8 +- tests/out/wgsl/image.wgsl | 136 ++--- tests/out/wgsl/type-alias.wgsl | 2 +- tests/wgsl-errors.rs | 74 +-- 24 files changed, 926 insertions(+), 931 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 6f06a3232..fe0c4f92d 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -363,11 +363,16 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { fn const_access(&self, handle: Handle) -> Option { match self.expr_type { - ExpressionContextType::Runtime(ref ctx) => self - .module - .to_ctx() - .eval_expr_to_u32_from(handle, ctx.naga_expressions) - .ok(), + ExpressionContextType::Runtime(ref ctx) => { + if !ctx.expression_constness.is_const(handle) { + return None; + } + + self.module + .to_ctx() + .eval_expr_to_u32_from(handle, ctx.naga_expressions) + .ok() + } ExpressionContextType::Constant => self.module.to_ctx().eval_expr_to_u32(handle).ok(), } } @@ -404,6 +409,12 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { ) -> Result> { match self.expr_type { ExpressionContextType::Runtime(ref rctx) => { + if !rctx.expression_constness.is_const(expr) { + return Err(Error::ExpectedConstExprConcreteIntegerScalar( + component_span, + )); + } + let index = self .module .to_ctx() @@ -1076,6 +1087,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { emitter.start(ctx.naga_expressions); let value = self.expression(l.init, ctx.as_expression(block, &mut emitter))?; + ctx.expression_constness.force_non_const(value); let explicit_ty = l.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_global())) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index a95684e78..6453989b3 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -37,6 +37,11 @@ impl ExpressionConstnessTracker { } } + /// Forces the the expression to not be const + pub fn force_non_const(&mut self, value: Handle) { + self.inner.remove(value.index()); + } + fn insert(&mut self, value: Handle) { self.inner.insert(value.index()); } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index bfa0d160c..481ea8902 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -612,7 +612,7 @@ impl GlobalCtx<'_> { self.eval_expr_to_literal_from(handle, self.const_expressions) } - pub(crate) fn eval_expr_to_literal_from( + fn eval_expr_to_literal_from( &self, handle: crate::Handle, arena: &crate::Arena, diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl index 89d8976f5..49e95a275 100644 --- a/tests/in/const-exprs.wgsl +++ b/tests/in/const-exprs.wgsl @@ -13,16 +13,12 @@ fn main() { // Swizzle the value of nested Compose expressions. fn swizzle_of_compose() { - let a = vec2(1, 2); - let b = vec2(3, 4); - out = vec4(a, b).wzyx; // should assign vec4(4, 3, 2, 1); + out = vec4(vec2(1, 2), vec2(3, 4)).wzyx; // should assign vec4(4, 3, 2, 1); } // Index the value of nested Compose expressions. fn index_of_compose() { - let a = vec2(1, 2); - let b = vec2(3, 4); - out2 += vec4(a, b)[1]; // should assign 2 + out2 += vec4(vec2(1, 2), vec2(3, 4))[1]; // should assign 2 } // Index the value of Compose expressions nested three deep diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron index f66a79285..80a2cb162 100644 --- a/tests/out/analysis/access.info.ron +++ b/tests/out/analysis/access.info.ron @@ -2774,7 +2774,7 @@ non_uniform_result: None, requirements: (""), ), - ref_count: 0, + ref_count: 1, assignable_global: None, ty: Value(Scalar( kind: Uint, diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/tests/out/glsl/access.foo_vert.Vertex.glsl index a79ff3039..edc7ce1e6 100644 --- a/tests/out/glsl/access.foo_vert.Vertex.glsl +++ b/tests/out/glsl/access.foo_vert.Vertex.glsl @@ -132,7 +132,7 @@ void main() { test_matrix_within_array_within_struct_accesses(); mat4x3 _matrix = _group_0_binding_0_vs._matrix; uvec2 arr_1[2] = _group_0_binding_0_vs.arr; - float b = _group_0_binding_0_vs._matrix[3][0]; + float b = _group_0_binding_0_vs._matrix[3u][0]; int a_1 = _group_0_binding_0_vs.data[(uint(_group_0_binding_0_vs.data.length()) - 2u)].value; ivec2 c = _group_0_binding_2_vs; float _e33 = read_from_private(foo); diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index 00714b34f..e75ffa650 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -16,17 +16,13 @@ layout(std430) buffer type_1_block_1Compute { int _group_0_binding_1_cs; }; void swizzle_of_compose() { - ivec2 a = ivec2(1, 2); - ivec2 b = ivec2(3, 4); _group_0_binding_0_cs = ivec4(4, 3, 2, 1); return; } void index_of_compose() { - ivec2 a_1 = ivec2(1, 2); - ivec2 b_1 = ivec2(3, 4); - int _e7 = _group_0_binding_1_cs; - _group_0_binding_1_cs = (_e7 + 2); + int _e2 = _group_0_binding_1_cs; + _group_0_binding_1_cs = (_e2 + 2); return; } diff --git a/tests/out/glsl/image.texture_sample.Fragment.glsl b/tests/out/glsl/image.texture_sample.Fragment.glsl index dc17cedc2..97be5a59d 100644 --- a/tests/out/glsl/image.texture_sample.Fragment.glsl +++ b/tests/out/glsl/image.texture_sample.Fragment.glsl @@ -18,74 +18,74 @@ void main() { vec4 a = vec4(0.0); vec2 tc = vec2(0.5); vec3 tc3_ = vec3(0.5); - vec4 _e8 = texture(_group_0_binding_0_fs, vec2(0.5, 0.0)); - vec4 _e9 = a; - a = (_e9 + _e8); - vec4 _e13 = texture(_group_0_binding_1_fs, vec2(tc)); - vec4 _e14 = a; - a = (_e14 + _e13); - vec4 _e18 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1)); - vec4 _e19 = a; - a = (_e19 + _e18); - vec4 _e23 = textureLod(_group_0_binding_1_fs, vec2(tc), 2.3); - vec4 _e24 = a; - a = (_e24 + _e23); - vec4 _e28 = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.3, ivec2(3, 1)); - vec4 _e29 = a; - a = (_e29 + _e28); - vec4 _e34 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 2.0); - vec4 _e35 = a; - a = (_e35 + _e34); - vec4 _e40 = texture(_group_0_binding_4_fs, vec3(tc, 0u)); - vec4 _e41 = a; - a = (_e41 + _e40); - vec4 _e46 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1)); - vec4 _e47 = a; - a = (_e47 + _e46); - vec4 _e52 = textureLod(_group_0_binding_4_fs, vec3(tc, 0u), 2.3); - vec4 _e53 = a; - a = (_e53 + _e52); - vec4 _e58 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0u), 2.3, ivec2(3, 1)); - vec4 _e59 = a; - a = (_e59 + _e58); - vec4 _e65 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1), 2.0); - vec4 _e66 = a; - a = (_e66 + _e65); - vec4 _e71 = texture(_group_0_binding_4_fs, vec3(tc, 0)); - vec4 _e72 = a; - a = (_e72 + _e71); - vec4 _e77 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1)); - vec4 _e78 = a; - a = (_e78 + _e77); - vec4 _e83 = textureLod(_group_0_binding_4_fs, vec3(tc, 0), 2.3); - vec4 _e84 = a; - a = (_e84 + _e83); - vec4 _e89 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0), 2.3, ivec2(3, 1)); - vec4 _e90 = a; - a = (_e90 + _e89); - vec4 _e96 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1), 2.0); - vec4 _e97 = a; - a = (_e97 + _e96); - vec4 _e102 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u)); - vec4 _e103 = a; - a = (_e103 + _e102); - vec4 _e108 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.3); - vec4 _e109 = a; - a = (_e109 + _e108); - vec4 _e115 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.0); - vec4 _e116 = a; - a = (_e116 + _e115); - vec4 _e121 = texture(_group_0_binding_6_fs, vec4(tc3_, 0)); - vec4 _e122 = a; - a = (_e122 + _e121); - vec4 _e127 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0), 2.3); - vec4 _e128 = a; - a = (_e128 + _e127); - vec4 _e134 = texture(_group_0_binding_6_fs, vec4(tc3_, 0), 2.0); - vec4 _e135 = a; - a = (_e135 + _e134); - vec4 _e137 = a; - _fs2p_location0 = _e137; + vec4 _e9 = texture(_group_0_binding_0_fs, vec2(tc.x, 0.0)); + vec4 _e10 = a; + a = (_e10 + _e9); + vec4 _e14 = texture(_group_0_binding_1_fs, vec2(tc)); + vec4 _e15 = a; + a = (_e15 + _e14); + vec4 _e19 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1)); + vec4 _e20 = a; + a = (_e20 + _e19); + vec4 _e24 = textureLod(_group_0_binding_1_fs, vec2(tc), 2.3); + vec4 _e25 = a; + a = (_e25 + _e24); + vec4 _e29 = textureLodOffset(_group_0_binding_1_fs, vec2(tc), 2.3, ivec2(3, 1)); + vec4 _e30 = a; + a = (_e30 + _e29); + vec4 _e35 = textureOffset(_group_0_binding_1_fs, vec2(tc), ivec2(3, 1), 2.0); + vec4 _e36 = a; + a = (_e36 + _e35); + vec4 _e41 = texture(_group_0_binding_4_fs, vec3(tc, 0u)); + vec4 _e42 = a; + a = (_e42 + _e41); + vec4 _e47 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1)); + vec4 _e48 = a; + a = (_e48 + _e47); + vec4 _e53 = textureLod(_group_0_binding_4_fs, vec3(tc, 0u), 2.3); + vec4 _e54 = a; + a = (_e54 + _e53); + vec4 _e59 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0u), 2.3, ivec2(3, 1)); + vec4 _e60 = a; + a = (_e60 + _e59); + vec4 _e66 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0u), ivec2(3, 1), 2.0); + vec4 _e67 = a; + a = (_e67 + _e66); + vec4 _e72 = texture(_group_0_binding_4_fs, vec3(tc, 0)); + vec4 _e73 = a; + a = (_e73 + _e72); + vec4 _e78 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1)); + vec4 _e79 = a; + a = (_e79 + _e78); + vec4 _e84 = textureLod(_group_0_binding_4_fs, vec3(tc, 0), 2.3); + vec4 _e85 = a; + a = (_e85 + _e84); + vec4 _e90 = textureLodOffset(_group_0_binding_4_fs, vec3(tc, 0), 2.3, ivec2(3, 1)); + vec4 _e91 = a; + a = (_e91 + _e90); + vec4 _e97 = textureOffset(_group_0_binding_4_fs, vec3(tc, 0), ivec2(3, 1), 2.0); + vec4 _e98 = a; + a = (_e98 + _e97); + vec4 _e103 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u)); + vec4 _e104 = a; + a = (_e104 + _e103); + vec4 _e109 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.3); + vec4 _e110 = a; + a = (_e110 + _e109); + vec4 _e116 = texture(_group_0_binding_6_fs, vec4(tc3_, 0u), 2.0); + vec4 _e117 = a; + a = (_e117 + _e116); + vec4 _e122 = texture(_group_0_binding_6_fs, vec4(tc3_, 0)); + vec4 _e123 = a; + a = (_e123 + _e122); + vec4 _e128 = textureLod(_group_0_binding_6_fs, vec4(tc3_, 0), 2.3); + vec4 _e129 = a; + a = (_e129 + _e128); + vec4 _e135 = texture(_group_0_binding_6_fs, vec4(tc3_, 0), 2.0); + vec4 _e136 = a; + a = (_e136 + _e135); + vec4 _e138 = a; + _fs2p_location0 = _e138; return; } diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index 6f44bdb07..a4c739d74 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -256,7 +256,7 @@ float4 foo_vert(uint vi : SV_VertexID) : SV_Position test_matrix_within_array_within_struct_accesses(); float4x3 _matrix = float4x3(asfloat(bar.Load3(0+0)), asfloat(bar.Load3(0+16)), asfloat(bar.Load3(0+32)), asfloat(bar.Load3(0+48))); uint2 arr_1[2] = Constructarray2_uint2_(asuint(bar.Load2(144+0)), asuint(bar.Load2(144+8))); - float b = asfloat(bar.Load(0+48+0)); + float b = asfloat(bar.Load(0+3u*16+0)); int a_1 = asint(bar.Load(0+(((NagaBufferLengthRW(bar) - 160) / 8) - 2u)*8+160)); int2 c = asint(qux.Load2(0)); const float _e33 = read_from_private(foo); diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index 46961977e..91b82ec56 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -8,18 +8,14 @@ RWByteAddressBuffer out2_ : register(u1); void swizzle_of_compose() { - int2 a = int2(1, 2); - int2 b = int2(3, 4); out_.Store4(0, asuint(int4(4, 3, 2, 1))); return; } void index_of_compose() { - int2 a_1 = int2(1, 2); - int2 b_1 = int2(3, 4); - int _expr7 = asint(out2_.Load(0)); - out2_.Store(0, asuint((_expr7 + 2))); + int _expr2 = asint(out2_.Load(0)); + out2_.Store(0, asuint((_expr2 + 2))); return; } diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl index 05825e18c..7fbd68b10 100644 --- a/tests/out/hlsl/image.hlsl +++ b/tests/out/hlsl/image.hlsl @@ -246,74 +246,74 @@ float4 texture_sample() : SV_Target0 float2 tc = (0.5).xx; float3 tc3_ = (0.5).xxx; - float4 _expr8 = image_1d.Sample(sampler_reg, 0.5); - float4 _expr9 = a; - a = (_expr9 + _expr8); - float4 _expr13 = image_2d.Sample(sampler_reg, tc); - float4 _expr14 = a; - a = (_expr14 + _expr13); - float4 _expr18 = image_2d.Sample(sampler_reg, tc, int2(int2(3, 1))); - float4 _expr19 = a; - a = (_expr19 + _expr18); - float4 _expr23 = image_2d.SampleLevel(sampler_reg, tc, 2.3); - float4 _expr24 = a; - a = (_expr24 + _expr23); - float4 _expr28 = image_2d.SampleLevel(sampler_reg, tc, 2.3, int2(int2(3, 1))); - float4 _expr29 = a; - a = (_expr29 + _expr28); - float4 _expr34 = image_2d.SampleBias(sampler_reg, tc, 2.0, int2(int2(3, 1))); - float4 _expr35 = a; - a = (_expr35 + _expr34); - float4 _expr40 = image_2d_array.Sample(sampler_reg, float3(tc, 0u)); - float4 _expr41 = a; - a = (_expr41 + _expr40); - float4 _expr46 = image_2d_array.Sample(sampler_reg, float3(tc, 0u), int2(int2(3, 1))); - float4 _expr47 = a; - a = (_expr47 + _expr46); - float4 _expr52 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3); - float4 _expr53 = a; - a = (_expr53 + _expr52); - float4 _expr58 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3, int2(int2(3, 1))); - float4 _expr59 = a; - a = (_expr59 + _expr58); - float4 _expr65 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0u), 2.0, int2(int2(3, 1))); - float4 _expr66 = a; - a = (_expr66 + _expr65); - float4 _expr71 = image_2d_array.Sample(sampler_reg, float3(tc, 0)); - float4 _expr72 = a; - a = (_expr72 + _expr71); - float4 _expr77 = image_2d_array.Sample(sampler_reg, float3(tc, 0), int2(int2(3, 1))); - float4 _expr78 = a; - a = (_expr78 + _expr77); - float4 _expr83 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3); - float4 _expr84 = a; - a = (_expr84 + _expr83); - float4 _expr89 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3, int2(int2(3, 1))); - float4 _expr90 = a; - a = (_expr90 + _expr89); - float4 _expr96 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0), 2.0, int2(int2(3, 1))); - float4 _expr97 = a; - a = (_expr97 + _expr96); - float4 _expr102 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0u)); - float4 _expr103 = a; - a = (_expr103 + _expr102); - float4 _expr108 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0u), 2.3); - float4 _expr109 = a; - a = (_expr109 + _expr108); - float4 _expr115 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0u), 2.0); - float4 _expr116 = a; - a = (_expr116 + _expr115); - float4 _expr121 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0)); - float4 _expr122 = a; - a = (_expr122 + _expr121); - float4 _expr127 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0), 2.3); - float4 _expr128 = a; - a = (_expr128 + _expr127); - float4 _expr134 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0), 2.0); - float4 _expr135 = a; - a = (_expr135 + _expr134); - float4 _expr137 = a; - return _expr137; + float4 _expr9 = image_1d.Sample(sampler_reg, tc.x); + float4 _expr10 = a; + a = (_expr10 + _expr9); + float4 _expr14 = image_2d.Sample(sampler_reg, tc); + float4 _expr15 = a; + a = (_expr15 + _expr14); + float4 _expr19 = image_2d.Sample(sampler_reg, tc, int2(int2(3, 1))); + float4 _expr20 = a; + a = (_expr20 + _expr19); + float4 _expr24 = image_2d.SampleLevel(sampler_reg, tc, 2.3); + float4 _expr25 = a; + a = (_expr25 + _expr24); + float4 _expr29 = image_2d.SampleLevel(sampler_reg, tc, 2.3, int2(int2(3, 1))); + float4 _expr30 = a; + a = (_expr30 + _expr29); + float4 _expr35 = image_2d.SampleBias(sampler_reg, tc, 2.0, int2(int2(3, 1))); + float4 _expr36 = a; + a = (_expr36 + _expr35); + float4 _expr41 = image_2d_array.Sample(sampler_reg, float3(tc, 0u)); + float4 _expr42 = a; + a = (_expr42 + _expr41); + float4 _expr47 = image_2d_array.Sample(sampler_reg, float3(tc, 0u), int2(int2(3, 1))); + float4 _expr48 = a; + a = (_expr48 + _expr47); + float4 _expr53 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3); + float4 _expr54 = a; + a = (_expr54 + _expr53); + float4 _expr59 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0u), 2.3, int2(int2(3, 1))); + float4 _expr60 = a; + a = (_expr60 + _expr59); + float4 _expr66 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0u), 2.0, int2(int2(3, 1))); + float4 _expr67 = a; + a = (_expr67 + _expr66); + float4 _expr72 = image_2d_array.Sample(sampler_reg, float3(tc, 0)); + float4 _expr73 = a; + a = (_expr73 + _expr72); + float4 _expr78 = image_2d_array.Sample(sampler_reg, float3(tc, 0), int2(int2(3, 1))); + float4 _expr79 = a; + a = (_expr79 + _expr78); + float4 _expr84 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3); + float4 _expr85 = a; + a = (_expr85 + _expr84); + float4 _expr90 = image_2d_array.SampleLevel(sampler_reg, float3(tc, 0), 2.3, int2(int2(3, 1))); + float4 _expr91 = a; + a = (_expr91 + _expr90); + float4 _expr97 = image_2d_array.SampleBias(sampler_reg, float3(tc, 0), 2.0, int2(int2(3, 1))); + float4 _expr98 = a; + a = (_expr98 + _expr97); + float4 _expr103 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0u)); + float4 _expr104 = a; + a = (_expr104 + _expr103); + float4 _expr109 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0u), 2.3); + float4 _expr110 = a; + a = (_expr110 + _expr109); + float4 _expr116 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0u), 2.0); + float4 _expr117 = a; + a = (_expr117 + _expr116); + float4 _expr122 = image_cube_array.Sample(sampler_reg, float4(tc3_, 0)); + float4 _expr123 = a; + a = (_expr123 + _expr122); + float4 _expr128 = image_cube_array.SampleLevel(sampler_reg, float4(tc3_, 0), 2.3); + float4 _expr129 = a; + a = (_expr129 + _expr128); + float4 _expr135 = image_cube_array.SampleBias(sampler_reg, float4(tc3_, 0), 2.0); + float4 _expr136 = a; + a = (_expr136 + _expr135); + float4 _expr138 = a; + return _expr138; } float texture_sample_comparison() : SV_Target0 diff --git a/tests/out/ir/access.compact.ron b/tests/out/ir/access.compact.ron index 1c0220141..f24f830af 100644 --- a/tests/out/ir/access.compact.ron +++ b/tests/out/ir/access.compact.ron @@ -1697,9 +1697,9 @@ base: 13, index: 0, ), - AccessIndex( + Access( base: 14, - index: 3, + index: 12, ), AccessIndex( base: 15, diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index fcdd3b8b7..9a1820fc8 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -1792,9 +1792,9 @@ base: 13, index: 0, ), - AccessIndex( + Access( base: 14, - index: 3, + index: 12, ), AccessIndex( base: 15, diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 3d57ebd7c..7c901c35a 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -180,7 +180,7 @@ vertex foo_vertOutput foo_vert( test_matrix_within_array_within_struct_accesses(nested_mat_cx2_); metal::float4x3 _matrix = bar._matrix; type_9 arr_1 = bar.arr; - float b = bar._matrix[3].x; + float b = bar._matrix[3u].x; int a_1 = bar.data[(1 + (_buffer_sizes.size1 - 160 - 8) / 8) - 2u].value; metal::int2 c = qux; float _e33 = read_from_private(foo); diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 135b4ec10..5cbc23a00 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -12,8 +12,6 @@ constant int TEST_CONSTANT_ALIAS_ADDITION = 8; void swizzle_of_compose( device metal::int4& out ) { - metal::int2 a = metal::int2(1, 2); - metal::int2 b = metal::int2(3, 4); out = metal::int4(4, 3, 2, 1); return; } @@ -21,10 +19,8 @@ void swizzle_of_compose( void index_of_compose( device int& out2_ ) { - metal::int2 a_1 = metal::int2(1, 2); - metal::int2 b_1 = metal::int2(3, 4); - int _e7 = out2_; - out2_ = _e7 + 2; + int _e2 = out2_; + out2_ = _e2 + 2; return; } diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index 1612314ec..e390c2e0f 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -119,74 +119,74 @@ fragment texture_sampleOutput texture_sample( metal::float4 a = {}; metal::float2 tc = metal::float2(0.5); metal::float3 tc3_ = metal::float3(0.5); - metal::float4 _e8 = image_1d.sample(sampler_reg, 0.5); - metal::float4 _e9 = a; - a = _e9 + _e8; - metal::float4 _e13 = image_2d.sample(sampler_reg, tc); - metal::float4 _e14 = a; - a = _e14 + _e13; - metal::float4 _e18 = image_2d.sample(sampler_reg, tc, metal::int2(3, 1)); - metal::float4 _e19 = a; - a = _e19 + _e18; - metal::float4 _e23 = image_2d.sample(sampler_reg, tc, metal::level(2.3)); - metal::float4 _e24 = a; - a = _e24 + _e23; - metal::float4 _e28 = image_2d.sample(sampler_reg, tc, metal::level(2.3), metal::int2(3, 1)); - metal::float4 _e29 = a; - a = _e29 + _e28; - metal::float4 _e34 = image_2d.sample(sampler_reg, tc, metal::bias(2.0), metal::int2(3, 1)); - metal::float4 _e35 = a; - a = _e35 + _e34; - metal::float4 _e40 = image_2d_array.sample(sampler_reg, tc, 0u); - metal::float4 _e41 = a; - a = _e41 + _e40; - metal::float4 _e46 = image_2d_array.sample(sampler_reg, tc, 0u, metal::int2(3, 1)); - metal::float4 _e47 = a; - a = _e47 + _e46; - metal::float4 _e52 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3)); - metal::float4 _e53 = a; - a = _e53 + _e52; - metal::float4 _e58 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3), metal::int2(3, 1)); - metal::float4 _e59 = a; - a = _e59 + _e58; - metal::float4 _e65 = image_2d_array.sample(sampler_reg, tc, 0u, metal::bias(2.0), metal::int2(3, 1)); - metal::float4 _e66 = a; - a = _e66 + _e65; - metal::float4 _e71 = image_2d_array.sample(sampler_reg, tc, 0); - metal::float4 _e72 = a; - a = _e72 + _e71; - metal::float4 _e77 = image_2d_array.sample(sampler_reg, tc, 0, metal::int2(3, 1)); - metal::float4 _e78 = a; - a = _e78 + _e77; - metal::float4 _e83 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3)); - metal::float4 _e84 = a; - a = _e84 + _e83; - metal::float4 _e89 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3), metal::int2(3, 1)); - metal::float4 _e90 = a; - a = _e90 + _e89; - metal::float4 _e96 = image_2d_array.sample(sampler_reg, tc, 0, metal::bias(2.0), metal::int2(3, 1)); - metal::float4 _e97 = a; - a = _e97 + _e96; - metal::float4 _e102 = image_cube_array.sample(sampler_reg, tc3_, 0u); - metal::float4 _e103 = a; - a = _e103 + _e102; - metal::float4 _e108 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::level(2.3)); - metal::float4 _e109 = a; - a = _e109 + _e108; - metal::float4 _e115 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::bias(2.0)); - metal::float4 _e116 = a; - a = _e116 + _e115; - metal::float4 _e121 = image_cube_array.sample(sampler_reg, tc3_, 0); - metal::float4 _e122 = a; - a = _e122 + _e121; - metal::float4 _e127 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::level(2.3)); - metal::float4 _e128 = a; - a = _e128 + _e127; - metal::float4 _e134 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::bias(2.0)); - metal::float4 _e135 = a; - a = _e135 + _e134; - metal::float4 _e137 = a; - return texture_sampleOutput { _e137 }; + metal::float4 _e9 = image_1d.sample(sampler_reg, tc.x); + metal::float4 _e10 = a; + a = _e10 + _e9; + metal::float4 _e14 = image_2d.sample(sampler_reg, tc); + metal::float4 _e15 = a; + a = _e15 + _e14; + metal::float4 _e19 = image_2d.sample(sampler_reg, tc, metal::int2(3, 1)); + metal::float4 _e20 = a; + a = _e20 + _e19; + metal::float4 _e24 = image_2d.sample(sampler_reg, tc, metal::level(2.3)); + metal::float4 _e25 = a; + a = _e25 + _e24; + metal::float4 _e29 = image_2d.sample(sampler_reg, tc, metal::level(2.3), metal::int2(3, 1)); + metal::float4 _e30 = a; + a = _e30 + _e29; + metal::float4 _e35 = image_2d.sample(sampler_reg, tc, metal::bias(2.0), metal::int2(3, 1)); + metal::float4 _e36 = a; + a = _e36 + _e35; + metal::float4 _e41 = image_2d_array.sample(sampler_reg, tc, 0u); + metal::float4 _e42 = a; + a = _e42 + _e41; + metal::float4 _e47 = image_2d_array.sample(sampler_reg, tc, 0u, metal::int2(3, 1)); + metal::float4 _e48 = a; + a = _e48 + _e47; + metal::float4 _e53 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3)); + metal::float4 _e54 = a; + a = _e54 + _e53; + metal::float4 _e59 = image_2d_array.sample(sampler_reg, tc, 0u, metal::level(2.3), metal::int2(3, 1)); + metal::float4 _e60 = a; + a = _e60 + _e59; + metal::float4 _e66 = image_2d_array.sample(sampler_reg, tc, 0u, metal::bias(2.0), metal::int2(3, 1)); + metal::float4 _e67 = a; + a = _e67 + _e66; + metal::float4 _e72 = image_2d_array.sample(sampler_reg, tc, 0); + metal::float4 _e73 = a; + a = _e73 + _e72; + metal::float4 _e78 = image_2d_array.sample(sampler_reg, tc, 0, metal::int2(3, 1)); + metal::float4 _e79 = a; + a = _e79 + _e78; + metal::float4 _e84 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3)); + metal::float4 _e85 = a; + a = _e85 + _e84; + metal::float4 _e90 = image_2d_array.sample(sampler_reg, tc, 0, metal::level(2.3), metal::int2(3, 1)); + metal::float4 _e91 = a; + a = _e91 + _e90; + metal::float4 _e97 = image_2d_array.sample(sampler_reg, tc, 0, metal::bias(2.0), metal::int2(3, 1)); + metal::float4 _e98 = a; + a = _e98 + _e97; + metal::float4 _e103 = image_cube_array.sample(sampler_reg, tc3_, 0u); + metal::float4 _e104 = a; + a = _e104 + _e103; + metal::float4 _e109 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::level(2.3)); + metal::float4 _e110 = a; + a = _e110 + _e109; + metal::float4 _e116 = image_cube_array.sample(sampler_reg, tc3_, 0u, metal::bias(2.0)); + metal::float4 _e117 = a; + a = _e117 + _e116; + metal::float4 _e122 = image_cube_array.sample(sampler_reg, tc3_, 0); + metal::float4 _e123 = a; + a = _e123 + _e122; + metal::float4 _e128 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::level(2.3)); + metal::float4 _e129 = a; + a = _e129 + _e128; + metal::float4 _e135 = image_cube_array.sample(sampler_reg, tc3_, 0, metal::bias(2.0)); + metal::float4 _e136 = a; + a = _e136 + _e135; + metal::float4 _e138 = a; + return texture_sampleOutput { _e138 }; } diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index 0b5c91317..1f7bf5c8c 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,130 +1,127 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 85 +; Bound: 82 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %75 "main" -OpExecutionMode %75 LocalSize 1 1 1 -OpDecorate %8 DescriptorSet 0 -OpDecorate %8 Binding 0 -OpDecorate %9 Block -OpMemberDecorate %9 0 Offset 0 -OpDecorate %11 DescriptorSet 0 -OpDecorate %11 Binding 1 -OpDecorate %12 Block -OpMemberDecorate %12 0 Offset 0 +OpEntryPoint GLCompute %72 "main" +OpExecutionMode %72 LocalSize 1 1 1 +OpDecorate %7 DescriptorSet 0 +OpDecorate %7 Binding 0 +OpDecorate %8 Block +OpMemberDecorate %8 0 Offset 0 +OpDecorate %10 DescriptorSet 0 +OpDecorate %10 Binding 1 +OpDecorate %11 Block +OpMemberDecorate %11 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 4 -%5 = OpTypeVector %4 2 -%6 = OpConstant %4 4 -%7 = OpConstant %4 8 -%9 = OpTypeStruct %3 -%10 = OpTypePointer StorageBuffer %9 -%8 = OpVariable %10 StorageBuffer -%12 = OpTypeStruct %4 -%13 = OpTypePointer StorageBuffer %12 -%11 = OpVariable %13 StorageBuffer -%16 = OpTypeFunction %2 -%17 = OpTypePointer StorageBuffer %3 -%19 = OpTypeInt 32 0 -%18 = OpConstant %19 0 -%21 = OpConstant %4 1 -%22 = OpConstant %4 2 -%23 = OpConstantComposite %5 %21 %22 -%24 = OpConstant %4 3 -%25 = OpConstantComposite %5 %24 %6 -%26 = OpConstantComposite %3 %6 %24 %22 %21 -%30 = OpTypePointer StorageBuffer %4 -%38 = OpConstant %4 6 -%45 = OpConstant %4 30 -%46 = OpConstant %4 70 -%48 = OpTypePointer Function %4 -%50 = OpConstantNull %4 -%52 = OpConstantNull %4 -%67 = OpConstant %4 -4 -%68 = OpConstantComposite %3 %67 %67 %67 %67 -%15 = OpFunction %2 None %16 -%14 = OpLabel -%20 = OpAccessChain %17 %8 %18 -OpBranch %27 -%27 = OpLabel -OpStore %20 %26 +%5 = OpConstant %4 4 +%6 = OpConstant %4 8 +%8 = OpTypeStruct %3 +%9 = OpTypePointer StorageBuffer %8 +%7 = OpVariable %9 StorageBuffer +%11 = OpTypeStruct %4 +%12 = OpTypePointer StorageBuffer %11 +%10 = OpVariable %12 StorageBuffer +%15 = OpTypeFunction %2 +%16 = OpTypePointer StorageBuffer %3 +%18 = OpTypeInt 32 0 +%17 = OpConstant %18 0 +%20 = OpConstant %4 1 +%21 = OpConstant %4 2 +%22 = OpConstant %4 3 +%23 = OpConstantComposite %3 %5 %22 %21 %20 +%27 = OpTypePointer StorageBuffer %4 +%35 = OpConstant %4 6 +%42 = OpConstant %4 30 +%43 = OpConstant %4 70 +%45 = OpTypePointer Function %4 +%47 = OpConstantNull %4 +%49 = OpConstantNull %4 +%64 = OpConstant %4 -4 +%65 = OpConstantComposite %3 %64 %64 %64 %64 +%14 = OpFunction %2 None %15 +%13 = OpLabel +%19 = OpAccessChain %16 %7 %17 +OpBranch %24 +%24 = OpLabel +OpStore %19 %23 OpReturn OpFunctionEnd -%29 = OpFunction %2 None %16 -%28 = OpLabel -%31 = OpAccessChain %30 %11 %18 -OpBranch %32 +%26 = OpFunction %2 None %15 +%25 = OpLabel +%28 = OpAccessChain %27 %10 %17 +OpBranch %29 +%29 = OpLabel +%30 = OpLoad %4 %28 +%31 = OpIAdd %4 %30 %21 +OpStore %28 %31 +OpReturn +OpFunctionEnd +%33 = OpFunction %2 None %15 %32 = OpLabel -%33 = OpLoad %4 %31 -%34 = OpIAdd %4 %33 %22 -OpStore %31 %34 +%34 = OpAccessChain %27 %10 %17 +OpBranch %36 +%36 = OpLabel +%37 = OpLoad %4 %34 +%38 = OpIAdd %4 %37 %35 +OpStore %34 %38 OpReturn OpFunctionEnd -%36 = OpFunction %2 None %16 -%35 = OpLabel -%37 = OpAccessChain %30 %11 %18 -OpBranch %39 +%40 = OpFunction %2 None %15 %39 = OpLabel -%40 = OpLoad %4 %37 -%41 = OpIAdd %4 %40 %38 -OpStore %37 %41 +%46 = OpVariable %45 Function %47 +%50 = OpVariable %45 Function %43 +%44 = OpVariable %45 Function %42 +%48 = OpVariable %45 Function %49 +%41 = OpAccessChain %16 %7 %17 +OpBranch %51 +%51 = OpLabel +%52 = OpLoad %4 %44 +OpStore %46 %52 +%53 = OpLoad %4 %46 +OpStore %48 %53 +%54 = OpLoad %4 %44 +%55 = OpLoad %4 %46 +%56 = OpLoad %4 %48 +%57 = OpLoad %4 %50 +%58 = OpCompositeConstruct %3 %54 %55 %56 %57 +%59 = OpLoad %3 %41 +%60 = OpIAdd %3 %59 %58 +OpStore %41 %60 OpReturn OpFunctionEnd -%43 = OpFunction %2 None %16 -%42 = OpLabel -%49 = OpVariable %48 Function %50 -%53 = OpVariable %48 Function %46 -%47 = OpVariable %48 Function %45 -%51 = OpVariable %48 Function %52 -%44 = OpAccessChain %17 %8 %18 -OpBranch %54 -%54 = OpLabel -%55 = OpLoad %4 %47 -OpStore %49 %55 -%56 = OpLoad %4 %49 -OpStore %51 %56 -%57 = OpLoad %4 %47 -%58 = OpLoad %4 %49 -%59 = OpLoad %4 %51 -%60 = OpLoad %4 %53 -%61 = OpCompositeConstruct %3 %57 %58 %59 %60 -%62 = OpLoad %3 %44 -%63 = OpIAdd %3 %62 %61 -OpStore %44 %63 +%62 = OpFunction %2 None %15 +%61 = OpLabel +%63 = OpAccessChain %16 %7 %17 +OpBranch %66 +%66 = OpLabel +OpStore %63 %65 OpReturn OpFunctionEnd -%65 = OpFunction %2 None %16 -%64 = OpLabel -%66 = OpAccessChain %17 %8 %18 -OpBranch %69 -%69 = OpLabel -OpStore %66 %68 -OpReturn -OpFunctionEnd -%71 = OpFunction %2 None %16 +%68 = OpFunction %2 None %15 +%67 = OpLabel +%69 = OpAccessChain %16 %7 %17 +OpBranch %70 %70 = OpLabel -%72 = OpAccessChain %17 %8 %18 -OpBranch %73 -%73 = OpLabel -OpStore %72 %68 +OpStore %69 %65 OpReturn OpFunctionEnd -%75 = OpFunction %2 None %16 -%74 = OpLabel -%76 = OpAccessChain %17 %8 %18 -%77 = OpAccessChain %30 %11 %18 -OpBranch %78 -%78 = OpLabel -%79 = OpFunctionCall %2 %15 -%80 = OpFunctionCall %2 %29 -%81 = OpFunctionCall %2 %36 -%82 = OpFunctionCall %2 %43 -%83 = OpFunctionCall %2 %65 -%84 = OpFunctionCall %2 %71 +%72 = OpFunction %2 None %15 +%71 = OpLabel +%73 = OpAccessChain %16 %7 %17 +%74 = OpAccessChain %27 %10 %17 +OpBranch %75 +%75 = OpLabel +%76 = OpFunctionCall %2 %14 +%77 = OpFunctionCall %2 %26 +%78 = OpFunctionCall %2 %33 +%79 = OpFunctionCall %2 %40 +%80 = OpFunctionCall %2 %62 +%81 = OpFunctionCall %2 %68 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/debug-symbol-terrain.spvasm b/tests/out/spv/debug-symbol-terrain.spvasm index 30ecd2f8f..36fae9d60 100644 --- a/tests/out/spv/debug-symbol-terrain.spvasm +++ b/tests/out/spv/debug-symbol-terrain.spvasm @@ -360,10 +360,10 @@ OpName %52 "x" OpName %53 "permute3" OpName %66 "v" OpName %67 "snoise2" -OpName %90 "i" -OpName %93 "i1" -OpName %95 "x12" -OpName %98 "m" +OpName %86 "i" +OpName %89 "i1" +OpName %91 "x12" +OpName %94 "m" OpName %203 "p" OpName %204 "fbm" OpName %209 "x" @@ -547,34 +547,30 @@ OpDecorate %582 Location 0 %71 = OpConstant %5 -0.57735026 %72 = OpConstant %5 0.024390243 %73 = OpConstantComposite %7 %69 %70 %71 %72 -%74 = OpConstantComposite %6 %70 %70 -%75 = OpConstantComposite %6 %69 %69 -%76 = OpConstant %5 0.0 -%77 = OpConstantComposite %6 %56 %76 -%78 = OpConstantComposite %6 %76 %56 -%79 = OpConstantComposite %7 %69 %69 %71 %71 -%80 = OpConstantComposite %6 %58 %58 -%81 = OpConstant %5 0.5 -%82 = OpConstantComposite %4 %81 %81 %81 -%83 = OpConstantComposite %4 %76 %76 %76 -%84 = OpConstant %5 2.0 -%85 = OpConstantComposite %4 %72 %72 %72 -%86 = OpConstant %5 1.7928429 -%87 = OpConstant %5 0.85373473 -%88 = OpConstantComposite %4 %86 %86 %86 -%89 = OpConstant %5 130.0 -%91 = OpTypePointer Function %6 -%92 = OpConstantNull %6 -%94 = OpConstantNull %6 -%96 = OpTypePointer Function %7 -%97 = OpConstantNull %7 -%99 = OpTypePointer Function %4 -%100 = OpConstantNull %4 -%114 = OpTypeBool -%117 = OpTypeVector %114 2 -%126 = OpTypePointer Function %5 -%127 = OpConstant %8 1 -%136 = OpConstant %8 0 +%74 = OpConstant %5 0.0 +%75 = OpConstantComposite %6 %56 %74 +%76 = OpConstantComposite %6 %74 %56 +%77 = OpConstantComposite %6 %58 %58 +%78 = OpConstant %5 0.5 +%79 = OpConstantComposite %4 %78 %78 %78 +%80 = OpConstantComposite %4 %74 %74 %74 +%81 = OpConstant %5 2.0 +%82 = OpConstant %5 1.7928429 +%83 = OpConstant %5 0.85373473 +%84 = OpConstantComposite %4 %82 %82 %82 +%85 = OpConstant %5 130.0 +%87 = OpTypePointer Function %6 +%88 = OpConstantNull %6 +%90 = OpConstantNull %6 +%92 = OpTypePointer Function %7 +%93 = OpConstantNull %7 +%95 = OpTypePointer Function %4 +%96 = OpConstantNull %4 +%112 = OpTypeBool +%115 = OpTypeVector %112 2 +%125 = OpTypePointer Function %5 +%126 = OpConstant %8 1 +%135 = OpConstant %8 0 %205 = OpConstant %8 5 %206 = OpConstant %5 0.01 %207 = OpConstant %5 100.0 @@ -585,11 +581,11 @@ OpDecorate %582 Location 0 %258 = OpTypeFunction %4 %6 %6 %271 = OpTypeFunction %14 %6 %6 %272 = OpConstant %5 0.1 -%273 = OpConstantComposite %6 %272 %76 -%274 = OpConstantComposite %6 %76 %272 +%273 = OpConstantComposite %6 %272 %74 +%274 = OpConstantComposite %6 %74 %272 %275 = OpConstant %5 -0.1 -%276 = OpConstantComposite %6 %275 %76 -%277 = OpConstantComposite %6 %76 %275 +%276 = OpConstantComposite %6 %275 %74 +%277 = OpConstantComposite %6 %74 %275 %304 = OpTypeFunction %6 %8 %10 %11 %321 = OpTypeFunction %4 %6 %322 = OpConstant %5 23.0 @@ -650,7 +646,7 @@ OpDecorate %582 Location 0 %585 = OpTypePointer Uniform %25 %587 = OpConstantComposite %4 %272 %272 %272 %588 = OpConstant %5 0.7 -%589 = OpConstantComposite %4 %81 %272 %588 +%589 = OpConstantComposite %4 %78 %272 %588 %590 = OpConstant %5 0.2 %591 = OpConstantComposite %4 %590 %590 %590 %593 = OpConstantNull %4 @@ -673,163 +669,167 @@ OpFunctionEnd %67 = OpFunction %5 None %68 %66 = OpFunctionParameter %6 %65 = OpLabel -%93 = OpVariable %91 Function %94 -%98 = OpVariable %99 Function %100 -%90 = OpVariable %91 Function %92 -%95 = OpVariable %96 Function %97 -OpBranch %101 -%101 = OpLabel +%89 = OpVariable %87 Function %90 +%94 = OpVariable %95 Function %96 +%86 = OpVariable %87 Function %88 +%91 = OpVariable %92 Function %93 +OpBranch %97 +%97 = OpLabel OpLine %3 13 13 OpLine %3 14 24 -%102 = OpDot %5 %66 %74 -%103 = OpCompositeConstruct %6 %102 %102 -%104 = OpFAdd %6 %66 %103 -%105 = OpExtInst %6 %1 Floor %104 +%98 = OpVectorShuffle %6 %73 %73 1 1 +%99 = OpDot %5 %66 %98 +%100 = OpCompositeConstruct %6 %99 %99 +%101 = OpFAdd %6 %66 %100 +%102 = OpExtInst %6 %1 Floor %101 OpLine %3 14 5 -OpStore %90 %105 +OpStore %86 %102 OpLine %3 15 14 -%106 = OpLoad %6 %90 -%107 = OpFSub %6 %66 %106 -%108 = OpLoad %6 %90 -%109 = OpDot %5 %108 %75 -%110 = OpCompositeConstruct %6 %109 %109 -%111 = OpFAdd %6 %107 %110 +%103 = OpLoad %6 %86 +%104 = OpFSub %6 %66 %103 +%105 = OpLoad %6 %86 +%106 = OpVectorShuffle %6 %73 %73 0 0 +%107 = OpDot %5 %105 %106 +%108 = OpCompositeConstruct %6 %107 %107 +%109 = OpFAdd %6 %104 %108 OpLine %3 17 32 OpLine %3 17 25 -%112 = OpCompositeExtract %5 %111 0 -%113 = OpCompositeExtract %5 %111 1 -%115 = OpFOrdLessThan %114 %112 %113 -%118 = OpCompositeConstruct %117 %115 %115 -%116 = OpSelect %6 %118 %78 %77 +%110 = OpCompositeExtract %5 %109 0 +%111 = OpCompositeExtract %5 %109 1 +%113 = OpFOrdLessThan %112 %110 %111 +%116 = OpCompositeConstruct %115 %113 %113 +%114 = OpSelect %6 %116 %76 %75 OpLine %3 17 5 -OpStore %93 %116 +OpStore %89 %114 OpLine %3 18 26 -%119 = OpVectorShuffle %7 %111 %111 0 1 0 1 -%120 = OpFAdd %7 %119 %79 -%121 = OpLoad %6 %93 +%117 = OpVectorShuffle %7 %109 %109 0 1 0 1 +%118 = OpVectorShuffle %7 %73 %73 0 0 2 2 +%119 = OpFAdd %7 %117 %118 +%120 = OpLoad %6 %89 OpLine %3 18 26 -%122 = OpCompositeConstruct %7 %121 %76 %76 -%123 = OpFSub %7 %120 %122 +%121 = OpCompositeConstruct %7 %120 %74 %74 +%122 = OpFSub %7 %119 %121 OpLine %3 18 5 -OpStore %95 %123 +OpStore %91 %122 OpLine %3 1 1 -%124 = OpLoad %6 %90 +%123 = OpLoad %6 %86 OpLine %3 19 9 -%125 = OpFRem %6 %124 %80 +%124 = OpFRem %6 %123 %77 OpLine %3 19 5 -OpStore %90 %125 +OpStore %86 %124 OpLine %3 20 31 -%128 = OpAccessChain %126 %90 %127 -%129 = OpLoad %5 %128 +%127 = OpAccessChain %125 %86 %126 +%128 = OpLoad %5 %127 OpLine %3 20 51 -%130 = OpAccessChain %126 %93 %127 -%131 = OpLoad %5 %130 +%129 = OpAccessChain %125 %89 %126 +%130 = OpLoad %5 %129 OpLine %3 20 31 -%132 = OpCompositeConstruct %4 %76 %131 %56 -%133 = OpCompositeConstruct %4 %129 %129 %129 -%134 = OpFAdd %4 %133 %132 +%131 = OpCompositeConstruct %4 %74 %130 %56 +%132 = OpCompositeConstruct %4 %128 %128 %128 +%133 = OpFAdd %4 %132 %131 OpLine %3 20 22 -%135 = OpFunctionCall %4 %53 %134 +%134 = OpFunctionCall %4 %53 %133 OpLine %3 20 22 -%137 = OpAccessChain %126 %90 %136 -%138 = OpLoad %5 %137 -%139 = OpCompositeConstruct %4 %138 %138 %138 -%140 = OpFAdd %4 %135 %139 +%136 = OpAccessChain %125 %86 %135 +%137 = OpLoad %5 %136 +%138 = OpCompositeConstruct %4 %137 %137 %137 +%139 = OpFAdd %4 %134 %138 OpLine %3 20 84 -%141 = OpAccessChain %126 %93 %136 -%142 = OpLoad %5 %141 +%140 = OpAccessChain %125 %89 %135 +%141 = OpLoad %5 %140 OpLine %3 20 22 -%143 = OpCompositeConstruct %4 %76 %142 %56 -%144 = OpFAdd %4 %140 %143 +%142 = OpCompositeConstruct %4 %74 %141 %56 +%143 = OpFAdd %4 %139 %142 OpLine %3 20 13 -%145 = OpFunctionCall %4 %53 %144 +%144 = OpFunctionCall %4 %53 %143 OpLine %3 21 28 -%146 = OpDot %5 %111 %111 -%147 = OpLoad %7 %95 -%148 = OpVectorShuffle %6 %147 %147 0 1 -%149 = OpLoad %7 %95 -%150 = OpVectorShuffle %6 %149 %149 0 1 -%151 = OpDot %5 %148 %150 -%152 = OpLoad %7 %95 -%153 = OpVectorShuffle %6 %152 %152 2 3 -%154 = OpLoad %7 %95 -%155 = OpVectorShuffle %6 %154 %154 2 3 -%156 = OpDot %5 %153 %155 -%157 = OpCompositeConstruct %4 %146 %151 %156 -%158 = OpFSub %4 %82 %157 +%145 = OpDot %5 %109 %109 +%146 = OpLoad %7 %91 +%147 = OpVectorShuffle %6 %146 %146 0 1 +%148 = OpLoad %7 %91 +%149 = OpVectorShuffle %6 %148 %148 0 1 +%150 = OpDot %5 %147 %149 +%151 = OpLoad %7 %91 +%152 = OpVectorShuffle %6 %151 %151 2 3 +%153 = OpLoad %7 %91 +%154 = OpVectorShuffle %6 %153 %153 2 3 +%155 = OpDot %5 %152 %154 +%156 = OpCompositeConstruct %4 %145 %150 %155 +%157 = OpFSub %4 %79 %156 OpLine %3 21 24 -%159 = OpExtInst %4 %1 FMax %158 %83 +%158 = OpExtInst %4 %1 FMax %157 %80 OpLine %3 21 5 -OpStore %98 %159 +OpStore %94 %158 OpLine %3 22 9 -%160 = OpLoad %4 %98 -%161 = OpLoad %4 %98 -%162 = OpFMul %4 %160 %161 +%159 = OpLoad %4 %94 +%160 = OpLoad %4 %94 +%161 = OpFMul %4 %159 %160 OpLine %3 22 5 -OpStore %98 %162 +OpStore %94 %161 OpLine %3 23 9 -%163 = OpLoad %4 %98 -%164 = OpLoad %4 %98 -%165 = OpFMul %4 %163 %164 +%162 = OpLoad %4 %94 +%163 = OpLoad %4 %94 +%164 = OpFMul %4 %162 %163 OpLine %3 23 5 -OpStore %98 %165 +OpStore %94 %164 OpLine %3 24 13 -%166 = OpFMul %4 %145 %85 +%165 = OpVectorShuffle %4 %73 %73 3 3 3 +%166 = OpFMul %4 %144 %165 %167 = OpExtInst %4 %1 Fract %166 -%168 = OpVectorTimesScalar %4 %167 %84 +%168 = OpVectorTimesScalar %4 %167 %81 OpLine %3 24 13 %169 = OpFSub %4 %168 %57 OpLine %3 25 13 %170 = OpExtInst %4 %1 FAbs %169 OpLine %3 25 13 -%171 = OpFSub %4 %170 %82 +%171 = OpFSub %4 %170 %79 OpLine %3 26 14 -%172 = OpFAdd %4 %169 %82 +%172 = OpFAdd %4 %169 %79 %173 = OpExtInst %4 %1 Floor %172 OpLine %3 27 14 %174 = OpFSub %4 %169 %173 OpLine %3 1 1 -%175 = OpLoad %4 %98 +%175 = OpLoad %4 %94 OpLine %3 28 9 %176 = OpFMul %4 %174 %174 %177 = OpFMul %4 %171 %171 %178 = OpFAdd %4 %176 %177 -%179 = OpVectorTimesScalar %4 %178 %87 -%180 = OpFSub %4 %88 %179 +%179 = OpVectorTimesScalar %4 %178 %83 +%180 = OpFSub %4 %84 %179 %181 = OpFMul %4 %175 %180 OpLine %3 28 5 -OpStore %98 %181 +OpStore %94 %181 OpLine %3 29 13 %182 = OpCompositeExtract %5 %174 0 -%183 = OpCompositeExtract %5 %111 0 +%183 = OpCompositeExtract %5 %109 0 %184 = OpFMul %5 %182 %183 %185 = OpCompositeExtract %5 %171 0 -%186 = OpCompositeExtract %5 %111 1 +%186 = OpCompositeExtract %5 %109 1 %187 = OpFMul %5 %185 %186 %188 = OpFAdd %5 %184 %187 %189 = OpVectorShuffle %6 %174 %174 1 2 -%190 = OpLoad %7 %95 +%190 = OpLoad %7 %91 %191 = OpVectorShuffle %6 %190 %190 0 2 %192 = OpFMul %6 %189 %191 %193 = OpVectorShuffle %6 %171 %171 1 2 -%194 = OpLoad %7 %95 +%194 = OpLoad %7 %91 %195 = OpVectorShuffle %6 %194 %194 1 3 %196 = OpFMul %6 %193 %195 %197 = OpFAdd %6 %192 %196 %198 = OpCompositeConstruct %4 %188 %197 OpLine %3 30 12 -%199 = OpLoad %4 %98 +%199 = OpLoad %4 %94 %200 = OpDot %5 %199 %198 -%201 = OpFMul %5 %89 %200 +%201 = OpFMul %5 %85 %200 OpReturnValue %201 OpFunctionEnd %204 = OpFunction %5 None %68 %203 = OpFunctionParameter %6 %202 = OpLabel -%211 = OpVariable %212 Function %76 -%214 = OpVariable %215 Function %136 -%209 = OpVariable %91 Function %210 -%213 = OpVariable %212 Function %81 +%211 = OpVariable %212 Function %74 +%214 = OpVariable %215 Function %135 +%209 = OpVariable %87 Function %210 +%213 = OpVariable %212 Function %78 OpBranch %216 %216 = OpLabel OpLine %3 36 13 @@ -838,9 +838,9 @@ OpLine %3 36 5 OpStore %209 %217 OpLine %3 39 17 OpLine %3 40 24 -%218 = OpExtInst %5 %1 Cos %81 +%218 = OpExtInst %5 %1 Cos %78 OpLine %3 40 14 -%219 = OpExtInst %5 %1 Sin %81 +%219 = OpExtInst %5 %1 Sin %78 %220 = OpCompositeConstruct %6 %218 %219 OpLine %3 41 15 %221 = OpCompositeExtract %5 %220 0 @@ -859,7 +859,7 @@ OpBranch %231 %231 = OpLabel OpLine %3 43 22 %233 = OpLoad %8 %214 -%234 = OpULessThan %114 %233 %205 +%234 = OpULessThan %112 %233 %205 OpLine %3 43 21 OpSelectionMerge %235 None OpBranchConditional %234 %235 %236 @@ -883,14 +883,14 @@ OpLine %3 45 13 %245 = OpLoad %6 %209 %246 = OpMatrixTimesVector %6 %228 %245 OpLine %3 45 13 -%247 = OpVectorTimesScalar %6 %246 %84 +%247 = OpVectorTimesScalar %6 %246 %81 %248 = OpFAdd %6 %247 %208 OpLine %3 45 9 OpStore %209 %248 OpLine %3 1 1 %249 = OpLoad %5 %213 OpLine %3 46 13 -%250 = OpFMul %5 %249 %81 +%250 = OpFMul %5 %249 %78 OpLine %3 46 9 OpStore %213 %250 OpBranch %238 @@ -900,7 +900,7 @@ OpBranch %232 OpLine %3 1 1 %251 = OpLoad %8 %214 OpLine %3 43 43 -%252 = OpIAdd %8 %251 %127 +%252 = OpIAdd %8 %251 %126 OpLine %3 43 39 OpStore %214 %252 OpBranch %229 @@ -968,7 +968,7 @@ OpLine %3 92 14 OpLine %3 94 14 %296 = OpFAdd %4 %293 %295 OpLine %3 94 13 -%297 = OpVectorTimesScalar %4 %296 %81 +%297 = OpVectorTimesScalar %4 %296 %78 OpLine %3 96 12 %298 = OpCompositeConstruct %14 %279 %297 OpReturnValue %298 @@ -984,12 +984,12 @@ OpLine %3 101 9 %306 = OpConvertUToF %5 %300 %307 = OpCompositeExtract %8 %301 0 OpLine %3 101 9 -%308 = OpIAdd %8 %307 %127 +%308 = OpIAdd %8 %307 %126 %309 = OpConvertUToF %5 %308 %310 = OpFRem %5 %306 %309 %311 = OpCompositeExtract %8 %301 0 OpLine %3 100 12 -%312 = OpIAdd %8 %311 %127 +%312 = OpIAdd %8 %311 %126 %313 = OpUDiv %8 %300 %312 %314 = OpConvertUToF %5 %313 %315 = OpCompositeConstruct %6 %310 %314 @@ -1005,41 +1005,41 @@ OpBranch %328 OpLine %3 270 9 %329 = OpFunctionCall %5 %67 %319 OpLine %3 270 9 -%330 = OpFMul %5 %329 %81 +%330 = OpFMul %5 %329 %78 OpLine %3 270 9 -%331 = OpFAdd %5 %330 %81 +%331 = OpFAdd %5 %330 %78 OpLine %3 271 17 %332 = OpFAdd %6 %319 %324 OpLine %3 271 9 %333 = OpFunctionCall %5 %67 %332 OpLine %3 271 9 -%334 = OpFMul %5 %333 %81 +%334 = OpFMul %5 %333 %78 OpLine %3 271 9 -%335 = OpFAdd %5 %334 %81 +%335 = OpFAdd %5 %334 %78 OpLine %3 272 17 %336 = OpFAdd %6 %319 %327 OpLine %3 272 9 %337 = OpFunctionCall %5 %67 %336 OpLine %3 272 9 -%338 = OpFMul %5 %337 %81 +%338 = OpFMul %5 %337 %78 OpLine %3 269 12 -%339 = OpFAdd %5 %338 %81 +%339 = OpFAdd %5 %338 %78 %340 = OpCompositeConstruct %4 %331 %335 %339 OpReturnValue %340 OpFunctionEnd %345 = OpFunction %2 None %346 %341 = OpLabel %344 = OpLoad %19 %342 -%348 = OpAccessChain %347 %29 %136 +%348 = OpAccessChain %347 %29 %135 OpBranch %353 %353 = OpLabel OpLine %3 111 22 %354 = OpCompositeExtract %8 %344 0 OpLine %3 113 36 -%356 = OpAccessChain %355 %348 %136 +%356 = OpAccessChain %355 %348 %135 %357 = OpLoad %10 %356 OpLine %3 113 59 -%359 = OpAccessChain %358 %348 %127 +%359 = OpAccessChain %358 %348 %126 %360 = OpLoad %11 %359 OpLine %3 113 13 %361 = OpFunctionCall %6 %303 %354 %357 %360 @@ -1050,22 +1050,22 @@ OpLine %3 115 51 OpLine %3 115 33 %367 = OpFunctionCall %14 %270 %361 %366 OpLine %3 115 5 -%368 = OpAccessChain %363 %32 %136 %354 +%368 = OpAccessChain %363 %32 %135 %354 OpStore %368 %367 OpLine %3 118 23 %369 = OpCompositeExtract %8 %344 0 OpLine %3 118 23 %370 = OpIMul %8 %369 %349 OpLine %3 120 25 -%372 = OpAccessChain %371 %348 %136 %136 +%372 = OpAccessChain %371 %348 %135 %135 %373 = OpLoad %8 %372 OpLine %3 120 25 -%374 = OpAccessChain %371 %348 %136 %127 +%374 = OpAccessChain %371 %348 %135 %126 %375 = OpLoad %8 %374 %376 = OpIMul %8 %373 %375 OpLine %3 120 9 %377 = OpIMul %8 %376 %349 -%378 = OpUGreaterThanEqual %114 %370 %377 +%378 = OpUGreaterThanEqual %112 %370 %377 OpLine %3 120 5 OpSelectionMerge %379 None OpBranchConditional %378 %380 %379 @@ -1075,60 +1075,60 @@ OpReturn OpLine %3 122 28 %381 = OpCompositeExtract %8 %344 0 OpLine %3 122 15 -%382 = OpAccessChain %371 %348 %136 %136 +%382 = OpAccessChain %371 %348 %135 %135 %383 = OpLoad %8 %382 %384 = OpUDiv %8 %381 %383 %385 = OpIAdd %8 %354 %384 OpLine %3 123 15 -%386 = OpIAdd %8 %385 %127 +%386 = OpIAdd %8 %385 %126 OpLine %3 124 15 -%387 = OpAccessChain %371 %348 %136 %136 +%387 = OpAccessChain %371 %348 %135 %135 %388 = OpLoad %8 %387 %389 = OpIAdd %8 %385 %388 OpLine %3 124 15 -%390 = OpIAdd %8 %389 %127 +%390 = OpIAdd %8 %389 %126 OpLine %3 125 15 -%391 = OpIAdd %8 %390 %127 +%391 = OpIAdd %8 %390 %126 OpLine %3 127 5 OpLine %3 127 5 -%394 = OpAccessChain %393 %34 %136 %370 +%394 = OpAccessChain %393 %34 %135 %370 OpStore %394 %385 OpLine %3 128 5 OpLine %3 128 5 -%395 = OpIAdd %8 %370 %127 +%395 = OpIAdd %8 %370 %126 OpLine %3 128 5 -%396 = OpAccessChain %393 %34 %136 %395 +%396 = OpAccessChain %393 %34 %135 %395 OpStore %396 %390 OpLine %3 129 5 OpLine %3 129 5 %397 = OpIAdd %8 %370 %350 OpLine %3 129 5 -%398 = OpAccessChain %393 %34 %136 %397 +%398 = OpAccessChain %393 %34 %135 %397 OpStore %398 %391 OpLine %3 130 5 OpLine %3 130 5 %399 = OpIAdd %8 %370 %351 OpLine %3 130 5 -%400 = OpAccessChain %393 %34 %136 %399 +%400 = OpAccessChain %393 %34 %135 %399 OpStore %400 %385 OpLine %3 131 5 OpLine %3 131 5 %401 = OpIAdd %8 %370 %352 OpLine %3 131 5 -%402 = OpAccessChain %393 %34 %136 %401 +%402 = OpAccessChain %393 %34 %135 %401 OpStore %402 %391 OpLine %3 132 5 OpLine %3 132 5 %403 = OpIAdd %8 %370 %205 OpLine %3 132 5 -%404 = OpAccessChain %393 %34 %136 %403 +%404 = OpAccessChain %393 %34 %135 %403 OpStore %404 %386 OpReturn OpFunctionEnd %415 = OpFunction %2 None %346 %405 = OpLabel %408 = OpLoad %8 %406 -%417 = OpAccessChain %416 %36 %136 +%417 = OpAccessChain %416 %36 %135 OpBranch %420 %420 = OpLabel OpLine %3 161 19 @@ -1139,7 +1139,7 @@ OpLine %3 161 13 %423 = OpUMod %8 %422 %350 %424 = OpConvertUToF %5 %423 OpLine %3 162 19 -%425 = OpIAdd %8 %408 %127 +%425 = OpIAdd %8 %408 %126 OpLine %3 162 18 %426 = OpUDiv %8 %425 %351 OpLine %3 162 13 @@ -1148,10 +1148,10 @@ OpLine %3 162 13 OpLine %3 163 14 %429 = OpCompositeConstruct %6 %424 %428 OpLine %3 165 30 -%430 = OpVectorTimesScalar %6 %429 %84 +%430 = OpVectorTimesScalar %6 %429 %81 %431 = OpFAdd %6 %419 %430 OpLine %3 165 20 -%432 = OpCompositeConstruct %7 %431 %76 %56 +%432 = OpCompositeConstruct %7 %431 %74 %56 OpLine %3 168 21 %433 = OpCompositeExtract %5 %429 0 OpLine %3 168 21 @@ -1183,13 +1183,13 @@ OpReturn OpFunctionEnd %465 = OpFunction %2 None %346 %453 = OpLabel -%468 = OpVariable %212 Function %76 -%469 = OpVariable %215 Function %136 +%468 = OpVariable %212 Function %74 +%469 = OpVariable %215 Function %135 %456 = OpLoad %8 %455 %459 = OpLoad %7 %457 %462 = OpLoad %6 %460 %454 = OpCompositeConstruct %21 %456 %459 %462 -%466 = OpAccessChain %416 %36 %136 +%466 = OpAccessChain %416 %36 %135 OpBranch %470 %470 = OpLabel OpLine %3 181 17 @@ -1226,10 +1226,10 @@ OpLine %3 182 22 OpLine %3 183 22 %495 = OpUMod %8 %490 %349 OpLine %3 185 36 -%496 = OpAccessChain %355 %466 %136 +%496 = OpAccessChain %355 %466 %135 %497 = OpLoad %10 %496 OpLine %3 185 57 -%498 = OpAccessChain %358 %466 %127 +%498 = OpAccessChain %358 %466 %126 %499 = OpLoad %11 %498 OpLine %3 185 13 %500 = OpFunctionCall %6 %303 %494 %497 %499 @@ -1287,20 +1287,20 @@ OpBranch %504 OpBranch %504 %504 = OpLabel OpLine %3 200 15 -%524 = OpAccessChain %371 %466 %136 %136 +%524 = OpAccessChain %371 %466 %135 %135 %525 = OpLoad %8 %524 %526 = OpUDiv %8 %494 %525 %527 = OpIAdd %8 %494 %526 OpLine %3 201 15 -%528 = OpIAdd %8 %527 %127 +%528 = OpIAdd %8 %527 %126 OpLine %3 202 15 -%529 = OpAccessChain %371 %466 %136 %136 +%529 = OpAccessChain %371 %466 %135 %135 %530 = OpLoad %8 %529 %531 = OpIAdd %8 %527 %530 OpLine %3 202 15 -%532 = OpIAdd %8 %531 %127 +%532 = OpIAdd %8 %531 %126 OpLine %3 203 15 -%533 = OpIAdd %8 %532 %127 +%533 = OpIAdd %8 %532 %126 OpLine %3 206 5 OpSelectionMerge %534 None OpSwitch %495 %539 0 %535 3 %535 2 %536 4 %536 1 %537 5 %538 @@ -1344,11 +1344,11 @@ OpFunctionEnd %551 = OpLoad %4 %549 %553 = OpLoad %4 %552 %548 = OpCompositeConstruct %14 %551 %553 -%560 = OpAccessChain %559 %39 %136 +%560 = OpAccessChain %559 %39 %135 OpBranch %561 %561 = OpLabel OpLine %3 254 25 -%563 = OpAccessChain %562 %560 %127 +%563 = OpAccessChain %562 %560 %126 %564 = OpLoad %23 %563 %565 = OpCompositeExtract %4 %548 0 OpLine %3 254 25 @@ -1369,30 +1369,30 @@ OpReturn OpFunctionEnd %583 = OpFunction %2 None %346 %574 = OpLabel -%592 = OpVariable %99 Function %593 +%592 = OpVariable %95 Function %593 %577 = OpLoad %7 %576 %579 = OpLoad %4 %578 %581 = OpLoad %4 %580 %575 = OpCompositeConstruct %26 %577 %579 %581 -%584 = OpAccessChain %559 %39 %136 -%586 = OpAccessChain %585 %42 %136 +%584 = OpAccessChain %559 %39 %135 +%586 = OpAccessChain %585 %42 %135 OpBranch %594 %594 = OpLabel OpLine %3 278 28 OpLine %3 278 17 %595 = OpCompositeExtract %4 %575 2 %596 = OpExtInst %4 %1 Fract %595 -%597 = OpExtInst %4 %1 SmoothStep %83 %587 %596 +%597 = OpExtInst %4 %1 SmoothStep %80 %587 %596 OpLine %3 278 5 OpStore %592 %597 OpLine %3 279 17 OpLine %3 279 13 -%598 = OpAccessChain %126 %592 %136 +%598 = OpAccessChain %125 %592 %135 %599 = OpLoad %5 %598 -%600 = OpAccessChain %126 %592 %127 +%600 = OpAccessChain %125 %592 %126 %601 = OpLoad %5 %600 %602 = OpFMul %5 %599 %601 -%603 = OpAccessChain %126 %592 %350 +%603 = OpAccessChain %125 %592 %350 %604 = OpLoad %5 %603 %605 = OpFMul %5 %602 %604 %606 = OpCompositeConstruct %4 %605 %605 %605 @@ -1400,17 +1400,17 @@ OpLine %3 279 13 OpLine %3 279 5 OpStore %592 %607 OpLine %3 282 25 -%609 = OpAccessChain %608 %586 %127 +%609 = OpAccessChain %608 %586 %126 %610 = OpLoad %4 %609 %611 = OpVectorTimesScalar %4 %610 %272 OpLine %3 284 21 -%612 = OpAccessChain %608 %586 %136 +%612 = OpAccessChain %608 %586 %135 %613 = OpLoad %4 %612 %614 = OpCompositeExtract %4 %575 2 %615 = OpFSub %4 %613 %614 %616 = OpExtInst %4 %1 Normalize %615 OpLine %3 285 20 -%618 = OpAccessChain %617 %584 %136 +%618 = OpAccessChain %617 %584 %135 %619 = OpLoad %7 %618 %620 = OpVectorShuffle %4 %619 %619 0 1 2 %621 = OpCompositeExtract %4 %575 2 @@ -1423,20 +1423,20 @@ OpLine %3 288 32 %626 = OpCompositeExtract %4 %575 1 %627 = OpDot %5 %626 %616 OpLine %3 288 28 -%628 = OpExtInst %5 %1 FMax %627 %76 +%628 = OpExtInst %5 %1 FMax %627 %74 OpLine %3 289 25 -%629 = OpAccessChain %608 %586 %127 +%629 = OpAccessChain %608 %586 %126 %630 = OpLoad %4 %629 %631 = OpVectorTimesScalar %4 %630 %628 OpLine %3 291 37 %632 = OpCompositeExtract %4 %575 1 %633 = OpDot %5 %632 %625 OpLine %3 291 33 -%634 = OpExtInst %5 %1 FMax %633 %76 +%634 = OpExtInst %5 %1 FMax %633 %74 OpLine %3 291 29 %635 = OpExtInst %5 %1 Pow %634 %323 OpLine %3 292 26 -%636 = OpAccessChain %608 %586 %127 +%636 = OpAccessChain %608 %586 %126 %637 = OpLoad %4 %636 %638 = OpVectorTimesScalar %4 %637 %635 OpLine %3 294 18 diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm index ec35372f8..708cd65f2 100644 --- a/tests/out/spv/image.spvasm +++ b/tests/out/spv/image.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 517 +; Bound: 518 OpCapability Shader OpCapability Image1D OpCapability Sampled1D @@ -14,15 +14,15 @@ OpEntryPoint GLCompute %169 "depth_load" %167 OpEntryPoint Vertex %189 "queries" %187 OpEntryPoint Vertex %241 "levels_queries" %240 OpEntryPoint Fragment %270 "texture_sample" %269 -OpEntryPoint Fragment %416 "texture_sample_comparison" %414 -OpEntryPoint Fragment %472 "gather" %471 -OpEntryPoint Fragment %506 "depth_no_comparison" %505 +OpEntryPoint Fragment %417 "texture_sample_comparison" %415 +OpEntryPoint Fragment %473 "gather" %472 +OpEntryPoint Fragment %507 "depth_no_comparison" %506 OpExecutionMode %78 LocalSize 16 1 1 OpExecutionMode %169 LocalSize 16 1 1 OpExecutionMode %270 OriginUpperLeft -OpExecutionMode %416 OriginUpperLeft -OpExecutionMode %472 OriginUpperLeft -OpExecutionMode %506 OriginUpperLeft +OpExecutionMode %417 OriginUpperLeft +OpExecutionMode %473 OriginUpperLeft +OpExecutionMode %507 OriginUpperLeft OpName %31 "image_mipmapped_src" OpName %33 "image_multisampled_src" OpName %35 "image_depth_multisampled_src" @@ -53,10 +53,10 @@ OpName %189 "queries" OpName %241 "levels_queries" OpName %270 "texture_sample" OpName %284 "a" -OpName %416 "texture_sample_comparison" -OpName %421 "a" -OpName %472 "gather" -OpName %506 "depth_no_comparison" +OpName %417 "texture_sample_comparison" +OpName %422 "a" +OpName %473 "gather" +OpName %507 "depth_no_comparison" OpDecorate %31 DescriptorSet 0 OpDecorate %31 Binding 0 OpDecorate %33 DescriptorSet 0 @@ -109,9 +109,9 @@ OpDecorate %167 BuiltIn LocalInvocationId OpDecorate %187 BuiltIn Position OpDecorate %240 BuiltIn Position OpDecorate %269 Location 0 -OpDecorate %414 Location 0 -OpDecorate %471 Location 0 -OpDecorate %505 Location 0 +OpDecorate %415 Location 0 +OpDecorate %472 Location 0 +OpDecorate %506 Location 0 %2 = OpTypeVoid %4 = OpTypeInt 32 0 %3 = OpTypeImage %4 2D 0 0 0 1 Unknown @@ -209,25 +209,25 @@ OpDecorate %505 Location 0 %283 = OpConstant %14 0 %285 = OpTypePointer Function %23 %286 = OpConstantNull %23 -%288 = OpTypeSampledImage %15 -%293 = OpTypeSampledImage %16 -%314 = OpTypeSampledImage %18 -%375 = OpTypeSampledImage %20 -%415 = OpTypePointer Output %7 -%414 = OpVariable %415 Output -%422 = OpTypePointer Function %7 -%423 = OpConstantNull %7 -%425 = OpTypeSampledImage %25 -%430 = OpTypeSampledImage %26 -%443 = OpTypeSampledImage %27 -%450 = OpConstant %7 0.0 -%471 = OpVariable %188 Output -%482 = OpConstant %4 1 -%485 = OpConstant %4 3 -%490 = OpTypeSampledImage %3 -%493 = OpTypeVector %14 4 -%494 = OpTypeSampledImage %17 -%505 = OpVariable %188 Output +%289 = OpTypeSampledImage %15 +%294 = OpTypeSampledImage %16 +%315 = OpTypeSampledImage %18 +%376 = OpTypeSampledImage %20 +%416 = OpTypePointer Output %7 +%415 = OpVariable %416 Output +%423 = OpTypePointer Function %7 +%424 = OpConstantNull %7 +%426 = OpTypeSampledImage %25 +%431 = OpTypeSampledImage %26 +%444 = OpTypeSampledImage %27 +%451 = OpConstant %7 0.0 +%472 = OpVariable %188 Output +%483 = OpConstant %4 1 +%486 = OpConstant %4 3 +%491 = OpTypeSampledImage %3 +%494 = OpTypeVector %14 4 +%495 = OpTypeSampledImage %17 +%506 = OpVariable %188 Output %78 = OpFunction %2 None %79 %74 = OpLabel %77 = OpLoad %12 %75 @@ -434,258 +434,259 @@ OpFunctionEnd %275 = OpLoad %24 %64 OpBranch %287 %287 = OpLabel -%289 = OpSampledImage %288 %271 %275 -%290 = OpImageSampleImplicitLod %23 %289 %276 -%291 = OpLoad %23 %284 -%292 = OpFAdd %23 %291 %290 -OpStore %284 %292 -%294 = OpSampledImage %293 %272 %275 -%295 = OpImageSampleImplicitLod %23 %294 %278 -%296 = OpLoad %23 %284 -%297 = OpFAdd %23 %296 %295 -OpStore %284 %297 -%298 = OpSampledImage %293 %272 %275 -%299 = OpImageSampleImplicitLod %23 %298 %278 ConstOffset %30 -%300 = OpLoad %23 %284 -%301 = OpFAdd %23 %300 %299 -OpStore %284 %301 -%302 = OpSampledImage %293 %272 %275 -%303 = OpImageSampleExplicitLod %23 %302 %278 Lod %281 -%304 = OpLoad %23 %284 -%305 = OpFAdd %23 %304 %303 -OpStore %284 %305 -%306 = OpSampledImage %293 %272 %275 -%307 = OpImageSampleExplicitLod %23 %306 %278 Lod|ConstOffset %281 %30 -%308 = OpLoad %23 %284 -%309 = OpFAdd %23 %308 %307 -OpStore %284 %309 -%310 = OpSampledImage %293 %272 %275 -%311 = OpImageSampleImplicitLod %23 %310 %278 Bias|ConstOffset %282 %30 -%312 = OpLoad %23 %284 -%313 = OpFAdd %23 %312 %311 -OpStore %284 %313 -%315 = OpConvertUToF %7 %198 -%316 = OpCompositeConstruct %279 %278 %315 -%317 = OpSampledImage %314 %273 %275 -%318 = OpImageSampleImplicitLod %23 %317 %316 -%319 = OpLoad %23 %284 -%320 = OpFAdd %23 %319 %318 -OpStore %284 %320 -%321 = OpConvertUToF %7 %198 -%322 = OpCompositeConstruct %279 %278 %321 -%323 = OpSampledImage %314 %273 %275 -%324 = OpImageSampleImplicitLod %23 %323 %322 ConstOffset %30 -%325 = OpLoad %23 %284 -%326 = OpFAdd %23 %325 %324 -OpStore %284 %326 -%327 = OpConvertUToF %7 %198 -%328 = OpCompositeConstruct %279 %278 %327 -%329 = OpSampledImage %314 %273 %275 -%330 = OpImageSampleExplicitLod %23 %329 %328 Lod %281 -%331 = OpLoad %23 %284 -%332 = OpFAdd %23 %331 %330 -OpStore %284 %332 -%333 = OpConvertUToF %7 %198 -%334 = OpCompositeConstruct %279 %278 %333 -%335 = OpSampledImage %314 %273 %275 -%336 = OpImageSampleExplicitLod %23 %335 %334 Lod|ConstOffset %281 %30 -%337 = OpLoad %23 %284 -%338 = OpFAdd %23 %337 %336 -OpStore %284 %338 -%339 = OpConvertUToF %7 %198 -%340 = OpCompositeConstruct %279 %278 %339 -%341 = OpSampledImage %314 %273 %275 -%342 = OpImageSampleImplicitLod %23 %341 %340 Bias|ConstOffset %282 %30 -%343 = OpLoad %23 %284 -%344 = OpFAdd %23 %343 %342 -OpStore %284 %344 -%345 = OpConvertSToF %7 %283 -%346 = OpCompositeConstruct %279 %278 %345 -%347 = OpSampledImage %314 %273 %275 -%348 = OpImageSampleImplicitLod %23 %347 %346 -%349 = OpLoad %23 %284 -%350 = OpFAdd %23 %349 %348 -OpStore %284 %350 -%351 = OpConvertSToF %7 %283 -%352 = OpCompositeConstruct %279 %278 %351 -%353 = OpSampledImage %314 %273 %275 -%354 = OpImageSampleImplicitLod %23 %353 %352 ConstOffset %30 -%355 = OpLoad %23 %284 -%356 = OpFAdd %23 %355 %354 -OpStore %284 %356 -%357 = OpConvertSToF %7 %283 -%358 = OpCompositeConstruct %279 %278 %357 -%359 = OpSampledImage %314 %273 %275 -%360 = OpImageSampleExplicitLod %23 %359 %358 Lod %281 -%361 = OpLoad %23 %284 -%362 = OpFAdd %23 %361 %360 -OpStore %284 %362 -%363 = OpConvertSToF %7 %283 -%364 = OpCompositeConstruct %279 %278 %363 -%365 = OpSampledImage %314 %273 %275 -%366 = OpImageSampleExplicitLod %23 %365 %364 Lod|ConstOffset %281 %30 -%367 = OpLoad %23 %284 -%368 = OpFAdd %23 %367 %366 -OpStore %284 %368 -%369 = OpConvertSToF %7 %283 -%370 = OpCompositeConstruct %279 %278 %369 -%371 = OpSampledImage %314 %273 %275 -%372 = OpImageSampleImplicitLod %23 %371 %370 Bias|ConstOffset %282 %30 -%373 = OpLoad %23 %284 -%374 = OpFAdd %23 %373 %372 -OpStore %284 %374 -%376 = OpConvertUToF %7 %198 -%377 = OpCompositeConstruct %23 %280 %376 -%378 = OpSampledImage %375 %274 %275 -%379 = OpImageSampleImplicitLod %23 %378 %377 -%380 = OpLoad %23 %284 -%381 = OpFAdd %23 %380 %379 -OpStore %284 %381 -%382 = OpConvertUToF %7 %198 -%383 = OpCompositeConstruct %23 %280 %382 -%384 = OpSampledImage %375 %274 %275 -%385 = OpImageSampleExplicitLod %23 %384 %383 Lod %281 -%386 = OpLoad %23 %284 -%387 = OpFAdd %23 %386 %385 -OpStore %284 %387 -%388 = OpConvertUToF %7 %198 -%389 = OpCompositeConstruct %23 %280 %388 -%390 = OpSampledImage %375 %274 %275 -%391 = OpImageSampleImplicitLod %23 %390 %389 Bias %282 -%392 = OpLoad %23 %284 -%393 = OpFAdd %23 %392 %391 -OpStore %284 %393 -%394 = OpConvertSToF %7 %283 -%395 = OpCompositeConstruct %23 %280 %394 -%396 = OpSampledImage %375 %274 %275 -%397 = OpImageSampleImplicitLod %23 %396 %395 -%398 = OpLoad %23 %284 -%399 = OpFAdd %23 %398 %397 -OpStore %284 %399 -%400 = OpConvertSToF %7 %283 -%401 = OpCompositeConstruct %23 %280 %400 -%402 = OpSampledImage %375 %274 %275 -%403 = OpImageSampleExplicitLod %23 %402 %401 Lod %281 -%404 = OpLoad %23 %284 -%405 = OpFAdd %23 %404 %403 -OpStore %284 %405 -%406 = OpConvertSToF %7 %283 -%407 = OpCompositeConstruct %23 %280 %406 -%408 = OpSampledImage %375 %274 %275 -%409 = OpImageSampleImplicitLod %23 %408 %407 Bias %282 -%410 = OpLoad %23 %284 -%411 = OpFAdd %23 %410 %409 -OpStore %284 %411 -%412 = OpLoad %23 %284 -OpStore %269 %412 +%288 = OpCompositeExtract %7 %278 0 +%290 = OpSampledImage %289 %271 %275 +%291 = OpImageSampleImplicitLod %23 %290 %288 +%292 = OpLoad %23 %284 +%293 = OpFAdd %23 %292 %291 +OpStore %284 %293 +%295 = OpSampledImage %294 %272 %275 +%296 = OpImageSampleImplicitLod %23 %295 %278 +%297 = OpLoad %23 %284 +%298 = OpFAdd %23 %297 %296 +OpStore %284 %298 +%299 = OpSampledImage %294 %272 %275 +%300 = OpImageSampleImplicitLod %23 %299 %278 ConstOffset %30 +%301 = OpLoad %23 %284 +%302 = OpFAdd %23 %301 %300 +OpStore %284 %302 +%303 = OpSampledImage %294 %272 %275 +%304 = OpImageSampleExplicitLod %23 %303 %278 Lod %281 +%305 = OpLoad %23 %284 +%306 = OpFAdd %23 %305 %304 +OpStore %284 %306 +%307 = OpSampledImage %294 %272 %275 +%308 = OpImageSampleExplicitLod %23 %307 %278 Lod|ConstOffset %281 %30 +%309 = OpLoad %23 %284 +%310 = OpFAdd %23 %309 %308 +OpStore %284 %310 +%311 = OpSampledImage %294 %272 %275 +%312 = OpImageSampleImplicitLod %23 %311 %278 Bias|ConstOffset %282 %30 +%313 = OpLoad %23 %284 +%314 = OpFAdd %23 %313 %312 +OpStore %284 %314 +%316 = OpConvertUToF %7 %198 +%317 = OpCompositeConstruct %279 %278 %316 +%318 = OpSampledImage %315 %273 %275 +%319 = OpImageSampleImplicitLod %23 %318 %317 +%320 = OpLoad %23 %284 +%321 = OpFAdd %23 %320 %319 +OpStore %284 %321 +%322 = OpConvertUToF %7 %198 +%323 = OpCompositeConstruct %279 %278 %322 +%324 = OpSampledImage %315 %273 %275 +%325 = OpImageSampleImplicitLod %23 %324 %323 ConstOffset %30 +%326 = OpLoad %23 %284 +%327 = OpFAdd %23 %326 %325 +OpStore %284 %327 +%328 = OpConvertUToF %7 %198 +%329 = OpCompositeConstruct %279 %278 %328 +%330 = OpSampledImage %315 %273 %275 +%331 = OpImageSampleExplicitLod %23 %330 %329 Lod %281 +%332 = OpLoad %23 %284 +%333 = OpFAdd %23 %332 %331 +OpStore %284 %333 +%334 = OpConvertUToF %7 %198 +%335 = OpCompositeConstruct %279 %278 %334 +%336 = OpSampledImage %315 %273 %275 +%337 = OpImageSampleExplicitLod %23 %336 %335 Lod|ConstOffset %281 %30 +%338 = OpLoad %23 %284 +%339 = OpFAdd %23 %338 %337 +OpStore %284 %339 +%340 = OpConvertUToF %7 %198 +%341 = OpCompositeConstruct %279 %278 %340 +%342 = OpSampledImage %315 %273 %275 +%343 = OpImageSampleImplicitLod %23 %342 %341 Bias|ConstOffset %282 %30 +%344 = OpLoad %23 %284 +%345 = OpFAdd %23 %344 %343 +OpStore %284 %345 +%346 = OpConvertSToF %7 %283 +%347 = OpCompositeConstruct %279 %278 %346 +%348 = OpSampledImage %315 %273 %275 +%349 = OpImageSampleImplicitLod %23 %348 %347 +%350 = OpLoad %23 %284 +%351 = OpFAdd %23 %350 %349 +OpStore %284 %351 +%352 = OpConvertSToF %7 %283 +%353 = OpCompositeConstruct %279 %278 %352 +%354 = OpSampledImage %315 %273 %275 +%355 = OpImageSampleImplicitLod %23 %354 %353 ConstOffset %30 +%356 = OpLoad %23 %284 +%357 = OpFAdd %23 %356 %355 +OpStore %284 %357 +%358 = OpConvertSToF %7 %283 +%359 = OpCompositeConstruct %279 %278 %358 +%360 = OpSampledImage %315 %273 %275 +%361 = OpImageSampleExplicitLod %23 %360 %359 Lod %281 +%362 = OpLoad %23 %284 +%363 = OpFAdd %23 %362 %361 +OpStore %284 %363 +%364 = OpConvertSToF %7 %283 +%365 = OpCompositeConstruct %279 %278 %364 +%366 = OpSampledImage %315 %273 %275 +%367 = OpImageSampleExplicitLod %23 %366 %365 Lod|ConstOffset %281 %30 +%368 = OpLoad %23 %284 +%369 = OpFAdd %23 %368 %367 +OpStore %284 %369 +%370 = OpConvertSToF %7 %283 +%371 = OpCompositeConstruct %279 %278 %370 +%372 = OpSampledImage %315 %273 %275 +%373 = OpImageSampleImplicitLod %23 %372 %371 Bias|ConstOffset %282 %30 +%374 = OpLoad %23 %284 +%375 = OpFAdd %23 %374 %373 +OpStore %284 %375 +%377 = OpConvertUToF %7 %198 +%378 = OpCompositeConstruct %23 %280 %377 +%379 = OpSampledImage %376 %274 %275 +%380 = OpImageSampleImplicitLod %23 %379 %378 +%381 = OpLoad %23 %284 +%382 = OpFAdd %23 %381 %380 +OpStore %284 %382 +%383 = OpConvertUToF %7 %198 +%384 = OpCompositeConstruct %23 %280 %383 +%385 = OpSampledImage %376 %274 %275 +%386 = OpImageSampleExplicitLod %23 %385 %384 Lod %281 +%387 = OpLoad %23 %284 +%388 = OpFAdd %23 %387 %386 +OpStore %284 %388 +%389 = OpConvertUToF %7 %198 +%390 = OpCompositeConstruct %23 %280 %389 +%391 = OpSampledImage %376 %274 %275 +%392 = OpImageSampleImplicitLod %23 %391 %390 Bias %282 +%393 = OpLoad %23 %284 +%394 = OpFAdd %23 %393 %392 +OpStore %284 %394 +%395 = OpConvertSToF %7 %283 +%396 = OpCompositeConstruct %23 %280 %395 +%397 = OpSampledImage %376 %274 %275 +%398 = OpImageSampleImplicitLod %23 %397 %396 +%399 = OpLoad %23 %284 +%400 = OpFAdd %23 %399 %398 +OpStore %284 %400 +%401 = OpConvertSToF %7 %283 +%402 = OpCompositeConstruct %23 %280 %401 +%403 = OpSampledImage %376 %274 %275 +%404 = OpImageSampleExplicitLod %23 %403 %402 Lod %281 +%405 = OpLoad %23 %284 +%406 = OpFAdd %23 %405 %404 +OpStore %284 %406 +%407 = OpConvertSToF %7 %283 +%408 = OpCompositeConstruct %23 %280 %407 +%409 = OpSampledImage %376 %274 %275 +%410 = OpImageSampleImplicitLod %23 %409 %408 Bias %282 +%411 = OpLoad %23 %284 +%412 = OpFAdd %23 %411 %410 +OpStore %284 %412 +%413 = OpLoad %23 %284 +OpStore %269 %413 OpReturn OpFunctionEnd -%416 = OpFunction %2 None %79 -%413 = OpLabel -%421 = OpVariable %422 Function %423 -%417 = OpLoad %24 %66 -%418 = OpLoad %25 %68 -%419 = OpLoad %26 %70 -%420 = OpLoad %27 %72 -OpBranch %424 -%424 = OpLabel -%426 = OpSampledImage %425 %418 %417 -%427 = OpImageSampleDrefImplicitLod %7 %426 %278 %276 -%428 = OpLoad %7 %421 -%429 = OpFAdd %7 %428 %427 -OpStore %421 %429 -%431 = OpConvertUToF %7 %198 -%432 = OpCompositeConstruct %279 %278 %431 -%433 = OpSampledImage %430 %419 %417 -%434 = OpImageSampleDrefImplicitLod %7 %433 %432 %276 -%435 = OpLoad %7 %421 -%436 = OpFAdd %7 %435 %434 -OpStore %421 %436 -%437 = OpConvertSToF %7 %283 -%438 = OpCompositeConstruct %279 %278 %437 -%439 = OpSampledImage %430 %419 %417 -%440 = OpImageSampleDrefImplicitLod %7 %439 %438 %276 -%441 = OpLoad %7 %421 -%442 = OpFAdd %7 %441 %440 -OpStore %421 %442 -%444 = OpSampledImage %443 %420 %417 -%445 = OpImageSampleDrefImplicitLod %7 %444 %280 %276 -%446 = OpLoad %7 %421 -%447 = OpFAdd %7 %446 %445 -OpStore %421 %447 -%448 = OpSampledImage %425 %418 %417 -%449 = OpImageSampleDrefExplicitLod %7 %448 %278 %276 Lod %450 -%451 = OpLoad %7 %421 -%452 = OpFAdd %7 %451 %449 -OpStore %421 %452 -%453 = OpConvertUToF %7 %198 -%454 = OpCompositeConstruct %279 %278 %453 -%455 = OpSampledImage %430 %419 %417 -%456 = OpImageSampleDrefExplicitLod %7 %455 %454 %276 Lod %450 -%457 = OpLoad %7 %421 -%458 = OpFAdd %7 %457 %456 -OpStore %421 %458 -%459 = OpConvertSToF %7 %283 -%460 = OpCompositeConstruct %279 %278 %459 -%461 = OpSampledImage %430 %419 %417 -%462 = OpImageSampleDrefExplicitLod %7 %461 %460 %276 Lod %450 -%463 = OpLoad %7 %421 -%464 = OpFAdd %7 %463 %462 -OpStore %421 %464 -%465 = OpSampledImage %443 %420 %417 -%466 = OpImageSampleDrefExplicitLod %7 %465 %280 %276 Lod %450 -%467 = OpLoad %7 %421 -%468 = OpFAdd %7 %467 %466 -OpStore %421 %468 -%469 = OpLoad %7 %421 -OpStore %414 %469 +%417 = OpFunction %2 None %79 +%414 = OpLabel +%422 = OpVariable %423 Function %424 +%418 = OpLoad %24 %66 +%419 = OpLoad %25 %68 +%420 = OpLoad %26 %70 +%421 = OpLoad %27 %72 +OpBranch %425 +%425 = OpLabel +%427 = OpSampledImage %426 %419 %418 +%428 = OpImageSampleDrefImplicitLod %7 %427 %278 %276 +%429 = OpLoad %7 %422 +%430 = OpFAdd %7 %429 %428 +OpStore %422 %430 +%432 = OpConvertUToF %7 %198 +%433 = OpCompositeConstruct %279 %278 %432 +%434 = OpSampledImage %431 %420 %418 +%435 = OpImageSampleDrefImplicitLod %7 %434 %433 %276 +%436 = OpLoad %7 %422 +%437 = OpFAdd %7 %436 %435 +OpStore %422 %437 +%438 = OpConvertSToF %7 %283 +%439 = OpCompositeConstruct %279 %278 %438 +%440 = OpSampledImage %431 %420 %418 +%441 = OpImageSampleDrefImplicitLod %7 %440 %439 %276 +%442 = OpLoad %7 %422 +%443 = OpFAdd %7 %442 %441 +OpStore %422 %443 +%445 = OpSampledImage %444 %421 %418 +%446 = OpImageSampleDrefImplicitLod %7 %445 %280 %276 +%447 = OpLoad %7 %422 +%448 = OpFAdd %7 %447 %446 +OpStore %422 %448 +%449 = OpSampledImage %426 %419 %418 +%450 = OpImageSampleDrefExplicitLod %7 %449 %278 %276 Lod %451 +%452 = OpLoad %7 %422 +%453 = OpFAdd %7 %452 %450 +OpStore %422 %453 +%454 = OpConvertUToF %7 %198 +%455 = OpCompositeConstruct %279 %278 %454 +%456 = OpSampledImage %431 %420 %418 +%457 = OpImageSampleDrefExplicitLod %7 %456 %455 %276 Lod %451 +%458 = OpLoad %7 %422 +%459 = OpFAdd %7 %458 %457 +OpStore %422 %459 +%460 = OpConvertSToF %7 %283 +%461 = OpCompositeConstruct %279 %278 %460 +%462 = OpSampledImage %431 %420 %418 +%463 = OpImageSampleDrefExplicitLod %7 %462 %461 %276 Lod %451 +%464 = OpLoad %7 %422 +%465 = OpFAdd %7 %464 %463 +OpStore %422 %465 +%466 = OpSampledImage %444 %421 %418 +%467 = OpImageSampleDrefExplicitLod %7 %466 %280 %276 Lod %451 +%468 = OpLoad %7 %422 +%469 = OpFAdd %7 %468 %467 +OpStore %422 %469 +%470 = OpLoad %7 %422 +OpStore %415 %470 OpReturn OpFunctionEnd -%472 = OpFunction %2 None %79 -%470 = OpLabel -%473 = OpLoad %16 %49 -%474 = OpLoad %3 %51 -%475 = OpLoad %17 %52 -%476 = OpLoad %24 %64 -%477 = OpLoad %24 %66 -%478 = OpLoad %25 %68 -OpBranch %479 -%479 = OpLabel -%480 = OpSampledImage %293 %473 %476 -%481 = OpImageGather %23 %480 %278 %482 -%483 = OpSampledImage %293 %473 %476 -%484 = OpImageGather %23 %483 %278 %485 ConstOffset %30 -%486 = OpSampledImage %425 %478 %477 -%487 = OpImageDrefGather %23 %486 %278 %276 -%488 = OpSampledImage %425 %478 %477 -%489 = OpImageDrefGather %23 %488 %278 %276 ConstOffset %30 -%491 = OpSampledImage %490 %474 %476 -%492 = OpImageGather %98 %491 %278 %198 -%495 = OpSampledImage %494 %475 %476 -%496 = OpImageGather %493 %495 %278 %198 -%497 = OpConvertUToF %23 %492 -%498 = OpConvertSToF %23 %496 -%499 = OpFAdd %23 %497 %498 -%500 = OpFAdd %23 %481 %484 -%501 = OpFAdd %23 %500 %487 -%502 = OpFAdd %23 %501 %489 -%503 = OpFAdd %23 %502 %499 -OpStore %471 %503 +%473 = OpFunction %2 None %79 +%471 = OpLabel +%474 = OpLoad %16 %49 +%475 = OpLoad %3 %51 +%476 = OpLoad %17 %52 +%477 = OpLoad %24 %64 +%478 = OpLoad %24 %66 +%479 = OpLoad %25 %68 +OpBranch %480 +%480 = OpLabel +%481 = OpSampledImage %294 %474 %477 +%482 = OpImageGather %23 %481 %278 %483 +%484 = OpSampledImage %294 %474 %477 +%485 = OpImageGather %23 %484 %278 %486 ConstOffset %30 +%487 = OpSampledImage %426 %479 %478 +%488 = OpImageDrefGather %23 %487 %278 %276 +%489 = OpSampledImage %426 %479 %478 +%490 = OpImageDrefGather %23 %489 %278 %276 ConstOffset %30 +%492 = OpSampledImage %491 %475 %477 +%493 = OpImageGather %98 %492 %278 %198 +%496 = OpSampledImage %495 %476 %477 +%497 = OpImageGather %494 %496 %278 %198 +%498 = OpConvertUToF %23 %493 +%499 = OpConvertSToF %23 %497 +%500 = OpFAdd %23 %498 %499 +%501 = OpFAdd %23 %482 %485 +%502 = OpFAdd %23 %501 %488 +%503 = OpFAdd %23 %502 %490 +%504 = OpFAdd %23 %503 %500 +OpStore %472 %504 OpReturn OpFunctionEnd -%506 = OpFunction %2 None %79 -%504 = OpLabel -%507 = OpLoad %24 %64 -%508 = OpLoad %25 %68 -OpBranch %509 -%509 = OpLabel -%510 = OpSampledImage %425 %508 %507 -%511 = OpImageSampleImplicitLod %23 %510 %278 -%512 = OpCompositeExtract %7 %511 0 -%513 = OpSampledImage %425 %508 %507 -%514 = OpImageGather %23 %513 %278 %198 -%515 = OpCompositeConstruct %23 %512 %512 %512 %512 -%516 = OpFAdd %23 %515 %514 -OpStore %505 %516 +%507 = OpFunction %2 None %79 +%505 = OpLabel +%508 = OpLoad %24 %64 +%509 = OpLoad %25 %68 +OpBranch %510 +%510 = OpLabel +%511 = OpSampledImage %426 %509 %508 +%512 = OpImageSampleImplicitLod %23 %511 %278 +%513 = OpCompositeExtract %7 %512 0 +%514 = OpSampledImage %426 %509 %508 +%515 = OpImageGather %23 %514 %278 %198 +%516 = OpCompositeConstruct %23 %513 %513 %513 %513 +%517 = OpFAdd %23 %516 %515 +OpStore %506 %517 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index ba268dca9..de9863887 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -138,7 +138,7 @@ fn foo_vert(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { test_matrix_within_array_within_struct_accesses(); let _matrix = bar._matrix; let arr_1 = bar.arr; - let b = bar._matrix[3][0]; + let b = bar._matrix[3u][0]; let a_1 = bar.data[(arrayLength((&bar.data)) - 2u)].value; let c = qux; let data_pointer = (&bar.data[0].value); diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index 57f3ba6a4..2ddc903aa 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -9,17 +9,13 @@ var out: vec4; var out2_: i32; fn swizzle_of_compose() { - let a = vec2(1, 2); - let b = vec2(3, 4); out = vec4(4, 3, 2, 1); return; } fn index_of_compose() { - let a_1 = vec2(1, 2); - let b_1 = vec2(3, 4); - let _e7 = out2_; - out2_ = (_e7 + 2); + let _e2 = out2_; + out2_ = (_e2 + 2); return; } diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl index 6dfa0dbac..062d37713 100644 --- a/tests/out/wgsl/image.wgsl +++ b/tests/out/wgsl/image.wgsl @@ -112,74 +112,74 @@ fn texture_sample() -> @location(0) vec4 { let tc = vec2(0.5); let tc3_ = vec3(0.5); - let _e8 = textureSample(image_1d, sampler_reg, 0.5); - let _e9 = a; - a = (_e9 + _e8); - let _e13 = textureSample(image_2d, sampler_reg, tc); - let _e14 = a; - a = (_e14 + _e13); - let _e18 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); - let _e19 = a; - a = (_e19 + _e18); - let _e23 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3); - let _e24 = a; - a = (_e24 + _e23); - let _e28 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3, vec2(3, 1)); - let _e29 = a; - a = (_e29 + _e28); - let _e34 = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); - let _e35 = a; - a = (_e35 + _e34); - let _e40 = textureSample(image_2d_array, sampler_reg, tc, 0u); - let _e41 = a; - a = (_e41 + _e40); - let _e46 = textureSample(image_2d_array, sampler_reg, tc, 0u, vec2(3, 1)); - let _e47 = a; - a = (_e47 + _e46); - let _e52 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3); - let _e53 = a; - a = (_e53 + _e52); - let _e58 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3, vec2(3, 1)); - let _e59 = a; - a = (_e59 + _e58); - let _e65 = textureSampleBias(image_2d_array, sampler_reg, tc, 0u, 2.0, vec2(3, 1)); - let _e66 = a; - a = (_e66 + _e65); - let _e71 = textureSample(image_2d_array, sampler_reg, tc, 0); - let _e72 = a; - a = (_e72 + _e71); - let _e77 = textureSample(image_2d_array, sampler_reg, tc, 0, vec2(3, 1)); - let _e78 = a; - a = (_e78 + _e77); - let _e83 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3); - let _e84 = a; - a = (_e84 + _e83); - let _e89 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3, vec2(3, 1)); - let _e90 = a; - a = (_e90 + _e89); - let _e96 = textureSampleBias(image_2d_array, sampler_reg, tc, 0, 2.0, vec2(3, 1)); - let _e97 = a; - a = (_e97 + _e96); - let _e102 = textureSample(image_cube_array, sampler_reg, tc3_, 0u); - let _e103 = a; - a = (_e103 + _e102); - let _e108 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0u, 2.3); - let _e109 = a; - a = (_e109 + _e108); - let _e115 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0u, 2.0); - let _e116 = a; - a = (_e116 + _e115); - let _e121 = textureSample(image_cube_array, sampler_reg, tc3_, 0); - let _e122 = a; - a = (_e122 + _e121); - let _e127 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0, 2.3); - let _e128 = a; - a = (_e128 + _e127); - let _e134 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0, 2.0); - let _e135 = a; - a = (_e135 + _e134); - let _e137 = a; - return _e137; + let _e9 = textureSample(image_1d, sampler_reg, tc.x); + let _e10 = a; + a = (_e10 + _e9); + let _e14 = textureSample(image_2d, sampler_reg, tc); + let _e15 = a; + a = (_e15 + _e14); + let _e19 = textureSample(image_2d, sampler_reg, tc, vec2(3, 1)); + let _e20 = a; + a = (_e20 + _e19); + let _e24 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3); + let _e25 = a; + a = (_e25 + _e24); + let _e29 = textureSampleLevel(image_2d, sampler_reg, tc, 2.3, vec2(3, 1)); + let _e30 = a; + a = (_e30 + _e29); + let _e35 = textureSampleBias(image_2d, sampler_reg, tc, 2.0, vec2(3, 1)); + let _e36 = a; + a = (_e36 + _e35); + let _e41 = textureSample(image_2d_array, sampler_reg, tc, 0u); + let _e42 = a; + a = (_e42 + _e41); + let _e47 = textureSample(image_2d_array, sampler_reg, tc, 0u, vec2(3, 1)); + let _e48 = a; + a = (_e48 + _e47); + let _e53 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3); + let _e54 = a; + a = (_e54 + _e53); + let _e59 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0u, 2.3, vec2(3, 1)); + let _e60 = a; + a = (_e60 + _e59); + let _e66 = textureSampleBias(image_2d_array, sampler_reg, tc, 0u, 2.0, vec2(3, 1)); + let _e67 = a; + a = (_e67 + _e66); + let _e72 = textureSample(image_2d_array, sampler_reg, tc, 0); + let _e73 = a; + a = (_e73 + _e72); + let _e78 = textureSample(image_2d_array, sampler_reg, tc, 0, vec2(3, 1)); + let _e79 = a; + a = (_e79 + _e78); + let _e84 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3); + let _e85 = a; + a = (_e85 + _e84); + let _e90 = textureSampleLevel(image_2d_array, sampler_reg, tc, 0, 2.3, vec2(3, 1)); + let _e91 = a; + a = (_e91 + _e90); + let _e97 = textureSampleBias(image_2d_array, sampler_reg, tc, 0, 2.0, vec2(3, 1)); + let _e98 = a; + a = (_e98 + _e97); + let _e103 = textureSample(image_cube_array, sampler_reg, tc3_, 0u); + let _e104 = a; + a = (_e104 + _e103); + let _e109 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0u, 2.3); + let _e110 = a; + a = (_e110 + _e109); + let _e116 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0u, 2.0); + let _e117 = a; + a = (_e117 + _e116); + let _e122 = textureSample(image_cube_array, sampler_reg, tc3_, 0); + let _e123 = a; + a = (_e123 + _e122); + let _e128 = textureSampleLevel(image_cube_array, sampler_reg, tc3_, 0, 2.3); + let _e129 = a; + a = (_e129 + _e128); + let _e135 = textureSampleBias(image_cube_array, sampler_reg, tc3_, 0, 2.0); + let _e136 = a; + a = (_e136 + _e135); + let _e138 = a; + return _e138; } @fragment diff --git a/tests/out/wgsl/type-alias.wgsl b/tests/out/wgsl/type-alias.wgsl index a4a9438eb..fea2dec10 100644 --- a/tests/out/wgsl/type-alias.wgsl +++ b/tests/out/wgsl/type-alias.wgsl @@ -3,7 +3,7 @@ fn main() { let c = vec3(0.0); let b = vec3(vec2(0.0), 0.0); let d = vec3(vec2(0.0), 0.0); - let e = vec3(vec2(0, 0), 0); + let e = vec3(d); let f = mat2x2(vec2(1.0, 2.0), vec2(3.0, 4.0)); let g = mat3x3(a, a, a); } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 637b5372f..9e5eecccc 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1759,47 +1759,47 @@ fn assign_to_let() { "###, ); - // check( - // " - // fn f() { - // let a = array(1, 2); - // a[0] = 1; - // } - // ", - // r###"error: invalid left-hand side of assignment - // ┌─ wgsl:3:17 - // │ - // 3 │ let a = array(1, 2); - // │ ^ this is an immutable binding - // 4 │ a[0] = 1; - // │ ^^^^ cannot assign to this expression - // │ - // = note: consider declaring 'a' with `var` instead of `let` + check( + " + fn f() { + let a = array(1, 2); + a[0] = 1; + } + ", + r###"error: invalid left-hand side of assignment + ┌─ wgsl:3:17 + │ +3 │ let a = array(1, 2); + │ ^ this is an immutable binding +4 │ a[0] = 1; + │ ^^^^ cannot assign to this expression + │ + = note: consider declaring 'a' with `var` instead of `let` - // "###, - // ); +"###, + ); - // check( - // " - // struct S { a: i32 } + check( + " + struct S { a: i32 } - // fn f() { - // let a = S(10); - // a.a = 20; - // } - // ", - // r###"error: invalid left-hand side of assignment - // ┌─ wgsl:5:17 - // │ - // 5 │ let a = S(10); - // │ ^ this is an immutable binding - // 6 │ a.a = 20; - // │ ^^^ cannot assign to this expression - // │ - // = note: consider declaring 'a' with `var` instead of `let` + fn f() { + let a = S(10); + a.a = 20; + } + ", + r###"error: invalid left-hand side of assignment + ┌─ wgsl:5:17 + │ +5 │ let a = S(10); + │ ^ this is an immutable binding +6 │ a.a = 20; + │ ^^^ cannot assign to this expression + │ + = note: consider declaring 'a' with `var` instead of `let` - // "###, - // ); +"###, + ); } #[test] From b95a72b2f6c209e7a3a40adfd90ffa281f47360f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 29 Sep 2023 20:09:59 +0200 Subject: [PATCH 2146/2212] [wgsl] test `@workgroup_size` attribute with constants --- tests/in/const-exprs.wgsl | 5 +- tests/out/glsl/const-exprs.main.Compute.glsl | 4 +- tests/out/hlsl/const-exprs.hlsl | 4 +- tests/out/msl/const-exprs.msl | 2 + tests/out/spv/const-exprs.spvasm | 195 ++++++++++--------- tests/out/wgsl/const-exprs.wgsl | 4 +- 6 files changed, 113 insertions(+), 101 deletions(-) diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl index 49e95a275..11fee4a41 100644 --- a/tests/in/const-exprs.wgsl +++ b/tests/in/const-exprs.wgsl @@ -1,7 +1,10 @@ @group(0) @binding(0) var out: vec4; @group(0) @binding(1) var out2: i32; -@compute @workgroup_size(1) +const TWO: u32 = 2u; +const THREE: i32 = 3i; + +@compute @workgroup_size(TWO, THREE, TWO - 1u) fn main() { swizzle_of_compose(); index_of_compose(); diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index e75ffa650..8a1c3d45c 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -3,8 +3,10 @@ precision highp float; precision highp int; -layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +layout(local_size_x = 2, local_size_y = 3, local_size_z = 1) in; +const uint TWO = 2u; +const int THREE = 3; const int FOUR = 4; const int FOUR_ALIAS = 4; const int TEST_CONSTANT_ADDITION = 8; diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index 91b82ec56..08cf89091 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -1,3 +1,5 @@ +static const uint TWO = 2u; +static const int THREE = 3; static const int FOUR = 4; static const int FOUR_ALIAS = 4; static const int TEST_CONSTANT_ADDITION = 8; @@ -58,7 +60,7 @@ void compose_of_constant() return; } -[numthreads(1, 1, 1)] +[numthreads(2, 3, 1)] void main() { swizzle_of_compose(); diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 5cbc23a00..4e6d67f80 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -4,6 +4,8 @@ using metal::uint; +constant uint TWO = 2u; +constant int THREE = 3; constant int FOUR = 4; constant int FOUR_ALIAS = 4; constant int TEST_CONSTANT_ADDITION = 8; diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index 1f7bf5c8c..c8d41c59f 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,127 +1,128 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 82 +; Bound: 83 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %72 "main" -OpExecutionMode %72 LocalSize 1 1 1 -OpDecorate %7 DescriptorSet 0 -OpDecorate %7 Binding 0 -OpDecorate %8 Block -OpMemberDecorate %8 0 Offset 0 +OpEntryPoint GLCompute %73 "main" +OpExecutionMode %73 LocalSize 2 3 1 OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 1 +OpDecorate %10 Binding 0 OpDecorate %11 Block OpMemberDecorate %11 0 Offset 0 +OpDecorate %13 DescriptorSet 0 +OpDecorate %13 Binding 1 +OpDecorate %14 Block +OpMemberDecorate %14 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 4 -%5 = OpConstant %4 4 -%6 = OpConstant %4 8 -%8 = OpTypeStruct %3 -%9 = OpTypePointer StorageBuffer %8 -%7 = OpVariable %9 StorageBuffer -%11 = OpTypeStruct %4 +%5 = OpTypeInt 32 0 +%6 = OpConstant %5 2 +%7 = OpConstant %4 3 +%8 = OpConstant %4 4 +%9 = OpConstant %4 8 +%11 = OpTypeStruct %3 %12 = OpTypePointer StorageBuffer %11 %10 = OpVariable %12 StorageBuffer -%15 = OpTypeFunction %2 -%16 = OpTypePointer StorageBuffer %3 -%18 = OpTypeInt 32 0 -%17 = OpConstant %18 0 -%20 = OpConstant %4 1 -%21 = OpConstant %4 2 -%22 = OpConstant %4 3 -%23 = OpConstantComposite %3 %5 %22 %21 %20 -%27 = OpTypePointer StorageBuffer %4 -%35 = OpConstant %4 6 -%42 = OpConstant %4 30 -%43 = OpConstant %4 70 -%45 = OpTypePointer Function %4 -%47 = OpConstantNull %4 -%49 = OpConstantNull %4 -%64 = OpConstant %4 -4 -%65 = OpConstantComposite %3 %64 %64 %64 %64 -%14 = OpFunction %2 None %15 -%13 = OpLabel -%19 = OpAccessChain %16 %7 %17 -OpBranch %24 -%24 = OpLabel -OpStore %19 %23 -OpReturn -OpFunctionEnd -%26 = OpFunction %2 None %15 +%14 = OpTypeStruct %4 +%15 = OpTypePointer StorageBuffer %14 +%13 = OpVariable %15 StorageBuffer +%18 = OpTypeFunction %2 +%19 = OpTypePointer StorageBuffer %3 +%20 = OpConstant %5 0 +%22 = OpConstant %4 1 +%23 = OpConstant %4 2 +%24 = OpConstantComposite %3 %8 %7 %23 %22 +%28 = OpTypePointer StorageBuffer %4 +%36 = OpConstant %4 6 +%43 = OpConstant %4 30 +%44 = OpConstant %4 70 +%46 = OpTypePointer Function %4 +%48 = OpConstantNull %4 +%50 = OpConstantNull %4 +%65 = OpConstant %4 -4 +%66 = OpConstantComposite %3 %65 %65 %65 %65 +%17 = OpFunction %2 None %18 +%16 = OpLabel +%21 = OpAccessChain %19 %10 %20 +OpBranch %25 %25 = OpLabel -%28 = OpAccessChain %27 %10 %17 -OpBranch %29 -%29 = OpLabel -%30 = OpLoad %4 %28 -%31 = OpIAdd %4 %30 %21 -OpStore %28 %31 +OpStore %21 %24 OpReturn OpFunctionEnd -%33 = OpFunction %2 None %15 -%32 = OpLabel -%34 = OpAccessChain %27 %10 %17 -OpBranch %36 -%36 = OpLabel -%37 = OpLoad %4 %34 -%38 = OpIAdd %4 %37 %35 -OpStore %34 %38 +%27 = OpFunction %2 None %18 +%26 = OpLabel +%29 = OpAccessChain %28 %13 %20 +OpBranch %30 +%30 = OpLabel +%31 = OpLoad %4 %29 +%32 = OpIAdd %4 %31 %23 +OpStore %29 %32 OpReturn OpFunctionEnd -%40 = OpFunction %2 None %15 -%39 = OpLabel -%46 = OpVariable %45 Function %47 -%50 = OpVariable %45 Function %43 -%44 = OpVariable %45 Function %42 -%48 = OpVariable %45 Function %49 -%41 = OpAccessChain %16 %7 %17 -OpBranch %51 -%51 = OpLabel -%52 = OpLoad %4 %44 -OpStore %46 %52 -%53 = OpLoad %4 %46 -OpStore %48 %53 -%54 = OpLoad %4 %44 -%55 = OpLoad %4 %46 -%56 = OpLoad %4 %48 -%57 = OpLoad %4 %50 -%58 = OpCompositeConstruct %3 %54 %55 %56 %57 -%59 = OpLoad %3 %41 -%60 = OpIAdd %3 %59 %58 -OpStore %41 %60 +%34 = OpFunction %2 None %18 +%33 = OpLabel +%35 = OpAccessChain %28 %13 %20 +OpBranch %37 +%37 = OpLabel +%38 = OpLoad %4 %35 +%39 = OpIAdd %4 %38 %36 +OpStore %35 %39 OpReturn OpFunctionEnd -%62 = OpFunction %2 None %15 -%61 = OpLabel -%63 = OpAccessChain %16 %7 %17 -OpBranch %66 -%66 = OpLabel -OpStore %63 %65 +%41 = OpFunction %2 None %18 +%40 = OpLabel +%47 = OpVariable %46 Function %48 +%51 = OpVariable %46 Function %44 +%45 = OpVariable %46 Function %43 +%49 = OpVariable %46 Function %50 +%42 = OpAccessChain %19 %10 %20 +OpBranch %52 +%52 = OpLabel +%53 = OpLoad %4 %45 +OpStore %47 %53 +%54 = OpLoad %4 %47 +OpStore %49 %54 +%55 = OpLoad %4 %45 +%56 = OpLoad %4 %47 +%57 = OpLoad %4 %49 +%58 = OpLoad %4 %51 +%59 = OpCompositeConstruct %3 %55 %56 %57 %58 +%60 = OpLoad %3 %42 +%61 = OpIAdd %3 %60 %59 +OpStore %42 %61 OpReturn OpFunctionEnd -%68 = OpFunction %2 None %15 +%63 = OpFunction %2 None %18 +%62 = OpLabel +%64 = OpAccessChain %19 %10 %20 +OpBranch %67 %67 = OpLabel -%69 = OpAccessChain %16 %7 %17 -OpBranch %70 -%70 = OpLabel -OpStore %69 %65 +OpStore %64 %66 OpReturn OpFunctionEnd -%72 = OpFunction %2 None %15 +%69 = OpFunction %2 None %18 +%68 = OpLabel +%70 = OpAccessChain %19 %10 %20 +OpBranch %71 %71 = OpLabel -%73 = OpAccessChain %16 %7 %17 -%74 = OpAccessChain %27 %10 %17 -OpBranch %75 -%75 = OpLabel -%76 = OpFunctionCall %2 %14 -%77 = OpFunctionCall %2 %26 -%78 = OpFunctionCall %2 %33 -%79 = OpFunctionCall %2 %40 -%80 = OpFunctionCall %2 %62 -%81 = OpFunctionCall %2 %68 +OpStore %70 %66 +OpReturn +OpFunctionEnd +%73 = OpFunction %2 None %18 +%72 = OpLabel +%74 = OpAccessChain %19 %10 %20 +%75 = OpAccessChain %28 %13 %20 +OpBranch %76 +%76 = OpLabel +%77 = OpFunctionCall %2 %17 +%78 = OpFunctionCall %2 %27 +%79 = OpFunctionCall %2 %34 +%80 = OpFunctionCall %2 %41 +%81 = OpFunctionCall %2 %63 +%82 = OpFunctionCall %2 %69 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index 2ddc903aa..df675a896 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -1,3 +1,5 @@ +const TWO: u32 = 2u; +const THREE: i32 = 3; const FOUR: i32 = 4; const FOUR_ALIAS: i32 = 4; const TEST_CONSTANT_ADDITION: i32 = 8; @@ -54,7 +56,7 @@ fn compose_of_constant() { return; } -@compute @workgroup_size(1, 1, 1) +@compute @workgroup_size(2, 3, 1) fn main() { swizzle_of_compose(); index_of_compose(); From 5de27f20786785403adacebc15b50f1faae7bdc3 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 29 Sep 2023 20:11:31 +0200 Subject: [PATCH 2147/2212] [wgsl] test const evaluation of division and multiplication --- tests/in/const-exprs.wgsl | 5 + tests/out/glsl/const-exprs.main.Compute.glsl | 3 + tests/out/hlsl/const-exprs.hlsl | 3 + tests/out/msl/const-exprs.msl | 3 + tests/out/spv/const-exprs.spvasm | 209 ++++++++++--------- tests/out/wgsl/const-exprs.wgsl | 3 + 6 files changed, 125 insertions(+), 101 deletions(-) diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl index 11fee4a41..580eda184 100644 --- a/tests/in/const-exprs.wgsl +++ b/tests/in/const-exprs.wgsl @@ -64,3 +64,8 @@ fn splat_of_constant() { fn compose_of_constant() { out = -vec4(FOUR, FOUR, FOUR, FOUR); } + +const PI: f32 = 3.141; +const phi_sun: f32 = PI * 2.0; + +const DIV: vec4f = vec4(4.0 / 9.0, 0.0, 0.0, 0.0); diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index 8a1c3d45c..a9fbb3b77 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -11,6 +11,9 @@ const int FOUR = 4; const int FOUR_ALIAS = 4; const int TEST_CONSTANT_ADDITION = 8; const int TEST_CONSTANT_ALIAS_ADDITION = 8; +const float PI = 3.141; +const float phi_sun = 6.282; +const vec4 DIV = vec4(0.44444445, 0.0, 0.0, 0.0); layout(std430) buffer type_block_0Compute { ivec4 _group_0_binding_0_cs; }; diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index 08cf89091..ed1b86415 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -4,6 +4,9 @@ static const int FOUR = 4; static const int FOUR_ALIAS = 4; static const int TEST_CONSTANT_ADDITION = 8; static const int TEST_CONSTANT_ALIAS_ADDITION = 8; +static const float PI = 3.141; +static const float phi_sun = 6.282; +static const float4 DIV = float4(0.44444445, 0.0, 0.0, 0.0); RWByteAddressBuffer out_ : register(u0); RWByteAddressBuffer out2_ : register(u1); diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 4e6d67f80..1707df1e8 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -10,6 +10,9 @@ constant int FOUR = 4; constant int FOUR_ALIAS = 4; constant int TEST_CONSTANT_ADDITION = 8; constant int TEST_CONSTANT_ALIAS_ADDITION = 8; +constant float PI = 3.141; +constant float phi_sun = 6.282; +constant metal::float4 DIV = metal::float4(0.44444445, 0.0, 0.0, 0.0); void swizzle_of_compose( device metal::int4& out diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index c8d41c59f..f4103b868 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,128 +1,135 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 83 +; Bound: 90 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %73 "main" -OpExecutionMode %73 LocalSize 2 3 1 -OpDecorate %10 DescriptorSet 0 -OpDecorate %10 Binding 0 -OpDecorate %11 Block -OpMemberDecorate %11 0 Offset 0 -OpDecorate %13 DescriptorSet 0 -OpDecorate %13 Binding 1 -OpDecorate %14 Block -OpMemberDecorate %14 0 Offset 0 +OpEntryPoint GLCompute %80 "main" +OpExecutionMode %80 LocalSize 2 3 1 +OpDecorate %17 DescriptorSet 0 +OpDecorate %17 Binding 0 +OpDecorate %18 Block +OpMemberDecorate %18 0 Offset 0 +OpDecorate %20 DescriptorSet 0 +OpDecorate %20 Binding 1 +OpDecorate %21 Block +OpMemberDecorate %21 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 4 %5 = OpTypeInt 32 0 -%6 = OpConstant %5 2 -%7 = OpConstant %4 3 -%8 = OpConstant %4 4 -%9 = OpConstant %4 8 -%11 = OpTypeStruct %3 -%12 = OpTypePointer StorageBuffer %11 -%10 = OpVariable %12 StorageBuffer -%14 = OpTypeStruct %4 -%15 = OpTypePointer StorageBuffer %14 -%13 = OpVariable %15 StorageBuffer -%18 = OpTypeFunction %2 -%19 = OpTypePointer StorageBuffer %3 -%20 = OpConstant %5 0 -%22 = OpConstant %4 1 -%23 = OpConstant %4 2 -%24 = OpConstantComposite %3 %8 %7 %23 %22 -%28 = OpTypePointer StorageBuffer %4 -%36 = OpConstant %4 6 -%43 = OpConstant %4 30 -%44 = OpConstant %4 70 -%46 = OpTypePointer Function %4 -%48 = OpConstantNull %4 -%50 = OpConstantNull %4 -%65 = OpConstant %4 -4 -%66 = OpConstantComposite %3 %65 %65 %65 %65 -%17 = OpFunction %2 None %18 -%16 = OpLabel -%21 = OpAccessChain %19 %10 %20 -OpBranch %25 -%25 = OpLabel -OpStore %21 %24 +%6 = OpTypeFloat 32 +%7 = OpTypeVector %6 4 +%8 = OpConstant %5 2 +%9 = OpConstant %4 3 +%10 = OpConstant %4 4 +%11 = OpConstant %4 8 +%12 = OpConstant %6 3.141 +%13 = OpConstant %6 6.282 +%14 = OpConstant %6 0.44444445 +%15 = OpConstant %6 0.0 +%16 = OpConstantComposite %7 %14 %15 %15 %15 +%18 = OpTypeStruct %3 +%19 = OpTypePointer StorageBuffer %18 +%17 = OpVariable %19 StorageBuffer +%21 = OpTypeStruct %4 +%22 = OpTypePointer StorageBuffer %21 +%20 = OpVariable %22 StorageBuffer +%25 = OpTypeFunction %2 +%26 = OpTypePointer StorageBuffer %3 +%27 = OpConstant %5 0 +%29 = OpConstant %4 1 +%30 = OpConstant %4 2 +%31 = OpConstantComposite %3 %10 %9 %30 %29 +%35 = OpTypePointer StorageBuffer %4 +%43 = OpConstant %4 6 +%50 = OpConstant %4 30 +%51 = OpConstant %4 70 +%53 = OpTypePointer Function %4 +%55 = OpConstantNull %4 +%57 = OpConstantNull %4 +%72 = OpConstant %4 -4 +%73 = OpConstantComposite %3 %72 %72 %72 %72 +%24 = OpFunction %2 None %25 +%23 = OpLabel +%28 = OpAccessChain %26 %17 %27 +OpBranch %32 +%32 = OpLabel +OpStore %28 %31 OpReturn OpFunctionEnd -%27 = OpFunction %2 None %18 -%26 = OpLabel -%29 = OpAccessChain %28 %13 %20 -OpBranch %30 -%30 = OpLabel -%31 = OpLoad %4 %29 -%32 = OpIAdd %4 %31 %23 -OpStore %29 %32 -OpReturn -OpFunctionEnd -%34 = OpFunction %2 None %18 +%34 = OpFunction %2 None %25 %33 = OpLabel -%35 = OpAccessChain %28 %13 %20 +%36 = OpAccessChain %35 %20 %27 OpBranch %37 %37 = OpLabel -%38 = OpLoad %4 %35 -%39 = OpIAdd %4 %38 %36 -OpStore %35 %39 +%38 = OpLoad %4 %36 +%39 = OpIAdd %4 %38 %30 +OpStore %36 %39 OpReturn OpFunctionEnd -%41 = OpFunction %2 None %18 +%41 = OpFunction %2 None %25 %40 = OpLabel -%47 = OpVariable %46 Function %48 -%51 = OpVariable %46 Function %44 -%45 = OpVariable %46 Function %43 -%49 = OpVariable %46 Function %50 -%42 = OpAccessChain %19 %10 %20 -OpBranch %52 -%52 = OpLabel -%53 = OpLoad %4 %45 -OpStore %47 %53 -%54 = OpLoad %4 %47 -OpStore %49 %54 -%55 = OpLoad %4 %45 -%56 = OpLoad %4 %47 -%57 = OpLoad %4 %49 -%58 = OpLoad %4 %51 -%59 = OpCompositeConstruct %3 %55 %56 %57 %58 -%60 = OpLoad %3 %42 -%61 = OpIAdd %3 %60 %59 -OpStore %42 %61 +%42 = OpAccessChain %35 %20 %27 +OpBranch %44 +%44 = OpLabel +%45 = OpLoad %4 %42 +%46 = OpIAdd %4 %45 %43 +OpStore %42 %46 OpReturn OpFunctionEnd -%63 = OpFunction %2 None %18 -%62 = OpLabel -%64 = OpAccessChain %19 %10 %20 -OpBranch %67 -%67 = OpLabel -OpStore %64 %66 +%48 = OpFunction %2 None %25 +%47 = OpLabel +%54 = OpVariable %53 Function %55 +%58 = OpVariable %53 Function %51 +%52 = OpVariable %53 Function %50 +%56 = OpVariable %53 Function %57 +%49 = OpAccessChain %26 %17 %27 +OpBranch %59 +%59 = OpLabel +%60 = OpLoad %4 %52 +OpStore %54 %60 +%61 = OpLoad %4 %54 +OpStore %56 %61 +%62 = OpLoad %4 %52 +%63 = OpLoad %4 %54 +%64 = OpLoad %4 %56 +%65 = OpLoad %4 %58 +%66 = OpCompositeConstruct %3 %62 %63 %64 %65 +%67 = OpLoad %3 %49 +%68 = OpIAdd %3 %67 %66 +OpStore %49 %68 OpReturn OpFunctionEnd -%69 = OpFunction %2 None %18 -%68 = OpLabel -%70 = OpAccessChain %19 %10 %20 -OpBranch %71 -%71 = OpLabel -OpStore %70 %66 +%70 = OpFunction %2 None %25 +%69 = OpLabel +%71 = OpAccessChain %26 %17 %27 +OpBranch %74 +%74 = OpLabel +OpStore %71 %73 OpReturn OpFunctionEnd -%73 = OpFunction %2 None %18 -%72 = OpLabel -%74 = OpAccessChain %19 %10 %20 -%75 = OpAccessChain %28 %13 %20 -OpBranch %76 -%76 = OpLabel -%77 = OpFunctionCall %2 %17 -%78 = OpFunctionCall %2 %27 -%79 = OpFunctionCall %2 %34 -%80 = OpFunctionCall %2 %41 -%81 = OpFunctionCall %2 %63 -%82 = OpFunctionCall %2 %69 +%76 = OpFunction %2 None %25 +%75 = OpLabel +%77 = OpAccessChain %26 %17 %27 +OpBranch %78 +%78 = OpLabel +OpStore %77 %73 +OpReturn +OpFunctionEnd +%80 = OpFunction %2 None %25 +%79 = OpLabel +%81 = OpAccessChain %26 %17 %27 +%82 = OpAccessChain %35 %20 %27 +OpBranch %83 +%83 = OpLabel +%84 = OpFunctionCall %2 %24 +%85 = OpFunctionCall %2 %34 +%86 = OpFunctionCall %2 %41 +%87 = OpFunctionCall %2 %48 +%88 = OpFunctionCall %2 %70 +%89 = OpFunctionCall %2 %76 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index df675a896..532883d9b 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -4,6 +4,9 @@ const FOUR: i32 = 4; const FOUR_ALIAS: i32 = 4; const TEST_CONSTANT_ADDITION: i32 = 8; const TEST_CONSTANT_ALIAS_ADDITION: i32 = 8; +const PI: f32 = 3.141; +const phi_sun: f32 = 6.282; +const DIV: vec4 = vec4(0.44444445, 0.0, 0.0, 0.0); @group(0) @binding(0) var out: vec4; From 4e95667a1cf53d5502af8f87a505f8ee91ec9491 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 29 Sep 2023 20:12:14 +0200 Subject: [PATCH 2148/2212] [wgsl] test usage of constants in switch cases --- tests/in/const-exprs.wgsl | 13 ++ tests/out/glsl/const-exprs.main.Compute.glsl | 20 ++ tests/out/hlsl/const-exprs.hlsl | 21 ++ tests/out/msl/const-exprs.msl | 22 ++ tests/out/spv/const-exprs.spvasm | 210 +++++++++++-------- tests/out/wgsl/const-exprs.wgsl | 20 ++ 6 files changed, 213 insertions(+), 93 deletions(-) diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl index 580eda184..e388c378a 100644 --- a/tests/in/const-exprs.wgsl +++ b/tests/in/const-exprs.wgsl @@ -69,3 +69,16 @@ const PI: f32 = 3.141; const phi_sun: f32 = PI * 2.0; const DIV: vec4f = vec4(4.0 / 9.0, 0.0, 0.0, 0.0); + +const TEXTURE_KIND_REGULAR: i32 = 0; +const TEXTURE_KIND_WARP: i32 = 1; +const TEXTURE_KIND_SKY: i32 = 2; + +fn map_texture_kind(texture_kind: i32) -> u32 { + switch (texture_kind) { + case TEXTURE_KIND_REGULAR: { return 10u; } + case TEXTURE_KIND_WARP: { return 20u; } + case TEXTURE_KIND_SKY: { return 30u; } + default: { return 0u; } + } +} diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index a9fbb3b77..738d0d7ef 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -14,6 +14,9 @@ const int TEST_CONSTANT_ALIAS_ADDITION = 8; const float PI = 3.141; const float phi_sun = 6.282; const vec4 DIV = vec4(0.44444445, 0.0, 0.0, 0.0); +const int TEXTURE_KIND_REGULAR = 0; +const int TEXTURE_KIND_WARP = 1; +const int TEXTURE_KIND_SKY = 2; layout(std430) buffer type_block_0Compute { ivec4 _group_0_binding_0_cs; }; @@ -65,6 +68,23 @@ void compose_of_constant() { return; } +uint map_texture_kind(int texture_kind) { + switch(texture_kind) { + case 0: { + return 10u; + } + case 1: { + return 20u; + } + case 2: { + return 30u; + } + default: { + return 0u; + } + } +} + void main() { swizzle_of_compose(); index_of_compose(); diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index ed1b86415..f3f59a584 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -7,6 +7,9 @@ static const int TEST_CONSTANT_ALIAS_ADDITION = 8; static const float PI = 3.141; static const float phi_sun = 6.282; static const float4 DIV = float4(0.44444445, 0.0, 0.0, 0.0); +static const int TEXTURE_KIND_REGULAR = 0; +static const int TEXTURE_KIND_WARP = 1; +static const int TEXTURE_KIND_SKY = 2; RWByteAddressBuffer out_ : register(u0); RWByteAddressBuffer out2_ : register(u1); @@ -63,6 +66,24 @@ void compose_of_constant() return; } +uint map_texture_kind(int texture_kind) +{ + switch(texture_kind) { + case 0: { + return 10u; + } + case 1: { + return 20u; + } + case 2: { + return 30u; + } + default: { + return 0u; + } + } +} + [numthreads(2, 3, 1)] void main() { diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 1707df1e8..48299e767 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -13,6 +13,9 @@ constant int TEST_CONSTANT_ALIAS_ADDITION = 8; constant float PI = 3.141; constant float phi_sun = 6.282; constant metal::float4 DIV = metal::float4(0.44444445, 0.0, 0.0, 0.0); +constant int TEXTURE_KIND_REGULAR = 0; +constant int TEXTURE_KIND_WARP = 1; +constant int TEXTURE_KIND_SKY = 2; void swizzle_of_compose( device metal::int4& out @@ -71,6 +74,25 @@ void compose_of_constant( return; } +uint map_texture_kind( + int texture_kind +) { + switch(texture_kind) { + case 0: { + return 10u; + } + case 1: { + return 20u; + } + case 2: { + return 30u; + } + default: { + return 0u; + } + } +} + kernel void main_( device metal::int4& out [[user(fake0)]] , device int& out2_ [[user(fake0)]] diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index f4103b868..b05f0f7df 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,21 +1,21 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 90 +; Bound: 105 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %80 "main" -OpExecutionMode %80 LocalSize 2 3 1 -OpDecorate %17 DescriptorSet 0 -OpDecorate %17 Binding 0 -OpDecorate %18 Block -OpMemberDecorate %18 0 Offset 0 +OpEntryPoint GLCompute %95 "main" +OpExecutionMode %95 LocalSize 2 3 1 OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 1 +OpDecorate %20 Binding 0 OpDecorate %21 Block OpMemberDecorate %21 0 Offset 0 +OpDecorate %23 DescriptorSet 0 +OpDecorate %23 Binding 1 +OpDecorate %24 Block +OpMemberDecorate %24 0 Offset 0 %2 = OpTypeVoid %4 = OpTypeInt 32 1 %3 = OpTypeVector %4 4 @@ -31,105 +31,129 @@ OpMemberDecorate %21 0 Offset 0 %14 = OpConstant %6 0.44444445 %15 = OpConstant %6 0.0 %16 = OpConstantComposite %7 %14 %15 %15 %15 -%18 = OpTypeStruct %3 -%19 = OpTypePointer StorageBuffer %18 -%17 = OpVariable %19 StorageBuffer -%21 = OpTypeStruct %4 +%17 = OpConstant %4 0 +%18 = OpConstant %4 1 +%19 = OpConstant %4 2 +%21 = OpTypeStruct %3 %22 = OpTypePointer StorageBuffer %21 %20 = OpVariable %22 StorageBuffer -%25 = OpTypeFunction %2 -%26 = OpTypePointer StorageBuffer %3 -%27 = OpConstant %5 0 -%29 = OpConstant %4 1 -%30 = OpConstant %4 2 -%31 = OpConstantComposite %3 %10 %9 %30 %29 -%35 = OpTypePointer StorageBuffer %4 -%43 = OpConstant %4 6 -%50 = OpConstant %4 30 -%51 = OpConstant %4 70 -%53 = OpTypePointer Function %4 -%55 = OpConstantNull %4 -%57 = OpConstantNull %4 -%72 = OpConstant %4 -4 -%73 = OpConstantComposite %3 %72 %72 %72 %72 -%24 = OpFunction %2 None %25 -%23 = OpLabel -%28 = OpAccessChain %26 %17 %27 -OpBranch %32 -%32 = OpLabel -OpStore %28 %31 -OpReturn -OpFunctionEnd -%34 = OpFunction %2 None %25 +%24 = OpTypeStruct %4 +%25 = OpTypePointer StorageBuffer %24 +%23 = OpVariable %25 StorageBuffer +%28 = OpTypeFunction %2 +%29 = OpTypePointer StorageBuffer %3 +%30 = OpConstant %5 0 +%32 = OpConstantComposite %3 %10 %9 %19 %18 +%36 = OpTypePointer StorageBuffer %4 +%44 = OpConstant %4 6 +%51 = OpConstant %4 30 +%52 = OpConstant %4 70 +%54 = OpTypePointer Function %4 +%56 = OpConstantNull %4 +%58 = OpConstantNull %4 +%73 = OpConstant %4 -4 +%74 = OpConstantComposite %3 %73 %73 %73 %73 +%83 = OpTypeFunction %5 %4 +%84 = OpConstant %5 10 +%85 = OpConstant %5 20 +%86 = OpConstant %5 30 +%93 = OpConstantNull %5 +%27 = OpFunction %2 None %28 +%26 = OpLabel +%31 = OpAccessChain %29 %20 %30 +OpBranch %33 %33 = OpLabel -%36 = OpAccessChain %35 %20 %27 -OpBranch %37 -%37 = OpLabel -%38 = OpLoad %4 %36 -%39 = OpIAdd %4 %38 %30 -OpStore %36 %39 +OpStore %31 %32 OpReturn OpFunctionEnd -%41 = OpFunction %2 None %25 -%40 = OpLabel -%42 = OpAccessChain %35 %20 %27 -OpBranch %44 -%44 = OpLabel -%45 = OpLoad %4 %42 -%46 = OpIAdd %4 %45 %43 -OpStore %42 %46 +%35 = OpFunction %2 None %28 +%34 = OpLabel +%37 = OpAccessChain %36 %23 %30 +OpBranch %38 +%38 = OpLabel +%39 = OpLoad %4 %37 +%40 = OpIAdd %4 %39 %19 +OpStore %37 %40 OpReturn OpFunctionEnd -%48 = OpFunction %2 None %25 -%47 = OpLabel -%54 = OpVariable %53 Function %55 -%58 = OpVariable %53 Function %51 -%52 = OpVariable %53 Function %50 -%56 = OpVariable %53 Function %57 -%49 = OpAccessChain %26 %17 %27 -OpBranch %59 -%59 = OpLabel -%60 = OpLoad %4 %52 -OpStore %54 %60 -%61 = OpLoad %4 %54 -OpStore %56 %61 -%62 = OpLoad %4 %52 -%63 = OpLoad %4 %54 -%64 = OpLoad %4 %56 -%65 = OpLoad %4 %58 -%66 = OpCompositeConstruct %3 %62 %63 %64 %65 -%67 = OpLoad %3 %49 -%68 = OpIAdd %3 %67 %66 -OpStore %49 %68 +%42 = OpFunction %2 None %28 +%41 = OpLabel +%43 = OpAccessChain %36 %23 %30 +OpBranch %45 +%45 = OpLabel +%46 = OpLoad %4 %43 +%47 = OpIAdd %4 %46 %44 +OpStore %43 %47 OpReturn OpFunctionEnd -%70 = OpFunction %2 None %25 -%69 = OpLabel -%71 = OpAccessChain %26 %17 %27 -OpBranch %74 -%74 = OpLabel -OpStore %71 %73 +%49 = OpFunction %2 None %28 +%48 = OpLabel +%55 = OpVariable %54 Function %56 +%59 = OpVariable %54 Function %52 +%53 = OpVariable %54 Function %51 +%57 = OpVariable %54 Function %58 +%50 = OpAccessChain %29 %20 %30 +OpBranch %60 +%60 = OpLabel +%61 = OpLoad %4 %53 +OpStore %55 %61 +%62 = OpLoad %4 %55 +OpStore %57 %62 +%63 = OpLoad %4 %53 +%64 = OpLoad %4 %55 +%65 = OpLoad %4 %57 +%66 = OpLoad %4 %59 +%67 = OpCompositeConstruct %3 %63 %64 %65 %66 +%68 = OpLoad %3 %50 +%69 = OpIAdd %3 %68 %67 +OpStore %50 %69 OpReturn OpFunctionEnd -%76 = OpFunction %2 None %25 +%71 = OpFunction %2 None %28 +%70 = OpLabel +%72 = OpAccessChain %29 %20 %30 +OpBranch %75 %75 = OpLabel -%77 = OpAccessChain %26 %17 %27 -OpBranch %78 -%78 = OpLabel -OpStore %77 %73 +OpStore %72 %74 OpReturn OpFunctionEnd -%80 = OpFunction %2 None %25 +%77 = OpFunction %2 None %28 +%76 = OpLabel +%78 = OpAccessChain %29 %20 %30 +OpBranch %79 %79 = OpLabel -%81 = OpAccessChain %26 %17 %27 -%82 = OpAccessChain %35 %20 %27 -OpBranch %83 -%83 = OpLabel -%84 = OpFunctionCall %2 %24 -%85 = OpFunctionCall %2 %34 -%86 = OpFunctionCall %2 %41 -%87 = OpFunctionCall %2 %48 -%88 = OpFunctionCall %2 %70 -%89 = OpFunctionCall %2 %76 +OpStore %78 %74 +OpReturn +OpFunctionEnd +%82 = OpFunction %5 None %83 +%81 = OpFunctionParameter %4 +%80 = OpLabel +OpBranch %87 +%87 = OpLabel +OpSelectionMerge %88 None +OpSwitch %81 %92 0 %89 1 %90 2 %91 +%89 = OpLabel +OpReturnValue %84 +%90 = OpLabel +OpReturnValue %85 +%91 = OpLabel +OpReturnValue %86 +%92 = OpLabel +OpReturnValue %30 +%88 = OpLabel +OpReturnValue %93 +OpFunctionEnd +%95 = OpFunction %2 None %28 +%94 = OpLabel +%96 = OpAccessChain %29 %20 %30 +%97 = OpAccessChain %36 %23 %30 +OpBranch %98 +%98 = OpLabel +%99 = OpFunctionCall %2 %27 +%100 = OpFunctionCall %2 %35 +%101 = OpFunctionCall %2 %42 +%102 = OpFunctionCall %2 %49 +%103 = OpFunctionCall %2 %71 +%104 = OpFunctionCall %2 %77 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index 532883d9b..569d08264 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -7,6 +7,9 @@ const TEST_CONSTANT_ALIAS_ADDITION: i32 = 8; const PI: f32 = 3.141; const phi_sun: f32 = 6.282; const DIV: vec4 = vec4(0.44444445, 0.0, 0.0, 0.0); +const TEXTURE_KIND_REGULAR: i32 = 0; +const TEXTURE_KIND_WARP: i32 = 1; +const TEXTURE_KIND_SKY: i32 = 2; @group(0) @binding(0) var out: vec4; @@ -59,6 +62,23 @@ fn compose_of_constant() { return; } +fn map_texture_kind(texture_kind: i32) -> u32 { + switch texture_kind { + case 0: { + return 10u; + } + case 1: { + return 20u; + } + case 2: { + return 30u; + } + default: { + return 0u; + } + } +} + @compute @workgroup_size(2, 3, 1) fn main() { swizzle_of_compose(); From c2141ab804e24fe66c49aa8c14e734cfe73001b8 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:31:02 +0200 Subject: [PATCH 2149/2212] [const-eval] add wgsl/glsl behavior switch to evaluator --- src/front/glsl/context.rs | 4 +- src/front/wgsl/lower/mod.rs | 4 +- src/proc/constant_evaluator.rs | 120 +++++++++++++++++++++++++-------- 3 files changed, 97 insertions(+), 31 deletions(-) diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 871d110c7..0eceb24e4 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -249,9 +249,9 @@ impl<'a> Context<'a> { pub fn add_expression(&mut self, expr: Expression, meta: Span) -> Result> { let mut eval = if self.is_const { - crate::proc::ConstantEvaluator::for_module(self.module) + crate::proc::ConstantEvaluator::for_glsl_module(self.module) } else { - crate::proc::ConstantEvaluator::for_function( + crate::proc::ConstantEvaluator::for_glsl_function( self.module, &mut self.expressions, &mut self.expression_constness, diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index fe0c4f92d..94118e65e 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -340,7 +340,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { ) -> Result, Error<'source>> { match self.expr_type { ExpressionContextType::Runtime(ref mut rctx) => { - let mut eval = ConstantEvaluator::for_function( + let mut eval = ConstantEvaluator::for_wgsl_function( self.module, rctx.naga_expressions, rctx.expression_constness, @@ -354,7 +354,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { } } ExpressionContextType::Constant => { - let mut eval = ConstantEvaluator::for_module(self.module); + let mut eval = ConstantEvaluator::for_wgsl_module(self.module); eval.try_eval_and_append(&expr, span) .map_err(|e| Error::ConstantEvaluatorError(e, span)) } diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 6453989b3..05d657cd9 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -4,8 +4,15 @@ use crate::{ UnaryOperator, }; +#[derive(Debug)] +enum Behavior { + Wgsl, + Glsl, +} + #[derive(Debug)] pub struct ConstantEvaluator<'a> { + behavior: Behavior, types: &'a mut UniqueArena, constants: &'a Arena, expressions: &'a mut Arena, @@ -109,6 +116,8 @@ pub enum ConstantEvaluatorError { InvalidAccessIndexTy, #[error("Constants don't support bitcasts")] Bitcast, + #[error("Constants don't support array length expressions")] + ArrayLength, #[error("Cannot cast type")] InvalidCastArg, #[error("Cannot apply the unary op to the argument")] @@ -131,20 +140,18 @@ pub enum ConstantEvaluatorError { NotImplemented(String), } -// Access -// AccessIndex -// Splat -// Swizzle -// Unary -// Binary -// Select -// Relational -// Math -// As - impl<'a> ConstantEvaluator<'a> { - pub fn for_module(module: &'a mut crate::Module) -> Self { + pub fn for_wgsl_module(module: &'a mut crate::Module) -> Self { + Self::for_module(Behavior::Wgsl, module) + } + + pub fn for_glsl_module(module: &'a mut crate::Module) -> Self { + Self::for_module(Behavior::Glsl, module) + } + + fn for_module(behavior: Behavior, module: &'a mut crate::Module) -> Self { Self { + behavior, types: &mut module.types, constants: &module.constants, expressions: &mut module.const_expressions, @@ -152,7 +159,42 @@ impl<'a> ConstantEvaluator<'a> { } } - pub fn for_function( + pub fn for_wgsl_function( + module: &'a mut crate::Module, + expressions: &'a mut Arena, + expression_constness: &'a mut ExpressionConstnessTracker, + emitter: &'a mut super::Emitter, + block: &'a mut crate::Block, + ) -> Self { + Self::for_function( + Behavior::Wgsl, + module, + expressions, + expression_constness, + emitter, + block, + ) + } + + pub fn for_glsl_function( + module: &'a mut crate::Module, + expressions: &'a mut Arena, + expression_constness: &'a mut ExpressionConstnessTracker, + emitter: &'a mut super::Emitter, + block: &'a mut crate::Block, + ) -> Self { + Self::for_function( + Behavior::Glsl, + module, + expressions, + expression_constness, + emitter, + block, + ) + } + + fn for_function( + behavior: Behavior, module: &'a mut crate::Module, expressions: &'a mut Arena, expression_constness: &'a mut ExpressionConstnessTracker, @@ -160,6 +202,7 @@ impl<'a> ConstantEvaluator<'a> { block: &'a mut crate::Block, ) -> Self { Self { + behavior, types: &mut module.types, constants: &module.constants, expressions, @@ -288,20 +331,36 @@ impl<'a> ConstantEvaluator<'a> { match convert { Some(width) => self.cast(expr, kind, width, span), - None => Err(ConstantEvaluatorError::Bitcast), + None => match self.behavior { + Behavior::Wgsl => Err(ConstantEvaluatorError::NotImplemented( + "bitcast built-in function".into(), + )), + Behavior::Glsl => Err(ConstantEvaluatorError::Bitcast), + }, } } - Expression::ArrayLength(expr) => { - let expr = self.check_and_get(expr)?; - - self.array_length(expr, span) - } - + Expression::Select { .. } => match self.behavior { + Behavior::Wgsl => Err(ConstantEvaluatorError::NotImplemented( + "select built-in function".into(), + )), + Behavior::Glsl => Err(ConstantEvaluatorError::Select), + }, + Expression::Relational { fun, .. } => match self.behavior { + Behavior::Wgsl => Err(ConstantEvaluatorError::NotImplemented(format!( + "{fun:?} built-in function" + ))), + Behavior::Glsl => Err(ConstantEvaluatorError::Relational), + }, + Expression::ArrayLength(expr) => match self.behavior { + Behavior::Wgsl => Err(ConstantEvaluatorError::ArrayLength), + Behavior::Glsl => { + let expr = self.check_and_get(expr)?; + self.array_length(expr, span) + } + }, Expression::Load { .. } => Err(ConstantEvaluatorError::Load), - Expression::Select { .. } => Err(ConstantEvaluatorError::Select), Expression::LocalVariable(_) => Err(ConstantEvaluatorError::LocalVariable), Expression::Derivative { .. } => Err(ConstantEvaluatorError::Derivative), - Expression::Relational { .. } => Err(ConstantEvaluatorError::Relational), Expression::CallResult { .. } => Err(ConstantEvaluatorError::Call), Expression::WorkGroupUniformLoadResult { .. } => { Err(ConstantEvaluatorError::WorkGroupUniformLoadResult) @@ -468,16 +527,18 @@ impl<'a> ConstantEvaluator<'a> { _ => return Err(ConstantEvaluatorError::InvalidMathArg), }, _ => { - return Err(ConstantEvaluatorError::NotImplemented(format!( - "{fun:?} applied to vector values" - ))) + return Err(ConstantEvaluatorError::NotImplemented( + "clamp built-in function with vector values".into(), + )) } }; let expr = Expression::Literal(literal); Ok(self.register_evaluated_expr(expr, span)) } - _ => Err(ConstantEvaluatorError::NotImplemented(format!("{fun:?}"))), + fun => Err(ConstantEvaluatorError::NotImplemented(format!( + "{fun:?} built-in function" + ))), } } @@ -999,7 +1060,7 @@ mod tests { UniqueArena, VectorSize, }; - use super::ConstantEvaluator; + use super::{Behavior, ConstantEvaluator}; #[test] fn nan_handling() { @@ -1100,6 +1161,7 @@ mod tests { }; let mut solver = ConstantEvaluator { + behavior: Behavior::Wgsl, types: &mut types, constants: &constants, expressions: &mut const_expressions, @@ -1186,6 +1248,7 @@ mod tests { }; let mut solver = ConstantEvaluator { + behavior: Behavior::Wgsl, types: &mut types, constants: &constants, expressions: &mut const_expressions, @@ -1304,6 +1367,7 @@ mod tests { let base = const_expressions.append(Expression::Constant(h), Default::default()); let mut solver = ConstantEvaluator { + behavior: Behavior::Wgsl, types: &mut types, constants: &constants, expressions: &mut const_expressions, @@ -1398,6 +1462,7 @@ mod tests { let h_expr = const_expressions.append(Expression::Constant(h), Default::default()); let mut solver = ConstantEvaluator { + behavior: Behavior::Wgsl, types: &mut types, constants: &constants, expressions: &mut const_expressions, @@ -1481,6 +1546,7 @@ mod tests { let h_expr = const_expressions.append(Expression::Constant(h), Default::default()); let mut solver = ConstantEvaluator { + behavior: Behavior::Wgsl, types: &mut types, constants: &constants, expressions: &mut const_expressions, From d50c3843285633ce9b2cce0097e5195a353713a5 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:56:37 +0200 Subject: [PATCH 2150/2212] [const-eval] check number of arguments for math functions --- src/proc/constant_evaluator.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 05d657cd9..43aae48d2 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -126,6 +126,8 @@ pub enum ConstantEvaluatorError { InvalidBinaryOpArgs, #[error("Cannot apply math function to type")] InvalidMathArg, + #[error("{0:?} built-in function expects {1:?} arguments but {2:?} were supplied")] + InvalidMathArgCount(crate::MathFunction, usize, usize), #[error("Splat is defined only on scalar values")] SplatScalarOnly, #[error("Can only swizzle vector constants")] @@ -486,6 +488,19 @@ impl<'a> ConstantEvaluator<'a> { fun: crate::MathFunction, span: Span, ) -> Result, ConstantEvaluatorError> { + let expected = fun.argument_count(); + let given = Some(arg) + .into_iter() + .chain(arg1) + .chain(arg2) + .chain(arg3) + .count(); + if expected != given { + return Err(ConstantEvaluatorError::InvalidMathArgCount( + fun, expected, given, + )); + } + let const0 = &self.expressions[arg]; let const1 = arg1.map(|arg| &self.expressions[arg]); let const2 = arg2.map(|arg| &self.expressions[arg]); From c46a69d9938f229f8e0727f83709b37097746c41 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Oct 2023 01:29:06 +0200 Subject: [PATCH 2151/2212] [const-eval] account for `ZeroValue` index for `AccessIndex` expression --- src/proc/constant_evaluator.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 43aae48d2..3b0fd7860 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -632,6 +632,17 @@ impl<'a> ConstantEvaluator<'a> { fn constant_index(&self, expr: Handle) -> Result { match self.expressions[expr] { + Expression::ZeroValue(ty) + if matches!( + self.types[ty].inner, + crate::TypeInner::Scalar { + kind: crate::ScalarKind::Uint, + .. + } + ) => + { + Ok(0) + } Expression::Literal(Literal::U32(index)) => Ok(index as usize), _ => Err(ConstantEvaluatorError::InvalidAccessIndexTy), } From 4945b7a8033f4e9d72b747d01ddfbb8a4cc9b9f2 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Oct 2023 01:34:13 +0200 Subject: [PATCH 2152/2212] [const-eval] implement `pow` & `clamp` built-in functions properly --- src/proc/constant_evaluator.rs | 287 ++++++++++++++++++++------------- 1 file changed, 174 insertions(+), 113 deletions(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 3b0fd7860..9ed068be7 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -128,6 +128,8 @@ pub enum ConstantEvaluatorError { InvalidMathArg, #[error("{0:?} built-in function expects {1:?} arguments but {2:?} were supplied")] InvalidMathArgCount(crate::MathFunction, usize, usize), + #[error("value of `low` is greater than `high` for clamp built-in function")] + InvalidClamp, #[error("Splat is defined only on scalar values")] SplatScalarOnly, #[error("Can only swizzle vector constants")] @@ -501,62 +503,183 @@ impl<'a> ConstantEvaluator<'a> { )); } - let const0 = &self.expressions[arg]; - let const1 = arg1.map(|arg| &self.expressions[arg]); - let const2 = arg2.map(|arg| &self.expressions[arg]); - let _const3 = arg3.map(|arg| &self.expressions[arg]); - match fun { - crate::MathFunction::Pow => { - let literal = match (const0, const1.unwrap()) { - (&Expression::Literal(value0), &Expression::Literal(value1)) => { - match (value0, value1) { - (Literal::I32(a), Literal::I32(b)) => Literal::I32(a.pow(b as u32)), - (Literal::U32(a), Literal::U32(b)) => Literal::U32(a.pow(b)), - (Literal::F32(a), Literal::F32(b)) => Literal::F32(a.powf(b)), - _ => return Err(ConstantEvaluatorError::InvalidMathArg), - } - } - _ => return Err(ConstantEvaluatorError::InvalidMathArg), - }; - - let expr = Expression::Literal(literal); - Ok(self.register_evaluated_expr(expr, span)) - } - crate::MathFunction::Clamp => { - let literal = match (const0, const1.unwrap(), const2.unwrap()) { - ( - &Expression::Literal(value0), - &Expression::Literal(value1), - &Expression::Literal(value2), - ) => match (value0, value1, value2) { - (Literal::I32(a), Literal::I32(b), Literal::I32(c)) => { - Literal::I32(a.clamp(b, c)) - } - (Literal::U32(a), Literal::U32(b), Literal::U32(c)) => { - Literal::U32(a.clamp(b, c)) - } - (Literal::F32(a), Literal::F32(b), Literal::F32(c)) => { - Literal::F32(glsl_float_clamp(a, b, c)) - } - _ => return Err(ConstantEvaluatorError::InvalidMathArg), - }, - _ => { - return Err(ConstantEvaluatorError::NotImplemented( - "clamp built-in function with vector values".into(), - )) - } - }; - - let expr = Expression::Literal(literal); - Ok(self.register_evaluated_expr(expr, span)) - } + crate::MathFunction::Pow => self.math_pow(arg, arg1.unwrap(), span), + crate::MathFunction::Clamp => self.math_clamp(arg, arg1.unwrap(), arg2.unwrap(), span), fun => Err(ConstantEvaluatorError::NotImplemented(format!( "{fun:?} built-in function" ))), } } + fn math_pow( + &mut self, + e1: Handle, + e2: Handle, + span: Span, + ) -> Result, ConstantEvaluatorError> { + let e1 = self.eval_zero_value_and_splat(e1, span)?; + let e2 = self.eval_zero_value_and_splat(e2, span)?; + + let expr = match (&self.expressions[e1], &self.expressions[e2]) { + (&Expression::Literal(Literal::F32(a)), &Expression::Literal(Literal::F32(b))) => { + Expression::Literal(Literal::F32(a.powf(b))) + } + ( + &Expression::Compose { + components: ref src_components0, + ty: ty0, + }, + &Expression::Compose { + components: ref src_components1, + ty: ty1, + }, + ) if ty0 == ty1 + && matches!( + self.types[ty0].inner, + crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + .. + } + ) => + { + let mut components: Vec<_> = crate::proc::flatten_compose( + ty0, + src_components0, + self.expressions, + self.types, + ) + .chain(crate::proc::flatten_compose( + ty1, + src_components1, + self.expressions, + self.types, + )) + .collect(); + + let mid = components.len() / 2; + let (first, last) = components.split_at_mut(mid); + for (a, b) in first.iter_mut().zip(&*last) { + *a = self.math_pow(*a, *b, span)?; + } + components.truncate(mid); + + Expression::Compose { + ty: ty0, + components, + } + } + _ => return Err(ConstantEvaluatorError::InvalidMathArg), + }; + + Ok(self.register_evaluated_expr(expr, span)) + } + + fn math_clamp( + &mut self, + e: Handle, + low: Handle, + high: Handle, + span: Span, + ) -> Result, ConstantEvaluatorError> { + let e = self.eval_zero_value_and_splat(e, span)?; + let low = self.eval_zero_value_and_splat(low, span)?; + let high = self.eval_zero_value_and_splat(high, span)?; + + let expr = match ( + &self.expressions[e], + &self.expressions[low], + &self.expressions[high], + ) { + (&Expression::Literal(e), &Expression::Literal(low), &Expression::Literal(high)) => { + let literal = match (e, low, high) { + (Literal::I32(e), Literal::I32(low), Literal::I32(high)) => { + if low > high { + return Err(ConstantEvaluatorError::InvalidClamp); + } else { + Literal::I32(e.clamp(low, high)) + } + } + (Literal::U32(e), Literal::U32(low), Literal::U32(high)) => { + if low > high { + return Err(ConstantEvaluatorError::InvalidClamp); + } else { + Literal::U32(e.clamp(low, high)) + } + } + (Literal::F32(e), Literal::F32(low), Literal::F32(high)) => { + if low > high { + return Err(ConstantEvaluatorError::InvalidClamp); + } else { + Literal::F32(e.clamp(low, high)) + } + } + _ => return Err(ConstantEvaluatorError::InvalidMathArg), + }; + Expression::Literal(literal) + } + ( + &Expression::Compose { + components: ref src_components0, + ty: ty0, + }, + &Expression::Compose { + components: ref src_components1, + ty: ty1, + }, + &Expression::Compose { + components: ref src_components2, + ty: ty2, + }, + ) if ty0 == ty1 + && ty0 == ty2 + && matches!( + self.types[ty0].inner, + crate::TypeInner::Vector { + kind: crate::ScalarKind::Float, + .. + } + ) => + { + let mut components: Vec<_> = crate::proc::flatten_compose( + ty0, + src_components0, + self.expressions, + self.types, + ) + .chain(crate::proc::flatten_compose( + ty1, + src_components1, + self.expressions, + self.types, + )) + .chain(crate::proc::flatten_compose( + ty2, + src_components2, + self.expressions, + self.types, + )) + .collect(); + + let chunk_size = components.len() / 3; + let (es, rem) = components.split_at_mut(chunk_size); + let (lows, highs) = rem.split_at(chunk_size); + for ((e, low), high) in es.iter_mut().zip(lows).zip(highs) { + *e = self.math_clamp(*e, *low, *high, span)?; + } + components.truncate(chunk_size); + + Expression::Compose { + ty: ty0, + components, + } + } + _ => return Err(ConstantEvaluatorError::InvalidMathArg), + }; + + Ok(self.register_evaluated_expr(expr, span)) + } + fn array_length( &mut self, array: Handle, @@ -1000,6 +1123,8 @@ impl<'a> ConstantEvaluator<'a> { } fn register_evaluated_expr(&mut self, expr: Expression, span: Span) -> Handle { + // TODO: use the validate_literal function from https://github.com/gfx-rs/naga/pull/2508 here + if let Some(FunctionLocalData { ref mut emitter, ref mut block, @@ -1026,57 +1151,6 @@ impl<'a> ConstantEvaluator<'a> { } } -/// Helper function to implement the GLSL `max` function for floats. -/// -/// While Rust does provide a `f64::max` method, it has a different behavior than the -/// GLSL `max` for NaNs. In Rust, if any of the arguments is a NaN, then the other -/// is returned. -/// -/// This leads to different results in the following example -/// ``` -/// use std::cmp::max; -/// std::f64::NAN.max(1.0); -/// ``` -/// -/// Rust will return `1.0` while GLSL should return NaN. -fn glsl_float_max(x: f32, y: f32) -> f32 { - if x < y { - y - } else { - x - } -} - -/// Helper function to implement the GLSL `min` function for floats. -/// -/// While Rust does provide a `f64::min` method, it has a different behavior than the -/// GLSL `min` for NaNs. In Rust, if any of the arguments is a NaN, then the other -/// is returned. -/// -/// This leads to different results in the following example -/// ``` -/// use std::cmp::min; -/// std::f64::NAN.min(1.0); -/// ``` -/// -/// Rust will return `1.0` while GLSL should return NaN. -fn glsl_float_min(x: f32, y: f32) -> f32 { - if y < x { - y - } else { - x - } -} - -/// Helper function to implement the GLSL `clamp` function for floats. -/// -/// While Rust does provide a `f64::clamp` method, it panics if either -/// `min` or `max` are `NaN`s which is not the behavior specified by -/// the glsl specification. -fn glsl_float_clamp(value: f32, min: f32, max: f32) -> f32 { - glsl_float_min(glsl_float_max(value, min), max) -} - #[cfg(test)] mod tests { use std::vec; @@ -1088,19 +1162,6 @@ mod tests { use super::{Behavior, ConstantEvaluator}; - #[test] - fn nan_handling() { - assert!(super::glsl_float_max(f32::NAN, 2.0).is_nan()); - assert!(!super::glsl_float_max(2.0, f32::NAN).is_nan()); - - assert!(super::glsl_float_min(f32::NAN, 2.0).is_nan()); - assert!(!super::glsl_float_min(2.0, f32::NAN).is_nan()); - - assert!(super::glsl_float_clamp(f32::NAN, 1.0, 2.0).is_nan()); - assert!(!super::glsl_float_clamp(1.0, f32::NAN, 2.0).is_nan()); - assert!(!super::glsl_float_clamp(1.0, 2.0, f32::NAN).is_nan()); - } - #[test] fn unary_op() { let mut types = UniqueArena::new(); From a9c28d47c37554fda3947e981f344c5c1e24a8b6 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Oct 2023 01:54:52 +0200 Subject: [PATCH 2153/2212] [const-eval] allow bitcast, select and relational functions for GLSL since they should be supported --- src/proc/constant_evaluator.rs | 33 +++++++++------------------------ 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 9ed068be7..d4e4acd8d 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -96,12 +96,8 @@ pub enum ConstantEvaluatorError { WorkGroupUniformLoadResult, #[error("Constants don't support atomic functions")] Atomic, - #[error("Constants don't support relational functions")] - Relational, #[error("Constants don't support derivative functions")] Derivative, - #[error("Constants don't support select expressions")] - Select, #[error("Constants don't support load expressions")] Load, #[error("Constants don't support image expressions")] @@ -114,8 +110,6 @@ pub enum ConstantEvaluatorError { InvalidAccessIndex, #[error("Cannot access with index of type")] InvalidAccessIndexTy, - #[error("Constants don't support bitcasts")] - Bitcast, #[error("Constants don't support array length expressions")] ArrayLength, #[error("Cannot cast type")] @@ -335,26 +329,17 @@ impl<'a> ConstantEvaluator<'a> { match convert { Some(width) => self.cast(expr, kind, width, span), - None => match self.behavior { - Behavior::Wgsl => Err(ConstantEvaluatorError::NotImplemented( - "bitcast built-in function".into(), - )), - Behavior::Glsl => Err(ConstantEvaluatorError::Bitcast), - }, + None => Err(ConstantEvaluatorError::NotImplemented( + "bitcast built-in function".into(), + )), } } - Expression::Select { .. } => match self.behavior { - Behavior::Wgsl => Err(ConstantEvaluatorError::NotImplemented( - "select built-in function".into(), - )), - Behavior::Glsl => Err(ConstantEvaluatorError::Select), - }, - Expression::Relational { fun, .. } => match self.behavior { - Behavior::Wgsl => Err(ConstantEvaluatorError::NotImplemented(format!( - "{fun:?} built-in function" - ))), - Behavior::Glsl => Err(ConstantEvaluatorError::Relational), - }, + Expression::Select { .. } => Err(ConstantEvaluatorError::NotImplemented( + "select built-in function".into(), + )), + Expression::Relational { fun, .. } => Err(ConstantEvaluatorError::NotImplemented( + format!("{fun:?} built-in function"), + )), Expression::ArrayLength(expr) => match self.behavior { Behavior::Wgsl => Err(ConstantEvaluatorError::ArrayLength), Behavior::Glsl => { From 13a0ed4eaea0852cc83079125f82b7e36b6683e2 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Oct 2023 03:05:52 +0200 Subject: [PATCH 2154/2212] [const-eval] evaluate `BinaryOperator::Modulo` correctly (use the truncated version instead of floored) --- src/proc/constant_evaluator.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index d4e4acd8d..b3c63e8e4 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -1027,7 +1027,7 @@ impl<'a> ConstantEvaluator<'a> { BinaryOperator::Subtract => a - b, BinaryOperator::Multiply => a * b, BinaryOperator::Divide => a / b, - BinaryOperator::Modulo => a - b * (a / b).floor(), + BinaryOperator::Modulo => a % b, _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }), (Literal::Bool(a), Literal::Bool(b)) => Literal::Bool(match op { From c5b2afaf783b7ad6882bda252d960b2baecfa544 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Oct 2023 03:47:15 +0200 Subject: [PATCH 2155/2212] [const-eval] error on invalid binary operations --- src/proc/constant_evaluator.rs | 72 +++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 14 deletions(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index b3c63e8e4..eb45179b7 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -136,6 +136,14 @@ pub enum ConstantEvaluatorError { SubexpressionsAreNotConstant, #[error("Not implemented as constant expression: {0}")] NotImplemented(String), + #[error("{0} operation overflowed")] + Overflow(String), + #[error("Division by zero")] + DivisionByZero, + #[error("Remainder by zero")] + RemainderByZero, + #[error("RHS of shift operation is greater than or equal to 32")] + ShiftedMoreThan32Bits, } impl<'a> ConstantEvaluator<'a> { @@ -994,32 +1002,68 @@ impl<'a> ConstantEvaluator<'a> { _ => match (left_value, right_value) { (Literal::I32(a), Literal::I32(b)) => Literal::I32(match op { - BinaryOperator::Add => a.wrapping_add(b), - BinaryOperator::Subtract => a.wrapping_sub(b), - BinaryOperator::Multiply => a.wrapping_mul(b), - BinaryOperator::Divide => a.checked_div(b).unwrap_or(0), - BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0), + BinaryOperator::Add => a.checked_add(b).ok_or_else(|| { + ConstantEvaluatorError::Overflow("addition".into()) + })?, + BinaryOperator::Subtract => a.checked_sub(b).ok_or_else(|| { + ConstantEvaluatorError::Overflow("subtraction".into()) + })?, + BinaryOperator::Multiply => a.checked_mul(b).ok_or_else(|| { + ConstantEvaluatorError::Overflow("multiplication".into()) + })?, + BinaryOperator::Divide => a.checked_div(b).ok_or_else(|| { + if b == 0 { + ConstantEvaluatorError::DivisionByZero + } else { + ConstantEvaluatorError::Overflow("division".into()) + } + })?, + BinaryOperator::Modulo => a.checked_rem(b).ok_or_else(|| { + if b == 0 { + ConstantEvaluatorError::RemainderByZero + } else { + ConstantEvaluatorError::Overflow("remainder".into()) + } + })?, BinaryOperator::And => a & b, BinaryOperator::ExclusiveOr => a ^ b, BinaryOperator::InclusiveOr => a | b, _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }), (Literal::I32(a), Literal::U32(b)) => Literal::I32(match op { - BinaryOperator::ShiftLeft => a.wrapping_shl(b), - BinaryOperator::ShiftRight => a.wrapping_shr(b), + BinaryOperator::ShiftLeft => a + .checked_shl(b) + .ok_or(ConstantEvaluatorError::ShiftedMoreThan32Bits)?, + BinaryOperator::ShiftRight => a + .checked_shr(b) + .ok_or(ConstantEvaluatorError::ShiftedMoreThan32Bits)?, _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }), (Literal::U32(a), Literal::U32(b)) => Literal::U32(match op { - BinaryOperator::Add => a.wrapping_add(b), - BinaryOperator::Subtract => a.wrapping_sub(b), - BinaryOperator::Multiply => a.wrapping_mul(b), - BinaryOperator::Divide => a.checked_div(b).unwrap_or(0), - BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0), + BinaryOperator::Add => a.checked_add(b).ok_or_else(|| { + ConstantEvaluatorError::Overflow("addition".into()) + })?, + BinaryOperator::Subtract => a.checked_sub(b).ok_or_else(|| { + ConstantEvaluatorError::Overflow("subtraction".into()) + })?, + BinaryOperator::Multiply => a.checked_mul(b).ok_or_else(|| { + ConstantEvaluatorError::Overflow("multiplication".into()) + })?, + BinaryOperator::Divide => a + .checked_div(b) + .ok_or(ConstantEvaluatorError::DivisionByZero)?, + BinaryOperator::Modulo => a + .checked_rem(b) + .ok_or(ConstantEvaluatorError::RemainderByZero)?, BinaryOperator::And => a & b, BinaryOperator::ExclusiveOr => a ^ b, BinaryOperator::InclusiveOr => a | b, - BinaryOperator::ShiftLeft => a.wrapping_shl(b), - BinaryOperator::ShiftRight => a.wrapping_shr(b), + BinaryOperator::ShiftLeft => a + .checked_shl(b) + .ok_or(ConstantEvaluatorError::ShiftedMoreThan32Bits)?, + BinaryOperator::ShiftRight => a + .checked_shr(b) + .ok_or(ConstantEvaluatorError::ShiftedMoreThan32Bits)?, _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }), (Literal::F32(a), Literal::F32(b)) => Literal::F32(match op { From ca2e8104923d3712b71331fc80c60e5e75c67355 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 5 Oct 2023 14:03:07 -0700 Subject: [PATCH 2156/2212] Properly recognize `Literal` expressions as non-dynamic indices. (#2537) Restore `negative_index` test in `tests/wgsl-errors.rs`, as part of the `invalid_arrays` test function. --- src/proc/mod.rs | 12 +++++++----- tests/wgsl-errors.rs | 39 ++++++++++++++++++++------------------- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 481ea8902..d50f165a5 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -466,11 +466,13 @@ impl crate::Expression { /// [`Access`]: crate::Expression::Access /// [`ResolveContext`]: crate::proc::ResolveContext pub fn is_dynamic_index(&self, module: &crate::Module) -> bool { - if let Self::Constant(handle) = *self { - let constant = &module.constants[handle]; - !matches!(constant.r#override, crate::Override::None) - } else { - true + match *self { + Self::Literal(_) | Self::ZeroValue(_) => false, + Self::Constant(handle) => { + let constant = &module.constants[handle]; + !matches!(constant.r#override, crate::Override::None) + } + _ => true, } } } diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 9e5eecccc..90785d4f2 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -107,25 +107,6 @@ fn unknown_identifier() { ); } -// #[test] -// fn negative_index() { -// check( -// r#" -// fn main() -> f32 { -// let a = array(0., 1., 2.); -// return a[-1]; -// } -// "#, -// r#"error: expected unsigned integer constant expression, found `-1` -// ┌─ wgsl:4:26 -// │ -// 4 │ return a[-1]; -// │ ^^ expected unsigned integer - -// "#, -// ); -// } - #[test] fn bad_texture() { check( @@ -921,6 +902,26 @@ fn invalid_arrays() { }) } + check_validation! { + r#" + fn main() -> f32 { + let a = array(0., 1., 2.); + return a[-1]; + } + "#: + Err( + naga::valid::ValidationError::Function { + name, + source: naga::valid::FunctionError::Expression { + source: naga::valid::ExpressionError::NegativeIndex(_), + .. + }, + .. + } + ) + if name == "main" + } + check( "alias Bad = array;", r###"error: must be a const-expression that resolves to a concrete integer scalar (u32 or i32) From d8ceeae3b2a6b46226f452d13c0770406d61998e Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Oct 2023 23:46:02 +0200 Subject: [PATCH 2157/2212] Avoid FXC's error X3694: race condition writing to shared resource detected --- tests/in/const-exprs.wgsl | 35 ++- tests/out/glsl/const-exprs.main.Compute.glsl | 33 +-- tests/out/hlsl/const-exprs.hlsl | 37 ++-- tests/out/msl/const-exprs.msl | 49 ++--- tests/out/spv/const-exprs.spvasm | 216 ++++++++----------- tests/out/wgsl/const-exprs.wgsl | 39 ++-- 6 files changed, 170 insertions(+), 239 deletions(-) diff --git a/tests/in/const-exprs.wgsl b/tests/in/const-exprs.wgsl index e388c378a..24d48665e 100644 --- a/tests/in/const-exprs.wgsl +++ b/tests/in/const-exprs.wgsl @@ -1,32 +1,29 @@ -@group(0) @binding(0) var out: vec4; -@group(0) @binding(1) var out2: i32; - const TWO: u32 = 2u; const THREE: i32 = 3i; @compute @workgroup_size(TWO, THREE, TWO - 1u) fn main() { - swizzle_of_compose(); - index_of_compose(); - compose_three_deep(); - non_constant_initializers(); - splat_of_constant(); - compose_of_constant(); + swizzle_of_compose(); + index_of_compose(); + compose_three_deep(); + non_constant_initializers(); + splat_of_constant(); + compose_of_constant(); } // Swizzle the value of nested Compose expressions. fn swizzle_of_compose() { - out = vec4(vec2(1, 2), vec2(3, 4)).wzyx; // should assign vec4(4, 3, 2, 1); + var out = vec4(vec2(1, 2), vec2(3, 4)).wzyx; // should assign vec4(4, 3, 2, 1); } // Index the value of nested Compose expressions. fn index_of_compose() { - out2 += vec4(vec2(1, 2), vec2(3, 4))[1]; // should assign 2 + var out = vec4(vec2(1, 2), vec2(3, 4))[1]; // should assign 2 } // Index the value of Compose expressions nested three deep fn compose_three_deep() { - out2 += vec4(vec3(vec2(6, 7), 8), 9)[0]; // should assign 6 + var out = vec4(vec3(vec2(6, 7), 8), 9)[0]; // should assign 6 } // While WGSL allows local variables to be declared anywhere in the function, @@ -40,12 +37,12 @@ fn compose_three_deep() { // initializers that are constants as Naga locals with initializers. This test // checks that Naga local variable initializers are only used when safe. fn non_constant_initializers() { - var w = 10 + 20; - var x = w; - var y = x; - var z = 30 + 40; + var w = 10 + 20; + var x = w; + var y = x; + var z = 30 + 40; - out += vec4(w, x, y, z); + var out = vec4(w, x, y, z); } // Constant evaluation should be able to see through constants to @@ -58,11 +55,11 @@ const TEST_CONSTANT_ADDITION: i32 = FOUR + FOUR; const TEST_CONSTANT_ALIAS_ADDITION: i32 = FOUR_ALIAS + FOUR_ALIAS; fn splat_of_constant() { - out = -vec4(FOUR); + var out = -vec4(FOUR); } fn compose_of_constant() { - out = -vec4(FOUR, FOUR, FOUR, FOUR); + var out = -vec4(FOUR, FOUR, FOUR, FOUR); } const PI: f32 = 3.141; diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/tests/out/glsl/const-exprs.main.Compute.glsl index 738d0d7ef..b6bbe5daa 100644 --- a/tests/out/glsl/const-exprs.main.Compute.glsl +++ b/tests/out/glsl/const-exprs.main.Compute.glsl @@ -18,26 +18,17 @@ const int TEXTURE_KIND_REGULAR = 0; const int TEXTURE_KIND_WARP = 1; const int TEXTURE_KIND_SKY = 2; -layout(std430) buffer type_block_0Compute { ivec4 _group_0_binding_0_cs; }; - -layout(std430) buffer type_1_block_1Compute { int _group_0_binding_1_cs; }; - void swizzle_of_compose() { - _group_0_binding_0_cs = ivec4(4, 3, 2, 1); - return; + ivec4 out_ = ivec4(4, 3, 2, 1); } void index_of_compose() { - int _e2 = _group_0_binding_1_cs; - _group_0_binding_1_cs = (_e2 + 2); - return; + int out_1 = 2; } void compose_three_deep() { - int _e2 = _group_0_binding_1_cs; - _group_0_binding_1_cs = (_e2 + 6); - return; + int out_2 = 6; } void non_constant_initializers() { @@ -45,27 +36,25 @@ void non_constant_initializers() { int x = 0; int y = 0; int z = 70; + ivec4 out_3 = ivec4(0); int _e2 = w; x = _e2; int _e4 = x; y = _e4; - int _e9 = w; - int _e10 = x; - int _e11 = y; - int _e12 = z; - ivec4 _e14 = _group_0_binding_0_cs; - _group_0_binding_0_cs = (_e14 + ivec4(_e9, _e10, _e11, _e12)); + int _e8 = w; + int _e9 = x; + int _e10 = y; + int _e11 = z; + out_3 = ivec4(_e8, _e9, _e10, _e11); return; } void splat_of_constant() { - _group_0_binding_0_cs = ivec4(-4, -4, -4, -4); - return; + ivec4 out_4 = ivec4(-4, -4, -4, -4); } void compose_of_constant() { - _group_0_binding_0_cs = ivec4(-4, -4, -4, -4); - return; + ivec4 out_5 = ivec4(-4, -4, -4, -4); } uint map_texture_kind(int texture_kind) { diff --git a/tests/out/hlsl/const-exprs.hlsl b/tests/out/hlsl/const-exprs.hlsl index f3f59a584..fc52a1129 100644 --- a/tests/out/hlsl/const-exprs.hlsl +++ b/tests/out/hlsl/const-exprs.hlsl @@ -11,27 +11,22 @@ static const int TEXTURE_KIND_REGULAR = 0; static const int TEXTURE_KIND_WARP = 1; static const int TEXTURE_KIND_SKY = 2; -RWByteAddressBuffer out_ : register(u0); -RWByteAddressBuffer out2_ : register(u1); - void swizzle_of_compose() { - out_.Store4(0, asuint(int4(4, 3, 2, 1))); - return; + int4 out_ = int4(4, 3, 2, 1); + } void index_of_compose() { - int _expr2 = asint(out2_.Load(0)); - out2_.Store(0, asuint((_expr2 + 2))); - return; + int out_1 = 2; + } void compose_three_deep() { - int _expr2 = asint(out2_.Load(0)); - out2_.Store(0, asuint((_expr2 + 6))); - return; + int out_2 = 6; + } void non_constant_initializers() @@ -40,30 +35,30 @@ void non_constant_initializers() int x = (int)0; int y = (int)0; int z = 70; + int4 out_3 = (int4)0; int _expr2 = w; x = _expr2; int _expr4 = x; y = _expr4; - int _expr9 = w; - int _expr10 = x; - int _expr11 = y; - int _expr12 = z; - int4 _expr14 = asint(out_.Load4(0)); - out_.Store4(0, asuint((_expr14 + int4(_expr9, _expr10, _expr11, _expr12)))); + int _expr8 = w; + int _expr9 = x; + int _expr10 = y; + int _expr11 = z; + out_3 = int4(_expr8, _expr9, _expr10, _expr11); return; } void splat_of_constant() { - out_.Store4(0, asuint(int4(-4, -4, -4, -4))); - return; + int4 out_4 = int4(-4, -4, -4, -4); + } void compose_of_constant() { - out_.Store4(0, asuint(int4(-4, -4, -4, -4))); - return; + int4 out_5 = int4(-4, -4, -4, -4); + } uint map_texture_kind(int texture_kind) diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 48299e767..47b3615e1 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -18,60 +18,47 @@ constant int TEXTURE_KIND_WARP = 1; constant int TEXTURE_KIND_SKY = 2; void swizzle_of_compose( - device metal::int4& out ) { - out = metal::int4(4, 3, 2, 1); - return; + metal::int4 out = metal::int4(4, 3, 2, 1); } void index_of_compose( - device int& out2_ ) { - int _e2 = out2_; - out2_ = _e2 + 2; - return; + int out_1 = 2; } void compose_three_deep( - device int& out2_ ) { - int _e2 = out2_; - out2_ = _e2 + 6; - return; + int out_2 = 6; } void non_constant_initializers( - device metal::int4& out ) { int w = 30; int x = {}; int y = {}; int z = 70; + metal::int4 out_3 = {}; int _e2 = w; x = _e2; int _e4 = x; y = _e4; - int _e9 = w; - int _e10 = x; - int _e11 = y; - int _e12 = z; - metal::int4 _e14 = out; - out = _e14 + metal::int4(_e9, _e10, _e11, _e12); + int _e8 = w; + int _e9 = x; + int _e10 = y; + int _e11 = z; + out_3 = metal::int4(_e8, _e9, _e10, _e11); return; } void splat_of_constant( - device metal::int4& out ) { - out = metal::int4(-4, -4, -4, -4); - return; + metal::int4 out_4 = metal::int4(-4, -4, -4, -4); } void compose_of_constant( - device metal::int4& out ) { - out = metal::int4(-4, -4, -4, -4); - return; + metal::int4 out_5 = metal::int4(-4, -4, -4, -4); } uint map_texture_kind( @@ -94,14 +81,12 @@ uint map_texture_kind( } kernel void main_( - device metal::int4& out [[user(fake0)]] -, device int& out2_ [[user(fake0)]] ) { - swizzle_of_compose(out); - index_of_compose(out2_); - compose_three_deep(out2_); - non_constant_initializers(out); - splat_of_constant(out); - compose_of_constant(out); + swizzle_of_compose(); + index_of_compose(); + compose_three_deep(); + non_constant_initializers(); + splat_of_constant(); + compose_of_constant(); return; } diff --git a/tests/out/spv/const-exprs.spvasm b/tests/out/spv/const-exprs.spvasm index b05f0f7df..e6aff5079 100644 --- a/tests/out/spv/const-exprs.spvasm +++ b/tests/out/spv/const-exprs.spvasm @@ -1,28 +1,19 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 105 +; Bound: 91 OpCapability Shader -OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %95 "main" -OpExecutionMode %95 LocalSize 2 3 1 -OpDecorate %20 DescriptorSet 0 -OpDecorate %20 Binding 0 -OpDecorate %21 Block -OpMemberDecorate %21 0 Offset 0 -OpDecorate %23 DescriptorSet 0 -OpDecorate %23 Binding 1 -OpDecorate %24 Block -OpMemberDecorate %24 0 Offset 0 +OpEntryPoint GLCompute %83 "main" +OpExecutionMode %83 LocalSize 2 3 1 %2 = OpTypeVoid +%3 = OpTypeInt 32 0 %4 = OpTypeInt 32 1 -%3 = OpTypeVector %4 4 -%5 = OpTypeInt 32 0 +%5 = OpTypeVector %4 4 %6 = OpTypeFloat 32 %7 = OpTypeVector %6 4 -%8 = OpConstant %5 2 +%8 = OpConstant %3 2 %9 = OpConstant %4 3 %10 = OpConstant %4 4 %11 = OpConstant %4 8 @@ -34,126 +25,107 @@ OpMemberDecorate %24 0 Offset 0 %17 = OpConstant %4 0 %18 = OpConstant %4 1 %19 = OpConstant %4 2 -%21 = OpTypeStruct %3 -%22 = OpTypePointer StorageBuffer %21 -%20 = OpVariable %22 StorageBuffer -%24 = OpTypeStruct %4 -%25 = OpTypePointer StorageBuffer %24 -%23 = OpVariable %25 StorageBuffer -%28 = OpTypeFunction %2 -%29 = OpTypePointer StorageBuffer %3 -%30 = OpConstant %5 0 -%32 = OpConstantComposite %3 %10 %9 %19 %18 -%36 = OpTypePointer StorageBuffer %4 -%44 = OpConstant %4 6 -%51 = OpConstant %4 30 -%52 = OpConstant %4 70 -%54 = OpTypePointer Function %4 -%56 = OpConstantNull %4 -%58 = OpConstantNull %4 -%73 = OpConstant %4 -4 -%74 = OpConstantComposite %3 %73 %73 %73 %73 -%83 = OpTypeFunction %5 %4 -%84 = OpConstant %5 10 -%85 = OpConstant %5 20 -%86 = OpConstant %5 30 -%93 = OpConstantNull %5 -%27 = OpFunction %2 None %28 +%22 = OpTypeFunction %2 +%23 = OpConstantComposite %5 %10 %9 %19 %18 +%25 = OpTypePointer Function %5 +%30 = OpTypePointer Function %4 +%34 = OpConstant %4 6 +%39 = OpConstant %4 30 +%40 = OpConstant %4 70 +%43 = OpConstantNull %4 +%45 = OpConstantNull %4 +%48 = OpConstantNull %5 +%59 = OpConstant %4 -4 +%60 = OpConstantComposite %5 %59 %59 %59 %59 +%70 = OpTypeFunction %3 %4 +%71 = OpConstant %3 10 +%72 = OpConstant %3 20 +%73 = OpConstant %3 30 +%74 = OpConstant %3 0 +%81 = OpConstantNull %3 +%21 = OpFunction %2 None %22 +%20 = OpLabel +%24 = OpVariable %25 Function %23 +OpBranch %26 %26 = OpLabel -%31 = OpAccessChain %29 %20 %30 -OpBranch %33 -%33 = OpLabel -OpStore %31 %32 OpReturn OpFunctionEnd -%35 = OpFunction %2 None %28 -%34 = OpLabel -%37 = OpAccessChain %36 %23 %30 -OpBranch %38 -%38 = OpLabel -%39 = OpLoad %4 %37 -%40 = OpIAdd %4 %39 %19 -OpStore %37 %40 +%28 = OpFunction %2 None %22 +%27 = OpLabel +%29 = OpVariable %30 Function %19 +OpBranch %31 +%31 = OpLabel OpReturn OpFunctionEnd -%42 = OpFunction %2 None %28 -%41 = OpLabel -%43 = OpAccessChain %36 %23 %30 -OpBranch %45 -%45 = OpLabel -%46 = OpLoad %4 %43 -%47 = OpIAdd %4 %46 %44 -OpStore %43 %47 +%33 = OpFunction %2 None %22 +%32 = OpLabel +%35 = OpVariable %30 Function %34 +OpBranch %36 +%36 = OpLabel OpReturn OpFunctionEnd -%49 = OpFunction %2 None %28 -%48 = OpLabel -%55 = OpVariable %54 Function %56 -%59 = OpVariable %54 Function %52 -%53 = OpVariable %54 Function %51 -%57 = OpVariable %54 Function %58 -%50 = OpAccessChain %29 %20 %30 -OpBranch %60 -%60 = OpLabel -%61 = OpLoad %4 %53 -OpStore %55 %61 -%62 = OpLoad %4 %55 -OpStore %57 %62 -%63 = OpLoad %4 %53 -%64 = OpLoad %4 %55 -%65 = OpLoad %4 %57 -%66 = OpLoad %4 %59 -%67 = OpCompositeConstruct %3 %63 %64 %65 %66 -%68 = OpLoad %3 %50 -%69 = OpIAdd %3 %68 %67 -OpStore %50 %69 +%38 = OpFunction %2 None %22 +%37 = OpLabel +%47 = OpVariable %25 Function %48 +%42 = OpVariable %30 Function %43 +%46 = OpVariable %30 Function %40 +%41 = OpVariable %30 Function %39 +%44 = OpVariable %30 Function %45 +OpBranch %49 +%49 = OpLabel +%50 = OpLoad %4 %41 +OpStore %42 %50 +%51 = OpLoad %4 %42 +OpStore %44 %51 +%52 = OpLoad %4 %41 +%53 = OpLoad %4 %42 +%54 = OpLoad %4 %44 +%55 = OpLoad %4 %46 +%56 = OpCompositeConstruct %5 %52 %53 %54 %55 +OpStore %47 %56 OpReturn OpFunctionEnd -%71 = OpFunction %2 None %28 -%70 = OpLabel -%72 = OpAccessChain %29 %20 %30 +%58 = OpFunction %2 None %22 +%57 = OpLabel +%61 = OpVariable %25 Function %60 +OpBranch %62 +%62 = OpLabel +OpReturn +OpFunctionEnd +%64 = OpFunction %2 None %22 +%63 = OpLabel +%65 = OpVariable %25 Function %60 +OpBranch %66 +%66 = OpLabel +OpReturn +OpFunctionEnd +%69 = OpFunction %3 None %70 +%68 = OpFunctionParameter %4 +%67 = OpLabel OpBranch %75 %75 = OpLabel -OpStore %72 %74 -OpReturn -OpFunctionEnd -%77 = OpFunction %2 None %28 -%76 = OpLabel -%78 = OpAccessChain %29 %20 %30 -OpBranch %79 +OpSelectionMerge %76 None +OpSwitch %68 %80 0 %77 1 %78 2 %79 +%77 = OpLabel +OpReturnValue %71 +%78 = OpLabel +OpReturnValue %72 %79 = OpLabel -OpStore %78 %74 -OpReturn -OpFunctionEnd -%82 = OpFunction %5 None %83 -%81 = OpFunctionParameter %4 +OpReturnValue %73 %80 = OpLabel -OpBranch %87 -%87 = OpLabel -OpSelectionMerge %88 None -OpSwitch %81 %92 0 %89 1 %90 2 %91 -%89 = OpLabel -OpReturnValue %84 -%90 = OpLabel -OpReturnValue %85 -%91 = OpLabel -OpReturnValue %86 -%92 = OpLabel -OpReturnValue %30 -%88 = OpLabel -OpReturnValue %93 +OpReturnValue %74 +%76 = OpLabel +OpReturnValue %81 OpFunctionEnd -%95 = OpFunction %2 None %28 -%94 = OpLabel -%96 = OpAccessChain %29 %20 %30 -%97 = OpAccessChain %36 %23 %30 -OpBranch %98 -%98 = OpLabel -%99 = OpFunctionCall %2 %27 -%100 = OpFunctionCall %2 %35 -%101 = OpFunctionCall %2 %42 -%102 = OpFunctionCall %2 %49 -%103 = OpFunctionCall %2 %71 -%104 = OpFunctionCall %2 %77 +%83 = OpFunction %2 None %22 +%82 = OpLabel +OpBranch %84 +%84 = OpLabel +%85 = OpFunctionCall %2 %21 +%86 = OpFunctionCall %2 %28 +%87 = OpFunctionCall %2 %33 +%88 = OpFunctionCall %2 %38 +%89 = OpFunctionCall %2 %58 +%90 = OpFunctionCall %2 %64 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/const-exprs.wgsl b/tests/out/wgsl/const-exprs.wgsl index 569d08264..fffc11f34 100644 --- a/tests/out/wgsl/const-exprs.wgsl +++ b/tests/out/wgsl/const-exprs.wgsl @@ -11,26 +11,19 @@ const TEXTURE_KIND_REGULAR: i32 = 0; const TEXTURE_KIND_WARP: i32 = 1; const TEXTURE_KIND_SKY: i32 = 2; -@group(0) @binding(0) -var out: vec4; -@group(0) @binding(1) -var out2_: i32; - fn swizzle_of_compose() { - out = vec4(4, 3, 2, 1); - return; + var out: vec4 = vec4(4, 3, 2, 1); + } fn index_of_compose() { - let _e2 = out2_; - out2_ = (_e2 + 2); - return; + var out_1: i32 = 2; + } fn compose_three_deep() { - let _e2 = out2_; - out2_ = (_e2 + 6); - return; + var out_2: i32 = 6; + } fn non_constant_initializers() { @@ -38,28 +31,28 @@ fn non_constant_initializers() { var x: i32; var y: i32; var z: i32 = 70; + var out_3: vec4; let _e2 = w; x = _e2; let _e4 = x; y = _e4; - let _e9 = w; - let _e10 = x; - let _e11 = y; - let _e12 = z; - let _e14 = out; - out = (_e14 + vec4(_e9, _e10, _e11, _e12)); + let _e8 = w; + let _e9 = x; + let _e10 = y; + let _e11 = z; + out_3 = vec4(_e8, _e9, _e10, _e11); return; } fn splat_of_constant() { - out = vec4(-4, -4, -4, -4); - return; + var out_4: vec4 = vec4(-4, -4, -4, -4); + } fn compose_of_constant() { - out = vec4(-4, -4, -4, -4); - return; + var out_5: vec4 = vec4(-4, -4, -4, -4); + } fn map_texture_kind(texture_kind: i32) -> u32 { From a77f6ff51cbfdc36136023b9da185fc04294025a Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 5 Oct 2023 23:55:47 +0200 Subject: [PATCH 2158/2212] [const-eval] error on NaN and infinite floats --- src/proc/constant_evaluator.rs | 69 ++++++++++++++++++++-------------- src/valid/expression.rs | 2 +- src/valid/mod.rs | 1 + 3 files changed, 42 insertions(+), 30 deletions(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index eb45179b7..61adf0fdd 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -78,7 +78,7 @@ impl ExpressionConstnessTracker { } } -#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum ConstantEvaluatorError { #[error("Constants cannot access function arguments")] FunctionArg, @@ -144,6 +144,8 @@ pub enum ConstantEvaluatorError { RemainderByZero, #[error("RHS of shift operation is greater than or equal to 32")] ShiftedMoreThan32Bits, + #[error(transparent)] + Literal(#[from] crate::valid::LiteralError), } impl<'a> ConstantEvaluator<'a> { @@ -270,18 +272,18 @@ impl<'a> ConstantEvaluator<'a> { Ok(self.constants[c].init) } Expression::Literal(_) | Expression::ZeroValue(_) | Expression::Constant(_) => { - Ok(self.register_evaluated_expr(expr.clone(), span)) + self.register_evaluated_expr(expr.clone(), span) } Expression::Compose { ty, ref components } => { let components = components .iter() .map(|component| self.check_and_get(*component)) .collect::, _>>()?; - Ok(self.register_evaluated_expr(Expression::Compose { ty, components }, span)) + self.register_evaluated_expr(Expression::Compose { ty, components }, span) } Expression::Splat { size, value } => { let value = self.check_and_get(value)?; - Ok(self.register_evaluated_expr(Expression::Splat { size, value }, span)) + self.register_evaluated_expr(Expression::Splat { size, value }, span) } Expression::AccessIndex { base, index } => { let base = self.check_and_get(base)?; @@ -395,7 +397,7 @@ impl<'a> ConstantEvaluator<'a> { ty, components: vec![value; size as usize], }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } Expression::ZeroValue(ty) => { let inner = match self.types[ty].inner { @@ -404,7 +406,7 @@ impl<'a> ConstantEvaluator<'a> { }; let res_ty = self.types.insert(Type { name: None, inner }, span); let expr = Expression::ZeroValue(res_ty); - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } _ => Err(ConstantEvaluatorError::SplatScalarOnly), } @@ -436,11 +438,11 @@ impl<'a> ConstantEvaluator<'a> { Expression::ZeroValue(ty) => { let dst_ty = get_dst_ty(ty)?; let expr = Expression::ZeroValue(dst_ty); - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } Expression::Splat { value, .. } => { let expr = Expression::Splat { size, value }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } Expression::Compose { ty, ref components } => { let dst_ty = get_dst_ty(ty)?; @@ -468,7 +470,7 @@ impl<'a> ConstantEvaluator<'a> { ty: dst_ty, components: swizzled_components, }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } _ => Err(ConstantEvaluatorError::SwizzleVectorOnly), } @@ -565,7 +567,7 @@ impl<'a> ConstantEvaluator<'a> { _ => return Err(ConstantEvaluatorError::InvalidMathArg), }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } fn math_clamp( @@ -670,7 +672,7 @@ impl<'a> ConstantEvaluator<'a> { _ => return Err(ConstantEvaluatorError::InvalidMathArg), }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } fn array_length( @@ -684,7 +686,7 @@ impl<'a> ConstantEvaluator<'a> { TypeInner::Array { size, .. } => match size { crate::ArraySize::Constant(len) => { let expr = Expression::Literal(Literal::U32(len.get())); - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } crate::ArraySize::Dynamic => { Err(ConstantEvaluatorError::ArrayLengthDynamic) @@ -722,7 +724,7 @@ impl<'a> ConstantEvaluator<'a> { self.types.insert(Type { name: None, inner }, span) } }; - Ok(self.register_evaluated_expr(Expression::ZeroValue(ty), span)) + self.register_evaluated_expr(Expression::ZeroValue(ty), span) } } Expression::Splat { size, value } => { @@ -788,7 +790,7 @@ impl<'a> ConstantEvaluator<'a> { Literal::zero(kind, width) .ok_or(ConstantEvaluatorError::TypeNotConstructible)?, ); - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } TypeInner::Vector { size, kind, width } => { let scalar_ty = self.types.insert( @@ -803,7 +805,7 @@ impl<'a> ConstantEvaluator<'a> { ty, components: vec![el; size as usize], }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } TypeInner::Matrix { columns, @@ -826,7 +828,7 @@ impl<'a> ConstantEvaluator<'a> { ty, components: vec![el; columns as usize], }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } TypeInner::Array { base, @@ -838,7 +840,7 @@ impl<'a> ConstantEvaluator<'a> { ty, components: vec![el; size.get() as usize], }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } TypeInner::Struct { ref members, .. } => { let types: Vec<_> = members.iter().map(|m| m.ty).collect(); @@ -847,7 +849,7 @@ impl<'a> ConstantEvaluator<'a> { components.push(self.eval_zero_value_impl(ty, span)?); } let expr = Expression::Compose { ty, components }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } _ => Err(ConstantEvaluatorError::TypeNotConstructible), } @@ -933,7 +935,7 @@ impl<'a> ConstantEvaluator<'a> { _ => return Err(ConstantEvaluatorError::InvalidCastArg), }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } fn unary_op( @@ -977,7 +979,7 @@ impl<'a> ConstantEvaluator<'a> { _ => return Err(ConstantEvaluatorError::InvalidUnaryOpArg), }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } fn binary_op( @@ -1113,7 +1115,7 @@ impl<'a> ConstantEvaluator<'a> { _ => return Err(ConstantEvaluatorError::InvalidBinaryOpArgs), }; - Ok(self.register_evaluated_expr(expr, span)) + self.register_evaluated_expr(expr, span) } /// Deep copy `expr` from `expressions` into `self.expressions`. @@ -1132,17 +1134,17 @@ impl<'a> ConstantEvaluator<'a> { match expressions[expr] { ref expr @ (Expression::Literal(_) | Expression::Constant(_) - | Expression::ZeroValue(_)) => Ok(self.register_evaluated_expr(expr.clone(), span)), + | Expression::ZeroValue(_)) => self.register_evaluated_expr(expr.clone(), span), Expression::Compose { ty, ref components } => { let mut components = components.clone(); for component in &mut components { *component = self.copy_from(*component, expressions)?; } - Ok(self.register_evaluated_expr(Expression::Compose { ty, components }, span)) + self.register_evaluated_expr(Expression::Compose { ty, components }, span) } Expression::Splat { size, value } => { let value = self.copy_from(value, expressions)?; - Ok(self.register_evaluated_expr(Expression::Splat { size, value }, span)) + self.register_evaluated_expr(Expression::Splat { size, value }, span) } _ => { log::debug!("copy_from: SubexpressionsAreNotConstant"); @@ -1151,8 +1153,17 @@ impl<'a> ConstantEvaluator<'a> { } } - fn register_evaluated_expr(&mut self, expr: Expression, span: Span) -> Handle { - // TODO: use the validate_literal function from https://github.com/gfx-rs/naga/pull/2508 here + fn register_evaluated_expr( + &mut self, + expr: Expression, + span: Span, + ) -> Result, ConstantEvaluatorError> { + // It suffices to only check literals, since we only register one + // expression at a time, `Compose` expressions can only refer to other + // expressions, and `ZeroValue` expressions are always okay. + if let Expression::Literal(literal) = expr { + crate::valid::validate_literal(literal)?; + } if let Some(FunctionLocalData { ref mut emitter, @@ -1168,14 +1179,14 @@ impl<'a> ConstantEvaluator<'a> { let h = self.expressions.append(expr, span); emitter.start(self.expressions); expression_constness.insert(h); - h + Ok(h) } else { let h = self.expressions.append(expr, span); expression_constness.insert(h); - h + Ok(h) } } else { - self.expressions.append(expr, span) + Ok(self.expressions.append(expr, span)) } } } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index af4b774f1..95225a392 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -1566,7 +1566,7 @@ impl super::Validator { } } -fn validate_literal(literal: crate::Literal) -> Result<(), LiteralError> { +pub fn validate_literal(literal: crate::Literal) -> Result<(), LiteralError> { let is_nan = match literal { crate::Literal::F64(v) => v.is_nan(), crate::Literal::F32(v) => v.is_nan(), diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 6175aa094..8c065bb15 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -24,6 +24,7 @@ use std::ops; use crate::span::{AddSpan as _, WithSpan}; pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements}; pub use compose::ComposeError; +pub use expression::{validate_literal, LiteralError}; pub use expression::{ConstExpressionError, ExpressionError}; pub use function::{CallError, FunctionError, LocalVariableError}; pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; From 4f453b40414558e3acfbfc1e736fbb15f6bed974 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 9 Oct 2023 16:24:55 +0200 Subject: [PATCH 2159/2212] avoid const-evaluating the `operators.wgsl` snapshot --- tests/in/operators.wgsl | 336 +++++----- tests/out/glsl/operators.main.Compute.glsl | 161 +++-- tests/out/hlsl/operators.hlsl | 161 +++-- tests/out/msl/operators.msl | 161 +++-- tests/out/spv/operators.spvasm | 732 +++++++++++---------- tests/out/wgsl/operators.wgsl | 161 +++-- 6 files changed, 1019 insertions(+), 693 deletions(-) diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl index eaf16ab8f..40d1ce8ea 100644 --- a/tests/in/operators.wgsl +++ b/tests/in/operators.wgsl @@ -41,215 +41,242 @@ fn bool_cast(x: vec3) -> vec3 { } fn logical() { + let t = true; + let f = false; + // unary - let neg0 = !true; - let neg1 = !vec2(true); + let neg0 = !t; + let neg1 = !vec2(t); // binary - let or = true || false; - let and = true && false; - let bitwise_or0 = true | false; - let bitwise_or1 = vec3(true) | vec3(false); - let bitwise_and0 = true & false; - let bitwise_and1 = vec4(true) & vec4(false); + let or = t || f; + let and = t && f; + let bitwise_or0 = t | f; + let bitwise_or1 = vec3(t) | vec3(f); + let bitwise_and0 = t & f; + let bitwise_and1 = vec4(t) & vec4(f); } fn arithmetic() { + let one_i = 1i; + let one_u = 1u; + let one_f = 1.0; + let two_i = 2i; + let two_u = 2u; + let two_f = 2.0; + // unary - let neg0 = -1.0; - let neg1 = -vec2(1); - let neg2 = -vec2(1.0); + let neg0 = -one_f; + let neg1 = -vec2(one_i); + let neg2 = -vec2(one_f); // binary // Addition - let add0 = 2 + 1; - let add1 = 2u + 1u; - let add2 = 2.0 + 1.0; - let add3 = vec2(2) + vec2(1); - let add4 = vec3(2u) + vec3(1u); - let add5 = vec4(2.0) + vec4(1.0); + let add0 = two_i + one_i; + let add1 = two_u + one_u; + let add2 = two_f + one_f; + let add3 = vec2(two_i) + vec2(one_i); + let add4 = vec3(two_u) + vec3(one_u); + let add5 = vec4(two_f) + vec4(one_f); // Subtraction - let sub0 = 2 - 1; - let sub1 = 2u - 1u; - let sub2 = 2.0 - 1.0; - let sub3 = vec2(2) - vec2(1); - let sub4 = vec3(2u) - vec3(1u); - let sub5 = vec4(2.0) - vec4(1.0); + let sub0 = two_i - one_i; + let sub1 = two_u - one_u; + let sub2 = two_f - one_f; + let sub3 = vec2(two_i) - vec2(one_i); + let sub4 = vec3(two_u) - vec3(one_u); + let sub5 = vec4(two_f) - vec4(one_f); // Multiplication - let mul0 = 2 * 1; - let mul1 = 2u * 1u; - let mul2 = 2.0 * 1.0; - let mul3 = vec2(2) * vec2(1); - let mul4 = vec3(2u) * vec3(1u); - let mul5 = vec4(2.0) * vec4(1.0); + let mul0 = two_i * one_i; + let mul1 = two_u * one_u; + let mul2 = two_f * one_f; + let mul3 = vec2(two_i) * vec2(one_i); + let mul4 = vec3(two_u) * vec3(one_u); + let mul5 = vec4(two_f) * vec4(one_f); // Division - let div0 = 2 / 1; - let div1 = 2u / 1u; - let div2 = 2.0 / 1.0; - let div3 = vec2(2) / vec2(1); - let div4 = vec3(2u) / vec3(1u); - let div5 = vec4(2.0) / vec4(1.0); + let div0 = two_i / one_i; + let div1 = two_u / one_u; + let div2 = two_f / one_f; + let div3 = vec2(two_i) / vec2(one_i); + let div4 = vec3(two_u) / vec3(one_u); + let div5 = vec4(two_f) / vec4(one_f); // Remainder - let rem0 = 2 % 1; - let rem1 = 2u % 1u; - let rem2 = 2.0 % 1.0; - let rem3 = vec2(2) % vec2(1); - let rem4 = vec3(2u) % vec3(1u); - let rem5 = vec4(2.0) % vec4(1.0); + let rem0 = two_i % one_i; + let rem1 = two_u % one_u; + let rem2 = two_f % one_f; + let rem3 = vec2(two_i) % vec2(one_i); + let rem4 = vec3(two_u) % vec3(one_u); + let rem5 = vec4(two_f) % vec4(one_f); // Binary arithmetic expressions with mixed scalar and vector operands { - let add0 = vec2(2) + 1; - let add1 = 2 + vec2(1); - let add2 = vec2(2u) + 1u; - let add3 = 2u + vec2(1u); - let add4 = vec2(2.0) + 1.0; - let add5 = 2.0 + vec2(1.0); + let add0 = vec2(two_i) + one_i; + let add1 = two_i + vec2(one_i); + let add2 = vec2(two_u) + one_u; + let add3 = two_u + vec2(one_u); + let add4 = vec2(two_f) + one_f; + let add5 = two_f + vec2(one_f); - let sub0 = vec2(2) - 1; - let sub1 = 2 - vec2(1); - let sub2 = vec2(2u) - 1u; - let sub3 = 2u - vec2(1u); - let sub4 = vec2(2.0) - 1.0; - let sub5 = 2.0 - vec2(1.0); + let sub0 = vec2(two_i) - one_i; + let sub1 = two_i - vec2(one_i); + let sub2 = vec2(two_u) - one_u; + let sub3 = two_u - vec2(one_u); + let sub4 = vec2(two_f) - one_f; + let sub5 = two_f - vec2(one_f); - let mul0 = vec2(2) * 1; - let mul1 = 2 * vec2(1); - let mul2 = vec2(2u) * 1u; - let mul3 = 2u * vec2(1u); - let mul4 = vec2(2.0) * 1.0; - let mul5 = 2.0 * vec2(1.0); + let mul0 = vec2(two_i) * one_i; + let mul1 = two_i * vec2(one_i); + let mul2 = vec2(two_u) * one_u; + let mul3 = two_u * vec2(one_u); + let mul4 = vec2(two_f) * one_f; + let mul5 = two_f * vec2(one_f); - let div0 = vec2(2) / 1; - let div1 = 2 / vec2(1); - let div2 = vec2(2u) / 1u; - let div3 = 2u / vec2(1u); - let div4 = vec2(2.0) / 1.0; - let div5 = 2.0 / vec2(1.0); + let div0 = vec2(two_i) / one_i; + let div1 = two_i / vec2(one_i); + let div2 = vec2(two_u) / one_u; + let div3 = two_u / vec2(one_u); + let div4 = vec2(two_f) / one_f; + let div5 = two_f / vec2(one_f); - let rem0 = vec2(2) % 1; - let rem1 = 2 % vec2(1); - let rem2 = vec2(2u) % 1u; - let rem3 = 2u % vec2(1u); - let rem4 = vec2(2.0) % 1.0; - let rem5 = 2.0 % vec2(1.0); + let rem0 = vec2(two_i) % one_i; + let rem1 = two_i % vec2(one_i); + let rem2 = vec2(two_u) % one_u; + let rem3 = two_u % vec2(one_u); + let rem4 = vec2(two_f) % one_f; + let rem5 = two_f % vec2(one_f); } // Matrix arithmetic let add = mat3x3() + mat3x3(); let sub = mat3x3() - mat3x3(); - let mul_scalar0 = mat3x3() * 1.0; - let mul_scalar1 = 2.0 * mat3x3(); + let mul_scalar0 = mat3x3() * one_f; + let mul_scalar1 = two_f * mat3x3(); - let mul_vector0 = mat4x3() * vec4(1.0); - let mul_vector1 = vec3f(2.0) * mat4x3f(); + let mul_vector0 = mat4x3() * vec4(one_f); + let mul_vector1 = vec3f(two_f) * mat4x3f(); let mul = mat4x3() * mat3x4(); } fn bit() { + let one_i = 1i; + let one_u = 1u; + let two_i = 2i; + let two_u = 2u; + // unary - let flip0 = ~1; - let flip1 = ~1u; - let flip2 = ~vec2(1); - let flip3 = ~vec3(1u); + let flip0 = ~one_i; + let flip1 = ~one_u; + let flip2 = ~vec2(one_i); + let flip3 = ~vec3(one_u); // binary - let or0 = 2 | 1; - let or1 = 2u | 1u; - let or2 = vec2(2) | vec2(1); - let or3 = vec3(2u) | vec3(1u); + let or0 = two_i | one_i; + let or1 = two_u | one_u; + let or2 = vec2(two_i) | vec2(one_i); + let or3 = vec3(two_u) | vec3(one_u); - let and0 = 2 & 1; - let and1 = 2u & 1u; - let and2 = vec2(2) & vec2(1); - let and3 = vec3(2u) & vec3(1u); + let and0 = two_i & one_i; + let and1 = two_u & one_u; + let and2 = vec2(two_i) & vec2(one_i); + let and3 = vec3(two_u) & vec3(one_u); - let xor0 = 2 ^ 1; - let xor1 = 2u ^ 1u; - let xor2 = vec2(2) ^ vec2(1); - let xor3 = vec3(2u) ^ vec3(1u); + let xor0 = two_i ^ one_i; + let xor1 = two_u ^ one_u; + let xor2 = vec2(two_i) ^ vec2(one_i); + let xor3 = vec3(two_u) ^ vec3(one_u); - let shl0 = 2 << 1u; - let shl1 = 2u << 1u; - let shl2 = vec2(2) << vec2(1u); - let shl3 = vec3(2u) << vec3(1u); + let shl0 = two_i << one_u; + let shl1 = two_u << one_u; + let shl2 = vec2(two_i) << vec2(one_u); + let shl3 = vec3(two_u) << vec3(one_u); - let shr0 = 2 >> 1u; - let shr1 = 2u >> 1u; - let shr2 = vec2(2) >> vec2(1u); - let shr3 = vec3(2u) >> vec3(1u); + let shr0 = two_i >> one_u; + let shr1 = two_u >> one_u; + let shr2 = vec2(two_i) >> vec2(one_u); + let shr3 = vec3(two_u) >> vec3(one_u); } fn comparison() { - let eq0 = 2 == 1; - let eq1 = 2u == 1u; - let eq2 = 2.0 == 1.0; - let eq3 = vec2(2) == vec2(1); - let eq4 = vec3(2u) == vec3(1u); - let eq5 = vec4(2.0) == vec4(1.0); + let one_i = 1i; + let one_u = 1u; + let one_f = 1.0; + let two_i = 2i; + let two_u = 2u; + let two_f = 2.0; - let neq0 = 2 != 1; - let neq1 = 2u != 1u; - let neq2 = 2.0 != 1.0; - let neq3 = vec2(2) != vec2(1); - let neq4 = vec3(2u) != vec3(1u); - let neq5 = vec4(2.0) != vec4(1.0); + let eq0 = two_i == one_i; + let eq1 = two_u == one_u; + let eq2 = two_f == one_f; + let eq3 = vec2(two_i) == vec2(one_i); + let eq4 = vec3(two_u) == vec3(one_u); + let eq5 = vec4(two_f) == vec4(one_f); - let lt0 = 2 < 1; - let lt1 = 2u < 1u; - let lt2 = 2.0 < 1.0; - let lt3 = vec2(2) < vec2(1); - let lt4 = vec3(2u) < vec3(1u); - let lt5 = vec4(2.0) < vec4(1.0); + let neq0 = two_i != one_i; + let neq1 = two_u != one_u; + let neq2 = two_f != one_f; + let neq3 = vec2(two_i) != vec2(one_i); + let neq4 = vec3(two_u) != vec3(one_u); + let neq5 = vec4(two_f) != vec4(one_f); - let lte0 = 2 <= 1; - let lte1 = 2u <= 1u; - let lte2 = 2.0 <= 1.0; - let lte3 = vec2(2) <= vec2(1); - let lte4 = vec3(2u) <= vec3(1u); - let lte5 = vec4(2.0) <= vec4(1.0); + let lt0 = two_i < one_i; + let lt1 = two_u < one_u; + let lt2 = two_f < one_f; + let lt3 = vec2(two_i) < vec2(one_i); + let lt4 = vec3(two_u) < vec3(one_u); + let lt5 = vec4(two_f) < vec4(one_f); - let gt0 = 2 > 1; - let gt1 = 2u > 1u; - let gt2 = 2.0 > 1.0; - let gt3 = vec2(2) > vec2(1); - let gt4 = vec3(2u) > vec3(1u); - let gt5 = vec4(2.0) > vec4(1.0); + let lte0 = two_i <= one_i; + let lte1 = two_u <= one_u; + let lte2 = two_f <= one_f; + let lte3 = vec2(two_i) <= vec2(one_i); + let lte4 = vec3(two_u) <= vec3(one_u); + let lte5 = vec4(two_f) <= vec4(one_f); - let gte0 = 2 >= 1; - let gte1 = 2u >= 1u; - let gte2 = 2.0 >= 1.0; - let gte3 = vec2(2) >= vec2(1); - let gte4 = vec3(2u) >= vec3(1u); - let gte5 = vec4(2.0) >= vec4(1.0); + let gt0 = two_i > one_i; + let gt1 = two_u > one_u; + let gt2 = two_f > one_f; + let gt3 = vec2(two_i) > vec2(one_i); + let gt4 = vec3(two_u) > vec3(one_u); + let gt5 = vec4(two_f) > vec4(one_f); + + let gte0 = two_i >= one_i; + let gte1 = two_u >= one_u; + let gte2 = two_f >= one_f; + let gte3 = vec2(two_i) >= vec2(one_i); + let gte4 = vec3(two_u) >= vec3(one_u); + let gte5 = vec4(two_f) >= vec4(one_f); } fn assignment() { - var a = 1; + let zero_i = 0i; + let one_i = 1i; + let one_u = 1u; + let two_u = 2u; - a += 1; - a -= 1; + var a = one_i; + + a += one_i; + a -= one_i; a *= a; a /= a; - a %= 1; - a &= 0; - a |= 0; - a ^= 0; - a <<= 2u; - a >>= 1u; + a %= one_i; + a &= zero_i; + a |= zero_i; + a ^= zero_i; + a <<= two_u; + a >>= one_u; a++; a--; var vec0: vec3 = vec3(); - vec0[1]++; - vec0[1]--; + vec0[one_i]++; + vec0[one_i]--; } @compute @workgroup_size(1) @@ -266,12 +293,13 @@ fn main() { } fn negation_avoids_prefix_decrement() { - let p0 = -1; - let p1 = - -2; - let p2 = -(-3); - let p3 = -(- 4); - let p4 = - - -5; - let p5 = - - - - 6; - let p6 = - - -(- -7); - let p7 = (- - - - -8); + let x = 1; + let p0 = -x; + let p1 = - -x; + let p2 = -(-x); + let p3 = -(- x); + let p4 = - - -x; + let p5 = - - - - x; + let p6 = - - -(- -x); + let p7 = (- - - - -x); } diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl index a1a7131e9..83dd56f8a 100644 --- a/tests/out/glsl/operators.main.Compute.glsl +++ b/tests/out/glsl/operators.main.Compute.glsl @@ -47,7 +47,10 @@ vec3 bool_cast(vec3 x) { } void logical() { - bvec2 neg1_ = bvec2(false, false); + bool neg0_ = !(true); + bvec2 neg1_ = not(bvec2(true)); + bool or = (true || false); + bool and = (true && false); bool bitwise_or0_ = (true || false); bvec3 bitwise_or1_ = bvec3(bvec3(true).x || bvec3(false).x, bvec3(true).y || bvec3(false).y, bvec3(true).z || bvec3(false).z); bool bitwise_and0_ = (true && false); @@ -55,138 +58,192 @@ void logical() { } void arithmetic() { - ivec2 neg1_1 = ivec2(-1, -1); - vec2 neg2_ = vec2(-1.0, -1.0); + float neg0_1 = -(1.0); + ivec2 neg1_1 = -(ivec2(1)); + vec2 neg2_ = -(vec2(1.0)); + int add0_ = (2 + 1); + uint add1_ = (2u + 1u); + float add2_ = (2.0 + 1.0); ivec2 add3_ = (ivec2(2) + ivec2(1)); uvec3 add4_ = (uvec3(2u) + uvec3(1u)); vec4 add5_ = (vec4(2.0) + vec4(1.0)); + int sub0_ = (2 - 1); + uint sub1_ = (2u - 1u); + float sub2_ = (2.0 - 1.0); ivec2 sub3_ = (ivec2(2) - ivec2(1)); uvec3 sub4_ = (uvec3(2u) - uvec3(1u)); vec4 sub5_ = (vec4(2.0) - vec4(1.0)); + int mul0_ = (2 * 1); + uint mul1_ = (2u * 1u); + float mul2_ = (2.0 * 1.0); ivec2 mul3_ = (ivec2(2) * ivec2(1)); uvec3 mul4_ = (uvec3(2u) * uvec3(1u)); vec4 mul5_ = (vec4(2.0) * vec4(1.0)); + int div0_ = (2 / 1); + uint div1_ = (2u / 1u); + float div2_ = (2.0 / 1.0); ivec2 div3_ = (ivec2(2) / ivec2(1)); uvec3 div4_ = (uvec3(2u) / uvec3(1u)); vec4 div5_ = (vec4(2.0) / vec4(1.0)); + int rem0_ = (2 % 1); + uint rem1_ = (2u % 1u); + float rem2_ = (2.0 - 1.0 * trunc(2.0 / 1.0)); ivec2 rem3_ = (ivec2(2) % ivec2(1)); uvec3 rem4_ = (uvec3(2u) % uvec3(1u)); vec4 rem5_ = (vec4(2.0) - vec4(1.0) * trunc(vec4(2.0) / vec4(1.0))); { - ivec2 add0_ = (ivec2(2) + ivec2(1)); - ivec2 add1_ = (ivec2(2) + ivec2(1)); - uvec2 add2_ = (uvec2(2u) + uvec2(1u)); + ivec2 add0_1 = (ivec2(2) + ivec2(1)); + ivec2 add1_1 = (ivec2(2) + ivec2(1)); + uvec2 add2_1 = (uvec2(2u) + uvec2(1u)); uvec2 add3_1 = (uvec2(2u) + uvec2(1u)); vec2 add4_1 = (vec2(2.0) + vec2(1.0)); vec2 add5_1 = (vec2(2.0) + vec2(1.0)); - ivec2 sub0_ = (ivec2(2) - ivec2(1)); - ivec2 sub1_ = (ivec2(2) - ivec2(1)); - uvec2 sub2_ = (uvec2(2u) - uvec2(1u)); + ivec2 sub0_1 = (ivec2(2) - ivec2(1)); + ivec2 sub1_1 = (ivec2(2) - ivec2(1)); + uvec2 sub2_1 = (uvec2(2u) - uvec2(1u)); uvec2 sub3_1 = (uvec2(2u) - uvec2(1u)); vec2 sub4_1 = (vec2(2.0) - vec2(1.0)); vec2 sub5_1 = (vec2(2.0) - vec2(1.0)); - ivec2 mul0_ = ivec2(2, 2); - ivec2 mul1_ = ivec2(2, 2); - uvec2 mul2_ = uvec2(2u, 2u); - uvec2 mul3_1 = uvec2(2u, 2u); - vec2 mul4_1 = vec2(2.0, 2.0); - vec2 mul5_1 = vec2(2.0, 2.0); - ivec2 div0_ = (ivec2(2) / ivec2(1)); - ivec2 div1_ = (ivec2(2) / ivec2(1)); - uvec2 div2_ = (uvec2(2u) / uvec2(1u)); + ivec2 mul0_1 = (ivec2(2) * 1); + ivec2 mul1_1 = (2 * ivec2(1)); + uvec2 mul2_1 = (uvec2(2u) * 1u); + uvec2 mul3_1 = (2u * uvec2(1u)); + vec2 mul4_1 = (vec2(2.0) * 1.0); + vec2 mul5_1 = (2.0 * vec2(1.0)); + ivec2 div0_1 = (ivec2(2) / ivec2(1)); + ivec2 div1_1 = (ivec2(2) / ivec2(1)); + uvec2 div2_1 = (uvec2(2u) / uvec2(1u)); uvec2 div3_1 = (uvec2(2u) / uvec2(1u)); vec2 div4_1 = (vec2(2.0) / vec2(1.0)); vec2 div5_1 = (vec2(2.0) / vec2(1.0)); - ivec2 rem0_ = (ivec2(2) % ivec2(1)); - ivec2 rem1_ = (ivec2(2) % ivec2(1)); - uvec2 rem2_ = (uvec2(2u) % uvec2(1u)); + ivec2 rem0_1 = (ivec2(2) % ivec2(1)); + ivec2 rem1_1 = (ivec2(2) % ivec2(1)); + uvec2 rem2_1 = (uvec2(2u) % uvec2(1u)); uvec2 rem3_1 = (uvec2(2u) % uvec2(1u)); vec2 rem4_1 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); vec2 rem5_1 = (vec2(2.0) - vec2(1.0) * trunc(vec2(2.0) / vec2(1.0))); } mat3x3 add = (mat3x3(0.0) + mat3x3(0.0)); mat3x3 sub = (mat3x3(0.0) - mat3x3(0.0)); - mat3x3 mul_scalar0_ = mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); - mat3x3 mul_scalar1_ = mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); + mat3x3 mul_scalar0_ = (mat3x3(0.0) * 1.0); + mat3x3 mul_scalar1_ = (2.0 * mat3x3(0.0)); vec3 mul_vector0_ = (mat4x3(0.0) * vec4(1.0)); vec4 mul_vector1_ = (vec3(2.0) * mat4x3(0.0)); mat3x3 mul = (mat4x3(0.0) * mat3x4(0.0)); } void bit() { - ivec2 flip2_ = ivec2(-2, -2); - uvec3 flip3_ = uvec3(4294967294u, 4294967294u, 4294967294u); + int flip0_ = ~(1); + uint flip1_ = ~(1u); + ivec2 flip2_ = ~(ivec2(1)); + uvec3 flip3_ = ~(uvec3(1u)); + int or0_ = (2 | 1); + uint or1_ = (2u | 1u); ivec2 or2_ = (ivec2(2) | ivec2(1)); uvec3 or3_ = (uvec3(2u) | uvec3(1u)); + int and0_ = (2 & 1); + uint and1_ = (2u & 1u); ivec2 and2_ = (ivec2(2) & ivec2(1)); uvec3 and3_ = (uvec3(2u) & uvec3(1u)); + int xor0_ = (2 ^ 1); + uint xor1_ = (2u ^ 1u); ivec2 xor2_ = (ivec2(2) ^ ivec2(1)); uvec3 xor3_ = (uvec3(2u) ^ uvec3(1u)); + int shl0_ = (2 << 1u); + uint shl1_ = (2u << 1u); ivec2 shl2_ = (ivec2(2) << uvec2(1u)); uvec3 shl3_ = (uvec3(2u) << uvec3(1u)); + int shr0_ = (2 >> 1u); + uint shr1_ = (2u >> 1u); ivec2 shr2_ = (ivec2(2) >> uvec2(1u)); uvec3 shr3_ = (uvec3(2u) >> uvec3(1u)); } void comparison() { + bool eq0_ = (2 == 1); + bool eq1_ = (2u == 1u); + bool eq2_ = (2.0 == 1.0); bvec2 eq3_ = equal(ivec2(2), ivec2(1)); bvec3 eq4_ = equal(uvec3(2u), uvec3(1u)); bvec4 eq5_ = equal(vec4(2.0), vec4(1.0)); + bool neq0_ = (2 != 1); + bool neq1_ = (2u != 1u); + bool neq2_ = (2.0 != 1.0); bvec2 neq3_ = notEqual(ivec2(2), ivec2(1)); bvec3 neq4_ = notEqual(uvec3(2u), uvec3(1u)); bvec4 neq5_ = notEqual(vec4(2.0), vec4(1.0)); + bool lt0_ = (2 < 1); + bool lt1_ = (2u < 1u); + bool lt2_ = (2.0 < 1.0); bvec2 lt3_ = lessThan(ivec2(2), ivec2(1)); bvec3 lt4_ = lessThan(uvec3(2u), uvec3(1u)); bvec4 lt5_ = lessThan(vec4(2.0), vec4(1.0)); + bool lte0_ = (2 <= 1); + bool lte1_ = (2u <= 1u); + bool lte2_ = (2.0 <= 1.0); bvec2 lte3_ = lessThanEqual(ivec2(2), ivec2(1)); bvec3 lte4_ = lessThanEqual(uvec3(2u), uvec3(1u)); bvec4 lte5_ = lessThanEqual(vec4(2.0), vec4(1.0)); + bool gt0_ = (2 > 1); + bool gt1_ = (2u > 1u); + bool gt2_ = (2.0 > 1.0); bvec2 gt3_ = greaterThan(ivec2(2), ivec2(1)); bvec3 gt4_ = greaterThan(uvec3(2u), uvec3(1u)); bvec4 gt5_ = greaterThan(vec4(2.0), vec4(1.0)); + bool gte0_ = (2 >= 1); + bool gte1_ = (2u >= 1u); + bool gte2_ = (2.0 >= 1.0); bvec2 gte3_ = greaterThanEqual(ivec2(2), ivec2(1)); bvec3 gte4_ = greaterThanEqual(uvec3(2u), uvec3(1u)); bvec4 gte5_ = greaterThanEqual(vec4(2.0), vec4(1.0)); } void assignment() { - int a_1 = 1; + int a_1 = 0; ivec3 vec0_ = ivec3(0); - int _e3 = a_1; - a_1 = (_e3 + 1); - int _e6 = a_1; - a_1 = (_e6 - 1); - int _e8 = a_1; + a_1 = 1; + int _e5 = a_1; + a_1 = (_e5 + 1); + int _e7 = a_1; + a_1 = (_e7 - 1); int _e9 = a_1; - a_1 = (_e9 * _e8); - int _e11 = a_1; + int _e10 = a_1; + a_1 = (_e10 * _e9); int _e12 = a_1; - a_1 = (_e12 / _e11); + int _e13 = a_1; + a_1 = (_e13 / _e12); int _e15 = a_1; a_1 = (_e15 % 1); - int _e18 = a_1; - a_1 = (_e18 & 0); + int _e17 = a_1; + a_1 = (_e17 & 0); + int _e19 = a_1; + a_1 = (_e19 | 0); int _e21 = a_1; - a_1 = (_e21 | 0); - int _e24 = a_1; - a_1 = (_e24 ^ 0); - int _e27 = a_1; - a_1 = (_e27 << 2u); - int _e30 = a_1; - a_1 = (_e30 >> 1u); - int _e33 = a_1; - a_1 = (_e33 + 1); - int _e36 = a_1; - a_1 = (_e36 - 1); - int _e42 = vec0_.y; - vec0_.y = (_e42 + 1); - int _e46 = vec0_.y; - vec0_.y = (_e46 - 1); + a_1 = (_e21 ^ 0); + int _e23 = a_1; + a_1 = (_e23 << 2u); + int _e25 = a_1; + a_1 = (_e25 >> 1u); + int _e28 = a_1; + a_1 = (_e28 + 1); + int _e31 = a_1; + a_1 = (_e31 - 1); + int _e37 = vec0_[1]; + vec0_[1] = (_e37 + 1); + int _e41 = vec0_[1]; + vec0_[1] = (_e41 - 1); return; } void negation_avoids_prefix_decrement() { - return; + int p0_ = -(1); + int p1_ = -(-(1)); + int p2_ = -(-(1)); + int p3_ = -(-(1)); + int p4_ = -(-(-(1))); + int p5_ = -(-(-(-(1)))); + int p6_ = -(-(-(-(-(1))))); + int p7_ = -(-(-(-(-(1))))); } void main() { diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl index 7074d1d56..6d18d07ed 100644 --- a/tests/out/hlsl/operators.hlsl +++ b/tests/out/hlsl/operators.hlsl @@ -45,7 +45,10 @@ float3 bool_cast(float3 x) void logical() { - bool2 neg1_ = bool2(false, false); + bool neg0_ = !(true); + bool2 neg1_ = !((true).xx); + bool or_ = (true || false); + bool and_ = (true && false); bool bitwise_or0_ = (true | false); bool3 bitwise_or1_ = ((true).xxx | (false).xxx); bool bitwise_and0_ = (true & false); @@ -54,59 +57,75 @@ void logical() void arithmetic() { - int2 neg1_1 = int2(-1, -1); - float2 neg2_ = float2(-1.0, -1.0); + float neg0_1 = -(1.0); + int2 neg1_1 = -((1).xx); + float2 neg2_ = -((1.0).xx); + int add0_ = (2 + 1); + uint add1_ = (2u + 1u); + float add2_ = (2.0 + 1.0); int2 add3_ = ((2).xx + (1).xx); uint3 add4_ = ((2u).xxx + (1u).xxx); float4 add5_ = ((2.0).xxxx + (1.0).xxxx); + int sub0_ = (2 - 1); + uint sub1_ = (2u - 1u); + float sub2_ = (2.0 - 1.0); int2 sub3_ = ((2).xx - (1).xx); uint3 sub4_ = ((2u).xxx - (1u).xxx); float4 sub5_ = ((2.0).xxxx - (1.0).xxxx); + int mul0_ = (2 * 1); + uint mul1_ = (2u * 1u); + float mul2_ = (2.0 * 1.0); int2 mul3_ = ((2).xx * (1).xx); uint3 mul4_ = ((2u).xxx * (1u).xxx); float4 mul5_ = ((2.0).xxxx * (1.0).xxxx); + int div0_ = (2 / 1); + uint div1_ = (2u / 1u); + float div2_ = (2.0 / 1.0); int2 div3_ = ((2).xx / (1).xx); uint3 div4_ = ((2u).xxx / (1u).xxx); float4 div5_ = ((2.0).xxxx / (1.0).xxxx); + int rem0_ = (2 % 1); + uint rem1_ = (2u % 1u); + float rem2_ = fmod(2.0, 1.0); int2 rem3_ = ((2).xx % (1).xx); uint3 rem4_ = ((2u).xxx % (1u).xxx); float4 rem5_ = fmod((2.0).xxxx, (1.0).xxxx); { - int2 add0_ = ((2).xx + (1).xx); - int2 add1_ = ((2).xx + (1).xx); - uint2 add2_ = ((2u).xx + (1u).xx); + int2 add0_1 = ((2).xx + (1).xx); + int2 add1_1 = ((2).xx + (1).xx); + uint2 add2_1 = ((2u).xx + (1u).xx); uint2 add3_1 = ((2u).xx + (1u).xx); float2 add4_1 = ((2.0).xx + (1.0).xx); float2 add5_1 = ((2.0).xx + (1.0).xx); - int2 sub0_ = ((2).xx - (1).xx); - int2 sub1_ = ((2).xx - (1).xx); - uint2 sub2_ = ((2u).xx - (1u).xx); + int2 sub0_1 = ((2).xx - (1).xx); + int2 sub1_1 = ((2).xx - (1).xx); + uint2 sub2_1 = ((2u).xx - (1u).xx); uint2 sub3_1 = ((2u).xx - (1u).xx); float2 sub4_1 = ((2.0).xx - (1.0).xx); float2 sub5_1 = ((2.0).xx - (1.0).xx); - int2 mul0_ = int2(2, 2); - int2 mul1_ = int2(2, 2); - uint2 mul2_ = uint2(2u, 2u); - uint2 mul3_1 = uint2(2u, 2u); - float2 mul4_1 = float2(2.0, 2.0); - float2 mul5_1 = float2(2.0, 2.0); - int2 div0_ = ((2).xx / (1).xx); - int2 div1_ = ((2).xx / (1).xx); - uint2 div2_ = ((2u).xx / (1u).xx); + int2 mul0_1 = ((2).xx * 1); + int2 mul1_1 = (2 * (1).xx); + uint2 mul2_1 = ((2u).xx * 1u); + uint2 mul3_1 = (2u * (1u).xx); + float2 mul4_1 = ((2.0).xx * 1.0); + float2 mul5_1 = (2.0 * (1.0).xx); + int2 div0_1 = ((2).xx / (1).xx); + int2 div1_1 = ((2).xx / (1).xx); + uint2 div2_1 = ((2u).xx / (1u).xx); uint2 div3_1 = ((2u).xx / (1u).xx); float2 div4_1 = ((2.0).xx / (1.0).xx); float2 div5_1 = ((2.0).xx / (1.0).xx); - int2 rem0_ = ((2).xx % (1).xx); - int2 rem1_ = ((2).xx % (1).xx); - uint2 rem2_ = ((2u).xx % (1u).xx); + int2 rem0_1 = ((2).xx % (1).xx); + int2 rem1_1 = ((2).xx % (1).xx); + uint2 rem2_1 = ((2u).xx % (1u).xx); uint2 rem3_1 = ((2u).xx % (1u).xx); float2 rem4_1 = fmod((2.0).xx, (1.0).xx); float2 rem5_1 = fmod((2.0).xx, (1.0).xx); } float3x3 add = ((float3x3)0 + (float3x3)0); float3x3 sub = ((float3x3)0 - (float3x3)0); - float3x3 mul_scalar0_ = float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)); - float3x3 mul_scalar1_ = float3x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)); + float3x3 mul_scalar0_ = mul(1.0, (float3x3)0); + float3x3 mul_scalar1_ = mul((float3x3)0, 2.0); float3 mul_vector0_ = mul((1.0).xxxx, (float4x3)0); float4 mul_vector1_ = mul((float4x3)0, (2.0).xxx); float3x3 mul_ = mul((float3x4)0, (float4x3)0); @@ -114,37 +133,67 @@ void arithmetic() void bit() { - int2 flip2_ = int2(-2, -2); - uint3 flip3_ = uint3(4294967294u, 4294967294u, 4294967294u); + int flip0_ = ~(1); + uint flip1_ = ~(1u); + int2 flip2_ = ~((1).xx); + uint3 flip3_ = ~((1u).xxx); + int or0_ = (2 | 1); + uint or1_ = (2u | 1u); int2 or2_ = ((2).xx | (1).xx); uint3 or3_ = ((2u).xxx | (1u).xxx); + int and0_ = (2 & 1); + uint and1_ = (2u & 1u); int2 and2_ = ((2).xx & (1).xx); uint3 and3_ = ((2u).xxx & (1u).xxx); + int xor0_ = (2 ^ 1); + uint xor1_ = (2u ^ 1u); int2 xor2_ = ((2).xx ^ (1).xx); uint3 xor3_ = ((2u).xxx ^ (1u).xxx); + int shl0_ = (2 << 1u); + uint shl1_ = (2u << 1u); int2 shl2_ = ((2).xx << (1u).xx); uint3 shl3_ = ((2u).xxx << (1u).xxx); + int shr0_ = (2 >> 1u); + uint shr1_ = (2u >> 1u); int2 shr2_ = ((2).xx >> (1u).xx); uint3 shr3_ = ((2u).xxx >> (1u).xxx); } void comparison() { + bool eq0_ = (2 == 1); + bool eq1_ = (2u == 1u); + bool eq2_ = (2.0 == 1.0); bool2 eq3_ = ((2).xx == (1).xx); bool3 eq4_ = ((2u).xxx == (1u).xxx); bool4 eq5_ = ((2.0).xxxx == (1.0).xxxx); + bool neq0_ = (2 != 1); + bool neq1_ = (2u != 1u); + bool neq2_ = (2.0 != 1.0); bool2 neq3_ = ((2).xx != (1).xx); bool3 neq4_ = ((2u).xxx != (1u).xxx); bool4 neq5_ = ((2.0).xxxx != (1.0).xxxx); + bool lt0_ = (2 < 1); + bool lt1_ = (2u < 1u); + bool lt2_ = (2.0 < 1.0); bool2 lt3_ = ((2).xx < (1).xx); bool3 lt4_ = ((2u).xxx < (1u).xxx); bool4 lt5_ = ((2.0).xxxx < (1.0).xxxx); + bool lte0_ = (2 <= 1); + bool lte1_ = (2u <= 1u); + bool lte2_ = (2.0 <= 1.0); bool2 lte3_ = ((2).xx <= (1).xx); bool3 lte4_ = ((2u).xxx <= (1u).xxx); bool4 lte5_ = ((2.0).xxxx <= (1.0).xxxx); + bool gt0_ = (2 > 1); + bool gt1_ = (2u > 1u); + bool gt2_ = (2.0 > 1.0); bool2 gt3_ = ((2).xx > (1).xx); bool3 gt4_ = ((2u).xxx > (1u).xxx); bool4 gt5_ = ((2.0).xxxx > (1.0).xxxx); + bool gte0_ = (2 >= 1); + bool gte1_ = (2u >= 1u); + bool gte2_ = (2.0 >= 1.0); bool2 gte3_ = ((2).xx >= (1).xx); bool3 gte4_ = ((2u).xxx >= (1u).xxx); bool4 gte5_ = ((2.0).xxxx >= (1.0).xxxx); @@ -152,45 +201,53 @@ void comparison() void assignment() { - int a_1 = 1; + int a_1 = (int)0; int3 vec0_ = (int3)0; - int _expr3 = a_1; - a_1 = (_expr3 + 1); - int _expr6 = a_1; - a_1 = (_expr6 - 1); - int _expr8 = a_1; + a_1 = 1; + int _expr5 = a_1; + a_1 = (_expr5 + 1); + int _expr7 = a_1; + a_1 = (_expr7 - 1); int _expr9 = a_1; - a_1 = (_expr9 * _expr8); - int _expr11 = a_1; + int _expr10 = a_1; + a_1 = (_expr10 * _expr9); int _expr12 = a_1; - a_1 = (_expr12 / _expr11); + int _expr13 = a_1; + a_1 = (_expr13 / _expr12); int _expr15 = a_1; a_1 = (_expr15 % 1); - int _expr18 = a_1; - a_1 = (_expr18 & 0); + int _expr17 = a_1; + a_1 = (_expr17 & 0); + int _expr19 = a_1; + a_1 = (_expr19 | 0); int _expr21 = a_1; - a_1 = (_expr21 | 0); - int _expr24 = a_1; - a_1 = (_expr24 ^ 0); - int _expr27 = a_1; - a_1 = (_expr27 << 2u); - int _expr30 = a_1; - a_1 = (_expr30 >> 1u); - int _expr33 = a_1; - a_1 = (_expr33 + 1); - int _expr36 = a_1; - a_1 = (_expr36 - 1); - int _expr42 = vec0_.y; - vec0_.y = (_expr42 + 1); - int _expr46 = vec0_.y; - vec0_.y = (_expr46 - 1); + a_1 = (_expr21 ^ 0); + int _expr23 = a_1; + a_1 = (_expr23 << 2u); + int _expr25 = a_1; + a_1 = (_expr25 >> 1u); + int _expr28 = a_1; + a_1 = (_expr28 + 1); + int _expr31 = a_1; + a_1 = (_expr31 - 1); + int _expr37 = vec0_[1]; + vec0_[1] = (_expr37 + 1); + int _expr41 = vec0_[1]; + vec0_[1] = (_expr41 - 1); return; } void negation_avoids_prefix_decrement() { - return; + int p0_ = -(1); + int p1_ = -(-(1)); + int p2_ = -(-(1)); + int p3_ = -(-(1)); + int p4_ = -(-(-(1))); + int p5_ = -(-(-(-(1)))); + int p6_ = -(-(-(-(-(1))))); + int p7_ = -(-(-(-(-(1))))); } [numthreads(1, 1, 1)] diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 2a7463646..114865451 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -51,7 +51,10 @@ metal::float3 bool_cast( void logical( ) { - metal::bool2 neg1_ = metal::bool2(false, false); + bool neg0_ = !(true); + metal::bool2 neg1_ = !(metal::bool2(true)); + bool or_ = true || false; + bool and_ = true && false; bool bitwise_or0_ = true | false; metal::bool3 bitwise_or1_ = metal::bool3(true) | metal::bool3(false); bool bitwise_and0_ = true & false; @@ -60,59 +63,75 @@ void logical( void arithmetic( ) { - metal::int2 neg1_1 = metal::int2(-1, -1); - metal::float2 neg2_ = metal::float2(-1.0, -1.0); + float neg0_1 = -(1.0); + metal::int2 neg1_1 = -(metal::int2(1)); + metal::float2 neg2_ = -(metal::float2(1.0)); + int add0_ = 2 + 1; + uint add1_ = 2u + 1u; + float add2_ = 2.0 + 1.0; metal::int2 add3_ = metal::int2(2) + metal::int2(1); metal::uint3 add4_ = metal::uint3(2u) + metal::uint3(1u); metal::float4 add5_ = metal::float4(2.0) + metal::float4(1.0); + int sub0_ = 2 - 1; + uint sub1_ = 2u - 1u; + float sub2_ = 2.0 - 1.0; metal::int2 sub3_ = metal::int2(2) - metal::int2(1); metal::uint3 sub4_ = metal::uint3(2u) - metal::uint3(1u); metal::float4 sub5_ = metal::float4(2.0) - metal::float4(1.0); + int mul0_ = 2 * 1; + uint mul1_ = 2u * 1u; + float mul2_ = 2.0 * 1.0; metal::int2 mul3_ = metal::int2(2) * metal::int2(1); metal::uint3 mul4_ = metal::uint3(2u) * metal::uint3(1u); metal::float4 mul5_ = metal::float4(2.0) * metal::float4(1.0); + int div0_ = 2 / 1; + uint div1_ = 2u / 1u; + float div2_ = 2.0 / 1.0; metal::int2 div3_ = metal::int2(2) / metal::int2(1); metal::uint3 div4_ = metal::uint3(2u) / metal::uint3(1u); metal::float4 div5_ = metal::float4(2.0) / metal::float4(1.0); + int rem0_ = 2 % 1; + uint rem1_ = 2u % 1u; + float rem2_ = metal::fmod(2.0, 1.0); metal::int2 rem3_ = metal::int2(2) % metal::int2(1); metal::uint3 rem4_ = metal::uint3(2u) % metal::uint3(1u); metal::float4 rem5_ = metal::fmod(metal::float4(2.0), metal::float4(1.0)); { - metal::int2 add0_ = metal::int2(2) + metal::int2(1); - metal::int2 add1_ = metal::int2(2) + metal::int2(1); - metal::uint2 add2_ = metal::uint2(2u) + metal::uint2(1u); + metal::int2 add0_1 = metal::int2(2) + metal::int2(1); + metal::int2 add1_1 = metal::int2(2) + metal::int2(1); + metal::uint2 add2_1 = metal::uint2(2u) + metal::uint2(1u); metal::uint2 add3_1 = metal::uint2(2u) + metal::uint2(1u); metal::float2 add4_1 = metal::float2(2.0) + metal::float2(1.0); metal::float2 add5_1 = metal::float2(2.0) + metal::float2(1.0); - metal::int2 sub0_ = metal::int2(2) - metal::int2(1); - metal::int2 sub1_ = metal::int2(2) - metal::int2(1); - metal::uint2 sub2_ = metal::uint2(2u) - metal::uint2(1u); + metal::int2 sub0_1 = metal::int2(2) - metal::int2(1); + metal::int2 sub1_1 = metal::int2(2) - metal::int2(1); + metal::uint2 sub2_1 = metal::uint2(2u) - metal::uint2(1u); metal::uint2 sub3_1 = metal::uint2(2u) - metal::uint2(1u); metal::float2 sub4_1 = metal::float2(2.0) - metal::float2(1.0); metal::float2 sub5_1 = metal::float2(2.0) - metal::float2(1.0); - metal::int2 mul0_ = metal::int2(2, 2); - metal::int2 mul1_ = metal::int2(2, 2); - metal::uint2 mul2_ = metal::uint2(2u, 2u); - metal::uint2 mul3_1 = metal::uint2(2u, 2u); - metal::float2 mul4_1 = metal::float2(2.0, 2.0); - metal::float2 mul5_1 = metal::float2(2.0, 2.0); - metal::int2 div0_ = metal::int2(2) / metal::int2(1); - metal::int2 div1_ = metal::int2(2) / metal::int2(1); - metal::uint2 div2_ = metal::uint2(2u) / metal::uint2(1u); + metal::int2 mul0_1 = metal::int2(2) * 1; + metal::int2 mul1_1 = 2 * metal::int2(1); + metal::uint2 mul2_1 = metal::uint2(2u) * 1u; + metal::uint2 mul3_1 = 2u * metal::uint2(1u); + metal::float2 mul4_1 = metal::float2(2.0) * 1.0; + metal::float2 mul5_1 = 2.0 * metal::float2(1.0); + metal::int2 div0_1 = metal::int2(2) / metal::int2(1); + metal::int2 div1_1 = metal::int2(2) / metal::int2(1); + metal::uint2 div2_1 = metal::uint2(2u) / metal::uint2(1u); metal::uint2 div3_1 = metal::uint2(2u) / metal::uint2(1u); metal::float2 div4_1 = metal::float2(2.0) / metal::float2(1.0); metal::float2 div5_1 = metal::float2(2.0) / metal::float2(1.0); - metal::int2 rem0_ = metal::int2(2) % metal::int2(1); - metal::int2 rem1_ = metal::int2(2) % metal::int2(1); - metal::uint2 rem2_ = metal::uint2(2u) % metal::uint2(1u); + metal::int2 rem0_1 = metal::int2(2) % metal::int2(1); + metal::int2 rem1_1 = metal::int2(2) % metal::int2(1); + metal::uint2 rem2_1 = metal::uint2(2u) % metal::uint2(1u); metal::uint2 rem3_1 = metal::uint2(2u) % metal::uint2(1u); metal::float2 rem4_1 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); metal::float2 rem5_1 = metal::fmod(metal::float2(2.0), metal::float2(1.0)); } metal::float3x3 add = metal::float3x3 {} + metal::float3x3 {}; metal::float3x3 sub = metal::float3x3 {} - metal::float3x3 {}; - metal::float3x3 mul_scalar0_ = metal::float3x3(metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0)); - metal::float3x3 mul_scalar1_ = metal::float3x3(metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0)); + metal::float3x3 mul_scalar0_ = metal::float3x3 {} * 1.0; + metal::float3x3 mul_scalar1_ = 2.0 * metal::float3x3 {}; metal::float3 mul_vector0_ = metal::float4x3 {} * metal::float4(1.0); metal::float4 mul_vector1_ = metal::float3(2.0) * metal::float4x3 {}; metal::float3x3 mul = metal::float4x3 {} * metal::float3x4 {}; @@ -120,37 +139,67 @@ void arithmetic( void bit( ) { - metal::int2 flip2_ = metal::int2(-2, -2); - metal::uint3 flip3_ = metal::uint3(4294967294u, 4294967294u, 4294967294u); + int flip0_ = ~(1); + uint flip1_ = ~(1u); + metal::int2 flip2_ = ~(metal::int2(1)); + metal::uint3 flip3_ = ~(metal::uint3(1u)); + int or0_ = 2 | 1; + uint or1_ = 2u | 1u; metal::int2 or2_ = metal::int2(2) | metal::int2(1); metal::uint3 or3_ = metal::uint3(2u) | metal::uint3(1u); + int and0_ = 2 & 1; + uint and1_ = 2u & 1u; metal::int2 and2_ = metal::int2(2) & metal::int2(1); metal::uint3 and3_ = metal::uint3(2u) & metal::uint3(1u); + int xor0_ = 2 ^ 1; + uint xor1_ = 2u ^ 1u; metal::int2 xor2_ = metal::int2(2) ^ metal::int2(1); metal::uint3 xor3_ = metal::uint3(2u) ^ metal::uint3(1u); + int shl0_ = 2 << 1u; + uint shl1_ = 2u << 1u; metal::int2 shl2_ = metal::int2(2) << metal::uint2(1u); metal::uint3 shl3_ = metal::uint3(2u) << metal::uint3(1u); + int shr0_ = 2 >> 1u; + uint shr1_ = 2u >> 1u; metal::int2 shr2_ = metal::int2(2) >> metal::uint2(1u); metal::uint3 shr3_ = metal::uint3(2u) >> metal::uint3(1u); } void comparison( ) { + bool eq0_ = 2 == 1; + bool eq1_ = 2u == 1u; + bool eq2_ = 2.0 == 1.0; metal::bool2 eq3_ = metal::int2(2) == metal::int2(1); metal::bool3 eq4_ = metal::uint3(2u) == metal::uint3(1u); metal::bool4 eq5_ = metal::float4(2.0) == metal::float4(1.0); + bool neq0_ = 2 != 1; + bool neq1_ = 2u != 1u; + bool neq2_ = 2.0 != 1.0; metal::bool2 neq3_ = metal::int2(2) != metal::int2(1); metal::bool3 neq4_ = metal::uint3(2u) != metal::uint3(1u); metal::bool4 neq5_ = metal::float4(2.0) != metal::float4(1.0); + bool lt0_ = 2 < 1; + bool lt1_ = 2u < 1u; + bool lt2_ = 2.0 < 1.0; metal::bool2 lt3_ = metal::int2(2) < metal::int2(1); metal::bool3 lt4_ = metal::uint3(2u) < metal::uint3(1u); metal::bool4 lt5_ = metal::float4(2.0) < metal::float4(1.0); + bool lte0_ = 2 <= 1; + bool lte1_ = 2u <= 1u; + bool lte2_ = 2.0 <= 1.0; metal::bool2 lte3_ = metal::int2(2) <= metal::int2(1); metal::bool3 lte4_ = metal::uint3(2u) <= metal::uint3(1u); metal::bool4 lte5_ = metal::float4(2.0) <= metal::float4(1.0); + bool gt0_ = 2 > 1; + bool gt1_ = 2u > 1u; + bool gt2_ = 2.0 > 1.0; metal::bool2 gt3_ = metal::int2(2) > metal::int2(1); metal::bool3 gt4_ = metal::uint3(2u) > metal::uint3(1u); metal::bool4 gt5_ = metal::float4(2.0) > metal::float4(1.0); + bool gte0_ = 2 >= 1; + bool gte1_ = 2u >= 1u; + bool gte2_ = 2.0 >= 1.0; metal::bool2 gte3_ = metal::int2(2) >= metal::int2(1); metal::bool3 gte4_ = metal::uint3(2u) >= metal::uint3(1u); metal::bool4 gte5_ = metal::float4(2.0) >= metal::float4(1.0); @@ -158,44 +207,52 @@ void comparison( void assignment( ) { - int a_1 = 1; + int a_1 = {}; metal::int3 vec0_ = metal::int3 {}; - int _e3 = a_1; - a_1 = _e3 + 1; - int _e6 = a_1; - a_1 = _e6 - 1; - int _e8 = a_1; + a_1 = 1; + int _e5 = a_1; + a_1 = _e5 + 1; + int _e7 = a_1; + a_1 = _e7 - 1; int _e9 = a_1; - a_1 = _e9 * _e8; - int _e11 = a_1; + int _e10 = a_1; + a_1 = _e10 * _e9; int _e12 = a_1; - a_1 = _e12 / _e11; + int _e13 = a_1; + a_1 = _e13 / _e12; int _e15 = a_1; a_1 = _e15 % 1; - int _e18 = a_1; - a_1 = _e18 & 0; + int _e17 = a_1; + a_1 = _e17 & 0; + int _e19 = a_1; + a_1 = _e19 | 0; int _e21 = a_1; - a_1 = _e21 | 0; - int _e24 = a_1; - a_1 = _e24 ^ 0; - int _e27 = a_1; - a_1 = _e27 << 2u; - int _e30 = a_1; - a_1 = _e30 >> 1u; - int _e33 = a_1; - a_1 = _e33 + 1; - int _e36 = a_1; - a_1 = _e36 - 1; - int _e42 = vec0_.y; - vec0_.y = _e42 + 1; - int _e46 = vec0_.y; - vec0_.y = _e46 - 1; + a_1 = _e21 ^ 0; + int _e23 = a_1; + a_1 = _e23 << 2u; + int _e25 = a_1; + a_1 = _e25 >> 1u; + int _e28 = a_1; + a_1 = _e28 + 1; + int _e31 = a_1; + a_1 = _e31 - 1; + int _e37 = vec0_[1]; + vec0_[1] = _e37 + 1; + int _e41 = vec0_[1]; + vec0_[1] = _e41 - 1; return; } void negation_avoids_prefix_decrement( ) { - return; + int p0_ = -(1); + int p1_ = -(-(1)); + int p2_ = -(-(1)); + int p3_ = -(-(1)); + int p4_ = -(-(-(1))); + int p5_ = -(-(-(-(1)))); + int p6_ = -(-(-(-(-(1))))); + int p7_ = -(-(-(-(-(1))))); } kernel void main_( diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm index 538c080e3..89bc4ccf2 100644 --- a/tests/out/spv/operators.spvasm +++ b/tests/out/spv/operators.spvasm @@ -1,12 +1,12 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 308 +; Bound: 377 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %297 "main" -OpExecutionMode %297 LocalSize 1 1 1 +OpEntryPoint GLCompute %366 "main" +OpExecutionMode %366 LocalSize 1 1 1 %2 = OpTypeVoid %4 = OpTypeFloat 32 %3 = OpTypeVector %4 4 @@ -16,352 +16,422 @@ OpExecutionMode %297 LocalSize 1 1 1 %7 = OpTypeVector %8 4 %9 = OpTypeVector %4 2 %10 = OpTypeVector %4 3 -%11 = OpTypeVector %8 2 -%12 = OpTypeVector %6 2 -%14 = OpTypeInt 32 0 -%13 = OpTypeVector %14 3 -%15 = OpTypeVector %14 2 -%16 = OpTypeMatrix %10 3 -%17 = OpTypeMatrix %10 4 -%18 = OpTypeMatrix %3 3 -%19 = OpTypeVector %6 3 -%20 = OpConstant %4 1.0 -%21 = OpConstantComposite %3 %20 %20 %20 %20 -%22 = OpConstant %4 0.0 -%23 = OpConstantComposite %3 %22 %22 %22 %22 -%24 = OpConstant %4 0.5 -%25 = OpConstantComposite %3 %24 %24 %24 %24 -%26 = OpConstant %6 1 -%27 = OpConstantComposite %5 %26 %26 %26 %26 -%30 = OpTypeFunction %3 -%31 = OpConstantTrue %8 -%32 = OpConstant %6 0 -%33 = OpConstantFalse %8 -%34 = OpConstantComposite %7 %33 %33 %33 %33 -%35 = OpConstant %4 0.1 -%36 = OpConstantComposite %5 %32 %32 %32 %32 -%58 = OpConstant %4 2.0 +%11 = OpTypeMatrix %10 3 +%12 = OpTypeMatrix %10 4 +%13 = OpTypeMatrix %3 3 +%14 = OpTypeVector %6 3 +%15 = OpConstant %4 1.0 +%16 = OpConstantComposite %3 %15 %15 %15 %15 +%17 = OpConstant %4 0.0 +%18 = OpConstantComposite %3 %17 %17 %17 %17 +%19 = OpConstant %4 0.5 +%20 = OpConstantComposite %3 %19 %19 %19 %19 +%21 = OpConstant %6 1 +%22 = OpConstantComposite %5 %21 %21 %21 %21 +%25 = OpTypeFunction %3 +%26 = OpConstantTrue %8 +%27 = OpConstant %6 0 +%28 = OpConstantFalse %8 +%29 = OpConstantComposite %7 %28 %28 %28 %28 +%30 = OpConstant %4 0.1 +%31 = OpConstantComposite %5 %27 %27 %27 %27 +%53 = OpConstant %4 2.0 +%54 = OpConstantComposite %9 %53 %53 +%55 = OpConstantComposite %9 %15 %15 +%56 = OpConstant %4 3.0 +%57 = OpConstantComposite %9 %56 %56 +%58 = OpConstant %4 4.0 %59 = OpConstantComposite %9 %58 %58 -%60 = OpConstantComposite %9 %20 %20 -%61 = OpConstant %4 3.0 -%62 = OpConstantComposite %9 %61 %61 -%63 = OpConstant %4 4.0 -%64 = OpConstantComposite %9 %63 %63 -%65 = OpConstant %6 5 -%66 = OpConstantComposite %5 %65 %65 %65 %65 -%67 = OpConstant %6 2 -%68 = OpConstantComposite %5 %67 %67 %67 %67 -%79 = OpTypeFunction %9 -%81 = OpTypePointer Function %9 -%93 = OpTypeFunction %10 %10 -%95 = OpTypeVector %8 3 -%96 = OpConstantComposite %10 %22 %22 %22 -%98 = OpConstantComposite %10 %20 %20 %20 -%102 = OpTypeFunction %2 -%103 = OpConstantComposite %11 %33 %33 -%104 = OpConstantComposite %95 %31 %31 %31 -%105 = OpConstantComposite %95 %33 %33 %33 -%106 = OpConstantComposite %7 %31 %31 %31 %31 -%107 = OpConstantComposite %7 %33 %33 %33 %33 -%115 = OpConstant %4 -1.0 -%116 = OpConstant %6 -1 -%117 = OpConstantComposite %12 %116 %116 -%118 = OpConstantComposite %9 %115 %115 -%119 = OpConstant %6 3 -%120 = OpConstant %14 3 -%121 = OpConstantComposite %12 %67 %67 -%122 = OpConstantComposite %12 %26 %26 -%123 = OpConstant %14 2 -%124 = OpConstantComposite %13 %123 %123 %123 -%125 = OpConstant %14 1 -%126 = OpConstantComposite %13 %125 %125 %125 -%127 = OpConstantComposite %3 %58 %58 %58 %58 -%128 = OpConstantComposite %3 %20 %20 %20 %20 -%129 = OpConstant %14 0 -%130 = OpConstantComposite %15 %123 %123 -%131 = OpConstantComposite %15 %125 %125 -%132 = OpConstantComposite %12 %67 %67 -%133 = OpConstantComposite %15 %123 %123 -%134 = OpConstantComposite %9 %58 %58 -%135 = OpConstantNull %16 -%136 = OpConstantComposite %10 %22 %22 %22 -%137 = OpConstantComposite %16 %136 %136 %136 -%138 = OpConstantNull %17 -%139 = OpConstantComposite %10 %58 %58 %58 -%140 = OpConstantNull %18 -%208 = OpConstant %6 -2 -%209 = OpConstant %14 4294967294 -%210 = OpConstantComposite %12 %208 %208 -%211 = OpConstantComposite %13 %209 %209 %209 -%212 = OpConstant %6 4 -%213 = OpConstant %14 4 -%248 = OpConstantNull %19 -%250 = OpTypePointer Function %6 -%252 = OpTypePointer Function %19 -%280 = OpTypePointer Function %6 -%291 = OpConstant %6 -5 -%292 = OpConstant %6 6 -%293 = OpConstant %6 -7 -%294 = OpConstant %6 -8 -%298 = OpConstantComposite %10 %20 %20 %20 -%29 = OpFunction %3 None %30 -%28 = OpLabel -OpBranch %37 -%37 = OpLabel -%38 = OpSelect %6 %31 %26 %32 -%40 = OpCompositeConstruct %7 %31 %31 %31 %31 -%39 = OpSelect %3 %40 %21 %23 -%41 = OpSelect %3 %34 %23 %21 -%42 = OpExtInst %3 %1 FMix %23 %21 %25 -%44 = OpCompositeConstruct %3 %35 %35 %35 %35 -%43 = OpExtInst %3 %1 FMix %23 %21 %44 -%45 = OpBitcast %4 %26 -%46 = OpBitcast %3 %27 -%47 = OpCompositeConstruct %5 %38 %38 %38 %38 -%48 = OpIAdd %5 %47 %36 -%49 = OpConvertSToF %3 %48 -%50 = OpFAdd %3 %49 %39 -%51 = OpFAdd %3 %50 %42 -%52 = OpFAdd %3 %51 %43 -%53 = OpCompositeConstruct %3 %45 %45 %45 %45 -%54 = OpFAdd %3 %52 %53 -%55 = OpFAdd %3 %54 %46 -OpReturnValue %55 +%60 = OpConstant %6 5 +%61 = OpConstantComposite %5 %60 %60 %60 %60 +%62 = OpConstant %6 2 +%63 = OpConstantComposite %5 %62 %62 %62 %62 +%74 = OpTypeFunction %9 +%76 = OpTypePointer Function %9 +%88 = OpTypeFunction %10 %10 +%90 = OpTypeVector %8 3 +%91 = OpConstantComposite %10 %17 %17 %17 +%93 = OpConstantComposite %10 %15 %15 %15 +%97 = OpTypeFunction %2 +%98 = OpTypeVector %8 2 +%99 = OpConstantComposite %98 %26 %26 +%100 = OpConstantComposite %90 %26 %26 %26 +%101 = OpConstantComposite %90 %28 %28 %28 +%102 = OpConstantComposite %7 %26 %26 %26 %26 +%103 = OpConstantComposite %7 %28 %28 %28 %28 +%115 = OpTypeInt 32 0 +%116 = OpConstant %115 1 +%117 = OpConstant %115 2 +%118 = OpTypeVector %6 2 +%119 = OpConstantComposite %118 %21 %21 +%120 = OpConstantComposite %118 %62 %62 +%121 = OpTypeVector %115 3 +%122 = OpConstantComposite %121 %117 %117 %117 +%123 = OpConstantComposite %121 %116 %116 %116 +%124 = OpConstantComposite %3 %53 %53 %53 %53 +%125 = OpConstantComposite %3 %15 %15 %15 %15 +%126 = OpTypeVector %115 2 +%127 = OpConstantComposite %126 %117 %117 +%128 = OpConstantComposite %126 %116 %116 +%129 = OpConstantNull %11 +%130 = OpConstantNull %12 +%131 = OpConstantComposite %10 %53 %53 %53 +%132 = OpConstantNull %13 +%296 = OpConstantNull %14 +%298 = OpTypePointer Function %6 +%299 = OpConstantNull %6 +%301 = OpTypePointer Function %14 +%329 = OpTypePointer Function %6 +%367 = OpConstantComposite %10 %15 %15 %15 +%24 = OpFunction %3 None %25 +%23 = OpLabel +OpBranch %32 +%32 = OpLabel +%33 = OpSelect %6 %26 %21 %27 +%35 = OpCompositeConstruct %7 %26 %26 %26 %26 +%34 = OpSelect %3 %35 %16 %18 +%36 = OpSelect %3 %29 %18 %16 +%37 = OpExtInst %3 %1 FMix %18 %16 %20 +%39 = OpCompositeConstruct %3 %30 %30 %30 %30 +%38 = OpExtInst %3 %1 FMix %18 %16 %39 +%40 = OpBitcast %4 %21 +%41 = OpBitcast %3 %22 +%42 = OpCompositeConstruct %5 %33 %33 %33 %33 +%43 = OpIAdd %5 %42 %31 +%44 = OpConvertSToF %3 %43 +%45 = OpFAdd %3 %44 %34 +%46 = OpFAdd %3 %45 %37 +%47 = OpFAdd %3 %46 %38 +%48 = OpCompositeConstruct %3 %40 %40 %40 %40 +%49 = OpFAdd %3 %47 %48 +%50 = OpFAdd %3 %49 %41 +OpReturnValue %50 OpFunctionEnd -%57 = OpFunction %3 None %30 -%56 = OpLabel -OpBranch %69 -%69 = OpLabel -%70 = OpFAdd %9 %60 %59 -%71 = OpFSub %9 %70 %62 -%72 = OpFDiv %9 %71 %64 -%73 = OpSRem %5 %66 %68 -%74 = OpVectorShuffle %3 %72 %72 0 1 0 1 -%75 = OpConvertSToF %3 %73 -%76 = OpFAdd %3 %74 %75 -OpReturnValue %76 +%52 = OpFunction %3 None %25 +%51 = OpLabel +OpBranch %64 +%64 = OpLabel +%65 = OpFAdd %9 %55 %54 +%66 = OpFSub %9 %65 %57 +%67 = OpFDiv %9 %66 %59 +%68 = OpSRem %5 %61 %63 +%69 = OpVectorShuffle %3 %67 %67 0 1 0 1 +%70 = OpConvertSToF %3 %68 +%71 = OpFAdd %3 %69 %70 +OpReturnValue %71 OpFunctionEnd -%78 = OpFunction %9 None %79 +%73 = OpFunction %9 None %74 +%72 = OpLabel +%75 = OpVariable %76 Function %54 +OpBranch %77 %77 = OpLabel -%80 = OpVariable %81 Function %59 -OpBranch %82 -%82 = OpLabel -%83 = OpLoad %9 %80 -%84 = OpFAdd %9 %83 %60 -OpStore %80 %84 -%85 = OpLoad %9 %80 -%86 = OpFSub %9 %85 %62 -OpStore %80 %86 -%87 = OpLoad %9 %80 -%88 = OpFDiv %9 %87 %64 -OpStore %80 %88 -%89 = OpLoad %9 %80 -OpReturnValue %89 +%78 = OpLoad %9 %75 +%79 = OpFAdd %9 %78 %55 +OpStore %75 %79 +%80 = OpLoad %9 %75 +%81 = OpFSub %9 %80 %57 +OpStore %75 %81 +%82 = OpLoad %9 %75 +%83 = OpFDiv %9 %82 %59 +OpStore %75 %83 +%84 = OpLoad %9 %75 +OpReturnValue %84 OpFunctionEnd -%92 = OpFunction %10 None %93 -%91 = OpFunctionParameter %10 -%90 = OpLabel -OpBranch %94 -%94 = OpLabel -%97 = OpFUnordNotEqual %95 %91 %96 -%99 = OpSelect %10 %97 %98 %96 -OpReturnValue %99 +%87 = OpFunction %10 None %88 +%86 = OpFunctionParameter %10 +%85 = OpLabel +OpBranch %89 +%89 = OpLabel +%92 = OpFUnordNotEqual %90 %86 %91 +%94 = OpSelect %10 %92 %93 %91 +OpReturnValue %94 OpFunctionEnd -%101 = OpFunction %2 None %102 -%100 = OpLabel -OpBranch %108 -%108 = OpLabel -%109 = OpLogicalOr %8 %31 %33 -%110 = OpLogicalOr %95 %104 %105 -%111 = OpLogicalAnd %8 %31 %33 -%112 = OpLogicalAnd %7 %106 %107 +%96 = OpFunction %2 None %97 +%95 = OpLabel +OpBranch %104 +%104 = OpLabel +%105 = OpLogicalNot %8 %26 +%106 = OpLogicalNot %98 %99 +%107 = OpLogicalOr %8 %26 %28 +%108 = OpLogicalAnd %8 %26 %28 +%109 = OpLogicalOr %8 %26 %28 +%110 = OpLogicalOr %90 %100 %101 +%111 = OpLogicalAnd %8 %26 %28 +%112 = OpLogicalAnd %7 %102 %103 OpReturn OpFunctionEnd -%114 = OpFunction %2 None %102 +%114 = OpFunction %2 None %97 %113 = OpLabel -OpBranch %141 -%141 = OpLabel -%142 = OpIAdd %12 %121 %122 -%143 = OpIAdd %13 %124 %126 -%144 = OpFAdd %3 %127 %128 -%145 = OpISub %12 %121 %122 -%146 = OpISub %13 %124 %126 -%147 = OpFSub %3 %127 %128 -%148 = OpIMul %12 %121 %122 -%149 = OpIMul %13 %124 %126 -%150 = OpFMul %3 %127 %128 -%151 = OpSDiv %12 %121 %122 -%152 = OpUDiv %13 %124 %126 -%153 = OpFDiv %3 %127 %128 -%154 = OpSRem %12 %121 %122 -%155 = OpUMod %13 %124 %126 -%156 = OpFRem %3 %127 %128 -OpBranch %157 -%157 = OpLabel -%159 = OpIAdd %12 %121 %122 -%160 = OpIAdd %12 %121 %122 -%161 = OpIAdd %15 %130 %131 -%162 = OpIAdd %15 %130 %131 -%163 = OpFAdd %9 %59 %60 -%164 = OpFAdd %9 %59 %60 -%165 = OpISub %12 %121 %122 -%166 = OpISub %12 %121 %122 -%167 = OpISub %15 %130 %131 -%168 = OpISub %15 %130 %131 -%169 = OpFSub %9 %59 %60 -%170 = OpFSub %9 %59 %60 -%171 = OpSDiv %12 %121 %122 -%172 = OpSDiv %12 %121 %122 -%173 = OpUDiv %15 %130 %131 -%174 = OpUDiv %15 %130 %131 -%175 = OpFDiv %9 %59 %60 -%176 = OpFDiv %9 %59 %60 -%177 = OpSRem %12 %121 %122 -%178 = OpSRem %12 %121 %122 -%179 = OpUMod %15 %130 %131 -%180 = OpUMod %15 %130 %131 -%181 = OpFRem %9 %59 %60 -%182 = OpFRem %9 %59 %60 -OpBranch %158 -%158 = OpLabel -%184 = OpCompositeExtract %10 %135 0 -%185 = OpCompositeExtract %10 %135 0 -%186 = OpFAdd %10 %184 %185 -%187 = OpCompositeExtract %10 %135 1 -%188 = OpCompositeExtract %10 %135 1 -%189 = OpFAdd %10 %187 %188 -%190 = OpCompositeExtract %10 %135 2 -%191 = OpCompositeExtract %10 %135 2 -%192 = OpFAdd %10 %190 %191 -%183 = OpCompositeConstruct %16 %186 %189 %192 -%194 = OpCompositeExtract %10 %135 0 -%195 = OpCompositeExtract %10 %135 0 -%196 = OpFSub %10 %194 %195 -%197 = OpCompositeExtract %10 %135 1 -%198 = OpCompositeExtract %10 %135 1 -%199 = OpFSub %10 %197 %198 -%200 = OpCompositeExtract %10 %135 2 -%201 = OpCompositeExtract %10 %135 2 -%202 = OpFSub %10 %200 %201 -%193 = OpCompositeConstruct %16 %196 %199 %202 -%203 = OpMatrixTimesVector %10 %138 %128 -%204 = OpVectorTimesMatrix %3 %139 %138 -%205 = OpMatrixTimesMatrix %16 %138 %140 +OpBranch %133 +%133 = OpLabel +%134 = OpFNegate %4 %15 +%135 = OpSNegate %118 %119 +%136 = OpFNegate %9 %55 +%137 = OpIAdd %6 %62 %21 +%138 = OpIAdd %115 %117 %116 +%139 = OpFAdd %4 %53 %15 +%140 = OpIAdd %118 %120 %119 +%141 = OpIAdd %121 %122 %123 +%142 = OpFAdd %3 %124 %125 +%143 = OpISub %6 %62 %21 +%144 = OpISub %115 %117 %116 +%145 = OpFSub %4 %53 %15 +%146 = OpISub %118 %120 %119 +%147 = OpISub %121 %122 %123 +%148 = OpFSub %3 %124 %125 +%149 = OpIMul %6 %62 %21 +%150 = OpIMul %115 %117 %116 +%151 = OpFMul %4 %53 %15 +%152 = OpIMul %118 %120 %119 +%153 = OpIMul %121 %122 %123 +%154 = OpFMul %3 %124 %125 +%155 = OpSDiv %6 %62 %21 +%156 = OpUDiv %115 %117 %116 +%157 = OpFDiv %4 %53 %15 +%158 = OpSDiv %118 %120 %119 +%159 = OpUDiv %121 %122 %123 +%160 = OpFDiv %3 %124 %125 +%161 = OpSRem %6 %62 %21 +%162 = OpUMod %115 %117 %116 +%163 = OpFRem %4 %53 %15 +%164 = OpSRem %118 %120 %119 +%165 = OpUMod %121 %122 %123 +%166 = OpFRem %3 %124 %125 +OpBranch %167 +%167 = OpLabel +%169 = OpIAdd %118 %120 %119 +%170 = OpIAdd %118 %120 %119 +%171 = OpIAdd %126 %127 %128 +%172 = OpIAdd %126 %127 %128 +%173 = OpFAdd %9 %54 %55 +%174 = OpFAdd %9 %54 %55 +%175 = OpISub %118 %120 %119 +%176 = OpISub %118 %120 %119 +%177 = OpISub %126 %127 %128 +%178 = OpISub %126 %127 %128 +%179 = OpFSub %9 %54 %55 +%180 = OpFSub %9 %54 %55 +%182 = OpCompositeConstruct %118 %21 %21 +%181 = OpIMul %118 %120 %182 +%184 = OpCompositeConstruct %118 %62 %62 +%183 = OpIMul %118 %119 %184 +%186 = OpCompositeConstruct %126 %116 %116 +%185 = OpIMul %126 %127 %186 +%188 = OpCompositeConstruct %126 %117 %117 +%187 = OpIMul %126 %128 %188 +%189 = OpVectorTimesScalar %9 %54 %15 +%190 = OpVectorTimesScalar %9 %55 %53 +%191 = OpSDiv %118 %120 %119 +%192 = OpSDiv %118 %120 %119 +%193 = OpUDiv %126 %127 %128 +%194 = OpUDiv %126 %127 %128 +%195 = OpFDiv %9 %54 %55 +%196 = OpFDiv %9 %54 %55 +%197 = OpSRem %118 %120 %119 +%198 = OpSRem %118 %120 %119 +%199 = OpUMod %126 %127 %128 +%200 = OpUMod %126 %127 %128 +%201 = OpFRem %9 %54 %55 +%202 = OpFRem %9 %54 %55 +OpBranch %168 +%168 = OpLabel +%204 = OpCompositeExtract %10 %129 0 +%205 = OpCompositeExtract %10 %129 0 +%206 = OpFAdd %10 %204 %205 +%207 = OpCompositeExtract %10 %129 1 +%208 = OpCompositeExtract %10 %129 1 +%209 = OpFAdd %10 %207 %208 +%210 = OpCompositeExtract %10 %129 2 +%211 = OpCompositeExtract %10 %129 2 +%212 = OpFAdd %10 %210 %211 +%203 = OpCompositeConstruct %11 %206 %209 %212 +%214 = OpCompositeExtract %10 %129 0 +%215 = OpCompositeExtract %10 %129 0 +%216 = OpFSub %10 %214 %215 +%217 = OpCompositeExtract %10 %129 1 +%218 = OpCompositeExtract %10 %129 1 +%219 = OpFSub %10 %217 %218 +%220 = OpCompositeExtract %10 %129 2 +%221 = OpCompositeExtract %10 %129 2 +%222 = OpFSub %10 %220 %221 +%213 = OpCompositeConstruct %11 %216 %219 %222 +%223 = OpMatrixTimesScalar %11 %129 %15 +%224 = OpMatrixTimesScalar %11 %129 %53 +%225 = OpMatrixTimesVector %10 %130 %125 +%226 = OpVectorTimesMatrix %3 %131 %130 +%227 = OpMatrixTimesMatrix %11 %130 %132 OpReturn OpFunctionEnd -%207 = OpFunction %2 None %102 -%206 = OpLabel -OpBranch %214 -%214 = OpLabel -%215 = OpBitwiseOr %12 %121 %122 -%216 = OpBitwiseOr %13 %124 %126 -%217 = OpBitwiseAnd %12 %121 %122 -%218 = OpBitwiseAnd %13 %124 %126 -%219 = OpBitwiseXor %12 %121 %122 -%220 = OpBitwiseXor %13 %124 %126 -%221 = OpShiftLeftLogical %12 %121 %131 -%222 = OpShiftLeftLogical %13 %124 %126 -%223 = OpShiftRightArithmetic %12 %121 %131 -%224 = OpShiftRightLogical %13 %124 %126 +%229 = OpFunction %2 None %97 +%228 = OpLabel +OpBranch %230 +%230 = OpLabel +%231 = OpNot %6 %21 +%232 = OpNot %115 %116 +%233 = OpNot %118 %119 +%234 = OpNot %121 %123 +%235 = OpBitwiseOr %6 %62 %21 +%236 = OpBitwiseOr %115 %117 %116 +%237 = OpBitwiseOr %118 %120 %119 +%238 = OpBitwiseOr %121 %122 %123 +%239 = OpBitwiseAnd %6 %62 %21 +%240 = OpBitwiseAnd %115 %117 %116 +%241 = OpBitwiseAnd %118 %120 %119 +%242 = OpBitwiseAnd %121 %122 %123 +%243 = OpBitwiseXor %6 %62 %21 +%244 = OpBitwiseXor %115 %117 %116 +%245 = OpBitwiseXor %118 %120 %119 +%246 = OpBitwiseXor %121 %122 %123 +%247 = OpShiftLeftLogical %6 %62 %116 +%248 = OpShiftLeftLogical %115 %117 %116 +%249 = OpShiftLeftLogical %118 %120 %128 +%250 = OpShiftLeftLogical %121 %122 %123 +%251 = OpShiftRightArithmetic %6 %62 %116 +%252 = OpShiftRightLogical %115 %117 %116 +%253 = OpShiftRightArithmetic %118 %120 %128 +%254 = OpShiftRightLogical %121 %122 %123 OpReturn OpFunctionEnd -%226 = OpFunction %2 None %102 -%225 = OpLabel -OpBranch %227 -%227 = OpLabel -%228 = OpIEqual %11 %121 %122 -%229 = OpIEqual %95 %124 %126 -%230 = OpFOrdEqual %7 %127 %128 -%231 = OpINotEqual %11 %121 %122 -%232 = OpINotEqual %95 %124 %126 -%233 = OpFOrdNotEqual %7 %127 %128 -%234 = OpSLessThan %11 %121 %122 -%235 = OpULessThan %95 %124 %126 -%236 = OpFOrdLessThan %7 %127 %128 -%237 = OpSLessThanEqual %11 %121 %122 -%238 = OpULessThanEqual %95 %124 %126 -%239 = OpFOrdLessThanEqual %7 %127 %128 -%240 = OpSGreaterThan %11 %121 %122 -%241 = OpUGreaterThan %95 %124 %126 -%242 = OpFOrdGreaterThan %7 %127 %128 -%243 = OpSGreaterThanEqual %11 %121 %122 -%244 = OpUGreaterThanEqual %95 %124 %126 -%245 = OpFOrdGreaterThanEqual %7 %127 %128 +%256 = OpFunction %2 None %97 +%255 = OpLabel +OpBranch %257 +%257 = OpLabel +%258 = OpIEqual %8 %62 %21 +%259 = OpIEqual %8 %117 %116 +%260 = OpFOrdEqual %8 %53 %15 +%261 = OpIEqual %98 %120 %119 +%262 = OpIEqual %90 %122 %123 +%263 = OpFOrdEqual %7 %124 %125 +%264 = OpINotEqual %8 %62 %21 +%265 = OpINotEqual %8 %117 %116 +%266 = OpFOrdNotEqual %8 %53 %15 +%267 = OpINotEqual %98 %120 %119 +%268 = OpINotEqual %90 %122 %123 +%269 = OpFOrdNotEqual %7 %124 %125 +%270 = OpSLessThan %8 %62 %21 +%271 = OpULessThan %8 %117 %116 +%272 = OpFOrdLessThan %8 %53 %15 +%273 = OpSLessThan %98 %120 %119 +%274 = OpULessThan %90 %122 %123 +%275 = OpFOrdLessThan %7 %124 %125 +%276 = OpSLessThanEqual %8 %62 %21 +%277 = OpULessThanEqual %8 %117 %116 +%278 = OpFOrdLessThanEqual %8 %53 %15 +%279 = OpSLessThanEqual %98 %120 %119 +%280 = OpULessThanEqual %90 %122 %123 +%281 = OpFOrdLessThanEqual %7 %124 %125 +%282 = OpSGreaterThan %8 %62 %21 +%283 = OpUGreaterThan %8 %117 %116 +%284 = OpFOrdGreaterThan %8 %53 %15 +%285 = OpSGreaterThan %98 %120 %119 +%286 = OpUGreaterThan %90 %122 %123 +%287 = OpFOrdGreaterThan %7 %124 %125 +%288 = OpSGreaterThanEqual %8 %62 %21 +%289 = OpUGreaterThanEqual %8 %117 %116 +%290 = OpFOrdGreaterThanEqual %8 %53 %15 +%291 = OpSGreaterThanEqual %98 %120 %119 +%292 = OpUGreaterThanEqual %90 %122 %123 +%293 = OpFOrdGreaterThanEqual %7 %124 %125 OpReturn OpFunctionEnd -%247 = OpFunction %2 None %102 -%246 = OpLabel -%249 = OpVariable %250 Function %26 -%251 = OpVariable %252 Function %248 -OpBranch %253 -%253 = OpLabel -%254 = OpLoad %6 %249 -%255 = OpIAdd %6 %254 %26 -OpStore %249 %255 -%256 = OpLoad %6 %249 -%257 = OpISub %6 %256 %26 -OpStore %249 %257 -%258 = OpLoad %6 %249 -%259 = OpLoad %6 %249 -%260 = OpIMul %6 %259 %258 -OpStore %249 %260 -%261 = OpLoad %6 %249 -%262 = OpLoad %6 %249 -%263 = OpSDiv %6 %262 %261 -OpStore %249 %263 -%264 = OpLoad %6 %249 -%265 = OpSRem %6 %264 %26 -OpStore %249 %265 -%266 = OpLoad %6 %249 -%267 = OpBitwiseAnd %6 %266 %32 -OpStore %249 %267 -%268 = OpLoad %6 %249 -%269 = OpBitwiseOr %6 %268 %32 -OpStore %249 %269 -%270 = OpLoad %6 %249 -%271 = OpBitwiseXor %6 %270 %32 -OpStore %249 %271 -%272 = OpLoad %6 %249 -%273 = OpShiftLeftLogical %6 %272 %123 -OpStore %249 %273 -%274 = OpLoad %6 %249 -%275 = OpShiftRightArithmetic %6 %274 %125 -OpStore %249 %275 -%276 = OpLoad %6 %249 -%277 = OpIAdd %6 %276 %26 -OpStore %249 %277 -%278 = OpLoad %6 %249 -%279 = OpISub %6 %278 %26 -OpStore %249 %279 -%281 = OpAccessChain %280 %251 %125 -%282 = OpLoad %6 %281 -%283 = OpIAdd %6 %282 %26 -%284 = OpAccessChain %280 %251 %125 -OpStore %284 %283 -%285 = OpAccessChain %280 %251 %125 -%286 = OpLoad %6 %285 -%287 = OpISub %6 %286 %26 -%288 = OpAccessChain %280 %251 %125 -OpStore %288 %287 +%295 = OpFunction %2 None %97 +%294 = OpLabel +%297 = OpVariable %298 Function %299 +%300 = OpVariable %301 Function %296 +OpBranch %302 +%302 = OpLabel +OpStore %297 %21 +%303 = OpLoad %6 %297 +%304 = OpIAdd %6 %303 %21 +OpStore %297 %304 +%305 = OpLoad %6 %297 +%306 = OpISub %6 %305 %21 +OpStore %297 %306 +%307 = OpLoad %6 %297 +%308 = OpLoad %6 %297 +%309 = OpIMul %6 %308 %307 +OpStore %297 %309 +%310 = OpLoad %6 %297 +%311 = OpLoad %6 %297 +%312 = OpSDiv %6 %311 %310 +OpStore %297 %312 +%313 = OpLoad %6 %297 +%314 = OpSRem %6 %313 %21 +OpStore %297 %314 +%315 = OpLoad %6 %297 +%316 = OpBitwiseAnd %6 %315 %27 +OpStore %297 %316 +%317 = OpLoad %6 %297 +%318 = OpBitwiseOr %6 %317 %27 +OpStore %297 %318 +%319 = OpLoad %6 %297 +%320 = OpBitwiseXor %6 %319 %27 +OpStore %297 %320 +%321 = OpLoad %6 %297 +%322 = OpShiftLeftLogical %6 %321 %117 +OpStore %297 %322 +%323 = OpLoad %6 %297 +%324 = OpShiftRightArithmetic %6 %323 %116 +OpStore %297 %324 +%325 = OpLoad %6 %297 +%326 = OpIAdd %6 %325 %21 +OpStore %297 %326 +%327 = OpLoad %6 %297 +%328 = OpISub %6 %327 %21 +OpStore %297 %328 +%330 = OpAccessChain %329 %300 %21 +%331 = OpLoad %6 %330 +%332 = OpIAdd %6 %331 %21 +%333 = OpAccessChain %329 %300 %21 +OpStore %333 %332 +%334 = OpAccessChain %329 %300 %21 +%335 = OpLoad %6 %334 +%336 = OpISub %6 %335 %21 +%337 = OpAccessChain %329 %300 %21 +OpStore %337 %336 OpReturn OpFunctionEnd -%290 = OpFunction %2 None %102 -%289 = OpLabel -OpBranch %295 -%295 = OpLabel +%339 = OpFunction %2 None %97 +%338 = OpLabel +OpBranch %340 +%340 = OpLabel +%341 = OpSNegate %6 %21 +%342 = OpSNegate %6 %21 +%343 = OpSNegate %6 %342 +%344 = OpSNegate %6 %21 +%345 = OpSNegate %6 %344 +%346 = OpSNegate %6 %21 +%347 = OpSNegate %6 %346 +%348 = OpSNegate %6 %21 +%349 = OpSNegate %6 %348 +%350 = OpSNegate %6 %349 +%351 = OpSNegate %6 %21 +%352 = OpSNegate %6 %351 +%353 = OpSNegate %6 %352 +%354 = OpSNegate %6 %353 +%355 = OpSNegate %6 %21 +%356 = OpSNegate %6 %355 +%357 = OpSNegate %6 %356 +%358 = OpSNegate %6 %357 +%359 = OpSNegate %6 %358 +%360 = OpSNegate %6 %21 +%361 = OpSNegate %6 %360 +%362 = OpSNegate %6 %361 +%363 = OpSNegate %6 %362 +%364 = OpSNegate %6 %363 OpReturn OpFunctionEnd -%297 = OpFunction %2 None %102 -%296 = OpLabel -OpBranch %299 -%299 = OpLabel -%300 = OpFunctionCall %3 %29 -%301 = OpFunctionCall %3 %57 -%302 = OpFunctionCall %10 %92 %298 -%303 = OpFunctionCall %2 %101 -%304 = OpFunctionCall %2 %114 -%305 = OpFunctionCall %2 %207 -%306 = OpFunctionCall %2 %226 -%307 = OpFunctionCall %2 %247 +%366 = OpFunction %2 None %97 +%365 = OpLabel +OpBranch %368 +%368 = OpLabel +%369 = OpFunctionCall %3 %24 +%370 = OpFunctionCall %3 %52 +%371 = OpFunctionCall %10 %87 %367 +%372 = OpFunctionCall %2 %96 +%373 = OpFunctionCall %2 %114 +%374 = OpFunctionCall %2 %229 +%375 = OpFunctionCall %2 %256 +%376 = OpFunctionCall %2 %295 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 9c07526d3..5038bdc85 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -40,7 +40,10 @@ fn bool_cast(x: vec3) -> vec3 { } fn logical() { - let neg1_ = vec2(false, false); + let neg0_ = !(true); + let neg1_ = !(vec2(true)); + let or = (true || false); + let and = (true && false); let bitwise_or0_ = (true | false); let bitwise_or1_ = (vec3(true) | vec3(false)); let bitwise_and0_ = (true & false); @@ -48,139 +51,193 @@ fn logical() { } fn arithmetic() { - let neg1_1 = vec2(-1, -1); - let neg2_ = vec2(-1.0, -1.0); + let neg0_1 = -(1.0); + let neg1_1 = -(vec2(1)); + let neg2_ = -(vec2(1.0)); + let add0_ = (2 + 1); + let add1_ = (2u + 1u); + let add2_ = (2.0 + 1.0); let add3_ = (vec2(2) + vec2(1)); let add4_ = (vec3(2u) + vec3(1u)); let add5_ = (vec4(2.0) + vec4(1.0)); + let sub0_ = (2 - 1); + let sub1_ = (2u - 1u); + let sub2_ = (2.0 - 1.0); let sub3_ = (vec2(2) - vec2(1)); let sub4_ = (vec3(2u) - vec3(1u)); let sub5_ = (vec4(2.0) - vec4(1.0)); + let mul0_ = (2 * 1); + let mul1_ = (2u * 1u); + let mul2_ = (2.0 * 1.0); let mul3_ = (vec2(2) * vec2(1)); let mul4_ = (vec3(2u) * vec3(1u)); let mul5_ = (vec4(2.0) * vec4(1.0)); + let div0_ = (2 / 1); + let div1_ = (2u / 1u); + let div2_ = (2.0 / 1.0); let div3_ = (vec2(2) / vec2(1)); let div4_ = (vec3(2u) / vec3(1u)); let div5_ = (vec4(2.0) / vec4(1.0)); + let rem0_ = (2 % 1); + let rem1_ = (2u % 1u); + let rem2_ = (2.0 % 1.0); let rem3_ = (vec2(2) % vec2(1)); let rem4_ = (vec3(2u) % vec3(1u)); let rem5_ = (vec4(2.0) % vec4(1.0)); { - let add0_ = (vec2(2) + vec2(1)); - let add1_ = (vec2(2) + vec2(1)); - let add2_ = (vec2(2u) + vec2(1u)); + let add0_1 = (vec2(2) + vec2(1)); + let add1_1 = (vec2(2) + vec2(1)); + let add2_1 = (vec2(2u) + vec2(1u)); let add3_1 = (vec2(2u) + vec2(1u)); let add4_1 = (vec2(2.0) + vec2(1.0)); let add5_1 = (vec2(2.0) + vec2(1.0)); - let sub0_ = (vec2(2) - vec2(1)); - let sub1_ = (vec2(2) - vec2(1)); - let sub2_ = (vec2(2u) - vec2(1u)); + let sub0_1 = (vec2(2) - vec2(1)); + let sub1_1 = (vec2(2) - vec2(1)); + let sub2_1 = (vec2(2u) - vec2(1u)); let sub3_1 = (vec2(2u) - vec2(1u)); let sub4_1 = (vec2(2.0) - vec2(1.0)); let sub5_1 = (vec2(2.0) - vec2(1.0)); - let mul0_ = vec2(2, 2); - let mul1_ = vec2(2, 2); - let mul2_ = vec2(2u, 2u); - let mul3_1 = vec2(2u, 2u); - let mul4_1 = vec2(2.0, 2.0); - let mul5_1 = vec2(2.0, 2.0); - let div0_ = (vec2(2) / vec2(1)); - let div1_ = (vec2(2) / vec2(1)); - let div2_ = (vec2(2u) / vec2(1u)); + let mul0_1 = (vec2(2) * 1); + let mul1_1 = (2 * vec2(1)); + let mul2_1 = (vec2(2u) * 1u); + let mul3_1 = (2u * vec2(1u)); + let mul4_1 = (vec2(2.0) * 1.0); + let mul5_1 = (2.0 * vec2(1.0)); + let div0_1 = (vec2(2) / vec2(1)); + let div1_1 = (vec2(2) / vec2(1)); + let div2_1 = (vec2(2u) / vec2(1u)); let div3_1 = (vec2(2u) / vec2(1u)); let div4_1 = (vec2(2.0) / vec2(1.0)); let div5_1 = (vec2(2.0) / vec2(1.0)); - let rem0_ = (vec2(2) % vec2(1)); - let rem1_ = (vec2(2) % vec2(1)); - let rem2_ = (vec2(2u) % vec2(1u)); + let rem0_1 = (vec2(2) % vec2(1)); + let rem1_1 = (vec2(2) % vec2(1)); + let rem2_1 = (vec2(2u) % vec2(1u)); let rem3_1 = (vec2(2u) % vec2(1u)); let rem4_1 = (vec2(2.0) % vec2(1.0)); let rem5_1 = (vec2(2.0) % vec2(1.0)); } let add = (mat3x3() + mat3x3()); let sub = (mat3x3() - mat3x3()); - let mul_scalar0_ = mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); - let mul_scalar1_ = mat3x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); + let mul_scalar0_ = (mat3x3() * 1.0); + let mul_scalar1_ = (2.0 * mat3x3()); let mul_vector0_ = (mat4x3() * vec4(1.0)); let mul_vector1_ = (vec3(2.0) * mat4x3()); let mul = (mat4x3() * mat3x4()); } fn bit() { - let flip2_ = vec2(-2, -2); - let flip3_ = vec3(4294967294u, 4294967294u, 4294967294u); + let flip0_ = ~(1); + let flip1_ = ~(1u); + let flip2_ = !(vec2(1)); + let flip3_ = !(vec3(1u)); + let or0_ = (2 | 1); + let or1_ = (2u | 1u); let or2_ = (vec2(2) | vec2(1)); let or3_ = (vec3(2u) | vec3(1u)); + let and0_ = (2 & 1); + let and1_ = (2u & 1u); let and2_ = (vec2(2) & vec2(1)); let and3_ = (vec3(2u) & vec3(1u)); + let xor0_ = (2 ^ 1); + let xor1_ = (2u ^ 1u); let xor2_ = (vec2(2) ^ vec2(1)); let xor3_ = (vec3(2u) ^ vec3(1u)); + let shl0_ = (2 << 1u); + let shl1_ = (2u << 1u); let shl2_ = (vec2(2) << vec2(1u)); let shl3_ = (vec3(2u) << vec3(1u)); + let shr0_ = (2 >> 1u); + let shr1_ = (2u >> 1u); let shr2_ = (vec2(2) >> vec2(1u)); let shr3_ = (vec3(2u) >> vec3(1u)); } fn comparison() { + let eq0_ = (2 == 1); + let eq1_ = (2u == 1u); + let eq2_ = (2.0 == 1.0); let eq3_ = (vec2(2) == vec2(1)); let eq4_ = (vec3(2u) == vec3(1u)); let eq5_ = (vec4(2.0) == vec4(1.0)); + let neq0_ = (2 != 1); + let neq1_ = (2u != 1u); + let neq2_ = (2.0 != 1.0); let neq3_ = (vec2(2) != vec2(1)); let neq4_ = (vec3(2u) != vec3(1u)); let neq5_ = (vec4(2.0) != vec4(1.0)); + let lt0_ = (2 < 1); + let lt1_ = (2u < 1u); + let lt2_ = (2.0 < 1.0); let lt3_ = (vec2(2) < vec2(1)); let lt4_ = (vec3(2u) < vec3(1u)); let lt5_ = (vec4(2.0) < vec4(1.0)); + let lte0_ = (2 <= 1); + let lte1_ = (2u <= 1u); + let lte2_ = (2.0 <= 1.0); let lte3_ = (vec2(2) <= vec2(1)); let lte4_ = (vec3(2u) <= vec3(1u)); let lte5_ = (vec4(2.0) <= vec4(1.0)); + let gt0_ = (2 > 1); + let gt1_ = (2u > 1u); + let gt2_ = (2.0 > 1.0); let gt3_ = (vec2(2) > vec2(1)); let gt4_ = (vec3(2u) > vec3(1u)); let gt5_ = (vec4(2.0) > vec4(1.0)); + let gte0_ = (2 >= 1); + let gte1_ = (2u >= 1u); + let gte2_ = (2.0 >= 1.0); let gte3_ = (vec2(2) >= vec2(1)); let gte4_ = (vec3(2u) >= vec3(1u)); let gte5_ = (vec4(2.0) >= vec4(1.0)); } fn assignment() { - var a_1: i32 = 1; + var a_1: i32; var vec0_: vec3 = vec3(); - let _e3 = a_1; - a_1 = (_e3 + 1); - let _e6 = a_1; - a_1 = (_e6 - 1); - let _e8 = a_1; + a_1 = 1; + let _e5 = a_1; + a_1 = (_e5 + 1); + let _e7 = a_1; + a_1 = (_e7 - 1); let _e9 = a_1; - a_1 = (_e9 * _e8); - let _e11 = a_1; + let _e10 = a_1; + a_1 = (_e10 * _e9); let _e12 = a_1; - a_1 = (_e12 / _e11); + let _e13 = a_1; + a_1 = (_e13 / _e12); let _e15 = a_1; a_1 = (_e15 % 1); - let _e18 = a_1; - a_1 = (_e18 & 0); + let _e17 = a_1; + a_1 = (_e17 & 0); + let _e19 = a_1; + a_1 = (_e19 | 0); let _e21 = a_1; - a_1 = (_e21 | 0); - let _e24 = a_1; - a_1 = (_e24 ^ 0); - let _e27 = a_1; - a_1 = (_e27 << 2u); - let _e30 = a_1; - a_1 = (_e30 >> 1u); - let _e33 = a_1; - a_1 = (_e33 + 1); - let _e36 = a_1; - a_1 = (_e36 - 1); - let _e42 = vec0_.y; - vec0_.y = (_e42 + 1); - let _e46 = vec0_.y; - vec0_.y = (_e46 - 1); + a_1 = (_e21 ^ 0); + let _e23 = a_1; + a_1 = (_e23 << 2u); + let _e25 = a_1; + a_1 = (_e25 >> 1u); + let _e28 = a_1; + a_1 = (_e28 + 1); + let _e31 = a_1; + a_1 = (_e31 - 1); + let _e37 = vec0_[1]; + vec0_[1] = (_e37 + 1); + let _e41 = vec0_[1]; + vec0_[1] = (_e41 - 1); return; } fn negation_avoids_prefix_decrement() { - return; + let p0_ = -(1); + let p1_ = -(-(1)); + let p2_ = -(-(1)); + let p3_ = -(-(1)); + let p4_ = -(-(-(1))); + let p5_ = -(-(-(-(1)))); + let p6_ = -(-(-(-(-(1))))); + let p7_ = -(-(-(-(-(1))))); } @compute @workgroup_size(1, 1, 1) From 504b33d8cd40174e21b142b00f50c7901198e7e6 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 9 Oct 2023 10:35:46 -0700 Subject: [PATCH 2160/2212] [wgsl-in] Document necessity of `force_non_const`. --- src/front/wgsl/lower/mod.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 94118e65e..6bbd8d919 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -106,7 +106,16 @@ pub struct StatementContext<'source, 'temp, 'out> { named_expressions: &'out mut FastIndexMap, (String, Span)>, arguments: &'out [crate::FunctionArgument], module: &'out mut crate::Module, - /// Tracks the constness of `Expression`s residing in `self.naga_expressions` + + /// Which `Expression`s in `self.naga_expressions` are const expressions, in + /// the WGSL sense. + /// + /// According to the WGSL spec, a const expression must not refer to any + /// `let` declarations, even if those declarations' initializers are + /// themselves const expressions. So this tracker is not simply concerned + /// with the form of the expressions; it is also tracking whether WGSL says + /// we should consider them to be const. See the use of `force_non_const` in + /// the code for lowering `let` bindings. expression_constness: &'temp mut crate::proc::ExpressionConstnessTracker, } @@ -192,7 +201,11 @@ pub struct RuntimeExpressionContext<'temp, 'out> { block: &'temp mut crate::Block, emitter: &'temp mut Emitter, typifier: &'temp mut Typifier, - /// Tracks the constness of `Expression`s residing in `self.naga_expressions` + + /// Which `Expression`s in `self.naga_expressions` are const expressions, in + /// the WGSL sense. + /// + /// See [`StatementContext::expression_constness`] for details. expression_constness: &'temp mut crate::proc::ExpressionConstnessTracker, } @@ -1087,6 +1100,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { emitter.start(ctx.naga_expressions); let value = self.expression(l.init, ctx.as_expression(block, &mut emitter))?; + + // The WGSL spec says that any expression that refers to a + // `let`-bound variable is not a const expression. This + // affects when errors must be reported, so we can't even + // treat suitable `let` bindings as constant as an + // optimization. ctx.expression_constness.force_non_const(value); let explicit_ty = From a3ba3259fe83b4cb0741b8e69e457b7dc18a7160 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 9 Oct 2023 20:03:11 -0700 Subject: [PATCH 2161/2212] Some documentation for ConstantEvaluator. --- src/proc/constant_evaluator.rs | 66 ++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 61adf0fdd..70a46114a 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -10,11 +10,40 @@ enum Behavior { Glsl, } +/// A context for evaluating constant expressions. +/// +/// A `ConstantEvaluator` points at an expression arena to which it can append +/// newly evaluated expressions: you pass [`try_eval_and_append`] whatever kind +/// of Naga [`Expression`] you like, and if its value can be computed at compile +/// time, `try_eval_and_append` appends an expression representing the computed +/// value - a tree of [`Literal`], [`Compose`], [`ZeroValue`], and [`Swizzle`] +/// expressions - to the arena. See the [`try_eval_and_append`] method for details. +/// +/// A `ConstantEvaluator` also holds whatever information we need to carry out +/// that evaluation: types, other constants, and so on. +/// +/// [`try_eval_and_append`]: ConstantEvaluator::try_eval_and_append +/// [`Compose`]: Expression::Compose +/// [`ZeroValue`]: Expression::ZeroValue +/// [`Literal`]: Expression::Literal +/// [`Swizzle`]: Expression::Swizzle #[derive(Debug)] pub struct ConstantEvaluator<'a> { + /// Which language's evaluation rules we should follow. behavior: Behavior, + + /// The module's type arena. + /// + /// Because expressions like [`Splat`] contain type handles, we need to be + /// able to add new types to produce those expressions. + /// + /// [`Splat`]: Expression::Splat types: &'a mut UniqueArena, + + /// The module's constant arena. constants: &'a Arena, + + /// The arena to which we are contributing expressions. expressions: &'a mut Arena, /// When `self.expressions` refers to a function's local expression @@ -149,10 +178,18 @@ pub enum ConstantEvaluatorError { } impl<'a> ConstantEvaluator<'a> { + /// Return a [`ConstantEvaluator`] that will add expressions to `module`'s + /// constant expression arena. + /// + /// Report errors according to WGSL's rules for constant evaluation. pub fn for_wgsl_module(module: &'a mut crate::Module) -> Self { Self::for_module(Behavior::Wgsl, module) } + /// Return a [`ConstantEvaluator`] that will add expressions to `module`'s + /// constant expression arena. + /// + /// Report errors according to GLSL's rules for constant evaluation. pub fn for_glsl_module(module: &'a mut crate::Module) -> Self { Self::for_module(Behavior::Glsl, module) } @@ -167,6 +204,10 @@ impl<'a> ConstantEvaluator<'a> { } } + /// Return a [`ConstantEvaluator`] that will add expressions to `function`'s + /// expression arena. + /// + /// Report errors according to WGSL's rules for constant evaluation. pub fn for_wgsl_function( module: &'a mut crate::Module, expressions: &'a mut Arena, @@ -184,6 +225,10 @@ impl<'a> ConstantEvaluator<'a> { ) } + /// Return a [`ConstantEvaluator`] that will add expressions to `function`'s + /// expression arena. + /// + /// Report errors according to GLSL's rules for constant evaluation. pub fn for_glsl_function( module: &'a mut crate::Module, expressions: &'a mut Arena, @@ -259,6 +304,27 @@ impl<'a> ConstantEvaluator<'a> { } } + /// Try to evaluate `expr` at compile time. + /// + /// The `expr` argument can be any sort of Naga [`Expression`] you like. If + /// we can determine its value at compile time, we append an expression + /// representing its value - a tree of [`Literal`], [`Compose`], + /// [`ZeroValue`], and [`Swizzle`] expressions - to the expression arena + /// `self` contributes to. + /// + /// If `expr`'s value cannot be determined at compile time, return a an + /// error. If it's acceptable to evaluate `expr` at runtime, this error can + /// be ignored, and the caller can append `expr` to the arena itself. + /// + /// We only consider `expr` itself, without recursing into its operands. Its + /// operands must all have been produced by prior calls to + /// `try_eval_and_append`, to ensure that they have already been reduced to + /// an evaluated form if possible. + /// + /// [`Literal`]: Expression::Literal + /// [`Compose`]: Expression::Compose + /// [`ZeroValue`]: Expression::ZeroValue + /// [`Swizzle`]: Expression::Swizzle pub fn try_eval_and_append( &mut self, expr: &Expression, From f7e15bf391029d15ff40bedf5200822530726a00 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 11 Oct 2023 14:07:20 +0200 Subject: [PATCH 2162/2212] [valid] check local variable initializer is const --- src/lib.rs | 8 +++++++- src/valid/function.rs | 13 ++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 80461e16f..9d7019042 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -978,7 +978,13 @@ pub struct LocalVariable { pub name: Option, /// The type of this variable. pub ty: Handle, - /// Initial value for this variable. Must be a const-expression. + /// Initial value for this variable. + /// + /// This handle refers to this `LocalVariable`'s function's + /// [`expressions`] arena, but it is required to be an evaluated + /// constant expression. + /// + /// [`expressions`]: Function::expressions pub init: Option>, } diff --git a/src/valid/function.rs b/src/valid/function.rs index a056a1d1f..ca5877ba1 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -58,6 +58,8 @@ pub enum LocalVariableError { InvalidType(Handle), #[error("Initializer doesn't match the variable type")] InitializerType, + #[error("Initializer is not const")] + NonConstInitializer, } #[derive(Clone, Debug, thiserror::Error)] @@ -942,6 +944,7 @@ impl super::Validator { var: &crate::LocalVariable, gctx: crate::proc::GlobalCtx, fun_info: &FunctionInfo, + expression_constness: &crate::proc::ExpressionConstnessTracker, ) -> Result<(), LocalVariableError> { log::debug!("var {:?}", var); let type_info = self @@ -958,6 +961,10 @@ impl super::Validator { if !decl_ty.equivalent(init_ty, gctx.types) { return Err(LocalVariableError::InitializerType); } + + if !expression_constness.is_const(init) { + return Err(LocalVariableError::NonConstInitializer); + } } Ok(()) @@ -973,9 +980,13 @@ impl super::Validator { #[cfg_attr(not(feature = "validate"), allow(unused_mut))] let mut info = mod_info.process_function(fun, module, self.flags, self.capabilities)?; + #[cfg(feature = "validate")] + let expression_constness = + crate::proc::ExpressionConstnessTracker::from_arena(&fun.expressions); + #[cfg(feature = "validate")] for (var_handle, var) in fun.local_variables.iter() { - self.validate_local_var(var, module.to_ctx(), &info) + self.validate_local_var(var, module.to_ctx(), &info, &expression_constness) .map_err(|source| { FunctionError::LocalVariable { handle: var_handle, From 1b485ea92514d2efc3328bc1122e53a2ed0e4ffa Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 11 Oct 2023 17:17:01 -0700 Subject: [PATCH 2163/2212] [wgsl-in] Don't double-initialize variables local to loops. --- src/front/wgsl/lower/mod.rs | 16 +- tests/out/spv/atomicCompareExchange.spvasm | 270 +++++++++++---------- tests/out/wgsl/atomicCompareExchange.wgsl | 4 +- 3 files changed, 151 insertions(+), 139 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 6bbd8d919..c883732e8 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1181,10 +1181,20 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let (const_initializer, initializer) = { match initializer { - Some(init) if ctx.expression_constness.is_const(init) => { - (Some(init), is_inside_loop.then_some(init)) + Some(init) => { + // It's not correct to hoist the initializer up + // to the top of the function if: + // - the initialization is inside a loop, and should + // take place on every iteration, or + // - the initialization is not a constant + // expression, so its value depends on the + // state at the point of initialization. + if is_inside_loop || !ctx.expression_constness.is_const(init) { + (None, Some(init)) + } else { + (Some(init), None) + } } - Some(init) => (None, Some(init)), None => (None, None), } }; diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/tests/out/spv/atomicCompareExchange.spvasm index d08e3656f..bfd4591d4 100644 --- a/tests/out/spv/atomicCompareExchange.spvasm +++ b/tests/out/spv/atomicCompareExchange.spvasm @@ -1,15 +1,15 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 122 +; Bound: 124 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %18 "test_atomic_compare_exchange_i32" -OpEntryPoint GLCompute %76 "test_atomic_compare_exchange_u32" +OpEntryPoint GLCompute %77 "test_atomic_compare_exchange_u32" OpExecutionMode %18 LocalSize 1 1 1 -OpExecutionMode %76 LocalSize 1 1 1 +OpExecutionMode %77 LocalSize 1 1 1 OpDecorate %5 ArrayStride 4 OpDecorate %7 ArrayStride 4 OpMemberDecorate %9 0 Offset 0 @@ -50,153 +50,155 @@ OpMemberDecorate %15 0 Offset 0 %30 = OpTypePointer Function %4 %31 = OpConstantNull %4 %33 = OpTypePointer Function %8 -%46 = OpTypePointer StorageBuffer %4 -%49 = OpConstant %4 1 -%50 = OpConstant %3 64 -%77 = OpTypePointer StorageBuffer %7 -%81 = OpConstantNull %3 -%95 = OpTypePointer StorageBuffer %3 +%34 = OpConstantNull %8 +%47 = OpTypePointer StorageBuffer %4 +%50 = OpConstant %4 1 +%51 = OpConstant %3 64 +%78 = OpTypePointer StorageBuffer %7 +%82 = OpConstantNull %3 +%84 = OpConstantNull %8 +%97 = OpTypePointer StorageBuffer %3 %18 = OpFunction %2 None %19 %17 = OpLabel %27 = OpVariable %28 Function %21 %29 = OpVariable %30 Function %31 -%32 = OpVariable %33 Function %23 +%32 = OpVariable %33 Function %34 %22 = OpAccessChain %20 %11 %21 -OpBranch %34 -%34 = OpLabel OpBranch %35 %35 = OpLabel -OpLoopMerge %36 %38 None -OpBranch %37 -%37 = OpLabel -%39 = OpLoad %3 %27 -%40 = OpULessThan %8 %39 %6 -OpSelectionMerge %41 None -OpBranchConditional %40 %41 %42 -%42 = OpLabel OpBranch %36 -%41 = OpLabel -OpBranch %43 -%43 = OpLabel -%45 = OpLoad %3 %27 -%47 = OpAccessChain %46 %22 %45 -%48 = OpAtomicLoad %4 %47 %49 %50 -OpStore %29 %48 -OpStore %32 %23 -OpBranch %51 -%51 = OpLabel -OpLoopMerge %52 %54 None -OpBranch %53 -%53 = OpLabel -%55 = OpLoad %8 %32 -%56 = OpLogicalNot %8 %55 -OpSelectionMerge %57 None -OpBranchConditional %56 %57 %58 -%58 = OpLabel -OpBranch %52 -%57 = OpLabel -OpBranch %59 -%59 = OpLabel -%61 = OpLoad %4 %29 -%62 = OpBitcast %24 %61 -%63 = OpFAdd %24 %62 %25 -%64 = OpBitcast %4 %63 -%65 = OpLoad %3 %27 -%66 = OpLoad %4 %29 -%68 = OpAccessChain %46 %22 %65 -%69 = OpAtomicCompareExchange %4 %68 %49 %50 %50 %64 %66 -%70 = OpIEqual %8 %69 %66 -%67 = OpCompositeConstruct %9 %69 %70 -%71 = OpCompositeExtract %4 %67 0 -OpStore %29 %71 -%72 = OpCompositeExtract %8 %67 1 -OpStore %32 %72 -OpBranch %60 -%60 = OpLabel -OpBranch %54 -%54 = OpLabel -OpBranch %51 -%52 = OpLabel -OpBranch %44 -%44 = OpLabel +%36 = OpLabel +OpLoopMerge %37 %39 None OpBranch %38 %38 = OpLabel -%73 = OpLoad %3 %27 -%74 = OpIAdd %3 %73 %26 -OpStore %27 %74 -OpBranch %35 -%36 = OpLabel +%40 = OpLoad %3 %27 +%41 = OpULessThan %8 %40 %6 +OpSelectionMerge %42 None +OpBranchConditional %41 %42 %43 +%43 = OpLabel +OpBranch %37 +%42 = OpLabel +OpBranch %44 +%44 = OpLabel +%46 = OpLoad %3 %27 +%48 = OpAccessChain %47 %22 %46 +%49 = OpAtomicLoad %4 %48 %50 %51 +OpStore %29 %49 +OpStore %32 %23 +OpBranch %52 +%52 = OpLabel +OpLoopMerge %53 %55 None +OpBranch %54 +%54 = OpLabel +%56 = OpLoad %8 %32 +%57 = OpLogicalNot %8 %56 +OpSelectionMerge %58 None +OpBranchConditional %57 %58 %59 +%59 = OpLabel +OpBranch %53 +%58 = OpLabel +OpBranch %60 +%60 = OpLabel +%62 = OpLoad %4 %29 +%63 = OpBitcast %24 %62 +%64 = OpFAdd %24 %63 %25 +%65 = OpBitcast %4 %64 +%66 = OpLoad %3 %27 +%67 = OpLoad %4 %29 +%69 = OpAccessChain %47 %22 %66 +%70 = OpAtomicCompareExchange %4 %69 %50 %51 %51 %65 %67 +%71 = OpIEqual %8 %70 %67 +%68 = OpCompositeConstruct %9 %70 %71 +%72 = OpCompositeExtract %4 %68 0 +OpStore %29 %72 +%73 = OpCompositeExtract %8 %68 1 +OpStore %32 %73 +OpBranch %61 +%61 = OpLabel +OpBranch %55 +%55 = OpLabel +OpBranch %52 +%53 = OpLabel +OpBranch %45 +%45 = OpLabel +OpBranch %39 +%39 = OpLabel +%74 = OpLoad %3 %27 +%75 = OpIAdd %3 %74 %26 +OpStore %27 %75 +OpBranch %36 +%37 = OpLabel OpReturn OpFunctionEnd -%76 = OpFunction %2 None %19 -%75 = OpLabel -%79 = OpVariable %28 Function %21 -%80 = OpVariable %28 Function %81 -%82 = OpVariable %33 Function %23 -%78 = OpAccessChain %77 %14 %21 -OpBranch %83 -%83 = OpLabel -OpBranch %84 -%84 = OpLabel -OpLoopMerge %85 %87 None +%77 = OpFunction %2 None %19 +%76 = OpLabel +%80 = OpVariable %28 Function %21 +%81 = OpVariable %28 Function %82 +%83 = OpVariable %33 Function %84 +%79 = OpAccessChain %78 %14 %21 +OpBranch %85 +%85 = OpLabel OpBranch %86 %86 = OpLabel -%88 = OpLoad %3 %79 -%89 = OpULessThan %8 %88 %6 -OpSelectionMerge %90 None -OpBranchConditional %89 %90 %91 -%91 = OpLabel -OpBranch %85 -%90 = OpLabel -OpBranch %92 -%92 = OpLabel -%94 = OpLoad %3 %79 -%96 = OpAccessChain %95 %78 %94 -%97 = OpAtomicLoad %3 %96 %49 %50 -OpStore %80 %97 -OpStore %82 %23 -OpBranch %98 -%98 = OpLabel -OpLoopMerge %99 %101 None -OpBranch %100 -%100 = OpLabel -%102 = OpLoad %8 %82 -%103 = OpLogicalNot %8 %102 -OpSelectionMerge %104 None -OpBranchConditional %103 %104 %105 -%105 = OpLabel -OpBranch %99 -%104 = OpLabel -OpBranch %106 -%106 = OpLabel -%108 = OpLoad %3 %80 -%109 = OpBitcast %24 %108 -%110 = OpFAdd %24 %109 %25 -%111 = OpBitcast %3 %110 -%112 = OpLoad %3 %79 -%113 = OpLoad %3 %80 -%115 = OpAccessChain %95 %78 %112 -%116 = OpAtomicCompareExchange %3 %115 %49 %50 %50 %111 %113 -%117 = OpIEqual %8 %116 %113 -%114 = OpCompositeConstruct %10 %116 %117 -%118 = OpCompositeExtract %3 %114 0 -OpStore %80 %118 -%119 = OpCompositeExtract %8 %114 1 -OpStore %82 %119 -OpBranch %107 -%107 = OpLabel -OpBranch %101 -%101 = OpLabel -OpBranch %98 -%99 = OpLabel -OpBranch %93 +OpLoopMerge %87 %89 None +OpBranch %88 +%88 = OpLabel +%90 = OpLoad %3 %80 +%91 = OpULessThan %8 %90 %6 +OpSelectionMerge %92 None +OpBranchConditional %91 %92 %93 %93 = OpLabel OpBranch %87 +%92 = OpLabel +OpBranch %94 +%94 = OpLabel +%96 = OpLoad %3 %80 +%98 = OpAccessChain %97 %79 %96 +%99 = OpAtomicLoad %3 %98 %50 %51 +OpStore %81 %99 +OpStore %83 %23 +OpBranch %100 +%100 = OpLabel +OpLoopMerge %101 %103 None +OpBranch %102 +%102 = OpLabel +%104 = OpLoad %8 %83 +%105 = OpLogicalNot %8 %104 +OpSelectionMerge %106 None +OpBranchConditional %105 %106 %107 +%107 = OpLabel +OpBranch %101 +%106 = OpLabel +OpBranch %108 +%108 = OpLabel +%110 = OpLoad %3 %81 +%111 = OpBitcast %24 %110 +%112 = OpFAdd %24 %111 %25 +%113 = OpBitcast %3 %112 +%114 = OpLoad %3 %80 +%115 = OpLoad %3 %81 +%117 = OpAccessChain %97 %79 %114 +%118 = OpAtomicCompareExchange %3 %117 %50 %51 %51 %113 %115 +%119 = OpIEqual %8 %118 %115 +%116 = OpCompositeConstruct %10 %118 %119 +%120 = OpCompositeExtract %3 %116 0 +OpStore %81 %120 +%121 = OpCompositeExtract %8 %116 1 +OpStore %83 %121 +OpBranch %109 +%109 = OpLabel +OpBranch %103 +%103 = OpLabel +OpBranch %100 +%101 = OpLabel +OpBranch %95 +%95 = OpLabel +OpBranch %89 +%89 = OpLabel +%122 = OpLoad %3 %80 +%123 = OpIAdd %3 %122 %26 +OpStore %80 %123 +OpBranch %86 %87 = OpLabel -%120 = OpLoad %3 %79 -%121 = OpIAdd %3 %120 %26 -OpStore %79 %121 -OpBranch %84 -%85 = OpLabel OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/tests/out/wgsl/atomicCompareExchange.wgsl index f68017028..5f98c6196 100644 --- a/tests/out/wgsl/atomicCompareExchange.wgsl +++ b/tests/out/wgsl/atomicCompareExchange.wgsl @@ -9,7 +9,7 @@ var arr_u32_: array, 128>; fn test_atomic_compare_exchange_i32_() { var i: u32 = 0u; var old: i32; - var exchanged: bool = false; + var exchanged: bool; loop { let _e2 = i; @@ -51,7 +51,7 @@ fn test_atomic_compare_exchange_i32_() { fn test_atomic_compare_exchange_u32_() { var i_1: u32 = 0u; var old_1: u32; - var exchanged_1: bool = false; + var exchanged_1: bool; loop { let _e2 = i_1; From 9eb3a1dc8a522e627b266f9157442f0fe8b65ec9 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 9 Oct 2023 10:51:11 -0700 Subject: [PATCH 2164/2212] [wgsl-out] Generate correct code for bit complement on integers. Remove incorrect special case for `UnaryOperator::Not` on vectors. --- src/back/wgsl/writer.rs | 11 ++++------- tests/out/wgsl/operators.wgsl | 4 ++-- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 0655fcde8..36380952a 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1600,13 +1600,10 @@ impl Writer { let unary = match op { crate::UnaryOperator::Negate => "-", crate::UnaryOperator::Not => { - match *func_ctx.resolve_type(expr, &module.types) { - TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - .. - } - | TypeInner::Vector { .. } => "!", - _ => "~", + match func_ctx.resolve_type(expr, &module.types).scalar_kind() { + Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => "~", + Some(crate::ScalarKind::Bool) => "!", + _ => return Err(Error::Custom("validation failure".to_string())), } } }; diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl index 5038bdc85..95621e32e 100644 --- a/tests/out/wgsl/operators.wgsl +++ b/tests/out/wgsl/operators.wgsl @@ -128,8 +128,8 @@ fn arithmetic() { fn bit() { let flip0_ = ~(1); let flip1_ = ~(1u); - let flip2_ = !(vec2(1)); - let flip3_ = !(vec3(1u)); + let flip2_ = ~(vec2(1)); + let flip3_ = ~(vec3(1u)); let or0_ = (2 | 1); let or1_ = (2u | 1u); let or2_ = (vec2(2) | vec2(1)); From 841d360f0638ff7082de1e07de205d6a0121050d Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 16 Oct 2023 15:27:37 +0200 Subject: [PATCH 2165/2212] [valid] avoid OOM with large sparse resource bindings --- src/valid/interface.rs | 10 ++-------- src/valid/mod.rs | 6 +++--- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/valid/interface.rs b/src/valid/interface.rs index 7c6c5244e..6c41ece81 100644 --- a/src/valid/interface.rs +++ b/src/valid/interface.rs @@ -707,10 +707,6 @@ impl super::Validator { return Err(EntryPointError::MissingVertexOutputPosition.with_span()); } - for bg in self.bind_group_masks.iter_mut() { - bg.clear(); - } - #[cfg(feature = "validate")] { let used_push_constants = module @@ -728,6 +724,7 @@ impl super::Validator { } } + self.ep_resource_bindings.clear(); #[cfg(feature = "validate")] for (var_handle, var) in module.global_variables.iter() { let usage = info[var_handle]; @@ -768,10 +765,7 @@ impl super::Validator { } if let Some(ref bind) = var.binding { - while self.bind_group_masks.len() <= bind.group as usize { - self.bind_group_masks.push(BitSet::new()); - } - if !self.bind_group_masks[bind.group as usize].insert(bind.binding as usize) { + if !self.ep_resource_bindings.insert(bind.clone()) { if self.flags.contains(super::ValidationFlags::BINDINGS) { return Err(EntryPointError::BindingCollision(var_handle) .with_span_handle(var_handle, &module.global_variables)); diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 8c065bb15..454d9739c 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -174,7 +174,7 @@ pub struct Validator { types: Vec, layouter: Layouter, location_mask: BitSet, - bind_group_masks: Vec, + ep_resource_bindings: FastHashSet, #[allow(dead_code)] switch_values: FastHashSet, valid_expression_list: Vec>, @@ -290,7 +290,7 @@ impl Validator { types: Vec::new(), layouter: Layouter::default(), location_mask: BitSet::new(), - bind_group_masks: Vec::new(), + ep_resource_bindings: FastHashSet::default(), switch_values: FastHashSet::default(), valid_expression_list: Vec::new(), valid_expression_set: BitSet::new(), @@ -302,7 +302,7 @@ impl Validator { self.types.clear(); self.layouter.clear(); self.location_mask.clear(); - self.bind_group_masks.clear(); + self.ep_resource_bindings.clear(); self.switch_values.clear(); self.valid_expression_list.clear(); self.valid_expression_set.clear(); From 04562dea2681c8fea9f2f3472e0700599ed57d44 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 12 Oct 2023 13:58:56 +0200 Subject: [PATCH 2166/2212] Split `UnaryOperator::Not` into `UnaryOperator::LogicalNot` & `UnaryOperator::BitwiseNot` since it should not be valid to use the logical and bitwise not operators interchangeably also, don't allow `UnaryOperator::Negate` to operate on booleans (no frontend/backend supports this) --- src/back/glsl/mod.rs | 40 +++++++--------------------- src/back/hlsl/writer.rs | 18 +++---------- src/back/msl/writer.rs | 10 +++---- src/back/spv/block.rs | 12 +++------ src/back/wgsl/writer.rs | 9 ++----- src/front/glsl/builtins.rs | 2 +- src/front/glsl/parser/expressions.rs | 8 ++++-- src/front/glsl/parser/functions.rs | 6 ++--- src/front/spv/mod.rs | 6 ++--- src/front/wgsl/parse/mod.rs | 14 ++++++++-- src/lib.rs | 3 ++- src/proc/constant_evaluator.rs | 11 +++++--- src/valid/expression.rs | 7 +++-- 13 files changed, 58 insertions(+), 88 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 77e206d3c..a4d0839d4 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2762,38 +2762,18 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, ")")?; } - // `Unary` is pretty straightforward - // "-" - for `Negate` - // "~" - for `Not` if it's an integer - // "!" - for `Not` if it's a boolean - // - // We also wrap the everything in parentheses to avoid precedence issues Expression::Unary { op, expr } => { - use crate::{ScalarKind as Sk, UnaryOperator as Uo}; - - let ty = ctx.info[expr].ty.inner_with(&self.module.types); - - match *ty { - TypeInner::Vector { kind: Sk::Bool, .. } => { - write!(self.out, "not(")?; + let operator_or_fn = match op { + crate::UnaryOperator::Negate => "-", + crate::UnaryOperator::LogicalNot => { + match *ctx.info[expr].ty.inner_with(&self.module.types) { + TypeInner::Vector { .. } => "not", + _ => "!", + } } - _ => { - let operator = match op { - Uo::Negate => "-", - Uo::Not => match ty.scalar_kind() { - Some(Sk::Sint) | Some(Sk::Uint) => "~", - Some(Sk::Bool) => "!", - ref other => { - return Err(Error::Custom(format!( - "Cannot apply not to type {other:?}" - ))) - } - }, - }; - - write!(self.out, "{operator}(")?; - } - } + crate::UnaryOperator::BitwiseNot => "~", + }; + write!(self.out, "{operator_or_fn}(")?; self.write_expr(expr, ctx)?; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 590850fc4..b8581e5e7 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -2566,23 +2566,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Expression::Unary { op, expr } => { - use crate::{ScalarKind as Sk, UnaryOperator as Uo}; // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators let op_str = match op { - Uo::Negate => "-", - Uo::Not => match func_ctx.info[expr] - .ty - .inner_with(&module.types) - .scalar_kind() - { - Some(Sk::Sint) | Some(Sk::Uint) => "~", - Some(Sk::Bool) => "!", - ref other => { - return Err(Error::Custom(format!( - "Cannot apply not to type {other:?}" - ))) - } - }, + crate::UnaryOperator::Negate => "-", + crate::UnaryOperator::LogicalNot => "!", + crate::UnaryOperator::BitwiseNot => "~", }; write!(self.out, "{op_str}(")?; self.write_expr(module, expr, func_ctx)?; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index d0f541313..c0c19aa49 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1551,14 +1551,10 @@ impl Writer { } }, crate::Expression::Unary { op, expr } => { - use crate::{ScalarKind as Sk, UnaryOperator as Uo}; let op_str = match op { - Uo::Negate => "-", - Uo::Not => match context.resolve_type(expr).scalar_kind() { - Some(Sk::Sint) | Some(Sk::Uint) => "~", - Some(Sk::Bool) => "!", - _ => return Err(Error::Validation), - }, + crate::UnaryOperator::Negate => "-", + crate::UnaryOperator::LogicalNot => "!", + crate::UnaryOperator::BitwiseNot => "~", }; write!(self.out, "{op_str}(")?; self.put_expression(expr, context, false)?; diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 4dba7ea0c..0e3a7c16e 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -463,16 +463,10 @@ impl<'w> BlockContext<'w> { crate::UnaryOperator::Negate => match expr_ty_inner.scalar_kind() { Some(crate::ScalarKind::Float) => spirv::Op::FNegate, Some(crate::ScalarKind::Sint) => spirv::Op::SNegate, - Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNot, - Some(crate::ScalarKind::Uint) | None => { - log::error!("Unable to negate {:?}", expr_ty_inner); - return Err(Error::FeatureNotImplemented("negation")); - } - }, - crate::UnaryOperator::Not => match expr_ty_inner.scalar_kind() { - Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNot, - _ => spirv::Op::Not, + _ => return Err(Error::Validation("Unexpected kind for negation")), }, + crate::UnaryOperator::LogicalNot => spirv::Op::LogicalNot, + crate::UnaryOperator::BitwiseNot => spirv::Op::Not, }; block diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs index 36380952a..075d85558 100644 --- a/src/back/wgsl/writer.rs +++ b/src/back/wgsl/writer.rs @@ -1599,13 +1599,8 @@ impl Writer { Expression::Unary { op, expr } => { let unary = match op { crate::UnaryOperator::Negate => "-", - crate::UnaryOperator::Not => { - match func_ctx.resolve_type(expr, &module.types).scalar_kind() { - Some(crate::ScalarKind::Sint) | Some(crate::ScalarKind::Uint) => "~", - Some(crate::ScalarKind::Bool) => "!", - _ => return Err(Error::Custom("validation failure".to_string())), - } - } + crate::UnaryOperator::LogicalNot => "!", + crate::UnaryOperator::BitwiseNot => "~", }; write!(self.out, "{unary}(")?; diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 8d57b66da..bf7559ee2 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -844,7 +844,7 @@ fn inject_standard_builtins( let fun = match name { "all" => MacroCall::Relational(RelationalFunction::All), "any" => MacroCall::Relational(RelationalFunction::Any), - "not" => MacroCall::Unary(UnaryOperator::Not), + "not" => MacroCall::Unary(UnaryOperator::LogicalNot), _ => unreachable!(), }; diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index 32e0959c2..1b8febce9 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -296,8 +296,12 @@ impl<'source> ParsingContext<'source> { op: UnaryOperator::Negate, expr, }, - TokenValue::Bang | TokenValue::Tilde => HirExprKind::Unary { - op: UnaryOperator::Not, + TokenValue::Bang => HirExprKind::Unary { + op: UnaryOperator::LogicalNot, + expr, + }, + TokenValue::Tilde => HirExprKind::Unary { + op: UnaryOperator::BitwiseNot, expr, }, _ => return Ok(expr), diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index eebaec269..b63b13a4a 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -338,7 +338,7 @@ impl<'source> ParsingContext<'source> { let (expr, expr_meta) = ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs)?; let condition = ctx.add_expression( Expression::Unary { - op: UnaryOperator::Not, + op: UnaryOperator::LogicalNot, expr, }, expr_meta, @@ -393,7 +393,7 @@ impl<'source> ParsingContext<'source> { let (expr, expr_meta) = ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs)?; let condition = ctx.add_expression( Expression::Unary { - op: UnaryOperator::Not, + op: UnaryOperator::LogicalNot, expr, }, expr_meta, @@ -481,7 +481,7 @@ impl<'source> ParsingContext<'source> { let condition = ctx.add_expression( Expression::Unary { - op: UnaryOperator::Not, + op: UnaryOperator::LogicalNot, expr, }, expr_meta, diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 4bb696a63..7116925d0 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2559,7 +2559,7 @@ impl> Frontend { &mut block, block_id, body_idx, - crate::UnaryOperator::Not, + crate::UnaryOperator::BitwiseNot, )?; } Op::ShiftRightLogical => { @@ -3033,7 +3033,7 @@ impl> Frontend { // Relational and Logical Instructions Op::LogicalNot => { inst.expect(4)?; - parse_expr_op!(crate::UnaryOperator::Not, UNARY)?; + parse_expr_op!(crate::UnaryOperator::LogicalNot, UNARY)?; } Op::LogicalOr => { inst.expect(5)?; @@ -3249,7 +3249,7 @@ impl> Frontend { } else { ctx.expressions.append( crate::Expression::Unary { - op: crate::UnaryOperator::Not, + op: crate::UnaryOperator::LogicalNot, expr: condition, }, span, diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 74738ab23..23398e611 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -741,11 +741,21 @@ impl Parser { let span = self.peek_rule_span(lexer); ctx.expressions.append(expr, span) } - Token::Operation('!' | '~') => { + Token::Operation('!') => { let _ = lexer.next(); let expr = self.unary_expression(lexer, ctx.reborrow())?; let expr = ast::Expression::Unary { - op: crate::UnaryOperator::Not, + op: crate::UnaryOperator::LogicalNot, + expr, + }; + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) + } + Token::Operation('~') => { + let _ = lexer.next(); + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Unary { + op: crate::UnaryOperator::BitwiseNot, expr, }; let span = self.peek_rule_span(lexer); diff --git a/src/lib.rs b/src/lib.rs index 9d7019042..9b563b94a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -995,7 +995,8 @@ pub struct LocalVariable { #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum UnaryOperator { Negate, - Not, + LogicalNot, + BitwiseNot, } /// Operation that can be applied on two values. diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index 70a46114a..d2604ae1c 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -1019,10 +1019,13 @@ impl<'a> ConstantEvaluator<'a> { Literal::F32(v) => Literal::F32(-v), _ => return Err(ConstantEvaluatorError::InvalidUnaryOpArg), }, - UnaryOperator::Not => match value { + UnaryOperator::LogicalNot => match value { + Literal::Bool(v) => Literal::Bool(!v), + _ => return Err(ConstantEvaluatorError::InvalidUnaryOpArg), + }, + UnaryOperator::BitwiseNot => match value { Literal::I32(v) => Literal::I32(!v), Literal::U32(v) => Literal::U32(!v), - Literal::Bool(v) => Literal::Bool(!v), _ => return Err(ConstantEvaluatorError::InvalidUnaryOpArg), }, }), @@ -1344,12 +1347,12 @@ mod tests { }; let expr3 = Expression::Unary { - op: UnaryOperator::Not, + op: UnaryOperator::BitwiseNot, expr, }; let expr4 = Expression::Unary { - op: UnaryOperator::Not, + op: UnaryOperator::BitwiseNot, expr: expr1, }; diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 95225a392..cc77de38b 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -649,10 +649,9 @@ impl super::Validator { use crate::UnaryOperator as Uo; let inner = &resolver[expr]; match (op, inner.scalar_kind()) { - (_, Some(Sk::Sint | Sk::Bool)) - //TODO: restrict Negate for bools? - | (Uo::Negate, Some(Sk::Float)) - | (Uo::Not, Some(Sk::Uint)) => {} + (Uo::Negate, Some(Sk::Float | Sk::Sint)) + | (Uo::LogicalNot, Some(Sk::Bool)) + | (Uo::BitwiseNot, Some(Sk::Sint | Sk::Uint)) => {} other => { log::error!("Op {:?} kind {:?}", op, other); return Err(ExpressionError::InvalidUnaryOperandType(op, expr)); From d71f2541a3f2e1d327fbb1a1e3c3e0d54c5dac8e Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Tue, 3 Oct 2023 15:12:44 +0200 Subject: [PATCH 2167/2212] remove `IsFinite` & `IsNormal` completely --- src/back/glsl/mod.rs | 4 ---- src/back/hlsl/writer.rs | 2 -- src/back/msl/writer.rs | 2 -- src/back/spv/block.rs | 4 ---- src/front/spv/convert.rs | 2 -- src/lib.rs | 2 -- src/proc/typifier.rs | 35 +++++++++++++++++------------------ src/valid/expression.rs | 2 +- 8 files changed, 18 insertions(+), 35 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index a4d0839d4..5f24fd651 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -2981,12 +2981,8 @@ impl<'a, W: Write> Writer<'a, W> { use crate::RelationalFunction as Rf; let fun_name = match fun { - // There's no specific function for this but we can invert the result of `isinf` - Rf::IsFinite => "!isinf", Rf::IsInf => "isinf", Rf::IsNan => "isnan", - // There's also no function for this but we can invert `isnan` - Rf::IsNormal => "!isnan", Rf::All => "all", Rf::Any => "any", }; diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index b8581e5e7..5286eb6dd 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -3151,8 +3151,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Rf::Any => "any", Rf::IsNan => "isnan", Rf::IsInf => "isinf", - Rf::IsFinite => "isfinite", - Rf::IsNormal => "isnormal", }; write!(self.out, "{fun_str}(")?; self.write_expr(module, argument, func_ctx)?; diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c0c19aa49..54941836e 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1671,8 +1671,6 @@ impl Writer { crate::RelationalFunction::All => "all", crate::RelationalFunction::IsNan => "isnan", crate::RelationalFunction::IsInf => "isinf", - crate::RelationalFunction::IsFinite => "isfinite", - crate::RelationalFunction::IsNormal => "isnormal", }; write!(self.out, "{NAMESPACE}::{op}")?; self.put_call_parameters(iter::once(argument), context)?; diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs index 0e3a7c16e..0471d957f 100644 --- a/src/back/spv/block.rs +++ b/src/back/spv/block.rs @@ -1406,10 +1406,6 @@ impl<'w> BlockContext<'w> { Rf::Any => spirv::Op::Any, Rf::IsNan => spirv::Op::IsNan, Rf::IsInf => spirv::Op::IsInf, - //TODO: these require Kernel capability - Rf::IsFinite | Rf::IsNormal => { - return Err(Error::FeatureNotImplemented("is finite/normal")) - } }; let id = self.gen_id(); block diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index f547e806a..efd95898b 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -52,8 +52,6 @@ pub(super) const fn map_relational_fun( Op::Any => Ok(Rf::Any), Op::IsNan => Ok(Rf::IsNan), Op::IsInf => Ok(Rf::IsInf), - Op::IsFinite => Ok(Rf::IsFinite), - Op::IsNormal => Ok(Rf::IsNormal), _ => Err(Error::UnknownRelationalFunction(word)), } } diff --git a/src/lib.rs b/src/lib.rs index 9b563b94a..300c6e482 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1117,8 +1117,6 @@ pub enum RelationalFunction { Any, IsNan, IsInf, - IsFinite, - IsNormal, } /// Built-in shader function for math. diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index a6130ad79..ad9eec94d 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -648,25 +648,24 @@ impl<'a> ResolveContext<'a> { width: crate::BOOL_WIDTH, }) } - crate::RelationalFunction::IsNan - | crate::RelationalFunction::IsInf - | crate::RelationalFunction::IsFinite - | crate::RelationalFunction::IsNormal => match *past(argument)?.inner_with(types) { - Ti::Scalar { .. } => TypeResolution::Value(Ti::Scalar { - kind: crate::ScalarKind::Bool, - width: crate::BOOL_WIDTH, - }), - Ti::Vector { size, .. } => TypeResolution::Value(Ti::Vector { - kind: crate::ScalarKind::Bool, - width: crate::BOOL_WIDTH, - size, - }), - ref other => { - return Err(ResolveError::IncompatibleOperands(format!( - "{fun:?}({other:?})" - ))) + crate::RelationalFunction::IsNan | crate::RelationalFunction::IsInf => { + match *past(argument)?.inner_with(types) { + Ti::Scalar { .. } => TypeResolution::Value(Ti::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }), + Ti::Vector { size, .. } => TypeResolution::Value(Ti::Vector { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + size, + }), + ref other => { + return Err(ResolveError::IncompatibleOperands(format!( + "{fun:?}({other:?})" + ))) + } } - }, + } }, crate::Expression::Math { fun, diff --git a/src/valid/expression.rs b/src/valid/expression.rs index cc77de38b..ef14de713 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -897,7 +897,7 @@ impl super::Validator { return Err(ExpressionError::InvalidBooleanVector(argument)); } }, - Rf::IsNan | Rf::IsInf | Rf::IsFinite | Rf::IsNormal => match *argument_inner { + Rf::IsNan | Rf::IsInf => match *argument_inner { Ti::Scalar { kind: Sk::Float, .. } From 68ce1ebfa2556c9fdb56415956b02bf9da2128c7 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 16 Oct 2023 16:50:46 -0700 Subject: [PATCH 2168/2212] [glsl-in, glsl-out] Fix warnings about redundant doc link targets. --- src/back/glsl/features.rs | 5 ++--- src/back/glsl/mod.rs | 6 +++--- src/front/glsl/ast.rs | 2 +- src/front/glsl/context.rs | 21 +++++++++++---------- src/front/glsl/mod.rs | 26 +++++++++++++------------- src/front/glsl/offset.rs | 14 +++++++------- 6 files changed, 37 insertions(+), 37 deletions(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index 4aac9b2e6..b1fff4d4b 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -64,8 +64,7 @@ impl FeaturesManager { } /// Checks that all required [`Features`] are available for the specified - /// [`Version`](super::Version) otherwise returns an - /// [`Error::MissingFeatures`](super::Error::MissingFeatures) + /// [`Version`] otherwise returns an [`Error::MissingFeatures`]. pub fn check_availability(&self, version: Version) -> BackendResult { // Will store all the features that are unavailable let mut missing = Features::empty(); @@ -245,7 +244,7 @@ impl<'a, W> Writer<'a, W> { /// /// # Errors /// If the version doesn't support any of the needed [`Features`] a - /// [`Error::MissingFeatures`](super::Error::MissingFeatures) will be returned + /// [`Error::MissingFeatures`] will be returned pub(super) fn collect_required_features(&mut self) -> BackendResult { let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 5f24fd651..37d3303c7 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -327,7 +327,7 @@ impl IdGenerator { /// Helper wrapper used to get a name for a varying /// /// Varying have different naming schemes depending on their binding: -/// - Varyings with builtin bindings get the from [`glsl_built_in`](glsl_built_in). +/// - Varyings with builtin bindings get the from [`glsl_built_in`]. /// - Varyings with location bindings are named `_S_location_X` where `S` is a /// prefix identifying which pipeline stage the varying connects, and `X` is /// the location. @@ -4050,7 +4050,7 @@ impl<'a, W: Write> Writer<'a, W> { } } -/// Structure returned by [`glsl_scalar`](glsl_scalar) +/// Structure returned by [`glsl_scalar`] /// /// It contains both a prefix used in other types and the full type name struct ScalarString<'a> { @@ -4062,7 +4062,7 @@ struct ScalarString<'a> { /// Helper function that returns scalar related strings /// -/// Check [`ScalarString`](ScalarString) for the information provided +/// Check [`ScalarString`] for the information provided /// /// # Errors /// If a [`Float`](crate::ScalarKind::Float) with an width that isn't 4 or 8 diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs index 138a22767..0548fc25e 100644 --- a/src/front/glsl/ast.rs +++ b/src/front/glsl/ast.rs @@ -377,7 +377,7 @@ impl ParameterQualifier { } } - /// Converts from a parameter qualifier into a [`ExprPos`](ExprPos) + /// Converts from a parameter qualifier into a [`ExprPos`] pub const fn as_pos(&self) -> ExprPos { match *self { ParameterQualifier::Out | ParameterQualifier::InOut => ExprPos::Lhs, diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 0eceb24e4..a54e718aa 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -396,20 +396,21 @@ impl<'a> Context<'a> { Ok(()) } - /// Returns a [`StmtContext`](StmtContext) to be used in parsing and lowering + /// Returns a [`StmtContext`] to be used in parsing and lowering /// /// # Panics - /// - If more than one [`StmtContext`](StmtContext) are active at the same - /// time or if the previous call didn't use it in lowering. + /// + /// - If more than one [`StmtContext`] are active at the same time or if the + /// previous call didn't use it in lowering. #[must_use] pub fn stmt_ctx(&mut self) -> StmtContext { self.stmt_ctx.take().unwrap() } - /// Lowers a [`HirExpr`](HirExpr) which might produce a [`Expression`](Expression). + /// Lowers a [`HirExpr`] which might produce a [`Expression`]. /// - /// consumes a [`StmtContext`](StmtContext) returning it to the context so - /// that it can be used again later. + /// consumes a [`StmtContext`] returning it to the context so that it can be + /// used again later. pub fn lower( &mut self, mut stmt: StmtContext, @@ -426,10 +427,10 @@ impl<'a> Context<'a> { } /// Similar to [`lower`](Self::lower) but returns an error if the expression - /// returns void (ie. doesn't produce a [`Expression`](Expression)). + /// returns void (ie. doesn't produce a [`Expression`]). /// - /// consumes a [`StmtContext`](StmtContext) returning it to the context so - /// that it can be used again later. + /// consumes a [`StmtContext`] returning it to the context so that it can be + /// used again later. pub fn lower_expect( &mut self, mut stmt: StmtContext, @@ -1518,7 +1519,7 @@ impl Index> for Context<'_> { #[derive(Debug)] pub struct StmtContext { /// A arena of high level expressions which can be lowered through a - /// [`Context`](Context) to naga's [`Expression`](crate::Expression)s + /// [`Context`] to Naga's [`Expression`]s pub hir_exprs: Arena, } diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 4ce0dc478..49624a943 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -38,8 +38,9 @@ type Result = std::result::Result; /// Per-shader options passed to [`parse`](Frontend::parse). /// -/// The [`From`](From) trait is implemented for [`ShaderStage`](ShaderStage) to -/// provide a quick way to create a Options instance. +/// The [`From`] trait is implemented for [`ShaderStage`] to provide a quick way +/// to create an `Options` instance. +/// /// ```rust /// # use naga::ShaderStage; /// # use naga::front::glsl::Options; @@ -69,7 +70,7 @@ impl From for Options { /// Additional information about the GLSL shader. /// /// Stores additional information about the GLSL shader which might not be -/// stored in the shader [`Module`](Module). +/// stored in the shader [`Module`]. #[derive(Debug)] pub struct ShaderMetadata { /// The GLSL version specified in the shader through the use of the @@ -79,7 +80,7 @@ pub struct ShaderMetadata { /// `#version` preprocessor directive. pub profile: Profile, /// The shader stage in the pipeline, passed to the [`parse`](Frontend::parse) - /// method via the [`Options`](Options) struct. + /// method via the [`Options`] struct. pub stage: ShaderStage, /// The workgroup size for compute shaders, defaults to `[1; 3]` for @@ -125,17 +126,17 @@ impl Default for ShaderMetadata { /// The `Frontend` is the central structure of the GLSL frontend. /// -/// To instantiate a new `Frontend` the [`Default`](Default) trait is used, so a +/// To instantiate a new `Frontend` the [`Default`] trait is used, so a /// call to the associated function [`Frontend::default`](Frontend::default) will /// return a new `Frontend` instance. /// /// To parse a shader simply call the [`parse`](Frontend::parse) method with a -/// [`Options`](Options) struct and a [`&str`](str) holding the glsl code. +/// [`Options`] struct and a [`&str`](str) holding the glsl code. /// /// The `Frontend` also provides the [`metadata`](Frontend::metadata) to get some /// further information about the previously parsed shader, like version and /// extensions used (see the documentation for -/// [`ShaderMetadata`](ShaderMetadata) to see all the returned information) +/// [`ShaderMetadata`] to see all the returned information) /// /// # Example usage /// ```rust @@ -187,8 +188,8 @@ impl Frontend { self.layouter.clear(); } - /// Parses a shader either outputting a shader [`Module`](Module) or a list - /// of [`Error`](Error)s. + /// Parses a shader either outputting a shader [`Module`] or a list of + /// [`Error`]s. /// /// Multiple calls using the same `Frontend` and different shaders are supported. pub fn parse( @@ -216,10 +217,9 @@ impl Frontend { } } - /// Returns additional information about the parsed shader which might not be - /// stored in the [`Module`](Module), see the documentation for - /// [`ShaderMetadata`](ShaderMetadata) for more information about the - /// returned data. + /// Returns additional information about the parsed shader which might not + /// be stored in the [`Module`], see the documentation for + /// [`ShaderMetadata`] for more information about the returned data. /// /// # Notes /// diff --git a/src/front/glsl/offset.rs b/src/front/glsl/offset.rs index 21481372b..2d4177852 100644 --- a/src/front/glsl/offset.rs +++ b/src/front/glsl/offset.rs @@ -20,12 +20,12 @@ use crate::{proc::Alignment, Handle, Type, TypeInner, UniqueArena}; /// Struct with information needed for defining a struct member. /// -/// Returned by [`calculate_offset`](calculate_offset) +/// Returned by [`calculate_offset`]. #[derive(Debug)] pub struct TypeAlignSpan { /// The handle to the type, this might be the same handle passed to - /// [`calculate_offset`](calculate_offset) or a new such a new array type - /// with a different stride set. + /// [`calculate_offset`] or a new such a new array type with a different + /// stride set. pub ty: Handle, /// The alignment required by the type. pub align: Alignment, @@ -33,11 +33,11 @@ pub struct TypeAlignSpan { pub span: u32, } -/// Returns the type, alignment and span of a struct member according to a [`StructLayout`](StructLayout). +/// Returns the type, alignment and span of a struct member according to a [`StructLayout`]. /// -/// The functions returns a [`TypeAlignSpan`](TypeAlignSpan) which has a `ty` member -/// this should be used as the struct member type because for example arrays may have to -/// change the stride and as such need to have a different type. +/// The functions returns a [`TypeAlignSpan`] which has a `ty` member this +/// should be used as the struct member type because for example arrays may have +/// to change the stride and as such need to have a different type. pub fn calculate_offset( mut ty: Handle, meta: Span, From 0cfd2213ccd163322474cfe4548bb7d03f82798b Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 18 Sep 2023 20:11:07 +0200 Subject: [PATCH 2169/2212] [msl-out] remove min version check on storage address space --- src/back/msl/mod.rs | 4 +--- src/back/msl/writer.rs | 3 --- tests/in/access.param.ron | 2 +- tests/in/bitcast.params.ron | 2 +- tests/in/boids.param.ron | 2 +- tests/in/bounds-check-image-restrict.param.ron | 8 ++++++++ tests/in/bounds-check-image-rzsw.param.ron | 8 ++++++++ tests/in/dualsource.param.ron | 18 ++++++++---------- tests/in/padding.param.ron | 2 +- tests/in/resource-binding-map.param.ron | 2 +- tests/in/workgroup-var-init.param.ron | 2 +- tests/out/msl/access.msl | 2 +- tests/out/msl/array-in-ctor.msl | 2 +- .../out/msl/array-in-function-return-type.msl | 2 +- tests/out/msl/atomicOps.msl | 2 +- tests/out/msl/bitcast.msl | 2 +- tests/out/msl/boids.msl | 2 +- tests/out/msl/bounds-check-image-restrict.msl | 2 +- tests/out/msl/bounds-check-image-rzsw.msl | 2 +- tests/out/msl/bounds-check-restrict.msl | 2 +- tests/out/msl/bounds-check-zero-atomic.msl | 2 +- tests/out/msl/bounds-check-zero.msl | 2 +- tests/out/msl/break-if.msl | 2 +- tests/out/msl/collatz.msl | 2 +- tests/out/msl/const-exprs.msl | 2 +- tests/out/msl/constructors.msl | 2 +- tests/out/msl/control-flow.msl | 2 +- tests/out/msl/do-while.msl | 2 +- tests/out/msl/dualsource.msl | 2 +- tests/out/msl/empty-global-name.msl | 2 +- tests/out/msl/empty.msl | 2 +- tests/out/msl/fragment-output.msl | 2 +- tests/out/msl/functions.msl | 2 +- tests/out/msl/globals.msl | 2 +- tests/out/msl/image.msl | 2 +- tests/out/msl/interpolate.msl | 2 +- tests/out/msl/math-functions.msl | 2 +- tests/out/msl/msl-varyings.msl | 2 +- tests/out/msl/operators.msl | 2 +- tests/out/msl/padding.msl | 2 +- tests/out/msl/policy-mix.msl | 2 +- tests/out/msl/quad-vert.msl | 2 +- tests/out/msl/quad.msl | 2 +- tests/out/msl/resource-binding-map.msl | 2 +- tests/out/msl/shadow.msl | 2 +- tests/out/msl/standard.msl | 2 +- tests/out/msl/texture-arg.msl | 2 +- tests/out/msl/workgroup-uniform-load.msl | 2 +- tests/out/msl/workgroup-var-init.msl | 2 +- 49 files changed, 69 insertions(+), 60 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 819d48a8f..a5c713965 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -127,8 +127,6 @@ pub enum Error { UnsupportedBuiltIn(crate::BuiltIn), #[error("capability {0:?} is not supported")] CapabilityNotSupported(crate::valid::Capabilities), - #[error("address space {0:?} is not supported for target MSL version")] - UnsupportedAddressSpace(crate::AddressSpace), #[error("attribute '{0}' is not supported for target MSL version")] UnsupportedAttribute(String), } @@ -197,7 +195,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { Options { - lang_version: (2, 0), + lang_version: (1, 0), per_entry_point_map: EntryPointResourceMap::default(), inline_samplers: Vec::new(), spirv_cross_compatibility: false, diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 54941836e..bdb0b0ac3 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3940,9 +3940,6 @@ impl Writer { let resolved = match var.space { crate::AddressSpace::PushConstant => options.resolve_push_constants(ep).ok(), crate::AddressSpace::WorkGroup => None, - crate::AddressSpace::Storage { .. } if options.lang_version < (2, 0) => { - return Err(Error::UnsupportedAddressSpace(var.space)) - } _ => options .resolve_resource_binding(ep, var.binding.as_ref().unwrap()) .ok(), diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron index 5cd8e79a4..e67f90cf2 100644 --- a/tests/in/access.param.ron +++ b/tests/in/access.param.ron @@ -5,7 +5,7 @@ adjust_coordinate_space: false, ), msl: ( - lang_version: (2, 0), + lang_version: (1, 2), per_entry_point_map: { "foo_vert": ( resources: { diff --git a/tests/in/bitcast.params.ron b/tests/in/bitcast.params.ron index b40cf9fa0..febd505f7 100644 --- a/tests/in/bitcast.params.ron +++ b/tests/in/bitcast.params.ron @@ -1,6 +1,6 @@ ( msl: ( - lang_version: (1, 2), + lang_version: (1, 0), per_entry_point_map: { "main": ( resources: { diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron index 976b457ed..25f81b8af 100644 --- a/tests/in/boids.param.ron +++ b/tests/in/boids.param.ron @@ -5,7 +5,7 @@ adjust_coordinate_space: false, ), msl: ( - lang_version: (2, 0), + lang_version: (1, 0), per_entry_point_map: { "main": ( resources: { diff --git a/tests/in/bounds-check-image-restrict.param.ron b/tests/in/bounds-check-image-restrict.param.ron index 448db8a5d..d7ff0f006 100644 --- a/tests/in/bounds-check-image-restrict.param.ron +++ b/tests/in/bounds-check-image-restrict.param.ron @@ -13,4 +13,12 @@ binding_map: { }, zero_initialize_workgroup_memory: true, ), + msl: ( + lang_version: (1, 2), + per_entry_point_map: {}, + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: true, + zero_initialize_workgroup_memory: true, + ), ) diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/tests/in/bounds-check-image-rzsw.param.ron index 0a82f9584..b256790e1 100644 --- a/tests/in/bounds-check-image-rzsw.param.ron +++ b/tests/in/bounds-check-image-rzsw.param.ron @@ -13,4 +13,12 @@ binding_map: { }, zero_initialize_workgroup_memory: true, ), + msl: ( + lang_version: (1, 2), + per_entry_point_map: {}, + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: true, + zero_initialize_workgroup_memory: true, + ), ) diff --git a/tests/in/dualsource.param.ron b/tests/in/dualsource.param.ron index 1cf512c6c..9ab5ee414 100644 --- a/tests/in/dualsource.param.ron +++ b/tests/in/dualsource.param.ron @@ -1,13 +1,11 @@ ( god_mode: true, - vertex:[ - ], - fragment:[ - ( - entry_point:"main", - target_profile:"ps_5_1", - ), - ], - compute:[ - ], + msl: ( + lang_version: (1, 2), + per_entry_point_map: {}, + inline_samplers: [], + spirv_cross_compatibility: false, + fake_missing_bindings: false, + zero_initialize_workgroup_memory: true, + ), ) diff --git a/tests/in/padding.param.ron b/tests/in/padding.param.ron index 14859bba3..1a735a201 100644 --- a/tests/in/padding.param.ron +++ b/tests/in/padding.param.ron @@ -5,7 +5,7 @@ adjust_coordinate_space: false, ), msl: ( - lang_version: (2, 0), + lang_version: (1, 0), per_entry_point_map: { "vertex": ( resources: { diff --git a/tests/in/resource-binding-map.param.ron b/tests/in/resource-binding-map.param.ron index 15a14b197..25e7b054b 100644 --- a/tests/in/resource-binding-map.param.ron +++ b/tests/in/resource-binding-map.param.ron @@ -1,7 +1,7 @@ ( god_mode: true, msl: ( - lang_version: (2, 0), + lang_version: (1, 0), per_entry_point_map: { "entry_point_one": ( resources: { diff --git a/tests/in/workgroup-var-init.param.ron b/tests/in/workgroup-var-init.param.ron index be5302284..a00ecf6bf 100644 --- a/tests/in/workgroup-var-init.param.ron +++ b/tests/in/workgroup-var-init.param.ron @@ -5,7 +5,7 @@ adjust_coordinate_space: false, ), msl: ( - lang_version: (2, 0), + lang_version: (1, 0), per_entry_point_map: { "main": ( resources: { diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index 7c901c35a..d0f48ba4f 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.2 #include #include diff --git a/tests/out/msl/array-in-ctor.msl b/tests/out/msl/array-in-ctor.msl index 9428cb1e7..a3bbb2057 100644 --- a/tests/out/msl/array-in-ctor.msl +++ b/tests/out/msl/array-in-ctor.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/array-in-function-return-type.msl b/tests/out/msl/array-in-function-return-type.msl index c2c2379cc..77399f642 100644 --- a/tests/out/msl/array-in-function-return-type.msl +++ b/tests/out/msl/array-in-function-return-type.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/atomicOps.msl b/tests/out/msl/atomicOps.msl index 3a34cc307..4732b4a32 100644 --- a/tests/out/msl/atomicOps.msl +++ b/tests/out/msl/atomicOps.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/bitcast.msl b/tests/out/msl/bitcast.msl index ca8bc329b..20f4b850e 100644 --- a/tests/out/msl/bitcast.msl +++ b/tests/out/msl/bitcast.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl index de9d7186a..ce1ccc7cc 100644 --- a/tests/out/msl/boids.msl +++ b/tests/out/msl/boids.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/bounds-check-image-restrict.msl b/tests/out/msl/bounds-check-image-restrict.msl index 9f94ef0a6..6a3c43f0c 100644 --- a/tests/out/msl/bounds-check-image-restrict.msl +++ b/tests/out/msl/bounds-check-image-restrict.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.2 #include #include diff --git a/tests/out/msl/bounds-check-image-rzsw.msl b/tests/out/msl/bounds-check-image-rzsw.msl index a93014cb2..5db0c9df9 100644 --- a/tests/out/msl/bounds-check-image-rzsw.msl +++ b/tests/out/msl/bounds-check-image-rzsw.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.2 #include #include diff --git a/tests/out/msl/bounds-check-restrict.msl b/tests/out/msl/bounds-check-restrict.msl index 4191fd276..0d4143653 100644 --- a/tests/out/msl/bounds-check-restrict.msl +++ b/tests/out/msl/bounds-check-restrict.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/bounds-check-zero-atomic.msl b/tests/out/msl/bounds-check-zero-atomic.msl index daaa07923..4a2f0b07d 100644 --- a/tests/out/msl/bounds-check-zero-atomic.msl +++ b/tests/out/msl/bounds-check-zero-atomic.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/bounds-check-zero.msl b/tests/out/msl/bounds-check-zero.msl index c83f25b31..7bbdd50d1 100644 --- a/tests/out/msl/bounds-check-zero.msl +++ b/tests/out/msl/bounds-check-zero.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/break-if.msl b/tests/out/msl/break-if.msl index 3a6f2e9bf..657fdf9f7 100644 --- a/tests/out/msl/break-if.msl +++ b/tests/out/msl/break-if.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl index 3c8bcf172..e28374145 100644 --- a/tests/out/msl/collatz.msl +++ b/tests/out/msl/collatz.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/const-exprs.msl b/tests/out/msl/const-exprs.msl index 47b3615e1..c61ca952e 100644 --- a/tests/out/msl/const-exprs.msl +++ b/tests/out/msl/const-exprs.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/constructors.msl b/tests/out/msl/constructors.msl index 100d6994e..b3a0ecd89 100644 --- a/tests/out/msl/constructors.msl +++ b/tests/out/msl/constructors.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl index be396e23a..0d0e082e4 100644 --- a/tests/out/msl/control-flow.msl +++ b/tests/out/msl/control-flow.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/do-while.msl b/tests/out/msl/do-while.msl index 6ddd59dab..c1b4d08b0 100644 --- a/tests/out/msl/do-while.msl +++ b/tests/out/msl/do-while.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/dualsource.msl b/tests/out/msl/dualsource.msl index 871957c81..439e3c0d8 100644 --- a/tests/out/msl/dualsource.msl +++ b/tests/out/msl/dualsource.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.2 #include #include diff --git a/tests/out/msl/empty-global-name.msl b/tests/out/msl/empty-global-name.msl index 1cbf9adf4..01cac3f6e 100644 --- a/tests/out/msl/empty-global-name.msl +++ b/tests/out/msl/empty-global-name.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/empty.msl b/tests/out/msl/empty.msl index 4f8bf9f5e..414cd2201 100644 --- a/tests/out/msl/empty.msl +++ b/tests/out/msl/empty.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/fragment-output.msl b/tests/out/msl/fragment-output.msl index 4d25809e4..c886fc885 100644 --- a/tests/out/msl/fragment-output.msl +++ b/tests/out/msl/fragment-output.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/functions.msl b/tests/out/msl/functions.msl index 31f57c656..42632f99b 100644 --- a/tests/out/msl/functions.msl +++ b/tests/out/msl/functions.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl index 9d09db805..d2ed89ed4 100644 --- a/tests/out/msl/globals.msl +++ b/tests/out/msl/globals.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl index e390c2e0f..40d6e809e 100644 --- a/tests/out/msl/image.msl +++ b/tests/out/msl/image.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl index 5d8b67111..616291253 100644 --- a/tests/out/msl/interpolate.msl +++ b/tests/out/msl/interpolate.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl index d0ae8c504..d93e502dc 100644 --- a/tests/out/msl/math-functions.msl +++ b/tests/out/msl/math-functions.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/msl-varyings.msl b/tests/out/msl/msl-varyings.msl index 62d635249..5e5788c8c 100644 --- a/tests/out/msl/msl-varyings.msl +++ b/tests/out/msl/msl-varyings.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl index 114865451..960a87f01 100644 --- a/tests/out/msl/operators.msl +++ b/tests/out/msl/operators.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/padding.msl b/tests/out/msl/padding.msl index 4d99bb4c4..ae11b7d16 100644 --- a/tests/out/msl/padding.msl +++ b/tests/out/msl/padding.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/policy-mix.msl b/tests/out/msl/policy-mix.msl index bb7c12671..24a40179a 100644 --- a/tests/out/msl/policy-mix.msl +++ b/tests/out/msl/policy-mix.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl index 718d7aafa..24b6cdd09 100644 --- a/tests/out/msl/quad-vert.msl +++ b/tests/out/msl/quad-vert.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl index 5fa5788aa..75fdafb6d 100644 --- a/tests/out/msl/quad.msl +++ b/tests/out/msl/quad.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/resource-binding-map.msl b/tests/out/msl/resource-binding-map.msl index b4a53d97b..56fcea0cc 100644 --- a/tests/out/msl/resource-binding-map.msl +++ b/tests/out/msl/resource-binding-map.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl index 15dd042b8..2443f002f 100644 --- a/tests/out/msl/shadow.msl +++ b/tests/out/msl/shadow.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/standard.msl b/tests/out/msl/standard.msl index f02243eaa..e02ef7f89 100644 --- a/tests/out/msl/standard.msl +++ b/tests/out/msl/standard.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/texture-arg.msl b/tests/out/msl/texture-arg.msl index 5fb9b2564..4c173fce0 100644 --- a/tests/out/msl/texture-arg.msl +++ b/tests/out/msl/texture-arg.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/workgroup-uniform-load.msl b/tests/out/msl/workgroup-uniform-load.msl index 37a878173..32495c198 100644 --- a/tests/out/msl/workgroup-uniform-load.msl +++ b/tests/out/msl/workgroup-uniform-load.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include diff --git a/tests/out/msl/workgroup-var-init.msl b/tests/out/msl/workgroup-var-init.msl index ac300d433..991c8b014 100644 --- a/tests/out/msl/workgroup-var-init.msl +++ b/tests/out/msl/workgroup-var-init.msl @@ -1,4 +1,4 @@ -// language: metal2.0 +// language: metal1.0 #include #include From 0340c2e685a3c8ec5d0c55192ae3af48f2c3962f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 20 Sep 2023 12:29:29 +0200 Subject: [PATCH 2170/2212] [msl] add undocumented checks --- src/back/msl/mod.rs | 4 ++++ src/back/msl/writer.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index a5c713965..cb4e72397 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -129,6 +129,10 @@ pub enum Error { CapabilityNotSupported(crate::valid::Capabilities), #[error("attribute '{0}' is not supported for target MSL version")] UnsupportedAttribute(String), + #[error("can not use writeable storage buffers in fragment stage prior to MSL 1.2")] + UnsupportedWriteableStorageBuffer, + #[error("can not use writeable storage textures in {0:?} stage prior to MSL 1.2")] + UnsupportedWriteableStorageTexture(crate::ShaderStage), } #[derive(Clone, Debug, PartialEq, thiserror::Error)] diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index bdb0b0ac3..64808c001 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3940,6 +3940,35 @@ impl Writer { let resolved = match var.space { crate::AddressSpace::PushConstant => options.resolve_push_constants(ep).ok(), crate::AddressSpace::WorkGroup => None, + // This restriciton is not documented in the MSL spec but validation will fail if not upheld. + // We imply the version check from the "Function Buffer Read-Writes" section of https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html + // where the feaure sets listed correspond with the ones supporting MSL 1.2. + crate::AddressSpace::Storage { access } + if access.contains(crate::StorageAccess::STORE) + && options.lang_version < (1, 2) + && ep.stage == crate::ShaderStage::Fragment => + { + return Err(Error::UnsupportedWriteableStorageBuffer) + } + // This restriciton is not documented in the MSL spec but validation will fail if not upheld. + // We imply the version check from the "Function Texture Read-Writes" section of https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html + // where the feaure set listed corresponds with the one supporting MSL 1.2. + crate::AddressSpace::Handle + if match module.types[var.ty].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Storage { access, .. }, + .. + } => { + access.contains(crate::StorageAccess::STORE) + && options.lang_version < (1, 2) + && (ep.stage == crate::ShaderStage::Vertex + || ep.stage == crate::ShaderStage::Fragment) + } + _ => false, + } => + { + return Err(Error::UnsupportedWriteableStorageTexture(ep.stage)) + } _ => options .resolve_resource_binding(ep, var.binding.as_ref().unwrap()) .ok(), From a7146b07a147c8806f7318518fa8c31a8e4c0bb6 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 20 Sep 2023 12:45:59 +0200 Subject: [PATCH 2171/2212] [msl-out] add min version check for `base_instance` & `instance_id` --- src/back/msl/mod.rs | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index cb4e72397..f6ea6d42b 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -232,16 +232,25 @@ impl Options { ) -> Result { match *binding { crate::Binding::BuiltIn(mut built_in) => { - if let crate::BuiltIn::Position { ref mut invariant } = built_in { - if *invariant && self.lang_version < (2, 1) { - return Err(Error::UnsupportedAttribute("invariant".to_string())); - } + match built_in { + crate::BuiltIn::Position { ref mut invariant } => { + if *invariant && self.lang_version < (2, 1) { + return Err(Error::UnsupportedAttribute("invariant".to_string())); + } - // The 'invariant' attribute may only appear on vertex - // shader outputs, not fragment shader inputs. - if !matches!(mode, LocationMode::VertexOutput) { - *invariant = false; + // The 'invariant' attribute may only appear on vertex + // shader outputs, not fragment shader inputs. + if !matches!(mode, LocationMode::VertexOutput) { + *invariant = false; + } } + crate::BuiltIn::BaseInstance if self.lang_version < (1, 2) => { + return Err(Error::UnsupportedAttribute("base_instance".to_string())); + } + crate::BuiltIn::InstanceIndex if self.lang_version < (1, 2) => { + return Err(Error::UnsupportedAttribute("instance_id".to_string())); + } + _ => {} } Ok(ResolvedBinding::BuiltIn(built_in)) From 0c63be8904430350c2144ab613e613f83186288f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 20 Sep 2023 13:09:25 +0200 Subject: [PATCH 2172/2212] [msl-out] add min version check for `reverse_bits`, `extract_bits` & `insert_bits` --- src/back/msl/mod.rs | 2 ++ src/back/msl/writer.rs | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index f6ea6d42b..76e0c39e1 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -129,6 +129,8 @@ pub enum Error { CapabilityNotSupported(crate::valid::Capabilities), #[error("attribute '{0}' is not supported for target MSL version")] UnsupportedAttribute(String), + #[error("function '{0}' is not supported for target MSL version")] + UnsupportedFunction(String), #[error("can not use writeable storage buffers in fragment stage prior to MSL 1.2")] UnsupportedWriteableStorageBuffer, #[error("can not use writeable storage textures in {0:?} stage prior to MSL 1.2")] diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 64808c001..ecec0d70b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -503,6 +503,7 @@ struct ExpressionContext<'a> { module: &'a crate::Module, mod_info: &'a valid::ModuleInfo, pipeline_options: &'a PipelineOptions, + lang_version: (u8, u8), policies: index::BoundsCheckPolicies, /// A bitset containing the `Expression` handle indexes of expressions used @@ -1789,6 +1790,23 @@ impl Writer { Mf::Unpack2x16float => "", }; + match fun { + Mf::ReverseBits | Mf::ExtractBits | Mf::InsertBits => { + // reverse_bits is listed as requiring MSL 2.1 but that + // is a copy/paste error. Looking at previous snapshots + // on web.archive.org it's present in MSL 1.2. + // + // https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html + // also talks about MSL 1.2 adding "New integer + // functions to extract, insert, and reverse bits, as + // described in Integer Functions." + if context.lang_version < (1, 2) { + return Err(Error::UnsupportedFunction(fun_name.to_string())); + } + } + _ => {} + } + if fun == Mf::Distance && scalar_argument { write!(self.out, "{NAMESPACE}::abs(")?; self.put_expression(arg, context, false)?; @@ -3559,6 +3577,7 @@ impl Writer { function: fun, origin: FunctionOrigin::Handle(fun_handle), info: fun_info, + lang_version: options.lang_version, policies: options.bounds_check_policies, guarded_indices, module, @@ -4141,6 +4160,7 @@ impl Writer { function: fun, origin: FunctionOrigin::EntryPoint(ep_index as _), info: fun_info, + lang_version: options.lang_version, policies: options.bounds_check_policies, guarded_indices, module, From f4a43b1bf07af3e72f95b35e284eb2ac5724ca10 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 20 Sep 2023 13:24:44 +0200 Subject: [PATCH 2173/2212] [msl-out] add min version check for read-write storage textures --- src/back/msl/mod.rs | 2 + src/back/msl/writer.rs | 84 +++++++++++++++++++++++++++--------------- 2 files changed, 57 insertions(+), 29 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 76e0c39e1..7b32ce80d 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -135,6 +135,8 @@ pub enum Error { UnsupportedWriteableStorageBuffer, #[error("can not use writeable storage textures in {0:?} stage prior to MSL 1.2")] UnsupportedWriteableStorageTexture(crate::ShaderStage), + #[error("can not use read-write storage textures prior to MSL 1.2")] + UnsupportedRWStorageTexture, } #[derive(Clone, Debug, PartialEq, thiserror::Error)] diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index ecec0d70b..c17e84216 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -3955,39 +3955,65 @@ impl Writer { if usage.is_empty() || var.space == crate::AddressSpace::Private { continue; } + + if options.lang_version < (1, 2) { + match var.space { + // This restriction is not documented in the MSL spec + // but validation will fail if it is not upheld. + // + // We infer the required version from the "Function + // Buffer Read-Writes" section of [what's new], where + // the feature sets listed correspond with the ones + // supporting MSL 1.2. + // + // [what's new]: https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html + crate::AddressSpace::Storage { access } + if access.contains(crate::StorageAccess::STORE) + && ep.stage == crate::ShaderStage::Fragment => + { + return Err(Error::UnsupportedWriteableStorageBuffer) + } + crate::AddressSpace::Handle => { + match module.types[var.ty].inner { + crate::TypeInner::Image { + class: crate::ImageClass::Storage { access, .. }, + .. + } => { + // This restriction is not documented in the MSL spec + // but validation will fail if it is not upheld. + // + // We infer the required version from the "Function + // Texture Read-Writes" section of [what's new], where + // the feature sets listed correspond with the ones + // supporting MSL 1.2. + // + // [what's new]: https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html + if access.contains(crate::StorageAccess::STORE) + && (ep.stage == crate::ShaderStage::Vertex + || ep.stage == crate::ShaderStage::Fragment) + { + return Err(Error::UnsupportedWriteableStorageTexture( + ep.stage, + )); + } + + if access.contains( + crate::StorageAccess::LOAD | crate::StorageAccess::STORE, + ) { + return Err(Error::UnsupportedRWStorageTexture); + } + } + _ => {} + } + } + _ => {} + } + } + // the resolves have already been checked for `!fake_missing_bindings` case let resolved = match var.space { crate::AddressSpace::PushConstant => options.resolve_push_constants(ep).ok(), crate::AddressSpace::WorkGroup => None, - // This restriciton is not documented in the MSL spec but validation will fail if not upheld. - // We imply the version check from the "Function Buffer Read-Writes" section of https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html - // where the feaure sets listed correspond with the ones supporting MSL 1.2. - crate::AddressSpace::Storage { access } - if access.contains(crate::StorageAccess::STORE) - && options.lang_version < (1, 2) - && ep.stage == crate::ShaderStage::Fragment => - { - return Err(Error::UnsupportedWriteableStorageBuffer) - } - // This restriciton is not documented in the MSL spec but validation will fail if not upheld. - // We imply the version check from the "Function Texture Read-Writes" section of https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html - // where the feaure set listed corresponds with the one supporting MSL 1.2. - crate::AddressSpace::Handle - if match module.types[var.ty].inner { - crate::TypeInner::Image { - class: crate::ImageClass::Storage { access, .. }, - .. - } => { - access.contains(crate::StorageAccess::STORE) - && options.lang_version < (1, 2) - && (ep.stage == crate::ShaderStage::Vertex - || ep.stage == crate::ShaderStage::Fragment) - } - _ => false, - } => - { - return Err(Error::UnsupportedWriteableStorageTexture(ep.stage)) - } _ => options .resolve_resource_binding(ep, var.binding.as_ref().unwrap()) .ok(), From 46c472731f28ce5df4100e2e04cf5f6257b567c6 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 20 Sep 2023 14:09:50 +0200 Subject: [PATCH 2174/2212] [msl-out] add min version checks for binding arrays --- src/back/msl/mod.rs | 4 +++ src/back/msl/writer.rs | 59 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 7b32ce80d..fc507b4ea 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -137,6 +137,10 @@ pub enum Error { UnsupportedWriteableStorageTexture(crate::ShaderStage), #[error("can not use read-write storage textures prior to MSL 1.2")] UnsupportedRWStorageTexture, + #[error("array of '{0}' is not supported for target MSL version")] + UnsupportedArrayOf(String), + #[error("array of type '{0:?}' is not supported")] + UnsupportedArrayOfType(Handle), } #[derive(Clone, Debug, PartialEq, thiserror::Error)] diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index c17e84216..285dcc4e7 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -4010,6 +4010,65 @@ impl Writer { } } + // Check min MSL version for binding arrays + match var.space { + crate::AddressSpace::Handle => match module.types[var.ty].inner { + crate::TypeInner::BindingArray { base, .. } => { + match module.types[base].inner { + crate::TypeInner::Sampler { .. } => { + if options.lang_version < (2, 0) { + return Err(Error::UnsupportedArrayOf( + "samplers".to_string(), + )); + } + } + crate::TypeInner::Image { class, .. } => match class { + crate::ImageClass::Sampled { .. } + | crate::ImageClass::Depth { .. } + | crate::ImageClass::Storage { + access: crate::StorageAccess::LOAD, + .. + } => { + // Array of textures since: + // - iOS: Metal 1.2 (check depends on https://github.com/gfx-rs/naga/issues/2164) + // - macOS: Metal 2 + + if options.lang_version < (2, 0) { + return Err(Error::UnsupportedArrayOf( + "textures".to_string(), + )); + } + } + crate::ImageClass::Storage { + access: crate::StorageAccess::STORE, + .. + } => { + // Array of write-only textures since: + // - iOS: Metal 2.2 (check depends on https://github.com/gfx-rs/naga/issues/2164) + // - macOS: Metal 2 + + if options.lang_version < (2, 0) { + return Err(Error::UnsupportedArrayOf( + "write-only textures".to_string(), + )); + } + } + crate::ImageClass::Storage { .. } => { + return Err(Error::UnsupportedArrayOf( + "read-write textures".to_string(), + )); + } + }, + _ => { + return Err(Error::UnsupportedArrayOfType(base)); + } + } + } + _ => {} + }, + _ => {} + } + // the resolves have already been checked for `!fake_missing_bindings` case let resolved = match var.space { crate::AddressSpace::PushConstant => options.resolve_push_constants(ep).ok(), From 89ab5902b2300bbb04281ebb7862a3ce53ab8f4b Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 20 Sep 2023 14:16:17 +0200 Subject: [PATCH 2175/2212] [msl-out] add min version check for `primitive_id` --- src/back/msl/mod.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index fc507b4ea..15af43abd 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -258,6 +258,11 @@ impl Options { crate::BuiltIn::InstanceIndex if self.lang_version < (1, 2) => { return Err(Error::UnsupportedAttribute("instance_id".to_string())); } + // macOS: Since Metal 2.2 + // iOS: Since Metal 2.3 (check depends on https://github.com/gfx-rs/naga/issues/2164) + crate::BuiltIn::PrimitiveIndex if self.lang_version < (2, 2) => { + return Err(Error::UnsupportedAttribute("primitive_id".to_string())); + } _ => {} } From ea83f62a949ea076c3e5db56d4e099a9a4b34f0b Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 20 Sep 2023 14:57:43 +0200 Subject: [PATCH 2176/2212] [msl-out] add min version check for ray tracing --- src/back/msl/mod.rs | 2 + src/back/msl/writer.rs | 97 +++++++++++++++++++++++++++++------------- 2 files changed, 69 insertions(+), 30 deletions(-) diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs index 15af43abd..5ef18730c 100644 --- a/src/back/msl/mod.rs +++ b/src/back/msl/mod.rs @@ -141,6 +141,8 @@ pub enum Error { UnsupportedArrayOf(String), #[error("array of type '{0:?}' is not supported")] UnsupportedArrayOfType(Handle), + #[error("ray tracing is not supported prior to MSL 2.3")] + UnsupportedRayTracing, } #[derive(Clone, Debug, PartialEq, thiserror::Error)] diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 285dcc4e7..91315eb5b 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -1961,6 +1961,10 @@ impl Writer { } } crate::Expression::RayQueryGetIntersection { query, committed } => { + if context.lang_version < (2, 4) { + return Err(Error::UnsupportedRayTracing); + } + if !committed { unimplemented!() } @@ -1971,16 +1975,16 @@ impl Writer { write!(self.out, ".{RAY_QUERY_FIELD_INTERSECTION}.type)")?; let fields = [ "distance", - "user_instance_id", + "user_instance_id", // req Metal 2.4 "instance_id", "", // SBT offset "geometry_id", "primitive_id", "triangle_barycentric_coord", "triangle_front_facing", - "", // padding - "object_to_world_transform", - "world_to_object_transform", + "", // padding + "object_to_world_transform", // req Metal 2.4 + "world_to_object_transform", // req Metal 2.4 ]; for field in fields { write!(self.out, ", ")?; @@ -2913,6 +2917,10 @@ impl Writer { self.write_barrier(crate::Barrier::WORK_GROUP, level)?; } crate::Statement::RayQuery { query, ref fun } => { + if context.expression.lang_version < (2, 4) { + return Err(Error::UnsupportedRayTracing); + } + match *fun { crate::RayQueryFunction::Initialize { acceleration_structure, @@ -3104,33 +3112,36 @@ impl Writer { // Work around Metal bug where `uint` is not available by default writeln!(self.out, "using {NAMESPACE}::uint;")?; - if module.types.iter().any(|(_, t)| match t.inner { - crate::TypeInner::RayQuery => true, - _ => false, - }) { - let tab = back::INDENT; - writeln!(self.out, "struct {RAY_QUERY_TYPE} {{")?; - let full_type = format!("{RT_NAMESPACE}::intersector<{RT_NAMESPACE}::instancing, {RT_NAMESPACE}::triangle_data, {RT_NAMESPACE}::world_space_data>"); - writeln!(self.out, "{tab}{full_type} {RAY_QUERY_FIELD_INTERSECTOR};")?; - writeln!( - self.out, - "{tab}{full_type}::result_type {RAY_QUERY_FIELD_INTERSECTION};" - )?; - writeln!(self.out, "{tab}bool {RAY_QUERY_FIELD_READY} = false;")?; - writeln!(self.out, "}};")?; - writeln!(self.out, "constexpr {NAMESPACE}::uint {RAY_QUERY_FUN_MAP_INTERSECTION}(const {RT_NAMESPACE}::intersection_type ty) {{")?; - let v_triangle = back::RayIntersectionType::Triangle as u32; - let v_bbox = back::RayIntersectionType::BoundingBox as u32; - writeln!( - self.out, - "{tab}return ty=={RT_NAMESPACE}::intersection_type::triangle ? {v_triangle} : " - )?; - writeln!( - self.out, - "{tab}{tab}ty=={RT_NAMESPACE}::intersection_type::bounding_box ? {v_bbox} : 0;" - )?; - writeln!(self.out, "}}")?; + let mut uses_ray_query = false; + for (_, ty) in module.types.iter() { + match ty.inner { + crate::TypeInner::AccelerationStructure => { + if options.lang_version < (2, 4) { + return Err(Error::UnsupportedRayTracing); + } + } + crate::TypeInner::RayQuery => { + if options.lang_version < (2, 4) { + return Err(Error::UnsupportedRayTracing); + } + uses_ray_query = true; + } + _ => (), + } } + + if module.special_types.ray_desc.is_some() + || module.special_types.ray_intersection.is_some() + { + if options.lang_version < (2, 4) { + return Err(Error::UnsupportedRayTracing); + } + } + + if uses_ray_query { + self.put_ray_query_type()?; + } + if options .bounds_check_policies .contains(index::BoundsCheckPolicy::ReadZeroSkipWrite) @@ -3188,6 +3199,32 @@ impl Writer { Ok(()) } + fn put_ray_query_type(&mut self) -> BackendResult { + let tab = back::INDENT; + writeln!(self.out, "struct {RAY_QUERY_TYPE} {{")?; + let full_type = format!("{RT_NAMESPACE}::intersector<{RT_NAMESPACE}::instancing, {RT_NAMESPACE}::triangle_data, {RT_NAMESPACE}::world_space_data>"); + writeln!(self.out, "{tab}{full_type} {RAY_QUERY_FIELD_INTERSECTOR};")?; + writeln!( + self.out, + "{tab}{full_type}::result_type {RAY_QUERY_FIELD_INTERSECTION};" + )?; + writeln!(self.out, "{tab}bool {RAY_QUERY_FIELD_READY} = false;")?; + writeln!(self.out, "}};")?; + writeln!(self.out, "constexpr {NAMESPACE}::uint {RAY_QUERY_FUN_MAP_INTERSECTION}(const {RT_NAMESPACE}::intersection_type ty) {{")?; + let v_triangle = back::RayIntersectionType::Triangle as u32; + let v_bbox = back::RayIntersectionType::BoundingBox as u32; + writeln!( + self.out, + "{tab}return ty=={RT_NAMESPACE}::intersection_type::triangle ? {v_triangle} : " + )?; + writeln!( + self.out, + "{tab}{tab}ty=={RT_NAMESPACE}::intersection_type::bounding_box ? {v_bbox} : 0;" + )?; + writeln!(self.out, "}}")?; + Ok(()) + } + fn write_type_defs(&mut self, module: &crate::Module) -> BackendResult { for (handle, ty) in module.types.iter() { if !ty.needs_alias() { From 6854b0ab4f105131bfb87704927abec3fe366ef9 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 25 Sep 2023 17:49:56 +0200 Subject: [PATCH 2177/2212] disallow ptr to workgroup fn arguments --- src/valid/function.rs | 7 +- src/valid/type.rs | 14 +- tests/in/access.wgsl | 9 +- tests/out/analysis/access.info.ron | 47 +- .../access.assign_through_ptr.Compute.glsl | 8 +- tests/out/hlsl/access.hlsl | 8 +- tests/out/ir/access.compact.ron | 53 +- tests/out/ir/access.ron | 53 +- tests/out/msl/access.msl | 9 +- tests/out/spv/access.spvasm | 659 +++++++++--------- tests/out/wgsl/access.wgsl | 4 +- tests/wgsl-errors.rs | 16 +- 12 files changed, 431 insertions(+), 456 deletions(-) diff --git a/src/valid/function.rs b/src/valid/function.rs index ca5877ba1..d967f4b1f 100644 --- a/src/valid/function.rs +++ b/src/valid/function.rs @@ -1001,12 +1001,7 @@ impl super::Validator { #[cfg(feature = "validate")] for (index, argument) in fun.arguments.iter().enumerate() { match module.types[argument.ty].inner.pointer_space() { - Some( - crate::AddressSpace::Private - | crate::AddressSpace::Function - | crate::AddressSpace::WorkGroup, - ) - | None => {} + Some(crate::AddressSpace::Private | crate::AddressSpace::Function) | None => {} Some(other) => { return Err(FunctionError::InvalidArgumentPointerSpace { index, diff --git a/src/valid/type.rs b/src/valid/type.rs index c0d8a1295..64f770833 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -164,12 +164,14 @@ fn check_member_layout( /// `TypeFlags::empty()`. /// /// Pointers passed as arguments to user-defined functions must be in the -/// `Function`, `Private`, or `Workgroup` storage space. +/// `Function` or `Private` address space. const fn ptr_space_argument_flag(space: crate::AddressSpace) -> TypeFlags { use crate::AddressSpace as As; match space { - As::Function | As::Private | As::WorkGroup => TypeFlags::ARGUMENT, - As::Uniform | As::Storage { .. } | As::Handle | As::PushConstant => TypeFlags::empty(), + As::Function | As::Private => TypeFlags::ARGUMENT, + As::Uniform | As::Storage { .. } | As::Handle | As::PushConstant | As::WorkGroup => { + TypeFlags::empty() + } } } @@ -316,7 +318,7 @@ impl super::Validator { return Err(TypeError::InvalidPointerBase(base)); } - // Runtime-sized values can only live in the `Storage` storage + // Runtime-sized values can only live in the `Storage` address // space, so it's useless to have a pointer to such a type in // any other space. // @@ -336,7 +338,7 @@ impl super::Validator { } } - // `Validator::validate_function` actually checks the storage + // `Validator::validate_function` actually checks the address // space of pointer arguments explicitly before checking the // `ARGUMENT` flag, to give better error messages. But it seems // best to set `ARGUMENT` accurately anyway. @@ -364,7 +366,7 @@ impl super::Validator { // `InvalidPointerBase` or `InvalidPointerToUnsized`. self.check_width(kind, width)?; - // `Validator::validate_function` actually checks the storage + // `Validator::validate_function` actually checks the address // space of pointer arguments explicitly before checking the // `ARGUMENT` flag, to give better error messages. But it seems // best to set `ARGUMENT` accurately anyway. diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl index c9097f913..956a694aa 100644 --- a/tests/in/access.wgsl +++ b/tests/in/access.wgsl @@ -151,9 +151,7 @@ fn foo_frag() -> @location(0) vec4 { return vec4(0.0); } -var val: u32; - -fn assign_through_ptr_fn(p: ptr) { +fn assign_through_ptr_fn(p: ptr) { *p = 42u; } @@ -163,8 +161,9 @@ fn assign_array_through_ptr_fn(foo: ptr, 2>>) { @compute @workgroup_size(1) fn assign_through_ptr() { - var arr = array, 2>(vec4(6.0), vec4(7.0)); - + var val = 33u; assign_through_ptr_fn(&val); + + var arr = array, 2>(vec4(6.0), vec4(7.0)); assign_array_through_ptr_fn(&arr); } diff --git a/tests/out/analysis/access.info.ron b/tests/out/analysis/access.info.ron index 80a2cb162..93eda7f39 100644 --- a/tests/out/analysis/access.info.ron +++ b/tests/out/analysis/access.info.ron @@ -46,7 +46,6 @@ ("READ"), (""), (""), - (""), ], expressions: [ ( @@ -1144,7 +1143,6 @@ (""), (""), ("READ"), - (""), ], expressions: [ ( @@ -2414,7 +2412,6 @@ (""), (""), (""), - (""), ], expressions: [ ( @@ -2454,7 +2451,6 @@ (""), (""), (""), - (""), ], expressions: [ ( @@ -2503,7 +2499,6 @@ (""), (""), (""), - (""), ], expressions: [ ( @@ -2546,7 +2541,6 @@ (""), (""), (""), - (""), ], expressions: [ ( @@ -2638,7 +2632,6 @@ ("READ"), ("READ"), ("READ"), - (""), ], expressions: [ ( @@ -3302,7 +3295,6 @@ (""), ("WRITE"), (""), - (""), ], expressions: [ ( @@ -3736,9 +3728,32 @@ (""), (""), (""), - ("READ"), ], expressions: [ + ( + uniformity: ( + non_uniform_result: None, + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Scalar( + kind: Uint, + width: 4, + )), + ), + ( + uniformity: ( + non_uniform_result: Some(2), + requirements: (""), + ), + ref_count: 1, + assignable_global: None, + ty: Value(Pointer( + base: 1, + space: Function, + )), + ), ( uniformity: ( non_uniform_result: None, @@ -3800,7 +3815,7 @@ ), ( uniformity: ( - non_uniform_result: Some(6), + non_uniform_result: Some(8), requirements: (""), ), ref_count: 1, @@ -3810,18 +3825,6 @@ space: Function, )), ), - ( - uniformity: ( - non_uniform_result: None, - requirements: (""), - ), - ref_count: 1, - assignable_global: Some(6), - ty: Value(Pointer( - base: 1, - space: WorkGroup, - )), - ), ], sampling: [], dual_source_blending: false, diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/tests/out/glsl/access.assign_through_ptr.Compute.glsl index a75b0f4d9..2e51bbde6 100644 --- a/tests/out/glsl/access.assign_through_ptr.Compute.glsl +++ b/tests/out/glsl/access.assign_through_ptr.Compute.glsl @@ -19,8 +19,6 @@ struct Baz { struct MatCx2InArray { mat4x2 am[2]; }; -shared uint val; - float read_from_private(inout float foo_1) { float _e1 = foo_1; @@ -42,11 +40,7 @@ void assign_array_through_ptr_fn(inout vec4 foo_2[2]) { } void main() { - if (gl_LocalInvocationID == uvec3(0u)) { - val = 0u; - } - memoryBarrierShared(); - barrier(); + uint val = 33u; vec4 arr[2] = vec4[2](vec4(6.0), vec4(7.0)); assign_through_ptr_fn(val); assign_array_through_ptr_fn(arr); diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl index a4c739d74..47d9cc24f 100644 --- a/tests/out/hlsl/access.hlsl +++ b/tests/out/hlsl/access.hlsl @@ -81,7 +81,6 @@ RWByteAddressBuffer bar : register(u0); cbuffer baz : register(b1) { Baz baz; } RWByteAddressBuffer qux : register(u2); cbuffer nested_mat_cx2_ : register(b3) { MatCx2InArray nested_mat_cx2_; } -groupshared uint val; Baz ConstructBaz(float3x2 arg0) { Baz ret = (Baz)0; @@ -288,12 +287,9 @@ float4 foo_frag() : SV_Target0 } [numthreads(1, 1, 1)] -void assign_through_ptr(uint3 __local_invocation_id : SV_GroupThreadID) +void assign_through_ptr() { - if (all(__local_invocation_id == uint3(0u, 0u, 0u))) { - val = (uint)0; - } - GroupMemoryBarrierWithGroupSync(); + uint val = 33u; float4 arr[2] = Constructarray2_float4_((6.0).xxxx, (7.0).xxxx); assign_through_ptr_fn(val); diff --git a/tests/out/ir/access.compact.ron b/tests/out/ir/access.compact.ron index f24f830af..65f9622f2 100644 --- a/tests/out/ir/access.compact.ron +++ b/tests/out/ir/access.compact.ron @@ -279,7 +279,7 @@ name: None, inner: Pointer( base: 1, - space: WorkGroup, + space: Function, ), ), ( @@ -356,13 +356,6 @@ ty: 20, init: None, ), - ( - name: Some("val"), - space: WorkGroup, - binding: None, - ty: 1, - init: None, - ), ], const_expressions: [ Literal(U32(0)), @@ -2137,54 +2130,60 @@ arguments: [], result: None, local_variables: [ + ( + name: Some("val"), + ty: 1, + init: Some(1), + ), ( name: Some("arr"), ty: 28, - init: Some(5), + init: Some(7), ), ], expressions: [ + Literal(U32(33)), + LocalVariable(1), Literal(F32(6.0)), - Splat( - size: Quad, - value: 1, - ), - Literal(F32(7.0)), Splat( size: Quad, value: 3, ), + Literal(F32(7.0)), + Splat( + size: Quad, + value: 5, + ), Compose( ty: 28, components: [ - 2, 4, + 6, ], ), - LocalVariable(1), - GlobalVariable(6), + LocalVariable(2), ], named_expressions: {}, body: [ - Emit(( - start: 1, - end: 2, - )), - Emit(( - start: 3, - end: 5, - )), Call( function: 5, arguments: [ - 7, + 2, ], result: None, ), + Emit(( + start: 3, + end: 4, + )), + Emit(( + start: 5, + end: 7, + )), Call( function: 6, arguments: [ - 6, + 8, ], result: None, ), diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron index 9a1820fc8..77d95dd58 100644 --- a/tests/out/ir/access.ron +++ b/tests/out/ir/access.ron @@ -312,7 +312,7 @@ name: None, inner: Pointer( base: 1, - space: WorkGroup, + space: Function, ), ), ( @@ -389,13 +389,6 @@ ty: 21, init: None, ), - ( - name: Some("val"), - space: WorkGroup, - binding: None, - ty: 1, - init: None, - ), ], const_expressions: [ Literal(U32(0)), @@ -2235,54 +2228,60 @@ arguments: [], result: None, local_variables: [ + ( + name: Some("val"), + ty: 1, + init: Some(1), + ), ( name: Some("arr"), ty: 32, - init: Some(5), + init: Some(7), ), ], expressions: [ + Literal(U32(33)), + LocalVariable(1), Literal(F32(6.0)), - Splat( - size: Quad, - value: 1, - ), - Literal(F32(7.0)), Splat( size: Quad, value: 3, ), + Literal(F32(7.0)), + Splat( + size: Quad, + value: 5, + ), Compose( ty: 32, components: [ - 2, 4, + 6, ], ), - LocalVariable(1), - GlobalVariable(6), + LocalVariable(2), ], named_expressions: {}, body: [ - Emit(( - start: 1, - end: 2, - )), - Emit(( - start: 3, - end: 5, - )), Call( function: 5, arguments: [ - 7, + 2, ], result: None, ), + Emit(( + start: 3, + end: 4, + )), + Emit(( + start: 5, + end: 7, + )), Call( function: 6, arguments: [ - 6, + 8, ], result: None, ), diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl index d0f48ba4f..908535ea3 100644 --- a/tests/out/msl/access.msl +++ b/tests/out/msl/access.msl @@ -146,7 +146,7 @@ float test_arr_as_arg( } void assign_through_ptr_fn( - threadgroup uint& p + thread uint& p ) { p = 42u; return; @@ -210,13 +210,8 @@ fragment foo_fragOutput foo_frag( kernel void assign_through_ptr( - metal::uint3 __local_invocation_id [[thread_position_in_threadgroup]] -, threadgroup uint& val ) { - if (metal::all(__local_invocation_id == metal::uint3(0u))) { - val = {}; - } - metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup); + uint val = 33u; type_22 arr = type_22 {metal::float4(6.0), metal::float4(7.0)}; assign_through_ptr_fn(val); assign_array_through_ptr_fn(arr); diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm index 40476395c..3446878c9 100644 --- a/tests/out/spv/access.spvasm +++ b/tests/out/spv/access.spvasm @@ -1,16 +1,16 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 313 +; Bound: 301 OpCapability Shader OpExtension "SPV_KHR_storage_buffer_storage_class" %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %220 "foo_vert" %215 %218 -OpEntryPoint Fragment %274 "foo_frag" %273 -OpEntryPoint GLCompute %292 "assign_through_ptr" %299 -OpExecutionMode %274 OriginUpperLeft -OpExecutionMode %292 LocalSize 1 1 1 +OpEntryPoint Vertex %219 "foo_vert" %214 %217 +OpEntryPoint Fragment %273 "foo_frag" %272 +OpEntryPoint GLCompute %291 "assign_through_ptr" +OpExecutionMode %273 OriginUpperLeft +OpExecutionMode %291 LocalSize 1 1 1 OpMemberName %6 0 "a" OpMemberName %6 1 "b" OpMemberName %6 2 "c" @@ -33,28 +33,28 @@ OpName %42 "bar" OpName %44 "baz" OpName %47 "qux" OpName %50 "nested_mat_cx2" -OpName %53 "val" -OpName %55 "test_matrix_within_struct_accesses" -OpName %83 "idx" -OpName %85 "t" -OpName %131 "test_matrix_within_array_within_struct_accesses" -OpName %141 "idx" -OpName %142 "t" -OpName %188 "foo" -OpName %189 "read_from_private" -OpName %194 "a" -OpName %195 "test_arr_as_arg" -OpName %201 "p" -OpName %202 "assign_through_ptr_fn" -OpName %207 "foo" -OpName %208 "assign_array_through_ptr_fn" -OpName %215 "vi" -OpName %220 "foo_vert" -OpName %232 "foo" -OpName %233 "c2" -OpName %274 "foo_frag" -OpName %292 "assign_through_ptr" -OpName %296 "arr" +OpName %54 "test_matrix_within_struct_accesses" +OpName %82 "idx" +OpName %84 "t" +OpName %130 "test_matrix_within_array_within_struct_accesses" +OpName %140 "idx" +OpName %141 "t" +OpName %187 "foo" +OpName %188 "read_from_private" +OpName %193 "a" +OpName %194 "test_arr_as_arg" +OpName %200 "p" +OpName %201 "assign_through_ptr_fn" +OpName %206 "foo" +OpName %207 "assign_array_through_ptr_fn" +OpName %214 "vi" +OpName %219 "foo_vert" +OpName %231 "foo" +OpName %232 "c2" +OpName %273 "foo_frag" +OpName %291 "assign_through_ptr" +OpName %296 "val" +OpName %297 "arr" OpMemberDecorate %6 0 Offset 0 OpMemberDecorate %6 1 Offset 16 OpMemberDecorate %6 2 Offset 28 @@ -99,10 +99,9 @@ OpDecorate %50 DescriptorSet 0 OpDecorate %50 Binding 3 OpDecorate %51 Block OpMemberDecorate %51 0 Offset 0 -OpDecorate %215 BuiltIn VertexIndex -OpDecorate %218 BuiltIn Position -OpDecorate %273 Location 0 -OpDecorate %299 BuiltIn LocalInvocationId +OpDecorate %214 BuiltIn VertexIndex +OpDecorate %217 BuiltIn Position +OpDecorate %272 Location 0 %2 = OpTypeVoid %3 = OpTypeInt 32 0 %4 = OpTypeVector %3 3 @@ -134,7 +133,7 @@ OpDecorate %299 BuiltIn LocalInvocationId %29 = OpTypeArray %28 %30 %31 = OpTypeVector %10 4 %32 = OpTypeArray %5 %30 -%33 = OpTypePointer Workgroup %3 +%33 = OpTypePointer Function %3 %34 = OpTypeArray %31 %14 %35 = OpTypePointer Function %34 %36 = OpConstant %3 0 @@ -154,327 +153,309 @@ OpDecorate %299 BuiltIn LocalInvocationId %51 = OpTypeStruct %26 %52 = OpTypePointer Uniform %51 %50 = OpVariable %52 Uniform -%53 = OpVariable %33 Workgroup -%56 = OpTypeFunction %2 -%57 = OpTypePointer Uniform %22 -%59 = OpConstant %5 1 -%60 = OpConstant %10 1.0 -%61 = OpConstantComposite %12 %60 %60 -%62 = OpConstant %10 2.0 -%63 = OpConstantComposite %12 %62 %62 -%64 = OpConstant %10 3.0 -%65 = OpConstantComposite %12 %64 %64 -%66 = OpConstantComposite %21 %61 %63 %65 -%67 = OpConstantComposite %22 %66 -%68 = OpConstant %10 6.0 -%69 = OpConstantComposite %12 %68 %68 -%70 = OpConstant %10 5.0 -%71 = OpConstantComposite %12 %70 %70 -%72 = OpConstant %10 4.0 -%73 = OpConstantComposite %12 %72 %72 -%74 = OpConstantComposite %21 %69 %71 %73 -%75 = OpConstant %10 9.0 -%76 = OpConstantComposite %12 %75 %75 -%77 = OpConstant %10 90.0 -%78 = OpConstantComposite %12 %77 %77 -%79 = OpConstant %10 10.0 -%80 = OpConstant %10 20.0 -%81 = OpConstant %10 30.0 -%82 = OpConstant %10 40.0 -%84 = OpTypePointer Function %5 -%86 = OpTypePointer Function %22 -%90 = OpTypePointer Uniform %21 -%93 = OpTypePointer Uniform %12 -%99 = OpTypePointer Uniform %10 -%100 = OpConstant %3 1 -%115 = OpTypePointer Function %21 -%117 = OpTypePointer Function %12 -%121 = OpTypePointer Function %10 -%132 = OpTypePointer Uniform %26 -%134 = OpConstantNull %25 -%135 = OpConstantComposite %26 %134 -%136 = OpConstant %10 8.0 -%137 = OpConstantComposite %12 %136 %136 -%138 = OpConstant %10 7.0 -%139 = OpConstantComposite %12 %138 %138 -%140 = OpConstantComposite %24 %137 %139 %69 %71 -%143 = OpTypePointer Function %26 -%147 = OpTypePointer Uniform %25 -%150 = OpTypePointer Uniform %24 -%172 = OpTypePointer Function %25 -%174 = OpTypePointer Function %24 -%190 = OpTypeFunction %10 %27 -%196 = OpTypeFunction %10 %29 -%203 = OpTypeFunction %2 %33 -%204 = OpConstant %3 42 -%209 = OpTypeFunction %2 %35 -%210 = OpConstantComposite %31 %60 %60 %60 %60 -%211 = OpConstantComposite %31 %62 %62 %62 %62 -%212 = OpConstantComposite %34 %210 %211 -%216 = OpTypePointer Input %3 -%215 = OpVariable %216 Input -%219 = OpTypePointer Output %31 -%218 = OpVariable %219 Output -%222 = OpTypePointer StorageBuffer %23 -%225 = OpConstant %10 0.0 -%226 = OpConstant %3 3 -%227 = OpConstant %5 3 -%228 = OpConstant %5 4 -%229 = OpConstant %5 5 -%230 = OpConstant %5 42 -%231 = OpConstantNull %29 -%234 = OpTypePointer Function %32 -%235 = OpConstantNull %32 -%240 = OpTypePointer StorageBuffer %8 -%243 = OpTypePointer StorageBuffer %18 -%244 = OpConstant %3 4 -%247 = OpTypePointer StorageBuffer %9 -%248 = OpTypePointer StorageBuffer %10 -%251 = OpTypePointer StorageBuffer %19 -%254 = OpTypePointer StorageBuffer %7 -%255 = OpTypePointer StorageBuffer %5 -%267 = OpTypeVector %5 4 -%273 = OpVariable %219 Output -%276 = OpConstantComposite %9 %225 %225 %225 -%277 = OpConstantComposite %9 %60 %60 %60 -%278 = OpConstantComposite %9 %62 %62 %62 -%279 = OpConstantComposite %9 %64 %64 %64 -%280 = OpConstantComposite %8 %276 %277 %278 %279 -%281 = OpConstantComposite %17 %36 %36 -%282 = OpConstantComposite %17 %100 %100 -%283 = OpConstantComposite %18 %281 %282 -%284 = OpConstantNull %23 -%285 = OpConstantComposite %31 %225 %225 %225 %225 -%293 = OpConstantComposite %31 %68 %68 %68 %68 -%294 = OpConstantComposite %31 %138 %138 %138 %138 +%55 = OpTypeFunction %2 +%56 = OpTypePointer Uniform %22 +%58 = OpConstant %5 1 +%59 = OpConstant %10 1.0 +%60 = OpConstantComposite %12 %59 %59 +%61 = OpConstant %10 2.0 +%62 = OpConstantComposite %12 %61 %61 +%63 = OpConstant %10 3.0 +%64 = OpConstantComposite %12 %63 %63 +%65 = OpConstantComposite %21 %60 %62 %64 +%66 = OpConstantComposite %22 %65 +%67 = OpConstant %10 6.0 +%68 = OpConstantComposite %12 %67 %67 +%69 = OpConstant %10 5.0 +%70 = OpConstantComposite %12 %69 %69 +%71 = OpConstant %10 4.0 +%72 = OpConstantComposite %12 %71 %71 +%73 = OpConstantComposite %21 %68 %70 %72 +%74 = OpConstant %10 9.0 +%75 = OpConstantComposite %12 %74 %74 +%76 = OpConstant %10 90.0 +%77 = OpConstantComposite %12 %76 %76 +%78 = OpConstant %10 10.0 +%79 = OpConstant %10 20.0 +%80 = OpConstant %10 30.0 +%81 = OpConstant %10 40.0 +%83 = OpTypePointer Function %5 +%85 = OpTypePointer Function %22 +%89 = OpTypePointer Uniform %21 +%92 = OpTypePointer Uniform %12 +%98 = OpTypePointer Uniform %10 +%99 = OpConstant %3 1 +%114 = OpTypePointer Function %21 +%116 = OpTypePointer Function %12 +%120 = OpTypePointer Function %10 +%131 = OpTypePointer Uniform %26 +%133 = OpConstantNull %25 +%134 = OpConstantComposite %26 %133 +%135 = OpConstant %10 8.0 +%136 = OpConstantComposite %12 %135 %135 +%137 = OpConstant %10 7.0 +%138 = OpConstantComposite %12 %137 %137 +%139 = OpConstantComposite %24 %136 %138 %68 %70 +%142 = OpTypePointer Function %26 +%146 = OpTypePointer Uniform %25 +%149 = OpTypePointer Uniform %24 +%171 = OpTypePointer Function %25 +%173 = OpTypePointer Function %24 +%189 = OpTypeFunction %10 %27 +%195 = OpTypeFunction %10 %29 +%202 = OpTypeFunction %2 %33 +%203 = OpConstant %3 42 +%208 = OpTypeFunction %2 %35 +%209 = OpConstantComposite %31 %59 %59 %59 %59 +%210 = OpConstantComposite %31 %61 %61 %61 %61 +%211 = OpConstantComposite %34 %209 %210 +%215 = OpTypePointer Input %3 +%214 = OpVariable %215 Input +%218 = OpTypePointer Output %31 +%217 = OpVariable %218 Output +%221 = OpTypePointer StorageBuffer %23 +%224 = OpConstant %10 0.0 +%225 = OpConstant %3 3 +%226 = OpConstant %5 3 +%227 = OpConstant %5 4 +%228 = OpConstant %5 5 +%229 = OpConstant %5 42 +%230 = OpConstantNull %29 +%233 = OpTypePointer Function %32 +%234 = OpConstantNull %32 +%239 = OpTypePointer StorageBuffer %8 +%242 = OpTypePointer StorageBuffer %18 +%243 = OpConstant %3 4 +%246 = OpTypePointer StorageBuffer %9 +%247 = OpTypePointer StorageBuffer %10 +%250 = OpTypePointer StorageBuffer %19 +%253 = OpTypePointer StorageBuffer %7 +%254 = OpTypePointer StorageBuffer %5 +%266 = OpTypeVector %5 4 +%272 = OpVariable %218 Output +%275 = OpConstantComposite %9 %224 %224 %224 +%276 = OpConstantComposite %9 %59 %59 %59 +%277 = OpConstantComposite %9 %61 %61 %61 +%278 = OpConstantComposite %9 %63 %63 %63 +%279 = OpConstantComposite %8 %275 %276 %277 %278 +%280 = OpConstantComposite %17 %36 %36 +%281 = OpConstantComposite %17 %99 %99 +%282 = OpConstantComposite %18 %280 %281 +%283 = OpConstantNull %23 +%284 = OpConstantComposite %31 %224 %224 %224 %224 +%292 = OpConstant %3 33 +%293 = OpConstantComposite %31 %67 %67 %67 %67 +%294 = OpConstantComposite %31 %137 %137 %137 %137 %295 = OpConstantComposite %34 %293 %294 -%298 = OpConstantNull %3 -%300 = OpTypePointer Input %4 -%299 = OpVariable %300 Input -%302 = OpConstantNull %4 -%304 = OpTypeBool -%303 = OpTypeVector %304 3 -%309 = OpConstant %3 264 -%55 = OpFunction %2 None %56 -%54 = OpLabel -%83 = OpVariable %84 Function %59 -%85 = OpVariable %86 Function %67 -%58 = OpAccessChain %57 %44 %36 -OpBranch %87 -%87 = OpLabel -%88 = OpLoad %5 %83 -%89 = OpISub %5 %88 %59 -OpStore %83 %89 -%91 = OpAccessChain %90 %58 %36 -%92 = OpLoad %21 %91 -%94 = OpAccessChain %93 %58 %36 %36 -%95 = OpLoad %12 %94 -%96 = OpLoad %5 %83 -%97 = OpAccessChain %93 %58 %36 %96 -%98 = OpLoad %12 %97 -%101 = OpAccessChain %99 %58 %36 %36 %100 -%102 = OpLoad %10 %101 -%103 = OpLoad %5 %83 -%104 = OpAccessChain %99 %58 %36 %36 %103 -%105 = OpLoad %10 %104 -%106 = OpLoad %5 %83 -%107 = OpAccessChain %99 %58 %36 %106 %100 -%108 = OpLoad %10 %107 -%109 = OpLoad %5 %83 -%110 = OpLoad %5 %83 -%111 = OpAccessChain %99 %58 %36 %109 %110 -%112 = OpLoad %10 %111 -%113 = OpLoad %5 %83 -%114 = OpIAdd %5 %113 %59 -OpStore %83 %114 -%116 = OpAccessChain %115 %85 %36 -OpStore %116 %74 -%118 = OpAccessChain %117 %85 %36 %36 -OpStore %118 %76 -%119 = OpLoad %5 %83 -%120 = OpAccessChain %117 %85 %36 %119 -OpStore %120 %78 -%122 = OpAccessChain %121 %85 %36 %36 %100 -OpStore %122 %79 -%123 = OpLoad %5 %83 -%124 = OpAccessChain %121 %85 %36 %36 %123 -OpStore %124 %80 -%125 = OpLoad %5 %83 -%126 = OpAccessChain %121 %85 %36 %125 %100 -OpStore %126 %81 -%127 = OpLoad %5 %83 -%128 = OpLoad %5 %83 -%129 = OpAccessChain %121 %85 %36 %127 %128 -OpStore %129 %82 +%54 = OpFunction %2 None %55 +%53 = OpLabel +%82 = OpVariable %83 Function %58 +%84 = OpVariable %85 Function %66 +%57 = OpAccessChain %56 %44 %36 +OpBranch %86 +%86 = OpLabel +%87 = OpLoad %5 %82 +%88 = OpISub %5 %87 %58 +OpStore %82 %88 +%90 = OpAccessChain %89 %57 %36 +%91 = OpLoad %21 %90 +%93 = OpAccessChain %92 %57 %36 %36 +%94 = OpLoad %12 %93 +%95 = OpLoad %5 %82 +%96 = OpAccessChain %92 %57 %36 %95 +%97 = OpLoad %12 %96 +%100 = OpAccessChain %98 %57 %36 %36 %99 +%101 = OpLoad %10 %100 +%102 = OpLoad %5 %82 +%103 = OpAccessChain %98 %57 %36 %36 %102 +%104 = OpLoad %10 %103 +%105 = OpLoad %5 %82 +%106 = OpAccessChain %98 %57 %36 %105 %99 +%107 = OpLoad %10 %106 +%108 = OpLoad %5 %82 +%109 = OpLoad %5 %82 +%110 = OpAccessChain %98 %57 %36 %108 %109 +%111 = OpLoad %10 %110 +%112 = OpLoad %5 %82 +%113 = OpIAdd %5 %112 %58 +OpStore %82 %113 +%115 = OpAccessChain %114 %84 %36 +OpStore %115 %73 +%117 = OpAccessChain %116 %84 %36 %36 +OpStore %117 %75 +%118 = OpLoad %5 %82 +%119 = OpAccessChain %116 %84 %36 %118 +OpStore %119 %77 +%121 = OpAccessChain %120 %84 %36 %36 %99 +OpStore %121 %78 +%122 = OpLoad %5 %82 +%123 = OpAccessChain %120 %84 %36 %36 %122 +OpStore %123 %79 +%124 = OpLoad %5 %82 +%125 = OpAccessChain %120 %84 %36 %124 %99 +OpStore %125 %80 +%126 = OpLoad %5 %82 +%127 = OpLoad %5 %82 +%128 = OpAccessChain %120 %84 %36 %126 %127 +OpStore %128 %81 OpReturn OpFunctionEnd -%131 = OpFunction %2 None %56 -%130 = OpLabel -%141 = OpVariable %84 Function %59 -%142 = OpVariable %143 Function %135 -%133 = OpAccessChain %132 %50 %36 -OpBranch %144 -%144 = OpLabel -%145 = OpLoad %5 %141 -%146 = OpISub %5 %145 %59 -OpStore %141 %146 -%148 = OpAccessChain %147 %133 %36 -%149 = OpLoad %25 %148 -%151 = OpAccessChain %150 %133 %36 %36 -%152 = OpLoad %24 %151 -%153 = OpAccessChain %93 %133 %36 %36 %36 -%154 = OpLoad %12 %153 -%155 = OpLoad %5 %141 -%156 = OpAccessChain %93 %133 %36 %36 %155 -%157 = OpLoad %12 %156 -%158 = OpAccessChain %99 %133 %36 %36 %36 %100 -%159 = OpLoad %10 %158 -%160 = OpLoad %5 %141 -%161 = OpAccessChain %99 %133 %36 %36 %36 %160 -%162 = OpLoad %10 %161 -%163 = OpLoad %5 %141 -%164 = OpAccessChain %99 %133 %36 %36 %163 %100 -%165 = OpLoad %10 %164 -%166 = OpLoad %5 %141 -%167 = OpLoad %5 %141 -%168 = OpAccessChain %99 %133 %36 %36 %166 %167 -%169 = OpLoad %10 %168 -%170 = OpLoad %5 %141 -%171 = OpIAdd %5 %170 %59 -OpStore %141 %171 -%173 = OpAccessChain %172 %142 %36 -OpStore %173 %134 -%175 = OpAccessChain %174 %142 %36 %36 -OpStore %175 %140 -%176 = OpAccessChain %117 %142 %36 %36 %36 -OpStore %176 %76 -%177 = OpLoad %5 %141 -%178 = OpAccessChain %117 %142 %36 %36 %177 +%130 = OpFunction %2 None %55 +%129 = OpLabel +%140 = OpVariable %83 Function %58 +%141 = OpVariable %142 Function %134 +%132 = OpAccessChain %131 %50 %36 +OpBranch %143 +%143 = OpLabel +%144 = OpLoad %5 %140 +%145 = OpISub %5 %144 %58 +OpStore %140 %145 +%147 = OpAccessChain %146 %132 %36 +%148 = OpLoad %25 %147 +%150 = OpAccessChain %149 %132 %36 %36 +%151 = OpLoad %24 %150 +%152 = OpAccessChain %92 %132 %36 %36 %36 +%153 = OpLoad %12 %152 +%154 = OpLoad %5 %140 +%155 = OpAccessChain %92 %132 %36 %36 %154 +%156 = OpLoad %12 %155 +%157 = OpAccessChain %98 %132 %36 %36 %36 %99 +%158 = OpLoad %10 %157 +%159 = OpLoad %5 %140 +%160 = OpAccessChain %98 %132 %36 %36 %36 %159 +%161 = OpLoad %10 %160 +%162 = OpLoad %5 %140 +%163 = OpAccessChain %98 %132 %36 %36 %162 %99 +%164 = OpLoad %10 %163 +%165 = OpLoad %5 %140 +%166 = OpLoad %5 %140 +%167 = OpAccessChain %98 %132 %36 %36 %165 %166 +%168 = OpLoad %10 %167 +%169 = OpLoad %5 %140 +%170 = OpIAdd %5 %169 %58 +OpStore %140 %170 +%172 = OpAccessChain %171 %141 %36 +OpStore %172 %133 +%174 = OpAccessChain %173 %141 %36 %36 +OpStore %174 %139 +%175 = OpAccessChain %116 %141 %36 %36 %36 +OpStore %175 %75 +%176 = OpLoad %5 %140 +%177 = OpAccessChain %116 %141 %36 %36 %176 +OpStore %177 %77 +%178 = OpAccessChain %120 %141 %36 %36 %36 %99 OpStore %178 %78 -%179 = OpAccessChain %121 %142 %36 %36 %36 %100 -OpStore %179 %79 -%180 = OpLoad %5 %141 -%181 = OpAccessChain %121 %142 %36 %36 %36 %180 -OpStore %181 %80 -%182 = OpLoad %5 %141 -%183 = OpAccessChain %121 %142 %36 %36 %182 %100 -OpStore %183 %81 -%184 = OpLoad %5 %141 -%185 = OpLoad %5 %141 -%186 = OpAccessChain %121 %142 %36 %36 %184 %185 -OpStore %186 %82 +%179 = OpLoad %5 %140 +%180 = OpAccessChain %120 %141 %36 %36 %36 %179 +OpStore %180 %79 +%181 = OpLoad %5 %140 +%182 = OpAccessChain %120 %141 %36 %36 %181 %99 +OpStore %182 %80 +%183 = OpLoad %5 %140 +%184 = OpLoad %5 %140 +%185 = OpAccessChain %120 %141 %36 %36 %183 %184 +OpStore %185 %81 OpReturn OpFunctionEnd -%189 = OpFunction %10 None %190 -%188 = OpFunctionParameter %27 -%187 = OpLabel -OpBranch %191 -%191 = OpLabel -%192 = OpLoad %10 %188 -OpReturnValue %192 +%188 = OpFunction %10 None %189 +%187 = OpFunctionParameter %27 +%186 = OpLabel +OpBranch %190 +%190 = OpLabel +%191 = OpLoad %10 %187 +OpReturnValue %191 OpFunctionEnd -%195 = OpFunction %10 None %196 -%194 = OpFunctionParameter %29 -%193 = OpLabel -OpBranch %197 -%197 = OpLabel -%198 = OpCompositeExtract %28 %194 4 -%199 = OpCompositeExtract %10 %198 9 -OpReturnValue %199 +%194 = OpFunction %10 None %195 +%193 = OpFunctionParameter %29 +%192 = OpLabel +OpBranch %196 +%196 = OpLabel +%197 = OpCompositeExtract %28 %193 4 +%198 = OpCompositeExtract %10 %197 9 +OpReturnValue %198 OpFunctionEnd -%202 = OpFunction %2 None %203 -%201 = OpFunctionParameter %33 -%200 = OpLabel -OpBranch %205 +%201 = OpFunction %2 None %202 +%200 = OpFunctionParameter %33 +%199 = OpLabel +OpBranch %204 +%204 = OpLabel +OpStore %200 %203 +OpReturn +OpFunctionEnd +%207 = OpFunction %2 None %208 +%206 = OpFunctionParameter %35 %205 = OpLabel -OpStore %201 %204 +OpBranch %212 +%212 = OpLabel +OpStore %206 %211 OpReturn OpFunctionEnd -%208 = OpFunction %2 None %209 -%207 = OpFunctionParameter %35 -%206 = OpLabel -OpBranch %213 +%219 = OpFunction %2 None %55 %213 = OpLabel -OpStore %207 %212 +%231 = OpVariable %27 Function %224 +%232 = OpVariable %233 Function %234 +%216 = OpLoad %3 %214 +%220 = OpAccessChain %56 %44 %36 +%222 = OpAccessChain %221 %47 %36 +%223 = OpAccessChain %131 %50 %36 +OpBranch %235 +%235 = OpLabel +%236 = OpLoad %10 %231 +OpStore %231 %59 +%237 = OpFunctionCall %2 %54 +%238 = OpFunctionCall %2 %130 +%240 = OpAccessChain %239 %42 %36 +%241 = OpLoad %8 %240 +%244 = OpAccessChain %242 %42 %243 +%245 = OpLoad %18 %244 +%248 = OpAccessChain %247 %42 %36 %225 %36 +%249 = OpLoad %10 %248 +%251 = OpArrayLength %3 %42 5 +%252 = OpISub %3 %251 %14 +%255 = OpAccessChain %254 %42 %30 %252 %36 +%256 = OpLoad %5 %255 +%257 = OpLoad %23 %222 +%258 = OpFunctionCall %10 %188 %231 +%259 = OpConvertFToS %5 %249 +%260 = OpCompositeConstruct %32 %256 %259 %226 %227 %228 +OpStore %232 %260 +%261 = OpIAdd %3 %216 %99 +%262 = OpAccessChain %83 %232 %261 +OpStore %262 %229 +%263 = OpAccessChain %83 %232 %216 +%264 = OpLoad %5 %263 +%265 = OpFunctionCall %10 %194 %230 +%267 = OpCompositeConstruct %266 %264 %264 %264 %264 +%268 = OpConvertSToF %31 %267 +%269 = OpMatrixTimesVector %9 %241 %268 +%270 = OpCompositeConstruct %31 %269 %61 +OpStore %217 %270 OpReturn OpFunctionEnd -%220 = OpFunction %2 None %56 -%214 = OpLabel -%232 = OpVariable %27 Function %225 -%233 = OpVariable %234 Function %235 -%217 = OpLoad %3 %215 -%221 = OpAccessChain %57 %44 %36 -%223 = OpAccessChain %222 %47 %36 -%224 = OpAccessChain %132 %50 %36 -OpBranch %236 -%236 = OpLabel -%237 = OpLoad %10 %232 -OpStore %232 %60 -%238 = OpFunctionCall %2 %55 -%239 = OpFunctionCall %2 %131 -%241 = OpAccessChain %240 %42 %36 -%242 = OpLoad %8 %241 -%245 = OpAccessChain %243 %42 %244 -%246 = OpLoad %18 %245 -%249 = OpAccessChain %248 %42 %36 %226 %36 -%250 = OpLoad %10 %249 -%252 = OpArrayLength %3 %42 5 -%253 = OpISub %3 %252 %14 -%256 = OpAccessChain %255 %42 %30 %253 %36 -%257 = OpLoad %5 %256 -%258 = OpLoad %23 %223 -%259 = OpFunctionCall %10 %189 %232 -%260 = OpConvertFToS %5 %250 -%261 = OpCompositeConstruct %32 %257 %260 %227 %228 %229 -OpStore %233 %261 -%262 = OpIAdd %3 %217 %100 -%263 = OpAccessChain %84 %233 %262 -OpStore %263 %230 -%264 = OpAccessChain %84 %233 %217 -%265 = OpLoad %5 %264 -%266 = OpFunctionCall %10 %195 %231 -%268 = OpCompositeConstruct %267 %265 %265 %265 %265 -%269 = OpConvertSToF %31 %268 -%270 = OpMatrixTimesVector %9 %242 %269 -%271 = OpCompositeConstruct %31 %270 %62 -OpStore %218 %271 +%273 = OpFunction %2 None %55 +%271 = OpLabel +%274 = OpAccessChain %221 %47 %36 +OpBranch %285 +%285 = OpLabel +%286 = OpAccessChain %247 %42 %36 %99 %14 +OpStore %286 %59 +%287 = OpAccessChain %239 %42 %36 +OpStore %287 %279 +%288 = OpAccessChain %242 %42 %243 +OpStore %288 %282 +%289 = OpAccessChain %254 %42 %30 %99 %36 +OpStore %289 %58 +OpStore %274 %283 +OpStore %272 %284 OpReturn OpFunctionEnd -%274 = OpFunction %2 None %56 -%272 = OpLabel -%275 = OpAccessChain %222 %47 %36 -OpBranch %286 -%286 = OpLabel -%287 = OpAccessChain %248 %42 %36 %100 %14 -OpStore %287 %60 -%288 = OpAccessChain %240 %42 %36 -OpStore %288 %280 -%289 = OpAccessChain %243 %42 %244 -OpStore %289 %283 -%290 = OpAccessChain %255 %42 %30 %100 %36 -OpStore %290 %59 -OpStore %275 %284 -OpStore %273 %285 -OpReturn -OpFunctionEnd -%292 = OpFunction %2 None %56 -%291 = OpLabel -%296 = OpVariable %35 Function %295 -OpBranch %297 -%297 = OpLabel -%301 = OpLoad %4 %299 -%305 = OpIEqual %303 %301 %302 -%306 = OpAll %304 %305 -OpSelectionMerge %307 None -OpBranchConditional %306 %308 %307 -%308 = OpLabel -OpStore %53 %298 -OpBranch %307 -%307 = OpLabel -OpControlBarrier %14 %14 %309 -OpBranch %310 -%310 = OpLabel -%311 = OpFunctionCall %2 %202 %53 -%312 = OpFunctionCall %2 %208 %296 +%291 = OpFunction %2 None %55 +%290 = OpLabel +%296 = OpVariable %33 Function %292 +%297 = OpVariable %35 Function %295 +OpBranch %298 +%298 = OpLabel +%299 = OpFunctionCall %2 %201 %296 +%300 = OpFunctionCall %2 %207 %297 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl index de9863887..e6904bd62 100644 --- a/tests/out/wgsl/access.wgsl +++ b/tests/out/wgsl/access.wgsl @@ -34,7 +34,6 @@ var baz: Baz; var qux: vec2; @group(0) @binding(3) var nested_mat_cx2_: MatCx2InArray; -var val: u32; fn test_matrix_within_struct_accesses() { var idx: i32 = 1; @@ -117,7 +116,7 @@ fn test_arr_as_arg(a: array, 5>) -> f32 { return a[4][9]; } -fn assign_through_ptr_fn(p: ptr) { +fn assign_through_ptr_fn(p: ptr) { (*p) = 42u; return; } @@ -162,6 +161,7 @@ fn foo_frag() -> @location(0) vec4 { @compute @workgroup_size(1, 1, 1) fn assign_through_ptr() { + var val: u32 = 33u; var arr: array, 2> = array, 2>(vec4(6.0), vec4(7.0)); assign_through_ptr_fn((&val)); diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs index 90785d4f2..10dcd5406 100644 --- a/tests/wgsl-errors.rs +++ b/tests/wgsl-errors.rs @@ -1065,7 +1065,7 @@ fn invalid_functions() { }) } - // Pointers of these storage classes cannot be passed as arguments. + // Pointers of these address spaces cannot be passed as arguments. check_validation! { "fn unacceptable_ptr_space(arg: ptr>) { }": Err(naga::valid::ValidationError::Function { @@ -1079,7 +1079,6 @@ fn invalid_functions() { }) if function_name == "unacceptable_ptr_space" && argument_name == "arg" } - check_validation! { "fn unacceptable_ptr_space(arg: ptr) { }": Err(naga::valid::ValidationError::Function { @@ -1093,6 +1092,19 @@ fn invalid_functions() { }) if function_name == "unacceptable_ptr_space" && argument_name == "arg" } + check_validation! { + "fn unacceptable_ptr_space(arg: ptr) { }": + Err(naga::valid::ValidationError::Function { + name: function_name, + source: naga::valid::FunctionError::InvalidArgumentPointerSpace { + index: 0, + name: argument_name, + space: naga::AddressSpace::WorkGroup, + }, + .. + }) + if function_name == "unacceptable_ptr_space" && argument_name == "arg" + } check_validation! { " From 7ee474b4a5d5658147d9bba4858c5fdfd4f29ccf Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 2 Oct 2023 20:33:24 +0200 Subject: [PATCH 2178/2212] [spv-in] remove duplicated capabilities --- src/front/spv/mod.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 7116925d0..0da11ad43 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -63,8 +63,6 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::ImageCubeArray, spirv::Capability::ImageMSArray, spirv::Capability::StorageImageExtendedFormats, - spirv::Capability::Sampled1D, - spirv::Capability::SampledCubeArray, spirv::Capability::Int8, spirv::Capability::Int16, spirv::Capability::Int64, From 2f6a32f5f997ffdccf8d99d4a78e03d2fb84116f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 2 Oct 2023 20:34:50 +0200 Subject: [PATCH 2179/2212] [spv-in] remove `spirv::Capability::InterpolationFunction` as we don't support the `InterpolateAtCentroid`, `InterpolateAtSample`, or `InterpolateAtOffset` `GLSL.std.450` extended instructions --- src/front/spv/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 0da11ad43..d5fea6e35 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -54,7 +54,6 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::CullDistance, spirv::Capability::SampleRateShading, spirv::Capability::DerivativeControl, - spirv::Capability::InterpolationFunction, spirv::Capability::Matrix, spirv::Capability::ImageQuery, spirv::Capability::Sampled1D, From de9913f4760eaa407ac4ce0e3ae980d964297a1e Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Tue, 3 Oct 2023 11:57:21 +0200 Subject: [PATCH 2180/2212] [spv-in] remove `spirv::Capability::ImageMSArray` as we don't support multisampled storage textures at all --- src/front/spv/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index d5fea6e35..b5feb7320 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -60,7 +60,6 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Image1D, spirv::Capability::SampledCubeArray, spirv::Capability::ImageCubeArray, - spirv::Capability::ImageMSArray, spirv::Capability::StorageImageExtendedFormats, spirv::Capability::Int8, spirv::Capability::Int16, From 5a0fb630da5ccdb3aab0830bd7c9dbecc70c6be5 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 2 Oct 2023 21:08:02 +0200 Subject: [PATCH 2181/2212] [valid] add `Capabilities::CUBE_ARRAY_TEXTURES` --- src/valid/mod.rs | 6 ++++-- src/valid/type.rs | 10 +++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/valid/mod.rs b/src/valid/mod.rs index 454d9739c..f593b8753 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -113,14 +113,16 @@ bitflags::bitflags! { const MULTISAMPLED_SHADING = 0x800; /// Support for ray queries and acceleration structures. const RAY_QUERY = 0x1000; - /// Support for generating two sources for blending from fragement shaders + /// Support for generating two sources for blending from fragement shaders. const DUAL_SOURCE_BLENDING = 0x2000; + /// Support for arrayed cube textures. + const CUBE_ARRAY_TEXTURES = 0x4000; } } impl Default for Capabilities { fn default() -> Self { - Self::MULTISAMPLED_SHADING + Self::MULTISAMPLED_SHADING | Self::CUBE_ARRAY_TEXTURES } } diff --git a/src/valid/type.rs b/src/valid/type.rs index 64f770833..4e766b43b 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -559,9 +559,17 @@ impl super::Validator { ti } - Ti::Image { .. } | Ti::Sampler { .. } => { + Ti::Image { + dim, + arrayed, + class: _, + } => { + if arrayed && matches!(dim, crate::ImageDimension::Cube) { + self.require_type_capability(Capabilities::CUBE_ARRAY_TEXTURES)?; + } TypeInfo::new(TypeFlags::ARGUMENT, Alignment::ONE) } + Ti::Sampler { .. } => TypeInfo::new(TypeFlags::ARGUMENT, Alignment::ONE), Ti::AccelerationStructure => { self.require_type_capability(Capabilities::RAY_QUERY)?; TypeInfo::new(TypeFlags::ARGUMENT, Alignment::ONE) From 4b7a555e9f434c8110b450d786c03091fe83f234 Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 2 Oct 2023 17:33:18 +0200 Subject: [PATCH 2182/2212] [glsl-in] disable modf & frexp --- src/front/glsl/builtins.rs | 58 ++------------------------------------ 1 file changed, 2 insertions(+), 56 deletions(-) diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index bf7559ee2..c68370645 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -1408,62 +1408,8 @@ fn inject_common_builtin( declaration.overloads.push(module.add_builtin(args, fun)) } } - "modf" | "frexp" => { - // bits layout - // bit 0 through 1 - dims - for bits in 0..0b100 { - let size = match bits { - 0b00 => None, - 0b01 => Some(VectorSize::Bi), - 0b10 => Some(VectorSize::Tri), - _ => Some(VectorSize::Quad), - }; - - let ty = module.types.insert( - Type { - name: None, - inner: match size { - Some(size) => TypeInner::Vector { - size, - kind: Sk::Float, - width: float_width, - }, - None => TypeInner::Scalar { - kind: Sk::Float, - width: float_width, - }, - }, - }, - Span::default(), - ); - - let parameters = vec![ty, ty]; - - let fun = match name { - "modf" => MacroCall::MathFunction(MathFunction::Modf), - "frexp" => MacroCall::MathFunction(MathFunction::Frexp), - _ => unreachable!(), - }; - - declaration.overloads.push(Overload { - parameters, - parameters_info: vec![ - ParameterInfo { - qualifier: ParameterQualifier::In, - depth: false, - }, - ParameterInfo { - qualifier: ParameterQualifier::Out, - depth: false, - }, - ], - kind: FunctionKind::Macro(fun), - defined: false, - internal: true, - void: false, - }) - } - } + // TODO: https://github.com/gfx-rs/naga/issues/2526 + // "modf" | "frexp" => { ... } "cross" => { let args = vec![ TypeInner::Vector { From cf113bdb53a59dbd6fba56f0b18c26ae189f794b Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 2 Oct 2023 17:35:41 +0200 Subject: [PATCH 2183/2212] [spv-in] translate ModfStruct & FrexpStruct to their IR equivalents --- src/front/spv/mod.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index b5feb7320..083205a45 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -2949,7 +2949,7 @@ impl> Frontend { Glo::InverseSqrt => Mf::InverseSqrt, Glo::MatrixInverse => Mf::Inverse, Glo::Determinant => Mf::Determinant, - Glo::Modf => Mf::Modf, + Glo::ModfStruct => Mf::Modf, Glo::FMin | Glo::UMin | Glo::SMin | Glo::NMin => Mf::Min, Glo::FMax | Glo::UMax | Glo::SMax | Glo::NMax => Mf::Max, Glo::FClamp | Glo::UClamp | Glo::SClamp | Glo::NClamp => Mf::Clamp, @@ -2957,7 +2957,7 @@ impl> Frontend { Glo::Step => Mf::Step, Glo::SmoothStep => Mf::SmoothStep, Glo::Fma => Mf::Fma, - Glo::Frexp => Mf::Frexp, //TODO: FrexpStruct? + Glo::FrexpStruct => Mf::Frexp, Glo::Ldexp => Mf::Ldexp, Glo::Length => Mf::Length, Glo::Distance => Mf::Distance, @@ -2978,7 +2978,16 @@ impl> Frontend { Glo::UnpackSnorm2x16 => Mf::Unpack2x16snorm, Glo::FindILsb => Mf::FindLsb, Glo::FindUMsb | Glo::FindSMsb => Mf::FindMsb, - _ => return Err(Error::UnsupportedExtInst(inst_id)), + // TODO: https://github.com/gfx-rs/naga/issues/2526 + Glo::Modf | Glo::Frexp => return Err(Error::UnsupportedExtInst(inst_id)), + Glo::IMix + | Glo::PackDouble2x32 + | Glo::UnpackDouble2x32 + | Glo::InterpolateAtCentroid + | Glo::InterpolateAtSample + | Glo::InterpolateAtOffset => { + return Err(Error::UnsupportedExtInst(inst_id)) + } }; let arg_count = fun.argument_count(); From e25280df9316434ef7752970016d01a3aede3f17 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 18 Oct 2023 14:50:52 +0200 Subject: [PATCH 2184/2212] [glsl/spv-out] Cull functions that should not be available for a given stage (#2531) --- src/back/glsl/mod.rs | 13 +++++++ src/back/spv/writer.rs | 13 +++++++ tests/in/separate-entry-points.param.ron | 6 ++++ tests/in/separate-entry-points.wgsl | 23 ++++++++++++ ...separate-entry-points.compute.Compute.glsl | 21 +++++++++++ ...parate-entry-points.fragment.Fragment.glsl | 19 ++++++++++ .../spv/separate-entry-points.compute.spvasm | 33 +++++++++++++++++ .../spv/separate-entry-points.fragment.spvasm | 35 +++++++++++++++++++ tests/snapshots.rs | 1 + 9 files changed, 164 insertions(+) create mode 100644 tests/in/separate-entry-points.param.ron create mode 100644 tests/in/separate-entry-points.wgsl create mode 100644 tests/out/glsl/separate-entry-points.compute.Compute.glsl create mode 100644 tests/out/glsl/separate-entry-points.fragment.Fragment.glsl create mode 100644 tests/out/spv/separate-entry-points.compute.spvasm create mode 100644 tests/out/spv/separate-entry-points.fragment.spvasm diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 37d3303c7..c6f211183 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -827,6 +827,19 @@ impl<'a, W: Write> Writer<'a, W> { let fun_info = &self.info[handle]; + // Skip functions that that are not compatible with this entry point's stage. + // + // When validation is enabled, it rejects modules whose entry points try to call + // incompatible functions, so if we got this far, then any functions incompatible + // with our selected entry point must not be used. + // + // When validation is disabled, `fun_info.available_stages` is always just + // `ShaderStages::all()`, so this will write all functions in the module, and + // the downstream GLSL compiler will catch any problems. + if !fun_info.available_stages.contains(ep_info.available_stages) { + continue; + } + // Write the function self.write_function(back::FunctionType::Function(handle), function, fun_info)?; diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index 2e133985a..24cb14a16 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1952,6 +1952,19 @@ impl Writer { log::info!("Skip function {:?}", ir_function.name); continue; } + + // Skip functions that that are not compatible with this entry point's stage. + // + // When validation is enabled, it rejects modules whose entry points try to call + // incompatible functions, so if we got this far, then any functions incompatible + // with our selected entry point must not be used. + // + // When validation is disabled, `fun_info.available_stages` is always just + // `ShaderStages::all()`, so this will write all functions in the module, and + // the downstream GLSL compiler will catch any problems. + if !info.available_stages.contains(ep_info.available_stages) { + continue; + } } let id = self.write_function(ir_function, info, ir_module, None, &debug_info_inner)?; self.lookup_function.insert(handle, id); diff --git a/tests/in/separate-entry-points.param.ron b/tests/in/separate-entry-points.param.ron new file mode 100644 index 000000000..af0931c11 --- /dev/null +++ b/tests/in/separate-entry-points.param.ron @@ -0,0 +1,6 @@ +( + spv: ( + version: (1, 0), + separate_entry_points: true, + ), +) diff --git a/tests/in/separate-entry-points.wgsl b/tests/in/separate-entry-points.wgsl new file mode 100644 index 000000000..a7ec3b083 --- /dev/null +++ b/tests/in/separate-entry-points.wgsl @@ -0,0 +1,23 @@ +// only available in the fragment stage +fn derivatives() { + let x = dpdx(0.0); + let y = dpdy(0.0); + let width = fwidth(0.0); +} + +// only available in the compute stage +fn barriers() { + storageBarrier(); + workgroupBarrier(); +} + +@fragment +fn fragment() -> @location(0) vec4 { + derivatives(); + return vec4(); +} + +@compute @workgroup_size(1) +fn compute() { + barriers(); +} \ No newline at end of file diff --git a/tests/out/glsl/separate-entry-points.compute.Compute.glsl b/tests/out/glsl/separate-entry-points.compute.Compute.glsl new file mode 100644 index 000000000..869b7ca41 --- /dev/null +++ b/tests/out/glsl/separate-entry-points.compute.Compute.glsl @@ -0,0 +1,21 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + + +void barriers() { + memoryBarrierBuffer(); + barrier(); + memoryBarrierShared(); + barrier(); + return; +} + +void main() { + barriers(); + return; +} + diff --git a/tests/out/glsl/separate-entry-points.fragment.Fragment.glsl b/tests/out/glsl/separate-entry-points.fragment.Fragment.glsl new file mode 100644 index 000000000..9ea32684c --- /dev/null +++ b/tests/out/glsl/separate-entry-points.fragment.Fragment.glsl @@ -0,0 +1,19 @@ +#version 310 es + +precision highp float; +precision highp int; + +layout(location = 0) out vec4 _fs2p_location0; + +void derivatives() { + float x = dFdx(0.0); + float y = dFdy(0.0); + float width = fwidth(0.0); +} + +void main() { + derivatives(); + _fs2p_location0 = vec4(0.0); + return; +} + diff --git a/tests/out/spv/separate-entry-points.compute.spvasm b/tests/out/spv/separate-entry-points.compute.spvasm new file mode 100644 index 000000000..38b7ea417 --- /dev/null +++ b/tests/out/spv/separate-entry-points.compute.spvasm @@ -0,0 +1,33 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 18 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %15 "compute" +OpExecutionMode %15 LocalSize 1 1 1 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%7 = OpTypeFunction %2 +%10 = OpTypeInt 32 0 +%9 = OpConstant %10 2 +%11 = OpConstant %10 1 +%12 = OpConstant %10 72 +%13 = OpConstant %10 264 +%6 = OpFunction %2 None %7 +%5 = OpLabel +OpBranch %8 +%8 = OpLabel +OpControlBarrier %9 %11 %12 +OpControlBarrier %9 %9 %13 +OpReturn +OpFunctionEnd +%15 = OpFunction %2 None %7 +%14 = OpLabel +OpBranch %16 +%16 = OpLabel +%17 = OpFunctionCall %2 %6 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/out/spv/separate-entry-points.fragment.spvasm b/tests/out/spv/separate-entry-points.fragment.spvasm new file mode 100644 index 000000000..e29ce8f15 --- /dev/null +++ b/tests/out/spv/separate-entry-points.fragment.spvasm @@ -0,0 +1,35 @@ +; SPIR-V +; Version: 1.0 +; Generator: rspirv +; Bound: 20 +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %16 "fragment" %14 +OpExecutionMode %16 OriginUpperLeft +OpDecorate %14 Location 0 +%2 = OpTypeVoid +%4 = OpTypeFloat 32 +%3 = OpTypeVector %4 4 +%7 = OpTypeFunction %2 +%8 = OpConstant %4 0.0 +%15 = OpTypePointer Output %3 +%14 = OpVariable %15 Output +%17 = OpConstantNull %3 +%6 = OpFunction %2 None %7 +%5 = OpLabel +OpBranch %9 +%9 = OpLabel +%10 = OpDPdx %4 %8 +%11 = OpDPdy %4 %8 +%12 = OpFwidth %4 %8 +OpReturn +OpFunctionEnd +%16 = OpFunction %2 None %7 +%13 = OpLabel +OpBranch %18 +%18 = OpLabel +%19 = OpFunctionCall %2 %6 +OpStore %14 %17 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/tests/snapshots.rs b/tests/snapshots.rs index 2bc7f4544..c3455dd86 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -781,6 +781,7 @@ fn convert_wgsl() { "const-exprs", Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL, ), + ("separate-entry-points", Targets::SPIRV | Targets::GLSL), ]; for &(name, targets) in inputs.iter() { From 5b65f11e3cb491707f9cdbb78388972367feb52d Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Wed, 18 Oct 2023 15:35:22 +0200 Subject: [PATCH 2185/2212] [refactor] make use of `resolve_type` wherever possible --- src/back/glsl/mod.rs | 46 ++++++++++----------- src/back/hlsl/help.rs | 11 +++-- src/back/hlsl/storage.rs | 2 +- src/back/hlsl/writer.rs | 86 +++++++++++++++------------------------- src/back/mod.rs | 2 +- src/back/msl/writer.rs | 6 +-- 6 files changed, 61 insertions(+), 92 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index c6f211183..60431e986 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -1828,8 +1828,7 @@ impl<'a, W: Write> Writer<'a, W> { // This is where we can generate intermediate constants for some expression types. Statement::Emit(ref range) => { for handle in range.clone() { - let info = &ctx.info[handle]; - let ptr_class = info.ty.inner_with(&self.module.types).pointer_space(); + let ptr_class = ctx.resolve_type(handle, &self.module.types).pointer_space(); let expr_name = if ptr_class.is_some() { // GLSL can't save a pointer-valued expression in a variable, // but we shouldn't ever need to: they should never be named expressions, @@ -1859,7 +1858,7 @@ impl<'a, W: Write> Writer<'a, W> { if let TypeInner::Image { class: crate::ImageClass::Sampled { .. }, .. - } = *ctx.info[image].ty.inner_with(&self.module.types) + } = *ctx.resolve_type(image, &self.module.types) { if let proc::BoundsCheckPolicy::Restrict = self.policies.image_load { write!(self.out, "{level}")?; @@ -2225,7 +2224,7 @@ impl<'a, W: Write> Writer<'a, W> { } => { write!(self.out, "{level}")?; let res_name = format!("{}{}", back::BAKE_PREFIX, result.index()); - let res_ty = ctx.info[result].ty.inner_with(&self.module.types); + let res_ty = ctx.resolve_type(result, &self.module.types); self.write_value_type(res_ty)?; write!(self.out, " {res_name} = ")?; self.named_expressions.insert(result, res_name); @@ -2484,7 +2483,7 @@ impl<'a, W: Write> Writer<'a, W> { level, depth_ref, } => { - let dim = match *ctx.info[image].ty.inner_with(&self.module.types) { + let dim = match *ctx.resolve_type(image, &self.module.types) { TypeInner::Image { dim, .. } => dim, _ => unreachable!(), }; @@ -2545,7 +2544,7 @@ impl<'a, W: Write> Writer<'a, W> { // We need to get the coordinates vector size to later build a vector that's `size + 1` // if `depth_ref` is some, if it isn't a vector we panic as that's not a valid expression - let mut coord_dim = match *ctx.info[coordinate].ty.inner_with(&self.module.types) { + let mut coord_dim = match *ctx.resolve_type(coordinate, &self.module.types) { TypeInner::Vector { size, .. } => size as u8, TypeInner::Scalar { .. } => 1, _ => unreachable!(), @@ -2672,7 +2671,7 @@ impl<'a, W: Write> Writer<'a, W> { use crate::ImageClass; // This will only panic if the module is invalid - let (dim, class) = match *ctx.info[image].ty.inner_with(&self.module.types) { + let (dim, class) = match *ctx.resolve_type(image, &self.module.types) { TypeInner::Image { dim, arrayed: _, @@ -2704,7 +2703,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(image, ctx)?; if let Some(expr) = level { let cast_to_int = matches!( - *ctx.info[expr].ty.inner_with(&self.module.types), + *ctx.resolve_type(expr, &self.module.types), crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, .. @@ -2779,7 +2778,7 @@ impl<'a, W: Write> Writer<'a, W> { let operator_or_fn = match op { crate::UnaryOperator::Negate => "-", crate::UnaryOperator::LogicalNot => { - match *ctx.info[expr].ty.inner_with(&self.module.types) { + match *ctx.resolve_type(expr, &self.module.types) { TypeInner::Vector { .. } => "not", _ => "!", } @@ -2805,8 +2804,8 @@ impl<'a, W: Write> Writer<'a, W> { // implemented as a function call use crate::{BinaryOperator as Bo, ScalarKind as Sk, TypeInner as Ti}; - let left_inner = ctx.info[left].ty.inner_with(&self.module.types); - let right_inner = ctx.info[right].ty.inner_with(&self.module.types); + let left_inner = ctx.resolve_type(left, &self.module.types); + let right_inner = ctx.resolve_type(right, &self.module.types); let function = match (left_inner, right_inner) { (&Ti::Vector { kind, .. }, &Ti::Vector { .. }) => match op { @@ -2935,7 +2934,7 @@ impl<'a, W: Write> Writer<'a, W> { accept, reject, } => { - let cond_ty = ctx.info[condition].ty.inner_with(&self.module.types); + let cond_ty = ctx.resolve_type(condition, &self.module.types); let vec_select = if let TypeInner::Vector { .. } = *cond_ty { true } else { @@ -3025,7 +3024,7 @@ impl<'a, W: Write> Writer<'a, W> { self.write_expr(arg, ctx)?; - match *ctx.info[arg].ty.inner_with(&self.module.types) { + match *ctx.resolve_type(arg, &self.module.types) { crate::TypeInner::Vector { size, .. } => write!( self.out, ", vec{}(0.0), vec{0}(1.0)", @@ -3072,7 +3071,7 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Log2 => "log2", Mf::Pow => "pow", // geometry - Mf::Dot => match *ctx.info[arg].ty.inner_with(&self.module.types) { + Mf::Dot => match *ctx.resolve_type(arg, &self.module.types) { crate::TypeInner::Vector { kind: crate::ScalarKind::Float, .. @@ -3128,7 +3127,7 @@ impl<'a, W: Write> Writer<'a, W> { Mf::Determinant => "determinant", // bits Mf::CountTrailingZeros => { - match *ctx.info[arg].ty.inner_with(&self.module.types) { + match *ctx.resolve_type(arg, &self.module.types) { crate::TypeInner::Vector { size, kind, .. } => { let s = back::vector_size_str(size); if let crate::ScalarKind::Uint = kind { @@ -3158,7 +3157,7 @@ impl<'a, W: Write> Writer<'a, W> { } Mf::CountLeadingZeros => { if self.options.version.supports_integer_functions() { - match *ctx.info[arg].ty.inner_with(&self.module.types) { + match *ctx.resolve_type(arg, &self.module.types) { crate::TypeInner::Vector { size, kind, .. } => { let s = back::vector_size_str(size); @@ -3189,7 +3188,7 @@ impl<'a, W: Write> Writer<'a, W> { _ => unreachable!(), }; } else { - match *ctx.info[arg].ty.inner_with(&self.module.types) { + match *ctx.resolve_type(arg, &self.module.types) { crate::TypeInner::Vector { size, kind, .. } => { let s = back::vector_size_str(size); @@ -3262,7 +3261,7 @@ impl<'a, W: Write> Writer<'a, W> { // Check if the argument is an unsigned integer and return the vector size // in case it's a vector - let maybe_uint_size = match *ctx.info[arg].ty.inner_with(&self.module.types) { + let maybe_uint_size = match *ctx.resolve_type(arg, &self.module.types) { crate::TypeInner::Scalar { kind: crate::ScalarKind::Uint, .. @@ -3349,7 +3348,7 @@ impl<'a, W: Write> Writer<'a, W> { kind: target_kind, convert, } => { - let inner = ctx.info[expr].ty.inner_with(&self.module.types); + let inner = ctx.resolve_type(expr, &self.module.types); match convert { Some(width) => { // this is similar to `write_type`, but with the target kind @@ -3515,7 +3514,7 @@ impl<'a, W: Write> Writer<'a, W> { } // Otherwise write just the expression (and the 1D hack if needed) None => { - let uvec_size = match *ctx.info[coordinate].ty.inner_with(&self.module.types) { + let uvec_size = match *ctx.resolve_type(coordinate, &self.module.types) { TypeInner::Scalar { kind: crate::ScalarKind::Uint, .. @@ -3563,7 +3562,7 @@ impl<'a, W: Write> Writer<'a, W> { // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20) // This will only panic if the module is invalid - let dim = match *ctx.info[image].ty.inner_with(&self.module.types) { + let dim = match *ctx.resolve_type(image, &self.module.types) { TypeInner::Image { dim, .. } => dim, _ => unreachable!(), }; @@ -3626,7 +3625,7 @@ impl<'a, W: Write> Writer<'a, W> { // in bounds (`ReadZeroSkipWrite`) or make them a valid texel (`Restrict`). // This will only panic if the module is invalid - let (dim, class) = match *ctx.info[image].ty.inner_with(&self.module.types) { + let (dim, class) = match *ctx.resolve_type(image, &self.module.types) { TypeInner::Image { dim, arrayed: _, @@ -3891,8 +3890,7 @@ impl<'a, W: Write> Writer<'a, W> { } } - let base_ty_res = &ctx.info[named].ty; - let resolved = base_ty_res.inner_with(&self.module.types); + let resolved = ctx.resolve_type(named, &self.module.types); write!(self.out, " {name}")?; if let TypeInner::Array { base, size, .. } = *resolved { diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs index 2d725514b..fcb9949fe 100644 --- a/src/back/hlsl/help.rs +++ b/src/back/hlsl/help.rs @@ -244,7 +244,7 @@ impl<'a, W: Write> super::Writer<'a, W> { const MIP_LEVEL_PARAM: &str = "mip_level"; // Write function return type and name - let ret_ty = func_ctx.info[expr_handle].ty.inner_with(&module.types); + let ret_ty = func_ctx.resolve_type(expr_handle, &module.types); self.write_value_type(module, ret_ty)?; write!(self.out, " ")?; self.write_wrapped_image_query_function_name(wiq)?; @@ -891,7 +891,7 @@ impl<'a, W: Write> super::Writer<'a, W> { } } crate::Expression::ImageQuery { image, query } => { - let wiq = match *func_ctx.info[image].ty.inner_with(&module.types) { + let wiq = match *func_ctx.resolve_type(image, &module.types) { crate::TypeInner::Image { dim, arrayed, @@ -912,9 +912,8 @@ impl<'a, W: Write> super::Writer<'a, W> { // Write `WrappedConstructor` for structs that are loaded from `AddressSpace::Storage` // since they will later be used by the fn `write_storage_load` crate::Expression::Load { pointer } => { - let pointer_space = func_ctx.info[pointer] - .ty - .inner_with(&module.types) + let pointer_space = func_ctx + .resolve_type(pointer, &module.types) .pointer_space(); if let Some(crate::AddressSpace::Storage { .. }) = pointer_space { @@ -1016,7 +1015,7 @@ impl<'a, W: Write> super::Writer<'a, W> { if extra == 0 { self.write_expr(module, coordinate, func_ctx)?; } else { - let num_coords = match *func_ctx.info[coordinate].ty.inner_with(&module.types) { + let num_coords = match *func_ctx.resolve_type(coordinate, &module.types) { crate::TypeInner::Scalar { .. } => 1, crate::TypeInner::Vector { size, .. } => size as usize, _ => unreachable!(), diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs index d4eeefe3e..1e02e9e50 100644 --- a/src/back/hlsl/storage.rs +++ b/src/back/hlsl/storage.rs @@ -466,7 +466,7 @@ impl super::Writer<'_, W> { } }; - let parent = match *func_ctx.info[next_expr].ty.inner_with(&module.types) { + let parent = match *func_ctx.resolve_type(next_expr, &module.types) { crate::TypeInner::Pointer { base, .. } => match module.types[base].inner { crate::TypeInner::Struct { ref members, .. } => Parent::Struct(members), crate::TypeInner::Array { stride, .. } => Parent::Array { stride }, diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs index 5286eb6dd..f26604476 100644 --- a/src/back/hlsl/writer.rs +++ b/src/back/hlsl/writer.rs @@ -1320,8 +1320,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match *stmt { Statement::Emit(ref range) => { for handle in range.clone() { - let info = &func_ctx.info[handle]; - let ptr_class = info.ty.inner_with(&module.types).pointer_space(); + let ptr_class = func_ctx.resolve_type(handle, &module.types).pointer_space(); let expr_name = if ptr_class.is_some() { // HLSL can't save a pointer-valued expression in a variable, // but we shouldn't ever need to: they should never be named expressions, @@ -1441,7 +1440,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Statement::Store { pointer, value } => { - let ty_inner = func_ctx.info[pointer].ty.inner_with(&module.types); + let ty_inner = func_ctx.resolve_type(pointer, &module.types); if let Some(crate::AddressSpace::Storage { .. }) = ty_inner.pointer_space() { let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; self.write_storage_store( @@ -1467,8 +1466,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } let get_members = |expr: Handle| { - let base_ty_res = &func_ctx.info[expr].ty; - let resolved = base_ty_res.inner_with(&module.types); + let resolved = func_ctx.resolve_type(expr, &module.types); match *resolved { TypeInner::Pointer { base, .. } => match module.types[base].inner { TypeInner::Struct { ref members, .. } => Some(members), @@ -1484,7 +1482,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let mut current_expr = pointer; for _ in 0..3 { - let resolved = func_ctx.info[current_expr].ty.inner_with(&module.types); + let resolved = func_ctx.resolve_type(current_expr, &module.types); match (resolved, &func_ctx.expressions[current_expr]) { ( @@ -1634,7 +1632,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let mut current_expr = pointer; for _ in 0..3 { - let resolved = func_ctx.info[current_expr].ty.inner_with(&module.types); + let resolved = func_ctx.resolve_type(current_expr, &module.types); match (resolved, &func_ctx.expressions[current_expr]) { ( &TypeInner::ValuePointer { @@ -1726,8 +1724,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }) = get_inner_matrix_of_struct_array_member( module, pointer, func_ctx, false, ) { - let mut resolved = - func_ctx.info[pointer].ty.inner_with(&module.types); + let mut resolved = func_ctx.resolve_type(pointer, &module.types); if let TypeInner::Pointer { base, .. } = *resolved { resolved = &module.types[base].inner; } @@ -1854,9 +1851,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; // Validation ensures that `pointer` has a `Pointer` type. - let pointer_space = func_ctx.info[pointer] - .ty - .inner_with(&module.types) + let pointer_space = func_ctx + .resolve_type(pointer, &module.types) .pointer_space() .unwrap(); @@ -2163,11 +2159,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { op: crate::BinaryOperator::Multiply, left, right, - } if func_ctx.info[left].ty.inner_with(&module.types).is_matrix() - || func_ctx.info[right] - .ty - .inner_with(&module.types) - .is_matrix() => + } if func_ctx.resolve_type(left, &module.types).is_matrix() + || func_ctx.resolve_type(right, &module.types).is_matrix() => { // We intentionally flip the order of multiplication as our matrices are implicitly transposed. write!(self.out, "mul(")?; @@ -2196,10 +2189,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { op: crate::BinaryOperator::Modulo, left, right, - } if func_ctx.info[left] - .ty - .inner_with(&module.types) - .scalar_kind() + } if func_ctx.resolve_type(left, &module.types).scalar_kind() == Some(crate::ScalarKind::Float) => { write!(self.out, "fmod(")?; @@ -2216,10 +2206,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; } Expression::Access { base, index } => { - if let Some(crate::AddressSpace::Storage { .. }) = func_ctx.info[expr] - .ty - .inner_with(&module.types) - .pointer_space() + if let Some(crate::AddressSpace::Storage { .. }) = + func_ctx.resolve_type(expr, &module.types).pointer_space() { // do nothing, the chain is written on `Load`/`Store` } else { @@ -2243,8 +2231,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { return Ok(()); } - let base_ty_res = &func_ctx.info[base].ty; - let resolved = base_ty_res.inner_with(&module.types); + let resolved = func_ctx.resolve_type(base, &module.types); let non_uniform_qualifier = match *resolved { TypeInner::BindingArray { .. } => { @@ -2268,10 +2255,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Expression::AccessIndex { base, index } => { - if let Some(crate::AddressSpace::Storage { .. }) = func_ctx.info[expr] - .ty - .inner_with(&module.types) - .pointer_space() + if let Some(crate::AddressSpace::Storage { .. }) = + func_ctx.resolve_type(expr, &module.types).pointer_space() { // do nothing, the chain is written on `Load`/`Store` } else { @@ -2450,7 +2435,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { dim, arrayed, class, - } = *func_ctx.info[image].ty.inner_with(&module.types) + } = *func_ctx.resolve_type(image, &module.types) { let wrapped_image_query = WrappedImageQuery { dim, @@ -2499,8 +2484,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; // return x component if return type is scalar - if let TypeInner::Scalar { .. } = *func_ctx.info[expr].ty.inner_with(&module.types) - { + if let TypeInner::Scalar { .. } = *func_ctx.resolve_type(expr, &module.types) { write!(self.out, ".x")?; } } @@ -2515,9 +2499,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])? } Expression::Load { pointer } => { - match func_ctx.info[pointer] - .ty - .inner_with(&module.types) + match func_ctx + .resolve_type(pointer, &module.types) .pointer_space() { Some(crate::AddressSpace::Storage { .. }) => { @@ -2541,7 +2524,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ) .or_else(|| get_inner_matrix_of_global_uniform(module, pointer, func_ctx)) { - let mut resolved = func_ctx.info[pointer].ty.inner_with(&module.types); + let mut resolved = func_ctx.resolve_type(pointer, &module.types); if let TypeInner::Pointer { base, .. } = *resolved { resolved = &module.types[base].inner; } @@ -2581,7 +2564,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { kind, convert, } => { - let inner = func_ctx.info[expr].ty.inner_with(&module.types); + let inner = func_ctx.resolve_type(expr, &module.types); match convert { Some(dst_width) => { match *inner { @@ -2956,11 +2939,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")? } Function::MissingIntOverload(fun_name) => { - let scalar_kind = &func_ctx.info[arg] - .ty - .inner_with(&module.types) - .scalar_kind(); - if let Some(ScalarKind::Sint) = *scalar_kind { + let scalar_kind = func_ctx.resolve_type(arg, &module.types).scalar_kind(); + if let Some(ScalarKind::Sint) = scalar_kind { write!(self.out, "asint({fun_name}(asuint(")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, ")))")?; @@ -2971,11 +2951,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Function::MissingIntReturnType(fun_name) => { - let scalar_kind = &func_ctx.info[arg] - .ty - .inner_with(&module.types) - .scalar_kind(); - if let Some(ScalarKind::Sint) = *scalar_kind { + let scalar_kind = func_ctx.resolve_type(arg, &module.types).scalar_kind(); + if let Some(ScalarKind::Sint) = scalar_kind { write!(self.out, "asint({fun_name}(")?; self.write_expr(module, arg, func_ctx)?; write!(self.out, "))")?; @@ -2986,7 +2963,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Function::CountTrailingZeros => { - match *func_ctx.info[arg].ty.inner_with(&module.types) { + match *func_ctx.resolve_type(arg, &module.types) { TypeInner::Vector { size, kind, .. } => { let s = match size { crate::VectorSize::Bi => ".xx", @@ -3021,7 +2998,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { return Ok(()); } Function::CountLeadingZeros => { - match *func_ctx.info[arg].ty.inner_with(&module.types) { + match *func_ctx.resolve_type(arg, &module.types) { TypeInner::Vector { size, kind, .. } => { let s = match size { crate::VectorSize::Bi => ".xx", @@ -3209,8 +3186,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - let base_ty_res = &ctx.info[named].ty; - let resolved = base_ty_res.inner_with(&module.types); + let resolved = ctx.resolve_type(named, &module.types); write!(self.out, " {name}")?; // If rhs is a array type, we should write array size @@ -3287,7 +3263,7 @@ pub(super) fn get_inner_matrix_of_struct_array_member( let mut current_base = base; loop { - let mut resolved = func_ctx.info[current_base].ty.inner_with(&module.types); + let mut resolved = func_ctx.resolve_type(current_base, &module.types); if let TypeInner::Pointer { base, .. } = *resolved { resolved = &module.types[base].inner; }; @@ -3344,7 +3320,7 @@ fn get_inner_matrix_of_global_uniform( let mut current_base = base; loop { - let mut resolved = func_ctx.info[current_base].ty.inner_with(&module.types); + let mut resolved = func_ctx.resolve_type(current_base, &module.types); if let TypeInner::Pointer { base, .. } = *resolved { resolved = &module.types[base].inner; }; diff --git a/src/back/mod.rs b/src/back/mod.rs index 1314e14d7..8100b930e 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -135,7 +135,7 @@ impl FunctionCtx<'_> { }; } crate::Expression::AccessIndex { base, index } => { - match *self.info[base].ty.inner_with(&module.types) { + match *self.resolve_type(base, &module.types) { crate::TypeInner::Struct { ref members, .. } => { if let Some(crate::Binding::BuiltIn(bi)) = members[index as usize].binding diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs index 91315eb5b..09f7b1c73 100644 --- a/src/back/msl/writer.rs +++ b/src/back/msl/writer.rs @@ -2624,11 +2624,7 @@ impl Writer { )?; } - let info = &context.expression.info[handle]; - let ptr_class = info - .ty - .inner_with(&context.expression.module.types) - .pointer_space(); + let ptr_class = context.expression.resolve_type(handle).pointer_space(); let expr_name = if ptr_class.is_some() { None // don't bake pointer expressions (just yet) } else if let Some(name) = From 860c20046989e4c9cee4a70fa7aaa96dee371bf1 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 14 Sep 2023 14:37:51 -0700 Subject: [PATCH 2186/2212] Give Validator::check_width its own error type, `WidthError`. Later changes will use `check_width` in new functions. Separating out `WidthError` will make it easier to incorporate `check_width`'s results into its new callers'. --- src/valid/type.rs | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/src/valid/type.rs b/src/valid/type.rs index 4e766b43b..c93ae67d7 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -90,8 +90,6 @@ pub enum Disalignment { pub enum TypeError { #[error("Capability {0:?} is required")] MissingCapability(Capabilities), - #[error("The {0:?} scalar width {1} is not supported")] - InvalidWidth(crate::ScalarKind, crate::Bytes), #[error("The {0:?} scalar width {1} is not supported for an atomic")] InvalidAtomicWidth(crate::ScalarKind, crate::Bytes), #[error("Invalid type for pointer target {0:?}")] @@ -126,6 +124,22 @@ pub enum TypeError { }, #[error("Structure types must have at least one member")] EmptyStruct, + #[error(transparent)] + WidthError(#[from] WidthError), +} + +#[derive(Clone, Debug, thiserror::Error)] +pub enum WidthError { + #[error("The {0:?} scalar width {1} is not supported")] + Invalid(crate::ScalarKind, crate::Bytes), + #[error("Using `{name}` values requires the `naga::valid::Capabilities::{flag}` flag")] + MissingCapability { + name: &'static str, + flag: &'static str, + }, + + #[error("64-bit integers are not yet supported")] + Unsupported64Bit, } // Only makes sense if `flags.contains(HOST_SHAREABLE)` @@ -209,16 +223,21 @@ impl super::Validator { } } - pub(super) fn check_width( + pub(super) const fn check_width( &self, kind: crate::ScalarKind, width: crate::Bytes, - ) -> Result<(), TypeError> { + ) -> Result<(), WidthError> { let good = match kind { crate::ScalarKind::Bool => width == crate::BOOL_WIDTH, crate::ScalarKind::Float => { if width == 8 { - self.require_type_capability(Capabilities::FLOAT64)?; + if !self.capabilities.contains(Capabilities::FLOAT64) { + return Err(WidthError::MissingCapability { + name: "f64", + flag: "FLOAT64", + }); + } true } else { width == 4 @@ -229,7 +248,7 @@ impl super::Validator { if good { Ok(()) } else { - Err(TypeError::InvalidWidth(kind, width)) + Err(WidthError::Invalid(kind, width)) } } From 1bb84aef0bbf6ef6baf37c4dc961c76f6bce61e0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 18 Oct 2023 17:35:06 -0700 Subject: [PATCH 2187/2212] rename validate_literal to check_literal_value --- src/proc/constant_evaluator.rs | 2 +- src/valid/expression.rs | 6 +++--- src/valid/mod.rs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/proc/constant_evaluator.rs b/src/proc/constant_evaluator.rs index d2604ae1c..208274397 100644 --- a/src/proc/constant_evaluator.rs +++ b/src/proc/constant_evaluator.rs @@ -1231,7 +1231,7 @@ impl<'a> ConstantEvaluator<'a> { // expression at a time, `Compose` expressions can only refer to other // expressions, and `ZeroValue` expressions are always okay. if let Expression::Literal(literal) = expr { - crate::valid::validate_literal(literal)?; + crate::valid::check_literal_value(literal)?; } if let Some(FunctionLocalData { diff --git a/src/valid/expression.rs b/src/valid/expression.rs index ef14de713..765c8e271 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -188,7 +188,7 @@ impl super::Validator { match gctx.const_expressions[handle] { E::Literal(literal) => { - validate_literal(literal)?; + check_literal_value(literal)?; } E::Constant(_) | E::ZeroValue(_) => {} E::Compose { ref components, ty } => { @@ -343,7 +343,7 @@ impl super::Validator { ShaderStages::all() } E::Literal(literal) => { - validate_literal(literal)?; + check_literal_value(literal)?; ShaderStages::all() } E::Constant(_) | E::ZeroValue(_) => ShaderStages::all(), @@ -1565,7 +1565,7 @@ impl super::Validator { } } -pub fn validate_literal(literal: crate::Literal) -> Result<(), LiteralError> { +pub fn check_literal_value(literal: crate::Literal) -> Result<(), LiteralError> { let is_nan = match literal { crate::Literal::F64(v) => v.is_nan(), crate::Literal::F32(v) => v.is_nan(), diff --git a/src/valid/mod.rs b/src/valid/mod.rs index f593b8753..2fb0a7277 100644 --- a/src/valid/mod.rs +++ b/src/valid/mod.rs @@ -24,7 +24,7 @@ use std::ops; use crate::span::{AddSpan as _, WithSpan}; pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements}; pub use compose::ComposeError; -pub use expression::{validate_literal, LiteralError}; +pub use expression::{check_literal_value, LiteralError}; pub use expression::{ConstExpressionError, ExpressionError}; pub use function::{CallError, FunctionError, LocalVariableError}; pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; From 334f7453660169251d5ec576ebfc3b9b0625ca79 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 18 Oct 2023 17:35:41 -0700 Subject: [PATCH 2188/2212] Make validation reject 64-bit floating-point literals. Make expression validation and constant expression validation reject `Literal` expressions containing `F64` literals unless the `FLOAT64` capability is enabled. --- src/valid/expression.rs | 17 +++++++++++++++-- src/valid/type.rs | 1 + 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 765c8e271..f77844b4b 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -140,6 +140,8 @@ pub enum ConstExpressionError { Type(#[from] ResolveError), #[error(transparent)] Literal(#[from] LiteralError), + #[error(transparent)] + Width(#[from] super::r#type::WidthError), } #[derive(Clone, Debug, thiserror::Error)] @@ -149,6 +151,8 @@ pub enum LiteralError { NaN, #[error("Float literal is infinite")] Infinity, + #[error(transparent)] + Width(#[from] super::r#type::WidthError), } #[cfg(feature = "validate")] @@ -188,7 +192,7 @@ impl super::Validator { match gctx.const_expressions[handle] { E::Literal(literal) => { - check_literal_value(literal)?; + self.validate_literal(literal)?; } E::Constant(_) | E::ZeroValue(_) => {} E::Compose { ref components, ty } => { @@ -343,7 +347,7 @@ impl super::Validator { ShaderStages::all() } E::Literal(literal) => { - check_literal_value(literal)?; + self.validate_literal(literal)?; ShaderStages::all() } E::Constant(_) | E::ZeroValue(_) => ShaderStages::all(), @@ -1563,6 +1567,15 @@ impl super::Validator { _ => Err(ExpressionError::ExpectedGlobalVariable), } } + + pub fn validate_literal(&self, literal: crate::Literal) -> Result<(), LiteralError> { + let kind = literal.scalar_kind(); + let width = literal.width(); + self.check_width(kind, width)?; + check_literal_value(literal)?; + + Ok(()) + } } pub fn check_literal_value(literal: crate::Literal) -> Result<(), LiteralError> { diff --git a/src/valid/type.rs b/src/valid/type.rs index c93ae67d7..a5321178c 100644 --- a/src/valid/type.rs +++ b/src/valid/type.rs @@ -129,6 +129,7 @@ pub enum TypeError { } #[derive(Clone, Debug, thiserror::Error)] +#[cfg_attr(test, derive(PartialEq))] pub enum WidthError { #[error("The {0:?} scalar width {1} is not supported")] Invalid(crate::ScalarKind, crate::Bytes), From af26d77ce436c85efb660d36c73c2de16c37cb6f Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Wed, 18 Oct 2023 17:56:49 -0700 Subject: [PATCH 2189/2212] [wgsl-in] Abstract out ExpressionContext::as_const_evaluator. --- src/front/wgsl/lower/mod.rs | 41 +++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index c883732e8..b9d536cf5 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -346,31 +346,36 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { } } + fn as_const_evaluator(&mut self) -> ConstantEvaluator { + match self.expr_type { + ExpressionContextType::Runtime(ref mut rctx) => ConstantEvaluator::for_wgsl_function( + self.module, + rctx.naga_expressions, + rctx.expression_constness, + rctx.emitter, + rctx.block, + ), + ExpressionContextType::Constant => ConstantEvaluator::for_wgsl_module(self.module), + } + } + fn append_expression( &mut self, expr: crate::Expression, span: Span, ) -> Result, Error<'source>> { - match self.expr_type { - ExpressionContextType::Runtime(ref mut rctx) => { - let mut eval = ConstantEvaluator::for_wgsl_function( - self.module, - rctx.naga_expressions, - rctx.expression_constness, - rctx.emitter, - rctx.block, - ); + let mut eval = self.as_const_evaluator(); + match eval.try_eval_and_append(&expr, span) { + Ok(expr) => Ok(expr), - match eval.try_eval_and_append(&expr, span) { - Ok(expr) => Ok(expr), - Err(_) => Ok(rctx.naga_expressions.append(expr, span)), + // `expr` is not a constant expression. This is fine as + // long as we're not building `Module::const_expressions`. + Err(err) => match self.expr_type { + ExpressionContextType::Runtime(ref mut rctx) => { + Ok(rctx.naga_expressions.append(expr, span)) } - } - ExpressionContextType::Constant => { - let mut eval = ConstantEvaluator::for_wgsl_module(self.module); - eval.try_eval_and_append(&expr, span) - .map_err(|e| Error::ConstantEvaluatorError(e, span)) - } + ExpressionContextType::Constant => Err(Error::ConstantEvaluatorError(err, span)), + }, } } From 29ca53148d217bbb69ef52c17f46e101da79e06b Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Thu, 19 Oct 2023 18:08:54 +0200 Subject: [PATCH 2190/2212] fix OOB typifier indexing --- src/front/wgsl/lower/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index b9d536cf5..6ff520e95 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -1707,6 +1707,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { crate::TypeInner::Scalar { kind, .. } => kind, crate::TypeInner::Vector { kind, .. } => kind, _ => { + ctx.grow_types(expr)?; let ty = &ctx.typifier()[expr]; return Err(Error::BadTypeCast { from_type: ctx.format_type_resolution(ty), From 19209b67d26c4cb231c1b5464dbf712539ab7a5a Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Thu, 19 Oct 2023 22:20:02 +0200 Subject: [PATCH 2191/2212] [wgsl-in] consolidate type resolution logic in a few macros (#2571) * [wgsl-in] consolidate type resolution logic in a few macros * rename + docs * reorder macros (avoids doc linking not working) --- src/front/wgsl/lower/construction.rs | 6 +- src/front/wgsl/lower/mod.rs | 129 ++++++++++++++++----------- 2 files changed, 79 insertions(+), 56 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 59d7b1743..ec3a33870 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -152,8 +152,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { [component] => { let span = ctx.ast_expressions.get_span(component); let component = self.expression(component, ctx.reborrow())?; - ctx.grow_types(component)?; - let ty = &ctx.typifier()[component]; + let ty = super::resolve!(ctx, component); ComponentsHandle::One { component, @@ -178,8 +177,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ) .collect(); - ctx.grow_types(component)?; - let ty = &ctx.typifier()[component]; + let ty = super::resolve!(ctx, component); ComponentsHandle::Many { components, diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 6ff520e95..ae178cb70 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -13,6 +13,59 @@ use crate::{Arena, FastHashMap, FastIndexMap, Handle, Span}; mod construction; +/// Resolves the inner type of a given expression. +/// +/// Expects a &mut [`ExpressionContext`] and a [`Handle`]. +/// +/// Returns a &[`crate::TypeInner`]. +/// +/// Ideally, we would simply have a function that takes a `&mut ExpressionContext` +/// and returns a `&TypeResolution`. Unfortunately, this leads the borrow checker +/// to conclude that the mutable borrow lasts for as long as we are using the +/// `&TypeResolution`, so we can't use the `ExpressionContext` for anything else - +/// like, say, resolving another operand's type. Using a macro that expands to +/// two separate calls, only the first of which needs a `&mut`, +/// lets the borrow checker see that the mutable borrow is over. +macro_rules! resolve_inner { + ($ctx:ident, $expr:expr) => {{ + $ctx.grow_types($expr)?; + $ctx.typifier()[$expr].inner_with(&$ctx.module.types) + }}; +} + +/// Resolves the inner types of two given expressions. +/// +/// Expects a &mut [`ExpressionContext`] and two [`Handle`]s. +/// +/// Returns a tuple containing two &[`crate::TypeInner`]. +/// +/// See the documentation of [`resolve_inner!`] for why this macro is necessary. +macro_rules! resolve_inner_binary { + ($ctx:ident, $left:expr, $right:expr) => {{ + $ctx.grow_types($left)?; + $ctx.grow_types($right)?; + ( + $ctx.typifier()[$left].inner_with(&$ctx.module.types), + $ctx.typifier()[$right].inner_with(&$ctx.module.types), + ) + }}; +} + +/// Resolves the type of a given expression. +/// +/// Expects a &mut [`ExpressionContext`] and a [`Handle`]. +/// +/// Returns a &[`TypeResolution`]. +/// +/// See the documentation of [`resolve_inner!`] for why this macro is necessary. +macro_rules! resolve { + ($ctx:ident, $expr:expr) => {{ + $ctx.grow_types($expr)?; + &$ctx.typifier()[$expr] + }}; +} +pub(super) use resolve; + /// State for constructing a `crate::Module`. pub struct GlobalContext<'source, 'temp, 'out> { /// The `TranslationUnit`'s expressions arena. @@ -460,15 +513,13 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { /// Determine the type of `handle`, and add it to the module's arena. /// - /// If you just need a `TypeInner` for `handle`'s type, use - /// [`grow_types`] and [`resolved_inner`] instead. This function + /// If you just need a `TypeInner` for `handle`'s type, use the + /// [`resolve_inner!`] macro instead. This function /// should only be used when the type of `handle` needs to appear /// in the module's final `Arena`, for example, if you're /// creating a [`LocalVariable`] whose type is inferred from its /// initializer. /// - /// [`grow_types`]: Self::grow_types - /// [`resolved_inner`]: Self::resolved_inner /// [`LocalVariable`]: crate::LocalVariable fn register_type( &mut self, @@ -498,12 +549,11 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { /// return a shared reference to the resulting `TypeResolution`: /// the shared reference would extend the mutable borrow, and you /// wouldn't be able to use `self` for anything else. Instead, you - /// should call `grow_types` to cover the handles you need, and - /// then use `self.typifier[handle]` or - /// [`self.resolved_inner(handle)`] to get at their resolutions. + /// should use [`register_type`] or one of [`resolve!`], + /// [`resolve_inner!`] or [`resolve_inner_binary!`]. /// /// [`self.typifier`]: ExpressionContext::typifier - /// [`self.resolved_inner(handle)`]: ExpressionContext::resolved_inner + /// [`register_type`]: Self::register_type /// [`Typifier`]: Typifier fn grow_types( &mut self, @@ -533,17 +583,12 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { Ok(self) } - fn resolved_inner(&self, handle: Handle) -> &crate::TypeInner { - self.typifier()[handle].inner_with(&self.module.types) - } - fn image_data( &mut self, image: Handle, span: Span, ) -> Result<(crate::ImageClass, bool), Error<'source>> { - self.grow_types(image)?; - match *self.resolved_inner(image) { + match *resolve_inner!(self, image) { crate::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), _ => Err(Error::BadTexture(span)), } @@ -584,9 +629,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { | crate::BinaryOperator::Divide | crate::BinaryOperator::Modulo ) { - self.grow_types(*left)?.grow_types(*right)?; - - match (self.resolved_inner(*left), self.resolved_inner(*right)) { + match resolve_inner_binary!(self, *left, *right) { (&crate::TypeInner::Vector { size, .. }, &crate::TypeInner::Scalar { .. }) => { *right = self.append_expression( crate::Expression::Splat { @@ -1146,11 +1189,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let initializer = match v.init { Some(init) => { - let initializer = - self.expression(init, ctx.as_expression(block, &mut emitter))?; - ctx.as_expression(block, &mut emitter) - .grow_types(initializer)?; - Some(initializer) + Some(self.expression(init, ctx.as_expression(block, &mut emitter))?) } None => None, }; @@ -1161,8 +1200,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let ty = match (explicit_ty, initializer) { (Some(explicit), Some(initializer)) => { - let ctx = ctx.as_expression(block, &mut emitter); - let initializer_ty = ctx.resolved_inner(initializer); + let mut ctx = ctx.as_expression(block, &mut emitter); + let initializer_ty = resolve_inner!(ctx, initializer); if !ctx.module.types[explicit] .inner .equivalent(initializer_ty, &ctx.module.types) @@ -1266,9 +1305,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut ectx = ctx.as_expression(block, &mut emitter); let selector = self.expression(selector, ectx.reborrow())?; - ectx.grow_types(selector)?; let uint = - ectx.resolved_inner(selector).scalar_kind() == Some(crate::ScalarKind::Uint); + resolve_inner!(ectx, selector).scalar_kind() == Some(crate::ScalarKind::Uint); block.extend(emitter.finish(ctx.naga_expressions)); let cases = cases @@ -1407,8 +1445,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { self.expression_for_reference(value, ctx.as_expression(block, &mut emitter))?; let mut ectx = ctx.as_expression(block, &mut emitter); - ectx.grow_types(reference.handle)?; - let (kind, width) = match *ectx.resolved_inner(reference.handle) { + let (kind, width) = match *resolve_inner!(ectx, reference.handle) { crate::TypeInner::ValuePointer { size: None, kind, @@ -1553,8 +1590,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // The pointer we dereference must be loaded. let pointer = self.expression(expr, ctx.reborrow())?; - ctx.grow_types(pointer)?; - if ctx.resolved_inner(pointer).pointer_space().is_none() { + if resolve_inner!(ctx, pointer).pointer_space().is_none() { return Err(Error::NotPointer(span)); } @@ -1583,9 +1619,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let expr = self.expression_for_reference(base, ctx.reborrow())?; let index = self.expression(index, ctx.reborrow())?; - ctx.grow_types(expr.handle)?; - let wgsl_pointer = - ctx.resolved_inner(expr.handle).pointer_space().is_some() && !expr.is_reference; + let wgsl_pointer = resolve_inner!(ctx, expr.handle).pointer_space().is_some() + && !expr.is_reference; if wgsl_pointer { return Err(Error::Pointer( @@ -1618,9 +1653,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { is_reference, } = self.expression_for_reference(base, ctx.reborrow())?; - ctx.grow_types(handle)?; let temp_inner; - let (composite, wgsl_pointer) = match *ctx.resolved_inner(handle) { + let (composite, wgsl_pointer) = match *resolve_inner!(ctx, handle) { crate::TypeInner::Pointer { base, .. } => { (&ctx.module.types[base].inner, !is_reference) } @@ -1707,8 +1741,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { crate::TypeInner::Scalar { kind, .. } => kind, crate::TypeInner::Vector { kind, .. } => kind, _ => { - ctx.grow_types(expr)?; - let ty = &ctx.typifier()[expr]; + let ty = resolve!(ctx, expr); return Err(Error::BadTypeCast { from_type: ctx.format_type_resolution(ty), span: ty_span, @@ -1814,9 +1847,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fun, crate::RelationalFunction::All | crate::RelationalFunction::Any ) && { - ctx.grow_types(argument)?; matches!( - ctx.resolved_inner(argument), + resolve_inner!(ctx, argument), &crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, .. @@ -1859,8 +1891,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args.finish()?; if fun == crate::MathFunction::Modf || fun == crate::MathFunction::Frexp { - ctx.grow_types(arg)?; - if let Some((size, width)) = match *ctx.resolved_inner(arg) { + if let Some((size, width)) = match *resolve_inner!(ctx, arg) { crate::TypeInner::Scalar { width, .. } => Some((None, width)), crate::TypeInner::Vector { size, width, .. } => { Some((Some(size), width)) @@ -2005,11 +2036,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let value = args.next()?; let value_span = ctx.ast_expressions.get_span(value); let value = self.expression(value, ctx.reborrow())?; - ctx.grow_types(value)?; args.finish()?; - let expression = match *ctx.resolved_inner(value) { + let expression = match *resolve_inner!(ctx, value) { crate::TypeInner::Scalar { kind, width } => { crate::Expression::AtomicResult { ty: ctx.module.generate_predeclared_type( @@ -2061,8 +2091,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args.finish()?; let pointer = self.expression(expr, ctx.reborrow())?; - ctx.grow_types(pointer)?; - let result_ty = match *ctx.resolved_inner(pointer) { + let result_ty = match *resolve_inner!(ctx, pointer) { crate::TypeInner::Pointer { base, space: crate::AddressSpace::WorkGroup, @@ -2083,7 +2112,6 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, ); - ctx.grow_types(pointer)?; return Ok(Some(result)); } "textureStore" => { @@ -2280,8 +2308,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let span = ctx.ast_expressions.get_span(expr); let pointer = self.expression(expr, ctx.reborrow())?; - ctx.grow_types(pointer)?; - match *ctx.resolved_inner(pointer) { + match *resolve_inner!(ctx, pointer) { crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { crate::TypeInner::Atomic { .. } => Ok(pointer), ref other => { @@ -2361,8 +2388,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let lowered_image_or_component = self.expression(image_or_component, ctx.reborrow())?; - ctx.grow_types(lowered_image_or_component)?; - match *ctx.resolved_inner(lowered_image_or_component) { + match *resolve_inner!(ctx, lowered_image_or_component) { crate::TypeInner::Image { class: crate::ImageClass::Depth { .. }, .. @@ -2683,8 +2709,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let span = ctx.ast_expressions.get_span(expr); let pointer = self.expression(expr, ctx.reborrow())?; - ctx.grow_types(pointer)?; - match *ctx.resolved_inner(pointer) { + match *resolve_inner!(ctx, pointer) { crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { crate::TypeInner::RayQuery => Ok(pointer), ref other => { From 17dfdb93659d6b3340f22ea4659a4e1bf3ca831c Mon Sep 17 00:00:00 2001 From: exrook Date: Sun, 22 Oct 2023 15:25:29 -0400 Subject: [PATCH 2192/2212] fix clippy lints introduced in 1.72 and 1.73 (#2581) fixes: - [non_canonical_clone_impl](https://rust-lang.github.io/rust-clippy/master/index.html#non_canonical_clone_impl) - [non_canonical_partial_ord_impl](https://rust-lang.github.io/rust-clippy/master/index.html#non_canonical_partial_ord_impl) - [redundant_guards](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_guards) --- src/arena.rs | 7 ++----- src/front/wgsl/parse/lexer.rs | 4 +--- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 3f17c5729..a9df06665 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -41,10 +41,7 @@ pub struct Handle { impl Clone for Handle { fn clone(&self) -> Self { - Handle { - index: self.index, - marker: self.marker, - } + *self } } @@ -60,7 +57,7 @@ impl Eq for Handle {} impl PartialOrd for Handle { fn partial_cmp(&self, other: &Self) -> Option { - self.index.partial_cmp(&other.index) + Some(self.cmp(other)) } } diff --git a/src/front/wgsl/parse/lexer.rs b/src/front/wgsl/parse/lexer.rs index 4654d4087..ed273fbbb 100644 --- a/src/front/wgsl/parse/lexer.rs +++ b/src/front/wgsl/parse/lexer.rs @@ -350,9 +350,7 @@ impl<'a> Lexer<'a> { &mut self, ) -> Result<(&'a str, Span), Error<'a>> { match self.next() { - (Token::Word(word), span) if word == "_" => { - Err(Error::InvalidIdentifierUnderscore(span)) - } + (Token::Word("_"), span) => Err(Error::InvalidIdentifierUnderscore(span)), (Token::Word(word), span) if word.starts_with("__") => { Err(Error::ReservedIdentifierPrefix(span)) } From 509ea4c85702ee1d5009eb13301547c77c0c5e58 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Mon, 23 Oct 2023 05:48:18 -0700 Subject: [PATCH 2193/2212] [wgsl-in] Generate no code for trivial vector/matrix construction. (#2576) Do not emit an `Expression::As` conversion for WGSL like `vec3(v)` where `v` is already a `vec3`, or `mat2x3(m)` where `m` is already a 2x3 matrix. This doesn't fix any bugs, but it makes it clearer to the reader of `Lowerer::construct` that no conversion can actually take place in this case. Some snapshots are affected because `As` expressions whose `width` is `None` are bitcast expressions, which the constant evaluator does not yet support. When this commit removes those `As` expressions, the constant evaluator can reduce the expression to a `Literal` or `ZeroValue`, which is then concealed by #2539. --- src/front/wgsl/lower/construction.rs | 29 +++++++++---------- tests/out/glsl/constructors.main.Compute.glsl | 2 -- tests/out/hlsl/constructors.hlsl | 2 -- tests/out/msl/constructors.msl | 2 -- tests/out/spv/constructors.spvasm | 3 +- tests/out/wgsl/constructors.wgsl | 2 -- 6 files changed, 14 insertions(+), 26 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index ec3a33870..43025d024 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -239,20 +239,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ( Components::One { component, - ty_inner: - &crate::TypeInner::Vector { - size: src_size, - kind: src_kind, - .. - }, + ty_inner: &crate::TypeInner::Vector { size: src_size, .. }, .. }, ConcreteConstructor::PartialVector { size: dst_size }, - ) if dst_size == src_size => crate::Expression::As { - expr: component, - kind: src_kind, - convert: None, - }, + ) if dst_size == src_size => { + // This is a trivial conversion: the sizes match, and a Partial + // constructor doesn't specify a scalar type, so nothing can + // possibly happen. + return Ok(component); + } // Matrix conversion (matrix -> matrix) ( @@ -296,11 +292,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { columns: dst_columns, rows: dst_rows, }, - ) if dst_columns == src_columns && dst_rows == src_rows => crate::Expression::As { - expr: component, - kind: crate::ScalarKind::Float, - convert: None, - }, + ) if dst_columns == src_columns && dst_rows == src_rows => { + // This is a trivial conversion: the sizes match, and a Partial + // constructor doesn't specify a scalar type, so nothing can + // possibly happen. + return Ok(component); + } // Vector constructor (splat) - infer type ( diff --git a/tests/out/glsl/constructors.main.Compute.glsl b/tests/out/glsl/constructors.main.Compute.glsl index 8ef0a60ba..4b4b0e71a 100644 --- a/tests/out/glsl/constructors.main.Compute.glsl +++ b/tests/out/glsl/constructors.main.Compute.glsl @@ -34,7 +34,5 @@ void main() { bool ic0_ = bool(false); uvec2 ic4_ = uvec2(0u, 0u); mat2x3 ic5_ = mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); - uvec2 ic6_ = uvec2(0u); - mat2x3 ic7_ = mat2x3(0.0); } diff --git a/tests/out/hlsl/constructors.hlsl b/tests/out/hlsl/constructors.hlsl index 52de162f4..232494fa2 100644 --- a/tests/out/hlsl/constructors.hlsl +++ b/tests/out/hlsl/constructors.hlsl @@ -52,6 +52,4 @@ void main() bool ic0_ = bool((bool)0); uint2 ic4_ = uint2(0u, 0u); float2x3 ic5_ = float2x3(float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0)); - uint2 ic6_ = asuint((uint2)0); - float2x3 ic7_ = asfloat((float2x3)0); } diff --git a/tests/out/msl/constructors.msl b/tests/out/msl/constructors.msl index b3a0ecd89..b29e2468b 100644 --- a/tests/out/msl/constructors.msl +++ b/tests/out/msl/constructors.msl @@ -42,6 +42,4 @@ kernel void main_( bool ic0_ = static_cast(bool {}); metal::uint2 ic4_ = metal::uint2(0u, 0u); metal::float2x3 ic5_ = metal::float2x3(metal::float3(0.0, 0.0, 0.0), metal::float3(0.0, 0.0, 0.0)); - metal::uint2 ic6_ = as_type(metal::uint2 {}); - metal::float2x3 ic7_ = metal::float2x3(metal::float2x3 {}); } diff --git a/tests/out/spv/constructors.spvasm b/tests/out/spv/constructors.spvasm index e8e2e2595..1a481aa95 100644 --- a/tests/out/spv/constructors.spvasm +++ b/tests/out/spv/constructors.spvasm @@ -1,7 +1,7 @@ ; SPIR-V ; Version: 1.1 ; Generator: rspirv -; Bound: 70 +; Bound: 68 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -79,6 +79,5 @@ OpDecorate %17 ArrayStride 4 OpBranch %66 %66 = OpLabel OpStore %63 %47 -%69 = OpCopyObject %20 %62 OpReturn OpFunctionEnd \ No newline at end of file diff --git a/tests/out/wgsl/constructors.wgsl b/tests/out/wgsl/constructors.wgsl index f15bcb6c8..a52fb0021 100644 --- a/tests/out/wgsl/constructors.wgsl +++ b/tests/out/wgsl/constructors.wgsl @@ -29,6 +29,4 @@ fn main() { let ic0_ = bool(bool()); let ic4_ = vec2(0u, 0u); let ic5_ = mat2x3(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0)); - let ic6_ = bitcast>(vec2()); - let ic7_ = mat2x3(mat2x3()); } From 6d4807fc6d10388ab4ebb3809959a0e6a1ec8b84 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 19 Oct 2023 16:52:23 -0700 Subject: [PATCH 2194/2212] [wgsl-in] Delete front::wgsl::parse::ExpressionContext::reborrow. Remove `ExpressionContext::reborrow` in favor of Rust's automatic reborrowing of `&mut` references. Use lifetime elision in more places. --- src/front/wgsl/parse/mod.rs | 285 +++++++++++++++++------------------- 1 file changed, 135 insertions(+), 150 deletions(-) diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 23398e611..431257aff 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -55,31 +55,21 @@ struct ExpressionContext<'input, 'temp, 'out> { } impl<'a> ExpressionContext<'a, '_, '_> { - fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { - ExpressionContext { - expressions: self.expressions, - types: self.types, - local_table: self.local_table, - locals: self.locals, - unresolved: self.unresolved, - } - } - fn parse_binary_op( &mut self, lexer: &mut Lexer<'a>, classifier: impl Fn(Token<'a>) -> Option, mut parser: impl FnMut( &mut Lexer<'a>, - ExpressionContext<'a, '_, '_>, + &mut Self, ) -> Result>, Error<'a>>, ) -> Result>, Error<'a>> { let start = lexer.start_byte_offset(); - let mut accumulator = parser(lexer, self.reborrow())?; + let mut accumulator = parser(lexer, self)?; while let Some(op) = classifier(lexer.peek().0) { let _ = lexer.next(); let left = accumulator; - let right = parser(lexer, self.reborrow())?; + let right = parser(lexer, self)?; accumulator = self.expressions.append( ast::Expression::Binary { op, left, right }, lexer.span_from(start), @@ -157,13 +147,13 @@ impl<'a> BindingParser<'a> { lexer: &mut Lexer<'a>, name: &'a str, name_span: Span, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result<(), Error<'a>> { match name { "location" => { lexer.expect(Token::Paren('('))?; self.location - .set(parser.general_expression(lexer, ctx.reborrow())?, name_span)?; + .set(parser.general_expression(lexer, ctx)?, name_span)?; lexer.expect(Token::Paren(')'))?; } "builtin" => { @@ -258,14 +248,14 @@ impl Parser { fn switch_value<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { if let Token::Word("default") = lexer.peek().0 { let _ = lexer.next(); return Ok(ast::SwitchValue::Default); } - let expr = self.general_expression(lexer, ctx.reborrow())?; + let expr = self.general_expression(lexer, ctx)?; Ok(ast::SwitchValue::Expr(expr)) } @@ -285,7 +275,7 @@ impl Parser { lexer: &mut Lexer<'a>, word: &'a str, span: Span, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { if let Some((kind, width)) = conv::get_scalar_type(word) { return Ok(Some(ast::ConstructorType::Scalar { kind, width })); @@ -509,9 +499,9 @@ impl Parser { } (Token::Paren('<'), ast::ConstructorType::PartialArray) => { lexer.expect_generic_paren('<')?; - let base = self.type_decl(lexer, ctx.reborrow())?; + let base = self.type_decl(lexer, ctx)?; let size = if lexer.skip(Token::Separator(',')) { - let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = self.unary_expression(lexer, ctx)?; ast::ArraySize::Constant(expr) } else { ast::ArraySize::Dynamic @@ -528,7 +518,7 @@ impl Parser { fn arguments<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>>, Error<'a>> { lexer.open_arguments()?; let mut arguments = Vec::new(); @@ -540,7 +530,7 @@ impl Parser { } else if lexer.skip(Token::Paren(')')) { break; } - let arg = self.general_expression(lexer, ctx.reborrow())?; + let arg = self.general_expression(lexer, ctx)?; arguments.push(arg); } @@ -554,7 +544,7 @@ impl Parser { lexer: &mut Lexer<'a>, name: &'a str, name_span: Span, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { assert!(self.rules.last().is_some()); @@ -563,12 +553,12 @@ impl Parser { "bitcast" => { lexer.expect_generic_paren('<')?; let start = lexer.start_byte_offset(); - let to = self.type_decl(lexer, ctx.reborrow())?; + let to = self.type_decl(lexer, ctx)?; let span = lexer.span_from(start); lexer.expect_generic_paren('>')?; lexer.open_arguments()?; - let expr = self.general_expression(lexer, ctx.reborrow())?; + let expr = self.general_expression(lexer, ctx)?; lexer.close_arguments()?; ast::Expression::Bitcast { @@ -579,7 +569,7 @@ impl Parser { } // everything else must be handled later, since they can be hidden by user-defined functions. _ => { - let arguments = self.arguments(lexer, ctx.reborrow())?; + let arguments = self.arguments(lexer, ctx)?; ctx.unresolved.insert(ast::Dependency { ident: name, usage: name_span, @@ -603,7 +593,7 @@ impl Parser { &mut self, name: &'a str, name_span: Span, - ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> ast::IdentExpr<'a> { match ctx.local_table.lookup(name) { Some(&local) => ast::IdentExpr::Local(local), @@ -620,14 +610,14 @@ impl Parser { fn primary_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { self.push_rule_span(Rule::PrimaryExpr, lexer); let expr = match lexer.peek() { (Token::Paren('('), _) => { let _ = lexer.next(); - let expr = self.general_expression(lexer, ctx.reborrow())?; + let expr = self.general_expression(lexer, ctx)?; lexer.expect(Token::Paren(')'))?; self.pop_rule_span(lexer); return Ok(expr); @@ -661,9 +651,9 @@ impl Parser { let start = lexer.start_byte_offset(); let _ = lexer.next(); - if let Some(ty) = self.constructor_type(lexer, word, span, ctx.reborrow())? { + if let Some(ty) = self.constructor_type(lexer, word, span, ctx)? { let ty_span = lexer.span_from(start); - let components = self.arguments(lexer, ctx.reborrow())?; + let components = self.arguments(lexer, ctx)?; ast::Expression::Construct { ty, ty_span, @@ -676,7 +666,7 @@ impl Parser { self.pop_rule_span(lexer); return self.function_call(lexer, word, span, ctx); } else { - let ident = self.ident_expr(word, span, ctx.reborrow()); + let ident = self.ident_expr(word, span, ctx); ast::Expression::Ident(ident) } } @@ -692,7 +682,7 @@ impl Parser { &mut self, span_start: usize, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, expr: Handle>, ) -> Result>, Error<'a>> { let mut expr = expr; @@ -707,7 +697,7 @@ impl Parser { } Token::Paren('[') => { let _ = lexer.next(); - let index = self.general_expression(lexer, ctx.reborrow())?; + let index = self.general_expression(lexer, ctx)?; lexer.expect(Token::Paren(']'))?; ast::Expression::Index { base: expr, index } @@ -726,14 +716,14 @@ impl Parser { fn unary_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { self.push_rule_span(Rule::UnaryExpr, lexer); //TODO: refactor this to avoid backing up let expr = match lexer.peek().0 { Token::Operation('-') => { let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = self.unary_expression(lexer, ctx)?; let expr = ast::Expression::Unary { op: crate::UnaryOperator::Negate, expr, @@ -743,7 +733,7 @@ impl Parser { } Token::Operation('!') => { let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = self.unary_expression(lexer, ctx)?; let expr = ast::Expression::Unary { op: crate::UnaryOperator::LogicalNot, expr, @@ -753,7 +743,7 @@ impl Parser { } Token::Operation('~') => { let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = self.unary_expression(lexer, ctx)?; let expr = ast::Expression::Unary { op: crate::UnaryOperator::BitwiseNot, expr, @@ -763,19 +753,19 @@ impl Parser { } Token::Operation('*') => { let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = self.unary_expression(lexer, ctx)?; let expr = ast::Expression::Deref(expr); let span = self.peek_rule_span(lexer); ctx.expressions.append(expr, span) } Token::Operation('&') => { let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = self.unary_expression(lexer, ctx)?; let expr = ast::Expression::AddrOf(expr); let span = self.peek_rule_span(lexer); ctx.expressions.append(expr, span) } - _ => self.singular_expression(lexer, ctx.reborrow())?, + _ => self.singular_expression(lexer, ctx)?, }; self.pop_rule_span(lexer); @@ -786,12 +776,12 @@ impl Parser { fn singular_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { let start = lexer.start_byte_offset(); self.push_rule_span(Rule::SingularExpr, lexer); - let primary_expr = self.primary_expression(lexer, ctx.reborrow())?; - let singular_expr = self.postfix(start, lexer, ctx.reborrow(), primary_expr)?; + let primary_expr = self.primary_expression(lexer, ctx)?; + let singular_expr = self.postfix(start, lexer, ctx, primary_expr)?; self.pop_rule_span(lexer); Ok(singular_expr) @@ -800,7 +790,7 @@ impl Parser { fn equality_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut context: ExpressionContext<'a, '_, '_>, + context: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { // equality_expression context.parse_binary_op( @@ -811,7 +801,7 @@ impl Parser { _ => None, }, // relational_expression - |lexer, mut context| { + |lexer, context| { context.parse_binary_op( lexer, |token| match token { @@ -822,7 +812,7 @@ impl Parser { _ => None, }, // shift_expression - |lexer, mut context| { + |lexer, context| { context.parse_binary_op( lexer, |token| match token { @@ -835,7 +825,7 @@ impl Parser { _ => None, }, // additive_expression - |lexer, mut context| { + |lexer, context| { context.parse_binary_op( lexer, |token| match token { @@ -846,7 +836,7 @@ impl Parser { _ => None, }, // multiplicative_expression - |lexer, mut context| { + |lexer, context| { context.parse_binary_op( lexer, |token| match token { @@ -876,16 +866,16 @@ impl Parser { fn general_expression<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { - self.general_expression_with_span(lexer, ctx.reborrow()) + self.general_expression_with_span(lexer, ctx) .map(|(expr, _)| expr) } fn general_expression_with_span<'a>( &mut self, lexer: &mut Lexer<'a>, - mut context: ExpressionContext<'a, '_, '_>, + context: &mut ExpressionContext<'a, '_, '_>, ) -> Result<(Handle>, Span), Error<'a>> { self.push_rule_span(Rule::GeneralExpr, lexer); // logical_or_expression @@ -896,7 +886,7 @@ impl Parser { _ => None, }, // logical_and_expression - |lexer, mut context| { + |lexer, context| { context.parse_binary_op( lexer, |token| match token { @@ -904,7 +894,7 @@ impl Parser { _ => None, }, // inclusive_or_expression - |lexer, mut context| { + |lexer, context| { context.parse_binary_op( lexer, |token| match token { @@ -912,7 +902,7 @@ impl Parser { _ => None, }, // exclusive_or_expression - |lexer, mut context| { + |lexer, context| { context.parse_binary_op( lexer, |token| match token { @@ -922,7 +912,7 @@ impl Parser { _ => None, }, // and_expression - |lexer, mut context| { + |lexer, context| { context.parse_binary_op( lexer, |token| match token { @@ -949,7 +939,7 @@ impl Parser { fn variable_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { self.push_rule_span(Rule::VariableDecl, lexer); let mut space = crate::AddressSpace::Handle; @@ -972,10 +962,10 @@ impl Parser { } let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.type_decl(lexer, ctx.reborrow())?; + let ty = self.type_decl(lexer, ctx)?; let init = if lexer.skip(Token::Operation('=')) { - let handle = self.general_expression(lexer, ctx.reborrow())?; + let handle = self.general_expression(lexer, ctx)?; Some(handle) } else { None @@ -995,7 +985,7 @@ impl Parser { fn struct_body<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { let mut members = Vec::new(); @@ -1015,19 +1005,17 @@ impl Parser { match lexer.next_ident_with_span()? { ("size", name_span) => { lexer.expect(Token::Paren('('))?; - let expr = self.general_expression(lexer, ctx.reborrow())?; + let expr = self.general_expression(lexer, ctx)?; lexer.expect(Token::Paren(')'))?; size.set(expr, name_span)?; } ("align", name_span) => { lexer.expect(Token::Paren('('))?; - let expr = self.general_expression(lexer, ctx.reborrow())?; + let expr = self.general_expression(lexer, ctx)?; lexer.expect(Token::Paren(')'))?; align.set(expr, name_span)?; } - (word, word_span) => { - bind_parser.parse(self, lexer, word, word_span, ctx.reborrow())? - } + (word, word_span) => bind_parser.parse(self, lexer, word, word_span, ctx)?, } } @@ -1036,7 +1024,7 @@ impl Parser { let name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let ty = self.type_decl(lexer, ctx.reborrow())?; + let ty = self.type_decl(lexer, ctx)?; ready = lexer.skip(Token::Separator(',')); members.push(ast::StructMember { @@ -1072,7 +1060,7 @@ impl Parser { &mut self, lexer: &mut Lexer<'a>, word: &'a str, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { if let Some((kind, width)) = conv::get_scalar_type(word) { return Ok(Some(ast::Type::Scalar { kind, width })); @@ -1242,9 +1230,9 @@ impl Parser { } "array" => { lexer.expect_generic_paren('<')?; - let base = self.type_decl(lexer, ctx.reborrow())?; + let base = self.type_decl(lexer, ctx)?; let size = if lexer.skip(Token::Separator(',')) { - let size = self.unary_expression(lexer, ctx.reborrow())?; + let size = self.unary_expression(lexer, ctx)?; ast::ArraySize::Constant(size) } else { ast::ArraySize::Dynamic @@ -1255,9 +1243,9 @@ impl Parser { } "binding_array" => { lexer.expect_generic_paren('<')?; - let base = self.type_decl(lexer, ctx.reborrow())?; + let base = self.type_decl(lexer, ctx)?; let size = if lexer.skip(Token::Separator(',')) { - let size = self.unary_expression(lexer, ctx.reborrow())?; + let size = self.unary_expression(lexer, ctx)?; ast::ArraySize::Constant(size) } else { ast::ArraySize::Dynamic @@ -1439,13 +1427,13 @@ impl Parser { fn type_decl<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { self.push_rule_span(Rule::TypeDecl, lexer); let (name, span) = lexer.next_ident_with_span()?; - let ty = match self.type_decl_impl(lexer, name, ctx.reborrow())? { + let ty = match self.type_decl_impl(lexer, name, ctx)? { Some(ty) => ty, None => { ctx.unresolved.insert(ast::Dependency { @@ -1462,11 +1450,11 @@ impl Parser { Ok(handle) } - fn assignment_op_and_rhs<'a, 'out>( + fn assignment_op_and_rhs<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, + ctx: &mut ExpressionContext<'a, '_, '_>, + block: &mut ast::Block<'a>, target: Handle>, span_start: usize, ) -> Result<(), Error<'a>> { @@ -1475,7 +1463,7 @@ impl Parser { let op = lexer.next(); let (op, value) = match op { (Token::Operation('='), _) => { - let value = self.general_expression(lexer, ctx.reborrow())?; + let value = self.general_expression(lexer, ctx)?; (None, value) } (Token::AssignmentOperation(c), _) => { @@ -1494,7 +1482,7 @@ impl Parser { _ => unreachable!(), }; - let value = self.general_expression(lexer, ctx.reborrow())?; + let value = self.general_expression(lexer, ctx)?; (Some(op), value) } token @ (Token::IncrementOperation | Token::DecrementOperation, _) => { @@ -1523,27 +1511,27 @@ impl Parser { } /// Parse an assignment statement (will also parse increment and decrement statements) - fn assignment_statement<'a, 'out>( + fn assignment_statement<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, + ctx: &mut ExpressionContext<'a, '_, '_>, + block: &mut ast::Block<'a>, ) -> Result<(), Error<'a>> { let span_start = lexer.start_byte_offset(); - let target = self.general_expression(lexer, ctx.reborrow())?; + let target = self.general_expression(lexer, ctx)?; self.assignment_op_and_rhs(lexer, ctx, block, target, span_start) } /// Parse a function call statement. /// Expects `ident` to be consumed (not in the lexer). - fn function_statement<'a, 'out>( + fn function_statement<'a>( &mut self, lexer: &mut Lexer<'a>, ident: &'a str, ident_span: Span, span_start: usize, - mut context: ExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, + context: &mut ExpressionContext<'a, '_, '_>, + block: &mut ast::Block<'a>, ) -> Result<(), Error<'a>> { self.push_rule_span(Rule::SingularExpr, lexer); @@ -1551,7 +1539,7 @@ impl Parser { ident, usage: ident_span, }); - let arguments = self.arguments(lexer, context.reborrow())?; + let arguments = self.arguments(lexer, context)?; let span = lexer.span_from(span_start); block.stmts.push(ast::Statement { @@ -1570,11 +1558,11 @@ impl Parser { Ok(()) } - fn function_call_or_assignment_statement<'a, 'out>( + fn function_call_or_assignment_statement<'a>( &mut self, lexer: &mut Lexer<'a>, - mut context: ExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, + context: &mut ExpressionContext<'a, '_, '_>, + block: &mut ast::Block<'a>, ) -> Result<(), Error<'a>> { let span_start = lexer.start_byte_offset(); match lexer.peek() { @@ -1583,29 +1571,24 @@ impl Parser { let cloned = lexer.clone(); let _ = lexer.next(); match lexer.peek() { - (Token::Paren('('), _) => self.function_statement( - lexer, - name, - span, - span_start, - context.reborrow(), - block, - ), + (Token::Paren('('), _) => { + self.function_statement(lexer, name, span, span_start, context, block) + } _ => { *lexer = cloned; - self.assignment_statement(lexer, context.reborrow(), block) + self.assignment_statement(lexer, context, block) } } } - _ => self.assignment_statement(lexer, context.reborrow(), block), + _ => self.assignment_statement(lexer, context, block), } } - fn statement<'a, 'out>( + fn statement<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, + ctx: &mut ExpressionContext<'a, '_, '_>, + block: &mut ast::Block<'a>, ) -> Result<(), Error<'a>> { self.push_rule_span(Rule::Statement, lexer); match lexer.peek() { @@ -1615,7 +1598,7 @@ impl Parser { return Ok(()); } (Token::Paren('{'), _) => { - let (inner, span) = self.block(lexer, ctx.reborrow())?; + let (inner, span) = self.block(lexer, ctx)?; block.stmts.push(ast::Statement { kind: ast::StatementKind::Block(inner), span, @@ -1628,7 +1611,7 @@ impl Parser { "_" => { let _ = lexer.next(); lexer.expect(Token::Operation('='))?; - let expr = self.general_expression(lexer, ctx.reborrow())?; + let expr = self.general_expression(lexer, ctx)?; lexer.expect(Token::Separator(';'))?; ast::StatementKind::Ignore(expr) @@ -1638,13 +1621,13 @@ impl Parser { let name = lexer.next_ident()?; let given_ty = if lexer.skip(Token::Separator(':')) { - let ty = self.type_decl(lexer, ctx.reborrow())?; + let ty = self.type_decl(lexer, ctx)?; Some(ty) } else { None }; lexer.expect(Token::Operation('='))?; - let expr_id = self.general_expression(lexer, ctx.reborrow())?; + let expr_id = self.general_expression(lexer, ctx)?; lexer.expect(Token::Separator(';'))?; let handle = ctx.declare_local(name)?; @@ -1660,14 +1643,14 @@ impl Parser { let name = lexer.next_ident()?; let ty = if lexer.skip(Token::Separator(':')) { - let ty = self.type_decl(lexer, ctx.reborrow())?; + let ty = self.type_decl(lexer, ctx)?; Some(ty) } else { None }; let init = if lexer.skip(Token::Operation('=')) { - let init = self.general_expression(lexer, ctx.reborrow())?; + let init = self.general_expression(lexer, ctx)?; Some(init) } else { None @@ -1686,7 +1669,7 @@ impl Parser { "return" => { let _ = lexer.next(); let value = if lexer.peek().0 != Token::Separator(';') { - let handle = self.general_expression(lexer, ctx.reborrow())?; + let handle = self.general_expression(lexer, ctx)?; Some(handle) } else { None @@ -1696,9 +1679,9 @@ impl Parser { } "if" => { let _ = lexer.next(); - let condition = self.general_expression(lexer, ctx.reborrow())?; + let condition = self.general_expression(lexer, ctx)?; - let accept = self.block(lexer, ctx.reborrow())?.0; + let accept = self.block(lexer, ctx)?.0; let mut elsif_stack = Vec::new(); let mut elseif_span_start = lexer.start_byte_offset(); @@ -1709,12 +1692,12 @@ impl Parser { if !lexer.skip(Token::Word("if")) { // ... else { ... } - break self.block(lexer, ctx.reborrow())?.0; + break self.block(lexer, ctx)?.0; } // ... else if (...) { ... } - let other_condition = self.general_expression(lexer, ctx.reborrow())?; - let other_block = self.block(lexer, ctx.reborrow())?; + let other_condition = self.general_expression(lexer, ctx)?; + let other_block = self.block(lexer, ctx)?; elsif_stack.push((elseif_span_start, other_condition, other_block)); elseif_span_start = lexer.start_byte_offset(); }; @@ -1745,7 +1728,7 @@ impl Parser { } "switch" => { let _ = lexer.next(); - let selector = self.general_expression(lexer, ctx.reborrow())?; + let selector = self.general_expression(lexer, ctx)?; lexer.expect(Token::Paren('{'))?; let mut cases = Vec::new(); @@ -1755,7 +1738,7 @@ impl Parser { (Token::Word("case"), _) => { // parse a list of values let value = loop { - let value = self.switch_value(lexer, ctx.reborrow())?; + let value = self.switch_value(lexer, ctx)?; if lexer.skip(Token::Separator(',')) { if lexer.skip(Token::Separator(':')) { break value; @@ -1771,7 +1754,7 @@ impl Parser { }); }; - let body = self.block(lexer, ctx.reborrow())?.0; + let body = self.block(lexer, ctx)?.0; cases.push(ast::SwitchCase { value, @@ -1781,7 +1764,7 @@ impl Parser { } (Token::Word("default"), _) => { lexer.skip(Token::Separator(':')); - let body = self.block(lexer, ctx.reborrow())?.0; + let body = self.block(lexer, ctx)?.0; cases.push(ast::SwitchCase { value: ast::SwitchValue::Default, body, @@ -1797,13 +1780,13 @@ impl Parser { ast::StatementKind::Switch { selector, cases } } - "loop" => self.r#loop(lexer, ctx.reborrow())?, + "loop" => self.r#loop(lexer, ctx)?, "while" => { let _ = lexer.next(); let mut body = ast::Block::default(); let (condition, span) = lexer.capture_span(|lexer| { - let condition = self.general_expression(lexer, ctx.reborrow())?; + let condition = self.general_expression(lexer, ctx)?; Ok(condition) })?; let mut reject = ast::Block::default(); @@ -1821,7 +1804,7 @@ impl Parser { span, }); - let (block, span) = self.block(lexer, ctx.reborrow())?; + let (block, span) = self.block(lexer, ctx)?; body.stmts.push(ast::Statement { kind: ast::StatementKind::Block(block), span, @@ -1841,9 +1824,11 @@ impl Parser { if !lexer.skip(Token::Separator(';')) { let num_statements = block.stmts.len(); - let (_, span) = lexer.capture_span(|lexer| { - self.statement(lexer, ctx.reborrow(), block) - })?; + let (_, span) = { + let ctx = &mut *ctx; + let block = &mut *block; + lexer.capture_span(|lexer| self.statement(lexer, ctx, block))? + }; if block.stmts.len() != num_statements { match block.stmts.last().unwrap().kind { @@ -1858,7 +1843,7 @@ impl Parser { let mut body = ast::Block::default(); if !lexer.skip(Token::Separator(';')) { let (condition, span) = lexer.capture_span(|lexer| { - let condition = self.general_expression(lexer, ctx.reborrow())?; + let condition = self.general_expression(lexer, ctx)?; lexer.expect(Token::Separator(';'))?; Ok(condition) })?; @@ -1881,13 +1866,13 @@ impl Parser { if !lexer.skip(Token::Paren(')')) { self.function_call_or_assignment_statement( lexer, - ctx.reborrow(), + ctx, &mut continuing, )?; lexer.expect(Token::Paren(')'))?; } - let (block, span) = self.block(lexer, ctx.reborrow())?; + let (block, span) = self.block(lexer, ctx)?; body.stmts.push(ast::Statement { kind: ast::StatementKind::Block(block), span, @@ -1926,7 +1911,7 @@ impl Parser { } // assignment or a function call _ => { - self.function_call_or_assignment_statement(lexer, ctx.reborrow(), block)?; + self.function_call_or_assignment_statement(lexer, ctx, block)?; lexer.expect(Token::Separator(';'))?; self.pop_rule_span(lexer); return Ok(()); @@ -1937,7 +1922,7 @@ impl Parser { block.stmts.push(ast::Statement { kind, span }); } _ => { - self.assignment_statement(lexer, ctx.reborrow(), block)?; + self.assignment_statement(lexer, ctx, block)?; lexer.expect(Token::Separator(';'))?; self.pop_rule_span(lexer); } @@ -1948,7 +1933,7 @@ impl Parser { fn r#loop<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result, Error<'a>> { let _ = lexer.next(); let mut body = ast::Block::default(); @@ -1976,7 +1961,7 @@ impl Parser { // the break if lexer.expect(Token::Word("if"))?; - let condition = self.general_expression(lexer, ctx.reborrow())?; + let condition = self.general_expression(lexer, ctx)?; // Set the condition of the break if to the newly parsed // expression break_if = Some(condition); @@ -1994,7 +1979,7 @@ impl Parser { break; } else { // Otherwise try to parse a statement - self.statement(lexer, ctx.reborrow(), &mut continuing)?; + self.statement(lexer, ctx, &mut continuing)?; } } // Since the continuing block must be the last part of the loop body, @@ -2008,7 +1993,7 @@ impl Parser { break; } // Otherwise try to parse a statement - self.statement(lexer, ctx.reborrow(), &mut body)?; + self.statement(lexer, ctx, &mut body)?; } ctx.local_table.pop_scope(); @@ -2024,7 +2009,7 @@ impl Parser { fn block<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result<(ast::Block<'a>, Span), Error<'a>> { self.push_rule_span(Rule::Block, lexer); @@ -2033,7 +2018,7 @@ impl Parser { lexer.expect(Token::Paren('{'))?; let mut block = ast::Block::default(); while !lexer.skip(Token::Paren('}')) { - self.statement(lexer, ctx.reborrow(), &mut block)?; + self.statement(lexer, ctx, &mut block)?; } ctx.local_table.pop_scope(); @@ -2045,14 +2030,14 @@ impl Parser { fn varying_binding<'a>( &mut self, lexer: &mut Lexer<'a>, - mut ctx: ExpressionContext<'a, '_, '_>, + ctx: &mut ExpressionContext<'a, '_, '_>, ) -> Result>, Error<'a>> { let mut bind_parser = BindingParser::default(); self.push_rule_span(Rule::Attribute, lexer); while lexer.skip(Token::Attribute) { let (word, span) = lexer.next_ident_with_span()?; - bind_parser.parse(self, lexer, word, span, ctx.reborrow())?; + bind_parser.parse(self, lexer, word, span, ctx)?; } let span = self.pop_rule_span(lexer); @@ -2093,12 +2078,12 @@ impl Parser { ExpectedToken::Token(Token::Separator(',')), )); } - let binding = self.varying_binding(lexer, ctx.reborrow())?; + let binding = self.varying_binding(lexer, &mut ctx)?; let param_name = lexer.next_ident()?; lexer.expect(Token::Separator(':'))?; - let param_type = self.type_decl(lexer, ctx.reborrow())?; + let param_type = self.type_decl(lexer, &mut ctx)?; let handle = ctx.declare_local(param_name)?; arguments.push(ast::FunctionArgument { @@ -2111,8 +2096,8 @@ impl Parser { } // read return type let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { - let binding = self.varying_binding(lexer, ctx.reborrow())?; - let ty = self.type_decl(lexer, ctx.reborrow())?; + let binding = self.varying_binding(lexer, &mut ctx)?; + let ty = self.type_decl(lexer, &mut ctx)?; Some(ast::FunctionResult { ty, binding }) } else { None @@ -2122,7 +2107,7 @@ impl Parser { lexer.expect(Token::Paren('{'))?; let mut body = ast::Block::default(); while !lexer.skip(Token::Paren('}')) { - self.statement(lexer, ctx.reborrow(), &mut body)?; + self.statement(lexer, &mut ctx, &mut body)?; } ctx.local_table.pop_scope(); @@ -2170,12 +2155,12 @@ impl Parser { match lexer.next_ident_with_span()? { ("binding", name_span) => { lexer.expect(Token::Paren('('))?; - bind_index.set(self.general_expression(lexer, ctx.reborrow())?, name_span)?; + bind_index.set(self.general_expression(lexer, &mut ctx)?, name_span)?; lexer.expect(Token::Paren(')'))?; } ("group", name_span) => { lexer.expect(Token::Paren('('))?; - bind_group.set(self.general_expression(lexer, ctx.reborrow())?, name_span)?; + bind_group.set(self.general_expression(lexer, &mut ctx)?, name_span)?; lexer.expect(Token::Paren(')'))?; } ("vertex", name_span) => { @@ -2192,7 +2177,7 @@ impl Parser { lexer.expect(Token::Paren('('))?; let mut new_workgroup_size = [None; 3]; for (i, size) in new_workgroup_size.iter_mut().enumerate() { - *size = Some(self.general_expression(lexer, ctx.reborrow())?); + *size = Some(self.general_expression(lexer, &mut ctx)?); match lexer.next() { (Token::Paren(')'), _) => break, (Token::Separator(','), _) if i != 2 => (), @@ -2241,14 +2226,14 @@ impl Parser { (Token::Word("struct"), _) => { let name = lexer.next_ident()?; - let members = self.struct_body(lexer, ctx)?; + let members = self.struct_body(lexer, &mut ctx)?; Some(ast::GlobalDeclKind::Struct(ast::Struct { name, members })) } (Token::Word("alias"), _) => { let name = lexer.next_ident()?; lexer.expect(Token::Operation('='))?; - let ty = self.type_decl(lexer, ctx)?; + let ty = self.type_decl(lexer, &mut ctx)?; lexer.expect(Token::Separator(';'))?; Some(ast::GlobalDeclKind::Type(ast::TypeAlias { name, ty })) } @@ -2256,20 +2241,20 @@ impl Parser { let name = lexer.next_ident()?; let ty = if lexer.skip(Token::Separator(':')) { - let ty = self.type_decl(lexer, ctx.reborrow())?; + let ty = self.type_decl(lexer, &mut ctx)?; Some(ty) } else { None }; lexer.expect(Token::Operation('='))?; - let init = self.general_expression(lexer, ctx)?; + let init = self.general_expression(lexer, &mut ctx)?; lexer.expect(Token::Separator(';'))?; Some(ast::GlobalDeclKind::Const(ast::Const { name, ty, init })) } (Token::Word("var"), _) => { - let mut var = self.variable_decl(lexer, ctx)?; + let mut var = self.variable_decl(lexer, &mut ctx)?; var.binding = binding.take(); Some(ast::GlobalDeclKind::Var(var)) } From 0285bf93885c90e4b71033abe84d5cb69996fbf0 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 19 Oct 2023 17:07:41 -0700 Subject: [PATCH 2195/2212] [wgsl-in] Delete front::wgsl::lower::GlobalContext::reborrow. Remove `GlobalContext::reborrow` in favor of Rust's automatic reborrowing of `&mut` references. --- src/front/wgsl/lower/construction.rs | 4 +- src/front/wgsl/lower/mod.rs | 58 ++++++++++++---------------- 2 files changed, 26 insertions(+), 36 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 43025d024..ab46f1164 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -576,8 +576,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::ConstructorType::PartialArray => ConcreteConstructorHandle::PartialArray, ast::ConstructorType::Array { base, size } => { - let base = self.resolve_ast_type(base, ctx.as_global())?; - let size = self.array_size(size, ctx.as_global())?; + let base = self.resolve_ast_type(base, &mut ctx.as_global())?; + let size = self.array_size(size, &mut ctx.as_global())?; self.layouter.update(ctx.module.to_ctx()).unwrap(); let stride = self.layouter[base].to_stride(); diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index ae178cb70..f6d0cc185 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -86,16 +86,6 @@ pub struct GlobalContext<'source, 'temp, 'out> { } impl<'source> GlobalContext<'source, '_, '_> { - fn reborrow(&mut self) -> GlobalContext<'source, '_, '_> { - GlobalContext { - ast_expressions: self.ast_expressions, - globals: self.globals, - types: self.types, - module: self.module, - const_typifier: self.const_typifier, - } - } - fn as_const(&mut self) -> ExpressionContext<'source, '_, '_> { ExpressionContext { ast_expressions: self.ast_expressions, @@ -917,11 +907,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { match decl.kind { ast::GlobalDeclKind::Fn(ref f) => { - let lowered_decl = self.function(f, span, ctx.reborrow())?; + let lowered_decl = self.function(f, span, &mut ctx)?; ctx.globals.insert(f.name.name, lowered_decl); } ast::GlobalDeclKind::Var(ref v) => { - let ty = self.resolve_ast_type(v.ty, ctx.reborrow())?; + let ty = self.resolve_ast_type(v.ty, &mut ctx)?; let init = v .init @@ -957,7 +947,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let inferred_type = ectx.register_type(init)?; let explicit_ty = - c.ty.map(|ty| self.resolve_ast_type(ty, ctx.reborrow())) + c.ty.map(|ty| self.resolve_ast_type(ty, &mut ctx)) .transpose()?; if let Some(explicit) = explicit_ty { @@ -996,12 +986,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .insert(c.name.name, LoweredGlobalDecl::Const(handle)); } ast::GlobalDeclKind::Struct(ref s) => { - let handle = self.r#struct(s, span, ctx.reborrow())?; + let handle = self.r#struct(s, span, &mut ctx)?; ctx.globals .insert(s.name.name, LoweredGlobalDecl::Type(handle)); } ast::GlobalDeclKind::Type(ref alias) => { - let ty = self.resolve_ast_type(alias.ty, ctx.reborrow())?; + let ty = self.resolve_ast_type(alias.ty, &mut ctx)?; ctx.globals .insert(alias.name.name, LoweredGlobalDecl::Type(ty)); } @@ -1015,7 +1005,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, f: &ast::Function<'source>, span: Span, - mut ctx: GlobalContext<'source, '_, '_>, + ctx: &mut GlobalContext<'source, '_, '_>, ) -> Result> { let mut local_table = FastHashMap::default(); let mut local_variables = Arena::new(); @@ -1027,7 +1017,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .iter() .enumerate() .map(|(i, arg)| { - let ty = self.resolve_ast_type(arg.ty, ctx.reborrow())?; + let ty = self.resolve_ast_type(arg.ty, ctx)?; let expr = expressions .append(crate::Expression::FunctionArgument(i as u32), arg.name.span); local_table.insert(arg.handle, TypedExpression::non_reference(expr)); @@ -1036,7 +1026,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok(crate::FunctionArgument { name: Some(arg.name.name.to_string()), ty, - binding: self.binding(&arg.binding, ty, ctx.reborrow())?, + binding: self.binding(&arg.binding, ty, ctx)?, }) }) .collect::, _>>()?; @@ -1045,10 +1035,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .result .as_ref() .map(|res| { - let ty = self.resolve_ast_type(res.ty, ctx.reborrow())?; + let ty = self.resolve_ast_type(res.ty, ctx)?; Ok(crate::FunctionResult { ty, - binding: self.binding(&res.binding, ty, ctx.reborrow())?, + binding: self.binding(&res.binding, ty, ctx)?, }) }) .transpose()?; @@ -1157,7 +1147,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ctx.expression_constness.force_non_const(value); let explicit_ty = - l.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_global())) + l.ty.map(|ty| self.resolve_ast_type(ty, &mut ctx.as_global())) .transpose()?; if let Some(ty) = explicit_ty { @@ -1195,7 +1185,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let explicit_ty = - v.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_global())) + v.ty.map(|ty| self.resolve_ast_type(ty, &mut ctx.as_global())) .transpose()?; let ty = match (explicit_ty, initializer) { @@ -1735,7 +1725,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::Expression::Bitcast { expr, to, ty_span } => { let expr = self.expression(expr, ctx.reborrow())?; - let to_resolved = self.resolve_ast_type(to, ctx.as_global())?; + let to_resolved = self.resolve_ast_type(to, &mut ctx.as_global())?; let kind = match ctx.module.types[to_resolved].inner { crate::TypeInner::Scalar { kind, .. } => kind, @@ -2486,14 +2476,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, s: &ast::Struct<'source>, span: Span, - mut ctx: GlobalContext<'source, '_, '_>, + ctx: &mut GlobalContext<'source, '_, '_>, ) -> Result, Error<'source>> { let mut offset = 0; let mut struct_alignment = Alignment::ONE; let mut members = Vec::with_capacity(s.members.len()); for member in s.members.iter() { - let ty = self.resolve_ast_type(member.ty, ctx.reborrow())?; + let ty = self.resolve_ast_type(member.ty, ctx)?; self.layouter.update(ctx.module.to_ctx()).unwrap(); @@ -2526,7 +2516,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { member_min_alignment }; - let binding = self.binding(&member.binding, ty, ctx.reborrow())?; + let binding = self.binding(&member.binding, ty, ctx)?; offset = member_alignment.round_up(offset); struct_alignment = struct_alignment.max(member_alignment); @@ -2580,7 +2570,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn array_size( &mut self, size: ast::ArraySize<'source>, - mut ctx: GlobalContext<'source, '_, '_>, + ctx: &mut GlobalContext<'source, '_, '_>, ) -> Result> { Ok(match size { ast::ArraySize::Constant(expr) => { @@ -2609,7 +2599,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn resolve_ast_type( &mut self, handle: Handle>, - mut ctx: GlobalContext<'source, '_, '_>, + ctx: &mut GlobalContext<'source, '_, '_>, ) -> Result, Error<'source>> { let inner = match ctx.types[handle] { ast::Type::Scalar { kind, width } => crate::TypeInner::Scalar { kind, width }, @@ -2627,12 +2617,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }, ast::Type::Atomic { kind, width } => crate::TypeInner::Atomic { kind, width }, ast::Type::Pointer { base, space } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; + let base = self.resolve_ast_type(base, ctx)?; crate::TypeInner::Pointer { base, space } } ast::Type::Array { base, size } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; - let size = self.array_size(size, ctx.reborrow())?; + let base = self.resolve_ast_type(base, ctx)?; + let size = self.array_size(size, ctx)?; self.layouter.update(ctx.module.to_ctx()).unwrap(); let stride = self.layouter[base].to_stride(); @@ -2652,8 +2642,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ast::Type::AccelerationStructure => crate::TypeInner::AccelerationStructure, ast::Type::RayQuery => crate::TypeInner::RayQuery, ast::Type::BindingArray { base, size } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; - let size = self.array_size(size, ctx.reborrow())?; + let base = self.resolve_ast_type(base, ctx)?; + let size = self.array_size(size, ctx)?; crate::TypeInner::BindingArray { base, size } } ast::Type::RayDesc => { @@ -2678,7 +2668,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, binding: &Option>, ty: Handle, - mut ctx: GlobalContext<'source, '_, '_>, + ctx: &mut GlobalContext<'source, '_, '_>, ) -> Result, Error<'source>> { Ok(match *binding { Some(ast::Binding::BuiltIn(b)) => Some(crate::Binding::BuiltIn(b)), From a647c64432a0537f7a224eb9577cf86d937302d4 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 19 Oct 2023 17:14:08 -0700 Subject: [PATCH 2196/2212] [wgsl-in] Delete front::wgsl::lower::StatementContext::reborrow. Remove `StatementContext::reborrow` in favor of Rust's automatic reborrowing of `&mut` references. --- src/front/wgsl/lower/mod.rs | 68 +++++++++++++------------------------ 1 file changed, 24 insertions(+), 44 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index f6d0cc185..3dfc05c9e 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -163,23 +163,6 @@ pub struct StatementContext<'source, 'temp, 'out> { } impl<'a, 'temp> StatementContext<'a, 'temp, '_> { - fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { - StatementContext { - local_table: self.local_table, - globals: self.globals, - types: self.types, - ast_expressions: self.ast_expressions, - const_typifier: self.const_typifier, - typifier: self.typifier, - variables: self.variables, - naga_expressions: self.naga_expressions, - named_expressions: self.named_expressions, - arguments: self.arguments, - module: self.module, - expression_constness: self.expression_constness, - } - } - fn as_expression<'t>( &'t mut self, block: &'t mut crate::Block, @@ -1044,24 +1027,21 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .transpose()?; let mut typifier = Typifier::default(); - let mut body = self.block( - &f.body, - false, - StatementContext { - local_table: &mut local_table, - globals: ctx.globals, - ast_expressions: ctx.ast_expressions, - const_typifier: ctx.const_typifier, - typifier: &mut typifier, - variables: &mut local_variables, - naga_expressions: &mut expressions, - named_expressions: &mut named_expressions, - types: ctx.types, - module: ctx.module, - arguments: &arguments, - expression_constness: &mut crate::proc::ExpressionConstnessTracker::new(), - }, - )?; + let mut stmt_ctx = StatementContext { + local_table: &mut local_table, + globals: ctx.globals, + ast_expressions: ctx.ast_expressions, + const_typifier: ctx.const_typifier, + typifier: &mut typifier, + variables: &mut local_variables, + naga_expressions: &mut expressions, + named_expressions: &mut named_expressions, + types: ctx.types, + module: ctx.module, + arguments: &arguments, + expression_constness: &mut crate::proc::ExpressionConstnessTracker::new(), + }; + let mut body = self.block(&f.body, false, &mut stmt_ctx)?; ensure_block_returns(&mut body); let function = crate::Function { @@ -1109,12 +1089,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, b: &ast::Block<'source>, is_inside_loop: bool, - mut ctx: StatementContext<'source, '_, '_>, + ctx: &mut StatementContext<'source, '_, '_>, ) -> Result> { let mut block = crate::Block::default(); for stmt in b.stmts.iter() { - self.statement(stmt, &mut block, is_inside_loop, ctx.reborrow())?; + self.statement(stmt, &mut block, is_inside_loop, ctx)?; } Ok(block) @@ -1125,11 +1105,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { stmt: &ast::Statement<'source>, block: &mut crate::Block, is_inside_loop: bool, - mut ctx: StatementContext<'source, '_, '_>, + ctx: &mut StatementContext<'source, '_, '_>, ) -> Result<(), Error<'source>> { let out = match stmt.kind { ast::StatementKind::Block(ref block) => { - let block = self.block(block, is_inside_loop, ctx.reborrow())?; + let block = self.block(block, is_inside_loop, ctx)?; crate::Statement::Block(block) } ast::StatementKind::LocalDecl(ref decl) => match *decl { @@ -1276,8 +1256,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { self.expression(condition, ctx.as_expression(block, &mut emitter))?; block.extend(emitter.finish(ctx.naga_expressions)); - let accept = self.block(accept, is_inside_loop, ctx.reborrow())?; - let reject = self.block(reject, is_inside_loop, ctx.reborrow())?; + let accept = self.block(accept, is_inside_loop, ctx)?; + let reject = self.block(reject, is_inside_loop, ctx)?; crate::Statement::If { condition, @@ -1321,7 +1301,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::SwitchValue::Default => crate::SwitchValue::Default, }, - body: self.block(&case.body, is_inside_loop, ctx.reborrow())?, + body: self.block(&case.body, is_inside_loop, ctx)?, fall_through: case.fall_through, }) }) @@ -1334,8 +1314,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ref continuing, break_if, } => { - let body = self.block(body, true, ctx.reborrow())?; - let mut continuing = self.block(continuing, true, ctx.reborrow())?; + let body = self.block(body, true, ctx)?; + let mut continuing = self.block(continuing, true, ctx)?; let mut emitter = Emitter::default(); emitter.start(ctx.naga_expressions); From d038506a8cdb23d24b63ec951f340f1d55dffd98 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 19 Oct 2023 17:31:58 -0700 Subject: [PATCH 2197/2212] [wgsl-in] Delete {ExpressionContext,RuntimeContext}::reborrow. Remove `front::wgsl::lower::ExpressionContext::reborrow` and `front::wgsl::lower::RuntimeExpressionContext::reborrow` in favor of Rust's automatic reborrowing of `&mut` references. --- src/front/wgsl/lower/construction.rs | 16 +- src/front/wgsl/lower/mod.rs | 273 ++++++++++++--------------- 2 files changed, 129 insertions(+), 160 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index ab46f1164..12e30d28d 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -45,7 +45,7 @@ enum ConcreteConstructor<'a> { } impl ConcreteConstructorHandle { - fn to_error_string(&self, ctx: ExpressionContext) -> String { + fn to_error_string(&self, ctx: &mut ExpressionContext) -> String { match *self { Self::PartialVector { size } => { format!("vec{}", size as u32,) @@ -143,15 +143,15 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { constructor: &ast::ConstructorType<'source>, ty_span: Span, components: &[Handle>], - mut ctx: ExpressionContext<'source, '_, '_>, + ctx: &mut ExpressionContext<'source, '_, '_>, ) -> Result, Error<'source>> { - let constructor_h = self.constructor(constructor, ctx.reborrow())?; + let constructor_h = self.constructor(constructor, ctx)?; let components_h = match *components { [] => ComponentsHandle::None, [component] => { let span = ctx.ast_expressions.get_span(component); - let component = self.expression(component, ctx.reborrow())?; + let component = self.expression(component, ctx)?; let ty = super::resolve!(ctx, component); ComponentsHandle::One { @@ -162,12 +162,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } [component, ref rest @ ..] => { let span = ctx.ast_expressions.get_span(component); - let component = self.expression(component, ctx.reborrow())?; + let component = self.expression(component, ctx)?; let components = std::iter::once(Ok(component)) .chain( rest.iter() - .map(|&component| self.expression(component, ctx.reborrow())), + .map(|&component| self.expression(component, ctx)), ) .collect::>()?; let spans = std::iter::once(span) @@ -488,7 +488,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { return Err(Error::BadTypeCast { span, from_type, - to_type: constructor_h.to_error_string(ctx.reborrow()), + to_type: constructor_h.to_error_string(ctx), }); } @@ -545,7 +545,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn constructor<'out>( &mut self, constructor: &ast::ConstructorType<'source>, - mut ctx: ExpressionContext<'source, '_, 'out>, + ctx: &mut ExpressionContext<'source, '_, 'out>, ) -> Result> { let c = match *constructor { ast::ConstructorType::Scalar { width, kind } => { diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 3dfc05c9e..9176acca3 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -235,21 +235,6 @@ pub struct RuntimeExpressionContext<'temp, 'out> { expression_constness: &'temp mut crate::proc::ExpressionConstnessTracker, } -impl RuntimeExpressionContext<'_, '_> { - fn reborrow(&mut self) -> RuntimeExpressionContext<'_, '_> { - RuntimeExpressionContext { - local_table: self.local_table, - naga_expressions: self.naga_expressions, - local_vars: self.local_vars, - arguments: self.arguments, - block: self.block, - emitter: self.emitter, - typifier: self.typifier, - expression_constness: self.expression_constness, - } - } -} - /// The type of Naga IR expression we are lowering an [`ast::Expression`] to. pub enum ExpressionContextType<'temp, 'out> { /// We are lowering to an arbitrary runtime expression, to be @@ -295,9 +280,6 @@ pub enum ExpressionContextType<'temp, 'out> { /// expressions, via [`Expression::Constant`], but constant /// expressions can't refer to a function's expressions. /// -/// - You can always call [`ExpressionContext::reborrow`] to get a fresh context -/// for a recursive call. The reborrowed context is equivalent to the original. -/// /// Not to be confused with `wgsl::parse::ExpressionContext`, which is /// for parsing the `ast::Expression` in the first place. /// @@ -335,22 +317,6 @@ pub struct ExpressionContext<'source, 'temp, 'out> { } impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { - fn reborrow(&mut self) -> ExpressionContext<'source, '_, '_> { - ExpressionContext { - globals: self.globals, - types: self.types, - ast_expressions: self.ast_expressions, - const_typifier: self.const_typifier, - module: self.module, - expr_type: match self.expr_type { - ExpressionContextType::Runtime(ref mut c) => { - ExpressionContextType::Runtime(c.reborrow()) - } - ExpressionContextType::Constant => ExpressionContextType::Constant, - }, - } - } - fn as_const(&mut self) -> ExpressionContext<'source, '_, '_> { ExpressionContext { globals: self.globals, @@ -438,9 +404,9 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { fn runtime_expression_ctx( &mut self, span: Span, - ) -> Result, Error<'source>> { + ) -> Result<&mut RuntimeExpressionContext<'temp, 'out>, Error<'source>> { match self.expr_type { - ExpressionContextType::Runtime(ref mut ctx) => Ok(ctx.reborrow()), + ExpressionContextType::Runtime(ref mut ctx) => Ok(ctx), ExpressionContextType::Constant => Err(Error::UnexpectedOperationInConstContext(span)), } } @@ -898,13 +864,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let init = v .init - .map(|init| self.expression(init, ctx.as_const())) + .map(|init| self.expression(init, &mut ctx.as_const())) .transpose()?; let binding = if let Some(ref binding) = v.binding { Some(crate::ResourceBinding { - group: self.const_u32(binding.group, ctx.as_const())?.0, - binding: self.const_u32(binding.binding, ctx.as_const())?.0, + group: self.const_u32(binding.group, &mut ctx.as_const())?.0, + binding: self.const_u32(binding.binding, &mut ctx.as_const())?.0, }) } else { None @@ -926,7 +892,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::GlobalDeclKind::Const(ref c) => { let mut ectx = ctx.as_const(); - let init = self.expression(c.init, ectx.reborrow())?; + let init = self.expression(c.init, &mut ectx)?; let inferred_type = ectx.register_type(init)?; let explicit_ty = @@ -1063,7 +1029,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut workgroup_size_out = [1; 3]; for (i, size) in workgroup_size.into_iter().enumerate() { if let Some(size_expr) = size { - workgroup_size_out[i] = self.const_u32(size_expr, ctx.as_const())?.0; + workgroup_size_out[i] = self.const_u32(size_expr, &mut ctx.as_const())?.0; } } workgroup_size_out @@ -1117,7 +1083,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut emitter = Emitter::default(); emitter.start(ctx.naga_expressions); - let value = self.expression(l.init, ctx.as_expression(block, &mut emitter))?; + let value = + self.expression(l.init, &mut ctx.as_expression(block, &mut emitter))?; // The WGSL spec says that any expression that refers to a // `let`-bound variable is not a const expression. This @@ -1158,9 +1125,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { emitter.start(ctx.naga_expressions); let initializer = match v.init { - Some(init) => { - Some(self.expression(init, ctx.as_expression(block, &mut emitter))?) - } + Some(init) => Some( + self.expression(init, &mut ctx.as_expression(block, &mut emitter))?, + ), None => None, }; @@ -1253,7 +1220,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { emitter.start(ctx.naga_expressions); let condition = - self.expression(condition, ctx.as_expression(block, &mut emitter))?; + self.expression(condition, &mut ctx.as_expression(block, &mut emitter))?; block.extend(emitter.finish(ctx.naga_expressions)); let accept = self.block(accept, is_inside_loop, ctx)?; @@ -1273,7 +1240,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { emitter.start(ctx.naga_expressions); let mut ectx = ctx.as_expression(block, &mut emitter); - let selector = self.expression(selector, ectx.reborrow())?; + let selector = self.expression(selector, &mut ectx)?; let uint = resolve_inner!(ectx, selector).scalar_kind() == Some(crate::ScalarKind::Uint); @@ -1286,7 +1253,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { value: match case.value { ast::SwitchValue::Expr(expr) => { let span = ctx.ast_expressions.get_span(expr); - let expr = self.expression(expr, ctx.as_global().as_const())?; + let expr = + self.expression(expr, &mut ctx.as_global().as_const())?; match ctx.module.to_ctx().eval_expr_to_literal(expr) { Some(crate::Literal::I32(value)) if !uint => { crate::SwitchValue::I32(value) @@ -1320,7 +1288,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut emitter = Emitter::default(); emitter.start(ctx.naga_expressions); let break_if = break_if - .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) + .map(|expr| self.expression(expr, &mut ctx.as_expression(block, &mut emitter))) .transpose()?; continuing.extend(emitter.finish(ctx.naga_expressions)); @@ -1337,7 +1305,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { emitter.start(ctx.naga_expressions); let value = value - .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) + .map(|expr| self.expression(expr, &mut ctx.as_expression(block, &mut emitter))) .transpose()?; block.extend(emitter.finish(ctx.naga_expressions)); @@ -1355,7 +1323,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { stmt.span, function, arguments, - ctx.as_expression(block, &mut emitter), + &mut ctx.as_expression(block, &mut emitter), )?; block.extend(emitter.finish(ctx.naga_expressions)); return Ok(()); @@ -1364,9 +1332,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut emitter = Emitter::default(); emitter.start(ctx.naga_expressions); - let expr = - self.expression_for_reference(target, ctx.as_expression(block, &mut emitter))?; - let mut value = self.expression(value, ctx.as_expression(block, &mut emitter))?; + let expr = self.expression_for_reference( + target, + &mut ctx.as_expression(block, &mut emitter), + )?; + let mut value = + self.expression(value, &mut ctx.as_expression(block, &mut emitter))?; if !expr.is_reference { let ty = ctx.invalid_assignment_type(expr.handle); @@ -1411,8 +1382,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let value_span = ctx.ast_expressions.get_span(value); - let reference = - self.expression_for_reference(value, ctx.as_expression(block, &mut emitter))?; + let reference = self + .expression_for_reference(value, &mut ctx.as_expression(block, &mut emitter))?; let mut ectx = ctx.as_expression(block, &mut emitter); let (kind, width) = match *resolve_inner!(ectx, reference.handle) { @@ -1459,7 +1430,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut emitter = Emitter::default(); emitter.start(ctx.naga_expressions); - let _ = self.expression(expr, ctx.as_expression(block, &mut emitter))?; + let _ = self.expression(expr, &mut ctx.as_expression(block, &mut emitter))?; block.extend(emitter.finish(ctx.naga_expressions)); return Ok(()); } @@ -1473,16 +1444,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn expression( &mut self, expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, + ctx: &mut ExpressionContext<'source, '_, '_>, ) -> Result, Error<'source>> { - let expr = self.expression_for_reference(expr, ctx.reborrow())?; + let expr = self.expression_for_reference(expr, ctx)?; ctx.apply_load_rule(expr) } fn expression_for_reference( &mut self, expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, + ctx: &mut ExpressionContext<'source, '_, '_>, ) -> Result> { let span = ctx.ast_expressions.get_span(expr); let expr = &ctx.ast_expressions[expr]; @@ -1535,17 +1506,17 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ty_span, ref components, } => { - let handle = self.construct(span, ty, ty_span, components, ctx.reborrow())?; + let handle = self.construct(span, ty, ty_span, components, ctx)?; return Ok(TypedExpression::non_reference(handle)); } ast::Expression::Unary { op, expr } => { - let expr = self.expression(expr, ctx.reborrow())?; + let expr = self.expression(expr, ctx)?; (crate::Expression::Unary { op, expr }, false) } ast::Expression::AddrOf(expr) => { // The `&` operator simply converts a reference to a pointer. And since a // reference is required, the Load Rule is not applied. - let expr = self.expression_for_reference(expr, ctx.reborrow())?; + let expr = self.expression_for_reference(expr, ctx)?; if !expr.is_reference { return Err(Error::NotReference("the operand of the `&` operator", span)); } @@ -1558,7 +1529,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::Expression::Deref(expr) => { // The pointer we dereference must be loaded. - let pointer = self.expression(expr, ctx.reborrow())?; + let pointer = self.expression(expr, ctx)?; if resolve_inner!(ctx, pointer).pointer_space().is_none() { return Err(Error::NotPointer(span)); @@ -1571,8 +1542,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::Expression::Binary { op, left, right } => { // Load both operands. - let mut left = self.expression(left, ctx.reborrow())?; - let mut right = self.expression(right, ctx.reborrow())?; + let mut left = self.expression(left, ctx)?; + let mut right = self.expression(right, ctx)?; ctx.binary_op_splat(op, &mut left, &mut right)?; (crate::Expression::Binary { op, left, right }, false) } @@ -1581,13 +1552,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ref arguments, } => { let handle = self - .call(span, function, arguments, ctx.reborrow())? + .call(span, function, arguments, ctx)? .ok_or(Error::FunctionReturnsVoid(function.span))?; return Ok(TypedExpression::non_reference(handle)); } ast::Expression::Index { base, index } => { - let expr = self.expression_for_reference(base, ctx.reborrow())?; - let index = self.expression(index, ctx.reborrow())?; + let expr = self.expression_for_reference(base, ctx)?; + let index = self.expression(index, ctx)?; let wgsl_pointer = resolve_inner!(ctx, expr.handle).pointer_space().is_some() && !expr.is_reference; @@ -1621,7 +1592,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let TypedExpression { handle, is_reference, - } = self.expression_for_reference(base, ctx.reborrow())?; + } = self.expression_for_reference(base, ctx)?; let temp_inner; let (composite, wgsl_pointer) = match *resolve_inner!(ctx, handle) { @@ -1704,7 +1675,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { access } ast::Expression::Bitcast { expr, to, ty_span } => { - let expr = self.expression(expr, ctx.reborrow())?; + let expr = self.expression(expr, ctx)?; let to_resolved = self.resolve_ast_type(to, &mut ctx.as_global())?; let kind = match ctx.module.types[to_resolved].inner { @@ -1761,7 +1732,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span: Span, function: &ast::Ident<'source>, arguments: &[Handle>], - mut ctx: ExpressionContext<'source, '_, '_>, + ctx: &mut ExpressionContext<'source, '_, '_>, ) -> Result>, Error<'source>> { match ctx.globals.get(function.name) { Some(&LoweredGlobalDecl::Type(ty)) => { @@ -1770,7 +1741,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &ast::ConstructorType::Type(ty), function.span, arguments, - ctx.reborrow(), + ctx, )?; Ok(Some(handle)) } @@ -1781,7 +1752,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Some(&LoweredGlobalDecl::Function(function)) => { let arguments = arguments .iter() - .map(|&arg| self.expression(arg, ctx.reborrow())) + .map(|&arg| self.expression(arg, ctx)) .collect::, _>>()?; let has_result = ctx.module.functions[function].result.is_some(); @@ -1809,7 +1780,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let span = function.span; let expr = if let Some(fun) = conv::map_relational_fun(function.name) { let mut args = ctx.prepare_args(arguments, 1, span); - let argument = self.expression(args.next()?, ctx.reborrow())?; + let argument = self.expression(args.next()?, ctx)?; args.finish()?; // Check for no-op all(bool) and any(bool): @@ -1833,7 +1804,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } } else if let Some((axis, ctrl)) = conv::map_derivative(function.name) { let mut args = ctx.prepare_args(arguments, 1, span); - let expr = self.expression(args.next()?, ctx.reborrow())?; + let expr = self.expression(args.next()?, ctx)?; args.finish()?; crate::Expression::Derivative { axis, ctrl, expr } @@ -1841,20 +1812,20 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let expected = fun.argument_count() as _; let mut args = ctx.prepare_args(arguments, expected, span); - let arg = self.expression(args.next()?, ctx.reborrow())?; + let arg = self.expression(args.next()?, ctx)?; let arg1 = args .next() - .map(|x| self.expression(x, ctx.reborrow())) + .map(|x| self.expression(x, ctx)) .ok() .transpose()?; let arg2 = args .next() - .map(|x| self.expression(x, ctx.reborrow())) + .map(|x| self.expression(x, ctx)) .ok() .transpose()?; let arg3 = args .next() - .map(|x| self.expression(x, ctx.reborrow())) + .map(|x| self.expression(x, ctx)) .ok() .transpose()?; @@ -1886,15 +1857,15 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { arg3, } } else if let Some(fun) = Texture::map(function.name) { - self.texture_sample_helper(fun, arguments, span, ctx.reborrow())? + self.texture_sample_helper(fun, arguments, span, ctx)? } else { match function.name { "select" => { let mut args = ctx.prepare_args(arguments, 3, span); - let reject = self.expression(args.next()?, ctx.reborrow())?; - let accept = self.expression(args.next()?, ctx.reborrow())?; - let condition = self.expression(args.next()?, ctx.reborrow())?; + let reject = self.expression(args.next()?, ctx)?; + let accept = self.expression(args.next()?, ctx)?; + let condition = self.expression(args.next()?, ctx)?; args.finish()?; @@ -1906,22 +1877,22 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "arrayLength" => { let mut args = ctx.prepare_args(arguments, 1, span); - let expr = self.expression(args.next()?, ctx.reborrow())?; + let expr = self.expression(args.next()?, ctx)?; args.finish()?; crate::Expression::ArrayLength(expr) } "atomicLoad" => { let mut args = ctx.prepare_args(arguments, 1, span); - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + let pointer = self.atomic_pointer(args.next()?, ctx)?; args.finish()?; crate::Expression::Load { pointer } } "atomicStore" => { let mut args = ctx.prepare_args(arguments, 2, span); - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; - let value = self.expression(args.next()?, ctx.reborrow())?; + let pointer = self.atomic_pointer(args.next()?, ctx)?; + let value = self.expression(args.next()?, ctx)?; args.finish()?; let rctx = ctx.runtime_expression_ctx(span)?; @@ -1937,7 +1908,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, crate::AtomicFunction::Add, arguments, - ctx.reborrow(), + ctx, )?)) } "atomicSub" => { @@ -1945,7 +1916,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, crate::AtomicFunction::Subtract, arguments, - ctx.reborrow(), + ctx, )?)) } "atomicAnd" => { @@ -1953,7 +1924,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, crate::AtomicFunction::And, arguments, - ctx.reborrow(), + ctx, )?)) } "atomicOr" => { @@ -1961,7 +1932,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, crate::AtomicFunction::InclusiveOr, arguments, - ctx.reborrow(), + ctx, )?)) } "atomicXor" => { @@ -1969,7 +1940,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, crate::AtomicFunction::ExclusiveOr, arguments, - ctx.reborrow(), + ctx, )?)) } "atomicMin" => { @@ -1977,7 +1948,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, crate::AtomicFunction::Min, arguments, - ctx.reborrow(), + ctx, )?)) } "atomicMax" => { @@ -1985,7 +1956,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, crate::AtomicFunction::Max, arguments, - ctx.reborrow(), + ctx, )?)) } "atomicExchange" => { @@ -1993,19 +1964,19 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, crate::AtomicFunction::Exchange { compare: None }, arguments, - ctx.reborrow(), + ctx, )?)) } "atomicCompareExchangeWeak" => { let mut args = ctx.prepare_args(arguments, 3, span); - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + let pointer = self.atomic_pointer(args.next()?, ctx)?; - let compare = self.expression(args.next()?, ctx.reborrow())?; + let compare = self.expression(args.next()?, ctx)?; let value = args.next()?; let value_span = ctx.ast_expressions.get_span(value); - let value = self.expression(value, ctx.reborrow())?; + let value = self.expression(value, ctx)?; args.finish()?; @@ -2060,7 +2031,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let expr = args.next()?; args.finish()?; - let pointer = self.expression(expr, ctx.reborrow())?; + let pointer = self.expression(expr, ctx)?; let result_ty = match *resolve_inner!(ctx, pointer) { crate::TypeInner::Pointer { base, @@ -2089,19 +2060,19 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let image = args.next()?; let image_span = ctx.ast_expressions.get_span(image); - let image = self.expression(image, ctx.reborrow())?; + let image = self.expression(image, ctx)?; - let coordinate = self.expression(args.next()?, ctx.reborrow())?; + let coordinate = self.expression(args.next()?, ctx)?; let (_, arrayed) = ctx.image_data(image, image_span)?; let array_index = arrayed .then(|| { args.min_args += 1; - self.expression(args.next()?, ctx.reborrow()) + self.expression(args.next()?, ctx) }) .transpose()?; - let value = self.expression(args.next()?, ctx.reborrow())?; + let value = self.expression(args.next()?, ctx)?; args.finish()?; @@ -2123,26 +2094,26 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let image = args.next()?; let image_span = ctx.ast_expressions.get_span(image); - let image = self.expression(image, ctx.reborrow())?; + let image = self.expression(image, ctx)?; - let coordinate = self.expression(args.next()?, ctx.reborrow())?; + let coordinate = self.expression(args.next()?, ctx)?; let (class, arrayed) = ctx.image_data(image, image_span)?; let array_index = arrayed .then(|| { args.min_args += 1; - self.expression(args.next()?, ctx.reborrow()) + self.expression(args.next()?, ctx) }) .transpose()?; let level = class .is_mipmapped() - .then(|| self.expression(args.next()?, ctx.reborrow())) + .then(|| self.expression(args.next()?, ctx)) .transpose()?; let sample = class .is_multisampled() - .then(|| self.expression(args.next()?, ctx.reborrow())) + .then(|| self.expression(args.next()?, ctx)) .transpose()?; args.finish()?; @@ -2157,10 +2128,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "textureDimensions" => { let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; + let image = self.expression(args.next()?, ctx)?; let level = args .next() - .map(|arg| self.expression(arg, ctx.reborrow())) + .map(|arg| self.expression(arg, ctx)) .ok() .transpose()?; args.finish()?; @@ -2172,7 +2143,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "textureNumLevels" => { let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; + let image = self.expression(args.next()?, ctx)?; args.finish()?; crate::Expression::ImageQuery { @@ -2182,7 +2153,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "textureNumLayers" => { let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; + let image = self.expression(args.next()?, ctx)?; args.finish()?; crate::Expression::ImageQuery { @@ -2192,7 +2163,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "textureNumSamples" => { let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; + let image = self.expression(args.next()?, ctx)?; args.finish()?; crate::Expression::ImageQuery { @@ -2202,10 +2173,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "rayQueryInitialize" => { let mut args = ctx.prepare_args(arguments, 3, span); - let query = self.ray_query_pointer(args.next()?, ctx.reborrow())?; - let acceleration_structure = - self.expression(args.next()?, ctx.reborrow())?; - let descriptor = self.expression(args.next()?, ctx.reborrow())?; + let query = self.ray_query_pointer(args.next()?, ctx)?; + let acceleration_structure = self.expression(args.next()?, ctx)?; + let descriptor = self.expression(args.next()?, ctx)?; args.finish()?; let _ = ctx.module.generate_ray_desc_type(); @@ -2224,7 +2194,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "rayQueryProceed" => { let mut args = ctx.prepare_args(arguments, 1, span); - let query = self.ray_query_pointer(args.next()?, ctx.reborrow())?; + let query = self.ray_query_pointer(args.next()?, ctx)?; args.finish()?; let result = ctx.interrupt_emitter( @@ -2239,7 +2209,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } "rayQueryGetCommittedIntersection" => { let mut args = ctx.prepare_args(arguments, 1, span); - let query = self.ray_query_pointer(args.next()?, ctx.reborrow())?; + let query = self.ray_query_pointer(args.next()?, ctx)?; args.finish()?; let _ = ctx.module.generate_ray_intersection_type(); @@ -2256,7 +2226,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &ast::ConstructorType::Type(ty), function.span, arguments, - ctx.reborrow(), + ctx, )?; return Ok(Some(handle)); } @@ -2273,10 +2243,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn atomic_pointer( &mut self, expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, + ctx: &mut ExpressionContext<'source, '_, '_>, ) -> Result, Error<'source>> { let span = ctx.ast_expressions.get_span(expr); - let pointer = self.expression(expr, ctx.reborrow())?; + let pointer = self.expression(expr, ctx)?; match *resolve_inner!(ctx, pointer) { crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { @@ -2298,14 +2268,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span: Span, fun: crate::AtomicFunction, args: &[Handle>], - mut ctx: ExpressionContext<'source, '_, '_>, + ctx: &mut ExpressionContext<'source, '_, '_>, ) -> Result, Error<'source>> { let mut args = ctx.prepare_args(args, 2, span); - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + let pointer = self.atomic_pointer(args.next()?, ctx)?; let value = args.next()?; - let value = self.expression(value, ctx.reborrow())?; + let value = self.expression(value, ctx)?; let ty = ctx.register_type(value)?; args.finish()?; @@ -2335,7 +2305,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fun: Texture, args: &[Handle>], span: Span, - mut ctx: ExpressionContext<'source, '_, '_>, + ctx: &mut ExpressionContext<'source, '_, '_>, ) -> Result> { let mut args = ctx.prepare_args(args, fun.min_argument_count(), span); @@ -2346,7 +2316,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ) -> Result<(Handle, Span), Error<'source>> { let image = args.next()?; let image_span = ctx.ast_expressions.get_span(image); - let image = lowerer.expression(image, ctx.reborrow())?; + let image = lowerer.expression(image, ctx)?; Ok((image, image_span)) } @@ -2355,8 +2325,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let image_or_component = args.next()?; let image_or_component_span = ctx.ast_expressions.get_span(image_or_component); // Gathers from depth textures don't take an initial `component` argument. - let lowered_image_or_component = - self.expression(image_or_component, ctx.reborrow())?; + let lowered_image_or_component = self.expression(image_or_component, ctx)?; match *resolve_inner!(ctx, lowered_image_or_component) { crate::TypeInner::Image { @@ -2368,7 +2337,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Some(crate::SwizzleComponent::X), ), _ => { - let (image, image_span) = get_image_and_span(self, &mut args, &mut ctx)?; + let (image, image_span) = get_image_and_span(self, &mut args, ctx)?; ( image, image_span, @@ -2382,59 +2351,59 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } } Texture::GatherCompare => { - let (image, image_span) = get_image_and_span(self, &mut args, &mut ctx)?; + let (image, image_span) = get_image_and_span(self, &mut args, ctx)?; (image, image_span, Some(crate::SwizzleComponent::X)) } _ => { - let (image, image_span) = get_image_and_span(self, &mut args, &mut ctx)?; + let (image, image_span) = get_image_and_span(self, &mut args, ctx)?; (image, image_span, None) } }; - let sampler = self.expression(args.next()?, ctx.reborrow())?; + let sampler = self.expression(args.next()?, ctx)?; - let coordinate = self.expression(args.next()?, ctx.reborrow())?; + let coordinate = self.expression(args.next()?, ctx)?; let (_, arrayed) = ctx.image_data(image, image_span)?; let array_index = arrayed - .then(|| self.expression(args.next()?, ctx.reborrow())) + .then(|| self.expression(args.next()?, ctx)) .transpose()?; let (level, depth_ref) = match fun { Texture::Gather => (crate::SampleLevel::Zero, None), Texture::GatherCompare => { - let reference = self.expression(args.next()?, ctx.reborrow())?; + let reference = self.expression(args.next()?, ctx)?; (crate::SampleLevel::Zero, Some(reference)) } Texture::Sample => (crate::SampleLevel::Auto, None), Texture::SampleBias => { - let bias = self.expression(args.next()?, ctx.reborrow())?; + let bias = self.expression(args.next()?, ctx)?; (crate::SampleLevel::Bias(bias), None) } Texture::SampleCompare => { - let reference = self.expression(args.next()?, ctx.reborrow())?; + let reference = self.expression(args.next()?, ctx)?; (crate::SampleLevel::Auto, Some(reference)) } Texture::SampleCompareLevel => { - let reference = self.expression(args.next()?, ctx.reborrow())?; + let reference = self.expression(args.next()?, ctx)?; (crate::SampleLevel::Zero, Some(reference)) } Texture::SampleGrad => { - let x = self.expression(args.next()?, ctx.reborrow())?; - let y = self.expression(args.next()?, ctx.reborrow())?; + let x = self.expression(args.next()?, ctx)?; + let y = self.expression(args.next()?, ctx)?; (crate::SampleLevel::Gradient { x, y }, None) } Texture::SampleLevel => { - let level = self.expression(args.next()?, ctx.reborrow())?; + let level = self.expression(args.next()?, ctx)?; (crate::SampleLevel::Exact(level), None) } }; let offset = args .next() - .map(|arg| self.expression(arg, ctx.as_const())) + .map(|arg| self.expression(arg, &mut ctx.as_const())) .ok() .transpose()?; @@ -2471,7 +2440,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let member_min_alignment = self.layouter[ty].alignment; let member_size = if let Some(size_expr) = member.size { - let (size, span) = self.const_u32(size_expr, ctx.as_const())?; + let (size, span) = self.const_u32(size_expr, &mut ctx.as_const())?; if size < member_min_size { return Err(Error::SizeAttributeTooLow(span, member_min_size)); } else { @@ -2482,7 +2451,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let member_alignment = if let Some(align_expr) = member.align { - let (align, span) = self.const_u32(align_expr, ctx.as_const())?; + let (align, span) = self.const_u32(align_expr, &mut ctx.as_const())?; if let Some(alignment) = Alignment::new(align) { if alignment < member_min_alignment { return Err(Error::AlignAttributeTooLow(span, member_min_alignment)); @@ -2530,10 +2499,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn const_u32( &mut self, expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, + ctx: &mut ExpressionContext<'source, '_, '_>, ) -> Result<(u32, Span), Error<'source>> { let span = ctx.ast_expressions.get_span(expr); - let expr = self.expression(expr, ctx.reborrow())?; + let expr = self.expression(expr, ctx)?; let value = ctx .module .to_ctx() @@ -2555,7 +2524,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok(match size { ast::ArraySize::Constant(expr) => { let span = ctx.ast_expressions.get_span(expr); - let const_expr = self.expression(expr, ctx.as_const())?; + let const_expr = self.expression(expr, &mut ctx.as_const())?; let len = ctx.module .to_ctx() @@ -2659,7 +2628,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { sampling, }) => { let mut binding = crate::Binding::Location { - location: self.const_u32(location, ctx.as_const())?.0, + location: self.const_u32(location, &mut ctx.as_const())?.0, second_blend_source, interpolation, sampling, @@ -2674,10 +2643,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn ray_query_pointer( &mut self, expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, + ctx: &mut ExpressionContext<'source, '_, '_>, ) -> Result, Error<'source>> { let span = ctx.ast_expressions.get_span(expr); - let pointer = self.expression(expr, ctx.reborrow())?; + let pointer = self.expression(expr, ctx)?; match *resolve_inner!(ctx, pointer) { crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { From dd8f8143446b59c20f010bc532f9a25b46195580 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 19 Oct 2023 18:18:55 -0700 Subject: [PATCH 2198/2212] [wgsl-in] Clean up swizzle/component access type. Rename `front::wgsl::lower::Composition` to `Components`. It doesn't represent a composition, it represents either a single component being selected from a vector or a swizzle. Clean up code and helper function names. --- src/front/wgsl/lower/mod.rs | 53 ++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 9176acca3..6b0d1c75c 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -723,12 +723,20 @@ impl TypedExpression { } } -enum Composition { +/// A single vector component or swizzle. +/// +/// This represents the things that can appear after the `.` in a vector access +/// expression: either a single component name, or a series of them, +/// representing a swizzle. +enum Components { Single(u32), - Multi(crate::VectorSize, [crate::SwizzleComponent; 4]), + Swizzle { + size: crate::VectorSize, + pattern: [crate::SwizzleComponent; 4], + }, } -impl Composition { +impl Components { const fn letter_component(letter: char) -> Option { use crate::SwizzleComponent as Sc; match letter { @@ -740,7 +748,7 @@ impl Composition { } } - fn extract_impl(name: &str, name_span: Span) -> Result { + fn single_component(name: &str, name_span: Span) -> Result { let ch = name.chars().next().ok_or(Error::BadAccessor(name_span))?; match Self::letter_component(ch) { Some(sc) => Ok(sc as u32), @@ -748,23 +756,24 @@ impl Composition { } } - fn make(name: &str, name_span: Span) -> Result { - if name.len() > 1 { - let mut components = [crate::SwizzleComponent::X; 4]; - for (comp, ch) in components.iter_mut().zip(name.chars()) { - *comp = Self::letter_component(ch).ok_or(Error::BadAccessor(name_span))?; - } + /// Construct a `Components` value from a 'member' name, like `"wzy"` or `"x"`. + /// + /// Use `name_span` for reporting errors in parsing the component string. + fn new(name: &str, name_span: Span) -> Result { + let size = match name.len() { + 1 => return Ok(Components::Single(Self::single_component(name, name_span)?)), + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + 4 => crate::VectorSize::Quad, + _ => return Err(Error::BadAccessor(name_span)), + }; - let size = match name.len() { - 2 => crate::VectorSize::Bi, - 3 => crate::VectorSize::Tri, - 4 => crate::VectorSize::Quad, - _ => return Err(Error::BadAccessor(name_span)), - }; - Ok(Composition::Multi(size, components)) - } else { - Self::extract_impl(name, name_span).map(Composition::Single) + let mut pattern = [crate::SwizzleComponent::X; 4]; + for (comp, ch) in pattern.iter_mut().zip(name.chars()) { + *comp = Self::letter_component(ch).ok_or(Error::BadAccessor(name_span))?; } + + Ok(Components::Swizzle { size, pattern }) } } @@ -1644,8 +1653,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ) } crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { - match Composition::make(field.name, field.span)? { - Composition::Multi(size, pattern) => { + match Components::new(field.name, field.span)? { + Components::Swizzle { size, pattern } => { let vector = ctx.apply_load_rule(TypedExpression { handle, is_reference, @@ -1660,7 +1669,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { false, ) } - Composition::Single(index) => ( + Components::Single(index) => ( crate::Expression::AccessIndex { base: handle, index, From 946745d38fc2063a899794a40046d84ee2cbb8ef Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Thu, 19 Oct 2023 18:30:26 -0700 Subject: [PATCH 2199/2212] [wgsl-in] Turn `Error::Other` into `Error::Internal`, to help devs. Provide a textual message with `front::wgsl::Error::Internal`, so that a developer who sees one of these errors can at least search the source tree to find out where it came from. --- src/front/wgsl/error.rs | 8 ++++---- src/front/wgsl/parse/mod.rs | 5 ++--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index 93fff0490..e8a2ea9f1 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -233,7 +233,7 @@ pub enum Error<'a> { }, FunctionReturnsVoid(Span), InvalidWorkGroupUniformLoad(Span), - Other, + Internal(&'static str), ExpectedConstExprConcreteIntegerScalar(Span), ExpectedNonNegative(Span), ExpectedPositiveArrayLength(Span), @@ -667,10 +667,10 @@ impl<'a> Error<'a> { labels: vec![(span, "".into())], notes: vec!["passed type must be a workgroup pointer".into()], }, - Error::Other => ParseError { - message: "other error".to_string(), + Error::Internal(message) => ParseError { + message: "internal WGSL front end error".to_string(), labels: vec![], - notes: vec![], + notes: vec![message.into()], }, Error::ExpectedConstExprConcreteIntegerScalar(span) => ParseError { message: "must be a const-expression that resolves to a concrete integer scalar (u32 or i32)".to_string(), diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs index 431257aff..ae690018f 100644 --- a/src/front/wgsl/parse/mod.rs +++ b/src/front/wgsl/parse/mod.rs @@ -2290,13 +2290,12 @@ impl Parser { if !self.rules.is_empty() { log::error!("Reached the end of global decl, but rule stack is not empty"); log::error!("Rules: {:?}", self.rules); - return Err(Error::Other); + return Err(Error::Internal("rule stack is not empty")); }; match binding { None => Ok(()), - // we had the attribute but no var? - Some(_) => Err(Error::Other), + Some(_) => Err(Error::Internal("we had the attribute but no var?")), } } From 528bca75f71b7d611afd101b59cb83eff154e722 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sat, 21 Oct 2023 17:03:19 -0700 Subject: [PATCH 2200/2212] Give front::wgsl::Error::InitializationTypeMismatch named fields. --- src/front/wgsl/error.rs | 14 +++++++++----- src/front/wgsl/lower/mod.rs | 34 +++++++++++++++++----------------- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs index e8a2ea9f1..9143a8c07 100644 --- a/src/front/wgsl/error.rs +++ b/src/front/wgsl/error.rs @@ -177,7 +177,11 @@ pub enum Error<'a> { InconsistentBinding(Span), TypeNotConstructible(Span), TypeNotInferrable(Span), - InitializationTypeMismatch(Span, String, String), + InitializationTypeMismatch { + name: Span, + expected: String, + got: String, + }, MissingType(Span), MissingAttribute(&'static str, Span), InvalidAtomicPointer(Span), @@ -475,15 +479,15 @@ impl<'a> Error<'a> { labels: vec![(span, "type can't be inferred".into())], notes: vec![], }, - Error::InitializationTypeMismatch(name_span, ref expected_ty, ref got_ty) => { + Error::InitializationTypeMismatch { name, ref expected, ref got } => { ParseError { message: format!( "the type of `{}` is expected to be `{}`, but got `{}`", - &source[name_span], expected_ty, got_ty, + &source[name], expected, got, ), labels: vec![( - name_span, - format!("definition of `{}`", &source[name_span]).into(), + name, + format!("definition of `{}`", &source[name]).into(), )], notes: vec![], } diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 6b0d1c75c..631db7d26 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -911,22 +911,22 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { if let Some(explicit) = explicit_ty { if explicit != inferred_type { let ty = &ctx.module.types[explicit]; - let explicit = ty + let expected = ty .name .clone() .unwrap_or_else(|| ty.inner.to_wgsl(ctx.module.to_ctx())); let ty = &ctx.module.types[inferred_type]; - let inferred = ty + let got = ty .name .clone() .unwrap_or_else(|| ty.inner.to_wgsl(ctx.module.to_ctx())); - return Err(Error::InitializationTypeMismatch( - c.name.span, - explicit, - inferred, - )); + return Err(Error::InitializationTypeMismatch { + name: c.name.span, + expected, + got, + }); } } @@ -1113,11 +1113,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .inner .equivalent(&ctx.module.types[init_ty].inner, &ctx.module.types) { - return Err(Error::InitializationTypeMismatch( - l.name.span, - ctx.format_type(ty), - ctx.format_type(init_ty), - )); + return Err(Error::InitializationTypeMismatch { + name: l.name.span, + expected: ctx.format_type(ty), + got: ctx.format_type(init_ty), + }); } } @@ -1152,11 +1152,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .inner .equivalent(initializer_ty, &ctx.module.types) { - return Err(Error::InitializationTypeMismatch( - v.name.span, - ctx.format_type(explicit), - ctx.format_typeinner(initializer_ty), - )); + return Err(Error::InitializationTypeMismatch { + name: v.name.span, + expected: ctx.format_type(explicit), + got: ctx.format_typeinner(initializer_ty), + }); } explicit } From f081f06f54fab2cfdf636258b26670995861468e Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 23 Oct 2023 16:31:44 +0200 Subject: [PATCH 2201/2212] fix expected min arg count of `textureLoad` --- src/front/wgsl/lower/mod.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 631db7d26..c5db0663f 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -2099,7 +2099,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { return Ok(None); } "textureLoad" => { - let mut args = ctx.prepare_args(arguments, 3, span); + let mut args = ctx.prepare_args(arguments, 2, span); let image = args.next()?; let image_span = ctx.ast_expressions.get_span(image); @@ -2117,7 +2117,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let level = class .is_mipmapped() - .then(|| self.expression(args.next()?, ctx)) + .then(|| { + args.min_args += 1; + self.expression(args.next()?, ctx) + }) .transpose()?; let sample = class From 49f6730624537ca7448d01f6a91707aee978d0bc Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 20 Oct 2023 21:45:56 -0700 Subject: [PATCH 2202/2212] [wgsl-in] Consolidate array and struct cases in construction. --- src/front/wgsl/lower/construction.rs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 12e30d28d..d02826834 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -466,20 +466,18 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { crate::Expression::Compose { ty, components } } - // Array constructor - (components, ConcreteConstructor::Type(ty, &crate::TypeInner::Array { .. })) => { + // Array or Struct constructor + ( + components, + ConcreteConstructor::Type( + ty, + &crate::TypeInner::Array { .. } | &crate::TypeInner::Struct { .. }, + ), + ) => { let components = components.into_components_vec(); crate::Expression::Compose { ty, components } } - // Struct constructor - (components, ConcreteConstructor::Type(ty, &crate::TypeInner::Struct { .. })) => { - crate::Expression::Compose { - ty, - components: components.into_components_vec(), - } - } - // ERRORS // Bad conversion (type cast) From 93ae5cc82ee8a7a7cfb038499cf4b45981bf7e32 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 20 Oct 2023 22:04:39 -0700 Subject: [PATCH 2203/2212] [wgsl-in] Delete ComponentsHandle type. In `front:wgsl::lower::construct`, build `Components` values directly, rather than building a `ComponentsHandle` and then calling its `borrow` method. --- src/front/wgsl/lower/construction.rs | 63 +++++----------------------- src/front/wgsl/lower/mod.rs | 2 +- 2 files changed, 11 insertions(+), 54 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index d02826834..9ce29aa35 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -5,7 +5,6 @@ use crate::{Handle, Span}; use crate::front::wgsl::error::Error; use crate::front::wgsl::lower::{ExpressionContext, Lowerer}; -use crate::proc::TypeResolution; enum ConcreteConstructorHandle { PartialVector { @@ -59,46 +58,6 @@ impl ConcreteConstructorHandle { } } -enum ComponentsHandle<'a> { - None, - One { - component: Handle, - span: Span, - ty: &'a TypeResolution, - }, - Many { - components: Vec>, - spans: Vec, - first_component_ty: &'a TypeResolution, - }, -} - -impl<'a> ComponentsHandle<'a> { - fn borrow(self, module: &'a crate::Module) -> Components<'a> { - match self { - Self::None => Components::None, - Self::One { - component, - span, - ty, - } => Components::One { - component, - span, - ty_inner: ty.inner_with(&module.types), - }, - Self::Many { - components, - spans, - first_component_ty, - } => Components::Many { - components, - spans, - first_component_ty_inner: first_component_ty.inner_with(&module.types), - }, - } - } -} - enum Components<'a> { None, One { @@ -147,17 +106,17 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ) -> Result, Error<'source>> { let constructor_h = self.constructor(constructor, ctx)?; - let components_h = match *components { - [] => ComponentsHandle::None, + let components = match *components { + [] => Components::None, [component] => { let span = ctx.ast_expressions.get_span(component); let component = self.expression(component, ctx)?; - let ty = super::resolve!(ctx, component); + let ty_inner = super::resolve_inner!(ctx, component); - ComponentsHandle::One { + Components::One { component, span, - ty, + ty_inner, } } [component, ref rest @ ..] => { @@ -177,20 +136,18 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ) .collect(); - let ty = super::resolve!(ctx, component); + let first_component_ty_inner = super::resolve_inner!(ctx, component); - ComponentsHandle::Many { + Components::Many { components, spans, - first_component_ty: ty, + first_component_ty_inner, } } }; - let (components, constructor) = ( - components_h.borrow(ctx.module), - constructor_h.borrow(ctx.module), - ); + let constructor = constructor_h.borrow(ctx.module); + let expr = match (components, constructor) { // Empty constructor (Components::None, dst_ty) => match dst_ty { diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index c5db0663f..7a0db365a 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -32,6 +32,7 @@ macro_rules! resolve_inner { $ctx.typifier()[$expr].inner_with(&$ctx.module.types) }}; } +pub(super) use resolve_inner; /// Resolves the inner types of two given expressions. /// @@ -64,7 +65,6 @@ macro_rules! resolve { &$ctx.typifier()[$expr] }}; } -pub(super) use resolve; /// State for constructing a `crate::Module`. pub struct GlobalContext<'source, 'temp, 'out> { From 65f2216ecfe9b4c09acc5824c094c28e6b71baa3 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Fri, 20 Oct 2023 22:09:07 -0700 Subject: [PATCH 2204/2212] [wgsl-in] Doc fix for `Lowerer::constructor`. --- src/front/wgsl/lower/construction.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 9ce29aa35..80543d434 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -489,14 +489,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { /// in [`ctx.module`] a suitable Naga `Type` and return a /// [`ConcreteConstructorHandle::Type`] value holding its handle. /// - /// Note that constructing an [`Array`] type may require inserting - /// [`Constant`]s as well as `Type`s into `ctx.module`, to represent the - /// array's length. - /// /// [`Type`]: crate::Type /// [`ctx.module`]: ExpressionContext::module - /// [`Array`]: crate::TypeInner::Array - /// [`Constant`]: crate::Constant fn constructor<'out>( &mut self, constructor: &ast::ConstructorType<'source>, From d10590936b446cce7db1d1105b1ee47ec4fd4be5 Mon Sep 17 00:00:00 2001 From: Zoxc Date: Tue, 24 Oct 2023 11:56:04 +0200 Subject: [PATCH 2205/2212] Don't use layout qualifiers to allow for GLSL 140 support (#2575) --- src/back/glsl/mod.rs | 61 ++++++++++++++++--- ...age-restrict.fragment_shader.Fragment.glsl | 18 +++--- ...k-image-rzsw.fragment_shader.Fragment.glsl | 18 +++--- 3 files changed, 71 insertions(+), 26 deletions(-) diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs index 60431e986..592c72a9a 100644 --- a/src/back/glsl/mod.rs +++ b/src/back/glsl/mod.rs @@ -55,6 +55,7 @@ use std::{ cmp::Ordering, fmt, fmt::{Error as FmtError, Write}, + mem, }; use thiserror::Error; @@ -64,7 +65,7 @@ mod features; mod keywords; /// List of supported `core` GLSL versions. -pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]; +pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[140, 150, 330, 400, 410, 420, 430, 440, 450, 460]; /// List of supported `es` GLSL versions. pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320]; @@ -163,6 +164,10 @@ impl Version { } } + fn supports_io_locations(&self) -> bool { + *self >= Version::Desktop(330) || *self >= Version::new_gles(300) + } + /// Checks if the version supports all of the explicit layouts: /// - `location=` qualifiers for bindings /// - `binding=` qualifiers for resources @@ -285,12 +290,25 @@ pub struct PipelineOptions { pub multiview: Option, } +#[derive(Debug)] +pub struct VaryingLocation { + /// The location of the global. + /// This corresponds to `layout(location = ..)` in GLSL. + pub location: u32, + /// The index which can be used for dual source blending. + /// This corresponds to `layout(index = ..)` in GLSL. + pub index: u32, +} + /// Reflection info for texture mappings and uniforms. +#[derive(Debug)] pub struct ReflectionInfo { /// Mapping between texture names and variables/samplers. pub texture_mapping: crate::FastHashMap, /// Mapping between uniform variables and names. pub uniforms: crate::FastHashMap, String>, + /// Mapping between names and attribute locations. + pub varying: crate::FastHashMap, } /// Mapping between a texture and its sampler, if it exists. @@ -463,6 +481,8 @@ pub struct Writer<'a, W> { need_bake_expressions: back::NeedBakeExpressions, /// How many views to render to, if doing multiview rendering. multiview: Option, + /// Mapping of varying variables to their location. Needed for reflections. + varying: crate::FastHashMap, } impl<'a, W: Write> Writer<'a, W> { @@ -525,6 +545,7 @@ impl<'a, W: Write> Writer<'a, W> { block_id: IdGenerator::default(), named_expressions: Default::default(), need_bake_expressions: Default::default(), + varying: Default::default(), }; // Find all features required to print this module @@ -1006,9 +1027,16 @@ impl<'a, W: Write> Writer<'a, W> { Ic::Storage { format, .. } => ("image", format.into(), "", ""), }; + let precision = if self.options.version.is_es() { + "highp " + } else { + "" + }; + write!( self.out, - "highp {}{}{}{}{}{}", + "{}{}{}{}{}{}{}", + precision, glsl_scalar(kind, 4)?.prefix, base, glsl_dimension(dim), @@ -1367,13 +1395,25 @@ impl<'a, W: Write> Writer<'a, W> { }; // Write the I/O locations, if allowed - if self.options.version.supports_explicit_locations() || !emit_interpolation_and_auxiliary { - if second_blend_source { - write!(self.out, "layout(location = {location}, index = 1) ")?; + let io_location = if self.options.version.supports_explicit_locations() + || !emit_interpolation_and_auxiliary + { + if self.options.version.supports_io_locations() { + if second_blend_source { + write!(self.out, "layout(location = {location}, index = 1) ")?; + } else { + write!(self.out, "layout(location = {location}) ")?; + } + None } else { - write!(self.out, "layout(location = {location}) ")?; + Some(VaryingLocation { + location, + index: second_blend_source as u32, + }) } - } + } else { + None + }; // Write the interpolation qualifier. if let Some(interp) = interpolation { @@ -1417,6 +1457,10 @@ impl<'a, W: Write> Writer<'a, W> { }; writeln!(self.out, " {vname};")?; + if let Some(location) = io_location { + self.varying.insert(vname.to_string(), location); + } + Ok(()) } @@ -4000,7 +4044,7 @@ impl<'a, W: Write> Writer<'a, W> { } /// Helper method used to produce the reflection info that's returned to the user - fn collect_reflection_info(&self) -> Result { + fn collect_reflection_info(&mut self) -> Result { use std::collections::hash_map::Entry; let info = self.info.get_entry_point(self.entry_point_idx as usize); let mut texture_mapping = crate::FastHashMap::default(); @@ -4057,6 +4101,7 @@ impl<'a, W: Write> Writer<'a, W> { Ok(ReflectionInfo { texture_mapping, uniforms, + varying: mem::take(&mut self.varying), }) } } diff --git a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl index cf5a2806f..f582e85ec 100644 --- a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl +++ b/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl @@ -1,22 +1,22 @@ #version 430 core #extension GL_ARB_shader_texture_image_samples : require -uniform highp sampler1D _group_0_binding_0_fs; +uniform sampler1D _group_0_binding_0_fs; -uniform highp sampler2D _group_0_binding_1_fs; +uniform sampler2D _group_0_binding_1_fs; -uniform highp sampler2DArray _group_0_binding_2_fs; +uniform sampler2DArray _group_0_binding_2_fs; -uniform highp sampler3D _group_0_binding_3_fs; +uniform sampler3D _group_0_binding_3_fs; -uniform highp sampler2DMS _group_0_binding_4_fs; +uniform sampler2DMS _group_0_binding_4_fs; -layout(rgba8) writeonly uniform highp image1D _group_0_binding_8_fs; +layout(rgba8) writeonly uniform image1D _group_0_binding_8_fs; -layout(rgba8) writeonly uniform highp image2D _group_0_binding_9_fs; +layout(rgba8) writeonly uniform image2D _group_0_binding_9_fs; -layout(rgba8) writeonly uniform highp image2DArray _group_0_binding_10_fs; +layout(rgba8) writeonly uniform image2DArray _group_0_binding_10_fs; -layout(rgba8) writeonly uniform highp image3D _group_0_binding_11_fs; +layout(rgba8) writeonly uniform image3D _group_0_binding_11_fs; layout(location = 0) out vec4 _fs2p_location0; diff --git a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl index 4a6718e39..b2096add7 100644 --- a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl +++ b/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl @@ -1,22 +1,22 @@ #version 430 core #extension GL_ARB_shader_texture_image_samples : require -uniform highp sampler1D _group_0_binding_0_fs; +uniform sampler1D _group_0_binding_0_fs; -uniform highp sampler2D _group_0_binding_1_fs; +uniform sampler2D _group_0_binding_1_fs; -uniform highp sampler2DArray _group_0_binding_2_fs; +uniform sampler2DArray _group_0_binding_2_fs; -uniform highp sampler3D _group_0_binding_3_fs; +uniform sampler3D _group_0_binding_3_fs; -uniform highp sampler2DMS _group_0_binding_4_fs; +uniform sampler2DMS _group_0_binding_4_fs; -layout(rgba8) writeonly uniform highp image1D _group_0_binding_8_fs; +layout(rgba8) writeonly uniform image1D _group_0_binding_8_fs; -layout(rgba8) writeonly uniform highp image2D _group_0_binding_9_fs; +layout(rgba8) writeonly uniform image2D _group_0_binding_9_fs; -layout(rgba8) writeonly uniform highp image2DArray _group_0_binding_10_fs; +layout(rgba8) writeonly uniform image2DArray _group_0_binding_10_fs; -layout(rgba8) writeonly uniform highp image3D _group_0_binding_11_fs; +layout(rgba8) writeonly uniform image3D _group_0_binding_11_fs; layout(location = 0) out vec4 _fs2p_location0; From 86b6db6f7645c5103f85c7a038a2eb91f97295ab Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 24 Oct 2023 03:04:41 -0700 Subject: [PATCH 2206/2212] [wgsl-in] Let lowering contexts point to a Function directly. (#2580) Change `StatementContext` and `RuntimeExpressionContext` in `front::wgsl::lower` to hold a `&mut crate::Function` reference, rather than separate pointers to individual fields of the `Function`. This replaces three fields with one, and clarifies their relationships. --- src/front/wgsl/lower/mod.rs | 155 ++++++++++++++++++------------------ 1 file changed, 77 insertions(+), 78 deletions(-) diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs index 7a0db365a..236656c45 100644 --- a/src/front/wgsl/lower/mod.rs +++ b/src/front/wgsl/lower/mod.rs @@ -142,12 +142,10 @@ pub struct StatementContext<'source, 'temp, 'out> { const_typifier: &'temp mut Typifier, typifier: &'temp mut Typifier, - variables: &'out mut Arena, - naga_expressions: &'out mut Arena, + function: &'out mut crate::Function, /// Stores the names of expressions that are assigned in `let` statement /// Also stores the spans of the names, for use in errors. named_expressions: &'out mut FastIndexMap, (String, Span)>, - arguments: &'out [crate::FunctionArgument], module: &'out mut crate::Module, /// Which `Expression`s in `self.naga_expressions` are const expressions, in @@ -179,12 +177,10 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { module: self.module, expr_type: ExpressionContextType::Runtime(RuntimeExpressionContext { local_table: self.local_table, - naga_expressions: self.naga_expressions, - local_vars: self.variables, - arguments: self.arguments, - typifier: self.typifier, + function: self.function, block, emitter, + typifier: self.typifier, expression_constness: self.expression_constness, }), } @@ -204,7 +200,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { if let Some(&(_, span)) = self.named_expressions.get(&expr) { InvalidAssignmentType::ImmutableBinding(span) } else { - match self.naga_expressions[expr] { + match self.function.expressions[expr] { crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, crate::Expression::Access { base, .. } => self.invalid_assignment_type(base), crate::Expression::AccessIndex { base, .. } => self.invalid_assignment_type(base), @@ -221,9 +217,7 @@ pub struct RuntimeExpressionContext<'temp, 'out> { /// enclosing statement; see that documentation for details. local_table: &'temp FastHashMap, TypedExpression>, - naga_expressions: &'out mut Arena, - local_vars: &'out Arena, - arguments: &'out [crate::FunctionArgument], + function: &'out mut crate::Function, block: &'temp mut crate::Block, emitter: &'temp mut Emitter, typifier: &'temp mut Typifier, @@ -342,7 +336,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { match self.expr_type { ExpressionContextType::Runtime(ref mut rctx) => ConstantEvaluator::for_wgsl_function( self.module, - rctx.naga_expressions, + &mut rctx.function.expressions, rctx.expression_constness, rctx.emitter, rctx.block, @@ -364,7 +358,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { // long as we're not building `Module::const_expressions`. Err(err) => match self.expr_type { ExpressionContextType::Runtime(ref mut rctx) => { - Ok(rctx.naga_expressions.append(expr, span)) + Ok(rctx.function.expressions.append(expr, span)) } ExpressionContextType::Constant => Err(Error::ConstantEvaluatorError(err, span)), }, @@ -380,7 +374,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { self.module .to_ctx() - .eval_expr_to_u32_from(handle, ctx.naga_expressions) + .eval_expr_to_u32_from(handle, &ctx.function.expressions) .ok() } ExpressionContextType::Constant => self.module.to_ctx().eval_expr_to_u32(handle).ok(), @@ -389,7 +383,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { fn get_expression_span(&self, handle: Handle) -> Span { match self.expr_type { - ExpressionContextType::Runtime(ref ctx) => ctx.naga_expressions.get_span(handle), + ExpressionContextType::Runtime(ref ctx) => ctx.function.expressions.get_span(handle), ExpressionContextType::Constant => self.module.const_expressions.get_span(handle), } } @@ -428,7 +422,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { let index = self .module .to_ctx() - .eval_expr_to_u32_from(expr, rctx.naga_expressions) + .eval_expr_to_u32_from(expr, &rctx.function.expressions) .map_err(|err| match err { crate::proc::U32EvalError::NonConst => { Error::ExpectedConstExprConcreteIntegerScalar(component_span) @@ -478,7 +472,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { /// Resolve the types of all expressions up through `handle`. /// /// Ensure that [`self.typifier`] has a [`TypeResolution`] for - /// every expression in [`self.naga_expressions`]. + /// every expression in [`self.function.expressions`]. /// /// This does not add types to any arena. The [`Typifier`] /// documentation explains the steps we take to avoid filling @@ -499,20 +493,23 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { handle: Handle, ) -> Result<&mut Self, Error<'source>> { let empty_arena = Arena::new(); - let resolve_ctx = match self.expr_type { - ExpressionContextType::Runtime(ref ctx) => { - ResolveContext::with_locals(self.module, ctx.local_vars, ctx.arguments) - } - ExpressionContextType::Constant => { - ResolveContext::with_locals(self.module, &empty_arena, &[]) - } - }; - let (typifier, expressions) = match self.expr_type { + let resolve_ctx; + let typifier; + let expressions; + match self.expr_type { ExpressionContextType::Runtime(ref mut ctx) => { - (&mut *ctx.typifier, &*ctx.naga_expressions) + resolve_ctx = ResolveContext::with_locals( + self.module, + &ctx.function.local_variables, + &ctx.function.arguments, + ); + typifier = &mut *ctx.typifier; + expressions = &ctx.function.expressions; } ExpressionContextType::Constant => { - (&mut *self.const_typifier, &self.module.const_expressions) + resolve_ctx = ResolveContext::with_locals(self.module, &empty_arena, &[]); + typifier = self.const_typifier; + expressions = &self.module.const_expressions; } }; typifier @@ -603,14 +600,14 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { match self.expr_type { ExpressionContextType::Runtime(ref mut rctx) => { rctx.block - .extend(rctx.emitter.finish(rctx.naga_expressions)); + .extend(rctx.emitter.finish(&rctx.function.expressions)); } ExpressionContextType::Constant => {} } let result = self.append_expression(expression, span); match self.expr_type { ExpressionContextType::Runtime(ref mut rctx) => { - rctx.emitter.start(rctx.naga_expressions); + rctx.emitter.start(&rctx.function.expressions); } ExpressionContextType::Constant => {} } @@ -966,7 +963,6 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ctx: &mut GlobalContext<'source, '_, '_>, ) -> Result> { let mut local_table = FastHashMap::default(); - let mut local_variables = Arena::new(); let mut expressions = Arena::new(); let mut named_expressions = FastIndexMap::default(); @@ -1001,6 +997,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }) .transpose()?; + let mut function = crate::Function { + name: Some(f.name.name.to_string()), + arguments, + result, + local_variables: Arena::new(), + expressions, + named_expressions: crate::NamedExpressions::default(), + body: crate::Block::default(), + }; + let mut typifier = Typifier::default(); let mut stmt_ctx = StatementContext { local_table: &mut local_table, @@ -1008,29 +1014,20 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ast_expressions: ctx.ast_expressions, const_typifier: ctx.const_typifier, typifier: &mut typifier, - variables: &mut local_variables, - naga_expressions: &mut expressions, + function: &mut function, named_expressions: &mut named_expressions, types: ctx.types, module: ctx.module, - arguments: &arguments, expression_constness: &mut crate::proc::ExpressionConstnessTracker::new(), }; let mut body = self.block(&f.body, false, &mut stmt_ctx)?; ensure_block_returns(&mut body); - let function = crate::Function { - name: Some(f.name.name.to_string()), - arguments, - result, - local_variables, - expressions, - named_expressions: named_expressions - .into_iter() - .map(|(key, (name, _))| (key, name)) - .collect(), - body, - }; + function.body = body; + function.named_expressions = named_expressions + .into_iter() + .map(|(key, (name, _))| (key, name)) + .collect(); if let Some(ref entry) = f.entry_point { let workgroup_size = if let Some(workgroup_size) = entry.workgroup_size { @@ -1090,7 +1087,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ast::StatementKind::LocalDecl(ref decl) => match *decl { ast::LocalDecl::Let(ref l) => { let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let value = self.expression(l.init, &mut ctx.as_expression(block, &mut emitter))?; @@ -1121,7 +1118,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } } - block.extend(emitter.finish(ctx.naga_expressions)); + block.extend(emitter.finish(&ctx.function.expressions)); ctx.local_table .insert(l.handle, TypedExpression::non_reference(value)); ctx.named_expressions @@ -1131,7 +1128,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::LocalDecl::Var(ref v) => { let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let initializer = match v.init { Some(init) => Some( @@ -1189,7 +1186,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; - let var = ctx.variables.append( + let var = ctx.function.local_variables.append( crate::LocalVariable { name: Some(v.name.name.to_string()), ty, @@ -1202,7 +1199,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { crate::Expression::LocalVariable(var), Span::UNDEFINED, )?; - block.extend(emitter.finish(ctx.naga_expressions)); + block.extend(emitter.finish(&ctx.function.expressions)); ctx.local_table.insert( v.handle, TypedExpression { @@ -1226,11 +1223,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ref reject, } => { let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let condition = self.expression(condition, &mut ctx.as_expression(block, &mut emitter))?; - block.extend(emitter.finish(ctx.naga_expressions)); + block.extend(emitter.finish(&ctx.function.expressions)); let accept = self.block(accept, is_inside_loop, ctx)?; let reject = self.block(reject, is_inside_loop, ctx)?; @@ -1246,14 +1243,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ref cases, } => { let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let mut ectx = ctx.as_expression(block, &mut emitter); let selector = self.expression(selector, &mut ectx)?; let uint = resolve_inner!(ectx, selector).scalar_kind() == Some(crate::ScalarKind::Uint); - block.extend(emitter.finish(ctx.naga_expressions)); + block.extend(emitter.finish(&ctx.function.expressions)); let cases = cases .iter() @@ -1295,11 +1292,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut continuing = self.block(continuing, true, ctx)?; let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let break_if = break_if .map(|expr| self.expression(expr, &mut ctx.as_expression(block, &mut emitter))) .transpose()?; - continuing.extend(emitter.finish(ctx.naga_expressions)); + continuing.extend(emitter.finish(&ctx.function.expressions)); crate::Statement::Loop { body, @@ -1311,12 +1308,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ast::StatementKind::Continue => crate::Statement::Continue, ast::StatementKind::Return { value } => { let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let value = value .map(|expr| self.expression(expr, &mut ctx.as_expression(block, &mut emitter))) .transpose()?; - block.extend(emitter.finish(ctx.naga_expressions)); + block.extend(emitter.finish(&ctx.function.expressions)); crate::Statement::Return { value } } @@ -1326,7 +1323,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ref arguments, } => { let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let _ = self.call( stmt.span, @@ -1334,12 +1331,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { arguments, &mut ctx.as_expression(block, &mut emitter), )?; - block.extend(emitter.finish(ctx.naga_expressions)); + block.extend(emitter.finish(&ctx.function.expressions)); return Ok(()); } ast::StatementKind::Assign { target, op, value } => { let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let expr = self.expression_for_reference( target, @@ -1373,7 +1370,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } None => value, }; - block.extend(emitter.finish(ctx.naga_expressions)); + block.extend(emitter.finish(&ctx.function.expressions)); crate::Statement::Store { pointer: expr.handle, @@ -1382,7 +1379,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::StatementKind::Increment(value) | ast::StatementKind::Decrement(value) => { let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let op = match stmt.kind { ast::StatementKind::Increment(_) => crate::BinaryOperator::Add, @@ -1419,17 +1416,18 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let right = ectx.interrupt_emitter(crate::Expression::Literal(literal), Span::UNDEFINED)?; let rctx = ectx.runtime_expression_ctx(stmt.span)?; - let left = rctx.naga_expressions.append( + let left = rctx.function.expressions.append( crate::Expression::Load { pointer: reference.handle, }, value_span, ); let value = rctx - .naga_expressions + .function + .expressions .append(crate::Expression::Binary { op, left, right }, stmt.span); - block.extend(emitter.finish(ctx.naga_expressions)); + block.extend(emitter.finish(&ctx.function.expressions)); crate::Statement::Store { pointer: reference.handle, value, @@ -1437,10 +1435,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::StatementKind::Ignore(expr) => { let mut emitter = Emitter::default(); - emitter.start(ctx.naga_expressions); + emitter.start(&ctx.function.expressions); let _ = self.expression(expr, &mut ctx.as_expression(block, &mut emitter))?; - block.extend(emitter.finish(ctx.naga_expressions)); + block.extend(emitter.finish(&ctx.function.expressions)); return Ok(()); } }; @@ -1768,12 +1766,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let rctx = ctx.runtime_expression_ctx(span)?; // we need to always do this before a fn call since all arguments need to be emitted before the fn call rctx.block - .extend(rctx.emitter.finish(rctx.naga_expressions)); + .extend(rctx.emitter.finish(&rctx.function.expressions)); let result = has_result.then(|| { - rctx.naga_expressions + rctx.function + .expressions .append(crate::Expression::CallResult(function), span) }); - rctx.emitter.start(rctx.naga_expressions); + rctx.emitter.start(&rctx.function.expressions); rctx.block.push( crate::Statement::Call { function, @@ -1906,8 +1905,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .extend(rctx.emitter.finish(rctx.naga_expressions)); - rctx.emitter.start(rctx.naga_expressions); + .extend(rctx.emitter.finish(&rctx.function.expressions)); + rctx.emitter.start(&rctx.function.expressions); rctx.block .push(crate::Statement::Store { pointer, value }, span); return Ok(None); @@ -2087,8 +2086,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .extend(rctx.emitter.finish(rctx.naga_expressions)); - rctx.emitter.start(rctx.naga_expressions); + .extend(rctx.emitter.finish(&rctx.function.expressions)); + rctx.emitter.start(&rctx.function.expressions); let stmt = crate::Statement::ImageStore { image, coordinate, @@ -2198,8 +2197,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .extend(rctx.emitter.finish(rctx.naga_expressions)); - rctx.emitter.start(rctx.naga_expressions); + .extend(rctx.emitter.finish(&rctx.function.expressions)); + rctx.emitter.start(&rctx.function.expressions); rctx.block .push(crate::Statement::RayQuery { query, fun }, span); return Ok(None); From ada3cd85bb046a220e61be8fd70a98a21c9cda77 Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Tue, 24 Oct 2023 13:49:30 -0700 Subject: [PATCH 2207/2212] [wgsl-in] Unify ConcreteConstructor and ConcreteConstructorHandle. (#2577) Replace the `ConcreteConstructor` and `ConcreteConstructorHandle` types in `front::wgsl::lower::construction` with a single type `Constructor` with a type parameter that determines how it refers to Naga types. --- src/front/wgsl/lower/construction.rs | 183 +++++++++++++++------------ 1 file changed, 100 insertions(+), 83 deletions(-) diff --git a/src/front/wgsl/lower/construction.rs b/src/front/wgsl/lower/construction.rs index 80543d434..912713f91 100644 --- a/src/front/wgsl/lower/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -6,45 +6,57 @@ use crate::{Handle, Span}; use crate::front::wgsl::error::Error; use crate::front::wgsl::lower::{ExpressionContext, Lowerer}; -enum ConcreteConstructorHandle { - PartialVector { - size: crate::VectorSize, - }, +/// A cooked form of `ast::ConstructorType` that uses Naga types whenever +/// possible. +enum Constructor { + /// A vector construction whose component type is inferred from the + /// argument: `vec3(1.0)`. + PartialVector { size: crate::VectorSize }, + + /// A matrix construction whose component type is inferred from the + /// argument: `mat2x2(1,2,3,4)`. PartialMatrix { columns: crate::VectorSize, rows: crate::VectorSize, }, + + /// An array whose component type and size are inferred from the arguments: + /// `array(3,4,5)`. PartialArray, - Type(Handle), + + /// A known Naga type. + /// + /// When we match on this type, we need to see the `TypeInner` here, but at + /// the point that we build this value we'll still need mutable access to + /// the module later. To avoid borrowing from the module, the type parameter + /// `T` is `Handle` initially. Then we use `borrow_inner` to produce a + /// version holding a tuple `(Handle, &TypeInner)`. + Type(T), } -impl ConcreteConstructorHandle { - fn borrow<'a>(&self, module: &'a crate::Module) -> ConcreteConstructor<'a> { - match *self { - Self::PartialVector { size } => ConcreteConstructor::PartialVector { size }, - Self::PartialMatrix { columns, rows } => { - ConcreteConstructor::PartialMatrix { columns, rows } +impl Constructor> { + /// Return an equivalent `Constructor` value that includes borrowed + /// `TypeInner` values alongside any type handles. + /// + /// The returned form is more convenient to match on, since the patterns + /// can actually see what the handle refers to. + fn borrow_inner( + self, + module: &crate::Module, + ) -> Constructor<(Handle, &crate::TypeInner)> { + match self { + Constructor::PartialVector { size } => Constructor::PartialVector { size }, + Constructor::PartialMatrix { columns, rows } => { + Constructor::PartialMatrix { columns, rows } } - Self::PartialArray => ConcreteConstructor::PartialArray, - Self::Type(handle) => ConcreteConstructor::Type(handle, &module.types[handle].inner), + Constructor::PartialArray => Constructor::PartialArray, + Constructor::Type(handle) => Constructor::Type((handle, &module.types[handle].inner)), } } } -enum ConcreteConstructor<'a> { - PartialVector { - size: crate::VectorSize, - }, - PartialMatrix { - columns: crate::VectorSize, - rows: crate::VectorSize, - }, - PartialArray, - Type(Handle, &'a crate::TypeInner), -} - -impl ConcreteConstructorHandle { - fn to_error_string(&self, ctx: &mut ExpressionContext) -> String { +impl Constructor<(Handle, &crate::TypeInner)> { + fn to_error_string(&self, ctx: &ExpressionContext) -> String { match *self { Self::PartialVector { size } => { format!("vec{}", size as u32,) @@ -53,7 +65,7 @@ impl ConcreteConstructorHandle { format!("mat{}x{}", columns as u32, rows as u32,) } Self::PartialArray => "array".to_string(), - Self::Type(ty) => ctx.format_type(ty), + Self::Type((handle, _inner)) => ctx.format_type(handle), } } } @@ -146,15 +158,24 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; - let constructor = constructor_h.borrow(ctx.module); + // Even though we computed `constructor` above, wait until now to borrow + // a reference to the `TypeInner`, so that the component-handling code + // above can have mutable access to the type arena. + let constructor = constructor_h.borrow_inner(ctx.module); let expr = match (components, constructor) { // Empty constructor (Components::None, dst_ty) => match dst_ty { - ConcreteConstructor::Type(ty, _) => { - return ctx.append_expression(crate::Expression::ZeroValue(ty), span) + Constructor::Type((result_ty, _)) => { + return ctx.append_expression(crate::Expression::ZeroValue(result_ty), span) + } + Constructor::PartialVector { .. } + | Constructor::PartialMatrix { .. } + | Constructor::PartialArray => { + // We have no arguments from which to infer the result type, so + // partial constructors aren't acceptable here. + return Err(Error::TypeNotInferrable(ty_span)); } - _ => return Err(Error::TypeNotInferrable(ty_span)), }, // Scalar constructor & conversion (scalar -> scalar) @@ -164,7 +185,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ty_inner: &crate::TypeInner::Scalar { .. }, .. }, - ConcreteConstructor::Type(_, &crate::TypeInner::Scalar { kind, width }), + Constructor::Type((_, &crate::TypeInner::Scalar { kind, width })), ) => crate::Expression::As { expr: component, kind, @@ -178,14 +199,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ty_inner: &crate::TypeInner::Vector { size: src_size, .. }, .. }, - ConcreteConstructor::Type( + Constructor::Type(( _, &crate::TypeInner::Vector { size: dst_size, kind: dst_kind, width: dst_width, }, - ), + )), ) if dst_size == src_size => crate::Expression::As { expr: component, kind: dst_kind, @@ -199,7 +220,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ty_inner: &crate::TypeInner::Vector { size: src_size, .. }, .. }, - ConcreteConstructor::PartialVector { size: dst_size }, + Constructor::PartialVector { size: dst_size }, ) if dst_size == src_size => { // This is a trivial conversion: the sizes match, and a Partial // constructor doesn't specify a scalar type, so nothing can @@ -219,14 +240,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }, .. }, - ConcreteConstructor::Type( + Constructor::Type(( _, &crate::TypeInner::Matrix { columns: dst_columns, rows: dst_rows, width: dst_width, }, - ), + )), ) if dst_columns == src_columns && dst_rows == src_rows => crate::Expression::As { expr: component, kind: crate::ScalarKind::Float, @@ -245,7 +266,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }, .. }, - ConcreteConstructor::PartialMatrix { + Constructor::PartialMatrix { columns: dst_columns, rows: dst_rows, }, @@ -263,7 +284,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ty_inner: &crate::TypeInner::Scalar { .. }, .. }, - ConcreteConstructor::PartialVector { size }, + Constructor::PartialVector { size }, ) => crate::Expression::Splat { size, value: component, @@ -281,14 +302,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }, .. }, - ConcreteConstructor::Type( + Constructor::Type(( _, &crate::TypeInner::Vector { size, kind: dst_kind, width: dst_width, }, - ), + )), ) if dst_kind == src_kind || dst_width == src_width => crate::Expression::Splat { size, value: component, @@ -303,7 +324,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { | &crate::TypeInner::Vector { kind, width, .. }, .. }, - ConcreteConstructor::PartialVector { size }, + Constructor::PartialVector { size }, ) | ( Components::Many { @@ -312,7 +333,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &crate::TypeInner::Scalar { .. } | &crate::TypeInner::Vector { .. }, .. }, - ConcreteConstructor::Type(_, &crate::TypeInner::Vector { size, width, kind }), + Constructor::Type((_, &crate::TypeInner::Vector { size, width, kind })), ) => { let inner = crate::TypeInner::Vector { size, kind, width }; let ty = ctx.ensure_type_exists(inner); @@ -326,7 +347,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { first_component_ty_inner: &crate::TypeInner::Scalar { width, .. }, .. }, - ConcreteConstructor::PartialMatrix { columns, rows }, + Constructor::PartialMatrix { columns, rows }, ) | ( Components::Many { @@ -334,14 +355,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { first_component_ty_inner: &crate::TypeInner::Scalar { .. }, .. }, - ConcreteConstructor::Type( + Constructor::Type(( _, &crate::TypeInner::Matrix { columns, rows, width, }, - ), + )), ) => { let vec_ty = ctx.ensure_type_exists(crate::TypeInner::Vector { width, @@ -377,7 +398,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { first_component_ty_inner: &crate::TypeInner::Vector { width, .. }, .. }, - ConcreteConstructor::PartialMatrix { columns, rows }, + Constructor::PartialMatrix { columns, rows }, ) | ( Components::Many { @@ -385,14 +406,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { first_component_ty_inner: &crate::TypeInner::Vector { .. }, .. }, - ConcreteConstructor::Type( + Constructor::Type(( _, &crate::TypeInner::Matrix { columns, rows, width, }, - ), + )), ) => { let ty = ctx.ensure_type_exists(crate::TypeInner::Matrix { columns, @@ -403,7 +424,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } // Array constructor - infer type - (components, ConcreteConstructor::PartialArray) => { + (components, Constructor::PartialArray) => { let components = components.into_components_vec(); let base = ctx.register_type(components[0])?; @@ -426,10 +447,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // Array or Struct constructor ( components, - ConcreteConstructor::Type( + Constructor::Type(( ty, &crate::TypeInner::Array { .. } | &crate::TypeInner::Struct { .. }, - ), + )), ) => { let components = components.into_components_vec(); crate::Expression::Compose { ty, components } @@ -438,19 +459,19 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // ERRORS // Bad conversion (type cast) - (Components::One { span, ty_inner, .. }, _) => { + (Components::One { span, ty_inner, .. }, constructor) => { let from_type = ctx.format_typeinner(ty_inner); return Err(Error::BadTypeCast { span, from_type, - to_type: constructor_h.to_error_string(ctx), + to_type: constructor.to_error_string(ctx), }); } // Too many parameters for scalar constructor ( Components::Many { spans, .. }, - ConcreteConstructor::Type(_, &crate::TypeInner::Scalar { .. }), + Constructor::Type((_, &crate::TypeInner::Scalar { .. })), ) => { let span = spans[1].until(spans.last().unwrap()); return Err(Error::UnexpectedComponents(span)); @@ -459,12 +480,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // Parameters are of the wrong type for vector or matrix constructor ( Components::Many { spans, .. }, - ConcreteConstructor::Type( + Constructor::Type(( _, &crate::TypeInner::Vector { .. } | &crate::TypeInner::Matrix { .. }, - ) - | ConcreteConstructor::PartialVector { .. } - | ConcreteConstructor::PartialMatrix { .. }, + )) + | Constructor::PartialVector { .. } + | Constructor::PartialMatrix { .. }, ) => { return Err(Error::InvalidConstructorComponentType(spans[0], 0)); } @@ -477,17 +498,15 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok(expr) } - /// Build a Naga IR [`Type`] for `constructor` if there is enough - /// information to do so. + /// Build a [`Constructor`] for a WGSL construction expression. /// - /// For `Partial` variants of [`ast::ConstructorType`], we don't know the - /// component type, so in that case we return the appropriate `Partial` - /// variant of [`ConcreteConstructorHandle`]. + /// If `constructor` conveys enough information to determine which Naga [`Type`] + /// we're actually building (i.e., it's not a partial constructor), then + /// ensure the `Type` exists in [`ctx.module`], and return + /// [`Constructor::Type`]. /// - /// But for the other `ConstructorType` variants, we have everything we need - /// to know to actually produce a Naga IR type. In this case we add to/find - /// in [`ctx.module`] a suitable Naga `Type` and return a - /// [`ConcreteConstructorHandle::Type`] value holding its handle. + /// Otherwise, return the [`Constructor`] partial variant corresponding to + /// `constructor`. /// /// [`Type`]: crate::Type /// [`ctx.module`]: ExpressionContext::module @@ -495,21 +514,19 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, constructor: &ast::ConstructorType<'source>, ctx: &mut ExpressionContext<'source, '_, 'out>, - ) -> Result> { - let c = match *constructor { + ) -> Result>, Error<'source>> { + let handle = match *constructor { ast::ConstructorType::Scalar { width, kind } => { let ty = ctx.ensure_type_exists(crate::TypeInner::Scalar { width, kind }); - ConcreteConstructorHandle::Type(ty) - } - ast::ConstructorType::PartialVector { size } => { - ConcreteConstructorHandle::PartialVector { size } + Constructor::Type(ty) } + ast::ConstructorType::PartialVector { size } => Constructor::PartialVector { size }, ast::ConstructorType::Vector { size, kind, width } => { let ty = ctx.ensure_type_exists(crate::TypeInner::Vector { size, kind, width }); - ConcreteConstructorHandle::Type(ty) + Constructor::Type(ty) } - ast::ConstructorType::PartialMatrix { rows, columns } => { - ConcreteConstructorHandle::PartialMatrix { rows, columns } + ast::ConstructorType::PartialMatrix { columns, rows } => { + Constructor::PartialMatrix { columns, rows } } ast::ConstructorType::Matrix { rows, @@ -521,9 +538,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { rows, width, }); - ConcreteConstructorHandle::Type(ty) + Constructor::Type(ty) } - ast::ConstructorType::PartialArray => ConcreteConstructorHandle::PartialArray, + ast::ConstructorType::PartialArray => Constructor::PartialArray, ast::ConstructorType::Array { base, size } => { let base = self.resolve_ast_type(base, &mut ctx.as_global())?; let size = self.array_size(size, &mut ctx.as_global())?; @@ -532,11 +549,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let stride = self.layouter[base].to_stride(); let ty = ctx.ensure_type_exists(crate::TypeInner::Array { base, size, stride }); - ConcreteConstructorHandle::Type(ty) + Constructor::Type(ty) } - ast::ConstructorType::Type(ty) => ConcreteConstructorHandle::Type(ty), + ast::ConstructorType::Type(ty) => Constructor::Type(ty), }; - Ok(c) + Ok(handle) } } From a1c5f38b538da4457aa831dc8951ad27d43c6c8a Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 25 Oct 2023 14:15:56 +0200 Subject: [PATCH 2208/2212] [glsl-out] remove duplicate version check (#2587) --- src/back/glsl/features.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/back/glsl/features.rs b/src/back/glsl/features.rs index b1fff4d4b..d6f3aae35 100644 --- a/src/back/glsl/features.rs +++ b/src/back/glsl/features.rs @@ -98,7 +98,6 @@ impl FeaturesManager { check_feature!(ARRAY_OF_ARRAYS, 120, 310); check_feature!(IMAGE_LOAD_STORE, 130, 310); check_feature!(CONSERVATIVE_DEPTH, 130, 300); - check_feature!(CONSERVATIVE_DEPTH, 130, 300); check_feature!(NOPERSPECTIVE_QUALIFIER, 130); check_feature!(SAMPLE_QUALIFIER, 400, 320); check_feature!(CLIP_DISTANCE, 130, 300 /* with extension */); From 7acd1aaa5e767b1f7f7a935262eb01381ca91978 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Wed, 25 Oct 2023 18:06:02 +0200 Subject: [PATCH 2209/2212] add 0.14 changelog (#2588) --- CHANGELOG.md | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 86 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6dd01339..da7eb276d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,94 @@ # Change Log -## Unreleased +## v0.14 (2023-10-25) #### GENERAL -- Bump MSRV to 1.65 ([#2420](https://github.com/gfx-rs/naga/pull/2420)) **@jimblandy** +- Add support for const-expressions. ([#2309](https://github.com/gfx-rs/naga/pull/2309)) **@teoxoy**, **@jimblandy** +- Add support for the `rgb10a2uint` storage format. ([#2525](https://github.com/gfx-rs/naga/pull/2525)) **@teoxoy** +- Implement module compaction for snapshot testing and the CLI. ([#2472](https://github.com/gfx-rs/naga/pull/2472)) **@jimblandy** +- Fix validation and GLSL parsing of `ldexp`. ([#2449](https://github.com/gfx-rs/naga/pull/2449)) **@fornwall** +- Add support for dual source blending. ([#2427](https://github.com/gfx-rs/naga/pull/2427)) **@freqmod** +- Bump `indexmap` to v2. ([#2426](https://github.com/gfx-rs/naga/pull/2426)) **@daxpedda** +- Bump MSRV to 1.65. ([#2420](https://github.com/gfx-rs/naga/pull/2420)) **@jimblandy** + +#### API + +- Split `UnaryOperator::Not` into `UnaryOperator::LogicalNot` & `UnaryOperator::BitwiseNot`. ([#2554](https://github.com/gfx-rs/naga/pull/2554)) **@teoxoy** +- Remove `IsFinite` & `IsNormal` relational functions. ([#2532](https://github.com/gfx-rs/naga/pull/2532)) **@teoxoy** +- Derive `PartialEq` on `Expression`. ([#2417](https://github.com/gfx-rs/naga/pull/2417)) **@robtfm** +- Use `FastIndexMap` for `SpecialTypes::predeclared_types`. ([#2495](https://github.com/gfx-rs/naga/pull/2495)) **@jimblandy** + +#### CLI + +- Change `--generate-debug-symbols` from an `option` to a `switch`. ([#2472](https://github.com/gfx-rs/naga/pull/2472)) **@jimblandy** +- Add support for `.{vert,frag,comp}.glsl` files. ([#2462](https://github.com/gfx-rs/naga/pull/2462)) **@eliemichel** + +#### VALIDATOR + +- Require `Capabilities::FLOAT64` for 64-bit floating-point literals. ([#2567](https://github.com/gfx-rs/naga/pull/2567)) **@jimblandy** +- Add `Capabilities::CUBE_ARRAY_TEXTURES`. ([#2530](https://github.com/gfx-rs/naga/pull/2530)) **@teoxoy** +- Disallow passing pointers to variables in the workgroup address space to functions. ([#2507](https://github.com/gfx-rs/naga/pull/2507)) **@teoxoy** +- Avoid OOM with large sparse resource bindings. ([#2561](https://github.com/gfx-rs/naga/pull/2561)) **@teoxoy** +- Require that `Function` and `Private` variables be `CONSTRUCTIBLE`. ([#2545](https://github.com/gfx-rs/naga/pull/2545)) **@jimblandy** +- Disallow floating-point NaNs and infinities. ([#2508](https://github.com/gfx-rs/naga/pull/2508)) **@teoxoy** +- Temporarily disable uniformity analysis for the fragment stage. ([#2515](https://github.com/gfx-rs/naga/pull/2515)) **@teoxoy** +- Validate that `textureSampleBias` is only used in the fragment stage. ([#2515](https://github.com/gfx-rs/naga/pull/2515)) **@teoxoy** +- Validate variable initializer for address spaces. ([#2513](https://github.com/gfx-rs/naga/pull/2513)) **@teoxoy** +- Prevent using multiple push constant variables in one entry point. ([#2484](https://github.com/gfx-rs/naga/pull/2484)) **@andriyDev** +- Validate `binding_array` variable address space. ([#2422](https://github.com/gfx-rs/naga/pull/2422)) **@teoxoy** +- Validate storage buffer access. ([#2415](https://github.com/gfx-rs/naga/pull/2415)) **@teoxoy** + +#### WGSL-IN + +- Fix expected min arg count of `textureLoad`. ([#2584](https://github.com/gfx-rs/naga/pull/2584)) **@teoxoy** +- Turn `Error::Other` into `Error::Internal`, to help devs. ([#2574](https://github.com/gfx-rs/naga/pull/2574)) **@jimblandy** +- Fix OOB typifier indexing. ([#2570](https://github.com/gfx-rs/naga/pull/2570)) **@teoxoy** +- Add support for the `bgra8unorm` storage format. ([#2542](https://github.com/gfx-rs/naga/pull/2542) & [#2550](https://github.com/gfx-rs/naga/pull/2550)) **@nical** +- Remove the `outerProduct` built-in function. ([#2535](https://github.com/gfx-rs/naga/pull/2535)) **@teoxoy** +- Add support for `i32` overload of the `sign` built-in function. ([#2463](https://github.com/gfx-rs/naga/pull/2463)) **@fornwall** +- Properly implement `modf` and `frexp`. ([#2454](https://github.com/gfx-rs/naga/pull/2454)) **@fornwall** +- Add support for scalar overloads of `all` & `any` built-in functions. ([#2445](https://github.com/gfx-rs/naga/pull/2445)) **@fornwall** +- Don't splat the left hand operand of a binary operation if it's not a scalar. ([#2444](https://github.com/gfx-rs/naga/pull/2444)) **@fornwall** +- Avoid splatting all binary operator expressions. ([#2440](https://github.com/gfx-rs/naga/pull/2440)) **@fornwall** +- Error on repeated or missing `@workgroup_size()`. ([#2435](https://github.com/gfx-rs/naga/pull/2435)) **@fornwall** +- Error on repeated attributes. ([#2428](https://github.com/gfx-rs/naga/pull/2428)) **@fornwall** +- Fix error message for invalid `texture{Load,Store}()` on arrayed textures. ([#2432](https://github.com/gfx-rs/naga/pull/2432)) **@fornwall** + +#### SPV-IN + +- Disable `Modf` & `Frexp` and translate `ModfStruct` & `FrexpStruct` to their IR equivalents. ([#2527](https://github.com/gfx-rs/naga/pull/2527)) **@teoxoy** +- Don't advertise support for `Capability::ImageMSArray` & `Capability::InterpolationFunction`. ([#2529](https://github.com/gfx-rs/naga/pull/2529)) **@teoxoy** +- Fix `OpImageQueries` to allow Uints. ([#2404](https://github.com/gfx-rs/naga/pull/2404)) **@evahop** + +#### GLSL-IN + +- Disable `modf` & `frexp`. ([#2527](https://github.com/gfx-rs/naga/pull/2527)) **@teoxoy** + +#### SPV-OUT + +- Require `ClipDistance` & `CullDistance` capabilities if necessary. ([#2528](https://github.com/gfx-rs/naga/pull/2528)) **@teoxoy** +- Change `naga::back::spv::DebugInfo::file_name` to a `&Path`. ([#2501](https://github.com/gfx-rs/naga/pull/2501)) **@jimblandy** +- Always give structs with runtime arrays a `Block` decoration. ([#2455](https://github.com/gfx-rs/naga/pull/2455)) **@TheoDulka** +- Decorate the result of the `OpLoad` with `NonUniform` (not the access chain) when loading images/samplers (resources in the Handle address space). ([#2422](https://github.com/gfx-rs/naga/pull/2422)) **@teoxoy** +- Cache `OpConstantNull`. ([#2414](https://github.com/gfx-rs/naga/pull/2414)) **@evahop** + +#### MSL-OUT + +- Add and fix minimum Metal version checks for optional functionality. ([#2486](https://github.com/gfx-rs/naga/pull/2486)) **@teoxoy** +- Make varyings' struct members unique. ([#2521](https://github.com/gfx-rs/naga/pull/2521)) **@evahop** + +#### GLSL-OUT + +- Cull functions that should not be available for a given stage. ([#2531](https://github.com/gfx-rs/naga/pull/2531)) **@teoxoy** +- Rename identifiers containing double underscores. ([#2510](https://github.com/gfx-rs/naga/pull/2510)) **@evahop** +- Polyfill `frexp`. ([#2504](https://github.com/gfx-rs/naga/pull/2504)) **@evahop** +- Add built-in functions to keywords. ([#2410](https://github.com/gfx-rs/naga/pull/2410)) **@fornwall** + +#### WGSL-OUT + +- Generate correct code for bit complement on integers. ([#2548](https://github.com/gfx-rs/naga/pull/2548)) **@jimblandy** +- Don't include type parameter in splat expressions. ([#2469](https://github.com/gfx-rs/naga/pull/2469)) **@jimblandy** ## v0.13 (2023-07-21) From 95d216bb5764128fa37554f2d0f9f97cf5eb7ccd Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Wed, 25 Oct 2023 13:16:06 -0400 Subject: [PATCH 2210/2212] Bump Versions --- Cargo.toml | 6 +++--- cli/Cargo.toml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0efdd20d1..c74a8cd86 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga" -version = "0.13.0" +version = "0.14.0" authors = ["Naga Developers"] edition = "2021" description = "Shader translation infrastructure" @@ -60,7 +60,7 @@ num-traits = "0.2" spirv = { version = "0.2", optional = true } thiserror = "1.0.21" serde = { version = "1.0.103", features = ["derive"], optional = true } -petgraph = { version ="0.6", optional = true } +petgraph = { version = "0.6", optional = true } pp-rs = { version = "0.2.1", optional = true } hexf-parse = { version = "0.2.1", optional = true } unicode-xid = { version = "0.2.3", optional = true } @@ -70,7 +70,7 @@ bincode = "1" criterion = { version = "0.5", features = [] } diff = "0.1" env_logger = "0.10" -hlsl-snapshots = { path = "./hlsl-snapshots"} +hlsl-snapshots = { path = "./hlsl-snapshots" } # Require at least version 0.7.1 of ron, this version changed how floating points are # serialized by forcing them to always have the decimal part, this makes it backwards # incompatible with our tests because we do a syntatic diff and not a semantic one. diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 1a786ee03..6f7c762fb 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "naga-cli" -version = "0.13.0" +version = "0.14.0" authors = ["Naga Developers"] edition = "2021" description = "Shader translation command line tool" @@ -33,5 +33,5 @@ features = [ "hlsl-out", "dot-out", "serialize", - "deserialize" + "deserialize", ] From 92e41b43e437146b5d946eb238de963be1168016 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Wed, 25 Oct 2023 13:18:06 -0400 Subject: [PATCH 2211/2212] Fix dependency --- cli/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 6f7c762fb..00581905f 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -17,7 +17,7 @@ env_logger = "0.10" argh = "0.1.5" [dependencies.naga] -version = "0.13" +version = "0.14" path = "../" features = [ "validate", From 5369eec3b2ff2888b87ddc0a4e6eeda822bc33ec Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Wed, 25 Oct 2023 14:25:04 -0400 Subject: [PATCH 2212/2212] Move naga to subfolder --- {.cargo => naga/.cargo}/config.toml | 0 .gitattributes => naga/.gitattributes | 0 {.github => naga/.github}/CODEOWNERS | 0 {.github => naga/.github}/workflows/ci.yml | 0 {.github => naga/.github}/workflows/lazy.yml | 0 .../.github}/workflows/validation-linux.yml | 0 .../.github}/workflows/validation-macos.yml | 0 .../.github}/workflows/validation-windows.yml | 0 .gitignore => naga/.gitignore | 0 CHANGELOG.md => naga/CHANGELOG.md | 0 Cargo.toml => naga/Cargo.toml | 0 LICENSE-APACHE => naga/LICENSE-APACHE | 0 LICENSE-MIT => naga/LICENSE-MIT | 0 README.md => naga/README.md | 0 {benches => naga/benches}/criterion.rs | 0 {cli => naga/cli}/Cargo.toml | 0 {cli => naga/cli}/src/bin/naga.rs | 0 codecov.yml => naga/codecov.yml | 0 {fuzz => naga/fuzz}/.gitignore | 0 {fuzz => naga/fuzz}/Cargo.toml | 0 {fuzz => naga/fuzz}/fuzz_targets/glsl_parser.rs | 0 {fuzz => naga/fuzz}/fuzz_targets/ir.rs | 0 {fuzz => naga/fuzz}/fuzz_targets/spv_parser.rs | 0 {fuzz => naga/fuzz}/fuzz_targets/wgsl_parser.rs | 0 {hlsl-snapshots => naga/hlsl-snapshots}/Cargo.toml | 0 {hlsl-snapshots => naga/hlsl-snapshots}/src/lib.rs | 0 {src => naga/src}/arena.rs | 0 {src => naga/src}/back/dot/mod.rs | 0 {src => naga/src}/back/glsl/features.rs | 0 {src => naga/src}/back/glsl/keywords.rs | 0 {src => naga/src}/back/glsl/mod.rs | 0 {src => naga/src}/back/hlsl/conv.rs | 0 {src => naga/src}/back/hlsl/help.rs | 0 {src => naga/src}/back/hlsl/keywords.rs | 0 {src => naga/src}/back/hlsl/mod.rs | 0 {src => naga/src}/back/hlsl/storage.rs | 0 {src => naga/src}/back/hlsl/writer.rs | 0 {src => naga/src}/back/mod.rs | 0 {src => naga/src}/back/msl/keywords.rs | 0 {src => naga/src}/back/msl/mod.rs | 0 {src => naga/src}/back/msl/sampler.rs | 0 {src => naga/src}/back/msl/writer.rs | 0 {src => naga/src}/back/spv/block.rs | 0 {src => naga/src}/back/spv/helpers.rs | 0 {src => naga/src}/back/spv/image.rs | 0 {src => naga/src}/back/spv/index.rs | 0 {src => naga/src}/back/spv/instructions.rs | 0 {src => naga/src}/back/spv/layout.rs | 0 {src => naga/src}/back/spv/mod.rs | 0 {src => naga/src}/back/spv/ray.rs | 0 {src => naga/src}/back/spv/recyclable.rs | 0 {src => naga/src}/back/spv/selection.rs | 0 {src => naga/src}/back/spv/writer.rs | 0 {src => naga/src}/back/wgsl/mod.rs | 0 {src => naga/src}/back/wgsl/writer.rs | 0 {src => naga/src}/block.rs | 0 {src => naga/src}/compact/expressions.rs | 0 {src => naga/src}/compact/functions.rs | 0 {src => naga/src}/compact/handle_set_map.rs | 0 {src => naga/src}/compact/mod.rs | 0 {src => naga/src}/compact/statements.rs | 0 {src => naga/src}/compact/types.rs | 0 {src => naga/src}/front/glsl/ast.rs | 0 {src => naga/src}/front/glsl/builtins.rs | 0 {src => naga/src}/front/glsl/context.rs | 0 {src => naga/src}/front/glsl/error.rs | 0 {src => naga/src}/front/glsl/functions.rs | 0 {src => naga/src}/front/glsl/lex.rs | 0 {src => naga/src}/front/glsl/mod.rs | 0 {src => naga/src}/front/glsl/offset.rs | 0 {src => naga/src}/front/glsl/parser.rs | 0 {src => naga/src}/front/glsl/parser/declarations.rs | 0 {src => naga/src}/front/glsl/parser/expressions.rs | 0 {src => naga/src}/front/glsl/parser/functions.rs | 0 {src => naga/src}/front/glsl/parser/types.rs | 0 {src => naga/src}/front/glsl/parser_tests.rs | 0 {src => naga/src}/front/glsl/token.rs | 0 {src => naga/src}/front/glsl/types.rs | 0 {src => naga/src}/front/glsl/variables.rs | 0 {src => naga/src}/front/interpolator.rs | 0 {src => naga/src}/front/mod.rs | 0 {src => naga/src}/front/spv/convert.rs | 0 {src => naga/src}/front/spv/error.rs | 0 {src => naga/src}/front/spv/function.rs | 0 {src => naga/src}/front/spv/image.rs | 0 {src => naga/src}/front/spv/mod.rs | 0 {src => naga/src}/front/spv/null.rs | 0 {src => naga/src}/front/type_gen.rs | 0 {src => naga/src}/front/wgsl/error.rs | 0 {src => naga/src}/front/wgsl/index.rs | 0 {src => naga/src}/front/wgsl/lower/construction.rs | 0 {src => naga/src}/front/wgsl/lower/mod.rs | 0 {src => naga/src}/front/wgsl/mod.rs | 0 {src => naga/src}/front/wgsl/parse/ast.rs | 0 {src => naga/src}/front/wgsl/parse/conv.rs | 0 {src => naga/src}/front/wgsl/parse/lexer.rs | 0 {src => naga/src}/front/wgsl/parse/mod.rs | 0 {src => naga/src}/front/wgsl/parse/number.rs | 0 {src => naga/src}/front/wgsl/tests.rs | 0 {src => naga/src}/keywords/mod.rs | 0 {src => naga/src}/keywords/wgsl.rs | 0 {src => naga/src}/lib.rs | 0 {src => naga/src}/proc/constant_evaluator.rs | 0 {src => naga/src}/proc/emitter.rs | 0 {src => naga/src}/proc/index.rs | 0 {src => naga/src}/proc/layouter.rs | 0 {src => naga/src}/proc/mod.rs | 0 {src => naga/src}/proc/namer.rs | 0 {src => naga/src}/proc/terminator.rs | 0 {src => naga/src}/proc/typifier.rs | 0 {src => naga/src}/span.rs | 0 {src => naga/src}/valid/analyzer.rs | 0 {src => naga/src}/valid/compose.rs | 0 {src => naga/src}/valid/expression.rs | 0 {src => naga/src}/valid/function.rs | 0 {src => naga/src}/valid/handles.rs | 0 {src => naga/src}/valid/interface.rs | 0 {src => naga/src}/valid/mod.rs | 0 {src => naga/src}/valid/type.rs | 0 {tests => naga/tests}/in/access.param.ron | 0 {tests => naga/tests}/in/access.wgsl | 0 {tests => naga/tests}/in/array-in-ctor.param.ron | 0 {tests => naga/tests}/in/array-in-ctor.wgsl | 0 .../in/array-in-function-return-type.param.ron | 0 .../tests}/in/array-in-function-return-type.wgsl | 0 {tests => naga/tests}/in/atomicCompareExchange.wgsl | 0 {tests => naga/tests}/in/atomicOps.wgsl | 0 {tests => naga/tests}/in/binding-arrays.param.ron | 0 {tests => naga/tests}/in/binding-arrays.wgsl | 0 .../tests}/in/binding-buffer-arrays.param.ron | 0 {tests => naga/tests}/in/binding-buffer-arrays.wgsl | 0 {tests => naga/tests}/in/bitcast.params.ron | 0 {tests => naga/tests}/in/bitcast.wgsl | 0 {tests => naga/tests}/in/bits.param.ron | 0 {tests => naga/tests}/in/bits.wgsl | 0 {tests => naga/tests}/in/boids.param.ron | 0 {tests => naga/tests}/in/boids.wgsl | 0 .../tests}/in/bounds-check-image-restrict.param.ron | 0 .../tests}/in/bounds-check-image-restrict.wgsl | 0 .../tests}/in/bounds-check-image-rzsw.param.ron | 0 .../tests}/in/bounds-check-image-rzsw.wgsl | 0 .../tests}/in/bounds-check-restrict.param.ron | 0 {tests => naga/tests}/in/bounds-check-restrict.wgsl | 0 .../tests}/in/bounds-check-zero-atomic.param.ron | 0 .../tests}/in/bounds-check-zero-atomic.wgsl | 0 .../tests}/in/bounds-check-zero.param.ron | 0 {tests => naga/tests}/in/bounds-check-zero.wgsl | 0 {tests => naga/tests}/in/break-if.wgsl | 0 {tests => naga/tests}/in/collatz.param.ron | 0 {tests => naga/tests}/in/collatz.wgsl | 0 {tests => naga/tests}/in/const-exprs.wgsl | 0 {tests => naga/tests}/in/constructors.param.ron | 0 {tests => naga/tests}/in/constructors.wgsl | 0 {tests => naga/tests}/in/control-flow.param.ron | 0 {tests => naga/tests}/in/control-flow.wgsl | 0 {tests => naga/tests}/in/cubeArrayShadow.wgsl | 0 .../tests}/in/debug-symbol-simple.param.ron | 0 {tests => naga/tests}/in/debug-symbol-simple.wgsl | 0 .../tests}/in/debug-symbol-terrain.param.ron | 0 {tests => naga/tests}/in/debug-symbol-terrain.wgsl | 0 {tests => naga/tests}/in/dualsource.param.ron | 0 {tests => naga/tests}/in/dualsource.wgsl | 0 {tests => naga/tests}/in/empty.param.ron | 0 {tests => naga/tests}/in/empty.wgsl | 0 {tests => naga/tests}/in/extra.param.ron | 0 {tests => naga/tests}/in/extra.wgsl | 0 .../force_point_size_vertex_shader_webgl.param.ron | 0 .../in/force_point_size_vertex_shader_webgl.wgsl | 0 {tests => naga/tests}/in/fragment-output.wgsl | 0 {tests => naga/tests}/in/functions-webgl.param.ron | 0 {tests => naga/tests}/in/functions-webgl.wgsl | 0 {tests => naga/tests}/in/functions.param.ron | 0 {tests => naga/tests}/in/functions.wgsl | 0 {tests => naga/tests}/in/globals.param.ron | 0 {tests => naga/tests}/in/globals.wgsl | 0 .../tests}/in/glsl/210-bevy-2d-shader.frag | 0 .../tests}/in/glsl/210-bevy-2d-shader.vert | 0 {tests => naga/tests}/in/glsl/210-bevy-shader.vert | 0 {tests => naga/tests}/in/glsl/246-collatz.comp | 0 {tests => naga/tests}/in/glsl/277-casting.frag | 0 {tests => naga/tests}/in/glsl/280-matrix-cast.frag | 0 .../tests}/in/glsl/484-preprocessor-if.frag | 0 .../tests}/in/glsl/800-out-of-bounds-panic.vert | 0 .../tests}/in/glsl/896-push-constant.frag | 0 .../tests}/in/glsl/900-implicit-conversions.frag | 0 .../tests}/in/glsl/901-lhs-field-select.frag | 0 .../tests}/in/glsl/931-constant-emitting.frag | 0 {tests => naga/tests}/in/glsl/932-for-loop-if.frag | 0 {tests => naga/tests}/in/glsl/bevy-pbr.frag | 0 {tests => naga/tests}/in/glsl/bevy-pbr.vert | 0 {tests => naga/tests}/in/glsl/bits_glsl.frag | 0 {tests => naga/tests}/in/glsl/bool-select.frag | 0 {tests => naga/tests}/in/glsl/buffer.frag | 0 {tests => naga/tests}/in/glsl/clamp-splat.vert | 0 .../tests}/in/glsl/constant-array-size.frag | 0 {tests => naga/tests}/in/glsl/declarations.frag | 0 {tests => naga/tests}/in/glsl/expressions.frag | 0 {tests => naga/tests}/in/glsl/fma.frag | 0 {tests => naga/tests}/in/glsl/functions_call.frag | 0 .../tests}/in/glsl/global-constant-array.frag | 0 {tests => naga/tests}/in/glsl/images.frag | 0 .../tests}/in/glsl/local-var-init-in-loop.comp | 0 {tests => naga/tests}/in/glsl/long-form-matrix.frag | 0 {tests => naga/tests}/in/glsl/math-functions.frag | 0 {tests => naga/tests}/in/glsl/prepostfix.frag | 0 {tests => naga/tests}/in/glsl/quad_glsl.frag | 0 {tests => naga/tests}/in/glsl/quad_glsl.vert | 0 .../tests}/in/glsl/sampler-functions.frag | 0 {tests => naga/tests}/in/glsl/samplers.frag | 0 {tests => naga/tests}/in/glsl/statements.frag | 0 {tests => naga/tests}/in/glsl/vector-functions.frag | 0 {tests => naga/tests}/in/hlsl-keyword.wgsl | 0 {tests => naga/tests}/in/image.param.ron | 0 {tests => naga/tests}/in/image.wgsl | 0 {tests => naga/tests}/in/interface.param.ron | 0 {tests => naga/tests}/in/interface.wgsl | 0 {tests => naga/tests}/in/interpolate.param.ron | 0 {tests => naga/tests}/in/interpolate.wgsl | 0 {tests => naga/tests}/in/invariant.param.ron | 0 {tests => naga/tests}/in/invariant.wgsl | 0 {tests => naga/tests}/in/lexical-scopes.wgsl | 0 {tests => naga/tests}/in/math-functions.param.ron | 0 {tests => naga/tests}/in/math-functions.wgsl | 0 {tests => naga/tests}/in/module-scope.wgsl | 0 {tests => naga/tests}/in/msl-varyings.wgsl | 0 {tests => naga/tests}/in/multiview.param.ron | 0 {tests => naga/tests}/in/multiview.wgsl | 0 {tests => naga/tests}/in/multiview_webgl.param.ron | 0 {tests => naga/tests}/in/multiview_webgl.wgsl | 0 {tests => naga/tests}/in/operators.param.ron | 0 {tests => naga/tests}/in/operators.wgsl | 0 {tests => naga/tests}/in/padding.param.ron | 0 {tests => naga/tests}/in/padding.wgsl | 0 {tests => naga/tests}/in/pointers.param.ron | 0 {tests => naga/tests}/in/pointers.wgsl | 0 {tests => naga/tests}/in/policy-mix.param.ron | 0 {tests => naga/tests}/in/policy-mix.wgsl | 0 {tests => naga/tests}/in/push-constants.param.ron | 0 {tests => naga/tests}/in/push-constants.wgsl | 0 {tests => naga/tests}/in/quad.param.ron | 0 {tests => naga/tests}/in/quad.wgsl | 0 {tests => naga/tests}/in/ray-query.param.ron | 0 {tests => naga/tests}/in/ray-query.wgsl | 0 .../tests}/in/resource-binding-map.param.ron | 0 {tests => naga/tests}/in/resource-binding-map.wgsl | 0 .../tests}/in/runtime-array-in-unused-struct.wgsl | 0 .../tests}/in/separate-entry-points.param.ron | 0 {tests => naga/tests}/in/separate-entry-points.wgsl | 0 {tests => naga/tests}/in/shadow.param.ron | 0 {tests => naga/tests}/in/shadow.wgsl | 0 {tests => naga/tests}/in/skybox.param.ron | 0 {tests => naga/tests}/in/skybox.wgsl | 0 {tests => naga/tests}/in/sprite.param.ron | 0 {tests => naga/tests}/in/sprite.wgsl | 0 .../tests}/in/spv/binding-arrays.dynamic.spv | Bin .../tests}/in/spv/binding-arrays.dynamic.spvasm | 0 .../tests}/in/spv/binding-arrays.static.spv | Bin .../tests}/in/spv/binding-arrays.static.spvasm | 0 {tests => naga/tests}/in/spv/degrees.spv | Bin {tests => naga/tests}/in/spv/degrees.spvasm | 0 {tests => naga/tests}/in/spv/do-while.spv | Bin {tests => naga/tests}/in/spv/do-while.spvasm | 0 {tests => naga/tests}/in/spv/empty-global-name.spv | Bin .../tests}/in/spv/empty-global-name.spvasm | 0 .../tests}/in/spv/inv-hyperbolic-trig-functions.spv | Bin .../in/spv/inv-hyperbolic-trig-functions.spvasm | 0 {tests => naga/tests}/in/spv/quad-vert.spv | Bin {tests => naga/tests}/in/spv/quad-vert.spvasm | 0 {tests => naga/tests}/in/spv/shadow.spv | Bin {tests => naga/tests}/in/spv/shadow.spvasm | 0 {tests => naga/tests}/in/standard.param.ron | 0 {tests => naga/tests}/in/standard.wgsl | 0 {tests => naga/tests}/in/texture-arg.param.ron | 0 {tests => naga/tests}/in/texture-arg.wgsl | 0 {tests => naga/tests}/in/type-alias.wgsl | 0 {tests => naga/tests}/in/variations.glsl | 0 .../tests}/in/workgroup-uniform-load.wgsl | 0 .../tests}/in/workgroup-var-init.param.ron | 0 {tests => naga/tests}/in/workgroup-var-init.wgsl | 0 {tests => naga/tests}/out/analysis/access.info.ron | 0 {tests => naga/tests}/out/analysis/collatz.info.ron | 0 {tests => naga/tests}/out/analysis/shadow.info.ron | 0 {tests => naga/tests}/out/dot/quad.dot | 0 .../out/glsl/access.assign_through_ptr.Compute.glsl | 0 .../tests}/out/glsl/access.foo_frag.Fragment.glsl | 0 .../tests}/out/glsl/access.foo_vert.Vertex.glsl | 0 .../out/glsl/array-in-ctor.cs_main.Compute.glsl | 0 ...array-in-function-return-type.main.Fragment.glsl | 0 .../tests}/out/glsl/atomicOps.cs_main.Compute.glsl | 0 .../tests}/out/glsl/bitcast.main.Compute.glsl | 0 .../tests}/out/glsl/bits.main.Compute.glsl | 0 .../tests}/out/glsl/boids.main.Compute.glsl | 0 ...eck-image-restrict.fragment_shader.Fragment.glsl | 0 ...s-check-image-rzsw.fragment_shader.Fragment.glsl | 0 .../tests}/out/glsl/break-if.main.Compute.glsl | 0 .../tests}/out/glsl/const-exprs.main.Compute.glsl | 0 .../tests}/out/glsl/constructors.main.Compute.glsl | 0 .../tests}/out/glsl/control-flow.main.Compute.glsl | 0 .../out/glsl/cubeArrayShadow.fragment.Fragment.glsl | 0 .../tests}/out/glsl/do-while.main.Fragment.glsl | 0 .../tests}/out/glsl/dualsource.main.Fragment.glsl | 0 .../tests}/out/glsl/empty.main.Compute.glsl | 0 ...t_size_vertex_shader_webgl.fs_main.Fragment.glsl | 0 ...int_size_vertex_shader_webgl.vs_main.Vertex.glsl | 0 .../fragment-output.main_vec2scalar.Fragment.glsl | 0 .../fragment-output.main_vec4vec3.Fragment.glsl | 0 .../out/glsl/functions-webgl.main.Fragment.glsl | 0 .../tests}/out/glsl/functions.main.Compute.glsl | 0 .../tests}/out/glsl/globals.main.Compute.glsl | 0 .../tests}/out/glsl/image.gather.Fragment.glsl | 0 .../tests}/out/glsl/image.main.Compute.glsl | 0 .../tests}/out/glsl/image.queries.Vertex.glsl | 0 .../out/glsl/image.texture_sample.Fragment.glsl | 0 .../image.texture_sample_comparison.Fragment.glsl | 0 .../out/glsl/interpolate.frag_main.Fragment.glsl | 0 .../out/glsl/interpolate.vert_main.Vertex.glsl | 0 .../tests}/out/glsl/invariant.fs.Fragment.glsl | 0 .../tests}/out/glsl/invariant.vs.Vertex.glsl | 0 .../out/glsl/math-functions.main.Fragment.glsl | 0 .../tests}/out/glsl/multiview.main.Fragment.glsl | 0 .../out/glsl/multiview_webgl.main.Fragment.glsl | 0 .../tests}/out/glsl/operators.main.Compute.glsl | 0 .../tests}/out/glsl/padding.vertex.Vertex.glsl | 0 .../out/glsl/push-constants.main.Fragment.glsl | 0 .../out/glsl/push-constants.vert_main.Vertex.glsl | 0 .../tests}/out/glsl/quad-vert.main.Vertex.glsl | 0 .../tests}/out/glsl/quad.frag_main.Fragment.glsl | 0 .../tests}/out/glsl/quad.fs_extra.Fragment.glsl | 0 .../tests}/out/glsl/quad.vert_main.Vertex.glsl | 0 .../glsl/separate-entry-points.compute.Compute.glsl | 0 .../separate-entry-points.fragment.Fragment.glsl | 0 .../tests}/out/glsl/shadow.fs_main.Fragment.glsl | 0 .../shadow.fs_main_without_storage.Fragment.glsl | 0 .../tests}/out/glsl/shadow.vs_main.Vertex.glsl | 0 .../tests}/out/glsl/skybox.fs_main.Fragment.glsl | 0 .../tests}/out/glsl/skybox.vs_main.Vertex.glsl | 0 .../out/glsl/standard.derivatives.Fragment.glsl | 0 .../tests}/out/glsl/texture-arg.main.Fragment.glsl | 0 .../tests}/out/glsl/variations.main.Fragment.glsl | 0 ...form-load.test_workgroupUniformLoad.Compute.glsl | 0 .../out/glsl/workgroup-var-init.main.Compute.glsl | 0 {tests => naga/tests}/out/hlsl/access.hlsl | 0 {tests => naga/tests}/out/hlsl/access.ron | 0 {tests => naga/tests}/out/hlsl/array-in-ctor.hlsl | 0 {tests => naga/tests}/out/hlsl/array-in-ctor.ron | 0 {tests => naga/tests}/out/hlsl/atomicOps.hlsl | 0 {tests => naga/tests}/out/hlsl/atomicOps.ron | 0 {tests => naga/tests}/out/hlsl/binding-arrays.hlsl | 0 {tests => naga/tests}/out/hlsl/binding-arrays.ron | 0 {tests => naga/tests}/out/hlsl/bitcast.hlsl | 0 {tests => naga/tests}/out/hlsl/bitcast.ron | 0 {tests => naga/tests}/out/hlsl/bits.hlsl | 0 {tests => naga/tests}/out/hlsl/bits.ron | 0 {tests => naga/tests}/out/hlsl/boids.hlsl | 0 {tests => naga/tests}/out/hlsl/boids.ron | 0 {tests => naga/tests}/out/hlsl/break-if.hlsl | 0 {tests => naga/tests}/out/hlsl/break-if.ron | 0 {tests => naga/tests}/out/hlsl/collatz.hlsl | 0 {tests => naga/tests}/out/hlsl/collatz.ron | 0 {tests => naga/tests}/out/hlsl/const-exprs.hlsl | 0 {tests => naga/tests}/out/hlsl/const-exprs.ron | 0 {tests => naga/tests}/out/hlsl/constructors.hlsl | 0 {tests => naga/tests}/out/hlsl/constructors.ron | 0 {tests => naga/tests}/out/hlsl/control-flow.hlsl | 0 {tests => naga/tests}/out/hlsl/control-flow.ron | 0 {tests => naga/tests}/out/hlsl/do-while.hlsl | 0 {tests => naga/tests}/out/hlsl/do-while.ron | 0 {tests => naga/tests}/out/hlsl/dualsource.hlsl | 0 {tests => naga/tests}/out/hlsl/dualsource.ron | 0 .../tests}/out/hlsl/empty-global-name.hlsl | 0 .../tests}/out/hlsl/empty-global-name.ron | 0 {tests => naga/tests}/out/hlsl/empty.hlsl | 0 {tests => naga/tests}/out/hlsl/empty.ron | 0 {tests => naga/tests}/out/hlsl/fragment-output.hlsl | 0 {tests => naga/tests}/out/hlsl/fragment-output.ron | 0 {tests => naga/tests}/out/hlsl/functions.hlsl | 0 {tests => naga/tests}/out/hlsl/functions.ron | 0 {tests => naga/tests}/out/hlsl/globals.hlsl | 0 {tests => naga/tests}/out/hlsl/globals.ron | 0 {tests => naga/tests}/out/hlsl/hlsl-keyword.hlsl | 0 {tests => naga/tests}/out/hlsl/hlsl-keyword.ron | 0 {tests => naga/tests}/out/hlsl/image.hlsl | 0 {tests => naga/tests}/out/hlsl/image.ron | 0 {tests => naga/tests}/out/hlsl/interface.hlsl | 0 {tests => naga/tests}/out/hlsl/interface.ron | 0 {tests => naga/tests}/out/hlsl/interpolate.hlsl | 0 {tests => naga/tests}/out/hlsl/interpolate.ron | 0 .../out/hlsl/inv-hyperbolic-trig-functions.hlsl | 0 .../out/hlsl/inv-hyperbolic-trig-functions.ron | 0 {tests => naga/tests}/out/hlsl/math-functions.hlsl | 0 {tests => naga/tests}/out/hlsl/math-functions.ron | 0 {tests => naga/tests}/out/hlsl/operators.hlsl | 0 {tests => naga/tests}/out/hlsl/operators.ron | 0 {tests => naga/tests}/out/hlsl/padding.hlsl | 0 {tests => naga/tests}/out/hlsl/padding.ron | 0 {tests => naga/tests}/out/hlsl/push-constants.hlsl | 0 {tests => naga/tests}/out/hlsl/push-constants.ron | 0 {tests => naga/tests}/out/hlsl/quad-vert.hlsl | 0 {tests => naga/tests}/out/hlsl/quad-vert.ron | 0 {tests => naga/tests}/out/hlsl/quad.hlsl | 0 {tests => naga/tests}/out/hlsl/quad.ron | 0 {tests => naga/tests}/out/hlsl/shadow.hlsl | 0 {tests => naga/tests}/out/hlsl/shadow.ron | 0 {tests => naga/tests}/out/hlsl/skybox.hlsl | 0 {tests => naga/tests}/out/hlsl/skybox.ron | 0 {tests => naga/tests}/out/hlsl/standard.hlsl | 0 {tests => naga/tests}/out/hlsl/standard.ron | 0 {tests => naga/tests}/out/hlsl/texture-arg.hlsl | 0 {tests => naga/tests}/out/hlsl/texture-arg.ron | 0 .../tests}/out/hlsl/workgroup-uniform-load.hlsl | 0 .../tests}/out/hlsl/workgroup-uniform-load.ron | 0 .../tests}/out/hlsl/workgroup-var-init.hlsl | 0 .../tests}/out/hlsl/workgroup-var-init.ron | 0 {tests => naga/tests}/out/ir/access.compact.ron | 0 {tests => naga/tests}/out/ir/access.ron | 0 {tests => naga/tests}/out/ir/collatz.compact.ron | 0 {tests => naga/tests}/out/ir/collatz.ron | 0 {tests => naga/tests}/out/ir/shadow.compact.ron | 0 {tests => naga/tests}/out/ir/shadow.ron | 0 {tests => naga/tests}/out/msl/access.msl | 0 {tests => naga/tests}/out/msl/array-in-ctor.msl | 0 .../out/msl/array-in-function-return-type.msl | 0 {tests => naga/tests}/out/msl/atomicOps.msl | 0 {tests => naga/tests}/out/msl/binding-arrays.msl | 0 {tests => naga/tests}/out/msl/bitcast.msl | 0 {tests => naga/tests}/out/msl/bits.msl | 0 {tests => naga/tests}/out/msl/boids.msl | 0 .../tests}/out/msl/bounds-check-image-restrict.msl | 0 .../tests}/out/msl/bounds-check-image-rzsw.msl | 0 .../tests}/out/msl/bounds-check-restrict.msl | 0 .../tests}/out/msl/bounds-check-zero-atomic.msl | 0 {tests => naga/tests}/out/msl/bounds-check-zero.msl | 0 {tests => naga/tests}/out/msl/break-if.msl | 0 {tests => naga/tests}/out/msl/collatz.msl | 0 {tests => naga/tests}/out/msl/const-exprs.msl | 0 {tests => naga/tests}/out/msl/constructors.msl | 0 {tests => naga/tests}/out/msl/control-flow.msl | 0 {tests => naga/tests}/out/msl/do-while.msl | 0 {tests => naga/tests}/out/msl/dualsource.msl | 0 {tests => naga/tests}/out/msl/empty-global-name.msl | 0 {tests => naga/tests}/out/msl/empty.msl | 0 {tests => naga/tests}/out/msl/extra.msl | 0 {tests => naga/tests}/out/msl/fragment-output.msl | 0 {tests => naga/tests}/out/msl/functions.msl | 0 {tests => naga/tests}/out/msl/globals.msl | 0 {tests => naga/tests}/out/msl/image.msl | 0 {tests => naga/tests}/out/msl/interface.msl | 0 {tests => naga/tests}/out/msl/interpolate.msl | 0 {tests => naga/tests}/out/msl/math-functions.msl | 0 {tests => naga/tests}/out/msl/msl-varyings.msl | 0 {tests => naga/tests}/out/msl/operators.msl | 0 {tests => naga/tests}/out/msl/padding.msl | 0 {tests => naga/tests}/out/msl/policy-mix.msl | 0 {tests => naga/tests}/out/msl/quad-vert.msl | 0 {tests => naga/tests}/out/msl/quad.msl | 0 {tests => naga/tests}/out/msl/ray-query.msl | 0 .../tests}/out/msl/resource-binding-map.msl | 0 {tests => naga/tests}/out/msl/shadow.msl | 0 {tests => naga/tests}/out/msl/skybox.msl | 0 {tests => naga/tests}/out/msl/standard.msl | 0 {tests => naga/tests}/out/msl/texture-arg.msl | 0 .../tests}/out/msl/workgroup-uniform-load.msl | 0 .../tests}/out/msl/workgroup-var-init.msl | 0 {tests => naga/tests}/out/spv/access.spvasm | 0 {tests => naga/tests}/out/spv/array-in-ctor.spvasm | 0 .../out/spv/array-in-function-return-type.spvasm | 0 .../tests}/out/spv/atomicCompareExchange.spvasm | 0 {tests => naga/tests}/out/spv/atomicOps.spvasm | 0 {tests => naga/tests}/out/spv/binding-arrays.spvasm | 0 .../tests}/out/spv/binding-buffer-arrays.spvasm | 0 {tests => naga/tests}/out/spv/bitcast.spvasm | 0 {tests => naga/tests}/out/spv/bits.spvasm | 0 {tests => naga/tests}/out/spv/boids.spvasm | 0 .../out/spv/bounds-check-image-restrict.spvasm | 0 .../tests}/out/spv/bounds-check-image-rzsw.spvasm | 0 .../tests}/out/spv/bounds-check-restrict.spvasm | 0 .../tests}/out/spv/bounds-check-zero.spvasm | 0 {tests => naga/tests}/out/spv/break-if.spvasm | 0 {tests => naga/tests}/out/spv/collatz.spvasm | 0 {tests => naga/tests}/out/spv/const-exprs.spvasm | 0 {tests => naga/tests}/out/spv/constructors.spvasm | 0 {tests => naga/tests}/out/spv/control-flow.spvasm | 0 .../tests}/out/spv/debug-symbol-simple.spvasm | 0 .../tests}/out/spv/debug-symbol-terrain.spvasm | 0 {tests => naga/tests}/out/spv/dualsource.spvasm | 0 {tests => naga/tests}/out/spv/empty.spvasm | 0 {tests => naga/tests}/out/spv/extra.spvasm | 0 .../tests}/out/spv/fragment-output.spvasm | 0 {tests => naga/tests}/out/spv/functions.spvasm | 0 {tests => naga/tests}/out/spv/globals.spvasm | 0 {tests => naga/tests}/out/spv/image.spvasm | 0 .../tests}/out/spv/interface.compute.spvasm | 0 .../tests}/out/spv/interface.fragment.spvasm | 0 .../tests}/out/spv/interface.vertex.spvasm | 0 .../out/spv/interface.vertex_two_structs.spvasm | 0 {tests => naga/tests}/out/spv/interpolate.spvasm | 0 {tests => naga/tests}/out/spv/math-functions.spvasm | 0 {tests => naga/tests}/out/spv/multiview.spvasm | 0 {tests => naga/tests}/out/spv/operators.spvasm | 0 {tests => naga/tests}/out/spv/padding.spvasm | 0 {tests => naga/tests}/out/spv/pointers.spvasm | 0 {tests => naga/tests}/out/spv/policy-mix.spvasm | 0 {tests => naga/tests}/out/spv/quad.spvasm | 0 {tests => naga/tests}/out/spv/ray-query.spvasm | 0 .../out/spv/runtime-array-in-unused-struct.spvasm | 0 .../out/spv/separate-entry-points.compute.spvasm | 0 .../out/spv/separate-entry-points.fragment.spvasm | 0 {tests => naga/tests}/out/spv/shadow.spvasm | 0 {tests => naga/tests}/out/spv/skybox.spvasm | 0 {tests => naga/tests}/out/spv/sprite.spvasm | 0 {tests => naga/tests}/out/spv/standard.spvasm | 0 {tests => naga/tests}/out/spv/texture-arg.spvasm | 0 .../tests}/out/spv/workgroup-uniform-load.spvasm | 0 .../tests}/out/spv/workgroup-var-init.spvasm | 0 .../tests}/out/wgsl/210-bevy-2d-shader.frag.wgsl | 0 .../tests}/out/wgsl/210-bevy-2d-shader.vert.wgsl | 0 .../tests}/out/wgsl/210-bevy-shader.vert.wgsl | 0 .../tests}/out/wgsl/246-collatz.comp.wgsl | 0 .../tests}/out/wgsl/277-casting.frag.wgsl | 0 .../tests}/out/wgsl/280-matrix-cast.frag.wgsl | 0 .../tests}/out/wgsl/484-preprocessor-if.frag.wgsl | 0 .../out/wgsl/800-out-of-bounds-panic.vert.wgsl | 0 .../tests}/out/wgsl/896-push-constant.frag.wgsl | 0 .../out/wgsl/900-implicit-conversions.frag.wgsl | 0 .../tests}/out/wgsl/901-lhs-field-select.frag.wgsl | 0 .../tests}/out/wgsl/931-constant-emitting.frag.wgsl | 0 .../tests}/out/wgsl/932-for-loop-if.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/access.wgsl | 0 {tests => naga/tests}/out/wgsl/array-in-ctor.wgsl | 0 .../out/wgsl/array-in-function-return-type.wgsl | 0 .../tests}/out/wgsl/atomicCompareExchange.wgsl | 0 {tests => naga/tests}/out/wgsl/atomicOps.wgsl | 0 {tests => naga/tests}/out/wgsl/bevy-pbr.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/bevy-pbr.vert.wgsl | 0 .../tests}/out/wgsl/binding-arrays.dynamic.wgsl | 0 .../tests}/out/wgsl/binding-arrays.static.wgsl | 0 {tests => naga/tests}/out/wgsl/binding-arrays.wgsl | 0 .../tests}/out/wgsl/binding-buffer-arrays.wgsl | 0 {tests => naga/tests}/out/wgsl/bitcast.wgsl | 0 {tests => naga/tests}/out/wgsl/bits.wgsl | 0 {tests => naga/tests}/out/wgsl/bits_glsl.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/boids.wgsl | 0 .../tests}/out/wgsl/bool-select.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/break-if.wgsl | 0 {tests => naga/tests}/out/wgsl/buffer.frag.wgsl | 0 .../tests}/out/wgsl/clamp-splat.vert.wgsl | 0 {tests => naga/tests}/out/wgsl/collatz.wgsl | 0 {tests => naga/tests}/out/wgsl/const-exprs.wgsl | 0 .../tests}/out/wgsl/constant-array-size.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/constructors.wgsl | 0 {tests => naga/tests}/out/wgsl/control-flow.wgsl | 0 .../tests}/out/wgsl/declarations.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/do-while.wgsl | 0 {tests => naga/tests}/out/wgsl/dualsource.wgsl | 0 .../tests}/out/wgsl/empty-global-name.wgsl | 0 {tests => naga/tests}/out/wgsl/empty.wgsl | 0 .../tests}/out/wgsl/expressions.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/extra.wgsl | 0 {tests => naga/tests}/out/wgsl/fma.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/fragment-output.wgsl | 0 {tests => naga/tests}/out/wgsl/functions.wgsl | 0 .../tests}/out/wgsl/functions_call.frag.wgsl | 0 .../tests}/out/wgsl/global-constant-array.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/globals.wgsl | 0 {tests => naga/tests}/out/wgsl/image.wgsl | 0 {tests => naga/tests}/out/wgsl/images.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/interface.wgsl | 0 {tests => naga/tests}/out/wgsl/interpolate.wgsl | 0 .../out/wgsl/inv-hyperbolic-trig-functions.wgsl | 0 {tests => naga/tests}/out/wgsl/lexical-scopes.wgsl | 0 .../out/wgsl/local-var-init-in-loop.comp.wgsl | 0 .../tests}/out/wgsl/long-form-matrix.frag.wgsl | 0 .../tests}/out/wgsl/math-functions.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/math-functions.wgsl | 0 {tests => naga/tests}/out/wgsl/module-scope.wgsl | 0 {tests => naga/tests}/out/wgsl/multiview.wgsl | 0 {tests => naga/tests}/out/wgsl/operators.wgsl | 0 {tests => naga/tests}/out/wgsl/padding.wgsl | 0 {tests => naga/tests}/out/wgsl/pointers.wgsl | 0 {tests => naga/tests}/out/wgsl/prepostfix.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/quad-vert.wgsl | 0 {tests => naga/tests}/out/wgsl/quad.wgsl | 0 {tests => naga/tests}/out/wgsl/quad_glsl.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/quad_glsl.vert.wgsl | 0 .../tests}/out/wgsl/sampler-functions.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/samplers.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/shadow.wgsl | 0 {tests => naga/tests}/out/wgsl/skybox.wgsl | 0 {tests => naga/tests}/out/wgsl/standard.wgsl | 0 {tests => naga/tests}/out/wgsl/statements.frag.wgsl | 0 {tests => naga/tests}/out/wgsl/texture-arg.wgsl | 0 {tests => naga/tests}/out/wgsl/type-alias.wgsl | 0 .../tests}/out/wgsl/vector-functions.frag.wgsl | 0 .../tests}/out/wgsl/workgroup-uniform-load.wgsl | 0 .../tests}/out/wgsl/workgroup-var-init.wgsl | 0 {tests => naga/tests}/snapshots.rs | 0 {tests => naga/tests}/spirv-capabilities.rs | 0 {tests => naga/tests}/wgsl-errors.rs | 0 {xtask => naga/xtask}/.gitignore | 0 {xtask => naga/xtask}/Cargo.lock | 0 {xtask => naga/xtask}/Cargo.toml | 0 {xtask => naga/xtask}/src/cli.rs | 0 {xtask => naga/xtask}/src/fs.rs | 0 {xtask => naga/xtask}/src/glob.rs | 0 {xtask => naga/xtask}/src/main.rs | 0 {xtask => naga/xtask}/src/path.rs | 0 {xtask => naga/xtask}/src/process.rs | 0 {xtask => naga/xtask}/src/result.rs | 0 608 files changed, 0 insertions(+), 0 deletions(-) rename {.cargo => naga/.cargo}/config.toml (100%) rename .gitattributes => naga/.gitattributes (100%) rename {.github => naga/.github}/CODEOWNERS (100%) rename {.github => naga/.github}/workflows/ci.yml (100%) rename {.github => naga/.github}/workflows/lazy.yml (100%) rename {.github => naga/.github}/workflows/validation-linux.yml (100%) rename {.github => naga/.github}/workflows/validation-macos.yml (100%) rename {.github => naga/.github}/workflows/validation-windows.yml (100%) rename .gitignore => naga/.gitignore (100%) rename CHANGELOG.md => naga/CHANGELOG.md (100%) rename Cargo.toml => naga/Cargo.toml (100%) rename LICENSE-APACHE => naga/LICENSE-APACHE (100%) rename LICENSE-MIT => naga/LICENSE-MIT (100%) rename README.md => naga/README.md (100%) rename {benches => naga/benches}/criterion.rs (100%) rename {cli => naga/cli}/Cargo.toml (100%) rename {cli => naga/cli}/src/bin/naga.rs (100%) rename codecov.yml => naga/codecov.yml (100%) rename {fuzz => naga/fuzz}/.gitignore (100%) rename {fuzz => naga/fuzz}/Cargo.toml (100%) rename {fuzz => naga/fuzz}/fuzz_targets/glsl_parser.rs (100%) rename {fuzz => naga/fuzz}/fuzz_targets/ir.rs (100%) rename {fuzz => naga/fuzz}/fuzz_targets/spv_parser.rs (100%) rename {fuzz => naga/fuzz}/fuzz_targets/wgsl_parser.rs (100%) rename {hlsl-snapshots => naga/hlsl-snapshots}/Cargo.toml (100%) rename {hlsl-snapshots => naga/hlsl-snapshots}/src/lib.rs (100%) rename {src => naga/src}/arena.rs (100%) rename {src => naga/src}/back/dot/mod.rs (100%) rename {src => naga/src}/back/glsl/features.rs (100%) rename {src => naga/src}/back/glsl/keywords.rs (100%) rename {src => naga/src}/back/glsl/mod.rs (100%) rename {src => naga/src}/back/hlsl/conv.rs (100%) rename {src => naga/src}/back/hlsl/help.rs (100%) rename {src => naga/src}/back/hlsl/keywords.rs (100%) rename {src => naga/src}/back/hlsl/mod.rs (100%) rename {src => naga/src}/back/hlsl/storage.rs (100%) rename {src => naga/src}/back/hlsl/writer.rs (100%) rename {src => naga/src}/back/mod.rs (100%) rename {src => naga/src}/back/msl/keywords.rs (100%) rename {src => naga/src}/back/msl/mod.rs (100%) rename {src => naga/src}/back/msl/sampler.rs (100%) rename {src => naga/src}/back/msl/writer.rs (100%) rename {src => naga/src}/back/spv/block.rs (100%) rename {src => naga/src}/back/spv/helpers.rs (100%) rename {src => naga/src}/back/spv/image.rs (100%) rename {src => naga/src}/back/spv/index.rs (100%) rename {src => naga/src}/back/spv/instructions.rs (100%) rename {src => naga/src}/back/spv/layout.rs (100%) rename {src => naga/src}/back/spv/mod.rs (100%) rename {src => naga/src}/back/spv/ray.rs (100%) rename {src => naga/src}/back/spv/recyclable.rs (100%) rename {src => naga/src}/back/spv/selection.rs (100%) rename {src => naga/src}/back/spv/writer.rs (100%) rename {src => naga/src}/back/wgsl/mod.rs (100%) rename {src => naga/src}/back/wgsl/writer.rs (100%) rename {src => naga/src}/block.rs (100%) rename {src => naga/src}/compact/expressions.rs (100%) rename {src => naga/src}/compact/functions.rs (100%) rename {src => naga/src}/compact/handle_set_map.rs (100%) rename {src => naga/src}/compact/mod.rs (100%) rename {src => naga/src}/compact/statements.rs (100%) rename {src => naga/src}/compact/types.rs (100%) rename {src => naga/src}/front/glsl/ast.rs (100%) rename {src => naga/src}/front/glsl/builtins.rs (100%) rename {src => naga/src}/front/glsl/context.rs (100%) rename {src => naga/src}/front/glsl/error.rs (100%) rename {src => naga/src}/front/glsl/functions.rs (100%) rename {src => naga/src}/front/glsl/lex.rs (100%) rename {src => naga/src}/front/glsl/mod.rs (100%) rename {src => naga/src}/front/glsl/offset.rs (100%) rename {src => naga/src}/front/glsl/parser.rs (100%) rename {src => naga/src}/front/glsl/parser/declarations.rs (100%) rename {src => naga/src}/front/glsl/parser/expressions.rs (100%) rename {src => naga/src}/front/glsl/parser/functions.rs (100%) rename {src => naga/src}/front/glsl/parser/types.rs (100%) rename {src => naga/src}/front/glsl/parser_tests.rs (100%) rename {src => naga/src}/front/glsl/token.rs (100%) rename {src => naga/src}/front/glsl/types.rs (100%) rename {src => naga/src}/front/glsl/variables.rs (100%) rename {src => naga/src}/front/interpolator.rs (100%) rename {src => naga/src}/front/mod.rs (100%) rename {src => naga/src}/front/spv/convert.rs (100%) rename {src => naga/src}/front/spv/error.rs (100%) rename {src => naga/src}/front/spv/function.rs (100%) rename {src => naga/src}/front/spv/image.rs (100%) rename {src => naga/src}/front/spv/mod.rs (100%) rename {src => naga/src}/front/spv/null.rs (100%) rename {src => naga/src}/front/type_gen.rs (100%) rename {src => naga/src}/front/wgsl/error.rs (100%) rename {src => naga/src}/front/wgsl/index.rs (100%) rename {src => naga/src}/front/wgsl/lower/construction.rs (100%) rename {src => naga/src}/front/wgsl/lower/mod.rs (100%) rename {src => naga/src}/front/wgsl/mod.rs (100%) rename {src => naga/src}/front/wgsl/parse/ast.rs (100%) rename {src => naga/src}/front/wgsl/parse/conv.rs (100%) rename {src => naga/src}/front/wgsl/parse/lexer.rs (100%) rename {src => naga/src}/front/wgsl/parse/mod.rs (100%) rename {src => naga/src}/front/wgsl/parse/number.rs (100%) rename {src => naga/src}/front/wgsl/tests.rs (100%) rename {src => naga/src}/keywords/mod.rs (100%) rename {src => naga/src}/keywords/wgsl.rs (100%) rename {src => naga/src}/lib.rs (100%) rename {src => naga/src}/proc/constant_evaluator.rs (100%) rename {src => naga/src}/proc/emitter.rs (100%) rename {src => naga/src}/proc/index.rs (100%) rename {src => naga/src}/proc/layouter.rs (100%) rename {src => naga/src}/proc/mod.rs (100%) rename {src => naga/src}/proc/namer.rs (100%) rename {src => naga/src}/proc/terminator.rs (100%) rename {src => naga/src}/proc/typifier.rs (100%) rename {src => naga/src}/span.rs (100%) rename {src => naga/src}/valid/analyzer.rs (100%) rename {src => naga/src}/valid/compose.rs (100%) rename {src => naga/src}/valid/expression.rs (100%) rename {src => naga/src}/valid/function.rs (100%) rename {src => naga/src}/valid/handles.rs (100%) rename {src => naga/src}/valid/interface.rs (100%) rename {src => naga/src}/valid/mod.rs (100%) rename {src => naga/src}/valid/type.rs (100%) rename {tests => naga/tests}/in/access.param.ron (100%) rename {tests => naga/tests}/in/access.wgsl (100%) rename {tests => naga/tests}/in/array-in-ctor.param.ron (100%) rename {tests => naga/tests}/in/array-in-ctor.wgsl (100%) rename {tests => naga/tests}/in/array-in-function-return-type.param.ron (100%) rename {tests => naga/tests}/in/array-in-function-return-type.wgsl (100%) rename {tests => naga/tests}/in/atomicCompareExchange.wgsl (100%) rename {tests => naga/tests}/in/atomicOps.wgsl (100%) rename {tests => naga/tests}/in/binding-arrays.param.ron (100%) rename {tests => naga/tests}/in/binding-arrays.wgsl (100%) rename {tests => naga/tests}/in/binding-buffer-arrays.param.ron (100%) rename {tests => naga/tests}/in/binding-buffer-arrays.wgsl (100%) rename {tests => naga/tests}/in/bitcast.params.ron (100%) rename {tests => naga/tests}/in/bitcast.wgsl (100%) rename {tests => naga/tests}/in/bits.param.ron (100%) rename {tests => naga/tests}/in/bits.wgsl (100%) rename {tests => naga/tests}/in/boids.param.ron (100%) rename {tests => naga/tests}/in/boids.wgsl (100%) rename {tests => naga/tests}/in/bounds-check-image-restrict.param.ron (100%) rename {tests => naga/tests}/in/bounds-check-image-restrict.wgsl (100%) rename {tests => naga/tests}/in/bounds-check-image-rzsw.param.ron (100%) rename {tests => naga/tests}/in/bounds-check-image-rzsw.wgsl (100%) rename {tests => naga/tests}/in/bounds-check-restrict.param.ron (100%) rename {tests => naga/tests}/in/bounds-check-restrict.wgsl (100%) rename {tests => naga/tests}/in/bounds-check-zero-atomic.param.ron (100%) rename {tests => naga/tests}/in/bounds-check-zero-atomic.wgsl (100%) rename {tests => naga/tests}/in/bounds-check-zero.param.ron (100%) rename {tests => naga/tests}/in/bounds-check-zero.wgsl (100%) rename {tests => naga/tests}/in/break-if.wgsl (100%) rename {tests => naga/tests}/in/collatz.param.ron (100%) rename {tests => naga/tests}/in/collatz.wgsl (100%) rename {tests => naga/tests}/in/const-exprs.wgsl (100%) rename {tests => naga/tests}/in/constructors.param.ron (100%) rename {tests => naga/tests}/in/constructors.wgsl (100%) rename {tests => naga/tests}/in/control-flow.param.ron (100%) rename {tests => naga/tests}/in/control-flow.wgsl (100%) rename {tests => naga/tests}/in/cubeArrayShadow.wgsl (100%) rename {tests => naga/tests}/in/debug-symbol-simple.param.ron (100%) rename {tests => naga/tests}/in/debug-symbol-simple.wgsl (100%) rename {tests => naga/tests}/in/debug-symbol-terrain.param.ron (100%) rename {tests => naga/tests}/in/debug-symbol-terrain.wgsl (100%) rename {tests => naga/tests}/in/dualsource.param.ron (100%) rename {tests => naga/tests}/in/dualsource.wgsl (100%) rename {tests => naga/tests}/in/empty.param.ron (100%) rename {tests => naga/tests}/in/empty.wgsl (100%) rename {tests => naga/tests}/in/extra.param.ron (100%) rename {tests => naga/tests}/in/extra.wgsl (100%) rename {tests => naga/tests}/in/force_point_size_vertex_shader_webgl.param.ron (100%) rename {tests => naga/tests}/in/force_point_size_vertex_shader_webgl.wgsl (100%) rename {tests => naga/tests}/in/fragment-output.wgsl (100%) rename {tests => naga/tests}/in/functions-webgl.param.ron (100%) rename {tests => naga/tests}/in/functions-webgl.wgsl (100%) rename {tests => naga/tests}/in/functions.param.ron (100%) rename {tests => naga/tests}/in/functions.wgsl (100%) rename {tests => naga/tests}/in/globals.param.ron (100%) rename {tests => naga/tests}/in/globals.wgsl (100%) rename {tests => naga/tests}/in/glsl/210-bevy-2d-shader.frag (100%) rename {tests => naga/tests}/in/glsl/210-bevy-2d-shader.vert (100%) rename {tests => naga/tests}/in/glsl/210-bevy-shader.vert (100%) rename {tests => naga/tests}/in/glsl/246-collatz.comp (100%) rename {tests => naga/tests}/in/glsl/277-casting.frag (100%) rename {tests => naga/tests}/in/glsl/280-matrix-cast.frag (100%) rename {tests => naga/tests}/in/glsl/484-preprocessor-if.frag (100%) rename {tests => naga/tests}/in/glsl/800-out-of-bounds-panic.vert (100%) rename {tests => naga/tests}/in/glsl/896-push-constant.frag (100%) rename {tests => naga/tests}/in/glsl/900-implicit-conversions.frag (100%) rename {tests => naga/tests}/in/glsl/901-lhs-field-select.frag (100%) rename {tests => naga/tests}/in/glsl/931-constant-emitting.frag (100%) rename {tests => naga/tests}/in/glsl/932-for-loop-if.frag (100%) rename {tests => naga/tests}/in/glsl/bevy-pbr.frag (100%) rename {tests => naga/tests}/in/glsl/bevy-pbr.vert (100%) rename {tests => naga/tests}/in/glsl/bits_glsl.frag (100%) rename {tests => naga/tests}/in/glsl/bool-select.frag (100%) rename {tests => naga/tests}/in/glsl/buffer.frag (100%) rename {tests => naga/tests}/in/glsl/clamp-splat.vert (100%) rename {tests => naga/tests}/in/glsl/constant-array-size.frag (100%) rename {tests => naga/tests}/in/glsl/declarations.frag (100%) rename {tests => naga/tests}/in/glsl/expressions.frag (100%) rename {tests => naga/tests}/in/glsl/fma.frag (100%) rename {tests => naga/tests}/in/glsl/functions_call.frag (100%) rename {tests => naga/tests}/in/glsl/global-constant-array.frag (100%) rename {tests => naga/tests}/in/glsl/images.frag (100%) rename {tests => naga/tests}/in/glsl/local-var-init-in-loop.comp (100%) rename {tests => naga/tests}/in/glsl/long-form-matrix.frag (100%) rename {tests => naga/tests}/in/glsl/math-functions.frag (100%) rename {tests => naga/tests}/in/glsl/prepostfix.frag (100%) rename {tests => naga/tests}/in/glsl/quad_glsl.frag (100%) rename {tests => naga/tests}/in/glsl/quad_glsl.vert (100%) rename {tests => naga/tests}/in/glsl/sampler-functions.frag (100%) rename {tests => naga/tests}/in/glsl/samplers.frag (100%) rename {tests => naga/tests}/in/glsl/statements.frag (100%) rename {tests => naga/tests}/in/glsl/vector-functions.frag (100%) rename {tests => naga/tests}/in/hlsl-keyword.wgsl (100%) rename {tests => naga/tests}/in/image.param.ron (100%) rename {tests => naga/tests}/in/image.wgsl (100%) rename {tests => naga/tests}/in/interface.param.ron (100%) rename {tests => naga/tests}/in/interface.wgsl (100%) rename {tests => naga/tests}/in/interpolate.param.ron (100%) rename {tests => naga/tests}/in/interpolate.wgsl (100%) rename {tests => naga/tests}/in/invariant.param.ron (100%) rename {tests => naga/tests}/in/invariant.wgsl (100%) rename {tests => naga/tests}/in/lexical-scopes.wgsl (100%) rename {tests => naga/tests}/in/math-functions.param.ron (100%) rename {tests => naga/tests}/in/math-functions.wgsl (100%) rename {tests => naga/tests}/in/module-scope.wgsl (100%) rename {tests => naga/tests}/in/msl-varyings.wgsl (100%) rename {tests => naga/tests}/in/multiview.param.ron (100%) rename {tests => naga/tests}/in/multiview.wgsl (100%) rename {tests => naga/tests}/in/multiview_webgl.param.ron (100%) rename {tests => naga/tests}/in/multiview_webgl.wgsl (100%) rename {tests => naga/tests}/in/operators.param.ron (100%) rename {tests => naga/tests}/in/operators.wgsl (100%) rename {tests => naga/tests}/in/padding.param.ron (100%) rename {tests => naga/tests}/in/padding.wgsl (100%) rename {tests => naga/tests}/in/pointers.param.ron (100%) rename {tests => naga/tests}/in/pointers.wgsl (100%) rename {tests => naga/tests}/in/policy-mix.param.ron (100%) rename {tests => naga/tests}/in/policy-mix.wgsl (100%) rename {tests => naga/tests}/in/push-constants.param.ron (100%) rename {tests => naga/tests}/in/push-constants.wgsl (100%) rename {tests => naga/tests}/in/quad.param.ron (100%) rename {tests => naga/tests}/in/quad.wgsl (100%) rename {tests => naga/tests}/in/ray-query.param.ron (100%) rename {tests => naga/tests}/in/ray-query.wgsl (100%) rename {tests => naga/tests}/in/resource-binding-map.param.ron (100%) rename {tests => naga/tests}/in/resource-binding-map.wgsl (100%) rename {tests => naga/tests}/in/runtime-array-in-unused-struct.wgsl (100%) rename {tests => naga/tests}/in/separate-entry-points.param.ron (100%) rename {tests => naga/tests}/in/separate-entry-points.wgsl (100%) rename {tests => naga/tests}/in/shadow.param.ron (100%) rename {tests => naga/tests}/in/shadow.wgsl (100%) rename {tests => naga/tests}/in/skybox.param.ron (100%) rename {tests => naga/tests}/in/skybox.wgsl (100%) rename {tests => naga/tests}/in/sprite.param.ron (100%) rename {tests => naga/tests}/in/sprite.wgsl (100%) rename {tests => naga/tests}/in/spv/binding-arrays.dynamic.spv (100%) rename {tests => naga/tests}/in/spv/binding-arrays.dynamic.spvasm (100%) rename {tests => naga/tests}/in/spv/binding-arrays.static.spv (100%) rename {tests => naga/tests}/in/spv/binding-arrays.static.spvasm (100%) rename {tests => naga/tests}/in/spv/degrees.spv (100%) rename {tests => naga/tests}/in/spv/degrees.spvasm (100%) rename {tests => naga/tests}/in/spv/do-while.spv (100%) rename {tests => naga/tests}/in/spv/do-while.spvasm (100%) rename {tests => naga/tests}/in/spv/empty-global-name.spv (100%) rename {tests => naga/tests}/in/spv/empty-global-name.spvasm (100%) rename {tests => naga/tests}/in/spv/inv-hyperbolic-trig-functions.spv (100%) rename {tests => naga/tests}/in/spv/inv-hyperbolic-trig-functions.spvasm (100%) rename {tests => naga/tests}/in/spv/quad-vert.spv (100%) rename {tests => naga/tests}/in/spv/quad-vert.spvasm (100%) rename {tests => naga/tests}/in/spv/shadow.spv (100%) rename {tests => naga/tests}/in/spv/shadow.spvasm (100%) rename {tests => naga/tests}/in/standard.param.ron (100%) rename {tests => naga/tests}/in/standard.wgsl (100%) rename {tests => naga/tests}/in/texture-arg.param.ron (100%) rename {tests => naga/tests}/in/texture-arg.wgsl (100%) rename {tests => naga/tests}/in/type-alias.wgsl (100%) rename {tests => naga/tests}/in/variations.glsl (100%) rename {tests => naga/tests}/in/workgroup-uniform-load.wgsl (100%) rename {tests => naga/tests}/in/workgroup-var-init.param.ron (100%) rename {tests => naga/tests}/in/workgroup-var-init.wgsl (100%) rename {tests => naga/tests}/out/analysis/access.info.ron (100%) rename {tests => naga/tests}/out/analysis/collatz.info.ron (100%) rename {tests => naga/tests}/out/analysis/shadow.info.ron (100%) rename {tests => naga/tests}/out/dot/quad.dot (100%) rename {tests => naga/tests}/out/glsl/access.assign_through_ptr.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/access.foo_frag.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/access.foo_vert.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/array-in-ctor.cs_main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/array-in-function-return-type.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/atomicOps.cs_main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/bitcast.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/bits.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/boids.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/break-if.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/const-exprs.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/constructors.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/control-flow.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/cubeArrayShadow.fragment.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/do-while.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/dualsource.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/empty.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/force_point_size_vertex_shader_webgl.fs_main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/force_point_size_vertex_shader_webgl.vs_main.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/fragment-output.main_vec2scalar.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/fragment-output.main_vec4vec3.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/functions-webgl.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/functions.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/globals.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/image.gather.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/image.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/image.queries.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/image.texture_sample.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/image.texture_sample_comparison.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/interpolate.frag_main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/interpolate.vert_main.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/invariant.fs.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/invariant.vs.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/math-functions.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/multiview.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/multiview_webgl.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/operators.main.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/padding.vertex.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/push-constants.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/push-constants.vert_main.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/quad-vert.main.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/quad.frag_main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/quad.fs_extra.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/quad.vert_main.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/separate-entry-points.compute.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/separate-entry-points.fragment.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/shadow.fs_main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/shadow.fs_main_without_storage.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/shadow.vs_main.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/skybox.fs_main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/skybox.vs_main.Vertex.glsl (100%) rename {tests => naga/tests}/out/glsl/standard.derivatives.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/texture-arg.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/variations.main.Fragment.glsl (100%) rename {tests => naga/tests}/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl (100%) rename {tests => naga/tests}/out/glsl/workgroup-var-init.main.Compute.glsl (100%) rename {tests => naga/tests}/out/hlsl/access.hlsl (100%) rename {tests => naga/tests}/out/hlsl/access.ron (100%) rename {tests => naga/tests}/out/hlsl/array-in-ctor.hlsl (100%) rename {tests => naga/tests}/out/hlsl/array-in-ctor.ron (100%) rename {tests => naga/tests}/out/hlsl/atomicOps.hlsl (100%) rename {tests => naga/tests}/out/hlsl/atomicOps.ron (100%) rename {tests => naga/tests}/out/hlsl/binding-arrays.hlsl (100%) rename {tests => naga/tests}/out/hlsl/binding-arrays.ron (100%) rename {tests => naga/tests}/out/hlsl/bitcast.hlsl (100%) rename {tests => naga/tests}/out/hlsl/bitcast.ron (100%) rename {tests => naga/tests}/out/hlsl/bits.hlsl (100%) rename {tests => naga/tests}/out/hlsl/bits.ron (100%) rename {tests => naga/tests}/out/hlsl/boids.hlsl (100%) rename {tests => naga/tests}/out/hlsl/boids.ron (100%) rename {tests => naga/tests}/out/hlsl/break-if.hlsl (100%) rename {tests => naga/tests}/out/hlsl/break-if.ron (100%) rename {tests => naga/tests}/out/hlsl/collatz.hlsl (100%) rename {tests => naga/tests}/out/hlsl/collatz.ron (100%) rename {tests => naga/tests}/out/hlsl/const-exprs.hlsl (100%) rename {tests => naga/tests}/out/hlsl/const-exprs.ron (100%) rename {tests => naga/tests}/out/hlsl/constructors.hlsl (100%) rename {tests => naga/tests}/out/hlsl/constructors.ron (100%) rename {tests => naga/tests}/out/hlsl/control-flow.hlsl (100%) rename {tests => naga/tests}/out/hlsl/control-flow.ron (100%) rename {tests => naga/tests}/out/hlsl/do-while.hlsl (100%) rename {tests => naga/tests}/out/hlsl/do-while.ron (100%) rename {tests => naga/tests}/out/hlsl/dualsource.hlsl (100%) rename {tests => naga/tests}/out/hlsl/dualsource.ron (100%) rename {tests => naga/tests}/out/hlsl/empty-global-name.hlsl (100%) rename {tests => naga/tests}/out/hlsl/empty-global-name.ron (100%) rename {tests => naga/tests}/out/hlsl/empty.hlsl (100%) rename {tests => naga/tests}/out/hlsl/empty.ron (100%) rename {tests => naga/tests}/out/hlsl/fragment-output.hlsl (100%) rename {tests => naga/tests}/out/hlsl/fragment-output.ron (100%) rename {tests => naga/tests}/out/hlsl/functions.hlsl (100%) rename {tests => naga/tests}/out/hlsl/functions.ron (100%) rename {tests => naga/tests}/out/hlsl/globals.hlsl (100%) rename {tests => naga/tests}/out/hlsl/globals.ron (100%) rename {tests => naga/tests}/out/hlsl/hlsl-keyword.hlsl (100%) rename {tests => naga/tests}/out/hlsl/hlsl-keyword.ron (100%) rename {tests => naga/tests}/out/hlsl/image.hlsl (100%) rename {tests => naga/tests}/out/hlsl/image.ron (100%) rename {tests => naga/tests}/out/hlsl/interface.hlsl (100%) rename {tests => naga/tests}/out/hlsl/interface.ron (100%) rename {tests => naga/tests}/out/hlsl/interpolate.hlsl (100%) rename {tests => naga/tests}/out/hlsl/interpolate.ron (100%) rename {tests => naga/tests}/out/hlsl/inv-hyperbolic-trig-functions.hlsl (100%) rename {tests => naga/tests}/out/hlsl/inv-hyperbolic-trig-functions.ron (100%) rename {tests => naga/tests}/out/hlsl/math-functions.hlsl (100%) rename {tests => naga/tests}/out/hlsl/math-functions.ron (100%) rename {tests => naga/tests}/out/hlsl/operators.hlsl (100%) rename {tests => naga/tests}/out/hlsl/operators.ron (100%) rename {tests => naga/tests}/out/hlsl/padding.hlsl (100%) rename {tests => naga/tests}/out/hlsl/padding.ron (100%) rename {tests => naga/tests}/out/hlsl/push-constants.hlsl (100%) rename {tests => naga/tests}/out/hlsl/push-constants.ron (100%) rename {tests => naga/tests}/out/hlsl/quad-vert.hlsl (100%) rename {tests => naga/tests}/out/hlsl/quad-vert.ron (100%) rename {tests => naga/tests}/out/hlsl/quad.hlsl (100%) rename {tests => naga/tests}/out/hlsl/quad.ron (100%) rename {tests => naga/tests}/out/hlsl/shadow.hlsl (100%) rename {tests => naga/tests}/out/hlsl/shadow.ron (100%) rename {tests => naga/tests}/out/hlsl/skybox.hlsl (100%) rename {tests => naga/tests}/out/hlsl/skybox.ron (100%) rename {tests => naga/tests}/out/hlsl/standard.hlsl (100%) rename {tests => naga/tests}/out/hlsl/standard.ron (100%) rename {tests => naga/tests}/out/hlsl/texture-arg.hlsl (100%) rename {tests => naga/tests}/out/hlsl/texture-arg.ron (100%) rename {tests => naga/tests}/out/hlsl/workgroup-uniform-load.hlsl (100%) rename {tests => naga/tests}/out/hlsl/workgroup-uniform-load.ron (100%) rename {tests => naga/tests}/out/hlsl/workgroup-var-init.hlsl (100%) rename {tests => naga/tests}/out/hlsl/workgroup-var-init.ron (100%) rename {tests => naga/tests}/out/ir/access.compact.ron (100%) rename {tests => naga/tests}/out/ir/access.ron (100%) rename {tests => naga/tests}/out/ir/collatz.compact.ron (100%) rename {tests => naga/tests}/out/ir/collatz.ron (100%) rename {tests => naga/tests}/out/ir/shadow.compact.ron (100%) rename {tests => naga/tests}/out/ir/shadow.ron (100%) rename {tests => naga/tests}/out/msl/access.msl (100%) rename {tests => naga/tests}/out/msl/array-in-ctor.msl (100%) rename {tests => naga/tests}/out/msl/array-in-function-return-type.msl (100%) rename {tests => naga/tests}/out/msl/atomicOps.msl (100%) rename {tests => naga/tests}/out/msl/binding-arrays.msl (100%) rename {tests => naga/tests}/out/msl/bitcast.msl (100%) rename {tests => naga/tests}/out/msl/bits.msl (100%) rename {tests => naga/tests}/out/msl/boids.msl (100%) rename {tests => naga/tests}/out/msl/bounds-check-image-restrict.msl (100%) rename {tests => naga/tests}/out/msl/bounds-check-image-rzsw.msl (100%) rename {tests => naga/tests}/out/msl/bounds-check-restrict.msl (100%) rename {tests => naga/tests}/out/msl/bounds-check-zero-atomic.msl (100%) rename {tests => naga/tests}/out/msl/bounds-check-zero.msl (100%) rename {tests => naga/tests}/out/msl/break-if.msl (100%) rename {tests => naga/tests}/out/msl/collatz.msl (100%) rename {tests => naga/tests}/out/msl/const-exprs.msl (100%) rename {tests => naga/tests}/out/msl/constructors.msl (100%) rename {tests => naga/tests}/out/msl/control-flow.msl (100%) rename {tests => naga/tests}/out/msl/do-while.msl (100%) rename {tests => naga/tests}/out/msl/dualsource.msl (100%) rename {tests => naga/tests}/out/msl/empty-global-name.msl (100%) rename {tests => naga/tests}/out/msl/empty.msl (100%) rename {tests => naga/tests}/out/msl/extra.msl (100%) rename {tests => naga/tests}/out/msl/fragment-output.msl (100%) rename {tests => naga/tests}/out/msl/functions.msl (100%) rename {tests => naga/tests}/out/msl/globals.msl (100%) rename {tests => naga/tests}/out/msl/image.msl (100%) rename {tests => naga/tests}/out/msl/interface.msl (100%) rename {tests => naga/tests}/out/msl/interpolate.msl (100%) rename {tests => naga/tests}/out/msl/math-functions.msl (100%) rename {tests => naga/tests}/out/msl/msl-varyings.msl (100%) rename {tests => naga/tests}/out/msl/operators.msl (100%) rename {tests => naga/tests}/out/msl/padding.msl (100%) rename {tests => naga/tests}/out/msl/policy-mix.msl (100%) rename {tests => naga/tests}/out/msl/quad-vert.msl (100%) rename {tests => naga/tests}/out/msl/quad.msl (100%) rename {tests => naga/tests}/out/msl/ray-query.msl (100%) rename {tests => naga/tests}/out/msl/resource-binding-map.msl (100%) rename {tests => naga/tests}/out/msl/shadow.msl (100%) rename {tests => naga/tests}/out/msl/skybox.msl (100%) rename {tests => naga/tests}/out/msl/standard.msl (100%) rename {tests => naga/tests}/out/msl/texture-arg.msl (100%) rename {tests => naga/tests}/out/msl/workgroup-uniform-load.msl (100%) rename {tests => naga/tests}/out/msl/workgroup-var-init.msl (100%) rename {tests => naga/tests}/out/spv/access.spvasm (100%) rename {tests => naga/tests}/out/spv/array-in-ctor.spvasm (100%) rename {tests => naga/tests}/out/spv/array-in-function-return-type.spvasm (100%) rename {tests => naga/tests}/out/spv/atomicCompareExchange.spvasm (100%) rename {tests => naga/tests}/out/spv/atomicOps.spvasm (100%) rename {tests => naga/tests}/out/spv/binding-arrays.spvasm (100%) rename {tests => naga/tests}/out/spv/binding-buffer-arrays.spvasm (100%) rename {tests => naga/tests}/out/spv/bitcast.spvasm (100%) rename {tests => naga/tests}/out/spv/bits.spvasm (100%) rename {tests => naga/tests}/out/spv/boids.spvasm (100%) rename {tests => naga/tests}/out/spv/bounds-check-image-restrict.spvasm (100%) rename {tests => naga/tests}/out/spv/bounds-check-image-rzsw.spvasm (100%) rename {tests => naga/tests}/out/spv/bounds-check-restrict.spvasm (100%) rename {tests => naga/tests}/out/spv/bounds-check-zero.spvasm (100%) rename {tests => naga/tests}/out/spv/break-if.spvasm (100%) rename {tests => naga/tests}/out/spv/collatz.spvasm (100%) rename {tests => naga/tests}/out/spv/const-exprs.spvasm (100%) rename {tests => naga/tests}/out/spv/constructors.spvasm (100%) rename {tests => naga/tests}/out/spv/control-flow.spvasm (100%) rename {tests => naga/tests}/out/spv/debug-symbol-simple.spvasm (100%) rename {tests => naga/tests}/out/spv/debug-symbol-terrain.spvasm (100%) rename {tests => naga/tests}/out/spv/dualsource.spvasm (100%) rename {tests => naga/tests}/out/spv/empty.spvasm (100%) rename {tests => naga/tests}/out/spv/extra.spvasm (100%) rename {tests => naga/tests}/out/spv/fragment-output.spvasm (100%) rename {tests => naga/tests}/out/spv/functions.spvasm (100%) rename {tests => naga/tests}/out/spv/globals.spvasm (100%) rename {tests => naga/tests}/out/spv/image.spvasm (100%) rename {tests => naga/tests}/out/spv/interface.compute.spvasm (100%) rename {tests => naga/tests}/out/spv/interface.fragment.spvasm (100%) rename {tests => naga/tests}/out/spv/interface.vertex.spvasm (100%) rename {tests => naga/tests}/out/spv/interface.vertex_two_structs.spvasm (100%) rename {tests => naga/tests}/out/spv/interpolate.spvasm (100%) rename {tests => naga/tests}/out/spv/math-functions.spvasm (100%) rename {tests => naga/tests}/out/spv/multiview.spvasm (100%) rename {tests => naga/tests}/out/spv/operators.spvasm (100%) rename {tests => naga/tests}/out/spv/padding.spvasm (100%) rename {tests => naga/tests}/out/spv/pointers.spvasm (100%) rename {tests => naga/tests}/out/spv/policy-mix.spvasm (100%) rename {tests => naga/tests}/out/spv/quad.spvasm (100%) rename {tests => naga/tests}/out/spv/ray-query.spvasm (100%) rename {tests => naga/tests}/out/spv/runtime-array-in-unused-struct.spvasm (100%) rename {tests => naga/tests}/out/spv/separate-entry-points.compute.spvasm (100%) rename {tests => naga/tests}/out/spv/separate-entry-points.fragment.spvasm (100%) rename {tests => naga/tests}/out/spv/shadow.spvasm (100%) rename {tests => naga/tests}/out/spv/skybox.spvasm (100%) rename {tests => naga/tests}/out/spv/sprite.spvasm (100%) rename {tests => naga/tests}/out/spv/standard.spvasm (100%) rename {tests => naga/tests}/out/spv/texture-arg.spvasm (100%) rename {tests => naga/tests}/out/spv/workgroup-uniform-load.spvasm (100%) rename {tests => naga/tests}/out/spv/workgroup-var-init.spvasm (100%) rename {tests => naga/tests}/out/wgsl/210-bevy-2d-shader.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/210-bevy-2d-shader.vert.wgsl (100%) rename {tests => naga/tests}/out/wgsl/210-bevy-shader.vert.wgsl (100%) rename {tests => naga/tests}/out/wgsl/246-collatz.comp.wgsl (100%) rename {tests => naga/tests}/out/wgsl/277-casting.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/280-matrix-cast.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/484-preprocessor-if.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/800-out-of-bounds-panic.vert.wgsl (100%) rename {tests => naga/tests}/out/wgsl/896-push-constant.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/900-implicit-conversions.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/901-lhs-field-select.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/931-constant-emitting.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/932-for-loop-if.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/access.wgsl (100%) rename {tests => naga/tests}/out/wgsl/array-in-ctor.wgsl (100%) rename {tests => naga/tests}/out/wgsl/array-in-function-return-type.wgsl (100%) rename {tests => naga/tests}/out/wgsl/atomicCompareExchange.wgsl (100%) rename {tests => naga/tests}/out/wgsl/atomicOps.wgsl (100%) rename {tests => naga/tests}/out/wgsl/bevy-pbr.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/bevy-pbr.vert.wgsl (100%) rename {tests => naga/tests}/out/wgsl/binding-arrays.dynamic.wgsl (100%) rename {tests => naga/tests}/out/wgsl/binding-arrays.static.wgsl (100%) rename {tests => naga/tests}/out/wgsl/binding-arrays.wgsl (100%) rename {tests => naga/tests}/out/wgsl/binding-buffer-arrays.wgsl (100%) rename {tests => naga/tests}/out/wgsl/bitcast.wgsl (100%) rename {tests => naga/tests}/out/wgsl/bits.wgsl (100%) rename {tests => naga/tests}/out/wgsl/bits_glsl.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/boids.wgsl (100%) rename {tests => naga/tests}/out/wgsl/bool-select.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/break-if.wgsl (100%) rename {tests => naga/tests}/out/wgsl/buffer.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/clamp-splat.vert.wgsl (100%) rename {tests => naga/tests}/out/wgsl/collatz.wgsl (100%) rename {tests => naga/tests}/out/wgsl/const-exprs.wgsl (100%) rename {tests => naga/tests}/out/wgsl/constant-array-size.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/constructors.wgsl (100%) rename {tests => naga/tests}/out/wgsl/control-flow.wgsl (100%) rename {tests => naga/tests}/out/wgsl/declarations.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/do-while.wgsl (100%) rename {tests => naga/tests}/out/wgsl/dualsource.wgsl (100%) rename {tests => naga/tests}/out/wgsl/empty-global-name.wgsl (100%) rename {tests => naga/tests}/out/wgsl/empty.wgsl (100%) rename {tests => naga/tests}/out/wgsl/expressions.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/extra.wgsl (100%) rename {tests => naga/tests}/out/wgsl/fma.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/fragment-output.wgsl (100%) rename {tests => naga/tests}/out/wgsl/functions.wgsl (100%) rename {tests => naga/tests}/out/wgsl/functions_call.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/global-constant-array.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/globals.wgsl (100%) rename {tests => naga/tests}/out/wgsl/image.wgsl (100%) rename {tests => naga/tests}/out/wgsl/images.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/interface.wgsl (100%) rename {tests => naga/tests}/out/wgsl/interpolate.wgsl (100%) rename {tests => naga/tests}/out/wgsl/inv-hyperbolic-trig-functions.wgsl (100%) rename {tests => naga/tests}/out/wgsl/lexical-scopes.wgsl (100%) rename {tests => naga/tests}/out/wgsl/local-var-init-in-loop.comp.wgsl (100%) rename {tests => naga/tests}/out/wgsl/long-form-matrix.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/math-functions.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/math-functions.wgsl (100%) rename {tests => naga/tests}/out/wgsl/module-scope.wgsl (100%) rename {tests => naga/tests}/out/wgsl/multiview.wgsl (100%) rename {tests => naga/tests}/out/wgsl/operators.wgsl (100%) rename {tests => naga/tests}/out/wgsl/padding.wgsl (100%) rename {tests => naga/tests}/out/wgsl/pointers.wgsl (100%) rename {tests => naga/tests}/out/wgsl/prepostfix.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/quad-vert.wgsl (100%) rename {tests => naga/tests}/out/wgsl/quad.wgsl (100%) rename {tests => naga/tests}/out/wgsl/quad_glsl.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/quad_glsl.vert.wgsl (100%) rename {tests => naga/tests}/out/wgsl/sampler-functions.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/samplers.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/shadow.wgsl (100%) rename {tests => naga/tests}/out/wgsl/skybox.wgsl (100%) rename {tests => naga/tests}/out/wgsl/standard.wgsl (100%) rename {tests => naga/tests}/out/wgsl/statements.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/texture-arg.wgsl (100%) rename {tests => naga/tests}/out/wgsl/type-alias.wgsl (100%) rename {tests => naga/tests}/out/wgsl/vector-functions.frag.wgsl (100%) rename {tests => naga/tests}/out/wgsl/workgroup-uniform-load.wgsl (100%) rename {tests => naga/tests}/out/wgsl/workgroup-var-init.wgsl (100%) rename {tests => naga/tests}/snapshots.rs (100%) rename {tests => naga/tests}/spirv-capabilities.rs (100%) rename {tests => naga/tests}/wgsl-errors.rs (100%) rename {xtask => naga/xtask}/.gitignore (100%) rename {xtask => naga/xtask}/Cargo.lock (100%) rename {xtask => naga/xtask}/Cargo.toml (100%) rename {xtask => naga/xtask}/src/cli.rs (100%) rename {xtask => naga/xtask}/src/fs.rs (100%) rename {xtask => naga/xtask}/src/glob.rs (100%) rename {xtask => naga/xtask}/src/main.rs (100%) rename {xtask => naga/xtask}/src/path.rs (100%) rename {xtask => naga/xtask}/src/process.rs (100%) rename {xtask => naga/xtask}/src/result.rs (100%) diff --git a/.cargo/config.toml b/naga/.cargo/config.toml similarity index 100% rename from .cargo/config.toml rename to naga/.cargo/config.toml diff --git a/.gitattributes b/naga/.gitattributes similarity index 100% rename from .gitattributes rename to naga/.gitattributes diff --git a/.github/CODEOWNERS b/naga/.github/CODEOWNERS similarity index 100% rename from .github/CODEOWNERS rename to naga/.github/CODEOWNERS diff --git a/.github/workflows/ci.yml b/naga/.github/workflows/ci.yml similarity index 100% rename from .github/workflows/ci.yml rename to naga/.github/workflows/ci.yml diff --git a/.github/workflows/lazy.yml b/naga/.github/workflows/lazy.yml similarity index 100% rename from .github/workflows/lazy.yml rename to naga/.github/workflows/lazy.yml diff --git a/.github/workflows/validation-linux.yml b/naga/.github/workflows/validation-linux.yml similarity index 100% rename from .github/workflows/validation-linux.yml rename to naga/.github/workflows/validation-linux.yml diff --git a/.github/workflows/validation-macos.yml b/naga/.github/workflows/validation-macos.yml similarity index 100% rename from .github/workflows/validation-macos.yml rename to naga/.github/workflows/validation-macos.yml diff --git a/.github/workflows/validation-windows.yml b/naga/.github/workflows/validation-windows.yml similarity index 100% rename from .github/workflows/validation-windows.yml rename to naga/.github/workflows/validation-windows.yml diff --git a/.gitignore b/naga/.gitignore similarity index 100% rename from .gitignore rename to naga/.gitignore diff --git a/CHANGELOG.md b/naga/CHANGELOG.md similarity index 100% rename from CHANGELOG.md rename to naga/CHANGELOG.md diff --git a/Cargo.toml b/naga/Cargo.toml similarity index 100% rename from Cargo.toml rename to naga/Cargo.toml diff --git a/LICENSE-APACHE b/naga/LICENSE-APACHE similarity index 100% rename from LICENSE-APACHE rename to naga/LICENSE-APACHE diff --git a/LICENSE-MIT b/naga/LICENSE-MIT similarity index 100% rename from LICENSE-MIT rename to naga/LICENSE-MIT diff --git a/README.md b/naga/README.md similarity index 100% rename from README.md rename to naga/README.md diff --git a/benches/criterion.rs b/naga/benches/criterion.rs similarity index 100% rename from benches/criterion.rs rename to naga/benches/criterion.rs diff --git a/cli/Cargo.toml b/naga/cli/Cargo.toml similarity index 100% rename from cli/Cargo.toml rename to naga/cli/Cargo.toml diff --git a/cli/src/bin/naga.rs b/naga/cli/src/bin/naga.rs similarity index 100% rename from cli/src/bin/naga.rs rename to naga/cli/src/bin/naga.rs diff --git a/codecov.yml b/naga/codecov.yml similarity index 100% rename from codecov.yml rename to naga/codecov.yml diff --git a/fuzz/.gitignore b/naga/fuzz/.gitignore similarity index 100% rename from fuzz/.gitignore rename to naga/fuzz/.gitignore diff --git a/fuzz/Cargo.toml b/naga/fuzz/Cargo.toml similarity index 100% rename from fuzz/Cargo.toml rename to naga/fuzz/Cargo.toml diff --git a/fuzz/fuzz_targets/glsl_parser.rs b/naga/fuzz/fuzz_targets/glsl_parser.rs similarity index 100% rename from fuzz/fuzz_targets/glsl_parser.rs rename to naga/fuzz/fuzz_targets/glsl_parser.rs diff --git a/fuzz/fuzz_targets/ir.rs b/naga/fuzz/fuzz_targets/ir.rs similarity index 100% rename from fuzz/fuzz_targets/ir.rs rename to naga/fuzz/fuzz_targets/ir.rs diff --git a/fuzz/fuzz_targets/spv_parser.rs b/naga/fuzz/fuzz_targets/spv_parser.rs similarity index 100% rename from fuzz/fuzz_targets/spv_parser.rs rename to naga/fuzz/fuzz_targets/spv_parser.rs diff --git a/fuzz/fuzz_targets/wgsl_parser.rs b/naga/fuzz/fuzz_targets/wgsl_parser.rs similarity index 100% rename from fuzz/fuzz_targets/wgsl_parser.rs rename to naga/fuzz/fuzz_targets/wgsl_parser.rs diff --git a/hlsl-snapshots/Cargo.toml b/naga/hlsl-snapshots/Cargo.toml similarity index 100% rename from hlsl-snapshots/Cargo.toml rename to naga/hlsl-snapshots/Cargo.toml diff --git a/hlsl-snapshots/src/lib.rs b/naga/hlsl-snapshots/src/lib.rs similarity index 100% rename from hlsl-snapshots/src/lib.rs rename to naga/hlsl-snapshots/src/lib.rs diff --git a/src/arena.rs b/naga/src/arena.rs similarity index 100% rename from src/arena.rs rename to naga/src/arena.rs diff --git a/src/back/dot/mod.rs b/naga/src/back/dot/mod.rs similarity index 100% rename from src/back/dot/mod.rs rename to naga/src/back/dot/mod.rs diff --git a/src/back/glsl/features.rs b/naga/src/back/glsl/features.rs similarity index 100% rename from src/back/glsl/features.rs rename to naga/src/back/glsl/features.rs diff --git a/src/back/glsl/keywords.rs b/naga/src/back/glsl/keywords.rs similarity index 100% rename from src/back/glsl/keywords.rs rename to naga/src/back/glsl/keywords.rs diff --git a/src/back/glsl/mod.rs b/naga/src/back/glsl/mod.rs similarity index 100% rename from src/back/glsl/mod.rs rename to naga/src/back/glsl/mod.rs diff --git a/src/back/hlsl/conv.rs b/naga/src/back/hlsl/conv.rs similarity index 100% rename from src/back/hlsl/conv.rs rename to naga/src/back/hlsl/conv.rs diff --git a/src/back/hlsl/help.rs b/naga/src/back/hlsl/help.rs similarity index 100% rename from src/back/hlsl/help.rs rename to naga/src/back/hlsl/help.rs diff --git a/src/back/hlsl/keywords.rs b/naga/src/back/hlsl/keywords.rs similarity index 100% rename from src/back/hlsl/keywords.rs rename to naga/src/back/hlsl/keywords.rs diff --git a/src/back/hlsl/mod.rs b/naga/src/back/hlsl/mod.rs similarity index 100% rename from src/back/hlsl/mod.rs rename to naga/src/back/hlsl/mod.rs diff --git a/src/back/hlsl/storage.rs b/naga/src/back/hlsl/storage.rs similarity index 100% rename from src/back/hlsl/storage.rs rename to naga/src/back/hlsl/storage.rs diff --git a/src/back/hlsl/writer.rs b/naga/src/back/hlsl/writer.rs similarity index 100% rename from src/back/hlsl/writer.rs rename to naga/src/back/hlsl/writer.rs diff --git a/src/back/mod.rs b/naga/src/back/mod.rs similarity index 100% rename from src/back/mod.rs rename to naga/src/back/mod.rs diff --git a/src/back/msl/keywords.rs b/naga/src/back/msl/keywords.rs similarity index 100% rename from src/back/msl/keywords.rs rename to naga/src/back/msl/keywords.rs diff --git a/src/back/msl/mod.rs b/naga/src/back/msl/mod.rs similarity index 100% rename from src/back/msl/mod.rs rename to naga/src/back/msl/mod.rs diff --git a/src/back/msl/sampler.rs b/naga/src/back/msl/sampler.rs similarity index 100% rename from src/back/msl/sampler.rs rename to naga/src/back/msl/sampler.rs diff --git a/src/back/msl/writer.rs b/naga/src/back/msl/writer.rs similarity index 100% rename from src/back/msl/writer.rs rename to naga/src/back/msl/writer.rs diff --git a/src/back/spv/block.rs b/naga/src/back/spv/block.rs similarity index 100% rename from src/back/spv/block.rs rename to naga/src/back/spv/block.rs diff --git a/src/back/spv/helpers.rs b/naga/src/back/spv/helpers.rs similarity index 100% rename from src/back/spv/helpers.rs rename to naga/src/back/spv/helpers.rs diff --git a/src/back/spv/image.rs b/naga/src/back/spv/image.rs similarity index 100% rename from src/back/spv/image.rs rename to naga/src/back/spv/image.rs diff --git a/src/back/spv/index.rs b/naga/src/back/spv/index.rs similarity index 100% rename from src/back/spv/index.rs rename to naga/src/back/spv/index.rs diff --git a/src/back/spv/instructions.rs b/naga/src/back/spv/instructions.rs similarity index 100% rename from src/back/spv/instructions.rs rename to naga/src/back/spv/instructions.rs diff --git a/src/back/spv/layout.rs b/naga/src/back/spv/layout.rs similarity index 100% rename from src/back/spv/layout.rs rename to naga/src/back/spv/layout.rs diff --git a/src/back/spv/mod.rs b/naga/src/back/spv/mod.rs similarity index 100% rename from src/back/spv/mod.rs rename to naga/src/back/spv/mod.rs diff --git a/src/back/spv/ray.rs b/naga/src/back/spv/ray.rs similarity index 100% rename from src/back/spv/ray.rs rename to naga/src/back/spv/ray.rs diff --git a/src/back/spv/recyclable.rs b/naga/src/back/spv/recyclable.rs similarity index 100% rename from src/back/spv/recyclable.rs rename to naga/src/back/spv/recyclable.rs diff --git a/src/back/spv/selection.rs b/naga/src/back/spv/selection.rs similarity index 100% rename from src/back/spv/selection.rs rename to naga/src/back/spv/selection.rs diff --git a/src/back/spv/writer.rs b/naga/src/back/spv/writer.rs similarity index 100% rename from src/back/spv/writer.rs rename to naga/src/back/spv/writer.rs diff --git a/src/back/wgsl/mod.rs b/naga/src/back/wgsl/mod.rs similarity index 100% rename from src/back/wgsl/mod.rs rename to naga/src/back/wgsl/mod.rs diff --git a/src/back/wgsl/writer.rs b/naga/src/back/wgsl/writer.rs similarity index 100% rename from src/back/wgsl/writer.rs rename to naga/src/back/wgsl/writer.rs diff --git a/src/block.rs b/naga/src/block.rs similarity index 100% rename from src/block.rs rename to naga/src/block.rs diff --git a/src/compact/expressions.rs b/naga/src/compact/expressions.rs similarity index 100% rename from src/compact/expressions.rs rename to naga/src/compact/expressions.rs diff --git a/src/compact/functions.rs b/naga/src/compact/functions.rs similarity index 100% rename from src/compact/functions.rs rename to naga/src/compact/functions.rs diff --git a/src/compact/handle_set_map.rs b/naga/src/compact/handle_set_map.rs similarity index 100% rename from src/compact/handle_set_map.rs rename to naga/src/compact/handle_set_map.rs diff --git a/src/compact/mod.rs b/naga/src/compact/mod.rs similarity index 100% rename from src/compact/mod.rs rename to naga/src/compact/mod.rs diff --git a/src/compact/statements.rs b/naga/src/compact/statements.rs similarity index 100% rename from src/compact/statements.rs rename to naga/src/compact/statements.rs diff --git a/src/compact/types.rs b/naga/src/compact/types.rs similarity index 100% rename from src/compact/types.rs rename to naga/src/compact/types.rs diff --git a/src/front/glsl/ast.rs b/naga/src/front/glsl/ast.rs similarity index 100% rename from src/front/glsl/ast.rs rename to naga/src/front/glsl/ast.rs diff --git a/src/front/glsl/builtins.rs b/naga/src/front/glsl/builtins.rs similarity index 100% rename from src/front/glsl/builtins.rs rename to naga/src/front/glsl/builtins.rs diff --git a/src/front/glsl/context.rs b/naga/src/front/glsl/context.rs similarity index 100% rename from src/front/glsl/context.rs rename to naga/src/front/glsl/context.rs diff --git a/src/front/glsl/error.rs b/naga/src/front/glsl/error.rs similarity index 100% rename from src/front/glsl/error.rs rename to naga/src/front/glsl/error.rs diff --git a/src/front/glsl/functions.rs b/naga/src/front/glsl/functions.rs similarity index 100% rename from src/front/glsl/functions.rs rename to naga/src/front/glsl/functions.rs diff --git a/src/front/glsl/lex.rs b/naga/src/front/glsl/lex.rs similarity index 100% rename from src/front/glsl/lex.rs rename to naga/src/front/glsl/lex.rs diff --git a/src/front/glsl/mod.rs b/naga/src/front/glsl/mod.rs similarity index 100% rename from src/front/glsl/mod.rs rename to naga/src/front/glsl/mod.rs diff --git a/src/front/glsl/offset.rs b/naga/src/front/glsl/offset.rs similarity index 100% rename from src/front/glsl/offset.rs rename to naga/src/front/glsl/offset.rs diff --git a/src/front/glsl/parser.rs b/naga/src/front/glsl/parser.rs similarity index 100% rename from src/front/glsl/parser.rs rename to naga/src/front/glsl/parser.rs diff --git a/src/front/glsl/parser/declarations.rs b/naga/src/front/glsl/parser/declarations.rs similarity index 100% rename from src/front/glsl/parser/declarations.rs rename to naga/src/front/glsl/parser/declarations.rs diff --git a/src/front/glsl/parser/expressions.rs b/naga/src/front/glsl/parser/expressions.rs similarity index 100% rename from src/front/glsl/parser/expressions.rs rename to naga/src/front/glsl/parser/expressions.rs diff --git a/src/front/glsl/parser/functions.rs b/naga/src/front/glsl/parser/functions.rs similarity index 100% rename from src/front/glsl/parser/functions.rs rename to naga/src/front/glsl/parser/functions.rs diff --git a/src/front/glsl/parser/types.rs b/naga/src/front/glsl/parser/types.rs similarity index 100% rename from src/front/glsl/parser/types.rs rename to naga/src/front/glsl/parser/types.rs diff --git a/src/front/glsl/parser_tests.rs b/naga/src/front/glsl/parser_tests.rs similarity index 100% rename from src/front/glsl/parser_tests.rs rename to naga/src/front/glsl/parser_tests.rs diff --git a/src/front/glsl/token.rs b/naga/src/front/glsl/token.rs similarity index 100% rename from src/front/glsl/token.rs rename to naga/src/front/glsl/token.rs diff --git a/src/front/glsl/types.rs b/naga/src/front/glsl/types.rs similarity index 100% rename from src/front/glsl/types.rs rename to naga/src/front/glsl/types.rs diff --git a/src/front/glsl/variables.rs b/naga/src/front/glsl/variables.rs similarity index 100% rename from src/front/glsl/variables.rs rename to naga/src/front/glsl/variables.rs diff --git a/src/front/interpolator.rs b/naga/src/front/interpolator.rs similarity index 100% rename from src/front/interpolator.rs rename to naga/src/front/interpolator.rs diff --git a/src/front/mod.rs b/naga/src/front/mod.rs similarity index 100% rename from src/front/mod.rs rename to naga/src/front/mod.rs diff --git a/src/front/spv/convert.rs b/naga/src/front/spv/convert.rs similarity index 100% rename from src/front/spv/convert.rs rename to naga/src/front/spv/convert.rs diff --git a/src/front/spv/error.rs b/naga/src/front/spv/error.rs similarity index 100% rename from src/front/spv/error.rs rename to naga/src/front/spv/error.rs diff --git a/src/front/spv/function.rs b/naga/src/front/spv/function.rs similarity index 100% rename from src/front/spv/function.rs rename to naga/src/front/spv/function.rs diff --git a/src/front/spv/image.rs b/naga/src/front/spv/image.rs similarity index 100% rename from src/front/spv/image.rs rename to naga/src/front/spv/image.rs diff --git a/src/front/spv/mod.rs b/naga/src/front/spv/mod.rs similarity index 100% rename from src/front/spv/mod.rs rename to naga/src/front/spv/mod.rs diff --git a/src/front/spv/null.rs b/naga/src/front/spv/null.rs similarity index 100% rename from src/front/spv/null.rs rename to naga/src/front/spv/null.rs diff --git a/src/front/type_gen.rs b/naga/src/front/type_gen.rs similarity index 100% rename from src/front/type_gen.rs rename to naga/src/front/type_gen.rs diff --git a/src/front/wgsl/error.rs b/naga/src/front/wgsl/error.rs similarity index 100% rename from src/front/wgsl/error.rs rename to naga/src/front/wgsl/error.rs diff --git a/src/front/wgsl/index.rs b/naga/src/front/wgsl/index.rs similarity index 100% rename from src/front/wgsl/index.rs rename to naga/src/front/wgsl/index.rs diff --git a/src/front/wgsl/lower/construction.rs b/naga/src/front/wgsl/lower/construction.rs similarity index 100% rename from src/front/wgsl/lower/construction.rs rename to naga/src/front/wgsl/lower/construction.rs diff --git a/src/front/wgsl/lower/mod.rs b/naga/src/front/wgsl/lower/mod.rs similarity index 100% rename from src/front/wgsl/lower/mod.rs rename to naga/src/front/wgsl/lower/mod.rs diff --git a/src/front/wgsl/mod.rs b/naga/src/front/wgsl/mod.rs similarity index 100% rename from src/front/wgsl/mod.rs rename to naga/src/front/wgsl/mod.rs diff --git a/src/front/wgsl/parse/ast.rs b/naga/src/front/wgsl/parse/ast.rs similarity index 100% rename from src/front/wgsl/parse/ast.rs rename to naga/src/front/wgsl/parse/ast.rs diff --git a/src/front/wgsl/parse/conv.rs b/naga/src/front/wgsl/parse/conv.rs similarity index 100% rename from src/front/wgsl/parse/conv.rs rename to naga/src/front/wgsl/parse/conv.rs diff --git a/src/front/wgsl/parse/lexer.rs b/naga/src/front/wgsl/parse/lexer.rs similarity index 100% rename from src/front/wgsl/parse/lexer.rs rename to naga/src/front/wgsl/parse/lexer.rs diff --git a/src/front/wgsl/parse/mod.rs b/naga/src/front/wgsl/parse/mod.rs similarity index 100% rename from src/front/wgsl/parse/mod.rs rename to naga/src/front/wgsl/parse/mod.rs diff --git a/src/front/wgsl/parse/number.rs b/naga/src/front/wgsl/parse/number.rs similarity index 100% rename from src/front/wgsl/parse/number.rs rename to naga/src/front/wgsl/parse/number.rs diff --git a/src/front/wgsl/tests.rs b/naga/src/front/wgsl/tests.rs similarity index 100% rename from src/front/wgsl/tests.rs rename to naga/src/front/wgsl/tests.rs diff --git a/src/keywords/mod.rs b/naga/src/keywords/mod.rs similarity index 100% rename from src/keywords/mod.rs rename to naga/src/keywords/mod.rs diff --git a/src/keywords/wgsl.rs b/naga/src/keywords/wgsl.rs similarity index 100% rename from src/keywords/wgsl.rs rename to naga/src/keywords/wgsl.rs diff --git a/src/lib.rs b/naga/src/lib.rs similarity index 100% rename from src/lib.rs rename to naga/src/lib.rs diff --git a/src/proc/constant_evaluator.rs b/naga/src/proc/constant_evaluator.rs similarity index 100% rename from src/proc/constant_evaluator.rs rename to naga/src/proc/constant_evaluator.rs diff --git a/src/proc/emitter.rs b/naga/src/proc/emitter.rs similarity index 100% rename from src/proc/emitter.rs rename to naga/src/proc/emitter.rs diff --git a/src/proc/index.rs b/naga/src/proc/index.rs similarity index 100% rename from src/proc/index.rs rename to naga/src/proc/index.rs diff --git a/src/proc/layouter.rs b/naga/src/proc/layouter.rs similarity index 100% rename from src/proc/layouter.rs rename to naga/src/proc/layouter.rs diff --git a/src/proc/mod.rs b/naga/src/proc/mod.rs similarity index 100% rename from src/proc/mod.rs rename to naga/src/proc/mod.rs diff --git a/src/proc/namer.rs b/naga/src/proc/namer.rs similarity index 100% rename from src/proc/namer.rs rename to naga/src/proc/namer.rs diff --git a/src/proc/terminator.rs b/naga/src/proc/terminator.rs similarity index 100% rename from src/proc/terminator.rs rename to naga/src/proc/terminator.rs diff --git a/src/proc/typifier.rs b/naga/src/proc/typifier.rs similarity index 100% rename from src/proc/typifier.rs rename to naga/src/proc/typifier.rs diff --git a/src/span.rs b/naga/src/span.rs similarity index 100% rename from src/span.rs rename to naga/src/span.rs diff --git a/src/valid/analyzer.rs b/naga/src/valid/analyzer.rs similarity index 100% rename from src/valid/analyzer.rs rename to naga/src/valid/analyzer.rs diff --git a/src/valid/compose.rs b/naga/src/valid/compose.rs similarity index 100% rename from src/valid/compose.rs rename to naga/src/valid/compose.rs diff --git a/src/valid/expression.rs b/naga/src/valid/expression.rs similarity index 100% rename from src/valid/expression.rs rename to naga/src/valid/expression.rs diff --git a/src/valid/function.rs b/naga/src/valid/function.rs similarity index 100% rename from src/valid/function.rs rename to naga/src/valid/function.rs diff --git a/src/valid/handles.rs b/naga/src/valid/handles.rs similarity index 100% rename from src/valid/handles.rs rename to naga/src/valid/handles.rs diff --git a/src/valid/interface.rs b/naga/src/valid/interface.rs similarity index 100% rename from src/valid/interface.rs rename to naga/src/valid/interface.rs diff --git a/src/valid/mod.rs b/naga/src/valid/mod.rs similarity index 100% rename from src/valid/mod.rs rename to naga/src/valid/mod.rs diff --git a/src/valid/type.rs b/naga/src/valid/type.rs similarity index 100% rename from src/valid/type.rs rename to naga/src/valid/type.rs diff --git a/tests/in/access.param.ron b/naga/tests/in/access.param.ron similarity index 100% rename from tests/in/access.param.ron rename to naga/tests/in/access.param.ron diff --git a/tests/in/access.wgsl b/naga/tests/in/access.wgsl similarity index 100% rename from tests/in/access.wgsl rename to naga/tests/in/access.wgsl diff --git a/tests/in/array-in-ctor.param.ron b/naga/tests/in/array-in-ctor.param.ron similarity index 100% rename from tests/in/array-in-ctor.param.ron rename to naga/tests/in/array-in-ctor.param.ron diff --git a/tests/in/array-in-ctor.wgsl b/naga/tests/in/array-in-ctor.wgsl similarity index 100% rename from tests/in/array-in-ctor.wgsl rename to naga/tests/in/array-in-ctor.wgsl diff --git a/tests/in/array-in-function-return-type.param.ron b/naga/tests/in/array-in-function-return-type.param.ron similarity index 100% rename from tests/in/array-in-function-return-type.param.ron rename to naga/tests/in/array-in-function-return-type.param.ron diff --git a/tests/in/array-in-function-return-type.wgsl b/naga/tests/in/array-in-function-return-type.wgsl similarity index 100% rename from tests/in/array-in-function-return-type.wgsl rename to naga/tests/in/array-in-function-return-type.wgsl diff --git a/tests/in/atomicCompareExchange.wgsl b/naga/tests/in/atomicCompareExchange.wgsl similarity index 100% rename from tests/in/atomicCompareExchange.wgsl rename to naga/tests/in/atomicCompareExchange.wgsl diff --git a/tests/in/atomicOps.wgsl b/naga/tests/in/atomicOps.wgsl similarity index 100% rename from tests/in/atomicOps.wgsl rename to naga/tests/in/atomicOps.wgsl diff --git a/tests/in/binding-arrays.param.ron b/naga/tests/in/binding-arrays.param.ron similarity index 100% rename from tests/in/binding-arrays.param.ron rename to naga/tests/in/binding-arrays.param.ron diff --git a/tests/in/binding-arrays.wgsl b/naga/tests/in/binding-arrays.wgsl similarity index 100% rename from tests/in/binding-arrays.wgsl rename to naga/tests/in/binding-arrays.wgsl diff --git a/tests/in/binding-buffer-arrays.param.ron b/naga/tests/in/binding-buffer-arrays.param.ron similarity index 100% rename from tests/in/binding-buffer-arrays.param.ron rename to naga/tests/in/binding-buffer-arrays.param.ron diff --git a/tests/in/binding-buffer-arrays.wgsl b/naga/tests/in/binding-buffer-arrays.wgsl similarity index 100% rename from tests/in/binding-buffer-arrays.wgsl rename to naga/tests/in/binding-buffer-arrays.wgsl diff --git a/tests/in/bitcast.params.ron b/naga/tests/in/bitcast.params.ron similarity index 100% rename from tests/in/bitcast.params.ron rename to naga/tests/in/bitcast.params.ron diff --git a/tests/in/bitcast.wgsl b/naga/tests/in/bitcast.wgsl similarity index 100% rename from tests/in/bitcast.wgsl rename to naga/tests/in/bitcast.wgsl diff --git a/tests/in/bits.param.ron b/naga/tests/in/bits.param.ron similarity index 100% rename from tests/in/bits.param.ron rename to naga/tests/in/bits.param.ron diff --git a/tests/in/bits.wgsl b/naga/tests/in/bits.wgsl similarity index 100% rename from tests/in/bits.wgsl rename to naga/tests/in/bits.wgsl diff --git a/tests/in/boids.param.ron b/naga/tests/in/boids.param.ron similarity index 100% rename from tests/in/boids.param.ron rename to naga/tests/in/boids.param.ron diff --git a/tests/in/boids.wgsl b/naga/tests/in/boids.wgsl similarity index 100% rename from tests/in/boids.wgsl rename to naga/tests/in/boids.wgsl diff --git a/tests/in/bounds-check-image-restrict.param.ron b/naga/tests/in/bounds-check-image-restrict.param.ron similarity index 100% rename from tests/in/bounds-check-image-restrict.param.ron rename to naga/tests/in/bounds-check-image-restrict.param.ron diff --git a/tests/in/bounds-check-image-restrict.wgsl b/naga/tests/in/bounds-check-image-restrict.wgsl similarity index 100% rename from tests/in/bounds-check-image-restrict.wgsl rename to naga/tests/in/bounds-check-image-restrict.wgsl diff --git a/tests/in/bounds-check-image-rzsw.param.ron b/naga/tests/in/bounds-check-image-rzsw.param.ron similarity index 100% rename from tests/in/bounds-check-image-rzsw.param.ron rename to naga/tests/in/bounds-check-image-rzsw.param.ron diff --git a/tests/in/bounds-check-image-rzsw.wgsl b/naga/tests/in/bounds-check-image-rzsw.wgsl similarity index 100% rename from tests/in/bounds-check-image-rzsw.wgsl rename to naga/tests/in/bounds-check-image-rzsw.wgsl diff --git a/tests/in/bounds-check-restrict.param.ron b/naga/tests/in/bounds-check-restrict.param.ron similarity index 100% rename from tests/in/bounds-check-restrict.param.ron rename to naga/tests/in/bounds-check-restrict.param.ron diff --git a/tests/in/bounds-check-restrict.wgsl b/naga/tests/in/bounds-check-restrict.wgsl similarity index 100% rename from tests/in/bounds-check-restrict.wgsl rename to naga/tests/in/bounds-check-restrict.wgsl diff --git a/tests/in/bounds-check-zero-atomic.param.ron b/naga/tests/in/bounds-check-zero-atomic.param.ron similarity index 100% rename from tests/in/bounds-check-zero-atomic.param.ron rename to naga/tests/in/bounds-check-zero-atomic.param.ron diff --git a/tests/in/bounds-check-zero-atomic.wgsl b/naga/tests/in/bounds-check-zero-atomic.wgsl similarity index 100% rename from tests/in/bounds-check-zero-atomic.wgsl rename to naga/tests/in/bounds-check-zero-atomic.wgsl diff --git a/tests/in/bounds-check-zero.param.ron b/naga/tests/in/bounds-check-zero.param.ron similarity index 100% rename from tests/in/bounds-check-zero.param.ron rename to naga/tests/in/bounds-check-zero.param.ron diff --git a/tests/in/bounds-check-zero.wgsl b/naga/tests/in/bounds-check-zero.wgsl similarity index 100% rename from tests/in/bounds-check-zero.wgsl rename to naga/tests/in/bounds-check-zero.wgsl diff --git a/tests/in/break-if.wgsl b/naga/tests/in/break-if.wgsl similarity index 100% rename from tests/in/break-if.wgsl rename to naga/tests/in/break-if.wgsl diff --git a/tests/in/collatz.param.ron b/naga/tests/in/collatz.param.ron similarity index 100% rename from tests/in/collatz.param.ron rename to naga/tests/in/collatz.param.ron diff --git a/tests/in/collatz.wgsl b/naga/tests/in/collatz.wgsl similarity index 100% rename from tests/in/collatz.wgsl rename to naga/tests/in/collatz.wgsl diff --git a/tests/in/const-exprs.wgsl b/naga/tests/in/const-exprs.wgsl similarity index 100% rename from tests/in/const-exprs.wgsl rename to naga/tests/in/const-exprs.wgsl diff --git a/tests/in/constructors.param.ron b/naga/tests/in/constructors.param.ron similarity index 100% rename from tests/in/constructors.param.ron rename to naga/tests/in/constructors.param.ron diff --git a/tests/in/constructors.wgsl b/naga/tests/in/constructors.wgsl similarity index 100% rename from tests/in/constructors.wgsl rename to naga/tests/in/constructors.wgsl diff --git a/tests/in/control-flow.param.ron b/naga/tests/in/control-flow.param.ron similarity index 100% rename from tests/in/control-flow.param.ron rename to naga/tests/in/control-flow.param.ron diff --git a/tests/in/control-flow.wgsl b/naga/tests/in/control-flow.wgsl similarity index 100% rename from tests/in/control-flow.wgsl rename to naga/tests/in/control-flow.wgsl diff --git a/tests/in/cubeArrayShadow.wgsl b/naga/tests/in/cubeArrayShadow.wgsl similarity index 100% rename from tests/in/cubeArrayShadow.wgsl rename to naga/tests/in/cubeArrayShadow.wgsl diff --git a/tests/in/debug-symbol-simple.param.ron b/naga/tests/in/debug-symbol-simple.param.ron similarity index 100% rename from tests/in/debug-symbol-simple.param.ron rename to naga/tests/in/debug-symbol-simple.param.ron diff --git a/tests/in/debug-symbol-simple.wgsl b/naga/tests/in/debug-symbol-simple.wgsl similarity index 100% rename from tests/in/debug-symbol-simple.wgsl rename to naga/tests/in/debug-symbol-simple.wgsl diff --git a/tests/in/debug-symbol-terrain.param.ron b/naga/tests/in/debug-symbol-terrain.param.ron similarity index 100% rename from tests/in/debug-symbol-terrain.param.ron rename to naga/tests/in/debug-symbol-terrain.param.ron diff --git a/tests/in/debug-symbol-terrain.wgsl b/naga/tests/in/debug-symbol-terrain.wgsl similarity index 100% rename from tests/in/debug-symbol-terrain.wgsl rename to naga/tests/in/debug-symbol-terrain.wgsl diff --git a/tests/in/dualsource.param.ron b/naga/tests/in/dualsource.param.ron similarity index 100% rename from tests/in/dualsource.param.ron rename to naga/tests/in/dualsource.param.ron diff --git a/tests/in/dualsource.wgsl b/naga/tests/in/dualsource.wgsl similarity index 100% rename from tests/in/dualsource.wgsl rename to naga/tests/in/dualsource.wgsl diff --git a/tests/in/empty.param.ron b/naga/tests/in/empty.param.ron similarity index 100% rename from tests/in/empty.param.ron rename to naga/tests/in/empty.param.ron diff --git a/tests/in/empty.wgsl b/naga/tests/in/empty.wgsl similarity index 100% rename from tests/in/empty.wgsl rename to naga/tests/in/empty.wgsl diff --git a/tests/in/extra.param.ron b/naga/tests/in/extra.param.ron similarity index 100% rename from tests/in/extra.param.ron rename to naga/tests/in/extra.param.ron diff --git a/tests/in/extra.wgsl b/naga/tests/in/extra.wgsl similarity index 100% rename from tests/in/extra.wgsl rename to naga/tests/in/extra.wgsl diff --git a/tests/in/force_point_size_vertex_shader_webgl.param.ron b/naga/tests/in/force_point_size_vertex_shader_webgl.param.ron similarity index 100% rename from tests/in/force_point_size_vertex_shader_webgl.param.ron rename to naga/tests/in/force_point_size_vertex_shader_webgl.param.ron diff --git a/tests/in/force_point_size_vertex_shader_webgl.wgsl b/naga/tests/in/force_point_size_vertex_shader_webgl.wgsl similarity index 100% rename from tests/in/force_point_size_vertex_shader_webgl.wgsl rename to naga/tests/in/force_point_size_vertex_shader_webgl.wgsl diff --git a/tests/in/fragment-output.wgsl b/naga/tests/in/fragment-output.wgsl similarity index 100% rename from tests/in/fragment-output.wgsl rename to naga/tests/in/fragment-output.wgsl diff --git a/tests/in/functions-webgl.param.ron b/naga/tests/in/functions-webgl.param.ron similarity index 100% rename from tests/in/functions-webgl.param.ron rename to naga/tests/in/functions-webgl.param.ron diff --git a/tests/in/functions-webgl.wgsl b/naga/tests/in/functions-webgl.wgsl similarity index 100% rename from tests/in/functions-webgl.wgsl rename to naga/tests/in/functions-webgl.wgsl diff --git a/tests/in/functions.param.ron b/naga/tests/in/functions.param.ron similarity index 100% rename from tests/in/functions.param.ron rename to naga/tests/in/functions.param.ron diff --git a/tests/in/functions.wgsl b/naga/tests/in/functions.wgsl similarity index 100% rename from tests/in/functions.wgsl rename to naga/tests/in/functions.wgsl diff --git a/tests/in/globals.param.ron b/naga/tests/in/globals.param.ron similarity index 100% rename from tests/in/globals.param.ron rename to naga/tests/in/globals.param.ron diff --git a/tests/in/globals.wgsl b/naga/tests/in/globals.wgsl similarity index 100% rename from tests/in/globals.wgsl rename to naga/tests/in/globals.wgsl diff --git a/tests/in/glsl/210-bevy-2d-shader.frag b/naga/tests/in/glsl/210-bevy-2d-shader.frag similarity index 100% rename from tests/in/glsl/210-bevy-2d-shader.frag rename to naga/tests/in/glsl/210-bevy-2d-shader.frag diff --git a/tests/in/glsl/210-bevy-2d-shader.vert b/naga/tests/in/glsl/210-bevy-2d-shader.vert similarity index 100% rename from tests/in/glsl/210-bevy-2d-shader.vert rename to naga/tests/in/glsl/210-bevy-2d-shader.vert diff --git a/tests/in/glsl/210-bevy-shader.vert b/naga/tests/in/glsl/210-bevy-shader.vert similarity index 100% rename from tests/in/glsl/210-bevy-shader.vert rename to naga/tests/in/glsl/210-bevy-shader.vert diff --git a/tests/in/glsl/246-collatz.comp b/naga/tests/in/glsl/246-collatz.comp similarity index 100% rename from tests/in/glsl/246-collatz.comp rename to naga/tests/in/glsl/246-collatz.comp diff --git a/tests/in/glsl/277-casting.frag b/naga/tests/in/glsl/277-casting.frag similarity index 100% rename from tests/in/glsl/277-casting.frag rename to naga/tests/in/glsl/277-casting.frag diff --git a/tests/in/glsl/280-matrix-cast.frag b/naga/tests/in/glsl/280-matrix-cast.frag similarity index 100% rename from tests/in/glsl/280-matrix-cast.frag rename to naga/tests/in/glsl/280-matrix-cast.frag diff --git a/tests/in/glsl/484-preprocessor-if.frag b/naga/tests/in/glsl/484-preprocessor-if.frag similarity index 100% rename from tests/in/glsl/484-preprocessor-if.frag rename to naga/tests/in/glsl/484-preprocessor-if.frag diff --git a/tests/in/glsl/800-out-of-bounds-panic.vert b/naga/tests/in/glsl/800-out-of-bounds-panic.vert similarity index 100% rename from tests/in/glsl/800-out-of-bounds-panic.vert rename to naga/tests/in/glsl/800-out-of-bounds-panic.vert diff --git a/tests/in/glsl/896-push-constant.frag b/naga/tests/in/glsl/896-push-constant.frag similarity index 100% rename from tests/in/glsl/896-push-constant.frag rename to naga/tests/in/glsl/896-push-constant.frag diff --git a/tests/in/glsl/900-implicit-conversions.frag b/naga/tests/in/glsl/900-implicit-conversions.frag similarity index 100% rename from tests/in/glsl/900-implicit-conversions.frag rename to naga/tests/in/glsl/900-implicit-conversions.frag diff --git a/tests/in/glsl/901-lhs-field-select.frag b/naga/tests/in/glsl/901-lhs-field-select.frag similarity index 100% rename from tests/in/glsl/901-lhs-field-select.frag rename to naga/tests/in/glsl/901-lhs-field-select.frag diff --git a/tests/in/glsl/931-constant-emitting.frag b/naga/tests/in/glsl/931-constant-emitting.frag similarity index 100% rename from tests/in/glsl/931-constant-emitting.frag rename to naga/tests/in/glsl/931-constant-emitting.frag diff --git a/tests/in/glsl/932-for-loop-if.frag b/naga/tests/in/glsl/932-for-loop-if.frag similarity index 100% rename from tests/in/glsl/932-for-loop-if.frag rename to naga/tests/in/glsl/932-for-loop-if.frag diff --git a/tests/in/glsl/bevy-pbr.frag b/naga/tests/in/glsl/bevy-pbr.frag similarity index 100% rename from tests/in/glsl/bevy-pbr.frag rename to naga/tests/in/glsl/bevy-pbr.frag diff --git a/tests/in/glsl/bevy-pbr.vert b/naga/tests/in/glsl/bevy-pbr.vert similarity index 100% rename from tests/in/glsl/bevy-pbr.vert rename to naga/tests/in/glsl/bevy-pbr.vert diff --git a/tests/in/glsl/bits_glsl.frag b/naga/tests/in/glsl/bits_glsl.frag similarity index 100% rename from tests/in/glsl/bits_glsl.frag rename to naga/tests/in/glsl/bits_glsl.frag diff --git a/tests/in/glsl/bool-select.frag b/naga/tests/in/glsl/bool-select.frag similarity index 100% rename from tests/in/glsl/bool-select.frag rename to naga/tests/in/glsl/bool-select.frag diff --git a/tests/in/glsl/buffer.frag b/naga/tests/in/glsl/buffer.frag similarity index 100% rename from tests/in/glsl/buffer.frag rename to naga/tests/in/glsl/buffer.frag diff --git a/tests/in/glsl/clamp-splat.vert b/naga/tests/in/glsl/clamp-splat.vert similarity index 100% rename from tests/in/glsl/clamp-splat.vert rename to naga/tests/in/glsl/clamp-splat.vert diff --git a/tests/in/glsl/constant-array-size.frag b/naga/tests/in/glsl/constant-array-size.frag similarity index 100% rename from tests/in/glsl/constant-array-size.frag rename to naga/tests/in/glsl/constant-array-size.frag diff --git a/tests/in/glsl/declarations.frag b/naga/tests/in/glsl/declarations.frag similarity index 100% rename from tests/in/glsl/declarations.frag rename to naga/tests/in/glsl/declarations.frag diff --git a/tests/in/glsl/expressions.frag b/naga/tests/in/glsl/expressions.frag similarity index 100% rename from tests/in/glsl/expressions.frag rename to naga/tests/in/glsl/expressions.frag diff --git a/tests/in/glsl/fma.frag b/naga/tests/in/glsl/fma.frag similarity index 100% rename from tests/in/glsl/fma.frag rename to naga/tests/in/glsl/fma.frag diff --git a/tests/in/glsl/functions_call.frag b/naga/tests/in/glsl/functions_call.frag similarity index 100% rename from tests/in/glsl/functions_call.frag rename to naga/tests/in/glsl/functions_call.frag diff --git a/tests/in/glsl/global-constant-array.frag b/naga/tests/in/glsl/global-constant-array.frag similarity index 100% rename from tests/in/glsl/global-constant-array.frag rename to naga/tests/in/glsl/global-constant-array.frag diff --git a/tests/in/glsl/images.frag b/naga/tests/in/glsl/images.frag similarity index 100% rename from tests/in/glsl/images.frag rename to naga/tests/in/glsl/images.frag diff --git a/tests/in/glsl/local-var-init-in-loop.comp b/naga/tests/in/glsl/local-var-init-in-loop.comp similarity index 100% rename from tests/in/glsl/local-var-init-in-loop.comp rename to naga/tests/in/glsl/local-var-init-in-loop.comp diff --git a/tests/in/glsl/long-form-matrix.frag b/naga/tests/in/glsl/long-form-matrix.frag similarity index 100% rename from tests/in/glsl/long-form-matrix.frag rename to naga/tests/in/glsl/long-form-matrix.frag diff --git a/tests/in/glsl/math-functions.frag b/naga/tests/in/glsl/math-functions.frag similarity index 100% rename from tests/in/glsl/math-functions.frag rename to naga/tests/in/glsl/math-functions.frag diff --git a/tests/in/glsl/prepostfix.frag b/naga/tests/in/glsl/prepostfix.frag similarity index 100% rename from tests/in/glsl/prepostfix.frag rename to naga/tests/in/glsl/prepostfix.frag diff --git a/tests/in/glsl/quad_glsl.frag b/naga/tests/in/glsl/quad_glsl.frag similarity index 100% rename from tests/in/glsl/quad_glsl.frag rename to naga/tests/in/glsl/quad_glsl.frag diff --git a/tests/in/glsl/quad_glsl.vert b/naga/tests/in/glsl/quad_glsl.vert similarity index 100% rename from tests/in/glsl/quad_glsl.vert rename to naga/tests/in/glsl/quad_glsl.vert diff --git a/tests/in/glsl/sampler-functions.frag b/naga/tests/in/glsl/sampler-functions.frag similarity index 100% rename from tests/in/glsl/sampler-functions.frag rename to naga/tests/in/glsl/sampler-functions.frag diff --git a/tests/in/glsl/samplers.frag b/naga/tests/in/glsl/samplers.frag similarity index 100% rename from tests/in/glsl/samplers.frag rename to naga/tests/in/glsl/samplers.frag diff --git a/tests/in/glsl/statements.frag b/naga/tests/in/glsl/statements.frag similarity index 100% rename from tests/in/glsl/statements.frag rename to naga/tests/in/glsl/statements.frag diff --git a/tests/in/glsl/vector-functions.frag b/naga/tests/in/glsl/vector-functions.frag similarity index 100% rename from tests/in/glsl/vector-functions.frag rename to naga/tests/in/glsl/vector-functions.frag diff --git a/tests/in/hlsl-keyword.wgsl b/naga/tests/in/hlsl-keyword.wgsl similarity index 100% rename from tests/in/hlsl-keyword.wgsl rename to naga/tests/in/hlsl-keyword.wgsl diff --git a/tests/in/image.param.ron b/naga/tests/in/image.param.ron similarity index 100% rename from tests/in/image.param.ron rename to naga/tests/in/image.param.ron diff --git a/tests/in/image.wgsl b/naga/tests/in/image.wgsl similarity index 100% rename from tests/in/image.wgsl rename to naga/tests/in/image.wgsl diff --git a/tests/in/interface.param.ron b/naga/tests/in/interface.param.ron similarity index 100% rename from tests/in/interface.param.ron rename to naga/tests/in/interface.param.ron diff --git a/tests/in/interface.wgsl b/naga/tests/in/interface.wgsl similarity index 100% rename from tests/in/interface.wgsl rename to naga/tests/in/interface.wgsl diff --git a/tests/in/interpolate.param.ron b/naga/tests/in/interpolate.param.ron similarity index 100% rename from tests/in/interpolate.param.ron rename to naga/tests/in/interpolate.param.ron diff --git a/tests/in/interpolate.wgsl b/naga/tests/in/interpolate.wgsl similarity index 100% rename from tests/in/interpolate.wgsl rename to naga/tests/in/interpolate.wgsl diff --git a/tests/in/invariant.param.ron b/naga/tests/in/invariant.param.ron similarity index 100% rename from tests/in/invariant.param.ron rename to naga/tests/in/invariant.param.ron diff --git a/tests/in/invariant.wgsl b/naga/tests/in/invariant.wgsl similarity index 100% rename from tests/in/invariant.wgsl rename to naga/tests/in/invariant.wgsl diff --git a/tests/in/lexical-scopes.wgsl b/naga/tests/in/lexical-scopes.wgsl similarity index 100% rename from tests/in/lexical-scopes.wgsl rename to naga/tests/in/lexical-scopes.wgsl diff --git a/tests/in/math-functions.param.ron b/naga/tests/in/math-functions.param.ron similarity index 100% rename from tests/in/math-functions.param.ron rename to naga/tests/in/math-functions.param.ron diff --git a/tests/in/math-functions.wgsl b/naga/tests/in/math-functions.wgsl similarity index 100% rename from tests/in/math-functions.wgsl rename to naga/tests/in/math-functions.wgsl diff --git a/tests/in/module-scope.wgsl b/naga/tests/in/module-scope.wgsl similarity index 100% rename from tests/in/module-scope.wgsl rename to naga/tests/in/module-scope.wgsl diff --git a/tests/in/msl-varyings.wgsl b/naga/tests/in/msl-varyings.wgsl similarity index 100% rename from tests/in/msl-varyings.wgsl rename to naga/tests/in/msl-varyings.wgsl diff --git a/tests/in/multiview.param.ron b/naga/tests/in/multiview.param.ron similarity index 100% rename from tests/in/multiview.param.ron rename to naga/tests/in/multiview.param.ron diff --git a/tests/in/multiview.wgsl b/naga/tests/in/multiview.wgsl similarity index 100% rename from tests/in/multiview.wgsl rename to naga/tests/in/multiview.wgsl diff --git a/tests/in/multiview_webgl.param.ron b/naga/tests/in/multiview_webgl.param.ron similarity index 100% rename from tests/in/multiview_webgl.param.ron rename to naga/tests/in/multiview_webgl.param.ron diff --git a/tests/in/multiview_webgl.wgsl b/naga/tests/in/multiview_webgl.wgsl similarity index 100% rename from tests/in/multiview_webgl.wgsl rename to naga/tests/in/multiview_webgl.wgsl diff --git a/tests/in/operators.param.ron b/naga/tests/in/operators.param.ron similarity index 100% rename from tests/in/operators.param.ron rename to naga/tests/in/operators.param.ron diff --git a/tests/in/operators.wgsl b/naga/tests/in/operators.wgsl similarity index 100% rename from tests/in/operators.wgsl rename to naga/tests/in/operators.wgsl diff --git a/tests/in/padding.param.ron b/naga/tests/in/padding.param.ron similarity index 100% rename from tests/in/padding.param.ron rename to naga/tests/in/padding.param.ron diff --git a/tests/in/padding.wgsl b/naga/tests/in/padding.wgsl similarity index 100% rename from tests/in/padding.wgsl rename to naga/tests/in/padding.wgsl diff --git a/tests/in/pointers.param.ron b/naga/tests/in/pointers.param.ron similarity index 100% rename from tests/in/pointers.param.ron rename to naga/tests/in/pointers.param.ron diff --git a/tests/in/pointers.wgsl b/naga/tests/in/pointers.wgsl similarity index 100% rename from tests/in/pointers.wgsl rename to naga/tests/in/pointers.wgsl diff --git a/tests/in/policy-mix.param.ron b/naga/tests/in/policy-mix.param.ron similarity index 100% rename from tests/in/policy-mix.param.ron rename to naga/tests/in/policy-mix.param.ron diff --git a/tests/in/policy-mix.wgsl b/naga/tests/in/policy-mix.wgsl similarity index 100% rename from tests/in/policy-mix.wgsl rename to naga/tests/in/policy-mix.wgsl diff --git a/tests/in/push-constants.param.ron b/naga/tests/in/push-constants.param.ron similarity index 100% rename from tests/in/push-constants.param.ron rename to naga/tests/in/push-constants.param.ron diff --git a/tests/in/push-constants.wgsl b/naga/tests/in/push-constants.wgsl similarity index 100% rename from tests/in/push-constants.wgsl rename to naga/tests/in/push-constants.wgsl diff --git a/tests/in/quad.param.ron b/naga/tests/in/quad.param.ron similarity index 100% rename from tests/in/quad.param.ron rename to naga/tests/in/quad.param.ron diff --git a/tests/in/quad.wgsl b/naga/tests/in/quad.wgsl similarity index 100% rename from tests/in/quad.wgsl rename to naga/tests/in/quad.wgsl diff --git a/tests/in/ray-query.param.ron b/naga/tests/in/ray-query.param.ron similarity index 100% rename from tests/in/ray-query.param.ron rename to naga/tests/in/ray-query.param.ron diff --git a/tests/in/ray-query.wgsl b/naga/tests/in/ray-query.wgsl similarity index 100% rename from tests/in/ray-query.wgsl rename to naga/tests/in/ray-query.wgsl diff --git a/tests/in/resource-binding-map.param.ron b/naga/tests/in/resource-binding-map.param.ron similarity index 100% rename from tests/in/resource-binding-map.param.ron rename to naga/tests/in/resource-binding-map.param.ron diff --git a/tests/in/resource-binding-map.wgsl b/naga/tests/in/resource-binding-map.wgsl similarity index 100% rename from tests/in/resource-binding-map.wgsl rename to naga/tests/in/resource-binding-map.wgsl diff --git a/tests/in/runtime-array-in-unused-struct.wgsl b/naga/tests/in/runtime-array-in-unused-struct.wgsl similarity index 100% rename from tests/in/runtime-array-in-unused-struct.wgsl rename to naga/tests/in/runtime-array-in-unused-struct.wgsl diff --git a/tests/in/separate-entry-points.param.ron b/naga/tests/in/separate-entry-points.param.ron similarity index 100% rename from tests/in/separate-entry-points.param.ron rename to naga/tests/in/separate-entry-points.param.ron diff --git a/tests/in/separate-entry-points.wgsl b/naga/tests/in/separate-entry-points.wgsl similarity index 100% rename from tests/in/separate-entry-points.wgsl rename to naga/tests/in/separate-entry-points.wgsl diff --git a/tests/in/shadow.param.ron b/naga/tests/in/shadow.param.ron similarity index 100% rename from tests/in/shadow.param.ron rename to naga/tests/in/shadow.param.ron diff --git a/tests/in/shadow.wgsl b/naga/tests/in/shadow.wgsl similarity index 100% rename from tests/in/shadow.wgsl rename to naga/tests/in/shadow.wgsl diff --git a/tests/in/skybox.param.ron b/naga/tests/in/skybox.param.ron similarity index 100% rename from tests/in/skybox.param.ron rename to naga/tests/in/skybox.param.ron diff --git a/tests/in/skybox.wgsl b/naga/tests/in/skybox.wgsl similarity index 100% rename from tests/in/skybox.wgsl rename to naga/tests/in/skybox.wgsl diff --git a/tests/in/sprite.param.ron b/naga/tests/in/sprite.param.ron similarity index 100% rename from tests/in/sprite.param.ron rename to naga/tests/in/sprite.param.ron diff --git a/tests/in/sprite.wgsl b/naga/tests/in/sprite.wgsl similarity index 100% rename from tests/in/sprite.wgsl rename to naga/tests/in/sprite.wgsl diff --git a/tests/in/spv/binding-arrays.dynamic.spv b/naga/tests/in/spv/binding-arrays.dynamic.spv similarity index 100% rename from tests/in/spv/binding-arrays.dynamic.spv rename to naga/tests/in/spv/binding-arrays.dynamic.spv diff --git a/tests/in/spv/binding-arrays.dynamic.spvasm b/naga/tests/in/spv/binding-arrays.dynamic.spvasm similarity index 100% rename from tests/in/spv/binding-arrays.dynamic.spvasm rename to naga/tests/in/spv/binding-arrays.dynamic.spvasm diff --git a/tests/in/spv/binding-arrays.static.spv b/naga/tests/in/spv/binding-arrays.static.spv similarity index 100% rename from tests/in/spv/binding-arrays.static.spv rename to naga/tests/in/spv/binding-arrays.static.spv diff --git a/tests/in/spv/binding-arrays.static.spvasm b/naga/tests/in/spv/binding-arrays.static.spvasm similarity index 100% rename from tests/in/spv/binding-arrays.static.spvasm rename to naga/tests/in/spv/binding-arrays.static.spvasm diff --git a/tests/in/spv/degrees.spv b/naga/tests/in/spv/degrees.spv similarity index 100% rename from tests/in/spv/degrees.spv rename to naga/tests/in/spv/degrees.spv diff --git a/tests/in/spv/degrees.spvasm b/naga/tests/in/spv/degrees.spvasm similarity index 100% rename from tests/in/spv/degrees.spvasm rename to naga/tests/in/spv/degrees.spvasm diff --git a/tests/in/spv/do-while.spv b/naga/tests/in/spv/do-while.spv similarity index 100% rename from tests/in/spv/do-while.spv rename to naga/tests/in/spv/do-while.spv diff --git a/tests/in/spv/do-while.spvasm b/naga/tests/in/spv/do-while.spvasm similarity index 100% rename from tests/in/spv/do-while.spvasm rename to naga/tests/in/spv/do-while.spvasm diff --git a/tests/in/spv/empty-global-name.spv b/naga/tests/in/spv/empty-global-name.spv similarity index 100% rename from tests/in/spv/empty-global-name.spv rename to naga/tests/in/spv/empty-global-name.spv diff --git a/tests/in/spv/empty-global-name.spvasm b/naga/tests/in/spv/empty-global-name.spvasm similarity index 100% rename from tests/in/spv/empty-global-name.spvasm rename to naga/tests/in/spv/empty-global-name.spvasm diff --git a/tests/in/spv/inv-hyperbolic-trig-functions.spv b/naga/tests/in/spv/inv-hyperbolic-trig-functions.spv similarity index 100% rename from tests/in/spv/inv-hyperbolic-trig-functions.spv rename to naga/tests/in/spv/inv-hyperbolic-trig-functions.spv diff --git a/tests/in/spv/inv-hyperbolic-trig-functions.spvasm b/naga/tests/in/spv/inv-hyperbolic-trig-functions.spvasm similarity index 100% rename from tests/in/spv/inv-hyperbolic-trig-functions.spvasm rename to naga/tests/in/spv/inv-hyperbolic-trig-functions.spvasm diff --git a/tests/in/spv/quad-vert.spv b/naga/tests/in/spv/quad-vert.spv similarity index 100% rename from tests/in/spv/quad-vert.spv rename to naga/tests/in/spv/quad-vert.spv diff --git a/tests/in/spv/quad-vert.spvasm b/naga/tests/in/spv/quad-vert.spvasm similarity index 100% rename from tests/in/spv/quad-vert.spvasm rename to naga/tests/in/spv/quad-vert.spvasm diff --git a/tests/in/spv/shadow.spv b/naga/tests/in/spv/shadow.spv similarity index 100% rename from tests/in/spv/shadow.spv rename to naga/tests/in/spv/shadow.spv diff --git a/tests/in/spv/shadow.spvasm b/naga/tests/in/spv/shadow.spvasm similarity index 100% rename from tests/in/spv/shadow.spvasm rename to naga/tests/in/spv/shadow.spvasm diff --git a/tests/in/standard.param.ron b/naga/tests/in/standard.param.ron similarity index 100% rename from tests/in/standard.param.ron rename to naga/tests/in/standard.param.ron diff --git a/tests/in/standard.wgsl b/naga/tests/in/standard.wgsl similarity index 100% rename from tests/in/standard.wgsl rename to naga/tests/in/standard.wgsl diff --git a/tests/in/texture-arg.param.ron b/naga/tests/in/texture-arg.param.ron similarity index 100% rename from tests/in/texture-arg.param.ron rename to naga/tests/in/texture-arg.param.ron diff --git a/tests/in/texture-arg.wgsl b/naga/tests/in/texture-arg.wgsl similarity index 100% rename from tests/in/texture-arg.wgsl rename to naga/tests/in/texture-arg.wgsl diff --git a/tests/in/type-alias.wgsl b/naga/tests/in/type-alias.wgsl similarity index 100% rename from tests/in/type-alias.wgsl rename to naga/tests/in/type-alias.wgsl diff --git a/tests/in/variations.glsl b/naga/tests/in/variations.glsl similarity index 100% rename from tests/in/variations.glsl rename to naga/tests/in/variations.glsl diff --git a/tests/in/workgroup-uniform-load.wgsl b/naga/tests/in/workgroup-uniform-load.wgsl similarity index 100% rename from tests/in/workgroup-uniform-load.wgsl rename to naga/tests/in/workgroup-uniform-load.wgsl diff --git a/tests/in/workgroup-var-init.param.ron b/naga/tests/in/workgroup-var-init.param.ron similarity index 100% rename from tests/in/workgroup-var-init.param.ron rename to naga/tests/in/workgroup-var-init.param.ron diff --git a/tests/in/workgroup-var-init.wgsl b/naga/tests/in/workgroup-var-init.wgsl similarity index 100% rename from tests/in/workgroup-var-init.wgsl rename to naga/tests/in/workgroup-var-init.wgsl diff --git a/tests/out/analysis/access.info.ron b/naga/tests/out/analysis/access.info.ron similarity index 100% rename from tests/out/analysis/access.info.ron rename to naga/tests/out/analysis/access.info.ron diff --git a/tests/out/analysis/collatz.info.ron b/naga/tests/out/analysis/collatz.info.ron similarity index 100% rename from tests/out/analysis/collatz.info.ron rename to naga/tests/out/analysis/collatz.info.ron diff --git a/tests/out/analysis/shadow.info.ron b/naga/tests/out/analysis/shadow.info.ron similarity index 100% rename from tests/out/analysis/shadow.info.ron rename to naga/tests/out/analysis/shadow.info.ron diff --git a/tests/out/dot/quad.dot b/naga/tests/out/dot/quad.dot similarity index 100% rename from tests/out/dot/quad.dot rename to naga/tests/out/dot/quad.dot diff --git a/tests/out/glsl/access.assign_through_ptr.Compute.glsl b/naga/tests/out/glsl/access.assign_through_ptr.Compute.glsl similarity index 100% rename from tests/out/glsl/access.assign_through_ptr.Compute.glsl rename to naga/tests/out/glsl/access.assign_through_ptr.Compute.glsl diff --git a/tests/out/glsl/access.foo_frag.Fragment.glsl b/naga/tests/out/glsl/access.foo_frag.Fragment.glsl similarity index 100% rename from tests/out/glsl/access.foo_frag.Fragment.glsl rename to naga/tests/out/glsl/access.foo_frag.Fragment.glsl diff --git a/tests/out/glsl/access.foo_vert.Vertex.glsl b/naga/tests/out/glsl/access.foo_vert.Vertex.glsl similarity index 100% rename from tests/out/glsl/access.foo_vert.Vertex.glsl rename to naga/tests/out/glsl/access.foo_vert.Vertex.glsl diff --git a/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl b/naga/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl similarity index 100% rename from tests/out/glsl/array-in-ctor.cs_main.Compute.glsl rename to naga/tests/out/glsl/array-in-ctor.cs_main.Compute.glsl diff --git a/tests/out/glsl/array-in-function-return-type.main.Fragment.glsl b/naga/tests/out/glsl/array-in-function-return-type.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/array-in-function-return-type.main.Fragment.glsl rename to naga/tests/out/glsl/array-in-function-return-type.main.Fragment.glsl diff --git a/tests/out/glsl/atomicOps.cs_main.Compute.glsl b/naga/tests/out/glsl/atomicOps.cs_main.Compute.glsl similarity index 100% rename from tests/out/glsl/atomicOps.cs_main.Compute.glsl rename to naga/tests/out/glsl/atomicOps.cs_main.Compute.glsl diff --git a/tests/out/glsl/bitcast.main.Compute.glsl b/naga/tests/out/glsl/bitcast.main.Compute.glsl similarity index 100% rename from tests/out/glsl/bitcast.main.Compute.glsl rename to naga/tests/out/glsl/bitcast.main.Compute.glsl diff --git a/tests/out/glsl/bits.main.Compute.glsl b/naga/tests/out/glsl/bits.main.Compute.glsl similarity index 100% rename from tests/out/glsl/bits.main.Compute.glsl rename to naga/tests/out/glsl/bits.main.Compute.glsl diff --git a/tests/out/glsl/boids.main.Compute.glsl b/naga/tests/out/glsl/boids.main.Compute.glsl similarity index 100% rename from tests/out/glsl/boids.main.Compute.glsl rename to naga/tests/out/glsl/boids.main.Compute.glsl diff --git a/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl b/naga/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl similarity index 100% rename from tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl rename to naga/tests/out/glsl/bounds-check-image-restrict.fragment_shader.Fragment.glsl diff --git a/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl b/naga/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl similarity index 100% rename from tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl rename to naga/tests/out/glsl/bounds-check-image-rzsw.fragment_shader.Fragment.glsl diff --git a/tests/out/glsl/break-if.main.Compute.glsl b/naga/tests/out/glsl/break-if.main.Compute.glsl similarity index 100% rename from tests/out/glsl/break-if.main.Compute.glsl rename to naga/tests/out/glsl/break-if.main.Compute.glsl diff --git a/tests/out/glsl/const-exprs.main.Compute.glsl b/naga/tests/out/glsl/const-exprs.main.Compute.glsl similarity index 100% rename from tests/out/glsl/const-exprs.main.Compute.glsl rename to naga/tests/out/glsl/const-exprs.main.Compute.glsl diff --git a/tests/out/glsl/constructors.main.Compute.glsl b/naga/tests/out/glsl/constructors.main.Compute.glsl similarity index 100% rename from tests/out/glsl/constructors.main.Compute.glsl rename to naga/tests/out/glsl/constructors.main.Compute.glsl diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/naga/tests/out/glsl/control-flow.main.Compute.glsl similarity index 100% rename from tests/out/glsl/control-flow.main.Compute.glsl rename to naga/tests/out/glsl/control-flow.main.Compute.glsl diff --git a/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl b/naga/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl similarity index 100% rename from tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl rename to naga/tests/out/glsl/cubeArrayShadow.fragment.Fragment.glsl diff --git a/tests/out/glsl/do-while.main.Fragment.glsl b/naga/tests/out/glsl/do-while.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/do-while.main.Fragment.glsl rename to naga/tests/out/glsl/do-while.main.Fragment.glsl diff --git a/tests/out/glsl/dualsource.main.Fragment.glsl b/naga/tests/out/glsl/dualsource.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/dualsource.main.Fragment.glsl rename to naga/tests/out/glsl/dualsource.main.Fragment.glsl diff --git a/tests/out/glsl/empty.main.Compute.glsl b/naga/tests/out/glsl/empty.main.Compute.glsl similarity index 100% rename from tests/out/glsl/empty.main.Compute.glsl rename to naga/tests/out/glsl/empty.main.Compute.glsl diff --git a/tests/out/glsl/force_point_size_vertex_shader_webgl.fs_main.Fragment.glsl b/naga/tests/out/glsl/force_point_size_vertex_shader_webgl.fs_main.Fragment.glsl similarity index 100% rename from tests/out/glsl/force_point_size_vertex_shader_webgl.fs_main.Fragment.glsl rename to naga/tests/out/glsl/force_point_size_vertex_shader_webgl.fs_main.Fragment.glsl diff --git a/tests/out/glsl/force_point_size_vertex_shader_webgl.vs_main.Vertex.glsl b/naga/tests/out/glsl/force_point_size_vertex_shader_webgl.vs_main.Vertex.glsl similarity index 100% rename from tests/out/glsl/force_point_size_vertex_shader_webgl.vs_main.Vertex.glsl rename to naga/tests/out/glsl/force_point_size_vertex_shader_webgl.vs_main.Vertex.glsl diff --git a/tests/out/glsl/fragment-output.main_vec2scalar.Fragment.glsl b/naga/tests/out/glsl/fragment-output.main_vec2scalar.Fragment.glsl similarity index 100% rename from tests/out/glsl/fragment-output.main_vec2scalar.Fragment.glsl rename to naga/tests/out/glsl/fragment-output.main_vec2scalar.Fragment.glsl diff --git a/tests/out/glsl/fragment-output.main_vec4vec3.Fragment.glsl b/naga/tests/out/glsl/fragment-output.main_vec4vec3.Fragment.glsl similarity index 100% rename from tests/out/glsl/fragment-output.main_vec4vec3.Fragment.glsl rename to naga/tests/out/glsl/fragment-output.main_vec4vec3.Fragment.glsl diff --git a/tests/out/glsl/functions-webgl.main.Fragment.glsl b/naga/tests/out/glsl/functions-webgl.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/functions-webgl.main.Fragment.glsl rename to naga/tests/out/glsl/functions-webgl.main.Fragment.glsl diff --git a/tests/out/glsl/functions.main.Compute.glsl b/naga/tests/out/glsl/functions.main.Compute.glsl similarity index 100% rename from tests/out/glsl/functions.main.Compute.glsl rename to naga/tests/out/glsl/functions.main.Compute.glsl diff --git a/tests/out/glsl/globals.main.Compute.glsl b/naga/tests/out/glsl/globals.main.Compute.glsl similarity index 100% rename from tests/out/glsl/globals.main.Compute.glsl rename to naga/tests/out/glsl/globals.main.Compute.glsl diff --git a/tests/out/glsl/image.gather.Fragment.glsl b/naga/tests/out/glsl/image.gather.Fragment.glsl similarity index 100% rename from tests/out/glsl/image.gather.Fragment.glsl rename to naga/tests/out/glsl/image.gather.Fragment.glsl diff --git a/tests/out/glsl/image.main.Compute.glsl b/naga/tests/out/glsl/image.main.Compute.glsl similarity index 100% rename from tests/out/glsl/image.main.Compute.glsl rename to naga/tests/out/glsl/image.main.Compute.glsl diff --git a/tests/out/glsl/image.queries.Vertex.glsl b/naga/tests/out/glsl/image.queries.Vertex.glsl similarity index 100% rename from tests/out/glsl/image.queries.Vertex.glsl rename to naga/tests/out/glsl/image.queries.Vertex.glsl diff --git a/tests/out/glsl/image.texture_sample.Fragment.glsl b/naga/tests/out/glsl/image.texture_sample.Fragment.glsl similarity index 100% rename from tests/out/glsl/image.texture_sample.Fragment.glsl rename to naga/tests/out/glsl/image.texture_sample.Fragment.glsl diff --git a/tests/out/glsl/image.texture_sample_comparison.Fragment.glsl b/naga/tests/out/glsl/image.texture_sample_comparison.Fragment.glsl similarity index 100% rename from tests/out/glsl/image.texture_sample_comparison.Fragment.glsl rename to naga/tests/out/glsl/image.texture_sample_comparison.Fragment.glsl diff --git a/tests/out/glsl/interpolate.frag_main.Fragment.glsl b/naga/tests/out/glsl/interpolate.frag_main.Fragment.glsl similarity index 100% rename from tests/out/glsl/interpolate.frag_main.Fragment.glsl rename to naga/tests/out/glsl/interpolate.frag_main.Fragment.glsl diff --git a/tests/out/glsl/interpolate.vert_main.Vertex.glsl b/naga/tests/out/glsl/interpolate.vert_main.Vertex.glsl similarity index 100% rename from tests/out/glsl/interpolate.vert_main.Vertex.glsl rename to naga/tests/out/glsl/interpolate.vert_main.Vertex.glsl diff --git a/tests/out/glsl/invariant.fs.Fragment.glsl b/naga/tests/out/glsl/invariant.fs.Fragment.glsl similarity index 100% rename from tests/out/glsl/invariant.fs.Fragment.glsl rename to naga/tests/out/glsl/invariant.fs.Fragment.glsl diff --git a/tests/out/glsl/invariant.vs.Vertex.glsl b/naga/tests/out/glsl/invariant.vs.Vertex.glsl similarity index 100% rename from tests/out/glsl/invariant.vs.Vertex.glsl rename to naga/tests/out/glsl/invariant.vs.Vertex.glsl diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/naga/tests/out/glsl/math-functions.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/math-functions.main.Fragment.glsl rename to naga/tests/out/glsl/math-functions.main.Fragment.glsl diff --git a/tests/out/glsl/multiview.main.Fragment.glsl b/naga/tests/out/glsl/multiview.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/multiview.main.Fragment.glsl rename to naga/tests/out/glsl/multiview.main.Fragment.glsl diff --git a/tests/out/glsl/multiview_webgl.main.Fragment.glsl b/naga/tests/out/glsl/multiview_webgl.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/multiview_webgl.main.Fragment.glsl rename to naga/tests/out/glsl/multiview_webgl.main.Fragment.glsl diff --git a/tests/out/glsl/operators.main.Compute.glsl b/naga/tests/out/glsl/operators.main.Compute.glsl similarity index 100% rename from tests/out/glsl/operators.main.Compute.glsl rename to naga/tests/out/glsl/operators.main.Compute.glsl diff --git a/tests/out/glsl/padding.vertex.Vertex.glsl b/naga/tests/out/glsl/padding.vertex.Vertex.glsl similarity index 100% rename from tests/out/glsl/padding.vertex.Vertex.glsl rename to naga/tests/out/glsl/padding.vertex.Vertex.glsl diff --git a/tests/out/glsl/push-constants.main.Fragment.glsl b/naga/tests/out/glsl/push-constants.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/push-constants.main.Fragment.glsl rename to naga/tests/out/glsl/push-constants.main.Fragment.glsl diff --git a/tests/out/glsl/push-constants.vert_main.Vertex.glsl b/naga/tests/out/glsl/push-constants.vert_main.Vertex.glsl similarity index 100% rename from tests/out/glsl/push-constants.vert_main.Vertex.glsl rename to naga/tests/out/glsl/push-constants.vert_main.Vertex.glsl diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/naga/tests/out/glsl/quad-vert.main.Vertex.glsl similarity index 100% rename from tests/out/glsl/quad-vert.main.Vertex.glsl rename to naga/tests/out/glsl/quad-vert.main.Vertex.glsl diff --git a/tests/out/glsl/quad.frag_main.Fragment.glsl b/naga/tests/out/glsl/quad.frag_main.Fragment.glsl similarity index 100% rename from tests/out/glsl/quad.frag_main.Fragment.glsl rename to naga/tests/out/glsl/quad.frag_main.Fragment.glsl diff --git a/tests/out/glsl/quad.fs_extra.Fragment.glsl b/naga/tests/out/glsl/quad.fs_extra.Fragment.glsl similarity index 100% rename from tests/out/glsl/quad.fs_extra.Fragment.glsl rename to naga/tests/out/glsl/quad.fs_extra.Fragment.glsl diff --git a/tests/out/glsl/quad.vert_main.Vertex.glsl b/naga/tests/out/glsl/quad.vert_main.Vertex.glsl similarity index 100% rename from tests/out/glsl/quad.vert_main.Vertex.glsl rename to naga/tests/out/glsl/quad.vert_main.Vertex.glsl diff --git a/tests/out/glsl/separate-entry-points.compute.Compute.glsl b/naga/tests/out/glsl/separate-entry-points.compute.Compute.glsl similarity index 100% rename from tests/out/glsl/separate-entry-points.compute.Compute.glsl rename to naga/tests/out/glsl/separate-entry-points.compute.Compute.glsl diff --git a/tests/out/glsl/separate-entry-points.fragment.Fragment.glsl b/naga/tests/out/glsl/separate-entry-points.fragment.Fragment.glsl similarity index 100% rename from tests/out/glsl/separate-entry-points.fragment.Fragment.glsl rename to naga/tests/out/glsl/separate-entry-points.fragment.Fragment.glsl diff --git a/tests/out/glsl/shadow.fs_main.Fragment.glsl b/naga/tests/out/glsl/shadow.fs_main.Fragment.glsl similarity index 100% rename from tests/out/glsl/shadow.fs_main.Fragment.glsl rename to naga/tests/out/glsl/shadow.fs_main.Fragment.glsl diff --git a/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl b/naga/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl similarity index 100% rename from tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl rename to naga/tests/out/glsl/shadow.fs_main_without_storage.Fragment.glsl diff --git a/tests/out/glsl/shadow.vs_main.Vertex.glsl b/naga/tests/out/glsl/shadow.vs_main.Vertex.glsl similarity index 100% rename from tests/out/glsl/shadow.vs_main.Vertex.glsl rename to naga/tests/out/glsl/shadow.vs_main.Vertex.glsl diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/naga/tests/out/glsl/skybox.fs_main.Fragment.glsl similarity index 100% rename from tests/out/glsl/skybox.fs_main.Fragment.glsl rename to naga/tests/out/glsl/skybox.fs_main.Fragment.glsl diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/naga/tests/out/glsl/skybox.vs_main.Vertex.glsl similarity index 100% rename from tests/out/glsl/skybox.vs_main.Vertex.glsl rename to naga/tests/out/glsl/skybox.vs_main.Vertex.glsl diff --git a/tests/out/glsl/standard.derivatives.Fragment.glsl b/naga/tests/out/glsl/standard.derivatives.Fragment.glsl similarity index 100% rename from tests/out/glsl/standard.derivatives.Fragment.glsl rename to naga/tests/out/glsl/standard.derivatives.Fragment.glsl diff --git a/tests/out/glsl/texture-arg.main.Fragment.glsl b/naga/tests/out/glsl/texture-arg.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/texture-arg.main.Fragment.glsl rename to naga/tests/out/glsl/texture-arg.main.Fragment.glsl diff --git a/tests/out/glsl/variations.main.Fragment.glsl b/naga/tests/out/glsl/variations.main.Fragment.glsl similarity index 100% rename from tests/out/glsl/variations.main.Fragment.glsl rename to naga/tests/out/glsl/variations.main.Fragment.glsl diff --git a/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl b/naga/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl similarity index 100% rename from tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl rename to naga/tests/out/glsl/workgroup-uniform-load.test_workgroupUniformLoad.Compute.glsl diff --git a/tests/out/glsl/workgroup-var-init.main.Compute.glsl b/naga/tests/out/glsl/workgroup-var-init.main.Compute.glsl similarity index 100% rename from tests/out/glsl/workgroup-var-init.main.Compute.glsl rename to naga/tests/out/glsl/workgroup-var-init.main.Compute.glsl diff --git a/tests/out/hlsl/access.hlsl b/naga/tests/out/hlsl/access.hlsl similarity index 100% rename from tests/out/hlsl/access.hlsl rename to naga/tests/out/hlsl/access.hlsl diff --git a/tests/out/hlsl/access.ron b/naga/tests/out/hlsl/access.ron similarity index 100% rename from tests/out/hlsl/access.ron rename to naga/tests/out/hlsl/access.ron diff --git a/tests/out/hlsl/array-in-ctor.hlsl b/naga/tests/out/hlsl/array-in-ctor.hlsl similarity index 100% rename from tests/out/hlsl/array-in-ctor.hlsl rename to naga/tests/out/hlsl/array-in-ctor.hlsl diff --git a/tests/out/hlsl/array-in-ctor.ron b/naga/tests/out/hlsl/array-in-ctor.ron similarity index 100% rename from tests/out/hlsl/array-in-ctor.ron rename to naga/tests/out/hlsl/array-in-ctor.ron diff --git a/tests/out/hlsl/atomicOps.hlsl b/naga/tests/out/hlsl/atomicOps.hlsl similarity index 100% rename from tests/out/hlsl/atomicOps.hlsl rename to naga/tests/out/hlsl/atomicOps.hlsl diff --git a/tests/out/hlsl/atomicOps.ron b/naga/tests/out/hlsl/atomicOps.ron similarity index 100% rename from tests/out/hlsl/atomicOps.ron rename to naga/tests/out/hlsl/atomicOps.ron diff --git a/tests/out/hlsl/binding-arrays.hlsl b/naga/tests/out/hlsl/binding-arrays.hlsl similarity index 100% rename from tests/out/hlsl/binding-arrays.hlsl rename to naga/tests/out/hlsl/binding-arrays.hlsl diff --git a/tests/out/hlsl/binding-arrays.ron b/naga/tests/out/hlsl/binding-arrays.ron similarity index 100% rename from tests/out/hlsl/binding-arrays.ron rename to naga/tests/out/hlsl/binding-arrays.ron diff --git a/tests/out/hlsl/bitcast.hlsl b/naga/tests/out/hlsl/bitcast.hlsl similarity index 100% rename from tests/out/hlsl/bitcast.hlsl rename to naga/tests/out/hlsl/bitcast.hlsl diff --git a/tests/out/hlsl/bitcast.ron b/naga/tests/out/hlsl/bitcast.ron similarity index 100% rename from tests/out/hlsl/bitcast.ron rename to naga/tests/out/hlsl/bitcast.ron diff --git a/tests/out/hlsl/bits.hlsl b/naga/tests/out/hlsl/bits.hlsl similarity index 100% rename from tests/out/hlsl/bits.hlsl rename to naga/tests/out/hlsl/bits.hlsl diff --git a/tests/out/hlsl/bits.ron b/naga/tests/out/hlsl/bits.ron similarity index 100% rename from tests/out/hlsl/bits.ron rename to naga/tests/out/hlsl/bits.ron diff --git a/tests/out/hlsl/boids.hlsl b/naga/tests/out/hlsl/boids.hlsl similarity index 100% rename from tests/out/hlsl/boids.hlsl rename to naga/tests/out/hlsl/boids.hlsl diff --git a/tests/out/hlsl/boids.ron b/naga/tests/out/hlsl/boids.ron similarity index 100% rename from tests/out/hlsl/boids.ron rename to naga/tests/out/hlsl/boids.ron diff --git a/tests/out/hlsl/break-if.hlsl b/naga/tests/out/hlsl/break-if.hlsl similarity index 100% rename from tests/out/hlsl/break-if.hlsl rename to naga/tests/out/hlsl/break-if.hlsl diff --git a/tests/out/hlsl/break-if.ron b/naga/tests/out/hlsl/break-if.ron similarity index 100% rename from tests/out/hlsl/break-if.ron rename to naga/tests/out/hlsl/break-if.ron diff --git a/tests/out/hlsl/collatz.hlsl b/naga/tests/out/hlsl/collatz.hlsl similarity index 100% rename from tests/out/hlsl/collatz.hlsl rename to naga/tests/out/hlsl/collatz.hlsl diff --git a/tests/out/hlsl/collatz.ron b/naga/tests/out/hlsl/collatz.ron similarity index 100% rename from tests/out/hlsl/collatz.ron rename to naga/tests/out/hlsl/collatz.ron diff --git a/tests/out/hlsl/const-exprs.hlsl b/naga/tests/out/hlsl/const-exprs.hlsl similarity index 100% rename from tests/out/hlsl/const-exprs.hlsl rename to naga/tests/out/hlsl/const-exprs.hlsl diff --git a/tests/out/hlsl/const-exprs.ron b/naga/tests/out/hlsl/const-exprs.ron similarity index 100% rename from tests/out/hlsl/const-exprs.ron rename to naga/tests/out/hlsl/const-exprs.ron diff --git a/tests/out/hlsl/constructors.hlsl b/naga/tests/out/hlsl/constructors.hlsl similarity index 100% rename from tests/out/hlsl/constructors.hlsl rename to naga/tests/out/hlsl/constructors.hlsl diff --git a/tests/out/hlsl/constructors.ron b/naga/tests/out/hlsl/constructors.ron similarity index 100% rename from tests/out/hlsl/constructors.ron rename to naga/tests/out/hlsl/constructors.ron diff --git a/tests/out/hlsl/control-flow.hlsl b/naga/tests/out/hlsl/control-flow.hlsl similarity index 100% rename from tests/out/hlsl/control-flow.hlsl rename to naga/tests/out/hlsl/control-flow.hlsl diff --git a/tests/out/hlsl/control-flow.ron b/naga/tests/out/hlsl/control-flow.ron similarity index 100% rename from tests/out/hlsl/control-flow.ron rename to naga/tests/out/hlsl/control-flow.ron diff --git a/tests/out/hlsl/do-while.hlsl b/naga/tests/out/hlsl/do-while.hlsl similarity index 100% rename from tests/out/hlsl/do-while.hlsl rename to naga/tests/out/hlsl/do-while.hlsl diff --git a/tests/out/hlsl/do-while.ron b/naga/tests/out/hlsl/do-while.ron similarity index 100% rename from tests/out/hlsl/do-while.ron rename to naga/tests/out/hlsl/do-while.ron diff --git a/tests/out/hlsl/dualsource.hlsl b/naga/tests/out/hlsl/dualsource.hlsl similarity index 100% rename from tests/out/hlsl/dualsource.hlsl rename to naga/tests/out/hlsl/dualsource.hlsl diff --git a/tests/out/hlsl/dualsource.ron b/naga/tests/out/hlsl/dualsource.ron similarity index 100% rename from tests/out/hlsl/dualsource.ron rename to naga/tests/out/hlsl/dualsource.ron diff --git a/tests/out/hlsl/empty-global-name.hlsl b/naga/tests/out/hlsl/empty-global-name.hlsl similarity index 100% rename from tests/out/hlsl/empty-global-name.hlsl rename to naga/tests/out/hlsl/empty-global-name.hlsl diff --git a/tests/out/hlsl/empty-global-name.ron b/naga/tests/out/hlsl/empty-global-name.ron similarity index 100% rename from tests/out/hlsl/empty-global-name.ron rename to naga/tests/out/hlsl/empty-global-name.ron diff --git a/tests/out/hlsl/empty.hlsl b/naga/tests/out/hlsl/empty.hlsl similarity index 100% rename from tests/out/hlsl/empty.hlsl rename to naga/tests/out/hlsl/empty.hlsl diff --git a/tests/out/hlsl/empty.ron b/naga/tests/out/hlsl/empty.ron similarity index 100% rename from tests/out/hlsl/empty.ron rename to naga/tests/out/hlsl/empty.ron diff --git a/tests/out/hlsl/fragment-output.hlsl b/naga/tests/out/hlsl/fragment-output.hlsl similarity index 100% rename from tests/out/hlsl/fragment-output.hlsl rename to naga/tests/out/hlsl/fragment-output.hlsl diff --git a/tests/out/hlsl/fragment-output.ron b/naga/tests/out/hlsl/fragment-output.ron similarity index 100% rename from tests/out/hlsl/fragment-output.ron rename to naga/tests/out/hlsl/fragment-output.ron diff --git a/tests/out/hlsl/functions.hlsl b/naga/tests/out/hlsl/functions.hlsl similarity index 100% rename from tests/out/hlsl/functions.hlsl rename to naga/tests/out/hlsl/functions.hlsl diff --git a/tests/out/hlsl/functions.ron b/naga/tests/out/hlsl/functions.ron similarity index 100% rename from tests/out/hlsl/functions.ron rename to naga/tests/out/hlsl/functions.ron diff --git a/tests/out/hlsl/globals.hlsl b/naga/tests/out/hlsl/globals.hlsl similarity index 100% rename from tests/out/hlsl/globals.hlsl rename to naga/tests/out/hlsl/globals.hlsl diff --git a/tests/out/hlsl/globals.ron b/naga/tests/out/hlsl/globals.ron similarity index 100% rename from tests/out/hlsl/globals.ron rename to naga/tests/out/hlsl/globals.ron diff --git a/tests/out/hlsl/hlsl-keyword.hlsl b/naga/tests/out/hlsl/hlsl-keyword.hlsl similarity index 100% rename from tests/out/hlsl/hlsl-keyword.hlsl rename to naga/tests/out/hlsl/hlsl-keyword.hlsl diff --git a/tests/out/hlsl/hlsl-keyword.ron b/naga/tests/out/hlsl/hlsl-keyword.ron similarity index 100% rename from tests/out/hlsl/hlsl-keyword.ron rename to naga/tests/out/hlsl/hlsl-keyword.ron diff --git a/tests/out/hlsl/image.hlsl b/naga/tests/out/hlsl/image.hlsl similarity index 100% rename from tests/out/hlsl/image.hlsl rename to naga/tests/out/hlsl/image.hlsl diff --git a/tests/out/hlsl/image.ron b/naga/tests/out/hlsl/image.ron similarity index 100% rename from tests/out/hlsl/image.ron rename to naga/tests/out/hlsl/image.ron diff --git a/tests/out/hlsl/interface.hlsl b/naga/tests/out/hlsl/interface.hlsl similarity index 100% rename from tests/out/hlsl/interface.hlsl rename to naga/tests/out/hlsl/interface.hlsl diff --git a/tests/out/hlsl/interface.ron b/naga/tests/out/hlsl/interface.ron similarity index 100% rename from tests/out/hlsl/interface.ron rename to naga/tests/out/hlsl/interface.ron diff --git a/tests/out/hlsl/interpolate.hlsl b/naga/tests/out/hlsl/interpolate.hlsl similarity index 100% rename from tests/out/hlsl/interpolate.hlsl rename to naga/tests/out/hlsl/interpolate.hlsl diff --git a/tests/out/hlsl/interpolate.ron b/naga/tests/out/hlsl/interpolate.ron similarity index 100% rename from tests/out/hlsl/interpolate.ron rename to naga/tests/out/hlsl/interpolate.ron diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl b/naga/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl similarity index 100% rename from tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl rename to naga/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.ron b/naga/tests/out/hlsl/inv-hyperbolic-trig-functions.ron similarity index 100% rename from tests/out/hlsl/inv-hyperbolic-trig-functions.ron rename to naga/tests/out/hlsl/inv-hyperbolic-trig-functions.ron diff --git a/tests/out/hlsl/math-functions.hlsl b/naga/tests/out/hlsl/math-functions.hlsl similarity index 100% rename from tests/out/hlsl/math-functions.hlsl rename to naga/tests/out/hlsl/math-functions.hlsl diff --git a/tests/out/hlsl/math-functions.ron b/naga/tests/out/hlsl/math-functions.ron similarity index 100% rename from tests/out/hlsl/math-functions.ron rename to naga/tests/out/hlsl/math-functions.ron diff --git a/tests/out/hlsl/operators.hlsl b/naga/tests/out/hlsl/operators.hlsl similarity index 100% rename from tests/out/hlsl/operators.hlsl rename to naga/tests/out/hlsl/operators.hlsl diff --git a/tests/out/hlsl/operators.ron b/naga/tests/out/hlsl/operators.ron similarity index 100% rename from tests/out/hlsl/operators.ron rename to naga/tests/out/hlsl/operators.ron diff --git a/tests/out/hlsl/padding.hlsl b/naga/tests/out/hlsl/padding.hlsl similarity index 100% rename from tests/out/hlsl/padding.hlsl rename to naga/tests/out/hlsl/padding.hlsl diff --git a/tests/out/hlsl/padding.ron b/naga/tests/out/hlsl/padding.ron similarity index 100% rename from tests/out/hlsl/padding.ron rename to naga/tests/out/hlsl/padding.ron diff --git a/tests/out/hlsl/push-constants.hlsl b/naga/tests/out/hlsl/push-constants.hlsl similarity index 100% rename from tests/out/hlsl/push-constants.hlsl rename to naga/tests/out/hlsl/push-constants.hlsl diff --git a/tests/out/hlsl/push-constants.ron b/naga/tests/out/hlsl/push-constants.ron similarity index 100% rename from tests/out/hlsl/push-constants.ron rename to naga/tests/out/hlsl/push-constants.ron diff --git a/tests/out/hlsl/quad-vert.hlsl b/naga/tests/out/hlsl/quad-vert.hlsl similarity index 100% rename from tests/out/hlsl/quad-vert.hlsl rename to naga/tests/out/hlsl/quad-vert.hlsl diff --git a/tests/out/hlsl/quad-vert.ron b/naga/tests/out/hlsl/quad-vert.ron similarity index 100% rename from tests/out/hlsl/quad-vert.ron rename to naga/tests/out/hlsl/quad-vert.ron diff --git a/tests/out/hlsl/quad.hlsl b/naga/tests/out/hlsl/quad.hlsl similarity index 100% rename from tests/out/hlsl/quad.hlsl rename to naga/tests/out/hlsl/quad.hlsl diff --git a/tests/out/hlsl/quad.ron b/naga/tests/out/hlsl/quad.ron similarity index 100% rename from tests/out/hlsl/quad.ron rename to naga/tests/out/hlsl/quad.ron diff --git a/tests/out/hlsl/shadow.hlsl b/naga/tests/out/hlsl/shadow.hlsl similarity index 100% rename from tests/out/hlsl/shadow.hlsl rename to naga/tests/out/hlsl/shadow.hlsl diff --git a/tests/out/hlsl/shadow.ron b/naga/tests/out/hlsl/shadow.ron similarity index 100% rename from tests/out/hlsl/shadow.ron rename to naga/tests/out/hlsl/shadow.ron diff --git a/tests/out/hlsl/skybox.hlsl b/naga/tests/out/hlsl/skybox.hlsl similarity index 100% rename from tests/out/hlsl/skybox.hlsl rename to naga/tests/out/hlsl/skybox.hlsl diff --git a/tests/out/hlsl/skybox.ron b/naga/tests/out/hlsl/skybox.ron similarity index 100% rename from tests/out/hlsl/skybox.ron rename to naga/tests/out/hlsl/skybox.ron diff --git a/tests/out/hlsl/standard.hlsl b/naga/tests/out/hlsl/standard.hlsl similarity index 100% rename from tests/out/hlsl/standard.hlsl rename to naga/tests/out/hlsl/standard.hlsl diff --git a/tests/out/hlsl/standard.ron b/naga/tests/out/hlsl/standard.ron similarity index 100% rename from tests/out/hlsl/standard.ron rename to naga/tests/out/hlsl/standard.ron diff --git a/tests/out/hlsl/texture-arg.hlsl b/naga/tests/out/hlsl/texture-arg.hlsl similarity index 100% rename from tests/out/hlsl/texture-arg.hlsl rename to naga/tests/out/hlsl/texture-arg.hlsl diff --git a/tests/out/hlsl/texture-arg.ron b/naga/tests/out/hlsl/texture-arg.ron similarity index 100% rename from tests/out/hlsl/texture-arg.ron rename to naga/tests/out/hlsl/texture-arg.ron diff --git a/tests/out/hlsl/workgroup-uniform-load.hlsl b/naga/tests/out/hlsl/workgroup-uniform-load.hlsl similarity index 100% rename from tests/out/hlsl/workgroup-uniform-load.hlsl rename to naga/tests/out/hlsl/workgroup-uniform-load.hlsl diff --git a/tests/out/hlsl/workgroup-uniform-load.ron b/naga/tests/out/hlsl/workgroup-uniform-load.ron similarity index 100% rename from tests/out/hlsl/workgroup-uniform-load.ron rename to naga/tests/out/hlsl/workgroup-uniform-load.ron diff --git a/tests/out/hlsl/workgroup-var-init.hlsl b/naga/tests/out/hlsl/workgroup-var-init.hlsl similarity index 100% rename from tests/out/hlsl/workgroup-var-init.hlsl rename to naga/tests/out/hlsl/workgroup-var-init.hlsl diff --git a/tests/out/hlsl/workgroup-var-init.ron b/naga/tests/out/hlsl/workgroup-var-init.ron similarity index 100% rename from tests/out/hlsl/workgroup-var-init.ron rename to naga/tests/out/hlsl/workgroup-var-init.ron diff --git a/tests/out/ir/access.compact.ron b/naga/tests/out/ir/access.compact.ron similarity index 100% rename from tests/out/ir/access.compact.ron rename to naga/tests/out/ir/access.compact.ron diff --git a/tests/out/ir/access.ron b/naga/tests/out/ir/access.ron similarity index 100% rename from tests/out/ir/access.ron rename to naga/tests/out/ir/access.ron diff --git a/tests/out/ir/collatz.compact.ron b/naga/tests/out/ir/collatz.compact.ron similarity index 100% rename from tests/out/ir/collatz.compact.ron rename to naga/tests/out/ir/collatz.compact.ron diff --git a/tests/out/ir/collatz.ron b/naga/tests/out/ir/collatz.ron similarity index 100% rename from tests/out/ir/collatz.ron rename to naga/tests/out/ir/collatz.ron diff --git a/tests/out/ir/shadow.compact.ron b/naga/tests/out/ir/shadow.compact.ron similarity index 100% rename from tests/out/ir/shadow.compact.ron rename to naga/tests/out/ir/shadow.compact.ron diff --git a/tests/out/ir/shadow.ron b/naga/tests/out/ir/shadow.ron similarity index 100% rename from tests/out/ir/shadow.ron rename to naga/tests/out/ir/shadow.ron diff --git a/tests/out/msl/access.msl b/naga/tests/out/msl/access.msl similarity index 100% rename from tests/out/msl/access.msl rename to naga/tests/out/msl/access.msl diff --git a/tests/out/msl/array-in-ctor.msl b/naga/tests/out/msl/array-in-ctor.msl similarity index 100% rename from tests/out/msl/array-in-ctor.msl rename to naga/tests/out/msl/array-in-ctor.msl diff --git a/tests/out/msl/array-in-function-return-type.msl b/naga/tests/out/msl/array-in-function-return-type.msl similarity index 100% rename from tests/out/msl/array-in-function-return-type.msl rename to naga/tests/out/msl/array-in-function-return-type.msl diff --git a/tests/out/msl/atomicOps.msl b/naga/tests/out/msl/atomicOps.msl similarity index 100% rename from tests/out/msl/atomicOps.msl rename to naga/tests/out/msl/atomicOps.msl diff --git a/tests/out/msl/binding-arrays.msl b/naga/tests/out/msl/binding-arrays.msl similarity index 100% rename from tests/out/msl/binding-arrays.msl rename to naga/tests/out/msl/binding-arrays.msl diff --git a/tests/out/msl/bitcast.msl b/naga/tests/out/msl/bitcast.msl similarity index 100% rename from tests/out/msl/bitcast.msl rename to naga/tests/out/msl/bitcast.msl diff --git a/tests/out/msl/bits.msl b/naga/tests/out/msl/bits.msl similarity index 100% rename from tests/out/msl/bits.msl rename to naga/tests/out/msl/bits.msl diff --git a/tests/out/msl/boids.msl b/naga/tests/out/msl/boids.msl similarity index 100% rename from tests/out/msl/boids.msl rename to naga/tests/out/msl/boids.msl diff --git a/tests/out/msl/bounds-check-image-restrict.msl b/naga/tests/out/msl/bounds-check-image-restrict.msl similarity index 100% rename from tests/out/msl/bounds-check-image-restrict.msl rename to naga/tests/out/msl/bounds-check-image-restrict.msl diff --git a/tests/out/msl/bounds-check-image-rzsw.msl b/naga/tests/out/msl/bounds-check-image-rzsw.msl similarity index 100% rename from tests/out/msl/bounds-check-image-rzsw.msl rename to naga/tests/out/msl/bounds-check-image-rzsw.msl diff --git a/tests/out/msl/bounds-check-restrict.msl b/naga/tests/out/msl/bounds-check-restrict.msl similarity index 100% rename from tests/out/msl/bounds-check-restrict.msl rename to naga/tests/out/msl/bounds-check-restrict.msl diff --git a/tests/out/msl/bounds-check-zero-atomic.msl b/naga/tests/out/msl/bounds-check-zero-atomic.msl similarity index 100% rename from tests/out/msl/bounds-check-zero-atomic.msl rename to naga/tests/out/msl/bounds-check-zero-atomic.msl diff --git a/tests/out/msl/bounds-check-zero.msl b/naga/tests/out/msl/bounds-check-zero.msl similarity index 100% rename from tests/out/msl/bounds-check-zero.msl rename to naga/tests/out/msl/bounds-check-zero.msl diff --git a/tests/out/msl/break-if.msl b/naga/tests/out/msl/break-if.msl similarity index 100% rename from tests/out/msl/break-if.msl rename to naga/tests/out/msl/break-if.msl diff --git a/tests/out/msl/collatz.msl b/naga/tests/out/msl/collatz.msl similarity index 100% rename from tests/out/msl/collatz.msl rename to naga/tests/out/msl/collatz.msl diff --git a/tests/out/msl/const-exprs.msl b/naga/tests/out/msl/const-exprs.msl similarity index 100% rename from tests/out/msl/const-exprs.msl rename to naga/tests/out/msl/const-exprs.msl diff --git a/tests/out/msl/constructors.msl b/naga/tests/out/msl/constructors.msl similarity index 100% rename from tests/out/msl/constructors.msl rename to naga/tests/out/msl/constructors.msl diff --git a/tests/out/msl/control-flow.msl b/naga/tests/out/msl/control-flow.msl similarity index 100% rename from tests/out/msl/control-flow.msl rename to naga/tests/out/msl/control-flow.msl diff --git a/tests/out/msl/do-while.msl b/naga/tests/out/msl/do-while.msl similarity index 100% rename from tests/out/msl/do-while.msl rename to naga/tests/out/msl/do-while.msl diff --git a/tests/out/msl/dualsource.msl b/naga/tests/out/msl/dualsource.msl similarity index 100% rename from tests/out/msl/dualsource.msl rename to naga/tests/out/msl/dualsource.msl diff --git a/tests/out/msl/empty-global-name.msl b/naga/tests/out/msl/empty-global-name.msl similarity index 100% rename from tests/out/msl/empty-global-name.msl rename to naga/tests/out/msl/empty-global-name.msl diff --git a/tests/out/msl/empty.msl b/naga/tests/out/msl/empty.msl similarity index 100% rename from tests/out/msl/empty.msl rename to naga/tests/out/msl/empty.msl diff --git a/tests/out/msl/extra.msl b/naga/tests/out/msl/extra.msl similarity index 100% rename from tests/out/msl/extra.msl rename to naga/tests/out/msl/extra.msl diff --git a/tests/out/msl/fragment-output.msl b/naga/tests/out/msl/fragment-output.msl similarity index 100% rename from tests/out/msl/fragment-output.msl rename to naga/tests/out/msl/fragment-output.msl diff --git a/tests/out/msl/functions.msl b/naga/tests/out/msl/functions.msl similarity index 100% rename from tests/out/msl/functions.msl rename to naga/tests/out/msl/functions.msl diff --git a/tests/out/msl/globals.msl b/naga/tests/out/msl/globals.msl similarity index 100% rename from tests/out/msl/globals.msl rename to naga/tests/out/msl/globals.msl diff --git a/tests/out/msl/image.msl b/naga/tests/out/msl/image.msl similarity index 100% rename from tests/out/msl/image.msl rename to naga/tests/out/msl/image.msl diff --git a/tests/out/msl/interface.msl b/naga/tests/out/msl/interface.msl similarity index 100% rename from tests/out/msl/interface.msl rename to naga/tests/out/msl/interface.msl diff --git a/tests/out/msl/interpolate.msl b/naga/tests/out/msl/interpolate.msl similarity index 100% rename from tests/out/msl/interpolate.msl rename to naga/tests/out/msl/interpolate.msl diff --git a/tests/out/msl/math-functions.msl b/naga/tests/out/msl/math-functions.msl similarity index 100% rename from tests/out/msl/math-functions.msl rename to naga/tests/out/msl/math-functions.msl diff --git a/tests/out/msl/msl-varyings.msl b/naga/tests/out/msl/msl-varyings.msl similarity index 100% rename from tests/out/msl/msl-varyings.msl rename to naga/tests/out/msl/msl-varyings.msl diff --git a/tests/out/msl/operators.msl b/naga/tests/out/msl/operators.msl similarity index 100% rename from tests/out/msl/operators.msl rename to naga/tests/out/msl/operators.msl diff --git a/tests/out/msl/padding.msl b/naga/tests/out/msl/padding.msl similarity index 100% rename from tests/out/msl/padding.msl rename to naga/tests/out/msl/padding.msl diff --git a/tests/out/msl/policy-mix.msl b/naga/tests/out/msl/policy-mix.msl similarity index 100% rename from tests/out/msl/policy-mix.msl rename to naga/tests/out/msl/policy-mix.msl diff --git a/tests/out/msl/quad-vert.msl b/naga/tests/out/msl/quad-vert.msl similarity index 100% rename from tests/out/msl/quad-vert.msl rename to naga/tests/out/msl/quad-vert.msl diff --git a/tests/out/msl/quad.msl b/naga/tests/out/msl/quad.msl similarity index 100% rename from tests/out/msl/quad.msl rename to naga/tests/out/msl/quad.msl diff --git a/tests/out/msl/ray-query.msl b/naga/tests/out/msl/ray-query.msl similarity index 100% rename from tests/out/msl/ray-query.msl rename to naga/tests/out/msl/ray-query.msl diff --git a/tests/out/msl/resource-binding-map.msl b/naga/tests/out/msl/resource-binding-map.msl similarity index 100% rename from tests/out/msl/resource-binding-map.msl rename to naga/tests/out/msl/resource-binding-map.msl diff --git a/tests/out/msl/shadow.msl b/naga/tests/out/msl/shadow.msl similarity index 100% rename from tests/out/msl/shadow.msl rename to naga/tests/out/msl/shadow.msl diff --git a/tests/out/msl/skybox.msl b/naga/tests/out/msl/skybox.msl similarity index 100% rename from tests/out/msl/skybox.msl rename to naga/tests/out/msl/skybox.msl diff --git a/tests/out/msl/standard.msl b/naga/tests/out/msl/standard.msl similarity index 100% rename from tests/out/msl/standard.msl rename to naga/tests/out/msl/standard.msl diff --git a/tests/out/msl/texture-arg.msl b/naga/tests/out/msl/texture-arg.msl similarity index 100% rename from tests/out/msl/texture-arg.msl rename to naga/tests/out/msl/texture-arg.msl diff --git a/tests/out/msl/workgroup-uniform-load.msl b/naga/tests/out/msl/workgroup-uniform-load.msl similarity index 100% rename from tests/out/msl/workgroup-uniform-load.msl rename to naga/tests/out/msl/workgroup-uniform-load.msl diff --git a/tests/out/msl/workgroup-var-init.msl b/naga/tests/out/msl/workgroup-var-init.msl similarity index 100% rename from tests/out/msl/workgroup-var-init.msl rename to naga/tests/out/msl/workgroup-var-init.msl diff --git a/tests/out/spv/access.spvasm b/naga/tests/out/spv/access.spvasm similarity index 100% rename from tests/out/spv/access.spvasm rename to naga/tests/out/spv/access.spvasm diff --git a/tests/out/spv/array-in-ctor.spvasm b/naga/tests/out/spv/array-in-ctor.spvasm similarity index 100% rename from tests/out/spv/array-in-ctor.spvasm rename to naga/tests/out/spv/array-in-ctor.spvasm diff --git a/tests/out/spv/array-in-function-return-type.spvasm b/naga/tests/out/spv/array-in-function-return-type.spvasm similarity index 100% rename from tests/out/spv/array-in-function-return-type.spvasm rename to naga/tests/out/spv/array-in-function-return-type.spvasm diff --git a/tests/out/spv/atomicCompareExchange.spvasm b/naga/tests/out/spv/atomicCompareExchange.spvasm similarity index 100% rename from tests/out/spv/atomicCompareExchange.spvasm rename to naga/tests/out/spv/atomicCompareExchange.spvasm diff --git a/tests/out/spv/atomicOps.spvasm b/naga/tests/out/spv/atomicOps.spvasm similarity index 100% rename from tests/out/spv/atomicOps.spvasm rename to naga/tests/out/spv/atomicOps.spvasm diff --git a/tests/out/spv/binding-arrays.spvasm b/naga/tests/out/spv/binding-arrays.spvasm similarity index 100% rename from tests/out/spv/binding-arrays.spvasm rename to naga/tests/out/spv/binding-arrays.spvasm diff --git a/tests/out/spv/binding-buffer-arrays.spvasm b/naga/tests/out/spv/binding-buffer-arrays.spvasm similarity index 100% rename from tests/out/spv/binding-buffer-arrays.spvasm rename to naga/tests/out/spv/binding-buffer-arrays.spvasm diff --git a/tests/out/spv/bitcast.spvasm b/naga/tests/out/spv/bitcast.spvasm similarity index 100% rename from tests/out/spv/bitcast.spvasm rename to naga/tests/out/spv/bitcast.spvasm diff --git a/tests/out/spv/bits.spvasm b/naga/tests/out/spv/bits.spvasm similarity index 100% rename from tests/out/spv/bits.spvasm rename to naga/tests/out/spv/bits.spvasm diff --git a/tests/out/spv/boids.spvasm b/naga/tests/out/spv/boids.spvasm similarity index 100% rename from tests/out/spv/boids.spvasm rename to naga/tests/out/spv/boids.spvasm diff --git a/tests/out/spv/bounds-check-image-restrict.spvasm b/naga/tests/out/spv/bounds-check-image-restrict.spvasm similarity index 100% rename from tests/out/spv/bounds-check-image-restrict.spvasm rename to naga/tests/out/spv/bounds-check-image-restrict.spvasm diff --git a/tests/out/spv/bounds-check-image-rzsw.spvasm b/naga/tests/out/spv/bounds-check-image-rzsw.spvasm similarity index 100% rename from tests/out/spv/bounds-check-image-rzsw.spvasm rename to naga/tests/out/spv/bounds-check-image-rzsw.spvasm diff --git a/tests/out/spv/bounds-check-restrict.spvasm b/naga/tests/out/spv/bounds-check-restrict.spvasm similarity index 100% rename from tests/out/spv/bounds-check-restrict.spvasm rename to naga/tests/out/spv/bounds-check-restrict.spvasm diff --git a/tests/out/spv/bounds-check-zero.spvasm b/naga/tests/out/spv/bounds-check-zero.spvasm similarity index 100% rename from tests/out/spv/bounds-check-zero.spvasm rename to naga/tests/out/spv/bounds-check-zero.spvasm diff --git a/tests/out/spv/break-if.spvasm b/naga/tests/out/spv/break-if.spvasm similarity index 100% rename from tests/out/spv/break-if.spvasm rename to naga/tests/out/spv/break-if.spvasm diff --git a/tests/out/spv/collatz.spvasm b/naga/tests/out/spv/collatz.spvasm similarity index 100% rename from tests/out/spv/collatz.spvasm rename to naga/tests/out/spv/collatz.spvasm diff --git a/tests/out/spv/const-exprs.spvasm b/naga/tests/out/spv/const-exprs.spvasm similarity index 100% rename from tests/out/spv/const-exprs.spvasm rename to naga/tests/out/spv/const-exprs.spvasm diff --git a/tests/out/spv/constructors.spvasm b/naga/tests/out/spv/constructors.spvasm similarity index 100% rename from tests/out/spv/constructors.spvasm rename to naga/tests/out/spv/constructors.spvasm diff --git a/tests/out/spv/control-flow.spvasm b/naga/tests/out/spv/control-flow.spvasm similarity index 100% rename from tests/out/spv/control-flow.spvasm rename to naga/tests/out/spv/control-flow.spvasm diff --git a/tests/out/spv/debug-symbol-simple.spvasm b/naga/tests/out/spv/debug-symbol-simple.spvasm similarity index 100% rename from tests/out/spv/debug-symbol-simple.spvasm rename to naga/tests/out/spv/debug-symbol-simple.spvasm diff --git a/tests/out/spv/debug-symbol-terrain.spvasm b/naga/tests/out/spv/debug-symbol-terrain.spvasm similarity index 100% rename from tests/out/spv/debug-symbol-terrain.spvasm rename to naga/tests/out/spv/debug-symbol-terrain.spvasm diff --git a/tests/out/spv/dualsource.spvasm b/naga/tests/out/spv/dualsource.spvasm similarity index 100% rename from tests/out/spv/dualsource.spvasm rename to naga/tests/out/spv/dualsource.spvasm diff --git a/tests/out/spv/empty.spvasm b/naga/tests/out/spv/empty.spvasm similarity index 100% rename from tests/out/spv/empty.spvasm rename to naga/tests/out/spv/empty.spvasm diff --git a/tests/out/spv/extra.spvasm b/naga/tests/out/spv/extra.spvasm similarity index 100% rename from tests/out/spv/extra.spvasm rename to naga/tests/out/spv/extra.spvasm diff --git a/tests/out/spv/fragment-output.spvasm b/naga/tests/out/spv/fragment-output.spvasm similarity index 100% rename from tests/out/spv/fragment-output.spvasm rename to naga/tests/out/spv/fragment-output.spvasm diff --git a/tests/out/spv/functions.spvasm b/naga/tests/out/spv/functions.spvasm similarity index 100% rename from tests/out/spv/functions.spvasm rename to naga/tests/out/spv/functions.spvasm diff --git a/tests/out/spv/globals.spvasm b/naga/tests/out/spv/globals.spvasm similarity index 100% rename from tests/out/spv/globals.spvasm rename to naga/tests/out/spv/globals.spvasm diff --git a/tests/out/spv/image.spvasm b/naga/tests/out/spv/image.spvasm similarity index 100% rename from tests/out/spv/image.spvasm rename to naga/tests/out/spv/image.spvasm diff --git a/tests/out/spv/interface.compute.spvasm b/naga/tests/out/spv/interface.compute.spvasm similarity index 100% rename from tests/out/spv/interface.compute.spvasm rename to naga/tests/out/spv/interface.compute.spvasm diff --git a/tests/out/spv/interface.fragment.spvasm b/naga/tests/out/spv/interface.fragment.spvasm similarity index 100% rename from tests/out/spv/interface.fragment.spvasm rename to naga/tests/out/spv/interface.fragment.spvasm diff --git a/tests/out/spv/interface.vertex.spvasm b/naga/tests/out/spv/interface.vertex.spvasm similarity index 100% rename from tests/out/spv/interface.vertex.spvasm rename to naga/tests/out/spv/interface.vertex.spvasm diff --git a/tests/out/spv/interface.vertex_two_structs.spvasm b/naga/tests/out/spv/interface.vertex_two_structs.spvasm similarity index 100% rename from tests/out/spv/interface.vertex_two_structs.spvasm rename to naga/tests/out/spv/interface.vertex_two_structs.spvasm diff --git a/tests/out/spv/interpolate.spvasm b/naga/tests/out/spv/interpolate.spvasm similarity index 100% rename from tests/out/spv/interpolate.spvasm rename to naga/tests/out/spv/interpolate.spvasm diff --git a/tests/out/spv/math-functions.spvasm b/naga/tests/out/spv/math-functions.spvasm similarity index 100% rename from tests/out/spv/math-functions.spvasm rename to naga/tests/out/spv/math-functions.spvasm diff --git a/tests/out/spv/multiview.spvasm b/naga/tests/out/spv/multiview.spvasm similarity index 100% rename from tests/out/spv/multiview.spvasm rename to naga/tests/out/spv/multiview.spvasm diff --git a/tests/out/spv/operators.spvasm b/naga/tests/out/spv/operators.spvasm similarity index 100% rename from tests/out/spv/operators.spvasm rename to naga/tests/out/spv/operators.spvasm diff --git a/tests/out/spv/padding.spvasm b/naga/tests/out/spv/padding.spvasm similarity index 100% rename from tests/out/spv/padding.spvasm rename to naga/tests/out/spv/padding.spvasm diff --git a/tests/out/spv/pointers.spvasm b/naga/tests/out/spv/pointers.spvasm similarity index 100% rename from tests/out/spv/pointers.spvasm rename to naga/tests/out/spv/pointers.spvasm diff --git a/tests/out/spv/policy-mix.spvasm b/naga/tests/out/spv/policy-mix.spvasm similarity index 100% rename from tests/out/spv/policy-mix.spvasm rename to naga/tests/out/spv/policy-mix.spvasm diff --git a/tests/out/spv/quad.spvasm b/naga/tests/out/spv/quad.spvasm similarity index 100% rename from tests/out/spv/quad.spvasm rename to naga/tests/out/spv/quad.spvasm diff --git a/tests/out/spv/ray-query.spvasm b/naga/tests/out/spv/ray-query.spvasm similarity index 100% rename from tests/out/spv/ray-query.spvasm rename to naga/tests/out/spv/ray-query.spvasm diff --git a/tests/out/spv/runtime-array-in-unused-struct.spvasm b/naga/tests/out/spv/runtime-array-in-unused-struct.spvasm similarity index 100% rename from tests/out/spv/runtime-array-in-unused-struct.spvasm rename to naga/tests/out/spv/runtime-array-in-unused-struct.spvasm diff --git a/tests/out/spv/separate-entry-points.compute.spvasm b/naga/tests/out/spv/separate-entry-points.compute.spvasm similarity index 100% rename from tests/out/spv/separate-entry-points.compute.spvasm rename to naga/tests/out/spv/separate-entry-points.compute.spvasm diff --git a/tests/out/spv/separate-entry-points.fragment.spvasm b/naga/tests/out/spv/separate-entry-points.fragment.spvasm similarity index 100% rename from tests/out/spv/separate-entry-points.fragment.spvasm rename to naga/tests/out/spv/separate-entry-points.fragment.spvasm diff --git a/tests/out/spv/shadow.spvasm b/naga/tests/out/spv/shadow.spvasm similarity index 100% rename from tests/out/spv/shadow.spvasm rename to naga/tests/out/spv/shadow.spvasm diff --git a/tests/out/spv/skybox.spvasm b/naga/tests/out/spv/skybox.spvasm similarity index 100% rename from tests/out/spv/skybox.spvasm rename to naga/tests/out/spv/skybox.spvasm diff --git a/tests/out/spv/sprite.spvasm b/naga/tests/out/spv/sprite.spvasm similarity index 100% rename from tests/out/spv/sprite.spvasm rename to naga/tests/out/spv/sprite.spvasm diff --git a/tests/out/spv/standard.spvasm b/naga/tests/out/spv/standard.spvasm similarity index 100% rename from tests/out/spv/standard.spvasm rename to naga/tests/out/spv/standard.spvasm diff --git a/tests/out/spv/texture-arg.spvasm b/naga/tests/out/spv/texture-arg.spvasm similarity index 100% rename from tests/out/spv/texture-arg.spvasm rename to naga/tests/out/spv/texture-arg.spvasm diff --git a/tests/out/spv/workgroup-uniform-load.spvasm b/naga/tests/out/spv/workgroup-uniform-load.spvasm similarity index 100% rename from tests/out/spv/workgroup-uniform-load.spvasm rename to naga/tests/out/spv/workgroup-uniform-load.spvasm diff --git a/tests/out/spv/workgroup-var-init.spvasm b/naga/tests/out/spv/workgroup-var-init.spvasm similarity index 100% rename from tests/out/spv/workgroup-var-init.spvasm rename to naga/tests/out/spv/workgroup-var-init.spvasm diff --git a/tests/out/wgsl/210-bevy-2d-shader.frag.wgsl b/naga/tests/out/wgsl/210-bevy-2d-shader.frag.wgsl similarity index 100% rename from tests/out/wgsl/210-bevy-2d-shader.frag.wgsl rename to naga/tests/out/wgsl/210-bevy-2d-shader.frag.wgsl diff --git a/tests/out/wgsl/210-bevy-2d-shader.vert.wgsl b/naga/tests/out/wgsl/210-bevy-2d-shader.vert.wgsl similarity index 100% rename from tests/out/wgsl/210-bevy-2d-shader.vert.wgsl rename to naga/tests/out/wgsl/210-bevy-2d-shader.vert.wgsl diff --git a/tests/out/wgsl/210-bevy-shader.vert.wgsl b/naga/tests/out/wgsl/210-bevy-shader.vert.wgsl similarity index 100% rename from tests/out/wgsl/210-bevy-shader.vert.wgsl rename to naga/tests/out/wgsl/210-bevy-shader.vert.wgsl diff --git a/tests/out/wgsl/246-collatz.comp.wgsl b/naga/tests/out/wgsl/246-collatz.comp.wgsl similarity index 100% rename from tests/out/wgsl/246-collatz.comp.wgsl rename to naga/tests/out/wgsl/246-collatz.comp.wgsl diff --git a/tests/out/wgsl/277-casting.frag.wgsl b/naga/tests/out/wgsl/277-casting.frag.wgsl similarity index 100% rename from tests/out/wgsl/277-casting.frag.wgsl rename to naga/tests/out/wgsl/277-casting.frag.wgsl diff --git a/tests/out/wgsl/280-matrix-cast.frag.wgsl b/naga/tests/out/wgsl/280-matrix-cast.frag.wgsl similarity index 100% rename from tests/out/wgsl/280-matrix-cast.frag.wgsl rename to naga/tests/out/wgsl/280-matrix-cast.frag.wgsl diff --git a/tests/out/wgsl/484-preprocessor-if.frag.wgsl b/naga/tests/out/wgsl/484-preprocessor-if.frag.wgsl similarity index 100% rename from tests/out/wgsl/484-preprocessor-if.frag.wgsl rename to naga/tests/out/wgsl/484-preprocessor-if.frag.wgsl diff --git a/tests/out/wgsl/800-out-of-bounds-panic.vert.wgsl b/naga/tests/out/wgsl/800-out-of-bounds-panic.vert.wgsl similarity index 100% rename from tests/out/wgsl/800-out-of-bounds-panic.vert.wgsl rename to naga/tests/out/wgsl/800-out-of-bounds-panic.vert.wgsl diff --git a/tests/out/wgsl/896-push-constant.frag.wgsl b/naga/tests/out/wgsl/896-push-constant.frag.wgsl similarity index 100% rename from tests/out/wgsl/896-push-constant.frag.wgsl rename to naga/tests/out/wgsl/896-push-constant.frag.wgsl diff --git a/tests/out/wgsl/900-implicit-conversions.frag.wgsl b/naga/tests/out/wgsl/900-implicit-conversions.frag.wgsl similarity index 100% rename from tests/out/wgsl/900-implicit-conversions.frag.wgsl rename to naga/tests/out/wgsl/900-implicit-conversions.frag.wgsl diff --git a/tests/out/wgsl/901-lhs-field-select.frag.wgsl b/naga/tests/out/wgsl/901-lhs-field-select.frag.wgsl similarity index 100% rename from tests/out/wgsl/901-lhs-field-select.frag.wgsl rename to naga/tests/out/wgsl/901-lhs-field-select.frag.wgsl diff --git a/tests/out/wgsl/931-constant-emitting.frag.wgsl b/naga/tests/out/wgsl/931-constant-emitting.frag.wgsl similarity index 100% rename from tests/out/wgsl/931-constant-emitting.frag.wgsl rename to naga/tests/out/wgsl/931-constant-emitting.frag.wgsl diff --git a/tests/out/wgsl/932-for-loop-if.frag.wgsl b/naga/tests/out/wgsl/932-for-loop-if.frag.wgsl similarity index 100% rename from tests/out/wgsl/932-for-loop-if.frag.wgsl rename to naga/tests/out/wgsl/932-for-loop-if.frag.wgsl diff --git a/tests/out/wgsl/access.wgsl b/naga/tests/out/wgsl/access.wgsl similarity index 100% rename from tests/out/wgsl/access.wgsl rename to naga/tests/out/wgsl/access.wgsl diff --git a/tests/out/wgsl/array-in-ctor.wgsl b/naga/tests/out/wgsl/array-in-ctor.wgsl similarity index 100% rename from tests/out/wgsl/array-in-ctor.wgsl rename to naga/tests/out/wgsl/array-in-ctor.wgsl diff --git a/tests/out/wgsl/array-in-function-return-type.wgsl b/naga/tests/out/wgsl/array-in-function-return-type.wgsl similarity index 100% rename from tests/out/wgsl/array-in-function-return-type.wgsl rename to naga/tests/out/wgsl/array-in-function-return-type.wgsl diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/naga/tests/out/wgsl/atomicCompareExchange.wgsl similarity index 100% rename from tests/out/wgsl/atomicCompareExchange.wgsl rename to naga/tests/out/wgsl/atomicCompareExchange.wgsl diff --git a/tests/out/wgsl/atomicOps.wgsl b/naga/tests/out/wgsl/atomicOps.wgsl similarity index 100% rename from tests/out/wgsl/atomicOps.wgsl rename to naga/tests/out/wgsl/atomicOps.wgsl diff --git a/tests/out/wgsl/bevy-pbr.frag.wgsl b/naga/tests/out/wgsl/bevy-pbr.frag.wgsl similarity index 100% rename from tests/out/wgsl/bevy-pbr.frag.wgsl rename to naga/tests/out/wgsl/bevy-pbr.frag.wgsl diff --git a/tests/out/wgsl/bevy-pbr.vert.wgsl b/naga/tests/out/wgsl/bevy-pbr.vert.wgsl similarity index 100% rename from tests/out/wgsl/bevy-pbr.vert.wgsl rename to naga/tests/out/wgsl/bevy-pbr.vert.wgsl diff --git a/tests/out/wgsl/binding-arrays.dynamic.wgsl b/naga/tests/out/wgsl/binding-arrays.dynamic.wgsl similarity index 100% rename from tests/out/wgsl/binding-arrays.dynamic.wgsl rename to naga/tests/out/wgsl/binding-arrays.dynamic.wgsl diff --git a/tests/out/wgsl/binding-arrays.static.wgsl b/naga/tests/out/wgsl/binding-arrays.static.wgsl similarity index 100% rename from tests/out/wgsl/binding-arrays.static.wgsl rename to naga/tests/out/wgsl/binding-arrays.static.wgsl diff --git a/tests/out/wgsl/binding-arrays.wgsl b/naga/tests/out/wgsl/binding-arrays.wgsl similarity index 100% rename from tests/out/wgsl/binding-arrays.wgsl rename to naga/tests/out/wgsl/binding-arrays.wgsl diff --git a/tests/out/wgsl/binding-buffer-arrays.wgsl b/naga/tests/out/wgsl/binding-buffer-arrays.wgsl similarity index 100% rename from tests/out/wgsl/binding-buffer-arrays.wgsl rename to naga/tests/out/wgsl/binding-buffer-arrays.wgsl diff --git a/tests/out/wgsl/bitcast.wgsl b/naga/tests/out/wgsl/bitcast.wgsl similarity index 100% rename from tests/out/wgsl/bitcast.wgsl rename to naga/tests/out/wgsl/bitcast.wgsl diff --git a/tests/out/wgsl/bits.wgsl b/naga/tests/out/wgsl/bits.wgsl similarity index 100% rename from tests/out/wgsl/bits.wgsl rename to naga/tests/out/wgsl/bits.wgsl diff --git a/tests/out/wgsl/bits_glsl.frag.wgsl b/naga/tests/out/wgsl/bits_glsl.frag.wgsl similarity index 100% rename from tests/out/wgsl/bits_glsl.frag.wgsl rename to naga/tests/out/wgsl/bits_glsl.frag.wgsl diff --git a/tests/out/wgsl/boids.wgsl b/naga/tests/out/wgsl/boids.wgsl similarity index 100% rename from tests/out/wgsl/boids.wgsl rename to naga/tests/out/wgsl/boids.wgsl diff --git a/tests/out/wgsl/bool-select.frag.wgsl b/naga/tests/out/wgsl/bool-select.frag.wgsl similarity index 100% rename from tests/out/wgsl/bool-select.frag.wgsl rename to naga/tests/out/wgsl/bool-select.frag.wgsl diff --git a/tests/out/wgsl/break-if.wgsl b/naga/tests/out/wgsl/break-if.wgsl similarity index 100% rename from tests/out/wgsl/break-if.wgsl rename to naga/tests/out/wgsl/break-if.wgsl diff --git a/tests/out/wgsl/buffer.frag.wgsl b/naga/tests/out/wgsl/buffer.frag.wgsl similarity index 100% rename from tests/out/wgsl/buffer.frag.wgsl rename to naga/tests/out/wgsl/buffer.frag.wgsl diff --git a/tests/out/wgsl/clamp-splat.vert.wgsl b/naga/tests/out/wgsl/clamp-splat.vert.wgsl similarity index 100% rename from tests/out/wgsl/clamp-splat.vert.wgsl rename to naga/tests/out/wgsl/clamp-splat.vert.wgsl diff --git a/tests/out/wgsl/collatz.wgsl b/naga/tests/out/wgsl/collatz.wgsl similarity index 100% rename from tests/out/wgsl/collatz.wgsl rename to naga/tests/out/wgsl/collatz.wgsl diff --git a/tests/out/wgsl/const-exprs.wgsl b/naga/tests/out/wgsl/const-exprs.wgsl similarity index 100% rename from tests/out/wgsl/const-exprs.wgsl rename to naga/tests/out/wgsl/const-exprs.wgsl diff --git a/tests/out/wgsl/constant-array-size.frag.wgsl b/naga/tests/out/wgsl/constant-array-size.frag.wgsl similarity index 100% rename from tests/out/wgsl/constant-array-size.frag.wgsl rename to naga/tests/out/wgsl/constant-array-size.frag.wgsl diff --git a/tests/out/wgsl/constructors.wgsl b/naga/tests/out/wgsl/constructors.wgsl similarity index 100% rename from tests/out/wgsl/constructors.wgsl rename to naga/tests/out/wgsl/constructors.wgsl diff --git a/tests/out/wgsl/control-flow.wgsl b/naga/tests/out/wgsl/control-flow.wgsl similarity index 100% rename from tests/out/wgsl/control-flow.wgsl rename to naga/tests/out/wgsl/control-flow.wgsl diff --git a/tests/out/wgsl/declarations.frag.wgsl b/naga/tests/out/wgsl/declarations.frag.wgsl similarity index 100% rename from tests/out/wgsl/declarations.frag.wgsl rename to naga/tests/out/wgsl/declarations.frag.wgsl diff --git a/tests/out/wgsl/do-while.wgsl b/naga/tests/out/wgsl/do-while.wgsl similarity index 100% rename from tests/out/wgsl/do-while.wgsl rename to naga/tests/out/wgsl/do-while.wgsl diff --git a/tests/out/wgsl/dualsource.wgsl b/naga/tests/out/wgsl/dualsource.wgsl similarity index 100% rename from tests/out/wgsl/dualsource.wgsl rename to naga/tests/out/wgsl/dualsource.wgsl diff --git a/tests/out/wgsl/empty-global-name.wgsl b/naga/tests/out/wgsl/empty-global-name.wgsl similarity index 100% rename from tests/out/wgsl/empty-global-name.wgsl rename to naga/tests/out/wgsl/empty-global-name.wgsl diff --git a/tests/out/wgsl/empty.wgsl b/naga/tests/out/wgsl/empty.wgsl similarity index 100% rename from tests/out/wgsl/empty.wgsl rename to naga/tests/out/wgsl/empty.wgsl diff --git a/tests/out/wgsl/expressions.frag.wgsl b/naga/tests/out/wgsl/expressions.frag.wgsl similarity index 100% rename from tests/out/wgsl/expressions.frag.wgsl rename to naga/tests/out/wgsl/expressions.frag.wgsl diff --git a/tests/out/wgsl/extra.wgsl b/naga/tests/out/wgsl/extra.wgsl similarity index 100% rename from tests/out/wgsl/extra.wgsl rename to naga/tests/out/wgsl/extra.wgsl diff --git a/tests/out/wgsl/fma.frag.wgsl b/naga/tests/out/wgsl/fma.frag.wgsl similarity index 100% rename from tests/out/wgsl/fma.frag.wgsl rename to naga/tests/out/wgsl/fma.frag.wgsl diff --git a/tests/out/wgsl/fragment-output.wgsl b/naga/tests/out/wgsl/fragment-output.wgsl similarity index 100% rename from tests/out/wgsl/fragment-output.wgsl rename to naga/tests/out/wgsl/fragment-output.wgsl diff --git a/tests/out/wgsl/functions.wgsl b/naga/tests/out/wgsl/functions.wgsl similarity index 100% rename from tests/out/wgsl/functions.wgsl rename to naga/tests/out/wgsl/functions.wgsl diff --git a/tests/out/wgsl/functions_call.frag.wgsl b/naga/tests/out/wgsl/functions_call.frag.wgsl similarity index 100% rename from tests/out/wgsl/functions_call.frag.wgsl rename to naga/tests/out/wgsl/functions_call.frag.wgsl diff --git a/tests/out/wgsl/global-constant-array.frag.wgsl b/naga/tests/out/wgsl/global-constant-array.frag.wgsl similarity index 100% rename from tests/out/wgsl/global-constant-array.frag.wgsl rename to naga/tests/out/wgsl/global-constant-array.frag.wgsl diff --git a/tests/out/wgsl/globals.wgsl b/naga/tests/out/wgsl/globals.wgsl similarity index 100% rename from tests/out/wgsl/globals.wgsl rename to naga/tests/out/wgsl/globals.wgsl diff --git a/tests/out/wgsl/image.wgsl b/naga/tests/out/wgsl/image.wgsl similarity index 100% rename from tests/out/wgsl/image.wgsl rename to naga/tests/out/wgsl/image.wgsl diff --git a/tests/out/wgsl/images.frag.wgsl b/naga/tests/out/wgsl/images.frag.wgsl similarity index 100% rename from tests/out/wgsl/images.frag.wgsl rename to naga/tests/out/wgsl/images.frag.wgsl diff --git a/tests/out/wgsl/interface.wgsl b/naga/tests/out/wgsl/interface.wgsl similarity index 100% rename from tests/out/wgsl/interface.wgsl rename to naga/tests/out/wgsl/interface.wgsl diff --git a/tests/out/wgsl/interpolate.wgsl b/naga/tests/out/wgsl/interpolate.wgsl similarity index 100% rename from tests/out/wgsl/interpolate.wgsl rename to naga/tests/out/wgsl/interpolate.wgsl diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/naga/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl similarity index 100% rename from tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl rename to naga/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/naga/tests/out/wgsl/lexical-scopes.wgsl similarity index 100% rename from tests/out/wgsl/lexical-scopes.wgsl rename to naga/tests/out/wgsl/lexical-scopes.wgsl diff --git a/tests/out/wgsl/local-var-init-in-loop.comp.wgsl b/naga/tests/out/wgsl/local-var-init-in-loop.comp.wgsl similarity index 100% rename from tests/out/wgsl/local-var-init-in-loop.comp.wgsl rename to naga/tests/out/wgsl/local-var-init-in-loop.comp.wgsl diff --git a/tests/out/wgsl/long-form-matrix.frag.wgsl b/naga/tests/out/wgsl/long-form-matrix.frag.wgsl similarity index 100% rename from tests/out/wgsl/long-form-matrix.frag.wgsl rename to naga/tests/out/wgsl/long-form-matrix.frag.wgsl diff --git a/tests/out/wgsl/math-functions.frag.wgsl b/naga/tests/out/wgsl/math-functions.frag.wgsl similarity index 100% rename from tests/out/wgsl/math-functions.frag.wgsl rename to naga/tests/out/wgsl/math-functions.frag.wgsl diff --git a/tests/out/wgsl/math-functions.wgsl b/naga/tests/out/wgsl/math-functions.wgsl similarity index 100% rename from tests/out/wgsl/math-functions.wgsl rename to naga/tests/out/wgsl/math-functions.wgsl diff --git a/tests/out/wgsl/module-scope.wgsl b/naga/tests/out/wgsl/module-scope.wgsl similarity index 100% rename from tests/out/wgsl/module-scope.wgsl rename to naga/tests/out/wgsl/module-scope.wgsl diff --git a/tests/out/wgsl/multiview.wgsl b/naga/tests/out/wgsl/multiview.wgsl similarity index 100% rename from tests/out/wgsl/multiview.wgsl rename to naga/tests/out/wgsl/multiview.wgsl diff --git a/tests/out/wgsl/operators.wgsl b/naga/tests/out/wgsl/operators.wgsl similarity index 100% rename from tests/out/wgsl/operators.wgsl rename to naga/tests/out/wgsl/operators.wgsl diff --git a/tests/out/wgsl/padding.wgsl b/naga/tests/out/wgsl/padding.wgsl similarity index 100% rename from tests/out/wgsl/padding.wgsl rename to naga/tests/out/wgsl/padding.wgsl diff --git a/tests/out/wgsl/pointers.wgsl b/naga/tests/out/wgsl/pointers.wgsl similarity index 100% rename from tests/out/wgsl/pointers.wgsl rename to naga/tests/out/wgsl/pointers.wgsl diff --git a/tests/out/wgsl/prepostfix.frag.wgsl b/naga/tests/out/wgsl/prepostfix.frag.wgsl similarity index 100% rename from tests/out/wgsl/prepostfix.frag.wgsl rename to naga/tests/out/wgsl/prepostfix.frag.wgsl diff --git a/tests/out/wgsl/quad-vert.wgsl b/naga/tests/out/wgsl/quad-vert.wgsl similarity index 100% rename from tests/out/wgsl/quad-vert.wgsl rename to naga/tests/out/wgsl/quad-vert.wgsl diff --git a/tests/out/wgsl/quad.wgsl b/naga/tests/out/wgsl/quad.wgsl similarity index 100% rename from tests/out/wgsl/quad.wgsl rename to naga/tests/out/wgsl/quad.wgsl diff --git a/tests/out/wgsl/quad_glsl.frag.wgsl b/naga/tests/out/wgsl/quad_glsl.frag.wgsl similarity index 100% rename from tests/out/wgsl/quad_glsl.frag.wgsl rename to naga/tests/out/wgsl/quad_glsl.frag.wgsl diff --git a/tests/out/wgsl/quad_glsl.vert.wgsl b/naga/tests/out/wgsl/quad_glsl.vert.wgsl similarity index 100% rename from tests/out/wgsl/quad_glsl.vert.wgsl rename to naga/tests/out/wgsl/quad_glsl.vert.wgsl diff --git a/tests/out/wgsl/sampler-functions.frag.wgsl b/naga/tests/out/wgsl/sampler-functions.frag.wgsl similarity index 100% rename from tests/out/wgsl/sampler-functions.frag.wgsl rename to naga/tests/out/wgsl/sampler-functions.frag.wgsl diff --git a/tests/out/wgsl/samplers.frag.wgsl b/naga/tests/out/wgsl/samplers.frag.wgsl similarity index 100% rename from tests/out/wgsl/samplers.frag.wgsl rename to naga/tests/out/wgsl/samplers.frag.wgsl diff --git a/tests/out/wgsl/shadow.wgsl b/naga/tests/out/wgsl/shadow.wgsl similarity index 100% rename from tests/out/wgsl/shadow.wgsl rename to naga/tests/out/wgsl/shadow.wgsl diff --git a/tests/out/wgsl/skybox.wgsl b/naga/tests/out/wgsl/skybox.wgsl similarity index 100% rename from tests/out/wgsl/skybox.wgsl rename to naga/tests/out/wgsl/skybox.wgsl diff --git a/tests/out/wgsl/standard.wgsl b/naga/tests/out/wgsl/standard.wgsl similarity index 100% rename from tests/out/wgsl/standard.wgsl rename to naga/tests/out/wgsl/standard.wgsl diff --git a/tests/out/wgsl/statements.frag.wgsl b/naga/tests/out/wgsl/statements.frag.wgsl similarity index 100% rename from tests/out/wgsl/statements.frag.wgsl rename to naga/tests/out/wgsl/statements.frag.wgsl diff --git a/tests/out/wgsl/texture-arg.wgsl b/naga/tests/out/wgsl/texture-arg.wgsl similarity index 100% rename from tests/out/wgsl/texture-arg.wgsl rename to naga/tests/out/wgsl/texture-arg.wgsl diff --git a/tests/out/wgsl/type-alias.wgsl b/naga/tests/out/wgsl/type-alias.wgsl similarity index 100% rename from tests/out/wgsl/type-alias.wgsl rename to naga/tests/out/wgsl/type-alias.wgsl diff --git a/tests/out/wgsl/vector-functions.frag.wgsl b/naga/tests/out/wgsl/vector-functions.frag.wgsl similarity index 100% rename from tests/out/wgsl/vector-functions.frag.wgsl rename to naga/tests/out/wgsl/vector-functions.frag.wgsl diff --git a/tests/out/wgsl/workgroup-uniform-load.wgsl b/naga/tests/out/wgsl/workgroup-uniform-load.wgsl similarity index 100% rename from tests/out/wgsl/workgroup-uniform-load.wgsl rename to naga/tests/out/wgsl/workgroup-uniform-load.wgsl diff --git a/tests/out/wgsl/workgroup-var-init.wgsl b/naga/tests/out/wgsl/workgroup-var-init.wgsl similarity index 100% rename from tests/out/wgsl/workgroup-var-init.wgsl rename to naga/tests/out/wgsl/workgroup-var-init.wgsl diff --git a/tests/snapshots.rs b/naga/tests/snapshots.rs similarity index 100% rename from tests/snapshots.rs rename to naga/tests/snapshots.rs diff --git a/tests/spirv-capabilities.rs b/naga/tests/spirv-capabilities.rs similarity index 100% rename from tests/spirv-capabilities.rs rename to naga/tests/spirv-capabilities.rs diff --git a/tests/wgsl-errors.rs b/naga/tests/wgsl-errors.rs similarity index 100% rename from tests/wgsl-errors.rs rename to naga/tests/wgsl-errors.rs diff --git a/xtask/.gitignore b/naga/xtask/.gitignore similarity index 100% rename from xtask/.gitignore rename to naga/xtask/.gitignore diff --git a/xtask/Cargo.lock b/naga/xtask/Cargo.lock similarity index 100% rename from xtask/Cargo.lock rename to naga/xtask/Cargo.lock diff --git a/xtask/Cargo.toml b/naga/xtask/Cargo.toml similarity index 100% rename from xtask/Cargo.toml rename to naga/xtask/Cargo.toml diff --git a/xtask/src/cli.rs b/naga/xtask/src/cli.rs similarity index 100% rename from xtask/src/cli.rs rename to naga/xtask/src/cli.rs diff --git a/xtask/src/fs.rs b/naga/xtask/src/fs.rs similarity index 100% rename from xtask/src/fs.rs rename to naga/xtask/src/fs.rs diff --git a/xtask/src/glob.rs b/naga/xtask/src/glob.rs similarity index 100% rename from xtask/src/glob.rs rename to naga/xtask/src/glob.rs diff --git a/xtask/src/main.rs b/naga/xtask/src/main.rs similarity index 100% rename from xtask/src/main.rs rename to naga/xtask/src/main.rs diff --git a/xtask/src/path.rs b/naga/xtask/src/path.rs similarity index 100% rename from xtask/src/path.rs rename to naga/xtask/src/path.rs diff --git a/xtask/src/process.rs b/naga/xtask/src/process.rs similarity index 100% rename from xtask/src/process.rs rename to naga/xtask/src/process.rs diff --git a/xtask/src/result.rs b/naga/xtask/src/result.rs similarity index 100% rename from xtask/src/result.rs rename to naga/xtask/src/result.rs